From d2ca021b50caad8378d3761e1b1a36d3dab833e4 Mon Sep 17 00:00:00 2001 From: Sukadia <37813632+Sukadia@users.noreply.github.com> Date: Fri, 5 Jan 2024 16:26:22 -0800 Subject: [PATCH] Add /poster redirect --- .next/BUILD_ID | 2 +- .next/app-build-manifest.json | 102 +- .next/app-path-routes-manifest.json | 9 +- .next/build-manifest.json | 24 +- .next/next-minimal-server.js.nft.json | 1 + .next/next-server.js.nft.json | 2 +- .next/prerender-manifest.js | 2 +- .next/prerender-manifest.json | 2 +- .next/required-server-files.json | 2 +- .next/routes-manifest.json | 2 +- .next/server/app-paths-manifest.json | 7 +- .next/server/app/_not-found.html | 1 + .next/server/app/_not-found.js | 1 + .next/server/app/_not-found.js.nft.json | 1 + .next/server/app/_not-found.meta | 5 + .next/server/app/_not-found.rsc | 11 + .../_not-found_client-reference-manifest.js | 1 + .next/server/app/everyone-votes/privacy.html | 2 +- .next/server/app/everyone-votes/privacy.meta | 6 +- .next/server/app/everyone-votes/privacy.rsc | 13 +- .../server/app/everyone-votes/privacy/page.js | 416 +- .../everyone-votes/privacy/page.js.nft.json | 2 +- .../privacy/page_client-reference-manifest.js | 1 + .next/server/app/everyone-votes/terms.html | 2 +- .next/server/app/everyone-votes/terms.meta | 6 +- .next/server/app/everyone-votes/terms.rsc | 13 +- .next/server/app/everyone-votes/terms/page.js | 408 +- .../app/everyone-votes/terms/page.js.nft.json | 2 +- .../terms/page_client-reference-manifest.js | 1 + .next/server/app/favicon.ico.meta | 2 +- .next/server/app/favicon.ico/route.js | 143 +- .../server/app/favicon.ico/route.js.nft.json | 2 +- .next/server/app/index.html | 2 +- .next/server/app/index.meta | 6 +- .next/server/app/index.rsc | 19 +- .next/server/app/page.js | 602 +- .next/server/app/page.js.nft.json | 2 +- .../app/page_client-reference-manifest.js | 1 + .next/server/app/space.html | 2 +- .next/server/app/space.meta | 6 +- .next/server/app/space.rsc | 17 +- .next/server/app/space/page.js | 721 +- .next/server/app/space/page.js.nft.json | 2 +- .../space/page_client-reference-manifest.js | 1 + .next/server/app/wiston.html | 2 +- .next/server/app/wiston.meta | 6 +- .next/server/app/wiston.rsc | 15 +- .next/server/app/wiston/page.js | 594 +- .next/server/app/wiston/page.js.nft.json | 2 +- .../wiston/page_client-reference-manifest.js | 1 + .next/server/chunks/106.js | 113 + .next/server/chunks/2.js | 1 + .next/server/chunks/201.js | 12 + .next/server/chunks/310.js | 1 + .next/server/chunks/323.js | 6 + .next/server/chunks/405.js | 509 - .next/server/chunks/421.js | 690 - .next/server/chunks/572.js | 5338 - .next/server/chunks/616.js | 9000 - .next/server/chunks/622.js | 1 + .next/server/chunks/676.js | 6 + .next/server/chunks/816.js | 90 - .next/server/chunks/837.js | 1 + .next/server/chunks/840.js | 1 + .next/server/chunks/862.js | 1 + .next/server/chunks/864.js | 267004 --------------- .next/server/chunks/984.js | 11502 + .next/server/client-reference-manifest.js | 1 - .next/server/client-reference-manifest.json | 1 - .next/server/flight-server-css-manifest.js | 1 - .next/server/flight-server-css-manifest.json | 1 - .next/server/functions-config-manifest.json | 1 + .next/server/middleware-build-manifest.js | 2 +- .../middleware-react-loadable-manifest.js | 2 +- .next/server/next-font-manifest.js | 2 +- .next/server/next-font-manifest.json | 7 +- .next/server/pages-manifest.json | 7 +- .next/server/pages/404.html | 2 +- .next/server/pages/500.html | 2 +- .next/server/pages/_app.js | 95 +- .next/server/pages/_app.js.nft.json | 2 +- .next/server/pages/_document.js | 931 +- .next/server/pages/_document.js.nft.json | 2 +- .next/server/pages/_error.js | 413 +- .next/server/pages/_error.js.nft.json | 2 +- .next/server/server-reference-manifest.js | 2 +- .next/server/server-reference-manifest.json | 2 +- .next/server/webpack-runtime.js | 191 +- .../9CqSqX2Hqhh4fwiD8kSfJ/_buildManifest.js | 1 + .../_ssgManifest.js | 0 .../Qb5fVlqLpQAODnw100j4z/_buildManifest.js | 1 - .next/static/chunks/173-2ffa9652644381a8.js | 11507 + .../chunks/1f3d3139-f107a678ff6361e9.js | 1 + .next/static/chunks/23-fb41cbadaf19fac2.js | 11400 - .../chunks/2443530c-097fe1871e1d7679.js | 9 - .../chunks/43cb4aaa-0dfcb2e81cc1cbc1.js | 1 - .next/static/chunks/472-51fd3a56159f1e5b.js | 25 + .next/static/chunks/488-66ca2c1db348e680.js | 25 - .../chunks/51231e76-cf1b2fc1d6b83e48.js | 1 - .../chunks/53417c1a-c755bb806ffa7a5d.js | 1 - .../chunks/537cd76e-7aba1cf7a4752418.js | 1 + .../chunks/604a08ec-59af37265fb99b3d.js | 4 + .next/static/chunks/716.9317a587abbcf60a.js | 1 - .next/static/chunks/751.591370f90aaa22a6.js | 1 + .next/static/chunks/986-37229c658d9b7b30.js | 9 + .../chunks/app/_not-found-fbdfab077d258bb2.js | 1 + .../privacy/page-29a62894605199e6.js | 1 + .../privacy/page-4d788de82a96b899.js | 1 - .../terms/page-5aa776690a4e5edf.js | 1 - .../terms/page-c0da9088d7e5e9ae.js | 1 + .../chunks/app/layout-3d94fcc1098e9e97.js | 1 - .../chunks/app/layout-ca25527909104096.js | 1 + .../chunks/app/page-39b6caed82efc627.js | 1 + .../chunks/app/page-8204c3b0f59bd205.js | 9 - .../app/space/loading-12fd180f06101306.js | 1 + .../app/space/loading-df1b886b524be596.js | 1 - .../chunks/app/space/page-aa0f5917bd776cea.js | 1 - .../chunks/app/space/page-b8120f6d5470d1c7.js | 1 + .../app/wiston/page-becb82f49ed47545.js | 9 - .../app/wiston/page-c31b345ea6ea73af.js | 1 + .../chunks/d67c510a-e497b3cd5bf43bb4.js | 1 + .../chunks/e1206f8c-ab5b5541f866e530.js | 1 + .../chunks/f126df28-0647fc1012c29407.js | 1 - .../chunks/f75787ed-011198ef7e5d7754.js | 1 - .../chunks/fd9d1056-ba10bf844a47945b.js | 9 + .../chunks/framework-8883d1e9be70c3da.js | 8 +- .next/static/chunks/main-07bf56c05aa7cd6e.js | 1 + .../chunks/main-app-0be5dce44311dbbf.js | 1 - .../chunks/main-app-cf3eb22ffef632f7.js | 1 + .next/static/chunks/main-dba5d122367f02b7.js | 1 - .../chunks/pages/_app-1534f180665c857f.js | 1 + .../chunks/pages/_app-b555d5e1eab47959.js | 1 - ...86538ac0.js => _error-b646007f40c4f0a8.js} | 2 +- .../static/chunks/webpack-54b114c68857d808.js | 1 - .../static/chunks/webpack-c42a79c5d8b7c910.js | 1 + ...0d1a0ca01c66f.css => 1d2d59615145af7d.css} | 2 +- .next/static/media/05a31a2ca4975f99-s.woff2 | Bin 0 -> 10496 bytes .next/static/media/2aaf0723e720e8b9-s.p.woff2 | Bin 37780 -> 0 bytes .next/static/media/513657b02c5c193f-s.woff2 | Bin 0 -> 17612 bytes .next/static/media/51ed15f9841b9f9d-s.woff2 | Bin 0 -> 22524 bytes .next/static/media/9c4f34569c9b36ca-s.woff2 | Bin 57244 -> 0 bytes .next/static/media/ae9ae6716d4f8bf8-s.woff2 | Bin 11924 -> 0 bytes .next/static/media/b1db3e28af9ef94a-s.woff2 | Bin 8652 -> 0 bytes .next/static/media/b967158bc7d7a9fb-s.woff2 | Bin 17040 -> 0 bytes .next/static/media/c0f5ec5bbf5913b7-s.woff2 | Bin 21960 -> 0 bytes .next/static/media/c9a5bc6a7c948fb0-s.p.woff2 | Bin 0 -> 46552 bytes .next/static/media/d1d9458b69004127-s.woff2 | Bin 26728 -> 0 bytes .next/static/media/d6b16ce4a6175f26-s.woff2 | Bin 0 -> 80044 bytes .next/static/media/ec159349637c90ad-s.woff2 | Bin 0 -> 27316 bytes .next/static/media/fd4db3eb5472fc27-s.woff2 | Bin 0 -> 12768 bytes .next/trace | 37 +- .../types/app/everyone-votes/privacy/page.ts | 11 +- .next/types/app/everyone-votes/terms/page.ts | 11 +- .next/types/app/page.ts | 11 +- .next/types/app/space/page.ts | 11 +- .next/types/app/wiston/page.ts | 11 +- app/wiston/page.tsx | 2 - next.config.js | 5 + package-lock.json | 777 +- package.json | 2 +- 160 files changed, 23932 insertions(+), 299138 deletions(-) create mode 100644 .next/next-minimal-server.js.nft.json create mode 100644 .next/server/app/_not-found.html create mode 100644 .next/server/app/_not-found.js create mode 100644 .next/server/app/_not-found.js.nft.json create mode 100644 .next/server/app/_not-found.meta create mode 100644 .next/server/app/_not-found.rsc create mode 100644 .next/server/app/_not-found_client-reference-manifest.js create mode 100644 .next/server/app/everyone-votes/privacy/page_client-reference-manifest.js create mode 100644 .next/server/app/everyone-votes/terms/page_client-reference-manifest.js create mode 100644 .next/server/app/page_client-reference-manifest.js create mode 100644 .next/server/app/space/page_client-reference-manifest.js create mode 100644 .next/server/app/wiston/page_client-reference-manifest.js create mode 100644 .next/server/chunks/106.js create mode 100644 .next/server/chunks/2.js create mode 100644 .next/server/chunks/201.js create mode 100644 .next/server/chunks/310.js create mode 100644 .next/server/chunks/323.js delete mode 100644 .next/server/chunks/405.js delete mode 100644 .next/server/chunks/421.js delete mode 100644 .next/server/chunks/572.js delete mode 100644 .next/server/chunks/616.js create mode 100644 .next/server/chunks/622.js create mode 100644 .next/server/chunks/676.js delete mode 100644 .next/server/chunks/816.js create mode 100644 .next/server/chunks/837.js create mode 100644 .next/server/chunks/840.js create mode 100644 .next/server/chunks/862.js delete mode 100644 .next/server/chunks/864.js create mode 100644 .next/server/chunks/984.js delete mode 100644 .next/server/client-reference-manifest.js delete mode 100644 .next/server/client-reference-manifest.json delete mode 100644 .next/server/flight-server-css-manifest.js delete mode 100644 .next/server/flight-server-css-manifest.json create mode 100644 .next/server/functions-config-manifest.json create mode 100644 .next/static/9CqSqX2Hqhh4fwiD8kSfJ/_buildManifest.js rename .next/static/{Qb5fVlqLpQAODnw100j4z => 9CqSqX2Hqhh4fwiD8kSfJ}/_ssgManifest.js (100%) delete mode 100644 .next/static/Qb5fVlqLpQAODnw100j4z/_buildManifest.js create mode 100644 .next/static/chunks/173-2ffa9652644381a8.js create mode 100644 .next/static/chunks/1f3d3139-f107a678ff6361e9.js delete mode 100644 .next/static/chunks/23-fb41cbadaf19fac2.js delete mode 100644 .next/static/chunks/2443530c-097fe1871e1d7679.js delete mode 100644 .next/static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js create mode 100644 .next/static/chunks/472-51fd3a56159f1e5b.js delete mode 100644 .next/static/chunks/488-66ca2c1db348e680.js delete mode 100644 .next/static/chunks/51231e76-cf1b2fc1d6b83e48.js delete mode 100644 .next/static/chunks/53417c1a-c755bb806ffa7a5d.js create mode 100644 .next/static/chunks/537cd76e-7aba1cf7a4752418.js create mode 100644 .next/static/chunks/604a08ec-59af37265fb99b3d.js delete mode 100644 .next/static/chunks/716.9317a587abbcf60a.js create mode 100644 .next/static/chunks/751.591370f90aaa22a6.js create mode 100644 .next/static/chunks/986-37229c658d9b7b30.js create mode 100644 .next/static/chunks/app/_not-found-fbdfab077d258bb2.js create mode 100644 .next/static/chunks/app/everyone-votes/privacy/page-29a62894605199e6.js delete mode 100644 .next/static/chunks/app/everyone-votes/privacy/page-4d788de82a96b899.js delete mode 100644 .next/static/chunks/app/everyone-votes/terms/page-5aa776690a4e5edf.js create mode 100644 .next/static/chunks/app/everyone-votes/terms/page-c0da9088d7e5e9ae.js delete mode 100644 .next/static/chunks/app/layout-3d94fcc1098e9e97.js create mode 100644 .next/static/chunks/app/layout-ca25527909104096.js create mode 100644 .next/static/chunks/app/page-39b6caed82efc627.js delete mode 100644 .next/static/chunks/app/page-8204c3b0f59bd205.js create mode 100644 .next/static/chunks/app/space/loading-12fd180f06101306.js delete mode 100644 .next/static/chunks/app/space/loading-df1b886b524be596.js delete mode 100644 .next/static/chunks/app/space/page-aa0f5917bd776cea.js create mode 100644 .next/static/chunks/app/space/page-b8120f6d5470d1c7.js delete mode 100644 .next/static/chunks/app/wiston/page-becb82f49ed47545.js create mode 100644 .next/static/chunks/app/wiston/page-c31b345ea6ea73af.js create mode 100644 .next/static/chunks/d67c510a-e497b3cd5bf43bb4.js create mode 100644 .next/static/chunks/e1206f8c-ab5b5541f866e530.js delete mode 100644 .next/static/chunks/f126df28-0647fc1012c29407.js delete mode 100644 .next/static/chunks/f75787ed-011198ef7e5d7754.js create mode 100644 .next/static/chunks/fd9d1056-ba10bf844a47945b.js create mode 100644 .next/static/chunks/main-07bf56c05aa7cd6e.js delete mode 100644 .next/static/chunks/main-app-0be5dce44311dbbf.js create mode 100644 .next/static/chunks/main-app-cf3eb22ffef632f7.js delete mode 100644 .next/static/chunks/main-dba5d122367f02b7.js create mode 100644 .next/static/chunks/pages/_app-1534f180665c857f.js delete mode 100644 .next/static/chunks/pages/_app-b555d5e1eab47959.js rename .next/static/chunks/pages/{_error-d79168f986538ac0.js => _error-b646007f40c4f0a8.js} (74%) delete mode 100644 .next/static/chunks/webpack-54b114c68857d808.js create mode 100644 .next/static/chunks/webpack-c42a79c5d8b7c910.js rename .next/static/css/{3930d1a0ca01c66f.css => 1d2d59615145af7d.css} (90%) create mode 100644 .next/static/media/05a31a2ca4975f99-s.woff2 delete mode 100644 .next/static/media/2aaf0723e720e8b9-s.p.woff2 create mode 100644 .next/static/media/513657b02c5c193f-s.woff2 create mode 100644 .next/static/media/51ed15f9841b9f9d-s.woff2 delete mode 100644 .next/static/media/9c4f34569c9b36ca-s.woff2 delete mode 100644 .next/static/media/ae9ae6716d4f8bf8-s.woff2 delete mode 100644 .next/static/media/b1db3e28af9ef94a-s.woff2 delete mode 100644 .next/static/media/b967158bc7d7a9fb-s.woff2 delete mode 100644 .next/static/media/c0f5ec5bbf5913b7-s.woff2 create mode 100644 .next/static/media/c9a5bc6a7c948fb0-s.p.woff2 delete mode 100644 .next/static/media/d1d9458b69004127-s.woff2 create mode 100644 .next/static/media/d6b16ce4a6175f26-s.woff2 create mode 100644 .next/static/media/ec159349637c90ad-s.woff2 create mode 100644 .next/static/media/fd4db3eb5472fc27-s.woff2 diff --git a/.next/BUILD_ID b/.next/BUILD_ID index b79c999..44f36d8 100644 --- a/.next/BUILD_ID +++ b/.next/BUILD_ID @@ -1 +1 @@ -Qb5fVlqLpQAODnw100j4z \ No newline at end of file +9CqSqX2Hqhh4fwiD8kSfJ \ No newline at end of file diff --git a/.next/app-build-manifest.json b/.next/app-build-manifest.json index 4c849a5..3d95bc5 100644 --- a/.next/app-build-manifest.json +++ b/.next/app-build-manifest.json @@ -1,61 +1,69 @@ { "pages": { + "/_not-found": [ + "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/fd9d1056-ba10bf844a47945b.js", + "static/chunks/472-51fd3a56159f1e5b.js", + "static/chunks/main-app-cf3eb22ffef632f7.js", + "static/chunks/app/_not-found-fbdfab077d258bb2.js" + ], "/layout": [ - "static/chunks/webpack-54b114c68857d808.js", - "static/chunks/2443530c-097fe1871e1d7679.js", - "static/chunks/488-66ca2c1db348e680.js", - "static/chunks/main-app-0be5dce44311dbbf.js", - "static/css/3930d1a0ca01c66f.css", - "static/chunks/app/layout-3d94fcc1098e9e97.js" + "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/fd9d1056-ba10bf844a47945b.js", + "static/chunks/472-51fd3a56159f1e5b.js", + "static/chunks/main-app-cf3eb22ffef632f7.js", + "static/css/1d2d59615145af7d.css", + "static/chunks/app/layout-ca25527909104096.js" + ], + "/everyone-votes/terms/page": [ + "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/fd9d1056-ba10bf844a47945b.js", + "static/chunks/472-51fd3a56159f1e5b.js", + "static/chunks/main-app-cf3eb22ffef632f7.js", + "static/chunks/app/everyone-votes/terms/page-c0da9088d7e5e9ae.js" + ], + "/everyone-votes/privacy/page": [ + "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/fd9d1056-ba10bf844a47945b.js", + "static/chunks/472-51fd3a56159f1e5b.js", + "static/chunks/main-app-cf3eb22ffef632f7.js", + "static/chunks/app/everyone-votes/privacy/page-29a62894605199e6.js" ], "/page": [ - "static/chunks/webpack-54b114c68857d808.js", - "static/chunks/2443530c-097fe1871e1d7679.js", - "static/chunks/488-66ca2c1db348e680.js", - "static/chunks/main-app-0be5dce44311dbbf.js", + "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/fd9d1056-ba10bf844a47945b.js", + "static/chunks/472-51fd3a56159f1e5b.js", + "static/chunks/main-app-cf3eb22ffef632f7.js", + "static/chunks/986-37229c658d9b7b30.js", "static/css/60c69e914bf8dd4b.css", - "static/chunks/app/page-8204c3b0f59bd205.js" - ], - "/wiston/page": [ - "static/chunks/webpack-54b114c68857d808.js", - "static/chunks/2443530c-097fe1871e1d7679.js", - "static/chunks/488-66ca2c1db348e680.js", - "static/chunks/main-app-0be5dce44311dbbf.js", - "static/chunks/app/wiston/page-becb82f49ed47545.js" + "static/chunks/app/page-39b6caed82efc627.js" ], "/space/page": [ - "static/chunks/webpack-54b114c68857d808.js", - "static/chunks/2443530c-097fe1871e1d7679.js", - "static/chunks/488-66ca2c1db348e680.js", - "static/chunks/main-app-0be5dce44311dbbf.js", - "static/chunks/f75787ed-011198ef7e5d7754.js", - "static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js", - "static/chunks/f126df28-0647fc1012c29407.js", - "static/chunks/51231e76-cf1b2fc1d6b83e48.js", - "static/chunks/53417c1a-c755bb806ffa7a5d.js", - "static/chunks/23-fb41cbadaf19fac2.js", - "static/chunks/app/space/page-aa0f5917bd776cea.js" + "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/fd9d1056-ba10bf844a47945b.js", + "static/chunks/472-51fd3a56159f1e5b.js", + "static/chunks/main-app-cf3eb22ffef632f7.js", + "static/chunks/e1206f8c-ab5b5541f866e530.js", + "static/chunks/1f3d3139-f107a678ff6361e9.js", + "static/chunks/604a08ec-59af37265fb99b3d.js", + "static/chunks/d67c510a-e497b3cd5bf43bb4.js", + "static/chunks/537cd76e-7aba1cf7a4752418.js", + "static/chunks/173-2ffa9652644381a8.js", + "static/chunks/app/space/page-b8120f6d5470d1c7.js" ], "/space/loading": [ - "static/chunks/webpack-54b114c68857d808.js", - "static/chunks/2443530c-097fe1871e1d7679.js", - "static/chunks/488-66ca2c1db348e680.js", - "static/chunks/main-app-0be5dce44311dbbf.js", - "static/chunks/app/space/loading-df1b886b524be596.js" - ], - "/everyone-votes/privacy/page": [ - "static/chunks/webpack-54b114c68857d808.js", - "static/chunks/2443530c-097fe1871e1d7679.js", - "static/chunks/488-66ca2c1db348e680.js", - "static/chunks/main-app-0be5dce44311dbbf.js", - "static/chunks/app/everyone-votes/privacy/page-4d788de82a96b899.js" + "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/fd9d1056-ba10bf844a47945b.js", + "static/chunks/472-51fd3a56159f1e5b.js", + "static/chunks/main-app-cf3eb22ffef632f7.js", + "static/chunks/app/space/loading-12fd180f06101306.js" ], - "/everyone-votes/terms/page": [ - "static/chunks/webpack-54b114c68857d808.js", - "static/chunks/2443530c-097fe1871e1d7679.js", - "static/chunks/488-66ca2c1db348e680.js", - "static/chunks/main-app-0be5dce44311dbbf.js", - "static/chunks/app/everyone-votes/terms/page-5aa776690a4e5edf.js" + "/wiston/page": [ + "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/fd9d1056-ba10bf844a47945b.js", + "static/chunks/472-51fd3a56159f1e5b.js", + "static/chunks/main-app-cf3eb22ffef632f7.js", + "static/chunks/app/wiston/page-c31b345ea6ea73af.js" ] } } \ No newline at end of file diff --git a/.next/app-path-routes-manifest.json b/.next/app-path-routes-manifest.json index 2eae688..e5fc0ac 100644 --- a/.next/app-path-routes-manifest.json +++ b/.next/app-path-routes-manifest.json @@ -1,8 +1 @@ -{ - "/favicon.ico/route": "/favicon.ico", - "/page": "/", - "/wiston/page": "/wiston", - "/space/page": "/space", - "/everyone-votes/privacy/page": "/everyone-votes/privacy", - "/everyone-votes/terms/page": "/everyone-votes/terms" -} \ No newline at end of file +{"/_not-found":"/_not-found","/everyone-votes/terms/page":"/everyone-votes/terms","/everyone-votes/privacy/page":"/everyone-votes/privacy","/favicon.ico/route":"/favicon.ico","/page":"/","/space/page":"/space","/wiston/page":"/wiston"} \ No newline at end of file diff --git a/.next/build-manifest.json b/.next/build-manifest.json index 3f555bb..6aea16f 100644 --- a/.next/build-manifest.json +++ b/.next/build-manifest.json @@ -5,27 +5,27 @@ "devFiles": [], "ampDevFiles": [], "lowPriorityFiles": [ - "static/Qb5fVlqLpQAODnw100j4z/_buildManifest.js", - "static/Qb5fVlqLpQAODnw100j4z/_ssgManifest.js" + "static/9CqSqX2Hqhh4fwiD8kSfJ/_buildManifest.js", + "static/9CqSqX2Hqhh4fwiD8kSfJ/_ssgManifest.js" ], "rootMainFiles": [ - "static/chunks/webpack-54b114c68857d808.js", - "static/chunks/2443530c-097fe1871e1d7679.js", - "static/chunks/488-66ca2c1db348e680.js", - "static/chunks/main-app-0be5dce44311dbbf.js" + "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/fd9d1056-ba10bf844a47945b.js", + "static/chunks/472-51fd3a56159f1e5b.js", + "static/chunks/main-app-cf3eb22ffef632f7.js" ], "pages": { "/_app": [ - "static/chunks/webpack-54b114c68857d808.js", + "static/chunks/webpack-c42a79c5d8b7c910.js", "static/chunks/framework-8883d1e9be70c3da.js", - "static/chunks/main-dba5d122367f02b7.js", - "static/chunks/pages/_app-b555d5e1eab47959.js" + "static/chunks/main-07bf56c05aa7cd6e.js", + "static/chunks/pages/_app-1534f180665c857f.js" ], "/_error": [ - "static/chunks/webpack-54b114c68857d808.js", + "static/chunks/webpack-c42a79c5d8b7c910.js", "static/chunks/framework-8883d1e9be70c3da.js", - "static/chunks/main-dba5d122367f02b7.js", - "static/chunks/pages/_error-d79168f986538ac0.js" + "static/chunks/main-07bf56c05aa7cd6e.js", + "static/chunks/pages/_error-b646007f40c4f0a8.js" ] }, "ampFirstPages": [] diff --git a/.next/next-minimal-server.js.nft.json b/.next/next-minimal-server.js.nft.json new file mode 100644 index 0000000..9f9db74 --- /dev/null +++ b/.next/next-minimal-server.js.nft.json @@ -0,0 +1 @@ +{"version":1,"files":["../node_modules/styled-jsx/index.js","../node_modules/styled-jsx/package.json","../node_modules/styled-jsx/dist/index/index.js","../node_modules/react/package.json","../node_modules/react/index.js","../node_modules/client-only/package.json","../node_modules/react/cjs/react.production.min.js","../node_modules/client-only/index.js","../node_modules/styled-jsx/style.js","../node_modules/next/dist/compiled/next-server/server.runtime.prod.js","../node_modules/next/package.json","../node_modules/next/dist/server/body-streams.js","../node_modules/next/dist/shared/lib/constants.js","../node_modules/next/dist/server/web/utils.js","../node_modules/next/dist/client/components/app-router-headers.js","../node_modules/next/dist/server/lib/trace/tracer.js","../node_modules/next/dist/server/lib/trace/constants.js","../node_modules/next/dist/shared/lib/modern-browserslist-target.js","../node_modules/next/dist/shared/lib/runtime-config.external.js","../node_modules/next/dist/compiled/ws/package.json","../node_modules/@swc/helpers/_/_interop_require_default/package.json","../node_modules/next/dist/compiled/ws/index.js","../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../node_modules/next/dist/compiled/jsonwebtoken/package.json","../node_modules/@swc/helpers/package.json","../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../node_modules/next/dist/compiled/jsonwebtoken/index.js","../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../node_modules/next/dist/lib/semver-noop.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/amp-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/app-router-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/entrypoints.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/head-manager-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/hooks-client-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/html-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/image-config-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/loadable-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/loadable.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/router-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/server-inserted-html.js","../node_modules/next/dist/server/future/route-modules/app-page/module.compiled.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/amp-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/app-router-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/entrypoints.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/head-manager-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/hooks-client-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/html-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/image-config-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/loadable-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/loadable.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/router-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/server-inserted-html.js","../node_modules/next/dist/server/future/route-modules/pages/module.compiled.js"]} \ No newline at end of file diff --git a/.next/next-server.js.nft.json b/.next/next-server.js.nft.json index ee817aa..4e0328b 100644 --- a/.next/next-server.js.nft.json +++ b/.next/next-server.js.nft.json @@ -1 +1 @@ -{"version":1,"cacheKey":"b3e86ffef9547a098a3078a4d5597d5e0ecd63676df688a95520b81c124ec042","files":["../node_modules/next/dist/server/next-server.js","../node_modules/next/package.json","../node_modules/next/dist/server/node-environment.js","../node_modules/next/dist/server/require-hook.js","../node_modules/next/dist/server/base-server.js","../node_modules/next/dist/server/node-polyfill-form.js","../node_modules/next/dist/server/node-polyfill-fetch.js","../node_modules/next/dist/server/node-polyfill-web-streams.js","../node_modules/next/dist/server/node-polyfill-crypto.js","../node_modules/next/dist/server/request-meta.js","../node_modules/next/dist/server/server-route-utils.js","../node_modules/next/dist/server/serve-static.js","../node_modules/next/dist/server/render.js","../node_modules/next/dist/server/require.js","../node_modules/next/dist/server/load-components.js","../node_modules/next/dist/server/body-streams.js","../node_modules/next/dist/server/api-utils/node.js","../node_modules/next/dist/server/config.js","../node_modules/next/dist/server/image-optimizer.js","../node_modules/next/dist/server/lib/recursive-readdir-sync.js","../node_modules/next/dist/server/lib/node-fs-methods.js","../node_modules/next/dist/server/lib/mock-request.js","../node_modules/next/dist/server/lib/server-ipc/invoke-request.js","../node_modules/next/dist/server/lib/server-ipc/utils.js","../node_modules/next/dist/lib/find-pages-dir.js","../node_modules/next/dist/lib/is-error.js","../node_modules/next/dist/lib/constants.js","../node_modules/next/dist/server/base-http/node.js","../node_modules/next/dist/server/web/utils.js","../node_modules/next/dist/server/future/route-kind.js","../node_modules/next/dist/server/lib/trace/constants.js","../node_modules/next/dist/server/lib/trace/tracer.js","../node_modules/next/dist/server/app-render/app-render.js","../node_modules/next/dist/shared/lib/constants.js","../node_modules/next/dist/shared/lib/utils.js","../node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js","../node_modules/next/dist/shared/lib/page-path/normalize-page-path.js","../node_modules/next/dist/shared/lib/router/utils/route-matcher.js","../node_modules/next/dist/shared/lib/router/utils/path-match.js","../node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.js","../node_modules/next/dist/shared/lib/router/utils/parse-url.js","../node_modules/next/dist/shared/lib/router/utils/relativize-url.js","../node_modules/next/dist/shared/lib/router/utils/prepare-destination.js","../node_modules/next/dist/shared/lib/router/utils/querystring.js","../node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.js","../node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js","../node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js","../node_modules/next/dist/shared/lib/router/utils/app-paths.js","../node_modules/next/dist/shared/lib/router/utils/route-regex.js","../node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js","../node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js","../node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js","../node_modules/next/dist/build/output/log.js","../node_modules/next/dist/server/send-payload/index.js","../node_modules/next/dist/server/api-utils/index.js","../node_modules/next/dist/server/response-cache/index.js","../node_modules/next/dist/server/lib/incremental-cache/index.js","../node_modules/next/dist/server/lib/server-ipc/index.js","../node_modules/next/dist/server/web/sandbox/index.js","../node_modules/next/dist/server/utils.js","../node_modules/next/dist/lib/redirect-status.js","../node_modules/next/dist/lib/is-edge-runtime.js","../node_modules/next/dist/shared/lib/runtime-config.js","../node_modules/next/dist/server/send-payload/revalidate-headers.js","../node_modules/next/dist/server/router.js","../node_modules/next/dist/server/render-result.js","../node_modules/next/dist/shared/lib/router/utils/is-bot.js","../node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js","../node_modules/next/dist/server/server-utils.js","../node_modules/next/dist/shared/lib/get-hostname.js","../node_modules/next/dist/server/send-response.js","../node_modules/next/dist/lib/interop-default.js","../node_modules/next/dist/lib/is-serializable-props.js","../node_modules/next/dist/shared/lib/amp-mode.js","../node_modules/next/dist/shared/lib/amp-context.js","../node_modules/next/dist/shared/lib/head-manager-context.js","../node_modules/next/dist/shared/lib/head.js","../node_modules/next/dist/shared/lib/loadable.js","../node_modules/next/dist/shared/lib/loadable-context.js","../node_modules/next/dist/shared/lib/router-context.js","../node_modules/next/dist/shared/lib/router/utils/is-dynamic.js","../node_modules/next/dist/shared/lib/html-context.js","../node_modules/next/dist/server/internal-utils.js","../node_modules/next/dist/shared/lib/image-config-context.js","../node_modules/next/dist/shared/lib/router/adapters.js","../node_modules/next/dist/shared/lib/hooks-client-context.js","../node_modules/next/dist/shared/lib/app-router-context.js","../node_modules/next/dist/server/post-process.js","../node_modules/next/dist/lib/chalk.js","../node_modules/next/dist/server/config-shared.js","../node_modules/next/dist/server/config-utils.js","../node_modules/next/dist/lib/find-root.js","../node_modules/next/dist/shared/lib/image-config.js","../node_modules/next/dist/shared/lib/image-blur-svg.js","../node_modules/next/dist/shared/lib/match-remote-pattern.js","../node_modules/next/dist/server/future/route-handler-managers/route-handler-manager.js","../node_modules/next/dist/server/future/normalizers/locale-route-normalizer.js","../node_modules/next/dist/server/future/route-matcher-managers/default-route-matcher-manager.js","../node_modules/next/dist/server/future/route-matcher-providers/app-page-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/app-route-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/pages-api-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/pages-route-matcher-provider.js","../node_modules/next/dist/server/future/helpers/i18n-provider.js","../node_modules/next/dist/shared/lib/i18n/get-locale-redirect.js","../node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js","../node_modules/next/dist/server/stream-utils/node-web-streams-helper.js","../node_modules/next/dist/server/lib/etag.js","../node_modules/next/dist/server/crypto-utils.js","../node_modules/next/dist/telemetry/flush-and-exit.js","../node_modules/next/dist/server/lib/squoosh/main.js","../node_modules/next/dist/client/components/app-router-headers.js","../node_modules/next/dist/server/future/route-modules/helpers/response-handlers.js","../node_modules/next/dist/server/future/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader.js","../node_modules/next/dist/shared/lib/is-plain-object.js","../node_modules/next/dist/server/base-http/index.js","../node_modules/next/dist/server/web/spec-extension/cookies.js","../node_modules/next/dist/server/web/spec-extension/adapters/headers.js","../node_modules/next/dist/server/web/spec-extension/adapters/reflect.js","../node_modules/next/dist/client/components/error.js","../node_modules/next/dist/client/components/match-segments.js","../node_modules/next/dist/server/app-render/create-server-components-renderer.js","../node_modules/next/dist/shared/lib/server-inserted-html.js","../node_modules/next/dist/lib/client-reference.js","../node_modules/next/dist/server/lib/app-dir-module.js","../node_modules/next/dist/client/components/redirect.js","../node_modules/next/dist/client/components/not-found.js","../node_modules/next/dist/server/lib/patch-fetch.js","../node_modules/next/dist/server/app-render/interop-default.js","../node_modules/next/dist/server/app-render/flight-render-result.js","../node_modules/next/dist/server/app-render/preload-component.js","../node_modules/next/dist/server/app-render/create-error-handler.js","../node_modules/next/dist/server/app-render/get-short-dynamic-param-type.js","../node_modules/next/dist/server/app-render/get-segment-param.js","../node_modules/next/dist/server/app-render/get-css-inlined-link-tags.js","../node_modules/next/dist/server/app-render/get-server-css-for-entries.js","../node_modules/next/dist/server/app-render/get-preloadable-fonts.js","../node_modules/next/dist/server/app-render/get-script-nonce-from-header.js","../node_modules/next/dist/server/app-render/render-to-string.js","../node_modules/next/dist/server/app-render/parse-and-validate-flight-router-state.js","../node_modules/next/dist/server/app-render/validate-url.js","../node_modules/next/dist/server/app-render/action-handler.js","../node_modules/next/dist/server/app-render/create-flight-router-state-from-loader-tree.js","../node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js","../node_modules/next/dist/server/async-storage/request-async-storage-wrapper.js","../node_modules/next/dist/lib/metadata/metadata.js","../node_modules/next/dist/server/async-storage/static-generation-async-storage-wrapper.js","../node_modules/next/dist/shared/lib/lazy-dynamic/no-ssr-error.js","../node_modules/next/dist/shared/lib/modern-browserslist-target.js","../node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js","../node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js","../node_modules/next/dist/shared/lib/escape-regexp.js","../node_modules/next/dist/server/future/helpers/interception-routes.js","../node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js","../node_modules/next/dist/shared/lib/router/utils/parse-path.js","../node_modules/next/dist/shared/lib/router/utils/index.js","../node_modules/next/dist/server/lib/render-server.js","../node_modules/next/dist/server/lib/worker-utils.js","../node_modules/next/dist/server/lib/utils.js","../node_modules/next/dist/server/response-cache/types.js","../node_modules/next/dist/lib/is-api-route.js","../node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js","../node_modules/next/dist/shared/lib/i18n/detect-locale-cookie.js","../node_modules/next/dist/server/accept-header.js","../node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js","../node_modules/next/dist/server/lib/incremental-cache/file-system-cache.js","../node_modules/next/dist/server/lib/incremental-cache/fetch-cache.js","../node_modules/next/dist/server/stream-utils/encode-decode.js","../node_modules/next/dist/shared/lib/base64-arraybuffer.js","../node_modules/next/dist/shared/lib/utils/warn-once.js","../node_modules/next/dist/shared/lib/side-effect.js","../node_modules/next/dist/lib/non-nullable.js","../node_modules/next/dist/server/font-utils.js","../node_modules/next/dist/server/optimize-amp.js","../node_modules/next/dist/server/web/sandbox/sandbox.js","../node_modules/next/dist/server/web/sandbox/context.js","../node_modules/next/dist/shared/lib/isomorphic/path.js","../node_modules/next/dist/lib/web/chalk.js","../node_modules/next/dist/server/web/spec-extension/adapters/next-request.js","../node_modules/next/dist/lib/is-app-page-route.js","../node_modules/next/dist/server/future/route-matcher-providers/manifest-route-matcher-provider.js","../node_modules/next/dist/lib/is-app-route-route.js","../node_modules/next/dist/shared/lib/router/utils/format-url.js","../node_modules/next/dist/server/app-render/use-flight-response.js","../node_modules/next/dist/lib/format-server-error.js","../node_modules/next/dist/client/components/hooks-server-context.js","../node_modules/next/dist/server/htmlescape.js","../node_modules/next/dist/server/app-render/types.js","../node_modules/next/dist/server/future/helpers/module-loader/node-module-loader.js","../node_modules/next/dist/server/future/helpers/module-loader/route-module-loader.js","../node_modules/next/dist/server/future/route-matchers/app-page-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/locale-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/pages-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/app-route-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/pages-api-route-matcher.js","../node_modules/next/dist/trace/shared.js","../node_modules/next/dist/server/dev/log-app-dir-error.js","../node_modules/next/dist/client/components/request-async-storage.js","../node_modules/next/dist/compiled/react-experimental/package.json","../node_modules/next/dist/compiled/react-experimental/jsx-runtime.js","../node_modules/next/dist/compiled/react-experimental/jsx-dev-runtime.js","../node_modules/next/dist/compiled/react/package.json","../node_modules/next/dist/compiled/react/jsx-runtime.js","../node_modules/next/dist/compiled/react/jsx-dev-runtime.js","../node_modules/next/dist/compiled/react-dom-experimental/package.json","../node_modules/next/dist/compiled/react-dom-experimental/client.js","../node_modules/next/dist/compiled/react-dom-experimental/server-rendering-stub.js","../node_modules/next/dist/compiled/react-dom-experimental/server.js","../node_modules/next/dist/compiled/react-dom-experimental/server.browser.js","../node_modules/next/dist/compiled/react-dom-experimental/server.edge.js","../node_modules/next/dist/compiled/react-dom/package.json","../node_modules/next/dist/compiled/react-dom/server-rendering-stub.js","../node_modules/next/dist/compiled/react-dom/client.js","../node_modules/next/dist/compiled/react-dom/server.browser.js","../node_modules/next/dist/compiled/react-dom/server.js","../node_modules/next/dist/compiled/react-dom/server.edge.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/client.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/client.edge.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/server.node.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/server.edge.js","../node_modules/next/dist/compiled/react-server-dom-webpack/client.js","../node_modules/next/dist/compiled/react-server-dom-webpack/server.edge.js","../node_modules/next/dist/compiled/react-server-dom-webpack/client.edge.js","../node_modules/next/dist/compiled/react-server-dom-webpack/server.node.js","../node_modules/styled-jsx/style.js","../node_modules/next/dist/server/async-storage/draft-mode-provider.js","../node_modules/next/dist/lib/metadata/resolve-metadata.js","../node_modules/next/dist/shared/lib/router/utils/sorted-routes.js","../node_modules/next/dist/next-config-validate.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/fetch.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/streams.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/blob.js","../node_modules/react/package.json","../node_modules/next/dist/lib/metadata/generate/basic.js","../node_modules/next/dist/lib/metadata/generate/opengraph.js","../node_modules/next/dist/lib/metadata/generate/alternate.js","../node_modules/next/dist/lib/metadata/generate/icons.js","../node_modules/next/dist/compiled/react-server-dom-webpack/package.json","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/package.json","../node_modules/react/jsx-runtime.js","../node_modules/react/jsx-dev-runtime.js","../node_modules/styled-jsx/package.json","../node_modules/react-dom/package.json","../node_modules/next/dist/server/next.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/package.json","../node_modules/next/dist/compiled/@next/react-dev-overlay/dist/middleware.js","../node_modules/react-dom/server.browser.js","../node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js","../node_modules/next/dist/shared/lib/router/utils/add-locale.js","../node_modules/next/dist/server/lib/incremental-cache/utils.js","../node_modules/next/dist/server/web/sandbox/fetch-inline-assets.js","../node_modules/next/dist/lib/pick.js","../node_modules/react/index.js","../node_modules/next/dist/server/future/normalizers/built/app/index.js","../node_modules/next/dist/server/future/normalizers/built/pages/index.js","../node_modules/next/dist/build/webpack/plugins/nextjs-require-cache-hot-reloader.js","../node_modules/next/dist/compiled/webpack/webpack.js","../node_modules/styled-jsx/index.js","../node_modules/next/dist/server/web/spec-extension/request.js","../node_modules/next/dist/server/future/route-matcher-providers/helpers/cached-route-matcher-provider.js","../node_modules/next/dist/compiled/webpack/package.json","../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.production.min.js","../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.development.js","../node_modules/next/dist/compiled/react/cjs/react-jsx-dev-runtime.production.min.js","../node_modules/next/dist/compiled/react/cjs/react-jsx-dev-runtime.development.js","../node_modules/next/dist/compiled/react-experimental/cjs/react-jsx-runtime.production.min.js","../node_modules/next/dist/compiled/react-experimental/cjs/react-jsx-runtime.development.js","../node_modules/next/dist/compiled/react-experimental/cjs/react-jsx-dev-runtime.development.js","../node_modules/next/dist/compiled/react-experimental/cjs/react-jsx-dev-runtime.production.min.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.production.min.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.development.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.production.min.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-legacy.browser.development.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.browser.development.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.edge.production.min.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.edge.development.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server-rendering-stub.production.min.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server-rendering-stub.development.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server.browser.production.min.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server-legacy.browser.production.min.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server-legacy.browser.development.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server.browser.development.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server.edge.development.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server.edge.production.min.js","../node_modules/next/dist/server/future/route-matchers/route-matcher.js","../node_modules/next/dist/client/components/async-local-storage.js","../node_modules/next/dist/compiled/path-to-regexp/index.js","../node_modules/next/dist/compiled/react/index.js","../node_modules/next/dist/compiled/react-dom-experimental/server.node.js","../node_modules/next/dist/compiled/react-dom/server.node.js","../node_modules/next/dist/compiled/react-experimental/index.js","../node_modules/next/dist/lib/metadata/default-metadata.js","../node_modules/next/dist/lib/metadata/generate/utils.js","../node_modules/next/dist/lib/metadata/clone-metadata.js","../node_modules/@next/env/package.json","../node_modules/@next/env/dist/index.js","../node_modules/next/dist/compiled/chalk/package.json","../node_modules/next/dist/compiled/chalk/index.js","../node_modules/next/dist/compiled/compression/package.json","../node_modules/next/dist/compiled/compression/index.js","../node_modules/next/dist/compiled/http-proxy/package.json","../node_modules/next/dist/compiled/http-proxy/index.js","../node_modules/next/dist/compiled/ws/package.json","../node_modules/next/dist/compiled/ws/index.js","../node_modules/next/dist/compiled/undici/package.json","../node_modules/next/dist/compiled/undici/index.js","../node_modules/next/dist/compiled/edge-runtime/package.json","../node_modules/next/dist/compiled/edge-runtime/index.js","../node_modules/next/dist/compiled/send/package.json","../node_modules/next/dist/compiled/send/index.js","../node_modules/next/dist/compiled/lru-cache/package.json","../node_modules/next/dist/compiled/lru-cache/index.js","../node_modules/next/dist/compiled/strip-ansi/package.json","../node_modules/next/dist/compiled/strip-ansi/index.js","../node_modules/next/dist/compiled/react-is/package.json","../node_modules/next/dist/compiled/react-is/index.js","../node_modules/next/dist/compiled/content-disposition/package.json","../node_modules/next/dist/compiled/content-disposition/index.js","../node_modules/next/dist/compiled/find-up/package.json","../node_modules/next/dist/compiled/find-up/index.js","../node_modules/next/dist/compiled/get-orientation/package.json","../node_modules/next/dist/compiled/get-orientation/index.js","../node_modules/next/dist/compiled/bytes/package.json","../node_modules/next/dist/compiled/bytes/index.js","../node_modules/next/dist/compiled/image-size/package.json","../node_modules/next/dist/compiled/image-size/index.js","../node_modules/next/dist/compiled/is-animated/package.json","../node_modules/next/dist/compiled/is-animated/index.js","../node_modules/next/dist/compiled/content-type/package.json","../node_modules/next/dist/compiled/content-type/index.js","../node_modules/next/dist/compiled/cookie/package.json","../node_modules/next/dist/compiled/cookie/index.js","../node_modules/next/dist/compiled/nanoid/package.json","../node_modules/next/dist/compiled/nanoid/index.cjs","../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-server.edge.production.min.js","../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-server.edge.development.js","../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.production.min.js","../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.development.js","../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-server.node.production.min.js","../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-server.node.development.js","../node_modules/next/dist/compiled/raw-body/package.json","../node_modules/next/dist/compiled/raw-body/index.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.production.min.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.development.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.edge.production.min.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.edge.development.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.edge.development.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.edge.production.min.js","../node_modules/next/dist/compiled/jsonwebtoken/package.json","../node_modules/next/dist/compiled/jsonwebtoken/index.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-opengraph.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-title.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-basics.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-icons.js","../node_modules/next/dist/compiled/react-server-dom-webpack/client.browser.js","../node_modules/next/dist/compiled/@hapi/accept/package.json","../node_modules/next/dist/compiled/@hapi/accept/index.js","../node_modules/next/dist/compiled/@segment/ajv-human-errors/package.json","../node_modules/next/dist/compiled/@segment/ajv-human-errors/index.js","../node_modules/react/cjs/react-jsx-runtime.development.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react-jsx-dev-runtime.production.min.js","../node_modules/react/cjs/react-jsx-dev-runtime.development.js","../node_modules/react/cjs/react.production.min.js","../node_modules/react/cjs/react.development.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/client.browser.js","../node_modules/next/dist/lib/metadata/generate/meta.js","../node_modules/next/dist/server/next-typescript.js","../node_modules/next/dist/server/dev/next-dev-server.js","../node_modules/next/dist/server/lib/render-server-standalone.js","../node_modules/next/dist/server/capsize-font-metrics.json","../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js","../node_modules/react-dom/cjs/react-dom-server.browser.development.js","../node_modules/next/dist/compiled/fresh/package.json","../node_modules/next/dist/compiled/fresh/index.js","../node_modules/next/dist/compiled/micromatch/package.json","../node_modules/next/dist/compiled/micromatch/index.js","../node_modules/next/dist/compiled/node-html-parser/package.json","../node_modules/next/dist/compiled/node-html-parser/index.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/abort-controller.js","../node_modules/busboy/package.json","../node_modules/busboy/lib/index.js","../node_modules/next/dist/server/web/next-url.js","../node_modules/next/dist/server/web/error.js","../node_modules/next/dist/compiled/react/cjs/react.production.min.js","../node_modules/next/dist/compiled/react/cjs/react.development.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server.node.development.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server-legacy.node.development.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server.node.production.min.js","../node_modules/next/dist/compiled/react-dom-experimental/cjs/react-dom-server-legacy.node.production.min.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.node.production.min.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-legacy.node.production.min.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-legacy.node.development.js","../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server.node.development.js","../node_modules/next/dist/compiled/string-hash/package.json","../node_modules/next/dist/compiled/string-hash/index.js","../node_modules/next/dist/server/future/normalizers/built/app/app-bundle-path-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-filename-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-page-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-pathname-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-bundle-path-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-filename-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-page-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-pathname-normalizer.js","../node_modules/next/dist/compiled/react-experimental/cjs/react.production.min.js","../node_modules/next/dist/compiled/react-experimental/cjs/react.development.js","../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.production.min.js","../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.development.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.browser.production.min.js","../node_modules/next/dist/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-client.browser.development.js","../node_modules/next/dist/compiled/@edge-runtime/cookies/package.json","../node_modules/next/dist/compiled/@edge-runtime/cookies/index.js","../node_modules/styled-jsx/dist/index/index.js","../node_modules/next/dist/compiled/react-is/cjs/react-is.production.min.js","../node_modules/next/dist/compiled/react-is/cjs/react-is.development.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-url.js","../node_modules/next/dist/lib/metadata/constants.js","../node_modules/next/dist/lib/file-exists.js","../node_modules/next/dist/lib/load-custom-routes.js","../node_modules/next/dist/lib/verifyTypeScriptSetup.js","../node_modules/next/dist/lib/verify-partytown-setup.js","../node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.js","../node_modules/next/dist/telemetry/storage.js","../node_modules/next/dist/server/dev/hot-reloader.js","../node_modules/next/dist/server/lib/find-page-file.js","../node_modules/next/dist/build/entries.js","../node_modules/next/dist/lib/coalesced-function.js","../node_modules/next/dist/build/utils.js","../node_modules/next/dist/build/webpack-config.js","../node_modules/next/dist/build/load-jsconfig.js","../node_modules/next/dist/build/webpack/plugins/next-types-plugin.js","../node_modules/next/dist/server/future/route-matcher-managers/dev-route-matcher-manager.js","../node_modules/next/dist/server/future/route-matcher-providers/helpers/manifest-loaders/node-manifest-loader.js","../node_modules/next/dist/build/build-context.js","../node_modules/next/dist/lib/create-client-router-filter.js","../node_modules/next/dist/lib/generate-interception-routes-rewrites.js","../node_modules/next/dist/server/dev/static-paths-worker.js","../node_modules/next/dist/server/future/route-matcher-providers/dev/dev-pages-api-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/dev/dev-pages-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/dev/dev-app-page-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/dev/dev-app-route-route-matcher-provider.js","../node_modules/next/dist/lib/realpath.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/events.js","../node_modules/next/dist/server/future/route-matcher-providers/dev/helpers/file-reader/cached-file-reader.js","../node_modules/next/dist/server/future/route-matcher-providers/dev/helpers/file-reader/default-file-reader.js","../node_modules/react-dom/index.js","../node_modules/zod/package.json","../node_modules/@swc/helpers/_/_interop_require_default/package.json","../node_modules/@swc/helpers/_/_interop_require_wildcard/package.json","../node_modules/busboy/lib/utils.js","../node_modules/next/dist/server/future/normalizers/normalizers.js","../node_modules/next/dist/server/future/normalizers/prefixing-normalizer.js","../node_modules/next/dist/server/future/normalizers/wrap-normalizer-fn.js","../node_modules/next/dist/server/future/normalizers/absolute-filename-normalizer.js","../node_modules/next/dist/server/future/normalizers/underscore-normalizer.js","../node_modules/next/dist/compiled/path-browserify/package.json","../node_modules/next/dist/compiled/path-browserify/index.js","../node_modules/zod/lib/index.js","../node_modules/next/dist/trace/index.js","../node_modules/next/dist/build/output/index.js","../node_modules/@swc/helpers/package.json","../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../node_modules/@swc/helpers/cjs/_interop_require_wildcard.cjs","../node_modules/next/dist/telemetry/events/index.js","../node_modules/busboy/lib/types/multipart.js","../node_modules/busboy/lib/types/urlencoded.js","../node_modules/next/dist/server/typescript/index.js","../node_modules/next/dist/compiled/@next/react-dev-overlay/dist/client.js","../node_modules/next/dist/lib/has-necessary-dependencies.js","../node_modules/next/dist/lib/try-to-parse-path.js","../node_modules/next/dist/lib/compile-error.js","../node_modules/next/dist/lib/fatal-error.js","../node_modules/next/dist/lib/install-dependencies.js","../node_modules/next/dist/telemetry/ci-info.js","../node_modules/next/dist/lib/recursive-delete.js","../node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.js","../node_modules/next/dist/lib/metadata/get-metadata-route.js","../node_modules/next/dist/telemetry/anonymous-meta.js","../node_modules/next/dist/telemetry/detached-flush.js","../node_modules/next/dist/telemetry/project-id.js","../node_modules/next/dist/telemetry/post-payload.js","../node_modules/next/dist/shared/lib/page-path/get-page-paths.js","../node_modules/next/dist/lib/metadata/is-metadata-route.js","../node_modules/next/dist/server/dev/on-demand-entry-handler.js","../node_modules/next/dist/server/dev/hot-middleware.js","../node_modules/next/dist/server/get-route-from-entrypoint.js","../node_modules/next/dist/server/dev/parse-version-info.js","../node_modules/next/dist/lib/is-internal-pathname.js","../node_modules/next/dist/client/router.js","../node_modules/next/dist/lib/pretty-bytes.js","../node_modules/next/dist/server/web/http.js","../node_modules/next/dist/client/components/static-generation-async-storage.js","../node_modules/next/dist/shared/lib/bloom-filter.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/react-dom/cjs/react-dom.development.js","../node_modules/next/dist/lib/typescript/writeAppTypeDeclarations.js","../node_modules/next/dist/lib/typescript/getTypeScriptIntent.js","../node_modules/next/dist/lib/typescript/runTypeCheck.js","../node_modules/next/dist/lib/typescript/missingDependencyError.js","../node_modules/next/dist/lib/typescript/writeConfigurationDefaults.js","../node_modules/next/dist/lib/typescript/getTypeScriptConfiguration.js","../node_modules/next/dist/lib/helpers/get-pkg-manager.js","../node_modules/next/dist/lib/helpers/get-registry.js","../node_modules/next/dist/build/webpack/loaders/next-route-loader.js","../node_modules/next/dist/build/webpack/loaders/next-middleware-loader.js","../node_modules/next/dist/build/analysis/get-page-static-info.js","../node_modules/next/dist/server/future/route-matcher-providers/dev/file-cache-route-matcher-provider.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/encoding.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/crypto.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/url.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/structured-clone.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/console.js","../node_modules/next/dist/compiled/@edge-runtime/primitives/cache.js","../node_modules/next/dist/trace/trace.js","../node_modules/next/dist/build/output/store.js","../node_modules/zod/lib/external.js","../node_modules/next/dist/telemetry/events/build.js","../node_modules/next/dist/telemetry/events/version.js","../node_modules/next/dist/telemetry/events/plugins.js","../node_modules/next/dist/client/dev/error-overlay/format-webpack-messages.js","../node_modules/next/dist/lib/resolve-from.js","../node_modules/next/dist/server/typescript/utils.js","../node_modules/next/dist/server/typescript/constant.js","../node_modules/next/dist/lib/helpers/install.js","../node_modules/next/dist/lib/helpers/get-online.js","../node_modules/next/dist/shared/lib/hash.js","../node_modules/next/dist/lib/get-project-dir.js","../node_modules/next/dist/shared/lib/flatten.js","../node_modules/next/dist/server/match-bundle.js","../node_modules/next/dist/server/get-app-route-from-entrypoint.js","../node_modules/next/dist/shared/lib/router/router.js","../node_modules/next/dist/client/with-router.js","../node_modules/next/dist/compiled/shell-quote/package.json","../node_modules/next/dist/compiled/shell-quote/index.js","../node_modules/next/dist/compiled/stacktrace-parser/package.json","../node_modules/next/dist/compiled/stacktrace-parser/stack-trace-parser.cjs.js","../node_modules/next/dist/compiled/data-uri-to-buffer/package.json","../node_modules/next/dist/compiled/data-uri-to-buffer/index.js","../node_modules/next/dist/server/typescript/rules/client-boundary.js","../node_modules/next/dist/server/typescript/rules/entry.js","../node_modules/next/dist/server/typescript/rules/server.js","../node_modules/next/dist/server/typescript/rules/config.js","../node_modules/next/dist/server/typescript/rules/metadata.js","../node_modules/next/dist/server/typescript/rules/error.js","../node_modules/next/dist/compiled/babel/code-frame.js","../node_modules/next/dist/compiled/watchpack/package.json","../node_modules/next/dist/compiled/watchpack/watchpack.js","../node_modules/next/dist/compiled/amphtml-validator/package.json","../node_modules/next/dist/compiled/amphtml-validator/index.js","../node_modules/next/dist/lib/recursive-readdir.js","../node_modules/next/dist/lib/oxford-comma-list.js","../node_modules/next/dist/lib/typescript/diagnosticFormatter.js","../node_modules/next/dist/build/webpack/loaders/get-module-build-info.js","../node_modules/next/dist/build/webpack/stringify-request.js","../node_modules/next/dist/build/analysis/extract-const-value.js","../node_modules/next/dist/build/analysis/parse-module.js","../node_modules/next/dist/compiled/babel/package.json","../node_modules/client-only/package.json","../node_modules/client-only/index.js","../node_modules/next/dist/compiled/debug/package.json","../node_modules/next/dist/compiled/debug/index.js","../node_modules/next/dist/compiled/p-limit/package.json","../node_modules/next/dist/compiled/p-limit/index.js","../node_modules/next/dist/compiled/semver/package.json","../node_modules/next/dist/compiled/semver/index.js","../node_modules/zod/lib/errors.js","../node_modules/zod/lib/types.js","../node_modules/zod/lib/ZodError.js","../node_modules/zod/lib/helpers/parseUtil.js","../node_modules/zod/lib/helpers/typeAliases.js","../node_modules/zod/lib/helpers/util.js","../node_modules/next/dist/lib/commands.js","../node_modules/next/dist/lib/detect-typo.js","../node_modules/next/dist/compiled/gzip-size/package.json","../node_modules/next/dist/compiled/gzip-size/index.js","../node_modules/next/dist/compiled/text-table/package.json","../node_modules/next/dist/compiled/text-table/index.js","../node_modules/next/dist/compiled/browserslist/package.json","../node_modules/next/dist/compiled/browserslist/index.js","../node_modules/next/dist/compiled/json5/package.json","../node_modules/next/dist/compiled/json5/index.js","../node_modules/next/dist/compiled/async-sema/package.json","../node_modules/next/dist/compiled/async-sema/index.js","../node_modules/scheduler/package.json","../node_modules/scheduler/index.js","../node_modules/next/dist/compiled/conf/package.json","../node_modules/next/dist/compiled/conf/index.js","../node_modules/next/dist/compiled/is-docker/package.json","../node_modules/next/dist/compiled/is-docker/index.js","../node_modules/next/dist/client/route-loader.js","../node_modules/next/dist/client/script.js","../node_modules/next/dist/shared/lib/mitt.js","../node_modules/next/dist/client/detect-domain-locale.js","../node_modules/next/dist/shared/lib/router/utils/resolve-rewrites.js","../node_modules/next/dist/client/add-locale.js","../node_modules/next/dist/client/has-base-path.js","../node_modules/next/dist/client/remove-base-path.js","../node_modules/next/dist/client/remove-locale.js","../node_modules/next/dist/client/add-base-path.js","../node_modules/next/dist/shared/lib/router/utils/compare-states.js","../node_modules/next/dist/shared/lib/router/utils/is-local-url.js","../node_modules/next/dist/shared/lib/router/utils/omit.js","../node_modules/next/dist/shared/lib/router/utils/interpolate-as.js","../node_modules/next/dist/shared/lib/router/utils/resolve-href.js","../node_modules/next/dist/shared/lib/router/utils/handle-smooth-scroll.js","../node_modules/next/dist/lib/with-promise-cache.js","../node_modules/next/dist/compiled/babel/bundle.js","../node_modules/next/dist/trace/report/index.js","../node_modules/next/dist/build/swc/index.js","../node_modules/streamsearch/package.json","../node_modules/streamsearch/lib/sbmh.js","../node_modules/next/dist/compiled/babel/core.js","../node_modules/next/dist/compiled/unistore/package.json","../node_modules/next/dist/compiled/unistore/unistore.js","../node_modules/zod/lib/helpers/errorUtil.js","../node_modules/next/dist/compiled/platform/package.json","../node_modules/next/dist/compiled/platform/platform.js","../node_modules/next/dist/compiled/anser/package.json","../node_modules/next/dist/compiled/anser/index.js","../node_modules/next/dist/compiled/css.escape/package.json","../node_modules/next/dist/compiled/css.escape/css.escape.js","../node_modules/zod/lib/locales/en.js","../node_modules/next/dist/compiled/ci-info/package.json","../node_modules/next/dist/compiled/ci-info/index.js","../node_modules/next/dist/compiled/is-wsl/package.json","../node_modules/next/dist/compiled/is-wsl/index.js","../node_modules/next/dist/compiled/async-retry/package.json","../node_modules/next/dist/compiled/async-retry/index.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/cjs/scheduler.development.js","../node_modules/next/dist/cli/next-build.js","../node_modules/next/dist/cli/next-dev.js","../node_modules/next/dist/cli/next-telemetry.js","../node_modules/next/dist/cli/next-start.js","../node_modules/next/dist/cli/next-export.js","../node_modules/next/dist/cli/next-lint.js","../node_modules/next/dist/cli/next-info.js","../node_modules/next/dist/shared/lib/router/utils/get-asset-path-from-route.js","../node_modules/next/dist/client/trusted-types.js","../node_modules/next/dist/client/request-idle-callback.js","../node_modules/next/dist/client/head-manager.js","../node_modules/next/dist/client/normalize-trailing-slash.js","../node_modules/next/dist/compiled/comment-json/package.json","../node_modules/next/dist/compiled/comment-json/index.js","../node_modules/next/dist/trace/report/to-telemetry.js","../node_modules/next/dist/trace/report/to-json.js","../node_modules/next/dist/telemetry/events/swc-load-failure.js","../node_modules/next/dist/build/swc/options.js","../node_modules/next/dist/lib/patch-incorrect-lockfile.js","../node_modules/next/dist/lib/download-wasm-swc.js","../node_modules/next/dist/compiled/cross-spawn/package.json","../node_modules/next/dist/compiled/cross-spawn/index.js","../node_modules/next/dist/server/lib/start-server.js","../node_modules/next/dist/telemetry/events/session-stopped.js","../node_modules/next/dist/build/worker.js","../node_modules/next/dist/lib/get-package-version.js","../node_modules/next/dist/lib/turbopack-warning.js","../node_modules/next/dist/lib/helpers/get-npx-command.js","../node_modules/next/dist/lib/eslint/runLintCheck.js","../node_modules/next/dist/build/index.js","../node_modules/next/dist/export/index.js","../node_modules/next/dist/export/worker.js","../node_modules/next/dist/compiled/arg/index.js","../node_modules/next/dist/lib/eslint/hasEslintConfiguration.js","../node_modules/next/dist/lib/eslint/customFormatter.js","../node_modules/next/dist/lib/eslint/writeOutputFile.js","../node_modules/next/dist/lib/eslint/writeDefaultConfig.js","../node_modules/next/dist/compiled/arg/package.json","../node_modules/next/dist/compiled/@next/react-refresh-utils/dist/loader.js","../node_modules/next/dist/compiled/@napi-rs/triples/package.json","../node_modules/next/dist/compiled/@napi-rs/triples/index.js","../node_modules/next/dist/lib/server-external-packages.json","../node_modules/next/dist/lib/worker.js","../node_modules/next/dist/build/spinner.js","../node_modules/next/dist/lib/recursive-copy.js","../node_modules/caniuse-lite/dist/unpacker/agents.js","../node_modules/caniuse-lite/dist/unpacker/region.js","../node_modules/caniuse-lite/dist/unpacker/feature.js","../node_modules/next/dist/build/webpack/plugins/middleware-plugin.js","../node_modules/next/dist/build/webpack/plugins/build-manifest-plugin.js","../node_modules/next/dist/build/webpack/plugins/next-drop-client-page-plugin.js","../node_modules/next/dist/build/webpack/plugins/jsconfig-paths-plugin.js","../node_modules/next/dist/build/webpack/plugins/pages-manifest-plugin.js","../node_modules/next/dist/build/webpack/plugins/react-loadable-plugin.js","../node_modules/next/dist/build/webpack/plugins/profiling-plugin.js","../node_modules/next/dist/build/webpack/plugins/copy-file-plugin.js","../node_modules/next/dist/build/webpack/plugins/flight-manifest-plugin.js","../node_modules/next/dist/build/webpack/plugins/flight-client-entry-plugin.js","../node_modules/next/dist/build/webpack/plugins/app-build-manifest-plugin.js","../node_modules/next/dist/build/webpack/plugins/subresource-integrity-plugin.js","../node_modules/next/dist/build/webpack/plugins/next-font-manifest-plugin.js","../node_modules/next/dist/build/webpack/plugins/css-minimizer-plugin.js","../node_modules/next/dist/build/webpack/plugins/terser-webpack-plugin/src/index.js","../node_modules/next/dist/build/webpack/plugins/next-trace-entrypoints-plugin.js","../node_modules/next/dist/build/webpack/plugins/font-stylesheet-gathering-plugin.js","../node_modules/next/dist/build/webpack/plugins/telemetry-plugin.js","../node_modules/next/dist/compiled/babel-packages/package.json","../node_modules/next/dist/compiled/babel-packages/packages-bundle.js","../node_modules/next/dist/build/webpack/loaders/metadata/discover.js","../node_modules/next/dist/build/polyfills/process.js","../node_modules/next/dist/build/polyfills/polyfill-nomodule.js","../node_modules/next/dist/compiled/regenerator-runtime/package.json","../node_modules/next/dist/compiled/regenerator-runtime/runtime.js","../node_modules/next/dist/compiled/tar/package.json","../node_modules/next/dist/compiled/tar/index.js","../node_modules/next/dist/build/babel/loader/index.js","../node_modules/caniuse-lite/package.json","../node_modules/next/dist/build/webpack/config/index.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/index.js","../node_modules/next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWebpackPlugin.js","../node_modules/next/dist/compiled/@next/react-refresh-utils/dist/runtime.js","../node_modules/next/head.js","../node_modules/next/dynamic.js","../node_modules/next/dist/build/webpack/config/blocks/css/index.js","../node_modules/next/dist/compiled/buffer/package.json","../node_modules/next/dist/compiled/buffer/index.js","../node_modules/next/dist/compiled/events/package.json","../node_modules/next/dist/compiled/events/events.js","../node_modules/next/dist/compiled/@next/react-refresh-utils/dist/internal/ReactRefreshModule.runtime.js","../node_modules/next/dist/compiled/util/package.json","../node_modules/next/dist/compiled/util/util.js","../node_modules/next/dist/build/webpack/loaders/utils.js","../node_modules/next/dist/build/webpack/utils.js","../node_modules/next/dist/client/link.js","../node_modules/next/dist/client/image.js","../node_modules/next/dist/client/components/navigation.js","../node_modules/next/dist/client/components/noop-head.js","../node_modules/next/dist/client/components/headers.js","../node_modules/next/dist/shared/lib/app-dynamic.js","../node_modules/next/dist/shared/lib/dynamic.js","../node_modules/next/dist/compiled/cli-select/package.json","../node_modules/next/dist/compiled/cli-select/index.js","../node_modules/caniuse-lite/dist/unpacker/browsers.js","../node_modules/caniuse-lite/dist/unpacker/browserVersions.js","../node_modules/next/dist/lib/setup-exception-listeners.js","../node_modules/next/dist/build/generate-build-id.js","../node_modules/next/dist/lib/flat-readdir.js","../node_modules/next/dist/build/write-build-id.js","../node_modules/next/dist/telemetry/events/swc-plugins.js","../node_modules/next/dist/build/type-check.js","../node_modules/next/dist/build/is-writeable.js","../node_modules/caniuse-lite/data/agents.js","../node_modules/caniuse-lite/dist/lib/statuses.js","../node_modules/caniuse-lite/dist/lib/supported.js","../node_modules/next/dist/build/babel/loader/transform.js","../node_modules/next/dist/compiled/@next/react-refresh-utils/dist/internal/helpers.js","../node_modules/next/dist/build/webpack/config/blocks/base.js","../node_modules/next/dist/build/webpack/config/utils.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/webpackModuleError.js","../node_modules/next/dist/compiled/native-url/package.json","../node_modules/next/dist/compiled/native-url/index.js","../node_modules/next/dist/client/components/client-hook-in-server-component-error.js","../node_modules/next/dist/client/components/bailout-to-client-rendering.js","../node_modules/next/dist/client/components/action-async-storage.js","../node_modules/next/dist/client/components/static-generation-bailout.js","../node_modules/next/dist/client/components/draft-mode.js","../node_modules/next/dist/compiled/assert/package.json","../node_modules/next/dist/compiled/assert/assert.js","../node_modules/next/dist/compiled/domain-browser/package.json","../node_modules/next/dist/compiled/domain-browser/index.js","../node_modules/next/dist/compiled/constants-browserify/package.json","../node_modules/next/dist/compiled/constants-browserify/constants.json","../node_modules/next/dist/compiled/crypto-browserify/package.json","../node_modules/next/dist/compiled/crypto-browserify/index.js","../node_modules/next/dist/compiled/punycode/package.json","../node_modules/next/dist/compiled/punycode/punycode.js","../node_modules/next/dist/compiled/stream-http/package.json","../node_modules/next/dist/compiled/stream-http/index.js","../node_modules/next/dist/compiled/https-browserify/package.json","../node_modules/next/dist/compiled/https-browserify/index.js","../node_modules/next/dist/compiled/os-browserify/package.json","../node_modules/next/dist/compiled/os-browserify/browser.js","../node_modules/next/dist/compiled/querystring-es3/package.json","../node_modules/next/dist/compiled/querystring-es3/index.js","../node_modules/next/dist/compiled/string_decoder/package.json","../node_modules/next/dist/compiled/string_decoder/string_decoder.js","../node_modules/next/dist/compiled/stream-browserify/package.json","../node_modules/next/dist/compiled/stream-browserify/index.js","../node_modules/next/dist/compiled/vm-browserify/package.json","../node_modules/next/dist/compiled/vm-browserify/index.js","../node_modules/next/dist/compiled/timers-browserify/package.json","../node_modules/next/dist/compiled/timers-browserify/main.js","../node_modules/next/dist/compiled/tty-browserify/package.json","../node_modules/next/dist/compiled/tty-browserify/index.js","../node_modules/next/dist/compiled/setimmediate/package.json","../node_modules/next/dist/compiled/setimmediate/setImmediate.js","../node_modules/next/dist/compiled/browserify-zlib/package.json","../node_modules/next/dist/compiled/browserify-zlib/index.js","../node_modules/next/dist/client/get-domain-locale.js","../node_modules/next/dist/client/use-intersection.js","../node_modules/next/node_modules/postcss/package.json","../node_modules/next/dist/build/webpack-build/index.js","../node_modules/next/dist/compiled/process/package.json","../node_modules/next/dist/compiled/process/browser.js","../node_modules/next/dist/client/components/router-reducer/router-reducer-types.js","../node_modules/next/dist/client/components/router-reducer/reducers/get-segment-value.js","../node_modules/next/dist/shared/lib/lazy-dynamic/loadable.js","../node_modules/caniuse-lite/data/browsers.js","../node_modules/caniuse-lite/data/browserVersions.js","../node_modules/next/node_modules/postcss/lib/postcss.js","../node_modules/next/dist/lib/verifyAndLint.js","../node_modules/next/dist/build/webpack/config/blocks/images/index.js","../node_modules/next/dist/compiled/cssnano-simple/index.js","../node_modules/next/dist/shared/lib/image-loader.js","../node_modules/next/dist/build/babel/loader/get-config.js","../node_modules/next/dist/build/babel/loader/util.js","../node_modules/next/dist/compiled/ora/package.json","../node_modules/next/dist/compiled/ora/index.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/parseBabel.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/parseCss.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/parseScss.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/parseRSC.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/parseNextFontError.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/parseNextAppLoaderError.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/parseNextInvalidImportError.js","../node_modules/next/dist/compiled/devalue/package.json","../node_modules/next/dist/compiled/devalue/devalue.umd.js","../node_modules/next/dist/compiled/loader-utils3/package.json","../node_modules/next/dist/compiled/loader-utils3/index.js","../node_modules/next/dist/compiled/babel/parser.js","../node_modules/next/dist/compiled/babel/traverse.js","../node_modules/next/dist/compiled/babel/types.js","../node_modules/next/dist/compiled/postcss-scss/package.json","../node_modules/next/dist/compiled/postcss-scss/scss-syntax.js","../node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-no-ssr.js","../node_modules/next/dist/compiled/react-refresh/runtime.js","../node_modules/next/dist/client/normalize-locale-path.js","../node_modules/next/dist/build/webpack-build/impl.js","../node_modules/next/node_modules/postcss/lib/result.js","../node_modules/next/dist/compiled/react-refresh/package.json","../node_modules/next/dist/compiled/@vercel/nft/package.json","../node_modules/next/dist/compiled/@vercel/nft/index.js","../node_modules/next/dist/compiled/glob/package.json","../node_modules/next/dist/compiled/glob/glob.js","../node_modules/next/node_modules/postcss/lib/css-syntax-error.js","../node_modules/next/node_modules/postcss/lib/declaration.js","../node_modules/next/node_modules/postcss/lib/lazy-result.js","../node_modules/next/node_modules/postcss/lib/container.js","../node_modules/next/node_modules/postcss/lib/stringify.js","../node_modules/next/node_modules/postcss/lib/processor.js","../node_modules/next/node_modules/postcss/lib/fromJSON.js","../node_modules/next/node_modules/postcss/lib/comment.js","../node_modules/next/node_modules/postcss/lib/document.js","../node_modules/next/node_modules/postcss/lib/at-rule.js","../node_modules/next/node_modules/postcss/lib/warning.js","../node_modules/next/node_modules/postcss/lib/input.js","../node_modules/next/node_modules/postcss/lib/parse.js","../node_modules/next/node_modules/postcss/lib/rule.js","../node_modules/next/node_modules/postcss/lib/list.js","../node_modules/next/node_modules/postcss/lib/node.js","../node_modules/next/node_modules/postcss/lib/root.js","../node_modules/next/dist/build/webpack/config/blocks/images/messages.js","../node_modules/next/dist/build/webpack/config/helpers.js","../node_modules/next/dist/compiled/babel/generator.js","../node_modules/next/dist/compiled/babel/core-lib-normalize-file.js","../node_modules/next/dist/compiled/babel/core-lib-block-hoist-plugin.js","../node_modules/next/dist/compiled/babel/core-lib-normalize-opts.js","../node_modules/next/dist/compiled/babel/core-lib-plugin-pass.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/simpleWebpackError.js","../node_modules/next/dist/build/webpack/plugins/wellknown-errors-plugin/getModuleTrace.js","../node_modules/next/dist/build/babel/plugins/next-ssg-transform.js","../node_modules/next/dist/build/babel/plugins/next-font-unsupported.js","../node_modules/next/dist/build/babel/plugins/commonjs.js","../node_modules/next/dist/build/babel/plugins/next-page-disallow-re-export-all-exports.js","../node_modules/next/dist/build/babel/plugins/next-page-config.js","../node_modules/next/dist/compiled/react-refresh/cjs/react-refresh-runtime.production.min.js","../node_modules/next/dist/compiled/react-refresh/cjs/react-refresh-runtime.development.js","../node_modules/next/dist/build/compiler.js","../node_modules/next/dist/compiled/sass-loader/package.json","../node_modules/next/dist/compiled/babel/core-lib-config.js","../node_modules/next/dist/compiled/react-refresh/babel.js","../node_modules/next/dist/compiled/babel/plugin-transform-modules-commonjs.js","../node_modules/next/dist/compiled/babel/plugin-transform-define.js","../node_modules/next/node_modules/postcss/lib/terminal-highlight.js","../node_modules/next/node_modules/postcss/lib/map-generator.js","../node_modules/next/node_modules/postcss/lib/symbols.js","../node_modules/next/node_modules/postcss/lib/warn-once.js","../node_modules/next/node_modules/postcss/lib/no-work-result.js","../node_modules/next/node_modules/postcss/lib/stringifier.js","../node_modules/next/node_modules/postcss/lib/previous-map.js","../node_modules/next/node_modules/postcss/lib/parser.js","../node_modules/caniuse-lite/dist/unpacker/index.js","../node_modules/next/dist/compiled/lodash.curry/package.json","../node_modules/next/dist/compiled/lodash.curry/index.js","../node_modules/next/dist/compiled/@vercel/nft/LICENSE","../node_modules/next/dist/compiled/react-refresh/cjs/react-refresh-babel.production.min.js","../node_modules/next/dist/compiled/react-refresh/cjs/react-refresh-babel.development.js","../node_modules/next/node_modules/postcss/lib/tokenize.js","../node_modules/caniuse-lite/dist/unpacker/features.js","../node_modules/next/dist/compiled/postcss-plugin-stub-for-cssnano-simple/index.js","../node_modules/next/dist/compiled/postcss-value-parser/package.json","../node_modules/next/dist/compiled/postcss-value-parser/index.js","../node_modules/caniuse-lite/data/features.js","../node_modules/picocolors/package.json","../node_modules/picocolors/picocolors.js","../node_modules/source-map-js/package.json","../node_modules/source-map-js/source-map.js","../node_modules/caniuse-lite/data/features/aac.js","../node_modules/caniuse-lite/data/features/abortcontroller.js","../node_modules/caniuse-lite/data/features/ac3-ec3.js","../node_modules/caniuse-lite/data/features/accelerometer.js","../node_modules/caniuse-lite/data/features/ambient-light.js","../node_modules/caniuse-lite/data/features/addeventlistener.js","../node_modules/caniuse-lite/data/features/alternate-stylesheet.js","../node_modules/caniuse-lite/data/features/array-find-index.js","../node_modules/caniuse-lite/data/features/apng.js","../node_modules/caniuse-lite/data/features/array-includes.js","../node_modules/caniuse-lite/data/features/array-find.js","../node_modules/caniuse-lite/data/features/array-flat.js","../node_modules/caniuse-lite/data/features/arrow-functions.js","../node_modules/caniuse-lite/data/features/asmjs.js","../node_modules/caniuse-lite/data/features/async-clipboard.js","../node_modules/caniuse-lite/data/features/async-functions.js","../node_modules/caniuse-lite/data/features/atob-btoa.js","../node_modules/caniuse-lite/data/features/audio-api.js","../node_modules/caniuse-lite/data/features/audio.js","../node_modules/caniuse-lite/data/features/autofocus.js","../node_modules/caniuse-lite/data/features/audiotracks.js","../node_modules/caniuse-lite/data/features/auxclick.js","../node_modules/caniuse-lite/data/features/av1.js","../node_modules/caniuse-lite/data/features/avif.js","../node_modules/caniuse-lite/data/features/background-clip-text.js","../node_modules/caniuse-lite/data/features/background-img-opts.js","../node_modules/caniuse-lite/data/features/background-attachment.js","../node_modules/caniuse-lite/data/features/background-position-x-y.js","../node_modules/caniuse-lite/data/features/background-repeat-round-space.js","../node_modules/caniuse-lite/data/features/background-sync.js","../node_modules/caniuse-lite/data/features/battery-status.js","../node_modules/caniuse-lite/data/features/beacon.js","../node_modules/caniuse-lite/data/features/beforeafterprint.js","../node_modules/caniuse-lite/data/features/bigint.js","../node_modules/caniuse-lite/data/features/blobbuilder.js","../node_modules/caniuse-lite/data/features/border-image.js","../node_modules/caniuse-lite/data/features/bloburls.js","../node_modules/caniuse-lite/data/features/border-radius.js","../node_modules/caniuse-lite/data/features/brotli.js","../node_modules/caniuse-lite/data/features/broadcastchannel.js","../node_modules/caniuse-lite/data/features/calc.js","../node_modules/caniuse-lite/data/features/canvas-blending.js","../node_modules/caniuse-lite/data/features/canvas-text.js","../node_modules/caniuse-lite/data/features/canvas.js","../node_modules/caniuse-lite/data/features/ch-unit.js","../node_modules/caniuse-lite/data/features/chacha20-poly1305.js","../node_modules/caniuse-lite/data/features/channel-messaging.js","../node_modules/caniuse-lite/data/features/childnode-remove.js","../node_modules/caniuse-lite/data/features/classlist.js","../node_modules/caniuse-lite/data/features/client-hints-dpr-width-viewport.js","../node_modules/caniuse-lite/data/features/colr-v1.js","../node_modules/caniuse-lite/data/features/clipboard.js","../node_modules/caniuse-lite/data/features/colr.js","../node_modules/caniuse-lite/data/features/comparedocumentposition.js","../node_modules/caniuse-lite/data/features/console-time.js","../node_modules/caniuse-lite/data/features/console-basic.js","../node_modules/caniuse-lite/data/features/constraint-validation.js","../node_modules/caniuse-lite/data/features/const.js","../node_modules/caniuse-lite/data/features/contenteditable.js","../node_modules/caniuse-lite/data/features/contentsecuritypolicy.js","../node_modules/caniuse-lite/data/features/contentsecuritypolicy2.js","../node_modules/caniuse-lite/data/features/cookie-store-api.js","../node_modules/caniuse-lite/data/features/cors.js","../node_modules/caniuse-lite/data/features/createimagebitmap.js","../node_modules/caniuse-lite/data/features/credential-management.js","../node_modules/caniuse-lite/data/features/cryptography.js","../node_modules/caniuse-lite/data/features/css-animation.js","../node_modules/caniuse-lite/data/features/css-any-link.js","../node_modules/caniuse-lite/data/features/css-appearance.js","../node_modules/caniuse-lite/data/features/css-at-counter-style.js","../node_modules/caniuse-lite/data/features/css-autofill.js","../node_modules/caniuse-lite/data/features/css-backdrop-filter.js","../node_modules/caniuse-lite/data/features/css-background-offsets.js","../node_modules/caniuse-lite/data/features/css-backgroundblendmode.js","../node_modules/caniuse-lite/data/features/css-all.js","../node_modules/caniuse-lite/data/features/css-boxdecorationbreak.js","../node_modules/caniuse-lite/data/features/css-boxshadow.js","../node_modules/caniuse-lite/data/features/css-caret-color.js","../node_modules/caniuse-lite/data/features/css-canvas.js","../node_modules/caniuse-lite/data/features/css-cascade-scope.js","../node_modules/caniuse-lite/data/features/css-cascade-layers.js","../node_modules/caniuse-lite/data/features/css-case-insensitive.js","../node_modules/caniuse-lite/data/features/css-color-adjust.js","../node_modules/caniuse-lite/data/features/css-clip-path.js","../node_modules/caniuse-lite/data/features/css-color-function.js","../node_modules/caniuse-lite/data/features/css-conic-gradients.js","../node_modules/caniuse-lite/data/features/css-container-queries.js","../node_modules/caniuse-lite/data/features/css-container-queries-style.js","../node_modules/caniuse-lite/data/features/css-containment.js","../node_modules/caniuse-lite/data/features/css-container-query-units.js","../node_modules/caniuse-lite/data/features/css-counters.js","../node_modules/caniuse-lite/data/features/css-content-visibility.js","../node_modules/caniuse-lite/data/features/css-crisp-edges.js","../node_modules/caniuse-lite/data/features/css-cross-fade.js","../node_modules/caniuse-lite/data/features/css-default-pseudo.js","../node_modules/caniuse-lite/data/features/css-descendant-gtgt.js","../node_modules/caniuse-lite/data/features/css-dir-pseudo.js","../node_modules/caniuse-lite/data/features/css-deviceadaptation.js","../node_modules/caniuse-lite/data/features/css-display-contents.js","../node_modules/caniuse-lite/data/features/css-element-function.js","../node_modules/caniuse-lite/data/features/css-env-function.js","../node_modules/caniuse-lite/data/features/css-featurequeries.js","../node_modules/caniuse-lite/data/features/css-exclusions.js","../node_modules/caniuse-lite/data/features/css-file-selector-button.js","../node_modules/caniuse-lite/data/features/css-filter-function.js","../node_modules/caniuse-lite/data/features/css-filters.js","../node_modules/caniuse-lite/data/features/css-first-letter.js","../node_modules/caniuse-lite/data/features/css-first-line.js","../node_modules/caniuse-lite/data/features/css-fixed.js","../node_modules/caniuse-lite/data/features/css-focus-within.js","../node_modules/caniuse-lite/data/features/css-focus-visible.js","../node_modules/caniuse-lite/data/features/css-font-palette.js","../node_modules/caniuse-lite/data/features/css-font-rendering-controls.js","../node_modules/caniuse-lite/data/features/css-font-stretch.js","../node_modules/caniuse-lite/data/features/css-gencontent.js","../node_modules/caniuse-lite/data/features/css-gradients.js","../node_modules/caniuse-lite/data/features/css-grid-animation.js","../node_modules/caniuse-lite/data/features/css-grid.js","../node_modules/caniuse-lite/data/features/css-hanging-punctuation.js","../node_modules/caniuse-lite/data/features/css-has.js","../node_modules/caniuse-lite/data/features/css-hyphens.js","../node_modules/caniuse-lite/data/features/css-image-orientation.js","../node_modules/caniuse-lite/data/features/css-image-set.js","../node_modules/caniuse-lite/data/features/css-in-out-of-range.js","../node_modules/caniuse-lite/data/features/css-indeterminate-pseudo.js","../node_modules/caniuse-lite/data/features/css-initial-letter.js","../node_modules/caniuse-lite/data/features/css-initial-value.js","../node_modules/caniuse-lite/data/features/css-lch-lab.js","../node_modules/caniuse-lite/data/features/css-logical-props.js","../node_modules/caniuse-lite/data/features/css-line-clamp.js","../node_modules/caniuse-lite/data/features/css-marker-pseudo.js","../node_modules/caniuse-lite/data/features/css-letter-spacing.js","../node_modules/caniuse-lite/data/features/css-masks.js","../node_modules/caniuse-lite/data/features/css-matches-pseudo.js","../node_modules/caniuse-lite/data/features/css-math-functions.js","../node_modules/caniuse-lite/data/features/css-media-interaction.js","../node_modules/caniuse-lite/data/features/css-media-range-syntax.js","../node_modules/caniuse-lite/data/features/css-media-resolution.js","../node_modules/caniuse-lite/data/features/css-mediaqueries.js","../node_modules/caniuse-lite/data/features/css-media-scripting.js","../node_modules/caniuse-lite/data/features/css-mixblendmode.js","../node_modules/caniuse-lite/data/features/css-motion-paths.js","../node_modules/caniuse-lite/data/features/css-namespaces.js","../node_modules/caniuse-lite/data/features/css-nesting.js","../node_modules/caniuse-lite/data/features/css-nth-child-of.js","../node_modules/caniuse-lite/data/features/css-not-sel-list.js","../node_modules/caniuse-lite/data/features/css-opacity.js","../node_modules/caniuse-lite/data/features/css-optional-pseudo.js","../node_modules/caniuse-lite/data/features/css-overflow-anchor.js","../node_modules/caniuse-lite/data/features/css-overflow-overlay.js","../node_modules/caniuse-lite/data/features/css-overflow.js","../node_modules/caniuse-lite/data/features/css-overscroll-behavior.js","../node_modules/caniuse-lite/data/features/css-page-break.js","../node_modules/caniuse-lite/data/features/css-paged-media.js","../node_modules/caniuse-lite/data/features/css-paint-api.js","../node_modules/caniuse-lite/data/features/css-placeholder-shown.js","../node_modules/caniuse-lite/data/features/css-placeholder.js","../node_modules/caniuse-lite/data/features/css-print-color-adjust.js","../node_modules/caniuse-lite/data/features/css-rebeccapurple.js","../node_modules/caniuse-lite/data/features/css-read-only-write.js","../node_modules/caniuse-lite/data/features/css-reflections.js","../node_modules/caniuse-lite/data/features/css-regions.js","../node_modules/caniuse-lite/data/features/css-relative-colors.js","../node_modules/caniuse-lite/data/features/css-repeating-gradients.js","../node_modules/caniuse-lite/data/features/css-resize.js","../node_modules/caniuse-lite/data/features/css-revert-value.js","../node_modules/caniuse-lite/data/features/css-rrggbbaa.js","../node_modules/caniuse-lite/data/features/css-scroll-behavior.js","../node_modules/caniuse-lite/data/features/css-scroll-timeline.js","../node_modules/caniuse-lite/data/features/css-scrollbar.js","../node_modules/caniuse-lite/data/features/css-sel2.js","../node_modules/caniuse-lite/data/features/css-sel3.js","../node_modules/caniuse-lite/data/features/css-shapes.js","../node_modules/caniuse-lite/data/features/css-selection.js","../node_modules/caniuse-lite/data/features/css-snappoints.js","../node_modules/caniuse-lite/data/features/css-sticky.js","../node_modules/caniuse-lite/data/features/css-subgrid.js","../node_modules/caniuse-lite/data/features/css-supports-api.js","../node_modules/caniuse-lite/data/features/css-table.js","../node_modules/caniuse-lite/data/features/css-text-align-last.js","../node_modules/caniuse-lite/data/features/css-text-box-trim.js","../node_modules/caniuse-lite/data/features/css-text-justify.js","../node_modules/caniuse-lite/data/features/css-text-orientation.js","../node_modules/caniuse-lite/data/features/css-text-spacing.js","../node_modules/caniuse-lite/data/features/css-text-wrap-balance.js","../node_modules/caniuse-lite/data/features/css-textshadow.js","../node_modules/caniuse-lite/data/features/css-touch-action.js","../node_modules/caniuse-lite/data/features/css-transitions.js","../node_modules/caniuse-lite/data/features/css-unicode-bidi.js","../node_modules/caniuse-lite/data/features/css-unset-value.js","../node_modules/caniuse-lite/data/features/css-variables.js","../node_modules/caniuse-lite/data/features/css-when-else.js","../node_modules/caniuse-lite/data/features/css-widows-orphans.js","../node_modules/caniuse-lite/data/features/css-width-stretch.js","../node_modules/caniuse-lite/data/features/css-writing-mode.js","../node_modules/caniuse-lite/data/features/css-zoom.js","../node_modules/caniuse-lite/data/features/css3-attr.js","../node_modules/caniuse-lite/data/features/css3-colors.js","../node_modules/caniuse-lite/data/features/css3-cursors-grab.js","../node_modules/caniuse-lite/data/features/css3-cursors-newer.js","../node_modules/caniuse-lite/data/features/css3-cursors.js","../node_modules/caniuse-lite/data/features/css3-tabsize.js","../node_modules/caniuse-lite/data/features/currentcolor.js","../node_modules/caniuse-lite/data/features/custom-elements.js","../node_modules/caniuse-lite/data/features/css3-boxsizing.js","../node_modules/caniuse-lite/data/features/custom-elementsv1.js","../node_modules/caniuse-lite/data/features/datalist.js","../node_modules/caniuse-lite/data/features/customevent.js","../node_modules/caniuse-lite/data/features/dataset.js","../node_modules/caniuse-lite/data/features/datauri.js","../node_modules/caniuse-lite/data/features/date-tolocaledatestring.js","../node_modules/caniuse-lite/data/features/declarative-shadow-dom.js","../node_modules/caniuse-lite/data/features/decorators.js","../node_modules/caniuse-lite/data/features/details.js","../node_modules/caniuse-lite/data/features/css-text-indent.js","../node_modules/caniuse-lite/data/features/deviceorientation.js","../node_modules/caniuse-lite/data/features/devicepixelratio.js","../node_modules/caniuse-lite/data/features/dialog.js","../node_modules/caniuse-lite/data/features/dispatchevent.js","../node_modules/caniuse-lite/data/features/dnssec.js","../node_modules/caniuse-lite/data/features/do-not-track.js","../node_modules/caniuse-lite/data/features/document-currentscript.js","../node_modules/caniuse-lite/data/features/document-evaluate-xpath.js","../node_modules/caniuse-lite/data/features/document-policy.js","../node_modules/caniuse-lite/data/features/document-execcommand.js","../node_modules/caniuse-lite/data/features/document-scrollingelement.js","../node_modules/caniuse-lite/data/features/dom-manip-convenience.js","../node_modules/caniuse-lite/data/features/documenthead.js","../node_modules/caniuse-lite/data/features/dom-range.js","../node_modules/caniuse-lite/data/features/domcontentloaded.js","../node_modules/caniuse-lite/data/features/dommatrix.js","../node_modules/caniuse-lite/data/features/dragndrop.js","../node_modules/caniuse-lite/data/features/download.js","../node_modules/caniuse-lite/data/features/element-closest.js","../node_modules/caniuse-lite/data/features/element-scroll-methods.js","../node_modules/caniuse-lite/data/features/element-from-point.js","../node_modules/caniuse-lite/data/features/eot.js","../node_modules/caniuse-lite/data/features/eme.js","../node_modules/caniuse-lite/data/features/es5.js","../node_modules/caniuse-lite/data/features/es6-class.js","../node_modules/caniuse-lite/data/features/es6-module-dynamic-import.js","../node_modules/caniuse-lite/data/features/es6-generators.js","../node_modules/caniuse-lite/data/features/es6-number.js","../node_modules/caniuse-lite/data/features/es6-module.js","../node_modules/caniuse-lite/data/features/es6-string-includes.js","../node_modules/caniuse-lite/data/features/es6.js","../node_modules/caniuse-lite/data/features/eventsource.js","../node_modules/caniuse-lite/data/features/feature-policy.js","../node_modules/caniuse-lite/data/features/fetch.js","../node_modules/caniuse-lite/data/features/extended-system-fonts.js","../node_modules/caniuse-lite/data/features/fieldset-disabled.js","../node_modules/caniuse-lite/data/features/fileapi.js","../node_modules/caniuse-lite/data/features/filereader.js","../node_modules/caniuse-lite/data/features/filereadersync.js","../node_modules/caniuse-lite/data/features/filesystem.js","../node_modules/caniuse-lite/data/features/flac.js","../node_modules/caniuse-lite/data/features/flexbox-gap.js","../node_modules/caniuse-lite/data/features/flexbox.js","../node_modules/caniuse-lite/data/features/focusin-focusout-events.js","../node_modules/caniuse-lite/data/features/flow-root.js","../node_modules/caniuse-lite/data/features/font-family-system-ui.js","../node_modules/caniuse-lite/data/features/font-feature.js","../node_modules/caniuse-lite/data/features/font-kerning.js","../node_modules/caniuse-lite/data/features/font-loading.js","../node_modules/caniuse-lite/data/features/font-smooth.js","../node_modules/caniuse-lite/data/features/font-size-adjust.js","../node_modules/caniuse-lite/data/features/font-unicode-range.js","../node_modules/caniuse-lite/data/features/font-variant-alternates.js","../node_modules/caniuse-lite/data/features/font-variant-numeric.js","../node_modules/caniuse-lite/data/features/form-attribute.js","../node_modules/caniuse-lite/data/features/fontface.js","../node_modules/caniuse-lite/data/features/form-submit-attributes.js","../node_modules/caniuse-lite/data/features/form-validation.js","../node_modules/caniuse-lite/data/features/forms.js","../node_modules/caniuse-lite/data/features/fullscreen.js","../node_modules/caniuse-lite/data/features/gamepad.js","../node_modules/caniuse-lite/data/features/geolocation.js","../node_modules/caniuse-lite/data/features/getboundingclientrect.js","../node_modules/caniuse-lite/data/features/getelementsbyclassname.js","../node_modules/caniuse-lite/data/features/getcomputedstyle.js","../node_modules/caniuse-lite/data/features/getrandomvalues.js","../node_modules/caniuse-lite/data/features/gyroscope.js","../node_modules/caniuse-lite/data/features/hashchange.js","../node_modules/caniuse-lite/data/features/hardwareconcurrency.js","../node_modules/caniuse-lite/data/features/heif.js","../node_modules/caniuse-lite/data/features/hevc.js","../node_modules/caniuse-lite/data/features/hidden.js","../node_modules/caniuse-lite/data/features/high-resolution-time.js","../node_modules/caniuse-lite/data/features/history.js","../node_modules/caniuse-lite/data/features/html-media-capture.js","../node_modules/caniuse-lite/data/features/http-live-streaming.js","../node_modules/caniuse-lite/data/features/html5semantic.js","../node_modules/caniuse-lite/data/features/http2.js","../node_modules/caniuse-lite/data/features/iframe-sandbox.js","../node_modules/caniuse-lite/data/features/http3.js","../node_modules/caniuse-lite/data/features/iframe-seamless.js","../node_modules/caniuse-lite/data/features/iframe-srcdoc.js","../node_modules/caniuse-lite/data/features/imagecapture.js","../node_modules/caniuse-lite/data/features/ime.js","../node_modules/caniuse-lite/data/features/img-naturalwidth-naturalheight.js","../node_modules/caniuse-lite/data/features/import-maps.js","../node_modules/caniuse-lite/data/features/imports.js","../node_modules/caniuse-lite/data/features/indeterminate-checkbox.js","../node_modules/caniuse-lite/data/features/indexeddb.js","../node_modules/caniuse-lite/data/features/indexeddb2.js","../node_modules/caniuse-lite/data/features/innertext.js","../node_modules/caniuse-lite/data/features/inline-block.js","../node_modules/caniuse-lite/data/features/input-autocomplete-onoff.js","../node_modules/caniuse-lite/data/features/input-color.js","../node_modules/caniuse-lite/data/features/input-datetime.js","../node_modules/caniuse-lite/data/features/input-email-tel-url.js","../node_modules/caniuse-lite/data/features/input-file-accept.js","../node_modules/caniuse-lite/data/features/input-event.js","../node_modules/caniuse-lite/data/features/input-file-directory.js","../node_modules/caniuse-lite/data/features/input-file-multiple.js","../node_modules/caniuse-lite/data/features/input-inputmode.js","../node_modules/caniuse-lite/data/features/input-number.js","../node_modules/caniuse-lite/data/features/input-minlength.js","../node_modules/caniuse-lite/data/features/input-pattern.js","../node_modules/caniuse-lite/data/features/input-placeholder.js","../node_modules/caniuse-lite/data/features/input-search.js","../node_modules/caniuse-lite/data/features/input-range.js","../node_modules/caniuse-lite/data/features/input-selection.js","../node_modules/caniuse-lite/data/features/insert-adjacent.js","../node_modules/caniuse-lite/data/features/insertadjacenthtml.js","../node_modules/caniuse-lite/data/features/internationalization.js","../node_modules/caniuse-lite/data/features/intersectionobserver-v2.js","../node_modules/caniuse-lite/data/features/intl-pluralrules.js","../node_modules/caniuse-lite/data/features/intrinsic-width.js","../node_modules/caniuse-lite/data/features/intersectionobserver.js","../node_modules/caniuse-lite/data/features/jpeg2000.js","../node_modules/caniuse-lite/data/features/jpegxl.js","../node_modules/caniuse-lite/data/features/jpegxr.js","../node_modules/caniuse-lite/data/features/js-regexp-lookbehind.js","../node_modules/caniuse-lite/data/features/json.js","../node_modules/caniuse-lite/data/features/kerning-pairs-ligatures.js","../node_modules/caniuse-lite/data/features/keyboardevent-charcode.js","../node_modules/caniuse-lite/data/features/justify-content-space-evenly.js","../node_modules/caniuse-lite/data/features/keyboardevent-code.js","../node_modules/caniuse-lite/data/features/keyboardevent-getmodifierstate.js","../node_modules/caniuse-lite/data/features/keyboardevent-key.js","../node_modules/caniuse-lite/data/features/keyboardevent-location.js","../node_modules/caniuse-lite/data/features/keyboardevent-which.js","../node_modules/caniuse-lite/data/features/lazyload.js","../node_modules/caniuse-lite/data/features/let.js","../node_modules/caniuse-lite/data/features/link-icon-png.js","../node_modules/caniuse-lite/data/features/link-icon-svg.js","../node_modules/caniuse-lite/data/features/link-rel-dns-prefetch.js","../node_modules/caniuse-lite/data/features/link-rel-modulepreload.js","../node_modules/caniuse-lite/data/features/link-rel-preconnect.js","../node_modules/caniuse-lite/data/features/link-rel-preload.js","../node_modules/caniuse-lite/data/features/link-rel-prefetch.js","../node_modules/caniuse-lite/data/features/link-rel-prerender.js","../node_modules/caniuse-lite/data/features/loading-lazy-attr.js","../node_modules/caniuse-lite/data/features/localecompare.js","../node_modules/caniuse-lite/data/features/magnetometer.js","../node_modules/caniuse-lite/data/features/matchesselector.js","../node_modules/caniuse-lite/data/features/matchmedia.js","../node_modules/caniuse-lite/data/features/mathml.js","../node_modules/caniuse-lite/data/features/mdn-css-backdrop-pseudo-element.js","../node_modules/caniuse-lite/data/features/mdn-css-unicode-bidi-isolate-override.js","../node_modules/caniuse-lite/data/features/maxlength.js","../node_modules/caniuse-lite/data/features/mdn-css-unicode-bidi-isolate.js","../node_modules/caniuse-lite/data/features/mdn-css-unicode-bidi-plaintext.js","../node_modules/caniuse-lite/data/features/mdn-text-decoration-color.js","../node_modules/caniuse-lite/data/features/mdn-text-decoration-line.js","../node_modules/caniuse-lite/data/features/mdn-text-decoration-shorthand.js","../node_modules/caniuse-lite/data/features/mdn-text-decoration-style.js","../node_modules/caniuse-lite/data/features/mediacapture-fromelement.js","../node_modules/caniuse-lite/data/features/media-fragments.js","../node_modules/caniuse-lite/data/features/mediarecorder.js","../node_modules/caniuse-lite/data/features/menu.js","../node_modules/caniuse-lite/data/features/mediasource.js","../node_modules/caniuse-lite/data/features/meta-theme-color.js","../node_modules/caniuse-lite/data/features/meter.js","../node_modules/caniuse-lite/data/features/midi.js","../node_modules/caniuse-lite/data/features/minmaxwh.js","../node_modules/caniuse-lite/data/features/mpeg-dash.js","../node_modules/caniuse-lite/data/features/mp3.js","../node_modules/caniuse-lite/data/features/mpeg4.js","../node_modules/caniuse-lite/data/features/multibackgrounds.js","../node_modules/caniuse-lite/data/features/multicolumn.js","../node_modules/caniuse-lite/data/features/mutation-events.js","../node_modules/caniuse-lite/data/features/mutationobserver.js","../node_modules/caniuse-lite/data/features/namevalue-storage.js","../node_modules/caniuse-lite/data/features/native-filesystem-api.js","../node_modules/caniuse-lite/data/features/nav-timing.js","../node_modules/caniuse-lite/data/features/netinfo.js","../node_modules/caniuse-lite/data/features/notifications.js","../node_modules/caniuse-lite/data/features/object-entries.js","../node_modules/caniuse-lite/data/features/object-fit.js","../node_modules/caniuse-lite/data/features/object-observe.js","../node_modules/caniuse-lite/data/features/object-values.js","../node_modules/caniuse-lite/data/features/objectrtc.js","../node_modules/caniuse-lite/data/features/offline-apps.js","../node_modules/caniuse-lite/data/features/offscreencanvas.js","../node_modules/caniuse-lite/data/features/ogg-vorbis.js","../node_modules/caniuse-lite/data/features/ogv.js","../node_modules/caniuse-lite/data/features/ol-reversed.js","../node_modules/caniuse-lite/data/features/once-event-listener.js","../node_modules/caniuse-lite/data/features/online-status.js","../node_modules/caniuse-lite/data/features/opus.js","../node_modules/caniuse-lite/data/features/orientation-sensor.js","../node_modules/caniuse-lite/data/features/outline.js","../node_modules/caniuse-lite/data/features/pad-start-end.js","../node_modules/caniuse-lite/data/features/page-transition-events.js","../node_modules/caniuse-lite/data/features/pagevisibility.js","../node_modules/caniuse-lite/data/features/passive-event-listener.js","../node_modules/caniuse-lite/data/features/passkeys.js","../node_modules/caniuse-lite/data/features/passwordrules.js","../node_modules/caniuse-lite/data/features/path2d.js","../node_modules/caniuse-lite/data/features/payment-request.js","../node_modules/caniuse-lite/data/features/pdf-viewer.js","../node_modules/caniuse-lite/data/features/permissions-api.js","../node_modules/caniuse-lite/data/features/permissions-policy.js","../node_modules/caniuse-lite/data/features/picture-in-picture.js","../node_modules/caniuse-lite/data/features/picture.js","../node_modules/caniuse-lite/data/features/ping.js","../node_modules/caniuse-lite/data/features/png-alpha.js","../node_modules/caniuse-lite/data/features/pointer.js","../node_modules/caniuse-lite/data/features/pointer-events.js","../node_modules/caniuse-lite/data/features/pointerlock.js","../node_modules/caniuse-lite/data/features/portals.js","../node_modules/caniuse-lite/data/features/prefers-color-scheme.js","../node_modules/caniuse-lite/data/features/prefers-reduced-motion.js","../node_modules/caniuse-lite/data/features/progress.js","../node_modules/caniuse-lite/data/features/promise-finally.js","../node_modules/caniuse-lite/data/features/promises.js","../node_modules/caniuse-lite/data/features/proximity.js","../node_modules/caniuse-lite/data/features/proxy.js","../node_modules/caniuse-lite/data/features/publickeypinning.js","../node_modules/caniuse-lite/data/features/push-api.js","../node_modules/caniuse-lite/data/features/queryselector.js","../node_modules/caniuse-lite/data/features/readonly-attr.js","../node_modules/caniuse-lite/data/features/referrer-policy.js","../node_modules/caniuse-lite/data/features/registerprotocolhandler.js","../node_modules/caniuse-lite/data/features/rel-noopener.js","../node_modules/caniuse-lite/data/features/rel-noreferrer.js","../node_modules/caniuse-lite/data/features/rellist.js","../node_modules/caniuse-lite/data/features/rem.js","../node_modules/caniuse-lite/data/features/requestanimationframe.js","../node_modules/caniuse-lite/data/features/requestidlecallback.js","../node_modules/caniuse-lite/data/features/resource-timing.js","../node_modules/caniuse-lite/data/features/resizeobserver.js","../node_modules/caniuse-lite/data/features/ruby.js","../node_modules/caniuse-lite/data/features/rtcpeerconnection.js","../node_modules/caniuse-lite/data/features/rest-parameters.js","../node_modules/caniuse-lite/data/features/same-site-cookie-attribute.js","../node_modules/caniuse-lite/data/features/run-in.js","../node_modules/caniuse-lite/data/features/screen-orientation.js","../node_modules/caniuse-lite/data/features/script-defer.js","../node_modules/caniuse-lite/data/features/script-async.js","../node_modules/caniuse-lite/data/features/scrollintoviewifneeded.js","../node_modules/caniuse-lite/data/features/scrollintoview.js","../node_modules/caniuse-lite/data/features/sdch.js","../node_modules/caniuse-lite/data/features/selection-api.js","../node_modules/caniuse-lite/data/features/server-timing.js","../node_modules/caniuse-lite/data/features/serviceworkers.js","../node_modules/caniuse-lite/data/features/setimmediate.js","../node_modules/caniuse-lite/data/features/shadowdom.js","../node_modules/caniuse-lite/data/features/shadowdomv1.js","../node_modules/caniuse-lite/data/features/sharedworkers.js","../node_modules/caniuse-lite/data/features/sharedarraybuffer.js","../node_modules/caniuse-lite/data/features/sni.js","../node_modules/caniuse-lite/data/features/spdy.js","../node_modules/caniuse-lite/data/features/speech-recognition.js","../node_modules/caniuse-lite/data/features/speech-synthesis.js","../node_modules/caniuse-lite/data/features/spellcheck-attribute.js","../node_modules/caniuse-lite/data/features/srcset.js","../node_modules/caniuse-lite/data/features/sql-storage.js","../node_modules/caniuse-lite/data/features/stream.js","../node_modules/caniuse-lite/data/features/streams.js","../node_modules/caniuse-lite/data/features/stricttransportsecurity.js","../node_modules/caniuse-lite/data/features/style-scoped.js","../node_modules/caniuse-lite/data/features/subresource-bundling.js","../node_modules/caniuse-lite/data/features/subresource-integrity.js","../node_modules/caniuse-lite/data/features/svg-css.js","../node_modules/caniuse-lite/data/features/svg-filters.js","../node_modules/caniuse-lite/data/features/svg-html.js","../node_modules/caniuse-lite/data/features/svg-fragment.js","../node_modules/caniuse-lite/data/features/svg-html5.js","../node_modules/caniuse-lite/data/features/svg-img.js","../node_modules/caniuse-lite/data/features/svg-fonts.js","../node_modules/caniuse-lite/data/features/svg.js","../node_modules/caniuse-lite/data/features/svg-smil.js","../node_modules/caniuse-lite/data/features/sxg.js","../node_modules/caniuse-lite/data/features/tabindex-attr.js","../node_modules/caniuse-lite/data/features/template-literals.js","../node_modules/caniuse-lite/data/features/template.js","../node_modules/caniuse-lite/data/features/testfeat.js","../node_modules/caniuse-lite/data/features/temporal.js","../node_modules/caniuse-lite/data/features/text-decoration.js","../node_modules/caniuse-lite/data/features/text-emphasis.js","../node_modules/caniuse-lite/data/features/text-overflow.js","../node_modules/caniuse-lite/data/features/text-size-adjust.js","../node_modules/caniuse-lite/data/features/text-stroke.js","../node_modules/caniuse-lite/data/features/textcontent.js","../node_modules/caniuse-lite/data/features/tls1-1.js","../node_modules/caniuse-lite/data/features/textencoder.js","../node_modules/caniuse-lite/data/features/tls1-2.js","../node_modules/caniuse-lite/data/features/tls1-3.js","../node_modules/caniuse-lite/data/features/transforms2d.js","../node_modules/caniuse-lite/data/features/touch.js","../node_modules/caniuse-lite/data/features/transforms3d.js","../node_modules/caniuse-lite/data/features/trusted-types.js","../node_modules/caniuse-lite/data/features/ttf.js","../node_modules/caniuse-lite/data/features/typedarrays.js","../node_modules/caniuse-lite/data/features/u2f.js","../node_modules/caniuse-lite/data/features/unhandledrejection.js","../node_modules/caniuse-lite/data/features/upgradeinsecurerequests.js","../node_modules/caniuse-lite/data/features/url-scroll-to-text-fragment.js","../node_modules/caniuse-lite/data/features/url.js","../node_modules/caniuse-lite/data/features/urlsearchparams.js","../node_modules/caniuse-lite/data/features/use-strict.js","../node_modules/caniuse-lite/data/features/user-select-none.js","../node_modules/caniuse-lite/data/features/user-timing.js","../node_modules/caniuse-lite/data/features/variable-fonts.js","../node_modules/caniuse-lite/data/features/vector-effect.js","../node_modules/caniuse-lite/data/features/vibration.js","../node_modules/caniuse-lite/data/features/video.js","../node_modules/caniuse-lite/data/features/videotracks.js","../node_modules/caniuse-lite/data/features/view-transitions.js","../node_modules/caniuse-lite/data/features/viewport-unit-variants.js","../node_modules/caniuse-lite/data/features/viewport-units.js","../node_modules/caniuse-lite/data/features/wai-aria.js","../node_modules/caniuse-lite/data/features/wake-lock.js","../node_modules/caniuse-lite/data/features/wasm.js","../node_modules/caniuse-lite/data/features/wav.js","../node_modules/caniuse-lite/data/features/wbr-element.js","../node_modules/caniuse-lite/data/features/web-animation.js","../node_modules/caniuse-lite/data/features/web-app-manifest.js","../node_modules/caniuse-lite/data/features/web-bluetooth.js","../node_modules/caniuse-lite/data/features/web-serial.js","../node_modules/caniuse-lite/data/features/web-share.js","../node_modules/caniuse-lite/data/features/webcodecs.js","../node_modules/caniuse-lite/data/features/webauthn.js","../node_modules/caniuse-lite/data/features/webgl.js","../node_modules/caniuse-lite/data/features/webgl2.js","../node_modules/caniuse-lite/data/features/webgpu.js","../node_modules/caniuse-lite/data/features/webhid.js","../node_modules/caniuse-lite/data/features/webkit-user-drag.js","../node_modules/caniuse-lite/data/features/webnfc.js","../node_modules/caniuse-lite/data/features/webm.js","../node_modules/caniuse-lite/data/features/webp.js","../node_modules/caniuse-lite/data/features/websockets.js","../node_modules/caniuse-lite/data/features/webtransport.js","../node_modules/caniuse-lite/data/features/webusb.js","../node_modules/caniuse-lite/data/features/webvr.js","../node_modules/caniuse-lite/data/features/webvtt.js","../node_modules/caniuse-lite/data/features/webworkers.js","../node_modules/caniuse-lite/data/features/webxr.js","../node_modules/caniuse-lite/data/features/will-change.js","../node_modules/caniuse-lite/data/features/woff.js","../node_modules/caniuse-lite/data/features/woff2.js","../node_modules/caniuse-lite/data/features/word-break.js","../node_modules/caniuse-lite/data/features/wordwrap.js","../node_modules/caniuse-lite/data/features/x-doc-messaging.js","../node_modules/caniuse-lite/data/features/x-frame-options.js","../node_modules/caniuse-lite/data/features/xhr2.js","../node_modules/caniuse-lite/data/features/xhtml.js","../node_modules/caniuse-lite/data/features/xhtmlsmil.js","../node_modules/caniuse-lite/data/features/xml-serializer.js","../node_modules/caniuse-lite/data/features/zstd.js","../node_modules/nanoid/non-secure/package.json","../node_modules/next/dist/compiled/acorn/package.json","../node_modules/next/dist/compiled/acorn/acorn.js","../node_modules/source-map-js/lib/source-map-generator.js","../node_modules/source-map-js/lib/source-map-consumer.js","../node_modules/source-map-js/lib/source-node.js","../node_modules/nanoid/package.json","../node_modules/nanoid/non-secure/index.cjs","../node_modules/source-map-js/lib/base64-vlq.js","../node_modules/source-map-js/lib/util.js","../node_modules/source-map-js/lib/mapping-list.js","../node_modules/source-map-js/lib/array-set.js","../node_modules/source-map-js/lib/binary-search.js","../node_modules/source-map-js/lib/quick-sort.js","../node_modules/source-map-js/lib/base64.js","../node_modules/next/font/google/target.css","../node_modules/next/dist/compiled/@next/font/google/loader.js","../node_modules/next/dist/compiled/@next/font/local/loader.js","../node_modules/next/dist/compiled/sass-loader/cjs.js","../node_modules/next/dist/compiled/@next/font/package.json","../node_modules/next/dist/build/webpack/config/blocks/css/messages.js","../node_modules/next/dist/build/webpack/config/blocks/css/loaders/next-font.js","../node_modules/next/dist/build/webpack/config/blocks/css/plugins.js","../node_modules/next/dist/build/webpack/loaders/next-flight-css-loader.js","../node_modules/next/dist/build/webpack/plugins/mini-css-extract-plugin.js","../node_modules/next/dist/build/webpack/loaders/resolve-url-loader/index.js","../node_modules/next/dist/build/webpack/config/blocks/css/loaders/index.js","../node_modules/next/dist/build/webpack/config/blocks/css/loaders/client.js","../node_modules/next/dist/build/webpack/config/blocks/css/loaders/file-resolve.js","../node_modules/next/dist/compiled/@next/font/dist/google/loader.js","../node_modules/next/dist/build/webpack/loaders/resolve-url-loader/lib/join-function.js","../node_modules/next/dist/build/webpack/loaders/resolve-url-loader/lib/value-processor.js","../node_modules/next/dist/build/webpack/loaders/resolve-url-loader/lib/postcss.js","../node_modules/next/dist/build/webpack/config/blocks/css/loaders/global.js","../node_modules/next/dist/build/webpack/config/blocks/css/loaders/modules.js","../node_modules/next/dist/compiled/@next/font/dist/local/loader.js","../node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js","../node_modules/next/dist/compiled/ignore-loader/package.json","../node_modules/next/dist/compiled/ignore-loader/index.js","../node_modules/next/dist/compiled/@next/font/dist/google/validate-google-font-function-call.js","../node_modules/next/dist/compiled/@next/font/dist/google/get-font-axes.js","../node_modules/next/dist/compiled/@next/font/dist/google/get-google-fonts-url.js","../node_modules/next/dist/compiled/@next/font/dist/next-font-error.js","../node_modules/next/dist/compiled/@next/font/dist/google/find-font-files-in-css.js","../node_modules/next/dist/compiled/@next/font/dist/google/get-fallback-font-override-metrics.js","../node_modules/next/dist/compiled/@next/font/dist/google/fetch-css-from-google-fonts.js","../node_modules/next/dist/compiled/@next/font/dist/google/fetch-font-file.js","../node_modules/next/dist/build/webpack/loaders/resolve-url-loader/lib/file-protocol.js","../node_modules/next/dist/build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.js","../node_modules/next/dist/compiled/@next/font/dist/local/get-fallback-metrics-from-font-file.js","../node_modules/next/dist/compiled/@next/font/dist/local/pick-font-file-for-fallback-generation.js","../node_modules/next/dist/compiled/@next/font/dist/local/validate-local-font-function-call.js","../node_modules/next/dist/compiled/postcss-flexbugs-fixes/package.json","../node_modules/next/dist/compiled/postcss-flexbugs-fixes/index.js","../node_modules/next/dist/compiled/mini-css-extract-plugin/package.json","../node_modules/next/dist/compiled/mini-css-extract-plugin/cjs.js","../node_modules/sass/package.json","../node_modules/next/dist/build/webpack/loaders/css-loader/src/CssSyntaxError.js","../node_modules/next/dist/build/webpack/loaders/postcss-loader/src/Warning.js","../node_modules/next/dist/build/webpack/loaders/css-loader/src/utils.js","../node_modules/sass/sass.node.js","../node_modules/next/dist/build/webpack/loaders/css-loader/src/runtime/api.js","../node_modules/next/dist/compiled/@next/font/dist/constants.js","../node_modules/next/dist/compiled/@next/font/dist/format-available-values.js","../node_modules/next/dist/compiled/@next/font/dist/google/google-fonts-metadata.js","../node_modules/next/dist/compiled/@next/font/dist/google/get-proxy-agent.js","../node_modules/next/dist/compiled/neo-async/package.json","../node_modules/next/dist/compiled/neo-async/async.js","../node_modules/next/dist/compiled/source-map/package.json","../node_modules/next/dist/compiled/source-map/source-map.js","../node_modules/next/dist/lib/find-config.js","../node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js","../node_modules/next/dist/compiled/@next/font/dist/fontkit/index.js","../node_modules/next/dist/build/webpack/loaders/css-loader/src/plugins/index.js","../node_modules/next/dist/compiled/mini-css-extract-plugin/index.js","../node_modules/next/dist/compiled/@next/font/dist/google/font-data.json","../node_modules/sass/sass.dart.js","../node_modules/next/dist/build/webpack/loaders/css-loader/src/camelcase.js","../node_modules/next/dist/build/webpack/loaders/postcss-loader/src/Error.js","../node_modules/next/dist/build/webpack/loaders/postcss-loader/src/utils.js","../node_modules/next/dist/compiled/loader-utils2/package.json","../node_modules/next/dist/compiled/loader-utils2/index.js","../node_modules/next/dist/build/webpack/loaders/css-loader/src/plugins/postcss-icss-parser.js","../node_modules/next/dist/build/webpack/loaders/css-loader/src/plugins/postcss-import-parser.js","../node_modules/next/dist/build/webpack/loaders/css-loader/src/plugins/postcss-url-parser.js","../node_modules/next/dist/compiled/node-fetch/package.json","../node_modules/next/dist/compiled/node-fetch/index.js","../node_modules/next/dist/compiled/postcss-preset-env/package.json","../node_modules/next/dist/compiled/postcss-preset-env/index.cjs","../node_modules/immutable/package.json","../node_modules/immutable/dist/immutable.js","../node_modules/next/dist/build/webpack/loaders/css-loader/src/runtime/getUrl.js","../node_modules/next/dist/compiled/https-proxy-agent/package.json","../node_modules/next/dist/compiled/https-proxy-agent/index.js","../node_modules/next/dist/compiled/http-proxy-agent/package.json","../node_modules/next/dist/compiled/http-proxy-agent/index.js","../node_modules/next/dist/compiled/postcss-modules-values/package.json","../node_modules/next/dist/compiled/postcss-modules-values/index.js","../node_modules/next/dist/compiled/postcss-modules-local-by-default/package.json","../node_modules/next/dist/compiled/postcss-modules-local-by-default/index.js","../node_modules/next/dist/compiled/postcss-modules-scope/package.json","../node_modules/next/dist/compiled/postcss-modules-scope/index.js","../node_modules/next/dist/compiled/postcss-modules-extract-imports/package.json","../node_modules/next/dist/compiled/postcss-modules-extract-imports/index.js","../node_modules/next/dist/compiled/schema-utils3/package.json","../node_modules/next/dist/compiled/schema-utils3/index.js","../node_modules/next/dist/compiled/icss-utils/package.json","../node_modules/next/dist/compiled/icss-utils/index.js"]} \ No newline at end of file +{"version":1,"files":["../node_modules/styled-jsx/index.js","../node_modules/styled-jsx/package.json","../node_modules/styled-jsx/dist/index/index.js","../node_modules/react/package.json","../node_modules/react/index.js","../node_modules/client-only/package.json","../node_modules/react/cjs/react.production.min.js","../node_modules/client-only/index.js","../node_modules/styled-jsx/style.js","../node_modules/next/dist/server/next-server.js","../node_modules/next/package.json","../node_modules/next/dist/server/base-server.js","../node_modules/next/dist/server/node-environment.js","../node_modules/next/dist/server/require-hook.js","../node_modules/next/dist/server/node-polyfill-crypto.js","../node_modules/next/dist/server/request-meta.js","../node_modules/next/dist/lib/find-pages-dir.js","../node_modules/next/dist/server/send-payload.js","../node_modules/next/dist/server/require.js","../node_modules/next/dist/lib/is-error.js","../node_modules/next/dist/server/load-components.js","../node_modules/next/dist/lib/constants.js","../node_modules/next/dist/server/body-streams.js","../node_modules/next/dist/server/setup-http-agent-env.js","../node_modules/next/dist/server/pipe-readable.js","../node_modules/next/dist/server/load-manifest.js","../node_modules/next/dist/lib/format-server-error.js","../node_modules/next/dist/server/image-optimizer.js","../node_modules/next/dist/server/serve-static.js","../node_modules/next/dist/lib/picocolors.js","../node_modules/next/dist/shared/lib/utils.js","../node_modules/next/dist/shared/lib/constants.js","../node_modules/next/dist/server/base-http/node.js","../node_modules/next/dist/build/output/log.js","../node_modules/next/dist/server/web/utils.js","../node_modules/next/dist/server/lib/node-fs-methods.js","../node_modules/next/dist/client/components/app-router-headers.js","../node_modules/next/dist/server/lib/mock-request.js","../node_modules/next/dist/experimental/testmode/server.js","../node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js","../node_modules/next/dist/shared/lib/page-path/normalize-page-path.js","../node_modules/next/dist/server/lib/trace/tracer.js","../node_modules/next/dist/server/lib/trace/constants.js","../node_modules/next/dist/server/lib/server-ipc/utils.js","../node_modules/next/dist/server/lib/server-ipc/invoke-request.js","../node_modules/next/dist/server/future/route-matches/pages-api-route-match.js","../node_modules/next/dist/shared/lib/router/utils/route-matcher.js","../node_modules/next/dist/shared/lib/router/utils/parse-url.js","../node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.js","../node_modules/next/dist/shared/lib/router/utils/querystring.js","../node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js","../node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js","../node_modules/next/dist/shared/lib/router/utils/app-paths.js","../node_modules/next/dist/shared/lib/router/utils/route-regex.js","../node_modules/next/dist/server/future/helpers/module-loader/route-module-loader.js","../node_modules/next/dist/server/web/spec-extension/adapters/next-request.js","../node_modules/next/dist/server/future/route-modules/app-page/module.render.js","../node_modules/next/dist/server/future/route-modules/pages/module.render.js","../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../node_modules/next/dist/client/components/request-async-storage.external.js","../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../node_modules/next/dist/compiled/next-server/pages.runtime.prod.js","../node_modules/next/dist/server/api-utils/index.js","../node_modules/next/dist/server/response-cache/index.js","../node_modules/next/dist/server/lib/incremental-cache/index.js","../node_modules/next/dist/server/web/sandbox/index.js","../node_modules/next/dist/lib/interop-default.js","../node_modules/next/dist/lib/wait.js","../node_modules/next/dist/lib/detached-promise.js","../node_modules/@next/env/package.json","../node_modules/next/dist/server/lib/revalidate.js","../node_modules/next/dist/server/lib/etag.js","../node_modules/next/dist/shared/lib/is-plain-object.js","../node_modules/next/dist/shared/lib/image-blur-svg.js","../node_modules/next/dist/shared/lib/match-remote-pattern.js","../node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js","../node_modules/next/dist/server/lib/squoosh/main.js","../node_modules/next/dist/server/base-http/index.js","../node_modules/next/dist/shared/lib/modern-browserslist-target.js","../node_modules/next/dist/lib/redirect-status.js","../node_modules/next/dist/lib/is-edge-runtime.js","../node_modules/next/dist/server/utils.js","../node_modules/next/dist/server/render-result.js","../node_modules/next/dist/server/server-utils.js","../node_modules/next/dist/server/internal-utils.js","../node_modules/next/dist/server/send-response.js","../node_modules/next/dist/shared/lib/runtime-config.external.js","../node_modules/next/dist/server/lib/format-hostname.js","../node_modules/next/dist/shared/lib/get-hostname.js","../node_modules/next/dist/server/future/route-kind.js","../node_modules/next/dist/server/lib/match-next-data-pathname.js","../node_modules/next/dist/server/future/normalizers/locale-route-normalizer.js","../node_modules/next/dist/server/future/helpers/i18n-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/pages-api-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-managers/default-route-matcher-manager.js","../node_modules/next/dist/server/future/route-matcher-providers/app-page-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/pages-route-matcher-provider.js","../node_modules/next/dist/server/api-utils/node/try-get-preview-data.js","../node_modules/next/dist/server/future/route-matcher-providers/app-route-route-matcher-provider.js","../node_modules/next/dist/shared/lib/i18n/get-locale-redirect.js","../node_modules/next/dist/client/components/async-local-storage.js","../node_modules/@next/env/dist/index.js","../node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js","../node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js","../node_modules/next/dist/shared/lib/segment.js","../node_modules/next/dist/shared/lib/escape-regexp.js","../node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js","../node_modules/next/dist/shared/lib/router/utils/is-bot.js","../node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js","../node_modules/next/dist/server/future/normalizers/request/rsc.js","../node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.js","../node_modules/next/dist/server/future/normalizers/request/postponed.js","../node_modules/next/dist/server/future/route-modules/helpers/response-handlers.js","../node_modules/next/dist/lib/batcher.js","../node_modules/next/dist/lib/scheduler.js","../node_modules/next/dist/server/future/helpers/interception-routes.js","../node_modules/next/dist/server/web/spec-extension/request.js","../node_modules/next/dist/server/future/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader.js","../node_modules/next/dist/server/response-cache/types.js","../node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js","../node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js","../node_modules/next/dist/shared/lib/router/utils/prepare-destination.js","../node_modules/next/dist/server/future/helpers/module-loader/node-module-loader.js","../node_modules/next/dist/server/future/route-modules/app-page/module.compiled.js","../node_modules/next/dist/server/future/route-modules/pages/module.compiled.js","../node_modules/next/dist/server/web/spec-extension/adapters/headers.js","../node_modules/next/dist/server/lib/incremental-cache/fetch-cache.js","../node_modules/next/dist/shared/lib/isomorphic/path.js","../node_modules/next/dist/server/lib/incremental-cache/file-system-cache.js","../node_modules/next/dist/server/lib/server-ipc/request-utils.js","../node_modules/next/dist/server/web/sandbox/context.js","../node_modules/next/dist/server/web/sandbox/sandbox.js","../node_modules/next/dist/shared/lib/router/utils/index.js","../node_modules/react-dom/package.json","../node_modules/next/dist/compiled/fresh/package.json","../node_modules/next/dist/compiled/ws/package.json","../node_modules/next/dist/compiled/lru-cache/package.json","../node_modules/next/dist/compiled/image-size/package.json","../node_modules/next/dist/compiled/is-animated/package.json","../node_modules/next/dist/compiled/content-disposition/package.json","../node_modules/next/dist/compiled/get-orientation/package.json","../node_modules/next/dist/compiled/send/package.json","../node_modules/next/dist/server/stream-utils/node-web-streams-helper.js","../node_modules/next/dist/server/api-utils/get-cookie-parser.js","../node_modules/next/dist/compiled/@hapi/accept/package.json","../node_modules/@swc/helpers/_/_interop_require_default/package.json","../node_modules/next/dist/server/lib/is-ipv6.js","../node_modules/next/dist/lib/is-api-route.js","../node_modules/next/dist/server/crypto-utils.js","../node_modules/next/dist/lib/is-app-page-route.js","../node_modules/next/dist/server/accept-header.js","../node_modules/next/dist/lib/is-app-route-route.js","../node_modules/next/dist/shared/lib/router/utils/path-match.js","../node_modules/react-dom/server.browser.js","../node_modules/next/dist/server/web/spec-extension/cookies.js","../node_modules/next/dist/server/future/route-matchers/locale-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/pages-api-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/app-page-route-matcher.js","../node_modules/next/dist/server/future/route-matcher-providers/manifest-route-matcher-provider.js","../node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js","../node_modules/next/dist/server/future/route-matchers/app-route-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/pages-route-matcher.js","../node_modules/next/dist/compiled/fresh/index.js","../node_modules/next/dist/compiled/ws/index.js","../node_modules/next/dist/compiled/lru-cache/index.js","../node_modules/next/dist/compiled/image-size/index.js","../node_modules/next/dist/compiled/is-animated/index.js","../node_modules/next/dist/server/web/next-url.js","../node_modules/next/dist/compiled/content-disposition/index.js","../node_modules/next/dist/compiled/get-orientation/index.js","../node_modules/next/dist/compiled/send/index.js","../node_modules/next/dist/server/web/error.js","../node_modules/next/dist/compiled/@mswjs/interceptors/ClientRequest/package.json","../node_modules/next/dist/shared/lib/router/utils/format-url.js","../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../node_modules/next/dist/compiled/jsonwebtoken/package.json","../node_modules/next/dist/compiled/node-html-parser/package.json","../node_modules/@swc/helpers/package.json","../node_modules/next/dist/compiled/cookie/package.json","../node_modules/next/dist/shared/lib/router/utils/is-dynamic.js","../node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js","../node_modules/next/dist/compiled/@hapi/accept/index.js","../node_modules/next/dist/lib/pick.js","../node_modules/next/dist/shared/lib/router/utils/parse-path.js","../node_modules/next/dist/server/web/sandbox/fetch-inline-assets.js","../node_modules/next/dist/server/web/sandbox/resource-managers.js","../node_modules/next/dist/server/web/spec-extension/adapters/reflect.js","../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../node_modules/next/dist/compiled/jsonwebtoken/index.js","../node_modules/next/dist/compiled/node-html-parser/index.js","../node_modules/next/dist/compiled/cookie/index.js","../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../node_modules/next/dist/compiled/@mswjs/interceptors/ClientRequest/index.js","../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../node_modules/next/dist/shared/lib/router/utils/sorted-routes.js","../node_modules/next/dist/server/future/normalizers/built/app/index.js","../node_modules/next/dist/server/future/normalizers/built/pages/index.js","../node_modules/next/dist/server/stream-utils/encode-decode.js","../node_modules/next/dist/compiled/micromatch/package.json","../node_modules/next/dist/server/future/route-matchers/route-matcher.js","../node_modules/next/dist/compiled/micromatch/index.js","../node_modules/next/dist/server/future/route-matcher-providers/helpers/cached-route-matcher-provider.js","../node_modules/next/dist/compiled/next-server/app-page-experimental.runtime.prod.js","../node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js","../node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js","../node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js","../node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js","../node_modules/next/dist/server/future/route-modules/app-page/module.js","../node_modules/next/dist/server/future/route-modules/pages/module.js","../node_modules/next/dist/compiled/path-browserify/package.json","../node_modules/next/dist/compiled/edge-runtime/package.json","../node_modules/next/dist/compiled/path-to-regexp/index.js","../node_modules/next/dist/compiled/path-browserify/index.js","../node_modules/next/dist/compiled/edge-runtime/index.js","../node_modules/next/dist/server/future/normalizers/built/app/app-pathname-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-bundle-path-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-filename-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-page-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-bundle-path-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-pathname-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-page-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-filename-normalizer.js","../node_modules/next/dist/compiled/debug/package.json","../node_modules/next/dist/compiled/@edge-runtime/cookies/package.json","../node_modules/@swc/helpers/_/_interop_require_wildcard/package.json","../node_modules/next/dist/lib/semver-noop.js","../node_modules/next/dist/server/render.js","../node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js","../node_modules/next/dist/shared/lib/router/utils/add-locale.js","../node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js","../node_modules/next/dist/server/app-render/app-render.js","../node_modules/next/dist/compiled/debug/index.js","../node_modules/next/dist/server/future/route-modules/route-module.js","../node_modules/next/dist/compiled/@edge-runtime/cookies/index.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/ssr/entrypoints.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/entrypoints.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/rsc/entrypoints.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/entrypoints.js","../node_modules/@swc/helpers/cjs/_interop_require_wildcard.cjs","../node_modules/next/dist/server/future/normalizers/wrap-normalizer-fn.js","../node_modules/next/dist/server/future/normalizers/normalizers.js","../node_modules/next/dist/server/future/normalizers/underscore-normalizer.js","../node_modules/next/dist/server/future/normalizers/prefixing-normalizer.js","../node_modules/next/dist/server/future/normalizers/absolute-filename-normalizer.js","../node_modules/next/dist/lib/is-serializable-props.js","../node_modules/next/dist/server/post-process.js","../node_modules/next/dist/shared/lib/amp-mode.js","../node_modules/next/dist/shared/lib/amp-context.shared-runtime.js","../node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.js","../node_modules/next/dist/shared/lib/head.js","../node_modules/next/dist/shared/lib/loadable.shared-runtime.js","../node_modules/next/dist/shared/lib/router-context.shared-runtime.js","../node_modules/next/dist/shared/lib/loadable-context.shared-runtime.js","../node_modules/next/dist/shared/lib/image-config-context.shared-runtime.js","../node_modules/next/dist/shared/lib/html-context.shared-runtime.js","../node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.js","../node_modules/next/dist/shared/lib/app-router-context.shared-runtime.js","../node_modules/next/dist/shared/lib/router/adapters.js","../node_modules/next/dist/client/components/match-segments.js","../node_modules/next/dist/server/app-render/create-server-components-renderer.js","../node_modules/next/dist/client/components/get-redirect-status-code-from-error.js","../node_modules/next/dist/client/components/not-found.js","../node_modules/next/dist/server/lib/patch-fetch.js","../node_modules/next/dist/client/components/redirect.js","../node_modules/next/dist/server/async-storage/static-generation-async-storage-wrapper.js","../node_modules/next/dist/server/app-render/get-segment-param.js","../node_modules/next/dist/server/async-storage/request-async-storage-wrapper.js","../node_modules/next/dist/lib/metadata/metadata.js","../node_modules/next/dist/server/app-render/create-error-handler.js","../node_modules/next/dist/server/app-render/get-script-nonce-from-header.js","../node_modules/next/dist/server/app-render/flight-render-result.js","../node_modules/next/dist/server/app-render/get-short-dynamic-param-type.js","../node_modules/next/dist/server/app-render/action-handler.js","../node_modules/next/dist/server/app-render/parse-and-validate-flight-router-state.js","../node_modules/next/dist/server/app-render/server-inserted-html.js","../node_modules/next/dist/server/app-render/validate-url.js","../node_modules/next/dist/server/app-render/walk-tree-with-flight-router-state.js","../node_modules/next/dist/server/app-render/create-flight-router-state-from-loader-tree.js","../node_modules/next/dist/server/app-render/required-scripts.js","../node_modules/next/dist/server/app-render/action-encryption-utils.js","../node_modules/next/dist/server/app-render/make-get-server-inserted-html.js","../node_modules/next/dist/server/app-render/get-asset-query-string.js","../node_modules/next/dist/server/app-render/create-component-tree.js","../node_modules/next/dist/client/components/dev-root-not-found-boundary.js","../node_modules/next/dist/shared/lib/lazy-dynamic/no-ssr-error.js","../node_modules/next/dist/server/app-render/static/static-renderer.js","../node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.js","../node_modules/next/dist/lib/non-nullable.js","../node_modules/next/dist/server/optimize-amp.js","../node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.js","../node_modules/next/dist/shared/lib/side-effect.js","../node_modules/next/dist/shared/lib/image-config.js","../node_modules/next/dist/server/htmlescape.js","../node_modules/next/dist/lib/client-reference.js","../node_modules/next/dist/compiled/strip-ansi/package.json","../node_modules/next/dist/compiled/react-is/package.json","../node_modules/next/dist/shared/lib/utils/warn-once.js","../node_modules/next/dist/client/components/maybe-postpone.js","../node_modules/next/dist/client/components/hooks-server-context.js","../node_modules/next/dist/server/app-render/use-flight-response.js","../node_modules/next/dist/lib/metadata/resolve-metadata.js","../node_modules/next/dist/server/dev/log-app-dir-error.js","../node_modules/next/dist/lib/metadata/default-metadata.js","../node_modules/next/dist/server/async-storage/draft-mode-provider.js","../node_modules/next/dist/server/app-render/react-server.node.js","../node_modules/next/dist/server/app-render/types.js","../node_modules/next/dist/server/app-render/get-css-inlined-link-tags.js","../node_modules/next/dist/server/app-render/get-preloadable-fonts.js","../node_modules/next/dist/server/app-render/parse-loader-tree.js","../node_modules/next/dist/server/app-render/get-layer-assets.js","../node_modules/next/dist/server/app-render/has-loading-component-in-tree.js","../node_modules/next/dist/client/components/not-found-boundary.js","../node_modules/next/dist/server/app-render/interop-default.js","../node_modules/next/dist/server/lib/app-dir-module.js","../node_modules/next/dist/server/app-render/preload-component.js","../node_modules/next/dist/server/app-render/create-component-styles-and-scripts.js","../node_modules/next/dist/lib/metadata/generate/alternate.js","../node_modules/next/dist/lib/metadata/generate/basic.js","../node_modules/next/dist/lib/metadata/generate/meta.js","../node_modules/next/dist/lib/metadata/generate/icons.js","../node_modules/next/dist/lib/metadata/generate/opengraph.js","../node_modules/next/dist/compiled/nanoid/package.json","../node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.js","../node_modules/next/dist/compiled/strip-ansi/index.js","../node_modules/next/dist/compiled/react-is/index.js","../node_modules/next/dist/compiled/nanoid/index.cjs","../node_modules/react/jsx-dev-runtime.js","../node_modules/react/jsx-runtime.js","../node_modules/next/dist/lib/metadata/get-metadata-route.js","../node_modules/busboy/package.json","../node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.js","../node_modules/next/dist/lib/metadata/clone-metadata.js","../node_modules/next/dist/client/components/navigation.js","../node_modules/busboy/lib/index.js","../node_modules/next/dist/lib/metadata/generate/utils.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-opengraph.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-title.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-icons.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-basics.js","../node_modules/next/dist/compiled/string-hash/package.json","../node_modules/next/dist/compiled/superstruct/package.json","../node_modules/next/dist/lib/metadata/constants.js","../node_modules/next/dist/compiled/bytes/package.json","../node_modules/react/cjs/react-jsx-dev-runtime.production.min.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react-dom/index.js","../node_modules/next/dist/compiled/react-is/cjs/react-is.production.min.js","../node_modules/next/dist/compiled/react-is/cjs/react-is.development.js","../node_modules/next/dist/compiled/string-hash/index.js","../node_modules/next/dist/compiled/superstruct/index.cjs","../node_modules/next/dist/compiled/bytes/index.js","../node_modules/next/dist/lib/metadata/is-metadata-route.js","../node_modules/next/dist/shared/lib/hash.js","../node_modules/busboy/lib/utils.js","../node_modules/busboy/lib/types/urlencoded.js","../node_modules/busboy/lib/types/multipart.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/next/dist/client/components/client-hook-in-server-component-error.js","../node_modules/next/dist/client/components/bailout-to-client-rendering.js","../node_modules/next/dist/client/components/router-reducer/reducers/get-segment-value.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-url.js","../node_modules/scheduler/package.json","../node_modules/streamsearch/package.json","../node_modules/scheduler/index.js","../node_modules/streamsearch/lib/sbmh.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/cjs/scheduler.development.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/amp-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/app-router-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/head-manager-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/hooks-client-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/html-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/image-config-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/loadable-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/loadable.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/router-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/server-inserted-html.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/amp-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/app-router-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/head-manager-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/hooks-client-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/html-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/image-config-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/loadable-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/loadable.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/router-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/server-inserted-html.js"]} \ No newline at end of file diff --git a/.next/prerender-manifest.js b/.next/prerender-manifest.js index 667acd6..e75d976 100644 --- a/.next/prerender-manifest.js +++ b/.next/prerender-manifest.js @@ -1 +1 @@ -self.__PRERENDER_MANIFEST={"version":4,"routes":{"/everyone-votes/terms":{"initialRevalidateSeconds":false,"srcRoute":"/everyone-votes/terms","dataRoute":"/everyone-votes/terms.rsc"},"/wiston":{"initialRevalidateSeconds":false,"srcRoute":"/wiston","dataRoute":"/wiston.rsc"},"/":{"initialRevalidateSeconds":false,"srcRoute":"/","dataRoute":"/index.rsc"},"/favicon.ico":{"initialHeaders":{"cache-control":"public, max-age=0, must-revalidate","content-type":"image/x-icon","x-next-cache-tags":"/favicon.ico/route"},"initialRevalidateSeconds":false,"srcRoute":"/favicon.ico","dataRoute":null},"/everyone-votes/privacy":{"initialRevalidateSeconds":false,"srcRoute":"/everyone-votes/privacy","dataRoute":"/everyone-votes/privacy.rsc"},"/space":{"initialRevalidateSeconds":false,"srcRoute":"/space","dataRoute":"/space.rsc"}},"dynamicRoutes":{},"notFoundRoutes":[],"preview":{"previewModeId":"f535f6d20b30f970858e245d10a15b60","previewModeSigningKey":"f446dbbf3baeceb78d5e2462b883019e0919e4c2c24b58ac3e046f3155c62382","previewModeEncryptionKey":"205f3708ebefd9d3ecffd81ac6d85216affc98a5490c5e20d03447d2181ab750"}} \ No newline at end of file +self.__PRERENDER_MANIFEST="{\"version\":4,\"routes\":{\"/favicon.ico\":{\"initialHeaders\":{\"cache-control\":\"public, max-age=0, must-revalidate\",\"content-type\":\"image/x-icon\",\"x-next-cache-tags\":\"_N_T_/layout,_N_T_/favicon.ico/layout,_N_T_/favicon.ico/route,_N_T_/favicon.ico\"},\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/favicon.ico\",\"dataRoute\":null},\"/everyone-votes/privacy\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/everyone-votes/privacy\",\"dataRoute\":\"/everyone-votes/privacy.rsc\"},\"/wiston\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/wiston\",\"dataRoute\":\"/wiston.rsc\"},\"/everyone-votes/terms\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/everyone-votes/terms\",\"dataRoute\":\"/everyone-votes/terms.rsc\"},\"/\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/\",\"dataRoute\":\"/index.rsc\"},\"/space\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/space\",\"dataRoute\":\"/space.rsc\"}},\"dynamicRoutes\":{},\"notFoundRoutes\":[],\"preview\":{\"previewModeId\":\"2ee7fa1dc80c077ce79225eb3cdc3971\",\"previewModeSigningKey\":\"bb0a0599827d52ceae33d3a5056574c66cefc41260f72eb521a7388635317a07\",\"previewModeEncryptionKey\":\"aa1eb598971c55ffca35521acca7df54e69c0ec6c1e86d4b5cded46c9e2dc6a5\"}}" \ No newline at end of file diff --git a/.next/prerender-manifest.json b/.next/prerender-manifest.json index 4d3bffe..9e34226 100644 --- a/.next/prerender-manifest.json +++ b/.next/prerender-manifest.json @@ -1 +1 @@ -{"version":4,"routes":{"/everyone-votes/terms":{"initialRevalidateSeconds":false,"srcRoute":"/everyone-votes/terms","dataRoute":"/everyone-votes/terms.rsc"},"/wiston":{"initialRevalidateSeconds":false,"srcRoute":"/wiston","dataRoute":"/wiston.rsc"},"/":{"initialRevalidateSeconds":false,"srcRoute":"/","dataRoute":"/index.rsc"},"/favicon.ico":{"initialHeaders":{"cache-control":"public, max-age=0, must-revalidate","content-type":"image/x-icon","x-next-cache-tags":"/favicon.ico/route"},"initialRevalidateSeconds":false,"srcRoute":"/favicon.ico","dataRoute":null},"/everyone-votes/privacy":{"initialRevalidateSeconds":false,"srcRoute":"/everyone-votes/privacy","dataRoute":"/everyone-votes/privacy.rsc"},"/space":{"initialRevalidateSeconds":false,"srcRoute":"/space","dataRoute":"/space.rsc"}},"dynamicRoutes":{},"notFoundRoutes":[],"preview":{"previewModeId":"f535f6d20b30f970858e245d10a15b60","previewModeSigningKey":"f446dbbf3baeceb78d5e2462b883019e0919e4c2c24b58ac3e046f3155c62382","previewModeEncryptionKey":"205f3708ebefd9d3ecffd81ac6d85216affc98a5490c5e20d03447d2181ab750"}} \ No newline at end of file +{"version":4,"routes":{"/favicon.ico":{"initialHeaders":{"cache-control":"public, max-age=0, must-revalidate","content-type":"image/x-icon","x-next-cache-tags":"_N_T_/layout,_N_T_/favicon.ico/layout,_N_T_/favicon.ico/route,_N_T_/favicon.ico"},"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/favicon.ico","dataRoute":null},"/everyone-votes/privacy":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/everyone-votes/privacy","dataRoute":"/everyone-votes/privacy.rsc"},"/wiston":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/wiston","dataRoute":"/wiston.rsc"},"/everyone-votes/terms":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/everyone-votes/terms","dataRoute":"/everyone-votes/terms.rsc"},"/":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/","dataRoute":"/index.rsc"},"/space":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/space","dataRoute":"/space.rsc"}},"dynamicRoutes":{},"notFoundRoutes":[],"preview":{"previewModeId":"2ee7fa1dc80c077ce79225eb3cdc3971","previewModeSigningKey":"bb0a0599827d52ceae33d3a5056574c66cefc41260f72eb521a7388635317a07","previewModeEncryptionKey":"aa1eb598971c55ffca35521acca7df54e69c0ec6c1e86d4b5cded46c9e2dc6a5"}} \ No newline at end of file diff --git a/.next/required-server-files.json b/.next/required-server-files.json index 883c60b..c35d7d7 100644 --- a/.next/required-server-files.json +++ b/.next/required-server-files.json @@ -1 +1 @@ -{"version":1,"config":{"env":{},"webpack":null,"eslint":{"ignoreDuringBuilds":false},"typescript":{"ignoreBuildErrors":false,"tsconfigPath":"tsconfig.json"},"distDir":".next","cleanDistDir":true,"assetPrefix":"","configOrigin":"next.config.js","useFileSystemPublicRoutes":true,"generateEtags":true,"pageExtensions":["tsx","ts","jsx","js"],"poweredByHeader":true,"compress":true,"analyticsId":"","images":{"deviceSizes":[640,750,828,1080,1200,1920,2048,3840],"imageSizes":[16,32,48,64,96,128,256,384],"path":"/_next/image","loader":"default","loaderFile":"","domains":[],"disableStaticImages":false,"minimumCacheTTL":60,"formats":["image/webp"],"dangerouslyAllowSVG":false,"contentSecurityPolicy":"script-src 'none'; frame-src 'none'; sandbox;","contentDispositionType":"inline","remotePatterns":[],"unoptimized":false},"devIndicators":{"buildActivity":true,"buildActivityPosition":"bottom-right"},"onDemandEntries":{"maxInactiveAge":15000,"pagesBufferLength":2},"amp":{"canonicalBase":""},"basePath":"","sassOptions":{},"trailingSlash":false,"i18n":null,"productionBrowserSourceMaps":false,"optimizeFonts":true,"excludeDefaultMomentLocales":true,"serverRuntimeConfig":{},"publicRuntimeConfig":{},"reactStrictMode":false,"httpAgentOptions":{"keepAlive":true},"outputFileTracing":true,"staticPageGenerationTimeout":60,"swcMinify":true,"experimental":{"clientRouterFilter":true,"clientRouterFilterRedirects":false,"fetchCacheKeyPrefix":"","middlewarePrefetch":"flexible","optimisticClientCache":true,"manualClientBasePath":false,"legacyBrowsers":false,"newNextLinkBehavior":true,"cpus":19,"memoryBasedWorkersCount":false,"sharedPool":true,"isrFlushToDisk":true,"workerThreads":false,"pageEnv":false,"optimizeCss":false,"nextScriptWorkers":false,"scrollRestoration":false,"externalDir":false,"disableOptimizedLoading":false,"gzipSize":true,"swcFileReading":true,"craCompat":false,"esmExternals":true,"appDir":true,"isrMemoryCacheSize":52428800,"fullySpecified":false,"outputFileTracingRoot":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev","swcTraceProfiling":false,"forceSwcTransforms":false,"largePageDataBytes":128000,"adjustFontFallbacks":false,"adjustFontFallbacksWithSizeAdjust":false,"typedRoutes":false,"instrumentationHook":false,"trustHostHeader":false},"configFileName":"next.config.js","_originalRedirects":[{"source":"/:slug(yt|youtube)","destination":"https://www.youtube.com/Sukadia","permanent":false},{"source":"/:slug(vod|vods)","destination":"https://www.youtube.com/channel/UC8S8l4sY8YsVcngSBTVyoSA","permanent":false},{"source":"/:slug(dev|update|updates)","destination":"https://www.youtube.com/channel/UCbzmy3xP2E0rLhCPFktbwAQ","permanent":false},{"source":"/:slug(ttv|twitch)","destination":"https://www.twitch.tv/Sukadia","permanent":false},{"source":"/:slug(hub|discord)","destination":"https://discord.gg/ReSCjYpXnK","permanent":false},{"source":"/:slug(ev|everyonevotes|everyone-votes)","destination":"https://top.gg/bot/805922495705251891","permanent":false},{"source":"/:slug(kofi|ko-fi)","destination":"https://ko-fi.com/sukadia/tiers","permanent":false},{"source":"/dark","destination":"https://marketplace.visualstudio.com/items?itemName=Sukadia.sukadia-dev-dark","permanent":false},{"source":"/banner","destination":"https://www.youtube.com/watch?v=tvq5aBROV_s","permanent":false},{"source":"/nsfw","destination":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","permanent":false}]},"appDir":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev","relativeAppDir":"","files":[".next\\routes-manifest.json",".next\\server\\pages-manifest.json",".next\\build-manifest.json",".next\\prerender-manifest.json",".next\\server\\middleware-manifest.json",".next\\server\\middleware-build-manifest.js",".next\\server\\middleware-react-loadable-manifest.js",".next\\server\\app-paths-manifest.json",".next\\app-build-manifest.json",".next\\server\\client-reference-manifest.js",".next\\server\\client-reference-manifest.json",".next\\server\\flight-server-css-manifest.js",".next\\server\\flight-server-css-manifest.json",".next\\server\\server-reference-manifest.js",".next\\server\\server-reference-manifest.json",".next\\react-loadable-manifest.json",".next\\server\\font-manifest.json",".next\\BUILD_ID",".next\\server\\app-paths-manifest.json",".next\\server\\next-font-manifest.js",".next\\server\\next-font-manifest.json"],"ignore":["node_modules\\next\\dist\\compiled\\@ampproject\\toolbox-optimizer\\**\\*"]} \ No newline at end of file +{"version":1,"config":{"env":{},"webpack":null,"eslint":{"ignoreDuringBuilds":false},"typescript":{"ignoreBuildErrors":false,"tsconfigPath":"tsconfig.json"},"distDir":".next","cleanDistDir":true,"assetPrefix":"","configOrigin":"next.config.js","useFileSystemPublicRoutes":true,"generateEtags":true,"pageExtensions":["tsx","ts","jsx","js"],"poweredByHeader":true,"compress":true,"analyticsId":"","images":{"deviceSizes":[640,750,828,1080,1200,1920,2048,3840],"imageSizes":[16,32,48,64,96,128,256,384],"path":"/_next/image","loader":"default","loaderFile":"","domains":[],"disableStaticImages":false,"minimumCacheTTL":60,"formats":["image/webp"],"dangerouslyAllowSVG":false,"contentSecurityPolicy":"script-src 'none'; frame-src 'none'; sandbox;","contentDispositionType":"inline","remotePatterns":[],"unoptimized":false},"devIndicators":{"buildActivity":true,"buildActivityPosition":"bottom-right"},"onDemandEntries":{"maxInactiveAge":60000,"pagesBufferLength":5},"amp":{"canonicalBase":""},"basePath":"","sassOptions":{},"trailingSlash":false,"i18n":null,"productionBrowserSourceMaps":false,"optimizeFonts":true,"excludeDefaultMomentLocales":true,"serverRuntimeConfig":{},"publicRuntimeConfig":{},"reactProductionProfiling":false,"reactStrictMode":null,"httpAgentOptions":{"keepAlive":true},"outputFileTracing":true,"staticPageGenerationTimeout":60,"swcMinify":true,"modularizeImports":{"@mui/icons-material":{"transform":"@mui/icons-material/{{member}}"},"date-fns":{"transform":"date-fns/{{member}}"},"lodash":{"transform":"lodash/{{member}}"},"lodash-es":{"transform":"lodash-es/{{member}}"},"ramda":{"transform":"ramda/es/{{member}}"},"react-bootstrap":{"transform":{"useAccordionButton":"modularize-import-loader?name=useAccordionButton&from=named&as=default!react-bootstrap/AccordionButton","*":"react-bootstrap/{{member}}"}},"antd":{"transform":"antd/lib/{{kebabCase member}}"},"ahooks":{"transform":{"createUpdateEffect":"modularize-import-loader?name=createUpdateEffect&from=named&as=default!ahooks/es/createUpdateEffect","*":"ahooks/es/{{member}}"}},"@ant-design/icons":{"transform":{"IconProvider":"modularize-import-loader?name=IconProvider&from=named&as=default!@ant-design/icons","createFromIconfontCN":"@ant-design/icons/es/components/IconFont","getTwoToneColor":"modularize-import-loader?name=getTwoToneColor&from=named&as=default!@ant-design/icons/es/components/twoTonePrimaryColor","setTwoToneColor":"modularize-import-loader?name=setTwoToneColor&from=named&as=default!@ant-design/icons/es/components/twoTonePrimaryColor","*":"@ant-design/icons/lib/icons/{{member}}"}},"next/server":{"transform":"next/dist/server/web/exports/{{ kebabCase member }}"}},"experimental":{"serverMinification":true,"serverSourceMaps":false,"caseSensitiveRoutes":false,"useDeploymentId":false,"useDeploymentIdServerActions":false,"clientRouterFilter":true,"clientRouterFilterRedirects":false,"fetchCacheKeyPrefix":"","middlewarePrefetch":"flexible","optimisticClientCache":true,"manualClientBasePath":false,"cpus":15,"memoryBasedWorkersCount":false,"isrFlushToDisk":true,"workerThreads":false,"optimizeCss":false,"nextScriptWorkers":false,"scrollRestoration":false,"externalDir":false,"disableOptimizedLoading":false,"gzipSize":true,"craCompat":false,"esmExternals":true,"isrMemoryCacheSize":52428800,"fullySpecified":false,"outputFileTracingRoot":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev","swcTraceProfiling":false,"forceSwcTransforms":false,"largePageDataBytes":128000,"adjustFontFallbacks":false,"adjustFontFallbacksWithSizeAdjust":false,"typedRoutes":false,"instrumentationHook":false,"bundlePagesExternals":false,"optimizePackageImports":["lucide-react","@headlessui/react","@headlessui-float/react","@heroicons/react/20/solid","@heroicons/react/24/solid","@heroicons/react/24/outline","@visx/visx","@tremor/react","rxjs","@mui/material","@mui/icons-material","recharts","react-use","@material-ui/core","@material-ui/icons","@tabler/icons-react","mui-core","react-icons/ai","react-icons/bi","react-icons/bs","react-icons/cg","react-icons/ci","react-icons/di","react-icons/fa","react-icons/fa6","react-icons/fc","react-icons/fi","react-icons/gi","react-icons/go","react-icons/gr","react-icons/hi","react-icons/hi2","react-icons/im","react-icons/io","react-icons/io5","react-icons/lia","react-icons/lib","react-icons/lu","react-icons/md","react-icons/pi","react-icons/ri","react-icons/rx","react-icons/si","react-icons/sl","react-icons/tb","react-icons/tfi","react-icons/ti","react-icons/vsc","react-icons/wi"],"trustHostHeader":false,"isExperimentalCompile":false},"configFileName":"next.config.js","_originalRedirects":[{"source":"/:slug(yt|youtube)","destination":"https://www.youtube.com/Sukadia","permanent":false},{"source":"/:slug(vod|vods)","destination":"https://www.youtube.com/channel/UC8S8l4sY8YsVcngSBTVyoSA","permanent":false},{"source":"/:slug(dev|update|updates)","destination":"https://www.youtube.com/channel/UCbzmy3xP2E0rLhCPFktbwAQ","permanent":false},{"source":"/:slug(ttv|twitch)","destination":"https://www.twitch.tv/Sukadia","permanent":false},{"source":"/:slug(hub|discord)","destination":"https://discord.gg/ReSCjYpXnK","permanent":false},{"source":"/:slug(ev|everyonevotes|everyone-votes)","destination":"https://top.gg/bot/805922495705251891","permanent":false},{"source":"/:slug(kofi|ko-fi)","destination":"https://ko-fi.com/sukadia/tiers","permanent":false},{"source":"/poster","destination":"https://ko-fi.com/s/3cf296742e","permanent":false},{"source":"/dark","destination":"https://marketplace.visualstudio.com/items?itemName=Sukadia.sukadia-dev-dark","permanent":false},{"source":"/banner","destination":"https://www.youtube.com/watch?v=tvq5aBROV_s","permanent":false},{"source":"/nsfw","destination":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","permanent":false}]},"appDir":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev","relativeAppDir":"","files":[".next\\routes-manifest.json",".next\\server\\pages-manifest.json",".next\\build-manifest.json",".next\\prerender-manifest.json",".next\\prerender-manifest.js",".next\\server\\middleware-manifest.json",".next\\server\\middleware-build-manifest.js",".next\\server\\middleware-react-loadable-manifest.js",".next\\server\\app-paths-manifest.json",".next\\app-path-routes-manifest.json",".next\\app-build-manifest.json",".next\\server\\server-reference-manifest.js",".next\\server\\server-reference-manifest.json",".next\\react-loadable-manifest.json",".next\\server\\font-manifest.json",".next\\BUILD_ID",".next\\server\\next-font-manifest.js",".next\\server\\next-font-manifest.json"],"ignore":["node_modules\\next\\dist\\compiled\\@ampproject\\toolbox-optimizer\\**\\*"]} \ No newline at end of file diff --git a/.next/routes-manifest.json b/.next/routes-manifest.json index 58b125c..d0ad8ac 100644 --- a/.next/routes-manifest.json +++ b/.next/routes-manifest.json @@ -1 +1 @@ -{"version":3,"pages404":true,"basePath":"","redirects":[{"source":"/:path+/","destination":"/:path+","internal":true,"statusCode":308,"regex":"^(?:/((?:[^/]+?)(?:/(?:[^/]+?))*))/$"},{"source":"/:slug(yt|youtube)","destination":"https://www.youtube.com/Sukadia","statusCode":307,"regex":"^(?!/_next)(?:/(yt|youtube))(?:/)?$"},{"source":"/:slug(vod|vods)","destination":"https://www.youtube.com/channel/UC8S8l4sY8YsVcngSBTVyoSA","statusCode":307,"regex":"^(?!/_next)(?:/(vod|vods))(?:/)?$"},{"source":"/:slug(dev|update|updates)","destination":"https://www.youtube.com/channel/UCbzmy3xP2E0rLhCPFktbwAQ","statusCode":307,"regex":"^(?!/_next)(?:/(dev|update|updates))(?:/)?$"},{"source":"/:slug(ttv|twitch)","destination":"https://www.twitch.tv/Sukadia","statusCode":307,"regex":"^(?!/_next)(?:/(ttv|twitch))(?:/)?$"},{"source":"/:slug(hub|discord)","destination":"https://discord.gg/ReSCjYpXnK","statusCode":307,"regex":"^(?!/_next)(?:/(hub|discord))(?:/)?$"},{"source":"/:slug(ev|everyonevotes|everyone-votes)","destination":"https://top.gg/bot/805922495705251891","statusCode":307,"regex":"^(?!/_next)(?:/(ev|everyonevotes|everyone-votes))(?:/)?$"},{"source":"/:slug(kofi|ko-fi)","destination":"https://ko-fi.com/sukadia/tiers","statusCode":307,"regex":"^(?!/_next)(?:/(kofi|ko-fi))(?:/)?$"},{"source":"/dark","destination":"https://marketplace.visualstudio.com/items?itemName=Sukadia.sukadia-dev-dark","statusCode":307,"regex":"^(?!/_next)/dark(?:/)?$"},{"source":"/banner","destination":"https://www.youtube.com/watch?v=tvq5aBROV_s","statusCode":307,"regex":"^(?!/_next)/banner(?:/)?$"},{"source":"/nsfw","destination":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","statusCode":307,"regex":"^(?!/_next)/nsfw(?:/)?$"}],"headers":[],"dynamicRoutes":[],"staticRoutes":[{"page":"/","regex":"^/(?:/)?$","routeKeys":{},"namedRegex":"^/(?:/)?$"},{"page":"/everyone-votes/privacy","regex":"^/everyone\\-votes/privacy(?:/)?$","routeKeys":{},"namedRegex":"^/everyone\\-votes/privacy(?:/)?$"},{"page":"/everyone-votes/terms","regex":"^/everyone\\-votes/terms(?:/)?$","routeKeys":{},"namedRegex":"^/everyone\\-votes/terms(?:/)?$"},{"page":"/favicon.ico","regex":"^/favicon\\.ico(?:/)?$","routeKeys":{},"namedRegex":"^/favicon\\.ico(?:/)?$"},{"page":"/space","regex":"^/space(?:/)?$","routeKeys":{},"namedRegex":"^/space(?:/)?$"},{"page":"/wiston","regex":"^/wiston(?:/)?$","routeKeys":{},"namedRegex":"^/wiston(?:/)?$"}],"dataRoutes":[],"rsc":{"header":"RSC","varyHeader":"RSC, Next-Router-State-Tree, Next-Router-Prefetch","contentTypeHeader":"text/x-component; charset=utf-8"},"rewrites":[]} \ No newline at end of file +{"version":3,"pages404":true,"caseSensitive":false,"basePath":"","redirects":[{"source":"/:path+/","destination":"/:path+","internal":true,"statusCode":308,"regex":"^(?:/((?:[^/]+?)(?:/(?:[^/]+?))*))/$"},{"source":"/:slug(yt|youtube)","destination":"https://www.youtube.com/Sukadia","statusCode":307,"regex":"^(?!/_next)(?:/(yt|youtube))(?:/)?$"},{"source":"/:slug(vod|vods)","destination":"https://www.youtube.com/channel/UC8S8l4sY8YsVcngSBTVyoSA","statusCode":307,"regex":"^(?!/_next)(?:/(vod|vods))(?:/)?$"},{"source":"/:slug(dev|update|updates)","destination":"https://www.youtube.com/channel/UCbzmy3xP2E0rLhCPFktbwAQ","statusCode":307,"regex":"^(?!/_next)(?:/(dev|update|updates))(?:/)?$"},{"source":"/:slug(ttv|twitch)","destination":"https://www.twitch.tv/Sukadia","statusCode":307,"regex":"^(?!/_next)(?:/(ttv|twitch))(?:/)?$"},{"source":"/:slug(hub|discord)","destination":"https://discord.gg/ReSCjYpXnK","statusCode":307,"regex":"^(?!/_next)(?:/(hub|discord))(?:/)?$"},{"source":"/:slug(ev|everyonevotes|everyone-votes)","destination":"https://top.gg/bot/805922495705251891","statusCode":307,"regex":"^(?!/_next)(?:/(ev|everyonevotes|everyone-votes))(?:/)?$"},{"source":"/:slug(kofi|ko-fi)","destination":"https://ko-fi.com/sukadia/tiers","statusCode":307,"regex":"^(?!/_next)(?:/(kofi|ko-fi))(?:/)?$"},{"source":"/poster","destination":"https://ko-fi.com/s/3cf296742e","statusCode":307,"regex":"^(?!/_next)/poster(?:/)?$"},{"source":"/dark","destination":"https://marketplace.visualstudio.com/items?itemName=Sukadia.sukadia-dev-dark","statusCode":307,"regex":"^(?!/_next)/dark(?:/)?$"},{"source":"/banner","destination":"https://www.youtube.com/watch?v=tvq5aBROV_s","statusCode":307,"regex":"^(?!/_next)/banner(?:/)?$"},{"source":"/nsfw","destination":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","statusCode":307,"regex":"^(?!/_next)/nsfw(?:/)?$"}],"headers":[],"dynamicRoutes":[],"staticRoutes":[{"page":"/","regex":"^/(?:/)?$","routeKeys":{},"namedRegex":"^/(?:/)?$"},{"page":"/_not-found","regex":"^/_not\\-found(?:/)?$","routeKeys":{},"namedRegex":"^/_not\\-found(?:/)?$"},{"page":"/everyone-votes/privacy","regex":"^/everyone\\-votes/privacy(?:/)?$","routeKeys":{},"namedRegex":"^/everyone\\-votes/privacy(?:/)?$"},{"page":"/everyone-votes/terms","regex":"^/everyone\\-votes/terms(?:/)?$","routeKeys":{},"namedRegex":"^/everyone\\-votes/terms(?:/)?$"},{"page":"/favicon.ico","regex":"^/favicon\\.ico(?:/)?$","routeKeys":{},"namedRegex":"^/favicon\\.ico(?:/)?$"},{"page":"/space","regex":"^/space(?:/)?$","routeKeys":{},"namedRegex":"^/space(?:/)?$"},{"page":"/wiston","regex":"^/wiston(?:/)?$","routeKeys":{},"namedRegex":"^/wiston(?:/)?$"}],"dataRoutes":[],"rsc":{"header":"RSC","varyHeader":"RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url","prefetchHeader":"Next-Router-Prefetch","contentTypeHeader":"text/x-component"},"rewrites":[]} \ No newline at end of file diff --git a/.next/server/app-paths-manifest.json b/.next/server/app-paths-manifest.json index aabd92c..e1286d6 100644 --- a/.next/server/app-paths-manifest.json +++ b/.next/server/app-paths-manifest.json @@ -1,8 +1,9 @@ { + "/_not-found": "app/_not-found.js", + "/everyone-votes/terms/page": "app/everyone-votes/terms/page.js", + "/everyone-votes/privacy/page": "app/everyone-votes/privacy/page.js", "/favicon.ico/route": "app/favicon.ico/route.js", "/page": "app/page.js", - "/wiston/page": "app/wiston/page.js", "/space/page": "app/space/page.js", - "/everyone-votes/privacy/page": "app/everyone-votes/privacy/page.js", - "/everyone-votes/terms/page": "app/everyone-votes/terms/page.js" + "/wiston/page": "app/wiston/page.js" } \ No newline at end of file diff --git a/.next/server/app/_not-found.html b/.next/server/app/_not-found.html new file mode 100644 index 0000000..adf7e8f --- /dev/null +++ b/.next/server/app/_not-found.html @@ -0,0 +1 @@ +404: This page could not be found.sukadia.dev

404

This page could not be found.

\ No newline at end of file diff --git a/.next/server/app/_not-found.js b/.next/server/app/_not-found.js new file mode 100644 index 0000000..23a8d9c --- /dev/null +++ b/.next/server/app/_not-found.js @@ -0,0 +1 @@ +"use strict";(()=>{var e={};e.id=165,e.ids=[165],e.modules={5403:e=>{e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},6813:(e,t,n)=>{n.r(t),n.d(t,{GlobalError:()=>a.a,__next_app__:()=>c,originalPathname:()=>u,pages:()=>p,routeModule:()=>x,tree:()=>d});var r=n(7096),o=n(6132),s=n(7284),a=n.n(s),i=n(2564),l={};for(let e in i)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>i[e]);n.d(t,l);let d=["",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(n.t.bind(n,9291,23)),"next/dist/client/components/not-found-error"]}]},{layout:[()=>Promise.resolve().then(n.bind(n,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(n.t.bind(n,9291,23)),"next/dist/client/components/not-found-error"]}],p=[],u="/_not-found",c={require:n,loadChunk:()=>Promise.resolve()},x=new r.AppPageRouteModule({definition:{kind:o.x.APP_PAGE,page:"/_not-found",pathname:"/_not-found",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:d}})}};var t=require("../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),n=t.X(0,[862,622],()=>__webpack_exec__(6813));module.exports=n})(); \ No newline at end of file diff --git a/.next/server/app/_not-found.js.nft.json b/.next/server/app/_not-found.js.nft.json new file mode 100644 index 0000000..3eecb82 --- /dev/null +++ b/.next/server/app/_not-found.js.nft.json @@ -0,0 +1 @@ +{"version":1,"files":["../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../node_modules/next/dist/client/components/async-local-storage.js","../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../package.json","../chunks/106.js","../chunks/2.js","../chunks/201.js","../chunks/310.js","../chunks/323.js","../chunks/622.js","../chunks/676.js","../chunks/837.js","../chunks/840.js","../chunks/862.js","../chunks/984.js","../chunks/font-manifest.json","../webpack-runtime.js","_not-found_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/_not-found.meta b/.next/server/app/_not-found.meta new file mode 100644 index 0000000..fc1dcd9 --- /dev/null +++ b/.next/server/app/_not-found.meta @@ -0,0 +1,5 @@ +{ + "headers": { + "x-next-cache-tags": "_N_T_/layout,_N_T_/_not-found/layout,_N_T_/_not-found" + } +} \ No newline at end of file diff --git a/.next/server/app/_not-found.rsc b/.next/server/app/_not-found.rsc new file mode 100644 index 0000000..12dc2e3 --- /dev/null +++ b/.next/server/app/_not-found.rsc @@ -0,0 +1,11 @@ +1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] +0:["9CqSqX2Hqhh4fwiD8kSfJ",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] +4:I[6954,[],""] +5:I[7264,[],""] +7:{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"} +8:{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"} +9:{"display":"inline-block"} +a:{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0} +2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$L6",[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$7","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$8","children":"404"}],["$","div",null,{"style":"$9","children":["$","h2",null,{"style":"$a","children":"This page could not be found."}]}]]}]}]],null],"segment":"__PAGE__"},"styles":null}]}]}],null] +3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}]] +6:null diff --git a/.next/server/app/_not-found_client-reference-manifest.js b/.next/server/app/_not-found_client-reference-manifest.js new file mode 100644 index 0000000..18ebb4c --- /dev/null +++ b/.next/server/app/_not-found_client-reference-manifest.js @@ -0,0 +1 @@ +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/_not-found"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"]}} \ No newline at end of file diff --git a/.next/server/app/everyone-votes/privacy.html b/.next/server/app/everyone-votes/privacy.html index 4c59327..df64de9 100644 --- a/.next/server/app/everyone-votes/privacy.html +++ b/.next/server/app/everyone-votes/privacy.html @@ -1 +1 @@ -sukadia.dev

Everyone Votes Privacy Policy

Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:


What We Store

By voting on a poll with Everyone Votes, we store:

This data is stored for up to 24 hours, and is wiped every day at UTC midnight.

A cumulative count of the number of votes for each poll option is saved indefinitely.


By setting up Everyone Votes, we store:

This data is stored for as long as Everyone Votes is setup within the server.


By adding server-wide polls on Everyone Votes, we store:

This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command.


In summary, I don't use your data for anything malicious, just for getting poll result counts.


Removal of Data

Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure.

User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data.


Contact

If you have questions or concerns about these terms, please join the support server on Discord, or email contact@sukadia.dev.

\ No newline at end of file +sukadia.dev

Everyone Votes Privacy Policy

Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:


What We Store

By voting on a poll with Everyone Votes, we store:

This data is stored for up to 24 hours, and is wiped every day at UTC midnight.

A cumulative count of the number of votes for each poll option is saved indefinitely.


By setting up Everyone Votes, we store:

This data is stored for as long as Everyone Votes is setup within the server.


By adding server-wide polls on Everyone Votes, we store:

This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command.


In summary, I don't use your data for anything malicious, just for getting poll result counts.


Removal of Data

Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure.

User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data.


Contact

If you have questions or concerns about these terms, please join the support server on Discord, or email contact@sukadia.dev.

\ No newline at end of file diff --git a/.next/server/app/everyone-votes/privacy.meta b/.next/server/app/everyone-votes/privacy.meta index 13ae687..7ffd6ee 100644 --- a/.next/server/app/everyone-votes/privacy.meta +++ b/.next/server/app/everyone-votes/privacy.meta @@ -1 +1,5 @@ -{"headers":{"x-next-cache-tags":"/everyone-votes/privacy/page"}} \ No newline at end of file +{ + "headers": { + "x-next-cache-tags": "_N_T_/layout,_N_T_/everyone-votes/layout,_N_T_/everyone-votes/privacy/layout,_N_T_/everyone-votes/privacy/page,_N_T_/everyone-votes/privacy" + } +} \ No newline at end of file diff --git a/.next/server/app/everyone-votes/privacy.rsc b/.next/server/app/everyone-votes/privacy.rsc index 0da0bec..909619c 100644 --- a/.next/server/app/everyone-votes/privacy.rsc +++ b/.next/server/app/everyone-votes/privacy.rsc @@ -1,6 +1,7 @@ -1:HL["/_next/static/css/3930d1a0ca01c66f.css",{"as":"style"}] -0:[[["",{"children":["everyone-votes",{"children":["privacy",{"children":["__PAGE__",{}]}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/3930d1a0ca01c66f.css","precedence":"next"}]],["$L3",null]]]] -4:I{"id":"4463","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -5:I{"id":"1010","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -2:[["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_0ec1f4","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$L5",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$L5",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children","privacy","children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$L5",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":[["$","main",null,{"className":"ml-[10%] mt-[5%] mr-[10%]","children":[["$","h1",null,{"className":"text-3xl","children":"Everyone Votes Privacy Policy"}],["$","p",null,{"children":"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"What We Store"}],["$","h3",null,{"className":"text-xl","children":"By voting on a poll with Everyone Votes, we store:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- The poll option(s) you voted on"}],["$","p",null,{"children":"- Your Discord user id"}]]}],["$","p",null,{"children":"This data is stored for up to 24 hours, and is wiped every day at UTC midnight."}],["$","p",null,{"children":"A cumulative count of the number of votes for each poll option is saved indefinitely."}],["$","br",null,{}],["$","h3",null,{"className":"text-xl","children":"By setting up Everyone Votes, we store:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- The server id, poll channel ids, and current poll messages"}],["$","p",null,{"children":"- Config settings"}]]}],["$","p",null,{"children":"This data is stored for as long as Everyone Votes is setup within the server."}],["$","br",null,{}],["$","h3",null,{"className":"text-xl","children":"By adding server-wide polls on Everyone Votes, we store:"}],["$","ul",null,{"children":["$","p",null,{"children":"- All of those polls' data"}]}],["$","p",null,{"children":"This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command."}],["$","br",null,{}],["$","p",null,{"children":"In summary, I don't use your data for anything malicious, just for getting poll result counts."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Removal of Data"}],["$","p",null,{"children":"Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure."}],["$","p",null,{"children":"User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Contact"}],["$","p",null,{"children":["If you have questions or concerns about these terms, please join the ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," on Discord, or email ",["$","span",null,{"className":"font-mono","children":"contact@sukadia.dev"}],"."]}]]}],null],"segment":"__PAGE__"},"styles":[]}],"segment":"privacy"},"styles":[]}],"segment":"everyone-votes"},"styles":[]}]}]}],null] -3:[[["$","meta",null,{"charSet":"utf-8"}],["$","title",null,{"children":"sukadia.dev"}],["$","meta",null,{"name":"description","content":"I code, stream, and create videos."}],null,null,null,null,null,null,null,null,["$","meta",null,{"name":"viewport","content":"width=device-width, initial-scale=1"}],null,null,null,null,null,null,null,null,null,null,[]],[null,null,null,null],null,null,[null,null,null,null,null],null,null,null,null,[null,[["$","link",null,{"rel":"icon","href":"\\favicon.ico","type":"image/x-icon","sizes":"any"}]],[],null]] +1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] +0:["9CqSqX2Hqhh4fwiD8kSfJ",[[["",{"children":["everyone-votes",{"children":["privacy",{"children":["__PAGE__",{}]}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] +4:I[6954,[],""] +5:I[7264,[],""] +2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children","privacy","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$L6",["$","main",null,{"className":"ml-[10%] mt-[5%] mr-[10%]","children":[["$","h1",null,{"className":"text-3xl","children":"Everyone Votes Privacy Policy"}],["$","p",null,{"children":"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"What We Store"}],["$","h3",null,{"className":"text-xl","children":"By voting on a poll with Everyone Votes, we store:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- The poll option(s) you voted on"}],["$","p",null,{"children":"- Your Discord user id"}]]}],["$","p",null,{"children":"This data is stored for up to 24 hours, and is wiped every day at UTC midnight."}],["$","p",null,{"children":"A cumulative count of the number of votes for each poll option is saved indefinitely."}],["$","br",null,{}],["$","h3",null,{"className":"text-xl","children":"By setting up Everyone Votes, we store:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- The server id, poll channel ids, and current poll messages"}],["$","p",null,{"children":"- Config settings"}]]}],["$","p",null,{"children":"This data is stored for as long as Everyone Votes is setup within the server."}],["$","br",null,{}],["$","h3",null,{"className":"text-xl","children":"By adding server-wide polls on Everyone Votes, we store:"}],["$","ul",null,{"children":["$","p",null,{"children":"- All of those polls' data"}]}],["$","p",null,{"children":"This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command."}],["$","br",null,{}],["$","p",null,{"children":"In summary, I don't use your data for anything malicious, just for getting poll result counts."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Removal of Data"}],["$","p",null,{"children":"Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure."}],["$","p",null,{"children":"User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Contact"}],["$","p",null,{"children":["If you have questions or concerns about these terms, please join the ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," on Discord, or email ",["$","span",null,{"className":"font-mono","children":"contact@sukadia.dev"}],"."]}]]}],null],"segment":"__PAGE__"},"styles":null}],"segment":"privacy"},"styles":null}],"segment":"everyone-votes"},"styles":null}]}]}],null] +3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +6:null diff --git a/.next/server/app/everyone-votes/privacy/page.js b/.next/server/app/everyone-votes/privacy/page.js index 3b28418..1c827f1 100644 --- a/.next/server/app/everyone-votes/privacy/page.js +++ b/.next/server/app/everyone-votes/privacy/page.js @@ -1,415 +1 @@ -(() => { -var exports = {}; -exports.id = 369; -exports.ids = [369]; -exports.modules = { - -/***/ 252: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/cookie"); - -/***/ }), - -/***/ 7999: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/path-to-regexp"); - -/***/ }), - -/***/ 8038: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react"); - -/***/ }), - -/***/ 8704: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react-dom/server-rendering-stub"); - -/***/ }), - -/***/ 7897: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react-server-dom-webpack/client"); - -/***/ }), - -/***/ 6786: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react/jsx-runtime"); - -/***/ }), - -/***/ 1090: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/server/app-render/get-segment-param.js"); - -/***/ }), - -/***/ 8652: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/server/future/helpers/interception-routes.js"); - -/***/ }), - -/***/ 3280: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/app-router-context.js"); - -/***/ }), - -/***/ 9274: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/hooks-client-context.js"); - -/***/ }), - -/***/ 1751: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/add-path-prefix.js"); - -/***/ }), - -/***/ 1668: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/handle-smooth-scroll.js"); - -/***/ }), - -/***/ 1897: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/is-bot.js"); - -/***/ }), - -/***/ 8854: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/parse-path.js"); - -/***/ }), - -/***/ 3297: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/remove-trailing-slash.js"); - -/***/ }), - -/***/ 3349: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/server-inserted-html.js"); - -/***/ }), - -/***/ 1017: -/***/ ((module) => { - -"use strict"; -module.exports = require("path"); - -/***/ }), - -/***/ 7310: -/***/ ((module) => { - -"use strict"; -module.exports = require("url"); - -/***/ }), - -/***/ 6058: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "AppRouter": () => (/* reexport default from dynamic */ next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0___default.a), -/* harmony export */ "GlobalError": () => (/* reexport default from dynamic */ next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3___default.a), -/* harmony export */ "LayoutRouter": () => (/* reexport default from dynamic */ next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1___default.a), -/* harmony export */ "RenderFromTemplateContext": () => (/* reexport default from dynamic */ next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2___default.a), -/* harmony export */ "StaticGenerationSearchParamsBailoutProvider": () => (/* reexport default from dynamic */ next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8___default.a), -/* harmony export */ "__next_app_webpack_require__": () => (/* binding */ __next_app_webpack_require__), -/* harmony export */ "actionAsyncStorage": () => (/* reexport safe */ next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__.actionAsyncStorage), -/* harmony export */ "createSearchParamsBailoutProxy": () => (/* reexport safe */ next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__.createSearchParamsBailoutProxy), -/* harmony export */ "decodeAction": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.decodeAction), -/* harmony export */ "decodeReply": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.decodeReply), -/* harmony export */ "originalPathname": () => (/* binding */ originalPathname), -/* harmony export */ "pages": () => (/* binding */ pages), -/* harmony export */ "preconnect": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preconnect), -/* harmony export */ "preloadFont": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preloadFont), -/* harmony export */ "preloadStyle": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preloadStyle), -/* harmony export */ "renderToReadableStream": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.renderToReadableStream), -/* harmony export */ "requestAsyncStorage": () => (/* reexport safe */ next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__.requestAsyncStorage), -/* harmony export */ "serverHooks": () => (/* reexport module object */ next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__), -/* harmony export */ "staticGenerationAsyncStorage": () => (/* reexport safe */ next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__.staticGenerationAsyncStorage), -/* harmony export */ "staticGenerationBailout": () => (/* reexport safe */ next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__.staticGenerationBailout), -/* harmony export */ "tree": () => (/* binding */ tree) -/* harmony export */ }); -/* harmony import */ var next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4592); -/* harmony import */ var next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6301); -/* harmony import */ var next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7431); -/* harmony import */ var next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2673); -/* harmony import */ var next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(94); -/* harmony import */ var next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4437); -/* harmony import */ var next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(6127); -/* harmony import */ var next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(5486); -/* harmony import */ var next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(6404); -/* harmony import */ var next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(2527); -/* harmony import */ var next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(3332); -/* harmony import */ var next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(7902); -/* harmony import */ var next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(3099); -/* harmony import */ var next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__); - - const tree = { - children: [ - '', - { - children: [ - 'everyone-votes', - { - children: [ - 'privacy', - { - children: ['__PAGE__', {}, { - page: [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4182)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page.tsx"], - - }] - }, - { - - - } - ] - }, - { - - metadata: { - icon: [(async (props) => (await Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4756))).default(props))], - apple: [], - openGraph: [], - twitter: [], - manifest: undefined - } - } - ] - }, - { - 'layout': [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 729)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"], - metadata: { - icon: [(async (props) => (await Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4756))).default(props))], - apple: [], - openGraph: [], - twitter: [], - manifest: undefined - } - } - ] - }.children; - const pages = ["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page.tsx"]; - - - - - - - - - - - - - - - - - - - const __next_app_webpack_require__ = __webpack_require__ - - - const originalPathname = "/everyone-votes/privacy/page" - - -/***/ }), - -/***/ 3259: -/***/ (() => { - - - -/***/ }), - -/***/ 4182: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Privacy) -/* harmony export */ }); -/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6786); -/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__); - -function Privacy() { - return /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("main", { - className: "ml-[10%] mt-[5%] mr-[10%]", - children: [ - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h1", { - className: "text-3xl", - children: "Everyone Votes Privacy Policy" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h2", { - className: "text-2xl", - children: "What We Store" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h3", { - className: "text-xl", - children: "By voting on a poll with Everyone Votes, we store:" - }), - /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("ul", { - children: [ - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "- The poll option(s) you voted on" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "- Your Discord user id" - }) - ] - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "This data is stored for up to 24 hours, and is wiped every day at UTC midnight." - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "A cumulative count of the number of votes for each poll option is saved indefinitely." - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h3", { - className: "text-xl", - children: "By setting up Everyone Votes, we store:" - }), - /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("ul", { - children: [ - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "- The server id, poll channel ids, and current poll messages" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "- Config settings" - }) - ] - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "This data is stored for as long as Everyone Votes is setup within the server." - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h3", { - className: "text-xl", - children: "By adding server-wide polls on Everyone Votes, we store:" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("ul", { - children: /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "- All of those polls' data" - }) - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command." - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "In summary, I don't use your data for anything malicious, just for getting poll result counts." - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h2", { - className: "text-2xl", - children: "Removal of Data" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure." - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data." - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h2", { - className: "text-2xl", - children: "Contact" - }), - /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("p", { - children: [ - "If you have questions or concerns about these terms, please join the ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("a", { - href: "https://discord.gg/pc6EcNjuZU", - className: "text-blue-500", - children: "support server" - }), - " on Discord, or email ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("span", { - className: "font-mono", - children: "contact@sukadia.dev" - }), - "." - ] - }) - ] - }); -} - - -/***/ }) - -}; -; - -// load runtime -var __webpack_require__ = require("../../../webpack-runtime.js"); -__webpack_require__.C(exports); -var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId)) -var __webpack_exports__ = __webpack_require__.X(0, [405,616,816], () => (__webpack_exec__(6058))); -module.exports = __webpack_exports__; - -})(); \ No newline at end of file +(()=>{var e={};e.id=369,e.ids=[369],e.modules={5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},2668:(e,t,s)=>{"use strict";s.r(t),s.d(t,{GlobalError:()=>i.a,__next_app__:()=>u,originalPathname:()=>p,pages:()=>c,routeModule:()=>x,tree:()=>d});var r=s(7096),a=s(6132),o=s(7284),i=s.n(o),n=s(2564),l={};for(let e in n)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>n[e]);s.d(t,l);let d=["",{children:["everyone-votes",{children:["privacy",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(s.bind(s,2330)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page.tsx"]}]},{}]},{metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(s.bind(s,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(s.t.bind(s,9291,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],c=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page.tsx"],p="/everyone-votes/privacy/page",u={require:s,loadChunk:()=>Promise.resolve()},x=new r.AppPageRouteModule({definition:{kind:a.x.APP_PAGE,page:"/everyone-votes/privacy/page",pathname:"/everyone-votes/privacy",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:d}})},5303:()=>{},2330:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>Privacy});var r=s(4656);function Privacy(){return(0,r.jsxs)("main",{className:"ml-[10%] mt-[5%] mr-[10%]",children:[r.jsx("h1",{className:"text-3xl",children:"Everyone Votes Privacy Policy"}),r.jsx("p",{children:"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:"}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"What We Store"}),r.jsx("h3",{className:"text-xl",children:"By voting on a poll with Everyone Votes, we store:"}),(0,r.jsxs)("ul",{children:[r.jsx("p",{children:"- The poll option(s) you voted on"}),r.jsx("p",{children:"- Your Discord user id"})]}),r.jsx("p",{children:"This data is stored for up to 24 hours, and is wiped every day at UTC midnight."}),r.jsx("p",{children:"A cumulative count of the number of votes for each poll option is saved indefinitely."}),r.jsx("br",{}),r.jsx("h3",{className:"text-xl",children:"By setting up Everyone Votes, we store:"}),(0,r.jsxs)("ul",{children:[r.jsx("p",{children:"- The server id, poll channel ids, and current poll messages"}),r.jsx("p",{children:"- Config settings"})]}),r.jsx("p",{children:"This data is stored for as long as Everyone Votes is setup within the server."}),r.jsx("br",{}),r.jsx("h3",{className:"text-xl",children:"By adding server-wide polls on Everyone Votes, we store:"}),r.jsx("ul",{children:r.jsx("p",{children:"- All of those polls' data"})}),r.jsx("p",{children:"This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command."}),r.jsx("br",{}),r.jsx("p",{children:"In summary, I don't use your data for anything malicious, just for getting poll result counts."}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Removal of Data"}),r.jsx("p",{children:"Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure."}),r.jsx("p",{children:"User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data."}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Contact"}),(0,r.jsxs)("p",{children:["If you have questions or concerns about these terms, please join the ",r.jsx("a",{href:"https://discord.gg/pc6EcNjuZU",className:"text-blue-500",children:"support server"})," on Discord, or email ",r.jsx("span",{className:"font-mono",children:"contact@sukadia.dev"}),"."]})]})}},7481:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var r=s(8531);let __WEBPACK_DEFAULT_EXPORT__=e=>{let t=(0,r.fillMetadataSegment)(".",e.params,"favicon.ico");return[{type:"image/x-icon",sizes:"16x16",url:t+""}]}}};var t=require("../../../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),s=t.X(0,[862,323,622],()=>__webpack_exec__(2668));module.exports=s})(); \ No newline at end of file diff --git a/.next/server/app/everyone-votes/privacy/page.js.nft.json b/.next/server/app/everyone-votes/privacy/page.js.nft.json index bd3de18..1bff456 100644 --- a/.next/server/app/everyone-votes/privacy/page.js.nft.json +++ b/.next/server/app/everyone-votes/privacy/page.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../webpack-runtime.js","../../../chunks/405.js","../../../chunks/616.js","../../../chunks/816.js","../../../../package.json","../../../../../node_modules/next/package.json","../../../../../node_modules/next/dist/shared/lib/app-router-context.js","../../../../../node_modules/next/dist/shared/lib/hooks-client-context.js","../../../../../node_modules/next/dist/shared/lib/server-inserted-html.js","../../../../../node_modules/next/dist/server/app-render/get-segment-param.js","../../../../../node_modules/next/dist/server/future/helpers/interception-routes.js","../../../../../node_modules/react/package.json","../../../../../node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js","../../../../../node_modules/next/dist/shared/lib/router/utils/handle-smooth-scroll.js","../../../../../node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js","../../../../../node_modules/next/dist/shared/lib/router/utils/is-bot.js","../../../../../node_modules/next/dist/shared/lib/router/utils/parse-path.js","../../../../../node_modules/react/index.js","../../../../../node_modules/next/dist/compiled/react/jsx-runtime.js","../../../../../node_modules/next/dist/compiled/react-dom/server-rendering-stub.js","../../../../../node_modules/next/dist/compiled/react-server-dom-webpack/client.js","../../../../../node_modules/next/dist/compiled/react/package.json","../../../../../node_modules/next/dist/compiled/react-dom/package.json","../../../../../node_modules/next/dist/compiled/react-server-dom-webpack/package.json","../../../../../node_modules/next/dist/compiled/path-to-regexp/index.js","../../../../../node_modules/next/dist/compiled/react/index.js","../../../../../node_modules/react/cjs/react.production.min.js","../../../../../node_modules/react/cjs/react.development.js","../../../../../node_modules/next/dist/compiled/cookie/package.json","../../../../../node_modules/next/dist/compiled/cookie/index.js","../../../../../node_modules/next/dist/shared/lib/router/utils/app-paths.js","../../../../../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.production.min.js","../../../../../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.development.js","../../../../../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.production.min.js","../../../../../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.development.js","../../../../../node_modules/next/dist/compiled/react-server-dom-webpack/client.browser.js","../../../../../node_modules/next/dist/compiled/react/cjs/react.production.min.js","../../../../../node_modules/next/dist/compiled/react/cjs/react.development.js","../../../../../node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js","../../../../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.production.min.js","../../../../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.development.js","../../../../../node_modules/@swc/helpers/_/_interop_require_default/package.json","../../../../../node_modules/@swc/helpers/_/_interop_require_wildcard/package.json","../../../../../node_modules/@swc/helpers/package.json","../../../../../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../../../../../node_modules/@swc/helpers/cjs/_interop_require_wildcard.cjs","../../../../../node_modules/react-dom/package.json","../../../../../node_modules/react-dom/index.js","../../../../../node_modules/react-dom/cjs/react-dom.production.min.js","../../../../../node_modules/react-dom/cjs/react-dom.development.js","../../../../../node_modules/scheduler/package.json","../../../../../node_modules/scheduler/index.js","../../../../../node_modules/scheduler/cjs/scheduler.production.min.js","../../../../../node_modules/scheduler/cjs/scheduler.development.js","../../../../../package.json"]} \ No newline at end of file +{"version":1,"files":["../../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../../node_modules/next/package.json","../../../../../package.json","../../../../package.json","../../../chunks/106.js","../../../chunks/2.js","../../../chunks/201.js","../../../chunks/310.js","../../../chunks/323.js","../../../chunks/622.js","../../../chunks/676.js","../../../chunks/837.js","../../../chunks/840.js","../../../chunks/862.js","../../../chunks/984.js","../../../chunks/font-manifest.json","../../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/everyone-votes/privacy/page_client-reference-manifest.js b/.next/server/app/everyone-votes/privacy/page_client-reference-manifest.js new file mode 100644 index 0000000..747de8d --- /dev/null +++ b/.next/server/app/everyone-votes/privacy/page_client-reference-manifest.js @@ -0,0 +1 @@ +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/everyone-votes/privacy/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page":[]}} \ No newline at end of file diff --git a/.next/server/app/everyone-votes/terms.html b/.next/server/app/everyone-votes/terms.html index be33f18..e0d677a 100644 --- a/.next/server/app/everyone-votes/terms.html +++ b/.next/server/app/everyone-votes/terms.html @@ -1 +1 @@ -sukadia.dev

Everyone Votes Terms of Service

Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:


User Conduct

"Users" include any Discord user interacting with Everyone Votes through Discord's slash commands or buttons. Users must adhere to the following guidelines:

Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer.


Paid Content

Everyone Votes offers certain features that require supporting the bot monthly on Ko-fi. In order to gain access to these features, the supporter must be in the Discord support server to properly track subscription status.

Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion.

Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)


Contact

If you have questions or concerns about these terms, please join the support server on Discord, or email contact@sukadia.dev.

I appreciate you for reading these terms, not many do that!

\ No newline at end of file +sukadia.dev

Everyone Votes Terms of Service

Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:


User Conduct

"Users" include any Discord user interacting with Everyone Votes through Discord's slash commands or buttons. Users must adhere to the following guidelines:

Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer.


Paid Content

Everyone Votes offers certain features that require supporting the bot monthly on Ko-fi. In order to gain access to these features, the supporter must be in the Discord support server to properly track subscription status.

Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion.

Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)


Contact

If you have questions or concerns about these terms, please join the support server on Discord, or email contact@sukadia.dev.

I appreciate you for reading these terms, not many do that!

\ No newline at end of file diff --git a/.next/server/app/everyone-votes/terms.meta b/.next/server/app/everyone-votes/terms.meta index 5d31670..f3547ee 100644 --- a/.next/server/app/everyone-votes/terms.meta +++ b/.next/server/app/everyone-votes/terms.meta @@ -1 +1,5 @@ -{"headers":{"x-next-cache-tags":"/everyone-votes/terms/page"}} \ No newline at end of file +{ + "headers": { + "x-next-cache-tags": "_N_T_/layout,_N_T_/everyone-votes/layout,_N_T_/everyone-votes/terms/layout,_N_T_/everyone-votes/terms/page,_N_T_/everyone-votes/terms" + } +} \ No newline at end of file diff --git a/.next/server/app/everyone-votes/terms.rsc b/.next/server/app/everyone-votes/terms.rsc index f3a0f86..cc0b5ae 100644 --- a/.next/server/app/everyone-votes/terms.rsc +++ b/.next/server/app/everyone-votes/terms.rsc @@ -1,6 +1,7 @@ -1:HL["/_next/static/css/3930d1a0ca01c66f.css",{"as":"style"}] -0:[[["",{"children":["everyone-votes",{"children":["terms",{"children":["__PAGE__",{}]}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/3930d1a0ca01c66f.css","precedence":"next"}]],["$L3",null]]]] -4:I{"id":"4463","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -5:I{"id":"1010","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -2:[["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_0ec1f4","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$L5",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$L5",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children","terms","children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$L5",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":[["$","main",null,{"className":"ml-[10%] mt-[5%] mr-[10%]","children":[["$","h1",null,{"className":"text-3xl","children":"Everyone Votes Terms of Service"}],["$","p",null,{"children":"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"User Conduct"}],["$","p",null,{"children":"\"Users\" include any Discord user interacting with Everyone Votes through Discord's slash commands or buttons. Users must adhere to the following guidelines:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- Spamming bot interactions is not allowed."}],["$","p",null,{"children":"- Only one account per person may vote on polls."}],["$","p",null,{"children":["- Follow ",["$","a",null,{"href":"https://discord.com/terms","className":"text-blue-500","children":"Discord's Terms of Service"}],"."]}]]}],["$","p",null,{"children":"Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Paid Content"}],["$","p",null,{"children":["Everyone Votes offers certain features that require supporting the bot monthly on ",["$","a",null,{"href":"https://ko-fi.com/everyonevotes/tiers","className":"text-blue-500","children":"Ko-fi"}],". In order to gain access to these features, the supporter must be in the Discord ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," to properly track subscription status."]}],["$","p",null,{"children":"Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion."}],["$","p",null,{"children":"Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Contact"}],["$","p",null,{"children":["If you have questions or concerns about these terms, please join the ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," on Discord, or email ",["$","span",null,{"className":"font-mono","children":"contact@sukadia.dev"}],"."]}],["$","p",null,{"children":"I appreciate you for reading these terms, not many do that!"}]]}],null],"segment":"__PAGE__"},"styles":[]}],"segment":"terms"},"styles":[]}],"segment":"everyone-votes"},"styles":[]}]}]}],null] -3:[[["$","meta",null,{"charSet":"utf-8"}],["$","title",null,{"children":"sukadia.dev"}],["$","meta",null,{"name":"description","content":"I code, stream, and create videos."}],null,null,null,null,null,null,null,null,["$","meta",null,{"name":"viewport","content":"width=device-width, initial-scale=1"}],null,null,null,null,null,null,null,null,null,null,[]],[null,null,null,null],null,null,[null,null,null,null,null],null,null,null,null,[null,[["$","link",null,{"rel":"icon","href":"\\favicon.ico","type":"image/x-icon","sizes":"any"}]],[],null]] +1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] +0:["9CqSqX2Hqhh4fwiD8kSfJ",[[["",{"children":["everyone-votes",{"children":["terms",{"children":["__PAGE__",{}]}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] +4:I[6954,[],""] +5:I[7264,[],""] +2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children","terms","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$L6",["$","main",null,{"className":"ml-[10%] mt-[5%] mr-[10%]","children":[["$","h1",null,{"className":"text-3xl","children":"Everyone Votes Terms of Service"}],["$","p",null,{"children":"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"User Conduct"}],["$","p",null,{"children":"\"Users\" include any Discord user interacting with Everyone Votes through Discord's slash commands or buttons. Users must adhere to the following guidelines:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- Spamming bot interactions is not allowed."}],["$","p",null,{"children":"- Only one account per person may vote on polls."}],["$","p",null,{"children":["- Follow ",["$","a",null,{"href":"https://discord.com/terms","className":"text-blue-500","children":"Discord's Terms of Service"}],"."]}]]}],["$","p",null,{"children":"Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Paid Content"}],["$","p",null,{"children":["Everyone Votes offers certain features that require supporting the bot monthly on ",["$","a",null,{"href":"https://ko-fi.com/everyonevotes/tiers","className":"text-blue-500","children":"Ko-fi"}],". In order to gain access to these features, the supporter must be in the Discord ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," to properly track subscription status."]}],["$","p",null,{"children":"Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion."}],["$","p",null,{"children":"Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Contact"}],["$","p",null,{"children":["If you have questions or concerns about these terms, please join the ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," on Discord, or email ",["$","span",null,{"className":"font-mono","children":"contact@sukadia.dev"}],"."]}],["$","p",null,{"children":"I appreciate you for reading these terms, not many do that!"}]]}],null],"segment":"__PAGE__"},"styles":null}],"segment":"terms"},"styles":null}],"segment":"everyone-votes"},"styles":null}]}]}],null] +3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +6:null diff --git a/.next/server/app/everyone-votes/terms/page.js b/.next/server/app/everyone-votes/terms/page.js index 2e28582..e6dc224 100644 --- a/.next/server/app/everyone-votes/terms/page.js +++ b/.next/server/app/everyone-votes/terms/page.js @@ -1,407 +1 @@ -(() => { -var exports = {}; -exports.id = 181; -exports.ids = [181]; -exports.modules = { - -/***/ 252: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/cookie"); - -/***/ }), - -/***/ 7999: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/path-to-regexp"); - -/***/ }), - -/***/ 8038: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react"); - -/***/ }), - -/***/ 8704: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react-dom/server-rendering-stub"); - -/***/ }), - -/***/ 7897: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react-server-dom-webpack/client"); - -/***/ }), - -/***/ 6786: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react/jsx-runtime"); - -/***/ }), - -/***/ 1090: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/server/app-render/get-segment-param.js"); - -/***/ }), - -/***/ 8652: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/server/future/helpers/interception-routes.js"); - -/***/ }), - -/***/ 3280: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/app-router-context.js"); - -/***/ }), - -/***/ 9274: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/hooks-client-context.js"); - -/***/ }), - -/***/ 1751: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/add-path-prefix.js"); - -/***/ }), - -/***/ 1668: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/handle-smooth-scroll.js"); - -/***/ }), - -/***/ 1897: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/is-bot.js"); - -/***/ }), - -/***/ 8854: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/parse-path.js"); - -/***/ }), - -/***/ 3297: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/remove-trailing-slash.js"); - -/***/ }), - -/***/ 3349: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/server-inserted-html.js"); - -/***/ }), - -/***/ 1017: -/***/ ((module) => { - -"use strict"; -module.exports = require("path"); - -/***/ }), - -/***/ 7310: -/***/ ((module) => { - -"use strict"; -module.exports = require("url"); - -/***/ }), - -/***/ 8125: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "AppRouter": () => (/* reexport default from dynamic */ next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0___default.a), -/* harmony export */ "GlobalError": () => (/* reexport default from dynamic */ next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3___default.a), -/* harmony export */ "LayoutRouter": () => (/* reexport default from dynamic */ next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1___default.a), -/* harmony export */ "RenderFromTemplateContext": () => (/* reexport default from dynamic */ next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2___default.a), -/* harmony export */ "StaticGenerationSearchParamsBailoutProvider": () => (/* reexport default from dynamic */ next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8___default.a), -/* harmony export */ "__next_app_webpack_require__": () => (/* binding */ __next_app_webpack_require__), -/* harmony export */ "actionAsyncStorage": () => (/* reexport safe */ next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__.actionAsyncStorage), -/* harmony export */ "createSearchParamsBailoutProxy": () => (/* reexport safe */ next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__.createSearchParamsBailoutProxy), -/* harmony export */ "decodeAction": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.decodeAction), -/* harmony export */ "decodeReply": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.decodeReply), -/* harmony export */ "originalPathname": () => (/* binding */ originalPathname), -/* harmony export */ "pages": () => (/* binding */ pages), -/* harmony export */ "preconnect": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preconnect), -/* harmony export */ "preloadFont": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preloadFont), -/* harmony export */ "preloadStyle": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preloadStyle), -/* harmony export */ "renderToReadableStream": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.renderToReadableStream), -/* harmony export */ "requestAsyncStorage": () => (/* reexport safe */ next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__.requestAsyncStorage), -/* harmony export */ "serverHooks": () => (/* reexport module object */ next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__), -/* harmony export */ "staticGenerationAsyncStorage": () => (/* reexport safe */ next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__.staticGenerationAsyncStorage), -/* harmony export */ "staticGenerationBailout": () => (/* reexport safe */ next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__.staticGenerationBailout), -/* harmony export */ "tree": () => (/* binding */ tree) -/* harmony export */ }); -/* harmony import */ var next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4592); -/* harmony import */ var next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6301); -/* harmony import */ var next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7431); -/* harmony import */ var next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2673); -/* harmony import */ var next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(94); -/* harmony import */ var next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4437); -/* harmony import */ var next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(6127); -/* harmony import */ var next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(5486); -/* harmony import */ var next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(6404); -/* harmony import */ var next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(2527); -/* harmony import */ var next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(3332); -/* harmony import */ var next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(7902); -/* harmony import */ var next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(3099); -/* harmony import */ var next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__); - - const tree = { - children: [ - '', - { - children: [ - 'everyone-votes', - { - children: [ - 'terms', - { - children: ['__PAGE__', {}, { - page: [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 2871)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page.tsx"], - - }] - }, - { - - - } - ] - }, - { - - metadata: { - icon: [(async (props) => (await Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4756))).default(props))], - apple: [], - openGraph: [], - twitter: [], - manifest: undefined - } - } - ] - }, - { - 'layout': [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 729)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"], - metadata: { - icon: [(async (props) => (await Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4756))).default(props))], - apple: [], - openGraph: [], - twitter: [], - manifest: undefined - } - } - ] - }.children; - const pages = ["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page.tsx"]; - - - - - - - - - - - - - - - - - - - const __next_app_webpack_require__ = __webpack_require__ - - - const originalPathname = "/everyone-votes/terms/page" - - -/***/ }), - -/***/ 3259: -/***/ (() => { - - - -/***/ }), - -/***/ 2871: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Terms) -/* harmony export */ }); -/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6786); -/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__); - -function Terms() { - return /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("main", { - className: "ml-[10%] mt-[5%] mr-[10%]", - children: [ - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h1", { - className: "text-3xl", - children: "Everyone Votes Terms of Service" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h2", { - className: "text-2xl", - children: "User Conduct" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: '"Users" include any Discord user interacting with Everyone Votes through Discord\'s slash commands or buttons. Users must adhere to the following guidelines:' - }), - /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("ul", { - children: [ - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "- Spamming bot interactions is not allowed." - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "- Only one account per person may vote on polls." - }), - /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("p", { - children: [ - "- Follow ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("a", { - href: "https://discord.com/terms", - className: "text-blue-500", - children: "Discord's Terms of Service" - }), - "." - ] - }) - ] - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer." - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h2", { - className: "text-2xl", - children: "Paid Content" - }), - /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("p", { - children: [ - "Everyone Votes offers certain features that require supporting the bot monthly on ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("a", { - href: "https://ko-fi.com/everyonevotes/tiers", - className: "text-blue-500", - children: "Ko-fi" - }), - ". In order to gain access to these features, the supporter must be in the Discord ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("a", { - href: "https://discord.gg/pc6EcNjuZU", - className: "text-blue-500", - children: "support server" - }), - " to properly track subscription status." - ] - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion." - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)" - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h2", { - className: "text-2xl", - children: "Contact" - }), - /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("p", { - children: [ - "If you have questions or concerns about these terms, please join the ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("a", { - href: "https://discord.gg/pc6EcNjuZU", - className: "text-blue-500", - children: "support server" - }), - " on Discord, or email ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("span", { - className: "font-mono", - children: "contact@sukadia.dev" - }), - "." - ] - }), - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", { - children: "I appreciate you for reading these terms, not many do that!" - }) - ] - }); -} - - -/***/ }) - -}; -; - -// load runtime -var __webpack_require__ = require("../../../webpack-runtime.js"); -__webpack_require__.C(exports); -var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId)) -var __webpack_exports__ = __webpack_require__.X(0, [405,616,816], () => (__webpack_exec__(8125))); -module.exports = __webpack_exports__; - -})(); \ No newline at end of file +(()=>{var e={};e.id=181,e.ids=[181],e.modules={5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},9167:(e,t,s)=>{"use strict";s.r(t),s.d(t,{GlobalError:()=>a.a,__next_app__:()=>u,originalPathname:()=>p,pages:()=>d,routeModule:()=>m,tree:()=>c});var r=s(7096),o=s(6132),n=s(7284),a=s.n(n),i=s(2564),l={};for(let e in i)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>i[e]);s.d(t,l);let c=["",{children:["everyone-votes",{children:["terms",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(s.bind(s,4182)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page.tsx"]}]},{}]},{metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(s.bind(s,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(s.t.bind(s,9291,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],d=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page.tsx"],p="/everyone-votes/terms/page",u={require:s,loadChunk:()=>Promise.resolve()},m=new r.AppPageRouteModule({definition:{kind:o.x.APP_PAGE,page:"/everyone-votes/terms/page",pathname:"/everyone-votes/terms",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:c}})},5303:()=>{},4182:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>Terms});var r=s(4656);function Terms(){return(0,r.jsxs)("main",{className:"ml-[10%] mt-[5%] mr-[10%]",children:[r.jsx("h1",{className:"text-3xl",children:"Everyone Votes Terms of Service"}),r.jsx("p",{children:"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:"}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"User Conduct"}),r.jsx("p",{children:'"Users" include any Discord user interacting with Everyone Votes through Discord\'s slash commands or buttons. Users must adhere to the following guidelines:'}),(0,r.jsxs)("ul",{children:[r.jsx("p",{children:"- Spamming bot interactions is not allowed."}),r.jsx("p",{children:"- Only one account per person may vote on polls."}),(0,r.jsxs)("p",{children:["- Follow ",r.jsx("a",{href:"https://discord.com/terms",className:"text-blue-500",children:"Discord's Terms of Service"}),"."]})]}),r.jsx("p",{children:"Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer."}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Paid Content"}),(0,r.jsxs)("p",{children:["Everyone Votes offers certain features that require supporting the bot monthly on ",r.jsx("a",{href:"https://ko-fi.com/everyonevotes/tiers",className:"text-blue-500",children:"Ko-fi"}),". In order to gain access to these features, the supporter must be in the Discord ",r.jsx("a",{href:"https://discord.gg/pc6EcNjuZU",className:"text-blue-500",children:"support server"})," to properly track subscription status."]}),r.jsx("p",{children:"Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion."}),r.jsx("p",{children:"Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)"}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Contact"}),(0,r.jsxs)("p",{children:["If you have questions or concerns about these terms, please join the ",r.jsx("a",{href:"https://discord.gg/pc6EcNjuZU",className:"text-blue-500",children:"support server"})," on Discord, or email ",r.jsx("span",{className:"font-mono",children:"contact@sukadia.dev"}),"."]}),r.jsx("p",{children:"I appreciate you for reading these terms, not many do that!"})]})}},7481:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var r=s(8531);let __WEBPACK_DEFAULT_EXPORT__=e=>{let t=(0,r.fillMetadataSegment)(".",e.params,"favicon.ico");return[{type:"image/x-icon",sizes:"16x16",url:t+""}]}}};var t=require("../../../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),s=t.X(0,[862,323,622],()=>__webpack_exec__(9167));module.exports=s})(); \ No newline at end of file diff --git a/.next/server/app/everyone-votes/terms/page.js.nft.json b/.next/server/app/everyone-votes/terms/page.js.nft.json index bd3de18..1bff456 100644 --- a/.next/server/app/everyone-votes/terms/page.js.nft.json +++ b/.next/server/app/everyone-votes/terms/page.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../webpack-runtime.js","../../../chunks/405.js","../../../chunks/616.js","../../../chunks/816.js","../../../../package.json","../../../../../node_modules/next/package.json","../../../../../node_modules/next/dist/shared/lib/app-router-context.js","../../../../../node_modules/next/dist/shared/lib/hooks-client-context.js","../../../../../node_modules/next/dist/shared/lib/server-inserted-html.js","../../../../../node_modules/next/dist/server/app-render/get-segment-param.js","../../../../../node_modules/next/dist/server/future/helpers/interception-routes.js","../../../../../node_modules/react/package.json","../../../../../node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js","../../../../../node_modules/next/dist/shared/lib/router/utils/handle-smooth-scroll.js","../../../../../node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js","../../../../../node_modules/next/dist/shared/lib/router/utils/is-bot.js","../../../../../node_modules/next/dist/shared/lib/router/utils/parse-path.js","../../../../../node_modules/react/index.js","../../../../../node_modules/next/dist/compiled/react/jsx-runtime.js","../../../../../node_modules/next/dist/compiled/react-dom/server-rendering-stub.js","../../../../../node_modules/next/dist/compiled/react-server-dom-webpack/client.js","../../../../../node_modules/next/dist/compiled/react/package.json","../../../../../node_modules/next/dist/compiled/react-dom/package.json","../../../../../node_modules/next/dist/compiled/react-server-dom-webpack/package.json","../../../../../node_modules/next/dist/compiled/path-to-regexp/index.js","../../../../../node_modules/next/dist/compiled/react/index.js","../../../../../node_modules/react/cjs/react.production.min.js","../../../../../node_modules/react/cjs/react.development.js","../../../../../node_modules/next/dist/compiled/cookie/package.json","../../../../../node_modules/next/dist/compiled/cookie/index.js","../../../../../node_modules/next/dist/shared/lib/router/utils/app-paths.js","../../../../../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.production.min.js","../../../../../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.development.js","../../../../../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.production.min.js","../../../../../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.development.js","../../../../../node_modules/next/dist/compiled/react-server-dom-webpack/client.browser.js","../../../../../node_modules/next/dist/compiled/react/cjs/react.production.min.js","../../../../../node_modules/next/dist/compiled/react/cjs/react.development.js","../../../../../node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js","../../../../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.production.min.js","../../../../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.development.js","../../../../../node_modules/@swc/helpers/_/_interop_require_default/package.json","../../../../../node_modules/@swc/helpers/_/_interop_require_wildcard/package.json","../../../../../node_modules/@swc/helpers/package.json","../../../../../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../../../../../node_modules/@swc/helpers/cjs/_interop_require_wildcard.cjs","../../../../../node_modules/react-dom/package.json","../../../../../node_modules/react-dom/index.js","../../../../../node_modules/react-dom/cjs/react-dom.production.min.js","../../../../../node_modules/react-dom/cjs/react-dom.development.js","../../../../../node_modules/scheduler/package.json","../../../../../node_modules/scheduler/index.js","../../../../../node_modules/scheduler/cjs/scheduler.production.min.js","../../../../../node_modules/scheduler/cjs/scheduler.development.js","../../../../../package.json"]} \ No newline at end of file +{"version":1,"files":["../../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../../node_modules/next/package.json","../../../../../package.json","../../../../package.json","../../../chunks/106.js","../../../chunks/2.js","../../../chunks/201.js","../../../chunks/310.js","../../../chunks/323.js","../../../chunks/622.js","../../../chunks/676.js","../../../chunks/837.js","../../../chunks/840.js","../../../chunks/862.js","../../../chunks/984.js","../../../chunks/font-manifest.json","../../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/everyone-votes/terms/page_client-reference-manifest.js b/.next/server/app/everyone-votes/terms/page_client-reference-manifest.js new file mode 100644 index 0000000..dbee375 --- /dev/null +++ b/.next/server/app/everyone-votes/terms/page_client-reference-manifest.js @@ -0,0 +1 @@ +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/everyone-votes/terms/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page":[]}} \ No newline at end of file diff --git a/.next/server/app/favicon.ico.meta b/.next/server/app/favicon.ico.meta index b22e0a8..b5516f2 100644 --- a/.next/server/app/favicon.ico.meta +++ b/.next/server/app/favicon.ico.meta @@ -1 +1 @@ -{"status":200,"headers":{"cache-control":"public, max-age=0, must-revalidate","content-type":"image/x-icon","x-next-cache-tags":"/favicon.ico/route"}} \ No newline at end of file +{"status":200,"headers":{"cache-control":"public, max-age=0, must-revalidate","content-type":"image/x-icon","x-next-cache-tags":"_N_T_/layout,_N_T_/favicon.ico/layout,_N_T_/favicon.ico/route,_N_T_/favicon.ico"}} \ No newline at end of file diff --git a/.next/server/app/favicon.ico/route.js b/.next/server/app/favicon.ico/route.js index de85ec2..8a36246 100644 --- a/.next/server/app/favicon.ico/route.js +++ b/.next/server/app/favicon.ico/route.js @@ -1,142 +1 @@ -"use strict"; -(() => { -var exports = {}; -exports.id = 155; -exports.ids = [155]; -exports.modules = { - -/***/ 7783: -/***/ ((module) => { - -module.exports = require("next/dist/compiled/@edge-runtime/cookies"); - -/***/ }), - -/***/ 8530: -/***/ ((module) => { - -module.exports = require("next/dist/compiled/@opentelemetry/api"); - -/***/ }), - -/***/ 4426: -/***/ ((module) => { - -module.exports = require("next/dist/compiled/chalk"); - -/***/ }), - -/***/ 252: -/***/ ((module) => { - -module.exports = require("next/dist/compiled/cookie"); - -/***/ }), - -/***/ 2196: -/***/ ((module) => { - -module.exports = require("next/dist/compiled/ua-parser-js"); - -/***/ }), - -/***/ 4021: -/***/ ((module) => { - -module.exports = import("next/dist/compiled/@vercel/og/index.node.js");; - -/***/ }), - -/***/ 8396: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "headerHooks": () => (/* binding */ headerHooks), - "originalPathname": () => (/* binding */ originalPathname), - "requestAsyncStorage": () => (/* binding */ requestAsyncStorage), - "routeModule": () => (/* binding */ routeModule), - "serverHooks": () => (/* binding */ serverHooks), - "staticGenerationAsyncStorage": () => (/* binding */ staticGenerationAsyncStorage), - "staticGenerationBailout": () => (/* binding */ staticGenerationBailout) -}); - -// NAMESPACE OBJECT: ./node_modules/next/dist/build/webpack/loaders/next-metadata-route-loader.js?page=%2Ffavicon.ico%2Froute&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js!./app/favicon.ico?__next_metadata -var favicon_next_metadata_namespaceObject = {}; -__webpack_require__.r(favicon_next_metadata_namespaceObject); -__webpack_require__.d(favicon_next_metadata_namespaceObject, { - "GET": () => (GET), - "dynamic": () => (dynamic) -}); - -// EXTERNAL MODULE: ./node_modules/next/dist/server/node-polyfill-headers.js -var node_polyfill_headers = __webpack_require__(5387); -// EXTERNAL MODULE: ./node_modules/next/dist/server/future/route-modules/app-route/module.js -var app_route_module = __webpack_require__(9267); -var module_default = /*#__PURE__*/__webpack_require__.n(app_route_module); -// EXTERNAL MODULE: ./node_modules/next/server.js -var server = __webpack_require__(4664); -;// CONCATENATED MODULE: ./node_modules/next/dist/build/webpack/loaders/next-metadata-route-loader.js?page=%2Ffavicon.ico%2Froute&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js!./app/favicon.ico?__next_metadata - - -const contentType = "image/x-icon" -const buffer = Buffer.from("AAABAAMAEBAAAAEAIABoBAAANgAAACAgAAABACAAKBEAAJ4EAAAwMAAAAQAgAGgmAADGFQAAKAAAABAAAAAgAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADg1Ukx1stHl7asSdmmoF75uLcS+bGvQtmppyCXsbF9MQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOPGOQnCuEeaxL10/q6qjf9aW5L/S02N/29xb/+9vbz/3tzR/7a0k/6hnxea4+PGCQAAAAAAAAAAAAAAAOPGOQnFu0PCr9DM/+H7/v/8/v//9PT8/3N44/9qcPb/s7f0///////d3f//mZaR/3h9U8Jxxv8JAAAAAAAAAADHu0Sag6Ka/5Xj+/+k8v7/qfL+/936/v/+/v//h4rv/56h8///////+/v//83N9/9visX/Uaf6mgAAAADg1UkxpLF+/p7u/v9wvfL/kOP+/4bc/f+V7v3/u8bP/8yfqP/Trrv/8ufp/87X+f+Al+//oqX7/1+F7v4+h+8x4tVKl5i+sP+c7/7/cMD0/2S39v9swfj/ku78/8aWov/ZkZz/9NDT/9yzuP98lO3/FTvi/2Rt9P9MdOr/PX31l+LVS9mOsKj/lur9/3LJ/P94we3/Wanz/4Le+/+7Wmf/5be8//nq7P/bkZr/1czk/3R89/94qe7/Tn/r/zx7+tm4r0P6q9rv/4vW9/9uxv3/idb0/2Kx8v9gt/z/ilZt/6EyOf/KXmP/s1dq/5aU+P9zh+7/eNf0/1Cj9f87ePT6uK9E+qbq9f+Z3vb/d8n3/3/P8/93yvb/TJv4/0+F4f+OlbP/hcno/3fE7f9twez/eeH4/1iw8P9DiPr/U4Dr+uLVS9mXr47/m/D9/5br/f93zPr/cMf8/0+c9P9xwPL/eOT7/3Hi+/9r2vn/cOP7/1aw8P8/gPf/Pnz0/4WF+NnczkmXqKhc/42+zf+H1/b/eMv9/3PC/P9wt/z/XK37/1iw+/9Sp/v/Uqb3/02Q8v8+gPb/Pn/4/3SN7f+YkfeXjZKxMZiu7P6i2fP/pev6/5fk+P99xfj/fr76/1uo+/9PoPv/TJv7/0qX+f9IkvT/Uo3r/7/R9P/4+P/+29v/MQAAAAC00fOavfT+/5rb9f+V3PX/gMry/3C79P9oxvv/cN37/125+/9So/L/b9P6/3HU+f+MwvD//Pz9mgAAAAAAAAAA4///CbT3/8Kr9v//pvb//5DV8v93yfL/h9f2/3fp+/935vv/XK/y/4LZ9f981fP/cszvwlVxxgkAAAAAAAAAAAAAAACq//8JqfX/mqb2//6R4/r/b63t/1ye9f+C1/X/fOr7/2a/8v+Z8/7+nfX/mo7j/wkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACn9f8xit3/l12n/9lWn//5gaKB+ZG7p9mAyeeXp/X/MQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAACAAAABAAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADdzEQPk4swWmNcIZuGg2LLnpqM6a+qiv2loxD9uLcS6by7Esu9vBCbtbMOWoiIEQ8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADk10om49VLnePVS/Xj1Uv/49VL/+PVS//czkn/cGsg/8/OFv+3tRL/nJhP/7m2ev+opTf/qaUQ9aumcJ3d3bwmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj41UJ49VLi+LUSvrSxEX/q6E4/4+GNv99d0H/dG9F/3hyQ/94cjH/RkQO/4iIDf+zsGf///////Tz7/+dmW7/1dO3/5WRLfqenA+Ljo4ACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA49VHJN/RSdSZkUL/oqCI/7y8vP/W1t7/qKro/1pg4v8dJeD/HCTj/yIs3P9udd//f4TB/2Rnmf/e3vL/9PT7//Py7v/V08b/mpig/6+sGP+Vkx/U4+O/JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAODRRzLd0EnrgX1X/+/v7////////////////////////////9LU8/9JUNr/GSHY/1lf8v+jqf//hozw/+vr+f/////////////////Pz///kY15/8K/jf+EezfrR1xmMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj1Uck49VL65GLNv+g4uz/q/P+/7f1/v/P+P7/8v3///////////////////r7/v9wdN3/QUfp/2pv//+co/r/wcPu////////////+fn//6ys//+Libv/h4OC/4Z1Df9oj7XratX4JAAAAAAAAAAAAAAAAAAAAAAAAAAA4+NVCePWS9Sglzr/VHCC/57t/v+m8/7/pfL+/6Ty/v+j8v7/wvb+//X9//////////////39/v90eeL/VVn8/3h++P/Exe//////////////////8fH+/7e39P+NjfD/fXiB/1qOzP9YtPrUceP/CQAAAAAAAAAAAAAAAAAAAADj1UuLoJg6/5W3uv+EzPL/br3z/6Hv/v+l8v7/pPL+/6Hx/v+e8f7/oPH9/+D6/v////////////j4/f9cYOP/Sk7p//Pz/P////////////////////////////Pz+v+foOb/RoHi/0qZ+f9TqfuLAAAAAAAAAAAAAAAA5NdKJtPGRfp9kYr/q/P+/5Pm/v9ipub/hNj+/6Xy/v+b6/7/f9X+/5nt/f+Y7/3/k+79/9T4/v/y6ev/yJ2k/7ODl/+ZbZP/5dLV//////////////////z8/v/Y3/r/7/L9/+Tk//+PlPn/Unvi/0WP9PpDlPgmAAAAAAAAAADj1UudiYM3/7nr8/+f8f7/ne7+/3vK9v9frO7/i9/+/3fQ/v90zf7/jeP9/5fv/f+R7v3/id3t/59baP/FipP/8dHU//bU1//Xpqz/yqGo///////3+f7/Rmno/xlE4v8hSeP/hY33/5GR//+Oj/7/WXnk/0GF8p0AAAAA3cxED+PVS/V/h17/tPT9/57w/v+h8v7/etL+/2Cm6P9rxf7/cMn+/3DH/P9+1v3/l+/9/5Dt/P+VlqT/6aaw/+ihq/+9eoT/9tTX//fV2P/mvcH/z6yy/8fR+P8ZROL/GUTi/xlE4v88Uev/fYLz/1Bw4v9Qdeb/O3rs9UR37g/j1Upa49VL/3+KaP+v8/3/m+/+/5jq/v+K3/7/Xaru/1qy+P9anuT/V6Ls/23G/f+U7v3/j+38/7eFkf/lmKT/+bjB/8VzgP/txcn/9tLW//bU1//Gj5b/6uz3/yZO4/8UOOL/EC3i/1Rg8v+Dg///VHHn/zt6+f8+fvr/PoD5WuPUSpvj1Uv/goNK/7Lz/f+c8P3/i+D+/5Pm/v9ht/j/RIPb/5jo+v9Pmen/Yrv9/4Te/f+N6fn/wHB8/9hzgv/rr7f/+e/x//vz9P/43+L/8MDF/9+vtf/jz9L/ydH5/05g7f9aZvL/b4Lt/2mI6P9hc+r/OHLx/zt6+v8/f/qb49ZLzN/SSv9jc2n/oNfy/5vw/f+W6v7/bsf+/2W//v9mp+P/nvH+/1ig6P9asf3/bMT9/43s+/+sXmr/qCk2/75ZZP/05OX///////PZ3P/RbHj/y2t2/9rBxv/Ozv//np7//4uN/f99sOj/jOz7/2ao6f86cen/O3j6/z5++szk1kvqnZQ1/7DZ3/+Fs+X/n+z8/4/k/v9wyP7/aMD8/3i/7P+d8P7/abDp/1Sp+/9XrP3/ftz8/5l8iv+ZICr/nyUu/6AyPv/KX2j/y15n/8xgaf+1T1v/o5nn/5ub//+QkP//bYHs/5vn+f9x5/r/VrD6/0qT5/86dvb/Pn376uPVS/+BgkX/vPT9/7zq+v+BtOf/ftP9/3LL/v9ux/7/dLvr/5zw/f+E2Pj/SZPr/1Km/f9Zrfz/YozM/5UvNP+fNDT/pT1F/8pcXf/KXmD/v1tj/45Sgv+Nj/v/jIz+/3iC9P9XiNv/arfo/2nX9P9YtPr/Spf4/zl15/89fPr/49VL/4GCRv+49P3/nO/8/7Ln+P96tuj/fdL8/3DI/v9ster/m/D9/4jf/f9ZoOf/UKP8/06e/P9Mmvz/YWOj/4Q4Tf+Ea5f/hJrH/4K15P+Lxez/h8Tr/1mN2P9tquT/f9Hx/4fp+v9pxe3/aNT0/0qY+v9Chfr/Qofl/zt28f/k1kvqnZQ1/63Y3v+Y7vz/l+/9/6Pu/P99xe7/dMTz/2m58f+N3vT/lO39/2e79/9Jkev/Spn8/0iT/P9Ihuj/isHs/6bw/P+P7fz/fur7/27b9v9bref/e+X5/3Lo+/9x5/r/buL6/0mX5f9Gj/r/P4D6/0KE+v9Xg+L/e4D06uPWS8zf0kr/cYBq/7Hz/f+X7/3/mfD9/5vw/f+I3v3/ftX8/3vL8f+I3/n/asH9/1Gd7/9GkPT/SYbo/5zg9v+H6/v/duf7/3To+/9z6Pv/XsD0/3Hn+/9y6Pv/cuj7/2/i+v9Xs+7/Pn/v/0GC+v8+fvr/QYP3/2p66/+Qiv/M49RKm+PVS/+8sT7/gJmT/6Px/f+Z8P3/mvD9/5rv/f92zv3/bMT9/2rC/f9kuv3/XLD8/0mT8f9isfD/fer7/3bl+/9t2Pv/dOj7/2jS+/9s2/v/cuj7/3Lo+/9p1vv/VKzx/z5/6P9Agvr/Pn/6/z59+v89cuf/jIn8/5SM/5vj1Upa49VL/+PVS/+wpTr/W29r/5fn+P+Z8P3/luz9/3XM/f9sxP3/aL/9/2+//P91vfz/Vqf8/1Wo+/9lw/v/Vqz7/2zW+/9o0Pv/TZ77/2DC+/9kyvr/Wqr3/z195/88e+v/PoD6/z1++v8/gPr/Pn3z/2d24f+Wjvn/nJP/Wt3MRA/QxEX1hoZI/4aiov+y3+f/ksLr/3u66v9zxfb/dc39/4zQ/f9xwv3/hcf8/4bE/P9xtvz/VqP7/1+l+/9Onfv/UKD7/0ya+/9IlPv/RY36/z6A7/9bkvH/Qob6/0CE+v8+gfr/P4H6/z5+8v92kOf/t7L5/5yV8PV3d90PAAAAAHV7n52BneL/k77q/7vy/P+l8v3/nvD9/4vZ9P9/z/H/ouL4/47Y/f+Cxfz/hsT8/3y7/P9Ypfv/bq/7/0+e+/9NnPv/TJn7/0mW+/9IlPv/SJL5/0iU+/9Ik/v/RpD6/0GH9v9OhOb/t8nu////////////5eL/nQAAAAAAAAAA8vL/JsTD/fqInOn/j7no/5rG7P++8vz/r/P9/6Dw/f+c7vz/fcjy/2mw9P+Fw/z/c7X1/1Om+v9Tpvv/UaT7/1Ci+/9PoPv/Tp77/06e+/9MmfX/SZPv/0aN6/8+fd7/haLg//n6/f///////////+Pi//rDvP8mAAAAAAAAAAAAAAAAqbD2i6LF7f/Z+v//oOj6/4XA6/+LwOv/hsHr/4DE7P93tOf/bcb8/2m4/P9ytO7/V6r7/2XH+/9t2Pv/Z8z7/1as+/9SpPr/VKf3/1So+/9kw/v/dN37/23Q+/9ZrvP/bJ3l/+nu+f//////////iwAAAAAAAAAAAAAAAAAAAAA5VcYJ2fn/1NL6//+r9v//rPb//6v2//+p9v//pvb//4a/6v+V7vz/cdD8/3Oy6/9rvvv/eOn7/3bo+/926Pv/dOT7/1mx+/9TpfL/T5nk/2fF+P9+6Pv/f+r7/37p+/902fv/aaXm//f4/dT///8JAAAAAAAAAAAAAAAAAAAAAAAAAADc+P8kyfr/66v2//+s9v//q/b//6j2//+l9v//er3q/6ft+/+A5vz/YKPp/5bY+/956fv/d+n7/3bo+/946fv/ctz7/1aq+/9fr+j/dMbu/2e46f9ov+v/eNr1/3/p+v974vjrXIDVJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACt9f8yq/b/66v2//+q9v//qPb//6X2//+Z6/v/h77q/4rs/P9yrun/dqzo/5bu/P936fv/d+n7/3np+/976fv/Ybz7/1mo6v+U8f7/mPT//5Ls/P9+zvH/ZKfj61eK1jIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACq+P8kq/f/1Kr2//+o9v//pPb//6D1//95w+z/ot/1/3Cp6f9RlvX/fbbp/5Dt+/946fv/een7/3zq+/9v0Pv/Wajr/5Pu/P+b9f//nPX//5z1/9Sc8f8kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACq//8Jqfb/i6f2//qk9v//oPX//4vh//9amen/UZLu/1Wc//9Okff/aKDm/5ro+f9/6vv/fer7/3bc+/9cqen/mvX//531//qg9v+Lqv//CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAqPj/JqT3/52f9v/1fc///2Gt//9Zov//U5f//1CU//9wx+3/WmVL/4Sytv+V7vz/fOL4/4C15fWm9f+dofj/JgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJnu/w9xwf9aYa3/m1mh/8tRlv/pZrj//WKPf/3f0UnpraM6y3aWlJuTzNVaRGZ3DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAADAAAABgAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//gALSw0sReHAlIlRNG0yOimeDyMWztNfVxdTj4M/uta+E/oqHDf6hoA/upaQO1KemELSnpRCDq6sNTLy8DyKlpQ8RgIAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//0AE5dVJMeHUTHbf0UmxtKk85qOZNv+fljT/mZA0/5SMP/+Ri1T/XVor/8jHFf/FwxT/s7AS/6ShFP+npBn/qKUQ/7W0EebCwRGxs7MRdnhyCjG/v4AEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN/XSCDi1Uqe49RL4+LUSvrj1Uv/49VL/+PVS//j1Uv/49VL/+LUS//WyEb/SkcS/8nIFf/QzxX/yMcU/5OPMP/j4tD/1NK1/6mla/+OiRr/nJcO+pKMU+Ps7NKdv7ePIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAHm2U0U4tNLc+LUSvDi1Ev/281I/9LFRf/Lv0P/xblF/8G2R/++s0j/vLFJ/72ySP/BtUb/oJc3/0E/Dv+RkA//vr0T/6CcLf/r6uP///////n59v+vq4r/sa6H/+jn0P/Fwp7/iIUe8JmXDXOMjA0U//8AAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOPTTEDj1Uu31slG+qidOf+clEr/nZdg/5iUcP9vbnX/OTp7/xsfhv8WG5T/ExmV/xQZkf8dIYj/LjR7/z5AcP9HSGH/UVI7/2VjLv/Kyc///Pz+///////n5tz/uLWX/7i0lP+SjnD/mZUe/7i2EfqioA+3fX0MPwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/AAAB4tVLYuHTS+ijmjf+cm5R/8LBt//j4uD/6+vr//Ly8//s7Pb/3d73/56h6v89Q9f/HCTf/x0l5P8cJOD/HifZ/2Fo4P+jqfT/mqDn/32Cy/+bndP/0tLu/+Xl9f/7+/3/+Pj1//Dv6v/e3e7/mpm8/4uGIf+7uRL+ioY56Ojow2IAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANvbSQfk1kpx4NJK9JqRPP+OjYb/9vb2///////////////////////////////////////z8/z/lJfi/zE41v8dJd3/GSHX/0xR6v+WnP//qbD//5ui+f+go+r/+/z+///////////////////////8/P//s7P//3x3dP+JhD//ycaa/62ocfRdVhdxSW1tBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/wAAAeTWSnHj1UrtoZg1/22Egf/N8PX/2Pn+/+H7/v/u/P7//f///////////////////////////////////9PU8/9hZtz/HSTU/z1C5P9nbP//mJ7//6Kp/P+Sl+r/8PD7///////////////////////x8f//ra3//4mGof+5to//q6dx/31wGf9iYTrteqnJcQD//wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4tVLYuPVS/Tj1Uv/TFAs/6Ho8/+n8/7/qPP+/6vz/v+v8/7/uvX+/+D6/v/8///////////////////////////////t7fr/am7Z/ysy1v9aXv//Zmv//6Kp/v+Kj+n/6er5//////////////////v7///Nzf//oKD//5ST7v+HhLD/f3yg/3ZpEf9zc0f/grfh9GvY+mIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAHj00xA5NVL6NLFRv+Bfjr/NU9j/6Hv/v+m8/7/pvP+/6bz/v+l8v7/pPL+/6Py/v+19P7/5Pv///n+////////////////////////+/v+/2lu3P9OU/P/V1v//3p//f+Ijen/6ur5///////////////////////+/v//29v8/6Gh8/+Vlfj/kpL6/4B8mP9eZ1j/ca7p/1av+uhp2/s/AP//AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAObZTRTj1Uu3zcBD/m5uQP+JrbL/W5TZ/3/R+f+f7f7/pvP+/6by/v+l8v7/pPL+/6Ly/v+g8f7/ofH+/7/1/v/q/P7//v///////////////////+jp+f9pbeL/Ulb5/1lc+v+Giuf/8vL7//////////////////////////////////f3/f/T0/H/ra3q/4aG2/9adK7/Upvx/0yd+v5Zt/m3Wb/yFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOLTS3PYy0f6V1Qq/6bGy/+n7fz/fcTv/1ie5v+J3f7/o/D+/6by/v+l8v7/pPL+/6Ly/v+g8f7/nfD9/5rw/f+m8f3/4/v+//////////////////7+///P0PL/R0zf/09T8/+doOf//v7/////////////////////////////////////////////+Pj9/9HR9v9vguD/QHvh/0mW+P9Mnvr6Tp34cwAAAAAAAAAAAAAAAAAAAAAAAAAA39dIIOHTSvCOhzX/k6yq/7n1/v+h8v7/i9/+/1yb4P9twPb/leX+/6Xy/v+k8v7/n+/+/4zg/v+M4f7/nO/9/5nw/f+V7v3/le/9/9z5/v/8////+PP0/+TR1P/Koaf/hVaD/2lHkv/Yytn/+vf3/////////////////////////////f3///P1/f/z9f3//f3///b2//+ys///fIrv/0Vz2v9Fi/D/SZf68EiP/yAAAAAAAAAAAAAAAAD//0AE4tVKntDDRf93f17/uuXs/6Lx/v+h8v7/juH+/3/M9f9epef/eM78/57t/v+Y6f7/gNf+/3XO/v9/1v7/me39/5nw/f+V7v3/kO79/5Tu/P/D3OT/toKM/72Ejf/ftLr/5bzA/9iorv/FjZX/wpKa/+jY2//////////////////t8P3/mq3y/2iE7P9ohOz/lKfx/9fZ/f+np///lZX//4iO+P9YeuT/QYLr/0aR+p1AgP8EAAAAAAAAAADl1Ukx49RL47mvQ/9+lZX/s/L9/5/x/v+h8f7/n+/+/3fO/f9nq+f/aLz3/4HX/v980/7/dc7+/3XN/v93z/7/luv9/5jw/f+U7v3/j+79/4rk8/+Lf47/ql1p/7Jlcv/Ikpn/89PW//bV2P/00dT/573B/7Z5g//fyMz///////v8/v+QpfH/IUrj/xlE4v8ZROL/HETj/0td7P+Ulf//jo7//4yM//+JjPv/U3Tf/z1+7ONEjfoxAAAAAP//gALh1Ex24tRK+o6KPv+bu7//pvL9/57x/v+g8f7/ovL+/3/V/v9vvfP/V5/o/2zG/v9wyf7/csv+/3LK/f9yyv7/jOP9/5jw/f+U7v3/j+38/4vH1v+9gY3/6aOu/+igqv+9bnr/1aWr//bU1//31dj/99XY/+7Hy/+8hI3/7+Tm/+3w/f9Wdun/GUTi/xlE4v8ZROL/GUTi/yJA5f92evL/dH3s/2B26P9jeev/YHno/zVs2fpBhvl2AID/AuHSSxHk1Uux49VL/3h3PP+oztP/o/H9/5zw/v+b7f7/ofH+/5Hk/v9vx/3/To3e/2O+/f9mv/z/WqXs/1uo7f9ux/7/e9P9/5fv/f+T7v3/ju38/5CMm//bmKP/6J+q//e1v//poq3/qlxo//TQ1P/209f/9tTX//bU1//brLH/w5ad/+/y/f9dfOr/GUTi/xhC4v8VO+L/FDji/yA55v97fvv/gIP8/0ps3f82b+f/OXbu/z199f8/gvuxPHjwEejaSyLi1Uvm49VL/358Pf+jytD/ofH9/5zx/v+S5v7/nO7+/5vs/v9vyf7/Wp/n/1Om8v9Omuj/dbvr/0iK4P9pwv3/bMT9/5Ps/f+S7v3/ju38/5tjcf/noKv/5pmk//Svuv/zrLf/sFdl/+Cyt//20dX/9tLW//bT1v/00dT/rGhy//Tv8f+arvL/IErj/xU64v8RLuL/Dyri/0JS7v+Ghv//goL//3B79P85bub/O3r6/z19+v8+gPnmPID/IuHTSkzj1Uv/49VL/52XQf+PsbT/ovH9/5zw/f+W6v7/iN3+/5vt/v950f7/X7Dz/0KH4P9mq+b/mur7/0SE3f9ivP3/ZL39/4Da/f+R7v3/jOj3/6pea//cgI3/44qX/+6msP/01Nj/8uLl//Xq6//66On/9tPX//TLzv/1z9L/y5Oa/9a6vv/3+P7/hpvw/ydC5v8kPOb/RVTu/4CG+f9pfuv/cX7y/3N69v9Gb+b/OXb3/zt5+v89ffr/PID4TOLVS4Xj1Uv/49VL/6SeQP90kJ7/p/D8/5vw/f+d8P7/hdz+/37U/v9yy/7/YLn7/z1z0f+K1PP/nvH+/06N3f9asvv/X7b9/2zE/f+O6/3/jOf3/6hbaP/IXmz/vkVU/8hib//78/T/////////////////9d/i/92Nl//imqL/0o2V/8Wco///////1NT//5ye/f+Pkvz/j4///2eA5/+Cvur/dLrp/2SN4/9BbN//OXT2/zp4+v88fPr/P4D5hePVS7Xj1Uv/2cxI/01XTf9/qtj/rOb4/5rw/f+d8P3/len+/2/I/v9rxP7/ZL7+/02G2P+d7v3/nvH+/2et5/9PoPP/WbD9/1+2/f+A3P3/jO38/5VWZP+1SVX/picz/6wwPP/OhIz/9Obn///////9+vr/5a+1/9Bpdv/Ra3f/w2Fu/8SZof/v7///srL//56e//+UlP//g4f6/2SW3v+e7fv/eun6/2i69v9XkOH/OnPw/zp3+v88e/r/P3/5teTVS9fj1Uv/hHws/4yttP+cyu7/lcLr/6Lw/f+a7v3/kOX+/3HJ/v9txv7/Zb37/12c3/+e8f7/nPD+/4HP9P9Jken/Vaz9/1et/f9qw/z/iOr8/4p/jv+pQkz/nCEr/6AkLv+mKjX/mjNB/8hgav/NZG7/zF9q/81ha//NY23/rklW/6aNx/+lpf//nJz//5SU//+MjP//XXjk/5ra9P+J6/v/cef6/2PM+v9PmfX/PXrb/zt2+P88e/r/P3761+PVS/Lf0kr/TU4s/8Hv9v/D8vz/hLHl/4/H7v+N3/3/etH+/3LK/v9vyP7/acH8/16e4P+e8f7/nPD9/4LV+P9VnOf/Uqb6/1So/f9YrPz/dtP8/3yw0P+TO0n/mSYs/5wpLv+jMjn/nDQ//8lYXv/JWmD/ylxh/8tdYv/FWWD/lEVk/5qW9/+Wlv//kpL//42N//99hPf/bqDl/6Dw/P915/r/cef6/2jW+v9Chfr/UaXr/zZu5f88evr/Pn368uPVS//SxUb/V2JQ/8H1/f+08/3/w/D8/4Ow5f+FxvD/etH+/3PL/v9xyv7/bsb+/1eX3/+c8P7/m/D9/4rh/P9jquf/UJ/1/1Km/f9RpPz/Vaj8/1af8v9xUnz/lzEy/583Nf+ZMzn/t01Q/8tdXf/MX17/yGBh/7tdaP+bRVn/g2m4/4aL9f+LjP7/iYr+/3J/8P9Obtv/ToXW/1qW3P9VpOH/bd73/2fU+v8/f/r/Uab5/zt42v88evn/Pn36/+PVS//RxEX/WGNS/8H1/f+d7/z/rPH9/7/v+/+AsuX/gs3y/3rQ/f9zy/7/cMf+/12i5f+R4/j/mvD9/5Pp/f9wwPP/S5Dl/1Gl/f9Pofz/T5/8/02c/P9ShNv/ez9b/5U5PP+WQlH/oGZ//31xpP9kfMH/YJHY/22j4P91reP/dKzj/2GW2/9JedL/VYva/3e35/+R2/T/lez7/4Hh9/9dtef/bd73/1q4+v8+ffr/Ro76/0aR4P87d/P/PXr3/+PVS/Lf0Un/TU8t/7/v9v+m8f3/lO79/6Hw/f+r6vr/iMHr/3m/7P95zPj/csr9/2q68v99x+z/me/9/5Xt/f960vz/Vpvj/0qX8v9On/z/S5r8/0qY/P9IlPv/SnfV/15Vk/99lsj/i8Hq/5/f9f+k7vv/nfD8/5bv/P+M4Pb/eLfn/2605v980vL/hur7/3vp+v9y5/r/cef6/2XP8v9Nnef/Wrn6/0SJ+v8+fvr/Q4b6/0uV3/9IceX/UHTq8uTVS9fj1Uv/g3ss/4qrsP+08/3/lu79/5bu/f+a8P3/nu/8/5De9/93wO3/cb7v/3HG+v9tt+n/kuf4/5fv/f+A2P3/aL35/0eI3/9Mm/n/SZb8/0eS/P9BhO//V43f/6Ha9P+s7fv/le77/4Dq+/966fv/dun7/3Dh+P9Wquf/aczy/3Xm+v9z6Pv/cuj7/3Hn+v9x5/r/atn6/0yd4/9Ag/H/Qof6/0CA+v8+ffr/Roz6/0yH3v+Agvf/iIb71+PVS7Xj1Uv/2cxI/0xUQv+35ez/nvD9/5bu/f+Y8P3/mvD9/5vw/f+R5/3/gdj8/4bb+/96zvf/fMfq/4/n+/+F3v3/Zbv9/1mp8/9Eien/SJX7/0OK9P9gl+P/q+n5/5rv/P996vv/duf7/3Xo+/9z6Pv/c+j7/2XO9f9dvfL/cuf7/3Lo+/9y6Pv/cuj7/3Hm+v9q2vr/Wbbv/zl14f9Ch/r/QIL6/z9/+v8+ffr/SI/4/0xv3P+OiP//kIr/teLVS4Xj1Uv/49VL/6WdPf96j4f/tOz1/5jv/f+Y8P3/mvD9/5vw/f+b8P3/j+X9/3PL/f91zP3/d8z4/3jM9v9sw/3/Y7n9/1uv+/9LlO//Qonu/0iG4P+I1PX/h+z7/3rp+/915fv/cuH7/3To+/9z6Pv/cOL7/2DF+v9w4/v/cuj7/3Lo+/9y6Pv/cuj7/2jV+v9YtfH/P4Lg/0CD9/9Bg/r/P4D6/z59+v8+fPr/OnTo/2166/+Riv//kor/heHTSkzj1Uv/49VL/97QSf+Jgzj/f5iX/7Tz/f+Y8P3/mvD9/5rw/f+a8P3/mvD9/3/W/f9uxv3/a8P9/2nB/f9nvv3/Y7n9/16z/P9WqPv/SpX0/1ak8P953vv/fOr7/3jn+/9pz/v/ceD7/3Xo+/9y5Pv/W7n7/2zb+/9y6Pv/cuj7/3Lo+/9w5Pv/Xbz7/1Gn9f9BhuH/Pn/z/0CC+v8/gPr/Pn76/z5++v8+fPf/Q23c/4+L/f+Ujf//lI3/TOjaSyLj1Uvm49VL/+PVS//g0kr/d3Ao/2J3dv+b3ej/me/8/5rw/f+a8P3/mO79/33U/f9uxv3/a8P9/2nA/f9mvv3/a7z8/227/P9er/z/UqL8/1Ki/P9u0Pv/cdj7/1+7+/9ct/v/cuL7/3Hi+/9fv/v/TZz7/2TJ+/9v4Pv/bd37/2fM+v9Lmff/RY7t/zt53f87fPP/PoD6/z5/+v8+f/r/P4D6/0CA+f89c+X/d4Dt/5eP/P+Zkf7mnpb/IuHSSxHk1Uux49VL/9rNSP+flzn/h4lR/2R0a/93nrn/e73q/5Hg+P+L4v3/f9b9/3HI/f9zyP3/fcn9/2zB/f9tv/3/hcf8/4fF/P96vfz/Wqn8/1Cf/P9Tn/v/T577/1Cg+/9Vqfv/YsX7/1q0+/9Nnfv/SZX7/0mW+/9Nnfb/RIzt/1SK7f9Mgun/Onjq/z+A+P8+gPr/Pn/6/z1++v8+f/r/QYL6/z966/9keeH/jIbr/46G6/+Qh+6xlofwEf//gALf0kl2sKY6+mJjOP+MqaX/td3j/7vs8/+37Pn/rdv0/3yu5P9mqOT/e832/3zU/f+Bz/3/j9H9/33I/f90wv3/icj8/4fF/P+Ewfz/bLL8/1Sj+/9srfv/W6P7/02c+/9Onfv/Tp37/0ya+/9Jlvv/R5L7/0aP+/9Eivn/QYb3/1CO9/9Vk/n/Qof7/0GG+/8/g/r/P4L6/z+C+v9Ag/n/OXbl/3mU5P/Dwvv/zMn9/6+q+/qel/Z2gID/AgAAAAA5OSoxUV+H416F0/+Wwez/uOX4/7zz/P+l8v3/nPD9/6Dx/f+b5vn/eL/r/2626P+Fye7/n932/57j/f9/y/z/h8f8/4bF/P+Ewfz/d7j8/1Wk+/9vr/v/Z6r7/06d+/9Onfv/TJv7/0ya+/9Klvv/SJT7/0eS+/9Hkfv/R5H7/0eR+/9Hkfv/R5D7/0WO+/9Di/r/QYb4/0GC8v9ShOL/sMLr/////////////////+/u/+Osp/8xAAAAAAAAAAD///8E09P8nbi6+P+Wo+3/cJPe/4q35/+z4fb/u/T9/6vz/f+d8P3/mPD9/5fv/f+b7/3/q/D9/57l/f91xvv/gL/4/4bE/P+Ewfz/dLX4/1Ok+v9dqfv/XKj7/1Ci+/9QoPv/Tp77/02d+/9Mm/v/TJr7/0uZ+/9Kl/n/R5Dy/0WN8P9GjfD/Ro3w/0OI7v9Ihej/aJbo/5m06f/b4/X//f7/////////////9/b//+Df/56/v/8EAAAAAAAAAAAAAAAA9/f/IM/P/vCusvn/b5He/7fe9f+BruT/hrLm/8Hu+v/F9v7/ufT9/6ny/f+f8P3/lur8/3fB7/9Wn+n/cLf3/4bE/P+Dwfz/Za3t/1Sn+/9Up/v/VKb7/1Kl+/9RpPv/UKP7/1Ch+/9PoPv/T5/7/0+f+/9Qofv/T5/4/0+f9/9NmvP/SJLt/0KF4/9Rgtn/pbrn//n7/f/////////////////19P//zMn/8L+3/yAAAAAAAAAAAAAAAAAAAAAAAAAAALy8+3OIner6utz0/9r7///A9v7/kNTy/2yf3/91puH/hbXn/3+x5f9uo+D/Z6Xh/2Wh4P9vvfT/Zbz8/266/P9nrPX/gsLw/1eq+/9Yrfv/YL37/2fM+/9lyfv/W7b7/1Oo+/9RpPv/UaP7/1Ol+f9Tpvv/VKf7/1mw+/9s0fv/b9T7/2bF+/9asfn/SpTq/2OQ3v/T3vT//f3+///////////6//3/cwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHOM2RScvO231PT9/tr7///A+P//qvX//6r1/v+p7vz/oOT4/57n+v+l8v3/pvb//3Gv5f+Y3/j/g+P8/2zI/P9Qm+//ltT0/12v+/9nyfv/d+f7/3fp+/926Pv/dOX7/2rS+/9Zsvv/U6b6/1Ki8P9VpvH/Wa76/2C7+/975/v/fur7/33q+/965Pv/cNT6/2C59v9ineb/x9Xx//////7///+3////FAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/wHO8/s/2/v/6Nj7//+59///rPb//6z2//+s9v//q/b//6r2//+o9v//pfb//3q86v+e2vP/je38/3/j/P9WpfD/jcfv/3i//P9w2fv/eOn7/3bo+/926fv/duj7/3fo+/9t1/v/WK37/1Wo+f9NluT/S5Hd/2O88/912/v/f+n7/4Dq+/9/6vv/fun7/3zm+/9v0fj/WZPf/+fs+Oj///9A////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2/z/YtX7//Sz9///rPb//6z2//+s9v//q/b//6n2//+n9v//pfb//47a9P+MwOr/lu78/4Pp/P9ow/j/ZqDi/5zV/P963/v/eOn7/3fp+/936Pv/duj7/3fp+/946fv/aMr7/1aq+/9ZrvL/Y7Hm/2ez5/9apeL/b8rw/3jb9v974fj/fub5/4Dp+/9/6vv/cdP19FuC1WIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AdD9/3Gu9v/tq/b//6z2//+r9v//q/b//6n2//+n9v//pPb//5np+/98t+f/p+r5/4Tr/P9/2vz/Vo3b/4zB7v+W5fz/e+n7/3fp+/936fv/d+n7/3jp+/956fv/eeb7/1y0+/9guvr/UZbe/5Tz//+O6Pr/eMjv/2686v9quen/aLjp/2W36P9mt+jteNv2cQD//wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALb//wes+P9xq/b/9Kv2//+r9v//qvb//6n2//+n9v//pPb//6D0//93vuv/ntPx/5bu/P+W6/z/VYze/1SO4v+e2fT/ke77/3fp+/936fv/eOn7/3jp+/966fv/fOr7/23P+/9ft/v/T5bf/5Ht/P+X9P//mPX//5j0//+U7fz/j+b6/4bZ9fRhmd1xbbbbBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8BrPf/Yqv2/+ir9v/+qvb//6j2//+m9v//pPb//6H1//+W6/v/YZze/63n+P+l5/j/U4zi/1ac+f9dl+P/o9/2/4zt+/956fv/eOn7/3np+/966fv/fOr7/3jg+/9hufz/Upvh/47n+v+Z9f//mvX//5v1//+c9f/+m/X/6Jz1/2IA//8BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKr3/z+q9/+3qfb/+qj2//+m9v//o/b//6H1//+d9f//fc71/2ad4v+DuOf/VZbw/1if//9PkvX/WZPl/47L7v+W7fv/fer7/3np+/976fv/fer7/3vk+/9oxfz/TpLe/5bx/f+b9f//nPX//531//qd9f+3m/P/QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wGm8v8UqfT/c6j2//Cm9v//o/b//6D1//+d9f//e87//1uj9f9Ni+X/Vp36/1ac//9TmP//T5P7/02J6P96s+f/p+77/4fr+/976fv/fur7/3zm+/9uzPr/VZje/5r1//+c9f//nvX/8J30/3Om8v8U////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/3/yCm9/+do/b/45/1//qb8v//cL7//2Ku//9eqP//WKH//1SZ//9Rlf//UJP//2a4/P9Tj6X/V21n/53R1/+W6vb/hOv7/37n+/9mu+3/k8Tt+qP2/+Od9f+en/f/IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC///8EofX/MaD0/3aT6f+xbLn/5mKu//9dp///WJ///1OY//9Qk///Xan//3rX5v9yhVb/tKg7/3p7QP94l4//ouLr/5Xo9eZfocexsdrudsb6/zG///8EAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID//wKH0v8Rabz/ImGr/0xdp/+DVqD/tFKY/9RRl//ue9z//mGdmf6nnzru49VL1NnMSLSKhjqDeZeXTKzo+CJah5YRgICAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==", 'base64' - ) - -function GET() { - return new server.NextResponse(buffer, { - headers: { - 'Content-Type': contentType, - 'Cache-Control': "public, max-age=0, must-revalidate", - }, - }) -} - -const dynamic = 'force-static' - -;// CONCATENATED MODULE: ./node_modules/next/dist/build/webpack/loaders/next-app-loader.js?page=%2Ffavicon.ico%2Froute&name=app%2Ffavicon.ico%2Froute&pagePath=private-next-app-dir%2Ffavicon.ico&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Ffavicon.ico&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=! - - - - - - - - const routeModule = new (module_default())({ - userland: favicon_next_metadata_namespaceObject, - pathname: "/favicon.ico", - resolvedPagePath: "next-metadata-route-loader?page=%2Ffavicon.ico%2Froute&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\favicon.ico?__next_metadata", - nextConfigOutput: undefined, - }) - - // Pull out the exports that we need to expose from the module. This should - // be eliminated when we've moved the other routes to the new format. These - // are used to hook into the route. - const { - requestAsyncStorage, - staticGenerationAsyncStorage, - serverHooks, - headerHooks, - staticGenerationBailout - } = routeModule - - const originalPathname = "/favicon.ico/route" - - - -/***/ }) - -}; -; - -// load runtime -var __webpack_require__ = require("../../webpack-runtime.js"); -__webpack_require__.C(exports); -var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId)) -var __webpack_exports__ = __webpack_require__.X(0, [405,572], () => (__webpack_exec__(8396))); -module.exports = __webpack_exports__; - -})(); \ No newline at end of file +"use strict";(()=>{var A={};A.id=155,A.ids=[155],A.modules={517:A=>{A.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},8837:(A,v,f)=>{f.r(v),f.d(v,{headerHooks:()=>t,originalPathname:()=>p,requestAsyncStorage:()=>j,routeModule:()=>L,serverHooks:()=>o,staticGenerationAsyncStorage:()=>u,staticGenerationBailout:()=>a});var P={};f.r(P),f.d(P,{GET:()=>GET,dynamic:()=>b});var r=f(884),n=f(6132),e=f(1057);let z=Buffer.from("AAABAAMAEBAAAAEAIABoBAAANgAAACAgAAABACAAKBEAAJ4EAAAwMAAAAQAgAGgmAADGFQAAKAAAABAAAAAgAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADg1Ukx1stHl7asSdmmoF75uLcS+bGvQtmppyCXsbF9MQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOPGOQnCuEeaxL10/q6qjf9aW5L/S02N/29xb/+9vbz/3tzR/7a0k/6hnxea4+PGCQAAAAAAAAAAAAAAAOPGOQnFu0PCr9DM/+H7/v/8/v//9PT8/3N44/9qcPb/s7f0///////d3f//mZaR/3h9U8Jxxv8JAAAAAAAAAADHu0Sag6Ka/5Xj+/+k8v7/qfL+/936/v/+/v//h4rv/56h8///////+/v//83N9/9visX/Uaf6mgAAAADg1UkxpLF+/p7u/v9wvfL/kOP+/4bc/f+V7v3/u8bP/8yfqP/Trrv/8ufp/87X+f+Al+//oqX7/1+F7v4+h+8x4tVKl5i+sP+c7/7/cMD0/2S39v9swfj/ku78/8aWov/ZkZz/9NDT/9yzuP98lO3/FTvi/2Rt9P9MdOr/PX31l+LVS9mOsKj/lur9/3LJ/P94we3/Wanz/4Le+/+7Wmf/5be8//nq7P/bkZr/1czk/3R89/94qe7/Tn/r/zx7+tm4r0P6q9rv/4vW9/9uxv3/idb0/2Kx8v9gt/z/ilZt/6EyOf/KXmP/s1dq/5aU+P9zh+7/eNf0/1Cj9f87ePT6uK9E+qbq9f+Z3vb/d8n3/3/P8/93yvb/TJv4/0+F4f+OlbP/hcno/3fE7f9twez/eeH4/1iw8P9DiPr/U4Dr+uLVS9mXr47/m/D9/5br/f93zPr/cMf8/0+c9P9xwPL/eOT7/3Hi+/9r2vn/cOP7/1aw8P8/gPf/Pnz0/4WF+NnczkmXqKhc/42+zf+H1/b/eMv9/3PC/P9wt/z/XK37/1iw+/9Sp/v/Uqb3/02Q8v8+gPb/Pn/4/3SN7f+YkfeXjZKxMZiu7P6i2fP/pev6/5fk+P99xfj/fr76/1uo+/9PoPv/TJv7/0qX+f9IkvT/Uo3r/7/R9P/4+P/+29v/MQAAAAC00fOavfT+/5rb9f+V3PX/gMry/3C79P9oxvv/cN37/125+/9So/L/b9P6/3HU+f+MwvD//Pz9mgAAAAAAAAAA4///CbT3/8Kr9v//pvb//5DV8v93yfL/h9f2/3fp+/935vv/XK/y/4LZ9f981fP/cszvwlVxxgkAAAAAAAAAAAAAAACq//8JqfX/mqb2//6R4/r/b63t/1ye9f+C1/X/fOr7/2a/8v+Z8/7+nfX/mo7j/wkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACn9f8xit3/l12n/9lWn//5gaKB+ZG7p9mAyeeXp/X/MQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAACAAAABAAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADdzEQPk4swWmNcIZuGg2LLnpqM6a+qiv2loxD9uLcS6by7Esu9vBCbtbMOWoiIEQ8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADk10om49VLnePVS/Xj1Uv/49VL/+PVS//czkn/cGsg/8/OFv+3tRL/nJhP/7m2ev+opTf/qaUQ9aumcJ3d3bwmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj41UJ49VLi+LUSvrSxEX/q6E4/4+GNv99d0H/dG9F/3hyQ/94cjH/RkQO/4iIDf+zsGf///////Tz7/+dmW7/1dO3/5WRLfqenA+Ljo4ACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA49VHJN/RSdSZkUL/oqCI/7y8vP/W1t7/qKro/1pg4v8dJeD/HCTj/yIs3P9udd//f4TB/2Rnmf/e3vL/9PT7//Py7v/V08b/mpig/6+sGP+Vkx/U4+O/JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAODRRzLd0EnrgX1X/+/v7////////////////////////////9LU8/9JUNr/GSHY/1lf8v+jqf//hozw/+vr+f/////////////////Pz///kY15/8K/jf+EezfrR1xmMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj1Uck49VL65GLNv+g4uz/q/P+/7f1/v/P+P7/8v3///////////////////r7/v9wdN3/QUfp/2pv//+co/r/wcPu////////////+fn//6ys//+Libv/h4OC/4Z1Df9oj7XratX4JAAAAAAAAAAAAAAAAAAAAAAAAAAA4+NVCePWS9Sglzr/VHCC/57t/v+m8/7/pfL+/6Ty/v+j8v7/wvb+//X9//////////////39/v90eeL/VVn8/3h++P/Exe//////////////////8fH+/7e39P+NjfD/fXiB/1qOzP9YtPrUceP/CQAAAAAAAAAAAAAAAAAAAADj1UuLoJg6/5W3uv+EzPL/br3z/6Hv/v+l8v7/pPL+/6Hx/v+e8f7/oPH9/+D6/v////////////j4/f9cYOP/Sk7p//Pz/P////////////////////////////Pz+v+foOb/RoHi/0qZ+f9TqfuLAAAAAAAAAAAAAAAA5NdKJtPGRfp9kYr/q/P+/5Pm/v9ipub/hNj+/6Xy/v+b6/7/f9X+/5nt/f+Y7/3/k+79/9T4/v/y6ev/yJ2k/7ODl/+ZbZP/5dLV//////////////////z8/v/Y3/r/7/L9/+Tk//+PlPn/Unvi/0WP9PpDlPgmAAAAAAAAAADj1UudiYM3/7nr8/+f8f7/ne7+/3vK9v9frO7/i9/+/3fQ/v90zf7/jeP9/5fv/f+R7v3/id3t/59baP/FipP/8dHU//bU1//Xpqz/yqGo///////3+f7/Rmno/xlE4v8hSeP/hY33/5GR//+Oj/7/WXnk/0GF8p0AAAAA3cxED+PVS/V/h17/tPT9/57w/v+h8v7/etL+/2Cm6P9rxf7/cMn+/3DH/P9+1v3/l+/9/5Dt/P+VlqT/6aaw/+ihq/+9eoT/9tTX//fV2P/mvcH/z6yy/8fR+P8ZROL/GUTi/xlE4v88Uev/fYLz/1Bw4v9Qdeb/O3rs9UR37g/j1Upa49VL/3+KaP+v8/3/m+/+/5jq/v+K3/7/Xaru/1qy+P9anuT/V6Ls/23G/f+U7v3/j+38/7eFkf/lmKT/+bjB/8VzgP/txcn/9tLW//bU1//Gj5b/6uz3/yZO4/8UOOL/EC3i/1Rg8v+Dg///VHHn/zt6+f8+fvr/PoD5WuPUSpvj1Uv/goNK/7Lz/f+c8P3/i+D+/5Pm/v9ht/j/RIPb/5jo+v9Pmen/Yrv9/4Te/f+N6fn/wHB8/9hzgv/rr7f/+e/x//vz9P/43+L/8MDF/9+vtf/jz9L/ydH5/05g7f9aZvL/b4Lt/2mI6P9hc+r/OHLx/zt6+v8/f/qb49ZLzN/SSv9jc2n/oNfy/5vw/f+W6v7/bsf+/2W//v9mp+P/nvH+/1ig6P9asf3/bMT9/43s+/+sXmr/qCk2/75ZZP/05OX///////PZ3P/RbHj/y2t2/9rBxv/Ozv//np7//4uN/f99sOj/jOz7/2ao6f86cen/O3j6/z5++szk1kvqnZQ1/7DZ3/+Fs+X/n+z8/4/k/v9wyP7/aMD8/3i/7P+d8P7/abDp/1Sp+/9XrP3/ftz8/5l8iv+ZICr/nyUu/6AyPv/KX2j/y15n/8xgaf+1T1v/o5nn/5ub//+QkP//bYHs/5vn+f9x5/r/VrD6/0qT5/86dvb/Pn376uPVS/+BgkX/vPT9/7zq+v+BtOf/ftP9/3LL/v9ux/7/dLvr/5zw/f+E2Pj/SZPr/1Km/f9Zrfz/YozM/5UvNP+fNDT/pT1F/8pcXf/KXmD/v1tj/45Sgv+Nj/v/jIz+/3iC9P9XiNv/arfo/2nX9P9YtPr/Spf4/zl15/89fPr/49VL/4GCRv+49P3/nO/8/7Ln+P96tuj/fdL8/3DI/v9ster/m/D9/4jf/f9ZoOf/UKP8/06e/P9Mmvz/YWOj/4Q4Tf+Ea5f/hJrH/4K15P+Lxez/h8Tr/1mN2P9tquT/f9Hx/4fp+v9pxe3/aNT0/0qY+v9Chfr/Qofl/zt28f/k1kvqnZQ1/63Y3v+Y7vz/l+/9/6Pu/P99xe7/dMTz/2m58f+N3vT/lO39/2e79/9Jkev/Spn8/0iT/P9Ihuj/isHs/6bw/P+P7fz/fur7/27b9v9bref/e+X5/3Lo+/9x5/r/buL6/0mX5f9Gj/r/P4D6/0KE+v9Xg+L/e4D06uPWS8zf0kr/cYBq/7Hz/f+X7/3/mfD9/5vw/f+I3v3/ftX8/3vL8f+I3/n/asH9/1Gd7/9GkPT/SYbo/5zg9v+H6/v/duf7/3To+/9z6Pv/XsD0/3Hn+/9y6Pv/cuj7/2/i+v9Xs+7/Pn/v/0GC+v8+fvr/QYP3/2p66/+Qiv/M49RKm+PVS/+8sT7/gJmT/6Px/f+Z8P3/mvD9/5rv/f92zv3/bMT9/2rC/f9kuv3/XLD8/0mT8f9isfD/fer7/3bl+/9t2Pv/dOj7/2jS+/9s2/v/cuj7/3Lo+/9p1vv/VKzx/z5/6P9Agvr/Pn/6/z59+v89cuf/jIn8/5SM/5vj1Upa49VL/+PVS/+wpTr/W29r/5fn+P+Z8P3/luz9/3XM/f9sxP3/aL/9/2+//P91vfz/Vqf8/1Wo+/9lw/v/Vqz7/2zW+/9o0Pv/TZ77/2DC+/9kyvr/Wqr3/z195/88e+v/PoD6/z1++v8/gPr/Pn3z/2d24f+Wjvn/nJP/Wt3MRA/QxEX1hoZI/4aiov+y3+f/ksLr/3u66v9zxfb/dc39/4zQ/f9xwv3/hcf8/4bE/P9xtvz/VqP7/1+l+/9Onfv/UKD7/0ya+/9IlPv/RY36/z6A7/9bkvH/Qob6/0CE+v8+gfr/P4H6/z5+8v92kOf/t7L5/5yV8PV3d90PAAAAAHV7n52BneL/k77q/7vy/P+l8v3/nvD9/4vZ9P9/z/H/ouL4/47Y/f+Cxfz/hsT8/3y7/P9Ypfv/bq/7/0+e+/9NnPv/TJn7/0mW+/9IlPv/SJL5/0iU+/9Ik/v/RpD6/0GH9v9OhOb/t8nu////////////5eL/nQAAAAAAAAAA8vL/JsTD/fqInOn/j7no/5rG7P++8vz/r/P9/6Dw/f+c7vz/fcjy/2mw9P+Fw/z/c7X1/1Om+v9Tpvv/UaT7/1Ci+/9PoPv/Tp77/06e+/9MmfX/SZPv/0aN6/8+fd7/haLg//n6/f///////////+Pi//rDvP8mAAAAAAAAAAAAAAAAqbD2i6LF7f/Z+v//oOj6/4XA6/+LwOv/hsHr/4DE7P93tOf/bcb8/2m4/P9ytO7/V6r7/2XH+/9t2Pv/Z8z7/1as+/9SpPr/VKf3/1So+/9kw/v/dN37/23Q+/9ZrvP/bJ3l/+nu+f//////////iwAAAAAAAAAAAAAAAAAAAAA5VcYJ2fn/1NL6//+r9v//rPb//6v2//+p9v//pvb//4a/6v+V7vz/cdD8/3Oy6/9rvvv/eOn7/3bo+/926Pv/dOT7/1mx+/9TpfL/T5nk/2fF+P9+6Pv/f+r7/37p+/902fv/aaXm//f4/dT///8JAAAAAAAAAAAAAAAAAAAAAAAAAADc+P8kyfr/66v2//+s9v//q/b//6j2//+l9v//er3q/6ft+/+A5vz/YKPp/5bY+/956fv/d+n7/3bo+/946fv/ctz7/1aq+/9fr+j/dMbu/2e46f9ov+v/eNr1/3/p+v974vjrXIDVJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACt9f8yq/b/66v2//+q9v//qPb//6X2//+Z6/v/h77q/4rs/P9yrun/dqzo/5bu/P936fv/d+n7/3np+/976fv/Ybz7/1mo6v+U8f7/mPT//5Ls/P9+zvH/ZKfj61eK1jIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACq+P8kq/f/1Kr2//+o9v//pPb//6D1//95w+z/ot/1/3Cp6f9RlvX/fbbp/5Dt+/946fv/een7/3zq+/9v0Pv/Wajr/5Pu/P+b9f//nPX//5z1/9Sc8f8kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACq//8Jqfb/i6f2//qk9v//oPX//4vh//9amen/UZLu/1Wc//9Okff/aKDm/5ro+f9/6vv/fer7/3bc+/9cqen/mvX//531//qg9v+Lqv//CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAqPj/JqT3/52f9v/1fc///2Gt//9Zov//U5f//1CU//9wx+3/WmVL/4Sytv+V7vz/fOL4/4C15fWm9f+dofj/JgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJnu/w9xwf9aYa3/m1mh/8tRlv/pZrj//WKPf/3f0UnpraM6y3aWlJuTzNVaRGZ3DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAADAAAABgAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//gALSw0sReHAlIlRNG0yOimeDyMWztNfVxdTj4M/uta+E/oqHDf6hoA/upaQO1KemELSnpRCDq6sNTLy8DyKlpQ8RgIAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//0AE5dVJMeHUTHbf0UmxtKk85qOZNv+fljT/mZA0/5SMP/+Ri1T/XVor/8jHFf/FwxT/s7AS/6ShFP+npBn/qKUQ/7W0EebCwRGxs7MRdnhyCjG/v4AEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN/XSCDi1Uqe49RL4+LUSvrj1Uv/49VL/+PVS//j1Uv/49VL/+LUS//WyEb/SkcS/8nIFf/QzxX/yMcU/5OPMP/j4tD/1NK1/6mla/+OiRr/nJcO+pKMU+Ps7NKdv7ePIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAHm2U0U4tNLc+LUSvDi1Ev/281I/9LFRf/Lv0P/xblF/8G2R/++s0j/vLFJ/72ySP/BtUb/oJc3/0E/Dv+RkA//vr0T/6CcLf/r6uP///////n59v+vq4r/sa6H/+jn0P/Fwp7/iIUe8JmXDXOMjA0U//8AAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOPTTEDj1Uu31slG+qidOf+clEr/nZdg/5iUcP9vbnX/OTp7/xsfhv8WG5T/ExmV/xQZkf8dIYj/LjR7/z5AcP9HSGH/UVI7/2VjLv/Kyc///Pz+///////n5tz/uLWX/7i0lP+SjnD/mZUe/7i2EfqioA+3fX0MPwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/AAAB4tVLYuHTS+ijmjf+cm5R/8LBt//j4uD/6+vr//Ly8//s7Pb/3d73/56h6v89Q9f/HCTf/x0l5P8cJOD/HifZ/2Fo4P+jqfT/mqDn/32Cy/+bndP/0tLu/+Xl9f/7+/3/+Pj1//Dv6v/e3e7/mpm8/4uGIf+7uRL+ioY56Ojow2IAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANvbSQfk1kpx4NJK9JqRPP+OjYb/9vb2///////////////////////////////////////z8/z/lJfi/zE41v8dJd3/GSHX/0xR6v+WnP//qbD//5ui+f+go+r/+/z+///////////////////////8/P//s7P//3x3dP+JhD//ycaa/62ocfRdVhdxSW1tBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/wAAAeTWSnHj1UrtoZg1/22Egf/N8PX/2Pn+/+H7/v/u/P7//f///////////////////////////////////9PU8/9hZtz/HSTU/z1C5P9nbP//mJ7//6Kp/P+Sl+r/8PD7///////////////////////x8f//ra3//4mGof+5to//q6dx/31wGf9iYTrteqnJcQD//wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4tVLYuPVS/Tj1Uv/TFAs/6Ho8/+n8/7/qPP+/6vz/v+v8/7/uvX+/+D6/v/8///////////////////////////////t7fr/am7Z/ysy1v9aXv//Zmv//6Kp/v+Kj+n/6er5//////////////////v7///Nzf//oKD//5ST7v+HhLD/f3yg/3ZpEf9zc0f/grfh9GvY+mIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAHj00xA5NVL6NLFRv+Bfjr/NU9j/6Hv/v+m8/7/pvP+/6bz/v+l8v7/pPL+/6Py/v+19P7/5Pv///n+////////////////////////+/v+/2lu3P9OU/P/V1v//3p//f+Ijen/6ur5///////////////////////+/v//29v8/6Gh8/+Vlfj/kpL6/4B8mP9eZ1j/ca7p/1av+uhp2/s/AP//AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAObZTRTj1Uu3zcBD/m5uQP+JrbL/W5TZ/3/R+f+f7f7/pvP+/6by/v+l8v7/pPL+/6Ly/v+g8f7/ofH+/7/1/v/q/P7//v///////////////////+jp+f9pbeL/Ulb5/1lc+v+Giuf/8vL7//////////////////////////////////f3/f/T0/H/ra3q/4aG2/9adK7/Upvx/0yd+v5Zt/m3Wb/yFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOLTS3PYy0f6V1Qq/6bGy/+n7fz/fcTv/1ie5v+J3f7/o/D+/6by/v+l8v7/pPL+/6Ly/v+g8f7/nfD9/5rw/f+m8f3/4/v+//////////////////7+///P0PL/R0zf/09T8/+doOf//v7/////////////////////////////////////////////+Pj9/9HR9v9vguD/QHvh/0mW+P9Mnvr6Tp34cwAAAAAAAAAAAAAAAAAAAAAAAAAA39dIIOHTSvCOhzX/k6yq/7n1/v+h8v7/i9/+/1yb4P9twPb/leX+/6Xy/v+k8v7/n+/+/4zg/v+M4f7/nO/9/5nw/f+V7v3/le/9/9z5/v/8////+PP0/+TR1P/Koaf/hVaD/2lHkv/Yytn/+vf3/////////////////////////////f3///P1/f/z9f3//f3///b2//+ys///fIrv/0Vz2v9Fi/D/SZf68EiP/yAAAAAAAAAAAAAAAAD//0AE4tVKntDDRf93f17/uuXs/6Lx/v+h8v7/juH+/3/M9f9epef/eM78/57t/v+Y6f7/gNf+/3XO/v9/1v7/me39/5nw/f+V7v3/kO79/5Tu/P/D3OT/toKM/72Ejf/ftLr/5bzA/9iorv/FjZX/wpKa/+jY2//////////////////t8P3/mq3y/2iE7P9ohOz/lKfx/9fZ/f+np///lZX//4iO+P9YeuT/QYLr/0aR+p1AgP8EAAAAAAAAAADl1Ukx49RL47mvQ/9+lZX/s/L9/5/x/v+h8f7/n+/+/3fO/f9nq+f/aLz3/4HX/v980/7/dc7+/3XN/v93z/7/luv9/5jw/f+U7v3/j+79/4rk8/+Lf47/ql1p/7Jlcv/Ikpn/89PW//bV2P/00dT/573B/7Z5g//fyMz///////v8/v+QpfH/IUrj/xlE4v8ZROL/HETj/0td7P+Ulf//jo7//4yM//+JjPv/U3Tf/z1+7ONEjfoxAAAAAP//gALh1Ex24tRK+o6KPv+bu7//pvL9/57x/v+g8f7/ovL+/3/V/v9vvfP/V5/o/2zG/v9wyf7/csv+/3LK/f9yyv7/jOP9/5jw/f+U7v3/j+38/4vH1v+9gY3/6aOu/+igqv+9bnr/1aWr//bU1//31dj/99XY/+7Hy/+8hI3/7+Tm/+3w/f9Wdun/GUTi/xlE4v8ZROL/GUTi/yJA5f92evL/dH3s/2B26P9jeev/YHno/zVs2fpBhvl2AID/AuHSSxHk1Uux49VL/3h3PP+oztP/o/H9/5zw/v+b7f7/ofH+/5Hk/v9vx/3/To3e/2O+/f9mv/z/WqXs/1uo7f9ux/7/e9P9/5fv/f+T7v3/ju38/5CMm//bmKP/6J+q//e1v//poq3/qlxo//TQ1P/209f/9tTX//bU1//brLH/w5ad/+/y/f9dfOr/GUTi/xhC4v8VO+L/FDji/yA55v97fvv/gIP8/0ps3f82b+f/OXbu/z199f8/gvuxPHjwEejaSyLi1Uvm49VL/358Pf+jytD/ofH9/5zx/v+S5v7/nO7+/5vs/v9vyf7/Wp/n/1Om8v9Omuj/dbvr/0iK4P9pwv3/bMT9/5Ps/f+S7v3/ju38/5tjcf/noKv/5pmk//Svuv/zrLf/sFdl/+Cyt//20dX/9tLW//bT1v/00dT/rGhy//Tv8f+arvL/IErj/xU64v8RLuL/Dyri/0JS7v+Ghv//goL//3B79P85bub/O3r6/z19+v8+gPnmPID/IuHTSkzj1Uv/49VL/52XQf+PsbT/ovH9/5zw/f+W6v7/iN3+/5vt/v950f7/X7Dz/0KH4P9mq+b/mur7/0SE3f9ivP3/ZL39/4Da/f+R7v3/jOj3/6pea//cgI3/44qX/+6msP/01Nj/8uLl//Xq6//66On/9tPX//TLzv/1z9L/y5Oa/9a6vv/3+P7/hpvw/ydC5v8kPOb/RVTu/4CG+f9pfuv/cX7y/3N69v9Gb+b/OXb3/zt5+v89ffr/PID4TOLVS4Xj1Uv/49VL/6SeQP90kJ7/p/D8/5vw/f+d8P7/hdz+/37U/v9yy/7/YLn7/z1z0f+K1PP/nvH+/06N3f9asvv/X7b9/2zE/f+O6/3/jOf3/6hbaP/IXmz/vkVU/8hib//78/T/////////////////9d/i/92Nl//imqL/0o2V/8Wco///////1NT//5ye/f+Pkvz/j4///2eA5/+Cvur/dLrp/2SN4/9BbN//OXT2/zp4+v88fPr/P4D5hePVS7Xj1Uv/2cxI/01XTf9/qtj/rOb4/5rw/f+d8P3/len+/2/I/v9rxP7/ZL7+/02G2P+d7v3/nvH+/2et5/9PoPP/WbD9/1+2/f+A3P3/jO38/5VWZP+1SVX/picz/6wwPP/OhIz/9Obn///////9+vr/5a+1/9Bpdv/Ra3f/w2Fu/8SZof/v7///srL//56e//+UlP//g4f6/2SW3v+e7fv/eun6/2i69v9XkOH/OnPw/zp3+v88e/r/P3/5teTVS9fj1Uv/hHws/4yttP+cyu7/lcLr/6Lw/f+a7v3/kOX+/3HJ/v9txv7/Zb37/12c3/+e8f7/nPD+/4HP9P9Jken/Vaz9/1et/f9qw/z/iOr8/4p/jv+pQkz/nCEr/6AkLv+mKjX/mjNB/8hgav/NZG7/zF9q/81ha//NY23/rklW/6aNx/+lpf//nJz//5SU//+MjP//XXjk/5ra9P+J6/v/cef6/2PM+v9PmfX/PXrb/zt2+P88e/r/P3761+PVS/Lf0kr/TU4s/8Hv9v/D8vz/hLHl/4/H7v+N3/3/etH+/3LK/v9vyP7/acH8/16e4P+e8f7/nPD9/4LV+P9VnOf/Uqb6/1So/f9YrPz/dtP8/3yw0P+TO0n/mSYs/5wpLv+jMjn/nDQ//8lYXv/JWmD/ylxh/8tdYv/FWWD/lEVk/5qW9/+Wlv//kpL//42N//99hPf/bqDl/6Dw/P915/r/cef6/2jW+v9Chfr/UaXr/zZu5f88evr/Pn368uPVS//SxUb/V2JQ/8H1/f+08/3/w/D8/4Ow5f+FxvD/etH+/3PL/v9xyv7/bsb+/1eX3/+c8P7/m/D9/4rh/P9jquf/UJ/1/1Km/f9RpPz/Vaj8/1af8v9xUnz/lzEy/583Nf+ZMzn/t01Q/8tdXf/MX17/yGBh/7tdaP+bRVn/g2m4/4aL9f+LjP7/iYr+/3J/8P9Obtv/ToXW/1qW3P9VpOH/bd73/2fU+v8/f/r/Uab5/zt42v88evn/Pn36/+PVS//RxEX/WGNS/8H1/f+d7/z/rPH9/7/v+/+AsuX/gs3y/3rQ/f9zy/7/cMf+/12i5f+R4/j/mvD9/5Pp/f9wwPP/S5Dl/1Gl/f9Pofz/T5/8/02c/P9ShNv/ez9b/5U5PP+WQlH/oGZ//31xpP9kfMH/YJHY/22j4P91reP/dKzj/2GW2/9JedL/VYva/3e35/+R2/T/lez7/4Hh9/9dtef/bd73/1q4+v8+ffr/Ro76/0aR4P87d/P/PXr3/+PVS/Lf0Un/TU8t/7/v9v+m8f3/lO79/6Hw/f+r6vr/iMHr/3m/7P95zPj/csr9/2q68v99x+z/me/9/5Xt/f960vz/Vpvj/0qX8v9On/z/S5r8/0qY/P9IlPv/SnfV/15Vk/99lsj/i8Hq/5/f9f+k7vv/nfD8/5bv/P+M4Pb/eLfn/2605v980vL/hur7/3vp+v9y5/r/cef6/2XP8v9Nnef/Wrn6/0SJ+v8+fvr/Q4b6/0uV3/9IceX/UHTq8uTVS9fj1Uv/g3ss/4qrsP+08/3/lu79/5bu/f+a8P3/nu/8/5De9/93wO3/cb7v/3HG+v9tt+n/kuf4/5fv/f+A2P3/aL35/0eI3/9Mm/n/SZb8/0eS/P9BhO//V43f/6Ha9P+s7fv/le77/4Dq+/966fv/dun7/3Dh+P9Wquf/aczy/3Xm+v9z6Pv/cuj7/3Hn+v9x5/r/atn6/0yd4/9Ag/H/Qof6/0CA+v8+ffr/Roz6/0yH3v+Agvf/iIb71+PVS7Xj1Uv/2cxI/0xUQv+35ez/nvD9/5bu/f+Y8P3/mvD9/5vw/f+R5/3/gdj8/4bb+/96zvf/fMfq/4/n+/+F3v3/Zbv9/1mp8/9Eien/SJX7/0OK9P9gl+P/q+n5/5rv/P996vv/duf7/3Xo+/9z6Pv/c+j7/2XO9f9dvfL/cuf7/3Lo+/9y6Pv/cuj7/3Hm+v9q2vr/Wbbv/zl14f9Ch/r/QIL6/z9/+v8+ffr/SI/4/0xv3P+OiP//kIr/teLVS4Xj1Uv/49VL/6WdPf96j4f/tOz1/5jv/f+Y8P3/mvD9/5vw/f+b8P3/j+X9/3PL/f91zP3/d8z4/3jM9v9sw/3/Y7n9/1uv+/9LlO//Qonu/0iG4P+I1PX/h+z7/3rp+/915fv/cuH7/3To+/9z6Pv/cOL7/2DF+v9w4/v/cuj7/3Lo+/9y6Pv/cuj7/2jV+v9YtfH/P4Lg/0CD9/9Bg/r/P4D6/z59+v8+fPr/OnTo/2166/+Riv//kor/heHTSkzj1Uv/49VL/97QSf+Jgzj/f5iX/7Tz/f+Y8P3/mvD9/5rw/f+a8P3/mvD9/3/W/f9uxv3/a8P9/2nB/f9nvv3/Y7n9/16z/P9WqPv/SpX0/1ak8P953vv/fOr7/3jn+/9pz/v/ceD7/3Xo+/9y5Pv/W7n7/2zb+/9y6Pv/cuj7/3Lo+/9w5Pv/Xbz7/1Gn9f9BhuH/Pn/z/0CC+v8/gPr/Pn76/z5++v8+fPf/Q23c/4+L/f+Ujf//lI3/TOjaSyLj1Uvm49VL/+PVS//g0kr/d3Ao/2J3dv+b3ej/me/8/5rw/f+a8P3/mO79/33U/f9uxv3/a8P9/2nA/f9mvv3/a7z8/227/P9er/z/UqL8/1Ki/P9u0Pv/cdj7/1+7+/9ct/v/cuL7/3Hi+/9fv/v/TZz7/2TJ+/9v4Pv/bd37/2fM+v9Lmff/RY7t/zt53f87fPP/PoD6/z5/+v8+f/r/P4D6/0CA+f89c+X/d4Dt/5eP/P+Zkf7mnpb/IuHSSxHk1Uux49VL/9rNSP+flzn/h4lR/2R0a/93nrn/e73q/5Hg+P+L4v3/f9b9/3HI/f9zyP3/fcn9/2zB/f9tv/3/hcf8/4fF/P96vfz/Wqn8/1Cf/P9Tn/v/T577/1Cg+/9Vqfv/YsX7/1q0+/9Nnfv/SZX7/0mW+/9Nnfb/RIzt/1SK7f9Mgun/Onjq/z+A+P8+gPr/Pn/6/z1++v8+f/r/QYL6/z966/9keeH/jIbr/46G6/+Qh+6xlofwEf//gALf0kl2sKY6+mJjOP+MqaX/td3j/7vs8/+37Pn/rdv0/3yu5P9mqOT/e832/3zU/f+Bz/3/j9H9/33I/f90wv3/icj8/4fF/P+Ewfz/bLL8/1Sj+/9srfv/W6P7/02c+/9Onfv/Tp37/0ya+/9Jlvv/R5L7/0aP+/9Eivn/QYb3/1CO9/9Vk/n/Qof7/0GG+/8/g/r/P4L6/z+C+v9Ag/n/OXbl/3mU5P/Dwvv/zMn9/6+q+/qel/Z2gID/AgAAAAA5OSoxUV+H416F0/+Wwez/uOX4/7zz/P+l8v3/nPD9/6Dx/f+b5vn/eL/r/2626P+Fye7/n932/57j/f9/y/z/h8f8/4bF/P+Ewfz/d7j8/1Wk+/9vr/v/Z6r7/06d+/9Onfv/TJv7/0ya+/9Klvv/SJT7/0eS+/9Hkfv/R5H7/0eR+/9Hkfv/R5D7/0WO+/9Di/r/QYb4/0GC8v9ShOL/sMLr/////////////////+/u/+Osp/8xAAAAAAAAAAD///8E09P8nbi6+P+Wo+3/cJPe/4q35/+z4fb/u/T9/6vz/f+d8P3/mPD9/5fv/f+b7/3/q/D9/57l/f91xvv/gL/4/4bE/P+Ewfz/dLX4/1Ok+v9dqfv/XKj7/1Ci+/9QoPv/Tp77/02d+/9Mm/v/TJr7/0uZ+/9Kl/n/R5Dy/0WN8P9GjfD/Ro3w/0OI7v9Ihej/aJbo/5m06f/b4/X//f7/////////////9/b//+Df/56/v/8EAAAAAAAAAAAAAAAA9/f/IM/P/vCusvn/b5He/7fe9f+BruT/hrLm/8Hu+v/F9v7/ufT9/6ny/f+f8P3/lur8/3fB7/9Wn+n/cLf3/4bE/P+Dwfz/Za3t/1Sn+/9Up/v/VKb7/1Kl+/9RpPv/UKP7/1Ch+/9PoPv/T5/7/0+f+/9Qofv/T5/4/0+f9/9NmvP/SJLt/0KF4/9Rgtn/pbrn//n7/f/////////////////19P//zMn/8L+3/yAAAAAAAAAAAAAAAAAAAAAAAAAAALy8+3OIner6utz0/9r7///A9v7/kNTy/2yf3/91puH/hbXn/3+x5f9uo+D/Z6Xh/2Wh4P9vvfT/Zbz8/266/P9nrPX/gsLw/1eq+/9Yrfv/YL37/2fM+/9lyfv/W7b7/1Oo+/9RpPv/UaP7/1Ol+f9Tpvv/VKf7/1mw+/9s0fv/b9T7/2bF+/9asfn/SpTq/2OQ3v/T3vT//f3+///////////6//3/cwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHOM2RScvO231PT9/tr7///A+P//qvX//6r1/v+p7vz/oOT4/57n+v+l8v3/pvb//3Gv5f+Y3/j/g+P8/2zI/P9Qm+//ltT0/12v+/9nyfv/d+f7/3fp+/926Pv/dOX7/2rS+/9Zsvv/U6b6/1Ki8P9VpvH/Wa76/2C7+/975/v/fur7/33q+/965Pv/cNT6/2C59v9ineb/x9Xx//////7///+3////FAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/wHO8/s/2/v/6Nj7//+59///rPb//6z2//+s9v//q/b//6r2//+o9v//pfb//3q86v+e2vP/je38/3/j/P9WpfD/jcfv/3i//P9w2fv/eOn7/3bo+/926fv/duj7/3fo+/9t1/v/WK37/1Wo+f9NluT/S5Hd/2O88/912/v/f+n7/4Dq+/9/6vv/fun7/3zm+/9v0fj/WZPf/+fs+Oj///9A////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2/z/YtX7//Sz9///rPb//6z2//+s9v//q/b//6n2//+n9v//pfb//47a9P+MwOr/lu78/4Pp/P9ow/j/ZqDi/5zV/P963/v/eOn7/3fp+/936Pv/duj7/3fp+/946fv/aMr7/1aq+/9ZrvL/Y7Hm/2ez5/9apeL/b8rw/3jb9v974fj/fub5/4Dp+/9/6vv/cdP19FuC1WIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AdD9/3Gu9v/tq/b//6z2//+r9v//q/b//6n2//+n9v//pPb//5np+/98t+f/p+r5/4Tr/P9/2vz/Vo3b/4zB7v+W5fz/e+n7/3fp+/936fv/d+n7/3jp+/956fv/eeb7/1y0+/9guvr/UZbe/5Tz//+O6Pr/eMjv/2686v9quen/aLjp/2W36P9mt+jteNv2cQD//wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALb//wes+P9xq/b/9Kv2//+r9v//qvb//6n2//+n9v//pPb//6D0//93vuv/ntPx/5bu/P+W6/z/VYze/1SO4v+e2fT/ke77/3fp+/936fv/eOn7/3jp+/966fv/fOr7/23P+/9ft/v/T5bf/5Ht/P+X9P//mPX//5j0//+U7fz/j+b6/4bZ9fRhmd1xbbbbBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8BrPf/Yqv2/+ir9v/+qvb//6j2//+m9v//pPb//6H1//+W6/v/YZze/63n+P+l5/j/U4zi/1ac+f9dl+P/o9/2/4zt+/956fv/eOn7/3np+/966fv/fOr7/3jg+/9hufz/Upvh/47n+v+Z9f//mvX//5v1//+c9f/+m/X/6Jz1/2IA//8BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKr3/z+q9/+3qfb/+qj2//+m9v//o/b//6H1//+d9f//fc71/2ad4v+DuOf/VZbw/1if//9PkvX/WZPl/47L7v+W7fv/fer7/3np+/976fv/fer7/3vk+/9oxfz/TpLe/5bx/f+b9f//nPX//531//qd9f+3m/P/QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wGm8v8UqfT/c6j2//Cm9v//o/b//6D1//+d9f//e87//1uj9f9Ni+X/Vp36/1ac//9TmP//T5P7/02J6P96s+f/p+77/4fr+/976fv/fur7/3zm+/9uzPr/VZje/5r1//+c9f//nvX/8J30/3Om8v8U////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/3/yCm9/+do/b/45/1//qb8v//cL7//2Ku//9eqP//WKH//1SZ//9Rlf//UJP//2a4/P9Tj6X/V21n/53R1/+W6vb/hOv7/37n+/9mu+3/k8Tt+qP2/+Od9f+en/f/IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC///8EofX/MaD0/3aT6f+xbLn/5mKu//9dp///WJ///1OY//9Qk///Xan//3rX5v9yhVb/tKg7/3p7QP94l4//ouLr/5Xo9eZfocexsdrudsb6/zG///8EAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID//wKH0v8Rabz/ImGr/0xdp/+DVqD/tFKY/9RRl//ue9z//mGdmf6nnzru49VL1NnMSLSKhjqDeZeXTKzo+CJah5YRgICAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==","base64");function GET(){return new e.NextResponse(z,{headers:{"Content-Type":"image/x-icon","Cache-Control":"public, max-age=0, must-revalidate"}})}let b="force-static",L=new r.AppRouteRouteModule({definition:{kind:n.x.APP_ROUTE,page:"/favicon.ico/route",pathname:"/favicon.ico",filename:"favicon",bundlePath:"app/favicon.ico/route"},resolvedPagePath:"next-metadata-route-loader?page=%2Ffavicon.ico%2Froute&isDynamic=0!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\favicon.ico?__next_metadata_route__",nextConfigOutput:"",userland:P}),{requestAsyncStorage:j,staticGenerationAsyncStorage:u,serverHooks:o,headerHooks:t,staticGenerationBailout:a}=L,p="/favicon.ico/route"}};var v=require("../../webpack-runtime.js");v.C(A);var __webpack_exec__=A=>v(v.s=A),f=v.X(0,[201],()=>__webpack_exec__(8837));module.exports=f})(); \ No newline at end of file diff --git a/.next/server/app/favicon.ico/route.js.nft.json b/.next/server/app/favicon.ico/route.js.nft.json index 8c8cba9..ce8b1e2 100644 --- a/.next/server/app/favicon.ico/route.js.nft.json +++ b/.next/server/app/favicon.ico/route.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../webpack-runtime.js","../../chunks/405.js","../../chunks/572.js","../../../package.json","../../../../node_modules/next/dist/compiled/@vercel/og/index.node.js","../../../../node_modules/next/dist/compiled/@vercel/og/package.json","../../../../node_modules/next/dist/compiled/chalk/package.json","../../../../node_modules/next/dist/compiled/chalk/index.js","../../../../node_modules/next/dist/compiled/cookie/package.json","../../../../node_modules/next/dist/compiled/cookie/index.js","../../../../node_modules/next/dist/compiled/ua-parser-js/package.json","../../../../node_modules/next/dist/compiled/ua-parser-js/ua-parser.js","../../../../node_modules/next/dist/compiled/@edge-runtime/cookies/package.json","../../../../node_modules/next/dist/compiled/@edge-runtime/cookies/index.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../node_modules/next/dist/compiled/@vercel/og/noto-sans-v27-latin-regular.ttf","../../../../node_modules/next/dist/compiled/@vercel/og/yoga.wasm","../../../../node_modules/next/dist/compiled/@vercel/og/resvg.wasm","../../../../package.json"]} \ No newline at end of file +{"version":1,"files":["../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js","../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../node_modules/next/package.json","../../../../package.json","../../../package.json","../../chunks/106.js","../../chunks/2.js","../../chunks/201.js","../../chunks/310.js","../../chunks/323.js","../../chunks/622.js","../../chunks/676.js","../../chunks/837.js","../../chunks/840.js","../../chunks/862.js","../../chunks/984.js","../../chunks/font-manifest.json","../../webpack-runtime.js"]} \ No newline at end of file diff --git a/.next/server/app/index.html b/.next/server/app/index.html index 743288d..41ec058 100644 --- a/.next/server/app/index.html +++ b/.next/server/app/index.html @@ -1 +1 @@ -sukadia.dev
sukadia
.
dev
  • sukadia.dev/ Youtube
    thumbnail

    Lots of VRChat videos focusing on roleplay.

    sukadia.dev/ Twitch
    thumbnail

    Occasional streams for whatever seems fun at the moment.

    sukadia.dev/ Discord
    thumbnail

    The hub for all my socials & projects. Join to stay updated!

    sukadia.dev/ Ko-fi
    thumbnail

    Support me monthly to help me make more content.

  • sukadia.dev/ Everyone-Votes
    thumbnail

    A Discord bot that sends and tallies daily polls from thousands of servers.

    sukadia.dev/ Space
    thumbnail

    A WebGPU space/nebula image generator with lots of parameters to modify.

    sukadia.dev/ Dark
    thumbnail

    A VSCode color theme based off of Brackets Dark.

  • \ No newline at end of file +sukadia.dev
    sukadia
    .
    dev
  • sukadia.dev/ Youtube
    thumbnail

    Lots of VRChat videos focusing on roleplay.

    sukadia.dev/ Twitch
    thumbnail

    Occasional streams for whatever seems fun at the moment.

    sukadia.dev/ Discord
    thumbnail

    The hub for all my socials & projects. Join to stay updated!

    sukadia.dev/ Ko-fi
    thumbnail

    Support me monthly to help me make more content.

  • sukadia.dev/ Everyone-Votes
    thumbnail

    A Discord bot that sends and tallies daily polls from thousands of servers.

    sukadia.dev/ Space
    thumbnail

    A WebGPU space/nebula image generator with lots of parameters to modify.

    sukadia.dev/ Dark
    thumbnail

    A VSCode color theme based off of Brackets Dark.

  • \ No newline at end of file diff --git a/.next/server/app/index.meta b/.next/server/app/index.meta index c0c305a..4bb6676 100644 --- a/.next/server/app/index.meta +++ b/.next/server/app/index.meta @@ -1 +1,5 @@ -{"headers":{"x-next-cache-tags":"/page"}} \ No newline at end of file +{ + "headers": { + "x-next-cache-tags": "_N_T_/layout,_N_T_/page,_N_T_/" + } +} \ No newline at end of file diff --git a/.next/server/app/index.rsc b/.next/server/app/index.rsc index 55f6629..9756229 100644 --- a/.next/server/app/index.rsc +++ b/.next/server/app/index.rsc @@ -1,9 +1,10 @@ -1:HL["/_next/static/css/3930d1a0ca01c66f.css",{"as":"style"}] -0:[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/3930d1a0ca01c66f.css","precedence":"next"}]],["$L3",null]]]] -4:HL["/_next/static/css/60c69e914bf8dd4b.css",{"as":"style"}] -5:I{"id":"4463","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -6:I{"id":"1010","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -7:I{"id":"4143","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -8:I{"id":"2645","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"name":"","async":false} -2:[["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_0ec1f4","children":["$","$L5",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$L6",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":[["$","$L7",null,{"propsForComponent":{"params":{}},"Component":"$8"}],null],"segment":"__PAGE__"},"styles":[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/60c69e914bf8dd4b.css","precedence":"next"}]]}]}]}],null] -3:[[["$","meta",null,{"charSet":"utf-8"}],["$","title",null,{"children":"sukadia.dev"}],["$","meta",null,{"name":"description","content":"I code, stream, and create videos."}],null,null,null,null,null,null,null,null,["$","meta",null,{"name":"viewport","content":"width=device-width, initial-scale=1"}],null,null,null,null,null,null,null,null,null,null,[]],[null,null,null,null],null,null,[null,null,null,null,null],null,null,null,null,[null,[["$","link",null,{"rel":"icon","href":"\\favicon.ico","type":"image/x-icon","sizes":"any"}]],[],null]] +1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] +0:["9CqSqX2Hqhh4fwiD8kSfJ",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] +4:HL["/_next/static/css/60c69e914bf8dd4b.css","style",{"crossOrigin":""}] +5:I[6954,[],""] +6:I[7264,[],""] +8:I[8297,[],""] +9:I[6916,["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],""] +2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L5",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L6",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$L7",["$","$L8",null,{"propsForComponent":{"params":{}},"Component":"$9","isStaticGeneration":true}],null],"segment":"__PAGE__"},"styles":[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/60c69e914bf8dd4b.css","precedence":"next","crossOrigin":""}]]}]}]}],null] +3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +7:null diff --git a/.next/server/app/page.js b/.next/server/app/page.js index bf226d3..11b5551 100644 --- a/.next/server/app/page.js +++ b/.next/server/app/page.js @@ -1,601 +1 @@ -(() => { -var exports = {}; -exports.id = 931; -exports.ids = [931]; -exports.modules = { - -/***/ 252: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/cookie"); - -/***/ }), - -/***/ 7999: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/path-to-regexp"); - -/***/ }), - -/***/ 8038: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react"); - -/***/ }), - -/***/ 8704: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react-dom/server-rendering-stub"); - -/***/ }), - -/***/ 7897: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react-server-dom-webpack/client"); - -/***/ }), - -/***/ 6786: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react/jsx-runtime"); - -/***/ }), - -/***/ 1090: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/server/app-render/get-segment-param.js"); - -/***/ }), - -/***/ 8652: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/server/future/helpers/interception-routes.js"); - -/***/ }), - -/***/ 3918: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/amp-context.js"); - -/***/ }), - -/***/ 5732: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/amp-mode.js"); - -/***/ }), - -/***/ 3280: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/app-router-context.js"); - -/***/ }), - -/***/ 2796: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/head-manager-context.js"); - -/***/ }), - -/***/ 9274: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/hooks-client-context.js"); - -/***/ }), - -/***/ 4486: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/image-blur-svg.js"); - -/***/ }), - -/***/ 744: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/image-config-context.js"); - -/***/ }), - -/***/ 5843: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/image-config.js"); - -/***/ }), - -/***/ 9552: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/image-loader"); - -/***/ }), - -/***/ 1751: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/add-path-prefix.js"); - -/***/ }), - -/***/ 1668: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/handle-smooth-scroll.js"); - -/***/ }), - -/***/ 1897: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/is-bot.js"); - -/***/ }), - -/***/ 8854: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/parse-path.js"); - -/***/ }), - -/***/ 3297: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/remove-trailing-slash.js"); - -/***/ }), - -/***/ 3349: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/server-inserted-html.js"); - -/***/ }), - -/***/ 2470: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/side-effect.js"); - -/***/ }), - -/***/ 618: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/utils/warn-once.js"); - -/***/ }), - -/***/ 1017: -/***/ ((module) => { - -"use strict"; -module.exports = require("path"); - -/***/ }), - -/***/ 7310: -/***/ ((module) => { - -"use strict"; -module.exports = require("url"); - -/***/ }), - -/***/ 4394: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "AppRouter": () => (/* reexport default from dynamic */ next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0___default.a), -/* harmony export */ "GlobalError": () => (/* reexport default from dynamic */ next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3___default.a), -/* harmony export */ "LayoutRouter": () => (/* reexport default from dynamic */ next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1___default.a), -/* harmony export */ "RenderFromTemplateContext": () => (/* reexport default from dynamic */ next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2___default.a), -/* harmony export */ "StaticGenerationSearchParamsBailoutProvider": () => (/* reexport default from dynamic */ next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8___default.a), -/* harmony export */ "__next_app_webpack_require__": () => (/* binding */ __next_app_webpack_require__), -/* harmony export */ "actionAsyncStorage": () => (/* reexport safe */ next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__.actionAsyncStorage), -/* harmony export */ "createSearchParamsBailoutProxy": () => (/* reexport safe */ next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__.createSearchParamsBailoutProxy), -/* harmony export */ "decodeAction": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.decodeAction), -/* harmony export */ "decodeReply": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.decodeReply), -/* harmony export */ "originalPathname": () => (/* binding */ originalPathname), -/* harmony export */ "pages": () => (/* binding */ pages), -/* harmony export */ "preconnect": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preconnect), -/* harmony export */ "preloadFont": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preloadFont), -/* harmony export */ "preloadStyle": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preloadStyle), -/* harmony export */ "renderToReadableStream": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.renderToReadableStream), -/* harmony export */ "requestAsyncStorage": () => (/* reexport safe */ next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__.requestAsyncStorage), -/* harmony export */ "serverHooks": () => (/* reexport module object */ next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__), -/* harmony export */ "staticGenerationAsyncStorage": () => (/* reexport safe */ next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__.staticGenerationAsyncStorage), -/* harmony export */ "staticGenerationBailout": () => (/* reexport safe */ next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__.staticGenerationBailout), -/* harmony export */ "tree": () => (/* binding */ tree) -/* harmony export */ }); -/* harmony import */ var next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4592); -/* harmony import */ var next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6301); -/* harmony import */ var next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7431); -/* harmony import */ var next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2673); -/* harmony import */ var next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(94); -/* harmony import */ var next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4437); -/* harmony import */ var next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(6127); -/* harmony import */ var next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(5486); -/* harmony import */ var next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(6404); -/* harmony import */ var next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(2527); -/* harmony import */ var next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(3332); -/* harmony import */ var next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(7902); -/* harmony import */ var next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(3099); -/* harmony import */ var next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__); - - const tree = { - children: [ - '', - { - children: ['__PAGE__', {}, { - page: [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 3428)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx"], - metadata: { - icon: [(async (props) => (await Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4756))).default(props))], - apple: [], - openGraph: [], - twitter: [], - manifest: undefined - } - }] - }, - { - 'layout': [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 729)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"], - metadata: { - icon: [(async (props) => (await Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4756))).default(props))], - apple: [], - openGraph: [], - twitter: [], - manifest: undefined - } - } - ] - }.children; - const pages = ["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx"]; - - - - - - - - - - - - - - - - - - - const __next_app_webpack_require__ = __webpack_require__ - - - const originalPathname = "/page" - - -/***/ }), - -/***/ 9603: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { - -Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 5157)) - -/***/ }), - -/***/ 5157: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "default": () => (/* binding */ Home) -}); - -// EXTERNAL MODULE: external "next/dist/compiled/react/jsx-runtime" -var jsx_runtime_ = __webpack_require__(6786); -// EXTERNAL MODULE: external "next/dist/compiled/react" -var react_ = __webpack_require__(8038); -// EXTERNAL MODULE: ./app/style.scss -var style = __webpack_require__(3009); -// EXTERNAL MODULE: ./node_modules/next/image.js -var next_image = __webpack_require__(8421); -var image_default = /*#__PURE__*/__webpack_require__.n(next_image); -;// CONCATENATED MODULE: ./app/Card.tsx -/* __next_internal_client_entry_do_not_use__ default auto */ - - -function Card(props) { - //w-[20rem] h-[8rem] on 4k screen - return /*#__PURE__*/ (0,jsx_runtime_.jsxs)("a", { - className: `w-[20rem] h-[8rem] p-2 rounded-2xl bg-slate-800 shadow-lg ${props.shadow} flex flex-col flex-shrink-0 ease-out duration-300 hover:scale-105 hover:-translate-y-1 transition-all`, - href: props.link, - target: "_blank", - children: [ - /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", { - className: "flex flex-row items-center gap-1 ml-2 h-[2rem] w-full rounded-2xl", - children: [ - /*#__PURE__*/ jsx_runtime_.jsx("span", { - className: "text-l font-bold text-cyan-500", - children: "sukadia.dev" - }), - /*#__PURE__*/ (0,jsx_runtime_.jsxs)("span", { - className: "text-xl font-bold dark:text-white", - children: [ - "/ ", - props.title - ] - }) - ] - }), - /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", { - className: "flex flex-row w-full overflow-clip h-[84px]", - children: [ - /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: "h-full aspect-square rounded-2xl relative", - children: /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: "h-full w-full aspect-square relative rounded-2xl overflow-hidden", - children: /*#__PURE__*/ jsx_runtime_.jsx((image_default()), { - fill: true, - src: props.icon, - sizes: "128px", - alt: "thumbnail", - className: "" - }) - }) - }), - /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: "h-full w-full m-2 ml-4 rounded-2xl", - children: /*#__PURE__*/ jsx_runtime_.jsx("p", { - children: props.description - }) - }) - ] - }) - ] - }); -} - -;// CONCATENATED MODULE: ./app/page.tsx -/* __next_internal_client_entry_do_not_use__ default auto */ - - - -let dotHoldSound; -function Home() { - const [clickedOption, setOption] = (0,react_.useState)(""); - const sound = (0,react_.useRef)(typeof Audio !== "undefined" ? new Audio("audio/the-fabled-period-button.mp3") : undefined).current; - let sukadiaClick = (e)=>{ - setOption(clickedOption == "sukadia" ? "" : "sukadia"); - }; - let dotclickcount = 0; - let dotHoldSecret; - let dotClick = (e)=>{ - setOption(clickedOption == "." ? "" : "."); - dotclickcount++; - let currentclick = dotclickcount; - //TODO: Want it to be based off pushed-downness, if already pushed down it still needs to wait - dotHoldSound = setTimeout(()=>{ - if (dotclickcount == currentclick) { - (sound?.cloneNode()).play(); - } - }, 100); - }; - let dotLeave = (e)=>{ - //BUG: Stays held down since onMouseUp doesn't capture when it happens not over the element - setOption(""); - clearTimeout(dotHoldSound); - }; - let devClick = (e)=>{ - setOption(clickedOption == "dev" ? "" : "dev"); - }; - return /*#__PURE__*/ (0,jsx_runtime_.jsxs)("main", { - className: "select-none", - children: [ - /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: "flex flex-col items-center h-screen overflow-hidden", - children: /*#__PURE__*/ (0,jsx_runtime_.jsxs)("div", { - className: (clickedOption == "sukadia" || clickedOption == "dev" ? "-translate-y-24" : "") + " flex flex-row w-screen items-center justify-center overflow-hidden text-6xl min-[437px]:text-7xl min-[577px]:text-8xl md:text-9xl m-auto transition-all duration-500 z-20", - children: [ - /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: "overflow-hidden flex-shrink", - onMouseDown: sukadiaClick, - children: /*#__PURE__*/ jsx_runtime_.jsx("div", { - id: "sukadia", - className: (clickedOption == "sukadia" ? "maintitle-pressed top-2" : "maintitle hover:-translate-y-0.5") + " transition-all hover:m-2", - children: "sukadia" - }) - }), - /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: "overflow-hidden flex-shrink", - onMouseDown: dotClick, - onMouseUp: dotLeave, - children: /*#__PURE__*/ jsx_runtime_.jsx("div", { - id: ".", - className: (clickedOption == "." ? "maintitle-pressed top-2" : "maintitle hover:-translate-y-0.5") + " transition-all hover:m-2", - children: "." - }) - }), - /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: "overflow-hidden flex-shrink", - onMouseDown: devClick, - children: /*#__PURE__*/ jsx_runtime_.jsx("div", { - id: "dev", - className: (clickedOption == "dev" ? "maintitle-pressed top-2" : "maintitle hover:-translate-y-0.5") + " transition-all hover:m-2", - children: "dev" - }) - }) - ] - }) - }), - /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: (clickedOption == "sukadia" ? "" : "pointer-events-none") + " flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden", - children: /*#__PURE__*/ (0,jsx_runtime_.jsxs)("li", { - className: (clickedOption == "sukadia" ? "opacity-100 z-10" : "opacity-0 pointer-events-none -translate-y-12 z-1") + " flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500", - children: [ - /*#__PURE__*/ jsx_runtime_.jsx(Card, { - title: "Youtube", - description: "Lots of VRChat videos focusing on roleplay.", - icon: "/images/YoutubeIcon.png", - link: "/youtube", - shadow: "shadow-red-950" - }), - /*#__PURE__*/ jsx_runtime_.jsx(Card, { - title: "Twitch", - description: "Occasional streams for whatever seems fun at the moment.", - icon: "/images/TwitchIcon.png", - link: "/twitch", - shadow: "shadow-violet-950" - }), - /*#__PURE__*/ jsx_runtime_.jsx(Card, { - title: "Discord", - description: "The hub for all my socials & projects. Join to stay updated!", - icon: "/images/DiscordIcon.png", - link: "/discord", - shadow: "shadow-blue-900" - }), - /*#__PURE__*/ jsx_runtime_.jsx(Card, { - title: "Ko-fi", - description: "Support me monthly to help me make more content.", - icon: "/images/KofiIcon.png", - link: "/ko-fi", - shadow: "shadow-sky-900" - }) - ] - }) - }), - /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: (clickedOption == "dev" ? "" : "pointer-events-none") + " flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden", - children: /*#__PURE__*/ (0,jsx_runtime_.jsxs)("li", { - className: (clickedOption == "dev" ? "opacity-100 z-10" : "opacity-0 -translate-y-12 z-0") + " flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500", - children: [ - /*#__PURE__*/ jsx_runtime_.jsx(Card, { - title: "Everyone-Votes", - description: "A Discord bot that sends and tallies daily polls from thousands of servers.", - icon: "/images/EveryoneVotesIcon.png", - link: "/everyone-votes", - shadow: "shadow-blue-900" - }), - /*#__PURE__*/ jsx_runtime_.jsx(Card, { - title: "Space", - description: "A WebGPU space/nebula image generator with lots of parameters to modify.", - icon: "/images/SpaceIcon.png", - link: "/space", - shadow: "shadow-violet-950" - }), - /*#__PURE__*/ jsx_runtime_.jsx(Card, { - title: "Dark", - description: "A VSCode color theme based off of Brackets Dark.", - icon: "/images/DarkIcon.png", - link: "/dark", - shadow: "shadow-yellow-950" - }) - ] - }) - }) - ] - }); -} - - -/***/ }), - -/***/ 3428: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "$$typeof": () => (/* binding */ $$typeof), -/* harmony export */ "__esModule": () => (/* binding */ __esModule), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var next_dist_build_webpack_loaders_next_flight_loader_module_proxy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1313); - -const proxy = (0,next_dist_build_webpack_loaders_next_flight_loader_module_proxy__WEBPACK_IMPORTED_MODULE_0__.createProxy)(String.raw`X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\page.tsx`) - -// Accessing the __esModule property and exporting $$typeof are required here. -// The __esModule getter forces the proxy target to create the default export -// and the $$typeof value is for rendering logic to determine if the module -// is a client boundary. -const { __esModule, $$typeof } = proxy; -const __default__ = proxy.default; - - -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__default__); - -/***/ }), - -/***/ 3009: -/***/ (() => { - - - -/***/ }) - -}; -; - -// load runtime -var __webpack_require__ = require("../webpack-runtime.js"); -__webpack_require__.C(exports); -var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId)) -var __webpack_exports__ = __webpack_require__.X(0, [405,616,421,816], () => (__webpack_exec__(4394))); -module.exports = __webpack_exports__; - -})(); \ No newline at end of file +(()=>{var e={};e.id=931,e.ids=[931],e.modules={5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},4345:(e,t,s)=>{"use strict";s.r(t),s.d(t,{GlobalError:()=>n.a,__next_app__:()=>u,originalPathname:()=>p,pages:()=>c,routeModule:()=>x,tree:()=>d});var a=s(7096),i=s(6132),o=s(7284),n=s.n(o),r=s(2564),l={};for(let e in r)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>r[e]);s.d(t,l);let d=["",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(s.bind(s,3982)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx"],metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(s.bind(s,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(s.t.bind(s,9291,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],c=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx"],p="/page",u={require:s,loadChunk:()=>Promise.resolve()},x=new a.AppPageRouteModule({definition:{kind:i.x.APP_PAGE,page:"/page",pathname:"/",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:d}})},8530:(e,t,s)=>{Promise.resolve().then(s.bind(s,5698))},5698:(e,t,s)=>{"use strict";let a;s.r(t),s.d(t,{default:()=>Home});var i=s(784),o=s(9885);s(8294);var n=s(2451),r=s.n(n);function Card(e){return(0,i.jsxs)("a",{className:`w-[20rem] h-[8rem] p-2 rounded-2xl bg-slate-800 shadow-lg ${e.shadow} flex flex-col flex-shrink-0 ease-out duration-300 hover:scale-105 hover:-translate-y-1 transition-all`,href:e.link,target:"_blank",children:[(0,i.jsxs)("div",{className:"flex flex-row items-center gap-1 ml-2 h-[2rem] w-full rounded-2xl",children:[i.jsx("span",{className:"text-l font-bold text-cyan-500",children:"sukadia.dev"}),(0,i.jsxs)("span",{className:"text-xl font-bold dark:text-white",children:["/ ",e.title]})]}),(0,i.jsxs)("div",{className:"flex flex-row w-full overflow-clip h-[84px]",children:[i.jsx("div",{className:"h-full aspect-square rounded-2xl relative",children:i.jsx("div",{className:"h-full w-full aspect-square relative rounded-2xl overflow-hidden",children:i.jsx(r(),{fill:!0,src:e.icon,sizes:"128px",alt:"thumbnail",className:""})})}),i.jsx("div",{className:"h-full w-full m-2 ml-4 rounded-2xl",children:i.jsx("p",{children:e.description})})]})]})}function Home(){let[e,t]=(0,o.useState)(""),s=(0,o.useRef)("undefined"!=typeof Audio?new Audio("audio/the-fabled-period-button.mp3"):void 0).current,n=0;return(0,i.jsxs)("main",{className:"select-none",children:[i.jsx("div",{className:"flex flex-col items-center h-screen overflow-hidden",children:(0,i.jsxs)("div",{className:("sukadia"==e||"dev"==e?"-translate-y-24":"")+" flex flex-row w-screen items-center justify-center overflow-hidden text-6xl min-[437px]:text-7xl min-[577px]:text-8xl md:text-9xl m-auto transition-all duration-500 z-20",children:[i.jsx("div",{className:"overflow-hidden flex-shrink",onMouseDown:s=>{t("sukadia"==e?"":"sukadia")},children:i.jsx("div",{id:"sukadia",className:("sukadia"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"sukadia"})}),i.jsx("div",{className:"overflow-hidden flex-shrink",onMouseDown:i=>{t("."==e?"":".");let o=++n;a=setTimeout(()=>{n==o&&s?.cloneNode().play()},100)},onMouseUp:e=>{t(""),clearTimeout(a)},children:i.jsx("div",{id:".",className:("."==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"."})}),i.jsx("div",{className:"overflow-hidden flex-shrink",onMouseDown:s=>{t("dev"==e?"":"dev")},children:i.jsx("div",{id:"dev",className:("dev"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"dev"})})]})}),i.jsx("div",{className:("sukadia"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("sukadia"==e?"opacity-100 z-10":"opacity-0 pointer-events-none -translate-y-12 z-1")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[i.jsx(Card,{title:"Youtube",description:"Lots of VRChat videos focusing on roleplay.",icon:"/images/YoutubeIcon.png",link:"/youtube",shadow:"shadow-red-950"}),i.jsx(Card,{title:"Twitch",description:"Occasional streams for whatever seems fun at the moment.",icon:"/images/TwitchIcon.png",link:"/twitch",shadow:"shadow-violet-950"}),i.jsx(Card,{title:"Discord",description:"The hub for all my socials & projects. Join to stay updated!",icon:"/images/DiscordIcon.png",link:"/discord",shadow:"shadow-blue-900"}),i.jsx(Card,{title:"Ko-fi",description:"Support me monthly to help me make more content.",icon:"/images/KofiIcon.png",link:"/ko-fi",shadow:"shadow-sky-900"})]})}),i.jsx("div",{className:("dev"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("dev"==e?"opacity-100 z-10":"opacity-0 -translate-y-12 z-0")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[i.jsx(Card,{title:"Everyone-Votes",description:"A Discord bot that sends and tallies daily polls from thousands of servers.",icon:"/images/EveryoneVotesIcon.png",link:"/everyone-votes",shadow:"shadow-blue-900"}),i.jsx(Card,{title:"Space",description:"A WebGPU space/nebula image generator with lots of parameters to modify.",icon:"/images/SpaceIcon.png",link:"/space",shadow:"shadow-violet-950"}),i.jsx(Card,{title:"Dark",description:"A VSCode color theme based off of Brackets Dark.",icon:"/images/DarkIcon.png",link:"/dark",shadow:"shadow-yellow-950"})]})})]})}},3982:(e,t,s)=>{"use strict";s.r(t),s.d(t,{$$typeof:()=>n,__esModule:()=>o,default:()=>l});var a=s(5153);let i=(0,a.createProxy)(String.raw`X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\page.tsx`),{__esModule:o,$$typeof:n}=i,r=i.default,l=r},7481:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var a=s(8531);let __WEBPACK_DEFAULT_EXPORT__=e=>{let t=(0,a.fillMetadataSegment)(".",e.params,"favicon.ico");return[{type:"image/x-icon",sizes:"16x16",url:t+""}]}},8294:()=>{}};var t=require("../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),s=t.X(0,[862,323,837,622],()=>__webpack_exec__(4345));module.exports=s})(); \ No newline at end of file diff --git a/.next/server/app/page.js.nft.json b/.next/server/app/page.js.nft.json index 92352fb..d933c24 100644 --- a/.next/server/app/page.js.nft.json +++ b/.next/server/app/page.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../webpack-runtime.js","../chunks/405.js","../chunks/616.js","../chunks/421.js","../chunks/816.js","../../package.json","../../../node_modules/next/package.json","../../../node_modules/next/dist/shared/lib/amp-context.js","../../../node_modules/next/dist/shared/lib/amp-mode.js","../../../node_modules/next/dist/shared/lib/side-effect.js","../../../node_modules/next/dist/shared/lib/head-manager-context.js","../../../node_modules/next/dist/shared/lib/app-router-context.js","../../../node_modules/next/dist/shared/lib/hooks-client-context.js","../../../node_modules/next/dist/shared/lib/image-blur-svg.js","../../../node_modules/next/dist/shared/lib/image-config-context.js","../../../node_modules/next/dist/shared/lib/image-config.js","../../../node_modules/next/dist/shared/lib/server-inserted-html.js","../../../node_modules/next/dist/server/app-render/get-segment-param.js","../../../node_modules/next/dist/shared/lib/image-loader.js","../../../node_modules/next/dist/shared/lib/utils/warn-once.js","../../../node_modules/next/dist/server/future/helpers/interception-routes.js","../../../node_modules/react/package.json","../../../node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js","../../../node_modules/next/dist/shared/lib/router/utils/handle-smooth-scroll.js","../../../node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js","../../../node_modules/next/dist/shared/lib/router/utils/is-bot.js","../../../node_modules/next/dist/shared/lib/router/utils/parse-path.js","../../../node_modules/react/index.js","../../../node_modules/next/dist/compiled/react/jsx-runtime.js","../../../node_modules/next/dist/compiled/react-dom/server-rendering-stub.js","../../../node_modules/next/dist/compiled/react-server-dom-webpack/client.js","../../../node_modules/next/dist/compiled/react/package.json","../../../node_modules/next/dist/compiled/react-dom/package.json","../../../node_modules/next/dist/compiled/react-server-dom-webpack/package.json","../../../node_modules/next/dist/compiled/path-to-regexp/index.js","../../../node_modules/next/dist/shared/lib/match-remote-pattern.js","../../../node_modules/next/dist/compiled/react/index.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/next/dist/compiled/cookie/package.json","../../../node_modules/next/dist/compiled/cookie/index.js","../../../node_modules/next/dist/shared/lib/router/utils/app-paths.js","../../../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.production.min.js","../../../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.development.js","../../../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.production.min.js","../../../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.development.js","../../../node_modules/next/dist/compiled/react-server-dom-webpack/client.browser.js","../../../node_modules/next/dist/compiled/react/cjs/react.production.min.js","../../../node_modules/next/dist/compiled/react/cjs/react.development.js","../../../node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js","../../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.production.min.js","../../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.development.js","../../../node_modules/@swc/helpers/_/_interop_require_default/package.json","../../../node_modules/@swc/helpers/_/_interop_require_wildcard/package.json","../../../node_modules/@swc/helpers/package.json","../../../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../../../node_modules/@swc/helpers/cjs/_interop_require_wildcard.cjs","../../../node_modules/next/dist/compiled/micromatch/package.json","../../../node_modules/next/dist/compiled/micromatch/index.js","../../../node_modules/react-dom/package.json","../../../node_modules/react-dom/index.js","../../../node_modules/react-dom/cjs/react-dom.production.min.js","../../../node_modules/react-dom/cjs/react-dom.development.js","../../../node_modules/scheduler/package.json","../../../node_modules/scheduler/index.js","../../../node_modules/scheduler/cjs/scheduler.production.min.js","../../../node_modules/scheduler/cjs/scheduler.development.js","../../../package.json"]} \ No newline at end of file +{"version":1,"files":["../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../node_modules/next/dist/client/components/async-local-storage.js","../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../../package.json","../../package.json","../chunks/106.js","../chunks/2.js","../chunks/201.js","../chunks/310.js","../chunks/323.js","../chunks/622.js","../chunks/676.js","../chunks/837.js","../chunks/840.js","../chunks/862.js","../chunks/984.js","../chunks/font-manifest.json","../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/page_client-reference-manifest.js b/.next/server/app/page_client-reference-manifest.js new file mode 100644 index 0000000..0143196 --- /dev/null +++ b/.next/server/app/page_client-reference-manifest.js @@ -0,0 +1 @@ +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"]}} \ No newline at end of file diff --git a/.next/server/app/space.html b/.next/server/app/space.html index 9070b92..c4a93a3 100644 --- a/.next/server/app/space.html +++ b/.next/server/app/space.html @@ -1 +1 @@ -sukadia.dev
    \ No newline at end of file +sukadia.dev
    \ No newline at end of file diff --git a/.next/server/app/space.meta b/.next/server/app/space.meta index e5bae34..2f18811 100644 --- a/.next/server/app/space.meta +++ b/.next/server/app/space.meta @@ -1 +1,5 @@ -{"headers":{"x-next-cache-tags":"/space/page"}} \ No newline at end of file +{ + "headers": { + "x-next-cache-tags": "_N_T_/layout,_N_T_/space/layout,_N_T_/space/page,_N_T_/space" + } +} \ No newline at end of file diff --git a/.next/server/app/space.rsc b/.next/server/app/space.rsc index cbbec08..3167a19 100644 --- a/.next/server/app/space.rsc +++ b/.next/server/app/space.rsc @@ -1,8 +1,9 @@ -1:HL["/_next/static/css/3930d1a0ca01c66f.css",{"as":"style"}] -0:[[["",{"children":["space",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/3930d1a0ca01c66f.css","precedence":"next"}]],["$L3",null]]]] -4:I{"id":"4463","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -5:I{"id":"1010","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -6:I{"id":"4143","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -7:I{"id":"476","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"name":"","async":false} -2:[["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_0ec1f4","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$L5",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","space","children"],"error":"$undefined","errorStyles":"$undefined","loading":["$","div",null,{"className":"flex h-screen justify-center items-center","children":["$","div",null,{"className":"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin","children":["$","div",null,{"className":"h-10 w-10 rounded-full bg-black"}]}]}],"loadingStyles":[],"hasLoading":true,"template":["$","$L5",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":[["$","$L6",null,{"propsForComponent":{"params":{}},"Component":"$7"}],null],"segment":"__PAGE__"},"styles":[]}],"segment":"space"},"styles":[]}]}]}],null] -3:[[["$","meta",null,{"charSet":"utf-8"}],["$","title",null,{"children":"sukadia.dev"}],["$","meta",null,{"name":"description","content":"I code, stream, and create videos."}],null,null,null,null,null,null,null,null,["$","meta",null,{"name":"viewport","content":"width=device-width, initial-scale=1"}],null,null,null,null,null,null,null,null,null,null,[]],[null,null,null,null],null,null,[null,null,null,null,null],null,null,null,null,[null,[["$","link",null,{"rel":"icon","href":"\\favicon.ico","type":"image/x-icon","sizes":"any"}]],[],null]] +1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] +0:["9CqSqX2Hqhh4fwiD8kSfJ",[[["",{"children":["space",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] +4:I[6954,[],""] +5:I[7264,[],""] +7:I[8297,[],""] +8:I[341,["732","static/chunks/e1206f8c-ab5b5541f866e530.js","105","static/chunks/1f3d3139-f107a678ff6361e9.js","735","static/chunks/604a08ec-59af37265fb99b3d.js","790","static/chunks/d67c510a-e497b3cd5bf43bb4.js","116","static/chunks/537cd76e-7aba1cf7a4752418.js","173","static/chunks/173-2ffa9652644381a8.js","514","static/chunks/app/space/page-b8120f6d5470d1c7.js"],""] +2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","space","children"],"loading":["$","div",null,{"className":"flex h-screen justify-center items-center","children":["$","div",null,{"className":"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin","children":["$","div",null,{"className":"h-10 w-10 rounded-full bg-black"}]}]}],"loadingStyles":[],"loadingScripts":[],"hasLoading":true,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$L6",["$","$L7",null,{"propsForComponent":{"params":{}},"Component":"$8","isStaticGeneration":true}],null],"segment":"__PAGE__"},"styles":null}],"segment":"space"},"styles":null}]}]}],null] +3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +6:null diff --git a/.next/server/app/space/page.js b/.next/server/app/space/page.js index c108e51..dfd8869 100644 --- a/.next/server/app/space/page.js +++ b/.next/server/app/space/page.js @@ -1,720 +1 @@ -(() => { -var exports = {}; -exports.id = 514; -exports.ids = [514]; -exports.modules = { - -/***/ 252: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/cookie"); - -/***/ }), - -/***/ 7999: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/path-to-regexp"); - -/***/ }), - -/***/ 8038: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react"); - -/***/ }), - -/***/ 8704: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react-dom/server-rendering-stub"); - -/***/ }), - -/***/ 7897: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react-server-dom-webpack/client"); - -/***/ }), - -/***/ 6786: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react/jsx-runtime"); - -/***/ }), - -/***/ 1090: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/server/app-render/get-segment-param.js"); - -/***/ }), - -/***/ 8652: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/server/future/helpers/interception-routes.js"); - -/***/ }), - -/***/ 3280: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/app-router-context.js"); - -/***/ }), - -/***/ 9274: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/hooks-client-context.js"); - -/***/ }), - -/***/ 1751: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/add-path-prefix.js"); - -/***/ }), - -/***/ 1668: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/handle-smooth-scroll.js"); - -/***/ }), - -/***/ 1897: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/is-bot.js"); - -/***/ }), - -/***/ 8854: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/parse-path.js"); - -/***/ }), - -/***/ 3297: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/remove-trailing-slash.js"); - -/***/ }), - -/***/ 3349: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/server-inserted-html.js"); - -/***/ }), - -/***/ 1017: -/***/ ((module) => { - -"use strict"; -module.exports = require("path"); - -/***/ }), - -/***/ 7310: -/***/ ((module) => { - -"use strict"; -module.exports = require("url"); - -/***/ }), - -/***/ 3014: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "AppRouter": () => (/* reexport default from dynamic */ next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0___default.a), -/* harmony export */ "GlobalError": () => (/* reexport default from dynamic */ next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3___default.a), -/* harmony export */ "LayoutRouter": () => (/* reexport default from dynamic */ next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1___default.a), -/* harmony export */ "RenderFromTemplateContext": () => (/* reexport default from dynamic */ next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2___default.a), -/* harmony export */ "StaticGenerationSearchParamsBailoutProvider": () => (/* reexport default from dynamic */ next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8___default.a), -/* harmony export */ "__next_app_webpack_require__": () => (/* binding */ __next_app_webpack_require__), -/* harmony export */ "actionAsyncStorage": () => (/* reexport safe */ next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__.actionAsyncStorage), -/* harmony export */ "createSearchParamsBailoutProxy": () => (/* reexport safe */ next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__.createSearchParamsBailoutProxy), -/* harmony export */ "decodeAction": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.decodeAction), -/* harmony export */ "decodeReply": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.decodeReply), -/* harmony export */ "originalPathname": () => (/* binding */ originalPathname), -/* harmony export */ "pages": () => (/* binding */ pages), -/* harmony export */ "preconnect": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preconnect), -/* harmony export */ "preloadFont": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preloadFont), -/* harmony export */ "preloadStyle": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preloadStyle), -/* harmony export */ "renderToReadableStream": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.renderToReadableStream), -/* harmony export */ "requestAsyncStorage": () => (/* reexport safe */ next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__.requestAsyncStorage), -/* harmony export */ "serverHooks": () => (/* reexport module object */ next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__), -/* harmony export */ "staticGenerationAsyncStorage": () => (/* reexport safe */ next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__.staticGenerationAsyncStorage), -/* harmony export */ "staticGenerationBailout": () => (/* reexport safe */ next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__.staticGenerationBailout), -/* harmony export */ "tree": () => (/* binding */ tree) -/* harmony export */ }); -/* harmony import */ var next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4592); -/* harmony import */ var next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6301); -/* harmony import */ var next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7431); -/* harmony import */ var next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2673); -/* harmony import */ var next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(94); -/* harmony import */ var next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4437); -/* harmony import */ var next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(6127); -/* harmony import */ var next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(5486); -/* harmony import */ var next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(6404); -/* harmony import */ var next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(2527); -/* harmony import */ var next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(3332); -/* harmony import */ var next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(7902); -/* harmony import */ var next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(3099); -/* harmony import */ var next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__); - - const tree = { - children: [ - '', - { - children: [ - 'space', - { - children: ['__PAGE__', {}, { - page: [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 6374)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx"], - - }] - }, - { - 'loading': [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4494)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\loading.tsx"], - metadata: { - icon: [(async (props) => (await Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4756))).default(props))], - apple: [], - openGraph: [], - twitter: [], - manifest: undefined - } - } - ] - }, - { - 'layout': [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 729)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"], - metadata: { - icon: [(async (props) => (await Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4756))).default(props))], - apple: [], - openGraph: [], - twitter: [], - manifest: undefined - } - } - ] - }.children; - const pages = ["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx"]; - - - - - - - - - - - - - - - - - - - const __next_app_webpack_require__ = __webpack_require__ - - - const originalPathname = "/space/page" - - -/***/ }), - -/***/ 8522: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { - -Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 7711)) - -/***/ }), - -/***/ 3259: -/***/ (() => { - - - -/***/ }), - -/***/ 7711: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "default": () => (/* binding */ Sp) -}); - -// EXTERNAL MODULE: external "next/dist/compiled/react/jsx-runtime" -var jsx_runtime_ = __webpack_require__(6786); -// EXTERNAL MODULE: external "next/dist/compiled/react" -var react_ = __webpack_require__(8038); -// EXTERNAL MODULE: ./node_modules/next/dist/shared/lib/app-dynamic.js -var app_dynamic = __webpack_require__(5319); -var app_dynamic_default = /*#__PURE__*/__webpack_require__.n(app_dynamic); -;// CONCATENATED MODULE: ./app/space/loading.tsx - -function Loading() { - return /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: "flex h-screen justify-center items-center", - children: /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: "flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin", - children: /*#__PURE__*/ jsx_runtime_.jsx("div", { - className: "h-10 w-10 rounded-full bg-black" - }) - }) - }); -} - -// EXTERNAL MODULE: ./node_modules/tweakpane/dist/tweakpane.js -var tweakpane = __webpack_require__(1853); -// EXTERNAL MODULE: ./node_modules/@babylonjs/core/index.js + 1254 modules -var core = __webpack_require__(6803); -;// CONCATENATED MODULE: ./app/space/BabylonInteractivity.tsx -/* __next_internal_client_entry_do_not_use__ default auto */ - -let canvas; -let engine; -let scene; -let camera; -let starshader; -let nebulashaders = []; -function hashString(string) { - var hash = 0, i, chr; - for(i = 0; i < string.length; i++){ - chr = string.charCodeAt(i); - hash = (hash << 5) - hash + chr; - hash |= 0; // Convert to 32bit integer - } - return Math.abs(hash); -} -function mulberry32(a) { - var t = a += 0x6D2B79F5; - t = Math.imul(t ^ t >>> 15, t | 1); - t ^= t + Math.imul(t ^ t >>> 7, t | 61); - return ((t ^ t >>> 14) >>> 0) / 4294967296; -} -let lastseed; -let seednum; -class BabylonInteractivity { - static generateFrame() { - if (!canvas) return; - let starttime = performance.now(); - const parameters = getParameters(); - // Resize canvas if necessary - if (canvas.width != parameters.width || canvas.height != parameters.height) { - this.resizeFrame(parameters.width, parameters.height); - } - // Only rehash seed if necessary - if (lastseed != parameters.seed) { - seednum = mulberry32(hashString(parameters.seed)); - lastseed = parameters.seed; - console.log(1); - } - // Apply new parameters - starshader.onApply = (effect)=>{ - effect.setFloat("seed", seednum + 5); - effect.setFloat("density", parameters.density / 100); - effect.setFloat("brightness", parameters.brightness / 100); - }; - for(let i = 0; i < nebulashaders.length; i++){ - camera.detachPostProcess(nebulashaders[i]); - } - for(let i = 0; i < parameters.count; i++){ - camera.attachPostProcess(nebulashaders[i]); - nebulashaders[i].onApply = (effect)=>{ - effect.setFloat("seed", seednum * 1000 * (i + 1)); - effect.setFloat4("color", parameters[`color${i + 1}`].r / 255, parameters[`color${i + 1}`].g / 255, parameters[`color${i + 1}`].b / 255, 1); - effect.setUInt("nebulascale", parameters.scale); - effect.setUInt("depth", parameters.depth); - effect.setFloat("intensity", parameters.intensity / 100 - 1); - effect.setFloat("falloff", parameters.falloff); - effect.setFloat("persistence", parameters.persistence); - }; - //BUG: Renders are delayed by one render - nebulashaders[i].onApplyObservable.add((effect)=>{ - effect.setTextureSampler("textureSamplerSampler", nebulashaders[i].inputTexture.texture); - }); - } - scene.onAfterRenderObservable.addOnce(()=>{ - console.log(`Rendered in ${Math.round((performance.now() - starttime) * 100) / 100}ms`); - }); - engine.beginFrame(); - scene.render(); - engine.endFrame(); - } - static resizeFrame(width, height) { - canvas.style.width = width.toString() + "px"; - canvas.style.height = height.toString() + "px"; - engine.resize(); - } - static async exportFrame() { - const parameters = getParameters(); - core/* Tools.CreateScreenshotUsingRenderTarget */.w1W.CreateScreenshotUsingRenderTarget(engine, camera, { - width: canvas.width, - height: canvas.height - }, undefined, undefined, undefined, undefined, `nebula-${parameters.seed}`); - this.generateFrame(); - } - static setTransparency(bool) { - if (bool) scene.clearColor = new core/* Color4 */.HEv(0, 0, 0, 0); - else scene.clearColor = new core/* Color4 */.HEv(0, 0, 0, 1); - } - static initialize(newcanvas, newengine, newscene, newcamera) { - canvas = newcanvas; - engine = newengine; - scene = newscene; - camera = newcamera; - starshader = new core/* PostProcess */.Dso("StarShader", "stars", null, null, 1, camera, undefined, engine, true, undefined, undefined, undefined, undefined, undefined, undefined, core/* ShaderLanguage.WGSL */.xeF.WGSL); - camera.attachPostProcess(starshader); - for(let i = 0; i < 10; i++){ - nebulashaders.push(new core/* PostProcess */.Dso("NebulaShader", "nebulas", null, null, 1, camera, undefined, engine, true, undefined, undefined, undefined, undefined, undefined, undefined, core/* ShaderLanguage.WGSL */.xeF.WGSL)); - } - } -} - -;// CONCATENATED MODULE: ./app/space/ParameterPanel.tsx -/* __next_internal_client_entry_do_not_use__ default,getParameters auto */ - -let pane; -function ParameterPanel() { - pane = new tweakpane.Pane({ - title: "Parameters", - container: document.getElementById("TweakPane") || undefined - }); - let canvasparameters = { - width: window.innerWidth, - height: window.innerHeight, - transparent: false, - autoupdate: false - }; - let canvasfolder = pane.addFolder({ - title: "Canvas", - expanded: true - }); - canvasfolder.addInput(canvasparameters, "width", { - min: 100, - max: 7680, - step: 1 - }); - canvasfolder.addInput(canvasparameters, "height", { - min: 100, - max: 4320, - step: 1 - }); - canvasfolder.addInput(canvasparameters, "transparent").on("change", ()=>{ - console.log(1); - BabylonInteractivity.setTransparency(canvasparameters.transparent); - }); - let starparameters = { - density: 1.5, - brightness: 100 - }; - let starfolder = pane.addFolder({ - title: "Stars", - expanded: true - }); - starfolder.addInput(starparameters, "density", { - min: 0, - max: 10, - step: 0.01, - format: (value)=>value.toFixed(2) + "%" - }); - starfolder.addInput(starparameters, "brightness", { - min: 0, - max: 200, - step: 0.1, - format: (value)=>value.toFixed(1) + "%" - }); - let nebulaparameters = { - count: 2, - scale: 5, - depth: 2, - intensity: 100, - falloff: 2, - persistence: 0.5 - }; - let nebulafolder = pane.addFolder({ - title: "Nebula", - expanded: true - }); - nebulafolder.addInput(nebulaparameters, "count", { - min: 0, - max: 3, - step: 1 - }).on("change", ()=>{ - if (nebulaparameters.count == 0) { - colorfolder.hidden = true; - } else { - colorfolder.hidden = false; - for(let i = 0; i < colorinputs.length; i++){ - if (i < nebulaparameters.count) { - colorinputs[i].hidden = false; - } else { - colorinputs[i].hidden = true; - } - } - } - pane.refresh(); - }); - let colorparameters = {}; - let colorfolder = nebulafolder.addFolder({ - title: "Colors", - expanded: false - }); - let colorinputs = []; - for(let i = 0; i < 3; i++){ - colorparameters["color" + (i + 1)] = { - r: Math.ceil(255 * Math.random()), - g: Math.ceil(255 * Math.random()), - b: Math.ceil(255 * Math.random()) - }; - colorinputs.push(colorfolder.addInput(colorparameters, "color" + (i + 1))); - if (i > nebulaparameters.count - 1) { - colorinputs[i].hidden = true; - } - } - nebulafolder.addInput(nebulaparameters, "scale", { - min: 1, - max: 50, - step: 1 - }); - nebulafolder.addInput(nebulaparameters, "depth", { - min: 0, - max: 20, - step: 1 - }); - nebulafolder.addInput(nebulaparameters, "intensity", { - min: 50, - max: 150, - step: 1, - format: (value)=>value + "%" - }); - nebulafolder.addInput(nebulaparameters, "falloff", { - min: 1, - max: 10, - step: 0.1 - }); - nebulafolder.addInput(nebulaparameters, "persistence", { - min: 0, - max: 1, - step: 0.01 - }); - let seedparameters = { - seed: "" + Math.floor(Math.random() * Math.pow(10, 12)) - }; - let seedfolder = pane.addFolder({ - title: "Seed", - expanded: false - }); - seedfolder.addInput(seedparameters, "seed", { - format: (value)=>value.toFixed(0) - }); - seedfolder.addButton({ - title: "Randomize seed" - }).on("click", ()=>{ - seedparameters.seed = Math.floor(Math.random() * 10 ** 12).toString(); - pane.refresh(); - BabylonInteractivity.generateFrame(); - }); - pane.addSeparator(); - pane.addButton({ - title: "Render" - }).on("click", ()=>{ - BabylonInteractivity.generateFrame(); - }); - pane.addButton({ - title: "Render Random" - }).on("click", ()=>{ - seedparameters.seed = Math.floor(Math.random() * Math.pow(10, 12)).toString(); - for(let i = 0; i < 3; i++){ - colorparameters["color" + (i + 1)] = { - r: Math.ceil(255 * Math.random()), - g: Math.ceil(255 * Math.random()), - b: Math.ceil(255 * Math.random()) - }; - } - pane.refresh(); - BabylonInteractivity.generateFrame(); - }); - pane.addSeparator(); - pane.addButton({ - title: "Save Image" - }).on("click", ()=>{ - BabylonInteractivity.exportFrame(); - }); - pane.addSeparator(); - pane.addInput(canvasparameters, "autoupdate"); - pane.on("change", (event)=>{ - let changedvalue = event.presetKey; - if (canvasparameters.autoupdate) { - if (changedvalue == "width" || changedvalue == "height") { - BabylonInteractivity.resizeFrame(canvasparameters.width, canvasparameters.height); - } - BabylonInteractivity.generateFrame(); - } - }); -} -function getParameters() { - return pane.exportPreset(); -} - -;// CONCATENATED MODULE: ./app/space/page.tsx -/* __next_internal_client_entry_do_not_use__ default auto */ - - - - -const BabylonScene = app_dynamic_default()(null, { - loadableGenerated: { - modules: [ - "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx -> " + "./BabylonScene" - ] - }, - ssr: false -}); -function Sp() { - const [loaded, setLoaded] = (0,react_.useState)(false); - // Execute setLoaded(true) on the client side immediately after - // HomePage() is rendered. This will change the state and trigger - // re-render of HomePage(). - // We want the immediate re-rendering to happen because - // 1) first time (back when `loaded === false` was true) when we render - // we ddon't render BabylonScene component at all - // (see `loaded && ...` line below) and so the page *renders completely* - // (and, hopefully, on the server) except with no Babylon.js scene/stuff - // on it (crawlers, bots, page speed analysers will love that!). - // 2) rendering it for the second time immediately after, we will actually - // render BabylonScene component, and so BabylonScene.render() will add the - // canvas node to the DOM tree and BabylonScene.componentDidMount() will - // execute all our Babylon {engine, scene, cameras, light, etc} setup on - // the client side immediately after the component (canvas element) - // is mounted to the DOM. - (0,react_.useEffect)(()=>{ - setLoaded(true); - ParameterPanel(); - }, []); - return /*#__PURE__*/ (0,jsx_runtime_.jsxs)("main", { - children: [ - /*#__PURE__*/ jsx_runtime_.jsx("div", { - id: "TweakPane", - className: "fixed top-2.5 right-2.5" - }), - loaded && /*#__PURE__*/ jsx_runtime_.jsx(BabylonScene, {}), - !loaded && /*#__PURE__*/ jsx_runtime_.jsx(Loading, {}) - ] - }); -} - - -/***/ }), - -/***/ 4494: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Loading) -/* harmony export */ }); -/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6786); -/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__); - -function Loading() { - return /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("div", { - className: "flex h-screen justify-center items-center", - children: /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("div", { - className: "flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin", - children: /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("div", { - className: "h-10 w-10 rounded-full bg-black" - }) - }) - }); -} - - -/***/ }), - -/***/ 6374: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "$$typeof": () => (/* binding */ $$typeof), -/* harmony export */ "__esModule": () => (/* binding */ __esModule), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var next_dist_build_webpack_loaders_next_flight_loader_module_proxy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1313); - -const proxy = (0,next_dist_build_webpack_loaders_next_flight_loader_module_proxy__WEBPACK_IMPORTED_MODULE_0__.createProxy)(String.raw`X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\space\page.tsx`) - -// Accessing the __esModule property and exporting $$typeof are required here. -// The __esModule getter forces the proxy target to create the default export -// and the $$typeof value is for rendering logic to determine if the module -// is a client boundary. -const { __esModule, $$typeof } = proxy; -const __default__ = proxy.default; - - -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__default__); - -/***/ }) - -}; -; - -// load runtime -var __webpack_require__ = require("../../webpack-runtime.js"); -__webpack_require__.C(exports); -var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId)) -var __webpack_exports__ = __webpack_require__.X(0, [405,616,864,816], () => (__webpack_exec__(3014))); -module.exports = __webpack_exports__; - -})(); \ No newline at end of file +(()=>{var e={};e.id=514,e.ids=[514],e.modules={5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},8899:(e,t,a)=>{"use strict";a.r(t),a.d(t,{GlobalError:()=>i.a,__next_app__:()=>u,originalPathname:()=>p,pages:()=>c,routeModule:()=>h,tree:()=>l});var n=a(7096),r=a(6132),s=a(7284),i=a.n(s),o=a(2564),d={};for(let e in o)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(d[e]=()=>o[e]);a.d(t,d);let l=["",{children:["space",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(a.bind(a,5237)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx"]}]},{loading:[()=>Promise.resolve().then(a.bind(a,9771)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\loading.tsx"],metadata:{icon:[async e=>(await Promise.resolve().then(a.bind(a,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(a.bind(a,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(a.t.bind(a,9291,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(a.bind(a,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],c=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx"],p="/space/page",u={require:a,loadChunk:()=>Promise.resolve()},h=new n.AppPageRouteModule({definition:{kind:r.x.APP_PAGE,page:"/space/page",pathname:"/space",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:l}})},4038:(e,t,a)=>{Promise.resolve().then(a.bind(a,9663))},5303:()=>{},7690:(e,t,a)=>{"use strict";let n,r,s,i,o,d,l;a.d(t,{Z:()=>BabylonInteractivity});var c=a(4494),p=a(102);let u=[];function hashString(e){var t,a=0;for(t=0;t>>15,1|t),(((t^=t+Math.imul(t^t>>>7,61|t))^t>>>14)>>>0)/4294967296}let BabylonInteractivity=class BabylonInteractivity{static generateFrame(){if(!n)return;let e=performance.now(),t=(0,p.g)();(n.width!=t.width||n.height!=t.height)&&this.resizeFrame(t.width,t.height),d!=t.seed&&(l=mulberry32(hashString(t.seed)),d=t.seed,console.log(1)),o.onApply=e=>{e.setFloat("seed",l+5),e.setFloat("density",t.density/100),e.setFloat("brightness",t.brightness/100)};for(let e=0;e{a.setFloat("seed",1e3*l*(e+1)),a.setFloat4("color",t[`color${e+1}`].r/255,t[`color${e+1}`].g/255,t[`color${e+1}`].b/255,1),a.setUInt("nebulascale",t.scale),a.setUInt("depth",t.depth),a.setFloat("intensity",t.intensity/100-1),a.setFloat("falloff",t.falloff),a.setFloat("persistence",t.persistence)},u[e].onApplyObservable.add(t=>{t.setTextureSampler("textureSamplerSampler",u[e].inputTexture.texture)});s.onAfterRenderObservable.addOnce(()=>{console.log(`Rendered in ${Math.round((performance.now()-e)*100)/100}ms`)}),r.beginFrame(),s.render(),r.endFrame()}static resizeFrame(e,t){n.style.width=e.toString()+"px",n.style.height=t.toString()+"px",r.resize()}static async exportFrame(){let e=(0,p.g)();c.w1W.CreateScreenshotUsingRenderTarget(r,i,{width:n.width,height:n.height},void 0,void 0,void 0,void 0,`nebula-${e.seed}`),this.generateFrame()}static setTransparency(e){e?s.clearColor=new c.HEv(0,0,0,0):s.clearColor=new c.HEv(0,0,0,1)}static initialize(e,t,a,d){n=e,r=t,s=a,i=d,o=new c.Dso("StarShader","stars",null,null,1,i,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL),i.attachPostProcess(o);for(let e=0;e<10;e++)u.push(new c.Dso("NebulaShader","nebulas",null,null,1,i,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL))}}},102:(e,t,a)=>{"use strict";let n;a.d(t,{Z:()=>ParameterPanel,g:()=>getParameters});var r=a(6224),s=a(7690);function ParameterPanel(){n=new r.Pane({title:"Parameters",container:document.getElementById("TweakPane")||void 0});let e={width:window.innerWidth,height:window.innerHeight,transparent:!1,autoupdate:!1},t=n.addFolder({title:"Canvas",expanded:!0});t.addInput(e,"width",{min:100,max:7680,step:1}),t.addInput(e,"height",{min:100,max:4320,step:1}),t.addInput(e,"transparent").on("change",()=>{console.log(1),s.Z.setTransparency(e.transparent)});let a={density:1.5,brightness:100},i=n.addFolder({title:"Stars",expanded:!0});i.addInput(a,"density",{min:0,max:10,step:.01,format:e=>e.toFixed(2)+"%"}),i.addInput(a,"brightness",{min:0,max:200,step:.1,format:e=>e.toFixed(1)+"%"});let o={count:2,scale:5,depth:2,intensity:100,falloff:2,persistence:.5},d=n.addFolder({title:"Nebula",expanded:!0});d.addInput(o,"count",{min:0,max:3,step:1}).on("change",()=>{if(0==o.count)c.hidden=!0;else{c.hidden=!1;for(let e=0;eo.count-1&&(p[e].hidden=!0);d.addInput(o,"scale",{min:1,max:50,step:1}),d.addInput(o,"depth",{min:0,max:20,step:1}),d.addInput(o,"intensity",{min:50,max:150,step:1,format:e=>e+"%"}),d.addInput(o,"falloff",{min:1,max:10,step:.1}),d.addInput(o,"persistence",{min:0,max:1,step:.01});let u={seed:""+Math.floor(1e12*Math.random())},h=n.addFolder({title:"Seed",expanded:!1});h.addInput(u,"seed",{format:e=>e.toFixed(0)}),h.addButton({title:"Randomize seed"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString(),n.refresh(),s.Z.generateFrame()}),n.addSeparator(),n.addButton({title:"Render"}).on("click",()=>{s.Z.generateFrame()}),n.addButton({title:"Render Random"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString();for(let e=0;e<3;e++)l["color"+(e+1)]={r:Math.ceil(255*Math.random()),g:Math.ceil(255*Math.random()),b:Math.ceil(255*Math.random())};n.refresh(),s.Z.generateFrame()}),n.addSeparator(),n.addButton({title:"Save Image"}).on("click",()=>{s.Z.exportFrame()}),n.addSeparator(),n.addInput(e,"autoupdate"),n.on("change",t=>{let a=t.presetKey;e.autoupdate&&(("width"==a||"height"==a)&&s.Z.resizeFrame(e.width,e.height),s.Z.generateFrame())})}function getParameters(){return n.exportPreset()}},9663:(e,t,a)=>{"use strict";a.r(t),a.d(t,{default:()=>Sp});var n=a(784),r=a(9885),s=a(3642),i=a.n(s);function Loading(){return n.jsx("div",{className:"flex h-screen justify-center items-center",children:n.jsx("div",{className:"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin",children:n.jsx("div",{className:"h-10 w-10 rounded-full bg-black"})})})}var o=a(102);let d=i()(()=>a.e(106).then(a.bind(a,4106)),{loadableGenerated:{modules:["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx -> ./BabylonScene"]},ssr:!1});function Sp(){let[e,t]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{t(!0),(0,o.Z)()},[]),(0,n.jsxs)("main",{children:[n.jsx("div",{id:"TweakPane",className:"fixed top-2.5 right-2.5"}),e&&n.jsx(d,{}),!e&&n.jsx(Loading,{})]})}},9771:(e,t,a)=>{"use strict";a.r(t),a.d(t,{default:()=>Loading});var n=a(4656);function Loading(){return n.jsx("div",{className:"flex h-screen justify-center items-center",children:n.jsx("div",{className:"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin",children:n.jsx("div",{className:"h-10 w-10 rounded-full bg-black"})})})}},5237:(e,t,a)=>{"use strict";a.r(t),a.d(t,{$$typeof:()=>i,__esModule:()=>s,default:()=>d});var n=a(5153);let r=(0,n.createProxy)(String.raw`X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\space\page.tsx`),{__esModule:s,$$typeof:i}=r,o=r.default,d=o},7481:(e,t,a)=>{"use strict";a.r(t),a.d(t,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var n=a(8531);let __WEBPACK_DEFAULT_EXPORT__=e=>{let t=(0,n.fillMetadataSegment)(".",e.params,"favicon.ico");return[{type:"image/x-icon",sizes:"16x16",url:t+""}]}}};var t=require("../../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),a=t.X(0,[862,323,984,622],()=>__webpack_exec__(8899));module.exports=a})(); \ No newline at end of file diff --git a/.next/server/app/space/page.js.nft.json b/.next/server/app/space/page.js.nft.json index e3639a7..886634f 100644 --- a/.next/server/app/space/page.js.nft.json +++ b/.next/server/app/space/page.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../webpack-runtime.js","../../chunks/405.js","../../chunks/616.js","../../chunks/864.js","../../chunks/816.js","../../../package.json","../../../../node_modules/next/package.json","../../../../node_modules/next/dist/shared/lib/app-router-context.js","../../../../node_modules/next/dist/shared/lib/hooks-client-context.js","../../../../node_modules/next/dist/shared/lib/server-inserted-html.js","../../../../node_modules/next/dist/server/app-render/get-segment-param.js","../../../../node_modules/next/dist/server/future/helpers/interception-routes.js","../../../../node_modules/react/package.json","../../../../node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js","../../../../node_modules/next/dist/shared/lib/router/utils/handle-smooth-scroll.js","../../../../node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js","../../../../node_modules/next/dist/shared/lib/router/utils/is-bot.js","../../../../node_modules/next/dist/shared/lib/router/utils/parse-path.js","../../../../node_modules/react/index.js","../../../../node_modules/next/dist/compiled/react/jsx-runtime.js","../../../../node_modules/next/dist/compiled/react-dom/server-rendering-stub.js","../../../../node_modules/next/dist/compiled/react-server-dom-webpack/client.js","../../../../node_modules/next/dist/compiled/react/package.json","../../../../node_modules/next/dist/compiled/react-dom/package.json","../../../../node_modules/next/dist/compiled/react-server-dom-webpack/package.json","../../../../node_modules/next/dist/compiled/path-to-regexp/index.js","../../../../node_modules/next/dist/compiled/react/index.js","../../../../node_modules/react/cjs/react.production.min.js","../../../../node_modules/react/cjs/react.development.js","../../../../node_modules/next/dist/compiled/cookie/package.json","../../../../node_modules/next/dist/compiled/cookie/index.js","../../../../node_modules/next/dist/shared/lib/router/utils/app-paths.js","../../../../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.production.min.js","../../../../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.development.js","../../../../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.production.min.js","../../../../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.development.js","../../../../node_modules/next/dist/compiled/react-server-dom-webpack/client.browser.js","../../../../node_modules/next/dist/compiled/react/cjs/react.production.min.js","../../../../node_modules/next/dist/compiled/react/cjs/react.development.js","../../../../node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js","../../../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.production.min.js","../../../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.development.js","../../../../node_modules/@swc/helpers/_/_interop_require_default/package.json","../../../../node_modules/@swc/helpers/_/_interop_require_wildcard/package.json","../../../../node_modules/@swc/helpers/package.json","../../../../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../../../../node_modules/@swc/helpers/cjs/_interop_require_wildcard.cjs","../../../../node_modules/react-dom/package.json","../../../../node_modules/react-dom/index.js","../../../../node_modules/react-dom/cjs/react-dom.production.min.js","../../../../node_modules/react-dom/cjs/react-dom.development.js","../../../../node_modules/scheduler/package.json","../../../../node_modules/scheduler/index.js","../../../../node_modules/scheduler/cjs/scheduler.production.min.js","../../../../node_modules/scheduler/cjs/scheduler.development.js","../../../../package.json"]} \ No newline at end of file +{"version":1,"files":["../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../node_modules/next/package.json","../../../../package.json","../../../package.json","../../chunks/106.js","../../chunks/2.js","../../chunks/201.js","../../chunks/310.js","../../chunks/323.js","../../chunks/622.js","../../chunks/676.js","../../chunks/837.js","../../chunks/840.js","../../chunks/862.js","../../chunks/984.js","../../chunks/font-manifest.json","../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/space/page_client-reference-manifest.js b/.next/server/app/space/page_client-reference-manifest.js new file mode 100644 index 0000000..2c62eb3 --- /dev/null +++ b/.next/server/app/space/page_client-reference-manifest.js @@ -0,0 +1 @@ +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/space/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"341":{"*":{"id":"9663","name":"*","chunks":[],"async":false}},"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx":{"id":341,"name":"*","chunks":["732","static/chunks/e1206f8c-ab5b5541f866e530.js","105","static/chunks/1f3d3139-f107a678ff6361e9.js","735","static/chunks/604a08ec-59af37265fb99b3d.js","790","static/chunks/d67c510a-e497b3cd5bf43bb4.js","116","static/chunks/537cd76e-7aba1cf7a4752418.js","173","static/chunks/173-2ffa9652644381a8.js","514","static/chunks/app/space/page-b8120f6d5470d1c7.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\loading":[]}} \ No newline at end of file diff --git a/.next/server/app/wiston.html b/.next/server/app/wiston.html index ab9b752..f44fe18 100644 --- a/.next/server/app/wiston.html +++ b/.next/server/app/wiston.html @@ -1 +1 @@ -sukadia.dev
    ‎ -+=-:. -
    ‎ .*%#%#%%%%#*+-. ++= .:-==:
    ‎ =%%########%##%%%*-. ++-# .-+*%%%###%#-
    ‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#.
    ‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%=
    ‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%#
    ‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%:
    ‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%-
    ‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%-
    ‎ %%###################%*--------#**********#%%######################%%#%%%######%@-
    ‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@-
    ‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@:
    ‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%.
    ‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%%
    ‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%*
    ‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%=
    ‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%.
    ‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%#
    ‎ ######%%%%%%%######################################################%@%######%%#%#%##########%-
    ‎ %%#%%%%%%%%########################################################%@%#########%%%###########%
    ‎ .%%%%%%%%%###########################################################%###########%@###########%+
    ‎ =#%%%%%%########################################################################################%
    ‎ +%%%%%############################################%%#%############################################%-
    ‎ =%%%%##########%#########################################%%##########################################%%**++======+**#%
    ‎ -#%%%#########################################################%####################################%###################%.
    ‎ *%%%#####################################################################################################%###%##########%
    ‎ .#%###################################################################%##%###############%###############################%#
    ‎ .+%##############################################################################%#########################################%=
    ‎ .+%#########################################################################################################################%%
    ‎ +%##########################################################################################################################%%.
    ‎ =%#################################################################################%%@%%#####################################%%:
    ‎ -#################################################################################%@@@%#######################################%%.
    ‎ :################################################################################%@@#%########################################%%+
    ‎ +%#############################################################################%@@#- +######################################%+.
    ‎ -#############################################################################%@@#= :*#################################%*-
    ‎ =%##########################################################################%@%*- :==- +################################%.
    ‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################.
    ‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+:
    ‎ : .-+####################################################################: #%@+--- =############%#=
    ‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=:
    ‎ .:. :-+*############################################################: :+*+- - ....
    ‎ ::. .:=+*########################################################=. =
    ‎ ::. .:-=*####################################################*: .-
    ‎ ::. .:-=+*##########################################*=: .-
    ‎ .:: ..:--==++***################***++===-::. .-
    ‎ :-. ..... ..:::. .=
    ‎ .::. .-+****+====+==: +
    ‎ :::. .-+#*=:. . +
    ‎ .::. .=*#+: .::::. =:
    ‎ .... =*=. ::::: .+
    ‎ .:::. ::::. +
    ‎ .:::::.. .:::::. .=
    ‎ .::::::::::::.......::::::::::+-. =.
    ‎ ...... .+. +
    ‎ .::+ .-
    ‎ .::. +. .:
    ‎ -: :-. ::
    ‎ -- .-=: .:::. :.
    ‎ --.-=:. .---. :.
    ‎ -=. ==: :=-. :.
    ‎ :+: :-+. .-=: -
    ‎ :+- .=-. :=-. -
    ‎ .+- :-- :=- :. -
    ‎ .+=. = -=: :: .-
    ‎ .+=. =:-: -+: .-. .-
    ‎ .==. .:::::--:.=+ .=: :- .:
    ‎ ::=:---: .---. .:--+: .-. ::
    ‎ --. .+-:. .--: :- :.
    ‎ :- .. .:: .-. -.
    ‎ :: : .=. :: -.
    ‎ = .: .+: ::. -.
    ‎ =. - +. .:. -.
    ‎ + - .+ :: ::
    ‎ + . :-. + .:. ::
    ‎ + .: :- =. .:. .-
    ‎ -. .: :- .--. .:: .-
    ‎ = ::. .= == :: .-
    ‎ :: ::: :: .:-- .:. -
    ‎ -. .:::: = :---. .:. :.
    ‎ :. .:::::::=:--:. :: :.
    ‎ .:. :-= .:
    ‎ .:: .-. .:
    ‎ ::. .-: -
    ‎ .::. :-. =
    ‎ :::: .-. .=
    ‎ ::::. :: .-
    ‎ .::::::::::::. :-
    ‎ - -:
    ‎ - =
    ‎ ::::-----:::::=. =
    ‎ ::--:. .: .:
    ‎ :--:. : :
    ‎ :--. .-: :
    ‎ ----------. .==. -
    ‎ = -+. .-
    ‎ =. .+- =
    ‎ +. .*: +
    ‎ .::--: .*. +
    ‎ .- .+. :-
    ‎ :: +. --:
    ‎ -. :- .---::::.
    ‎ .: + .-
    ‎ = .- .-
    ‎ -. -. :=
    ‎ = = .-=:
    ‎ -: - .=---:
    ‎ = -. .--:-
    ‎ = ....:::-= .=.
    ‎ ..::::......:::::::::::. + .:.. .::::. :==
    ‎ :::::::. .::-::::: = .... :---:. .:-==:
    ‎ .- .. .:-::: = .:.. .:--:. --
    ‎ .:=. :+ .:. ::::. .*
    ‎ -: :: ::. :::: *.
    ‎ .: -. .-. .. .:. --
    ‎ - .-: .=. .= .=- =. .+
    ‎ - -=. .=. -. :+. +: .+
    ‎ - =- .=. = :*. +: +
    ‎ .: := -: - .*. :+ =.
    ‎ :. * .-. + +: *. .-
    ‎ :: + :-. --:. .* .* ::.
    ‎ ::. + --. ...-:. := .+ :-:
    ‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:.
    ‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--:
    ‎ .:::::::::... ..... + .... .:--::
    ‎ ..::::::::..:- .:..:::::. .::-:::::
    \ No newline at end of file +wiston
    ‎ -+=-:. -
    ‎ .*%#%#%%%%#*+-. ++= .:-==:
    ‎ =%%########%##%%%*-. ++-# .-+*%%%###%#-
    ‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#.
    ‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%=
    ‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%#
    ‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%:
    ‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%-
    ‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%-
    ‎ %%###################%*--------#**********#%%######################%%#%%%######%@-
    ‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@-
    ‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@:
    ‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%.
    ‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%%
    ‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%*
    ‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%=
    ‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%.
    ‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%#
    ‎ ######%%%%%%%######################################################%@%######%%#%#%##########%-
    ‎ %%#%%%%%%%%########################################################%@%#########%%%###########%
    ‎ .%%%%%%%%%###########################################################%###########%@###########%+
    ‎ =#%%%%%%########################################################################################%
    ‎ +%%%%%############################################%%#%############################################%-
    ‎ =%%%%##########%#########################################%%##########################################%%**++======+**#%
    ‎ -#%%%#########################################################%####################################%###################%.
    ‎ *%%%#####################################################################################################%###%##########%
    ‎ .#%###################################################################%##%###############%###############################%#
    ‎ .+%##############################################################################%#########################################%=
    ‎ .+%#########################################################################################################################%%
    ‎ +%##########################################################################################################################%%.
    ‎ =%#################################################################################%%@%%#####################################%%:
    ‎ -#################################################################################%@@@%#######################################%%.
    ‎ :################################################################################%@@#%########################################%%+
    ‎ +%#############################################################################%@@#- +######################################%+.
    ‎ -#############################################################################%@@#= :*#################################%*-
    ‎ =%##########################################################################%@%*- :==- +################################%.
    ‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################.
    ‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+:
    ‎ : .-+####################################################################: #%@+--- =############%#=
    ‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=:
    ‎ .:. :-+*############################################################: :+*+- - ....
    ‎ ::. .:=+*########################################################=. =
    ‎ ::. .:-=*####################################################*: .-
    ‎ ::. .:-=+*##########################################*=: .-
    ‎ .:: ..:--==++***################***++===-::. .-
    ‎ :-. ..... ..:::. .=
    ‎ .::. .-+****+====+==: +
    ‎ :::. .-+#*=:. . +
    ‎ .::. .=*#+: .::::. =:
    ‎ .... =*=. ::::: .+
    ‎ .:::. ::::. +
    ‎ .:::::.. .:::::. .=
    ‎ .::::::::::::.......::::::::::+-. =.
    ‎ ...... .+. +
    ‎ .::+ .-
    ‎ .::. +. .:
    ‎ -: :-. ::
    ‎ -- .-=: .:::. :.
    ‎ --.-=:. .---. :.
    ‎ -=. ==: :=-. :.
    ‎ :+: :-+. .-=: -
    ‎ :+- .=-. :=-. -
    ‎ .+- :-- :=- :. -
    ‎ .+=. = -=: :: .-
    ‎ .+=. =:-: -+: .-. .-
    ‎ .==. .:::::--:.=+ .=: :- .:
    ‎ ::=:---: .---. .:--+: .-. ::
    ‎ --. .+-:. .--: :- :.
    ‎ :- .. .:: .-. -.
    ‎ :: : .=. :: -.
    ‎ = .: .+: ::. -.
    ‎ =. - +. .:. -.
    ‎ + - .+ :: ::
    ‎ + . :-. + .:. ::
    ‎ + .: :- =. .:. .-
    ‎ -. .: :- .--. .:: .-
    ‎ = ::. .= == :: .-
    ‎ :: ::: :: .:-- .:. -
    ‎ -. .:::: = :---. .:. :.
    ‎ :. .:::::::=:--:. :: :.
    ‎ .:. :-= .:
    ‎ .:: .-. .:
    ‎ ::. .-: -
    ‎ .::. :-. =
    ‎ :::: .-. .=
    ‎ ::::. :: .-
    ‎ .::::::::::::. :-
    ‎ - -:
    ‎ - =
    ‎ ::::-----:::::=. =
    ‎ ::--:. .: .:
    ‎ :--:. : :
    ‎ :--. .-: :
    ‎ ----------. .==. -
    ‎ = -+. .-
    ‎ =. .+- =
    ‎ +. .*: +
    ‎ .::--: .*. +
    ‎ .- .+. :-
    ‎ :: +. --:
    ‎ -. :- .---::::.
    ‎ .: + .-
    ‎ = .- .-
    ‎ -. -. :=
    ‎ = = .-=:
    ‎ -: - .=---:
    ‎ = -. .--:-
    ‎ = ....:::-= .=.
    ‎ ..::::......:::::::::::. + .:.. .::::. :==
    ‎ :::::::. .::-::::: = .... :---:. .:-==:
    ‎ .- .. .:-::: = .:.. .:--:. --
    ‎ .:=. :+ .:. ::::. .*
    ‎ -: :: ::. :::: *.
    ‎ .: -. .-. .. .:. --
    ‎ - .-: .=. .= .=- =. .+
    ‎ - -=. .=. -. :+. +: .+
    ‎ - =- .=. = :*. +: +
    ‎ .: := -: - .*. :+ =.
    ‎ :. * .-. + +: *. .-
    ‎ :: + :-. --:. .* .* ::.
    ‎ ::. + --. ...-:. := .+ :-:
    ‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:.
    ‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--:
    ‎ .:::::::::... ..... + .... .:--::
    ‎ ..::::::::..:- .:..:::::. .::-:::::
    \ No newline at end of file diff --git a/.next/server/app/wiston.meta b/.next/server/app/wiston.meta index 8dc4f28..ddd29df 100644 --- a/.next/server/app/wiston.meta +++ b/.next/server/app/wiston.meta @@ -1 +1,5 @@ -{"headers":{"x-next-cache-tags":"/wiston/page"}} \ No newline at end of file +{ + "headers": { + "x-next-cache-tags": "_N_T_/layout,_N_T_/wiston/layout,_N_T_/wiston/page,_N_T_/wiston" + } +} \ No newline at end of file diff --git a/.next/server/app/wiston.rsc b/.next/server/app/wiston.rsc index d4bc822..d07b312 100644 --- a/.next/server/app/wiston.rsc +++ b/.next/server/app/wiston.rsc @@ -1,8 +1,7 @@ -1:HL["/_next/static/css/3930d1a0ca01c66f.css",{"as":"style"}] -0:[[["",{"children":["wiston",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/3930d1a0ca01c66f.css","precedence":"next"}]],["$L3",null]]]] -4:I{"id":"4463","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -5:I{"id":"1010","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -6:I{"id":"4143","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"name":"","async":false} -7:I{"id":"1899","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"name":"","async":false} -2:[["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_0ec1f4","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$L5",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","wiston","children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$L5",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":[["$","$L6",null,{"propsForComponent":{"params":{}},"Component":"$7"}],null],"segment":"__PAGE__"},"styles":[]}],"segment":"wiston"},"styles":[]}]}]}],null] -3:[[["$","meta",null,{"charSet":"utf-8"}],["$","title",null,{"children":"sukadia.dev"}],["$","meta",null,{"name":"description","content":"I code, stream, and create videos."}],null,null,null,null,null,null,null,null,["$","meta",null,{"name":"viewport","content":"width=device-width, initial-scale=1"}],null,null,null,null,null,null,null,null,null,null,[]],[null,null,null,null],null,null,[null,null,null,null,null],null,null,null,null,[null,[["$","link",null,{"rel":"icon","href":"\\favicon.ico","type":"image/x-icon","sizes":"any"}]],[],null]] +1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] +0:["9CqSqX2Hqhh4fwiD8kSfJ",[[["",{"children":["wiston",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] +4:I[6954,[],""] +5:I[7264,[],""] +2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","wiston","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$L6",["$","main",null,{"className":"flex flex-col items-center","children":["$","span",null,{"className":"whitespace-pre-wrap font-mono text-[0.2rem] leading-[0.25rem]","children":["‎ -+=-:. - ",["$","br",null,{}],"‎ .*%#%#%%%%#*+-. ++= .:-==: ",["$","br",null,{}],"‎ =%%########%##%%%*-. ++-# .-+*%%%###%#- ",["$","br",null,{}],"‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#. ",["$","br",null,{}],"‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%= ",["$","br",null,{}],"‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%# ",["$","br",null,{}],"‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%: ",["$","br",null,{}],"‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%- ",["$","br",null,{}],"‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%- ",["$","br",null,{}],"‎ %%###################%*--------#**********#%%######################%%#%%%######%@- ",["$","br",null,{}],"‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@- ",["$","br",null,{}],"‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@: ",["$","br",null,{}],"‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%. ",["$","br",null,{}],"‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%% ",["$","br",null,{}],"‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%* ",["$","br",null,{}],"‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%= ",["$","br",null,{}],"‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%. ",["$","br",null,{}],"‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%# ",["$","br",null,{}],"‎ ######%%%%%%%######################################################%@%######%%#%#%##########%- ",["$","br",null,{}],"‎ %%#%%%%%%%%########################################################%@%#########%%%###########% ",["$","br",null,{}],"‎ .%%%%%%%%%###########################################################%###########%@###########%+ ",["$","br",null,{}],"‎ =#%%%%%%########################################################################################% ",["$","br",null,{}],"‎ +%%%%%############################################%%#%############################################%- ",["$","br",null,{}],"‎ =%%%%##########%#########################################%%##########################################%%**++======+**#% ",["$","br",null,{}],"‎ -#%%%#########################################################%####################################%###################%. ",["$","br",null,{}],"‎ *%%%#####################################################################################################%###%##########% ",["$","br",null,{}],"‎ .#%###################################################################%##%###############%###############################%# ",["$","br",null,{}],"‎ .+%##############################################################################%#########################################%= ",["$","br",null,{}],"‎ .+%#########################################################################################################################%% ",["$","br",null,{}],"‎ +%##########################################################################################################################%%. ",["$","br",null,{}],"‎ =%#################################################################################%%@%%#####################################%%: ",["$","br",null,{}],"‎ -#################################################################################%@@@%#######################################%%. ",["$","br",null,{}],"‎ :################################################################################%@@#%########################################%%+ ",["$","br",null,{}],"‎ +%#############################################################################%@@#- +######################################%+. ",["$","br",null,{}],"‎ -#############################################################################%@@#= :*#################################%*- ",["$","br",null,{}],"‎ =%##########################################################################%@%*- :==- +################################%. ",["$","br",null,{}],"‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################. ",["$","br",null,{}],"‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+: ",["$","br",null,{}],"‎ : .-+####################################################################: #%@+--- =############%#= ",["$","br",null,{}],"‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=: ",["$","br",null,{}],"‎ .:. :-+*############################################################: :+*+- - .... ",["$","br",null,{}],"‎ ::. .:=+*########################################################=. = ",["$","br",null,{}],"‎ ::. .:-=*####################################################*: .- ",["$","br",null,{}],"‎ ::. .:-=+*##########################################*=: .- ",["$","br",null,{}],"‎ .:: ..:--==++***################***++===-::. .- ",["$","br",null,{}],"‎ :-. ..... ..:::. .= ",["$","br",null,{}],"‎ .::. .-+****+====+==: + ",["$","br",null,{}],"‎ :::. .-+#*=:. . + ",["$","br",null,{}],"‎ .::. .=*#+: .::::. =: ",["$","br",null,{}],"‎ .... =*=. ::::: .+ ",["$","br",null,{}],"‎ .:::. ::::. + ",["$","br",null,{}],"‎ .:::::.. .:::::. .= ",["$","br",null,{}],"‎ .::::::::::::.......::::::::::+-. =. ",["$","br",null,{}],"‎ ...... .+. + ",["$","br",null,{}],"‎ .::+ .- ",["$","br",null,{}],"‎ .::. +. .: ",["$","br",null,{}],"‎ -: :-. :: ",["$","br",null,{}],"‎ -- .-=: .:::. :. ",["$","br",null,{}],"‎ --.-=:. .---. :. ",["$","br",null,{}],"‎ -=. ==: :=-. :. ",["$","br",null,{}],"‎ :+: :-+. .-=: - ",["$","br",null,{}],"‎ :+- .=-. :=-. - ",["$","br",null,{}],"‎ .+- :-- :=- :. - ",["$","br",null,{}],"‎ .+=. = -=: :: .- ",["$","br",null,{}],"‎ .+=. =:-: -+: .-. .- ",["$","br",null,{}],"‎ .==. .:::::--:.=+ .=: :- .: ",["$","br",null,{}],"‎ ::=:---: .---. .:--+: .-. :: ",["$","br",null,{}],"‎ --. .+-:. .--: :- :. ",["$","br",null,{}],"‎ :- .. .:: .-. -. ",["$","br",null,{}],"‎ :: : .=. :: -. ",["$","br",null,{}],"‎ = .: .+: ::. -. ",["$","br",null,{}],"‎ =. - +. .:. -. ",["$","br",null,{}],"‎ + - .+ :: :: ",["$","br",null,{}],"‎ + . :-. + .:. :: ",["$","br",null,{}],"‎ + .: :- =. .:. .- ",["$","br",null,{}],"‎ -. .: :- .--. .:: .- ",["$","br",null,{}],"‎ = ::. .= == :: .- ",["$","br",null,{}],"‎ :: ::: :: .:-- .:. - ",["$","br",null,{}],"‎ -. .:::: = :---. .:. :. ",["$","br",null,{}],"‎ :. .:::::::=:--:. :: :. ",["$","br",null,{}],"‎ .:. :-= .: ",["$","br",null,{}],"‎ .:: .-. .: ",["$","br",null,{}],"‎ ::. .-: - ",["$","br",null,{}],"‎ .::. :-. = ",["$","br",null,{}],"‎ :::: .-. .= ",["$","br",null,{}],"‎ ::::. :: .- ",["$","br",null,{}],"‎ .::::::::::::. :- ",["$","br",null,{}],"‎ - -: ",["$","br",null,{}],"‎ - = ",["$","br",null,{}],"‎ ::::-----:::::=. = ",["$","br",null,{}],"‎ ::--:. .: .: ",["$","br",null,{}],"‎ :--:. : : ",["$","br",null,{}],"‎ :--. .-: : ",["$","br",null,{}],"‎ ----------. .==. - ",["$","br",null,{}],"‎ = -+. .- ",["$","br",null,{}],"‎ =. .+- = ",["$","br",null,{}],"‎ +. .*: + ",["$","br",null,{}],"‎ .::--: .*. + ",["$","br",null,{}],"‎ .- .+. :- ",["$","br",null,{}],"‎ :: +. --: ",["$","br",null,{}],"‎ -. :- .---::::. ",["$","br",null,{}],"‎ .: + .-",["$","br",null,{}],"‎ = .- .-",["$","br",null,{}],"‎ -. -. :=",["$","br",null,{}],"‎ = = .-=: ",["$","br",null,{}],"‎ -: - .=---: ",["$","br",null,{}],"‎ = -. .--:- ",["$","br",null,{}],"‎ = ....:::-= .=. ",["$","br",null,{}],"‎ ..::::......:::::::::::. + .:.. .::::. :== ",["$","br",null,{}],"‎ :::::::. .::-::::: = .... :---:. .:-==: ",["$","br",null,{}],"‎ .- .. .:-::: = .:.. .:--:. -- ",["$","br",null,{}],"‎ .:=. :+ .:. ::::. .* ",["$","br",null,{}],"‎ -: :: ::. :::: *. ",["$","br",null,{}],"‎ .: -. .-. .. .:. -- ",["$","br",null,{}],"‎ - .-: .=. .= .=- =. .+ ",["$","br",null,{}],"‎ - -=. .=. -. :+. +: .+ ",["$","br",null,{}],"‎ - =- .=. = :*. +: + ",["$","br",null,{}],"‎ .: := -: - .*. :+ =. ",["$","br",null,{}],"‎ :. * .-. + +: *. .- ",["$","br",null,{}],"‎ :: + :-. --:. .* .* ::. ",["$","br",null,{}],"‎ ::. + --. ...-:. := .+ :-: ",["$","br",null,{}],"‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:. ",["$","br",null,{}],"‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--: ",["$","br",null,{}],"‎ .:::::::::... ..... + .... .:--:: ",["$","br",null,{}],"‎ ..::::::::..:- .:..:::::. .::-::::: ",["$","br",null,{}]]}]}],null],"segment":"__PAGE__"},"styles":null}],"segment":"wiston"},"styles":null}]}]}],null] +3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"wiston"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +6:null diff --git a/.next/server/app/wiston/page.js b/.next/server/app/wiston/page.js index 68aec72..8327831 100644 --- a/.next/server/app/wiston/page.js +++ b/.next/server/app/wiston/page.js @@ -1,593 +1 @@ -(() => { -var exports = {}; -exports.id = 619; -exports.ids = [619]; -exports.modules = { - -/***/ 252: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/cookie"); - -/***/ }), - -/***/ 7999: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/path-to-regexp"); - -/***/ }), - -/***/ 8038: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react"); - -/***/ }), - -/***/ 8704: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react-dom/server-rendering-stub"); - -/***/ }), - -/***/ 7897: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react-server-dom-webpack/client"); - -/***/ }), - -/***/ 6786: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/compiled/react/jsx-runtime"); - -/***/ }), - -/***/ 1090: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/server/app-render/get-segment-param.js"); - -/***/ }), - -/***/ 8652: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/server/future/helpers/interception-routes.js"); - -/***/ }), - -/***/ 3280: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/app-router-context.js"); - -/***/ }), - -/***/ 9274: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/hooks-client-context.js"); - -/***/ }), - -/***/ 1751: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/add-path-prefix.js"); - -/***/ }), - -/***/ 1668: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/handle-smooth-scroll.js"); - -/***/ }), - -/***/ 1897: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/is-bot.js"); - -/***/ }), - -/***/ 8854: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/parse-path.js"); - -/***/ }), - -/***/ 3297: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/router/utils/remove-trailing-slash.js"); - -/***/ }), - -/***/ 3349: -/***/ ((module) => { - -"use strict"; -module.exports = require("next/dist/shared/lib/server-inserted-html.js"); - -/***/ }), - -/***/ 1017: -/***/ ((module) => { - -"use strict"; -module.exports = require("path"); - -/***/ }), - -/***/ 7310: -/***/ ((module) => { - -"use strict"; -module.exports = require("url"); - -/***/ }), - -/***/ 7390: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "AppRouter": () => (/* reexport default from dynamic */ next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0___default.a), -/* harmony export */ "GlobalError": () => (/* reexport default from dynamic */ next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3___default.a), -/* harmony export */ "LayoutRouter": () => (/* reexport default from dynamic */ next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1___default.a), -/* harmony export */ "RenderFromTemplateContext": () => (/* reexport default from dynamic */ next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2___default.a), -/* harmony export */ "StaticGenerationSearchParamsBailoutProvider": () => (/* reexport default from dynamic */ next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8___default.a), -/* harmony export */ "__next_app_webpack_require__": () => (/* binding */ __next_app_webpack_require__), -/* harmony export */ "actionAsyncStorage": () => (/* reexport safe */ next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__.actionAsyncStorage), -/* harmony export */ "createSearchParamsBailoutProxy": () => (/* reexport safe */ next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__.createSearchParamsBailoutProxy), -/* harmony export */ "decodeAction": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.decodeAction), -/* harmony export */ "decodeReply": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.decodeReply), -/* harmony export */ "originalPathname": () => (/* binding */ originalPathname), -/* harmony export */ "pages": () => (/* binding */ pages), -/* harmony export */ "preconnect": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preconnect), -/* harmony export */ "preloadFont": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preloadFont), -/* harmony export */ "preloadStyle": () => (/* reexport safe */ next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__.preloadStyle), -/* harmony export */ "renderToReadableStream": () => (/* reexport safe */ react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__.renderToReadableStream), -/* harmony export */ "requestAsyncStorage": () => (/* reexport safe */ next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__.requestAsyncStorage), -/* harmony export */ "serverHooks": () => (/* reexport module object */ next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__), -/* harmony export */ "staticGenerationAsyncStorage": () => (/* reexport safe */ next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__.staticGenerationAsyncStorage), -/* harmony export */ "staticGenerationBailout": () => (/* reexport safe */ next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__.staticGenerationBailout), -/* harmony export */ "tree": () => (/* binding */ tree) -/* harmony export */ }); -/* harmony import */ var next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4592); -/* harmony import */ var next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_app_router__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6301); -/* harmony import */ var next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_layout_router__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7431); -/* harmony import */ var next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_render_from_template_context__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2673); -/* harmony import */ var next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_error_boundary__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(94); -/* harmony import */ var next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_async_storage__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4437); -/* harmony import */ var next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_request_async_storage__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(6127); -/* harmony import */ var next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_action_async_storage__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(5486); -/* harmony import */ var next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_bailout__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(6404); -/* harmony import */ var next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_static_generation_searchparams_bailout_provider__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(2527); -/* harmony import */ var next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_searchparams_bailout_proxy__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(3332); -/* harmony import */ var next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(next_dist_client_components_hooks_server_context__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var react_server_dom_webpack_server_edge__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(7902); -/* harmony import */ var next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(3099); -/* harmony import */ var next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(next_dist_server_app_render_rsc_preloads__WEBPACK_IMPORTED_MODULE_12__); - - const tree = { - children: [ - '', - { - children: [ - 'wiston', - { - children: ['__PAGE__', {}, { - page: [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 2967)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx"], - - }] - }, - { - - metadata: { - icon: [(async (props) => (await Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4756))).default(props))], - apple: [], - openGraph: [], - twitter: [], - manifest: undefined - } - } - ] - }, - { - 'layout': [() => Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 729)), "X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"], - metadata: { - icon: [(async (props) => (await Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 4756))).default(props))], - apple: [], - openGraph: [], - twitter: [], - manifest: undefined - } - } - ] - }.children; - const pages = ["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx"]; - - - - - - - - - - - - - - - - - - - const __next_app_webpack_require__ = __webpack_require__ - - - const originalPathname = "/wiston/page" - - -/***/ }), - -/***/ 3784: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { - -Promise.resolve(/* import() eager */).then(__webpack_require__.bind(__webpack_require__, 5121)) - -/***/ }), - -/***/ 5121: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Wiston), -/* harmony export */ "metadata": () => (/* binding */ metadata) -/* harmony export */ }); -/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6786); -/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__); -/* __next_internal_client_entry_do_not_use__ metadata,default auto */ -const metadata = { - title: "wiston" -}; -function Wiston() { - return /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("main", { - className: "flex flex-col items-center", - children: /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("span", { - className: "whitespace-pre-wrap font-mono text-[0.2rem] leading-[0.25rem]", - children: [ - "‎ -+=-:. - ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .*%#%#%%%%#*+-. ++= .:-==: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ =%%########%##%%%*-. ++-# .-+*%%%###%#- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%= ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%# ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ %%###################%*--------#**********#%%######################%%#%%%######%@- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%% ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%* ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%= ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%# ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ######%%%%%%%######################################################%@%######%%#%#%##########%- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ %%#%%%%%%%%########################################################%@%#########%%%###########% ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .%%%%%%%%%###########################################################%###########%@###########%+ ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ =#%%%%%%########################################################################################% ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ +%%%%%############################################%%#%############################################%- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ =%%%%##########%#########################################%%##########################################%%**++======+**#% ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -#%%%#########################################################%####################################%###################%. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ *%%%#####################################################################################################%###%##########% ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .#%###################################################################%##%###############%###############################%# ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .+%##############################################################################%#########################################%= ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .+%#########################################################################################################################%% ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ +%##########################################################################################################################%%. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ =%#################################################################################%%@%%#####################################%%: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -#################################################################################%@@@%#######################################%%. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :################################################################################%@@#%########################################%%+ ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ +%#############################################################################%@@#- +######################################%+. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -#############################################################################%@@#= :*#################################%*- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ =%##########################################################################%@%*- :==- +################################%. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ : .-+####################################################################: #%@+--- =############%#= ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .:. :-+*############################################################: :+*+- - .... ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ::. .:=+*########################################################=. = ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ::. .:-=*####################################################*: .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ::. .:-=+*##########################################*=: .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .:: ..:--==++***################***++===-::. .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :-. ..... ..:::. .= ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .::. .-+****+====+==: + ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :::. .-+#*=:. . + ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .::. .=*#+: .::::. =: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .... =*=. ::::: .+ ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .:::. ::::. + ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .:::::.. .:::::. .= ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .::::::::::::.......::::::::::+-. =. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ...... .+. + ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .::+ .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .::. +. .: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -: :-. :: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -- .-=: .:::. :. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ --.-=:. .---. :. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -=. ==: :=-. :. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :+: :-+. .-=: - ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :+- .=-. :=-. - ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .+- :-- :=- :. - ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .+=. = -=: :: .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .+=. =:-: -+: .-. .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .==. .:::::--:.=+ .=: :- .: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ::=:---: .---. .:--+: .-. :: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ --. .+-:. .--: :- :. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :- .. .:: .-. -. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :: : .=. :: -. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ = .: .+: ::. -. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ =. - +. .:. -. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ + - .+ :: :: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ + . :-. + .:. :: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ + .: :- =. .:. .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -. .: :- .--. .:: .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ = ::. .= == :: .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :: ::: :: .:-- .:. - ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -. .:::: = :---. .:. :. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :. .:::::::=:--:. :: :. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .:. :-= .: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .:: .-. .: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ::. .-: - ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .::. :-. = ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :::: .-. .= ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ::::. :: .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .::::::::::::. :- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ - -: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ - = ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ::::-----:::::=. = ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ::--:. .: .: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :--:. : : ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :--. .-: : ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ----------. .==. - ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ = -+. .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ =. .+- = ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ +. .*: + ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .::--: .*. + ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .- .+. :- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :: +. --: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -. :- .---::::. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .: + .-", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ = .- .-", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -. -. :=", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ = = .-=: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -: - .=---: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ = -. .--:- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ = ....:::-= .=. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ..::::......:::::::::::. + .:.. .::::. :== ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :::::::. .::-::::: = .... :---:. .:-==: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .- .. .:-::: = .:.. .:--:. -- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .:=. :+ .:. ::::. .* ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ -: :: ::. :::: *. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .: -. .-. .. .:. -- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ - .-: .=. .= .=- =. .+ ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ - -=. .=. -. :+. +: .+ ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ - =- .=. = :*. +: + ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .: := -: - .*. :+ =. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :. * .-. + +: *. .- ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ :: + :-. --:. .* .* ::. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ::. + --. ...-:. := .+ :-: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:. ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ .:::::::::... ..... + .... .:--:: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}), - "‎ ..::::::::..:- .:..:::::. .::-::::: ", - /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("br", {}) - ] - }) - }); -} - - -/***/ }), - -/***/ 2967: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "$$typeof": () => (/* binding */ $$typeof), -/* harmony export */ "__esModule": () => (/* binding */ __esModule), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), -/* harmony export */ "metadata": () => (/* binding */ e0) -/* harmony export */ }); -/* harmony import */ var next_dist_build_webpack_loaders_next_flight_loader_module_proxy__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1313); - -const proxy = (0,next_dist_build_webpack_loaders_next_flight_loader_module_proxy__WEBPACK_IMPORTED_MODULE_0__.createProxy)(String.raw`X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\wiston\page.tsx`) - -// Accessing the __esModule property and exporting $$typeof are required here. -// The __esModule getter forces the proxy target to create the default export -// and the $$typeof value is for rendering logic to determine if the module -// is a client boundary. -const { __esModule, $$typeof } = proxy; -const __default__ = proxy.default; - -const e0 = proxy["metadata"]; - - -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (__default__); - -/***/ }) - -}; -; - -// load runtime -var __webpack_require__ = require("../../webpack-runtime.js"); -__webpack_require__.C(exports); -var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId)) -var __webpack_exports__ = __webpack_require__.X(0, [405,616,816], () => (__webpack_exec__(7390))); -module.exports = __webpack_exports__; - -})(); \ No newline at end of file +(()=>{var s={};s.id=619,s.ids=[619],s.modules={5403:s=>{"use strict";s.exports=require("next/dist/client/components/request-async-storage.external")},4749:s=>{"use strict";s.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:s=>{"use strict";s.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:s=>{"use strict";s.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:s=>{"use strict";s.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:s=>{"use strict";s.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:s=>{"use strict";s.exports=require("path")},7310:s=>{"use strict";s.exports=require("url")},1663:(s,r,e)=>{"use strict";e.r(r),e.d(r,{GlobalError:()=>j.a,__next_app__:()=>p,originalPathname:()=>l,pages:()=>o,routeModule:()=>u,tree:()=>i});var x=e(7096),t=e(6132),b=e(7284),j=e.n(b),a=e(2564),n={};for(let s in a)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(s)&&(n[s]=()=>a[s]);e.d(r,n);let i=["",{children:["wiston",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(e.bind(e,5410)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx"]}]},{metadata:{icon:[async s=>(await Promise.resolve().then(e.bind(e,7481))).default(s)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(e.bind(e,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(e.t.bind(e,9291,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async s=>(await Promise.resolve().then(e.bind(e,7481))).default(s)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],o=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx"],l="/wiston/page",p={require:e,loadChunk:()=>Promise.resolve()},u=new x.AppPageRouteModule({definition:{kind:t.x.APP_PAGE,page:"/wiston/page",pathname:"/wiston",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:i}})},5303:()=>{},5410:(s,r,e)=>{"use strict";e.r(r),e.d(r,{default:()=>Wiston,metadata:()=>t});var x=e(4656);let t={title:"wiston"};function Wiston(){return x.jsx("main",{className:"flex flex-col items-center",children:(0,x.jsxs)("span",{className:"whitespace-pre-wrap font-mono text-[0.2rem] leading-[0.25rem]",children:["‎ -+=-:. - ",x.jsx("br",{}),"‎ .*%#%#%%%%#*+-. ++= .:-==: ",x.jsx("br",{}),"‎ =%%########%##%%%*-. ++-# .-+*%%%###%#- ",x.jsx("br",{}),"‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#. ",x.jsx("br",{}),"‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%= ",x.jsx("br",{}),"‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%# ",x.jsx("br",{}),"‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%: ",x.jsx("br",{}),"‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%- ",x.jsx("br",{}),"‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%- ",x.jsx("br",{}),"‎ %%###################%*--------#**********#%%######################%%#%%%######%@- ",x.jsx("br",{}),"‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@- ",x.jsx("br",{}),"‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@: ",x.jsx("br",{}),"‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%. ",x.jsx("br",{}),"‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%% ",x.jsx("br",{}),"‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%* ",x.jsx("br",{}),"‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%= ",x.jsx("br",{}),"‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%. ",x.jsx("br",{}),"‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%# ",x.jsx("br",{}),"‎ ######%%%%%%%######################################################%@%######%%#%#%##########%- ",x.jsx("br",{}),"‎ %%#%%%%%%%%########################################################%@%#########%%%###########% ",x.jsx("br",{}),"‎ .%%%%%%%%%###########################################################%###########%@###########%+ ",x.jsx("br",{}),"‎ =#%%%%%%########################################################################################% ",x.jsx("br",{}),"‎ +%%%%%############################################%%#%############################################%- ",x.jsx("br",{}),"‎ =%%%%##########%#########################################%%##########################################%%**++======+**#% ",x.jsx("br",{}),"‎ -#%%%#########################################################%####################################%###################%. ",x.jsx("br",{}),"‎ *%%%#####################################################################################################%###%##########% ",x.jsx("br",{}),"‎ .#%###################################################################%##%###############%###############################%# ",x.jsx("br",{}),"‎ .+%##############################################################################%#########################################%= ",x.jsx("br",{}),"‎ .+%#########################################################################################################################%% ",x.jsx("br",{}),"‎ +%##########################################################################################################################%%. ",x.jsx("br",{}),"‎ =%#################################################################################%%@%%#####################################%%: ",x.jsx("br",{}),"‎ -#################################################################################%@@@%#######################################%%. ",x.jsx("br",{}),"‎ :################################################################################%@@#%########################################%%+ ",x.jsx("br",{}),"‎ +%#############################################################################%@@#- +######################################%+. ",x.jsx("br",{}),"‎ -#############################################################################%@@#= :*#################################%*- ",x.jsx("br",{}),"‎ =%##########################################################################%@%*- :==- +################################%. ",x.jsx("br",{}),"‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################. ",x.jsx("br",{}),"‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+: ",x.jsx("br",{}),"‎ : .-+####################################################################: #%@+--- =############%#= ",x.jsx("br",{}),"‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=: ",x.jsx("br",{}),"‎ .:. :-+*############################################################: :+*+- - .... ",x.jsx("br",{}),"‎ ::. .:=+*########################################################=. = ",x.jsx("br",{}),"‎ ::. .:-=*####################################################*: .- ",x.jsx("br",{}),"‎ ::. .:-=+*##########################################*=: .- ",x.jsx("br",{}),"‎ .:: ..:--==++***################***++===-::. .- ",x.jsx("br",{}),"‎ :-. ..... ..:::. .= ",x.jsx("br",{}),"‎ .::. .-+****+====+==: + ",x.jsx("br",{}),"‎ :::. .-+#*=:. . + ",x.jsx("br",{}),"‎ .::. .=*#+: .::::. =: ",x.jsx("br",{}),"‎ .... =*=. ::::: .+ ",x.jsx("br",{}),"‎ .:::. ::::. + ",x.jsx("br",{}),"‎ .:::::.. .:::::. .= ",x.jsx("br",{}),"‎ .::::::::::::.......::::::::::+-. =. ",x.jsx("br",{}),"‎ ...... .+. + ",x.jsx("br",{}),"‎ .::+ .- ",x.jsx("br",{}),"‎ .::. +. .: ",x.jsx("br",{}),"‎ -: :-. :: ",x.jsx("br",{}),"‎ -- .-=: .:::. :. ",x.jsx("br",{}),"‎ --.-=:. .---. :. ",x.jsx("br",{}),"‎ -=. ==: :=-. :. ",x.jsx("br",{}),"‎ :+: :-+. .-=: - ",x.jsx("br",{}),"‎ :+- .=-. :=-. - ",x.jsx("br",{}),"‎ .+- :-- :=- :. - ",x.jsx("br",{}),"‎ .+=. = -=: :: .- ",x.jsx("br",{}),"‎ .+=. =:-: -+: .-. .- ",x.jsx("br",{}),"‎ .==. .:::::--:.=+ .=: :- .: ",x.jsx("br",{}),"‎ ::=:---: .---. .:--+: .-. :: ",x.jsx("br",{}),"‎ --. .+-:. .--: :- :. ",x.jsx("br",{}),"‎ :- .. .:: .-. -. ",x.jsx("br",{}),"‎ :: : .=. :: -. ",x.jsx("br",{}),"‎ = .: .+: ::. -. ",x.jsx("br",{}),"‎ =. - +. .:. -. ",x.jsx("br",{}),"‎ + - .+ :: :: ",x.jsx("br",{}),"‎ + . :-. + .:. :: ",x.jsx("br",{}),"‎ + .: :- =. .:. .- ",x.jsx("br",{}),"‎ -. .: :- .--. .:: .- ",x.jsx("br",{}),"‎ = ::. .= == :: .- ",x.jsx("br",{}),"‎ :: ::: :: .:-- .:. - ",x.jsx("br",{}),"‎ -. .:::: = :---. .:. :. ",x.jsx("br",{}),"‎ :. .:::::::=:--:. :: :. ",x.jsx("br",{}),"‎ .:. :-= .: ",x.jsx("br",{}),"‎ .:: .-. .: ",x.jsx("br",{}),"‎ ::. .-: - ",x.jsx("br",{}),"‎ .::. :-. = ",x.jsx("br",{}),"‎ :::: .-. .= ",x.jsx("br",{}),"‎ ::::. :: .- ",x.jsx("br",{}),"‎ .::::::::::::. :- ",x.jsx("br",{}),"‎ - -: ",x.jsx("br",{}),"‎ - = ",x.jsx("br",{}),"‎ ::::-----:::::=. = ",x.jsx("br",{}),"‎ ::--:. .: .: ",x.jsx("br",{}),"‎ :--:. : : ",x.jsx("br",{}),"‎ :--. .-: : ",x.jsx("br",{}),"‎ ----------. .==. - ",x.jsx("br",{}),"‎ = -+. .- ",x.jsx("br",{}),"‎ =. .+- = ",x.jsx("br",{}),"‎ +. .*: + ",x.jsx("br",{}),"‎ .::--: .*. + ",x.jsx("br",{}),"‎ .- .+. :- ",x.jsx("br",{}),"‎ :: +. --: ",x.jsx("br",{}),"‎ -. :- .---::::. ",x.jsx("br",{}),"‎ .: + .-",x.jsx("br",{}),"‎ = .- .-",x.jsx("br",{}),"‎ -. -. :=",x.jsx("br",{}),"‎ = = .-=: ",x.jsx("br",{}),"‎ -: - .=---: ",x.jsx("br",{}),"‎ = -. .--:- ",x.jsx("br",{}),"‎ = ....:::-= .=. ",x.jsx("br",{}),"‎ ..::::......:::::::::::. + .:.. .::::. :== ",x.jsx("br",{}),"‎ :::::::. .::-::::: = .... :---:. .:-==: ",x.jsx("br",{}),"‎ .- .. .:-::: = .:.. .:--:. -- ",x.jsx("br",{}),"‎ .:=. :+ .:. ::::. .* ",x.jsx("br",{}),"‎ -: :: ::. :::: *. ",x.jsx("br",{}),"‎ .: -. .-. .. .:. -- ",x.jsx("br",{}),"‎ - .-: .=. .= .=- =. .+ ",x.jsx("br",{}),"‎ - -=. .=. -. :+. +: .+ ",x.jsx("br",{}),"‎ - =- .=. = :*. +: + ",x.jsx("br",{}),"‎ .: := -: - .*. :+ =. ",x.jsx("br",{}),"‎ :. * .-. + +: *. .- ",x.jsx("br",{}),"‎ :: + :-. --:. .* .* ::. ",x.jsx("br",{}),"‎ ::. + --. ...-:. := .+ :-: ",x.jsx("br",{}),"‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:. ",x.jsx("br",{}),"‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--: ",x.jsx("br",{}),"‎ .:::::::::... ..... + .... .:--:: ",x.jsx("br",{}),"‎ ..::::::::..:- .:..:::::. .::-::::: ",x.jsx("br",{})]})})}},7481:(s,r,e)=>{"use strict";e.r(r),e.d(r,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var x=e(8531);let __WEBPACK_DEFAULT_EXPORT__=s=>{let r=(0,x.fillMetadataSegment)(".",s.params,"favicon.ico");return[{type:"image/x-icon",sizes:"16x16",url:r+""}]}}};var r=require("../../webpack-runtime.js");r.C(s);var __webpack_exec__=s=>r(r.s=s),e=r.X(0,[862,323,622],()=>__webpack_exec__(1663));module.exports=e})(); \ No newline at end of file diff --git a/.next/server/app/wiston/page.js.nft.json b/.next/server/app/wiston/page.js.nft.json index a7c8dc6..886634f 100644 --- a/.next/server/app/wiston/page.js.nft.json +++ b/.next/server/app/wiston/page.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../webpack-runtime.js","../../chunks/405.js","../../chunks/616.js","../../chunks/816.js","../../../package.json","../../../../node_modules/next/package.json","../../../../node_modules/next/dist/shared/lib/app-router-context.js","../../../../node_modules/next/dist/shared/lib/hooks-client-context.js","../../../../node_modules/next/dist/shared/lib/server-inserted-html.js","../../../../node_modules/next/dist/server/app-render/get-segment-param.js","../../../../node_modules/next/dist/server/future/helpers/interception-routes.js","../../../../node_modules/react/package.json","../../../../node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js","../../../../node_modules/next/dist/shared/lib/router/utils/handle-smooth-scroll.js","../../../../node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js","../../../../node_modules/next/dist/shared/lib/router/utils/is-bot.js","../../../../node_modules/next/dist/shared/lib/router/utils/parse-path.js","../../../../node_modules/react/index.js","../../../../node_modules/next/dist/compiled/react/jsx-runtime.js","../../../../node_modules/next/dist/compiled/react-dom/server-rendering-stub.js","../../../../node_modules/next/dist/compiled/react-server-dom-webpack/client.js","../../../../node_modules/next/dist/compiled/react/package.json","../../../../node_modules/next/dist/compiled/react-dom/package.json","../../../../node_modules/next/dist/compiled/react-server-dom-webpack/package.json","../../../../node_modules/next/dist/compiled/path-to-regexp/index.js","../../../../node_modules/next/dist/compiled/react/index.js","../../../../node_modules/react/cjs/react.production.min.js","../../../../node_modules/react/cjs/react.development.js","../../../../node_modules/next/dist/compiled/cookie/package.json","../../../../node_modules/next/dist/compiled/cookie/index.js","../../../../node_modules/next/dist/shared/lib/router/utils/app-paths.js","../../../../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.production.min.js","../../../../node_modules/next/dist/compiled/react/cjs/react-jsx-runtime.development.js","../../../../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.production.min.js","../../../../node_modules/next/dist/compiled/react-dom/cjs/react-dom-server-rendering-stub.development.js","../../../../node_modules/next/dist/compiled/react-server-dom-webpack/client.browser.js","../../../../node_modules/next/dist/compiled/react/cjs/react.production.min.js","../../../../node_modules/next/dist/compiled/react/cjs/react.development.js","../../../../node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js","../../../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.production.min.js","../../../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.development.js","../../../../node_modules/@swc/helpers/_/_interop_require_default/package.json","../../../../node_modules/@swc/helpers/_/_interop_require_wildcard/package.json","../../../../node_modules/@swc/helpers/package.json","../../../../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../../../../node_modules/@swc/helpers/cjs/_interop_require_wildcard.cjs","../../../../node_modules/react-dom/package.json","../../../../node_modules/react-dom/index.js","../../../../node_modules/react-dom/cjs/react-dom.production.min.js","../../../../node_modules/react-dom/cjs/react-dom.development.js","../../../../node_modules/scheduler/package.json","../../../../node_modules/scheduler/index.js","../../../../node_modules/scheduler/cjs/scheduler.production.min.js","../../../../node_modules/scheduler/cjs/scheduler.development.js","../../../../package.json"]} \ No newline at end of file +{"version":1,"files":["../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../node_modules/next/package.json","../../../../package.json","../../../package.json","../../chunks/106.js","../../chunks/2.js","../../chunks/201.js","../../chunks/310.js","../../chunks/323.js","../../chunks/622.js","../../chunks/676.js","../../chunks/837.js","../../chunks/840.js","../../chunks/862.js","../../chunks/984.js","../../chunks/font-manifest.json","../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/wiston/page_client-reference-manifest.js b/.next/server/app/wiston/page_client-reference-manifest.js new file mode 100644 index 0000000..db0d848 --- /dev/null +++ b/.next/server/app/wiston/page_client-reference-manifest.js @@ -0,0 +1 @@ +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/wiston/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page":[]}} \ No newline at end of file diff --git a/.next/server/chunks/106.js b/.next/server/chunks/106.js new file mode 100644 index 0000000..1cd284b --- /dev/null +++ b/.next/server/chunks/106.js @@ -0,0 +1,113 @@ +"use strict";exports.id=106,exports.ids=[106],exports.modules={4106:(e,r,n)=>{n.r(r),n.d(r,{default:()=>BabylonScene});var t=n(784),i=n(9885),s=n(4494),a=n(7690);let BabylonScene=class BabylonScene extends i.PureComponent{componentDidMount(){console.clear(),this.setup(this.canvas)}render(){return t.jsx(t.Fragment,{children:t.jsx("canvas",{id:this.id,ref:this.onMount,style:o})})}constructor(...e){super(...e),this.setup=async e=>{s.vGS.ShadersStoreWGSL.starsPixelShader=` + uniform seed : f32; + uniform density : f32; + uniform brightness : f32; + + fn rand(seed : vec2) -> f32 { + return fract(sin(dot(seed, vec2(12.9898, 78.233))) * 43758.5453); + } + + @fragment + fn main(input : FragmentInputs) -> FragmentOutputs { + + let random = rand(input.vUV*uniforms.seed); + var brightness = 0.0; + if (random < uniforms.density){ + brightness = random/uniforms.density*uniforms.brightness; + } + //fragmentOutputs.color = vec4(1., 1., 1., brightness); + fragmentOutputs.color = vec4(brightness, brightness, brightness, 1.); + } + `,s.vGS.ShadersStoreWGSL.nebulasPixelShader=` + var textureSampler: texture_2d; + var textureSamplerSampler: sampler; + + uniform seed: f32; + uniform color: vec4; + uniform nebulascale: u32; + uniform depth: u32; + uniform intensity: f32; + uniform falloff: f32; + uniform persistence: f32; + + fn mod289(x: vec2) -> vec2 { + return x - floor(x * (1. / 289.)) * 289.; + } + + fn mod289_3(x: vec3) -> vec3 { + return x - floor(x * (1. / 289.)) * 289.; + } + + fn permute3(x: vec3) -> vec3 { + return mod289_3(((x * 34.) + 1.) * x); + } + + // MIT License. \xa9 Ian McEwan, Stefan Gustavson, Munrocket + fn simplexNoise2(v: vec2) -> f32 { + let C = vec4( + 0.211324865405187, // (3.0-sqrt(3.0))/6.0 + 0.366025403784439, // 0.5*(sqrt(3.0)-1.0) + -0.577350269189626, // -1.0 + 2.0 * C.x + 0.024390243902439 // 1.0 / 41.0 + ); + + // First corner + var i = floor(v + dot(v, C.yy)); + let x0 = v - i + dot(i, C.xx); + + // Other corners + var i1 = select(vec2(0., 1.), vec2(1., 0.), x0.x > x0.y); + + // x0 = x0 - 0.0 + 0.0 * C.xx ; + // x1 = x0 - i1 + 1.0 * C.xx ; + // x2 = x0 - 1.0 + 2.0 * C.xx ; + var x12 = x0.xyxy + C.xxzz; + x12.x = x12.x - i1.x; + x12.y = x12.y - i1.y; + + // Permutations + i = mod289(i); // Avoid truncation effects in permutation + + var p = permute3(permute3(i.y + vec3(0., i1.y, 1.)) + i.x + vec3(0., i1.x, 1.)); + var m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), vec3(0.)); + m *= m; + m *= m; + + // Gradients: 41 points uniformly over a line, mapped onto a diamond. + // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287) + let x = 2. * fract(p * C.www) - 1.; + let h = abs(x) - 0.5; + let ox = floor(x + 0.5); + let a0 = x - ox; + + // Normalize gradients implicitly by scaling m + // Approximation of: m *= inversesqrt( a0*a0 + h*h ); + m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h); + + // Compute final noise value at P + let g = vec3(a0.x * x0.x + h.x * x0.y, a0.yz * x12.xz + h.yz * x12.yw); + return 130. * dot(m, g); + } + + fn normalNoise(v: vec2) -> f32 { + return simplexNoise2(v)*0.5 + 0.5; + } + + @fragment + fn main(input : FragmentInputs) -> FragmentOutputs { + let sampleColor = textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV); + + var offset = 0.; + let scaledUV = (input.vUV+offset+uniforms.seed)*f32(uniforms.nebulascale)/uniforms.scale; + + var displace = 0.; + var i=u32(0); + for (i=0; i{let r;return await s.fWK.IsSupportedAsync?(r=new s.fWK(e),await r.initAsync()):(console.log("WebGPU is not supported (or turned on) for this browser!"),r=new s.fWK(e)),r},this.id="Babylon",this.onMount=e=>this.canvas=e}};let o={width:window.innerWidth,height:window.innerHeight,background:"transparent"}}}; \ No newline at end of file diff --git a/.next/server/chunks/2.js b/.next/server/chunks/2.js new file mode 100644 index 0000000..ec8dffc --- /dev/null +++ b/.next/server/chunks/2.js @@ -0,0 +1 @@ +"use strict";exports.id=2,exports.ids=[2],exports.modules={1323:(e,t)=>{function hoist(e,t){return t in e?e[t]:"then"in e&&"function"==typeof e.then?e.then(e=>hoist(e,t)):"function"==typeof e&&"default"===t?e:void 0}Object.defineProperty(t,"l",{enumerable:!0,get:function(){return hoist}})},2534:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return Error}});let r=n(167),o=r._(n(6689)),l=r._(n(6561)),a={400:"Bad Request",404:"This page could not be found",405:"Method Not Allowed",500:"Internal Server Error"};function _getInitialProps(e){let{res:t,err:n}=e,r=t&&t.statusCode?t.statusCode:n?n.statusCode:404;return{statusCode:r}}let i={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{lineHeight:"48px"},h1:{display:"inline-block",margin:"0 20px 0 0",paddingRight:23,fontSize:24,fontWeight:500,verticalAlign:"top"},h2:{fontSize:14,fontWeight:400,lineHeight:"28px"},wrap:{display:"inline-block"}};let Error=class Error extends o.default.Component{render(){let{statusCode:e,withDarkMode:t=!0}=this.props,n=this.props.title||a[e]||"An unexpected error has occurred";return o.default.createElement("div",{style:i.error},o.default.createElement(l.default,null,o.default.createElement("title",null,e?e+": "+n:"Application error: a client-side exception has occurred")),o.default.createElement("div",{style:i.desc},o.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}"+(t?"@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}":"")}}),e?o.default.createElement("h1",{className:"next-error-h1",style:i.h1},e):null,o.default.createElement("div",{style:i.wrap},o.default.createElement("h2",{style:i.h2},this.props.title||e?n:o.default.createElement(o.default.Fragment,null,"Application error: a client-side exception has occurred (see the browser console for more information)"),"."))))}};Error.displayName="ErrorPage",Error.getInitialProps=_getInitialProps,Error.origGetInitialProps=_getInitialProps,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8801:(e,t)=>{function isInAmpMode(e){let{ampFirst:t=!1,hybrid:n=!1,hasQuery:r=!1}=void 0===e?{}:e;return t||n&&r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return isInAmpMode}})},6561:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{defaultHead:function(){return defaultHead},default:function(){return c}});let r=n(167),o=n(8760),l=o._(n(6689)),a=r._(n(9737)),i=n(8039),d=n(1988),u=n(8801);function defaultHead(e){void 0===e&&(e=!1);let t=[l.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(l.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function onlyReactElement(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===l.default.Fragment?e.concat(l.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}n(8565);let f=["name","httpEquiv","charSet","itemProp"];function unique(){let e=new Set,t=new Set,n=new Set,r={};return o=>{let l=!0,a=!1;if(o.key&&"number"!=typeof o.key&&o.key.indexOf("$")>0){a=!0;let t=o.key.slice(o.key.indexOf("$")+1);e.has(t)?l=!1:e.add(t)}switch(o.type){case"title":case"base":t.has(o.type)?l=!1:t.add(o.type);break;case"meta":for(let e=0,t=f.length;e{let r=e.key||t;if(!n&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,l.default.cloneElement(e,t)}return l.default.cloneElement(e,{key:r})})}function Head(e){let{children:t}=e,n=(0,l.useContext)(i.AmpStateContext),r=(0,l.useContext)(d.HeadManagerContext);return l.default.createElement(a.default,{reduceComponentsToState:reduceComponents,headManager:r,inAmpMode:(0,u.isInAmpMode)(n)},t)}let c=Head;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9737:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return SideEffect}});let r=n(6689),useClientOnlyLayoutEffect=()=>{},useClientOnlyEffect=()=>{};function SideEffect(e){var t;let{headManager:n,reduceComponentsToState:o}=e;function emitChange(){if(n&&n.mountedInstances){let t=r.Children.toArray(Array.from(n.mountedInstances).filter(Boolean));n.updateHead(o(t,e))}}return null==n||null==(t=n.mountedInstances)||t.add(e.children),emitChange(),useClientOnlyLayoutEffect(()=>{var t;return null==n||null==(t=n.mountedInstances)||t.add(e.children),()=>{var t;null==n||null==(t=n.mountedInstances)||t.delete(e.children)}}),useClientOnlyLayoutEffect(()=>(n&&(n._pendingUpdate=emitChange),()=>{n&&(n._pendingUpdate=emitChange)})),useClientOnlyEffect(()=>(n&&n._pendingUpdate&&(n._pendingUpdate(),n._pendingUpdate=null),()=>{n&&n._pendingUpdate&&(n._pendingUpdate(),n._pendingUpdate=null)})),null}},8565:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return warnOnce}});let warnOnce=e=>{}},5244:(e,t)=>{var n;Object.defineProperty(t,"x",{enumerable:!0,get:function(){return n}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE"}(n||(n={}))},8039:(e,t,n)=>{e.exports=n(7093).vendored.contexts.AmpContext},1988:(e,t,n)=>{e.exports=n(7093).vendored.contexts.HeadManagerContext},8760:(e,t)=>{function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(_getRequireWildcardCache=function(e){return e?n:t})(e)}function _interop_require_wildcard(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=_getRequireWildcardCache(t);if(n&&n.has(e))return n.get(e);var r={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var l in e)if("default"!==l&&Object.prototype.hasOwnProperty.call(e,l)){var a=o?Object.getOwnPropertyDescriptor(e,l):null;a&&(a.get||a.set)?Object.defineProperty(r,l,a):r[l]=e[l]}return r.default=e,n&&n.set(e,r),r}t._=t._interop_require_wildcard=_interop_require_wildcard}}; \ No newline at end of file diff --git a/.next/server/chunks/201.js b/.next/server/chunks/201.js new file mode 100644 index 0000000..5764cae --- /dev/null +++ b/.next/server/chunks/201.js @@ -0,0 +1,12 @@ +"use strict";exports.id=201,exports.ids=[201],exports.modules={8450:e=>{var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,n={};function stringifyCookie(e){var t;let r=["path"in e&&e.path&&`Path=${e.path}`,"expires"in e&&(e.expires||0===e.expires)&&`Expires=${("number"==typeof e.expires?new Date(e.expires):e.expires).toUTCString()}`,"maxAge"in e&&"number"==typeof e.maxAge&&`Max-Age=${e.maxAge}`,"domain"in e&&e.domain&&`Domain=${e.domain}`,"secure"in e&&e.secure&&"Secure","httpOnly"in e&&e.httpOnly&&"HttpOnly","sameSite"in e&&e.sameSite&&`SameSite=${e.sameSite}`,"priority"in e&&e.priority&&`Priority=${e.priority}`].filter(Boolean);return`${e.name}=${encodeURIComponent(null!=(t=e.value)?t:"")}; ${r.join("; ")}`}function parseCookie(e){let t=new Map;for(let r of e.split(/; */)){if(!r)continue;let e=r.indexOf("=");if(-1===e){t.set(r,"true");continue}let[i,o]=[r.slice(0,e),r.slice(e+1)];try{t.set(i,decodeURIComponent(null!=o?o:"true"))}catch{}}return t}function parseSetCookie(e){if(!e)return;let[[t,r],...i]=parseCookie(e),{domain:o,expires:n,httponly:a,maxage:s,path:l,samesite:u,secure:d,priority:c}=Object.fromEntries(i.map(([e,t])=>[e.toLowerCase(),t])),h={name:t,value:decodeURIComponent(r),domain:o,...n&&{expires:new Date(n)},...a&&{httpOnly:!0},..."string"==typeof s&&{maxAge:Number(s)},path:l,...u&&{sameSite:parseSameSite(u)},...d&&{secure:!0},...c&&{priority:parsePriority(c)}};return compact(h)}function compact(e){let t={};for(let r in e)e[r]&&(t[r]=e[r]);return t}((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(n,{RequestCookies:()=>l,ResponseCookies:()=>u,parseCookie:()=>parseCookie,parseSetCookie:()=>parseSetCookie,stringifyCookie:()=>stringifyCookie}),e.exports=((e,n,a,s)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let a of i(n))o.call(e,a)||void 0===a||t(e,a,{get:()=>n[a],enumerable:!(s=r(n,a))||s.enumerable});return e})(t({},"__esModule",{value:!0}),n);var a=["strict","lax","none"];function parseSameSite(e){return e=e.toLowerCase(),a.includes(e)?e:void 0}var s=["low","medium","high"];function parsePriority(e){return e=e.toLowerCase(),s.includes(e)?e:void 0}function splitCookiesString(e){if(!e)return[];var t,r,i,o,n,a=[],s=0;function skipWhitespace(){for(;s=e.length)&&a.push(e.substring(t,e.length))}return a}var l=class{constructor(e){this._parsed=new Map,this._headers=e;let t=e.get("cookie");if(t){let e=parseCookie(t);for(let[t,r]of e)this._parsed.set(t,{name:t,value:r})}}[Symbol.iterator](){return this._parsed[Symbol.iterator]()}get size(){return this._parsed.size}get(...e){let t="string"==typeof e[0]?e[0]:e[0].name;return this._parsed.get(t)}getAll(...e){var t;let r=Array.from(this._parsed);if(!e.length)return r.map(([e,t])=>t);let i="string"==typeof e[0]?e[0]:null==(t=e[0])?void 0:t.name;return r.filter(([e])=>e===i).map(([e,t])=>t)}has(e){return this._parsed.has(e)}set(...e){let[t,r]=1===e.length?[e[0].name,e[0].value]:e,i=this._parsed;return i.set(t,{name:t,value:r}),this._headers.set("cookie",Array.from(i).map(([e,t])=>stringifyCookie(t)).join("; ")),this}delete(e){let t=this._parsed,r=Array.isArray(e)?e.map(e=>t.delete(e)):t.delete(e);return this._headers.set("cookie",Array.from(t).map(([e,t])=>stringifyCookie(t)).join("; ")),r}clear(){return this.delete(Array.from(this._parsed.keys())),this}[Symbol.for("edge-runtime.inspect.custom")](){return`RequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(e=>`${e.name}=${encodeURIComponent(e.value)}`).join("; ")}},u=class{constructor(e){var t,r,i;this._parsed=new Map,this._headers=e;let o=null!=(i=null!=(r=null==(t=e.getSetCookie)?void 0:t.call(e))?r:e.get("set-cookie"))?i:[],n=Array.isArray(o)?o:splitCookiesString(o);for(let e of n){let t=parseSetCookie(e);t&&this._parsed.set(t.name,t)}}get(...e){let t="string"==typeof e[0]?e[0]:e[0].name;return this._parsed.get(t)}getAll(...e){var t;let r=Array.from(this._parsed.values());if(!e.length)return r;let i="string"==typeof e[0]?e[0]:null==(t=e[0])?void 0:t.name;return r.filter(e=>e.name===i)}has(e){return this._parsed.has(e)}set(...e){let[t,r,i]=1===e.length?[e[0].name,e[0].value,e[0]]:e,o=this._parsed;return o.set(t,normalizeCookie({name:t,value:r,...i})),replace(o,this._headers),this}delete(...e){let[t,r,i]="string"==typeof e[0]?[e[0]]:[e[0].name,e[0].path,e[0].domain];return this.set({name:t,path:r,domain:i,value:"",expires:new Date(0)})}[Symbol.for("edge-runtime.inspect.custom")](){return`ResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(stringifyCookie).join("; ")}};function replace(e,t){for(let[,r]of(t.delete("set-cookie"),e)){let e=stringifyCookie(r);t.append("set-cookie",e)}}function normalizeCookie(e={name:"",value:""}){return"number"==typeof e.expires&&(e.expires=new Date(e.expires)),e.maxAge&&(e.expires=new Date(Date.now()+1e3*e.maxAge)),(null===e.path||void 0===e.path)&&(e.path="/"),e}},5842:(e,t,r)=>{var i;(()=>{var o={226:function(o,n){!function(a,s){var l="function",u="undefined",d="object",c="string",h="major",p="model",b="name",f="type",m="vendor",g="version",w="architecture",v="console",x="mobile",y="tablet",P="smarttv",k="wearable",_="embedded",S="Amazon",A="Apple",R="ASUS",O="BlackBerry",C="Browser",j="Chrome",L="Firefox",U="Google",N="Huawei",q="Microsoft",E="Motorola",M="Opera",z="Samsung",I="Sharp",T="Sony",H="Xiaomi",$="Zebra",D="Facebook",B="Chromium OS",W="Mac OS",extend=function(e,t){var r={};for(var i in e)t[i]&&t[i].length%2==0?r[i]=t[i].concat(e[i]):r[i]=e[i];return r},enumerize=function(e){for(var t={},r=0;r0?2===n.length?typeof n[1]==l?this[n[0]]=n[1].call(this,u):this[n[0]]=n[1]:3===n.length?typeof n[1]!==l||n[1].exec&&n[1].test?this[n[0]]=u?u.replace(n[1],n[2]):s:this[n[0]]=u?n[1].call(this,u,n[2]):s:4===n.length&&(this[n[0]]=u?n[3].call(this,u.replace(n[1],n[2])):s):this[n]=u||s;c+=2}},strMapper=function(e,t){for(var r in t)if(typeof t[r]===d&&t[r].length>0){for(var i=0;i2&&(e[p]="iPad",e[f]=y),e},this.getEngine=function(){var e={};return e[b]=s,e[g]=s,rgxMapper.call(e,i,n.engine),e},this.getOS=function(){var e={};return e[b]=s,e[g]=s,rgxMapper.call(e,i,n.os),v&&!e[b]&&o&&"Unknown"!=o.platform&&(e[b]=o.platform.replace(/chrome os/i,B).replace(/macos/i,W)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return i},this.setUA=function(e){return i=typeof e===c&&e.length>350?trim(e,350):e,this},this.setUA(i),this};UAParser.VERSION="1.0.35",UAParser.BROWSER=enumerize([b,g,h]),UAParser.CPU=enumerize([w]),UAParser.DEVICE=enumerize([p,m,f,v,x,P,y,k,_]),UAParser.ENGINE=UAParser.OS=enumerize([b,g]),typeof n!==u?(o.exports&&(n=o.exports=UAParser),n.UAParser=UAParser):r.amdO?void 0!==(i=(function(){return UAParser}).call(t,r,t,e))&&(e.exports=i):typeof a!==u&&(a.UAParser=UAParser);var V=typeof a!==u&&(a.jQuery||a.Zepto);if(V&&!V.ua){var Z=new UAParser;V.ua=Z.getResult(),V.ua.get=function(){return Z.getUA()},V.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var r in t)V.ua[r]=t[r]}}}(this)}},n={};function __nccwpck_require__(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}},i=!0;try{o[e].call(r.exports,r,r.exports,__nccwpck_require__),i=!1}finally{i&&delete n[e]}return r.exports}__nccwpck_require__.ab=__dirname+"/";var a=__nccwpck_require__(226);e.exports=a})()},6132:(e,t)=>{var r;Object.defineProperty(t,"x",{enumerable:!0,get:function(){return r}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE"}(r||(r={}))},884:(e,t,r)=>{e.exports=r(517)},8726:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PageSignatureError:function(){return PageSignatureError},RemovedPageError:function(){return RemovedPageError},RemovedUAError:function(){return RemovedUAError}});let PageSignatureError=class PageSignatureError extends Error{constructor({page:e}){super(`The middleware "${e}" accepts an async API directly with the form: + + export function middleware(request, event) { + return NextResponse.redirect('/new-location') + } + + Read more: https://nextjs.org/docs/messages/middleware-new-signature + `)}};let RemovedPageError=class RemovedPageError extends Error{constructor(){super(`The request.page has been deprecated in favour of \`URLPattern\`. + Read more: https://nextjs.org/docs/messages/middleware-request-page + `)}};let RemovedUAError=class RemovedUAError extends Error{constructor(){super(`The request.ua has been removed in favour of \`userAgent\` function. + Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent + `)}}},8098:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NextURL",{enumerable:!0,get:function(){return NextURL}});let i=r(4582),o=r(3987),n=r(5913),a=r(2020),s=/(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)/;function parseURL(e,t){return new URL(String(e).replace(s,"localhost"),t&&String(t).replace(s,"localhost"))}let l=Symbol("NextURLInternal");let NextURL=class NextURL{constructor(e,t,r){let i,o;"object"==typeof t&&"pathname"in t||"string"==typeof t?(i=t,o=r||{}):o=r||t||{},this[l]={url:parseURL(e,i??o.base),options:o,basePath:""},this.analyze()}analyze(){var e,t,r,o,s;let u=(0,a.getNextPathnameInfo)(this[l].url.pathname,{nextConfig:this[l].options.nextConfig,parseData:!0,i18nProvider:this[l].options.i18nProvider}),d=(0,n.getHostname)(this[l].url,this[l].options.headers);this[l].domainLocale=this[l].options.i18nProvider?this[l].options.i18nProvider.detectDomainLocale(d):(0,i.detectDomainLocale)(null==(t=this[l].options.nextConfig)?void 0:null==(e=t.i18n)?void 0:e.domains,d);let c=(null==(r=this[l].domainLocale)?void 0:r.defaultLocale)||(null==(s=this[l].options.nextConfig)?void 0:null==(o=s.i18n)?void 0:o.defaultLocale);this[l].url.pathname=u.pathname,this[l].defaultLocale=c,this[l].basePath=u.basePath??"",this[l].buildId=u.buildId,this[l].locale=u.locale??c,this[l].trailingSlash=u.trailingSlash}formatPathname(){return(0,o.formatNextPathnameInfo)({basePath:this[l].basePath,buildId:this[l].buildId,defaultLocale:this[l].options.forceLocale?void 0:this[l].defaultLocale,locale:this[l].locale,pathname:this[l].url.pathname,trailingSlash:this[l].trailingSlash})}formatSearch(){return this[l].url.search}get buildId(){return this[l].buildId}set buildId(e){this[l].buildId=e}get locale(){return this[l].locale??""}set locale(e){var t,r;if(!this[l].locale||!(null==(r=this[l].options.nextConfig)?void 0:null==(t=r.i18n)?void 0:t.locales.includes(e)))throw TypeError(`The NextURL configuration includes no locale "${e}"`);this[l].locale=e}get defaultLocale(){return this[l].defaultLocale}get domainLocale(){return this[l].domainLocale}get searchParams(){return this[l].url.searchParams}get host(){return this[l].url.host}set host(e){this[l].url.host=e}get hostname(){return this[l].url.hostname}set hostname(e){this[l].url.hostname=e}get port(){return this[l].url.port}set port(e){this[l].url.port=e}get protocol(){return this[l].url.protocol}set protocol(e){this[l].url.protocol=e}get href(){let e=this.formatPathname(),t=this.formatSearch();return`${this.protocol}//${this.host}${e}${t}${this.hash}`}set href(e){this[l].url=parseURL(e),this.analyze()}get origin(){return this[l].url.origin}get pathname(){return this[l].url.pathname}set pathname(e){this[l].url.pathname=e}get hash(){return this[l].url.hash}set hash(e){this[l].url.hash=e}get search(){return this[l].url.search}set search(e){this[l].url.search=e}get password(){return this[l].url.password}set password(e){this[l].url.password=e}get username(){return this[l].url.username}set username(e){this[l].url.username=e}get basePath(){return this[l].basePath}set basePath(e){this[l].basePath=e.startsWith("/")?e:`/${e}`}toString(){return this.href}toJSON(){return this.href}[Symbol.for("edge-runtime.inspect.custom")](){return{href:this.href,origin:this.origin,protocol:this.protocol,username:this.username,password:this.password,host:this.host,hostname:this.hostname,port:this.port,pathname:this.pathname,search:this.search,searchParams:this.searchParams,hash:this.hash}}clone(){return new NextURL(String(this),this[l].options)}}},1109:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RequestCookies:function(){return i.RequestCookies},ResponseCookies:function(){return i.ResponseCookies}});let i=r(8450)},8052:(e,t)=>{function ImageResponse(){throw Error('ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead')}Object.defineProperty(t,"E",{enumerable:!0,get:function(){return ImageResponse}})},3169:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERNALS:function(){return s},NextRequest:function(){return NextRequest}});let i=r(8098),o=r(1542),n=r(8726),a=r(1109),s=Symbol("internal request");let NextRequest=class NextRequest extends Request{constructor(e,t={}){let r="string"!=typeof e&&"url"in e?e.url:String(e);(0,o.validateURL)(r),e instanceof Request?super(e,t):super(r,t);let n=new i.NextURL(r,{headers:(0,o.toNodeOutgoingHttpHeaders)(this.headers),nextConfig:t.nextConfig});this[s]={cookies:new a.RequestCookies(this.headers),geo:t.geo||{},ip:t.ip,nextUrl:n,url:n.toString()}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,geo:this.geo,ip:this.ip,nextUrl:this.nextUrl,url:this.url,bodyUsed:this.bodyUsed,cache:this.cache,credentials:this.credentials,destination:this.destination,headers:Object.fromEntries(this.headers),integrity:this.integrity,keepalive:this.keepalive,method:this.method,mode:this.mode,redirect:this.redirect,referrer:this.referrer,referrerPolicy:this.referrerPolicy,signal:this.signal}}get cookies(){return this[s].cookies}get geo(){return this[s].geo}get ip(){return this[s].ip}get nextUrl(){return this[s].nextUrl}get page(){throw new n.RemovedPageError}get ua(){throw new n.RemovedUAError}get url(){return this[s].url}}},7715:(e,t,r)=>{Object.defineProperty(t,"x",{enumerable:!0,get:function(){return NextResponse}});let i=r(8098),o=r(1542),n=r(1109),a=Symbol("internal response"),s=new Set([301,302,303,307,308]);function handleMiddlewareField(e,t){var r;if(null==e?void 0:null==(r=e.request)?void 0:r.headers){if(!(e.request.headers instanceof Headers))throw Error("request.headers must be an instance of Headers");let r=[];for(let[i,o]of e.request.headers)t.set("x-middleware-request-"+i,o),r.push(i);t.set("x-middleware-override-headers",r.join(","))}}let NextResponse=class NextResponse extends Response{constructor(e,t={}){super(e,t),this[a]={cookies:new n.ResponseCookies(this.headers),url:t.url?new i.NextURL(t.url,{headers:(0,o.toNodeOutgoingHttpHeaders)(this.headers),nextConfig:t.nextConfig}):void 0}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,url:this.url,body:this.body,bodyUsed:this.bodyUsed,headers:Object.fromEntries(this.headers),ok:this.ok,redirected:this.redirected,status:this.status,statusText:this.statusText,type:this.type}}get cookies(){return this[a].cookies}static json(e,t){let r=Response.json(e,t);return new NextResponse(r.body,r)}static redirect(e,t){let r="number"==typeof t?t:(null==t?void 0:t.status)??307;if(!s.has(r))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');let i="object"==typeof t?t:{},n=new Headers(null==i?void 0:i.headers);return n.set("Location",(0,o.validateURL)(e)),new NextResponse(null,{...i,headers:n,status:r})}static rewrite(e,t){let r=new Headers(null==t?void 0:t.headers);return r.set("x-middleware-rewrite",(0,o.validateURL)(e)),handleMiddlewareField(t,r),new NextResponse(null,{...t,headers:r})}static next(e){let t=new Headers(null==e?void 0:e.headers);return t.set("x-middleware-next","1"),handleMiddlewareField(e,t),new NextResponse(null,{...e,headers:t})}}},1654:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{isBot:function(){return isBot},userAgentFromString:function(){return userAgentFromString},userAgent:function(){return userAgent}});let i=_interop_require_default(r(5842));function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}function isBot(e){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Google-InspectionTool|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(e)}function userAgentFromString(e){return{...(0,i.default)(e),isBot:void 0!==e&&isBot(e)}}function userAgent({headers:e}){return userAgentFromString(e.get("user-agent")||void 0)}},1542:(e,t)=>{function fromNodeOutgoingHttpHeaders(e){let t=new Headers;for(let[r,i]of Object.entries(e)){let e=Array.isArray(i)?i:[i];for(let i of e)void 0!==i&&("number"==typeof i&&(i=i.toString()),t.append(r,i))}return t}function splitCookiesString(e){var t,r,i,o,n,a=[],s=0;function skipWhitespace(){for(;s=e.length)&&a.push(e.substring(t,e.length))}return a}function toNodeOutgoingHttpHeaders(e){let t={},r=[];if(e)for(let[i,o]of e.entries())"set-cookie"===i.toLowerCase()?(r.push(...splitCookiesString(o)),t[i]=1===r.length?r[0]:r):t[i]=o;return t}function validateURL(e){try{return String(new URL(String(e)))}catch(t){throw Error(`URL is malformed "${String(e)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,{cause:t})}}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{fromNodeOutgoingHttpHeaders:function(){return fromNodeOutgoingHttpHeaders},splitCookiesString:function(){return splitCookiesString},toNodeOutgoingHttpHeaders:function(){return toNodeOutgoingHttpHeaders},validateURL:function(){return validateURL}})},5913:(e,t)=>{function getHostname(e,t){let r;if((null==t?void 0:t.host)&&!Array.isArray(t.host))r=t.host.toString().split(":",1)[0];else{if(!e.hostname)return;r=e.hostname}return r.toLowerCase()}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getHostname",{enumerable:!0,get:function(){return getHostname}})},4582:(e,t)=>{function detectDomainLocale(e,t,r){if(e)for(let n of(r&&(r=r.toLowerCase()),e)){var i,o;let e=null==(i=n.domain)?void 0:i.split(":",1)[0].toLowerCase();if(t===e||r===n.defaultLocale.toLowerCase()||(null==(o=n.locales)?void 0:o.some(e=>e.toLowerCase()===r)))return n}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"detectDomainLocale",{enumerable:!0,get:function(){return detectDomainLocale}})},4340:(e,t)=>{function normalizeLocalePath(e,t){let r;let i=e.split("/");return(t||[]).some(t=>!!i[1]&&i[1].toLowerCase()===t.toLowerCase()&&(r=t,i.splice(1,1),e=i.join("/")||"/",!0)),{pathname:e,detectedLocale:r}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizeLocalePath",{enumerable:!0,get:function(){return normalizeLocalePath}})},446:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addLocale",{enumerable:!0,get:function(){return addLocale}});let i=r(8888),o=r(5794);function addLocale(e,t,r,n){if(!t||t===r)return e;let a=e.toLowerCase();return!n&&((0,o.pathHasPrefix)(a,"/api")||(0,o.pathHasPrefix)(a,"/"+t.toLowerCase()))?e:(0,i.addPathPrefix)(e,"/"+t)}},8888:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return addPathPrefix}});let i=r(3974);function addPathPrefix(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:o,hash:n}=(0,i.parsePath)(e);return""+t+r+o+n}},8277:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathSuffix",{enumerable:!0,get:function(){return addPathSuffix}});let i=r(3974);function addPathSuffix(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:o,hash:n}=(0,i.parsePath)(e);return""+r+t+o+n}},3987:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"formatNextPathnameInfo",{enumerable:!0,get:function(){return formatNextPathnameInfo}});let i=r(6976),o=r(8888),n=r(8277),a=r(446);function formatNextPathnameInfo(e){let t=(0,a.addLocale)(e.pathname,e.locale,e.buildId?void 0:e.defaultLocale,e.ignorePrefix);return(e.buildId||!e.trailingSlash)&&(t=(0,i.removeTrailingSlash)(t)),e.buildId&&(t=(0,n.addPathSuffix)((0,o.addPathPrefix)(t,"/_next/data/"+e.buildId),"/"===e.pathname?"index.json":".json")),t=(0,o.addPathPrefix)(t,e.basePath),!e.buildId&&e.trailingSlash?t.endsWith("/")?t:(0,n.addPathSuffix)(t,"/"):(0,i.removeTrailingSlash)(t)}},2020:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getNextPathnameInfo",{enumerable:!0,get:function(){return getNextPathnameInfo}});let i=r(4340),o=r(3863),n=r(5794);function getNextPathnameInfo(e,t){var r,a;let{basePath:s,i18n:l,trailingSlash:u}=null!=(r=t.nextConfig)?r:{},d={pathname:e,trailingSlash:"/"!==e?e.endsWith("/"):u};s&&(0,n.pathHasPrefix)(d.pathname,s)&&(d.pathname=(0,o.removePathPrefix)(d.pathname,s),d.basePath=s);let c=d.pathname;if(d.pathname.startsWith("/_next/data/")&&d.pathname.endsWith(".json")){let e=d.pathname.replace(/^\/_next\/data\//,"").replace(/\.json$/,"").split("/"),r=e[0];d.buildId=r,c="index"!==e[1]?"/"+e.slice(1).join("/"):"/",!0===t.parseData&&(d.pathname=c)}if(l){let e=t.i18nProvider?t.i18nProvider.analyze(d.pathname):(0,i.normalizeLocalePath)(d.pathname,l.locales);d.locale=e.detectedLocale,d.pathname=null!=(a=e.pathname)?a:d.pathname,!e.detectedLocale&&d.buildId&&(e=t.i18nProvider?t.i18nProvider.analyze(c):(0,i.normalizeLocalePath)(c,l.locales)).detectedLocale&&(d.locale=e.detectedLocale)}return d}},3974:(e,t)=>{function parsePath(e){let t=e.indexOf("#"),r=e.indexOf("?"),i=r>-1&&(t<0||r-1?{pathname:e.substring(0,i?r:t),query:i?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return parsePath}})},5794:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return pathHasPrefix}});let i=r(3974);function pathHasPrefix(e,t){if("string"!=typeof e)return!1;let{pathname:r}=(0,i.parsePath)(e);return r===t||r.startsWith(t+"/")}},3863:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removePathPrefix",{enumerable:!0,get:function(){return removePathPrefix}});let i=r(5794);function removePathPrefix(e,t){if(!(0,i.pathHasPrefix)(e,t))return e;let r=e.slice(t.length);return r.startsWith("/")?r:"/"+r}},6976:(e,t)=>{function removeTrailingSlash(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return removeTrailingSlash}})},1057:(e,t,r)=>{let i={NextRequest:r(3169).NextRequest,NextResponse:r(7715).x,ImageResponse:r(8052).E,userAgentFromString:r(1654).userAgentFromString,userAgent:r(1654).userAgent};"undefined"!=typeof URLPattern&&(i.URLPattern=URLPattern),e.exports=i,t.NextRequest=i.NextRequest,t.NextResponse=i.NextResponse,t.ImageResponse=i.ImageResponse,t.userAgentFromString=i.userAgentFromString,t.userAgent=i.userAgent,t.URLPattern=i.URLPattern}}; \ No newline at end of file diff --git a/.next/server/chunks/310.js b/.next/server/chunks/310.js new file mode 100644 index 0000000..e453be6 --- /dev/null +++ b/.next/server/chunks/310.js @@ -0,0 +1 @@ +"use strict";exports.id=310,exports.ids=[310],exports.modules={7921:(e,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),function(e,r){for(var t in r)Object.defineProperty(e,t,{enumerable:!0,get:r[t]})}(r,{WEB_VITALS:function(){return t},execOnce:function(){return execOnce},isAbsoluteUrl:function(){return isAbsoluteUrl},getLocationOrigin:function(){return getLocationOrigin},getURL:function(){return getURL},getDisplayName:function(){return getDisplayName},isResSent:function(){return isResSent},normalizeRepeatedSlashes:function(){return normalizeRepeatedSlashes},loadGetInitialProps:function(){return loadGetInitialProps},SP:function(){return o},ST:function(){return i},DecodeError:function(){return DecodeError},NormalizeError:function(){return NormalizeError},PageNotFoundError:function(){return PageNotFoundError},MissingStaticPage:function(){return MissingStaticPage},MiddlewareNotFoundError:function(){return MiddlewareNotFoundError},stringifyError:function(){return stringifyError}});let t=["CLS","FCP","FID","INP","LCP","TTFB"];function execOnce(e){let r,t=!1;return function(){for(var n=arguments.length,o=Array(n),i=0;in.test(e);function getLocationOrigin(){let{protocol:e,hostname:r,port:t}=window.location;return e+"//"+r+(t?":"+t:"")}function getURL(){let{href:e}=window.location,r=getLocationOrigin();return e.substring(r.length)}function getDisplayName(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function isResSent(e){return e.finished||e.headersSent}function normalizeRepeatedSlashes(e){let r=e.split("?"),t=r[0];return t.replace(/\\/g,"/").replace(/\/\/+/g,"/")+(r[1]?"?"+r.slice(1).join("?"):"")}async function loadGetInitialProps(e,r){let t=r.res||r.ctx&&r.ctx.res;if(!e.getInitialProps)return r.ctx&&r.Component?{pageProps:await loadGetInitialProps(r.Component,r.ctx)}:{};let n=await e.getInitialProps(r);if(t&&isResSent(t))return n;if(!n){let r='"'+getDisplayName(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.';throw Error(r)}return n}let o="undefined"!=typeof performance,i=o&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);let DecodeError=class DecodeError extends Error{};let NormalizeError=class NormalizeError extends Error{};let PageNotFoundError=class PageNotFoundError extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}};let MissingStaticPage=class MissingStaticPage extends Error{constructor(e,r){super(),this.message="Failed to load static file for page: "+e+" "+r}};let MiddlewareNotFoundError=class MiddlewareNotFoundError extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}};function stringifyError(e){return JSON.stringify({message:e.message,stack:e.stack})}},167:(e,r)=>{r._=r._interop_require_default=_interop_require_default;function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}}}; \ No newline at end of file diff --git a/.next/server/chunks/323.js b/.next/server/chunks/323.js new file mode 100644 index 0000000..7aae388 --- /dev/null +++ b/.next/server/chunks/323.js @@ -0,0 +1,6 @@ +"use strict";exports.id=323,exports.ids=[323],exports.modules={9001:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RSC:function(){return r},ACTION:function(){return n},NEXT_ROUTER_STATE_TREE:function(){return a},NEXT_ROUTER_PREFETCH:function(){return o},NEXT_URL:function(){return i},RSC_CONTENT_TYPE_HEADER:function(){return u},RSC_VARY_HEADER:function(){return s},FLIGHT_PARAMETERS:function(){return c},NEXT_RSC_UNION_QUERY:function(){return l}});let r="RSC",n="Next-Action",a="Next-Router-State-Tree",o="Next-Router-Prefetch",i="Next-Url",u="text/x-component",s=r+", "+a+", "+o+", "+i,c=[[r],[a],[o]],l="_rsc";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8712:e=>{(()=>{"undefined"!=typeof __nccwpck_require__&&(__nccwpck_require__.ab=__dirname+"/");var t={};(()=>{/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */t.parse=parse,t.serialize=serialize;var e=decodeURIComponent,r=encodeURIComponent,n=/; */,a=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function parse(t,r){if("string"!=typeof t)throw TypeError("argument str must be a string");for(var a={},o=t.split(n),i=(r||{}).decode||e,u=0;u{function lexer(e){for(var t=[],r=0;r=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||95===i){a+=e[o++];continue}break}if(!a)throw TypeError("Missing parameter name at "+r);t.push({type:"NAME",index:r,value:a}),r=o;continue}if("("===n){var u=1,s="",o=r+1;if("?"===e[o])throw TypeError('Pattern cannot start with "?" at '+o);for(;o-1:void 0===h;a||(p+="(?:"+l+"(?="+c+"))?"),E||(p+="(?="+l+"|"+c+")")}return new RegExp(p,flags(r))}function pathToRegexp(e,t,r){return e instanceof RegExp?regexpToRegexp(e,t):Array.isArray(e)?arrayToRegexp(e,t,r):stringToRegexp(e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t.parse=parse,t.compile=compile,t.tokensToFunction=tokensToFunction,t.match=match,t.regexpToFunction=regexpToFunction,t.tokensToRegexp=tokensToRegexp,t.pathToRegexp=pathToRegexp},9368:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXT_QUERY_PARAM_PREFIX:function(){return r},PRERENDER_REVALIDATE_HEADER:function(){return n},PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER:function(){return a},NEXT_DID_POSTPONE_HEADER:function(){return o},NEXT_CACHE_TAGS_HEADER:function(){return i},NEXT_CACHE_SOFT_TAGS_HEADER:function(){return u},NEXT_CACHE_REVALIDATED_TAGS_HEADER:function(){return s},NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER:function(){return c},NEXT_CACHE_TAG_MAX_LENGTH:function(){return l},NEXT_CACHE_SOFT_TAG_MAX_LENGTH:function(){return p},NEXT_CACHE_IMPLICIT_TAG_ID:function(){return f},CACHE_ONE_YEAR:function(){return d},MIDDLEWARE_FILENAME:function(){return g},MIDDLEWARE_LOCATION_REGEXP:function(){return m},INSTRUMENTATION_HOOK_FILENAME:function(){return R},PAGES_DIR_ALIAS:function(){return h},DOT_NEXT_ALIAS:function(){return E},ROOT_DIR_ALIAS:function(){return _},APP_DIR_ALIAS:function(){return y},RSC_MOD_REF_PROXY_ALIAS:function(){return x},RSC_ACTION_VALIDATE_ALIAS:function(){return P},RSC_ACTION_PROXY_ALIAS:function(){return S},RSC_ACTION_ENCRYPTION_ALIAS:function(){return v},RSC_ACTION_CLIENT_WRAPPER_ALIAS:function(){return A},PUBLIC_DIR_MIDDLEWARE_CONFLICT:function(){return T},SSG_GET_INITIAL_PROPS_CONFLICT:function(){return b},SERVER_PROPS_GET_INIT_PROPS_CONFLICT:function(){return O},SERVER_PROPS_SSG_CONFLICT:function(){return N},STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR:function(){return C},SERVER_PROPS_EXPORT_ERROR:function(){return I},GSP_NO_RETURNED_VALUE:function(){return M},GSSP_NO_RETURNED_VALUE:function(){return j},UNSTABLE_REVALIDATE_RENAME_ERROR:function(){return L},GSSP_COMPONENT_MEMBER_ERROR:function(){return w},NON_STANDARD_NODE_ENV:function(){return U},SSG_FALLBACK_EXPORT_ERROR:function(){return D},ESLINT_DEFAULT_DIRS:function(){return k},ESLINT_PROMPT_VALUES:function(){return $},SERVER_RUNTIME:function(){return F},WEBPACK_LAYERS:function(){return H},WEBPACK_RESOURCE_QUERIES:function(){return G}});let r="nxtP",n="x-prerender-revalidate",a="x-prerender-revalidate-if-generated",o="x-nextjs-postponed",i="x-next-cache-tags",u="x-next-cache-soft-tags",s="x-next-revalidated-tags",c="x-next-revalidate-tag-token",l=256,p=1024,f="_N_T_",d=31536e3,g="middleware",m=`(?:src/)?${g}`,R="instrumentation",h="private-next-pages",E="private-dot-next",_="private-next-root-dir",y="private-next-app-dir",x="next/dist/build/webpack/loaders/next-flight-loader/module-proxy",P="private-next-rsc-action-validate",S="private-next-rsc-action-proxy",v="private-next-rsc-action-encryption",A="private-next-rsc-action-client-wrapper",T="You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict",b="You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps",O="You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.",N="You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps",C="can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props",I="pages with `getServerSideProps` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export",M="Your `getStaticProps` function did not return an object. Did you forget to add a `return`?",j="Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?",L="The `unstable_revalidate` property is available for general use.\nPlease use `revalidate` instead.",w="can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member",U='You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env',D="Pages with `fallback` enabled in `getStaticPaths` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export",k=["app","pages","components","lib","src"],$=[{title:"Strict",recommended:!0,config:{extends:"next/core-web-vitals"}},{title:"Base",config:{extends:"next"}},{title:"Cancel",config:null}],F={edge:"edge",experimentalEdge:"experimental-edge",nodejs:"nodejs"},z={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",api:"api",middleware:"middleware",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",appMetadataRoute:"app-metadata-route",appRouteHandler:"app-route-handler"},H={...z,GROUP:{server:[z.reactServerComponents,z.actionBrowser,z.appMetadataRoute,z.appRouteHandler],nonClientServerTarget:[z.middleware,z.api],app:[z.reactServerComponents,z.actionBrowser,z.appMetadataRoute,z.appRouteHandler,z.serverSideRendering,z.appPagesBrowser]}},G={edgeSSREntry:"__next_edge_ssr_entry__",metadata:"__next_metadata__",metadataRoute:"__next_metadata_route__",metadataImageMeta:"__next_metadata_image_meta__"}},8531:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{fillMetadataSegment:function(){return fillMetadataSegment},normalizeMetadataRoute:function(){return normalizeMetadataRoute}});let n=r(2038),a=_interop_require_default(r(5585)),o=r(1239),i=r(4018),u=r(8043),s=r(1478),c=r(7819);function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}function getMetadataRouteSuffix(e){let t="";return(e.includes("(")&&e.includes(")")||e.includes("@"))&&(t=(0,u.djb2Hash)(e).toString(36).slice(0,6)),t}function fillMetadataSegment(e,t,r){let n=(0,s.normalizeAppPath)(e),u=(0,i.getNamedRouteRegex)(n,!1),l=(0,o.interpolateDynamicPath)(n,t,u),p=getMetadataRouteSuffix(e),f=p?`-${p}`:"",{name:d,ext:g}=a.default.parse(r);return(0,c.normalizePathSep)(a.default.join(l,`${d}${f}${g}`))}function normalizeMetadataRoute(e){if(!(0,n.isMetadataRoute)(e))return e;let t=e,r="";if("/robots"===e)t+=".txt";else if("/manifest"===e)t+=".webmanifest";else if(e.endsWith("/sitemap"))t+=".xml";else{let t=e.slice(0,-(a.default.basename(e).length+1));r=getMetadataRouteSuffix(t)}if(!t.endsWith("/route")){let{dir:o,name:i,ext:u}=a.default.parse(t),s=(0,n.isStaticMetadataRoute)(e);t=a.default.posix.join(o,`${i}${r?`-${r}`:""}${u}`,s?"":"[[...__metadata_id__]]","route")}return t}},2038:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{STATIC_METADATA_IMAGES:function(){return a},isMetadataRouteFile:function(){return isMetadataRouteFile},isStaticMetadataRouteFile:function(){return isStaticMetadataRouteFile},isStaticMetadataRoute:function(){return isStaticMetadataRoute},isMetadataRoute:function(){return isMetadataRoute}});let n=r(7819),a={icon:{filename:"icon",extensions:["ico","jpg","jpeg","png","svg"]},apple:{filename:"apple-icon",extensions:["jpg","jpeg","png"]},favicon:{filename:"favicon",extensions:["ico"]},openGraph:{filename:"opengraph-image",extensions:["jpg","jpeg","png","gif"]},twitter:{filename:"twitter-image",extensions:["jpg","jpeg","png","gif"]}},o=["js","jsx","ts","tsx"],getExtensionRegexString=e=>`(?:${e.join("|")})`;function isMetadataRouteFile(e,t,r){let o=[RegExp(`^[\\\\/]robots${r?`\\.${getExtensionRegexString(t.concat("txt"))}$`:""}`),RegExp(`^[\\\\/]manifest${r?`\\.${getExtensionRegexString(t.concat("webmanifest","json"))}$`:""}`),RegExp("^[\\\\/]favicon\\.ico$"),RegExp(`[\\\\/]sitemap${r?`\\.${getExtensionRegexString(t.concat("xml"))}$`:""}`),RegExp(`[\\\\/]${a.icon.filename}\\d?${r?`\\.${getExtensionRegexString(t.concat(a.icon.extensions))}$`:""}`),RegExp(`[\\\\/]${a.apple.filename}\\d?${r?`\\.${getExtensionRegexString(t.concat(a.apple.extensions))}$`:""}`),RegExp(`[\\\\/]${a.openGraph.filename}\\d?${r?`\\.${getExtensionRegexString(t.concat(a.openGraph.extensions))}$`:""}`),RegExp(`[\\\\/]${a.twitter.filename}\\d?${r?`\\.${getExtensionRegexString(t.concat(a.twitter.extensions))}$`:""}`)],i=(0,n.normalizePathSep)(e);return o.some(e=>e.test(i))}function isStaticMetadataRouteFile(e){return isMetadataRouteFile(e,[],!0)}function isStaticMetadataRoute(e){return"/robots"===e||"/manifest"===e||isStaticMetadataRouteFile(e)}function isMetadataRoute(e){let t=e.replace(/^\/?app\//,"").replace(/\/route$/,"");return"/"!==t[0]&&(t="/"+t),!t.endsWith("/page")&&isMetadataRouteFile(t,o,!1)}},4427:(e,t,r)=>{function getCookieParser(e){return function(){let{cookie:t}=e;if(!t)return{};let{parse:n}=r(8712);return n(Array.isArray(t)?t.join("; "):t)}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getCookieParser",{enumerable:!0,get:function(){return getCookieParser}})},7302:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return a},isInterceptionRouteAppPath:function(){return isInterceptionRouteAppPath},extractInterceptionRouteInformation:function(){return extractInterceptionRouteInformation}});let n=r(1478),a=["(..)(..)","(.)","(..)","(...)"];function isInterceptionRouteAppPath(e){return void 0!==e.split("/").find(e=>a.find(t=>e.startsWith(t)))}function extractInterceptionRouteInformation(e){let t,r,o;for(let n of e.split("/"))if(r=a.find(e=>n.startsWith(e))){[t,o]=e.split(r,2);break}if(!t||!r||!o)throw Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`);switch(t=(0,n.normalizeAppPath)(t),r){case"(.)":o="/"===t?`/${o}`:t+"/"+o;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);o=t.split("/").slice(0,-1).concat(o).join("/");break;case"(...)":o="/"+o;break;case"(..)(..)":let i=t.split("/");if(i.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);o=i.slice(0,-2).concat(o).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:o}}},1239:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeVercelUrl:function(){return normalizeVercelUrl},interpolateDynamicPath:function(){return interpolateDynamicPath},getUtils:function(){return getUtils}});let n=r(7310),a=r(5259),o=r(9302),i=r(4018),u=r(4893),s=r(1731),c=r(4419),l=r(1478),p=r(9368);function normalizeVercelUrl(e,t,r,a,o){if(a&&t&&o){let t=(0,n.parse)(e.url,!0);for(let e of(delete t.search,Object.keys(t.query)))(e!==p.NEXT_QUERY_PARAM_PREFIX&&e.startsWith(p.NEXT_QUERY_PARAM_PREFIX)||(r||Object.keys(o.groups)).includes(e))&&delete t.query[e];e.url=(0,n.format)(t)}}function interpolateDynamicPath(e,t,r){if(!r)return e;for(let n of Object.keys(r.groups)){let{optional:a,repeat:o}=r.groups[n],i=`[${o?"...":""}${n}]`;a&&(i=`[${i}]`);let u=e.indexOf(i);if(u>-1){let r;let a=t[n];r=Array.isArray(a)?a.map(e=>e&&encodeURIComponent(e)).join("/"):a?encodeURIComponent(a):"",e=e.slice(0,u)+r+e.slice(u+i.length)}}return e}function getUtils({page:e,i18n:t,basePath:r,rewrites:n,pageIsDynamic:f,trailingSlash:d,caseSensitive:g}){let m,R,h;function getParamsFromRouteMatches(e,r,n){return(0,u.getRouteMatcher)(function(){let{groups:e,routeKeys:a}=m;return{re:{exec:o=>{let i=Object.fromEntries(new URLSearchParams(o)),u=t&&n&&i["1"]===n;for(let e of Object.keys(i)){let t=i[e];if(e!==p.NEXT_QUERY_PARAM_PREFIX&&e.startsWith(p.NEXT_QUERY_PARAM_PREFIX)){let r=e.substring(p.NEXT_QUERY_PARAM_PREFIX.length);i[r]=t,delete i[e]}}let s=Object.keys(a||{}),filterLocaleItem=e=>{if(t){let a=Array.isArray(e),o=a?e[0]:e;if("string"==typeof o&&t.locales.some(e=>e.toLowerCase()===o.toLowerCase()&&(n=e,r.locale=n,!0)))return a&&e.splice(0,1),!a||0===e.length}return!1};return s.every(e=>i[e])?s.reduce((t,r)=>{let n=null==a?void 0:a[r];return n&&!filterLocaleItem(i[r])&&(t[e[n].pos]=i[r]),t},{}):Object.keys(i).reduce((e,t)=>{if(!filterLocaleItem(i[t])){let r=t;return u&&(r=parseInt(t,10)-1+""),Object.assign(e,{[r]:i[t]})}return e},{})}},groups:e}}())(e.headers["x-now-route-matches"])}function normalizeDynamicRouteParams(e,t){let r=!0;return m?{params:e=Object.keys(m.groups).reduce((n,a)=>{let o=e[a];"string"==typeof o&&(o=(0,l.normalizeRscURL)(o)),Array.isArray(o)&&(o=o.map(e=>("string"==typeof e&&(e=(0,l.normalizeRscURL)(e)),e)));let i=h[a],u=m.groups[a].optional,s=Array.isArray(i)?i.some(e=>Array.isArray(o)?o.some(t=>t.includes(e)):null==o?void 0:o.includes(e)):null==o?void 0:o.includes(i);return(s||void 0===o&&!(u&&t))&&(r=!1),u&&(!o||Array.isArray(o)&&1===o.length&&("index"===o[0]||o[0]===`[[...${a}]]`))&&(o=void 0,delete e[a]),o&&"string"==typeof o&&m.groups[a].repeat&&(o=o.split("/")),o&&(n[a]=o),n},{}),hasValidParams:r}:{params:e,hasValidParams:!1}}return f&&(m=(0,i.getNamedRouteRegex)(e,!1),h=(R=(0,u.getRouteMatcher)(m))(e)),{handleRewrites:function(i,u){let l={},p=u.pathname,checkRewrite=n=>{let c=(0,o.getPathMatch)(n.source+(d?"(/)?":""),{removeUnnamedParams:!0,strict:!0,sensitive:!!g}),m=c(u.pathname);if((n.has||n.missing)&&m){let e=(0,s.matchHas)(i,u.query,n.has,n.missing);e?Object.assign(m,e):m=!1}if(m){let{parsedDestination:o,destQuery:i}=(0,s.prepareDestination)({appendParamsToQuery:!0,destination:n.destination,params:m,query:u.query});if(o.protocol)return!0;if(Object.assign(l,i,m),Object.assign(u.query,o.query),delete o.query,Object.assign(u,o),p=u.pathname,r&&(p=p.replace(RegExp(`^${r}`),"")||"/"),t){let e=(0,a.normalizeLocalePath)(p,t.locales);p=e.pathname,u.query.nextInternalLocale=e.detectedLocale||m.nextInternalLocale}if(p===e)return!0;if(f&&R){let e=R(p);if(e)return u.query={...u.query,...e},!0}}return!1};for(let e of n.beforeFiles||[])checkRewrite(e);if(p!==e){let t=!1;for(let e of n.afterFiles||[])if(t=checkRewrite(e))break;if(!t&&!(()=>{let t=(0,c.removeTrailingSlash)(p||"");return t===(0,c.removeTrailingSlash)(e)||(null==R?void 0:R(t))})()){for(let e of n.fallback||[])if(t=checkRewrite(e))break}}return l},defaultRouteRegex:m,dynamicRouteMatcher:R,defaultRouteMatches:h,getParamsFromRouteMatches,normalizeDynamicRouteParams,normalizeVercelUrl:(e,t,r)=>normalizeVercelUrl(e,t,r,f,m),interpolateDynamicPath:(e,t)=>interpolateDynamicPath(e,t,m)}}},9789:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"escapeStringRegexp",{enumerable:!0,get:function(){return escapeStringRegexp}});let r=/[|\\{}()[\]^$+*?.-]/,n=/[|\\{}()[\]^$+*?.-]/g;function escapeStringRegexp(e){return r.test(e)?e.replace(n,"\\$&"):e}},8043:(e,t)=>{function djb2Hash(e){let t=5381;for(let r=0;r{function normalizeLocalePath(e,t){let r;let n=e.split("/");return(t||[]).some(t=>!!n[1]&&n[1].toLowerCase()===t.toLowerCase()&&(r=t,n.splice(1,1),e=n.join("/")||"/",!0)),{pathname:e,detectedLocale:r}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizeLocalePath",{enumerable:!0,get:function(){return normalizeLocalePath}})},5585:(e,t,r)=>{let n;n=r(1017),e.exports=n},9701:(e,t)=>{function ensureLeadingSlash(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return ensureLeadingSlash}})},7819:(e,t)=>{function normalizePathSep(e){return e.replace(/\\/g,"/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathSep",{enumerable:!0,get:function(){return normalizePathSep}})},1478:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeAppPath:function(){return normalizeAppPath},normalizeRscURL:function(){return normalizeRscURL},normalizePostponedURL:function(){return normalizePostponedURL}});let n=r(9701),a=r(2219);function normalizeAppPath(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,r,n)=>!t||(0,a.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&r===n.length-1?e:e+"/"+t,""))}function normalizeRscURL(e){return e.replace(/\.rsc($|\?)/,"$1")}function normalizePostponedURL(e){let t=new URL(e),{pathname:r}=t;return r&&r.startsWith("/_next/postponed")?(t.pathname=r.substring(16)||"/",t.toString()):e}},129:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseRelativeUrl",{enumerable:!0,get:function(){return parseRelativeUrl}}),r(351);let n=r(6024);function parseRelativeUrl(e,t){let r=new URL("http://n"),a=t?new URL(t,r):e.startsWith(".")?new URL("http://n"):r,{pathname:o,searchParams:i,search:u,hash:s,href:c,origin:l}=new URL(e,a);if(l!==r.origin)throw Error("invariant: invalid relative URL, router received "+e);return{pathname:o,query:(0,n.searchParamsToUrlQuery)(i),search:u,hash:s,href:c.slice(r.origin.length)}}},6940:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseUrl",{enumerable:!0,get:function(){return parseUrl}});let n=r(6024),a=r(129);function parseUrl(e){if(e.startsWith("/"))return(0,a.parseRelativeUrl)(e);let t=new URL(e);return{hash:t.hash,hostname:t.hostname,href:t.href,pathname:t.pathname,port:t.port,protocol:t.protocol,query:(0,n.searchParamsToUrlQuery)(t.searchParams),search:t.search}}},9302:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getPathMatch",{enumerable:!0,get:function(){return getPathMatch}});let n=r(9481);function getPathMatch(e,t){let r=[],a=(0,n.pathToRegexp)(e,r,{delimiter:"/",sensitive:"boolean"==typeof(null==t?void 0:t.sensitive)&&t.sensitive,strict:null==t?void 0:t.strict}),o=(0,n.regexpToFunction)((null==t?void 0:t.regexModifier)?new RegExp(t.regexModifier(a.source),a.flags):a,r);return(e,n)=>{if("string"!=typeof e)return!1;let a=o(e);if(!a)return!1;if(null==t?void 0:t.removeUnnamedParams)for(let e of r)"number"==typeof e.name&&delete a.params[e.name];return{...n,...a.params}}}},1731:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{matchHas:function(){return matchHas},compileNonPath:function(){return compileNonPath},prepareDestination:function(){return prepareDestination}});let n=r(9481),a=r(9789),o=r(6940),i=r(7302),u=r(9001),s=r(4427);function getSafeParamName(e){let t="";for(let r=0;r64&&n<91||n>96&&n<123)&&(t+=e[r])}return t}function escapeSegment(e,t){return e.replace(RegExp(":"+(0,a.escapeStringRegexp)(t),"g"),"__ESC_COLON_"+t)}function unescapeSegments(e){return e.replace(/__ESC_COLON_/gi,":")}function matchHas(e,t,r,n){void 0===r&&(r=[]),void 0===n&&(n=[]);let a={},hasMatch=r=>{let n;let o=r.key;switch(r.type){case"header":o=o.toLowerCase(),n=e.headers[o];break;case"cookie":if("cookies"in e)n=e.cookies[r.key];else{let t=(0,s.getCookieParser)(e.headers)();n=t[r.key]}break;case"query":n=t[o];break;case"host":{let{host:t}=(null==e?void 0:e.headers)||{},r=null==t?void 0:t.split(":",1)[0].toLowerCase();n=r}}if(!r.value&&n)return a[getSafeParamName(o)]=n,!0;if(n){let e=RegExp("^"+r.value+"$"),t=Array.isArray(n)?n.slice(-1)[0].match(e):n.match(e);if(t)return Array.isArray(t)&&(t.groups?Object.keys(t.groups).forEach(e=>{a[e]=t.groups[e]}):"host"===r.type&&t[0]&&(a.host=t[0])),!0}return!1},o=r.every(e=>hasMatch(e))&&!n.some(e=>hasMatch(e));return!!o&&a}function compileNonPath(e,t){if(!e.includes(":"))return e;for(let r of Object.keys(t))e.includes(":"+r)&&(e=e.replace(RegExp(":"+r+"\\*","g"),":"+r+"--ESCAPED_PARAM_ASTERISKS").replace(RegExp(":"+r+"\\?","g"),":"+r+"--ESCAPED_PARAM_QUESTION").replace(RegExp(":"+r+"\\+","g"),":"+r+"--ESCAPED_PARAM_PLUS").replace(RegExp(":"+r+"(?!\\w)","g"),"--ESCAPED_PARAM_COLON"+r));return e=e.replace(/(:|\*|\?|\+|\(|\)|\{|\})/g,"\\$1").replace(/--ESCAPED_PARAM_PLUS/g,"+").replace(/--ESCAPED_PARAM_COLON/g,":").replace(/--ESCAPED_PARAM_QUESTION/g,"?").replace(/--ESCAPED_PARAM_ASTERISKS/g,"*"),(0,n.compile)("/"+e,{validate:!1})(t).slice(1)}function prepareDestination(e){let t;let r=Object.assign({},e.query);delete r.__nextLocale,delete r.__nextDefaultLocale,delete r.__nextDataReq,delete r.__nextInferredLocaleFromDefault,delete r[u.NEXT_RSC_UNION_QUERY];let a=e.destination;for(let t of Object.keys({...e.params,...r}))a=escapeSegment(a,t);let s=(0,o.parseUrl)(a),c=s.query,l=unescapeSegments(""+s.pathname+(s.hash||"")),p=unescapeSegments(s.hostname||""),f=[],d=[];(0,n.pathToRegexp)(l,f),(0,n.pathToRegexp)(p,d);let g=[];f.forEach(e=>g.push(e.name)),d.forEach(e=>g.push(e.name));let m=(0,n.compile)(l,{validate:!1}),R=(0,n.compile)(p,{validate:!1});for(let[t,r]of Object.entries(c))Array.isArray(r)?c[t]=r.map(t=>compileNonPath(unescapeSegments(t),e.params)):"string"==typeof r&&(c[t]=compileNonPath(unescapeSegments(r),e.params));let h=Object.keys(e.params).filter(e=>"nextInternalLocale"!==e);if(e.appendParamsToQuery&&!h.some(e=>g.includes(e)))for(let t of h)t in c||(c[t]=e.params[t]);if((0,i.isInterceptionRouteAppPath)(l))for(let t of l.split("/")){let r=i.INTERCEPTION_ROUTE_MARKERS.find(e=>t.startsWith(e));if(r){e.params["0"]=r;break}}try{t=m(e.params);let[r,n]=t.split("#",2);s.hostname=R(e.params),s.pathname=r,s.hash=(n?"#":"")+(n||""),delete s.search}catch(e){if(e.message.match(/Expected .*? to not repeat, but got an array/))throw Error("To use a multi-match in the destination you must add `*` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match");throw e}return s.query={...r,...s.query},{newUrl:t,destQuery:c,parsedDestination:s}}},6024:(e,t)=>{function searchParamsToUrlQuery(e){let t={};return e.forEach((e,r)=>{void 0===t[r]?t[r]=e:Array.isArray(t[r])?t[r].push(e):t[r]=[t[r],e]}),t}function stringifyUrlQueryParam(e){return"string"!=typeof e&&("number"!=typeof e||isNaN(e))&&"boolean"!=typeof e?"":String(e)}function urlQueryToSearchParams(e){let t=new URLSearchParams;return Object.entries(e).forEach(e=>{let[r,n]=e;Array.isArray(n)?n.forEach(e=>t.append(r,stringifyUrlQueryParam(e))):t.set(r,stringifyUrlQueryParam(n))}),t}function assign(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n{Array.from(t.keys()).forEach(t=>e.delete(t)),t.forEach((t,r)=>e.append(r,t))}),e}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{searchParamsToUrlQuery:function(){return searchParamsToUrlQuery},urlQueryToSearchParams:function(){return urlQueryToSearchParams},assign:function(){return assign}})},4419:(e,t)=>{function removeTrailingSlash(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return removeTrailingSlash}})},4893:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getRouteMatcher",{enumerable:!0,get:function(){return getRouteMatcher}});let n=r(351);function getRouteMatcher(e){let{re:t,groups:r}=e;return e=>{let a=t.exec(e);if(!a)return!1;let decode=e=>{try{return decodeURIComponent(e)}catch(e){throw new n.DecodeError("failed to decode param")}},o={};return Object.keys(r).forEach(e=>{let t=r[e],n=a[t.pos];void 0!==n&&(o[e]=~n.indexOf("/")?n.split("/").map(e=>decode(e)):t.repeat?[decode(n)]:decode(n))}),o}}},4018:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getRouteRegex:function(){return getRouteRegex},getNamedRouteRegex:function(){return getNamedRouteRegex},getNamedMiddlewareRegex:function(){return getNamedMiddlewareRegex}});let n=r(7302),a=r(9789),o=r(4419);function parseParameter(e){let t=e.startsWith("[")&&e.endsWith("]");t&&(e=e.slice(1,-1));let r=e.startsWith("...");return r&&(e=e.slice(3)),{key:e,repeat:r,optional:t}}function getParametrizedRoute(e){let t=(0,o.removeTrailingSlash)(e).slice(1).split("/"),r={},i=1;return{parameterizedRoute:t.map(e=>{let t=n.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t)),o=e.match(/\[((?:\[.*\])|.+)\]/);if(t&&o){let{key:e,optional:n,repeat:u}=parseParameter(o[1]);return r[e]={pos:i++,repeat:u,optional:n},"/"+(0,a.escapeStringRegexp)(t)+"([^/]+?)"}if(!o)return"/"+(0,a.escapeStringRegexp)(e);{let{key:e,repeat:t,optional:n}=parseParameter(o[1]);return r[e]={pos:i++,repeat:t,optional:n},t?n?"(?:/(.+?))?":"/(.+?)":"/([^/]+?)"}}).join(""),groups:r}}function getRouteRegex(e){let{parameterizedRoute:t,groups:r}=getParametrizedRoute(e);return{re:RegExp("^"+t+"(?:/)?$"),groups:r}}function buildGetSafeRouteKey(){let e=0;return()=>{let t="",r=++e;for(;r>0;)t+=String.fromCharCode(97+(r-1)%26),r=Math.floor((r-1)/26);return t}}function getSafeKeyFromSegment(e){let{getSafeRouteKey:t,segment:r,routeKeys:n,keyPrefix:a}=e,{key:o,optional:i,repeat:u}=parseParameter(r),s=o.replace(/\W/g,"");a&&(s=""+a+s);let c=!1;return(0===s.length||s.length>30)&&(c=!0),isNaN(parseInt(s.slice(0,1)))||(c=!0),c&&(s=t()),a?n[s]=""+a+o:n[s]=""+o,u?i?"(?:/(?<"+s+">.+?))?":"/(?<"+s+">.+?)":"/(?<"+s+">[^/]+?)"}function getNamedParametrizedRoute(e,t){let r=(0,o.removeTrailingSlash)(e).slice(1).split("/"),i=buildGetSafeRouteKey(),u={};return{namedParameterizedRoute:r.map(e=>{let r=n.INTERCEPTION_ROUTE_MARKERS.some(t=>e.startsWith(t)),o=e.match(/\[((?:\[.*\])|.+)\]/);return r&&o?getSafeKeyFromSegment({getSafeRouteKey:i,segment:o[1],routeKeys:u,keyPrefix:t?"nxtI":void 0}):o?getSafeKeyFromSegment({getSafeRouteKey:i,segment:o[1],routeKeys:u,keyPrefix:t?"nxtP":void 0}):"/"+(0,a.escapeStringRegexp)(e)}).join(""),routeKeys:u}}function getNamedRouteRegex(e,t){let r=getNamedParametrizedRoute(e,t);return{...getRouteRegex(e),namedRegex:"^"+r.namedParameterizedRoute+"(?:/)?$",routeKeys:r.routeKeys}}function getNamedMiddlewareRegex(e,t){let{parameterizedRoute:r}=getParametrizedRoute(e),{catchAll:n=!0}=t;if("/"===r)return{namedRegex:"^/"+(n?".*":"")+"$"};let{namedParameterizedRoute:a}=getNamedParametrizedRoute(e,!1);return{namedRegex:"^"+a+(n?"(?:(/.*)?)":"")+"$"}}},2219:(e,t)=>{function isGroupSegment(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isGroupSegment",{enumerable:!0,get:function(){return isGroupSegment}})},351:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{WEB_VITALS:function(){return r},execOnce:function(){return execOnce},isAbsoluteUrl:function(){return isAbsoluteUrl},getLocationOrigin:function(){return getLocationOrigin},getURL:function(){return getURL},getDisplayName:function(){return getDisplayName},isResSent:function(){return isResSent},normalizeRepeatedSlashes:function(){return normalizeRepeatedSlashes},loadGetInitialProps:function(){return loadGetInitialProps},SP:function(){return a},ST:function(){return o},DecodeError:function(){return DecodeError},NormalizeError:function(){return NormalizeError},PageNotFoundError:function(){return PageNotFoundError},MissingStaticPage:function(){return MissingStaticPage},MiddlewareNotFoundError:function(){return MiddlewareNotFoundError},stringifyError:function(){return stringifyError}});let r=["CLS","FCP","FID","INP","LCP","TTFB"];function execOnce(e){let t,r=!1;return function(){for(var n=arguments.length,a=Array(n),o=0;on.test(e);function getLocationOrigin(){let{protocol:e,hostname:t,port:r}=window.location;return e+"//"+t+(r?":"+r:"")}function getURL(){let{href:e}=window.location,t=getLocationOrigin();return e.substring(t.length)}function getDisplayName(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function isResSent(e){return e.finished||e.headersSent}function normalizeRepeatedSlashes(e){let t=e.split("?"),r=t[0];return r.replace(/\\/g,"/").replace(/\/\/+/g,"/")+(t[1]?"?"+t.slice(1).join("?"):"")}async function loadGetInitialProps(e,t){let r=t.res||t.ctx&&t.ctx.res;if(!e.getInitialProps)return t.ctx&&t.Component?{pageProps:await loadGetInitialProps(t.Component,t.ctx)}:{};let n=await e.getInitialProps(t);if(r&&isResSent(r))return n;if(!n){let t='"'+getDisplayName(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.';throw Error(t)}return n}let a="undefined"!=typeof performance,o=a&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);let DecodeError=class DecodeError extends Error{};let NormalizeError=class NormalizeError extends Error{};let PageNotFoundError=class PageNotFoundError extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}};let MissingStaticPage=class MissingStaticPage extends Error{constructor(e,t){super(),this.message="Failed to load static file for page: "+e+" "+t}};let MiddlewareNotFoundError=class MiddlewareNotFoundError extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}};function stringifyError(e){return JSON.stringify({message:e.message,stack:e.stack})}}}; \ No newline at end of file diff --git a/.next/server/chunks/405.js b/.next/server/chunks/405.js deleted file mode 100644 index 73ad1e3..0000000 --- a/.next/server/chunks/405.js +++ /dev/null @@ -1,509 +0,0 @@ -"use strict"; -exports.id = 405; -exports.ids = [405]; -exports.modules = { - -/***/ 3332: -/***/ ((module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - DYNAMIC_ERROR_CODE: function() { - return DYNAMIC_ERROR_CODE; - }, - DynamicServerError: function() { - return DynamicServerError; - } -}); -const DYNAMIC_ERROR_CODE = "DYNAMIC_SERVER_USAGE"; -class DynamicServerError extends Error { - constructor(type){ - super("Dynamic server usage: " + type); - this.digest = DYNAMIC_ERROR_CODE; - } -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=hooks-server-context.js.map - - -/***/ }), - -/***/ 5486: -/***/ ((module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "staticGenerationBailout", ({ - enumerable: true, - get: function() { - return staticGenerationBailout; - } -})); -const _hooksservercontext = __webpack_require__(3332); -const _staticgenerationasyncstorage = __webpack_require__(94); -class StaticGenBailoutError extends Error { - constructor(...args){ - super(...args); - this.code = "NEXT_STATIC_GEN_BAILOUT"; - } -} -const staticGenerationBailout = (reason, opts)=>{ - const staticGenerationStore = _staticgenerationasyncstorage.staticGenerationAsyncStorage.getStore(); - if (staticGenerationStore == null ? void 0 : staticGenerationStore.forceStatic) { - return true; - } - if (staticGenerationStore == null ? void 0 : staticGenerationStore.dynamicShouldError) { - const { dynamic ="error" , link } = opts || {}; - const suffix = link ? " See more info here: " + link : ""; - throw new StaticGenBailoutError('Page with `dynamic = "' + dynamic + "\"` couldn't be rendered statically because it used `" + reason + "`." + suffix); - } - if (staticGenerationStore) { - staticGenerationStore.revalidate = 0; - } - if (staticGenerationStore == null ? void 0 : staticGenerationStore.isStaticGeneration) { - const err = new _hooksservercontext.DynamicServerError(reason); - staticGenerationStore.dynamicUsageDescription = reason; - staticGenerationStore.dynamicUsageStack = err.stack; - throw err; - } - return false; -}; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=static-generation-bailout.js.map - - -/***/ }), - -/***/ 8537: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - NEXT_QUERY_PARAM_PREFIX: function() { - return NEXT_QUERY_PARAM_PREFIX; - }, - PRERENDER_REVALIDATE_HEADER: function() { - return PRERENDER_REVALIDATE_HEADER; - }, - PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER: function() { - return PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER; - }, - CACHE_ONE_YEAR: function() { - return CACHE_ONE_YEAR; - }, - MIDDLEWARE_FILENAME: function() { - return MIDDLEWARE_FILENAME; - }, - MIDDLEWARE_LOCATION_REGEXP: function() { - return MIDDLEWARE_LOCATION_REGEXP; - }, - INSTRUMENTATION_HOOK_FILENAME: function() { - return INSTRUMENTATION_HOOK_FILENAME; - }, - INSTRUMENTATION_HOOKS_LOCATION_REGEXP: function() { - return INSTRUMENTATION_HOOKS_LOCATION_REGEXP; - }, - PAGES_DIR_ALIAS: function() { - return PAGES_DIR_ALIAS; - }, - DOT_NEXT_ALIAS: function() { - return DOT_NEXT_ALIAS; - }, - ROOT_DIR_ALIAS: function() { - return ROOT_DIR_ALIAS; - }, - APP_DIR_ALIAS: function() { - return APP_DIR_ALIAS; - }, - RSC_MOD_REF_PROXY_ALIAS: function() { - return RSC_MOD_REF_PROXY_ALIAS; - }, - RSC_ACTION_VALIDATE_ALIAS: function() { - return RSC_ACTION_VALIDATE_ALIAS; - }, - RSC_ACTION_PROXY_ALIAS: function() { - return RSC_ACTION_PROXY_ALIAS; - }, - RSC_ACTION_CLIENT_WRAPPER_ALIAS: function() { - return RSC_ACTION_CLIENT_WRAPPER_ALIAS; - }, - PUBLIC_DIR_MIDDLEWARE_CONFLICT: function() { - return PUBLIC_DIR_MIDDLEWARE_CONFLICT; - }, - SSG_GET_INITIAL_PROPS_CONFLICT: function() { - return SSG_GET_INITIAL_PROPS_CONFLICT; - }, - SERVER_PROPS_GET_INIT_PROPS_CONFLICT: function() { - return SERVER_PROPS_GET_INIT_PROPS_CONFLICT; - }, - SERVER_PROPS_SSG_CONFLICT: function() { - return SERVER_PROPS_SSG_CONFLICT; - }, - STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR: function() { - return STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR; - }, - SERVER_PROPS_EXPORT_ERROR: function() { - return SERVER_PROPS_EXPORT_ERROR; - }, - GSP_NO_RETURNED_VALUE: function() { - return GSP_NO_RETURNED_VALUE; - }, - GSSP_NO_RETURNED_VALUE: function() { - return GSSP_NO_RETURNED_VALUE; - }, - UNSTABLE_REVALIDATE_RENAME_ERROR: function() { - return UNSTABLE_REVALIDATE_RENAME_ERROR; - }, - GSSP_COMPONENT_MEMBER_ERROR: function() { - return GSSP_COMPONENT_MEMBER_ERROR; - }, - NON_STANDARD_NODE_ENV: function() { - return NON_STANDARD_NODE_ENV; - }, - SSG_FALLBACK_EXPORT_ERROR: function() { - return SSG_FALLBACK_EXPORT_ERROR; - }, - ESLINT_DEFAULT_DIRS: function() { - return ESLINT_DEFAULT_DIRS; - }, - ESLINT_DEFAULT_DIRS_WITH_APP: function() { - return ESLINT_DEFAULT_DIRS_WITH_APP; - }, - ESLINT_PROMPT_VALUES: function() { - return ESLINT_PROMPT_VALUES; - }, - SERVER_RUNTIME: function() { - return SERVER_RUNTIME; - }, - WEBPACK_LAYERS: function() { - return WEBPACK_LAYERS; - } -}); -const NEXT_QUERY_PARAM_PREFIX = "nxtP"; -const PRERENDER_REVALIDATE_HEADER = "x-prerender-revalidate"; -const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER = "x-prerender-revalidate-if-generated"; -const CACHE_ONE_YEAR = 31536000; -const MIDDLEWARE_FILENAME = "middleware"; -const MIDDLEWARE_LOCATION_REGEXP = `(?:src/)?${MIDDLEWARE_FILENAME}`; -const INSTRUMENTATION_HOOK_FILENAME = "instrumentation"; -const INSTRUMENTATION_HOOKS_LOCATION_REGEXP = `(?:src/)?${INSTRUMENTATION_HOOK_FILENAME}`; -const PAGES_DIR_ALIAS = "private-next-pages"; -const DOT_NEXT_ALIAS = "private-dot-next"; -const ROOT_DIR_ALIAS = "private-next-root-dir"; -const APP_DIR_ALIAS = "private-next-app-dir"; -const RSC_MOD_REF_PROXY_ALIAS = "next/dist/build/webpack/loaders/next-flight-loader/module-proxy"; -const RSC_ACTION_VALIDATE_ALIAS = "private-next-rsc-action-validate"; -const RSC_ACTION_PROXY_ALIAS = "private-next-rsc-action-proxy"; -const RSC_ACTION_CLIENT_WRAPPER_ALIAS = "private-next-rsc-action-client-wrapper"; -const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict`; -const SSG_GET_INITIAL_PROPS_CONFLICT = `You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps`; -const SERVER_PROPS_GET_INIT_PROPS_CONFLICT = `You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.`; -const SERVER_PROPS_SSG_CONFLICT = `You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps`; -const STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR = `can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props`; -const SERVER_PROPS_EXPORT_ERROR = `pages with \`getServerSideProps\` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export`; -const GSP_NO_RETURNED_VALUE = "Your `getStaticProps` function did not return an object. Did you forget to add a `return`?"; -const GSSP_NO_RETURNED_VALUE = "Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?"; -const UNSTABLE_REVALIDATE_RENAME_ERROR = "The `unstable_revalidate` property is available for general use.\n" + "Please use `revalidate` instead."; -const GSSP_COMPONENT_MEMBER_ERROR = `can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member`; -const NON_STANDARD_NODE_ENV = `You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env`; -const SSG_FALLBACK_EXPORT_ERROR = `Pages with \`fallback\` enabled in \`getStaticPaths\` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export`; -const ESLINT_DEFAULT_DIRS = [ - "pages", - "components", - "lib", - "src" -]; -const ESLINT_DEFAULT_DIRS_WITH_APP = [ - "app", - ...ESLINT_DEFAULT_DIRS -]; -const ESLINT_PROMPT_VALUES = [ - { - title: "Strict", - recommended: true, - config: { - extends: "next/core-web-vitals" - } - }, - { - title: "Base", - config: { - extends: "next" - } - }, - { - title: "Cancel", - config: null - } -]; -const SERVER_RUNTIME = { - edge: "edge", - experimentalEdge: "experimental-edge", - nodejs: "nodejs" -}; -const WEBPACK_LAYERS = { - shared: "sc_shared", - server: "sc_server", - client: "sc_client", - action: "sc_action", - api: "api", - middleware: "middleware", - edgeAsset: "edge-asset", - appClient: "app-client" -}; //# sourceMappingURL=constants.js.map - - -/***/ }), - -/***/ 2207: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "detectDomainLocale", ({ - enumerable: true, - get: function() { - return detectDomainLocale; - } -})); -function detectDomainLocale(domainItems, hostname, detectedLocale) { - if (!domainItems) return; - if (detectedLocale) { - detectedLocale = detectedLocale.toLowerCase(); - } - for (const item of domainItems){ - var _item_domain, _item_locales; - // remove port if present - const domainHostname = (_item_domain = item.domain) == null ? void 0 : _item_domain.split(":")[0].toLowerCase(); - if (hostname === domainHostname || detectedLocale === item.defaultLocale.toLowerCase() || ((_item_locales = item.locales) == null ? void 0 : _item_locales.some((locale)=>locale.toLowerCase() === detectedLocale))) { - return item; - } - } -} //# sourceMappingURL=detect-domain-locale.js.map - - -/***/ }), - -/***/ 9962: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "normalizeLocalePath", ({ - enumerable: true, - get: function() { - return normalizeLocalePath; - } -})); -function normalizeLocalePath(pathname, locales) { - let detectedLocale; - // first item will be empty string from splitting at first char - const pathnameParts = pathname.split("/"); - (locales || []).some((locale)=>{ - if (pathnameParts[1] && pathnameParts[1].toLowerCase() === locale.toLowerCase()) { - detectedLocale = locale; - pathnameParts.splice(1, 1); - pathname = pathnameParts.join("/") || "/"; - return true; - } - return false; - }); - return { - pathname, - detectedLocale - }; -} //# sourceMappingURL=normalize-locale-path.js.map - - -/***/ }), - -/***/ 465: -/***/ ((__unused_webpack_module, exports) => { - -/** - * Removes the trailing slash for a given route or page path. Preserves the - * root page. Examples: - * - `/foo/bar/` -> `/foo/bar` - * - `/foo/bar` -> `/foo/bar` - * - `/` -> `/` - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "removeTrailingSlash", ({ - enumerable: true, - get: function() { - return removeTrailingSlash; - } -})); -function removeTrailingSlash(route) { - return route.replace(/\/$/, "") || "/"; -} //# sourceMappingURL=remove-trailing-slash.js.map - - -/***/ }), - -/***/ 6127: -/***/ ((module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "actionAsyncStorage", ({ - enumerable: true, - get: function() { - return actionAsyncStorage; - } -})); -const _asynclocalstorage = __webpack_require__(5862); -const actionAsyncStorage = (0, _asynclocalstorage.createAsyncLocalStorage)(); -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=action-async-storage.js.map - - -/***/ }), - -/***/ 5862: -/***/ ((module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createAsyncLocalStorage", ({ - enumerable: true, - get: function() { - return createAsyncLocalStorage; - } -})); -class FakeAsyncLocalStorage { - disable() { - throw new Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"); - } - getStore() { - // This fake implementation of AsyncLocalStorage always returns `undefined`. - return undefined; - } - run() { - throw new Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"); - } - exit() { - throw new Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"); - } - enterWith() { - throw new Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"); - } -} -function createAsyncLocalStorage() { - if (globalThis.AsyncLocalStorage) { - return new globalThis.AsyncLocalStorage(); - } - return new FakeAsyncLocalStorage(); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=async-local-storage.js.map - - -/***/ }), - -/***/ 4437: -/***/ ((module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "requestAsyncStorage", ({ - enumerable: true, - get: function() { - return requestAsyncStorage; - } -})); -const _asynclocalstorage = __webpack_require__(5862); -const requestAsyncStorage = (0, _asynclocalstorage.createAsyncLocalStorage)(); -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=request-async-storage.js.map - - -/***/ }), - -/***/ 94: -/***/ ((module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "staticGenerationAsyncStorage", ({ - enumerable: true, - get: function() { - return staticGenerationAsyncStorage; - } -})); -const _asynclocalstorage = __webpack_require__(5862); -const staticGenerationAsyncStorage = (0, _asynclocalstorage.createAsyncLocalStorage)(); -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=static-generation-async-storage.js.map - - -/***/ }) - -}; -; \ No newline at end of file diff --git a/.next/server/chunks/421.js b/.next/server/chunks/421.js deleted file mode 100644 index 94026cd..0000000 --- a/.next/server/chunks/421.js +++ /dev/null @@ -1,690 +0,0 @@ -exports.id = 421; -exports.ids = [421]; -exports.modules = { - -/***/ 7649: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "default", ({ - enumerable: true, - get: function() { - return _default; - } -})); -const _interop_require_default = __webpack_require__(5967); -const _interop_require_wildcard = __webpack_require__(1113); -const _react = /*#__PURE__*/ _interop_require_wildcard._(__webpack_require__(8038)); -const _head = /*#__PURE__*/ _interop_require_default._(__webpack_require__(9040)); -const _imageblursvg = __webpack_require__(4486); -const _imageconfig = __webpack_require__(5843); -const _imageconfigcontext = __webpack_require__(744); -const _warnonce = __webpack_require__(618); -const _imageloader = /*#__PURE__*/ _interop_require_default._(__webpack_require__(9552)); -const configEnv = {"deviceSizes":[640,750,828,1080,1200,1920,2048,3840],"imageSizes":[16,32,48,64,96,128,256,384],"path":"/_next/image","loader":"default","dangerouslyAllowSVG":false,"unoptimized":false}; -const allImgs = new Map(); -let perfObserver; -if (true) { - globalThis.__NEXT_IMAGE_IMPORTED = true; -} -const VALID_LOADING_VALUES = (/* unused pure expression or super */ null && ([ - "lazy", - "eager", - undefined -])); -function isStaticRequire(src) { - return src.default !== undefined; -} -function isStaticImageData(src) { - return src.src !== undefined; -} -function isStaticImport(src) { - return typeof src === "object" && (isStaticRequire(src) || isStaticImageData(src)); -} -function getWidths(param, width, sizes) { - let { deviceSizes , allSizes } = param; - if (sizes) { - // Find all the "vw" percent sizes used in the sizes prop - const viewportWidthRe = /(^|\s)(1?\d?\d)vw/g; - const percentSizes = []; - for(let match; match = viewportWidthRe.exec(sizes); match){ - percentSizes.push(parseInt(match[2])); - } - if (percentSizes.length) { - const smallestRatio = Math.min(...percentSizes) * 0.01; - return { - widths: allSizes.filter((s)=>s >= deviceSizes[0] * smallestRatio), - kind: "w" - }; - } - return { - widths: allSizes, - kind: "w" - }; - } - if (typeof width !== "number") { - return { - widths: deviceSizes, - kind: "w" - }; - } - const widths = [ - ...new Set(// > are actually 3x in the green color, but only 1.5x in the red and - // > blue colors. Showing a 3x resolution image in the app vs a 2x - // > resolution image will be visually the same, though the 3x image - // > takes significantly more data. Even true 3x resolution screens are - // > wasteful as the human eye cannot see that level of detail without - // > something like a magnifying glass. - // https://blog.twitter.com/engineering/en_us/topics/infrastructure/2019/capping-image-fidelity-on-ultra-high-resolution-devices.html - [ - width, - width * 2 /*, width * 3*/ - ].map((w)=>allSizes.find((p)=>p >= w) || allSizes[allSizes.length - 1])) - ]; - return { - widths, - kind: "x" - }; -} -function generateImgAttrs(param) { - let { config , src , unoptimized , width , quality , sizes , loader } = param; - if (unoptimized) { - return { - src, - srcSet: undefined, - sizes: undefined - }; - } - const { widths , kind } = getWidths(config, width, sizes); - const last = widths.length - 1; - return { - sizes: !sizes && kind === "w" ? "100vw" : sizes, - srcSet: widths.map((w, i)=>loader({ - config, - src, - quality, - width: w - }) + " " + (kind === "w" ? w : i + 1) + kind).join(", "), - // It's intended to keep `src` the last attribute because React updates - // attributes in order. If we keep `src` the first one, Safari will - // immediately start to fetch `src`, before `sizes` and `srcSet` are even - // updated by React. That causes multiple unnecessary requests if `srcSet` - // and `sizes` are defined. - // This bug cannot be reproduced in Chrome or Firefox. - src: loader({ - config, - src, - quality, - width: widths[last] - }) - }; -} -function getInt(x) { - if (typeof x === "undefined") { - return x; - } - if (typeof x === "number") { - return Number.isFinite(x) ? x : NaN; - } - if (typeof x === "string" && /^[0-9]+$/.test(x)) { - return parseInt(x, 10); - } - return NaN; -} -// See https://stackoverflow.com/q/39777833/266535 for why we use this ref -// handler instead of the img's onLoad attribute. -function handleLoading(img, src, placeholder, onLoadRef, onLoadingCompleteRef, setBlurComplete, unoptimized) { - if (!img || img["data-loaded-src"] === src) { - return; - } - img["data-loaded-src"] = src; - const p = "decode" in img ? img.decode() : Promise.resolve(); - p.catch(()=>{}).then(()=>{ - if (!img.parentElement || !img.isConnected) { - // Exit early in case of race condition: - // - onload() is called - // - decode() is called but incomplete - // - unmount is called - // - decode() completes - return; - } - if (placeholder === "blur") { - setBlurComplete(true); - } - if (onLoadRef == null ? void 0 : onLoadRef.current) { - // Since we don't have the SyntheticEvent here, - // we must create one with the same shape. - // See https://reactjs.org/docs/events.html - const event = new Event("load"); - Object.defineProperty(event, "target", { - writable: false, - value: img - }); - let prevented = false; - let stopped = false; - onLoadRef.current({ - ...event, - nativeEvent: event, - currentTarget: img, - target: img, - isDefaultPrevented: ()=>prevented, - isPropagationStopped: ()=>stopped, - persist: ()=>{}, - preventDefault: ()=>{ - prevented = true; - event.preventDefault(); - }, - stopPropagation: ()=>{ - stopped = true; - event.stopPropagation(); - } - }); - } - if (onLoadingCompleteRef == null ? void 0 : onLoadingCompleteRef.current) { - onLoadingCompleteRef.current(img); - } - if (false) {} - }); -} -function getDynamicProps(fetchPriority) { - const [majorStr, minorStr] = _react.version.split("."); - const major = parseInt(majorStr, 10); - const minor = parseInt(minorStr, 10); - if (major > 18 || major === 18 && minor >= 3) { - // In React 18.3.0 or newer, we must use camelCase - // prop to avoid "Warning: Invalid DOM property". - // See https://github.com/facebook/react/pull/25927 - return { - fetchPriority - }; - } - // In React 18.2.0 or older, we must use lowercase prop - // to avoid "Warning: Invalid DOM property". - return { - fetchpriority: fetchPriority - }; -} -const ImageElement = /*#__PURE__*/ (0, _react.forwardRef)((param, forwardedRef)=>{ - let { imgAttributes , heightInt , widthInt , qualityInt , className , imgStyle , blurStyle , isLazy , fetchPriority , fill , placeholder , loading , srcString , config , unoptimized , loader , onLoadRef , onLoadingCompleteRef , setBlurComplete , setShowAltText , onLoad , onError , ...rest } = param; - loading = isLazy ? "lazy" : loading; - return /*#__PURE__*/ _react.default.createElement("img", { - ...rest, - ...getDynamicProps(fetchPriority), - loading: loading, - width: widthInt, - height: heightInt, - decoding: "async", - "data-nimg": fill ? "fill" : "1", - className: className, - style: { - ...imgStyle, - ...blurStyle - }, - ...imgAttributes, - ref: (0, _react.useCallback)((img)=>{ - if (forwardedRef) { - if (typeof forwardedRef === "function") forwardedRef(img); - else if (typeof forwardedRef === "object") { - // @ts-ignore - .current is read only it's usually assigned by react internally - forwardedRef.current = img; - } - } - if (!img) { - return; - } - if (onError) { - // If the image has an error before react hydrates, then the error is lost. - // The workaround is to wait until the image is mounted which is after hydration, - // then we set the src again to trigger the error handler (if there was an error). - // eslint-disable-next-line no-self-assign - img.src = img.src; - } - if (false) {} - if (img.complete) { - handleLoading(img, srcString, placeholder, onLoadRef, onLoadingCompleteRef, setBlurComplete, unoptimized); - } - }, [ - srcString, - placeholder, - onLoadRef, - onLoadingCompleteRef, - setBlurComplete, - onError, - unoptimized, - forwardedRef - ]), - onLoad: (event)=>{ - const img = event.currentTarget; - handleLoading(img, srcString, placeholder, onLoadRef, onLoadingCompleteRef, setBlurComplete, unoptimized); - }, - onError: (event)=>{ - // if the real image fails to load, this will ensure "alt" is visible - setShowAltText(true); - if (placeholder === "blur") { - // If the real image fails to load, this will still remove the placeholder. - setBlurComplete(true); - } - if (onError) { - onError(event); - } - } - }); -}); -const Image = /*#__PURE__*/ (0, _react.forwardRef)((param, forwardedRef)=>{ - let { src , sizes , unoptimized =false , priority =false , loading , className , quality , width , height , fill , style , onLoad , onLoadingComplete , placeholder ="empty" , blurDataURL , fetchPriority , layout , objectFit , objectPosition , lazyBoundary , lazyRoot , ...all } = param; - const configContext = (0, _react.useContext)(_imageconfigcontext.ImageConfigContext); - const config = (0, _react.useMemo)(()=>{ - const c = configEnv || configContext || _imageconfig.imageConfigDefault; - const allSizes = [ - ...c.deviceSizes, - ...c.imageSizes - ].sort((a, b)=>a - b); - const deviceSizes = c.deviceSizes.sort((a, b)=>a - b); - return { - ...c, - allSizes, - deviceSizes - }; - }, [ - configContext - ]); - let rest = all; - let loader = rest.loader || _imageloader.default; - // Remove property so it's not spread on element - delete rest.loader; - // This special value indicates that the user - // didn't define a "loader" prop or "loader" config. - const isDefaultLoader = "__next_img_default" in loader; - if (isDefaultLoader) { - if (config.loader === "custom") { - throw new Error('Image with src "' + src + '" is missing "loader" prop.' + "\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader"); - } - } else { - // The user defined a "loader" prop or config. - // Since the config object is internal only, we - // must not pass it to the user-defined "loader". - const customImageLoader = loader; - loader = (obj)=>{ - const { config: _ , ...opts } = obj; - return customImageLoader(opts); - }; - } - if (layout) { - if (layout === "fill") { - fill = true; - } - const layoutToStyle = { - intrinsic: { - maxWidth: "100%", - height: "auto" - }, - responsive: { - width: "100%", - height: "auto" - } - }; - const layoutToSizes = { - responsive: "100vw", - fill: "100vw" - }; - const layoutStyle = layoutToStyle[layout]; - if (layoutStyle) { - style = { - ...style, - ...layoutStyle - }; - } - const layoutSizes = layoutToSizes[layout]; - if (layoutSizes && !sizes) { - sizes = layoutSizes; - } - } - let staticSrc = ""; - let widthInt = getInt(width); - let heightInt = getInt(height); - let blurWidth; - let blurHeight; - if (isStaticImport(src)) { - const staticImageData = isStaticRequire(src) ? src.default : src; - if (!staticImageData.src) { - throw new Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received " + JSON.stringify(staticImageData)); - } - if (!staticImageData.height || !staticImageData.width) { - throw new Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received " + JSON.stringify(staticImageData)); - } - blurWidth = staticImageData.blurWidth; - blurHeight = staticImageData.blurHeight; - blurDataURL = blurDataURL || staticImageData.blurDataURL; - staticSrc = staticImageData.src; - if (!fill) { - if (!widthInt && !heightInt) { - widthInt = staticImageData.width; - heightInt = staticImageData.height; - } else if (widthInt && !heightInt) { - const ratio = widthInt / staticImageData.width; - heightInt = Math.round(staticImageData.height * ratio); - } else if (!widthInt && heightInt) { - const ratio = heightInt / staticImageData.height; - widthInt = Math.round(staticImageData.width * ratio); - } - } - } - src = typeof src === "string" ? src : staticSrc; - let isLazy = !priority && (loading === "lazy" || typeof loading === "undefined"); - if (!src || src.startsWith("data:") || src.startsWith("blob:")) { - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs - unoptimized = true; - isLazy = false; - } - if (config.unoptimized) { - unoptimized = true; - } - if (isDefaultLoader && src.endsWith(".svg") && !config.dangerouslyAllowSVG) { - // Special case to make svg serve as-is to avoid proxying - // through the built-in Image Optimization API. - unoptimized = true; - } - if (priority) { - fetchPriority = "high"; - } - const [blurComplete, setBlurComplete] = (0, _react.useState)(false); - const [showAltText, setShowAltText] = (0, _react.useState)(false); - const qualityInt = getInt(quality); - if (false) {} - const imgStyle = Object.assign(fill ? { - position: "absolute", - height: "100%", - width: "100%", - left: 0, - top: 0, - right: 0, - bottom: 0, - objectFit, - objectPosition - } : {}, showAltText ? {} : { - color: "transparent" - }, style); - const blurStyle = placeholder === "blur" && blurDataURL && !blurComplete ? { - backgroundSize: imgStyle.objectFit || "cover", - backgroundPosition: imgStyle.objectPosition || "50% 50%", - backgroundRepeat: "no-repeat", - backgroundImage: 'url("data:image/svg+xml;charset=utf-8,' + (0, _imageblursvg.getImageBlurSvg)({ - widthInt, - heightInt, - blurWidth, - blurHeight, - blurDataURL, - objectFit: imgStyle.objectFit - }) + '")' - } : {}; - if (false) {} - const imgAttributes = generateImgAttrs({ - config, - src, - unoptimized, - width: widthInt, - quality: qualityInt, - sizes, - loader - }); - let srcString = src; - if (false) {} - const onLoadRef = (0, _react.useRef)(onLoad); - (0, _react.useEffect)(()=>{ - onLoadRef.current = onLoad; - }, [ - onLoad - ]); - const onLoadingCompleteRef = (0, _react.useRef)(onLoadingComplete); - (0, _react.useEffect)(()=>{ - onLoadingCompleteRef.current = onLoadingComplete; - }, [ - onLoadingComplete - ]); - const imgElementArgs = { - isLazy, - imgAttributes, - heightInt, - widthInt, - qualityInt, - className, - imgStyle, - blurStyle, - loading, - config, - fetchPriority, - fill, - unoptimized, - placeholder, - loader, - srcString, - onLoadRef, - onLoadingCompleteRef, - setBlurComplete, - setShowAltText, - ...rest - }; - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(ImageElement, { - ...imgElementArgs, - ref: forwardedRef - }), priority ? // for browsers that do not support `imagesrcset`, and in those cases - // it would likely cause the incorrect image to be preloaded. - // - // https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesrcset - /*#__PURE__*/ _react.default.createElement(_head.default, null, /*#__PURE__*/ _react.default.createElement("link", { - key: "__nimg-" + imgAttributes.src + imgAttributes.srcSet + imgAttributes.sizes, - rel: "preload", - as: "image", - href: imgAttributes.srcSet ? undefined : imgAttributes.src, - imageSrcSet: imgAttributes.srcSet, - imageSizes: imgAttributes.sizes, - crossOrigin: rest.crossOrigin, - referrerPolicy: rest.referrerPolicy, - ...getDynamicProps(fetchPriority) - })) : null); -}); -const _default = Image; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=image.js.map - - -/***/ }), - -/***/ 9040: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - defaultHead: function() { - return defaultHead; - }, - default: function() { - return _default; - } -}); -const _interop_require_default = __webpack_require__(5967); -const _interop_require_wildcard = __webpack_require__(1113); -const _react = /*#__PURE__*/ _interop_require_wildcard._(__webpack_require__(8038)); -const _sideeffect = /*#__PURE__*/ _interop_require_default._(__webpack_require__(2470)); -const _ampcontext = __webpack_require__(3918); -const _headmanagercontext = __webpack_require__(2796); -const _ampmode = __webpack_require__(5732); -const _warnonce = __webpack_require__(618); -function defaultHead(inAmpMode) { - if (inAmpMode === void 0) inAmpMode = false; - const head = [ - /*#__PURE__*/ _react.default.createElement("meta", { - charSet: "utf-8" - }) - ]; - if (!inAmpMode) { - head.push(/*#__PURE__*/ _react.default.createElement("meta", { - name: "viewport", - content: "width=device-width" - })); - } - return head; -} -function onlyReactElement(list, child) { - // React children can be "string" or "number" in this case we ignore them for backwards compat - if (typeof child === "string" || typeof child === "number") { - return list; - } - // Adds support for React.Fragment - if (child.type === _react.default.Fragment) { - return list.concat(_react.default.Children.toArray(child.props.children).reduce((fragmentList, fragmentChild)=>{ - if (typeof fragmentChild === "string" || typeof fragmentChild === "number") { - return fragmentList; - } - return fragmentList.concat(fragmentChild); - }, [])); - } - return list.concat(child); -} -const METATYPES = [ - "name", - "httpEquiv", - "charSet", - "itemProp" -]; -/* - returns a function for filtering head child elements - which shouldn't be duplicated, like - Also adds support for deduplicated `key` properties -*/ function unique() { - const keys = new Set(); - const tags = new Set(); - const metaTypes = new Set(); - const metaCategories = {}; - return (h)=>{ - let isUnique = true; - let hasKey = false; - if (h.key && typeof h.key !== "number" && h.key.indexOf("$") > 0) { - hasKey = true; - const key = h.key.slice(h.key.indexOf("$") + 1); - if (keys.has(key)) { - isUnique = false; - } else { - keys.add(key); - } - } - // eslint-disable-next-line default-case - switch(h.type){ - case "title": - case "base": - if (tags.has(h.type)) { - isUnique = false; - } else { - tags.add(h.type); - } - break; - case "meta": - for(let i = 0, len = METATYPES.length; i < len; i++){ - const metatype = METATYPES[i]; - if (!h.props.hasOwnProperty(metatype)) continue; - if (metatype === "charSet") { - if (metaTypes.has(metatype)) { - isUnique = false; - } else { - metaTypes.add(metatype); - } - } else { - const category = h.props[metatype]; - const categories = metaCategories[metatype] || new Set(); - if ((metatype !== "name" || !hasKey) && categories.has(category)) { - isUnique = false; - } else { - categories.add(category); - metaCategories[metatype] = categories; - } - } - } - break; - } - return isUnique; - }; -} -/** - * - * @param headChildrenElements List of children of <Head> - */ function reduceComponents(headChildrenElements, props) { - const { inAmpMode } = props; - return headChildrenElements.reduce(onlyReactElement, []).reverse().concat(defaultHead(inAmpMode).reverse()).filter(unique()).reverse().map((c, i)=>{ - const key = c.key || i; - if ( true && !inAmpMode) { - if (c.type === "link" && c.props["href"] && // TODO(prateekbh@): Replace this with const from `constants` when the tree shaking works. - [ - "https://fonts.googleapis.com/css", - "https://use.typekit.net/" - ].some((url)=>c.props["href"].startsWith(url))) { - const newProps = { - ...c.props || {} - }; - newProps["data-href"] = newProps["href"]; - newProps["href"] = undefined; - // Add this attribute to make it easy to identify optimized tags - newProps["data-optimized-fonts"] = true; - return /*#__PURE__*/ _react.default.cloneElement(c, newProps); - } - } - if (false) {} - return /*#__PURE__*/ _react.default.cloneElement(c, { - key - }); - }); -} -/** - * This component injects elements to `<head>` of your page. - * To avoid duplicated `tags` in `<head>` you can use the `key` property, which will make sure every tag is only rendered once. - */ function Head(param) { - let { children } = param; - const ampState = (0, _react.useContext)(_ampcontext.AmpStateContext); - const headManager = (0, _react.useContext)(_headmanagercontext.HeadManagerContext); - return /*#__PURE__*/ _react.default.createElement(_sideeffect.default, { - reduceComponentsToState: reduceComponents, - headManager: headManager, - inAmpMode: (0, _ampmode.isInAmpMode)(ampState) - }, children); -} -const _default = Head; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=head.js.map - - -/***/ }), - -/***/ 8421: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -module.exports = __webpack_require__(7649) - - -/***/ }) - -}; -; \ No newline at end of file diff --git a/.next/server/chunks/572.js b/.next/server/chunks/572.js deleted file mode 100644 index 0010045..0000000 --- a/.next/server/chunks/572.js +++ /dev/null @@ -1,5338 +0,0 @@ -"use strict"; -exports.id = 572; -exports.ids = [572]; -exports.modules = { - -/***/ 3724: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - prefixes: function() { - return prefixes; - }, - wait: function() { - return wait; - }, - error: function() { - return error; - }, - warn: function() { - return warn; - }, - ready: function() { - return ready; - }, - info: function() { - return info; - }, - event: function() { - return event; - }, - trace: function() { - return trace; - }, - warnOnce: function() { - return warnOnce; - } -}); -const _chalk = /*#__PURE__*/ _interop_require_default(__webpack_require__(3942)); -function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} -const prefixes = { - wait: "- " + _chalk.default.cyan("wait"), - error: "- " + _chalk.default.red("error"), - warn: "- " + _chalk.default.yellow("warn"), - ready: "- " + _chalk.default.green("ready"), - info: "- " + _chalk.default.cyan("info"), - event: "- " + _chalk.default.magenta("event"), - trace: "- " + _chalk.default.magenta("trace") -}; -function wait(...message) { - console.log(prefixes.wait, ...message); -} -function error(...message) { - console.error(prefixes.error, ...message); -} -function warn(...message) { - console.warn(prefixes.warn, ...message); -} -function ready(...message) { - console.log(prefixes.ready, ...message); -} -function info(...message) { - console.log(prefixes.info, ...message); -} -function event(...message) { - console.log(prefixes.event, ...message); -} -function trace(...message) { - console.log(prefixes.trace, ...message); -} -const warnOnceMessages = new Set(); -function warnOnce(...message) { - if (!warnOnceMessages.has(message[0])) { - warnOnceMessages.add(message.join(" ")); - warn(...message); - } -} //# sourceMappingURL=log.js.map - - -/***/ }), - -/***/ 42: -/***/ ((module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - RSC: function() { - return RSC; - }, - ACTION: function() { - return ACTION; - }, - NEXT_ROUTER_STATE_TREE: function() { - return NEXT_ROUTER_STATE_TREE; - }, - NEXT_ROUTER_PREFETCH: function() { - return NEXT_ROUTER_PREFETCH; - }, - NEXT_URL: function() { - return NEXT_URL; - }, - FETCH_CACHE_HEADER: function() { - return FETCH_CACHE_HEADER; - }, - RSC_CONTENT_TYPE_HEADER: function() { - return RSC_CONTENT_TYPE_HEADER; - }, - RSC_VARY_HEADER: function() { - return RSC_VARY_HEADER; - }, - FLIGHT_PARAMETERS: function() { - return FLIGHT_PARAMETERS; - } -}); -const RSC = "RSC"; -const ACTION = "Next-Action"; -const NEXT_ROUTER_STATE_TREE = "Next-Router-State-Tree"; -const NEXT_ROUTER_PREFETCH = "Next-Router-Prefetch"; -const NEXT_URL = "Next-Url"; -const FETCH_CACHE_HEADER = "x-vercel-sc-headers"; -const RSC_CONTENT_TYPE_HEADER = "text/x-component; charset=utf-8"; -const RSC_VARY_HEADER = RSC + ", " + NEXT_ROUTER_STATE_TREE + ", " + NEXT_ROUTER_PREFETCH; -const FLIGHT_PARAMETERS = [ - [ - RSC - ], - [ - NEXT_ROUTER_STATE_TREE - ], - [ - NEXT_ROUTER_PREFETCH - ] -]; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=app-router-headers.js.map - - -/***/ }), - -/***/ 1875: -/***/ ((module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "DraftMode", ({ - enumerable: true, - get: function() { - return DraftMode; - } -})); -const _staticgenerationbailout = __webpack_require__(5486); -class DraftMode { - get isEnabled() { - return this._provider.isEnabled; - } - enable() { - if ((0, _staticgenerationbailout.staticGenerationBailout)("draftMode().enable()")) { - return; - } - return this._provider.enable(); - } - disable() { - if ((0, _staticgenerationbailout.staticGenerationBailout)("draftMode().disable()")) { - return; - } - return this._provider.disable(); - } - constructor(provider){ - this._provider = provider; - } -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=draft-mode.js.map - - -/***/ }), - -/***/ 3851: -/***/ ((module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - headers: function() { - return headers; - }, - cookies: function() { - return cookies; - }, - draftMode: function() { - return draftMode; - } -}); -const _requestcookies = __webpack_require__(8661); -const _headers = __webpack_require__(7304); -const _cookies = __webpack_require__(4521); -const _requestasyncstorage = __webpack_require__(4437); -const _actionasyncstorage = __webpack_require__(6127); -const _staticgenerationbailout = __webpack_require__(5486); -const _draftmode = __webpack_require__(1875); -function headers() { - if ((0, _staticgenerationbailout.staticGenerationBailout)("headers")) { - return _headers.HeadersAdapter.seal(new Headers({})); - } - const requestStore = _requestasyncstorage.requestAsyncStorage.getStore(); - if (!requestStore) { - throw new Error("Invariant: Method expects to have requestAsyncStorage, none available"); - } - return requestStore.headers; -} -function cookies() { - if ((0, _staticgenerationbailout.staticGenerationBailout)("cookies")) { - return _requestcookies.RequestCookiesAdapter.seal(new _cookies.RequestCookies(new Headers({}))); - } - const requestStore = _requestasyncstorage.requestAsyncStorage.getStore(); - if (!requestStore) { - throw new Error("Invariant: Method expects to have requestAsyncStorage, none available"); - } - const asyncActionStore = _actionasyncstorage.actionAsyncStorage.getStore(); - if (asyncActionStore && (asyncActionStore.isAction || asyncActionStore.isAppRoute)) { - // We can't conditionally return different types here based on the context. - // To avoid confusion, we always return the readonly type here. - return requestStore.mutableCookies; - } - return requestStore.cookies; -} -function draftMode() { - const requestStore = _requestasyncstorage.requestAsyncStorage.getStore(); - if (!requestStore) { - throw new Error("Invariant: Method expects to have requestAsyncStorage, none available"); - } - return new _draftmode.DraftMode(requestStore.draftMode); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=headers.js.map - - -/***/ }), - -/***/ 4399: -/***/ ((module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - notFound: function() { - return notFound; - }, - isNotFoundError: function() { - return isNotFoundError; - } -}); -const NOT_FOUND_ERROR_CODE = "NEXT_NOT_FOUND"; -function notFound() { - // eslint-disable-next-line no-throw-literal - const error = new Error(NOT_FOUND_ERROR_CODE); - error.digest = NOT_FOUND_ERROR_CODE; - throw error; -} -function isNotFoundError(error) { - return (error == null ? void 0 : error.digest) === NOT_FOUND_ERROR_CODE; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=not-found.js.map - - -/***/ }), - -/***/ 6552: -/***/ ((module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - RedirectType: function() { - return RedirectType; - }, - getRedirectError: function() { - return getRedirectError; - }, - redirect: function() { - return redirect; - }, - isRedirectError: function() { - return isRedirectError; - }, - getURLFromRedirectError: function() { - return getURLFromRedirectError; - }, - getRedirectTypeFromError: function() { - return getRedirectTypeFromError; - } -}); -const _requestasyncstorage = __webpack_require__(4437); -const REDIRECT_ERROR_CODE = "NEXT_REDIRECT"; -var RedirectType; -(function(RedirectType) { - RedirectType["push"] = "push"; - RedirectType["replace"] = "replace"; -})(RedirectType || (RedirectType = {})); -function getRedirectError(url, type) { - const error = new Error(REDIRECT_ERROR_CODE); - error.digest = REDIRECT_ERROR_CODE + ";" + type + ";" + url; - const requestStore = _requestasyncstorage.requestAsyncStorage.getStore(); - if (requestStore) { - error.mutableCookies = requestStore.mutableCookies; - } - return error; -} -function redirect(url, type) { - if (type === void 0) type = "replace"; - throw getRedirectError(url, type); -} -function isRedirectError(error) { - if (typeof (error == null ? void 0 : error.digest) !== "string") return false; - const [errorCode, type, destination] = error.digest.split(";", 3); - return errorCode === REDIRECT_ERROR_CODE && (type === "replace" || type === "push") && typeof destination === "string"; -} -function getURLFromRedirectError(error) { - if (!isRedirectError(error)) return null; - // Slices off the beginning of the digest that contains the code and the - // separating ';'. - return error.digest.split(";", 3)[2]; -} -function getRedirectTypeFromError(error) { - if (!isRedirectError(error)) { - throw new Error("Not a redirect error"); - } - return error.digest.split(";", 3)[1]; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=redirect.js.map - - -/***/ }), - -/***/ 2962: -/***/ ((module) => { - - -(()=>{ - "use strict"; - var e = { - 339: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.ContextAPI = void 0; - const n = r(44); - const a = r(38); - const o = r(741); - const i = "context"; - const c = new n.NoopContextManager; - class ContextAPI { - constructor(){} - static getInstance() { - if (!this._instance) { - this._instance = new ContextAPI; - } - return this._instance; - } - setGlobalContextManager(e) { - return (0, a.registerGlobal)(i, e, o.DiagAPI.instance()); - } - active() { - return this._getContextManager().active(); - } - with(e, t, r, ...n) { - return this._getContextManager().with(e, t, r, ...n); - } - bind(e, t) { - return this._getContextManager().bind(e, t); - } - _getContextManager() { - return (0, a.getGlobal)(i) || c; - } - disable() { - this._getContextManager().disable(); - (0, a.unregisterGlobal)(i, o.DiagAPI.instance()); - } - } - t.ContextAPI = ContextAPI; - }, - 741: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.DiagAPI = void 0; - const n = r(144); - const a = r(871); - const o = r(133); - const i = r(38); - const c = "diag"; - class DiagAPI { - constructor(){ - function _logProxy(e) { - return function(...t) { - const r = (0, i.getGlobal)("diag"); - if (!r) return; - return r[e](...t); - }; - } - const e = this; - const setLogger = (t, r = { - logLevel: o.DiagLogLevel.INFO - })=>{ - var n, c, s; - if (t === e) { - const t = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); - e.error((n = t.stack) !== null && n !== void 0 ? n : t.message); - return false; - } - if (typeof r === "number") { - r = { - logLevel: r - }; - } - const u = (0, i.getGlobal)("diag"); - const l = (0, a.createLogLevelDiagLogger)((c = r.logLevel) !== null && c !== void 0 ? c : o.DiagLogLevel.INFO, t); - if (u && !r.suppressOverrideMessage) { - const e = (s = (new Error).stack) !== null && s !== void 0 ? s : "<failed to generate stacktrace>"; - u.warn(`Current logger will be overwritten from ${e}`); - l.warn(`Current logger will overwrite one already registered from ${e}`); - } - return (0, i.registerGlobal)("diag", l, e, true); - }; - e.setLogger = setLogger; - e.disable = ()=>{ - (0, i.unregisterGlobal)(c, e); - }; - e.createComponentLogger = (e)=>new n.DiagComponentLogger(e); - e.verbose = _logProxy("verbose"); - e.debug = _logProxy("debug"); - e.info = _logProxy("info"); - e.warn = _logProxy("warn"); - e.error = _logProxy("error"); - } - static instance() { - if (!this._instance) { - this._instance = new DiagAPI; - } - return this._instance; - } - } - t.DiagAPI = DiagAPI; - }, - 128: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.MetricsAPI = void 0; - const n = r(333); - const a = r(38); - const o = r(741); - const i = "metrics"; - class MetricsAPI { - constructor(){} - static getInstance() { - if (!this._instance) { - this._instance = new MetricsAPI; - } - return this._instance; - } - setGlobalMeterProvider(e) { - return (0, a.registerGlobal)(i, e, o.DiagAPI.instance()); - } - getMeterProvider() { - return (0, a.getGlobal)(i) || n.NOOP_METER_PROVIDER; - } - getMeter(e, t, r) { - return this.getMeterProvider().getMeter(e, t, r); - } - disable() { - (0, a.unregisterGlobal)(i, o.DiagAPI.instance()); - } - } - t.MetricsAPI = MetricsAPI; - }, - 930: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.PropagationAPI = void 0; - const n = r(38); - const a = r(600); - const o = r(625); - const i = r(377); - const c = r(701); - const s = r(741); - const u = "propagation"; - const l = new a.NoopTextMapPropagator; - class PropagationAPI { - constructor(){ - this.createBaggage = c.createBaggage; - this.getBaggage = i.getBaggage; - this.getActiveBaggage = i.getActiveBaggage; - this.setBaggage = i.setBaggage; - this.deleteBaggage = i.deleteBaggage; - } - static getInstance() { - if (!this._instance) { - this._instance = new PropagationAPI; - } - return this._instance; - } - setGlobalPropagator(e) { - return (0, n.registerGlobal)(u, e, s.DiagAPI.instance()); - } - inject(e, t, r = o.defaultTextMapSetter) { - return this._getGlobalPropagator().inject(e, t, r); - } - extract(e, t, r = o.defaultTextMapGetter) { - return this._getGlobalPropagator().extract(e, t, r); - } - fields() { - return this._getGlobalPropagator().fields(); - } - disable() { - (0, n.unregisterGlobal)(u, s.DiagAPI.instance()); - } - _getGlobalPropagator() { - return (0, n.getGlobal)(u) || l; - } - } - t.PropagationAPI = PropagationAPI; - }, - 967: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.TraceAPI = void 0; - const n = r(38); - const a = r(414); - const o = r(994); - const i = r(542); - const c = r(741); - const s = "trace"; - class TraceAPI { - constructor(){ - this._proxyTracerProvider = new a.ProxyTracerProvider; - this.wrapSpanContext = o.wrapSpanContext; - this.isSpanContextValid = o.isSpanContextValid; - this.deleteSpan = i.deleteSpan; - this.getSpan = i.getSpan; - this.getActiveSpan = i.getActiveSpan; - this.getSpanContext = i.getSpanContext; - this.setSpan = i.setSpan; - this.setSpanContext = i.setSpanContext; - } - static getInstance() { - if (!this._instance) { - this._instance = new TraceAPI; - } - return this._instance; - } - setGlobalTracerProvider(e) { - const t = (0, n.registerGlobal)(s, this._proxyTracerProvider, c.DiagAPI.instance()); - if (t) { - this._proxyTracerProvider.setDelegate(e); - } - return t; - } - getTracerProvider() { - return (0, n.getGlobal)(s) || this._proxyTracerProvider; - } - getTracer(e, t) { - return this.getTracerProvider().getTracer(e, t); - } - disable() { - (0, n.unregisterGlobal)(s, c.DiagAPI.instance()); - this._proxyTracerProvider = new a.ProxyTracerProvider; - } - } - t.TraceAPI = TraceAPI; - }, - 377: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.deleteBaggage = t.setBaggage = t.getActiveBaggage = t.getBaggage = void 0; - const n = r(339); - const a = r(421); - const o = (0, a.createContextKey)("OpenTelemetry Baggage Key"); - function getBaggage(e) { - return e.getValue(o) || undefined; - } - t.getBaggage = getBaggage; - function getActiveBaggage() { - return getBaggage(n.ContextAPI.getInstance().active()); - } - t.getActiveBaggage = getActiveBaggage; - function setBaggage(e, t) { - return e.setValue(o, t); - } - t.setBaggage = setBaggage; - function deleteBaggage(e) { - return e.deleteValue(o); - } - t.deleteBaggage = deleteBaggage; - }, - 496: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.BaggageImpl = void 0; - class BaggageImpl { - constructor(e){ - this._entries = e ? new Map(e) : new Map; - } - getEntry(e) { - const t = this._entries.get(e); - if (!t) { - return undefined; - } - return Object.assign({}, t); - } - getAllEntries() { - return Array.from(this._entries.entries()).map(([e, t])=>[ - e, - t - ]); - } - setEntry(e, t) { - const r = new BaggageImpl(this._entries); - r._entries.set(e, t); - return r; - } - removeEntry(e) { - const t = new BaggageImpl(this._entries); - t._entries.delete(e); - return t; - } - removeEntries(...e) { - const t = new BaggageImpl(this._entries); - for (const r of e){ - t._entries.delete(r); - } - return t; - } - clear() { - return new BaggageImpl; - } - } - t.BaggageImpl = BaggageImpl; - }, - 817: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.baggageEntryMetadataSymbol = void 0; - t.baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata"); - }, - 701: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.baggageEntryMetadataFromString = t.createBaggage = void 0; - const n = r(741); - const a = r(496); - const o = r(817); - const i = n.DiagAPI.instance(); - function createBaggage(e = {}) { - return new a.BaggageImpl(new Map(Object.entries(e))); - } - t.createBaggage = createBaggage; - function baggageEntryMetadataFromString(e) { - if (typeof e !== "string") { - i.error(`Cannot create baggage metadata from unknown type: ${typeof e}`); - e = ""; - } - return { - __TYPE__: o.baggageEntryMetadataSymbol, - toString () { - return e; - } - }; - } - t.baggageEntryMetadataFromString = baggageEntryMetadataFromString; - }, - 388: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.context = void 0; - const n = r(339); - t.context = n.ContextAPI.getInstance(); - }, - 44: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.NoopContextManager = void 0; - const n = r(421); - class NoopContextManager { - active() { - return n.ROOT_CONTEXT; - } - with(e, t, r, ...n) { - return t.call(r, ...n); - } - bind(e, t) { - return t; - } - enable() { - return this; - } - disable() { - return this; - } - } - t.NoopContextManager = NoopContextManager; - }, - 421: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.ROOT_CONTEXT = t.createContextKey = void 0; - function createContextKey(e) { - return Symbol.for(e); - } - t.createContextKey = createContextKey; - class BaseContext { - constructor(e){ - const t = this; - t._currentContext = e ? new Map(e) : new Map; - t.getValue = (e)=>t._currentContext.get(e); - t.setValue = (e, r)=>{ - const n = new BaseContext(t._currentContext); - n._currentContext.set(e, r); - return n; - }; - t.deleteValue = (e)=>{ - const r = new BaseContext(t._currentContext); - r._currentContext.delete(e); - return r; - }; - } - } - t.ROOT_CONTEXT = new BaseContext; - }, - 920: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.diag = void 0; - const n = r(741); - t.diag = n.DiagAPI.instance(); - }, - 144: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.DiagComponentLogger = void 0; - const n = r(38); - class DiagComponentLogger { - constructor(e){ - this._namespace = e.namespace || "DiagComponentLogger"; - } - debug(...e) { - return logProxy("debug", this._namespace, e); - } - error(...e) { - return logProxy("error", this._namespace, e); - } - info(...e) { - return logProxy("info", this._namespace, e); - } - warn(...e) { - return logProxy("warn", this._namespace, e); - } - verbose(...e) { - return logProxy("verbose", this._namespace, e); - } - } - t.DiagComponentLogger = DiagComponentLogger; - function logProxy(e, t, r) { - const a = (0, n.getGlobal)("diag"); - if (!a) { - return; - } - r.unshift(t); - return a[e](...r); - } - }, - 689: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.DiagConsoleLogger = void 0; - const r = [ - { - n: "error", - c: "error" - }, - { - n: "warn", - c: "warn" - }, - { - n: "info", - c: "info" - }, - { - n: "debug", - c: "debug" - }, - { - n: "verbose", - c: "trace" - } - ]; - class DiagConsoleLogger { - constructor(){ - function _consoleFunc(e) { - return function(...t) { - if (console) { - let r = console[e]; - if (typeof r !== "function") { - r = console.log; - } - if (typeof r === "function") { - return r.apply(console, t); - } - } - }; - } - for(let e = 0; e < r.length; e++){ - this[r[e].n] = _consoleFunc(r[e].c); - } - } - } - t.DiagConsoleLogger = DiagConsoleLogger; - }, - 871: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.createLogLevelDiagLogger = void 0; - const n = r(133); - function createLogLevelDiagLogger(e, t) { - if (e < n.DiagLogLevel.NONE) { - e = n.DiagLogLevel.NONE; - } else if (e > n.DiagLogLevel.ALL) { - e = n.DiagLogLevel.ALL; - } - t = t || {}; - function _filterFunc(r, n) { - const a = t[r]; - if (typeof a === "function" && e >= n) { - return a.bind(t); - } - return function() {}; - } - return { - error: _filterFunc("error", n.DiagLogLevel.ERROR), - warn: _filterFunc("warn", n.DiagLogLevel.WARN), - info: _filterFunc("info", n.DiagLogLevel.INFO), - debug: _filterFunc("debug", n.DiagLogLevel.DEBUG), - verbose: _filterFunc("verbose", n.DiagLogLevel.VERBOSE) - }; - } - t.createLogLevelDiagLogger = createLogLevelDiagLogger; - }, - 133: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.DiagLogLevel = void 0; - var r; - (function(e) { - e[e["NONE"] = 0] = "NONE"; - e[e["ERROR"] = 30] = "ERROR"; - e[e["WARN"] = 50] = "WARN"; - e[e["INFO"] = 60] = "INFO"; - e[e["DEBUG"] = 70] = "DEBUG"; - e[e["VERBOSE"] = 80] = "VERBOSE"; - e[e["ALL"] = 9999] = "ALL"; - })(r = t.DiagLogLevel || (t.DiagLogLevel = {})); - }, - 38: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.unregisterGlobal = t.getGlobal = t.registerGlobal = void 0; - const n = r(966); - const a = r(520); - const o = r(565); - const i = a.VERSION.split(".")[0]; - const c = Symbol.for(`opentelemetry.js.api.${i}`); - const s = n._globalThis; - function registerGlobal(e, t, r, n = false) { - var o; - const i = s[c] = (o = s[c]) !== null && o !== void 0 ? o : { - version: a.VERSION - }; - if (!n && i[e]) { - const t = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`); - r.error(t.stack || t.message); - return false; - } - if (i.version !== a.VERSION) { - const t = new Error(`@opentelemetry/api: Registration of version v${i.version} for ${e} does not match previously registered API v${a.VERSION}`); - r.error(t.stack || t.message); - return false; - } - i[e] = t; - r.debug(`@opentelemetry/api: Registered a global for ${e} v${a.VERSION}.`); - return true; - } - t.registerGlobal = registerGlobal; - function getGlobal(e) { - var t, r; - const n = (t = s[c]) === null || t === void 0 ? void 0 : t.version; - if (!n || !(0, o.isCompatible)(n)) { - return; - } - return (r = s[c]) === null || r === void 0 ? void 0 : r[e]; - } - t.getGlobal = getGlobal; - function unregisterGlobal(e, t) { - t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${a.VERSION}.`); - const r = s[c]; - if (r) { - delete r[e]; - } - } - t.unregisterGlobal = unregisterGlobal; - }, - 565: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.isCompatible = t._makeCompatibilityCheck = void 0; - const n = r(520); - const a = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; - function _makeCompatibilityCheck(e) { - const t = new Set([ - e - ]); - const r = new Set; - const n = e.match(a); - if (!n) { - return ()=>false; - } - const o = { - major: +n[1], - minor: +n[2], - patch: +n[3], - prerelease: n[4] - }; - if (o.prerelease != null) { - return function isExactmatch(t) { - return t === e; - }; - } - function _reject(e) { - r.add(e); - return false; - } - function _accept(e) { - t.add(e); - return true; - } - return function isCompatible(e) { - if (t.has(e)) { - return true; - } - if (r.has(e)) { - return false; - } - const n = e.match(a); - if (!n) { - return _reject(e); - } - const i = { - major: +n[1], - minor: +n[2], - patch: +n[3], - prerelease: n[4] - }; - if (i.prerelease != null) { - return _reject(e); - } - if (o.major !== i.major) { - return _reject(e); - } - if (o.major === 0) { - if (o.minor === i.minor && o.patch <= i.patch) { - return _accept(e); - } - return _reject(e); - } - if (o.minor <= i.minor) { - return _accept(e); - } - return _reject(e); - }; - } - t._makeCompatibilityCheck = _makeCompatibilityCheck; - t.isCompatible = _makeCompatibilityCheck(n.VERSION); - }, - 934: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.metrics = void 0; - const n = r(128); - t.metrics = n.MetricsAPI.getInstance(); - }, - 28: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.ValueType = void 0; - var r; - (function(e) { - e[e["INT"] = 0] = "INT"; - e[e["DOUBLE"] = 1] = "DOUBLE"; - })(r = t.ValueType || (t.ValueType = {})); - }, - 962: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.createNoopMeter = t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = t.NOOP_OBSERVABLE_GAUGE_METRIC = t.NOOP_OBSERVABLE_COUNTER_METRIC = t.NOOP_UP_DOWN_COUNTER_METRIC = t.NOOP_HISTOGRAM_METRIC = t.NOOP_COUNTER_METRIC = t.NOOP_METER = t.NoopObservableUpDownCounterMetric = t.NoopObservableGaugeMetric = t.NoopObservableCounterMetric = t.NoopObservableMetric = t.NoopHistogramMetric = t.NoopUpDownCounterMetric = t.NoopCounterMetric = t.NoopMetric = t.NoopMeter = void 0; - class NoopMeter { - constructor(){} - createHistogram(e, r) { - return t.NOOP_HISTOGRAM_METRIC; - } - createCounter(e, r) { - return t.NOOP_COUNTER_METRIC; - } - createUpDownCounter(e, r) { - return t.NOOP_UP_DOWN_COUNTER_METRIC; - } - createObservableGauge(e, r) { - return t.NOOP_OBSERVABLE_GAUGE_METRIC; - } - createObservableCounter(e, r) { - return t.NOOP_OBSERVABLE_COUNTER_METRIC; - } - createObservableUpDownCounter(e, r) { - return t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; - } - addBatchObservableCallback(e, t) {} - removeBatchObservableCallback(e) {} - } - t.NoopMeter = NoopMeter; - class NoopMetric { - } - t.NoopMetric = NoopMetric; - class NoopCounterMetric extends NoopMetric { - add(e, t) {} - } - t.NoopCounterMetric = NoopCounterMetric; - class NoopUpDownCounterMetric extends NoopMetric { - add(e, t) {} - } - t.NoopUpDownCounterMetric = NoopUpDownCounterMetric; - class NoopHistogramMetric extends NoopMetric { - record(e, t) {} - } - t.NoopHistogramMetric = NoopHistogramMetric; - class NoopObservableMetric { - addCallback(e) {} - removeCallback(e) {} - } - t.NoopObservableMetric = NoopObservableMetric; - class NoopObservableCounterMetric extends NoopObservableMetric { - } - t.NoopObservableCounterMetric = NoopObservableCounterMetric; - class NoopObservableGaugeMetric extends NoopObservableMetric { - } - t.NoopObservableGaugeMetric = NoopObservableGaugeMetric; - class NoopObservableUpDownCounterMetric extends NoopObservableMetric { - } - t.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; - t.NOOP_METER = new NoopMeter; - t.NOOP_COUNTER_METRIC = new NoopCounterMetric; - t.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric; - t.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric; - t.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric; - t.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric; - t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric; - function createNoopMeter() { - return t.NOOP_METER; - } - t.createNoopMeter = createNoopMeter; - }, - 333: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.NOOP_METER_PROVIDER = t.NoopMeterProvider = void 0; - const n = r(962); - class NoopMeterProvider { - getMeter(e, t, r) { - return n.NOOP_METER; - } - } - t.NoopMeterProvider = NoopMeterProvider; - t.NOOP_METER_PROVIDER = new NoopMeterProvider; - }, - 966: function(e, t, r) { - var n = this && this.__createBinding || (Object.create ? function(e, t, r, n) { - if (n === undefined) n = r; - Object.defineProperty(e, n, { - enumerable: true, - get: function() { - return t[r]; - } - }); - } : function(e, t, r, n) { - if (n === undefined) n = r; - e[n] = t[r]; - }); - var a = this && this.__exportStar || function(e, t) { - for(var r in e)if (r !== "default" && !Object.prototype.hasOwnProperty.call(t, r)) n(t, e, r); - }; - Object.defineProperty(t, "__esModule", { - value: true - }); - a(r(652), t); - }, - 385: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t._globalThis = void 0; - t._globalThis = typeof globalThis === "object" ? globalThis : global; - }, - 652: function(e, t, r) { - var n = this && this.__createBinding || (Object.create ? function(e, t, r, n) { - if (n === undefined) n = r; - Object.defineProperty(e, n, { - enumerable: true, - get: function() { - return t[r]; - } - }); - } : function(e, t, r, n) { - if (n === undefined) n = r; - e[n] = t[r]; - }); - var a = this && this.__exportStar || function(e, t) { - for(var r in e)if (r !== "default" && !Object.prototype.hasOwnProperty.call(t, r)) n(t, e, r); - }; - Object.defineProperty(t, "__esModule", { - value: true - }); - a(r(385), t); - }, - 251: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.propagation = void 0; - const n = r(930); - t.propagation = n.PropagationAPI.getInstance(); - }, - 600: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.NoopTextMapPropagator = void 0; - class NoopTextMapPropagator { - inject(e, t) {} - extract(e, t) { - return e; - } - fields() { - return []; - } - } - t.NoopTextMapPropagator = NoopTextMapPropagator; - }, - 625: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.defaultTextMapSetter = t.defaultTextMapGetter = void 0; - t.defaultTextMapGetter = { - get (e, t) { - if (e == null) { - return undefined; - } - return e[t]; - }, - keys (e) { - if (e == null) { - return []; - } - return Object.keys(e); - } - }; - t.defaultTextMapSetter = { - set (e, t, r) { - if (e == null) { - return; - } - e[t] = r; - } - }; - }, - 978: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.trace = void 0; - const n = r(967); - t.trace = n.TraceAPI.getInstance(); - }, - 76: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.NonRecordingSpan = void 0; - const n = r(304); - class NonRecordingSpan { - constructor(e = n.INVALID_SPAN_CONTEXT){ - this._spanContext = e; - } - spanContext() { - return this._spanContext; - } - setAttribute(e, t) { - return this; - } - setAttributes(e) { - return this; - } - addEvent(e, t) { - return this; - } - setStatus(e) { - return this; - } - updateName(e) { - return this; - } - end(e) {} - isRecording() { - return false; - } - recordException(e, t) {} - } - t.NonRecordingSpan = NonRecordingSpan; - }, - 527: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.NoopTracer = void 0; - const n = r(339); - const a = r(542); - const o = r(76); - const i = r(994); - const c = n.ContextAPI.getInstance(); - class NoopTracer { - startSpan(e, t, r = c.active()) { - const n = Boolean(t === null || t === void 0 ? void 0 : t.root); - if (n) { - return new o.NonRecordingSpan; - } - const s = r && (0, a.getSpanContext)(r); - if (isSpanContext(s) && (0, i.isSpanContextValid)(s)) { - return new o.NonRecordingSpan(s); - } else { - return new o.NonRecordingSpan; - } - } - startActiveSpan(e, t, r, n) { - let o; - let i; - let s; - if (arguments.length < 2) { - return; - } else if (arguments.length === 2) { - s = t; - } else if (arguments.length === 3) { - o = t; - s = r; - } else { - o = t; - i = r; - s = n; - } - const u = i !== null && i !== void 0 ? i : c.active(); - const l = this.startSpan(e, o, u); - const g = (0, a.setSpan)(u, l); - return c.with(g, s, undefined, l); - } - } - t.NoopTracer = NoopTracer; - function isSpanContext(e) { - return typeof e === "object" && typeof e["spanId"] === "string" && typeof e["traceId"] === "string" && typeof e["traceFlags"] === "number"; - } - }, - 228: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.NoopTracerProvider = void 0; - const n = r(527); - class NoopTracerProvider { - getTracer(e, t, r) { - return new n.NoopTracer; - } - } - t.NoopTracerProvider = NoopTracerProvider; - }, - 387: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.ProxyTracer = void 0; - const n = r(527); - const a = new n.NoopTracer; - class ProxyTracer { - constructor(e, t, r, n){ - this._provider = e; - this.name = t; - this.version = r; - this.options = n; - } - startSpan(e, t, r) { - return this._getTracer().startSpan(e, t, r); - } - startActiveSpan(e, t, r, n) { - const a = this._getTracer(); - return Reflect.apply(a.startActiveSpan, a, arguments); - } - _getTracer() { - if (this._delegate) { - return this._delegate; - } - const e = this._provider.getDelegateTracer(this.name, this.version, this.options); - if (!e) { - return a; - } - this._delegate = e; - return this._delegate; - } - } - t.ProxyTracer = ProxyTracer; - }, - 414: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.ProxyTracerProvider = void 0; - const n = r(387); - const a = r(228); - const o = new a.NoopTracerProvider; - class ProxyTracerProvider { - getTracer(e, t, r) { - var a; - return (a = this.getDelegateTracer(e, t, r)) !== null && a !== void 0 ? a : new n.ProxyTracer(this, e, t, r); - } - getDelegate() { - var e; - return (e = this._delegate) !== null && e !== void 0 ? e : o; - } - setDelegate(e) { - this._delegate = e; - } - getDelegateTracer(e, t, r) { - var n; - return (n = this._delegate) === null || n === void 0 ? void 0 : n.getTracer(e, t, r); - } - } - t.ProxyTracerProvider = ProxyTracerProvider; - }, - 505: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.SamplingDecision = void 0; - var r; - (function(e) { - e[e["NOT_RECORD"] = 0] = "NOT_RECORD"; - e[e["RECORD"] = 1] = "RECORD"; - e[e["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; - })(r = t.SamplingDecision || (t.SamplingDecision = {})); - }, - 542: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.getSpanContext = t.setSpanContext = t.deleteSpan = t.setSpan = t.getActiveSpan = t.getSpan = void 0; - const n = r(421); - const a = r(76); - const o = r(339); - const i = (0, n.createContextKey)("OpenTelemetry Context Key SPAN"); - function getSpan(e) { - return e.getValue(i) || undefined; - } - t.getSpan = getSpan; - function getActiveSpan() { - return getSpan(o.ContextAPI.getInstance().active()); - } - t.getActiveSpan = getActiveSpan; - function setSpan(e, t) { - return e.setValue(i, t); - } - t.setSpan = setSpan; - function deleteSpan(e) { - return e.deleteValue(i); - } - t.deleteSpan = deleteSpan; - function setSpanContext(e, t) { - return setSpan(e, new a.NonRecordingSpan(t)); - } - t.setSpanContext = setSpanContext; - function getSpanContext(e) { - var t; - return (t = getSpan(e)) === null || t === void 0 ? void 0 : t.spanContext(); - } - t.getSpanContext = getSpanContext; - }, - 430: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.TraceStateImpl = void 0; - const n = r(450); - const a = 32; - const o = 512; - const i = ","; - const c = "="; - class TraceStateImpl { - constructor(e){ - this._internalState = new Map; - if (e) this._parse(e); - } - set(e, t) { - const r = this._clone(); - if (r._internalState.has(e)) { - r._internalState.delete(e); - } - r._internalState.set(e, t); - return r; - } - unset(e) { - const t = this._clone(); - t._internalState.delete(e); - return t; - } - get(e) { - return this._internalState.get(e); - } - serialize() { - return this._keys().reduce((e, t)=>{ - e.push(t + c + this.get(t)); - return e; - }, []).join(i); - } - _parse(e) { - if (e.length > o) return; - this._internalState = e.split(i).reverse().reduce((e, t)=>{ - const r = t.trim(); - const a = r.indexOf(c); - if (a !== -1) { - const o = r.slice(0, a); - const i = r.slice(a + 1, t.length); - if ((0, n.validateKey)(o) && (0, n.validateValue)(i)) { - e.set(o, i); - } else {} - } - return e; - }, new Map); - if (this._internalState.size > a) { - this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, a)); - } - } - _keys() { - return Array.from(this._internalState.keys()).reverse(); - } - _clone() { - const e = new TraceStateImpl; - e._internalState = new Map(this._internalState); - return e; - } - } - t.TraceStateImpl = TraceStateImpl; - }, - 450: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.validateValue = t.validateKey = void 0; - const r = "[_0-9a-z-*/]"; - const n = `[a-z]${r}{0,255}`; - const a = `[a-z0-9]${r}{0,240}@[a-z]${r}{0,13}`; - const o = new RegExp(`^(?:${n}|${a})$`); - const i = /^[ -~]{0,255}[!-~]$/; - const c = /,|=/; - function validateKey(e) { - return o.test(e); - } - t.validateKey = validateKey; - function validateValue(e) { - return i.test(e) && !c.test(e); - } - t.validateValue = validateValue; - }, - 757: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.createTraceState = void 0; - const n = r(430); - function createTraceState(e) { - return new n.TraceStateImpl(e); - } - t.createTraceState = createTraceState; - }, - 304: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.INVALID_SPAN_CONTEXT = t.INVALID_TRACEID = t.INVALID_SPANID = void 0; - const n = r(762); - t.INVALID_SPANID = "0000000000000000"; - t.INVALID_TRACEID = "00000000000000000000000000000000"; - t.INVALID_SPAN_CONTEXT = { - traceId: t.INVALID_TRACEID, - spanId: t.INVALID_SPANID, - traceFlags: n.TraceFlags.NONE - }; - }, - 902: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.SpanKind = void 0; - var r; - (function(e) { - e[e["INTERNAL"] = 0] = "INTERNAL"; - e[e["SERVER"] = 1] = "SERVER"; - e[e["CLIENT"] = 2] = "CLIENT"; - e[e["PRODUCER"] = 3] = "PRODUCER"; - e[e["CONSUMER"] = 4] = "CONSUMER"; - })(r = t.SpanKind || (t.SpanKind = {})); - }, - 994: (e, t, r)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.wrapSpanContext = t.isSpanContextValid = t.isValidSpanId = t.isValidTraceId = void 0; - const n = r(304); - const a = r(76); - const o = /^([0-9a-f]{32})$/i; - const i = /^[0-9a-f]{16}$/i; - function isValidTraceId(e) { - return o.test(e) && e !== n.INVALID_TRACEID; - } - t.isValidTraceId = isValidTraceId; - function isValidSpanId(e) { - return i.test(e) && e !== n.INVALID_SPANID; - } - t.isValidSpanId = isValidSpanId; - function isSpanContextValid(e) { - return isValidTraceId(e.traceId) && isValidSpanId(e.spanId); - } - t.isSpanContextValid = isSpanContextValid; - function wrapSpanContext(e) { - return new a.NonRecordingSpan(e); - } - t.wrapSpanContext = wrapSpanContext; - }, - 832: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.SpanStatusCode = void 0; - var r; - (function(e) { - e[e["UNSET"] = 0] = "UNSET"; - e[e["OK"] = 1] = "OK"; - e[e["ERROR"] = 2] = "ERROR"; - })(r = t.SpanStatusCode || (t.SpanStatusCode = {})); - }, - 762: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.TraceFlags = void 0; - var r; - (function(e) { - e[e["NONE"] = 0] = "NONE"; - e[e["SAMPLED"] = 1] = "SAMPLED"; - })(r = t.TraceFlags || (t.TraceFlags = {})); - }, - 520: (e, t)=>{ - Object.defineProperty(t, "__esModule", { - value: true - }); - t.VERSION = void 0; - t.VERSION = "1.4.1"; - } - }; - var t = {}; - function __nccwpck_require__(r) { - var n = t[r]; - if (n !== undefined) { - return n.exports; - } - var a = t[r] = { - exports: {} - }; - var o = true; - try { - e[r].call(a.exports, a, a.exports, __nccwpck_require__); - o = false; - } finally{ - if (o) delete t[r]; - } - return a.exports; - } - if (typeof __nccwpck_require__ !== "undefined") __nccwpck_require__.ab = __dirname + "/"; - var r = {}; - (()=>{ - var e = r; - Object.defineProperty(e, "__esModule", { - value: true - }); - e.trace = e.propagation = e.metrics = e.diag = e.context = e.INVALID_SPAN_CONTEXT = e.INVALID_TRACEID = e.INVALID_SPANID = e.isValidSpanId = e.isValidTraceId = e.isSpanContextValid = e.createTraceState = e.TraceFlags = e.SpanStatusCode = e.SpanKind = e.SamplingDecision = e.ProxyTracerProvider = e.ProxyTracer = e.defaultTextMapSetter = e.defaultTextMapGetter = e.ValueType = e.createNoopMeter = e.DiagLogLevel = e.DiagConsoleLogger = e.ROOT_CONTEXT = e.createContextKey = e.baggageEntryMetadataFromString = void 0; - var t = __nccwpck_require__(701); - Object.defineProperty(e, "baggageEntryMetadataFromString", { - enumerable: true, - get: function() { - return t.baggageEntryMetadataFromString; - } - }); - var n = __nccwpck_require__(421); - Object.defineProperty(e, "createContextKey", { - enumerable: true, - get: function() { - return n.createContextKey; - } - }); - Object.defineProperty(e, "ROOT_CONTEXT", { - enumerable: true, - get: function() { - return n.ROOT_CONTEXT; - } - }); - var a = __nccwpck_require__(689); - Object.defineProperty(e, "DiagConsoleLogger", { - enumerable: true, - get: function() { - return a.DiagConsoleLogger; - } - }); - var o = __nccwpck_require__(133); - Object.defineProperty(e, "DiagLogLevel", { - enumerable: true, - get: function() { - return o.DiagLogLevel; - } - }); - var i = __nccwpck_require__(962); - Object.defineProperty(e, "createNoopMeter", { - enumerable: true, - get: function() { - return i.createNoopMeter; - } - }); - var c = __nccwpck_require__(28); - Object.defineProperty(e, "ValueType", { - enumerable: true, - get: function() { - return c.ValueType; - } - }); - var s = __nccwpck_require__(625); - Object.defineProperty(e, "defaultTextMapGetter", { - enumerable: true, - get: function() { - return s.defaultTextMapGetter; - } - }); - Object.defineProperty(e, "defaultTextMapSetter", { - enumerable: true, - get: function() { - return s.defaultTextMapSetter; - } - }); - var u = __nccwpck_require__(387); - Object.defineProperty(e, "ProxyTracer", { - enumerable: true, - get: function() { - return u.ProxyTracer; - } - }); - var l = __nccwpck_require__(414); - Object.defineProperty(e, "ProxyTracerProvider", { - enumerable: true, - get: function() { - return l.ProxyTracerProvider; - } - }); - var g = __nccwpck_require__(505); - Object.defineProperty(e, "SamplingDecision", { - enumerable: true, - get: function() { - return g.SamplingDecision; - } - }); - var p = __nccwpck_require__(902); - Object.defineProperty(e, "SpanKind", { - enumerable: true, - get: function() { - return p.SpanKind; - } - }); - var d = __nccwpck_require__(832); - Object.defineProperty(e, "SpanStatusCode", { - enumerable: true, - get: function() { - return d.SpanStatusCode; - } - }); - var _ = __nccwpck_require__(762); - Object.defineProperty(e, "TraceFlags", { - enumerable: true, - get: function() { - return _.TraceFlags; - } - }); - var f = __nccwpck_require__(757); - Object.defineProperty(e, "createTraceState", { - enumerable: true, - get: function() { - return f.createTraceState; - } - }); - var b = __nccwpck_require__(994); - Object.defineProperty(e, "isSpanContextValid", { - enumerable: true, - get: function() { - return b.isSpanContextValid; - } - }); - Object.defineProperty(e, "isValidTraceId", { - enumerable: true, - get: function() { - return b.isValidTraceId; - } - }); - Object.defineProperty(e, "isValidSpanId", { - enumerable: true, - get: function() { - return b.isValidSpanId; - } - }); - var v = __nccwpck_require__(304); - Object.defineProperty(e, "INVALID_SPANID", { - enumerable: true, - get: function() { - return v.INVALID_SPANID; - } - }); - Object.defineProperty(e, "INVALID_TRACEID", { - enumerable: true, - get: function() { - return v.INVALID_TRACEID; - } - }); - Object.defineProperty(e, "INVALID_SPAN_CONTEXT", { - enumerable: true, - get: function() { - return v.INVALID_SPAN_CONTEXT; - } - }); - const O = __nccwpck_require__(388); - Object.defineProperty(e, "context", { - enumerable: true, - get: function() { - return O.context; - } - }); - const P = __nccwpck_require__(920); - Object.defineProperty(e, "diag", { - enumerable: true, - get: function() { - return P.diag; - } - }); - const N = __nccwpck_require__(934); - Object.defineProperty(e, "metrics", { - enumerable: true, - get: function() { - return N.metrics; - } - }); - const S = __nccwpck_require__(251); - Object.defineProperty(e, "propagation", { - enumerable: true, - get: function() { - return S.propagation; - } - }); - const C = __nccwpck_require__(978); - Object.defineProperty(e, "trace", { - enumerable: true, - get: function() { - return C.trace; - } - }); - e["default"] = { - context: O.context, - diag: P.diag, - metrics: N.metrics, - propagation: S.propagation, - trace: C.trace - }; - })(); - module.exports = r; -})(); - - -/***/ }), - -/***/ 3942: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "default", ({ - enumerable: true, - get: function() { - return _default; - } -})); -let chalk; -if (false) {} else { - chalk = __webpack_require__(4426); -} -const _default = chalk; //# sourceMappingURL=chalk.js.map - - -/***/ }), - -/***/ 9141: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - getCookieParser: function() { - return getCookieParser; - }, - sendStatusCode: function() { - return sendStatusCode; - }, - redirect: function() { - return redirect; - }, - checkIsOnDemandRevalidate: function() { - return checkIsOnDemandRevalidate; - }, - COOKIE_NAME_PRERENDER_BYPASS: function() { - return COOKIE_NAME_PRERENDER_BYPASS; - }, - COOKIE_NAME_PRERENDER_DATA: function() { - return COOKIE_NAME_PRERENDER_DATA; - }, - RESPONSE_LIMIT_DEFAULT: function() { - return RESPONSE_LIMIT_DEFAULT; - }, - SYMBOL_PREVIEW_DATA: function() { - return SYMBOL_PREVIEW_DATA; - }, - SYMBOL_CLEARED_COOKIES: function() { - return SYMBOL_CLEARED_COOKIES; - }, - clearPreviewData: function() { - return clearPreviewData; - }, - ApiError: function() { - return ApiError; - }, - sendError: function() { - return sendError; - }, - setLazyProp: function() { - return setLazyProp; - } -}); -const _headers = __webpack_require__(7304); -const _constants = __webpack_require__(8537); -function getCookieParser(headers) { - return function parseCookie() { - const { cookie } = headers; - if (!cookie) { - return {}; - } - const { parse: parseCookieFn } = __webpack_require__(252); - return parseCookieFn(Array.isArray(cookie) ? cookie.join("; ") : cookie); - }; -} -function sendStatusCode(res, statusCode) { - res.statusCode = statusCode; - return res; -} -function redirect(res, statusOrUrl, url) { - if (typeof statusOrUrl === "string") { - url = statusOrUrl; - statusOrUrl = 307; - } - if (typeof statusOrUrl !== "number" || typeof url !== "string") { - throw new Error(`Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').`); - } - res.writeHead(statusOrUrl, { - Location: url - }); - res.write(url); - res.end(); - return res; -} -function checkIsOnDemandRevalidate(req, previewProps) { - const headers = _headers.HeadersAdapter.from(req.headers); - const previewModeId = headers.get(_constants.PRERENDER_REVALIDATE_HEADER); - const isOnDemandRevalidate = previewModeId === previewProps.previewModeId; - const revalidateOnlyGenerated = headers.has(_constants.PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER); - return { - isOnDemandRevalidate, - revalidateOnlyGenerated - }; -} -const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`; -const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data`; -const RESPONSE_LIMIT_DEFAULT = 4 * 1024 * 1024; -const SYMBOL_PREVIEW_DATA = Symbol(COOKIE_NAME_PRERENDER_DATA); -const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS); -function clearPreviewData(res, options = {}) { - if (SYMBOL_CLEARED_COOKIES in res) { - return res; - } - const { serialize } = __webpack_require__(252); - const previous = res.getHeader("Set-Cookie"); - res.setHeader(`Set-Cookie`, [ - ...typeof previous === "string" ? [ - previous - ] : Array.isArray(previous) ? previous : [], - serialize(COOKIE_NAME_PRERENDER_BYPASS, "", { - // To delete a cookie, set `expires` to a date in the past: - // https://tools.ietf.org/html/rfc6265#section-4.1.1 - // `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted. - expires: new Date(0), - httpOnly: true, - sameSite: true ? "none" : 0, - secure: "production" !== "development", - path: "/", - ...options.path !== undefined ? { - path: options.path - } : undefined - }), - serialize(COOKIE_NAME_PRERENDER_DATA, "", { - // To delete a cookie, set `expires` to a date in the past: - // https://tools.ietf.org/html/rfc6265#section-4.1.1 - // `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted. - expires: new Date(0), - httpOnly: true, - sameSite: true ? "none" : 0, - secure: "production" !== "development", - path: "/", - ...options.path !== undefined ? { - path: options.path - } : undefined - }) - ]); - Object.defineProperty(res, SYMBOL_CLEARED_COOKIES, { - value: true, - enumerable: false - }); - return res; -} -class ApiError extends Error { - constructor(statusCode, message){ - super(message); - this.statusCode = statusCode; - } -} -function sendError(res, statusCode, message) { - res.statusCode = statusCode; - res.statusMessage = message; - res.end(message); -} -function setLazyProp({ req }, prop, getter) { - const opts = { - configurable: true, - enumerable: true - }; - const optsReset = { - ...opts, - writable: true - }; - Object.defineProperty(req, prop, { - ...opts, - get: ()=>{ - const value = getter(); - // we set the property on the object to avoid recalculating it - Object.defineProperty(req, prop, { - ...optsReset, - value - }); - return value; - }, - set: (value)=>{ - Object.defineProperty(req, prop, { - ...optsReset, - value - }); - } - }); -} //# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 5744: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "DraftModeProvider", ({ - enumerable: true, - get: function() { - return DraftModeProvider; - } -})); -const _apiutils = __webpack_require__(9141); -class DraftModeProvider { - constructor(previewProps, req, cookies, mutableCookies){ - var _cookies_get; - // The logic for draftMode() is very similar to tryGetPreviewData() - // but Draft Mode does not have any data associated with it. - const isOnDemandRevalidate = previewProps && (0, _apiutils.checkIsOnDemandRevalidate)(req, previewProps).isOnDemandRevalidate; - const cookieValue = (_cookies_get = cookies.get(_apiutils.COOKIE_NAME_PRERENDER_BYPASS)) == null ? void 0 : _cookies_get.value; - this.isEnabled = Boolean(!isOnDemandRevalidate && cookieValue && previewProps && cookieValue === previewProps.previewModeId); - this._previewModeId = previewProps == null ? void 0 : previewProps.previewModeId; - this._mutableCookies = mutableCookies; - } - enable() { - if (!this._previewModeId) { - throw new Error("Invariant: previewProps missing previewModeId this should never happen"); - } - this._mutableCookies.set({ - name: _apiutils.COOKIE_NAME_PRERENDER_BYPASS, - value: this._previewModeId, - httpOnly: true, - sameSite: true ? "none" : 0, - secure: "production" !== "development", - path: "/" - }); - } - disable() { - // To delete a cookie, set `expires` to a date in the past: - // https://tools.ietf.org/html/rfc6265#section-4.1.1 - // `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted. - this._mutableCookies.set({ - name: _apiutils.COOKIE_NAME_PRERENDER_BYPASS, - value: "", - httpOnly: true, - sameSite: true ? "none" : 0, - secure: "production" !== "development", - path: "/", - expires: new Date(0) - }); - } -} //# sourceMappingURL=draft-mode-provider.js.map - - -/***/ }), - -/***/ 3389: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "RequestAsyncStorageWrapper", ({ - enumerable: true, - get: function() { - return RequestAsyncStorageWrapper; - } -})); -const _approuterheaders = __webpack_require__(42); -const _headers = __webpack_require__(7304); -const _requestcookies = __webpack_require__(8661); -const _cookies = __webpack_require__(4521); -const _draftmodeprovider = __webpack_require__(5744); -function getHeaders(headers) { - const cleaned = _headers.HeadersAdapter.from(headers); - for (const param of _approuterheaders.FLIGHT_PARAMETERS){ - cleaned.delete(param.toString().toLowerCase()); - } - return _headers.HeadersAdapter.seal(cleaned); -} -function getCookies(headers) { - const cookies = new _cookies.RequestCookies(_headers.HeadersAdapter.from(headers)); - return _requestcookies.RequestCookiesAdapter.seal(cookies); -} -function getMutableCookies(headers, res) { - const cookies = new _cookies.RequestCookies(_headers.HeadersAdapter.from(headers)); - return _requestcookies.MutableRequestCookiesAdapter.wrap(cookies, res); -} -const RequestAsyncStorageWrapper = { - /** - * Wrap the callback with the given store so it can access the underlying - * store using hooks. - * - * @param storage underlying storage object returned by the module - * @param context context to seed the store - * @param callback function to call within the scope of the context - * @returns the result returned by the callback - */ wrap (storage, { req , res , renderOpts }, callback) { - let previewProps = undefined; - if (renderOpts && "previewProps" in renderOpts) { - // TODO: investigate why previewProps isn't on RenderOpts - previewProps = renderOpts.previewProps; - } - const cache = {}; - const store = { - get headers () { - if (!cache.headers) { - // Seal the headers object that'll freeze out any methods that could - // mutate the underlying data. - cache.headers = getHeaders(req.headers); - } - return cache.headers; - }, - get cookies () { - if (!cache.cookies) { - // Seal the cookies object that'll freeze out any methods that could - // mutate the underlying data. - cache.cookies = getCookies(req.headers); - } - return cache.cookies; - }, - get mutableCookies () { - if (!cache.mutableCookies) { - cache.mutableCookies = getMutableCookies(req.headers, res); - } - return cache.mutableCookies; - }, - get draftMode () { - if (!cache.draftMode) { - cache.draftMode = new _draftmodeprovider.DraftModeProvider(previewProps, req, this.cookies, this.mutableCookies); - } - return cache.draftMode; - } - }; - return storage.run(store, callback, store); - } -}; //# sourceMappingURL=request-async-storage-wrapper.js.map - - -/***/ }), - -/***/ 1482: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "StaticGenerationAsyncStorageWrapper", ({ - enumerable: true, - get: function() { - return StaticGenerationAsyncStorageWrapper; - } -})); -const StaticGenerationAsyncStorageWrapper = { - wrap (storage, { pathname , renderOpts }, callback) { - /** - * Rules of Static & Dynamic HTML: - * - * 1.) We must generate static HTML unless the caller explicitly opts - * in to dynamic HTML support. - * - * 2.) If dynamic HTML support is requested, we must honor that request - * or throw an error. It is the sole responsibility of the caller to - * ensure they aren't e.g. requesting dynamic HTML for an AMP page. - * - * These rules help ensure that other existing features like request caching, - * coalescing, and ISR continue working as intended. - */ const isStaticGeneration = !renderOpts.supportsDynamicHTML && !renderOpts.isBot; - const store = { - isStaticGeneration, - pathname, - originalPathname: renderOpts.originalPathname, - incrementalCache: // so that it can access the fs cache without mocks - renderOpts.incrementalCache || globalThis.__incrementalCache, - isRevalidate: renderOpts.isRevalidate, - isPrerendering: renderOpts.nextExport, - fetchCache: renderOpts.fetchCache, - isOnDemandRevalidate: renderOpts.isOnDemandRevalidate - }; - // TODO: remove this when we resolve accessing the store outside the execution context - renderOpts.store = store; - return storage.run(store, callback, store); - } -}; //# sourceMappingURL=static-generation-async-storage-wrapper.js.map - - -/***/ }), - -/***/ 6221: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "RouteKind", ({ - enumerable: true, - get: function() { - return RouteKind; - } -})); -var RouteKind; -(function(RouteKind) { - RouteKind[/** - * `PAGES` represents all the React pages that are under `pages/`. - */ "PAGES"] = "PAGES"; - RouteKind[/** - * `PAGES_API` represents all the API routes under `pages/api/`. - */ "PAGES_API"] = "PAGES_API"; - RouteKind[/** - * `APP_PAGE` represents all the React pages that are under `app/` with the - * filename of `page.{j,t}s{,x}`. - */ "APP_PAGE"] = "APP_PAGE"; - RouteKind[/** - * `APP_ROUTE` represents all the API routes and metadata routes that are under `app/` with the - * filename of `route.{j,t}s{,x}`. - */ "APP_ROUTE"] = "APP_ROUTE"; -})(RouteKind || (RouteKind = {})); //# sourceMappingURL=route-kind.js.map - - -/***/ }), - -/***/ 7053: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "autoImplementMethods", ({ - enumerable: true, - get: function() { - return autoImplementMethods; - } -})); -const _http = __webpack_require__(1183); -const _responsehandlers = __webpack_require__(717); -const AUTOMATIC_ROUTE_METHODS = [ - "HEAD", - "OPTIONS" -]; -function autoImplementMethods(handlers) { - // Loop through all the HTTP methods to create the initial methods object. - // Each of the methods will be set to the the 405 response handler. - const methods = _http.HTTP_METHODS.reduce((acc, method)=>({ - ...acc, - // If the userland module implements the method, then use it. Otherwise, - // use the 405 response handler. - [method]: handlers[method] ?? _responsehandlers.handleMethodNotAllowedResponse - }), {}); - // Get all the methods that could be automatically implemented that were not - // implemented by the userland module. - const implemented = new Set(_http.HTTP_METHODS.filter((method)=>handlers[method])); - const missing = AUTOMATIC_ROUTE_METHODS.filter((method)=>!implemented.has(method)); - // Loop over the missing methods to automatically implement them if we can. - for (const method of missing){ - // If the userland module doesn't implement the HEAD method, then - // we'll automatically implement it by calling the GET method (if it - // exists). - if (method === "HEAD") { - // If the userland module doesn't implement the GET method, then - // we're done. - if (!handlers.GET) break; - // Implement the HEAD method by calling the GET method. - methods.HEAD = handlers.GET; - // Mark it as implemented. - implemented.add("HEAD"); - continue; - } - // If OPTIONS is not provided then implement it. - if (method === "OPTIONS") { - // TODO: check if HEAD is implemented, if so, use it to add more headers - // Get all the methods that were implemented by the userland module. - const allow = [ - "OPTIONS", - ...implemented - ]; - // If the list of methods doesn't include HEAD, but it includes GET, then - // add HEAD as it's automatically implemented. - if (!implemented.has("HEAD") && implemented.has("GET")) { - allow.push("HEAD"); - } - // Sort and join the list with commas to create the `Allow` header. See: - // https://httpwg.org/specs/rfc9110.html#field.allow - const headers = { - Allow: allow.sort().join(", ") - }; - // Implement the OPTIONS method by returning a 204 response with the - // `Allow` header. - methods.OPTIONS = ()=>new Response(null, { - status: 204, - headers - }); - // Mark this method as implemented. - implemented.add("OPTIONS"); - continue; - } - throw new Error(`Invariant: should handle all automatic implementable methods, got method: ${method}`); - } - return methods; -} //# sourceMappingURL=auto-implement-methods.js.map - - -/***/ }), - -/***/ 8167: -/***/ ((__unused_webpack_module, exports) => { - -/** - * Cleans a URL by stripping the protocol, host, and search params. - * - * @param urlString the url to clean - * @returns the cleaned url - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "cleanURL", ({ - enumerable: true, - get: function() { - return cleanURL; - } -})); -function cleanURL(urlString) { - const url = new URL(urlString); - url.host = "localhost:3000"; - url.search = ""; - url.protocol = "http"; - return url.toString(); -} //# sourceMappingURL=clean-url.js.map - - -/***/ }), - -/***/ 3383: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "getNonStaticMethods", ({ - enumerable: true, - get: function() { - return getNonStaticMethods; - } -})); -const NON_STATIC_METHODS = [ - "OPTIONS", - "POST", - "PUT", - "DELETE", - "PATCH" -]; -function getNonStaticMethods(handlers) { - // We can currently only statically optimize if only GET/HEAD are used as - // prerender can't be used conditionally based on the method currently. - const methods = NON_STATIC_METHODS.filter((method)=>handlers[method]); - if (methods.length === 0) return false; - return methods; -} //# sourceMappingURL=get-non-static-methods.js.map - - -/***/ }), - -/***/ 2509: -/***/ ((__unused_webpack_module, exports) => { - -/** - * Get pathname from absolute path. - * - * @param absolutePath the absolute path - * @returns the pathname - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "getPathnameFromAbsolutePath", ({ - enumerable: true, - get: function() { - return getPathnameFromAbsolutePath; - } -})); -function getPathnameFromAbsolutePath(absolutePath) { - // Remove prefix including app dir - let appDir = "/app/"; - if (!absolutePath.includes(appDir)) { - appDir = "\\app\\"; - } - const [, ...parts] = absolutePath.split(appDir); - const relativePath = appDir[0] + parts.join(appDir); - // remove extension - const pathname = relativePath.split(".").slice(0, -1).join("."); - return pathname; -} //# sourceMappingURL=get-pathname-from-absolute-path.js.map - - -/***/ }), - -/***/ 1320: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "proxyRequest", ({ - enumerable: true, - get: function() { - return proxyRequest; - } -})); -const _cookies = __webpack_require__(7783); -const _nexturl = __webpack_require__(3369); -const _cleanurl = __webpack_require__(8167); -function proxyRequest(request, { dynamic }, hooks) { - function handleNextUrlBailout(prop) { - switch(prop){ - case "search": - case "searchParams": - case "toString": - case "href": - case "origin": - hooks.staticGenerationBailout(`nextUrl.${prop}`); - return; - default: - return; - } - } - const cache = {}; - const handleForceStatic = (url, prop)=>{ - switch(prop){ - case "search": - return ""; - case "searchParams": - if (!cache.searchParams) cache.searchParams = new URLSearchParams(); - return cache.searchParams; - case "url": - case "href": - if (!cache.url) cache.url = (0, _cleanurl.cleanURL)(url); - return cache.url; - case "toJSON": - case "toString": - if (!cache.url) cache.url = (0, _cleanurl.cleanURL)(url); - if (!cache.toString) cache.toString = ()=>cache.url; - return cache.toString; - case "headers": - if (!cache.headers) cache.headers = new Headers(); - return cache.headers; - case "cookies": - if (!cache.headers) cache.headers = new Headers(); - if (!cache.cookies) cache.cookies = new _cookies.RequestCookies(cache.headers); - return cache.cookies; - case "clone": - if (!cache.url) cache.url = (0, _cleanurl.cleanURL)(url); - return ()=>new _nexturl.NextURL(cache.url); - default: - break; - } - }; - const wrappedNextUrl = new Proxy(request.nextUrl, { - get (target, prop) { - handleNextUrlBailout(prop); - if (dynamic === "force-static" && typeof prop === "string") { - const result = handleForceStatic(target.href, prop); - if (result !== undefined) return result; - } - const value = target[prop]; - if (typeof value === "function") { - return value.bind(target); - } - return value; - }, - set (target, prop, value) { - handleNextUrlBailout(prop); - target[prop] = value; - return true; - } - }); - const handleReqBailout = (prop)=>{ - switch(prop){ - case "headers": - hooks.headerHooks.headers(); - return; - // if request.url is accessed directly instead of - // request.nextUrl we bail since it includes query - // values that can be relied on dynamically - case "url": - case "body": - case "blob": - case "json": - case "text": - case "arrayBuffer": - case "formData": - hooks.staticGenerationBailout(`request.${prop}`); - return; - default: - return; - } - }; - return new Proxy(request, { - get (target, prop) { - handleReqBailout(prop); - if (prop === "nextUrl") { - return wrappedNextUrl; - } - if (dynamic === "force-static" && typeof prop === "string") { - const result = handleForceStatic(target.url, prop); - if (result !== undefined) return result; - } - const value = target[prop]; - if (typeof value === "function") { - return value.bind(target); - } - return value; - }, - set (target, prop, value) { - handleReqBailout(prop); - target[prop] = value; - return true; - } - }); -} //# sourceMappingURL=proxy-request.js.map - - -/***/ }), - -/***/ 7714: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "resolveHandlerError", ({ - enumerable: true, - get: function() { - return resolveHandlerError; - } -})); -const _notfound = __webpack_require__(4399); -const _redirect = __webpack_require__(6552); -const _responsehandlers = __webpack_require__(717); -function resolveHandlerError(err) { - if ((0, _redirect.isRedirectError)(err)) { - const redirect = (0, _redirect.getURLFromRedirectError)(err); - if (!redirect) { - throw new Error("Invariant: Unexpected redirect url format"); - } - // This is a redirect error! Send the redirect response. - return (0, _responsehandlers.handleTemporaryRedirectResponse)(redirect, err.mutableCookies); - } - if ((0, _notfound.isNotFoundError)(err)) { - // This is a not found error! Send the not found response. - return (0, _responsehandlers.handleNotFoundResponse)(); - } - // Return false to indicate that this is not a handled error. - return false; -} //# sourceMappingURL=resolve-handler-error.js.map - - -/***/ }), - -/***/ 9267: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - AppRouteRouteModule: function() { - return AppRouteRouteModule; - }, - default: function() { - return _default; - } -}); -const _routemodule = __webpack_require__(6210); -const _requestasyncstoragewrapper = __webpack_require__(3389); -const _staticgenerationasyncstoragewrapper = __webpack_require__(1482); -const _responsehandlers = __webpack_require__(717); -const _http = __webpack_require__(1183); -const _patchfetch = __webpack_require__(6133); -const _tracer = __webpack_require__(9814); -const _constants = __webpack_require__(3993); -const _getpathnamefromabsolutepath = __webpack_require__(2509); -const _proxyrequest = __webpack_require__(1320); -const _resolvehandlererror = __webpack_require__(7714); -const _routekind = __webpack_require__(6221); -const _log = /*#__PURE__*/ _interop_require_wildcard(__webpack_require__(3724)); -const _autoimplementmethods = __webpack_require__(7053); -const _getnonstaticmethods = __webpack_require__(3383); -const _requestcookies = __webpack_require__(8661); -function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -} -function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) { - return obj; - } - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) { - return cache.get(obj); - } - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - newObj.default = obj; - if (cache) { - cache.set(obj, newObj); - } - return newObj; -} -class AppRouteRouteModule extends _routemodule.RouteModule { - constructor({ userland , pathname , resolvedPagePath , nextConfigOutput }){ - super({ - userland - }); - /** - * When true, indicates that the global interfaces have been patched via the - * `patch()` method. - */ this.hasSetup = false; - this.definition = { - kind: _routekind.RouteKind.APP_ROUTE, - pathname, - // The following aren't needed for the route handler. - page: "", - bundlePath: "", - filename: "" - }; - this.pathname = pathname; - this.resolvedPagePath = resolvedPagePath; - this.nextConfigOutput = nextConfigOutput; - // Automatically implement some methods if they aren't implemented by the - // userland module. - this.methods = (0, _autoimplementmethods.autoImplementMethods)(userland); - // Get the non-static methods for this route. - this.nonStaticMethods = (0, _getnonstaticmethods.getNonStaticMethods)(userland); - // Get the dynamic property from the userland module. - this.dynamic = this.userland.dynamic; - if (this.nextConfigOutput === "export") { - if (!this.dynamic || this.dynamic === "auto") { - this.dynamic = "error"; - } else if (this.dynamic === "force-dynamic") { - throw new Error(`export const dynamic = "force-dynamic" on page "${pathname}" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export`); - } - } - } - /** - * Validates the userland module to ensure the exported methods and properties - * are valid. - */ async setup() { - // If we've already setup, then return. - if (this.hasSetup) return; - // Mark the module as setup. The following warnings about the userland - // module will run if we're in development. If the module files are modified - // when in development, then the require cache will be busted for it and - // this method will be called again (resetting the `hasSetup` flag). - this.hasSetup = true; - // We only warn in development after here, so return if we're not in - // development. - if (false) {} - } - /** - * Resolves the handler function for the given method. - * - * @param method the requested method - * @returns the handler function for the given method - */ resolve(method) { - // Ensure that the requested method is a valid method (to prevent RCE's). - if (!(0, _http.isHTTPMethod)(method)) return _responsehandlers.handleBadRequestResponse; - // Return the handler. - return this.methods[method]; - } - /** - * Executes the route handler. - */ async execute(request, context) { - // Get the handler function for the given method. - const handler = this.resolve(request.method); - // Get the context for the request. - const requestContext = { - req: request - }; - requestContext.renderOpts = { - previewProps: context.prerenderManifest.preview - }; - // Get the context for the static generation. - const staticGenerationContext = { - pathname: this.definition.pathname, - renderOpts: // the default values. - context.staticGenerationContext ?? { - supportsDynamicHTML: false - } - }; - // Add the fetchCache option to the renderOpts. - staticGenerationContext.renderOpts.fetchCache = this.userland.fetchCache; - // Run the handler with the request AsyncLocalStorage to inject the helper - // support. We set this to `unknown` because the type is not known until - // runtime when we do a instanceof check below. - const response = await this.actionAsyncStorage.run({ - isAppRoute: true - }, ()=>{ - return _requestasyncstoragewrapper.RequestAsyncStorageWrapper.wrap(this.requestAsyncStorage, requestContext, ()=>{ - return _staticgenerationasyncstoragewrapper.StaticGenerationAsyncStorageWrapper.wrap(this.staticGenerationAsyncStorage, staticGenerationContext, (staticGenerationStore)=>{ - var _getTracer_getRootSpanAttributes; - // Check to see if we should bail out of static generation based on - // having non-static methods. - if (this.nonStaticMethods) { - this.staticGenerationBailout(`non-static methods used ${this.nonStaticMethods.join(", ")}`); - } - // Update the static generation store based on the dynamic property. - switch(this.dynamic){ - case "force-dynamic": - // The dynamic property is set to force-dynamic, so we should - // force the page to be dynamic. - staticGenerationStore.forceDynamic = true; - this.staticGenerationBailout(`force-dynamic`, { - dynamic: this.dynamic - }); - break; - case "force-static": - // The dynamic property is set to force-static, so we should - // force the page to be static. - staticGenerationStore.forceStatic = true; - break; - case "error": - // The dynamic property is set to error, so we should throw an - // error if the page is being statically generated. - staticGenerationStore.dynamicShouldError = true; - break; - default: - break; - } - // If the static generation store does not have a revalidate value - // set, then we should set it the revalidate value from the userland - // module or default to false. - staticGenerationStore.revalidate ??= this.userland.revalidate ?? false; - // Wrap the request so we can add additional functionality to cases - // that might change it's output or affect the rendering. - const wrappedRequest = (0, _proxyrequest.proxyRequest)(request, { - dynamic: this.dynamic - }, { - headerHooks: this.headerHooks, - serverHooks: this.serverHooks, - staticGenerationBailout: this.staticGenerationBailout - }); - // TODO: propagate this pathname from route matcher - const route = (0, _getpathnamefromabsolutepath.getPathnameFromAbsolutePath)(this.resolvedPagePath); - (_getTracer_getRootSpanAttributes = (0, _tracer.getTracer)().getRootSpanAttributes()) == null ? void 0 : _getTracer_getRootSpanAttributes.set("next.route", route); - return (0, _tracer.getTracer)().trace(_constants.AppRouteRouteHandlersSpan.runHandler, { - spanName: `executing api route (app) ${route}`, - attributes: { - "next.route": route - } - }, async ()=>{ - var _staticGenerationStore_tags; - // Patch the global fetch. - (0, _patchfetch.patchFetch)({ - serverHooks: this.serverHooks, - staticGenerationAsyncStorage: this.staticGenerationAsyncStorage - }); - const res = await handler(wrappedRequest, { - params: context.params - }); - context.staticGenerationContext.fetchMetrics = staticGenerationStore.fetchMetrics; - await Promise.all(staticGenerationStore.pendingRevalidates || []); - (0, _patchfetch.addImplicitTags)(staticGenerationStore); - context.staticGenerationContext.fetchTags = (_staticGenerationStore_tags = staticGenerationStore.tags) == null ? void 0 : _staticGenerationStore_tags.join(","); - // It's possible cookies were set in the handler, so we need - // to merge the modified cookies and the returned response - // here. - const requestStore = this.requestAsyncStorage.getStore(); - if (requestStore && requestStore.mutableCookies) { - const headers = new Headers(res.headers); - if ((0, _requestcookies.appendMutableCookies)(headers, requestStore.mutableCookies)) { - return new Response(res.body, { - status: res.status, - statusText: res.statusText, - headers - }); - } - } - return res; - }); - }); - }); - }); - // If the handler did't return a valid response, then return the internal - // error response. - if (!(response instanceof Response)) { - // TODO: validate the correct handling behavior, maybe log something? - return (0, _responsehandlers.handleInternalServerErrorResponse)(); - } - if (response.headers.has("x-middleware-rewrite")) { - // TODO: move this error into the `NextResponse.rewrite()` function. - // TODO-APP: re-enable support below when we can proxy these type of requests - throw new Error("NextResponse.rewrite() was used in a app route handler, this is not currently supported. Please remove the invocation to continue."); - // // This is a rewrite created via `NextResponse.rewrite()`. We need to send - // // the response up so it can be handled by the backing server. - // // If the server is running in minimal mode, we just want to forward the - // // response (including the rewrite headers) upstream so it can perform the - // // redirect for us, otherwise return with the special condition so this - // // server can perform a rewrite. - // if (!minimalMode) { - // return { response, condition: 'rewrite' } - // } - // // Relativize the url so it's relative to the base url. This is so the - // // outgoing headers upstream can be relative. - // const rewritePath = response.headers.get('x-middleware-rewrite')! - // const initUrl = getRequestMeta(req, '__NEXT_INIT_URL')! - // const { pathname } = parseUrl(relativizeURL(rewritePath, initUrl)) - // response.headers.set('x-middleware-rewrite', pathname) - } - if (response.headers.get("x-middleware-next") === "1") { - // TODO: move this error into the `NextResponse.next()` function. - throw new Error("NextResponse.next() was used in a app route handler, this is not supported. See here for more info: https://nextjs.org/docs/messages/next-response-next-in-app-route-handler"); - } - return response; - } - async handle(request, context) { - try { - // Execute the route to get the response. - const response = await this.execute(request, context); - // The response was handled, return it. - return response; - } catch (err) { - // Try to resolve the error to a response, else throw it again. - const response = (0, _resolvehandlererror.resolveHandlerError)(err); - if (!response) throw err; - // The response was resolved, return it. - return response; - } - } -} -const _default = AppRouteRouteModule; //# sourceMappingURL=module.js.map - - -/***/ }), - -/***/ 717: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - handleTemporaryRedirectResponse: function() { - return handleTemporaryRedirectResponse; - }, - handleBadRequestResponse: function() { - return handleBadRequestResponse; - }, - handleNotFoundResponse: function() { - return handleNotFoundResponse; - }, - handleMethodNotAllowedResponse: function() { - return handleMethodNotAllowedResponse; - }, - handleInternalServerErrorResponse: function() { - return handleInternalServerErrorResponse; - } -}); -const _requestcookies = __webpack_require__(8661); -function handleTemporaryRedirectResponse(url, mutableCookies) { - const headers = new Headers({ - location: url - }); - (0, _requestcookies.appendMutableCookies)(headers, mutableCookies); - return new Response(null, { - status: 307, - headers - }); -} -function handleBadRequestResponse() { - return new Response(null, { - status: 400 - }); -} -function handleNotFoundResponse() { - return new Response(null, { - status: 404 - }); -} -function handleMethodNotAllowedResponse() { - return new Response(null, { - status: 405 - }); -} -function handleInternalServerErrorResponse() { - return new Response(null, { - status: 500 - }); -} //# sourceMappingURL=response-handlers.js.map - - -/***/ }), - -/***/ 6210: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "RouteModule", ({ - enumerable: true, - get: function() { - return RouteModule; - } -})); -// These are imported weirdly like this because of the way that the bundling -// works. We need to import the built files from the dist directory, but we -// can't do that directly because we need types from the source files. So we -// import the types from the source files and then import the built files. -const { requestAsyncStorage } = __webpack_require__(4437); -const { staticGenerationAsyncStorage } = __webpack_require__(94); -const serverHooks = __webpack_require__(3332); -const headerHooks = __webpack_require__(3851); -const { staticGenerationBailout } = __webpack_require__(5486); -const { actionAsyncStorage } = __webpack_require__(6127); -class RouteModule { - constructor({ userland }){ - /** - * A reference to the request async storage. - */ this.requestAsyncStorage = requestAsyncStorage; - /** - * A reference to the static generation async storage. - */ this.staticGenerationAsyncStorage = staticGenerationAsyncStorage; - /** - * An interface to call server hooks which interact with the underlying - * storage. - */ this.serverHooks = serverHooks; - /** - * An interface to call header hooks which interact with the underlying - * request storage. - */ this.headerHooks = headerHooks; - /** - * An interface to call static generation bailout hooks which interact with - * the underlying static generation storage. - */ this.staticGenerationBailout = staticGenerationBailout; - /** - * A reference to the mutation related async storage, such as mutations of - * cookies. - */ this.actionAsyncStorage = actionAsyncStorage; - this.userland = userland; - } -} //# sourceMappingURL=route-module.js.map - - -/***/ }), - -/***/ 6133: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - addImplicitTags: function() { - return addImplicitTags; - }, - patchFetch: function() { - return patchFetch; - } -}); -const _constants = __webpack_require__(3993); -const _tracer = __webpack_require__(9814); -const _constants1 = __webpack_require__(8537); -const isEdgeRuntime = "nodejs" === "edge"; -function addImplicitTags(staticGenerationStore) { - const newTags = []; - const pathname = staticGenerationStore == null ? void 0 : staticGenerationStore.originalPathname; - if (!pathname) { - return newTags; - } - if (!Array.isArray(staticGenerationStore.tags)) { - staticGenerationStore.tags = []; - } - if (!staticGenerationStore.tags.includes(pathname)) { - staticGenerationStore.tags.push(pathname); - } - newTags.push(pathname); - return newTags; -} -function trackFetchMetric(staticGenerationStore, ctx) { - if (!staticGenerationStore) return; - if (!staticGenerationStore.fetchMetrics) { - staticGenerationStore.fetchMetrics = []; - } - const dedupeFields = [ - "url", - "status", - "method" - ]; - // don't add metric if one already exists for the fetch - if (staticGenerationStore.fetchMetrics.some((metric)=>{ - return dedupeFields.every((field)=>metric[field] === ctx[field]); - })) { - return; - } - staticGenerationStore.fetchMetrics.push({ - url: ctx.url, - cacheStatus: ctx.cacheStatus, - status: ctx.status, - method: ctx.method, - start: ctx.start, - end: Date.now(), - idx: staticGenerationStore.nextFetchId || 0 - }); -} -function patchFetch({ serverHooks , staticGenerationAsyncStorage }) { - if (!globalThis._nextOriginalFetch) { - globalThis._nextOriginalFetch = globalThis.fetch; - } - if (globalThis.fetch.__nextPatched) return; - const { DynamicServerError } = serverHooks; - const originFetch = globalThis._nextOriginalFetch; - globalThis.fetch = async (input, init)=>{ - var _init_method; - let url; - try { - url = new URL(input instanceof Request ? input.url : input); - url.username = ""; - url.password = ""; - } catch { - // Error caused by malformed URL should be handled by native fetch - url = undefined; - } - const fetchUrl = (url == null ? void 0 : url.href) ?? ""; - const fetchStart = Date.now(); - const method = (init == null ? void 0 : (_init_method = init.method) == null ? void 0 : _init_method.toUpperCase()) || "GET"; - return await (0, _tracer.getTracer)().trace(_constants.AppRenderSpan.fetch, { - kind: _tracer.SpanKind.CLIENT, - spanName: [ - "fetch", - method, - fetchUrl - ].filter(Boolean).join(" "), - attributes: { - "http.url": fetchUrl, - "http.method": method, - "net.peer.name": url == null ? void 0 : url.hostname, - "net.peer.port": (url == null ? void 0 : url.port) || undefined - } - }, async ()=>{ - var _ref, _getRequestMeta; - const staticGenerationStore = staticGenerationAsyncStorage.getStore(); - const isRequestInput = input && typeof input === "object" && typeof input.method === "string"; - const getRequestMeta = (field)=>{ - let value = isRequestInput ? input[field] : null; - return value || (init == null ? void 0 : init[field]); - }; - // If the staticGenerationStore is not available, we can't do any - // special treatment of fetch, therefore fallback to the original - // fetch implementation. - if (!staticGenerationStore || ((_ref = init == null ? void 0 : init.next) == null ? void 0 : _ref.internal)) { - return originFetch(input, init); - } - let revalidate = undefined; - const getNextField = (field)=>{ - var _init_next, _init_next1, _input_next; - return typeof (init == null ? void 0 : (_init_next = init.next) == null ? void 0 : _init_next[field]) !== "undefined" ? init == null ? void 0 : (_init_next1 = init.next) == null ? void 0 : _init_next1[field] : isRequestInput ? (_input_next = input.next) == null ? void 0 : _input_next[field] : undefined; - }; - // RequestInit doesn't keep extra fields e.g. next so it's - // only available if init is used separate - let curRevalidate = getNextField("revalidate"); - const tags = getNextField("tags") || []; - if (Array.isArray(tags)) { - if (!staticGenerationStore.tags) { - staticGenerationStore.tags = []; - } - for (const tag of tags){ - if (!staticGenerationStore.tags.includes(tag)) { - staticGenerationStore.tags.push(tag); - } - } - } - const implicitTags = addImplicitTags(staticGenerationStore); - for (const tag of implicitTags || []){ - if (!tags.includes(tag)) { - tags.push(tag); - } - } - const isOnlyCache = staticGenerationStore.fetchCache === "only-cache"; - const isForceCache = staticGenerationStore.fetchCache === "force-cache"; - const isDefaultCache = staticGenerationStore.fetchCache === "default-cache"; - const isDefaultNoStore = staticGenerationStore.fetchCache === "default-no-store"; - const isOnlyNoStore = staticGenerationStore.fetchCache === "only-no-store"; - const isForceNoStore = staticGenerationStore.fetchCache === "force-no-store"; - let _cache = getRequestMeta("cache"); - if (typeof _cache === "string" && typeof curRevalidate !== "undefined") { - console.warn(`Warning: fetch for ${fetchUrl} on ${staticGenerationStore.pathname} specified "cache: ${_cache}" and "revalidate: ${curRevalidate}", only one should be specified.`); - _cache = undefined; - } - if (_cache === "force-cache") { - curRevalidate = false; - } - if ([ - "no-cache", - "no-store" - ].includes(_cache || "")) { - curRevalidate = 0; - } - if (typeof curRevalidate === "number" || curRevalidate === false) { - revalidate = curRevalidate; - } - let cacheReason = ""; - const _headers = getRequestMeta("headers"); - const initHeaders = typeof (_headers == null ? void 0 : _headers.get) === "function" ? _headers : new Headers(_headers || {}); - const hasUnCacheableHeader = initHeaders.get("authorization") || initHeaders.get("cookie"); - const isUnCacheableMethod = ![ - "get", - "head" - ].includes(((_getRequestMeta = getRequestMeta("method")) == null ? void 0 : _getRequestMeta.toLowerCase()) || "get"); - // if there are authorized headers or a POST method and - // dynamic data usage was present above the tree we bail - // e.g. if cookies() is used before an authed/POST fetch - const autoNoCache = (hasUnCacheableHeader || isUnCacheableMethod) && staticGenerationStore.revalidate === 0; - if (isForceNoStore) { - revalidate = 0; - cacheReason = "fetchCache = force-no-store"; - } - if (isOnlyNoStore) { - if (_cache === "force-cache" || revalidate === 0) { - throw new Error(`cache: 'force-cache' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-no-store'`); - } - revalidate = 0; - cacheReason = "fetchCache = only-no-store"; - } - if (isOnlyCache && _cache === "no-store") { - throw new Error(`cache: 'no-store' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-cache'`); - } - if (isForceCache && (typeof curRevalidate === "undefined" || curRevalidate === 0)) { - cacheReason = "fetchCache = force-cache"; - revalidate = false; - } - if (typeof revalidate === "undefined") { - if (isDefaultCache) { - revalidate = false; - cacheReason = "fetchCache = default-cache"; - } else if (autoNoCache) { - revalidate = 0; - cacheReason = "auto no cache"; - } else if (isDefaultNoStore) { - revalidate = 0; - cacheReason = "fetchCache = default-no-store"; - } else { - cacheReason = "auto cache"; - revalidate = typeof staticGenerationStore.revalidate === "boolean" || typeof staticGenerationStore.revalidate === "undefined" ? false : staticGenerationStore.revalidate; - } - } else if (!cacheReason) { - cacheReason = `revalidate: ${revalidate}`; - } - if (// revalidate although if it occurs during build we do - !autoNoCache && (typeof staticGenerationStore.revalidate === "undefined" || typeof revalidate === "number" && (staticGenerationStore.revalidate === false || typeof staticGenerationStore.revalidate === "number" && revalidate < staticGenerationStore.revalidate))) { - staticGenerationStore.revalidate = revalidate; - } - const isCacheableRevalidate = typeof revalidate === "number" && revalidate > 0 || revalidate === false; - let cacheKey; - if (staticGenerationStore.incrementalCache && isCacheableRevalidate) { - try { - cacheKey = await staticGenerationStore.incrementalCache.fetchCacheKey(fetchUrl, isRequestInput ? input : init); - } catch (err) { - console.error(`Failed to generate cache key for`, input); - } - } - const requestInputFields = [ - "cache", - "credentials", - "headers", - "integrity", - "keepalive", - "method", - "mode", - "redirect", - "referrer", - "referrerPolicy", - "signal", - "window", - "duplex" - ]; - if (isRequestInput) { - const reqInput = input; - const reqOptions = { - body: reqInput._ogBody || reqInput.body - }; - for (const field of requestInputFields){ - // @ts-expect-error custom fields - reqOptions[field] = reqInput[field]; - } - input = new Request(reqInput.url, reqOptions); - } else if (init) { - const initialInit = init; - init = { - body: init._ogBody || init.body - }; - for (const field of requestInputFields){ - // @ts-expect-error custom fields - init[field] = initialInit[field]; - } - } - const fetchIdx = staticGenerationStore.nextFetchId ?? 1; - staticGenerationStore.nextFetchId = fetchIdx + 1; - const normalizedRevalidate = typeof revalidate !== "number" ? _constants1.CACHE_ONE_YEAR : revalidate; - const doOriginalFetch = async (isStale)=>{ - // add metadata to init without editing the original - const clonedInit = { - ...init, - next: { - ...init == null ? void 0 : init.next, - fetchType: "origin", - fetchIdx - } - }; - return originFetch(input, clonedInit).then(async (res)=>{ - if (!isStale) { - trackFetchMetric(staticGenerationStore, { - start: fetchStart, - url: fetchUrl, - cacheReason, - cacheStatus: "miss", - status: res.status, - method: clonedInit.method || "GET" - }); - } - if (res.status === 200 && staticGenerationStore.incrementalCache && cacheKey && isCacheableRevalidate) { - const bodyBuffer = Buffer.from(await res.arrayBuffer()); - try { - await staticGenerationStore.incrementalCache.set(cacheKey, { - kind: "FETCH", - data: { - headers: Object.fromEntries(res.headers.entries()), - body: bodyBuffer.toString("base64"), - status: res.status, - tags - }, - revalidate: normalizedRevalidate - }, revalidate, true, fetchUrl, fetchIdx); - } catch (err) { - console.warn(`Failed to set fetch cache`, input, err); - } - return new Response(bodyBuffer, { - headers: new Headers(res.headers), - status: res.status - }); - } - return res; - }); - }; - if (cacheKey && (staticGenerationStore == null ? void 0 : staticGenerationStore.incrementalCache)) { - const entry = staticGenerationStore.isOnDemandRevalidate ? null : await staticGenerationStore.incrementalCache.get(cacheKey, true, revalidate, fetchUrl, fetchIdx); - if ((entry == null ? void 0 : entry.value) && entry.value.kind === "FETCH") { - const currentTags = entry.value.data.tags; - // when stale and is revalidating we wait for fresh data - // so the revalidated entry has the updated data - if (!(staticGenerationStore.isRevalidate && entry.isStale)) { - if (entry.isStale) { - if (!staticGenerationStore.pendingRevalidates) { - staticGenerationStore.pendingRevalidates = []; - } - staticGenerationStore.pendingRevalidates.push(doOriginalFetch(true).catch(console.error)); - } else if (tags && !tags.every((tag)=>{ - return currentTags == null ? void 0 : currentTags.includes(tag); - })) { - var _staticGenerationStore_incrementalCache; - // if new tags are being added we need to set even if - // the data isn't stale - if (!entry.value.data.tags) { - entry.value.data.tags = []; - } - for (const tag of tags){ - if (!entry.value.data.tags.includes(tag)) { - entry.value.data.tags.push(tag); - } - } - (_staticGenerationStore_incrementalCache = staticGenerationStore.incrementalCache) == null ? void 0 : _staticGenerationStore_incrementalCache.set(cacheKey, entry.value, revalidate, true, fetchUrl, fetchIdx); - } - const resData = entry.value.data; - let decodedBody; - if (false) {} else { - decodedBody = Buffer.from(resData.body, "base64").subarray(); - } - trackFetchMetric(staticGenerationStore, { - start: fetchStart, - url: fetchUrl, - cacheReason, - cacheStatus: "hit", - status: resData.status || 200, - method: (init == null ? void 0 : init.method) || "GET" - }); - return new Response(decodedBody, { - headers: resData.headers, - status: resData.status - }); - } - } - } - if (staticGenerationStore.isStaticGeneration) { - if (init && typeof init === "object") { - const cache = init.cache; - // Delete `cache` property as Cloudflare Workers will throw an error - if (isEdgeRuntime) { - delete init.cache; - } - if (cache === "no-store") { - staticGenerationStore.revalidate = 0; - // TODO: ensure this error isn't logged to the user - // seems it's slipping through currently - const dynamicUsageReason = `no-store fetch ${input}${staticGenerationStore.pathname ? ` ${staticGenerationStore.pathname}` : ""}`; - const err = new DynamicServerError(dynamicUsageReason); - staticGenerationStore.dynamicUsageStack = err.stack; - staticGenerationStore.dynamicUsageDescription = dynamicUsageReason; - throw err; - } - const hasNextConfig = "next" in init; - const next = init.next || {}; - if (typeof next.revalidate === "number" && (typeof staticGenerationStore.revalidate === "undefined" || next.revalidate < staticGenerationStore.revalidate)) { - const forceDynamic = staticGenerationStore.forceDynamic; - if (!forceDynamic || next.revalidate !== 0) { - staticGenerationStore.revalidate = next.revalidate; - } - if (!forceDynamic && next.revalidate === 0) { - const dynamicUsageReason = `revalidate: ${next.revalidate} fetch ${input}${staticGenerationStore.pathname ? ` ${staticGenerationStore.pathname}` : ""}`; - const err = new DynamicServerError(dynamicUsageReason); - staticGenerationStore.dynamicUsageStack = err.stack; - staticGenerationStore.dynamicUsageDescription = dynamicUsageReason; - throw err; - } - } - if (hasNextConfig) delete init.next; - } - } - return doOriginalFetch(); - }); - }; - globalThis.fetch.__nextGetStaticStore = ()=>{ - return staticGenerationAsyncStorage; - }; - globalThis.fetch.__nextPatched = true; -} //# sourceMappingURL=patch-fetch.js.map - - -/***/ }), - -/***/ 3993: -/***/ ((__unused_webpack_module, exports) => { - -/** - * Contains predefined constants for the trace span name in next/server. - * - * Currently, next/server/tracer is internal implementation only for tracking - * next.js's implementation only with known span names defined here. - **/ // eslint typescript has a bug with TS enums -/* eslint-disable no-shadow */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - NextVanillaSpanAllowlist: function() { - return NextVanillaSpanAllowlist; - }, - BaseServerSpan: function() { - return BaseServerSpan; - }, - LoadComponentsSpan: function() { - return LoadComponentsSpan; - }, - NextServerSpan: function() { - return NextServerSpan; - }, - NextNodeServerSpan: function() { - return NextNodeServerSpan; - }, - StartServerSpan: function() { - return StartServerSpan; - }, - RenderSpan: function() { - return RenderSpan; - }, - RouterSpan: function() { - return RouterSpan; - }, - AppRenderSpan: function() { - return AppRenderSpan; - }, - NodeSpan: function() { - return NodeSpan; - }, - AppRouteRouteHandlersSpan: function() { - return AppRouteRouteHandlersSpan; - }, - ResolveMetadataSpan: function() { - return ResolveMetadataSpan; - } -}); -var BaseServerSpan; -(function(BaseServerSpan) { - BaseServerSpan["handleRequest"] = "BaseServer.handleRequest"; - BaseServerSpan["run"] = "BaseServer.run"; - BaseServerSpan["pipe"] = "BaseServer.pipe"; - BaseServerSpan["getStaticHTML"] = "BaseServer.getStaticHTML"; - BaseServerSpan["render"] = "BaseServer.render"; - BaseServerSpan["renderToResponseWithComponents"] = "BaseServer.renderToResponseWithComponents"; - BaseServerSpan["renderToResponse"] = "BaseServer.renderToResponse"; - BaseServerSpan["renderToHTML"] = "BaseServer.renderToHTML"; - BaseServerSpan["renderError"] = "BaseServer.renderError"; - BaseServerSpan["renderErrorToResponse"] = "BaseServer.renderErrorToResponse"; - BaseServerSpan["renderErrorToHTML"] = "BaseServer.renderErrorToHTML"; - BaseServerSpan["render404"] = "BaseServer.render404"; -})(BaseServerSpan || (BaseServerSpan = {})); -var LoadComponentsSpan; -(function(LoadComponentsSpan) { - LoadComponentsSpan["loadDefaultErrorComponents"] = "LoadComponents.loadDefaultErrorComponents"; - LoadComponentsSpan["loadComponents"] = "LoadComponents.loadComponents"; -})(LoadComponentsSpan || (LoadComponentsSpan = {})); -var NextServerSpan; -(function(NextServerSpan) { - NextServerSpan["getRequestHandler"] = "NextServer.getRequestHandler"; - NextServerSpan["getServer"] = "NextServer.getServer"; - NextServerSpan["getServerRequestHandler"] = "NextServer.getServerRequestHandler"; - NextServerSpan["createServer"] = "createServer.createServer"; -})(NextServerSpan || (NextServerSpan = {})); -var NextNodeServerSpan; -(function(NextNodeServerSpan) { - NextNodeServerSpan["compression"] = "NextNodeServer.compression"; - NextNodeServerSpan["getBuildId"] = "NextNodeServer.getBuildId"; - NextNodeServerSpan["generateStaticRoutes"] = "NextNodeServer.generateStaticRoutes"; - NextNodeServerSpan["generateFsStaticRoutes"] = "NextNodeServer.generateFsStaticRoutes"; - NextNodeServerSpan["generatePublicRoutes"] = "NextNodeServer.generatePublicRoutes"; - NextNodeServerSpan["generateImageRoutes"] = "NextNodeServer.generateImageRoutes.route"; - NextNodeServerSpan["sendRenderResult"] = "NextNodeServer.sendRenderResult"; - NextNodeServerSpan["sendStatic"] = "NextNodeServer.sendStatic"; - NextNodeServerSpan["proxyRequest"] = "NextNodeServer.proxyRequest"; - NextNodeServerSpan["runApi"] = "NextNodeServer.runApi"; - NextNodeServerSpan["render"] = "NextNodeServer.render"; - NextNodeServerSpan["renderHTML"] = "NextNodeServer.renderHTML"; - NextNodeServerSpan["imageOptimizer"] = "NextNodeServer.imageOptimizer"; - NextNodeServerSpan["getPagePath"] = "NextNodeServer.getPagePath"; - NextNodeServerSpan["getRoutesManifest"] = "NextNodeServer.getRoutesManifest"; - NextNodeServerSpan["findPageComponents"] = "NextNodeServer.findPageComponents"; - NextNodeServerSpan["getFontManifest"] = "NextNodeServer.getFontManifest"; - NextNodeServerSpan["getServerComponentManifest"] = "NextNodeServer.getServerComponentManifest"; - NextNodeServerSpan["getRequestHandler"] = "NextNodeServer.getRequestHandler"; - NextNodeServerSpan["renderToHTML"] = "NextNodeServer.renderToHTML"; - NextNodeServerSpan["renderError"] = "NextNodeServer.renderError"; - NextNodeServerSpan["renderErrorToHTML"] = "NextNodeServer.renderErrorToHTML"; - NextNodeServerSpan["render404"] = "NextNodeServer.render404"; - NextNodeServerSpan["route"] = "route"; - NextNodeServerSpan["onProxyReq"] = "onProxyReq"; - NextNodeServerSpan["apiResolver"] = "apiResolver"; -})(NextNodeServerSpan || (NextNodeServerSpan = {})); -var StartServerSpan; -(function(StartServerSpan) { - StartServerSpan["startServer"] = "startServer.startServer"; -})(StartServerSpan || (StartServerSpan = {})); -var RenderSpan; -(function(RenderSpan) { - RenderSpan["getServerSideProps"] = "Render.getServerSideProps"; - RenderSpan["getStaticProps"] = "Render.getStaticProps"; - RenderSpan["renderToString"] = "Render.renderToString"; - RenderSpan["renderDocument"] = "Render.renderDocument"; - RenderSpan["createBodyResult"] = "Render.createBodyResult"; -})(RenderSpan || (RenderSpan = {})); -var AppRenderSpan; -(function(AppRenderSpan) { - AppRenderSpan["renderToString"] = "AppRender.renderToString"; - AppRenderSpan["renderToReadableStream"] = "AppRender.renderToReadableStream"; - AppRenderSpan["getBodyResult"] = "AppRender.getBodyResult"; - AppRenderSpan["fetch"] = "AppRender.fetch"; -})(AppRenderSpan || (AppRenderSpan = {})); -var RouterSpan; -(function(RouterSpan) { - RouterSpan["executeRoute"] = "Router.executeRoute"; -})(RouterSpan || (RouterSpan = {})); -var NodeSpan; -(function(NodeSpan) { - NodeSpan["runHandler"] = "Node.runHandler"; -})(NodeSpan || (NodeSpan = {})); -var AppRouteRouteHandlersSpan; -(function(AppRouteRouteHandlersSpan) { - AppRouteRouteHandlersSpan["runHandler"] = "AppRouteRouteHandlers.runHandler"; -})(AppRouteRouteHandlersSpan || (AppRouteRouteHandlersSpan = {})); -var ResolveMetadataSpan; -(function(ResolveMetadataSpan) { - ResolveMetadataSpan["generateMetadata"] = "ResolveMetadata.generateMetadata"; -})(ResolveMetadataSpan || (ResolveMetadataSpan = {})); -const NextVanillaSpanAllowlist = [ - "BaseServer.handleRequest", - "Render.getServerSideProps", - "Render.getStaticProps", - "AppRender.fetch", - "AppRender.getBodyResult", - "Render.renderDocument", - "Node.runHandler", - "AppRouteRouteHandlers.runHandler", - "ResolveMetadata.generateMetadata" -]; //# sourceMappingURL=constants.js.map - - -/***/ }), - -/***/ 9814: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - getTracer: function() { - return getTracer; - }, - SpanStatusCode: function() { - return SpanStatusCode; - }, - SpanKind: function() { - return SpanKind; - } -}); -const _constants = __webpack_require__(3993); -let api; -// we want to allow users to use their own version of @opentelemetry/api if they -// want to, so we try to require it first, and if it fails we fall back to the -// version that is bundled with Next.js -// this is because @opentelemetry/api has to be synced with the version of -// @opentelemetry/tracing that is used, and we don't want to force users to use -// the version that is bundled with Next.js. -// the API is ~stable, so this should be fine -if (false) {} else { - try { - api = __webpack_require__(2962); - } catch (err) { - api = __webpack_require__(8530); - } -} -const { context , trace , SpanStatusCode , SpanKind } = api; -const isPromise = (p)=>{ - return p !== null && typeof p === "object" && typeof p.then === "function"; -}; -const closeSpanWithError = (span, error)=>{ - if (error) { - span.recordException(error); - } - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error == null ? void 0 : error.message - }); - span.end(); -}; -/** we use this map to propagate attributes from nested spans to the top span */ const rootSpanAttributesStore = new Map(); -const rootSpanIdKey = api.createContextKey("next.rootSpanId"); -let lastSpanId = 0; -const getSpanId = ()=>lastSpanId++; -class NextTracerImpl { - /** - * Returns an instance to the trace with configured name. - * Since wrap / trace can be defined in any place prior to actual trace subscriber initialization, - * This should be lazily evaluated. - */ getTracerInstance() { - return trace.getTracer("next.js", "0.0.1"); - } - getContext() { - return context; - } - getActiveScopeSpan() { - return trace.getSpan(context == null ? void 0 : context.active()); - } - trace(...args) { - const [type, fnOrOptions, fnOrEmpty] = args; - // coerce options form overload - const { fn , options } = typeof fnOrOptions === "function" ? { - fn: fnOrOptions, - options: {} - } : { - fn: fnOrEmpty, - options: { - ...fnOrOptions - } - }; - if (!_constants.NextVanillaSpanAllowlist.includes(type) && process.env.NEXT_OTEL_VERBOSE !== "1" || options.hideSpan) { - return fn(); - } - const spanName = options.spanName ?? type; - // Trying to get active scoped span to assign parent. If option specifies parent span manually, will try to use it. - let spanContext = this.getSpanContext((options == null ? void 0 : options.parentSpan) ?? this.getActiveScopeSpan()); - let isRootSpan = false; - if (!spanContext) { - spanContext = api.ROOT_CONTEXT; - isRootSpan = true; - } - const spanId = getSpanId(); - options.attributes = { - "next.span_name": spanName, - "next.span_type": type, - ...options.attributes - }; - return api.context.with(spanContext.setValue(rootSpanIdKey, spanId), ()=>this.getTracerInstance().startActiveSpan(spanName, options, (span)=>{ - const onCleanup = ()=>{ - rootSpanAttributesStore.delete(spanId); - }; - if (isRootSpan) { - rootSpanAttributesStore.set(spanId, new Map(Object.entries(options.attributes ?? {}))); - } - try { - if (fn.length > 1) { - return fn(span, (err)=>closeSpanWithError(span, err)); - } - const result = fn(span); - if (isPromise(result)) { - result.then(()=>span.end(), (err)=>closeSpanWithError(span, err)).finally(onCleanup); - } else { - span.end(); - onCleanup(); - } - return result; - } catch (err) { - closeSpanWithError(span, err); - onCleanup(); - throw err; - } - })); - } - wrap(...args) { - const tracer = this; - const [name, options, fn] = args.length === 3 ? args : [ - args[0], - {}, - args[1] - ]; - if (!_constants.NextVanillaSpanAllowlist.includes(name) && process.env.NEXT_OTEL_VERBOSE !== "1") { - return fn; - } - return function() { - let optionsObj = options; - if (typeof optionsObj === "function" && typeof fn === "function") { - optionsObj = optionsObj.apply(this, arguments); - } - const lastArgId = arguments.length - 1; - const cb = arguments[lastArgId]; - if (typeof cb === "function") { - const scopeBoundCb = tracer.getContext().bind(context.active(), cb); - return tracer.trace(name, optionsObj, (_span, done)=>{ - arguments[lastArgId] = function(err) { - done == null ? void 0 : done(err); - return scopeBoundCb.apply(this, arguments); - }; - return fn.apply(this, arguments); - }); - } else { - return tracer.trace(name, optionsObj, ()=>fn.apply(this, arguments)); - } - }; - } - startSpan(...args) { - const [type, options] = args; - const spanContext = this.getSpanContext((options == null ? void 0 : options.parentSpan) ?? this.getActiveScopeSpan()); - return this.getTracerInstance().startSpan(type, options, spanContext); - } - getSpanContext(parentSpan) { - const spanContext = parentSpan ? trace.setSpan(context.active(), parentSpan) : undefined; - return spanContext; - } - getRootSpanAttributes() { - const spanId = context.active().getValue(rootSpanIdKey); - return rootSpanAttributesStore.get(spanId); - } -} -const getTracer = (()=>{ - const tracer = new NextTracerImpl(); - return ()=>tracer; -})(); //# sourceMappingURL=tracer.js.map - - -/***/ }), - -/***/ 5387: -/***/ (() => { - -/** - * Polyfills the `Headers.getAll(name)` method so it'll work in the edge - * runtime. - */ -if (!("getAll" in Headers.prototype)) { - // @ts-expect-error - this is polyfilling this method so it doesn't exist yet - Headers.prototype.getAll = function(name) { - name = name.toLowerCase(); - if (name !== "set-cookie") throw new Error("Headers.getAll is only supported for Set-Cookie header"); - const headers = [ - ...this.entries() - ].filter(([key])=>key === name); - return headers.map(([, value])=>value); - }; -} //# sourceMappingURL=node-polyfill-headers.js.map - - -/***/ }), - -/***/ 222: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - PageSignatureError: function() { - return PageSignatureError; - }, - RemovedPageError: function() { - return RemovedPageError; - }, - RemovedUAError: function() { - return RemovedUAError; - } -}); -class PageSignatureError extends Error { - constructor({ page }){ - super(`The middleware "${page}" accepts an async API directly with the form: - - export function middleware(request, event) { - return NextResponse.redirect('/new-location') - } - - Read more: https://nextjs.org/docs/messages/middleware-new-signature - `); - } -} -class RemovedPageError extends Error { - constructor(){ - super(`The request.page has been deprecated in favour of \`URLPattern\`. - Read more: https://nextjs.org/docs/messages/middleware-request-page - `); - } -} -class RemovedUAError extends Error { - constructor(){ - super(`The request.ua has been removed in favour of \`userAgent\` function. - Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent - `); - } -} //# sourceMappingURL=error.js.map - - -/***/ }), - -/***/ 1183: -/***/ ((__unused_webpack_module, exports) => { - -/** - * List of valid HTTP methods that can be implemented by Next.js's Custom App - * Routes. - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - HTTP_METHODS: function() { - return HTTP_METHODS; - }, - isHTTPMethod: function() { - return isHTTPMethod; - } -}); -const HTTP_METHODS = [ - "GET", - "HEAD", - "OPTIONS", - "POST", - "PUT", - "DELETE", - "PATCH" -]; -function isHTTPMethod(maybeMethod) { - return HTTP_METHODS.includes(maybeMethod); -} //# sourceMappingURL=http.js.map - - -/***/ }), - -/***/ 3369: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "NextURL", ({ - enumerable: true, - get: function() { - return NextURL; - } -})); -const _detectdomainlocale = __webpack_require__(2207); -const _formatnextpathnameinfo = __webpack_require__(7723); -const _gethostname = __webpack_require__(6056); -const _getnextpathnameinfo = __webpack_require__(9433); -const REGEX_LOCALHOST_HOSTNAME = /(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|::1|localhost)/; -function parseURL(url, base) { - return new URL(String(url).replace(REGEX_LOCALHOST_HOSTNAME, "localhost"), base && String(base).replace(REGEX_LOCALHOST_HOSTNAME, "localhost")); -} -const Internal = Symbol("NextURLInternal"); -class NextURL { - constructor(input, baseOrOpts, opts){ - let base; - let options; - if (typeof baseOrOpts === "object" && "pathname" in baseOrOpts || typeof baseOrOpts === "string") { - base = baseOrOpts; - options = opts || {}; - } else { - options = opts || baseOrOpts || {}; - } - this[Internal] = { - url: parseURL(input, base ?? options.base), - options: options, - basePath: "" - }; - this.analyze(); - } - analyze() { - var _this_Internal_options_nextConfig, _this_Internal_options_nextConfig_i18n, _this_Internal_domainLocale, _this_Internal_options_nextConfig1, _this_Internal_options_nextConfig_i18n1; - const info = (0, _getnextpathnameinfo.getNextPathnameInfo)(this[Internal].url.pathname, { - nextConfig: this[Internal].options.nextConfig, - parseData: !undefined, - i18nProvider: this[Internal].options.i18nProvider - }); - const hostname = (0, _gethostname.getHostname)(this[Internal].url, this[Internal].options.headers); - this[Internal].domainLocale = this[Internal].options.i18nProvider ? this[Internal].options.i18nProvider.detectDomainLocale(hostname) : (0, _detectdomainlocale.detectDomainLocale)((_this_Internal_options_nextConfig = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n = _this_Internal_options_nextConfig.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n.domains, hostname); - const defaultLocale = ((_this_Internal_domainLocale = this[Internal].domainLocale) == null ? void 0 : _this_Internal_domainLocale.defaultLocale) || ((_this_Internal_options_nextConfig1 = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n1 = _this_Internal_options_nextConfig1.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n1.defaultLocale); - this[Internal].url.pathname = info.pathname; - this[Internal].defaultLocale = defaultLocale; - this[Internal].basePath = info.basePath ?? ""; - this[Internal].buildId = info.buildId; - this[Internal].locale = info.locale ?? defaultLocale; - this[Internal].trailingSlash = info.trailingSlash; - } - formatPathname() { - return (0, _formatnextpathnameinfo.formatNextPathnameInfo)({ - basePath: this[Internal].basePath, - buildId: this[Internal].buildId, - defaultLocale: !this[Internal].options.forceLocale ? this[Internal].defaultLocale : undefined, - locale: this[Internal].locale, - pathname: this[Internal].url.pathname, - trailingSlash: this[Internal].trailingSlash - }); - } - formatSearch() { - return this[Internal].url.search; - } - get buildId() { - return this[Internal].buildId; - } - set buildId(buildId) { - this[Internal].buildId = buildId; - } - get locale() { - return this[Internal].locale ?? ""; - } - set locale(locale) { - var _this_Internal_options_nextConfig, _this_Internal_options_nextConfig_i18n; - if (!this[Internal].locale || !((_this_Internal_options_nextConfig = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n = _this_Internal_options_nextConfig.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n.locales.includes(locale))) { - throw new TypeError(`The NextURL configuration includes no locale "${locale}"`); - } - this[Internal].locale = locale; - } - get defaultLocale() { - return this[Internal].defaultLocale; - } - get domainLocale() { - return this[Internal].domainLocale; - } - get searchParams() { - return this[Internal].url.searchParams; - } - get host() { - return this[Internal].url.host; - } - set host(value) { - this[Internal].url.host = value; - } - get hostname() { - return this[Internal].url.hostname; - } - set hostname(value) { - this[Internal].url.hostname = value; - } - get port() { - return this[Internal].url.port; - } - set port(value) { - this[Internal].url.port = value; - } - get protocol() { - return this[Internal].url.protocol; - } - set protocol(value) { - this[Internal].url.protocol = value; - } - get href() { - const pathname = this.formatPathname(); - const search = this.formatSearch(); - return `${this.protocol}//${this.host}${pathname}${search}${this.hash}`; - } - set href(url) { - this[Internal].url = parseURL(url); - this.analyze(); - } - get origin() { - return this[Internal].url.origin; - } - get pathname() { - return this[Internal].url.pathname; - } - set pathname(value) { - this[Internal].url.pathname = value; - } - get hash() { - return this[Internal].url.hash; - } - set hash(value) { - this[Internal].url.hash = value; - } - get search() { - return this[Internal].url.search; - } - set search(value) { - this[Internal].url.search = value; - } - get password() { - return this[Internal].url.password; - } - set password(value) { - this[Internal].url.password = value; - } - get username() { - return this[Internal].url.username; - } - set username(value) { - this[Internal].url.username = value; - } - get basePath() { - return this[Internal].basePath; - } - set basePath(value) { - this[Internal].basePath = value.startsWith("/") ? value : `/${value}`; - } - toString() { - return this.href; - } - toJSON() { - return this.href; - } - [Symbol.for("edge-runtime.inspect.custom")]() { - return { - href: this.href, - origin: this.origin, - protocol: this.protocol, - username: this.username, - password: this.password, - host: this.host, - hostname: this.hostname, - port: this.port, - pathname: this.pathname, - search: this.search, - searchParams: this.searchParams, - hash: this.hash - }; - } - clone() { - return new NextURL(String(this), this[Internal].options); - } -} //# sourceMappingURL=next-url.js.map - - -/***/ }), - -/***/ 7304: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - ReadonlyHeadersError: function() { - return ReadonlyHeadersError; - }, - HeadersAdapter: function() { - return HeadersAdapter; - } -}); -const _reflect = __webpack_require__(9470); -class ReadonlyHeadersError extends Error { - constructor(){ - super("Headers cannot be modified. Read more: https://nextjs.org/docs/api-reference/headers"); - } - static callable() { - throw new ReadonlyHeadersError(); - } -} -class HeadersAdapter extends Headers { - constructor(headers){ - // We've already overridden the methods that would be called, so we're just - // calling the super constructor to ensure that the instanceof check works. - super(); - this.headers = new Proxy(headers, { - get (target, prop, receiver) { - // Because this is just an object, we expect that all "get" operations - // are for properties. If it's a "get" for a symbol, we'll just return - // the symbol. - if (typeof prop === "symbol") { - return _reflect.ReflectAdapter.get(target, prop, receiver); - } - const lowercased = prop.toLowerCase(); - // Let's find the original casing of the key. This assumes that there is - // no mixed case keys (e.g. "Content-Type" and "content-type") in the - // headers object. - const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased); - // If the original casing doesn't exist, return undefined. - if (typeof original === "undefined") return; - // If the original casing exists, return the value. - return _reflect.ReflectAdapter.get(target, original, receiver); - }, - set (target, prop, value, receiver) { - if (typeof prop === "symbol") { - return _reflect.ReflectAdapter.set(target, prop, value, receiver); - } - const lowercased = prop.toLowerCase(); - // Let's find the original casing of the key. This assumes that there is - // no mixed case keys (e.g. "Content-Type" and "content-type") in the - // headers object. - const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased); - // If the original casing doesn't exist, use the prop as the key. - return _reflect.ReflectAdapter.set(target, original ?? prop, value, receiver); - }, - has (target, prop) { - if (typeof prop === "symbol") return _reflect.ReflectAdapter.has(target, prop); - const lowercased = prop.toLowerCase(); - // Let's find the original casing of the key. This assumes that there is - // no mixed case keys (e.g. "Content-Type" and "content-type") in the - // headers object. - const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased); - // If the original casing doesn't exist, return false. - if (typeof original === "undefined") return false; - // If the original casing exists, return true. - return _reflect.ReflectAdapter.has(target, original); - }, - deleteProperty (target, prop) { - if (typeof prop === "symbol") return _reflect.ReflectAdapter.deleteProperty(target, prop); - const lowercased = prop.toLowerCase(); - // Let's find the original casing of the key. This assumes that there is - // no mixed case keys (e.g. "Content-Type" and "content-type") in the - // headers object. - const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased); - // If the original casing doesn't exist, return true. - if (typeof original === "undefined") return true; - // If the original casing exists, delete the property. - return _reflect.ReflectAdapter.deleteProperty(target, original); - } - }); - } - /** - * Seals a Headers instance to prevent modification by throwing an error when - * any mutating method is called. - */ static seal(headers) { - return new Proxy(headers, { - get (target, prop, receiver) { - switch(prop){ - case "append": - case "delete": - case "set": - return ReadonlyHeadersError.callable; - default: - return _reflect.ReflectAdapter.get(target, prop, receiver); - } - } - }); - } - /** - * Merges a header value into a string. This stores multiple values as an - * array, so we need to merge them into a string. - * - * @param value a header value - * @returns a merged header value (a string) - */ merge(value) { - if (Array.isArray(value)) return value.join(", "); - return value; - } - /** - * Creates a Headers instance from a plain object or a Headers instance. - * - * @param headers a plain object or a Headers instance - * @returns a headers instance - */ static from(headers) { - if (headers instanceof Headers) return headers; - return new HeadersAdapter(headers); - } - append(name, value) { - const existing = this.headers[name]; - if (typeof existing === "string") { - this.headers[name] = [ - existing, - value - ]; - } else if (Array.isArray(existing)) { - existing.push(value); - } else { - this.headers[name] = value; - } - } - delete(name) { - delete this.headers[name]; - } - get(name) { - const value = this.headers[name]; - if (typeof value !== "undefined") return this.merge(value); - return null; - } - has(name) { - return typeof this.headers[name] !== "undefined"; - } - set(name, value) { - this.headers[name] = value; - } - forEach(callbackfn, thisArg) { - for (const [name, value] of this.entries()){ - callbackfn.call(thisArg, value, name, this); - } - } - *entries() { - for (const key of Object.keys(this.headers)){ - const name = key.toLowerCase(); - // We assert here that this is a string because we got it from the - // Object.keys() call above. - const value = this.get(name); - yield [ - name, - value - ]; - } - } - *keys() { - for (const key of Object.keys(this.headers)){ - const name = key.toLowerCase(); - yield name; - } - } - *values() { - for (const key of Object.keys(this.headers)){ - // We assert here that this is a string because we got it from the - // Object.keys() call above. - const value = this.get(key); - yield value; - } - } - [Symbol.iterator]() { - return this.entries(); - } -} //# sourceMappingURL=headers.js.map - - -/***/ }), - -/***/ 9470: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "ReflectAdapter", ({ - enumerable: true, - get: function() { - return ReflectAdapter; - } -})); -class ReflectAdapter { - static get(target, prop, receiver) { - const value = Reflect.get(target, prop, receiver); - if (typeof value === "function") { - return value.bind(target); - } - return value; - } - static set(target, prop, value, receiver) { - return Reflect.set(target, prop, value, receiver); - } - static has(target, prop) { - return Reflect.has(target, prop); - } - static deleteProperty(target, prop) { - return Reflect.deleteProperty(target, prop); - } -} //# sourceMappingURL=reflect.js.map - - -/***/ }), - -/***/ 8661: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - ReadonlyRequestCookiesError: function() { - return ReadonlyRequestCookiesError; - }, - RequestCookiesAdapter: function() { - return RequestCookiesAdapter; - }, - appendMutableCookies: function() { - return appendMutableCookies; - }, - MutableRequestCookiesAdapter: function() { - return MutableRequestCookiesAdapter; - } -}); -const _cookies = __webpack_require__(4521); -const _reflect = __webpack_require__(9470); -class ReadonlyRequestCookiesError extends Error { - constructor(){ - super("Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options"); - } - static callable() { - throw new ReadonlyRequestCookiesError(); - } -} -class RequestCookiesAdapter { - static seal(cookies) { - return new Proxy(cookies, { - get (target, prop, receiver) { - switch(prop){ - case "clear": - case "delete": - case "set": - return ReadonlyRequestCookiesError.callable; - default: - return _reflect.ReflectAdapter.get(target, prop, receiver); - } - } - }); - } -} -const SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for("next.mutated.cookies"); -function getModifiedCookieValues(cookies) { - const modified = cookies[SYMBOL_MODIFY_COOKIE_VALUES]; - if (!modified || !Array.isArray(modified) || modified.length === 0) { - return []; - } - return modified; -} -function appendMutableCookies(headers, mutableCookies) { - const modifiedCookieValues = getModifiedCookieValues(mutableCookies); - if (modifiedCookieValues.length === 0) { - return false; - } - // Return a new response that extends the response with - // the modified cookies as fallbacks. `res`' cookies - // will still take precedence. - const resCookies = new _cookies.ResponseCookies(headers); - const returnedCookies = resCookies.getAll(); - // Set the modified cookies as fallbacks. - for (const cookie of modifiedCookieValues){ - resCookies.set(cookie); - } - // Set the original cookies as the final values. - for (const cookie of returnedCookies){ - resCookies.set(cookie); - } - return true; -} -class MutableRequestCookiesAdapter { - static wrap(cookies, res) { - const responseCookes = new _cookies.ResponseCookies(new Headers()); - for (const cookie of cookies.getAll()){ - responseCookes.set(cookie); - } - let modifiedValues = []; - const modifiedCookies = new Set(); - const updateResponseCookies = ()=>{ - var _fetch___nextGetStaticStore; - // TODO-APP: change method of getting staticGenerationAsyncStore - const staticGenerationAsyncStore = fetch.__nextGetStaticStore == null ? void 0 : (_fetch___nextGetStaticStore = fetch.__nextGetStaticStore()) == null ? void 0 : _fetch___nextGetStaticStore.getStore(); - if (staticGenerationAsyncStore) { - staticGenerationAsyncStore.pathWasRevalidated = true; - } - const allCookies = responseCookes.getAll(); - modifiedValues = allCookies.filter((c)=>modifiedCookies.has(c.name)); - if (res) { - const serializedCookies = []; - for (const cookie of modifiedValues){ - const tempCookies = new _cookies.ResponseCookies(new Headers()); - tempCookies.set(cookie); - serializedCookies.push(tempCookies.toString()); - } - res.setHeader("Set-Cookie", serializedCookies); - } - }; - return new Proxy(responseCookes, { - get (target, prop, receiver) { - switch(prop){ - // A special symbol to get the modified cookie values - case SYMBOL_MODIFY_COOKIE_VALUES: - return modifiedValues; - // TODO: Throw error if trying to set a cookie after the response - // headers have been set. - case "delete": - return function(...args) { - modifiedCookies.add(typeof args[0] === "string" ? args[0] : args[0].name); - try { - target.delete(...args); - } finally{ - updateResponseCookies(); - } - }; - case "set": - return function(...args) { - modifiedCookies.add(typeof args[0] === "string" ? args[0] : args[0].name); - try { - return target.set(...args); - } finally{ - updateResponseCookies(); - } - }; - default: - return _reflect.ReflectAdapter.get(target, prop, receiver); - } - } - }); - } -} //# sourceMappingURL=request-cookies.js.map - - -/***/ }), - -/***/ 4521: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - RequestCookies: function() { - return _cookies.RequestCookies; - }, - ResponseCookies: function() { - return _cookies.ResponseCookies; - } -}); -const _cookies = __webpack_require__(7783); //# sourceMappingURL=cookies.js.map - - -/***/ }), - -/***/ 7970: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -var __webpack_unused_export__; - -__webpack_unused_export__ = ({ - value: true -}); -Object.defineProperty(exports, "E", ({ - enumerable: true, - get: function() { - return ImageResponse; - } -})); -class ImageResponse { - constructor(...args){ - // @ts-expect-error - process.turbopack is a custom property - if (false) {} else { - const readable = new ReadableStream({ - async start (controller) { - const OGImageResponse = // as the auto resolving is not working - (await Promise.resolve(/* import() */).then(__webpack_require__.bind(__webpack_require__, 4021))).ImageResponse; - const imageResponse = new OGImageResponse(...args); - if (!imageResponse.body) { - return controller.close(); - } - const reader = imageResponse.body.getReader(); - while(true){ - const { done , value } = await reader.read(); - if (done) { - return controller.close(); - } - controller.enqueue(value); - } - } - }); - const options = args[1] || {}; - return new Response(readable, { - headers: { - "content-type": "image/png", - "cache-control": false ? 0 : "public, immutable, no-transform, max-age=31536000", - ...options.headers - }, - status: options.status, - statusText: options.statusText - }); - } - } -} //# sourceMappingURL=image-response.js.map - - -/***/ }), - -/***/ 6569: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - INTERNALS: function() { - return INTERNALS; - }, - NextRequest: function() { - return NextRequest; - } -}); -const _nexturl = __webpack_require__(3369); -const _utils = __webpack_require__(7252); -const _error = __webpack_require__(222); -const _cookies = __webpack_require__(4521); -const INTERNALS = Symbol("internal request"); -class NextRequest extends Request { - constructor(input, init = {}){ - const url = typeof input !== "string" && "url" in input ? input.url : String(input); - (0, _utils.validateURL)(url); - super(url, init); - const nextUrl = new _nexturl.NextURL(url, { - headers: (0, _utils.toNodeHeaders)(this.headers), - nextConfig: init.nextConfig - }); - this[INTERNALS] = { - cookies: new _cookies.RequestCookies(this.headers), - geo: init.geo || {}, - ip: init.ip, - nextUrl, - url: false ? 0 : nextUrl.toString() - }; - } - [Symbol.for("edge-runtime.inspect.custom")]() { - return { - cookies: this.cookies, - geo: this.geo, - ip: this.ip, - nextUrl: this.nextUrl, - url: this.url, - // rest of props come from Request - bodyUsed: this.bodyUsed, - cache: this.cache, - credentials: this.credentials, - destination: this.destination, - headers: Object.fromEntries(this.headers), - integrity: this.integrity, - keepalive: this.keepalive, - method: this.method, - mode: this.mode, - redirect: this.redirect, - referrer: this.referrer, - referrerPolicy: this.referrerPolicy, - signal: this.signal - }; - } - get cookies() { - return this[INTERNALS].cookies; - } - get geo() { - return this[INTERNALS].geo; - } - get ip() { - return this[INTERNALS].ip; - } - get nextUrl() { - return this[INTERNALS].nextUrl; - } - /** - * @deprecated - * `page` has been deprecated in favour of `URLPattern`. - * Read more: https://nextjs.org/docs/messages/middleware-request-page - */ get page() { - throw new _error.RemovedPageError(); - } - /** - * @deprecated - * `ua` has been removed in favour of \`userAgent\` function. - * Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent - */ get ua() { - throw new _error.RemovedUAError(); - } - get url() { - return this[INTERNALS].url; - } -} //# sourceMappingURL=request.js.map - - -/***/ }), - -/***/ 2917: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -var __webpack_unused_export__; - -__webpack_unused_export__ = ({ - value: true -}); -Object.defineProperty(exports, "x", ({ - enumerable: true, - get: function() { - return NextResponse; - } -})); -const _nexturl = __webpack_require__(3369); -const _utils = __webpack_require__(7252); -const _cookies = __webpack_require__(4521); -const INTERNALS = Symbol("internal response"); -const REDIRECTS = new Set([ - 301, - 302, - 303, - 307, - 308 -]); -function handleMiddlewareField(init, headers) { - var _init_request; - if (init == null ? void 0 : (_init_request = init.request) == null ? void 0 : _init_request.headers) { - if (!(init.request.headers instanceof Headers)) { - throw new Error("request.headers must be an instance of Headers"); - } - const keys = []; - for (const [key, value] of init.request.headers){ - headers.set("x-middleware-request-" + key, value); - keys.push(key); - } - headers.set("x-middleware-override-headers", keys.join(",")); - } -} -class NextResponse extends Response { - constructor(body, init = {}){ - super(body, init); - this[INTERNALS] = { - cookies: new _cookies.ResponseCookies(this.headers), - url: init.url ? new _nexturl.NextURL(init.url, { - headers: (0, _utils.toNodeHeaders)(this.headers), - nextConfig: init.nextConfig - }) : undefined - }; - } - [Symbol.for("edge-runtime.inspect.custom")]() { - return { - cookies: this.cookies, - url: this.url, - // rest of props come from Response - body: this.body, - bodyUsed: this.bodyUsed, - headers: Object.fromEntries(this.headers), - ok: this.ok, - redirected: this.redirected, - status: this.status, - statusText: this.statusText, - type: this.type - }; - } - get cookies() { - return this[INTERNALS].cookies; - } - static json(body, init) { - // @ts-expect-error This is not in lib/dom right now, and we can't augment it. - const response = Response.json(body, init); - return new NextResponse(response.body, response); - } - static redirect(url, init) { - const status = typeof init === "number" ? init : (init == null ? void 0 : init.status) ?? 307; - if (!REDIRECTS.has(status)) { - throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); - } - const initObj = typeof init === "object" ? init : {}; - const headers = new Headers(initObj == null ? void 0 : initObj.headers); - headers.set("Location", (0, _utils.validateURL)(url)); - return new NextResponse(null, { - ...initObj, - headers, - status - }); - } - static rewrite(destination, init) { - const headers = new Headers(init == null ? void 0 : init.headers); - headers.set("x-middleware-rewrite", (0, _utils.validateURL)(destination)); - handleMiddlewareField(init, headers); - return new NextResponse(null, { - ...init, - headers - }); - } - static next(init) { - const headers = new Headers(init == null ? void 0 : init.headers); - headers.set("x-middleware-next", "1"); - handleMiddlewareField(init, headers); - return new NextResponse(null, { - ...init, - headers - }); - } -} //# sourceMappingURL=response.js.map - - -/***/ }), - -/***/ 1789: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - isBot: function() { - return isBot; - }, - userAgentFromString: function() { - return userAgentFromString; - }, - userAgent: function() { - return userAgent; - } -}); -const _uaparserjs = /*#__PURE__*/ _interop_require_default(__webpack_require__(2196)); -function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} -function isBot(input) { - return /Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(input); -} -function userAgentFromString(input) { - return { - ...(0, _uaparserjs.default)(input), - isBot: input === undefined ? false : isBot(input) - }; -} -function userAgent({ headers }) { - return userAgentFromString(headers.get("user-agent") || undefined); -} //# sourceMappingURL=user-agent.js.map - - -/***/ }), - -/***/ 7252: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - fromNodeHeaders: function() { - return fromNodeHeaders; - }, - splitCookiesString: function() { - return splitCookiesString; - }, - toNodeHeaders: function() { - return toNodeHeaders; - }, - validateURL: function() { - return validateURL; - } -}); -function fromNodeHeaders(object) { - const headers = new Headers(); - for (let [key, value] of Object.entries(object)){ - const values = Array.isArray(value) ? value : [ - value - ]; - for (let v of values){ - if (typeof v === "undefined") continue; - if (typeof v === "number") { - v = v.toString(); - } - headers.append(key, v); - } - } - return headers; -} -function splitCookiesString(cookiesString) { - var cookiesStrings = []; - var pos = 0; - var start; - var ch; - var lastComma; - var nextStart; - var cookiesSeparatorFound; - function skipWhitespace() { - while(pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))){ - pos += 1; - } - return pos < cookiesString.length; - } - function notSpecialChar() { - ch = cookiesString.charAt(pos); - return ch !== "=" && ch !== ";" && ch !== ","; - } - while(pos < cookiesString.length){ - start = pos; - cookiesSeparatorFound = false; - while(skipWhitespace()){ - ch = cookiesString.charAt(pos); - if (ch === ",") { - // ',' is a cookie separator if we have later first '=', not ';' or ',' - lastComma = pos; - pos += 1; - skipWhitespace(); - nextStart = pos; - while(pos < cookiesString.length && notSpecialChar()){ - pos += 1; - } - // currently special character - if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { - // we found cookies separator - cookiesSeparatorFound = true; - // pos is inside the next cookie, so back up and return it. - pos = nextStart; - cookiesStrings.push(cookiesString.substring(start, lastComma)); - start = pos; - } else { - // in param ',' or param separator ';', - // we continue from that comma - pos = lastComma + 1; - } - } else { - pos += 1; - } - } - if (!cookiesSeparatorFound || pos >= cookiesString.length) { - cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); - } - } - return cookiesStrings; -} -function toNodeHeaders(headers) { - const result = {}; - const cookies = []; - if (headers) { - for (const [key, value] of headers.entries()){ - if (key.toLowerCase() === "set-cookie") { - // We may have gotten a comma joined string of cookies, or multiple - // set-cookie headers. We need to merge them into one header array - // to represent all the cookies. - cookies.push(...splitCookiesString(value)); - result[key] = cookies.length === 1 ? cookies[0] : cookies; - } else { - result[key] = value; - } - } - } - return result; -} -function validateURL(url) { - try { - return String(new URL(String(url))); - } catch (error) { - throw new Error(`URL is malformed "${String(url)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`, { - cause: error - }); - } -} //# sourceMappingURL=utils.js.map - - -/***/ }), - -/***/ 6056: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "getHostname", ({ - enumerable: true, - get: function() { - return getHostname; - } -})); -function getHostname(parsed, headers) { - // Get the hostname from the headers if it exists, otherwise use the parsed - // hostname. - let hostname; - if ((headers == null ? void 0 : headers.host) && !Array.isArray(headers.host)) { - hostname = headers.host.toString().split(":")[0]; - } else if (parsed.hostname) { - hostname = parsed.hostname; - } else return; - return hostname.toLowerCase(); -} //# sourceMappingURL=get-hostname.js.map - - -/***/ }), - -/***/ 5723: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "addLocale", ({ - enumerable: true, - get: function() { - return addLocale; - } -})); -const _addpathprefix = __webpack_require__(2610); -const _pathhasprefix = __webpack_require__(1342); -function addLocale(path, locale, defaultLocale, ignorePrefix) { - // If no locale was given or the locale is the default locale, we don't need - // to prefix the path. - if (!locale || locale === defaultLocale) return path; - const lower = path.toLowerCase(); - // If the path is an API path or the path already has the locale prefix, we - // don't need to prefix the path. - if (!ignorePrefix) { - if ((0, _pathhasprefix.pathHasPrefix)(lower, "/api")) return path; - if ((0, _pathhasprefix.pathHasPrefix)(lower, "/" + locale.toLowerCase())) return path; - } - // Add the locale prefix to the path. - return (0, _addpathprefix.addPathPrefix)(path, "/" + locale); -} //# sourceMappingURL=add-locale.js.map - - -/***/ }), - -/***/ 2610: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "addPathPrefix", ({ - enumerable: true, - get: function() { - return addPathPrefix; - } -})); -const _parsepath = __webpack_require__(5084); -function addPathPrefix(path, prefix) { - if (!path.startsWith("/") || !prefix) { - return path; - } - const { pathname , query , hash } = (0, _parsepath.parsePath)(path); - return "" + prefix + pathname + query + hash; -} //# sourceMappingURL=add-path-prefix.js.map - - -/***/ }), - -/***/ 7928: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "addPathSuffix", ({ - enumerable: true, - get: function() { - return addPathSuffix; - } -})); -const _parsepath = __webpack_require__(5084); -function addPathSuffix(path, suffix) { - if (!path.startsWith("/") || !suffix) { - return path; - } - const { pathname , query , hash } = (0, _parsepath.parsePath)(path); - return "" + pathname + suffix + query + hash; -} //# sourceMappingURL=add-path-suffix.js.map - - -/***/ }), - -/***/ 7723: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "formatNextPathnameInfo", ({ - enumerable: true, - get: function() { - return formatNextPathnameInfo; - } -})); -const _removetrailingslash = __webpack_require__(465); -const _addpathprefix = __webpack_require__(2610); -const _addpathsuffix = __webpack_require__(7928); -const _addlocale = __webpack_require__(5723); -function formatNextPathnameInfo(info) { - let pathname = (0, _addlocale.addLocale)(info.pathname, info.locale, info.buildId ? undefined : info.defaultLocale, info.ignorePrefix); - if (info.buildId || !info.trailingSlash) { - pathname = (0, _removetrailingslash.removeTrailingSlash)(pathname); - } - if (info.buildId) { - pathname = (0, _addpathsuffix.addPathSuffix)((0, _addpathprefix.addPathPrefix)(pathname, "/_next/data/" + info.buildId), info.pathname === "/" ? "index.json" : ".json"); - } - pathname = (0, _addpathprefix.addPathPrefix)(pathname, info.basePath); - return !info.buildId && info.trailingSlash ? !pathname.endsWith("/") ? (0, _addpathsuffix.addPathSuffix)(pathname, "/") : pathname : (0, _removetrailingslash.removeTrailingSlash)(pathname); -} //# sourceMappingURL=format-next-pathname-info.js.map - - -/***/ }), - -/***/ 9433: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "getNextPathnameInfo", ({ - enumerable: true, - get: function() { - return getNextPathnameInfo; - } -})); -const _normalizelocalepath = __webpack_require__(9962); -const _removepathprefix = __webpack_require__(1507); -const _pathhasprefix = __webpack_require__(1342); -function getNextPathnameInfo(pathname, options) { - var _options_nextConfig; - const { basePath , i18n , trailingSlash } = (_options_nextConfig = options.nextConfig) != null ? _options_nextConfig : {}; - const info = { - pathname: pathname, - trailingSlash: pathname !== "/" ? pathname.endsWith("/") : trailingSlash - }; - if (basePath && (0, _pathhasprefix.pathHasPrefix)(info.pathname, basePath)) { - info.pathname = (0, _removepathprefix.removePathPrefix)(info.pathname, basePath); - info.basePath = basePath; - } - if (options.parseData === true && info.pathname.startsWith("/_next/data/") && info.pathname.endsWith(".json")) { - const paths = info.pathname.replace(/^\/_next\/data\//, "").replace(/\.json$/, "").split("/"); - const buildId = paths[0]; - info.pathname = paths[1] !== "index" ? "/" + paths.slice(1).join("/") : "/"; - info.buildId = buildId; - } - // If provided, use the locale route normalizer to detect the locale instead - // of the function below. - if (options.i18nProvider) { - const result = options.i18nProvider.analyze(info.pathname); - info.locale = result.detectedLocale; - var _result_pathname; - info.pathname = (_result_pathname = result.pathname) != null ? _result_pathname : info.pathname; - } else if (i18n) { - const pathLocale = (0, _normalizelocalepath.normalizeLocalePath)(info.pathname, i18n.locales); - info.locale = pathLocale.detectedLocale; - var _pathLocale_pathname; - info.pathname = (_pathLocale_pathname = pathLocale.pathname) != null ? _pathLocale_pathname : info.pathname; - } - return info; -} //# sourceMappingURL=get-next-pathname-info.js.map - - -/***/ }), - -/***/ 5084: -/***/ ((__unused_webpack_module, exports) => { - -/** - * Given a path this function will find the pathname, query and hash and return - * them. This is useful to parse full paths on the client side. - * @param path A path to parse e.g. /foo/bar?id=1#hash - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "parsePath", ({ - enumerable: true, - get: function() { - return parsePath; - } -})); -function parsePath(path) { - const hashIndex = path.indexOf("#"); - const queryIndex = path.indexOf("?"); - const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex); - if (hasQuery || hashIndex > -1) { - return { - pathname: path.substring(0, hasQuery ? queryIndex : hashIndex), - query: hasQuery ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined) : "", - hash: hashIndex > -1 ? path.slice(hashIndex) : "" - }; - } - return { - pathname: path, - query: "", - hash: "" - }; -} //# sourceMappingURL=parse-path.js.map - - -/***/ }), - -/***/ 1342: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "pathHasPrefix", ({ - enumerable: true, - get: function() { - return pathHasPrefix; - } -})); -const _parsepath = __webpack_require__(5084); -function pathHasPrefix(path, prefix) { - if (typeof path !== "string") { - return false; - } - const { pathname } = (0, _parsepath.parsePath)(path); - return pathname === prefix || pathname.startsWith(prefix + "/"); -} //# sourceMappingURL=path-has-prefix.js.map - - -/***/ }), - -/***/ 1507: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "removePathPrefix", ({ - enumerable: true, - get: function() { - return removePathPrefix; - } -})); -const _pathhasprefix = __webpack_require__(1342); -function removePathPrefix(path, prefix) { - // If the path doesn't start with the prefix we can return it as is. This - // protects us from situations where the prefix is a substring of the path - // prefix such as: - // - // For prefix: /blog - // - // /blog -> true - // /blog/ -> true - // /blog/1 -> true - // /blogging -> false - // /blogging/ -> false - // /blogging/1 -> false - if (!(0, _pathhasprefix.pathHasPrefix)(path, prefix)) { - return path; - } - // Remove the prefix from the path via slicing. - const withoutPrefix = path.slice(prefix.length); - // If the path without the prefix starts with a `/` we can return it as is. - if (withoutPrefix.startsWith("/")) { - return withoutPrefix; - } - // If the path without the prefix doesn't start with a `/` we need to add it - // back to the path to make sure it's a valid path. - return "/" + withoutPrefix; -} //# sourceMappingURL=remove-path-prefix.js.map - - -/***/ }), - -/***/ 4664: -/***/ ((module, exports, __webpack_require__) => { - - -const serverExports = { - NextRequest: (__webpack_require__(6569).NextRequest), - NextResponse: (__webpack_require__(2917)/* .NextResponse */ .x), - ImageResponse: (__webpack_require__(7970)/* .ImageResponse */ .E), - userAgentFromString: (__webpack_require__(1789).userAgentFromString), - userAgent: (__webpack_require__(1789).userAgent) -}; -if (typeof URLPattern !== "undefined") { - // eslint-disable-next-line no-undef - serverExports.URLPattern = URLPattern; -} -// https://nodejs.org/api/esm.html#commonjs-namespaces -// When importing CommonJS modules, the module.exports object is provided as the default export -module.exports = serverExports; -// make import { xxx } from 'next/server' work -exports.NextRequest = serverExports.NextRequest; -exports.NextResponse = serverExports.NextResponse; -exports.ImageResponse = serverExports.ImageResponse; -exports.userAgentFromString = serverExports.userAgentFromString; -exports.userAgent = serverExports.userAgent; -exports.URLPattern = serverExports.URLPattern; - - -/***/ }) - -}; -; \ No newline at end of file diff --git a/.next/server/chunks/616.js b/.next/server/chunks/616.js deleted file mode 100644 index 396dbec..0000000 --- a/.next/server/chunks/616.js +++ /dev/null @@ -1,9000 +0,0 @@ -exports.id = 616; -exports.ids = [616]; -exports.modules = { - -/***/ 160: -/***/ ((module) => { - -// Exports -module.exports = { - "style": {"fontFamily":"'__Inter_0ec1f4', '__Inter_Fallback_0ec1f4'","fontStyle":"normal"}, - "className": "__className_0ec1f4" -}; - - -/***/ }), - -/***/ 739: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "addBasePath", ({ - enumerable: true, - get: function() { - return addBasePath; - } -})); -const _addpathprefix = __webpack_require__(1751); -const _normalizetrailingslash = __webpack_require__(6089); -const basePath = false || ""; -function addBasePath(path, required) { - if (false) {} - return (0, _normalizetrailingslash.normalizePathTrailingSlash)((0, _addpathprefix.addPathPrefix)(path, basePath)); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=add-base-path.js.map - - -/***/ }), - -/***/ 4783: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "callServer", ({ - enumerable: true, - get: function() { - return callServer; - } -})); -const _approuter = __webpack_require__(125); -async function callServer(actionId, actionArgs) { - const actionDispatcher = (0, _approuter.getServerActionDispatcher)(); - if (!actionDispatcher) { - throw new Error("Invariant: missing action dispatcher."); - } - return new Promise((resolve, reject)=>{ - actionDispatcher({ - actionId, - actionArgs, - resolve, - reject - }); - }); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=app-call-server.js.map - - -/***/ }), - -/***/ 4275: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "AppRouterAnnouncer", ({ - enumerable: true, - get: function() { - return AppRouterAnnouncer; - } -})); -const _react = __webpack_require__(8038); -const _reactdom = __webpack_require__(8704); -const ANNOUNCER_TYPE = "next-route-announcer"; -const ANNOUNCER_ID = "__next-route-announcer__"; -function getAnnouncerNode() { - var _existingAnnouncer_shadowRoot; - const existingAnnouncer = document.getElementsByName(ANNOUNCER_TYPE)[0]; - if (existingAnnouncer == null ? void 0 : (_existingAnnouncer_shadowRoot = existingAnnouncer.shadowRoot) == null ? void 0 : _existingAnnouncer_shadowRoot.childNodes[0]) { - return existingAnnouncer.shadowRoot.childNodes[0]; - } else { - const container = document.createElement(ANNOUNCER_TYPE); - container.style.cssText = "position:absolute"; - const announcer = document.createElement("div"); - announcer.setAttribute("aria-live", "assertive"); - announcer.setAttribute("id", ANNOUNCER_ID); - announcer.setAttribute("role", "alert"); - announcer.style.cssText = "position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal"; - // Use shadow DOM here to avoid any potential CSS bleed - const shadow = container.attachShadow({ - mode: "open" - }); - shadow.appendChild(announcer); - document.body.appendChild(container); - return announcer; - } -} -function AppRouterAnnouncer(param) { - let { tree } = param; - const [portalNode, setPortalNode] = (0, _react.useState)(null); - (0, _react.useEffect)(()=>{ - const announcer = getAnnouncerNode(); - setPortalNode(announcer); - return ()=>{ - const container = document.getElementsByTagName(ANNOUNCER_TYPE)[0]; - if (container == null ? void 0 : container.isConnected) { - document.body.removeChild(container); - } - }; - }, []); - const [routeAnnouncement, setRouteAnnouncement] = (0, _react.useState)(""); - const previousTitle = (0, _react.useRef)(); - (0, _react.useEffect)(()=>{ - let currentTitle = ""; - if (document.title) { - currentTitle = document.title; - } else { - const pageHeader = document.querySelector("h1"); - if (pageHeader) { - currentTitle = pageHeader.innerText || pageHeader.textContent || ""; - } - } - // Only announce the title change, but not for the first load because screen - // readers do that automatically. - if (typeof previousTitle.current !== "undefined") { - setRouteAnnouncement(currentTitle); - } - previousTitle.current = currentTitle; - }, [ - tree - ]); - return portalNode ? /*#__PURE__*/ (0, _reactdom.createPortal)(routeAnnouncement, portalNode) : null; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=app-router-announcer.js.map - - -/***/ }), - -/***/ 281: -/***/ ((module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - RSC: function() { - return RSC; - }, - ACTION: function() { - return ACTION; - }, - NEXT_ROUTER_STATE_TREE: function() { - return NEXT_ROUTER_STATE_TREE; - }, - NEXT_ROUTER_PREFETCH: function() { - return NEXT_ROUTER_PREFETCH; - }, - NEXT_URL: function() { - return NEXT_URL; - }, - FETCH_CACHE_HEADER: function() { - return FETCH_CACHE_HEADER; - }, - RSC_CONTENT_TYPE_HEADER: function() { - return RSC_CONTENT_TYPE_HEADER; - }, - RSC_VARY_HEADER: function() { - return RSC_VARY_HEADER; - }, - FLIGHT_PARAMETERS: function() { - return FLIGHT_PARAMETERS; - } -}); -const RSC = "RSC"; -const ACTION = "Next-Action"; -const NEXT_ROUTER_STATE_TREE = "Next-Router-State-Tree"; -const NEXT_ROUTER_PREFETCH = "Next-Router-Prefetch"; -const NEXT_URL = "Next-Url"; -const FETCH_CACHE_HEADER = "x-vercel-sc-headers"; -const RSC_CONTENT_TYPE_HEADER = "text/x-component; charset=utf-8"; -const RSC_VARY_HEADER = RSC + ", " + NEXT_ROUTER_STATE_TREE + ", " + NEXT_ROUTER_PREFETCH; -const FLIGHT_PARAMETERS = [ - [ - RSC - ], - [ - NEXT_ROUTER_STATE_TREE - ], - [ - NEXT_ROUTER_PREFETCH - ] -]; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=app-router-headers.js.map - - -/***/ }), - -/***/ 125: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - getServerActionDispatcher: function() { - return getServerActionDispatcher; - }, - urlToUrlWithoutFlightMarker: function() { - return urlToUrlWithoutFlightMarker; - }, - default: function() { - return AppRouter; - } -}); -const _interop_require_wildcard = __webpack_require__(1113); -const _react = /*#__PURE__*/ _interop_require_wildcard._(__webpack_require__(8038)); -const _approutercontext = __webpack_require__(3280); -const _routerreducer = __webpack_require__(5192); -const _routerreducertypes = __webpack_require__(549); -const _createhreffromurl = __webpack_require__(8253); -const _hooksclientcontext = __webpack_require__(9274); -const _usereducerwithdevtools = __webpack_require__(9051); -const _errorboundary = __webpack_require__(1522); -const _createinitialrouterstate = __webpack_require__(3558); -const _isbot = __webpack_require__(1897); -const _addbasepath = __webpack_require__(739); -const _approuterannouncer = __webpack_require__(4275); -const _redirectboundary = __webpack_require__(606); -const _notfoundboundary = __webpack_require__(7944); -const _findheadincache = __webpack_require__(7997); -const _infinitepromise = __webpack_require__(6479); -const isServer = "undefined" === "undefined"; -// Ensure the initialParallelRoutes are not combined because of double-rendering in the browser with Strict Mode. -let initialParallelRoutes = isServer ? null : new Map(); -let globalServerActionDispatcher = null; -function getServerActionDispatcher() { - return globalServerActionDispatcher; -} -function urlToUrlWithoutFlightMarker(url) { - const urlWithoutFlightParameters = new URL(url, location.origin); - // TODO-APP: handle .rsc for static export case - return urlWithoutFlightParameters; -} -const HotReloader = true ? null : 0; -function isExternalURL(url) { - return url.origin !== window.location.origin; -} -function HistoryUpdater(param) { - let { tree , pushRef , canonicalUrl , sync } = param; - // @ts-ignore TODO-APP: useInsertionEffect is available - _react.default.useInsertionEffect(()=>{ - // Identifier is shortened intentionally. - // __NA is used to identify if the history entry can be handled by the app-router. - // __N is used to identify if the history entry can be handled by the old router. - const historyState = { - __NA: true, - tree - }; - if (pushRef.pendingPush && (0, _createhreffromurl.createHrefFromUrl)(new URL(window.location.href)) !== canonicalUrl) { - // This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry. - pushRef.pendingPush = false; - window.history.pushState(historyState, "", canonicalUrl); - } else { - window.history.replaceState(historyState, "", canonicalUrl); - } - sync(); - }, [ - tree, - pushRef, - canonicalUrl, - sync - ]); - return null; -} -/** - * The global router that wraps the application components. - */ function Router(param) { - let { initialHead , initialTree , initialCanonicalUrl , children , assetPrefix , notFound , notFoundStyles , asNotFound } = param; - const initialState = (0, _react.useMemo)(()=>(0, _createinitialrouterstate.createInitialRouterState)({ - children, - initialCanonicalUrl, - initialTree, - initialParallelRoutes, - isServer, - location: !isServer ? window.location : null, - initialHead - }), [ - children, - initialCanonicalUrl, - initialTree, - initialHead - ]); - const [{ tree , cache , prefetchCache , pushRef , focusAndScrollRef , canonicalUrl , nextUrl }, dispatch, sync] = (0, _usereducerwithdevtools.useReducerWithReduxDevtools)(_routerreducer.reducer, initialState); - (0, _react.useEffect)(()=>{ - // Ensure initialParallelRoutes is cleaned up from memory once it's used. - initialParallelRoutes = null; - }, []); - // Add memoized pathname/query for useSearchParams and usePathname. - const { searchParams , pathname } = (0, _react.useMemo)(()=>{ - const url = new URL(canonicalUrl, true ? "http://n" : 0); - return { - // This is turned into a readonly class in `useSearchParams` - searchParams: url.searchParams, - pathname: url.pathname - }; - }, [ - canonicalUrl - ]); - /** - * Server response that only patches the cache and tree. - */ const changeByServerResponse = (0, _react.useCallback)((previousTree, flightData, overrideCanonicalUrl)=>{ - _react.default.startTransition(()=>{ - dispatch({ - type: _routerreducertypes.ACTION_SERVER_PATCH, - flightData, - previousTree, - overrideCanonicalUrl, - cache: { - status: _approutercontext.CacheStates.LAZY_INITIALIZED, - data: null, - subTreeData: null, - parallelRoutes: new Map() - }, - mutable: {} - }); - }); - }, [ - dispatch - ]); - const navigate = (0, _react.useCallback)((href, navigateType, forceOptimisticNavigation)=>{ - const url = new URL((0, _addbasepath.addBasePath)(href), location.origin); - return dispatch({ - type: _routerreducertypes.ACTION_NAVIGATE, - url, - isExternalUrl: isExternalURL(url), - locationSearch: location.search, - forceOptimisticNavigation, - navigateType, - cache: { - status: _approutercontext.CacheStates.LAZY_INITIALIZED, - data: null, - subTreeData: null, - parallelRoutes: new Map() - }, - mutable: {} - }); - }, [ - dispatch - ]); - const serverActionDispatcher = (0, _react.useCallback)((actionPayload)=>{ - _react.default.startTransition(()=>{ - dispatch({ - ...actionPayload, - type: _routerreducertypes.ACTION_SERVER_ACTION, - mutable: {}, - navigate, - changeByServerResponse - }); - }); - }, [ - changeByServerResponse, - dispatch, - navigate - ]); - globalServerActionDispatcher = serverActionDispatcher; - /** - * The app router that is exposed through `useRouter`. It's only concerned with dispatching actions to the reducer, does not hold state. - */ const appRouter = (0, _react.useMemo)(()=>{ - const routerInstance = { - back: ()=>window.history.back(), - forward: ()=>window.history.forward(), - prefetch: (href, options)=>{ - // If prefetch has already been triggered, don't trigger it again. - if ((0, _isbot.isBot)(window.navigator.userAgent)) { - return; - } - const url = new URL((0, _addbasepath.addBasePath)(href), location.origin); - // External urls can't be prefetched in the same way. - if (isExternalURL(url)) { - return; - } - // @ts-ignore startTransition exists - _react.default.startTransition(()=>{ - var _options_kind; - dispatch({ - type: _routerreducertypes.ACTION_PREFETCH, - url, - kind: (_options_kind = options == null ? void 0 : options.kind) != null ? _options_kind : _routerreducertypes.PrefetchKind.FULL - }); - }); - }, - replace: (href, options)=>{ - if (options === void 0) options = {}; - // @ts-ignore startTransition exists - _react.default.startTransition(()=>{ - navigate(href, "replace", Boolean(options.forceOptimisticNavigation)); - }); - }, - push: (href, options)=>{ - if (options === void 0) options = {}; - // @ts-ignore startTransition exists - _react.default.startTransition(()=>{ - navigate(href, "push", Boolean(options.forceOptimisticNavigation)); - }); - }, - refresh: ()=>{ - // @ts-ignore startTransition exists - _react.default.startTransition(()=>{ - dispatch({ - type: _routerreducertypes.ACTION_REFRESH, - cache: { - status: _approutercontext.CacheStates.LAZY_INITIALIZED, - data: null, - subTreeData: null, - parallelRoutes: new Map() - }, - mutable: {}, - origin: window.location.origin - }); - }); - }, - // @ts-ignore we don't want to expose this method at all - fastRefresh: ()=>{ - if (true) { - throw new Error("fastRefresh can only be used in development mode. Please use refresh instead."); - } else {} - } - }; - return routerInstance; - }, [ - dispatch, - navigate - ]); - (0, _react.useEffect)(()=>{ - // Exists for debugging purposes. Don't use in application code. - if (window.next) { - window.next.router = appRouter; - } - }, [ - appRouter - ]); - (0, _react.useEffect)(()=>{ - // Add `window.nd` for debugging purposes. - // This is not meant for use in applications as concurrent rendering will affect the cache/tree/router. - // @ts-ignore this is for debugging - window.nd = { - router: appRouter, - cache, - prefetchCache, - tree - }; - }, [ - appRouter, - cache, - prefetchCache, - tree - ]); - // When mpaNavigation flag is set do a hard navigation to the new url. - // Infinitely suspend because we don't actually want to rerender any child - // components with the new URL and any entangled state updates shouldn't - // commit either (eg: useTransition isPending should stay true until the page - // unloads). - // - // This is a side effect in render. Don't try this at home, kids. It's - // probably safe because we know this is a singleton component and it's never - // in <Offscreen>. At least I hope so. (It will run twice in dev strict mode, - // but that's... fine?) - if (pushRef.mpaNavigation) { - const location1 = window.location; - if (pushRef.pendingPush) { - location1.assign(canonicalUrl); - } else { - location1.replace(canonicalUrl); - } - // TODO-APP: Should we listen to navigateerror here to catch failed - // navigations somehow? And should we call window.stop() if a SPA navigation - // should interrupt an MPA one? - (0, _react.use)((0, _infinitepromise.createInfinitePromise)()); - } - /** - * Handle popstate event, this is used to handle back/forward in the browser. - * By default dispatches ACTION_RESTORE, however if the history entry was not pushed/replaced by app-router it will reload the page. - * That case can happen when the old router injected the history entry. - */ const onPopState = (0, _react.useCallback)((param)=>{ - let { state } = param; - if (!state) { - // TODO-APP: this case only happens when pushState/replaceState was called outside of Next.js. It should probably reload the page in this case. - return; - } - // This case happens when the history entry was pushed by the `pages` router. - if (!state.__NA) { - window.location.reload(); - return; - } - // @ts-ignore useTransition exists - // TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously - // Without startTransition works if the cache is there for this path - _react.default.startTransition(()=>{ - dispatch({ - type: _routerreducertypes.ACTION_RESTORE, - url: new URL(window.location.href), - tree: state.tree - }); - }); - }, [ - dispatch - ]); - // Register popstate event to call onPopstate. - (0, _react.useEffect)(()=>{ - window.addEventListener("popstate", onPopState); - return ()=>{ - window.removeEventListener("popstate", onPopState); - }; - }, [ - onPopState - ]); - const head = (0, _react.useMemo)(()=>{ - return (0, _findheadincache.findHeadInCache)(cache, tree[1]); - }, [ - cache, - tree - ]); - const content = /*#__PURE__*/ _react.default.createElement(_notfoundboundary.NotFoundBoundary, { - notFound: notFound, - notFoundStyles: notFoundStyles, - asNotFound: asNotFound - }, /*#__PURE__*/ _react.default.createElement(_redirectboundary.RedirectBoundary, null, head, cache.subTreeData, /*#__PURE__*/ _react.default.createElement(_approuterannouncer.AppRouterAnnouncer, { - tree: tree - }))); - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(HistoryUpdater, { - tree: tree, - pushRef: pushRef, - canonicalUrl: canonicalUrl, - sync: sync - }), /*#__PURE__*/ _react.default.createElement(_hooksclientcontext.PathnameContext.Provider, { - value: pathname - }, /*#__PURE__*/ _react.default.createElement(_hooksclientcontext.SearchParamsContext.Provider, { - value: searchParams - }, /*#__PURE__*/ _react.default.createElement(_approutercontext.GlobalLayoutRouterContext.Provider, { - value: { - changeByServerResponse, - tree, - focusAndScrollRef, - nextUrl - } - }, /*#__PURE__*/ _react.default.createElement(_approutercontext.AppRouterContext.Provider, { - value: appRouter - }, /*#__PURE__*/ _react.default.createElement(_approutercontext.LayoutRouterContext.Provider, { - value: { - childNodes: cache.parallelRoutes, - tree: tree, - // Root node always has `url` - // Provided in AppTreeContext to ensure it can be overwritten in layout-router - url: canonicalUrl - } - }, HotReloader ? /*#__PURE__*/ _react.default.createElement(HotReloader, { - assetPrefix: assetPrefix - }, content) : content)))))); -} -function AppRouter(props) { - const { globalErrorComponent , ...rest } = props; - return /*#__PURE__*/ _react.default.createElement(_errorboundary.ErrorBoundary, { - errorComponent: globalErrorComponent - }, /*#__PURE__*/ _react.default.createElement(Router, rest)); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=app-router.js.map - - -/***/ }), - -/***/ 2594: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "bailoutToClientRendering", ({ - enumerable: true, - get: function() { - return bailoutToClientRendering; - } -})); -const _dynamicnossr = __webpack_require__(701); -const _staticgenerationasyncstorage = __webpack_require__(94); -function bailoutToClientRendering() { - const staticGenerationStore = _staticgenerationasyncstorage.staticGenerationAsyncStorage.getStore(); - if (staticGenerationStore == null ? void 0 : staticGenerationStore.forceStatic) { - return true; - } - if (staticGenerationStore == null ? void 0 : staticGenerationStore.isStaticGeneration) { - (0, _dynamicnossr.suspense)(); - } - return false; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=bailout-to-client-rendering.js.map - - -/***/ }), - -/***/ 5078: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "clientHookInServerComponentError", ({ - enumerable: true, - get: function() { - return clientHookInServerComponentError; - } -})); -const _interop_require_default = __webpack_require__(5967); -const _react = /*#__PURE__*/ _interop_require_default._(__webpack_require__(8038)); -function clientHookInServerComponentError(hookName) { - if (false) {} -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=client-hook-in-server-component-error.js.map - - -/***/ }), - -/***/ 1522: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - ErrorBoundaryHandler: function() { - return ErrorBoundaryHandler; - }, - default: function() { - return GlobalError; - }, - ErrorBoundary: function() { - return ErrorBoundary; - } -}); -const _interop_require_default = __webpack_require__(5967); -const _react = /*#__PURE__*/ _interop_require_default._(__webpack_require__(8038)); -const _navigation = __webpack_require__(5171); -const styles = { - error: { - // https://github.com/sindresorhus/modern-normalize/blob/main/modern-normalize.css#L38-L52 - fontFamily: 'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"', - height: "100vh", - textAlign: "center", - display: "flex", - flexDirection: "column", - alignItems: "center", - justifyContent: "center" - }, - desc: { - textAlign: "left" - }, - text: { - fontSize: "14px", - fontWeight: 400, - lineHeight: "3em", - margin: 0 - } -}; -class ErrorBoundaryHandler extends _react.default.Component { - static getDerivedStateFromError(error) { - return { - error - }; - } - static getDerivedStateFromProps(props, state) { - /** - * Handles reset of the error boundary when a navigation happens. - * Ensures the error boundary does not stay enabled when navigating to a new page. - * Approach of setState in render is safe as it checks the previous pathname and then overrides - * it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders - */ if (props.pathname !== state.previousPathname && state.error) { - return { - error: null, - previousPathname: props.pathname - }; - } - return { - error: state.error, - previousPathname: props.pathname - }; - } - render() { - if (this.state.error) { - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, this.props.errorStyles, /*#__PURE__*/ _react.default.createElement(this.props.errorComponent, { - error: this.state.error, - reset: this.reset - })); - } - return this.props.children; - } - constructor(props){ - super(props); - this.reset = ()=>{ - this.setState({ - error: null - }); - }; - this.state = { - error: null, - previousPathname: this.props.pathname - }; - } -} -function GlobalError(param) { - let { error } = param; - return /*#__PURE__*/ _react.default.createElement("html", null, /*#__PURE__*/ _react.default.createElement("head", null), /*#__PURE__*/ _react.default.createElement("body", null, /*#__PURE__*/ _react.default.createElement("div", { - style: styles.error - }, /*#__PURE__*/ _react.default.createElement("div", { - style: styles.desc - }, /*#__PURE__*/ _react.default.createElement("h2", { - style: styles.text - }, "Application error: a client-side exception has occurred (see the browser console for more information)."), (error == null ? void 0 : error.digest) && /*#__PURE__*/ _react.default.createElement("p", { - style: styles.text - }, "Digest: " + error.digest))))); -} -function ErrorBoundary(param) { - let { errorComponent , errorStyles , children } = param; - const pathname = (0, _navigation.usePathname)(); - if (errorComponent) { - return /*#__PURE__*/ _react.default.createElement(ErrorBoundaryHandler, { - pathname: pathname, - errorComponent: errorComponent, - errorStyles: errorStyles - }, children); - } - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, children); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=error-boundary.js.map - - -/***/ }), - -/***/ 8340: -/***/ ((module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - DYNAMIC_ERROR_CODE: function() { - return DYNAMIC_ERROR_CODE; - }, - DynamicServerError: function() { - return DynamicServerError; - } -}); -const DYNAMIC_ERROR_CODE = "DYNAMIC_SERVER_USAGE"; -class DynamicServerError extends Error { - constructor(type){ - super("Dynamic server usage: " + type); - this.digest = DYNAMIC_ERROR_CODE; - } -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=hooks-server-context.js.map - - -/***/ }), - -/***/ 6479: -/***/ ((module, exports) => { - -"use strict"; -/** - * Used to cache in createInfinitePromise - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createInfinitePromise", ({ - enumerable: true, - get: function() { - return createInfinitePromise; - } -})); -let infinitePromise; -function createInfinitePromise() { - if (!infinitePromise) { - // Only create the Promise once - infinitePromise = new Promise(()=>{ - // This is used to debug when the rendering is never updated. - // setTimeout(() => { - // infinitePromise = new Error('Infinite promise') - // resolve() - // }, 5000) - }); - } - return infinitePromise; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=infinite-promise.js.map - - -/***/ }), - -/***/ 6249: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "default", ({ - enumerable: true, - get: function() { - return OuterLayoutRouter; - } -})); -const _interop_require_default = __webpack_require__(5967); -const _interop_require_wildcard = __webpack_require__(1113); -const _react = /*#__PURE__*/ _interop_require_wildcard._(__webpack_require__(8038)); -const _reactdom = /*#__PURE__*/ _interop_require_default._(__webpack_require__(8704)); -const _approutercontext = __webpack_require__(3280); -const _fetchserverresponse = __webpack_require__(969); -const _infinitepromise = __webpack_require__(6479); -const _errorboundary = __webpack_require__(1522); -const _matchsegments = __webpack_require__(5507); -const _handlesmoothscroll = __webpack_require__(1668); -const _redirectboundary = __webpack_require__(606); -const _notfoundboundary = __webpack_require__(7944); -const _getsegmentvalue = __webpack_require__(3715); -const _createroutercachekey = __webpack_require__(5370); -/** - * Add refetch marker to router state at the point of the current layout segment. - * This ensures the response returned is not further down than the current layout segment. - */ function walkAddRefetch(segmentPathToWalk, treeToRecreate) { - if (segmentPathToWalk) { - const [segment, parallelRouteKey] = segmentPathToWalk; - const isLast = segmentPathToWalk.length === 2; - if ((0, _matchsegments.matchSegment)(treeToRecreate[0], segment)) { - if (treeToRecreate[1].hasOwnProperty(parallelRouteKey)) { - if (isLast) { - const subTree = walkAddRefetch(undefined, treeToRecreate[1][parallelRouteKey]); - return [ - treeToRecreate[0], - { - ...treeToRecreate[1], - [parallelRouteKey]: [ - subTree[0], - subTree[1], - subTree[2], - "refetch" - ] - } - ]; - } - return [ - treeToRecreate[0], - { - ...treeToRecreate[1], - [parallelRouteKey]: walkAddRefetch(segmentPathToWalk.slice(2), treeToRecreate[1][parallelRouteKey]) - } - ]; - } - } - } - return treeToRecreate; -} -// TODO-APP: Replace with new React API for finding dom nodes without a `ref` when available -/** - * Wraps ReactDOM.findDOMNode with additional logic to hide React Strict Mode warning - */ function findDOMNode(instance) { - // Tree-shake for server bundle - if (true) return null; - // Only apply strict mode warning when not in production - if (false) {} - return _reactdom.default.findDOMNode(instance); -} -const rectProperties = [ - "bottom", - "height", - "left", - "right", - "top", - "width", - "x", - "y" -]; -/** - * Check if a HTMLElement is hidden. - */ function elementCanScroll(element) { - // Uses `getBoundingClientRect` to check if the element is hidden instead of `offsetParent` - // because `offsetParent` doesn't consider document/body - const rect = element.getBoundingClientRect(); - return rectProperties.every((item)=>rect[item] === 0); -} -/** - * Check if the top corner of the HTMLElement is in the viewport. - */ function topOfElementInViewport(element, viewportHeight) { - const rect = element.getBoundingClientRect(); - return rect.top >= 0 && rect.top <= viewportHeight; -} -/** - * Find the DOM node for a hash fragment. - * If `top` the page has to scroll to the top of the page. This mirrors the browser's behavior. - * If the hash fragment is an id, the page has to scroll to the element with that id. - * If the hash fragment is a name, the page has to scroll to the first element with that name. - */ function getHashFragmentDomNode(hashFragment) { - // If the hash fragment is `top` the page has to scroll to the top of the page. - if (hashFragment === "top") { - return document.body; - } - var _document_getElementById; - // If the hash fragment is an id, the page has to scroll to the element with that id. - return (_document_getElementById = document.getElementById(hashFragment)) != null ? _document_getElementById : document.getElementsByName(hashFragment)[0]; -} -class InnerScrollAndFocusHandler extends _react.default.Component { - componentDidMount() { - this.handlePotentialScroll(); - } - componentDidUpdate() { - // Because this property is overwritten in handlePotentialScroll it's fine to always run it when true as it'll be set to false for subsequent renders. - if (this.props.focusAndScrollRef.apply) { - this.handlePotentialScroll(); - } - } - render() { - return this.props.children; - } - constructor(...args){ - super(...args); - this.handlePotentialScroll = ()=>{ - // Handle scroll and focus, it's only applied once in the first useEffect that triggers that changed. - const { focusAndScrollRef , segmentPath } = this.props; - if (focusAndScrollRef.apply) { - // segmentPaths is an array of segment paths that should be scrolled to - // if the current segment path is not in the array, the scroll is not applied - // unless the array is empty, in which case the scroll is always applied - if (focusAndScrollRef.segmentPaths.length !== 0 && !focusAndScrollRef.segmentPaths.some((scrollRefSegmentPath)=>segmentPath.every((segment, index)=>(0, _matchsegments.matchSegment)(segment, scrollRefSegmentPath[index])))) { - return; - } - let domNode = null; - const hashFragment = focusAndScrollRef.hashFragment; - if (hashFragment) { - domNode = getHashFragmentDomNode(hashFragment); - } - // `findDOMNode` is tricky because it returns just the first child if the component is a fragment. - // This already caused a bug where the first child was a <link/> in head. - if (!domNode) { - domNode = findDOMNode(this); - } - // TODO-APP: Handle the case where we couldn't select any DOM node, even higher up in the layout-router above the current segmentPath. - // If there is no DOM node this layout-router level is skipped. It'll be handled higher-up in the tree. - if (!(domNode instanceof Element)) { - return; - } - // Verify if the element is a HTMLElement and if it's visible on screen (e.g. not display: none). - // If the element is not a HTMLElement or not visible we try to select the next sibling and try again. - while(!(domNode instanceof HTMLElement) || elementCanScroll(domNode)){ - // TODO-APP: Handle the case where we couldn't select any DOM node, even higher up in the layout-router above the current segmentPath. - // No siblings found that are visible so we handle scroll higher up in the tree instead. - if (domNode.nextElementSibling === null) { - return; - } - domNode = domNode.nextElementSibling; - } - // State is mutated to ensure that the focus and scroll is applied only once. - focusAndScrollRef.apply = false; - focusAndScrollRef.hashFragment = null; - focusAndScrollRef.segmentPaths = []; - (0, _handlesmoothscroll.handleSmoothScroll)(()=>{ - // In case of hash scroll we need to scroll to the top of the element - if (hashFragment) { - window.scrollTo(0, domNode.offsetTop); - return; - } - // Store the current viewport height because reading `clientHeight` causes a reflow, - // and it won't change during this function. - const htmlElement = document.documentElement; - const viewportHeight = htmlElement.clientHeight; - // If the element's top edge is already in the viewport, exit early. - if (topOfElementInViewport(domNode, viewportHeight)) { - return; - } - // Otherwise, try scrolling go the top of the document to be backward compatible with pages - // scrollIntoView() called on `<html/>` element scrolls horizontally on chrome and firefox (that shouldn't happen) - // We could use it to scroll horizontally following RTL but that also seems to be broken - it will always scroll left - // scrollLeft = 0 also seems to ignore RTL and manually checking for RTL is too much hassle so we will scroll just vertically - htmlElement.scrollTop = 0; - // Scroll to domNode if domNode is not in viewport when scrolled to top of document - if (!topOfElementInViewport(domNode, viewportHeight)) { - domNode.scrollIntoView(); - } - }, { - // We will force layout by querying domNode position - dontForceLayout: true - }); - // Set focus on the element - domNode.focus(); - } - }; - } -} -function ScrollAndFocusHandler(param) { - let { segmentPath , children } = param; - const context = (0, _react.useContext)(_approutercontext.GlobalLayoutRouterContext); - if (!context) { - throw new Error("invariant global layout router not mounted"); - } - return /*#__PURE__*/ _react.default.createElement(InnerScrollAndFocusHandler, { - segmentPath: segmentPath, - focusAndScrollRef: context.focusAndScrollRef - }, children); -} -/** - * InnerLayoutRouter handles rendering the provided segment based on the cache. - */ function InnerLayoutRouter(param) { - let { parallelRouterKey , url , childNodes , childProp , segmentPath , tree , // isActive, - cacheKey } = param; - const context = (0, _react.useContext)(_approutercontext.GlobalLayoutRouterContext); - if (!context) { - throw new Error("invariant global layout router not mounted"); - } - const { changeByServerResponse , tree: fullTree } = context; - // Read segment path from the parallel router cache node. - let childNode = childNodes.get(cacheKey); - // If childProp is available this means it's the Flight / SSR case. - if (childProp && // TODO-APP: verify if this can be null based on user code - childProp.current !== null) { - if (!childNode) { - // Add the segment's subTreeData to the cache. - // This writes to the cache when there is no item in the cache yet. It never *overwrites* existing cache items which is why it's safe in concurrent mode. - childNodes.set(cacheKey, { - status: _approutercontext.CacheStates.READY, - data: null, - subTreeData: childProp.current, - parallelRoutes: new Map() - }); - // In the above case childNode was set on childNodes, so we have to get it from the cacheNodes again. - childNode = childNodes.get(cacheKey); - } else { - if (childNode.status === _approutercontext.CacheStates.LAZY_INITIALIZED) { - // @ts-expect-error we're changing it's type! - childNode.status = _approutercontext.CacheStates.READY; - // @ts-expect-error - childNode.subTreeData = childProp.current; - } - } - } - // When childNode is not available during rendering client-side we need to fetch it from the server. - if (!childNode || childNode.status === _approutercontext.CacheStates.LAZY_INITIALIZED) { - /** - * Router state with refetch marker added - */ // TODO-APP: remove '' - const refetchTree = walkAddRefetch([ - "", - ...segmentPath - ], fullTree); - /** - * Flight data fetch kicked off during render and put into the cache. - */ childNodes.set(cacheKey, { - status: _approutercontext.CacheStates.DATA_FETCH, - data: (0, _fetchserverresponse.fetchServerResponse)(new URL(url, location.origin), refetchTree, context.nextUrl), - subTreeData: null, - head: childNode && childNode.status === _approutercontext.CacheStates.LAZY_INITIALIZED ? childNode.head : undefined, - parallelRoutes: childNode && childNode.status === _approutercontext.CacheStates.LAZY_INITIALIZED ? childNode.parallelRoutes : new Map() - }); - // In the above case childNode was set on childNodes, so we have to get it from the cacheNodes again. - childNode = childNodes.get(cacheKey); - } - // This case should never happen so it throws an error. It indicates there's a bug in the Next.js. - if (!childNode) { - throw new Error("Child node should always exist"); - } - // This case should never happen so it throws an error. It indicates there's a bug in the Next.js. - if (childNode.subTreeData && childNode.data) { - throw new Error("Child node should not have both subTreeData and data"); - } - // If cache node has a data request we have to unwrap response by `use` and update the cache. - if (childNode.data) { - /** - * Flight response data - */ // When the data has not resolved yet `use` will suspend here. - const [flightData, overrideCanonicalUrl] = (0, _react.use)(childNode.data); - // Handle case when navigating to page in `pages` from `app` - if (typeof flightData === "string") { - window.location.href = url; - return null; - } - // segmentPath from the server does not match the layout's segmentPath - childNode.data = null; - // setTimeout is used to start a new transition during render, this is an intentional hack around React. - setTimeout(()=>{ - // @ts-ignore startTransition exists - _react.default.startTransition(()=>{ - changeByServerResponse(fullTree, flightData, overrideCanonicalUrl); - }); - }); - // Suspend infinitely as `changeByServerResponse` will cause a different part of the tree to be rendered. - (0, _react.use)((0, _infinitepromise.createInfinitePromise)()); - } - // If cache node has no subTreeData and no data request we have to infinitely suspend as the data will likely flow in from another place. - // TODO-APP: double check users can't return null in a component that will kick in here. - if (!childNode.subTreeData) { - (0, _react.use)((0, _infinitepromise.createInfinitePromise)()); - } - const subtree = /*#__PURE__*/ _react.default.createElement(_approutercontext.LayoutRouterContext.Provider, { - value: { - tree: tree[1][parallelRouterKey], - childNodes: childNode.parallelRoutes, - // TODO-APP: overriding of url for parallel routes - url: url - } - }, childNode.subTreeData); - // Ensure root layout is not wrapped in a div as the root layout renders `<html>` - return subtree; -} -/** - * Renders suspense boundary with the provided "loading" property as the fallback. - * If no loading property is provided it renders the children without a suspense boundary. - */ function LoadingBoundary(param) { - let { children , loading , loadingStyles , hasLoading } = param; - if (hasLoading) { - return /*#__PURE__*/ _react.default.createElement(_react.default.Suspense, { - fallback: /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, loadingStyles, loading) - }, children); - } - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, children); -} -function OuterLayoutRouter(param) { - let { parallelRouterKey , segmentPath , childProp , error , errorStyles , templateStyles , loading , loadingStyles , hasLoading , template , notFound , notFoundStyles , asNotFound , styles } = param; - const context = (0, _react.useContext)(_approutercontext.LayoutRouterContext); - if (!context) { - throw new Error("invariant expected layout router to be mounted"); - } - const { childNodes , tree , url } = context; - // Get the current parallelRouter cache node - let childNodesForParallelRouter = childNodes.get(parallelRouterKey); - // If the parallel router cache node does not exist yet, create it. - // This writes to the cache when there is no item in the cache yet. It never *overwrites* existing cache items which is why it's safe in concurrent mode. - if (!childNodesForParallelRouter) { - childNodes.set(parallelRouterKey, new Map()); - childNodesForParallelRouter = childNodes.get(parallelRouterKey); - } - // Get the active segment in the tree - // The reason arrays are used in the data format is that these are transferred from the server to the browser so it's optimized to save bytes. - const treeSegment = tree[1][parallelRouterKey][0]; - const childPropSegment = childProp.segment; - // If segment is an array it's a dynamic route and we want to read the dynamic route value as the segment to get from the cache. - const currentChildSegmentValue = (0, _getsegmentvalue.getSegmentValue)(treeSegment); - /** - * Decides which segments to keep rendering, all segments that are not active will be wrapped in `<Offscreen>`. - */ // TODO-APP: Add handling of `<Offscreen>` when it's available. - const preservedSegments = [ - treeSegment - ]; - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, styles, preservedSegments.map((preservedSegment)=>{ - const isChildPropSegment = (0, _matchsegments.matchSegment)(preservedSegment, childPropSegment); - const preservedSegmentValue = (0, _getsegmentvalue.getSegmentValue)(preservedSegment); - const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(preservedSegment); - return(/* - - Error boundary - - Only renders error boundary if error component is provided. - - Rendered for each segment to ensure they have their own error state. - - Loading boundary - - Only renders suspense boundary if loading components is provided. - - Rendered for each segment to ensure they have their own loading state. - - Passed to the router during rendering to ensure it can be immediately rendered when suspending on a Flight fetch. - */ /*#__PURE__*/ _react.default.createElement(_approutercontext.TemplateContext.Provider, { - key: (0, _createroutercachekey.createRouterCacheKey)(preservedSegment, true), - value: /*#__PURE__*/ _react.default.createElement(ScrollAndFocusHandler, { - segmentPath: segmentPath - }, /*#__PURE__*/ _react.default.createElement(_errorboundary.ErrorBoundary, { - errorComponent: error, - errorStyles: errorStyles - }, /*#__PURE__*/ _react.default.createElement(LoadingBoundary, { - hasLoading: hasLoading, - loading: loading, - loadingStyles: loadingStyles - }, /*#__PURE__*/ _react.default.createElement(_notfoundboundary.NotFoundBoundary, { - notFound: notFound, - notFoundStyles: notFoundStyles, - asNotFound: asNotFound - }, /*#__PURE__*/ _react.default.createElement(_redirectboundary.RedirectBoundary, null, /*#__PURE__*/ _react.default.createElement(InnerLayoutRouter, { - parallelRouterKey: parallelRouterKey, - url: url, - tree: tree, - childNodes: childNodesForParallelRouter, - childProp: isChildPropSegment ? childProp : null, - segmentPath: segmentPath, - cacheKey: cacheKey, - isActive: currentChildSegmentValue === preservedSegmentValue - })))))) - }, /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, templateStyles, template))); - })); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=layout-router.js.map - - -/***/ }), - -/***/ 5507: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - matchSegment: function() { - return matchSegment; - }, - canSegmentBeOverridden: function() { - return canSegmentBeOverridden; - } -}); -const _getsegmentparam = __webpack_require__(1090); -const matchSegment = (existingSegment, segment)=>{ - // Common case: segment is just a string - if (typeof existingSegment === "string" && typeof segment === "string") { - return existingSegment === segment; - } - // Dynamic parameter case: segment is an array with param/value. Both param and value are compared. - if (Array.isArray(existingSegment) && Array.isArray(segment)) { - return existingSegment[0] === segment[0] && existingSegment[1] === segment[1]; - } - return false; -}; -const canSegmentBeOverridden = (existingSegment, segment)=>{ - var _getSegmentParam; - if (Array.isArray(existingSegment) || !Array.isArray(segment)) { - return false; - } - return ((_getSegmentParam = (0, _getsegmentparam.getSegmentParam)(existingSegment)) == null ? void 0 : _getSegmentParam.param) === segment[0]; -}; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=match-segments.js.map - - -/***/ }), - -/***/ 5171: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; -// useLayoutSegments() // Only the segments for the current place. ['children', 'dashboard', 'children', 'integrations'] -> /dashboard/integrations (/dashboard/layout.js would get ['children', 'dashboard', 'children', 'integrations']) - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - ReadonlyURLSearchParams: function() { - return ReadonlyURLSearchParams; - }, - useSearchParams: function() { - return useSearchParams; - }, - usePathname: function() { - return usePathname; - }, - ServerInsertedHTMLContext: function() { - return _serverinsertedhtml.ServerInsertedHTMLContext; - }, - useServerInsertedHTML: function() { - return _serverinsertedhtml.useServerInsertedHTML; - }, - useRouter: function() { - return useRouter; - }, - useParams: function() { - return useParams; - }, - useSelectedLayoutSegments: function() { - return useSelectedLayoutSegments; - }, - useSelectedLayoutSegment: function() { - return useSelectedLayoutSegment; - }, - redirect: function() { - return _redirect.redirect; - }, - notFound: function() { - return _notfound.notFound; - } -}); -const _react = __webpack_require__(8038); -const _approutercontext = __webpack_require__(3280); -const _hooksclientcontext = __webpack_require__(9274); -const _clienthookinservercomponenterror = __webpack_require__(5078); -const _getsegmentvalue = __webpack_require__(3715); -const _serverinsertedhtml = __webpack_require__(3349); -const _redirect = __webpack_require__(6932); -const _notfound = __webpack_require__(8424); -const INTERNAL_URLSEARCHPARAMS_INSTANCE = Symbol("internal for urlsearchparams readonly"); -function readonlyURLSearchParamsError() { - return new Error("ReadonlyURLSearchParams cannot be modified"); -} -class ReadonlyURLSearchParams { - [Symbol.iterator]() { - return this[INTERNAL_URLSEARCHPARAMS_INSTANCE][Symbol.iterator](); - } - append() { - throw readonlyURLSearchParamsError(); - } - delete() { - throw readonlyURLSearchParamsError(); - } - set() { - throw readonlyURLSearchParamsError(); - } - sort() { - throw readonlyURLSearchParamsError(); - } - constructor(urlSearchParams){ - this[INTERNAL_URLSEARCHPARAMS_INSTANCE] = urlSearchParams; - this.entries = urlSearchParams.entries.bind(urlSearchParams); - this.forEach = urlSearchParams.forEach.bind(urlSearchParams); - this.get = urlSearchParams.get.bind(urlSearchParams); - this.getAll = urlSearchParams.getAll.bind(urlSearchParams); - this.has = urlSearchParams.has.bind(urlSearchParams); - this.keys = urlSearchParams.keys.bind(urlSearchParams); - this.values = urlSearchParams.values.bind(urlSearchParams); - this.toString = urlSearchParams.toString.bind(urlSearchParams); - } -} -function useSearchParams() { - (0, _clienthookinservercomponenterror.clientHookInServerComponentError)("useSearchParams"); - const searchParams = (0, _react.useContext)(_hooksclientcontext.SearchParamsContext); - // In the case where this is `null`, the compat types added in - // `next-env.d.ts` will add a new overload that changes the return type to - // include `null`. - const readonlySearchParams = (0, _react.useMemo)(()=>{ - if (!searchParams) { - // When the router is not ready in pages, we won't have the search params - // available. - return null; - } - return new ReadonlyURLSearchParams(searchParams); - }, [ - searchParams - ]); - if (true) { - // AsyncLocalStorage should not be included in the client bundle. - const { bailoutToClientRendering } = __webpack_require__(2594); - if (bailoutToClientRendering()) { - // TODO-APP: handle dynamic = 'force-static' here and on the client - return readonlySearchParams; - } - } - return readonlySearchParams; -} -function usePathname() { - (0, _clienthookinservercomponenterror.clientHookInServerComponentError)("usePathname"); - // In the case where this is `null`, the compat types added in `next-env.d.ts` - // will add a new overload that changes the return type to include `null`. - return (0, _react.useContext)(_hooksclientcontext.PathnameContext); -} -function useRouter() { - (0, _clienthookinservercomponenterror.clientHookInServerComponentError)("useRouter"); - const router = (0, _react.useContext)(_approutercontext.AppRouterContext); - if (router === null) { - throw new Error("invariant expected app router to be mounted"); - } - return router; -} -// this function performs a depth-first search of the tree to find the selected -// params -function getSelectedParams(tree, params) { - if (params === void 0) params = {}; - const parallelRoutes = tree[1]; - for (const parallelRoute of Object.values(parallelRoutes)){ - const segment = parallelRoute[0]; - const isDynamicParameter = Array.isArray(segment); - const segmentValue = isDynamicParameter ? segment[1] : segment; - if (!segmentValue || segmentValue.startsWith("__PAGE__")) continue; - if (isDynamicParameter) { - params[segment[0]] = segment[1]; - } - params = getSelectedParams(parallelRoute, params); - } - return params; -} -function useParams() { - (0, _clienthookinservercomponenterror.clientHookInServerComponentError)("useParams"); - const globalLayoutRouterContext = (0, _react.useContext)(_approutercontext.GlobalLayoutRouterContext); - if (!globalLayoutRouterContext) { - // This only happens in `pages`. Type is overwritten in navigation.d.ts - return null; - } - return getSelectedParams(globalLayoutRouterContext.tree); -} -// TODO-APP: handle parallel routes -/** - * Get the canonical parameters from the current level to the leaf node. - */ function getSelectedLayoutSegmentPath(tree, parallelRouteKey, first, segmentPath) { - if (first === void 0) first = true; - if (segmentPath === void 0) segmentPath = []; - let node; - if (first) { - // Use the provided parallel route key on the first parallel route - node = tree[1][parallelRouteKey]; - } else { - // After first parallel route prefer children, if there's no children pick the first parallel route. - const parallelRoutes = tree[1]; - var _parallelRoutes_children; - node = (_parallelRoutes_children = parallelRoutes.children) != null ? _parallelRoutes_children : Object.values(parallelRoutes)[0]; - } - if (!node) return segmentPath; - const segment = node[0]; - const segmentValue = (0, _getsegmentvalue.getSegmentValue)(segment); - if (!segmentValue || segmentValue.startsWith("__PAGE__")) return segmentPath; - segmentPath.push(segmentValue); - return getSelectedLayoutSegmentPath(node, parallelRouteKey, false, segmentPath); -} -function useSelectedLayoutSegments(parallelRouteKey) { - if (parallelRouteKey === void 0) parallelRouteKey = "children"; - (0, _clienthookinservercomponenterror.clientHookInServerComponentError)("useSelectedLayoutSegments"); - const { tree } = (0, _react.useContext)(_approutercontext.LayoutRouterContext); - return getSelectedLayoutSegmentPath(tree, parallelRouteKey); -} -function useSelectedLayoutSegment(parallelRouteKey) { - if (parallelRouteKey === void 0) parallelRouteKey = "children"; - (0, _clienthookinservercomponenterror.clientHookInServerComponentError)("useSelectedLayoutSegment"); - const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey); - if (selectedLayoutSegments.length === 0) { - return null; - } - return selectedLayoutSegments[0]; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=navigation.js.map - - -/***/ }), - -/***/ 7944: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "NotFoundBoundary", ({ - enumerable: true, - get: function() { - return NotFoundBoundary; - } -})); -const _interop_require_default = __webpack_require__(5967); -const _react = /*#__PURE__*/ _interop_require_default._(__webpack_require__(8038)); -const _navigation = __webpack_require__(5171); -class NotFoundErrorBoundary extends _react.default.Component { - static getDerivedStateFromError(error) { - if ((error == null ? void 0 : error.digest) === "NEXT_NOT_FOUND") { - return { - notFoundTriggered: true - }; - } - // Re-throw if error is not for 404 - throw error; - } - static getDerivedStateFromProps(props, state) { - /** - * Handles reset of the error boundary when a navigation happens. - * Ensures the error boundary does not stay enabled when navigating to a new page. - * Approach of setState in render is safe as it checks the previous pathname and then overrides - * it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders - */ if (props.pathname !== state.previousPathname && state.notFoundTriggered) { - return { - notFoundTriggered: false, - previousPathname: props.pathname - }; - } - return { - notFoundTriggered: state.notFoundTriggered, - previousPathname: props.pathname - }; - } - render() { - if (this.state.notFoundTriggered) { - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement("meta", { - name: "robots", - content: "noindex" - }), this.props.notFoundStyles, this.props.notFound); - } - return this.props.children; - } - constructor(props){ - super(props); - this.state = { - notFoundTriggered: !!props.asNotFound, - previousPathname: props.pathname - }; - } -} -function NotFoundBoundary(param) { - let { notFound , notFoundStyles , asNotFound , children } = param; - const pathname = (0, _navigation.usePathname)(); - return notFound ? /*#__PURE__*/ _react.default.createElement(NotFoundErrorBoundary, { - pathname: pathname, - notFound: notFound, - notFoundStyles: notFoundStyles, - asNotFound: asNotFound - }, children) : /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, children); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=not-found-boundary.js.map - - -/***/ }), - -/***/ 8424: -/***/ ((module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - notFound: function() { - return notFound; - }, - isNotFoundError: function() { - return isNotFoundError; - } -}); -const NOT_FOUND_ERROR_CODE = "NEXT_NOT_FOUND"; -function notFound() { - // eslint-disable-next-line no-throw-literal - const error = new Error(NOT_FOUND_ERROR_CODE); - error.digest = NOT_FOUND_ERROR_CODE; - throw error; -} -function isNotFoundError(error) { - return (error == null ? void 0 : error.digest) === NOT_FOUND_ERROR_CODE; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=not-found.js.map - - -/***/ }), - -/***/ 606: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - RedirectErrorBoundary: function() { - return RedirectErrorBoundary; - }, - RedirectBoundary: function() { - return RedirectBoundary; - } -}); -const _interop_require_wildcard = __webpack_require__(1113); -const _react = /*#__PURE__*/ _interop_require_wildcard._(__webpack_require__(8038)); -const _navigation = __webpack_require__(5171); -const _redirect = __webpack_require__(6932); -function HandleRedirect(param) { - let { redirect , reset , redirectType } = param; - const router = (0, _navigation.useRouter)(); - (0, _react.useEffect)(()=>{ - // @ts-ignore startTransition exists - _react.default.startTransition(()=>{ - if (redirectType === _redirect.RedirectType.push) { - router.push(redirect, {}); - } else { - router.replace(redirect, {}); - } - reset(); - }); - }, [ - redirect, - redirectType, - reset, - router - ]); - return null; -} -class RedirectErrorBoundary extends _react.default.Component { - static getDerivedStateFromError(error) { - if ((0, _redirect.isRedirectError)(error)) { - const url = (0, _redirect.getURLFromRedirectError)(error); - const redirectType = (0, _redirect.getRedirectTypeFromError)(error); - return { - redirect: url, - redirectType - }; - } - // Re-throw if error is not for redirect - throw error; - } - render() { - const { redirect , redirectType } = this.state; - if (redirect !== null && redirectType !== null) { - return /*#__PURE__*/ _react.default.createElement(HandleRedirect, { - redirect: redirect, - redirectType: redirectType, - reset: ()=>this.setState({ - redirect: null - }) - }); - } - return this.props.children; - } - constructor(props){ - super(props); - this.state = { - redirect: null, - redirectType: null - }; - } -} -function RedirectBoundary(param) { - let { children } = param; - const router = (0, _navigation.useRouter)(); - return /*#__PURE__*/ _react.default.createElement(RedirectErrorBoundary, { - router: router - }, children); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=redirect-boundary.js.map - - -/***/ }), - -/***/ 6932: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - RedirectType: function() { - return RedirectType; - }, - getRedirectError: function() { - return getRedirectError; - }, - redirect: function() { - return redirect; - }, - isRedirectError: function() { - return isRedirectError; - }, - getURLFromRedirectError: function() { - return getURLFromRedirectError; - }, - getRedirectTypeFromError: function() { - return getRedirectTypeFromError; - } -}); -const _requestasyncstorage = __webpack_require__(4437); -const REDIRECT_ERROR_CODE = "NEXT_REDIRECT"; -var RedirectType; -(function(RedirectType) { - RedirectType["push"] = "push"; - RedirectType["replace"] = "replace"; -})(RedirectType || (RedirectType = {})); -function getRedirectError(url, type) { - const error = new Error(REDIRECT_ERROR_CODE); - error.digest = REDIRECT_ERROR_CODE + ";" + type + ";" + url; - const requestStore = _requestasyncstorage.requestAsyncStorage.getStore(); - if (requestStore) { - error.mutableCookies = requestStore.mutableCookies; - } - return error; -} -function redirect(url, type) { - if (type === void 0) type = "replace"; - throw getRedirectError(url, type); -} -function isRedirectError(error) { - if (typeof (error == null ? void 0 : error.digest) !== "string") return false; - const [errorCode, type, destination] = error.digest.split(";", 3); - return errorCode === REDIRECT_ERROR_CODE && (type === "replace" || type === "push") && typeof destination === "string"; -} -function getURLFromRedirectError(error) { - if (!isRedirectError(error)) return null; - // Slices off the beginning of the digest that contains the code and the - // separating ';'. - return error.digest.split(";", 3)[2]; -} -function getRedirectTypeFromError(error) { - if (!isRedirectError(error)) { - throw new Error("Not a redirect error"); - } - return error.digest.split(";", 3)[1]; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=redirect.js.map - - -/***/ }), - -/***/ 7844: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "default", ({ - enumerable: true, - get: function() { - return RenderFromTemplateContext; - } -})); -const _interop_require_wildcard = __webpack_require__(1113); -const _react = /*#__PURE__*/ _interop_require_wildcard._(__webpack_require__(8038)); -const _approutercontext = __webpack_require__(3280); -function RenderFromTemplateContext() { - const children = (0, _react.useContext)(_approutercontext.TemplateContext); - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, children); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=render-from-template-context.js.map - - -/***/ }), - -/***/ 8837: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "applyFlightData", ({ - enumerable: true, - get: function() { - return applyFlightData; - } -})); -const _approutercontext = __webpack_require__(3280); -const _filllazyitemstillleafwithhead = __webpack_require__(985); -const _fillcachewithnewsubtreedata = __webpack_require__(4940); -function applyFlightData(existingCache, cache, flightDataPath, wasPrefetched) { - if (wasPrefetched === void 0) wasPrefetched = false; - // The one before last item is the router state tree patch - const [treePatch, subTreeData, head] = flightDataPath.slice(-3); - // Handles case where prefetch only returns the router tree patch without rendered components. - if (subTreeData === null) { - return false; - } - if (flightDataPath.length === 3) { - cache.status = _approutercontext.CacheStates.READY; - cache.subTreeData = subTreeData; - (0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(cache, existingCache, treePatch, head, wasPrefetched); - } else { - // Copy subTreeData for the root node of the cache. - cache.status = _approutercontext.CacheStates.READY; - cache.subTreeData = existingCache.subTreeData; - cache.parallelRoutes = new Map(existingCache.parallelRoutes); - // Create a copy of the existing cache with the subTreeData applied. - (0, _fillcachewithnewsubtreedata.fillCacheWithNewSubTreeData)(cache, existingCache, flightDataPath, wasPrefetched); - } - return true; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=apply-flight-data.js.map - - -/***/ }), - -/***/ 951: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "applyRouterStatePatchToTree", ({ - enumerable: true, - get: function() { - return applyRouterStatePatchToTree; - } -})); -const _matchsegments = __webpack_require__(5507); -/** - * Deep merge of the two router states. Parallel route keys are preserved if the patch doesn't have them. - */ function applyPatch(initialTree, patchTree) { - const [initialSegment, initialParallelRoutes] = initialTree; - const [patchSegment, patchParallelRoutes] = patchTree; - // if the applied patch segment is __DEFAULT__ then we can ignore it and return the initial tree - // this is because the __DEFAULT__ segment is used as a placeholder on navigation - if (patchSegment === "__DEFAULT__" && initialSegment !== "__DEFAULT__") { - return initialTree; - } - if ((0, _matchsegments.matchSegment)(initialSegment, patchSegment)) { - const newParallelRoutes = {}; - for(const key in initialParallelRoutes){ - const isInPatchTreeParallelRoutes = typeof patchParallelRoutes[key] !== "undefined"; - if (isInPatchTreeParallelRoutes) { - newParallelRoutes[key] = applyPatch(initialParallelRoutes[key], patchParallelRoutes[key]); - } else { - newParallelRoutes[key] = initialParallelRoutes[key]; - } - } - for(const key in patchParallelRoutes){ - if (newParallelRoutes[key]) { - continue; - } - newParallelRoutes[key] = patchParallelRoutes[key]; - } - const tree = [ - initialSegment, - newParallelRoutes - ]; - if (initialTree[2]) { - tree[2] = initialTree[2]; - } - if (initialTree[3]) { - tree[3] = initialTree[3]; - } - if (initialTree[4]) { - tree[4] = initialTree[4]; - } - return tree; - } - return patchTree; -} -function applyRouterStatePatchToTree(flightSegmentPath, flightRouterState, treePatch) { - const [segment, parallelRoutes, , , isRootLayout] = flightRouterState; - // Root refresh - if (flightSegmentPath.length === 1) { - const tree = applyPatch(flightRouterState, treePatch); - return tree; - } - const [currentSegment, parallelRouteKey] = flightSegmentPath; - // Tree path returned from the server should always match up with the current tree in the browser - if (!(0, _matchsegments.matchSegment)(currentSegment, segment)) { - return null; - } - const lastSegment = flightSegmentPath.length === 2; - let parallelRoutePatch; - if (lastSegment) { - parallelRoutePatch = applyPatch(parallelRoutes[parallelRouteKey], treePatch); - } else { - parallelRoutePatch = applyRouterStatePatchToTree(flightSegmentPath.slice(2), parallelRoutes[parallelRouteKey], treePatch); - if (parallelRoutePatch === null) { - return null; - } - } - const tree = [ - flightSegmentPath[0], - { - ...parallelRoutes, - [parallelRouteKey]: parallelRoutePatch - } - ]; - // Current segment is the root layout - if (isRootLayout) { - tree[4] = true; - } - return tree; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=apply-router-state-patch-to-tree.js.map - - -/***/ }), - -/***/ 226: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - extractPathFromFlightRouterState: function() { - return extractPathFromFlightRouterState; - }, - computeChangedPath: function() { - return computeChangedPath; - } -}); -const _interceptionroutes = __webpack_require__(8652); -const _matchsegments = __webpack_require__(5507); -const segmentToPathname = (segment)=>{ - if (typeof segment === "string") { - return segment; - } - return segment[1]; -}; -function normalizePathname(pathname) { - return pathname.split("/").reduce((acc, segment)=>{ - if (segment === "" || segment.startsWith("(") && segment.endsWith(")")) { - return acc; - } - return acc + "/" + segment; - }, "") || "/"; -} -function extractPathFromFlightRouterState(flightRouterState) { - const segment = Array.isArray(flightRouterState[0]) ? flightRouterState[0][1] : flightRouterState[0]; - if (segment === "__DEFAULT__" || _interceptionroutes.INTERCEPTION_ROUTE_MARKERS.some((m)=>segment.startsWith(m))) return undefined; - if (segment.startsWith("__PAGE__")) return ""; - const path = [ - segment - ]; - var _flightRouterState_; - const parallelRoutes = (_flightRouterState_ = flightRouterState[1]) != null ? _flightRouterState_ : {}; - const childrenPath = parallelRoutes.children ? extractPathFromFlightRouterState(parallelRoutes.children) : undefined; - if (childrenPath !== undefined) { - path.push(childrenPath); - } else { - for (const [key, value] of Object.entries(parallelRoutes)){ - if (key === "children") continue; - const childPath = extractPathFromFlightRouterState(value); - if (childPath !== undefined) { - path.push(childPath); - } - } - } - // TODO-APP: optimise this, it's not ideal to join and split - return normalizePathname(path.join("/")); -} -function computeChangedPathImpl(treeA, treeB) { - const [segmentA, parallelRoutesA] = treeA; - const [segmentB, parallelRoutesB] = treeB; - const normalizedSegmentA = segmentToPathname(segmentA); - const normalizedSegmentB = segmentToPathname(segmentB); - if (_interceptionroutes.INTERCEPTION_ROUTE_MARKERS.some((m)=>normalizedSegmentA.startsWith(m) || normalizedSegmentB.startsWith(m))) { - return ""; - } - if (!(0, _matchsegments.matchSegment)(segmentA, segmentB)) { - var _extractPathFromFlightRouterState; - // once we find where the tree changed, we compute the rest of the path by traversing the tree - return (_extractPathFromFlightRouterState = extractPathFromFlightRouterState(treeB)) != null ? _extractPathFromFlightRouterState : ""; - } - for(const parallelRouterKey in parallelRoutesA){ - if (parallelRoutesB[parallelRouterKey]) { - const changedPath = computeChangedPathImpl(parallelRoutesA[parallelRouterKey], parallelRoutesB[parallelRouterKey]); - if (changedPath !== null) { - return segmentToPathname(segmentB) + "/" + changedPath; - } - } - } - return null; -} -function computeChangedPath(treeA, treeB) { - const changedPath = computeChangedPathImpl(treeA, treeB); - if (changedPath == null || changedPath === "/") { - return changedPath; - } - // lightweight normalization to remove route groups - return normalizePathname(changedPath); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=compute-changed-path.js.map - - -/***/ }), - -/***/ 8253: -/***/ ((module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createHrefFromUrl", ({ - enumerable: true, - get: function() { - return createHrefFromUrl; - } -})); -function createHrefFromUrl(url, includeHash) { - if (includeHash === void 0) includeHash = true; - return url.pathname + url.search + (includeHash ? url.hash : ""); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=create-href-from-url.js.map - - -/***/ }), - -/***/ 3558: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createInitialRouterState", ({ - enumerable: true, - get: function() { - return createInitialRouterState; - } -})); -const _approutercontext = __webpack_require__(3280); -const _createhreffromurl = __webpack_require__(8253); -const _filllazyitemstillleafwithhead = __webpack_require__(985); -const _computechangedpath = __webpack_require__(226); -function createInitialRouterState(param) { - let { initialTree , children , initialCanonicalUrl , initialParallelRoutes , isServer , location , initialHead } = param; - const cache = { - status: _approutercontext.CacheStates.READY, - data: null, - subTreeData: children, - // The cache gets seeded during the first render. `initialParallelRoutes` ensures the cache from the first render is there during the second render. - parallelRoutes: isServer ? new Map() : initialParallelRoutes - }; - // When the cache hasn't been seeded yet we fill the cache with the head. - if (initialParallelRoutes === null || initialParallelRoutes.size === 0) { - (0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(cache, undefined, initialTree, initialHead); - } - var _ref; - return { - tree: initialTree, - cache, - prefetchCache: new Map(), - pushRef: { - pendingPush: false, - mpaNavigation: false - }, - focusAndScrollRef: { - apply: false, - hashFragment: null, - segmentPaths: [] - }, - canonicalUrl: // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file. - location ? (0, _createhreffromurl.createHrefFromUrl)(location) : initialCanonicalUrl, - nextUrl: (_ref = (0, _computechangedpath.extractPathFromFlightRouterState)(initialTree) || (location == null ? void 0 : location.pathname)) != null ? _ref : null - }; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=create-initial-router-state.js.map - - -/***/ }), - -/***/ 5603: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createOptimisticTree", ({ - enumerable: true, - get: function() { - return createOptimisticTree; - } -})); -const _matchsegments = __webpack_require__(5507); -function createOptimisticTree(segments, flightRouterState, parentRefetch) { - const [existingSegment, existingParallelRoutes, url, refresh, isRootLayout] = flightRouterState || [ - null, - {} - ]; - const segment = segments[0]; - const isLastSegment = segments.length === 1; - const segmentMatches = existingSegment !== null && (0, _matchsegments.matchSegment)(existingSegment, segment); - // if there are multiple parallel routes at this level, we need to refetch here - // to ensure we get the correct tree. This is because we don't know which - // parallel route will match the next segment. - const hasMultipleParallelRoutes = Object.keys(existingParallelRoutes).length > 1; - const shouldRefetchThisLevel = !flightRouterState || !segmentMatches || hasMultipleParallelRoutes; - let parallelRoutes = {}; - if (existingSegment !== null && segmentMatches) { - parallelRoutes = existingParallelRoutes; - } - let childTree; - // if there's multiple parallel routes at this level, we shouldn't create an - // optimistic tree for the next level because we don't know which one will - // match the next segment. - if (!isLastSegment && !hasMultipleParallelRoutes) { - const childItem = createOptimisticTree(segments.slice(1), parallelRoutes ? parallelRoutes.children : null, parentRefetch || shouldRefetchThisLevel); - childTree = childItem; - } - const result = [ - segment, - { - ...parallelRoutes, - ...childTree ? { - children: childTree - } : {} - } - ]; - if (url) { - result[2] = url; - } - if (!parentRefetch && shouldRefetchThisLevel) { - result[3] = "refetch"; - } else if (segmentMatches && refresh) { - result[3] = refresh; - } - if (segmentMatches && isRootLayout) { - result[4] = isRootLayout; - } - return result; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=create-optimistic-tree.js.map - - -/***/ }), - -/***/ 5792: -/***/ ((module, exports) => { - -"use strict"; -/** - * Create data fetching record for Promise. - */ // TODO-APP: change `any` to type inference. - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createRecordFromThenable", ({ - enumerable: true, - get: function() { - return createRecordFromThenable; - } -})); -function createRecordFromThenable(thenable) { - thenable.status = "pending"; - thenable.then((value)=>{ - if (thenable.status === "pending") { - thenable.status = "fulfilled"; - thenable.value = value; - } - }, (err)=>{ - if (thenable.status === "pending") { - thenable.status = "rejected"; - thenable.value = err; - } - }); - return thenable; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=create-record-from-thenable.js.map - - -/***/ }), - -/***/ 5370: -/***/ ((module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createRouterCacheKey", ({ - enumerable: true, - get: function() { - return createRouterCacheKey; - } -})); -function createRouterCacheKey(segment, withoutSearchParameters) { - if (withoutSearchParameters === void 0) withoutSearchParameters = false; - return Array.isArray(segment) ? segment[0] + "|" + segment[1] + "|" + segment[2] : withoutSearchParameters && segment.startsWith("__PAGE__") ? "__PAGE__" : segment; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=create-router-cache-key.js.map - - -/***/ }), - -/***/ 969: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "fetchServerResponse", ({ - enumerable: true, - get: function() { - return fetchServerResponse; - } -})); -const _client = __webpack_require__(7897); -const _approuterheaders = __webpack_require__(281); -const _approuter = __webpack_require__(125); -const _appcallserver = __webpack_require__(4783); -const _routerreducertypes = __webpack_require__(549); -async function fetchServerResponse(url, flightRouterState, nextUrl, prefetchKind) { - const headers = { - // Enable flight response - [_approuterheaders.RSC]: "1", - // Provide the current router state - [_approuterheaders.NEXT_ROUTER_STATE_TREE]: JSON.stringify(flightRouterState) - }; - /** - * Three cases: - * - `prefetchKind` is `undefined`, it means it's a normal navigation, so we want to prefetch the page data fully - * - `prefetchKind` is `full` - we want to prefetch the whole page so same as above - * - `prefetchKind` is `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully - */ if (prefetchKind === _routerreducertypes.PrefetchKind.AUTO) { - headers[_approuterheaders.NEXT_ROUTER_PREFETCH] = "1"; - } - if (nextUrl) { - headers[_approuterheaders.NEXT_URL] = nextUrl; - } - try { - let fetchUrl = url; - if (true) { - if (false) {} - } - const res = await fetch(fetchUrl, { - // Backwards compat for older browsers. `same-origin` is the default in modern browsers. - credentials: "same-origin", - headers - }); - const canonicalUrl = res.redirected ? (0, _approuter.urlToUrlWithoutFlightMarker)(res.url) : undefined; - const contentType = res.headers.get("content-type") || ""; - let isFlightResponse = contentType === _approuterheaders.RSC_CONTENT_TYPE_HEADER; - if (true) { - if (false) {} - } - // If fetch returns something different than flight response handle it like a mpa navigation - // If the fetch was not 200, we also handle it like a mpa navigation - if (!isFlightResponse || !res.ok) { - return [ - res.url, - undefined - ]; - } - // Handle the `fetch` readable stream that can be unwrapped by `React.use`. - const flightData = await (0, _client.createFromFetch)(Promise.resolve(res), { - callServer: _appcallserver.callServer - }); - return [ - flightData, - canonicalUrl - ]; - } catch (err) { - console.error("Failed to fetch RSC payload. Falling back to browser navigation.", err); - // If fetch fails handle it like a mpa navigation - // TODO-APP: Add a test for the case where a CORS request fails, e.g. external url redirect coming from the response. - // See https://github.com/vercel/next.js/issues/43605#issuecomment-1451617521 for a reproduction. - return [ - url.toString(), - undefined - ]; - } -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=fetch-server-response.js.map - - -/***/ }), - -/***/ 277: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "fillCacheWithDataProperty", ({ - enumerable: true, - get: function() { - return fillCacheWithDataProperty; - } -})); -const _approutercontext = __webpack_require__(3280); -const _createroutercachekey = __webpack_require__(5370); -function fillCacheWithDataProperty(newCache, existingCache, flightSegmentPath, fetchResponse, bailOnParallelRoutes) { - if (bailOnParallelRoutes === void 0) bailOnParallelRoutes = false; - const isLastEntry = flightSegmentPath.length <= 2; - const [parallelRouteKey, segment] = flightSegmentPath; - const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segment); - const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey); - if (!existingChildSegmentMap || bailOnParallelRoutes && existingCache.parallelRoutes.size > 1) { - // Bailout because the existing cache does not have the path to the leaf node - // or the existing cache has multiple parallel routes - // Will trigger lazy fetch in layout-router because of missing segment - return { - bailOptimistic: true - }; - } - let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey); - if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) { - childSegmentMap = new Map(existingChildSegmentMap); - newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap); - } - const existingChildCacheNode = existingChildSegmentMap.get(cacheKey); - let childCacheNode = childSegmentMap.get(cacheKey); - // In case of last segment start off the fetch at this level and don't copy further down. - if (isLastEntry) { - if (!childCacheNode || !childCacheNode.data || childCacheNode === existingChildCacheNode) { - childSegmentMap.set(cacheKey, { - status: _approutercontext.CacheStates.DATA_FETCH, - data: fetchResponse(), - subTreeData: null, - parallelRoutes: new Map() - }); - } - return; - } - if (!childCacheNode || !existingChildCacheNode) { - // Start fetch in the place where the existing cache doesn't have the data yet. - if (!childCacheNode) { - childSegmentMap.set(cacheKey, { - status: _approutercontext.CacheStates.DATA_FETCH, - data: fetchResponse(), - subTreeData: null, - parallelRoutes: new Map() - }); - } - return; - } - if (childCacheNode === existingChildCacheNode) { - childCacheNode = { - status: childCacheNode.status, - data: childCacheNode.data, - subTreeData: childCacheNode.subTreeData, - parallelRoutes: new Map(childCacheNode.parallelRoutes) - }; - childSegmentMap.set(cacheKey, childCacheNode); - } - return fillCacheWithDataProperty(childCacheNode, existingChildCacheNode, flightSegmentPath.slice(2), fetchResponse); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=fill-cache-with-data-property.js.map - - -/***/ }), - -/***/ 4940: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "fillCacheWithNewSubTreeData", ({ - enumerable: true, - get: function() { - return fillCacheWithNewSubTreeData; - } -})); -const _approutercontext = __webpack_require__(3280); -const _invalidatecachebyrouterstate = __webpack_require__(6246); -const _filllazyitemstillleafwithhead = __webpack_require__(985); -const _createroutercachekey = __webpack_require__(5370); -function fillCacheWithNewSubTreeData(newCache, existingCache, flightDataPath, wasPrefetched) { - const isLastEntry = flightDataPath.length <= 5; - const [parallelRouteKey, segment] = flightDataPath; - const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segment); - const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey); - if (!existingChildSegmentMap) { - // Bailout because the existing cache does not have the path to the leaf node - // Will trigger lazy fetch in layout-router because of missing segment - return; - } - let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey); - if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) { - childSegmentMap = new Map(existingChildSegmentMap); - newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap); - } - const existingChildCacheNode = existingChildSegmentMap.get(cacheKey); - let childCacheNode = childSegmentMap.get(cacheKey); - if (isLastEntry) { - if (!childCacheNode || !childCacheNode.data || childCacheNode === existingChildCacheNode) { - childCacheNode = { - status: _approutercontext.CacheStates.READY, - data: null, - subTreeData: flightDataPath[3], - // Ensure segments other than the one we got data for are preserved. - parallelRoutes: existingChildCacheNode ? new Map(existingChildCacheNode.parallelRoutes) : new Map() - }; - if (existingChildCacheNode) { - (0, _invalidatecachebyrouterstate.invalidateCacheByRouterState)(childCacheNode, existingChildCacheNode, flightDataPath[2]); - } - (0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(childCacheNode, existingChildCacheNode, flightDataPath[2], flightDataPath[4], wasPrefetched); - childSegmentMap.set(cacheKey, childCacheNode); - } - return; - } - if (!childCacheNode || !existingChildCacheNode) { - // Bailout because the existing cache does not have the path to the leaf node - // Will trigger lazy fetch in layout-router because of missing segment - return; - } - if (childCacheNode === existingChildCacheNode) { - childCacheNode = { - status: childCacheNode.status, - data: childCacheNode.data, - subTreeData: childCacheNode.subTreeData, - parallelRoutes: new Map(childCacheNode.parallelRoutes) - }; - childSegmentMap.set(cacheKey, childCacheNode); - } - fillCacheWithNewSubTreeData(childCacheNode, existingChildCacheNode, flightDataPath.slice(2), wasPrefetched); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=fill-cache-with-new-subtree-data.js.map - - -/***/ }), - -/***/ 985: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "fillLazyItemsTillLeafWithHead", ({ - enumerable: true, - get: function() { - return fillLazyItemsTillLeafWithHead; - } -})); -const _approutercontext = __webpack_require__(3280); -const _createroutercachekey = __webpack_require__(5370); -function fillLazyItemsTillLeafWithHead(newCache, existingCache, routerState, head, wasPrefetched) { - const isLastSegment = Object.keys(routerState[1]).length === 0; - if (isLastSegment) { - newCache.head = head; - return; - } - // Remove segment that we got data for so that it is filled in during rendering of subTreeData. - for(const key in routerState[1]){ - const parallelRouteState = routerState[1][key]; - const segmentForParallelRoute = parallelRouteState[0]; - const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segmentForParallelRoute); - if (existingCache) { - const existingParallelRoutesCacheNode = existingCache.parallelRoutes.get(key); - if (existingParallelRoutesCacheNode) { - let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode); - const existingCacheNode = parallelRouteCacheNode.get(cacheKey); - const newCacheNode = wasPrefetched && existingCacheNode ? { - status: existingCacheNode.status, - data: existingCacheNode.data, - subTreeData: existingCacheNode.subTreeData, - parallelRoutes: new Map(existingCacheNode.parallelRoutes) - } : { - status: _approutercontext.CacheStates.LAZY_INITIALIZED, - data: null, - subTreeData: null, - parallelRoutes: new Map(existingCacheNode == null ? void 0 : existingCacheNode.parallelRoutes) - }; - // Overrides the cache key with the new cache node. - parallelRouteCacheNode.set(cacheKey, newCacheNode); - // Traverse deeper to apply the head / fill lazy items till the head. - fillLazyItemsTillLeafWithHead(newCacheNode, existingCacheNode, parallelRouteState, head, wasPrefetched); - newCache.parallelRoutes.set(key, parallelRouteCacheNode); - continue; - } - } - const newCacheNode = { - status: _approutercontext.CacheStates.LAZY_INITIALIZED, - data: null, - subTreeData: null, - parallelRoutes: new Map() - }; - const existingParallelRoutes = newCache.parallelRoutes.get(key); - if (existingParallelRoutes) { - existingParallelRoutes.set(cacheKey, newCacheNode); - } else { - newCache.parallelRoutes.set(key, new Map([ - [ - cacheKey, - newCacheNode - ] - ])); - } - fillLazyItemsTillLeafWithHead(newCacheNode, undefined, parallelRouteState, head, wasPrefetched); - } -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=fill-lazy-items-till-leaf-with-head.js.map - - -/***/ }), - -/***/ 9362: -/***/ ((module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - PrefetchCacheEntryStatus: function() { - return PrefetchCacheEntryStatus; - }, - getPrefetchEntryCacheStatus: function() { - return getPrefetchEntryCacheStatus; - } -}); -const FIVE_MINUTES = 5 * 60 * 1000; -const THIRTY_SECONDS = 30 * 1000; -var PrefetchCacheEntryStatus; -(function(PrefetchCacheEntryStatus) { - PrefetchCacheEntryStatus["fresh"] = "fresh"; - PrefetchCacheEntryStatus["reusable"] = "reusable"; - PrefetchCacheEntryStatus["expired"] = "expired"; - PrefetchCacheEntryStatus["stale"] = "stale"; -})(PrefetchCacheEntryStatus || (PrefetchCacheEntryStatus = {})); -function getPrefetchEntryCacheStatus(param) { - let { kind , prefetchTime , lastUsedTime } = param; - // if the cache entry was prefetched or read less than 30s ago, then we want to re-use it - if (Date.now() < (lastUsedTime != null ? lastUsedTime : prefetchTime) + THIRTY_SECONDS) { - return lastUsedTime ? "reusable" : "fresh"; - } - // if the cache entry was prefetched less than 5 mins ago, then we want to re-use only the loading state - if (kind === "auto") { - if (Date.now() < prefetchTime + FIVE_MINUTES) { - return "stale"; - } - } - // if the cache entry was prefetched less than 5 mins ago and was a "full" prefetch, then we want to re-use it "full - if (kind === "full") { - if (Date.now() < prefetchTime + FIVE_MINUTES) { - return "reusable"; - } - } - return "expired"; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=get-prefetch-cache-entry-status.js.map - - -/***/ }), - -/***/ 5098: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "handleMutable", ({ - enumerable: true, - get: function() { - return handleMutable; - } -})); -const _computechangedpath = __webpack_require__(226); -function handleMutable(state, mutable) { - var _mutable_scrollableSegments, _computeChangedPath; - return { - // Set href. - canonicalUrl: typeof mutable.canonicalUrl !== "undefined" ? mutable.canonicalUrl === state.canonicalUrl ? state.canonicalUrl : mutable.canonicalUrl : state.canonicalUrl, - pushRef: { - pendingPush: typeof mutable.pendingPush !== "undefined" ? mutable.pendingPush : state.pushRef.pendingPush, - mpaNavigation: typeof mutable.mpaNavigation !== "undefined" ? mutable.mpaNavigation : state.pushRef.mpaNavigation - }, - // All navigation requires scroll and focus management to trigger. - focusAndScrollRef: { - apply: (mutable == null ? void 0 : mutable.scrollableSegments) !== undefined ? true : state.focusAndScrollRef.apply, - hashFragment: // #top is handled in layout-router. - mutable.hashFragment && mutable.hashFragment !== "" ? decodeURIComponent(mutable.hashFragment.slice(1)) : state.focusAndScrollRef.hashFragment, - segmentPaths: (_mutable_scrollableSegments = mutable == null ? void 0 : mutable.scrollableSegments) != null ? _mutable_scrollableSegments : state.focusAndScrollRef.segmentPaths - }, - // Apply cache. - cache: mutable.cache ? mutable.cache : state.cache, - prefetchCache: mutable.prefetchCache ? mutable.prefetchCache : state.prefetchCache, - // Apply patched router state. - tree: typeof mutable.patchedTree !== "undefined" ? mutable.patchedTree : state.tree, - nextUrl: typeof mutable.patchedTree !== "undefined" ? (_computeChangedPath = (0, _computechangedpath.computeChangedPath)(state.tree, mutable.patchedTree)) != null ? _computeChangedPath : state.canonicalUrl : state.nextUrl - }; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=handle-mutable.js.map - - -/***/ }), - -/***/ 1986: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "invalidateCacheBelowFlightSegmentPath", ({ - enumerable: true, - get: function() { - return invalidateCacheBelowFlightSegmentPath; - } -})); -const _createroutercachekey = __webpack_require__(5370); -function invalidateCacheBelowFlightSegmentPath(newCache, existingCache, flightSegmentPath) { - const isLastEntry = flightSegmentPath.length <= 2; - const [parallelRouteKey, segment] = flightSegmentPath; - const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segment); - const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey); - if (!existingChildSegmentMap) { - // Bailout because the existing cache does not have the path to the leaf node - // Will trigger lazy fetch in layout-router because of missing segment - return; - } - let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey); - if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) { - childSegmentMap = new Map(existingChildSegmentMap); - newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap); - } - // In case of last entry don't copy further down. - if (isLastEntry) { - childSegmentMap.delete(cacheKey); - return; - } - const existingChildCacheNode = existingChildSegmentMap.get(cacheKey); - let childCacheNode = childSegmentMap.get(cacheKey); - if (!childCacheNode || !existingChildCacheNode) { - // Bailout because the existing cache does not have the path to the leaf node - // Will trigger lazy fetch in layout-router because of missing segment - return; - } - if (childCacheNode === existingChildCacheNode) { - childCacheNode = { - status: childCacheNode.status, - data: childCacheNode.data, - subTreeData: childCacheNode.subTreeData, - parallelRoutes: new Map(childCacheNode.parallelRoutes) - }; - childSegmentMap.set(cacheKey, childCacheNode); - } - invalidateCacheBelowFlightSegmentPath(childCacheNode, existingChildCacheNode, flightSegmentPath.slice(2)); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=invalidate-cache-below-flight-segmentpath.js.map - - -/***/ }), - -/***/ 6246: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "invalidateCacheByRouterState", ({ - enumerable: true, - get: function() { - return invalidateCacheByRouterState; - } -})); -const _createroutercachekey = __webpack_require__(5370); -function invalidateCacheByRouterState(newCache, existingCache, routerState) { - // Remove segment that we got data for so that it is filled in during rendering of subTreeData. - for(const key in routerState[1]){ - const segmentForParallelRoute = routerState[1][key][0]; - const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segmentForParallelRoute); - const existingParallelRoutesCacheNode = existingCache.parallelRoutes.get(key); - if (existingParallelRoutesCacheNode) { - let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode); - parallelRouteCacheNode.delete(cacheKey); - newCache.parallelRoutes.set(key, parallelRouteCacheNode); - } - } -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=invalidate-cache-by-router-state.js.map - - -/***/ }), - -/***/ 9610: -/***/ ((module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "isNavigatingToNewRootLayout", ({ - enumerable: true, - get: function() { - return isNavigatingToNewRootLayout; - } -})); -function isNavigatingToNewRootLayout(currentTree, nextTree) { - // Compare segments - const currentTreeSegment = currentTree[0]; - const nextTreeSegment = nextTree[0]; - // If any segment is different before we find the root layout, the root layout has changed. - // E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js - // First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed. - if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) { - // Compare dynamic param name and type but ignore the value, different values would not affect the current root layout - // /[name] - /slug1 and /slug2, both values (slug1 & slug2) still has the same layout /[name]/layout.js - if (currentTreeSegment[0] !== nextTreeSegment[0] || currentTreeSegment[2] !== nextTreeSegment[2]) { - return true; - } - } else if (currentTreeSegment !== nextTreeSegment) { - return true; - } - // Current tree root layout found - if (currentTree[4]) { - // If the next tree doesn't have the root layout flag, it must have changed. - return !nextTree[4]; - } - // Current tree didn't have its root layout here, must have changed. - if (nextTree[4]) { - return true; - } - // We can't assume it's `parallelRoutes.children` here in case the root layout is `app/@something/layout.js` - // But it's not possible to be more than one parallelRoutes before the root layout is found - // TODO-APP: change to traverse all parallel routes - const currentTreeChild = Object.values(currentTree[1])[0]; - const nextTreeChild = Object.values(nextTree[1])[0]; - if (!currentTreeChild || !nextTreeChild) return true; - return isNavigatingToNewRootLayout(currentTreeChild, nextTreeChild); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=is-navigating-to-new-root-layout.js.map - - -/***/ }), - -/***/ 4170: -/***/ ((module, exports) => { - -"use strict"; -/** - * Read record value or throw Promise if it's not resolved yet. - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "readRecordValue", ({ - enumerable: true, - get: function() { - return readRecordValue; - } -})); -function readRecordValue(thenable) { - // @ts-expect-error TODO: fix type - if (thenable.status === "fulfilled") { - // @ts-expect-error TODO: fix type - return thenable.value; - } else { - throw thenable; - } -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=read-record-value.js.map - - -/***/ }), - -/***/ 7709: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "fastRefreshReducer", ({ - enumerable: true, - get: function() { - return fastRefreshReducer; - } -})); -const _fetchserverresponse = __webpack_require__(969); -const _createrecordfromthenable = __webpack_require__(5792); -const _readrecordvalue = __webpack_require__(4170); -const _createhreffromurl = __webpack_require__(8253); -const _applyrouterstatepatchtotree = __webpack_require__(951); -const _isnavigatingtonewrootlayout = __webpack_require__(9610); -const _navigatereducer = __webpack_require__(1935); -const _handlemutable = __webpack_require__(5098); -const _applyflightdata = __webpack_require__(8837); -// A version of refresh reducer that keeps the cache around instead of wiping all of it. -function fastRefreshReducerImpl(state, action) { - const { cache , mutable , origin } = action; - const href = state.canonicalUrl; - const isForCurrentTree = JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree); - if (isForCurrentTree) { - return (0, _handlemutable.handleMutable)(state, mutable); - } - if (!cache.data) { - // TODO-APP: verify that `href` is not an external url. - // Fetch data from the root of the tree. - cache.data = (0, _createrecordfromthenable.createRecordFromThenable)((0, _fetchserverresponse.fetchServerResponse)(new URL(href, origin), [ - state.tree[0], - state.tree[1], - state.tree[2], - "refetch" - ], state.nextUrl)); - } - const [flightData, canonicalUrlOverride] = (0, _readrecordvalue.readRecordValue)(cache.data); - // Handle case when navigating to page in `pages` from `app` - if (typeof flightData === "string") { - return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush); - } - // Remove cache.data as it has been resolved at this point. - cache.data = null; - let currentTree = state.tree; - let currentCache = state.cache; - for (const flightDataPath of flightData){ - // FlightDataPath with more than two items means unexpected Flight data was returned - if (flightDataPath.length !== 3) { - // TODO-APP: handle this case better - console.log("REFRESH FAILED"); - return state; - } - // Given the path can only have two items the items are only the router state and subTreeData for the root. - const [treePatch] = flightDataPath; - const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)([ - "" - ], currentTree, treePatch); - if (newTree === null) { - throw new Error("SEGMENT MISMATCH"); - } - if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) { - return (0, _navigatereducer.handleExternalUrl)(state, mutable, href, state.pushRef.pendingPush); - } - const canonicalUrlOverrideHref = canonicalUrlOverride ? (0, _createhreffromurl.createHrefFromUrl)(canonicalUrlOverride) : undefined; - if (canonicalUrlOverride) { - mutable.canonicalUrl = canonicalUrlOverrideHref; - } - const applied = (0, _applyflightdata.applyFlightData)(currentCache, cache, flightDataPath); - if (applied) { - mutable.cache = cache; - currentCache = cache; - } - mutable.previousTree = currentTree; - mutable.patchedTree = newTree; - mutable.canonicalUrl = href; - currentTree = newTree; - } - return (0, _handlemutable.handleMutable)(state, mutable); -} -function fastRefreshReducerNoop(state, _action) { - return state; -} -const fastRefreshReducer = true ? fastRefreshReducerNoop : 0; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=fast-refresh-reducer.js.map - - -/***/ }), - -/***/ 7997: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "findHeadInCache", ({ - enumerable: true, - get: function() { - return findHeadInCache; - } -})); -const _createroutercachekey = __webpack_require__(5370); -function findHeadInCache(cache, parallelRoutes) { - const isLastItem = Object.keys(parallelRoutes).length === 0; - if (isLastItem) { - return cache.head; - } - for(const key in parallelRoutes){ - const [segment, childParallelRoutes] = parallelRoutes[key]; - const childSegmentMap = cache.parallelRoutes.get(key); - if (!childSegmentMap) { - continue; - } - const cacheKey = (0, _createroutercachekey.createRouterCacheKey)(segment); - const cacheNode = childSegmentMap.get(cacheKey); - if (!cacheNode) { - continue; - } - const item = findHeadInCache(cacheNode, childParallelRoutes); - if (item) { - return item; - } - } - return undefined; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=find-head-in-cache.js.map - - -/***/ }), - -/***/ 3715: -/***/ ((module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "getSegmentValue", ({ - enumerable: true, - get: function() { - return getSegmentValue; - } -})); -function getSegmentValue(segment) { - return Array.isArray(segment) ? segment[1] : segment; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=get-segment-value.js.map - - -/***/ }), - -/***/ 1935: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - handleExternalUrl: function() { - return handleExternalUrl; - }, - navigateReducer: function() { - return navigateReducer; - } -}); -const _approutercontext = __webpack_require__(3280); -const _fetchserverresponse = __webpack_require__(969); -const _createrecordfromthenable = __webpack_require__(5792); -const _readrecordvalue = __webpack_require__(4170); -const _createhreffromurl = __webpack_require__(8253); -const _invalidatecachebelowflightsegmentpath = __webpack_require__(1986); -const _fillcachewithdataproperty = __webpack_require__(277); -const _createoptimistictree = __webpack_require__(5603); -const _applyrouterstatepatchtotree = __webpack_require__(951); -const _shouldhardnavigate = __webpack_require__(9425); -const _isnavigatingtonewrootlayout = __webpack_require__(9610); -const _routerreducertypes = __webpack_require__(549); -const _handlemutable = __webpack_require__(5098); -const _applyflightdata = __webpack_require__(8837); -const _getprefetchcacheentrystatus = __webpack_require__(9362); -const _pruneprefetchcache = __webpack_require__(1262); -function handleExternalUrl(state, mutable, url, pendingPush) { - mutable.previousTree = state.tree; - mutable.mpaNavigation = true; - mutable.canonicalUrl = url; - mutable.pendingPush = pendingPush; - mutable.scrollableSegments = undefined; - return (0, _handlemutable.handleMutable)(state, mutable); -} -function generateSegmentsFromPatch(flightRouterPatch) { - const segments = []; - const [segment, parallelRoutes] = flightRouterPatch; - if (Object.keys(parallelRoutes).length === 0) { - return [ - [ - segment - ] - ]; - } - for (const [parallelRouteKey, parallelRoute] of Object.entries(parallelRoutes)){ - for (const childSegment of generateSegmentsFromPatch(parallelRoute)){ - // If the segment is empty, it means we are at the root of the tree - if (segment === "") { - segments.push([ - parallelRouteKey, - ...childSegment - ]); - } else { - segments.push([ - segment, - parallelRouteKey, - ...childSegment - ]); - } - } - } - return segments; -} -function addRefetchToLeafSegments(newCache, currentCache, flightSegmentPath, treePatch, data) { - let appliedPatch = false; - newCache.status = _approutercontext.CacheStates.READY; - newCache.subTreeData = currentCache.subTreeData; - newCache.parallelRoutes = new Map(currentCache.parallelRoutes); - const segmentPathsToFill = generateSegmentsFromPatch(treePatch).map((segment)=>[ - ...flightSegmentPath, - ...segment - ]); - for (const segmentPaths of segmentPathsToFill){ - const res = (0, _fillcachewithdataproperty.fillCacheWithDataProperty)(newCache, currentCache, segmentPaths, data); - if (!(res == null ? void 0 : res.bailOptimistic)) { - appliedPatch = true; - } - } - return appliedPatch; -} -function navigateReducer(state, action) { - const { url , isExternalUrl , navigateType , cache , mutable , forceOptimisticNavigation } = action; - const { pathname , hash } = url; - const href = (0, _createhreffromurl.createHrefFromUrl)(url); - const pendingPush = navigateType === "push"; - // we want to prune the prefetch cache on every navigation to avoid it growing too large - (0, _pruneprefetchcache.prunePrefetchCache)(state.prefetchCache); - const isForCurrentTree = JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree); - if (isForCurrentTree) { - return (0, _handlemutable.handleMutable)(state, mutable); - } - if (isExternalUrl) { - return handleExternalUrl(state, mutable, url.toString(), pendingPush); - } - let prefetchValues = state.prefetchCache.get((0, _createhreffromurl.createHrefFromUrl)(url, false)); - if (forceOptimisticNavigation && (prefetchValues == null ? void 0 : prefetchValues.kind) !== _routerreducertypes.PrefetchKind.TEMPORARY) { - const segments = pathname.split("/"); - // TODO-APP: figure out something better for index pages - segments.push("__PAGE__"); - // Optimistic tree case. - // If the optimistic tree is deeper than the current state leave that deeper part out of the fetch - const optimisticTree = (0, _createoptimistictree.createOptimisticTree)(segments, state.tree, false); - // we need a copy of the cache in case we need to revert to it - const temporaryCacheNode = { - ...cache - }; - // Copy subTreeData for the root node of the cache. - // Note: didn't do it above because typescript doesn't like it. - temporaryCacheNode.status = _approutercontext.CacheStates.READY; - temporaryCacheNode.subTreeData = state.cache.subTreeData; - temporaryCacheNode.parallelRoutes = new Map(state.cache.parallelRoutes); - const data = (0, _createrecordfromthenable.createRecordFromThenable)((0, _fetchserverresponse.fetchServerResponse)(url, optimisticTree, state.nextUrl)); - // TODO-APP: segments.slice(1) strips '', we can get rid of '' altogether. - // TODO-APP: re-evaluate if we need to strip the last segment - const optimisticFlightSegmentPath = segments.slice(1).map((segment)=>[ - "children", - segment - ]).flat(); - // Copy existing cache nodes as far as possible and fill in `data` property with the started data fetch. - // The `data` property is used to suspend in layout-router during render if it hasn't resolved yet by the time it renders. - const res = (0, _fillcachewithdataproperty.fillCacheWithDataProperty)(temporaryCacheNode, state.cache, optimisticFlightSegmentPath, ()=>data, true); - // If optimistic fetch couldn't happen it falls back to the non-optimistic case. - if (!(res == null ? void 0 : res.bailOptimistic)) { - mutable.previousTree = state.tree; - mutable.patchedTree = optimisticTree; - mutable.pendingPush = pendingPush; - mutable.hashFragment = hash; - mutable.scrollableSegments = []; - mutable.cache = temporaryCacheNode; - mutable.canonicalUrl = href; - state.prefetchCache.set((0, _createhreffromurl.createHrefFromUrl)(url, false), { - data: Promise.resolve(data), - // this will make sure that the entry will be discarded after 30s - kind: _routerreducertypes.PrefetchKind.TEMPORARY, - prefetchTime: Date.now(), - treeAtTimeOfPrefetch: state.tree, - lastUsedTime: Date.now() - }); - return (0, _handlemutable.handleMutable)(state, mutable); - } - } - // If we don't have a prefetch value, we need to create one - if (!prefetchValues) { - const data = (0, _createrecordfromthenable.createRecordFromThenable)((0, _fetchserverresponse.fetchServerResponse)(url, state.tree, state.nextUrl)); - const newPrefetchValue = { - data: Promise.resolve(data), - // this will make sure that the entry will be discarded after 30s - kind: _routerreducertypes.PrefetchKind.TEMPORARY, - prefetchTime: Date.now(), - treeAtTimeOfPrefetch: state.tree, - lastUsedTime: null - }; - state.prefetchCache.set((0, _createhreffromurl.createHrefFromUrl)(url, false), newPrefetchValue); - prefetchValues = newPrefetchValue; - } - const prefetchEntryCacheStatus = (0, _getprefetchcacheentrystatus.getPrefetchEntryCacheStatus)(prefetchValues); - // The one before last item is the router state tree patch - const { treeAtTimeOfPrefetch , data } = prefetchValues; - // Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves. - const [flightData, canonicalUrlOverride] = (0, _readrecordvalue.readRecordValue)(data); - // important: we should only mark the cache node as dirty after we unsuspend from the call above - prefetchValues.lastUsedTime = Date.now(); - // Handle case when navigating to page in `pages` from `app` - if (typeof flightData === "string") { - return handleExternalUrl(state, mutable, flightData, pendingPush); - } - let currentTree = state.tree; - let currentCache = state.cache; - let scrollableSegments = []; - for (const flightDataPath of flightData){ - const flightSegmentPath = flightDataPath.slice(0, -4); - // The one before last item is the router state tree patch - const [treePatch] = flightDataPath.slice(-3); - // Create new tree based on the flightSegmentPath and router state patch - let newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)([ - "", - ...flightSegmentPath - ], currentTree, treePatch); - // If the tree patch can't be applied to the current tree then we use the tree at time of prefetch - // TODO-APP: This should instead fill in the missing pieces in `currentTree` with the data from `treeAtTimeOfPrefetch`, then apply the patch. - if (newTree === null) { - newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)([ - "", - ...flightSegmentPath - ], treeAtTimeOfPrefetch, treePatch); - } - if (newTree !== null) { - if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) { - return handleExternalUrl(state, mutable, href, pendingPush); - } - let applied = (0, _applyflightdata.applyFlightData)(currentCache, cache, flightDataPath, prefetchValues.kind === "auto" && prefetchEntryCacheStatus === _getprefetchcacheentrystatus.PrefetchCacheEntryStatus.reusable); - if (!applied && prefetchEntryCacheStatus === _getprefetchcacheentrystatus.PrefetchCacheEntryStatus.stale) { - applied = addRefetchToLeafSegments(cache, currentCache, flightSegmentPath, treePatch, ()=>(0, _fetchserverresponse.fetchServerResponse)(url, currentTree, state.nextUrl)); - } - const hardNavigate = (0, _shouldhardnavigate.shouldHardNavigate)([ - "", - ...flightSegmentPath - ], currentTree); - if (hardNavigate) { - cache.status = _approutercontext.CacheStates.READY; - // Copy subTreeData for the root node of the cache. - cache.subTreeData = currentCache.subTreeData; - (0, _invalidatecachebelowflightsegmentpath.invalidateCacheBelowFlightSegmentPath)(cache, currentCache, flightSegmentPath); - // Ensure the existing cache value is used when the cache was not invalidated. - mutable.cache = cache; - } else if (applied) { - mutable.cache = cache; - } - currentCache = cache; - currentTree = newTree; - for (const subSegment of generateSegmentsFromPatch(treePatch)){ - const scrollableSegmentPath = [ - ...flightSegmentPath, - ...subSegment - ]; - // Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case. - if (scrollableSegmentPath[scrollableSegmentPath.length - 1] !== "__DEFAULT__") { - scrollableSegments.push(scrollableSegmentPath); - } - } - } - } - mutable.previousTree = state.tree; - mutable.patchedTree = currentTree; - mutable.scrollableSegments = scrollableSegments; - mutable.canonicalUrl = canonicalUrlOverride ? (0, _createhreffromurl.createHrefFromUrl)(canonicalUrlOverride) : href; - mutable.pendingPush = pendingPush; - mutable.hashFragment = hash; - return (0, _handlemutable.handleMutable)(state, mutable); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=navigate-reducer.js.map - - -/***/ }), - -/***/ 8411: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "prefetchReducer", ({ - enumerable: true, - get: function() { - return prefetchReducer; - } -})); -const _createhreffromurl = __webpack_require__(8253); -const _fetchserverresponse = __webpack_require__(969); -const _routerreducertypes = __webpack_require__(549); -const _createrecordfromthenable = __webpack_require__(5792); -const _pruneprefetchcache = __webpack_require__(1262); -function prefetchReducer(state, action) { - // let's prune the prefetch cache before we do anything else - (0, _pruneprefetchcache.prunePrefetchCache)(state.prefetchCache); - const { url } = action; - const href = (0, _createhreffromurl.createHrefFromUrl)(url, false); - const cacheEntry = state.prefetchCache.get(href); - if (cacheEntry) { - /** - * If the cache entry present was marked as temporary, it means that we prefetched it from the navigate reducer, - * where we didn't have the prefetch intent. We want to update it to the new, more accurate, kind here. - */ if (cacheEntry.kind === _routerreducertypes.PrefetchKind.TEMPORARY) { - state.prefetchCache.set(href, { - ...cacheEntry, - kind: action.kind - }); - } - /** - * if the prefetch action was a full prefetch and that the current cache entry wasn't one, we want to re-prefetch, - * otherwise we can re-use the current cache entry - **/ if (!(cacheEntry.kind === _routerreducertypes.PrefetchKind.AUTO && action.kind === _routerreducertypes.PrefetchKind.FULL)) { - return state; - } - } - // fetchServerResponse is intentionally not awaited so that it can be unwrapped in the navigate-reducer - const serverResponse = (0, _createrecordfromthenable.createRecordFromThenable)((0, _fetchserverresponse.fetchServerResponse)(url, state.tree, state.nextUrl, action.kind)); - // Create new tree based on the flightSegmentPath and router state patch - state.prefetchCache.set(href, { - // Create new tree based on the flightSegmentPath and router state patch - treeAtTimeOfPrefetch: state.tree, - data: serverResponse, - kind: action.kind, - prefetchTime: Date.now(), - lastUsedTime: null - }); - return state; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=prefetch-reducer.js.map - - -/***/ }), - -/***/ 1262: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "prunePrefetchCache", ({ - enumerable: true, - get: function() { - return prunePrefetchCache; - } -})); -const _getprefetchcacheentrystatus = __webpack_require__(9362); -function prunePrefetchCache(prefetchCache) { - for (const [href, prefetchCacheEntry] of prefetchCache){ - if ((0, _getprefetchcacheentrystatus.getPrefetchEntryCacheStatus)(prefetchCacheEntry) === _getprefetchcacheentrystatus.PrefetchCacheEntryStatus.expired) { - prefetchCache.delete(href); - } - } -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=prune-prefetch-cache.js.map - - -/***/ }), - -/***/ 9153: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "refreshReducer", ({ - enumerable: true, - get: function() { - return refreshReducer; - } -})); -const _fetchserverresponse = __webpack_require__(969); -const _createrecordfromthenable = __webpack_require__(5792); -const _readrecordvalue = __webpack_require__(4170); -const _createhreffromurl = __webpack_require__(8253); -const _applyrouterstatepatchtotree = __webpack_require__(951); -const _isnavigatingtonewrootlayout = __webpack_require__(9610); -const _navigatereducer = __webpack_require__(1935); -const _handlemutable = __webpack_require__(5098); -const _approutercontext = __webpack_require__(3280); -const _filllazyitemstillleafwithhead = __webpack_require__(985); -function refreshReducer(state, action) { - const { cache , mutable , origin } = action; - const href = state.canonicalUrl; - const isForCurrentTree = JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree); - if (isForCurrentTree) { - return (0, _handlemutable.handleMutable)(state, mutable); - } - if (!cache.data) { - // TODO-APP: verify that `href` is not an external url. - // Fetch data from the root of the tree. - cache.data = (0, _createrecordfromthenable.createRecordFromThenable)((0, _fetchserverresponse.fetchServerResponse)(new URL(href, origin), [ - state.tree[0], - state.tree[1], - state.tree[2], - "refetch" - ], state.nextUrl)); - } - const [flightData, canonicalUrlOverride] = (0, _readrecordvalue.readRecordValue)(cache.data); - // Handle case when navigating to page in `pages` from `app` - if (typeof flightData === "string") { - return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush); - } - // Remove cache.data as it has been resolved at this point. - cache.data = null; - let currentTree = state.tree; - for (const flightDataPath of flightData){ - // FlightDataPath with more than two items means unexpected Flight data was returned - if (flightDataPath.length !== 3) { - // TODO-APP: handle this case better - console.log("REFRESH FAILED"); - return state; - } - // Given the path can only have two items the items are only the router state and subTreeData for the root. - const [treePatch] = flightDataPath; - const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)([ - "" - ], currentTree, treePatch); - if (newTree === null) { - throw new Error("SEGMENT MISMATCH"); - } - if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) { - return (0, _navigatereducer.handleExternalUrl)(state, mutable, href, state.pushRef.pendingPush); - } - const canonicalUrlOverrideHref = canonicalUrlOverride ? (0, _createhreffromurl.createHrefFromUrl)(canonicalUrlOverride) : undefined; - if (canonicalUrlOverride) { - mutable.canonicalUrl = canonicalUrlOverrideHref; - } - // The one before last item is the router state tree patch - const [subTreeData, head] = flightDataPath.slice(-2); - // Handles case where prefetch only returns the router tree patch without rendered components. - if (subTreeData !== null) { - cache.status = _approutercontext.CacheStates.READY; - cache.subTreeData = subTreeData; - (0, _filllazyitemstillleafwithhead.fillLazyItemsTillLeafWithHead)(cache, undefined, treePatch, head); - mutable.cache = cache; - mutable.prefetchCache = new Map(); - } - mutable.previousTree = currentTree; - mutable.patchedTree = newTree; - mutable.canonicalUrl = href; - currentTree = newTree; - } - return (0, _handlemutable.handleMutable)(state, mutable); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=refresh-reducer.js.map - - -/***/ }), - -/***/ 734: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "restoreReducer", ({ - enumerable: true, - get: function() { - return restoreReducer; - } -})); -const _createhreffromurl = __webpack_require__(8253); -function restoreReducer(state, action) { - const { url , tree } = action; - const href = (0, _createhreffromurl.createHrefFromUrl)(url); - return { - // Set canonical url - canonicalUrl: href, - pushRef: state.pushRef, - focusAndScrollRef: state.focusAndScrollRef, - cache: state.cache, - prefetchCache: state.prefetchCache, - // Restore provided tree - tree: tree, - nextUrl: url.pathname - }; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=restore-reducer.js.map - - -/***/ }), - -/***/ 7647: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "serverActionReducer", ({ - enumerable: true, - get: function() { - return serverActionReducer; - } -})); -const _appcallserver = __webpack_require__(4783); -const _approuterheaders = __webpack_require__(281); -const _createrecordfromthenable = __webpack_require__(5792); -const _readrecordvalue = __webpack_require__(4170); -const _client = __webpack_require__(7897); -const _routerreducertypes = __webpack_require__(549); -const _addbasepath = __webpack_require__(739); -const _createhreffromurl = __webpack_require__(8253); -const _redirect = __webpack_require__(6932); -async function fetchServerAction(state, param) { - let { actionId , actionArgs } = param; - const body = await (0, _client.encodeReply)(actionArgs); - const res = await fetch("", { - method: "POST", - headers: { - Accept: _approuterheaders.RSC_CONTENT_TYPE_HEADER, - "Next-Action": actionId, - [_approuterheaders.NEXT_ROUTER_STATE_TREE]: JSON.stringify(state.tree), - ...state.nextUrl ? { - [_approuterheaders.NEXT_URL]: state.nextUrl - } : {} - }, - body - }); - const location = res.headers.get("x-action-redirect"); - const redirectLocation = location ? new URL((0, _addbasepath.addBasePath)(location), window.location.origin) : undefined; - let isFlightResponse = res.headers.get("content-type") === _approuterheaders.RSC_CONTENT_TYPE_HEADER; - if (isFlightResponse) { - const result = await (0, _client.createFromFetch)(Promise.resolve(res), { - callServer: _appcallserver.callServer - }); - // if it was a redirection, then result is just a regular RSC payload - if (location) { - return { - actionFlightData: result, - redirectLocation - }; - // otherwise it's a tuple of [actionResult, actionFlightData] - } else { - const [actionResult, actionFlightData] = result != null ? result : []; - return { - actionResult, - actionFlightData, - redirectLocation - }; - } - } - return { - redirectLocation - }; -} -function serverActionReducer(state, action) { - // the action could be called twice so we need to check if we already have applied it - if (action.mutable.serverActionApplied) { - return state; - } - if (!action.mutable.inFlightServerAction) { - action.mutable.previousTree = state.tree; - action.mutable.previousUrl = state.canonicalUrl; - action.mutable.inFlightServerAction = (0, _createrecordfromthenable.createRecordFromThenable)(fetchServerAction(state, action)); - } - try { - // suspends until the server action is resolved. - const { actionResult , actionFlightData , redirectLocation } = (0, _readrecordvalue.readRecordValue)(action.mutable.inFlightServerAction); - if (redirectLocation) { - // the redirection might have a flight data associated with it, so we'll populate the cache with it - if (actionFlightData) { - const href = (0, _createhreffromurl.createHrefFromUrl)(redirectLocation, false); - const previousCacheEntry = state.prefetchCache.get(href); - var _previousCacheEntry_kind; - state.prefetchCache.set(href, { - data: (0, _createrecordfromthenable.createRecordFromThenable)(Promise.resolve([ - actionFlightData, - // TODO-APP: verify the logic around canonical URL overrides - undefined - ])), - kind: (_previousCacheEntry_kind = previousCacheEntry == null ? void 0 : previousCacheEntry.kind) != null ? _previousCacheEntry_kind : _routerreducertypes.PrefetchKind.TEMPORARY, - prefetchTime: Date.now(), - treeAtTimeOfPrefetch: action.mutable.previousTree, - lastUsedTime: null - }); - } - // we throw the redirection in the action handler so that it is caught during render - action.reject((0, _redirect.getRedirectError)(redirectLocation.toString(), _redirect.RedirectType.push)); - } else { - if (actionFlightData) { - const href = (0, _createhreffromurl.createHrefFromUrl)(new URL(action.mutable.previousUrl, window.location.origin), false); - const previousCacheEntry = state.prefetchCache.get(href); - var _previousCacheEntry_kind1; - state.prefetchCache.set((0, _createhreffromurl.createHrefFromUrl)(new URL(action.mutable.previousUrl, window.location.origin), false), { - data: (0, _createrecordfromthenable.createRecordFromThenable)(Promise.resolve([ - actionFlightData, - // TODO-APP: verify the logic around canonical URL overrides - undefined - ])), - kind: (_previousCacheEntry_kind1 = previousCacheEntry == null ? void 0 : previousCacheEntry.kind) != null ? _previousCacheEntry_kind1 : _routerreducertypes.PrefetchKind.TEMPORARY, - prefetchTime: Date.now(), - treeAtTimeOfPrefetch: action.mutable.previousTree, - lastUsedTime: null - }); - // this is an intentional hack around React: we want to update the tree in a new render - setTimeout(()=>{ - action.changeByServerResponse(action.mutable.previousTree, actionFlightData, undefined); - }); - } - action.resolve(actionResult); - } - } catch (e) { - if (e.status === "rejected") { - action.reject(e.value); - } else { - throw e; - } - } - action.mutable.serverActionApplied = true; - return state; -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=server-action-reducer.js.map - - -/***/ }), - -/***/ 2813: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "serverPatchReducer", ({ - enumerable: true, - get: function() { - return serverPatchReducer; - } -})); -const _createhreffromurl = __webpack_require__(8253); -const _applyrouterstatepatchtotree = __webpack_require__(951); -const _isnavigatingtonewrootlayout = __webpack_require__(9610); -const _navigatereducer = __webpack_require__(1935); -const _applyflightdata = __webpack_require__(8837); -const _handlemutable = __webpack_require__(5098); -function serverPatchReducer(state, action) { - const { flightData , previousTree , overrideCanonicalUrl , cache , mutable } = action; - const isForCurrentTree = JSON.stringify(previousTree) === JSON.stringify(state.tree); - // When a fetch is slow to resolve it could be that you navigated away while the request was happening or before the reducer runs. - // In that case opt-out of applying the patch given that the data could be stale. - if (!isForCurrentTree) { - // TODO-APP: Handle tree mismatch - console.log("TREE MISMATCH"); - // Keep everything as-is. - return state; - } - if (mutable.previousTree) { - return (0, _handlemutable.handleMutable)(state, mutable); - } - // Handle case when navigating to page in `pages` from `app` - if (typeof flightData === "string") { - return (0, _navigatereducer.handleExternalUrl)(state, mutable, flightData, state.pushRef.pendingPush); - } - let currentTree = state.tree; - let currentCache = state.cache; - for (const flightDataPath of flightData){ - // Slices off the last segment (which is at -4) as it doesn't exist in the tree yet - const flightSegmentPath = flightDataPath.slice(0, -4); - const [treePatch] = flightDataPath.slice(-3, -2); - const newTree = (0, _applyrouterstatepatchtotree.applyRouterStatePatchToTree)([ - "", - ...flightSegmentPath - ], currentTree, treePatch); - if (newTree === null) { - throw new Error("SEGMENT MISMATCH"); - } - if ((0, _isnavigatingtonewrootlayout.isNavigatingToNewRootLayout)(currentTree, newTree)) { - return (0, _navigatereducer.handleExternalUrl)(state, mutable, state.canonicalUrl, state.pushRef.pendingPush); - } - const canonicalUrlOverrideHref = overrideCanonicalUrl ? (0, _createhreffromurl.createHrefFromUrl)(overrideCanonicalUrl) : undefined; - if (canonicalUrlOverrideHref) { - mutable.canonicalUrl = canonicalUrlOverrideHref; - } - (0, _applyflightdata.applyFlightData)(currentCache, cache, flightDataPath); - mutable.previousTree = currentTree; - mutable.patchedTree = newTree; - mutable.cache = cache; - currentCache = cache; - currentTree = newTree; - } - return (0, _handlemutable.handleMutable)(state, mutable); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=server-patch-reducer.js.map - - -/***/ }), - -/***/ 549: -/***/ ((module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - PrefetchKind: function() { - return PrefetchKind; - }, - ACTION_REFRESH: function() { - return ACTION_REFRESH; - }, - ACTION_NAVIGATE: function() { - return ACTION_NAVIGATE; - }, - ACTION_RESTORE: function() { - return ACTION_RESTORE; - }, - ACTION_SERVER_PATCH: function() { - return ACTION_SERVER_PATCH; - }, - ACTION_PREFETCH: function() { - return ACTION_PREFETCH; - }, - ACTION_FAST_REFRESH: function() { - return ACTION_FAST_REFRESH; - }, - ACTION_SERVER_ACTION: function() { - return ACTION_SERVER_ACTION; - } -}); -const ACTION_REFRESH = "refresh"; -const ACTION_NAVIGATE = "navigate"; -const ACTION_RESTORE = "restore"; -const ACTION_SERVER_PATCH = "server-patch"; -const ACTION_PREFETCH = "prefetch"; -const ACTION_FAST_REFRESH = "fast-refresh"; -const ACTION_SERVER_ACTION = "server-action"; -var PrefetchKind; -(function(PrefetchKind) { - PrefetchKind["AUTO"] = "auto"; - PrefetchKind["FULL"] = "full"; - PrefetchKind["TEMPORARY"] = "temporary"; -})(PrefetchKind || (PrefetchKind = {})); -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=router-reducer-types.js.map - - -/***/ }), - -/***/ 5192: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "reducer", ({ - enumerable: true, - get: function() { - return reducer; - } -})); -const _routerreducertypes = __webpack_require__(549); -const _navigatereducer = __webpack_require__(1935); -const _serverpatchreducer = __webpack_require__(2813); -const _restorereducer = __webpack_require__(734); -const _refreshreducer = __webpack_require__(9153); -const _prefetchreducer = __webpack_require__(8411); -const _fastrefreshreducer = __webpack_require__(7709); -const _serveractionreducer = __webpack_require__(7647); -/** - * Reducer that handles the app-router state updates. - */ function clientReducer(state, action) { - switch(action.type){ - case _routerreducertypes.ACTION_NAVIGATE: - { - return (0, _navigatereducer.navigateReducer)(state, action); - } - case _routerreducertypes.ACTION_SERVER_PATCH: - { - return (0, _serverpatchreducer.serverPatchReducer)(state, action); - } - case _routerreducertypes.ACTION_RESTORE: - { - return (0, _restorereducer.restoreReducer)(state, action); - } - case _routerreducertypes.ACTION_REFRESH: - { - return (0, _refreshreducer.refreshReducer)(state, action); - } - case _routerreducertypes.ACTION_FAST_REFRESH: - { - return (0, _fastrefreshreducer.fastRefreshReducer)(state, action); - } - case _routerreducertypes.ACTION_PREFETCH: - { - return (0, _prefetchreducer.prefetchReducer)(state, action); - } - case _routerreducertypes.ACTION_SERVER_ACTION: - { - return (0, _serveractionreducer.serverActionReducer)(state, action); - } - // This case should never be hit as dispatch is strongly typed. - default: - throw new Error("Unknown action"); - } -} -function serverReducer(state, _action) { - return state; -} -const reducer = true ? serverReducer : 0; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=router-reducer.js.map - - -/***/ }), - -/***/ 9425: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "shouldHardNavigate", ({ - enumerable: true, - get: function() { - return shouldHardNavigate; - } -})); -const _matchsegments = __webpack_require__(5507); -function shouldHardNavigate(flightSegmentPath, flightRouterState) { - const [segment, parallelRoutes] = flightRouterState; - // TODO-APP: Check if `as` can be replaced. - const [currentSegment, parallelRouteKey] = flightSegmentPath; - // Check if current segment matches the existing segment. - if (!(0, _matchsegments.matchSegment)(currentSegment, segment)) { - // If dynamic parameter in tree doesn't match up with segment path a hard navigation is triggered. - if (Array.isArray(currentSegment)) { - return true; - } - // If the existing segment did not match soft navigation is triggered. - return false; - } - const lastSegment = flightSegmentPath.length <= 2; - if (lastSegment) { - return false; - } - return shouldHardNavigate(flightSegmentPath.slice(2), parallelRoutes[parallelRouteKey]); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=should-hard-navigate.js.map - - -/***/ }), - -/***/ 9859: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createSearchParamsBailoutProxy", ({ - enumerable: true, - get: function() { - return createSearchParamsBailoutProxy; - } -})); -const _staticgenerationbailout = __webpack_require__(9837); -function createSearchParamsBailoutProxy() { - return new Proxy({}, { - get (_target, prop) { - // React adds some properties on the object when serializing for client components - if (typeof prop === "string") { - (0, _staticgenerationbailout.staticGenerationBailout)("searchParams." + prop); - } - } - }); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=searchparams-bailout-proxy.js.map - - -/***/ }), - -/***/ 9837: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "staticGenerationBailout", ({ - enumerable: true, - get: function() { - return staticGenerationBailout; - } -})); -const _hooksservercontext = __webpack_require__(8340); -const _staticgenerationasyncstorage = __webpack_require__(94); -class StaticGenBailoutError extends Error { - constructor(...args){ - super(...args); - this.code = "NEXT_STATIC_GEN_BAILOUT"; - } -} -const staticGenerationBailout = (reason, opts)=>{ - const staticGenerationStore = _staticgenerationasyncstorage.staticGenerationAsyncStorage.getStore(); - if (staticGenerationStore == null ? void 0 : staticGenerationStore.forceStatic) { - return true; - } - if (staticGenerationStore == null ? void 0 : staticGenerationStore.dynamicShouldError) { - const { dynamic ="error" , link } = opts || {}; - const suffix = link ? " See more info here: " + link : ""; - throw new StaticGenBailoutError('Page with `dynamic = "' + dynamic + "\"` couldn't be rendered statically because it used `" + reason + "`." + suffix); - } - if (staticGenerationStore) { - staticGenerationStore.revalidate = 0; - } - if (staticGenerationStore == null ? void 0 : staticGenerationStore.isStaticGeneration) { - const err = new _hooksservercontext.DynamicServerError(reason); - staticGenerationStore.dynamicUsageDescription = reason; - staticGenerationStore.dynamicUsageStack = err.stack; - throw err; - } - return false; -}; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=static-generation-bailout.js.map - - -/***/ }), - -/***/ 3100: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "default", ({ - enumerable: true, - get: function() { - return StaticGenerationSearchParamsBailoutProvider; - } -})); -const _interop_require_default = __webpack_require__(5967); -const _react = /*#__PURE__*/ _interop_require_default._(__webpack_require__(8038)); -const _searchparamsbailoutproxy = __webpack_require__(9859); -function StaticGenerationSearchParamsBailoutProvider(param) { - let { Component , propsForComponent } = param; - const searchParams = (0, _searchparamsbailoutproxy.createSearchParamsBailoutProxy)(); - return /*#__PURE__*/ _react.default.createElement(Component, { - searchParams: searchParams, - ...propsForComponent - }); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=static-generation-searchparams-bailout-provider.js.map - - -/***/ }), - -/***/ 9051: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "useReducerWithReduxDevtools", ({ - enumerable: true, - get: function() { - return useReducerWithReduxDevtools; - } -})); -const _react = __webpack_require__(8038); -function normalizeRouterState(val) { - if (val instanceof Map) { - const obj = {}; - for (const [key, value] of val.entries()){ - if (typeof value === "function") { - obj[key] = "fn()"; - continue; - } - if (typeof value === "object" && value !== null) { - if (value.$$typeof) { - obj[key] = value.$$typeof.toString(); - continue; - } - if (value._bundlerConfig) { - obj[key] = "FlightData"; - continue; - } - } - obj[key] = normalizeRouterState(value); - } - return obj; - } - if (typeof val === "object" && val !== null) { - const obj = {}; - for(const key in val){ - const value = val[key]; - if (typeof value === "function") { - obj[key] = "fn()"; - continue; - } - if (typeof value === "object" && value !== null) { - if (value.$$typeof) { - obj[key] = value.$$typeof.toString(); - continue; - } - if (value.hasOwnProperty("_bundlerConfig")) { - obj[key] = "FlightData"; - continue; - } - } - obj[key] = normalizeRouterState(value); - } - return obj; - } - if (Array.isArray(val)) { - return val.map(normalizeRouterState); - } - return val; -} -function devToolReducer(fn, ref) { - return (state, action)=>{ - const res = fn(state, action); - if (ref.current) { - ref.current.send(action, normalizeRouterState(res)); - } - return res; - }; -} -function useReducerWithReduxDevtoolsNoop(fn, initialState) { - const [state, dispatch] = (0, _react.useReducer)(fn, initialState); - return [ - state, - dispatch, - ()=>{} - ]; -} -function useReducerWithReduxDevtoolsImpl(fn, initialState) { - const devtoolsConnectionRef = (0, _react.useRef)(); - const enabledRef = (0, _react.useRef)(); - (0, _react.useEffect)(()=>{ - if (devtoolsConnectionRef.current || enabledRef.current === false) { - return; - } - if (enabledRef.current === undefined && typeof window.__REDUX_DEVTOOLS_EXTENSION__ === "undefined") { - enabledRef.current = false; - return; - } - devtoolsConnectionRef.current = window.__REDUX_DEVTOOLS_EXTENSION__.connect({ - instanceId: 8000, - name: "next-router" - }); - if (devtoolsConnectionRef.current) { - devtoolsConnectionRef.current.init(normalizeRouterState(initialState)); - } - return ()=>{ - devtoolsConnectionRef.current = undefined; - }; - }, [ - initialState - ]); - const [state, dispatch] = (0, _react.useReducer)(devToolReducer(/* logReducer( */ fn /*)*/ , devtoolsConnectionRef), initialState); - const sync = (0, _react.useCallback)(()=>{ - if (devtoolsConnectionRef.current) { - devtoolsConnectionRef.current.send({ - type: "RENDER_SYNC" - }, normalizeRouterState(state)); - } - }, [ - state - ]); - return [ - state, - dispatch, - sync - ]; -} -const useReducerWithReduxDevtools = false ? 0 : useReducerWithReduxDevtoolsNoop; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=use-reducer-with-devtools.js.map - - -/***/ }), - -/***/ 6089: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "normalizePathTrailingSlash", ({ - enumerable: true, - get: function() { - return normalizePathTrailingSlash; - } -})); -const _removetrailingslash = __webpack_require__(3297); -const _parsepath = __webpack_require__(8854); -const normalizePathTrailingSlash = (path)=>{ - if (!path.startsWith("/") || undefined) { - return path; - } - const { pathname , query , hash } = (0, _parsepath.parsePath)(path); - if (false) {} - return "" + (0, _removetrailingslash.removeTrailingSlash)(pathname) + query + hash; -}; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=normalize-trailing-slash.js.map - - -/***/ }), - -/***/ 701: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - suspense: function() { - return suspense; - }, - NoSSR: function() { - return NoSSR; - } -}); -const _interop_require_default = __webpack_require__(5967); -const _react = /*#__PURE__*/ _interop_require_default._(__webpack_require__(8038)); -const _nossrerror = __webpack_require__(3904); -function suspense() { - const error = new Error(_nossrerror.NEXT_DYNAMIC_NO_SSR_CODE); - error.digest = _nossrerror.NEXT_DYNAMIC_NO_SSR_CODE; - throw error; -} -function NoSSR(param) { - let { children } = param; - if (true) { - suspense(); - } - return children; -} //# sourceMappingURL=dynamic-no-ssr.js.map - - -/***/ }), - -/***/ 3904: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -// This has to be a shared module which is shared between client component error boundary and dynamic component - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "NEXT_DYNAMIC_NO_SSR_CODE", ({ - enumerable: true, - get: function() { - return NEXT_DYNAMIC_NO_SSR_CODE; - } -})); -const NEXT_DYNAMIC_NO_SSR_CODE = "NEXT_DYNAMIC_NO_SSR_CODE"; //# sourceMappingURL=no-ssr-error.js.map - - -/***/ }), - -/***/ 1313: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/** - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ // Modified from https://github.com/facebook/react/blob/main/packages/react-server-dom-webpack/src/ReactFlightWebpackNodeRegister.js - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createProxy", ({ - enumerable: true, - get: function() { - return createProxy; - } -})); -const CLIENT_REFERENCE = Symbol.for("react.client.reference"); -const PROMISE_PROTOTYPE = Promise.prototype; -const deepProxyHandlers = { - get: function(target, name, _receiver) { - switch(name){ - // These names are read by the Flight runtime if you end up using the exports object. - case "$$typeof": - // These names are a little too common. We should probably have a way to - // have the Flight runtime extract the inner target instead. - return target.$$typeof; - case "$$id": - return target.$$id; - case "$$async": - return target.$$async; - case "name": - return target.name; - case "displayName": - return undefined; - // We need to special case this because createElement reads it if we pass this - // reference. - case "defaultProps": - return undefined; - // Avoid this attempting to be serialized. - case "toJSON": - return undefined; - case Symbol.toPrimitive.toString(): - // @ts-ignore - return Object.prototype[Symbol.toPrimitive]; - case "Provider": - throw new Error(`Cannot render a Client Context Provider on the Server. ` + `Instead, you can export a Client Component wrapper ` + `that itself renders a Client Context Provider.`); - default: - break; - } - const expression = String(target.name) + "." + String(name); - throw new Error(`Cannot access ${expression} on the server. ` + "You cannot dot into a client module from a server component. " + "You can only pass the imported name through."); - }, - set: function() { - throw new Error("Cannot assign to a client module from a server module."); - } -}; -const proxyHandlers = { - get: function(target, name, _receiver) { - switch(name){ - // These names are read by the Flight runtime if you end up using the exports object. - case "$$typeof": - return target.$$typeof; - case "$$id": - return target.$$id; - case "$$async": - return target.$$async; - case "name": - return target.name; - // We need to special case this because createElement reads it if we pass this - // reference. - case "defaultProps": - return undefined; - // Avoid this attempting to be serialized. - case "toJSON": - return undefined; - case Symbol.toPrimitive.toString(): - // @ts-ignore - return Object.prototype[Symbol.toPrimitive]; - case "__esModule": - // Something is conditionally checking which export to use. We'll pretend to be - // an ESM compat module but then we'll check again on the client. - const moduleId = target.$$id; - target.default = Object.defineProperties(function() { - throw new Error(`Attempted to call the default export of ${moduleId} from the server ` + `but it's on the client. It's not possible to invoke a client function from ` + `the server, it can only be rendered as a Component or passed to props of a ` + `Client Component.`); - }, { - $$typeof: { - value: CLIENT_REFERENCE - }, - // This a placeholder value that tells the client to conditionally use the - // whole object or just the default export. - $$id: { - value: target.$$id + "#" - }, - $$async: { - value: target.$$async - } - }); - return true; - case "then": - if (target.then) { - // Use a cached value - return target.then; - } - if (!target.$$async) { - // If this module is expected to return a Promise (such as an AsyncModule) then - // we should resolve that with a client reference that unwraps the Promise on - // the client. - const clientReference = Object.defineProperties({}, { - $$typeof: { - value: CLIENT_REFERENCE - }, - $$id: { - value: target.$$id - }, - $$async: { - value: true - } - }); - const proxy = new Proxy(clientReference, proxyHandlers); - // Treat this as a resolved Promise for React's use() - target.status = "fulfilled"; - target.value = proxy; - const then = target.then = Object.defineProperties(function then(resolve, _reject) { - // Expose to React. - return Promise.resolve(resolve(proxy)); - }, // export then we should treat it as a reference to that name. - { - $$typeof: { - value: CLIENT_REFERENCE - }, - $$id: { - value: target.$$id - }, - $$async: { - value: false - } - }); - return then; - } else { - // Since typeof .then === 'function' is a feature test we'd continue recursing - // indefinitely if we return a function. Instead, we return an object reference - // if we check further. - return undefined; - } - default: - break; - } - let cachedReference = target[name]; - if (!cachedReference) { - const reference = Object.defineProperties(function() { - throw new Error(`Attempted to call ${String(name)}() from the server but ${String(name)} is on the client. ` + `It's not possible to invoke a client function from the server, it can ` + `only be rendered as a Component or passed to props of a Client Component.`); - }, { - $$typeof: { - value: CLIENT_REFERENCE - }, - $$id: { - value: target.$$id + "#" + name - }, - $$async: { - value: target.$$async - } - }); - cachedReference = target[name] = new Proxy(reference, deepProxyHandlers); - } - return cachedReference; - }, - getPrototypeOf (_target) { - // Pretend to be a Promise in case anyone asks. - return PROMISE_PROTOTYPE; - }, - set: function() { - throw new Error("Cannot assign to a client module from a server module."); - } -}; -function createProxy(moduleId) { - const clientReference = Object.defineProperties({}, { - $$typeof: { - value: CLIENT_REFERENCE - }, - // Represents the whole Module object instead of a particular import. - $$id: { - value: moduleId - }, - $$async: { - value: false - } - }); - return new Proxy(clientReference, proxyHandlers); -} //# sourceMappingURL=module-proxy.js.map - - -/***/ }), - -/***/ 4592: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -const { createProxy } = __webpack_require__(1313); -module.exports = createProxy("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js"); - //# sourceMappingURL=app-router.js.map - - -/***/ }), - -/***/ 2673: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -const { createProxy } = __webpack_require__(1313); -module.exports = createProxy("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js"); - //# sourceMappingURL=error-boundary.js.map - - -/***/ }), - -/***/ 6301: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -const { createProxy } = __webpack_require__(1313); -module.exports = createProxy("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js"); - //# sourceMappingURL=layout-router.js.map - - -/***/ }), - -/***/ 7431: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -const { createProxy } = __webpack_require__(1313); -module.exports = createProxy("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js"); - //# sourceMappingURL=render-from-template-context.js.map - - -/***/ }), - -/***/ 2527: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "createSearchParamsBailoutProxy", ({ - enumerable: true, - get: function() { - return createSearchParamsBailoutProxy; - } -})); -const _staticgenerationbailout = __webpack_require__(5486); -function createSearchParamsBailoutProxy() { - return new Proxy({}, { - get (_target, prop) { - // React adds some properties on the object when serializing for client components - if (typeof prop === "string") { - (0, _staticgenerationbailout.staticGenerationBailout)("searchParams." + prop); - } - } - }); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=searchparams-bailout-proxy.js.map - - -/***/ }), - -/***/ 6404: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; -/* __next_internal_client_entry_do_not_use__ cjs */ -const { createProxy } = __webpack_require__(1313); -module.exports = createProxy("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js"); - //# sourceMappingURL=static-generation-searchparams-bailout-provider.js.map - - -/***/ }), - -/***/ 362: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/** - * @license React - * react-dom-server-rendering-stub.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -var d = { - usingClientEntryPoint: !1, - Events: null, - Dispatcher: { - current: null - } -}; -function e(c) { - for(var b = "https://reactjs.org/docs/error-decoder.html?invariant=" + c, a = 1; a < arguments.length; a++)b += "&args[]=" + encodeURIComponent(arguments[a]); - return "Minified React error #" + c + "; visit " + b + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."; -} -var f = d.Dispatcher; -exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = d; -exports.createPortal = function() { - throw Error(e(448)); -}; -exports.experimental_useFormStatus = function() { - throw Error(e(248)); -}; -exports.flushSync = function() { - throw Error(e(449)); -}; -exports.preconnect = function(c, b) { - var a = f.current; - a && a.preconnect(c, b); -}; -exports.prefetchDNS = function(c) { - var b = f.current; - b && b.prefetchDNS(c); -}; -exports.preinit = function(c, b) { - var a = f.current; - a && a.preinit(c, b); -}; -exports.preload = function(c, b) { - var a = f.current; - a && a.preload(c, b); -}; -exports.version = "18.3.0-canary-16d053d59-20230506"; - - -/***/ }), - -/***/ 6155: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -if (true) { - module.exports = __webpack_require__(362); -} else {} - - -/***/ }), - -/***/ 8387: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -/** - * @license React - * react-server-dom-webpack-server.edge.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -var aa = __webpack_require__(7887), ba = __webpack_require__(6155), l = null, m = 0; -function n(a, b) { - if (0 !== b.length) if (512 < b.length) 0 < m && (a.enqueue(new Uint8Array(l.buffer, 0, m)), l = new Uint8Array(512), m = 0), a.enqueue(b); - else { - var d = l.length - m; - d < b.length && (0 === d ? a.enqueue(l) : (l.set(b.subarray(0, d), m), a.enqueue(l), b = b.subarray(d)), l = new Uint8Array(512), m = 0); - l.set(b, m); - m += b.length; - } - return !0; -} -var p = new TextEncoder; -function ca(a, b) { - "function" === typeof a.error ? a.error(b) : a.close(); -} -var q = JSON.stringify; -function da(a, b, d) { - a = q(d, a.toJSON); - b = b.toString(16) + ":" + a + "\n"; - return p.encode(b); -} -function t(a, b, d) { - a = q(d); - b = b.toString(16) + ":" + a + "\n"; - return p.encode(b); -} -var u = Symbol.for("react.client.reference"), ea = Symbol.for("react.server.reference"), ka = { - prefetchDNS: fa, - preconnect: ha, - preload: ia, - preinit: ja -}; -function fa(a, b) { - if ("string" === typeof a) { - var d = v(); - if (d) { - var c = d.hints, e = "D" + a; - c.has(e) || (c.add(e), b ? A(d, "D", [ - a, - b - ]) : A(d, "D", a), B(d)); - } - } -} -function ha(a, b) { - if ("string" === typeof a) { - var d = v(); - if (d) { - var c = d.hints, e = null == b || "string" !== typeof b.crossOrigin ? null : "use-credentials" === b.crossOrigin ? "use-credentials" : ""; - e = "C" + (null === e ? "null" : e) + "|" + a; - c.has(e) || (c.add(e), b ? A(d, "C", [ - a, - b - ]) : A(d, "C", a), B(d)); - } - } -} -function ia(a, b) { - if ("string" === typeof a) { - var d = v(); - if (d) { - var c = d.hints, e = "L" + a; - c.has(e) || (c.add(e), A(d, "L", [ - a, - b - ]), B(d)); - } - } -} -function ja(a, b) { - if ("string" === typeof a) { - var d = v(); - if (d) { - var c = d.hints, e = "I" + a; - c.has(e) || (c.add(e), A(d, "I", [ - a, - b - ]), B(d)); - } - } -} -var la = ba.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Dispatcher, C = "function" === typeof AsyncLocalStorage, na = C ? new AsyncLocalStorage : null, D = Symbol.for("react.element"), oa = Symbol.for("react.fragment"), pa = Symbol.for("react.provider"), qa = Symbol.for("react.server_context"), ra = Symbol.for("react.forward_ref"), sa = Symbol.for("react.suspense"), ta = Symbol.for("react.suspense_list"), ua = Symbol.for("react.memo"), E = Symbol.for("react.lazy"), va = Symbol.for("react.default_value"), wa = Symbol.for("react.memo_cache_sentinel"), xa = Symbol.iterator, F = null; -function G(a, b) { - if (a !== b) { - a.context._currentValue = a.parentValue; - a = a.parent; - var d = b.parent; - if (null === a) { - if (null !== d) throw Error("The stacks must reach the root at the same time. This is a bug in React."); - } else { - if (null === d) throw Error("The stacks must reach the root at the same time. This is a bug in React."); - G(a, d); - b.context._currentValue = b.value; - } - } -} -function ya(a) { - a.context._currentValue = a.parentValue; - a = a.parent; - null !== a && ya(a); -} -function za(a) { - var b = a.parent; - null !== b && za(b); - a.context._currentValue = a.value; -} -function Aa(a, b) { - a.context._currentValue = a.parentValue; - a = a.parent; - if (null === a) throw Error("The depth must equal at least at zero before reaching the root. This is a bug in React."); - a.depth === b.depth ? G(a, b) : Aa(a, b); -} -function Ba(a, b) { - var d = b.parent; - if (null === d) throw Error("The depth must equal at least at zero before reaching the root. This is a bug in React."); - a.depth === d.depth ? G(a, d) : Ba(a, d); - b.context._currentValue = b.value; -} -function H(a) { - var b = F; - b !== a && (null === b ? za(a) : null === a ? ya(b) : b.depth === a.depth ? G(b, a) : b.depth > a.depth ? Aa(b, a) : Ba(b, a), F = a); -} -function Ca(a, b) { - var d = a._currentValue; - a._currentValue = b; - var c = F; - return F = a = { - parent: c, - depth: null === c ? 0 : c.depth + 1, - context: a, - parentValue: d, - value: b - }; -} -var Da = Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`"); -function Ea() {} -function Fa(a, b, d) { - d = a[d]; - void 0 === d ? a.push(b) : d !== b && (b.then(Ea, Ea), b = d); - switch(b.status){ - case "fulfilled": - return b.value; - case "rejected": - throw b.reason; - default: - if ("string" !== typeof b.status) switch(a = b, a.status = "pending", a.then(function(c) { - if ("pending" === b.status) { - var e = b; - e.status = "fulfilled"; - e.value = c; - } - }, function(c) { - if ("pending" === b.status) { - var e = b; - e.status = "rejected"; - e.reason = c; - } - }), b.status){ - case "fulfilled": - return b.value; - case "rejected": - throw b.reason; - } - I = b; - throw Da; - } -} -var I = null; -function Ga() { - if (null === I) throw Error("Expected a suspended thenable. This is a bug in React. Please file an issue."); - var a = I; - I = null; - return a; -} -var J = null, K = 0, L = null; -function Ha() { - var a = L; - L = null; - return a; -} -function Ia(a) { - return a._currentValue; -} -var Ma = { - useMemo: function(a) { - return a(); - }, - useCallback: function(a) { - return a; - }, - useDebugValue: function() {}, - useDeferredValue: M, - useTransition: M, - readContext: Ia, - useContext: Ia, - useReducer: M, - useRef: M, - useState: M, - useInsertionEffect: M, - useLayoutEffect: M, - useImperativeHandle: M, - useEffect: M, - useId: Ja, - useMutableSource: M, - useSyncExternalStore: M, - useCacheRefresh: function() { - return Ka; - }, - useMemoCache: function(a) { - for(var b = Array(a), d = 0; d < a; d++)b[d] = wa; - return b; - }, - use: La -}; -function M() { - throw Error("This Hook is not supported in Server Components."); -} -function Ka() { - throw Error("Refreshing the cache is not supported in Server Components."); -} -function Ja() { - if (null === J) throw Error("useId can only be used while React is rendering"); - var a = J.identifierCount++; - return ":" + J.identifierPrefix + "S" + a.toString(32) + ":"; -} -function La(a) { - if (null !== a && "object" === typeof a || "function" === typeof a) { - if ("function" === typeof a.then) { - var b = K; - K += 1; - null === L && (L = []); - return Fa(L, a, b); - } - if (a.$$typeof === qa) return a._currentValue; - } - throw Error("An unsupported type was passed to use(): " + String(a)); -} -function Na() { - return (new AbortController).signal; -} -function Oa() { - var a = v(); - return a ? a.cache : new Map; -} -var Pa = { - getCacheSignal: function() { - var a = Oa(), b = a.get(Na); - void 0 === b && (b = Na(), a.set(Na, b)); - return b; - }, - getCacheForType: function(a) { - var b = Oa(), d = b.get(a); - void 0 === d && (d = a(), b.set(a, d)); - return d; - } -}, Qa = Array.isArray; -function Ra(a) { - return Object.prototype.toString.call(a).replace(/^\[object (.*)\]$/, function(b, d) { - return d; - }); -} -function Sa(a) { - switch(typeof a){ - case "string": - return JSON.stringify(10 >= a.length ? a : a.slice(0, 10) + "..."); - case "object": - if (Qa(a)) return "[...]"; - a = Ra(a); - return "Object" === a ? "{...}" : a; - case "function": - return "function"; - default: - return String(a); - } -} -function N(a) { - if ("string" === typeof a) return a; - switch(a){ - case sa: - return "Suspense"; - case ta: - return "SuspenseList"; - } - if ("object" === typeof a) switch(a.$$typeof){ - case ra: - return N(a.render); - case ua: - return N(a.type); - case E: - var b = a._payload; - a = a._init; - try { - return N(a(b)); - } catch (d) {} - } - return ""; -} -function O(a, b) { - var d = Ra(a); - if ("Object" !== d && "Array" !== d) return d; - d = -1; - var c = 0; - if (Qa(a)) { - var e = "["; - for(var f = 0; f < a.length; f++){ - 0 < f && (e += ", "); - var g = a[f]; - g = "object" === typeof g && null !== g ? O(g) : Sa(g); - "" + f === b ? (d = e.length, c = g.length, e += g) : e = 10 > g.length && 40 > e.length + g.length ? e + g : e + "..."; - } - e += "]"; - } else if (a.$$typeof === D) e = "<" + N(a.type) + "/>"; - else { - e = "{"; - f = Object.keys(a); - for(g = 0; g < f.length; g++){ - 0 < g && (e += ", "); - var h = f[g], k = JSON.stringify(h); - e += ('"' + h + '"' === k ? h : k) + ": "; - k = a[h]; - k = "object" === typeof k && null !== k ? O(k) : Sa(k); - h === b ? (d = e.length, c = k.length, e += k) : e = 10 > k.length && 40 > e.length + k.length ? e + k : e + "..."; - } - e += "}"; - } - return void 0 === b ? e : -1 < d && 0 < c ? (a = " ".repeat(d) + "^".repeat(c), "\n " + e + "\n " + a) : "\n " + e; -} -var Ta = aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, Ua = Ta.ContextRegistry, Va = Ta.ReactCurrentDispatcher, Wa = Ta.ReactCurrentCache; -function Xa(a) { - console.error(a); -} -function Ya(a, b, d, c, e) { - if (null !== Wa.current && Wa.current !== Pa) throw Error("Currently React only supports one RSC renderer at a time."); - la.current = ka; - Wa.current = Pa; - var f = new Set, g = [], h = new Set, k = { - status: 0, - flushScheduled: !1, - fatalError: null, - destination: null, - bundlerConfig: b, - cache: new Map, - nextChunkId: 0, - pendingChunks: 0, - hints: h, - abortableTasks: f, - pingedTasks: g, - completedImportChunks: [], - completedHintChunks: [], - completedJSONChunks: [], - completedErrorChunks: [], - writtenSymbols: new Map, - writtenClientReferences: new Map, - writtenServerReferences: new Map, - writtenProviders: new Map, - identifierPrefix: e || "", - identifierCount: 1, - onError: void 0 === d ? Xa : d, - toJSON: function(r, w) { - return Za(k, this, r, w); - } - }; - k.pendingChunks++; - b = $a(c); - a = ab(k, a, b, f); - g.push(a); - return k; -} -var P = null; -function v() { - if (P) return P; - if (C) { - var a = na.getStore(); - if (a) return a; - } - return null; -} -var bb = {}; -function cb(a, b) { - a.pendingChunks++; - var d = ab(a, null, F, a.abortableTasks); - switch(b.status){ - case "fulfilled": - return d.model = b.value, db(a, d), d.id; - case "rejected": - var c = Q(a, b.reason); - R(a, d.id, c); - return d.id; - default: - "string" !== typeof b.status && (b.status = "pending", b.then(function(e) { - "pending" === b.status && (b.status = "fulfilled", b.value = e); - }, function(e) { - "pending" === b.status && (b.status = "rejected", b.reason = e); - })); - } - b.then(function(e) { - d.model = e; - db(a, d); - }, function(e) { - d.status = 4; - e = Q(a, e); - R(a, d.id, e); - null !== a.destination && S(a, a.destination); - }); - return d.id; -} -function eb(a) { - if ("fulfilled" === a.status) return a.value; - if ("rejected" === a.status) throw a.reason; - throw a; -} -function fb(a) { - switch(a.status){ - case "fulfilled": - case "rejected": - break; - default: - "string" !== typeof a.status && (a.status = "pending", a.then(function(b) { - "pending" === a.status && (a.status = "fulfilled", a.value = b); - }, function(b) { - "pending" === a.status && (a.status = "rejected", a.reason = b); - })); - } - return { - $$typeof: E, - _payload: a, - _init: eb - }; -} -function T(a, b, d, c, e, f) { - if (null !== c && void 0 !== c) throw Error("Refs cannot be used in Server Components, nor passed to Client Components."); - if ("function" === typeof b) { - if (b.$$typeof === u) return [ - D, - b, - d, - e - ]; - K = 0; - L = f; - e = b(e); - return "object" === typeof e && null !== e && "function" === typeof e.then ? "fulfilled" === e.status ? e.value : fb(e) : e; - } - if ("string" === typeof b) return [ - D, - b, - d, - e - ]; - if ("symbol" === typeof b) return b === oa ? e.children : [ - D, - b, - d, - e - ]; - if (null != b && "object" === typeof b) { - if (b.$$typeof === u) return [ - D, - b, - d, - e - ]; - switch(b.$$typeof){ - case E: - var g = b._init; - b = g(b._payload); - return T(a, b, d, c, e, f); - case ra: - return a = b.render, K = 0, L = f, a(e, void 0); - case ua: - return T(a, b.type, d, c, e, f); - case pa: - return Ca(b._context, e.value), [ - D, - b, - d, - { - value: e.value, - children: e.children, - __pop: bb - } - ]; - } - } - throw Error("Unsupported Server Component type: " + Sa(b)); -} -function db(a, b) { - var d = a.pingedTasks; - d.push(b); - 1 === d.length && (a.flushScheduled = null !== a.destination, setTimeout(function() { - return gb(a); - }, 0)); -} -function ab(a, b, d, c) { - var e = { - id: a.nextChunkId++, - status: 0, - model: b, - context: d, - ping: function() { - return db(a, e); - }, - thenableState: null - }; - c.add(e); - return e; -} -function hb(a, b, d, c) { - var e = c.$$async ? c.$$id + "#async" : c.$$id, f = a.writtenClientReferences, g = f.get(e); - if (void 0 !== g) return b[0] === D && "1" === d ? "$L" + g.toString(16) : "$" + g.toString(16); - try { - var h = a.bundlerConfig, k = c.$$id; - g = ""; - var r = h[k]; - if (r) g = r.name; - else { - var w = k.lastIndexOf("#"); - -1 !== w && (g = k.slice(w + 1), r = h[k.slice(0, w)]); - if (!r) throw Error('Could not find the module "' + k + '" in the React Client Manifest. This is probably a bug in the React Server Components bundler.'); - } - var x = { - id: r.id, - chunks: r.chunks, - name: g, - async: !!c.$$async - }; - a.pendingChunks++; - var y = a.nextChunkId++, ma = q(x), z = y.toString(16) + ":I" + ma + "\n"; - var vb = p.encode(z); - a.completedImportChunks.push(vb); - f.set(e, y); - return b[0] === D && "1" === d ? "$L" + y.toString(16) : "$" + y.toString(16); - } catch (wb) { - return a.pendingChunks++, b = a.nextChunkId++, d = Q(a, wb), R(a, b, d), "$" + b.toString(16); - } -} -function Za(a, b, d, c) { - switch(c){ - case D: - return "$"; - } - for(; "object" === typeof c && null !== c && (c.$$typeof === D || c.$$typeof === E);)try { - switch(c.$$typeof){ - case D: - var e = c; - c = T(a, e.type, e.key, e.ref, e.props, null); - break; - case E: - var f = c._init; - c = f(c._payload); - } - } catch (g) { - d = g === Da ? Ga() : g; - if ("object" === typeof d && null !== d && "function" === typeof d.then) return a.pendingChunks++, a = ab(a, c, F, a.abortableTasks), c = a.ping, d.then(c, c), a.thenableState = Ha(), "$L" + a.id.toString(16); - a.pendingChunks++; - c = a.nextChunkId++; - d = Q(a, d); - R(a, c, d); - return "$L" + c.toString(16); - } - if (null === c) return null; - if ("object" === typeof c) { - if (c.$$typeof === u) return hb(a, b, d, c); - if ("function" === typeof c.then) return "$@" + cb(a, c).toString(16); - if (c.$$typeof === pa) return c = c._context._globalName, b = a.writtenProviders, d = b.get(d), void 0 === d && (a.pendingChunks++, d = a.nextChunkId++, b.set(c, d), c = t(a, d, "$P" + c), a.completedJSONChunks.push(c)), "$" + d.toString(16); - if (c === bb) { - a = F; - if (null === a) throw Error("Tried to pop a Context at the root of the app. This is a bug in React."); - c = a.parentValue; - a.context._currentValue = c === va ? a.context._defaultValue : c; - F = a.parent; - return; - } - return !Qa(c) && (null === c || "object" !== typeof c ? a = null : (a = xa && c[xa] || c["@@iterator"], a = "function" === typeof a ? a : null), a) ? Array.from(c) : c; - } - if ("string" === typeof c) { - if ("Z" === c[c.length - 1] && b[d] instanceof Date) return "$D" + c; - a = "$" === c[0] ? "$" + c : c; - return a; - } - if ("boolean" === typeof c) return c; - if ("number" === typeof c) return a = c, Number.isFinite(a) ? 0 === a && -Infinity === 1 / a ? "$-0" : a : Infinity === a ? "$Infinity" : -Infinity === a ? "$-Infinity" : "$NaN"; - if ("undefined" === typeof c) return "$undefined"; - if ("function" === typeof c) { - if (c.$$typeof === u) return hb(a, b, d, c); - if (c.$$typeof === ea) return d = a.writtenServerReferences, b = d.get(c), void 0 !== b ? a = "$F" + b.toString(16) : (b = c.$$bound, e = { - id: c.$$id, - bound: b ? Promise.resolve(b) : null - }, a.pendingChunks++, b = a.nextChunkId++, e = da(a, b, e), a.completedJSONChunks.push(e), d.set(c, b), a = "$F" + b.toString(16)), a; - if (/^on[A-Z]/.test(d)) throw Error("Event handlers cannot be passed to Client Component props." + O(b, d) + "\nIf you need interactivity, consider converting part of this to a Client Component."); - throw Error('Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".' + O(b, d)); - } - if ("symbol" === typeof c) { - e = a.writtenSymbols; - f = e.get(c); - if (void 0 !== f) return "$" + f.toString(16); - f = c.description; - if (Symbol.for(f) !== c) throw Error("Only global symbols received from Symbol.for(...) can be passed to Client Components. The symbol Symbol.for(" + (c.description + ") cannot be found among global symbols.") + O(b, d)); - a.pendingChunks++; - d = a.nextChunkId++; - b = t(a, d, "$S" + f); - a.completedImportChunks.push(b); - e.set(c, d); - return "$" + d.toString(16); - } - if ("bigint" === typeof c) return "$n" + c.toString(10); - throw Error("Type " + typeof c + " is not supported in Client Component props." + O(b, d)); -} -function Q(a, b) { - a = a.onError; - b = a(b); - if (null != b && "string" !== typeof b) throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "' + typeof b + '" instead'); - return b || ""; -} -function ib(a, b) { - null !== a.destination ? (a.status = 2, ca(a.destination, b)) : (a.status = 1, a.fatalError = b); -} -function R(a, b, d) { - d = { - digest: d - }; - b = b.toString(16) + ":E" + q(d) + "\n"; - b = p.encode(b); - a.completedErrorChunks.push(b); -} -function A(a, b, d) { - var c = a.nextChunkId++; - d = q(d); - b = "H" + b; - c = c.toString(16) + ":" + b; - c = p.encode(c + d + "\n"); - a.completedHintChunks.push(c); -} -function gb(a) { - var b = Va.current; - Va.current = Ma; - var d = P; - J = P = a; - try { - var c = a.pingedTasks; - a.pingedTasks = []; - for(var e = 0; e < c.length; e++){ - var f = c[e]; - var g = a; - if (0 === f.status) { - H(f.context); - try { - var h = f.model; - if ("object" === typeof h && null !== h && h.$$typeof === D) { - var k = h, r = f.thenableState; - f.model = h; - h = T(g, k.type, k.key, k.ref, k.props, r); - for(f.thenableState = null; "object" === typeof h && null !== h && h.$$typeof === D;)k = h, f.model = h, h = T(g, k.type, k.key, k.ref, k.props, null); - } - var w = da(g, f.id, h); - g.completedJSONChunks.push(w); - g.abortableTasks.delete(f); - f.status = 1; - } catch (z) { - var x = z === Da ? Ga() : z; - if ("object" === typeof x && null !== x && "function" === typeof x.then) { - var y = f.ping; - x.then(y, y); - f.thenableState = Ha(); - } else { - g.abortableTasks.delete(f); - f.status = 4; - var ma = Q(g, x); - R(g, f.id, ma); - } - } - } - } - null !== a.destination && S(a, a.destination); - } catch (z) { - Q(a, z), ib(a, z); - } finally{ - Va.current = b, J = null, P = d; - } -} -function S(a, b) { - l = new Uint8Array(512); - m = 0; - try { - for(var d = a.completedImportChunks, c = 0; c < d.length; c++)a.pendingChunks--, n(b, d[c]); - d.splice(0, c); - var e = a.completedHintChunks; - for(c = 0; c < e.length; c++)n(b, e[c]); - e.splice(0, c); - var f = a.completedJSONChunks; - for(c = 0; c < f.length; c++)a.pendingChunks--, n(b, f[c]); - f.splice(0, c); - var g = a.completedErrorChunks; - for(c = 0; c < g.length; c++)a.pendingChunks--, n(b, g[c]); - g.splice(0, c); - } finally{ - a.flushScheduled = !1, l && 0 < m && (b.enqueue(new Uint8Array(l.buffer, 0, m)), l = null, m = 0); - } - 0 === a.pendingChunks && b.close(); -} -function jb(a) { - a.flushScheduled = null !== a.destination; - C ? setTimeout(function() { - return na.run(a, gb, a); - }, 0) : setTimeout(function() { - return gb(a); - }, 0); -} -function B(a) { - if (!1 === a.flushScheduled && 0 === a.pingedTasks.length && null !== a.destination) { - var b = a.destination; - a.flushScheduled = !0; - setTimeout(function() { - return S(a, b); - }, 0); - } -} -function kb(a, b) { - try { - var d = a.abortableTasks; - if (0 < d.size) { - var c = Q(a, void 0 === b ? Error("The render was aborted by the server without a reason.") : b); - a.pendingChunks++; - var e = a.nextChunkId++; - R(a, e, c); - d.forEach(function(f) { - f.status = 3; - var g = "$" + e.toString(16); - f = t(a, f.id, g); - a.completedErrorChunks.push(f); - }); - d.clear(); - } - null !== a.destination && S(a, a.destination); - } catch (f) { - Q(a, f), ib(a, f); - } -} -function $a(a) { - if (a) { - var b = F; - H(null); - for(var d = 0; d < a.length; d++){ - var c = a[d], e = c[0]; - c = c[1]; - Ua[e] || (Ua[e] = aa.createServerContext(e, va)); - Ca(Ua[e], c); - } - a = F; - H(b); - return a; - } - return null; -} -function lb(a, b) { - var d = "", c = a[b]; - if (c) d = c.name; - else { - var e = b.lastIndexOf("#"); - -1 !== e && (d = b.slice(e + 1), c = a[b.slice(0, e)]); - if (!c) throw Error('Could not find the module "' + b + '" in the React Server Manifest. This is probably a bug in the React Server Components bundler.'); - } - return { - id: c.id, - chunks: c.chunks, - name: d, - async: !1 - }; -} -var U = new Map, mb = new Map; -function nb() {} -function ob(a) { - for(var b = a.chunks, d = [], c = 0; c < b.length; c++){ - var e = b[c], f = U.get(e); - if (void 0 === f) { - f = globalThis.__next_chunk_load__(e); - d.push(f); - var g = U.set.bind(U, e, null); - f.then(g, nb); - U.set(e, f); - } else null !== f && d.push(f); - } - if (a.async) { - if (b = mb.get(a.id)) return "fulfilled" === b.status ? null : b; - var h = Promise.all(d).then(function() { - return globalThis.__next_require__(a.id); - }); - h.then(function(k) { - h.status = "fulfilled"; - h.value = k; - }, function(k) { - h.status = "rejected"; - h.reason = k; - }); - mb.set(a.id, h); - return h; - } - return 0 < d.length ? Promise.all(d) : null; -} -function V(a) { - if (a.async) { - var b = mb.get(a.id); - if ("fulfilled" === b.status) b = b.value; - else throw b.reason; - } else b = globalThis.__next_require__(a.id); - return "*" === a.name ? b : "" === a.name ? b.__esModule ? b.default : b : b[a.name]; -} -function W(a, b, d, c) { - this.status = a; - this.value = b; - this.reason = d; - this._response = c; -} -W.prototype = Object.create(Promise.prototype); -W.prototype.then = function(a, b) { - switch(this.status){ - case "resolved_model": - pb(this); - } - switch(this.status){ - case "fulfilled": - a(this.value); - break; - case "pending": - case "blocked": - a && (null === this.value && (this.value = []), this.value.push(a)); - b && (null === this.reason && (this.reason = []), this.reason.push(b)); - break; - default: - b(this.reason); - } -}; -function qb(a, b) { - for(var d = 0; d < a.length; d++)(0, a[d])(b); -} -function rb(a, b) { - if ("pending" === a.status || "blocked" === a.status) { - var d = a.reason; - a.status = "rejected"; - a.reason = b; - null !== d && qb(d, b); - } -} -function sb(a, b, d, c, e, f) { - var g = lb(a._bundlerConfig, b); - a = ob(g); - if (d) d = Promise.all([ - d, - a - ]).then(function(h) { - h = h[0]; - var k = V(g); - return k.bind.apply(k, [ - null - ].concat(h)); - }); - else if (a) d = Promise.resolve(a).then(function() { - return V(g); - }); - else return V(g); - d.then(tb(c, e, f), ub(c)); - return null; -} -var X = null, Y = null; -function pb(a) { - var b = X, d = Y; - X = a; - Y = null; - try { - var c = JSON.parse(a.value, a._response._fromJSON); - null !== Y && 0 < Y.deps ? (Y.value = c, a.status = "blocked", a.value = null, a.reason = null) : (a.status = "fulfilled", a.value = c); - } catch (e) { - a.status = "rejected", a.reason = e; - } finally{ - X = b, Y = d; - } -} -function xb(a, b) { - a._chunks.forEach(function(d) { - "pending" === d.status && rb(d, b); - }); -} -function Z(a, b) { - var d = a._chunks, c = d.get(b); - c || (c = a._formData.get(a._prefix + b), c = null != c ? new W("resolved_model", c, null, a) : new W("pending", null, null, a), d.set(b, c)); - return c; -} -function tb(a, b, d) { - if (Y) { - var c = Y; - c.deps++; - } else c = Y = { - deps: 1, - value: null - }; - return function(e) { - b[d] = e; - c.deps--; - 0 === c.deps && "blocked" === a.status && (e = a.value, a.status = "fulfilled", a.value = c.value, null !== e && qb(e, c.value)); - }; -} -function ub(a) { - return function(b) { - return rb(a, b); - }; -} -function yb(a, b, d, c) { - if ("$" === c[0]) switch(c[1]){ - case "$": - return c.slice(1); - case "@": - return b = parseInt(c.slice(2), 16), Z(a, b); - case "S": - return Symbol.for(c.slice(2)); - case "F": - c = parseInt(c.slice(2), 16); - c = Z(a, c); - "resolved_model" === c.status && pb(c); - if ("fulfilled" !== c.status) throw c.reason; - c = c.value; - return sb(a, c.id, c.bound, X, b, d); - case "K": - b = c.slice(2); - var e = a._prefix + b + "_", f = new FormData; - a._formData.forEach(function(g, h) { - h.startsWith(e) && f.append(h.slice(e.length), g); - }); - return f; - case "I": - return Infinity; - case "-": - return "$-0" === c ? -0 : -Infinity; - case "N": - return NaN; - case "u": - return; - case "D": - return new Date(Date.parse(c.slice(2))); - case "n": - return BigInt(c.slice(2)); - default: - c = parseInt(c.slice(1), 16); - a = Z(a, c); - switch(a.status){ - case "resolved_model": - pb(a); - } - switch(a.status){ - case "fulfilled": - return a.value; - case "pending": - case "blocked": - return c = X, a.then(tb(c, b, d), ub(c)), null; - default: - throw a.reason; - } - } - return c; -} -function zb(a, b) { - var d = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : new FormData, c = new Map, e = { - _bundlerConfig: a, - _prefix: b, - _formData: d, - _chunks: c, - _fromJSON: function(f, g) { - return "string" === typeof g ? yb(e, this, f, g) : g; - } - }; - return e; -} -function Ab(a) { - xb(a, Error("Connection closed.")); -} -function Bb(a, b, d) { - var c = lb(a, b); - a = ob(c); - return d ? Promise.all([ - d, - a - ]).then(function(e) { - e = e[0]; - var f = V(c); - return f.bind.apply(f, [ - null - ].concat(e)); - }) : a ? Promise.resolve(a).then(function() { - return V(c); - }) : Promise.resolve(V(c)); -} -exports.decodeAction = function(a, b) { - var d = new FormData, c = null; - a.forEach(function(e, f) { - if (f.startsWith("$ACTION_")) if (f.startsWith("$ACTION_REF_")) { - e = "$ACTION_" + f.slice(12) + ":"; - e = zb(b, e, a); - Ab(e); - e = Z(e, 0); - e.then(function() {}); - if ("fulfilled" !== e.status) throw e.reason; - e = e.value; - c = Bb(b, e.id, e.bound); - } else f.startsWith("$ACTION_ID_") && (e = f.slice(11), c = Bb(b, e, null)); - else d.append(f, e); - }); - return null === c ? null : c.then(function(e) { - return e.bind(null, d); - }); -}; -exports.decodeReply = function(a, b) { - if ("string" === typeof a) { - var d = new FormData; - d.append("0", a); - a = d; - } - a = zb(b, "", a); - Ab(a); - return Z(a, 0); -}; -exports.renderToReadableStream = function(a, b, d) { - var c = Ya(a, b, d ? d.onError : void 0, d ? d.context : void 0, d ? d.identifierPrefix : void 0); - if (d && d.signal) { - var e = d.signal; - if (e.aborted) kb(c, e.reason); - else { - var f = function() { - kb(c, e.reason); - e.removeEventListener("abort", f); - }; - e.addEventListener("abort", f); - } - } - return new ReadableStream({ - type: "bytes", - start: function() { - jb(c); - }, - pull: function(g) { - if (1 === c.status) c.status = 2, ca(g, c.fatalError); - else if (2 !== c.status && null === c.destination) { - c.destination = g; - try { - S(c, g); - } catch (h) { - Q(c, h), ib(c, h); - } - } - }, - cancel: function() {} - }, { - highWaterMark: 0 - }); -}; - - -/***/ }), - -/***/ 7902: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -if (true) { - module.exports = __webpack_require__(8387); -} else {} - - -/***/ }), - -/***/ 7789: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/** - * @license React - * react.shared-subset.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -var m = Object.assign, n = { - current: null -}; -function p() { - return new Map; -} -if ("function" === typeof fetch) { - var q = fetch, r = function(a, b) { - var d = n.current; - if (!d || b && b.signal && b.signal !== d.getCacheSignal()) return q(a, b); - if ("string" !== typeof a || b) { - var c = "string" === typeof a || a instanceof URL ? new Request(a, b) : a; - if ("GET" !== c.method && "HEAD" !== c.method || c.keepalive) return q(a, b); - var e = JSON.stringify([ - c.method, - Array.from(c.headers.entries()), - c.mode, - c.redirect, - c.credentials, - c.referrer, - c.referrerPolicy, - c.integrity - ]); - c = c.url; - } else e = '["GET",[],null,"follow",null,null,null,null]', c = a; - var f = d.getCacheForType(p); - d = f.get(c); - if (void 0 === d) a = q(a, b), f.set(c, [ - e, - a - ]); - else { - c = 0; - for(f = d.length; c < f; c += 2){ - var h = d[c + 1]; - if (d[c] === e) return a = h, a.then(function(g) { - return g.clone(); - }); - } - a = q(a, b); - d.push(e, a); - } - return a.then(function(g) { - return g.clone(); - }); - }; - m(r, q); - try { - fetch = r; - } catch (a) { - try { - globalThis.fetch = r; - } catch (b) { - console.warn("React was unable to patch the fetch() function in this environment. Suspensey APIs might not work correctly as a result."); - } - } -} -var t = Symbol.for("react.element"), u = Symbol.for("react.portal"), v = Symbol.for("react.fragment"), w = Symbol.for("react.strict_mode"), x = Symbol.for("react.profiler"), y = Symbol.for("react.provider"), z = Symbol.for("react.server_context"), A = Symbol.for("react.forward_ref"), B = Symbol.for("react.suspense"), C = Symbol.for("react.memo"), aa = Symbol.for("react.lazy"), D = Symbol.for("react.default_value"), E = Symbol.iterator; -function ba(a) { - if (null === a || "object" !== typeof a) return null; - a = E && a[E] || a["@@iterator"]; - return "function" === typeof a ? a : null; -} -function F(a) { - for(var b = "https://reactjs.org/docs/error-decoder.html?invariant=" + a, d = 1; d < arguments.length; d++)b += "&args[]=" + encodeURIComponent(arguments[d]); - return "Minified React error #" + a + "; visit " + b + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."; -} -var G = { - isMounted: function() { - return !1; - }, - enqueueForceUpdate: function() {}, - enqueueReplaceState: function() {}, - enqueueSetState: function() {} -}, H = {}; -function I(a, b, d) { - this.props = a; - this.context = b; - this.refs = H; - this.updater = d || G; -} -I.prototype.isReactComponent = {}; -I.prototype.setState = function(a, b) { - if ("object" !== typeof a && "function" !== typeof a && null != a) throw Error(F(85)); - this.updater.enqueueSetState(this, a, b, "setState"); -}; -I.prototype.forceUpdate = function(a) { - this.updater.enqueueForceUpdate(this, a, "forceUpdate"); -}; -function J() {} -J.prototype = I.prototype; -function K(a, b, d) { - this.props = a; - this.context = b; - this.refs = H; - this.updater = d || G; -} -var L = K.prototype = new J; -L.constructor = K; -m(L, I.prototype); -L.isPureReactComponent = !0; -var M = Array.isArray, N = Object.prototype.hasOwnProperty, O = { - current: null -}, P = { - key: !0, - ref: !0, - __self: !0, - __source: !0 -}; -function ca(a, b) { - return { - $$typeof: t, - type: a.type, - key: b, - ref: a.ref, - props: a.props, - _owner: a._owner - }; -} -function Q(a) { - return "object" === typeof a && null !== a && a.$$typeof === t; -} -function escape(a) { - var b = { - "=": "=0", - ":": "=2" - }; - return "$" + a.replace(/[=:]/g, function(d) { - return b[d]; - }); -} -var R = /\/+/g; -function S(a, b) { - return "object" === typeof a && null !== a && null != a.key ? escape("" + a.key) : b.toString(36); -} -function T(a, b, d, c, e) { - var f = typeof a; - if ("undefined" === f || "boolean" === f) a = null; - var h = !1; - if (null === a) h = !0; - else switch(f){ - case "string": - case "number": - h = !0; - break; - case "object": - switch(a.$$typeof){ - case t: - case u: - h = !0; - } - } - if (h) return h = a, e = e(h), a = "" === c ? "." + S(h, 0) : c, M(e) ? (d = "", null != a && (d = a.replace(R, "$&/") + "/"), T(e, b, d, "", function(l) { - return l; - })) : null != e && (Q(e) && (e = ca(e, d + (!e.key || h && h.key === e.key ? "" : ("" + e.key).replace(R, "$&/") + "/") + a)), b.push(e)), 1; - h = 0; - c = "" === c ? "." : c + ":"; - if (M(a)) for(var g = 0; g < a.length; g++){ - f = a[g]; - var k = c + S(f, g); - h += T(f, b, d, k, e); - } - else if (k = ba(a), "function" === typeof k) for(a = k.call(a), g = 0; !(f = a.next()).done;)f = f.value, k = c + S(f, g++), h += T(f, b, d, k, e); - else if ("object" === f) throw b = String(a), Error(F(31, "[object Object]" === b ? "object with keys {" + Object.keys(a).join(", ") + "}" : b)); - return h; -} -function U(a, b, d) { - if (null == a) return a; - var c = [], e = 0; - T(a, c, "", "", function(f) { - return b.call(d, f, e++); - }); - return c; -} -function da(a) { - if (-1 === a._status) { - var b = a._result; - b = b(); - b.then(function(d) { - if (0 === a._status || -1 === a._status) a._status = 1, a._result = d; - }, function(d) { - if (0 === a._status || -1 === a._status) a._status = 2, a._result = d; - }); - -1 === a._status && (a._status = 0, a._result = b); - } - if (1 === a._status) return a._result.default; - throw a._result; -} -function ea() { - return new WeakMap; -} -function V() { - return { - s: 0, - v: void 0, - o: null, - p: null - }; -} -var W = { - current: null -}, X = { - transition: null -}, Y = { - ReactCurrentDispatcher: W, - ReactCurrentCache: n, - ReactCurrentBatchConfig: X, - ReactCurrentOwner: O, - ContextRegistry: {} -}, Z = Y.ContextRegistry; -exports.Children = { - map: U, - forEach: function(a, b, d) { - U(a, function() { - b.apply(this, arguments); - }, d); - }, - count: function(a) { - var b = 0; - U(a, function() { - b++; - }); - return b; - }, - toArray: function(a) { - return U(a, function(b) { - return b; - }) || []; - }, - only: function(a) { - if (!Q(a)) throw Error(F(143)); - return a; - } -}; -exports.Fragment = v; -exports.Profiler = x; -exports.StrictMode = w; -exports.Suspense = B; -exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Y; -exports.cache = function(a) { - return function() { - var b = n.current; - if (!b) return a.apply(null, arguments); - var d = b.getCacheForType(ea); - b = d.get(a); - void 0 === b && (b = V(), d.set(a, b)); - d = 0; - for(var c = arguments.length; d < c; d++){ - var e = arguments[d]; - if ("function" === typeof e || "object" === typeof e && null !== e) { - var f = b.o; - null === f && (b.o = f = new WeakMap); - b = f.get(e); - void 0 === b && (b = V(), f.set(e, b)); - } else f = b.p, null === f && (b.p = f = new Map), b = f.get(e), void 0 === b && (b = V(), f.set(e, b)); - } - if (1 === b.s) return b.v; - if (2 === b.s) throw b.v; - try { - var h = a.apply(null, arguments); - d = b; - d.s = 1; - return d.v = h; - } catch (g) { - throw h = b, h.s = 2, h.v = g, g; - } - }; -}; -exports.cloneElement = function(a, b, d) { - if (null === a || void 0 === a) throw Error(F(267, a)); - var c = m({}, a.props), e = a.key, f = a.ref, h = a._owner; - if (null != b) { - void 0 !== b.ref && (f = b.ref, h = O.current); - void 0 !== b.key && (e = "" + b.key); - if (a.type && a.type.defaultProps) var g = a.type.defaultProps; - for(k in b)N.call(b, k) && !P.hasOwnProperty(k) && (c[k] = void 0 === b[k] && void 0 !== g ? g[k] : b[k]); - } - var k = arguments.length - 2; - if (1 === k) c.children = d; - else if (1 < k) { - g = Array(k); - for(var l = 0; l < k; l++)g[l] = arguments[l + 2]; - c.children = g; - } - return { - $$typeof: t, - type: a.type, - key: e, - ref: f, - props: c, - _owner: h - }; -}; -exports.createElement = function(a, b, d) { - var c, e = {}, f = null, h = null; - if (null != b) for(c in void 0 !== b.ref && (h = b.ref), void 0 !== b.key && (f = "" + b.key), b)N.call(b, c) && !P.hasOwnProperty(c) && (e[c] = b[c]); - var g = arguments.length - 2; - if (1 === g) e.children = d; - else if (1 < g) { - for(var k = Array(g), l = 0; l < g; l++)k[l] = arguments[l + 2]; - e.children = k; - } - if (a && a.defaultProps) for(c in g = a.defaultProps, g)void 0 === e[c] && (e[c] = g[c]); - return { - $$typeof: t, - type: a, - key: f, - ref: h, - props: e, - _owner: O.current - }; -}; -exports.createRef = function() { - return { - current: null - }; -}; -exports.createServerContext = function(a, b) { - var d = !0; - if (!Z[a]) { - d = !1; - var c = { - $$typeof: z, - _currentValue: b, - _currentValue2: b, - _defaultValue: b, - _threadCount: 0, - Provider: null, - Consumer: null, - _globalName: a - }; - c.Provider = { - $$typeof: y, - _context: c - }; - Z[a] = c; - } - c = Z[a]; - if (c._defaultValue === D) c._defaultValue = b, c._currentValue === D && (c._currentValue = b), c._currentValue2 === D && (c._currentValue2 = b); - else if (d) throw Error(F(429, a)); - return c; -}; -exports.forwardRef = function(a) { - return { - $$typeof: A, - render: a - }; -}; -exports.isValidElement = Q; -exports.lazy = function(a) { - return { - $$typeof: aa, - _payload: { - _status: -1, - _result: a - }, - _init: da - }; -}; -exports.memo = function(a, b) { - return { - $$typeof: C, - type: a, - compare: void 0 === b ? null : b - }; -}; -exports.startTransition = function(a) { - var b = X.transition; - X.transition = {}; - try { - a(); - } finally{ - X.transition = b; - } -}; -exports.use = function(a) { - return W.current.use(a); -}; -exports.useCallback = function(a, b) { - return W.current.useCallback(a, b); -}; -exports.useContext = function(a) { - return W.current.useContext(a); -}; -exports.useDebugValue = function() {}; -exports.useId = function() { - return W.current.useId(); -}; -exports.useMemo = function(a, b) { - return W.current.useMemo(a, b); -}; -exports.version = "18.3.0-canary-16d053d59-20230506"; - - -/***/ }), - -/***/ 7887: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - -if (true) { - module.exports = __webpack_require__(7789); -} else {} - - -/***/ }), - -/***/ 3180: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - fillMetadataSegment: function() { - return fillMetadataSegment; - }, - normalizeMetadataRoute: function() { - return normalizeMetadataRoute; - } -}); -const _ismetadataroute = __webpack_require__(8865); -const _path = /*#__PURE__*/ _interop_require_default(__webpack_require__(2080)); -const _serverutils = __webpack_require__(3160); -const _routeregex = __webpack_require__(9601); -const _hash = __webpack_require__(6230); -const _apppaths = __webpack_require__(8401); -function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} -/* - * If there's special convention like (...) or @ in the page path, - * Give it a unique hash suffix to avoid conflicts - * - * e.g. - * /app/open-graph.tsx -> /open-graph/route - * /app/(post)/open-graph.tsx -> /open-graph/route-[0-9a-z]{6} - */ function getMetadataRouteSuffix(page) { - let suffix = ""; - if (page.includes("(") && page.includes(")") || page.includes("@")) { - suffix = (0, _hash.djb2Hash)(page).toString(36).slice(0, 6); - } - return suffix; -} -function fillMetadataSegment(segment, params, imageSegment) { - const pathname = (0, _apppaths.normalizeAppPath)(segment); - const routeRegex = (0, _routeregex.getNamedRouteRegex)(pathname, false); - const route = (0, _serverutils.interpolateDynamicPath)(pathname, params, routeRegex); - const suffix = getMetadataRouteSuffix(segment); - const routeSuffix = suffix ? `-${suffix}` : ""; - const { name , ext } = _path.default.parse(imageSegment); - return _path.default.join(route, `${name}${routeSuffix}${ext}`); -} -function normalizeMetadataRoute(page) { - if (!(0, _ismetadataroute.isMetadataRoute)(page)) { - return page; - } - let route = page; - let suffix = ""; - if (route === "/robots") { - route += ".txt"; - } else if (route === "/manifest") { - route += ".webmanifest"; - } else if (route.endsWith("/sitemap")) { - route += ".xml"; - } else { - // Remove the file extension, e.g. /route-path/robots.txt -> /route-path - const pathnamePrefix = page.slice(0, -(_path.default.basename(page).length + 1)); - suffix = getMetadataRouteSuffix(pathnamePrefix); - } - // Support both /<metadata-route.ext> and custom routes /<metadata-route>/route.ts. - // If it's a metadata file route, we need to append /[id]/route to the page. - if (!route.endsWith("/route")) { - const isStaticMetadataFile = (0, _ismetadataroute.isMetadataRouteFile)(page, [], true); - const { dir , name: baseName , ext } = _path.default.parse(route); - const isStaticRoute = page.startsWith("/robots") || page.startsWith("/manifest") || isStaticMetadataFile; - route = _path.default.posix.join(dir, `${baseName}${suffix ? `-${suffix}` : ""}${ext}`, isStaticRoute ? "" : "[[...__metadata_id__]]", "route"); - } - return route; -} //# sourceMappingURL=get-metadata-route.js.map - - -/***/ }), - -/***/ 8865: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - STATIC_METADATA_IMAGES: function() { - return STATIC_METADATA_IMAGES; - }, - isMetadataRouteFile: function() { - return isMetadataRouteFile; - }, - isMetadataRoute: function() { - return isMetadataRoute; - } -}); -const STATIC_METADATA_IMAGES = { - icon: { - filename: "icon", - extensions: [ - "ico", - "jpg", - "jpeg", - "png", - "svg" - ] - }, - apple: { - filename: "apple-icon", - extensions: [ - "jpg", - "jpeg", - "png" - ] - }, - favicon: { - filename: "favicon", - extensions: [ - "ico" - ] - }, - openGraph: { - filename: "opengraph-image", - extensions: [ - "jpg", - "jpeg", - "png", - "gif" - ] - }, - twitter: { - filename: "twitter-image", - extensions: [ - "jpg", - "jpeg", - "png", - "gif" - ] - } -}; -// Match routes that are metadata routes, e.g. /sitemap.xml, /favicon.<ext>, /<icon>.<ext>, etc. -// TODO-METADATA: support more metadata routes with more extensions -const defaultExtensions = [ - "js", - "jsx", - "ts", - "tsx" -]; -const getExtensionRegexString = (extensions)=>`(?:${extensions.join("|")})`; -function isMetadataRouteFile(appDirRelativePath, pageExtensions, withExtension) { - const metadataRouteFilesRegex = [ - new RegExp(`^[\\\\/]robots${withExtension ? `\\.${getExtensionRegexString(pageExtensions.concat("txt"))}$` : ""}`), - new RegExp(`^[\\\\/]manifest${withExtension ? `\\.${getExtensionRegexString(pageExtensions.concat("webmanifest", "json"))}$` : ""}`), - new RegExp(`^[\\\\/]favicon\\.ico$`), - new RegExp(`[\\\\/]sitemap${withExtension ? `\\.${getExtensionRegexString(pageExtensions.concat("xml"))}$` : ""}`), - new RegExp(`[\\\\/]${STATIC_METADATA_IMAGES.icon.filename}\\d?${withExtension ? `\\.${getExtensionRegexString(pageExtensions.concat(STATIC_METADATA_IMAGES.icon.extensions))}$` : ""}`), - new RegExp(`[\\\\/]${STATIC_METADATA_IMAGES.apple.filename}\\d?${withExtension ? `\\.${getExtensionRegexString(pageExtensions.concat(STATIC_METADATA_IMAGES.apple.extensions))}$` : ""}`), - new RegExp(`[\\\\/]${STATIC_METADATA_IMAGES.openGraph.filename}\\d?${withExtension ? `\\.${getExtensionRegexString(pageExtensions.concat(STATIC_METADATA_IMAGES.openGraph.extensions))}$` : ""}`), - new RegExp(`[\\\\/]${STATIC_METADATA_IMAGES.twitter.filename}\\d?${withExtension ? `\\.${getExtensionRegexString(pageExtensions.concat(STATIC_METADATA_IMAGES.twitter.extensions))}$` : ""}`) - ]; - return metadataRouteFilesRegex.some((r)=>r.test(appDirRelativePath)); -} -function isMetadataRoute(route) { - let page = route.replace(/^\/?app\//, "").replace(/\/route$/, ""); - if (page[0] !== "/") page = "/" + page; - return !page.endsWith("/page") && isMetadataRouteFile(page, defaultExtensions, false); -} //# sourceMappingURL=is-metadata-route.js.map - - -/***/ }), - -/***/ 2112: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "acceptLanguage", ({ - enumerable: true, - get: function() { - return acceptLanguage; - } -})); -function parse(raw, preferences, options) { - const lowers = new Map(); - const header = raw.replace(/[ \t]/g, ""); - if (preferences) { - let pos = 0; - for (const preference of preferences){ - const lower = preference.toLowerCase(); - lowers.set(lower, { - orig: preference, - pos: pos++ - }); - if (options.prefixMatch) { - const parts = lower.split("-"); - while(parts.pop(), parts.length > 0){ - const joined = parts.join("-"); - if (!lowers.has(joined)) { - lowers.set(joined, { - orig: preference, - pos: pos++ - }); - } - } - } - } - } - const parts = header.split(","); - const selections = []; - const map = new Set(); - for(let i = 0; i < parts.length; ++i){ - const part = parts[i]; - if (!part) { - continue; - } - const params = part.split(";"); - if (params.length > 2) { - throw new Error(`Invalid ${options.type} header`); - } - let token = params[0].toLowerCase(); - if (!token) { - throw new Error(`Invalid ${options.type} header`); - } - const selection = { - token, - pos: i, - q: 1 - }; - if (preferences && lowers.has(token)) { - selection.pref = lowers.get(token).pos; - } - map.add(selection.token); - if (params.length === 2) { - const q = params[1]; - const [key, value] = q.split("="); - if (!value || key !== "q" && key !== "Q") { - throw new Error(`Invalid ${options.type} header`); - } - const score = parseFloat(value); - if (score === 0) { - continue; - } - if (Number.isFinite(score) && score <= 1 && score >= 0.001) { - selection.q = score; - } - } - selections.push(selection); - } - selections.sort((a, b)=>{ - if (b.q !== a.q) { - return b.q - a.q; - } - if (b.pref !== a.pref) { - if (a.pref === undefined) { - return 1; - } - if (b.pref === undefined) { - return -1; - } - return a.pref - b.pref; - } - return a.pos - b.pos; - }); - const values = selections.map((selection)=>selection.token); - if (!preferences || !preferences.length) { - return values; - } - const preferred = []; - for (const selection of values){ - if (selection === "*") { - for (const [preference, value] of lowers){ - if (!map.has(preference)) { - preferred.push(value.orig); - } - } - } else { - const lower = selection.toLowerCase(); - if (lowers.has(lower)) { - preferred.push(lowers.get(lower).orig); - } - } - } - return preferred; -} -function acceptLanguage(header = "", preferences) { - return parse(header, preferences, { - type: "accept-language", - prefixMatch: true - })[0] || ""; -} //# sourceMappingURL=accept-header.js.map - - -/***/ }), - -/***/ 3099: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; -/* - -Files in the rsc directory are meant to be packaged as part of the RSC graph using next-app-loader. - -*/ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - preloadStyle: function() { - return preloadStyle; - }, - preloadFont: function() { - return preloadFont; - }, - preconnect: function() { - return preconnect; - } -}); -const _reactdom = /*#__PURE__*/ _interop_require_default(__webpack_require__(6155)); -function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} -const stylePreloadOptions = { - as: "style" -}; -function preloadStyle(href) { - _reactdom.default.preload(href, stylePreloadOptions); -} -function preloadFont(href, type) { - _reactdom.default.preload(href, { - as: "font", - type - }); -} -function preconnect(href, crossOrigin) { - if (typeof crossOrigin === "string") { - _reactdom.default.preconnect(href, { - crossOrigin - }); - } else { - _reactdom.default.preconnect(href); - } -} //# sourceMappingURL=preloads.js.map - - -/***/ }), - -/***/ 3958: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - INTERCEPTION_ROUTE_MARKERS: function() { - return INTERCEPTION_ROUTE_MARKERS; - }, - isInterceptionRouteAppPath: function() { - return isInterceptionRouteAppPath; - }, - extractInterceptionRouteInformation: function() { - return extractInterceptionRouteInformation; - } -}); -const _apppaths = __webpack_require__(8401); -const INTERCEPTION_ROUTE_MARKERS = [ - "(..)(..)", - "(.)", - "(..)", - "(...)" -]; -function isInterceptionRouteAppPath(path) { - // TODO-APP: add more serious validation - return path.split("/").find((segment)=>INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m))) !== undefined; -} -function extractInterceptionRouteInformation(path) { - let interceptingRoute, marker, interceptedRoute; - for (const segment of path.split("/")){ - marker = INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m)); - if (marker) { - [interceptingRoute, interceptedRoute] = path.split(marker, 2); - break; - } - } - if (!interceptingRoute || !marker || !interceptedRoute) { - throw new Error(`Invalid interception route: ${path}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`); - } - interceptingRoute = (0, _apppaths.normalizeAppPath)(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed - ; - switch(marker){ - case "(.)": - // (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route - if (interceptingRoute === "/") { - interceptedRoute = `/${interceptedRoute}`; - } else { - interceptedRoute = interceptingRoute + "/" + interceptedRoute; - } - break; - case "(..)": - // (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route - if (interceptingRoute === "/") { - throw new Error(`Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`); - } - interceptedRoute = interceptingRoute.split("/").slice(0, -1).concat(interceptedRoute).join("/"); - break; - case "(...)": - // (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route - interceptedRoute = "/" + interceptedRoute; - break; - case "(..)(..)": - // (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route - const splitInterceptingRoute = interceptingRoute.split("/"); - if (splitInterceptingRoute.length <= 2) { - throw new Error(`Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`); - } - interceptedRoute = splitInterceptingRoute.slice(0, -2).concat(interceptedRoute).join("/"); - break; - default: - throw new Error("Invariant: unexpected marker"); - } - return { - interceptingRoute, - interceptedRoute - }; -} //# sourceMappingURL=interception-routes.js.map - - -/***/ }), - -/***/ 3271: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/* eslint-disable no-redeclare */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - NEXT_REQUEST_META: function() { - return NEXT_REQUEST_META; - }, - getRequestMeta: function() { - return getRequestMeta; - }, - setRequestMeta: function() { - return setRequestMeta; - }, - addRequestMeta: function() { - return addRequestMeta; - }, - getNextInternalQuery: function() { - return getNextInternalQuery; - } -}); -const NEXT_REQUEST_META = Symbol.for("NextInternalRequestMeta"); -function getRequestMeta(req, key) { - const meta = req[NEXT_REQUEST_META] || {}; - return typeof key === "string" ? meta[key] : meta; -} -function setRequestMeta(req, meta) { - req[NEXT_REQUEST_META] = meta; - return getRequestMeta(req); -} -function addRequestMeta(request, key, value) { - const meta = getRequestMeta(request); - meta[key] = value; - return setRequestMeta(request, meta); -} -function getNextInternalQuery(query) { - const keysToInclude = [ - "__nextDefaultLocale", - "__nextFallback", - "__nextLocale", - "__nextSsgPath", - "_nextBubbleNoFallback", - "__nextDataReq", - "__nextInferredLocaleFromDefault" - ]; - const nextInternalQuery = {}; - for (const key of keysToInclude){ - if (key in query) { - // @ts-ignore this can't be typed correctly - nextInternalQuery[key] = query[key]; - } - } - return nextInternalQuery; -} //# sourceMappingURL=request-meta.js.map - - -/***/ }), - -/***/ 3160: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - normalizeVercelUrl: function() { - return normalizeVercelUrl; - }, - interpolateDynamicPath: function() { - return interpolateDynamicPath; - }, - getUtils: function() { - return getUtils; - } -}); -const _url = __webpack_require__(7310); -const _normalizelocalepath = __webpack_require__(9962); -const _pathmatch = __webpack_require__(247); -const _routeregex = __webpack_require__(9601); -const _routematcher = __webpack_require__(4060); -const _preparedestination = __webpack_require__(880); -const _acceptheader = __webpack_require__(2112); -const _detectlocalecookie = __webpack_require__(8090); -const _detectdomainlocale = __webpack_require__(2207); -const _denormalizepagepath = __webpack_require__(6115); -const _cookie = /*#__PURE__*/ _interop_require_default(__webpack_require__(252)); -const _constants = __webpack_require__(2205); -const _requestmeta = __webpack_require__(3271); -const _removetrailingslash = __webpack_require__(465); -const _apppaths = __webpack_require__(8401); -const _constants1 = __webpack_require__(8537); -function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} -function normalizeVercelUrl(req, trustQuery, paramKeys, pageIsDynamic, defaultRouteRegex) { - // make sure to normalize req.url on Vercel to strip dynamic params - // from the query which are added during routing - if (pageIsDynamic && trustQuery && defaultRouteRegex) { - const _parsedUrl = (0, _url.parse)(req.url, true); - delete _parsedUrl.search; - for (const key of Object.keys(_parsedUrl.query)){ - if (key !== _constants1.NEXT_QUERY_PARAM_PREFIX && key.startsWith(_constants1.NEXT_QUERY_PARAM_PREFIX) || (paramKeys || Object.keys(defaultRouteRegex.groups)).includes(key)) { - delete _parsedUrl.query[key]; - } - } - req.url = (0, _url.format)(_parsedUrl); - } -} -function interpolateDynamicPath(pathname, params, defaultRouteRegex) { - if (!defaultRouteRegex) return pathname; - for (const param of Object.keys(defaultRouteRegex.groups)){ - const { optional , repeat } = defaultRouteRegex.groups[param]; - let builtParam = `[${repeat ? "..." : ""}${param}]`; - if (optional) { - builtParam = `[${builtParam}]`; - } - const paramIdx = pathname.indexOf(builtParam); - if (paramIdx > -1) { - let paramValue; - const value = params[param]; - if (Array.isArray(value)) { - paramValue = value.map((v)=>v && encodeURIComponent(v)).join("/"); - } else if (value) { - paramValue = encodeURIComponent(value); - } else { - paramValue = ""; - } - pathname = pathname.slice(0, paramIdx) + paramValue + pathname.slice(paramIdx + builtParam.length); - } - } - return pathname; -} -function getUtils({ page , i18n , basePath , rewrites , pageIsDynamic , trailingSlash }) { - let defaultRouteRegex; - let dynamicRouteMatcher; - let defaultRouteMatches; - if (pageIsDynamic) { - defaultRouteRegex = (0, _routeregex.getNamedRouteRegex)(page, false); - dynamicRouteMatcher = (0, _routematcher.getRouteMatcher)(defaultRouteRegex); - defaultRouteMatches = dynamicRouteMatcher(page); - } - function handleRewrites(req, parsedUrl) { - const rewriteParams = {}; - let fsPathname = parsedUrl.pathname; - const matchesPage = ()=>{ - const fsPathnameNoSlash = (0, _removetrailingslash.removeTrailingSlash)(fsPathname || ""); - return fsPathnameNoSlash === (0, _removetrailingslash.removeTrailingSlash)(page) || (dynamicRouteMatcher == null ? void 0 : dynamicRouteMatcher(fsPathnameNoSlash)); - }; - const checkRewrite = (rewrite)=>{ - const matcher = (0, _pathmatch.getPathMatch)(rewrite.source + (trailingSlash ? "(/)?" : ""), { - removeUnnamedParams: true, - strict: true - }); - let params = matcher(parsedUrl.pathname); - if ((rewrite.has || rewrite.missing) && params) { - const hasParams = (0, _preparedestination.matchHas)(req, parsedUrl.query, rewrite.has, rewrite.missing); - if (hasParams) { - Object.assign(params, hasParams); - } else { - params = false; - } - } - if (params) { - const { parsedDestination , destQuery } = (0, _preparedestination.prepareDestination)({ - appendParamsToQuery: true, - destination: rewrite.destination, - params: params, - query: parsedUrl.query - }); - // if the rewrite destination is external break rewrite chain - if (parsedDestination.protocol) { - return true; - } - Object.assign(rewriteParams, destQuery, params); - Object.assign(parsedUrl.query, parsedDestination.query); - delete parsedDestination.query; - Object.assign(parsedUrl, parsedDestination); - fsPathname = parsedUrl.pathname; - if (basePath) { - fsPathname = fsPathname.replace(new RegExp(`^${basePath}`), "") || "/"; - } - if (i18n) { - const destLocalePathResult = (0, _normalizelocalepath.normalizeLocalePath)(fsPathname, i18n.locales); - fsPathname = destLocalePathResult.pathname; - parsedUrl.query.nextInternalLocale = destLocalePathResult.detectedLocale || params.nextInternalLocale; - } - if (fsPathname === page) { - return true; - } - if (pageIsDynamic && dynamicRouteMatcher) { - const dynamicParams = dynamicRouteMatcher(fsPathname); - if (dynamicParams) { - parsedUrl.query = { - ...parsedUrl.query, - ...dynamicParams - }; - return true; - } - } - } - return false; - }; - for (const rewrite of rewrites.beforeFiles || []){ - checkRewrite(rewrite); - } - if (fsPathname !== page) { - let finished = false; - for (const rewrite of rewrites.afterFiles || []){ - finished = checkRewrite(rewrite); - if (finished) break; - } - if (!finished && !matchesPage()) { - for (const rewrite of rewrites.fallback || []){ - finished = checkRewrite(rewrite); - if (finished) break; - } - } - } - return rewriteParams; - } - function handleBasePath(req, parsedUrl) { - // always strip the basePath if configured since it is required - req.url = req.url.replace(new RegExp(`^${basePath}`), "") || "/"; - parsedUrl.pathname = parsedUrl.pathname.replace(new RegExp(`^${basePath}`), "") || "/"; - } - function getParamsFromRouteMatches(req, renderOpts, detectedLocale) { - return (0, _routematcher.getRouteMatcher)(function() { - const { groups , routeKeys } = defaultRouteRegex; - return { - re: { - // Simulate a RegExp match from the \`req.url\` input - exec: (str)=>{ - const obj = Object.fromEntries(new URLSearchParams(str)); - const matchesHasLocale = i18n && detectedLocale && obj["1"] === detectedLocale; - for (const key of Object.keys(obj)){ - const value = obj[key]; - if (key !== _constants1.NEXT_QUERY_PARAM_PREFIX && key.startsWith(_constants1.NEXT_QUERY_PARAM_PREFIX)) { - const normalizedKey = key.substring(_constants1.NEXT_QUERY_PARAM_PREFIX.length); - obj[normalizedKey] = value; - delete obj[key]; - } - } - // favor named matches if available - const routeKeyNames = Object.keys(routeKeys || {}); - const filterLocaleItem = (val)=>{ - if (i18n) { - // locale items can be included in route-matches - // for fallback SSG pages so ensure they are - // filtered - const isCatchAll = Array.isArray(val); - const _val = isCatchAll ? val[0] : val; - if (typeof _val === "string" && i18n.locales.some((item)=>{ - if (item.toLowerCase() === _val.toLowerCase()) { - detectedLocale = item; - renderOpts.locale = detectedLocale; - return true; - } - return false; - })) { - // remove the locale item from the match - if (isCatchAll) { - val.splice(0, 1); - } - // the value is only a locale item and - // shouldn't be added - return isCatchAll ? val.length === 0 : true; - } - } - return false; - }; - if (routeKeyNames.every((name)=>obj[name])) { - return routeKeyNames.reduce((prev, keyName)=>{ - const paramName = routeKeys == null ? void 0 : routeKeys[keyName]; - if (paramName && !filterLocaleItem(obj[keyName])) { - prev[groups[paramName].pos] = obj[keyName]; - } - return prev; - }, {}); - } - return Object.keys(obj).reduce((prev, key)=>{ - if (!filterLocaleItem(obj[key])) { - let normalizedKey = key; - if (matchesHasLocale) { - normalizedKey = parseInt(key, 10) - 1 + ""; - } - return Object.assign(prev, { - [normalizedKey]: obj[key] - }); - } - return prev; - }, {}); - } - }, - groups - }; - }())(req.headers["x-now-route-matches"]); - } - function normalizeDynamicRouteParams(params, ignoreOptional) { - let hasValidParams = true; - if (!defaultRouteRegex) return { - params, - hasValidParams: false - }; - params = Object.keys(defaultRouteRegex.groups).reduce((prev, key)=>{ - let value = params[key]; - if (typeof value === "string") { - value = (0, _apppaths.normalizeRscPath)(value, true); - } - if (Array.isArray(value)) { - value = value.map((val)=>{ - if (typeof val === "string") { - val = (0, _apppaths.normalizeRscPath)(val, true); - } - return val; - }); - } - // if the value matches the default value we can't rely - // on the parsed params, this is used to signal if we need - // to parse x-now-route-matches or not - const defaultValue = defaultRouteMatches[key]; - const isOptional = defaultRouteRegex.groups[key].optional; - const isDefaultValue = Array.isArray(defaultValue) ? defaultValue.some((defaultVal)=>{ - return Array.isArray(value) ? value.some((val)=>val.includes(defaultVal)) : value == null ? void 0 : value.includes(defaultVal); - }) : value == null ? void 0 : value.includes(defaultValue); - if (isDefaultValue || typeof value === "undefined" && !(isOptional && ignoreOptional)) { - hasValidParams = false; - } - // non-provided optional values should be undefined so normalize - // them to undefined - if (isOptional && (!value || Array.isArray(value) && value.length === 1 && // fallback optional catch-all SSG pages have - // [[...paramName]] for the root path on Vercel - (value[0] === "index" || value[0] === `[[...${key}]]`))) { - value = undefined; - delete params[key]; - } - // query values from the proxy aren't already split into arrays - // so make sure to normalize catch-all values - if (value && typeof value === "string" && defaultRouteRegex.groups[key].repeat) { - value = value.split("/"); - } - if (value) { - prev[key] = value; - } - return prev; - }, {}); - return { - params, - hasValidParams - }; - } - function handleLocale(req, res, parsedUrl, routeNoAssetPath, shouldNotRedirect) { - if (!i18n) return; - const pathname = parsedUrl.pathname || "/"; - let defaultLocale = i18n.defaultLocale; - let detectedLocale = (0, _detectlocalecookie.detectLocaleCookie)(req, i18n.locales); - let acceptPreferredLocale; - try { - acceptPreferredLocale = i18n.localeDetection !== false ? (0, _acceptheader.acceptLanguage)(req.headers["accept-language"], i18n.locales) : detectedLocale; - } catch (_) { - acceptPreferredLocale = detectedLocale; - } - const { host } = req.headers || {}; - // remove port from host and remove port if present - const hostname = host && host.split(":")[0].toLowerCase(); - const detectedDomain = (0, _detectdomainlocale.detectDomainLocale)(i18n.domains, hostname); - if (detectedDomain) { - defaultLocale = detectedDomain.defaultLocale; - detectedLocale = defaultLocale; - (0, _requestmeta.addRequestMeta)(req, "__nextIsLocaleDomain", true); - } - // if not domain specific locale use accept-language preferred - detectedLocale = detectedLocale || acceptPreferredLocale; - let localeDomainRedirect; - const localePathResult = (0, _normalizelocalepath.normalizeLocalePath)(pathname, i18n.locales); - routeNoAssetPath = (0, _normalizelocalepath.normalizeLocalePath)(routeNoAssetPath, i18n.locales).pathname; - if (localePathResult.detectedLocale) { - detectedLocale = localePathResult.detectedLocale; - req.url = (0, _url.format)({ - ...parsedUrl, - pathname: localePathResult.pathname - }); - (0, _requestmeta.addRequestMeta)(req, "__nextStrippedLocale", true); - parsedUrl.pathname = localePathResult.pathname; - } - // If a detected locale is a domain specific locale and we aren't already - // on that domain and path prefix redirect to it to prevent duplicate - // content from multiple domains - if (detectedDomain) { - const localeToCheck = localePathResult.detectedLocale ? detectedLocale : acceptPreferredLocale; - const matchedDomain = (0, _detectdomainlocale.detectDomainLocale)(i18n.domains, undefined, localeToCheck); - if (matchedDomain && matchedDomain.domain !== detectedDomain.domain) { - localeDomainRedirect = `http${matchedDomain.http ? "" : "s"}://${matchedDomain.domain}/${localeToCheck === matchedDomain.defaultLocale ? "" : localeToCheck}`; - } - } - const denormalizedPagePath = (0, _denormalizepagepath.denormalizePagePath)(pathname); - const detectedDefaultLocale = !detectedLocale || detectedLocale.toLowerCase() === defaultLocale.toLowerCase(); - const shouldStripDefaultLocale = false; - // detectedDefaultLocale && - // denormalizedPagePath.toLowerCase() === \`/\${i18n.defaultLocale.toLowerCase()}\` - const shouldAddLocalePrefix = !detectedDefaultLocale && denormalizedPagePath === "/"; - detectedLocale = detectedLocale || i18n.defaultLocale; - if (!shouldNotRedirect && !req.headers["x-vercel-id"] && i18n.localeDetection !== false && (localeDomainRedirect || shouldAddLocalePrefix || shouldStripDefaultLocale)) { - // set the NEXT_LOCALE cookie when a user visits the default locale - // with the locale prefix so that they aren't redirected back to - // their accept-language preferred locale - if (shouldStripDefaultLocale && acceptPreferredLocale !== defaultLocale) { - const previous = res.getHeader("set-cookie"); - res.setHeader("set-cookie", [ - ...typeof previous === "string" ? [ - previous - ] : Array.isArray(previous) ? previous : [], - _cookie.default.serialize("NEXT_LOCALE", defaultLocale, { - httpOnly: true, - path: "/" - }) - ]); - } - res.setHeader("Location", (0, _url.format)({ - // make sure to include any query values when redirecting - ...parsedUrl, - pathname: localeDomainRedirect ? localeDomainRedirect : shouldStripDefaultLocale ? basePath || "/" : `${basePath}/${detectedLocale}` - })); - res.statusCode = _constants.TEMPORARY_REDIRECT_STATUS; - res.end(); - return; - } - detectedLocale = localePathResult.detectedLocale || detectedDomain && detectedDomain.defaultLocale || defaultLocale; - return { - defaultLocale, - detectedLocale, - routeNoAssetPath - }; - } - return { - handleLocale, - handleRewrites, - handleBasePath, - defaultRouteRegex, - dynamicRouteMatcher, - defaultRouteMatches, - getParamsFromRouteMatches, - normalizeDynamicRouteParams, - normalizeVercelUrl: (req, trustQuery, paramKeys)=>normalizeVercelUrl(req, trustQuery, paramKeys, pageIsDynamic, defaultRouteRegex), - interpolateDynamicPath: (pathname, params)=>interpolateDynamicPath(pathname, params, defaultRouteRegex) - }; -} //# sourceMappingURL=server-utils.js.map - - -/***/ }), - -/***/ 2205: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - MODERN_BROWSERSLIST_TARGET: function() { - return _modernbrowserslisttarget.default; - }, - COMPILER_NAMES: function() { - return COMPILER_NAMES; - }, - COMPILER_INDEXES: function() { - return COMPILER_INDEXES; - }, - PHASE_EXPORT: function() { - return PHASE_EXPORT; - }, - PHASE_PRODUCTION_BUILD: function() { - return PHASE_PRODUCTION_BUILD; - }, - PHASE_PRODUCTION_SERVER: function() { - return PHASE_PRODUCTION_SERVER; - }, - PHASE_DEVELOPMENT_SERVER: function() { - return PHASE_DEVELOPMENT_SERVER; - }, - PHASE_TEST: function() { - return PHASE_TEST; - }, - PAGES_MANIFEST: function() { - return PAGES_MANIFEST; - }, - APP_PATHS_MANIFEST: function() { - return APP_PATHS_MANIFEST; - }, - APP_PATH_ROUTES_MANIFEST: function() { - return APP_PATH_ROUTES_MANIFEST; - }, - BUILD_MANIFEST: function() { - return BUILD_MANIFEST; - }, - APP_BUILD_MANIFEST: function() { - return APP_BUILD_MANIFEST; - }, - SUBRESOURCE_INTEGRITY_MANIFEST: function() { - return SUBRESOURCE_INTEGRITY_MANIFEST; - }, - NEXT_FONT_MANIFEST: function() { - return NEXT_FONT_MANIFEST; - }, - EXPORT_MARKER: function() { - return EXPORT_MARKER; - }, - EXPORT_DETAIL: function() { - return EXPORT_DETAIL; - }, - PRERENDER_MANIFEST: function() { - return PRERENDER_MANIFEST; - }, - ROUTES_MANIFEST: function() { - return ROUTES_MANIFEST; - }, - IMAGES_MANIFEST: function() { - return IMAGES_MANIFEST; - }, - SERVER_FILES_MANIFEST: function() { - return SERVER_FILES_MANIFEST; - }, - DEV_CLIENT_PAGES_MANIFEST: function() { - return DEV_CLIENT_PAGES_MANIFEST; - }, - MIDDLEWARE_MANIFEST: function() { - return MIDDLEWARE_MANIFEST; - }, - DEV_MIDDLEWARE_MANIFEST: function() { - return DEV_MIDDLEWARE_MANIFEST; - }, - REACT_LOADABLE_MANIFEST: function() { - return REACT_LOADABLE_MANIFEST; - }, - FONT_MANIFEST: function() { - return FONT_MANIFEST; - }, - SERVER_DIRECTORY: function() { - return SERVER_DIRECTORY; - }, - CONFIG_FILES: function() { - return CONFIG_FILES; - }, - BUILD_ID_FILE: function() { - return BUILD_ID_FILE; - }, - BLOCKED_PAGES: function() { - return BLOCKED_PAGES; - }, - CLIENT_PUBLIC_FILES_PATH: function() { - return CLIENT_PUBLIC_FILES_PATH; - }, - CLIENT_STATIC_FILES_PATH: function() { - return CLIENT_STATIC_FILES_PATH; - }, - CLIENT_STATIC_FILES_RUNTIME: function() { - return CLIENT_STATIC_FILES_RUNTIME; - }, - STRING_LITERAL_DROP_BUNDLE: function() { - return STRING_LITERAL_DROP_BUNDLE; - }, - NEXT_BUILTIN_DOCUMENT: function() { - return NEXT_BUILTIN_DOCUMENT; - }, - NEXT_CLIENT_SSR_ENTRY_SUFFIX: function() { - return NEXT_CLIENT_SSR_ENTRY_SUFFIX; - }, - CLIENT_REFERENCE_MANIFEST: function() { - return CLIENT_REFERENCE_MANIFEST; - }, - FLIGHT_SERVER_CSS_MANIFEST: function() { - return FLIGHT_SERVER_CSS_MANIFEST; - }, - SERVER_REFERENCE_MANIFEST: function() { - return SERVER_REFERENCE_MANIFEST; - }, - MIDDLEWARE_BUILD_MANIFEST: function() { - return MIDDLEWARE_BUILD_MANIFEST; - }, - MIDDLEWARE_REACT_LOADABLE_MANIFEST: function() { - return MIDDLEWARE_REACT_LOADABLE_MANIFEST; - }, - CLIENT_STATIC_FILES_RUNTIME_MAIN: function() { - return CLIENT_STATIC_FILES_RUNTIME_MAIN; - }, - CLIENT_STATIC_FILES_RUNTIME_MAIN_APP: function() { - return CLIENT_STATIC_FILES_RUNTIME_MAIN_APP; - }, - APP_CLIENT_INTERNALS: function() { - return APP_CLIENT_INTERNALS; - }, - CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH: function() { - return CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH; - }, - CLIENT_STATIC_FILES_RUNTIME_AMP: function() { - return CLIENT_STATIC_FILES_RUNTIME_AMP; - }, - CLIENT_STATIC_FILES_RUNTIME_WEBPACK: function() { - return CLIENT_STATIC_FILES_RUNTIME_WEBPACK; - }, - CLIENT_STATIC_FILES_RUNTIME_POLYFILLS: function() { - return CLIENT_STATIC_FILES_RUNTIME_POLYFILLS; - }, - CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL: function() { - return CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL; - }, - EDGE_RUNTIME_WEBPACK: function() { - return EDGE_RUNTIME_WEBPACK; - }, - TEMPORARY_REDIRECT_STATUS: function() { - return TEMPORARY_REDIRECT_STATUS; - }, - PERMANENT_REDIRECT_STATUS: function() { - return PERMANENT_REDIRECT_STATUS; - }, - STATIC_PROPS_ID: function() { - return STATIC_PROPS_ID; - }, - SERVER_PROPS_ID: function() { - return SERVER_PROPS_ID; - }, - PAGE_SEGMENT_KEY: function() { - return PAGE_SEGMENT_KEY; - }, - GOOGLE_FONT_PROVIDER: function() { - return GOOGLE_FONT_PROVIDER; - }, - OPTIMIZED_FONT_PROVIDERS: function() { - return OPTIMIZED_FONT_PROVIDERS; - }, - DEFAULT_SERIF_FONT: function() { - return DEFAULT_SERIF_FONT; - }, - DEFAULT_SANS_SERIF_FONT: function() { - return DEFAULT_SANS_SERIF_FONT; - }, - STATIC_STATUS_PAGES: function() { - return STATIC_STATUS_PAGES; - }, - TRACE_OUTPUT_VERSION: function() { - return TRACE_OUTPUT_VERSION; - }, - TURBO_TRACE_DEFAULT_MEMORY_LIMIT: function() { - return TURBO_TRACE_DEFAULT_MEMORY_LIMIT; - }, - RSC_MODULE_TYPES: function() { - return RSC_MODULE_TYPES; - }, - EDGE_UNSUPPORTED_NODE_APIS: function() { - return EDGE_UNSUPPORTED_NODE_APIS; - }, - SYSTEM_ENTRYPOINTS: function() { - return SYSTEM_ENTRYPOINTS; - } -}); -const _interop_require_default = __webpack_require__(1550); -const _modernbrowserslisttarget = /*#__PURE__*/ _interop_require_default._(__webpack_require__(2159)); -const COMPILER_NAMES = { - client: "client", - server: "server", - edgeServer: "edge-server" -}; -const COMPILER_INDEXES = { - [COMPILER_NAMES.client]: 0, - [COMPILER_NAMES.server]: 1, - [COMPILER_NAMES.edgeServer]: 2 -}; -const PHASE_EXPORT = "phase-export"; -const PHASE_PRODUCTION_BUILD = "phase-production-build"; -const PHASE_PRODUCTION_SERVER = "phase-production-server"; -const PHASE_DEVELOPMENT_SERVER = "phase-development-server"; -const PHASE_TEST = "phase-test"; -const PAGES_MANIFEST = "pages-manifest.json"; -const APP_PATHS_MANIFEST = "app-paths-manifest.json"; -const APP_PATH_ROUTES_MANIFEST = "app-path-routes-manifest.json"; -const BUILD_MANIFEST = "build-manifest.json"; -const APP_BUILD_MANIFEST = "app-build-manifest.json"; -const SUBRESOURCE_INTEGRITY_MANIFEST = "subresource-integrity-manifest"; -const NEXT_FONT_MANIFEST = "next-font-manifest"; -const EXPORT_MARKER = "export-marker.json"; -const EXPORT_DETAIL = "export-detail.json"; -const PRERENDER_MANIFEST = "prerender-manifest.json"; -const ROUTES_MANIFEST = "routes-manifest.json"; -const IMAGES_MANIFEST = "images-manifest.json"; -const SERVER_FILES_MANIFEST = "required-server-files.json"; -const DEV_CLIENT_PAGES_MANIFEST = "_devPagesManifest.json"; -const MIDDLEWARE_MANIFEST = "middleware-manifest.json"; -const DEV_MIDDLEWARE_MANIFEST = "_devMiddlewareManifest.json"; -const REACT_LOADABLE_MANIFEST = "react-loadable-manifest.json"; -const FONT_MANIFEST = "font-manifest.json"; -const SERVER_DIRECTORY = "server"; -const CONFIG_FILES = [ - "next.config.js", - "next.config.mjs" -]; -const BUILD_ID_FILE = "BUILD_ID"; -const BLOCKED_PAGES = [ - "/_document", - "/_app", - "/_error" -]; -const CLIENT_PUBLIC_FILES_PATH = "public"; -const CLIENT_STATIC_FILES_PATH = "static"; -const CLIENT_STATIC_FILES_RUNTIME = "runtime"; -const STRING_LITERAL_DROP_BUNDLE = "__NEXT_DROP_CLIENT_FILE__"; -const NEXT_BUILTIN_DOCUMENT = "__NEXT_BUILTIN_DOCUMENT__"; -const NEXT_CLIENT_SSR_ENTRY_SUFFIX = ".__sc_client__"; -const CLIENT_REFERENCE_MANIFEST = "client-reference-manifest"; -const FLIGHT_SERVER_CSS_MANIFEST = "flight-server-css-manifest"; -const SERVER_REFERENCE_MANIFEST = "server-reference-manifest"; -const MIDDLEWARE_BUILD_MANIFEST = "middleware-build-manifest"; -const MIDDLEWARE_REACT_LOADABLE_MANIFEST = "middleware-react-loadable-manifest"; -const CLIENT_STATIC_FILES_RUNTIME_MAIN = "main"; -const CLIENT_STATIC_FILES_RUNTIME_MAIN_APP = "" + CLIENT_STATIC_FILES_RUNTIME_MAIN + "-app"; -const APP_CLIENT_INTERNALS = "app-client-internals"; -const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = "react-refresh"; -const CLIENT_STATIC_FILES_RUNTIME_AMP = "amp"; -const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = "webpack"; -const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = "polyfills"; -const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL = Symbol(CLIENT_STATIC_FILES_RUNTIME_POLYFILLS); -const EDGE_RUNTIME_WEBPACK = "edge-runtime-webpack"; -const TEMPORARY_REDIRECT_STATUS = 307; -const PERMANENT_REDIRECT_STATUS = 308; -const STATIC_PROPS_ID = "__N_SSG"; -const SERVER_PROPS_ID = "__N_SSP"; -const PAGE_SEGMENT_KEY = "__PAGE__"; -const GOOGLE_FONT_PROVIDER = "https://fonts.googleapis.com/"; -const OPTIMIZED_FONT_PROVIDERS = [ - { - url: GOOGLE_FONT_PROVIDER, - preconnect: "https://fonts.gstatic.com" - }, - { - url: "https://use.typekit.net", - preconnect: "https://use.typekit.net" - } -]; -const DEFAULT_SERIF_FONT = { - name: "Times New Roman", - xAvgCharWidth: 821, - azAvgWidth: 854.3953488372093, - unitsPerEm: 2048 -}; -const DEFAULT_SANS_SERIF_FONT = { - name: "Arial", - xAvgCharWidth: 904, - azAvgWidth: 934.5116279069767, - unitsPerEm: 2048 -}; -const STATIC_STATUS_PAGES = [ - "/500" -]; -const TRACE_OUTPUT_VERSION = 1; -const TURBO_TRACE_DEFAULT_MEMORY_LIMIT = 6000; -const RSC_MODULE_TYPES = { - client: "client", - server: "server" -}; -const EDGE_UNSUPPORTED_NODE_APIS = [ - "clearImmediate", - "setImmediate", - "BroadcastChannel", - "ByteLengthQueuingStrategy", - "CompressionStream", - "CountQueuingStrategy", - "DecompressionStream", - "DomException", - "MessageChannel", - "MessageEvent", - "MessagePort", - "ReadableByteStreamController", - "ReadableStreamBYOBRequest", - "ReadableStreamDefaultController", - "TransformStreamDefaultController", - "WritableStreamDefaultController" -]; -const SYSTEM_ENTRYPOINTS = new Set([ - CLIENT_STATIC_FILES_RUNTIME_MAIN, - CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, - CLIENT_STATIC_FILES_RUNTIME_AMP, - CLIENT_STATIC_FILES_RUNTIME_MAIN_APP -]); -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=constants.js.map - - -/***/ }), - -/***/ 536: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -// regexp is based on https://github.com/sindresorhus/escape-string-regexp - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "escapeStringRegexp", ({ - enumerable: true, - get: function() { - return escapeStringRegexp; - } -})); -const reHasRegExp = /[|\\{}()[\]^$+*?.-]/; -const reReplaceRegExp = /[|\\{}()[\]^$+*?.-]/g; -function escapeStringRegexp(str) { - // see also: https://github.com/lodash/lodash/blob/2da024c3b4f9947a48517639de7560457cd4ec6c/escapeRegExp.js#L23 - if (reHasRegExp.test(str)) { - return str.replace(reReplaceRegExp, "\\$&"); - } - return str; -} //# sourceMappingURL=escape-regexp.js.map - - -/***/ }), - -/***/ 6230: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -// http://www.cse.yorku.ca/~oz/hash.html - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "djb2Hash", ({ - enumerable: true, - get: function() { - return djb2Hash; - } -})); -function djb2Hash(str) { - let hash = 5381; - for(let i = 0; i < str.length; i++){ - const char = str.charCodeAt(i); - hash = (hash << 5) + hash + char; - } - return Math.abs(hash); -} //# sourceMappingURL=hash.js.map - - -/***/ }), - -/***/ 8090: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "detectLocaleCookie", ({ - enumerable: true, - get: function() { - return detectLocaleCookie; - } -})); -function detectLocaleCookie(req, locales) { - const { NEXT_LOCALE } = req.cookies || {}; - return NEXT_LOCALE ? locales.find((locale)=>NEXT_LOCALE.toLowerCase() === locale.toLowerCase()) : undefined; -} //# sourceMappingURL=detect-locale-cookie.js.map - - -/***/ }), - -/***/ 2080: -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; -/** - * This module is for next.js server internal usage of path module. - * It will use native path module for nodejs runtime. - * It will use path-browserify polyfill for edge runtime. - */ -let path; -if (false) {} else { - path = __webpack_require__(1017); -} -module.exports = path; //# sourceMappingURL=path.js.map - - -/***/ }), - -/***/ 2159: -/***/ ((module) => { - -"use strict"; -// Note: This file is JS because it's used by the taskfile-swc.js file, which is JS. -// Keep file changes in sync with the corresponding `.d.ts` files. -/** - * These are the browser versions that support all of the following: - * static import: https://caniuse.com/es6-module - * dynamic import: https://caniuse.com/es6-module-dynamic-import - * import.meta: https://caniuse.com/mdn-javascript_operators_import_meta - */ -const MODERN_BROWSERSLIST_TARGET = [ - "chrome 64", - "edge 79", - "firefox 67", - "opera 51", - "safari 12" -]; -module.exports = MODERN_BROWSERSLIST_TARGET; //# sourceMappingURL=modern-browserslist-target.js.map - - -/***/ }), - -/***/ 6115: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "denormalizePagePath", ({ - enumerable: true, - get: function() { - return denormalizePagePath; - } -})); -const _utils = __webpack_require__(9824); -const _normalizepathsep = __webpack_require__(9019); -function denormalizePagePath(page) { - let _page = (0, _normalizepathsep.normalizePathSep)(page); - return _page.startsWith("/index/") && !(0, _utils.isDynamicRoute)(_page) ? _page.slice(6) : _page !== "/index" ? _page : "/"; -} //# sourceMappingURL=denormalize-page-path.js.map - - -/***/ }), - -/***/ 6921: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/** - * For a given page path, this function ensures that there is a leading slash. - * If there is not a leading slash, one is added, otherwise it is noop. - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "ensureLeadingSlash", ({ - enumerable: true, - get: function() { - return ensureLeadingSlash; - } -})); -function ensureLeadingSlash(path) { - return path.startsWith("/") ? path : "/" + path; -} //# sourceMappingURL=ensure-leading-slash.js.map - - -/***/ }), - -/***/ 9019: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/** - * For a given page path, this function ensures that there is no backslash - * escaping slashes in the path. Example: - * - `foo\/bar\/baz` -> `foo/bar/baz` - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "normalizePathSep", ({ - enumerable: true, - get: function() { - return normalizePathSep; - } -})); -function normalizePathSep(path) { - return path.replace(/\\/g, "/"); -} //# sourceMappingURL=normalize-path-sep.js.map - - -/***/ }), - -/***/ 8401: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - normalizeAppPath: function() { - return normalizeAppPath; - }, - normalizeRscPath: function() { - return normalizeRscPath; - } -}); -const _ensureleadingslash = __webpack_require__(6921); -function normalizeAppPath(route) { - return (0, _ensureleadingslash.ensureLeadingSlash)(route.split("/").reduce((pathname, segment, index, segments)=>{ - // Empty segments are ignored. - if (!segment) { - return pathname; - } - // Groups are ignored. - if (segment.startsWith("(") && segment.endsWith(")")) { - return pathname; - } - // Parallel segments are ignored. - if (segment.startsWith("@")) { - return pathname; - } - // The last segment (if it's a leaf) should be ignored. - if ((segment === "page" || segment === "route") && index === segments.length - 1) { - return pathname; - } - return pathname + "/" + segment; - }, "")); -} -function normalizeRscPath(pathname, enabled) { - return enabled ? pathname.replace(/\.rsc($|\?)/, "$1") : pathname; -} //# sourceMappingURL=app-paths.js.map - - -/***/ }), - -/***/ 9824: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - getSortedRoutes: function() { - return _sortedroutes.getSortedRoutes; - }, - isDynamicRoute: function() { - return _isdynamic.isDynamicRoute; - } -}); -const _sortedroutes = __webpack_require__(6262); -const _isdynamic = __webpack_require__(815); //# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 815: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -// Identify /[param]/ in route string - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "isDynamicRoute", ({ - enumerable: true, - get: function() { - return isDynamicRoute; - } -})); -const TEST_ROUTE = /\/\[[^/]+?\](?=\/|$)/; -function isDynamicRoute(route) { - return TEST_ROUTE.test(route); -} //# sourceMappingURL=is-dynamic.js.map - - -/***/ }), - -/***/ 3767: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "parseRelativeUrl", ({ - enumerable: true, - get: function() { - return parseRelativeUrl; - } -})); -const _utils = __webpack_require__(1265); -const _querystring = __webpack_require__(4557); -function parseRelativeUrl(url, base) { - const globalBase = new URL( true ? "http://n" : 0); - const resolvedBase = base ? new URL(base, globalBase) : url.startsWith(".") ? new URL( true ? "http://n" : 0) : globalBase; - const { pathname , searchParams , search , hash , href , origin } = new URL(url, resolvedBase); - if (origin !== globalBase.origin) { - throw new Error("invariant: invalid relative URL, router received " + url); - } - return { - pathname, - query: (0, _querystring.searchParamsToUrlQuery)(searchParams), - search, - hash, - href: href.slice(globalBase.origin.length) - }; -} //# sourceMappingURL=parse-relative-url.js.map - - -/***/ }), - -/***/ 429: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "parseUrl", ({ - enumerable: true, - get: function() { - return parseUrl; - } -})); -const _querystring = __webpack_require__(4557); -const _parserelativeurl = __webpack_require__(3767); -function parseUrl(url) { - if (url.startsWith("/")) { - return (0, _parserelativeurl.parseRelativeUrl)(url); - } - const parsedURL = new URL(url); - return { - hash: parsedURL.hash, - hostname: parsedURL.hostname, - href: parsedURL.href, - pathname: parsedURL.pathname, - port: parsedURL.port, - protocol: parsedURL.protocol, - query: (0, _querystring.searchParamsToUrlQuery)(parsedURL.searchParams), - search: parsedURL.search - }; -} //# sourceMappingURL=parse-url.js.map - - -/***/ }), - -/***/ 247: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "getPathMatch", ({ - enumerable: true, - get: function() { - return getPathMatch; - } -})); -const _pathtoregexp = __webpack_require__(7999); -function getPathMatch(path, options) { - const keys = []; - const regexp = (0, _pathtoregexp.pathToRegexp)(path, keys, { - delimiter: "/", - sensitive: false, - strict: options == null ? void 0 : options.strict - }); - const matcher = (0, _pathtoregexp.regexpToFunction)((options == null ? void 0 : options.regexModifier) ? new RegExp(options.regexModifier(regexp.source), regexp.flags) : regexp, keys); - /** - * A matcher function that will check if a given pathname matches the path - * given in the builder function. When the path does not match it will return - * `false` but if it does it will return an object with the matched params - * merged with the params provided in the second argument. - */ return (pathname, params)=>{ - const res = pathname == null ? false : matcher(pathname); - if (!res) { - return false; - } - /** - * If unnamed params are not allowed they must be removed from - * the matched parameters. path-to-regexp uses "string" for named and - * "number" for unnamed parameters. - */ if (options == null ? void 0 : options.removeUnnamedParams) { - for (const key of keys){ - if (typeof key.name === "number") { - delete res.params[key.name]; - } - } - } - return { - ...params, - ...res.params - }; - }; -} //# sourceMappingURL=path-match.js.map - - -/***/ }), - -/***/ 880: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - matchHas: function() { - return matchHas; - }, - compileNonPath: function() { - return compileNonPath; - }, - prepareDestination: function() { - return prepareDestination; - } -}); -const _pathtoregexp = __webpack_require__(7999); -const _escaperegexp = __webpack_require__(536); -const _parseurl = __webpack_require__(429); -const _interceptionroutes = __webpack_require__(3958); -/** - * Ensure only a-zA-Z are used for param names for proper interpolating - * with path-to-regexp - */ function getSafeParamName(paramName) { - let newParamName = ""; - for(let i = 0; i < paramName.length; i++){ - const charCode = paramName.charCodeAt(i); - if (charCode > 64 && charCode < 91 || // A-Z - charCode > 96 && charCode < 123 // a-z - ) { - newParamName += paramName[i]; - } - } - return newParamName; -} -function escapeSegment(str, segmentName) { - return str.replace(new RegExp(":" + (0, _escaperegexp.escapeStringRegexp)(segmentName), "g"), "__ESC_COLON_" + segmentName); -} -function unescapeSegments(str) { - return str.replace(/__ESC_COLON_/gi, ":"); -} -function matchHas(req, query, has, missing) { - if (has === void 0) has = []; - if (missing === void 0) missing = []; - const params = {}; - const hasMatch = (hasItem)=>{ - let value; - let key = hasItem.key; - switch(hasItem.type){ - case "header": - { - key = key.toLowerCase(); - value = req.headers[key]; - break; - } - case "cookie": - { - value = req.cookies[hasItem.key]; - break; - } - case "query": - { - value = query[key]; - break; - } - case "host": - { - const { host } = (req == null ? void 0 : req.headers) || {}; - // remove port from host if present - const hostname = host == null ? void 0 : host.split(":")[0].toLowerCase(); - value = hostname; - break; - } - default: - { - break; - } - } - if (!hasItem.value && value) { - params[getSafeParamName(key)] = value; - return true; - } else if (value) { - const matcher = new RegExp("^" + hasItem.value + "$"); - const matches = Array.isArray(value) ? value.slice(-1)[0].match(matcher) : value.match(matcher); - if (matches) { - if (Array.isArray(matches)) { - if (matches.groups) { - Object.keys(matches.groups).forEach((groupKey)=>{ - params[groupKey] = matches.groups[groupKey]; - }); - } else if (hasItem.type === "host" && matches[0]) { - params.host = matches[0]; - } - } - return true; - } - } - return false; - }; - const allMatch = has.every((item)=>hasMatch(item)) && !missing.some((item)=>hasMatch(item)); - if (allMatch) { - return params; - } - return false; -} -function compileNonPath(value, params) { - if (!value.includes(":")) { - return value; - } - for (const key of Object.keys(params)){ - if (value.includes(":" + key)) { - value = value.replace(new RegExp(":" + key + "\\*", "g"), ":" + key + "--ESCAPED_PARAM_ASTERISKS").replace(new RegExp(":" + key + "\\?", "g"), ":" + key + "--ESCAPED_PARAM_QUESTION").replace(new RegExp(":" + key + "\\+", "g"), ":" + key + "--ESCAPED_PARAM_PLUS").replace(new RegExp(":" + key + "(?!\\w)", "g"), "--ESCAPED_PARAM_COLON" + key); - } - } - value = value.replace(/(:|\*|\?|\+|\(|\)|\{|\})/g, "\\$1").replace(/--ESCAPED_PARAM_PLUS/g, "+").replace(/--ESCAPED_PARAM_COLON/g, ":").replace(/--ESCAPED_PARAM_QUESTION/g, "?").replace(/--ESCAPED_PARAM_ASTERISKS/g, "*"); - // the value needs to start with a forward-slash to be compiled - // correctly - return (0, _pathtoregexp.compile)("/" + value, { - validate: false - })(params).slice(1); -} -function prepareDestination(args) { - const query = Object.assign({}, args.query); - delete query.__nextLocale; - delete query.__nextDefaultLocale; - delete query.__nextDataReq; - delete query.__nextInferredLocaleFromDefault; - let escapedDestination = args.destination; - for (const param of Object.keys({ - ...args.params, - ...query - })){ - escapedDestination = escapeSegment(escapedDestination, param); - } - const parsedDestination = (0, _parseurl.parseUrl)(escapedDestination); - const destQuery = parsedDestination.query; - const destPath = unescapeSegments("" + parsedDestination.pathname + (parsedDestination.hash || "")); - const destHostname = unescapeSegments(parsedDestination.hostname || ""); - const destPathParamKeys = []; - const destHostnameParamKeys = []; - (0, _pathtoregexp.pathToRegexp)(destPath, destPathParamKeys); - (0, _pathtoregexp.pathToRegexp)(destHostname, destHostnameParamKeys); - const destParams = []; - destPathParamKeys.forEach((key)=>destParams.push(key.name)); - destHostnameParamKeys.forEach((key)=>destParams.push(key.name)); - const destPathCompiler = (0, _pathtoregexp.compile)(destPath, // have already validated before we got to this point and validating - // breaks compiling destinations with named pattern params from the source - // e.g. /something:hello(.*) -> /another/:hello is broken with validation - // since compile validation is meant for reversing and not for inserting - // params from a separate path-regex into another - { - validate: false - }); - const destHostnameCompiler = (0, _pathtoregexp.compile)(destHostname, { - validate: false - }); - // update any params in query values - for (const [key, strOrArray] of Object.entries(destQuery)){ - // the value needs to start with a forward-slash to be compiled - // correctly - if (Array.isArray(strOrArray)) { - destQuery[key] = strOrArray.map((value)=>compileNonPath(unescapeSegments(value), args.params)); - } else if (typeof strOrArray === "string") { - destQuery[key] = compileNonPath(unescapeSegments(strOrArray), args.params); - } - } - // add path params to query if it's not a redirect and not - // already defined in destination query or path - let paramKeys = Object.keys(args.params).filter((name)=>name !== "nextInternalLocale"); - if (args.appendParamsToQuery && !paramKeys.some((key)=>destParams.includes(key))) { - for (const key of paramKeys){ - if (!(key in destQuery)) { - destQuery[key] = args.params[key]; - } - } - } - let newUrl; - // The compiler also that the interception route marker is an unnamed param, hence '0', - // so we need to add it to the params object. - if ((0, _interceptionroutes.isInterceptionRouteAppPath)(destPath)) { - for (const segment of destPath.split("/")){ - const marker = _interceptionroutes.INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m)); - if (marker) { - args.params["0"] = marker; - break; - } - } - } - try { - newUrl = destPathCompiler(args.params); - const [pathname, hash] = newUrl.split("#"); - parsedDestination.hostname = destHostnameCompiler(args.params); - parsedDestination.pathname = pathname; - parsedDestination.hash = "" + (hash ? "#" : "") + (hash || ""); - delete parsedDestination.search; - } catch (err) { - if (err.message.match(/Expected .*? to not repeat, but got an array/)) { - throw new Error("To use a multi-match in the destination you must add `*` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match"); - } - throw err; - } - // Query merge order lowest priority to highest - // 1. initial URL query values - // 2. path segment values - // 3. destination specified query values - parsedDestination.query = { - ...query, - ...parsedDestination.query - }; - return { - newUrl, - destQuery, - parsedDestination - }; -} //# sourceMappingURL=prepare-destination.js.map - - -/***/ }), - -/***/ 4557: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - searchParamsToUrlQuery: function() { - return searchParamsToUrlQuery; - }, - urlQueryToSearchParams: function() { - return urlQueryToSearchParams; - }, - assign: function() { - return assign; - } -}); -function searchParamsToUrlQuery(searchParams) { - const query = {}; - searchParams.forEach((value, key)=>{ - if (typeof query[key] === "undefined") { - query[key] = value; - } else if (Array.isArray(query[key])) { - query[key].push(value); - } else { - query[key] = [ - query[key], - value - ]; - } - }); - return query; -} -function stringifyUrlQueryParam(param) { - if (typeof param === "string" || typeof param === "number" && !isNaN(param) || typeof param === "boolean") { - return String(param); - } else { - return ""; - } -} -function urlQueryToSearchParams(urlQuery) { - const result = new URLSearchParams(); - Object.entries(urlQuery).forEach((param)=>{ - let [key, value] = param; - if (Array.isArray(value)) { - value.forEach((item)=>result.append(key, stringifyUrlQueryParam(item))); - } else { - result.set(key, stringifyUrlQueryParam(value)); - } - }); - return result; -} -function assign(target) { - for(var _len = arguments.length, searchParamsList = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){ - searchParamsList[_key - 1] = arguments[_key]; - } - searchParamsList.forEach((searchParams)=>{ - Array.from(searchParams.keys()).forEach((key)=>target.delete(key)); - searchParams.forEach((value, key)=>target.append(key, value)); - }); - return target; -} //# sourceMappingURL=querystring.js.map - - -/***/ }), - -/***/ 4060: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "getRouteMatcher", ({ - enumerable: true, - get: function() { - return getRouteMatcher; - } -})); -const _utils = __webpack_require__(1265); -function getRouteMatcher(param) { - let { re , groups } = param; - return (pathname)=>{ - const routeMatch = re.exec(pathname); - if (!routeMatch) { - return false; - } - const decode = (param)=>{ - try { - return decodeURIComponent(param); - } catch (_) { - throw new _utils.DecodeError("failed to decode param"); - } - }; - const params = {}; - Object.keys(groups).forEach((slugName)=>{ - const g = groups[slugName]; - const m = routeMatch[g.pos]; - if (m !== undefined) { - params[slugName] = ~m.indexOf("/") ? m.split("/").map((entry)=>decode(entry)) : g.repeat ? [ - decode(m) - ] : decode(m); - } - }); - return params; - }; -} //# sourceMappingURL=route-matcher.js.map - - -/***/ }), - -/***/ 9601: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - getRouteRegex: function() { - return getRouteRegex; - }, - getNamedRouteRegex: function() { - return getNamedRouteRegex; - }, - getNamedMiddlewareRegex: function() { - return getNamedMiddlewareRegex; - } -}); -const _escaperegexp = __webpack_require__(536); -const _removetrailingslash = __webpack_require__(465); -const NEXT_QUERY_PARAM_PREFIX = "nxtP"; -/** - * Parses a given parameter from a route to a data structure that can be used - * to generate the parametrized route. Examples: - * - `[...slug]` -> `{ key: 'slug', repeat: true, optional: true }` - * - `...slug` -> `{ key: 'slug', repeat: true, optional: false }` - * - `[foo]` -> `{ key: 'foo', repeat: false, optional: true }` - * - `bar` -> `{ key: 'bar', repeat: false, optional: false }` - */ function parseParameter(param) { - const optional = param.startsWith("[") && param.endsWith("]"); - if (optional) { - param = param.slice(1, -1); - } - const repeat = param.startsWith("..."); - if (repeat) { - param = param.slice(3); - } - return { - key: param, - repeat, - optional - }; -} -function getParametrizedRoute(route) { - const segments = (0, _removetrailingslash.removeTrailingSlash)(route).slice(1).split("/"); - const groups = {}; - let groupIndex = 1; - return { - parameterizedRoute: segments.map((segment)=>{ - if (segment.startsWith("[") && segment.endsWith("]")) { - const { key , optional , repeat } = parseParameter(segment.slice(1, -1)); - groups[key] = { - pos: groupIndex++, - repeat, - optional - }; - return repeat ? optional ? "(?:/(.+?))?" : "/(.+?)" : "/([^/]+?)"; - } else { - return "/" + (0, _escaperegexp.escapeStringRegexp)(segment); - } - }).join(""), - groups - }; -} -function getRouteRegex(normalizedRoute) { - const { parameterizedRoute , groups } = getParametrizedRoute(normalizedRoute); - return { - re: new RegExp("^" + parameterizedRoute + "(?:/)?$"), - groups: groups - }; -} -/** - * Builds a function to generate a minimal routeKey using only a-z and minimal - * number of characters. - */ function buildGetSafeRouteKey() { - let routeKeyCharCode = 97; - let routeKeyCharLength = 1; - return ()=>{ - let routeKey = ""; - for(let i = 0; i < routeKeyCharLength; i++){ - routeKey += String.fromCharCode(routeKeyCharCode); - routeKeyCharCode++; - if (routeKeyCharCode > 122) { - routeKeyCharLength++; - routeKeyCharCode = 97; - } - } - return routeKey; - }; -} -function getNamedParametrizedRoute(route, prefixRouteKeys) { - const segments = (0, _removetrailingslash.removeTrailingSlash)(route).slice(1).split("/"); - const getSafeRouteKey = buildGetSafeRouteKey(); - const routeKeys = {}; - return { - namedParameterizedRoute: segments.map((segment)=>{ - if (segment.startsWith("[") && segment.endsWith("]")) { - const { key , optional , repeat } = parseParameter(segment.slice(1, -1)); - // replace any non-word characters since they can break - // the named regex - let cleanedKey = key.replace(/\W/g, ""); - if (prefixRouteKeys) { - cleanedKey = "" + NEXT_QUERY_PARAM_PREFIX + cleanedKey; - } - let invalidKey = false; - // check if the key is still invalid and fallback to using a known - // safe key - if (cleanedKey.length === 0 || cleanedKey.length > 30) { - invalidKey = true; - } - if (!isNaN(parseInt(cleanedKey.slice(0, 1)))) { - invalidKey = true; - } - if (invalidKey) { - cleanedKey = getSafeRouteKey(); - } - if (prefixRouteKeys) { - routeKeys[cleanedKey] = "" + NEXT_QUERY_PARAM_PREFIX + key; - } else { - routeKeys[cleanedKey] = "" + key; - } - return repeat ? optional ? "(?:/(?<" + cleanedKey + ">.+?))?" : "/(?<" + cleanedKey + ">.+?)" : "/(?<" + cleanedKey + ">[^/]+?)"; - } else { - return "/" + (0, _escaperegexp.escapeStringRegexp)(segment); - } - }).join(""), - routeKeys - }; -} -function getNamedRouteRegex(normalizedRoute, prefixRouteKey) { - const result = getNamedParametrizedRoute(normalizedRoute, prefixRouteKey); - return { - ...getRouteRegex(normalizedRoute), - namedRegex: "^" + result.namedParameterizedRoute + "(?:/)?$", - routeKeys: result.routeKeys - }; -} -function getNamedMiddlewareRegex(normalizedRoute, options) { - const { parameterizedRoute } = getParametrizedRoute(normalizedRoute); - const { catchAll =true } = options; - if (parameterizedRoute === "/") { - let catchAllRegex = catchAll ? ".*" : ""; - return { - namedRegex: "^/" + catchAllRegex + "$" - }; - } - const { namedParameterizedRoute } = getNamedParametrizedRoute(normalizedRoute, false); - let catchAllGroupedRegex = catchAll ? "(?:(/.*)?)" : ""; - return { - namedRegex: "^" + namedParameterizedRoute + catchAllGroupedRegex + "$" - }; -} //# sourceMappingURL=route-regex.js.map - - -/***/ }), - -/***/ 6262: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "getSortedRoutes", ({ - enumerable: true, - get: function() { - return getSortedRoutes; - } -})); -class UrlNode { - insert(urlPath) { - this._insert(urlPath.split("/").filter(Boolean), [], false); - } - smoosh() { - return this._smoosh(); - } - _smoosh(prefix) { - if (prefix === void 0) prefix = "/"; - const childrenPaths = [ - ...this.children.keys() - ].sort(); - if (this.slugName !== null) { - childrenPaths.splice(childrenPaths.indexOf("[]"), 1); - } - if (this.restSlugName !== null) { - childrenPaths.splice(childrenPaths.indexOf("[...]"), 1); - } - if (this.optionalRestSlugName !== null) { - childrenPaths.splice(childrenPaths.indexOf("[[...]]"), 1); - } - const routes = childrenPaths.map((c)=>this.children.get(c)._smoosh("" + prefix + c + "/")).reduce((prev, curr)=>[ - ...prev, - ...curr - ], []); - if (this.slugName !== null) { - routes.push(...this.children.get("[]")._smoosh(prefix + "[" + this.slugName + "]/")); - } - if (!this.placeholder) { - const r = prefix === "/" ? "/" : prefix.slice(0, -1); - if (this.optionalRestSlugName != null) { - throw new Error('You cannot define a route with the same specificity as a optional catch-all route ("' + r + '" and "' + r + "[[..." + this.optionalRestSlugName + ']]").'); - } - routes.unshift(r); - } - if (this.restSlugName !== null) { - routes.push(...this.children.get("[...]")._smoosh(prefix + "[..." + this.restSlugName + "]/")); - } - if (this.optionalRestSlugName !== null) { - routes.push(...this.children.get("[[...]]")._smoosh(prefix + "[[..." + this.optionalRestSlugName + "]]/")); - } - return routes; - } - _insert(urlPaths, slugNames, isCatchAll) { - if (urlPaths.length === 0) { - this.placeholder = false; - return; - } - if (isCatchAll) { - throw new Error("Catch-all must be the last part of the URL."); - } - // The next segment in the urlPaths list - let nextSegment = urlPaths[0]; - // Check if the segment matches `[something]` - if (nextSegment.startsWith("[") && nextSegment.endsWith("]")) { - // Strip `[` and `]`, leaving only `something` - let segmentName = nextSegment.slice(1, -1); - let isOptional = false; - if (segmentName.startsWith("[") && segmentName.endsWith("]")) { - // Strip optional `[` and `]`, leaving only `something` - segmentName = segmentName.slice(1, -1); - isOptional = true; - } - if (segmentName.startsWith("...")) { - // Strip `...`, leaving only `something` - segmentName = segmentName.substring(3); - isCatchAll = true; - } - if (segmentName.startsWith("[") || segmentName.endsWith("]")) { - throw new Error("Segment names may not start or end with extra brackets ('" + segmentName + "')."); - } - if (segmentName.startsWith(".")) { - throw new Error("Segment names may not start with erroneous periods ('" + segmentName + "')."); - } - function handleSlug(previousSlug, nextSlug) { - if (previousSlug !== null) { - // If the specific segment already has a slug but the slug is not `something` - // This prevents collisions like: - // pages/[post]/index.js - // pages/[id]/index.js - // Because currently multiple dynamic params on the same segment level are not supported - if (previousSlug !== nextSlug) { - // TODO: This error seems to be confusing for users, needs an error link, the description can be based on above comment. - throw new Error("You cannot use different slug names for the same dynamic path ('" + previousSlug + "' !== '" + nextSlug + "')."); - } - } - slugNames.forEach((slug)=>{ - if (slug === nextSlug) { - throw new Error('You cannot have the same slug name "' + nextSlug + '" repeat within a single dynamic path'); - } - if (slug.replace(/\W/g, "") === nextSegment.replace(/\W/g, "")) { - throw new Error('You cannot have the slug names "' + slug + '" and "' + nextSlug + '" differ only by non-word symbols within a single dynamic path'); - } - }); - slugNames.push(nextSlug); - } - if (isCatchAll) { - if (isOptional) { - if (this.restSlugName != null) { - throw new Error('You cannot use both an required and optional catch-all route at the same level ("[...' + this.restSlugName + ']" and "' + urlPaths[0] + '" ).'); - } - handleSlug(this.optionalRestSlugName, segmentName); - // slugName is kept as it can only be one particular slugName - this.optionalRestSlugName = segmentName; - // nextSegment is overwritten to [[...]] so that it can later be sorted specifically - nextSegment = "[[...]]"; - } else { - if (this.optionalRestSlugName != null) { - throw new Error('You cannot use both an optional and required catch-all route at the same level ("[[...' + this.optionalRestSlugName + ']]" and "' + urlPaths[0] + '").'); - } - handleSlug(this.restSlugName, segmentName); - // slugName is kept as it can only be one particular slugName - this.restSlugName = segmentName; - // nextSegment is overwritten to [...] so that it can later be sorted specifically - nextSegment = "[...]"; - } - } else { - if (isOptional) { - throw new Error('Optional route parameters are not yet supported ("' + urlPaths[0] + '").'); - } - handleSlug(this.slugName, segmentName); - // slugName is kept as it can only be one particular slugName - this.slugName = segmentName; - // nextSegment is overwritten to [] so that it can later be sorted specifically - nextSegment = "[]"; - } - } - // If this UrlNode doesn't have the nextSegment yet we create a new child UrlNode - if (!this.children.has(nextSegment)) { - this.children.set(nextSegment, new UrlNode()); - } - this.children.get(nextSegment)._insert(urlPaths.slice(1), slugNames, isCatchAll); - } - constructor(){ - this.placeholder = true; - this.children = new Map(); - this.slugName = null; - this.restSlugName = null; - this.optionalRestSlugName = null; - } -} -function getSortedRoutes(normalizedPages) { - // First the UrlNode is created, and every UrlNode can have only 1 dynamic segment - // Eg you can't have pages/[post]/abc.js and pages/[hello]/something-else.js - // Only 1 dynamic segment per nesting level - // So in the case that is test/integration/dynamic-routing it'll be this: - // pages/[post]/comments.js - // pages/blog/[post]/comment/[id].js - // Both are fine because `pages/[post]` and `pages/blog` are on the same level - // So in this case `UrlNode` created here has `this.slugName === 'post'` - // And since your PR passed through `slugName` as an array basically it'd including it in too many possibilities - // Instead what has to be passed through is the upwards path's dynamic names - const root = new UrlNode(); - // Here the `root` gets injected multiple paths, and insert will break them up into sublevels - normalizedPages.forEach((pagePath)=>root.insert(pagePath)); - // Smoosh will then sort those sublevels up to the point where you get the correct route definition priority - return root.smoosh(); -} //# sourceMappingURL=sorted-routes.js.map - - -/***/ }), - -/***/ 1265: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - WEB_VITALS: function() { - return WEB_VITALS; - }, - execOnce: function() { - return execOnce; - }, - isAbsoluteUrl: function() { - return isAbsoluteUrl; - }, - getLocationOrigin: function() { - return getLocationOrigin; - }, - getURL: function() { - return getURL; - }, - getDisplayName: function() { - return getDisplayName; - }, - isResSent: function() { - return isResSent; - }, - normalizeRepeatedSlashes: function() { - return normalizeRepeatedSlashes; - }, - loadGetInitialProps: function() { - return loadGetInitialProps; - }, - SP: function() { - return SP; - }, - ST: function() { - return ST; - }, - DecodeError: function() { - return DecodeError; - }, - NormalizeError: function() { - return NormalizeError; - }, - PageNotFoundError: function() { - return PageNotFoundError; - }, - MissingStaticPage: function() { - return MissingStaticPage; - }, - MiddlewareNotFoundError: function() { - return MiddlewareNotFoundError; - } -}); -const WEB_VITALS = [ - "CLS", - "FCP", - "FID", - "INP", - "LCP", - "TTFB" -]; -function execOnce(fn) { - let used = false; - let result; - return function() { - for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){ - args[_key] = arguments[_key]; - } - if (!used) { - used = true; - result = fn(...args); - } - return result; - }; -} -// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 -// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 -const ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\d+\-.]*?:/; -const isAbsoluteUrl = (url)=>ABSOLUTE_URL_REGEX.test(url); -function getLocationOrigin() { - const { protocol , hostname , port } = window.location; - return protocol + "//" + hostname + (port ? ":" + port : ""); -} -function getURL() { - const { href } = window.location; - const origin = getLocationOrigin(); - return href.substring(origin.length); -} -function getDisplayName(Component) { - return typeof Component === "string" ? Component : Component.displayName || Component.name || "Unknown"; -} -function isResSent(res) { - return res.finished || res.headersSent; -} -function normalizeRepeatedSlashes(url) { - const urlParts = url.split("?"); - const urlNoQuery = urlParts[0]; - return urlNoQuery // first we replace any non-encoded backslashes with forward - // then normalize repeated forward slashes - .replace(/\\/g, "/").replace(/\/\/+/g, "/") + (urlParts[1] ? "?" + urlParts.slice(1).join("?") : ""); -} -async function loadGetInitialProps(App, ctx) { - if (false) { var _App_prototype; } - // when called from _app `ctx` is nested in `ctx` - const res = ctx.res || ctx.ctx && ctx.ctx.res; - if (!App.getInitialProps) { - if (ctx.ctx && ctx.Component) { - // @ts-ignore pageProps default - return { - pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx) - }; - } - return {}; - } - const props = await App.getInitialProps(ctx); - if (res && isResSent(res)) { - return props; - } - if (!props) { - const message = '"' + getDisplayName(App) + '.getInitialProps()" should resolve to an object. But found "' + props + '" instead.'; - throw new Error(message); - } - if (false) {} - return props; -} -const SP = typeof performance !== "undefined"; -const ST = SP && [ - "mark", - "measure", - "getEntriesByName" -].every((method)=>typeof performance[method] === "function"); -class DecodeError extends Error { -} -class NormalizeError extends Error { -} -class PageNotFoundError extends Error { - constructor(page){ - super(); - this.code = "ENOENT"; - this.name = "PageNotFoundError"; - this.message = "Cannot find module for page: " + page; - } -} -class MissingStaticPage extends Error { - constructor(page, message){ - super(); - this.message = "Failed to load static file for page: " + page + " " + message; - } -} -class MiddlewareNotFoundError extends Error { - constructor(){ - super(); - this.code = "ENOENT"; - this.message = "Cannot find the middleware module"; - } -} //# sourceMappingURL=utils.js.map - - -/***/ }), - -/***/ 5967: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -exports._ = exports._interop_require_default = _interop_require_default; -function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { default: obj }; -} - - -/***/ }), - -/***/ 1113: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -} -exports._ = exports._interop_require_wildcard = _interop_require_wildcard; -function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj }; - - var cache = _getRequireWildcardCache(nodeInterop); - - if (cache && cache.has(obj)) return cache.get(obj); - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - - newObj.default = obj; - - if (cache) cache.set(obj, newObj); - - return newObj; -} - - -/***/ }), - -/***/ 1550: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -exports._ = exports._interop_require_default = _interop_require_default; -function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} - - -/***/ }) - -}; -; \ No newline at end of file diff --git a/.next/server/chunks/622.js b/.next/server/chunks/622.js new file mode 100644 index 0000000..a9afa78 --- /dev/null +++ b/.next/server/chunks/622.js @@ -0,0 +1 @@ +exports.id=622,exports.ids=[622],exports.modules={6254:(e,t,s)=>{Promise.resolve().then(s.t.bind(s,3724,23)),Promise.resolve().then(s.t.bind(s,5365,23)),Promise.resolve().then(s.t.bind(s,4900,23)),Promise.resolve().then(s.t.bind(s,4714,23)),Promise.resolve().then(s.t.bind(s,5392,23)),Promise.resolve().then(s.t.bind(s,8898,23))},2731:()=>{},5345:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>RootLayout,metadata:()=>n});var o=s(4656),r=s(2999),i=s.n(r);s(3440);let n={title:"sukadia.dev",description:"I code, stream, and create videos."};function RootLayout({children:e}){return o.jsx("html",{lang:"en",children:o.jsx("body",{className:i().className,children:e})})}},3440:()=>{}}; \ No newline at end of file diff --git a/.next/server/chunks/676.js b/.next/server/chunks/676.js new file mode 100644 index 0000000..d1f6098 --- /dev/null +++ b/.next/server/chunks/676.js @@ -0,0 +1,6 @@ +"use strict";exports.id=676,exports.ids=[676],exports.modules={8676:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{Head:function(){return Head},NextScript:function(){return NextScript},Html:function(){return Html},Main:function(){return Main},default:function(){return Document}});let r=_interop_require_default(n(6689)),i=n(4191),o=n(5778),s=n(9630),l=_interop_require_default(n(676)),a=n(3112);function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}let u=new Set;function getDocumentFiles(e,t,n){let r=(0,o.getPageFiles)(e,"/_app"),i=n?[]:(0,o.getPageFiles)(e,t);return{sharedFiles:r,pageFiles:i,allFiles:[...new Set([...r,...i])]}}function getPolyfillScripts(e,t){let{assetPrefix:n,buildManifest:i,assetQueryString:o,disableOptimizedLoading:s,crossOrigin:l}=e;return i.polyfillFiles.filter(e=>e.endsWith(".js")&&!e.endsWith(".module.js")).map(e=>r.default.createElement("script",{key:e,defer:!s,nonce:t.nonce,crossOrigin:t.crossOrigin||l,noModule:!0,src:`${n}/_next/${e}${o}`}))}function hasComponentProps(e){return!!e&&!!e.props}function AmpStyles({styles:e}){if(!e)return null;let t=Array.isArray(e)?e:[];if(e.props&&Array.isArray(e.props.children)){let hasStyles=e=>{var t,n;return null==e?void 0:null==(n=e.props)?void 0:null==(t=n.dangerouslySetInnerHTML)?void 0:t.__html};e.props.children.forEach(e=>{Array.isArray(e)?e.forEach(e=>hasStyles(e)&&t.push(e)):hasStyles(e)&&t.push(e)})}return r.default.createElement("style",{"amp-custom":"",dangerouslySetInnerHTML:{__html:t.map(e=>e.props.dangerouslySetInnerHTML.__html).join("").replace(/\/\*# sourceMappingURL=.*\*\//g,"").replace(/\/\*@ sourceURL=.*?\*\//g,"")}})}function getDynamicChunks(e,t,n){let{dynamicImports:i,assetPrefix:o,isDevelopment:s,assetQueryString:l,disableOptimizedLoading:a,crossOrigin:u}=e;return i.map(e=>!e.endsWith(".js")||n.allFiles.includes(e)?null:r.default.createElement("script",{async:!s&&a,defer:!a,key:e,src:`${o}/_next/${encodeURI(e)}${l}`,nonce:t.nonce,crossOrigin:t.crossOrigin||u}))}function getScripts(e,t,n){var i;let{assetPrefix:o,buildManifest:s,isDevelopment:l,assetQueryString:a,disableOptimizedLoading:u,crossOrigin:c}=e,d=n.allFiles.filter(e=>e.endsWith(".js")),p=null==(i=s.lowPriorityFiles)?void 0:i.filter(e=>e.endsWith(".js"));return[...d,...p].map(e=>r.default.createElement("script",{key:e,src:`${o}/_next/${encodeURI(e)}${a}`,nonce:t.nonce,async:!l&&u,defer:!u,crossOrigin:t.crossOrigin||c}))}function getPreNextWorkerScripts(e,t){let{assetPrefix:n,scriptLoader:i,crossOrigin:o,nextScriptWorkers:s}=e;if(!s)return null;try{let{partytownSnippet:e}=require("@builder.io/partytown/integration"),s=Array.isArray(t.children)?t.children:[t.children],l=s.find(e=>{var t,n;return hasComponentProps(e)&&(null==e?void 0:null==(n=e.props)?void 0:null==(t=n.dangerouslySetInnerHTML)?void 0:t.__html.length)&&"data-partytown-config"in e.props});return r.default.createElement(r.default.Fragment,null,!l&&r.default.createElement("script",{"data-partytown-config":"",dangerouslySetInnerHTML:{__html:` + partytown = { + lib: "${n}/_next/static/~partytown/" + }; + `}}),r.default.createElement("script",{"data-partytown":"",dangerouslySetInnerHTML:{__html:e()}}),(i.worker||[]).map((e,n)=>{let{strategy:i,src:s,children:l,dangerouslySetInnerHTML:a,...u}=e,c={};if(s)c.src=s;else if(a&&a.__html)c.dangerouslySetInnerHTML={__html:a.__html};else if(l)c.dangerouslySetInnerHTML={__html:"string"==typeof l?l:Array.isArray(l)?l.join(""):""};else throw Error("Invalid usage of next/script. Did you forget to include a src attribute or an inline script? https://nextjs.org/docs/messages/invalid-script");return r.default.createElement("script",{...c,...u,type:"text/partytown",key:s||n,nonce:t.nonce,"data-nscript":"worker",crossOrigin:t.crossOrigin||o})}))}catch(e){return(0,l.default)(e)&&"MODULE_NOT_FOUND"!==e.code&&console.warn(`Warning: ${e.message}`),null}}function getPreNextScripts(e,t){let{scriptLoader:n,disableOptimizedLoading:i,crossOrigin:o}=e,s=getPreNextWorkerScripts(e,t),l=(n.beforeInteractive||[]).filter(e=>e.src).map((e,n)=>{let{strategy:s,...l}=e;return r.default.createElement("script",{...l,key:l.src||n,defer:l.defer??!i,nonce:t.nonce,"data-nscript":"beforeInteractive",crossOrigin:t.crossOrigin||o})});return r.default.createElement(r.default.Fragment,null,s,l)}function getHeadHTMLProps(e){let{crossOrigin:t,nonce:n,...r}=e;return r}function getAmpPath(e,t){return e||`${t}${t.includes("?")?"&":"?"}amp=1`}function getNextFontLinkTags(e,t,n=""){if(!e)return{preconnect:null,preload:null};let i=e.pages["/_app"],o=e.pages[t],s=[...i??[],...o??[]],l=!!(0===s.length&&(i||o));return{preconnect:l?r.default.createElement("link",{"data-next-font":e.pagesUsingSizeAdjust?"size-adjust":"",rel:"preconnect",href:"/",crossOrigin:"anonymous"}):null,preload:s?s.map(e=>{let t=/\.(woff|woff2|eot|ttf|otf)$/.exec(e)[1];return r.default.createElement("link",{key:e,rel:"preload",href:`${n}/_next/${encodeURI(e)}`,as:"font",type:`font/${t}`,crossOrigin:"anonymous","data-next-font":e.includes("-s")?"size-adjust":""})}):null}}let Head=class Head extends r.default.Component{static #e=this.contextType=a.HtmlContext;getCssLinks(e){let{assetPrefix:t,assetQueryString:n,dynamicImports:i,crossOrigin:o,optimizeCss:s,optimizeFonts:l}=this.context,a=e.allFiles.filter(e=>e.endsWith(".css")),u=new Set(e.sharedFiles),c=new Set([]),d=Array.from(new Set(i.filter(e=>e.endsWith(".css"))));if(d.length){let e=new Set(a);d=d.filter(t=>!(e.has(t)||u.has(t))),c=new Set(d),a.push(...d)}let p=[];return a.forEach(e=>{let i=u.has(e);s||p.push(r.default.createElement("link",{key:`${e}-preload`,nonce:this.props.nonce,rel:"preload",href:`${t}/_next/${encodeURI(e)}${n}`,as:"style",crossOrigin:this.props.crossOrigin||o}));let l=c.has(e);p.push(r.default.createElement("link",{key:e,nonce:this.props.nonce,rel:"stylesheet",href:`${t}/_next/${encodeURI(e)}${n}`,crossOrigin:this.props.crossOrigin||o,"data-n-g":l?void 0:i?"":void 0,"data-n-p":l?void 0:i?void 0:""}))}),l&&(p=this.makeStylesheetInert(p)),0===p.length?null:p}getPreloadDynamicChunks(){let{dynamicImports:e,assetPrefix:t,assetQueryString:n,crossOrigin:i}=this.context;return e.map(e=>e.endsWith(".js")?r.default.createElement("link",{rel:"preload",key:e,href:`${t}/_next/${encodeURI(e)}${n}`,as:"script",nonce:this.props.nonce,crossOrigin:this.props.crossOrigin||i}):null).filter(Boolean)}getPreloadMainLinks(e){let{assetPrefix:t,assetQueryString:n,scriptLoader:i,crossOrigin:o}=this.context,s=e.allFiles.filter(e=>e.endsWith(".js"));return[...(i.beforeInteractive||[]).map(e=>r.default.createElement("link",{key:e.src,nonce:this.props.nonce,rel:"preload",href:e.src,as:"script",crossOrigin:this.props.crossOrigin||o})),...s.map(e=>r.default.createElement("link",{key:e,nonce:this.props.nonce,rel:"preload",href:`${t}/_next/${encodeURI(e)}${n}`,as:"script",crossOrigin:this.props.crossOrigin||o}))]}getBeforeInteractiveInlineScripts(){let{scriptLoader:e}=this.context,{nonce:t,crossOrigin:n}=this.props;return(e.beforeInteractive||[]).filter(e=>!e.src&&(e.dangerouslySetInnerHTML||e.children)).map((e,i)=>{let{strategy:o,children:s,dangerouslySetInnerHTML:l,src:a,...u}=e,c="";return l&&l.__html?c=l.__html:s&&(c="string"==typeof s?s:Array.isArray(s)?s.join(""):""),r.default.createElement("script",{...u,dangerouslySetInnerHTML:{__html:c},key:u.id||i,nonce:t,"data-nscript":"beforeInteractive",crossOrigin:n||void 0})})}getDynamicChunks(e){return getDynamicChunks(this.context,this.props,e)}getPreNextScripts(){return getPreNextScripts(this.context,this.props)}getScripts(e){return getScripts(this.context,this.props,e)}getPolyfillScripts(){return getPolyfillScripts(this.context,this.props)}makeStylesheetInert(e){return r.default.Children.map(e,e=>{var t,n;if((null==e?void 0:e.type)==="link"&&(null==e?void 0:null==(t=e.props)?void 0:t.href)&&i.OPTIMIZED_FONT_PROVIDERS.some(({url:t})=>{var n,r;return null==e?void 0:null==(r=e.props)?void 0:null==(n=r.href)?void 0:n.startsWith(t)})){let t={...e.props||{},"data-href":e.props.href,href:void 0};return r.default.cloneElement(e,t)}if(null==e?void 0:null==(n=e.props)?void 0:n.children){let t={...e.props||{},children:this.makeStylesheetInert(e.props.children)};return r.default.cloneElement(e,t)}return e}).filter(Boolean)}render(){let{styles:e,ampPath:t,inAmpMode:i,hybridAmp:o,canonicalBase:s,__NEXT_DATA__:l,dangerousAsPath:a,headTags:u,unstable_runtimeJS:c,unstable_JsPreload:d,disableOptimizedLoading:p,optimizeCss:f,optimizeFonts:m,assetPrefix:h,nextFontManifest:g}=this.context,_=!1===c,E=!1===d||!p;this.context.docComponentsRendered.Head=!0;let{head:S}=this.context,y=[],I=[];S&&(S.forEach(e=>{let t;this.context.strictNextHead&&(t=r.default.createElement("meta",{name:"next-head",content:"1"})),e&&"link"===e.type&&"preload"===e.props.rel&&"style"===e.props.as?(t&&y.push(t),y.push(e)):e&&(t&&("meta"!==e.type||!e.props.charSet)&&I.push(t),I.push(e))}),S=y.concat(I));let P=r.default.Children.toArray(this.props.children).filter(Boolean);m&&!i&&(P=this.makeStylesheetInert(P));let T=!1,N=!1;S=r.default.Children.map(S||[],e=>{if(!e)return e;let{type:t,props:n}=e;if(i){let r="";if("meta"===t&&"viewport"===n.name?r='name="viewport"':"link"===t&&"canonical"===n.rel?N=!0:"script"===t&&(n.src&&-1>n.src.indexOf("ampproject")||n.dangerouslySetInnerHTML&&(!n.type||"text/javascript"===n.type))&&(r="<script",Object.keys(n).forEach(e=>{r+=` ${e}="${n[e]}"`}),r+="/>"),r)return console.warn(`Found conflicting amp tag "${e.type}" with conflicting prop ${r} in ${l.page}. https://nextjs.org/docs/messages/conflicting-amp-tag`),null}else"link"===t&&"amphtml"===n.rel&&(T=!0);return e});let O=getDocumentFiles(this.context.buildManifest,this.context.__NEXT_DATA__.page,i),b=getNextFontLinkTags(g,a,h);return r.default.createElement("head",getHeadHTMLProps(this.props),this.context.isDevelopment&&r.default.createElement(r.default.Fragment,null,r.default.createElement("style",{"data-next-hide-fouc":!0,"data-ampdevmode":i?"true":void 0,dangerouslySetInnerHTML:{__html:"body{display:none}"}}),r.default.createElement("noscript",{"data-next-hide-fouc":!0,"data-ampdevmode":i?"true":void 0},r.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{display:block}"}}))),S,this.context.strictNextHead?null:r.default.createElement("meta",{name:"next-head-count",content:r.default.Children.count(S||[]).toString()}),P,m&&r.default.createElement("meta",{name:"next-font-preconnect"}),b.preconnect,b.preload,i&&r.default.createElement(r.default.Fragment,null,r.default.createElement("meta",{name:"viewport",content:"width=device-width,minimum-scale=1,initial-scale=1"}),!N&&r.default.createElement("link",{rel:"canonical",href:s+n(733).cleanAmpPath(a)}),r.default.createElement("link",{rel:"preload",as:"script",href:"https://cdn.ampproject.org/v0.js"}),r.default.createElement(AmpStyles,{styles:e}),r.default.createElement("style",{"amp-boilerplate":"",dangerouslySetInnerHTML:{__html:"body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}"}}),r.default.createElement("noscript",null,r.default.createElement("style",{"amp-boilerplate":"",dangerouslySetInnerHTML:{__html:"body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}"}})),r.default.createElement("script",{async:!0,src:"https://cdn.ampproject.org/v0.js"})),!i&&r.default.createElement(r.default.Fragment,null,!T&&o&&r.default.createElement("link",{rel:"amphtml",href:s+getAmpPath(t,a)}),this.getBeforeInteractiveInlineScripts(),!f&&this.getCssLinks(O),!f&&r.default.createElement("noscript",{"data-n-css":this.props.nonce??""}),!_&&!E&&this.getPreloadDynamicChunks(),!_&&!E&&this.getPreloadMainLinks(O),!p&&!_&&this.getPolyfillScripts(),!p&&!_&&this.getPreNextScripts(),!p&&!_&&this.getDynamicChunks(O),!p&&!_&&this.getScripts(O),f&&this.getCssLinks(O),f&&r.default.createElement("noscript",{"data-n-css":this.props.nonce??""}),this.context.isDevelopment&&r.default.createElement("noscript",{id:"__next_css__DO_NOT_USE__"}),e||null),r.default.createElement(r.default.Fragment,{},...u||[]))}};function handleDocumentScriptLoaderItems(e,t,n){var i,o,s,l;if(!n.children)return;let a=[],u=Array.isArray(n.children)?n.children:[n.children],c=null==(o=u.find(e=>e.type===Head))?void 0:null==(i=o.props)?void 0:i.children,d=null==(l=u.find(e=>"body"===e.type))?void 0:null==(s=l.props)?void 0:s.children,p=[...Array.isArray(c)?c:[c],...Array.isArray(d)?d:[d]];r.default.Children.forEach(p,t=>{var n;if(t&&(null==(n=t.type)?void 0:n.__nextScript)){if("beforeInteractive"===t.props.strategy){e.beforeInteractive=(e.beforeInteractive||[]).concat([{...t.props}]);return}if(["lazyOnload","afterInteractive","worker"].includes(t.props.strategy)){a.push(t.props);return}}}),t.scriptLoader=a}let NextScript=class NextScript extends r.default.Component{static #e=this.contextType=a.HtmlContext;getDynamicChunks(e){return getDynamicChunks(this.context,this.props,e)}getPreNextScripts(){return getPreNextScripts(this.context,this.props)}getScripts(e){return getScripts(this.context,this.props,e)}getPolyfillScripts(){return getPolyfillScripts(this.context,this.props)}static getInlineScriptSource(e){let{__NEXT_DATA__:t,largePageDataBytes:r}=e;try{let i=JSON.stringify(t);if(u.has(t.page))return(0,s.htmlEscapeJsonString)(i);let o=Buffer.from(i).byteLength,l=n(5955).Z;return r&&o>r&&(u.add(t.page),console.warn(`Warning: data for page "${t.page}"${t.page===e.dangerousAsPath?"":` (path "${e.dangerousAsPath}")`} is ${l(o)} which exceeds the threshold of ${l(r)}, this amount of data can reduce performance. +See more info here: https://nextjs.org/docs/messages/large-page-data`)),(0,s.htmlEscapeJsonString)(i)}catch(e){if((0,l.default)(e)&&-1!==e.message.indexOf("circular structure"))throw Error(`Circular structure in "getInitialProps" result of page "${t.page}". https://nextjs.org/docs/messages/circular-structure`);throw e}}render(){let{assetPrefix:e,inAmpMode:t,buildManifest:n,unstable_runtimeJS:i,docComponentsRendered:o,assetQueryString:s,disableOptimizedLoading:l,crossOrigin:a}=this.context,u=!1===i;if(o.NextScript=!0,t)return null;let c=getDocumentFiles(this.context.buildManifest,this.context.__NEXT_DATA__.page,t);return r.default.createElement(r.default.Fragment,null,!u&&n.devFiles?n.devFiles.map(t=>r.default.createElement("script",{key:t,src:`${e}/_next/${encodeURI(t)}${s}`,nonce:this.props.nonce,crossOrigin:this.props.crossOrigin||a})):null,u?null:r.default.createElement("script",{id:"__NEXT_DATA__",type:"application/json",nonce:this.props.nonce,crossOrigin:this.props.crossOrigin||a,dangerouslySetInnerHTML:{__html:NextScript.getInlineScriptSource(this.context)}}),l&&!u&&this.getPolyfillScripts(),l&&!u&&this.getPreNextScripts(),l&&!u&&this.getDynamicChunks(c),l&&!u&&this.getScripts(c))}};function Html(e){let{inAmpMode:t,docComponentsRendered:n,locale:i,scriptLoader:o,__NEXT_DATA__:s}=(0,a.useHtmlContext)();return n.Html=!0,handleDocumentScriptLoaderItems(o,s,e),r.default.createElement("html",{...e,lang:e.lang||i||void 0,amp:t?"":void 0,"data-ampdevmode":void 0})}function Main(){let{docComponentsRendered:e}=(0,a.useHtmlContext)();return e.Main=!0,r.default.createElement("next-js-internal-body-render-target",null)}let Document=class Document extends r.default.Component{static getInitialProps(e){return e.defaultGetInitialProps(e)}render(){return r.default.createElement(Html,null,r.default.createElement(Head,null),r.default.createElement("body",null,r.default.createElement(Main,null),r.default.createElement(NextScript,null)))}};Document[i.NEXT_BUILTIN_DOCUMENT]=function(){return r.default.createElement(Html,null,r.default.createElement(Head,null),r.default.createElement("body",null,r.default.createElement(Main,null),r.default.createElement(NextScript,null)))}},4191:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{MODERN_BROWSERSLIST_TARGET:function(){return i.default},COMPILER_NAMES:function(){return o},INTERNAL_HEADERS:function(){return s},COMPILER_INDEXES:function(){return l},PHASE_EXPORT:function(){return a},PHASE_PRODUCTION_BUILD:function(){return u},PHASE_PRODUCTION_SERVER:function(){return c},PHASE_DEVELOPMENT_SERVER:function(){return d},PHASE_TEST:function(){return p},PHASE_INFO:function(){return f},PAGES_MANIFEST:function(){return m},APP_PATHS_MANIFEST:function(){return h},APP_PATH_ROUTES_MANIFEST:function(){return g},BUILD_MANIFEST:function(){return _},APP_BUILD_MANIFEST:function(){return E},FUNCTIONS_CONFIG_MANIFEST:function(){return S},SUBRESOURCE_INTEGRITY_MANIFEST:function(){return y},NEXT_FONT_MANIFEST:function(){return I},EXPORT_MARKER:function(){return P},EXPORT_DETAIL:function(){return T},PRERENDER_MANIFEST:function(){return N},ROUTES_MANIFEST:function(){return O},IMAGES_MANIFEST:function(){return b},SERVER_FILES_MANIFEST:function(){return v},DEV_CLIENT_PAGES_MANIFEST:function(){return A},MIDDLEWARE_MANIFEST:function(){return R},DEV_MIDDLEWARE_MANIFEST:function(){return x},REACT_LOADABLE_MANIFEST:function(){return M},FONT_MANIFEST:function(){return L},SERVER_DIRECTORY:function(){return C},CONFIG_FILES:function(){return D},BUILD_ID_FILE:function(){return j},BLOCKED_PAGES:function(){return F},CLIENT_PUBLIC_FILES_PATH:function(){return k},CLIENT_STATIC_FILES_PATH:function(){return w},STRING_LITERAL_DROP_BUNDLE:function(){return U},NEXT_BUILTIN_DOCUMENT:function(){return H},BARREL_OPTIMIZATION_PREFIX:function(){return B},CLIENT_REFERENCE_MANIFEST:function(){return $},SERVER_REFERENCE_MANIFEST:function(){return W},MIDDLEWARE_BUILD_MANIFEST:function(){return z},MIDDLEWARE_REACT_LOADABLE_MANIFEST:function(){return G},CLIENT_STATIC_FILES_RUNTIME_MAIN:function(){return Y},CLIENT_STATIC_FILES_RUNTIME_MAIN_APP:function(){return X},APP_CLIENT_INTERNALS:function(){return V},CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH:function(){return q},CLIENT_STATIC_FILES_RUNTIME_AMP:function(){return J},CLIENT_STATIC_FILES_RUNTIME_WEBPACK:function(){return K},CLIENT_STATIC_FILES_RUNTIME_POLYFILLS:function(){return Z},CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL:function(){return Q},EDGE_RUNTIME_WEBPACK:function(){return ee},TEMPORARY_REDIRECT_STATUS:function(){return et},PERMANENT_REDIRECT_STATUS:function(){return en},STATIC_PROPS_ID:function(){return er},SERVER_PROPS_ID:function(){return ei},PAGE_SEGMENT_KEY:function(){return eo},GOOGLE_FONT_PROVIDER:function(){return es},OPTIMIZED_FONT_PROVIDERS:function(){return el},DEFAULT_SERIF_FONT:function(){return ea},DEFAULT_SANS_SERIF_FONT:function(){return eu},STATIC_STATUS_PAGES:function(){return ec},TRACE_OUTPUT_VERSION:function(){return ed},TURBO_TRACE_DEFAULT_MEMORY_LIMIT:function(){return ep},RSC_MODULE_TYPES:function(){return ef},EDGE_UNSUPPORTED_NODE_APIS:function(){return em},SYSTEM_ENTRYPOINTS:function(){return eh}});let r=n(167),i=r._(n(7708)),o={client:"client",server:"server",edgeServer:"edge-server"},s=["x-invoke-path","x-invoke-status","x-invoke-error","x-invoke-query","x-middleware-invoke"],l={[o.client]:0,[o.server]:1,[o.edgeServer]:2},a="phase-export",u="phase-production-build",c="phase-production-server",d="phase-development-server",p="phase-test",f="phase-info",m="pages-manifest.json",h="app-paths-manifest.json",g="app-path-routes-manifest.json",_="build-manifest.json",E="app-build-manifest.json",S="functions-config-manifest.json",y="subresource-integrity-manifest",I="next-font-manifest",P="export-marker.json",T="export-detail.json",N="prerender-manifest.json",O="routes-manifest.json",b="images-manifest.json",v="required-server-files.json",A="_devPagesManifest.json",R="middleware-manifest.json",x="_devMiddlewareManifest.json",M="react-loadable-manifest.json",L="font-manifest.json",C="server",D=["next.config.js","next.config.mjs"],j="BUILD_ID",F=["/_document","/_app","/_error"],k="public",w="static",U="__NEXT_DROP_CLIENT_FILE__",H="__NEXT_BUILTIN_DOCUMENT__",B="__barrel_optimize__",$="client-reference-manifest",W="server-reference-manifest",z="middleware-build-manifest",G="middleware-react-loadable-manifest",Y="main",X=""+Y+"-app",V="app-pages-internals",q="react-refresh",J="amp",K="webpack",Z="polyfills",Q=Symbol(Z),ee="edge-runtime-webpack",et=307,en=308,er="__N_SSG",ei="__N_SSP",eo="__PAGE__",es="https://fonts.googleapis.com/",el=[{url:es,preconnect:"https://fonts.gstatic.com"},{url:"https://use.typekit.net",preconnect:"https://use.typekit.net"}],ea={name:"Times New Roman",xAvgCharWidth:821,azAvgWidth:854.3953488372093,unitsPerEm:2048},eu={name:"Arial",xAvgCharWidth:904,azAvgWidth:934.5116279069767,unitsPerEm:2048},ec=["/500"],ed=1,ep=6e3,ef={client:"client",server:"server"},em=["clearImmediate","setImmediate","BroadcastChannel","ByteLengthQueuingStrategy","CompressionStream","CountQueuingStrategy","DecompressionStream","DomException","MessageChannel","MessageEvent","MessagePort","ReadableByteStreamController","ReadableStreamBYOBRequest","ReadableStreamDefaultController","TransformStreamDefaultController","WritableStreamDefaultController"],eh=new Set([Y,q,J,X]);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},972:(e,t)=>{function getObjectClassLabel(e){return Object.prototype.toString.call(e)}function isPlainObject(e){if("[object Object]"!==getObjectClassLabel(e))return!1;let t=Object.getPrototypeOf(e);return null===t||t.hasOwnProperty("isPrototypeOf")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{getObjectClassLabel:function(){return getObjectClassLabel},isPlainObject:function(){return isPlainObject}})},7708:e=>{e.exports=["chrome 64","edge 79","firefox 67","opera 51","safari 12"]},64:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"denormalizePagePath",{enumerable:!0,get:function(){return denormalizePagePath}});let r=n(4676),i=n(9267);function denormalizePagePath(e){let t=(0,i.normalizePathSep)(e);return t.startsWith("/index/")&&!(0,r.isDynamicRoute)(t)?t.slice(6):"/index"!==t?t:"/"}},9341:(e,t)=>{function ensureLeadingSlash(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return ensureLeadingSlash}})},7072:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePagePath",{enumerable:!0,get:function(){return normalizePagePath}});let r=n(9341),i=n(4676),o=n(7921);function normalizePagePath(e){let t=/^\/index(\/|$)/.test(e)&&!(0,i.isDynamicRoute)(e)?"/index"+e:"/"===e?"/index":(0,r.ensureLeadingSlash)(e);{let{posix:e}=n(1017),r=e.normalize(t);if(r!==t)throw new o.NormalizeError("Requested and resolved page mismatch: "+t+" "+r)}return t}},9267:(e,t)=>{function normalizePathSep(e){return e.replace(/\\/g,"/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathSep",{enumerable:!0,get:function(){return normalizePathSep}})},4676:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{getSortedRoutes:function(){return r.getSortedRoutes},isDynamicRoute:function(){return i.isDynamicRoute}});let r=n(5651),i=n(3489)},3489:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isDynamicRoute",{enumerable:!0,get:function(){return isDynamicRoute}});let n=/\/\[[^/]+?\](?=\/|$)/;function isDynamicRoute(e){return n.test(e)}},5651:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSortedRoutes",{enumerable:!0,get:function(){return getSortedRoutes}});let UrlNode=class UrlNode{insert(e){this._insert(e.split("/").filter(Boolean),[],!1)}smoosh(){return this._smoosh()}_smoosh(e){void 0===e&&(e="/");let t=[...this.children.keys()].sort();null!==this.slugName&&t.splice(t.indexOf("[]"),1),null!==this.restSlugName&&t.splice(t.indexOf("[...]"),1),null!==this.optionalRestSlugName&&t.splice(t.indexOf("[[...]]"),1);let n=t.map(t=>this.children.get(t)._smoosh(""+e+t+"/")).reduce((e,t)=>[...e,...t],[]);if(null!==this.slugName&&n.push(...this.children.get("[]")._smoosh(e+"["+this.slugName+"]/")),!this.placeholder){let t="/"===e?"/":e.slice(0,-1);if(null!=this.optionalRestSlugName)throw Error('You cannot define a route with the same specificity as a optional catch-all route ("'+t+'" and "'+t+"[[..."+this.optionalRestSlugName+']]").');n.unshift(t)}return null!==this.restSlugName&&n.push(...this.children.get("[...]")._smoosh(e+"[..."+this.restSlugName+"]/")),null!==this.optionalRestSlugName&&n.push(...this.children.get("[[...]]")._smoosh(e+"[[..."+this.optionalRestSlugName+"]]/")),n}_insert(e,t,n){if(0===e.length){this.placeholder=!1;return}if(n)throw Error("Catch-all must be the last part of the URL.");let r=e[0];if(r.startsWith("[")&&r.endsWith("]")){let i=r.slice(1,-1),o=!1;if(i.startsWith("[")&&i.endsWith("]")&&(i=i.slice(1,-1),o=!0),i.startsWith("...")&&(i=i.substring(3),n=!0),i.startsWith("[")||i.endsWith("]"))throw Error("Segment names may not start or end with extra brackets ('"+i+"').");if(i.startsWith("."))throw Error("Segment names may not start with erroneous periods ('"+i+"').");function handleSlug(e,n){if(null!==e&&e!==n)throw Error("You cannot use different slug names for the same dynamic path ('"+e+"' !== '"+n+"').");t.forEach(e=>{if(e===n)throw Error('You cannot have the same slug name "'+n+'" repeat within a single dynamic path');if(e.replace(/\W/g,"")===r.replace(/\W/g,""))throw Error('You cannot have the slug names "'+e+'" and "'+n+'" differ only by non-word symbols within a single dynamic path')}),t.push(n)}if(n){if(o){if(null!=this.restSlugName)throw Error('You cannot use both an required and optional catch-all route at the same level ("[...'+this.restSlugName+']" and "'+e[0]+'" ).');handleSlug(this.optionalRestSlugName,i),this.optionalRestSlugName=i,r="[[...]]"}else{if(null!=this.optionalRestSlugName)throw Error('You cannot use both an optional and required catch-all route at the same level ("[[...'+this.optionalRestSlugName+']]" and "'+e[0]+'").');handleSlug(this.restSlugName,i),this.restSlugName=i,r="[...]"}}else{if(o)throw Error('Optional route parameters are not yet supported ("'+e[0]+'").');handleSlug(this.slugName,i),this.slugName=i,r="[]"}}this.children.has(r)||this.children.set(r,new UrlNode),this.children.get(r)._insert(e.slice(1),t,n)}constructor(){this.placeholder=!0,this.children=new Map,this.slugName=null,this.restSlugName=null,this.optionalRestSlugName=null}};function getSortedRoutes(e){let t=new UrlNode;return e.forEach(e=>t.insert(e)),t.smoosh()}},676:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{default:function(){return isError},getProperError:function(){return getProperError}});let r=n(972);function isError(e){return"object"==typeof e&&null!==e&&"name"in e&&"message"in e}function getProperError(e){return isError(e)?e:Error((0,r.isPlainObject)(e)?JSON.stringify(e):e+"")}},5955:(e,t)=>{Object.defineProperty(t,"Z",{enumerable:!0,get:function(){return prettyBytes}});let n=["B","kB","MB","GB","TB","PB","EB","ZB","YB"],toLocaleString=(e,t)=>{let n=e;return"string"==typeof t?n=e.toLocaleString(t):!0===t&&(n=e.toLocaleString()),n};function prettyBytes(e,t){if(!Number.isFinite(e))throw TypeError(`Expected a finite number, got ${typeof e}: ${e}`);if((t=Object.assign({},t)).signed&&0===e)return" 0 B";let r=e<0,i=r?"-":t.signed?"+":"";if(r&&(e=-e),e<1){let n=toLocaleString(e,t.locale);return i+n+" B"}let o=Math.min(Math.floor(Math.log10(e)/3),n.length-1);e=Number((e/Math.pow(1e3,o)).toPrecision(3));let s=toLocaleString(e,t.locale),l=n[o];return i+s+" "+l}},7093:(e,t,n)=>{e.exports=n(2785)},3112:(e,t,n)=>{e.exports=n(7093).vendored.contexts.HtmlContext},5778:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getPageFiles",{enumerable:!0,get:function(){return getPageFiles}});let r=n(64),i=n(7072);function getPageFiles(e,t){let n=(0,r.denormalizePagePath)((0,i.normalizePagePath)(t));return e.pages[n]||(console.warn(`Could not find files for ${n} in .next/build-manifest.json`),[])}},9630:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ESCAPE_REGEX:function(){return r},htmlEscapeJsonString:function(){return htmlEscapeJsonString}});let n={"&":"\\u0026",">":"\\u003e","<":"\\u003c","\u2028":"\\u2028","\u2029":"\\u2029"},r=/[&><\u2028\u2029]/g;function htmlEscapeJsonString(e){return e.replace(r,e=>n[e])}},733:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{isBlockedPage:function(){return isBlockedPage},cleanAmpPath:function(){return cleanAmpPath},debounce:function(){return debounce}});let r=n(4191);function isBlockedPage(e){return r.BLOCKED_PAGES.includes(e)}function cleanAmpPath(e){return e.match(/\?amp=(y|yes|true|1)/)&&(e=e.replace(/\?amp=(y|yes|true|1)&?/,"?")),e.match(/&=(y|yes|true|1)/)&&(e=e.replace(/&=(y|yes|true|1)/,"")),e=e.replace(/\?$/,"")}function debounce(e,t,n=1/0){let r,i,o;let s=0,l=0;function run(){let a=Date.now(),u=l+t-a;u<=0||s+n>=a?(r=void 0,e.apply(o,i)):r=setTimeout(run,u)}return function(...e){i=e,o=this,l=Date.now(),void 0===r&&(s=l,r=setTimeout(run,t))}}}}; \ No newline at end of file diff --git a/.next/server/chunks/816.js b/.next/server/chunks/816.js deleted file mode 100644 index 316b2fa..0000000 --- a/.next/server/chunks/816.js +++ /dev/null @@ -1,90 +0,0 @@ -exports.id = 816; -exports.ids = [816]; -exports.modules = { - -/***/ 7023: -/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { - -Promise.resolve(/* import() eager */).then(__webpack_require__.t.bind(__webpack_require__, 125, 23)); -Promise.resolve(/* import() eager */).then(__webpack_require__.t.bind(__webpack_require__, 6249, 23)); -Promise.resolve(/* import() eager */).then(__webpack_require__.t.bind(__webpack_require__, 7844, 23)); -Promise.resolve(/* import() eager */).then(__webpack_require__.t.bind(__webpack_require__, 1522, 23)); -Promise.resolve(/* import() eager */).then(__webpack_require__.t.bind(__webpack_require__, 3100, 23)) - -/***/ }), - -/***/ 6141: -/***/ (() => { - - - -/***/ }), - -/***/ 729: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ RootLayout), -/* harmony export */ "metadata": () => (/* binding */ metadata) -/* harmony export */ }); -/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6786); -/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var next_font_google_target_css_path_app_layout_tsx_import_Inter_arguments_subsets_latin_variableName_inter___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(160); -/* harmony import */ var next_font_google_target_css_path_app_layout_tsx_import_Inter_arguments_subsets_latin_variableName_inter___WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(next_font_google_target_css_path_app_layout_tsx_import_Inter_arguments_subsets_latin_variableName_inter___WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _globals_scss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3096); -/* harmony import */ var _globals_scss__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_globals_scss__WEBPACK_IMPORTED_MODULE_1__); - - - -const metadata = { - title: "sukadia.dev", - description: "I code, stream, and create videos." -}; -function RootLayout({ children }) { - return /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("html", { - lang: "en", - children: /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("body", { - className: (next_font_google_target_css_path_app_layout_tsx_import_Inter_arguments_subsets_latin_variableName_inter___WEBPACK_IMPORTED_MODULE_2___default().className), - children: children - }) - }); -} - - -/***/ }), - -/***/ 4756: -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var next_dist_lib_metadata_get_metadata_route__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3180); -/* harmony import */ var next_dist_lib_metadata_get_metadata_route__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(next_dist_lib_metadata_get_metadata_route__WEBPACK_IMPORTED_MODULE_0__); - - - /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((props) => { - const imageData = {"type":"image/x-icon","sizes":"any"} - const imageUrl = (0,next_dist_lib_metadata_get_metadata_route__WEBPACK_IMPORTED_MODULE_0__.fillMetadataSegment)(".", props.params, "favicon.ico") - - return [{ - ...imageData, - url: imageUrl + "", - }] - }); - -/***/ }), - -/***/ 3096: -/***/ (() => { - - - -/***/ }) - -}; -; \ No newline at end of file diff --git a/.next/server/chunks/837.js b/.next/server/chunks/837.js new file mode 100644 index 0000000..ed48f14 --- /dev/null +++ b/.next/server/chunks/837.js @@ -0,0 +1 @@ +exports.id=837,exports.ids=[837],exports.modules={6686:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Image",{enumerable:!0,get:function(){return m}});let n=r(85),i=r(8425),o=i._(r(9885)),a=n._(r(8908)),l=n._(r(6420)),s=r(5161),u=r(1412),d=r(7927);r(8601);let c=r(713),f=n._(r(8320)),p={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1};function handleLoading(e,t,r,n,i,o){let a=null==e?void 0:e.src;if(!e||e["data-loaded-src"]===a)return;e["data-loaded-src"]=a;let l="decode"in e?e.decode():Promise.resolve();l.catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("empty"!==t&&i(!0),null==r?void 0:r.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let n=!1,i=!1;r.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>n,isPropagationStopped:()=>i,persist:()=>{},preventDefault:()=>{n=!0,t.preventDefault()},stopPropagation:()=>{i=!0,t.stopPropagation()}})}(null==n?void 0:n.current)&&n.current(e)}})}function getDynamicProps(e){let[t,r]=o.version.split(".",2),n=parseInt(t,10),i=parseInt(r,10);return n>18||18===n&&i>=3?{fetchPriority:e}:{fetchpriority:e}}globalThis.__NEXT_IMAGE_IMPORTED=!0;let g=(0,o.forwardRef)((e,t)=>{let{src:r,srcSet:n,sizes:i,height:a,width:l,decoding:s,className:u,style:d,fetchPriority:c,placeholder:f,loading:p,unoptimized:g,fill:m,onLoadRef:h,onLoadingCompleteRef:y,setBlurComplete:v,setShowAltText:b,onLoad:_,onError:S,...w}=e;return o.default.createElement("img",{...w,...getDynamicProps(c),loading:p,width:l,height:a,decoding:s,"data-nimg":m?"fill":"1",className:u,style:d,sizes:i,srcSet:n,src:r,ref:(0,o.useCallback)(e=>{t&&("function"==typeof t?t(e):"object"==typeof t&&(t.current=e)),e&&(S&&(e.src=e.src),e.complete&&handleLoading(e,f,h,y,v,g))},[r,f,h,y,v,S,g,t]),onLoad:e=>{let t=e.currentTarget;handleLoading(t,f,h,y,v,g)},onError:e=>{b(!0),"empty"!==f&&v(!0),S&&S(e)}})});function ImagePreload(e){let{isAppRouter:t,imgAttributes:r}=e,n={as:"image",imageSrcSet:r.srcSet,imageSizes:r.sizes,crossOrigin:r.crossOrigin,referrerPolicy:r.referrerPolicy,...getDynamicProps(r.fetchPriority)};return t&&a.default.preload?(a.default.preload(r.src,n),null):o.default.createElement(l.default,null,o.default.createElement("link",{key:"__nimg-"+r.src+r.srcSet+r.sizes,rel:"preload",href:r.srcSet?void 0:r.src,...n}))}let m=(0,o.forwardRef)((e,t)=>{let r=(0,o.useContext)(c.RouterContext),n=(0,o.useContext)(d.ImageConfigContext),i=(0,o.useMemo)(()=>{let e=p||n||u.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),r=e.deviceSizes.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:r}},[n]),{onLoad:a,onLoadingComplete:l}=e,m=(0,o.useRef)(a);(0,o.useEffect)(()=>{m.current=a},[a]);let h=(0,o.useRef)(l);(0,o.useEffect)(()=>{h.current=l},[l]);let[y,v]=(0,o.useState)(!1),[b,_]=(0,o.useState)(!1),{props:S,meta:w}=(0,s.getImgProps)(e,{defaultLoader:f.default,imgConf:i,blurComplete:y,showAltText:b});return o.default.createElement(o.default.Fragment,null,o.default.createElement(g,{...S,unoptimized:w.unoptimized,placeholder:w.placeholder,fill:w.fill,onLoadRef:m,onLoadingCompleteRef:h,setBlurComplete:v,setShowAltText:_,ref:t}),w.priority?o.default.createElement(ImagePreload,{isAppRouter:!r,imgAttributes:S}):null)});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1281:(e,t)=>{"use strict";function isInAmpMode(e){let{ampFirst:t=!1,hybrid:r=!1,hasQuery:n=!1}=void 0===e?{}:e;return t||r&&n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return isInAmpMode}})},5161:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImgProps",{enumerable:!0,get:function(){return getImgProps}}),r(8601);let n=r(2490),i=r(1412);function isStaticRequire(e){return void 0!==e.default}function isStaticImageData(e){return void 0!==e.src}function isStaticImport(e){return"object"==typeof e&&(isStaticRequire(e)||isStaticImageData(e))}function getInt(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function getWidths(e,t,r){let{deviceSizes:n,allSizes:i}=e;if(r){let e=/(^|\s)(1?\d?\d)vw/g,t=[];for(let n;n=e.exec(r);n)t.push(parseInt(n[2]));if(t.length){let e=.01*Math.min(...t);return{widths:i.filter(t=>t>=n[0]*e),kind:"w"}}return{widths:i,kind:"w"}}if("number"!=typeof t)return{widths:n,kind:"w"};let o=[...new Set([t,2*t].map(e=>i.find(t=>t>=e)||i[i.length-1]))];return{widths:o,kind:"x"}}function generateImgAttrs(e){let{config:t,src:r,unoptimized:n,width:i,quality:o,sizes:a,loader:l}=e;if(n)return{src:r,srcSet:void 0,sizes:void 0};let{widths:s,kind:u}=getWidths(t,i,a),d=s.length-1;return{sizes:a||"w"!==u?a:"100vw",srcSet:s.map((e,n)=>l({config:t,src:r,quality:o,width:e})+" "+("w"===u?e:n+1)+u).join(", "),src:l({config:t,src:r,quality:o,width:s[d]})}}function getImgProps(e,t){let r,o,a,{src:l,sizes:s,unoptimized:u=!1,priority:d=!1,loading:c,className:f,quality:p,width:g,height:m,fill:h=!1,style:y,onLoad:v,onLoadingComplete:b,placeholder:_="empty",blurDataURL:S,fetchPriority:w,layout:C,objectFit:x,objectPosition:P,lazyBoundary:I,lazyRoot:E,...O}=e,{imgConf:j,showAltText:M,blurComplete:z,defaultLoader:R}=t,A=j||i.imageConfigDefault;if("allSizes"in A)r=A;else{let e=[...A.deviceSizes,...A.imageSizes].sort((e,t)=>e-t),t=A.deviceSizes.sort((e,t)=>e-t);r={...A,allSizes:e,deviceSizes:t}}let k=O.loader||R;delete O.loader,delete O.srcSet;let D="__next_img_default"in k;if(D){if("custom"===r.loader)throw Error('Image with src "'+l+'" is missing "loader" prop.\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader')}else{let e=k;k=t=>{let{config:r,...n}=t;return e(n)}}if(C){"fill"===C&&(h=!0);let e={intrinsic:{maxWidth:"100%",height:"auto"},responsive:{width:"100%",height:"auto"}}[C];e&&(y={...y,...e});let t={responsive:"100vw",fill:"100vw"}[C];t&&!s&&(s=t)}let L="",U=getInt(g),B=getInt(m);if(isStaticImport(l)){let e=isStaticRequire(l)?l.default:l;if(!e.src)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received "+JSON.stringify(e));if(!e.height||!e.width)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received "+JSON.stringify(e));if(o=e.blurWidth,a=e.blurHeight,S=S||e.blurDataURL,L=e.src,!h){if(U||B){if(U&&!B){let t=U/e.width;B=Math.round(e.height*t)}else if(!U&&B){let t=B/e.height;U=Math.round(e.width*t)}}else U=e.width,B=e.height}}let H=!d&&("lazy"===c||void 0===c);(!(l="string"==typeof l?l:L)||l.startsWith("data:")||l.startsWith("blob:"))&&(u=!0,H=!1),r.unoptimized&&(u=!0),D&&l.endsWith(".svg")&&!r.dangerouslyAllowSVG&&(u=!0),d&&(w="high");let T=getInt(p),G=Object.assign(h?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:x,objectPosition:P}:{},M?{}:{color:"transparent"},y),N=z||"empty"===_?null:"blur"===_?'url("data:image/svg+xml;charset=utf-8,'+(0,n.getImageBlurSvg)({widthInt:U,heightInt:B,blurWidth:o,blurHeight:a,blurDataURL:S||"",objectFit:G.objectFit})+'")':'url("'+_+'")',W=N?{backgroundSize:G.objectFit||"cover",backgroundPosition:G.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:N}:{},q=generateImgAttrs({config:r,src:l,unoptimized:u,width:U,quality:T,sizes:s,loader:k}),F={...O,loading:H?"lazy":c,fetchPriority:w,width:U,height:B,decoding:"async",className:f,style:{...G,...W},sizes:q.sizes,srcSet:q.srcSet,src:q.src},V={unoptimized:u,priority:d,placeholder:_,fill:h};return{props:F,meta:V}}},6420:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{defaultHead:function(){return defaultHead},default:function(){return c}});let n=r(85),i=r(8425),o=i._(r(9885)),a=n._(r(4005)),l=r(8364),s=r(5851),u=r(1281);function defaultHead(e){void 0===e&&(e=!1);let t=[o.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(o.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function onlyReactElement(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===o.default.Fragment?e.concat(o.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}r(8601);let d=["name","httpEquiv","charSet","itemProp"];function unique(){let e=new Set,t=new Set,r=new Set,n={};return i=>{let o=!0,a=!1;if(i.key&&"number"!=typeof i.key&&i.key.indexOf("$")>0){a=!0;let t=i.key.slice(i.key.indexOf("$")+1);e.has(t)?o=!1:e.add(t)}switch(i.type){case"title":case"base":t.has(i.type)?o=!1:t.add(i.type);break;case"meta":for(let e=0,t=d.length;e<t;e++){let t=d[e];if(i.props.hasOwnProperty(t)){if("charSet"===t)r.has(t)?o=!1:r.add(t);else{let e=i.props[t],r=n[t]||new Set;("name"!==t||!a)&&r.has(e)?o=!1:(r.add(e),n[t]=r)}}}}return o}}function reduceComponents(e,t){let{inAmpMode:r}=t;return e.reduce(onlyReactElement,[]).reverse().concat(defaultHead(r).reverse()).filter(unique()).reverse().map((e,t)=>{let n=e.key||t;if(!r&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,o.default.cloneElement(e,t)}return o.default.cloneElement(e,{key:n})})}function Head(e){let{children:t}=e,r=(0,o.useContext)(l.AmpStateContext),n=(0,o.useContext)(s.HeadManagerContext);return o.default.createElement(a.default,{reduceComponentsToState:reduceComponents,headManager:n,inAmpMode:(0,u.isInAmpMode)(r)},t)}let c=Head;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2490:(e,t)=>{"use strict";function getImageBlurSvg(e){let{widthInt:t,heightInt:r,blurWidth:n,blurHeight:i,blurDataURL:o,objectFit:a}=e,l=n?40*n:t,s=i?40*i:r,u=l&&s?"viewBox='0 0 "+l+" "+s+"'":"";return"%3Csvg xmlns='http://www.w3.org/2000/svg' "+u+"%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='"+(u?"none":"contain"===a?"xMidYMid":"cover"===a?"xMidYMid slice":"none")+"' style='filter: url(%23b);' href='"+o+"'/%3E%3C/svg%3E"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImageBlurSvg",{enumerable:!0,get:function(){return getImageBlurSvg}})},1412:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{VALID_LOADERS:function(){return r},imageConfigDefault:function(){return n}});let r=["default","imgix","cloudinary","akamai","custom"],n={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"inline",remotePatterns:[],unoptimized:!1}},7990:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{unstable_getImgProps:function(){return unstable_getImgProps},default:function(){return s}});let n=r(85),i=r(5161),o=r(8601),a=r(6686),l=n._(r(8320)),unstable_getImgProps=e=>{(0,o.warnOnce)("Warning: unstable_getImgProps() is experimental and may change or be removed at any time. Use at your own risk.");let{props:t}=(0,i.getImgProps)(e,{defaultLoader:l.default,imgConf:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1}});for(let[e,r]of Object.entries(t))void 0===r&&delete t[e];return{props:t}},s=a.Image},8320:(e,t)=>{"use strict";function defaultLoader(e){let{config:t,src:r,width:n,quality:i}=e;return t.path+"?url="+encodeURIComponent(r)+"&w="+n+"&q="+(i||75)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r}}),defaultLoader.__next_img_default=!0;let r=defaultLoader},4005:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return SideEffect}});let n=r(9885),useClientOnlyLayoutEffect=()=>{},useClientOnlyEffect=()=>{};function SideEffect(e){var t;let{headManager:r,reduceComponentsToState:i}=e;function emitChange(){if(r&&r.mountedInstances){let t=n.Children.toArray(Array.from(r.mountedInstances).filter(Boolean));r.updateHead(i(t,e))}}return null==r||null==(t=r.mountedInstances)||t.add(e.children),emitChange(),useClientOnlyLayoutEffect(()=>{var t;return null==r||null==(t=r.mountedInstances)||t.add(e.children),()=>{var t;null==r||null==(t=r.mountedInstances)||t.delete(e.children)}}),useClientOnlyLayoutEffect(()=>(r&&(r._pendingUpdate=emitChange),()=>{r&&(r._pendingUpdate=emitChange)})),useClientOnlyEffect(()=>(r&&r._pendingUpdate&&(r._pendingUpdate(),r._pendingUpdate=null),()=>{r&&r._pendingUpdate&&(r._pendingUpdate(),r._pendingUpdate=null)})),null}},8601:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return warnOnce}});let warnOnce=e=>{}},8364:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.AmpContext},5851:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.HeadManagerContext},7927:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.ImageConfigContext},713:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.RouterContext},784:(e,t,r)=>{"use strict";e.exports=r(316).vendored["react-ssr"].ReactJsxRuntime},2451:(e,t,r)=>{e.exports=r(7990)}}; \ No newline at end of file diff --git a/.next/server/chunks/840.js b/.next/server/chunks/840.js new file mode 100644 index 0000000..b33fb27 --- /dev/null +++ b/.next/server/chunks/840.js @@ -0,0 +1 @@ +"use strict";exports.id=840,exports.ids=[840],exports.modules={2840:(e,t,p)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return App}});let l=p(167),a=l._(p(6689)),o=p(7921);async function appGetInitialProps(e){let{Component:t,ctx:p}=e,l=await (0,o.loadGetInitialProps)(t,p);return{pageProps:l}}let App=class App extends a.default.Component{render(){let{Component:e,pageProps:t}=this.props;return a.default.createElement(e,t)}};App.origGetInitialProps=appGetInitialProps,App.getInitialProps=appGetInitialProps,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)}}; \ No newline at end of file diff --git a/.next/server/chunks/862.js b/.next/server/chunks/862.js new file mode 100644 index 0000000..3dfc942 --- /dev/null +++ b/.next/server/chunks/862.js @@ -0,0 +1 @@ +exports.id=862,exports.ids=[862],exports.modules={2999:e=>{e.exports={style:{fontFamily:"'__Inter_e66fe9', '__Inter_Fallback_e66fe9'",fontStyle:"normal"},className:"__className_e66fe9"}},6879:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addBasePath",{enumerable:!0,get:function(){return addBasePath}});let n=r(8549),a=r(6945);function addBasePath(e,t){return(0,a.normalizePathTrailingSlash)((0,n.addPathPrefix)(e,""))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5422:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"callServer",{enumerable:!0,get:function(){return callServer}});let n=r(3724);async function callServer(e,t){let r=(0,n.getServerActionDispatcher)();if(!r)throw Error("Invariant: missing action dispatcher.");return new Promise((n,a)=>{r({actionId:e,actionArgs:t,resolve:n,reject:a})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3204:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AppRouterAnnouncer",{enumerable:!0,get:function(){return AppRouterAnnouncer}});let n=r(9885),a=r(8908),o="next-route-announcer";function getAnnouncerNode(){var e;let t=document.getElementsByName(o)[0];if(null==t?void 0:null==(e=t.shadowRoot)?void 0:e.childNodes[0])return t.shadowRoot.childNodes[0];{let e=document.createElement(o);e.style.cssText="position:absolute";let t=document.createElement("div");t.ariaLive="assertive",t.id="__next-route-announcer__",t.role="alert",t.style.cssText="position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal";let r=e.attachShadow({mode:"open"});return r.appendChild(t),document.body.appendChild(e),t}}function AppRouterAnnouncer(e){let{tree:t}=e,[r,l]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=getAnnouncerNode();return l(e),()=>{let e=document.getElementsByTagName(o)[0];(null==e?void 0:e.isConnected)&&document.body.removeChild(e)}},[]);let[u,i]=(0,n.useState)(""),s=(0,n.useRef)();return(0,n.useEffect)(()=>{let e="";if(document.title)e=document.title;else{let t=document.querySelector("h1");t&&(e=t.innerText||t.textContent||"")}void 0!==s.current&&s.current!==e&&i(e),s.current=e},[t]),r?(0,a.createPortal)(u,r):null}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4361:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RSC:function(){return r},ACTION:function(){return n},NEXT_ROUTER_STATE_TREE:function(){return a},NEXT_ROUTER_PREFETCH:function(){return o},NEXT_URL:function(){return l},RSC_CONTENT_TYPE_HEADER:function(){return u},RSC_VARY_HEADER:function(){return i},FLIGHT_PARAMETERS:function(){return s},NEXT_RSC_UNION_QUERY:function(){return c}});let r="RSC",n="Next-Action",a="Next-Router-State-Tree",o="Next-Router-Prefetch",l="Next-Url",u="text/x-component",i=r+", "+a+", "+o+", "+l,s=[[r],[a],[o]],c="_rsc";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3724:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getServerActionDispatcher:function(){return getServerActionDispatcher},urlToUrlWithoutFlightMarker:function(){return urlToUrlWithoutFlightMarker},default:function(){return AppRouter}});let n=r(8425),a=n._(r(9885)),o=r(2428),l=r(7986),u=r(3678),i=r(1706),s=r(1736),c=r(9236),d=r(5365),f=r(9624),p=r(4692),h=r(6879),_=r(3204),y=r(7502),m=r(2226),g=r(9880),b=r(4361),v=r(4978),P=r(9760),R=null,S=null;function getServerActionDispatcher(){return S}let E={refresh:()=>{}};function urlToUrlWithoutFlightMarker(e){let t=new URL(e,location.origin);return t.searchParams.delete(b.NEXT_RSC_UNION_QUERY),t}function isExternalURL(e){return e.origin!==window.location.origin}function HistoryUpdater(e){let{tree:t,pushRef:r,canonicalUrl:n,sync:o}=e;return(0,a.useInsertionEffect)(()=>{let e={__NA:!0,tree:t};r.pendingPush&&(0,i.createHrefFromUrl)(new URL(window.location.href))!==n?(r.pendingPush=!1,window.history.pushState(e,"",n)):window.history.replaceState(e,"",n),o()},[t,r,n,o]),null}let createEmptyCacheNode=()=>({status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map});function useServerActionDispatcher(e){let t=(0,a.useCallback)(t=>{(0,a.startTransition)(()=>{e({...t,type:u.ACTION_SERVER_ACTION,mutable:{globalMutable:E},cache:createEmptyCacheNode()})})},[e]);S=t}function useChangeByServerResponse(e){return(0,a.useCallback)((t,r,n)=>{(0,a.startTransition)(()=>{e({type:u.ACTION_SERVER_PATCH,flightData:r,previousTree:t,overrideCanonicalUrl:n,cache:createEmptyCacheNode(),mutable:{globalMutable:E}})})},[e])}function useNavigate(e){return(0,a.useCallback)((t,r,n,a)=>{let o=new URL((0,h.addBasePath)(t),location.href);return E.pendingNavigatePath=(0,i.createHrefFromUrl)(o),e({type:u.ACTION_NAVIGATE,url:o,isExternalUrl:isExternalURL(o),locationSearch:location.search,forceOptimisticNavigation:n,shouldScroll:null==a||a,navigateType:r,cache:createEmptyCacheNode(),mutable:{globalMutable:E}})},[e])}function Router(e){let{buildId:t,initialHead:r,initialTree:n,initialCanonicalUrl:i,children:d,assetPrefix:b}=e,S=(0,a.useMemo)(()=>(0,f.createInitialRouterState)({buildId:t,children:d,initialCanonicalUrl:i,initialTree:n,initialParallelRoutes:R,isServer:!0,location:null,initialHead:r}),[t,d,i,n,r]),[{tree:O,cache:T,prefetchCache:j,pushRef:M,focusAndScrollRef:x,canonicalUrl:A,nextUrl:C},N,w]=(0,c.useReducerWithReduxDevtools)(l.reducer,S);(0,a.useEffect)(()=>{R=null},[]);let{searchParams:I,pathname:F}=(0,a.useMemo)(()=>{let e=new URL(A,"http://n");return{searchParams:e.searchParams,pathname:(0,P.hasBasePath)(e.pathname)?(0,v.removeBasePath)(e.pathname):e.pathname}},[A]),D=useChangeByServerResponse(N),L=useNavigate(N);useServerActionDispatcher(N);let U=(0,a.useMemo)(()=>{let e={back:()=>window.history.back(),forward:()=>window.history.forward(),prefetch:(e,t)=>{if((0,p.isBot)(window.navigator.userAgent))return;let r=new URL((0,h.addBasePath)(e),location.href);isExternalURL(r)||(0,a.startTransition)(()=>{var e;N({type:u.ACTION_PREFETCH,url:r,kind:null!=(e=null==t?void 0:t.kind)?e:u.PrefetchKind.FULL})})},replace:(e,t)=>{void 0===t&&(t={}),(0,a.startTransition)(()=>{var r;L(e,"replace",!!t.forceOptimisticNavigation,null==(r=t.scroll)||r)})},push:(e,t)=>{void 0===t&&(t={}),(0,a.startTransition)(()=>{var r;L(e,"push",!!t.forceOptimisticNavigation,null==(r=t.scroll)||r)})},refresh:()=>{(0,a.startTransition)(()=>{N({type:u.ACTION_REFRESH,cache:createEmptyCacheNode(),mutable:{globalMutable:E},origin:window.location.origin})})},fastRefresh:()=>{throw Error("fastRefresh can only be used in development mode. Please use refresh instead.")}};return e},[N,L]);if((0,a.useEffect)(()=>{window.next&&(window.next.router=U)},[U]),(0,a.useEffect)(()=>{E.refresh=U.refresh},[U.refresh]),(0,a.useEffect)(()=>{function handlePageShow(e){var t;e.persisted&&(null==(t=window.history.state)?void 0:t.tree)&&N({type:u.ACTION_RESTORE,url:new URL(window.location.href),tree:window.history.state.tree})}return window.addEventListener("pageshow",handlePageShow),()=>{window.removeEventListener("pageshow",handlePageShow)}},[N]),M.mpaNavigation){if(E.pendingMpaPath!==A){let e=window.location;M.pendingPush?e.assign(A):e.replace(A),E.pendingMpaPath=A}(0,a.use)((0,g.createInfinitePromise)())}let H=(0,a.useCallback)(e=>{let{state:t}=e;if(t){if(!t.__NA){window.location.reload();return}(0,a.startTransition)(()=>{N({type:u.ACTION_RESTORE,url:new URL(window.location.href),tree:t.tree})})}},[N]);(0,a.useEffect)(()=>(window.addEventListener("popstate",H),()=>{window.removeEventListener("popstate",H)}),[H]);let B=(0,a.useMemo)(()=>(0,m.findHeadInCache)(T,O[1]),[T,O]),k=a.default.createElement(y.RedirectBoundary,null,B,T.subTreeData,a.default.createElement(_.AppRouterAnnouncer,{tree:O}));return a.default.createElement(a.default.Fragment,null,a.default.createElement(HistoryUpdater,{tree:O,pushRef:M,canonicalUrl:A,sync:w}),a.default.createElement(s.PathnameContext.Provider,{value:F},a.default.createElement(s.SearchParamsContext.Provider,{value:I},a.default.createElement(o.GlobalLayoutRouterContext.Provider,{value:{buildId:t,changeByServerResponse:D,tree:O,focusAndScrollRef:x,nextUrl:C}},a.default.createElement(o.AppRouterContext.Provider,{value:U},a.default.createElement(o.LayoutRouterContext.Provider,{value:{childNodes:T.parallelRoutes,tree:O,url:A}},k))))))}function AppRouter(e){let{globalErrorComponent:t,...r}=e;return a.default.createElement(d.ErrorBoundary,{errorComponent:t},a.default.createElement(Router,r))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4954:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"bailoutToClientRendering",{enumerable:!0,get:function(){return bailoutToClientRendering}});let n=r(1118),a=r(4749);function bailoutToClientRendering(){let e=a.staticGenerationAsyncStorage.getStore();return null!=e&&!!e.forceStatic||((null==e?void 0:e.isStaticGeneration)&&(0,n.throwWithNoSSR)(),!1)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3402:(e,t,r)=>{"use strict";function clientHookInServerComponentError(e){}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"clientHookInServerComponentError",{enumerable:!0,get:function(){return clientHookInServerComponentError}}),r(85),r(9885),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5365:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ErrorBoundaryHandler:function(){return ErrorBoundaryHandler},GlobalError:function(){return GlobalError},default:function(){return u},ErrorBoundary:function(){return ErrorBoundary}});let n=r(85),a=n._(r(9885)),o=r(4979),l={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},text:{fontSize:"14px",fontWeight:400,lineHeight:"28px",margin:"0 8px"}};function HandleISRError(e){let{error:t}=e;if("function"==typeof fetch.__nextGetStaticStore){var r;let e=null==(r=fetch.__nextGetStaticStore())?void 0:r.getStore();if((null==e?void 0:e.isRevalidate)||(null==e?void 0:e.isStaticGeneration))throw console.error(t),t}return null}let ErrorBoundaryHandler=class ErrorBoundaryHandler extends a.default.Component{static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.error?{error:null,previousPathname:e.pathname}:{error:t.error,previousPathname:e.pathname}}render(){return this.state.error?a.default.createElement(a.default.Fragment,null,a.default.createElement(HandleISRError,{error:this.state.error}),this.props.errorStyles,this.props.errorScripts,a.default.createElement(this.props.errorComponent,{error:this.state.error,reset:this.reset})):this.props.children}constructor(e){super(e),this.reset=()=>{this.setState({error:null})},this.state={error:null,previousPathname:this.props.pathname}}};function GlobalError(e){let{error:t}=e,r=null==t?void 0:t.digest;return a.default.createElement("html",{id:"__next_error__"},a.default.createElement("head",null),a.default.createElement("body",null,a.default.createElement(HandleISRError,{error:t}),a.default.createElement("div",{style:l.error},a.default.createElement("div",null,a.default.createElement("h2",{style:l.text},"Application error: a "+(r?"server":"client")+"-side exception has occurred (see the "+(r?"server logs":"browser console")+" for more information)."),r?a.default.createElement("p",{style:l.text},"Digest: "+r):null))))}let u=GlobalError;function ErrorBoundary(e){let{errorComponent:t,errorStyles:r,errorScripts:n,children:l}=e,u=(0,o.usePathname)();return t?a.default.createElement(ErrorBoundaryHandler,{pathname:u,errorComponent:t,errorStyles:r,errorScripts:n},l):a.default.createElement(a.default.Fragment,null,l)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5171:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DYNAMIC_ERROR_CODE:function(){return r},DynamicServerError:function(){return DynamicServerError}});let r="DYNAMIC_SERVER_USAGE";let DynamicServerError=class DynamicServerError extends Error{constructor(e){super("Dynamic server usage: "+e),this.digest=r}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9880:(e,t)=>{"use strict";let r;function createInfinitePromise(){return r||(r=new Promise(()=>{})),r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInfinitePromise",{enumerable:!0,get:function(){return createInfinitePromise}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4900:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return OuterLayoutRouter}}),r(85);let n=r(8425),a=n._(r(9885));r(8908);let o=r(2428),l=r(9102),u=r(9880),i=r(5365),s=r(4538),c=r(4448),d=r(7502),f=r(4714),p=r(1275),h=r(4701),_=r(8026);function walkAddRefetch(e,t){if(e){let[r,n]=e,a=2===e.length;if((0,s.matchSegment)(t[0],r)&&t[1].hasOwnProperty(n)){if(a){let e=walkAddRefetch(void 0,t[1][n]);return[t[0],{...t[1],[n]:[e[0],e[1],e[2],"refetch"]}]}return[t[0],{...t[1],[n]:walkAddRefetch(e.slice(2),t[1][n])}]}}return t}function findDOMNode(e){return null}let y=["bottom","height","left","right","top","width","x","y"];function shouldSkipElement(e){if(["sticky","fixed"].includes(getComputedStyle(e).position))return!0;let t=e.getBoundingClientRect();return y.every(e=>0===t[e])}function topOfElementInViewport(e,t){let r=e.getBoundingClientRect();return r.top>=0&&r.top<=t}function getHashFragmentDomNode(e){var t;return"top"===e?document.body:null!=(t=document.getElementById(e))?t:document.getElementsByName(e)[0]}let InnerScrollAndFocusHandler=class InnerScrollAndFocusHandler extends a.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...e){super(...e),this.handlePotentialScroll=()=>{let{focusAndScrollRef:e,segmentPath:t}=this.props;if(e.apply){if(0!==e.segmentPaths.length&&!e.segmentPaths.some(e=>t.every((t,r)=>(0,s.matchSegment)(t,e[r]))))return;let r=null,n=e.hashFragment;if(n&&(r=getHashFragmentDomNode(n)),r||(r=findDOMNode(this)),!(r instanceof Element))return;for(;!(r instanceof HTMLElement)||shouldSkipElement(r);){if(null===r.nextElementSibling)return;r=r.nextElementSibling}e.apply=!1,e.hashFragment=null,e.segmentPaths=[],(0,c.handleSmoothScroll)(()=>{if(n){r.scrollIntoView();return}let e=document.documentElement,t=e.clientHeight;!topOfElementInViewport(r,t)&&(e.scrollTop=0,topOfElementInViewport(r,t)||r.scrollIntoView())},{dontForceLayout:!0,onlyHashChange:e.onlyHashChange}),e.onlyHashChange=!1,r.focus()}}}};function ScrollAndFocusHandler(e){let{segmentPath:t,children:r}=e,n=(0,a.useContext)(o.GlobalLayoutRouterContext);if(!n)throw Error("invariant global layout router not mounted");return a.default.createElement(InnerScrollAndFocusHandler,{segmentPath:t,focusAndScrollRef:n.focusAndScrollRef},r)}function InnerLayoutRouter(e){let{parallelRouterKey:t,url:r,childNodes:n,childProp:i,segmentPath:s,tree:c,cacheKey:d}=e,f=(0,a.useContext)(o.GlobalLayoutRouterContext);if(!f)throw Error("invariant global layout router not mounted");let{buildId:p,changeByServerResponse:h,tree:y}=f,m=n.get(d);if(i&&null!==i.current&&(m?m.status===o.CacheStates.LAZY_INITIALIZED&&(m.status=o.CacheStates.READY,m.subTreeData=i.current):(m={status:o.CacheStates.READY,data:null,subTreeData:i.current,parallelRoutes:new Map},n.set(d,m))),!m||m.status===o.CacheStates.LAZY_INITIALIZED){let e=walkAddRefetch(["",...s],y);m={status:o.CacheStates.DATA_FETCH,data:(0,_.createRecordFromThenable)((0,l.fetchServerResponse)(new URL(r,location.origin),e,f.nextUrl,p)),subTreeData:null,head:m&&m.status===o.CacheStates.LAZY_INITIALIZED?m.head:void 0,parallelRoutes:m&&m.status===o.CacheStates.LAZY_INITIALIZED?m.parallelRoutes:new Map},n.set(d,m)}if(!m)throw Error("Child node should always exist");if(m.subTreeData&&m.data)throw Error("Child node should not have both subTreeData and data");if(m.data){let[e,t]=(0,a.use)(m.data);m.data=null,setTimeout(()=>{(0,a.startTransition)(()=>{h(y,e,t)})}),(0,a.use)((0,u.createInfinitePromise)())}m.subTreeData||(0,a.use)((0,u.createInfinitePromise)());let g=a.default.createElement(o.LayoutRouterContext.Provider,{value:{tree:c[1][t],childNodes:m.parallelRoutes,url:r}},m.subTreeData);return g}function LoadingBoundary(e){let{children:t,loading:r,loadingStyles:n,loadingScripts:o,hasLoading:l}=e;return l?a.default.createElement(a.Suspense,{fallback:a.default.createElement(a.default.Fragment,null,n,o,r)},t):a.default.createElement(a.default.Fragment,null,t)}function OuterLayoutRouter(e){let{parallelRouterKey:t,segmentPath:r,childProp:n,error:l,errorStyles:u,errorScripts:c,templateStyles:_,templateScripts:y,loading:m,loadingStyles:g,loadingScripts:b,hasLoading:v,template:P,notFound:R,notFoundStyles:S,styles:E}=e,O=(0,a.useContext)(o.LayoutRouterContext);if(!O)throw Error("invariant expected layout router to be mounted");let{childNodes:T,tree:j,url:M}=O,x=T.get(t);x||(x=new Map,T.set(t,x));let A=j[1][t][0],C=n.segment,N=(0,p.getSegmentValue)(A),w=[A];return a.default.createElement(a.default.Fragment,null,E,w.map(e=>{let E=(0,s.matchSegment)(e,C),O=(0,p.getSegmentValue)(e),T=(0,h.createRouterCacheKey)(e);return a.default.createElement(o.TemplateContext.Provider,{key:(0,h.createRouterCacheKey)(e,!0),value:a.default.createElement(ScrollAndFocusHandler,{segmentPath:r},a.default.createElement(i.ErrorBoundary,{errorComponent:l,errorStyles:u,errorScripts:c},a.default.createElement(LoadingBoundary,{hasLoading:v,loading:m,loadingStyles:g,loadingScripts:b},a.default.createElement(f.NotFoundBoundary,{notFound:R,notFoundStyles:S},a.default.createElement(d.RedirectBoundary,null,a.default.createElement(InnerLayoutRouter,{parallelRouterKey:t,url:M,tree:j,childNodes:x,childProp:E?n:null,segmentPath:r,cacheKey:T,isActive:N===O}))))))},_,y,P)}))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4538:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{matchSegment:function(){return matchSegment},canSegmentBeOverridden:function(){return canSegmentBeOverridden}});let n=r(2290),matchSegment=(e,t)=>"string"==typeof e?"string"==typeof t&&e===t:"string"!=typeof t&&e[0]===t[0]&&e[1]===t[1],canSegmentBeOverridden=(e,t)=>{var r;return!Array.isArray(e)&&!!Array.isArray(t)&&(null==(r=(0,n.getSegmentParam)(e))?void 0:r.param)===t[0]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3094:(e,t,r)=>{"use strict";function maybePostpone(e,t){if(!e.isStaticGeneration||!e.experimental.ppr)return;let n=r(9885);"function"==typeof n.unstable_postpone&&n.unstable_postpone(t)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"maybePostpone",{enumerable:!0,get:function(){return maybePostpone}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4979:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ReadonlyURLSearchParams:function(){return ReadonlyURLSearchParams},useSearchParams:function(){return useSearchParams},usePathname:function(){return usePathname},ServerInsertedHTMLContext:function(){return i.ServerInsertedHTMLContext},useServerInsertedHTML:function(){return i.useServerInsertedHTML},useRouter:function(){return useRouter},useParams:function(){return useParams},useSelectedLayoutSegments:function(){return useSelectedLayoutSegments},useSelectedLayoutSegment:function(){return useSelectedLayoutSegment},redirect:function(){return s.redirect},permanentRedirect:function(){return s.permanentRedirect},RedirectType:function(){return s.RedirectType},notFound:function(){return c.notFound}});let n=r(9885),a=r(2428),o=r(1736),l=r(3402),u=r(1275),i=r(5753),s=r(1612),c=r(1103),d=Symbol("internal for urlsearchparams readonly");function readonlyURLSearchParamsError(){return Error("ReadonlyURLSearchParams cannot be modified")}let ReadonlyURLSearchParams=class ReadonlyURLSearchParams{[Symbol.iterator](){return this[d][Symbol.iterator]()}append(){throw readonlyURLSearchParamsError()}delete(){throw readonlyURLSearchParamsError()}set(){throw readonlyURLSearchParamsError()}sort(){throw readonlyURLSearchParamsError()}constructor(e){this[d]=e,this.entries=e.entries.bind(e),this.forEach=e.forEach.bind(e),this.get=e.get.bind(e),this.getAll=e.getAll.bind(e),this.has=e.has.bind(e),this.keys=e.keys.bind(e),this.values=e.values.bind(e),this.toString=e.toString.bind(e),this.size=e.size}};function useSearchParams(){(0,l.clientHookInServerComponentError)("useSearchParams");let e=(0,n.useContext)(o.SearchParamsContext),t=(0,n.useMemo)(()=>e?new ReadonlyURLSearchParams(e):null,[e]);{let{bailoutToClientRendering:e}=r(4954);e()}return t}function usePathname(){return(0,l.clientHookInServerComponentError)("usePathname"),(0,n.useContext)(o.PathnameContext)}function useRouter(){(0,l.clientHookInServerComponentError)("useRouter");let e=(0,n.useContext)(a.AppRouterContext);if(null===e)throw Error("invariant expected app router to be mounted");return e}function getSelectedParams(e,t){void 0===t&&(t={});let r=e[1];for(let e of Object.values(r)){let r=e[0],n=Array.isArray(r),a=n?r[1]:r;if(!a||a.startsWith("__PAGE__"))continue;let o=n&&("c"===r[2]||"oc"===r[2]);o?t[r[0]]=r[1].split("/"):n&&(t[r[0]]=r[1]),t=getSelectedParams(e,t)}return t}function useParams(){(0,l.clientHookInServerComponentError)("useParams");let e=(0,n.useContext)(a.GlobalLayoutRouterContext),t=(0,n.useContext)(o.PathParamsContext);return(0,n.useMemo)(()=>(null==e?void 0:e.tree)?getSelectedParams(e.tree):t,[null==e?void 0:e.tree,t])}function getSelectedLayoutSegmentPath(e,t,r,n){let a;if(void 0===r&&(r=!0),void 0===n&&(n=[]),r)a=e[1][t];else{var o;let t=e[1];a=null!=(o=t.children)?o:Object.values(t)[0]}if(!a)return n;let l=a[0],i=(0,u.getSegmentValue)(l);return!i||i.startsWith("__PAGE__")?n:(n.push(i),getSelectedLayoutSegmentPath(a,t,!1,n))}function useSelectedLayoutSegments(e){void 0===e&&(e="children"),(0,l.clientHookInServerComponentError)("useSelectedLayoutSegments");let{tree:t}=(0,n.useContext)(a.LayoutRouterContext);return getSelectedLayoutSegmentPath(t,e)}function useSelectedLayoutSegment(e){void 0===e&&(e="children"),(0,l.clientHookInServerComponentError)("useSelectedLayoutSegment");let t=useSelectedLayoutSegments(e);return 0===t.length?null:t[0]}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4714:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NotFoundBoundary",{enumerable:!0,get:function(){return NotFoundBoundary}});let n=r(85),a=n._(r(9885)),o=r(4979);let NotFoundErrorBoundary=class NotFoundErrorBoundary extends a.default.Component{static getDerivedStateFromError(e){if((null==e?void 0:e.digest)==="NEXT_NOT_FOUND")return{notFoundTriggered:!0};throw e}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.notFoundTriggered?{notFoundTriggered:!1,previousPathname:e.pathname}:{notFoundTriggered:t.notFoundTriggered,previousPathname:e.pathname}}render(){return this.state.notFoundTriggered?a.default.createElement(a.default.Fragment,null,a.default.createElement("meta",{name:"robots",content:"noindex"}),!1,this.props.notFoundStyles,this.props.notFound):this.props.children}constructor(e){super(e),this.state={notFoundTriggered:!!e.asNotFound,previousPathname:e.pathname}}};function NotFoundBoundary(e){let{notFound:t,notFoundStyles:r,asNotFound:n,children:l}=e,u=(0,o.usePathname)();return t?a.default.createElement(NotFoundErrorBoundary,{pathname:u,notFound:t,notFoundStyles:r,asNotFound:n},l):a.default.createElement(a.default.Fragment,null,l)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1103:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{notFound:function(){return notFound},isNotFoundError:function(){return isNotFoundError}});let r="NEXT_NOT_FOUND";function notFound(){let e=Error(r);throw e.digest=r,e}function isNotFoundError(e){return(null==e?void 0:e.digest)===r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8862:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"PromiseQueue",{enumerable:!0,get:function(){return PromiseQueue}});let n=r(3592),a=r(4941);var o=a._("_maxConcurrency"),l=a._("_runningCount"),u=a._("_queue"),i=a._("_processNext");let PromiseQueue=class PromiseQueue{enqueue(e){let t,r;let a=new Promise((e,n)=>{t=e,r=n}),task=async()=>{try{n._(this,l)[l]++;let r=await e();t(r)}catch(e){r(e)}finally{n._(this,l)[l]--,n._(this,i)[i]()}};return n._(this,u)[u].push({promiseFn:a,task}),n._(this,i)[i](),a}bump(e){let t=n._(this,u)[u].findIndex(t=>t.promiseFn===e);if(t>-1){let e=n._(this,u)[u].splice(t,1)[0];n._(this,u)[u].unshift(e),n._(this,i)[i](!0)}}constructor(e=5){Object.defineProperty(this,i,{value:processNext}),Object.defineProperty(this,o,{writable:!0,value:void 0}),Object.defineProperty(this,l,{writable:!0,value:void 0}),Object.defineProperty(this,u,{writable:!0,value:void 0}),n._(this,o)[o]=e,n._(this,l)[l]=0,n._(this,u)[u]=[]}};function processNext(e){if(void 0===e&&(e=!1),(n._(this,l)[l]<n._(this,o)[o]||e)&&n._(this,u)[u].length>0){var t;null==(t=n._(this,u)[u].shift())||t.task()}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7502:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectErrorBoundary:function(){return RedirectErrorBoundary},RedirectBoundary:function(){return RedirectBoundary}});let n=r(8425),a=n._(r(9885)),o=r(4979),l=r(1612);function HandleRedirect(e){let{redirect:t,reset:r,redirectType:n}=e,u=(0,o.useRouter)();return(0,a.useEffect)(()=>{a.default.startTransition(()=>{n===l.RedirectType.push?u.push(t,{}):u.replace(t,{}),r()})},[t,n,r,u]),null}let RedirectErrorBoundary=class RedirectErrorBoundary extends a.default.Component{static getDerivedStateFromError(e){if((0,l.isRedirectError)(e)){let t=(0,l.getURLFromRedirectError)(e),r=(0,l.getRedirectTypeFromError)(e);return{redirect:t,redirectType:r}}throw e}render(){let{redirect:e,redirectType:t}=this.state;return null!==e&&null!==t?a.default.createElement(HandleRedirect,{redirect:e,redirectType:t,reset:()=>this.setState({redirect:null})}):this.props.children}constructor(e){super(e),this.state={redirect:null,redirectType:null}}};function RedirectBoundary(e){let{children:t}=e,r=(0,o.useRouter)();return a.default.createElement(RedirectErrorBoundary,{router:r},t)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1612:(e,t,r)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectType:function(){return n},getRedirectError:function(){return getRedirectError},redirect:function(){return redirect},permanentRedirect:function(){return permanentRedirect},isRedirectError:function(){return isRedirectError},getURLFromRedirectError:function(){return getURLFromRedirectError},getRedirectTypeFromError:function(){return getRedirectTypeFromError}});let a=r(5403),o="NEXT_REDIRECT";function getRedirectError(e,t,r){void 0===r&&(r=!1);let n=Error(o);n.digest=o+";"+t+";"+e+";"+r;let l=a.requestAsyncStorage.getStore();return l&&(n.mutableCookies=l.mutableCookies),n}function redirect(e,t){throw void 0===t&&(t="replace"),getRedirectError(e,t,!1)}function permanentRedirect(e,t){throw void 0===t&&(t="replace"),getRedirectError(e,t,!0)}function isRedirectError(e){if("string"!=typeof(null==e?void 0:e.digest))return!1;let[t,r,n,a]=e.digest.split(";",4);return t===o&&("replace"===r||"push"===r)&&"string"==typeof n&&("true"===a||"false"===a)}function getURLFromRedirectError(e){return isRedirectError(e)?e.digest.split(";",3)[2]:null}function getRedirectTypeFromError(e){if(!isRedirectError(e))throw Error("Not a redirect error");return e.digest.split(";",2)[1]}(function(e){e.push="push",e.replace="replace"})(n||(n={})),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5392:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return RenderFromTemplateContext}});let n=r(8425),a=n._(r(9885)),o=r(2428);function RenderFromTemplateContext(){let e=(0,a.useContext)(o.TemplateContext);return a.default.createElement(a.default.Fragment,null,e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1847:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyFlightData",{enumerable:!0,get:function(){return applyFlightData}});let n=r(2428),a=r(5929),o=r(4059);function applyFlightData(e,t,r,l){void 0===l&&(l=!1);let[u,i,s]=r.slice(-3);return null!==i&&(3===r.length?(t.status=n.CacheStates.READY,t.subTreeData=i,(0,a.fillLazyItemsTillLeafWithHead)(t,e,u,s,l)):(t.status=n.CacheStates.READY,t.subTreeData=e.subTreeData,t.parallelRoutes=new Map(e.parallelRoutes),(0,o.fillCacheWithNewSubTreeData)(t,e,r,l)),!0)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9605:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyRouterStatePatchToTree",{enumerable:!0,get:function(){return applyRouterStatePatchToTree}});let n=r(4538);function applyPatch(e,t){let[r,a]=e,[o,l]=t;if("__DEFAULT__"===o&&"__DEFAULT__"!==r)return e;if((0,n.matchSegment)(r,o)){let t={};for(let e in a){let r=void 0!==l[e];r?t[e]=applyPatch(a[e],l[e]):t[e]=a[e]}for(let e in l)t[e]||(t[e]=l[e]);let n=[r,t];return e[2]&&(n[2]=e[2]),e[3]&&(n[3]=e[3]),e[4]&&(n[4]=e[4]),n}return t}function applyRouterStatePatchToTree(e,t,r){let a;let[o,l,,,u]=t;if(1===e.length){let e=applyPatch(t,r);return e}let[i,s]=e;if(!(0,n.matchSegment)(i,o))return null;let c=2===e.length;if(c)a=applyPatch(l[s],r);else if(null===(a=applyRouterStatePatchToTree(e.slice(2),l[s],r)))return null;let d=[e[0],{...l,[s]:a}];return u&&(d[4]=!0),d}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6663:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{extractPathFromFlightRouterState:function(){return extractPathFromFlightRouterState},computeChangedPath:function(){return computeChangedPath}});let n=r(4265),a=r(392),o=r(4538),removeLeadingSlash=e=>"/"===e[0]?e.slice(1):e,segmentToPathname=e=>"string"==typeof e?e:e[1];function normalizeSegments(e){return e.reduce((e,t)=>""===(t=removeLeadingSlash(t))||(0,a.isGroupSegment)(t)?e:e+"/"+t,"")||"/"}function extractPathFromFlightRouterState(e){var t;let r=Array.isArray(e[0])?e[0][1]:e[0];if("__DEFAULT__"===r||n.INTERCEPTION_ROUTE_MARKERS.some(e=>r.startsWith(e)))return;if(r.startsWith("__PAGE__"))return"";let a=[r],o=null!=(t=e[1])?t:{},l=o.children?extractPathFromFlightRouterState(o.children):void 0;if(void 0!==l)a.push(l);else for(let[e,t]of Object.entries(o)){if("children"===e)continue;let r=extractPathFromFlightRouterState(t);void 0!==r&&a.push(r)}return normalizeSegments(a)}function computeChangedPathImpl(e,t){let[r,a]=e,[l,u]=t,i=segmentToPathname(r),s=segmentToPathname(l);if(n.INTERCEPTION_ROUTE_MARKERS.some(e=>i.startsWith(e)||s.startsWith(e)))return"";if(!(0,o.matchSegment)(r,l)){var c;return null!=(c=extractPathFromFlightRouterState(t))?c:""}for(let e in a)if(u[e]){let t=computeChangedPathImpl(a[e],u[e]);if(null!==t)return segmentToPathname(l)+"/"+t}return null}function computeChangedPath(e,t){let r=computeChangedPathImpl(e,t);return null==r||"/"===r?r:normalizeSegments(r.split("/"))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1706:(e,t)=>{"use strict";function createHrefFromUrl(e,t){return void 0===t&&(t=!0),e.pathname+e.search+(t?e.hash:"")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createHrefFromUrl",{enumerable:!0,get:function(){return createHrefFromUrl}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9624:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInitialRouterState",{enumerable:!0,get:function(){return createInitialRouterState}});let n=r(2428),a=r(1706),o=r(5929),l=r(6663);function createInitialRouterState(e){var t;let{buildId:r,initialTree:u,children:i,initialCanonicalUrl:s,initialParallelRoutes:c,isServer:d,location:f,initialHead:p}=e,h={status:n.CacheStates.READY,data:null,subTreeData:i,parallelRoutes:d?new Map:c};return(null===c||0===c.size)&&(0,o.fillLazyItemsTillLeafWithHead)(h,void 0,u,p),{buildId:r,tree:u,cache:h,prefetchCache:new Map,pushRef:{pendingPush:!1,mpaNavigation:!1},focusAndScrollRef:{apply:!1,onlyHashChange:!1,hashFragment:null,segmentPaths:[]},canonicalUrl:f?(0,a.createHrefFromUrl)(f):s,nextUrl:null!=(t=(0,l.extractPathFromFlightRouterState)(u)||(null==f?void 0:f.pathname))?t:null}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8775:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createOptimisticTree",{enumerable:!0,get:function(){return createOptimisticTree}});let n=r(4538);function createOptimisticTree(e,t,r){let a;let[o,l,u,i,s]=t||[null,{}],c=e[0],d=1===e.length,f=null!==o&&(0,n.matchSegment)(o,c),p=Object.keys(l).length>1,h=!t||!f||p,_={};if(null!==o&&f&&(_=l),!d&&!p){let t=createOptimisticTree(e.slice(1),_?_.children:null,r||h);a=t}let y=[c,{..._,...a?{children:a}:{}}];return u&&(y[2]=u),!r&&h?y[3]="refetch":f&&i&&(y[3]=i),f&&s&&(y[4]=s),y}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8026:(e,t)=>{"use strict";function createRecordFromThenable(e){return e.status="pending",e.then(t=>{"pending"===e.status&&(e.status="fulfilled",e.value=t)},t=>{"pending"===e.status&&(e.status="rejected",e.reason=t)}),e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRecordFromThenable",{enumerable:!0,get:function(){return createRecordFromThenable}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4701:(e,t)=>{"use strict";function createRouterCacheKey(e,t){return void 0===t&&(t=!1),Array.isArray(e)?(e[0]+"|"+e[1]+"|"+e[2]).toLowerCase():t&&e.startsWith("__PAGE__")?"__PAGE__":e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRouterCacheKey",{enumerable:!0,get:function(){return createRouterCacheKey}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9102:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fetchServerResponse",{enumerable:!0,get:function(){return fetchServerResponse}});let n=r(4361),a=r(3724),o=r(5422),l=r(3678),u=r(755),i=r(5082),{createFromFetch:s}=r(2623);function doMpaNavigation(e){return[(0,a.urlToUrlWithoutFlightMarker)(e).toString(),void 0]}async function fetchServerResponse(e,t,r,c,d){let f={[n.RSC]:"1",[n.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(t))};d===l.PrefetchKind.AUTO&&(f[n.NEXT_ROUTER_PREFETCH]="1"),r&&(f[n.NEXT_URL]=r);let p=(0,u.hexHash)([f[n.NEXT_ROUTER_PREFETCH]||"0",f[n.NEXT_ROUTER_STATE_TREE],f[n.NEXT_URL]].join(","));try{let t=new URL(e);t.searchParams.set(n.NEXT_RSC_UNION_QUERY,p);let r=await fetch(t,{credentials:"same-origin",headers:f}),l=(0,a.urlToUrlWithoutFlightMarker)(r.url),u=r.redirected?l:void 0,d=r.headers.get("content-type")||"",h=!!r.headers.get(i.NEXT_DID_POSTPONE_HEADER);if(d!==n.RSC_CONTENT_TYPE_HEADER||!r.ok)return e.hash&&(l.hash=e.hash),doMpaNavigation(l.toString());let[_,y]=await s(Promise.resolve(r),{callServer:o.callServer});if(c!==_)return doMpaNavigation(r.url);return[y,u,h]}catch(t){return console.error("Failed to fetch RSC payload for "+e+". Falling back to browser navigation.",t),[e.toString(),void 0]}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1924:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithDataProperty",{enumerable:!0,get:function(){return fillCacheWithDataProperty}});let n=r(2428),a=r(4701);function fillCacheWithDataProperty(e,t,r,o,l){void 0===l&&(l=!1);let u=r.length<=2,[i,s]=r,c=(0,a.createRouterCacheKey)(s),d=t.parallelRoutes.get(i);if(!d||l&&t.parallelRoutes.size>1)return{bailOptimistic:!0};let f=e.parallelRoutes.get(i);f&&f!==d||(f=new Map(d),e.parallelRoutes.set(i,f));let p=d.get(c),h=f.get(c);if(u){h&&h.data&&h!==p||f.set(c,{status:n.CacheStates.DATA_FETCH,data:o(),subTreeData:null,parallelRoutes:new Map});return}if(!h||!p){h||f.set(c,{status:n.CacheStates.DATA_FETCH,data:o(),subTreeData:null,parallelRoutes:new Map});return}return h===p&&(h={status:h.status,data:h.data,subTreeData:h.subTreeData,parallelRoutes:new Map(h.parallelRoutes)},f.set(c,h)),fillCacheWithDataProperty(h,p,r.slice(2),o)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4059:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithNewSubTreeData",{enumerable:!0,get:function(){return fillCacheWithNewSubTreeData}});let n=r(2428),a=r(2582),o=r(5929),l=r(4701);function fillCacheWithNewSubTreeData(e,t,r,u){let i=r.length<=5,[s,c]=r,d=(0,l.createRouterCacheKey)(c),f=t.parallelRoutes.get(s);if(!f)return;let p=e.parallelRoutes.get(s);p&&p!==f||(p=new Map(f),e.parallelRoutes.set(s,p));let h=f.get(d),_=p.get(d);if(i){_&&_.data&&_!==h||(_={status:n.CacheStates.READY,data:null,subTreeData:r[3],parallelRoutes:h?new Map(h.parallelRoutes):new Map},h&&(0,a.invalidateCacheByRouterState)(_,h,r[2]),(0,o.fillLazyItemsTillLeafWithHead)(_,h,r[2],r[4],u),p.set(d,_));return}_&&h&&(_===h&&(_={status:_.status,data:_.data,subTreeData:_.subTreeData,parallelRoutes:new Map(_.parallelRoutes)},p.set(d,_)),fillCacheWithNewSubTreeData(_,h,r.slice(2),u))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5929:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillLazyItemsTillLeafWithHead",{enumerable:!0,get:function(){return fillLazyItemsTillLeafWithHead}});let n=r(2428),a=r(4701);function fillLazyItemsTillLeafWithHead(e,t,r,o,l){let u=0===Object.keys(r[1]).length;if(u){e.head=o;return}for(let u in r[1]){let i=r[1][u],s=i[0],c=(0,a.createRouterCacheKey)(s);if(t){let r=t.parallelRoutes.get(u);if(r){let t=new Map(r),a=t.get(c),s=l&&a?{status:a.status,data:a.data,subTreeData:a.subTreeData,parallelRoutes:new Map(a.parallelRoutes)}:{status:n.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map(null==a?void 0:a.parallelRoutes)};t.set(c,s),fillLazyItemsTillLeafWithHead(s,a,i,o,l),e.parallelRoutes.set(u,t);continue}}let d={status:n.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map},f=e.parallelRoutes.get(u);f?f.set(c,d):e.parallelRoutes.set(u,new Map([[c,d]])),fillLazyItemsTillLeafWithHead(d,void 0,i,o,l)}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6699:(e,t)=>{"use strict";var r;function getPrefetchEntryCacheStatus(e){let{kind:t,prefetchTime:r,lastUsedTime:n}=e;return Date.now()<(null!=n?n:r)+3e4?n?"reusable":"fresh":"auto"===t&&Date.now()<r+3e5?"stale":"full"===t&&Date.now()<r+3e5?"reusable":"expired"}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PrefetchCacheEntryStatus:function(){return r},getPrefetchEntryCacheStatus:function(){return getPrefetchEntryCacheStatus}}),function(e){e.fresh="fresh",e.reusable="reusable",e.expired="expired",e.stale="stale"}(r||(r={})),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3466:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleMutable",{enumerable:!0,get:function(){return handleMutable}});let n=r(6663);function handleMutable(e,t){var r,a,o,l;let u=null==(a=t.shouldScroll)||a;return{buildId:e.buildId,canonicalUrl:null!=t.canonicalUrl?t.canonicalUrl===e.canonicalUrl?e.canonicalUrl:t.canonicalUrl:e.canonicalUrl,pushRef:{pendingPush:null!=t.pendingPush?t.pendingPush:e.pushRef.pendingPush,mpaNavigation:null!=t.mpaNavigation?t.mpaNavigation:e.pushRef.mpaNavigation},focusAndScrollRef:{apply:!!u&&((null==t?void 0:t.scrollableSegments)!==void 0||e.focusAndScrollRef.apply),onlyHashChange:!!t.hashFragment&&e.canonicalUrl.split("#",1)[0]===(null==(r=t.canonicalUrl)?void 0:r.split("#",1)[0]),hashFragment:u?t.hashFragment&&""!==t.hashFragment?decodeURIComponent(t.hashFragment.slice(1)):e.focusAndScrollRef.hashFragment:null,segmentPaths:u?null!=(o=null==t?void 0:t.scrollableSegments)?o:e.focusAndScrollRef.segmentPaths:[]},cache:t.cache?t.cache:e.cache,prefetchCache:t.prefetchCache?t.prefetchCache:e.prefetchCache,tree:void 0!==t.patchedTree?t.patchedTree:e.tree,nextUrl:void 0!==t.patchedTree?null!=(l=(0,n.computeChangedPath)(e.tree,t.patchedTree))?l:e.canonicalUrl:e.nextUrl}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1986:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheBelowFlightSegmentPath",{enumerable:!0,get:function(){return invalidateCacheBelowFlightSegmentPath}});let n=r(4701);function invalidateCacheBelowFlightSegmentPath(e,t,r){let a=r.length<=2,[o,l]=r,u=(0,n.createRouterCacheKey)(l),i=t.parallelRoutes.get(o);if(!i)return;let s=e.parallelRoutes.get(o);if(s&&s!==i||(s=new Map(i),e.parallelRoutes.set(o,s)),a){s.delete(u);return}let c=i.get(u),d=s.get(u);d&&c&&(d===c&&(d={status:d.status,data:d.data,subTreeData:d.subTreeData,parallelRoutes:new Map(d.parallelRoutes)},s.set(u,d)),invalidateCacheBelowFlightSegmentPath(d,c,r.slice(2)))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2582:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheByRouterState",{enumerable:!0,get:function(){return invalidateCacheByRouterState}});let n=r(4701);function invalidateCacheByRouterState(e,t,r){for(let a in r[1]){let o=r[1][a][0],l=(0,n.createRouterCacheKey)(o),u=t.parallelRoutes.get(a);if(u){let t=new Map(u);t.delete(l),e.parallelRoutes.set(a,t)}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},145:(e,t)=>{"use strict";function isNavigatingToNewRootLayout(e,t){let r=e[0],n=t[0];if(Array.isArray(r)&&Array.isArray(n)){if(r[0]!==n[0]||r[2]!==n[2])return!0}else if(r!==n)return!0;if(e[4])return!t[4];if(t[4])return!0;let a=Object.values(e[1])[0],o=Object.values(t[1])[0];return!a||!o||isNavigatingToNewRootLayout(a,o)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNavigatingToNewRootLayout",{enumerable:!0,get:function(){return isNavigatingToNewRootLayout}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4879:(e,t)=>{"use strict";function readRecordValue(e){if("fulfilled"===e.status)return e.value;throw e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"readRecordValue",{enumerable:!0,get:function(){return readRecordValue}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2755:(e,t,r)=>{"use strict";function fastRefreshReducerNoop(e,t){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fastRefreshReducer",{enumerable:!0,get:function(){return n}}),r(9102),r(8026),r(4879),r(1706),r(9605),r(145),r(8237),r(3466),r(1847);let n=fastRefreshReducerNoop;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2226:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"findHeadInCache",{enumerable:!0,get:function(){return findHeadInCache}});let n=r(4701);function findHeadInCache(e,t){let r=0===Object.keys(t).length;if(r)return e.head;for(let r in t){let[a,o]=t[r],l=e.parallelRoutes.get(r);if(!l)continue;let u=(0,n.createRouterCacheKey)(a),i=l.get(u);if(!i)continue;let s=findHeadInCache(i,o);if(s)return s}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1275:(e,t)=>{"use strict";function getSegmentValue(e){return Array.isArray(e)?e[1]:e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentValue",{enumerable:!0,get:function(){return getSegmentValue}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8237:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{handleExternalUrl:function(){return handleExternalUrl},navigateReducer:function(){return navigateReducer}});let n=r(2428),a=r(9102),o=r(8026),l=r(4879),u=r(1706),i=r(1986),s=r(1924),c=r(8775),d=r(9605),f=r(4320),p=r(145),h=r(3678),_=r(3466),y=r(1847),m=r(6699),g=r(8155),b=r(1196);function handleExternalUrl(e,t,r,n){return t.previousTree=e.tree,t.mpaNavigation=!0,t.canonicalUrl=r,t.pendingPush=n,t.scrollableSegments=void 0,(0,_.handleMutable)(e,t)}function generateSegmentsFromPatch(e){let t=[],[r,n]=e;if(0===Object.keys(n).length)return[[r]];for(let[e,a]of Object.entries(n))for(let n of generateSegmentsFromPatch(a))""===r?t.push([e,...n]):t.push([r,e,...n]);return t}function addRefetchToLeafSegments(e,t,r,a,o){let l=!1;e.status=n.CacheStates.READY,e.subTreeData=t.subTreeData,e.parallelRoutes=new Map(t.parallelRoutes);let u=generateSegmentsFromPatch(a).map(e=>[...r,...e]);for(let r of u){let n=(0,s.fillCacheWithDataProperty)(e,t,r,o);(null==n?void 0:n.bailOptimistic)||(l=!0)}return l}function navigateReducer(e,t){let{url:r,isExternalUrl:v,navigateType:P,cache:R,mutable:S,forceOptimisticNavigation:E,shouldScroll:O}=t,{pathname:T,hash:j}=r,M=(0,u.createHrefFromUrl)(r),x="push"===P;(0,g.prunePrefetchCache)(e.prefetchCache);let A=JSON.stringify(S.previousTree)===JSON.stringify(e.tree);if(A)return(0,_.handleMutable)(e,S);if(v)return handleExternalUrl(e,S,r.toString(),x);let C=e.prefetchCache.get((0,u.createHrefFromUrl)(r,!1));if(E&&(null==C?void 0:C.kind)!==h.PrefetchKind.TEMPORARY){let t=T.split("/");t.push("__PAGE__");let l=(0,c.createOptimisticTree)(t,e.tree,!1),i={...R};i.status=n.CacheStates.READY,i.subTreeData=e.cache.subTreeData,i.parallelRoutes=new Map(e.cache.parallelRoutes);let d=null,f=t.slice(1).map(e=>["children",e]).flat(),p=(0,s.fillCacheWithDataProperty)(i,e.cache,f,()=>(d||(d=(0,o.createRecordFromThenable)((0,a.fetchServerResponse)(r,l,e.nextUrl,e.buildId))),d),!0);if(!(null==p?void 0:p.bailOptimistic))return S.previousTree=e.tree,S.patchedTree=l,S.pendingPush=x,S.hashFragment=j,S.shouldScroll=O,S.scrollableSegments=[],S.cache=i,S.canonicalUrl=M,e.prefetchCache.set((0,u.createHrefFromUrl)(r,!1),{data:d?(0,o.createRecordFromThenable)(Promise.resolve(d)):null,kind:h.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:e.tree,lastUsedTime:Date.now()}),(0,_.handleMutable)(e,S)}if(!C){let t=(0,o.createRecordFromThenable)((0,a.fetchServerResponse)(r,e.tree,e.nextUrl,e.buildId,void 0)),n={data:(0,o.createRecordFromThenable)(Promise.resolve(t)),kind:h.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:e.tree,lastUsedTime:null};e.prefetchCache.set((0,u.createHrefFromUrl)(r,!1),n),C=n}let N=(0,m.getPrefetchEntryCacheStatus)(C),{treeAtTimeOfPrefetch:w,data:I}=C;b.prefetchQueue.bump(I);let[F,D,L]=(0,l.readRecordValue)(I);if(C.lastUsedTime||(C.lastUsedTime=Date.now()),"string"==typeof F)return handleExternalUrl(e,S,F,x);let U=e.tree,H=e.cache,B=[];for(let t of F){let l=t.slice(0,-4),u=t.slice(-3)[0],s=["",...l],c=(0,d.applyRouterStatePatchToTree)(s,U,u);if(null===c&&(c=(0,d.applyRouterStatePatchToTree)(s,w,u)),null!==c){if((0,p.isNavigatingToNewRootLayout)(U,c))return handleExternalUrl(e,S,M,x);let d=!L&&(0,y.applyFlightData)(H,R,t,"auto"===C.kind&&N===m.PrefetchCacheEntryStatus.reusable);d||N!==m.PrefetchCacheEntryStatus.stale||(d=addRefetchToLeafSegments(R,H,l,u,()=>(0,o.createRecordFromThenable)((0,a.fetchServerResponse)(r,U,e.nextUrl,e.buildId))));let h=(0,f.shouldHardNavigate)(s,U);for(let e of(h?(R.status=n.CacheStates.READY,R.subTreeData=H.subTreeData,(0,i.invalidateCacheBelowFlightSegmentPath)(R,H,l),S.cache=R):d&&(S.cache=R),H=R,U=c,generateSegmentsFromPatch(u))){let t=[...l,...e];"__DEFAULT__"!==t[t.length-1]&&B.push(t)}}}return S.previousTree=e.tree,S.patchedTree=U,S.canonicalUrl=D?(0,u.createHrefFromUrl)(D):M,S.pendingPush=x,S.scrollableSegments=B,S.hashFragment=j,S.shouldScroll=O,(0,_.handleMutable)(e,S)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1196:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{prefetchQueue:function(){return c},prefetchReducer:function(){return prefetchReducer}});let n=r(1706),a=r(9102),o=r(3678),l=r(8026),u=r(8155),i=r(4361),s=r(8862),c=new s.PromiseQueue(5);function prefetchReducer(e,t){(0,u.prunePrefetchCache)(e.prefetchCache);let{url:r}=t;r.searchParams.delete(i.NEXT_RSC_UNION_QUERY);let s=(0,n.createHrefFromUrl)(r,!1),d=e.prefetchCache.get(s);if(d&&(d.kind===o.PrefetchKind.TEMPORARY&&e.prefetchCache.set(s,{...d,kind:t.kind}),!(d.kind===o.PrefetchKind.AUTO&&t.kind===o.PrefetchKind.FULL)))return e;let f=(0,l.createRecordFromThenable)(c.enqueue(()=>(0,a.fetchServerResponse)(r,e.tree,e.nextUrl,e.buildId,t.kind)));return e.prefetchCache.set(s,{treeAtTimeOfPrefetch:e.tree,data:f,kind:t.kind,prefetchTime:Date.now(),lastUsedTime:null}),e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8155:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"prunePrefetchCache",{enumerable:!0,get:function(){return prunePrefetchCache}});let n=r(6699);function prunePrefetchCache(e){for(let[t,r]of e)(0,n.getPrefetchEntryCacheStatus)(r)===n.PrefetchCacheEntryStatus.expired&&e.delete(t)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8038:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"refreshReducer",{enumerable:!0,get:function(){return refreshReducer}});let n=r(9102),a=r(8026),o=r(4879),l=r(1706),u=r(9605),i=r(145),s=r(8237),c=r(3466),d=r(2428),f=r(5929);function refreshReducer(e,t){let{cache:r,mutable:p,origin:h}=t,_=e.canonicalUrl,y=e.tree,m=JSON.stringify(p.previousTree)===JSON.stringify(y);if(m)return(0,c.handleMutable)(e,p);r.data||(r.data=(0,a.createRecordFromThenable)((0,n.fetchServerResponse)(new URL(_,h),[y[0],y[1],y[2],"refetch"],e.nextUrl,e.buildId)));let[g,b]=(0,o.readRecordValue)(r.data);if("string"==typeof g)return(0,s.handleExternalUrl)(e,p,g,e.pushRef.pendingPush);for(let t of(r.data=null,g)){if(3!==t.length)return console.log("REFRESH FAILED"),e;let[n]=t,a=(0,u.applyRouterStatePatchToTree)([""],y,n);if(null===a)throw Error("SEGMENT MISMATCH");if((0,i.isNavigatingToNewRootLayout)(y,a))return(0,s.handleExternalUrl)(e,p,_,e.pushRef.pendingPush);let o=b?(0,l.createHrefFromUrl)(b):void 0;b&&(p.canonicalUrl=o);let[c,h]=t.slice(-2);null!==c&&(r.status=d.CacheStates.READY,r.subTreeData=c,(0,f.fillLazyItemsTillLeafWithHead)(r,void 0,n,h),p.cache=r,p.prefetchCache=new Map),p.previousTree=y,p.patchedTree=a,p.canonicalUrl=_,y=a}return(0,c.handleMutable)(e,p)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2910:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"restoreReducer",{enumerable:!0,get:function(){return restoreReducer}});let n=r(1706);function restoreReducer(e,t){let{url:r,tree:a}=t,o=(0,n.createHrefFromUrl)(r);return{buildId:e.buildId,canonicalUrl:o,pushRef:e.pushRef,focusAndScrollRef:e.focusAndScrollRef,cache:e.cache,prefetchCache:e.prefetchCache,tree:a,nextUrl:r.pathname}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9747:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverActionReducer",{enumerable:!0,get:function(){return serverActionReducer}});let n=r(5422),a=r(4361),o=r(8026),l=r(4879),u=r(6879),i=r(1706),s=r(8237),c=r(9605),d=r(145),f=r(2428),p=r(3466),h=r(5929),{createFromFetch:_,encodeReply:y}=r(2623);async function fetchServerAction(e,t){let r,{actionId:o,actionArgs:l}=t,i=await y(l),s=await fetch("",{method:"POST",headers:{Accept:a.RSC_CONTENT_TYPE_HEADER,[a.ACTION]:o,[a.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(e.tree)),...e.nextUrl?{[a.NEXT_URL]:e.nextUrl}:{}},body:i}),c=s.headers.get("x-action-redirect");try{let e=JSON.parse(s.headers.get("x-action-revalidated")||"[[],0,0]");r={paths:e[0]||[],tag:!!e[1],cookie:e[2]}}catch(e){r={paths:[],tag:!1,cookie:!1}}let d=c?new URL((0,u.addBasePath)(c),new URL(e.canonicalUrl,window.location.href)):void 0;if(s.headers.get("content-type")===a.RSC_CONTENT_TYPE_HEADER){let e=await _(Promise.resolve(s),{callServer:n.callServer});if(c){let[,t]=null!=e?e:[];return{actionFlightData:t,redirectLocation:d,revalidatedParts:r}}let[t,[,a]]=null!=e?e:[];return{actionResult:t,actionFlightData:a,redirectLocation:d,revalidatedParts:r}}return{redirectLocation:d,revalidatedParts:r}}function serverActionReducer(e,t){let{mutable:r,cache:n,resolve:a,reject:u}=t,_=e.canonicalUrl,y=e.tree,m=JSON.stringify(r.previousTree)===JSON.stringify(y);if(m)return(0,p.handleMutable)(e,r);if(r.inFlightServerAction){if("fulfilled"!==r.inFlightServerAction.status&&r.globalMutable.pendingNavigatePath&&r.globalMutable.pendingNavigatePath!==_)return r.inFlightServerAction.then(()=>{r.actionResultResolved||(r.inFlightServerAction=null,r.globalMutable.pendingNavigatePath=void 0,r.globalMutable.refresh(),r.actionResultResolved=!0)},()=>{}),e}else r.inFlightServerAction=(0,o.createRecordFromThenable)(fetchServerAction(e,t));try{let{actionResult:t,actionFlightData:o,redirectLocation:u}=(0,l.readRecordValue)(r.inFlightServerAction);if(u&&(e.pushRef.pendingPush=!0,r.pendingPush=!0),r.previousTree=e.tree,!o){if(r.actionResultResolved||(a(t),r.actionResultResolved=!0),u)return(0,s.handleExternalUrl)(e,r,u.href,e.pushRef.pendingPush);return e}if("string"==typeof o)return(0,s.handleExternalUrl)(e,r,o,e.pushRef.pendingPush);for(let t of(r.inFlightServerAction=null,o)){if(3!==t.length)return console.log("SERVER ACTION APPLY FAILED"),e;let[a]=t,o=(0,c.applyRouterStatePatchToTree)([""],y,a);if(null===o)throw Error("SEGMENT MISMATCH");if((0,d.isNavigatingToNewRootLayout)(y,o))return(0,s.handleExternalUrl)(e,r,_,e.pushRef.pendingPush);let[l,u]=t.slice(-2);null!==l&&(n.status=f.CacheStates.READY,n.subTreeData=l,(0,h.fillLazyItemsTillLeafWithHead)(n,void 0,a,u),r.cache=n,r.prefetchCache=new Map),r.previousTree=y,r.patchedTree=o,r.canonicalUrl=_,y=o}if(u){let e=(0,i.createHrefFromUrl)(u,!1);r.canonicalUrl=e}return r.actionResultResolved||(a(t),r.actionResultResolved=!0),(0,p.handleMutable)(e,r)}catch(t){if("rejected"===t.status)return r.actionResultResolved||(u(t.reason),r.actionResultResolved=!0),e;throw t}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9794:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverPatchReducer",{enumerable:!0,get:function(){return serverPatchReducer}});let n=r(1706),a=r(9605),o=r(145),l=r(8237),u=r(1847),i=r(3466);function serverPatchReducer(e,t){let{flightData:r,previousTree:s,overrideCanonicalUrl:c,cache:d,mutable:f}=t,p=JSON.stringify(s)===JSON.stringify(e.tree);if(!p)return console.log("TREE MISMATCH"),e;if(f.previousTree)return(0,i.handleMutable)(e,f);if("string"==typeof r)return(0,l.handleExternalUrl)(e,f,r,e.pushRef.pendingPush);let h=e.tree,_=e.cache;for(let t of r){let r=t.slice(0,-4),[i]=t.slice(-3,-2),s=(0,a.applyRouterStatePatchToTree)(["",...r],h,i);if(null===s)throw Error("SEGMENT MISMATCH");if((0,o.isNavigatingToNewRootLayout)(h,s))return(0,l.handleExternalUrl)(e,f,e.canonicalUrl,e.pushRef.pendingPush);let p=c?(0,n.createHrefFromUrl)(c):void 0;p&&(f.canonicalUrl=p),(0,u.applyFlightData)(_,d,t),f.previousTree=h,f.patchedTree=s,f.cache=d,_=d,h=s}return(0,i.handleMutable)(e,f)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3678:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PrefetchKind:function(){return r},ACTION_REFRESH:function(){return n},ACTION_NAVIGATE:function(){return a},ACTION_RESTORE:function(){return o},ACTION_SERVER_PATCH:function(){return l},ACTION_PREFETCH:function(){return u},ACTION_FAST_REFRESH:function(){return i},ACTION_SERVER_ACTION:function(){return s}});let n="refresh",a="navigate",o="restore",l="server-patch",u="prefetch",i="fast-refresh",s="server-action";(function(e){e.AUTO="auto",e.FULL="full",e.TEMPORARY="temporary"})(r||(r={})),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7986:(e,t,r)=>{"use strict";function serverReducer(e,t){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"reducer",{enumerable:!0,get:function(){return n}}),r(3678),r(8237),r(9794),r(2910),r(8038),r(1196),r(2755),r(9747);let n=serverReducer;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4320:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"shouldHardNavigate",{enumerable:!0,get:function(){return shouldHardNavigate}});let n=r(4538);function shouldHardNavigate(e,t){let[r,a]=t,[o,l]=e;if(!(0,n.matchSegment)(o,r))return!!Array.isArray(o);let u=e.length<=2;return!u&&shouldHardNavigate(e.slice(2),a[l])}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3032:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createSearchParamsBailoutProxy",{enumerable:!0,get:function(){return createSearchParamsBailoutProxy}});let n=r(1492);function createSearchParamsBailoutProxy(){return new Proxy({},{get(e,t){"string"==typeof t&&(0,n.staticGenerationBailout)("searchParams."+t)}})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1492:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationBailout",{enumerable:!0,get:function(){return staticGenerationBailout}});let n=r(5171),a=r(3094),o=r(4749);let StaticGenBailoutError=class StaticGenBailoutError extends Error{constructor(...e){super(...e),this.code="NEXT_STATIC_GEN_BAILOUT"}};function formatErrorMessage(e,t){let{dynamic:r,link:n}=t||{};return"Page"+(r?' with `dynamic = "'+r+'"`':"")+" couldn't be rendered statically because it used `"+e+"`."+(n?" See more info here: "+n:"")}let staticGenerationBailout=(e,t)=>{let r=o.staticGenerationAsyncStorage.getStore();if(!r)return!1;if(r.forceStatic)return!0;if(r.dynamicShouldError){var l;throw new StaticGenBailoutError(formatErrorMessage(e,{...t,dynamic:null!=(l=null==t?void 0:t.dynamic)?l:"error"}))}let u=formatErrorMessage(e,{...t,link:"https://nextjs.org/docs/messages/dynamic-server-error"});if((0,a.maybePostpone)(r,u),r.revalidate=0,(null==t?void 0:t.dynamic)||(r.staticPrefetchBailout=!0),r.isStaticGeneration){let t=new n.DynamicServerError(u);throw r.dynamicUsageDescription=e,r.dynamicUsageStack=t.stack,t}return!1};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8898:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return StaticGenerationSearchParamsBailoutProvider}});let n=r(85),a=n._(r(9885)),o=r(3032);function StaticGenerationSearchParamsBailoutProvider(e){let{Component:t,propsForComponent:r,isStaticGeneration:n}=e;if(n){let e=(0,o.createSearchParamsBailoutProxy)();return a.default.createElement(t,{searchParams:e,...r})}return a.default.createElement(t,r)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9236:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"useReducerWithReduxDevtools",{enumerable:!0,get:function(){return a}});let n=r(9885);function useReducerWithReduxDevtoolsNoop(e,t){let[r,a]=(0,n.useReducer)(e,t);return[r,a,()=>{}]}let a=useReducerWithReduxDevtoolsNoop;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9760:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hasBasePath",{enumerable:!0,get:function(){return hasBasePath}});let n=r(6364);function hasBasePath(e){return(0,n.pathHasPrefix)(e,"")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6945:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return normalizePathTrailingSlash}});let n=r(6923),a=r(5525),normalizePathTrailingSlash=e=>{if(!e.startsWith("/"))return e;let{pathname:t,query:r,hash:o}=(0,a.parsePath)(e);return""+(0,n.removeTrailingSlash)(t)+r+o};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4978:(e,t,r)=>{"use strict";function removeBasePath(e){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeBasePath",{enumerable:!0,get:function(){return removeBasePath}}),r(9760),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},755:(e,t)=>{"use strict";function djb2Hash(e){let t=5381;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);t=(t<<5)+t+n}return Math.abs(t)}function hexHash(e){return djb2Hash(e).toString(36).slice(0,5)}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{djb2Hash:function(){return djb2Hash},hexHash:function(){return hexHash}})},1118:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXT_DYNAMIC_NO_SSR_CODE:function(){return r},throwWithNoSSR:function(){return throwWithNoSSR}});let r="NEXT_DYNAMIC_NO_SSR_CODE";function throwWithNoSSR(){let e=Error(r);throw e.digest=r,e}},1518:(e,t)=>{"use strict";function ensureLeadingSlash(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return ensureLeadingSlash}})},8549:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return addPathPrefix}});let n=r(5525);function addPathPrefix(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:a,hash:o}=(0,n.parsePath)(e);return""+t+r+a+o}},8321:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeAppPath:function(){return normalizeAppPath},normalizeRscURL:function(){return normalizeRscURL},normalizePostponedURL:function(){return normalizePostponedURL}});let n=r(1518),a=r(392);function normalizeAppPath(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,r,n)=>!t||(0,a.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&r===n.length-1?e:e+"/"+t,""))}function normalizeRscURL(e){return e.replace(/\.rsc($|\?)/,"$1")}function normalizePostponedURL(e){let t=new URL(e),{pathname:r}=t;return r&&r.startsWith("/_next/postponed")?(t.pathname=r.substring(16)||"/",t.toString()):e}},4448:(e,t)=>{"use strict";function handleSmoothScroll(e,t){if(void 0===t&&(t={}),t.onlyHashChange){e();return}let r=document.documentElement,n=r.style.scrollBehavior;r.style.scrollBehavior="auto",t.dontForceLayout||r.getClientRects(),e(),r.style.scrollBehavior=n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSmoothScroll",{enumerable:!0,get:function(){return handleSmoothScroll}})},4692:(e,t)=>{"use strict";function isBot(e){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isBot",{enumerable:!0,get:function(){return isBot}})},5525:(e,t)=>{"use strict";function parsePath(e){let t=e.indexOf("#"),r=e.indexOf("?"),n=r>-1&&(t<0||r<t);return n||t>-1?{pathname:e.substring(0,n?r:t),query:n?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return parsePath}})},6364:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return pathHasPrefix}});let n=r(5525);function pathHasPrefix(e,t){if("string"!=typeof e)return!1;let{pathname:r}=(0,n.parsePath)(e);return r===t||r.startsWith(t+"/")}},6923:(e,t)=>{"use strict";function removeTrailingSlash(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return removeTrailingSlash}})},392:(e,t)=>{"use strict";function isGroupSegment(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isGroupSegment",{enumerable:!0,get:function(){return isGroupSegment}})},5153:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createProxy",{enumerable:!0,get:function(){return a}});let n=r(5951),a=n.createClientModuleProxy},8730:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js")},7284:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js")},9195:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DYNAMIC_ERROR_CODE:function(){return r},DynamicServerError:function(){return DynamicServerError}});let r="DYNAMIC_SERVER_USAGE";let DynamicServerError=class DynamicServerError extends Error{constructor(e){super("Dynamic server usage: "+e),this.digest=r}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8165:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js")},2236:(e,t,r)=>{"use strict";function maybePostpone(e,t){if(!e.isStaticGeneration||!e.experimental.ppr)return;let n=r(3542);"function"==typeof n.unstable_postpone&&n.unstable_postpone(t)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"maybePostpone",{enumerable:!0,get:function(){return maybePostpone}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4009:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js")},9291:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return NotFound}});let n=r(5196),a=n._(r(3542)),o={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{display:"inline-block"},h1:{display:"inline-block",margin:"0 20px 0 0",padding:"0 23px 0 0",fontSize:24,fontWeight:500,verticalAlign:"top",lineHeight:"49px"},h2:{fontSize:14,fontWeight:400,lineHeight:"49px",margin:0}};function NotFound(){return a.default.createElement(a.default.Fragment,null,a.default.createElement("title",null,"404: This page could not be found."),a.default.createElement("div",{style:o.error},a.default.createElement("div",null,a.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}),a.default.createElement("h1",{className:"next-error-h1",style:o.h1},"404"),a.default.createElement("div",{style:o.desc},a.default.createElement("h2",{style:o.h2},"This page could not be found.")))))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5676:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js")},1263:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createSearchParamsBailoutProxy",{enumerable:!0,get:function(){return createSearchParamsBailoutProxy}});let n=r(3657);function createSearchParamsBailoutProxy(){return new Proxy({},{get(e,t){"string"==typeof t&&(0,n.staticGenerationBailout)("searchParams."+t)}})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3657:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationBailout",{enumerable:!0,get:function(){return staticGenerationBailout}});let n=r(9195),a=r(2236),o=r(5319);let StaticGenBailoutError=class StaticGenBailoutError extends Error{constructor(...e){super(...e),this.code="NEXT_STATIC_GEN_BAILOUT"}};function formatErrorMessage(e,t){let{dynamic:r,link:n}=t||{};return"Page"+(r?' with `dynamic = "'+r+'"`':"")+" couldn't be rendered statically because it used `"+e+"`."+(n?" See more info here: "+n:"")}let staticGenerationBailout=(e,t)=>{let r=o.staticGenerationAsyncStorage.getStore();if(!r)return!1;if(r.forceStatic)return!0;if(r.dynamicShouldError){var l;throw new StaticGenBailoutError(formatErrorMessage(e,{...t,dynamic:null!=(l=null==t?void 0:t.dynamic)?l:"error"}))}let u=formatErrorMessage(e,{...t,link:"https://nextjs.org/docs/messages/dynamic-server-error"});if((0,a.maybePostpone)(r,u),r.revalidate=0,(null==t?void 0:t.dynamic)||(r.staticPrefetchBailout=!0),r.isStaticGeneration){let t=new n.DynamicServerError(u);throw r.dynamicUsageDescription=e,r.dynamicUsageStack=t.stack,t}return!1};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7701:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js")},2564:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{renderToReadableStream:function(){return n.renderToReadableStream},decodeReply:function(){return n.decodeReply},decodeAction:function(){return n.decodeAction},decodeFormState:function(){return n.decodeFormState},AppRouter:function(){return a.default},LayoutRouter:function(){return o.default},RenderFromTemplateContext:function(){return l.default},staticGenerationAsyncStorage:function(){return u.staticGenerationAsyncStorage},requestAsyncStorage:function(){return i.requestAsyncStorage},actionAsyncStorage:function(){return s.actionAsyncStorage},staticGenerationBailout:function(){return c.staticGenerationBailout},createSearchParamsBailoutProxy:function(){return f.createSearchParamsBailoutProxy},serverHooks:function(){return p},preloadStyle:function(){return h.preloadStyle},preloadFont:function(){return h.preloadFont},preconnect:function(){return h.preconnect},taintObjectReference:function(){return _.taintObjectReference},StaticGenerationSearchParamsBailoutProvider:function(){return d.default},NotFoundBoundary:function(){return y}});let n=r(5951),a=_interop_require_default(r(8730)),o=_interop_require_default(r(8165)),l=_interop_require_default(r(5676)),u=r(5319),i=r(1877),s=r(5528),c=r(3657),d=_interop_require_default(r(7701)),f=r(1263),p=_interop_require_wildcard(r(9195)),h=r(8483),_=r(3369);function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(_getRequireWildcardCache=function(e){return e?r:t})(e)}function _interop_require_wildcard(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=_getRequireWildcardCache(t);if(r&&r.has(e))return r.get(e);var n={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var l=a?Object.getOwnPropertyDescriptor(e,o):null;l&&(l.get||l.set)?Object.defineProperty(n,o,l):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}let{NotFoundBoundary:y}=r(4009)},8483:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{preloadStyle:function(){return preloadStyle},preloadFont:function(){return preloadFont},preconnect:function(){return preconnect}});let n=_interop_require_default(r(8337));function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}function preloadStyle(e,t){let r={as:"style"};"string"==typeof t&&(r.crossOrigin=t),n.default.preload(e,r)}function preloadFont(e,t,r){let a={as:"font",type:t};"string"==typeof r&&(a.crossOrigin=r),n.default.preload(e,a)}function preconnect(e,t){n.default.preconnect(e,"string"==typeof t?{crossOrigin:t}:void 0)}},3369:(e,t,r)=>{"use strict";function notImplemented(){throw Error("Taint can only be used with the taint flag.")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{taintObjectReference:function(){return n},taintUniqueValue:function(){return a}}),r(3542);let n=notImplemented,a=notImplemented},6132:(e,t)=>{"use strict";var r;Object.defineProperty(t,"x",{enumerable:!0,get:function(){return r}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE"}(r||(r={}))},7096:(e,t,r)=>{"use strict";e.exports=r(399)},8337:(e,t,r)=>{"use strict";e.exports=r(7096).vendored["react-rsc"].ReactDOM},4656:(e,t,r)=>{"use strict";e.exports=r(7096).vendored["react-rsc"].ReactJsxRuntime},5951:(e,t,r)=>{"use strict";e.exports=r(7096).vendored["react-rsc"].ReactServerDOMWebpackServerEdge},3542:(e,t,r)=>{"use strict";e.exports=r(7096).vendored["react-rsc"].React},5082:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXT_QUERY_PARAM_PREFIX:function(){return r},PRERENDER_REVALIDATE_HEADER:function(){return n},PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER:function(){return a},NEXT_DID_POSTPONE_HEADER:function(){return o},NEXT_CACHE_TAGS_HEADER:function(){return l},NEXT_CACHE_SOFT_TAGS_HEADER:function(){return u},NEXT_CACHE_REVALIDATED_TAGS_HEADER:function(){return i},NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER:function(){return s},NEXT_CACHE_TAG_MAX_LENGTH:function(){return c},NEXT_CACHE_SOFT_TAG_MAX_LENGTH:function(){return d},NEXT_CACHE_IMPLICIT_TAG_ID:function(){return f},CACHE_ONE_YEAR:function(){return p},MIDDLEWARE_FILENAME:function(){return h},MIDDLEWARE_LOCATION_REGEXP:function(){return _},INSTRUMENTATION_HOOK_FILENAME:function(){return y},PAGES_DIR_ALIAS:function(){return m},DOT_NEXT_ALIAS:function(){return g},ROOT_DIR_ALIAS:function(){return b},APP_DIR_ALIAS:function(){return v},RSC_MOD_REF_PROXY_ALIAS:function(){return P},RSC_ACTION_VALIDATE_ALIAS:function(){return R},RSC_ACTION_PROXY_ALIAS:function(){return S},RSC_ACTION_ENCRYPTION_ALIAS:function(){return E},RSC_ACTION_CLIENT_WRAPPER_ALIAS:function(){return O},PUBLIC_DIR_MIDDLEWARE_CONFLICT:function(){return T},SSG_GET_INITIAL_PROPS_CONFLICT:function(){return j},SERVER_PROPS_GET_INIT_PROPS_CONFLICT:function(){return M},SERVER_PROPS_SSG_CONFLICT:function(){return x},STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR:function(){return A},SERVER_PROPS_EXPORT_ERROR:function(){return C},GSP_NO_RETURNED_VALUE:function(){return N},GSSP_NO_RETURNED_VALUE:function(){return w},UNSTABLE_REVALIDATE_RENAME_ERROR:function(){return I},GSSP_COMPONENT_MEMBER_ERROR:function(){return F},NON_STANDARD_NODE_ENV:function(){return D},SSG_FALLBACK_EXPORT_ERROR:function(){return L},ESLINT_DEFAULT_DIRS:function(){return U},ESLINT_PROMPT_VALUES:function(){return H},SERVER_RUNTIME:function(){return B},WEBPACK_LAYERS:function(){return G},WEBPACK_RESOURCE_QUERIES:function(){return W}});let r="nxtP",n="x-prerender-revalidate",a="x-prerender-revalidate-if-generated",o="x-nextjs-postponed",l="x-next-cache-tags",u="x-next-cache-soft-tags",i="x-next-revalidated-tags",s="x-next-revalidate-tag-token",c=256,d=1024,f="_N_T_",p=31536e3,h="middleware",_=`(?:src/)?${h}`,y="instrumentation",m="private-next-pages",g="private-dot-next",b="private-next-root-dir",v="private-next-app-dir",P="private-next-rsc-mod-ref-proxy",R="private-next-rsc-action-validate",S="private-next-rsc-action-proxy",E="private-next-rsc-action-encryption",O="private-next-rsc-action-client-wrapper",T="You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict",j="You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps",M="You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.",x="You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps",A="can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props",C="pages with `getServerSideProps` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export",N="Your `getStaticProps` function did not return an object. Did you forget to add a `return`?",w="Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?",I="The `unstable_revalidate` property is available for general use.\nPlease use `revalidate` instead.",F="can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member",D='You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env',L="Pages with `fallback` enabled in `getStaticPaths` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export",U=["app","pages","components","lib","src"],H=[{title:"Strict",recommended:!0,config:{extends:"next/core-web-vitals"}},{title:"Base",config:{extends:"next"}},{title:"Cancel",config:null}],B={edge:"edge",experimentalEdge:"experimental-edge",nodejs:"nodejs"},k={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",api:"api",middleware:"middleware",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",appMetadataRoute:"app-metadata-route",appRouteHandler:"app-route-handler"},G={...k,GROUP:{server:[k.reactServerComponents,k.actionBrowser,k.appMetadataRoute,k.appRouteHandler],nonClientServerTarget:[k.middleware,k.api],app:[k.reactServerComponents,k.actionBrowser,k.appMetadataRoute,k.appRouteHandler,k.serverSideRendering,k.appPagesBrowser]}},W={edgeSSREntry:"__next_edge_ssr_entry__",metadata:"__next_metadata__",metadataRoute:"__next_metadata_route__",metadataImageMeta:"__next_metadata_image_meta__"}},2290:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentParam",{enumerable:!0,get:function(){return getSegmentParam}});let n=r(4265);function getSegmentParam(e){let t=n.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t));return(t&&(e=e.slice(t.length)),e.startsWith("[[...")&&e.endsWith("]]"))?{type:"optional-catchall",param:e.slice(5,-2)}:e.startsWith("[...")&&e.endsWith("]")?{type:"catchall",param:e.slice(4,-1)}:e.startsWith("[")&&e.endsWith("]")?{type:"dynamic",param:e.slice(1,-1)}:null}},4265:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return a},isInterceptionRouteAppPath:function(){return isInterceptionRouteAppPath},extractInterceptionRouteInformation:function(){return extractInterceptionRouteInformation}});let n=r(8321),a=["(..)(..)","(.)","(..)","(...)"];function isInterceptionRouteAppPath(e){return void 0!==e.split("/").find(e=>a.find(t=>e.startsWith(t)))}function extractInterceptionRouteInformation(e){let t,r,o;for(let n of e.split("/"))if(r=a.find(e=>n.startsWith(e))){[t,o]=e.split(r,2);break}if(!t||!r||!o)throw Error(`Invalid interception route: ${e}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`);switch(t=(0,n.normalizeAppPath)(t),r){case"(.)":o="/"===t?`/${o}`:t+"/"+o;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);o=t.split("/").slice(0,-1).concat(o).join("/");break;case"(...)":o="/"+o;break;case"(..)(..)":let l=t.split("/");if(l.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);o=l.slice(0,-2).concat(o).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:o}}},316:(e,t,r)=>{"use strict";e.exports=r(399)},2428:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.AppRouterContext},1736:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.HooksClientContext},5753:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.ServerInsertedHtml},8908:(e,t,r)=>{"use strict";e.exports=r(316).vendored["react-ssr"].ReactDOM},2623:(e,t,r)=>{"use strict";e.exports=r(316).vendored["react-ssr"].ReactServerDOMWebpackClientEdge},9885:(e,t,r)=>{"use strict";e.exports=r(316).vendored["react-ssr"].React},3592:(e,t,r)=>{"use strict";function _class_private_field_loose_base(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}r.r(t),r.d(t,{_:()=>_class_private_field_loose_base,_class_private_field_loose_base:()=>_class_private_field_loose_base})},4941:(e,t,r)=>{"use strict";r.r(t),r.d(t,{_:()=>_class_private_field_loose_key,_class_private_field_loose_key:()=>_class_private_field_loose_key});var n=0;function _class_private_field_loose_key(e){return"__private_"+n+++"_"+e}},85:(e,t,r)=>{"use strict";function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:()=>_interop_require_default,_interop_require_default:()=>_interop_require_default})},8425:(e,t,r)=>{"use strict";function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(_getRequireWildcardCache=function(e){return e?r:t})(e)}function _interop_require_wildcard(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=_getRequireWildcardCache(t);if(r&&r.has(e))return r.get(e);var n={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var l=a?Object.getOwnPropertyDescriptor(e,o):null;l&&(l.get||l.set)?Object.defineProperty(n,o,l):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}r.r(t),r.d(t,{_:()=>_interop_require_wildcard,_interop_require_wildcard:()=>_interop_require_wildcard})},5196:(e,t,r)=>{"use strict";function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:()=>_interop_require_default,_interop_require_default:()=>_interop_require_default})}}; \ No newline at end of file diff --git a/.next/server/chunks/864.js b/.next/server/chunks/864.js deleted file mode 100644 index 0c7c17c..0000000 --- a/.next/server/chunks/864.js +++ /dev/null @@ -1,267004 +0,0 @@ -exports.id = 864; -exports.ids = [864]; -exports.modules = { - -/***/ 5319: -/***/ ((module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "default", ({ - enumerable: true, - get: function() { - return dynamic; - } -})); -const _interop_require_default = __webpack_require__(5967); -const _react = /*#__PURE__*/ _interop_require_default._(__webpack_require__(8038)); -const _loadable = /*#__PURE__*/ _interop_require_default._(__webpack_require__(5727)); -// Normalize loader to return the module as form { default: Component } for `React.lazy`. -// Also for backward compatible since next/dynamic allows to resolve a component directly with loader -// Client component reference proxy need to be converted to a module. -function convertModule(mod) { - return { - default: (mod == null ? void 0 : mod.default) || mod - }; -} -function dynamic(dynamicOptions, options) { - const loadableFn = _loadable.default; - const loadableOptions = { - // A loading component is not required, so we default it - loading: (param)=>{ - let { error , isLoading , pastDelay } = param; - if (!pastDelay) return null; - if (false) {} - return null; - } - }; - if (typeof dynamicOptions === "function") { - loadableOptions.loader = dynamicOptions; - } - Object.assign(loadableOptions, options); - const loaderFn = loadableOptions.loader; - const loader = ()=>loaderFn != null ? loaderFn().then(convertModule) : Promise.resolve(convertModule(()=>null)); - return loadableFn({ - ...loadableOptions, - loader: loader - }); -} -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=app-dynamic.js.map - - -/***/ }), - -/***/ 5727: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "default", ({ - enumerable: true, - get: function() { - return _default; - } -})); -const _interop_require_default = __webpack_require__(5967); -const _react = /*#__PURE__*/ _interop_require_default._(__webpack_require__(8038)); -const _dynamicnossr = __webpack_require__(701); -function Loadable(options) { - const opts = Object.assign({ - loader: null, - loading: null, - ssr: true - }, options); - opts.lazy = /*#__PURE__*/ _react.default.lazy(opts.loader); - function LoadableComponent(props) { - const Loading = opts.loading; - const fallbackElement = /*#__PURE__*/ _react.default.createElement(Loading, { - isLoading: true, - pastDelay: true, - error: null - }); - const Wrap = opts.ssr ? _react.default.Fragment : _dynamicnossr.NoSSR; - const Lazy = opts.lazy; - return /*#__PURE__*/ _react.default.createElement(_react.default.Suspense, { - fallback: fallbackElement - }, /*#__PURE__*/ _react.default.createElement(Wrap, null, /*#__PURE__*/ _react.default.createElement(Lazy, props))); - } - LoadableComponent.displayName = "LoadableComponent"; - return LoadableComponent; -} -const _default = Loadable; //# sourceMappingURL=loadable.js.map - - -/***/ }), - -/***/ 1853: -/***/ (function(__unused_webpack_module, exports) { - -/*! Tweakpane 3.1.10 (c) 2016 cocopon, licensed under the MIT license. */ -(function (global, factory) { - true ? factory(exports) : - 0; -})(this, (function (exports) { 'use strict'; - - /*** - * A simple semantic versioning perser. - */ - class Semver { - /** - * @hidden - */ - constructor(text) { - const [core, prerelease] = text.split('-'); - const coreComps = core.split('.'); - this.major = parseInt(coreComps[0], 10); - this.minor = parseInt(coreComps[1], 10); - this.patch = parseInt(coreComps[2], 10); - this.prerelease = prerelease !== null && prerelease !== void 0 ? prerelease : null; - } - toString() { - const core = [this.major, this.minor, this.patch].join('.'); - return this.prerelease !== null ? [core, this.prerelease].join('-') : core; - } - } - - class BladeApi { - constructor(controller) { - this.controller_ = controller; - } - get element() { - return this.controller_.view.element; - } - get disabled() { - return this.controller_.viewProps.get('disabled'); - } - set disabled(disabled) { - this.controller_.viewProps.set('disabled', disabled); - } - get hidden() { - return this.controller_.viewProps.get('hidden'); - } - set hidden(hidden) { - this.controller_.viewProps.set('hidden', hidden); - } - dispose() { - this.controller_.viewProps.set('disposed', true); - } - } - - class TpEvent { - constructor(target) { - this.target = target; - } - } - class TpChangeEvent extends TpEvent { - constructor(target, value, presetKey, last) { - super(target); - this.value = value; - this.presetKey = presetKey; - this.last = last !== null && last !== void 0 ? last : true; - } - } - class TpUpdateEvent extends TpEvent { - constructor(target, value, presetKey) { - super(target); - this.value = value; - this.presetKey = presetKey; - } - } - class TpFoldEvent extends TpEvent { - constructor(target, expanded) { - super(target); - this.expanded = expanded; - } - } - class TpTabSelectEvent extends TpEvent { - constructor(target, index) { - super(target); - this.index = index; - } - } - - function forceCast(v) { - return v; - } - function isEmpty(value) { - return value === null || value === undefined; - } - function deepEqualsArray(a1, a2) { - if (a1.length !== a2.length) { - return false; - } - for (let i = 0; i < a1.length; i++) { - if (a1[i] !== a2[i]) { - return false; - } - } - return true; - } - function isPropertyWritable(obj, key) { - let target = obj; - do { - const d = Object.getOwnPropertyDescriptor(target, key); - if (d && (d.set !== undefined || d.writable === true)) { - return true; - } - target = Object.getPrototypeOf(target); - } while (target !== null); - return false; - } - - const CREATE_MESSAGE_MAP = { - alreadydisposed: () => 'View has been already disposed', - invalidparams: (context) => `Invalid parameters for '${context.name}'`, - nomatchingcontroller: (context) => `No matching controller for '${context.key}'`, - nomatchingview: (context) => `No matching view for '${JSON.stringify(context.params)}'`, - notbindable: () => `Value is not bindable`, - propertynotfound: (context) => `Property '${context.name}' not found`, - shouldneverhappen: () => 'This error should never happen', - }; - class TpError { - static alreadyDisposed() { - return new TpError({ type: 'alreadydisposed' }); - } - static notBindable() { - return new TpError({ - type: 'notbindable', - }); - } - static propertyNotFound(name) { - return new TpError({ - type: 'propertynotfound', - context: { - name: name, - }, - }); - } - static shouldNeverHappen() { - return new TpError({ type: 'shouldneverhappen' }); - } - constructor(config) { - var _a; - this.message = - (_a = CREATE_MESSAGE_MAP[config.type](forceCast(config.context))) !== null && _a !== void 0 ? _a : 'Unexpected error'; - this.name = this.constructor.name; - this.stack = new Error(this.message).stack; - this.type = config.type; - } - } - - class BindingTarget { - constructor(obj, key, opt_id) { - this.obj_ = obj; - this.key_ = key; - this.presetKey_ = opt_id !== null && opt_id !== void 0 ? opt_id : key; - } - static isBindable(obj) { - if (obj === null) { - return false; - } - if (typeof obj !== 'object' && typeof obj !== 'function') { - return false; - } - return true; - } - get key() { - return this.key_; - } - get presetKey() { - return this.presetKey_; - } - read() { - return this.obj_[this.key_]; - } - write(value) { - this.obj_[this.key_] = value; - } - writeProperty(name, value) { - const valueObj = this.read(); - if (!BindingTarget.isBindable(valueObj)) { - throw TpError.notBindable(); - } - if (!(name in valueObj)) { - throw TpError.propertyNotFound(name); - } - valueObj[name] = value; - } - } - - class ButtonApi extends BladeApi { - get label() { - return this.controller_.props.get('label'); - } - set label(label) { - this.controller_.props.set('label', label); - } - get title() { - var _a; - return (_a = this.controller_.valueController.props.get('title')) !== null && _a !== void 0 ? _a : ''; - } - set title(title) { - this.controller_.valueController.props.set('title', title); - } - on(eventName, handler) { - const bh = handler.bind(this); - const emitter = this.controller_.valueController.emitter; - emitter.on(eventName, () => { - bh(new TpEvent(this)); - }); - return this; - } - } - - class Emitter { - constructor() { - this.observers_ = {}; - } - on(eventName, handler) { - let observers = this.observers_[eventName]; - if (!observers) { - observers = this.observers_[eventName] = []; - } - observers.push({ - handler: handler, - }); - return this; - } - off(eventName, handler) { - const observers = this.observers_[eventName]; - if (observers) { - this.observers_[eventName] = observers.filter((observer) => { - return observer.handler !== handler; - }); - } - return this; - } - emit(eventName, event) { - const observers = this.observers_[eventName]; - if (!observers) { - return; - } - observers.forEach((observer) => { - observer.handler(event); - }); - } - } - - const PREFIX = 'tp'; - function ClassName(viewName) { - const fn = (opt_elementName, opt_modifier) => { - return [ - PREFIX, - '-', - viewName, - 'v', - opt_elementName ? `_${opt_elementName}` : '', - opt_modifier ? `-${opt_modifier}` : '', - ].join(''); - }; - return fn; - } - - function compose(h1, h2) { - return (input) => h2(h1(input)); - } - function extractValue(ev) { - return ev.rawValue; - } - function bindValue(value, applyValue) { - value.emitter.on('change', compose(extractValue, applyValue)); - applyValue(value.rawValue); - } - function bindValueMap(valueMap, key, applyValue) { - bindValue(valueMap.value(key), applyValue); - } - - function applyClass(elem, className, active) { - if (active) { - elem.classList.add(className); - } - else { - elem.classList.remove(className); - } - } - function valueToClassName(elem, className) { - return (value) => { - applyClass(elem, className, value); - }; - } - function bindValueToTextContent(value, elem) { - bindValue(value, (text) => { - elem.textContent = text !== null && text !== void 0 ? text : ''; - }); - } - - const className$q = ClassName('btn'); - class ButtonView { - constructor(doc, config) { - this.element = doc.createElement('div'); - this.element.classList.add(className$q()); - config.viewProps.bindClassModifiers(this.element); - const buttonElem = doc.createElement('button'); - buttonElem.classList.add(className$q('b')); - config.viewProps.bindDisabled(buttonElem); - this.element.appendChild(buttonElem); - this.buttonElement = buttonElem; - const titleElem = doc.createElement('div'); - titleElem.classList.add(className$q('t')); - bindValueToTextContent(config.props.value('title'), titleElem); - this.buttonElement.appendChild(titleElem); - } - } - - class ButtonController { - constructor(doc, config) { - this.emitter = new Emitter(); - this.onClick_ = this.onClick_.bind(this); - this.props = config.props; - this.viewProps = config.viewProps; - this.view = new ButtonView(doc, { - props: this.props, - viewProps: this.viewProps, - }); - this.view.buttonElement.addEventListener('click', this.onClick_); - } - onClick_() { - this.emitter.emit('click', { - sender: this, - }); - } - } - - class BoundValue { - constructor(initialValue, config) { - var _a; - this.constraint_ = config === null || config === void 0 ? void 0 : config.constraint; - this.equals_ = (_a = config === null || config === void 0 ? void 0 : config.equals) !== null && _a !== void 0 ? _a : ((v1, v2) => v1 === v2); - this.emitter = new Emitter(); - this.rawValue_ = initialValue; - } - get constraint() { - return this.constraint_; - } - get rawValue() { - return this.rawValue_; - } - set rawValue(rawValue) { - this.setRawValue(rawValue, { - forceEmit: false, - last: true, - }); - } - setRawValue(rawValue, options) { - const opts = options !== null && options !== void 0 ? options : { - forceEmit: false, - last: true, - }; - const constrainedValue = this.constraint_ - ? this.constraint_.constrain(rawValue) - : rawValue; - const prevValue = this.rawValue_; - const changed = !this.equals_(prevValue, constrainedValue); - if (!changed && !opts.forceEmit) { - return; - } - this.emitter.emit('beforechange', { - sender: this, - }); - this.rawValue_ = constrainedValue; - this.emitter.emit('change', { - options: opts, - previousRawValue: prevValue, - rawValue: constrainedValue, - sender: this, - }); - } - } - - class PrimitiveValue { - constructor(initialValue) { - this.emitter = new Emitter(); - this.value_ = initialValue; - } - get rawValue() { - return this.value_; - } - set rawValue(value) { - this.setRawValue(value, { - forceEmit: false, - last: true, - }); - } - setRawValue(value, options) { - const opts = options !== null && options !== void 0 ? options : { - forceEmit: false, - last: true, - }; - const prevValue = this.value_; - if (prevValue === value && !opts.forceEmit) { - return; - } - this.emitter.emit('beforechange', { - sender: this, - }); - this.value_ = value; - this.emitter.emit('change', { - options: opts, - previousRawValue: prevValue, - rawValue: this.value_, - sender: this, - }); - } - } - - function createValue(initialValue, config) { - const constraint = config === null || config === void 0 ? void 0 : config.constraint; - const equals = config === null || config === void 0 ? void 0 : config.equals; - if (!constraint && !equals) { - return new PrimitiveValue(initialValue); - } - return new BoundValue(initialValue, config); - } - - class ValueMap { - constructor(valueMap) { - this.emitter = new Emitter(); - this.valMap_ = valueMap; - for (const key in this.valMap_) { - const v = this.valMap_[key]; - v.emitter.on('change', () => { - this.emitter.emit('change', { - key: key, - sender: this, - }); - }); - } - } - static createCore(initialValue) { - const keys = Object.keys(initialValue); - return keys.reduce((o, key) => { - return Object.assign(o, { - [key]: createValue(initialValue[key]), - }); - }, {}); - } - static fromObject(initialValue) { - const core = this.createCore(initialValue); - return new ValueMap(core); - } - get(key) { - return this.valMap_[key].rawValue; - } - set(key, value) { - this.valMap_[key].rawValue = value; - } - value(key) { - return this.valMap_[key]; - } - } - - function parseObject(value, keyToParserMap) { - const keys = Object.keys(keyToParserMap); - const result = keys.reduce((tmp, key) => { - if (tmp === undefined) { - return undefined; - } - const parser = keyToParserMap[key]; - const result = parser(value[key]); - return result.succeeded - ? Object.assign(Object.assign({}, tmp), { [key]: result.value }) : undefined; - }, {}); - return forceCast(result); - } - function parseArray(value, parseItem) { - return value.reduce((tmp, item) => { - if (tmp === undefined) { - return undefined; - } - const result = parseItem(item); - if (!result.succeeded || result.value === undefined) { - return undefined; - } - return [...tmp, result.value]; - }, []); - } - function isObject(value) { - if (value === null) { - return false; - } - return typeof value === 'object'; - } - function createParamsParserBuilder(parse) { - return (optional) => (v) => { - if (!optional && v === undefined) { - return { - succeeded: false, - value: undefined, - }; - } - if (optional && v === undefined) { - return { - succeeded: true, - value: undefined, - }; - } - const result = parse(v); - return result !== undefined - ? { - succeeded: true, - value: result, - } - : { - succeeded: false, - value: undefined, - }; - }; - } - function createParamsParserBuilders(optional) { - return { - custom: (parse) => createParamsParserBuilder(parse)(optional), - boolean: createParamsParserBuilder((v) => typeof v === 'boolean' ? v : undefined)(optional), - number: createParamsParserBuilder((v) => typeof v === 'number' ? v : undefined)(optional), - string: createParamsParserBuilder((v) => typeof v === 'string' ? v : undefined)(optional), - function: createParamsParserBuilder((v) => - typeof v === 'function' ? v : undefined)(optional), - constant: (value) => createParamsParserBuilder((v) => (v === value ? value : undefined))(optional), - raw: createParamsParserBuilder((v) => v)(optional), - object: (keyToParserMap) => createParamsParserBuilder((v) => { - if (!isObject(v)) { - return undefined; - } - return parseObject(v, keyToParserMap); - })(optional), - array: (itemParser) => createParamsParserBuilder((v) => { - if (!Array.isArray(v)) { - return undefined; - } - return parseArray(v, itemParser); - })(optional), - }; - } - const ParamsParsers = { - optional: createParamsParserBuilders(true), - required: createParamsParserBuilders(false), - }; - function parseParams(value, keyToParserMap) { - const result = ParamsParsers.required.object(keyToParserMap)(value); - return result.succeeded ? result.value : undefined; - } - - function warnMissing(info) { - console.warn([ - `Missing '${info.key}' of ${info.target} in ${info.place}.`, - 'Please rebuild plugins with the latest core package.', - ].join(' ')); - } - - function disposeElement(elem) { - if (elem && elem.parentElement) { - elem.parentElement.removeChild(elem); - } - return null; - } - - class ReadonlyValue { - constructor(value) { - this.value_ = value; - } - static create(value) { - return [ - new ReadonlyValue(value), - (rawValue, options) => { - value.setRawValue(rawValue, options); - }, - ]; - } - get emitter() { - return this.value_.emitter; - } - get rawValue() { - return this.value_.rawValue; - } - } - - const className$p = ClassName(''); - function valueToModifier(elem, modifier) { - return valueToClassName(elem, className$p(undefined, modifier)); - } - class ViewProps extends ValueMap { - constructor(valueMap) { - var _a; - super(valueMap); - this.onDisabledChange_ = this.onDisabledChange_.bind(this); - this.onParentChange_ = this.onParentChange_.bind(this); - this.onParentGlobalDisabledChange_ = - this.onParentGlobalDisabledChange_.bind(this); - [this.globalDisabled_, this.setGlobalDisabled_] = ReadonlyValue.create(createValue(this.getGlobalDisabled_())); - this.value('disabled').emitter.on('change', this.onDisabledChange_); - this.value('parent').emitter.on('change', this.onParentChange_); - (_a = this.get('parent')) === null || _a === void 0 ? void 0 : _a.globalDisabled.emitter.on('change', this.onParentGlobalDisabledChange_); - } - static create(opt_initialValue) { - var _a, _b, _c; - const initialValue = opt_initialValue !== null && opt_initialValue !== void 0 ? opt_initialValue : {}; - return new ViewProps(ValueMap.createCore({ - disabled: (_a = initialValue.disabled) !== null && _a !== void 0 ? _a : false, - disposed: false, - hidden: (_b = initialValue.hidden) !== null && _b !== void 0 ? _b : false, - parent: (_c = initialValue.parent) !== null && _c !== void 0 ? _c : null, - })); - } - get globalDisabled() { - return this.globalDisabled_; - } - bindClassModifiers(elem) { - bindValue(this.globalDisabled_, valueToModifier(elem, 'disabled')); - bindValueMap(this, 'hidden', valueToModifier(elem, 'hidden')); - } - bindDisabled(target) { - bindValue(this.globalDisabled_, (disabled) => { - target.disabled = disabled; - }); - } - bindTabIndex(elem) { - bindValue(this.globalDisabled_, (disabled) => { - elem.tabIndex = disabled ? -1 : 0; - }); - } - handleDispose(callback) { - this.value('disposed').emitter.on('change', (disposed) => { - if (disposed) { - callback(); - } - }); - } - getGlobalDisabled_() { - const parent = this.get('parent'); - const parentDisabled = parent ? parent.globalDisabled.rawValue : false; - return parentDisabled || this.get('disabled'); - } - updateGlobalDisabled_() { - this.setGlobalDisabled_(this.getGlobalDisabled_()); - } - onDisabledChange_() { - this.updateGlobalDisabled_(); - } - onParentGlobalDisabledChange_() { - this.updateGlobalDisabled_(); - } - onParentChange_(ev) { - var _a; - const prevParent = ev.previousRawValue; - prevParent === null || prevParent === void 0 ? void 0 : prevParent.globalDisabled.emitter.off('change', this.onParentGlobalDisabledChange_); - (_a = this.get('parent')) === null || _a === void 0 ? void 0 : _a.globalDisabled.emitter.on('change', this.onParentGlobalDisabledChange_); - this.updateGlobalDisabled_(); - } - } - - function getAllBladePositions() { - return ['veryfirst', 'first', 'last', 'verylast']; - } - - const className$o = ClassName(''); - const POS_TO_CLASS_NAME_MAP = { - veryfirst: 'vfst', - first: 'fst', - last: 'lst', - verylast: 'vlst', - }; - class BladeController { - constructor(config) { - this.parent_ = null; - this.blade = config.blade; - this.view = config.view; - this.viewProps = config.viewProps; - const elem = this.view.element; - this.blade.value('positions').emitter.on('change', () => { - getAllBladePositions().forEach((pos) => { - elem.classList.remove(className$o(undefined, POS_TO_CLASS_NAME_MAP[pos])); - }); - this.blade.get('positions').forEach((pos) => { - elem.classList.add(className$o(undefined, POS_TO_CLASS_NAME_MAP[pos])); - }); - }); - this.viewProps.handleDispose(() => { - disposeElement(elem); - }); - } - get parent() { - return this.parent_; - } - set parent(parent) { - this.parent_ = parent; - if (!('parent' in this.viewProps.valMap_)) { - warnMissing({ - key: 'parent', - target: ViewProps.name, - place: 'BladeController.parent', - }); - return; - } - this.viewProps.set('parent', this.parent_ ? this.parent_.viewProps : null); - } - } - - const SVG_NS = 'http://www.w3.org/2000/svg'; - function forceReflow(element) { - element.offsetHeight; - } - function disableTransitionTemporarily(element, callback) { - const t = element.style.transition; - element.style.transition = 'none'; - callback(); - element.style.transition = t; - } - function supportsTouch(doc) { - return doc.ontouchstart !== undefined; - } - function getGlobalObject() { - return globalThis; - } - function getWindowDocument() { - const globalObj = forceCast(getGlobalObject()); - return globalObj.document; - } - function getCanvasContext(canvasElement) { - const win = canvasElement.ownerDocument.defaultView; - if (!win) { - return null; - } - const isBrowser = 'document' in win; - return isBrowser - ? canvasElement.getContext('2d', { - willReadFrequently: true, - }) - : null; - } - const ICON_ID_TO_INNER_HTML_MAP = { - check: '<path d="M2 8l4 4l8 -8"/>', - dropdown: '<path d="M5 7h6l-3 3 z"/>', - p2dpad: '<path d="M8 4v8"/><path d="M4 8h8"/><circle cx="12" cy="12" r="1.2"/>', - }; - function createSvgIconElement(document, iconId) { - const elem = document.createElementNS(SVG_NS, 'svg'); - elem.innerHTML = ICON_ID_TO_INNER_HTML_MAP[iconId]; - return elem; - } - function insertElementAt(parentElement, element, index) { - parentElement.insertBefore(element, parentElement.children[index]); - } - function removeElement(element) { - if (element.parentElement) { - element.parentElement.removeChild(element); - } - } - function removeChildElements(element) { - while (element.children.length > 0) { - element.removeChild(element.children[0]); - } - } - function removeChildNodes(element) { - while (element.childNodes.length > 0) { - element.removeChild(element.childNodes[0]); - } - } - function findNextTarget(ev) { - if (ev.relatedTarget) { - return forceCast(ev.relatedTarget); - } - if ('explicitOriginalTarget' in ev) { - return ev.explicitOriginalTarget; - } - return null; - } - - const className$n = ClassName('lbl'); - function createLabelNode(doc, label) { - const frag = doc.createDocumentFragment(); - const lineNodes = label.split('\n').map((line) => { - return doc.createTextNode(line); - }); - lineNodes.forEach((lineNode, index) => { - if (index > 0) { - frag.appendChild(doc.createElement('br')); - } - frag.appendChild(lineNode); - }); - return frag; - } - class LabelView { - constructor(doc, config) { - this.element = doc.createElement('div'); - this.element.classList.add(className$n()); - config.viewProps.bindClassModifiers(this.element); - const labelElem = doc.createElement('div'); - labelElem.classList.add(className$n('l')); - bindValueMap(config.props, 'label', (value) => { - if (isEmpty(value)) { - this.element.classList.add(className$n(undefined, 'nol')); - } - else { - this.element.classList.remove(className$n(undefined, 'nol')); - removeChildNodes(labelElem); - labelElem.appendChild(createLabelNode(doc, value)); - } - }); - this.element.appendChild(labelElem); - this.labelElement = labelElem; - const valueElem = doc.createElement('div'); - valueElem.classList.add(className$n('v')); - this.element.appendChild(valueElem); - this.valueElement = valueElem; - } - } - - class LabelController extends BladeController { - constructor(doc, config) { - const viewProps = config.valueController.viewProps; - super(Object.assign(Object.assign({}, config), { view: new LabelView(doc, { - props: config.props, - viewProps: viewProps, - }), viewProps: viewProps })); - this.props = config.props; - this.valueController = config.valueController; - this.view.valueElement.appendChild(this.valueController.view.element); - } - } - - const ButtonBladePlugin = { - id: 'button', - type: 'blade', - accept(params) { - const p = ParamsParsers; - const result = parseParams(params, { - title: p.required.string, - view: p.required.constant('button'), - label: p.optional.string, - }); - return result ? { params: result } : null; - }, - controller(args) { - return new LabelController(args.document, { - blade: args.blade, - props: ValueMap.fromObject({ - label: args.params.label, - }), - valueController: new ButtonController(args.document, { - props: ValueMap.fromObject({ - title: args.params.title, - }), - viewProps: args.viewProps, - }), - }); - }, - api(args) { - if (!(args.controller instanceof LabelController)) { - return null; - } - if (!(args.controller.valueController instanceof ButtonController)) { - return null; - } - return new ButtonApi(args.controller); - }, - }; - - class ValueBladeController extends BladeController { - constructor(config) { - super(config); - this.value = config.value; - } - } - - function createBlade() { - return new ValueMap({ - positions: createValue([], { - equals: deepEqualsArray, - }), - }); - } - - class Foldable extends ValueMap { - constructor(valueMap) { - super(valueMap); - } - static create(expanded) { - const coreObj = { - completed: true, - expanded: expanded, - expandedHeight: null, - shouldFixHeight: false, - temporaryExpanded: null, - }; - const core = ValueMap.createCore(coreObj); - return new Foldable(core); - } - get styleExpanded() { - var _a; - return (_a = this.get('temporaryExpanded')) !== null && _a !== void 0 ? _a : this.get('expanded'); - } - get styleHeight() { - if (!this.styleExpanded) { - return '0'; - } - const exHeight = this.get('expandedHeight'); - if (this.get('shouldFixHeight') && !isEmpty(exHeight)) { - return `${exHeight}px`; - } - return 'auto'; - } - bindExpandedClass(elem, expandedClassName) { - const onExpand = () => { - const expanded = this.styleExpanded; - if (expanded) { - elem.classList.add(expandedClassName); - } - else { - elem.classList.remove(expandedClassName); - } - }; - bindValueMap(this, 'expanded', onExpand); - bindValueMap(this, 'temporaryExpanded', onExpand); - } - cleanUpTransition() { - this.set('shouldFixHeight', false); - this.set('expandedHeight', null); - this.set('completed', true); - } - } - function computeExpandedFolderHeight(folder, containerElement) { - let height = 0; - disableTransitionTemporarily(containerElement, () => { - folder.set('expandedHeight', null); - folder.set('temporaryExpanded', true); - forceReflow(containerElement); - height = containerElement.clientHeight; - folder.set('temporaryExpanded', null); - forceReflow(containerElement); - }); - return height; - } - function applyHeight(foldable, elem) { - elem.style.height = foldable.styleHeight; - } - function bindFoldable(foldable, elem) { - foldable.value('expanded').emitter.on('beforechange', () => { - foldable.set('completed', false); - if (isEmpty(foldable.get('expandedHeight'))) { - const h = computeExpandedFolderHeight(foldable, elem); - if (h > 0) { - foldable.set('expandedHeight', h); - } - } - foldable.set('shouldFixHeight', true); - forceReflow(elem); - }); - foldable.emitter.on('change', () => { - applyHeight(foldable, elem); - }); - applyHeight(foldable, elem); - elem.addEventListener('transitionend', (ev) => { - if (ev.propertyName !== 'height') { - return; - } - foldable.cleanUpTransition(); - }); - } - - class RackLikeApi extends BladeApi { - constructor(controller, rackApi) { - super(controller); - this.rackApi_ = rackApi; - } - } - - function addButtonAsBlade(api, params) { - return api.addBlade(Object.assign(Object.assign({}, params), { view: 'button' })); - } - function addFolderAsBlade(api, params) { - return api.addBlade(Object.assign(Object.assign({}, params), { view: 'folder' })); - } - function addSeparatorAsBlade(api, opt_params) { - const params = opt_params !== null && opt_params !== void 0 ? opt_params : {}; - return api.addBlade(Object.assign(Object.assign({}, params), { view: 'separator' })); - } - function addTabAsBlade(api, params) { - return api.addBlade(Object.assign(Object.assign({}, params), { view: 'tab' })); - } - - class NestedOrderedSet { - constructor(extract) { - this.emitter = new Emitter(); - this.items_ = []; - this.cache_ = new Set(); - this.onSubListAdd_ = this.onSubListAdd_.bind(this); - this.onSubListRemove_ = this.onSubListRemove_.bind(this); - this.extract_ = extract; - } - get items() { - return this.items_; - } - allItems() { - return Array.from(this.cache_); - } - find(callback) { - for (const item of this.allItems()) { - if (callback(item)) { - return item; - } - } - return null; - } - includes(item) { - return this.cache_.has(item); - } - add(item, opt_index) { - if (this.includes(item)) { - throw TpError.shouldNeverHappen(); - } - const index = opt_index !== undefined ? opt_index : this.items_.length; - this.items_.splice(index, 0, item); - this.cache_.add(item); - const subList = this.extract_(item); - if (subList) { - subList.emitter.on('add', this.onSubListAdd_); - subList.emitter.on('remove', this.onSubListRemove_); - subList.allItems().forEach((item) => { - this.cache_.add(item); - }); - } - this.emitter.emit('add', { - index: index, - item: item, - root: this, - target: this, - }); - } - remove(item) { - const index = this.items_.indexOf(item); - if (index < 0) { - return; - } - this.items_.splice(index, 1); - this.cache_.delete(item); - const subList = this.extract_(item); - if (subList) { - subList.emitter.off('add', this.onSubListAdd_); - subList.emitter.off('remove', this.onSubListRemove_); - } - this.emitter.emit('remove', { - index: index, - item: item, - root: this, - target: this, - }); - } - onSubListAdd_(ev) { - this.cache_.add(ev.item); - this.emitter.emit('add', { - index: ev.index, - item: ev.item, - root: this, - target: ev.target, - }); - } - onSubListRemove_(ev) { - this.cache_.delete(ev.item); - this.emitter.emit('remove', { - index: ev.index, - item: ev.item, - root: this, - target: ev.target, - }); - } - } - - class InputBindingApi extends BladeApi { - constructor(controller) { - super(controller); - this.onBindingChange_ = this.onBindingChange_.bind(this); - this.emitter_ = new Emitter(); - this.controller_.binding.emitter.on('change', this.onBindingChange_); - } - get label() { - return this.controller_.props.get('label'); - } - set label(label) { - this.controller_.props.set('label', label); - } - on(eventName, handler) { - const bh = handler.bind(this); - this.emitter_.on(eventName, (ev) => { - bh(ev.event); - }); - return this; - } - refresh() { - this.controller_.binding.read(); - } - onBindingChange_(ev) { - const value = ev.sender.target.read(); - this.emitter_.emit('change', { - event: new TpChangeEvent(this, forceCast(value), this.controller_.binding.target.presetKey, ev.options.last), - }); - } - } - - class InputBindingController extends LabelController { - constructor(doc, config) { - super(doc, config); - this.binding = config.binding; - } - } - - class MonitorBindingApi extends BladeApi { - constructor(controller) { - super(controller); - this.onBindingUpdate_ = this.onBindingUpdate_.bind(this); - this.emitter_ = new Emitter(); - this.controller_.binding.emitter.on('update', this.onBindingUpdate_); - } - get label() { - return this.controller_.props.get('label'); - } - set label(label) { - this.controller_.props.set('label', label); - } - on(eventName, handler) { - const bh = handler.bind(this); - this.emitter_.on(eventName, (ev) => { - bh(ev.event); - }); - return this; - } - refresh() { - this.controller_.binding.read(); - } - onBindingUpdate_(ev) { - const value = ev.sender.target.read(); - this.emitter_.emit('update', { - event: new TpUpdateEvent(this, forceCast(value), this.controller_.binding.target.presetKey), - }); - } - } - - class MonitorBindingController extends LabelController { - constructor(doc, config) { - super(doc, config); - this.binding = config.binding; - this.viewProps.bindDisabled(this.binding.ticker); - this.viewProps.handleDispose(() => { - this.binding.dispose(); - }); - } - } - - function findSubBladeApiSet(api) { - if (api instanceof RackApi) { - return api['apiSet_']; - } - if (api instanceof RackLikeApi) { - return api['rackApi_']['apiSet_']; - } - return null; - } - function getApiByController(apiSet, controller) { - const api = apiSet.find((api) => api.controller_ === controller); - if (!api) { - throw TpError.shouldNeverHappen(); - } - return api; - } - function createBindingTarget(obj, key, opt_id) { - if (!BindingTarget.isBindable(obj)) { - throw TpError.notBindable(); - } - return new BindingTarget(obj, key, opt_id); - } - class RackApi extends BladeApi { - constructor(controller, pool) { - super(controller); - this.onRackAdd_ = this.onRackAdd_.bind(this); - this.onRackRemove_ = this.onRackRemove_.bind(this); - this.onRackInputChange_ = this.onRackInputChange_.bind(this); - this.onRackMonitorUpdate_ = this.onRackMonitorUpdate_.bind(this); - this.emitter_ = new Emitter(); - this.apiSet_ = new NestedOrderedSet(findSubBladeApiSet); - this.pool_ = pool; - const rack = this.controller_.rack; - rack.emitter.on('add', this.onRackAdd_); - rack.emitter.on('remove', this.onRackRemove_); - rack.emitter.on('inputchange', this.onRackInputChange_); - rack.emitter.on('monitorupdate', this.onRackMonitorUpdate_); - rack.children.forEach((bc) => { - this.setUpApi_(bc); - }); - } - get children() { - return this.controller_.rack.children.map((bc) => getApiByController(this.apiSet_, bc)); - } - addInput(object, key, opt_params) { - const params = opt_params !== null && opt_params !== void 0 ? opt_params : {}; - const doc = this.controller_.view.element.ownerDocument; - const bc = this.pool_.createInput(doc, createBindingTarget(object, key, params.presetKey), params); - const api = new InputBindingApi(bc); - return this.add(api, params.index); - } - addMonitor(object, key, opt_params) { - const params = opt_params !== null && opt_params !== void 0 ? opt_params : {}; - const doc = this.controller_.view.element.ownerDocument; - const bc = this.pool_.createMonitor(doc, createBindingTarget(object, key), params); - const api = new MonitorBindingApi(bc); - return forceCast(this.add(api, params.index)); - } - addFolder(params) { - return addFolderAsBlade(this, params); - } - addButton(params) { - return addButtonAsBlade(this, params); - } - addSeparator(opt_params) { - return addSeparatorAsBlade(this, opt_params); - } - addTab(params) { - return addTabAsBlade(this, params); - } - add(api, opt_index) { - this.controller_.rack.add(api.controller_, opt_index); - const gapi = this.apiSet_.find((a) => a.controller_ === api.controller_); - if (gapi) { - this.apiSet_.remove(gapi); - } - this.apiSet_.add(api); - return api; - } - remove(api) { - this.controller_.rack.remove(api.controller_); - } - addBlade(params) { - const doc = this.controller_.view.element.ownerDocument; - const bc = this.pool_.createBlade(doc, params); - const api = this.pool_.createBladeApi(bc); - return this.add(api, params.index); - } - on(eventName, handler) { - const bh = handler.bind(this); - this.emitter_.on(eventName, (ev) => { - bh(ev.event); - }); - return this; - } - setUpApi_(bc) { - const api = this.apiSet_.find((api) => api.controller_ === bc); - if (!api) { - this.apiSet_.add(this.pool_.createBladeApi(bc)); - } - } - onRackAdd_(ev) { - this.setUpApi_(ev.bladeController); - } - onRackRemove_(ev) { - if (ev.isRoot) { - const api = getApiByController(this.apiSet_, ev.bladeController); - this.apiSet_.remove(api); - } - } - onRackInputChange_(ev) { - const bc = ev.bladeController; - if (bc instanceof InputBindingController) { - const api = getApiByController(this.apiSet_, bc); - const binding = bc.binding; - this.emitter_.emit('change', { - event: new TpChangeEvent(api, forceCast(binding.target.read()), binding.target.presetKey, ev.options.last), - }); - } - else if (bc instanceof ValueBladeController) { - const api = getApiByController(this.apiSet_, bc); - this.emitter_.emit('change', { - event: new TpChangeEvent(api, bc.value.rawValue, undefined, ev.options.last), - }); - } - } - onRackMonitorUpdate_(ev) { - if (!(ev.bladeController instanceof MonitorBindingController)) { - throw TpError.shouldNeverHappen(); - } - const api = getApiByController(this.apiSet_, ev.bladeController); - const binding = ev.bladeController.binding; - this.emitter_.emit('update', { - event: new TpUpdateEvent(api, forceCast(binding.target.read()), binding.target.presetKey), - }); - } - } - - class FolderApi extends RackLikeApi { - constructor(controller, pool) { - super(controller, new RackApi(controller.rackController, pool)); - this.emitter_ = new Emitter(); - this.controller_.foldable - .value('expanded') - .emitter.on('change', (ev) => { - this.emitter_.emit('fold', { - event: new TpFoldEvent(this, ev.sender.rawValue), - }); - }); - this.rackApi_.on('change', (ev) => { - this.emitter_.emit('change', { - event: ev, - }); - }); - this.rackApi_.on('update', (ev) => { - this.emitter_.emit('update', { - event: ev, - }); - }); - } - get expanded() { - return this.controller_.foldable.get('expanded'); - } - set expanded(expanded) { - this.controller_.foldable.set('expanded', expanded); - } - get title() { - return this.controller_.props.get('title'); - } - set title(title) { - this.controller_.props.set('title', title); - } - get children() { - return this.rackApi_.children; - } - addInput(object, key, opt_params) { - return this.rackApi_.addInput(object, key, opt_params); - } - addMonitor(object, key, opt_params) { - return this.rackApi_.addMonitor(object, key, opt_params); - } - addFolder(params) { - return this.rackApi_.addFolder(params); - } - addButton(params) { - return this.rackApi_.addButton(params); - } - addSeparator(opt_params) { - return this.rackApi_.addSeparator(opt_params); - } - addTab(params) { - return this.rackApi_.addTab(params); - } - add(api, opt_index) { - return this.rackApi_.add(api, opt_index); - } - remove(api) { - this.rackApi_.remove(api); - } - addBlade(params) { - return this.rackApi_.addBlade(params); - } - on(eventName, handler) { - const bh = handler.bind(this); - this.emitter_.on(eventName, (ev) => { - bh(ev.event); - }); - return this; - } - } - - class RackLikeController extends BladeController { - constructor(config) { - super({ - blade: config.blade, - view: config.view, - viewProps: config.rackController.viewProps, - }); - this.rackController = config.rackController; - } - } - - class PlainView { - constructor(doc, config) { - const className = ClassName(config.viewName); - this.element = doc.createElement('div'); - this.element.classList.add(className()); - config.viewProps.bindClassModifiers(this.element); - } - } - - function findInputBindingController(bcs, b) { - for (let i = 0; i < bcs.length; i++) { - const bc = bcs[i]; - if (bc instanceof InputBindingController && bc.binding === b) { - return bc; - } - } - return null; - } - function findMonitorBindingController(bcs, b) { - for (let i = 0; i < bcs.length; i++) { - const bc = bcs[i]; - if (bc instanceof MonitorBindingController && bc.binding === b) { - return bc; - } - } - return null; - } - function findValueBladeController(bcs, v) { - for (let i = 0; i < bcs.length; i++) { - const bc = bcs[i]; - if (bc instanceof ValueBladeController && bc.value === v) { - return bc; - } - } - return null; - } - function findSubRack(bc) { - if (bc instanceof RackController) { - return bc.rack; - } - if (bc instanceof RackLikeController) { - return bc.rackController.rack; - } - return null; - } - function findSubBladeControllerSet(bc) { - const rack = findSubRack(bc); - return rack ? rack['bcSet_'] : null; - } - class BladeRack { - constructor(config) { - var _a, _b; - this.onBladePositionsChange_ = this.onBladePositionsChange_.bind(this); - this.onSetAdd_ = this.onSetAdd_.bind(this); - this.onSetRemove_ = this.onSetRemove_.bind(this); - this.onChildDispose_ = this.onChildDispose_.bind(this); - this.onChildPositionsChange_ = this.onChildPositionsChange_.bind(this); - this.onChildInputChange_ = this.onChildInputChange_.bind(this); - this.onChildMonitorUpdate_ = this.onChildMonitorUpdate_.bind(this); - this.onChildValueChange_ = this.onChildValueChange_.bind(this); - this.onChildViewPropsChange_ = this.onChildViewPropsChange_.bind(this); - this.onDescendantLayout_ = this.onDescendantLayout_.bind(this); - this.onDescendantInputChange_ = this.onDescendantInputChange_.bind(this); - this.onDescendantMonitorUpdate_ = - this.onDescendantMonitorUpdate_.bind(this); - this.emitter = new Emitter(); - this.blade_ = (_a = config.blade) !== null && _a !== void 0 ? _a : null; - (_b = this.blade_) === null || _b === void 0 ? void 0 : _b.value('positions').emitter.on('change', this.onBladePositionsChange_); - this.viewProps = config.viewProps; - this.bcSet_ = new NestedOrderedSet(findSubBladeControllerSet); - this.bcSet_.emitter.on('add', this.onSetAdd_); - this.bcSet_.emitter.on('remove', this.onSetRemove_); - } - get children() { - return this.bcSet_.items; - } - add(bc, opt_index) { - var _a; - (_a = bc.parent) === null || _a === void 0 ? void 0 : _a.remove(bc); - if (isPropertyWritable(bc, 'parent')) { - bc.parent = this; - } - else { - bc['parent_'] = this; - warnMissing({ - key: 'parent', - target: 'BladeController', - place: 'BladeRack.add', - }); - } - this.bcSet_.add(bc, opt_index); - } - remove(bc) { - if (isPropertyWritable(bc, 'parent')) { - bc.parent = null; - } - else { - bc['parent_'] = null; - warnMissing({ - key: 'parent', - target: 'BladeController', - place: 'BladeRack.remove', - }); - } - this.bcSet_.remove(bc); - } - find(controllerClass) { - return forceCast(this.bcSet_.allItems().filter((bc) => { - return bc instanceof controllerClass; - })); - } - onSetAdd_(ev) { - this.updatePositions_(); - const isRoot = ev.target === ev.root; - this.emitter.emit('add', { - bladeController: ev.item, - index: ev.index, - isRoot: isRoot, - sender: this, - }); - if (!isRoot) { - return; - } - const bc = ev.item; - bc.viewProps.emitter.on('change', this.onChildViewPropsChange_); - bc.blade - .value('positions') - .emitter.on('change', this.onChildPositionsChange_); - bc.viewProps.handleDispose(this.onChildDispose_); - if (bc instanceof InputBindingController) { - bc.binding.emitter.on('change', this.onChildInputChange_); - } - else if (bc instanceof MonitorBindingController) { - bc.binding.emitter.on('update', this.onChildMonitorUpdate_); - } - else if (bc instanceof ValueBladeController) { - bc.value.emitter.on('change', this.onChildValueChange_); - } - else { - const rack = findSubRack(bc); - if (rack) { - const emitter = rack.emitter; - emitter.on('layout', this.onDescendantLayout_); - emitter.on('inputchange', this.onDescendantInputChange_); - emitter.on('monitorupdate', this.onDescendantMonitorUpdate_); - } - } - } - onSetRemove_(ev) { - this.updatePositions_(); - const isRoot = ev.target === ev.root; - this.emitter.emit('remove', { - bladeController: ev.item, - isRoot: isRoot, - sender: this, - }); - if (!isRoot) { - return; - } - const bc = ev.item; - if (bc instanceof InputBindingController) { - bc.binding.emitter.off('change', this.onChildInputChange_); - } - else if (bc instanceof MonitorBindingController) { - bc.binding.emitter.off('update', this.onChildMonitorUpdate_); - } - else if (bc instanceof ValueBladeController) { - bc.value.emitter.off('change', this.onChildValueChange_); - } - else { - const rack = findSubRack(bc); - if (rack) { - const emitter = rack.emitter; - emitter.off('layout', this.onDescendantLayout_); - emitter.off('inputchange', this.onDescendantInputChange_); - emitter.off('monitorupdate', this.onDescendantMonitorUpdate_); - } - } - } - updatePositions_() { - const visibleItems = this.bcSet_.items.filter((bc) => !bc.viewProps.get('hidden')); - const firstVisibleItem = visibleItems[0]; - const lastVisibleItem = visibleItems[visibleItems.length - 1]; - this.bcSet_.items.forEach((bc) => { - const ps = []; - if (bc === firstVisibleItem) { - ps.push('first'); - if (!this.blade_ || - this.blade_.get('positions').includes('veryfirst')) { - ps.push('veryfirst'); - } - } - if (bc === lastVisibleItem) { - ps.push('last'); - if (!this.blade_ || this.blade_.get('positions').includes('verylast')) { - ps.push('verylast'); - } - } - bc.blade.set('positions', ps); - }); - } - onChildPositionsChange_() { - this.updatePositions_(); - this.emitter.emit('layout', { - sender: this, - }); - } - onChildViewPropsChange_(_ev) { - this.updatePositions_(); - this.emitter.emit('layout', { - sender: this, - }); - } - onChildDispose_() { - const disposedUcs = this.bcSet_.items.filter((bc) => { - return bc.viewProps.get('disposed'); - }); - disposedUcs.forEach((bc) => { - this.bcSet_.remove(bc); - }); - } - onChildInputChange_(ev) { - const bc = findInputBindingController(this.find(InputBindingController), ev.sender); - if (!bc) { - throw TpError.alreadyDisposed(); - } - this.emitter.emit('inputchange', { - bladeController: bc, - options: ev.options, - sender: this, - }); - } - onChildMonitorUpdate_(ev) { - const bc = findMonitorBindingController(this.find(MonitorBindingController), ev.sender); - if (!bc) { - throw TpError.alreadyDisposed(); - } - this.emitter.emit('monitorupdate', { - bladeController: bc, - sender: this, - }); - } - onChildValueChange_(ev) { - const bc = findValueBladeController(this.find(ValueBladeController), ev.sender); - if (!bc) { - throw TpError.alreadyDisposed(); - } - this.emitter.emit('inputchange', { - bladeController: bc, - options: ev.options, - sender: this, - }); - } - onDescendantLayout_(_) { - this.updatePositions_(); - this.emitter.emit('layout', { - sender: this, - }); - } - onDescendantInputChange_(ev) { - this.emitter.emit('inputchange', { - bladeController: ev.bladeController, - options: ev.options, - sender: this, - }); - } - onDescendantMonitorUpdate_(ev) { - this.emitter.emit('monitorupdate', { - bladeController: ev.bladeController, - sender: this, - }); - } - onBladePositionsChange_() { - this.updatePositions_(); - } - } - - class RackController extends BladeController { - constructor(doc, config) { - super(Object.assign(Object.assign({}, config), { view: new PlainView(doc, { - viewName: 'brk', - viewProps: config.viewProps, - }) })); - this.onRackAdd_ = this.onRackAdd_.bind(this); - this.onRackRemove_ = this.onRackRemove_.bind(this); - const rack = new BladeRack({ - blade: config.root ? undefined : config.blade, - viewProps: config.viewProps, - }); - rack.emitter.on('add', this.onRackAdd_); - rack.emitter.on('remove', this.onRackRemove_); - this.rack = rack; - this.viewProps.handleDispose(() => { - for (let i = this.rack.children.length - 1; i >= 0; i--) { - const bc = this.rack.children[i]; - bc.viewProps.set('disposed', true); - } - }); - } - onRackAdd_(ev) { - if (!ev.isRoot) { - return; - } - insertElementAt(this.view.element, ev.bladeController.view.element, ev.index); - } - onRackRemove_(ev) { - if (!ev.isRoot) { - return; - } - removeElement(ev.bladeController.view.element); - } - } - - const bladeContainerClassName = ClassName('cnt'); - - class FolderView { - constructor(doc, config) { - var _a; - this.className_ = ClassName((_a = config.viewName) !== null && _a !== void 0 ? _a : 'fld'); - this.element = doc.createElement('div'); - this.element.classList.add(this.className_(), bladeContainerClassName()); - config.viewProps.bindClassModifiers(this.element); - this.foldable_ = config.foldable; - this.foldable_.bindExpandedClass(this.element, this.className_(undefined, 'expanded')); - bindValueMap(this.foldable_, 'completed', valueToClassName(this.element, this.className_(undefined, 'cpl'))); - const buttonElem = doc.createElement('button'); - buttonElem.classList.add(this.className_('b')); - bindValueMap(config.props, 'title', (title) => { - if (isEmpty(title)) { - this.element.classList.add(this.className_(undefined, 'not')); - } - else { - this.element.classList.remove(this.className_(undefined, 'not')); - } - }); - config.viewProps.bindDisabled(buttonElem); - this.element.appendChild(buttonElem); - this.buttonElement = buttonElem; - const indentElem = doc.createElement('div'); - indentElem.classList.add(this.className_('i')); - this.element.appendChild(indentElem); - const titleElem = doc.createElement('div'); - titleElem.classList.add(this.className_('t')); - bindValueToTextContent(config.props.value('title'), titleElem); - this.buttonElement.appendChild(titleElem); - this.titleElement = titleElem; - const markElem = doc.createElement('div'); - markElem.classList.add(this.className_('m')); - this.buttonElement.appendChild(markElem); - const containerElem = config.containerElement; - containerElem.classList.add(this.className_('c')); - this.element.appendChild(containerElem); - this.containerElement = containerElem; - } - } - - class FolderController extends RackLikeController { - constructor(doc, config) { - var _a; - const foldable = Foldable.create((_a = config.expanded) !== null && _a !== void 0 ? _a : true); - const rc = new RackController(doc, { - blade: config.blade, - root: config.root, - viewProps: config.viewProps, - }); - super(Object.assign(Object.assign({}, config), { rackController: rc, view: new FolderView(doc, { - containerElement: rc.view.element, - foldable: foldable, - props: config.props, - viewName: config.root ? 'rot' : undefined, - viewProps: config.viewProps, - }) })); - this.onTitleClick_ = this.onTitleClick_.bind(this); - this.props = config.props; - this.foldable = foldable; - bindFoldable(this.foldable, this.view.containerElement); - this.rackController.rack.emitter.on('add', () => { - this.foldable.cleanUpTransition(); - }); - this.rackController.rack.emitter.on('remove', () => { - this.foldable.cleanUpTransition(); - }); - this.view.buttonElement.addEventListener('click', this.onTitleClick_); - } - get document() { - return this.view.element.ownerDocument; - } - onTitleClick_() { - this.foldable.set('expanded', !this.foldable.get('expanded')); - } - } - - const FolderBladePlugin = { - id: 'folder', - type: 'blade', - accept(params) { - const p = ParamsParsers; - const result = parseParams(params, { - title: p.required.string, - view: p.required.constant('folder'), - expanded: p.optional.boolean, - }); - return result ? { params: result } : null; - }, - controller(args) { - return new FolderController(args.document, { - blade: args.blade, - expanded: args.params.expanded, - props: ValueMap.fromObject({ - title: args.params.title, - }), - viewProps: args.viewProps, - }); - }, - api(args) { - if (!(args.controller instanceof FolderController)) { - return null; - } - return new FolderApi(args.controller, args.pool); - }, - }; - - class LabeledValueController extends ValueBladeController { - constructor(doc, config) { - const viewProps = config.valueController.viewProps; - super(Object.assign(Object.assign({}, config), { value: config.valueController.value, view: new LabelView(doc, { - props: config.props, - viewProps: viewProps, - }), viewProps: viewProps })); - this.props = config.props; - this.valueController = config.valueController; - this.view.valueElement.appendChild(this.valueController.view.element); - } - } - - class SeparatorApi extends BladeApi { - } - - const className$m = ClassName('spr'); - class SeparatorView { - constructor(doc, config) { - this.element = doc.createElement('div'); - this.element.classList.add(className$m()); - config.viewProps.bindClassModifiers(this.element); - const hrElem = doc.createElement('hr'); - hrElem.classList.add(className$m('r')); - this.element.appendChild(hrElem); - } - } - - class SeparatorController extends BladeController { - constructor(doc, config) { - super(Object.assign(Object.assign({}, config), { view: new SeparatorView(doc, { - viewProps: config.viewProps, - }) })); - } - } - - const SeparatorBladePlugin = { - id: 'separator', - type: 'blade', - accept(params) { - const p = ParamsParsers; - const result = parseParams(params, { - view: p.required.constant('separator'), - }); - return result ? { params: result } : null; - }, - controller(args) { - return new SeparatorController(args.document, { - blade: args.blade, - viewProps: args.viewProps, - }); - }, - api(args) { - if (!(args.controller instanceof SeparatorController)) { - return null; - } - return new SeparatorApi(args.controller); - }, - }; - - const className$l = ClassName('tbi'); - class TabItemView { - constructor(doc, config) { - this.element = doc.createElement('div'); - this.element.classList.add(className$l()); - config.viewProps.bindClassModifiers(this.element); - bindValueMap(config.props, 'selected', (selected) => { - if (selected) { - this.element.classList.add(className$l(undefined, 'sel')); - } - else { - this.element.classList.remove(className$l(undefined, 'sel')); - } - }); - const buttonElem = doc.createElement('button'); - buttonElem.classList.add(className$l('b')); - config.viewProps.bindDisabled(buttonElem); - this.element.appendChild(buttonElem); - this.buttonElement = buttonElem; - const titleElem = doc.createElement('div'); - titleElem.classList.add(className$l('t')); - bindValueToTextContent(config.props.value('title'), titleElem); - this.buttonElement.appendChild(titleElem); - this.titleElement = titleElem; - } - } - - class TabItemController { - constructor(doc, config) { - this.emitter = new Emitter(); - this.onClick_ = this.onClick_.bind(this); - this.props = config.props; - this.viewProps = config.viewProps; - this.view = new TabItemView(doc, { - props: config.props, - viewProps: config.viewProps, - }); - this.view.buttonElement.addEventListener('click', this.onClick_); - } - onClick_() { - this.emitter.emit('click', { - sender: this, - }); - } - } - - class TabPageController { - constructor(doc, config) { - this.onItemClick_ = this.onItemClick_.bind(this); - this.ic_ = new TabItemController(doc, { - props: config.itemProps, - viewProps: ViewProps.create(), - }); - this.ic_.emitter.on('click', this.onItemClick_); - this.cc_ = new RackController(doc, { - blade: createBlade(), - viewProps: ViewProps.create(), - }); - this.props = config.props; - bindValueMap(this.props, 'selected', (selected) => { - this.itemController.props.set('selected', selected); - this.contentController.viewProps.set('hidden', !selected); - }); - } - get itemController() { - return this.ic_; - } - get contentController() { - return this.cc_; - } - onItemClick_() { - this.props.set('selected', true); - } - } - - class TabPageApi { - constructor(controller, contentRackApi) { - this.controller_ = controller; - this.rackApi_ = contentRackApi; - } - get title() { - var _a; - return (_a = this.controller_.itemController.props.get('title')) !== null && _a !== void 0 ? _a : ''; - } - set title(title) { - this.controller_.itemController.props.set('title', title); - } - get selected() { - return this.controller_.props.get('selected'); - } - set selected(selected) { - this.controller_.props.set('selected', selected); - } - get children() { - return this.rackApi_.children; - } - addButton(params) { - return this.rackApi_.addButton(params); - } - addFolder(params) { - return this.rackApi_.addFolder(params); - } - addSeparator(opt_params) { - return this.rackApi_.addSeparator(opt_params); - } - addTab(params) { - return this.rackApi_.addTab(params); - } - add(api, opt_index) { - this.rackApi_.add(api, opt_index); - } - remove(api) { - this.rackApi_.remove(api); - } - addInput(object, key, opt_params) { - return this.rackApi_.addInput(object, key, opt_params); - } - addMonitor(object, key, opt_params) { - return this.rackApi_.addMonitor(object, key, opt_params); - } - addBlade(params) { - return this.rackApi_.addBlade(params); - } - } - - class TabApi extends RackLikeApi { - constructor(controller, pool) { - super(controller, new RackApi(controller.rackController, pool)); - this.onPageAdd_ = this.onPageAdd_.bind(this); - this.onPageRemove_ = this.onPageRemove_.bind(this); - this.onSelect_ = this.onSelect_.bind(this); - this.emitter_ = new Emitter(); - this.pageApiMap_ = new Map(); - this.rackApi_.on('change', (ev) => { - this.emitter_.emit('change', { - event: ev, - }); - }); - this.rackApi_.on('update', (ev) => { - this.emitter_.emit('update', { - event: ev, - }); - }); - this.controller_.tab.selectedIndex.emitter.on('change', this.onSelect_); - this.controller_.pageSet.emitter.on('add', this.onPageAdd_); - this.controller_.pageSet.emitter.on('remove', this.onPageRemove_); - this.controller_.pageSet.items.forEach((pc) => { - this.setUpPageApi_(pc); - }); - } - get pages() { - return this.controller_.pageSet.items.map((pc) => { - const api = this.pageApiMap_.get(pc); - if (!api) { - throw TpError.shouldNeverHappen(); - } - return api; - }); - } - addPage(params) { - const doc = this.controller_.view.element.ownerDocument; - const pc = new TabPageController(doc, { - itemProps: ValueMap.fromObject({ - selected: false, - title: params.title, - }), - props: ValueMap.fromObject({ - selected: false, - }), - }); - this.controller_.add(pc, params.index); - const api = this.pageApiMap_.get(pc); - if (!api) { - throw TpError.shouldNeverHappen(); - } - return api; - } - removePage(index) { - this.controller_.remove(index); - } - on(eventName, handler) { - const bh = handler.bind(this); - this.emitter_.on(eventName, (ev) => { - bh(ev.event); - }); - return this; - } - setUpPageApi_(pc) { - const rackApi = this.rackApi_['apiSet_'].find((api) => api.controller_ === pc.contentController); - if (!rackApi) { - throw TpError.shouldNeverHappen(); - } - const api = new TabPageApi(pc, rackApi); - this.pageApiMap_.set(pc, api); - } - onPageAdd_(ev) { - this.setUpPageApi_(ev.item); - } - onPageRemove_(ev) { - const api = this.pageApiMap_.get(ev.item); - if (!api) { - throw TpError.shouldNeverHappen(); - } - this.pageApiMap_.delete(ev.item); - } - onSelect_(ev) { - this.emitter_.emit('select', { - event: new TpTabSelectEvent(this, ev.rawValue), - }); - } - } - - const INDEX_NOT_SELECTED = -1; - class Tab { - constructor() { - this.onItemSelectedChange_ = this.onItemSelectedChange_.bind(this); - this.empty = createValue(true); - this.selectedIndex = createValue(INDEX_NOT_SELECTED); - this.items_ = []; - } - add(item, opt_index) { - const index = opt_index !== null && opt_index !== void 0 ? opt_index : this.items_.length; - this.items_.splice(index, 0, item); - item.emitter.on('change', this.onItemSelectedChange_); - this.keepSelection_(); - } - remove(item) { - const index = this.items_.indexOf(item); - if (index < 0) { - return; - } - this.items_.splice(index, 1); - item.emitter.off('change', this.onItemSelectedChange_); - this.keepSelection_(); - } - keepSelection_() { - if (this.items_.length === 0) { - this.selectedIndex.rawValue = INDEX_NOT_SELECTED; - this.empty.rawValue = true; - return; - } - const firstSelIndex = this.items_.findIndex((s) => s.rawValue); - if (firstSelIndex < 0) { - this.items_.forEach((s, i) => { - s.rawValue = i === 0; - }); - this.selectedIndex.rawValue = 0; - } - else { - this.items_.forEach((s, i) => { - s.rawValue = i === firstSelIndex; - }); - this.selectedIndex.rawValue = firstSelIndex; - } - this.empty.rawValue = false; - } - onItemSelectedChange_(ev) { - if (ev.rawValue) { - const index = this.items_.findIndex((s) => s === ev.sender); - this.items_.forEach((s, i) => { - s.rawValue = i === index; - }); - this.selectedIndex.rawValue = index; - } - else { - this.keepSelection_(); - } - } - } - - const className$k = ClassName('tab'); - class TabView { - constructor(doc, config) { - this.element = doc.createElement('div'); - this.element.classList.add(className$k(), bladeContainerClassName()); - config.viewProps.bindClassModifiers(this.element); - bindValue(config.empty, valueToClassName(this.element, className$k(undefined, 'nop'))); - const titleElem = doc.createElement('div'); - titleElem.classList.add(className$k('t')); - this.element.appendChild(titleElem); - this.itemsElement = titleElem; - const indentElem = doc.createElement('div'); - indentElem.classList.add(className$k('i')); - this.element.appendChild(indentElem); - const contentsElem = config.contentsElement; - contentsElem.classList.add(className$k('c')); - this.element.appendChild(contentsElem); - this.contentsElement = contentsElem; - } - } - - class TabController extends RackLikeController { - constructor(doc, config) { - const cr = new RackController(doc, { - blade: config.blade, - viewProps: config.viewProps, - }); - const tab = new Tab(); - super({ - blade: config.blade, - rackController: cr, - view: new TabView(doc, { - contentsElement: cr.view.element, - empty: tab.empty, - viewProps: config.viewProps, - }), - }); - this.onPageAdd_ = this.onPageAdd_.bind(this); - this.onPageRemove_ = this.onPageRemove_.bind(this); - this.pageSet_ = new NestedOrderedSet(() => null); - this.pageSet_.emitter.on('add', this.onPageAdd_); - this.pageSet_.emitter.on('remove', this.onPageRemove_); - this.tab = tab; - } - get pageSet() { - return this.pageSet_; - } - add(pc, opt_index) { - this.pageSet_.add(pc, opt_index); - } - remove(index) { - this.pageSet_.remove(this.pageSet_.items[index]); - } - onPageAdd_(ev) { - const pc = ev.item; - insertElementAt(this.view.itemsElement, pc.itemController.view.element, ev.index); - pc.itemController.viewProps.set('parent', this.viewProps); - this.rackController.rack.add(pc.contentController, ev.index); - this.tab.add(pc.props.value('selected')); - } - onPageRemove_(ev) { - const pc = ev.item; - removeElement(pc.itemController.view.element); - pc.itemController.viewProps.set('parent', null); - this.rackController.rack.remove(pc.contentController); - this.tab.remove(pc.props.value('selected')); - } - } - - const TabBladePlugin = { - id: 'tab', - type: 'blade', - accept(params) { - const p = ParamsParsers; - const result = parseParams(params, { - pages: p.required.array(p.required.object({ title: p.required.string })), - view: p.required.constant('tab'), - }); - if (!result || result.pages.length === 0) { - return null; - } - return { params: result }; - }, - controller(args) { - const c = new TabController(args.document, { - blade: args.blade, - viewProps: args.viewProps, - }); - args.params.pages.forEach((p) => { - const pc = new TabPageController(args.document, { - itemProps: ValueMap.fromObject({ - selected: false, - title: p.title, - }), - props: ValueMap.fromObject({ - selected: false, - }), - }); - c.add(pc); - }); - return c; - }, - api(args) { - if (!(args.controller instanceof TabController)) { - return null; - } - return new TabApi(args.controller, args.pool); - }, - }; - - function createBladeController(plugin, args) { - const ac = plugin.accept(args.params); - if (!ac) { - return null; - } - const disabled = ParamsParsers.optional.boolean(args.params['disabled']).value; - const hidden = ParamsParsers.optional.boolean(args.params['hidden']).value; - return plugin.controller({ - blade: createBlade(), - document: args.document, - params: forceCast(Object.assign(Object.assign({}, ac.params), { disabled: disabled, hidden: hidden })), - viewProps: ViewProps.create({ - disabled: disabled, - hidden: hidden, - }), - }); - } - - class ManualTicker { - constructor() { - this.disabled = false; - this.emitter = new Emitter(); - } - dispose() { } - tick() { - if (this.disabled) { - return; - } - this.emitter.emit('tick', { - sender: this, - }); - } - } - - class IntervalTicker { - constructor(doc, interval) { - this.disabled_ = false; - this.timerId_ = null; - this.onTick_ = this.onTick_.bind(this); - this.doc_ = doc; - this.emitter = new Emitter(); - this.interval_ = interval; - this.setTimer_(); - } - get disabled() { - return this.disabled_; - } - set disabled(inactive) { - this.disabled_ = inactive; - if (this.disabled_) { - this.clearTimer_(); - } - else { - this.setTimer_(); - } - } - dispose() { - this.clearTimer_(); - } - clearTimer_() { - if (this.timerId_ === null) { - return; - } - const win = this.doc_.defaultView; - if (win) { - win.clearInterval(this.timerId_); - } - this.timerId_ = null; - } - setTimer_() { - this.clearTimer_(); - if (this.interval_ <= 0) { - return; - } - const win = this.doc_.defaultView; - if (win) { - this.timerId_ = win.setInterval(this.onTick_, this.interval_); - } - } - onTick_() { - if (this.disabled_) { - return; - } - this.emitter.emit('tick', { - sender: this, - }); - } - } - - class InputBinding { - constructor(config) { - this.onValueChange_ = this.onValueChange_.bind(this); - this.reader = config.reader; - this.writer = config.writer; - this.emitter = new Emitter(); - this.value = config.value; - this.value.emitter.on('change', this.onValueChange_); - this.target = config.target; - this.read(); - } - read() { - const targetValue = this.target.read(); - if (targetValue !== undefined) { - this.value.rawValue = this.reader(targetValue); - } - } - write_(rawValue) { - this.writer(this.target, rawValue); - } - onValueChange_(ev) { - this.write_(ev.rawValue); - this.emitter.emit('change', { - options: ev.options, - rawValue: ev.rawValue, - sender: this, - }); - } - } - - function fillBuffer(buffer, bufferSize) { - while (buffer.length < bufferSize) { - buffer.push(undefined); - } - } - function initializeBuffer(bufferSize) { - const buffer = []; - fillBuffer(buffer, bufferSize); - return createValue(buffer); - } - function createTrimmedBuffer(buffer) { - const index = buffer.indexOf(undefined); - return forceCast(index < 0 ? buffer : buffer.slice(0, index)); - } - function createPushedBuffer(buffer, newValue) { - const newBuffer = [...createTrimmedBuffer(buffer), newValue]; - if (newBuffer.length > buffer.length) { - newBuffer.splice(0, newBuffer.length - buffer.length); - } - else { - fillBuffer(newBuffer, buffer.length); - } - return newBuffer; - } - - class MonitorBinding { - constructor(config) { - this.onTick_ = this.onTick_.bind(this); - this.reader_ = config.reader; - this.target = config.target; - this.emitter = new Emitter(); - this.value = config.value; - this.ticker = config.ticker; - this.ticker.emitter.on('tick', this.onTick_); - this.read(); - } - dispose() { - this.ticker.dispose(); - } - read() { - const targetValue = this.target.read(); - if (targetValue === undefined) { - return; - } - const buffer = this.value.rawValue; - const newValue = this.reader_(targetValue); - this.value.rawValue = createPushedBuffer(buffer, newValue); - this.emitter.emit('update', { - rawValue: newValue, - sender: this, - }); - } - onTick_(_) { - this.read(); - } - } - - class CompositeConstraint { - constructor(constraints) { - this.constraints = constraints; - } - constrain(value) { - return this.constraints.reduce((result, c) => { - return c.constrain(result); - }, value); - } - } - function findConstraint(c, constraintClass) { - if (c instanceof constraintClass) { - return c; - } - if (c instanceof CompositeConstraint) { - const result = c.constraints.reduce((tmpResult, sc) => { - if (tmpResult) { - return tmpResult; - } - return sc instanceof constraintClass ? sc : null; - }, null); - if (result) { - return result; - } - } - return null; - } - - class DefiniteRangeConstraint { - constructor(config) { - this.values = ValueMap.fromObject({ - max: config.max, - min: config.min, - }); - } - constrain(value) { - const max = this.values.get('max'); - const min = this.values.get('min'); - return Math.min(Math.max(value, min), max); - } - } - - class ListConstraint { - constructor(options) { - this.values = ValueMap.fromObject({ - options: options, - }); - } - get options() { - return this.values.get('options'); - } - constrain(value) { - const opts = this.values.get('options'); - if (opts.length === 0) { - return value; - } - const matched = opts.filter((item) => { - return item.value === value; - }).length > 0; - return matched ? value : opts[0].value; - } - } - - class RangeConstraint { - constructor(config) { - this.values = ValueMap.fromObject({ - max: config.max, - min: config.min, - }); - } - get maxValue() { - return this.values.get('max'); - } - get minValue() { - return this.values.get('min'); - } - constrain(value) { - const max = this.values.get('max'); - const min = this.values.get('min'); - let result = value; - if (!isEmpty(min)) { - result = Math.max(result, min); - } - if (!isEmpty(max)) { - result = Math.min(result, max); - } - return result; - } - } - - class StepConstraint { - constructor(step, origin = 0) { - this.step = step; - this.origin = origin; - } - constrain(value) { - const o = this.origin % this.step; - const r = Math.round((value - o) / this.step); - return o + r * this.step; - } - } - - const className$j = ClassName('lst'); - class ListView { - constructor(doc, config) { - this.onValueChange_ = this.onValueChange_.bind(this); - this.props_ = config.props; - this.element = doc.createElement('div'); - this.element.classList.add(className$j()); - config.viewProps.bindClassModifiers(this.element); - const selectElem = doc.createElement('select'); - selectElem.classList.add(className$j('s')); - config.viewProps.bindDisabled(selectElem); - this.element.appendChild(selectElem); - this.selectElement = selectElem; - const markElem = doc.createElement('div'); - markElem.classList.add(className$j('m')); - markElem.appendChild(createSvgIconElement(doc, 'dropdown')); - this.element.appendChild(markElem); - config.value.emitter.on('change', this.onValueChange_); - this.value_ = config.value; - bindValueMap(this.props_, 'options', (opts) => { - removeChildElements(this.selectElement); - opts.forEach((item) => { - const optionElem = doc.createElement('option'); - optionElem.textContent = item.text; - this.selectElement.appendChild(optionElem); - }); - this.update_(); - }); - } - update_() { - const values = this.props_.get('options').map((o) => o.value); - this.selectElement.selectedIndex = values.indexOf(this.value_.rawValue); - } - onValueChange_() { - this.update_(); - } - } - - class ListController { - constructor(doc, config) { - this.onSelectChange_ = this.onSelectChange_.bind(this); - this.props = config.props; - this.value = config.value; - this.viewProps = config.viewProps; - this.view = new ListView(doc, { - props: this.props, - value: this.value, - viewProps: this.viewProps, - }); - this.view.selectElement.addEventListener('change', this.onSelectChange_); - } - onSelectChange_(e) { - const selectElem = forceCast(e.currentTarget); - this.value.rawValue = - this.props.get('options')[selectElem.selectedIndex].value; - } - } - - const className$i = ClassName('pop'); - class PopupView { - constructor(doc, config) { - this.element = doc.createElement('div'); - this.element.classList.add(className$i()); - config.viewProps.bindClassModifiers(this.element); - bindValue(config.shows, valueToClassName(this.element, className$i(undefined, 'v'))); - } - } - - class PopupController { - constructor(doc, config) { - this.shows = createValue(false); - this.viewProps = config.viewProps; - this.view = new PopupView(doc, { - shows: this.shows, - viewProps: this.viewProps, - }); - } - } - - const className$h = ClassName('txt'); - class TextView { - constructor(doc, config) { - this.onChange_ = this.onChange_.bind(this); - this.element = doc.createElement('div'); - this.element.classList.add(className$h()); - config.viewProps.bindClassModifiers(this.element); - this.props_ = config.props; - this.props_.emitter.on('change', this.onChange_); - const inputElem = doc.createElement('input'); - inputElem.classList.add(className$h('i')); - inputElem.type = 'text'; - config.viewProps.bindDisabled(inputElem); - this.element.appendChild(inputElem); - this.inputElement = inputElem; - config.value.emitter.on('change', this.onChange_); - this.value_ = config.value; - this.refresh(); - } - refresh() { - const formatter = this.props_.get('formatter'); - this.inputElement.value = formatter(this.value_.rawValue); - } - onChange_() { - this.refresh(); - } - } - - class TextController { - constructor(doc, config) { - this.onInputChange_ = this.onInputChange_.bind(this); - this.parser_ = config.parser; - this.props = config.props; - this.value = config.value; - this.viewProps = config.viewProps; - this.view = new TextView(doc, { - props: config.props, - value: this.value, - viewProps: this.viewProps, - }); - this.view.inputElement.addEventListener('change', this.onInputChange_); - } - onInputChange_(e) { - const inputElem = forceCast(e.currentTarget); - const value = inputElem.value; - const parsedValue = this.parser_(value); - if (!isEmpty(parsedValue)) { - this.value.rawValue = parsedValue; - } - this.view.refresh(); - } - } - - function boolToString(value) { - return String(value); - } - function boolFromUnknown(value) { - if (value === 'false') { - return false; - } - return !!value; - } - function BooleanFormatter(value) { - return boolToString(value); - } - - class NumberLiteralNode { - constructor(text) { - this.text = text; - } - evaluate() { - return Number(this.text); - } - toString() { - return this.text; - } - } - const BINARY_OPERATION_MAP = { - '**': (v1, v2) => Math.pow(v1, v2), - '*': (v1, v2) => v1 * v2, - '/': (v1, v2) => v1 / v2, - '%': (v1, v2) => v1 % v2, - '+': (v1, v2) => v1 + v2, - '-': (v1, v2) => v1 - v2, - '<<': (v1, v2) => v1 << v2, - '>>': (v1, v2) => v1 >> v2, - '>>>': (v1, v2) => v1 >>> v2, - '&': (v1, v2) => v1 & v2, - '^': (v1, v2) => v1 ^ v2, - '|': (v1, v2) => v1 | v2, - }; - class BinaryOperationNode { - constructor(operator, left, right) { - this.left = left; - this.operator = operator; - this.right = right; - } - evaluate() { - const op = BINARY_OPERATION_MAP[this.operator]; - if (!op) { - throw new Error(`unexpected binary operator: '${this.operator}`); - } - return op(this.left.evaluate(), this.right.evaluate()); - } - toString() { - return [ - 'b(', - this.left.toString(), - this.operator, - this.right.toString(), - ')', - ].join(' '); - } - } - const UNARY_OPERATION_MAP = { - '+': (v) => v, - '-': (v) => -v, - '~': (v) => ~v, - }; - class UnaryOperationNode { - constructor(operator, expr) { - this.operator = operator; - this.expression = expr; - } - evaluate() { - const op = UNARY_OPERATION_MAP[this.operator]; - if (!op) { - throw new Error(`unexpected unary operator: '${this.operator}`); - } - return op(this.expression.evaluate()); - } - toString() { - return ['u(', this.operator, this.expression.toString(), ')'].join(' '); - } - } - - function combineReader(parsers) { - return (text, cursor) => { - for (let i = 0; i < parsers.length; i++) { - const result = parsers[i](text, cursor); - if (result !== '') { - return result; - } - } - return ''; - }; - } - function readWhitespace(text, cursor) { - var _a; - const m = text.substr(cursor).match(/^\s+/); - return (_a = (m && m[0])) !== null && _a !== void 0 ? _a : ''; - } - function readNonZeroDigit(text, cursor) { - const ch = text.substr(cursor, 1); - return ch.match(/^[1-9]$/) ? ch : ''; - } - function readDecimalDigits(text, cursor) { - var _a; - const m = text.substr(cursor).match(/^[0-9]+/); - return (_a = (m && m[0])) !== null && _a !== void 0 ? _a : ''; - } - function readSignedInteger(text, cursor) { - const ds = readDecimalDigits(text, cursor); - if (ds !== '') { - return ds; - } - const sign = text.substr(cursor, 1); - cursor += 1; - if (sign !== '-' && sign !== '+') { - return ''; - } - const sds = readDecimalDigits(text, cursor); - if (sds === '') { - return ''; - } - return sign + sds; - } - function readExponentPart(text, cursor) { - const e = text.substr(cursor, 1); - cursor += 1; - if (e.toLowerCase() !== 'e') { - return ''; - } - const si = readSignedInteger(text, cursor); - if (si === '') { - return ''; - } - return e + si; - } - function readDecimalIntegerLiteral(text, cursor) { - const ch = text.substr(cursor, 1); - if (ch === '0') { - return ch; - } - const nzd = readNonZeroDigit(text, cursor); - cursor += nzd.length; - if (nzd === '') { - return ''; - } - return nzd + readDecimalDigits(text, cursor); - } - function readDecimalLiteral1(text, cursor) { - const dil = readDecimalIntegerLiteral(text, cursor); - cursor += dil.length; - if (dil === '') { - return ''; - } - const dot = text.substr(cursor, 1); - cursor += dot.length; - if (dot !== '.') { - return ''; - } - const dds = readDecimalDigits(text, cursor); - cursor += dds.length; - return dil + dot + dds + readExponentPart(text, cursor); - } - function readDecimalLiteral2(text, cursor) { - const dot = text.substr(cursor, 1); - cursor += dot.length; - if (dot !== '.') { - return ''; - } - const dds = readDecimalDigits(text, cursor); - cursor += dds.length; - if (dds === '') { - return ''; - } - return dot + dds + readExponentPart(text, cursor); - } - function readDecimalLiteral3(text, cursor) { - const dil = readDecimalIntegerLiteral(text, cursor); - cursor += dil.length; - if (dil === '') { - return ''; - } - return dil + readExponentPart(text, cursor); - } - const readDecimalLiteral = combineReader([ - readDecimalLiteral1, - readDecimalLiteral2, - readDecimalLiteral3, - ]); - function parseBinaryDigits(text, cursor) { - var _a; - const m = text.substr(cursor).match(/^[01]+/); - return (_a = (m && m[0])) !== null && _a !== void 0 ? _a : ''; - } - function readBinaryIntegerLiteral(text, cursor) { - const prefix = text.substr(cursor, 2); - cursor += prefix.length; - if (prefix.toLowerCase() !== '0b') { - return ''; - } - const bds = parseBinaryDigits(text, cursor); - if (bds === '') { - return ''; - } - return prefix + bds; - } - function readOctalDigits(text, cursor) { - var _a; - const m = text.substr(cursor).match(/^[0-7]+/); - return (_a = (m && m[0])) !== null && _a !== void 0 ? _a : ''; - } - function readOctalIntegerLiteral(text, cursor) { - const prefix = text.substr(cursor, 2); - cursor += prefix.length; - if (prefix.toLowerCase() !== '0o') { - return ''; - } - const ods = readOctalDigits(text, cursor); - if (ods === '') { - return ''; - } - return prefix + ods; - } - function readHexDigits(text, cursor) { - var _a; - const m = text.substr(cursor).match(/^[0-9a-f]+/i); - return (_a = (m && m[0])) !== null && _a !== void 0 ? _a : ''; - } - function readHexIntegerLiteral(text, cursor) { - const prefix = text.substr(cursor, 2); - cursor += prefix.length; - if (prefix.toLowerCase() !== '0x') { - return ''; - } - const hds = readHexDigits(text, cursor); - if (hds === '') { - return ''; - } - return prefix + hds; - } - const readNonDecimalIntegerLiteral = combineReader([ - readBinaryIntegerLiteral, - readOctalIntegerLiteral, - readHexIntegerLiteral, - ]); - const readNumericLiteral = combineReader([ - readNonDecimalIntegerLiteral, - readDecimalLiteral, - ]); - - function parseLiteral(text, cursor) { - const num = readNumericLiteral(text, cursor); - cursor += num.length; - if (num === '') { - return null; - } - return { - evaluable: new NumberLiteralNode(num), - cursor: cursor, - }; - } - function parseParenthesizedExpression(text, cursor) { - const op = text.substr(cursor, 1); - cursor += op.length; - if (op !== '(') { - return null; - } - const expr = parseExpression(text, cursor); - if (!expr) { - return null; - } - cursor = expr.cursor; - cursor += readWhitespace(text, cursor).length; - const cl = text.substr(cursor, 1); - cursor += cl.length; - if (cl !== ')') { - return null; - } - return { - evaluable: expr.evaluable, - cursor: cursor, - }; - } - function parsePrimaryExpression(text, cursor) { - var _a; - return ((_a = parseLiteral(text, cursor)) !== null && _a !== void 0 ? _a : parseParenthesizedExpression(text, cursor)); - } - function parseUnaryExpression(text, cursor) { - const expr = parsePrimaryExpression(text, cursor); - if (expr) { - return expr; - } - const op = text.substr(cursor, 1); - cursor += op.length; - if (op !== '+' && op !== '-' && op !== '~') { - return null; - } - const num = parseUnaryExpression(text, cursor); - if (!num) { - return null; - } - cursor = num.cursor; - return { - cursor: cursor, - evaluable: new UnaryOperationNode(op, num.evaluable), - }; - } - function readBinaryOperator(ops, text, cursor) { - cursor += readWhitespace(text, cursor).length; - const op = ops.filter((op) => text.startsWith(op, cursor))[0]; - if (!op) { - return null; - } - cursor += op.length; - cursor += readWhitespace(text, cursor).length; - return { - cursor: cursor, - operator: op, - }; - } - function createBinaryOperationExpressionParser(exprParser, ops) { - return (text, cursor) => { - const firstExpr = exprParser(text, cursor); - if (!firstExpr) { - return null; - } - cursor = firstExpr.cursor; - let expr = firstExpr.evaluable; - for (;;) { - const op = readBinaryOperator(ops, text, cursor); - if (!op) { - break; - } - cursor = op.cursor; - const nextExpr = exprParser(text, cursor); - if (!nextExpr) { - return null; - } - cursor = nextExpr.cursor; - expr = new BinaryOperationNode(op.operator, expr, nextExpr.evaluable); - } - return expr - ? { - cursor: cursor, - evaluable: expr, - } - : null; - }; - } - const parseBinaryOperationExpression = [ - ['**'], - ['*', '/', '%'], - ['+', '-'], - ['<<', '>>>', '>>'], - ['&'], - ['^'], - ['|'], - ].reduce((parser, ops) => { - return createBinaryOperationExpressionParser(parser, ops); - }, parseUnaryExpression); - function parseExpression(text, cursor) { - cursor += readWhitespace(text, cursor).length; - return parseBinaryOperationExpression(text, cursor); - } - function parseEcmaNumberExpression(text) { - const expr = parseExpression(text, 0); - if (!expr) { - return null; - } - const cursor = expr.cursor + readWhitespace(text, expr.cursor).length; - if (cursor !== text.length) { - return null; - } - return expr.evaluable; - } - - function parseNumber(text) { - var _a; - const r = parseEcmaNumberExpression(text); - return (_a = r === null || r === void 0 ? void 0 : r.evaluate()) !== null && _a !== void 0 ? _a : null; - } - function numberFromUnknown(value) { - if (typeof value === 'number') { - return value; - } - if (typeof value === 'string') { - const pv = parseNumber(value); - if (!isEmpty(pv)) { - return pv; - } - } - return 0; - } - function numberToString(value) { - return String(value); - } - function createNumberFormatter(digits) { - return (value) => { - return value.toFixed(Math.max(Math.min(digits, 20), 0)); - }; - } - - const innerFormatter = createNumberFormatter(0); - function formatPercentage(value) { - return innerFormatter(value) + '%'; - } - - function stringFromUnknown(value) { - return String(value); - } - function formatString(value) { - return value; - } - - function connectValues({ primary, secondary, forward, backward, }) { - let changing = false; - function preventFeedback(callback) { - if (changing) { - return; - } - changing = true; - callback(); - changing = false; - } - primary.emitter.on('change', (ev) => { - preventFeedback(() => { - secondary.setRawValue(forward(primary, secondary), ev.options); - }); - }); - secondary.emitter.on('change', (ev) => { - preventFeedback(() => { - primary.setRawValue(backward(primary, secondary), ev.options); - }); - preventFeedback(() => { - secondary.setRawValue(forward(primary, secondary), ev.options); - }); - }); - preventFeedback(() => { - secondary.setRawValue(forward(primary, secondary), { - forceEmit: false, - last: true, - }); - }); - } - - function getStepForKey(baseStep, keys) { - const step = baseStep * (keys.altKey ? 0.1 : 1) * (keys.shiftKey ? 10 : 1); - if (keys.upKey) { - return +step; - } - else if (keys.downKey) { - return -step; - } - return 0; - } - function getVerticalStepKeys(ev) { - return { - altKey: ev.altKey, - downKey: ev.key === 'ArrowDown', - shiftKey: ev.shiftKey, - upKey: ev.key === 'ArrowUp', - }; - } - function getHorizontalStepKeys(ev) { - return { - altKey: ev.altKey, - downKey: ev.key === 'ArrowLeft', - shiftKey: ev.shiftKey, - upKey: ev.key === 'ArrowRight', - }; - } - function isVerticalArrowKey(key) { - return key === 'ArrowUp' || key === 'ArrowDown'; - } - function isArrowKey(key) { - return isVerticalArrowKey(key) || key === 'ArrowLeft' || key === 'ArrowRight'; - } - - function computeOffset$1(ev, elem) { - var _a, _b; - const win = elem.ownerDocument.defaultView; - const rect = elem.getBoundingClientRect(); - return { - x: ev.pageX - (((_a = (win && win.scrollX)) !== null && _a !== void 0 ? _a : 0) + rect.left), - y: ev.pageY - (((_b = (win && win.scrollY)) !== null && _b !== void 0 ? _b : 0) + rect.top), - }; - } - class PointerHandler { - constructor(element) { - this.lastTouch_ = null; - this.onDocumentMouseMove_ = this.onDocumentMouseMove_.bind(this); - this.onDocumentMouseUp_ = this.onDocumentMouseUp_.bind(this); - this.onMouseDown_ = this.onMouseDown_.bind(this); - this.onTouchEnd_ = this.onTouchEnd_.bind(this); - this.onTouchMove_ = this.onTouchMove_.bind(this); - this.onTouchStart_ = this.onTouchStart_.bind(this); - this.elem_ = element; - this.emitter = new Emitter(); - element.addEventListener('touchstart', this.onTouchStart_, { - passive: false, - }); - element.addEventListener('touchmove', this.onTouchMove_, { - passive: true, - }); - element.addEventListener('touchend', this.onTouchEnd_); - element.addEventListener('mousedown', this.onMouseDown_); - } - computePosition_(offset) { - const rect = this.elem_.getBoundingClientRect(); - return { - bounds: { - width: rect.width, - height: rect.height, - }, - point: offset - ? { - x: offset.x, - y: offset.y, - } - : null, - }; - } - onMouseDown_(ev) { - var _a; - ev.preventDefault(); - (_a = ev.currentTarget) === null || _a === void 0 ? void 0 : _a.focus(); - const doc = this.elem_.ownerDocument; - doc.addEventListener('mousemove', this.onDocumentMouseMove_); - doc.addEventListener('mouseup', this.onDocumentMouseUp_); - this.emitter.emit('down', { - altKey: ev.altKey, - data: this.computePosition_(computeOffset$1(ev, this.elem_)), - sender: this, - shiftKey: ev.shiftKey, - }); - } - onDocumentMouseMove_(ev) { - this.emitter.emit('move', { - altKey: ev.altKey, - data: this.computePosition_(computeOffset$1(ev, this.elem_)), - sender: this, - shiftKey: ev.shiftKey, - }); - } - onDocumentMouseUp_(ev) { - const doc = this.elem_.ownerDocument; - doc.removeEventListener('mousemove', this.onDocumentMouseMove_); - doc.removeEventListener('mouseup', this.onDocumentMouseUp_); - this.emitter.emit('up', { - altKey: ev.altKey, - data: this.computePosition_(computeOffset$1(ev, this.elem_)), - sender: this, - shiftKey: ev.shiftKey, - }); - } - onTouchStart_(ev) { - ev.preventDefault(); - const touch = ev.targetTouches.item(0); - const rect = this.elem_.getBoundingClientRect(); - this.emitter.emit('down', { - altKey: ev.altKey, - data: this.computePosition_(touch - ? { - x: touch.clientX - rect.left, - y: touch.clientY - rect.top, - } - : undefined), - sender: this, - shiftKey: ev.shiftKey, - }); - this.lastTouch_ = touch; - } - onTouchMove_(ev) { - const touch = ev.targetTouches.item(0); - const rect = this.elem_.getBoundingClientRect(); - this.emitter.emit('move', { - altKey: ev.altKey, - data: this.computePosition_(touch - ? { - x: touch.clientX - rect.left, - y: touch.clientY - rect.top, - } - : undefined), - sender: this, - shiftKey: ev.shiftKey, - }); - this.lastTouch_ = touch; - } - onTouchEnd_(ev) { - var _a; - const touch = (_a = ev.targetTouches.item(0)) !== null && _a !== void 0 ? _a : this.lastTouch_; - const rect = this.elem_.getBoundingClientRect(); - this.emitter.emit('up', { - altKey: ev.altKey, - data: this.computePosition_(touch - ? { - x: touch.clientX - rect.left, - y: touch.clientY - rect.top, - } - : undefined), - sender: this, - shiftKey: ev.shiftKey, - }); - } - } - - function mapRange(value, start1, end1, start2, end2) { - const p = (value - start1) / (end1 - start1); - return start2 + p * (end2 - start2); - } - function getDecimalDigits(value) { - const text = String(value.toFixed(10)); - const frac = text.split('.')[1]; - return frac.replace(/0+$/, '').length; - } - function constrainRange(value, min, max) { - return Math.min(Math.max(value, min), max); - } - function loopRange(value, max) { - return ((value % max) + max) % max; - } - - const className$g = ClassName('txt'); - class NumberTextView { - constructor(doc, config) { - this.onChange_ = this.onChange_.bind(this); - this.props_ = config.props; - this.props_.emitter.on('change', this.onChange_); - this.element = doc.createElement('div'); - this.element.classList.add(className$g(), className$g(undefined, 'num')); - if (config.arrayPosition) { - this.element.classList.add(className$g(undefined, config.arrayPosition)); - } - config.viewProps.bindClassModifiers(this.element); - const inputElem = doc.createElement('input'); - inputElem.classList.add(className$g('i')); - inputElem.type = 'text'; - config.viewProps.bindDisabled(inputElem); - this.element.appendChild(inputElem); - this.inputElement = inputElem; - this.onDraggingChange_ = this.onDraggingChange_.bind(this); - this.dragging_ = config.dragging; - this.dragging_.emitter.on('change', this.onDraggingChange_); - this.element.classList.add(className$g()); - this.inputElement.classList.add(className$g('i')); - const knobElem = doc.createElement('div'); - knobElem.classList.add(className$g('k')); - this.element.appendChild(knobElem); - this.knobElement = knobElem; - const guideElem = doc.createElementNS(SVG_NS, 'svg'); - guideElem.classList.add(className$g('g')); - this.knobElement.appendChild(guideElem); - const bodyElem = doc.createElementNS(SVG_NS, 'path'); - bodyElem.classList.add(className$g('gb')); - guideElem.appendChild(bodyElem); - this.guideBodyElem_ = bodyElem; - const headElem = doc.createElementNS(SVG_NS, 'path'); - headElem.classList.add(className$g('gh')); - guideElem.appendChild(headElem); - this.guideHeadElem_ = headElem; - const tooltipElem = doc.createElement('div'); - tooltipElem.classList.add(ClassName('tt')()); - this.knobElement.appendChild(tooltipElem); - this.tooltipElem_ = tooltipElem; - config.value.emitter.on('change', this.onChange_); - this.value = config.value; - this.refresh(); - } - onDraggingChange_(ev) { - if (ev.rawValue === null) { - this.element.classList.remove(className$g(undefined, 'drg')); - return; - } - this.element.classList.add(className$g(undefined, 'drg')); - const x = ev.rawValue / this.props_.get('draggingScale'); - const aox = x + (x > 0 ? -1 : x < 0 ? +1 : 0); - const adx = constrainRange(-aox, -4, +4); - this.guideHeadElem_.setAttributeNS(null, 'd', [`M ${aox + adx},0 L${aox},4 L${aox + adx},8`, `M ${x},-1 L${x},9`].join(' ')); - this.guideBodyElem_.setAttributeNS(null, 'd', `M 0,4 L${x},4`); - const formatter = this.props_.get('formatter'); - this.tooltipElem_.textContent = formatter(this.value.rawValue); - this.tooltipElem_.style.left = `${x}px`; - } - refresh() { - const formatter = this.props_.get('formatter'); - this.inputElement.value = formatter(this.value.rawValue); - } - onChange_() { - this.refresh(); - } - } - - class NumberTextController { - constructor(doc, config) { - var _a; - this.originRawValue_ = 0; - this.onInputChange_ = this.onInputChange_.bind(this); - this.onInputKeyDown_ = this.onInputKeyDown_.bind(this); - this.onInputKeyUp_ = this.onInputKeyUp_.bind(this); - this.onPointerDown_ = this.onPointerDown_.bind(this); - this.onPointerMove_ = this.onPointerMove_.bind(this); - this.onPointerUp_ = this.onPointerUp_.bind(this); - this.baseStep_ = config.baseStep; - this.parser_ = config.parser; - this.props = config.props; - this.sliderProps_ = (_a = config.sliderProps) !== null && _a !== void 0 ? _a : null; - this.value = config.value; - this.viewProps = config.viewProps; - this.dragging_ = createValue(null); - this.view = new NumberTextView(doc, { - arrayPosition: config.arrayPosition, - dragging: this.dragging_, - props: this.props, - value: this.value, - viewProps: this.viewProps, - }); - this.view.inputElement.addEventListener('change', this.onInputChange_); - this.view.inputElement.addEventListener('keydown', this.onInputKeyDown_); - this.view.inputElement.addEventListener('keyup', this.onInputKeyUp_); - const ph = new PointerHandler(this.view.knobElement); - ph.emitter.on('down', this.onPointerDown_); - ph.emitter.on('move', this.onPointerMove_); - ph.emitter.on('up', this.onPointerUp_); - } - constrainValue_(value) { - var _a, _b; - const min = (_a = this.sliderProps_) === null || _a === void 0 ? void 0 : _a.get('minValue'); - const max = (_b = this.sliderProps_) === null || _b === void 0 ? void 0 : _b.get('maxValue'); - let v = value; - if (min !== undefined) { - v = Math.max(v, min); - } - if (max !== undefined) { - v = Math.min(v, max); - } - return v; - } - onInputChange_(e) { - const inputElem = forceCast(e.currentTarget); - const value = inputElem.value; - const parsedValue = this.parser_(value); - if (!isEmpty(parsedValue)) { - this.value.rawValue = this.constrainValue_(parsedValue); - } - this.view.refresh(); - } - onInputKeyDown_(ev) { - const step = getStepForKey(this.baseStep_, getVerticalStepKeys(ev)); - if (step === 0) { - return; - } - this.value.setRawValue(this.constrainValue_(this.value.rawValue + step), { - forceEmit: false, - last: false, - }); - } - onInputKeyUp_(ev) { - const step = getStepForKey(this.baseStep_, getVerticalStepKeys(ev)); - if (step === 0) { - return; - } - this.value.setRawValue(this.value.rawValue, { - forceEmit: true, - last: true, - }); - } - onPointerDown_() { - this.originRawValue_ = this.value.rawValue; - this.dragging_.rawValue = 0; - } - computeDraggingValue_(data) { - if (!data.point) { - return null; - } - const dx = data.point.x - data.bounds.width / 2; - return this.constrainValue_(this.originRawValue_ + dx * this.props.get('draggingScale')); - } - onPointerMove_(ev) { - const v = this.computeDraggingValue_(ev.data); - if (v === null) { - return; - } - this.value.setRawValue(v, { - forceEmit: false, - last: false, - }); - this.dragging_.rawValue = this.value.rawValue - this.originRawValue_; - } - onPointerUp_(ev) { - const v = this.computeDraggingValue_(ev.data); - if (v === null) { - return; - } - this.value.setRawValue(v, { - forceEmit: true, - last: true, - }); - this.dragging_.rawValue = null; - } - } - - const className$f = ClassName('sld'); - class SliderView { - constructor(doc, config) { - this.onChange_ = this.onChange_.bind(this); - this.props_ = config.props; - this.props_.emitter.on('change', this.onChange_); - this.element = doc.createElement('div'); - this.element.classList.add(className$f()); - config.viewProps.bindClassModifiers(this.element); - const trackElem = doc.createElement('div'); - trackElem.classList.add(className$f('t')); - config.viewProps.bindTabIndex(trackElem); - this.element.appendChild(trackElem); - this.trackElement = trackElem; - const knobElem = doc.createElement('div'); - knobElem.classList.add(className$f('k')); - this.trackElement.appendChild(knobElem); - this.knobElement = knobElem; - config.value.emitter.on('change', this.onChange_); - this.value = config.value; - this.update_(); - } - update_() { - const p = constrainRange(mapRange(this.value.rawValue, this.props_.get('minValue'), this.props_.get('maxValue'), 0, 100), 0, 100); - this.knobElement.style.width = `${p}%`; - } - onChange_() { - this.update_(); - } - } - - class SliderController { - constructor(doc, config) { - this.onKeyDown_ = this.onKeyDown_.bind(this); - this.onKeyUp_ = this.onKeyUp_.bind(this); - this.onPointerDownOrMove_ = this.onPointerDownOrMove_.bind(this); - this.onPointerUp_ = this.onPointerUp_.bind(this); - this.baseStep_ = config.baseStep; - this.value = config.value; - this.viewProps = config.viewProps; - this.props = config.props; - this.view = new SliderView(doc, { - props: this.props, - value: this.value, - viewProps: this.viewProps, - }); - this.ptHandler_ = new PointerHandler(this.view.trackElement); - this.ptHandler_.emitter.on('down', this.onPointerDownOrMove_); - this.ptHandler_.emitter.on('move', this.onPointerDownOrMove_); - this.ptHandler_.emitter.on('up', this.onPointerUp_); - this.view.trackElement.addEventListener('keydown', this.onKeyDown_); - this.view.trackElement.addEventListener('keyup', this.onKeyUp_); - } - handlePointerEvent_(d, opts) { - if (!d.point) { - return; - } - this.value.setRawValue(mapRange(constrainRange(d.point.x, 0, d.bounds.width), 0, d.bounds.width, this.props.get('minValue'), this.props.get('maxValue')), opts); - } - onPointerDownOrMove_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: false, - last: false, - }); - } - onPointerUp_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: true, - last: true, - }); - } - onKeyDown_(ev) { - const step = getStepForKey(this.baseStep_, getHorizontalStepKeys(ev)); - if (step === 0) { - return; - } - this.value.setRawValue(this.value.rawValue + step, { - forceEmit: false, - last: false, - }); - } - onKeyUp_(ev) { - const step = getStepForKey(this.baseStep_, getHorizontalStepKeys(ev)); - if (step === 0) { - return; - } - this.value.setRawValue(this.value.rawValue, { - forceEmit: true, - last: true, - }); - } - } - - const className$e = ClassName('sldtxt'); - class SliderTextView { - constructor(doc, config) { - this.element = doc.createElement('div'); - this.element.classList.add(className$e()); - const sliderElem = doc.createElement('div'); - sliderElem.classList.add(className$e('s')); - this.sliderView_ = config.sliderView; - sliderElem.appendChild(this.sliderView_.element); - this.element.appendChild(sliderElem); - const textElem = doc.createElement('div'); - textElem.classList.add(className$e('t')); - this.textView_ = config.textView; - textElem.appendChild(this.textView_.element); - this.element.appendChild(textElem); - } - } - - class SliderTextController { - constructor(doc, config) { - this.value = config.value; - this.viewProps = config.viewProps; - this.sliderC_ = new SliderController(doc, { - baseStep: config.baseStep, - props: config.sliderProps, - value: config.value, - viewProps: this.viewProps, - }); - this.textC_ = new NumberTextController(doc, { - baseStep: config.baseStep, - parser: config.parser, - props: config.textProps, - sliderProps: config.sliderProps, - value: config.value, - viewProps: config.viewProps, - }); - this.view = new SliderTextView(doc, { - sliderView: this.sliderC_.view, - textView: this.textC_.view, - }); - } - get sliderController() { - return this.sliderC_; - } - get textController() { - return this.textC_; - } - } - - function writePrimitive(target, value) { - target.write(value); - } - - function parseListOptions(value) { - const p = ParamsParsers; - if (Array.isArray(value)) { - return p.required.array(p.required.object({ - text: p.required.string, - value: p.required.raw, - }))(value).value; - } - if (typeof value === 'object') { - return p.required.raw(value) - .value; - } - return undefined; - } - function parsePickerLayout(value) { - if (value === 'inline' || value === 'popup') { - return value; - } - return undefined; - } - function parsePointDimensionParams(value) { - const p = ParamsParsers; - return p.required.object({ - max: p.optional.number, - min: p.optional.number, - step: p.optional.number, - })(value).value; - } - function normalizeListOptions(options) { - if (Array.isArray(options)) { - return options; - } - const items = []; - Object.keys(options).forEach((text) => { - items.push({ text: text, value: options[text] }); - }); - return items; - } - function createListConstraint(options) { - return !isEmpty(options) - ? new ListConstraint(normalizeListOptions(forceCast(options))) - : null; - } - function findStep(constraint) { - const c = constraint ? findConstraint(constraint, StepConstraint) : null; - if (!c) { - return null; - } - return c.step; - } - function getSuitableDecimalDigits(constraint, rawValue) { - const sc = constraint && findConstraint(constraint, StepConstraint); - if (sc) { - return getDecimalDigits(sc.step); - } - return Math.max(getDecimalDigits(rawValue), 2); - } - function getBaseStep(constraint) { - const step = findStep(constraint); - return step !== null && step !== void 0 ? step : 1; - } - function getSuitableDraggingScale(constraint, rawValue) { - var _a; - const sc = constraint && findConstraint(constraint, StepConstraint); - const base = Math.abs((_a = sc === null || sc === void 0 ? void 0 : sc.step) !== null && _a !== void 0 ? _a : rawValue); - return base === 0 ? 0.1 : Math.pow(10, Math.floor(Math.log10(base)) - 1); - } - - const className$d = ClassName('ckb'); - class CheckboxView { - constructor(doc, config) { - this.onValueChange_ = this.onValueChange_.bind(this); - this.element = doc.createElement('div'); - this.element.classList.add(className$d()); - config.viewProps.bindClassModifiers(this.element); - const labelElem = doc.createElement('label'); - labelElem.classList.add(className$d('l')); - this.element.appendChild(labelElem); - const inputElem = doc.createElement('input'); - inputElem.classList.add(className$d('i')); - inputElem.type = 'checkbox'; - labelElem.appendChild(inputElem); - this.inputElement = inputElem; - config.viewProps.bindDisabled(this.inputElement); - const wrapperElem = doc.createElement('div'); - wrapperElem.classList.add(className$d('w')); - labelElem.appendChild(wrapperElem); - const markElem = createSvgIconElement(doc, 'check'); - wrapperElem.appendChild(markElem); - config.value.emitter.on('change', this.onValueChange_); - this.value = config.value; - this.update_(); - } - update_() { - this.inputElement.checked = this.value.rawValue; - } - onValueChange_() { - this.update_(); - } - } - - class CheckboxController { - constructor(doc, config) { - this.onInputChange_ = this.onInputChange_.bind(this); - this.value = config.value; - this.viewProps = config.viewProps; - this.view = new CheckboxView(doc, { - value: this.value, - viewProps: this.viewProps, - }); - this.view.inputElement.addEventListener('change', this.onInputChange_); - } - onInputChange_(e) { - const inputElem = forceCast(e.currentTarget); - this.value.rawValue = inputElem.checked; - } - } - - function createConstraint$6(params) { - const constraints = []; - const lc = createListConstraint(params.options); - if (lc) { - constraints.push(lc); - } - return new CompositeConstraint(constraints); - } - const BooleanInputPlugin = { - id: 'input-bool', - type: 'input', - accept: (value, params) => { - if (typeof value !== 'boolean') { - return null; - } - const p = ParamsParsers; - const result = parseParams(params, { - options: p.optional.custom(parseListOptions), - }); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (_args) => boolFromUnknown, - constraint: (args) => createConstraint$6(args.params), - writer: (_args) => writePrimitive, - }, - controller: (args) => { - const doc = args.document; - const value = args.value; - const c = args.constraint; - const lc = c && findConstraint(c, ListConstraint); - if (lc) { - return new ListController(doc, { - props: new ValueMap({ - options: lc.values.value('options'), - }), - value: value, - viewProps: args.viewProps, - }); - } - return new CheckboxController(doc, { - value: value, - viewProps: args.viewProps, - }); - }, - }; - - const className$c = ClassName('col'); - class ColorView { - constructor(doc, config) { - this.element = doc.createElement('div'); - this.element.classList.add(className$c()); - config.foldable.bindExpandedClass(this.element, className$c(undefined, 'expanded')); - bindValueMap(config.foldable, 'completed', valueToClassName(this.element, className$c(undefined, 'cpl'))); - const headElem = doc.createElement('div'); - headElem.classList.add(className$c('h')); - this.element.appendChild(headElem); - const swatchElem = doc.createElement('div'); - swatchElem.classList.add(className$c('s')); - headElem.appendChild(swatchElem); - this.swatchElement = swatchElem; - const textElem = doc.createElement('div'); - textElem.classList.add(className$c('t')); - headElem.appendChild(textElem); - this.textElement = textElem; - if (config.pickerLayout === 'inline') { - const pickerElem = doc.createElement('div'); - pickerElem.classList.add(className$c('p')); - this.element.appendChild(pickerElem); - this.pickerElement = pickerElem; - } - else { - this.pickerElement = null; - } - } - } - - function rgbToHslInt(r, g, b) { - const rp = constrainRange(r / 255, 0, 1); - const gp = constrainRange(g / 255, 0, 1); - const bp = constrainRange(b / 255, 0, 1); - const cmax = Math.max(rp, gp, bp); - const cmin = Math.min(rp, gp, bp); - const c = cmax - cmin; - let h = 0; - let s = 0; - const l = (cmin + cmax) / 2; - if (c !== 0) { - s = c / (1 - Math.abs(cmax + cmin - 1)); - if (rp === cmax) { - h = (gp - bp) / c; - } - else if (gp === cmax) { - h = 2 + (bp - rp) / c; - } - else { - h = 4 + (rp - gp) / c; - } - h = h / 6 + (h < 0 ? 1 : 0); - } - return [h * 360, s * 100, l * 100]; - } - function hslToRgbInt(h, s, l) { - const hp = ((h % 360) + 360) % 360; - const sp = constrainRange(s / 100, 0, 1); - const lp = constrainRange(l / 100, 0, 1); - const c = (1 - Math.abs(2 * lp - 1)) * sp; - const x = c * (1 - Math.abs(((hp / 60) % 2) - 1)); - const m = lp - c / 2; - let rp, gp, bp; - if (hp >= 0 && hp < 60) { - [rp, gp, bp] = [c, x, 0]; - } - else if (hp >= 60 && hp < 120) { - [rp, gp, bp] = [x, c, 0]; - } - else if (hp >= 120 && hp < 180) { - [rp, gp, bp] = [0, c, x]; - } - else if (hp >= 180 && hp < 240) { - [rp, gp, bp] = [0, x, c]; - } - else if (hp >= 240 && hp < 300) { - [rp, gp, bp] = [x, 0, c]; - } - else { - [rp, gp, bp] = [c, 0, x]; - } - return [(rp + m) * 255, (gp + m) * 255, (bp + m) * 255]; - } - function rgbToHsvInt(r, g, b) { - const rp = constrainRange(r / 255, 0, 1); - const gp = constrainRange(g / 255, 0, 1); - const bp = constrainRange(b / 255, 0, 1); - const cmax = Math.max(rp, gp, bp); - const cmin = Math.min(rp, gp, bp); - const d = cmax - cmin; - let h; - if (d === 0) { - h = 0; - } - else if (cmax === rp) { - h = 60 * (((((gp - bp) / d) % 6) + 6) % 6); - } - else if (cmax === gp) { - h = 60 * ((bp - rp) / d + 2); - } - else { - h = 60 * ((rp - gp) / d + 4); - } - const s = cmax === 0 ? 0 : d / cmax; - const v = cmax; - return [h, s * 100, v * 100]; - } - function hsvToRgbInt(h, s, v) { - const hp = loopRange(h, 360); - const sp = constrainRange(s / 100, 0, 1); - const vp = constrainRange(v / 100, 0, 1); - const c = vp * sp; - const x = c * (1 - Math.abs(((hp / 60) % 2) - 1)); - const m = vp - c; - let rp, gp, bp; - if (hp >= 0 && hp < 60) { - [rp, gp, bp] = [c, x, 0]; - } - else if (hp >= 60 && hp < 120) { - [rp, gp, bp] = [x, c, 0]; - } - else if (hp >= 120 && hp < 180) { - [rp, gp, bp] = [0, c, x]; - } - else if (hp >= 180 && hp < 240) { - [rp, gp, bp] = [0, x, c]; - } - else if (hp >= 240 && hp < 300) { - [rp, gp, bp] = [x, 0, c]; - } - else { - [rp, gp, bp] = [c, 0, x]; - } - return [(rp + m) * 255, (gp + m) * 255, (bp + m) * 255]; - } - function hslToHsvInt(h, s, l) { - const sd = l + (s * (100 - Math.abs(2 * l - 100))) / (2 * 100); - return [ - h, - sd !== 0 ? (s * (100 - Math.abs(2 * l - 100))) / sd : 0, - l + (s * (100 - Math.abs(2 * l - 100))) / (2 * 100), - ]; - } - function hsvToHslInt(h, s, v) { - const sd = 100 - Math.abs((v * (200 - s)) / 100 - 100); - return [h, sd !== 0 ? (s * v) / sd : 0, (v * (200 - s)) / (2 * 100)]; - } - function removeAlphaComponent(comps) { - return [comps[0], comps[1], comps[2]]; - } - function appendAlphaComponent(comps, alpha) { - return [comps[0], comps[1], comps[2], alpha]; - } - const MODE_CONVERTER_MAP = { - hsl: { - hsl: (h, s, l) => [h, s, l], - hsv: hslToHsvInt, - rgb: hslToRgbInt, - }, - hsv: { - hsl: hsvToHslInt, - hsv: (h, s, v) => [h, s, v], - rgb: hsvToRgbInt, - }, - rgb: { - hsl: rgbToHslInt, - hsv: rgbToHsvInt, - rgb: (r, g, b) => [r, g, b], - }, - }; - function getColorMaxComponents(mode, type) { - return [ - type === 'float' ? 1 : mode === 'rgb' ? 255 : 360, - type === 'float' ? 1 : mode === 'rgb' ? 255 : 100, - type === 'float' ? 1 : mode === 'rgb' ? 255 : 100, - ]; - } - function loopHueRange(hue, max) { - return hue === max ? max : loopRange(hue, max); - } - function constrainColorComponents(components, mode, type) { - var _a; - const ms = getColorMaxComponents(mode, type); - return [ - mode === 'rgb' - ? constrainRange(components[0], 0, ms[0]) - : loopHueRange(components[0], ms[0]), - constrainRange(components[1], 0, ms[1]), - constrainRange(components[2], 0, ms[2]), - constrainRange((_a = components[3]) !== null && _a !== void 0 ? _a : 1, 0, 1), - ]; - } - function convertColorType(comps, mode, from, to) { - const fms = getColorMaxComponents(mode, from); - const tms = getColorMaxComponents(mode, to); - return comps.map((c, index) => (c / fms[index]) * tms[index]); - } - function convertColor(components, from, to) { - const intComps = convertColorType(components, from.mode, from.type, 'int'); - const result = MODE_CONVERTER_MAP[from.mode][to.mode](...intComps); - return convertColorType(result, to.mode, 'int', to.type); - } - - function isRgbColorComponent(obj, key) { - if (typeof obj !== 'object' || isEmpty(obj)) { - return false; - } - return key in obj && typeof obj[key] === 'number'; - } - class Color { - static black(type = 'int') { - return new Color([0, 0, 0], 'rgb', type); - } - static fromObject(obj, type = 'int') { - const comps = 'a' in obj ? [obj.r, obj.g, obj.b, obj.a] : [obj.r, obj.g, obj.b]; - return new Color(comps, 'rgb', type); - } - static toRgbaObject(color, type = 'int') { - return color.toRgbaObject(type); - } - static isRgbColorObject(obj) { - return (isRgbColorComponent(obj, 'r') && - isRgbColorComponent(obj, 'g') && - isRgbColorComponent(obj, 'b')); - } - static isRgbaColorObject(obj) { - return this.isRgbColorObject(obj) && isRgbColorComponent(obj, 'a'); - } - static isColorObject(obj) { - return this.isRgbColorObject(obj); - } - static equals(v1, v2) { - if (v1.mode !== v2.mode) { - return false; - } - const comps1 = v1.comps_; - const comps2 = v2.comps_; - for (let i = 0; i < comps1.length; i++) { - if (comps1[i] !== comps2[i]) { - return false; - } - } - return true; - } - constructor(comps, mode, type = 'int') { - this.mode = mode; - this.type = type; - this.comps_ = constrainColorComponents(comps, mode, type); - } - getComponents(opt_mode, type = 'int') { - return appendAlphaComponent(convertColor(removeAlphaComponent(this.comps_), { mode: this.mode, type: this.type }, { mode: opt_mode !== null && opt_mode !== void 0 ? opt_mode : this.mode, type }), this.comps_[3]); - } - toRgbaObject(type = 'int') { - const rgbComps = this.getComponents('rgb', type); - return { - r: rgbComps[0], - g: rgbComps[1], - b: rgbComps[2], - a: rgbComps[3], - }; - } - } - - const className$b = ClassName('colp'); - class ColorPickerView { - constructor(doc, config) { - this.alphaViews_ = null; - this.element = doc.createElement('div'); - this.element.classList.add(className$b()); - config.viewProps.bindClassModifiers(this.element); - const hsvElem = doc.createElement('div'); - hsvElem.classList.add(className$b('hsv')); - const svElem = doc.createElement('div'); - svElem.classList.add(className$b('sv')); - this.svPaletteView_ = config.svPaletteView; - svElem.appendChild(this.svPaletteView_.element); - hsvElem.appendChild(svElem); - const hElem = doc.createElement('div'); - hElem.classList.add(className$b('h')); - this.hPaletteView_ = config.hPaletteView; - hElem.appendChild(this.hPaletteView_.element); - hsvElem.appendChild(hElem); - this.element.appendChild(hsvElem); - const rgbElem = doc.createElement('div'); - rgbElem.classList.add(className$b('rgb')); - this.textView_ = config.textView; - rgbElem.appendChild(this.textView_.element); - this.element.appendChild(rgbElem); - if (config.alphaViews) { - this.alphaViews_ = { - palette: config.alphaViews.palette, - text: config.alphaViews.text, - }; - const aElem = doc.createElement('div'); - aElem.classList.add(className$b('a')); - const apElem = doc.createElement('div'); - apElem.classList.add(className$b('ap')); - apElem.appendChild(this.alphaViews_.palette.element); - aElem.appendChild(apElem); - const atElem = doc.createElement('div'); - atElem.classList.add(className$b('at')); - atElem.appendChild(this.alphaViews_.text.element); - aElem.appendChild(atElem); - this.element.appendChild(aElem); - } - } - get allFocusableElements() { - const elems = [ - this.svPaletteView_.element, - this.hPaletteView_.element, - this.textView_.modeSelectElement, - ...this.textView_.textViews.map((v) => v.inputElement), - ]; - if (this.alphaViews_) { - elems.push(this.alphaViews_.palette.element, this.alphaViews_.text.inputElement); - } - return elems; - } - } - - function parseColorType(value) { - return value === 'int' ? 'int' : value === 'float' ? 'float' : undefined; - } - function parseColorInputParams(params) { - const p = ParamsParsers; - return parseParams(params, { - alpha: p.optional.boolean, - color: p.optional.object({ - alpha: p.optional.boolean, - type: p.optional.custom(parseColorType), - }), - expanded: p.optional.boolean, - picker: p.optional.custom(parsePickerLayout), - }); - } - function getBaseStepForColor(forAlpha) { - return forAlpha ? 0.1 : 1; - } - function extractColorType(params) { - var _a; - return (_a = params.color) === null || _a === void 0 ? void 0 : _a.type; - } - - function equalsStringColorFormat(f1, f2) { - return (f1.alpha === f2.alpha && - f1.mode === f2.mode && - f1.notation === f2.notation && - f1.type === f2.type); - } - function parseCssNumberOrPercentage(text, maxValue) { - const m = text.match(/^(.+)%$/); - if (!m) { - return Math.min(parseFloat(text), maxValue); - } - return Math.min(parseFloat(m[1]) * 0.01 * maxValue, maxValue); - } - const ANGLE_TO_DEG_MAP = { - deg: (angle) => angle, - grad: (angle) => (angle * 360) / 400, - rad: (angle) => (angle * 360) / (2 * Math.PI), - turn: (angle) => angle * 360, - }; - function parseCssNumberOrAngle(text) { - const m = text.match(/^([0-9.]+?)(deg|grad|rad|turn)$/); - if (!m) { - return parseFloat(text); - } - const angle = parseFloat(m[1]); - const unit = m[2]; - return ANGLE_TO_DEG_MAP[unit](angle); - } - function parseFunctionalRgbColorComponents(text) { - const m = text.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/); - if (!m) { - return null; - } - const comps = [ - parseCssNumberOrPercentage(m[1], 255), - parseCssNumberOrPercentage(m[2], 255), - parseCssNumberOrPercentage(m[3], 255), - ]; - if (isNaN(comps[0]) || isNaN(comps[1]) || isNaN(comps[2])) { - return null; - } - return comps; - } - function createFunctionalRgbColorParser(type) { - return (text) => { - const comps = parseFunctionalRgbColorComponents(text); - return comps ? new Color(comps, 'rgb', type) : null; - }; - } - function parseFunctionalRgbaColorComponents(text) { - const m = text.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/); - if (!m) { - return null; - } - const comps = [ - parseCssNumberOrPercentage(m[1], 255), - parseCssNumberOrPercentage(m[2], 255), - parseCssNumberOrPercentage(m[3], 255), - parseCssNumberOrPercentage(m[4], 1), - ]; - if (isNaN(comps[0]) || - isNaN(comps[1]) || - isNaN(comps[2]) || - isNaN(comps[3])) { - return null; - } - return comps; - } - function createFunctionalRgbaColorParser(type) { - return (text) => { - const comps = parseFunctionalRgbaColorComponents(text); - return comps ? new Color(comps, 'rgb', type) : null; - }; - } - function parseHslColorComponents(text) { - const m = text.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/); - if (!m) { - return null; - } - const comps = [ - parseCssNumberOrAngle(m[1]), - parseCssNumberOrPercentage(m[2], 100), - parseCssNumberOrPercentage(m[3], 100), - ]; - if (isNaN(comps[0]) || isNaN(comps[1]) || isNaN(comps[2])) { - return null; - } - return comps; - } - function createHslColorParser(type) { - return (text) => { - const comps = parseHslColorComponents(text); - return comps ? new Color(comps, 'hsl', type) : null; - }; - } - function parseHslaColorComponents(text) { - const m = text.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/); - if (!m) { - return null; - } - const comps = [ - parseCssNumberOrAngle(m[1]), - parseCssNumberOrPercentage(m[2], 100), - parseCssNumberOrPercentage(m[3], 100), - parseCssNumberOrPercentage(m[4], 1), - ]; - if (isNaN(comps[0]) || - isNaN(comps[1]) || - isNaN(comps[2]) || - isNaN(comps[3])) { - return null; - } - return comps; - } - function createHslaColorParser(type) { - return (text) => { - const comps = parseHslaColorComponents(text); - return comps ? new Color(comps, 'hsl', type) : null; - }; - } - function parseHexRgbColorComponents(text) { - const mRgb = text.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/); - if (mRgb) { - return [ - parseInt(mRgb[1] + mRgb[1], 16), - parseInt(mRgb[2] + mRgb[2], 16), - parseInt(mRgb[3] + mRgb[3], 16), - ]; - } - const mRrggbb = text.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/); - if (mRrggbb) { - return [ - parseInt(mRrggbb[1], 16), - parseInt(mRrggbb[2], 16), - parseInt(mRrggbb[3], 16), - ]; - } - return null; - } - function parseHexRgbColor(text) { - const comps = parseHexRgbColorComponents(text); - return comps ? new Color(comps, 'rgb', 'int') : null; - } - function parseHexRgbaColorComponents(text) { - const mRgb = text.match(/^#?([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/); - if (mRgb) { - return [ - parseInt(mRgb[1] + mRgb[1], 16), - parseInt(mRgb[2] + mRgb[2], 16), - parseInt(mRgb[3] + mRgb[3], 16), - mapRange(parseInt(mRgb[4] + mRgb[4], 16), 0, 255, 0, 1), - ]; - } - const mRrggbb = text.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/); - if (mRrggbb) { - return [ - parseInt(mRrggbb[1], 16), - parseInt(mRrggbb[2], 16), - parseInt(mRrggbb[3], 16), - mapRange(parseInt(mRrggbb[4], 16), 0, 255, 0, 1), - ]; - } - return null; - } - function parseHexRgbaColor(text) { - const comps = parseHexRgbaColorComponents(text); - return comps ? new Color(comps, 'rgb', 'int') : null; - } - function parseObjectRgbColorComponents(text) { - const m = text.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/); - if (!m) { - return null; - } - const comps = [ - parseFloat(m[1]), - parseFloat(m[2]), - parseFloat(m[3]), - ]; - if (isNaN(comps[0]) || isNaN(comps[1]) || isNaN(comps[2])) { - return null; - } - return comps; - } - function createObjectRgbColorParser(type) { - return (text) => { - const comps = parseObjectRgbColorComponents(text); - return comps ? new Color(comps, 'rgb', type) : null; - }; - } - function parseObjectRgbaColorComponents(text) { - const m = text.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/); - if (!m) { - return null; - } - const comps = [ - parseFloat(m[1]), - parseFloat(m[2]), - parseFloat(m[3]), - parseFloat(m[4]), - ]; - if (isNaN(comps[0]) || - isNaN(comps[1]) || - isNaN(comps[2]) || - isNaN(comps[3])) { - return null; - } - return comps; - } - function createObjectRgbaColorParser(type) { - return (text) => { - const comps = parseObjectRgbaColorComponents(text); - return comps ? new Color(comps, 'rgb', type) : null; - }; - } - const PARSER_AND_RESULT = [ - { - parser: parseHexRgbColorComponents, - result: { - alpha: false, - mode: 'rgb', - notation: 'hex', - }, - }, - { - parser: parseHexRgbaColorComponents, - result: { - alpha: true, - mode: 'rgb', - notation: 'hex', - }, - }, - { - parser: parseFunctionalRgbColorComponents, - result: { - alpha: false, - mode: 'rgb', - notation: 'func', - }, - }, - { - parser: parseFunctionalRgbaColorComponents, - result: { - alpha: true, - mode: 'rgb', - notation: 'func', - }, - }, - { - parser: parseHslColorComponents, - result: { - alpha: false, - mode: 'hsl', - notation: 'func', - }, - }, - { - parser: parseHslaColorComponents, - result: { - alpha: true, - mode: 'hsl', - notation: 'func', - }, - }, - { - parser: parseObjectRgbColorComponents, - result: { - alpha: false, - mode: 'rgb', - notation: 'object', - }, - }, - { - parser: parseObjectRgbaColorComponents, - result: { - alpha: true, - mode: 'rgb', - notation: 'object', - }, - }, - ]; - function detectStringColor(text) { - return PARSER_AND_RESULT.reduce((prev, { parser, result: detection }) => { - if (prev) { - return prev; - } - return parser(text) ? detection : null; - }, null); - } - function detectStringColorFormat(text, type = 'int') { - const r = detectStringColor(text); - if (!r) { - return null; - } - if (r.notation === 'hex' && type !== 'float') { - return Object.assign(Object.assign({}, r), { type: 'int' }); - } - if (r.notation === 'func') { - return Object.assign(Object.assign({}, r), { type: type }); - } - return null; - } - const TYPE_TO_PARSERS = { - int: [ - parseHexRgbColor, - parseHexRgbaColor, - createFunctionalRgbColorParser('int'), - createFunctionalRgbaColorParser('int'), - createHslColorParser('int'), - createHslaColorParser('int'), - createObjectRgbColorParser('int'), - createObjectRgbaColorParser('int'), - ], - float: [ - createFunctionalRgbColorParser('float'), - createFunctionalRgbaColorParser('float'), - createHslColorParser('float'), - createHslaColorParser('float'), - createObjectRgbColorParser('float'), - createObjectRgbaColorParser('float'), - ], - }; - function createColorStringBindingReader(type) { - const parsers = TYPE_TO_PARSERS[type]; - return (value) => { - if (typeof value !== 'string') { - return Color.black(type); - } - const result = parsers.reduce((prev, parser) => { - if (prev) { - return prev; - } - return parser(value); - }, null); - return result !== null && result !== void 0 ? result : Color.black(type); - }; - } - function createColorStringParser(type) { - const parsers = TYPE_TO_PARSERS[type]; - return (value) => { - return parsers.reduce((prev, parser) => { - if (prev) { - return prev; - } - return parser(value); - }, null); - }; - } - function zerofill(comp) { - const hex = constrainRange(Math.floor(comp), 0, 255).toString(16); - return hex.length === 1 ? `0${hex}` : hex; - } - function colorToHexRgbString(value, prefix = '#') { - const hexes = removeAlphaComponent(value.getComponents('rgb')) - .map(zerofill) - .join(''); - return `${prefix}${hexes}`; - } - function colorToHexRgbaString(value, prefix = '#') { - const rgbaComps = value.getComponents('rgb'); - const hexes = [rgbaComps[0], rgbaComps[1], rgbaComps[2], rgbaComps[3] * 255] - .map(zerofill) - .join(''); - return `${prefix}${hexes}`; - } - function colorToFunctionalRgbString(value, opt_type) { - const formatter = createNumberFormatter(opt_type === 'float' ? 2 : 0); - const comps = removeAlphaComponent(value.getComponents('rgb', opt_type)).map((comp) => formatter(comp)); - return `rgb(${comps.join(', ')})`; - } - function createFunctionalRgbColorFormatter(type) { - return (value) => { - return colorToFunctionalRgbString(value, type); - }; - } - function colorToFunctionalRgbaString(value, opt_type) { - const aFormatter = createNumberFormatter(2); - const rgbFormatter = createNumberFormatter(opt_type === 'float' ? 2 : 0); - const comps = value.getComponents('rgb', opt_type).map((comp, index) => { - const formatter = index === 3 ? aFormatter : rgbFormatter; - return formatter(comp); - }); - return `rgba(${comps.join(', ')})`; - } - function createFunctionalRgbaColorFormatter(type) { - return (value) => { - return colorToFunctionalRgbaString(value, type); - }; - } - function colorToFunctionalHslString(value) { - const formatters = [ - createNumberFormatter(0), - formatPercentage, - formatPercentage, - ]; - const comps = removeAlphaComponent(value.getComponents('hsl')).map((comp, index) => formatters[index](comp)); - return `hsl(${comps.join(', ')})`; - } - function colorToFunctionalHslaString(value) { - const formatters = [ - createNumberFormatter(0), - formatPercentage, - formatPercentage, - createNumberFormatter(2), - ]; - const comps = value - .getComponents('hsl') - .map((comp, index) => formatters[index](comp)); - return `hsla(${comps.join(', ')})`; - } - function colorToObjectRgbString(value, type) { - const formatter = createNumberFormatter(type === 'float' ? 2 : 0); - const names = ['r', 'g', 'b']; - const comps = removeAlphaComponent(value.getComponents('rgb', type)).map((comp, index) => `${names[index]}: ${formatter(comp)}`); - return `{${comps.join(', ')}}`; - } - function createObjectRgbColorFormatter(type) { - return (value) => colorToObjectRgbString(value, type); - } - function colorToObjectRgbaString(value, type) { - const aFormatter = createNumberFormatter(2); - const rgbFormatter = createNumberFormatter(type === 'float' ? 2 : 0); - const names = ['r', 'g', 'b', 'a']; - const comps = value.getComponents('rgb', type).map((comp, index) => { - const formatter = index === 3 ? aFormatter : rgbFormatter; - return `${names[index]}: ${formatter(comp)}`; - }); - return `{${comps.join(', ')}}`; - } - function createObjectRgbaColorFormatter(type) { - return (value) => colorToObjectRgbaString(value, type); - } - const FORMAT_AND_STRINGIFIERS = [ - { - format: { - alpha: false, - mode: 'rgb', - notation: 'hex', - type: 'int', - }, - stringifier: colorToHexRgbString, - }, - { - format: { - alpha: true, - mode: 'rgb', - notation: 'hex', - type: 'int', - }, - stringifier: colorToHexRgbaString, - }, - { - format: { - alpha: false, - mode: 'hsl', - notation: 'func', - type: 'int', - }, - stringifier: colorToFunctionalHslString, - }, - { - format: { - alpha: true, - mode: 'hsl', - notation: 'func', - type: 'int', - }, - stringifier: colorToFunctionalHslaString, - }, - ...['int', 'float'].reduce((prev, type) => { - return [ - ...prev, - { - format: { - alpha: false, - mode: 'rgb', - notation: 'func', - type: type, - }, - stringifier: createFunctionalRgbColorFormatter(type), - }, - { - format: { - alpha: true, - mode: 'rgb', - notation: 'func', - type: type, - }, - stringifier: createFunctionalRgbaColorFormatter(type), - }, - { - format: { - alpha: false, - mode: 'rgb', - notation: 'object', - type: type, - }, - stringifier: createObjectRgbColorFormatter(type), - }, - { - format: { - alpha: true, - mode: 'rgb', - notation: 'object', - type: type, - }, - stringifier: createObjectRgbaColorFormatter(type), - }, - ]; - }, []), - ]; - function findColorStringifier(format) { - return FORMAT_AND_STRINGIFIERS.reduce((prev, fas) => { - if (prev) { - return prev; - } - return equalsStringColorFormat(fas.format, format) - ? fas.stringifier - : null; - }, null); - } - - const className$a = ClassName('apl'); - class APaletteView { - constructor(doc, config) { - this.onValueChange_ = this.onValueChange_.bind(this); - this.value = config.value; - this.value.emitter.on('change', this.onValueChange_); - this.element = doc.createElement('div'); - this.element.classList.add(className$a()); - config.viewProps.bindClassModifiers(this.element); - config.viewProps.bindTabIndex(this.element); - const barElem = doc.createElement('div'); - barElem.classList.add(className$a('b')); - this.element.appendChild(barElem); - const colorElem = doc.createElement('div'); - colorElem.classList.add(className$a('c')); - barElem.appendChild(colorElem); - this.colorElem_ = colorElem; - const markerElem = doc.createElement('div'); - markerElem.classList.add(className$a('m')); - this.element.appendChild(markerElem); - this.markerElem_ = markerElem; - const previewElem = doc.createElement('div'); - previewElem.classList.add(className$a('p')); - this.markerElem_.appendChild(previewElem); - this.previewElem_ = previewElem; - this.update_(); - } - update_() { - const c = this.value.rawValue; - const rgbaComps = c.getComponents('rgb'); - const leftColor = new Color([rgbaComps[0], rgbaComps[1], rgbaComps[2], 0], 'rgb'); - const rightColor = new Color([rgbaComps[0], rgbaComps[1], rgbaComps[2], 255], 'rgb'); - const gradientComps = [ - 'to right', - colorToFunctionalRgbaString(leftColor), - colorToFunctionalRgbaString(rightColor), - ]; - this.colorElem_.style.background = `linear-gradient(${gradientComps.join(',')})`; - this.previewElem_.style.backgroundColor = colorToFunctionalRgbaString(c); - const left = mapRange(rgbaComps[3], 0, 1, 0, 100); - this.markerElem_.style.left = `${left}%`; - } - onValueChange_() { - this.update_(); - } - } - - class APaletteController { - constructor(doc, config) { - this.onKeyDown_ = this.onKeyDown_.bind(this); - this.onKeyUp_ = this.onKeyUp_.bind(this); - this.onPointerDown_ = this.onPointerDown_.bind(this); - this.onPointerMove_ = this.onPointerMove_.bind(this); - this.onPointerUp_ = this.onPointerUp_.bind(this); - this.value = config.value; - this.viewProps = config.viewProps; - this.view = new APaletteView(doc, { - value: this.value, - viewProps: this.viewProps, - }); - this.ptHandler_ = new PointerHandler(this.view.element); - this.ptHandler_.emitter.on('down', this.onPointerDown_); - this.ptHandler_.emitter.on('move', this.onPointerMove_); - this.ptHandler_.emitter.on('up', this.onPointerUp_); - this.view.element.addEventListener('keydown', this.onKeyDown_); - this.view.element.addEventListener('keyup', this.onKeyUp_); - } - handlePointerEvent_(d, opts) { - if (!d.point) { - return; - } - const alpha = d.point.x / d.bounds.width; - const c = this.value.rawValue; - const [h, s, v] = c.getComponents('hsv'); - this.value.setRawValue(new Color([h, s, v, alpha], 'hsv'), opts); - } - onPointerDown_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: false, - last: false, - }); - } - onPointerMove_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: false, - last: false, - }); - } - onPointerUp_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: true, - last: true, - }); - } - onKeyDown_(ev) { - const step = getStepForKey(getBaseStepForColor(true), getHorizontalStepKeys(ev)); - if (step === 0) { - return; - } - const c = this.value.rawValue; - const [h, s, v, a] = c.getComponents('hsv'); - this.value.setRawValue(new Color([h, s, v, a + step], 'hsv'), { - forceEmit: false, - last: false, - }); - } - onKeyUp_(ev) { - const step = getStepForKey(getBaseStepForColor(true), getHorizontalStepKeys(ev)); - if (step === 0) { - return; - } - this.value.setRawValue(this.value.rawValue, { - forceEmit: true, - last: true, - }); - } - } - - const className$9 = ClassName('coltxt'); - function createModeSelectElement(doc) { - const selectElem = doc.createElement('select'); - const items = [ - { text: 'RGB', value: 'rgb' }, - { text: 'HSL', value: 'hsl' }, - { text: 'HSV', value: 'hsv' }, - ]; - selectElem.appendChild(items.reduce((frag, item) => { - const optElem = doc.createElement('option'); - optElem.textContent = item.text; - optElem.value = item.value; - frag.appendChild(optElem); - return frag; - }, doc.createDocumentFragment())); - return selectElem; - } - class ColorTextView { - constructor(doc, config) { - this.element = doc.createElement('div'); - this.element.classList.add(className$9()); - config.viewProps.bindClassModifiers(this.element); - const modeElem = doc.createElement('div'); - modeElem.classList.add(className$9('m')); - this.modeElem_ = createModeSelectElement(doc); - this.modeElem_.classList.add(className$9('ms')); - modeElem.appendChild(this.modeSelectElement); - config.viewProps.bindDisabled(this.modeElem_); - const modeMarkerElem = doc.createElement('div'); - modeMarkerElem.classList.add(className$9('mm')); - modeMarkerElem.appendChild(createSvgIconElement(doc, 'dropdown')); - modeElem.appendChild(modeMarkerElem); - this.element.appendChild(modeElem); - const textsElem = doc.createElement('div'); - textsElem.classList.add(className$9('w')); - this.element.appendChild(textsElem); - this.textsElem_ = textsElem; - this.textViews_ = config.textViews; - this.applyTextViews_(); - bindValue(config.colorMode, (mode) => { - this.modeElem_.value = mode; - }); - } - get modeSelectElement() { - return this.modeElem_; - } - get textViews() { - return this.textViews_; - } - set textViews(textViews) { - this.textViews_ = textViews; - this.applyTextViews_(); - } - applyTextViews_() { - removeChildElements(this.textsElem_); - const doc = this.element.ownerDocument; - this.textViews_.forEach((v) => { - const compElem = doc.createElement('div'); - compElem.classList.add(className$9('c')); - compElem.appendChild(v.element); - this.textsElem_.appendChild(compElem); - }); - } - } - - function createFormatter$2(type) { - return createNumberFormatter(type === 'float' ? 2 : 0); - } - function createConstraint$5(mode, type, index) { - const max = getColorMaxComponents(mode, type)[index]; - return new DefiniteRangeConstraint({ - min: 0, - max: max, - }); - } - function createComponentController(doc, config, index) { - return new NumberTextController(doc, { - arrayPosition: index === 0 ? 'fst' : index === 3 - 1 ? 'lst' : 'mid', - baseStep: getBaseStepForColor(false), - parser: config.parser, - props: ValueMap.fromObject({ - draggingScale: config.colorType === 'float' ? 0.01 : 1, - formatter: createFormatter$2(config.colorType), - }), - value: createValue(0, { - constraint: createConstraint$5(config.colorMode, config.colorType, index), - }), - viewProps: config.viewProps, - }); - } - class ColorTextController { - constructor(doc, config) { - this.onModeSelectChange_ = this.onModeSelectChange_.bind(this); - this.colorType_ = config.colorType; - this.parser_ = config.parser; - this.value = config.value; - this.viewProps = config.viewProps; - this.colorMode = createValue(this.value.rawValue.mode); - this.ccs_ = this.createComponentControllers_(doc); - this.view = new ColorTextView(doc, { - colorMode: this.colorMode, - textViews: [this.ccs_[0].view, this.ccs_[1].view, this.ccs_[2].view], - viewProps: this.viewProps, - }); - this.view.modeSelectElement.addEventListener('change', this.onModeSelectChange_); - } - createComponentControllers_(doc) { - const cc = { - colorMode: this.colorMode.rawValue, - colorType: this.colorType_, - parser: this.parser_, - viewProps: this.viewProps, - }; - const ccs = [ - createComponentController(doc, cc, 0), - createComponentController(doc, cc, 1), - createComponentController(doc, cc, 2), - ]; - ccs.forEach((cs, index) => { - connectValues({ - primary: this.value, - secondary: cs.value, - forward: (p) => { - return p.rawValue.getComponents(this.colorMode.rawValue, this.colorType_)[index]; - }, - backward: (p, s) => { - const pickedMode = this.colorMode.rawValue; - const comps = p.rawValue.getComponents(pickedMode, this.colorType_); - comps[index] = s.rawValue; - return new Color(appendAlphaComponent(removeAlphaComponent(comps), comps[3]), pickedMode, this.colorType_); - }, - }); - }); - return ccs; - } - onModeSelectChange_(ev) { - const selectElem = ev.currentTarget; - this.colorMode.rawValue = selectElem.value; - this.ccs_ = this.createComponentControllers_(this.view.element.ownerDocument); - this.view.textViews = [ - this.ccs_[0].view, - this.ccs_[1].view, - this.ccs_[2].view, - ]; - } - } - - const className$8 = ClassName('hpl'); - class HPaletteView { - constructor(doc, config) { - this.onValueChange_ = this.onValueChange_.bind(this); - this.value = config.value; - this.value.emitter.on('change', this.onValueChange_); - this.element = doc.createElement('div'); - this.element.classList.add(className$8()); - config.viewProps.bindClassModifiers(this.element); - config.viewProps.bindTabIndex(this.element); - const colorElem = doc.createElement('div'); - colorElem.classList.add(className$8('c')); - this.element.appendChild(colorElem); - const markerElem = doc.createElement('div'); - markerElem.classList.add(className$8('m')); - this.element.appendChild(markerElem); - this.markerElem_ = markerElem; - this.update_(); - } - update_() { - const c = this.value.rawValue; - const [h] = c.getComponents('hsv'); - this.markerElem_.style.backgroundColor = colorToFunctionalRgbString(new Color([h, 100, 100], 'hsv')); - const left = mapRange(h, 0, 360, 0, 100); - this.markerElem_.style.left = `${left}%`; - } - onValueChange_() { - this.update_(); - } - } - - class HPaletteController { - constructor(doc, config) { - this.onKeyDown_ = this.onKeyDown_.bind(this); - this.onKeyUp_ = this.onKeyUp_.bind(this); - this.onPointerDown_ = this.onPointerDown_.bind(this); - this.onPointerMove_ = this.onPointerMove_.bind(this); - this.onPointerUp_ = this.onPointerUp_.bind(this); - this.value = config.value; - this.viewProps = config.viewProps; - this.view = new HPaletteView(doc, { - value: this.value, - viewProps: this.viewProps, - }); - this.ptHandler_ = new PointerHandler(this.view.element); - this.ptHandler_.emitter.on('down', this.onPointerDown_); - this.ptHandler_.emitter.on('move', this.onPointerMove_); - this.ptHandler_.emitter.on('up', this.onPointerUp_); - this.view.element.addEventListener('keydown', this.onKeyDown_); - this.view.element.addEventListener('keyup', this.onKeyUp_); - } - handlePointerEvent_(d, opts) { - if (!d.point) { - return; - } - const hue = mapRange(constrainRange(d.point.x, 0, d.bounds.width), 0, d.bounds.width, 0, 360); - const c = this.value.rawValue; - const [, s, v, a] = c.getComponents('hsv'); - this.value.setRawValue(new Color([hue, s, v, a], 'hsv'), opts); - } - onPointerDown_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: false, - last: false, - }); - } - onPointerMove_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: false, - last: false, - }); - } - onPointerUp_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: true, - last: true, - }); - } - onKeyDown_(ev) { - const step = getStepForKey(getBaseStepForColor(false), getHorizontalStepKeys(ev)); - if (step === 0) { - return; - } - const c = this.value.rawValue; - const [h, s, v, a] = c.getComponents('hsv'); - this.value.setRawValue(new Color([h + step, s, v, a], 'hsv'), { - forceEmit: false, - last: false, - }); - } - onKeyUp_(ev) { - const step = getStepForKey(getBaseStepForColor(false), getHorizontalStepKeys(ev)); - if (step === 0) { - return; - } - this.value.setRawValue(this.value.rawValue, { - forceEmit: true, - last: true, - }); - } - } - - const className$7 = ClassName('svp'); - const CANVAS_RESOL = 64; - class SvPaletteView { - constructor(doc, config) { - this.onValueChange_ = this.onValueChange_.bind(this); - this.value = config.value; - this.value.emitter.on('change', this.onValueChange_); - this.element = doc.createElement('div'); - this.element.classList.add(className$7()); - config.viewProps.bindClassModifiers(this.element); - config.viewProps.bindTabIndex(this.element); - const canvasElem = doc.createElement('canvas'); - canvasElem.height = CANVAS_RESOL; - canvasElem.width = CANVAS_RESOL; - canvasElem.classList.add(className$7('c')); - this.element.appendChild(canvasElem); - this.canvasElement = canvasElem; - const markerElem = doc.createElement('div'); - markerElem.classList.add(className$7('m')); - this.element.appendChild(markerElem); - this.markerElem_ = markerElem; - this.update_(); - } - update_() { - const ctx = getCanvasContext(this.canvasElement); - if (!ctx) { - return; - } - const c = this.value.rawValue; - const hsvComps = c.getComponents('hsv'); - const width = this.canvasElement.width; - const height = this.canvasElement.height; - const imgData = ctx.getImageData(0, 0, width, height); - const data = imgData.data; - for (let iy = 0; iy < height; iy++) { - for (let ix = 0; ix < width; ix++) { - const s = mapRange(ix, 0, width, 0, 100); - const v = mapRange(iy, 0, height, 100, 0); - const rgbComps = hsvToRgbInt(hsvComps[0], s, v); - const i = (iy * width + ix) * 4; - data[i] = rgbComps[0]; - data[i + 1] = rgbComps[1]; - data[i + 2] = rgbComps[2]; - data[i + 3] = 255; - } - } - ctx.putImageData(imgData, 0, 0); - const left = mapRange(hsvComps[1], 0, 100, 0, 100); - this.markerElem_.style.left = `${left}%`; - const top = mapRange(hsvComps[2], 0, 100, 100, 0); - this.markerElem_.style.top = `${top}%`; - } - onValueChange_() { - this.update_(); - } - } - - class SvPaletteController { - constructor(doc, config) { - this.onKeyDown_ = this.onKeyDown_.bind(this); - this.onKeyUp_ = this.onKeyUp_.bind(this); - this.onPointerDown_ = this.onPointerDown_.bind(this); - this.onPointerMove_ = this.onPointerMove_.bind(this); - this.onPointerUp_ = this.onPointerUp_.bind(this); - this.value = config.value; - this.viewProps = config.viewProps; - this.view = new SvPaletteView(doc, { - value: this.value, - viewProps: this.viewProps, - }); - this.ptHandler_ = new PointerHandler(this.view.element); - this.ptHandler_.emitter.on('down', this.onPointerDown_); - this.ptHandler_.emitter.on('move', this.onPointerMove_); - this.ptHandler_.emitter.on('up', this.onPointerUp_); - this.view.element.addEventListener('keydown', this.onKeyDown_); - this.view.element.addEventListener('keyup', this.onKeyUp_); - } - handlePointerEvent_(d, opts) { - if (!d.point) { - return; - } - const saturation = mapRange(d.point.x, 0, d.bounds.width, 0, 100); - const value = mapRange(d.point.y, 0, d.bounds.height, 100, 0); - const [h, , , a] = this.value.rawValue.getComponents('hsv'); - this.value.setRawValue(new Color([h, saturation, value, a], 'hsv'), opts); - } - onPointerDown_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: false, - last: false, - }); - } - onPointerMove_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: false, - last: false, - }); - } - onPointerUp_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: true, - last: true, - }); - } - onKeyDown_(ev) { - if (isArrowKey(ev.key)) { - ev.preventDefault(); - } - const [h, s, v, a] = this.value.rawValue.getComponents('hsv'); - const baseStep = getBaseStepForColor(false); - const ds = getStepForKey(baseStep, getHorizontalStepKeys(ev)); - const dv = getStepForKey(baseStep, getVerticalStepKeys(ev)); - if (ds === 0 && dv === 0) { - return; - } - this.value.setRawValue(new Color([h, s + ds, v + dv, a], 'hsv'), { - forceEmit: false, - last: false, - }); - } - onKeyUp_(ev) { - const baseStep = getBaseStepForColor(false); - const ds = getStepForKey(baseStep, getHorizontalStepKeys(ev)); - const dv = getStepForKey(baseStep, getVerticalStepKeys(ev)); - if (ds === 0 && dv === 0) { - return; - } - this.value.setRawValue(this.value.rawValue, { - forceEmit: true, - last: true, - }); - } - } - - class ColorPickerController { - constructor(doc, config) { - this.value = config.value; - this.viewProps = config.viewProps; - this.hPaletteC_ = new HPaletteController(doc, { - value: this.value, - viewProps: this.viewProps, - }); - this.svPaletteC_ = new SvPaletteController(doc, { - value: this.value, - viewProps: this.viewProps, - }); - this.alphaIcs_ = config.supportsAlpha - ? { - palette: new APaletteController(doc, { - value: this.value, - viewProps: this.viewProps, - }), - text: new NumberTextController(doc, { - parser: parseNumber, - baseStep: 0.1, - props: ValueMap.fromObject({ - draggingScale: 0.01, - formatter: createNumberFormatter(2), - }), - value: createValue(0, { - constraint: new DefiniteRangeConstraint({ min: 0, max: 1 }), - }), - viewProps: this.viewProps, - }), - } - : null; - if (this.alphaIcs_) { - connectValues({ - primary: this.value, - secondary: this.alphaIcs_.text.value, - forward: (p) => { - return p.rawValue.getComponents()[3]; - }, - backward: (p, s) => { - const comps = p.rawValue.getComponents(); - comps[3] = s.rawValue; - return new Color(comps, p.rawValue.mode); - }, - }); - } - this.textC_ = new ColorTextController(doc, { - colorType: config.colorType, - parser: parseNumber, - value: this.value, - viewProps: this.viewProps, - }); - this.view = new ColorPickerView(doc, { - alphaViews: this.alphaIcs_ - ? { - palette: this.alphaIcs_.palette.view, - text: this.alphaIcs_.text.view, - } - : null, - hPaletteView: this.hPaletteC_.view, - supportsAlpha: config.supportsAlpha, - svPaletteView: this.svPaletteC_.view, - textView: this.textC_.view, - viewProps: this.viewProps, - }); - } - get textController() { - return this.textC_; - } - } - - const className$6 = ClassName('colsw'); - class ColorSwatchView { - constructor(doc, config) { - this.onValueChange_ = this.onValueChange_.bind(this); - config.value.emitter.on('change', this.onValueChange_); - this.value = config.value; - this.element = doc.createElement('div'); - this.element.classList.add(className$6()); - config.viewProps.bindClassModifiers(this.element); - const swatchElem = doc.createElement('div'); - swatchElem.classList.add(className$6('sw')); - this.element.appendChild(swatchElem); - this.swatchElem_ = swatchElem; - const buttonElem = doc.createElement('button'); - buttonElem.classList.add(className$6('b')); - config.viewProps.bindDisabled(buttonElem); - this.element.appendChild(buttonElem); - this.buttonElement = buttonElem; - this.update_(); - } - update_() { - const value = this.value.rawValue; - this.swatchElem_.style.backgroundColor = colorToHexRgbaString(value); - } - onValueChange_() { - this.update_(); - } - } - - class ColorSwatchController { - constructor(doc, config) { - this.value = config.value; - this.viewProps = config.viewProps; - this.view = new ColorSwatchView(doc, { - value: this.value, - viewProps: this.viewProps, - }); - } - } - - class ColorController { - constructor(doc, config) { - this.onButtonBlur_ = this.onButtonBlur_.bind(this); - this.onButtonClick_ = this.onButtonClick_.bind(this); - this.onPopupChildBlur_ = this.onPopupChildBlur_.bind(this); - this.onPopupChildKeydown_ = this.onPopupChildKeydown_.bind(this); - this.value = config.value; - this.viewProps = config.viewProps; - this.foldable_ = Foldable.create(config.expanded); - this.swatchC_ = new ColorSwatchController(doc, { - value: this.value, - viewProps: this.viewProps, - }); - const buttonElem = this.swatchC_.view.buttonElement; - buttonElem.addEventListener('blur', this.onButtonBlur_); - buttonElem.addEventListener('click', this.onButtonClick_); - this.textC_ = new TextController(doc, { - parser: config.parser, - props: ValueMap.fromObject({ - formatter: config.formatter, - }), - value: this.value, - viewProps: this.viewProps, - }); - this.view = new ColorView(doc, { - foldable: this.foldable_, - pickerLayout: config.pickerLayout, - }); - this.view.swatchElement.appendChild(this.swatchC_.view.element); - this.view.textElement.appendChild(this.textC_.view.element); - this.popC_ = - config.pickerLayout === 'popup' - ? new PopupController(doc, { - viewProps: this.viewProps, - }) - : null; - const pickerC = new ColorPickerController(doc, { - colorType: config.colorType, - supportsAlpha: config.supportsAlpha, - value: this.value, - viewProps: this.viewProps, - }); - pickerC.view.allFocusableElements.forEach((elem) => { - elem.addEventListener('blur', this.onPopupChildBlur_); - elem.addEventListener('keydown', this.onPopupChildKeydown_); - }); - this.pickerC_ = pickerC; - if (this.popC_) { - this.view.element.appendChild(this.popC_.view.element); - this.popC_.view.element.appendChild(pickerC.view.element); - connectValues({ - primary: this.foldable_.value('expanded'), - secondary: this.popC_.shows, - forward: (p) => p.rawValue, - backward: (_, s) => s.rawValue, - }); - } - else if (this.view.pickerElement) { - this.view.pickerElement.appendChild(this.pickerC_.view.element); - bindFoldable(this.foldable_, this.view.pickerElement); - } - } - get textController() { - return this.textC_; - } - onButtonBlur_(e) { - if (!this.popC_) { - return; - } - const elem = this.view.element; - const nextTarget = forceCast(e.relatedTarget); - if (!nextTarget || !elem.contains(nextTarget)) { - this.popC_.shows.rawValue = false; - } - } - onButtonClick_() { - this.foldable_.set('expanded', !this.foldable_.get('expanded')); - if (this.foldable_.get('expanded')) { - this.pickerC_.view.allFocusableElements[0].focus(); - } - } - onPopupChildBlur_(ev) { - if (!this.popC_) { - return; - } - const elem = this.popC_.view.element; - const nextTarget = findNextTarget(ev); - if (nextTarget && elem.contains(nextTarget)) { - return; - } - if (nextTarget && - nextTarget === this.swatchC_.view.buttonElement && - !supportsTouch(elem.ownerDocument)) { - return; - } - this.popC_.shows.rawValue = false; - } - onPopupChildKeydown_(ev) { - if (this.popC_) { - if (ev.key === 'Escape') { - this.popC_.shows.rawValue = false; - } - } - else if (this.view.pickerElement) { - if (ev.key === 'Escape') { - this.swatchC_.view.buttonElement.focus(); - } - } - } - } - - function colorFromObject(value, opt_type) { - if (Color.isColorObject(value)) { - return Color.fromObject(value, opt_type); - } - return Color.black(opt_type); - } - function colorToRgbNumber(value) { - return removeAlphaComponent(value.getComponents('rgb')).reduce((result, comp) => { - return (result << 8) | (Math.floor(comp) & 0xff); - }, 0); - } - function colorToRgbaNumber(value) { - return (value.getComponents('rgb').reduce((result, comp, index) => { - const hex = Math.floor(index === 3 ? comp * 255 : comp) & 0xff; - return (result << 8) | hex; - }, 0) >>> 0); - } - function numberToRgbColor(num) { - return new Color([(num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff], 'rgb'); - } - function numberToRgbaColor(num) { - return new Color([ - (num >> 24) & 0xff, - (num >> 16) & 0xff, - (num >> 8) & 0xff, - mapRange(num & 0xff, 0, 255, 0, 1), - ], 'rgb'); - } - function colorFromRgbNumber(value) { - if (typeof value !== 'number') { - return Color.black(); - } - return numberToRgbColor(value); - } - function colorFromRgbaNumber(value) { - if (typeof value !== 'number') { - return Color.black(); - } - return numberToRgbaColor(value); - } - - function createColorStringWriter(format) { - const stringify = findColorStringifier(format); - return stringify - ? (target, value) => { - writePrimitive(target, stringify(value)); - } - : null; - } - function createColorNumberWriter(supportsAlpha) { - const colorToNumber = supportsAlpha ? colorToRgbaNumber : colorToRgbNumber; - return (target, value) => { - writePrimitive(target, colorToNumber(value)); - }; - } - function writeRgbaColorObject(target, value, opt_type) { - const obj = value.toRgbaObject(opt_type); - target.writeProperty('r', obj.r); - target.writeProperty('g', obj.g); - target.writeProperty('b', obj.b); - target.writeProperty('a', obj.a); - } - function writeRgbColorObject(target, value, opt_type) { - const obj = value.toRgbaObject(opt_type); - target.writeProperty('r', obj.r); - target.writeProperty('g', obj.g); - target.writeProperty('b', obj.b); - } - function createColorObjectWriter(supportsAlpha, opt_type) { - return (target, inValue) => { - if (supportsAlpha) { - writeRgbaColorObject(target, inValue, opt_type); - } - else { - writeRgbColorObject(target, inValue, opt_type); - } - }; - } - - function shouldSupportAlpha$1(inputParams) { - var _a; - if ((inputParams === null || inputParams === void 0 ? void 0 : inputParams.alpha) || ((_a = inputParams === null || inputParams === void 0 ? void 0 : inputParams.color) === null || _a === void 0 ? void 0 : _a.alpha)) { - return true; - } - return false; - } - function createFormatter$1(supportsAlpha) { - return supportsAlpha - ? (v) => colorToHexRgbaString(v, '0x') - : (v) => colorToHexRgbString(v, '0x'); - } - function isForColor(params) { - if ('color' in params) { - return true; - } - if ('view' in params && params.view === 'color') { - return true; - } - return false; - } - const NumberColorInputPlugin = { - id: 'input-color-number', - type: 'input', - accept: (value, params) => { - if (typeof value !== 'number') { - return null; - } - if (!isForColor(params)) { - return null; - } - const result = parseColorInputParams(params); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (args) => { - return shouldSupportAlpha$1(args.params) - ? colorFromRgbaNumber - : colorFromRgbNumber; - }, - equals: Color.equals, - writer: (args) => { - return createColorNumberWriter(shouldSupportAlpha$1(args.params)); - }, - }, - controller: (args) => { - const supportsAlpha = shouldSupportAlpha$1(args.params); - const expanded = 'expanded' in args.params ? args.params.expanded : undefined; - const picker = 'picker' in args.params ? args.params.picker : undefined; - return new ColorController(args.document, { - colorType: 'int', - expanded: expanded !== null && expanded !== void 0 ? expanded : false, - formatter: createFormatter$1(supportsAlpha), - parser: createColorStringParser('int'), - pickerLayout: picker !== null && picker !== void 0 ? picker : 'popup', - supportsAlpha: supportsAlpha, - value: args.value, - viewProps: args.viewProps, - }); - }, - }; - - function shouldSupportAlpha(initialValue) { - return Color.isRgbaColorObject(initialValue); - } - function createColorObjectReader(opt_type) { - return (value) => { - return colorFromObject(value, opt_type); - }; - } - function createColorObjectFormatter(supportsAlpha, type) { - return (value) => { - if (supportsAlpha) { - return colorToObjectRgbaString(value, type); - } - return colorToObjectRgbString(value, type); - }; - } - const ObjectColorInputPlugin = { - id: 'input-color-object', - type: 'input', - accept: (value, params) => { - if (!Color.isColorObject(value)) { - return null; - } - const result = parseColorInputParams(params); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (args) => createColorObjectReader(extractColorType(args.params)), - equals: Color.equals, - writer: (args) => createColorObjectWriter(shouldSupportAlpha(args.initialValue), extractColorType(args.params)), - }, - controller: (args) => { - var _a; - const supportsAlpha = Color.isRgbaColorObject(args.initialValue); - const expanded = 'expanded' in args.params ? args.params.expanded : undefined; - const picker = 'picker' in args.params ? args.params.picker : undefined; - const type = (_a = extractColorType(args.params)) !== null && _a !== void 0 ? _a : 'int'; - return new ColorController(args.document, { - colorType: type, - expanded: expanded !== null && expanded !== void 0 ? expanded : false, - formatter: createColorObjectFormatter(supportsAlpha, type), - parser: createColorStringParser(type), - pickerLayout: picker !== null && picker !== void 0 ? picker : 'popup', - supportsAlpha: supportsAlpha, - value: args.value, - viewProps: args.viewProps, - }); - }, - }; - - const StringColorInputPlugin = { - id: 'input-color-string', - type: 'input', - accept: (value, params) => { - if (typeof value !== 'string') { - return null; - } - if ('view' in params && params.view === 'text') { - return null; - } - const format = detectStringColorFormat(value, extractColorType(params)); - if (!format) { - return null; - } - const stringifier = findColorStringifier(format); - if (!stringifier) { - return null; - } - const result = parseColorInputParams(params); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (args) => { var _a; return createColorStringBindingReader((_a = extractColorType(args.params)) !== null && _a !== void 0 ? _a : 'int'); }, - equals: Color.equals, - writer: (args) => { - const format = detectStringColorFormat(args.initialValue, extractColorType(args.params)); - if (!format) { - throw TpError.shouldNeverHappen(); - } - const writer = createColorStringWriter(format); - if (!writer) { - throw TpError.notBindable(); - } - return writer; - }, - }, - controller: (args) => { - const format = detectStringColorFormat(args.initialValue, extractColorType(args.params)); - if (!format) { - throw TpError.shouldNeverHappen(); - } - const stringifier = findColorStringifier(format); - if (!stringifier) { - throw TpError.shouldNeverHappen(); - } - const expanded = 'expanded' in args.params ? args.params.expanded : undefined; - const picker = 'picker' in args.params ? args.params.picker : undefined; - return new ColorController(args.document, { - colorType: format.type, - expanded: expanded !== null && expanded !== void 0 ? expanded : false, - formatter: stringifier, - parser: createColorStringParser(format.type), - pickerLayout: picker !== null && picker !== void 0 ? picker : 'popup', - supportsAlpha: format.alpha, - value: args.value, - viewProps: args.viewProps, - }); - }, - }; - - class PointNdConstraint { - constructor(config) { - this.components = config.components; - this.asm_ = config.assembly; - } - constrain(value) { - const comps = this.asm_ - .toComponents(value) - .map((comp, index) => { var _a, _b; return (_b = (_a = this.components[index]) === null || _a === void 0 ? void 0 : _a.constrain(comp)) !== null && _b !== void 0 ? _b : comp; }); - return this.asm_.fromComponents(comps); - } - } - - const className$5 = ClassName('pndtxt'); - class PointNdTextView { - constructor(doc, config) { - this.textViews = config.textViews; - this.element = doc.createElement('div'); - this.element.classList.add(className$5()); - this.textViews.forEach((v) => { - const axisElem = doc.createElement('div'); - axisElem.classList.add(className$5('a')); - axisElem.appendChild(v.element); - this.element.appendChild(axisElem); - }); - } - } - - function createAxisController(doc, config, index) { - return new NumberTextController(doc, { - arrayPosition: index === 0 ? 'fst' : index === config.axes.length - 1 ? 'lst' : 'mid', - baseStep: config.axes[index].baseStep, - parser: config.parser, - props: config.axes[index].textProps, - value: createValue(0, { - constraint: config.axes[index].constraint, - }), - viewProps: config.viewProps, - }); - } - class PointNdTextController { - constructor(doc, config) { - this.value = config.value; - this.viewProps = config.viewProps; - this.acs_ = config.axes.map((_, index) => createAxisController(doc, config, index)); - this.acs_.forEach((c, index) => { - connectValues({ - primary: this.value, - secondary: c.value, - forward: (p) => { - return config.assembly.toComponents(p.rawValue)[index]; - }, - backward: (p, s) => { - const comps = config.assembly.toComponents(p.rawValue); - comps[index] = s.rawValue; - return config.assembly.fromComponents(comps); - }, - }); - }); - this.view = new PointNdTextView(doc, { - textViews: this.acs_.map((ac) => ac.view), - }); - } - } - - function createStepConstraint(params, initialValue) { - if ('step' in params && !isEmpty(params.step)) { - return new StepConstraint(params.step, initialValue); - } - return null; - } - function createRangeConstraint(params) { - if (!isEmpty(params.max) && !isEmpty(params.min)) { - return new DefiniteRangeConstraint({ - max: params.max, - min: params.min, - }); - } - if (!isEmpty(params.max) || !isEmpty(params.min)) { - return new RangeConstraint({ - max: params.max, - min: params.min, - }); - } - return null; - } - function findNumberRange(c) { - const drc = findConstraint(c, DefiniteRangeConstraint); - if (drc) { - return [drc.values.get('min'), drc.values.get('max')]; - } - const rc = findConstraint(c, RangeConstraint); - if (rc) { - return [rc.minValue, rc.maxValue]; - } - return [undefined, undefined]; - } - function createConstraint$4(params, - initialValue) { - const constraints = []; - const sc = createStepConstraint(params, initialValue); - if (sc) { - constraints.push(sc); - } - const rc = createRangeConstraint(params); - if (rc) { - constraints.push(rc); - } - const lc = createListConstraint(params.options); - if (lc) { - constraints.push(lc); - } - return new CompositeConstraint(constraints); - } - const NumberInputPlugin = { - id: 'input-number', - type: 'input', - accept: (value, params) => { - if (typeof value !== 'number') { - return null; - } - const p = ParamsParsers; - const result = parseParams(params, { - format: p.optional.function, - max: p.optional.number, - min: p.optional.number, - options: p.optional.custom(parseListOptions), - step: p.optional.number, - }); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (_args) => numberFromUnknown, - constraint: (args) => createConstraint$4(args.params, args.initialValue), - writer: (_args) => writePrimitive, - }, - controller: (args) => { - var _a; - const value = args.value; - const c = args.constraint; - const lc = c && findConstraint(c, ListConstraint); - if (lc) { - return new ListController(args.document, { - props: new ValueMap({ - options: lc.values.value('options'), - }), - value: value, - viewProps: args.viewProps, - }); - } - const formatter = (_a = ('format' in args.params ? args.params.format : undefined)) !== null && _a !== void 0 ? _a : createNumberFormatter(getSuitableDecimalDigits(c, value.rawValue)); - const drc = c && findConstraint(c, DefiniteRangeConstraint); - if (drc) { - return new SliderTextController(args.document, { - baseStep: getBaseStep(c), - parser: parseNumber, - sliderProps: new ValueMap({ - maxValue: drc.values.value('max'), - minValue: drc.values.value('min'), - }), - textProps: ValueMap.fromObject({ - draggingScale: getSuitableDraggingScale(c, value.rawValue), - formatter: formatter, - }), - value: value, - viewProps: args.viewProps, - }); - } - return new NumberTextController(args.document, { - baseStep: getBaseStep(c), - parser: parseNumber, - props: ValueMap.fromObject({ - draggingScale: getSuitableDraggingScale(c, value.rawValue), - formatter: formatter, - }), - value: value, - viewProps: args.viewProps, - }); - }, - }; - - class Point2d { - constructor(x = 0, y = 0) { - this.x = x; - this.y = y; - } - getComponents() { - return [this.x, this.y]; - } - static isObject(obj) { - if (isEmpty(obj)) { - return false; - } - const x = obj.x; - const y = obj.y; - if (typeof x !== 'number' || typeof y !== 'number') { - return false; - } - return true; - } - static equals(v1, v2) { - return v1.x === v2.x && v1.y === v2.y; - } - toObject() { - return { - x: this.x, - y: this.y, - }; - } - } - const Point2dAssembly = { - toComponents: (p) => p.getComponents(), - fromComponents: (comps) => new Point2d(...comps), - }; - - const className$4 = ClassName('p2d'); - class Point2dView { - constructor(doc, config) { - this.element = doc.createElement('div'); - this.element.classList.add(className$4()); - config.viewProps.bindClassModifiers(this.element); - bindValue(config.expanded, valueToClassName(this.element, className$4(undefined, 'expanded'))); - const headElem = doc.createElement('div'); - headElem.classList.add(className$4('h')); - this.element.appendChild(headElem); - const buttonElem = doc.createElement('button'); - buttonElem.classList.add(className$4('b')); - buttonElem.appendChild(createSvgIconElement(doc, 'p2dpad')); - config.viewProps.bindDisabled(buttonElem); - headElem.appendChild(buttonElem); - this.buttonElement = buttonElem; - const textElem = doc.createElement('div'); - textElem.classList.add(className$4('t')); - headElem.appendChild(textElem); - this.textElement = textElem; - if (config.pickerLayout === 'inline') { - const pickerElem = doc.createElement('div'); - pickerElem.classList.add(className$4('p')); - this.element.appendChild(pickerElem); - this.pickerElement = pickerElem; - } - else { - this.pickerElement = null; - } - } - } - - const className$3 = ClassName('p2dp'); - class Point2dPickerView { - constructor(doc, config) { - this.onFoldableChange_ = this.onFoldableChange_.bind(this); - this.onValueChange_ = this.onValueChange_.bind(this); - this.invertsY_ = config.invertsY; - this.maxValue_ = config.maxValue; - this.element = doc.createElement('div'); - this.element.classList.add(className$3()); - if (config.layout === 'popup') { - this.element.classList.add(className$3(undefined, 'p')); - } - config.viewProps.bindClassModifiers(this.element); - const padElem = doc.createElement('div'); - padElem.classList.add(className$3('p')); - config.viewProps.bindTabIndex(padElem); - this.element.appendChild(padElem); - this.padElement = padElem; - const svgElem = doc.createElementNS(SVG_NS, 'svg'); - svgElem.classList.add(className$3('g')); - this.padElement.appendChild(svgElem); - this.svgElem_ = svgElem; - const xAxisElem = doc.createElementNS(SVG_NS, 'line'); - xAxisElem.classList.add(className$3('ax')); - xAxisElem.setAttributeNS(null, 'x1', '0'); - xAxisElem.setAttributeNS(null, 'y1', '50%'); - xAxisElem.setAttributeNS(null, 'x2', '100%'); - xAxisElem.setAttributeNS(null, 'y2', '50%'); - this.svgElem_.appendChild(xAxisElem); - const yAxisElem = doc.createElementNS(SVG_NS, 'line'); - yAxisElem.classList.add(className$3('ax')); - yAxisElem.setAttributeNS(null, 'x1', '50%'); - yAxisElem.setAttributeNS(null, 'y1', '0'); - yAxisElem.setAttributeNS(null, 'x2', '50%'); - yAxisElem.setAttributeNS(null, 'y2', '100%'); - this.svgElem_.appendChild(yAxisElem); - const lineElem = doc.createElementNS(SVG_NS, 'line'); - lineElem.classList.add(className$3('l')); - lineElem.setAttributeNS(null, 'x1', '50%'); - lineElem.setAttributeNS(null, 'y1', '50%'); - this.svgElem_.appendChild(lineElem); - this.lineElem_ = lineElem; - const markerElem = doc.createElement('div'); - markerElem.classList.add(className$3('m')); - this.padElement.appendChild(markerElem); - this.markerElem_ = markerElem; - config.value.emitter.on('change', this.onValueChange_); - this.value = config.value; - this.update_(); - } - get allFocusableElements() { - return [this.padElement]; - } - update_() { - const [x, y] = this.value.rawValue.getComponents(); - const max = this.maxValue_; - const px = mapRange(x, -max, +max, 0, 100); - const py = mapRange(y, -max, +max, 0, 100); - const ipy = this.invertsY_ ? 100 - py : py; - this.lineElem_.setAttributeNS(null, 'x2', `${px}%`); - this.lineElem_.setAttributeNS(null, 'y2', `${ipy}%`); - this.markerElem_.style.left = `${px}%`; - this.markerElem_.style.top = `${ipy}%`; - } - onValueChange_() { - this.update_(); - } - onFoldableChange_() { - this.update_(); - } - } - - function computeOffset(ev, baseSteps, invertsY) { - return [ - getStepForKey(baseSteps[0], getHorizontalStepKeys(ev)), - getStepForKey(baseSteps[1], getVerticalStepKeys(ev)) * (invertsY ? 1 : -1), - ]; - } - class Point2dPickerController { - constructor(doc, config) { - this.onPadKeyDown_ = this.onPadKeyDown_.bind(this); - this.onPadKeyUp_ = this.onPadKeyUp_.bind(this); - this.onPointerDown_ = this.onPointerDown_.bind(this); - this.onPointerMove_ = this.onPointerMove_.bind(this); - this.onPointerUp_ = this.onPointerUp_.bind(this); - this.value = config.value; - this.viewProps = config.viewProps; - this.baseSteps_ = config.baseSteps; - this.maxValue_ = config.maxValue; - this.invertsY_ = config.invertsY; - this.view = new Point2dPickerView(doc, { - invertsY: this.invertsY_, - layout: config.layout, - maxValue: this.maxValue_, - value: this.value, - viewProps: this.viewProps, - }); - this.ptHandler_ = new PointerHandler(this.view.padElement); - this.ptHandler_.emitter.on('down', this.onPointerDown_); - this.ptHandler_.emitter.on('move', this.onPointerMove_); - this.ptHandler_.emitter.on('up', this.onPointerUp_); - this.view.padElement.addEventListener('keydown', this.onPadKeyDown_); - this.view.padElement.addEventListener('keyup', this.onPadKeyUp_); - } - handlePointerEvent_(d, opts) { - if (!d.point) { - return; - } - const max = this.maxValue_; - const px = mapRange(d.point.x, 0, d.bounds.width, -max, +max); - const py = mapRange(this.invertsY_ ? d.bounds.height - d.point.y : d.point.y, 0, d.bounds.height, -max, +max); - this.value.setRawValue(new Point2d(px, py), opts); - } - onPointerDown_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: false, - last: false, - }); - } - onPointerMove_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: false, - last: false, - }); - } - onPointerUp_(ev) { - this.handlePointerEvent_(ev.data, { - forceEmit: true, - last: true, - }); - } - onPadKeyDown_(ev) { - if (isArrowKey(ev.key)) { - ev.preventDefault(); - } - const [dx, dy] = computeOffset(ev, this.baseSteps_, this.invertsY_); - if (dx === 0 && dy === 0) { - return; - } - this.value.setRawValue(new Point2d(this.value.rawValue.x + dx, this.value.rawValue.y + dy), { - forceEmit: false, - last: false, - }); - } - onPadKeyUp_(ev) { - const [dx, dy] = computeOffset(ev, this.baseSteps_, this.invertsY_); - if (dx === 0 && dy === 0) { - return; - } - this.value.setRawValue(this.value.rawValue, { - forceEmit: true, - last: true, - }); - } - } - - class Point2dController { - constructor(doc, config) { - var _a, _b; - this.onPopupChildBlur_ = this.onPopupChildBlur_.bind(this); - this.onPopupChildKeydown_ = this.onPopupChildKeydown_.bind(this); - this.onPadButtonBlur_ = this.onPadButtonBlur_.bind(this); - this.onPadButtonClick_ = this.onPadButtonClick_.bind(this); - this.value = config.value; - this.viewProps = config.viewProps; - this.foldable_ = Foldable.create(config.expanded); - this.popC_ = - config.pickerLayout === 'popup' - ? new PopupController(doc, { - viewProps: this.viewProps, - }) - : null; - const padC = new Point2dPickerController(doc, { - baseSteps: [config.axes[0].baseStep, config.axes[1].baseStep], - invertsY: config.invertsY, - layout: config.pickerLayout, - maxValue: config.maxValue, - value: this.value, - viewProps: this.viewProps, - }); - padC.view.allFocusableElements.forEach((elem) => { - elem.addEventListener('blur', this.onPopupChildBlur_); - elem.addEventListener('keydown', this.onPopupChildKeydown_); - }); - this.pickerC_ = padC; - this.textC_ = new PointNdTextController(doc, { - assembly: Point2dAssembly, - axes: config.axes, - parser: config.parser, - value: this.value, - viewProps: this.viewProps, - }); - this.view = new Point2dView(doc, { - expanded: this.foldable_.value('expanded'), - pickerLayout: config.pickerLayout, - viewProps: this.viewProps, - }); - this.view.textElement.appendChild(this.textC_.view.element); - (_a = this.view.buttonElement) === null || _a === void 0 ? void 0 : _a.addEventListener('blur', this.onPadButtonBlur_); - (_b = this.view.buttonElement) === null || _b === void 0 ? void 0 : _b.addEventListener('click', this.onPadButtonClick_); - if (this.popC_) { - this.view.element.appendChild(this.popC_.view.element); - this.popC_.view.element.appendChild(this.pickerC_.view.element); - connectValues({ - primary: this.foldable_.value('expanded'), - secondary: this.popC_.shows, - forward: (p) => p.rawValue, - backward: (_, s) => s.rawValue, - }); - } - else if (this.view.pickerElement) { - this.view.pickerElement.appendChild(this.pickerC_.view.element); - bindFoldable(this.foldable_, this.view.pickerElement); - } - } - onPadButtonBlur_(e) { - if (!this.popC_) { - return; - } - const elem = this.view.element; - const nextTarget = forceCast(e.relatedTarget); - if (!nextTarget || !elem.contains(nextTarget)) { - this.popC_.shows.rawValue = false; - } - } - onPadButtonClick_() { - this.foldable_.set('expanded', !this.foldable_.get('expanded')); - if (this.foldable_.get('expanded')) { - this.pickerC_.view.allFocusableElements[0].focus(); - } - } - onPopupChildBlur_(ev) { - if (!this.popC_) { - return; - } - const elem = this.popC_.view.element; - const nextTarget = findNextTarget(ev); - if (nextTarget && elem.contains(nextTarget)) { - return; - } - if (nextTarget && - nextTarget === this.view.buttonElement && - !supportsTouch(elem.ownerDocument)) { - return; - } - this.popC_.shows.rawValue = false; - } - onPopupChildKeydown_(ev) { - if (this.popC_) { - if (ev.key === 'Escape') { - this.popC_.shows.rawValue = false; - } - } - else if (this.view.pickerElement) { - if (ev.key === 'Escape') { - this.view.buttonElement.focus(); - } - } - } - } - - class Point3d { - constructor(x = 0, y = 0, z = 0) { - this.x = x; - this.y = y; - this.z = z; - } - getComponents() { - return [this.x, this.y, this.z]; - } - static isObject(obj) { - if (isEmpty(obj)) { - return false; - } - const x = obj.x; - const y = obj.y; - const z = obj.z; - if (typeof x !== 'number' || - typeof y !== 'number' || - typeof z !== 'number') { - return false; - } - return true; - } - static equals(v1, v2) { - return v1.x === v2.x && v1.y === v2.y && v1.z === v2.z; - } - toObject() { - return { - x: this.x, - y: this.y, - z: this.z, - }; - } - } - const Point3dAssembly = { - toComponents: (p) => p.getComponents(), - fromComponents: (comps) => new Point3d(...comps), - }; - - function point3dFromUnknown(value) { - return Point3d.isObject(value) - ? new Point3d(value.x, value.y, value.z) - : new Point3d(); - } - function writePoint3d(target, value) { - target.writeProperty('x', value.x); - target.writeProperty('y', value.y); - target.writeProperty('z', value.z); - } - - function createConstraint$3(params, initialValue) { - return new PointNdConstraint({ - assembly: Point3dAssembly, - components: [ - createDimensionConstraint('x' in params ? params.x : undefined, initialValue.x), - createDimensionConstraint('y' in params ? params.y : undefined, initialValue.y), - createDimensionConstraint('z' in params ? params.z : undefined, initialValue.z), - ], - }); - } - function createAxis$2(initialValue, constraint) { - return { - baseStep: getBaseStep(constraint), - constraint: constraint, - textProps: ValueMap.fromObject({ - draggingScale: getSuitableDraggingScale(constraint, initialValue), - formatter: createNumberFormatter(getSuitableDecimalDigits(constraint, initialValue)), - }), - }; - } - const Point3dInputPlugin = { - id: 'input-point3d', - type: 'input', - accept: (value, params) => { - if (!Point3d.isObject(value)) { - return null; - } - const p = ParamsParsers; - const result = parseParams(params, { - x: p.optional.custom(parsePointDimensionParams), - y: p.optional.custom(parsePointDimensionParams), - z: p.optional.custom(parsePointDimensionParams), - }); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (_args) => point3dFromUnknown, - constraint: (args) => createConstraint$3(args.params, args.initialValue), - equals: Point3d.equals, - writer: (_args) => writePoint3d, - }, - controller: (args) => { - const value = args.value; - const c = args.constraint; - if (!(c instanceof PointNdConstraint)) { - throw TpError.shouldNeverHappen(); - } - return new PointNdTextController(args.document, { - assembly: Point3dAssembly, - axes: [ - createAxis$2(value.rawValue.x, c.components[0]), - createAxis$2(value.rawValue.y, c.components[1]), - createAxis$2(value.rawValue.z, c.components[2]), - ], - parser: parseNumber, - value: value, - viewProps: args.viewProps, - }); - }, - }; - - class Point4d { - constructor(x = 0, y = 0, z = 0, w = 0) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - getComponents() { - return [this.x, this.y, this.z, this.w]; - } - static isObject(obj) { - if (isEmpty(obj)) { - return false; - } - const x = obj.x; - const y = obj.y; - const z = obj.z; - const w = obj.w; - if (typeof x !== 'number' || - typeof y !== 'number' || - typeof z !== 'number' || - typeof w !== 'number') { - return false; - } - return true; - } - static equals(v1, v2) { - return v1.x === v2.x && v1.y === v2.y && v1.z === v2.z && v1.w === v2.w; - } - toObject() { - return { - x: this.x, - y: this.y, - z: this.z, - w: this.w, - }; - } - } - const Point4dAssembly = { - toComponents: (p) => p.getComponents(), - fromComponents: (comps) => new Point4d(...comps), - }; - - function point4dFromUnknown(value) { - return Point4d.isObject(value) - ? new Point4d(value.x, value.y, value.z, value.w) - : new Point4d(); - } - function writePoint4d(target, value) { - target.writeProperty('x', value.x); - target.writeProperty('y', value.y); - target.writeProperty('z', value.z); - target.writeProperty('w', value.w); - } - - function createConstraint$2(params, initialValue) { - return new PointNdConstraint({ - assembly: Point4dAssembly, - components: [ - createDimensionConstraint('x' in params ? params.x : undefined, initialValue.x), - createDimensionConstraint('y' in params ? params.y : undefined, initialValue.y), - createDimensionConstraint('z' in params ? params.z : undefined, initialValue.z), - createDimensionConstraint('w' in params ? params.w : undefined, initialValue.w), - ], - }); - } - function createAxis$1(initialValue, constraint) { - return { - baseStep: getBaseStep(constraint), - constraint: constraint, - textProps: ValueMap.fromObject({ - draggingScale: getSuitableDraggingScale(constraint, initialValue), - formatter: createNumberFormatter(getSuitableDecimalDigits(constraint, initialValue)), - }), - }; - } - const Point4dInputPlugin = { - id: 'input-point4d', - type: 'input', - accept: (value, params) => { - if (!Point4d.isObject(value)) { - return null; - } - const p = ParamsParsers; - const result = parseParams(params, { - x: p.optional.custom(parsePointDimensionParams), - y: p.optional.custom(parsePointDimensionParams), - z: p.optional.custom(parsePointDimensionParams), - w: p.optional.custom(parsePointDimensionParams), - }); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (_args) => point4dFromUnknown, - constraint: (args) => createConstraint$2(args.params, args.initialValue), - equals: Point4d.equals, - writer: (_args) => writePoint4d, - }, - controller: (args) => { - const value = args.value; - const c = args.constraint; - if (!(c instanceof PointNdConstraint)) { - throw TpError.shouldNeverHappen(); - } - return new PointNdTextController(args.document, { - assembly: Point4dAssembly, - axes: value.rawValue - .getComponents() - .map((comp, index) => createAxis$1(comp, c.components[index])), - parser: parseNumber, - value: value, - viewProps: args.viewProps, - }); - }, - }; - - function createConstraint$1(params) { - const constraints = []; - const lc = createListConstraint(params.options); - if (lc) { - constraints.push(lc); - } - return new CompositeConstraint(constraints); - } - const StringInputPlugin = { - id: 'input-string', - type: 'input', - accept: (value, params) => { - if (typeof value !== 'string') { - return null; - } - const p = ParamsParsers; - const result = parseParams(params, { - options: p.optional.custom(parseListOptions), - }); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (_args) => stringFromUnknown, - constraint: (args) => createConstraint$1(args.params), - writer: (_args) => writePrimitive, - }, - controller: (args) => { - const doc = args.document; - const value = args.value; - const c = args.constraint; - const lc = c && findConstraint(c, ListConstraint); - if (lc) { - return new ListController(doc, { - props: new ValueMap({ - options: lc.values.value('options'), - }), - value: value, - viewProps: args.viewProps, - }); - } - return new TextController(doc, { - parser: (v) => v, - props: ValueMap.fromObject({ - formatter: formatString, - }), - value: value, - viewProps: args.viewProps, - }); - }, - }; - - const Constants = { - monitor: { - defaultInterval: 200, - defaultLineCount: 3, - }, - }; - - const className$2 = ClassName('mll'); - class MultiLogView { - constructor(doc, config) { - this.onValueUpdate_ = this.onValueUpdate_.bind(this); - this.formatter_ = config.formatter; - this.element = doc.createElement('div'); - this.element.classList.add(className$2()); - config.viewProps.bindClassModifiers(this.element); - const textareaElem = doc.createElement('textarea'); - textareaElem.classList.add(className$2('i')); - textareaElem.style.height = `calc(var(--bld-us) * ${config.lineCount})`; - textareaElem.readOnly = true; - config.viewProps.bindDisabled(textareaElem); - this.element.appendChild(textareaElem); - this.textareaElem_ = textareaElem; - config.value.emitter.on('change', this.onValueUpdate_); - this.value = config.value; - this.update_(); - } - update_() { - const elem = this.textareaElem_; - const shouldScroll = elem.scrollTop === elem.scrollHeight - elem.clientHeight; - const lines = []; - this.value.rawValue.forEach((value) => { - if (value !== undefined) { - lines.push(this.formatter_(value)); - } - }); - elem.textContent = lines.join('\n'); - if (shouldScroll) { - elem.scrollTop = elem.scrollHeight; - } - } - onValueUpdate_() { - this.update_(); - } - } - - class MultiLogController { - constructor(doc, config) { - this.value = config.value; - this.viewProps = config.viewProps; - this.view = new MultiLogView(doc, { - formatter: config.formatter, - lineCount: config.lineCount, - value: this.value, - viewProps: this.viewProps, - }); - } - } - - const className$1 = ClassName('sgl'); - class SingleLogView { - constructor(doc, config) { - this.onValueUpdate_ = this.onValueUpdate_.bind(this); - this.formatter_ = config.formatter; - this.element = doc.createElement('div'); - this.element.classList.add(className$1()); - config.viewProps.bindClassModifiers(this.element); - const inputElem = doc.createElement('input'); - inputElem.classList.add(className$1('i')); - inputElem.readOnly = true; - inputElem.type = 'text'; - config.viewProps.bindDisabled(inputElem); - this.element.appendChild(inputElem); - this.inputElement = inputElem; - config.value.emitter.on('change', this.onValueUpdate_); - this.value = config.value; - this.update_(); - } - update_() { - const values = this.value.rawValue; - const lastValue = values[values.length - 1]; - this.inputElement.value = - lastValue !== undefined ? this.formatter_(lastValue) : ''; - } - onValueUpdate_() { - this.update_(); - } - } - - class SingleLogController { - constructor(doc, config) { - this.value = config.value; - this.viewProps = config.viewProps; - this.view = new SingleLogView(doc, { - formatter: config.formatter, - value: this.value, - viewProps: this.viewProps, - }); - } - } - - const BooleanMonitorPlugin = { - id: 'monitor-bool', - type: 'monitor', - accept: (value, params) => { - if (typeof value !== 'boolean') { - return null; - } - const p = ParamsParsers; - const result = parseParams(params, { - lineCount: p.optional.number, - }); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (_args) => boolFromUnknown, - }, - controller: (args) => { - var _a; - if (args.value.rawValue.length === 1) { - return new SingleLogController(args.document, { - formatter: BooleanFormatter, - value: args.value, - viewProps: args.viewProps, - }); - } - return new MultiLogController(args.document, { - formatter: BooleanFormatter, - lineCount: (_a = args.params.lineCount) !== null && _a !== void 0 ? _a : Constants.monitor.defaultLineCount, - value: args.value, - viewProps: args.viewProps, - }); - }, - }; - - const className = ClassName('grl'); - class GraphLogView { - constructor(doc, config) { - this.onCursorChange_ = this.onCursorChange_.bind(this); - this.onValueUpdate_ = this.onValueUpdate_.bind(this); - this.element = doc.createElement('div'); - this.element.classList.add(className()); - config.viewProps.bindClassModifiers(this.element); - this.formatter_ = config.formatter; - this.props_ = config.props; - this.cursor_ = config.cursor; - this.cursor_.emitter.on('change', this.onCursorChange_); - const svgElem = doc.createElementNS(SVG_NS, 'svg'); - svgElem.classList.add(className('g')); - svgElem.style.height = `calc(var(--bld-us) * ${config.lineCount})`; - this.element.appendChild(svgElem); - this.svgElem_ = svgElem; - const lineElem = doc.createElementNS(SVG_NS, 'polyline'); - this.svgElem_.appendChild(lineElem); - this.lineElem_ = lineElem; - const tooltipElem = doc.createElement('div'); - tooltipElem.classList.add(className('t'), ClassName('tt')()); - this.element.appendChild(tooltipElem); - this.tooltipElem_ = tooltipElem; - config.value.emitter.on('change', this.onValueUpdate_); - this.value = config.value; - this.update_(); - } - get graphElement() { - return this.svgElem_; - } - update_() { - const bounds = this.svgElem_.getBoundingClientRect(); - const maxIndex = this.value.rawValue.length - 1; - const min = this.props_.get('minValue'); - const max = this.props_.get('maxValue'); - const points = []; - this.value.rawValue.forEach((v, index) => { - if (v === undefined) { - return; - } - const x = mapRange(index, 0, maxIndex, 0, bounds.width); - const y = mapRange(v, min, max, bounds.height, 0); - points.push([x, y].join(',')); - }); - this.lineElem_.setAttributeNS(null, 'points', points.join(' ')); - const tooltipElem = this.tooltipElem_; - const value = this.value.rawValue[this.cursor_.rawValue]; - if (value === undefined) { - tooltipElem.classList.remove(className('t', 'a')); - return; - } - const tx = mapRange(this.cursor_.rawValue, 0, maxIndex, 0, bounds.width); - const ty = mapRange(value, min, max, bounds.height, 0); - tooltipElem.style.left = `${tx}px`; - tooltipElem.style.top = `${ty}px`; - tooltipElem.textContent = `${this.formatter_(value)}`; - if (!tooltipElem.classList.contains(className('t', 'a'))) { - tooltipElem.classList.add(className('t', 'a'), className('t', 'in')); - forceReflow(tooltipElem); - tooltipElem.classList.remove(className('t', 'in')); - } - } - onValueUpdate_() { - this.update_(); - } - onCursorChange_() { - this.update_(); - } - } - - class GraphLogController { - constructor(doc, config) { - this.onGraphMouseMove_ = this.onGraphMouseMove_.bind(this); - this.onGraphMouseLeave_ = this.onGraphMouseLeave_.bind(this); - this.onGraphPointerDown_ = this.onGraphPointerDown_.bind(this); - this.onGraphPointerMove_ = this.onGraphPointerMove_.bind(this); - this.onGraphPointerUp_ = this.onGraphPointerUp_.bind(this); - this.props_ = config.props; - this.value = config.value; - this.viewProps = config.viewProps; - this.cursor_ = createValue(-1); - this.view = new GraphLogView(doc, { - cursor: this.cursor_, - formatter: config.formatter, - lineCount: config.lineCount, - props: this.props_, - value: this.value, - viewProps: this.viewProps, - }); - if (!supportsTouch(doc)) { - this.view.element.addEventListener('mousemove', this.onGraphMouseMove_); - this.view.element.addEventListener('mouseleave', this.onGraphMouseLeave_); - } - else { - const ph = new PointerHandler(this.view.element); - ph.emitter.on('down', this.onGraphPointerDown_); - ph.emitter.on('move', this.onGraphPointerMove_); - ph.emitter.on('up', this.onGraphPointerUp_); - } - } - onGraphMouseLeave_() { - this.cursor_.rawValue = -1; - } - onGraphMouseMove_(ev) { - const bounds = this.view.element.getBoundingClientRect(); - this.cursor_.rawValue = Math.floor(mapRange(ev.offsetX, 0, bounds.width, 0, this.value.rawValue.length)); - } - onGraphPointerDown_(ev) { - this.onGraphPointerMove_(ev); - } - onGraphPointerMove_(ev) { - if (!ev.data.point) { - this.cursor_.rawValue = -1; - return; - } - this.cursor_.rawValue = Math.floor(mapRange(ev.data.point.x, 0, ev.data.bounds.width, 0, this.value.rawValue.length)); - } - onGraphPointerUp_() { - this.cursor_.rawValue = -1; - } - } - - function createFormatter(params) { - return 'format' in params && !isEmpty(params.format) - ? params.format - : createNumberFormatter(2); - } - function createTextMonitor(args) { - var _a; - if (args.value.rawValue.length === 1) { - return new SingleLogController(args.document, { - formatter: createFormatter(args.params), - value: args.value, - viewProps: args.viewProps, - }); - } - return new MultiLogController(args.document, { - formatter: createFormatter(args.params), - lineCount: (_a = args.params.lineCount) !== null && _a !== void 0 ? _a : Constants.monitor.defaultLineCount, - value: args.value, - viewProps: args.viewProps, - }); - } - function createGraphMonitor(args) { - var _a, _b, _c; - return new GraphLogController(args.document, { - formatter: createFormatter(args.params), - lineCount: (_a = args.params.lineCount) !== null && _a !== void 0 ? _a : Constants.monitor.defaultLineCount, - props: ValueMap.fromObject({ - maxValue: (_b = ('max' in args.params ? args.params.max : null)) !== null && _b !== void 0 ? _b : 100, - minValue: (_c = ('min' in args.params ? args.params.min : null)) !== null && _c !== void 0 ? _c : 0, - }), - value: args.value, - viewProps: args.viewProps, - }); - } - function shouldShowGraph(params) { - return 'view' in params && params.view === 'graph'; - } - const NumberMonitorPlugin = { - id: 'monitor-number', - type: 'monitor', - accept: (value, params) => { - if (typeof value !== 'number') { - return null; - } - const p = ParamsParsers; - const result = parseParams(params, { - format: p.optional.function, - lineCount: p.optional.number, - max: p.optional.number, - min: p.optional.number, - view: p.optional.string, - }); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - defaultBufferSize: (params) => (shouldShowGraph(params) ? 64 : 1), - reader: (_args) => numberFromUnknown, - }, - controller: (args) => { - if (shouldShowGraph(args.params)) { - return createGraphMonitor(args); - } - return createTextMonitor(args); - }, - }; - - const StringMonitorPlugin = { - id: 'monitor-string', - type: 'monitor', - accept: (value, params) => { - if (typeof value !== 'string') { - return null; - } - const p = ParamsParsers; - const result = parseParams(params, { - lineCount: p.optional.number, - multiline: p.optional.boolean, - }); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (_args) => stringFromUnknown, - }, - controller: (args) => { - var _a; - const value = args.value; - const multiline = value.rawValue.length > 1 || - ('multiline' in args.params && args.params.multiline); - if (multiline) { - return new MultiLogController(args.document, { - formatter: formatString, - lineCount: (_a = args.params.lineCount) !== null && _a !== void 0 ? _a : Constants.monitor.defaultLineCount, - value: value, - viewProps: args.viewProps, - }); - } - return new SingleLogController(args.document, { - formatter: formatString, - value: value, - viewProps: args.viewProps, - }); - }, - }; - - function createInputBindingController(plugin, args) { - var _a; - const result = plugin.accept(args.target.read(), args.params); - if (isEmpty(result)) { - return null; - } - const p = ParamsParsers; - const valueArgs = { - target: args.target, - initialValue: result.initialValue, - params: result.params, - }; - const reader = plugin.binding.reader(valueArgs); - const constraint = plugin.binding.constraint - ? plugin.binding.constraint(valueArgs) - : undefined; - const value = createValue(reader(result.initialValue), { - constraint: constraint, - equals: plugin.binding.equals, - }); - const binding = new InputBinding({ - reader: reader, - target: args.target, - value: value, - writer: plugin.binding.writer(valueArgs), - }); - const disabled = p.optional.boolean(args.params.disabled).value; - const hidden = p.optional.boolean(args.params.hidden).value; - const controller = plugin.controller({ - constraint: constraint, - document: args.document, - initialValue: result.initialValue, - params: result.params, - value: binding.value, - viewProps: ViewProps.create({ - disabled: disabled, - hidden: hidden, - }), - }); - return new InputBindingController(args.document, { - binding: binding, - blade: createBlade(), - props: ValueMap.fromObject({ - label: 'label' in args.params - ? (_a = p.optional.string(args.params.label).value) !== null && _a !== void 0 ? _a : null - : args.target.key, - }), - valueController: controller, - }); - } - - function createTicker(document, interval) { - return interval === 0 - ? new ManualTicker() - : new IntervalTicker(document, interval !== null && interval !== void 0 ? interval : Constants.monitor.defaultInterval); - } - function createMonitorBindingController(plugin, args) { - var _a, _b, _c; - const p = ParamsParsers; - const result = plugin.accept(args.target.read(), args.params); - if (isEmpty(result)) { - return null; - } - const bindingArgs = { - target: args.target, - initialValue: result.initialValue, - params: result.params, - }; - const reader = plugin.binding.reader(bindingArgs); - const bufferSize = (_b = (_a = p.optional.number(args.params.bufferSize).value) !== null && _a !== void 0 ? _a : (plugin.binding.defaultBufferSize && - plugin.binding.defaultBufferSize(result.params))) !== null && _b !== void 0 ? _b : 1; - const interval = p.optional.number(args.params.interval).value; - const binding = new MonitorBinding({ - reader: reader, - target: args.target, - ticker: createTicker(args.document, interval), - value: initializeBuffer(bufferSize), - }); - const disabled = p.optional.boolean(args.params.disabled).value; - const hidden = p.optional.boolean(args.params.hidden).value; - const controller = plugin.controller({ - document: args.document, - params: result.params, - value: binding.value, - viewProps: ViewProps.create({ - disabled: disabled, - hidden: hidden, - }), - }); - return new MonitorBindingController(args.document, { - binding: binding, - blade: createBlade(), - props: ValueMap.fromObject({ - label: 'label' in args.params - ? (_c = p.optional.string(args.params.label).value) !== null && _c !== void 0 ? _c : null - : args.target.key, - }), - valueController: controller, - }); - } - - class PluginPool { - constructor() { - this.pluginsMap_ = { - blades: [], - inputs: [], - monitors: [], - }; - } - getAll() { - return [ - ...this.pluginsMap_.blades, - ...this.pluginsMap_.inputs, - ...this.pluginsMap_.monitors, - ]; - } - register(r) { - if (r.type === 'blade') { - this.pluginsMap_.blades.unshift(r); - } - else if (r.type === 'input') { - this.pluginsMap_.inputs.unshift(r); - } - else if (r.type === 'monitor') { - this.pluginsMap_.monitors.unshift(r); - } - } - createInput(document, target, params) { - const initialValue = target.read(); - if (isEmpty(initialValue)) { - throw new TpError({ - context: { - key: target.key, - }, - type: 'nomatchingcontroller', - }); - } - const bc = this.pluginsMap_.inputs.reduce((result, plugin) => result !== null && result !== void 0 ? result : createInputBindingController(plugin, { - document: document, - target: target, - params: params, - }), null); - if (bc) { - return bc; - } - throw new TpError({ - context: { - key: target.key, - }, - type: 'nomatchingcontroller', - }); - } - createMonitor(document, target, params) { - const bc = this.pluginsMap_.monitors.reduce((result, plugin) => result !== null && result !== void 0 ? result : createMonitorBindingController(plugin, { - document: document, - params: params, - target: target, - }), null); - if (bc) { - return bc; - } - throw new TpError({ - context: { - key: target.key, - }, - type: 'nomatchingcontroller', - }); - } - createBlade(document, params) { - const bc = this.pluginsMap_.blades.reduce((result, plugin) => result !== null && result !== void 0 ? result : createBladeController(plugin, { - document: document, - params: params, - }), null); - if (!bc) { - throw new TpError({ - type: 'nomatchingview', - context: { - params: params, - }, - }); - } - return bc; - } - createBladeApi(bc) { - if (bc instanceof InputBindingController) { - return new InputBindingApi(bc); - } - if (bc instanceof MonitorBindingController) { - return new MonitorBindingApi(bc); - } - if (bc instanceof RackController) { - return new RackApi(bc, this); - } - const api = this.pluginsMap_.blades.reduce((result, plugin) => result !== null && result !== void 0 ? result : plugin.api({ - controller: bc, - pool: this, - }), null); - if (!api) { - throw TpError.shouldNeverHappen(); - } - return api; - } - } - - function createDefaultPluginPool() { - const pool = new PluginPool(); - [ - Point2dInputPlugin, - Point3dInputPlugin, - Point4dInputPlugin, - StringInputPlugin, - NumberInputPlugin, - StringColorInputPlugin, - ObjectColorInputPlugin, - NumberColorInputPlugin, - BooleanInputPlugin, - BooleanMonitorPlugin, - StringMonitorPlugin, - NumberMonitorPlugin, - ButtonBladePlugin, - FolderBladePlugin, - SeparatorBladePlugin, - TabBladePlugin, - ].forEach((p) => { - pool.register(p); - }); - return pool; - } - - function point2dFromUnknown(value) { - return Point2d.isObject(value) - ? new Point2d(value.x, value.y) - : new Point2d(); - } - function writePoint2d(target, value) { - target.writeProperty('x', value.x); - target.writeProperty('y', value.y); - } - - function createDimensionConstraint(params, initialValue) { - if (!params) { - return undefined; - } - const constraints = []; - const cs = createStepConstraint(params, initialValue); - if (cs) { - constraints.push(cs); - } - const rs = createRangeConstraint(params); - if (rs) { - constraints.push(rs); - } - return new CompositeConstraint(constraints); - } - function createConstraint(params, initialValue) { - return new PointNdConstraint({ - assembly: Point2dAssembly, - components: [ - createDimensionConstraint('x' in params ? params.x : undefined, initialValue.x), - createDimensionConstraint('y' in params ? params.y : undefined, initialValue.y), - ], - }); - } - function getSuitableMaxDimensionValue(constraint, rawValue) { - const [min, max] = constraint ? findNumberRange(constraint) : []; - if (!isEmpty(min) || !isEmpty(max)) { - return Math.max(Math.abs(min !== null && min !== void 0 ? min : 0), Math.abs(max !== null && max !== void 0 ? max : 0)); - } - const step = getBaseStep(constraint); - return Math.max(Math.abs(step) * 10, Math.abs(rawValue) * 10); - } - function getSuitableMaxValue(initialValue, constraint) { - const xc = constraint instanceof PointNdConstraint - ? constraint.components[0] - : undefined; - const yc = constraint instanceof PointNdConstraint - ? constraint.components[1] - : undefined; - const xr = getSuitableMaxDimensionValue(xc, initialValue.x); - const yr = getSuitableMaxDimensionValue(yc, initialValue.y); - return Math.max(xr, yr); - } - function createAxis(initialValue, constraint) { - return { - baseStep: getBaseStep(constraint), - constraint: constraint, - textProps: ValueMap.fromObject({ - draggingScale: getSuitableDraggingScale(constraint, initialValue), - formatter: createNumberFormatter(getSuitableDecimalDigits(constraint, initialValue)), - }), - }; - } - function shouldInvertY(params) { - if (!('y' in params)) { - return false; - } - const yParams = params.y; - if (!yParams) { - return false; - } - return 'inverted' in yParams ? !!yParams.inverted : false; - } - const Point2dInputPlugin = { - id: 'input-point2d', - type: 'input', - accept: (value, params) => { - if (!Point2d.isObject(value)) { - return null; - } - const p = ParamsParsers; - const result = parseParams(params, { - expanded: p.optional.boolean, - picker: p.optional.custom(parsePickerLayout), - x: p.optional.custom(parsePointDimensionParams), - y: p.optional.object({ - inverted: p.optional.boolean, - max: p.optional.number, - min: p.optional.number, - step: p.optional.number, - }), - }); - return result - ? { - initialValue: value, - params: result, - } - : null; - }, - binding: { - reader: (_args) => point2dFromUnknown, - constraint: (args) => createConstraint(args.params, args.initialValue), - equals: Point2d.equals, - writer: (_args) => writePoint2d, - }, - controller: (args) => { - const doc = args.document; - const value = args.value; - const c = args.constraint; - if (!(c instanceof PointNdConstraint)) { - throw TpError.shouldNeverHappen(); - } - const expanded = 'expanded' in args.params ? args.params.expanded : undefined; - const picker = 'picker' in args.params ? args.params.picker : undefined; - return new Point2dController(doc, { - axes: [ - createAxis(value.rawValue.x, c.components[0]), - createAxis(value.rawValue.y, c.components[1]), - ], - expanded: expanded !== null && expanded !== void 0 ? expanded : false, - invertsY: shouldInvertY(args.params), - maxValue: getSuitableMaxValue(value.rawValue, c), - parser: parseNumber, - pickerLayout: picker !== null && picker !== void 0 ? picker : 'popup', - value: value, - viewProps: args.viewProps, - }); - }, - }; - - class ListApi extends BladeApi { - constructor(controller) { - super(controller); - this.emitter_ = new Emitter(); - this.controller_.valueController.value.emitter.on('change', (ev) => { - this.emitter_.emit('change', { - event: new TpChangeEvent(this, ev.rawValue), - }); - }); - } - get label() { - return this.controller_.props.get('label'); - } - set label(label) { - this.controller_.props.set('label', label); - } - get options() { - return this.controller_.valueController.props.get('options'); - } - set options(options) { - this.controller_.valueController.props.set('options', options); - } - get value() { - return this.controller_.valueController.value.rawValue; - } - set value(value) { - this.controller_.valueController.value.rawValue = value; - } - on(eventName, handler) { - const bh = handler.bind(this); - this.emitter_.on(eventName, (ev) => { - bh(ev.event); - }); - return this; - } - } - - class SliderApi extends BladeApi { - constructor(controller) { - super(controller); - this.emitter_ = new Emitter(); - this.controller_.valueController.value.emitter.on('change', (ev) => { - this.emitter_.emit('change', { - event: new TpChangeEvent(this, ev.rawValue), - }); - }); - } - get label() { - return this.controller_.props.get('label'); - } - set label(label) { - this.controller_.props.set('label', label); - } - get maxValue() { - return this.controller_.valueController.sliderController.props.get('maxValue'); - } - set maxValue(maxValue) { - this.controller_.valueController.sliderController.props.set('maxValue', maxValue); - } - get minValue() { - return this.controller_.valueController.sliderController.props.get('minValue'); - } - set minValue(minValue) { - this.controller_.valueController.sliderController.props.set('minValue', minValue); - } - get value() { - return this.controller_.valueController.value.rawValue; - } - set value(value) { - this.controller_.valueController.value.rawValue = value; - } - on(eventName, handler) { - const bh = handler.bind(this); - this.emitter_.on(eventName, (ev) => { - bh(ev.event); - }); - return this; - } - } - - class TextApi extends BladeApi { - constructor(controller) { - super(controller); - this.emitter_ = new Emitter(); - this.controller_.valueController.value.emitter.on('change', (ev) => { - this.emitter_.emit('change', { - event: new TpChangeEvent(this, ev.rawValue), - }); - }); - } - get label() { - return this.controller_.props.get('label'); - } - set label(label) { - this.controller_.props.set('label', label); - } - get formatter() { - return this.controller_.valueController.props.get('formatter'); - } - set formatter(formatter) { - this.controller_.valueController.props.set('formatter', formatter); - } - get value() { - return this.controller_.valueController.value.rawValue; - } - set value(value) { - this.controller_.valueController.value.rawValue = value; - } - on(eventName, handler) { - const bh = handler.bind(this); - this.emitter_.on(eventName, (ev) => { - bh(ev.event); - }); - return this; - } - } - - const ListBladePlugin = (function () { - return { - id: 'list', - type: 'blade', - accept(params) { - const p = ParamsParsers; - const result = parseParams(params, { - options: p.required.custom(parseListOptions), - value: p.required.raw, - view: p.required.constant('list'), - label: p.optional.string, - }); - return result ? { params: result } : null; - }, - controller(args) { - const lc = new ListConstraint(normalizeListOptions(args.params.options)); - const value = createValue(args.params.value, { - constraint: lc, - }); - const ic = new ListController(args.document, { - props: new ValueMap({ - options: lc.values.value('options'), - }), - value: value, - viewProps: args.viewProps, - }); - return new LabeledValueController(args.document, { - blade: args.blade, - props: ValueMap.fromObject({ - label: args.params.label, - }), - valueController: ic, - }); - }, - api(args) { - if (!(args.controller instanceof LabeledValueController)) { - return null; - } - if (!(args.controller.valueController instanceof ListController)) { - return null; - } - return new ListApi(args.controller); - }, - }; - })(); - - /** - * @hidden - */ - function exportPresetJson(targets) { - return targets.reduce((result, target) => { - return Object.assign(result, { - [target.presetKey]: target.read(), - }); - }, {}); - } - /** - * @hidden - */ - function importPresetJson(bindings, preset) { - bindings.forEach((binding) => { - const value = preset[binding.target.presetKey]; - if (value !== undefined) { - binding.writer(binding.target, binding.reader(value)); - } - }); - } - - class RootApi extends FolderApi { - /** - * @hidden - */ - constructor(controller, pool) { - super(controller, pool); - } - get element() { - return this.controller_.view.element; - } - /** - * Imports a preset of all inputs. - * @param preset The preset object to import. - */ - importPreset(preset) { - const bindings = this.controller_.rackController.rack - .find(InputBindingController) - .map((ibc) => { - return ibc.binding; - }); - importPresetJson(bindings, preset); - this.refresh(); - } - /** - * Exports a preset of all inputs. - * @return An exported preset object. - */ - exportPreset() { - const targets = this.controller_.rackController.rack - .find(InputBindingController) - .map((ibc) => { - return ibc.binding.target; - }); - return exportPresetJson(targets); - } - /** - * Refreshes all bindings of the pane. - */ - refresh() { - // Force-read all input bindings - this.controller_.rackController.rack - .find(InputBindingController) - .forEach((ibc) => { - ibc.binding.read(); - }); - // Force-read all monitor bindings - this.controller_.rackController.rack - .find(MonitorBindingController) - .forEach((mbc) => { - mbc.binding.read(); - }); - } - } - - class RootController extends FolderController { - constructor(doc, config) { - super(doc, { - expanded: config.expanded, - blade: config.blade, - props: config.props, - root: true, - viewProps: config.viewProps, - }); - } - } - - const SliderBladePlugin = { - id: 'slider', - type: 'blade', - accept(params) { - const p = ParamsParsers; - const result = parseParams(params, { - max: p.required.number, - min: p.required.number, - view: p.required.constant('slider'), - format: p.optional.function, - label: p.optional.string, - value: p.optional.number, - }); - return result ? { params: result } : null; - }, - controller(args) { - var _a, _b; - const initialValue = (_a = args.params.value) !== null && _a !== void 0 ? _a : 0; - const drc = new DefiniteRangeConstraint({ - max: args.params.max, - min: args.params.min, - }); - const vc = new SliderTextController(args.document, { - baseStep: 1, - parser: parseNumber, - sliderProps: new ValueMap({ - maxValue: drc.values.value('max'), - minValue: drc.values.value('min'), - }), - textProps: ValueMap.fromObject({ - draggingScale: getSuitableDraggingScale(undefined, initialValue), - formatter: (_b = args.params.format) !== null && _b !== void 0 ? _b : numberToString, - }), - value: createValue(initialValue, { - constraint: drc, - }), - viewProps: args.viewProps, - }); - return new LabeledValueController(args.document, { - blade: args.blade, - props: ValueMap.fromObject({ - label: args.params.label, - }), - valueController: vc, - }); - }, - api(args) { - if (!(args.controller instanceof LabeledValueController)) { - return null; - } - if (!(args.controller.valueController instanceof SliderTextController)) { - return null; - } - return new SliderApi(args.controller); - }, - }; - - const TextBladePlugin = (function () { - return { - id: 'text', - type: 'blade', - accept(params) { - const p = ParamsParsers; - const result = parseParams(params, { - parse: p.required.function, - value: p.required.raw, - view: p.required.constant('text'), - format: p.optional.function, - label: p.optional.string, - }); - return result ? { params: result } : null; - }, - controller(args) { - var _a; - const ic = new TextController(args.document, { - parser: args.params.parse, - props: ValueMap.fromObject({ - formatter: (_a = args.params.format) !== null && _a !== void 0 ? _a : ((v) => String(v)), - }), - value: createValue(args.params.value), - viewProps: args.viewProps, - }); - return new LabeledValueController(args.document, { - blade: args.blade, - props: ValueMap.fromObject({ - label: args.params.label, - }), - valueController: ic, - }); - }, - api(args) { - if (!(args.controller instanceof LabeledValueController)) { - return null; - } - if (!(args.controller.valueController instanceof TextController)) { - return null; - } - return new TextApi(args.controller); - }, - }; - })(); - - function createDefaultWrapperElement(doc) { - const elem = doc.createElement('div'); - elem.classList.add(ClassName('dfw')()); - if (doc.body) { - doc.body.appendChild(elem); - } - return elem; - } - function embedStyle(doc, id, css) { - if (doc.querySelector(`style[data-tp-style=${id}]`)) { - return; - } - const styleElem = doc.createElement('style'); - styleElem.dataset.tpStyle = id; - styleElem.textContent = css; - doc.head.appendChild(styleElem); - } - /** - * The root pane of Tweakpane. - */ - class Pane extends RootApi { - constructor(opt_config) { - var _a, _b; - const config = opt_config !== null && opt_config !== void 0 ? opt_config : {}; - const doc = (_a = config.document) !== null && _a !== void 0 ? _a : getWindowDocument(); - const pool = createDefaultPluginPool(); - const rootController = new RootController(doc, { - expanded: config.expanded, - blade: createBlade(), - props: ValueMap.fromObject({ - title: config.title, - }), - viewProps: ViewProps.create(), - }); - super(rootController, pool); - this.pool_ = pool; - this.containerElem_ = (_b = config.container) !== null && _b !== void 0 ? _b : createDefaultWrapperElement(doc); - this.containerElem_.appendChild(this.element); - this.doc_ = doc; - this.usesDefaultWrapper_ = !config.container; - this.setUpDefaultPlugins_(); - } - get document() { - if (!this.doc_) { - throw TpError.alreadyDisposed(); - } - return this.doc_; - } - dispose() { - const containerElem = this.containerElem_; - if (!containerElem) { - throw TpError.alreadyDisposed(); - } - if (this.usesDefaultWrapper_) { - const parentElem = containerElem.parentElement; - if (parentElem) { - parentElem.removeChild(containerElem); - } - } - this.containerElem_ = null; - this.doc_ = null; - super.dispose(); - } - registerPlugin(bundle) { - const plugins = 'plugin' in bundle - ? [bundle.plugin] - : 'plugins' in bundle - ? bundle.plugins - : []; - plugins.forEach((p) => { - this.pool_.register(p); - this.embedPluginStyle_(p); - }); - } - embedPluginStyle_(plugin) { - if (plugin.css) { - embedStyle(this.document, `plugin-${plugin.id}`, plugin.css); - } - } - setUpDefaultPlugins_() { - // NOTE: This string literal will be replaced with the default CSS by Rollup at the compilation time - embedStyle(this.document, 'default', '.tp-tbiv_b,.tp-coltxtv_ms,.tp-ckbv_i,.tp-rotv_b,.tp-fldv_b,.tp-mllv_i,.tp-sglv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--elm-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--bld-us);line-height:var(--bld-us);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--bld-us);line-height:var(--bld-us);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-mllv_i,.tp-sglv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--mo-fg);height:var(--bld-us);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-mllv_i::-webkit-scrollbar,.tp-sglv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-mllv_i::-webkit-scrollbar-corner,.tp-sglv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-mllv_i::-webkit-scrollbar-thumb,.tp-sglv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-rotv{--font-family: var(--tp-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-br: var(--tp-base-border-radius, 6px);--cnt-h-p: var(--tp-container-horizontal-padding, 4px);--cnt-v-p: var(--tp-container-vertical-padding, 4px);--elm-br: var(--tp-element-border-radius, 2px);--bld-s: var(--tp-blade-spacing, 4px);--bld-us: var(--tp-blade-unit-size, 20px);--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tabv_c .tp-brkv>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-v-p))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tabv_c .tp-brkv>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--bld-s)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tabv_c .tp-brkv>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tabv_c .tp-brkv>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--elm-br);border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tabv_c .tp-brkv .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--elm-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);overflow:hidden;padding-left:var(--cnt-h-p);padding-right:calc(4px + var(--bld-us) + var(--cnt-h-p));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-h-p) + (var(--bld-us) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-v-p);padding-top:var(--cnt-v-p);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--elm-br);cursor:pointer;display:block;height:var(--bld-us);position:relative;width:var(--bld-us)}.tp-ckbv_w svg{bottom:0;display:block;height:16px;left:0;margin:auto;opacity:0;position:absolute;right:0;top:0;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--bld-us)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--bld-s);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--bld-s)}.tp-colpv_rgb{display:flex;margin-top:var(--bld-s);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-v-p);padding-top:calc(var(--cnt-v-p) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-h-p));position:absolute;right:calc(-1*var(--cnt-h-p));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--elm-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--bld-us)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--elm-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;pointer-events:none;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--elm-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;cursor:pointer;display:block;height:var(--bld-us);left:0;margin:0;outline:none;padding:0;position:absolute;top:0;width:var(--bld-us)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--elm-br);bottom:0;content:"";display:block;left:0;position:absolute;right:0;top:0}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--elm-br);color:var(--lbl-fg);cursor:pointer;height:var(--bld-us);line-height:var(--bld-us);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv.tp-fldv-not .tp-fldv_b{display:none}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--bld-us)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-h-p);padding-right:var(--cnt-h-p)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:160px}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding:0 4px}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--bld-us)*3);line-height:var(--bld-us);padding:0 4px;resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--bld-us);margin-right:4px;position:relative;width:var(--bld-us)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--bld-s);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-p2dpv{padding-left:calc(var(--bld-us) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:6px;box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:168px;padding:var(--cnt-v-p) var(--cnt-h-p);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--bld-us);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin:auto;position:absolute;right:0;top:0}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin-bottom:auto;margin-top:auto;position:absolute;right:0;top:0}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--elm-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--bld-us) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_c{padding-bottom:var(--cnt-v-p);padding-left:4px;padding-top:var(--cnt-v-p)}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-h-p) + 4px);padding-right:calc(var(--cnt-h-p) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);bottom:2px;content:"";left:0;pointer-events:none;position:absolute;right:0;top:0}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);opacity:.5;overflow:hidden;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-txtv{position:relative}.tp-txtv_i{padding:0 4px}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:-3px;position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--bld-us) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--elm-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--font-family);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--bld-us) + var(--cnt-h-p));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0}.tp-rotv.tp-rotv-not .tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}'); - this.pool_.getAll().forEach((plugin) => { - this.embedPluginStyle_(plugin); - }); - this.registerPlugin({ - plugins: [ - SliderBladePlugin, - ListBladePlugin, - TabBladePlugin, - TextBladePlugin, - ], - }); - } - } - - const VERSION = new Semver('3.1.10'); - - exports.BladeApi = BladeApi; - exports.ButtonApi = ButtonApi; - exports.FolderApi = FolderApi; - exports.InputBindingApi = InputBindingApi; - exports.ListApi = ListApi; - exports.MonitorBindingApi = MonitorBindingApi; - exports.Pane = Pane; - exports.SeparatorApi = SeparatorApi; - exports.SliderApi = SliderApi; - exports.TabApi = TabApi; - exports.TabPageApi = TabPageApi; - exports.TextApi = TextApi; - exports.TpChangeEvent = TpChangeEvent; - exports.VERSION = VERSION; - - Object.defineProperty(exports, '__esModule', { value: true }); - -})); - - -/***/ }), - -/***/ 6803: -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "HEv": () => (/* reexport */ math_color_Color4), - "Dso": () => (/* reexport */ postProcess_PostProcess), - "xeF": () => (/* reexport */ ShaderLanguage), - "w1W": () => (/* reexport */ tools_Tools) -}); - -// UNUSED EXPORTS: AbstractActionManager, AbstractAssetTask, AbstractMesh, AbstractScene, AcquireNativeObjectAsync, Action, ActionEvent, ActionManager, AddBlock, AddressMode, AdvancedTimer, AlignBlock, AlphaState, AmmoJSPlugin, AnaglyphArcRotateCamera, AnaglyphFreeCamera, AnaglyphGamepadCamera, AnaglyphPostProcess, AnaglyphUniversalCamera, Analyser, AndOrNotEvaluator, Angle, Animatable, AnimatedInputBlockTypes, Animation, AnimationAssetTask, AnimationEvent, AnimationGroup, AnimationGroupMask, AnimationGroupMaskMode, AnimationKeyInterpolation, AnimationPropertiesOverride, AnimationRange, AnisotropyBlock, ApplyPostProcess, Arc2, ArcFollowCamera, ArcRotateCamera, ArcRotateCameraGamepadInput, ArcRotateCameraInputsManager, ArcRotateCameraKeyboardMoveInput, ArcRotateCameraMouseWheelInput, ArcRotateCameraPointersInput, ArcRotateCameraVRDeviceOrientationInput, ArcTan2Block, AssetContainer, AssetTaskState, AssetsManager, AssetsProgressEvent, AsyncLoop, AttachToBoxBehavior, AudioEngine, AudioSceneComponent, AutoLayoutMode, AutoReleaseWorkerPool, AutoRotationBehavior, AxesViewer, Axis, AxisDragGizmo, AxisScaleGizmo, BRDFTextureTools, BabylonFileLoaderConfiguration, BackEase, BackgroundMaterial, BakedVertexAnimationManager, BallAndSocketConstraint, BaseCameraMouseWheelInput, BaseCameraPointersInput, BaseError, BaseParticleSystem, BaseSixDofDragBehavior, BaseTexture, BasisTools, BasisToolsOptions, BasisTranscodeConfiguration, BezierCurve, BezierCurveEase, BiPlanarBlock, BinaryFileAssetTask, BlackAndWhitePostProcess, BlendFactor, BlendOperation, BloomEffect, BloomMergePostProcess, BlurPostProcess, Bone, BoneAxesViewer, BoneIKController, BoneLookController, BonesBlock, BounceEase, BouncingBehavior, BoundingBox, BoundingBoxGizmo, BoundingBoxRenderer, BoundingInfo, BoundingSphere, BoxBlock, BoxBuilder, BoxParticleEmitter, Buffer, BufferBindingType, BufferMapState, BufferUsage, CSG, Camera, CameraGizmo, CameraInputTypes, CameraInputsManager, CannonJSPlugin, CanvasAlphaMode, CapsuleBlock, CapsuleBuilder, CascadedShadowGenerator, ChromaticAberrationPostProcess, CircleEase, CircleOfConfusionPostProcess, ClampBlock, ClearCoatBlock, ClipPlanesBlock, ClipboardEventTypes, ClipboardInfo, CloudBlock, CloudPoint, Collider, Color3, Color3Gradient, ColorCorrectionPostProcess, ColorCurves, ColorGradient, ColorGradingTexture, ColorMergerBlock, ColorSplitterBlock, ColorWriteFlags, CombineAction, CompareFunction, CompatibilityOptions, CompilationMessageType, CompleteGreasedLineColorTable, CompleteGreasedLineWidthTable, ComputeBindingType, ComputeEffect, ComputeNormalsBlock, ComputePassTimestampLocation, ComputeShader, ComputeShaderParticleSystem, Condition, ConditionBlock, ConditionBlockTests, ConditionalBlock, ConditionalBlockConditions, ConeParticleEmitter, Constants, ContainerAssetTask, ConversionMode, ConvolutionPostProcess, Coordinate, CopyTextureToTexture, CopyTools, CreateBox, CreateBoxVertexData, CreateCapsule, CreateCapsuleVertexData, CreateCylinder, CreateCylinderVertexData, CreateDashedLines, CreateDashedLinesVertexData, CreateDecal, CreateDisc, CreateDiscVertexData, CreateEnvTextureAsync, CreateGeodesic, CreateGoldberg, CreateGoldbergVertexData, CreateGreasedLine, CreateGreasedLineMaterial, CreateGround, CreateGroundFromHeightMap, CreateGroundFromHeightMapVertexData, CreateGroundVertexData, CreateHemisphere, CreateIcoSphere, CreateIcoSphereVertexData, CreateImageDataArrayBufferViews, CreateLathe, CreateLineSystem, CreateLineSystemVertexData, CreateLines, CreatePlane, CreatePlaneVertexData, CreatePolygon, CreatePolygonVertexData, CreatePolyhedron, CreatePolyhedronVertexData, CreateResizedCopy, CreateRibbon, CreateRibbonVertexData, CreateScreenshot, CreateScreenshotAsync, CreateScreenshotUsingRenderTarget, CreateScreenshotUsingRenderTargetAsync, CreateScreenshotWithResizeAsync, CreateSegmentedBoxVertexData, CreateSphere, CreateSphereVertexData, CreateText, CreateTextShapePaths, CreateTiledBox, CreateTiledBoxVertexData, CreateTiledGround, CreateTiledGroundVertexData, CreateTiledPlane, CreateTiledPlaneVertexData, CreateTorus, CreateTorusKnot, CreateTorusKnotVertexData, CreateTorusVertexData, CreateTube, CrossBlock, CubeMapToSphericalPolynomialTools, CubeTexture, CubeTextureAssetTask, CubicEase, CullMode, CurrentScreenBlock, Curve3, CurveBlock, CurveBlockTypes, CustomBlock, CustomOptimization, CustomParticleEmitter, CustomProceduralTexture, CylinderBlock, CylinderBuilder, CylinderDirectedParticleEmitter, CylinderParticleEmitter, DDSTools, DataBuffer, DataReader, DataStorage, Database, DaydreamController, DebugBlock, DebugLayer, DebugLayerTab, DecalBuilder, DecalMapConfiguration, DecalMapDefines, Decode, DecodeBase64ToBinary, DecodeBase64ToString, DecodeBase64UrlToBinary, DecodeBase64UrlToString, DeepCopier, DefaultCollisionCoordinator, DefaultKTX2DecoderOptions, DefaultLoadingScreen, DefaultRenderingPipeline, Deferred, DepthCullingState, DepthOfFieldBlurPostProcess, DepthOfFieldEffect, DepthOfFieldEffectBlurLevel, DepthOfFieldMergePostProcess, DepthPeelingRenderer, DepthPeelingSceneComponent, DepthReducer, DepthRenderer, DepthRendererSceneComponent, DepthSortedParticle, DerivativeBlock, DesaturateBlock, DetailMapConfiguration, DeviceInputEventType, DeviceLostReason, DeviceOrientationCamera, DeviceSource, DeviceSourceManager, DeviceType, DirectionalLight, DirectionalLightFrustumViewer, DiscBlock, DiscBuilder, DiscardBlock, DisplayPassPostProcess, DistanceBlock, DistanceConstraint, DistanceJoint, DivideBlock, DoNothingAction, DomManagement, DotBlock, DracoCompression, DrawWrapper, DualSenseInput, DualShockButton, DualShockDpad, DualShockInput, DualShockPad, DumpTools, DynamicFloat32Array, DynamicTexture, EasingFunction, EdgesRenderer, Effect, EffectFallbacks, EffectLayer, EffectLayerSceneComponent, EffectRenderer, EffectWrapper, ElasticEase, ElbowBlock, EncodeArrayBufferToBase64, EndsWith, Engine, EngineFactory, EngineFormat, EngineInstrumentation, EngineStore, EngineView, EnvironmentHelper, EnvironmentTextureTools, Epsilon, EquiRectangularCubeTexture, EquiRectangularCubeTextureAssetTask, ErrorCodes, ErrorFilter, EventConstants, EventState, ExecuteCodeAction, ExponentialEase, ExternalTexture, ExtractHighlightsPostProcess, ExtrudePolygon, ExtrudeShape, ExtrudeShapeCustom, FactorGradient, FadeInOutBehavior, FeatureName, FileTools, FileToolsOptions, FilesInput, FilesInputStore, FilterMode, FilterPostProcess, FlowGraph, FlowGraphAddNumberBlock, FlowGraphBlock, FlowGraphEventBlock, FlowGraphExecutionBlock, FlowGraphForLoopBlock, FlowGraphLogBlock, FlowGraphMeshPickEventBlock, FlowGraphSceneReadyEventBlock, FlowGraphSignalConnection, FluidRenderer, FluidRendererSceneComponent, FluidRenderingDebug, FluidRenderingObject, FluidRenderingObjectCustomParticles, FluidRenderingObjectParticleSystem, FluidRenderingTargetRenderer, FlyCamera, FlyCameraInputsManager, FlyCameraKeyboardInput, FlyCameraMouseInput, FogBlock, FollowBehavior, FollowCamera, FollowCameraInputsManager, FollowCameraKeyboardMoveInput, FollowCameraMouseWheelInput, FollowCameraPointersInput, FragCoordBlock, FragDepthBlock, FragmentOutputBlock, FramingBehavior, FreeCamera, FreeCameraDeviceOrientationInput, FreeCameraGamepadInput, FreeCameraInputsManager, FreeCameraKeyboardMoveInput, FreeCameraMouseInput, FreeCameraMouseWheelInput, FreeCameraTouchInput, FreeCameraVirtualJoystickInput, FresnelBlock, FresnelParameters, FromHalfFloat, FrontFace, FrontFacingBlock, Frustum, FxaaPostProcess, GPUParticleSystem, GUID, Gamepad, GamepadCamera, GamepadManager, GamepadSystemSceneComponent, GearVRController, GenerateBase64StringFromPixelData, GenerateBase64StringFromTexture, GenerateBase64StringFromTextureAsync, GenericController, GenericPad, GeodesicData, Geometry, GeometryBufferRenderer, GeometryBufferRendererSceneComponent, GeometryCollectionBlock, GeometryElbowBlock, GeometryInfoBlock, GeometryInputBlock, GeometryOptimizeBlock, GeometryOutputBlock, GeometryTransformBlock, GeometryTrigonometryBlock, GeometryTrigonometryBlockOperations, GetClass, GetDOMTextContent, GetEnvInfo, GetEnvironmentBRDFTexture, GetInternalFormatFromBasisFormat, GetTGAHeader, Gizmo, GizmoAnchorPoint, GizmoCoordinatesMode, GizmoManager, GlowLayer, GoldbergMesh, GradientBlock, GradientBlockColorStep, GradientHelper, GrainPostProcess, GreasedLineMesh, GreasedLineMeshColorDistribution, GreasedLineMeshColorDistributionType, GreasedLineMeshColorMode, GreasedLineMeshMaterialType, GreasedLineMeshWidthDistribution, GreasedLinePluginMaterial, GreasedLineTools, GridBlock, GroundBuilder, GroundMesh, HDRCubeTexture, HDRCubeTextureAssetTask, HDRFiltering, HDRTools, HandConstraintBehavior, HandConstraintOrientation, HandConstraintVisibility, HandConstraintZone, HandPart, HardwareScalingOptimization, HavokPlugin, HeightToNormalBlock, HemisphereBuilder, HemisphericLight, HemisphericParticleEmitter, HighlightLayer, HighlightsPostProcess, Hinge2Joint, HingeConstraint, HingeJoint, HtmlElementTexture, IWebXRControllerPhysicsOptions, IcoSphereBlock, IcoSphereBuilder, ImageAssetTask, ImageProcessingBlock, ImageProcessingConfiguration, ImageProcessingConfigurationDefines, ImageProcessingPostProcess, ImageSourceBlock, IncrementValueAction, IndexFormat, InputBlock, InputStepMode, InspectableType, InstancedLinesMesh, InstancedMesh, InstancesBlock, InstantiateBlock, InstantiateOnFacesBlock, InstantiateOnVerticesBlock, InstantiateOnVolumeBlock, InstantiatedEntries, IntFloatConverterBlock, InternalTexture, InternalTextureSource, InterpolateValueAction, IntersectionInfo, IsBase64DataUrl, IsDocumentAvailable, IsFileURL, IsNavigatorAvailable, IsWindowObjectExist, JoystickAxis, KeepAssets, KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre, KhronosTextureContainer, KhronosTextureContainer2, LatheBuilder, Layer, LayerSceneComponent, LengthBlock, LensFlare, LensFlareSystem, LensFlareSystemSceneComponent, LensFlaresOptimization, LensRenderingPipeline, LerpBlock, Light, LightBlock, LightGizmo, LightInformationBlock, LineEdgesRenderer, LinesBuilder, LinesMesh, LoadFile, LoadFileError, LoadImage, LoadOp, LoadTextureFromTranscodeResult, LockConstraint, Logger, MapMode, MapRangeBlock, Material, MaterialAnisotropicDefines, MaterialClearCoatDefines, MaterialDefines, MaterialDetailMapDefines, MaterialFlags, MaterialGreasedLineDefines, MaterialHelper, MaterialIridescenceDefines, MaterialPluginBase, MaterialPluginEvent, MaterialPluginManager, MaterialSheenDefines, MaterialSubSurfaceDefines, MathBlock, MathBlockOperations, Matrix, MatrixBuilderBlock, MatrixDeterminantBlock, MatrixTransposeBlock, MaxBlock, MergeGeometryBlock, MergeMeshesOptimization, Mesh, MeshAssetTask, MeshAttributeExistsBlock, MeshAttributeExistsBlockTypes, MeshBlock, MeshBuilder, MeshDebugMode, MeshDebugPluginMaterial, MeshExploder, MeshLODLevel, MeshParticleEmitter, MeshUVSpaceRenderer, MeshoptCompression, MinBlock, MinMaxReducer, MipmapFilterMode, MirrorTexture, ModBlock, ModelShape, MorphTarget, MorphTargetManager, MorphTargetsBlock, MotionBlurPostProcess, MotorEnabledJoint, MultiMaterial, MultiObserver, MultiPointerScaleBehavior, MultiRenderTarget, MultiplyBlock, NLerpBlock, NativeDataStream, NativeEngine, NativePointerInput, NativeXRFrame, NativeXRLayerRenderTargetTextureProvider, NativeXRLayerWrapper, NativeXRRenderTarget, NegateBlock, Node, NodeGeometry, NodeGeometryBlock, NodeGeometryBlockConnectionPointTypes, NodeGeometryBuildState, NodeGeometryConnectionPoint, NodeGeometryConnectionPointCompatibilityStates, NodeGeometryConnectionPointDirection, NodeGeometryContextualSources, NodeMaterial, NodeMaterialBlock, NodeMaterialBlockConnectionPointMode, NodeMaterialBlockConnectionPointTypes, NodeMaterialBlockTargets, NodeMaterialConnectionPoint, NodeMaterialConnectionPointCompatibilityStates, NodeMaterialConnectionPointCustomObject, NodeMaterialConnectionPointDirection, NodeMaterialDefines, NodeMaterialModes, NodeMaterialOptimizer, NodeMaterialSystemValues, NodeMaterialTeleportInBlock, NodeMaterialTeleportOutBlock, NoiseBlock, NoiseProceduralTexture, NormalBlendBlock, NormalizeBlock, NormalizeVectorBlock, NullBlock, NullEngine, NullEngineOptions, Observable, Observer, OcclusionMaterial, Octree, OctreeBlock, OctreeSceneComponent, OculusTouchController, OimoJSPlugin, OnAfterEnteringVRObservableEvent, OneMinusBlock, Orientation, OutlineRenderer, PBRAnisotropicConfiguration, PBRBaseMaterial, PBRBaseSimpleMaterial, PBRClearCoatConfiguration, PBRIridescenceConfiguration, PBRMaterial, PBRMaterialDefines, PBRMetallicRoughnessBlock, PBRMetallicRoughnessMaterial, PBRSheenConfiguration, PBRSpecularGlossinessMaterial, PBRSubSurfaceConfiguration, PHI, PadNumber, PanoramaToCubeMapTools, Particle, ParticleBlendMultiplyBlock, ParticleHelper, ParticleRampGradientBlock, ParticleSystem, ParticleSystemSet, ParticleTextureBlock, ParticlesOptimization, PassCubePostProcess, PassPostProcess, Path2, Path3D, PathCursor, PerfCollectionStrategy, PerfCounter, PerformanceConfigurator, PerformanceMonitor, PerformanceViewerCollector, PerturbNormalBlock, PhotoDome, Physics6DoFConstraint, Physics6DoFLimit, PhysicsAggregate, PhysicsBody, PhysicsConstraint, PhysicsConstraintAxis, PhysicsConstraintAxisLimitMode, PhysicsConstraintMotorType, PhysicsConstraintType, PhysicsEngine, PhysicsEngineV2, PhysicsEventType, PhysicsHelper, PhysicsImpostor, PhysicsJoint, PhysicsMaterialCombineMode, PhysicsMotionType, PhysicsRadialExplosionEventOptions, PhysicsRadialImpulseFalloff, PhysicsRaycastResult, PhysicsShape, PhysicsShapeBox, PhysicsShapeCapsule, PhysicsShapeContainer, PhysicsShapeConvexHull, PhysicsShapeCylinder, PhysicsShapeMesh, PhysicsShapeSphere, PhysicsShapeType, PhysicsUpdraftEventOptions, PhysicsUpdraftMode, PhysicsViewer, PhysicsVortexEventOptions, PickingInfo, PipelineErrorReason, PivotTools, Plane, PlaneBlock, PlaneBuilder, PlaneDragGizmo, PlaneRotationGizmo, PlayAnimationAction, PlaySoundAction, PointColor, PointLight, PointParticleEmitter, PointerDragBehavior, PointerEventTypes, PointerInfo, PointerInfoBase, PointerInfoPre, PointerInput, PointsCloudSystem, PointsGroup, Polar, Polygon, PolygonBuilder, PolygonMeshBuilder, PolyhedronBuilder, PolyhedronData, PoseEnabledController, PoseEnabledControllerHelper, PoseEnabledControllerType, PositionGizmo, PositionNormalTextureVertex, PositionNormalVertex, PostProcessManager, PostProcessRenderEffect, PostProcessRenderPipeline, PostProcessRenderPipelineManager, PostProcessRenderPipelineManagerSceneComponent, PostProcessesOptimization, PosterizeBlock, PowBlock, PowerEase, PowerPreference, PrePassRenderer, PrePassRendererSceneComponent, PrecisionDate, PredicateCondition, PressureObserverWrapper, PrimitiveTopology, PrismaticConstraint, ProceduralTexture, ProceduralTextureSceneComponent, PropertyTypeForEdition, PushMaterial, QuadraticEase, QuadraticErrorSimplification, QuarticEase, Quaternion, QueryType, QuinticEase, RGBDTextureTools, RandomBlock, RandomGUID, RandomNumberBlock, RawCubeTexture, RawTexture, RawTexture2DArray, RawTexture3D, Ray, RayHelper, ReadFile, ReadFileError, RecastJSCrowd, RecastJSPlugin, ReciprocalBlock, ReflectBlock, ReflectionBlock, ReflectionProbe, ReflectionTextureBlock, Reflector, RefractBlock, RefractionBlock, RefractionPostProcess, RefractionTexture, RegisterClass, RegisterMaterialPlugin, RegisterNativeTypeAsync, RemapBlock, RenderPassTimestampLocation, RenderTargetTexture, RenderTargetWrapper, RenderTargetsOptimization, RenderingGroup, RenderingGroupInfo, RenderingManager, ReplaceColorBlock, RequestFile, RequestFileError, RetryStrategy, RibbonBuilder, RollingAverage, Rotate2dBlock, RotationGizmo, RotationXBlock, RotationYBlock, RotationZBlock, RuntimeAnimation, RuntimeError, SSAO2RenderingPipeline, SSAORenderingPipeline, SSRRenderingPipeline, SamplerBindingType, Scalar, ScaleBlock, ScaleGizmo, ScalingBlock, Scene, SceneComponentConstants, SceneDepthBlock, SceneInstrumentation, SceneLoader, SceneLoaderAnimationGroupLoadingMode, SceneLoaderFlags, SceneOptimization, SceneOptimizer, SceneOptimizerOptions, ScenePerformancePriority, SceneRecorder, SceneSerializer, ScreenSizeBlock, ScreenSpaceBlock, ScreenSpaceCurvaturePostProcess, ScreenSpaceReflectionPostProcess, ScreenshotTools, SerializationHelper, SetColorsBlock, SetCorsBehavior, SetMaterialIDBlock, SetNormalsBlock, SetParentAction, SetPositionsBlock, SetStateAction, SetTangentsBlock, SetUVsBlock, SetValueAction, ShaderCodeInliner, ShaderMaterial, ShaderStage, ShaderStore, ShadowDepthWrapper, ShadowGenerator, ShadowGeneratorSceneComponent, ShadowLight, ShadowMapBlock, ShadowsOptimization, ShapeBuilder, SharpenPostProcess, SheenBlock, SimplexPerlin3DBlock, SimplicationQueueSceneComponent, SimplificationQueue, SimplificationSettings, SimplificationType, SineEase, SixDofDragBehavior, Size, Skeleton, SkeletonViewer, SliderConstraint, SmartArray, SmartArrayNoDuplicate, SmoothStepBlock, SolidParticle, SolidParticleSystem, SolidParticleVertex, Sound, SoundTrack, SourceTextureFormat, Space, SphereBlock, SphereBuilder, SphereDirectedParticleEmitter, SphereParticleEmitter, Spherical, SphericalHarmonics, SphericalPolynomial, SpotLight, SpringConstraint, Sprite, SpriteManager, SpriteMap, SpritePackedManager, SpriteSceneComponent, Stage, StandardMaterial, StandardMaterialDefines, StandardRenderingPipeline, StartsWith, StateCondition, StencilOperation, StencilState, StencilStateComposer, StepBlock, StereoscopicArcRotateCamera, StereoscopicFreeCamera, StereoscopicGamepadCamera, StereoscopicInterlacePostProcess, StereoscopicInterlacePostProcessI, StereoscopicScreenUniversalCamera, StereoscopicUniversalCamera, StickValues, StopAnimationAction, StopSoundAction, StorageBuffer, StorageTextureAccess, StoreOp, StringDictionary, StringTools, SubEmitter, SubEmitterType, SubMesh, SubSurfaceBlock, SubSurfaceSceneComponent, SubtractBlock, SurfaceMagnetismBehavior, SwitchBooleanAction, SwitchInput, TBNBlock, TGATools, Tags, TargetCamera, TargetedAnimation, TeleportInBlock, TeleportOutBlock, TestBase64DataUrl, TextFileAssetTask, Texture, TextureAspect, TextureAssetTask, TextureBlock, TextureDimension, TextureFormat, TextureOptimization, TexturePacker, TexturePackerFrame, TextureSampleType, TextureSampler, TextureTools, TextureUsage, TextureViewDimension, ThinEngine, ThinRenderTargetTexture, ThinTexture, TiledBoxBuilder, TiledPlaneBuilder, TimerState, TmpColors, TmpVectors, ToGammaSpace, ToHalfFloat, ToLinearSpace, TonemapPostProcess, TonemappingOperator, TorusBlock, TorusBuilder, TorusKnotBuilder, TouchCamera, TrailMesh, Trajectory, TrajectoryClassifier, TranscodeAsync, TranscodeTarget, TransformBlock, TransformNode, TranslationBlock, TriPlanarBlock, TrigonometryBlock, TrigonometryBlockOperations, TubeBuilder, TwirlBlock, UniformBuffer, UniversalCamera, UnregisterAllMaterialPlugins, UnregisterMaterialPlugin, UploadContent, UploadEnvLevelsAsync, UploadEnvSpherical, UploadLevelsAsync, UtilityLayerRenderer, VRCameraMetrics, VRDeviceOrientationArcRotateCamera, VRDeviceOrientationFreeCamera, VRDeviceOrientationGamepadCamera, VRDistortionCorrectionPostProcess, VRExperienceHelper, VRMultiviewToSingleviewPostProcess, ValidatedNativeDataStream, ValueCondition, Vector2, Vector3, Vector4, VectorConverterBlock, VectorMergerBlock, VectorSplitterBlock, VertexAnimationBaker, VertexBuffer, VertexData, VertexDataMaterialInfo, VertexFormat, VertexOutputBlock, VideoDome, VideoRecorder, VideoTexture, ViewDirectionBlock, Viewport, VirtualJoystick, VirtualJoysticksCamera, ViveController, VolumetricLightScatteringPostProcess, VoronoiNoiseBlock, WaveBlock, WaveBlockKind, WebGL2ParticleSystem, WebGL2ShaderProcessor, WebGLDataBuffer, WebGLHardwareTexture, WebGLPipelineContext, WebGPUCacheBindGroups, WebGPUCacheRenderPipeline, WebGPUCacheRenderPipelineTree, WebGPUCacheSampler, WebGPUDataBuffer, WebGPUDrawContext, WebGPUEngine, WebGPUTintWASM, WebRequest, WebVRController, WebVRFreeCamera, WebXRAbstractFeature, WebXRAbstractMotionController, WebXRAnchorSystem, WebXRBackgroundRemover, WebXRCamera, WebXRCompositionLayerWrapper, WebXRControllerComponent, WebXRControllerMovement, WebXRControllerPhysics, WebXRControllerPointerSelection, WebXRDefaultExperience, WebXRDefaultExperienceOptions, WebXRDepthSensing, WebXRDomOverlay, WebXREnterExitUI, WebXREnterExitUIButton, WebXREnterExitUIOptions, WebXRExperienceHelper, WebXREyeTracking, WebXRFeatureName, WebXRFeaturePointSystem, WebXRFeaturesManager, WebXRGenericHandController, WebXRGenericTriggerMotionController, WebXRHTCViveMotionController, WebXRHand, WebXRHandJoint, WebXRHandTracking, WebXRHitTest, WebXRHitTestLegacy, WebXRImageTracking, WebXRInput, WebXRInputSource, WebXRLayers, WebXRLightEstimation, WebXRManagedOutputCanvas, WebXRManagedOutputCanvasOptions, WebXRMeshDetector, WebXRMicrosoftMixedRealityController, WebXRMotionControllerManager, WebXRMotionControllerTeleportation, WebXRNearControllerMode, WebXRNearInteraction, WebXROculusTouchMotionController, WebXRPlaneDetector, WebXRProfiledMotionController, WebXRProjectionLayerWrapper, WebXRSessionManager, WebXRSpaceWarp, WebXRSpaceWarpRenderTargetTextureProvider, WebXRState, WebXRTrackingState, WebXRWalkingLocomotion, WeightedSound, WindowsMotionController, WorkerPool, WorleyNoise3DBlock, XRSpaceWarpRenderTarget, XRWindowsMotionController, Xbox360Button, Xbox360Dpad, Xbox360Pad, XboxInput, _BabylonLoaderRegistered, _BasisTextureLoader, _CreationDataStorage, _DDSTextureLoader, _ENVTextureLoader, _HDRTextureLoader, _IAnimationState, _InstancesBatch, _KTXTextureLoader, _MeshCollisionData, _OcclusionDataStorage, _PrimaryIsoTriangle, _TGATextureLoader, _TimeToken, _UpdateRGBDAsync, _forceSceneHelpersToBundle, _forceTransformFeedbackToBundle, _injectLTSFileTools, addClipPlaneUniforms, allocateAndCopyTypedBuffer, bindClipPlane, className, createDetailMapPlugin, createPBRAnisotropicPlugin, createPBRBRDFPlugin, createPBRClearCoatPlugin, createPBRIridescencePlugin, createPBRSheenPlugin, createPBRSubSurfacePlugin, createYieldingScheduler, editableInPropertyPage, expandToProperty, extractMinAndMax, extractMinAndMaxIndexed, inlineScheduler, makeAsyncFunction, makeSyncFunction, nativeOverride, normalizeEnvInfo, prepareDefinesForClipPlanes, prepareStringDefinesForClipPlanes, runCoroutine, runCoroutineAsync, runCoroutineSync, serialize, serializeAsCameraReference, serializeAsColor3, serializeAsColor4, serializeAsColorCurves, serializeAsFresnelParameters, serializeAsImageProcessingConfiguration, serializeAsMatrix, serializeAsMeshReference, serializeAsQuaternion, serializeAsTexture, serializeAsVector2, serializeAsVector3, setAndStartTimer, setStereoscopicAnaglyphRigMode, setStereoscopicRigMode, setVRRigMode, setWebVRRigMode - -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/abstractScene.js -/** - * Base class of the scene acting as a container for the different elements composing a scene. - * This class is dynamically extended by the different components of the scene increasing - * flexibility and reducing coupling - */ -class AbstractScene { - constructor() { - /** - * Gets the list of root nodes (ie. nodes with no parent) - */ - this.rootNodes = new Array(); - /** All of the cameras added to this scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras - */ - this.cameras = new Array(); - /** - * All of the lights added to this scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction - */ - this.lights = new Array(); - /** - * All of the (abstract) meshes added to this scene - */ - this.meshes = new Array(); - /** - * The list of skeletons added to the scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons - */ - this.skeletons = new Array(); - /** - * All of the particle systems added to this scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro - */ - this.particleSystems = new Array(); - /** - * Gets a list of Animations associated with the scene - */ - this.animations = []; - /** - * All of the animation groups added to this scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations - */ - this.animationGroups = new Array(); - /** - * All of the multi-materials added to this scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials - */ - this.multiMaterials = new Array(); - /** - * All of the materials added to this scene - * In the context of a Scene, it is not supposed to be modified manually. - * Any addition or removal should be done using the addMaterial and removeMaterial Scene methods. - * Note also that the order of the Material within the array is not significant and might change. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction - */ - this.materials = new Array(); - /** - * The list of morph target managers added to the scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph - */ - this.morphTargetManagers = new Array(); - /** - * The list of geometries used in the scene. - */ - this.geometries = new Array(); - /** - * All of the transform nodes added to this scene - * In the context of a Scene, it is not supposed to be modified manually. - * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods. - * Note also that the order of the TransformNode within the array is not significant and might change. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node - */ - this.transformNodes = new Array(); - /** - * ActionManagers available on the scene. - * @deprecated - */ - this.actionManagers = new Array(); - /** - * Textures to keep. - */ - this.textures = new Array(); - /** @internal */ - this._environmentTexture = null; - /** - * The list of postprocesses added to the scene - */ - this.postProcesses = new Array(); - } - /** - * Adds a parser in the list of available ones - * @param name Defines the name of the parser - * @param parser Defines the parser to add - */ - static AddParser(name, parser) { - this._BabylonFileParsers[name] = parser; - } - /** - * Gets a general parser from the list of available ones - * @param name Defines the name of the parser - * @returns the requested parser or null - */ - static GetParser(name) { - if (this._BabylonFileParsers[name]) { - return this._BabylonFileParsers[name]; - } - return null; - } - /** - * Adds n individual parser in the list of available ones - * @param name Defines the name of the parser - * @param parser Defines the parser to add - */ - static AddIndividualParser(name, parser) { - this._IndividualBabylonFileParsers[name] = parser; - } - /** - * Gets an individual parser from the list of available ones - * @param name Defines the name of the parser - * @returns the requested parser or null - */ - static GetIndividualParser(name) { - if (this._IndividualBabylonFileParsers[name]) { - return this._IndividualBabylonFileParsers[name]; - } - return null; - } - /** - * Parser json data and populate both a scene and its associated container object - * @param jsonData Defines the data to parse - * @param scene Defines the scene to parse the data for - * @param container Defines the container attached to the parsing sequence - * @param rootUrl Defines the root url of the data - */ - static Parse(jsonData, scene, container, rootUrl) { - for (const parserName in this._BabylonFileParsers) { - if (Object.prototype.hasOwnProperty.call(this._BabylonFileParsers, parserName)) { - this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl); - } - } - } - /** - * Texture used in all pbr material as the reflection texture. - * As in the majority of the scene they are the same (exception for multi room and so on), - * this is easier to reference from here than from all the materials. - */ - get environmentTexture() { - return this._environmentTexture; - } - set environmentTexture(value) { - this._environmentTexture = value; - } - /** - * @returns all meshes, lights, cameras, transformNodes and bones - */ - getNodes() { - let nodes = new Array(); - nodes = nodes.concat(this.meshes); - nodes = nodes.concat(this.lights); - nodes = nodes.concat(this.cameras); - nodes = nodes.concat(this.transformNodes); // dummies - this.skeletons.forEach((skeleton) => (nodes = nodes.concat(skeleton.bones))); - return nodes; - } -} -/** - * Stores the list of available parsers in the application. - */ -AbstractScene._BabylonFileParsers = {}; -/** - * Stores the list of available individual parsers in the application. - */ -AbstractScene._IndividualBabylonFileParsers = {}; -//# sourceMappingURL=abstractScene.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Actions/abstractActionManager.js - -/** - * Abstract class used to decouple action Manager from scene and meshes. - * Do not instantiate. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class AbstractActionManager { - constructor() { - /** Gets the cursor to use when hovering items */ - this.hoverCursor = ""; - /** Gets the list of actions */ - this.actions = new Array(); - /** - * Gets or sets a boolean indicating that the manager is recursive meaning that it can trigger action from children - */ - this.isRecursive = false; - } - /** - * Does exist one action manager with at least one trigger - **/ - static get HasTriggers() { - for (const t in AbstractActionManager.Triggers) { - if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) { - return true; - } - } - return false; - } - /** - * Does exist one action manager with at least one pick trigger - **/ - static get HasPickTriggers() { - for (const t in AbstractActionManager.Triggers) { - if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) { - const tAsInt = parseInt(t); - if (tAsInt >= 1 && tAsInt <= 7) { - return true; - } - } - } - return false; - } - /** - * Does exist one action manager that handles actions of a given trigger - * @param trigger defines the trigger to be tested - * @returns a boolean indicating whether the trigger is handled by at least one action manager - **/ - static HasSpecificTrigger(trigger) { - for (const t in AbstractActionManager.Triggers) { - if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) { - const tAsInt = parseInt(t); - if (tAsInt === trigger) { - return true; - } - } - } - return false; - } -} -/** Gets the list of active triggers */ -AbstractActionManager.Triggers = {}; -//# sourceMappingURL=abstractActionManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/observable.js -/** - * A class serves as a medium between the observable and its observers - */ -class EventState { - /** - * Create a new EventState - * @param mask defines the mask associated with this state - * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true - * @param target defines the original target of the state - * @param currentTarget defines the current target of the state - */ - constructor(mask, skipNextObservers = false, target, currentTarget) { - this.initialize(mask, skipNextObservers, target, currentTarget); - } - /** - * Initialize the current event state - * @param mask defines the mask associated with this state - * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true - * @param target defines the original target of the state - * @param currentTarget defines the current target of the state - * @returns the current event state - */ - initialize(mask, skipNextObservers = false, target, currentTarget) { - this.mask = mask; - this.skipNextObservers = skipNextObservers; - this.target = target; - this.currentTarget = currentTarget; - return this; - } -} -/** - * Represent an Observer registered to a given Observable object. - */ -class Observer { - /** - * Creates a new observer - * @param callback defines the callback to call when the observer is notified - * @param mask defines the mask of the observer (used to filter notifications) - * @param scope defines the current scope used to restore the JS context - */ - constructor( - /** - * Defines the callback to call when the observer is notified - */ - callback, - /** - * Defines the mask of the observer (used to filter notifications) - */ - mask, - /** - * Defines the current scope used to restore the JS context - */ - scope = null) { - this.callback = callback; - this.mask = mask; - this.scope = scope; - /** @internal */ - this._willBeUnregistered = false; - /** - * Gets or sets a property defining that the observer as to be unregistered after the next notification - */ - this.unregisterOnNextCall = false; - /** - * this function can be used to remove the observer from the observable. - * It will be set by the observable that the observer belongs to. - * @internal - */ - this._remove = null; - } - /** - * Remove the observer from its observable - * This can be used instead of using the observable's remove function. - */ - remove() { - if (this._remove) { - this._remove(); - } - } -} -/** - * The Observable class is a simple implementation of the Observable pattern. - * - * 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. - * This enable a more fine grained execution without having to rely on multiple different Observable objects. - * 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). - * 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. - */ -class observable_Observable { - /** - * Create an observable from a Promise. - * @param promise a promise to observe for fulfillment. - * @param onErrorObservable an observable to notify if a promise was rejected. - * @returns the new Observable - */ - static FromPromise(promise, onErrorObservable) { - const observable = new observable_Observable(); - promise - .then((ret) => { - observable.notifyObservers(ret); - }) - .catch((err) => { - if (onErrorObservable) { - onErrorObservable.notifyObservers(err); - } - else { - throw err; - } - }); - return observable; - } - /** - * Gets the list of observers - * 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! - */ - get observers() { - return this._observers; - } - /** - * Creates a new observable - * @param onObserverAdded defines a callback to call when a new observer is added - * @param notifyIfTriggered If set to true the observable will notify when an observer was added if the observable was already triggered. - */ - constructor(onObserverAdded, - /** - * If set to true the observable will notify when an observer was added if the observable was already triggered. - * This is helpful to single-state observables like the scene onReady or the dispose observable. - */ - notifyIfTriggered = false) { - this.notifyIfTriggered = notifyIfTriggered; - this._observers = new Array(); - this._numObserversMarkedAsDeleted = 0; - this._hasNotified = false; - this._eventState = new EventState(0); - if (onObserverAdded) { - this._onObserverAdded = onObserverAdded; - } - } - /** - * Create a new Observer with the specified callback - * @param callback the callback that will be executed for that Observer - * @param mask the mask used to filter observers - * @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. - * @param scope optional scope for the callback to be called from - * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification - * @returns the new observer created for the callback - */ - add(callback, mask = -1, insertFirst = false, scope = null, unregisterOnFirstCall = false) { - if (!callback) { - return null; - } - const observer = new Observer(callback, mask, scope); - observer.unregisterOnNextCall = unregisterOnFirstCall; - if (insertFirst) { - this._observers.unshift(observer); - } - else { - this._observers.push(observer); - } - if (this._onObserverAdded) { - this._onObserverAdded(observer); - } - // If the observable was already triggered and the observable is set to notify if triggered, notify the new observer - if (this._hasNotified && this.notifyIfTriggered) { - if (this._lastNotifiedValue !== undefined) { - this.notifyObserver(observer, this._lastNotifiedValue); - } - } - // attach the remove function to the observer - observer._remove = () => { - this.remove(observer); - }; - return observer; - } - /** - * Create a new Observer with the specified callback and unregisters after the next notification - * @param callback the callback that will be executed for that Observer - * @returns the new observer created for the callback - */ - addOnce(callback) { - return this.add(callback, undefined, undefined, undefined, true); - } - /** - * Remove an Observer from the Observable object - * @param observer the instance of the Observer to remove - * @returns false if it doesn't belong to this Observable - */ - remove(observer) { - if (!observer) { - return false; - } - observer._remove = null; - const index = this._observers.indexOf(observer); - if (index !== -1) { - this._deferUnregister(observer); - return true; - } - return false; - } - /** - * Remove a callback from the Observable object - * @param callback the callback to remove - * @param scope optional scope. If used only the callbacks with this scope will be removed - * @returns false if it doesn't belong to this Observable - */ - removeCallback(callback, scope) { - for (let index = 0; index < this._observers.length; index++) { - const observer = this._observers[index]; - if (observer._willBeUnregistered) { - continue; - } - if (observer.callback === callback && (!scope || scope === observer.scope)) { - this._deferUnregister(observer); - return true; - } - } - return false; - } - /** - * @internal - */ - _deferUnregister(observer) { - if (observer._willBeUnregistered) { - return; - } - this._numObserversMarkedAsDeleted++; - observer.unregisterOnNextCall = false; - observer._willBeUnregistered = true; - setTimeout(() => { - this._remove(observer); - }, 0); - } - // This should only be called when not iterating over _observers to avoid callback skipping. - // Removes an observer from the _observer Array. - _remove(observer, updateCounter = true) { - if (!observer) { - return false; - } - const index = this._observers.indexOf(observer); - if (index !== -1) { - if (updateCounter) { - this._numObserversMarkedAsDeleted--; - } - this._observers.splice(index, 1); - return true; - } - return false; - } - /** - * Moves the observable to the top of the observer list making it get called first when notified - * @param observer the observer to move - */ - makeObserverTopPriority(observer) { - this._remove(observer, false); - this._observers.unshift(observer); - } - /** - * Moves the observable to the bottom of the observer list making it get called last when notified - * @param observer the observer to move - */ - makeObserverBottomPriority(observer) { - this._remove(observer, false); - this._observers.push(observer); - } - /** - * Notify all Observers by calling their respective callback with the given data - * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute - * @param eventData defines the data to send to all observers - * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified) - * @param target defines the original target of the state - * @param currentTarget defines the current target of the state - * @param userInfo defines any user info to send to observers - * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true) - */ - notifyObservers(eventData, mask = -1, target, currentTarget, userInfo) { - // this prevents potential memory leaks - if an object is disposed but the observable doesn't get cleared. - if (this.notifyIfTriggered) { - this._hasNotified = true; - this._lastNotifiedValue = eventData; - } - if (!this._observers.length) { - return true; - } - const state = this._eventState; - state.mask = mask; - state.target = target; - state.currentTarget = currentTarget; - state.skipNextObservers = false; - state.lastReturnValue = eventData; - state.userInfo = userInfo; - for (const obs of this._observers) { - if (obs._willBeUnregistered) { - continue; - } - if (obs.mask & mask) { - if (obs.unregisterOnNextCall) { - this._deferUnregister(obs); - } - if (obs.scope) { - state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]); - } - else { - state.lastReturnValue = obs.callback(eventData, state); - } - } - if (state.skipNextObservers) { - return false; - } - } - return true; - } - /** - * Notify a specific observer - * @param observer defines the observer to notify - * @param eventData defines the data to be sent to each callback - * @param mask is used to filter observers defaults to -1 - */ - notifyObserver(observer, eventData, mask = -1) { - // this prevents potential memory leaks - if an object is disposed but the observable doesn't get cleared. - if (this.notifyIfTriggered) { - this._hasNotified = true; - this._lastNotifiedValue = eventData; - } - if (observer._willBeUnregistered) { - return; - } - const state = this._eventState; - state.mask = mask; - state.skipNextObservers = false; - if (observer.unregisterOnNextCall) { - this._deferUnregister(observer); - } - observer.callback(eventData, state); - } - /** - * Gets a boolean indicating if the observable has at least one observer - * @returns true is the Observable has at least one Observer registered - */ - hasObservers() { - return this._observers.length - this._numObserversMarkedAsDeleted > 0; - } - /** - * Clear the list of observers - */ - clear() { - while (this._observers.length) { - const o = this._observers.pop(); - if (o) { - o._remove = null; - } - } - this._onObserverAdded = null; - this._numObserversMarkedAsDeleted = 0; - this.cleanLastNotifiedState(); - } - /** - * Clean the last notified state - both the internal last value and the has-notified flag - */ - cleanLastNotifiedState() { - this._hasNotified = false; - this._lastNotifiedValue = undefined; - } - /** - * Clone the current observable - * @returns a new observable - */ - clone() { - const result = new observable_Observable(); - result._observers = this._observers.slice(0); - return result; - } - /** - * Does this observable handles observer registered with a given mask - * @param mask defines the mask to be tested - * @returns whether or not one observer registered with the given mask is handled - **/ - hasSpecificMask(mask = -1) { - for (const obs of this._observers) { - if (obs.mask & mask || obs.mask === mask) { - return true; - } - } - return false; - } -} -//# sourceMappingURL=observable.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.scalar.js -/** - * Scalar computation library - */ -class math_scalar_Scalar { - /** - * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45) - * @param a number - * @param b number - * @param epsilon (default = 1.401298E-45) - * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45) - */ - static WithinEpsilon(a, b, epsilon = 1.401298e-45) { - return Math.abs(a - b) <= epsilon; - } - /** - * Returns a string : the upper case translation of the number i to hexadecimal. - * @param i number - * @returns the upper case translation of the number i to hexadecimal. - */ - static ToHex(i) { - const str = i.toString(16); - if (i <= 15) { - return ("0" + str).toUpperCase(); - } - return str.toUpperCase(); - } - /** - * Returns -1 if value is negative and +1 is value is positive. - * @param value the value - * @returns the value itself if it's equal to zero. - */ - static Sign(value) { - value = +value; // convert to a number - if (value === 0 || isNaN(value)) { - return value; - } - return value > 0 ? 1 : -1; - } - /** - * Returns the value itself if it's between min and max. - * Returns min if the value is lower than min. - * Returns max if the value is greater than max. - * @param value the value to clmap - * @param min the min value to clamp to (default: 0) - * @param max the max value to clamp to (default: 1) - * @returns the clamped value - */ - static Clamp(value, min = 0, max = 1) { - return Math.min(max, Math.max(min, value)); - } - /** - * the log2 of value. - * @param value the value to compute log2 of - * @returns the log2 of value. - */ - static Log2(value) { - return Math.log(value) * Math.LOG2E; - } - /** - * the floor part of a log2 value. - * @param value the value to compute log2 of - * @returns the log2 of value. - */ - static ILog2(value) { - if (Math.log2) { - return Math.floor(Math.log2(value)); - } - if (value < 0) { - return NaN; - } - else if (value === 0) { - return -Infinity; - } - let n = 0; - if (value < 1) { - while (value < 1) { - n++; - value = value * 2; - } - n = -n; - } - else if (value > 1) { - while (value > 1) { - n++; - value = Math.floor(value / 2); - } - } - return n; - } - /** - * Loops the value, so that it is never larger than length and never smaller than 0. - * - * This is similar to the modulo operator but it works with floating point numbers. - * For example, using 3.0 for t and 2.5 for length, the result would be 0.5. - * With t = 5 and length = 2.5, the result would be 0.0. - * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator - * @param value the value - * @param length the length - * @returns the looped value - */ - static Repeat(value, length) { - return value - Math.floor(value / length) * length; - } - /** - * Normalize the value between 0.0 and 1.0 using min and max values - * @param value value to normalize - * @param min max to normalize between - * @param max min to normalize between - * @returns the normalized value - */ - static Normalize(value, min, max) { - return (value - min) / (max - min); - } - /** - * Denormalize the value from 0.0 and 1.0 using min and max values - * @param normalized value to denormalize - * @param min max to denormalize between - * @param max min to denormalize between - * @returns the denormalized value - */ - static Denormalize(normalized, min, max) { - return normalized * (max - min) + min; - } - /** - * Calculates the shortest difference between two given angles given in degrees. - * @param current current angle in degrees - * @param target target angle in degrees - * @returns the delta - */ - static DeltaAngle(current, target) { - let num = math_scalar_Scalar.Repeat(target - current, 360.0); - if (num > 180.0) { - num -= 360.0; - } - return num; - } - /** - * PingPongs the value t, so that it is never larger than length and never smaller than 0. - * @param tx value - * @param length length - * @returns The returned value will move back and forth between 0 and length - */ - static PingPong(tx, length) { - const t = math_scalar_Scalar.Repeat(tx, length * 2.0); - return length - Math.abs(t - length); - } - /** - * Interpolates between min and max with smoothing at the limits. - * - * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up - * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions. - * @param from from - * @param to to - * @param tx value - * @returns the smooth stepped value - */ - static SmoothStep(from, to, tx) { - let t = math_scalar_Scalar.Clamp(tx); - t = -2.0 * t * t * t + 3.0 * t * t; - return to * t + from * (1.0 - t); - } - /** - * Moves a value current towards target. - * - * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta. - * Negative values of maxDelta pushes the value away from target. - * @param current current value - * @param target target value - * @param maxDelta max distance to move - * @returns resulting value - */ - static MoveTowards(current, target, maxDelta) { - let result = 0; - if (Math.abs(target - current) <= maxDelta) { - result = target; - } - else { - result = current + math_scalar_Scalar.Sign(target - current) * maxDelta; - } - return result; - } - /** - * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees. - * - * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta - * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead. - * @param current current value - * @param target target value - * @param maxDelta max distance to move - * @returns resulting angle - */ - static MoveTowardsAngle(current, target, maxDelta) { - const num = math_scalar_Scalar.DeltaAngle(current, target); - let result = 0; - if (-maxDelta < num && num < maxDelta) { - result = target; - } - else { - target = current + num; - result = math_scalar_Scalar.MoveTowards(current, target, maxDelta); - } - return result; - } - /** - * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar. - * @param start start value - * @param end target value - * @param amount amount to lerp between - * @returns the lerped value - */ - static Lerp(start, end, amount) { - return start + (end - start) * amount; - } - /** - * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees. - * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees. - * @param start start value - * @param end target value - * @param amount amount to lerp between - * @returns the lerped value - */ - static LerpAngle(start, end, amount) { - let num = math_scalar_Scalar.Repeat(end - start, 360.0); - if (num > 180.0) { - num -= 360.0; - } - return start + num * math_scalar_Scalar.Clamp(amount); - } - /** - * Calculates the linear parameter t that produces the interpolant value within the range [a, b]. - * @param a start value - * @param b target value - * @param value value between a and b - * @returns the inverseLerp value - */ - static InverseLerp(a, b, value) { - let result = 0; - if (a != b) { - result = math_scalar_Scalar.Clamp((value - a) / (b - a)); - } - else { - result = 0.0; - } - return result; - } - /** - * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2". - * @see http://mathworld.wolfram.com/HermitePolynomial.html - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param amount defines the amount on the interpolation spline (between 0 and 1) - * @returns hermite result - */ - static Hermite(value1, tangent1, value2, tangent2, amount) { - const squared = amount * amount; - const cubed = amount * squared; - const part1 = 2.0 * cubed - 3.0 * squared + 1.0; - const part2 = -2.0 * cubed + 3.0 * squared; - const part3 = cubed - 2.0 * squared + amount; - const part4 = cubed - squared; - return value1 * part1 + value2 * part2 + tangent1 * part3 + tangent2 * part4; - } - /** - * Returns a new scalar which is the 1st derivative of the Hermite spline defined by the scalars "value1", "value2", "tangent1", "tangent2". - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @returns 1st derivative - */ - static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { - const t2 = time * time; - return (t2 - time) * 6 * value1 + (3 * t2 - 4 * time + 1) * tangent1 + (-t2 + time) * 6 * value2 + (3 * t2 - 2 * time) * tangent2; - } - /** - * Returns a random float number between and min and max values - * @param min min value of random - * @param max max value of random - * @returns random value - */ - static RandomRange(min, max) { - if (min === max) { - return min; - } - return Math.random() * (max - min) + min; - } - /** - * This function returns percentage of a number in a given range. - * - * RangeToPercent(40,20,60) will return 0.5 (50%) - * RangeToPercent(34,0,100) will return 0.34 (34%) - * @param number to convert to percentage - * @param min min range - * @param max max range - * @returns the percentage - */ - static RangeToPercent(number, min, max) { - return (number - min) / (max - min); - } - /** - * This function returns number that corresponds to the percentage in a given range. - * - * PercentToRange(0.34,0,100) will return 34. - * @param percent to convert to number - * @param min min range - * @param max max range - * @returns the number - */ - static PercentToRange(percent, min, max) { - return (max - min) * percent + min; - } - /** - * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians. - * @param angle The angle to normalize in radian. - * @returns The converted angle. - */ - static NormalizeRadians(angle) { - // More precise but slower version kept for reference. - // angle = angle % Tools.TwoPi; - // angle = (angle + Tools.TwoPi) % Tools.TwoPi; - //if (angle > Math.PI) { - // angle -= Tools.TwoPi; - //} - angle -= math_scalar_Scalar.TwoPi * Math.floor((angle + Math.PI) / math_scalar_Scalar.TwoPi); - return angle; - } - /** - * Returns the highest common factor of two integers. - * @param a first parameter - * @param b second parameter - * @returns HCF of a and b - */ - static HCF(a, b) { - const r = a % b; - if (r === 0) { - return b; - } - return math_scalar_Scalar.HCF(b, r); - } -} -/** - * Two pi constants convenient for computation. - */ -math_scalar_Scalar.TwoPi = Math.PI * 2; -//# sourceMappingURL=math.scalar.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.constants.js -/** - * Constant used to convert a value to gamma space - * @ignorenaming - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -const ToGammaSpace = 1 / 2.2; -/** - * Constant used to convert a value to linear space - * @ignorenaming - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -const ToLinearSpace = 2.2; -/** - * Constant Golden Ratio value in Babylon.js - * @ignorenaming - */ -const PHI = (1 + Math.sqrt(5)) / 2; -/** - * Constant used to define the minimal number value in Babylon.js - * @ignorenaming - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -const math_constants_Epsilon = 0.001; - -//# sourceMappingURL=math.constants.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/arrayTools.js -/* eslint-disable @typescript-eslint/naming-convention */ -/** - * Class containing a set of static utilities functions for arrays. - */ -class arrayTools_ArrayTools { - /** - * Returns an array of the given size filled with elements built from the given constructor and the parameters. - * @param size the number of element to construct and put in the array. - * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry. - * @returns a new array filled with new objects. - */ - static BuildArray(size, itemBuilder) { - const a = []; - for (let i = 0; i < size; ++i) { - a.push(itemBuilder()); - } - return a; - } - /** - * Returns a tuple of the given size filled with elements built from the given constructor and the parameters. - * @param size he number of element to construct and put in the tuple. - * @param itemBuilder a callback responsible for creating new instance of item. Called once per tuple entry. - * @returns a new tuple filled with new objects. - */ - static BuildTuple(size, itemBuilder) { - return arrayTools_ArrayTools.BuildArray(size, itemBuilder); - } -} -/** - * Observes a function and calls the given callback when it is called. - * @param object Defines the object the function to observe belongs to. - * @param functionName Defines the name of the function to observe. - * @param callback Defines the callback to call when the function is called. - * @returns A function to call to stop observing - */ -function _observeArrayfunction(object, functionName, callback) { - // Finds the function to observe - const oldFunction = object[functionName]; - if (typeof oldFunction !== "function") { - return null; - } - // Creates a new function that calls the callback and the old function - const newFunction = function () { - const previousLength = object.length; - const returnValue = newFunction.previous.apply(object, arguments); - callback(functionName, previousLength); - return returnValue; - }; - // Doublishly links the new function and the old function - oldFunction.next = newFunction; - newFunction.previous = oldFunction; - // Replaces the old function with the new function - object[functionName] = newFunction; - // Returns a function to disable the hook - return () => { - // Only unhook if the function is still hooked - const previous = newFunction.previous; - if (!previous) { - return; - } - // Finds the ref to the next function in the chain - const next = newFunction.next; - // If in the middle of the chain, link the previous and next functions - if (next) { - previous.next = next; - next.previous = previous; - } - // If at the end of the chain, remove the reference to the previous function - // and restore the previous function - else { - previous.next = undefined; - object[functionName] = previous; - } - // Lose reference to the previous and next functions - newFunction.next = undefined; - newFunction.previous = undefined; - }; -} -/** - * Defines the list of functions to proxy when observing an array. - * The scope is currently reduced to the common functions used in the render target render list and the scene cameras. - */ -const observedArrayFunctions = ["push", "splice", "pop", "shift", "unshift"]; -/** - * Observes an array and notifies the given observer when the array is modified. - * @param array Defines the array to observe - * @param callback Defines the function to call when the array is modified (in the limit of the observed array functions) - * @returns A function to call to stop observing the array - * @internal - */ -function _ObserveArray(array, callback) { - // Observes all the required array functions and stores the unhook functions - const unObserveFunctions = observedArrayFunctions.map((name) => { - return _observeArrayfunction(array, name, callback); - }); - // Returns a function that unhook all the observed functions - return () => { - unObserveFunctions.forEach((unObserveFunction) => { - unObserveFunction === null || unObserveFunction === void 0 ? void 0 : unObserveFunction(); - }); - }; -} -//# sourceMappingURL=arrayTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/typeStore.js -/** @internal */ -// eslint-disable-next-line @typescript-eslint/naming-convention -const _RegisteredTypes = {}; -/** - * @internal - */ -function RegisterClass(className, type) { - _RegisteredTypes[className] = type; -} -/** - * @internal - */ -function GetClass(fqdn) { - return _RegisteredTypes[fqdn]; -} -//# sourceMappingURL=typeStore.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/performanceConfigurator.js -/** @internal */ -class performanceConfigurator_PerformanceConfigurator { - /** - * @internal - */ - static SetMatrixPrecision(use64bits) { - performanceConfigurator_PerformanceConfigurator.MatrixTrackPrecisionChange = false; - if (use64bits && !performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits) { - if (performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices) { - for (let m = 0; m < performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices.length; ++m) { - const matrix = performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices[m]; - const values = matrix._m; - matrix._m = new Array(16); - for (let i = 0; i < 16; ++i) { - matrix._m[i] = values[i]; - } - } - } - } - performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits = use64bits; - performanceConfigurator_PerformanceConfigurator.MatrixCurrentType = performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits ? Array : Float32Array; - performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices = null; // reclaim some memory, as we don't need _TrackedMatrices anymore - } -} -/** @internal */ -performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits = false; -/** @internal */ -performanceConfigurator_PerformanceConfigurator.MatrixTrackPrecisionChange = true; -/** @internal */ -performanceConfigurator_PerformanceConfigurator.MatrixCurrentType = Float32Array; -/** @internal */ -performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices = []; -//# sourceMappingURL=performanceConfigurator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/engineStore.js - -/** - * The engine store class is responsible to hold all the instances of Engine and Scene created - * during the life time of the application. - */ -class engineStore_EngineStore { - /** - * Gets the latest created engine - */ - static get LastCreatedEngine() { - if (this.Instances.length === 0) { - return null; - } - return this.Instances[this.Instances.length - 1]; - } - /** - * Gets the latest created scene - */ - static get LastCreatedScene() { - return this._LastCreatedScene; - } -} -/** Gets the list of created engines */ -engineStore_EngineStore.Instances = new Array(); -/** - * Notifies when an engine was disposed. - * Mainly used for static/cache cleanup - */ -engineStore_EngineStore.OnEnginesDisposedObservable = new observable_Observable(); -/** @internal */ -engineStore_EngineStore._LastCreatedScene = null; -/** - * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded - * @ignorenaming - */ -engineStore_EngineStore.UseFallbackTexture = true; -/** - * Texture content used if a texture cannot loaded - * @ignorenaming - */ -engineStore_EngineStore.FallbackTexture = ""; -//# sourceMappingURL=engineStore.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.vector.js -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - -// eslint-disable-next-line @typescript-eslint/naming-convention -const _ExtractAsInt = (value) => { - return parseInt(value.toString().replace(/\W/g, "")); -}; -/** - * Class representing a vector containing 2 coordinates - * Example Playground - Overview - https://playground.babylonjs.com/#QYBWV4#9 - */ -class math_vector_Vector2 { - /** - * Creates a new Vector2 from the given x and y coordinates - * @param x defines the first coordinate - * @param y defines the second coordinate - */ - constructor( - /** defines the first coordinate */ - x = 0, - /** defines the second coordinate */ - y = 0) { - this.x = x; - this.y = y; - } - /** - * Gets a string with the Vector2 coordinates - * @returns a string with the Vector2 coordinates - */ - toString() { - return `{X: ${this.x} Y: ${this.y}}`; - } - /** - * Gets class name - * @returns the string "Vector2" - */ - getClassName() { - return "Vector2"; - } - /** - * Gets current vector hash code - * @returns the Vector2 hash code as a number - */ - getHashCode() { - const x = _ExtractAsInt(this.x); - const y = _ExtractAsInt(this.y); - let hash = x; - hash = (hash * 397) ^ y; - return hash; - } - // Operators - /** - * Sets the Vector2 coordinates in the given array or Float32Array from the given index. - * Example Playground https://playground.babylonjs.com/#QYBWV4#15 - * @param array defines the source array - * @param index defines the offset in source array - * @returns the current Vector2 - */ - toArray(array, index = 0) { - array[index] = this.x; - array[index + 1] = this.y; - return this; - } - /** - * Update the current vector from an array - * Example Playground https://playground.babylonjs.com/#QYBWV4#39 - * @param array defines the destination array - * @param index defines the offset in the destination array - * @returns the current Vector2 - */ - fromArray(array, index = 0) { - math_vector_Vector2.FromArrayToRef(array, index, this); - return this; - } - /** - * Copy the current vector to an array - * Example Playground https://playground.babylonjs.com/#QYBWV4#40 - * @returns a new array with 2 elements: the Vector2 coordinates. - */ - asArray() { - const result = new Array(); - this.toArray(result, 0); - return result; - } - /** - * Sets the Vector2 coordinates with the given Vector2 coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#24 - * @param source defines the source Vector2 - * @returns the current updated Vector2 - */ - copyFrom(source) { - this.x = source.x; - this.y = source.y; - return this; - } - /** - * Sets the Vector2 coordinates with the given floats - * Example Playground https://playground.babylonjs.com/#QYBWV4#25 - * @param x defines the first coordinate - * @param y defines the second coordinate - * @returns the current updated Vector2 - */ - copyFromFloats(x, y) { - this.x = x; - this.y = y; - return this; - } - /** - * Sets the Vector2 coordinates with the given floats - * Example Playground https://playground.babylonjs.com/#QYBWV4#62 - * @param x defines the first coordinate - * @param y defines the second coordinate - * @returns the current updated Vector2 - */ - set(x, y) { - return this.copyFromFloats(x, y); - } - /** - * Add another vector with the current one - * Example Playground https://playground.babylonjs.com/#QYBWV4#11 - * @param otherVector defines the other vector - * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates - */ - add(otherVector) { - return new this.constructor(this.x + otherVector.x, this.y + otherVector.y); - } - /** - * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#12 - * @param otherVector defines the other vector - * @param result defines the target vector - * @returns result input - */ - addToRef(otherVector, result) { - result.x = this.x + otherVector.x; - result.y = this.y + otherVector.y; - return result; - } - /** - * Set the Vector2 coordinates by adding the given Vector2 coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#13 - * @param otherVector defines the other vector - * @returns the current updated Vector2 - */ - addInPlace(otherVector) { - this.x += otherVector.x; - this.y += otherVector.y; - return this; - } - /** - * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#14 - * @param otherVector defines the other vector - * @returns a new Vector2 - */ - addVector3(otherVector) { - return new this.constructor(this.x + otherVector.x, this.y + otherVector.y); - } - /** - * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2 - * Example Playground https://playground.babylonjs.com/#QYBWV4#61 - * @param otherVector defines the other vector - * @returns a new Vector2 - */ - subtract(otherVector) { - return new this.constructor(this.x - otherVector.x, this.y - otherVector.y); - } - /** - * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates. - * Example Playground https://playground.babylonjs.com/#QYBWV4#63 - * @param otherVector defines the other vector - * @param result defines the target vector - * @returns result input - */ - subtractToRef(otherVector, result) { - result.x = this.x - otherVector.x; - result.y = this.y - otherVector.y; - return result; - } - /** - * Sets the current Vector2 coordinates by subtracting from it the given one coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#88 - * @param otherVector defines the other vector - * @returns the current updated Vector2 - */ - subtractInPlace(otherVector) { - this.x -= otherVector.x; - this.y -= otherVector.y; - return this; - } - /** - * Multiplies in place the current Vector2 coordinates by the given ones - * Example Playground https://playground.babylonjs.com/#QYBWV4#43 - * @param otherVector defines the other vector - * @returns the current updated Vector2 - */ - multiplyInPlace(otherVector) { - this.x *= otherVector.x; - this.y *= otherVector.y; - return this; - } - /** - * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#42 - * @param otherVector defines the other vector - * @returns a new Vector2 - */ - multiply(otherVector) { - return new this.constructor(this.x * otherVector.x, this.y * otherVector.y); - } - /** - * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#44 - * @param otherVector defines the other vector - * @param result defines the target vector - * @returns result input - */ - multiplyToRef(otherVector, result) { - result.x = this.x * otherVector.x; - result.y = this.y * otherVector.y; - return result; - } - /** - * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats - * Example Playground https://playground.babylonjs.com/#QYBWV4#89 - * @param x defines the first coordinate - * @param y defines the second coordinate - * @returns a new Vector2 - */ - multiplyByFloats(x, y) { - return new this.constructor(this.x * x, this.y * y); - } - /** - * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#27 - * @param otherVector defines the other vector - * @returns a new Vector2 - */ - divide(otherVector) { - return new this.constructor(this.x / otherVector.x, this.y / otherVector.y); - } - /** - * Sets the "result" coordinates with the Vector2 divided by the given one coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#30 - * @param otherVector defines the other vector - * @param result defines the target vector - * @returns result input - */ - divideToRef(otherVector, result) { - result.x = this.x / otherVector.x; - result.y = this.y / otherVector.y; - return result; - } - /** - * Divides the current Vector2 coordinates by the given ones - * Example Playground https://playground.babylonjs.com/#QYBWV4#28 - * @param otherVector defines the other vector - * @returns the current updated Vector2 - */ - divideInPlace(otherVector) { - return this.divideToRef(otherVector, this); - } - /** - * Gets a new Vector2 with current Vector2 negated coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#22 - * @returns a new Vector2 - */ - negate() { - return new this.constructor(-this.x, -this.y); - } - /** - * Negate this vector in place - * Example Playground https://playground.babylonjs.com/#QYBWV4#23 - * @returns this - */ - negateInPlace() { - this.x *= -1; - this.y *= -1; - return this; - } - /** - * Negate the current Vector2 and stores the result in the given vector "result" coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#41 - * @param result defines the Vector3 object where to store the result - * @returns the result - */ - negateToRef(result) { - return result.copyFromFloats(this.x * -1, this.y * -1); - } - /** - * Multiply the Vector2 coordinates by - * Example Playground https://playground.babylonjs.com/#QYBWV4#59 - * @param scale defines the scaling factor - * @returns the current updated Vector2 - */ - scaleInPlace(scale) { - this.x *= scale; - this.y *= scale; - return this; - } - /** - * Returns a new Vector2 scaled by "scale" from the current Vector2 - * Example Playground https://playground.babylonjs.com/#QYBWV4#52 - * @param scale defines the scaling factor - * @returns a new Vector2 - */ - scale(scale) { - const result = new this.constructor(0, 0); - this.scaleToRef(scale, result); - return result; - } - /** - * Scale the current Vector2 values by a factor to a given Vector2 - * Example Playground https://playground.babylonjs.com/#QYBWV4#57 - * @param scale defines the scale factor - * @param result defines the Vector2 object where to store the result - * @returns result input - */ - scaleToRef(scale, result) { - result.x = this.x * scale; - result.y = this.y * scale; - return result; - } - /** - * Scale the current Vector2 values by a factor and add the result to a given Vector2 - * Example Playground https://playground.babylonjs.com/#QYBWV4#58 - * @param scale defines the scale factor - * @param result defines the Vector2 object where to store the result - * @returns result input - */ - scaleAndAddToRef(scale, result) { - result.x += this.x * scale; - result.y += this.y * scale; - return result; - } - /** - * Gets a boolean if two vectors are equals - * Example Playground https://playground.babylonjs.com/#QYBWV4#31 - * @param otherVector defines the other vector - * @returns true if the given vector coordinates strictly equal the current Vector2 ones - */ - equals(otherVector) { - return otherVector && this.x === otherVector.x && this.y === otherVector.y; - } - /** - * Gets a boolean if two vectors are equals (using an epsilon value) - * Example Playground https://playground.babylonjs.com/#QYBWV4#32 - * @param otherVector defines the other vector - * @param epsilon defines the minimal distance to consider equality - * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon. - */ - equalsWithEpsilon(otherVector, epsilon = math_constants_Epsilon) { - return otherVector && math_scalar_Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && math_scalar_Scalar.WithinEpsilon(this.y, otherVector.y, epsilon); - } - /** - * Gets a new Vector2 from current Vector2 floored values - * Example Playground https://playground.babylonjs.com/#QYBWV4#35 - * eg (1.2, 2.31) returns (1, 2) - * @returns a new Vector2 - */ - floor() { - return new this.constructor(Math.floor(this.x), Math.floor(this.y)); - } - /** - * Gets a new Vector2 from current Vector2 fractional values - * Example Playground https://playground.babylonjs.com/#QYBWV4#34 - * eg (1.2, 2.31) returns (0.2, 0.31) - * @returns a new Vector2 - */ - fract() { - return new this.constructor(this.x - Math.floor(this.x), this.y - Math.floor(this.y)); - } - /** - * Rotate the current vector into a given result vector - * Example Playground https://playground.babylonjs.com/#QYBWV4#49 - * @param angle defines the rotation angle - * @param result defines the result vector where to store the rotated vector - * @returns result input - */ - rotateToRef(angle, result) { - const cos = Math.cos(angle); - const sin = Math.sin(angle); - const x = cos * this.x - sin * this.y; - const y = sin * this.x + cos * this.y; - result.x = x; - result.y = y; - return result; - } - // Properties - /** - * Gets the length of the vector - * @returns the vector length (float) - */ - length() { - return Math.sqrt(this.x * this.x + this.y * this.y); - } - /** - * Gets the vector squared length - * @returns the vector squared length (float) - */ - lengthSquared() { - return this.x * this.x + this.y * this.y; - } - // Methods - /** - * Normalize the vector - * Example Playground https://playground.babylonjs.com/#QYBWV4#48 - * @returns the current updated Vector2 - */ - normalize() { - math_vector_Vector2.NormalizeToRef(this, this); - return this; - } - /** - * Gets a new Vector2 copied from the Vector2 - * Example Playground https://playground.babylonjs.com/#QYBWV4#20 - * @returns a new Vector2 - */ - clone() { - return new this.constructor(this.x, this.y); - } - // Statics - /** - * Gets a new Vector2(0, 0) - * @returns a new Vector2 - */ - static Zero() { - return new math_vector_Vector2(0, 0); - } - /** - * Gets a new Vector2(1, 1) - * @returns a new Vector2 - */ - static One() { - return new math_vector_Vector2(1, 1); - } - /** - * Returns a new Vector2 with random values between min and max - * @param min the minimum random value - * @param max the maximum random value - * @returns a Vector2 with random values between min and max - */ - static Random(min = 0, max = 1) { - return new math_vector_Vector2(math_scalar_Scalar.RandomRange(min, max), math_scalar_Scalar.RandomRange(min, max)); - } - /** - * Gets a zero Vector2 that must not be updated - */ - static get ZeroReadOnly() { - return math_vector_Vector2._ZeroReadOnly; - } - /** - * Gets a new Vector2 set from the given index element of the given array - * Example Playground https://playground.babylonjs.com/#QYBWV4#79 - * @param array defines the data source - * @param offset defines the offset in the data source - * @returns a new Vector2 - */ - static FromArray(array, offset = 0) { - return new math_vector_Vector2(array[offset], array[offset + 1]); - } - /** - * Sets "result" from the given index element of the given array - * Example Playground https://playground.babylonjs.com/#QYBWV4#80 - * @param array defines the data source - * @param offset defines the offset in the data source - * @param result defines the target vector - * @returns result input - */ - static FromArrayToRef(array, offset, result) { - result.x = array[offset]; - result.y = array[offset + 1]; - return result; - } - /** - * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2 - * Example Playground https://playground.babylonjs.com/#QYBWV4#65 - * @param value1 defines 1st point of control - * @param value2 defines 2nd point of control - * @param value3 defines 3rd point of control - * @param value4 defines 4th point of control - * @param amount defines the interpolation factor - * @returns a new Vector2 - */ - static CatmullRom(value1, value2, value3, value4, amount) { - const squared = amount * amount; - const cubed = amount * squared; - const x = 0.5 * - (2.0 * value2.x + - (-value1.x + value3.x) * amount + - (2.0 * value1.x - 5.0 * value2.x + 4.0 * value3.x - value4.x) * squared + - (-value1.x + 3.0 * value2.x - 3.0 * value3.x + value4.x) * cubed); - const y = 0.5 * - (2.0 * value2.y + - (-value1.y + value3.y) * amount + - (2.0 * value1.y - 5.0 * value2.y + 4.0 * value3.y - value4.y) * squared + - (-value1.y + 3.0 * value2.y - 3.0 * value3.y + value4.y) * cubed); - return new value1.constructor(x, y); - } - /** - * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max". - * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate. - * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate - * Example Playground https://playground.babylonjs.com/#QYBWV4#76 - * @param value defines the value to clamp - * @param min defines the lower limit - * @param max defines the upper limit - * @returns a new Vector2 - */ - static Clamp(value, min, max) { - let x = value.x; - x = x > max.x ? max.x : x; - x = x < min.x ? min.x : x; - let y = value.y; - y = y > max.y ? max.y : y; - y = y < min.y ? min.y : y; - return new value.constructor(x, y); - } - /** - * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2" - * Example Playground https://playground.babylonjs.com/#QYBWV4#81 - * @param value1 defines the 1st control point - * @param tangent1 defines the outgoing tangent - * @param value2 defines the 2nd control point - * @param tangent2 defines the incoming tangent - * @param amount defines the interpolation factor - * @returns a new Vector2 - */ - static Hermite(value1, tangent1, value2, tangent2, amount) { - const squared = amount * amount; - const cubed = amount * squared; - const part1 = 2.0 * cubed - 3.0 * squared + 1.0; - const part2 = -2.0 * cubed + 3.0 * squared; - const part3 = cubed - 2.0 * squared + amount; - const part4 = cubed - squared; - const x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4; - const y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4; - return new value1.constructor(x, y); - } - /** - * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". - * Example Playground https://playground.babylonjs.com/#QYBWV4#82 - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @returns 1st derivative - */ - static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { - const result = new value1.constructor(); - this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); - return result; - } - /** - * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". - * Example Playground https://playground.babylonjs.com/#QYBWV4#83 - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @param result define where the derivative will be stored - * @returns result input - */ - static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { - const t2 = time * time; - result.x = (t2 - time) * 6 * value1.x + (3 * t2 - 4 * time + 1) * tangent1.x + (-t2 + time) * 6 * value2.x + (3 * t2 - 2 * time) * tangent2.x; - result.y = (t2 - time) * 6 * value1.y + (3 * t2 - 4 * time + 1) * tangent1.y + (-t2 + time) * 6 * value2.y + (3 * t2 - 2 * time) * tangent2.y; - return result; - } - /** - * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end". - * Example Playground https://playground.babylonjs.com/#QYBWV4#84 - * @param start defines the start vector - * @param end defines the end vector - * @param amount defines the interpolation factor - * @returns a new Vector2 - */ - static Lerp(start, end, amount) { - const x = start.x + (end.x - start.x) * amount; - const y = start.y + (end.y - start.y) * amount; - return new start.constructor(x, y); - } - /** - * Gets the dot product of the vector "left" and the vector "right" - * Example Playground https://playground.babylonjs.com/#QYBWV4#90 - * @param left defines first vector - * @param right defines second vector - * @returns the dot product (float) - */ - static Dot(left, right) { - return left.x * right.x + left.y * right.y; - } - /** - * Returns a new Vector2 equal to the normalized given vector - * Example Playground https://playground.babylonjs.com/#QYBWV4#46 - * @param vector defines the vector to normalize - * @returns a new Vector2 - */ - static Normalize(vector) { - const newVector = new vector.constructor(); - this.NormalizeToRef(vector, newVector); - return newVector; - } - /** - * Normalize a given vector into a second one - * Example Playground https://playground.babylonjs.com/#QYBWV4#50 - * @param vector defines the vector to normalize - * @param result defines the vector where to store the result - * @returns result input - */ - static NormalizeToRef(vector, result) { - const len = vector.length(); - if (len === 0) { - return result; - } - result.x = vector.x / len; - result.y = vector.y / len; - return result; - } - /** - * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors - * Example Playground https://playground.babylonjs.com/#QYBWV4#86 - * @param left defines 1st vector - * @param right defines 2nd vector - * @returns a new Vector2 - */ - static Minimize(left, right) { - const x = left.x < right.x ? left.x : right.x; - const y = left.y < right.y ? left.y : right.y; - return new left.constructor(x, y); - } - /** - * Gets a new Vector2 set with the maximal coordinate values from the "left" and "right" vectors - * Example Playground https://playground.babylonjs.com/#QYBWV4#86 - * @param left defines 1st vector - * @param right defines 2nd vector - * @returns a new Vector2 - */ - static Maximize(left, right) { - const x = left.x > right.x ? left.x : right.x; - const y = left.y > right.y ? left.y : right.y; - return new left.constructor(x, y); - } - /** - * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix - * Example Playground https://playground.babylonjs.com/#QYBWV4#17 - * @param vector defines the vector to transform - * @param transformation defines the matrix to apply - * @returns a new Vector2 - */ - static Transform(vector, transformation) { - const result = new vector.constructor(); - math_vector_Vector2.TransformToRef(vector, transformation, result); - return result; - } - /** - * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates - * Example Playground https://playground.babylonjs.com/#QYBWV4#19 - * @param vector defines the vector to transform - * @param transformation defines the matrix to apply - * @param result defines the target vector - * @returns result input - */ - static TransformToRef(vector, transformation, result) { - const m = transformation.m; - const x = vector.x * m[0] + vector.y * m[4] + m[12]; - const y = vector.x * m[1] + vector.y * m[5] + m[13]; - result.x = x; - result.y = y; - return result; - } - /** - * Determines if a given vector is included in a triangle - * Example Playground https://playground.babylonjs.com/#QYBWV4#87 - * @param p defines the vector to test - * @param p0 defines 1st triangle point - * @param p1 defines 2nd triangle point - * @param p2 defines 3rd triangle point - * @returns true if the point "p" is in the triangle defined by the vectors "p0", "p1", "p2" - */ - static PointInTriangle(p, p0, p1, p2) { - const a = (1 / 2) * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y); - const sign = a < 0 ? -1 : 1; - const s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign; - const t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign; - return s > 0 && t > 0 && s + t < 2 * a * sign; - } - /** - * Gets the distance between the vectors "value1" and "value2" - * Example Playground https://playground.babylonjs.com/#QYBWV4#71 - * @param value1 defines first vector - * @param value2 defines second vector - * @returns the distance between vectors - */ - static Distance(value1, value2) { - return Math.sqrt(math_vector_Vector2.DistanceSquared(value1, value2)); - } - /** - * Returns the squared distance between the vectors "value1" and "value2" - * Example Playground https://playground.babylonjs.com/#QYBWV4#72 - * @param value1 defines first vector - * @param value2 defines second vector - * @returns the squared distance between vectors - */ - static DistanceSquared(value1, value2) { - const x = value1.x - value2.x; - const y = value1.y - value2.y; - return x * x + y * y; - } - /** - * Gets a new Vector2 located at the center of the vectors "value1" and "value2" - * Example Playground https://playground.babylonjs.com/#QYBWV4#86 - * Example Playground https://playground.babylonjs.com/#QYBWV4#66 - * @param value1 defines first vector - * @param value2 defines second vector - * @returns a new Vector2 - */ - static Center(value1, value2) { - const result = new value1.constructor(); - return math_vector_Vector2.CenterToRef(value1, value2, result); - } - /** - * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref" - * Example Playground https://playground.babylonjs.com/#QYBWV4#66 - * @param value1 defines first vector - * @param value2 defines second vector - * @param ref defines third vector - * @returns ref - */ - static CenterToRef(value1, value2, ref) { - return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2); - } - /** - * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB". - * Example Playground https://playground.babylonjs.com/#QYBWV4#77 - * @param p defines the middle point - * @param segA defines one point of the segment - * @param segB defines the other point of the segment - * @returns the shortest distance - */ - static DistanceOfPointFromSegment(p, segA, segB) { - const l2 = math_vector_Vector2.DistanceSquared(segA, segB); - if (l2 === 0.0) { - return math_vector_Vector2.Distance(p, segA); - } - const v = segB.subtract(segA); - const t = Math.max(0, Math.min(1, math_vector_Vector2.Dot(p.subtract(segA), v) / l2)); - const proj = segA.add(v.multiplyByFloats(t, t)); - return math_vector_Vector2.Distance(p, proj); - } -} -math_vector_Vector2._ZeroReadOnly = math_vector_Vector2.Zero(); -/** - * Class used to store (x,y,z) vector representation - * A Vector3 is the main object used in 3D geometry - * It can represent either the coordinates of a point the space, either a direction - * Reminder: js uses a left handed forward facing system - * Example Playground - Overview - https://playground.babylonjs.com/#R1F8YU - */ -class math_vector_Vector3 { - /** Gets or sets the x coordinate */ - get x() { - return this._x; - } - set x(value) { - this._x = value; - this._isDirty = true; - } - /** Gets or sets the y coordinate */ - get y() { - return this._y; - } - set y(value) { - this._y = value; - this._isDirty = true; - } - /** Gets or sets the z coordinate */ - get z() { - return this._z; - } - set z(value) { - this._z = value; - this._isDirty = true; - } - /** - * Creates a new Vector3 object from the given x, y, z (floats) coordinates. - * @param x defines the first coordinates (on X axis) - * @param y defines the second coordinates (on Y axis) - * @param z defines the third coordinates (on Z axis) - */ - constructor(x = 0, y = 0, z = 0) { - /** @internal */ - this._isDirty = true; - this._x = x; - this._y = y; - this._z = z; - } - /** - * Creates a string representation of the Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#67 - * @returns a string with the Vector3 coordinates. - */ - toString() { - return `{X: ${this._x} Y: ${this._y} Z: ${this._z}}`; - } - /** - * Gets the class name - * @returns the string "Vector3" - */ - getClassName() { - return "Vector3"; - } - /** - * Creates the Vector3 hash code - * @returns a number which tends to be unique between Vector3 instances - */ - getHashCode() { - const x = _ExtractAsInt(this._x); - const y = _ExtractAsInt(this._y); - const z = _ExtractAsInt(this._z); - let hash = x; - hash = (hash * 397) ^ y; - hash = (hash * 397) ^ z; - return hash; - } - // Operators - /** - * Creates an array containing three elements : the coordinates of the Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#10 - * @returns a new array of numbers - */ - asArray() { - const result = []; - this.toArray(result, 0); - return result; - } - /** - * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#65 - * @param array defines the destination array - * @param index defines the offset in the destination array - * @returns the current Vector3 - */ - toArray(array, index = 0) { - array[index] = this._x; - array[index + 1] = this._y; - array[index + 2] = this._z; - return this; - } - /** - * Update the current vector from an array - * Example Playground https://playground.babylonjs.com/#R1F8YU#24 - * @param array defines the destination array - * @param index defines the offset in the destination array - * @returns the current Vector3 - */ - fromArray(array, index = 0) { - math_vector_Vector3.FromArrayToRef(array, index, this); - return this; - } - /** - * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation) - * Example Playground https://playground.babylonjs.com/#R1F8YU#66 - * @returns a new Quaternion object, computed from the Vector3 coordinates - */ - toQuaternion() { - return math_vector_Quaternion.RotationYawPitchRoll(this._y, this._x, this._z); - } - /** - * Adds the given vector to the current Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#4 - * @param otherVector defines the second operand - * @returns the current updated Vector3 - */ - addInPlace(otherVector) { - return this.addInPlaceFromFloats(otherVector._x, otherVector._y, otherVector._z); - } - /** - * Adds the given coordinates to the current Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#5 - * @param x defines the x coordinate of the operand - * @param y defines the y coordinate of the operand - * @param z defines the z coordinate of the operand - * @returns the current updated Vector3 - */ - addInPlaceFromFloats(x, y, z) { - this._x += x; - this._y += y; - this._z += z; - this._isDirty = true; - return this; - } - /** - * Gets a new Vector3, result of the addition the current Vector3 and the given vector - * Example Playground https://playground.babylonjs.com/#R1F8YU#3 - * @param otherVector defines the second operand - * @returns the resulting Vector3 - */ - add(otherVector) { - return new this.constructor(this._x + otherVector._x, this._y + otherVector._y, this._z + otherVector._z); - } - /** - * Adds the current Vector3 to the given one and stores the result in the vector "result" - * Example Playground https://playground.babylonjs.com/#R1F8YU#6 - * @param otherVector defines the second operand - * @param result defines the Vector3 object where to store the result - * @returns the result - */ - addToRef(otherVector, result) { - return result.copyFromFloats(this._x + otherVector._x, this._y + otherVector._y, this._z + otherVector._z); - } - /** - * Subtract the given vector from the current Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#61 - * @param otherVector defines the second operand - * @returns the current updated Vector3 - */ - subtractInPlace(otherVector) { - this._x -= otherVector._x; - this._y -= otherVector._y; - this._z -= otherVector._z; - this._isDirty = true; - return this; - } - /** - * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#60 - * @param otherVector defines the second operand - * @returns the resulting Vector3 - */ - subtract(otherVector) { - return new this.constructor(this._x - otherVector._x, this._y - otherVector._y, this._z - otherVector._z); - } - /** - * Subtracts the given vector from the current Vector3 and stores the result in the vector "result". - * Example Playground https://playground.babylonjs.com/#R1F8YU#63 - * @param otherVector defines the second operand - * @param result defines the Vector3 object where to store the result - * @returns the result - */ - subtractToRef(otherVector, result) { - return this.subtractFromFloatsToRef(otherVector._x, otherVector._y, otherVector._z, result); - } - /** - * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates - * Example Playground https://playground.babylonjs.com/#R1F8YU#62 - * @param x defines the x coordinate of the operand - * @param y defines the y coordinate of the operand - * @param z defines the z coordinate of the operand - * @returns the resulting Vector3 - */ - subtractFromFloats(x, y, z) { - return new this.constructor(this._x - x, this._y - y, this._z - z); - } - /** - * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result - * Example Playground https://playground.babylonjs.com/#R1F8YU#64 - * @param x defines the x coordinate of the operand - * @param y defines the y coordinate of the operand - * @param z defines the z coordinate of the operand - * @param result defines the Vector3 object where to store the result - * @returns the result - */ - subtractFromFloatsToRef(x, y, z, result) { - return result.copyFromFloats(this._x - x, this._y - y, this._z - z); - } - /** - * Gets a new Vector3 set with the current Vector3 negated coordinates - * Example Playground https://playground.babylonjs.com/#R1F8YU#35 - * @returns a new Vector3 - */ - negate() { - return new this.constructor(-this._x, -this._y, -this._z); - } - /** - * Negate this vector in place - * Example Playground https://playground.babylonjs.com/#R1F8YU#36 - * @returns this - */ - negateInPlace() { - this._x *= -1; - this._y *= -1; - this._z *= -1; - this._isDirty = true; - return this; - } - /** - * Negate the current Vector3 and stores the result in the given vector "result" coordinates - * Example Playground https://playground.babylonjs.com/#R1F8YU#37 - * @param result defines the Vector3 object where to store the result - * @returns the result - */ - negateToRef(result) { - return result.copyFromFloats(this._x * -1, this._y * -1, this._z * -1); - } - /** - * Multiplies the Vector3 coordinates by the float "scale" - * Example Playground https://playground.babylonjs.com/#R1F8YU#56 - * @param scale defines the multiplier factor - * @returns the current updated Vector3 - */ - scaleInPlace(scale) { - this._x *= scale; - this._y *= scale; - this._z *= scale; - this._isDirty = true; - return this; - } - /** - * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale" - * Example Playground https://playground.babylonjs.com/#R1F8YU#53 - * @param scale defines the multiplier factor - * @returns a new Vector3 - */ - scale(scale) { - return new this.constructor(this._x * scale, this._y * scale, this._z * scale); - } - /** - * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates - * Example Playground https://playground.babylonjs.com/#R1F8YU#57 - * @param scale defines the multiplier factor - * @param result defines the Vector3 object where to store the result - * @returns the result - */ - scaleToRef(scale, result) { - return result.copyFromFloats(this._x * scale, this._y * scale, this._z * scale); - } - /** - * Creates a vector normal (perpendicular) to the current Vector3 and stores the result in the given vector - * Out of the infinite possibilities the normal chosen is the one formed by rotating the current vector - * 90 degrees about an axis which lies perpendicular to the current vector - * and its projection on the xz plane. In the case of a current vector in the xz plane - * the normal is calculated to be along the y axis. - * Example Playground https://playground.babylonjs.com/#R1F8YU#230 - * Example Playground https://playground.babylonjs.com/#R1F8YU#231 - * @param result defines the Vector3 object where to store the resultant normal - * returns the result - */ - getNormalToRef(result) { - /** - * Calculates the spherical coordinates of the current vector - * so saves on memory rather than importing whole Spherical Class - */ - const radius = this.length(); - let theta = Math.acos(this.y / radius); - const phi = Math.atan2(this.z, this.x); - //makes angle 90 degs to current vector - if (theta > Math.PI / 2) { - theta -= Math.PI / 2; - } - else { - theta += Math.PI / 2; - } - //Calculates resutant normal vector from spherical coordinate of perpendicular vector - const x = radius * Math.sin(theta) * Math.cos(phi); - const y = radius * Math.cos(theta); - const z = radius * Math.sin(theta) * Math.sin(phi); - result.set(x, y, z); - return result; - } - /** - * Rotates the vector using the given unit quaternion and stores the new vector in result - * Example Playground https://playground.babylonjs.com/#R1F8YU#9 - * @param q the unit quaternion representing the rotation - * @param result the output vector - * @returns the result - */ - applyRotationQuaternionToRef(q, result) { - // Derived from https://raw.org/proof/vector-rotation-using-quaternions/ - const vx = this._x, vy = this._y, vz = this._z; - const qx = q._x, qy = q._y, qz = q._z, qw = q._w; - // t = 2q x v - const tx = 2 * (qy * vz - qz * vy); - const ty = 2 * (qz * vx - qx * vz); - const tz = 2 * (qx * vy - qy * vx); - // v + w t + q x t - result._x = vx + qw * tx + qy * tz - qz * ty; - result._y = vy + qw * ty + qz * tx - qx * tz; - result._z = vz + qw * tz + qx * ty - qy * tx; - result._isDirty = true; - return result; - } - /** - * Rotates the vector in place using the given unit quaternion - * Example Playground https://playground.babylonjs.com/#R1F8YU#8 - * @param q the unit quaternion representing the rotation - * @returns the current updated Vector3 - */ - applyRotationQuaternionInPlace(q) { - return this.applyRotationQuaternionToRef(q, this); - } - /** - * Rotates the vector using the given unit quaternion and returns the new vector - * Example Playground https://playground.babylonjs.com/#R1F8YU#7 - * @param q the unit quaternion representing the rotation - * @returns a new Vector3 - */ - applyRotationQuaternion(q) { - return this.applyRotationQuaternionToRef(q, new this.constructor()); - } - /** - * Scale the current Vector3 values by a factor and add the result to a given Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#55 - * @param scale defines the scale factor - * @param result defines the Vector3 object where to store the result - * @returns result input - */ - scaleAndAddToRef(scale, result) { - return result.addInPlaceFromFloats(this._x * scale, this._y * scale, this._z * scale); - } - /** - * Projects the current point Vector3 to a plane along a ray starting from a specified origin and passing through the current point Vector3. - * Example Playground https://playground.babylonjs.com/#R1F8YU#48 - * @param plane defines the plane to project to - * @param origin defines the origin of the projection ray - * @returns the projected vector3 - */ - projectOnPlane(plane, origin) { - const result = new this.constructor(); - this.projectOnPlaneToRef(plane, origin, result); - return result; - } - /** - * Projects the current point Vector3 to a plane along a ray starting from a specified origin and passing through the current point Vector3. - * Example Playground https://playground.babylonjs.com/#R1F8YU#49 - * @param plane defines the plane to project to - * @param origin defines the origin of the projection ray - * @param result defines the Vector3 where to store the result - * @returns result input - */ - projectOnPlaneToRef(plane, origin, result) { - const n = plane.normal; - const d = plane.d; - const V = MathTmp.Vector3[0]; - // ray direction - this.subtractToRef(origin, V); - V.normalize(); - const denom = math_vector_Vector3.Dot(V, n); - //When the ray is close to parallel to the plane return infinity vector - if (Math.abs(denom) < Math.pow(10, -10)) { - result.setAll(Infinity); - } - else { - const t = -(math_vector_Vector3.Dot(origin, n) + d) / denom; - // P = P0 + t*V - const scaledV = V.scaleInPlace(t); - origin.addToRef(scaledV, result); - } - return result; - } - /** - * Returns true if the current Vector3 and the given vector coordinates are strictly equal - * Example Playground https://playground.babylonjs.com/#R1F8YU#19 - * @param otherVector defines the second operand - * @returns true if both vectors are equals - */ - equals(otherVector) { - return otherVector && this._x === otherVector._x && this._y === otherVector._y && this._z === otherVector._z; - } - /** - * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon - * Example Playground https://playground.babylonjs.com/#R1F8YU#21 - * @param otherVector defines the second operand - * @param epsilon defines the minimal distance to define values as equals - * @returns true if both vectors are distant less than epsilon - */ - equalsWithEpsilon(otherVector, epsilon = math_constants_Epsilon) { - return (otherVector && - math_scalar_Scalar.WithinEpsilon(this._x, otherVector._x, epsilon) && - math_scalar_Scalar.WithinEpsilon(this._y, otherVector._y, epsilon) && - math_scalar_Scalar.WithinEpsilon(this._z, otherVector._z, epsilon)); - } - /** - * Returns true if the current Vector3 coordinates equals the given floats - * Example Playground https://playground.babylonjs.com/#R1F8YU#20 - * @param x defines the x coordinate of the operand - * @param y defines the y coordinate of the operand - * @param z defines the z coordinate of the operand - * @returns true if both vectors are equal - */ - equalsToFloats(x, y, z) { - return this._x === x && this._y === y && this._z === z; - } - /** - * Multiplies the current Vector3 coordinates by the given ones - * Example Playground https://playground.babylonjs.com/#R1F8YU#32 - * @param otherVector defines the second operand - * @returns the current updated Vector3 - */ - multiplyInPlace(otherVector) { - this._x *= otherVector._x; - this._y *= otherVector._y; - this._z *= otherVector._z; - this._isDirty = true; - return this; - } - /** - * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector - * Example Playground https://playground.babylonjs.com/#R1F8YU#31 - * @param otherVector defines the second operand - * @returns the new Vector3 - */ - multiply(otherVector) { - return this.multiplyByFloats(otherVector._x, otherVector._y, otherVector._z); - } - /** - * Multiplies the current Vector3 by the given one and stores the result in the given vector "result" - * Example Playground https://playground.babylonjs.com/#R1F8YU#33 - * @param otherVector defines the second operand - * @param result defines the Vector3 object where to store the result - * @returns the result - */ - multiplyToRef(otherVector, result) { - return result.copyFromFloats(this._x * otherVector._x, this._y * otherVector._y, this._z * otherVector._z); - } - /** - * Returns a new Vector3 set with the result of the multiplication of the current Vector3 coordinates by the given floats - * Example Playground https://playground.babylonjs.com/#R1F8YU#34 - * @param x defines the x coordinate of the operand - * @param y defines the y coordinate of the operand - * @param z defines the z coordinate of the operand - * @returns the new Vector3 - */ - multiplyByFloats(x, y, z) { - return new this.constructor(this._x * x, this._y * y, this._z * z); - } - /** - * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones - * Example Playground https://playground.babylonjs.com/#R1F8YU#16 - * @param otherVector defines the second operand - * @returns the new Vector3 - */ - divide(otherVector) { - return new this.constructor(this._x / otherVector._x, this._y / otherVector._y, this._z / otherVector._z); - } - /** - * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result" - * Example Playground https://playground.babylonjs.com/#R1F8YU#18 - * @param otherVector defines the second operand - * @param result defines the Vector3 object where to store the result - * @returns the result - */ - divideToRef(otherVector, result) { - return result.copyFromFloats(this._x / otherVector._x, this._y / otherVector._y, this._z / otherVector._z); - } - /** - * Divides the current Vector3 coordinates by the given ones. - * Example Playground https://playground.babylonjs.com/#R1F8YU#17 - * @param otherVector defines the second operand - * @returns the current updated Vector3 - */ - divideInPlace(otherVector) { - return this.divideToRef(otherVector, this); - } - /** - * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones - * Example Playground https://playground.babylonjs.com/#R1F8YU#29 - * @param other defines the second operand - * @returns the current updated Vector3 - */ - minimizeInPlace(other) { - return this.minimizeInPlaceFromFloats(other._x, other._y, other._z); - } - /** - * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones. - * Example Playground https://playground.babylonjs.com/#R1F8YU#27 - * @param other defines the second operand - * @returns the current updated Vector3 - */ - maximizeInPlace(other) { - return this.maximizeInPlaceFromFloats(other._x, other._y, other._z); - } - /** - * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates - * Example Playground https://playground.babylonjs.com/#R1F8YU#30 - * @param x defines the x coordinate of the operand - * @param y defines the y coordinate of the operand - * @param z defines the z coordinate of the operand - * @returns the current updated Vector3 - */ - minimizeInPlaceFromFloats(x, y, z) { - if (x < this._x) { - this.x = x; - } - if (y < this._y) { - this.y = y; - } - if (z < this._z) { - this.z = z; - } - return this; - } - /** - * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates. - * Example Playground https://playground.babylonjs.com/#R1F8YU#28 - * @param x defines the x coordinate of the operand - * @param y defines the y coordinate of the operand - * @param z defines the z coordinate of the operand - * @returns the current updated Vector3 - */ - maximizeInPlaceFromFloats(x, y, z) { - if (x > this._x) { - this.x = x; - } - if (y > this._y) { - this.y = y; - } - if (z > this._z) { - this.z = z; - } - return this; - } - /** - * Due to float precision, scale of a mesh could be uniform but float values are off by a small fraction - * Check if is non uniform within a certain amount of decimal places to account for this - * @param epsilon the amount the values can differ - * @returns if the the vector is non uniform to a certain number of decimal places - */ - isNonUniformWithinEpsilon(epsilon) { - const absX = Math.abs(this._x); - const absY = Math.abs(this._y); - if (!math_scalar_Scalar.WithinEpsilon(absX, absY, epsilon)) { - return true; - } - const absZ = Math.abs(this._z); - if (!math_scalar_Scalar.WithinEpsilon(absX, absZ, epsilon)) { - return true; - } - if (!math_scalar_Scalar.WithinEpsilon(absY, absZ, epsilon)) { - return true; - } - return false; - } - /** - * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same - */ - get isNonUniform() { - const absX = Math.abs(this._x); - const absY = Math.abs(this._y); - if (absX !== absY) { - return true; - } - const absZ = Math.abs(this._z); - if (absX !== absZ) { - return true; - } - return false; - } - /** - * Gets a new Vector3 from current Vector3 floored values - * Example Playground https://playground.babylonjs.com/#R1F8YU#22 - * @returns a new Vector3 - */ - floor() { - return new this.constructor(Math.floor(this._x), Math.floor(this._y), Math.floor(this._z)); - } - /** - * Gets a new Vector3 from current Vector3 fractional values - * Example Playground https://playground.babylonjs.com/#R1F8YU#23 - * @returns a new Vector3 - */ - fract() { - return new this.constructor(this._x - Math.floor(this._x), this._y - Math.floor(this._y), this._z - Math.floor(this._z)); - } - // Properties - /** - * Gets the length of the Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#25 - * @returns the length of the Vector3 - */ - length() { - return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z); - } - /** - * Gets the squared length of the Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#26 - * @returns squared length of the Vector3 - */ - lengthSquared() { - return this._x * this._x + this._y * this._y + this._z * this._z; - } - /** - * Gets a boolean indicating if the vector contains a zero in one of its components - * Example Playground https://playground.babylonjs.com/#R1F8YU#1 - */ - get hasAZeroComponent() { - return this._x * this._y * this._z === 0; - } - /** - * Normalize the current Vector3. - * Please note that this is an in place operation. - * Example Playground https://playground.babylonjs.com/#R1F8YU#122 - * @returns the current updated Vector3 - */ - normalize() { - return this.normalizeFromLength(this.length()); - } - /** - * Reorders the x y z properties of the vector in place - * Example Playground https://playground.babylonjs.com/#R1F8YU#44 - * @param order new ordering of the properties (eg. for vector 1,2,3 with "ZYX" will produce 3,2,1) - * @returns the current updated vector - */ - reorderInPlace(order) { - order = order.toLowerCase(); - if (order === "xyz") { - return this; - } - MathTmp.Vector3[0].copyFrom(this); - ["x", "y", "z"].forEach((val, i) => { - this[val] = MathTmp.Vector3[0][order[i]]; - }); - return this; - } - /** - * Rotates the vector around 0,0,0 by a quaternion - * Example Playground https://playground.babylonjs.com/#R1F8YU#47 - * @param quaternion the rotation quaternion - * @param result vector to store the result - * @returns the resulting vector - */ - rotateByQuaternionToRef(quaternion, result) { - quaternion.toRotationMatrix(MathTmp.Matrix[0]); - math_vector_Vector3.TransformCoordinatesToRef(this, MathTmp.Matrix[0], result); - return result; - } - /** - * Rotates a vector around a given point - * Example Playground https://playground.babylonjs.com/#R1F8YU#46 - * @param quaternion the rotation quaternion - * @param point the point to rotate around - * @param result vector to store the result - * @returns the resulting vector - */ - rotateByQuaternionAroundPointToRef(quaternion, point, result) { - this.subtractToRef(point, MathTmp.Vector3[0]); - MathTmp.Vector3[0].rotateByQuaternionToRef(quaternion, MathTmp.Vector3[0]); - point.addToRef(MathTmp.Vector3[0], result); - return result; - } - /** - * Returns a new Vector3 as the cross product of the current vector and the "other" one - * The cross product is then orthogonal to both current and "other" - * Example Playground https://playground.babylonjs.com/#R1F8YU#14 - * @param other defines the right operand - * @returns the cross product - */ - cross(other) { - const result = new this.constructor(); - return math_vector_Vector3.CrossToRef(this, other, result); - } - /** - * Normalize the current Vector3 with the given input length. - * Please note that this is an in place operation. - * Example Playground https://playground.babylonjs.com/#R1F8YU#123 - * @param len the length of the vector - * @returns the current updated Vector3 - */ - normalizeFromLength(len) { - if (len === 0 || len === 1.0) { - return this; - } - return this.scaleInPlace(1.0 / len); - } - /** - * Normalize the current Vector3 to a new vector - * Example Playground https://playground.babylonjs.com/#R1F8YU#124 - * @returns the new Vector3 - */ - normalizeToNew() { - const normalized = new this.constructor(0, 0, 0); - this.normalizeToRef(normalized); - return normalized; - } - /** - * Normalize the current Vector3 to the reference - * Example Playground https://playground.babylonjs.com/#R1F8YU#125 - * @param reference define the Vector3 to update - * @returns the updated Vector3 - */ - normalizeToRef(reference) { - const len = this.length(); - if (len === 0 || len === 1.0) { - return reference.copyFromFloats(this._x, this._y, this._z); - } - return this.scaleToRef(1.0 / len, reference); - } - /** - * Creates a new Vector3 copied from the current Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#11 - * @returns the new Vector3 - */ - clone() { - return new this.constructor(this._x, this._y, this._z); - } - /** - * Copies the given vector coordinates to the current Vector3 ones - * Example Playground https://playground.babylonjs.com/#R1F8YU#12 - * @param source defines the source Vector3 - * @returns the current updated Vector3 - */ - copyFrom(source) { - return this.copyFromFloats(source._x, source._y, source._z); - } - /** - * Copies the given floats to the current Vector3 coordinates - * Example Playground https://playground.babylonjs.com/#R1F8YU#13 - * @param x defines the x coordinate of the operand - * @param y defines the y coordinate of the operand - * @param z defines the z coordinate of the operand - * @returns the current updated Vector3 - */ - copyFromFloats(x, y, z) { - this._x = x; - this._y = y; - this._z = z; - this._isDirty = true; - return this; - } - /** - * Copies the given floats to the current Vector3 coordinates - * Example Playground https://playground.babylonjs.com/#R1F8YU#58 - * @param x defines the x coordinate of the operand - * @param y defines the y coordinate of the operand - * @param z defines the z coordinate of the operand - * @returns the current updated Vector3 - */ - set(x, y, z) { - return this.copyFromFloats(x, y, z); - } - /** - * Copies the given float to the current Vector3 coordinates - * Example Playground https://playground.babylonjs.com/#R1F8YU#59 - * @param v defines the x, y and z coordinates of the operand - * @returns the current updated Vector3 - */ - setAll(v) { - this._x = this._y = this._z = v; - this._isDirty = true; - return this; - } - // Statics - /** - * Get the clip factor between two vectors - * Example Playground https://playground.babylonjs.com/#R1F8YU#126 - * @param vector0 defines the first operand - * @param vector1 defines the second operand - * @param axis defines the axis to use - * @param size defines the size along the axis - * @returns the clip factor - */ - static GetClipFactor(vector0, vector1, axis, size) { - const d0 = math_vector_Vector3.Dot(vector0, axis) - size; - const d1 = math_vector_Vector3.Dot(vector1, axis) - size; - const s = d0 / (d0 - d1); - return s; - } - /** - * Get angle between two vectors - * Example Playground https://playground.babylonjs.com/#R1F8YU#86 - * @param vector0 the starting point - * @param vector1 the ending point - * @param normal direction of the normal - * @returns the angle between vector0 and vector1 - */ - static GetAngleBetweenVectors(vector0, vector1, normal) { - const v0 = vector0.normalizeToRef(MathTmp.Vector3[1]); - const v1 = vector1.normalizeToRef(MathTmp.Vector3[2]); - let dot = math_vector_Vector3.Dot(v0, v1); - // Vectors are normalized so dot will be in [-1, 1] (aside precision issues enough to break the result which explains the below clamp) - dot = math_scalar_Scalar.Clamp(dot, -1, 1); - const angle = Math.acos(dot); - const n = MathTmp.Vector3[3]; - math_vector_Vector3.CrossToRef(v0, v1, n); - if (math_vector_Vector3.Dot(n, normal) > 0) { - return isNaN(angle) ? 0 : angle; - } - return isNaN(angle) ? -Math.PI : -Math.acos(dot); - } - /** - * Get angle between two vectors projected on a plane - * Example Playground https://playground.babylonjs.com/#R1F8YU#87 - * Expectation compute time: 0.01 ms (median) and 0.02 ms (percentile 95%) - * @param vector0 angle between vector0 and vector1 - * @param vector1 angle between vector0 and vector1 - * @param normal Normal of the projection plane - * @returns the angle in radians (float) between vector0 and vector1 projected on the plane with the specified normal - */ - static GetAngleBetweenVectorsOnPlane(vector0, vector1, normal) { - MathTmp.Vector3[0].copyFrom(vector0); - const v0 = MathTmp.Vector3[0]; - MathTmp.Vector3[1].copyFrom(vector1); - const v1 = MathTmp.Vector3[1]; - MathTmp.Vector3[2].copyFrom(normal); - const vNormal = MathTmp.Vector3[2]; - const right = MathTmp.Vector3[3]; - const forward = MathTmp.Vector3[4]; - v0.normalize(); - v1.normalize(); - vNormal.normalize(); - math_vector_Vector3.CrossToRef(vNormal, v0, right); - math_vector_Vector3.CrossToRef(right, vNormal, forward); - const angle = Math.atan2(math_vector_Vector3.Dot(v1, right), math_vector_Vector3.Dot(v1, forward)); - return math_scalar_Scalar.NormalizeRadians(angle); - } - /** - * Gets the rotation that aligns the roll axis (Y) to the line joining the start point to the target point and stores it in the ref Vector3 - * Example PG https://playground.babylonjs.com/#R1F8YU#189 - * @param start the starting point - * @param target the target point - * @param ref the vector3 to store the result - * @returns ref in the form (pitch, yaw, 0) - */ - static PitchYawRollToMoveBetweenPointsToRef(start, target, ref) { - const diff = math_vector_TmpVectors.Vector3[0]; - target.subtractToRef(start, diff); - ref._y = Math.atan2(diff.x, diff.z) || 0; - ref._x = Math.atan2(Math.sqrt(diff.x ** 2 + diff.z ** 2), diff.y) || 0; - ref._z = 0; - ref._isDirty = true; - return ref; - } - /** - * Gets the rotation that aligns the roll axis (Y) to the line joining the start point to the target point - * Example PG https://playground.babylonjs.com/#R1F8YU#188 - * @param start the starting point - * @param target the target point - * @returns the rotation in the form (pitch, yaw, 0) - */ - static PitchYawRollToMoveBetweenPoints(start, target) { - const ref = math_vector_Vector3.Zero(); - return math_vector_Vector3.PitchYawRollToMoveBetweenPointsToRef(start, target, ref); - } - /** - * Slerp between two vectors. See also `SmoothToRef` - * Slerp is a spherical linear interpolation - * giving a slow in and out effect - * Example Playground 1 https://playground.babylonjs.com/#R1F8YU#108 - * Example Playground 2 https://playground.babylonjs.com/#R1F8YU#109 - * @param vector0 Start vector - * @param vector1 End vector - * @param slerp amount (will be clamped between 0 and 1) - * @param result The slerped vector - */ - static SlerpToRef(vector0, vector1, slerp, result) { - slerp = math_scalar_Scalar.Clamp(slerp, 0, 1); - const vector0Dir = MathTmp.Vector3[0]; - const vector1Dir = MathTmp.Vector3[1]; - vector0Dir.copyFrom(vector0); - const vector0Length = vector0Dir.length(); - vector0Dir.normalizeFromLength(vector0Length); - vector1Dir.copyFrom(vector1); - const vector1Length = vector1Dir.length(); - vector1Dir.normalizeFromLength(vector1Length); - const dot = math_vector_Vector3.Dot(vector0Dir, vector1Dir); - let scale0; - let scale1; - if (dot < 1 - math_constants_Epsilon) { - const omega = Math.acos(dot); - const invSin = 1 / Math.sin(omega); - scale0 = Math.sin((1 - slerp) * omega) * invSin; - scale1 = Math.sin(slerp * omega) * invSin; - } - else { - // Use linear interpolation - scale0 = 1 - slerp; - scale1 = slerp; - } - vector0Dir.scaleInPlace(scale0); - vector1Dir.scaleInPlace(scale1); - result.copyFrom(vector0Dir).addInPlace(vector1Dir); - result.scaleInPlace(math_scalar_Scalar.Lerp(vector0Length, vector1Length, slerp)); - return result; - } - /** - * Smooth interpolation between two vectors using Slerp - * Example Playground https://playground.babylonjs.com/#R1F8YU#110 - * @param source source vector - * @param goal goal vector - * @param deltaTime current interpolation frame - * @param lerpTime total interpolation time - * @param result the smoothed vector - */ - static SmoothToRef(source, goal, deltaTime, lerpTime, result) { - math_vector_Vector3.SlerpToRef(source, goal, lerpTime === 0 ? 1 : deltaTime / lerpTime, result); - return result; - } - /** - * Returns a new Vector3 set from the index "offset" of the given array - * Example Playground https://playground.babylonjs.com/#R1F8YU#83 - * @param array defines the source array - * @param offset defines the offset in the source array - * @returns the new Vector3 - */ - static FromArray(array, offset = 0) { - return new math_vector_Vector3(array[offset], array[offset + 1], array[offset + 2]); - } - /** - * Returns a new Vector3 set from the index "offset" of the given Float32Array - * @param array defines the source array - * @param offset defines the offset in the source array - * @returns the new Vector3 - * @deprecated Please use FromArray instead. - */ - static FromFloatArray(array, offset) { - return math_vector_Vector3.FromArray(array, offset); - } - /** - * Sets the given vector "result" with the element values from the index "offset" of the given array - * Example Playground https://playground.babylonjs.com/#R1F8YU#84 - * @param array defines the source array - * @param offset defines the offset in the source array - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static FromArrayToRef(array, offset, result) { - result._x = array[offset]; - result._y = array[offset + 1]; - result._z = array[offset + 2]; - result._isDirty = true; - return result; - } - /** - * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array - * @param array defines the source array - * @param offset defines the offset in the source array - * @param result defines the Vector3 where to store the result - * @deprecated Please use FromArrayToRef instead. - */ - static FromFloatArrayToRef(array, offset, result) { - return math_vector_Vector3.FromArrayToRef(array, offset, result); - } - /** - * Sets the given vector "result" with the given floats. - * Example Playground https://playground.babylonjs.com/#R1F8YU#85 - * @param x defines the x coordinate of the source - * @param y defines the y coordinate of the source - * @param z defines the z coordinate of the source - * @param result defines the Vector3 where to store the result - */ - static FromFloatsToRef(x, y, z, result) { - result.copyFromFloats(x, y, z); - return result; - } - /** - * Returns a new Vector3 set to (0.0, 0.0, 0.0) - * @returns a new empty Vector3 - */ - static Zero() { - return new math_vector_Vector3(0.0, 0.0, 0.0); - } - /** - * Returns a new Vector3 set to (1.0, 1.0, 1.0) - * @returns a new Vector3 - */ - static One() { - return new math_vector_Vector3(1.0, 1.0, 1.0); - } - /** - * Returns a new Vector3 set to (0.0, 1.0, 0.0) - * Example Playground https://playground.babylonjs.com/#R1F8YU#71 - * @returns a new up Vector3 - */ - static Up() { - return new math_vector_Vector3(0.0, 1.0, 0.0); - } - /** - * Gets an up Vector3 that must not be updated - */ - static get UpReadOnly() { - return math_vector_Vector3._UpReadOnly; - } - /** - * Gets a down Vector3 that must not be updated - */ - static get DownReadOnly() { - return math_vector_Vector3._DownReadOnly; - } - /** - * Gets a right Vector3 that must not be updated - */ - static get RightReadOnly() { - return math_vector_Vector3._RightReadOnly; - } - /** - * Gets a left Vector3 that must not be updated - */ - static get LeftReadOnly() { - return math_vector_Vector3._LeftReadOnly; - } - /** - * Gets a forward Vector3 that must not be updated - */ - static get LeftHandedForwardReadOnly() { - return math_vector_Vector3._LeftHandedForwardReadOnly; - } - /** - * Gets a forward Vector3 that must not be updated - */ - static get RightHandedForwardReadOnly() { - return math_vector_Vector3._RightHandedForwardReadOnly; - } - /** - * Gets a backward Vector3 that must not be updated - */ - static get LeftHandedBackwardReadOnly() { - return math_vector_Vector3._LeftHandedBackwardReadOnly; - } - /** - * Gets a backward Vector3 that must not be updated - */ - static get RightHandedBackwardReadOnly() { - return math_vector_Vector3._RightHandedBackwardReadOnly; - } - /** - * Gets a zero Vector3 that must not be updated - */ - static get ZeroReadOnly() { - return math_vector_Vector3._ZeroReadOnly; - } - /** - * Gets a one Vector3 that must not be updated - */ - static get OneReadOnly() { - return math_vector_Vector3._OneReadOnly; - } - /** - * Returns a new Vector3 set to (0.0, -1.0, 0.0) - * Example Playground https://playground.babylonjs.com/#R1F8YU#71 - * @returns a new down Vector3 - */ - static Down() { - return new math_vector_Vector3(0.0, -1.0, 0.0); - } - /** - * Returns a new Vector3 set to (0.0, 0.0, 1.0) - * Example Playground https://playground.babylonjs.com/#R1F8YU#71 - * @param rightHandedSystem is the scene right-handed (negative z) - * @returns a new forward Vector3 - */ - static Forward(rightHandedSystem = false) { - return new math_vector_Vector3(0.0, 0.0, rightHandedSystem ? -1.0 : 1.0); - } - /** - * Returns a new Vector3 set to (0.0, 0.0, -1.0) - * Example Playground https://playground.babylonjs.com/#R1F8YU#71 - * @param rightHandedSystem is the scene right-handed (negative-z) - * @returns a new Backward Vector3 - */ - static Backward(rightHandedSystem = false) { - return new math_vector_Vector3(0.0, 0.0, rightHandedSystem ? 1.0 : -1.0); - } - /** - * Returns a new Vector3 set to (1.0, 0.0, 0.0) - * Example Playground https://playground.babylonjs.com/#R1F8YU#71 - * @returns a new right Vector3 - */ - static Right() { - return new math_vector_Vector3(1.0, 0.0, 0.0); - } - /** - * Returns a new Vector3 set to (-1.0, 0.0, 0.0) - * Example Playground https://playground.babylonjs.com/#R1F8YU#71 - * @returns a new left Vector3 - */ - static Left() { - return new math_vector_Vector3(-1.0, 0.0, 0.0); - } - /** - * Returns a new Vector3 with random values between min and max - * @param min the minimum random value - * @param max the maximum random value - * @returns a Vector3 with random values between min and max - */ - static Random(min = 0, max = 1) { - return new math_vector_Vector3(math_scalar_Scalar.RandomRange(min, max), math_scalar_Scalar.RandomRange(min, max), math_scalar_Scalar.RandomRange(min, max)); - } - /** - * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector. - * This method computes transformed coordinates only, not transformed direction vectors (ie. it takes translation in account) - * Example Playground https://playground.babylonjs.com/#R1F8YU#111 - * @param vector defines the Vector3 to transform - * @param transformation defines the transformation matrix - * @returns the transformed Vector3 - */ - static TransformCoordinates(vector, transformation) { - const result = math_vector_Vector3.Zero(); - math_vector_Vector3.TransformCoordinatesToRef(vector, transformation, result); - return result; - } - /** - * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector - * This method computes transformed coordinates only, not transformed direction vectors (ie. it takes translation in account) - * Example Playground https://playground.babylonjs.com/#R1F8YU#113 - * @param vector defines the Vector3 to transform - * @param transformation defines the transformation matrix - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static TransformCoordinatesToRef(vector, transformation, result) { - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result); - return result; - } - /** - * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z) - * This method computes transformed coordinates only, not transformed direction vectors - * Example Playground https://playground.babylonjs.com/#R1F8YU#115 - * @param x define the x coordinate of the source vector - * @param y define the y coordinate of the source vector - * @param z define the z coordinate of the source vector - * @param transformation defines the transformation matrix - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static TransformCoordinatesFromFloatsToRef(x, y, z, transformation, result) { - const m = transformation.m; - const rx = x * m[0] + y * m[4] + z * m[8] + m[12]; - const ry = x * m[1] + y * m[5] + z * m[9] + m[13]; - const rz = x * m[2] + y * m[6] + z * m[10] + m[14]; - const rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]); - result._x = rx * rw; - result._y = ry * rw; - result._z = rz * rw; - result._isDirty = true; - return result; - } - /** - * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector - * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) - * Example Playground https://playground.babylonjs.com/#R1F8YU#112 - * @param vector defines the Vector3 to transform - * @param transformation defines the transformation matrix - * @returns the new Vector3 - */ - static TransformNormal(vector, transformation) { - const result = math_vector_Vector3.Zero(); - math_vector_Vector3.TransformNormalToRef(vector, transformation, result); - return result; - } - /** - * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector - * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) - * Example Playground https://playground.babylonjs.com/#R1F8YU#114 - * @param vector defines the Vector3 to transform - * @param transformation defines the transformation matrix - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static TransformNormalToRef(vector, transformation, result) { - this.TransformNormalFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result); - return result; - } - /** - * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z) - * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) - * Example Playground https://playground.babylonjs.com/#R1F8YU#116 - * @param x define the x coordinate of the source vector - * @param y define the y coordinate of the source vector - * @param z define the z coordinate of the source vector - * @param transformation defines the transformation matrix - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static TransformNormalFromFloatsToRef(x, y, z, transformation, result) { - const m = transformation.m; - result._x = x * m[0] + y * m[4] + z * m[8]; - result._y = x * m[1] + y * m[5] + z * m[9]; - result._z = x * m[2] + y * m[6] + z * m[10]; - result._isDirty = true; - return result; - } - /** - * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4" - * Example Playground https://playground.babylonjs.com/#R1F8YU#69 - * @param value1 defines the first control point - * @param value2 defines the second control point - * @param value3 defines the third control point - * @param value4 defines the fourth control point - * @param amount defines the amount on the spline to use - * @returns the new Vector3 - */ - static CatmullRom(value1, value2, value3, value4, amount) { - const squared = amount * amount; - const cubed = amount * squared; - const x = 0.5 * - (2.0 * value2._x + - (-value1._x + value3._x) * amount + - (2.0 * value1._x - 5.0 * value2._x + 4.0 * value3._x - value4._x) * squared + - (-value1._x + 3.0 * value2._x - 3.0 * value3._x + value4._x) * cubed); - const y = 0.5 * - (2.0 * value2._y + - (-value1._y + value3._y) * amount + - (2.0 * value1._y - 5.0 * value2._y + 4.0 * value3._y - value4._y) * squared + - (-value1._y + 3.0 * value2._y - 3.0 * value3._y + value4._y) * cubed); - const z = 0.5 * - (2.0 * value2._z + - (-value1._z + value3._z) * amount + - (2.0 * value1._z - 5.0 * value2._z + 4.0 * value3._z - value4._z) * squared + - (-value1._z + 3.0 * value2._z - 3.0 * value3._z + value4._z) * cubed); - return new value1.constructor(x, y, z); - } - /** - * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" - * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one - * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one - * Example Playground https://playground.babylonjs.com/#R1F8YU#76 - * @param value defines the current value - * @param min defines the lower range value - * @param max defines the upper range value - * @returns the new Vector3 - */ - static Clamp(value, min, max) { - const result = new value.constructor(); - math_vector_Vector3.ClampToRef(value, min, max, result); - return result; - } - /** - * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" - * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one - * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one - * Example Playground https://playground.babylonjs.com/#R1F8YU#77 - * @param value defines the current value - * @param min defines the lower range value - * @param max defines the upper range value - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static ClampToRef(value, min, max, result) { - let x = value._x; - x = x > max._x ? max._x : x; - x = x < min._x ? min._x : x; - let y = value._y; - y = y > max._y ? max._y : y; - y = y < min._y ? min._y : y; - let z = value._z; - z = z > max._z ? max._z : z; - z = z < min._z ? min._z : z; - result.copyFromFloats(x, y, z); - return result; - } - /** - * Checks if a given vector is inside a specific range - * Example Playground https://playground.babylonjs.com/#R1F8YU#75 - * @param v defines the vector to test - * @param min defines the minimum range - * @param max defines the maximum range - */ - static CheckExtends(v, min, max) { - min.minimizeInPlace(v); - max.maximizeInPlace(v); - } - /** - * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2" - * Example Playground https://playground.babylonjs.com/#R1F8YU#89 - * @param value1 defines the first control point - * @param tangent1 defines the first tangent vector - * @param value2 defines the second control point - * @param tangent2 defines the second tangent vector - * @param amount defines the amount on the interpolation spline (between 0 and 1) - * @returns the new Vector3 - */ - static Hermite(value1, tangent1, value2, tangent2, amount) { - const squared = amount * amount; - const cubed = amount * squared; - const part1 = 2.0 * cubed - 3.0 * squared + 1.0; - const part2 = -2.0 * cubed + 3.0 * squared; - const part3 = cubed - 2.0 * squared + amount; - const part4 = cubed - squared; - const x = value1._x * part1 + value2._x * part2 + tangent1._x * part3 + tangent2._x * part4; - const y = value1._y * part1 + value2._y * part2 + tangent1._y * part3 + tangent2._y * part4; - const z = value1._z * part1 + value2._z * part2 + tangent1._z * part3 + tangent2._z * part4; - return new value1.constructor(x, y, z); - } - /** - * Returns a new Vector3 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". - * Example Playground https://playground.babylonjs.com/#R1F8YU#90 - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @returns 1st derivative - */ - static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { - const result = new value1.constructor(); - this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); - return result; - } - /** - * Update a Vector3 with the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". - * Example Playground https://playground.babylonjs.com/#R1F8YU#91 - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @param result define where to store the derivative - * @returns result input - */ - static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { - const t2 = time * time; - result._x = (t2 - time) * 6 * value1._x + (3 * t2 - 4 * time + 1) * tangent1._x + (-t2 + time) * 6 * value2._x + (3 * t2 - 2 * time) * tangent2._x; - result._y = (t2 - time) * 6 * value1._y + (3 * t2 - 4 * time + 1) * tangent1._y + (-t2 + time) * 6 * value2._y + (3 * t2 - 2 * time) * tangent2._y; - result._z = (t2 - time) * 6 * value1._z + (3 * t2 - 4 * time + 1) * tangent1._z + (-t2 + time) * 6 * value2._z + (3 * t2 - 2 * time) * tangent2._z; - result._isDirty = true; - return result; - } - /** - * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end" - * Example Playground https://playground.babylonjs.com/#R1F8YU#95 - * @param start defines the start value - * @param end defines the end value - * @param amount max defines amount between both (between 0 and 1) - * @returns the new Vector3 - */ - static Lerp(start, end, amount) { - const result = new start.constructor(0, 0, 0); - math_vector_Vector3.LerpToRef(start, end, amount, result); - return result; - } - /** - * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end" - * Example Playground https://playground.babylonjs.com/#R1F8YU#93 - * @param start defines the start value - * @param end defines the end value - * @param amount max defines amount between both (between 0 and 1) - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static LerpToRef(start, end, amount, result) { - result._x = start._x + (end._x - start._x) * amount; - result._y = start._y + (end._y - start._y) * amount; - result._z = start._z + (end._z - start._z) * amount; - result._isDirty = true; - return result; - } - /** - * Returns the dot product (float) between the vectors "left" and "right" - * Example Playground https://playground.babylonjs.com/#R1F8YU#82 - * @param left defines the left operand - * @param right defines the right operand - * @returns the dot product - */ - static Dot(left, right) { - return left._x * right._x + left._y * right._y + left._z * right._z; - } - /** - * Returns a new Vector3 as the cross product of the vectors "left" and "right" - * The cross product is then orthogonal to both "left" and "right" - * Example Playground https://playground.babylonjs.com/#R1F8YU#15 - * @param left defines the left operand - * @param right defines the right operand - * @returns the cross product - */ - static Cross(left, right) { - const result = new left.constructor(); - math_vector_Vector3.CrossToRef(left, right, result); - return result; - } - /** - * Sets the given vector "result" with the cross product of "left" and "right" - * The cross product is then orthogonal to both "left" and "right" - * Example Playground https://playground.babylonjs.com/#R1F8YU#78 - * @param left defines the left operand - * @param right defines the right operand - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static CrossToRef(left, right, result) { - const x = left._y * right._z - left._z * right._y; - const y = left._z * right._x - left._x * right._z; - const z = left._x * right._y - left._y * right._x; - result.copyFromFloats(x, y, z); - return result; - } - /** - * Returns a new Vector3 as the normalization of the given vector - * Example Playground https://playground.babylonjs.com/#R1F8YU#98 - * @param vector defines the Vector3 to normalize - * @returns the new Vector3 - */ - static Normalize(vector) { - const result = math_vector_Vector3.Zero(); - math_vector_Vector3.NormalizeToRef(vector, result); - return result; - } - /** - * Sets the given vector "result" with the normalization of the given first vector - * Example Playground https://playground.babylonjs.com/#R1F8YU#98 - * @param vector defines the Vector3 to normalize - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static NormalizeToRef(vector, result) { - vector.normalizeToRef(result); - return result; - } - /** - * Project a Vector3 onto screen space - * Example Playground https://playground.babylonjs.com/#R1F8YU#101 - * @param vector defines the Vector3 to project - * @param world defines the world matrix to use - * @param transform defines the transform (view x projection) matrix to use - * @param viewport defines the screen viewport to use - * @returns the new Vector3 - */ - static Project(vector, world, transform, viewport) { - const result = new vector.constructor(); - math_vector_Vector3.ProjectToRef(vector, world, transform, viewport, result); - return result; - } - /** - * Project a Vector3 onto screen space to reference - * Example Playground https://playground.babylonjs.com/#R1F8YU#102 - * @param vector defines the Vector3 to project - * @param world defines the world matrix to use - * @param transform defines the transform (view x projection) matrix to use - * @param viewport defines the screen viewport to use - * @param result the vector in which the screen space will be stored - * @returns result input - */ - static ProjectToRef(vector, world, transform, viewport, result) { - const cw = viewport.width; - const ch = viewport.height; - const cx = viewport.x; - const cy = viewport.y; - const viewportMatrix = MathTmp.Matrix[1]; - math_vector_Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix); - const matrix = MathTmp.Matrix[0]; - world.multiplyToRef(transform, matrix); - matrix.multiplyToRef(viewportMatrix, matrix); - math_vector_Vector3.TransformCoordinatesToRef(vector, matrix, result); - return result; - } - /** - * Reflects a vector off the plane defined by a normalized normal - * @param inDirection defines the vector direction - * @param normal defines the normal - Must be normalized - * @returns the resulting vector - */ - static Reflect(inDirection, normal) { - return this.ReflectToRef(inDirection, normal, new math_vector_Vector3()); - } - /** - * Reflects a vector off the plane defined by a normalized normal to reference - * @param inDirection defines the vector direction - * @param normal defines the normal - Must be normalized - * @param result defines the Vector3 where to store the result - * @returns the resulting vector - */ - static ReflectToRef(inDirection, normal, ref) { - const tmp = math_vector_TmpVectors.Vector3[0]; - tmp.copyFrom(normal).scaleInPlace(2 * math_vector_Vector3.Dot(inDirection, normal)); - return ref.copyFrom(inDirection).subtractInPlace(tmp); - } - /** - * @internal - */ - static _UnprojectFromInvertedMatrixToRef(source, matrix, result) { - math_vector_Vector3.TransformCoordinatesToRef(source, matrix, result); - const m = matrix.m; - const num = source._x * m[3] + source._y * m[7] + source._z * m[11] + m[15]; - if (math_scalar_Scalar.WithinEpsilon(num, 1.0)) { - result.scaleInPlace(1.0 / num); - } - return result; - } - /** - * Unproject from screen space to object space - * Example Playground https://playground.babylonjs.com/#R1F8YU#121 - * @param source defines the screen space Vector3 to use - * @param viewportWidth defines the current width of the viewport - * @param viewportHeight defines the current height of the viewport - * @param world defines the world matrix to use (can be set to Identity to go to world space) - * @param transform defines the transform (view x projection) matrix to use - * @returns the new Vector3 - */ - static UnprojectFromTransform(source, viewportWidth, viewportHeight, world, transform) { - return this.Unproject(source, viewportWidth, viewportHeight, world, transform, math_vector_Matrix.IdentityReadOnly); - } - /** - * Unproject from screen space to object space - * Example Playground https://playground.babylonjs.com/#R1F8YU#117 - * @param source defines the screen space Vector3 to use - * @param viewportWidth defines the current width of the viewport - * @param viewportHeight defines the current height of the viewport - * @param world defines the world matrix to use (can be set to Identity to go to world space) - * @param view defines the view matrix to use - * @param projection defines the projection matrix to use - * @returns the new Vector3 - */ - static Unproject(source, viewportWidth, viewportHeight, world, view, projection) { - const result = new source.constructor(); - math_vector_Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result); - return result; - } - /** - * Unproject from screen space to object space - * Example Playground https://playground.babylonjs.com/#R1F8YU#119 - * @param source defines the screen space Vector3 to use - * @param viewportWidth defines the current width of the viewport - * @param viewportHeight defines the current height of the viewport - * @param world defines the world matrix to use (can be set to Identity to go to world space) - * @param view defines the view matrix to use - * @param projection defines the projection matrix to use - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result) { - math_vector_Vector3.UnprojectFloatsToRef(source._x, source._y, source._z, viewportWidth, viewportHeight, world, view, projection, result); - return result; - } - /** - * Unproject from screen space to object space - * Example Playground https://playground.babylonjs.com/#R1F8YU#120 - * @param sourceX defines the screen space x coordinate to use - * @param sourceY defines the screen space y coordinate to use - * @param sourceZ defines the screen space z coordinate to use - * @param viewportWidth defines the current width of the viewport - * @param viewportHeight defines the current height of the viewport - * @param world defines the world matrix to use (can be set to Identity to go to world space) - * @param view defines the view matrix to use - * @param projection defines the projection matrix to use - * @param result defines the Vector3 where to store the result - * @returns result input - */ - static UnprojectFloatsToRef(sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) { - var _a; - const matrix = MathTmp.Matrix[0]; - world.multiplyToRef(view, matrix); - matrix.multiplyToRef(projection, matrix); - matrix.invert(); - const screenSource = MathTmp.Vector3[0]; - screenSource.x = (sourceX / viewportWidth) * 2 - 1; - screenSource.y = -((sourceY / viewportHeight) * 2 - 1); - if ((_a = engineStore_EngineStore.LastCreatedEngine) === null || _a === void 0 ? void 0 : _a.isNDCHalfZRange) { - screenSource.z = sourceZ; - } - else { - screenSource.z = 2 * sourceZ - 1.0; - } - math_vector_Vector3._UnprojectFromInvertedMatrixToRef(screenSource, matrix, result); - return result; - } - /** - * Gets the minimal coordinate values between two Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#97 - * @param left defines the first operand - * @param right defines the second operand - * @returns the new Vector3 - */ - static Minimize(left, right) { - const min = new left.constructor(); - min.copyFrom(left); - min.minimizeInPlace(right); - return min; - } - /** - * Gets the maximal coordinate values between two Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#96 - * @param left defines the first operand - * @param right defines the second operand - * @returns the new Vector3 - */ - static Maximize(left, right) { - const max = new left.constructor(); - max.copyFrom(left); - max.maximizeInPlace(right); - return max; - } - /** - * Returns the distance between the vectors "value1" and "value2" - * Example Playground https://playground.babylonjs.com/#R1F8YU#81 - * @param value1 defines the first operand - * @param value2 defines the second operand - * @returns the distance - */ - static Distance(value1, value2) { - return Math.sqrt(math_vector_Vector3.DistanceSquared(value1, value2)); - } - /** - * Returns the squared distance between the vectors "value1" and "value2" - * Example Playground https://playground.babylonjs.com/#R1F8YU#80 - * @param value1 defines the first operand - * @param value2 defines the second operand - * @returns the squared distance - */ - static DistanceSquared(value1, value2) { - const x = value1._x - value2._x; - const y = value1._y - value2._y; - const z = value1._z - value2._z; - return x * x + y * y + z * z; - } - /** - * Projects "vector" on the triangle determined by its extremities "p0", "p1" and "p2", stores the result in "ref" - * and returns the distance to the projected point. - * Example Playground https://playground.babylonjs.com/#R1F8YU#104 - * From http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.104.4264&rep=rep1&type=pdf - * - * @param vector the vector to get distance from - * @param p0 extremity of the triangle - * @param p1 extremity of the triangle - * @param p2 extremity of the triangle - * @param ref variable to store the result to - * @returns The distance between "ref" and "vector" - */ - static ProjectOnTriangleToRef(vector, p0, p1, p2, ref) { - const p1p0 = MathTmp.Vector3[0]; - const p2p0 = MathTmp.Vector3[1]; - const p2p1 = MathTmp.Vector3[2]; - const normal = MathTmp.Vector3[3]; - const vectorp0 = MathTmp.Vector3[4]; - // Triangle vectors - p1.subtractToRef(p0, p1p0); - p2.subtractToRef(p0, p2p0); - p2.subtractToRef(p1, p2p1); - const p1p0L = p1p0.length(); - const p2p0L = p2p0.length(); - const p2p1L = p2p1.length(); - if (p1p0L < math_constants_Epsilon || p2p0L < math_constants_Epsilon || p2p1L < math_constants_Epsilon) { - // This is a degenerate triangle. As we assume this is part of a non-degenerate mesh, - // we will find a better intersection later. - // Let's just return one of the extremities - ref.copyFrom(p0); - return math_vector_Vector3.Distance(vector, p0); - } - // Compute normal and vector to p0 - vector.subtractToRef(p0, vectorp0); - math_vector_Vector3.CrossToRef(p1p0, p2p0, normal); - const nl = normal.length(); - if (nl < math_constants_Epsilon) { - // Extremities are aligned, we are back on the case of a degenerate triangle - ref.copyFrom(p0); - return math_vector_Vector3.Distance(vector, p0); - } - normal.normalizeFromLength(nl); - let l = vectorp0.length(); - if (l < math_constants_Epsilon) { - // Vector is p0 - ref.copyFrom(p0); - return 0; - } - vectorp0.normalizeFromLength(l); - // Project to "proj" that lies on the triangle plane - const cosA = math_vector_Vector3.Dot(normal, vectorp0); - const projVector = MathTmp.Vector3[5]; - const proj = MathTmp.Vector3[6]; - projVector.copyFrom(normal).scaleInPlace(-l * cosA); - proj.copyFrom(vector).addInPlace(projVector); - // Compute barycentric coordinates (v0, v1 and v2 are axis from barycenter to extremities) - const v0 = MathTmp.Vector3[4]; - const v1 = MathTmp.Vector3[5]; - const v2 = MathTmp.Vector3[7]; - const tmp = MathTmp.Vector3[8]; - v0.copyFrom(p1p0).scaleInPlace(1 / p1p0L); - tmp.copyFrom(p2p0).scaleInPlace(1 / p2p0L); - v0.addInPlace(tmp).scaleInPlace(-1); - v1.copyFrom(p1p0).scaleInPlace(-1 / p1p0L); - tmp.copyFrom(p2p1).scaleInPlace(1 / p2p1L); - v1.addInPlace(tmp).scaleInPlace(-1); - v2.copyFrom(p2p1).scaleInPlace(-1 / p2p1L); - tmp.copyFrom(p2p0).scaleInPlace(-1 / p2p0L); - v2.addInPlace(tmp).scaleInPlace(-1); - // Determines which edge of the triangle is closest to "proj" - const projP = MathTmp.Vector3[9]; - let dot; - projP.copyFrom(proj).subtractInPlace(p0); - math_vector_Vector3.CrossToRef(v0, projP, tmp); - dot = math_vector_Vector3.Dot(tmp, normal); - const s0 = dot; - projP.copyFrom(proj).subtractInPlace(p1); - math_vector_Vector3.CrossToRef(v1, projP, tmp); - dot = math_vector_Vector3.Dot(tmp, normal); - const s1 = dot; - projP.copyFrom(proj).subtractInPlace(p2); - math_vector_Vector3.CrossToRef(v2, projP, tmp); - dot = math_vector_Vector3.Dot(tmp, normal); - const s2 = dot; - const edge = MathTmp.Vector3[10]; - let e0, e1; - if (s0 > 0 && s1 < 0) { - edge.copyFrom(p1p0); - e0 = p0; - e1 = p1; - } - else if (s1 > 0 && s2 < 0) { - edge.copyFrom(p2p1); - e0 = p1; - e1 = p2; - } - else { - edge.copyFrom(p2p0).scaleInPlace(-1); - e0 = p2; - e1 = p0; - } - // Determines if "proj" lies inside the triangle - const tmp2 = MathTmp.Vector3[9]; - const tmp3 = MathTmp.Vector3[4]; - e0.subtractToRef(proj, tmp); - e1.subtractToRef(proj, tmp2); - math_vector_Vector3.CrossToRef(tmp, tmp2, tmp3); - const isOutside = math_vector_Vector3.Dot(tmp3, normal) < 0; - // If inside, we already found the projected point, "proj" - if (!isOutside) { - ref.copyFrom(proj); - return Math.abs(l * cosA); - } - // If outside, we find "triProj", the closest point from "proj" on the closest edge - const r = MathTmp.Vector3[5]; - math_vector_Vector3.CrossToRef(edge, tmp3, r); - r.normalize(); - const e0proj = MathTmp.Vector3[9]; - e0proj.copyFrom(e0).subtractInPlace(proj); - const e0projL = e0proj.length(); - if (e0projL < math_constants_Epsilon) { - // Proj is e0 - ref.copyFrom(e0); - return math_vector_Vector3.Distance(vector, e0); - } - e0proj.normalizeFromLength(e0projL); - const cosG = math_vector_Vector3.Dot(r, e0proj); - const triProj = MathTmp.Vector3[7]; - triProj.copyFrom(proj).addInPlace(r.scaleInPlace(e0projL * cosG)); - // Now we clamp "triProj" so it lies between e0 and e1 - tmp.copyFrom(triProj).subtractInPlace(e0); - l = edge.length(); - edge.normalizeFromLength(l); - let t = math_vector_Vector3.Dot(tmp, edge) / Math.max(l, math_constants_Epsilon); - t = math_scalar_Scalar.Clamp(t, 0, 1); - triProj.copyFrom(e0).addInPlace(edge.scaleInPlace(t * l)); - ref.copyFrom(triProj); - return math_vector_Vector3.Distance(vector, triProj); - } - /** - * Returns a new Vector3 located at the center between "value1" and "value2" - * Example Playground https://playground.babylonjs.com/#R1F8YU#72 - * @param value1 defines the first operand - * @param value2 defines the second operand - * @returns the new Vector3 - */ - static Center(value1, value2) { - return math_vector_Vector3.CenterToRef(value1, value2, math_vector_Vector3.Zero()); - } - /** - * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref" - * Example Playground https://playground.babylonjs.com/#R1F8YU#73 - * @param value1 defines first vector - * @param value2 defines second vector - * @param ref defines third vector - * @returns ref - */ - static CenterToRef(value1, value2, ref) { - return ref.copyFromFloats((value1._x + value2._x) / 2, (value1._y + value2._y) / 2, (value1._z + value2._z) / 2); - } - /** - * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system), - * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply - * to something in order to rotate it from its local system to the given target system - * Note: axis1, axis2 and axis3 are normalized during this operation - * Example Playground https://playground.babylonjs.com/#R1F8YU#106 - * @param axis1 defines the first axis - * @param axis2 defines the second axis - * @param axis3 defines the third axis - * @returns a new Vector3 - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/target_align - */ - static RotationFromAxis(axis1, axis2, axis3) { - const rotation = new axis1.constructor(); - math_vector_Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation); - return rotation; - } - /** - * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3 - * Example Playground https://playground.babylonjs.com/#R1F8YU#107 - * @param axis1 defines the first axis - * @param axis2 defines the second axis - * @param axis3 defines the third axis - * @param ref defines the Vector3 where to store the result - * @returns result input - */ - static RotationFromAxisToRef(axis1, axis2, axis3, ref) { - const quat = MathTmp.Quaternion[0]; - math_vector_Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat); - quat.toEulerAnglesToRef(ref); - return ref; - } -} -math_vector_Vector3._UpReadOnly = math_vector_Vector3.Up(); -math_vector_Vector3._DownReadOnly = math_vector_Vector3.Down(); -math_vector_Vector3._LeftHandedForwardReadOnly = math_vector_Vector3.Forward(false); -math_vector_Vector3._RightHandedForwardReadOnly = math_vector_Vector3.Forward(true); -math_vector_Vector3._LeftHandedBackwardReadOnly = math_vector_Vector3.Backward(false); -math_vector_Vector3._RightHandedBackwardReadOnly = math_vector_Vector3.Backward(true); -math_vector_Vector3._RightReadOnly = math_vector_Vector3.Right(); -math_vector_Vector3._LeftReadOnly = math_vector_Vector3.Left(); -math_vector_Vector3._ZeroReadOnly = math_vector_Vector3.Zero(); -math_vector_Vector3._OneReadOnly = math_vector_Vector3.One(); -/** - * Vector4 class created for EulerAngle class conversion to Quaternion - */ -class math_vector_Vector4 { - /** - * Creates a Vector4 object from the given floats. - * @param x x value of the vector - * @param y y value of the vector - * @param z z value of the vector - * @param w w value of the vector - */ - constructor( - /** x value of the vector */ - x = 0, - /** y value of the vector */ - y = 0, - /** z value of the vector */ - z = 0, - /** w value of the vector */ - w = 0) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - /** - * Returns the string with the Vector4 coordinates. - * @returns a string containing all the vector values - */ - toString() { - return `{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`; - } - /** - * Returns the string "Vector4". - * @returns "Vector4" - */ - getClassName() { - return "Vector4"; - } - /** - * Returns the Vector4 hash code. - * @returns a unique hash code - */ - getHashCode() { - const x = _ExtractAsInt(this.x); - const y = _ExtractAsInt(this.y); - const z = _ExtractAsInt(this.z); - const w = _ExtractAsInt(this.w); - let hash = x; - hash = (hash * 397) ^ y; - hash = (hash * 397) ^ z; - hash = (hash * 397) ^ w; - return hash; - } - // Operators - /** - * Returns a new array populated with 4 elements : the Vector4 coordinates. - * @returns the resulting array - */ - asArray() { - const result = new Array(); - this.toArray(result, 0); - return result; - } - /** - * Populates the given array from the given index with the Vector4 coordinates. - * @param array array to populate - * @param index index of the array to start at (default: 0) - * @returns the Vector4. - */ - toArray(array, index) { - if (index === undefined) { - index = 0; - } - array[index] = this.x; - array[index + 1] = this.y; - array[index + 2] = this.z; - array[index + 3] = this.w; - return this; - } - /** - * Update the current vector from an array - * @param array defines the destination array - * @param index defines the offset in the destination array - * @returns the current Vector3 - */ - fromArray(array, index = 0) { - math_vector_Vector4.FromArrayToRef(array, index, this); - return this; - } - /** - * Adds the given vector to the current Vector4. - * @param otherVector the vector to add - * @returns the updated Vector4. - */ - addInPlace(otherVector) { - this.x += otherVector.x; - this.y += otherVector.y; - this.z += otherVector.z; - this.w += otherVector.w; - return this; - } - /** - * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one. - * @param otherVector the vector to add - * @returns the resulting vector - */ - add(otherVector) { - return new this.constructor(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w); - } - /** - * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one. - * @param otherVector the vector to add - * @param result the vector to store the result - * @returns result input - */ - addToRef(otherVector, result) { - result.x = this.x + otherVector.x; - result.y = this.y + otherVector.y; - result.z = this.z + otherVector.z; - result.w = this.w + otherVector.w; - return result; - } - /** - * Subtract in place the given vector from the current Vector4. - * @param otherVector the vector to subtract - * @returns the updated Vector4. - */ - subtractInPlace(otherVector) { - this.x -= otherVector.x; - this.y -= otherVector.y; - this.z -= otherVector.z; - this.w -= otherVector.w; - return this; - } - /** - * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4. - * @param otherVector the vector to add - * @returns the new vector with the result - */ - subtract(otherVector) { - return new this.constructor(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w); - } - /** - * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4. - * @param otherVector the vector to subtract - * @param result the vector to store the result - * @returns result input - */ - subtractToRef(otherVector, result) { - result.x = this.x - otherVector.x; - result.y = this.y - otherVector.y; - result.z = this.z - otherVector.z; - result.w = this.w - otherVector.w; - return result; - } - /** - * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates. - */ - /** - * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates. - * @param x value to subtract - * @param y value to subtract - * @param z value to subtract - * @param w value to subtract - * @returns new vector containing the result - */ - subtractFromFloats(x, y, z, w) { - return new this.constructor(this.x - x, this.y - y, this.z - z, this.w - w); - } - /** - * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates. - * @param x value to subtract - * @param y value to subtract - * @param z value to subtract - * @param w value to subtract - * @param result the vector to store the result in - * @returns result input - */ - subtractFromFloatsToRef(x, y, z, w, result) { - result.x = this.x - x; - result.y = this.y - y; - result.z = this.z - z; - result.w = this.w - w; - return result; - } - /** - * Returns a new Vector4 set with the current Vector4 negated coordinates. - * @returns a new vector with the negated values - */ - negate() { - return new this.constructor(-this.x, -this.y, -this.z, -this.w); - } - /** - * Negate this vector in place - * @returns this - */ - negateInPlace() { - this.x *= -1; - this.y *= -1; - this.z *= -1; - this.w *= -1; - return this; - } - /** - * Negate the current Vector4 and stores the result in the given vector "result" coordinates - * @param result defines the Vector3 object where to store the result - * @returns the result - */ - negateToRef(result) { - return result.copyFromFloats(this.x * -1, this.y * -1, this.z * -1, this.w * -1); - } - /** - * Multiplies the current Vector4 coordinates by scale (float). - * @param scale the number to scale with - * @returns the updated Vector4. - */ - scaleInPlace(scale) { - this.x *= scale; - this.y *= scale; - this.z *= scale; - this.w *= scale; - return this; - } - /** - * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float). - * @param scale the number to scale with - * @returns a new vector with the result - */ - scale(scale) { - return new this.constructor(this.x * scale, this.y * scale, this.z * scale, this.w * scale); - } - /** - * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float). - * @param scale the number to scale with - * @param result a vector to store the result in - * @returns result input - */ - scaleToRef(scale, result) { - result.x = this.x * scale; - result.y = this.y * scale; - result.z = this.z * scale; - result.w = this.w * scale; - return result; - } - /** - * Scale the current Vector4 values by a factor and add the result to a given Vector4 - * @param scale defines the scale factor - * @param result defines the Vector4 object where to store the result - * @returns result input - */ - scaleAndAddToRef(scale, result) { - result.x += this.x * scale; - result.y += this.y * scale; - result.z += this.z * scale; - result.w += this.w * scale; - return result; - } - /** - * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones. - * @param otherVector the vector to compare against - * @returns true if they are equal - */ - equals(otherVector) { - return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w; - } - /** - * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones. - * @param otherVector vector to compare against - * @param epsilon (Default: very small number) - * @returns true if they are equal - */ - equalsWithEpsilon(otherVector, epsilon = math_constants_Epsilon) { - return (otherVector && - math_scalar_Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && - math_scalar_Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && - math_scalar_Scalar.WithinEpsilon(this.z, otherVector.z, epsilon) && - math_scalar_Scalar.WithinEpsilon(this.w, otherVector.w, epsilon)); - } - /** - * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates. - * @param x x value to compare against - * @param y y value to compare against - * @param z z value to compare against - * @param w w value to compare against - * @returns true if equal - */ - equalsToFloats(x, y, z, w) { - return this.x === x && this.y === y && this.z === z && this.w === w; - } - /** - * Multiplies in place the current Vector4 by the given one. - * @param otherVector vector to multiple with - * @returns the updated Vector4. - */ - multiplyInPlace(otherVector) { - this.x *= otherVector.x; - this.y *= otherVector.y; - this.z *= otherVector.z; - this.w *= otherVector.w; - return this; - } - /** - * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one. - * @param otherVector vector to multiple with - * @returns resulting new vector - */ - multiply(otherVector) { - return new this.constructor(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w); - } - /** - * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one. - * @param otherVector vector to multiple with - * @param result vector to store the result - * @returns result input - */ - multiplyToRef(otherVector, result) { - result.x = this.x * otherVector.x; - result.y = this.y * otherVector.y; - result.z = this.z * otherVector.z; - result.w = this.w * otherVector.w; - return result; - } - /** - * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates. - * @param x x value multiply with - * @param y y value multiply with - * @param z z value multiply with - * @param w w value multiply with - * @returns resulting new vector - */ - multiplyByFloats(x, y, z, w) { - return new this.constructor(this.x * x, this.y * y, this.z * z, this.w * w); - } - /** - * Returns a new Vector4 set with the division result of the current Vector4 by the given one. - * @param otherVector vector to devide with - * @returns resulting new vector - */ - divide(otherVector) { - return new this.constructor(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w); - } - /** - * Updates the given vector "result" with the division result of the current Vector4 by the given one. - * @param otherVector vector to devide with - * @param result vector to store the result - * @returns result input - */ - divideToRef(otherVector, result) { - result.x = this.x / otherVector.x; - result.y = this.y / otherVector.y; - result.z = this.z / otherVector.z; - result.w = this.w / otherVector.w; - return result; - } - /** - * Divides the current Vector3 coordinates by the given ones. - * @param otherVector vector to devide with - * @returns the updated Vector3. - */ - divideInPlace(otherVector) { - return this.divideToRef(otherVector, this); - } - /** - * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones - * @param other defines the second operand - * @returns the current updated Vector4 - */ - minimizeInPlace(other) { - if (other.x < this.x) { - this.x = other.x; - } - if (other.y < this.y) { - this.y = other.y; - } - if (other.z < this.z) { - this.z = other.z; - } - if (other.w < this.w) { - this.w = other.w; - } - return this; - } - /** - * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones - * @param other defines the second operand - * @returns the current updated Vector4 - */ - maximizeInPlace(other) { - if (other.x > this.x) { - this.x = other.x; - } - if (other.y > this.y) { - this.y = other.y; - } - if (other.z > this.z) { - this.z = other.z; - } - if (other.w > this.w) { - this.w = other.w; - } - return this; - } - /** - * Gets a new Vector4 from current Vector4 floored values - * @returns a new Vector4 - */ - floor() { - return new this.constructor(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w)); - } - /** - * Gets a new Vector4 from current Vector4 fractional values - * @returns a new Vector4 - */ - fract() { - return new this.constructor(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w)); - } - // Properties - /** - * Returns the Vector4 length (float). - * @returns the length - */ - length() { - return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); - } - /** - * Returns the Vector4 squared length (float). - * @returns the length squared - */ - lengthSquared() { - return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; - } - // Methods - /** - * Normalizes in place the Vector4. - * @returns the updated Vector4. - */ - normalize() { - const len = this.length(); - if (len === 0) { - return this; - } - return this.scaleInPlace(1.0 / len); - } - /** - * Returns a new Vector3 from the Vector4 (x, y, z) coordinates. - * @returns this converted to a new vector3 - */ - toVector3() { - return new math_vector_Vector3(this.x, this.y, this.z); - } - /** - * Returns a new Vector4 copied from the current one. - * @returns the new cloned vector - */ - clone() { - return new this.constructor(this.x, this.y, this.z, this.w); - } - /** - * Updates the current Vector4 with the given one coordinates. - * @param source the source vector to copy from - * @returns the updated Vector4. - */ - copyFrom(source) { - this.x = source.x; - this.y = source.y; - this.z = source.z; - this.w = source.w; - return this; - } - /** - * Updates the current Vector4 coordinates with the given floats. - * @param x float to copy from - * @param y float to copy from - * @param z float to copy from - * @param w float to copy from - * @returns the updated Vector4. - */ - copyFromFloats(x, y, z, w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - return this; - } - /** - * Updates the current Vector4 coordinates with the given floats. - * @param x float to set from - * @param y float to set from - * @param z float to set from - * @param w float to set from - * @returns the updated Vector4. - */ - set(x, y, z, w) { - return this.copyFromFloats(x, y, z, w); - } - /** - * Copies the given float to the current Vector3 coordinates - * @param v defines the x, y, z and w coordinates of the operand - * @returns the current updated Vector3 - */ - setAll(v) { - this.x = this.y = this.z = this.w = v; - return this; - } - // Statics - /** - * Returns a new Vector4 set from the starting index of the given array. - * @param array the array to pull values from - * @param offset the offset into the array to start at - * @returns the new vector - */ - static FromArray(array, offset) { - if (!offset) { - offset = 0; - } - return new math_vector_Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); - } - /** - * Updates the given vector "result" from the starting index of the given array. - * @param array the array to pull values from - * @param offset the offset into the array to start at - * @param result the vector to store the result in - * @returns result input - */ - static FromArrayToRef(array, offset, result) { - result.x = array[offset]; - result.y = array[offset + 1]; - result.z = array[offset + 2]; - result.w = array[offset + 3]; - return result; - } - /** - * Updates the given vector "result" from the starting index of the given Float32Array. - * @param array the array to pull values from - * @param offset the offset into the array to start at - * @param result the vector to store the result in - * @returns result input - */ - static FromFloatArrayToRef(array, offset, result) { - math_vector_Vector4.FromArrayToRef(array, offset, result); - return result; - } - /** - * Updates the given vector "result" coordinates from the given floats. - * @param x float to set from - * @param y float to set from - * @param z float to set from - * @param w float to set from - * @param result the vector to the floats in - * @returns result input - */ - static FromFloatsToRef(x, y, z, w, result) { - result.x = x; - result.y = y; - result.z = z; - result.w = w; - return result; - } - /** - * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0) - * @returns the new vector - */ - static Zero() { - return new math_vector_Vector4(0.0, 0.0, 0.0, 0.0); - } - /** - * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0) - * @returns the new vector - */ - static One() { - return new math_vector_Vector4(1.0, 1.0, 1.0, 1.0); - } - /** - * Returns a new Vector4 with random values between min and max - * @param min the minimum random value - * @param max the maximum random value - * @returns a Vector4 with random values between min and max - */ - static Random(min = 0, max = 1) { - return new math_vector_Vector4(math_scalar_Scalar.RandomRange(min, max), math_scalar_Scalar.RandomRange(min, max), math_scalar_Scalar.RandomRange(min, max), math_scalar_Scalar.RandomRange(min, max)); - } - /** - * Gets a zero Vector4 that must not be updated - */ - static get ZeroReadOnly() { - return math_vector_Vector4._ZeroReadOnly; - } - /** - * Returns a new normalized Vector4 from the given one. - * @param vector the vector to normalize - * @returns the vector - */ - static Normalize(vector) { - const result = math_vector_Vector4.Zero(); - math_vector_Vector4.NormalizeToRef(vector, result); - return result; - } - /** - * Updates the given vector "result" from the normalization of the given one. - * @param vector the vector to normalize - * @param result the vector to store the result in - * @returns result input - */ - static NormalizeToRef(vector, result) { - result.copyFrom(vector); - result.normalize(); - return result; - } - /** - * Returns a vector with the minimum values from the left and right vectors - * @param left left vector to minimize - * @param right right vector to minimize - * @returns a new vector with the minimum of the left and right vector values - */ - static Minimize(left, right) { - const min = new left.constructor(); - min.copyFrom(left); - min.minimizeInPlace(right); - return min; - } - /** - * Returns a vector with the maximum values from the left and right vectors - * @param left left vector to maximize - * @param right right vector to maximize - * @returns a new vector with the maximum of the left and right vector values - */ - static Maximize(left, right) { - const max = new left.constructor(); - max.copyFrom(left); - max.maximizeInPlace(right); - return max; - } - /** - * Returns the distance (float) between the vectors "value1" and "value2". - * @param value1 value to calulate the distance between - * @param value2 value to calulate the distance between - * @returns the distance between the two vectors - */ - static Distance(value1, value2) { - return Math.sqrt(math_vector_Vector4.DistanceSquared(value1, value2)); - } - /** - * Returns the squared distance (float) between the vectors "value1" and "value2". - * @param value1 value to calulate the distance between - * @param value2 value to calulate the distance between - * @returns the distance between the two vectors squared - */ - static DistanceSquared(value1, value2) { - const x = value1.x - value2.x; - const y = value1.y - value2.y; - const z = value1.z - value2.z; - const w = value1.w - value2.w; - return x * x + y * y + z * z + w * w; - } - /** - * Returns a new Vector4 located at the center between the vectors "value1" and "value2". - * @param value1 value to calulate the center between - * @param value2 value to calulate the center between - * @returns the center between the two vectors - */ - static Center(value1, value2) { - return math_vector_Vector4.CenterToRef(value1, value2, math_vector_Vector4.Zero()); - } - /** - * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref" - * @param value1 defines first vector - * @param value2 defines second vector - * @param ref defines third vector - * @returns ref - */ - static CenterToRef(value1, value2, ref) { - return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2, (value1.z + value2.z) / 2, (value1.w + value2.w) / 2); - } - /** - * Returns a new Vector4 set with the result of the transformation by the given matrix of the given vector. - * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account) - * The difference with Vector3.TransformCoordinates is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead - * @param vector defines the Vector3 to transform - * @param transformation defines the transformation matrix - * @returns the transformed Vector4 - */ - static TransformCoordinates(vector, transformation) { - const result = math_vector_Vector4.Zero(); - math_vector_Vector4.TransformCoordinatesToRef(vector, transformation, result); - return result; - } - /** - * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector - * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account) - * The difference with Vector3.TransformCoordinatesToRef is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead - * @param vector defines the Vector3 to transform - * @param transformation defines the transformation matrix - * @param result defines the Vector4 where to store the result - * @returns result input - */ - static TransformCoordinatesToRef(vector, transformation, result) { - math_vector_Vector4.TransformCoordinatesFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result); - return result; - } - /** - * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z) - * This method computes tranformed coordinates only, not transformed direction vectors - * The difference with Vector3.TransformCoordinatesFromFloatsToRef is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead - * @param x define the x coordinate of the source vector - * @param y define the y coordinate of the source vector - * @param z define the z coordinate of the source vector - * @param transformation defines the transformation matrix - * @param result defines the Vector4 where to store the result - * @returns result input - */ - static TransformCoordinatesFromFloatsToRef(x, y, z, transformation, result) { - const m = transformation.m; - const rx = x * m[0] + y * m[4] + z * m[8] + m[12]; - const ry = x * m[1] + y * m[5] + z * m[9] + m[13]; - const rz = x * m[2] + y * m[6] + z * m[10] + m[14]; - const rw = x * m[3] + y * m[7] + z * m[11] + m[15]; - result.x = rx; - result.y = ry; - result.z = rz; - result.w = rw; - return result; - } - /** - * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector. - * This methods computes transformed normalized direction vectors only. - * @param vector the vector to transform - * @param transformation the transformation matrix to apply - * @returns the new vector - */ - static TransformNormal(vector, transformation) { - const result = new vector.constructor(); - math_vector_Vector4.TransformNormalToRef(vector, transformation, result); - return result; - } - /** - * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector. - * This methods computes transformed normalized direction vectors only. - * @param vector the vector to transform - * @param transformation the transformation matrix to apply - * @param result the vector to store the result in - * @returns result input - */ - static TransformNormalToRef(vector, transformation, result) { - const m = transformation.m; - const x = vector.x * m[0] + vector.y * m[4] + vector.z * m[8]; - const y = vector.x * m[1] + vector.y * m[5] + vector.z * m[9]; - const z = vector.x * m[2] + vector.y * m[6] + vector.z * m[10]; - result.x = x; - result.y = y; - result.z = z; - result.w = vector.w; - return result; - } - /** - * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w). - * This methods computes transformed normalized direction vectors only. - * @param x value to transform - * @param y value to transform - * @param z value to transform - * @param w value to transform - * @param transformation the transformation matrix to apply - * @param result the vector to store the results in - * @returns result input - */ - static TransformNormalFromFloatsToRef(x, y, z, w, transformation, result) { - const m = transformation.m; - result.x = x * m[0] + y * m[4] + z * m[8]; - result.y = x * m[1] + y * m[5] + z * m[9]; - result.z = x * m[2] + y * m[6] + z * m[10]; - result.w = w; - return result; - } - /** - * Creates a new Vector4 from a Vector3 - * @param source defines the source data - * @param w defines the 4th component (default is 0) - * @returns a new Vector4 - */ - static FromVector3(source, w = 0) { - return new math_vector_Vector4(source._x, source._y, source._z, w); - } -} -math_vector_Vector4._ZeroReadOnly = math_vector_Vector4.Zero(); -/** - * Class used to store quaternion data - * Example Playground - Overview - https://playground.babylonjs.com/#L49EJ7#100 - * @see https://en.wikipedia.org/wiki/Quaternion - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms - */ -class math_vector_Quaternion { - /** Gets or sets the x coordinate */ - get x() { - return this._x; - } - set x(value) { - this._x = value; - this._isDirty = true; - } - /** Gets or sets the y coordinate */ - get y() { - return this._y; - } - set y(value) { - this._y = value; - this._isDirty = true; - } - /** Gets or sets the z coordinate */ - get z() { - return this._z; - } - set z(value) { - this._z = value; - this._isDirty = true; - } - /** Gets or sets the w coordinate */ - get w() { - return this._w; - } - set w(value) { - this._w = value; - this._isDirty = true; - } - /** - * Creates a new Quaternion from the given floats - * @param x defines the first component (0 by default) - * @param y defines the second component (0 by default) - * @param z defines the third component (0 by default) - * @param w defines the fourth component (1.0 by default) - */ - constructor(x = 0.0, y = 0.0, z = 0.0, w = 1.0) { - /** @internal */ - this._isDirty = true; - this._x = x; - this._y = y; - this._z = z; - this._w = w; - } - /** - * Gets a string representation for the current quaternion - * @returns a string with the Quaternion coordinates - */ - toString() { - return `{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`; - } - /** - * Gets the class name of the quaternion - * @returns the string "Quaternion" - */ - getClassName() { - return "Quaternion"; - } - /** - * Gets a hash code for this quaternion - * @returns the quaternion hash code - */ - getHashCode() { - const x = _ExtractAsInt(this._x); - const y = _ExtractAsInt(this._y); - const z = _ExtractAsInt(this._z); - const w = _ExtractAsInt(this._w); - let hash = x; - hash = (hash * 397) ^ y; - hash = (hash * 397) ^ z; - hash = (hash * 397) ^ w; - return hash; - } - /** - * Copy the quaternion to an array - * Example Playground https://playground.babylonjs.com/#L49EJ7#13 - * @returns a new array populated with 4 elements from the quaternion coordinates - */ - asArray() { - return [this._x, this._y, this._z, this._w]; - } - /** - * Stores from the starting index in the given array the Quaternion successive values - * Example Playground https://playground.babylonjs.com/#L49EJ7#59 - * @param array defines the array where to store the x,y,z,w components - * @param index defines an optional index in the target array to define where to start storing values - * @returns the current Quaternion object - */ - toArray(array, index = 0) { - array[index] = this._x; - array[index + 1] = this._y; - array[index + 2] = this._z; - array[index + 3] = this._w; - return this; - } - /** - * Check if two quaternions are equals - * Example Playground https://playground.babylonjs.com/#L49EJ7#38 - * @param otherQuaternion defines the second operand - * @returns true if the current quaternion and the given one coordinates are strictly equals - */ - equals(otherQuaternion) { - return otherQuaternion && this._x === otherQuaternion._x && this._y === otherQuaternion._y && this._z === otherQuaternion._z && this._w === otherQuaternion._w; - } - /** - * Gets a boolean if two quaternions are equals (using an epsilon value) - * Example Playground https://playground.babylonjs.com/#L49EJ7#37 - * @param otherQuaternion defines the other quaternion - * @param epsilon defines the minimal distance to consider equality - * @returns true if the given quaternion coordinates are close to the current ones by a distance of epsilon. - */ - equalsWithEpsilon(otherQuaternion, epsilon = math_constants_Epsilon) { - return (otherQuaternion && - math_scalar_Scalar.WithinEpsilon(this._x, otherQuaternion._x, epsilon) && - math_scalar_Scalar.WithinEpsilon(this._y, otherQuaternion._y, epsilon) && - math_scalar_Scalar.WithinEpsilon(this._z, otherQuaternion._z, epsilon) && - math_scalar_Scalar.WithinEpsilon(this._w, otherQuaternion._w, epsilon)); - } - /** - * Clone the current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#12 - * @returns a new quaternion copied from the current one - */ - clone() { - return new this.constructor(this._x, this._y, this._z, this._w); - } - /** - * Copy a quaternion to the current one - * Example Playground https://playground.babylonjs.com/#L49EJ7#86 - * @param other defines the other quaternion - * @returns the updated current quaternion - */ - copyFrom(other) { - this._x = other._x; - this._y = other._y; - this._z = other._z; - this._w = other._w; - this._isDirty = true; - return this; - } - /** - * Updates the current quaternion with the given float coordinates - * Example Playground https://playground.babylonjs.com/#L49EJ7#87 - * @param x defines the x coordinate - * @param y defines the y coordinate - * @param z defines the z coordinate - * @param w defines the w coordinate - * @returns the updated current quaternion - */ - copyFromFloats(x, y, z, w) { - this._x = x; - this._y = y; - this._z = z; - this._w = w; - this._isDirty = true; - return this; - } - /** - * Updates the current quaternion from the given float coordinates - * Example Playground https://playground.babylonjs.com/#L49EJ7#56 - * @param x defines the x coordinate - * @param y defines the y coordinate - * @param z defines the z coordinate - * @param w defines the w coordinate - * @returns the updated current quaternion - */ - set(x, y, z, w) { - return this.copyFromFloats(x, y, z, w); - } - /** - * Adds two quaternions - * Example Playground https://playground.babylonjs.com/#L49EJ7#10 - * @param other defines the second operand - * @returns a new quaternion as the addition result of the given one and the current quaternion - */ - add(other) { - return new this.constructor(this._x + other._x, this._y + other._y, this._z + other._z, this._w + other._w); - } - /** - * Add a quaternion to the current one - * Example Playground https://playground.babylonjs.com/#L49EJ7#11 - * @param other defines the quaternion to add - * @returns the current quaternion - */ - addInPlace(other) { - this._x += other._x; - this._y += other._y; - this._z += other._z; - this._w += other._w; - this._isDirty = true; - return this; - } - /** - * Subtract two quaternions - * Example Playground https://playground.babylonjs.com/#L49EJ7#57 - * @param other defines the second operand - * @returns a new quaternion as the subtraction result of the given one from the current one - */ - subtract(other) { - return new this.constructor(this._x - other._x, this._y - other._y, this._z - other._z, this._w - other._w); - } - /** - * Subtract a quaternion to the current one - * Example Playground https://playground.babylonjs.com/#L49EJ7#58 - * @param other defines the quaternion to subtract - * @returns the current quaternion - */ - subtractInPlace(other) { - this._x -= other._x; - this._y -= other._y; - this._z -= other._z; - this._w -= other._w; - this._isDirty = true; - return this; - } - /** - * Multiplies the current quaternion by a scale factor - * Example Playground https://playground.babylonjs.com/#L49EJ7#88 - * @param value defines the scale factor - * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale" - */ - scale(value) { - return new this.constructor(this._x * value, this._y * value, this._z * value, this._w * value); - } - /** - * Scale the current quaternion values by a factor and stores the result to a given quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#89 - * @param scale defines the scale factor - * @param result defines the Quaternion object where to store the result - * @returns result input - */ - scaleToRef(scale, result) { - result._x = this._x * scale; - result._y = this._y * scale; - result._z = this._z * scale; - result._w = this._w * scale; - result._isDirty = true; - return result; - } - /** - * Multiplies in place the current quaternion by a scale factor - * Example Playground https://playground.babylonjs.com/#L49EJ7#90 - * @param value defines the scale factor - * @returns the current modified quaternion - */ - scaleInPlace(value) { - this._x *= value; - this._y *= value; - this._z *= value; - this._w *= value; - this._isDirty = true; - return this; - } - /** - * Scale the current quaternion values by a factor and add the result to a given quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#91 - * @param scale defines the scale factor - * @param result defines the Quaternion object where to store the result - * @returns result input - */ - scaleAndAddToRef(scale, result) { - result._x += this._x * scale; - result._y += this._y * scale; - result._z += this._z * scale; - result._w += this._w * scale; - result._isDirty = true; - return result; - } - /** - * Multiplies two quaternions - * Example Playground https://playground.babylonjs.com/#L49EJ7#43 - * @param q1 defines the second operand - * @returns a new quaternion set as the multiplication result of the current one with the given one "q1" - */ - multiply(q1) { - const result = new this.constructor(0, 0, 0, 1.0); - this.multiplyToRef(q1, result); - return result; - } - /** - * Sets the given "result" as the the multiplication result of the current one with the given one "q1" - * Example Playground https://playground.babylonjs.com/#L49EJ7#45 - * @param q1 defines the second operand - * @param result defines the target quaternion - * @returns the current quaternion - */ - multiplyToRef(q1, result) { - const x = this._x * q1._w + this._y * q1._z - this._z * q1._y + this._w * q1._x; - const y = -this._x * q1._z + this._y * q1._w + this._z * q1._x + this._w * q1._y; - const z = this._x * q1._y - this._y * q1._x + this._z * q1._w + this._w * q1._z; - const w = -this._x * q1._x - this._y * q1._y - this._z * q1._z + this._w * q1._w; - result.copyFromFloats(x, y, z, w); - return result; - } - /** - * Updates the current quaternion with the multiplication of itself with the given one "q1" - * Example Playground https://playground.babylonjs.com/#L49EJ7#46 - * @param q1 defines the second operand - * @returns the currentupdated quaternion - */ - multiplyInPlace(q1) { - this.multiplyToRef(q1, this); - return this; - } - /** - * Conjugates the current quaternion and stores the result in the given quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#81 - * @param ref defines the target quaternion - * @returns result input - */ - conjugateToRef(ref) { - ref.copyFromFloats(-this._x, -this._y, -this._z, this._w); - return ref; - } - /** - * Conjugates in place the current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#82 - * @returns the current updated quaternion - */ - conjugateInPlace() { - this._x *= -1; - this._y *= -1; - this._z *= -1; - this._isDirty = true; - return this; - } - /** - * Conjugates (1-q) the current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#83 - * @returns a new quaternion - */ - conjugate() { - return new this.constructor(-this._x, -this._y, -this._z, this._w); - } - /** - * Returns the inverse of the current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#84 - * @returns a new quaternion - */ - invert() { - const conjugate = this.conjugate(); - const lengthSquared = this.lengthSquared(); - if (lengthSquared == 0 || lengthSquared == 1) { - return conjugate; - } - conjugate.scaleInPlace(1 / lengthSquared); - return conjugate; - } - /** - * Invert in place the current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#85 - * @returns this quaternion - */ - invertInPlace() { - this.conjugateInPlace(); - const lengthSquared = this.lengthSquared(); - if (lengthSquared == 0 || lengthSquared == 1) { - return this; - } - this.scaleInPlace(1 / lengthSquared); - return this; - } - /** - * Gets squared length of current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#29 - * @returns the quaternion length (float) - */ - lengthSquared() { - return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; - } - /** - * Gets length of current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#28 - * @returns the quaternion length (float) - */ - length() { - return Math.sqrt(this.lengthSquared()); - } - /** - * Normalize in place the current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#54 - * @returns the current updated quaternion - */ - normalize() { - const len = this.length(); - if (len === 0) { - return this; - } - const inv = 1.0 / len; - this.scaleInPlace(inv); - return this; - } - /** - * Normalize a copy of the current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#55 - * @returns the normalized quaternion - */ - normalizeToNew() { - const len = this.length(); - if (len === 0) { - return this.clone(); - } - const inv = 1.0 / len; - return this.scale(inv); - } - /** - * Returns a new Vector3 set with the Euler angles translated from the current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#32 - * @returns a new Vector3 containing the Euler angles - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions - */ - toEulerAngles() { - const result = math_vector_Vector3.Zero(); - this.toEulerAnglesToRef(result); - return result; - } - /** - * Sets the given vector3 "result" with the Euler angles translated from the current quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#31 - * @param result defines the vector which will be filled with the Euler angles - * @returns result input - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions - */ - toEulerAnglesToRef(result) { - const qz = this._z; - const qx = this._x; - const qy = this._y; - const qw = this._w; - const zAxisY = qy * qz - qx * qw; - const limit = 0.4999999; - if (zAxisY < -limit) { - result._y = 2 * Math.atan2(qy, qw); - result._x = Math.PI / 2; - result._z = 0; - result._isDirty = true; - } - else if (zAxisY > limit) { - result._y = 2 * Math.atan2(qy, qw); - result._x = -Math.PI / 2; - result._z = 0; - result._isDirty = true; - } - else { - const sqw = qw * qw; - const sqz = qz * qz; - const sqx = qx * qx; - const sqy = qy * qy; - result._z = Math.atan2(2.0 * (qx * qy + qz * qw), -sqz - sqx + sqy + sqw); - result._x = Math.asin(-2.0 * zAxisY); - result._y = Math.atan2(2.0 * (qz * qx + qy * qw), sqz - sqx - sqy + sqw); - result._isDirty = true; - } - return result; - } - /** - * Updates the given rotation matrix with the current quaternion values - * Example Playground https://playground.babylonjs.com/#L49EJ7#67 - * @param result defines the target matrix - * @returns the current unchanged quaternion - */ - toRotationMatrix(result) { - math_vector_Matrix.FromQuaternionToRef(this, result); - return result; - } - /** - * Updates the current quaternion from the given rotation matrix values - * Example Playground https://playground.babylonjs.com/#L49EJ7#41 - * @param matrix defines the source matrix - * @returns the current updated quaternion - */ - fromRotationMatrix(matrix) { - math_vector_Quaternion.FromRotationMatrixToRef(matrix, this); - return this; - } - // Statics - /** - * Creates a new quaternion from a rotation matrix - * Example Playground https://playground.babylonjs.com/#L49EJ7#101 - * @param matrix defines the source matrix - * @returns a new quaternion created from the given rotation matrix values - */ - static FromRotationMatrix(matrix) { - const result = new math_vector_Quaternion(); - math_vector_Quaternion.FromRotationMatrixToRef(matrix, result); - return result; - } - /** - * Updates the given quaternion with the given rotation matrix values - * Example Playground https://playground.babylonjs.com/#L49EJ7#102 - * @param matrix defines the source matrix - * @param result defines the target quaternion - * @returns result input - */ - static FromRotationMatrixToRef(matrix, result) { - const data = matrix.m; - const m11 = data[0], m12 = data[4], m13 = data[8]; - const m21 = data[1], m22 = data[5], m23 = data[9]; - const m31 = data[2], m32 = data[6], m33 = data[10]; - const trace = m11 + m22 + m33; - let s; - if (trace > 0) { - s = 0.5 / Math.sqrt(trace + 1.0); - result._w = 0.25 / s; - result._x = (m32 - m23) * s; - result._y = (m13 - m31) * s; - result._z = (m21 - m12) * s; - result._isDirty = true; - } - else if (m11 > m22 && m11 > m33) { - s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33); - result._w = (m32 - m23) / s; - result._x = 0.25 * s; - result._y = (m12 + m21) / s; - result._z = (m13 + m31) / s; - result._isDirty = true; - } - else if (m22 > m33) { - s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33); - result._w = (m13 - m31) / s; - result._x = (m12 + m21) / s; - result._y = 0.25 * s; - result._z = (m23 + m32) / s; - result._isDirty = true; - } - else { - s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22); - result._w = (m21 - m12) / s; - result._x = (m13 + m31) / s; - result._y = (m23 + m32) / s; - result._z = 0.25 * s; - result._isDirty = true; - } - return result; - } - /** - * Returns the dot product (float) between the quaternions "left" and "right" - * Example Playground https://playground.babylonjs.com/#L49EJ7#61 - * @param left defines the left operand - * @param right defines the right operand - * @returns the dot product - */ - static Dot(left, right) { - return left._x * right._x + left._y * right._y + left._z * right._z + left._w * right._w; - } - /** - * Checks if the orientations of two rotation quaternions are close to each other - * Example Playground https://playground.babylonjs.com/#L49EJ7#60 - * @param quat0 defines the first quaternion to check - * @param quat1 defines the second quaternion to check - * @param epsilon defines closeness, 0 same orientation, 1 PI apart, default 0.1 - * @returns true if the two quaternions are close to each other within epsilon - */ - static AreClose(quat0, quat1, epsilon = 0.1) { - const dot = math_vector_Quaternion.Dot(quat0, quat1); - return 1 - dot * dot <= epsilon; - } - /** - * Smooth interpolation between two quaternions using Slerp - * Example Playground https://playground.babylonjs.com/#L49EJ7#93 - * @param source source quaternion - * @param goal goal quaternion - * @param deltaTime current interpolation frame - * @param lerpTime total interpolation time - * @param result the smoothed quaternion - */ - static SmoothToRef(source, goal, deltaTime, lerpTime, result) { - let slerp = lerpTime === 0 ? 1 : deltaTime / lerpTime; - slerp = math_scalar_Scalar.Clamp(slerp, 0, 1); - math_vector_Quaternion.SlerpToRef(source, goal, slerp, result); - return result; - } - /** - * Creates an empty quaternion - * @returns a new quaternion set to (0.0, 0.0, 0.0) - */ - static Zero() { - return new math_vector_Quaternion(0.0, 0.0, 0.0, 0.0); - } - /** - * Inverse a given quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#103 - * @param q defines the source quaternion - * @returns a new quaternion as the inverted current quaternion - */ - static Inverse(q) { - return new q.constructor(-q._x, -q._y, -q._z, q._w); - } - /** - * Inverse a given quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#104 - * @param q defines the source quaternion - * @param result the quaternion the result will be stored in - * @returns the result quaternion - */ - static InverseToRef(q, result) { - result.set(-q._x, -q._y, -q._z, q._w); - return result; - } - /** - * Creates an identity quaternion - * @returns the identity quaternion - */ - static Identity() { - return new math_vector_Quaternion(0.0, 0.0, 0.0, 1.0); - } - /** - * Gets a boolean indicating if the given quaternion is identity - * @param quaternion defines the quaternion to check - * @returns true if the quaternion is identity - */ - static IsIdentity(quaternion) { - return quaternion && quaternion._x === 0 && quaternion._y === 0 && quaternion._z === 0 && quaternion._w === 1; - } - /** - * Creates a quaternion from a rotation around an axis - * Example Playground https://playground.babylonjs.com/#L49EJ7#72 - * @param axis defines the axis to use - * @param angle defines the angle to use - * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float) - */ - static RotationAxis(axis, angle) { - return math_vector_Quaternion.RotationAxisToRef(axis, angle, new math_vector_Quaternion()); - } - /** - * Creates a rotation around an axis and stores it into the given quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#73 - * @param axis defines the axis to use - * @param angle defines the angle to use - * @param result defines the target quaternion - * @returns the target quaternion - */ - static RotationAxisToRef(axis, angle, result) { - const sin = Math.sin(angle / 2); - axis.normalize(); - result._w = Math.cos(angle / 2); - result._x = axis._x * sin; - result._y = axis._y * sin; - result._z = axis._z * sin; - result._isDirty = true; - return result; - } - /** - * Creates a new quaternion from data stored into an array - * Example Playground https://playground.babylonjs.com/#L49EJ7#63 - * @param array defines the data source - * @param offset defines the offset in the source array where the data starts - * @returns a new quaternion - */ - static FromArray(array, offset) { - if (!offset) { - offset = 0; - } - return new math_vector_Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); - } - /** - * Updates the given quaternion "result" from the starting index of the given array. - * Example Playground https://playground.babylonjs.com/#L49EJ7#64 - * @param array the array to pull values from - * @param offset the offset into the array to start at - * @param result the quaternion to store the result in - * @returns result input - */ - static FromArrayToRef(array, offset, result) { - result._x = array[offset]; - result._y = array[offset + 1]; - result._z = array[offset + 2]; - result._w = array[offset + 3]; - result._isDirty = true; - return result; - } - /** - * Create a quaternion from Euler rotation angles - * Example Playground https://playground.babylonjs.com/#L49EJ7#33 - * @param x Pitch - * @param y Yaw - * @param z Roll - * @returns the new Quaternion - */ - static FromEulerAngles(x, y, z) { - const q = new math_vector_Quaternion(); - math_vector_Quaternion.RotationYawPitchRollToRef(y, x, z, q); - return q; - } - /** - * Updates a quaternion from Euler rotation angles - * Example Playground https://playground.babylonjs.com/#L49EJ7#34 - * @param x Pitch - * @param y Yaw - * @param z Roll - * @param result the quaternion to store the result - * @returns the updated quaternion - */ - static FromEulerAnglesToRef(x, y, z, result) { - math_vector_Quaternion.RotationYawPitchRollToRef(y, x, z, result); - return result; - } - /** - * Create a quaternion from Euler rotation vector - * Example Playground https://playground.babylonjs.com/#L49EJ7#35 - * @param vec the Euler vector (x Pitch, y Yaw, z Roll) - * @returns the new Quaternion - */ - static FromEulerVector(vec) { - const q = new math_vector_Quaternion(); - math_vector_Quaternion.RotationYawPitchRollToRef(vec._y, vec._x, vec._z, q); - return q; - } - /** - * Updates a quaternion from Euler rotation vector - * Example Playground https://playground.babylonjs.com/#L49EJ7#36 - * @param vec the Euler vector (x Pitch, y Yaw, z Roll) - * @param result the quaternion to store the result - * @returns the updated quaternion - */ - static FromEulerVectorToRef(vec, result) { - math_vector_Quaternion.RotationYawPitchRollToRef(vec._y, vec._x, vec._z, result); - return result; - } - /** - * Updates a quaternion so that it rotates vector vecFrom to vector vecTo - * Example Playground - https://playground.babylonjs.com/#L49EJ7#70 - * @param vecFrom defines the direction vector from which to rotate - * @param vecTo defines the direction vector to which to rotate - * @param result the quaternion to store the result - * @param epsilon defines the minimal dot value to define vecs as opposite. Default: `BABYLON.Epsilon` - * @returns the updated quaternion - */ - static FromUnitVectorsToRef(vecFrom, vecTo, result, epsilon = math_constants_Epsilon) { - const r = math_vector_Vector3.Dot(vecFrom, vecTo) + 1; - if (r < epsilon) { - if (Math.abs(vecFrom.x) > Math.abs(vecFrom.z)) { - result.set(-vecFrom.y, vecFrom.x, 0, 0); - } - else { - result.set(0, -vecFrom.z, vecFrom.y, 0); - } - } - else { - math_vector_Vector3.CrossToRef(vecFrom, vecTo, math_vector_TmpVectors.Vector3[0]); - result.set(math_vector_TmpVectors.Vector3[0].x, math_vector_TmpVectors.Vector3[0].y, math_vector_TmpVectors.Vector3[0].z, r); - } - return result.normalize(); - } - /** - * Creates a new quaternion from the given Euler float angles (y, x, z) - * Example Playground https://playground.babylonjs.com/#L49EJ7#77 - * @param yaw defines the rotation around Y axis - * @param pitch defines the rotation around X axis - * @param roll defines the rotation around Z axis - * @returns the new quaternion - */ - static RotationYawPitchRoll(yaw, pitch, roll) { - const q = new math_vector_Quaternion(); - math_vector_Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q); - return q; - } - /** - * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#78 - * @param yaw defines the rotation around Y axis - * @param pitch defines the rotation around X axis - * @param roll defines the rotation around Z axis - * @param result defines the target quaternion - * @returns result input - */ - static RotationYawPitchRollToRef(yaw, pitch, roll, result) { - // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles) - const halfRoll = roll * 0.5; - const halfPitch = pitch * 0.5; - const halfYaw = yaw * 0.5; - const sinRoll = Math.sin(halfRoll); - const cosRoll = Math.cos(halfRoll); - const sinPitch = Math.sin(halfPitch); - const cosPitch = Math.cos(halfPitch); - const sinYaw = Math.sin(halfYaw); - const cosYaw = Math.cos(halfYaw); - result._x = cosYaw * sinPitch * cosRoll + sinYaw * cosPitch * sinRoll; - result._y = sinYaw * cosPitch * cosRoll - cosYaw * sinPitch * sinRoll; - result._z = cosYaw * cosPitch * sinRoll - sinYaw * sinPitch * cosRoll; - result._w = cosYaw * cosPitch * cosRoll + sinYaw * sinPitch * sinRoll; - result._isDirty = true; - return result; - } - /** - * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation - * Example Playground https://playground.babylonjs.com/#L49EJ7#68 - * @param alpha defines the rotation around first axis - * @param beta defines the rotation around second axis - * @param gamma defines the rotation around third axis - * @returns the new quaternion - */ - static RotationAlphaBetaGamma(alpha, beta, gamma) { - const result = new math_vector_Quaternion(); - math_vector_Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result); - return result; - } - /** - * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#69 - * @param alpha defines the rotation around first axis - * @param beta defines the rotation around second axis - * @param gamma defines the rotation around third axis - * @param result defines the target quaternion - * @returns result input - */ - static RotationAlphaBetaGammaToRef(alpha, beta, gamma, result) { - // Produces a quaternion from Euler angles in the z-x-z orientation - const halfGammaPlusAlpha = (gamma + alpha) * 0.5; - const halfGammaMinusAlpha = (gamma - alpha) * 0.5; - const halfBeta = beta * 0.5; - result._x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta); - result._y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta); - result._z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta); - result._w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta); - result._isDirty = true; - return result; - } - /** - * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) - * Example Playground https://playground.babylonjs.com/#L49EJ7#75 - * @param axis1 defines the first axis - * @param axis2 defines the second axis - * @param axis3 defines the third axis - * @returns the new quaternion - */ - static RotationQuaternionFromAxis(axis1, axis2, axis3) { - const quat = new math_vector_Quaternion(0.0, 0.0, 0.0, 0.0); - math_vector_Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat); - return quat; - } - /** - * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#76 - * @param axis1 defines the first axis - * @param axis2 defines the second axis - * @param axis3 defines the third axis - * @param ref defines the target quaternion - * @returns result input - */ - static RotationQuaternionFromAxisToRef(axis1, axis2, axis3, ref) { - const rotMat = MathTmp.Matrix[0]; - math_vector_Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat); - math_vector_Quaternion.FromRotationMatrixToRef(rotMat, ref); - return ref; - } - /** - * Creates a new rotation value to orient an object to look towards the given forward direction, the up direction being oriented like "up". - * This function works in left handed mode - * Example Playground https://playground.babylonjs.com/#L49EJ7#96 - * @param forward defines the forward direction - Must be normalized and orthogonal to up. - * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. - * @returns A new quaternion oriented toward the specified forward and up. - */ - static FromLookDirectionLH(forward, up) { - const quat = new math_vector_Quaternion(); - math_vector_Quaternion.FromLookDirectionLHToRef(forward, up, quat); - return quat; - } - /** - * Creates a new rotation value to orient an object to look towards the given forward direction with the up direction being oriented like "up", and stores it in the target quaternion. - * This function works in left handed mode - * Example Playground https://playground.babylonjs.com/#L49EJ7#97 - * @param forward defines the forward direction - Must be normalized and orthogonal to up. - * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. - * @param ref defines the target quaternion. - * @returns result input - */ - static FromLookDirectionLHToRef(forward, up, ref) { - const rotMat = MathTmp.Matrix[0]; - math_vector_Matrix.LookDirectionLHToRef(forward, up, rotMat); - math_vector_Quaternion.FromRotationMatrixToRef(rotMat, ref); - return ref; - } - /** - * Creates a new rotation value to orient an object to look towards the given forward direction, the up direction being oriented like "up". - * This function works in right handed mode - * Example Playground https://playground.babylonjs.com/#L49EJ7#98 - * @param forward defines the forward direction - Must be normalized and orthogonal to up. - * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. - * @returns A new quaternion oriented toward the specified forward and up. - */ - static FromLookDirectionRH(forward, up) { - const quat = new math_vector_Quaternion(); - math_vector_Quaternion.FromLookDirectionRHToRef(forward, up, quat); - return quat; - } - /** - * Creates a new rotation value to orient an object to look towards the given forward direction with the up direction being oriented like "up", and stores it in the target quaternion. - * This function works in right handed mode - * Example Playground https://playground.babylonjs.com/#L49EJ7#105 - * @param forward defines the forward direction - Must be normalized and orthogonal to up. - * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. - * @param ref defines the target quaternion. - * @returns result input - */ - static FromLookDirectionRHToRef(forward, up, ref) { - const rotMat = MathTmp.Matrix[0]; - math_vector_Matrix.LookDirectionRHToRef(forward, up, rotMat); - return math_vector_Quaternion.FromRotationMatrixToRef(rotMat, ref); - } - /** - * Interpolates between two quaternions - * Example Playground https://playground.babylonjs.com/#L49EJ7#79 - * @param left defines first quaternion - * @param right defines second quaternion - * @param amount defines the gradient to use - * @returns the new interpolated quaternion - */ - static Slerp(left, right, amount) { - const result = math_vector_Quaternion.Identity(); - math_vector_Quaternion.SlerpToRef(left, right, amount, result); - return result; - } - /** - * Interpolates between two quaternions and stores it into a target quaternion - * Example Playground https://playground.babylonjs.com/#L49EJ7#92 - * @param left defines first quaternion - * @param right defines second quaternion - * @param amount defines the gradient to use - * @param result defines the target quaternion - * @returns result input - */ - static SlerpToRef(left, right, amount, result) { - let num2; - let num3; - let num4 = left._x * right._x + left._y * right._y + left._z * right._z + left._w * right._w; - let flag = false; - if (num4 < 0) { - flag = true; - num4 = -num4; - } - if (num4 > 0.999999) { - num3 = 1 - amount; - num2 = flag ? -amount : amount; - } - else { - const num5 = Math.acos(num4); - const num6 = 1.0 / Math.sin(num5); - num3 = Math.sin((1.0 - amount) * num5) * num6; - num2 = flag ? -Math.sin(amount * num5) * num6 : Math.sin(amount * num5) * num6; - } - result._x = num3 * left._x + num2 * right._x; - result._y = num3 * left._y + num2 * right._y; - result._z = num3 * left._z + num2 * right._z; - result._w = num3 * left._w + num2 * right._w; - result._isDirty = true; - return result; - } - /** - * Interpolate between two quaternions using Hermite interpolation - * Example Playground https://playground.babylonjs.com/#L49EJ7#47 - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#hermite-quaternion-spline - * @param value1 defines first quaternion - * @param tangent1 defines the incoming tangent - * @param value2 defines second quaternion - * @param tangent2 defines the outgoing tangent - * @param amount defines the target quaternion - * @returns the new interpolated quaternion - */ - static Hermite(value1, tangent1, value2, tangent2, amount) { - const squared = amount * amount; - const cubed = amount * squared; - const part1 = 2.0 * cubed - 3.0 * squared + 1.0; - const part2 = -2.0 * cubed + 3.0 * squared; - const part3 = cubed - 2.0 * squared + amount; - const part4 = cubed - squared; - const x = value1._x * part1 + value2._x * part2 + tangent1._x * part3 + tangent2._x * part4; - const y = value1._y * part1 + value2._y * part2 + tangent1._y * part3 + tangent2._y * part4; - const z = value1._z * part1 + value2._z * part2 + tangent1._z * part3 + tangent2._z * part4; - const w = value1._w * part1 + value2._w * part2 + tangent1._w * part3 + tangent2._w * part4; - return new value1.constructor(x, y, z, w); - } - /** - * Returns a new Quaternion which is the 1st derivative of the Hermite spline defined by the quaternions "value1", "value2", "tangent1", "tangent2". - * Example Playground https://playground.babylonjs.com/#L49EJ7#48 - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @returns 1st derivative - */ - static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { - const result = new value1.constructor(); - this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); - return result; - } - /** - * Update a Quaternion with the 1st derivative of the Hermite spline defined by the quaternions "value1", "value2", "tangent1", "tangent2". - * Example Playground https://playground.babylonjs.com/#L49EJ7#49 - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @param result define where to store the derivative - * @returns result input - */ - static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { - const t2 = time * time; - result._x = (t2 - time) * 6 * value1._x + (3 * t2 - 4 * time + 1) * tangent1._x + (-t2 + time) * 6 * value2._x + (3 * t2 - 2 * time) * tangent2._x; - result._y = (t2 - time) * 6 * value1._y + (3 * t2 - 4 * time + 1) * tangent1._y + (-t2 + time) * 6 * value2._y + (3 * t2 - 2 * time) * tangent2._y; - result._z = (t2 - time) * 6 * value1._z + (3 * t2 - 4 * time + 1) * tangent1._z + (-t2 + time) * 6 * value2._z + (3 * t2 - 2 * time) * tangent2._z; - result._w = (t2 - time) * 6 * value1._w + (3 * t2 - 4 * time + 1) * tangent1._w + (-t2 + time) * 6 * value2._w + (3 * t2 - 2 * time) * tangent2._w; - result._isDirty = true; - return result; - } -} -/** - * Class used to store matrix data (4x4) - * Note on matrix definitions in Babylon.js for setting values directly - * rather than using one of the methods available. - * Matrix size is given by rows x columns. - * A Vector3 is a 1 X 3 matrix [x, y, z]. - * - * In Babylon.js multiplying a 1 x 3 matrix by a 4 x 4 matrix - * is done using BABYLON.Vector4.TransformCoordinates(Vector3, Matrix). - * and extending the passed Vector3 to a Vector4, V = [x, y, z, 1]. - * Let M be a matrix with elements m(row, column), so that - * m(2, 3) is the element in row 2 column 3 of M. - * - * Multiplication is of the form VM and has the resulting Vector4 - * VM = [xm(0, 0) + ym(1, 0) + zm(2, 0) + m(3, 0), xm(0, 1) + ym(1, 1) + zm(2, 1) + m(3, 1), xm(0, 2) + ym(1, 2) + zm(2, 2) + m(3, 2), xm(0, 3) + ym(1, 3) + zm(2, 3) + m(3, 3)]. - * On the web you will find many examples that use the opposite convention of MV, - * in which case to make use of the examples you will need to transpose the matrix. - * - * Example Playground - Overview Linear Algebra - https://playground.babylonjs.com/#AV9X17 - * Example Playground - Overview Transformation - https://playground.babylonjs.com/#AV9X17#1 - * Example Playground - Overview Projection - https://playground.babylonjs.com/#AV9X17#2 - */ -class math_vector_Matrix { - /** - * Gets the precision of matrix computations - */ - static get Use64Bits() { - return performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits; - } - /** - * Gets the internal data of the matrix - */ - get m() { - return this._m; - } - /** - * Update the updateFlag to indicate that the matrix has been updated - */ - markAsUpdated() { - this.updateFlag = math_vector_Matrix._UpdateFlagSeed++; - this._isIdentity = false; - this._isIdentity3x2 = false; - this._isIdentityDirty = true; - this._isIdentity3x2Dirty = true; - } - _updateIdentityStatus(isIdentity, isIdentityDirty = false, isIdentity3x2 = false, isIdentity3x2Dirty = true) { - this._isIdentity = isIdentity; - this._isIdentity3x2 = isIdentity || isIdentity3x2; - this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty; - this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty; - } - /** - * Creates an empty matrix (filled with zeros) - */ - constructor() { - this._isIdentity = false; - this._isIdentityDirty = true; - this._isIdentity3x2 = true; - this._isIdentity3x2Dirty = true; - /** - * Gets the update flag of the matrix which is an unique number for the matrix. - * It will be incremented every time the matrix data change. - * You can use it to speed the comparison between two versions of the same matrix. - */ - this.updateFlag = -1; - if (performanceConfigurator_PerformanceConfigurator.MatrixTrackPrecisionChange) { - performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices.push(this); - } - this._m = new performanceConfigurator_PerformanceConfigurator.MatrixCurrentType(16); - this.markAsUpdated(); - } - // Properties - /** - * Check if the current matrix is identity - * @returns true is the matrix is the identity matrix - */ - isIdentity() { - if (this._isIdentityDirty) { - this._isIdentityDirty = false; - const m = this._m; - this._isIdentity = - m[0] === 1.0 && - m[1] === 0.0 && - m[2] === 0.0 && - m[3] === 0.0 && - m[4] === 0.0 && - m[5] === 1.0 && - m[6] === 0.0 && - m[7] === 0.0 && - m[8] === 0.0 && - m[9] === 0.0 && - m[10] === 1.0 && - m[11] === 0.0 && - m[12] === 0.0 && - m[13] === 0.0 && - m[14] === 0.0 && - m[15] === 1.0; - } - return this._isIdentity; - } - /** - * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4) - * @returns true is the matrix is the identity matrix - */ - isIdentityAs3x2() { - if (this._isIdentity3x2Dirty) { - this._isIdentity3x2Dirty = false; - if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) { - this._isIdentity3x2 = false; - } - else if (this._m[1] !== 0.0 || - this._m[2] !== 0.0 || - this._m[3] !== 0.0 || - this._m[4] !== 0.0 || - this._m[6] !== 0.0 || - this._m[7] !== 0.0 || - this._m[8] !== 0.0 || - this._m[9] !== 0.0 || - this._m[10] !== 0.0 || - this._m[11] !== 0.0 || - this._m[12] !== 0.0 || - this._m[13] !== 0.0 || - this._m[14] !== 0.0) { - this._isIdentity3x2 = false; - } - else { - this._isIdentity3x2 = true; - } - } - return this._isIdentity3x2; - } - /** - * Gets the determinant of the matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#34 - * @returns the matrix determinant - */ - determinant() { - if (this._isIdentity === true) { - return 1; - } - const m = this._m; - const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3]; - const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7]; - const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11]; - const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15]; - // https://en.wikipedia.org/wiki/Laplace_expansion - // to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column, - // then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant - // Cofactor(i, j) = sign(i,j) * det(Minor(i, j)) - // where - // - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1 - // - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix - // - // Here we do that for the 1st row. - const det_22_33 = m22 * m33 - m32 * m23; - const det_21_33 = m21 * m33 - m31 * m23; - const det_21_32 = m21 * m32 - m31 * m22; - const det_20_33 = m20 * m33 - m30 * m23; - const det_20_32 = m20 * m32 - m22 * m30; - const det_20_31 = m20 * m31 - m30 * m21; - const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32); - const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32); - const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31); - const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31); - return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03; - } - // Methods - /** - * Returns the matrix as a Float32Array or Array<number> - * Example Playground - https://playground.babylonjs.com/#AV9X17#49 - * @returns the matrix underlying array - */ - toArray() { - return this._m; - } - /** - * Returns the matrix as a Float32Array or Array<number> - * Example Playground - https://playground.babylonjs.com/#AV9X17#114 - * @returns the matrix underlying array. - */ - asArray() { - return this._m; - } - /** - * Inverts the current matrix in place - * Example Playground - https://playground.babylonjs.com/#AV9X17#118 - * @returns the current inverted matrix - */ - invert() { - this.invertToRef(this); - return this; - } - /** - * Sets all the matrix elements to zero - * @returns the current matrix - */ - reset() { - math_vector_Matrix.FromValuesToRef(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, this); - this._updateIdentityStatus(false); - return this; - } - /** - * Adds the current matrix with a second one - * Example Playground - https://playground.babylonjs.com/#AV9X17#44 - * @param other defines the matrix to add - * @returns a new matrix as the addition of the current matrix and the given one - */ - add(other) { - const result = new this.constructor(); - this.addToRef(other, result); - return result; - } - /** - * Sets the given matrix "result" to the addition of the current matrix and the given one - * Example Playground - https://playground.babylonjs.com/#AV9X17#45 - * @param other defines the matrix to add - * @param result defines the target matrix - * @returns result input - */ - addToRef(other, result) { - const m = this._m; - const resultM = result._m; - const otherM = other.m; - for (let index = 0; index < 16; index++) { - resultM[index] = m[index] + otherM[index]; - } - result.markAsUpdated(); - return result; - } - /** - * Adds in place the given matrix to the current matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#46 - * @param other defines the second operand - * @returns the current updated matrix - */ - addToSelf(other) { - const m = this._m; - const otherM = other.m; - for (let index = 0; index < 16; index++) { - m[index] += otherM[index]; - } - this.markAsUpdated(); - return this; - } - /** - * Sets the given matrix to the current inverted Matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#119 - * @param other defines the target matrix - * @returns result input - */ - invertToRef(other) { - if (this._isIdentity === true) { - math_vector_Matrix.IdentityToRef(other); - return other; - } - // the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant - const m = this._m; - const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3]; - const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7]; - const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11]; - const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15]; - const det_22_33 = m22 * m33 - m32 * m23; - const det_21_33 = m21 * m33 - m31 * m23; - const det_21_32 = m21 * m32 - m31 * m22; - const det_20_33 = m20 * m33 - m30 * m23; - const det_20_32 = m20 * m32 - m22 * m30; - const det_20_31 = m20 * m31 - m30 * m21; - const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32); - const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32); - const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31); - const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31); - const det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03; - if (det === 0) { - // not invertible - other.copyFrom(this); - return other; - } - const detInv = 1 / det; - const det_12_33 = m12 * m33 - m32 * m13; - const det_11_33 = m11 * m33 - m31 * m13; - const det_11_32 = m11 * m32 - m31 * m12; - const det_10_33 = m10 * m33 - m30 * m13; - const det_10_32 = m10 * m32 - m30 * m12; - const det_10_31 = m10 * m31 - m30 * m11; - const det_12_23 = m12 * m23 - m22 * m13; - const det_11_23 = m11 * m23 - m21 * m13; - const det_11_22 = m11 * m22 - m21 * m12; - const det_10_23 = m10 * m23 - m20 * m13; - const det_10_22 = m10 * m22 - m20 * m12; - const det_10_21 = m10 * m21 - m20 * m11; - const cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32); - const cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32); - const cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31); - const cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31); - const cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32); - const cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32); - const cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31); - const cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31); - const cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22); - const cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22); - const cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21); - const cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21); - math_vector_Matrix.FromValuesToRef(cofact_00 * detInv, cofact_10 * detInv, cofact_20 * detInv, cofact_30 * detInv, cofact_01 * detInv, cofact_11 * detInv, cofact_21 * detInv, cofact_31 * detInv, cofact_02 * detInv, cofact_12 * detInv, cofact_22 * detInv, cofact_32 * detInv, cofact_03 * detInv, cofact_13 * detInv, cofact_23 * detInv, cofact_33 * detInv, other); - return other; - } - /** - * add a value at the specified position in the current Matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#47 - * @param index the index of the value within the matrix. between 0 and 15. - * @param value the value to be added - * @returns the current updated matrix - */ - addAtIndex(index, value) { - this._m[index] += value; - this.markAsUpdated(); - return this; - } - /** - * mutiply the specified position in the current Matrix by a value - * @param index the index of the value within the matrix. between 0 and 15. - * @param value the value to be added - * @returns the current updated matrix - */ - multiplyAtIndex(index, value) { - this._m[index] *= value; - this.markAsUpdated(); - return this; - } - /** - * Inserts the translation vector (using 3 floats) in the current matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#120 - * @param x defines the 1st component of the translation - * @param y defines the 2nd component of the translation - * @param z defines the 3rd component of the translation - * @returns the current updated matrix - */ - setTranslationFromFloats(x, y, z) { - this._m[12] = x; - this._m[13] = y; - this._m[14] = z; - this.markAsUpdated(); - return this; - } - /** - * Adds the translation vector (using 3 floats) in the current matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#20 - * Example Playground - https://playground.babylonjs.com/#AV9X17#48 - * @param x defines the 1st component of the translation - * @param y defines the 2nd component of the translation - * @param z defines the 3rd component of the translation - * @returns the current updated matrix - */ - addTranslationFromFloats(x, y, z) { - this._m[12] += x; - this._m[13] += y; - this._m[14] += z; - this.markAsUpdated(); - return this; - } - /** - * Inserts the translation vector in the current matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#121 - * @param vector3 defines the translation to insert - * @returns the current updated matrix - */ - setTranslation(vector3) { - return this.setTranslationFromFloats(vector3._x, vector3._y, vector3._z); - } - /** - * Gets the translation value of the current matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#122 - * @returns a new Vector3 as the extracted translation from the matrix - */ - getTranslation() { - return new math_vector_Vector3(this._m[12], this._m[13], this._m[14]); - } - /** - * Fill a Vector3 with the extracted translation from the matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#123 - * @param result defines the Vector3 where to store the translation - * @returns the current matrix - */ - getTranslationToRef(result) { - result.x = this._m[12]; - result.y = this._m[13]; - result.z = this._m[14]; - return result; - } - /** - * Remove rotation and scaling part from the matrix - * @returns the updated matrix - */ - removeRotationAndScaling() { - const m = this.m; - math_vector_Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, m[12], m[13], m[14], m[15], this); - this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1); - return this; - } - /** - * Multiply two matrices - * Example Playground - https://playground.babylonjs.com/#AV9X17#15 - * A.multiply(B) means apply B to A so result is B x A - * @param other defines the second operand - * @returns a new matrix set with the multiplication result of the current Matrix and the given one - */ - multiply(other) { - const result = new this.constructor(); - this.multiplyToRef(other, result); - return result; - } - /** - * Copy the current matrix from the given one - * Example Playground - https://playground.babylonjs.com/#AV9X17#21 - * @param other defines the source matrix - * @returns the current updated matrix - */ - copyFrom(other) { - other.copyToArray(this._m); - const o = other; - this.updateFlag = o.updateFlag; - this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty); - return this; - } - /** - * Populates the given array from the starting index with the current matrix values - * @param array defines the target array - * @param offset defines the offset in the target array where to start storing values - * @returns the current matrix - */ - copyToArray(array, offset = 0) { - const source = this._m; - array[offset] = source[0]; - array[offset + 1] = source[1]; - array[offset + 2] = source[2]; - array[offset + 3] = source[3]; - array[offset + 4] = source[4]; - array[offset + 5] = source[5]; - array[offset + 6] = source[6]; - array[offset + 7] = source[7]; - array[offset + 8] = source[8]; - array[offset + 9] = source[9]; - array[offset + 10] = source[10]; - array[offset + 11] = source[11]; - array[offset + 12] = source[12]; - array[offset + 13] = source[13]; - array[offset + 14] = source[14]; - array[offset + 15] = source[15]; - return this; - } - /** - * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one - * A.multiplyToRef(B, R) means apply B to A and store in R and R = B x A - * Example Playground - https://playground.babylonjs.com/#AV9X17#16 - * @param other defines the second operand - * @param result defines the matrix where to store the multiplication - * @returns result input - */ - multiplyToRef(other, result) { - if (this._isIdentity) { - result.copyFrom(other); - return result; - } - if (other._isIdentity) { - result.copyFrom(this); - return result; - } - this.multiplyToArray(other, result._m, 0); - result.markAsUpdated(); - return result; - } - /** - * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one - * @param other defines the second operand - * @param result defines the array where to store the multiplication - * @param offset defines the offset in the target array where to start storing values - * @returns the current matrix - */ - multiplyToArray(other, result, offset) { - const m = this._m; - const otherM = other.m; - const tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3]; - const tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7]; - const tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11]; - const tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15]; - const om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3]; - const om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7]; - const om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11]; - const om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15]; - result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12; - result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13; - result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14; - result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15; - result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12; - result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13; - result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14; - result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15; - result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12; - result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13; - result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14; - result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15; - result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12; - result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13; - result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14; - result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15; - return this; - } - /** - * Check equality between this matrix and a second one - * @param value defines the second matrix to compare - * @returns true is the current matrix and the given one values are strictly equal - */ - equals(value) { - const other = value; - if (!other) { - return false; - } - if (this._isIdentity || other._isIdentity) { - if (!this._isIdentityDirty && !other._isIdentityDirty) { - return this._isIdentity && other._isIdentity; - } - } - const m = this.m; - const om = other.m; - return (m[0] === om[0] && - m[1] === om[1] && - m[2] === om[2] && - m[3] === om[3] && - m[4] === om[4] && - m[5] === om[5] && - m[6] === om[6] && - m[7] === om[7] && - m[8] === om[8] && - m[9] === om[9] && - m[10] === om[10] && - m[11] === om[11] && - m[12] === om[12] && - m[13] === om[13] && - m[14] === om[14] && - m[15] === om[15]); - } - /** - * Clone the current matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#18 - * @returns a new matrix from the current matrix - */ - clone() { - const matrix = new this.constructor(); - matrix.copyFrom(this); - return matrix; - } - /** - * Returns the name of the current matrix class - * @returns the string "Matrix" - */ - getClassName() { - return "Matrix"; - } - /** - * Gets the hash code of the current matrix - * @returns the hash code - */ - getHashCode() { - let hash = _ExtractAsInt(this._m[0]); - for (let i = 1; i < 16; i++) { - hash = (hash * 397) ^ _ExtractAsInt(this._m[i]); - } - return hash; - } - /** - * Decomposes the current Matrix into a translation, rotation and scaling components of the provided node - * Example Playground - https://playground.babylonjs.com/#AV9X17#13 - * @param node the node to decompose the matrix to - * @returns true if operation was successful - */ - decomposeToTransformNode(node) { - node.rotationQuaternion = node.rotationQuaternion || new math_vector_Quaternion(); - return this.decompose(node.scaling, node.rotationQuaternion, node.position); - } - /** - * Decomposes the current Matrix into a translation, rotation and scaling components - * Example Playground - https://playground.babylonjs.com/#AV9X17#12 - * @param scale defines the scale vector3 given as a reference to update - * @param rotation defines the rotation quaternion given as a reference to update - * @param translation defines the translation vector3 given as a reference to update - * @param preserveScalingNode Use scaling sign coming from this node. Otherwise scaling sign might change. - * @returns true if operation was successful - */ - decompose(scale, rotation, translation, preserveScalingNode) { - if (this._isIdentity) { - if (translation) { - translation.setAll(0); - } - if (scale) { - scale.setAll(1); - } - if (rotation) { - rotation.copyFromFloats(0, 0, 0, 1); - } - return true; - } - const m = this._m; - if (translation) { - translation.copyFromFloats(m[12], m[13], m[14]); - } - scale = scale || MathTmp.Vector3[0]; - scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]); - scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]); - scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]); - if (preserveScalingNode) { - const signX = preserveScalingNode.scaling.x < 0 ? -1 : 1; - const signY = preserveScalingNode.scaling.y < 0 ? -1 : 1; - const signZ = preserveScalingNode.scaling.z < 0 ? -1 : 1; - scale.x *= signX; - scale.y *= signY; - scale.z *= signZ; - } - else { - if (this.determinant() <= 0) { - scale.y *= -1; - } - } - if (scale._x === 0 || scale._y === 0 || scale._z === 0) { - if (rotation) { - rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0); - } - return false; - } - if (rotation) { - const sx = 1 / scale._x, sy = 1 / scale._y, sz = 1 / scale._z; - math_vector_Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, MathTmp.Matrix[0]); - math_vector_Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation); - } - return true; - } - /** - * Gets specific row of the matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#36 - * @param index defines the number of the row to get - * @returns the index-th row of the current matrix as a new Vector4 - */ - getRow(index) { - if (index < 0 || index > 3) { - return null; - } - const i = index * 4; - return new math_vector_Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]); - } - /** - * Gets specific row of the matrix to ref - * Example Playground - https://playground.babylonjs.com/#AV9X17#36 - * @param index defines the number of the row to get - * @param rowVector vector to store the index-th row of the current matrix - * @returns result input - */ - getRowToRef(index, rowVector) { - if (index >= 0 && index < 3) { - const i = index * 4; - rowVector.x = this._m[i + 0]; - rowVector.y = this._m[i + 1]; - rowVector.z = this._m[i + 2]; - rowVector.w = this._m[i + 3]; - } - return rowVector; - } - /** - * Sets the index-th row of the current matrix to the vector4 values - * Example Playground - https://playground.babylonjs.com/#AV9X17#36 - * @param index defines the number of the row to set - * @param row defines the target vector4 - * @returns the updated current matrix - */ - setRow(index, row) { - return this.setRowFromFloats(index, row.x, row.y, row.z, row.w); - } - /** - * Compute the transpose of the matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#40 - * @returns the new transposed matrix - */ - transpose() { - const result = new this.constructor(); - math_vector_Matrix.TransposeToRef(this, result); - return result; - } - /** - * Compute the transpose of the matrix and store it in a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#41 - * @param result defines the target matrix - * @returns result input - */ - transposeToRef(result) { - math_vector_Matrix.TransposeToRef(this, result); - return result; - } - /** - * Sets the index-th row of the current matrix with the given 4 x float values - * Example Playground - https://playground.babylonjs.com/#AV9X17#36 - * @param index defines the row index - * @param x defines the x component to set - * @param y defines the y component to set - * @param z defines the z component to set - * @param w defines the w component to set - * @returns the updated current matrix - */ - setRowFromFloats(index, x, y, z, w) { - if (index < 0 || index > 3) { - return this; - } - const i = index * 4; - this._m[i + 0] = x; - this._m[i + 1] = y; - this._m[i + 2] = z; - this._m[i + 3] = w; - this.markAsUpdated(); - return this; - } - /** - * Compute a new matrix set with the current matrix values multiplied by scale (float) - * @param scale defines the scale factor - * @returns a new matrix - */ - scale(scale) { - const result = new this.constructor(); - this.scaleToRef(scale, result); - return result; - } - /** - * Scale the current matrix values by a factor to a given result matrix - * @param scale defines the scale factor - * @param result defines the matrix to store the result - * @returns result input - */ - scaleToRef(scale, result) { - for (let index = 0; index < 16; index++) { - result._m[index] = this._m[index] * scale; - } - result.markAsUpdated(); - return result; - } - /** - * Scale the current matrix values by a factor and add the result to a given matrix - * @param scale defines the scale factor - * @param result defines the Matrix to store the result - * @returns result input - */ - scaleAndAddToRef(scale, result) { - for (let index = 0; index < 16; index++) { - result._m[index] += this._m[index] * scale; - } - result.markAsUpdated(); - return result; - } - /** - * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column). - * Example Playground - https://playground.babylonjs.com/#AV9X17#17 - * @param ref matrix to store the result - */ - toNormalMatrix(ref) { - const tmp = MathTmp.Matrix[0]; - this.invertToRef(tmp); - tmp.transposeToRef(ref); - const m = ref._m; - math_vector_Matrix.FromValuesToRef(m[0], m[1], m[2], 0.0, m[4], m[5], m[6], 0.0, m[8], m[9], m[10], 0.0, 0.0, 0.0, 0.0, 1.0, ref); - return ref; - } - /** - * Gets only rotation part of the current matrix - * @returns a new matrix sets to the extracted rotation matrix from the current one - */ - getRotationMatrix() { - const result = new this.constructor(); - this.getRotationMatrixToRef(result); - return result; - } - /** - * Extracts the rotation matrix from the current one and sets it as the given "result" - * @param result defines the target matrix to store data to - * @returns result input - */ - getRotationMatrixToRef(result) { - const scale = MathTmp.Vector3[0]; - if (!this.decompose(scale)) { - math_vector_Matrix.IdentityToRef(result); - return result; - } - const m = this._m; - const sx = 1 / scale._x, sy = 1 / scale._y, sz = 1 / scale._z; - math_vector_Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0.0, m[4] * sy, m[5] * sy, m[6] * sy, 0.0, m[8] * sz, m[9] * sz, m[10] * sz, 0.0, 0.0, 0.0, 0.0, 1.0, result); - return result; - } - /** - * Toggles model matrix from being right handed to left handed in place and vice versa - */ - toggleModelMatrixHandInPlace() { - const m = this._m; - m[2] *= -1; - m[6] *= -1; - m[8] *= -1; - m[9] *= -1; - m[14] *= -1; - this.markAsUpdated(); - return this; - } - /** - * Toggles projection matrix from being right handed to left handed in place and vice versa - */ - toggleProjectionMatrixHandInPlace() { - const m = this._m; - m[8] *= -1; - m[9] *= -1; - m[10] *= -1; - m[11] *= -1; - this.markAsUpdated(); - return this; - } - // Statics - /** - * Creates a matrix from an array - * Example Playground - https://playground.babylonjs.com/#AV9X17#42 - * @param array defines the source array - * @param offset defines an offset in the source array - * @returns a new Matrix set from the starting index of the given array - */ - static FromArray(array, offset = 0) { - const result = new math_vector_Matrix(); - math_vector_Matrix.FromArrayToRef(array, offset, result); - return result; - } - /** - * Copy the content of an array into a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#43 - * @param array defines the source array - * @param offset defines an offset in the source array - * @param result defines the target matrix - * @returns result input - */ - static FromArrayToRef(array, offset, result) { - for (let index = 0; index < 16; index++) { - result._m[index] = array[index + offset]; - } - result.markAsUpdated(); - return result; - } - /** - * Stores an array into a matrix after having multiplied each component by a given factor - * Example Playground - https://playground.babylonjs.com/#AV9X17#50 - * @param array defines the source array - * @param offset defines the offset in the source array - * @param scale defines the scaling factor - * @param result defines the target matrix - * @returns result input - */ - static FromFloat32ArrayToRefScaled(array, offset, scale, result) { - for (let index = 0; index < 16; index++) { - result._m[index] = array[index + offset] * scale; - } - result.markAsUpdated(); - return result; - } - /** - * Gets an identity matrix that must not be updated - */ - static get IdentityReadOnly() { - return math_vector_Matrix._IdentityReadOnly; - } - /** - * Stores a list of values (16) inside a given matrix - * @param initialM11 defines 1st value of 1st row - * @param initialM12 defines 2nd value of 1st row - * @param initialM13 defines 3rd value of 1st row - * @param initialM14 defines 4th value of 1st row - * @param initialM21 defines 1st value of 2nd row - * @param initialM22 defines 2nd value of 2nd row - * @param initialM23 defines 3rd value of 2nd row - * @param initialM24 defines 4th value of 2nd row - * @param initialM31 defines 1st value of 3rd row - * @param initialM32 defines 2nd value of 3rd row - * @param initialM33 defines 3rd value of 3rd row - * @param initialM34 defines 4th value of 3rd row - * @param initialM41 defines 1st value of 4th row - * @param initialM42 defines 2nd value of 4th row - * @param initialM43 defines 3rd value of 4th row - * @param initialM44 defines 4th value of 4th row - * @param result defines the target matrix - * @returns result input - */ - static FromValuesToRef(initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) { - const m = result._m; - m[0] = initialM11; - m[1] = initialM12; - m[2] = initialM13; - m[3] = initialM14; - m[4] = initialM21; - m[5] = initialM22; - m[6] = initialM23; - m[7] = initialM24; - m[8] = initialM31; - m[9] = initialM32; - m[10] = initialM33; - m[11] = initialM34; - m[12] = initialM41; - m[13] = initialM42; - m[14] = initialM43; - m[15] = initialM44; - result.markAsUpdated(); - } - /** - * Creates new matrix from a list of values (16) - * @param initialM11 defines 1st value of 1st row - * @param initialM12 defines 2nd value of 1st row - * @param initialM13 defines 3rd value of 1st row - * @param initialM14 defines 4th value of 1st row - * @param initialM21 defines 1st value of 2nd row - * @param initialM22 defines 2nd value of 2nd row - * @param initialM23 defines 3rd value of 2nd row - * @param initialM24 defines 4th value of 2nd row - * @param initialM31 defines 1st value of 3rd row - * @param initialM32 defines 2nd value of 3rd row - * @param initialM33 defines 3rd value of 3rd row - * @param initialM34 defines 4th value of 3rd row - * @param initialM41 defines 1st value of 4th row - * @param initialM42 defines 2nd value of 4th row - * @param initialM43 defines 3rd value of 4th row - * @param initialM44 defines 4th value of 4th row - * @returns the new matrix - */ - static FromValues(initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) { - const result = new math_vector_Matrix(); - const m = result._m; - m[0] = initialM11; - m[1] = initialM12; - m[2] = initialM13; - m[3] = initialM14; - m[4] = initialM21; - m[5] = initialM22; - m[6] = initialM23; - m[7] = initialM24; - m[8] = initialM31; - m[9] = initialM32; - m[10] = initialM33; - m[11] = initialM34; - m[12] = initialM41; - m[13] = initialM42; - m[14] = initialM43; - m[15] = initialM44; - result.markAsUpdated(); - return result; - } - /** - * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3) - * Example Playground - https://playground.babylonjs.com/#AV9X17#24 - * @param scale defines the scale vector3 - * @param rotation defines the rotation quaternion - * @param translation defines the translation vector3 - * @returns a new matrix - */ - static Compose(scale, rotation, translation) { - const result = new math_vector_Matrix(); - math_vector_Matrix.ComposeToRef(scale, rotation, translation, result); - return result; - } - /** - * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3) - * Example Playground - https://playground.babylonjs.com/#AV9X17#25 - * @param scale defines the scale vector3 - * @param rotation defines the rotation quaternion - * @param translation defines the translation vector3 - * @param result defines the target matrix - * @returns result input - */ - static ComposeToRef(scale, rotation, translation, result) { - const m = result._m; - const x = rotation._x, y = rotation._y, z = rotation._z, w = rotation._w; - const x2 = x + x, y2 = y + y, z2 = z + z; - const xx = x * x2, xy = x * y2, xz = x * z2; - const yy = y * y2, yz = y * z2, zz = z * z2; - const wx = w * x2, wy = w * y2, wz = w * z2; - const sx = scale._x, sy = scale._y, sz = scale._z; - m[0] = (1 - (yy + zz)) * sx; - m[1] = (xy + wz) * sx; - m[2] = (xz - wy) * sx; - m[3] = 0; - m[4] = (xy - wz) * sy; - m[5] = (1 - (xx + zz)) * sy; - m[6] = (yz + wx) * sy; - m[7] = 0; - m[8] = (xz + wy) * sz; - m[9] = (yz - wx) * sz; - m[10] = (1 - (xx + yy)) * sz; - m[11] = 0; - m[12] = translation._x; - m[13] = translation._y; - m[14] = translation._z; - m[15] = 1; - result.markAsUpdated(); - return result; - } - /** - * Creates a new identity matrix - * @returns a new identity matrix - */ - static Identity() { - const identity = math_vector_Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); - identity._updateIdentityStatus(true); - return identity; - } - /** - * Creates a new identity matrix and stores the result in a given matrix - * @param result defines the target matrix - * @returns result input - */ - static IdentityToRef(result) { - math_vector_Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result); - result._updateIdentityStatus(true); - return result; - } - /** - * Creates a new zero matrix - * @returns a new zero matrix - */ - static Zero() { - const zero = math_vector_Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); - zero._updateIdentityStatus(false); - return zero; - } - /** - * Creates a new rotation matrix for "angle" radians around the X axis - * Example Playground - https://playground.babylonjs.com/#AV9X17#97 - * @param angle defines the angle (in radians) to use - * @returns the new matrix - */ - static RotationX(angle) { - const result = new math_vector_Matrix(); - math_vector_Matrix.RotationXToRef(angle, result); - return result; - } - /** - * Creates a new matrix as the invert of a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#124 - * @param source defines the source matrix - * @returns the new matrix - */ - static Invert(source) { - const result = new source.constructor(); - source.invertToRef(result); - return result; - } - /** - * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#98 - * @param angle defines the angle (in radians) to use - * @param result defines the target matrix - * @returns result input - */ - static RotationXToRef(angle, result) { - const s = Math.sin(angle); - const c = Math.cos(angle); - math_vector_Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, result); - result._updateIdentityStatus(c === 1 && s === 0); - return result; - } - /** - * Creates a new rotation matrix for "angle" radians around the Y axis - * Example Playground - https://playground.babylonjs.com/#AV9X17#99 - * @param angle defines the angle (in radians) to use - * @returns the new matrix - */ - static RotationY(angle) { - const result = new math_vector_Matrix(); - math_vector_Matrix.RotationYToRef(angle, result); - return result; - } - /** - * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#100 - * @param angle defines the angle (in radians) to use - * @param result defines the target matrix - * @returns result input - */ - static RotationYToRef(angle, result) { - const s = Math.sin(angle); - const c = Math.cos(angle); - math_vector_Matrix.FromValuesToRef(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0, result); - result._updateIdentityStatus(c === 1 && s === 0); - return result; - } - /** - * Creates a new rotation matrix for "angle" radians around the Z axis - * Example Playground - https://playground.babylonjs.com/#AV9X17#101 - * @param angle defines the angle (in radians) to use - * @returns the new matrix - */ - static RotationZ(angle) { - const result = new math_vector_Matrix(); - math_vector_Matrix.RotationZToRef(angle, result); - return result; - } - /** - * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#102 - * @param angle defines the angle (in radians) to use - * @param result defines the target matrix - * @returns result input - */ - static RotationZToRef(angle, result) { - const s = Math.sin(angle); - const c = Math.cos(angle); - math_vector_Matrix.FromValuesToRef(c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result); - result._updateIdentityStatus(c === 1 && s === 0); - return result; - } - /** - * Creates a new rotation matrix for "angle" radians around the given axis - * Example Playground - https://playground.babylonjs.com/#AV9X17#96 - * @param axis defines the axis to use - * @param angle defines the angle (in radians) to use - * @returns the new matrix - */ - static RotationAxis(axis, angle) { - const result = new math_vector_Matrix(); - math_vector_Matrix.RotationAxisToRef(axis, angle, result); - return result; - } - /** - * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#94 - * @param axis defines the axis to use - * @param angle defines the angle (in radians) to use - * @param result defines the target matrix - * @returns result input - */ - static RotationAxisToRef(axis, angle, result) { - const s = Math.sin(-angle); - const c = Math.cos(-angle); - const c1 = 1 - c; - axis.normalize(); - const m = result._m; - m[0] = axis._x * axis._x * c1 + c; - m[1] = axis._x * axis._y * c1 - axis._z * s; - m[2] = axis._x * axis._z * c1 + axis._y * s; - m[3] = 0.0; - m[4] = axis._y * axis._x * c1 + axis._z * s; - m[5] = axis._y * axis._y * c1 + c; - m[6] = axis._y * axis._z * c1 - axis._x * s; - m[7] = 0.0; - m[8] = axis._z * axis._x * c1 - axis._y * s; - m[9] = axis._z * axis._y * c1 + axis._x * s; - m[10] = axis._z * axis._z * c1 + c; - m[11] = 0.0; - m[12] = 0.0; - m[13] = 0.0; - m[14] = 0.0; - m[15] = 1.0; - result.markAsUpdated(); - return result; - } - /** - * Takes normalised vectors and returns a rotation matrix to align "from" with "to". - * Taken from http://www.iquilezles.org/www/articles/noacos/noacos.htm - * Example Playground - https://playground.babylonjs.com/#AV9X17#93 - * @param from defines the vector to align - * @param to defines the vector to align to - * @param result defines the target matrix - * @returns result input - */ - static RotationAlignToRef(from, to, result) { - const c = math_vector_Vector3.Dot(to, from); - const m = result._m; - if (c < -1 + math_constants_Epsilon) { - // from and to are colinear and opposite direction. - // compute a PI rotation on Z axis - m[0] = -1; - m[1] = 0; - m[2] = 0; - m[3] = 0; - m[4] = 0; - m[5] = -1; - m[6] = 0; - m[7] = 0; - m[8] = 0; - m[9] = 0; - m[10] = 1; - m[11] = 0; - } - else { - const v = math_vector_Vector3.Cross(to, from); - const k = 1 / (1 + c); - m[0] = v._x * v._x * k + c; - m[1] = v._y * v._x * k - v._z; - m[2] = v._z * v._x * k + v._y; - m[3] = 0; - m[4] = v._x * v._y * k + v._z; - m[5] = v._y * v._y * k + c; - m[6] = v._z * v._y * k - v._x; - m[7] = 0; - m[8] = v._x * v._z * k - v._y; - m[9] = v._y * v._z * k + v._x; - m[10] = v._z * v._z * k + c; - m[11] = 0; - } - m[12] = 0; - m[13] = 0; - m[14] = 0; - m[15] = 1; - result.markAsUpdated(); - return result; - } - /** - * Creates a rotation matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#103 - * Example Playground - https://playground.babylonjs.com/#AV9X17#105 - * @param yaw defines the yaw angle in radians (Y axis) - * @param pitch defines the pitch angle in radians (X axis) - * @param roll defines the roll angle in radians (Z axis) - * @returns the new rotation matrix - */ - static RotationYawPitchRoll(yaw, pitch, roll) { - const result = new math_vector_Matrix(); - math_vector_Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result); - return result; - } - /** - * Creates a rotation matrix and stores it in a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#104 - * @param yaw defines the yaw angle in radians (Y axis) - * @param pitch defines the pitch angle in radians (X axis) - * @param roll defines the roll angle in radians (Z axis) - * @param result defines the target matrix - * @returns result input - */ - static RotationYawPitchRollToRef(yaw, pitch, roll, result) { - math_vector_Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]); - MathTmp.Quaternion[0].toRotationMatrix(result); - return result; - } - /** - * Creates a scaling matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#107 - * @param x defines the scale factor on X axis - * @param y defines the scale factor on Y axis - * @param z defines the scale factor on Z axis - * @returns the new matrix - */ - static Scaling(x, y, z) { - const result = new math_vector_Matrix(); - math_vector_Matrix.ScalingToRef(x, y, z, result); - return result; - } - /** - * Creates a scaling matrix and stores it in a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#108 - * @param x defines the scale factor on X axis - * @param y defines the scale factor on Y axis - * @param z defines the scale factor on Z axis - * @param result defines the target matrix - * @returns result input - */ - static ScalingToRef(x, y, z, result) { - math_vector_Matrix.FromValuesToRef(x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0, result); - result._updateIdentityStatus(x === 1 && y === 1 && z === 1); - return result; - } - /** - * Creates a translation matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#109 - * @param x defines the translation on X axis - * @param y defines the translation on Y axis - * @param z defines the translationon Z axis - * @returns the new matrix - */ - static Translation(x, y, z) { - const result = new math_vector_Matrix(); - math_vector_Matrix.TranslationToRef(x, y, z, result); - return result; - } - /** - * Creates a translation matrix and stores it in a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#110 - * @param x defines the translation on X axis - * @param y defines the translation on Y axis - * @param z defines the translationon Z axis - * @param result defines the target matrix - * @returns result input - */ - static TranslationToRef(x, y, z, result) { - math_vector_Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result); - result._updateIdentityStatus(x === 0 && y === 0 && z === 0); - return result; - } - /** - * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue". - * Example Playground - https://playground.babylonjs.com/#AV9X17#55 - * @param startValue defines the start value - * @param endValue defines the end value - * @param gradient defines the gradient factor - * @returns the new matrix - */ - static Lerp(startValue, endValue, gradient) { - const result = new startValue.constructor(); - math_vector_Matrix.LerpToRef(startValue, endValue, gradient, result); - return result; - } - /** - * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue". - * Example Playground - https://playground.babylonjs.com/#AV9X17#54 - * @param startValue defines the start value - * @param endValue defines the end value - * @param gradient defines the gradient factor - * @param result defines the Matrix object where to store data - * @returns result input - */ - static LerpToRef(startValue, endValue, gradient, result) { - const resultM = result._m; - const startM = startValue.m; - const endM = endValue.m; - for (let index = 0; index < 16; index++) { - resultM[index] = startM[index] * (1.0 - gradient) + endM[index] * gradient; - } - result.markAsUpdated(); - return result; - } - /** - * Builds a new matrix whose values are computed by: - * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices - * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end - * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices - * Example Playground - https://playground.babylonjs.com/#AV9X17#22 - * Example Playground - https://playground.babylonjs.com/#AV9X17#51 - * @param startValue defines the first matrix - * @param endValue defines the second matrix - * @param gradient defines the gradient between the two matrices - * @returns the new matrix - */ - static DecomposeLerp(startValue, endValue, gradient) { - const result = new startValue.constructor(); - math_vector_Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result); - return result; - } - /** - * Update a matrix to values which are computed by: - * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices - * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end - * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices - * Example Playground - https://playground.babylonjs.com/#AV9X17#23 - * Example Playground - https://playground.babylonjs.com/#AV9X17#53 - * @param startValue defines the first matrix - * @param endValue defines the second matrix - * @param gradient defines the gradient between the two matrices - * @param result defines the target matrix - * @returns result input - */ - static DecomposeLerpToRef(startValue, endValue, gradient, result) { - const startScale = MathTmp.Vector3[0]; - const startRotation = MathTmp.Quaternion[0]; - const startTranslation = MathTmp.Vector3[1]; - startValue.decompose(startScale, startRotation, startTranslation); - const endScale = MathTmp.Vector3[2]; - const endRotation = MathTmp.Quaternion[1]; - const endTranslation = MathTmp.Vector3[3]; - endValue.decompose(endScale, endRotation, endTranslation); - const resultScale = MathTmp.Vector3[4]; - math_vector_Vector3.LerpToRef(startScale, endScale, gradient, resultScale); - const resultRotation = MathTmp.Quaternion[2]; - math_vector_Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation); - const resultTranslation = MathTmp.Vector3[5]; - math_vector_Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation); - math_vector_Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result); - return result; - } - /** - * Creates a new matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. - * This function generates a matrix suitable for a left handed coordinate system - * Example Playground - https://playground.babylonjs.com/#AV9X17#58 - * Example Playground - https://playground.babylonjs.com/#AV9X17#59 - * @param eye defines the final position of the entity - * @param target defines where the entity should look at - * @param up defines the up vector for the entity - * @returns the new matrix - */ - static LookAtLH(eye, target, up) { - const result = new math_vector_Matrix(); - math_vector_Matrix.LookAtLHToRef(eye, target, up, result); - return result; - } - /** - * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. - * This function generates a matrix suitable for a left handed coordinate system - * Example Playground - https://playground.babylonjs.com/#AV9X17#60 - * Example Playground - https://playground.babylonjs.com/#AV9X17#61 - * @param eye defines the final position of the entity - * @param target defines where the entity should look at - * @param up defines the up vector for the entity - * @param result defines the target matrix - * @returns result input - */ - static LookAtLHToRef(eye, target, up, result) { - const xAxis = MathTmp.Vector3[0]; - const yAxis = MathTmp.Vector3[1]; - const zAxis = MathTmp.Vector3[2]; - // Z axis - target.subtractToRef(eye, zAxis); - zAxis.normalize(); - // X axis - math_vector_Vector3.CrossToRef(up, zAxis, xAxis); - const xSquareLength = xAxis.lengthSquared(); - if (xSquareLength === 0) { - xAxis.x = 1.0; - } - else { - xAxis.normalizeFromLength(Math.sqrt(xSquareLength)); - } - // Y axis - math_vector_Vector3.CrossToRef(zAxis, xAxis, yAxis); - yAxis.normalize(); - // Eye angles - const ex = -math_vector_Vector3.Dot(xAxis, eye); - const ey = -math_vector_Vector3.Dot(yAxis, eye); - const ez = -math_vector_Vector3.Dot(zAxis, eye); - math_vector_Matrix.FromValuesToRef(xAxis._x, yAxis._x, zAxis._x, 0.0, xAxis._y, yAxis._y, zAxis._y, 0.0, xAxis._z, yAxis._z, zAxis._z, 0.0, ex, ey, ez, 1.0, result); - } - /** - * Creates a new matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. - * This function generates a matrix suitable for a right handed coordinate system - * Example Playground - https://playground.babylonjs.com/#AV9X17#62 - * Example Playground - https://playground.babylonjs.com/#AV9X17#63 - * @param eye defines the final position of the entity - * @param target defines where the entity should look at - * @param up defines the up vector for the entity - * @returns the new matrix - */ - static LookAtRH(eye, target, up) { - const result = new math_vector_Matrix(); - math_vector_Matrix.LookAtRHToRef(eye, target, up, result); - return result; - } - /** - * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. - * This function generates a matrix suitable for a right handed coordinate system - * Example Playground - https://playground.babylonjs.com/#AV9X17#64 - * Example Playground - https://playground.babylonjs.com/#AV9X17#65 - * @param eye defines the final position of the entity - * @param target defines where the entity should look at - * @param up defines the up vector for the entity - * @param result defines the target matrix - * @returns result input - */ - static LookAtRHToRef(eye, target, up, result) { - const xAxis = MathTmp.Vector3[0]; - const yAxis = MathTmp.Vector3[1]; - const zAxis = MathTmp.Vector3[2]; - // Z axis - eye.subtractToRef(target, zAxis); - zAxis.normalize(); - // X axis - math_vector_Vector3.CrossToRef(up, zAxis, xAxis); - const xSquareLength = xAxis.lengthSquared(); - if (xSquareLength === 0) { - xAxis.x = 1.0; - } - else { - xAxis.normalizeFromLength(Math.sqrt(xSquareLength)); - } - // Y axis - math_vector_Vector3.CrossToRef(zAxis, xAxis, yAxis); - yAxis.normalize(); - // Eye angles - const ex = -math_vector_Vector3.Dot(xAxis, eye); - const ey = -math_vector_Vector3.Dot(yAxis, eye); - const ez = -math_vector_Vector3.Dot(zAxis, eye); - math_vector_Matrix.FromValuesToRef(xAxis._x, yAxis._x, zAxis._x, 0.0, xAxis._y, yAxis._y, zAxis._y, 0.0, xAxis._z, yAxis._z, zAxis._z, 0.0, ex, ey, ez, 1.0, result); - return result; - } - /** - * Creates a new matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) - * This function generates a matrix suitable for a left handed coordinate system - * Example Playground - https://playground.babylonjs.com/#AV9X17#66 - * @param forward defines the forward direction - Must be normalized and orthogonal to up. - * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. - * @returns the new matrix - */ - static LookDirectionLH(forward, up) { - const result = new math_vector_Matrix(); - math_vector_Matrix.LookDirectionLHToRef(forward, up, result); - return result; - } - /** - * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) - * This function generates a matrix suitable for a left handed coordinate system - * Example Playground - https://playground.babylonjs.com/#AV9X17#67 - * @param forward defines the forward direction - Must be normalized and orthogonal to up. - * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. - * @param result defines the target matrix - * @returns result input - */ - static LookDirectionLHToRef(forward, up, result) { - const back = MathTmp.Vector3[0]; - back.copyFrom(forward); - back.scaleInPlace(-1); - const left = MathTmp.Vector3[1]; - math_vector_Vector3.CrossToRef(up, back, left); - // Generate the rotation matrix. - math_vector_Matrix.FromValuesToRef(left._x, left._y, left._z, 0.0, up._x, up._y, up._z, 0.0, back._x, back._y, back._z, 0.0, 0, 0, 0, 1.0, result); - return result; - } - /** - * Creates a new matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) - * This function generates a matrix suitable for a right handed coordinate system - * Example Playground - https://playground.babylonjs.com/#AV9X17#68 - * @param forward defines the forward direction - Must be normalized and orthogonal to up. - * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. - * @returns the new matrix - */ - static LookDirectionRH(forward, up) { - const result = new math_vector_Matrix(); - math_vector_Matrix.LookDirectionRHToRef(forward, up, result); - return result; - } - /** - * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) - * This function generates a matrix suitable for a right handed coordinate system - * Example Playground - https://playground.babylonjs.com/#AV9X17#69 - * @param forward defines the forward direction - Must be normalized and orthogonal to up. - * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. - * @param result defines the target matrix - * @returns result input - */ - static LookDirectionRHToRef(forward, up, result) { - const right = MathTmp.Vector3[2]; - math_vector_Vector3.CrossToRef(up, forward, right); - // Generate the rotation matrix. - math_vector_Matrix.FromValuesToRef(right._x, right._y, right._z, 0.0, up._x, up._y, up._z, 0.0, forward._x, forward._y, forward._z, 0.0, 0, 0, 0, 1.0, result); - return result; - } - /** - * Create a left-handed orthographic projection matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#70 - * @param width defines the viewport width - * @param height defines the viewport height - * @param znear defines the near clip plane - * @param zfar defines the far clip plane - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @returns a new matrix as a left-handed orthographic projection matrix - */ - static OrthoLH(width, height, znear, zfar, halfZRange) { - const matrix = new math_vector_Matrix(); - math_vector_Matrix.OrthoLHToRef(width, height, znear, zfar, matrix, halfZRange); - return matrix; - } - /** - * Store a left-handed orthographic projection to a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#71 - * @param width defines the viewport width - * @param height defines the viewport height - * @param znear defines the near clip plane - * @param zfar defines the far clip plane - * @param result defines the target matrix - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @returns result input - */ - static OrthoLHToRef(width, height, znear, zfar, result, halfZRange) { - const n = znear; - const f = zfar; - const a = 2.0 / width; - const b = 2.0 / height; - const c = 2.0 / (f - n); - const d = -(f + n) / (f - n); - math_vector_Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result); - if (halfZRange) { - result.multiplyToRef(mtxConvertNDCToHalfZRange, result); - } - result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0); - return result; - } - /** - * Create a left-handed orthographic projection matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#72 - * @param left defines the viewport left coordinate - * @param right defines the viewport right coordinate - * @param bottom defines the viewport bottom coordinate - * @param top defines the viewport top coordinate - * @param znear defines the near clip plane - * @param zfar defines the far clip plane - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @returns a new matrix as a left-handed orthographic projection matrix - */ - static OrthoOffCenterLH(left, right, bottom, top, znear, zfar, halfZRange) { - const matrix = new math_vector_Matrix(); - math_vector_Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix, halfZRange); - return matrix; - } - /** - * Stores a left-handed orthographic projection into a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#73 - * @param left defines the viewport left coordinate - * @param right defines the viewport right coordinate - * @param bottom defines the viewport bottom coordinate - * @param top defines the viewport top coordinate - * @param znear defines the near clip plane - * @param zfar defines the far clip plane - * @param result defines the target matrix - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @returns result input - */ - static OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange) { - const n = znear; - const f = zfar; - const a = 2.0 / (right - left); - const b = 2.0 / (top - bottom); - const c = 2.0 / (f - n); - const d = -(f + n) / (f - n); - const i0 = (left + right) / (left - right); - const i1 = (top + bottom) / (bottom - top); - math_vector_Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result); - if (halfZRange) { - result.multiplyToRef(mtxConvertNDCToHalfZRange, result); - } - result.markAsUpdated(); - return result; - } - /** - * Creates a right-handed orthographic projection matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#76 - * @param left defines the viewport left coordinate - * @param right defines the viewport right coordinate - * @param bottom defines the viewport bottom coordinate - * @param top defines the viewport top coordinate - * @param znear defines the near clip plane - * @param zfar defines the far clip plane - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @returns a new matrix as a right-handed orthographic projection matrix - */ - static OrthoOffCenterRH(left, right, bottom, top, znear, zfar, halfZRange) { - const matrix = new math_vector_Matrix(); - math_vector_Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix, halfZRange); - return matrix; - } - /** - * Stores a right-handed orthographic projection into a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#77 - * @param left defines the viewport left coordinate - * @param right defines the viewport right coordinate - * @param bottom defines the viewport bottom coordinate - * @param top defines the viewport top coordinate - * @param znear defines the near clip plane - * @param zfar defines the far clip plane - * @param result defines the target matrix - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @returns result input - */ - static OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, result, halfZRange) { - math_vector_Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange); - result._m[10] *= -1; // No need to call markAsUpdated as previous function already called it and let _isIdentityDirty to true - return result; - } - /** - * Creates a left-handed perspective projection matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#85 - * @param width defines the viewport width - * @param height defines the viewport height - * @param znear defines the near clip plane - * @param zfar defines the far clip plane - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) - * @returns a new matrix as a left-handed perspective projection matrix - */ - static PerspectiveLH(width, height, znear, zfar, halfZRange, projectionPlaneTilt = 0) { - const matrix = new math_vector_Matrix(); - const n = znear; - const f = zfar; - const a = (2.0 * n) / width; - const b = (2.0 * n) / height; - const c = (f + n) / (f - n); - const d = (-2.0 * f * n) / (f - n); - const rot = Math.tan(projectionPlaneTilt); - math_vector_Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix); - if (halfZRange) { - matrix.multiplyToRef(mtxConvertNDCToHalfZRange, matrix); - } - matrix._updateIdentityStatus(false); - return matrix; - } - /** - * Creates a left-handed perspective projection matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#78 - * @param fov defines the horizontal field of view - * @param aspect defines the aspect ratio - * @param znear defines the near clip plane - * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) - * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) - * @returns a new matrix as a left-handed perspective projection matrix - */ - static PerspectiveFovLH(fov, aspect, znear, zfar, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { - const matrix = new math_vector_Matrix(); - math_vector_Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix, true, halfZRange, projectionPlaneTilt, reverseDepthBufferMode); - return matrix; - } - /** - * Stores a left-handed perspective projection into a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#81 - * @param fov defines the horizontal field of view - * @param aspect defines the aspect ratio - * @param znear defines the near clip plane - * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode - * @param result defines the target matrix - * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) - * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) - * @returns result input - */ - static PerspectiveFovLHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { - const n = znear; - const f = zfar; - const t = 1.0 / Math.tan(fov * 0.5); - const a = isVerticalFovFixed ? t / aspect : t; - const b = isVerticalFovFixed ? t : t * aspect; - const c = reverseDepthBufferMode && n === 0 ? -1 : f !== 0 ? (f + n) / (f - n) : 1; - const d = reverseDepthBufferMode && n === 0 ? 2 * f : f !== 0 ? (-2.0 * f * n) / (f - n) : -2 * n; - const rot = Math.tan(projectionPlaneTilt); - math_vector_Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result); - if (halfZRange) { - result.multiplyToRef(mtxConvertNDCToHalfZRange, result); - } - result._updateIdentityStatus(false); - return result; - } - /** - * Stores a left-handed perspective projection into a given matrix with depth reversed - * Example Playground - https://playground.babylonjs.com/#AV9X17#89 - * @param fov defines the horizontal field of view - * @param aspect defines the aspect ratio - * @param znear defines the near clip plane - * @param zfar not used as infinity is used as far clip - * @param result defines the target matrix - * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) - * @returns result input - */ - static PerspectiveFovReverseLHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0) { - const t = 1.0 / Math.tan(fov * 0.5); - const a = isVerticalFovFixed ? t / aspect : t; - const b = isVerticalFovFixed ? t : t * aspect; - const rot = Math.tan(projectionPlaneTilt); - math_vector_Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, -znear, 1.0, 0.0, 0.0, 1.0, 0.0, result); - if (halfZRange) { - result.multiplyToRef(mtxConvertNDCToHalfZRange, result); - } - result._updateIdentityStatus(false); - return result; - } - /** - * Creates a right-handed perspective projection matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#83 - * @param fov defines the horizontal field of view - * @param aspect defines the aspect ratio - * @param znear defines the near clip plane - * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) - * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) - * @returns a new matrix as a right-handed perspective projection matrix - */ - static PerspectiveFovRH(fov, aspect, znear, zfar, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { - const matrix = new math_vector_Matrix(); - math_vector_Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix, true, halfZRange, projectionPlaneTilt, reverseDepthBufferMode); - return matrix; - } - /** - * Stores a right-handed perspective projection into a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#84 - * @param fov defines the horizontal field of view - * @param aspect defines the aspect ratio - * @param znear defines the near clip plane - * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode - * @param result defines the target matrix - * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) - * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) - * @returns result input - */ - static PerspectiveFovRHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { - //alternatively this could be expressed as: - // m = PerspectiveFovLHToRef - // m[10] *= -1.0; - // m[11] *= -1.0; - const n = znear; - const f = zfar; - const t = 1.0 / Math.tan(fov * 0.5); - const a = isVerticalFovFixed ? t / aspect : t; - const b = isVerticalFovFixed ? t : t * aspect; - const c = reverseDepthBufferMode && n === 0 ? 1 : f !== 0 ? -(f + n) / (f - n) : -1; - const d = reverseDepthBufferMode && n === 0 ? 2 * f : f !== 0 ? (-2 * f * n) / (f - n) : -2 * n; - const rot = Math.tan(projectionPlaneTilt); - math_vector_Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result); - if (halfZRange) { - result.multiplyToRef(mtxConvertNDCToHalfZRange, result); - } - result._updateIdentityStatus(false); - return result; - } - /** - * Stores a right-handed perspective projection into a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#90 - * @param fov defines the horizontal field of view - * @param aspect defines the aspect ratio - * @param znear defines the near clip plane - * @param zfar not used as infinity is used as far clip - * @param result defines the target matrix - * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) - * @returns result input - */ - static PerspectiveFovReverseRHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0) { - const t = 1.0 / Math.tan(fov * 0.5); - const a = isVerticalFovFixed ? t / aspect : t; - const b = isVerticalFovFixed ? t : t * aspect; - const rot = Math.tan(projectionPlaneTilt); - math_vector_Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, rot, 0.0, 0.0, -znear, -1.0, 0.0, 0.0, -1.0, 0.0, result); - if (halfZRange) { - result.multiplyToRef(mtxConvertNDCToHalfZRange, result); - } - result._updateIdentityStatus(false); - return result; - } - /** - * Stores a perspective projection for WebVR info a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#92 - * @param fov defines the field of view - * @param fov.upDegrees - * @param fov.downDegrees - * @param fov.leftDegrees - * @param fov.rightDegrees - * @param znear defines the near clip plane - * @param zfar defines the far clip plane - * @param result defines the target matrix - * @param rightHanded defines if the matrix must be in right-handed mode (false by default) - * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) - * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) - * @returns result input - */ - static PerspectiveFovWebVRToRef(fov, znear, zfar, result, rightHanded = false, halfZRange, projectionPlaneTilt = 0) { - const rightHandedFactor = rightHanded ? -1 : 1; - const upTan = Math.tan((fov.upDegrees * Math.PI) / 180.0); - const downTan = Math.tan((fov.downDegrees * Math.PI) / 180.0); - const leftTan = Math.tan((fov.leftDegrees * Math.PI) / 180.0); - const rightTan = Math.tan((fov.rightDegrees * Math.PI) / 180.0); - const xScale = 2.0 / (leftTan + rightTan); - const yScale = 2.0 / (upTan + downTan); - const rot = Math.tan(projectionPlaneTilt); - const m = result._m; - m[0] = xScale; - m[1] = m[2] = m[3] = m[4] = 0.0; - m[5] = yScale; - m[6] = 0.0; - m[7] = rot; - m[8] = (leftTan - rightTan) * xScale * 0.5; - m[9] = -((upTan - downTan) * yScale * 0.5); - m[10] = -zfar / (znear - zfar); - m[11] = 1.0 * rightHandedFactor; - m[12] = m[13] = m[15] = 0.0; - m[14] = -(2.0 * zfar * znear) / (zfar - znear); - if (halfZRange) { - result.multiplyToRef(mtxConvertNDCToHalfZRange, result); - } - result.markAsUpdated(); - return result; - } - /** - * Computes a complete transformation matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#113 - * @param viewport defines the viewport to use - * @param world defines the world matrix - * @param view defines the view matrix - * @param projection defines the projection matrix - * @param zmin defines the near clip plane - * @param zmax defines the far clip plane - * @returns the transformation matrix - */ - static GetFinalMatrix(viewport, world, view, projection, zmin, zmax) { - const cw = viewport.width; - const ch = viewport.height; - const cx = viewport.x; - const cy = viewport.y; - const viewportMatrix = math_vector_Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1.0); - const matrix = new world.constructor(); - world.multiplyToRef(view, matrix); - matrix.multiplyToRef(projection, matrix); - return matrix.multiplyToRef(viewportMatrix, matrix); - } - /** - * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array - * @param matrix defines the matrix to use - * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix - */ - static GetAsMatrix2x2(matrix) { - const m = matrix.m; - const arr = [m[0], m[1], m[4], m[5]]; - return performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits ? arr : new Float32Array(arr); - } - /** - * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array - * @param matrix defines the matrix to use - * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix - */ - static GetAsMatrix3x3(matrix) { - const m = matrix.m; - const arr = [m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]]; - return performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits ? arr : new Float32Array(arr); - } - /** - * Compute the transpose of a given matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#111 - * @param matrix defines the matrix to transpose - * @returns the new matrix - */ - static Transpose(matrix) { - const result = new matrix.constructor(); - math_vector_Matrix.TransposeToRef(matrix, result); - return result; - } - /** - * Compute the transpose of a matrix and store it in a target matrix - * Example Playground - https://playground.babylonjs.com/#AV9X17#112 - * @param matrix defines the matrix to transpose - * @param result defines the target matrix - * @returns result input - */ - static TransposeToRef(matrix, result) { - const rm = result._m; - const mm = matrix.m; - rm[0] = mm[0]; - rm[1] = mm[4]; - rm[2] = mm[8]; - rm[3] = mm[12]; - rm[4] = mm[1]; - rm[5] = mm[5]; - rm[6] = mm[9]; - rm[7] = mm[13]; - rm[8] = mm[2]; - rm[9] = mm[6]; - rm[10] = mm[10]; - rm[11] = mm[14]; - rm[12] = mm[3]; - rm[13] = mm[7]; - rm[14] = mm[11]; - rm[15] = mm[15]; - result.markAsUpdated(); - // identity-ness does not change when transposing - result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty); - return result; - } - /** - * Computes a reflection matrix from a plane - * Example Playground - https://playground.babylonjs.com/#AV9X17#87 - * @param plane defines the reflection plane - * @returns a new matrix - */ - static Reflection(plane) { - const matrix = new math_vector_Matrix(); - math_vector_Matrix.ReflectionToRef(plane, matrix); - return matrix; - } - /** - * Computes a reflection matrix from a plane - * Example Playground - https://playground.babylonjs.com/#AV9X17#88 - * @param plane defines the reflection plane - * @param result defines the target matrix - * @returns result input - */ - static ReflectionToRef(plane, result) { - plane.normalize(); - const x = plane.normal.x; - const y = plane.normal.y; - const z = plane.normal.z; - const temp = -2 * x; - const temp2 = -2 * y; - const temp3 = -2 * z; - math_vector_Matrix.FromValuesToRef(temp * x + 1, temp2 * x, temp3 * x, 0.0, temp * y, temp2 * y + 1, temp3 * y, 0.0, temp * z, temp2 * z, temp3 * z + 1, 0.0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1.0, result); - return result; - } - /** - * Sets the given matrix as a rotation matrix composed from the 3 left handed axes - * @param xaxis defines the value of the 1st axis - * @param yaxis defines the value of the 2nd axis - * @param zaxis defines the value of the 3rd axis - * @param result defines the target matrix - * @returns result input - */ - static FromXYZAxesToRef(xaxis, yaxis, zaxis, result) { - math_vector_Matrix.FromValuesToRef(xaxis._x, xaxis._y, xaxis._z, 0.0, yaxis._x, yaxis._y, yaxis._z, 0.0, zaxis._x, zaxis._y, zaxis._z, 0.0, 0.0, 0.0, 0.0, 1.0, result); - return result; - } - /** - * Creates a rotation matrix from a quaternion and stores it in a target matrix - * @param quat defines the quaternion to use - * @param result defines the target matrix - * @returns result input - */ - static FromQuaternionToRef(quat, result) { - const xx = quat._x * quat._x; - const yy = quat._y * quat._y; - const zz = quat._z * quat._z; - const xy = quat._x * quat._y; - const zw = quat._z * quat._w; - const zx = quat._z * quat._x; - const yw = quat._y * quat._w; - const yz = quat._y * quat._z; - const xw = quat._x * quat._w; - result._m[0] = 1.0 - 2.0 * (yy + zz); - result._m[1] = 2.0 * (xy + zw); - result._m[2] = 2.0 * (zx - yw); - result._m[3] = 0.0; - result._m[4] = 2.0 * (xy - zw); - result._m[5] = 1.0 - 2.0 * (zz + xx); - result._m[6] = 2.0 * (yz + xw); - result._m[7] = 0.0; - result._m[8] = 2.0 * (zx + yw); - result._m[9] = 2.0 * (yz - xw); - result._m[10] = 1.0 - 2.0 * (yy + xx); - result._m[11] = 0.0; - result._m[12] = 0.0; - result._m[13] = 0.0; - result._m[14] = 0.0; - result._m[15] = 1.0; - result.markAsUpdated(); - return result; - } -} -math_vector_Matrix._UpdateFlagSeed = 0; -math_vector_Matrix._IdentityReadOnly = math_vector_Matrix.Identity(); -/** - * @internal - * Same as Tmp but not exported to keep it only for math functions to avoid conflicts - */ -class MathTmp { -} -MathTmp.Vector3 = arrayTools_ArrayTools.BuildTuple(11, math_vector_Vector3.Zero); -MathTmp.Matrix = arrayTools_ArrayTools.BuildTuple(2, math_vector_Matrix.Identity); -MathTmp.Quaternion = arrayTools_ArrayTools.BuildTuple(3, math_vector_Quaternion.Zero); -/** - * @internal - */ -class math_vector_TmpVectors { -} -math_vector_TmpVectors.Vector2 = arrayTools_ArrayTools.BuildTuple(3, math_vector_Vector2.Zero); // 3 temp Vector2 at once should be enough -math_vector_TmpVectors.Vector3 = arrayTools_ArrayTools.BuildTuple(13, math_vector_Vector3.Zero); // 13 temp Vector3 at once should be enough -math_vector_TmpVectors.Vector4 = arrayTools_ArrayTools.BuildTuple(3, math_vector_Vector4.Zero); // 3 temp Vector4 at once should be enough -math_vector_TmpVectors.Quaternion = arrayTools_ArrayTools.BuildTuple(2, math_vector_Quaternion.Zero); // 2 temp Quaternion at once should be enough -math_vector_TmpVectors.Matrix = arrayTools_ArrayTools.BuildTuple(8, math_vector_Matrix.Identity); // 8 temp Matrices at once should be enough -RegisterClass("BABYLON.Vector2", math_vector_Vector2); -RegisterClass("BABYLON.Vector3", math_vector_Vector3); -RegisterClass("BABYLON.Vector4", math_vector_Vector4); -RegisterClass("BABYLON.Matrix", math_vector_Matrix); -const mtxConvertNDCToHalfZRange = math_vector_Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1); -//# sourceMappingURL=math.vector.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.color.js - - - - -function colorChannelToLinearSpace(color) { - return Math.pow(color, ToLinearSpace); -} -function colorChannelToLinearSpaceExact(color) { - if (color <= 0.04045) { - return 0.0773993808 * color; - } - return Math.pow(0.947867299 * (color + 0.055), 2.4); -} -function colorChannelToGammaSpace(color) { - return Math.pow(color, ToGammaSpace); -} -function colorChannelToGammaSpaceExact(color) { - if (color <= 0.0031308) { - return 12.92 * color; - } - return 1.055 * Math.pow(color, 0.41666) - 0.055; -} -/** - * Class used to hold a RGB color - */ -class math_color_Color3 { - /** - * Creates a new Color3 object from red, green, blue values, all between 0 and 1 - * @param r defines the red component (between 0 and 1, default is 0) - * @param g defines the green component (between 0 and 1, default is 0) - * @param b defines the blue component (between 0 and 1, default is 0) - */ - constructor( - /** - * Defines the red component (between 0 and 1, default is 0) - */ - r = 0, - /** - * Defines the green component (between 0 and 1, default is 0) - */ - g = 0, - /** - * Defines the blue component (between 0 and 1, default is 0) - */ - b = 0) { - this.r = r; - this.g = g; - this.b = b; - } - /** - * Creates a string with the Color3 current values - * @returns the string representation of the Color3 object - */ - toString() { - return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}"; - } - /** - * Returns the string "Color3" - * @returns "Color3" - */ - getClassName() { - return "Color3"; - } - /** - * Compute the Color3 hash code - * @returns an unique number that can be used to hash Color3 objects - */ - getHashCode() { - let hash = (this.r * 255) | 0; - hash = (hash * 397) ^ ((this.g * 255) | 0); - hash = (hash * 397) ^ ((this.b * 255) | 0); - return hash; - } - // Operators - /** - * Stores in the given array from the given starting index the red, green, blue values as successive elements - * @param array defines the array where to store the r,g,b components - * @param index defines an optional index in the target array to define where to start storing values - * @returns the current Color3 object - */ - toArray(array, index = 0) { - array[index] = this.r; - array[index + 1] = this.g; - array[index + 2] = this.b; - return this; - } - /** - * Update the current color with values stored in an array from the starting index of the given array - * @param array defines the source array - * @param offset defines an offset in the source array - * @returns the current Color3 object - */ - fromArray(array, offset = 0) { - math_color_Color3.FromArrayToRef(array, offset, this); - return this; - } - /** - * Returns a new Color4 object from the current Color3 and the given alpha - * @param alpha defines the alpha component on the new Color4 object (default is 1) - * @returns a new Color4 object - */ - toColor4(alpha = 1) { - return new math_color_Color4(this.r, this.g, this.b, alpha); - } - /** - * Returns a new array populated with 3 numeric elements : red, green and blue values - * @returns the new array - */ - asArray() { - return [this.r, this.g, this.b]; - } - /** - * Returns the luminance value - * @returns a float value - */ - toLuminance() { - return this.r * 0.3 + this.g * 0.59 + this.b * 0.11; - } - /** - * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object - * @param otherColor defines the second operand - * @returns the new Color3 object - */ - multiply(otherColor) { - return new math_color_Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b); - } - /** - * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result" - * @param otherColor defines the second operand - * @param result defines the Color3 object where to store the result - * @returns the current Color3 - */ - multiplyToRef(otherColor, result) { - result.r = this.r * otherColor.r; - result.g = this.g * otherColor.g; - result.b = this.b * otherColor.b; - return this; - } - /** - * Determines equality between Color3 objects - * @param otherColor defines the second operand - * @returns true if the rgb values are equal to the given ones - */ - equals(otherColor) { - return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b; - } - /** - * Determines equality between the current Color3 object and a set of r,b,g values - * @param r defines the red component to check - * @param g defines the green component to check - * @param b defines the blue component to check - * @returns true if the rgb values are equal to the given ones - */ - equalsFloats(r, g, b) { - return this.r === r && this.g === g && this.b === b; - } - /** - * Creates a new Color3 with the current Color3 values multiplied by scale - * @param scale defines the scaling factor to apply - * @returns a new Color3 object - */ - scale(scale) { - return new math_color_Color3(this.r * scale, this.g * scale, this.b * scale); - } - /** - * Multiplies the Color3 values by the float "scale" - * @param scale defines the scaling factor to apply - * @returns the current updated Color3 - */ - scaleInPlace(scale) { - this.r *= scale; - this.g *= scale; - this.b *= scale; - return this; - } - /** - * Multiplies the rgb values by scale and stores the result into "result" - * @param scale defines the scaling factor - * @param result defines the Color3 object where to store the result - * @returns the unmodified current Color3 - */ - scaleToRef(scale, result) { - result.r = this.r * scale; - result.g = this.g * scale; - result.b = this.b * scale; - return this; - } - /** - * Scale the current Color3 values by a factor and add the result to a given Color3 - * @param scale defines the scale factor - * @param result defines color to store the result into - * @returns the unmodified current Color3 - */ - scaleAndAddToRef(scale, result) { - result.r += this.r * scale; - result.g += this.g * scale; - result.b += this.b * scale; - return this; - } - /** - * Clamps the rgb values by the min and max values and stores the result into "result" - * @param min defines minimum clamping value (default is 0) - * @param max defines maximum clamping value (default is 1) - * @param result defines color to store the result into - * @returns the original Color3 - */ - clampToRef(min = 0, max = 1, result) { - result.r = math_scalar_Scalar.Clamp(this.r, min, max); - result.g = math_scalar_Scalar.Clamp(this.g, min, max); - result.b = math_scalar_Scalar.Clamp(this.b, min, max); - return this; - } - /** - * Creates a new Color3 set with the added values of the current Color3 and of the given one - * @param otherColor defines the second operand - * @returns the new Color3 - */ - add(otherColor) { - return new math_color_Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b); - } - /** - * Stores the result of the addition of the current Color3 and given one rgb values into "result" - * @param otherColor defines the second operand - * @param result defines Color3 object to store the result into - * @returns the unmodified current Color3 - */ - addToRef(otherColor, result) { - result.r = this.r + otherColor.r; - result.g = this.g + otherColor.g; - result.b = this.b + otherColor.b; - return this; - } - /** - * Returns a new Color3 set with the subtracted values of the given one from the current Color3 - * @param otherColor defines the second operand - * @returns the new Color3 - */ - subtract(otherColor) { - return new math_color_Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b); - } - /** - * Stores the result of the subtraction of given one from the current Color3 rgb values into "result" - * @param otherColor defines the second operand - * @param result defines Color3 object to store the result into - * @returns the unmodified current Color3 - */ - subtractToRef(otherColor, result) { - result.r = this.r - otherColor.r; - result.g = this.g - otherColor.g; - result.b = this.b - otherColor.b; - return this; - } - /** - * Copy the current object - * @returns a new Color3 copied the current one - */ - clone() { - return new math_color_Color3(this.r, this.g, this.b); - } - /** - * Copies the rgb values from the source in the current Color3 - * @param source defines the source Color3 object - * @returns the updated Color3 object - */ - copyFrom(source) { - this.r = source.r; - this.g = source.g; - this.b = source.b; - return this; - } - /** - * Updates the Color3 rgb values from the given floats - * @param r defines the red component to read from - * @param g defines the green component to read from - * @param b defines the blue component to read from - * @returns the current Color3 object - */ - copyFromFloats(r, g, b) { - this.r = r; - this.g = g; - this.b = b; - return this; - } - /** - * Updates the Color3 rgb values from the given floats - * @param r defines the red component to read from - * @param g defines the green component to read from - * @param b defines the blue component to read from - * @returns the current Color3 object - */ - set(r, g, b) { - return this.copyFromFloats(r, g, b); - } - /** - * Compute the Color3 hexadecimal code as a string - * @returns a string containing the hexadecimal representation of the Color3 object - */ - toHexString() { - const intR = Math.round(this.r * 255); - const intG = Math.round(this.g * 255); - const intB = Math.round(this.b * 255); - return "#" + math_scalar_Scalar.ToHex(intR) + math_scalar_Scalar.ToHex(intG) + math_scalar_Scalar.ToHex(intB); - } - /** - * Converts current color in rgb space to HSV values - * @returns a new color3 representing the HSV values - */ - toHSV() { - const result = new math_color_Color3(); - this.toHSVToRef(result); - return result; - } - /** - * Converts current color in rgb space to HSV values - * @param result defines the Color3 where to store the HSV values - */ - toHSVToRef(result) { - const r = this.r; - const g = this.g; - const b = this.b; - const max = Math.max(r, g, b); - const min = Math.min(r, g, b); - let h = 0; - let s = 0; - const v = max; - const dm = max - min; - if (max !== 0) { - s = dm / max; - } - if (max != min) { - if (max == r) { - h = (g - b) / dm; - if (g < b) { - h += 6; - } - } - else if (max == g) { - h = (b - r) / dm + 2; - } - else if (max == b) { - h = (r - g) / dm + 4; - } - h *= 60; - } - result.r = h; - result.g = s; - result.b = v; - } - /** - * Computes a new Color3 converted from the current one to linear space - * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) - * @returns a new Color3 object - */ - toLinearSpace(exact = false) { - const convertedColor = new math_color_Color3(); - this.toLinearSpaceToRef(convertedColor, exact); - return convertedColor; - } - /** - * Converts the Color3 values to linear space and stores the result in "convertedColor" - * @param convertedColor defines the Color3 object where to store the linear space version - * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) - * @returns the unmodified Color3 - */ - toLinearSpaceToRef(convertedColor, exact = false) { - if (exact) { - convertedColor.r = colorChannelToLinearSpaceExact(this.r); - convertedColor.g = colorChannelToLinearSpaceExact(this.g); - convertedColor.b = colorChannelToLinearSpaceExact(this.b); - } - else { - convertedColor.r = colorChannelToLinearSpace(this.r); - convertedColor.g = colorChannelToLinearSpace(this.g); - convertedColor.b = colorChannelToLinearSpace(this.b); - } - return this; - } - /** - * Computes a new Color3 converted from the current one to gamma space - * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) - * @returns a new Color3 object - */ - toGammaSpace(exact = false) { - const convertedColor = new math_color_Color3(); - this.toGammaSpaceToRef(convertedColor, exact); - return convertedColor; - } - /** - * Converts the Color3 values to gamma space and stores the result in "convertedColor" - * @param convertedColor defines the Color3 object where to store the gamma space version - * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) - * @returns the unmodified Color3 - */ - toGammaSpaceToRef(convertedColor, exact = false) { - if (exact) { - convertedColor.r = colorChannelToGammaSpaceExact(this.r); - convertedColor.g = colorChannelToGammaSpaceExact(this.g); - convertedColor.b = colorChannelToGammaSpaceExact(this.b); - } - else { - convertedColor.r = colorChannelToGammaSpace(this.r); - convertedColor.g = colorChannelToGammaSpace(this.g); - convertedColor.b = colorChannelToGammaSpace(this.b); - } - return this; - } - /** - * Converts Hue, saturation and value to a Color3 (RGB) - * @param hue defines the hue (value between 0 and 360) - * @param saturation defines the saturation (value between 0 and 1) - * @param value defines the value (value between 0 and 1) - * @param result defines the Color3 where to store the RGB values - */ - static HSVtoRGBToRef(hue, saturation, value, result) { - const chroma = value * saturation; - const h = hue / 60; - const x = chroma * (1 - Math.abs((h % 2) - 1)); - let r = 0; - let g = 0; - let b = 0; - if (h >= 0 && h <= 1) { - r = chroma; - g = x; - } - else if (h >= 1 && h <= 2) { - r = x; - g = chroma; - } - else if (h >= 2 && h <= 3) { - g = chroma; - b = x; - } - else if (h >= 3 && h <= 4) { - g = x; - b = chroma; - } - else if (h >= 4 && h <= 5) { - r = x; - b = chroma; - } - else if (h >= 5 && h <= 6) { - r = chroma; - b = x; - } - const m = value - chroma; - result.set(r + m, g + m, b + m); - } - /** - * Converts Hue, saturation and value to a new Color3 (RGB) - * @param hue defines the hue (value between 0 and 360) - * @param saturation defines the saturation (value between 0 and 1) - * @param value defines the value (value between 0 and 1) - * @returns a new Color3 object - */ - static FromHSV(hue, saturation, value) { - const result = new math_color_Color3(0, 0, 0); - math_color_Color3.HSVtoRGBToRef(hue, saturation, value, result); - return result; - } - /** - * Creates a new Color3 from the string containing valid hexadecimal values - * @param hex defines a string containing valid hexadecimal values - * @returns a new Color3 object - */ - static FromHexString(hex) { - if (hex.substring(0, 1) !== "#" || hex.length !== 7) { - return new math_color_Color3(0, 0, 0); - } - const r = parseInt(hex.substring(1, 3), 16); - const g = parseInt(hex.substring(3, 5), 16); - const b = parseInt(hex.substring(5, 7), 16); - return math_color_Color3.FromInts(r, g, b); - } - /** - * Creates a new Color3 from the starting index of the given array - * @param array defines the source array - * @param offset defines an offset in the source array - * @returns a new Color3 object - */ - static FromArray(array, offset = 0) { - return new math_color_Color3(array[offset], array[offset + 1], array[offset + 2]); - } - /** - * Creates a new Color3 from the starting index element of the given array - * @param array defines the source array to read from - * @param offset defines the offset in the source array - * @param result defines the target Color3 object - */ - static FromArrayToRef(array, offset = 0, result) { - result.r = array[offset]; - result.g = array[offset + 1]; - result.b = array[offset + 2]; - } - /** - * Creates a new Color3 from integer values (< 256) - * @param r defines the red component to read from (value between 0 and 255) - * @param g defines the green component to read from (value between 0 and 255) - * @param b defines the blue component to read from (value between 0 and 255) - * @returns a new Color3 object - */ - static FromInts(r, g, b) { - return new math_color_Color3(r / 255.0, g / 255.0, b / 255.0); - } - /** - * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3 - * @param start defines the start Color3 value - * @param end defines the end Color3 value - * @param amount defines the gradient value between start and end - * @returns a new Color3 object - */ - static Lerp(start, end, amount) { - const result = new math_color_Color3(0.0, 0.0, 0.0); - math_color_Color3.LerpToRef(start, end, amount, result); - return result; - } - /** - * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3 - * @param left defines the start value - * @param right defines the end value - * @param amount defines the gradient factor - * @param result defines the Color3 object where to store the result - */ - static LerpToRef(left, right, amount, result) { - result.r = left.r + (right.r - left.r) * amount; - result.g = left.g + (right.g - left.g) * amount; - result.b = left.b + (right.b - left.b) * amount; - } - /** - * Returns a new Color3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2" - * @param value1 defines the first control point - * @param tangent1 defines the first tangent Color3 - * @param value2 defines the second control point - * @param tangent2 defines the second tangent Color3 - * @param amount defines the amount on the interpolation spline (between 0 and 1) - * @returns the new Color3 - */ - static Hermite(value1, tangent1, value2, tangent2, amount) { - const squared = amount * amount; - const cubed = amount * squared; - const part1 = 2.0 * cubed - 3.0 * squared + 1.0; - const part2 = -2.0 * cubed + 3.0 * squared; - const part3 = cubed - 2.0 * squared + amount; - const part4 = cubed - squared; - const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4; - const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4; - const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4; - return new math_color_Color3(r, g, b); - } - /** - * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @returns 1st derivative - */ - static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { - const result = math_color_Color3.Black(); - this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); - return result; - } - /** - * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @param result define where to store the derivative - */ - static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { - const t2 = time * time; - 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; - 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; - 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; - } - /** - * Returns a Color3 value containing a red color - * @returns a new Color3 object - */ - static Red() { - return new math_color_Color3(1, 0, 0); - } - /** - * Returns a Color3 value containing a green color - * @returns a new Color3 object - */ - static Green() { - return new math_color_Color3(0, 1, 0); - } - /** - * Returns a Color3 value containing a blue color - * @returns a new Color3 object - */ - static Blue() { - return new math_color_Color3(0, 0, 1); - } - /** - * Returns a Color3 value containing a black color - * @returns a new Color3 object - */ - static Black() { - return new math_color_Color3(0, 0, 0); - } - /** - * Gets a Color3 value containing a black color that must not be updated - */ - static get BlackReadOnly() { - return math_color_Color3._BlackReadOnly; - } - /** - * Returns a Color3 value containing a white color - * @returns a new Color3 object - */ - static White() { - return new math_color_Color3(1, 1, 1); - } - /** - * Returns a Color3 value containing a purple color - * @returns a new Color3 object - */ - static Purple() { - return new math_color_Color3(0.5, 0, 0.5); - } - /** - * Returns a Color3 value containing a magenta color - * @returns a new Color3 object - */ - static Magenta() { - return new math_color_Color3(1, 0, 1); - } - /** - * Returns a Color3 value containing a yellow color - * @returns a new Color3 object - */ - static Yellow() { - return new math_color_Color3(1, 1, 0); - } - /** - * Returns a Color3 value containing a gray color - * @returns a new Color3 object - */ - static Gray() { - return new math_color_Color3(0.5, 0.5, 0.5); - } - /** - * Returns a Color3 value containing a teal color - * @returns a new Color3 object - */ - static Teal() { - return new math_color_Color3(0, 1.0, 1.0); - } - /** - * Returns a Color3 value containing a random color - * @returns a new Color3 object - */ - static Random() { - return new math_color_Color3(Math.random(), Math.random(), Math.random()); - } -} -// Statics -math_color_Color3._BlackReadOnly = math_color_Color3.Black(); -/** - * Class used to hold a RBGA color - */ -class math_color_Color4 { - /** - * Creates a new Color4 object from red, green, blue values, all between 0 and 1 - * @param r defines the red component (between 0 and 1, default is 0) - * @param g defines the green component (between 0 and 1, default is 0) - * @param b defines the blue component (between 0 and 1, default is 0) - * @param a defines the alpha component (between 0 and 1, default is 1) - */ - constructor( - /** - * Defines the red component (between 0 and 1, default is 0) - */ - r = 0, - /** - * Defines the green component (between 0 and 1, default is 0) - */ - g = 0, - /** - * Defines the blue component (between 0 and 1, default is 0) - */ - b = 0, - /** - * Defines the alpha component (between 0 and 1, default is 1) - */ - a = 1) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - } - // Operators - /** - * Adds in place the given Color4 values to the current Color4 object - * @param right defines the second operand - * @returns the current updated Color4 object - */ - addInPlace(right) { - this.r += right.r; - this.g += right.g; - this.b += right.b; - this.a += right.a; - return this; - } - /** - * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values - * @returns the new array - */ - asArray() { - return [this.r, this.g, this.b, this.a]; - } - /** - * Stores from the starting index in the given array the Color4 successive values - * @param array defines the array where to store the r,g,b components - * @param index defines an optional index in the target array to define where to start storing values - * @returns the current Color4 object - */ - toArray(array, index = 0) { - array[index] = this.r; - array[index + 1] = this.g; - array[index + 2] = this.b; - array[index + 3] = this.a; - return this; - } - /** - * Update the current color with values stored in an array from the starting index of the given array - * @param array defines the source array - * @param offset defines an offset in the source array - * @returns the current Color4 object - */ - fromArray(array, offset = 0) { - math_color_Color4.FromArrayToRef(array, offset, this); - return this; - } - /** - * Determines equality between Color4 objects - * @param otherColor defines the second operand - * @returns true if the rgba values are equal to the given ones - */ - equals(otherColor) { - return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b && this.a === otherColor.a; - } - /** - * Creates a new Color4 set with the added values of the current Color4 and of the given one - * @param right defines the second operand - * @returns a new Color4 object - */ - add(right) { - return new math_color_Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a); - } - /** - * Creates a new Color4 set with the subtracted values of the given one from the current Color4 - * @param right defines the second operand - * @returns a new Color4 object - */ - subtract(right) { - return new math_color_Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a); - } - /** - * Subtracts the given ones from the current Color4 values and stores the results in "result" - * @param right defines the second operand - * @param result defines the Color4 object where to store the result - * @returns the current Color4 object - */ - subtractToRef(right, result) { - result.r = this.r - right.r; - result.g = this.g - right.g; - result.b = this.b - right.b; - result.a = this.a - right.a; - return this; - } - /** - * Creates a new Color4 with the current Color4 values multiplied by scale - * @param scale defines the scaling factor to apply - * @returns a new Color4 object - */ - scale(scale) { - return new math_color_Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale); - } - /** - * Multiplies the Color4 values by the float "scale" - * @param scale defines the scaling factor to apply - * @returns the current updated Color4 - */ - scaleInPlace(scale) { - this.r *= scale; - this.g *= scale; - this.b *= scale; - this.a *= scale; - return this; - } - /** - * Multiplies the current Color4 values by scale and stores the result in "result" - * @param scale defines the scaling factor to apply - * @param result defines the Color4 object where to store the result - * @returns the current unmodified Color4 - */ - scaleToRef(scale, result) { - result.r = this.r * scale; - result.g = this.g * scale; - result.b = this.b * scale; - result.a = this.a * scale; - return this; - } - /** - * Scale the current Color4 values by a factor and add the result to a given Color4 - * @param scale defines the scale factor - * @param result defines the Color4 object where to store the result - * @returns the unmodified current Color4 - */ - scaleAndAddToRef(scale, result) { - result.r += this.r * scale; - result.g += this.g * scale; - result.b += this.b * scale; - result.a += this.a * scale; - return this; - } - /** - * Clamps the rgb values by the min and max values and stores the result into "result" - * @param min defines minimum clamping value (default is 0) - * @param max defines maximum clamping value (default is 1) - * @param result defines color to store the result into. - * @returns the current Color4 - */ - clampToRef(min = 0, max = 1, result) { - result.r = math_scalar_Scalar.Clamp(this.r, min, max); - result.g = math_scalar_Scalar.Clamp(this.g, min, max); - result.b = math_scalar_Scalar.Clamp(this.b, min, max); - result.a = math_scalar_Scalar.Clamp(this.a, min, max); - return this; - } - /** - * Multiply an Color4 value by another and return a new Color4 object - * @param color defines the Color4 value to multiply by - * @returns a new Color4 object - */ - multiply(color) { - return new math_color_Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a); - } - /** - * Multiply a Color4 value by another and push the result in a reference value - * @param color defines the Color4 value to multiply by - * @param result defines the Color4 to fill the result in - * @returns the result Color4 - */ - multiplyToRef(color, result) { - result.r = this.r * color.r; - result.g = this.g * color.g; - result.b = this.b * color.b; - result.a = this.a * color.a; - return result; - } - /** - * Creates a string with the Color4 current values - * @returns the string representation of the Color4 object - */ - toString() { - return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}"; - } - /** - * Returns the string "Color4" - * @returns "Color4" - */ - getClassName() { - return "Color4"; - } - /** - * Compute the Color4 hash code - * @returns an unique number that can be used to hash Color4 objects - */ - getHashCode() { - let hash = (this.r * 255) | 0; - hash = (hash * 397) ^ ((this.g * 255) | 0); - hash = (hash * 397) ^ ((this.b * 255) | 0); - hash = (hash * 397) ^ ((this.a * 255) | 0); - return hash; - } - /** - * Creates a new Color4 copied from the current one - * @returns a new Color4 object - */ - clone() { - return new math_color_Color4(this.r, this.g, this.b, this.a); - } - /** - * Copies the given Color4 values into the current one - * @param source defines the source Color4 object - * @returns the current updated Color4 object - */ - copyFrom(source) { - this.r = source.r; - this.g = source.g; - this.b = source.b; - this.a = source.a; - return this; - } - /** - * Copies the given float values into the current one - * @param r defines the red component to read from - * @param g defines the green component to read from - * @param b defines the blue component to read from - * @param a defines the alpha component to read from - * @returns the current updated Color4 object - */ - copyFromFloats(r, g, b, a) { - this.r = r; - this.g = g; - this.b = b; - this.a = a; - return this; - } - /** - * Copies the given float values into the current one - * @param r defines the red component to read from - * @param g defines the green component to read from - * @param b defines the blue component to read from - * @param a defines the alpha component to read from - * @returns the current updated Color4 object - */ - set(r, g, b, a) { - return this.copyFromFloats(r, g, b, a); - } - /** - * Compute the Color4 hexadecimal code as a string - * @param returnAsColor3 defines if the string should only contains RGB values (off by default) - * @returns a string containing the hexadecimal representation of the Color4 object - */ - toHexString(returnAsColor3 = false) { - const intR = Math.round(this.r * 255); - const intG = Math.round(this.g * 255); - const intB = Math.round(this.b * 255); - if (returnAsColor3) { - return "#" + math_scalar_Scalar.ToHex(intR) + math_scalar_Scalar.ToHex(intG) + math_scalar_Scalar.ToHex(intB); - } - const intA = Math.round(this.a * 255); - return "#" + math_scalar_Scalar.ToHex(intR) + math_scalar_Scalar.ToHex(intG) + math_scalar_Scalar.ToHex(intB) + math_scalar_Scalar.ToHex(intA); - } - /** - * Computes a new Color4 converted from the current one to linear space - * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) - * @returns a new Color4 object - */ - toLinearSpace(exact = false) { - const convertedColor = new math_color_Color4(); - this.toLinearSpaceToRef(convertedColor, exact); - return convertedColor; - } - /** - * Converts the Color4 values to linear space and stores the result in "convertedColor" - * @param convertedColor defines the Color4 object where to store the linear space version - * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) - * @returns the unmodified Color4 - */ - toLinearSpaceToRef(convertedColor, exact = false) { - if (exact) { - convertedColor.r = colorChannelToLinearSpaceExact(this.r); - convertedColor.g = colorChannelToLinearSpaceExact(this.g); - convertedColor.b = colorChannelToLinearSpaceExact(this.b); - } - else { - convertedColor.r = colorChannelToLinearSpace(this.r); - convertedColor.g = colorChannelToLinearSpace(this.g); - convertedColor.b = colorChannelToLinearSpace(this.b); - } - convertedColor.a = this.a; - return this; - } - /** - * Computes a new Color4 converted from the current one to gamma space - * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) - * @returns a new Color4 object - */ - toGammaSpace(exact = false) { - const convertedColor = new math_color_Color4(); - this.toGammaSpaceToRef(convertedColor, exact); - return convertedColor; - } - /** - * Converts the Color4 values to gamma space and stores the result in "convertedColor" - * @param convertedColor defines the Color4 object where to store the gamma space version - * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) - * @returns the unmodified Color4 - */ - toGammaSpaceToRef(convertedColor, exact = false) { - if (exact) { - convertedColor.r = colorChannelToGammaSpaceExact(this.r); - convertedColor.g = colorChannelToGammaSpaceExact(this.g); - convertedColor.b = colorChannelToGammaSpaceExact(this.b); - } - else { - convertedColor.r = colorChannelToGammaSpace(this.r); - convertedColor.g = colorChannelToGammaSpace(this.g); - convertedColor.b = colorChannelToGammaSpace(this.b); - } - convertedColor.a = this.a; - return this; - } - // Statics - /** - * Creates a new Color4 from the string containing valid hexadecimal values. - * - * A valid hex string is either in the format #RRGGBB or #RRGGBBAA. - * - * When a hex string without alpha is passed, the resulting Color4 has - * its alpha value set to 1.0. - * - * An invalid string results in a Color with all its channels set to 0.0, - * i.e. "transparent black". - * - * @param hex defines a string containing valid hexadecimal values - * @returns a new Color4 object - */ - static FromHexString(hex) { - if (hex.substring(0, 1) !== "#" || (hex.length !== 9 && hex.length !== 7)) { - return new math_color_Color4(0.0, 0.0, 0.0, 0.0); - } - const r = parseInt(hex.substring(1, 3), 16); - const g = parseInt(hex.substring(3, 5), 16); - const b = parseInt(hex.substring(5, 7), 16); - const a = hex.length === 9 ? parseInt(hex.substring(7, 9), 16) : 255; - return math_color_Color4.FromInts(r, g, b, a); - } - /** - * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object - * @param left defines the start value - * @param right defines the end value - * @param amount defines the gradient factor - * @returns a new Color4 object - */ - static Lerp(left, right, amount) { - const result = new math_color_Color4(0.0, 0.0, 0.0, 0.0); - math_color_Color4.LerpToRef(left, right, amount, result); - return result; - } - /** - * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object - * @param left defines the start value - * @param right defines the end value - * @param amount defines the gradient factor - * @param result defines the Color4 object where to store data - */ - static LerpToRef(left, right, amount, result) { - result.r = left.r + (right.r - left.r) * amount; - result.g = left.g + (right.g - left.g) * amount; - result.b = left.b + (right.b - left.b) * amount; - result.a = left.a + (right.a - left.a) * amount; - } - /** - * Interpolate between two Color4 using Hermite interpolation - * @param value1 defines first Color4 - * @param tangent1 defines the incoming tangent - * @param value2 defines second Color4 - * @param tangent2 defines the outgoing tangent - * @param amount defines the target Color4 - * @returns the new interpolated Color4 - */ - static Hermite(value1, tangent1, value2, tangent2, amount) { - const squared = amount * amount; - const cubed = amount * squared; - const part1 = 2.0 * cubed - 3.0 * squared + 1.0; - const part2 = -2.0 * cubed + 3.0 * squared; - const part3 = cubed - 2.0 * squared + amount; - const part4 = cubed - squared; - const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4; - const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4; - const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4; - const a = value1.a * part1 + value2.a * part2 + tangent1.a * part3 + tangent2.a * part4; - return new math_color_Color4(r, g, b, a); - } - /** - * Returns a new Color4 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @returns 1st derivative - */ - static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { - const result = new math_color_Color4(); - this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); - return result; - } - /** - * Update a Color4 with the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". - * @param value1 defines the first control point - * @param tangent1 defines the first tangent - * @param value2 defines the second control point - * @param tangent2 defines the second tangent - * @param time define where the derivative must be done - * @param result define where to store the derivative - */ - static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { - const t2 = time * time; - 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; - 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; - 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; - 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; - } - /** - * Creates a new Color4 from a Color3 and an alpha value - * @param color3 defines the source Color3 to read from - * @param alpha defines the alpha component (1.0 by default) - * @returns a new Color4 object - */ - static FromColor3(color3, alpha = 1.0) { - return new math_color_Color4(color3.r, color3.g, color3.b, alpha); - } - /** - * Creates a new Color4 from the starting index element of the given array - * @param array defines the source array to read from - * @param offset defines the offset in the source array - * @returns a new Color4 object - */ - static FromArray(array, offset = 0) { - return new math_color_Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); - } - /** - * Creates a new Color4 from the starting index element of the given array - * @param array defines the source array to read from - * @param offset defines the offset in the source array - * @param result defines the target Color4 object - */ - static FromArrayToRef(array, offset = 0, result) { - result.r = array[offset]; - result.g = array[offset + 1]; - result.b = array[offset + 2]; - result.a = array[offset + 3]; - } - /** - * Creates a new Color3 from integer values (< 256) - * @param r defines the red component to read from (value between 0 and 255) - * @param g defines the green component to read from (value between 0 and 255) - * @param b defines the blue component to read from (value between 0 and 255) - * @param a defines the alpha component to read from (value between 0 and 255) - * @returns a new Color3 object - */ - static FromInts(r, g, b, a) { - return new math_color_Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0); - } - /** - * Check the content of a given array and convert it to an array containing RGBA data - * If the original array was already containing count * 4 values then it is returned directly - * @param colors defines the array to check - * @param count defines the number of RGBA data to expect - * @returns an array containing count * 4 values (RGBA) - */ - static CheckColors4(colors, count) { - // Check if color3 was used - if (colors.length === count * 3) { - const colors4 = []; - for (let index = 0; index < colors.length; index += 3) { - const newIndex = (index / 3) * 4; - colors4[newIndex] = colors[index]; - colors4[newIndex + 1] = colors[index + 1]; - colors4[newIndex + 2] = colors[index + 2]; - colors4[newIndex + 3] = 1.0; - } - return colors4; - } - return colors; - } -} -/** - * @internal - */ -class TmpColors { -} -TmpColors.Color3 = arrayTools_ArrayTools.BuildArray(3, math_color_Color3.Black); -TmpColors.Color4 = arrayTools_ArrayTools.BuildArray(3, () => new math_color_Color4(0, 0, 0, 0)); -RegisterClass("BABYLON.Color3", math_color_Color3); -RegisterClass("BABYLON.Color4", math_color_Color4); -//# sourceMappingURL=math.color.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Actions/action.js - - - - -/** - * The action to be carried out following a trigger - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#available-actions - */ -class Action { - /** - * Creates a new Action - * @param triggerOptions the trigger, with or without parameters, for the action - * @param condition an optional determinant of action - */ - constructor( - /** the trigger, with or without parameters, for the action */ - triggerOptions, condition) { - this.triggerOptions = triggerOptions; - /** - * An event triggered prior to action being executed. - */ - this.onBeforeExecuteObservable = new observable_Observable(); - if (triggerOptions.parameter) { - this.trigger = triggerOptions.trigger; - this._triggerParameter = triggerOptions.parameter; - } - else if (triggerOptions.trigger) { - this.trigger = triggerOptions.trigger; - } - else { - this.trigger = triggerOptions; - } - this._nextActiveAction = this; - this._condition = condition; - } - /** - * Internal only - * @internal - */ - _prepare() { } - /** - * Gets the trigger parameter - * @returns the trigger parameter - */ - getTriggerParameter() { - return this._triggerParameter; - } - /** - * Sets the trigger parameter - * @param value defines the new trigger parameter - */ - setTriggerParameter(value) { - this._triggerParameter = value; - } - /** - * Internal only - Returns if the current condition allows to run the action - * @internal - */ - _evaluateConditionForCurrentFrame() { - const condition = this._condition; - if (!condition) { - return true; - } - const currentRenderId = this._actionManager.getScene().getRenderId(); - // We cache the current evaluation for the current frame - if (condition._evaluationId !== currentRenderId) { - condition._evaluationId = currentRenderId; - condition._currentResult = condition.isValid(); - } - return condition._currentResult; - } - /** - * Internal only - executes current action event - * @internal - */ - _executeCurrent(evt) { - const isConditionValid = this._evaluateConditionForCurrentFrame(); - if (!isConditionValid) { - return; - } - this.onBeforeExecuteObservable.notifyObservers(this); - this._nextActiveAction.execute(evt); - this.skipToNextActiveAction(); - } - /** - * Execute placeholder for child classes - * @param evt optional action event - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - execute(evt) { } - /** - * Skips to next active action - */ - skipToNextActiveAction() { - if (this._nextActiveAction._child) { - if (!this._nextActiveAction._child._actionManager) { - this._nextActiveAction._child._actionManager = this._actionManager; - } - this._nextActiveAction = this._nextActiveAction._child; - } - else { - this._nextActiveAction = this; - } - } - /** - * Adds action to chain of actions, may be a DoNothingAction - * @param action defines the next action to execute - * @returns The action passed in - * @see https://www.babylonjs-playground.com/#1T30HR#0 - */ - then(action) { - this._child = action; - action._actionManager = this._actionManager; - action._prepare(); - return action; - } - /** - * Internal only - * @internal - */ - _getProperty(propertyPath) { - return this._actionManager._getProperty(propertyPath); - } - /** - * @internal - */ - _getEffectiveTarget(target, propertyPath) { - return this._actionManager._getEffectiveTarget(target, propertyPath); - } - /** - * Serialize placeholder for child classes - * @param parent of child - * @returns the serialized object - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - serialize(parent) { } - /** - * Internal only called by serialize - * @internal - */ - _serialize(serializedAction, parent) { - const serializationObject = { - type: 1, - children: [], - name: serializedAction.name, - properties: serializedAction.properties || [], - }; - // Serialize child - if (this._child) { - this._child.serialize(serializationObject); - } - // Check if "this" has a condition - if (this._condition) { - const serializedCondition = this._condition.serialize(); - serializedCondition.children.push(serializationObject); - if (parent) { - parent.children.push(serializedCondition); - } - return serializedCondition; - } - if (parent) { - parent.children.push(serializationObject); - } - return serializationObject; - } -} -/** - * Internal only - * @internal - */ -Action._SerializeValueAsString = (value) => { - if (typeof value === "number") { - return value.toString(); - } - if (typeof value === "boolean") { - return value ? "true" : "false"; - } - if (value instanceof math_vector_Vector2) { - return value.x + ", " + value.y; - } - if (value instanceof math_vector_Vector3) { - return value.x + ", " + value.y + ", " + value.z; - } - if (value instanceof math_color_Color3) { - return value.r + ", " + value.g + ", " + value.b; - } - if (value instanceof math_color_Color4) { - return value.r + ", " + value.g + ", " + value.b + ", " + value.a; - } - return value; // string -}; -/** - * Internal only - * @internal - */ -Action._GetTargetProperty = (target) => { - return { - name: "target", - targetType: target._isMesh - ? "MeshProperties" - : target._isLight - ? "LightProperties" - : target._isCamera - ? "CameraProperties" - : target._isMaterial - ? "MaterialProperties" - : "SceneProperties", - value: target._isScene ? "Scene" : target.name, - }; -}; -RegisterClass("BABYLON.Action", Action); -//# sourceMappingURL=action.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Actions/actionEvent.js -/** - * ActionEvent is the event being sent when an action is triggered. - */ -class ActionEvent { - /** - * Creates a new ActionEvent - * @param source The mesh or sprite that triggered the action - * @param pointerX The X mouse cursor position at the time of the event - * @param pointerY The Y mouse cursor position at the time of the event - * @param meshUnderPointer The mesh that is currently pointed at (can be null) - * @param sourceEvent the original (browser) event that triggered the ActionEvent - * @param additionalData additional data for the event - */ - constructor( - /** The mesh or sprite that triggered the action */ - source, - /** The X mouse cursor position at the time of the event */ - pointerX, - /** The Y mouse cursor position at the time of the event */ - pointerY, - /** The mesh that is currently pointed at (can be null) */ - meshUnderPointer, - /** the original (browser) event that triggered the ActionEvent */ - sourceEvent, - /** additional data for the event */ - additionalData) { - this.source = source; - this.pointerX = pointerX; - this.pointerY = pointerY; - this.meshUnderPointer = meshUnderPointer; - this.sourceEvent = sourceEvent; - this.additionalData = additionalData; - } - /** - * Helper function to auto-create an ActionEvent from a source mesh. - * @param source The source mesh that triggered the event - * @param evt The original (browser) event - * @param additionalData additional data for the event - * @returns the new ActionEvent - */ - static CreateNew(source, evt, additionalData) { - const scene = source.getScene(); - return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer || source, evt, additionalData); - } - /** - * Helper function to auto-create an ActionEvent from a source sprite - * @param source The source sprite that triggered the event - * @param scene Scene associated with the sprite - * @param evt The original (browser) event - * @param additionalData additional data for the event - * @returns the new ActionEvent - */ - static CreateNewFromSprite(source, scene, evt, additionalData) { - return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData); - } - /** - * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew - * @param scene the scene where the event occurred - * @param evt The original (browser) event - * @returns the new ActionEvent - */ - static CreateNewFromScene(scene, evt) { - return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt); - } - /** - * Helper function to auto-create an ActionEvent from a primitive - * @param prim defines the target primitive - * @param pointerPos defines the pointer position - * @param evt The original (browser) event - * @param additionalData additional data for the event - * @returns the new ActionEvent - */ - static CreateNewFromPrimitive(prim, pointerPos, evt, additionalData) { - return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData); - } -} -//# sourceMappingURL=actionEvent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Actions/condition.js - - -/** - * A Condition applied to an Action - */ -class Condition { - /** - * Creates a new Condition - * @param actionManager the manager of the action the condition is applied to - */ - constructor(actionManager) { - this._actionManager = actionManager; - } - /** - * Check if the current condition is valid - * @returns a boolean - */ - isValid() { - return true; - } - /** - * @internal - */ - _getProperty(propertyPath) { - return this._actionManager._getProperty(propertyPath); - } - /** - * @internal - */ - _getEffectiveTarget(target, propertyPath) { - return this._actionManager._getEffectiveTarget(target, propertyPath); - } - /** - * Serialize placeholder for child classes - * @returns the serialized object - */ - serialize() { } - /** - * @internal - */ - _serialize(serializedCondition) { - return { - type: 2, - children: [], - name: serializedCondition.name, - properties: serializedCondition.properties, - }; - } -} -/** - * Defines specific conditional operators as extensions of Condition - */ -class ValueCondition extends Condition { - /** - * returns the number for IsEqual - */ - static get IsEqual() { - return ValueCondition._IsEqual; - } - /** - * Returns the number for IsDifferent - */ - static get IsDifferent() { - return ValueCondition._IsDifferent; - } - /** - * Returns the number for IsGreater - */ - static get IsGreater() { - return ValueCondition._IsGreater; - } - /** - * Returns the number for IsLesser - */ - static get IsLesser() { - return ValueCondition._IsLesser; - } - /** - * Creates a new ValueCondition - * @param actionManager manager for the action the condition applies to - * @param target for the action - * @param propertyPath path to specify the property of the target the conditional operator uses - * @param value the value compared by the conditional operator against the current value of the property - * @param operator the conditional operator, default ValueCondition.IsEqual - */ - constructor(actionManager, target, - /** path to specify the property of the target the conditional operator uses */ - propertyPath, - /** the value compared by the conditional operator against the current value of the property */ - value, - /** the conditional operator, default ValueCondition.IsEqual */ - operator = ValueCondition.IsEqual) { - super(actionManager); - this.propertyPath = propertyPath; - this.value = value; - this.operator = operator; - this._target = target; - this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath); - this._property = this._getProperty(this.propertyPath); - } - /** - * Compares the given value with the property value for the specified conditional operator - * @returns the result of the comparison - */ - isValid() { - switch (this.operator) { - case ValueCondition.IsGreater: - return this._effectiveTarget[this._property] > this.value; - case ValueCondition.IsLesser: - return this._effectiveTarget[this._property] < this.value; - case ValueCondition.IsEqual: - case ValueCondition.IsDifferent: { - let check; - if (this.value.equals) { - check = this.value.equals(this._effectiveTarget[this._property]); - } - else { - check = this.value === this._effectiveTarget[this._property]; - } - return this.operator === ValueCondition.IsEqual ? check : !check; - } - } - return false; - } - /** - * Serialize the ValueCondition into a JSON compatible object - * @returns serialization object - */ - serialize() { - return this._serialize({ - name: "ValueCondition", - properties: [ - Action._GetTargetProperty(this._target), - { name: "propertyPath", value: this.propertyPath }, - { name: "value", value: Action._SerializeValueAsString(this.value) }, - { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }, - ], - }); - } - /** - * Gets the name of the conditional operator for the ValueCondition - * @param operator the conditional operator - * @returns the name - */ - static GetOperatorName(operator) { - switch (operator) { - case ValueCondition._IsEqual: - return "IsEqual"; - case ValueCondition._IsDifferent: - return "IsDifferent"; - case ValueCondition._IsGreater: - return "IsGreater"; - case ValueCondition._IsLesser: - return "IsLesser"; - default: - return ""; - } - } -} -ValueCondition._IsEqual = 0; -ValueCondition._IsDifferent = 1; -ValueCondition._IsGreater = 2; -ValueCondition._IsLesser = 3; -/** - * Defines a predicate condition as an extension of Condition - */ -class PredicateCondition extends Condition { - /** - * Creates a new PredicateCondition - * @param actionManager manager for the action the condition applies to - * @param predicate defines the predicate function used to validate the condition - */ - constructor(actionManager, - /** defines the predicate function used to validate the condition */ - predicate) { - super(actionManager); - this.predicate = predicate; - } - /** - * @returns the validity of the predicate condition - */ - isValid() { - return this.predicate(); - } -} -/** - * Defines a state condition as an extension of Condition - */ -class StateCondition extends Condition { - /** - * Creates a new StateCondition - * @param actionManager manager for the action the condition applies to - * @param target of the condition - * @param value to compare with target state - */ - constructor(actionManager, target, - /** Value to compare with target state */ - value) { - super(actionManager); - this.value = value; - this._target = target; - } - /** - * Gets a boolean indicating if the current condition is met - * @returns the validity of the state - */ - isValid() { - return this._target.state === this.value; - } - /** - * Serialize the StateCondition into a JSON compatible object - * @returns serialization object - */ - serialize() { - return this._serialize({ - name: "StateCondition", - properties: [Action._GetTargetProperty(this._target), { name: "value", value: this.value }], - }); - } -} -RegisterClass("BABYLON.ValueCondition", ValueCondition); -RegisterClass("BABYLON.PredicateCondition", PredicateCondition); -RegisterClass("BABYLON.StateCondition", StateCondition); -//# sourceMappingURL=condition.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/logger.js -/** - * Logger used throughout the application to allow configuration of - * the log level required for the messages. - */ -class logger_Logger { - static _CheckLimit(message, limit) { - let entry = logger_Logger._LogLimitOutputs[message]; - if (!entry) { - entry = { limit, current: 1 }; - logger_Logger._LogLimitOutputs[message] = entry; - } - else { - entry.current++; - } - return entry.current <= entry.limit; - } - static _GenerateLimitMessage(message, level = 1) { - var _a; - const entry = logger_Logger._LogLimitOutputs[message]; - if (!entry || !logger_Logger.MessageLimitReached) { - return; - } - const type = this._Levels[level]; - if (entry.current === entry.limit) { - logger_Logger[type.name](logger_Logger.MessageLimitReached.replace(/%LIMIT%/g, "" + entry.limit).replace(/%TYPE%/g, (_a = type.name) !== null && _a !== void 0 ? _a : "")); - } - } - static _AddLogEntry(entry) { - logger_Logger._LogCache = entry + logger_Logger._LogCache; - if (logger_Logger.OnNewCacheEntry) { - logger_Logger.OnNewCacheEntry(entry); - } - } - static _FormatMessage(message) { - const padStr = (i) => (i < 10 ? "0" + i : "" + i); - const date = new Date(); - return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static _LogDisabled(message, limit) { - // nothing to do - } - static _LogEnabled(level = 1, message, limit) { - if (limit !== undefined && !logger_Logger._CheckLimit(message, limit)) { - return; - } - const formattedMessage = logger_Logger._FormatMessage(message); - const type = this._Levels[level]; - type.logFunc && type.logFunc("BJS - " + formattedMessage); - const entry = `<div style='color:${type.color}'>${formattedMessage}</div><br>`; - logger_Logger._AddLogEntry(entry); - logger_Logger._GenerateLimitMessage(message, level); - } - /** - * Gets current log cache (list of logs) - */ - static get LogCache() { - return logger_Logger._LogCache; - } - /** - * Clears the log cache - */ - static ClearLogCache() { - logger_Logger._LogCache = ""; - logger_Logger._LogLimitOutputs = {}; - logger_Logger.errorsCount = 0; - } - /** - * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel) - */ - static set LogLevels(level) { - logger_Logger.Log = logger_Logger._LogDisabled; - logger_Logger.Warn = logger_Logger._LogDisabled; - logger_Logger.Error = logger_Logger._LogDisabled; - [logger_Logger.MessageLogLevel, logger_Logger.WarningLogLevel, logger_Logger.ErrorLogLevel].forEach((l) => { - if ((level & l) === l) { - const type = this._Levels[l]; - logger_Logger[type.name] = logger_Logger._LogEnabled.bind(logger_Logger, l); - } - }); - } -} -/** - * No log - */ -logger_Logger.NoneLogLevel = 0; -/** - * Only message logs - */ -logger_Logger.MessageLogLevel = 1; -/** - * Only warning logs - */ -logger_Logger.WarningLogLevel = 2; -/** - * Only error logs - */ -logger_Logger.ErrorLogLevel = 4; -/** - * All logs - */ -logger_Logger.AllLogLevel = 7; -/** - * Message to display when a message has been logged too many times - */ -logger_Logger.MessageLimitReached = "Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message."; -logger_Logger._LogCache = ""; -logger_Logger._LogLimitOutputs = {}; -// levels according to the (binary) numbering. -logger_Logger._Levels = [ - {}, - { color: "white", logFunc: console.log, name: "Log" }, - { color: "orange", logFunc: console.warn, name: "Warn" }, - {}, - { color: "red", logFunc: console.error, name: "Error" }, -]; -/** - * Gets a value indicating the number of loading errors - * @ignorenaming - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -logger_Logger.errorsCount = 0; -/** - * Log a message to the console - */ -logger_Logger.Log = logger_Logger._LogEnabled.bind(logger_Logger, logger_Logger.MessageLogLevel); -/** - * Write a warning message to the console - */ -logger_Logger.Warn = logger_Logger._LogEnabled.bind(logger_Logger, logger_Logger.WarningLogLevel); -/** - * Write an error message to the console - */ -logger_Logger.Error = logger_Logger._LogEnabled.bind(logger_Logger, logger_Logger.ErrorLogLevel); -//# sourceMappingURL=logger.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Actions/directActions.js - - - - - -/** - * This defines an action responsible to toggle a boolean once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class SwitchBooleanAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param target defines the object containing the boolean - * @param propertyPath defines the path to the boolean property in the target object - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions, target, propertyPath, condition) { - super(triggerOptions, condition); - this.propertyPath = propertyPath; - this._target = this._effectiveTarget = target; - } - /** @internal */ - _prepare() { - this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); - this._property = this._getProperty(this.propertyPath); - } - /** - * Execute the action toggle the boolean value. - */ - execute() { - this._effectiveTarget[this._property] = !this._effectiveTarget[this._property]; - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "SwitchBooleanAction", - properties: [Action._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }], - }, parent); - } -} -/** - * This defines an action responsible to set a the state field of the target - * to a desired value once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class SetStateAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param target defines the object containing the state property - * @param value defines the value to store in the state field - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions, target, value, condition) { - super(triggerOptions, condition); - this.value = value; - this._target = target; - } - /** - * Execute the action and store the value on the target state property. - */ - execute() { - this._target.state = this.value; - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "SetStateAction", - properties: [Action._GetTargetProperty(this._target), { name: "value", value: this.value }], - }, parent); - } -} -/** - * This defines an action responsible to set a property of the target - * to a desired value once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class SetValueAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param target defines the object containing the property - * @param propertyPath defines the path of the property to set in the target - * @param value defines the value to set in the property - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions, target, propertyPath, value, condition) { - super(triggerOptions, condition); - this.propertyPath = propertyPath; - this.value = value; - this._target = this._effectiveTarget = target; - } - /** @internal */ - _prepare() { - this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); - this._property = this._getProperty(this.propertyPath); - } - /** - * Execute the action and set the targeted property to the desired value. - */ - execute() { - this._effectiveTarget[this._property] = this.value; - if (this._target.markAsDirty) { - this._target.markAsDirty(this._property); - } - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "SetValueAction", - properties: [ - Action._GetTargetProperty(this._target), - { name: "propertyPath", value: this.propertyPath }, - { name: "value", value: Action._SerializeValueAsString(this.value) }, - ], - }, parent); - } -} -/** - * This defines an action responsible to increment the target value - * to a desired value once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class IncrementValueAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param target defines the object containing the property - * @param propertyPath defines the path of the property to increment in the target - * @param value defines the value value we should increment the property by - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions, target, propertyPath, value, condition) { - super(triggerOptions, condition); - this.propertyPath = propertyPath; - this.value = value; - this._target = this._effectiveTarget = target; - } - /** @internal */ - _prepare() { - this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); - this._property = this._getProperty(this.propertyPath); - if (typeof this._effectiveTarget[this._property] !== "number") { - logger_Logger.Warn("Warning: IncrementValueAction can only be used with number values"); - } - } - /** - * Execute the action and increment the target of the value amount. - */ - execute() { - this._effectiveTarget[this._property] += this.value; - if (this._target.markAsDirty) { - this._target.markAsDirty(this._property); - } - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "IncrementValueAction", - properties: [ - Action._GetTargetProperty(this._target), - { name: "propertyPath", value: this.propertyPath }, - { name: "value", value: Action._SerializeValueAsString(this.value) }, - ], - }, parent); - } -} -/** - * This defines an action responsible to start an animation once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class PlayAnimationAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param target defines the target animation or animation name - * @param from defines from where the animation should start (animation frame) - * @param to defines where the animation should stop (animation frame) - * @param loop defines if the animation should loop or stop after the first play - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions, target, from, to, loop, condition) { - super(triggerOptions, condition); - this.from = from; - this.to = to; - this.loop = loop; - this._target = target; - } - /** @internal */ - _prepare() { } - /** - * Execute the action and play the animation. - */ - execute() { - const scene = this._actionManager.getScene(); - scene.beginAnimation(this._target, this.from, this.to, this.loop); - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "PlayAnimationAction", - properties: [ - Action._GetTargetProperty(this._target), - { name: "from", value: String(this.from) }, - { name: "to", value: String(this.to) }, - { name: "loop", value: Action._SerializeValueAsString(this.loop) || false }, - ], - }, parent); - } -} -/** - * This defines an action responsible to stop an animation once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class StopAnimationAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param target defines the target animation or animation name - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions, target, condition) { - super(triggerOptions, condition); - this._target = target; - } - /** @internal */ - _prepare() { } - /** - * Execute the action and stop the animation. - */ - execute() { - const scene = this._actionManager.getScene(); - scene.stopAnimation(this._target); - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "StopAnimationAction", - properties: [Action._GetTargetProperty(this._target)], - }, parent); - } -} -/** - * This defines an action responsible that does nothing once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class DoNothingAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions = 0, condition) { - super(triggerOptions, condition); - } - /** - * Execute the action and do nothing. - */ - execute() { } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "DoNothingAction", - properties: [], - }, parent); - } -} -/** - * This defines an action responsible to trigger several actions once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class CombineAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param children defines the list of aggregated animations to run - * @param condition defines the trigger related conditions - * @param enableChildrenConditions defines if the children actions conditions should be check before execution - */ - constructor(triggerOptions, children, condition, enableChildrenConditions = true) { - super(triggerOptions, condition); - this.children = children; - this.enableChildrenConditions = enableChildrenConditions; - } - /** @internal */ - _prepare() { - for (let index = 0; index < this.children.length; index++) { - this.children[index]._actionManager = this._actionManager; - this.children[index]._prepare(); - } - } - /** - * Execute the action and executes all the aggregated actions. - * @param evt - */ - execute(evt) { - for (const action of this.children) { - if (!this.enableChildrenConditions || action._evaluateConditionForCurrentFrame()) { - action.execute(evt); - } - } - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - const serializationObject = super._serialize({ - name: "CombineAction", - properties: [], - combine: [], - }, parent); - for (let i = 0; i < this.children.length; i++) { - serializationObject.combine.push(this.children[i].serialize(null)); - } - return serializationObject; - } -} -/** - * This defines an action responsible to run code (external event) once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class ExecuteCodeAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param func defines the callback function to run - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions, func, condition) { - super(triggerOptions, condition); - this.func = func; - } - /** - * Execute the action and run the attached code. - * @param evt - */ - execute(evt) { - this.func(evt); - } -} -/** - * This defines an action responsible to set the parent property of the target once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class SetParentAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param target defines the target containing the parent property - * @param parent defines from where the animation should start (animation frame) - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions, target, parent, condition) { - super(triggerOptions, condition); - this._target = target; - this._parent = parent; - } - /** @internal */ - _prepare() { } - /** - * Execute the action and set the parent property. - */ - execute() { - if (this._target.parent === this._parent) { - return; - } - const invertParentWorldMatrix = this._parent.getWorldMatrix().clone(); - invertParentWorldMatrix.invert(); - this._target.position = math_vector_Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix); - this._target.parent = this._parent; - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "SetParentAction", - properties: [Action._GetTargetProperty(this._target), Action._GetTargetProperty(this._parent)], - }, parent); - } -} -RegisterClass("BABYLON.SetParentAction", SetParentAction); -RegisterClass("BABYLON.ExecuteCodeAction", ExecuteCodeAction); -RegisterClass("BABYLON.DoNothingAction", DoNothingAction); -RegisterClass("BABYLON.StopAnimationAction", StopAnimationAction); -RegisterClass("BABYLON.PlayAnimationAction", PlayAnimationAction); -RegisterClass("BABYLON.IncrementValueAction", IncrementValueAction); -RegisterClass("BABYLON.SetValueAction", SetValueAction); -RegisterClass("BABYLON.SetStateAction", SetStateAction); -RegisterClass("BABYLON.SetParentAction", SetParentAction); -RegisterClass("BABYLON.SwitchBooleanAction", SwitchBooleanAction); -RegisterClass("BABYLON.CombineAction", CombineAction); -//# sourceMappingURL=directActions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/deepCopier.js - -const CloneValue = (source, destinationObject) => { - if (!source) { - return null; - } - if (source.getClassName && source.getClassName() === "Mesh") { - return null; - } - if (source.getClassName && (source.getClassName() === "SubMesh" || source.getClassName() === "PhysicsBody")) { - return source.clone(destinationObject); - } - else if (source.clone) { - return source.clone(); - } - else if (Array.isArray(source)) { - return source.slice(); - } - return null; -}; -function GetAllPropertyNames(obj) { - const props = []; - do { - Object.getOwnPropertyNames(obj).forEach(function (prop) { - if (props.indexOf(prop) === -1) { - props.push(prop); - } - }); - } while ((obj = Object.getPrototypeOf(obj))); - return props; -} -/** - * Class containing a set of static utilities functions for deep copy. - */ -class DeepCopier { - /** - * Tries to copy an object by duplicating every property - * @param source defines the source object - * @param destination defines the target object - * @param doNotCopyList defines a list of properties to avoid - * @param mustCopyList defines a list of properties to copy (even if they start with _) - */ - static DeepCopy(source, destination, doNotCopyList, mustCopyList) { - const properties = GetAllPropertyNames(source); - for (const prop of properties) { - if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) { - continue; - } - if (prop.endsWith("Observable")) { - continue; - } - if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) { - continue; - } - const sourceValue = source[prop]; - const typeOfSourceValue = typeof sourceValue; - if (typeOfSourceValue === "function") { - continue; - } - try { - if (typeOfSourceValue === "object") { - if (sourceValue instanceof Uint8Array) { - destination[prop] = Uint8Array.from(sourceValue); - } - else if (sourceValue instanceof Array) { - destination[prop] = []; - if (sourceValue.length > 0) { - if (typeof sourceValue[0] == "object") { - for (let index = 0; index < sourceValue.length; index++) { - const clonedValue = CloneValue(sourceValue[index], destination); - if (destination[prop].indexOf(clonedValue) === -1) { - // Test if auto inject was not done - destination[prop].push(clonedValue); - } - } - } - else { - destination[prop] = sourceValue.slice(0); - } - } - } - else { - destination[prop] = CloneValue(sourceValue, destination); - } - } - else { - destination[prop] = sourceValue; - } - } - catch (e) { - // Log a warning (it could be because of a read-only property) - logger_Logger.Warn(e.message); - } - } - } -} -//# sourceMappingURL=deepCopier.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Actions/actionManager.js - - - - - - - - - - - -/** - * Action Manager manages all events to be triggered on a given mesh or the global scene. - * A single scene can have many Action Managers to handle predefined actions on specific meshes. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class ActionManager extends AbstractActionManager { - /** - * Creates a new action manager - * @param scene defines the hosting scene - */ - constructor(scene) { - super(); - scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!scene) { - return; - } - this._scene = scene; - scene.actionManagers.push(this); - } - // Methods - /** - * Releases all associated resources - */ - dispose() { - const sceneIndex = this._scene.actionManagers.indexOf(this); - for (let i = 0; i < this.actions.length; i++) { - const action = this.actions[i]; - ActionManager.Triggers[action.trigger]--; - if (ActionManager.Triggers[action.trigger] === 0) { - delete ActionManager.Triggers[action.trigger]; - } - } - this.actions.length = 0; - if (sceneIndex > -1) { - this._scene.actionManagers.splice(sceneIndex, 1); - } - const ownerMesh = this._scene.meshes.find((m) => m.actionManager === this); - if (ownerMesh) { - ownerMesh.actionManager = null; - } - } - /** - * Gets hosting scene - * @returns the hosting scene - */ - getScene() { - return this._scene; - } - /** - * Does this action manager handles actions of any of the given triggers - * @param triggers defines the triggers to be tested - * @returns a boolean indicating whether one (or more) of the triggers is handled - */ - hasSpecificTriggers(triggers) { - for (let index = 0; index < this.actions.length; index++) { - const action = this.actions[index]; - if (triggers.indexOf(action.trigger) > -1) { - return true; - } - } - return false; - } - /** - * Does this action manager handles actions of any of the given triggers. This function takes two arguments for - * speed. - * @param triggerA defines the trigger to be tested - * @param triggerB defines the trigger to be tested - * @returns a boolean indicating whether one (or more) of the triggers is handled - */ - hasSpecificTriggers2(triggerA, triggerB) { - for (let index = 0; index < this.actions.length; index++) { - const action = this.actions[index]; - if (triggerA == action.trigger || triggerB == action.trigger) { - return true; - } - } - return false; - } - /** - * Does this action manager handles actions of a given trigger - * @param trigger defines the trigger to be tested - * @param parameterPredicate defines an optional predicate to filter triggers by parameter - * @returns whether the trigger is handled - */ - hasSpecificTrigger(trigger, parameterPredicate) { - for (let index = 0; index < this.actions.length; index++) { - const action = this.actions[index]; - if (action.trigger === trigger) { - if (parameterPredicate) { - if (parameterPredicate(action.getTriggerParameter())) { - return true; - } - } - else { - return true; - } - } - } - return false; - } - /** - * Does this action manager has pointer triggers - */ - get hasPointerTriggers() { - for (let index = 0; index < this.actions.length; index++) { - const action = this.actions[index]; - if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) { - return true; - } - } - return false; - } - /** - * Does this action manager has pick triggers - */ - get hasPickTriggers() { - for (let index = 0; index < this.actions.length; index++) { - const action = this.actions[index]; - if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) { - return true; - } - } - return false; - } - /** - * Registers an action to this action manager - * @param action defines the action to be registered - * @returns the action amended (prepared) after registration - */ - registerAction(action) { - if (action.trigger === ActionManager.OnEveryFrameTrigger) { - if (this.getScene().actionManager !== this) { - logger_Logger.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"); - return null; - } - } - this.actions.push(action); - this.getScene()._registeredActions++; - if (ActionManager.Triggers[action.trigger]) { - ActionManager.Triggers[action.trigger]++; - } - else { - ActionManager.Triggers[action.trigger] = 1; - } - action._actionManager = this; - action._prepare(); - return action; - } - /** - * Unregisters an action to this action manager - * @param action defines the action to be unregistered - * @returns a boolean indicating whether the action has been unregistered - */ - unregisterAction(action) { - const index = this.actions.indexOf(action); - if (index !== -1) { - this.actions.splice(index, 1); - ActionManager.Triggers[action.trigger] -= 1; - if (ActionManager.Triggers[action.trigger] === 0) { - delete ActionManager.Triggers[action.trigger]; - } - action._actionManager = null; - this.getScene()._registeredActions--; - return true; - } - return false; - } - /** - * Process a specific trigger - * @param trigger defines the trigger to process - * @param evt defines the event details to be processed - */ - processTrigger(trigger, evt) { - for (let index = 0; index < this.actions.length; index++) { - const action = this.actions[index]; - if (action.trigger === trigger) { - if (evt) { - if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) { - const parameter = action.getTriggerParameter(); - if (typeof parameter === "function") { - if (!parameter(evt)) { - continue; - } - } - else if (parameter && parameter !== evt.sourceEvent.keyCode) { - if (!parameter.toLowerCase) { - continue; - } - const lowerCase = parameter.toLowerCase(); - if (lowerCase !== evt.sourceEvent.key) { - const unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode; - const actualkey = String.fromCharCode(unicode).toLowerCase(); - if (actualkey !== lowerCase) { - continue; - } - } - } - } - } - action._executeCurrent(evt); - } - } - } - /** - * @internal - */ - _getEffectiveTarget(target, propertyPath) { - const properties = propertyPath.split("."); - for (let index = 0; index < properties.length - 1; index++) { - target = target[properties[index]]; - } - return target; - } - /** - * @internal - */ - _getProperty(propertyPath) { - const properties = propertyPath.split("."); - return properties[properties.length - 1]; - } - /** - * Serialize this manager to a JSON object - * @param name defines the property name to store this manager - * @returns a JSON representation of this manager - */ - serialize(name) { - const root = { - children: new Array(), - name: name, - type: 3, - properties: new Array(), // Empty for root but required - }; - for (let i = 0; i < this.actions.length; i++) { - const triggerObject = { - type: 0, - children: new Array(), - name: ActionManager.GetTriggerName(this.actions[i].trigger), - properties: new Array(), - }; - const triggerOptions = this.actions[i].triggerOptions; - if (triggerOptions && typeof triggerOptions !== "number") { - if (triggerOptions.parameter instanceof Node) { - triggerObject.properties.push(Action._GetTargetProperty(triggerOptions.parameter)); - } - else if (typeof triggerOptions.parameter === "object") { - const parameter = {}; - DeepCopier.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]); - if (triggerOptions.parameter && triggerOptions.parameter.mesh) { - parameter._meshId = triggerOptions.parameter.mesh.id; - } - triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter }); - } - else { - triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter }); - } - } - // Serialize child action, recursively - this.actions[i].serialize(triggerObject); - // Add serialized trigger - root.children.push(triggerObject); - } - return root; - } - /** - * Creates a new ActionManager from a JSON data - * @param parsedActions defines the JSON data to read from - * @param object defines the hosting mesh - * @param scene defines the hosting scene - */ - static Parse(parsedActions, object, scene) { - const actionManager = new ActionManager(scene); - if (object === null) { - scene.actionManager = actionManager; - } - else { - object.actionManager = actionManager; - } - // instantiate a new object - const instantiate = (name, params) => { - const internalClassType = GetClass("BABYLON." + name); - return internalClassType && new internalClassType(...params); - }; - const parseParameter = (name, value, target, propertyPath) => { - if (propertyPath === null) { - // String, boolean or float - const floatValue = parseFloat(value); - if (value === "true" || value === "false") { - return value === "true"; - } - else { - return isNaN(floatValue) ? value : floatValue; - } - } - const effectiveTarget = propertyPath.split("."); - const values = value.split(","); - // Get effective Target - for (let i = 0; i < effectiveTarget.length; i++) { - target = target[effectiveTarget[i]]; - } - // Return appropriate value with its type - if (typeof target === "boolean") { - return values[0] === "true"; - } - if (typeof target === "string") { - return values[0]; - } - // Parameters with multiple values such as Vector3 etc. - const split = new Array(); - for (let i = 0; i < values.length; i++) { - split.push(parseFloat(values[i])); - } - if (target instanceof math_vector_Vector3) { - return math_vector_Vector3.FromArray(split); - } - if (target instanceof math_vector_Vector4) { - return math_vector_Vector4.FromArray(split); - } - if (target instanceof math_color_Color3) { - return math_color_Color3.FromArray(split); - } - if (target instanceof math_color_Color4) { - return math_color_Color4.FromArray(split); - } - return parseFloat(values[0]); - }; - // traverse graph per trigger - const traverse = (parsedAction, trigger, condition, action, combineArray = null) => { - if (parsedAction.detached) { - return; - } - const parameters = new Array(); - let target = null; - let propertyPath = null; - const combine = parsedAction.combine && parsedAction.combine.length > 0; - // Parameters - if (parsedAction.type === 2) { - parameters.push(actionManager); - } - else { - parameters.push(trigger); - } - if (combine) { - const actions = new Array(); - for (let j = 0; j < parsedAction.combine.length; j++) { - traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions); - } - parameters.push(actions); - } - else { - for (let i = 0; i < parsedAction.properties.length; i++) { - let value = parsedAction.properties[i].value; - const name = parsedAction.properties[i].name; - const targetType = parsedAction.properties[i].targetType; - if (name === "target") { - if (targetType === "SceneProperties") { - value = target = scene; - } - else if (targetType === "MaterialProperties") { - value = target = scene.getMaterialByName(value); - } - else { - value = target = scene.getNodeByName(value); - } - } - else if (name === "parent") { - value = scene.getNodeByName(value); - } - else if (name === "sound") { - // Can not externalize to component, so only checks for the presence off the API. - if (scene.getSoundByName) { - value = scene.getSoundByName(value); - } - } - else if (name !== "propertyPath") { - if (parsedAction.type === 2 && name === "operator") { - value = ValueCondition[value]; - } - else { - value = parseParameter(name, value, target, name === "value" ? propertyPath : null); - } - } - else { - propertyPath = value; - } - parameters.push(value); - } - } - if (combineArray === null) { - parameters.push(condition); - } - else { - parameters.push(null); - } - // If interpolate value action - if (parsedAction.name === "InterpolateValueAction") { - const param = parameters[parameters.length - 2]; - parameters[parameters.length - 1] = param; - parameters[parameters.length - 2] = condition; - } - // Action or condition(s) and not CombineAction - let newAction = instantiate(parsedAction.name, parameters); - if (newAction instanceof Condition && condition !== null) { - const nothing = new DoNothingAction(trigger, condition); - if (action) { - action.then(nothing); - } - else { - actionManager.registerAction(nothing); - } - action = nothing; - } - if (combineArray === null) { - if (newAction instanceof Condition) { - condition = newAction; - newAction = action; - } - else { - condition = null; - if (action) { - action.then(newAction); - } - else { - actionManager.registerAction(newAction); - } - } - } - else { - combineArray.push(newAction); - } - for (let i = 0; i < parsedAction.children.length; i++) { - traverse(parsedAction.children[i], trigger, condition, newAction, null); - } - }; - // triggers - for (let i = 0; i < parsedActions.children.length; i++) { - let triggerParams; - const trigger = parsedActions.children[i]; - if (trigger.properties.length > 0) { - const param = trigger.properties[0].value; - const value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param); - if (value._meshId) { - value.mesh = scene.getMeshById(value._meshId); - } - triggerParams = { trigger: ActionManager[trigger.name], parameter: value }; - } - else { - triggerParams = ActionManager[trigger.name]; - } - for (let j = 0; j < trigger.children.length; j++) { - if (!trigger.detached) { - traverse(trigger.children[j], triggerParams, null, null); - } - } - } - } - /** - * Get a trigger name by index - * @param trigger defines the trigger index - * @returns a trigger name - */ - static GetTriggerName(trigger) { - switch (trigger) { - case 0: - return "NothingTrigger"; - case 1: - return "OnPickTrigger"; - case 2: - return "OnLeftPickTrigger"; - case 3: - return "OnRightPickTrigger"; - case 4: - return "OnCenterPickTrigger"; - case 5: - return "OnPickDownTrigger"; - case 6: - return "OnDoublePickTrigger"; // start; - case 7: - return "OnPickUpTrigger"; - case 8: - return "OnLongPressTrigger"; - case 9: - return "OnPointerOverTrigger"; - case 10: - return "OnPointerOutTrigger"; - case 11: - return "OnEveryFrameTrigger"; - case 12: - return "OnIntersectionEnterTrigger"; - case 13: - return "OnIntersectionExitTrigger"; - case 14: - return "OnKeyDownTrigger"; - case 15: - return "OnKeyUpTrigger"; - case 16: - return "OnPickOutTrigger"; - default: - return ""; - } - } -} -/** - * Nothing - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.NothingTrigger = 0; -/** - * On pick - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnPickTrigger = 1; -/** - * On left pick - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnLeftPickTrigger = 2; -/** - * On right pick - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnRightPickTrigger = 3; -/** - * On center pick - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnCenterPickTrigger = 4; -/** - * On pick down - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnPickDownTrigger = 5; -/** - * On double pick - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnDoublePickTrigger = 6; -/** - * On pick up - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnPickUpTrigger = 7; -/** - * On pick out. - * This trigger will only be raised if you also declared a OnPickDown - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnPickOutTrigger = 16; -/** - * On long press - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnLongPressTrigger = 8; -/** - * On pointer over - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnPointerOverTrigger = 9; -/** - * On pointer out - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnPointerOutTrigger = 10; -/** - * On every frame - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnEveryFrameTrigger = 11; -/** - * On intersection enter - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnIntersectionEnterTrigger = 12; -/** - * On intersection exit - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnIntersectionExitTrigger = 13; -/** - * On key down - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnKeyDownTrigger = 14; -/** - * On key up - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -ActionManager.OnKeyUpTrigger = 15; -//# sourceMappingURL=actionManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Actions/directAudioActions.js - - -/** - * This defines an action helpful to play a defined sound on a triggered action. - */ -class PlaySoundAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param sound defines the sound to play - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions, sound, condition) { - super(triggerOptions, condition); - this._sound = sound; - } - /** @internal */ - _prepare() { } - /** - * Execute the action and play the sound. - */ - execute() { - if (this._sound !== undefined) { - this._sound.play(); - } - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "PlaySoundAction", - properties: [{ name: "sound", value: this._sound.name }], - }, parent); - } -} -/** - * This defines an action helpful to stop a defined sound on a triggered action. - */ -class StopSoundAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param sound defines the sound to stop - * @param condition defines the trigger related conditions - */ - constructor(triggerOptions, sound, condition) { - super(triggerOptions, condition); - this._sound = sound; - } - /** @internal */ - _prepare() { } - /** - * Execute the action and stop the sound. - */ - execute() { - if (this._sound !== undefined) { - this._sound.stop(); - } - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "StopSoundAction", - properties: [{ name: "sound", value: this._sound.name }], - }, parent); - } -} -RegisterClass("BABYLON.PlaySoundAction", PlaySoundAction); -RegisterClass("BABYLON.StopSoundAction", StopSoundAction); -//# sourceMappingURL=directAudioActions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/andOrNotEvaluator.js -/** - * Class used to evaluate queries containing `and` and `or` operators - */ -class AndOrNotEvaluator { - /** - * Evaluate a query - * @param query defines the query to evaluate - * @param evaluateCallback defines the callback used to filter result - * @returns true if the query matches - */ - static Eval(query, evaluateCallback) { - if (!query.match(/\([^()]*\)/g)) { - query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback); - } - else { - query = query.replace(/\([^()]*\)/g, (r) => { - // remove parenthesis - r = r.slice(1, r.length - 1); - return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback); - }); - } - if (query === "true") { - return true; - } - if (query === "false") { - return false; - } - return AndOrNotEvaluator.Eval(query, evaluateCallback); - } - static _HandleParenthesisContent(parenthesisContent, evaluateCallback) { - evaluateCallback = - evaluateCallback || - ((r) => { - return r === "true" ? true : false; - }); - let result; - const or = parenthesisContent.split("||"); - for (const i in or) { - if (Object.prototype.hasOwnProperty.call(or, i)) { - let ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim()); - const and = ori.split("&&"); - if (and.length > 1) { - for (let j = 0; j < and.length; ++j) { - const andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim()); - if (andj !== "true" && andj !== "false") { - if (andj[0] === "!") { - result = !evaluateCallback(andj.substring(1)); - } - else { - result = evaluateCallback(andj); - } - } - else { - result = andj === "true" ? true : false; - } - if (!result) { - // no need to continue since 'false && ... && ...' will always return false - ori = "false"; - break; - } - } - } - if (result || ori === "true") { - // no need to continue since 'true || ... || ...' will always return true - result = true; - break; - } - // result equals false (or undefined) - if (ori !== "true" && ori !== "false") { - if (ori[0] === "!") { - result = !evaluateCallback(ori.substring(1)); - } - else { - result = evaluateCallback(ori); - } - } - else { - result = ori === "true" ? true : false; - } - } - } - // the whole parenthesis scope is replaced by 'true' or 'false' - return result ? "true" : "false"; - } - static _SimplifyNegation(booleanString) { - booleanString = booleanString.replace(/^[\s!]+/, (r) => { - // remove whitespaces - r = r.replace(/[\s]/g, () => ""); - return r.length % 2 ? "!" : ""; - }); - booleanString = booleanString.trim(); - if (booleanString === "!true") { - booleanString = "false"; - } - else if (booleanString === "!false") { - booleanString = "true"; - } - return booleanString; - } -} -//# sourceMappingURL=andOrNotEvaluator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/tags.js - -/** - * Class used to store custom tags - */ -class Tags { - /** - * Adds support for tags on the given object - * @param obj defines the object to use - */ - static EnableFor(obj) { - obj._tags = obj._tags || {}; - obj.hasTags = () => { - return Tags.HasTags(obj); - }; - obj.addTags = (tagsString) => { - return Tags.AddTagsTo(obj, tagsString); - }; - obj.removeTags = (tagsString) => { - return Tags.RemoveTagsFrom(obj, tagsString); - }; - obj.matchesTagsQuery = (tagsQuery) => { - return Tags.MatchesQuery(obj, tagsQuery); - }; - } - /** - * Removes tags support - * @param obj defines the object to use - */ - static DisableFor(obj) { - delete obj._tags; - delete obj.hasTags; - delete obj.addTags; - delete obj.removeTags; - delete obj.matchesTagsQuery; - } - /** - * Gets a boolean indicating if the given object has tags - * @param obj defines the object to use - * @returns a boolean - */ - static HasTags(obj) { - if (!obj._tags) { - return false; - } - const tags = obj._tags; - for (const i in tags) { - if (Object.prototype.hasOwnProperty.call(tags, i)) { - return true; - } - } - return false; - } - /** - * Gets the tags available on a given object - * @param obj defines the object to use - * @param asString defines if the tags must be returned as a string instead of an array of strings - * @returns the tags - */ - static GetTags(obj, asString = true) { - if (!obj._tags) { - return null; - } - if (asString) { - const tagsArray = []; - for (const tag in obj._tags) { - if (Object.prototype.hasOwnProperty.call(obj._tags, tag) && obj._tags[tag] === true) { - tagsArray.push(tag); - } - } - return tagsArray.join(" "); - } - else { - return obj._tags; - } - } - /** - * Adds tags to an object - * @param obj defines the object to use - * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags. - * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces - */ - static AddTagsTo(obj, tagsString) { - if (!tagsString) { - return; - } - if (typeof tagsString !== "string") { - return; - } - const tags = tagsString.split(" "); - tags.forEach(function (tag) { - Tags._AddTagTo(obj, tag); - }); - } - /** - * @internal - */ - static _AddTagTo(obj, tag) { - tag = tag.trim(); - if (tag === "" || tag === "true" || tag === "false") { - return; - } - if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) { - return; - } - Tags.EnableFor(obj); - obj._tags[tag] = true; - } - /** - * Removes specific tags from a specific object - * @param obj defines the object to use - * @param tagsString defines the tags to remove - */ - static RemoveTagsFrom(obj, tagsString) { - if (!Tags.HasTags(obj)) { - return; - } - const tags = tagsString.split(" "); - for (const t in tags) { - Tags._RemoveTagFrom(obj, tags[t]); - } - } - /** - * @internal - */ - static _RemoveTagFrom(obj, tag) { - delete obj._tags[tag]; - } - /** - * Defines if tags hosted on an object match a given query - * @param obj defines the object to use - * @param tagsQuery defines the tag query - * @returns a boolean - */ - static MatchesQuery(obj, tagsQuery) { - if (tagsQuery === undefined) { - return true; - } - if (tagsQuery === "") { - return Tags.HasTags(obj); - } - return AndOrNotEvaluator.Eval(tagsQuery, (r) => Tags.HasTags(obj) && obj._tags[r]); - } -} -//# sourceMappingURL=tags.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/devTools.js -/** - * @internal - */ -function _WarnImport(name) { - return `${name} needs to be imported before as it contains a side-effect required by your code.`; -} -//# sourceMappingURL=devTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/decorators.js -/* eslint-disable @typescript-eslint/no-unused-vars */ -/* eslint-disable @typescript-eslint/naming-convention */ - - - - -const __decoratorInitialStore = {}; -const __mergedStore = {}; -const _copySource = function (creationFunction, source, instanciate, options = {}) { - const destination = creationFunction(); - // Tags - if (Tags && Tags.HasTags(source)) { - Tags.AddTagsTo(destination, Tags.GetTags(source, true)); - } - const classStore = getMergedStore(destination); - // Map from source texture uniqueId to destination texture - const textureMap = {}; - // Properties - for (const property in classStore) { - const propertyDescriptor = classStore[property]; - const sourceProperty = source[property]; - const propertyType = propertyDescriptor.type; - if (sourceProperty !== undefined && sourceProperty !== null && (property !== "uniqueId" || decorators_SerializationHelper.AllowLoadingUniqueId)) { - switch (propertyType) { - case 0: // Value - case 6: // Mesh reference - case 11: // Camera reference - destination[property] = sourceProperty; - break; - case 1: // Texture - if (options.cloneTexturesOnlyOnce && textureMap[sourceProperty.uniqueId]) { - destination[property] = textureMap[sourceProperty.uniqueId]; - } - else { - destination[property] = instanciate || sourceProperty.isRenderTarget ? sourceProperty : sourceProperty.clone(); - textureMap[sourceProperty.uniqueId] = destination[property]; - } - break; - case 2: // Color3 - case 3: // FresnelParameters - case 4: // Vector2 - case 5: // Vector3 - case 7: // Color Curves - case 10: // Quaternion - case 12: // Matrix - destination[property] = instanciate ? sourceProperty : sourceProperty.clone(); - break; - } - } - } - return destination; -}; -function getDirectStore(target) { - const classKey = target.getClassName(); - if (!__decoratorInitialStore[classKey]) { - __decoratorInitialStore[classKey] = {}; - } - return __decoratorInitialStore[classKey]; -} -/** - * Return the list of properties flagged as serializable - * @param target host object - */ -function getMergedStore(target) { - const classKey = target.getClassName(); - if (__mergedStore[classKey]) { - return __mergedStore[classKey]; - } - __mergedStore[classKey] = {}; - const store = __mergedStore[classKey]; - let currentTarget = target; - let currentKey = classKey; - while (currentKey) { - const initialStore = __decoratorInitialStore[currentKey]; - for (const property in initialStore) { - store[property] = initialStore[property]; - } - let parent; - let done = false; - do { - parent = Object.getPrototypeOf(currentTarget); - if (!parent.getClassName) { - done = true; - break; - } - if (parent.getClassName() !== currentKey) { - break; - } - currentTarget = parent; - } while (parent); - if (done) { - break; - } - currentKey = parent.getClassName(); - currentTarget = parent; - } - return store; -} -function generateSerializableMember(type, sourceName) { - return (target, propertyKey) => { - const classStore = getDirectStore(target); - if (!classStore[propertyKey]) { - classStore[propertyKey] = { type: type, sourceName: sourceName }; - } - }; -} -function generateExpandMember(setCallback, targetKey = null) { - return (target, propertyKey) => { - const key = targetKey || "_" + propertyKey; - Object.defineProperty(target, propertyKey, { - get: function () { - return this[key]; - }, - set: function (value) { - // does this object (i.e. vector3) has an equals function? use it! - // Note - not using "with epsilon" here, it is expected te behave like the internal cache does. - if (typeof this.equals === "function") { - if (this.equals(value)) { - return; - } - } - if (this[key] === value) { - return; - } - this[key] = value; - target[setCallback].apply(this); - }, - enumerable: true, - configurable: true, - }); - }; -} -function expandToProperty(callback, targetKey = null) { - return generateExpandMember(callback, targetKey); -} -function serialize(sourceName) { - return generateSerializableMember(0, sourceName); // value member -} -function serializeAsTexture(sourceName) { - return generateSerializableMember(1, sourceName); // texture member -} -function serializeAsColor3(sourceName) { - return generateSerializableMember(2, sourceName); // color3 member -} -function serializeAsFresnelParameters(sourceName) { - return generateSerializableMember(3, sourceName); // fresnel parameters member -} -function serializeAsVector2(sourceName) { - return generateSerializableMember(4, sourceName); // vector2 member -} -function serializeAsVector3(sourceName) { - return generateSerializableMember(5, sourceName); // vector3 member -} -function serializeAsMeshReference(sourceName) { - return generateSerializableMember(6, sourceName); // mesh reference member -} -function serializeAsColorCurves(sourceName) { - return generateSerializableMember(7, sourceName); // color curves -} -function serializeAsColor4(sourceName) { - return generateSerializableMember(8, sourceName); // color 4 -} -function serializeAsImageProcessingConfiguration(sourceName) { - return generateSerializableMember(9, sourceName); // image processing -} -function serializeAsQuaternion(sourceName) { - return generateSerializableMember(10, sourceName); // quaternion member -} -function serializeAsMatrix(sourceName) { - return generateSerializableMember(12, sourceName); // matrix member -} -/** - * Decorator used to define property that can be serialized as reference to a camera - * @param sourceName defines the name of the property to decorate - */ -function serializeAsCameraReference(sourceName) { - return generateSerializableMember(11, sourceName); // camera reference member -} -/** - * Class used to help serialization objects - */ -class decorators_SerializationHelper { - /** - * Appends the serialized animations from the source animations - * @param source Source containing the animations - * @param destination Target to store the animations - */ - static AppendSerializedAnimations(source, destination) { - if (source.animations) { - destination.animations = []; - for (let animationIndex = 0; animationIndex < source.animations.length; animationIndex++) { - const animation = source.animations[animationIndex]; - destination.animations.push(animation.serialize()); - } - } - } - /** - * Static function used to serialized a specific entity - * @param entity defines the entity to serialize - * @param serializationObject defines the optional target object where serialization data will be stored - * @returns a JSON compatible object representing the serialization of the entity - */ - static Serialize(entity, serializationObject) { - if (!serializationObject) { - serializationObject = {}; - } - // Tags - if (Tags) { - serializationObject.tags = Tags.GetTags(entity); - } - const serializedProperties = getMergedStore(entity); - // Properties - for (const property in serializedProperties) { - const propertyDescriptor = serializedProperties[property]; - const targetPropertyName = propertyDescriptor.sourceName || property; - const propertyType = propertyDescriptor.type; - const sourceProperty = entity[property]; - if (sourceProperty !== undefined && sourceProperty !== null && (property !== "uniqueId" || decorators_SerializationHelper.AllowLoadingUniqueId)) { - switch (propertyType) { - case 0: // Value - serializationObject[targetPropertyName] = sourceProperty; - break; - case 1: // Texture - serializationObject[targetPropertyName] = sourceProperty.serialize(); - break; - case 2: // Color3 - serializationObject[targetPropertyName] = sourceProperty.asArray(); - break; - case 3: // FresnelParameters - serializationObject[targetPropertyName] = sourceProperty.serialize(); - break; - case 4: // Vector2 - serializationObject[targetPropertyName] = sourceProperty.asArray(); - break; - case 5: // Vector3 - serializationObject[targetPropertyName] = sourceProperty.asArray(); - break; - case 6: // Mesh reference - serializationObject[targetPropertyName] = sourceProperty.id; - break; - case 7: // Color Curves - serializationObject[targetPropertyName] = sourceProperty.serialize(); - break; - case 8: // Color 4 - serializationObject[targetPropertyName] = sourceProperty.asArray(); - break; - case 9: // Image Processing - serializationObject[targetPropertyName] = sourceProperty.serialize(); - break; - case 10: // Quaternion - serializationObject[targetPropertyName] = sourceProperty.asArray(); - break; - case 11: // Camera reference - serializationObject[targetPropertyName] = sourceProperty.id; - break; - case 12: // Matrix - serializationObject[targetPropertyName] = sourceProperty.asArray(); - break; - } - } - } - return serializationObject; - } - /** - * 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 - * @param source the source json data - * @param destination the destination object - * @param scene the scene where the object is - * @param rootUrl root url to use to load assets - */ - static ParseProperties(source, destination, scene, rootUrl) { - if (!rootUrl) { - rootUrl = ""; - } - const classStore = getMergedStore(destination); - // Properties - for (const property in classStore) { - const propertyDescriptor = classStore[property]; - const sourceProperty = source[propertyDescriptor.sourceName || property]; - const propertyType = propertyDescriptor.type; - if (sourceProperty !== undefined && sourceProperty !== null && (property !== "uniqueId" || decorators_SerializationHelper.AllowLoadingUniqueId)) { - const dest = destination; - switch (propertyType) { - case 0: // Value - dest[property] = sourceProperty; - break; - case 1: // Texture - if (scene) { - dest[property] = decorators_SerializationHelper._TextureParser(sourceProperty, scene, rootUrl); - } - break; - case 2: // Color3 - dest[property] = math_color_Color3.FromArray(sourceProperty); - break; - case 3: // FresnelParameters - dest[property] = decorators_SerializationHelper._FresnelParametersParser(sourceProperty); - break; - case 4: // Vector2 - dest[property] = math_vector_Vector2.FromArray(sourceProperty); - break; - case 5: // Vector3 - dest[property] = math_vector_Vector3.FromArray(sourceProperty); - break; - case 6: // Mesh reference - if (scene) { - dest[property] = scene.getLastMeshById(sourceProperty); - } - break; - case 7: // Color Curves - dest[property] = decorators_SerializationHelper._ColorCurvesParser(sourceProperty); - break; - case 8: // Color 4 - dest[property] = math_color_Color4.FromArray(sourceProperty); - break; - case 9: // Image Processing - dest[property] = decorators_SerializationHelper._ImageProcessingConfigurationParser(sourceProperty); - break; - case 10: // Quaternion - dest[property] = math_vector_Quaternion.FromArray(sourceProperty); - break; - case 11: // Camera reference - if (scene) { - dest[property] = scene.getCameraById(sourceProperty); - } - break; - case 12: // Matrix - dest[property] = math_vector_Matrix.FromArray(sourceProperty); - break; - } - } - } - } - /** - * Creates a new entity from a serialization data object - * @param creationFunction defines a function used to instanciated the new entity - * @param source defines the source serialization data - * @param scene defines the hosting scene - * @param rootUrl defines the root url for resources - * @returns a new entity - */ - static Parse(creationFunction, source, scene, rootUrl = null) { - const destination = creationFunction(); - // Tags - if (Tags) { - Tags.AddTagsTo(destination, source.tags); - } - decorators_SerializationHelper.ParseProperties(source, destination, scene, rootUrl); - return destination; - } - /** - * Clones an object - * @param creationFunction defines the function used to instanciate the new object - * @param source defines the source object - * @returns the cloned object - */ - static Clone(creationFunction, source, options = {}) { - return _copySource(creationFunction, source, false, options); - } - /** - * Instanciates a new object based on a source one (some data will be shared between both object) - * @param creationFunction defines the function used to instanciate the new object - * @param source defines the source object - * @returns the new object - */ - static Instanciate(creationFunction, source) { - return _copySource(creationFunction, source, true); - } -} -/** - * Gets or sets a boolean to indicate if the UniqueId property should be serialized - */ -decorators_SerializationHelper.AllowLoadingUniqueId = false; -/** - * @internal - */ -decorators_SerializationHelper._ImageProcessingConfigurationParser = (sourceProperty) => { - throw _WarnImport("ImageProcessingConfiguration"); -}; -/** - * @internal - */ -decorators_SerializationHelper._FresnelParametersParser = (sourceProperty) => { - throw _WarnImport("FresnelParameters"); -}; -/** - * @internal - */ -decorators_SerializationHelper._ColorCurvesParser = (sourceProperty) => { - throw _WarnImport("ColorCurves"); -}; -/** - * @internal - */ -decorators_SerializationHelper._TextureParser = (sourceProperty, scene, rootUrl) => { - throw _WarnImport("Texture"); -}; -/** - * Decorator used to redirect a function to a native implementation if available. - * @internal - */ -function nativeOverride(target, propertyKey, descriptor, predicate) { - // Cache the original JS function for later. - const jsFunc = descriptor.value; - // 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. - descriptor.value = (...params) => { - // Assume the resolved function will be the original JS function, then we will check for the Babylon Native context. - let func = jsFunc; - // 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. - if (typeof _native !== "undefined" && _native[propertyKey]) { - const nativeFunc = _native[propertyKey]; - // 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. - if (predicate) { - // The resolved function will execute the predicate and then either execute the native function or the JS function. - func = (...params) => (predicate(...params) ? nativeFunc(...params) : jsFunc(...params)); - } - else { - // The resolved function will directly execute the native function. - func = nativeFunc; - } - } - // Override the JS function again with the final resolved target function. - target[propertyKey] = func; - // 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. - // Future invocations of the function will just directly invoke the final overridden function, not any of the decorator setup logic above. - return func(...params); - }; -} -/** - * 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. - * @param predicate - * @example @nativeOverride.filter((...[arg1]: Parameters<typeof someClass.someMethod>) => arg1.length > 20) - * public someMethod(arg1: string, arg2: number): string { - * @internal - */ -nativeOverride.filter = function (predicate) { - return (target, propertyKey, descriptor) => nativeOverride(target, propertyKey, descriptor, predicate); -}; -//# sourceMappingURL=decorators.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/animationKey.js -/** - * Enum for the animation key frame interpolation type - */ -var AnimationKeyInterpolation; -(function (AnimationKeyInterpolation) { - /** - * Use tangents to interpolate between start and end values. - */ - AnimationKeyInterpolation[AnimationKeyInterpolation["NONE"] = 0] = "NONE"; - /** - * Do not interpolate between keys and use the start key value only. Tangents are ignored - */ - AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP"; -})(AnimationKeyInterpolation || (AnimationKeyInterpolation = {})); -//# sourceMappingURL=animationKey.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/animationRange.js -/** - * Represents the range of an animation - */ -class AnimationRange { - /** - * Initializes the range of an animation - * @param name The name of the animation range - * @param from The starting frame of the animation - * @param to The ending frame of the animation - */ - constructor( - /**The name of the animation range**/ - name, - /**The starting frame of the animation */ - from, - /**The ending frame of the animation*/ - to) { - this.name = name; - this.from = from; - this.to = to; - } - /** - * Makes a copy of the animation range - * @returns A copy of the animation range - */ - clone() { - return new AnimationRange(this.name, this.from, this.to); - } -} -//# sourceMappingURL=animationRange.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/tslib.es6.js - -/****************************************************************************** -Copyright (c) Microsoft Corporation. -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - } - return __assign.apply(this, arguments); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - 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; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - 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; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -var __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -}); - -function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} - -function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} - -function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -} - -/** @deprecated */ -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -/** @deprecated */ -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -} - -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - 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); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - 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; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - 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); - 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); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - 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"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - 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"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -} - -function __classPrivateFieldIn(state, receiver) { - if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} - -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/node.js - - - - - - -/** @internal */ -class _InternalNodeDataInfo { - constructor() { - this._doNotSerialize = false; - this._isDisposed = false; - this._sceneRootNodesIndex = -1; - this._isEnabled = true; - this._isParentEnabled = true; - this._isReady = true; - this._onEnabledStateChangedObservable = new observable_Observable(); - this._onClonedObservable = new observable_Observable(); - } -} -/** - * Node is the basic class for all scene objects (Mesh, Light, Camera.) - */ -class node_Node { - /** - * Add a new node constructor - * @param type defines the type name of the node to construct - * @param constructorFunc defines the constructor function - */ - static AddNodeConstructor(type, constructorFunc) { - this._NodeConstructors[type] = constructorFunc; - } - /** - * Returns a node constructor based on type name - * @param type defines the type name - * @param name defines the new node name - * @param scene defines the hosting scene - * @param options defines optional options to transmit to constructors - * @returns the new constructor or null - */ - static Construct(type, name, scene, options) { - const constructorFunc = this._NodeConstructors[type]; - if (!constructorFunc) { - return null; - } - return constructorFunc(name, scene, options); - } - /** - * Gets or sets the accessibility tag to describe the node for accessibility purpose. - */ - set accessibilityTag(value) { - this._accessibilityTag = value; - this.onAccessibilityTagChangedObservable.notifyObservers(value); - } - get accessibilityTag() { - return this._accessibilityTag; - } - /** - * Gets or sets a boolean used to define if the node must be serialized - */ - get doNotSerialize() { - if (this._nodeDataStorage._doNotSerialize) { - return true; - } - if (this._parentNode) { - return this._parentNode.doNotSerialize; - } - return false; - } - set doNotSerialize(value) { - this._nodeDataStorage._doNotSerialize = value; - } - /** - * Gets a boolean indicating if the node has been disposed - * @returns true if the node was disposed - */ - isDisposed() { - return this._nodeDataStorage._isDisposed; - } - /** - * Gets or sets the parent of the node (without keeping the current position in the scene) - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent - */ - set parent(parent) { - if (this._parentNode === parent) { - return; - } - const previousParentNode = this._parentNode; - // Remove self from list of children of parent - if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) { - const index = this._parentNode._children.indexOf(this); - if (index !== -1) { - this._parentNode._children.splice(index, 1); - } - if (!parent && !this._nodeDataStorage._isDisposed) { - this._addToSceneRootNodes(); - } - } - // Store new parent - this._parentNode = parent; - // Add as child to new parent - if (this._parentNode) { - if (this._parentNode._children === undefined || this._parentNode._children === null) { - this._parentNode._children = new Array(); - } - this._parentNode._children.push(this); - if (!previousParentNode) { - this._removeFromSceneRootNodes(); - } - } - // Enabled state - this._syncParentEnabledState(); - } - get parent() { - return this._parentNode; - } - /** - * @internal - */ - _serializeAsParent(serializationObject) { - serializationObject.parentId = this.uniqueId; - } - /** @internal */ - _addToSceneRootNodes() { - if (this._nodeDataStorage._sceneRootNodesIndex === -1) { - this._nodeDataStorage._sceneRootNodesIndex = this._scene.rootNodes.length; - this._scene.rootNodes.push(this); - } - } - /** @internal */ - _removeFromSceneRootNodes() { - if (this._nodeDataStorage._sceneRootNodesIndex !== -1) { - const rootNodes = this._scene.rootNodes; - const lastIdx = rootNodes.length - 1; - rootNodes[this._nodeDataStorage._sceneRootNodesIndex] = rootNodes[lastIdx]; - rootNodes[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex = this._nodeDataStorage._sceneRootNodesIndex; - this._scene.rootNodes.pop(); - this._nodeDataStorage._sceneRootNodesIndex = -1; - } - } - /** - * Gets or sets the animation properties override - */ - get animationPropertiesOverride() { - if (!this._animationPropertiesOverride) { - return this._scene.animationPropertiesOverride; - } - return this._animationPropertiesOverride; - } - set animationPropertiesOverride(value) { - this._animationPropertiesOverride = value; - } - /** - * Gets a string identifying the name of the class - * @returns "Node" string - */ - getClassName() { - return "Node"; - } - /** - * Sets a callback that will be raised when the node will be disposed - */ - set onDispose(callback) { - if (this._onDisposeObserver) { - this.onDisposeObservable.remove(this._onDisposeObserver); - } - this._onDisposeObserver = this.onDisposeObservable.add(callback); - } - /** - * An event triggered when the enabled state of the node changes - */ - get onEnabledStateChangedObservable() { - return this._nodeDataStorage._onEnabledStateChangedObservable; - } - /** - * An event triggered when the node is cloned - */ - get onClonedObservable() { - return this._nodeDataStorage._onClonedObservable; - } - /** - * Creates a new Node - * @param name the name and id to be given to this node - * @param scene the scene this node will be added to - */ - constructor(name, scene = null) { - this._isDirty = false; - this._nodeDataStorage = new _InternalNodeDataInfo(); - /** - * Gets or sets a string used to store user defined state for the node - */ - this.state = ""; - /** - * Gets or sets an object used to store user defined information for the node - */ - this.metadata = null; - /** - * For internal use only. Please do not use. - */ - this.reservedDataStore = null; - this._accessibilityTag = null; - this.onAccessibilityTagChangedObservable = new observable_Observable(); - /** @internal */ - this._parentContainer = null; - /** - * Gets a list of Animations associated with the node - */ - this.animations = new Array(); - this._ranges = {}; - /** - * Callback raised when the node is ready to be used - */ - this.onReady = null; - /** @internal */ - this._currentRenderId = -1; - this._parentUpdateId = -1; - /** @internal */ - this._childUpdateId = -1; - /** @internal */ - this._waitingParentId = null; - /** @internal */ - this._waitingParentInstanceIndex = null; - /** @internal */ - this._waitingParsedUniqueId = null; - /** @internal */ - this._cache = {}; - this._parentNode = null; - /** @internal */ - this._children = null; - /** @internal */ - this._worldMatrix = math_vector_Matrix.Identity(); - /** @internal */ - this._worldMatrixDeterminant = 0; - /** @internal */ - this._worldMatrixDeterminantIsDirty = true; - this._animationPropertiesOverride = null; - /** @internal */ - this._isNode = true; - /** - * An event triggered when the mesh is disposed - */ - this.onDisposeObservable = new observable_Observable(); - this._onDisposeObserver = null; - // Behaviors - this._behaviors = new Array(); - this.name = name; - this.id = name; - this._scene = (scene || engineStore_EngineStore.LastCreatedScene); - this.uniqueId = this._scene.getUniqueId(); - this._initCache(); - } - /** - * Gets the scene of the node - * @returns a scene - */ - getScene() { - return this._scene; - } - /** - * Gets the engine of the node - * @returns a Engine - */ - getEngine() { - return this._scene.getEngine(); - } - /** - * Attach a behavior to the node - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors - * @param behavior defines the behavior to attach - * @param attachImmediately defines that the behavior must be attached even if the scene is still loading - * @returns the current Node - */ - addBehavior(behavior, attachImmediately = false) { - const index = this._behaviors.indexOf(behavior); - if (index !== -1) { - return this; - } - behavior.init(); - if (this._scene.isLoading && !attachImmediately) { - // We defer the attach when the scene will be loaded - this._scene.onDataLoadedObservable.addOnce(() => { - behavior.attach(this); - }); - } - else { - behavior.attach(this); - } - this._behaviors.push(behavior); - return this; - } - /** - * Remove an attached behavior - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors - * @param behavior defines the behavior to attach - * @returns the current Node - */ - removeBehavior(behavior) { - const index = this._behaviors.indexOf(behavior); - if (index === -1) { - return this; - } - this._behaviors[index].detach(); - this._behaviors.splice(index, 1); - return this; - } - /** - * Gets the list of attached behaviors - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors - */ - get behaviors() { - return this._behaviors; - } - /** - * Gets an attached behavior by name - * @param name defines the name of the behavior to look for - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors - * @returns null if behavior was not found else the requested behavior - */ - getBehaviorByName(name) { - for (const behavior of this._behaviors) { - if (behavior.name === name) { - return behavior; - } - } - return null; - } - /** - * Returns the latest update of the World matrix - * @returns a Matrix - */ - getWorldMatrix() { - if (this._currentRenderId !== this._scene.getRenderId()) { - this.computeWorldMatrix(); - } - return this._worldMatrix; - } - /** @internal */ - _getWorldMatrixDeterminant() { - if (this._worldMatrixDeterminantIsDirty) { - this._worldMatrixDeterminantIsDirty = false; - this._worldMatrixDeterminant = this._worldMatrix.determinant(); - } - return this._worldMatrixDeterminant; - } - /** - * Returns directly the latest state of the mesh World matrix. - * A Matrix is returned. - */ - get worldMatrixFromCache() { - return this._worldMatrix; - } - // override it in derived class if you add new variables to the cache - // and call the parent class method - /** @internal */ - _initCache() { - this._cache = {}; - this._cache.parent = undefined; - } - /** - * @internal - */ - updateCache(force) { - if (!force && this.isSynchronized()) { - return; - } - this._cache.parent = this.parent; - this._updateCache(); - } - /** - * @internal - */ - _getActionManagerForTrigger(trigger, _initialCall = true) { - if (!this.parent) { - return null; - } - return this.parent._getActionManagerForTrigger(trigger, false); - } - // override it in derived class if you add new variables to the cache - // and call the parent class method if !ignoreParentClass - /** - * @internal - */ - _updateCache(_ignoreParentClass) { } - // override it in derived class if you add new variables to the cache - /** @internal */ - _isSynchronized() { - return true; - } - /** @internal */ - _markSyncedWithParent() { - if (this._parentNode) { - this._parentUpdateId = this._parentNode._childUpdateId; - } - } - /** @internal */ - isSynchronizedWithParent() { - if (!this._parentNode) { - return true; - } - if (this._parentNode._isDirty || this._parentUpdateId !== this._parentNode._childUpdateId) { - return false; - } - return this._parentNode.isSynchronized(); - } - /** @internal */ - isSynchronized() { - if (this._cache.parent !== this._parentNode) { - this._cache.parent = this._parentNode; - return false; - } - if (this._parentNode && !this.isSynchronizedWithParent()) { - return false; - } - return this._isSynchronized(); - } - /** - * Is this node ready to be used/rendered - * @param _completeCheck defines if a complete check (including materials and lights) has to be done (false by default) - * @returns true if the node is ready - */ - isReady(_completeCheck = false) { - return this._nodeDataStorage._isReady; - } - /** - * Flag the node as dirty (Forcing it to update everything) - * @param _property helps children apply precise "dirtyfication" - * @returns this node - */ - markAsDirty(_property) { - this._currentRenderId = Number.MAX_VALUE; - this._isDirty = true; - return this; - } - /** - * Is this node enabled? - * 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 - * @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 - * @returns whether this node (and its parent) is enabled - */ - isEnabled(checkAncestors = true) { - if (checkAncestors === false) { - return this._nodeDataStorage._isEnabled; - } - if (!this._nodeDataStorage._isEnabled) { - return false; - } - return this._nodeDataStorage._isParentEnabled; - } - /** @internal */ - _syncParentEnabledState() { - this._nodeDataStorage._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true; - if (this._children) { - this._children.forEach((c) => { - c._syncParentEnabledState(); // Force children to update accordingly - }); - } - } - /** - * Set the enabled state of this node - * @param value defines the new enabled state - */ - setEnabled(value) { - if (this._nodeDataStorage._isEnabled === value) { - return; - } - this._nodeDataStorage._isEnabled = value; - this._syncParentEnabledState(); - this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(value); - } - /** - * Is this node a descendant of the given node? - * The function will iterate up the hierarchy until the ancestor was found or no more parents defined - * @param ancestor defines the parent node to inspect - * @returns a boolean indicating if this node is a descendant of the given node - */ - isDescendantOf(ancestor) { - if (this.parent) { - if (this.parent === ancestor) { - return true; - } - return this.parent.isDescendantOf(ancestor); - } - return false; - } - /** - * @internal - */ - _getDescendants(results, directDescendantsOnly = false, predicate) { - if (!this._children) { - return; - } - for (let index = 0; index < this._children.length; index++) { - const item = this._children[index]; - if (!predicate || predicate(item)) { - results.push(item); - } - if (!directDescendantsOnly) { - item._getDescendants(results, false, predicate); - } - } - } - /** - * Will return all nodes that have this node as ascendant - * @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 - * @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 - * @returns all children nodes of all types - */ - getDescendants(directDescendantsOnly, predicate) { - const results = new Array(); - this._getDescendants(results, directDescendantsOnly, predicate); - return results; - } - /** - * Get all child-meshes of this node - * @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) - * @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 - * @returns an array of AbstractMesh - */ - getChildMeshes(directDescendantsOnly, predicate) { - const results = []; - this._getDescendants(results, directDescendantsOnly, (node) => { - return (!predicate || predicate(node)) && node.cullingStrategy !== undefined; - }); - return results; - } - /** - * Get all direct children of this node - * @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 - * @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) - * @returns an array of Node - */ - getChildren(predicate, directDescendantsOnly = true) { - return this.getDescendants(directDescendantsOnly, predicate); - } - /** - * @internal - */ - _setReady(state) { - if (state === this._nodeDataStorage._isReady) { - return; - } - if (!state) { - this._nodeDataStorage._isReady = false; - return; - } - if (this.onReady) { - this.onReady(this); - } - this._nodeDataStorage._isReady = true; - } - /** - * Get an animation by name - * @param name defines the name of the animation to look for - * @returns null if not found else the requested animation - */ - getAnimationByName(name) { - for (let i = 0; i < this.animations.length; i++) { - const animation = this.animations[i]; - if (animation.name === name) { - return animation; - } - } - return null; - } - /** - * Creates an animation range for this node - * @param name defines the name of the range - * @param from defines the starting key - * @param to defines the end key - */ - createAnimationRange(name, from, to) { - // check name not already in use - if (!this._ranges[name]) { - this._ranges[name] = node_Node._AnimationRangeFactory(name, from, to); - for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) { - if (this.animations[i]) { - this.animations[i].createRange(name, from, to); - } - } - } - } - /** - * Delete a specific animation range - * @param name defines the name of the range to delete - * @param deleteFrames defines if animation frames from the range must be deleted as well - */ - deleteAnimationRange(name, deleteFrames = true) { - for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) { - if (this.animations[i]) { - this.animations[i].deleteRange(name, deleteFrames); - } - } - this._ranges[name] = null; // said much faster than 'delete this._range[name]' - } - /** - * Get an animation range by name - * @param name defines the name of the animation range to look for - * @returns null if not found else the requested animation range - */ - getAnimationRange(name) { - return this._ranges[name] || null; - } - /** - * Clone the current node - * @param name Name of the new clone - * @param newParent New parent for the clone - * @param doNotCloneChildren Do not clone children hierarchy - * @returns the new transform node - */ - clone(name, newParent, doNotCloneChildren) { - const result = decorators_SerializationHelper.Clone(() => new node_Node(name, this.getScene()), this); - if (newParent) { - result.parent = newParent; - } - if (!doNotCloneChildren) { - // Children - const directDescendants = this.getDescendants(true); - for (let index = 0; index < directDescendants.length; index++) { - const child = directDescendants[index]; - child.clone(name + "." + child.name, result); - } - } - return result; - } - /** - * Gets the list of all animation ranges defined on this node - * @returns an array - */ - getAnimationRanges() { - const animationRanges = []; - let name; - for (name in this._ranges) { - animationRanges.push(this._ranges[name]); - } - return animationRanges; - } - /** - * Will start the animation sequence - * @param name defines the range frames for animation sequence - * @param loop defines if the animation should loop (false by default) - * @param speedRatio defines the speed factor in which to run the animation (1 by default) - * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default) - * @returns the object created for this animation. If range does not exist, it will return null - */ - beginAnimation(name, loop, speedRatio, onAnimationEnd) { - const range = this.getAnimationRange(name); - if (!range) { - return null; - } - return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd); - } - /** - * Serialize animation ranges into a JSON compatible object - * @returns serialization object - */ - serializeAnimationRanges() { - const serializationRanges = []; - for (const name in this._ranges) { - const localRange = this._ranges[name]; - if (!localRange) { - continue; - } - const range = {}; - range.name = name; - range.from = localRange.from; - range.to = localRange.to; - serializationRanges.push(range); - } - return serializationRanges; - } - /** - * Computes the world matrix of the node - * @param _force defines if the cache version should be invalidated forcing the world matrix to be created from scratch - * @returns the world matrix - */ - computeWorldMatrix(_force) { - if (!this._worldMatrix) { - this._worldMatrix = math_vector_Matrix.Identity(); - } - return this._worldMatrix; - } - /** - * Releases resources associated with this node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) - */ - dispose(doNotRecurse, disposeMaterialAndTextures = false) { - this._nodeDataStorage._isDisposed = true; - if (!doNotRecurse) { - const nodes = this.getDescendants(true); - for (const node of nodes) { - node.dispose(doNotRecurse, disposeMaterialAndTextures); - } - } - if (!this.parent) { - this._removeFromSceneRootNodes(); - } - else { - this.parent = null; - } - // Callback - this.onDisposeObservable.notifyObservers(this); - this.onDisposeObservable.clear(); - this.onEnabledStateChangedObservable.clear(); - this.onClonedObservable.clear(); - // Behaviors - for (const behavior of this._behaviors) { - behavior.detach(); - } - this._behaviors.length = 0; - this.metadata = null; - } - /** - * Parse animation range data from a serialization object and store them into a given node - * @param node defines where to store the animation ranges - * @param parsedNode defines the serialization object to read data from - * @param _scene defines the hosting scene - */ - static ParseAnimationRanges(node, parsedNode, _scene) { - if (parsedNode.ranges) { - for (let index = 0; index < parsedNode.ranges.length; index++) { - const data = parsedNode.ranges[index]; - node.createAnimationRange(data.name, data.from, data.to); - } - } - } - /** - * Return the minimum and maximum world vectors of the entire hierarchy under current node - * @param includeDescendants Include bounding info from descendants as well (true by default) - * @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 - * @returns the new bounding vectors - */ - getHierarchyBoundingVectors(includeDescendants = true, predicate = null) { - // Ensures that all world matrix will be recomputed. - this.getScene().incrementRenderId(); - this.computeWorldMatrix(true); - let min; - let max; - const thisAbstractMesh = this; - if (thisAbstractMesh.getBoundingInfo && thisAbstractMesh.subMeshes) { - // If this is an abstract mesh get its bounding info - const boundingInfo = thisAbstractMesh.getBoundingInfo(); - min = boundingInfo.boundingBox.minimumWorld.clone(); - max = boundingInfo.boundingBox.maximumWorld.clone(); - } - else { - min = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - max = new math_vector_Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); - } - if (includeDescendants) { - const descendants = this.getDescendants(false); - for (const descendant of descendants) { - const childMesh = descendant; - childMesh.computeWorldMatrix(true); - // Filters meshes based on custom predicate function. - if (predicate && !predicate(childMesh)) { - continue; - } - //make sure we have the needed params to get mix and max - if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) { - continue; - } - const childBoundingInfo = childMesh.getBoundingInfo(); - const boundingBox = childBoundingInfo.boundingBox; - const minBox = boundingBox.minimumWorld; - const maxBox = boundingBox.maximumWorld; - math_vector_Vector3.CheckExtends(minBox, min, max); - math_vector_Vector3.CheckExtends(maxBox, min, max); - } - } - return { - min: min, - max: max, - }; - } -} -/** - * @internal - */ -node_Node._AnimationRangeFactory = (_name, _from, _to) => { - throw _WarnImport("AnimationRange"); -}; -node_Node._NodeConstructors = {}; -__decorate([ - serialize() -], node_Node.prototype, "name", void 0); -__decorate([ - serialize() -], node_Node.prototype, "id", void 0); -__decorate([ - serialize() -], node_Node.prototype, "uniqueId", void 0); -__decorate([ - serialize() -], node_Node.prototype, "state", void 0); -__decorate([ - serialize() -], node_Node.prototype, "metadata", void 0); -//# sourceMappingURL=node.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.size.js -/** - * Size containing width and height - */ -class Size { - /** - * Creates a Size object from the given width and height (floats). - * @param width width of the new size - * @param height height of the new size - */ - constructor(width, height) { - this.width = width; - this.height = height; - } - /** - * Returns a string with the Size width and height - * @returns a string with the Size width and height - */ - toString() { - return `{W: ${this.width}, H: ${this.height}}`; - } - /** - * "Size" - * @returns the string "Size" - */ - getClassName() { - return "Size"; - } - /** - * Returns the Size hash code. - * @returns a hash code for a unique width and height - */ - getHashCode() { - let hash = this.width | 0; - hash = (hash * 397) ^ (this.height | 0); - return hash; - } - /** - * Updates the current size from the given one. - * @param src the given size - */ - copyFrom(src) { - this.width = src.width; - this.height = src.height; - } - /** - * Updates in place the current Size from the given floats. - * @param width width of the new size - * @param height height of the new size - * @returns the updated Size. - */ - copyFromFloats(width, height) { - this.width = width; - this.height = height; - return this; - } - /** - * Updates in place the current Size from the given floats. - * @param width width to set - * @param height height to set - * @returns the updated Size. - */ - set(width, height) { - return this.copyFromFloats(width, height); - } - /** - * Multiplies the width and height by numbers - * @param w factor to multiple the width by - * @param h factor to multiple the height by - * @returns a new Size set with the multiplication result of the current Size and the given floats. - */ - multiplyByFloats(w, h) { - return new Size(this.width * w, this.height * h); - } - /** - * Clones the size - * @returns a new Size copied from the given one. - */ - clone() { - return new Size(this.width, this.height); - } - /** - * True if the current Size and the given one width and height are strictly equal. - * @param other the other size to compare against - * @returns True if the current Size and the given one width and height are strictly equal. - */ - equals(other) { - if (!other) { - return false; - } - return this.width === other.width && this.height === other.height; - } - /** - * The surface of the Size : width * height (float). - */ - get surface() { - return this.width * this.height; - } - /** - * Create a new size of zero - * @returns a new Size set to (0.0, 0.0) - */ - static Zero() { - return new Size(0.0, 0.0); - } - /** - * Sums the width and height of two sizes - * @param otherSize size to add to this size - * @returns a new Size set as the addition result of the current Size and the given one. - */ - add(otherSize) { - const r = new Size(this.width + otherSize.width, this.height + otherSize.height); - return r; - } - /** - * Subtracts the width and height of two - * @param otherSize size to subtract to this size - * @returns a new Size set as the subtraction result of the given one from the current Size. - */ - subtract(otherSize) { - const r = new Size(this.width - otherSize.width, this.height - otherSize.height); - return r; - } - /** - * Creates a new Size set at the linear interpolation "amount" between "start" and "end" - * @param start starting size to lerp between - * @param end end size to lerp between - * @param amount amount to lerp between the start and end values - * @returns a new Size set at the linear interpolation "amount" between "start" and "end" - */ - static Lerp(start, end, amount) { - const w = start.width + (end.width - start.width) * amount; - const h = start.height + (end.height - start.height) * amount; - return new Size(w, h); - } -} -//# sourceMappingURL=math.size.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/webRequest.js -/** @internal */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function createXMLHttpRequest() { - // If running in Babylon Native, then defer to the native XMLHttpRequest, which has the same public contract - if (typeof _native !== "undefined" && _native.XMLHttpRequest) { - return new _native.XMLHttpRequest(); - } - else { - return new XMLHttpRequest(); - } -} -/** - * Extended version of XMLHttpRequest with support for customizations (headers, ...) - */ -class webRequest_WebRequest { - constructor() { - this._xhr = createXMLHttpRequest(); - this._requestURL = ""; - } - _injectCustomRequestHeaders() { - if (this._shouldSkipRequestModifications(this._requestURL)) { - return; - } - for (const key in webRequest_WebRequest.CustomRequestHeaders) { - const val = webRequest_WebRequest.CustomRequestHeaders[key]; - if (val) { - this._xhr.setRequestHeader(key, val); - } - } - } - _shouldSkipRequestModifications(url) { - return webRequest_WebRequest.SkipRequestModificationForBabylonCDN && (url.includes("preview.babylonjs.com") || url.includes("cdn.babylonjs.com")); - } - /** - * Gets or sets a function to be called when loading progress changes - */ - get onprogress() { - return this._xhr.onprogress; - } - set onprogress(value) { - this._xhr.onprogress = value; - } - /** - * Returns client's state - */ - get readyState() { - return this._xhr.readyState; - } - /** - * Returns client's status - */ - get status() { - return this._xhr.status; - } - /** - * Returns client's status as a text - */ - get statusText() { - return this._xhr.statusText; - } - /** - * Returns client's response - */ - get response() { - return this._xhr.response; - } - /** - * Returns client's response url - */ - get responseURL() { - return this._xhr.responseURL; - } - /** - * Returns client's response as text - */ - get responseText() { - return this._xhr.responseText; - } - /** - * Gets or sets the expected response type - */ - get responseType() { - return this._xhr.responseType; - } - set responseType(value) { - this._xhr.responseType = value; - } - /** - * Gets or sets the timeout value in milliseconds - */ - get timeout() { - return this._xhr.timeout; - } - set timeout(value) { - this._xhr.timeout = value; - } - addEventListener(type, listener, options) { - this._xhr.addEventListener(type, listener, options); - } - removeEventListener(type, listener, options) { - this._xhr.removeEventListener(type, listener, options); - } - /** - * Cancels any network activity - */ - abort() { - this._xhr.abort(); - } - /** - * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD - * @param body defines an optional request body - */ - send(body) { - if (webRequest_WebRequest.CustomRequestHeaders) { - this._injectCustomRequestHeaders(); - } - this._xhr.send(body); - } - /** - * Sets the request method, request URL - * @param method defines the method to use (GET, POST, etc..) - * @param url defines the url to connect with - */ - open(method, url) { - for (const update of webRequest_WebRequest.CustomRequestModifiers) { - if (this._shouldSkipRequestModifications(url)) { - return; - } - update(this._xhr, url); - } - // Clean url - url = url.replace("file:http:", "http:"); - url = url.replace("file:https:", "https:"); - this._requestURL = url; - return this._xhr.open(method, url, true); - } - /** - * Sets the value of a request header. - * @param name The name of the header whose value is to be set - * @param value The value to set as the body of the header - */ - setRequestHeader(name, value) { - this._xhr.setRequestHeader(name, value); - } - /** - * Get the string containing the text of a particular header's value. - * @param name The name of the header - * @returns The string containing the text of the given header name - */ - getResponseHeader(name) { - return this._xhr.getResponseHeader(name); - } -} -/** - * Custom HTTP Request Headers to be sent with XMLHttpRequests - * i.e. when loading files, where the server/service expects an Authorization header - */ -webRequest_WebRequest.CustomRequestHeaders = {}; -/** - * Add callback functions in this array to update all the requests before they get sent to the network - */ -webRequest_WebRequest.CustomRequestModifiers = new Array(); -webRequest_WebRequest.SkipRequestModificationForBabylonCDN = true; -//# sourceMappingURL=webRequest.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/animation.js - - - - - - - - - - - -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _IAnimationState { -} -/** - * Class used to store any kind of animation - */ -class animation_Animation { - /** - * @internal Internal use - */ - static _PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) { - let dataType = undefined; - if (!isNaN(parseFloat(from)) && isFinite(from)) { - dataType = animation_Animation.ANIMATIONTYPE_FLOAT; - } - else if (from instanceof math_vector_Quaternion) { - dataType = animation_Animation.ANIMATIONTYPE_QUATERNION; - } - else if (from instanceof math_vector_Vector3) { - dataType = animation_Animation.ANIMATIONTYPE_VECTOR3; - } - else if (from instanceof math_vector_Vector2) { - dataType = animation_Animation.ANIMATIONTYPE_VECTOR2; - } - else if (from instanceof math_color_Color3) { - dataType = animation_Animation.ANIMATIONTYPE_COLOR3; - } - else if (from instanceof math_color_Color4) { - dataType = animation_Animation.ANIMATIONTYPE_COLOR4; - } - else if (from instanceof Size) { - dataType = animation_Animation.ANIMATIONTYPE_SIZE; - } - if (dataType == undefined) { - return null; - } - const animation = new animation_Animation(name, targetProperty, framePerSecond, dataType, loopMode); - const keys = [ - { frame: 0, value: from }, - { frame: totalFrame, value: to }, - ]; - animation.setKeys(keys); - if (easingFunction !== undefined) { - animation.setEasingFunction(easingFunction); - } - return animation; - } - /** - * Sets up an animation - * @param property The property to animate - * @param animationType The animation type to apply - * @param framePerSecond The frames per second of the animation - * @param easingFunction The easing function used in the animation - * @returns The created animation - */ - static CreateAnimation(property, animationType, framePerSecond, easingFunction) { - const animation = new animation_Animation(property + "Animation", property, framePerSecond, animationType, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - animation.setEasingFunction(easingFunction); - return animation; - } - /** - * Create and start an animation on a node - * @param name defines the name of the global animation that will be run on all nodes - * @param target defines the target where the animation will take place - * @param targetProperty defines property to animate - * @param framePerSecond defines the number of frame per second yo use - * @param totalFrame defines the number of frames in total - * @param from defines the initial value - * @param to defines the final value - * @param loopMode defines which loop mode you want to use (off by default) - * @param easingFunction defines the easing function to use (linear by default) - * @param onAnimationEnd defines the callback to call when animation end - * @param scene defines the hosting scene - * @returns the animatable created for this animation - */ - static CreateAndStartAnimation(name, target, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd, scene) { - const animation = animation_Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); - if (!animation) { - return null; - } - if (target.getScene) { - scene = target.getScene(); - } - if (!scene) { - return null; - } - return scene.beginDirectAnimation(target, [animation], 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd); - } - /** - * Create and start an animation on a node and its descendants - * @param name defines the name of the global animation that will be run on all nodes - * @param node defines the root node where the animation will take place - * @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 - * @param targetProperty defines property to animate - * @param framePerSecond defines the number of frame per second to use - * @param totalFrame defines the number of frames in total - * @param from defines the initial value - * @param to defines the final value - * @param loopMode defines which loop mode you want to use (off by default) - * @param easingFunction defines the easing function to use (linear by default) - * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node) - * @returns the list of animatables created for all nodes - * @example https://www.babylonjs-playground.com/#MH0VLI - */ - static CreateAndStartHierarchyAnimation(name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { - const animation = animation_Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); - if (!animation) { - return null; - } - const scene = node.getScene(); - return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd); - } - /** - * Creates a new animation, merges it with the existing animations and starts it - * @param name Name of the animation - * @param node Node which contains the scene that begins the animations - * @param targetProperty Specifies which property to animate - * @param framePerSecond The frames per second of the animation - * @param totalFrame The total number of frames - * @param from The frame at the beginning of the animation - * @param to The frame at the end of the animation - * @param loopMode Specifies the loop mode of the animation - * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations - * @param onAnimationEnd Callback to run once the animation is complete - * @returns Nullable animation - */ - static CreateMergeAndStartAnimation(name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { - const animation = animation_Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); - if (!animation) { - return null; - } - node.animations.push(animation); - return node.getScene().beginAnimation(node, 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd); - } - /** - * Convert the keyframes for all animations belonging to the group to be relative to a given reference frame. - * @param sourceAnimation defines the Animation containing keyframes to convert - * @param referenceFrame defines the frame that keyframes in the range will be relative to - * @param range defines the name of the AnimationRange belonging to the Animation to convert - * @param cloneOriginal defines whether or not to clone the animation and convert the clone or convert the original animation (default is false) - * @param clonedName defines the name of the resulting cloned Animation if cloneOriginal is true - * @returns a new Animation if cloneOriginal is true or the original Animation if cloneOriginal is false - */ - static MakeAnimationAdditive(sourceAnimation, referenceFrame = 0, range, cloneOriginal = false, clonedName) { - let animation = sourceAnimation; - if (cloneOriginal) { - animation = sourceAnimation.clone(); - animation.name = clonedName || animation.name; - } - if (!animation._keys.length) { - return animation; - } - referenceFrame = referenceFrame >= 0 ? referenceFrame : 0; - let startIndex = 0; - const firstKey = animation._keys[0]; - let endIndex = animation._keys.length - 1; - const lastKey = animation._keys[endIndex]; - const valueStore = { - referenceValue: firstKey.value, - referencePosition: math_vector_TmpVectors.Vector3[0], - referenceQuaternion: math_vector_TmpVectors.Quaternion[0], - referenceScaling: math_vector_TmpVectors.Vector3[1], - keyPosition: math_vector_TmpVectors.Vector3[2], - keyQuaternion: math_vector_TmpVectors.Quaternion[1], - keyScaling: math_vector_TmpVectors.Vector3[3], - }; - let referenceFound = false; - let from = firstKey.frame; - let to = lastKey.frame; - if (range) { - const rangeValue = animation.getRange(range); - if (rangeValue) { - from = rangeValue.from; - to = rangeValue.to; - } - } - let fromKeyFound = firstKey.frame === from; - let toKeyFound = lastKey.frame === to; - // There's only one key, so use it - if (animation._keys.length === 1) { - const value = animation._getKeyValue(animation._keys[0]); - valueStore.referenceValue = value.clone ? value.clone() : value; - referenceFound = true; - } - // Reference frame is before the first frame, so just use the first frame - else if (referenceFrame <= firstKey.frame) { - const value = animation._getKeyValue(firstKey.value); - valueStore.referenceValue = value.clone ? value.clone() : value; - referenceFound = true; - } - // Reference frame is after the last frame, so just use the last frame - else if (referenceFrame >= lastKey.frame) { - const value = animation._getKeyValue(lastKey.value); - valueStore.referenceValue = value.clone ? value.clone() : value; - referenceFound = true; - } - // Find key bookends, create them if they don't exist - let index = 0; - while (!referenceFound || !fromKeyFound || (!toKeyFound && index < animation._keys.length - 1)) { - const currentKey = animation._keys[index]; - const nextKey = animation._keys[index + 1]; - // If reference frame wasn't found yet, check if we can interpolate to it - if (!referenceFound && referenceFrame >= currentKey.frame && referenceFrame <= nextKey.frame) { - let value; - if (referenceFrame === currentKey.frame) { - value = animation._getKeyValue(currentKey.value); - } - else if (referenceFrame === nextKey.frame) { - value = animation._getKeyValue(nextKey.value); - } - else { - const animationState = { - key: index, - repeatCount: 0, - loopMode: this.ANIMATIONLOOPMODE_CONSTANT, - }; - value = animation._interpolate(referenceFrame, animationState); - } - valueStore.referenceValue = value.clone ? value.clone() : value; - referenceFound = true; - } - // If from key wasn't found yet, check if we can interpolate to it - if (!fromKeyFound && from >= currentKey.frame && from <= nextKey.frame) { - if (from === currentKey.frame) { - startIndex = index; - } - else if (from === nextKey.frame) { - startIndex = index + 1; - } - else { - const animationState = { - key: index, - repeatCount: 0, - loopMode: this.ANIMATIONLOOPMODE_CONSTANT, - }; - const value = animation._interpolate(from, animationState); - const key = { - frame: from, - value: value.clone ? value.clone() : value, - }; - animation._keys.splice(index + 1, 0, key); - startIndex = index + 1; - } - fromKeyFound = true; - } - // If to key wasn't found yet, check if we can interpolate to it - if (!toKeyFound && to >= currentKey.frame && to <= nextKey.frame) { - if (to === currentKey.frame) { - endIndex = index; - } - else if (to === nextKey.frame) { - endIndex = index + 1; - } - else { - const animationState = { - key: index, - repeatCount: 0, - loopMode: this.ANIMATIONLOOPMODE_CONSTANT, - }; - const value = animation._interpolate(to, animationState); - const key = { - frame: to, - value: value.clone ? value.clone() : value, - }; - animation._keys.splice(index + 1, 0, key); - endIndex = index + 1; - } - toKeyFound = true; - } - index++; - } - // Conjugate the quaternion - if (animation.dataType === animation_Animation.ANIMATIONTYPE_QUATERNION) { - valueStore.referenceValue.normalize().conjugateInPlace(); - } - // Decompose matrix and conjugate the quaternion - else if (animation.dataType === animation_Animation.ANIMATIONTYPE_MATRIX) { - valueStore.referenceValue.decompose(valueStore.referenceScaling, valueStore.referenceQuaternion, valueStore.referencePosition); - valueStore.referenceQuaternion.normalize().conjugateInPlace(); - } - // Subtract the reference value from all of the key values - for (index = startIndex; index <= endIndex; index++) { - const key = animation._keys[index]; - // If this key was duplicated to create a frame 0 key, skip it because its value has already been updated - if (index && animation.dataType !== animation_Animation.ANIMATIONTYPE_FLOAT && key.value === firstKey.value) { - continue; - } - switch (animation.dataType) { - case animation_Animation.ANIMATIONTYPE_MATRIX: - key.value.decompose(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition); - valueStore.keyPosition.subtractInPlace(valueStore.referencePosition); - valueStore.keyScaling.divideInPlace(valueStore.referenceScaling); - valueStore.referenceQuaternion.multiplyToRef(valueStore.keyQuaternion, valueStore.keyQuaternion); - math_vector_Matrix.ComposeToRef(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition, key.value); - break; - case animation_Animation.ANIMATIONTYPE_QUATERNION: - valueStore.referenceValue.multiplyToRef(key.value, key.value); - break; - case animation_Animation.ANIMATIONTYPE_VECTOR2: - case animation_Animation.ANIMATIONTYPE_VECTOR3: - case animation_Animation.ANIMATIONTYPE_COLOR3: - case animation_Animation.ANIMATIONTYPE_COLOR4: - key.value.subtractToRef(valueStore.referenceValue, key.value); - break; - case animation_Animation.ANIMATIONTYPE_SIZE: - key.value.width -= valueStore.referenceValue.width; - key.value.height -= valueStore.referenceValue.height; - break; - default: - key.value -= valueStore.referenceValue; - } - } - return animation; - } - /** - * Transition property of an host to the target Value - * @param property The property to transition - * @param targetValue The target Value of the property - * @param host The object where the property to animate belongs - * @param scene Scene used to run the animation - * @param frameRate Framerate (in frame/s) to use - * @param transition The transition type we want to use - * @param duration The duration of the animation, in milliseconds - * @param onAnimationEnd Callback trigger at the end of the animation - * @returns Nullable animation - */ - static TransitionTo(property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd = null) { - if (duration <= 0) { - host[property] = targetValue; - if (onAnimationEnd) { - onAnimationEnd(); - } - return null; - } - const endFrame = frameRate * (duration / 1000); - transition.setKeys([ - { - frame: 0, - value: host[property].clone ? host[property].clone() : host[property], - }, - { - frame: endFrame, - value: targetValue, - }, - ]); - if (!host.animations) { - host.animations = []; - } - host.animations.push(transition); - const animation = scene.beginAnimation(host, 0, endFrame, false); - animation.onAnimationEnd = onAnimationEnd; - return animation; - } - /** - * Return the array of runtime animations currently using this animation - */ - get runtimeAnimations() { - return this._runtimeAnimations; - } - /** - * Specifies if any of the runtime animations are currently running - */ - get hasRunningRuntimeAnimations() { - for (const runtimeAnimation of this._runtimeAnimations) { - if (!runtimeAnimation.isStopped()) { - return true; - } - } - return false; - } - /** - * Initializes the animation - * @param name Name of the animation - * @param targetProperty Property to animate - * @param framePerSecond The frames per second of the animation - * @param dataType The data type of the animation - * @param loopMode The loop mode of the animation - * @param enableBlending Specifies if blending should be enabled - */ - constructor( - /**Name of the animation */ - name, - /**Property to animate */ - targetProperty, - /**The frames per second of the animation */ - framePerSecond, - /**The data type of the animation */ - dataType, - /**The loop mode of the animation */ - loopMode, - /**Specifies if blending should be enabled */ - enableBlending) { - this.name = name; - this.targetProperty = targetProperty; - this.framePerSecond = framePerSecond; - this.dataType = dataType; - this.loopMode = loopMode; - this.enableBlending = enableBlending; - /** - * Stores the easing function of the animation - */ - this._easingFunction = null; - /** - * @internal Internal use only - */ - this._runtimeAnimations = new Array(); - /** - * The set of event that will be linked to this animation - */ - this._events = new Array(); - /** - * Stores the blending speed of the animation - */ - this.blendingSpeed = 0.01; - /** - * Stores the animation ranges for the animation - */ - this._ranges = {}; - this.targetPropertyPath = targetProperty.split("."); - this.dataType = dataType; - this.loopMode = loopMode === undefined ? animation_Animation.ANIMATIONLOOPMODE_CYCLE : loopMode; - this.uniqueId = animation_Animation._UniqueIdGenerator++; - } - // Methods - /** - * Converts the animation to a string - * @param fullDetails support for multiple levels of logging within scene loading - * @returns String form of the animation - */ - toString(fullDetails) { - let ret = "Name: " + this.name + ", property: " + this.targetProperty; - ret += ", datatype: " + ["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"][this.dataType]; - ret += ", nKeys: " + (this._keys ? this._keys.length : "none"); - ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"); - if (fullDetails) { - ret += ", Ranges: {"; - let first = true; - for (const name in this._ranges) { - if (first) { - ret += ", "; - first = false; - } - ret += name; - } - ret += "}"; - } - return ret; - } - /** - * Add an event to this animation - * @param event Event to add - */ - addEvent(event) { - this._events.push(event); - this._events.sort((a, b) => a.frame - b.frame); - } - /** - * Remove all events found at the given frame - * @param frame The frame to remove events from - */ - removeEvents(frame) { - for (let index = 0; index < this._events.length; index++) { - if (this._events[index].frame === frame) { - this._events.splice(index, 1); - index--; - } - } - } - /** - * Retrieves all the events from the animation - * @returns Events from the animation - */ - getEvents() { - return this._events; - } - /** - * Creates an animation range - * @param name Name of the animation range - * @param from Starting frame of the animation range - * @param to Ending frame of the animation - */ - createRange(name, from, to) { - // check name not already in use; could happen for bones after serialized - if (!this._ranges[name]) { - this._ranges[name] = new AnimationRange(name, from, to); - } - } - /** - * Deletes an animation range by name - * @param name Name of the animation range to delete - * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false) - */ - deleteRange(name, deleteFrames = true) { - const range = this._ranges[name]; - if (!range) { - return; - } - if (deleteFrames) { - const from = range.from; - const to = range.to; - // this loop MUST go high to low for multiple splices to work - for (let key = this._keys.length - 1; key >= 0; key--) { - if (this._keys[key].frame >= from && this._keys[key].frame <= to) { - this._keys.splice(key, 1); - } - } - } - this._ranges[name] = null; // said much faster than 'delete this._range[name]' - } - /** - * Gets the animation range by name, or null if not defined - * @param name Name of the animation range - * @returns Nullable animation range - */ - getRange(name) { - return this._ranges[name]; - } - /** - * Gets the key frames from the animation - * @returns The key frames of the animation - */ - getKeys() { - return this._keys; - } - /** - * Gets the highest frame rate of the animation - * @returns Highest frame rate of the animation - */ - getHighestFrame() { - let ret = 0; - for (let key = 0, nKeys = this._keys.length; key < nKeys; key++) { - if (ret < this._keys[key].frame) { - ret = this._keys[key].frame; - } - } - return ret; - } - /** - * Gets the easing function of the animation - * @returns Easing function of the animation - */ - getEasingFunction() { - return this._easingFunction; - } - /** - * Sets the easing function of the animation - * @param easingFunction A custom mathematical formula for animation - */ - setEasingFunction(easingFunction) { - this._easingFunction = easingFunction; - } - /** - * Interpolates a scalar linearly - * @param startValue Start value of the animation curve - * @param endValue End value of the animation curve - * @param gradient Scalar amount to interpolate - * @returns Interpolated scalar value - */ - floatInterpolateFunction(startValue, endValue, gradient) { - return math_scalar_Scalar.Lerp(startValue, endValue, gradient); - } - /** - * Interpolates a scalar cubically - * @param startValue Start value of the animation curve - * @param outTangent End tangent of the animation - * @param endValue End value of the animation curve - * @param inTangent Start tangent of the animation curve - * @param gradient Scalar amount to interpolate - * @returns Interpolated scalar value - */ - floatInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { - return math_scalar_Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient); - } - /** - * Interpolates a quaternion using a spherical linear interpolation - * @param startValue Start value of the animation curve - * @param endValue End value of the animation curve - * @param gradient Scalar amount to interpolate - * @returns Interpolated quaternion value - */ - quaternionInterpolateFunction(startValue, endValue, gradient) { - return math_vector_Quaternion.Slerp(startValue, endValue, gradient); - } - /** - * Interpolates a quaternion cubically - * @param startValue Start value of the animation curve - * @param outTangent End tangent of the animation curve - * @param endValue End value of the animation curve - * @param inTangent Start tangent of the animation curve - * @param gradient Scalar amount to interpolate - * @returns Interpolated quaternion value - */ - quaternionInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { - return math_vector_Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize(); - } - /** - * Interpolates a Vector3 linearly - * @param startValue Start value of the animation curve - * @param endValue End value of the animation curve - * @param gradient Scalar amount to interpolate (value between 0 and 1) - * @returns Interpolated scalar value - */ - vector3InterpolateFunction(startValue, endValue, gradient) { - return math_vector_Vector3.Lerp(startValue, endValue, gradient); - } - /** - * Interpolates a Vector3 cubically - * @param startValue Start value of the animation curve - * @param outTangent End tangent of the animation - * @param endValue End value of the animation curve - * @param inTangent Start tangent of the animation curve - * @param gradient Scalar amount to interpolate (value between 0 and 1) - * @returns InterpolatedVector3 value - */ - vector3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { - return math_vector_Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient); - } - /** - * Interpolates a Vector2 linearly - * @param startValue Start value of the animation curve - * @param endValue End value of the animation curve - * @param gradient Scalar amount to interpolate (value between 0 and 1) - * @returns Interpolated Vector2 value - */ - vector2InterpolateFunction(startValue, endValue, gradient) { - return math_vector_Vector2.Lerp(startValue, endValue, gradient); - } - /** - * Interpolates a Vector2 cubically - * @param startValue Start value of the animation curve - * @param outTangent End tangent of the animation - * @param endValue End value of the animation curve - * @param inTangent Start tangent of the animation curve - * @param gradient Scalar amount to interpolate (value between 0 and 1) - * @returns Interpolated Vector2 value - */ - vector2InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { - return math_vector_Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient); - } - /** - * Interpolates a size linearly - * @param startValue Start value of the animation curve - * @param endValue End value of the animation curve - * @param gradient Scalar amount to interpolate - * @returns Interpolated Size value - */ - sizeInterpolateFunction(startValue, endValue, gradient) { - return Size.Lerp(startValue, endValue, gradient); - } - /** - * Interpolates a Color3 linearly - * @param startValue Start value of the animation curve - * @param endValue End value of the animation curve - * @param gradient Scalar amount to interpolate - * @returns Interpolated Color3 value - */ - color3InterpolateFunction(startValue, endValue, gradient) { - return math_color_Color3.Lerp(startValue, endValue, gradient); - } - /** - * Interpolates a Color3 cubically - * @param startValue Start value of the animation curve - * @param outTangent End tangent of the animation - * @param endValue End value of the animation curve - * @param inTangent Start tangent of the animation curve - * @param gradient Scalar amount to interpolate - * @returns interpolated value - */ - color3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { - return math_color_Color3.Hermite(startValue, outTangent, endValue, inTangent, gradient); - } - /** - * Interpolates a Color4 linearly - * @param startValue Start value of the animation curve - * @param endValue End value of the animation curve - * @param gradient Scalar amount to interpolate - * @returns Interpolated Color3 value - */ - color4InterpolateFunction(startValue, endValue, gradient) { - return math_color_Color4.Lerp(startValue, endValue, gradient); - } - /** - * Interpolates a Color4 cubically - * @param startValue Start value of the animation curve - * @param outTangent End tangent of the animation - * @param endValue End value of the animation curve - * @param inTangent Start tangent of the animation curve - * @param gradient Scalar amount to interpolate - * @returns interpolated value - */ - color4InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { - return math_color_Color4.Hermite(startValue, outTangent, endValue, inTangent, gradient); - } - /** - * @internal Internal use only - */ - _getKeyValue(value) { - if (typeof value === "function") { - return value(); - } - return value; - } - /** - * Evaluate the animation value at a given frame - * @param currentFrame defines the frame where we want to evaluate the animation - * @returns the animation value - */ - evaluate(currentFrame) { - return this._interpolate(currentFrame, { - key: 0, - repeatCount: 0, - loopMode: animation_Animation.ANIMATIONLOOPMODE_CONSTANT, - }); - } - /** - * @internal Internal use only - */ - _interpolate(currentFrame, state) { - if (state.loopMode === animation_Animation.ANIMATIONLOOPMODE_CONSTANT && state.repeatCount > 0) { - return state.highLimitValue.clone ? state.highLimitValue.clone() : state.highLimitValue; - } - const keys = this._keys; - const keysLength = keys.length; - let key = state.key; - while (key >= 0 && currentFrame < keys[key].frame) { - --key; - } - while (key + 1 <= keysLength - 1 && currentFrame >= keys[key + 1].frame) { - ++key; - } - state.key = key; - if (key < 0) { - return this._getKeyValue(keys[0].value); - } - else if (key + 1 > keysLength - 1) { - return this._getKeyValue(keys[keysLength - 1].value); - } - const startKey = keys[key]; - const endKey = keys[key + 1]; - const startValue = this._getKeyValue(startKey.value); - const endValue = this._getKeyValue(endKey.value); - if (startKey.interpolation === AnimationKeyInterpolation.STEP) { - if (endKey.frame > currentFrame) { - return startValue; - } - else { - return endValue; - } - } - const useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined; - const frameDelta = endKey.frame - startKey.frame; - // gradient : percent of currentFrame between the frame inf and the frame sup - let gradient = (currentFrame - startKey.frame) / frameDelta; - // check for easingFunction and correction of gradient - const easingFunction = this.getEasingFunction(); - if (easingFunction !== null) { - gradient = easingFunction.ease(gradient); - } - switch (this.dataType) { - // Float - case animation_Animation.ANIMATIONTYPE_FLOAT: { - const floatValue = useTangent - ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) - : this.floatInterpolateFunction(startValue, endValue, gradient); - switch (state.loopMode) { - case animation_Animation.ANIMATIONLOOPMODE_CYCLE: - case animation_Animation.ANIMATIONLOOPMODE_CONSTANT: - case animation_Animation.ANIMATIONLOOPMODE_YOYO: - return floatValue; - case animation_Animation.ANIMATIONLOOPMODE_RELATIVE: - return state.offsetValue * state.repeatCount + floatValue; - } - break; - } - // Quaternion - case animation_Animation.ANIMATIONTYPE_QUATERNION: { - const quatValue = useTangent - ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) - : this.quaternionInterpolateFunction(startValue, endValue, gradient); - switch (state.loopMode) { - case animation_Animation.ANIMATIONLOOPMODE_CYCLE: - case animation_Animation.ANIMATIONLOOPMODE_CONSTANT: - case animation_Animation.ANIMATIONLOOPMODE_YOYO: - return quatValue; - case animation_Animation.ANIMATIONLOOPMODE_RELATIVE: - return quatValue.addInPlace(state.offsetValue.scale(state.repeatCount)); - } - return quatValue; - } - // Vector3 - case animation_Animation.ANIMATIONTYPE_VECTOR3: { - const vec3Value = useTangent - ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) - : this.vector3InterpolateFunction(startValue, endValue, gradient); - switch (state.loopMode) { - case animation_Animation.ANIMATIONLOOPMODE_CYCLE: - case animation_Animation.ANIMATIONLOOPMODE_CONSTANT: - case animation_Animation.ANIMATIONLOOPMODE_YOYO: - return vec3Value; - case animation_Animation.ANIMATIONLOOPMODE_RELATIVE: - return vec3Value.add(state.offsetValue.scale(state.repeatCount)); - } - break; - } - // Vector2 - case animation_Animation.ANIMATIONTYPE_VECTOR2: { - const vec2Value = useTangent - ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) - : this.vector2InterpolateFunction(startValue, endValue, gradient); - switch (state.loopMode) { - case animation_Animation.ANIMATIONLOOPMODE_CYCLE: - case animation_Animation.ANIMATIONLOOPMODE_CONSTANT: - case animation_Animation.ANIMATIONLOOPMODE_YOYO: - return vec2Value; - case animation_Animation.ANIMATIONLOOPMODE_RELATIVE: - return vec2Value.add(state.offsetValue.scale(state.repeatCount)); - } - break; - } - // Size - case animation_Animation.ANIMATIONTYPE_SIZE: { - switch (state.loopMode) { - case animation_Animation.ANIMATIONLOOPMODE_CYCLE: - case animation_Animation.ANIMATIONLOOPMODE_CONSTANT: - case animation_Animation.ANIMATIONLOOPMODE_YOYO: - return this.sizeInterpolateFunction(startValue, endValue, gradient); - case animation_Animation.ANIMATIONLOOPMODE_RELATIVE: - return this.sizeInterpolateFunction(startValue, endValue, gradient).add(state.offsetValue.scale(state.repeatCount)); - } - break; - } - // Color3 - case animation_Animation.ANIMATIONTYPE_COLOR3: { - const color3Value = useTangent - ? this.color3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) - : this.color3InterpolateFunction(startValue, endValue, gradient); - switch (state.loopMode) { - case animation_Animation.ANIMATIONLOOPMODE_CYCLE: - case animation_Animation.ANIMATIONLOOPMODE_CONSTANT: - case animation_Animation.ANIMATIONLOOPMODE_YOYO: - return color3Value; - case animation_Animation.ANIMATIONLOOPMODE_RELATIVE: - return color3Value.add(state.offsetValue.scale(state.repeatCount)); - } - break; - } - // Color4 - case animation_Animation.ANIMATIONTYPE_COLOR4: { - const color4Value = useTangent - ? this.color4InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) - : this.color4InterpolateFunction(startValue, endValue, gradient); - switch (state.loopMode) { - case animation_Animation.ANIMATIONLOOPMODE_CYCLE: - case animation_Animation.ANIMATIONLOOPMODE_CONSTANT: - case animation_Animation.ANIMATIONLOOPMODE_YOYO: - return color4Value; - case animation_Animation.ANIMATIONLOOPMODE_RELATIVE: - return color4Value.add(state.offsetValue.scale(state.repeatCount)); - } - break; - } - // Matrix - case animation_Animation.ANIMATIONTYPE_MATRIX: { - switch (state.loopMode) { - case animation_Animation.ANIMATIONLOOPMODE_CYCLE: - case animation_Animation.ANIMATIONLOOPMODE_CONSTANT: - case animation_Animation.ANIMATIONLOOPMODE_YOYO: { - if (animation_Animation.AllowMatricesInterpolation) { - return this.matrixInterpolateFunction(startValue, endValue, gradient, state.workValue); - } - return startValue; - } - case animation_Animation.ANIMATIONLOOPMODE_RELATIVE: { - return startValue; - } - } - break; - } - } - return 0; - } - /** - * Defines the function to use to interpolate matrices - * @param startValue defines the start matrix - * @param endValue defines the end matrix - * @param gradient defines the gradient between both matrices - * @param result defines an optional target matrix where to store the interpolation - * @returns the interpolated matrix - */ - matrixInterpolateFunction(startValue, endValue, gradient, result) { - if (animation_Animation.AllowMatrixDecomposeForInterpolation) { - if (result) { - math_vector_Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result); - return result; - } - return math_vector_Matrix.DecomposeLerp(startValue, endValue, gradient); - } - if (result) { - math_vector_Matrix.LerpToRef(startValue, endValue, gradient, result); - return result; - } - return math_vector_Matrix.Lerp(startValue, endValue, gradient); - } - /** - * Makes a copy of the animation - * @returns Cloned animation - */ - clone() { - const clone = new animation_Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode); - clone.enableBlending = this.enableBlending; - clone.blendingSpeed = this.blendingSpeed; - if (this._keys) { - clone.setKeys(this._keys); - } - if (this._ranges) { - clone._ranges = {}; - for (const name in this._ranges) { - const range = this._ranges[name]; - if (!range) { - continue; - } - clone._ranges[name] = range.clone(); - } - } - return clone; - } - /** - * Sets the key frames of the animation - * @param values The animation key frames to set - */ - setKeys(values) { - this._keys = values.slice(0); - } - /** - * Serializes the animation to an object - * @returns Serialized object - */ - serialize() { - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.property = this.targetProperty; - serializationObject.framePerSecond = this.framePerSecond; - serializationObject.dataType = this.dataType; - serializationObject.loopBehavior = this.loopMode; - serializationObject.enableBlending = this.enableBlending; - serializationObject.blendingSpeed = this.blendingSpeed; - const dataType = this.dataType; - serializationObject.keys = []; - const keys = this.getKeys(); - for (let index = 0; index < keys.length; index++) { - const animationKey = keys[index]; - const key = {}; - key.frame = animationKey.frame; - switch (dataType) { - case animation_Animation.ANIMATIONTYPE_FLOAT: - key.values = [animationKey.value]; - if (animationKey.inTangent !== undefined) { - key.values.push(animationKey.inTangent); - } - if (animationKey.outTangent !== undefined) { - if (animationKey.inTangent === undefined) { - key.values.push(undefined); - } - key.values.push(animationKey.outTangent); - } - if (animationKey.interpolation !== undefined) { - if (animationKey.inTangent === undefined) { - key.values.push(undefined); - } - if (animationKey.outTangent === undefined) { - key.values.push(undefined); - } - key.values.push(animationKey.interpolation); - } - break; - case animation_Animation.ANIMATIONTYPE_QUATERNION: - case animation_Animation.ANIMATIONTYPE_MATRIX: - case animation_Animation.ANIMATIONTYPE_VECTOR3: - case animation_Animation.ANIMATIONTYPE_COLOR3: - case animation_Animation.ANIMATIONTYPE_COLOR4: - key.values = animationKey.value.asArray(); - if (animationKey.inTangent != undefined) { - key.values.push(animationKey.inTangent.asArray()); - } - if (animationKey.outTangent != undefined) { - if (animationKey.inTangent === undefined) { - key.values.push(undefined); - } - key.values.push(animationKey.outTangent.asArray()); - } - if (animationKey.interpolation !== undefined) { - if (animationKey.inTangent === undefined) { - key.values.push(undefined); - } - if (animationKey.outTangent === undefined) { - key.values.push(undefined); - } - key.values.push(animationKey.interpolation); - } - break; - } - serializationObject.keys.push(key); - } - serializationObject.ranges = []; - for (const name in this._ranges) { - const source = this._ranges[name]; - if (!source) { - continue; - } - const range = {}; - range.name = name; - range.from = source.from; - range.to = source.to; - serializationObject.ranges.push(range); - } - return serializationObject; - } - /** - * @internal - */ - static _UniversalLerp(left, right, amount) { - const constructor = left.constructor; - if (constructor.Lerp) { - // Lerp supported - return constructor.Lerp(left, right, amount); - } - else if (constructor.Slerp) { - // Slerp supported - return constructor.Slerp(left, right, amount); - } - else if (left.toFixed) { - // Number - return left * (1.0 - amount) + amount * right; - } - else { - // Blending not supported - return right; - } - } - /** - * Parses an animation object and creates an animation - * @param parsedAnimation Parsed animation object - * @returns Animation object - */ - static Parse(parsedAnimation) { - const animation = new animation_Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior); - const dataType = parsedAnimation.dataType; - const keys = []; - let data; - let index; - if (parsedAnimation.enableBlending) { - animation.enableBlending = parsedAnimation.enableBlending; - } - if (parsedAnimation.blendingSpeed) { - animation.blendingSpeed = parsedAnimation.blendingSpeed; - } - for (index = 0; index < parsedAnimation.keys.length; index++) { - const key = parsedAnimation.keys[index]; - let inTangent = undefined; - let outTangent = undefined; - let interpolation = undefined; - switch (dataType) { - case animation_Animation.ANIMATIONTYPE_FLOAT: - data = key.values[0]; - if (key.values.length >= 2) { - inTangent = key.values[1]; - } - if (key.values.length >= 3) { - outTangent = key.values[2]; - } - if (key.values.length >= 4) { - interpolation = key.values[3]; - } - break; - case animation_Animation.ANIMATIONTYPE_QUATERNION: - data = math_vector_Quaternion.FromArray(key.values); - if (key.values.length >= 8) { - const _inTangent = math_vector_Quaternion.FromArray(key.values.slice(4, 8)); - if (!_inTangent.equals(math_vector_Quaternion.Zero())) { - inTangent = _inTangent; - } - } - if (key.values.length >= 12) { - const _outTangent = math_vector_Quaternion.FromArray(key.values.slice(8, 12)); - if (!_outTangent.equals(math_vector_Quaternion.Zero())) { - outTangent = _outTangent; - } - } - if (key.values.length >= 13) { - interpolation = key.values[12]; - } - break; - case animation_Animation.ANIMATIONTYPE_MATRIX: - data = math_vector_Matrix.FromArray(key.values); - if (key.values.length >= 17) { - interpolation = key.values[16]; - } - break; - case animation_Animation.ANIMATIONTYPE_COLOR3: - data = math_color_Color3.FromArray(key.values); - if (key.values[3]) { - inTangent = math_color_Color3.FromArray(key.values[3]); - } - if (key.values[4]) { - outTangent = math_color_Color3.FromArray(key.values[4]); - } - if (key.values[5]) { - interpolation = key.values[5]; - } - break; - case animation_Animation.ANIMATIONTYPE_COLOR4: - data = math_color_Color4.FromArray(key.values); - if (key.values[4]) { - inTangent = math_color_Color4.FromArray(key.values[4]); - } - if (key.values[5]) { - outTangent = math_color_Color4.FromArray(key.values[5]); - } - if (key.values[6]) { - interpolation = math_color_Color4.FromArray(key.values[6]); - } - break; - case animation_Animation.ANIMATIONTYPE_VECTOR3: - default: - data = math_vector_Vector3.FromArray(key.values); - if (key.values[3]) { - inTangent = math_vector_Vector3.FromArray(key.values[3]); - } - if (key.values[4]) { - outTangent = math_vector_Vector3.FromArray(key.values[4]); - } - if (key.values[5]) { - interpolation = key.values[5]; - } - break; - } - const keyData = {}; - keyData.frame = key.frame; - keyData.value = data; - if (inTangent != undefined) { - keyData.inTangent = inTangent; - } - if (outTangent != undefined) { - keyData.outTangent = outTangent; - } - if (interpolation != undefined) { - keyData.interpolation = interpolation; - } - keys.push(keyData); - } - animation.setKeys(keys); - if (parsedAnimation.ranges) { - for (index = 0; index < parsedAnimation.ranges.length; index++) { - data = parsedAnimation.ranges[index]; - animation.createRange(data.name, data.from, data.to); - } - } - return animation; - } - /** - * Appends the serialized animations from the source animations - * @param source Source containing the animations - * @param destination Target to store the animations - */ - static AppendSerializedAnimations(source, destination) { - decorators_SerializationHelper.AppendSerializedAnimations(source, destination); - } - /** - * Creates a new animation or an array of animations from a snippet saved in a remote file - * @param name defines the name of the animation to create (can be null or empty to use the one from the json data) - * @param url defines the url to load from - * @returns a promise that will resolve to the new animation or an array of animations - */ - static ParseFromFileAsync(name, url) { - return new Promise((resolve, reject) => { - const request = new webRequest_WebRequest(); - request.addEventListener("readystatechange", () => { - if (request.readyState == 4) { - if (request.status == 200) { - let serializationObject = JSON.parse(request.responseText); - if (serializationObject.animations) { - serializationObject = serializationObject.animations; - } - if (serializationObject.length) { - const output = new Array(); - for (const serializedAnimation of serializationObject) { - output.push(this.Parse(serializedAnimation)); - } - resolve(output); - } - else { - const output = this.Parse(serializationObject); - if (name) { - output.name = name; - } - resolve(output); - } - } - else { - reject("Unable to load the animation"); - } - } - }); - request.open("GET", url); - request.send(); - }); - } - /** - * Creates an animation or an array of animations from a snippet saved by the Inspector - * @param snippetId defines the snippet to load - * @returns a promise that will resolve to the new animation or a new array of animations - */ - static ParseFromSnippetAsync(snippetId) { - return new Promise((resolve, reject) => { - const request = new webRequest_WebRequest(); - request.addEventListener("readystatechange", () => { - if (request.readyState == 4) { - if (request.status == 200) { - const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); - if (snippet.animations) { - const serializationObject = JSON.parse(snippet.animations); - const outputs = new Array(); - for (const serializedAnimation of serializationObject.animations) { - const output = this.Parse(serializedAnimation); - output.snippetId = snippetId; - outputs.push(output); - } - resolve(outputs); - } - else { - const serializationObject = JSON.parse(snippet.animation); - const output = this.Parse(serializationObject); - output.snippetId = snippetId; - resolve(output); - } - } - else { - reject("Unable to load the snippet " + snippetId); - } - } - }); - request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); - request.send(); - }); - } -} -animation_Animation._UniqueIdGenerator = 0; -/** - * Use matrix interpolation instead of using direct key value when animating matrices - */ -animation_Animation.AllowMatricesInterpolation = false; -/** - * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower - */ -animation_Animation.AllowMatrixDecomposeForInterpolation = true; -/** Define the Url to load snippets */ -animation_Animation.SnippetUrl = `https://snippet.babylonjs.com`; -// Statics -/** - * Float animation type - */ -animation_Animation.ANIMATIONTYPE_FLOAT = 0; -/** - * Vector3 animation type - */ -animation_Animation.ANIMATIONTYPE_VECTOR3 = 1; -/** - * Quaternion animation type - */ -animation_Animation.ANIMATIONTYPE_QUATERNION = 2; -/** - * Matrix animation type - */ -animation_Animation.ANIMATIONTYPE_MATRIX = 3; -/** - * Color3 animation type - */ -animation_Animation.ANIMATIONTYPE_COLOR3 = 4; -/** - * Color3 animation type - */ -animation_Animation.ANIMATIONTYPE_COLOR4 = 7; -/** - * Vector2 animation type - */ -animation_Animation.ANIMATIONTYPE_VECTOR2 = 5; -/** - * Size animation type - */ -animation_Animation.ANIMATIONTYPE_SIZE = 6; -/** - * Relative Loop Mode - */ -animation_Animation.ANIMATIONLOOPMODE_RELATIVE = 0; -/** - * Cycle Loop Mode - */ -animation_Animation.ANIMATIONLOOPMODE_CYCLE = 1; -/** - * Constant Loop Mode - */ -animation_Animation.ANIMATIONLOOPMODE_CONSTANT = 2; -/** - * Yoyo Loop Mode - */ -animation_Animation.ANIMATIONLOOPMODE_YOYO = 4; -/** - * Creates an animation or an array of animations from a snippet saved by the Inspector - * @deprecated Please use ParseFromSnippetAsync instead - * @param snippetId defines the snippet to load - * @returns a promise that will resolve to the new animation or a new array of animations - */ -animation_Animation.CreateFromSnippetAsync = animation_Animation.ParseFromSnippetAsync; -RegisterClass("BABYLON.Animation", animation_Animation); -node_Node._AnimationRangeFactory = (name, from, to) => new AnimationRange(name, from, to); -//# sourceMappingURL=animation.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Actions/interpolateValueAction.js - - - - - - - -/** - * This defines an action responsible to change the value of a property - * by interpolating between its current value and the newly set one once triggered. - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ -class InterpolateValueAction extends Action { - /** - * Instantiate the action - * @param triggerOptions defines the trigger options - * @param target defines the object containing the value to interpolate - * @param propertyPath defines the path to the property in the target object - * @param value defines the target value at the end of the interpolation - * @param duration defines the time it will take for the property to interpolate to the value. - * @param condition defines the trigger related conditions - * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered - * @param onInterpolationDone defines a callback raised once the interpolation animation has been done - */ - constructor(triggerOptions, target, propertyPath, value, duration = 1000, condition, stopOtherAnimations, onInterpolationDone) { - super(triggerOptions, condition); - /** - * Defines the time it will take for the property to interpolate to the value. - */ - this.duration = 1000; - /** - * Observable triggered once the interpolation animation has been done. - */ - this.onInterpolationDoneObservable = new observable_Observable(); - this.propertyPath = propertyPath; - this.value = value; - this.duration = duration; - this.stopOtherAnimations = stopOtherAnimations; - this.onInterpolationDone = onInterpolationDone; - this._target = this._effectiveTarget = target; - } - /** @internal */ - _prepare() { - this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); - this._property = this._getProperty(this.propertyPath); - } - /** - * Execute the action starts the value interpolation. - */ - execute() { - const scene = this._actionManager.getScene(); - const keys = [ - { - frame: 0, - value: this._effectiveTarget[this._property], - }, - { - frame: 100, - value: this.value, - }, - ]; - let dataType; - if (typeof this.value === "number") { - dataType = animation_Animation.ANIMATIONTYPE_FLOAT; - } - else if (this.value instanceof math_color_Color3) { - dataType = animation_Animation.ANIMATIONTYPE_COLOR3; - } - else if (this.value instanceof math_vector_Vector3) { - dataType = animation_Animation.ANIMATIONTYPE_VECTOR3; - } - else if (this.value instanceof math_vector_Matrix) { - dataType = animation_Animation.ANIMATIONTYPE_MATRIX; - } - else if (this.value instanceof math_vector_Quaternion) { - dataType = animation_Animation.ANIMATIONTYPE_QUATERNION; - } - else { - logger_Logger.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")"); - return; - } - const animation = new animation_Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - animation.setKeys(keys); - if (this.stopOtherAnimations) { - scene.stopAnimation(this._effectiveTarget); - } - const wrapper = () => { - this.onInterpolationDoneObservable.notifyObservers(this); - if (this.onInterpolationDone) { - this.onInterpolationDone(); - } - }; - scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper); - } - /** - * Serializes the actions and its related information. - * @param parent defines the object to serialize in - * @returns the serialized object - */ - serialize(parent) { - return super._serialize({ - name: "InterpolateValueAction", - properties: [ - Action._GetTargetProperty(this._target), - { name: "propertyPath", value: this.propertyPath }, - { name: "value", value: Action._SerializeValueAsString(this.value) }, - { name: "duration", value: Action._SerializeValueAsString(this.duration) }, - { name: "stopOtherAnimations", value: Action._SerializeValueAsString(this.stopOtherAnimations) || false }, - ], - }, parent); - } -} -RegisterClass("BABYLON.InterpolateValueAction", InterpolateValueAction); -//# sourceMappingURL=interpolateValueAction.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Actions/index.js - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/runtimeAnimation.js - - - - -// Static values to help the garbage collector -// Quaternion -const _staticOffsetValueQuaternion = Object.freeze(new math_vector_Quaternion(0, 0, 0, 0)); -// Vector3 -const _staticOffsetValueVector3 = Object.freeze(math_vector_Vector3.Zero()); -// Vector2 -const _staticOffsetValueVector2 = Object.freeze(math_vector_Vector2.Zero()); -// Size -const _staticOffsetValueSize = Object.freeze(Size.Zero()); -// Color3 -const _staticOffsetValueColor3 = Object.freeze(math_color_Color3.Black()); -/** - * Defines a runtime animation - */ -class RuntimeAnimation { - /** - * Gets the current frame of the runtime animation - */ - get currentFrame() { - return this._currentFrame; - } - /** - * Gets the weight of the runtime animation - */ - get weight() { - return this._weight; - } - /** - * Gets the current value of the runtime animation - */ - get currentValue() { - return this._currentValue; - } - /** - * Gets or sets the target path of the runtime animation - */ - get targetPath() { - return this._targetPath; - } - /** - * Gets the actual target of the runtime animation - */ - get target() { - return this._currentActiveTarget; - } - /** - * Gets the additive state of the runtime animation - */ - get isAdditive() { - return this._host && this._host.isAdditive; - } - /** - * Create a new RuntimeAnimation object - * @param target defines the target of the animation - * @param animation defines the source animation object - * @param scene defines the hosting scene - * @param host defines the initiating Animatable - */ - constructor(target, animation, scene, host) { - this._events = new Array(); - /** - * The current frame of the runtime animation - */ - this._currentFrame = 0; - /** - * The original value of the runtime animation - */ - this._originalValue = new Array(); - /** - * The original blend value of the runtime animation - */ - this._originalBlendValue = null; - /** - * The offsets cache of the runtime animation - */ - this._offsetsCache = {}; - /** - * The high limits cache of the runtime animation - */ - this._highLimitsCache = {}; - /** - * Specifies if the runtime animation has been stopped - */ - this._stopped = false; - /** - * The blending factor of the runtime animation - */ - this._blendingFactor = 0; - /** - * The current value of the runtime animation - */ - this._currentValue = null; - this._currentActiveTarget = null; - this._directTarget = null; - /** - * The target path of the runtime animation - */ - this._targetPath = ""; - /** - * The weight of the runtime animation - */ - this._weight = 1.0; - /** - * The absolute frame offset of the runtime animation - */ - this._absoluteFrameOffset = 0; - /** - * The previous elapsed time (since start of animation) of the runtime animation - */ - this._previousElapsedTime = 0; - /** - * The previous absolute frame of the runtime animation (meaning, without taking into account the from/to values, only the elapsed time and the fps) - */ - this._previousAbsoluteFrame = 0; - this._targetIsArray = false; - this._animation = animation; - this._target = target; - this._scene = scene; - this._host = host; - this._activeTargets = []; - animation._runtimeAnimations.push(this); - // State - this._animationState = { - key: 0, - repeatCount: 0, - loopMode: this._getCorrectLoopMode(), - }; - if (this._animation.dataType === animation_Animation.ANIMATIONTYPE_MATRIX) { - this._animationState.workValue = math_vector_Matrix.Zero(); - } - // Limits - 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; - // Add a start key at frame 0 if missing - if (this._minFrame !== 0) { - const newKey = { frame: 0, value: this._minValue }; - this._keys.splice(0, 0, newKey); - } - // Check data - if (this._target instanceof Array) { - let index = 0; - for (const target of this._target) { - this._preparePath(target, index); - this._getOriginalValues(index); - index++; - } - this._targetIsArray = true; - } - else { - this._preparePath(this._target); - this._getOriginalValues(); - this._targetIsArray = false; - this._directTarget = this._activeTargets[0]; - } - // Cloning events locally - const events = animation.getEvents(); - if (events && events.length > 0) { - events.forEach((e) => { - this._events.push(e._clone()); - }); - } - this._enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending; - } - _preparePath(target, targetIndex = 0) { - const targetPropertyPath = this._animation.targetPropertyPath; - if (targetPropertyPath.length > 1) { - let property = target[targetPropertyPath[0]]; - for (let index = 1; index < targetPropertyPath.length - 1; index++) { - property = property[targetPropertyPath[index]]; - } - this._targetPath = targetPropertyPath[targetPropertyPath.length - 1]; - this._activeTargets[targetIndex] = property; - } - else { - this._targetPath = targetPropertyPath[0]; - this._activeTargets[targetIndex] = target; - } - } - /** - * Gets the animation from the runtime animation - */ - get animation() { - return this._animation; - } - /** - * Resets the runtime animation to the beginning - * @param restoreOriginal defines whether to restore the target property to the original value - */ - reset(restoreOriginal = false) { - if (restoreOriginal) { - if (this._target instanceof Array) { - let index = 0; - for (const target of this._target) { - if (this._originalValue[index] !== undefined) { - this._setValue(target, this._activeTargets[index], this._originalValue[index], -1, index); - } - index++; - } - } - else { - if (this._originalValue[0] !== undefined) { - this._setValue(this._target, this._directTarget, this._originalValue[0], -1, 0); - } - } - } - this._offsetsCache = {}; - this._highLimitsCache = {}; - this._currentFrame = 0; - this._blendingFactor = 0; - // Events - for (let index = 0; index < this._events.length; index++) { - this._events[index].isDone = false; - } - } - /** - * Specifies if the runtime animation is stopped - * @returns Boolean specifying if the runtime animation is stopped - */ - isStopped() { - return this._stopped; - } - /** - * Disposes of the runtime animation - */ - dispose() { - const index = this._animation.runtimeAnimations.indexOf(this); - if (index > -1) { - this._animation.runtimeAnimations.splice(index, 1); - } - } - /** - * Apply the interpolated value to the target - * @param currentValue defines the value computed by the animation - * @param weight defines the weight to apply to this value (Defaults to 1.0) - */ - setValue(currentValue, weight) { - if (this._targetIsArray) { - for (let index = 0; index < this._target.length; index++) { - const target = this._target[index]; - this._setValue(target, this._activeTargets[index], currentValue, weight, index); - } - return; - } - this._setValue(this._target, this._directTarget, currentValue, weight, 0); - } - _getOriginalValues(targetIndex = 0) { - let originalValue; - const target = this._activeTargets[targetIndex]; - if (target.getRestPose && this._targetPath === "_matrix") { - // For bones - originalValue = target.getRestPose(); - } - else { - originalValue = target[this._targetPath]; - } - if (originalValue && originalValue.clone) { - this._originalValue[targetIndex] = originalValue.clone(); - } - else { - this._originalValue[targetIndex] = originalValue; - } - } - _setValue(target, destination, currentValue, weight, targetIndex) { - // Set value - this._currentActiveTarget = destination; - this._weight = weight; - if (this._enableBlending && this._blendingFactor <= 1.0) { - if (!this._originalBlendValue) { - const originalValue = destination[this._targetPath]; - if (originalValue.clone) { - this._originalBlendValue = originalValue.clone(); - } - else { - this._originalBlendValue = originalValue; - } - } - if (this._originalBlendValue.m) { - // Matrix - if (animation_Animation.AllowMatrixDecomposeForInterpolation) { - if (this._currentValue) { - math_vector_Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); - } - else { - this._currentValue = math_vector_Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor); - } - } - else { - if (this._currentValue) { - math_vector_Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); - } - else { - this._currentValue = math_vector_Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor); - } - } - } - else { - this._currentValue = animation_Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor); - } - const blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed; - this._blendingFactor += blendingSpeed; - } - else { - if (!this._currentValue) { - if (currentValue === null || currentValue === void 0 ? void 0 : currentValue.clone) { - this._currentValue = currentValue.clone(); - } - else { - this._currentValue = currentValue; - } - } - else if (this._currentValue.copyFrom) { - this._currentValue.copyFrom(currentValue); - } - else { - this._currentValue = currentValue; - } - } - if (weight !== -1.0) { - this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]); - } - else { - destination[this._targetPath] = this._currentValue; - } - if (target.markAsDirty) { - target.markAsDirty(this._animation.targetProperty); - } - } - /** - * Gets the loop pmode of the runtime animation - * @returns Loop Mode - */ - _getCorrectLoopMode() { - if (this._target && this._target.animationPropertiesOverride) { - return this._target.animationPropertiesOverride.loopMode; - } - return this._animation.loopMode; - } - /** - * Move the current animation to a given frame - * @param frame defines the frame to move to - */ - goToFrame(frame) { - const keys = this._animation.getKeys(); - if (frame < keys[0].frame) { - frame = keys[0].frame; - } - else if (frame > keys[keys.length - 1].frame) { - frame = keys[keys.length - 1].frame; - } - // Need to reset animation events - const events = this._events; - if (events.length) { - for (let index = 0; index < events.length; index++) { - if (!events[index].onlyOnce) { - // reset events in the future - events[index].isDone = events[index].frame < frame; - } - } - } - this._currentFrame = frame; - const currentValue = this._animation._interpolate(frame, this._animationState); - this.setValue(currentValue, -1); - } - /** - * @internal Internal use only - */ - _prepareForSpeedRatioChange(newSpeedRatio) { - const newAbsoluteFrame = (this._previousElapsedTime * (this._animation.framePerSecond * newSpeedRatio)) / 1000.0; - this._absoluteFrameOffset = this._previousAbsoluteFrame - newAbsoluteFrame; - } - /** - * Execute the current animation - * @param elapsedTimeSinceAnimationStart defines the elapsed time (in milliseconds) since the animation was started - * @param from defines the lower frame of the animation range - * @param to defines the upper frame of the animation range - * @param loop defines if the current animation must loop - * @param speedRatio defines the current speed ratio - * @param weight defines the weight of the animation (default is -1 so no weight) - * @returns a boolean indicating if the animation is running - */ - animate(elapsedTimeSinceAnimationStart, from, to, loop, speedRatio, weight = -1.0) { - const animation = this._animation; - const targetPropertyPath = animation.targetPropertyPath; - if (!targetPropertyPath || targetPropertyPath.length < 1) { - this._stopped = true; - return false; - } - let returnValue = true; - // Check limits - if (from < this._minFrame || from > this._maxFrame) { - from = this._minFrame; - } - if (to < this._minFrame || to > this._maxFrame) { - to = this._maxFrame; - } - const frameRange = to - from; - let offsetValue; - // Compute the frame according to the elapsed time and the fps of the animation ("from" and "to" are not factored in!) - let absoluteFrame = (elapsedTimeSinceAnimationStart * (animation.framePerSecond * speedRatio)) / 1000.0 + this._absoluteFrameOffset; - let highLimitValue = 0; - // Apply the yoyo function if required - if (loop && this._animationState.loopMode === animation_Animation.ANIMATIONLOOPMODE_YOYO) { - const position = (absoluteFrame - from) / frameRange; - // Apply the yoyo curve - const yoyoPosition = Math.abs(Math.sin(position * Math.PI)); - // Map the yoyo position back to the range - absoluteFrame = yoyoPosition * frameRange + from; - } - this._previousElapsedTime = elapsedTimeSinceAnimationStart; - this._previousAbsoluteFrame = absoluteFrame; - if (!loop && to >= from && absoluteFrame >= frameRange) { - // If we are out of range and not looping get back to caller - returnValue = false; - highLimitValue = animation._getKeyValue(this._maxValue); - } - else if (!loop && from >= to && absoluteFrame <= frameRange) { - returnValue = false; - highLimitValue = animation._getKeyValue(this._minValue); - } - else if (this._animationState.loopMode !== animation_Animation.ANIMATIONLOOPMODE_CYCLE) { - const keyOffset = to.toString() + from.toString(); - if (!this._offsetsCache[keyOffset]) { - this._animationState.repeatCount = 0; - this._animationState.loopMode = animation_Animation.ANIMATIONLOOPMODE_CYCLE; // force a specific codepath in animation._interpolate()! - const fromValue = animation._interpolate(from, this._animationState); - const toValue = animation._interpolate(to, this._animationState); - this._animationState.loopMode = this._getCorrectLoopMode(); - switch (animation.dataType) { - // Float - case animation_Animation.ANIMATIONTYPE_FLOAT: - this._offsetsCache[keyOffset] = toValue - fromValue; - break; - // Quaternion - case animation_Animation.ANIMATIONTYPE_QUATERNION: - this._offsetsCache[keyOffset] = toValue.subtract(fromValue); - break; - // Vector3 - case animation_Animation.ANIMATIONTYPE_VECTOR3: - this._offsetsCache[keyOffset] = toValue.subtract(fromValue); - break; - // Vector2 - case animation_Animation.ANIMATIONTYPE_VECTOR2: - this._offsetsCache[keyOffset] = toValue.subtract(fromValue); - break; - // Size - case animation_Animation.ANIMATIONTYPE_SIZE: - this._offsetsCache[keyOffset] = toValue.subtract(fromValue); - break; - // Color3 - case animation_Animation.ANIMATIONTYPE_COLOR3: - this._offsetsCache[keyOffset] = toValue.subtract(fromValue); - break; - default: - break; - } - this._highLimitsCache[keyOffset] = toValue; - } - highLimitValue = this._highLimitsCache[keyOffset]; - offsetValue = this._offsetsCache[keyOffset]; - } - if (offsetValue === undefined) { - switch (animation.dataType) { - // Float - case animation_Animation.ANIMATIONTYPE_FLOAT: - offsetValue = 0; - break; - // Quaternion - case animation_Animation.ANIMATIONTYPE_QUATERNION: - offsetValue = _staticOffsetValueQuaternion; - break; - // Vector3 - case animation_Animation.ANIMATIONTYPE_VECTOR3: - offsetValue = _staticOffsetValueVector3; - break; - // Vector2 - case animation_Animation.ANIMATIONTYPE_VECTOR2: - offsetValue = _staticOffsetValueVector2; - break; - // Size - case animation_Animation.ANIMATIONTYPE_SIZE: - offsetValue = _staticOffsetValueSize; - break; - // Color3 - case animation_Animation.ANIMATIONTYPE_COLOR3: - offsetValue = _staticOffsetValueColor3; - } - } - // Compute value - let currentFrame; - if (this._host && this._host.syncRoot) { - // If we must sync with an animatable, calculate the current frame based on the frame of the root animatable - const syncRoot = this._host.syncRoot; - const hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame); - currentFrame = from + frameRange * hostNormalizedFrame; - } - else { - if ((absoluteFrame > 0 && from > to) || (absoluteFrame < 0 && from < to)) { - currentFrame = returnValue && frameRange !== 0 ? to + (absoluteFrame % frameRange) : from; - } - else { - currentFrame = returnValue && frameRange !== 0 ? from + (absoluteFrame % frameRange) : to; - } - } - const events = this._events; - // Reset event/state if looping - if ((speedRatio > 0 && this.currentFrame > currentFrame) || (speedRatio < 0 && this.currentFrame < currentFrame)) { - this._onLoop(); - // Need to reset animation events - for (let index = 0; index < events.length; index++) { - if (!events[index].onlyOnce) { - // reset event, the animation is looping - events[index].isDone = false; - } - } - this._animationState.key = speedRatio > 0 ? 0 : animation.getKeys().length - 1; - } - this._currentFrame = currentFrame; - this._animationState.repeatCount = frameRange === 0 ? 0 : (absoluteFrame / frameRange) >> 0; - this._animationState.highLimitValue = highLimitValue; - this._animationState.offsetValue = offsetValue; - const currentValue = animation._interpolate(currentFrame, this._animationState); - // Set value - this.setValue(currentValue, weight); - // Check events - if (events.length) { - for (let index = 0; index < events.length; index++) { - // Make sure current frame has passed event frame and that event frame is within the current range - // Also, handle both forward and reverse animations - if ((frameRange > 0 && currentFrame >= events[index].frame && events[index].frame >= from) || - (frameRange < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) { - const event = events[index]; - if (!event.isDone) { - // If event should be done only once, remove it. - if (event.onlyOnce) { - events.splice(index, 1); - index--; - } - event.isDone = true; - event.action(currentFrame); - } // Don't do anything if the event has already been done. - } - } - } - if (!returnValue) { - this._stopped = true; - } - return returnValue; - } -} -//# sourceMappingURL=runtimeAnimation.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/domManagement.js -/* eslint-disable @typescript-eslint/naming-convention */ -/** - * Checks if the window object exists - * @returns true if the window object exists - */ -function IsWindowObjectExist() { - return typeof window !== "undefined"; -} -/** - * Checks if the navigator object exists - * @returns true if the navigator object exists - */ -function IsNavigatorAvailable() { - return typeof navigator !== "undefined"; -} -/** - * Check if the document object exists - * @returns true if the document object exists - */ -function IsDocumentAvailable() { - return typeof document !== "undefined"; -} -/** - * Extracts text content from a DOM element hierarchy - * @param element defines the root element - * @returns a string - */ -function GetDOMTextContent(element) { - let result = ""; - let child = element.firstChild; - while (child) { - if (child.nodeType === 3) { - result += child.textContent; - } - child = child.nextSibling; - } - return result; -} -/** - * Sets of helpers dealing with the DOM and some of the recurrent functions needed in - * Babylon.js - */ -const DomManagement = { - /** - * Checks if the window object exists - * @returns true if the window object exists - */ - IsWindowObjectExist, - /** - * Checks if the navigator object exists - * @returns true if the navigator object exists - */ - IsNavigatorAvailable, - /** - * Check if the document object exists - * @returns true if the document object exists - */ - IsDocumentAvailable, - /** - * Extracts text content from a DOM element hierarchy - * @param element defines the root element - * @returns a string - */ - GetDOMTextContent, -}; -//# sourceMappingURL=domManagement.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/precisionDate.js - -/** - * Class containing a set of static utilities functions for precision date - */ -class precisionDate_PrecisionDate { - /** - * Gets either window.performance.now() if supported or Date.now() else - */ - static get Now() { - if (IsWindowObjectExist() && window.performance && window.performance.now) { - return window.performance.now(); - } - return Date.now(); - } -} -//# sourceMappingURL=precisionDate.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/filesInputStore.js -/** - * Class used to help managing file picking and drag'n'drop - * File Storage - */ -class filesInputStore_FilesInputStore { -} -/** - * List of files ready to be loaded - */ -filesInputStore_FilesInputStore.FilesToLoad = {}; -//# sourceMappingURL=filesInputStore.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/retryStrategy.js -/** - * Class used to define a retry strategy when error happens while loading assets - */ -class RetryStrategy { - /** - * Function used to defines an exponential back off strategy - * @param maxRetries defines the maximum number of retries (3 by default) - * @param baseInterval defines the interval between retries - * @returns the strategy function to use - */ - static ExponentialBackoff(maxRetries = 3, baseInterval = 500) { - return (url, request, retryIndex) => { - if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) { - return -1; - } - return Math.pow(2, retryIndex) * baseInterval; - }; - } -} -//# sourceMappingURL=retryStrategy.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/error.js -/* eslint-disable @typescript-eslint/naming-convention */ -/** - * Base error. Due to limitations of typedoc-check and missing documentation - * in lib.es5.d.ts, cannot extend Error directly for RuntimeError. - * @ignore - */ -class BaseError extends Error { -} -// See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript -// and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work -// Polyfill for Object.setPrototypeOf if necessary. -BaseError._setPrototypeOf = Object.setPrototypeOf || - ((o, proto) => { - o.__proto__ = proto; - return o; - }); -/* IMP! DO NOT CHANGE THE NUMBERING OF EXISTING ERROR CODES */ -/** - * Error codes for BaseError - */ -const ErrorCodes = { - // Mesh errors 0-999 - /** Invalid or empty mesh vertex positions. */ - MeshInvalidPositionsError: 0, - // Texture errors 1000-1999 - /** Unsupported texture found. */ - UnsupportedTextureError: 1000, - // GLTFLoader errors 2000-2999 - /** Unexpected magic number found in GLTF file header. */ - GLTFLoaderUnexpectedMagicError: 2000, - // SceneLoader errors 3000-3999 - /** SceneLoader generic error code. Ideally wraps the inner exception. */ - SceneLoaderError: 3000, - // File related errors 4000-4999 - /** Load file error */ - LoadFileError: 4000, - /** Request file error */ - RequestFileError: 4001, - /** Read file error */ - ReadFileError: 4002, -}; -/** - * Application runtime error - */ -class RuntimeError extends BaseError { - /** - * Creates a new RuntimeError - * @param message defines the message of the error - * @param errorCode the error code - * @param innerError the error that caused the outer error - */ - constructor(message, errorCode, innerError) { - super(message); - this.errorCode = errorCode; - this.innerError = innerError; - this.name = "RuntimeError"; - BaseError._setPrototypeOf(this, RuntimeError.prototype); - } -} -//# sourceMappingURL=error.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/stringTools.js -/* eslint-disable @typescript-eslint/naming-convention */ -/** - * Checks for a matching suffix at the end of a string (for ES5 and lower) - * @param str Source string - * @param suffix Suffix to search for in the source string - * @returns Boolean indicating whether the suffix was found (true) or not (false) - * @deprecated Please use native string function instead - */ -const EndsWith = (str, suffix) => { - return str.endsWith(suffix); -}; -/** - * Checks for a matching suffix at the beginning of a string (for ES5 and lower) - * @param str Source string - * @param suffix Suffix to search for in the source string - * @returns Boolean indicating whether the suffix was found (true) or not (false) - * @deprecated Please use native string function instead - */ -const StartsWith = (str, suffix) => { - if (!str) { - return false; - } - return str.startsWith(suffix); -}; -/** - * Decodes a buffer into a string - * @param buffer The buffer to decode - * @returns The decoded string - */ -const stringTools_Decode = (buffer) => { - if (typeof TextDecoder !== "undefined") { - return new TextDecoder().decode(buffer); - } - let result = ""; - for (let i = 0; i < buffer.byteLength; i++) { - result += String.fromCharCode(buffer[i]); - } - return result; -}; -/** - * Encode a buffer to a base64 string - * @param buffer defines the buffer to encode - * @returns the encoded string - */ -const stringTools_EncodeArrayBufferToBase64 = (buffer) => { - const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; - let output = ""; - let chr1, chr2, chr3, enc1, enc2, enc3, enc4; - let i = 0; - const bytes = ArrayBuffer.isView(buffer) ? new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) : new Uint8Array(buffer); - while (i < bytes.length) { - chr1 = bytes[i++]; - chr2 = i < bytes.length ? bytes[i++] : Number.NaN; - chr3 = i < bytes.length ? bytes[i++] : Number.NaN; - enc1 = chr1 >> 2; - enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); - enc4 = chr3 & 63; - if (isNaN(chr2)) { - enc3 = enc4 = 64; - } - else if (isNaN(chr3)) { - enc4 = 64; - } - output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); - } - return output; -}; -/** - * Converts a given base64 string as an ASCII encoded stream of data - * @param base64Data The base64 encoded string to decode - * @returns Decoded ASCII string - */ -const DecodeBase64ToString = (base64Data) => { - return atob(base64Data); -}; -/** - * Converts a given base64 string into an ArrayBuffer of raw byte data - * @param base64Data The base64 encoded string to decode - * @returns ArrayBuffer of byte data - */ -const stringTools_DecodeBase64ToBinary = (base64Data) => { - const decodedString = DecodeBase64ToString(base64Data); - const bufferLength = decodedString.length; - const bufferView = new Uint8Array(new ArrayBuffer(bufferLength)); - for (let i = 0; i < bufferLength; i++) { - bufferView[i] = decodedString.charCodeAt(i); - } - return bufferView.buffer; -}; -/** - * Converts a number to string and pads with preceding zeroes until it is of specified length. - * @param num the number to convert and pad - * @param length the expected length of the string - * @returns the padded string - */ -const PadNumber = (num, length) => { - let str = String(num); - while (str.length < length) { - str = "0" + str; - } - return str; -}; -/** - * Helper to manipulate strings - */ -const StringTools = { - EndsWith, - StartsWith, - Decode: stringTools_Decode, - EncodeArrayBufferToBase64: stringTools_EncodeArrayBufferToBase64, - DecodeBase64ToString, - DecodeBase64ToBinary: stringTools_DecodeBase64ToBinary, - PadNumber, -}; -//# sourceMappingURL=stringTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/shaderCodeNode.js -const defaultAttributeKeywordName = "attribute"; -const defaultVaryingKeywordName = "varying"; -/** @internal */ -class ShaderCodeNode { - constructor() { - this.children = []; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - isValid(preprocessors) { - return true; - } - process(preprocessors, options) { - var _a, _b, _c, _d, _e, _f, _g; - let result = ""; - if (this.line) { - let value = this.line; - const processor = options.processor; - if (processor) { - // This must be done before other replacements to avoid mistakenly changing something that was already changed. - if (processor.lineProcessor) { - value = processor.lineProcessor(value, options.isFragment, options.processingContext); - } - const attributeKeyword = (_b = (_a = options.processor) === null || _a === void 0 ? void 0 : _a.attributeKeywordName) !== null && _b !== void 0 ? _b : defaultAttributeKeywordName; - const varyingKeyword = options.isFragment && ((_c = options.processor) === null || _c === void 0 ? void 0 : _c.varyingFragmentKeywordName) - ? (_d = options.processor) === null || _d === void 0 ? void 0 : _d.varyingFragmentKeywordName - : !options.isFragment && ((_e = options.processor) === null || _e === void 0 ? void 0 : _e.varyingVertexKeywordName) - ? (_f = options.processor) === null || _f === void 0 ? void 0 : _f.varyingVertexKeywordName - : defaultVaryingKeywordName; - if (!options.isFragment && processor.attributeProcessor && this.line.startsWith(attributeKeyword)) { - value = processor.attributeProcessor(this.line, preprocessors, options.processingContext); - } - else if (processor.varyingProcessor && - (((_g = processor.varyingCheck) === null || _g === void 0 ? void 0 : _g.call(processor, this.line, options.isFragment)) || (!processor.varyingCheck && this.line.startsWith(varyingKeyword)))) { - value = processor.varyingProcessor(this.line, options.isFragment, preprocessors, options.processingContext); - } - else if (processor.uniformProcessor && processor.uniformRegexp && processor.uniformRegexp.test(this.line)) { - if (!options.lookForClosingBracketForUniformBuffer) { - value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext); - } - } - else if (processor.uniformBufferProcessor && processor.uniformBufferRegexp && processor.uniformBufferRegexp.test(this.line)) { - if (!options.lookForClosingBracketForUniformBuffer) { - value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext); - options.lookForClosingBracketForUniformBuffer = true; - } - } - else if (processor.textureProcessor && processor.textureRegexp && processor.textureRegexp.test(this.line)) { - value = processor.textureProcessor(this.line, options.isFragment, preprocessors, options.processingContext); - } - else if ((processor.uniformProcessor || processor.uniformBufferProcessor) && this.line.startsWith("uniform") && !options.lookForClosingBracketForUniformBuffer) { - const regex = /uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/; - if (regex.test(this.line)) { - // uniform - if (processor.uniformProcessor) { - value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext); - } - } - else { - // Uniform buffer - if (processor.uniformBufferProcessor) { - value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext); - options.lookForClosingBracketForUniformBuffer = true; - } - } - } - if (options.lookForClosingBracketForUniformBuffer && this.line.indexOf("}") !== -1) { - options.lookForClosingBracketForUniformBuffer = false; - if (processor.endOfUniformBufferProcessor) { - value = processor.endOfUniformBufferProcessor(this.line, options.isFragment, options.processingContext); - } - } - } - result += value + "\n"; - } - this.children.forEach((child) => { - result += child.process(preprocessors, options); - }); - if (this.additionalDefineKey) { - preprocessors[this.additionalDefineKey] = this.additionalDefineValue || "true"; - } - return result; - } -} -//# sourceMappingURL=shaderCodeNode.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/shaderCodeCursor.js -/** @internal */ -class ShaderCodeCursor { - constructor() { - this._lines = []; - } - get currentLine() { - return this._lines[this.lineIndex]; - } - get canRead() { - return this.lineIndex < this._lines.length - 1; - } - set lines(value) { - this._lines.length = 0; - for (const line of value) { - // Skip empty lines - if (!line || line === "\r") { - continue; - } - // Prevent removing line break in macros. - if (line[0] === "#") { - this._lines.push(line); - continue; - } - // Do not split single line comments - const trimmedLine = line.trim(); - if (!trimmedLine) { - continue; - } - if (trimmedLine.startsWith("//")) { - this._lines.push(line); - continue; - } - // Work with semicolon in the line - const semicolonIndex = trimmedLine.indexOf(";"); - if (semicolonIndex === -1) { - // No semicolon in the line - this._lines.push(trimmedLine); - } - else if (semicolonIndex === trimmedLine.length - 1) { - // Single semicolon at the end of the line - // If trimmedLine == ";", we must not push, to be backward compatible with the old code! - if (trimmedLine.length > 1) { - this._lines.push(trimmedLine); - } - } - else { - // Semicolon in the middle of the line - const split = line.split(";"); - for (let index = 0; index < split.length; index++) { - let subLine = split[index]; - if (!subLine) { - continue; - } - subLine = subLine.trim(); - if (!subLine) { - continue; - } - this._lines.push(subLine + (index !== split.length - 1 ? ";" : "")); - } - } - } - } -} -//# sourceMappingURL=shaderCodeCursor.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/shaderCodeConditionNode.js - -/** @internal */ -class ShaderCodeConditionNode extends ShaderCodeNode { - process(preprocessors, options) { - for (let index = 0; index < this.children.length; index++) { - const node = this.children[index]; - if (node.isValid(preprocessors)) { - return node.process(preprocessors, options); - } - } - return ""; - } -} -//# sourceMappingURL=shaderCodeConditionNode.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/shaderCodeTestNode.js - -/** @internal */ -class ShaderCodeTestNode extends ShaderCodeNode { - isValid(preprocessors) { - return this.testExpression.isTrue(preprocessors); - } -} -//# sourceMappingURL=shaderCodeTestNode.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/Expressions/shaderDefineExpression.js -/* eslint-disable @typescript-eslint/naming-convention */ -/** @internal */ -class ShaderDefineExpression { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - isTrue(preprocessors) { - return true; - } - static postfixToInfix(postfix) { - const stack = []; - for (const c of postfix) { - if (ShaderDefineExpression._OperatorPriority[c] === undefined) { - stack.push(c); - } - else { - const v1 = stack[stack.length - 1], v2 = stack[stack.length - 2]; - stack.length -= 2; - stack.push(`(${v2}${c}${v1})`); - } - } - return stack[stack.length - 1]; - } - /** - * Converts an infix expression to a postfix expression. - * - * This method is used to transform infix expressions, which are more human-readable, - * into postfix expressions, also known as Reverse Polish Notation (RPN), that can be - * evaluated more efficiently by a computer. The conversion is based on the operator - * priority defined in _OperatorPriority. - * - * The function employs a stack-based algorithm for the conversion and caches the result - * to improve performance. The cache keeps track of each converted expression's access time - * to manage the cache size and optimize memory usage. When the cache size exceeds a specified - * limit, the least recently accessed items in the cache are deleted. - * - * The cache mechanism is particularly helpful for shader compilation, where the same infix - * expressions might be encountered repeatedly, hence the caching can speed up the process. - * - * @param infix - The infix expression to be converted. - * @returns The postfix expression as an array of strings. - */ - static infixToPostfix(infix) { - // Is infix already in cache - const cacheItem = ShaderDefineExpression._InfixToPostfixCache.get(infix); - if (cacheItem) { - cacheItem.accessTime = Date.now(); - return cacheItem.result; - } - // Is infix contain any operator - if (!infix.includes("&&") && !infix.includes("||") && !infix.includes(")") && !infix.includes("(")) { - return [infix]; - } - const result = []; - let stackIdx = -1; - const pushOperand = () => { - operand = operand.trim(); - if (operand !== "") { - result.push(operand); - operand = ""; - } - }; - const push = (s) => { - if (stackIdx < ShaderDefineExpression._Stack.length - 1) { - ShaderDefineExpression._Stack[++stackIdx] = s; - } - }; - const peek = () => ShaderDefineExpression._Stack[stackIdx]; - const pop = () => (stackIdx === -1 ? "!!INVALID EXPRESSION!!" : ShaderDefineExpression._Stack[stackIdx--]); - let idx = 0, operand = ""; - while (idx < infix.length) { - const c = infix.charAt(idx), token = idx < infix.length - 1 ? infix.substr(idx, 2) : ""; - if (c === "(") { - operand = ""; - push(c); - } - else if (c === ")") { - pushOperand(); - while (stackIdx !== -1 && peek() !== "(") { - result.push(pop()); - } - pop(); - } - else if (ShaderDefineExpression._OperatorPriority[token] > 1) { - pushOperand(); - while (stackIdx !== -1 && ShaderDefineExpression._OperatorPriority[peek()] >= ShaderDefineExpression._OperatorPriority[token]) { - result.push(pop()); - } - push(token); - idx++; - } - else { - operand += c; - } - idx++; - } - pushOperand(); - while (stackIdx !== -1) { - if (peek() === "(") { - pop(); - } - else { - result.push(pop()); - } - } - // If the cache is at capacity, clear it before adding a new item - if (ShaderDefineExpression._InfixToPostfixCache.size >= ShaderDefineExpression.InfixToPostfixCacheLimitSize) { - ShaderDefineExpression.ClearCache(); - } - // Add the new item to the cache, including the current time as the last access time - ShaderDefineExpression._InfixToPostfixCache.set(infix, { result, accessTime: Date.now() }); - return result; - } - static ClearCache() { - // Convert the cache to an array and sort by last access time - const sortedCache = Array.from(ShaderDefineExpression._InfixToPostfixCache.entries()).sort((a, b) => a[1].accessTime - b[1].accessTime); - // Remove the least recently accessed half of the cache - for (let i = 0; i < ShaderDefineExpression.InfixToPostfixCacheCleanupSize; i++) { - ShaderDefineExpression._InfixToPostfixCache.delete(sortedCache[i][0]); - } - } -} -/** - * Cache items count limit for the InfixToPostfix cache. - * It uses to improve the performance of the shader compilation. - * For details see PR: https://github.com/BabylonJS/Babylon.js/pull/13936 - */ -ShaderDefineExpression.InfixToPostfixCacheLimitSize = 50000; -/** - * When the cache size is exceeded, a cache cleanup will be triggered - * and the cache will be reduced by the size specified - * in the InfixToPostfixCacheCleanupSize variable, removing entries - * that have not been accessed the longest. - */ -ShaderDefineExpression.InfixToPostfixCacheCleanupSize = 25000; -ShaderDefineExpression._InfixToPostfixCache = new Map(); -ShaderDefineExpression._OperatorPriority = { - ")": 0, - "(": 1, - "||": 2, - "&&": 3, -}; -ShaderDefineExpression._Stack = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]; -//# sourceMappingURL=shaderDefineExpression.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.js - -/** @internal */ -class ShaderDefineIsDefinedOperator extends ShaderDefineExpression { - constructor(define, not = false) { - super(); - this.define = define; - this.not = not; - } - isTrue(preprocessors) { - let condition = preprocessors[this.define] !== undefined; - if (this.not) { - condition = !condition; - } - return condition; - } -} -//# sourceMappingURL=shaderDefineIsDefinedOperator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineOrOperator.js - -/** @internal */ -class ShaderDefineOrOperator extends ShaderDefineExpression { - isTrue(preprocessors) { - return this.leftOperand.isTrue(preprocessors) || this.rightOperand.isTrue(preprocessors); - } -} -//# sourceMappingURL=shaderDefineOrOperator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineAndOperator.js - -/** @internal */ -class ShaderDefineAndOperator extends ShaderDefineExpression { - isTrue(preprocessors) { - return this.leftOperand.isTrue(preprocessors) && this.rightOperand.isTrue(preprocessors); - } -} -//# sourceMappingURL=shaderDefineAndOperator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.js - -/** @internal */ -class ShaderDefineArithmeticOperator extends ShaderDefineExpression { - constructor(define, operand, testValue) { - super(); - this.define = define; - this.operand = operand; - this.testValue = testValue; - } - isTrue(preprocessors) { - let value = preprocessors[this.define]; - if (value === undefined) { - value = this.define; - } - let condition = false; - const left = parseInt(value); - const right = parseInt(this.testValue); - switch (this.operand) { - case ">": - condition = left > right; - break; - case "<": - condition = left < right; - break; - case "<=": - condition = left <= right; - break; - case ">=": - condition = left >= right; - break; - case "==": - condition = left === right; - break; - case "!=": - condition = left !== right; - break; - } - return condition; - } -} -//# sourceMappingURL=shaderDefineArithmeticOperator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/shaderLanguage.js -/** - * Language of the shader code - */ -var ShaderLanguage; -(function (ShaderLanguage) { - /** language is GLSL (used by WebGL) */ - ShaderLanguage[ShaderLanguage["GLSL"] = 0] = "GLSL"; - /** language is WGSL (used by WebGPU) */ - ShaderLanguage[ShaderLanguage["WGSL"] = 1] = "WGSL"; -})(ShaderLanguage || (ShaderLanguage = {})); -//# sourceMappingURL=shaderLanguage.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/shaderProcessor.js -/* eslint-disable @typescript-eslint/no-unused-vars */ - - - - - - - - - - - -const regexSE = /defined\s*?\((.+?)\)/g; -const regexSERevert = /defined\s*?\[(.+?)\]/g; -const regexShaderInclude = /#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g; -const regexShaderDecl = /__decl__/; -const regexLightX = /light\{X\}.(\w*)/g; -const regexX = /\{X\}/g; -const reusableMatches = []; -/** @internal */ -class ShaderProcessor { - static Initialize(options) { - if (options.processor && options.processor.initializeShaders) { - options.processor.initializeShaders(options.processingContext); - } - } - static Process(sourceCode, options, callback, engine) { - var _a; - if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.preProcessShaderCode) { - sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment); - } - this._ProcessIncludes(sourceCode, options, (codeWithIncludes) => { - if (options.processCodeAfterIncludes) { - codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? "fragment" : "vertex", codeWithIncludes); - } - const migratedCode = this._ProcessShaderConversion(codeWithIncludes, options, engine); - callback(migratedCode, codeWithIncludes); - }); - } - static PreProcess(sourceCode, options, callback, engine) { - var _a; - if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.preProcessShaderCode) { - sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment); - } - this._ProcessIncludes(sourceCode, options, (codeWithIncludes) => { - if (options.processCodeAfterIncludes) { - codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? "fragment" : "vertex", codeWithIncludes); - } - const migratedCode = this._ApplyPreProcessing(codeWithIncludes, options, engine); - callback(migratedCode, codeWithIncludes); - }); - } - static Finalize(vertexCode, fragmentCode, options) { - if (!options.processor || !options.processor.finalizeShaders) { - return { vertexCode, fragmentCode }; - } - return options.processor.finalizeShaders(vertexCode, fragmentCode, options.processingContext); - } - static _ProcessPrecision(source, options) { - var _a; - if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.noPrecision) { - return source; - } - const shouldUseHighPrecisionShader = options.shouldUseHighPrecisionShader; - if (source.indexOf("precision highp float") === -1) { - if (!shouldUseHighPrecisionShader) { - source = "precision mediump float;\n" + source; - } - else { - source = "precision highp float;\n" + source; - } - } - else { - if (!shouldUseHighPrecisionShader) { - // Moving highp to mediump - source = source.replace("precision highp float", "precision mediump float"); - } - } - return source; - } - static _ExtractOperation(expression) { - const regex = /defined\((.+)\)/; - const match = regex.exec(expression); - if (match && match.length) { - return new ShaderDefineIsDefinedOperator(match[1].trim(), expression[0] === "!"); - } - const operators = ["==", "!=", ">=", "<=", "<", ">"]; - let operator = ""; - let indexOperator = 0; - for (operator of operators) { - indexOperator = expression.indexOf(operator); - if (indexOperator > -1) { - break; - } - } - if (indexOperator === -1) { - return new ShaderDefineIsDefinedOperator(expression); - } - const define = expression.substring(0, indexOperator).trim(); - const value = expression.substring(indexOperator + operator.length).trim(); - return new ShaderDefineArithmeticOperator(define, operator, value); - } - static _BuildSubExpression(expression) { - expression = expression.replace(regexSE, "defined[$1]"); - const postfix = ShaderDefineExpression.infixToPostfix(expression); - const stack = []; - for (const c of postfix) { - if (c !== "||" && c !== "&&") { - stack.push(c); - } - else if (stack.length >= 2) { - let v1 = stack[stack.length - 1], v2 = stack[stack.length - 2]; - stack.length -= 2; - const operator = c == "&&" ? new ShaderDefineAndOperator() : new ShaderDefineOrOperator(); - if (typeof v1 === "string") { - v1 = v1.replace(regexSERevert, "defined($1)"); - } - if (typeof v2 === "string") { - v2 = v2.replace(regexSERevert, "defined($1)"); - } - operator.leftOperand = typeof v2 === "string" ? this._ExtractOperation(v2) : v2; - operator.rightOperand = typeof v1 === "string" ? this._ExtractOperation(v1) : v1; - stack.push(operator); - } - } - let result = stack[stack.length - 1]; - if (typeof result === "string") { - result = result.replace(regexSERevert, "defined($1)"); - } - // note: stack.length !== 1 if there was an error in the parsing - return typeof result === "string" ? this._ExtractOperation(result) : result; - } - static _BuildExpression(line, start) { - const node = new ShaderCodeTestNode(); - const command = line.substring(0, start); - let expression = line.substring(start); - expression = expression.substring(0, (expression.indexOf("//") + 1 || expression.length + 1) - 1).trim(); - if (command === "#ifdef") { - node.testExpression = new ShaderDefineIsDefinedOperator(expression); - } - else if (command === "#ifndef") { - node.testExpression = new ShaderDefineIsDefinedOperator(expression, true); - } - else { - node.testExpression = this._BuildSubExpression(expression); - } - return node; - } - static _MoveCursorWithinIf(cursor, rootNode, ifNode) { - let line = cursor.currentLine; - while (this._MoveCursor(cursor, ifNode)) { - line = cursor.currentLine; - const first5 = line.substring(0, 5).toLowerCase(); - if (first5 === "#else") { - const elseNode = new ShaderCodeNode(); - rootNode.children.push(elseNode); - this._MoveCursor(cursor, elseNode); - return; - } - else if (first5 === "#elif") { - const elifNode = this._BuildExpression(line, 5); - rootNode.children.push(elifNode); - ifNode = elifNode; - } - } - } - static _MoveCursor(cursor, rootNode) { - while (cursor.canRead) { - cursor.lineIndex++; - const line = cursor.currentLine; - if (line.indexOf("#") >= 0) { - const matches = ShaderProcessor._MoveCursorRegex.exec(line); - if (matches && matches.length) { - const keyword = matches[0]; - switch (keyword) { - case "#ifdef": { - const newRootNode = new ShaderCodeConditionNode(); - rootNode.children.push(newRootNode); - const ifNode = this._BuildExpression(line, 6); - newRootNode.children.push(ifNode); - this._MoveCursorWithinIf(cursor, newRootNode, ifNode); - break; - } - case "#else": - case "#elif": - return true; - case "#endif": - return false; - case "#ifndef": { - const newRootNode = new ShaderCodeConditionNode(); - rootNode.children.push(newRootNode); - const ifNode = this._BuildExpression(line, 7); - newRootNode.children.push(ifNode); - this._MoveCursorWithinIf(cursor, newRootNode, ifNode); - break; - } - case "#if": { - const newRootNode = new ShaderCodeConditionNode(); - const ifNode = this._BuildExpression(line, 3); - rootNode.children.push(newRootNode); - newRootNode.children.push(ifNode); - this._MoveCursorWithinIf(cursor, newRootNode, ifNode); - break; - } - } - continue; - } - } - const newNode = new ShaderCodeNode(); - newNode.line = line; - rootNode.children.push(newNode); - // Detect additional defines - if (line[0] === "#" && line[1] === "d") { - const split = line.replace(";", "").split(" "); - newNode.additionalDefineKey = split[1]; - if (split.length === 3) { - newNode.additionalDefineValue = split[2]; - } - } - } - return false; - } - static _EvaluatePreProcessors(sourceCode, preprocessors, options) { - const rootNode = new ShaderCodeNode(); - const cursor = new ShaderCodeCursor(); - cursor.lineIndex = -1; - cursor.lines = sourceCode.split("\n"); - // Decompose (We keep it in 2 steps so it is easier to maintain and perf hit is insignificant) - this._MoveCursor(cursor, rootNode); - // Recompose - return rootNode.process(preprocessors, options); - } - static _PreparePreProcessors(options, engine) { - var _a; - const defines = options.defines; - const preprocessors = {}; - for (const define of defines) { - const keyValue = define.replace("#define", "").replace(";", "").trim(); - const split = keyValue.split(" "); - preprocessors[split[0]] = split.length > 1 ? split[1] : ""; - } - if (((_a = options.processor) === null || _a === void 0 ? void 0 : _a.shaderLanguage) === ShaderLanguage.GLSL) { - preprocessors["GL_ES"] = "true"; - } - preprocessors["__VERSION__"] = options.version; - preprocessors[options.platformName] = "true"; - engine._getGlobalDefines(preprocessors); - return preprocessors; - } - static _ProcessShaderConversion(sourceCode, options, engine) { - let preparedSourceCode = this._ProcessPrecision(sourceCode, options); - if (!options.processor) { - return preparedSourceCode; - } - // Already converted - if (options.processor.shaderLanguage === ShaderLanguage.GLSL && preparedSourceCode.indexOf("#version 3") !== -1) { - preparedSourceCode = preparedSourceCode.replace("#version 300 es", ""); - if (!options.processor.parseGLES3) { - return preparedSourceCode; - } - } - const defines = options.defines; - const preprocessors = this._PreparePreProcessors(options, engine); - // General pre processing - if (options.processor.preProcessor) { - preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext); - } - preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options); - // Post processing - if (options.processor.postProcessor) { - preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine); - } - // Inline functions tagged with #define inline - if (engine._features.needShaderCodeInlining) { - preparedSourceCode = engine.inlineShaderCode(preparedSourceCode); - } - return preparedSourceCode; - } - static _ApplyPreProcessing(sourceCode, options, engine) { - var _a, _b; - let preparedSourceCode = sourceCode; - const defines = options.defines; - const preprocessors = this._PreparePreProcessors(options, engine); - // General pre processing - if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.preProcessor) { - preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext); - } - preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options); - // Post processing - if ((_b = options.processor) === null || _b === void 0 ? void 0 : _b.postProcessor) { - preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine); - } - // Inline functions tagged with #define inline - if (engine._features.needShaderCodeInlining) { - preparedSourceCode = engine.inlineShaderCode(preparedSourceCode); - } - return preparedSourceCode; - } - /** @internal */ - static _ProcessIncludes(sourceCode, options, callback) { - reusableMatches.length = 0; - let match; - // stay back-compat to the old matchAll syntax - while ((match = regexShaderInclude.exec(sourceCode)) !== null) { - reusableMatches.push(match); - } - let returnValue = String(sourceCode); - let parts = [sourceCode]; - let keepProcessing = false; - for (const match of reusableMatches) { - let includeFile = match[1]; - // Uniform declaration - if (includeFile.indexOf("__decl__") !== -1) { - includeFile = includeFile.replace(regexShaderDecl, ""); - if (options.supportsUniformBuffers) { - includeFile = includeFile.replace("Vertex", "Ubo").replace("Fragment", "Ubo"); - } - includeFile = includeFile + "Declaration"; - } - if (options.includesShadersStore[includeFile]) { - // Substitution - let includeContent = options.includesShadersStore[includeFile]; - if (match[2]) { - const splits = match[3].split(","); - for (let index = 0; index < splits.length; index += 2) { - const source = new RegExp(splits[index], "g"); - const dest = splits[index + 1]; - includeContent = includeContent.replace(source, dest); - } - } - if (match[4]) { - const indexString = match[5]; - if (indexString.indexOf("..") !== -1) { - const indexSplits = indexString.split(".."); - const minIndex = parseInt(indexSplits[0]); - let maxIndex = parseInt(indexSplits[1]); - let sourceIncludeContent = includeContent.slice(0); - includeContent = ""; - if (isNaN(maxIndex)) { - maxIndex = options.indexParameters[indexSplits[1]]; - } - for (let i = minIndex; i < maxIndex; i++) { - if (!options.supportsUniformBuffers) { - // Ubo replacement - sourceIncludeContent = sourceIncludeContent.replace(regexLightX, (str, p1) => { - return p1 + "{X}"; - }); - } - includeContent += sourceIncludeContent.replace(regexX, i.toString()) + "\n"; - } - } - else { - if (!options.supportsUniformBuffers) { - // Ubo replacement - includeContent = includeContent.replace(regexLightX, (str, p1) => { - return p1 + "{X}"; - }); - } - includeContent = includeContent.replace(regexX, indexString); - } - } - // Replace - // Split all parts on match[0] and intersperse the parts with the include content - const newParts = []; - for (const part of parts) { - const splitPart = part.split(match[0]); - for (let i = 0; i < splitPart.length - 1; i++) { - newParts.push(splitPart[i]); - newParts.push(includeContent); - } - newParts.push(splitPart[splitPart.length - 1]); - } - parts = newParts; - keepProcessing = keepProcessing || includeContent.indexOf("#include<") >= 0 || includeContent.indexOf("#include <") >= 0; - } - else { - const includeShaderUrl = options.shadersRepository + "ShadersInclude/" + includeFile + ".fx"; - ShaderProcessor._FileToolsLoadFile(includeShaderUrl, (fileContent) => { - options.includesShadersStore[includeFile] = fileContent; - this._ProcessIncludes(parts.join(""), options, callback); - }); - return; - } - } - reusableMatches.length = 0; - returnValue = parts.join(""); - if (keepProcessing) { - this._ProcessIncludes(returnValue.toString(), options, callback); - } - else { - callback(returnValue); - } - } - /** - * Loads a file from a url - * @param url url to load - * @param onSuccess callback called when the file successfully loads - * @param onProgress callback called while file is loading (if the server supports this mode) - * @param offlineProvider defines the offline provider for caching - * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer - * @param onError callback called when the file fails to load - * @returns a file request object - * @internal - */ - static _FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { - throw _WarnImport("FileTools"); - } -} -ShaderProcessor._MoveCursorRegex = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/; -//# sourceMappingURL=shaderProcessor.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/shaderStore.js - -/** - * Defines the shader related stores and directory - */ -class ShaderStore { - /** - * Gets the shaders repository path for a given shader language - * @param shaderLanguage the shader language - * @returns the path to the shaders repository - */ - static GetShadersRepository(shaderLanguage = ShaderLanguage.GLSL) { - return shaderLanguage === ShaderLanguage.GLSL ? ShaderStore.ShadersRepository : ShaderStore.ShadersRepositoryWGSL; - } - /** - * Gets the shaders store of a given shader language - * @param shaderLanguage the shader language - * @returns the shaders store - */ - static GetShadersStore(shaderLanguage = ShaderLanguage.GLSL) { - return shaderLanguage === ShaderLanguage.GLSL ? ShaderStore.ShadersStore : ShaderStore.ShadersStoreWGSL; - } - /** - * Gets the include shaders store of a given shader language - * @param shaderLanguage the shader language - * @returns the include shaders store - */ - static GetIncludesShadersStore(shaderLanguage = ShaderLanguage.GLSL) { - return shaderLanguage === ShaderLanguage.GLSL ? ShaderStore.IncludesShadersStore : ShaderStore.IncludesShadersStoreWGSL; - } -} -/** - * Gets or sets the relative url used to load shaders if using the engine in non-minified mode - */ -ShaderStore.ShadersRepository = "src/Shaders/"; -/** - * Store of each shader (The can be looked up using effect.key) - */ -ShaderStore.ShadersStore = {}; -/** - * Store of each included file for a shader (The can be looked up using effect.key) - */ -ShaderStore.IncludesShadersStore = {}; -/** - * Gets or sets the relative url used to load shaders (WGSL) if using the engine in non-minified mode - */ -ShaderStore.ShadersRepositoryWGSL = "src/ShadersWGSL/"; -/** - * Store of each shader (WGSL) - */ -ShaderStore.ShadersStoreWGSL = {}; -/** - * Store of each included file for a shader (WGSL) - */ -ShaderStore.IncludesShadersStoreWGSL = {}; -//# sourceMappingURL=shaderStore.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/effect.js - - - - - - - -/** - * Effect containing vertex and fragment shader that can be executed on an object. - */ -class effect_Effect { - /** - * Gets or sets the relative url used to load shaders if using the engine in non-minified mode - */ - static get ShadersRepository() { - return ShaderStore.ShadersRepository; - } - static set ShadersRepository(repo) { - ShaderStore.ShadersRepository = repo; - } - /** - * Observable that will be called when effect is bound. - */ - get onBindObservable() { - if (!this._onBindObservable) { - this._onBindObservable = new observable_Observable(); - } - return this._onBindObservable; - } - /** - * Instantiates an effect. - * An effect can be used to create/manage/execute vertex and fragment shaders. - * @param baseName Name of the effect. - * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect. - * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect. - * @param samplers List of sampler variables that will be passed to the shader. - * @param engine Engine to be used to render the effect - * @param defines Define statements to be added to the shader. - * @param fallbacks Possible fallbacks for this effect to improve performance when needed. - * @param onCompiled Callback that will be called when the shader is compiled. - * @param onError Callback that will be called if an error occurs during shader compilation. - * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10}) - * @param key Effect Key identifying uniquely compiled shader variants - * @param shaderLanguage the language the shader is written in (default: GLSL) - */ - constructor(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers = null, engine, defines = null, fallbacks = null, onCompiled = null, onError = null, indexParameters, key = "", shaderLanguage = ShaderLanguage.GLSL) { - var _a, _b, _c; - /** - * Name of the effect. - */ - this.name = null; - /** - * String container all the define statements that should be set on the shader. - */ - this.defines = ""; - /** - * Callback that will be called when the shader is compiled. - */ - this.onCompiled = null; - /** - * Callback that will be called if an error occurs during shader compilation. - */ - this.onError = null; - /** - * Callback that will be called when effect is bound. - */ - this.onBind = null; - /** - * Unique ID of the effect. - */ - this.uniqueId = 0; - /** - * Observable that will be called when the shader is compiled. - * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised. - */ - this.onCompileObservable = new observable_Observable(); - /** - * Observable that will be called if an error occurs during shader compilation. - */ - this.onErrorObservable = new observable_Observable(); - /** @internal */ - this._onBindObservable = null; - /** - * @internal - * Specifies if the effect was previously ready - */ - this._wasPreviouslyReady = false; - /** - * @internal - * Forces the code from bindForSubMesh to be fully run the next time it is called - * It is used in frozen mode to make sure the effect is properly rebound when a new effect is created - */ - this._forceRebindOnNextCall = false; - /** - * @internal - * Specifies if the effect was previously using instances - */ - this._wasPreviouslyUsingInstances = null; - this._isDisposed = false; - /** @internal */ - this._bonesComputationForcedToCPU = false; - /** @internal */ - this._uniformBuffersNames = {}; - /** @internal */ - this._multiTarget = false; - this._samplers = {}; - this._isReady = false; - this._compilationError = ""; - this._allFallbacksProcessed = false; - this._uniforms = {}; - /** - * Key for the effect. - * @internal - */ - this._key = ""; - this._fallbacks = null; - this._vertexSourceCodeOverride = ""; - this._fragmentSourceCodeOverride = ""; - this._transformFeedbackVaryings = null; - /** - * Compiled shader to webGL program. - * @internal - */ - this._pipelineContext = null; - /** @internal */ - this._vertexSourceCode = ""; - /** @internal */ - this._fragmentSourceCode = ""; - /** @internal */ - this._vertexSourceCodeBeforeMigration = ""; - /** @internal */ - this._fragmentSourceCodeBeforeMigration = ""; - /** @internal */ - this._rawVertexSourceCode = ""; - /** @internal */ - this._rawFragmentSourceCode = ""; - this.name = baseName; - this._key = key; - let processCodeAfterIncludes = undefined; - let processFinalCode = null; - if (attributesNamesOrOptions.attributes) { - const options = attributesNamesOrOptions; - this._engine = uniformsNamesOrEngine; - this._attributesNames = options.attributes; - this._uniformsNames = options.uniformsNames.concat(options.samplers); - this._samplerList = options.samplers.slice(); - this.defines = options.defines; - this.onError = options.onError; - this.onCompiled = options.onCompiled; - this._fallbacks = options.fallbacks; - this._indexParameters = options.indexParameters; - this._transformFeedbackVaryings = options.transformFeedbackVaryings || null; - this._multiTarget = !!options.multiTarget; - this._shaderLanguage = (_a = options.shaderLanguage) !== null && _a !== void 0 ? _a : ShaderLanguage.GLSL; - if (options.uniformBuffersNames) { - this._uniformBuffersNamesList = options.uniformBuffersNames.slice(); - for (let i = 0; i < options.uniformBuffersNames.length; i++) { - this._uniformBuffersNames[options.uniformBuffersNames[i]] = i; - } - } - processFinalCode = (_b = options.processFinalCode) !== null && _b !== void 0 ? _b : null; - processCodeAfterIncludes = (_c = options.processCodeAfterIncludes) !== null && _c !== void 0 ? _c : undefined; - } - else { - this._engine = engine; - this.defines = defines == null ? "" : defines; - this._uniformsNames = uniformsNamesOrEngine.concat(samplers); - this._samplerList = samplers ? samplers.slice() : []; - this._attributesNames = attributesNamesOrOptions; - this._uniformBuffersNamesList = []; - this._shaderLanguage = shaderLanguage; - this.onError = onError; - this.onCompiled = onCompiled; - this._indexParameters = indexParameters; - this._fallbacks = fallbacks; - } - this._attributeLocationByName = {}; - this.uniqueId = effect_Effect._UniqueIdSeed++; - let vertexSource; - let fragmentSource; - const hostDocument = IsWindowObjectExist() ? this._engine.getHostDocument() : null; - if (baseName.vertexSource) { - vertexSource = "source:" + baseName.vertexSource; - } - else if (baseName.vertexElement) { - vertexSource = hostDocument ? hostDocument.getElementById(baseName.vertexElement) : null; - if (!vertexSource) { - vertexSource = baseName.vertexElement; - } - } - else { - vertexSource = baseName.vertex || baseName; - } - if (baseName.fragmentSource) { - fragmentSource = "source:" + baseName.fragmentSource; - } - else if (baseName.fragmentElement) { - fragmentSource = hostDocument ? hostDocument.getElementById(baseName.fragmentElement) : null; - if (!fragmentSource) { - fragmentSource = baseName.fragmentElement; - } - } - else { - fragmentSource = baseName.fragment || baseName; - } - this._processingContext = this._engine._getShaderProcessingContext(this._shaderLanguage); - let processorOptions = { - defines: this.defines.split("\n"), - indexParameters: this._indexParameters, - isFragment: false, - shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader, - processor: this._engine._getShaderProcessor(this._shaderLanguage), - supportsUniformBuffers: this._engine.supportsUniformBuffers, - shadersRepository: ShaderStore.GetShadersRepository(this._shaderLanguage), - includesShadersStore: ShaderStore.GetIncludesShadersStore(this._shaderLanguage), - version: (this._engine.version * 100).toString(), - platformName: this._engine.shaderPlatformName, - processingContext: this._processingContext, - isNDCHalfZRange: this._engine.isNDCHalfZRange, - useReverseDepthBuffer: this._engine.useReverseDepthBuffer, - processCodeAfterIncludes, - }; - const shaderCodes = [undefined, undefined]; - const shadersLoaded = () => { - if (shaderCodes[0] && shaderCodes[1]) { - processorOptions.isFragment = true; - const [migratedVertexCode, fragmentCode] = shaderCodes; - ShaderProcessor.Process(fragmentCode, processorOptions, (migratedFragmentCode, codeBeforeMigration) => { - this._fragmentSourceCodeBeforeMigration = codeBeforeMigration; - if (processFinalCode) { - migratedFragmentCode = processFinalCode("fragment", migratedFragmentCode); - } - const finalShaders = ShaderProcessor.Finalize(migratedVertexCode, migratedFragmentCode, processorOptions); - processorOptions = null; - this._useFinalCode(finalShaders.vertexCode, finalShaders.fragmentCode, baseName); - }, this._engine); - } - }; - this._loadShader(vertexSource, "Vertex", "", (vertexCode) => { - ShaderProcessor.Initialize(processorOptions); - ShaderProcessor.Process(vertexCode, processorOptions, (migratedVertexCode, codeBeforeMigration) => { - this._rawVertexSourceCode = vertexCode; - this._vertexSourceCodeBeforeMigration = codeBeforeMigration; - if (processFinalCode) { - migratedVertexCode = processFinalCode("vertex", migratedVertexCode); - } - shaderCodes[0] = migratedVertexCode; - shadersLoaded(); - }, this._engine); - }); - this._loadShader(fragmentSource, "Fragment", "Pixel", (fragmentCode) => { - this._rawFragmentSourceCode = fragmentCode; - shaderCodes[1] = fragmentCode; - shadersLoaded(); - }); - } - _useFinalCode(migratedVertexCode, migratedFragmentCode, baseName) { - if (baseName) { - const vertex = baseName.vertexElement || baseName.vertex || baseName.spectorName || baseName; - const fragment = baseName.fragmentElement || baseName.fragment || baseName.spectorName || baseName; - this._vertexSourceCode = (this._shaderLanguage === ShaderLanguage.WGSL ? "//" : "") + "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode; - this._fragmentSourceCode = (this._shaderLanguage === ShaderLanguage.WGSL ? "//" : "") + "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode; - } - else { - this._vertexSourceCode = migratedVertexCode; - this._fragmentSourceCode = migratedFragmentCode; - } - this._prepareEffect(); - } - /** - * Unique key for this effect - */ - get key() { - return this._key; - } - /** - * If the effect has been compiled and prepared. - * @returns if the effect is compiled and prepared. - */ - isReady() { - try { - return this._isReadyInternal(); - } - catch (_a) { - return false; - } - } - _isReadyInternal() { - if (this._isReady) { - return true; - } - if (this._pipelineContext) { - return this._pipelineContext.isReady; - } - return false; - } - /** - * The engine the effect was initialized with. - * @returns the engine. - */ - getEngine() { - return this._engine; - } - /** - * The pipeline context for this effect - * @returns the associated pipeline context - */ - getPipelineContext() { - return this._pipelineContext; - } - /** - * The set of names of attribute variables for the shader. - * @returns An array of attribute names. - */ - getAttributesNames() { - return this._attributesNames; - } - /** - * Returns the attribute at the given index. - * @param index The index of the attribute. - * @returns The location of the attribute. - */ - getAttributeLocation(index) { - return this._attributes[index]; - } - /** - * Returns the attribute based on the name of the variable. - * @param name of the attribute to look up. - * @returns the attribute location. - */ - getAttributeLocationByName(name) { - return this._attributeLocationByName[name]; - } - /** - * The number of attributes. - * @returns the number of attributes. - */ - getAttributesCount() { - return this._attributes.length; - } - /** - * Gets the index of a uniform variable. - * @param uniformName of the uniform to look up. - * @returns the index. - */ - getUniformIndex(uniformName) { - return this._uniformsNames.indexOf(uniformName); - } - /** - * Returns the attribute based on the name of the variable. - * @param uniformName of the uniform to look up. - * @returns the location of the uniform. - */ - getUniform(uniformName) { - return this._uniforms[uniformName]; - } - /** - * Returns an array of sampler variable names - * @returns The array of sampler variable names. - */ - getSamplers() { - return this._samplerList; - } - /** - * Returns an array of uniform variable names - * @returns The array of uniform variable names. - */ - getUniformNames() { - return this._uniformsNames; - } - /** - * Returns an array of uniform buffer variable names - * @returns The array of uniform buffer variable names. - */ - getUniformBuffersNames() { - return this._uniformBuffersNamesList; - } - /** - * Returns the index parameters used to create the effect - * @returns The index parameters object - */ - getIndexParameters() { - return this._indexParameters; - } - /** - * The error from the last compilation. - * @returns the error string. - */ - getCompilationError() { - return this._compilationError; - } - /** - * Gets a boolean indicating that all fallbacks were used during compilation - * @returns true if all fallbacks were used - */ - allFallbacksProcessed() { - return this._allFallbacksProcessed; - } - /** - * Adds a callback to the onCompiled observable and call the callback immediately if already ready. - * @param func The callback to be used. - */ - executeWhenCompiled(func) { - if (this.isReady()) { - func(this); - return; - } - this.onCompileObservable.add((effect) => { - func(effect); - }); - if (!this._pipelineContext || this._pipelineContext.isAsync) { - setTimeout(() => { - this._checkIsReady(null); - }, 16); - } - } - _checkIsReady(previousPipelineContext) { - try { - if (this._isReadyInternal()) { - return; - } - } - catch (e) { - this._processCompilationErrors(e, previousPipelineContext); - return; - } - if (this._isDisposed) { - return; - } - setTimeout(() => { - this._checkIsReady(previousPipelineContext); - }, 16); - } - _loadShader(shader, key, optionalKey, callback) { - if (typeof HTMLElement !== "undefined") { - // DOM element ? - if (shader instanceof HTMLElement) { - const shaderCode = GetDOMTextContent(shader); - callback(shaderCode); - return; - } - } - // Direct source ? - if (shader.substr(0, 7) === "source:") { - callback(shader.substr(7)); - return; - } - // Base64 encoded ? - if (shader.substr(0, 7) === "base64:") { - const shaderBinary = window.atob(shader.substr(7)); - callback(shaderBinary); - return; - } - const shaderStore = ShaderStore.GetShadersStore(this._shaderLanguage); - // Is in local store ? - if (shaderStore[shader + key + "Shader"]) { - callback(shaderStore[shader + key + "Shader"]); - return; - } - if (optionalKey && shaderStore[shader + optionalKey + "Shader"]) { - callback(shaderStore[shader + optionalKey + "Shader"]); - return; - } - let shaderUrl; - if (shader[0] === "." || shader[0] === "/" || shader.indexOf("http") > -1) { - shaderUrl = shader; - } - else { - shaderUrl = ShaderStore.GetShadersRepository(this._shaderLanguage) + shader; - } - // Vertex shader - this._engine._loadFile(shaderUrl + "." + key.toLowerCase() + ".fx", callback); - } - /** - * Gets the vertex shader source code of this effect - * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc) - */ - get vertexSourceCode() { - var _a, _b; - return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride - ? this._vertexSourceCodeOverride - : (_b = (_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getVertexShaderCode()) !== null && _b !== void 0 ? _b : this._vertexSourceCode; - } - /** - * Gets the fragment shader source code of this effect - * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc) - */ - get fragmentSourceCode() { - var _a, _b; - return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride - ? this._fragmentSourceCodeOverride - : (_b = (_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getFragmentShaderCode()) !== null && _b !== void 0 ? _b : this._fragmentSourceCode; - } - /** - * Gets the vertex shader source code before migration. - * 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. - * 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). - */ - get vertexSourceCodeBeforeMigration() { - return this._vertexSourceCodeBeforeMigration; - } - /** - * Gets the fragment shader source code before migration. - * 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. - * 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). - */ - get fragmentSourceCodeBeforeMigration() { - return this._fragmentSourceCodeBeforeMigration; - } - /** - * Gets the vertex shader source code before it has been modified by any processing - */ - get rawVertexSourceCode() { - return this._rawVertexSourceCode; - } - /** - * Gets the fragment shader source code before it has been modified by any processing - */ - get rawFragmentSourceCode() { - return this._rawFragmentSourceCode; - } - /** - * Recompiles the webGL program - * @param vertexSourceCode The source code for the vertex shader. - * @param fragmentSourceCode The source code for the fragment shader. - * @param onCompiled Callback called when completed. - * @param onError Callback called on error. - * @internal - */ - _rebuildProgram(vertexSourceCode, fragmentSourceCode, onCompiled, onError) { - this._isReady = false; - this._vertexSourceCodeOverride = vertexSourceCode; - this._fragmentSourceCodeOverride = fragmentSourceCode; - this.onError = (effect, error) => { - if (onError) { - onError(error); - } - }; - this.onCompiled = () => { - const scenes = this.getEngine().scenes; - if (scenes) { - for (let i = 0; i < scenes.length; i++) { - scenes[i].markAllMaterialsAsDirty(63); - } - } - this._pipelineContext._handlesSpectorRebuildCallback(onCompiled); - }; - this._fallbacks = null; - this._prepareEffect(); - } - /** - * Prepares the effect - * @internal - */ - _prepareEffect() { - const attributesNames = this._attributesNames; - const defines = this.defines; - const previousPipelineContext = this._pipelineContext; - this._isReady = false; - try { - const engine = this._engine; - this._pipelineContext = engine.createPipelineContext(this._processingContext); - this._pipelineContext._name = this._key; - const rebuildRebind = this._rebuildProgram.bind(this); - if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) { - engine._preparePipelineContext(this._pipelineContext, this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, true, this._rawVertexSourceCode, this._rawFragmentSourceCode, rebuildRebind, null, this._transformFeedbackVaryings, this._key); - } - else { - engine._preparePipelineContext(this._pipelineContext, this._vertexSourceCode, this._fragmentSourceCode, false, this._rawVertexSourceCode, this._rawFragmentSourceCode, rebuildRebind, defines, this._transformFeedbackVaryings, this._key); - } - engine._executeWhenRenderingStateIsCompiled(this._pipelineContext, () => { - this._attributes = []; - this._pipelineContext._fillEffectInformation(this, this._uniformBuffersNames, this._uniformsNames, this._uniforms, this._samplerList, this._samplers, attributesNames, this._attributes); - // Caches attribute locations. - if (attributesNames) { - for (let i = 0; i < attributesNames.length; i++) { - const name = attributesNames[i]; - this._attributeLocationByName[name] = this._attributes[i]; - } - } - engine.bindSamplers(this); - this._compilationError = ""; - this._isReady = true; - if (this.onCompiled) { - this.onCompiled(this); - } - this.onCompileObservable.notifyObservers(this); - this.onCompileObservable.clear(); - // Unbind mesh reference in fallbacks - if (this._fallbacks) { - this._fallbacks.unBindMesh(); - } - if (previousPipelineContext) { - this.getEngine()._deletePipelineContext(previousPipelineContext); - } - }); - if (this._pipelineContext.isAsync) { - this._checkIsReady(previousPipelineContext); - } - } - catch (e) { - this._processCompilationErrors(e, previousPipelineContext); - } - } - _getShaderCodeAndErrorLine(code, error, isFragment) { - const regexp = isFragment ? /FRAGMENT SHADER ERROR: 0:(\d+?):/ : /VERTEX SHADER ERROR: 0:(\d+?):/; - let errorLine = null; - if (error && code) { - const res = error.match(regexp); - if (res && res.length === 2) { - const lineNumber = parseInt(res[1]); - const lines = code.split("\n", -1); - if (lines.length >= lineNumber) { - errorLine = `Offending line [${lineNumber}] in ${isFragment ? "fragment" : "vertex"} code: ${lines[lineNumber - 1]}`; - } - } - } - return [code, errorLine]; - } - _processCompilationErrors(e, previousPipelineContext = null) { - var _a, _b, _c; - this._compilationError = e.message; - const attributesNames = this._attributesNames; - const fallbacks = this._fallbacks; - // Let's go through fallbacks then - logger_Logger.Error("Unable to compile effect:"); - logger_Logger.Error("Uniforms: " + - this._uniformsNames.map(function (uniform) { - return " " + uniform; - })); - logger_Logger.Error("Attributes: " + - attributesNames.map(function (attribute) { - return " " + attribute; - })); - logger_Logger.Error("Defines:\n" + this.defines); - if (effect_Effect.LogShaderCodeOnCompilationError) { - let lineErrorVertex = null, lineErrorFragment = null, code = null; - if ((_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getVertexShaderCode()) { - [code, lineErrorVertex] = this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(), this._compilationError, false); - if (code) { - logger_Logger.Error("Vertex code:"); - logger_Logger.Error(code); - } - } - if ((_b = this._pipelineContext) === null || _b === void 0 ? void 0 : _b._getFragmentShaderCode()) { - [code, lineErrorFragment] = this._getShaderCodeAndErrorLine((_c = this._pipelineContext) === null || _c === void 0 ? void 0 : _c._getFragmentShaderCode(), this._compilationError, true); - if (code) { - logger_Logger.Error("Fragment code:"); - logger_Logger.Error(code); - } - } - if (lineErrorVertex) { - logger_Logger.Error(lineErrorVertex); - } - if (lineErrorFragment) { - logger_Logger.Error(lineErrorFragment); - } - } - logger_Logger.Error("Error: " + this._compilationError); - const notifyErrors = () => { - if (this.onError) { - this.onError(this, this._compilationError); - } - this.onErrorObservable.notifyObservers(this); - }; - // In case a previous compilation was successful, we need to restore the previous pipeline context - if (previousPipelineContext) { - this._pipelineContext = previousPipelineContext; - this._isReady = true; - notifyErrors(); - } - // Lets try to compile fallbacks as long as we have some. - if (fallbacks) { - this._pipelineContext = null; - if (fallbacks.hasMoreFallbacks) { - this._allFallbacksProcessed = false; - logger_Logger.Error("Trying next fallback."); - this.defines = fallbacks.reduce(this.defines, this); - this._prepareEffect(); - } - else { - // Sorry we did everything we can - this._allFallbacksProcessed = true; - notifyErrors(); - this.onErrorObservable.clear(); - // Unbind mesh reference in fallbacks - if (this._fallbacks) { - this._fallbacks.unBindMesh(); - } - } - } - else { - this._allFallbacksProcessed = true; - // In case of error, without any prior successful compilation, let s notify observers - if (!previousPipelineContext) { - notifyErrors(); - } - } - } - /** - * Checks if the effect is supported. (Must be called after compilation) - */ - get isSupported() { - return this._compilationError === ""; - } - /** - * Binds a texture to the engine to be used as output of the shader. - * @param channel Name of the output variable. - * @param texture Texture to bind. - * @internal - */ - _bindTexture(channel, texture) { - this._engine._bindTexture(this._samplers[channel], texture, channel); - } - /** - * Sets a texture on the engine to be used in the shader. - * @param channel Name of the sampler variable. - * @param texture Texture to set. - */ - setTexture(channel, texture) { - this._engine.setTexture(this._samplers[channel], this._uniforms[channel], texture, channel); - } - /** - * Sets a depth stencil texture from a render target on the engine to be used in the shader. - * @param channel Name of the sampler variable. - * @param texture Texture to set. - */ - setDepthStencilTexture(channel, texture) { - this._engine.setDepthStencilTexture(this._samplers[channel], this._uniforms[channel], texture, channel); - } - /** - * Sets an array of textures on the engine to be used in the shader. - * @param channel Name of the variable. - * @param textures Textures to set. - */ - setTextureArray(channel, textures) { - const exName = channel + "Ex"; - if (this._samplerList.indexOf(exName + "0") === -1) { - const initialPos = this._samplerList.indexOf(channel); - for (let index = 1; index < textures.length; index++) { - const currentExName = exName + (index - 1).toString(); - this._samplerList.splice(initialPos + index, 0, currentExName); - } - // Reset every channels - let channelIndex = 0; - for (const key of this._samplerList) { - this._samplers[key] = channelIndex; - channelIndex += 1; - } - } - this._engine.setTextureArray(this._samplers[channel], this._uniforms[channel], textures, channel); - } - /** - * 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) - * @param channel Name of the sampler variable. - * @param postProcess Post process to get the input texture from. - */ - setTextureFromPostProcess(channel, postProcess) { - this._engine.setTextureFromPostProcess(this._samplers[channel], postProcess, channel); - } - /** - * (Warning! setTextureFromPostProcessOutput may be desired instead) - * 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) - * @param channel Name of the sampler variable. - * @param postProcess Post process to get the output texture from. - */ - setTextureFromPostProcessOutput(channel, postProcess) { - this._engine.setTextureFromPostProcessOutput(this._samplers[channel], postProcess, channel); - } - /** - * Binds a buffer to a uniform. - * @param buffer Buffer to bind. - * @param name Name of the uniform variable to bind to. - */ - bindUniformBuffer(buffer, name) { - const bufferName = this._uniformBuffersNames[name]; - if (bufferName === undefined || (effect_Effect._BaseCache[bufferName] === buffer && this._engine._features.useUBOBindingCache)) { - return; - } - effect_Effect._BaseCache[bufferName] = buffer; - this._engine.bindUniformBufferBase(buffer, bufferName, name); - } - /** - * Binds block to a uniform. - * @param blockName Name of the block to bind. - * @param index Index to bind. - */ - bindUniformBlock(blockName, index) { - this._engine.bindUniformBlock(this._pipelineContext, blockName, index); - } - /** - * Sets an integer value on a uniform variable. - * @param uniformName Name of the variable. - * @param value Value to be set. - * @returns this effect. - */ - setInt(uniformName, value) { - this._pipelineContext.setInt(uniformName, value); - return this; - } - /** - * Sets an int2 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int2. - * @param y Second int in int2. - * @returns this effect. - */ - setInt2(uniformName, x, y) { - this._pipelineContext.setInt2(uniformName, x, y); - return this; - } - /** - * Sets an int3 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int3. - * @param y Second int in int3. - * @param z Third int in int3. - * @returns this effect. - */ - setInt3(uniformName, x, y, z) { - this._pipelineContext.setInt3(uniformName, x, y, z); - return this; - } - /** - * Sets an int4 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int4. - * @param y Second int in int4. - * @param z Third int in int4. - * @param w Fourth int in int4. - * @returns this effect. - */ - setInt4(uniformName, x, y, z, w) { - this._pipelineContext.setInt4(uniformName, x, y, z, w); - return this; - } - /** - * Sets an int array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setIntArray(uniformName, array) { - this._pipelineContext.setIntArray(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setIntArray2(uniformName, array) { - this._pipelineContext.setIntArray2(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setIntArray3(uniformName, array) { - this._pipelineContext.setIntArray3(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setIntArray4(uniformName, array) { - this._pipelineContext.setIntArray4(uniformName, array); - return this; - } - /** - * Sets an unsigned integer value on a uniform variable. - * @param uniformName Name of the variable. - * @param value Value to be set. - * @returns this effect. - */ - setUInt(uniformName, value) { - this._pipelineContext.setInt(uniformName, value); - return this; - } - /** - * Sets an unsigned int2 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint2. - * @param y Second unsigned int in uint2. - * @returns this effect. - */ - setUInt2(uniformName, x, y) { - this._pipelineContext.setInt2(uniformName, x, y); - return this; - } - /** - * Sets an unsigned int3 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint3. - * @param y Second unsigned int in uint3. - * @param z Third unsigned int in uint3. - * @returns this effect. - */ - setUInt3(uniformName, x, y, z) { - this._pipelineContext.setInt3(uniformName, x, y, z); - return this; - } - /** - * Sets an unsigned int4 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint4. - * @param y Second unsigned int in uint4. - * @param z Third unsigned int in uint4. - * @param w Fourth unsigned int in uint4. - * @returns this effect. - */ - setUInt4(uniformName, x, y, z, w) { - this._pipelineContext.setInt4(uniformName, x, y, z, w); - return this; - } - /** - * Sets an unsigned int array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setUIntArray(uniformName, array) { - this._pipelineContext.setUIntArray(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setUIntArray2(uniformName, array) { - this._pipelineContext.setUIntArray2(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setUIntArray3(uniformName, array) { - this._pipelineContext.setUIntArray3(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setUIntArray4(uniformName, array) { - this._pipelineContext.setUIntArray4(uniformName, array); - return this; - } - /** - * Sets an float array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setFloatArray(uniformName, array) { - this._pipelineContext.setArray(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setFloatArray2(uniformName, array) { - this._pipelineContext.setArray2(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setFloatArray3(uniformName, array) { - this._pipelineContext.setArray3(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setFloatArray4(uniformName, array) { - this._pipelineContext.setArray4(uniformName, array); - return this; - } - /** - * Sets an array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setArray(uniformName, array) { - this._pipelineContext.setArray(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setArray2(uniformName, array) { - this._pipelineContext.setArray2(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setArray3(uniformName, array) { - this._pipelineContext.setArray3(uniformName, array); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setArray4(uniformName, array) { - this._pipelineContext.setArray4(uniformName, array); - return this; - } - /** - * Sets matrices on a uniform variable. - * @param uniformName Name of the variable. - * @param matrices matrices to be set. - * @returns this effect. - */ - setMatrices(uniformName, matrices) { - this._pipelineContext.setMatrices(uniformName, matrices); - return this; - } - /** - * Sets matrix on a uniform variable. - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - * @returns this effect. - */ - setMatrix(uniformName, matrix) { - this._pipelineContext.setMatrix(uniformName, matrix); - return this; - } - /** - * 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) - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - * @returns this effect. - */ - setMatrix3x3(uniformName, matrix) { - // the cast is ok because it is gl.uniformMatrix3fv() which is called at the end, and this function accepts Float32Array and Array<number> - this._pipelineContext.setMatrix3x3(uniformName, matrix); - return this; - } - /** - * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix) - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - * @returns this effect. - */ - setMatrix2x2(uniformName, matrix) { - // the cast is ok because it is gl.uniformMatrix3fv() which is called at the end, and this function accepts Float32Array and Array<number> - this._pipelineContext.setMatrix2x2(uniformName, matrix); - return this; - } - /** - * Sets a float on a uniform variable. - * @param uniformName Name of the variable. - * @param value value to be set. - * @returns this effect. - */ - setFloat(uniformName, value) { - this._pipelineContext.setFloat(uniformName, value); - return this; - } - /** - * Sets a boolean on a uniform variable. - * @param uniformName Name of the variable. - * @param bool value to be set. - * @returns this effect. - */ - setBool(uniformName, bool) { - this._pipelineContext.setInt(uniformName, bool ? 1 : 0); - return this; - } - /** - * Sets a Vector2 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector2 vector2 to be set. - * @returns this effect. - */ - setVector2(uniformName, vector2) { - this._pipelineContext.setVector2(uniformName, vector2); - return this; - } - /** - * Sets a float2 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float2. - * @param y Second float in float2. - * @returns this effect. - */ - setFloat2(uniformName, x, y) { - this._pipelineContext.setFloat2(uniformName, x, y); - return this; - } - /** - * Sets a Vector3 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector3 Value to be set. - * @returns this effect. - */ - setVector3(uniformName, vector3) { - this._pipelineContext.setVector3(uniformName, vector3); - return this; - } - /** - * Sets a float3 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float3. - * @param y Second float in float3. - * @param z Third float in float3. - * @returns this effect. - */ - setFloat3(uniformName, x, y, z) { - this._pipelineContext.setFloat3(uniformName, x, y, z); - return this; - } - /** - * Sets a Vector4 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector4 Value to be set. - * @returns this effect. - */ - setVector4(uniformName, vector4) { - this._pipelineContext.setVector4(uniformName, vector4); - return this; - } - /** - * Sets a Quaternion on a uniform variable. - * @param uniformName Name of the variable. - * @param quaternion Value to be set. - * @returns this effect. - */ - setQuaternion(uniformName, quaternion) { - this._pipelineContext.setQuaternion(uniformName, quaternion); - return this; - } - /** - * Sets a float4 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float4. - * @param y Second float in float4. - * @param z Third float in float4. - * @param w Fourth float in float4. - * @returns this effect. - */ - setFloat4(uniformName, x, y, z, w) { - this._pipelineContext.setFloat4(uniformName, x, y, z, w); - return this; - } - /** - * Sets a Color3 on a uniform variable. - * @param uniformName Name of the variable. - * @param color3 Value to be set. - * @returns this effect. - */ - setColor3(uniformName, color3) { - this._pipelineContext.setColor3(uniformName, color3); - return this; - } - /** - * Sets a Color4 on a uniform variable. - * @param uniformName Name of the variable. - * @param color3 Value to be set. - * @param alpha Alpha value to be set. - * @returns this effect. - */ - setColor4(uniformName, color3, alpha) { - this._pipelineContext.setColor4(uniformName, color3, alpha); - return this; - } - /** - * Sets a Color4 on a uniform variable - * @param uniformName defines the name of the variable - * @param color4 defines the value to be set - * @returns this effect. - */ - setDirectColor4(uniformName, color4) { - this._pipelineContext.setDirectColor4(uniformName, color4); - return this; - } - /** - * Release all associated resources. - **/ - dispose() { - if (this._pipelineContext) { - this._pipelineContext.dispose(); - } - this._engine._releaseEffect(this); - this._isDisposed = true; - } - /** - * This function will add a new shader to the shader store - * @param name the name of the shader - * @param pixelShader optional pixel shader content - * @param vertexShader optional vertex shader content - * @param shaderLanguage the language the shader is written in (default: GLSL) - */ - static RegisterShader(name, pixelShader, vertexShader, shaderLanguage = ShaderLanguage.GLSL) { - if (pixelShader) { - ShaderStore.GetShadersStore(shaderLanguage)[`${name}PixelShader`] = pixelShader; - } - if (vertexShader) { - ShaderStore.GetShadersStore(shaderLanguage)[`${name}VertexShader`] = vertexShader; - } - } - /** - * Resets the cache of effects. - */ - static ResetCache() { - effect_Effect._BaseCache = {}; - } -} -/** - * Enable logging of the shader code when a compilation error occurs - */ -effect_Effect.LogShaderCodeOnCompilationError = true; -effect_Effect._UniqueIdSeed = 0; -effect_Effect._BaseCache = {}; -/** - * Store of each shader (The can be looked up using effect.key) - */ -effect_Effect.ShadersStore = ShaderStore.ShadersStore; -/** - * Store of each included file for a shader (The can be looked up using effect.key) - */ -effect_Effect.IncludesShadersStore = ShaderStore.IncludesShadersStore; -//# sourceMappingURL=effect.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/States/depthCullingState.js -/** - * @internal - **/ -class DepthCullingState { - /** - * Initializes the state. - * @param reset - */ - constructor(reset = true) { - this._isDepthTestDirty = false; - this._isDepthMaskDirty = false; - this._isDepthFuncDirty = false; - this._isCullFaceDirty = false; - this._isCullDirty = false; - this._isZOffsetDirty = false; - this._isFrontFaceDirty = false; - if (reset) { - this.reset(); - } - } - get isDirty() { - return (this._isDepthFuncDirty || - this._isDepthTestDirty || - this._isDepthMaskDirty || - this._isCullFaceDirty || - this._isCullDirty || - this._isZOffsetDirty || - this._isFrontFaceDirty); - } - get zOffset() { - return this._zOffset; - } - set zOffset(value) { - if (this._zOffset === value) { - return; - } - this._zOffset = value; - this._isZOffsetDirty = true; - } - get zOffsetUnits() { - return this._zOffsetUnits; - } - set zOffsetUnits(value) { - if (this._zOffsetUnits === value) { - return; - } - this._zOffsetUnits = value; - this._isZOffsetDirty = true; - } - get cullFace() { - return this._cullFace; - } - set cullFace(value) { - if (this._cullFace === value) { - return; - } - this._cullFace = value; - this._isCullFaceDirty = true; - } - get cull() { - return this._cull; - } - set cull(value) { - if (this._cull === value) { - return; - } - this._cull = value; - this._isCullDirty = true; - } - get depthFunc() { - return this._depthFunc; - } - set depthFunc(value) { - if (this._depthFunc === value) { - return; - } - this._depthFunc = value; - this._isDepthFuncDirty = true; - } - get depthMask() { - return this._depthMask; - } - set depthMask(value) { - if (this._depthMask === value) { - return; - } - this._depthMask = value; - this._isDepthMaskDirty = true; - } - get depthTest() { - return this._depthTest; - } - set depthTest(value) { - if (this._depthTest === value) { - return; - } - this._depthTest = value; - this._isDepthTestDirty = true; - } - get frontFace() { - return this._frontFace; - } - set frontFace(value) { - if (this._frontFace === value) { - return; - } - this._frontFace = value; - this._isFrontFaceDirty = true; - } - reset() { - this._depthMask = true; - this._depthTest = true; - this._depthFunc = null; - this._cullFace = null; - this._cull = null; - this._zOffset = 0; - this._zOffsetUnits = 0; - this._frontFace = null; - this._isDepthTestDirty = true; - this._isDepthMaskDirty = true; - this._isDepthFuncDirty = false; - this._isCullFaceDirty = false; - this._isCullDirty = false; - this._isZOffsetDirty = true; - this._isFrontFaceDirty = false; - } - apply(gl) { - if (!this.isDirty) { - return; - } - // Cull - if (this._isCullDirty) { - if (this.cull) { - gl.enable(gl.CULL_FACE); - } - else { - gl.disable(gl.CULL_FACE); - } - this._isCullDirty = false; - } - // Cull face - if (this._isCullFaceDirty) { - gl.cullFace(this.cullFace); - this._isCullFaceDirty = false; - } - // Depth mask - if (this._isDepthMaskDirty) { - gl.depthMask(this.depthMask); - this._isDepthMaskDirty = false; - } - // Depth test - if (this._isDepthTestDirty) { - if (this.depthTest) { - gl.enable(gl.DEPTH_TEST); - } - else { - gl.disable(gl.DEPTH_TEST); - } - this._isDepthTestDirty = false; - } - // Depth func - if (this._isDepthFuncDirty) { - gl.depthFunc(this.depthFunc); - this._isDepthFuncDirty = false; - } - // zOffset - if (this._isZOffsetDirty) { - if (this.zOffset || this.zOffsetUnits) { - gl.enable(gl.POLYGON_OFFSET_FILL); - gl.polygonOffset(this.zOffset, this.zOffsetUnits); - } - else { - gl.disable(gl.POLYGON_OFFSET_FILL); - } - this._isZOffsetDirty = false; - } - // Front face - if (this._isFrontFaceDirty) { - gl.frontFace(this.frontFace); - this._isFrontFaceDirty = false; - } - } -} -//# sourceMappingURL=depthCullingState.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/States/stencilState.js - -/** - * @internal - **/ -class StencilState { - constructor() { - this.reset(); - } - reset() { - this.enabled = false; - this.mask = 0xff; - this.func = StencilState.ALWAYS; - this.funcRef = 1; - this.funcMask = 0xff; - this.opStencilFail = StencilState.KEEP; - this.opDepthFail = StencilState.KEEP; - this.opStencilDepthPass = StencilState.REPLACE; - } - get stencilFunc() { - return this.func; - } - set stencilFunc(value) { - this.func = value; - } - get stencilFuncRef() { - return this.funcRef; - } - set stencilFuncRef(value) { - this.funcRef = value; - } - get stencilFuncMask() { - return this.funcMask; - } - set stencilFuncMask(value) { - this.funcMask = value; - } - get stencilOpStencilFail() { - return this.opStencilFail; - } - set stencilOpStencilFail(value) { - this.opStencilFail = value; - } - get stencilOpDepthFail() { - return this.opDepthFail; - } - set stencilOpDepthFail(value) { - this.opDepthFail = value; - } - get stencilOpStencilDepthPass() { - return this.opStencilDepthPass; - } - set stencilOpStencilDepthPass(value) { - this.opStencilDepthPass = value; - } - get stencilMask() { - return this.mask; - } - set stencilMask(value) { - this.mask = value; - } - get stencilTest() { - return this.enabled; - } - set stencilTest(value) { - this.enabled = value; - } -} -/** 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 */ -StencilState.ALWAYS = 519; -/** Passed to stencilOperation to specify that stencil value must be kept */ -StencilState.KEEP = 7680; -/** Passed to stencilOperation to specify that stencil value must be replaced */ -StencilState.REPLACE = 7681; -//# sourceMappingURL=stencilState.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/States/alphaCullingState.js -/** - * @internal - **/ -class AlphaState { - /** - * Initializes the state. - */ - constructor() { - this._blendFunctionParameters = new Array(4); - this._blendEquationParameters = new Array(2); - this._blendConstants = new Array(4); - this._isBlendConstantsDirty = false; - this._alphaBlend = false; - this._isAlphaBlendDirty = false; - this._isBlendFunctionParametersDirty = false; - this._isBlendEquationParametersDirty = false; - this.reset(); - } - get isDirty() { - return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty || this._isBlendEquationParametersDirty; - } - get alphaBlend() { - return this._alphaBlend; - } - set alphaBlend(value) { - if (this._alphaBlend === value) { - return; - } - this._alphaBlend = value; - this._isAlphaBlendDirty = true; - } - setAlphaBlendConstants(r, g, b, a) { - if (this._blendConstants[0] === r && this._blendConstants[1] === g && this._blendConstants[2] === b && this._blendConstants[3] === a) { - return; - } - this._blendConstants[0] = r; - this._blendConstants[1] = g; - this._blendConstants[2] = b; - this._blendConstants[3] = a; - this._isBlendConstantsDirty = true; - } - setAlphaBlendFunctionParameters(value0, value1, value2, value3) { - if (this._blendFunctionParameters[0] === value0 && - this._blendFunctionParameters[1] === value1 && - this._blendFunctionParameters[2] === value2 && - this._blendFunctionParameters[3] === value3) { - return; - } - this._blendFunctionParameters[0] = value0; - this._blendFunctionParameters[1] = value1; - this._blendFunctionParameters[2] = value2; - this._blendFunctionParameters[3] = value3; - this._isBlendFunctionParametersDirty = true; - } - setAlphaEquationParameters(rgb, alpha) { - if (this._blendEquationParameters[0] === rgb && this._blendEquationParameters[1] === alpha) { - return; - } - this._blendEquationParameters[0] = rgb; - this._blendEquationParameters[1] = alpha; - this._isBlendEquationParametersDirty = true; - } - reset() { - this._alphaBlend = false; - this._blendFunctionParameters[0] = null; - this._blendFunctionParameters[1] = null; - this._blendFunctionParameters[2] = null; - this._blendFunctionParameters[3] = null; - this._blendEquationParameters[0] = null; - this._blendEquationParameters[1] = null; - this._blendConstants[0] = null; - this._blendConstants[1] = null; - this._blendConstants[2] = null; - this._blendConstants[3] = null; - this._isAlphaBlendDirty = true; - this._isBlendFunctionParametersDirty = false; - this._isBlendEquationParametersDirty = false; - this._isBlendConstantsDirty = false; - } - apply(gl) { - if (!this.isDirty) { - return; - } - // Alpha blend - if (this._isAlphaBlendDirty) { - if (this._alphaBlend) { - gl.enable(gl.BLEND); - } - else { - gl.disable(gl.BLEND); - } - this._isAlphaBlendDirty = false; - } - // Alpha function - if (this._isBlendFunctionParametersDirty) { - gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]); - this._isBlendFunctionParametersDirty = false; - } - // Alpha equation - if (this._isBlendEquationParametersDirty) { - gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]); - this._isBlendEquationParametersDirty = false; - } - // Constants - if (this._isBlendConstantsDirty) { - gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]); - this._isBlendConstantsDirty = false; - } - } -} -//# sourceMappingURL=alphaCullingState.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/textureSampler.js - -/** - * Class used to store a texture sampler data - */ -class TextureSampler { - /** - * | Value | Type | Description | - * | ----- | ------------------ | ----------- | - * | 0 | CLAMP_ADDRESSMODE | | - * | 1 | WRAP_ADDRESSMODE | | - * | 2 | MIRROR_ADDRESSMODE | | - */ - get wrapU() { - return this._cachedWrapU; - } - set wrapU(value) { - this._cachedWrapU = value; - } - /** - * | Value | Type | Description | - * | ----- | ------------------ | ----------- | - * | 0 | CLAMP_ADDRESSMODE | | - * | 1 | WRAP_ADDRESSMODE | | - * | 2 | MIRROR_ADDRESSMODE | | - */ - get wrapV() { - return this._cachedWrapV; - } - set wrapV(value) { - this._cachedWrapV = value; - } - /** - * | Value | Type | Description | - * | ----- | ------------------ | ----------- | - * | 0 | CLAMP_ADDRESSMODE | | - * | 1 | WRAP_ADDRESSMODE | | - * | 2 | MIRROR_ADDRESSMODE | | - */ - get wrapR() { - return this._cachedWrapR; - } - set wrapR(value) { - this._cachedWrapR = value; - } - /** - * With compliant hardware and browser (supporting anisotropic filtering) - * this defines the level of anisotropic filtering in the texture. - * The higher the better but the slower. - */ - get anisotropicFilteringLevel() { - return this._cachedAnisotropicFilteringLevel; - } - set anisotropicFilteringLevel(value) { - this._cachedAnisotropicFilteringLevel = value; - } - /** - * Gets or sets the comparison function (513, 514, etc). Set 0 to not use a comparison function - */ - get comparisonFunction() { - return this._comparisonFunction; - } - set comparisonFunction(value) { - this._comparisonFunction = value; - } - /** - * Indicates to use the mip maps (if available on the texture). - * 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!) - */ - get useMipMaps() { - return this._useMipMaps; - } - set useMipMaps(value) { - this._useMipMaps = value; - } - /** - * Creates a Sampler instance - */ - constructor() { - /** - * Gets the sampling mode of the texture - */ - this.samplingMode = -1; - this._useMipMaps = true; - /** @internal */ - this._cachedWrapU = null; - /** @internal */ - this._cachedWrapV = null; - /** @internal */ - this._cachedWrapR = null; - /** @internal */ - this._cachedAnisotropicFilteringLevel = null; - /** @internal */ - this._comparisonFunction = 0; - } - /** - * Sets all the parameters of the sampler - * @param wrapU u address mode (default: TEXTURE_WRAP_ADDRESSMODE) - * @param wrapV v address mode (default: TEXTURE_WRAP_ADDRESSMODE) - * @param wrapR r address mode (default: TEXTURE_WRAP_ADDRESSMODE) - * @param anisotropicFilteringLevel anisotropic level (default: 1) - * @param samplingMode sampling mode (default: 2) - * @param comparisonFunction comparison function (default: 0 - no comparison function) - * @returns the current sampler instance - */ - setParameters(wrapU = 1, wrapV = 1, wrapR = 1, anisotropicFilteringLevel = 1, samplingMode = 2, comparisonFunction = 0) { - this._cachedWrapU = wrapU; - this._cachedWrapV = wrapV; - this._cachedWrapR = wrapR; - this._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel; - this.samplingMode = samplingMode; - this._comparisonFunction = comparisonFunction; - return this; - } - /** - * Compares this sampler with another one - * @param other sampler to compare with - * @returns true if the samplers have the same parametres, else false - */ - compareSampler(other) { - return (this._cachedWrapU === other._cachedWrapU && - this._cachedWrapV === other._cachedWrapV && - this._cachedWrapR === other._cachedWrapR && - this._cachedAnisotropicFilteringLevel === other._cachedAnisotropicFilteringLevel && - this.samplingMode === other.samplingMode && - this._comparisonFunction === other._comparisonFunction && - this._useMipMaps === other._useMipMaps); - } -} -//# sourceMappingURL=textureSampler.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/internalTexture.js - - -/** - * Defines the source of the internal texture - */ -var internalTexture_InternalTextureSource; -(function (InternalTextureSource) { - /** - * The source of the texture data is unknown - */ - InternalTextureSource[InternalTextureSource["Unknown"] = 0] = "Unknown"; - /** - * Texture data comes from an URL - */ - InternalTextureSource[InternalTextureSource["Url"] = 1] = "Url"; - /** - * Texture data is only used for temporary storage - */ - InternalTextureSource[InternalTextureSource["Temp"] = 2] = "Temp"; - /** - * Texture data comes from raw data (ArrayBuffer) - */ - InternalTextureSource[InternalTextureSource["Raw"] = 3] = "Raw"; - /** - * Texture content is dynamic (video or dynamic texture) - */ - InternalTextureSource[InternalTextureSource["Dynamic"] = 4] = "Dynamic"; - /** - * Texture content is generated by rendering to it - */ - InternalTextureSource[InternalTextureSource["RenderTarget"] = 5] = "RenderTarget"; - /** - * Texture content is part of a multi render target process - */ - InternalTextureSource[InternalTextureSource["MultiRenderTarget"] = 6] = "MultiRenderTarget"; - /** - * Texture data comes from a cube data file - */ - InternalTextureSource[InternalTextureSource["Cube"] = 7] = "Cube"; - /** - * Texture data comes from a raw cube data - */ - InternalTextureSource[InternalTextureSource["CubeRaw"] = 8] = "CubeRaw"; - /** - * Texture data come from a prefiltered cube data file - */ - InternalTextureSource[InternalTextureSource["CubePrefiltered"] = 9] = "CubePrefiltered"; - /** - * Texture content is raw 3D data - */ - InternalTextureSource[InternalTextureSource["Raw3D"] = 10] = "Raw3D"; - /** - * Texture content is raw 2D array data - */ - InternalTextureSource[InternalTextureSource["Raw2DArray"] = 11] = "Raw2DArray"; - /** - * Texture content is a depth/stencil texture - */ - InternalTextureSource[InternalTextureSource["DepthStencil"] = 12] = "DepthStencil"; - /** - * Texture data comes from a raw cube data encoded with RGBD - */ - InternalTextureSource[InternalTextureSource["CubeRawRGBD"] = 13] = "CubeRawRGBD"; - /** - * Texture content is a depth texture - */ - InternalTextureSource[InternalTextureSource["Depth"] = 14] = "Depth"; -})(internalTexture_InternalTextureSource || (internalTexture_InternalTextureSource = {})); -/** - * Class used to store data associated with WebGL texture data for the engine - * This class should not be used directly - */ -class internalTexture_InternalTexture extends TextureSampler { - /** - * Gets a boolean indicating if the texture uses mipmaps - * TODO implements useMipMaps as a separate setting from generateMipMaps - */ - get useMipMaps() { - return this.generateMipMaps; - } - set useMipMaps(value) { - this.generateMipMaps = value; - } - /** Gets the unique id of the internal texture */ - get uniqueId() { - return this._uniqueId; - } - /** @internal */ - _setUniqueId(id) { - this._uniqueId = id; - } - /** - * Gets the Engine the texture belongs to. - * @returns The babylon engine - */ - getEngine() { - return this._engine; - } - /** - * Gets the data source type of the texture - */ - get source() { - return this._source; - } - /** - * Creates a new InternalTexture - * @param engine defines the engine to use - * @param source defines the type of data that will be used - * @param delayAllocation if the texture allocation should be delayed (default: false) - */ - constructor(engine, source, delayAllocation = false) { - super(); - /** - * Defines if the texture is ready - */ - this.isReady = false; - /** - * Defines if the texture is a cube texture - */ - this.isCube = false; - /** - * Defines if the texture contains 3D data - */ - this.is3D = false; - /** - * Defines if the texture contains 2D array data - */ - this.is2DArray = false; - /** - * Defines if the texture contains multiview data - */ - this.isMultiview = false; - /** - * Gets the URL used to load this texture - */ - this.url = ""; - /** - * Gets a boolean indicating if the texture needs mipmaps generation - */ - this.generateMipMaps = false; - /** - * Gets the number of samples used by the texture (WebGL2+ only) - */ - this.samples = 0; - /** - * Gets the type of the texture (int, float...) - */ - this.type = -1; - /** - * Gets the format of the texture (RGB, RGBA...) - */ - this.format = -1; - /** - * Observable called when the texture is loaded - */ - this.onLoadedObservable = new observable_Observable(); - /** - * Observable called when the texture load is raising an error - */ - this.onErrorObservable = new observable_Observable(); - /** - * If this callback is defined it will be called instead of the default _rebuild function - */ - this.onRebuildCallback = null; - /** - * Gets the width of the texture - */ - this.width = 0; - /** - * Gets the height of the texture - */ - this.height = 0; - /** - * Gets the depth of the texture - */ - this.depth = 0; - /** - * Gets the initial width of the texture (It could be rescaled if the current system does not support non power of two textures) - */ - this.baseWidth = 0; - /** - * Gets the initial height of the texture (It could be rescaled if the current system does not support non power of two textures) - */ - this.baseHeight = 0; - /** - * Gets the initial depth of the texture (It could be rescaled if the current system does not support non power of two textures) - */ - this.baseDepth = 0; - /** - * Gets a boolean indicating if the texture is inverted on Y axis - */ - this.invertY = false; - // Private - /** @internal */ - this._invertVScale = false; - /** @internal */ - this._associatedChannel = -1; - /** @internal */ - this._source = internalTexture_InternalTextureSource.Unknown; - /** @internal */ - this._buffer = null; - /** @internal */ - this._bufferView = null; - /** @internal */ - this._bufferViewArray = null; - /** @internal */ - this._bufferViewArrayArray = null; - /** @internal */ - this._size = 0; - /** @internal */ - this._extension = ""; - /** @internal */ - this._files = null; - /** @internal */ - this._workingCanvas = null; - /** @internal */ - this._workingContext = null; - /** @internal */ - this._cachedCoordinatesMode = null; - /** @internal */ - this._isDisabled = false; - /** @internal */ - this._compression = null; - /** @internal */ - this._sphericalPolynomial = null; - /** @internal */ - this._sphericalPolynomialPromise = null; - /** @internal */ - this._sphericalPolynomialComputed = false; - /** @internal */ - this._lodGenerationScale = 0; - /** @internal */ - this._lodGenerationOffset = 0; - /** @internal */ - this._useSRGBBuffer = false; - // The following three fields helps sharing generated fixed LODs for texture filtering - // In environment not supporting the textureLOD extension like EDGE. They are for internal use only. - // They are at the level of the gl texture to benefit from the cache. - /** @internal */ - this._lodTextureHigh = null; - /** @internal */ - this._lodTextureMid = null; - /** @internal */ - this._lodTextureLow = null; - /** @internal */ - this._isRGBD = false; - /** @internal */ - this._linearSpecularLOD = false; - /** @internal */ - this._irradianceTexture = null; - /** @internal */ - this._hardwareTexture = null; - /** @internal */ - this._maxLodLevel = null; - /** @internal */ - this._references = 1; - /** @internal */ - this._gammaSpace = null; - this._engine = engine; - this._source = source; - this._uniqueId = internalTexture_InternalTexture._Counter++; - if (!delayAllocation) { - this._hardwareTexture = engine._createHardwareTexture(); - } - } - /** - * Increments the number of references (ie. the number of Texture that point to it) - */ - incrementReferences() { - this._references++; - } - /** - * Change the size of the texture (not the size of the content) - * @param width defines the new width - * @param height defines the new height - * @param depth defines the new depth (1 by default) - */ - updateSize(width, height, depth = 1) { - this._engine.updateTextureDimensions(this, width, height, depth); - this.width = width; - this.height = height; - this.depth = depth; - this.baseWidth = width; - this.baseHeight = height; - this.baseDepth = depth; - this._size = width * height * depth; - } - /** @internal */ - _rebuild() { - var _a; - this.isReady = false; - this._cachedCoordinatesMode = null; - this._cachedWrapU = null; - this._cachedWrapV = null; - this._cachedWrapR = null; - this._cachedAnisotropicFilteringLevel = null; - if (this.onRebuildCallback) { - const data = this.onRebuildCallback(this); - const swapAndSetIsReady = (proxyInternalTexture) => { - proxyInternalTexture._swapAndDie(this, false); - this.isReady = data.isReady; - }; - if (data.isAsync) { - data.proxy.then(swapAndSetIsReady); - } - else { - swapAndSetIsReady(data.proxy); - } - return; - } - let proxy; - switch (this.source) { - case internalTexture_InternalTextureSource.Temp: - break; - case internalTexture_InternalTextureSource.Url: - proxy = this._engine.createTexture((_a = this._originalUrl) !== null && _a !== void 0 ? _a : this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, - // Do not use Proxy here as it could be fully synchronous - // and proxy would be undefined. - (temp) => { - temp._swapAndDie(this, false); - this.isReady = true; - }, null, this._buffer, undefined, this.format, this._extension, undefined, undefined, undefined, this._useSRGBBuffer); - return; - case internalTexture_InternalTextureSource.Raw: - 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); - proxy._swapAndDie(this, false); - this.isReady = true; - break; - case internalTexture_InternalTextureSource.Raw3D: - proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type); - proxy._swapAndDie(this, false); - this.isReady = true; - break; - case internalTexture_InternalTextureSource.Raw2DArray: - proxy = this._engine.createRawTexture2DArray(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type); - proxy._swapAndDie(this, false); - this.isReady = true; - break; - case internalTexture_InternalTextureSource.Dynamic: - proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode); - proxy._swapAndDie(this, false); - this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, undefined, undefined, true); - // The engine will make sure to update content so no need to flag it as isReady = true - break; - case internalTexture_InternalTextureSource.Cube: - proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, () => { - proxy._swapAndDie(this, false); - this.isReady = true; - }, null, this.format, this._extension, false, 0, 0, null, undefined, this._useSRGBBuffer); - return; - case internalTexture_InternalTextureSource.CubeRaw: - proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); - proxy._swapAndDie(this, false); - this.isReady = true; - break; - case internalTexture_InternalTextureSource.CubeRawRGBD: - // This case is being handeled by the environment texture tools and is not a part of the rebuild process. - // To use CubeRawRGBD use updateRGBDAsync on the cube texture. - return; - case internalTexture_InternalTextureSource.CubePrefiltered: - proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, (proxy) => { - if (proxy) { - proxy._swapAndDie(this, false); - } - this.isReady = true; - }, null, this.format, this._extension); - proxy._sphericalPolynomial = this._sphericalPolynomial; - return; - } - } - /** - * @internal - */ - _swapAndDie(target, swapAll = true) { - // TODO what about refcount on target? - var _a; - (_a = this._hardwareTexture) === null || _a === void 0 ? void 0 : _a.setUsage(target._source, this.generateMipMaps, this.isCube, this.width, this.height); - target._hardwareTexture = this._hardwareTexture; - if (swapAll) { - target._isRGBD = this._isRGBD; - } - if (this._lodTextureHigh) { - if (target._lodTextureHigh) { - target._lodTextureHigh.dispose(); - } - target._lodTextureHigh = this._lodTextureHigh; - } - if (this._lodTextureMid) { - if (target._lodTextureMid) { - target._lodTextureMid.dispose(); - } - target._lodTextureMid = this._lodTextureMid; - } - if (this._lodTextureLow) { - if (target._lodTextureLow) { - target._lodTextureLow.dispose(); - } - target._lodTextureLow = this._lodTextureLow; - } - if (this._irradianceTexture) { - if (target._irradianceTexture) { - target._irradianceTexture.dispose(); - } - target._irradianceTexture = this._irradianceTexture; - } - const cache = this._engine.getLoadedTexturesCache(); - let index = cache.indexOf(this); - if (index !== -1) { - cache.splice(index, 1); - } - index = cache.indexOf(target); - if (index === -1) { - cache.push(target); - } - } - /** - * Dispose the current allocated resources - */ - dispose() { - this._references--; - this.onLoadedObservable.clear(); - this.onErrorObservable.clear(); - if (this._references === 0) { - this._engine._releaseTexture(this); - this._hardwareTexture = null; - } - } -} -/** @internal */ -internalTexture_InternalTexture._Counter = 0; -//# sourceMappingURL=internalTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGL/webGLShaderProcessors.js - -/** @internal */ -class WebGLShaderProcessor { - constructor() { - this.shaderLanguage = ShaderLanguage.GLSL; - } - postProcessor(code, defines, isFragment, processingContext, engine) { - // Remove extensions - if (!engine.getCaps().drawBuffersExtension) { - // even if enclosed in #if/#endif, IE11 does parse the #extension declaration, so we need to remove it altogether - const regex = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g; - code = code.replace(regex, ""); - } - return code; - } -} -//# sourceMappingURL=webGLShaderProcessors.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGL/webGL2ShaderProcessors.js - -const varyingRegex = /(flat\s)?\s*varying\s*.*/; -/** @internal */ -class WebGL2ShaderProcessor { - constructor() { - this.shaderLanguage = ShaderLanguage.GLSL; - } - attributeProcessor(attribute) { - return attribute.replace("attribute", "in"); - } - varyingCheck(varying, _isFragment) { - return varyingRegex.test(varying); - } - varyingProcessor(varying, isFragment) { - return varying.replace("varying", isFragment ? "in" : "out"); - } - postProcessor(code, defines, isFragment) { - const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1; - // Remove extensions - 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; - code = code.replace(regex, ""); - // Replace instructions - code = code.replace(/texture2D\s*\(/g, "texture("); - if (isFragment) { - const hasOutput = code.search(/layout *\(location *= *0\) *out/g) !== -1; - code = code.replace(/texture2DLodEXT\s*\(/g, "textureLod("); - code = code.replace(/textureCubeLodEXT\s*\(/g, "textureLod("); - code = code.replace(/textureCube\s*\(/g, "texture("); - code = code.replace(/gl_FragDepthEXT/g, "gl_FragDepth"); - code = code.replace(/gl_FragColor/g, "glFragColor"); - code = code.replace(/gl_FragData/g, "glFragData"); - code = code.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension || hasOutput ? "" : "layout(location = 0) out vec4 glFragColor;\n") + "void main("); - } - else { - const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1; - if (hasMultiviewExtension) { - return "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n" + code; - } - } - return code; - } -} -//# sourceMappingURL=webGL2ShaderProcessors.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Buffers/dataBuffer.js -/** - * Class used to store gfx data (like WebGLBuffer) - */ -class dataBuffer_DataBuffer { - /** - * Gets the underlying buffer - */ - get underlyingResource() { - return null; - } - /** - * Constructs the buffer - */ - constructor() { - /** - * Gets or sets the number of objects referencing this buffer - */ - this.references = 0; - /** Gets or sets the size of the underlying buffer */ - this.capacity = 0; - /** - * Gets or sets a boolean indicating if the buffer contains 32bits indices - */ - this.is32Bits = false; - this.uniqueId = dataBuffer_DataBuffer._Counter++; - } -} -dataBuffer_DataBuffer._Counter = 0; -//# sourceMappingURL=dataBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/WebGL/webGLDataBuffer.js - -/** @internal */ -class WebGLDataBuffer extends dataBuffer_DataBuffer { - constructor(resource) { - super(); - this._buffer = resource; - } - get underlyingResource() { - return this._buffer; - } -} -//# sourceMappingURL=webGLDataBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGL/webGLPipelineContext.js -/** @internal */ -class WebGLPipelineContext { - constructor() { - this._valueCache = {}; - this.vertexCompilationError = null; - this.fragmentCompilationError = null; - this.programLinkError = null; - this.programValidationError = null; - /** @internal */ - this._isDisposed = false; - } - get isAsync() { - return this.isParallelCompiled; - } - get isReady() { - if (this.program) { - if (this.isParallelCompiled) { - return this.engine._isRenderingStateCompiled(this); - } - return true; - } - return false; - } - _handlesSpectorRebuildCallback(onCompiled) { - if (onCompiled && this.program) { - onCompiled(this.program); - } - } - _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) { - const engine = this.engine; - if (engine.supportsUniformBuffers) { - for (const name in uniformBuffersNames) { - effect.bindUniformBlock(name, uniformBuffersNames[name]); - } - } - const effectAvailableUniforms = this.engine.getUniforms(this, uniformsNames); - effectAvailableUniforms.forEach((uniform, index) => { - uniforms[uniformsNames[index]] = uniform; - }); - this._uniforms = uniforms; - let index; - for (index = 0; index < samplerList.length; index++) { - const sampler = effect.getUniform(samplerList[index]); - if (sampler == null) { - samplerList.splice(index, 1); - index--; - } - } - samplerList.forEach((name, index) => { - samplers[name] = index; - }); - for (const attr of engine.getAttributes(this, attributesNames)) { - attributes.push(attr); - } - } - /** - * Release all associated resources. - **/ - dispose() { - this._uniforms = {}; - this._isDisposed = true; - } - /** - * @internal - */ - _cacheMatrix(uniformName, matrix) { - const cache = this._valueCache[uniformName]; - const flag = matrix.updateFlag; - if (cache !== undefined && cache === flag) { - return false; - } - this._valueCache[uniformName] = flag; - return true; - } - /** - * @internal - */ - _cacheFloat2(uniformName, x, y) { - let cache = this._valueCache[uniformName]; - if (!cache || cache.length !== 2) { - cache = [x, y]; - this._valueCache[uniformName] = cache; - return true; - } - let changed = false; - if (cache[0] !== x) { - cache[0] = x; - changed = true; - } - if (cache[1] !== y) { - cache[1] = y; - changed = true; - } - return changed; - } - /** - * @internal - */ - _cacheFloat3(uniformName, x, y, z) { - let cache = this._valueCache[uniformName]; - if (!cache || cache.length !== 3) { - cache = [x, y, z]; - this._valueCache[uniformName] = cache; - return true; - } - let changed = false; - if (cache[0] !== x) { - cache[0] = x; - changed = true; - } - if (cache[1] !== y) { - cache[1] = y; - changed = true; - } - if (cache[2] !== z) { - cache[2] = z; - changed = true; - } - return changed; - } - /** - * @internal - */ - _cacheFloat4(uniformName, x, y, z, w) { - let cache = this._valueCache[uniformName]; - if (!cache || cache.length !== 4) { - cache = [x, y, z, w]; - this._valueCache[uniformName] = cache; - return true; - } - let changed = false; - if (cache[0] !== x) { - cache[0] = x; - changed = true; - } - if (cache[1] !== y) { - cache[1] = y; - changed = true; - } - if (cache[2] !== z) { - cache[2] = z; - changed = true; - } - if (cache[3] !== w) { - cache[3] = w; - changed = true; - } - return changed; - } - /** - * Sets an integer value on a uniform variable. - * @param uniformName Name of the variable. - * @param value Value to be set. - */ - setInt(uniformName, value) { - const cache = this._valueCache[uniformName]; - if (cache !== undefined && cache === value) { - return; - } - if (this.engine.setInt(this._uniforms[uniformName], value)) { - this._valueCache[uniformName] = value; - } - } - /** - * Sets a int2 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int2. - * @param y Second int in int2. - */ - setInt2(uniformName, x, y) { - if (this._cacheFloat2(uniformName, x, y)) { - if (!this.engine.setInt2(this._uniforms[uniformName], x, y)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a int3 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int3. - * @param y Second int in int3. - * @param z Third int in int3. - */ - setInt3(uniformName, x, y, z) { - if (this._cacheFloat3(uniformName, x, y, z)) { - if (!this.engine.setInt3(this._uniforms[uniformName], x, y, z)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a int4 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int4. - * @param y Second int in int4. - * @param z Third int in int4. - * @param w Fourth int in int4. - */ - setInt4(uniformName, x, y, z, w) { - if (this._cacheFloat4(uniformName, x, y, z, w)) { - if (!this.engine.setInt4(this._uniforms[uniformName], x, y, z, w)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets an int array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setIntArray(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray2(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setIntArray2(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray3(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setIntArray3(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray4(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setIntArray4(this._uniforms[uniformName], array); - } - /** - * Sets an unsigned integer value on a uniform variable. - * @param uniformName Name of the variable. - * @param value Value to be set. - */ - setUInt(uniformName, value) { - const cache = this._valueCache[uniformName]; - if (cache !== undefined && cache === value) { - return; - } - if (this.engine.setUInt(this._uniforms[uniformName], value)) { - this._valueCache[uniformName] = value; - } - } - /** - * Sets an unsigned int2 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint2. - * @param y Second unsigned int in uint2. - */ - setUInt2(uniformName, x, y) { - if (this._cacheFloat2(uniformName, x, y)) { - if (!this.engine.setUInt2(this._uniforms[uniformName], x, y)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets an unsigned int3 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint3. - * @param y Second unsigned int in uint3. - * @param z Third unsigned int in uint3. - */ - setUInt3(uniformName, x, y, z) { - if (this._cacheFloat3(uniformName, x, y, z)) { - if (!this.engine.setUInt3(this._uniforms[uniformName], x, y, z)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets an unsigned int4 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint4. - * @param y Second unsigned int in uint4. - * @param z Third unsigned int in uint4. - * @param w Fourth unsigned int in uint4. - */ - setUInt4(uniformName, x, y, z, w) { - if (this._cacheFloat4(uniformName, x, y, z, w)) { - if (!this.engine.setUInt4(this._uniforms[uniformName], x, y, z, w)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets an unsigned int array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setUIntArray(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray2(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setUIntArray2(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray3(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setUIntArray3(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray4(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setUIntArray4(this._uniforms[uniformName], array); - } - /** - * Sets an array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setArray(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setArray(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setArray2(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setArray2(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setArray3(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setArray3(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setArray4(uniformName, array) { - this._valueCache[uniformName] = null; - this.engine.setArray4(this._uniforms[uniformName], array); - } - /** - * Sets matrices on a uniform variable. - * @param uniformName Name of the variable. - * @param matrices matrices to be set. - */ - setMatrices(uniformName, matrices) { - if (!matrices) { - return; - } - this._valueCache[uniformName] = null; - this.engine.setMatrices(this._uniforms[uniformName], matrices); - } - /** - * Sets matrix on a uniform variable. - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - */ - setMatrix(uniformName, matrix) { - if (this._cacheMatrix(uniformName, matrix)) { - if (!this.engine.setMatrices(this._uniforms[uniformName], matrix.toArray())) { - this._valueCache[uniformName] = null; - } - } - } - /** - * 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) - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - */ - setMatrix3x3(uniformName, matrix) { - this._valueCache[uniformName] = null; - this.engine.setMatrix3x3(this._uniforms[uniformName], matrix); - } - /** - * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix) - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - */ - setMatrix2x2(uniformName, matrix) { - this._valueCache[uniformName] = null; - this.engine.setMatrix2x2(this._uniforms[uniformName], matrix); - } - /** - * Sets a float on a uniform variable. - * @param uniformName Name of the variable. - * @param value value to be set. - * @returns this effect. - */ - setFloat(uniformName, value) { - const cache = this._valueCache[uniformName]; - if (cache !== undefined && cache === value) { - return; - } - if (this.engine.setFloat(this._uniforms[uniformName], value)) { - this._valueCache[uniformName] = value; - } - } - /** - * Sets a Vector2 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector2 vector2 to be set. - */ - setVector2(uniformName, vector2) { - if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) { - if (!this.engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a float2 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float2. - * @param y Second float in float2. - */ - setFloat2(uniformName, x, y) { - if (this._cacheFloat2(uniformName, x, y)) { - if (!this.engine.setFloat2(this._uniforms[uniformName], x, y)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Vector3 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector3 Value to be set. - */ - setVector3(uniformName, vector3) { - if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) { - if (!this.engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a float3 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float3. - * @param y Second float in float3. - * @param z Third float in float3. - */ - setFloat3(uniformName, x, y, z) { - if (this._cacheFloat3(uniformName, x, y, z)) { - if (!this.engine.setFloat3(this._uniforms[uniformName], x, y, z)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Vector4 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector4 Value to be set. - */ - setVector4(uniformName, vector4) { - if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) { - if (!this.engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Quaternion on a uniform variable. - * @param uniformName Name of the variable. - * @param quaternion Value to be set. - */ - setQuaternion(uniformName, quaternion) { - if (this._cacheFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w)) { - if (!this.engine.setFloat4(this._uniforms[uniformName], quaternion.x, quaternion.y, quaternion.z, quaternion.w)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a float4 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float4. - * @param y Second float in float4. - * @param z Third float in float4. - * @param w Fourth float in float4. - * @returns this effect. - */ - setFloat4(uniformName, x, y, z, w) { - if (this._cacheFloat4(uniformName, x, y, z, w)) { - if (!this.engine.setFloat4(this._uniforms[uniformName], x, y, z, w)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Color3 on a uniform variable. - * @param uniformName Name of the variable. - * @param color3 Value to be set. - */ - setColor3(uniformName, color3) { - if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) { - if (!this.engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Color4 on a uniform variable. - * @param uniformName Name of the variable. - * @param color3 Value to be set. - * @param alpha Alpha value to be set. - */ - setColor4(uniformName, color3, alpha) { - if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) { - if (!this.engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Color4 on a uniform variable - * @param uniformName defines the name of the variable - * @param color4 defines the value to be set - */ - setDirectColor4(uniformName, color4) { - if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) { - if (!this.engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a)) { - this._valueCache[uniformName] = null; - } - } - } - _getVertexShaderCode() { - return this.vertexShader ? this.engine._getShaderSource(this.vertexShader) : null; - } - _getFragmentShaderCode() { - return this.fragmentShader ? this.engine._getShaderSource(this.fragmentShader) : null; - } -} -//# sourceMappingURL=webGLPipelineContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGL/webGLHardwareTexture.js -/** @internal */ -class WebGLHardwareTexture { - get underlyingResource() { - return this._webGLTexture; - } - constructor(existingTexture = null, context) { - // There can be multiple buffers for a single WebGL texture because different layers of a 2DArrayTexture / 3DTexture - // or different faces of a cube texture can be bound to different render targets at the same time. - this._MSAARenderBuffers = null; - this._context = context; - if (!existingTexture) { - existingTexture = context.createTexture(); - if (!existingTexture) { - throw new Error("Unable to create webGL texture"); - } - } - this.set(existingTexture); - } - setUsage() { } - set(hardwareTexture) { - this._webGLTexture = hardwareTexture; - } - reset() { - this._webGLTexture = null; - this._MSAARenderBuffers = null; - } - addMSAARenderBuffer(buffer) { - if (!this._MSAARenderBuffers) { - this._MSAARenderBuffers = []; - } - this._MSAARenderBuffers.push(buffer); - } - releaseMSAARenderBuffers() { - if (this._MSAARenderBuffers) { - for (const buffer of this._MSAARenderBuffers) { - this._context.deleteRenderbuffer(buffer); - } - this._MSAARenderBuffers = null; - } - } - release() { - this.releaseMSAARenderBuffers(); - if (this._webGLTexture) { - this._context.deleteTexture(this._webGLTexture); - } - this.reset(); - } -} -//# sourceMappingURL=webGLHardwareTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/drawWrapper.js -/** @internal */ -class drawWrapper_DrawWrapper { - static IsWrapper(effect) { - return effect.getPipelineContext === undefined; - } - static GetEffect(effect) { - return effect.getPipelineContext === undefined ? effect.effect : effect; - } - constructor(engine, createMaterialContext = true) { - this.effect = null; - this.defines = null; - this.drawContext = engine.createDrawContext(); - if (createMaterialContext) { - this.materialContext = engine.createMaterialContext(); - } - } - setEffect(effect, defines, resetContext = true) { - var _a; - this.effect = effect; - if (defines !== undefined) { - this.defines = defines; - } - if (resetContext) { - (_a = this.drawContext) === null || _a === void 0 ? void 0 : _a.reset(); - } - } - dispose() { - var _a; - (_a = this.drawContext) === null || _a === void 0 ? void 0 : _a.dispose(); - } -} -//# sourceMappingURL=drawWrapper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/States/stencilStateComposer.js -/** - * @internal - **/ -class StencilStateComposer { - get isDirty() { - return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty; - } - get func() { - return this._func; - } - set func(value) { - if (this._func === value) { - return; - } - this._func = value; - this._isStencilFuncDirty = true; - } - get funcRef() { - return this._funcRef; - } - set funcRef(value) { - if (this._funcRef === value) { - return; - } - this._funcRef = value; - this._isStencilFuncDirty = true; - } - get funcMask() { - return this._funcMask; - } - set funcMask(value) { - if (this._funcMask === value) { - return; - } - this._funcMask = value; - this._isStencilFuncDirty = true; - } - get opStencilFail() { - return this._opStencilFail; - } - set opStencilFail(value) { - if (this._opStencilFail === value) { - return; - } - this._opStencilFail = value; - this._isStencilOpDirty = true; - } - get opDepthFail() { - return this._opDepthFail; - } - set opDepthFail(value) { - if (this._opDepthFail === value) { - return; - } - this._opDepthFail = value; - this._isStencilOpDirty = true; - } - get opStencilDepthPass() { - return this._opStencilDepthPass; - } - set opStencilDepthPass(value) { - if (this._opStencilDepthPass === value) { - return; - } - this._opStencilDepthPass = value; - this._isStencilOpDirty = true; - } - get mask() { - return this._mask; - } - set mask(value) { - if (this._mask === value) { - return; - } - this._mask = value; - this._isStencilMaskDirty = true; - } - get enabled() { - return this._enabled; - } - set enabled(value) { - if (this._enabled === value) { - return; - } - this._enabled = value; - this._isStencilTestDirty = true; - } - constructor(reset = true) { - this._isStencilTestDirty = false; - this._isStencilMaskDirty = false; - this._isStencilFuncDirty = false; - this._isStencilOpDirty = false; - this.useStencilGlobalOnly = false; - if (reset) { - this.reset(); - } - } - reset() { - var _a; - this.stencilMaterial = undefined; - (_a = this.stencilGlobal) === null || _a === void 0 ? void 0 : _a.reset(); - this._isStencilTestDirty = true; - this._isStencilMaskDirty = true; - this._isStencilFuncDirty = true; - this._isStencilOpDirty = true; - } - apply(gl) { - var _a; - if (!gl) { - return; - } - const stencilMaterialEnabled = !this.useStencilGlobalOnly && !!((_a = this.stencilMaterial) === null || _a === void 0 ? void 0 : _a.enabled); - this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled; - this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func; - this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef; - this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask; - this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail; - this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail; - this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass; - this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask; - if (!this.isDirty) { - return; - } - // Stencil test - if (this._isStencilTestDirty) { - if (this.enabled) { - gl.enable(gl.STENCIL_TEST); - } - else { - gl.disable(gl.STENCIL_TEST); - } - this._isStencilTestDirty = false; - } - // Stencil mask - if (this._isStencilMaskDirty) { - gl.stencilMask(this.mask); - this._isStencilMaskDirty = false; - } - // Stencil func - if (this._isStencilFuncDirty) { - gl.stencilFunc(this.func, this.funcRef, this.funcMask); - this._isStencilFuncDirty = false; - } - // Stencil op - if (this._isStencilOpDirty) { - gl.stencilOp(this.opStencilFail, this.opDepthFail, this.opStencilDepthPass); - this._isStencilOpDirty = false; - } - } -} -//# sourceMappingURL=stencilStateComposer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/thinEngine.js -/* eslint-disable @typescript-eslint/no-unused-vars */ - - - - - - - - - - - - - - - - - - - - - -/** - * Keeps track of all the buffer info used in engine. - */ -class BufferPointer { -} -/** - * The base engine class (root of all engines) - */ -class ThinEngine { - /** - * Returns the current npm package of the sdk - */ - // Not mixed with Version for tooling purpose. - static get NpmPackage() { - return "babylonjs@6.18.0"; - } - /** - * Returns the current version of the framework - */ - static get Version() { - return "6.18.0"; - } - /** - * Returns a string describing the current engine - */ - get description() { - let description = this.name + this.webGLVersion; - if (this._caps.parallelShaderCompile) { - description += " - Parallel shader compilation"; - } - return description; - } - /** - * Gets or sets the name of the engine - */ - get name() { - return this._name; - } - set name(value) { - this._name = value; - } - /** - * Returns the version of the engine - */ - get version() { - return this._webGLVersion; - } - get isDisposed() { - return this._isDisposed; - } - /** - * Gets or sets the relative url used to load shaders if using the engine in non-minified mode - */ - static get ShadersRepository() { - return effect_Effect.ShadersRepository; - } - static set ShadersRepository(value) { - effect_Effect.ShadersRepository = value; - } - /** - * @internal - */ - _getShaderProcessor(shaderLanguage) { - return this._shaderProcessor; - } - /** - * Gets or sets a boolean indicating if depth buffer should be reverse, going from far to near. - * This can provide greater z depth for distant objects. - */ - get useReverseDepthBuffer() { - return this._useReverseDepthBuffer; - } - set useReverseDepthBuffer(useReverse) { - if (useReverse === this._useReverseDepthBuffer) { - return; - } - this._useReverseDepthBuffer = useReverse; - if (useReverse) { - this._depthCullingState.depthFunc = 518; - } - else { - this._depthCullingState.depthFunc = 515; - } - } - /** - * Gets the current frame id - */ - get frameId() { - return this._frameId; - } - /** - * Gets a boolean indicating that the engine supports uniform buffers - * @see https://doc.babylonjs.com/setup/support/webGL2#uniform-buffer-objets - */ - get supportsUniformBuffers() { - return this.webGLVersion > 1 && !this.disableUniformBuffers; - } - /** - * Gets the options used for engine creation - * @returns EngineOptions object - */ - getCreationOptions() { - return this._creationOptions; - } - /** @internal */ - get _shouldUseHighPrecisionShader() { - return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed); - } - /** - * Gets a boolean indicating that only power of 2 textures are supported - * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them - */ - get needPOTTextures() { - return this._webGLVersion < 2 || this.forcePOTTextures; - } - /** - * Gets the list of current active render loop functions - * @returns an array with the current render loop functions - */ - get activeRenderLoops() { - return this._activeRenderLoops; - } - /** - * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#handling-webgl-context-lost - */ - get doNotHandleContextLost() { - return this._doNotHandleContextLost; - } - set doNotHandleContextLost(value) { - this._doNotHandleContextLost = value; - } - get _supportsHardwareTextureRescaling() { - return false; - } - /** - * sets the object from which width and height will be taken from when getting render width and height - * Will fallback to the gl object - * @param dimensions the framebuffer width and height that will be used. - */ - set framebufferDimensionsObject(dimensions) { - this._framebufferDimensionsObject = dimensions; - } - /** - * Gets the current viewport - */ - get currentViewport() { - return this._cachedViewport; - } - /** - * Gets the default empty texture - */ - get emptyTexture() { - if (!this._emptyTexture) { - this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, 5, false, false, 1); - } - return this._emptyTexture; - } - /** - * Gets the default empty 3D texture - */ - get emptyTexture3D() { - if (!this._emptyTexture3D) { - this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, 5, false, false, 1); - } - return this._emptyTexture3D; - } - /** - * Gets the default empty 2D array texture - */ - get emptyTexture2DArray() { - if (!this._emptyTexture2DArray) { - this._emptyTexture2DArray = this.createRawTexture2DArray(new Uint8Array(4), 1, 1, 1, 5, false, false, 1); - } - return this._emptyTexture2DArray; - } - /** - * Gets the default empty cube texture - */ - get emptyCubeTexture() { - if (!this._emptyCubeTexture) { - const faceData = new Uint8Array(4); - const cubeData = [faceData, faceData, faceData, faceData, faceData, faceData]; - this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, 5, 0, false, false, 1); - } - return this._emptyCubeTexture; - } - /** - * Gets a boolean indicating if the engine runs in WebGPU or not. - */ - get isWebGPU() { - return this._isWebGPU; - } - /** - * Gets the shader platform name used by the effects. - */ - get shaderPlatformName() { - return this._shaderPlatformName; - } - /** - * Enables or disables the snapshot rendering mode - * Note that the WebGL engine does not support snapshot rendering so setting the value won't have any effect for this engine - */ - get snapshotRendering() { - return false; - } - set snapshotRendering(activate) { - // WebGL engine does not support snapshot rendering - } - /** - * Gets or sets the snapshot rendering mode - */ - get snapshotRenderingMode() { - return this._snapshotRenderingMode; - } - set snapshotRenderingMode(mode) { - this._snapshotRenderingMode = mode; - } - /** - * Creates a new snapshot at the next frame using the current snapshotRenderingMode - */ - snapshotRenderingReset() { - this.snapshotRendering = false; - } - static _CreateCanvas(width, height) { - if (typeof document === "undefined") { - return new OffscreenCanvas(width, height); - } - const canvas = document.createElement("canvas"); - canvas.width = width; - canvas.height = height; - return canvas; - } - /** - * Create a canvas. This method is overridden by other engines - * @param width width - * @param height height - * @returns ICanvas interface - */ - createCanvas(width, height) { - return ThinEngine._CreateCanvas(width, height); - } - /** - * Create an image to use with canvas - * @returns IImage interface - */ - createCanvasImage() { - return document.createElement("img"); - } - /** - * Creates a new engine - * @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 - * @param antialias defines enable antialiasing (default: false) - * @param options defines further options to be sent to the getContext() function - * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false) - */ - constructor(canvasOrContext, antialias, options, adaptToDeviceRatio) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; - /** @internal */ - this._name = "WebGL"; - this._isDisposed = false; - /** - * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required - */ - this.forcePOTTextures = false; - /** - * Gets a boolean indicating if the engine is currently rendering in fullscreen mode - */ - this.isFullscreen = false; - /** - * Gets or sets a boolean indicating if back faces must be culled. If false, front faces are culled instead (true by default) - * If non null, this takes precedence over the value from the material - */ - this.cullBackFaces = null; - /** - * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foreground - */ - this.renderEvenInBackground = true; - /** - * Gets or sets a boolean indicating that cache can be kept between frames - */ - this.preventCacheWipeBetweenFrames = false; - /** Gets or sets a boolean indicating if the engine should validate programs after compilation */ - this.validateShaderPrograms = false; - this._useReverseDepthBuffer = false; - /** - * Indicates if the z range in NDC space is 0..1 (value: true) or -1..1 (value: false) - */ - this.isNDCHalfZRange = false; - /** - * Indicates that the origin of the texture/framebuffer space is the bottom left corner. If false, the origin is top left - */ - this.hasOriginBottomLeft = true; - /** - * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported - */ - this.disableUniformBuffers = false; - /** - * An event triggered when the engine is disposed. - */ - this.onDisposeObservable = new observable_Observable(); - this._frameId = 0; - /** @internal */ - this._uniformBuffers = new Array(); - /** @internal */ - this._storageBuffers = new Array(); - /** @internal */ - this._webGLVersion = 1.0; - this._windowIsBackground = false; - this._highPrecisionShadersAllowed = true; - /** @internal */ - this._badOS = false; - /** @internal */ - this._badDesktopOS = false; - this._renderingQueueLaunched = false; - this._activeRenderLoops = new Array(); - // Lost context - /** - * Observable signaled when a context lost event is raised - */ - this.onContextLostObservable = new observable_Observable(); - /** - * Observable signaled when a context restored event is raised - */ - this.onContextRestoredObservable = new observable_Observable(); - this._contextWasLost = false; - /** @internal */ - this._doNotHandleContextLost = false; - /** - * Gets or sets a boolean indicating that vertex array object must be disabled even if they are supported - */ - this.disableVertexArrayObjects = false; - // States - /** @internal */ - this._colorWrite = true; - /** @internal */ - this._colorWriteChanged = true; - /** @internal */ - this._depthCullingState = new DepthCullingState(); - /** @internal */ - this._stencilStateComposer = new StencilStateComposer(); - /** @internal */ - this._stencilState = new StencilState(); - /** @internal */ - this._alphaState = new AlphaState(); - /** @internal */ - this._alphaMode = 1; - /** @internal */ - this._alphaEquation = 0; - // Cache - /** @internal */ - this._internalTexturesCache = new Array(); - /** @internal */ - this._renderTargetWrapperCache = new Array(); - /** @internal */ - this._activeChannel = 0; - this._currentTextureChannel = -1; - /** @internal */ - this._boundTexturesCache = {}; - this._compiledEffects = {}; - this._vertexAttribArraysEnabled = []; - this._uintIndicesCurrentlySet = false; - this._currentBoundBuffer = new Array(); - /** @internal */ - this._currentFramebuffer = null; - /** @internal */ - this._dummyFramebuffer = null; - this._currentBufferPointers = new Array(); - this._currentInstanceLocations = new Array(); - this._currentInstanceBuffers = new Array(); - this._vaoRecordInProgress = false; - this._mustWipeVertexAttributes = false; - this._nextFreeTextureSlots = new Array(); - this._maxSimultaneousTextures = 0; - this._maxMSAASamplesOverride = null; - this._activeRequests = new Array(); - /** - * If set to true zooming in and out in the browser will rescale the hardware-scaling correctly. - */ - this.adaptToDeviceRatio = false; - /** @internal */ - this._lastDevicePixelRatio = 1.0; - /** @internal */ - this._transformTextureUrl = null; - /** - * Gets information about the current host - */ - this.hostInformation = { - isMobile: false, - }; - /** - * Defines whether the engine has been created with the premultipliedAlpha option on or not. - */ - this.premultipliedAlpha = true; - /** - * Observable event triggered before each texture is initialized - */ - this.onBeforeTextureInitObservable = new observable_Observable(); - /** @internal */ - this._isWebGPU = false; - this._snapshotRenderingMode = 0; - this._viewportCached = { x: 0, y: 0, z: 0, w: 0 }; - this._unpackFlipYCached = null; - /** - * In case you are sharing the context with other applications, it might - * be interested to not cache the unpack flip y state to ensure a consistent - * value would be set. - */ - this.enableUnpackFlipYCached = true; - this._boundUniforms = {}; - this.startTime = precisionDate_PrecisionDate.Now; - let canvas = null; - options = options || {}; - this._creationOptions = options; - // Save this off for use in resize(). - this.adaptToDeviceRatio = adaptToDeviceRatio !== null && adaptToDeviceRatio !== void 0 ? adaptToDeviceRatio : false; - this._stencilStateComposer.stencilGlobal = this._stencilState; - performanceConfigurator_PerformanceConfigurator.SetMatrixPrecision(!!options.useHighPrecisionMatrix); - options.antialias = antialias !== null && antialias !== void 0 ? antialias : options.antialias; - options.deterministicLockstep = (_a = options.deterministicLockstep) !== null && _a !== void 0 ? _a : false; - options.lockstepMaxSteps = (_b = options.lockstepMaxSteps) !== null && _b !== void 0 ? _b : 4; - options.timeStep = (_c = options.timeStep) !== null && _c !== void 0 ? _c : 1 / 60; - options.audioEngine = (_d = options.audioEngine) !== null && _d !== void 0 ? _d : true; - options.stencil = (_e = options.stencil) !== null && _e !== void 0 ? _e : true; - this._audioContext = (_g = (_f = options.audioEngineOptions) === null || _f === void 0 ? void 0 : _f.audioContext) !== null && _g !== void 0 ? _g : null; - this._audioDestination = (_j = (_h = options.audioEngineOptions) === null || _h === void 0 ? void 0 : _h.audioDestination) !== null && _j !== void 0 ? _j : null; - this.premultipliedAlpha = (_k = options.premultipliedAlpha) !== null && _k !== void 0 ? _k : true; - this.useExactSrgbConversions = (_l = options.useExactSrgbConversions) !== null && _l !== void 0 ? _l : false; - this._doNotHandleContextLost = !!options.doNotHandleContextLost; - this._isStencilEnable = options.stencil ? true : false; - // Viewport - adaptToDeviceRatio = adaptToDeviceRatio || options.adaptToDeviceRatio || false; - const devicePixelRatio = IsWindowObjectExist() ? window.devicePixelRatio || 1.0 : 1.0; - const limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio; - this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0; - this._lastDevicePixelRatio = devicePixelRatio; - if (!canvasOrContext) { - return; - } - if (canvasOrContext.getContext) { - canvas = canvasOrContext; - this._renderingCanvas = canvas; - if (options.preserveDrawingBuffer === undefined) { - options.preserveDrawingBuffer = false; - } - if (options.xrCompatible === undefined) { - options.xrCompatible = true; - } - // Exceptions - if (navigator && navigator.userAgent) { - this._setupMobileChecks(); - const ua = navigator.userAgent; - for (const exception of ThinEngine.ExceptionList) { - const key = exception.key; - const targets = exception.targets; - const check = new RegExp(key); - if (check.test(ua)) { - if (exception.capture && exception.captureConstraint) { - const capture = exception.capture; - const constraint = exception.captureConstraint; - const regex = new RegExp(capture); - const matches = regex.exec(ua); - if (matches && matches.length > 0) { - const capturedValue = parseInt(matches[matches.length - 1]); - if (capturedValue >= constraint) { - continue; - } - } - } - for (const target of targets) { - switch (target) { - case "uniformBuffer": - this.disableUniformBuffers = true; - break; - case "vao": - this.disableVertexArrayObjects = true; - break; - case "antialias": - options.antialias = false; - break; - case "maxMSAASamples": - this._maxMSAASamplesOverride = 1; - break; - } - } - } - } - } - // Context lost - if (!this._doNotHandleContextLost) { - this._onContextLost = (evt) => { - evt.preventDefault(); - this._contextWasLost = true; - logger_Logger.Warn("WebGL context lost."); - this.onContextLostObservable.notifyObservers(this); - }; - this._onContextRestored = () => { - this._restoreEngineAfterContextLost(this._initGLContext.bind(this)); - }; - canvas.addEventListener("webglcontextlost", this._onContextLost, false); - canvas.addEventListener("webglcontextrestored", this._onContextRestored, false); - options.powerPreference = options.powerPreference || "high-performance"; - } - // Detect if we are running on a faulty buggy desktop OS. - this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); - if (this._badDesktopOS) { - options.xrCompatible = false; - } - // GL - if (!options.disableWebGL2Support) { - try { - this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options)); - if (this._gl) { - this._webGLVersion = 2.0; - this._shaderPlatformName = "WEBGL2"; - // Prevent weird browsers to lie (yeah that happens!) - if (!this._gl.deleteQuery) { - this._webGLVersion = 1.0; - this._shaderPlatformName = "WEBGL1"; - } - } - } - catch (e) { - // Do nothing - } - } - if (!this._gl) { - if (!canvas) { - throw new Error("The provided canvas is null or undefined."); - } - try { - this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options)); - } - catch (e) { - throw new Error("WebGL not supported"); - } - } - if (!this._gl) { - throw new Error("WebGL not supported"); - } - } - else { - this._gl = canvasOrContext; - this._renderingCanvas = this._gl.canvas; - if (this._gl.renderbufferStorageMultisample) { - this._webGLVersion = 2.0; - this._shaderPlatformName = "WEBGL2"; - } - else { - this._shaderPlatformName = "WEBGL1"; - } - const attributes = this._gl.getContextAttributes(); - if (attributes) { - options.stencil = attributes.stencil; - } - } - // Ensures a consistent color space unpacking of textures cross browser. - this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE); - if (options.useHighPrecisionFloats !== undefined) { - this._highPrecisionShadersAllowed = options.useHighPrecisionFloats; - } - this.resize(); - this._initGLContext(); - this._initFeatures(); - // Prepare buffer pointers - for (let i = 0; i < this._caps.maxVertexAttribs; i++) { - this._currentBufferPointers[i] = new BufferPointer(); - } - // Shader processor - this._shaderProcessor = this.webGLVersion > 1 ? new WebGL2ShaderProcessor() : new WebGLShaderProcessor(); - // Detect if we are running on a faulty buggy OS. - this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent); - // Starting with iOS 14, we can trust the browser - // let matches = navigator.userAgent.match(/Version\/(\d+)/); - // if (matches && matches.length === 2) { - // if (parseInt(matches[1]) >= 14) { - // this._badOS = false; - // } - // } - const versionToLog = `Babylon.js v${ThinEngine.Version}`; - console.log(versionToLog + ` - ${this.description}`); - // Check setAttribute in case of workers - if (this._renderingCanvas && this._renderingCanvas.setAttribute) { - this._renderingCanvas.setAttribute("data-engine", versionToLog); - } - } - _setupMobileChecks() { - if (!(navigator && navigator.userAgent)) { - return; - } - // Function to check if running on mobile device - this._checkForMobile = () => { - const currentUA = navigator.userAgent; - this.hostInformation.isMobile = - currentUA.indexOf("Mobile") !== -1 || - // Needed for iOS 13+ detection on iPad (inspired by solution from https://stackoverflow.com/questions/9038625/detect-if-device-is-ios) - (currentUA.indexOf("Mac") !== -1 && IsDocumentAvailable() && "ontouchend" in document); - }; - // Set initial isMobile value - this._checkForMobile(); - // Set up event listener to check when window is resized (used to get emulator activation to work properly) - if (IsWindowObjectExist()) { - window.addEventListener("resize", this._checkForMobile); - } - } - _restoreEngineAfterContextLost(initEngine) { - // Adding a timeout to avoid race condition at browser level - setTimeout(async () => { - var _a; - this._dummyFramebuffer = null; - const depthTest = this._depthCullingState.depthTest; // backup those values because the call to initEngine / wipeCaches will reset them - const depthFunc = this._depthCullingState.depthFunc; - const depthMask = this._depthCullingState.depthMask; - const stencilTest = this._stencilState.stencilTest; - // Rebuild context - await initEngine(); - // Ensure webgl and engine states are matching - this.wipeCaches(true); - // Rebuild effects - this._rebuildEffects(); - (_a = this._rebuildComputeEffects) === null || _a === void 0 ? void 0 : _a.call(this); - // Note: - // The call to _rebuildBuffers must be made before the call to _rebuildInternalTextures because in the process of _rebuildBuffers the buffers used by the post process managers will be rebuilt - // and we may need to use the post process manager of the scene during _rebuildInternalTextures (in WebGL1, non-POT textures are rescaled using a post process + post process manager of the scene) - // Rebuild buffers - this._rebuildBuffers(); - // Rebuild textures - this._rebuildInternalTextures(); - // Rebuild textures - this._rebuildRenderTargetWrappers(); - // Reset engine states after all the buffer/textures/... have been rebuilt - this.wipeCaches(true); - this._depthCullingState.depthTest = depthTest; - this._depthCullingState.depthFunc = depthFunc; - this._depthCullingState.depthMask = depthMask; - this._stencilState.stencilTest = stencilTest; - logger_Logger.Warn(this.name + " context successfully restored."); - this.onContextRestoredObservable.notifyObservers(this); - this._contextWasLost = false; - }, 0); - } - /** - * Shared initialization across engines types. - * @param canvas The canvas associated with this instance of the engine. - */ - _sharedInit(canvas) { - this._renderingCanvas = canvas; - } - /** - * @internal - */ - _getShaderProcessingContext(shaderLanguage) { - return null; - } - _rebuildInternalTextures() { - const currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies - for (const internalTexture of currentState) { - internalTexture._rebuild(); - } - } - _rebuildRenderTargetWrappers() { - const currentState = this._renderTargetWrapperCache.slice(); // Do a copy because the rebuild will add proxies - for (const renderTargetWrapper of currentState) { - renderTargetWrapper._rebuild(); - } - } - _rebuildEffects() { - for (const key in this._compiledEffects) { - const effect = this._compiledEffects[key]; - effect._pipelineContext = null; // because _prepareEffect will try to dispose this pipeline before recreating it and that would lead to webgl errors - effect._wasPreviouslyReady = false; - effect._prepareEffect(); - } - effect_Effect.ResetCache(); - } - /** - * Gets a boolean indicating if all created effects are ready - * @returns true if all effects are ready - */ - areAllEffectsReady() { - for (const key in this._compiledEffects) { - const effect = this._compiledEffects[key]; - if (!effect.isReady()) { - return false; - } - } - return true; - } - _rebuildBuffers() { - // Uniforms - for (const uniformBuffer of this._uniformBuffers) { - uniformBuffer._rebuild(); - } - // Storage buffers - for (const storageBuffer of this._storageBuffers) { - storageBuffer._rebuild(); - } - } - _initGLContext() { - var _a; - // Caps - this._caps = { - maxTexturesImageUnits: this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS), - maxCombinedTexturesImageUnits: this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS), - maxVertexTextureImageUnits: this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS), - maxTextureSize: this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE), - maxSamples: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_SAMPLES) : 1, - maxCubemapTextureSize: this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE), - maxRenderTextureSize: this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE), - maxVertexAttribs: this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS), - maxVaryingVectors: this._gl.getParameter(this._gl.MAX_VARYING_VECTORS), - maxFragmentUniformVectors: this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS), - maxVertexUniformVectors: this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS), - parallelShaderCompile: this._gl.getExtension("KHR_parallel_shader_compile") || undefined, - standardDerivatives: this._webGLVersion > 1 || this._gl.getExtension("OES_standard_derivatives") !== null, - maxAnisotropy: 1, - astc: this._gl.getExtension("WEBGL_compressed_texture_astc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"), - bptc: this._gl.getExtension("EXT_texture_compression_bptc") || this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"), - s3tc: this._gl.getExtension("WEBGL_compressed_texture_s3tc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"), - // eslint-disable-next-line @typescript-eslint/naming-convention - s3tc_srgb: this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"), - pvrtc: this._gl.getExtension("WEBGL_compressed_texture_pvrtc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"), - etc1: this._gl.getExtension("WEBGL_compressed_texture_etc1") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"), - etc2: this._gl.getExtension("WEBGL_compressed_texture_etc") || - this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc") || - this._gl.getExtension("WEBGL_compressed_texture_es3_0"), - textureAnisotropicFilterExtension: this._gl.getExtension("EXT_texture_filter_anisotropic") || - this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic") || - this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"), - uintIndices: this._webGLVersion > 1 || this._gl.getExtension("OES_element_index_uint") !== null, - fragmentDepthSupported: this._webGLVersion > 1 || this._gl.getExtension("EXT_frag_depth") !== null, - highPrecisionShaderSupported: false, - timerQuery: this._gl.getExtension("EXT_disjoint_timer_query_webgl2") || this._gl.getExtension("EXT_disjoint_timer_query"), - supportOcclusionQuery: this._webGLVersion > 1, - canUseTimestampForTimerQuery: false, - drawBuffersExtension: false, - maxMSAASamples: 1, - colorBufferFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_float")), - colorBufferHalfFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_half_float")), - textureFloat: this._webGLVersion > 1 || this._gl.getExtension("OES_texture_float") ? true : false, - textureHalfFloat: this._webGLVersion > 1 || this._gl.getExtension("OES_texture_half_float") ? true : false, - textureHalfFloatRender: false, - textureFloatLinearFiltering: false, - textureFloatRender: false, - textureHalfFloatLinearFiltering: false, - vertexArrayObject: false, - instancedArrays: false, - textureLOD: this._webGLVersion > 1 || this._gl.getExtension("EXT_shader_texture_lod") ? true : false, - texelFetch: this._webGLVersion !== 1, - blendMinMax: false, - multiview: this._gl.getExtension("OVR_multiview2"), - oculusMultiview: this._gl.getExtension("OCULUS_multiview"), - depthTextureExtension: false, - canUseGLInstanceID: this._webGLVersion > 1, - canUseGLVertexID: this._webGLVersion > 1, - supportComputeShaders: false, - supportSRGBBuffers: false, - supportTransformFeedbacks: this._webGLVersion > 1, - textureMaxLevel: this._webGLVersion > 1, - texture2DArrayMaxLayerCount: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS) : 128, - disableMorphTargetTexture: false, - }; - // Infos - this._glVersion = this._gl.getParameter(this._gl.VERSION); - const rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info"); - if (rendererInfo != null) { - this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL); - this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL); - } - if (!this._glVendor) { - this._glVendor = this._gl.getParameter(this._gl.VENDOR) || "Unknown vendor"; - } - if (!this._glRenderer) { - this._glRenderer = this._gl.getParameter(this._gl.RENDERER) || "Unknown renderer"; - } - // Constants - if (this._gl.HALF_FLOAT_OES !== 0x8d61) { - this._gl.HALF_FLOAT_OES = 0x8d61; // Half floating-point type (16-bit). - } - if (this._gl.RGBA16F !== 0x881a) { - this._gl.RGBA16F = 0x881a; // RGBA 16-bit floating-point color-renderable internal sized format. - } - if (this._gl.RGBA32F !== 0x8814) { - this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format. - } - if (this._gl.DEPTH24_STENCIL8 !== 35056) { - this._gl.DEPTH24_STENCIL8 = 35056; - } - // Extensions - if (this._caps.timerQuery) { - if (this._webGLVersion === 1) { - this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery); - } - // WebGLQuery casted to number to avoid TS error - this._caps.canUseTimestampForTimerQuery = ((_a = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)) !== null && _a !== void 0 ? _a : 0) > 0; - } - this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension - ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) - : 0; - this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension("OES_texture_float_linear") ? true : false; - this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false; - this._caps.textureHalfFloatLinearFiltering = - this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension("OES_texture_half_float_linear")) ? true : false; - // Compressed formats - if (this._caps.astc) { - this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; - } - if (this._caps.bptc) { - this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT; - } - if (this._caps.s3tc_srgb) { - this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT; - this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - } - if (this._caps.etc2) { - this._gl.COMPRESSED_SRGB8_ETC2 = this._caps.etc2.COMPRESSED_SRGB8_ETC2; - this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; - } - // Checks if some of the format renders first to allow the use of webgl inspector. - if (this._webGLVersion > 1) { - if (this._gl.HALF_FLOAT_OES !== 0x140b) { - this._gl.HALF_FLOAT_OES = 0x140b; - } - } - this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer(); - // Draw buffers - if (this._webGLVersion > 1) { - this._caps.drawBuffersExtension = true; - this._caps.maxMSAASamples = this._maxMSAASamplesOverride !== null ? this._maxMSAASamplesOverride : this._gl.getParameter(this._gl.MAX_SAMPLES); - } - else { - const drawBuffersExtension = this._gl.getExtension("WEBGL_draw_buffers"); - if (drawBuffersExtension !== null) { - this._caps.drawBuffersExtension = true; - this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension); - this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER; - for (let i = 0; i < 16; i++) { - this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"]; - } - } - } - // Depth Texture - if (this._webGLVersion > 1) { - this._caps.depthTextureExtension = true; - } - else { - const depthTextureExtension = this._gl.getExtension("WEBGL_depth_texture"); - if (depthTextureExtension != null) { - this._caps.depthTextureExtension = true; - this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL; - } - } - // Vertex array object - if (this.disableVertexArrayObjects) { - this._caps.vertexArrayObject = false; - } - else if (this._webGLVersion > 1) { - this._caps.vertexArrayObject = true; - } - else { - const vertexArrayObjectExtension = this._gl.getExtension("OES_vertex_array_object"); - if (vertexArrayObjectExtension != null) { - this._caps.vertexArrayObject = true; - this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension); - this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension); - this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension); - } - } - // Instances count - if (this._webGLVersion > 1) { - this._caps.instancedArrays = true; - } - else { - const instanceExtension = this._gl.getExtension("ANGLE_instanced_arrays"); - if (instanceExtension != null) { - this._caps.instancedArrays = true; - this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension); - this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension); - this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension); - } - else { - this._caps.instancedArrays = false; - } - } - if (this._gl.getShaderPrecisionFormat) { - const vertexhighp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT); - const fragmenthighp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT); - if (vertexhighp && fragmenthighp) { - this._caps.highPrecisionShaderSupported = vertexhighp.precision !== 0 && fragmenthighp.precision !== 0; - } - } - if (this._webGLVersion > 1) { - this._caps.blendMinMax = true; - } - else { - const blendMinMaxExtension = this._gl.getExtension("EXT_blend_minmax"); - if (blendMinMaxExtension != null) { - this._caps.blendMinMax = true; - this._gl.MAX = blendMinMaxExtension.MAX_EXT; - this._gl.MIN = blendMinMaxExtension.MIN_EXT; - } - } - // sRGB buffers - // only run this if not already set to true (in the constructor, for example) - if (!this._caps.supportSRGBBuffers) { - if (this._webGLVersion > 1) { - this._caps.supportSRGBBuffers = true; - this._glSRGBExtensionValues = { - SRGB: WebGL2RenderingContext.SRGB, - SRGB8: WebGL2RenderingContext.SRGB8, - SRGB8_ALPHA8: WebGL2RenderingContext.SRGB8_ALPHA8, - }; - } - else { - const sRGBExtension = this._gl.getExtension("EXT_sRGB"); - if (sRGBExtension != null) { - this._caps.supportSRGBBuffers = true; - this._glSRGBExtensionValues = { - SRGB: sRGBExtension.SRGB_EXT, - SRGB8: sRGBExtension.SRGB_ALPHA_EXT, - SRGB8_ALPHA8: sRGBExtension.SRGB_ALPHA_EXT, - }; - } - } - // take into account the forced state that was provided in options - // When the issue in angle/chrome is fixed the flag should be taken into account only when it is explicitly defined - this._caps.supportSRGBBuffers = this._caps.supportSRGBBuffers && !!(this._creationOptions && this._creationOptions.forceSRGBBufferSupportState); - } - // Depth buffer - this._depthCullingState.depthTest = true; - this._depthCullingState.depthFunc = this._gl.LEQUAL; - this._depthCullingState.depthMask = true; - // Texture maps - this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits; - for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) { - this._nextFreeTextureSlots.push(slot); - } - if (this._glRenderer === "Mali-G72") { - // Overcome a bug when using a texture to store morph targets on Mali-G72 - this._caps.disableMorphTargetTexture = true; - } - } - _initFeatures() { - this._features = { - forceBitmapOverHTMLImageElement: false, - supportRenderAndCopyToLodForFloatTextures: this._webGLVersion !== 1, - supportDepthStencilTexture: this._webGLVersion !== 1, - supportShadowSamplers: this._webGLVersion !== 1, - uniformBufferHardCheckMatrix: false, - allowTexturePrefiltering: this._webGLVersion !== 1, - trackUbosInFrame: false, - checkUbosContentBeforeUpload: false, - supportCSM: this._webGLVersion !== 1, - basisNeedsPOT: this._webGLVersion === 1, - support3DTextures: this._webGLVersion !== 1, - needTypeSuffixInShaderConstants: this._webGLVersion !== 1, - supportMSAA: this._webGLVersion !== 1, - supportSSAO2: this._webGLVersion !== 1, - supportExtendedTextureFormats: this._webGLVersion !== 1, - supportSwitchCaseInShader: this._webGLVersion !== 1, - supportSyncTextureRead: true, - needsInvertingBitmap: true, - useUBOBindingCache: true, - needShaderCodeInlining: false, - needToAlwaysBindUniformBuffers: false, - supportRenderPasses: false, - supportSpriteInstancing: true, - _collectUbosUpdatedInFrame: false, - }; - } - /** - * Gets version of the current webGL context - * Keep it for back compat - use version instead - */ - get webGLVersion() { - return this._webGLVersion; - } - /** - * Gets a string identifying the name of the class - * @returns "Engine" string - */ - getClassName() { - return "ThinEngine"; - } - /** - * Returns true if the stencil buffer has been enabled through the creation option of the context. - */ - get isStencilEnable() { - return this._isStencilEnable; - } - /** @internal */ - _prepareWorkingCanvas() { - if (this._workingCanvas) { - return; - } - this._workingCanvas = this.createCanvas(1, 1); - const context = this._workingCanvas.getContext("2d"); - if (context) { - this._workingContext = context; - } - } - /** - * Reset the texture cache to empty state - */ - resetTextureCache() { - for (const key in this._boundTexturesCache) { - if (!Object.prototype.hasOwnProperty.call(this._boundTexturesCache, key)) { - continue; - } - this._boundTexturesCache[key] = null; - } - this._currentTextureChannel = -1; - } - /** - * Gets an object containing information about the current engine context - * @returns an object containing the vendor, the renderer and the version of the current engine context - */ - getInfo() { - return this.getGlInfo(); - } - /** - * Gets an object containing information about the current webGL context - * @returns an object containing the vendor, the renderer and the version of the current webGL context - */ - getGlInfo() { - return { - vendor: this._glVendor, - renderer: this._glRenderer, - version: this._glVersion, - }; - } - /** - * Defines the hardware scaling level. - * By default the hardware scaling level is computed from the window device ratio. - * 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. - * @param level defines the level to use - */ - setHardwareScalingLevel(level) { - this._hardwareScalingLevel = level; - this.resize(); - } - /** - * Gets the current hardware scaling level. - * By default the hardware scaling level is computed from the window device ratio. - * 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. - * @returns a number indicating the current hardware scaling level - */ - getHardwareScalingLevel() { - return this._hardwareScalingLevel; - } - /** - * Gets the list of loaded textures - * @returns an array containing all loaded textures - */ - getLoadedTexturesCache() { - return this._internalTexturesCache; - } - /** - * Gets the object containing all engine capabilities - * @returns the EngineCapabilities object - */ - getCaps() { - return this._caps; - } - /** - * stop executing a render loop function and remove it from the execution array - * @param renderFunction defines the function to be removed. If not provided all functions will be removed. - */ - stopRenderLoop(renderFunction) { - if (!renderFunction) { - this._activeRenderLoops.length = 0; - this._cancelFrame(); - return; - } - const index = this._activeRenderLoops.indexOf(renderFunction); - if (index >= 0) { - this._activeRenderLoops.splice(index, 1); - if (this._activeRenderLoops.length == 0) { - this._cancelFrame(); - } - } - } - _cancelFrame() { - if (this._renderingQueueLaunched && this._frameHandler) { - this._renderingQueueLaunched = false; - if (!IsWindowObjectExist()) { - if (typeof cancelAnimationFrame === "function") { - return cancelAnimationFrame(this._frameHandler); - } - } - else { - const { cancelAnimationFrame } = this.getHostWindow() || window; - if (typeof cancelAnimationFrame === "function") { - return cancelAnimationFrame(this._frameHandler); - } - } - return clearTimeout(this._frameHandler); - } - } - /** @internal */ - _renderLoop() { - if (!this._contextWasLost) { - let shouldRender = true; - if (this._isDisposed || (!this.renderEvenInBackground && this._windowIsBackground)) { - shouldRender = false; - } - if (shouldRender) { - // Start new frame - this.beginFrame(); - for (let index = 0; index < this._activeRenderLoops.length; index++) { - const renderFunction = this._activeRenderLoops[index]; - renderFunction(); - } - // Present - this.endFrame(); - } - } - if (this._activeRenderLoops.length > 0) { - this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()); - } - else { - this._renderingQueueLaunched = false; - } - } - /** - * Gets the HTML canvas attached with the current webGL context - * @returns a HTML canvas - */ - getRenderingCanvas() { - return this._renderingCanvas; - } - /** - * Gets the audio context specified in engine initialization options - * @returns an Audio Context - */ - getAudioContext() { - return this._audioContext; - } - /** - * Gets the audio destination specified in engine initialization options - * @returns an audio destination node - */ - getAudioDestination() { - return this._audioDestination; - } - /** - * Gets host window - * @returns the host window object - */ - getHostWindow() { - if (!IsWindowObjectExist()) { - return null; - } - if (this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView) { - return this._renderingCanvas.ownerDocument.defaultView; - } - return window; - } - /** - * Gets the current render width - * @param useScreen defines if screen size must be used (or the current render target if any) - * @returns a number defining the current render width - */ - getRenderWidth(useScreen = false) { - if (!useScreen && this._currentRenderTarget) { - return this._currentRenderTarget.width; - } - return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferWidth : this._gl.drawingBufferWidth; - } - /** - * Gets the current render height - * @param useScreen defines if screen size must be used (or the current render target if any) - * @returns a number defining the current render height - */ - getRenderHeight(useScreen = false) { - if (!useScreen && this._currentRenderTarget) { - return this._currentRenderTarget.height; - } - return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight; - } - /** - * Can be used to override the current requestAnimationFrame requester. - * @internal - */ - _queueNewFrame(bindedRenderFunction, requester) { - return ThinEngine.QueueNewFrame(bindedRenderFunction, requester); - } - /** - * Register and execute a render loop. The engine can have more than one render function - * @param renderFunction defines the function to continuously execute - */ - runRenderLoop(renderFunction) { - if (this._activeRenderLoops.indexOf(renderFunction) !== -1) { - return; - } - this._activeRenderLoops.push(renderFunction); - if (!this._renderingQueueLaunched) { - this._renderingQueueLaunched = true; - this._boundRenderFunction = this._renderLoop.bind(this); - this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()); - } - } - /** - * Clear the current render buffer or the current render target (if any is set up) - * @param color defines the color to use - * @param backBuffer defines if the back buffer must be cleared - * @param depth defines if the depth buffer must be cleared - * @param stencil defines if the stencil buffer must be cleared - */ - clear(color, backBuffer, depth, stencil = false) { - var _a, _b; - const useStencilGlobalOnly = this.stencilStateComposer.useStencilGlobalOnly; - this.stencilStateComposer.useStencilGlobalOnly = true; // make sure the stencil mask is coming from the global stencil and not from a material (effect) which would currently be in effect - this.applyStates(); - this.stencilStateComposer.useStencilGlobalOnly = useStencilGlobalOnly; - let mode = 0; - if (backBuffer && color) { - let setBackBufferColor = true; - if (this._currentRenderTarget) { - const textureFormat = (_a = this._currentRenderTarget.texture) === null || _a === void 0 ? void 0 : _a.format; - if (textureFormat === 8 || - textureFormat === 9 || - textureFormat === 10 || - textureFormat === 11) { - const textureType = (_b = this._currentRenderTarget.texture) === null || _b === void 0 ? void 0 : _b.type; - if (textureType === 7 || textureType === 5) { - ThinEngine._TempClearColorUint32[0] = color.r * 255; - ThinEngine._TempClearColorUint32[1] = color.g * 255; - ThinEngine._TempClearColorUint32[2] = color.b * 255; - ThinEngine._TempClearColorUint32[3] = color.a * 255; - this._gl.clearBufferuiv(this._gl.COLOR, 0, ThinEngine._TempClearColorUint32); - setBackBufferColor = false; - } - else { - ThinEngine._TempClearColorInt32[0] = color.r * 255; - ThinEngine._TempClearColorInt32[1] = color.g * 255; - ThinEngine._TempClearColorInt32[2] = color.b * 255; - ThinEngine._TempClearColorInt32[3] = color.a * 255; - this._gl.clearBufferiv(this._gl.COLOR, 0, ThinEngine._TempClearColorInt32); - setBackBufferColor = false; - } - } - } - if (setBackBufferColor) { - this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0); - mode |= this._gl.COLOR_BUFFER_BIT; - } - } - if (depth) { - if (this.useReverseDepthBuffer) { - this._depthCullingState.depthFunc = this._gl.GEQUAL; - this._gl.clearDepth(0.0); - } - else { - this._gl.clearDepth(1.0); - } - mode |= this._gl.DEPTH_BUFFER_BIT; - } - if (stencil) { - this._gl.clearStencil(0); - mode |= this._gl.STENCIL_BUFFER_BIT; - } - this._gl.clear(mode); - } - /** - * @internal - */ - _viewport(x, y, width, height) { - if (x !== this._viewportCached.x || y !== this._viewportCached.y || width !== this._viewportCached.z || height !== this._viewportCached.w) { - this._viewportCached.x = x; - this._viewportCached.y = y; - this._viewportCached.z = width; - this._viewportCached.w = height; - this._gl.viewport(x, y, width, height); - } - } - /** - * Set the WebGL's viewport - * @param viewport defines the viewport element to be used - * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used - * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used - */ - setViewport(viewport, requiredWidth, requiredHeight) { - const width = requiredWidth || this.getRenderWidth(); - const height = requiredHeight || this.getRenderHeight(); - const x = viewport.x || 0; - const y = viewport.y || 0; - this._cachedViewport = viewport; - this._viewport(x * width, y * height, width * viewport.width, height * viewport.height); - } - /** - * Begin a new frame - */ - beginFrame() { } - /** - * Enf the current frame - */ - endFrame() { - // Force a flush in case we are using a bad OS. - if (this._badOS) { - this.flushFramebuffer(); - } - this._frameId++; - } - /** - * Resize the view according to the canvas' size - * @param forceSetSize true to force setting the sizes of the underlying canvas - */ - resize(forceSetSize = false) { - let width; - let height; - // Re-query hardware scaling level to handle zoomed-in resizing. - if (this.adaptToDeviceRatio) { - const devicePixelRatio = IsWindowObjectExist() ? window.devicePixelRatio || 1.0 : 1.0; - const changeRatio = this._lastDevicePixelRatio / devicePixelRatio; - this._lastDevicePixelRatio = devicePixelRatio; - this._hardwareScalingLevel *= changeRatio; - } - if (IsWindowObjectExist() && IsDocumentAvailable()) { - // make sure it is a Node object, and is a part of the document. - if (this._renderingCanvas) { - const boundingRect = this._renderingCanvas.getBoundingClientRect - ? this._renderingCanvas.getBoundingClientRect() - : { - // fallback to last solution in case the function doesn't exist - width: this._renderingCanvas.width * this._hardwareScalingLevel, - height: this._renderingCanvas.height * this._hardwareScalingLevel, - }; - width = this._renderingCanvas.clientWidth || boundingRect.width || this._renderingCanvas.width || 100; - height = this._renderingCanvas.clientHeight || boundingRect.height || this._renderingCanvas.height || 100; - } - else { - width = window.innerWidth; - height = window.innerHeight; - } - } - else { - width = this._renderingCanvas ? this._renderingCanvas.width : 100; - height = this._renderingCanvas ? this._renderingCanvas.height : 100; - } - this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel, forceSetSize); - } - /** - * Force a specific size of the canvas - * @param width defines the new canvas' width - * @param height defines the new canvas' height - * @param forceSetSize true to force setting the sizes of the underlying canvas - * @returns true if the size was changed - */ - setSize(width, height, forceSetSize = false) { - if (!this._renderingCanvas) { - return false; - } - width = width | 0; - height = height | 0; - if (!forceSetSize && this._renderingCanvas.width === width && this._renderingCanvas.height === height) { - return false; - } - this._renderingCanvas.width = width; - this._renderingCanvas.height = height; - return true; - } - /** - * Binds the frame buffer to the specified texture. - * @param rtWrapper The render target wrapper to render to - * @param faceIndex The face of the texture to render to in case of cube texture and if the render target wrapper is not a multi render target - * @param requiredWidth The width of the target to render to - * @param requiredHeight The height of the target to render to - * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true - * @param lodLevel Defines the lod level to bind to the frame buffer - * @param layer Defines the 2d array index to bind to the frame buffer if the render target wrapper is not a multi render target - */ - bindFramebuffer(rtWrapper, faceIndex = 0, requiredWidth, requiredHeight, forceFullscreenViewport, lodLevel = 0, layer = 0) { - var _a, _b, _c, _d, _e; - const webglRTWrapper = rtWrapper; - if (this._currentRenderTarget) { - this.unBindFramebuffer(this._currentRenderTarget); - } - this._currentRenderTarget = rtWrapper; - this._bindUnboundFramebuffer(webglRTWrapper._MSAAFramebuffer ? webglRTWrapper._MSAAFramebuffer : webglRTWrapper._framebuffer); - const gl = this._gl; - if (!rtWrapper.isMulti) { - if (rtWrapper.is2DArray) { - gl.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, (_a = rtWrapper.texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource, lodLevel, layer); - } - else if (rtWrapper.isCube) { - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, (_b = rtWrapper.texture._hardwareTexture) === null || _b === void 0 ? void 0 : _b.underlyingResource, lodLevel); - } - } - const depthStencilTexture = rtWrapper._depthStencilTexture; - if (depthStencilTexture) { - const attachment = rtWrapper._depthStencilTextureWithStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; - if (rtWrapper.is2DArray) { - gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, (_c = depthStencilTexture._hardwareTexture) === null || _c === void 0 ? void 0 : _c.underlyingResource, lodLevel, layer); - } - else if (rtWrapper.isCube) { - gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, (_d = depthStencilTexture._hardwareTexture) === null || _d === void 0 ? void 0 : _d.underlyingResource, lodLevel); - } - else { - gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, (_e = depthStencilTexture._hardwareTexture) === null || _e === void 0 ? void 0 : _e.underlyingResource, lodLevel); - } - } - if (this._cachedViewport && !forceFullscreenViewport) { - this.setViewport(this._cachedViewport, requiredWidth, requiredHeight); - } - else { - if (!requiredWidth) { - requiredWidth = rtWrapper.width; - if (lodLevel) { - requiredWidth = requiredWidth / Math.pow(2, lodLevel); - } - } - if (!requiredHeight) { - requiredHeight = rtWrapper.height; - if (lodLevel) { - requiredHeight = requiredHeight / Math.pow(2, lodLevel); - } - } - this._viewport(0, 0, requiredWidth, requiredHeight); - } - this.wipeCaches(); - } - /** - * Set various states to the webGL context - * @param culling defines culling state: true to enable culling, false to disable it - * @param zOffset defines the value to apply to zOffset (0 by default) - * @param force defines if states must be applied even if cache is up to date - * @param reverseSide defines if culling must be reversed (CCW if false, CW if true) - * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled) - * @param stencil stencil states to set - * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default) - */ - setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) { - var _a, _b; - // Culling - if (this._depthCullingState.cull !== culling || force) { - this._depthCullingState.cull = culling; - } - // Cull face - const cullFace = ((_b = (_a = this.cullBackFaces) !== null && _a !== void 0 ? _a : cullBackFaces) !== null && _b !== void 0 ? _b : true) ? this._gl.BACK : this._gl.FRONT; - if (this._depthCullingState.cullFace !== cullFace || force) { - this._depthCullingState.cullFace = cullFace; - } - // Z offset - this.setZOffset(zOffset); - this.setZOffsetUnits(zOffsetUnits); - // Front face - const frontFace = reverseSide ? this._gl.CW : this._gl.CCW; - if (this._depthCullingState.frontFace !== frontFace || force) { - this._depthCullingState.frontFace = frontFace; - } - this._stencilStateComposer.stencilMaterial = stencil; - } - /** - * Gets a boolean indicating if depth testing is enabled - * @returns the current state - */ - getDepthBuffer() { - return this._depthCullingState.depthTest; - } - /** - * Enable or disable depth buffering - * @param enable defines the state to set - */ - setDepthBuffer(enable) { - this._depthCullingState.depthTest = enable; - } - /** - * Set the z offset Factor to apply to current rendering - * @param value defines the offset to apply - */ - setZOffset(value) { - this._depthCullingState.zOffset = this.useReverseDepthBuffer ? -value : value; - } - /** - * Gets the current value of the zOffset Factor - * @returns the current zOffset Factor state - */ - getZOffset() { - const zOffset = this._depthCullingState.zOffset; - return this.useReverseDepthBuffer ? -zOffset : zOffset; - } - /** - * Set the z offset Units to apply to current rendering - * @param value defines the offset to apply - */ - setZOffsetUnits(value) { - this._depthCullingState.zOffsetUnits = this.useReverseDepthBuffer ? -value : value; - } - /** - * Gets the current value of the zOffset Units - * @returns the current zOffset Units state - */ - getZOffsetUnits() { - const zOffsetUnits = this._depthCullingState.zOffsetUnits; - return this.useReverseDepthBuffer ? -zOffsetUnits : zOffsetUnits; - } - /** - * @internal - */ - _bindUnboundFramebuffer(framebuffer) { - if (this._currentFramebuffer !== framebuffer) { - this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer); - this._currentFramebuffer = framebuffer; - } - } - /** @internal */ - _currentFrameBufferIsDefaultFrameBuffer() { - return this._currentFramebuffer === null; - } - /** - * Generates the mipmaps for a texture - * @param texture texture to generate the mipmaps for - */ - generateMipmaps(texture) { - this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); - this._gl.generateMipmap(this._gl.TEXTURE_2D); - this._bindTextureDirectly(this._gl.TEXTURE_2D, null); - } - /** - * Unbind the current render target texture from the webGL context - * @param texture defines the render target wrapper to unbind - * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated - * @param onBeforeUnbind defines a function which will be called before the effective unbind - */ - unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) { - var _a; - const webglRTWrapper = texture; - this._currentRenderTarget = null; - // If MSAA, we need to bitblt back to main texture - const gl = this._gl; - if (webglRTWrapper._MSAAFramebuffer) { - if (texture.isMulti) { - // This texture is part of a MRT texture, we need to treat all attachments - this.unBindMultiColorAttachmentFramebuffer(texture, disableGenerateMipMaps, onBeforeUnbind); - return; - } - gl.bindFramebuffer(gl.READ_FRAMEBUFFER, webglRTWrapper._MSAAFramebuffer); - gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, webglRTWrapper._framebuffer); - gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST); - } - if (((_a = texture.texture) === null || _a === void 0 ? void 0 : _a.generateMipMaps) && !disableGenerateMipMaps && !texture.isCube) { - this.generateMipmaps(texture.texture); - } - if (onBeforeUnbind) { - if (webglRTWrapper._MSAAFramebuffer) { - // Bind the correct framebuffer - this._bindUnboundFramebuffer(webglRTWrapper._framebuffer); - } - onBeforeUnbind(); - } - this._bindUnboundFramebuffer(null); - } - /** - * Force a webGL flush (ie. a flush of all waiting webGL commands) - */ - flushFramebuffer() { - this._gl.flush(); - } - /** - * Unbind the current render target and bind the default framebuffer - */ - restoreDefaultFramebuffer() { - if (this._currentRenderTarget) { - this.unBindFramebuffer(this._currentRenderTarget); - } - else { - this._bindUnboundFramebuffer(null); - } - if (this._cachedViewport) { - this.setViewport(this._cachedViewport); - } - this.wipeCaches(); - } - // VBOs - /** @internal */ - _resetVertexBufferBinding() { - this.bindArrayBuffer(null); - this._cachedVertexBuffers = null; - } - /** - * Creates a vertex buffer - * @param data the data for the vertex buffer - * @returns the new WebGL static buffer - */ - createVertexBuffer(data) { - return this._createVertexBuffer(data, this._gl.STATIC_DRAW); - } - _createVertexBuffer(data, usage) { - const vbo = this._gl.createBuffer(); - if (!vbo) { - throw new Error("Unable to create vertex buffer"); - } - const dataBuffer = new WebGLDataBuffer(vbo); - this.bindArrayBuffer(dataBuffer); - if (data instanceof Array) { - this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), usage); - } - else { - this._gl.bufferData(this._gl.ARRAY_BUFFER, data, usage); - } - this._resetVertexBufferBinding(); - dataBuffer.references = 1; - return dataBuffer; - } - /** - * Creates a dynamic vertex buffer - * @param data the data for the dynamic vertex buffer - * @returns the new WebGL dynamic buffer - */ - createDynamicVertexBuffer(data) { - return this._createVertexBuffer(data, this._gl.DYNAMIC_DRAW); - } - _resetIndexBufferBinding() { - this.bindIndexBuffer(null); - this._cachedIndexBuffer = null; - } - /** - * Creates a new index buffer - * @param indices defines the content of the index buffer - * @param updatable defines if the index buffer must be updatable - * @returns a new webGL buffer - */ - createIndexBuffer(indices, updatable) { - const vbo = this._gl.createBuffer(); - const dataBuffer = new WebGLDataBuffer(vbo); - if (!vbo) { - throw new Error("Unable to create index buffer"); - } - this.bindIndexBuffer(dataBuffer); - const data = this._normalizeIndexData(indices); - this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, data, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW); - this._resetIndexBufferBinding(); - dataBuffer.references = 1; - dataBuffer.is32Bits = data.BYTES_PER_ELEMENT === 4; - return dataBuffer; - } - _normalizeIndexData(indices) { - const bytesPerElement = indices.BYTES_PER_ELEMENT; - if (bytesPerElement === 2) { - return indices; - } - // Check 32 bit support - if (this._caps.uintIndices) { - if (indices instanceof Uint32Array) { - return indices; - } - else { - // number[] or Int32Array, check if 32 bit is necessary - for (let index = 0; index < indices.length; index++) { - if (indices[index] >= 65535) { - return new Uint32Array(indices); - } - } - return new Uint16Array(indices); - } - } - // No 32 bit support, force conversion to 16 bit (values greater 16 bit are lost) - return new Uint16Array(indices); - } - /** - * Bind a webGL buffer to the webGL context - * @param buffer defines the buffer to bind - */ - bindArrayBuffer(buffer) { - if (!this._vaoRecordInProgress) { - this._unbindVertexArrayObject(); - } - this._bindBuffer(buffer, this._gl.ARRAY_BUFFER); - } - /** - * Bind a specific block at a given index in a specific shader program - * @param pipelineContext defines the pipeline context to use - * @param blockName defines the block name - * @param index defines the index where to bind the block - */ - bindUniformBlock(pipelineContext, blockName, index) { - const program = pipelineContext.program; - const uniformLocation = this._gl.getUniformBlockIndex(program, blockName); - this._gl.uniformBlockBinding(program, uniformLocation, index); - } - // eslint-disable-next-line @typescript-eslint/naming-convention - bindIndexBuffer(buffer) { - if (!this._vaoRecordInProgress) { - this._unbindVertexArrayObject(); - } - this._bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER); - } - _bindBuffer(buffer, target) { - if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) { - this._gl.bindBuffer(target, buffer ? buffer.underlyingResource : null); - this._currentBoundBuffer[target] = buffer; - } - } - /** - * update the bound buffer with the given data - * @param data defines the data to update - */ - updateArrayBuffer(data) { - this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); - } - _vertexAttribPointer(buffer, indx, size, type, normalized, stride, offset) { - const pointer = this._currentBufferPointers[indx]; - if (!pointer) { - return; - } - let changed = false; - if (!pointer.active) { - changed = true; - pointer.active = true; - pointer.index = indx; - pointer.size = size; - pointer.type = type; - pointer.normalized = normalized; - pointer.stride = stride; - pointer.offset = offset; - pointer.buffer = buffer; - } - else { - if (pointer.buffer !== buffer) { - pointer.buffer = buffer; - changed = true; - } - if (pointer.size !== size) { - pointer.size = size; - changed = true; - } - if (pointer.type !== type) { - pointer.type = type; - changed = true; - } - if (pointer.normalized !== normalized) { - pointer.normalized = normalized; - changed = true; - } - if (pointer.stride !== stride) { - pointer.stride = stride; - changed = true; - } - if (pointer.offset !== offset) { - pointer.offset = offset; - changed = true; - } - } - if (changed || this._vaoRecordInProgress) { - this.bindArrayBuffer(buffer); - if (type === this._gl.UNSIGNED_INT || type === this._gl.INT) { - this._gl.vertexAttribIPointer(indx, size, type, stride, offset); - } - else { - this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset); - } - } - } - /** - * @internal - */ - _bindIndexBufferWithCache(indexBuffer) { - if (indexBuffer == null) { - return; - } - if (this._cachedIndexBuffer !== indexBuffer) { - this._cachedIndexBuffer = indexBuffer; - this.bindIndexBuffer(indexBuffer); - this._uintIndicesCurrentlySet = indexBuffer.is32Bits; - } - } - _bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers) { - const attributes = effect.getAttributesNames(); - if (!this._vaoRecordInProgress) { - this._unbindVertexArrayObject(); - } - this.unbindAllAttributes(); - for (let index = 0; index < attributes.length; index++) { - const order = effect.getAttributeLocation(index); - if (order >= 0) { - const ai = attributes[index]; - let vertexBuffer = null; - if (overrideVertexBuffers) { - vertexBuffer = overrideVertexBuffers[ai]; - } - if (!vertexBuffer) { - vertexBuffer = vertexBuffers[ai]; - } - if (!vertexBuffer) { - continue; - } - this._gl.enableVertexAttribArray(order); - if (!this._vaoRecordInProgress) { - this._vertexAttribArraysEnabled[order] = true; - } - const buffer = vertexBuffer.getBuffer(); - if (buffer) { - this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset); - if (vertexBuffer.getIsInstanced()) { - this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor()); - if (!this._vaoRecordInProgress) { - this._currentInstanceLocations.push(order); - this._currentInstanceBuffers.push(buffer); - } - } - } - } - } - } - /** - * Records a vertex array object - * @see https://doc.babylonjs.com/setup/support/webGL2#vertex-array-objects - * @param vertexBuffers defines the list of vertex buffers to store - * @param indexBuffer defines the index buffer to store - * @param effect defines the effect to store - * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers - * @returns the new vertex array object - */ - recordVertexArrayObject(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { - const vao = this._gl.createVertexArray(); - if (!vao) { - throw new Error("Unable to create VAO"); - } - this._vaoRecordInProgress = true; - this._gl.bindVertexArray(vao); - this._mustWipeVertexAttributes = true; - this._bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers); - this.bindIndexBuffer(indexBuffer); - this._vaoRecordInProgress = false; - this._gl.bindVertexArray(null); - return vao; - } - /** - * Bind a specific vertex array object - * @see https://doc.babylonjs.com/setup/support/webGL2#vertex-array-objects - * @param vertexArrayObject defines the vertex array object to bind - * @param indexBuffer defines the index buffer to bind - */ - bindVertexArrayObject(vertexArrayObject, indexBuffer) { - if (this._cachedVertexArrayObject !== vertexArrayObject) { - this._cachedVertexArrayObject = vertexArrayObject; - this._gl.bindVertexArray(vertexArrayObject); - this._cachedVertexBuffers = null; - this._cachedIndexBuffer = null; - this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits; - this._mustWipeVertexAttributes = true; - } - } - /** - * Bind webGl buffers directly to the webGL context - * @param vertexBuffer defines the vertex buffer to bind - * @param indexBuffer defines the index buffer to bind - * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer - * @param vertexStrideSize defines the vertex stride of the vertex buffer - * @param effect defines the effect associated with the vertex buffer - */ - bindBuffersDirectly(vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) { - if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) { - this._cachedVertexBuffers = vertexBuffer; - this._cachedEffectForVertexBuffers = effect; - const attributesCount = effect.getAttributesCount(); - this._unbindVertexArrayObject(); - this.unbindAllAttributes(); - let offset = 0; - for (let index = 0; index < attributesCount; index++) { - if (index < vertexDeclaration.length) { - const order = effect.getAttributeLocation(index); - if (order >= 0) { - this._gl.enableVertexAttribArray(order); - this._vertexAttribArraysEnabled[order] = true; - this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset); - } - offset += vertexDeclaration[index] * 4; - } - } - } - this._bindIndexBufferWithCache(indexBuffer); - } - _unbindVertexArrayObject() { - if (!this._cachedVertexArrayObject) { - return; - } - this._cachedVertexArrayObject = null; - this._gl.bindVertexArray(null); - } - /** - * Bind a list of vertex buffers to the webGL context - * @param vertexBuffers defines the list of vertex buffers to bind - * @param indexBuffer defines the index buffer to bind - * @param effect defines the effect associated with the vertex buffers - * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers - */ - bindBuffers(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { - if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) { - this._cachedVertexBuffers = vertexBuffers; - this._cachedEffectForVertexBuffers = effect; - this._bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers); - } - this._bindIndexBufferWithCache(indexBuffer); - } - /** - * Unbind all instance attributes - */ - unbindInstanceAttributes() { - let boundBuffer; - for (let i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) { - const instancesBuffer = this._currentInstanceBuffers[i]; - if (boundBuffer != instancesBuffer && instancesBuffer.references) { - boundBuffer = instancesBuffer; - this.bindArrayBuffer(instancesBuffer); - } - const offsetLocation = this._currentInstanceLocations[i]; - this._gl.vertexAttribDivisor(offsetLocation, 0); - } - this._currentInstanceBuffers.length = 0; - this._currentInstanceLocations.length = 0; - } - /** - * Release and free the memory of a vertex array object - * @param vao defines the vertex array object to delete - */ - releaseVertexArrayObject(vao) { - this._gl.deleteVertexArray(vao); - } - /** - * @internal - */ - _releaseBuffer(buffer) { - buffer.references--; - if (buffer.references === 0) { - this._deleteBuffer(buffer); - return true; - } - return false; - } - _deleteBuffer(buffer) { - this._gl.deleteBuffer(buffer.underlyingResource); - } - /** - * Update the content of a webGL buffer used with instantiation and bind it to the webGL context - * @param instancesBuffer defines the webGL buffer to update and bind - * @param data defines the data to store in the buffer - * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer - */ - updateAndBindInstancesBuffer(instancesBuffer, data, offsetLocations) { - this.bindArrayBuffer(instancesBuffer); - if (data) { - this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); - } - if (offsetLocations[0].index !== undefined) { - this.bindInstancesBuffer(instancesBuffer, offsetLocations, true); - } - else { - for (let index = 0; index < 4; index++) { - const offsetLocation = offsetLocations[index]; - if (!this._vertexAttribArraysEnabled[offsetLocation]) { - this._gl.enableVertexAttribArray(offsetLocation); - this._vertexAttribArraysEnabled[offsetLocation] = true; - } - this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16); - this._gl.vertexAttribDivisor(offsetLocation, 1); - this._currentInstanceLocations.push(offsetLocation); - this._currentInstanceBuffers.push(instancesBuffer); - } - } - } - /** - * Bind the content of a webGL buffer used with instantiation - * @param instancesBuffer defines the webGL buffer to bind - * @param attributesInfo defines the offsets or attributes information used to determine where data must be stored in the buffer - * @param computeStride defines Whether to compute the strides from the info or use the default 0 - */ - bindInstancesBuffer(instancesBuffer, attributesInfo, computeStride = true) { - this.bindArrayBuffer(instancesBuffer); - let stride = 0; - if (computeStride) { - for (let i = 0; i < attributesInfo.length; i++) { - const ai = attributesInfo[i]; - stride += ai.attributeSize * 4; - } - } - for (let i = 0; i < attributesInfo.length; i++) { - const ai = attributesInfo[i]; - if (ai.index === undefined) { - ai.index = this._currentEffect.getAttributeLocationByName(ai.attributeName); - } - if (ai.index < 0) { - continue; - } - if (!this._vertexAttribArraysEnabled[ai.index]) { - this._gl.enableVertexAttribArray(ai.index); - this._vertexAttribArraysEnabled[ai.index] = true; - } - this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attributeType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset); - this._gl.vertexAttribDivisor(ai.index, ai.divisor === undefined ? 1 : ai.divisor); - this._currentInstanceLocations.push(ai.index); - this._currentInstanceBuffers.push(instancesBuffer); - } - } - /** - * Disable the instance attribute corresponding to the name in parameter - * @param name defines the name of the attribute to disable - */ - disableInstanceAttributeByName(name) { - if (!this._currentEffect) { - return; - } - const attributeLocation = this._currentEffect.getAttributeLocationByName(name); - this.disableInstanceAttribute(attributeLocation); - } - /** - * Disable the instance attribute corresponding to the location in parameter - * @param attributeLocation defines the attribute location of the attribute to disable - */ - disableInstanceAttribute(attributeLocation) { - let shouldClean = false; - let index; - while ((index = this._currentInstanceLocations.indexOf(attributeLocation)) !== -1) { - this._currentInstanceLocations.splice(index, 1); - this._currentInstanceBuffers.splice(index, 1); - shouldClean = true; - index = this._currentInstanceLocations.indexOf(attributeLocation); - } - if (shouldClean) { - this._gl.vertexAttribDivisor(attributeLocation, 0); - this.disableAttributeByIndex(attributeLocation); - } - } - /** - * Disable the attribute corresponding to the location in parameter - * @param attributeLocation defines the attribute location of the attribute to disable - */ - disableAttributeByIndex(attributeLocation) { - this._gl.disableVertexAttribArray(attributeLocation); - this._vertexAttribArraysEnabled[attributeLocation] = false; - this._currentBufferPointers[attributeLocation].active = false; - } - /** - * Send a draw order - * @param useTriangles defines if triangles must be used to draw (else wireframe will be used) - * @param indexStart defines the starting index - * @param indexCount defines the number of index to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - draw(useTriangles, indexStart, indexCount, instancesCount) { - this.drawElementsType(useTriangles ? 0 : 1, indexStart, indexCount, instancesCount); - } - /** - * Draw a list of points - * @param verticesStart defines the index of first vertex to draw - * @param verticesCount defines the count of vertices to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - drawPointClouds(verticesStart, verticesCount, instancesCount) { - this.drawArraysType(2, verticesStart, verticesCount, instancesCount); - } - /** - * Draw a list of unindexed primitives - * @param useTriangles defines if triangles must be used to draw (else wireframe will be used) - * @param verticesStart defines the index of first vertex to draw - * @param verticesCount defines the count of vertices to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - drawUnIndexed(useTriangles, verticesStart, verticesCount, instancesCount) { - this.drawArraysType(useTriangles ? 0 : 1, verticesStart, verticesCount, instancesCount); - } - /** - * Draw a list of indexed primitives - * @param fillMode defines the primitive to use - * @param indexStart defines the starting index - * @param indexCount defines the number of index to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - drawElementsType(fillMode, indexStart, indexCount, instancesCount) { - // Apply states - this.applyStates(); - this._reportDrawCall(); - // Render - const drawMode = this._drawMode(fillMode); - const indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT; - const mult = this._uintIndicesCurrentlySet ? 4 : 2; - if (instancesCount) { - this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount); - } - else { - this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult); - } - } - /** - * Draw a list of unindexed primitives - * @param fillMode defines the primitive to use - * @param verticesStart defines the index of first vertex to draw - * @param verticesCount defines the count of vertices to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) { - // Apply states - this.applyStates(); - this._reportDrawCall(); - const drawMode = this._drawMode(fillMode); - if (instancesCount) { - this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount); - } - else { - this._gl.drawArrays(drawMode, verticesStart, verticesCount); - } - } - _drawMode(fillMode) { - switch (fillMode) { - // Triangle views - case 0: - return this._gl.TRIANGLES; - case 2: - return this._gl.POINTS; - case 1: - return this._gl.LINES; - // Draw modes - case 3: - return this._gl.POINTS; - case 4: - return this._gl.LINES; - case 5: - return this._gl.LINE_LOOP; - case 6: - return this._gl.LINE_STRIP; - case 7: - return this._gl.TRIANGLE_STRIP; - case 8: - return this._gl.TRIANGLE_FAN; - default: - return this._gl.TRIANGLES; - } - } - /** @internal */ - _reportDrawCall() { - // Will be implemented by children - } - // Shaders - /** - * @internal - */ - _releaseEffect(effect) { - if (this._compiledEffects[effect._key]) { - delete this._compiledEffects[effect._key]; - } - const pipelineContext = effect.getPipelineContext(); - if (pipelineContext) { - this._deletePipelineContext(pipelineContext); - } - } - /** - * @internal - */ - _deletePipelineContext(pipelineContext) { - const webGLPipelineContext = pipelineContext; - if (webGLPipelineContext && webGLPipelineContext.program) { - webGLPipelineContext.program.__SPECTOR_rebuildProgram = null; - this._gl.deleteProgram(webGLPipelineContext.program); - } - } - /** @internal */ - _getGlobalDefines(defines) { - if (defines) { - if (this.isNDCHalfZRange) { - defines["IS_NDC_HALF_ZRANGE"] = ""; - } - else { - delete defines["IS_NDC_HALF_ZRANGE"]; - } - if (this.useReverseDepthBuffer) { - defines["USE_REVERSE_DEPTHBUFFER"] = ""; - } - else { - delete defines["USE_REVERSE_DEPTHBUFFER"]; - } - if (this.useExactSrgbConversions) { - defines["USE_EXACT_SRGB_CONVERSIONS"] = ""; - } - else { - delete defines["USE_EXACT_SRGB_CONVERSIONS"]; - } - return; - } - else { - let s = ""; - if (this.isNDCHalfZRange) { - s += "#define IS_NDC_HALF_ZRANGE"; - } - if (this.useReverseDepthBuffer) { - if (s) { - s += "\n"; - } - s += "#define USE_REVERSE_DEPTHBUFFER"; - } - if (this.useExactSrgbConversions) { - if (s) { - s += "\n"; - } - s += "#define USE_EXACT_SRGB_CONVERSIONS"; - } - return s; - } - } - /** - * Create a new effect (used to store vertex/fragment shaders) - * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx) - * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object - * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use - * @param samplers defines an array of string used to represent textures - * @param defines defines the string containing the defines to use to compile the shaders - * @param fallbacks defines the list of potential fallbacks to use if shader compilation fails - * @param onCompiled defines a function to call when the effect creation is successful - * @param onError defines a function to call when the effect creation has failed - * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights) - * @param shaderLanguage the language the shader is written in (default: GLSL) - * @returns the new Effect - */ - createEffect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters, shaderLanguage = ShaderLanguage.GLSL) { - var _a; - const vertex = baseName.vertexElement || baseName.vertex || baseName.vertexToken || baseName.vertexSource || baseName; - const fragment = baseName.fragmentElement || baseName.fragment || baseName.fragmentToken || baseName.fragmentSource || baseName; - const globalDefines = this._getGlobalDefines(); - let fullDefines = (_a = defines !== null && defines !== void 0 ? defines : attributesNamesOrOptions.defines) !== null && _a !== void 0 ? _a : ""; - if (globalDefines) { - fullDefines += globalDefines; - } - const name = vertex + "+" + fragment + "@" + fullDefines; - if (this._compiledEffects[name]) { - const compiledEffect = this._compiledEffects[name]; - if (onCompiled && compiledEffect.isReady()) { - onCompiled(compiledEffect); - } - return compiledEffect; - } - const effect = new effect_Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, shaderLanguage); - this._compiledEffects[name] = effect; - return effect; - } - // eslint-disable-next-line @typescript-eslint/naming-convention - static _ConcatenateShader(source, defines, shaderVersion = "") { - return shaderVersion + (defines ? defines + "\n" : "") + source; - } - _compileShader(source, type, defines, shaderVersion) { - return this._compileRawShader(ThinEngine._ConcatenateShader(source, defines, shaderVersion), type); - } - _compileRawShader(source, type) { - const gl = this._gl; - const shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER); - if (!shader) { - let error = gl.NO_ERROR; - let tempError = gl.NO_ERROR; - while ((tempError = gl.getError()) !== gl.NO_ERROR) { - error = tempError; - } - throw new Error(`Something went wrong while creating a gl ${type} shader object. gl error=${error}, gl isContextLost=${gl.isContextLost()}, _contextWasLost=${this._contextWasLost}`); - } - gl.shaderSource(shader, source); - gl.compileShader(shader); - return shader; - } - /** - * @internal - */ - _getShaderSource(shader) { - return this._gl.getShaderSource(shader); - } - /** - * Directly creates a webGL program - * @param pipelineContext defines the pipeline context to attach to - * @param vertexCode defines the vertex shader code to use - * @param fragmentCode defines the fragment shader code to use - * @param context defines the webGL context to use (if not set, the current one will be used) - * @param transformFeedbackVaryings defines the list of transform feedback varyings to use - * @returns the new webGL program - */ - createRawShaderProgram(pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings = null) { - context = context || this._gl; - const vertexShader = this._compileRawShader(vertexCode, "vertex"); - const fragmentShader = this._compileRawShader(fragmentCode, "fragment"); - return this._createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings); - } - /** - * Creates a webGL program - * @param pipelineContext defines the pipeline context to attach to - * @param vertexCode defines the vertex shader code to use - * @param fragmentCode defines the fragment shader code to use - * @param defines defines the string containing the defines to use to compile the shaders - * @param context defines the webGL context to use (if not set, the current one will be used) - * @param transformFeedbackVaryings defines the list of transform feedback varyings to use - * @returns the new webGL program - */ - createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) { - context = context || this._gl; - const shaderVersion = this._webGLVersion > 1 ? "#version 300 es\n#define WEBGL2 \n" : ""; - const vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion); - const fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion); - return this._createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings); - } - /** - * Inline functions in shader code that are marked to be inlined - * @param code code to inline - * @returns inlined code - */ - inlineShaderCode(code) { - // no inlining needed in the WebGL engine - return code; - } - /** - * Creates a new pipeline context - * @param shaderProcessingContext defines the shader processing context used during the processing if available - * @returns the new pipeline - */ - createPipelineContext(shaderProcessingContext) { - const pipelineContext = new WebGLPipelineContext(); - pipelineContext.engine = this; - if (this._caps.parallelShaderCompile) { - pipelineContext.isParallelCompiled = true; - } - return pipelineContext; - } - /** - * Creates a new material context - * @returns the new context - */ - createMaterialContext() { - return undefined; - } - /** - * Creates a new draw context - * @returns the new context - */ - createDrawContext() { - return undefined; - } - _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings = null) { - const shaderProgram = context.createProgram(); - pipelineContext.program = shaderProgram; - if (!shaderProgram) { - throw new Error("Unable to create program"); - } - context.attachShader(shaderProgram, vertexShader); - context.attachShader(shaderProgram, fragmentShader); - context.linkProgram(shaderProgram); - pipelineContext.context = context; - pipelineContext.vertexShader = vertexShader; - pipelineContext.fragmentShader = fragmentShader; - if (!pipelineContext.isParallelCompiled) { - this._finalizePipelineContext(pipelineContext); - } - return shaderProgram; - } - _finalizePipelineContext(pipelineContext) { - const context = pipelineContext.context; - const vertexShader = pipelineContext.vertexShader; - const fragmentShader = pipelineContext.fragmentShader; - const program = pipelineContext.program; - const linked = context.getProgramParameter(program, context.LINK_STATUS); - if (!linked) { - // Get more info - // Vertex - if (!this._gl.getShaderParameter(vertexShader, this._gl.COMPILE_STATUS)) { - const log = this._gl.getShaderInfoLog(vertexShader); - if (log) { - pipelineContext.vertexCompilationError = log; - throw new Error("VERTEX SHADER " + log); - } - } - // Fragment - if (!this._gl.getShaderParameter(fragmentShader, this._gl.COMPILE_STATUS)) { - const log = this._gl.getShaderInfoLog(fragmentShader); - if (log) { - pipelineContext.fragmentCompilationError = log; - throw new Error("FRAGMENT SHADER " + log); - } - } - const error = context.getProgramInfoLog(program); - if (error) { - pipelineContext.programLinkError = error; - throw new Error(error); - } - } - if (this.validateShaderPrograms) { - context.validateProgram(program); - const validated = context.getProgramParameter(program, context.VALIDATE_STATUS); - if (!validated) { - const error = context.getProgramInfoLog(program); - if (error) { - pipelineContext.programValidationError = error; - throw new Error(error); - } - } - } - context.deleteShader(vertexShader); - context.deleteShader(fragmentShader); - pipelineContext.vertexShader = undefined; - pipelineContext.fragmentShader = undefined; - if (pipelineContext.onCompiled) { - pipelineContext.onCompiled(); - pipelineContext.onCompiled = undefined; - } - } - /** - * @internal - */ - _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, rebuildRebind, defines, transformFeedbackVaryings, key) { - const webGLRenderingState = pipelineContext; - if (createAsRaw) { - webGLRenderingState.program = this.createRawShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings); - } - else { - webGLRenderingState.program = this.createShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings); - } - webGLRenderingState.program.__SPECTOR_rebuildProgram = rebuildRebind; - } - /** - * @internal - */ - _isRenderingStateCompiled(pipelineContext) { - const webGLPipelineContext = pipelineContext; - if (this._isDisposed || webGLPipelineContext._isDisposed) { - return false; - } - if (this._gl.getProgramParameter(webGLPipelineContext.program, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) { - this._finalizePipelineContext(webGLPipelineContext); - return true; - } - return false; - } - /** - * @internal - */ - _executeWhenRenderingStateIsCompiled(pipelineContext, action) { - const webGLPipelineContext = pipelineContext; - if (!webGLPipelineContext.isParallelCompiled) { - action(); - return; - } - const oldHandler = webGLPipelineContext.onCompiled; - if (oldHandler) { - webGLPipelineContext.onCompiled = () => { - oldHandler(); - action(); - }; - } - else { - webGLPipelineContext.onCompiled = action; - } - } - /** - * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names - * @param pipelineContext defines the pipeline context to use - * @param uniformsNames defines the list of uniform names - * @returns an array of webGL uniform locations - */ - getUniforms(pipelineContext, uniformsNames) { - const results = new Array(); - const webGLPipelineContext = pipelineContext; - for (let index = 0; index < uniformsNames.length; index++) { - results.push(this._gl.getUniformLocation(webGLPipelineContext.program, uniformsNames[index])); - } - return results; - } - /** - * Gets the list of active attributes for a given webGL program - * @param pipelineContext defines the pipeline context to use - * @param attributesNames defines the list of attribute names to get - * @returns an array of indices indicating the offset of each attribute - */ - getAttributes(pipelineContext, attributesNames) { - const results = []; - const webGLPipelineContext = pipelineContext; - for (let index = 0; index < attributesNames.length; index++) { - try { - results.push(this._gl.getAttribLocation(webGLPipelineContext.program, attributesNames[index])); - } - catch (e) { - results.push(-1); - } - } - return results; - } - /** - * Activates an effect, making it the current one (ie. the one used for rendering) - * @param effect defines the effect to activate - */ - enableEffect(effect) { - effect = effect !== null && drawWrapper_DrawWrapper.IsWrapper(effect) ? effect.effect : effect; // get only the effect, we don't need a Wrapper in the WebGL engine - if (!effect || effect === this._currentEffect) { - return; - } - this._stencilStateComposer.stencilMaterial = undefined; - effect = effect; - // Use program - this.bindSamplers(effect); - this._currentEffect = effect; - if (effect.onBind) { - effect.onBind(effect); - } - if (effect._onBindObservable) { - effect._onBindObservable.notifyObservers(effect); - } - } - /** - * Set the value of an uniform to a number (int) - * @param uniform defines the webGL uniform location where to store the value - * @param value defines the int number to store - * @returns true if the value was set - */ - setInt(uniform, value) { - if (!uniform) { - return false; - } - this._gl.uniform1i(uniform, value); - return true; - } - /** - * Set the value of an uniform to a int2 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @returns true if the value was set - */ - setInt2(uniform, x, y) { - if (!uniform) { - return false; - } - this._gl.uniform2i(uniform, x, y); - return true; - } - /** - * Set the value of an uniform to a int3 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @param z defines the 3rd component of the value - * @returns true if the value was set - */ - setInt3(uniform, x, y, z) { - if (!uniform) { - return false; - } - this._gl.uniform3i(uniform, x, y, z); - return true; - } - /** - * Set the value of an uniform to a int4 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @param z defines the 3rd component of the value - * @param w defines the 4th component of the value - * @returns true if the value was set - */ - setInt4(uniform, x, y, z, w) { - if (!uniform) { - return false; - } - this._gl.uniform4i(uniform, x, y, z, w); - return true; - } - /** - * Set the value of an uniform to an array of int32 - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of int32 to store - * @returns true if the value was set - */ - setIntArray(uniform, array) { - if (!uniform) { - return false; - } - this._gl.uniform1iv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of int32 (stored as vec2) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of int32 to store - * @returns true if the value was set - */ - setIntArray2(uniform, array) { - if (!uniform || array.length % 2 !== 0) { - return false; - } - this._gl.uniform2iv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of int32 (stored as vec3) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of int32 to store - * @returns true if the value was set - */ - setIntArray3(uniform, array) { - if (!uniform || array.length % 3 !== 0) { - return false; - } - this._gl.uniform3iv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of int32 (stored as vec4) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of int32 to store - * @returns true if the value was set - */ - setIntArray4(uniform, array) { - if (!uniform || array.length % 4 !== 0) { - return false; - } - this._gl.uniform4iv(uniform, array); - return true; - } - /** - * Set the value of an uniform to a number (unsigned int) - * @param uniform defines the webGL uniform location where to store the value - * @param value defines the unsigned int number to store - * @returns true if the value was set - */ - setUInt(uniform, value) { - if (!uniform) { - return false; - } - this._gl.uniform1ui(uniform, value); - return true; - } - /** - * Set the value of an uniform to a unsigned int2 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @returns true if the value was set - */ - setUInt2(uniform, x, y) { - if (!uniform) { - return false; - } - this._gl.uniform2ui(uniform, x, y); - return true; - } - /** - * Set the value of an uniform to a unsigned int3 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @param z defines the 3rd component of the value - * @returns true if the value was set - */ - setUInt3(uniform, x, y, z) { - if (!uniform) { - return false; - } - this._gl.uniform3ui(uniform, x, y, z); - return true; - } - /** - * Set the value of an uniform to a unsigned int4 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @param z defines the 3rd component of the value - * @param w defines the 4th component of the value - * @returns true if the value was set - */ - setUInt4(uniform, x, y, z, w) { - if (!uniform) { - return false; - } - this._gl.uniform4ui(uniform, x, y, z, w); - return true; - } - /** - * Set the value of an uniform to an array of unsigned int32 - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of unsigned int32 to store - * @returns true if the value was set - */ - setUIntArray(uniform, array) { - if (!uniform) { - return false; - } - this._gl.uniform1uiv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of unsigned int32 (stored as vec2) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of unsigned int32 to store - * @returns true if the value was set - */ - setUIntArray2(uniform, array) { - if (!uniform || array.length % 2 !== 0) { - return false; - } - this._gl.uniform2uiv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of unsigned int32 (stored as vec3) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of unsigned int32 to store - * @returns true if the value was set - */ - setUIntArray3(uniform, array) { - if (!uniform || array.length % 3 !== 0) { - return false; - } - this._gl.uniform3uiv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of unsigned int32 (stored as vec4) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of unsigned int32 to store - * @returns true if the value was set - */ - setUIntArray4(uniform, array) { - if (!uniform || array.length % 4 !== 0) { - return false; - } - this._gl.uniform4uiv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of number - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of number to store - * @returns true if the value was set - */ - setArray(uniform, array) { - if (!uniform) { - return false; - } - if (array.length < 1) { - return false; - } - this._gl.uniform1fv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of number (stored as vec2) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of number to store - * @returns true if the value was set - */ - setArray2(uniform, array) { - if (!uniform || array.length % 2 !== 0) { - return false; - } - this._gl.uniform2fv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of number (stored as vec3) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of number to store - * @returns true if the value was set - */ - setArray3(uniform, array) { - if (!uniform || array.length % 3 !== 0) { - return false; - } - this._gl.uniform3fv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of number (stored as vec4) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of number to store - * @returns true if the value was set - */ - setArray4(uniform, array) { - if (!uniform || array.length % 4 !== 0) { - return false; - } - this._gl.uniform4fv(uniform, array); - return true; - } - /** - * Set the value of an uniform to an array of float32 (stored as matrices) - * @param uniform defines the webGL uniform location where to store the value - * @param matrices defines the array of float32 to store - * @returns true if the value was set - */ - setMatrices(uniform, matrices) { - if (!uniform) { - return false; - } - this._gl.uniformMatrix4fv(uniform, false, matrices); - return true; - } - /** - * Set the value of an uniform to a matrix (3x3) - * @param uniform defines the webGL uniform location where to store the value - * @param matrix defines the Float32Array representing the 3x3 matrix to store - * @returns true if the value was set - */ - setMatrix3x3(uniform, matrix) { - if (!uniform) { - return false; - } - this._gl.uniformMatrix3fv(uniform, false, matrix); - return true; - } - /** - * Set the value of an uniform to a matrix (2x2) - * @param uniform defines the webGL uniform location where to store the value - * @param matrix defines the Float32Array representing the 2x2 matrix to store - * @returns true if the value was set - */ - setMatrix2x2(uniform, matrix) { - if (!uniform) { - return false; - } - this._gl.uniformMatrix2fv(uniform, false, matrix); - return true; - } - /** - * Set the value of an uniform to a number (float) - * @param uniform defines the webGL uniform location where to store the value - * @param value defines the float number to store - * @returns true if the value was transferred - */ - setFloat(uniform, value) { - if (!uniform) { - return false; - } - this._gl.uniform1f(uniform, value); - return true; - } - /** - * Set the value of an uniform to a vec2 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @returns true if the value was set - */ - setFloat2(uniform, x, y) { - if (!uniform) { - return false; - } - this._gl.uniform2f(uniform, x, y); - return true; - } - /** - * Set the value of an uniform to a vec3 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @param z defines the 3rd component of the value - * @returns true if the value was set - */ - setFloat3(uniform, x, y, z) { - if (!uniform) { - return false; - } - this._gl.uniform3f(uniform, x, y, z); - return true; - } - /** - * Set the value of an uniform to a vec4 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @param z defines the 3rd component of the value - * @param w defines the 4th component of the value - * @returns true if the value was set - */ - setFloat4(uniform, x, y, z, w) { - if (!uniform) { - return false; - } - this._gl.uniform4f(uniform, x, y, z, w); - return true; - } - // States - /** - * Apply all cached states (depth, culling, stencil and alpha) - */ - applyStates() { - this._depthCullingState.apply(this._gl); - this._stencilStateComposer.apply(this._gl); - this._alphaState.apply(this._gl); - if (this._colorWriteChanged) { - this._colorWriteChanged = false; - const enable = this._colorWrite; - this._gl.colorMask(enable, enable, enable, enable); - } - } - /** - * Enable or disable color writing - * @param enable defines the state to set - */ - setColorWrite(enable) { - if (enable !== this._colorWrite) { - this._colorWriteChanged = true; - this._colorWrite = enable; - } - } - /** - * Gets a boolean indicating if color writing is enabled - * @returns the current color writing state - */ - getColorWrite() { - return this._colorWrite; - } - /** - * Gets the depth culling state manager - */ - get depthCullingState() { - return this._depthCullingState; - } - /** - * Gets the alpha state manager - */ - get alphaState() { - return this._alphaState; - } - /** - * Gets the stencil state manager - */ - get stencilState() { - return this._stencilState; - } - /** - * Gets the stencil state composer - */ - get stencilStateComposer() { - return this._stencilStateComposer; - } - // Textures - /** - * Clears the list of texture accessible through engine. - * This can help preventing texture load conflict due to name collision. - */ - clearInternalTexturesCache() { - this._internalTexturesCache.length = 0; - } - /** - * Force the entire cache to be cleared - * You should not have to use this function unless your engine needs to share the webGL context with another engine - * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states) - */ - wipeCaches(bruteForce) { - if (this.preventCacheWipeBetweenFrames && !bruteForce) { - return; - } - this._currentEffect = null; - this._viewportCached.x = 0; - this._viewportCached.y = 0; - this._viewportCached.z = 0; - this._viewportCached.w = 0; - // Done before in case we clean the attributes - this._unbindVertexArrayObject(); - if (bruteForce) { - this._currentProgram = null; - this.resetTextureCache(); - this._stencilStateComposer.reset(); - this._depthCullingState.reset(); - this._depthCullingState.depthFunc = this._gl.LEQUAL; - this._alphaState.reset(); - this._alphaMode = 1; - this._alphaEquation = 0; - this._colorWrite = true; - this._colorWriteChanged = true; - this._unpackFlipYCached = null; - this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE); - this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); - this._mustWipeVertexAttributes = true; - this.unbindAllAttributes(); - } - this._resetVertexBufferBinding(); - this._cachedIndexBuffer = null; - this._cachedEffectForVertexBuffers = null; - this.bindIndexBuffer(null); - } - /** - * @internal - */ - _getSamplingParameters(samplingMode, generateMipMaps) { - const gl = this._gl; - let magFilter = gl.NEAREST; - let minFilter = gl.NEAREST; - switch (samplingMode) { - case 11: - magFilter = gl.LINEAR; - if (generateMipMaps) { - minFilter = gl.LINEAR_MIPMAP_NEAREST; - } - else { - minFilter = gl.LINEAR; - } - break; - case 3: - magFilter = gl.LINEAR; - if (generateMipMaps) { - minFilter = gl.LINEAR_MIPMAP_LINEAR; - } - else { - minFilter = gl.LINEAR; - } - break; - case 8: - magFilter = gl.NEAREST; - if (generateMipMaps) { - minFilter = gl.NEAREST_MIPMAP_LINEAR; - } - else { - minFilter = gl.NEAREST; - } - break; - case 4: - magFilter = gl.NEAREST; - if (generateMipMaps) { - minFilter = gl.NEAREST_MIPMAP_NEAREST; - } - else { - minFilter = gl.NEAREST; - } - break; - case 5: - magFilter = gl.NEAREST; - if (generateMipMaps) { - minFilter = gl.LINEAR_MIPMAP_NEAREST; - } - else { - minFilter = gl.LINEAR; - } - break; - case 6: - magFilter = gl.NEAREST; - if (generateMipMaps) { - minFilter = gl.LINEAR_MIPMAP_LINEAR; - } - else { - minFilter = gl.LINEAR; - } - break; - case 7: - magFilter = gl.NEAREST; - minFilter = gl.LINEAR; - break; - case 1: - magFilter = gl.NEAREST; - minFilter = gl.NEAREST; - break; - case 9: - magFilter = gl.LINEAR; - if (generateMipMaps) { - minFilter = gl.NEAREST_MIPMAP_NEAREST; - } - else { - minFilter = gl.NEAREST; - } - break; - case 10: - magFilter = gl.LINEAR; - if (generateMipMaps) { - minFilter = gl.NEAREST_MIPMAP_LINEAR; - } - else { - minFilter = gl.NEAREST; - } - break; - case 2: - magFilter = gl.LINEAR; - minFilter = gl.LINEAR; - break; - case 12: - magFilter = gl.LINEAR; - minFilter = gl.NEAREST; - break; - } - return { - min: minFilter, - mag: magFilter, - }; - } - /** @internal */ - _createTexture() { - const texture = this._gl.createTexture(); - if (!texture) { - throw new Error("Unable to create texture"); - } - return texture; - } - /** @internal */ - _createHardwareTexture() { - return new WebGLHardwareTexture(this._createTexture(), this._gl); - } - /** - * Creates an internal texture without binding it to a framebuffer - * @internal - * @param size defines the size of the texture - * @param options defines the options used to create the texture - * @param delayGPUTextureCreation true to delay the texture creation the first time it is really needed. false to create it right away - * @param source source type of the texture - * @returns a new internal texture - */ - _createInternalTexture(size, options, delayGPUTextureCreation = true, source = internalTexture_InternalTextureSource.Unknown) { - var _a; - let generateMipMaps = false; - let type = 0; - let samplingMode = 3; - let format = 5; - let useSRGBBuffer = false; - let samples = 1; - let label; - if (options !== undefined && typeof options === "object") { - generateMipMaps = !!options.generateMipMaps; - type = options.type === undefined ? 0 : options.type; - samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode; - format = options.format === undefined ? 5 : options.format; - useSRGBBuffer = options.useSRGBBuffer === undefined ? false : options.useSRGBBuffer; - samples = (_a = options.samples) !== null && _a !== void 0 ? _a : 1; - label = options.label; - } - else { - generateMipMaps = !!options; - } - useSRGBBuffer && (useSRGBBuffer = this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU)); - if (type === 1 && !this._caps.textureFloatLinearFiltering) { - // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE - samplingMode = 1; - } - else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { - // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE - samplingMode = 1; - } - if (type === 1 && !this._caps.textureFloat) { - type = 0; - logger_Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"); - } - const gl = this._gl; - const texture = new internalTexture_InternalTexture(this, source); - const width = size.width || size; - const height = size.height || size; - const layers = size.layers || 0; - const filters = this._getSamplingParameters(samplingMode, generateMipMaps); - const target = layers !== 0 ? gl.TEXTURE_2D_ARRAY : gl.TEXTURE_2D; - const sizedFormat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer); - const internalFormat = this._getInternalFormat(format); - const textureType = this._getWebGLTextureType(type); - // Bind - this._bindTextureDirectly(target, texture); - if (layers !== 0) { - texture.is2DArray = true; - gl.texImage3D(target, 0, sizedFormat, width, height, layers, 0, internalFormat, textureType, null); - } - else { - gl.texImage2D(target, 0, sizedFormat, width, height, 0, internalFormat, textureType, null); - } - gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filters.mag); - gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filters.min); - gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - // MipMaps - if (generateMipMaps) { - this._gl.generateMipmap(target); - } - this._bindTextureDirectly(target, null); - texture._useSRGBBuffer = useSRGBBuffer; - texture.baseWidth = width; - texture.baseHeight = height; - texture.width = width; - texture.height = height; - texture.depth = layers; - texture.isReady = true; - texture.samples = samples; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.type = type; - texture.format = format; - texture.label = label; - this._internalTexturesCache.push(texture); - return texture; - } - /** - * @internal - */ - _getUseSRGBBuffer(useSRGBBuffer, noMipmap) { - // Generating mipmaps for sRGB textures is not supported in WebGL1 so we must disable the support if mipmaps is enabled - return useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU || noMipmap); - } - _createTextureBase(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, prepareTexture, prepareTextureProcessFunction, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, useSRGBBuffer) { - url = url || ""; - const fromData = url.substr(0, 5) === "data:"; - const fromBlob = url.substr(0, 5) === "blob:"; - const isBase64 = fromData && url.indexOf(";base64,") !== -1; - const texture = fallback ? fallback : new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Url); - if (texture !== fallback) { - texture.label = url.substring(0, 60); // default label, can be overriden by the caller - } - const originalUrl = url; - if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) { - url = this._transformTextureUrl(url); - } - if (originalUrl !== url) { - texture._originalUrl = originalUrl; - } - // establish the file extension, if possible - const lastDot = url.lastIndexOf("."); - let extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : ""; - let loader = null; - // Remove query string - const queryStringIndex = extension.indexOf("?"); - if (queryStringIndex > -1) { - extension = extension.split("?")[0]; - } - for (const availableLoader of ThinEngine._TextureLoaders) { - if (availableLoader.canLoad(extension, mimeType)) { - loader = availableLoader; - break; - } - } - if (scene) { - scene.addPendingData(texture); - } - texture.url = url; - texture.generateMipMaps = !noMipmap; - texture.samplingMode = samplingMode; - texture.invertY = invertY; - texture._useSRGBBuffer = this._getUseSRGBBuffer(!!useSRGBBuffer, noMipmap); - if (!this._doNotHandleContextLost) { - // Keep a link to the buffer only if we plan to handle context lost - texture._buffer = buffer; - } - let onLoadObserver = null; - if (onLoad && !fallback) { - onLoadObserver = texture.onLoadedObservable.add(onLoad); - } - if (!fallback) { - this._internalTexturesCache.push(texture); - } - const onInternalError = (message, exception) => { - if (scene) { - scene.removePendingData(texture); - } - if (url === originalUrl) { - if (onLoadObserver) { - texture.onLoadedObservable.remove(onLoadObserver); - } - if (engineStore_EngineStore.UseFallbackTexture) { - this._createTextureBase(engineStore_EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, prepareTexture, prepareTextureProcessFunction, buffer, texture); - } - message = (message || "Unknown error") + (engineStore_EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""); - texture.onErrorObservable.notifyObservers({ message, exception }); - if (onError) { - onError(message, exception); - } - } - else { - // fall back to the original url if the transformed url fails to load - logger_Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`); - this._createTextureBase(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, prepareTexture, prepareTextureProcessFunction, buffer, texture, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer); - } - }; - // processing for non-image formats - if (loader) { - const callback = (data) => { - loader.loadData(data, texture, (width, height, loadMipmap, isCompressed, done, loadFailed) => { - if (loadFailed) { - onInternalError("TextureLoader failed to load data"); - } - else { - prepareTexture(texture, extension, scene, { width, height }, texture.invertY, !loadMipmap, isCompressed, () => { - done(); - return false; - }, samplingMode); - } - }, loaderOptions); - }; - if (!buffer) { - this._loadFile(url, (data) => callback(new Uint8Array(data)), undefined, scene ? scene.offlineProvider : undefined, true, (request, exception) => { - onInternalError("Unable to load " + (request ? request.responseURL : url, exception)); - }); - } - else { - if (buffer instanceof ArrayBuffer) { - callback(new Uint8Array(buffer)); - } - else if (ArrayBuffer.isView(buffer)) { - callback(buffer); - } - else { - if (onError) { - onError("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null); - } - } - } - } - else { - const onload = (img) => { - if (fromBlob && !this._doNotHandleContextLost) { - // We need to store the image if we need to rebuild the texture - // in case of a webgl context lost - texture._buffer = img; - } - prepareTexture(texture, extension, scene, img, texture.invertY, noMipmap, false, prepareTextureProcessFunction, samplingMode); - }; - // According to the WebGL spec section 6.10, ImageBitmaps must be inverted on creation. - // So, we pass imageOrientation to _FileToolsLoadImage() as it may create an ImageBitmap. - if (!fromData || isBase64) { - if (buffer && (typeof buffer.decoding === "string" || buffer.close)) { - onload(buffer); - } - else { - ThinEngine._FileToolsLoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType, texture.invertY && this._features.needsInvertingBitmap ? { imageOrientation: "flipY" } : undefined); - } - } - else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer) || buffer instanceof Blob) { - ThinEngine._FileToolsLoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType, texture.invertY && this._features.needsInvertingBitmap ? { imageOrientation: "flipY" } : undefined); - } - else if (buffer) { - onload(buffer); - } - } - return texture; - } - /** - * Usually called from Texture.ts. - * Passed information to create a WebGLTexture - * @param url defines a value which contains one of the following: - * * A conventional http URL, e.g. 'http://...' or 'file://...' - * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...' - * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg' - * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file - * @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) - * @param scene needed for loading to the correct scene - * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE) - * @param onLoad optional callback to be called upon successful completion - * @param onError optional callback to be called upon failure - * @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 - * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities - * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures - * @param forcedExtension defines the extension to use to pick the right loader - * @param mimeType defines an optional mime type - * @param loaderOptions options to be passed to the loader - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - * @returns a InternalTexture for assignment back into BABYLON.Texture - */ - createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer) { - return this._createTextureBase(url, noMipmap, invertY, scene, samplingMode, onLoad, onError, this._prepareWebGLTexture.bind(this), (potWidth, potHeight, img, extension, texture, continuationCallback) => { - const gl = this._gl; - const isPot = img.width === potWidth && img.height === potHeight; - const internalFormat = format - ? this._getInternalFormat(format, texture._useSRGBBuffer) - : extension === ".jpg" && !texture._useSRGBBuffer - ? gl.RGB - : texture._useSRGBBuffer - ? this._glSRGBExtensionValues.SRGB8_ALPHA8 - : gl.RGBA; - let texelFormat = format ? this._getInternalFormat(format) : extension === ".jpg" && !texture._useSRGBBuffer ? gl.RGB : gl.RGBA; - if (texture._useSRGBBuffer && this.webGLVersion === 1) { - texelFormat = internalFormat; - } - if (isPot) { - gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, img); - return false; - } - const maxTextureSize = this._caps.maxTextureSize; - if (img.width > maxTextureSize || img.height > maxTextureSize || !this._supportsHardwareTextureRescaling) { - this._prepareWorkingCanvas(); - if (!this._workingCanvas || !this._workingContext) { - return false; - } - this._workingCanvas.width = potWidth; - this._workingCanvas.height = potHeight; - this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight); - gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, this._workingCanvas); - texture.width = potWidth; - texture.height = potHeight; - return false; - } - else { - // Using shaders when possible to rescale because canvas.drawImage is lossy - const source = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Temp); - this._bindTextureDirectly(gl.TEXTURE_2D, source, true); - gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, img); - this._rescaleTexture(source, texture, scene, internalFormat, () => { - this._releaseTexture(source); - this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); - continuationCallback(); - }); - } - return true; - }, buffer, fallback, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer); - } - /** - * Loads an image as an HTMLImageElement. - * @param input url string, ArrayBuffer, or Blob to load - * @param onLoad callback called when the image successfully loads - * @param onError callback called when the image fails to load - * @param offlineProvider offline provider for caching - * @param mimeType optional mime type - * @param imageBitmapOptions optional the options to use when creating an ImageBitmap - * @returns the HTMLImageElement of the loaded image - * @internal - */ - static _FileToolsLoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions) { - throw _WarnImport("FileTools"); - } - /** - * @internal - */ - _rescaleTexture(source, destination, scene, internalFormat, onComplete) { } - /** - * Creates a raw texture - * @param data defines the data to store in the texture - * @param width defines the width of the texture - * @param height defines the height of the texture - * @param format defines the format of the data - * @param generateMipMaps defines if the engine should generate the mip levels - * @param invertY defines if data must be stored with Y axis inverted - * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default) - * @param compression defines the compression used (null by default) - * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default) - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - * @returns the raw texture inside an InternalTexture - */ - createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) { - throw _WarnImport("Engine.RawTexture"); - } - /** - * Creates a new raw cube texture - * @param data defines the array of data to use to create each face - * @param size defines the size of the textures - * @param format defines the format of the data - * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT) - * @param generateMipMaps defines if the engine should generate the mip levels - * @param invertY defines if data must be stored with Y axis inverted - * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) - * @param compression defines the compression used (null by default) - * @returns the cube texture as an InternalTexture - */ - createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) { - throw _WarnImport("Engine.RawTexture"); - } - /** - * Creates a new raw 3D texture - * @param data defines the data used to create the texture - * @param width defines the width of the texture - * @param height defines the height of the texture - * @param depth defines the depth of the texture - * @param format defines the format of the texture - * @param generateMipMaps defines if the engine must generate mip levels - * @param invertY defines if data must be stored with Y axis inverted - * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) - * @param compression defines the compressed used (can be null) - * @param textureType defines the compressed used (can be null) - * @returns a new raw 3D texture (stored in an InternalTexture) - */ - createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) { - throw _WarnImport("Engine.RawTexture"); - } - /** - * Creates a new raw 2D array texture - * @param data defines the data used to create the texture - * @param width defines the width of the texture - * @param height defines the height of the texture - * @param depth defines the number of layers of the texture - * @param format defines the format of the texture - * @param generateMipMaps defines if the engine must generate mip levels - * @param invertY defines if data must be stored with Y axis inverted - * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) - * @param compression defines the compressed used (can be null) - * @param textureType defines the compressed used (can be null) - * @returns a new raw 2D array texture (stored in an InternalTexture) - */ - createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) { - throw _WarnImport("Engine.RawTexture"); - } - /** - * @internal - */ - _unpackFlipY(value) { - if (this._unpackFlipYCached !== value) { - this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0); - if (this.enableUnpackFlipYCached) { - this._unpackFlipYCached = value; - } - } - } - /** @internal */ - _getUnpackAlignement() { - return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT); - } - _getTextureTarget(texture) { - if (texture.isCube) { - return this._gl.TEXTURE_CUBE_MAP; - } - else if (texture.is3D) { - return this._gl.TEXTURE_3D; - } - else if (texture.is2DArray || texture.isMultiview) { - return this._gl.TEXTURE_2D_ARRAY; - } - return this._gl.TEXTURE_2D; - } - /** - * Update the sampling mode of a given texture - * @param samplingMode defines the required sampling mode - * @param texture defines the texture to update - * @param generateMipMaps defines whether to generate mipmaps for the texture - */ - updateTextureSamplingMode(samplingMode, texture, generateMipMaps = false) { - const target = this._getTextureTarget(texture); - const filters = this._getSamplingParameters(samplingMode, texture.useMipMaps || generateMipMaps); - this._setTextureParameterInteger(target, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture); - this._setTextureParameterInteger(target, this._gl.TEXTURE_MIN_FILTER, filters.min); - if (generateMipMaps) { - texture.generateMipMaps = true; - this._gl.generateMipmap(target); - } - this._bindTextureDirectly(target, null); - texture.samplingMode = samplingMode; - } - /** - * Update the dimensions of a texture - * @param texture texture to update - * @param width new width of the texture - * @param height new height of the texture - * @param depth new depth of the texture - */ - updateTextureDimensions(texture, width, height, depth = 1) { } - /** - * Update the sampling mode of a given texture - * @param texture defines the texture to update - * @param wrapU defines the texture wrap mode of the u coordinates - * @param wrapV defines the texture wrap mode of the v coordinates - * @param wrapR defines the texture wrap mode of the r coordinates - */ - updateTextureWrappingMode(texture, wrapU, wrapV = null, wrapR = null) { - const target = this._getTextureTarget(texture); - if (wrapU !== null) { - this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(wrapU), texture); - texture._cachedWrapU = wrapU; - } - if (wrapV !== null) { - this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(wrapV), texture); - texture._cachedWrapV = wrapV; - } - if ((texture.is2DArray || texture.is3D) && wrapR !== null) { - this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(wrapR), texture); - texture._cachedWrapR = wrapR; - } - this._bindTextureDirectly(target, null); - } - /** - * @internal - */ - _setupDepthStencilTexture(internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction, samples = 1) { - const width = size.width || size; - const height = size.height || size; - const layers = size.layers || 0; - internalTexture.baseWidth = width; - internalTexture.baseHeight = height; - internalTexture.width = width; - internalTexture.height = height; - internalTexture.is2DArray = layers > 0; - internalTexture.depth = layers; - internalTexture.isReady = true; - internalTexture.samples = samples; - internalTexture.generateMipMaps = false; - internalTexture.samplingMode = bilinearFiltering ? 2 : 1; - internalTexture.type = 0; - internalTexture._comparisonFunction = comparisonFunction; - const gl = this._gl; - const target = this._getTextureTarget(internalTexture); - const samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false); - gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag); - gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min); - gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - // TEXTURE_COMPARE_FUNC/MODE are only availble in WebGL2. - if (this.webGLVersion > 1) { - if (comparisonFunction === 0) { - gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, 515); - gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE); - } - else { - gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction); - gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE); - } - } - } - /** - * @internal - */ - _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) { - const gl = this._gl; - let target = gl.TEXTURE_2D; - if (texture.isCube) { - target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; - } - if (texture._useSRGBBuffer) { - switch (internalFormat) { - case 37492: - case 36196: - // Note, if using ETC1 and sRGB is requested, this will use ETC2 if available. - if (this._caps.etc2) { - internalFormat = gl.COMPRESSED_SRGB8_ETC2; - } - else { - texture._useSRGBBuffer = false; - } - break; - case 37496: - if (this._caps.etc2) { - internalFormat = gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; - } - else { - texture._useSRGBBuffer = false; - } - break; - case 36492: - internalFormat = gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT; - break; - case 37808: - internalFormat = gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; - break; - case 33776: - if (this._caps.s3tc_srgb) { - internalFormat = gl.COMPRESSED_SRGB_S3TC_DXT1_EXT; - } - else { - // S3TC sRGB extension not supported - texture._useSRGBBuffer = false; - } - break; - case 33777: - if (this._caps.s3tc_srgb) { - internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - } - else { - // S3TC sRGB extension not supported - texture._useSRGBBuffer = false; - } - break; - case 33779: - if (this._caps.s3tc_srgb) { - internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - } - else { - // S3TC sRGB extension not supported - texture._useSRGBBuffer = false; - } - break; - default: - // We don't support a sRGB format corresponding to internalFormat, so revert to non sRGB format - texture._useSRGBBuffer = false; - break; - } - } - this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data); - } - /** - * @internal - */ - _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0, babylonInternalFormat, useTextureWidthAndHeight = false) { - const gl = this._gl; - const textureType = this._getWebGLTextureType(texture.type); - const format = this._getInternalFormat(texture.format); - const internalFormat = babylonInternalFormat === undefined - ? this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer) - : this._getInternalFormat(babylonInternalFormat, texture._useSRGBBuffer); - this._unpackFlipY(texture.invertY); - let target = gl.TEXTURE_2D; - if (texture.isCube) { - target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; - } - const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E); - const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E); - const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0)); - const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0)); - gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData); - } - /** - * Update a portion of an internal texture - * @param texture defines the texture to update - * @param imageData defines the data to store into the texture - * @param xOffset defines the x coordinates of the update rectangle - * @param yOffset defines the y coordinates of the update rectangle - * @param width defines the width of the update rectangle - * @param height defines the height of the update rectangle - * @param faceIndex defines the face index if texture is a cube (0 by default) - * @param lod defines the lod level to update (0 by default) - * @param generateMipMaps defines whether to generate mipmaps or not - */ - updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) { - const gl = this._gl; - const textureType = this._getWebGLTextureType(texture.type); - const format = this._getInternalFormat(texture.format); - this._unpackFlipY(texture.invertY); - let targetForBinding = gl.TEXTURE_2D; - let target = gl.TEXTURE_2D; - if (texture.isCube) { - target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; - targetForBinding = gl.TEXTURE_CUBE_MAP; - } - this._bindTextureDirectly(targetForBinding, texture, true); - gl.texSubImage2D(target, lod, xOffset, yOffset, width, height, format, textureType, imageData); - if (generateMipMaps) { - this._gl.generateMipmap(target); - } - this._bindTextureDirectly(targetForBinding, null); - } - /** - * @internal - */ - _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) { - const gl = this._gl; - const bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; - this._bindTextureDirectly(bindTarget, texture, true); - this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod); - this._bindTextureDirectly(bindTarget, null, true); - } - _prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode) { - const gl = this._gl; - if (!gl) { - return; - } - const filters = this._getSamplingParameters(samplingMode, !noMipmap); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min); - if (!noMipmap && !isCompressed) { - gl.generateMipmap(gl.TEXTURE_2D); - } - this._bindTextureDirectly(gl.TEXTURE_2D, null); - // this.resetTextureCache(); - if (scene) { - scene.removePendingData(texture); - } - texture.onLoadedObservable.notifyObservers(texture); - texture.onLoadedObservable.clear(); - } - _prepareWebGLTexture(texture, extension, scene, img, invertY, noMipmap, isCompressed, processFunction, samplingMode = 3) { - const maxTextureSize = this.getCaps().maxTextureSize; - const potWidth = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(img.width, maxTextureSize) : img.width); - const potHeight = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(img.height, maxTextureSize) : img.height); - const gl = this._gl; - if (!gl) { - return; - } - if (!texture._hardwareTexture) { - // this.resetTextureCache(); - if (scene) { - scene.removePendingData(texture); - } - return; - } - this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); - this._unpackFlipY(invertY === undefined ? true : invertY ? true : false); - texture.baseWidth = img.width; - texture.baseHeight = img.height; - texture.width = potWidth; - texture.height = potHeight; - texture.isReady = true; - if (processFunction(potWidth, potHeight, img, extension, texture, () => { - this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); - })) { - // Returning as texture needs extra async steps - return; - } - this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); - } - /** - * @internal - */ - _setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height, samples = 1) { - const gl = this._gl; - // Create the depth/stencil buffer - if (generateStencilBuffer && generateDepthBuffer) { - return this._createRenderBuffer(width, height, samples, gl.DEPTH_STENCIL, gl.DEPTH24_STENCIL8, gl.DEPTH_STENCIL_ATTACHMENT); - } - if (generateDepthBuffer) { - let depthFormat = gl.DEPTH_COMPONENT16; - if (this._webGLVersion > 1) { - depthFormat = gl.DEPTH_COMPONENT32F; - } - return this._createRenderBuffer(width, height, samples, depthFormat, depthFormat, gl.DEPTH_ATTACHMENT); - } - if (generateStencilBuffer) { - return this._createRenderBuffer(width, height, samples, gl.STENCIL_INDEX8, gl.STENCIL_INDEX8, gl.STENCIL_ATTACHMENT); - } - return null; - } - /** - * @internal - */ - _createRenderBuffer(width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer = true) { - const gl = this._gl; - const renderBuffer = gl.createRenderbuffer(); - return this._updateRenderBuffer(renderBuffer, width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer); - } - _updateRenderBuffer(renderBuffer, width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer = true) { - const gl = this._gl; - gl.bindRenderbuffer(gl.RENDERBUFFER, renderBuffer); - if (samples > 1 && gl.renderbufferStorageMultisample) { - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, msInternalFormat, width, height); - } - else { - gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, width, height); - } - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, renderBuffer); - if (unbindBuffer) { - gl.bindRenderbuffer(gl.RENDERBUFFER, null); - } - return renderBuffer; - } - /** - * @internal - */ - _releaseTexture(texture) { - var _a; - this._deleteTexture((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource); - // Unbind channels - this.unbindAllTextures(); - const index = this._internalTexturesCache.indexOf(texture); - if (index !== -1) { - this._internalTexturesCache.splice(index, 1); - } - // Integrated fixed lod samplers. - if (texture._lodTextureHigh) { - texture._lodTextureHigh.dispose(); - } - if (texture._lodTextureMid) { - texture._lodTextureMid.dispose(); - } - if (texture._lodTextureLow) { - texture._lodTextureLow.dispose(); - } - // Integrated irradiance map. - if (texture._irradianceTexture) { - texture._irradianceTexture.dispose(); - } - } - /** - * @internal - */ - _releaseRenderTargetWrapper(rtWrapper) { - const index = this._renderTargetWrapperCache.indexOf(rtWrapper); - if (index !== -1) { - this._renderTargetWrapperCache.splice(index, 1); - } - } - _deleteTexture(texture) { - if (texture) { - this._gl.deleteTexture(texture); - } - } - _setProgram(program) { - if (this._currentProgram !== program) { - this._gl.useProgram(program); - this._currentProgram = program; - } - } - /** - * Binds an effect to the webGL context - * @param effect defines the effect to bind - */ - bindSamplers(effect) { - const webGLPipelineContext = effect.getPipelineContext(); - this._setProgram(webGLPipelineContext.program); - const samplers = effect.getSamplers(); - for (let index = 0; index < samplers.length; index++) { - const uniform = effect.getUniform(samplers[index]); - if (uniform) { - this._boundUniforms[index] = uniform; - } - } - this._currentEffect = null; - } - _activateCurrentTexture() { - if (this._currentTextureChannel !== this._activeChannel) { - this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel); - this._currentTextureChannel = this._activeChannel; - } - } - /** - * @internal - */ - _bindTextureDirectly(target, texture, forTextureDataUpdate = false, force = false) { - var _a, _b; - let wasPreviouslyBound = false; - const isTextureForRendering = texture && texture._associatedChannel > -1; - if (forTextureDataUpdate && isTextureForRendering) { - this._activeChannel = texture._associatedChannel; - } - const currentTextureBound = this._boundTexturesCache[this._activeChannel]; - if (currentTextureBound !== texture || force) { - this._activateCurrentTexture(); - if (texture && texture.isMultiview) { - //this._gl.bindTexture(target, texture ? texture._colorTextureArray : null); - console.error(target, texture); - throw "_bindTextureDirectly called with a multiview texture!"; - } - else { - this._gl.bindTexture(target, (_b = (_a = texture === null || texture === void 0 ? void 0 : texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource) !== null && _b !== void 0 ? _b : null); - } - this._boundTexturesCache[this._activeChannel] = texture; - if (texture) { - texture._associatedChannel = this._activeChannel; - } - } - else if (forTextureDataUpdate) { - wasPreviouslyBound = true; - this._activateCurrentTexture(); - } - if (isTextureForRendering && !forTextureDataUpdate) { - this._bindSamplerUniformToChannel(texture._associatedChannel, this._activeChannel); - } - return wasPreviouslyBound; - } - /** - * @internal - */ - _bindTexture(channel, texture, name) { - if (channel === undefined) { - return; - } - if (texture) { - texture._associatedChannel = channel; - } - this._activeChannel = channel; - const target = texture ? this._getTextureTarget(texture) : this._gl.TEXTURE_2D; - this._bindTextureDirectly(target, texture); - } - /** - * Unbind all textures from the webGL context - */ - unbindAllTextures() { - for (let channel = 0; channel < this._maxSimultaneousTextures; channel++) { - this._activeChannel = channel; - this._bindTextureDirectly(this._gl.TEXTURE_2D, null); - this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); - if (this.webGLVersion > 1) { - this._bindTextureDirectly(this._gl.TEXTURE_3D, null); - this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null); - } - } - } - /** - * Sets a texture to the according uniform. - * @param channel The texture channel - * @param uniform The uniform to set - * @param texture The texture to apply - * @param name The name of the uniform in the effect - */ - setTexture(channel, uniform, texture, name) { - if (channel === undefined) { - return; - } - if (uniform) { - this._boundUniforms[channel] = uniform; - } - this._setTexture(channel, texture); - } - _bindSamplerUniformToChannel(sourceSlot, destination) { - const uniform = this._boundUniforms[sourceSlot]; - if (!uniform || uniform._currentState === destination) { - return; - } - this._gl.uniform1i(uniform, destination); - uniform._currentState = destination; - } - _getTextureWrapMode(mode) { - switch (mode) { - case 1: - return this._gl.REPEAT; - case 0: - return this._gl.CLAMP_TO_EDGE; - case 2: - return this._gl.MIRRORED_REPEAT; - } - return this._gl.REPEAT; - } - _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false, name = "") { - // Not ready? - if (!texture) { - if (this._boundTexturesCache[channel] != null) { - this._activeChannel = channel; - this._bindTextureDirectly(this._gl.TEXTURE_2D, null); - this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); - if (this.webGLVersion > 1) { - this._bindTextureDirectly(this._gl.TEXTURE_3D, null); - this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null); - } - } - return false; - } - // Video - if (texture.video) { - this._activeChannel = channel; - const videoInternalTexture = texture.getInternalTexture(); - if (videoInternalTexture) { - videoInternalTexture._associatedChannel = channel; - } - texture.update(); - } - else if (texture.delayLoadState === 4) { - // Delay loading - texture.delayLoad(); - return false; - } - let internalTexture; - if (depthStencilTexture) { - internalTexture = texture.depthStencilTexture; - } - else if (texture.isReady()) { - internalTexture = texture.getInternalTexture(); - } - else if (texture.isCube) { - internalTexture = this.emptyCubeTexture; - } - else if (texture.is3D) { - internalTexture = this.emptyTexture3D; - } - else if (texture.is2DArray) { - internalTexture = this.emptyTexture2DArray; - } - else { - internalTexture = this.emptyTexture; - } - if (!isPartOfTextureArray && internalTexture) { - internalTexture._associatedChannel = channel; - } - let needToBind = true; - if (this._boundTexturesCache[channel] === internalTexture) { - if (!isPartOfTextureArray) { - this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel); - } - needToBind = false; - } - this._activeChannel = channel; - const target = this._getTextureTarget(internalTexture); - if (needToBind) { - this._bindTextureDirectly(target, internalTexture, isPartOfTextureArray); - } - if (internalTexture && !internalTexture.isMultiview) { - // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT. - if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) { - internalTexture._cachedCoordinatesMode = texture.coordinatesMode; - const textureWrapMode = texture.coordinatesMode !== 3 && texture.coordinatesMode !== 5 - ? 1 - : 0; - texture.wrapU = textureWrapMode; - texture.wrapV = textureWrapMode; - } - if (internalTexture._cachedWrapU !== texture.wrapU) { - internalTexture._cachedWrapU = texture.wrapU; - this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture); - } - if (internalTexture._cachedWrapV !== texture.wrapV) { - internalTexture._cachedWrapV = texture.wrapV; - this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture); - } - if (internalTexture.is3D && internalTexture._cachedWrapR !== texture.wrapR) { - internalTexture._cachedWrapR = texture.wrapR; - this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture); - } - this._setAnisotropicLevel(target, internalTexture, texture.anisotropicFilteringLevel); - } - return true; - } - /** - * Sets an array of texture to the webGL context - * @param channel defines the channel where the texture array must be set - * @param uniform defines the associated uniform location - * @param textures defines the array of textures to bind - * @param name name of the channel - */ - setTextureArray(channel, uniform, textures, name) { - if (channel === undefined || !uniform) { - return; - } - if (!this._textureUnits || this._textureUnits.length !== textures.length) { - this._textureUnits = new Int32Array(textures.length); - } - for (let i = 0; i < textures.length; i++) { - const texture = textures[i].getInternalTexture(); - if (texture) { - this._textureUnits[i] = channel + i; - texture._associatedChannel = channel + i; - } - else { - this._textureUnits[i] = -1; - } - } - this._gl.uniform1iv(uniform, this._textureUnits); - for (let index = 0; index < textures.length; index++) { - this._setTexture(this._textureUnits[index], textures[index], true); - } - } - /** - * @internal - */ - _setAnisotropicLevel(target, internalTexture, anisotropicFilteringLevel) { - const anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension; - if (internalTexture.samplingMode !== 11 && - internalTexture.samplingMode !== 3 && - internalTexture.samplingMode !== 2) { - anisotropicFilteringLevel = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear - } - if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) { - this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy), internalTexture); - internalTexture._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel; - } - } - _setTextureParameterFloat(target, parameter, value, texture) { - this._bindTextureDirectly(target, texture, true, true); - this._gl.texParameterf(target, parameter, value); - } - _setTextureParameterInteger(target, parameter, value, texture) { - if (texture) { - this._bindTextureDirectly(target, texture, true, true); - } - this._gl.texParameteri(target, parameter, value); - } - /** - * Unbind all vertex attributes from the webGL context - */ - unbindAllAttributes() { - if (this._mustWipeVertexAttributes) { - this._mustWipeVertexAttributes = false; - for (let i = 0; i < this._caps.maxVertexAttribs; i++) { - this.disableAttributeByIndex(i); - } - return; - } - for (let i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) { - if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) { - continue; - } - this.disableAttributeByIndex(i); - } - } - /** - * 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 - */ - releaseEffects() { - for (const name in this._compiledEffects) { - const webGLPipelineContext = this._compiledEffects[name].getPipelineContext(); - this._deletePipelineContext(webGLPipelineContext); - } - this._compiledEffects = {}; - } - /** - * Dispose and release all associated resources - */ - dispose() { - var _a; - this._isDisposed = true; - this.stopRenderLoop(); - // Clear observables - if (this.onBeforeTextureInitObservable) { - this.onBeforeTextureInitObservable.clear(); - } - // Empty texture - if (this._emptyTexture) { - this._releaseTexture(this._emptyTexture); - this._emptyTexture = null; - } - if (this._emptyCubeTexture) { - this._releaseTexture(this._emptyCubeTexture); - this._emptyCubeTexture = null; - } - if (this._dummyFramebuffer) { - this._gl.deleteFramebuffer(this._dummyFramebuffer); - } - // Release effects - this.releaseEffects(); - (_a = this.releaseComputeEffects) === null || _a === void 0 ? void 0 : _a.call(this); - // Unbind - this.unbindAllAttributes(); - this._boundUniforms = {}; - // Events - if (IsWindowObjectExist()) { - if (this._renderingCanvas) { - if (!this._doNotHandleContextLost) { - this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost); - this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored); - } - window.removeEventListener("resize", this._checkForMobile); - } - } - this._workingCanvas = null; - this._workingContext = null; - this._currentBufferPointers.length = 0; - this._renderingCanvas = null; - this._currentProgram = null; - this._boundRenderFunction = null; - effect_Effect.ResetCache(); - // Abort active requests - for (const request of this._activeRequests) { - request.abort(); - } - this.onDisposeObservable.notifyObservers(this); - this.onDisposeObservable.clear(); - } - /** - * Attach a new callback raised when context lost event is fired - * @param callback defines the callback to call - */ - attachContextLostEvent(callback) { - if (this._renderingCanvas) { - this._renderingCanvas.addEventListener("webglcontextlost", callback, false); - } - } - /** - * Attach a new callback raised when context restored event is fired - * @param callback defines the callback to call - */ - attachContextRestoredEvent(callback) { - if (this._renderingCanvas) { - this._renderingCanvas.addEventListener("webglcontextrestored", callback, false); - } - } - /** - * Get the current error code of the webGL context - * @returns the error code - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError - */ - getError() { - return this._gl.getError(); - } - _canRenderToFloatFramebuffer() { - if (this._webGLVersion > 1) { - return this._caps.colorBufferFloat; - } - return this._canRenderToFramebuffer(1); - } - _canRenderToHalfFloatFramebuffer() { - if (this._webGLVersion > 1) { - return this._caps.colorBufferFloat; - } - return this._canRenderToFramebuffer(2); - } - // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture - _canRenderToFramebuffer(type) { - const gl = this._gl; - //clear existing errors - // eslint-disable-next-line no-empty - while (gl.getError() !== gl.NO_ERROR) { } - let successful = true; - const texture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - const fb = gl.createFramebuffer(); - gl.bindFramebuffer(gl.FRAMEBUFFER, fb); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); - const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); - successful = successful && status === gl.FRAMEBUFFER_COMPLETE; - successful = successful && gl.getError() === gl.NO_ERROR; - //try render by clearing frame buffer's color buffer - if (successful) { - gl.clear(gl.COLOR_BUFFER_BIT); - successful = successful && gl.getError() === gl.NO_ERROR; - } - //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported) - if (successful) { - //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - const readFormat = gl.RGBA; - const readType = gl.UNSIGNED_BYTE; - const buffer = new Uint8Array(4); - gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer); - successful = successful && gl.getError() === gl.NO_ERROR; - } - //clean up - gl.deleteTexture(texture); - gl.deleteFramebuffer(fb); - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - //clear accumulated errors - // eslint-disable-next-line no-empty - while (!successful && gl.getError() !== gl.NO_ERROR) { } - return successful; - } - /** - * @internal - */ - _getWebGLTextureType(type) { - if (this._webGLVersion === 1) { - switch (type) { - case 1: - return this._gl.FLOAT; - case 2: - return this._gl.HALF_FLOAT_OES; - case 0: - return this._gl.UNSIGNED_BYTE; - case 8: - return this._gl.UNSIGNED_SHORT_4_4_4_4; - case 9: - return this._gl.UNSIGNED_SHORT_5_5_5_1; - case 10: - return this._gl.UNSIGNED_SHORT_5_6_5; - } - return this._gl.UNSIGNED_BYTE; - } - switch (type) { - case 3: - return this._gl.BYTE; - case 0: - return this._gl.UNSIGNED_BYTE; - case 4: - return this._gl.SHORT; - case 5: - return this._gl.UNSIGNED_SHORT; - case 6: - return this._gl.INT; - case 7: // Refers to UNSIGNED_INT - return this._gl.UNSIGNED_INT; - case 1: - return this._gl.FLOAT; - case 2: - return this._gl.HALF_FLOAT; - case 8: - return this._gl.UNSIGNED_SHORT_4_4_4_4; - case 9: - return this._gl.UNSIGNED_SHORT_5_5_5_1; - case 10: - return this._gl.UNSIGNED_SHORT_5_6_5; - case 11: - return this._gl.UNSIGNED_INT_2_10_10_10_REV; - case 12: - return this._gl.UNSIGNED_INT_24_8; - case 13: - return this._gl.UNSIGNED_INT_10F_11F_11F_REV; - case 14: - return this._gl.UNSIGNED_INT_5_9_9_9_REV; - case 15: - return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV; - } - return this._gl.UNSIGNED_BYTE; - } - /** - * @internal - */ - _getInternalFormat(format, useSRGBBuffer = false) { - let internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA; - switch (format) { - case 0: - internalFormat = this._gl.ALPHA; - break; - case 1: - internalFormat = this._gl.LUMINANCE; - break; - case 2: - internalFormat = this._gl.LUMINANCE_ALPHA; - break; - case 6: - internalFormat = this._gl.RED; - break; - case 7: - internalFormat = this._gl.RG; - break; - case 4: - internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB : this._gl.RGB; - break; - case 5: - internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA; - break; - } - if (this._webGLVersion > 1) { - switch (format) { - case 8: - internalFormat = this._gl.RED_INTEGER; - break; - case 9: - internalFormat = this._gl.RG_INTEGER; - break; - case 10: - internalFormat = this._gl.RGB_INTEGER; - break; - case 11: - internalFormat = this._gl.RGBA_INTEGER; - break; - } - } - return internalFormat; - } - /** - * @internal - */ - _getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer = false) { - if (this._webGLVersion === 1) { - if (format !== undefined) { - switch (format) { - case 0: - return this._gl.ALPHA; - case 1: - return this._gl.LUMINANCE; - case 2: - return this._gl.LUMINANCE_ALPHA; - case 4: - return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB : this._gl.RGB; - } - } - return this._gl.RGBA; - } - switch (type) { - case 3: - switch (format) { - case 6: - return this._gl.R8_SNORM; - case 7: - return this._gl.RG8_SNORM; - case 4: - return this._gl.RGB8_SNORM; - case 8: - return this._gl.R8I; - case 9: - return this._gl.RG8I; - case 10: - return this._gl.RGB8I; - case 11: - return this._gl.RGBA8I; - default: - return this._gl.RGBA8_SNORM; - } - case 0: - switch (format) { - case 6: - return this._gl.R8; - case 7: - return this._gl.RG8; - case 4: - return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8 : this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8. - case 5: - return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8. - case 8: - return this._gl.R8UI; - case 9: - return this._gl.RG8UI; - case 10: - return this._gl.RGB8UI; - case 11: - return this._gl.RGBA8UI; - case 0: - return this._gl.ALPHA; - case 1: - return this._gl.LUMINANCE; - case 2: - return this._gl.LUMINANCE_ALPHA; - default: - return this._gl.RGBA8; - } - case 4: - switch (format) { - case 8: - return this._gl.R16I; - case 9: - return this._gl.RG16I; - case 10: - return this._gl.RGB16I; - case 11: - return this._gl.RGBA16I; - default: - return this._gl.RGBA16I; - } - case 5: - switch (format) { - case 8: - return this._gl.R16UI; - case 9: - return this._gl.RG16UI; - case 10: - return this._gl.RGB16UI; - case 11: - return this._gl.RGBA16UI; - default: - return this._gl.RGBA16UI; - } - case 6: - switch (format) { - case 8: - return this._gl.R32I; - case 9: - return this._gl.RG32I; - case 10: - return this._gl.RGB32I; - case 11: - return this._gl.RGBA32I; - default: - return this._gl.RGBA32I; - } - case 7: // Refers to UNSIGNED_INT - switch (format) { - case 8: - return this._gl.R32UI; - case 9: - return this._gl.RG32UI; - case 10: - return this._gl.RGB32UI; - case 11: - return this._gl.RGBA32UI; - default: - return this._gl.RGBA32UI; - } - case 1: - switch (format) { - case 6: - return this._gl.R32F; // By default. Other possibility is R16F. - case 7: - return this._gl.RG32F; // By default. Other possibility is RG16F. - case 4: - return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5. - case 5: - return this._gl.RGBA32F; // By default. Other possibility is RGBA16F. - default: - return this._gl.RGBA32F; - } - case 2: - switch (format) { - case 6: - return this._gl.R16F; - case 7: - return this._gl.RG16F; - case 4: - return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5. - case 5: - return this._gl.RGBA16F; - default: - return this._gl.RGBA16F; - } - case 10: - return this._gl.RGB565; - case 13: - return this._gl.R11F_G11F_B10F; - case 14: - return this._gl.RGB9_E5; - case 8: - return this._gl.RGBA4; - case 9: - return this._gl.RGB5_A1; - case 11: - switch (format) { - case 5: - return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1. - case 11: - return this._gl.RGB10_A2UI; - default: - return this._gl.RGB10_A2; - } - } - return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA8; - } - /** - * @internal - */ - _getRGBAMultiSampleBufferFormat(type, format = 5) { - switch (type) { - case 1: - switch (format) { - case 6: - return this._gl.R32F; - default: - return this._gl.RGBA32F; - } - case 2: - switch (format) { - case 6: - return this._gl.R16F; - default: - return this._gl.RGBA16F; - } - } - return this._gl.RGBA8; - } - /** - * @internal - */ - _loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { - const request = ThinEngine._FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); - this._activeRequests.push(request); - request.onCompleteObservable.add((request) => { - this._activeRequests.splice(this._activeRequests.indexOf(request), 1); - }); - return request; - } - /** - * Loads a file from a url - * @param url url to load - * @param onSuccess callback called when the file successfully loads - * @param onProgress callback called while file is loading (if the server supports this mode) - * @param offlineProvider defines the offline provider for caching - * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer - * @param onError callback called when the file fails to load - * @returns a file request object - * @internal - */ - static _FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { - throw _WarnImport("FileTools"); - } - /** - * Reads pixels from the current frame buffer. Please note that this function can be slow - * @param x defines the x coordinate of the rectangle where pixels must be read - * @param y defines the y coordinate of the rectangle where pixels must be read - * @param width defines the width of the rectangle where pixels must be read - * @param height defines the height of the rectangle where pixels must be read - * @param hasAlpha defines whether the output should have alpha or not (defaults to true) - * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels - * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors - */ - readPixels(x, y, width, height, hasAlpha = true, flushRenderer = true) { - const numChannels = hasAlpha ? 4 : 3; - const format = hasAlpha ? this._gl.RGBA : this._gl.RGB; - const data = new Uint8Array(height * width * numChannels); - if (flushRenderer) { - this.flushFramebuffer(); - } - this._gl.readPixels(x, y, width, height, format, this._gl.UNSIGNED_BYTE, data); - return Promise.resolve(data); - } - /** - * Gets a Promise<boolean> indicating if the engine can be instantiated (ie. if a webGL context can be found) - */ - static get IsSupportedAsync() { - return Promise.resolve(this.isSupported()); - } - /** - * Gets a boolean indicating if the engine can be instantiated (ie. if a webGL context can be found) - */ - static get IsSupported() { - return this.isSupported(); // Backward compat - } - /** - * Gets a boolean indicating if the engine can be instantiated (ie. if a webGL context can be found) - * @returns true if the engine can be created - * @ignorenaming - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static isSupported() { - if (this._HasMajorPerformanceCaveat !== null) { - return !this._HasMajorPerformanceCaveat; // We know it is performant so WebGL is supported - } - if (this._IsSupported === null) { - try { - const tempcanvas = this._CreateCanvas(1, 1); - const gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"); - this._IsSupported = gl != null && !!window.WebGLRenderingContext; - } - catch (e) { - this._IsSupported = false; - } - } - return this._IsSupported; - } - /** - * Gets a boolean indicating if the engine can be instantiated on a performant device (ie. if a webGL context can be found and it does not use a slow implementation) - */ - static get HasMajorPerformanceCaveat() { - if (this._HasMajorPerformanceCaveat === null) { - try { - const tempcanvas = this._CreateCanvas(1, 1); - const gl = tempcanvas.getContext("webgl", { failIfMajorPerformanceCaveat: true }) || - tempcanvas.getContext("experimental-webgl", { failIfMajorPerformanceCaveat: true }); - this._HasMajorPerformanceCaveat = !gl; - } - catch (e) { - this._HasMajorPerformanceCaveat = false; - } - } - return this._HasMajorPerformanceCaveat; - } - /** - * Find the next highest power of two. - * @param x Number to start search from. - * @returns Next highest power of two. - */ - static CeilingPOT(x) { - x--; - x |= x >> 1; - x |= x >> 2; - x |= x >> 4; - x |= x >> 8; - x |= x >> 16; - x++; - return x; - } - /** - * Find the next lowest power of two. - * @param x Number to start search from. - * @returns Next lowest power of two. - */ - static FloorPOT(x) { - x = x | (x >> 1); - x = x | (x >> 2); - x = x | (x >> 4); - x = x | (x >> 8); - x = x | (x >> 16); - return x - (x >> 1); - } - /** - * Find the nearest power of two. - * @param x Number to start search from. - * @returns Next nearest power of two. - */ - static NearestPOT(x) { - const c = ThinEngine.CeilingPOT(x); - const f = ThinEngine.FloorPOT(x); - return c - x > x - f ? f : c; - } - /** - * Get the closest exponent of two - * @param value defines the value to approximate - * @param max defines the maximum value to return - * @param mode defines how to define the closest value - * @returns closest exponent of two of the given value - */ - static GetExponentOfTwo(value, max, mode = 2) { - let pot; - switch (mode) { - case 1: - pot = ThinEngine.FloorPOT(value); - break; - case 2: - pot = ThinEngine.NearestPOT(value); - break; - case 3: - default: - pot = ThinEngine.CeilingPOT(value); - break; - } - return Math.min(pot, max); - } - /** - * Queue a new function into the requested animation frame pool (ie. this function will be executed by the browser (or the javascript engine) for the next frame) - * @param func - the function to be called - * @param requester - the object that will request the next frame. Falls back to window. - * @returns frame number - */ - static QueueNewFrame(func, requester) { - // Note that there is kind of a typing issue here, as `setTimeout` might return something else than a number (NodeJs returns a NodeJS.Timeout object). - // Also if the global `requestAnimationFrame`'s returnType is number, `requester.requestPostAnimationFrame` and `requester.requestAnimationFrame` types - // are `any`. - if (!IsWindowObjectExist()) { - if (typeof requestAnimationFrame === "function") { - return requestAnimationFrame(func); - } - } - else { - const { requestAnimationFrame } = requester || window; - if (typeof requestAnimationFrame === "function") { - return requestAnimationFrame(func); - } - } - // fallback to the global `setTimeout`. - // In most cases (aka in the browser), `window` is the global object, so instead of calling `window.setTimeout` we could call the global `setTimeout`. - return setTimeout(func, 16); - } - /** - * Gets host document - * @returns the host document object - */ - getHostDocument() { - if (this._renderingCanvas && this._renderingCanvas.ownerDocument) { - return this._renderingCanvas.ownerDocument; - } - return IsDocumentAvailable() ? document : null; - } -} -ThinEngine._TempClearColorUint32 = new Uint32Array(4); -ThinEngine._TempClearColorInt32 = new Int32Array(4); -/** Use this array to turn off some WebGL2 features on known buggy browsers version */ -ThinEngine.ExceptionList = [ - { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] }, - { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }, - { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }, - { key: "Chrome/72.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] }, - { key: "Chrome/73.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] }, - { key: "Chrome/74.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] }, - { key: "Mac OS.+Chrome/71", capture: null, captureConstraint: null, targets: ["vao"] }, - { key: "Mac OS.+Chrome/72", capture: null, captureConstraint: null, targets: ["vao"] }, - { key: "Mac OS.+Chrome", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }, - // desktop osx safari 15.4 - { key: ".*AppleWebKit.*(15.4).*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] }, - // mobile browsers using safari 15.4 on ios - { key: ".*(15.4).*AppleWebKit.*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] }, -]; -/** @internal */ -ThinEngine._TextureLoaders = []; -// Updatable statics so stick with vars here -/** - * Gets or sets the epsilon value used by collision engine - */ -ThinEngine.CollisionsEpsilon = 0.001; -// Statics -ThinEngine._IsSupported = null; -ThinEngine._HasMajorPerformanceCaveat = null; -//# sourceMappingURL=thinEngine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/timingTools.js - -/** - * Class used to provide helper for timing - */ -class TimingTools { - /** - * Polyfill for setImmediate - * @param action defines the action to execute after the current execution block - */ - static SetImmediate(action) { - if (IsWindowObjectExist() && window.setImmediate) { - window.setImmediate(action); - } - else { - setTimeout(action, 1); - } - } -} -//# sourceMappingURL=timingTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/fileTools.js -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - - - - - -const Base64DataUrlRegEx = new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i); -/** @ignore */ -class LoadFileError extends RuntimeError { - /** - * Creates a new LoadFileError - * @param message defines the message of the error - * @param object defines the optional web request - */ - constructor(message, object) { - super(message, ErrorCodes.LoadFileError); - this.name = "LoadFileError"; - BaseError._setPrototypeOf(this, LoadFileError.prototype); - if (object instanceof webRequest_WebRequest) { - this.request = object; - } - else { - this.file = object; - } - } -} -/** @ignore */ -class RequestFileError extends RuntimeError { - /** - * Creates a new LoadFileError - * @param message defines the message of the error - * @param request defines the optional web request - */ - constructor(message, request) { - super(message, ErrorCodes.RequestFileError); - this.request = request; - this.name = "RequestFileError"; - BaseError._setPrototypeOf(this, RequestFileError.prototype); - } -} -/** @ignore */ -class ReadFileError extends RuntimeError { - /** - * Creates a new ReadFileError - * @param message defines the message of the error - * @param file defines the optional file - */ - constructor(message, file) { - super(message, ErrorCodes.ReadFileError); - this.file = file; - this.name = "ReadFileError"; - BaseError._setPrototypeOf(this, ReadFileError.prototype); - } -} -/** - * @internal - */ -const FileToolsOptions = { - /** - * Gets or sets the retry strategy to apply when an error happens while loading an asset. - * When defining this function, return the wait time before trying again or return -1 to - * stop retrying and error out. - */ - DefaultRetryStrategy: RetryStrategy.ExponentialBackoff(), - /** - * Gets or sets the base URL to use to load assets - */ - BaseUrl: "", - /** - * Default behaviour for cors in the application. - * It can be a string if the expected behavior is identical in the entire app. - * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance) - */ - CorsBehavior: "anonymous", - /** - * Gets or sets a function used to pre-process url before using them to load assets - * @param url - */ - PreprocessUrl: (url) => { - return url; - }, -}; -/** - * Removes unwanted characters from an url - * @param url defines the url to clean - * @returns the cleaned url - */ -const _CleanUrl = (url) => { - url = url.replace(/#/gm, "%23"); - return url; -}; -/** - * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element. - * @param url define the url we are trying - * @param element define the dom element where to configure the cors policy - * @internal - */ -const SetCorsBehavior = (url, element) => { - if (url && url.indexOf("data:") === 0) { - return; - } - if (FileToolsOptions.CorsBehavior) { - if (typeof FileToolsOptions.CorsBehavior === "string" || FileToolsOptions.CorsBehavior instanceof String) { - element.crossOrigin = FileToolsOptions.CorsBehavior; - } - else { - const result = FileToolsOptions.CorsBehavior(url); - if (result) { - element.crossOrigin = result; - } - } - } -}; -/** - * Loads an image as an HTMLImageElement. - * @param input url string, ArrayBuffer, or Blob to load - * @param onLoad callback called when the image successfully loads - * @param onError callback called when the image fails to load - * @param offlineProvider offline provider for caching - * @param mimeType optional mime type - * @param imageBitmapOptions - * @returns the HTMLImageElement of the loaded image - * @internal - */ -const LoadImage = (input, onLoad, onError, offlineProvider, mimeType = "", imageBitmapOptions) => { - var _a; - let url; - let usingObjectURL = false; - if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) { - if (typeof Blob !== "undefined" && typeof URL !== "undefined") { - url = URL.createObjectURL(new Blob([input], { type: mimeType })); - usingObjectURL = true; - } - else { - url = `data:${mimeType};base64,` + stringTools_EncodeArrayBufferToBase64(input); - } - } - else if (input instanceof Blob) { - url = URL.createObjectURL(input); - usingObjectURL = true; - } - else { - url = _CleanUrl(input); - url = FileToolsOptions.PreprocessUrl(input); - } - const engine = engineStore_EngineStore.LastCreatedEngine; - const onErrorHandler = (exception) => { - if (onError) { - const inputText = url || input.toString(); - onError(`Error while trying to load image: ${inputText.indexOf("http") === 0 || inputText.length <= 128 ? inputText : inputText.slice(0, 128) + "..."}`, exception); - } - }; - if (typeof Image === "undefined" || ((_a = engine === null || engine === void 0 ? void 0 : engine._features.forceBitmapOverHTMLImageElement) !== null && _a !== void 0 ? _a : false)) { - LoadFile(url, (data) => { - engine - .createImageBitmap(new Blob([data], { type: mimeType }), Object.assign({ premultiplyAlpha: "none" }, imageBitmapOptions)) - .then((imgBmp) => { - onLoad(imgBmp); - if (usingObjectURL) { - URL.revokeObjectURL(url); - } - }) - .catch((reason) => { - if (onError) { - onError("Error while trying to load image: " + input, reason); - } - }); - }, undefined, offlineProvider || undefined, true, (request, exception) => { - onErrorHandler(exception); - }); - return null; - } - const img = new Image(); - SetCorsBehavior(url, img); - const handlersList = []; - const loadHandlersList = () => { - handlersList.forEach((handler) => { - handler.target.addEventListener(handler.name, handler.handler); - }); - }; - const unloadHandlersList = () => { - handlersList.forEach((handler) => { - handler.target.removeEventListener(handler.name, handler.handler); - }); - handlersList.length = 0; - }; - const loadHandler = () => { - unloadHandlersList(); - onLoad(img); - // Must revoke the URL after calling onLoad to avoid security exceptions in - // certain scenarios (e.g. when hosted in vscode). - if (usingObjectURL && img.src) { - URL.revokeObjectURL(img.src); - } - }; - const errorHandler = (err) => { - unloadHandlersList(); - onErrorHandler(err); - if (usingObjectURL && img.src) { - URL.revokeObjectURL(img.src); - } - }; - const cspHandler = (err) => { - if (err.blockedURI !== img.src) { - return; - } - unloadHandlersList(); - const cspException = new Error(`CSP violation of policy ${err.effectiveDirective} ${err.blockedURI}. Current policy is ${err.originalPolicy}`); - engineStore_EngineStore.UseFallbackTexture = false; - onErrorHandler(cspException); - if (usingObjectURL && img.src) { - URL.revokeObjectURL(img.src); - } - img.src = ""; - }; - handlersList.push({ target: img, name: "load", handler: loadHandler }); - handlersList.push({ target: img, name: "error", handler: errorHandler }); - handlersList.push({ target: document, name: "securitypolicyviolation", handler: cspHandler }); - loadHandlersList(); - const fromBlob = url.substring(0, 5) === "blob:"; - const fromData = url.substring(0, 5) === "data:"; - const noOfflineSupport = () => { - if (fromBlob || fromData) { - img.src = url; - } - else { - LoadFile(url, (data, _, contentType) => { - const type = !mimeType && contentType ? contentType : mimeType; - const blob = new Blob([data], { type }); - const url = URL.createObjectURL(blob); - usingObjectURL = true; - img.src = url; - }, undefined, offlineProvider || undefined, true, (request, exception) => { - onErrorHandler(exception); - }); - } - }; - const loadFromOfflineSupport = () => { - if (offlineProvider) { - offlineProvider.loadImage(url, img); - } - }; - if (!fromBlob && !fromData && offlineProvider && offlineProvider.enableTexturesOffline) { - offlineProvider.open(loadFromOfflineSupport, noOfflineSupport); - } - else { - if (url.indexOf("file:") !== -1) { - const textureName = decodeURIComponent(url.substring(5).toLowerCase()); - if (filesInputStore_FilesInputStore.FilesToLoad[textureName] && typeof URL !== "undefined") { - try { - let blobURL; - try { - blobURL = URL.createObjectURL(filesInputStore_FilesInputStore.FilesToLoad[textureName]); - } - catch (ex) { - // Chrome doesn't support oneTimeOnly parameter - blobURL = URL.createObjectURL(filesInputStore_FilesInputStore.FilesToLoad[textureName]); - } - img.src = blobURL; - usingObjectURL = true; - } - catch (e) { - img.src = ""; - } - return img; - } - } - noOfflineSupport(); - } - return img; -}; -/** - * Reads a file from a File object - * @param file defines the file to load - * @param onSuccess defines the callback to call when data is loaded - * @param onProgress defines the callback to call during loading process - * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer - * @param onError defines the callback to call when an error occurs - * @returns a file request object - * @internal - */ -const ReadFile = (file, onSuccess, onProgress, useArrayBuffer, onError) => { - const reader = new FileReader(); - const fileRequest = { - onCompleteObservable: new observable_Observable(), - abort: () => reader.abort(), - }; - reader.onloadend = () => fileRequest.onCompleteObservable.notifyObservers(fileRequest); - if (onError) { - reader.onerror = () => { - onError(new ReadFileError(`Unable to read ${file.name}`, file)); - }; - } - reader.onload = (e) => { - //target doesn't have result from ts 1.3 - onSuccess(e.target["result"]); - }; - if (onProgress) { - reader.onprogress = onProgress; - } - if (!useArrayBuffer) { - // Asynchronous read - reader.readAsText(file); - } - else { - reader.readAsArrayBuffer(file); - } - return fileRequest; -}; -/** - * Loads a file from a url, a data url, or a file url - * @param fileOrUrl file, url, data url, or file url to load - * @param onSuccess callback called when the file successfully loads - * @param onProgress callback called while file is loading (if the server supports this mode) - * @param offlineProvider defines the offline provider for caching - * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer - * @param onError callback called when the file fails to load - * @param onOpened - * @returns a file request object - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -const LoadFile = (fileOrUrl, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => { - if (fileOrUrl.name) { - return ReadFile(fileOrUrl, onSuccess, onProgress, useArrayBuffer, onError - ? (error) => { - onError(undefined, error); - } - : undefined); - } - const url = fileOrUrl; - // If file and file input are set - if (url.indexOf("file:") !== -1) { - let fileName = decodeURIComponent(url.substring(5).toLowerCase()); - if (fileName.indexOf("./") === 0) { - fileName = fileName.substring(2); - } - const file = filesInputStore_FilesInputStore.FilesToLoad[fileName]; - if (file) { - return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError ? (error) => onError(undefined, new LoadFileError(error.message, error.file)) : undefined); - } - } - // For a Base64 Data URL - const { match, type } = TestBase64DataUrl(url); - if (match) { - const fileRequest = { - onCompleteObservable: new observable_Observable(), - abort: () => () => { }, - }; - try { - const data = useArrayBuffer ? DecodeBase64UrlToBinary(url) : DecodeBase64UrlToString(url); - onSuccess(data, undefined, type); - } - catch (error) { - if (onError) { - onError(undefined, error); - } - else { - logger_Logger.Error(error.message || "Failed to parse the Data URL"); - } - } - TimingTools.SetImmediate(() => { - fileRequest.onCompleteObservable.notifyObservers(fileRequest); - }); - return fileRequest; - } - return RequestFile(url, (data, request) => { - onSuccess(data, request === null || request === void 0 ? void 0 : request.responseURL, request === null || request === void 0 ? void 0 : request.getResponseHeader("content-type")); - }, onProgress, offlineProvider, useArrayBuffer, onError - ? (error) => { - onError(error.request, new LoadFileError(error.message, error.request)); - } - : undefined, onOpened); -}; -/** - * Loads a file from a url - * @param url url to load - * @param onSuccess callback called when the file successfully loads - * @param onProgress callback called while file is loading (if the server supports this mode) - * @param offlineProvider defines the offline provider for caching - * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer - * @param onError callback called when the file fails to load - * @param onOpened callback called when the web request is opened - * @returns a file request object - * @internal - */ -const RequestFile = (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => { - url = _CleanUrl(url); - url = FileToolsOptions.PreprocessUrl(url); - const loadUrl = FileToolsOptions.BaseUrl + url; - let aborted = false; - const fileRequest = { - onCompleteObservable: new observable_Observable(), - abort: () => (aborted = true), - }; - const requestFile = () => { - let request = new webRequest_WebRequest(); - let retryHandle = null; - let onReadyStateChange; - const unbindEvents = () => { - if (!request) { - return; - } - if (onProgress) { - request.removeEventListener("progress", onProgress); - } - if (onReadyStateChange) { - request.removeEventListener("readystatechange", onReadyStateChange); - } - request.removeEventListener("loadend", onLoadEnd); - }; - let onLoadEnd = () => { - unbindEvents(); - fileRequest.onCompleteObservable.notifyObservers(fileRequest); - fileRequest.onCompleteObservable.clear(); - onProgress = undefined; - onReadyStateChange = null; - onLoadEnd = null; - onError = undefined; - onOpened = undefined; - onSuccess = undefined; - }; - fileRequest.abort = () => { - aborted = true; - if (onLoadEnd) { - onLoadEnd(); - } - if (request && request.readyState !== (XMLHttpRequest.DONE || 4)) { - request.abort(); - } - if (retryHandle !== null) { - clearTimeout(retryHandle); - retryHandle = null; - } - request = null; - }; - const handleError = (error) => { - const message = error.message || "Unknown error"; - if (onError && request) { - onError(new RequestFileError(message, request)); - } - else { - logger_Logger.Error(message); - } - }; - const retryLoop = (retryIndex) => { - if (!request) { - return; - } - request.open("GET", loadUrl); - if (onOpened) { - try { - onOpened(request); - } - catch (e) { - handleError(e); - return; - } - } - if (useArrayBuffer) { - request.responseType = "arraybuffer"; - } - if (onProgress) { - request.addEventListener("progress", onProgress); - } - if (onLoadEnd) { - request.addEventListener("loadend", onLoadEnd); - } - onReadyStateChange = () => { - if (aborted || !request) { - return; - } - // In case of undefined state in some browsers. - if (request.readyState === (XMLHttpRequest.DONE || 4)) { - // Some browsers have issues where onreadystatechange can be called multiple times with the same value. - if (onReadyStateChange) { - request.removeEventListener("readystatechange", onReadyStateChange); - } - if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!IsWindowObjectExist() || IsFileURL()))) { - try { - if (onSuccess) { - onSuccess(useArrayBuffer ? request.response : request.responseText, request); - } - } - catch (e) { - handleError(e); - } - return; - } - const retryStrategy = FileToolsOptions.DefaultRetryStrategy; - if (retryStrategy) { - const waitTime = retryStrategy(loadUrl, request, retryIndex); - if (waitTime !== -1) { - // Prevent the request from completing for retry. - unbindEvents(); - request = new webRequest_WebRequest(); - retryHandle = setTimeout(() => retryLoop(retryIndex + 1), waitTime); - return; - } - } - const error = new RequestFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request); - if (onError) { - onError(error); - } - } - }; - request.addEventListener("readystatechange", onReadyStateChange); - request.send(); - }; - retryLoop(0); - }; - // Caching all files - if (offlineProvider && offlineProvider.enableSceneOffline) { - const noOfflineSupport = (request) => { - if (request && request.status > 400) { - if (onError) { - onError(request); - } - } - else { - requestFile(); - } - }; - const loadFromOfflineSupport = () => { - // TODO: database needs to support aborting and should return a IFileRequest - if (offlineProvider) { - offlineProvider.loadFile(FileToolsOptions.BaseUrl + url, (data) => { - if (!aborted && onSuccess) { - onSuccess(data); - } - fileRequest.onCompleteObservable.notifyObservers(fileRequest); - }, onProgress - ? (event) => { - if (!aborted && onProgress) { - onProgress(event); - } - } - : undefined, noOfflineSupport, useArrayBuffer); - } - }; - offlineProvider.open(loadFromOfflineSupport, noOfflineSupport); - } - else { - requestFile(); - } - return fileRequest; -}; -/** - * Checks if the loaded document was accessed via `file:`-Protocol. - * @returns boolean - * @internal - */ -const IsFileURL = () => { - return typeof location !== "undefined" && location.protocol === "file:"; -}; -/** - * Test if the given uri is a valid base64 data url - * @param uri The uri to test - * @returns True if the uri is a base64 data url or false otherwise - * @internal - */ -const IsBase64DataUrl = (uri) => { - return Base64DataUrlRegEx.test(uri); -}; -const TestBase64DataUrl = (uri) => { - const results = Base64DataUrlRegEx.exec(uri); - if (results === null || results.length === 0) { - return { match: false, type: "" }; - } - else { - const type = results[0].replace("data:", "").replace("base64,", ""); - return { match: true, type }; - } -}; -/** - * Decode the given base64 uri. - * @param uri The uri to decode - * @returns The decoded base64 data. - * @internal - */ -function DecodeBase64UrlToBinary(uri) { - return stringTools_DecodeBase64ToBinary(uri.split(",")[1]); -} -/** - * Decode the given base64 uri into a UTF-8 encoded string. - * @param uri The uri to decode - * @returns The decoded base64 data. - * @internal - */ -const DecodeBase64UrlToString = (uri) => { - return DecodeBase64ToString(uri.split(",")[1]); -}; -/** - * This will be executed automatically for UMD and es5. - * If esm dev wants the side effects to execute they will have to run it manually - * Once we build native modules those need to be exported. - * @internal - */ -const initSideEffects = () => { - ThinEngine._FileToolsLoadImage = LoadImage; - ThinEngine._FileToolsLoadFile = LoadFile; - ShaderProcessor._FileToolsLoadFile = LoadFile; -}; -initSideEffects(); -// deprecated -/** - * FileTools defined as any. - * This should not be imported or used in future releases or in any module in the framework - * @internal - * @deprecated import the needed function from fileTools.ts - */ -let FileTools; -/** - * @param DecodeBase64UrlToBinary - * @param DecodeBase64UrlToString - * @param FileToolsOptions - * @internal - */ -const _injectLTSFileTools = (DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior) => { - /** - * Backwards compatibility. - * @internal - * @deprecated - */ - FileTools = { - DecodeBase64UrlToBinary, - DecodeBase64UrlToString, - DefaultRetryStrategy: FileToolsOptions.DefaultRetryStrategy, - BaseUrl: FileToolsOptions.BaseUrl, - CorsBehavior: FileToolsOptions.CorsBehavior, - PreprocessUrl: FileToolsOptions.PreprocessUrl, - IsBase64DataUrl, - IsFileURL, - LoadFile, - LoadImage, - ReadFile, - RequestFile, - SetCorsBehavior, - }; - Object.defineProperty(FileTools, "DefaultRetryStrategy", { - get: function () { - return FileToolsOptions.DefaultRetryStrategy; - }, - set: function (value) { - FileToolsOptions.DefaultRetryStrategy = value; - }, - }); - Object.defineProperty(FileTools, "BaseUrl", { - get: function () { - return FileToolsOptions.BaseUrl; - }, - set: function (value) { - FileToolsOptions.BaseUrl = value; - }, - }); - Object.defineProperty(FileTools, "PreprocessUrl", { - get: function () { - return FileToolsOptions.PreprocessUrl; - }, - set: function (value) { - FileToolsOptions.PreprocessUrl = value; - }, - }); - Object.defineProperty(FileTools, "CorsBehavior", { - get: function () { - return FileToolsOptions.CorsBehavior; - }, - set: function (value) { - FileToolsOptions.CorsBehavior = value; - }, - }); -}; -_injectLTSFileTools(DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior); -//# sourceMappingURL=fileTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/instantiationTools.js - - -/** - * Class used to enable instantiation of objects by class name - */ -class InstantiationTools { - /** - * Tries to instantiate a new object from a given class name - * @param className defines the class name to instantiate - * @returns the new object or null if the system was not able to do the instantiation - */ - static Instantiate(className) { - if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[className]) { - return this.RegisteredExternalClasses[className]; - } - const internalClass = GetClass(className); - if (internalClass) { - return internalClass; - } - logger_Logger.Warn(className + " not found, you may have missed an import."); - const arr = className.split("."); - let fn = window || this; - for (let i = 0, len = arr.length; i < len; i++) { - fn = fn[arr[i]]; - } - if (typeof fn !== "function") { - return null; - } - return fn; - } -} -/** - * Use this object to register external classes like custom textures or material - * to allow the loaders to instantiate them - */ -InstantiationTools.RegisteredExternalClasses = {}; -//# sourceMappingURL=instantiationTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/guid.js -/** - * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 - * Be aware Math.random() could cause collisions, but: - * "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" - * @returns a pseudo random id - */ -function guid_RandomGUID() { - return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { - const r = (Math.random() * 16) | 0, v = c === "x" ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); -} -/** - * Class used to manipulate GUIDs - */ -const GUID = { - /** - * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 - * Be aware Math.random() could cause collisions, but: - * "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" - * @returns a pseudo random id - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - RandomId: guid_RandomGUID, -}; -//# sourceMappingURL=guid.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/tools.js - - - - - - - - - - - - -/** - * Class containing a set of static utilities functions - */ -class tools_Tools { - /** - * Gets or sets the base URL to use to load assets - */ - static get BaseUrl() { - return FileToolsOptions.BaseUrl; - } - static set BaseUrl(value) { - FileToolsOptions.BaseUrl = value; - } - /** - * Gets or sets the retry strategy to apply when an error happens while loading an asset - */ - static get DefaultRetryStrategy() { - return FileToolsOptions.DefaultRetryStrategy; - } - static set DefaultRetryStrategy(strategy) { - FileToolsOptions.DefaultRetryStrategy = strategy; - } - /** - * Default behaviour for cors in the application. - * It can be a string if the expected behavior is identical in the entire app. - * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance) - */ - static get CorsBehavior() { - return FileToolsOptions.CorsBehavior; - } - static set CorsBehavior(value) { - FileToolsOptions.CorsBehavior = value; - } - /** - * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded - * @ignorenaming - */ - static get UseFallbackTexture() { - return engineStore_EngineStore.UseFallbackTexture; - } - static set UseFallbackTexture(value) { - engineStore_EngineStore.UseFallbackTexture = value; - } - /** - * Use this object to register external classes like custom textures or material - * to allow the loaders to instantiate them - */ - static get RegisteredExternalClasses() { - return InstantiationTools.RegisteredExternalClasses; - } - static set RegisteredExternalClasses(classes) { - InstantiationTools.RegisteredExternalClasses = classes; - } - /** - * Texture content used if a texture cannot loaded - * @ignorenaming - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static get fallbackTexture() { - return engineStore_EngineStore.FallbackTexture; - } - // eslint-disable-next-line @typescript-eslint/naming-convention - static set fallbackTexture(value) { - engineStore_EngineStore.FallbackTexture = value; - } - /** - * Read the content of a byte array at a specified coordinates (taking in account wrapping) - * @param u defines the coordinate on X axis - * @param v defines the coordinate on Y axis - * @param width defines the width of the source data - * @param height defines the height of the source data - * @param pixels defines the source byte array - * @param color defines the output color - */ - static FetchToRef(u, v, width, height, pixels, color) { - const wrappedU = (Math.abs(u) * width) % width | 0; - const wrappedV = (Math.abs(v) * height) % height | 0; - const position = (wrappedU + wrappedV * width) * 4; - color.r = pixels[position] / 255; - color.g = pixels[position + 1] / 255; - color.b = pixels[position + 2] / 255; - color.a = pixels[position + 3] / 255; - } - /** - * Interpolates between a and b via alpha - * @param a The lower value (returned when alpha = 0) - * @param b The upper value (returned when alpha = 1) - * @param alpha The interpolation-factor - * @returns The mixed value - */ - static Mix(a, b, alpha) { - return a * (1 - alpha) + b * alpha; - } - /** - * Tries to instantiate a new object from a given class name - * @param className defines the class name to instantiate - * @returns the new object or null if the system was not able to do the instantiation - */ - static Instantiate(className) { - return InstantiationTools.Instantiate(className); - } - /** - * Polyfill for setImmediate - * @param action defines the action to execute after the current execution block - */ - static SetImmediate(action) { - TimingTools.SetImmediate(action); - } - /** - * Function indicating if a number is an exponent of 2 - * @param value defines the value to test - * @returns true if the value is an exponent of 2 - */ - static IsExponentOfTwo(value) { - let count = 1; - do { - count *= 2; - } while (count < value); - return count === value; - } - /** - * Returns the nearest 32-bit single precision float representation of a Number - * @param value A Number. If the parameter is of a different type, it will get converted - * to a number or to NaN if it cannot be converted - * @returns number - */ - static FloatRound(value) { - if (Math.fround) { - return Math.fround(value); - } - return (tools_Tools._TmpFloatArray[0] = value), tools_Tools._TmpFloatArray[0]; - } - /** - * Extracts the filename from a path - * @param path defines the path to use - * @returns the filename - */ - static GetFilename(path) { - const index = path.lastIndexOf("/"); - if (index < 0) { - return path; - } - return path.substring(index + 1); - } - /** - * Extracts the "folder" part of a path (everything before the filename). - * @param uri The URI to extract the info from - * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present - * @returns The "folder" part of the path - */ - static GetFolderPath(uri, returnUnchangedIfNoSlash = false) { - const index = uri.lastIndexOf("/"); - if (index < 0) { - if (returnUnchangedIfNoSlash) { - return uri; - } - return ""; - } - return uri.substring(0, index + 1); - } - /** - * Convert an angle in radians to degrees - * @param angle defines the angle to convert - * @returns the angle in degrees - */ - static ToDegrees(angle) { - return (angle * 180) / Math.PI; - } - /** - * Convert an angle in degrees to radians - * @param angle defines the angle to convert - * @returns the angle in radians - */ - static ToRadians(angle) { - return (angle * Math.PI) / 180; - } - /** - * Smooth angle changes (kind of low-pass filter), in particular for device orientation "shaking" - * Use trigonometric functions to avoid discontinuity (0/360, -180/180) - * @param previousAngle defines last angle value, in degrees - * @param newAngle defines new angle value, in degrees - * @param smoothFactor defines smoothing sensitivity; min 0: no smoothing, max 1: new data ignored - * @returns the angle in degrees - */ - static SmoothAngleChange(previousAngle, newAngle, smoothFactor = 0.9) { - const previousAngleRad = this.ToRadians(previousAngle); - const newAngleRad = this.ToRadians(newAngle); - return this.ToDegrees(Math.atan2((1 - smoothFactor) * Math.sin(newAngleRad) + smoothFactor * Math.sin(previousAngleRad), (1 - smoothFactor) * Math.cos(newAngleRad) + smoothFactor * Math.cos(previousAngleRad))); - } - /** - * Returns an array if obj is not an array - * @param obj defines the object to evaluate as an array - * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined - * @returns either obj directly if obj is an array or a new array containing obj - */ - static MakeArray(obj, allowsNullUndefined) { - if (allowsNullUndefined !== true && (obj === undefined || obj == null)) { - return null; - } - return Array.isArray(obj) ? obj : [obj]; - } - /** - * Gets the pointer prefix to use - * @param engine defines the engine we are finding the prefix for - * @returns "pointer" if touch is enabled. Else returns "mouse" - */ - static GetPointerPrefix(engine) { - let eventPrefix = "pointer"; - // Check if pointer events are supported - if (IsWindowObjectExist() && !window.PointerEvent) { - eventPrefix = "mouse"; - } - // Special Fallback MacOS Safari... - if (engine._badDesktopOS && - !engine._badOS && - // And not ipad pros who claim to be macs... - !(document && "ontouchend" in document)) { - eventPrefix = "mouse"; - } - return eventPrefix; - } - /** - * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element. - * @param url define the url we are trying - * @param element define the dom element where to configure the cors policy - * @param element.crossOrigin - */ - static SetCorsBehavior(url, element) { - SetCorsBehavior(url, element); - } - /** - * Sets the referrerPolicy behavior on a dom element. - * @param referrerPolicy define the referrer policy to use - * @param element define the dom element where to configure the referrer policy - * @param element.referrerPolicy - */ - static SetReferrerPolicyBehavior(referrerPolicy, element) { - element.referrerPolicy = referrerPolicy; - } - // External files - /** - * Removes unwanted characters from an url - * @param url defines the url to clean - * @returns the cleaned url - */ - static CleanUrl(url) { - url = url.replace(/#/gm, "%23"); - return url; - } - /** - * Gets or sets a function used to pre-process url before using them to load assets - */ - static get PreprocessUrl() { - return FileToolsOptions.PreprocessUrl; - } - static set PreprocessUrl(processor) { - FileToolsOptions.PreprocessUrl = processor; - } - /** - * Loads an image as an HTMLImageElement. - * @param input url string, ArrayBuffer, or Blob to load - * @param onLoad callback called when the image successfully loads - * @param onError callback called when the image fails to load - * @param offlineProvider offline provider for caching - * @param mimeType optional mime type - * @param imageBitmapOptions optional the options to use when creating an ImageBitmap - * @returns the HTMLImageElement of the loaded image - */ - static LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions) { - return LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions); - } - /** - * Loads a file from a url - * @param url url string, ArrayBuffer, or Blob to load - * @param onSuccess callback called when the file successfully loads - * @param onProgress callback called while file is loading (if the server supports this mode) - * @param offlineProvider defines the offline provider for caching - * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer - * @param onError callback called when the file fails to load - * @returns a file request object - */ - static LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { - return LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); - } - /** - * Loads a file from a url - * @param url the file url to load - * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer - * @returns a promise containing an ArrayBuffer corresponding to the loaded file - */ - static LoadFileAsync(url, useArrayBuffer = true) { - return new Promise((resolve, reject) => { - LoadFile(url, (data) => { - resolve(data); - }, undefined, undefined, useArrayBuffer, (request, exception) => { - reject(exception); - }); - }); - } - /** - * Load a script (identified by an url). When the url returns, the - * content of this file is added into a new script element, attached to the DOM (body element) - * @param scriptUrl defines the url of the script to laod - * @param onSuccess defines the callback called when the script is loaded - * @param onError defines the callback to call if an error occurs - * @param scriptId defines the id of the script element - */ - static LoadScript(scriptUrl, onSuccess, onError, scriptId) { - if (typeof importScripts === "function") { - try { - importScripts(scriptUrl); - onSuccess(); - } - catch (e) { - onError === null || onError === void 0 ? void 0 : onError(`Unable to load script '${scriptUrl}' in worker`, e); - } - return; - } - else if (!IsWindowObjectExist()) { - onError === null || onError === void 0 ? void 0 : onError(`Cannot load script '${scriptUrl}' outside of a window or a worker`); - return; - } - const head = document.getElementsByTagName("head")[0]; - const script = document.createElement("script"); - script.setAttribute("type", "text/javascript"); - script.setAttribute("src", scriptUrl); - if (scriptId) { - script.id = scriptId; - } - script.onload = () => { - if (onSuccess) { - onSuccess(); - } - }; - script.onerror = (e) => { - if (onError) { - onError(`Unable to load script '${scriptUrl}'`, e); - } - }; - head.appendChild(script); - } - /** - * Load an asynchronous script (identified by an url). When the url returns, the - * content of this file is added into a new script element, attached to the DOM (body element) - * @param scriptUrl defines the url of the script to laod - * @returns a promise request object - */ - static LoadScriptAsync(scriptUrl) { - return new Promise((resolve, reject) => { - this.LoadScript(scriptUrl, () => { - resolve(); - }, (message, exception) => { - reject(exception || new Error(message)); - }); - }); - } - /** - * Loads a file from a blob - * @param fileToLoad defines the blob to use - * @param callback defines the callback to call when data is loaded - * @param progressCallback defines the callback to call during loading process - * @returns a file request object - */ - static ReadFileAsDataURL(fileToLoad, callback, progressCallback) { - const reader = new FileReader(); - const request = { - onCompleteObservable: new observable_Observable(), - abort: () => reader.abort(), - }; - reader.onloadend = () => { - request.onCompleteObservable.notifyObservers(request); - }; - reader.onload = (e) => { - //target doesn't have result from ts 1.3 - callback(e.target["result"]); - }; - reader.onprogress = progressCallback; - reader.readAsDataURL(fileToLoad); - return request; - } - /** - * Reads a file from a File object - * @param file defines the file to load - * @param onSuccess defines the callback to call when data is loaded - * @param onProgress defines the callback to call during loading process - * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer - * @param onError defines the callback to call when an error occurs - * @returns a file request object - */ - static ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError) { - return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError); - } - /** - * Creates a data url from a given string content - * @param content defines the content to convert - * @returns the new data url link - */ - static FileAsURL(content) { - const fileBlob = new Blob([content]); - const url = window.URL; - const link = url.createObjectURL(fileBlob); - return link; - } - /** - * Format the given number to a specific decimal format - * @param value defines the number to format - * @param decimals defines the number of decimals to use - * @returns the formatted string - */ - static Format(value, decimals = 2) { - return value.toFixed(decimals); - } - /** - * Tries to copy an object by duplicating every property - * @param source defines the source object - * @param destination defines the target object - * @param doNotCopyList defines a list of properties to avoid - * @param mustCopyList defines a list of properties to copy (even if they start with _) - */ - static DeepCopy(source, destination, doNotCopyList, mustCopyList) { - DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList); - } - /** - * Gets a boolean indicating if the given object has no own property - * @param obj defines the object to test - * @returns true if object has no own property - */ - static IsEmpty(obj) { - for (const i in obj) { - if (Object.prototype.hasOwnProperty.call(obj, i)) { - return false; - } - } - return true; - } - /** - * Function used to register events at window level - * @param windowElement defines the Window object to use - * @param events defines the events to register - */ - static RegisterTopRootEvents(windowElement, events) { - for (let index = 0; index < events.length; index++) { - const event = events[index]; - windowElement.addEventListener(event.name, event.handler, false); - try { - if (window.parent) { - window.parent.addEventListener(event.name, event.handler, false); - } - } - catch (e) { - // Silently fails... - } - } - } - /** - * Function used to unregister events from window level - * @param windowElement defines the Window object to use - * @param events defines the events to unregister - */ - static UnregisterTopRootEvents(windowElement, events) { - for (let index = 0; index < events.length; index++) { - const event = events[index]; - windowElement.removeEventListener(event.name, event.handler); - try { - if (windowElement.parent) { - windowElement.parent.removeEventListener(event.name, event.handler); - } - } - catch (e) { - // Silently fails... - } - } - } - /** - * Dumps the current bound framebuffer - * @param width defines the rendering width - * @param height defines the rendering height - * @param engine defines the hosting engine - * @param successCallback defines the callback triggered once the data are available - * @param mimeType defines the mime type of the result - * @param fileName defines the filename to download. If present, the result will automatically be downloaded - * @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. - * @returns a void promise - */ - static async DumpFramebuffer(width, height, engine, successCallback, mimeType = "image/png", fileName, quality) { - throw _WarnImport("DumpTools"); - } - /** - * Dumps an array buffer - * @param width defines the rendering width - * @param height defines the rendering height - * @param data the data array - * @param successCallback defines the callback triggered once the data are available - * @param mimeType defines the mime type of the result - * @param fileName defines the filename to download. If present, the result will automatically be downloaded - * @param invertY true to invert the picture in the Y dimension - * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string - * @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. - */ - static DumpData(width, height, data, successCallback, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { - throw _WarnImport("DumpTools"); - } - /** - * Dumps an array buffer - * @param width defines the rendering width - * @param height defines the rendering height - * @param data the data array - * @param mimeType defines the mime type of the result - * @param fileName defines the filename to download. If present, the result will automatically be downloaded - * @param invertY true to invert the picture in the Y dimension - * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string - * @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. - * @returns a promise that resolve to the final data - */ - static DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { - throw _WarnImport("DumpTools"); - } - static _IsOffScreenCanvas(canvas) { - return canvas.convertToBlob !== undefined; - } - /** - * Converts the canvas data to blob. - * This acts as a polyfill for browsers not supporting the to blob function. - * @param canvas Defines the canvas to extract the data from (can be an offscreen canvas) - * @param successCallback Defines the callback triggered once the data are available - * @param mimeType Defines the mime type of the result - * @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. - */ - static ToBlob(canvas, successCallback, mimeType = "image/png", quality) { - // We need HTMLCanvasElement.toBlob for HD screenshots - if (!tools_Tools._IsOffScreenCanvas(canvas) && !canvas.toBlob) { - // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob) - canvas.toBlob = function (callback, type, quality) { - setTimeout(() => { - const binStr = atob(this.toDataURL(type, quality).split(",")[1]), len = binStr.length, arr = new Uint8Array(len); - for (let i = 0; i < len; i++) { - arr[i] = binStr.charCodeAt(i); - } - callback(new Blob([arr])); - }); - }; - } - if (tools_Tools._IsOffScreenCanvas(canvas)) { - canvas - .convertToBlob({ - type: mimeType, - quality, - }) - .then((blob) => successCallback(blob)); - } - else { - canvas.toBlob(function (blob) { - successCallback(blob); - }, mimeType, quality); - } - } - /** - * Download a Blob object - * @param blob the Blob object - * @param fileName the file name to download - * @returns - */ - static DownloadBlob(blob, fileName) { - //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image. - if ("download" in document.createElement("a")) { - if (!fileName) { - const date = new Date(); - const stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ("0" + date.getMinutes()).slice(-2); - fileName = "screenshot_" + stringDate + ".png"; - } - tools_Tools.Download(blob, fileName); - } - else { - if (blob && typeof URL !== "undefined") { - const url = URL.createObjectURL(blob); - const newWindow = window.open(""); - if (!newWindow) { - return; - } - const img = newWindow.document.createElement("img"); - img.onload = function () { - // no longer need to read the blob so it's revoked - URL.revokeObjectURL(url); - }; - img.src = url; - newWindow.document.body.appendChild(img); - } - } - } - /** - * Encodes the canvas data to base 64, or automatically downloads the result if `fileName` is defined. - * @param canvas The canvas to get the data from, which can be an offscreen canvas. - * @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. - * @param mimeType The mime type of the result. - * @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. - * @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. - */ - static EncodeScreenshotCanvasData(canvas, successCallback, mimeType = "image/png", fileName, quality) { - if (typeof fileName === "string" || !successCallback) { - this.ToBlob(canvas, function (blob) { - if (blob) { - tools_Tools.DownloadBlob(blob, fileName); - } - if (successCallback) { - successCallback(""); - } - }, mimeType, quality); - } - else if (successCallback) { - if (tools_Tools._IsOffScreenCanvas(canvas)) { - canvas - .convertToBlob({ - type: mimeType, - quality, - }) - .then((blob) => { - const reader = new FileReader(); - reader.readAsDataURL(blob); - reader.onloadend = () => { - const base64data = reader.result; - successCallback(base64data); - }; - }); - return; - } - const base64Image = canvas.toDataURL(mimeType, quality); - successCallback(base64Image); - } - } - /** - * Downloads a blob in the browser - * @param blob defines the blob to download - * @param fileName defines the name of the downloaded file - */ - static Download(blob, fileName) { - if (typeof URL === "undefined") { - return; - } - const url = window.URL.createObjectURL(blob); - const a = document.createElement("a"); - document.body.appendChild(a); - a.style.display = "none"; - a.href = url; - a.download = fileName; - a.addEventListener("click", () => { - if (a.parentElement) { - a.parentElement.removeChild(a); - } - }); - a.click(); - window.URL.revokeObjectURL(url); - } - /** - * Will return the right value of the noPreventDefault variable - * Needed to keep backwards compatibility to the old API. - * - * @param args arguments passed to the attachControl function - * @returns the correct value for noPreventDefault - */ - static BackCompatCameraNoPreventDefault(args) { - // is it used correctly? - if (typeof args[0] === "boolean") { - return args[0]; - } - else if (typeof args[1] === "boolean") { - return args[1]; - } - return false; - } - /** - * Captures a screenshot of the current rendering - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine defines the rendering engine - * @param camera defines the source camera - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param successCallback defines the callback receives a single parameter which contains the - * screenshot as a string of base64-encoded characters. This string can be assigned to the - * src parameter of an <img> to display it - * @param mimeType defines the MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @param forceDownload force the system to download the image even if a successCallback is provided - * @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. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static CreateScreenshot(engine, camera, size, successCallback, mimeType = "image/png", forceDownload = false, quality) { - throw _WarnImport("ScreenshotTools"); - } - /** - * Captures a screenshot of the current rendering - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine defines the rendering engine - * @param camera defines the source camera - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param mimeType defines the MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @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. - * @returns screenshot as a string of base64-encoded characters. This string can be assigned - * to the src parameter of an <img> to display it - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static CreateScreenshotAsync(engine, camera, size, mimeType = "image/png", quality) { - throw _WarnImport("ScreenshotTools"); - } - /** - * Generates an image screenshot from the specified camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine The engine to use for rendering - * @param camera The camera to use for rendering - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param successCallback The callback receives a single parameter which contains the - * screenshot as a string of base64-encoded characters. This string can be assigned to the - * src parameter of an <img> to display it - * @param mimeType The MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @param samples Texture samples (default: 1) - * @param antialiasing Whether antialiasing should be turned on or not (default: false) - * @param fileName A name for for the downloaded file. - * @param renderSprites Whether the sprites should be rendered or not (default: false) - * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) - * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true) - * @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. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static CreateScreenshotUsingRenderTarget(engine, camera, size, successCallback, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) { - throw _WarnImport("ScreenshotTools"); - } - /** - * Generates an image screenshot from the specified camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine The engine to use for rendering - * @param camera The camera to use for rendering - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param mimeType The MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @param samples Texture samples (default: 1) - * @param antialiasing Whether antialiasing should be turned on or not (default: false) - * @param fileName A name for for the downloaded file. - * @returns screenshot as a string of base64-encoded characters. This string can be assigned - * @param renderSprites Whether the sprites should be rendered or not (default: false) - * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) - * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true) - * @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. - * to the src parameter of an <img> to display it - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) { - throw _WarnImport("ScreenshotTools"); - } - /** - * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 - * Be aware Math.random() could cause collisions, but: - * "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" - * @returns a pseudo random id - */ - static RandomId() { - return guid_RandomGUID(); - } - /** - * Test if the given uri is a base64 string - * @deprecated Please use FileTools.IsBase64DataUrl instead. - * @param uri The uri to test - * @returns True if the uri is a base64 string or false otherwise - */ - static IsBase64(uri) { - return IsBase64DataUrl(uri); - } - /** - * Decode the given base64 uri. - * @deprecated Please use FileTools.DecodeBase64UrlToBinary instead. - * @param uri The uri to decode - * @returns The decoded base64 data. - */ - static DecodeBase64(uri) { - return DecodeBase64UrlToBinary(uri); - } - /** - * Gets a value indicating the number of loading errors - * @ignorenaming - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static get errorsCount() { - return logger_Logger.errorsCount; - } - /** - * Log a message to the console - * @param message defines the message to log - */ - static Log(message) { - logger_Logger.Log(message); - } - /** - * Write a warning message to the console - * @param message defines the message to log - */ - static Warn(message) { - logger_Logger.Warn(message); - } - /** - * Write an error message to the console - * @param message defines the message to log - */ - static Error(message) { - logger_Logger.Error(message); - } - /** - * Gets current log cache (list of logs) - */ - static get LogCache() { - return logger_Logger.LogCache; - } - /** - * Clears the log cache - */ - static ClearLogCache() { - logger_Logger.ClearLogCache(); - } - /** - * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel) - */ - static set LogLevels(level) { - logger_Logger.LogLevels = level; - } - /** - * Sets the current performance log level - */ - static set PerformanceLogLevel(level) { - if ((level & tools_Tools.PerformanceUserMarkLogLevel) === tools_Tools.PerformanceUserMarkLogLevel) { - tools_Tools.StartPerformanceCounter = tools_Tools._StartUserMark; - tools_Tools.EndPerformanceCounter = tools_Tools._EndUserMark; - return; - } - if ((level & tools_Tools.PerformanceConsoleLogLevel) === tools_Tools.PerformanceConsoleLogLevel) { - tools_Tools.StartPerformanceCounter = tools_Tools._StartPerformanceConsole; - tools_Tools.EndPerformanceCounter = tools_Tools._EndPerformanceConsole; - return; - } - tools_Tools.StartPerformanceCounter = tools_Tools._StartPerformanceCounterDisabled; - tools_Tools.EndPerformanceCounter = tools_Tools._EndPerformanceCounterDisabled; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static _StartPerformanceCounterDisabled(counterName, condition) { } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static _EndPerformanceCounterDisabled(counterName, condition) { } - static _StartUserMark(counterName, condition = true) { - if (!tools_Tools._Performance) { - if (!IsWindowObjectExist()) { - return; - } - tools_Tools._Performance = window.performance; - } - if (!condition || !tools_Tools._Performance.mark) { - return; - } - tools_Tools._Performance.mark(counterName + "-Begin"); - } - static _EndUserMark(counterName, condition = true) { - if (!condition || !tools_Tools._Performance.mark) { - return; - } - tools_Tools._Performance.mark(counterName + "-End"); - tools_Tools._Performance.measure(counterName, counterName + "-Begin", counterName + "-End"); - } - static _StartPerformanceConsole(counterName, condition = true) { - if (!condition) { - return; - } - tools_Tools._StartUserMark(counterName, condition); - if (console.time) { - console.time(counterName); - } - } - static _EndPerformanceConsole(counterName, condition = true) { - if (!condition) { - return; - } - tools_Tools._EndUserMark(counterName, condition); - console.timeEnd(counterName); - } - /** - * Gets either window.performance.now() if supported or Date.now() else - */ - static get Now() { - return precisionDate_PrecisionDate.Now; - } - /** - * This method will return the name of the class used to create the instance of the given object. - * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator. - * @param object the object to get the class name from - * @param isType defines if the object is actually a type - * @returns the name of the class, will be "object" for a custom data type not using the @className decorator - */ - static GetClassName(object, isType = false) { - let name = null; - if (!isType && object.getClassName) { - name = object.getClassName(); - } - else { - if (object instanceof Object) { - const classObj = isType ? object : Object.getPrototypeOf(object); - name = classObj.constructor["__bjsclassName__"]; - } - if (!name) { - name = typeof object; - } - } - return name; - } - /** - * Gets the first element of an array satisfying a given predicate - * @param array defines the array to browse - * @param predicate defines the predicate to use - * @returns null if not found or the element - */ - static First(array, predicate) { - for (const el of array) { - if (predicate(el)) { - return el; - } - } - return null; - } - /** - * This method will return the name of the full name of the class, including its owning module (if any). - * 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). - * @param object the object to get the class name from - * @param isType defines if the object is actually a type - * @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. - * @ignorenaming - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static getFullClassName(object, isType = false) { - let className = null; - let moduleName = null; - if (!isType && object.getClassName) { - className = object.getClassName(); - } - else { - if (object instanceof Object) { - const classObj = isType ? object : Object.getPrototypeOf(object); - className = classObj.constructor["__bjsclassName__"]; - moduleName = classObj.constructor["__bjsmoduleName__"]; - } - if (!className) { - className = typeof object; - } - } - if (!className) { - return null; - } - return (moduleName != null ? moduleName + "." : "") + className; - } - /** - * Returns a promise that resolves after the given amount of time. - * @param delay Number of milliseconds to delay - * @returns Promise that resolves after the given amount of time - */ - static DelayAsync(delay) { - return new Promise((resolve) => { - setTimeout(() => { - resolve(); - }, delay); - }); - } - /** - * Utility function to detect if the current user agent is Safari - * @returns whether or not the current user agent is safari - */ - static IsSafari() { - if (!IsNavigatorAvailable()) { - return false; - } - return /^((?!chrome|android).)*safari/i.test(navigator.userAgent); - } -} -/** - * Enable/Disable Custom HTTP Request Headers globally. - * default = false - * @see CustomRequestHeaders - */ -tools_Tools.UseCustomRequestHeaders = false; -/** - * Custom HTTP Request Headers to be sent with XMLHttpRequests - * i.e. when loading files, where the server/service expects an Authorization header - */ -tools_Tools.CustomRequestHeaders = webRequest_WebRequest.CustomRequestHeaders; -tools_Tools._TmpFloatArray = new Float32Array(1); -/** - * Extracts text content from a DOM element hierarchy - * Back Compat only, please use GetDOMTextContent instead. - */ -tools_Tools.GetDOMTextContent = GetDOMTextContent; -tools_Tools.GetAbsoluteUrl = typeof document === "object" - ? (url) => { - const a = document.createElement("a"); - a.href = url; - return a.href; - } - : typeof URL === "function" && typeof location === "object" - ? (url) => new URL(url, location.origin).href - : () => { - throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context."); - }; -// Logs -/** - * No log - */ -tools_Tools.NoneLogLevel = logger_Logger.NoneLogLevel; -/** - * Only message logs - */ -tools_Tools.MessageLogLevel = logger_Logger.MessageLogLevel; -/** - * Only warning logs - */ -tools_Tools.WarningLogLevel = logger_Logger.WarningLogLevel; -/** - * Only error logs - */ -tools_Tools.ErrorLogLevel = logger_Logger.ErrorLogLevel; -/** - * All logs - */ -tools_Tools.AllLogLevel = logger_Logger.AllLogLevel; -/** - * Checks if the window object exists - * Back Compat only, please use IsWindowObjectExist instead. - */ -tools_Tools.IsWindowObjectExist = IsWindowObjectExist; -// Performances -/** - * No performance log - */ -tools_Tools.PerformanceNoneLogLevel = 0; -/** - * Use user marks to log performance - */ -tools_Tools.PerformanceUserMarkLogLevel = 1; -/** - * Log performance to the console - */ -tools_Tools.PerformanceConsoleLogLevel = 2; -/** - * Starts a performance counter - */ -tools_Tools.StartPerformanceCounter = tools_Tools._StartPerformanceCounterDisabled; -/** - * Ends a specific performance counter - */ -tools_Tools.EndPerformanceCounter = tools_Tools._EndPerformanceCounterDisabled; -/** - * Use this className as a decorator on a given class definition to add it a name and optionally its module. - * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name. - * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified - * @param name The name of the class, case should be preserved - * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved. - */ -function className(name, module) { - return (target) => { - target["__bjsclassName__"] = name; - target["__bjsmoduleName__"] = module != null ? module : null; - }; -} -/** - * An implementation of a loop for asynchronous functions. - */ -class AsyncLoop { - /** - * Constructor. - * @param iterations the number of iterations. - * @param func the function to run each iteration - * @param successCallback the callback that will be called upon successful execution - * @param offset starting offset. - */ - constructor( - /** - * Defines the number of iterations for the loop - */ - iterations, func, successCallback, offset = 0) { - this.iterations = iterations; - this.index = offset - 1; - this._done = false; - this._fn = func; - this._successCallback = successCallback; - } - /** - * Execute the next iteration. Must be called after the last iteration was finished. - */ - executeNext() { - if (!this._done) { - if (this.index + 1 < this.iterations) { - ++this.index; - this._fn(this); - } - else { - this.breakLoop(); - } - } - } - /** - * Break the loop and run the success callback. - */ - breakLoop() { - this._done = true; - this._successCallback(); - } - /** - * Create and run an async loop. - * @param iterations the number of iterations. - * @param fn the function to run each iteration - * @param successCallback the callback that will be called upon successful execution - * @param offset starting offset. - * @returns the created async loop object - */ - static Run(iterations, fn, successCallback, offset = 0) { - const loop = new AsyncLoop(iterations, fn, successCallback, offset); - loop.executeNext(); - return loop; - } - /** - * A for-loop that will run a given number of iterations synchronous and the rest async. - * @param iterations total number of iterations - * @param syncedIterations number of synchronous iterations in each async iteration. - * @param fn the function to call each iteration. - * @param callback a success call back that will be called when iterating stops. - * @param breakFunction a break condition (optional) - * @param timeout timeout settings for the setTimeout function. default - 0. - * @returns the created async loop object - */ - static SyncAsyncForLoop(iterations, syncedIterations, fn, callback, breakFunction, timeout = 0) { - return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop) => { - if (breakFunction && breakFunction()) { - loop.breakLoop(); - } - else { - setTimeout(() => { - for (let i = 0; i < syncedIterations; ++i) { - const iteration = loop.index * syncedIterations + i; - if (iteration >= iterations) { - break; - } - fn(iteration); - if (breakFunction && breakFunction()) { - loop.breakLoop(); - break; - } - } - loop.executeNext(); - }, timeout); - } - }, callback); - } -} -// Will only be define if Tools is imported freeing up some space when only engine is required -engineStore_EngineStore.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"; -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/smartArray.js -/** - * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations. - */ -class SmartArray { - /** - * Instantiates a Smart Array. - * @param capacity defines the default capacity of the array. - */ - constructor(capacity) { - /** - * The active length of the array. - */ - this.length = 0; - this.data = new Array(capacity); - this._id = SmartArray._GlobalId++; - } - /** - * Pushes a value at the end of the active data. - * @param value defines the object to push in the array. - */ - push(value) { - this.data[this.length++] = value; - if (this.length > this.data.length) { - this.data.length *= 2; - } - } - /** - * Iterates over the active data and apply the lambda to them. - * @param func defines the action to apply on each value. - */ - forEach(func) { - for (let index = 0; index < this.length; index++) { - func(this.data[index]); - } - } - /** - * Sorts the full sets of data. - * @param compareFn defines the comparison function to apply. - */ - sort(compareFn) { - this.data.sort(compareFn); - } - /** - * Resets the active data to an empty array. - */ - reset() { - this.length = 0; - } - /** - * Releases all the data from the array as well as the array. - */ - dispose() { - this.reset(); - if (this.data) { - this.data.length = 0; - } - } - /** - * Concats the active data with a given array. - * @param array defines the data to concatenate with. - */ - concat(array) { - if (array.length === 0) { - return; - } - if (this.length + array.length > this.data.length) { - this.data.length = (this.length + array.length) * 2; - } - for (let index = 0; index < array.length; index++) { - this.data[this.length++] = (array.data || array)[index]; - } - } - /** - * Returns the position of a value in the active data. - * @param value defines the value to find the index for - * @returns the index if found in the active data otherwise -1 - */ - indexOf(value) { - const position = this.data.indexOf(value); - if (position >= this.length) { - return -1; - } - return position; - } - /** - * Returns whether an element is part of the active data. - * @param value defines the value to look for - * @returns true if found in the active data otherwise false - */ - contains(value) { - return this.indexOf(value) !== -1; - } -} -// Statics -SmartArray._GlobalId = 0; -/** - * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations. - * The data in this array can only be present once - */ -class SmartArrayNoDuplicate extends SmartArray { - constructor() { - super(...arguments); - this._duplicateId = 0; - } - /** - * Pushes a value at the end of the active data. - * THIS DOES NOT PREVENT DUPPLICATE DATA - * @param value defines the object to push in the array. - */ - push(value) { - super.push(value); - if (!value.__smartArrayFlags) { - value.__smartArrayFlags = {}; - } - value.__smartArrayFlags[this._id] = this._duplicateId; - } - /** - * Pushes a value at the end of the active data. - * If the data is already present, it won t be added again - * @param value defines the object to push in the array. - * @returns true if added false if it was already present - */ - pushNoDuplicate(value) { - if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) { - return false; - } - this.push(value); - return true; - } - /** - * Resets the active data to an empty array. - */ - reset() { - super.reset(); - this._duplicateId++; - } - /** - * Concats the active data with a given array. - * This ensures no duplicate will be present in the result. - * @param array defines the data to concatenate with. - */ - concatWithNoDuplicate(array) { - if (array.length === 0) { - return; - } - if (this.length + array.length > this.data.length) { - this.data.length = (this.length + array.length) * 2; - } - for (let index = 0; index < array.length; index++) { - const item = (array.data || array)[index]; - this.pushNoDuplicate(item); - } - } -} -//# sourceMappingURL=smartArray.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/stringDictionary.js -/** - * This class implement a typical dictionary using a string as key and the generic type T as value. - * The underlying implementation relies on an associative array to ensure the best performances. - * The value can be anything including 'null' but except 'undefined' - */ -class StringDictionary { - constructor() { - this._count = 0; - this._data = {}; - } - /** - * This will clear this dictionary and copy the content from the 'source' one. - * If the T value is a custom object, it won't be copied/cloned, the same object will be used - * @param source the dictionary to take the content from and copy to this dictionary - */ - copyFrom(source) { - this.clear(); - source.forEach((t, v) => this.add(t, v)); - } - /** - * Get a value based from its key - * @param key the given key to get the matching value from - * @returns the value if found, otherwise undefined is returned - */ - get(key) { - const val = this._data[key]; - if (val !== undefined) { - return val; - } - return undefined; - } - /** - * Get a value from its key or add it if it doesn't exist. - * This method will ensure you that a given key/data will be present in the dictionary. - * @param key the given key to get the matching value from - * @param factory the factory that will create the value if the key is not present in the dictionary. - * The factory will only be invoked if there's no data for the given key. - * @returns the value corresponding to the key. - */ - getOrAddWithFactory(key, factory) { - let val = this.get(key); - if (val !== undefined) { - return val; - } - val = factory(key); - if (val) { - this.add(key, val); - } - return val; - } - /** - * Get a value from its key if present in the dictionary otherwise add it - * @param key the key to get the value from - * @param val if there's no such key/value pair in the dictionary add it with this value - * @returns the value corresponding to the key - */ - getOrAdd(key, val) { - const curVal = this.get(key); - if (curVal !== undefined) { - return curVal; - } - this.add(key, val); - return val; - } - /** - * Check if there's a given key in the dictionary - * @param key the key to check for - * @returns true if the key is present, false otherwise - */ - contains(key) { - return this._data[key] !== undefined; - } - /** - * Add a new key and its corresponding value - * @param key the key to add - * @param value the value corresponding to the key - * @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 - */ - add(key, value) { - if (this._data[key] !== undefined) { - return false; - } - this._data[key] = value; - ++this._count; - return true; - } - /** - * Update a specific value associated to a key - * @param key defines the key to use - * @param value defines the value to store - * @returns true if the value was updated (or false if the key was not found) - */ - set(key, value) { - if (this._data[key] === undefined) { - return false; - } - this._data[key] = value; - return true; - } - /** - * Get the element of the given key and remove it from the dictionary - * @param key defines the key to search - * @returns the value associated with the key or null if not found - */ - getAndRemove(key) { - const val = this.get(key); - if (val !== undefined) { - delete this._data[key]; - --this._count; - return val; - } - return null; - } - /** - * Remove a key/value from the dictionary. - * @param key the key to remove - * @returns true if the item was successfully deleted, false if no item with such key exist in the dictionary - */ - remove(key) { - if (this.contains(key)) { - delete this._data[key]; - --this._count; - return true; - } - return false; - } - /** - * Clear the whole content of the dictionary - */ - clear() { - this._data = {}; - this._count = 0; - } - /** - * Gets the current count - */ - get count() { - return this._count; - } - /** - * Execute a callback on each key/val of the dictionary. - * Note that you can remove any element in this dictionary in the callback implementation - * @param callback the callback to execute on a given key/value pair - */ - forEach(callback) { - for (const cur in this._data) { - const val = this._data[cur]; - callback(cur, val); - } - } - /** - * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object. - * If the callback returns null or undefined the method will iterate to the next key/value pair - * Note that you can remove any element in this dictionary in the callback implementation - * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned - * @returns the first item - */ - first(callback) { - for (const cur in this._data) { - const val = this._data[cur]; - const res = callback(cur, val); - if (res) { - return res; - } - } - return null; - } -} -//# sourceMappingURL=stringDictionary.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/materialDefines.js -/** - * Manages the defines for the Material - */ -class MaterialDefines { - /** - * Creates a new instance - * @param externalProperties list of external properties to inject into the object - */ - constructor(externalProperties) { - /** @internal */ - this._keys = []; - this._isDirty = true; - /** @internal */ - this._areLightsDirty = true; - /** @internal */ - this._areLightsDisposed = false; - /** @internal */ - this._areAttributesDirty = true; - /** @internal */ - this._areTexturesDirty = true; - /** @internal */ - this._areFresnelDirty = true; - /** @internal */ - this._areMiscDirty = true; - /** @internal */ - this._arePrePassDirty = true; - /** @internal */ - this._areImageProcessingDirty = true; - /** @internal */ - this._normals = false; - /** @internal */ - this._uvs = false; - /** @internal */ - this._needNormals = false; - /** @internal */ - this._needUVs = false; - this._externalProperties = externalProperties; - // Initialize External Properties - if (externalProperties) { - for (const prop in externalProperties) { - if (Object.prototype.hasOwnProperty.call(externalProperties, prop)) { - this._setDefaultValue(prop); - } - } - } - } - /** - * Specifies if the material needs to be re-calculated - */ - get isDirty() { - return this._isDirty; - } - /** - * Marks the material to indicate that it has been re-calculated - */ - markAsProcessed() { - this._isDirty = false; - this._areAttributesDirty = false; - this._areTexturesDirty = false; - this._areFresnelDirty = false; - this._areLightsDirty = false; - this._areLightsDisposed = false; - this._areMiscDirty = false; - this._arePrePassDirty = false; - this._areImageProcessingDirty = false; - } - /** - * Marks the material to indicate that it needs to be re-calculated - */ - markAsUnprocessed() { - this._isDirty = true; - } - /** - * Marks the material to indicate all of its defines need to be re-calculated - */ - markAllAsDirty() { - this._areTexturesDirty = true; - this._areAttributesDirty = true; - this._areLightsDirty = true; - this._areFresnelDirty = true; - this._areMiscDirty = true; - this._arePrePassDirty = false; - this._areImageProcessingDirty = true; - this._isDirty = true; - } - /** - * Marks the material to indicate that image processing needs to be re-calculated - */ - markAsImageProcessingDirty() { - this._areImageProcessingDirty = true; - this._isDirty = true; - } - /** - * Marks the material to indicate the lights need to be re-calculated - * @param disposed Defines whether the light is dirty due to dispose or not - */ - markAsLightDirty(disposed = false) { - this._areLightsDirty = true; - this._areLightsDisposed = this._areLightsDisposed || disposed; - this._isDirty = true; - } - /** - * Marks the attribute state as changed - */ - markAsAttributesDirty() { - this._areAttributesDirty = true; - this._isDirty = true; - } - /** - * Marks the texture state as changed - */ - markAsTexturesDirty() { - this._areTexturesDirty = true; - this._isDirty = true; - } - /** - * Marks the fresnel state as changed - */ - markAsFresnelDirty() { - this._areFresnelDirty = true; - this._isDirty = true; - } - /** - * Marks the misc state as changed - */ - markAsMiscDirty() { - this._areMiscDirty = true; - this._isDirty = true; - } - /** - * Marks the prepass state as changed - */ - markAsPrePassDirty() { - this._arePrePassDirty = true; - this._isDirty = true; - } - /** - * Rebuilds the material defines - */ - rebuild() { - this._keys.length = 0; - for (const key of Object.keys(this)) { - if (key[0] === "_") { - continue; - } - this._keys.push(key); - } - if (this._externalProperties) { - for (const name in this._externalProperties) { - if (this._keys.indexOf(name) === -1) { - this._keys.push(name); - } - } - } - } - /** - * Specifies if two material defines are equal - * @param other - A material define instance to compare to - * @returns - Boolean indicating if the material defines are equal (true) or not (false) - */ - isEqual(other) { - if (this._keys.length !== other._keys.length) { - return false; - } - for (let index = 0; index < this._keys.length; index++) { - const prop = this._keys[index]; - if (this[prop] !== other[prop]) { - return false; - } - } - return true; - } - /** - * Clones this instance's defines to another instance - * @param other - material defines to clone values to - */ - cloneTo(other) { - if (this._keys.length !== other._keys.length) { - other._keys = this._keys.slice(0); - } - for (let index = 0; index < this._keys.length; index++) { - const prop = this._keys[index]; - other[prop] = this[prop]; - } - } - /** - * Resets the material define values - */ - reset() { - this._keys.forEach((prop) => this._setDefaultValue(prop)); - } - _setDefaultValue(prop) { - var _a, _b, _c, _d, _e; - 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]; - const defValue = (_e = (_d = this._externalProperties) === null || _d === void 0 ? void 0 : _d[prop]) === null || _e === void 0 ? void 0 : _e.default; - switch (type) { - case "number": - this[prop] = defValue !== null && defValue !== void 0 ? defValue : 0; - break; - case "string": - this[prop] = defValue !== null && defValue !== void 0 ? defValue : ""; - break; - default: - this[prop] = defValue !== null && defValue !== void 0 ? defValue : false; - break; - } - } - /** - * Converts the material define values to a string - * @returns - String of material define information - */ - toString() { - let result = ""; - for (let index = 0; index < this._keys.length; index++) { - const prop = this._keys[index]; - const value = this[prop]; - const type = typeof value; - switch (type) { - case "number": - case "string": - result += "#define " + prop + " " + value + "\n"; - break; - default: - if (value) { - result += "#define " + prop + "\n"; - } - break; - } - } - return result; - } -} -//# sourceMappingURL=materialDefines.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/colorCurves.js - - - -/** - * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * 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; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ -class ColorCurves { - constructor() { - this._dirty = true; - this._tempColor = new math_color_Color4(0, 0, 0, 0); - this._globalCurve = new math_color_Color4(0, 0, 0, 0); - this._highlightsCurve = new math_color_Color4(0, 0, 0, 0); - this._midtonesCurve = new math_color_Color4(0, 0, 0, 0); - this._shadowsCurve = new math_color_Color4(0, 0, 0, 0); - this._positiveCurve = new math_color_Color4(0, 0, 0, 0); - this._negativeCurve = new math_color_Color4(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; - } - /** - * Gets the global Hue value. - * 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). - */ - get globalHue() { - return this._globalHue; - } - /** - * Sets the global Hue value. - * 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). - */ - set globalHue(value) { - this._globalHue = value; - this._dirty = true; - } - /** - * Gets the global Density value. - * 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. - * Values less than zero provide a filter of opposite hue. - */ - get globalDensity() { - return this._globalDensity; - } - /** - * Sets the global Density value. - * 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. - * Values less than zero provide a filter of opposite hue. - */ - set globalDensity(value) { - this._globalDensity = value; - this._dirty = true; - } - /** - * Gets the global Saturation value. - * 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. - */ - get globalSaturation() { - return this._globalSaturation; - } - /** - * Sets the global Saturation value. - * 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. - */ - set globalSaturation(value) { - this._globalSaturation = value; - this._dirty = true; - } - /** - * Gets the global Exposure value. - * 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. - */ - get globalExposure() { - return this._globalExposure; - } - /** - * Sets the global Exposure value. - * 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. - */ - set globalExposure(value) { - this._globalExposure = value; - this._dirty = true; - } - /** - * Gets the highlights Hue value. - * 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). - */ - get highlightsHue() { - return this._highlightsHue; - } - /** - * Sets the highlights Hue value. - * 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). - */ - set highlightsHue(value) { - this._highlightsHue = value; - this._dirty = true; - } - /** - * Gets the highlights Density value. - * 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. - * Values less than zero provide a filter of opposite hue. - */ - get highlightsDensity() { - return this._highlightsDensity; - } - /** - * Sets the highlights Density value. - * 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. - * Values less than zero provide a filter of opposite hue. - */ - set highlightsDensity(value) { - this._highlightsDensity = value; - this._dirty = true; - } - /** - * Gets the highlights Saturation value. - * 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. - */ - get highlightsSaturation() { - return this._highlightsSaturation; - } - /** - * Sets the highlights Saturation value. - * 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. - */ - set highlightsSaturation(value) { - this._highlightsSaturation = value; - this._dirty = true; - } - /** - * Gets the highlights Exposure value. - * 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. - */ - get highlightsExposure() { - return this._highlightsExposure; - } - /** - * Sets the highlights Exposure value. - * 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. - */ - set highlightsExposure(value) { - this._highlightsExposure = value; - this._dirty = true; - } - /** - * Gets the midtones Hue value. - * 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). - */ - get midtonesHue() { - return this._midtonesHue; - } - /** - * Sets the midtones Hue value. - * 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). - */ - set midtonesHue(value) { - this._midtonesHue = value; - this._dirty = true; - } - /** - * Gets the midtones Density value. - * 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. - * Values less than zero provide a filter of opposite hue. - */ - get midtonesDensity() { - return this._midtonesDensity; - } - /** - * Sets the midtones Density value. - * 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. - * Values less than zero provide a filter of opposite hue. - */ - set midtonesDensity(value) { - this._midtonesDensity = value; - this._dirty = true; - } - /** - * Gets the midtones Saturation value. - * 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. - */ - get midtonesSaturation() { - return this._midtonesSaturation; - } - /** - * Sets the midtones Saturation value. - * 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. - */ - set midtonesSaturation(value) { - this._midtonesSaturation = value; - this._dirty = true; - } - /** - * Gets the midtones Exposure value. - * 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. - */ - get midtonesExposure() { - return this._midtonesExposure; - } - /** - * Sets the midtones Exposure value. - * 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. - */ - set midtonesExposure(value) { - this._midtonesExposure = value; - this._dirty = true; - } - /** - * Gets the shadows Hue value. - * 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). - */ - get shadowsHue() { - return this._shadowsHue; - } - /** - * Sets the shadows Hue value. - * 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). - */ - set shadowsHue(value) { - this._shadowsHue = value; - this._dirty = true; - } - /** - * Gets the shadows Density value. - * 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. - * Values less than zero provide a filter of opposite hue. - */ - get shadowsDensity() { - return this._shadowsDensity; - } - /** - * Sets the shadows Density value. - * 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. - * Values less than zero provide a filter of opposite hue. - */ - set shadowsDensity(value) { - this._shadowsDensity = value; - this._dirty = true; - } - /** - * Gets the shadows Saturation value. - * 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. - */ - get shadowsSaturation() { - return this._shadowsSaturation; - } - /** - * Sets the shadows Saturation value. - * 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. - */ - set shadowsSaturation(value) { - this._shadowsSaturation = value; - this._dirty = true; - } - /** - * Gets the shadows Exposure value. - * 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. - */ - get shadowsExposure() { - return this._shadowsExposure; - } - /** - * Sets the shadows Exposure value. - * 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. - */ - set shadowsExposure(value) { - this._shadowsExposure = value; - this._dirty = true; - } - /** - * Returns the class name - * @returns The class name - */ - getClassName() { - return "ColorCurves"; - } - /** - * Binds the color curves to the shader. - * @param colorCurves The color curve to bind - * @param effect The effect to bind to - * @param positiveUniform The positive uniform shader parameter - * @param neutralUniform The neutral uniform shader parameter - * @param negativeUniform The negative uniform shader parameter - */ - static Bind(colorCurves, effect, positiveUniform = "vCameraColorCurvePositive", neutralUniform = "vCameraColorCurveNeutral", negativeUniform = "vCameraColorCurveNegative") { - if (colorCurves._dirty) { - colorCurves._dirty = false; - // Fill in global info. - colorCurves._getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve); - // Compute highlights info. - colorCurves._getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor); - colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve); - // Compute midtones info. - colorCurves._getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor); - colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve); - // Compute shadows info. - colorCurves._getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor); - colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve); - // Compute deltas (neutral is midtones). - colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve); - colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve); - } - if (effect) { - effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a); - effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a); - effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a); - } - } - /** - * Prepare the list of uniforms associated with the ColorCurves effects. - * @param uniformsList The list of uniforms used in the effect - */ - static PrepareUniforms(uniformsList) { - uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative"); - } - /** - * Returns color grading data based on a hue, density, saturation and exposure value. - * @param hue - * @param density - * @param saturation The saturation. - * @param exposure The exposure. - * @param result The result data container. - */ - _getColorGradingDataToRef(hue, density, saturation, exposure, result) { - if (hue == null) { - return; - } - hue = ColorCurves._Clamp(hue, 0, 360); - density = ColorCurves._Clamp(density, -100, 100); - saturation = ColorCurves._Clamp(saturation, -100, 100); - exposure = ColorCurves._Clamp(exposure, -100, 100); - // Remap the slider/config filter density with non-linear mapping and also scale by half - // so that the maximum filter density is only 50% control. This provides fine control - // for small values and reasonable range. - density = ColorCurves._ApplyColorGradingSliderNonlinear(density); - density *= 0.5; - exposure = ColorCurves._ApplyColorGradingSliderNonlinear(exposure); - if (density < 0) { - density *= -1; - hue = (hue + 180) % 360; - } - ColorCurves._FromHSBToRef(hue, density, 50 + 0.25 * exposure, result); - result.scaleToRef(2, result); - result.a = 1 + 0.01 * saturation; - } - /** - * Takes an input slider value and returns an adjusted value that provides extra control near the centre. - * @param value The input slider value in range [-100,100]. - * @returns Adjusted value. - */ - static _ApplyColorGradingSliderNonlinear(value) { - value /= 100; - let x = Math.abs(value); - x = Math.pow(x, 2); - if (value < 0) { - x *= -1; - } - x *= 100; - return x; - } - /** - * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV). - * @param hue The hue (H) input. - * @param saturation The saturation (S) input. - * @param brightness The brightness (B) input. - * @param result - * @result An RGBA color represented as Vector4. - */ - static _FromHSBToRef(hue, saturation, brightness, result) { - let h = ColorCurves._Clamp(hue, 0, 360); - const s = ColorCurves._Clamp(saturation / 100, 0, 1); - const v = ColorCurves._Clamp(brightness / 100, 0, 1); - if (s === 0) { - result.r = v; - result.g = v; - result.b = v; - } - else { - // sector 0 to 5 - h /= 60; - const i = Math.floor(h); - // fractional part of h - const f = h - i; - const p = v * (1 - s); - const q = v * (1 - s * f); - const t = v * (1 - s * (1 - f)); - switch (i) { - case 0: - result.r = v; - result.g = t; - result.b = p; - break; - case 1: - result.r = q; - result.g = v; - result.b = p; - break; - case 2: - result.r = p; - result.g = v; - result.b = t; - break; - case 3: - result.r = p; - result.g = q; - result.b = v; - break; - case 4: - result.r = t; - result.g = p; - result.b = v; - break; - default: - // case 5: - result.r = v; - result.g = p; - result.b = q; - break; - } - } - result.a = 1; - } - /** - * Returns a value clamped between min and max - * @param value The value to clamp - * @param min The minimum of value - * @param max The maximum of value - * @returns The clamped value. - */ - static _Clamp(value, min, max) { - return Math.min(Math.max(value, min), max); - } - /** - * Clones the current color curve instance. - * @returns The cloned curves - */ - clone() { - return decorators_SerializationHelper.Clone(() => new ColorCurves(), this); - } - /** - * Serializes the current color curve instance to a json representation. - * @returns a JSON representation - */ - serialize() { - return decorators_SerializationHelper.Serialize(this); - } - /** - * Parses the color curve from a json representation. - * @param source the JSON source to parse - * @returns The parsed curves - */ - static Parse(source) { - return decorators_SerializationHelper.Parse(() => new ColorCurves(), source, null, null); - } -} -__decorate([ - serialize() -], ColorCurves.prototype, "_globalHue", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_globalDensity", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_globalSaturation", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_globalExposure", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_highlightsHue", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_highlightsDensity", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_highlightsSaturation", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_highlightsExposure", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_midtonesHue", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_midtonesDensity", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_midtonesSaturation", void 0); -__decorate([ - serialize() -], ColorCurves.prototype, "_midtonesExposure", void 0); -// References the dependencies. -decorators_SerializationHelper._ColorCurvesParser = ColorCurves.Parse; -//# sourceMappingURL=colorCurves.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - -/** - * @internal - */ -class ImageProcessingConfigurationDefines extends MaterialDefines { - constructor() { - super(); - this.IMAGEPROCESSING = false; - this.VIGNETTE = false; - this.VIGNETTEBLENDMODEMULTIPLY = false; - this.VIGNETTEBLENDMODEOPAQUE = false; - this.TONEMAPPING = false; - this.TONEMAPPING_ACES = false; - this.CONTRAST = false; - this.COLORCURVES = false; - this.COLORGRADING = false; - this.COLORGRADING3D = false; - this.SAMPLER3DGREENDEPTH = false; - this.SAMPLER3DBGRMAP = false; - this.DITHER = false; - this.IMAGEPROCESSINGPOSTPROCESS = false; - this.EXPOSURE = false; - this.SKIPFINALCOLORCLAMP = false; - this.rebuild(); - } -} -/** - * This groups together the common properties used for image processing either in direct forward pass - * or through post processing effect depending on the use of the image processing pipeline in your scene - * or not. - */ -class ImageProcessingConfiguration { - constructor() { - /** - * Color curves setup used in the effect if colorCurvesEnabled is set to true - */ - this.colorCurves = new ColorCurves(); - this._colorCurvesEnabled = false; - this._colorGradingEnabled = false; - this._colorGradingWithGreenDepth = true; - this._colorGradingBGR = true; - /** @internal */ - this._exposure = 1.0; - this._toneMappingEnabled = false; - this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD; - this._contrast = 1.0; - /** - * Vignette stretch size. - */ - this.vignetteStretch = 0; - /** - * Vignette center X Offset. - */ - this.vignetteCenterX = 0; - /** - * Vignette center Y Offset. - */ - this.vignetteCenterY = 0; - /** - * Vignette weight or intensity of the vignette effect. - */ - this.vignetteWeight = 1.5; - /** - * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) - * if vignetteEnabled is set to true. - */ - this.vignetteColor = new math_color_Color4(0, 0, 0, 0); - /** - * Camera field of view used by the Vignette effect. - */ - this.vignetteCameraFov = 0.5; - this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY; - this._vignetteEnabled = false; - this._ditheringEnabled = false; - this._ditheringIntensity = 1.0 / 255.0; - /** @internal */ - this._skipFinalColorClamp = false; - /** @internal */ - this._applyByPostProcess = false; - this._isEnabled = true; - /** - * An event triggered when the configuration changes and requires Shader to Update some parameters. - */ - this.onUpdateParameters = new observable_Observable(); - } - /** - * Gets whether the color curves effect is enabled. - */ - get colorCurvesEnabled() { - return this._colorCurvesEnabled; - } - /** - * Sets whether the color curves effect is enabled. - */ - set colorCurvesEnabled(value) { - if (this._colorCurvesEnabled === value) { - return; - } - this._colorCurvesEnabled = value; - this._updateParameters(); - } - /** - * Color grading LUT texture used in the effect if colorGradingEnabled is set to true - */ - get colorGradingTexture() { - return this._colorGradingTexture; - } - /** - * Color grading LUT texture used in the effect if colorGradingEnabled is set to true - */ - set colorGradingTexture(value) { - if (this._colorGradingTexture === value) { - return; - } - this._colorGradingTexture = value; - this._updateParameters(); - } - /** - * Gets whether the color grading effect is enabled. - */ - get colorGradingEnabled() { - return this._colorGradingEnabled; - } - /** - * Sets whether the color grading effect is enabled. - */ - set colorGradingEnabled(value) { - if (this._colorGradingEnabled === value) { - return; - } - this._colorGradingEnabled = value; - this._updateParameters(); - } - /** - * Gets whether the color grading effect is using a green depth for the 3d Texture. - */ - get colorGradingWithGreenDepth() { - return this._colorGradingWithGreenDepth; - } - /** - * Sets whether the color grading effect is using a green depth for the 3d Texture. - */ - set colorGradingWithGreenDepth(value) { - if (this._colorGradingWithGreenDepth === value) { - return; - } - this._colorGradingWithGreenDepth = value; - this._updateParameters(); - } - /** - * Gets whether the color grading texture contains BGR values. - */ - get colorGradingBGR() { - return this._colorGradingBGR; - } - /** - * Sets whether the color grading texture contains BGR values. - */ - set colorGradingBGR(value) { - if (this._colorGradingBGR === value) { - return; - } - this._colorGradingBGR = value; - this._updateParameters(); - } - /** - * Gets the Exposure used in the effect. - */ - get exposure() { - return this._exposure; - } - /** - * Sets the Exposure used in the effect. - */ - set exposure(value) { - if (this._exposure === value) { - return; - } - this._exposure = value; - this._updateParameters(); - } - /** - * Gets whether the tone mapping effect is enabled. - */ - get toneMappingEnabled() { - return this._toneMappingEnabled; - } - /** - * Sets whether the tone mapping effect is enabled. - */ - set toneMappingEnabled(value) { - if (this._toneMappingEnabled === value) { - return; - } - this._toneMappingEnabled = value; - this._updateParameters(); - } - /** - * Gets the type of tone mapping effect. - */ - get toneMappingType() { - return this._toneMappingType; - } - /** - * Sets the type of tone mapping effect used in BabylonJS. - */ - set toneMappingType(value) { - if (this._toneMappingType === value) { - return; - } - this._toneMappingType = value; - this._updateParameters(); - } - /** - * Gets the contrast used in the effect. - */ - get contrast() { - return this._contrast; - } - /** - * Sets the contrast used in the effect. - */ - set contrast(value) { - if (this._contrast === value) { - return; - } - this._contrast = value; - this._updateParameters(); - } - /** - * Back Compat: Vignette center Y Offset. - * @deprecated use vignetteCenterY instead - */ - get vignetteCentreY() { - return this.vignetteCenterY; - } - set vignetteCentreY(value) { - this.vignetteCenterY = value; - } - /** - * Back Compat: Vignette center X Offset. - * @deprecated use vignetteCenterX instead - */ - get vignetteCentreX() { - return this.vignetteCenterX; - } - set vignetteCentreX(value) { - this.vignetteCenterX = value; - } - /** - * Gets the vignette blend mode allowing different kind of effect. - */ - get vignetteBlendMode() { - return this._vignetteBlendMode; - } - /** - * Sets the vignette blend mode allowing different kind of effect. - */ - set vignetteBlendMode(value) { - if (this._vignetteBlendMode === value) { - return; - } - this._vignetteBlendMode = value; - this._updateParameters(); - } - /** - * Gets whether the vignette effect is enabled. - */ - get vignetteEnabled() { - return this._vignetteEnabled; - } - /** - * Sets whether the vignette effect is enabled. - */ - set vignetteEnabled(value) { - if (this._vignetteEnabled === value) { - return; - } - this._vignetteEnabled = value; - this._updateParameters(); - } - /** - * Gets whether the dithering effect is enabled. - * The dithering effect can be used to reduce banding. - */ - get ditheringEnabled() { - return this._ditheringEnabled; - } - /** - * Sets whether the dithering effect is enabled. - * The dithering effect can be used to reduce banding. - */ - set ditheringEnabled(value) { - if (this._ditheringEnabled === value) { - return; - } - this._ditheringEnabled = value; - this._updateParameters(); - } - /** - * Gets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0. - */ - get ditheringIntensity() { - return this._ditheringIntensity; - } - /** - * Sets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0. - */ - set ditheringIntensity(value) { - if (this._ditheringIntensity === value) { - return; - } - this._ditheringIntensity = value; - this._updateParameters(); - } - /** - * 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 - * Applies to PBR materials. - */ - get skipFinalColorClamp() { - return this._skipFinalColorClamp; - } - /** - * 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 - * Applies to PBR materials. - */ - set skipFinalColorClamp(value) { - if (this._skipFinalColorClamp === value) { - return; - } - this._skipFinalColorClamp = value; - this._updateParameters(); - } - /** - * Gets whether the image processing is applied through a post process or not. - */ - get applyByPostProcess() { - return this._applyByPostProcess; - } - /** - * Sets whether the image processing is applied through a post process or not. - */ - set applyByPostProcess(value) { - if (this._applyByPostProcess === value) { - return; - } - this._applyByPostProcess = value; - this._updateParameters(); - } - /** - * Gets whether the image processing is enabled or not. - */ - get isEnabled() { - return this._isEnabled; - } - /** - * Sets whether the image processing is enabled or not. - */ - set isEnabled(value) { - if (this._isEnabled === value) { - return; - } - this._isEnabled = value; - this._updateParameters(); - } - /** - * Method called each time the image processing information changes requires to recompile the effect. - */ - _updateParameters() { - this.onUpdateParameters.notifyObservers(this); - } - /** - * Gets the current class name. - * @returns "ImageProcessingConfiguration" - */ - getClassName() { - return "ImageProcessingConfiguration"; - } - /** - * Prepare the list of uniforms associated with the Image Processing effects. - * @param uniforms The list of uniforms used in the effect - * @param defines the list of defines currently in use - */ - static PrepareUniforms(uniforms, defines) { - if (defines.EXPOSURE) { - uniforms.push("exposureLinear"); - } - if (defines.CONTRAST) { - uniforms.push("contrast"); - } - if (defines.COLORGRADING) { - uniforms.push("colorTransformSettings"); - } - if (defines.VIGNETTE || defines.DITHER) { - uniforms.push("vInverseScreenSize"); - } - if (defines.VIGNETTE) { - uniforms.push("vignetteSettings1"); - uniforms.push("vignetteSettings2"); - } - if (defines.COLORCURVES) { - ColorCurves.PrepareUniforms(uniforms); - } - if (defines.DITHER) { - uniforms.push("ditherIntensity"); - } - } - /** - * Prepare the list of samplers associated with the Image Processing effects. - * @param samplersList The list of uniforms used in the effect - * @param defines the list of defines currently in use - */ - static PrepareSamplers(samplersList, defines) { - if (defines.COLORGRADING) { - samplersList.push("txColorTransform"); - } - } - /** - * Prepare the list of defines associated to the shader. - * @param defines the list of defines to complete - * @param forPostProcess Define if we are currently in post process mode or not - */ - prepareDefines(defines, forPostProcess = false) { - if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) { - defines.VIGNETTE = false; - defines.TONEMAPPING = false; - defines.TONEMAPPING_ACES = false; - defines.CONTRAST = false; - defines.EXPOSURE = false; - defines.COLORCURVES = false; - defines.COLORGRADING = false; - defines.COLORGRADING3D = false; - defines.DITHER = false; - defines.IMAGEPROCESSING = false; - defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp; - defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled; - return; - } - defines.VIGNETTE = this.vignetteEnabled; - defines.VIGNETTEBLENDMODEMULTIPLY = this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY; - defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY; - defines.TONEMAPPING = this.toneMappingEnabled; - switch (this._toneMappingType) { - case ImageProcessingConfiguration.TONEMAPPING_ACES: - defines.TONEMAPPING_ACES = true; - break; - default: - defines.TONEMAPPING_ACES = false; - break; - } - defines.CONTRAST = this.contrast !== 1.0; - defines.EXPOSURE = this.exposure !== 1.0; - defines.COLORCURVES = this.colorCurvesEnabled && !!this.colorCurves; - defines.COLORGRADING = this.colorGradingEnabled && !!this.colorGradingTexture; - if (defines.COLORGRADING) { - defines.COLORGRADING3D = this.colorGradingTexture.is3D; - } - else { - defines.COLORGRADING3D = false; - } - defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth; - defines.SAMPLER3DBGRMAP = this.colorGradingBGR; - defines.DITHER = this._ditheringEnabled; - defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess; - defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp; - defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.DITHER; - } - /** - * Returns true if all the image processing information are ready. - * @returns True if ready, otherwise, false - */ - isReady() { - // Color Grading texture can not be none blocking. - return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady(); - } - /** - * Binds the image processing to the shader. - * @param effect The effect to bind to - * @param overrideAspectRatio Override the aspect ratio of the effect - */ - bind(effect, overrideAspectRatio) { - // Color Curves - if (this._colorCurvesEnabled && this.colorCurves) { - ColorCurves.Bind(this.colorCurves, effect); - } - // Vignette and dither handled together due to common uniform. - if (this._vignetteEnabled || this._ditheringEnabled) { - const inverseWidth = 1 / effect.getEngine().getRenderWidth(); - const inverseHeight = 1 / effect.getEngine().getRenderHeight(); - effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight); - if (this._ditheringEnabled) { - effect.setFloat("ditherIntensity", 0.5 * this._ditheringIntensity); - } - if (this._vignetteEnabled) { - const aspectRatio = overrideAspectRatio != null ? overrideAspectRatio : inverseHeight / inverseWidth; - let vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5); - let vignetteScaleX = vignetteScaleY * aspectRatio; - const vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY); - vignetteScaleX = tools_Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch); - vignetteScaleY = tools_Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch); - effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCenterX, -vignetteScaleY * this.vignetteCenterY); - const vignettePower = -2.0 * this.vignetteWeight; - effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower); - } - } - // Exposure - effect.setFloat("exposureLinear", this.exposure); - // Contrast - effect.setFloat("contrast", this.contrast); - // Color transform settings - if (this.colorGradingTexture) { - effect.setTexture("txColorTransform", this.colorGradingTexture); - const textureSize = this.colorGradingTexture.getSize().height; - effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale - 0.5 / textureSize, // textureOffset - textureSize, // textureSize - this.colorGradingTexture.level // weight - ); - } - } - /** - * Clones the current image processing instance. - * @returns The cloned image processing - */ - clone() { - return decorators_SerializationHelper.Clone(() => new ImageProcessingConfiguration(), this); - } - /** - * Serializes the current image processing instance to a json representation. - * @returns a JSON representation - */ - serialize() { - return decorators_SerializationHelper.Serialize(this); - } - /** - * Parses the image processing from a json representation. - * @param source the JSON source to parse - * @returns The parsed image processing - */ - static Parse(source) { - const parsed = decorators_SerializationHelper.Parse(() => new ImageProcessingConfiguration(), source, null, null); - // Backward compatibility - if (source.vignetteCentreX !== undefined) { - parsed.vignetteCenterX = source.vignetteCentreX; - } - if (source.vignetteCentreY !== undefined) { - parsed.vignetteCenterY = source.vignetteCentreY; - } - return parsed; - } - /** - * Used to apply the vignette as a mix with the pixel color. - */ - static get VIGNETTEMODE_MULTIPLY() { - return this._VIGNETTEMODE_MULTIPLY; - } - /** - * Used to apply the vignette as a replacement of the pixel color. - */ - static get VIGNETTEMODE_OPAQUE() { - return this._VIGNETTEMODE_OPAQUE; - } -} -/** - * Default tone mapping applied in BabylonJS. - */ -ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0; -/** - * ACES Tone mapping (used by default in unreal and unity). This can help getting closer - * to other engines rendering to increase portability. - */ -ImageProcessingConfiguration.TONEMAPPING_ACES = 1; -// Static constants associated to the image processing. -ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0; -ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1; -__decorate([ - serializeAsColorCurves() -], ImageProcessingConfiguration.prototype, "colorCurves", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0); -__decorate([ - serializeAsTexture("colorGradingTexture") -], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_exposure", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_contrast", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "vignetteCenterX", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "vignetteCenterY", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0); -__decorate([ - serializeAsColor4() -], ImageProcessingConfiguration.prototype, "vignetteColor", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_ditheringEnabled", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_ditheringIntensity", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_skipFinalColorClamp", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0); -__decorate([ - serialize() -], ImageProcessingConfiguration.prototype, "_isEnabled", void 0); -// References the dependencies. -decorators_SerializationHelper._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse; -//# sourceMappingURL=imageProcessingConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.uniformBuffer.js - - -ThinEngine.prototype.createUniformBuffer = function (elements) { - const ubo = this._gl.createBuffer(); - if (!ubo) { - throw new Error("Unable to create uniform buffer"); - } - const result = new WebGLDataBuffer(ubo); - this.bindUniformBuffer(result); - if (elements instanceof Float32Array) { - this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW); - } - else { - this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW); - } - this.bindUniformBuffer(null); - result.references = 1; - return result; -}; -ThinEngine.prototype.createDynamicUniformBuffer = function (elements) { - const ubo = this._gl.createBuffer(); - if (!ubo) { - throw new Error("Unable to create dynamic uniform buffer"); - } - const result = new WebGLDataBuffer(ubo); - this.bindUniformBuffer(result); - if (elements instanceof Float32Array) { - this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW); - } - else { - this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW); - } - this.bindUniformBuffer(null); - result.references = 1; - return result; -}; -ThinEngine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) { - this.bindUniformBuffer(uniformBuffer); - if (offset === undefined) { - offset = 0; - } - if (count === undefined) { - if (elements instanceof Float32Array) { - this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements); - } - else { - this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements)); - } - } - else { - if (elements instanceof Float32Array) { - this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count)); - } - else { - this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count)); - } - } - this.bindUniformBuffer(null); -}; -ThinEngine.prototype.bindUniformBuffer = function (buffer) { - this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer ? buffer.underlyingResource : null); -}; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -ThinEngine.prototype.bindUniformBufferBase = function (buffer, location, name) { - this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer ? buffer.underlyingResource : null); -}; -ThinEngine.prototype.bindUniformBlock = function (pipelineContext, blockName, index) { - const program = pipelineContext.program; - const uniformLocation = this._gl.getUniformBlockIndex(program, blockName); - if (uniformLocation !== 0xffffffff) { - this._gl.uniformBlockBinding(program, uniformLocation, index); - } -}; -//# sourceMappingURL=engine.uniformBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/uniformBuffer.js - - - -/** - * Uniform buffer objects. - * - * Handles blocks of uniform on the GPU. - * - * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls. - * - * For more information, please refer to : - * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object - */ -class UniformBuffer { - /** - * Instantiates a new Uniform buffer objects. - * - * Handles blocks of uniform on the GPU. - * - * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls. - * - * For more information, please refer to : - * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object - * @param engine Define the engine the buffer is associated with - * @param data Define the data contained in the buffer - * @param dynamic Define if the buffer is updatable - * @param name to assign to the buffer (debugging purpose) - * @param forceNoUniformBuffer define that this object must not rely on UBO objects - */ - constructor(engine, data, dynamic, name, forceNoUniformBuffer = false) { - // Matrix cache - this._valueCache = {}; - this._engine = engine; - this._noUBO = !engine.supportsUniformBuffers || forceNoUniformBuffer; - this._dynamic = dynamic; - this._name = name !== null && name !== void 0 ? name : "no-name"; - this._data = data || []; - this._uniformLocations = {}; - this._uniformSizes = {}; - this._uniformArraySizes = {}; - this._uniformLocationPointer = 0; - this._needSync = false; - if (this._engine._features.trackUbosInFrame) { - this._buffers = []; - this._bufferIndex = -1; - this._createBufferOnWrite = false; - this._currentFrameId = 0; - } - if (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; - } - else { - 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; - } - } - /** - * Indicates if the buffer is using the WebGL2 UBO implementation, - * or just falling back on setUniformXXX calls. - */ - get useUbo() { - return !this._noUBO; - } - /** - * Indicates if the WebGL underlying uniform buffer is in sync - * with the javascript cache data. - */ - get isSync() { - return !this._needSync; - } - /** - * Indicates if the WebGL underlying uniform buffer is dynamic. - * Also, a dynamic UniformBuffer will disable cache verification and always - * update the underlying WebGL uniform buffer to the GPU. - * @returns if Dynamic, otherwise false - */ - isDynamic() { - return this._dynamic !== undefined; - } - /** - * The data cache on JS side. - * @returns the underlying data as a float array - */ - getData() { - return this._bufferData; - } - /** - * The underlying WebGL Uniform buffer. - * @returns the webgl buffer - */ - getBuffer() { - return this._buffer; - } - /** - * std140 layout specifies how to align data within an UBO structure. - * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159 - * for specs. - * @param size - */ - _fillAlignment(size) { - // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components - // and 4x4 matrices - // TODO : change if other types are used - let alignment; - if (size <= 2) { - alignment = size; - } - else { - alignment = 4; - } - if (this._uniformLocationPointer % alignment !== 0) { - const oldPointer = this._uniformLocationPointer; - this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment); - const diff = this._uniformLocationPointer - oldPointer; - for (let i = 0; i < diff; i++) { - this._data.push(0); - } - } - } - /** - * Adds an uniform in the buffer. - * Warning : the subsequents calls of this function must be in the same order as declared in the shader - * for the layout to be correct ! The addUniform function only handles types like float, vec2, vec3, vec4, mat4, - * meaning size=1,2,3,4 or 16. It does not handle struct types. - * @param name Name of the uniform, as used in the uniform block in the shader. - * @param size Data size, or data directly. - * @param arraySize The number of elements in the array, 0 if not an array. - */ - addUniform(name, size, arraySize = 0) { - if (this._noUBO) { - return; - } - if (this._uniformLocations[name] !== undefined) { - // Already existing uniform - return; - } - // This function must be called in the order of the shader layout ! - // size can be the size of the uniform, or data directly - let data; - // std140 FTW... - if (arraySize > 0) { - if (size instanceof Array) { - throw "addUniform should not be use with Array in UBO: " + name; - } - this._fillAlignment(4); - this._uniformArraySizes[name] = { strideSize: size, arraySize }; - if (size == 16) { - size = size * arraySize; - } - else { - const perElementPadding = 4 - size; - const totalPadding = perElementPadding * arraySize; - size = size * arraySize + totalPadding; - } - data = []; - // Fill with zeros - for (let i = 0; i < size; i++) { - data.push(0); - } - } - else { - if (size instanceof Array) { - data = size; - size = data.length; - } - else { - size = size; - data = []; - // Fill with zeros - for (let i = 0; i < size; i++) { - data.push(0); - } - } - this._fillAlignment(size); - } - this._uniformSizes[name] = size; - this._uniformLocations[name] = this._uniformLocationPointer; - this._uniformLocationPointer += size; - for (let i = 0; i < size; i++) { - this._data.push(data[i]); - } - this._needSync = true; - } - /** - * Adds a Matrix 4x4 to the uniform buffer. - * @param name Name of the uniform, as used in the uniform block in the shader. - * @param mat A 4x4 matrix. - */ - addMatrix(name, mat) { - this.addUniform(name, Array.prototype.slice.call(mat.toArray())); - } - /** - * Adds a vec2 to the uniform buffer. - * @param name Name of the uniform, as used in the uniform block in the shader. - * @param x Define the x component value of the vec2 - * @param y Define the y component value of the vec2 - */ - addFloat2(name, x, y) { - const temp = [x, y]; - this.addUniform(name, temp); - } - /** - * Adds a vec3 to the uniform buffer. - * @param name Name of the uniform, as used in the uniform block in the shader. - * @param x Define the x component value of the vec3 - * @param y Define the y component value of the vec3 - * @param z Define the z component value of the vec3 - */ - addFloat3(name, x, y, z) { - const temp = [x, y, z]; - this.addUniform(name, temp); - } - /** - * Adds a vec3 to the uniform buffer. - * @param name Name of the uniform, as used in the uniform block in the shader. - * @param color Define the vec3 from a Color - */ - addColor3(name, color) { - const temp = [color.r, color.g, color.b]; - this.addUniform(name, temp); - } - /** - * Adds a vec4 to the uniform buffer. - * @param name Name of the uniform, as used in the uniform block in the shader. - * @param color Define the rgb components from a Color - * @param alpha Define the a component of the vec4 - */ - addColor4(name, color, alpha) { - const temp = [color.r, color.g, color.b, alpha]; - this.addUniform(name, temp); - } - /** - * Adds a vec3 to the uniform buffer. - * @param name Name of the uniform, as used in the uniform block in the shader. - * @param vector Define the vec3 components from a Vector - */ - addVector3(name, vector) { - const temp = [vector.x, vector.y, vector.z]; - this.addUniform(name, temp); - } - /** - * Adds a Matrix 3x3 to the uniform buffer. - * @param name Name of the uniform, as used in the uniform block in the shader. - */ - addMatrix3x3(name) { - this.addUniform(name, 12); - } - /** - * Adds a Matrix 2x2 to the uniform buffer. - * @param name Name of the uniform, as used in the uniform block in the shader. - */ - addMatrix2x2(name) { - this.addUniform(name, 8); - } - /** - * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`. - */ - create() { - if (this._noUBO) { - return; - } - if (this._buffer) { - return; // nothing to do - } - // See spec, alignment must be filled as a vec4 - this._fillAlignment(4); - this._bufferData = new Float32Array(this._data); - this._rebuild(); - this._needSync = true; - } - /** @internal */ - _rebuild() { - if (this._noUBO || !this._bufferData) { - return; - } - if (this._dynamic) { - this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData); - } - else { - this._buffer = this._engine.createUniformBuffer(this._bufferData); - } - if (this._engine._features.trackUbosInFrame) { - this._buffers.push([this._buffer, this._engine._features.checkUbosContentBeforeUpload ? this._bufferData.slice() : undefined]); - this._bufferIndex = this._buffers.length - 1; - this._createBufferOnWrite = false; - } - } - /** @internal */ - get _numBuffers() { - return this._buffers.length; - } - /** @internal */ - get _indexBuffer() { - return this._bufferIndex; - } - /** Gets the name of this buffer */ - get name() { - return this._name; - } - /** Gets the current effect */ - get currentEffect() { - return this._currentEffect; - } - _buffersEqual(buf1, buf2) { - for (let i = 0; i < buf1.length; ++i) { - if (buf1[i] !== buf2[i]) { - return false; - } - } - return true; - } - _copyBuffer(src, dst) { - for (let i = 0; i < src.length; ++i) { - dst[i] = src[i]; - } - } - /** - * Updates the WebGL Uniform Buffer on the GPU. - * If the `dynamic` flag is set to true, no cache comparison is done. - * Otherwise, the buffer will be updated only if the cache differs. - */ - update() { - if (this._noUBO) { - return; - } - this.bindUniformBuffer(); - if (!this._buffer) { - this.create(); - return; - } - if (!this._dynamic && !this._needSync) { - this._createBufferOnWrite = this._engine._features.trackUbosInFrame; - return; - } - if (this._buffers && this._buffers.length > 1 && this._buffers[this._bufferIndex][1]) { - if (this._buffersEqual(this._bufferData, this._buffers[this._bufferIndex][1])) { - this._needSync = false; - this._createBufferOnWrite = this._engine._features.trackUbosInFrame; - return; - } - else { - this._copyBuffer(this._bufferData, this._buffers[this._bufferIndex][1]); - } - } - this._engine.updateUniformBuffer(this._buffer, this._bufferData); - if (this._engine._features._collectUbosUpdatedInFrame) { - if (!UniformBuffer._UpdatedUbosInFrame[this._name]) { - UniformBuffer._UpdatedUbosInFrame[this._name] = 0; - } - UniformBuffer._UpdatedUbosInFrame[this._name]++; - } - this._needSync = false; - this._createBufferOnWrite = this._engine._features.trackUbosInFrame; - } - _createNewBuffer() { - if (this._bufferIndex + 1 < this._buffers.length) { - this._bufferIndex++; - this._buffer = this._buffers[this._bufferIndex][0]; - this._createBufferOnWrite = false; - this._needSync = true; - } - else { - this._rebuild(); - } - } - _checkNewFrame() { - if (this._engine._features.trackUbosInFrame && this._currentFrameId !== this._engine.frameId) { - this._currentFrameId = this._engine.frameId; - this._createBufferOnWrite = false; - if (this._buffers && this._buffers.length > 0) { - this._needSync = this._bufferIndex !== 0; - this._bufferIndex = 0; - this._buffer = this._buffers[this._bufferIndex][0]; - } - else { - this._bufferIndex = -1; - } - } - } - /** - * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU. - * @param uniformName Define the name of the uniform, as used in the uniform block in the shader. - * @param data Define the flattened data - * @param size Define the size of the data. - */ - updateUniform(uniformName, data, size) { - this._checkNewFrame(); - let location = this._uniformLocations[uniformName]; - if (location === undefined) { - if (this._buffer) { - // Cannot add an uniform if the buffer is already created - logger_Logger.Error("Cannot add an uniform after UBO has been created."); - return; - } - this.addUniform(uniformName, size); - location = this._uniformLocations[uniformName]; - } - if (!this._buffer) { - this.create(); - } - if (!this._dynamic) { - // Cache for static uniform buffers - let changed = false; - for (let i = 0; i < size; i++) { - // We are checking the matrix cache before calling updateUniform so we do not need to check it here - // Hence the test for size === 16 to simply commit the matrix values - if ((size === 16 && !this._engine._features.uniformBufferHardCheckMatrix) || this._bufferData[location + i] !== tools_Tools.FloatRound(data[i])) { - changed = true; - if (this._createBufferOnWrite) { - this._createNewBuffer(); - } - this._bufferData[location + i] = data[i]; - } - } - this._needSync = this._needSync || changed; - } - else { - // No cache for dynamic - for (let i = 0; i < size; i++) { - this._bufferData[location + i] = data[i]; - } - } - } - /** - * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU. - * @param uniformName Define the name of the uniform, as used in the uniform block in the shader. - * @param data Define the flattened data - * @param size Define the size of the data. - */ - updateUniformArray(uniformName, data, size) { - this._checkNewFrame(); - const location = this._uniformLocations[uniformName]; - if (location === undefined) { - logger_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."); - return; - } - if (!this._buffer) { - this.create(); - } - const arraySizes = this._uniformArraySizes[uniformName]; - if (!this._dynamic) { - // Cache for static uniform buffers - let changed = false; - let countToFour = 0; - let baseStride = 0; - for (let i = 0; i < size; i++) { - if (this._bufferData[location + baseStride * 4 + countToFour] !== tools_Tools.FloatRound(data[i])) { - changed = true; - if (this._createBufferOnWrite) { - this._createNewBuffer(); - } - this._bufferData[location + baseStride * 4 + countToFour] = data[i]; - } - countToFour++; - if (countToFour === arraySizes.strideSize) { - for (; countToFour < 4; countToFour++) { - this._bufferData[location + baseStride * 4 + countToFour] = 0; - } - countToFour = 0; - baseStride++; - } - } - this._needSync = this._needSync || changed; - } - else { - // No cache for dynamic - for (let i = 0; i < size; i++) { - this._bufferData[location + i] = data[i]; - } - } - } - _cacheMatrix(name, matrix) { - this._checkNewFrame(); - const cache = this._valueCache[name]; - const flag = matrix.updateFlag; - if (cache !== undefined && cache === flag) { - return false; - } - this._valueCache[name] = flag; - return true; - } - // Update methods - _updateMatrix3x3ForUniform(name, matrix) { - // To match std140, matrix must be realigned - for (let i = 0; i < 3; i++) { - UniformBuffer._TempBuffer[i * 4] = matrix[i * 3]; - UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 3 + 1]; - UniformBuffer._TempBuffer[i * 4 + 2] = matrix[i * 3 + 2]; - UniformBuffer._TempBuffer[i * 4 + 3] = 0.0; - } - this.updateUniform(name, UniformBuffer._TempBuffer, 12); - } - _updateMatrix3x3ForEffect(name, matrix) { - this._currentEffect.setMatrix3x3(name, matrix); - } - _updateMatrix2x2ForEffect(name, matrix) { - this._currentEffect.setMatrix2x2(name, matrix); - } - _updateMatrix2x2ForUniform(name, matrix) { - // To match std140, matrix must be realigned - for (let i = 0; i < 2; i++) { - UniformBuffer._TempBuffer[i * 4] = matrix[i * 2]; - UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 2 + 1]; - UniformBuffer._TempBuffer[i * 4 + 2] = 0.0; - UniformBuffer._TempBuffer[i * 4 + 3] = 0.0; - } - this.updateUniform(name, UniformBuffer._TempBuffer, 8); - } - _updateFloatForEffect(name, x) { - this._currentEffect.setFloat(name, x); - } - _updateFloatForUniform(name, x) { - UniformBuffer._TempBuffer[0] = x; - this.updateUniform(name, UniformBuffer._TempBuffer, 1); - } - _updateFloat2ForEffect(name, x, y, suffix = "") { - this._currentEffect.setFloat2(name + suffix, x, y); - } - _updateFloat2ForUniform(name, x, y) { - UniformBuffer._TempBuffer[0] = x; - UniformBuffer._TempBuffer[1] = y; - this.updateUniform(name, UniformBuffer._TempBuffer, 2); - } - _updateFloat3ForEffect(name, x, y, z, suffix = "") { - this._currentEffect.setFloat3(name + suffix, x, y, z); - } - _updateFloat3ForUniform(name, x, y, z) { - UniformBuffer._TempBuffer[0] = x; - UniformBuffer._TempBuffer[1] = y; - UniformBuffer._TempBuffer[2] = z; - this.updateUniform(name, UniformBuffer._TempBuffer, 3); - } - _updateFloat4ForEffect(name, x, y, z, w, suffix = "") { - this._currentEffect.setFloat4(name + suffix, x, y, z, w); - } - _updateFloat4ForUniform(name, x, y, z, w) { - UniformBuffer._TempBuffer[0] = x; - UniformBuffer._TempBuffer[1] = y; - UniformBuffer._TempBuffer[2] = z; - UniformBuffer._TempBuffer[3] = w; - this.updateUniform(name, UniformBuffer._TempBuffer, 4); - } - _updateFloatArrayForEffect(name, array) { - this._currentEffect.setFloatArray(name, array); - } - _updateFloatArrayForUniform(name, array) { - this.updateUniformArray(name, array, array.length); - } - _updateArrayForEffect(name, array) { - this._currentEffect.setArray(name, array); - } - _updateArrayForUniform(name, array) { - this.updateUniformArray(name, array, array.length); - } - _updateIntArrayForEffect(name, array) { - this._currentEffect.setIntArray(name, array); - } - _updateIntArrayForUniform(name, array) { - UniformBuffer._TempBufferInt32View.set(array); - this.updateUniformArray(name, UniformBuffer._TempBuffer, array.length); - } - _updateUIntArrayForEffect(name, array) { - this._currentEffect.setUIntArray(name, array); - } - _updateUIntArrayForUniform(name, array) { - UniformBuffer._TempBufferUInt32View.set(array); - this.updateUniformArray(name, UniformBuffer._TempBuffer, array.length); - } - _updateMatrixForEffect(name, mat) { - this._currentEffect.setMatrix(name, mat); - } - _updateMatrixForUniform(name, mat) { - if (this._cacheMatrix(name, mat)) { - this.updateUniform(name, mat.toArray(), 16); - } - } - _updateMatricesForEffect(name, mat) { - this._currentEffect.setMatrices(name, mat); - } - _updateMatricesForUniform(name, mat) { - this.updateUniform(name, mat, mat.length); - } - _updateVector3ForEffect(name, vector) { - this._currentEffect.setVector3(name, vector); - } - _updateVector3ForUniform(name, vector) { - UniformBuffer._TempBuffer[0] = vector.x; - UniformBuffer._TempBuffer[1] = vector.y; - UniformBuffer._TempBuffer[2] = vector.z; - this.updateUniform(name, UniformBuffer._TempBuffer, 3); - } - _updateVector4ForEffect(name, vector) { - this._currentEffect.setVector4(name, vector); - } - _updateVector4ForUniform(name, vector) { - UniformBuffer._TempBuffer[0] = vector.x; - UniformBuffer._TempBuffer[1] = vector.y; - UniformBuffer._TempBuffer[2] = vector.z; - UniformBuffer._TempBuffer[3] = vector.w; - this.updateUniform(name, UniformBuffer._TempBuffer, 4); - } - _updateColor3ForEffect(name, color, suffix = "") { - this._currentEffect.setColor3(name + suffix, color); - } - _updateColor3ForUniform(name, color) { - UniformBuffer._TempBuffer[0] = color.r; - UniformBuffer._TempBuffer[1] = color.g; - UniformBuffer._TempBuffer[2] = color.b; - this.updateUniform(name, UniformBuffer._TempBuffer, 3); - } - _updateColor4ForEffect(name, color, alpha, suffix = "") { - this._currentEffect.setColor4(name + suffix, color, alpha); - } - _updateDirectColor4ForEffect(name, color, suffix = "") { - this._currentEffect.setDirectColor4(name + suffix, color); - } - _updateColor4ForUniform(name, color, alpha) { - UniformBuffer._TempBuffer[0] = color.r; - UniformBuffer._TempBuffer[1] = color.g; - UniformBuffer._TempBuffer[2] = color.b; - UniformBuffer._TempBuffer[3] = alpha; - this.updateUniform(name, UniformBuffer._TempBuffer, 4); - } - _updateDirectColor4ForUniform(name, color) { - UniformBuffer._TempBuffer[0] = color.r; - UniformBuffer._TempBuffer[1] = color.g; - UniformBuffer._TempBuffer[2] = color.b; - UniformBuffer._TempBuffer[3] = color.a; - this.updateUniform(name, UniformBuffer._TempBuffer, 4); - } - _updateIntForEffect(name, x, suffix = "") { - this._currentEffect.setInt(name + suffix, x); - } - _updateIntForUniform(name, x) { - UniformBuffer._TempBufferInt32View[0] = x; - this.updateUniform(name, UniformBuffer._TempBuffer, 1); - } - _updateInt2ForEffect(name, x, y, suffix = "") { - this._currentEffect.setInt2(name + suffix, x, y); - } - _updateInt2ForUniform(name, x, y) { - UniformBuffer._TempBufferInt32View[0] = x; - UniformBuffer._TempBufferInt32View[1] = y; - this.updateUniform(name, UniformBuffer._TempBuffer, 2); - } - _updateInt3ForEffect(name, x, y, z, suffix = "") { - this._currentEffect.setInt3(name + suffix, x, y, z); - } - _updateInt3ForUniform(name, x, y, z) { - UniformBuffer._TempBufferInt32View[0] = x; - UniformBuffer._TempBufferInt32View[1] = y; - UniformBuffer._TempBufferInt32View[2] = z; - this.updateUniform(name, UniformBuffer._TempBuffer, 3); - } - _updateInt4ForEffect(name, x, y, z, w, suffix = "") { - this._currentEffect.setInt4(name + suffix, x, y, z, w); - } - _updateInt4ForUniform(name, x, y, z, w) { - UniformBuffer._TempBufferInt32View[0] = x; - UniformBuffer._TempBufferInt32View[1] = y; - UniformBuffer._TempBufferInt32View[2] = z; - UniformBuffer._TempBufferInt32View[3] = w; - this.updateUniform(name, UniformBuffer._TempBuffer, 4); - } - _updateUIntForEffect(name, x, suffix = "") { - this._currentEffect.setUInt(name + suffix, x); - } - _updateUIntForUniform(name, x) { - UniformBuffer._TempBufferUInt32View[0] = x; - this.updateUniform(name, UniformBuffer._TempBuffer, 1); - } - _updateUInt2ForEffect(name, x, y, suffix = "") { - this._currentEffect.setUInt2(name + suffix, x, y); - } - _updateUInt2ForUniform(name, x, y) { - UniformBuffer._TempBufferUInt32View[0] = x; - UniformBuffer._TempBufferUInt32View[1] = y; - this.updateUniform(name, UniformBuffer._TempBuffer, 2); - } - _updateUInt3ForEffect(name, x, y, z, suffix = "") { - this._currentEffect.setUInt3(name + suffix, x, y, z); - } - _updateUInt3ForUniform(name, x, y, z) { - UniformBuffer._TempBufferUInt32View[0] = x; - UniformBuffer._TempBufferUInt32View[1] = y; - UniformBuffer._TempBufferUInt32View[2] = z; - this.updateUniform(name, UniformBuffer._TempBuffer, 3); - } - _updateUInt4ForEffect(name, x, y, z, w, suffix = "") { - this._currentEffect.setUInt4(name + suffix, x, y, z, w); - } - _updateUInt4ForUniform(name, x, y, z, w) { - UniformBuffer._TempBufferUInt32View[0] = x; - UniformBuffer._TempBufferUInt32View[1] = y; - UniformBuffer._TempBufferUInt32View[2] = z; - UniformBuffer._TempBufferUInt32View[3] = w; - this.updateUniform(name, UniformBuffer._TempBuffer, 4); - } - /** - * Sets a sampler uniform on the effect. - * @param name Define the name of the sampler. - * @param texture Define the texture to set in the sampler - */ - setTexture(name, texture) { - this._currentEffect.setTexture(name, texture); - } - /** - * Directly updates the value of the uniform in the cache AND on the GPU. - * @param uniformName Define the name of the uniform, as used in the uniform block in the shader. - * @param data Define the flattened data - */ - updateUniformDirectly(uniformName, data) { - this.updateUniform(uniformName, data, data.length); - this.update(); - } - /** - * Associates an effect to this uniform buffer - * @param effect Define the effect to associate the buffer to - * @param name Name of the uniform block in the shader. - */ - bindToEffect(effect, name) { - this._currentEffect = effect; - this._currentEffectName = name; - } - /** - * Binds the current (GPU) buffer to the effect - */ - bindUniformBuffer() { - if (!this._noUBO && this._buffer && this._currentEffect) { - this._currentEffect.bindUniformBuffer(this._buffer, this._currentEffectName); - } - } - /** - * Dissociates the current effect from this uniform buffer - */ - unbindEffect() { - this._currentEffect = undefined; - this._currentEffectName = undefined; - } - /** - * 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) - * 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 - * @param dataBuffer buffer to look for - * @returns true if the buffer has been found and the class internal state points to it, else false - */ - setDataBuffer(dataBuffer) { - if (!this._buffers) { - return this._buffer === dataBuffer; - } - for (let b = 0; b < this._buffers.length; ++b) { - const buffer = this._buffers[b]; - if (buffer[0] === dataBuffer) { - this._bufferIndex = b; - this._buffer = dataBuffer; - this._createBufferOnWrite = false; - this._currentEffect = undefined; - return true; - } - } - return false; - } - /** - * Disposes the uniform buffer. - */ - dispose() { - if (this._noUBO) { - return; - } - const uniformBuffers = this._engine._uniformBuffers; - const index = uniformBuffers.indexOf(this); - if (index !== -1) { - uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1]; - uniformBuffers.pop(); - } - if (this._engine._features.trackUbosInFrame && this._buffers) { - for (let i = 0; i < this._buffers.length; ++i) { - const buffer = this._buffers[i][0]; - this._engine._releaseBuffer(buffer); - } - } - else if (this._buffer && this._engine._releaseBuffer(this._buffer)) { - this._buffer = null; - } - } -} -/** @internal */ -UniformBuffer._UpdatedUbosInFrame = {}; -// Pool for avoiding memory leaks -UniformBuffer._MAX_UNIFORM_SIZE = 256; -UniformBuffer._TempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE); -UniformBuffer._TempBufferInt32View = new Int32Array(UniformBuffer._TempBuffer.buffer); -UniformBuffer._TempBufferUInt32View = new Uint32Array(UniformBuffer._TempBuffer.buffer); -//# sourceMappingURL=uniformBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Buffers/buffer.js - -/** - * Class used to store data that will be store in GPU memory - */ -class Buffer { - /** - * Constructor - * @param engine the engine - * @param data the data to use for this buffer - * @param updatable whether the data is updatable - * @param stride the stride (optional) - * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) - * @param instanced whether the buffer is instanced (optional) - * @param useBytes set to true if the stride in in bytes (optional) - * @param divisor sets an optional divisor for instances (1 by default) - */ - constructor(engine, data, updatable, stride = 0, postponeInternalCreation = false, instanced = false, useBytes = false, divisor) { - this._isAlreadyOwned = false; - if (engine.getScene) { - // old versions of VertexBuffer accepted 'mesh' instead of 'engine' - this._engine = engine.getScene().getEngine(); - } - else { - this._engine = engine; - } - this._updatable = updatable; - this._instanced = instanced; - this._divisor = divisor || 1; - if (data instanceof dataBuffer_DataBuffer) { - this._data = null; - this._buffer = data; - } - else { - this._data = data; - this._buffer = null; - } - this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT; - if (!postponeInternalCreation) { - // by default - this.create(); - } - } - /** - * Create a new VertexBuffer based on the current buffer - * @param kind defines the vertex buffer kind (position, normal, etc.) - * @param offset defines offset in the buffer (0 by default) - * @param size defines the size in floats of attributes (position is 3 for instance) - * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved) - * @param instanced defines if the vertex buffer contains indexed data - * @param useBytes defines if the offset and stride are in bytes * - * @param divisor sets an optional divisor for instances (1 by default) - * @returns the new vertex buffer - */ - createVertexBuffer(kind, offset, size, stride, instanced, useBytes = false, divisor) { - const byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT; - const byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride; - // a lot of these parameters are ignored as they are overridden by the buffer - return new buffer_VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true, this._divisor || divisor); - } - // Properties - /** - * Gets a boolean indicating if the Buffer is updatable? - * @returns true if the buffer is updatable - */ - isUpdatable() { - return this._updatable; - } - /** - * Gets current buffer's data - * @returns a DataArray or null - */ - getData() { - return this._data; - } - /** - * Gets underlying native buffer - * @returns underlying native buffer - */ - getBuffer() { - return this._buffer; - } - /** - * Gets the stride in float32 units (i.e. byte stride / 4). - * May not be an integer if the byte stride is not divisible by 4. - * @returns the stride in float32 units - * @deprecated Please use byteStride instead. - */ - getStrideSize() { - return this.byteStride / Float32Array.BYTES_PER_ELEMENT; - } - // Methods - /** - * Store data into the buffer. Creates the buffer if not used already. - * If the buffer was already used, it will be updated only if it is updatable, otherwise it will do nothing. - * @param data defines the data to store - */ - create(data = null) { - if (!data && this._buffer) { - return; // nothing to do - } - data = data || this._data; - if (!data) { - return; - } - if (!this._buffer) { - // create buffer - if (this._updatable) { - this._buffer = this._engine.createDynamicVertexBuffer(data); - this._data = data; - } - else { - this._buffer = this._engine.createVertexBuffer(data); - } - } - else if (this._updatable) { - // update buffer - this._engine.updateDynamicVertexBuffer(this._buffer, data); - this._data = data; - } - } - /** @internal */ - _rebuild() { - this._buffer = null; - this.create(this._data); - } - /** - * Update current buffer data - * @param data defines the data to store - */ - update(data) { - this.create(data); - } - /** - * Updates the data directly. - * @param data the new data - * @param offset the new offset - * @param vertexCount the vertex count (optional) - * @param useBytes set to true if the offset is in bytes - */ - updateDirectly(data, offset, vertexCount, useBytes = false) { - if (!this._buffer) { - return; - } - if (this._updatable) { - // update buffer - this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, vertexCount ? vertexCount * this.byteStride : undefined); - if (offset === 0 && vertexCount === undefined) { - // Keep the data if we easily can - this._data = data; - } - else { - this._data = null; - } - } - } - /** @internal */ - _increaseReferences() { - if (!this._buffer) { - return; - } - if (!this._isAlreadyOwned) { - this._isAlreadyOwned = true; - return; - } - this._buffer.references++; - } - /** - * Release all resources - */ - dispose() { - if (!this._buffer) { - return; - } - if (this._engine._releaseBuffer(this._buffer)) { - this._buffer = null; - this._data = null; - } - } -} -/** - * Specialized buffer used to store vertex data - */ -class buffer_VertexBuffer { - /** - * Gets or sets the instance divisor when in instanced mode - */ - get instanceDivisor() { - return this._instanceDivisor; - } - set instanceDivisor(value) { - const isInstanced = value != 0; - this._instanceDivisor = value; - if (isInstanced !== this._instanced) { - this._instanced = isInstanced; - this._computeHashCode(); - } - } - /** - * Constructor - * @param engine the engine - * @param data the data to use for this vertex buffer - * @param kind the vertex buffer kind - * @param updatable whether the data is updatable - * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) - * @param stride the stride (optional) - * @param instanced whether the buffer is instanced (optional) - * @param offset the offset of the data (optional) - * @param size the number of components (optional) - * @param type the type of the component (optional) - * @param normalized whether the data contains normalized data (optional) - * @param useBytes set to true if stride and offset are in bytes (optional) - * @param divisor defines the instance divisor to use (1 by default) - * @param takeBufferOwnership defines if the buffer should be released when the vertex buffer is disposed - */ - constructor(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized = false, useBytes = false, divisor = 1, takeBufferOwnership = false) { - if (data instanceof Buffer) { - this._buffer = data; - this._ownsBuffer = takeBufferOwnership; - } - else { - this._buffer = new Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes); - this._ownsBuffer = true; - } - this.uniqueId = buffer_VertexBuffer._Counter++; - this._kind = kind; - if (type == undefined) { - const vertexData = this.getData(); - this.type = buffer_VertexBuffer.FLOAT; - if (vertexData instanceof Int8Array) { - this.type = buffer_VertexBuffer.BYTE; - } - else if (vertexData instanceof Uint8Array) { - this.type = buffer_VertexBuffer.UNSIGNED_BYTE; - } - else if (vertexData instanceof Int16Array) { - this.type = buffer_VertexBuffer.SHORT; - } - else if (vertexData instanceof Uint16Array) { - this.type = buffer_VertexBuffer.UNSIGNED_SHORT; - } - else if (vertexData instanceof Int32Array) { - this.type = buffer_VertexBuffer.INT; - } - else if (vertexData instanceof Uint32Array) { - this.type = buffer_VertexBuffer.UNSIGNED_INT; - } - } - else { - this.type = type; - } - const typeByteLength = buffer_VertexBuffer.GetTypeByteLength(this.type); - if (useBytes) { - this._size = size || (stride ? stride / typeByteLength : buffer_VertexBuffer.DeduceStride(kind)); - this.byteStride = stride || this._buffer.byteStride || this._size * typeByteLength; - this.byteOffset = offset || 0; - } - else { - this._size = size || stride || buffer_VertexBuffer.DeduceStride(kind); - this.byteStride = stride ? stride * typeByteLength : this._buffer.byteStride || this._size * typeByteLength; - this.byteOffset = (offset || 0) * typeByteLength; - } - this.normalized = normalized; - this._instanced = instanced !== undefined ? instanced : false; - this._instanceDivisor = instanced ? divisor : 0; - this._computeHashCode(); - } - _computeHashCode() { - // note: cast to any because the property is declared readonly - this.hashCode = - ((this.type - 5120) << 0) + - ((this.normalized ? 1 : 0) << 3) + - (this._size << 4) + - ((this._instanced ? 1 : 0) << 6) + - /* keep 5 bits free */ - (this.byteStride << 12); - } - /** @internal */ - _rebuild() { - if (!this._buffer) { - return; - } - this._buffer._rebuild(); - } - /** - * Returns the kind of the VertexBuffer (string) - * @returns a string - */ - getKind() { - return this._kind; - } - // Properties - /** - * Gets a boolean indicating if the VertexBuffer is updatable? - * @returns true if the buffer is updatable - */ - isUpdatable() { - return this._buffer.isUpdatable(); - } - /** - * Gets current buffer's data - * @returns a DataArray or null - */ - getData() { - return this._buffer.getData(); - } - /** - * Gets current buffer's data as a float array. Float data is constructed if the vertex buffer data cannot be returned directly. - * @param totalVertices number of vertices in the buffer to take into account - * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it - * @returns a float array containing vertex data - */ - getFloatData(totalVertices, forceCopy) { - const data = this.getData(); - if (!data) { - return null; - } - const tightlyPackedByteStride = this.getSize() * buffer_VertexBuffer.GetTypeByteLength(this.type); - const count = totalVertices * this.getSize(); - if (this.type !== buffer_VertexBuffer.FLOAT || this.byteStride !== tightlyPackedByteStride) { - const copy = new Float32Array(count); - this.forEach(count, (value, index) => (copy[index] = value)); - return copy; - } - if (!(data instanceof Array || data instanceof Float32Array) || this.byteOffset !== 0 || data.length !== count) { - if (data instanceof Array) { - const offset = this.byteOffset / 4; - return data.slice(offset, offset + count); - } - else if (data instanceof ArrayBuffer) { - return new Float32Array(data, this.byteOffset, count); - } - else { - let offset = data.byteOffset + this.byteOffset; - if (forceCopy) { - const result = new Float32Array(count); - const source = new Float32Array(data.buffer, offset, count); - result.set(source); - return result; - } - // Protect against bad data - const remainder = offset % 4; - if (remainder) { - offset = Math.max(0, offset - remainder); - } - return new Float32Array(data.buffer, offset, count); - } - } - if (forceCopy) { - return data.slice(); - } - return data; - } - /** - * Gets underlying native buffer - * @returns underlying native buffer - */ - getBuffer() { - return this._buffer.getBuffer(); - } - /** - * Gets the stride in float32 units (i.e. byte stride / 4). - * May not be an integer if the byte stride is not divisible by 4. - * @returns the stride in float32 units - * @deprecated Please use byteStride instead. - */ - getStrideSize() { - return this.byteStride / buffer_VertexBuffer.GetTypeByteLength(this.type); - } - /** - * Returns the offset as a multiple of the type byte length. - * @returns the offset in bytes - * @deprecated Please use byteOffset instead. - */ - getOffset() { - return this.byteOffset / buffer_VertexBuffer.GetTypeByteLength(this.type); - } - /** - * Returns the number of components or the byte size per vertex attribute - * @param sizeInBytes If true, returns the size in bytes or else the size in number of components of the vertex attribute (default: false) - * @returns the number of components - */ - getSize(sizeInBytes = false) { - return sizeInBytes ? this._size * buffer_VertexBuffer.GetTypeByteLength(this.type) : this._size; - } - /** - * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced - * @returns true if this buffer is instanced - */ - getIsInstanced() { - return this._instanced; - } - /** - * Returns the instancing divisor, zero for non-instanced (integer). - * @returns a number - */ - getInstanceDivisor() { - return this._instanceDivisor; - } - // Methods - /** - * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property - * @param data defines the data to store - */ - create(data) { - this._buffer.create(data); - } - /** - * Updates the underlying buffer according to the passed numeric array or Float32Array. - * This function will create a new buffer if the current one is not updatable - * @param data defines the data to store - */ - update(data) { - this._buffer.update(data); - } - /** - * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array. - * Returns the directly updated WebGLBuffer. - * @param data the new data - * @param offset the new offset - * @param useBytes set to true if the offset is in bytes - */ - updateDirectly(data, offset, useBytes = false) { - this._buffer.updateDirectly(data, offset, undefined, useBytes); - } - /** - * Disposes the VertexBuffer and the underlying WebGLBuffer. - */ - dispose() { - if (this._ownsBuffer) { - this._buffer.dispose(); - } - } - /** - * Enumerates each value of this vertex buffer as numbers. - * @param count the number of values to enumerate - * @param callback the callback function called for each value - */ - forEach(count, callback) { - buffer_VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback); - } - /** - * Deduces the stride given a kind. - * @param kind The kind string to deduce - * @returns The deduced stride - */ - static DeduceStride(kind) { - switch (kind) { - case buffer_VertexBuffer.UVKind: - case buffer_VertexBuffer.UV2Kind: - case buffer_VertexBuffer.UV3Kind: - case buffer_VertexBuffer.UV4Kind: - case buffer_VertexBuffer.UV5Kind: - case buffer_VertexBuffer.UV6Kind: - return 2; - case buffer_VertexBuffer.NormalKind: - case buffer_VertexBuffer.PositionKind: - return 3; - case buffer_VertexBuffer.ColorKind: - case buffer_VertexBuffer.MatricesIndicesKind: - case buffer_VertexBuffer.MatricesIndicesExtraKind: - case buffer_VertexBuffer.MatricesWeightsKind: - case buffer_VertexBuffer.MatricesWeightsExtraKind: - case buffer_VertexBuffer.TangentKind: - return 4; - default: - throw new Error("Invalid kind '" + kind + "'"); - } - } - /** - * Gets the byte length of the given type. - * @param type the type - * @returns the number of bytes - */ - static GetTypeByteLength(type) { - switch (type) { - case buffer_VertexBuffer.BYTE: - case buffer_VertexBuffer.UNSIGNED_BYTE: - return 1; - case buffer_VertexBuffer.SHORT: - case buffer_VertexBuffer.UNSIGNED_SHORT: - return 2; - case buffer_VertexBuffer.INT: - case buffer_VertexBuffer.UNSIGNED_INT: - case buffer_VertexBuffer.FLOAT: - return 4; - default: - throw new Error(`Invalid type '${type}'`); - } - } - /** - * Enumerates each value of the given parameters as numbers. - * @param data the data to enumerate - * @param byteOffset the byte offset of the data - * @param byteStride the byte stride of the data - * @param componentCount the number of components per element - * @param componentType the type of the component - * @param count the number of values to enumerate - * @param normalized whether the data is normalized - * @param callback the callback function called for each value - */ - static ForEach(data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) { - if (data instanceof Array) { - let offset = byteOffset / 4; - const stride = byteStride / 4; - for (let index = 0; index < count; index += componentCount) { - for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) { - callback(data[offset + componentIndex], index + componentIndex); - } - offset += stride; - } - } - else { - const dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength); - const componentByteLength = buffer_VertexBuffer.GetTypeByteLength(componentType); - for (let index = 0; index < count; index += componentCount) { - let componentByteOffset = byteOffset; - for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) { - const value = buffer_VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized); - callback(value, index + componentIndex); - componentByteOffset += componentByteLength; - } - byteOffset += byteStride; - } - } - } - static _GetFloatValue(dataView, type, byteOffset, normalized) { - switch (type) { - case buffer_VertexBuffer.BYTE: { - let value = dataView.getInt8(byteOffset); - if (normalized) { - value = Math.max(value / 127, -1); - } - return value; - } - case buffer_VertexBuffer.UNSIGNED_BYTE: { - let value = dataView.getUint8(byteOffset); - if (normalized) { - value = value / 255; - } - return value; - } - case buffer_VertexBuffer.SHORT: { - let value = dataView.getInt16(byteOffset, true); - if (normalized) { - value = Math.max(value / 32767, -1); - } - return value; - } - case buffer_VertexBuffer.UNSIGNED_SHORT: { - let value = dataView.getUint16(byteOffset, true); - if (normalized) { - value = value / 65535; - } - return value; - } - case buffer_VertexBuffer.INT: { - return dataView.getInt32(byteOffset, true); - } - case buffer_VertexBuffer.UNSIGNED_INT: { - return dataView.getUint32(byteOffset, true); - } - case buffer_VertexBuffer.FLOAT: { - return dataView.getFloat32(byteOffset, true); - } - default: { - throw new Error(`Invalid component type ${type}`); - } - } - } -} -buffer_VertexBuffer._Counter = 0; -/** - * The byte type. - */ -buffer_VertexBuffer.BYTE = 5120; -/** - * The unsigned byte type. - */ -buffer_VertexBuffer.UNSIGNED_BYTE = 5121; -/** - * The short type. - */ -buffer_VertexBuffer.SHORT = 5122; -/** - * The unsigned short type. - */ -buffer_VertexBuffer.UNSIGNED_SHORT = 5123; -/** - * The integer type. - */ -buffer_VertexBuffer.INT = 5124; -/** - * The unsigned integer type. - */ -buffer_VertexBuffer.UNSIGNED_INT = 5125; -/** - * The float type. - */ -buffer_VertexBuffer.FLOAT = 5126; -// Enums -/** - * Positions - */ -buffer_VertexBuffer.PositionKind = "position"; -/** - * Normals - */ -buffer_VertexBuffer.NormalKind = "normal"; -/** - * Tangents - */ -buffer_VertexBuffer.TangentKind = "tangent"; -/** - * Texture coordinates - */ -buffer_VertexBuffer.UVKind = "uv"; -/** - * Texture coordinates 2 - */ -buffer_VertexBuffer.UV2Kind = "uv2"; -/** - * Texture coordinates 3 - */ -buffer_VertexBuffer.UV3Kind = "uv3"; -/** - * Texture coordinates 4 - */ -buffer_VertexBuffer.UV4Kind = "uv4"; -/** - * Texture coordinates 5 - */ -buffer_VertexBuffer.UV5Kind = "uv5"; -/** - * Texture coordinates 6 - */ -buffer_VertexBuffer.UV6Kind = "uv6"; -/** - * Colors - */ -buffer_VertexBuffer.ColorKind = "color"; -/** - * Instance Colors - */ -buffer_VertexBuffer.ColorInstanceKind = "instanceColor"; -/** - * Matrix indices (for bones) - */ -buffer_VertexBuffer.MatricesIndicesKind = "matricesIndices"; -/** - * Matrix weights (for bones) - */ -buffer_VertexBuffer.MatricesWeightsKind = "matricesWeights"; -/** - * Additional matrix indices (for bones) - */ -buffer_VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra"; -/** - * Additional matrix weights (for bones) - */ -buffer_VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra"; -//# sourceMappingURL=buffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Collisions/pickingInfo.js - - -/** - * Information about the result of picking within a scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions - */ -class PickingInfo { - constructor() { - /** - * If the pick collided with an object - */ - this.hit = false; - /** - * Distance away where the pick collided - */ - this.distance = 0; - /** - * The location of pick collision - */ - this.pickedPoint = null; - /** - * The mesh corresponding the pick collision - */ - this.pickedMesh = null; - /** (See getTextureCoordinates) The barycentric U coordinate that is used when calculating the texture coordinates of the collision.*/ - this.bu = 0; - /** (See getTextureCoordinates) The barycentric V coordinate that is used when calculating the texture coordinates of the collision.*/ - this.bv = 0; - /** The index of the face on the mesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */ - this.faceId = -1; - /** The index of the face on the subMesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */ - this.subMeshFaceId = -1; - /** Id of the submesh that was picked */ - this.subMeshId = 0; - /** If a sprite was picked, this will be the sprite the pick collided with */ - this.pickedSprite = null; - /** If we are picking a mesh with thin instance, this will give you the picked thin instance */ - this.thinInstanceIndex = -1; - /** - * The ray that was used to perform the picking. - */ - this.ray = null; - /** - * If a mesh was used to do the picking (eg. 6dof controller) as a "near interaction", this will be populated. - */ - this.originMesh = null; - /** - * The aim-space transform of the input used for picking, if it is an XR input source. - */ - this.aimTransform = null; - /** - * The grip-space transform of the input used for picking, if it is an XR input source. - * Some XR sources, such as input coming from head mounted displays, do not have this. - */ - this.gripTransform = null; - } - /** - * Gets the normal corresponding to the face the pick collided with - * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false) - * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map (default: true) - * @returns The normal corresponding to the face the pick collided with - * @remarks Note that the returned normal will always point towards the picking ray. - */ - getNormal(useWorldCoordinates = false, useVerticesNormals = true) { - if (!this.pickedMesh || (useVerticesNormals && !this.pickedMesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind))) { - return null; - } - let indices = this.pickedMesh.getIndices(); - if ((indices === null || indices === void 0 ? void 0 : indices.length) === 0) { - indices = null; - } - let result; - const tmp0 = math_vector_TmpVectors.Vector3[0]; - const tmp1 = math_vector_TmpVectors.Vector3[1]; - const tmp2 = math_vector_TmpVectors.Vector3[2]; - if (useVerticesNormals) { - const normals = this.pickedMesh.getVerticesData(buffer_VertexBuffer.NormalKind); - let normal0 = indices - ? math_vector_Vector3.FromArrayToRef(normals, indices[this.faceId * 3] * 3, tmp0) - : tmp0.copyFromFloats(normals[this.faceId * 3 * 3], normals[this.faceId * 3 * 3 + 1], normals[this.faceId * 3 * 3 + 2]); - let normal1 = indices - ? math_vector_Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 1] * 3, tmp1) - : tmp1.copyFromFloats(normals[(this.faceId * 3 + 1) * 3], normals[(this.faceId * 3 + 1) * 3 + 1], normals[(this.faceId * 3 + 1) * 3 + 2]); - let normal2 = indices - ? math_vector_Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 2] * 3, tmp2) - : tmp2.copyFromFloats(normals[(this.faceId * 3 + 2) * 3], normals[(this.faceId * 3 + 2) * 3 + 1], normals[(this.faceId * 3 + 2) * 3 + 2]); - normal0 = normal0.scale(this.bu); - normal1 = normal1.scale(this.bv); - normal2 = normal2.scale(1.0 - this.bu - this.bv); - result = new math_vector_Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z); - } - else { - const positions = this.pickedMesh.getVerticesData(buffer_VertexBuffer.PositionKind); - const vertex1 = indices - ? math_vector_Vector3.FromArrayToRef(positions, indices[this.faceId * 3] * 3, tmp0) - : tmp0.copyFromFloats(positions[this.faceId * 3 * 3], positions[this.faceId * 3 * 3 + 1], positions[this.faceId * 3 * 3 + 2]); - const vertex2 = indices - ? math_vector_Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 1] * 3, tmp1) - : tmp1.copyFromFloats(positions[(this.faceId * 3 + 1) * 3], positions[(this.faceId * 3 + 1) * 3 + 1], positions[(this.faceId * 3 + 1) * 3 + 2]); - const vertex3 = indices - ? math_vector_Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 2] * 3, tmp2) - : tmp2.copyFromFloats(positions[(this.faceId * 3 + 2) * 3], positions[(this.faceId * 3 + 2) * 3 + 1], positions[(this.faceId * 3 + 2) * 3 + 2]); - const p1p2 = vertex1.subtract(vertex2); - const p3p2 = vertex3.subtract(vertex2); - result = math_vector_Vector3.Cross(p1p2, p3p2); - } - const transformNormalToWorld = (pickedMesh, n) => { - let wm = pickedMesh.getWorldMatrix(); - if (pickedMesh.nonUniformScaling) { - math_vector_TmpVectors.Matrix[0].copyFrom(wm); - wm = math_vector_TmpVectors.Matrix[0]; - wm.setTranslationFromFloats(0, 0, 0); - wm.invert(); - wm.transposeToRef(math_vector_TmpVectors.Matrix[1]); - wm = math_vector_TmpVectors.Matrix[1]; - } - math_vector_Vector3.TransformNormalToRef(n, wm, n); - }; - if (useWorldCoordinates) { - transformNormalToWorld(this.pickedMesh, result); - } - if (this.ray) { - const normalForDirectionChecking = math_vector_TmpVectors.Vector3[0].copyFrom(result); - if (!useWorldCoordinates) { - // the normal has not been transformed to world space as part as the normal processing, so we must do it now - transformNormalToWorld(this.pickedMesh, normalForDirectionChecking); - } - // Flip the normal if the picking ray is in the same direction. - if (math_vector_Vector3.Dot(normalForDirectionChecking, this.ray.direction) > 0) { - result.negateInPlace(); - } - } - result.normalize(); - return result; - } - /** - * Gets the texture coordinates of where the pick occurred - * @param uvSet The UV set to use to calculate the texture coordinates (default: VertexBuffer.UVKind) - * @returns The vector containing the coordinates of the texture - */ - getTextureCoordinates(uvSet = buffer_VertexBuffer.UVKind) { - if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(uvSet)) { - return null; - } - const indices = this.pickedMesh.getIndices(); - if (!indices) { - return null; - } - const uvs = this.pickedMesh.getVerticesData(uvSet); - if (!uvs) { - return null; - } - let uv0 = math_vector_Vector2.FromArray(uvs, indices[this.faceId * 3] * 2); - let uv1 = math_vector_Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2); - let uv2 = math_vector_Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2); - uv0 = uv0.scale(this.bu); - uv1 = uv1.scale(this.bv); - uv2 = uv2.scale(1.0 - this.bu - this.bv); - return new math_vector_Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y); - } -} -//# sourceMappingURL=pickingInfo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/postProcessManager.js - - -/** - * PostProcessManager is used to manage one or more post processes or post process pipelines - * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses - */ -class PostProcessManager { - /** - * Creates a new instance PostProcess - * @param scene The scene that the post process is associated with. - */ - constructor(scene) { - this._vertexBuffers = {}; - this._scene = scene; - } - _prepareBuffers() { - if (this._vertexBuffers[buffer_VertexBuffer.PositionKind]) { - return; - } - // VBO - const vertices = []; - vertices.push(1, 1); - vertices.push(-1, 1); - vertices.push(-1, -1); - vertices.push(1, -1); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = new buffer_VertexBuffer(this._scene.getEngine(), vertices, buffer_VertexBuffer.PositionKind, false, false, 2); - this._buildIndexBuffer(); - } - _buildIndexBuffer() { - // Indices - const indices = []; - indices.push(0); - indices.push(1); - indices.push(2); - indices.push(0); - indices.push(2); - indices.push(3); - this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices); - } - /** - * Rebuilds the vertex buffers of the manager. - * @internal - */ - _rebuild() { - const vb = this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - if (!vb) { - return; - } - vb._rebuild(); - this._buildIndexBuffer(); - } - // Methods - /** - * Prepares a frame to be run through a post process. - * @param sourceTexture The input texture to the post processes. (default: null) - * @param postProcesses An array of post processes to be run. (default: null) - * @returns True if the post processes were able to be run. - * @internal - */ - _prepareFrame(sourceTexture = null, postProcesses = null) { - const camera = this._scene.activeCamera; - if (!camera) { - return false; - } - postProcesses = postProcesses || camera._postProcesses.filter((pp) => { - return pp != null; - }); - if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) { - return false; - } - postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined); - return true; - } - /** - * Manually render a set of post processes to a texture. - * Please note, the frame buffer won't be unbound after the call in case you have more render to do. - * @param postProcesses An array of post processes to be run. - * @param targetTexture The render target wrapper to render to. - * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight - * @param faceIndex defines the face to render to if a cubemap is defined as the target - * @param lodLevel defines which lod of the texture to render to - * @param doNotBindFrambuffer If set to true, assumes that the framebuffer has been bound previously - */ - directRender(postProcesses, targetTexture = null, forceFullscreenViewport = false, faceIndex = 0, lodLevel = 0, doNotBindFrambuffer = false) { - var _a; - const engine = this._scene.getEngine(); - for (let index = 0; index < postProcesses.length; index++) { - if (index < postProcesses.length - 1) { - postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture === null || targetTexture === void 0 ? void 0 : targetTexture.texture); - } - else { - if (targetTexture) { - engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, lodLevel); - } - else if (!doNotBindFrambuffer) { - engine.restoreDefaultFramebuffer(); - } - (_a = engine._debugInsertMarker) === null || _a === void 0 ? void 0 : _a.call(engine, `post process ${postProcesses[index].name} output`); - } - const pp = postProcesses[index]; - const effect = pp.apply(); - if (effect) { - pp.onBeforeRenderObservable.notifyObservers(effect); - // VBOs - this._prepareBuffers(); - engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); - // Draw order - engine.drawElementsType(0, 0, 6); - pp.onAfterRenderObservable.notifyObservers(effect); - } - } - // Restore depth buffer - engine.setDepthBuffer(true); - engine.setDepthWrite(true); - } - /** - * Finalize the result of the output of the postprocesses. - * @param doNotPresent If true the result will not be displayed to the screen. - * @param targetTexture The render target wrapper to render to. - * @param faceIndex The index of the face to bind the target texture to. - * @param postProcesses The array of post processes to render. - * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false) - * @internal - */ - _finalizeFrame(doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport = false) { - var _a; - const camera = this._scene.activeCamera; - if (!camera) { - return; - } - postProcesses = postProcesses || camera._postProcesses.filter((pp) => { - return pp != null; - }); - if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) { - return; - } - const engine = this._scene.getEngine(); - for (let index = 0, len = postProcesses.length; index < len; index++) { - const pp = postProcesses[index]; - if (index < len - 1) { - pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture === null || targetTexture === void 0 ? void 0 : targetTexture.texture); - } - else { - if (targetTexture) { - engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport); - pp._outputTexture = targetTexture; - } - else { - engine.restoreDefaultFramebuffer(); - pp._outputTexture = null; - } - (_a = engine._debugInsertMarker) === null || _a === void 0 ? void 0 : _a.call(engine, `post process ${postProcesses[index].name} output`); - } - if (doNotPresent) { - break; - } - const effect = pp.apply(); - if (effect) { - pp.onBeforeRenderObservable.notifyObservers(effect); - // VBOs - this._prepareBuffers(); - engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); - // Draw order - engine.drawElementsType(0, 0, 6); - pp.onAfterRenderObservable.notifyObservers(effect); - } - } - // Restore states - engine.setDepthBuffer(true); - engine.setDepthWrite(true); - engine.setAlphaMode(0); - } - /** - * Disposes of the post process manager. - */ - dispose() { - const buffer = this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - if (buffer) { - buffer.dispose(); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = null; - } - if (this._indexBuffer) { - this._scene.getEngine()._releaseBuffer(this._indexBuffer); - this._indexBuffer = null; - } - } -} -//# sourceMappingURL=postProcessManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/renderingGroup.js - - - -/** - * This represents the object necessary to create a rendering group. - * This is exclusively used and created by the rendering manager. - * To modify the behavior, you use the available helpers in your scene or meshes. - * @internal - */ -class RenderingGroup { - /** - * Set the opaque sort comparison function. - * If null the sub meshes will be render in the order they were created - */ - set opaqueSortCompareFn(value) { - if (value) { - this._opaqueSortCompareFn = value; - } - else { - this._opaqueSortCompareFn = RenderingGroup.PainterSortCompare; - } - this._renderOpaque = this._renderOpaqueSorted; - } - /** - * Set the alpha test sort comparison function. - * If null the sub meshes will be render in the order they were created - */ - set alphaTestSortCompareFn(value) { - if (value) { - this._alphaTestSortCompareFn = value; - } - else { - this._alphaTestSortCompareFn = RenderingGroup.PainterSortCompare; - } - this._renderAlphaTest = this._renderAlphaTestSorted; - } - /** - * Set the transparent sort comparison function. - * If null the sub meshes will be render in the order they were created - */ - set transparentSortCompareFn(value) { - if (value) { - this._transparentSortCompareFn = value; - } - else { - this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare; - } - this._renderTransparent = this._renderTransparentSorted; - } - /** - * Creates a new rendering group. - * @param index The rendering group index - * @param scene - * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied - * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied - * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied - */ - constructor(index, scene, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { - this.index = index; - this._opaqueSubMeshes = new SmartArray(256); - this._transparentSubMeshes = new SmartArray(256); - this._alphaTestSubMeshes = new SmartArray(256); - this._depthOnlySubMeshes = new SmartArray(256); - this._particleSystems = new SmartArray(256); - this._spriteManagers = new SmartArray(256); - /** @internal */ - this._empty = true; - /** @internal */ - this._edgesRenderers = new SmartArrayNoDuplicate(16); - this._scene = scene; - this.opaqueSortCompareFn = opaqueSortCompareFn; - this.alphaTestSortCompareFn = alphaTestSortCompareFn; - this.transparentSortCompareFn = transparentSortCompareFn; - } - /** - * Render all the sub meshes contained in the group. - * @param customRenderFunction Used to override the default render behaviour of the group. - * @param renderSprites - * @param renderParticles - * @param activeMeshes - * @returns true if rendered some submeshes. - */ - render(customRenderFunction, renderSprites, renderParticles, activeMeshes) { - if (customRenderFunction) { - customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes); - return; - } - const engine = this._scene.getEngine(); - // Depth only - if (this._depthOnlySubMeshes.length !== 0) { - engine.setColorWrite(false); - this._renderAlphaTest(this._depthOnlySubMeshes); - engine.setColorWrite(true); - } - // Opaque - if (this._opaqueSubMeshes.length !== 0) { - this._renderOpaque(this._opaqueSubMeshes); - } - // Alpha test - if (this._alphaTestSubMeshes.length !== 0) { - this._renderAlphaTest(this._alphaTestSubMeshes); - } - const stencilState = engine.getStencilBuffer(); - engine.setStencilBuffer(false); - // Sprites - if (renderSprites) { - this._renderSprites(); - } - // Particles - if (renderParticles) { - this._renderParticles(activeMeshes); - } - if (this.onBeforeTransparentRendering) { - this.onBeforeTransparentRendering(); - } - // Transparent - if (this._transparentSubMeshes.length !== 0 || this._scene.useOrderIndependentTransparency) { - engine.setStencilBuffer(stencilState); - if (this._scene.useOrderIndependentTransparency) { - const excludedMeshes = this._scene.depthPeelingRenderer.render(this._transparentSubMeshes); - if (excludedMeshes.length) { - // Render leftover meshes that could not be processed by depth peeling - this._renderTransparent(excludedMeshes); - } - } - else { - this._renderTransparent(this._transparentSubMeshes); - } - engine.setAlphaMode(0); - } - // Set back stencil to false in case it changes before the edge renderer. - engine.setStencilBuffer(false); - // Edges - if (this._edgesRenderers.length) { - for (let edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) { - this._edgesRenderers.data[edgesRendererIndex].render(); - } - engine.setAlphaMode(0); - } - // Restore Stencil state. - engine.setStencilBuffer(stencilState); - } - /** - * Renders the opaque submeshes in the order from the opaqueSortCompareFn. - * @param subMeshes The submeshes to render - */ - _renderOpaqueSorted(subMeshes) { - return RenderingGroup._RenderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false); - } - /** - * Renders the opaque submeshes in the order from the alphatestSortCompareFn. - * @param subMeshes The submeshes to render - */ - _renderAlphaTestSorted(subMeshes) { - return RenderingGroup._RenderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false); - } - /** - * Renders the opaque submeshes in the order from the transparentSortCompareFn. - * @param subMeshes The submeshes to render - */ - _renderTransparentSorted(subMeshes) { - return RenderingGroup._RenderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true); - } - /** - * Renders the submeshes in a specified order. - * @param subMeshes The submeshes to sort before render - * @param sortCompareFn The comparison function use to sort - * @param camera The camera position use to preprocess the submeshes to help sorting - * @param transparent Specifies to activate blending if true - */ - static _RenderSorted(subMeshes, sortCompareFn, camera, transparent) { - let subIndex = 0; - let subMesh; - const cameraPosition = camera ? camera.globalPosition : RenderingGroup._ZeroVector; - if (transparent) { - for (; subIndex < subMeshes.length; subIndex++) { - subMesh = subMeshes.data[subIndex]; - subMesh._alphaIndex = subMesh.getMesh().alphaIndex; - subMesh._distanceToCamera = math_vector_Vector3.Distance(subMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition); - } - } - const sortedArray = subMeshes.length === subMeshes.data.length ? subMeshes.data : subMeshes.data.slice(0, subMeshes.length); - if (sortCompareFn) { - sortedArray.sort(sortCompareFn); - } - const scene = sortedArray[0].getMesh().getScene(); - for (subIndex = 0; subIndex < sortedArray.length; subIndex++) { - subMesh = sortedArray[subIndex]; - if (scene._activeMeshesFrozenButKeepClipping && !subMesh.isInFrustum(scene._frustumPlanes)) { - continue; - } - if (transparent) { - const material = subMesh.getMaterial(); - if (material && material.needDepthPrePass) { - const engine = material.getScene().getEngine(); - engine.setColorWrite(false); - engine.setAlphaMode(0); - subMesh.render(false); - engine.setColorWrite(true); - } - } - subMesh.render(transparent); - } - } - /** - * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) - * are rendered back to front if in the same alpha index. - * - * @param a The first submesh - * @param b The second submesh - * @returns The result of the comparison - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static defaultTransparentSortCompare(a, b) { - // Alpha index first - if (a._alphaIndex > b._alphaIndex) { - return 1; - } - if (a._alphaIndex < b._alphaIndex) { - return -1; - } - // Then distance to camera - return RenderingGroup.backToFrontSortCompare(a, b); - } - /** - * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) - * are rendered back to front. - * - * @param a The first submesh - * @param b The second submesh - * @returns The result of the comparison - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static backToFrontSortCompare(a, b) { - // Then distance to camera - if (a._distanceToCamera < b._distanceToCamera) { - return 1; - } - if (a._distanceToCamera > b._distanceToCamera) { - return -1; - } - return 0; - } - /** - * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) - * are rendered front to back (prevent overdraw). - * - * @param a The first submesh - * @param b The second submesh - * @returns The result of the comparison - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static frontToBackSortCompare(a, b) { - // Then distance to camera - if (a._distanceToCamera < b._distanceToCamera) { - return -1; - } - if (a._distanceToCamera > b._distanceToCamera) { - return 1; - } - return 0; - } - /** - * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) - * are grouped by material then geometry. - * - * @param a The first submesh - * @param b The second submesh - * @returns The result of the comparison - */ - static PainterSortCompare(a, b) { - const meshA = a.getMesh(); - const meshB = b.getMesh(); - if (meshA.material && meshB.material) { - return meshA.material.uniqueId - meshB.material.uniqueId; - } - return meshA.uniqueId - meshB.uniqueId; - } - /** - * Resets the different lists of submeshes to prepare a new frame. - */ - prepare() { - this._opaqueSubMeshes.reset(); - this._transparentSubMeshes.reset(); - this._alphaTestSubMeshes.reset(); - this._depthOnlySubMeshes.reset(); - this._particleSystems.reset(); - this.prepareSprites(); - this._edgesRenderers.reset(); - this._empty = true; - } - /** - * Resets the different lists of sprites to prepare a new frame. - */ - 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(); - } - /** - * Inserts the submesh in its correct queue depending on its material. - * @param subMesh The submesh to dispatch - * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. - * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. - */ - dispatch(subMesh, mesh, material) { - // Get mesh and materials if not provided - if (mesh === undefined) { - mesh = subMesh.getMesh(); - } - if (material === undefined) { - material = subMesh.getMaterial(); - } - if (material === null || material === undefined) { - return; - } - if (material.needAlphaBlendingForMesh(mesh)) { - // Transparent - this._transparentSubMeshes.push(subMesh); - } - else if (material.needAlphaTesting()) { - // Alpha test - if (material.needDepthPrePass) { - this._depthOnlySubMeshes.push(subMesh); - } - this._alphaTestSubMeshes.push(subMesh); - } - else { - if (material.needDepthPrePass) { - this._depthOnlySubMeshes.push(subMesh); - } - this._opaqueSubMeshes.push(subMesh); // Opaque - } - mesh._renderingGroup = this; - if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) { - this._edgesRenderers.pushNoDuplicate(mesh._edgesRenderer); - } - this._empty = false; - } - dispatchSprites(spriteManager) { - this._spriteManagers.push(spriteManager); - this._empty = false; - } - dispatchParticles(particleSystem) { - this._particleSystems.push(particleSystem); - this._empty = false; - } - _renderParticles(activeMeshes) { - if (this._particleSystems.length === 0) { - return; - } - // Particles - const activeCamera = this._scene.activeCamera; - this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene); - for (let particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) { - const particleSystem = this._particleSystems.data[particleIndex]; - if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) { - continue; - } - const emitter = particleSystem.emitter; - if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) { - this._scene._activeParticles.addCount(particleSystem.render(), false); - } - } - this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene); - } - _renderSprites() { - if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) { - return; - } - // Sprites - const activeCamera = this._scene.activeCamera; - this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene); - for (let id = 0; id < this._spriteManagers.length; id++) { - const spriteManager = this._spriteManagers.data[id]; - if ((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0) { - spriteManager.render(); - } - } - this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene); - } -} -RenderingGroup._ZeroVector = math_vector_Vector3.Zero(); -//# sourceMappingURL=renderingGroup.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/renderingManager.js - -/** - * This class is used by the onRenderingGroupObservable - */ -class RenderingGroupInfo { -} -/** - * This is the manager responsible of all the rendering for meshes sprites and particles. - * It is enable to manage the different groups as well as the different necessary sort functions. - * This should not be used directly aside of the few static configurations - */ -class RenderingManager { - /** - * Gets or sets a boolean indicating that the manager will not reset between frames. - * This means that if a mesh becomes invisible or transparent it will not be visible until this boolean is set to false again. - * By default, the rendering manager will dispatch all active meshes per frame (moving them to the transparent, opaque or alpha testing lists). - * By turning this property on, you will accelerate the rendering by keeping all these lists unchanged between frames. - */ - get maintainStateBetweenFrames() { - return this._maintainStateBetweenFrames; - } - set maintainStateBetweenFrames(value) { - if (value === this._maintainStateBetweenFrames) { - return; - } - this._maintainStateBetweenFrames = value; - // Restore wasDispatched flags when switching to maintainStateBetweenFrames to false - if (!this._maintainStateBetweenFrames) { - for (const mesh of this._scene.meshes) { - if (mesh.subMeshes) { - for (const subMesh of mesh.subMeshes) { - subMesh._wasDispatched = false; - } - } - } - if (this._scene.spriteManagers) { - for (const spriteManager of this._scene.spriteManagers) { - spriteManager._wasDispatched = false; - } - } - for (const particleSystem of this._scene.particleSystems) { - particleSystem._wasDispatched = false; - } - } - } - /** - * Instantiates a new rendering group for a particular scene - * @param scene Defines the scene the groups belongs to - */ - constructor(scene) { - /** - * @internal - */ - this._useSceneAutoClearSetup = false; - this._renderingGroups = new Array(); - this._autoClearDepthStencil = {}; - this._customOpaqueSortCompareFn = {}; - this._customAlphaTestSortCompareFn = {}; - this._customTransparentSortCompareFn = {}; - this._renderingGroupInfo = new RenderingGroupInfo(); - this._maintainStateBetweenFrames = false; - this._scene = scene; - for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) { - this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true }; - } - } - /** - * Gets the rendering group with the specified id. - */ - getRenderingGroup(id) { - const renderingGroupId = id || 0; - this._prepareRenderingGroup(renderingGroupId); - return this._renderingGroups[renderingGroupId]; - } - _clearDepthStencilBuffer(depth = true, stencil = true) { - if (this._depthStencilBufferAlreadyCleaned) { - return; - } - this._scene.getEngine().clear(null, false, depth, stencil); - this._depthStencilBufferAlreadyCleaned = true; - } - /** - * Renders the entire managed groups. This is used by the scene or the different render targets. - * @internal - */ - render(customRenderFunction, activeMeshes, renderParticles, renderSprites) { - // Update the observable context (not null as it only goes away on dispose) - const info = this._renderingGroupInfo; - info.scene = this._scene; - info.camera = this._scene.activeCamera; - // Dispatch sprites - if (this._scene.spriteManagers && renderSprites) { - for (let index = 0; index < this._scene.spriteManagers.length; index++) { - const manager = this._scene.spriteManagers[index]; - this.dispatchSprites(manager); - } - } - // Render - for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { - this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS; - const renderingGroup = this._renderingGroups[index]; - if (!renderingGroup || renderingGroup._empty) { - continue; - } - const renderingGroupMask = Math.pow(2, index); - info.renderingGroupId = index; - // Before Observable - this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask); - // Clear depth/stencil if needed - if (RenderingManager.AUTOCLEAR) { - const autoClear = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(index) : this._autoClearDepthStencil[index]; - if (autoClear && autoClear.autoClear) { - this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil); - } - } - // Render - for (const step of this._scene._beforeRenderingGroupDrawStage) { - step.action(index); - } - renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes); - for (const step of this._scene._afterRenderingGroupDrawStage) { - step.action(index); - } - // After Observable - this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask); - } - } - /** - * Resets the different information of the group to prepare a new frame - * @internal - */ - reset() { - if (this.maintainStateBetweenFrames) { - return; - } - for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { - const renderingGroup = this._renderingGroups[index]; - if (renderingGroup) { - renderingGroup.prepare(); - } - } - } - /** - * Resets the sprites information of the group to prepare a new frame - * @internal - */ - resetSprites() { - if (this.maintainStateBetweenFrames) { - return; - } - for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { - const renderingGroup = this._renderingGroups[index]; - if (renderingGroup) { - renderingGroup.prepareSprites(); - } - } - } - /** - * Dispose and release the group and its associated resources. - * @internal - */ - dispose() { - this.freeRenderingGroups(); - this._renderingGroups.length = 0; - this._renderingGroupInfo = null; - } - /** - * Clear the info related to rendering groups preventing retention points during dispose. - */ - freeRenderingGroups() { - for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { - const renderingGroup = this._renderingGroups[index]; - if (renderingGroup) { - renderingGroup.dispose(); - } - } - } - _prepareRenderingGroup(renderingGroupId) { - if (this._renderingGroups[renderingGroupId] === undefined) { - this._renderingGroups[renderingGroupId] = new RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]); - } - } - /** - * Add a sprite manager to the rendering manager in order to render it this frame. - * @param spriteManager Define the sprite manager to render - */ - dispatchSprites(spriteManager) { - if (this.maintainStateBetweenFrames && spriteManager._wasDispatched) { - return; - } - spriteManager._wasDispatched = true; - this.getRenderingGroup(spriteManager.renderingGroupId).dispatchSprites(spriteManager); - } - /** - * Add a particle system to the rendering manager in order to render it this frame. - * @param particleSystem Define the particle system to render - */ - dispatchParticles(particleSystem) { - if (this.maintainStateBetweenFrames && particleSystem._wasDispatched) { - return; - } - particleSystem._wasDispatched = true; - this.getRenderingGroup(particleSystem.renderingGroupId).dispatchParticles(particleSystem); - } - /** - * Add a submesh to the manager in order to render it this frame - * @param subMesh The submesh to dispatch - * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. - * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. - */ - dispatch(subMesh, mesh, material) { - if (mesh === undefined) { - mesh = subMesh.getMesh(); - } - if (this.maintainStateBetweenFrames && subMesh._wasDispatched) { - return; - } - subMesh._wasDispatched = true; - this.getRenderingGroup(mesh.renderingGroupId).dispatch(subMesh, mesh, material); - } - /** - * Overrides the default sort function applied in the rendering group to prepare the meshes. - * This allowed control for front to back rendering or reversely depending of the special needs. - * - * @param renderingGroupId The rendering group id corresponding to its index - * @param opaqueSortCompareFn The opaque queue comparison function use to sort. - * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. - * @param transparentSortCompareFn The transparent queue comparison function use to sort. - */ - setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { - this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn; - this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn; - this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn; - if (this._renderingGroups[renderingGroupId]) { - const group = this._renderingGroups[renderingGroupId]; - group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId]; - group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId]; - group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId]; - } - } - /** - * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. - * - * @param renderingGroupId The rendering group id corresponding to its index - * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. - * @param depth Automatically clears depth between groups if true and autoClear is true. - * @param stencil Automatically clears stencil between groups if true and autoClear is true. - */ - setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) { - this._autoClearDepthStencil[renderingGroupId] = { - autoClear: autoClearDepthStencil, - depth: depth, - stencil: stencil, - }; - } - /** - * Gets the current auto clear configuration for one rendering group of the rendering - * manager. - * @param index the rendering group index to get the information for - * @returns The auto clear setup for the requested rendering group - */ - getAutoClearDepthStencilSetup(index) { - return this._autoClearDepthStencil[index]; - } -} -/** - * The max id used for rendering groups (not included) - */ -RenderingManager.MAX_RENDERINGGROUPS = 4; -/** - * The min id used for rendering groups (included) - */ -RenderingManager.MIN_RENDERINGGROUPS = 0; -/** - * Used to globally prevent autoclearing scenes. - */ -RenderingManager.AUTOCLEAR = true; -//# sourceMappingURL=renderingManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/sceneComponent.js -/** - * Groups all the scene component constants in one place to ease maintenance. - * @internal - */ -class sceneComponent_SceneComponentConstants { -} -sceneComponent_SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer"; -sceneComponent_SceneComponentConstants.NAME_LAYER = "Layer"; -sceneComponent_SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem"; -sceneComponent_SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer"; -sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem"; -sceneComponent_SceneComponentConstants.NAME_GAMEPAD = "Gamepad"; -sceneComponent_SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue"; -sceneComponent_SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer"; -sceneComponent_SceneComponentConstants.NAME_PREPASSRENDERER = "PrePassRenderer"; -sceneComponent_SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer"; -sceneComponent_SceneComponentConstants.NAME_DEPTHPEELINGRENDERER = "DepthPeelingRenderer"; -sceneComponent_SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager"; -sceneComponent_SceneComponentConstants.NAME_SPRITE = "Sprite"; -sceneComponent_SceneComponentConstants.NAME_SUBSURFACE = "SubSurface"; -sceneComponent_SceneComponentConstants.NAME_OUTLINERENDERER = "Outline"; -sceneComponent_SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture"; -sceneComponent_SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator"; -sceneComponent_SceneComponentConstants.NAME_OCTREE = "Octree"; -sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine"; -sceneComponent_SceneComponentConstants.NAME_AUDIO = "Audio"; -sceneComponent_SceneComponentConstants.NAME_FLUIDRENDERER = "FluidRenderer"; -sceneComponent_SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0; -sceneComponent_SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0; -sceneComponent_SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0; -sceneComponent_SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER = 0; -sceneComponent_SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1; -sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS = 0; -sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 1; -sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 2; -sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS = 0; -sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER = 1; -sceneComponent_SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS = 0; -sceneComponent_SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 1; -sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS = 0; -sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 1; -sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0; -sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1; -sceneComponent_SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0; -sceneComponent_SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1; -sceneComponent_SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0; -sceneComponent_SceneComponentConstants.STEP_BEFORECLEAR_PREPASS = 1; -sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS = 0; -sceneComponent_SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_PREPASS = 0; -sceneComponent_SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER = 1; -sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS = 0; -sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 1; -sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 2; -sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3; -sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4; -sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER = 5; -sceneComponent_SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER = 0; -sceneComponent_SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER = 0; -sceneComponent_SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0; -sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 0; -sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1; -sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 2; -sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3; -sceneComponent_SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0; -sceneComponent_SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER = 1; -sceneComponent_SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0; -sceneComponent_SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0; -sceneComponent_SceneComponentConstants.STEP_POINTERUP_SPRITE = 0; -/** - * Representation of a stage in the scene (Basically a list of ordered steps) - * @internal - */ -class Stage extends Array { - /** - * Hide ctor from the rest of the world. - * @param items The items to add. - */ - constructor(items) { - super(...items); - } - /** - * Creates a new Stage. - * @returns A new instance of a Stage - */ - static Create() { - return Object.create(Stage.prototype); - } - /** - * Registers a step in an ordered way in the targeted stage. - * @param index Defines the position to register the step in - * @param component Defines the component attached to the step - * @param action Defines the action to launch during the step - */ - registerStep(index, component, action) { - let i = 0; - let maxIndex = Number.MAX_VALUE; - for (; i < this.length; i++) { - const step = this[i]; - maxIndex = step.index; - if (index < maxIndex) { - break; - } - } - this.splice(i, 0, { index, component, action: action.bind(component) }); - } - /** - * Clears all the steps from the stage. - */ - clear() { - this.length = 0; - } -} -//# sourceMappingURL=sceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Events/pointerEvents.js - -/** - * Gather the list of pointer event types as constants. - */ -class pointerEvents_PointerEventTypes { -} -/** - * 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. - */ -pointerEvents_PointerEventTypes.POINTERDOWN = 0x01; -/** - * The pointerup event is fired when a pointer is no longer active. - */ -pointerEvents_PointerEventTypes.POINTERUP = 0x02; -/** - * The pointermove event is fired when a pointer changes coordinates. - */ -pointerEvents_PointerEventTypes.POINTERMOVE = 0x04; -/** - * The pointerwheel event is fired when a mouse wheel has been rotated. - */ -pointerEvents_PointerEventTypes.POINTERWHEEL = 0x08; -/** - * The pointerpick event is fired when a mesh or sprite has been picked by the pointer. - */ -pointerEvents_PointerEventTypes.POINTERPICK = 0x10; -/** - * The pointertap event is fired when a the object has been touched and released without drag. - */ -pointerEvents_PointerEventTypes.POINTERTAP = 0x20; -/** - * The pointerdoubletap event is fired when a the object has been touched and released twice without drag. - */ -pointerEvents_PointerEventTypes.POINTERDOUBLETAP = 0x40; -/** - * Base class of pointer info types. - */ -class PointerInfoBase { - /** - * Instantiates the base class of pointers info. - * @param type Defines the type of event (PointerEventTypes) - * @param event Defines the related dom event - */ - constructor( - /** - * Defines the type of event (PointerEventTypes) - */ - type, - /** - * Defines the related dom event - */ - event) { - this.type = type; - this.event = event; - } -} -/** - * This class is used to store pointer related info for the onPrePointerObservable event. - * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable - */ -class PointerInfoPre extends PointerInfoBase { - /** - * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event. - * @param type Defines the type of event (PointerEventTypes) - * @param event Defines the related dom event - * @param localX Defines the local x coordinates of the pointer when the event occured - * @param localY Defines the local y coordinates of the pointer when the event occured - */ - constructor(type, event, localX, localY) { - super(type, event); - /** - * Ray from a pointer if available (eg. 6dof controller) - */ - this.ray = null; - /** - * The original picking info that was used to trigger the pointer event - */ - this.originalPickingInfo = null; - this.skipOnPointerObservable = false; - this.localPosition = new math_vector_Vector2(localX, localY); - } -} -/** - * This type contains all the data related to a pointer event in Babylon.js. - * 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. - */ -class PointerInfo extends PointerInfoBase { - /** - * Defines the picking info associated with this PointerInfo object (if applicable) - */ - get pickInfo() { - if (!this._pickInfo) { - this._generatePickInfo(); - } - return this._pickInfo; - } - /** - * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event. - * @param type Defines the type of event (PointerEventTypes) - * @param event Defines the related dom event - * @param pickInfo Defines the picking info associated to the info (if any) - * @param inputManager Defines the InputManager to use if there is no pickInfo - */ - constructor(type, event, pickInfo, inputManager = null) { - super(type, event); - this._pickInfo = pickInfo; - this._inputManager = inputManager; - } - /** - * Generates the picking info if needed - */ - /** @internal */ - _generatePickInfo() { - if (this._inputManager) { - this._pickInfo = this._inputManager._pickMove(this.event); - this._inputManager._setRayOnPointerInfo(this._pickInfo, this.event); - this._inputManager = null; - } - } -} -//# sourceMappingURL=pointerEvents.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Events/keyboardEvents.js -/** - * Gather the list of keyboard event types as constants. - */ -class KeyboardEventTypes { -} -/** - * The keydown event is fired when a key becomes active (pressed). - */ -KeyboardEventTypes.KEYDOWN = 0x01; -/** - * The keyup event is fired when a key has been released. - */ -KeyboardEventTypes.KEYUP = 0x02; -/** - * This class is used to store keyboard related info for the onKeyboardObservable event. - */ -class KeyboardInfo { - /** - * Instantiates a new keyboard info. - * This class is used to store keyboard related info for the onKeyboardObservable event. - * @param type Defines the type of event (KeyboardEventTypes) - * @param event Defines the related dom event - */ - constructor( - /** - * Defines the type of event (KeyboardEventTypes) - */ - type, - /** - * Defines the related dom event - */ - event) { - this.type = type; - this.event = event; - } -} -/** - * This class is used to store keyboard related info for the onPreKeyboardObservable event. - * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable - */ -class KeyboardInfoPre extends KeyboardInfo { - /** - * Defines whether the engine should skip the next onKeyboardObservable associated to this pre. - * @deprecated use skipOnKeyboardObservable property instead - */ - get skipOnPointerObservable() { - return this.skipOnKeyboardObservable; - } - set skipOnPointerObservable(value) { - this.skipOnKeyboardObservable = value; - } - /** - * Instantiates a new keyboard pre info. - * This class is used to store keyboard related info for the onPreKeyboardObservable event. - * @param type Defines the type of event (KeyboardEventTypes) - * @param event Defines the related dom event - */ - constructor( - /** - * Defines the type of event (KeyboardEventTypes) - */ - type, - /** - * Defines the related dom event - */ - event) { - super(type, event); - this.type = type; - this.event = event; - this.skipOnKeyboardObservable = false; - } -} -//# sourceMappingURL=keyboardEvents.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceEnums.js -/** - * Enum for Device Types - */ -var DeviceType; -(function (DeviceType) { - /** Generic */ - DeviceType[DeviceType["Generic"] = 0] = "Generic"; - /** Keyboard */ - DeviceType[DeviceType["Keyboard"] = 1] = "Keyboard"; - /** Mouse */ - DeviceType[DeviceType["Mouse"] = 2] = "Mouse"; - /** Touch Pointers */ - DeviceType[DeviceType["Touch"] = 3] = "Touch"; - /** PS4 Dual Shock */ - DeviceType[DeviceType["DualShock"] = 4] = "DualShock"; - /** Xbox */ - DeviceType[DeviceType["Xbox"] = 5] = "Xbox"; - /** Switch Controller */ - DeviceType[DeviceType["Switch"] = 6] = "Switch"; - /** PS5 DualSense */ - DeviceType[DeviceType["DualSense"] = 7] = "DualSense"; -})(DeviceType || (DeviceType = {})); -// Device Enums -/** - * Enum for All Pointers (Touch/Mouse) - */ -var PointerInput; -(function (PointerInput) { - /** Horizontal Axis (Not used in events/observables; only in polling) */ - PointerInput[PointerInput["Horizontal"] = 0] = "Horizontal"; - /** Vertical Axis (Not used in events/observables; only in polling) */ - PointerInput[PointerInput["Vertical"] = 1] = "Vertical"; - /** Left Click or Touch */ - PointerInput[PointerInput["LeftClick"] = 2] = "LeftClick"; - /** Middle Click */ - PointerInput[PointerInput["MiddleClick"] = 3] = "MiddleClick"; - /** Right Click */ - PointerInput[PointerInput["RightClick"] = 4] = "RightClick"; - /** Browser Back */ - PointerInput[PointerInput["BrowserBack"] = 5] = "BrowserBack"; - /** Browser Forward */ - PointerInput[PointerInput["BrowserForward"] = 6] = "BrowserForward"; - /** Mouse Wheel X */ - PointerInput[PointerInput["MouseWheelX"] = 7] = "MouseWheelX"; - /** Mouse Wheel Y */ - PointerInput[PointerInput["MouseWheelY"] = 8] = "MouseWheelY"; - /** Mouse Wheel Z */ - PointerInput[PointerInput["MouseWheelZ"] = 9] = "MouseWheelZ"; - /** Used in events/observables to identify if x/y changes occurred */ - PointerInput[PointerInput["Move"] = 12] = "Move"; -})(PointerInput || (PointerInput = {})); -/** @internal */ -var NativePointerInput; -(function (NativePointerInput) { - /** Horizontal Axis */ - NativePointerInput[NativePointerInput["Horizontal"] = 0] = "Horizontal"; - /** Vertical Axis */ - NativePointerInput[NativePointerInput["Vertical"] = 1] = "Vertical"; - /** Left Click or Touch */ - NativePointerInput[NativePointerInput["LeftClick"] = 2] = "LeftClick"; - /** Middle Click */ - NativePointerInput[NativePointerInput["MiddleClick"] = 3] = "MiddleClick"; - /** Right Click */ - NativePointerInput[NativePointerInput["RightClick"] = 4] = "RightClick"; - /** Browser Back */ - NativePointerInput[NativePointerInput["BrowserBack"] = 5] = "BrowserBack"; - /** Browser Forward */ - NativePointerInput[NativePointerInput["BrowserForward"] = 6] = "BrowserForward"; - /** Mouse Wheel X */ - NativePointerInput[NativePointerInput["MouseWheelX"] = 7] = "MouseWheelX"; - /** Mouse Wheel Y */ - NativePointerInput[NativePointerInput["MouseWheelY"] = 8] = "MouseWheelY"; - /** Mouse Wheel Z */ - NativePointerInput[NativePointerInput["MouseWheelZ"] = 9] = "MouseWheelZ"; - /** Delta X */ - NativePointerInput[NativePointerInput["DeltaHorizontal"] = 10] = "DeltaHorizontal"; - /** Delta Y */ - NativePointerInput[NativePointerInput["DeltaVertical"] = 11] = "DeltaVertical"; -})(NativePointerInput || (NativePointerInput = {})); -/** - * Enum for Dual Shock Gamepad - */ -var DualShockInput; -(function (DualShockInput) { - /** Cross */ - DualShockInput[DualShockInput["Cross"] = 0] = "Cross"; - /** Circle */ - DualShockInput[DualShockInput["Circle"] = 1] = "Circle"; - /** Square */ - DualShockInput[DualShockInput["Square"] = 2] = "Square"; - /** Triangle */ - DualShockInput[DualShockInput["Triangle"] = 3] = "Triangle"; - /** L1 */ - DualShockInput[DualShockInput["L1"] = 4] = "L1"; - /** R1 */ - DualShockInput[DualShockInput["R1"] = 5] = "R1"; - /** L2 */ - DualShockInput[DualShockInput["L2"] = 6] = "L2"; - /** R2 */ - DualShockInput[DualShockInput["R2"] = 7] = "R2"; - /** Share */ - DualShockInput[DualShockInput["Share"] = 8] = "Share"; - /** Options */ - DualShockInput[DualShockInput["Options"] = 9] = "Options"; - /** L3 */ - DualShockInput[DualShockInput["L3"] = 10] = "L3"; - /** R3 */ - DualShockInput[DualShockInput["R3"] = 11] = "R3"; - /** DPadUp */ - DualShockInput[DualShockInput["DPadUp"] = 12] = "DPadUp"; - /** DPadDown */ - DualShockInput[DualShockInput["DPadDown"] = 13] = "DPadDown"; - /** DPadLeft */ - DualShockInput[DualShockInput["DPadLeft"] = 14] = "DPadLeft"; - /** DRight */ - DualShockInput[DualShockInput["DPadRight"] = 15] = "DPadRight"; - /** Home */ - DualShockInput[DualShockInput["Home"] = 16] = "Home"; - /** TouchPad */ - DualShockInput[DualShockInput["TouchPad"] = 17] = "TouchPad"; - /** LStickXAxis */ - DualShockInput[DualShockInput["LStickXAxis"] = 18] = "LStickXAxis"; - /** LStickYAxis */ - DualShockInput[DualShockInput["LStickYAxis"] = 19] = "LStickYAxis"; - /** RStickXAxis */ - DualShockInput[DualShockInput["RStickXAxis"] = 20] = "RStickXAxis"; - /** RStickYAxis */ - DualShockInput[DualShockInput["RStickYAxis"] = 21] = "RStickYAxis"; -})(DualShockInput || (DualShockInput = {})); -/** - * Enum for Dual Sense Gamepad - */ -var DualSenseInput; -(function (DualSenseInput) { - /** Cross */ - DualSenseInput[DualSenseInput["Cross"] = 0] = "Cross"; - /** Circle */ - DualSenseInput[DualSenseInput["Circle"] = 1] = "Circle"; - /** Square */ - DualSenseInput[DualSenseInput["Square"] = 2] = "Square"; - /** Triangle */ - DualSenseInput[DualSenseInput["Triangle"] = 3] = "Triangle"; - /** L1 */ - DualSenseInput[DualSenseInput["L1"] = 4] = "L1"; - /** R1 */ - DualSenseInput[DualSenseInput["R1"] = 5] = "R1"; - /** L2 */ - DualSenseInput[DualSenseInput["L2"] = 6] = "L2"; - /** R2 */ - DualSenseInput[DualSenseInput["R2"] = 7] = "R2"; - /** Create */ - DualSenseInput[DualSenseInput["Create"] = 8] = "Create"; - /** Options */ - DualSenseInput[DualSenseInput["Options"] = 9] = "Options"; - /** L3 */ - DualSenseInput[DualSenseInput["L3"] = 10] = "L3"; - /** R3 */ - DualSenseInput[DualSenseInput["R3"] = 11] = "R3"; - /** DPadUp */ - DualSenseInput[DualSenseInput["DPadUp"] = 12] = "DPadUp"; - /** DPadDown */ - DualSenseInput[DualSenseInput["DPadDown"] = 13] = "DPadDown"; - /** DPadLeft */ - DualSenseInput[DualSenseInput["DPadLeft"] = 14] = "DPadLeft"; - /** DRight */ - DualSenseInput[DualSenseInput["DPadRight"] = 15] = "DPadRight"; - /** Home */ - DualSenseInput[DualSenseInput["Home"] = 16] = "Home"; - /** TouchPad */ - DualSenseInput[DualSenseInput["TouchPad"] = 17] = "TouchPad"; - /** LStickXAxis */ - DualSenseInput[DualSenseInput["LStickXAxis"] = 18] = "LStickXAxis"; - /** LStickYAxis */ - DualSenseInput[DualSenseInput["LStickYAxis"] = 19] = "LStickYAxis"; - /** RStickXAxis */ - DualSenseInput[DualSenseInput["RStickXAxis"] = 20] = "RStickXAxis"; - /** RStickYAxis */ - DualSenseInput[DualSenseInput["RStickYAxis"] = 21] = "RStickYAxis"; -})(DualSenseInput || (DualSenseInput = {})); -/** - * Enum for Xbox Gamepad - */ -var XboxInput; -(function (XboxInput) { - /** A */ - XboxInput[XboxInput["A"] = 0] = "A"; - /** B */ - XboxInput[XboxInput["B"] = 1] = "B"; - /** X */ - XboxInput[XboxInput["X"] = 2] = "X"; - /** Y */ - XboxInput[XboxInput["Y"] = 3] = "Y"; - /** LB */ - XboxInput[XboxInput["LB"] = 4] = "LB"; - /** RB */ - XboxInput[XboxInput["RB"] = 5] = "RB"; - /** LT */ - XboxInput[XboxInput["LT"] = 6] = "LT"; - /** RT */ - XboxInput[XboxInput["RT"] = 7] = "RT"; - /** Back */ - XboxInput[XboxInput["Back"] = 8] = "Back"; - /** Start */ - XboxInput[XboxInput["Start"] = 9] = "Start"; - /** LS */ - XboxInput[XboxInput["LS"] = 10] = "LS"; - /** RS */ - XboxInput[XboxInput["RS"] = 11] = "RS"; - /** DPadUp */ - XboxInput[XboxInput["DPadUp"] = 12] = "DPadUp"; - /** DPadDown */ - XboxInput[XboxInput["DPadDown"] = 13] = "DPadDown"; - /** DPadLeft */ - XboxInput[XboxInput["DPadLeft"] = 14] = "DPadLeft"; - /** DRight */ - XboxInput[XboxInput["DPadRight"] = 15] = "DPadRight"; - /** Home */ - XboxInput[XboxInput["Home"] = 16] = "Home"; - /** LStickXAxis */ - XboxInput[XboxInput["LStickXAxis"] = 17] = "LStickXAxis"; - /** LStickYAxis */ - XboxInput[XboxInput["LStickYAxis"] = 18] = "LStickYAxis"; - /** RStickXAxis */ - XboxInput[XboxInput["RStickXAxis"] = 19] = "RStickXAxis"; - /** RStickYAxis */ - XboxInput[XboxInput["RStickYAxis"] = 20] = "RStickYAxis"; -})(XboxInput || (XboxInput = {})); -/** - * Enum for Switch (Pro/JoyCon L+R) Gamepad - */ -var SwitchInput; -(function (SwitchInput) { - /** B */ - SwitchInput[SwitchInput["B"] = 0] = "B"; - /** A */ - SwitchInput[SwitchInput["A"] = 1] = "A"; - /** Y */ - SwitchInput[SwitchInput["Y"] = 2] = "Y"; - /** X */ - SwitchInput[SwitchInput["X"] = 3] = "X"; - /** L */ - SwitchInput[SwitchInput["L"] = 4] = "L"; - /** R */ - SwitchInput[SwitchInput["R"] = 5] = "R"; - /** ZL */ - SwitchInput[SwitchInput["ZL"] = 6] = "ZL"; - /** ZR */ - SwitchInput[SwitchInput["ZR"] = 7] = "ZR"; - /** Minus */ - SwitchInput[SwitchInput["Minus"] = 8] = "Minus"; - /** Plus */ - SwitchInput[SwitchInput["Plus"] = 9] = "Plus"; - /** LS */ - SwitchInput[SwitchInput["LS"] = 10] = "LS"; - /** RS */ - SwitchInput[SwitchInput["RS"] = 11] = "RS"; - /** DPadUp */ - SwitchInput[SwitchInput["DPadUp"] = 12] = "DPadUp"; - /** DPadDown */ - SwitchInput[SwitchInput["DPadDown"] = 13] = "DPadDown"; - /** DPadLeft */ - SwitchInput[SwitchInput["DPadLeft"] = 14] = "DPadLeft"; - /** DRight */ - SwitchInput[SwitchInput["DPadRight"] = 15] = "DPadRight"; - /** Home */ - SwitchInput[SwitchInput["Home"] = 16] = "Home"; - /** Capture */ - SwitchInput[SwitchInput["Capture"] = 17] = "Capture"; - /** LStickXAxis */ - SwitchInput[SwitchInput["LStickXAxis"] = 18] = "LStickXAxis"; - /** LStickYAxis */ - SwitchInput[SwitchInput["LStickYAxis"] = 19] = "LStickYAxis"; - /** RStickXAxis */ - SwitchInput[SwitchInput["RStickXAxis"] = 20] = "RStickXAxis"; - /** RStickYAxis */ - SwitchInput[SwitchInput["RStickYAxis"] = 21] = "RStickYAxis"; -})(SwitchInput || (SwitchInput = {})); -//# sourceMappingURL=deviceEnums.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Events/deviceInputEvents.js -/** - * Event Types - */ -var DeviceInputEventType; -(function (DeviceInputEventType) { - // Pointers - /** PointerMove */ - DeviceInputEventType[DeviceInputEventType["PointerMove"] = 0] = "PointerMove"; - /** PointerDown */ - DeviceInputEventType[DeviceInputEventType["PointerDown"] = 1] = "PointerDown"; - /** PointerUp */ - DeviceInputEventType[DeviceInputEventType["PointerUp"] = 2] = "PointerUp"; -})(DeviceInputEventType || (DeviceInputEventType = {})); -/** - * Constants used for Events - */ -class EventConstants { -} -/** - * Pixel delta for Wheel Events (Default) - */ -EventConstants.DOM_DELTA_PIXEL = 0x00; -/** - * Line delta for Wheel Events - */ -EventConstants.DOM_DELTA_LINE = 0x01; -/** - * Page delta for Wheel Events - */ -EventConstants.DOM_DELTA_PAGE = 0x02; -//# sourceMappingURL=deviceInputEvents.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/DeviceInput/eventFactory.js - - - -/** - * Class to wrap DeviceInputSystem data into an event object - */ -class DeviceEventFactory { - /** - * Create device input events based on provided type and slot - * - * @param deviceType Type of device - * @param deviceSlot "Slot" or index that device is referenced in - * @param inputIndex Id of input to be checked - * @param currentState Current value for given input - * @param deviceInputSystem Reference to DeviceInputSystem - * @param elementToAttachTo HTMLElement to reference as target for inputs - * @returns IUIEvent object - */ - static CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) { - switch (deviceType) { - case DeviceType.Keyboard: - return this._CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo); - case DeviceType.Mouse: - if (inputIndex === PointerInput.MouseWheelX || inputIndex === PointerInput.MouseWheelY || inputIndex === PointerInput.MouseWheelZ) { - return this._CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo); - } - // eslint-disable-next-line no-fallthrough - case DeviceType.Touch: - return this._CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId); - default: - throw `Unable to generate event for device ${DeviceType[deviceType]}`; - } - } - /** - * Creates pointer event - * - * @param deviceType Type of device - * @param deviceSlot "Slot" or index that device is referenced in - * @param inputIndex Id of input to be checked - * @param currentState Current value for given input - * @param deviceInputSystem Reference to DeviceInputSystem - * @param elementToAttachTo HTMLElement to reference as target for inputs - * @returns IUIEvent object (Pointer) - */ - static _CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) { - const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo); - if (deviceType === DeviceType.Mouse) { - evt.deviceType = DeviceType.Mouse; - evt.pointerId = 1; - evt.pointerType = "mouse"; - } - else { - evt.deviceType = DeviceType.Touch; - evt.pointerId = pointerId !== null && pointerId !== void 0 ? pointerId : deviceSlot; - evt.pointerType = "touch"; - } - let buttons = 0; - // Populate buttons property with current state of all mouse buttons - // Uses values found on: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons - buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.LeftClick); - buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.RightClick) * 2; - buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.MiddleClick) * 4; - evt.buttons = buttons; - if (inputIndex === PointerInput.Move) { - evt.type = "pointermove"; - } - else if (inputIndex >= PointerInput.LeftClick && inputIndex <= PointerInput.RightClick) { - evt.type = currentState === 1 ? "pointerdown" : "pointerup"; - evt.button = inputIndex - 2; - } - return evt; - } - /** - * Create Mouse Wheel Event - * @param deviceType Type of device - * @param deviceSlot "Slot" or index that device is referenced in - * @param inputIndex Id of input to be checked - * @param currentState Current value for given input - * @param deviceInputSystem Reference to DeviceInputSystem - * @param elementToAttachTo HTMLElement to reference as target for inputs - * @returns IUIEvent object (Wheel) - */ - static _CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) { - const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo); - // While WheelEvents don't generally have a pointerId, we used to add one in the InputManager - // This line has been added to make the InputManager more platform-agnostic - // Similar code exists in the WebDeviceInputSystem to handle browser created events - evt.pointerId = 1; - evt.type = "wheel"; - evt.deltaMode = EventConstants.DOM_DELTA_PIXEL; - evt.deltaX = 0; - evt.deltaY = 0; - evt.deltaZ = 0; - switch (inputIndex) { - case PointerInput.MouseWheelX: - evt.deltaX = currentState; - break; - case PointerInput.MouseWheelY: - evt.deltaY = currentState; - break; - case PointerInput.MouseWheelZ: - evt.deltaZ = currentState; - break; - } - return evt; - } - /** - * Create Mouse Event - * @param deviceType Type of device - * @param deviceSlot "Slot" or index that device is referenced in - * @param inputIndex Id of input to be checked - * @param currentState Current value for given input - * @param deviceInputSystem Reference to DeviceInputSystem - * @param elementToAttachTo HTMLElement to reference as target for inputs - * @returns IUIEvent object (Mouse) - */ - static _CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) { - const evt = this._CreateEvent(elementToAttachTo); - const pointerX = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Horizontal); - const pointerY = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Vertical); - // Handle offsets/deltas based on existence of HTMLElement - if (elementToAttachTo) { - evt.movementX = 0; - evt.movementY = 0; - evt.offsetX = evt.movementX - elementToAttachTo.getBoundingClientRect().x; - evt.offsetY = evt.movementY - elementToAttachTo.getBoundingClientRect().y; - } - else { - evt.movementX = deviceInputSystem.pollInput(deviceType, deviceSlot, NativePointerInput.DeltaHorizontal); // DeltaHorizontal - evt.movementY = deviceInputSystem.pollInput(deviceType, deviceSlot, NativePointerInput.DeltaVertical); // DeltaVertical - evt.offsetX = 0; - evt.offsetY = 0; - } - this._CheckNonCharacterKeys(evt, deviceInputSystem); - evt.clientX = pointerX; - evt.clientY = pointerY; - evt.x = pointerX; - evt.y = pointerY; - evt.deviceType = deviceType; - evt.deviceSlot = deviceSlot; - evt.inputIndex = inputIndex; - return evt; - } - /** - * Create Keyboard Event - * @param inputIndex Id of input to be checked - * @param currentState Current value for given input - * @param deviceInputSystem Reference to DeviceInputSystem - * @param elementToAttachTo HTMLElement to reference as target for inputs - * @returns IEvent object (Keyboard) - */ - static _CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo) { - const evt = this._CreateEvent(elementToAttachTo); - this._CheckNonCharacterKeys(evt, deviceInputSystem); - evt.deviceType = DeviceType.Keyboard; - evt.deviceSlot = 0; - evt.inputIndex = inputIndex; - evt.type = currentState === 1 ? "keydown" : "keyup"; - evt.key = String.fromCharCode(inputIndex); - evt.keyCode = inputIndex; - return evt; - } - /** - * Add parameters for non-character keys (Ctrl, Alt, Meta, Shift) - * @param evt Event object to add parameters to - * @param deviceInputSystem DeviceInputSystem to pull values from - */ - static _CheckNonCharacterKeys(evt, deviceInputSystem) { - const isKeyboardActive = deviceInputSystem.isDeviceAvailable(DeviceType.Keyboard); - const altKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 18) === 1; - const ctrlKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 17) === 1; - const metaKey = isKeyboardActive && - (deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 91) === 1 || - deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 92) === 1 || - deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 93) === 1); - const shiftKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 16) === 1; - evt.altKey = altKey; - evt.ctrlKey = ctrlKey; - evt.metaKey = metaKey; - evt.shiftKey = shiftKey; - } - /** - * Create base event object - * @param elementToAttachTo Value to use as event target - * @returns - */ - static _CreateEvent(elementToAttachTo) { - const evt = {}; - evt.preventDefault = () => { }; - evt.target = elementToAttachTo; - return evt; - } -} -//# sourceMappingURL=eventFactory.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/DeviceInput/nativeDeviceInputSystem.js - - -/** @internal */ -class NativeDeviceInputSystem { - constructor(onDeviceConnected, onDeviceDisconnected, onInputChanged) { - this._nativeInput = _native.DeviceInputSystem - ? new _native.DeviceInputSystem(onDeviceConnected, onDeviceDisconnected, (deviceType, deviceSlot, inputIndex, currentState) => { - const evt = DeviceEventFactory.CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, this); - onInputChanged(deviceType, deviceSlot, evt); - }) - : this._createDummyNativeInput(); - } - // Public functions - /** - * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized. - * @param deviceType Enum specifying device type - * @param deviceSlot "Slot" or index that device is referenced in - * @param inputIndex Id of input to be checked - * @returns Current value of input - */ - pollInput(deviceType, deviceSlot, inputIndex) { - return this._nativeInput.pollInput(deviceType, deviceSlot, inputIndex); - } - /** - * Check for a specific device in the DeviceInputSystem - * @param deviceType Type of device to check for - * @returns bool with status of device's existence - */ - isDeviceAvailable(deviceType) { - //TODO: FIx native side first - return deviceType === DeviceType.Mouse || deviceType === DeviceType.Touch; - } - /** - * Dispose of all the observables - */ - dispose() { - this._nativeInput.dispose(); - } - /** - * For versions of BabylonNative that don't have the NativeInput plugin initialized, create a dummy version - * @returns Object with dummy functions - */ - _createDummyNativeInput() { - const nativeInput = { - pollInput: () => { - return 0; - }, - isDeviceAvailable: () => { - return false; - }, - dispose: () => { }, - }; - return nativeInput; - } -} -//# sourceMappingURL=nativeDeviceInputSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/DeviceInput/webDeviceInputSystem.js - - - - -// eslint-disable-next-line @typescript-eslint/naming-convention -const MAX_KEYCODES = 255; -// eslint-disable-next-line @typescript-eslint/naming-convention -const MAX_POINTER_INPUTS = Object.keys(PointerInput).length / 2; -/** @internal */ -class WebDeviceInputSystem { - constructor(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged) { - // Private Members - this._inputs = []; - this._keyboardActive = false; - this._pointerActive = false; - this._usingSafari = tools_Tools.IsSafari(); - // Found solution for determining if MacOS is being used here: - // https://stackoverflow.com/questions/10527983/best-way-to-detect-mac-os-x-or-windows-computers-with-javascript-or-jquery - this._usingMacOS = IsNavigatorAvailable() && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform); - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._keyboardDownEvent = (evt) => { }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._keyboardUpEvent = (evt) => { }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._keyboardBlurEvent = (evt) => { }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._pointerMoveEvent = (evt) => { }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._pointerDownEvent = (evt) => { }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._pointerUpEvent = (evt) => { }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._pointerCancelEvent = (evt) => { }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._pointerWheelEvent = (evt) => { }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._pointerBlurEvent = (evt) => { }; - this._eventsAttached = false; - this._mouseId = -1; - this._isUsingFirefox = IsNavigatorAvailable() && navigator.userAgent && navigator.userAgent.indexOf("Firefox") !== -1; - this._maxTouchPoints = 0; - this._pointerInputClearObserver = null; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._gamepadConnectedEvent = (evt) => { }; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._gamepadDisconnectedEvent = (evt) => { }; - this._eventPrefix = tools_Tools.GetPointerPrefix(engine); - this._engine = engine; - this._onDeviceConnected = onDeviceConnected; - this._onDeviceDisconnected = onDeviceDisconnected; - this._onInputChanged = onInputChanged; - // If we need a pointerId, set one for future use - this._mouseId = this._isUsingFirefox ? 0 : 1; - this._enableEvents(); - if (this._usingMacOS) { - this._metaKeys = []; - } - // Set callback to enable event handler switching when inputElement changes - if (!this._engine._onEngineViewChanged) { - this._engine._onEngineViewChanged = () => { - this._enableEvents(); - }; - } - } - // Public functions - /** - * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized. - * @param deviceType Enum specifying device type - * @param deviceSlot "Slot" or index that device is referenced in - * @param inputIndex Id of input to be checked - * @returns Current value of input - */ - pollInput(deviceType, deviceSlot, inputIndex) { - const device = this._inputs[deviceType][deviceSlot]; - if (!device) { - throw `Unable to find device ${DeviceType[deviceType]}`; - } - if (deviceType >= DeviceType.DualShock && deviceType <= DeviceType.DualSense) { - this._updateDevice(deviceType, deviceSlot, inputIndex); - } - const currentValue = device[inputIndex]; - if (currentValue === undefined) { - throw `Unable to find input ${inputIndex} for device ${DeviceType[deviceType]} in slot ${deviceSlot}`; - } - if (inputIndex === PointerInput.Move) { - tools_Tools.Warn(`Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data.`); - } - return currentValue; - } - /** - * Check for a specific device in the DeviceInputSystem - * @param deviceType Type of device to check for - * @returns bool with status of device's existence - */ - isDeviceAvailable(deviceType) { - return this._inputs[deviceType] !== undefined; - } - /** - * Dispose of all the eventlisteners - */ - dispose() { - // Callbacks - this._onDeviceConnected = () => { }; - this._onDeviceDisconnected = () => { }; - this._onInputChanged = () => { }; - delete this._engine._onEngineViewChanged; - if (this._elementToAttachTo) { - this._disableEvents(); - } - } - /** - * Enable listening for user input events - */ - _enableEvents() { - const inputElement = this === null || this === void 0 ? void 0 : this._engine.getInputElement(); - if (inputElement && (!this._eventsAttached || this._elementToAttachTo !== inputElement)) { - // Remove events before adding to avoid double events or simultaneous events on multiple canvases - this._disableEvents(); - // If the inputs array has already been created, zero it out to before setting up events - if (this._inputs) { - for (const inputs of this._inputs) { - if (inputs) { - for (const deviceSlotKey in inputs) { - const deviceSlot = +deviceSlotKey; - const device = inputs[deviceSlot]; - if (device) { - for (let inputIndex = 0; inputIndex < device.length; inputIndex++) { - device[inputIndex] = 0; - } - } - } - } - } - } - this._elementToAttachTo = inputElement; - // Set tab index for the inputElement to the engine's canvasTabIndex, if and only if the element's tab index is -1 - this._elementToAttachTo.tabIndex = this._elementToAttachTo.tabIndex !== -1 ? this._elementToAttachTo.tabIndex : this._engine.canvasTabIndex; - this._handleKeyActions(); - this._handlePointerActions(); - this._handleGamepadActions(); - this._eventsAttached = true; - // Check for devices that are already connected but aren't registered. Currently, only checks for gamepads and mouse - this._checkForConnectedDevices(); - } - } - /** - * Disable listening for user input events - */ - _disableEvents() { - if (this._elementToAttachTo) { - // Blur Events - this._elementToAttachTo.removeEventListener("blur", this._keyboardBlurEvent); - this._elementToAttachTo.removeEventListener("blur", this._pointerBlurEvent); - // Keyboard Events - this._elementToAttachTo.removeEventListener("keydown", this._keyboardDownEvent); - this._elementToAttachTo.removeEventListener("keyup", this._keyboardUpEvent); - // Pointer Events - this._elementToAttachTo.removeEventListener(this._eventPrefix + "move", this._pointerMoveEvent); - this._elementToAttachTo.removeEventListener(this._eventPrefix + "down", this._pointerDownEvent); - this._elementToAttachTo.removeEventListener(this._eventPrefix + "up", this._pointerUpEvent); - this._elementToAttachTo.removeEventListener(this._eventPrefix + "cancel", this._pointerCancelEvent); - this._elementToAttachTo.removeEventListener(this._wheelEventName, this._pointerWheelEvent); - // Gamepad Events - window.removeEventListener("gamepadconnected", this._gamepadConnectedEvent); - window.removeEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent); - } - if (this._pointerInputClearObserver) { - this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver); - } - this._eventsAttached = false; - } - /** - * Checks for existing connections to devices and register them, if necessary - * Currently handles gamepads and mouse - */ - _checkForConnectedDevices() { - if (navigator.getGamepads) { - const gamepads = navigator.getGamepads(); - for (const gamepad of gamepads) { - if (gamepad) { - this._addGamePad(gamepad); - } - } - } - // If the device in use has mouse capabilities, pre-register mouse - if (typeof matchMedia === "function" && matchMedia("(pointer:fine)").matches) { - // This will provide a dummy value for the cursor position and is expected to be overridden when the first mouse event happens. - // There isn't any good way to get the current position outside of a pointer event so that's why this was done. - this._addPointerDevice(DeviceType.Mouse, 0, 0, 0); - } - } - // Private functions - /** - * Add a gamepad to the DeviceInputSystem - * @param gamepad A single DOM Gamepad object - */ - _addGamePad(gamepad) { - const deviceType = this._getGamepadDeviceType(gamepad.id); - const deviceSlot = gamepad.index; - this._gamepads = this._gamepads || new Array(gamepad.index + 1); - this._registerDevice(deviceType, deviceSlot, gamepad.buttons.length + gamepad.axes.length); - this._gamepads[deviceSlot] = deviceType; - } - /** - * Add pointer device to DeviceInputSystem - * @param deviceType Type of Pointer to add - * @param deviceSlot Pointer ID (0 for mouse, pointerId for Touch) - * @param currentX Current X at point of adding - * @param currentY Current Y at point of adding - */ - _addPointerDevice(deviceType, deviceSlot, currentX, currentY) { - if (!this._pointerActive) { - this._pointerActive = true; - } - this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS); - const pointer = this._inputs[deviceType][deviceSlot]; /* initialize our pointer position immediately after registration */ - pointer[0] = currentX; - pointer[1] = currentY; - } - /** - * Add device and inputs to device array - * @param deviceType Enum specifying device type - * @param deviceSlot "Slot" or index that device is referenced in - * @param numberOfInputs Number of input entries to create for given device - */ - _registerDevice(deviceType, deviceSlot, numberOfInputs) { - if (deviceSlot === undefined) { - throw `Unable to register device ${DeviceType[deviceType]} to undefined slot.`; - } - if (!this._inputs[deviceType]) { - this._inputs[deviceType] = {}; - } - if (!this._inputs[deviceType][deviceSlot]) { - const device = new Array(numberOfInputs); - device.fill(0); - this._inputs[deviceType][deviceSlot] = device; - this._onDeviceConnected(deviceType, deviceSlot); - } - } - /** - * Given a specific device name, remove that device from the device map - * @param deviceType Enum specifying device type - * @param deviceSlot "Slot" or index that device is referenced in - */ - _unregisterDevice(deviceType, deviceSlot) { - if (this._inputs[deviceType][deviceSlot]) { - delete this._inputs[deviceType][deviceSlot]; - this._onDeviceDisconnected(deviceType, deviceSlot); - } - } - /** - * Handle all actions that come from keyboard interaction - */ - _handleKeyActions() { - this._keyboardDownEvent = (evt) => { - if (!this._keyboardActive) { - this._keyboardActive = true; - this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES); - } - const kbKey = this._inputs[DeviceType.Keyboard][0]; - if (kbKey) { - kbKey[evt.keyCode] = 1; - const deviceEvent = evt; - deviceEvent.inputIndex = evt.keyCode; - if (this._usingMacOS && evt.metaKey && evt.key !== "Meta") { - if (!this._metaKeys.includes(evt.keyCode)) { - this._metaKeys.push(evt.keyCode); - } - } - this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); - } - }; - this._keyboardUpEvent = (evt) => { - if (!this._keyboardActive) { - this._keyboardActive = true; - this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES); - } - const kbKey = this._inputs[DeviceType.Keyboard][0]; - if (kbKey) { - kbKey[evt.keyCode] = 0; - const deviceEvent = evt; - deviceEvent.inputIndex = evt.keyCode; - if (this._usingMacOS && evt.key === "Meta" && this._metaKeys.length > 0) { - for (const keyCode of this._metaKeys) { - const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, keyCode, 0, this, this._elementToAttachTo); - kbKey[keyCode] = 0; - this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); - } - this._metaKeys.splice(0, this._metaKeys.length); - } - this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); - } - }; - this._keyboardBlurEvent = () => { - if (this._keyboardActive) { - const kbKey = this._inputs[DeviceType.Keyboard][0]; - for (let i = 0; i < kbKey.length; i++) { - if (kbKey[i] !== 0) { - kbKey[i] = 0; - const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, i, 0, this, this._elementToAttachTo); - this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); - } - } - if (this._usingMacOS) { - this._metaKeys.splice(0, this._metaKeys.length); - } - } - }; - this._elementToAttachTo.addEventListener("keydown", this._keyboardDownEvent); - this._elementToAttachTo.addEventListener("keyup", this._keyboardUpEvent); - this._elementToAttachTo.addEventListener("blur", this._keyboardBlurEvent); - } - /** - * Handle all actions that come from pointer interaction - */ - _handlePointerActions() { - // If maxTouchPoints is defined, use that value. Otherwise, allow for a minimum for supported gestures like pinch - this._maxTouchPoints = (IsNavigatorAvailable() && navigator.maxTouchPoints) || 2; - if (!this._activeTouchIds) { - this._activeTouchIds = new Array(this._maxTouchPoints); - } - for (let i = 0; i < this._maxTouchPoints; i++) { - this._activeTouchIds[i] = -1; - } - this._pointerMoveEvent = (evt) => { - const deviceType = this._getPointerType(evt); - let deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId); - // In the event that we're gettting pointermove events from touch inputs that we aren't tracking, - // look for an available slot and retroactively connect it. - if (deviceType === DeviceType.Touch && deviceSlot === -1) { - const idx = this._activeTouchIds.indexOf(-1); - if (idx >= 0) { - deviceSlot = idx; - this._activeTouchIds[idx] = evt.pointerId; - // Because this is a "new" input, inform the connected callback - this._onDeviceConnected(deviceType, deviceSlot); - } - else { - // We can't find an open slot to store new pointer so just return (can only support max number of touches) - tools_Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`); - return; - } - } - if (!this._inputs[deviceType]) { - this._inputs[deviceType] = {}; - } - if (!this._inputs[deviceType][deviceSlot]) { - this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY); - } - const pointer = this._inputs[deviceType][deviceSlot]; - if (pointer) { - const deviceEvent = evt; - deviceEvent.inputIndex = PointerInput.Move; - pointer[PointerInput.Horizontal] = evt.clientX; - pointer[PointerInput.Vertical] = evt.clientY; - // For touches that aren't started with a down, we need to set the button state to 1 - if (deviceType === DeviceType.Touch && pointer[PointerInput.LeftClick] === 0) { - pointer[PointerInput.LeftClick] = 1; - } - if (evt.pointerId === undefined) { - evt.pointerId = this._mouseId; - } - this._onInputChanged(deviceType, deviceSlot, deviceEvent); - // Lets Propagate the event for move with same position. - if (!this._usingSafari && evt.button !== -1) { - deviceEvent.inputIndex = evt.button + 2; - pointer[evt.button + 2] = pointer[evt.button + 2] ? 0 : 1; // Reverse state of button if evt.button has value - this._onInputChanged(deviceType, deviceSlot, deviceEvent); - } - } - }; - this._pointerDownEvent = (evt) => { - const deviceType = this._getPointerType(evt); - let deviceSlot = deviceType === DeviceType.Mouse ? 0 : evt.pointerId; - if (deviceType === DeviceType.Touch) { - const idx = this._activeTouchIds.indexOf(-1); - if (idx >= 0) { - deviceSlot = idx; - this._activeTouchIds[idx] = evt.pointerId; - } - else { - // We can't find an open slot to store new pointer so just return (can only support max number of touches) - tools_Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`); - return; - } - } - if (!this._inputs[deviceType]) { - this._inputs[deviceType] = {}; - } - if (!this._inputs[deviceType][deviceSlot]) { - this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY); - } - else if (deviceType === DeviceType.Touch) { - this._onDeviceConnected(deviceType, deviceSlot); - } - const pointer = this._inputs[deviceType][deviceSlot]; - if (pointer) { - const previousHorizontal = pointer[PointerInput.Horizontal]; - const previousVertical = pointer[PointerInput.Vertical]; - if (deviceType === DeviceType.Mouse) { - // Mouse; Set pointerId if undefined - if (evt.pointerId === undefined) { - evt.pointerId = this._mouseId; - } - if (!document.pointerLockElement) { - try { - this._elementToAttachTo.setPointerCapture(this._mouseId); - } - catch (e) { - // DO NOTHING - } - } - } - else { - // Touch; Since touches are dynamically assigned, only set capture if we have an id - if (evt.pointerId && !document.pointerLockElement) { - try { - this._elementToAttachTo.setPointerCapture(evt.pointerId); - } - catch (e) { - // DO NOTHING - } - } - } - pointer[PointerInput.Horizontal] = evt.clientX; - pointer[PointerInput.Vertical] = evt.clientY; - pointer[evt.button + 2] = 1; - const deviceEvent = evt; - // NOTE: The +2 used here to is because PointerInput has the same value progression for its mouse buttons as PointerEvent.button - // However, we have our X and Y values front-loaded to group together the touch inputs but not break this progression - // EG. ([X, Y, Left-click], Middle-click, etc...) - deviceEvent.inputIndex = evt.button + 2; - this._onInputChanged(deviceType, deviceSlot, deviceEvent); - if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) { - deviceEvent.inputIndex = PointerInput.Move; - this._onInputChanged(deviceType, deviceSlot, deviceEvent); - } - } - }; - this._pointerUpEvent = (evt) => { - var _a, _b, _c, _d, _e; - const deviceType = this._getPointerType(evt); - const deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId); - if (deviceType === DeviceType.Touch) { - // If we're getting a pointerup event for a touch that isn't active, just return. - if (deviceSlot === -1) { - return; - } - else { - this._activeTouchIds[deviceSlot] = -1; - } - } - const pointer = (_a = this._inputs[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot]; - if (pointer && pointer[evt.button + 2] !== 0) { - const previousHorizontal = pointer[PointerInput.Horizontal]; - const previousVertical = pointer[PointerInput.Vertical]; - pointer[PointerInput.Horizontal] = evt.clientX; - pointer[PointerInput.Vertical] = evt.clientY; - pointer[evt.button + 2] = 0; - const deviceEvent = evt; - if (evt.pointerId === undefined) { - evt.pointerId = this._mouseId; - } - if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) { - deviceEvent.inputIndex = PointerInput.Move; - this._onInputChanged(deviceType, deviceSlot, deviceEvent); - } - // NOTE: The +2 used here to is because PointerInput has the same value progression for its mouse buttons as PointerEvent.button - // However, we have our X and Y values front-loaded to group together the touch inputs but not break this progression - // EG. ([X, Y, Left-click], Middle-click, etc...) - deviceEvent.inputIndex = evt.button + 2; - if (deviceType === DeviceType.Mouse && this._mouseId >= 0 && ((_c = (_b = this._elementToAttachTo).hasPointerCapture) === null || _c === void 0 ? void 0 : _c.call(_b, this._mouseId))) { - this._elementToAttachTo.releasePointerCapture(this._mouseId); - } - else if (evt.pointerId && ((_e = (_d = this._elementToAttachTo).hasPointerCapture) === null || _e === void 0 ? void 0 : _e.call(_d, evt.pointerId))) { - this._elementToAttachTo.releasePointerCapture(evt.pointerId); - } - this._onInputChanged(deviceType, deviceSlot, deviceEvent); - if (deviceType === DeviceType.Touch) { - this._onDeviceDisconnected(deviceType, deviceSlot); - } - } - }; - this._pointerCancelEvent = (evt) => { - var _a, _b, _c, _d; - if (evt.pointerType === "mouse") { - const pointer = this._inputs[DeviceType.Mouse][0]; - if (this._mouseId >= 0 && ((_b = (_a = this._elementToAttachTo).hasPointerCapture) === null || _b === void 0 ? void 0 : _b.call(_a, this._mouseId))) { - this._elementToAttachTo.releasePointerCapture(this._mouseId); - } - for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) { - if (pointer[inputIndex] === 1) { - pointer[inputIndex] = 0; - const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo); - this._onInputChanged(DeviceType.Mouse, 0, deviceEvent); - } - } - } - else { - const deviceSlot = this._activeTouchIds.indexOf(evt.pointerId); - // If we're getting a pointercancel event for a touch that isn't active, just return - if (deviceSlot === -1) { - return; - } - if ((_d = (_c = this._elementToAttachTo).hasPointerCapture) === null || _d === void 0 ? void 0 : _d.call(_c, evt.pointerId)) { - this._elementToAttachTo.releasePointerCapture(evt.pointerId); - } - this._inputs[DeviceType.Touch][deviceSlot][PointerInput.LeftClick] = 0; - const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, evt.pointerId); - this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent); - this._activeTouchIds[deviceSlot] = -1; - this._onDeviceDisconnected(DeviceType.Touch, deviceSlot); - } - }; - // Set Wheel Event Name, code originally from scene.inputManager - this._wheelEventName = - "onwheel" in document.createElement("div") - ? "wheel" // Modern browsers support "wheel" - : document.onmousewheel !== undefined - ? "mousewheel" // Webkit and IE support at least "mousewheel" - : "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox - // Code originally in scene.inputManager.ts - // Chrome reports warning in console if wheel listener doesn't set an explicit passive option. - // IE11 only supports captureEvent:boolean, not options:object, and it defaults to false. - // Feature detection technique copied from: https://github.com/github/eventlistener-polyfill (MIT license) - let passiveSupported = false; - const noop = function () { }; - try { - const options = Object.defineProperty({}, "passive", { - get: function () { - passiveSupported = true; - }, - }); - this._elementToAttachTo.addEventListener("test", noop, options); - this._elementToAttachTo.removeEventListener("test", noop, options); - } - catch (e) { - /* */ - } - this._pointerBlurEvent = () => { - var _a, _b, _c, _d, _e; - // Handle mouse buttons - if (this.isDeviceAvailable(DeviceType.Mouse)) { - const pointer = this._inputs[DeviceType.Mouse][0]; - if (this._mouseId >= 0 && ((_b = (_a = this._elementToAttachTo).hasPointerCapture) === null || _b === void 0 ? void 0 : _b.call(_a, this._mouseId))) { - this._elementToAttachTo.releasePointerCapture(this._mouseId); - } - for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) { - if (pointer[inputIndex] === 1) { - pointer[inputIndex] = 0; - const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo); - this._onInputChanged(DeviceType.Mouse, 0, deviceEvent); - } - } - } - // Handle Active Touches - if (this.isDeviceAvailable(DeviceType.Touch)) { - const pointer = this._inputs[DeviceType.Touch]; - for (let deviceSlot = 0; deviceSlot < this._activeTouchIds.length; deviceSlot++) { - const pointerId = this._activeTouchIds[deviceSlot]; - if ((_d = (_c = this._elementToAttachTo).hasPointerCapture) === null || _d === void 0 ? void 0 : _d.call(_c, pointerId)) { - this._elementToAttachTo.releasePointerCapture(pointerId); - } - if (pointerId !== -1 && ((_e = pointer[deviceSlot]) === null || _e === void 0 ? void 0 : _e[PointerInput.LeftClick]) === 1) { - pointer[deviceSlot][PointerInput.LeftClick] = 0; - const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, pointerId); - this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent); - this._activeTouchIds[deviceSlot] = -1; - this._onDeviceDisconnected(DeviceType.Touch, deviceSlot); - } - } - } - }; - this._pointerWheelEvent = (evt) => { - const deviceType = DeviceType.Mouse; - const deviceSlot = 0; - if (!this._inputs[deviceType]) { - this._inputs[deviceType] = []; - } - if (!this._inputs[deviceType][deviceSlot]) { - this._pointerActive = true; - this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS); - } - const pointer = this._inputs[deviceType][deviceSlot]; - if (pointer) { - pointer[PointerInput.MouseWheelX] = evt.deltaX || 0; - pointer[PointerInput.MouseWheelY] = evt.deltaY || evt.wheelDelta || 0; - pointer[PointerInput.MouseWheelZ] = evt.deltaZ || 0; - const deviceEvent = evt; - // By default, there is no pointerId for mouse wheel events so we'll add one here - // This logic was originally in the InputManager but was added here to make the - // InputManager more platform-agnostic - if (evt.pointerId === undefined) { - evt.pointerId = this._mouseId; - } - if (pointer[PointerInput.MouseWheelX] !== 0) { - deviceEvent.inputIndex = PointerInput.MouseWheelX; - this._onInputChanged(deviceType, deviceSlot, deviceEvent); - } - if (pointer[PointerInput.MouseWheelY] !== 0) { - deviceEvent.inputIndex = PointerInput.MouseWheelY; - this._onInputChanged(deviceType, deviceSlot, deviceEvent); - } - if (pointer[PointerInput.MouseWheelZ] !== 0) { - deviceEvent.inputIndex = PointerInput.MouseWheelZ; - this._onInputChanged(deviceType, deviceSlot, deviceEvent); - } - } - }; - 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, passiveSupported ? { passive: false } : false); - // Since there's no up or down event for mouse wheel or delta x/y, clear mouse values at end of frame - this._pointerInputClearObserver = this._engine.onEndFrameObservable.add(() => { - if (this.isDeviceAvailable(DeviceType.Mouse)) { - const pointer = this._inputs[DeviceType.Mouse][0]; - pointer[PointerInput.MouseWheelX] = 0; - pointer[PointerInput.MouseWheelY] = 0; - pointer[PointerInput.MouseWheelZ] = 0; - } - }); - } - /** - * Handle all actions that come from gamepad interaction - */ - _handleGamepadActions() { - this._gamepadConnectedEvent = (evt) => { - this._addGamePad(evt.gamepad); - }; - this._gamepadDisconnectedEvent = (evt) => { - if (this._gamepads) { - const deviceType = this._getGamepadDeviceType(evt.gamepad.id); - const deviceSlot = evt.gamepad.index; - this._unregisterDevice(deviceType, deviceSlot); - delete this._gamepads[deviceSlot]; - } - }; - window.addEventListener("gamepadconnected", this._gamepadConnectedEvent); - window.addEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent); - } - /** - * Update all non-event based devices with each frame - * @param deviceType Enum specifying device type - * @param deviceSlot "Slot" or index that device is referenced in - * @param inputIndex Id of input to be checked - */ - _updateDevice(deviceType, deviceSlot, inputIndex) { - // Gamepads - const gp = navigator.getGamepads()[deviceSlot]; - if (gp && deviceType === this._gamepads[deviceSlot]) { - const device = this._inputs[deviceType][deviceSlot]; - if (inputIndex >= gp.buttons.length) { - device[inputIndex] = gp.axes[inputIndex - gp.buttons.length].valueOf(); - } - else { - device[inputIndex] = gp.buttons[inputIndex].value; - } - } - } - /** - * Gets DeviceType from the device name - * @param deviceName Name of Device from DeviceInputSystem - * @returns DeviceType enum value - */ - _getGamepadDeviceType(deviceName) { - if (deviceName.indexOf("054c") !== -1) { - // DualShock 4 Gamepad - return deviceName.indexOf("0ce6") !== -1 ? DeviceType.DualSense : DeviceType.DualShock; - } - else if (deviceName.indexOf("Xbox One") !== -1 || deviceName.search("Xbox 360") !== -1 || deviceName.search("xinput") !== -1) { - // Xbox Gamepad - return DeviceType.Xbox; - } - else if (deviceName.indexOf("057e") !== -1) { - // Switch Gamepad - return DeviceType.Switch; - } - return DeviceType.Generic; - } - /** - * Get DeviceType from a given pointer/mouse/touch event. - * @param evt PointerEvent to evaluate - * @returns DeviceType interpreted from event - */ - _getPointerType(evt) { - let deviceType = DeviceType.Mouse; - if (evt.pointerType === "touch" || evt.pointerType === "pen" || evt.touches) { - deviceType = DeviceType.Touch; - } - return deviceType; - } -} -//# sourceMappingURL=webDeviceInputSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSource.js - -/** - * Class that handles all input for a specific device - */ -class DeviceSource { - /** - * Default Constructor - * @param deviceInputSystem - Reference to DeviceInputSystem - * @param deviceType - Type of device - * @param deviceSlot - "Slot" or index that device is referenced in - */ - constructor(deviceInputSystem, - /** Type of device */ - deviceType, - /** "Slot" or index that device is referenced in */ - deviceSlot = 0) { - this.deviceType = deviceType; - this.deviceSlot = deviceSlot; - // Public Members - /** - * Observable to handle device input changes per device - */ - this.onInputChangedObservable = new observable_Observable(); - this._deviceInputSystem = deviceInputSystem; - } - /** - * Get input for specific input - * @param inputIndex - index of specific input on device - * @returns Input value from DeviceInputSystem - */ - getInput(inputIndex) { - return this._deviceInputSystem.pollInput(this.deviceType, this.deviceSlot, inputIndex); - } -} -//# sourceMappingURL=deviceSource.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/DeviceInput/internalDeviceSourceManager.js - - - - -/** @internal */ -class InternalDeviceSourceManager { - constructor(engine) { - this._registeredManagers = new Array(); - this._refCount = 0; - // Public Functions - this.registerManager = (manager) => { - for (let deviceType = 0; deviceType < this._devices.length; deviceType++) { - const device = this._devices[deviceType]; - for (const deviceSlotKey in device) { - const deviceSlot = +deviceSlotKey; - manager._addDevice(new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot)); - } - } - this._registeredManagers.push(manager); - }; - this.unregisterManager = (manager) => { - const idx = this._registeredManagers.indexOf(manager); - if (idx > -1) { - this._registeredManagers.splice(idx, 1); - } - }; - const numberOfDeviceTypes = Object.keys(DeviceType).length / 2; - this._devices = new Array(numberOfDeviceTypes); - const onDeviceConnected = (deviceType, deviceSlot) => { - if (!this._devices[deviceType]) { - this._devices[deviceType] = new Array(); - } - if (!this._devices[deviceType][deviceSlot]) { - this._devices[deviceType][deviceSlot] = deviceSlot; - } - for (const manager of this._registeredManagers) { - const deviceSource = new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot); - manager._addDevice(deviceSource); - } - }; - const onDeviceDisconnected = (deviceType, deviceSlot) => { - var _a; - if ((_a = this._devices[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot]) { - delete this._devices[deviceType][deviceSlot]; - } - for (const manager of this._registeredManagers) { - manager._removeDevice(deviceType, deviceSlot); - } - }; - const onInputChanged = (deviceType, deviceSlot, eventData) => { - if (eventData) { - for (const manager of this._registeredManagers) { - manager._onInputChanged(deviceType, deviceSlot, eventData); - } - } - }; - if (typeof _native !== "undefined") { - this._deviceInputSystem = new NativeDeviceInputSystem(onDeviceConnected, onDeviceDisconnected, onInputChanged); - } - else { - this._deviceInputSystem = new WebDeviceInputSystem(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged); - } - } - dispose() { - this._deviceInputSystem.dispose(); - } -} -//# sourceMappingURL=internalDeviceSourceManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSourceManager.js - - - -/** - * Class to keep track of devices - */ -class DeviceSourceManager { - // Public Functions - /** - * Gets a DeviceSource, given a type and slot - * @param deviceType - Type of Device - * @param deviceSlot - Slot or ID of device - * @returns DeviceSource - */ - getDeviceSource(deviceType, deviceSlot) { - if (deviceSlot === undefined) { - if (this._firstDevice[deviceType] === undefined) { - return null; - } - deviceSlot = this._firstDevice[deviceType]; - } - if (!this._devices[deviceType] || this._devices[deviceType][deviceSlot] === undefined) { - return null; - } - return this._devices[deviceType][deviceSlot]; - } - /** - * Gets an array of DeviceSource objects for a given device type - * @param deviceType - Type of Device - * @returns All available DeviceSources of a given type - */ - getDeviceSources(deviceType) { - // If device type hasn't had any devices connected yet, return empty array. - if (!this._devices[deviceType]) { - return []; - } - return this._devices[deviceType].filter((source) => { - return !!source; - }); - } - /** - * Default constructor - * @param engine - Used to get canvas (if applicable) - */ - constructor(engine) { - const numberOfDeviceTypes = Object.keys(DeviceType).length / 2; - this._devices = new Array(numberOfDeviceTypes); - this._firstDevice = new Array(numberOfDeviceTypes); - this._engine = engine; - if (!this._engine._deviceSourceManager) { - this._engine._deviceSourceManager = new InternalDeviceSourceManager(engine); - } - this._engine._deviceSourceManager._refCount++; - // Observables - this.onDeviceConnectedObservable = new observable_Observable((observer) => { - for (const devices of this._devices) { - if (devices) { - for (const device of devices) { - if (device) { - this.onDeviceConnectedObservable.notifyObserver(observer, device); - } - } - } - } - }); - this.onDeviceDisconnectedObservable = new observable_Observable(); - this._engine._deviceSourceManager.registerManager(this); - this._onDisposeObserver = engine.onDisposeObservable.add(() => { - this.dispose(); - }); - } - /** - * Dispose of DeviceSourceManager - */ - dispose() { - // Null out observable refs - this.onDeviceConnectedObservable.clear(); - this.onDeviceDisconnectedObservable.clear(); - if (this._engine._deviceSourceManager) { - this._engine._deviceSourceManager.unregisterManager(this); - if (--this._engine._deviceSourceManager._refCount < 1) { - this._engine._deviceSourceManager.dispose(); - delete this._engine._deviceSourceManager; - } - } - this._engine.onDisposeObservable.remove(this._onDisposeObserver); - } - // Hidden Functions - /** - * @param deviceSource - Source to add - * @internal - */ - _addDevice(deviceSource) { - if (!this._devices[deviceSource.deviceType]) { - this._devices[deviceSource.deviceType] = new Array(); - } - if (!this._devices[deviceSource.deviceType][deviceSource.deviceSlot]) { - this._devices[deviceSource.deviceType][deviceSource.deviceSlot] = deviceSource; - this._updateFirstDevices(deviceSource.deviceType); - } - this.onDeviceConnectedObservable.notifyObservers(deviceSource); - } - /** - * @param deviceType - DeviceType - * @param deviceSlot - DeviceSlot - * @internal - */ - _removeDevice(deviceType, deviceSlot) { - var _a, _b; - const deviceSource = (_a = this._devices[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot]; // Grab local reference to use before removing from devices - this.onDeviceDisconnectedObservable.notifyObservers(deviceSource); - if ((_b = this._devices[deviceType]) === null || _b === void 0 ? void 0 : _b[deviceSlot]) { - delete this._devices[deviceType][deviceSlot]; - } - // Even if we don't delete a device, we should still check for the first device as things may have gotten out of sync. - this._updateFirstDevices(deviceType); - } - /** - * @param deviceType - DeviceType - * @param deviceSlot - DeviceSlot - * @param eventData - Event - * @internal - */ - _onInputChanged(deviceType, deviceSlot, eventData) { - var _a, _b; - (_b = (_a = this._devices[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot]) === null || _b === void 0 ? void 0 : _b.onInputChangedObservable.notifyObservers(eventData); - } - // Private Functions - _updateFirstDevices(type) { - switch (type) { - case DeviceType.Keyboard: - case DeviceType.Mouse: - this._firstDevice[type] = 0; - break; - case DeviceType.Touch: - case DeviceType.DualSense: - case DeviceType.DualShock: - case DeviceType.Xbox: - case DeviceType.Switch: - case DeviceType.Generic: { - delete this._firstDevice[type]; - // eslint-disable-next-line no-case-declarations - const devices = this._devices[type]; - if (devices) { - for (let i = 0; i < devices.length; i++) { - if (devices[i]) { - this._firstDevice[type] = i; - break; - } - } - } - break; - } - } - } -} -//# sourceMappingURL=deviceSourceManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Inputs/scene.inputManager.js - - - - - - - - - - -/** @internal */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _ClickInfo { - constructor() { - this._singleClick = false; - this._doubleClick = false; - this._hasSwiped = false; - this._ignore = false; - } - get singleClick() { - return this._singleClick; - } - get doubleClick() { - return this._doubleClick; - } - get hasSwiped() { - return this._hasSwiped; - } - get ignore() { - return this._ignore; - } - set singleClick(b) { - this._singleClick = b; - } - set doubleClick(b) { - this._doubleClick = b; - } - set hasSwiped(b) { - this._hasSwiped = b; - } - set ignore(b) { - this._ignore = b; - } -} -/** - * Class used to manage all inputs for the scene. - */ -class InputManager { - /** - * Creates a new InputManager - * @param scene - defines the hosting scene - */ - constructor(scene) { - /** 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. */ - this._alreadyAttached = false; - this._meshPickProceed = false; - this._currentPickResult = null; - this._previousPickResult = null; - this._totalPointersPressed = 0; - this._doubleClickOccured = false; - this._isSwiping = false; - this._swipeButtonPressed = -1; - this._skipPointerTap = false; - this._isMultiTouchGesture = false; - this._pointerX = 0; - this._pointerY = 0; - this._startingPointerPosition = new math_vector_Vector2(0, 0); - this._previousStartingPointerPosition = new math_vector_Vector2(0, 0); - this._startingPointerTime = 0; - this._previousStartingPointerTime = 0; - this._pointerCaptures = {}; - this._meshUnderPointerId = {}; - this._movePointerInfo = null; - this._cameraObserverCount = 0; - this._delayedClicks = [null, null, null, null, null]; - this._deviceSourceManager = null; - this._scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!this._scene) { - return; - } - } - /** - * Gets the mesh that is currently under the pointer - * @returns Mesh that the pointer is pointer is hovering over - */ - get meshUnderPointer() { - if (this._movePointerInfo) { - // Because _pointerOverMesh is populated as part of _pickMove, we need to force a pick to update it. - // Calling _pickMove calls _setCursorAndPointerOverMesh which calls setPointerOverMesh - this._movePointerInfo._generatePickInfo(); - // Once we have what we need, we can clear _movePointerInfo because we don't need it anymore - this._movePointerInfo = null; - } - return this._pointerOverMesh; - } - /** - * When using more than one pointer (for example in XR) you can get the mesh under the specific pointer - * @param pointerId - the pointer id to use - * @returns The mesh under this pointer id or null if not found - */ - getMeshUnderPointerByPointerId(pointerId) { - return this._meshUnderPointerId[pointerId] || null; - } - /** - * Gets the pointer coordinates in 2D without any translation (ie. straight out of the pointer event) - * @returns Vector with X/Y values directly from pointer event - */ - get unTranslatedPointer() { - return new math_vector_Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY); - } - /** - * Gets or sets the current on-screen X position of the pointer - * @returns Translated X with respect to screen - */ - get pointerX() { - return this._pointerX; - } - set pointerX(value) { - this._pointerX = value; - } - /** - * Gets or sets the current on-screen Y position of the pointer - * @returns Translated Y with respect to screen - */ - get pointerY() { - return this._pointerY; - } - set pointerY(value) { - this._pointerY = value; - } - _updatePointerPosition(evt) { - const canvasRect = this._scene.getEngine().getInputElementClientRect(); - if (!canvasRect) { - return; - } - this._pointerX = evt.clientX - canvasRect.left; - this._pointerY = evt.clientY - canvasRect.top; - this._unTranslatedPointerX = this._pointerX; - this._unTranslatedPointerY = this._pointerY; - } - _processPointerMove(pickResult, evt) { - const scene = this._scene; - const engine = scene.getEngine(); - const canvas = engine.getInputElement(); - if (canvas) { - canvas.tabIndex = engine.canvasTabIndex; - // Restore pointer - if (!scene.doNotHandleCursors) { - canvas.style.cursor = scene.defaultCursor; - } - } - this._setCursorAndPointerOverMesh(pickResult, evt, scene); - for (const step of scene._pointerMoveStage) { - // If _pointerMoveState is defined, we have an active spriteManager and can't use Lazy Picking - // Therefore, we need to force a pick to update the pickResult - pickResult = pickResult || this._pickMove(evt); - const isMeshPicked = (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) ? true : false; - pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas); - } - const type = evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? pointerEvents_PointerEventTypes.POINTERWHEEL : pointerEvents_PointerEventTypes.POINTERMOVE; - if (scene.onPointerMove) { - // Because of lazy picking, we need to force a pick to update the pickResult - pickResult = pickResult || this._pickMove(evt); - scene.onPointerMove(evt, pickResult, type); - } - let pointerInfo; - if (pickResult) { - pointerInfo = new PointerInfo(type, evt, pickResult); - this._setRayOnPointerInfo(pickResult, evt); - } - else { - pointerInfo = new PointerInfo(type, evt, null, this); - this._movePointerInfo = pointerInfo; - } - if (scene.onPointerObservable.hasObservers()) { - scene.onPointerObservable.notifyObservers(pointerInfo, type); - } - } - // Pointers handling - /** @internal */ - _setRayOnPointerInfo(pickInfo, event) { - const scene = this._scene; - if (pickInfo && scene._pickingAvailable) { - if (!pickInfo.ray) { - pickInfo.ray = scene.createPickingRay(event.offsetX, event.offsetY, math_vector_Matrix.Identity(), scene.activeCamera); - } - } - } - /** @internal */ - _addCameraPointerObserver(observer, mask) { - this._cameraObserverCount++; - return this._scene.onPointerObservable.add(observer, mask); - } - /** @internal */ - _removeCameraPointerObserver(observer) { - this._cameraObserverCount--; - return this._scene.onPointerObservable.remove(observer); - } - _checkForPicking() { - return !!(this._scene.onPointerObservable.observers.length > this._cameraObserverCount || this._scene.onPointerPick); - } - _checkPrePointerObservable(pickResult, evt, type) { - const scene = this._scene; - const pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY); - if (pickResult) { - pi.originalPickingInfo = pickResult; - pi.ray = pickResult.ray; - if (pickResult.originMesh) { - pi.nearInteractionPickingInfo = pickResult; - } - } - scene.onPrePointerObservable.notifyObservers(pi, type); - if (pi.skipOnPointerObservable) { - return true; - } - else { - return false; - } - } - /** @internal */ - _pickMove(evt) { - const scene = this._scene; - const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerMovePredicate, scene.pointerMoveFastCheck, scene.cameraToUseForPointers, scene.pointerMoveTrianglePredicate); - this._setCursorAndPointerOverMesh(pickResult, evt, scene); - return pickResult; - } - _setCursorAndPointerOverMesh(pickResult, evt, scene) { - const engine = scene.getEngine(); - const canvas = engine.getInputElement(); - if (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) { - this.setPointerOverMesh(pickResult.pickedMesh, evt.pointerId, pickResult, evt); - if (!scene.doNotHandleCursors && canvas && this._pointerOverMesh) { - const actionManager = this._pointerOverMesh._getActionManagerForTrigger(); - if (actionManager && actionManager.hasPointerTriggers) { - canvas.style.cursor = actionManager.hoverCursor || scene.hoverCursor; - } - } - } - else { - this.setPointerOverMesh(null, evt.pointerId, pickResult, evt); - } - } - /** - * Use this method to simulate a pointer move on a mesh - * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay - * @param pickResult - pickingInfo of the object wished to simulate pointer event on - * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) - */ - simulatePointerMove(pickResult, pointerEventInit) { - const evt = new PointerEvent("pointermove", pointerEventInit); - evt.inputIndex = PointerInput.Move; - if (this._checkPrePointerObservable(pickResult, evt, pointerEvents_PointerEventTypes.POINTERMOVE)) { - return; - } - this._processPointerMove(pickResult, evt); - } - /** - * Use this method to simulate a pointer down on a mesh - * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay - * @param pickResult - pickingInfo of the object wished to simulate pointer event on - * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) - */ - simulatePointerDown(pickResult, pointerEventInit) { - const evt = new PointerEvent("pointerdown", pointerEventInit); - evt.inputIndex = evt.button + 2; - if (this._checkPrePointerObservable(pickResult, evt, pointerEvents_PointerEventTypes.POINTERDOWN)) { - return; - } - this._processPointerDown(pickResult, evt); - } - _processPointerDown(pickResult, evt) { - const scene = this._scene; - if (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) { - this._pickedDownMesh = pickResult.pickedMesh; - const actionManager = pickResult.pickedMesh._getActionManagerForTrigger(); - if (actionManager) { - if (actionManager.hasPickTriggers) { - actionManager.processTrigger(5, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); - switch (evt.button) { - case 0: - actionManager.processTrigger(2, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); - break; - case 1: - actionManager.processTrigger(4, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); - break; - case 2: - actionManager.processTrigger(3, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); - break; - } - } - if (actionManager.hasSpecificTrigger(8)) { - window.setTimeout(() => { - const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, (mesh) => ((mesh.isPickable && - mesh.isVisible && - mesh.isReady() && - mesh.actionManager && - mesh.actionManager.hasSpecificTrigger(8) && - mesh === this._pickedDownMesh)), false, scene.cameraToUseForPointers); - if ((pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) && actionManager) { - if (this._totalPointersPressed !== 0 && Date.now() - this._startingPointerTime > InputManager.LongPressDelay && !this._isPointerSwiping()) { - this._startingPointerTime = 0; - actionManager.processTrigger(8, ActionEvent.CreateNew(pickResult.pickedMesh, evt)); - } - } - }, InputManager.LongPressDelay); - } - } - } - else { - for (const step of scene._pointerDownStage) { - pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, false); - } - } - let pointerInfo; - const type = pointerEvents_PointerEventTypes.POINTERDOWN; - if (pickResult) { - if (scene.onPointerDown) { - scene.onPointerDown(evt, pickResult, type); - } - pointerInfo = new PointerInfo(type, evt, pickResult); - this._setRayOnPointerInfo(pickResult, evt); - } - else { - pointerInfo = new PointerInfo(type, evt, null, this); - } - if (scene.onPointerObservable.hasObservers()) { - scene.onPointerObservable.notifyObservers(pointerInfo, type); - } - } - /** - * @internal - * @internals Boolean if delta for pointer exceeds drag movement threshold - */ - _isPointerSwiping() { - return this._isSwiping; - } - /** - * Use this method to simulate a pointer up on a mesh - * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay - * @param pickResult - pickingInfo of the object wished to simulate pointer event on - * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) - * @param doubleTap - indicates that the pointer up event should be considered as part of a double click (false by default) - */ - simulatePointerUp(pickResult, pointerEventInit, doubleTap) { - const evt = new PointerEvent("pointerup", pointerEventInit); - evt.inputIndex = PointerInput.Move; - const clickInfo = new _ClickInfo(); - if (doubleTap) { - clickInfo.doubleClick = true; - } - else { - clickInfo.singleClick = true; - } - if (this._checkPrePointerObservable(pickResult, evt, pointerEvents_PointerEventTypes.POINTERUP)) { - return; - } - this._processPointerUp(pickResult, evt, clickInfo); - } - _processPointerUp(pickResult, evt, clickInfo) { - const scene = this._scene; - if (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) { - this._pickedUpMesh = pickResult.pickedMesh; - if (this._pickedDownMesh === this._pickedUpMesh) { - if (scene.onPointerPick) { - scene.onPointerPick(evt, pickResult); - } - if (clickInfo.singleClick && !clickInfo.ignore && scene.onPointerObservable.observers.length > this._cameraObserverCount) { - const type = pointerEvents_PointerEventTypes.POINTERPICK; - const pi = new PointerInfo(type, evt, pickResult); - this._setRayOnPointerInfo(pickResult, evt); - scene.onPointerObservable.notifyObservers(pi, type); - } - } - const actionManager = pickResult.pickedMesh._getActionManagerForTrigger(); - if (actionManager && !clickInfo.ignore) { - actionManager.processTrigger(7, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); - if (!clickInfo.hasSwiped && clickInfo.singleClick) { - actionManager.processTrigger(1, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); - } - const doubleClickActionManager = pickResult.pickedMesh._getActionManagerForTrigger(6); - if (clickInfo.doubleClick && doubleClickActionManager) { - doubleClickActionManager.processTrigger(6, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); - } - } - } - else { - if (!clickInfo.ignore) { - for (const step of scene._pointerUpStage) { - pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, clickInfo.doubleClick); - } - } - } - if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) { - const pickedDownActionManager = this._pickedDownMesh._getActionManagerForTrigger(16); - if (pickedDownActionManager) { - pickedDownActionManager.processTrigger(16, ActionEvent.CreateNew(this._pickedDownMesh, evt)); - } - } - if (!clickInfo.ignore) { - const pi = new PointerInfo(pointerEvents_PointerEventTypes.POINTERUP, evt, pickResult); - // Set ray on picking info. Note that this info will also be reused for the tap notification. - this._setRayOnPointerInfo(pickResult, evt); - scene.onPointerObservable.notifyObservers(pi, pointerEvents_PointerEventTypes.POINTERUP); - if (scene.onPointerUp) { - scene.onPointerUp(evt, pickResult, pointerEvents_PointerEventTypes.POINTERUP); - } - if (!clickInfo.hasSwiped && !this._skipPointerTap && !this._isMultiTouchGesture) { - let type = 0; - if (clickInfo.singleClick) { - type = pointerEvents_PointerEventTypes.POINTERTAP; - } - else if (clickInfo.doubleClick) { - type = pointerEvents_PointerEventTypes.POINTERDOUBLETAP; - } - if (type) { - const pi = new PointerInfo(type, evt, pickResult); - if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) { - scene.onPointerObservable.notifyObservers(pi, type); - } - } - } - } - } - /** - * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down) - * @param pointerId - defines the pointer id to use in a multi-touch scenario (0 by default) - * @returns true if the pointer was captured - */ - isPointerCaptured(pointerId = 0) { - return this._pointerCaptures[pointerId]; - } - /** - * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp - * @param attachUp - defines if you want to attach events to pointerup - * @param attachDown - defines if you want to attach events to pointerdown - * @param attachMove - defines if you want to attach events to pointermove - * @param elementToAttachTo - defines the target DOM element to attach to (will use the canvas by default) - */ - attachControl(attachUp = true, attachDown = true, attachMove = true, elementToAttachTo = null) { - const scene = this._scene; - const engine = scene.getEngine(); - if (!elementToAttachTo) { - elementToAttachTo = engine.getInputElement(); - } - if (this._alreadyAttached) { - this.detachControl(); - } - if (elementToAttachTo) { - this._alreadyAttachedTo = elementToAttachTo; - } - this._deviceSourceManager = new DeviceSourceManager(engine); - // Because this is only called from _initClickEvent, which is called in _onPointerUp, we'll use the pointerUpPredicate for the pick call - this._initActionManager = (act) => { - if (!this._meshPickProceed) { - const pickResult = scene.skipPointerUpPicking || (scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerUp) - ? null - : scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerUpPredicate, scene.pointerUpFastCheck, scene.cameraToUseForPointers); - this._currentPickResult = pickResult; - if (pickResult) { - act = pickResult.hit && pickResult.pickedMesh ? pickResult.pickedMesh._getActionManagerForTrigger() : null; - } - this._meshPickProceed = true; - } - return act; - }; - this._delayedSimpleClick = (btn, clickInfo, cb) => { - // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different - if ((Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay && !this._doubleClickOccured) || btn !== this._previousButtonPressed) { - this._doubleClickOccured = false; - clickInfo.singleClick = true; - clickInfo.ignore = false; - // If we have a delayed click, we need to resolve the TAP event - if (this._delayedClicks[btn]) { - const evt = this._delayedClicks[btn].evt; - const type = pointerEvents_PointerEventTypes.POINTERTAP; - const pi = new PointerInfo(type, evt, this._currentPickResult); - if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) { - scene.onPointerObservable.notifyObservers(pi, type); - } - // Clear the delayed click - this._delayedClicks[btn] = null; - } - } - }; - this._initClickEvent = (obs1, obs2, evt, cb) => { - var _a, _b; - const clickInfo = new _ClickInfo(); - this._currentPickResult = null; - let act = null; - let checkPicking = obs1.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERPICK) || - obs2.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERPICK) || - obs1.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERTAP) || - obs2.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERTAP) || - obs1.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP) || - obs2.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP); - if (!checkPicking && AbstractActionManager) { - act = this._initActionManager(act, clickInfo); - if (act) { - checkPicking = act.hasPickTriggers; - } - } - let needToIgnoreNext = false; - if (checkPicking) { - const btn = evt.button; - clickInfo.hasSwiped = this._isPointerSwiping(); - if (!clickInfo.hasSwiped) { - let checkSingleClickImmediately = !InputManager.ExclusiveDoubleClickMode; - if (!checkSingleClickImmediately) { - checkSingleClickImmediately = !obs1.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP) && !obs2.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP); - if (checkSingleClickImmediately && !AbstractActionManager.HasSpecificTrigger(6)) { - act = this._initActionManager(act, clickInfo); - if (act) { - checkSingleClickImmediately = !act.hasSpecificTrigger(6); - } - } - } - if (checkSingleClickImmediately) { - // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required - if (Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay || btn !== this._previousButtonPressed) { - clickInfo.singleClick = true; - cb(clickInfo, this._currentPickResult); - needToIgnoreNext = true; - } - } - // at least one double click is required to be check and exclusive double click is enabled - else { - // Queue up a delayed click, just in case this isn't a double click - // It should be noted that while this delayed event happens - // because of user input, it shouldn't be considered as a direct, - // timing-dependent result of that input. It's meant to just fire the TAP event - const delayedClick = { - evt: evt, - clickInfo: clickInfo, - timeoutId: window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), InputManager.DoubleClickDelay), - }; - this._delayedClicks[btn] = delayedClick; - } - let checkDoubleClick = obs1.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP); - if (!checkDoubleClick && AbstractActionManager.HasSpecificTrigger(6)) { - act = this._initActionManager(act, clickInfo); - if (act) { - checkDoubleClick = act.hasSpecificTrigger(6); - } - } - if (checkDoubleClick) { - // two successive keys pressed are equal, double click delay is not over and double click has not just occurred - if (btn === this._previousButtonPressed && Date.now() - this._previousStartingPointerTime < InputManager.DoubleClickDelay && !this._doubleClickOccured) { - // pointer has not moved for 2 clicks, it's a double click - if (!clickInfo.hasSwiped && !this._isPointerSwiping()) { - this._previousStartingPointerTime = 0; - this._doubleClickOccured = true; - clickInfo.doubleClick = true; - clickInfo.ignore = false; - // If we have a pending click, we need to cancel it - if (InputManager.ExclusiveDoubleClickMode && this._delayedClicks[btn]) { - clearTimeout((_a = this._delayedClicks[btn]) === null || _a === void 0 ? void 0 : _a.timeoutId); - this._delayedClicks[btn] = null; - } - cb(clickInfo, this._currentPickResult); - } - // if the two successive clicks are too far, it's just two simple clicks - else { - this._doubleClickOccured = false; - this._previousStartingPointerTime = this._startingPointerTime; - this._previousStartingPointerPosition.x = this._startingPointerPosition.x; - this._previousStartingPointerPosition.y = this._startingPointerPosition.y; - this._previousButtonPressed = btn; - if (InputManager.ExclusiveDoubleClickMode) { - // If we have a delayed click, we need to cancel it - if (this._delayedClicks[btn]) { - clearTimeout((_b = this._delayedClicks[btn]) === null || _b === void 0 ? void 0 : _b.timeoutId); - this._delayedClicks[btn] = null; - } - cb(clickInfo, this._previousPickResult); - } - else { - cb(clickInfo, this._currentPickResult); - } - } - needToIgnoreNext = true; - } - // just the first click of the double has been raised - else { - this._doubleClickOccured = false; - this._previousStartingPointerTime = this._startingPointerTime; - this._previousStartingPointerPosition.x = this._startingPointerPosition.x; - this._previousStartingPointerPosition.y = this._startingPointerPosition.y; - this._previousButtonPressed = btn; - } - } - } - } - // Even if ExclusiveDoubleClickMode is true, we need to always handle - // up events at time of execution, unless we're explicitly ignoring them. - if (!needToIgnoreNext) { - cb(clickInfo, this._currentPickResult); - } - }; - this._onPointerMove = (evt) => { - this._updatePointerPosition(evt); - // Check if pointer leaves DragMovementThreshold range to determine if swipe is occurring - if (!this._isSwiping && this._swipeButtonPressed !== -1) { - this._isSwiping = - Math.abs(this._startingPointerPosition.x - this._pointerX) > InputManager.DragMovementThreshold || - Math.abs(this._startingPointerPosition.y - this._pointerY) > InputManager.DragMovementThreshold; - } - // Because there's a race condition between pointermove and pointerlockchange events, we need to - // verify that the pointer is still locked after each pointermove event. - if (engine.isPointerLock) { - engine._verifyPointerLock(); - } - // PreObservable support - if (this._checkPrePointerObservable(null, evt, evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? pointerEvents_PointerEventTypes.POINTERWHEEL : pointerEvents_PointerEventTypes.POINTERMOVE)) { - return; - } - if (!scene.cameraToUseForPointers && !scene.activeCamera) { - return; - } - if (scene.skipPointerMovePicking) { - this._processPointerMove(new PickingInfo(), evt); - return; - } - if (!scene.pointerMovePredicate) { - scene.pointerMovePredicate = (mesh) => mesh.isPickable && - mesh.isVisible && - mesh.isReady() && - mesh.isEnabled() && - (mesh.enablePointerMoveEvents || scene.constantlyUpdateMeshUnderPointer || mesh._getActionManagerForTrigger() !== null) && - (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0); - } - const pickResult = scene._registeredActions > 0 || scene.constantlyUpdateMeshUnderPointer ? this._pickMove(evt) : null; - this._processPointerMove(pickResult, evt); - }; - this._onPointerDown = (evt) => { - var _a; - this._totalPointersPressed++; - this._pickedDownMesh = null; - this._meshPickProceed = false; - // If ExclusiveDoubleClickMode is true, we need to resolve any pending delayed clicks - if (InputManager.ExclusiveDoubleClickMode) { - for (let i = 0; i < this._delayedClicks.length; i++) { - if (this._delayedClicks[i]) { - // If the button that was pressed is the same as the one that was released, - // just clear the timer. This will be resolved in the up event. - if (evt.button === i) { - clearTimeout((_a = this._delayedClicks[i]) === null || _a === void 0 ? void 0 : _a.timeoutId); - } - else { - // Otherwise, we need to resolve the click - const clickInfo = this._delayedClicks[i].clickInfo; - this._doubleClickOccured = false; - clickInfo.singleClick = true; - clickInfo.ignore = false; - const prevEvt = this._delayedClicks[i].evt; - const type = pointerEvents_PointerEventTypes.POINTERTAP; - const pi = new PointerInfo(type, prevEvt, this._currentPickResult); - if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) { - scene.onPointerObservable.notifyObservers(pi, type); - } - // Clear the delayed click - this._delayedClicks[i] = null; - } - } - } - } - this._updatePointerPosition(evt); - if (this._swipeButtonPressed === -1) { - this._swipeButtonPressed = evt.button; - } - if (scene.preventDefaultOnPointerDown && elementToAttachTo) { - evt.preventDefault(); - elementToAttachTo.focus(); - } - this._startingPointerPosition.x = this._pointerX; - this._startingPointerPosition.y = this._pointerY; - this._startingPointerTime = Date.now(); - // PreObservable support - if (this._checkPrePointerObservable(null, evt, pointerEvents_PointerEventTypes.POINTERDOWN)) { - return; - } - if (!scene.cameraToUseForPointers && !scene.activeCamera) { - return; - } - this._pointerCaptures[evt.pointerId] = true; - if (!scene.pointerDownPredicate) { - scene.pointerDownPredicate = (mesh) => { - return (mesh.isPickable && - mesh.isVisible && - mesh.isReady() && - mesh.isEnabled() && - (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0)); - }; - } - // Meshes - this._pickedDownMesh = null; - let pickResult; - if (scene.skipPointerDownPicking || (scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerDown)) { - pickResult = new PickingInfo(); - } - else { - pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerDownPredicate, scene.pointerDownFastCheck, scene.cameraToUseForPointers); - } - this._processPointerDown(pickResult, evt); - }; - this._onPointerUp = (evt) => { - if (this._totalPointersPressed === 0) { - // We are attaching the pointer up to windows because of a bug in FF - return; // So we need to test it the pointer down was pressed before. - } - this._totalPointersPressed--; - this._pickedUpMesh = null; - this._meshPickProceed = false; - this._updatePointerPosition(evt); - if (scene.preventDefaultOnPointerUp && elementToAttachTo) { - evt.preventDefault(); - elementToAttachTo.focus(); - } - this._initClickEvent(scene.onPrePointerObservable, scene.onPointerObservable, evt, (clickInfo, pickResult) => { - // PreObservable support - if (scene.onPrePointerObservable.hasObservers()) { - this._skipPointerTap = false; - if (!clickInfo.ignore) { - if (this._checkPrePointerObservable(null, evt, pointerEvents_PointerEventTypes.POINTERUP)) { - // If we're skipping the next observable, we need to reset the swipe state before returning - if (this._swipeButtonPressed === evt.button) { - this._isSwiping = false; - this._swipeButtonPressed = -1; - } - // If we're going to skip the POINTERUP, we need to reset the pointer capture - if (evt.buttons === 0) { - this._pointerCaptures[evt.pointerId] = false; - } - return; - } - if (!clickInfo.hasSwiped) { - if (clickInfo.singleClick && scene.onPrePointerObservable.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERTAP)) { - if (this._checkPrePointerObservable(null, evt, pointerEvents_PointerEventTypes.POINTERTAP)) { - this._skipPointerTap = true; - } - } - if (clickInfo.doubleClick && scene.onPrePointerObservable.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP)) { - if (this._checkPrePointerObservable(null, evt, pointerEvents_PointerEventTypes.POINTERDOUBLETAP)) { - this._skipPointerTap = true; - } - } - } - } - } - // There should be a pointer captured at this point so if there isn't we should reset and return - if (!this._pointerCaptures[evt.pointerId]) { - if (this._swipeButtonPressed === evt.button) { - this._isSwiping = false; - this._swipeButtonPressed = -1; - } - return; - } - // Only release capture if all buttons are released - if (evt.buttons === 0) { - this._pointerCaptures[evt.pointerId] = false; - } - if (!scene.cameraToUseForPointers && !scene.activeCamera) { - return; - } - if (!scene.pointerUpPredicate) { - scene.pointerUpPredicate = (mesh) => { - return (mesh.isPickable && - mesh.isVisible && - mesh.isReady() && - mesh.isEnabled() && - (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0)); - }; - } - // Meshes - if (!this._meshPickProceed && ((AbstractActionManager && AbstractActionManager.HasTriggers) || this._checkForPicking() || scene.onPointerUp)) { - this._initActionManager(null, clickInfo); - } - if (!pickResult) { - pickResult = this._currentPickResult; - } - this._processPointerUp(pickResult, evt, clickInfo); - this._previousPickResult = this._currentPickResult; - if (this._swipeButtonPressed === evt.button) { - this._isSwiping = false; - this._swipeButtonPressed = -1; - } - }); - }; - this._onKeyDown = (evt) => { - const type = KeyboardEventTypes.KEYDOWN; - if (scene.onPreKeyboardObservable.hasObservers()) { - const pi = new KeyboardInfoPre(type, evt); - scene.onPreKeyboardObservable.notifyObservers(pi, type); - if (pi.skipOnKeyboardObservable) { - return; - } - } - if (scene.onKeyboardObservable.hasObservers()) { - const pi = new KeyboardInfo(type, evt); - scene.onKeyboardObservable.notifyObservers(pi, type); - } - if (scene.actionManager) { - scene.actionManager.processTrigger(14, ActionEvent.CreateNewFromScene(scene, evt)); - } - }; - this._onKeyUp = (evt) => { - const type = KeyboardEventTypes.KEYUP; - if (scene.onPreKeyboardObservable.hasObservers()) { - const pi = new KeyboardInfoPre(type, evt); - scene.onPreKeyboardObservable.notifyObservers(pi, type); - if (pi.skipOnKeyboardObservable) { - return; - } - } - if (scene.onKeyboardObservable.hasObservers()) { - const pi = new KeyboardInfo(type, evt); - scene.onKeyboardObservable.notifyObservers(pi, type); - } - if (scene.actionManager) { - scene.actionManager.processTrigger(15, ActionEvent.CreateNewFromScene(scene, evt)); - } - }; - // If a device connects that we can handle, wire up the observable - this._deviceSourceManager.onDeviceConnectedObservable.add((deviceSource) => { - if (deviceSource.deviceType === DeviceType.Mouse) { - deviceSource.onInputChangedObservable.add((eventData) => { - if (eventData.inputIndex === PointerInput.LeftClick || - eventData.inputIndex === PointerInput.MiddleClick || - eventData.inputIndex === PointerInput.RightClick || - eventData.inputIndex === PointerInput.BrowserBack || - eventData.inputIndex === PointerInput.BrowserForward) { - if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) { - this._onPointerDown(eventData); - } - else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) { - this._onPointerUp(eventData); - } - } - else if (attachMove) { - if (eventData.inputIndex === PointerInput.Move) { - this._onPointerMove(eventData); - } - else if (eventData.inputIndex === PointerInput.MouseWheelX || - eventData.inputIndex === PointerInput.MouseWheelY || - eventData.inputIndex === PointerInput.MouseWheelZ) { - this._onPointerMove(eventData); - } - } - }); - } - else if (deviceSource.deviceType === DeviceType.Touch) { - deviceSource.onInputChangedObservable.add((eventData) => { - if (eventData.inputIndex === PointerInput.LeftClick) { - if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) { - this._onPointerDown(eventData); - if (this._totalPointersPressed > 1) { - this._isMultiTouchGesture = true; - } - } - else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) { - this._onPointerUp(eventData); - if (this._totalPointersPressed === 0) { - this._isMultiTouchGesture = false; - } - } - } - if (attachMove && eventData.inputIndex === PointerInput.Move) { - this._onPointerMove(eventData); - } - }); - } - else if (deviceSource.deviceType === DeviceType.Keyboard) { - deviceSource.onInputChangedObservable.add((eventData) => { - if (eventData.type === "keydown") { - this._onKeyDown(eventData); - } - else if (eventData.type === "keyup") { - this._onKeyUp(eventData); - } - }); - } - }); - this._alreadyAttached = true; - } - /** - * Detaches all event handlers - */ - detachControl() { - if (this._alreadyAttached) { - this._deviceSourceManager.dispose(); - this._deviceSourceManager = null; - // Cursor - if (this._alreadyAttachedTo && !this._scene.doNotHandleCursors) { - this._alreadyAttachedTo.style.cursor = this._scene.defaultCursor; - } - this._alreadyAttached = false; - this._alreadyAttachedTo = null; - } - } - /** - * Force the value of meshUnderPointer - * @param mesh - defines the mesh to use - * @param pointerId - optional pointer id when using more than one pointer. Defaults to 0 - * @param pickResult - optional pickingInfo data used to find mesh - * @param evt - optional pointer event - */ - setPointerOverMesh(mesh, pointerId = 0, pickResult, evt) { - if (this._meshUnderPointerId[pointerId] === mesh && (!mesh || !mesh._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting)) { - return; - } - const underPointerMesh = this._meshUnderPointerId[pointerId]; - let actionManager; - if (underPointerMesh) { - actionManager = underPointerMesh._getActionManagerForTrigger(10); - if (actionManager) { - actionManager.processTrigger(10, ActionEvent.CreateNew(underPointerMesh, evt, { pointerId })); - } - } - if (mesh) { - this._meshUnderPointerId[pointerId] = mesh; - this._pointerOverMesh = mesh; - actionManager = mesh._getActionManagerForTrigger(9); - if (actionManager) { - actionManager.processTrigger(9, ActionEvent.CreateNew(mesh, evt, { pointerId, pickResult })); - } - } - else { - delete this._meshUnderPointerId[pointerId]; - this._pointerOverMesh = null; - } - } - /** - * Gets the mesh under the pointer - * @returns a Mesh or null if no mesh is under the pointer - */ - getPointerOverMesh() { - return this.meshUnderPointer; - } - /** - * @param mesh - Mesh to invalidate - * @internal - */ - _invalidateMesh(mesh) { - if (this._pointerOverMesh === mesh) { - this._pointerOverMesh = null; - } - if (this._pickedDownMesh === mesh) { - this._pickedDownMesh = null; - } - if (this._pickedUpMesh === mesh) { - this._pickedUpMesh = null; - } - for (const pointerId in this._meshUnderPointerId) { - if (this._meshUnderPointerId[pointerId] === mesh) { - delete this._meshUnderPointerId[pointerId]; - } - } - } -} -/** The distance in pixel that you have to move to prevent some events */ -InputManager.DragMovementThreshold = 10; // in pixels -/** Time in milliseconds to wait to raise long press events if button is still pressed */ -InputManager.LongPressDelay = 500; // in milliseconds -/** Time in milliseconds with two consecutive clicks will be considered as a double click */ -InputManager.DoubleClickDelay = 300; // in milliseconds -/** - * This flag will modify the behavior so that, when true, a click will happen if and only if - * another click DOES NOT happen within the DoubleClickDelay time frame. If another click does - * happen within that time frame, the first click will not fire an event and and a double click will occur. - */ -InputManager.ExclusiveDoubleClickMode = false; -//# sourceMappingURL=scene.inputManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/perfCounter.js - -/** - * This class is used to track a performance counter which is number based. - * The user has access to many properties which give statistics of different nature. - * - * The implementer can track two kinds of Performance Counter: time and count. - * 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. - * 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. - */ -class perfCounter_PerfCounter { - /** - * Returns the smallest value ever - */ - get min() { - return this._min; - } - /** - * Returns the biggest value ever - */ - get max() { - return this._max; - } - /** - * Returns the average value since the performance counter is running - */ - get average() { - return this._average; - } - /** - * Returns the average value of the last second the counter was monitored - */ - get lastSecAverage() { - return this._lastSecAverage; - } - /** - * Returns the current value - */ - get current() { - return this._current; - } - /** - * Gets the accumulated total - */ - get total() { - return this._totalAccumulated; - } - /** - * Gets the total value count - */ - get count() { - return this._totalValueCount; - } - /** - * Creates a new counter - */ - 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; - } - /** - * Call this method to start monitoring a new frame. - * 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. - */ - fetchNewFrame() { - this._totalValueCount++; - this._current = 0; - this._lastSecValueCount++; - } - /** - * Call this method to monitor a count of something (e.g. mesh drawn in viewport count) - * @param newCount the count value to add to the monitored count - * @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. - */ - addCount(newCount, fetchResult) { - if (!perfCounter_PerfCounter.Enabled) { - return; - } - this._current += newCount; - if (fetchResult) { - this._fetchResult(); - } - } - /** - * Start monitoring this performance counter - */ - beginMonitoring() { - if (!perfCounter_PerfCounter.Enabled) { - return; - } - this._startMonitoringTime = precisionDate_PrecisionDate.Now; - } - /** - * Compute the time lapsed since the previous beginMonitoring() call. - * @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 - */ - endMonitoring(newFrame = true) { - if (!perfCounter_PerfCounter.Enabled) { - return; - } - if (newFrame) { - this.fetchNewFrame(); - } - const currentTime = precisionDate_PrecisionDate.Now; - this._current = currentTime - this._startMonitoringTime; - if (newFrame) { - this._fetchResult(); - } - } - /** - * Call this method to end the monitoring of a frame. - * 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. - */ - endFrame() { - this._fetchResult(); - } - _fetchResult() { - this._totalAccumulated += this._current; - this._lastSecAccumulated += this._current; - // Min/Max update - this._min = Math.min(this._min, this._current); - this._max = Math.max(this._max, this._current); - this._average = this._totalAccumulated / this._totalValueCount; - // Reset last sec? - const now = precisionDate_PrecisionDate.Now; - if (now - this._lastSecTime > 1000) { - this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount; - this._lastSecTime = now; - this._lastSecAccumulated = 0; - this._lastSecValueCount = 0; - } - } -} -/** - * Gets or sets a global boolean to turn on and off all the counters - */ -perfCounter_PerfCounter.Enabled = true; -//# sourceMappingURL=perfCounter.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.plane.js - -/** - * Represents a plane by the equation ax + by + cz + d = 0 - */ -class math_plane_Plane { - /** - * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0 - * @param a a component of the plane - * @param b b component of the plane - * @param c c component of the plane - * @param d d component of the plane - */ - constructor(a, b, c, d) { - this.normal = new math_vector_Vector3(a, b, c); - this.d = d; - } - /** - * @returns the plane coordinates as a new array of 4 elements [a, b, c, d]. - */ - asArray() { - return [this.normal.x, this.normal.y, this.normal.z, this.d]; - } - // Methods - /** - * @returns a new plane copied from the current Plane. - */ - clone() { - return new math_plane_Plane(this.normal.x, this.normal.y, this.normal.z, this.d); - } - /** - * @returns the string "Plane". - */ - getClassName() { - return "Plane"; - } - /** - * @returns the Plane hash code. - */ - getHashCode() { - let hash = this.normal.getHashCode(); - hash = (hash * 397) ^ (this.d | 0); - return hash; - } - /** - * Normalize the current Plane in place. - * @returns the updated Plane. - */ - normalize() { - const norm = Math.sqrt(this.normal.x * this.normal.x + this.normal.y * this.normal.y + this.normal.z * this.normal.z); - let magnitude = 0.0; - if (norm !== 0) { - magnitude = 1.0 / norm; - } - this.normal.x *= magnitude; - this.normal.y *= magnitude; - this.normal.z *= magnitude; - this.d *= magnitude; - return this; - } - /** - * Applies a transformation the plane and returns the result - * @param transformation the transformation matrix to be applied to the plane - * @returns a new Plane as the result of the transformation of the current Plane by the given matrix. - */ - transform(transformation) { - const invertedMatrix = math_plane_Plane._TmpMatrix; - transformation.invertToRef(invertedMatrix); - const m = invertedMatrix.m; - const x = this.normal.x; - const y = this.normal.y; - const z = this.normal.z; - const d = this.d; - const normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3]; - const normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7]; - const normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11]; - const finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15]; - return new math_plane_Plane(normalX, normalY, normalZ, finalD); - } - /** - * Compute the dot product between the point and the plane normal - * @param point point to calculate the dot product with - * @returns the dot product (float) of the point coordinates and the plane normal. - */ - dotCoordinate(point) { - return this.normal.x * point.x + this.normal.y * point.y + this.normal.z * point.z + this.d; - } - /** - * Updates the current Plane from the plane defined by the three given points. - * @param point1 one of the points used to construct the plane - * @param point2 one of the points used to construct the plane - * @param point3 one of the points used to construct the plane - * @returns the updated Plane. - */ - copyFromPoints(point1, point2, point3) { - const x1 = point2.x - point1.x; - const y1 = point2.y - point1.y; - const z1 = point2.z - point1.z; - const x2 = point3.x - point1.x; - const y2 = point3.y - point1.y; - const z2 = point3.z - point1.z; - const yz = y1 * z2 - z1 * y2; - const xz = z1 * x2 - x1 * z2; - const xy = x1 * y2 - y1 * x2; - const pyth = Math.sqrt(yz * yz + xz * xz + xy * xy); - let invPyth; - if (pyth !== 0) { - invPyth = 1.0 / pyth; - } - else { - invPyth = 0.0; - } - this.normal.x = yz * invPyth; - this.normal.y = xz * invPyth; - this.normal.z = xy * invPyth; - this.d = -(this.normal.x * point1.x + this.normal.y * point1.y + this.normal.z * point1.z); - return this; - } - /** - * 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). - * Note that for this function to work as expected you should make sure that: - * - direction and the plane normal are normalized - * - epsilon is a number just bigger than -1, something like -0.99 for eg - * @param direction the direction to check if the plane is facing - * @param epsilon value the dot product is compared against (returns true if dot <= epsilon) - * @returns True if the plane is facing the given direction - */ - isFrontFacingTo(direction, epsilon) { - const dot = math_vector_Vector3.Dot(this.normal, direction); - return dot <= epsilon; - } - /** - * Calculates the distance to a point - * @param point point to calculate distance to - * @returns the signed distance (float) from the given point to the Plane. - */ - signedDistanceTo(point) { - return math_vector_Vector3.Dot(point, this.normal) + this.d; - } - // Statics - /** - * Creates a plane from an array - * @param array the array to create a plane from - * @returns a new Plane from the given array. - */ - static FromArray(array) { - return new math_plane_Plane(array[0], array[1], array[2], array[3]); - } - /** - * Creates a plane from three points - * @param point1 point used to create the plane - * @param point2 point used to create the plane - * @param point3 point used to create the plane - * @returns a new Plane defined by the three given points. - */ - static FromPoints(point1, point2, point3) { - const result = new math_plane_Plane(0.0, 0.0, 0.0, 0.0); - result.copyFromPoints(point1, point2, point3); - return result; - } - /** - * Creates a plane from an origin point and a normal - * @param origin origin of the plane to be constructed - * @param normal normal of the plane to be constructed - * @returns a new Plane the normal vector to this plane at the given origin point. - * Note : the vector "normal" is updated because normalized. - */ - static FromPositionAndNormal(origin, normal) { - const result = new math_plane_Plane(0.0, 0.0, 0.0, 0.0); - normal.normalize(); - result.normal = normal; - result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z); - return result; - } - /** - * Calculates the distance from a plane and a point - * @param origin origin of the plane to be constructed - * @param normal normal of the plane to be constructed - * @param point point to calculate distance to - * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point. - */ - static SignedDistanceToPlaneFromPositionAndNormal(origin, normal, point) { - const d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z); - return math_vector_Vector3.Dot(point, normal) + d; - } -} -math_plane_Plane._TmpMatrix = math_vector_Matrix.Identity(); -//# sourceMappingURL=math.plane.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.frustum.js - -/** - * Represents a camera frustum - */ -class Frustum { - /** - * Gets the planes representing the frustum - * @param transform matrix to be applied to the returned planes - * @returns a new array of 6 Frustum planes computed by the given transformation matrix. - */ - static GetPlanes(transform) { - const frustumPlanes = []; - for (let index = 0; index < 6; index++) { - frustumPlanes.push(new math_plane_Plane(0.0, 0.0, 0.0, 0.0)); - } - Frustum.GetPlanesToRef(transform, frustumPlanes); - return frustumPlanes; - } - /** - * Gets the near frustum plane transformed by the transform matrix - * @param transform transformation matrix to be applied to the resulting frustum plane - * @param frustumPlane the resulting frustum plane - */ - static GetNearPlaneToRef(transform, frustumPlane) { - const m = transform.m; - frustumPlane.normal.x = m[3] + m[2]; - frustumPlane.normal.y = m[7] + m[6]; - frustumPlane.normal.z = m[11] + m[10]; - frustumPlane.d = m[15] + m[14]; - frustumPlane.normalize(); - } - /** - * Gets the far frustum plane transformed by the transform matrix - * @param transform transformation matrix to be applied to the resulting frustum plane - * @param frustumPlane the resulting frustum plane - */ - static GetFarPlaneToRef(transform, frustumPlane) { - const m = transform.m; - frustumPlane.normal.x = m[3] - m[2]; - frustumPlane.normal.y = m[7] - m[6]; - frustumPlane.normal.z = m[11] - m[10]; - frustumPlane.d = m[15] - m[14]; - frustumPlane.normalize(); - } - /** - * Gets the left frustum plane transformed by the transform matrix - * @param transform transformation matrix to be applied to the resulting frustum plane - * @param frustumPlane the resulting frustum plane - */ - static GetLeftPlaneToRef(transform, frustumPlane) { - const m = transform.m; - frustumPlane.normal.x = m[3] + m[0]; - frustumPlane.normal.y = m[7] + m[4]; - frustumPlane.normal.z = m[11] + m[8]; - frustumPlane.d = m[15] + m[12]; - frustumPlane.normalize(); - } - /** - * Gets the right frustum plane transformed by the transform matrix - * @param transform transformation matrix to be applied to the resulting frustum plane - * @param frustumPlane the resulting frustum plane - */ - static GetRightPlaneToRef(transform, frustumPlane) { - const m = transform.m; - frustumPlane.normal.x = m[3] - m[0]; - frustumPlane.normal.y = m[7] - m[4]; - frustumPlane.normal.z = m[11] - m[8]; - frustumPlane.d = m[15] - m[12]; - frustumPlane.normalize(); - } - /** - * Gets the top frustum plane transformed by the transform matrix - * @param transform transformation matrix to be applied to the resulting frustum plane - * @param frustumPlane the resulting frustum plane - */ - static GetTopPlaneToRef(transform, frustumPlane) { - const m = transform.m; - frustumPlane.normal.x = m[3] - m[1]; - frustumPlane.normal.y = m[7] - m[5]; - frustumPlane.normal.z = m[11] - m[9]; - frustumPlane.d = m[15] - m[13]; - frustumPlane.normalize(); - } - /** - * Gets the bottom frustum plane transformed by the transform matrix - * @param transform transformation matrix to be applied to the resulting frustum plane - * @param frustumPlane the resulting frustum plane - */ - static GetBottomPlaneToRef(transform, frustumPlane) { - const m = transform.m; - frustumPlane.normal.x = m[3] + m[1]; - frustumPlane.normal.y = m[7] + m[5]; - frustumPlane.normal.z = m[11] + m[9]; - frustumPlane.d = m[15] + m[13]; - frustumPlane.normalize(); - } - /** - * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix. - * @param transform transformation matrix to be applied to the resulting frustum planes - * @param frustumPlanes the resulting frustum planes - */ - static GetPlanesToRef(transform, frustumPlanes) { - // Near - Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]); - // Far - Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]); - // Left - Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]); - // Right - Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]); - // Top - Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]); - // Bottom - Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]); - } - /** - * Tests if a point is located between the frustum planes. - * @param point defines the point to test - * @param frustumPlanes defines the frustum planes to test - * @returns true if the point is located between the frustum planes - */ - static IsPointInFrustum(point, frustumPlanes) { - for (let i = 0; i < 6; i++) { - if (frustumPlanes[i].dotCoordinate(point) < 0) { - return false; - } - } - return true; - } -} -//# sourceMappingURL=math.frustum.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/uniqueIdGenerator.js -/** - * Helper class used to generate session unique ID - */ -class UniqueIdGenerator { - /** - * Gets an unique (relatively to the current scene) Id - */ - static get UniqueId() { - const result = this._UniqueIdCounter; - this._UniqueIdCounter++; - return result; - } -} -// Statics -UniqueIdGenerator._UniqueIdCounter = 1; -//# sourceMappingURL=uniqueIdGenerator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/lightConstants.js -/** Defines the cross module constantsused by lights to avoid circular dependencies */ -class LightConstants { - /** - * Sort function to order lights for rendering. - * @param a First Light object to compare to second. - * @param b Second Light object to compare first. - * @returns -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b. - */ - static CompareLightsPriority(a, b) { - //shadow-casting lights have priority over non-shadow-casting lights - //the renderPriority is a secondary sort criterion - if (a.shadowEnabled !== b.shadowEnabled) { - return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0); - } - return b.renderPriority - a.renderPriority; - } -} -/** - * Falloff Default: light is falling off following the material specification: - * standard material is using standard falloff whereas pbr material can request special falloff per materials. - */ -LightConstants.FALLOFF_DEFAULT = 0; -/** - * Falloff Physical: light is falling off following the inverse squared distance law. - */ -LightConstants.FALLOFF_PHYSICAL = 1; -/** - * Falloff gltf: light is falling off as described in the gltf moving to PBR document - * to enhance interoperability with other engines. - */ -LightConstants.FALLOFF_GLTF = 2; -/** - * Falloff Standard: light is falling off like in the standard material - * to enhance interoperability with other materials. - */ -LightConstants.FALLOFF_STANDARD = 3; -//lightmapMode Consts -/** - * If every light affecting the material is in this lightmapMode, - * material.lightmapTexture adds or multiplies - * (depends on material.useLightmapAsShadowmap) - * after every other light calculations. - */ -LightConstants.LIGHTMAP_DEFAULT = 0; -/** - * material.lightmapTexture as only diffuse lighting from this light - * adds only specular lighting from this light - * adds dynamic shadows - */ -LightConstants.LIGHTMAP_SPECULAR = 1; -/** - * material.lightmapTexture as only lighting - * no light calculation from this light - * only adds dynamic shadows from this light - */ -LightConstants.LIGHTMAP_SHADOWSONLY = 2; -// Intensity Mode Consts -/** - * Each light type uses the default quantity according to its type: - * point/spot lights use luminous intensity - * directional lights use illuminance - */ -LightConstants.INTENSITYMODE_AUTOMATIC = 0; -/** - * lumen (lm) - */ -LightConstants.INTENSITYMODE_LUMINOUSPOWER = 1; -/** - * candela (lm/sr) - */ -LightConstants.INTENSITYMODE_LUMINOUSINTENSITY = 2; -/** - * lux (lm/m^2) - */ -LightConstants.INTENSITYMODE_ILLUMINANCE = 3; -/** - * nit (cd/m^2) - */ -LightConstants.INTENSITYMODE_LUMINANCE = 4; -// Light types ids const. -/** - * Light type const id of the point light. - */ -LightConstants.LIGHTTYPEID_POINTLIGHT = 0; -/** - * Light type const id of the directional light. - */ -LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT = 1; -/** - * Light type const id of the spot light. - */ -LightConstants.LIGHTTYPEID_SPOTLIGHT = 2; -/** - * Light type const id of the hemispheric light. - */ -LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT = 3; -//# sourceMappingURL=lightConstants.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Inputs/pointerPickingConfiguration.js -/** - * Class used to store configuration data associated with pointer picking - */ -class PointerPickingConfiguration { - constructor() { - /** - * Gets or sets a predicate used to select candidate meshes for a pointer down event - */ - this.pointerDownFastCheck = false; - /** - * Gets or sets a predicate used to select candidate meshes for a pointer up event - */ - this.pointerUpFastCheck = false; - /** - * Gets or sets a predicate used to select candidate meshes for a pointer move event - */ - this.pointerMoveFastCheck = false; - /** - * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer move event occurs. - */ - this.skipPointerMovePicking = false; - /** - * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer down event occurs. - */ - this.skipPointerDownPicking = false; - /** - * 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. - */ - this.skipPointerUpPicking = false; - } -} -//# sourceMappingURL=pointerPickingConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/scene.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/** - * Define how the scene should favor performance over ease of use - */ -var ScenePerformancePriority; -(function (ScenePerformancePriority) { - /** Default mode. No change. Performance will be treated as less important than backward compatibility */ - ScenePerformancePriority[ScenePerformancePriority["BackwardCompatible"] = 0] = "BackwardCompatible"; - /** Some performance options will be turned on trying to strike a balance between perf and ease of use */ - ScenePerformancePriority[ScenePerformancePriority["Intermediate"] = 1] = "Intermediate"; - /** Performance will be top priority */ - ScenePerformancePriority[ScenePerformancePriority["Aggressive"] = 2] = "Aggressive"; -})(ScenePerformancePriority || (ScenePerformancePriority = {})); -/** - * Represents a scene to be rendered by the engine. - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene - */ -class scene_Scene extends AbstractScene { - /** - * Factory used to create the default material. - * @param scene The scene to create the material for - * @returns The default material - */ - static DefaultMaterialFactory(scene) { - throw _WarnImport("StandardMaterial"); - } - /** - * Factory used to create the a collision coordinator. - * @returns The collision coordinator - */ - static CollisionCoordinatorFactory() { - throw _WarnImport("DefaultCollisionCoordinator"); - } - /** - * Texture used in all pbr material as the reflection texture. - * As in the majority of the scene they are the same (exception for multi room and so on), - * this is easier to reference from here than from all the materials. - */ - get environmentTexture() { - return this._environmentTexture; - } - /** - * Texture used in all pbr material as the reflection texture. - * As in the majority of the scene they are the same (exception for multi room and so on), - * this is easier to set here than in all the materials. - */ - set environmentTexture(value) { - if (this._environmentTexture === value) { - return; - } - this._environmentTexture = value; - this.markAllMaterialsAsDirty(1); - } - /** - * Default image processing configuration used either in the rendering - * Forward main pass or through the imageProcessingPostProcess if present. - * As in the majority of the scene they are the same (exception for multi camera), - * this is easier to reference from here than from all the materials and post process. - * - * No setter as we it is a shared configuration, you can set the values instead. - */ - get imageProcessingConfiguration() { - return this._imageProcessingConfiguration; - } - /** - * Gets or sets a value indicating how to treat performance relatively to ease of use and backward compatibility - */ - get performancePriority() { - return this._performancePriority; - } - set performancePriority(value) { - if (value === this._performancePriority) { - return; - } - this._performancePriority = value; - switch (value) { - case ScenePerformancePriority.BackwardCompatible: - this.skipFrustumClipping = false; - this._renderingManager.maintainStateBetweenFrames = false; - this.skipPointerMovePicking = false; - this.autoClear = true; - break; - case ScenePerformancePriority.Intermediate: - this.skipFrustumClipping = false; - this._renderingManager.maintainStateBetweenFrames = false; - this.skipPointerMovePicking = true; - this.autoClear = false; - break; - case ScenePerformancePriority.Aggressive: - this.skipFrustumClipping = true; - this._renderingManager.maintainStateBetweenFrames = true; - this.skipPointerMovePicking = true; - this.autoClear = false; - break; - } - this.onScenePerformancePriorityChangedObservable.notifyObservers(value); - } - /** - * Gets or sets a boolean indicating if all rendering must be done in wireframe - */ - set forceWireframe(value) { - if (this._forceWireframe === value) { - return; - } - this._forceWireframe = value; - this.markAllMaterialsAsDirty(16); - } - get forceWireframe() { - return this._forceWireframe; - } - /** - * Gets or sets a boolean indicating if we should skip the frustum clipping part of the active meshes selection - */ - set skipFrustumClipping(value) { - if (this._skipFrustumClipping === value) { - return; - } - this._skipFrustumClipping = value; - } - get skipFrustumClipping() { - return this._skipFrustumClipping; - } - /** - * Gets or sets a boolean indicating if all rendering must be done in point cloud - */ - set forcePointsCloud(value) { - if (this._forcePointsCloud === value) { - return; - } - this._forcePointsCloud = value; - this.markAllMaterialsAsDirty(16); - } - get forcePointsCloud() { - return this._forcePointsCloud; - } - /** - * Gets or sets the animation properties override - */ - get animationPropertiesOverride() { - return this._animationPropertiesOverride; - } - set animationPropertiesOverride(value) { - this._animationPropertiesOverride = value; - } - /** Sets a function to be executed when this scene is disposed. */ - set onDispose(callback) { - if (this._onDisposeObserver) { - this.onDisposeObservable.remove(this._onDisposeObserver); - } - this._onDisposeObserver = this.onDisposeObservable.add(callback); - } - /** Sets a function to be executed before rendering this scene */ - set beforeRender(callback) { - if (this._onBeforeRenderObserver) { - this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); - } - if (callback) { - this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); - } - } - /** Sets a function to be executed after rendering this scene */ - set afterRender(callback) { - if (this._onAfterRenderObserver) { - this.onAfterRenderObservable.remove(this._onAfterRenderObserver); - } - if (callback) { - this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); - } - } - /** Sets a function to be executed before rendering a camera*/ - set beforeCameraRender(callback) { - if (this._onBeforeCameraRenderObserver) { - this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); - } - this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback); - } - /** Sets a function to be executed after rendering a camera*/ - set afterCameraRender(callback) { - if (this._onAfterCameraRenderObserver) { - this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver); - } - this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback); - } - /** - * Gets or sets a predicate used to select candidate meshes for a pointer down event - */ - get pointerDownPredicate() { - return this._pointerPickingConfiguration.pointerDownPredicate; - } - set pointerDownPredicate(value) { - this._pointerPickingConfiguration.pointerDownPredicate = value; - } - /** - * Gets or sets a predicate used to select candidate meshes for a pointer up event - */ - get pointerUpPredicate() { - return this._pointerPickingConfiguration.pointerUpPredicate; - } - set pointerUpPredicate(value) { - this._pointerPickingConfiguration.pointerUpPredicate = value; - } - /** - * Gets or sets a predicate used to select candidate meshes for a pointer move event - */ - get pointerMovePredicate() { - return this._pointerPickingConfiguration.pointerMovePredicate; - } - set pointerMovePredicate(value) { - this._pointerPickingConfiguration.pointerMovePredicate = value; - } - /** - * Gets or sets a predicate used to select candidate meshes for a pointer down event - */ - get pointerDownFastCheck() { - return this._pointerPickingConfiguration.pointerDownFastCheck; - } - set pointerDownFastCheck(value) { - this._pointerPickingConfiguration.pointerDownFastCheck = value; - } - /** - * Gets or sets a predicate used to select candidate meshes for a pointer up event - */ - get pointerUpFastCheck() { - return this._pointerPickingConfiguration.pointerUpFastCheck; - } - set pointerUpFastCheck(value) { - this._pointerPickingConfiguration.pointerUpFastCheck = value; - } - /** - * Gets or sets a predicate used to select candidate meshes for a pointer move event - */ - get pointerMoveFastCheck() { - return this._pointerPickingConfiguration.pointerMoveFastCheck; - } - set pointerMoveFastCheck(value) { - this._pointerPickingConfiguration.pointerMoveFastCheck = value; - } - /** - * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer move event occurs. - */ - get skipPointerMovePicking() { - return this._pointerPickingConfiguration.skipPointerMovePicking; - } - set skipPointerMovePicking(value) { - this._pointerPickingConfiguration.skipPointerMovePicking = value; - } - /** - * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer down event occurs. - */ - get skipPointerDownPicking() { - return this._pointerPickingConfiguration.skipPointerDownPicking; - } - set skipPointerDownPicking(value) { - this._pointerPickingConfiguration.skipPointerDownPicking = value; - } - /** - * 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. - */ - get skipPointerUpPicking() { - return this._pointerPickingConfiguration.skipPointerUpPicking; - } - set skipPointerUpPicking(value) { - this._pointerPickingConfiguration.skipPointerUpPicking = value; - } - /** - * Gets the pointer coordinates without any translation (ie. straight out of the pointer event) - */ - get unTranslatedPointer() { - return this._inputManager.unTranslatedPointer; - } - /** - * Gets or sets the distance in pixel that you have to move to prevent some events. Default is 10 pixels - */ - static get DragMovementThreshold() { - return InputManager.DragMovementThreshold; - } - static set DragMovementThreshold(value) { - InputManager.DragMovementThreshold = value; - } - /** - * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 500 ms - */ - static get LongPressDelay() { - return InputManager.LongPressDelay; - } - static set LongPressDelay(value) { - InputManager.LongPressDelay = value; - } - /** - * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 300 ms - */ - static get DoubleClickDelay() { - return InputManager.DoubleClickDelay; - } - static set DoubleClickDelay(value) { - InputManager.DoubleClickDelay = value; - } - /** If you need to check double click without raising a single click at first click, enable this flag */ - static get ExclusiveDoubleClickMode() { - return InputManager.ExclusiveDoubleClickMode; - } - static set ExclusiveDoubleClickMode(value) { - InputManager.ExclusiveDoubleClickMode = value; - } - /** - * Bind the current view position to an effect. - * @param effect The effect to be bound - * @param variableName name of the shader variable that will hold the eye position - * @param isVector3 true to indicates that variableName is a Vector3 and not a Vector4 - * @returns the computed eye position - */ - bindEyePosition(effect, variableName = "vEyePosition", isVector3 = false) { - var _a; - const eyePosition = this._forcedViewPosition - ? this._forcedViewPosition - : this._mirroredCameraPosition - ? this._mirroredCameraPosition - : (_a = this.activeCamera.globalPosition) !== null && _a !== void 0 ? _a : this.activeCamera.devicePosition; - const invertNormal = this.useRightHandedSystem === (this._mirroredCameraPosition != null); - math_vector_TmpVectors.Vector4[0].set(eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1); - if (effect) { - if (isVector3) { - effect.setFloat3(variableName, math_vector_TmpVectors.Vector4[0].x, math_vector_TmpVectors.Vector4[0].y, math_vector_TmpVectors.Vector4[0].z); - } - else { - effect.setVector4(variableName, math_vector_TmpVectors.Vector4[0]); - } - } - return math_vector_TmpVectors.Vector4[0]; - } - /** - * Update the scene ubo before it can be used in rendering processing - * @returns the scene UniformBuffer - */ - finalizeSceneUbo() { - const ubo = this.getSceneUniformBuffer(); - const eyePosition = this.bindEyePosition(null); - ubo.updateFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, eyePosition.w); - ubo.update(); - return ubo; - } - /** - * Gets or sets a boolean indicating if the scene must use right-handed coordinates system - */ - set useRightHandedSystem(value) { - if (this._useRightHandedSystem === value) { - return; - } - this._useRightHandedSystem = value; - this.markAllMaterialsAsDirty(16); - } - get useRightHandedSystem() { - return this._useRightHandedSystem; - } - /** - * Sets the step Id used by deterministic lock step - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - * @param newStepId defines the step Id - */ - setStepId(newStepId) { - this._currentStepId = newStepId; - } - /** - * Gets the step Id used by deterministic lock step - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - * @returns the step Id - */ - getStepId() { - return this._currentStepId; - } - /** - * Gets the internal step used by deterministic lock step - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - * @returns the internal step - */ - getInternalStep() { - return this._currentInternalStep; - } - /** - * Gets or sets a boolean indicating if fog is enabled on this scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog - * (Default is true) - */ - set fogEnabled(value) { - if (this._fogEnabled === value) { - return; - } - this._fogEnabled = value; - this.markAllMaterialsAsDirty(16); - } - get fogEnabled() { - return this._fogEnabled; - } - /** - * Gets or sets the fog mode to use - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog - * | mode | value | - * | --- | --- | - * | FOGMODE_NONE | 0 | - * | FOGMODE_EXP | 1 | - * | FOGMODE_EXP2 | 2 | - * | FOGMODE_LINEAR | 3 | - */ - set fogMode(value) { - if (this._fogMode === value) { - return; - } - this._fogMode = value; - this.markAllMaterialsAsDirty(16); - } - get fogMode() { - return this._fogMode; - } - /** - * Flag indicating that the frame buffer binding is handled by another component - */ - get prePass() { - return !!this.prePassRenderer && this.prePassRenderer.defaultRT.enabled; - } - /** - * Gets or sets a boolean indicating if shadows are enabled on this scene - */ - set shadowsEnabled(value) { - if (this._shadowsEnabled === value) { - return; - } - this._shadowsEnabled = value; - this.markAllMaterialsAsDirty(2); - } - get shadowsEnabled() { - return this._shadowsEnabled; - } - /** - * Gets or sets a boolean indicating if lights are enabled on this scene - */ - set lightsEnabled(value) { - if (this._lightsEnabled === value) { - return; - } - this._lightsEnabled = value; - this.markAllMaterialsAsDirty(2); - } - get lightsEnabled() { - return this._lightsEnabled; - } - /** All of the active cameras added to this scene. */ - get activeCameras() { - return this._activeCameras; - } - set activeCameras(cameras) { - if (this._unObserveActiveCameras) { - this._unObserveActiveCameras(); - this._unObserveActiveCameras = null; - } - if (cameras) { - this._unObserveActiveCameras = _ObserveArray(cameras, () => { - this.onActiveCamerasChanged.notifyObservers(this); - }); - } - this._activeCameras = cameras; - } - /** Gets or sets the current active camera */ - get activeCamera() { - return this._activeCamera; - } - set activeCamera(value) { - if (value === this._activeCamera) { - return; - } - this._activeCamera = value; - this.onActiveCameraChanged.notifyObservers(this); - } - /** The default material used on meshes when no material is affected */ - get defaultMaterial() { - if (!this._defaultMaterial) { - this._defaultMaterial = scene_Scene.DefaultMaterialFactory(this); - } - return this._defaultMaterial; - } - /** The default material used on meshes when no material is affected */ - set defaultMaterial(value) { - this._defaultMaterial = value; - } - /** - * Gets or sets a boolean indicating if textures are enabled on this scene - */ - set texturesEnabled(value) { - if (this._texturesEnabled === value) { - return; - } - this._texturesEnabled = value; - this.markAllMaterialsAsDirty(1); - } - get texturesEnabled() { - return this._texturesEnabled; - } - /** - * Gets or sets a boolean indicating if skeletons are enabled on this scene - */ - set skeletonsEnabled(value) { - if (this._skeletonsEnabled === value) { - return; - } - this._skeletonsEnabled = value; - this.markAllMaterialsAsDirty(8); - } - get skeletonsEnabled() { - return this._skeletonsEnabled; - } - /** @internal */ - get collisionCoordinator() { - if (!this._collisionCoordinator) { - this._collisionCoordinator = scene_Scene.CollisionCoordinatorFactory(); - this._collisionCoordinator.init(this); - } - return this._collisionCoordinator; - } - /** - * Gets the scene's rendering manager - */ - get renderingManager() { - return this._renderingManager; - } - /** - * Gets the list of frustum planes (built from the active camera) - */ - get frustumPlanes() { - return this._frustumPlanes; - } - /** - * Registers the transient components if needed. - */ - _registerTransientComponents() { - // Register components that have been associated lately to the scene. - if (this._transientComponents.length > 0) { - for (const component of this._transientComponents) { - component.register(); - } - this._transientComponents.length = 0; - } - } - /** - * @internal - * Add a component to the scene. - * Note that the ccomponent could be registered on th next frame if this is called after - * the register component stage. - * @param component Defines the component to add to the scene - */ - _addComponent(component) { - this._components.push(component); - this._transientComponents.push(component); - const serializableComponent = component; - if (serializableComponent.addFromContainer && serializableComponent.serialize) { - this._serializableComponents.push(serializableComponent); - } - } - /** - * @internal - * Gets a component from the scene. - * @param name defines the name of the component to retrieve - * @returns the component or null if not present - */ - _getComponent(name) { - for (const component of this._components) { - if (component.name === name) { - return component; - } - } - return null; - } - /** - * Creates a new Scene - * @param engine defines the engine to use to render this scene - * @param options defines the scene options - */ - constructor(engine, options) { - super(); - // Members - /** @internal */ - this._inputManager = new InputManager(this); - /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */ - this.cameraToUseForPointers = null; - /** @internal */ - this._isScene = true; - /** @internal */ - this._blockEntityCollection = false; - /** - * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame - */ - this.autoClear = true; - /** - * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame - */ - this.autoClearDepthAndStencil = true; - /** - * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0)) - */ - this.clearColor = new math_color_Color4(0.2, 0.2, 0.3, 1.0); - /** - * Defines the color used to simulate the ambient color (Default is (0, 0, 0)) - */ - this.ambientColor = new math_color_Color3(0, 0, 0); - /** - * Intensity of the environment in all pbr material. - * This dims or reinforces the IBL lighting overall (reflection and diffuse). - * As in the majority of the scene they are the same (exception for multi room and so on), - * this is easier to reference from here than from all the materials. - */ - this.environmentIntensity = 1; - this._performancePriority = ScenePerformancePriority.BackwardCompatible; - /** - * Observable triggered when the performance priority is changed - */ - this.onScenePerformancePriorityChangedObservable = new observable_Observable(); - this._forceWireframe = false; - this._skipFrustumClipping = false; - this._forcePointsCloud = false; - /** - * Gets or sets a boolean indicating if animations are enabled - */ - this.animationsEnabled = true; - this._animationPropertiesOverride = null; - /** - * Gets or sets a boolean indicating if a constant deltatime has to be used - * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate - */ - this.useConstantAnimationDeltaTime = false; - /** - * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated - * Please note that it requires to run a ray cast through the scene on every frame - */ - this.constantlyUpdateMeshUnderPointer = false; - /** - * Defines the HTML cursor to use when hovering over interactive elements - */ - this.hoverCursor = "pointer"; - /** - * Defines the HTML default cursor to use (empty by default) - */ - this.defaultCursor = ""; - /** - * Defines whether cursors are handled by the scene. - */ - this.doNotHandleCursors = false; - /** - * This is used to call preventDefault() on pointer down - * in order to block unwanted artifacts like system double clicks - */ - this.preventDefaultOnPointerDown = true; - /** - * This is used to call preventDefault() on pointer up - * in order to block unwanted artifacts like system double clicks - */ - this.preventDefaultOnPointerUp = true; - // Metadata - /** - * Gets or sets user defined metadata - */ - this.metadata = null; - /** - * For internal use only. Please do not use. - */ - this.reservedDataStore = null; - /** - * Use this array to add regular expressions used to disable offline support for specific urls - */ - this.disableOfflineSupportExceptionRules = new Array(); - /** - * An event triggered when the scene is disposed. - */ - this.onDisposeObservable = new observable_Observable(); - this._onDisposeObserver = null; - /** - * An event triggered before rendering the scene (right after animations and physics) - */ - this.onBeforeRenderObservable = new observable_Observable(); - this._onBeforeRenderObserver = null; - /** - * An event triggered after rendering the scene - */ - this.onAfterRenderObservable = new observable_Observable(); - /** - * An event triggered after rendering the scene for an active camera (When scene.render is called this will be called after each camera) - * This is triggered for each "sub" camera in a Camera Rig unlike onAfterCameraRenderObservable - */ - this.onAfterRenderCameraObservable = new observable_Observable(); - this._onAfterRenderObserver = null; - /** - * An event triggered before animating the scene - */ - this.onBeforeAnimationsObservable = new observable_Observable(); - /** - * An event triggered after animations processing - */ - this.onAfterAnimationsObservable = new observable_Observable(); - /** - * An event triggered before draw calls are ready to be sent - */ - this.onBeforeDrawPhaseObservable = new observable_Observable(); - /** - * An event triggered after draw calls have been sent - */ - this.onAfterDrawPhaseObservable = new observable_Observable(); - /** - * An event triggered when the scene is ready - */ - this.onReadyObservable = new observable_Observable(); - /** - * An event triggered before rendering a camera - */ - this.onBeforeCameraRenderObservable = new observable_Observable(); - this._onBeforeCameraRenderObserver = null; - /** - * An event triggered after rendering a camera - * This is triggered for the full rig Camera only unlike onAfterRenderCameraObservable - */ - this.onAfterCameraRenderObservable = new observable_Observable(); - this._onAfterCameraRenderObserver = null; - /** - * An event triggered when active meshes evaluation is about to start - */ - this.onBeforeActiveMeshesEvaluationObservable = new observable_Observable(); - /** - * An event triggered when active meshes evaluation is done - */ - this.onAfterActiveMeshesEvaluationObservable = new observable_Observable(); - /** - * An event triggered when particles rendering is about to start - * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well) - */ - this.onBeforeParticlesRenderingObservable = new observable_Observable(); - /** - * An event triggered when particles rendering is done - * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well) - */ - this.onAfterParticlesRenderingObservable = new observable_Observable(); - /** - * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed - */ - this.onDataLoadedObservable = new observable_Observable(); - /** - * An event triggered when a camera is created - */ - this.onNewCameraAddedObservable = new observable_Observable(); - /** - * An event triggered when a camera is removed - */ - this.onCameraRemovedObservable = new observable_Observable(); - /** - * An event triggered when a light is created - */ - this.onNewLightAddedObservable = new observable_Observable(); - /** - * An event triggered when a light is removed - */ - this.onLightRemovedObservable = new observable_Observable(); - /** - * An event triggered when a geometry is created - */ - this.onNewGeometryAddedObservable = new observable_Observable(); - /** - * An event triggered when a geometry is removed - */ - this.onGeometryRemovedObservable = new observable_Observable(); - /** - * An event triggered when a transform node is created - */ - this.onNewTransformNodeAddedObservable = new observable_Observable(); - /** - * An event triggered when a transform node is removed - */ - this.onTransformNodeRemovedObservable = new observable_Observable(); - /** - * An event triggered when a mesh is created - */ - this.onNewMeshAddedObservable = new observable_Observable(); - /** - * An event triggered when a mesh is removed - */ - this.onMeshRemovedObservable = new observable_Observable(); - /** - * An event triggered when a skeleton is created - */ - this.onNewSkeletonAddedObservable = new observable_Observable(); - /** - * An event triggered when a skeleton is removed - */ - this.onSkeletonRemovedObservable = new observable_Observable(); - /** - * An event triggered when a material is created - */ - this.onNewMaterialAddedObservable = new observable_Observable(); - /** - * An event triggered when a multi material is created - */ - this.onNewMultiMaterialAddedObservable = new observable_Observable(); - /** - * An event triggered when a material is removed - */ - this.onMaterialRemovedObservable = new observable_Observable(); - /** - * An event triggered when a multi material is removed - */ - this.onMultiMaterialRemovedObservable = new observable_Observable(); - /** - * An event triggered when a texture is created - */ - this.onNewTextureAddedObservable = new observable_Observable(); - /** - * An event triggered when a texture is removed - */ - this.onTextureRemovedObservable = new observable_Observable(); - /** - * An event triggered when render targets are about to be rendered - * Can happen multiple times per frame. - */ - this.onBeforeRenderTargetsRenderObservable = new observable_Observable(); - /** - * An event triggered when render targets were rendered. - * Can happen multiple times per frame. - */ - this.onAfterRenderTargetsRenderObservable = new observable_Observable(); - /** - * An event triggered before calculating deterministic simulation step - */ - this.onBeforeStepObservable = new observable_Observable(); - /** - * An event triggered after calculating deterministic simulation step - */ - this.onAfterStepObservable = new observable_Observable(); - /** - * An event triggered when the activeCamera property is updated - */ - this.onActiveCameraChanged = new observable_Observable(); - /** - * An event triggered when the activeCameras property is updated - */ - this.onActiveCamerasChanged = new observable_Observable(); - /** - * This Observable will be triggered before rendering each renderingGroup of each rendered camera. - * The RenderingGroupInfo class contains all the information about the context in which the observable is called - * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3) - */ - this.onBeforeRenderingGroupObservable = new observable_Observable(); - /** - * This Observable will be triggered after rendering each renderingGroup of each rendered camera. - * The RenderingGroupInfo class contains all the information about the context in which the observable is called - * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3) - */ - this.onAfterRenderingGroupObservable = new observable_Observable(); - /** - * This Observable will when a mesh has been imported into the scene. - */ - this.onMeshImportedObservable = new observable_Observable(); - /** - * This Observable will when an animation file has been imported into the scene. - */ - this.onAnimationFileImportedObservable = new observable_Observable(); - // Animations - /** @internal */ - this._registeredForLateAnimationBindings = new SmartArrayNoDuplicate(256); - // Pointers - this._pointerPickingConfiguration = new PointerPickingConfiguration(); - /** - * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance). - * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true - */ - this.onPrePointerObservable = new observable_Observable(); - /** - * Observable event triggered each time an input event is received from the rendering canvas - */ - this.onPointerObservable = new observable_Observable(); - // Keyboard - /** - * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl() - * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true - */ - this.onPreKeyboardObservable = new observable_Observable(); - /** - * Observable event triggered each time an keyboard event is received from the hosting window - */ - this.onKeyboardObservable = new observable_Observable(); - // Coordinates system - this._useRightHandedSystem = false; - // Deterministic lockstep - this._timeAccumulator = 0; - this._currentStepId = 0; - this._currentInternalStep = 0; - // Fog - this._fogEnabled = true; - this._fogMode = scene_Scene.FOGMODE_NONE; - /** - * Gets or sets the fog color to use - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog - * (Default is Color3(0.2, 0.2, 0.3)) - */ - this.fogColor = new math_color_Color3(0.2, 0.2, 0.3); - /** - * Gets or sets the fog density to use - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog - * (Default is 0.1) - */ - this.fogDensity = 0.1; - /** - * Gets or sets the fog start distance to use - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog - * (Default is 0) - */ - this.fogStart = 0; - /** - * Gets or sets the fog end distance to use - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog - * (Default is 1000) - */ - this.fogEnd = 1000.0; - /** - * Flag indicating if we need to store previous matrices when rendering - */ - this.needsPreviousWorldMatrices = false; - // Lights - this._shadowsEnabled = true; - this._lightsEnabled = true; - this._unObserveActiveCameras = null; - // Textures - this._texturesEnabled = true; - // Physics - /** - * Gets or sets a boolean indicating if physic engines are enabled on this scene - */ - this.physicsEnabled = true; - // Particles - /** - * Gets or sets a boolean indicating if particles are enabled on this scene - */ - this.particlesEnabled = true; - // Sprites - /** - * Gets or sets a boolean indicating if sprites are enabled on this scene - */ - this.spritesEnabled = true; - // Skeletons - this._skeletonsEnabled = true; - // Lens flares - /** - * Gets or sets a boolean indicating if lens flares are enabled on this scene - */ - this.lensFlaresEnabled = true; - // Collisions - /** - * Gets or sets a boolean indicating if collisions are enabled on this scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions - */ - this.collisionsEnabled = true; - /** - * Defines the gravity applied to this scene (used only for collisions) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions - */ - this.gravity = new math_vector_Vector3(0, -9.807, 0); - // Postprocesses - /** - * Gets or sets a boolean indicating if postprocesses are enabled on this scene - */ - this.postProcessesEnabled = true; - // Customs render targets - /** - * Gets or sets a boolean indicating if render targets are enabled on this scene - */ - this.renderTargetsEnabled = true; - /** - * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes - * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com - */ - this.dumpNextRenderTargets = false; - /** - * The list of user defined render targets added to the scene - */ - this.customRenderTargets = new Array(); - /** - * Gets the list of meshes imported to the scene through SceneLoader - */ - this.importedMeshesFiles = new Array(); - // Probes - /** - * Gets or sets a boolean indicating if probes are enabled on this scene - */ - this.probesEnabled = true; - this._meshesForIntersections = new SmartArrayNoDuplicate(256); - // Procedural textures - /** - * Gets or sets a boolean indicating if procedural textures are enabled on this scene - */ - this.proceduralTexturesEnabled = true; - // Performance counters - this._totalVertices = new perfCounter_PerfCounter(); - /** @internal */ - this._activeIndices = new perfCounter_PerfCounter(); - /** @internal */ - this._activeParticles = new perfCounter_PerfCounter(); - /** @internal */ - this._activeBones = new perfCounter_PerfCounter(); - /** @internal */ - this._animationTime = 0; - /** - * Gets or sets a general scale for animation speed - * @see https://www.babylonjs-playground.com/#IBU2W7#3 - */ - this.animationTimeScale = 1; - this._renderId = 0; - this._frameId = 0; - this._executeWhenReadyTimeoutId = null; - this._intermediateRendering = false; - this._defaultFrameBufferCleared = false; - this._viewUpdateFlag = -1; - this._projectionUpdateFlag = -1; - /** @internal */ - this._toBeDisposed = new Array(256); - this._activeRequests = new Array(); - /** @internal */ - this._pendingData = new Array(); - this._isDisposed = false; - /** - * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered - * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound) - */ - this.dispatchAllSubMeshesOfActiveMeshes = false; - this._activeMeshes = new SmartArray(256); - this._processedMaterials = new SmartArray(256); - this._renderTargets = new SmartArrayNoDuplicate(256); - this._materialsRenderTargets = new SmartArrayNoDuplicate(256); - /** @internal */ - this._activeParticleSystems = new SmartArray(256); - this._activeSkeletons = new SmartArrayNoDuplicate(32); - this._softwareSkinnedMeshes = new SmartArrayNoDuplicate(32); - /** @internal */ - this._activeAnimatables = new Array(); - this._transformMatrix = math_vector_Matrix.Zero(); - /** - * Gets or sets a boolean indicating if lights must be sorted by priority (off by default) - * This is useful if there are more lights that the maximum simulteanous authorized - */ - this.requireLightSorting = false; - /** - * @internal - * Backing store of defined scene components. - */ - this._components = []; - /** - * @internal - * Backing store of defined scene components. - */ - this._serializableComponents = []; - /** - * List of components to register on the next registration step. - */ - this._transientComponents = []; - /** - * @internal - * Defines the actions happening before camera updates. - */ - this._beforeCameraUpdateStage = Stage.Create(); - /** - * @internal - * Defines the actions happening before clear the canvas. - */ - this._beforeClearStage = Stage.Create(); - /** - * @internal - * Defines the actions happening before clear the canvas. - */ - this._beforeRenderTargetClearStage = Stage.Create(); - /** - * @internal - * Defines the actions when collecting render targets for the frame. - */ - this._gatherRenderTargetsStage = Stage.Create(); - /** - * @internal - * Defines the actions happening for one camera in the frame. - */ - this._gatherActiveCameraRenderTargetsStage = Stage.Create(); - /** - * @internal - * Defines the actions happening during the per mesh ready checks. - */ - this._isReadyForMeshStage = Stage.Create(); - /** - * @internal - * Defines the actions happening before evaluate active mesh checks. - */ - this._beforeEvaluateActiveMeshStage = Stage.Create(); - /** - * @internal - * Defines the actions happening during the evaluate sub mesh checks. - */ - this._evaluateSubMeshStage = Stage.Create(); - /** - * @internal - * Defines the actions happening during the active mesh stage. - */ - this._preActiveMeshStage = Stage.Create(); - /** - * @internal - * Defines the actions happening during the per camera render target step. - */ - this._cameraDrawRenderTargetStage = Stage.Create(); - /** - * @internal - * Defines the actions happening just before the active camera is drawing. - */ - this._beforeCameraDrawStage = Stage.Create(); - /** - * @internal - * Defines the actions happening just before a render target is drawing. - */ - this._beforeRenderTargetDrawStage = Stage.Create(); - /** - * @internal - * Defines the actions happening just before a rendering group is drawing. - */ - this._beforeRenderingGroupDrawStage = Stage.Create(); - /** - * @internal - * Defines the actions happening just before a mesh is drawing. - */ - this._beforeRenderingMeshStage = Stage.Create(); - /** - * @internal - * Defines the actions happening just after a mesh has been drawn. - */ - this._afterRenderingMeshStage = Stage.Create(); - /** - * @internal - * Defines the actions happening just after a rendering group has been drawn. - */ - this._afterRenderingGroupDrawStage = Stage.Create(); - /** - * @internal - * Defines the actions happening just after the active camera has been drawn. - */ - this._afterCameraDrawStage = Stage.Create(); - /** - * @internal - * Defines the actions happening just after the post processing - */ - this._afterCameraPostProcessStage = Stage.Create(); - /** - * @internal - * Defines the actions happening just after a render target has been drawn. - */ - this._afterRenderTargetDrawStage = Stage.Create(); - /** - * Defines the actions happening just after the post processing on a render target - */ - this._afterRenderTargetPostProcessStage = Stage.Create(); - /** - * @internal - * Defines the actions happening just after rendering all cameras and computing intersections. - */ - this._afterRenderStage = Stage.Create(); - /** - * @internal - * Defines the actions happening when a pointer move event happens. - */ - this._pointerMoveStage = Stage.Create(); - /** - * @internal - * Defines the actions happening when a pointer down event happens. - */ - this._pointerDownStage = Stage.Create(); - /** - * @internal - * Defines the actions happening when a pointer up event happens. - */ - this._pointerUpStage = Stage.Create(); - /** - * an optional map from Geometry Id to Geometry index in the 'geometries' array - */ - this._geometriesByUniqueId = null; - this._defaultMeshCandidates = { - data: [], - length: 0, - }; - this._defaultSubMeshCandidates = { - data: [], - length: 0, - }; - this._preventFreeActiveMeshesAndRenderingGroups = false; - /** @internal */ - this._activeMeshesFrozen = false; - /** @internal */ - this._activeMeshesFrozenButKeepClipping = false; - this._skipEvaluateActiveMeshesCompletely = false; - /** @internal */ - this._allowPostProcessClearColor = true; - /** - * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode - */ - this.getDeterministicFrameTime = () => { - return this._engine.getTimeStep(); - }; - /** @internal */ - this._registeredActions = 0; - this._blockMaterialDirtyMechanism = false; - /** - * Internal perfCollector instance used for sharing between inspector and playground. - * Marked as protected to allow sharing between prototype extensions, but disallow access at toplevel. - */ - this._perfCollector = null; - this.activeCameras = new Array(); - const fullOptions = Object.assign({ useGeometryUniqueIdsMap: true, useMaterialMeshMap: true, useClonedMeshMap: true, virtual: false }, options); - this._engine = engine || engineStore_EngineStore.LastCreatedEngine; - if (!fullOptions.virtual) { - engineStore_EngineStore._LastCreatedScene = this; - this._engine.scenes.push(this); - } - else { - this._engine._virtualScenes.push(this); - } - this._uid = null; - this._renderingManager = new RenderingManager(this); - if (PostProcessManager) { - this.postProcessManager = new PostProcessManager(this); - } - if (IsWindowObjectExist()) { - this.attachControl(); - } - // Uniform Buffer - this._createUbo(); - // Default Image processing definition - if (ImageProcessingConfiguration) { - this._imageProcessingConfiguration = new ImageProcessingConfiguration(); - } - this.setDefaultCandidateProviders(); - if (fullOptions.useGeometryUniqueIdsMap) { - this._geometriesByUniqueId = {}; - } - this.useMaterialMeshMap = fullOptions.useMaterialMeshMap; - this.useClonedMeshMap = fullOptions.useClonedMeshMap; - if (!options || !options.virtual) { - this._engine.onNewSceneAddedObservable.notifyObservers(this); - } - } - /** - * Gets a string identifying the name of the class - * @returns "Scene" string - */ - getClassName() { - return "Scene"; - } - /** - * @internal - */ - _getDefaultMeshCandidates() { - this._defaultMeshCandidates.data = this.meshes; - this._defaultMeshCandidates.length = this.meshes.length; - return this._defaultMeshCandidates; - } - /** - * @internal - */ - _getDefaultSubMeshCandidates(mesh) { - this._defaultSubMeshCandidates.data = mesh.subMeshes; - this._defaultSubMeshCandidates.length = mesh.subMeshes.length; - return this._defaultSubMeshCandidates; - } - /** - * Sets the default candidate providers for the scene. - * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates - * and getCollidingSubMeshCandidates to their default function - */ - setDefaultCandidateProviders() { - this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this); - this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this); - this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this); - this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this); - } - /** - * Gets the mesh that is currently under the pointer - */ - get meshUnderPointer() { - return this._inputManager.meshUnderPointer; - } - /** - * Gets or sets the current on-screen X position of the pointer - */ - get pointerX() { - return this._inputManager.pointerX; - } - set pointerX(value) { - this._inputManager.pointerX = value; - } - /** - * Gets or sets the current on-screen Y position of the pointer - */ - get pointerY() { - return this._inputManager.pointerY; - } - set pointerY(value) { - this._inputManager.pointerY = value; - } - /** - * Gets the cached material (ie. the latest rendered one) - * @returns the cached material - */ - getCachedMaterial() { - return this._cachedMaterial; - } - /** - * Gets the cached effect (ie. the latest rendered one) - * @returns the cached effect - */ - getCachedEffect() { - return this._cachedEffect; - } - /** - * Gets the cached visibility state (ie. the latest rendered one) - * @returns the cached visibility state - */ - getCachedVisibility() { - return this._cachedVisibility; - } - /** - * Gets a boolean indicating if the current material / effect / visibility must be bind again - * @param material defines the current material - * @param effect defines the current effect - * @param visibility defines the current visibility state - * @returns true if one parameter is not cached - */ - isCachedMaterialInvalid(material, effect, visibility = 1) { - return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility; - } - /** - * Gets the engine associated with the scene - * @returns an Engine - */ - getEngine() { - return this._engine; - } - /** - * Gets the total number of vertices rendered per frame - * @returns the total number of vertices rendered per frame - */ - getTotalVertices() { - return this._totalVertices.current; - } - /** - * Gets the performance counter for total vertices - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation - */ - get totalVerticesPerfCounter() { - return this._totalVertices; - } - /** - * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3) - * @returns the total number of active indices rendered per frame - */ - getActiveIndices() { - return this._activeIndices.current; - } - /** - * Gets the performance counter for active indices - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation - */ - get totalActiveIndicesPerfCounter() { - return this._activeIndices; - } - /** - * Gets the total number of active particles rendered per frame - * @returns the total number of active particles rendered per frame - */ - getActiveParticles() { - return this._activeParticles.current; - } - /** - * Gets the performance counter for active particles - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation - */ - get activeParticlesPerfCounter() { - return this._activeParticles; - } - /** - * Gets the total number of active bones rendered per frame - * @returns the total number of active bones rendered per frame - */ - getActiveBones() { - return this._activeBones.current; - } - /** - * Gets the performance counter for active bones - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation - */ - get activeBonesPerfCounter() { - return this._activeBones; - } - /** - * Gets the array of active meshes - * @returns an array of AbstractMesh - */ - getActiveMeshes() { - return this._activeMeshes; - } - /** - * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.) - * @returns a number - */ - getAnimationRatio() { - return this._animationRatio !== undefined ? this._animationRatio : 1; - } - /** - * Gets an unique Id for the current render phase - * @returns a number - */ - getRenderId() { - return this._renderId; - } - /** - * Gets an unique Id for the current frame - * @returns a number - */ - getFrameId() { - return this._frameId; - } - /** Call this function if you want to manually increment the render Id*/ - incrementRenderId() { - this._renderId++; - } - _createUbo() { - this.setSceneUniformBuffer(this.createSceneUniformBuffer()); - } - /** - * Use this method to simulate a pointer move on a mesh - * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay - * @param pickResult pickingInfo of the object wished to simulate pointer event on - * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) - * @returns the current scene - */ - simulatePointerMove(pickResult, pointerEventInit) { - this._inputManager.simulatePointerMove(pickResult, pointerEventInit); - return this; - } - /** - * Use this method to simulate a pointer down on a mesh - * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay - * @param pickResult pickingInfo of the object wished to simulate pointer event on - * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) - * @returns the current scene - */ - simulatePointerDown(pickResult, pointerEventInit) { - this._inputManager.simulatePointerDown(pickResult, pointerEventInit); - return this; - } - /** - * Use this method to simulate a pointer up on a mesh - * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay - * @param pickResult pickingInfo of the object wished to simulate pointer event on - * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) - * @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default) - * @returns the current scene - */ - simulatePointerUp(pickResult, pointerEventInit, doubleTap) { - this._inputManager.simulatePointerUp(pickResult, pointerEventInit, doubleTap); - return this; - } - /** - * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down) - * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default) - * @returns true if the pointer was captured - */ - isPointerCaptured(pointerId = 0) { - return this._inputManager.isPointerCaptured(pointerId); - } - /** - * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp - * @param attachUp defines if you want to attach events to pointerup - * @param attachDown defines if you want to attach events to pointerdown - * @param attachMove defines if you want to attach events to pointermove - */ - attachControl(attachUp = true, attachDown = true, attachMove = true) { - this._inputManager.attachControl(attachUp, attachDown, attachMove); - } - /** Detaches all event handlers*/ - detachControl() { - this._inputManager.detachControl(); - } - /** - * This function will check if the scene can be rendered (textures are loaded, shaders are compiled) - * Delay loaded resources are not taking in account - * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: true) - * @returns true if all required resources are ready - */ - isReady(checkRenderTargets = true) { - var _a, _b, _c; - if (this._isDisposed) { - return false; - } - let index; - const engine = this.getEngine(); - const currentRenderPassId = engine.currentRenderPassId; - engine.currentRenderPassId = (_b = (_a = this.activeCamera) === null || _a === void 0 ? void 0 : _a.renderPassId) !== null && _b !== void 0 ? _b : currentRenderPassId; - let isReady = true; - // Pending data - if (this._pendingData.length > 0) { - isReady = false; - } - // Ensures that the pre-pass renderer is enabled if it is to be enabled. - (_c = this.prePassRenderer) === null || _c === void 0 ? void 0 : _c.update(); - // Meshes - if (checkRenderTargets) { - this._processedMaterials.reset(); - this._materialsRenderTargets.reset(); - } - for (index = 0; index < this.meshes.length; index++) { - const mesh = this.meshes[index]; - if (!mesh.subMeshes || mesh.subMeshes.length === 0) { - continue; - } - // Do not stop at the first encountered "unready" object as we want to ensure - // all materials are starting off their compilation in parallel. - if (!mesh.isReady(true)) { - isReady = false; - continue; - } - const hardwareInstancedRendering = mesh.hasThinInstances || - mesh.getClassName() === "InstancedMesh" || - mesh.getClassName() === "InstancedLinesMesh" || - (engine.getCaps().instancedArrays && mesh.instances.length > 0); - // Is Ready For Mesh - for (const step of this._isReadyForMeshStage) { - if (!step.action(mesh, hardwareInstancedRendering)) { - isReady = false; - } - } - if (!checkRenderTargets) { - continue; - } - const mat = mesh.material || this.defaultMaterial; - if (mat) { - if (mat._storeEffectOnSubMeshes) { - for (const subMesh of mesh.subMeshes) { - const material = subMesh.getMaterial(); - if (material && material.hasRenderTargetTextures && material.getRenderTargetTextures != null) { - if (this._processedMaterials.indexOf(material) === -1) { - this._processedMaterials.push(material); - this._materialsRenderTargets.concatWithNoDuplicate(material.getRenderTargetTextures()); - } - } - } - } - else { - if (mat.hasRenderTargetTextures && mat.getRenderTargetTextures != null) { - if (this._processedMaterials.indexOf(mat) === -1) { - this._processedMaterials.push(mat); - this._materialsRenderTargets.concatWithNoDuplicate(mat.getRenderTargetTextures()); - } - } - } - } - } - // Render targets - if (checkRenderTargets) { - for (index = 0; index < this._materialsRenderTargets.length; ++index) { - const rtt = this._materialsRenderTargets.data[index]; - if (!rtt.isReadyForRendering()) { - isReady = false; - } - } - } - // Geometries - for (index = 0; index < this.geometries.length; index++) { - const geometry = this.geometries[index]; - if (geometry.delayLoadState === 2) { - isReady = false; - } - } - // Post-processes - if (this.activeCameras && this.activeCameras.length > 0) { - for (const camera of this.activeCameras) { - if (!camera.isReady(true)) { - isReady = false; - } - } - } - else if (this.activeCamera) { - if (!this.activeCamera.isReady(true)) { - isReady = false; - } - } - // Particles - for (const particleSystem of this.particleSystems) { - if (!particleSystem.isReady()) { - isReady = false; - } - } - // Layers - if (this.layers) { - for (const layer of this.layers) { - if (!layer.isReady()) { - isReady = false; - } - } - } - // Effects - if (!engine.areAllEffectsReady()) { - isReady = false; - } - engine.currentRenderPassId = currentRenderPassId; - return isReady; - } - /** Resets all cached information relative to material (including effect and visibility) */ - resetCachedMaterial() { - this._cachedMaterial = null; - this._cachedEffect = null; - this._cachedVisibility = null; - } - /** - * Registers a function to be called before every frame render - * @param func defines the function to register - */ - registerBeforeRender(func) { - this.onBeforeRenderObservable.add(func); - } - /** - * Unregisters a function called before every frame render - * @param func defines the function to unregister - */ - unregisterBeforeRender(func) { - this.onBeforeRenderObservable.removeCallback(func); - } - /** - * Registers a function to be called after every frame render - * @param func defines the function to register - */ - registerAfterRender(func) { - this.onAfterRenderObservable.add(func); - } - /** - * Unregisters a function called after every frame render - * @param func defines the function to unregister - */ - unregisterAfterRender(func) { - this.onAfterRenderObservable.removeCallback(func); - } - _executeOnceBeforeRender(func) { - const execFunc = () => { - func(); - setTimeout(() => { - this.unregisterBeforeRender(execFunc); - }); - }; - this.registerBeforeRender(execFunc); - } - /** - * The provided function will run before render once and will be disposed afterwards. - * A timeout delay can be provided so that the function will be executed in N ms. - * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed. - * @param func The function to be executed. - * @param timeout optional delay in ms - */ - executeOnceBeforeRender(func, timeout) { - if (timeout !== undefined) { - setTimeout(() => { - this._executeOnceBeforeRender(func); - }, timeout); - } - else { - this._executeOnceBeforeRender(func); - } - } - /** - * This function can help adding any object to the list of data awaited to be ready in order to check for a complete scene loading. - * @param data defines the object to wait for - */ - addPendingData(data) { - this._pendingData.push(data); - } - /** - * Remove a pending data from the loading list which has previously been added with addPendingData. - * @param data defines the object to remove from the pending list - */ - removePendingData(data) { - const wasLoading = this.isLoading; - const index = this._pendingData.indexOf(data); - if (index !== -1) { - this._pendingData.splice(index, 1); - } - if (wasLoading && !this.isLoading) { - this.onDataLoadedObservable.notifyObservers(this); - } - } - /** - * Returns the number of items waiting to be loaded - * @returns the number of items waiting to be loaded - */ - getWaitingItemsCount() { - return this._pendingData.length; - } - /** - * Returns a boolean indicating if the scene is still loading data - */ - get isLoading() { - return this._pendingData.length > 0; - } - /** - * Registers a function to be executed when the scene is ready - * @param func - the function to be executed - * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: false) - */ - executeWhenReady(func, checkRenderTargets = false) { - this.onReadyObservable.addOnce(func); - if (this._executeWhenReadyTimeoutId !== null) { - return; - } - this._checkIsReady(checkRenderTargets); - } - /** - * Returns a promise that resolves when the scene is ready - * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: false) - * @returns A promise that resolves when the scene is ready - */ - whenReadyAsync(checkRenderTargets = false) { - return new Promise((resolve) => { - this.executeWhenReady(() => { - resolve(); - }, checkRenderTargets); - }); - } - /** - * @internal - */ - _checkIsReady(checkRenderTargets = false) { - this._registerTransientComponents(); - if (this.isReady(checkRenderTargets)) { - this.onReadyObservable.notifyObservers(this); - this.onReadyObservable.clear(); - this._executeWhenReadyTimeoutId = null; - return; - } - if (this._isDisposed) { - this.onReadyObservable.clear(); - this._executeWhenReadyTimeoutId = null; - return; - } - this._executeWhenReadyTimeoutId = setTimeout(() => { - // Ensure materials effects are checked outside render loops - this.incrementRenderId(); - this._checkIsReady(checkRenderTargets); - }, 100); - } - /** - * Gets all animatable attached to the scene - */ - get animatables() { - return this._activeAnimatables; - } - /** - * Resets the last animation time frame. - * Useful to override when animations start running when loading a scene for the first time. - */ - resetLastAnimationTimeFrame() { - this._animationTimeLast = precisionDate_PrecisionDate.Now; - } - // Matrix - /** - * Gets the current view matrix - * @returns a Matrix - */ - getViewMatrix() { - return this._viewMatrix; - } - /** - * Gets the current projection matrix - * @returns a Matrix - */ - getProjectionMatrix() { - return this._projectionMatrix; - } - /** - * Gets the current transform matrix - * @returns a Matrix made of View * Projection - */ - getTransformMatrix() { - return this._transformMatrix; - } - /** - * Sets the current transform matrix - * @param viewL defines the View matrix to use - * @param projectionL defines the Projection matrix to use - * @param viewR defines the right View matrix to use (if provided) - * @param projectionR defines the right Projection matrix to use (if provided) - */ - setTransformMatrix(viewL, projectionL, viewR, projectionR) { - // clear the multiviewSceneUbo if no viewR and projectionR are defined - if (!viewR && !projectionR && this._multiviewSceneUbo) { - this._multiviewSceneUbo.dispose(); - this._multiviewSceneUbo = null; - } - if (this._viewUpdateFlag === viewL.updateFlag && this._projectionUpdateFlag === projectionL.updateFlag) { - return; - } - this._viewUpdateFlag = viewL.updateFlag; - this._projectionUpdateFlag = projectionL.updateFlag; - this._viewMatrix = viewL; - this._projectionMatrix = projectionL; - this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); - // Update frustum - if (!this._frustumPlanes) { - this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix); - } - else { - Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes); - } - if (this._multiviewSceneUbo && this._multiviewSceneUbo.useUbo) { - this._updateMultiviewUbo(viewR, projectionR); - } - else if (this._sceneUbo.useUbo) { - this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix); - this._sceneUbo.updateMatrix("view", this._viewMatrix); - this._sceneUbo.updateMatrix("projection", this._projectionMatrix); - } - } - /** - * Gets the uniform buffer used to store scene data - * @returns a UniformBuffer - */ - getSceneUniformBuffer() { - return this._multiviewSceneUbo ? this._multiviewSceneUbo : this._sceneUbo; - } - /** - * Creates a scene UBO - * @param name name of the uniform buffer (optional, for debugging purpose only) - * @returns a new ubo - */ - createSceneUniformBuffer(name) { - const sceneUbo = new UniformBuffer(this._engine, undefined, false, name !== null && name !== void 0 ? name : "scene"); - sceneUbo.addUniform("viewProjection", 16); - sceneUbo.addUniform("view", 16); - sceneUbo.addUniform("projection", 16); - sceneUbo.addUniform("vEyePosition", 4); - return sceneUbo; - } - /** - * Sets the scene ubo - * @param ubo the ubo to set for the scene - */ - setSceneUniformBuffer(ubo) { - this._sceneUbo = ubo; - this._viewUpdateFlag = -1; - this._projectionUpdateFlag = -1; - } - /** - * Gets an unique (relatively to the current scene) Id - * @returns an unique number for the scene - */ - getUniqueId() { - return UniqueIdGenerator.UniqueId; - } - /** - * Add a mesh to the list of scene's meshes - * @param newMesh defines the mesh to add - * @param recursive if all child meshes should also be added to the scene - */ - addMesh(newMesh, recursive = false) { - if (this._blockEntityCollection) { - return; - } - this.meshes.push(newMesh); - newMesh._resyncLightSources(); - if (!newMesh.parent) { - newMesh._addToSceneRootNodes(); - } - this.onNewMeshAddedObservable.notifyObservers(newMesh); - if (recursive) { - newMesh.getChildMeshes().forEach((m) => { - this.addMesh(m); - }); - } - } - /** - * Remove a mesh for the list of scene's meshes - * @param toRemove defines the mesh to remove - * @param recursive if all child meshes should also be removed from the scene - * @returns the index where the mesh was in the mesh list - */ - removeMesh(toRemove, recursive = false) { - const index = this.meshes.indexOf(toRemove); - if (index !== -1) { - // Remove from the scene if mesh found - this.meshes[index] = this.meshes[this.meshes.length - 1]; - this.meshes.pop(); - if (!toRemove.parent) { - toRemove._removeFromSceneRootNodes(); - } - } - this._inputManager._invalidateMesh(toRemove); - this.onMeshRemovedObservable.notifyObservers(toRemove); - if (recursive) { - toRemove.getChildMeshes().forEach((m) => { - this.removeMesh(m); - }); - } - return index; - } - /** - * Add a transform node to the list of scene's transform nodes - * @param newTransformNode defines the transform node to add - */ - addTransformNode(newTransformNode) { - if (this._blockEntityCollection) { - return; - } - if (newTransformNode.getScene() === this && newTransformNode._indexInSceneTransformNodesArray !== -1) { - // Already there? - return; - } - newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length; - this.transformNodes.push(newTransformNode); - if (!newTransformNode.parent) { - newTransformNode._addToSceneRootNodes(); - } - this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode); - } - /** - * Remove a transform node for the list of scene's transform nodes - * @param toRemove defines the transform node to remove - * @returns the index where the transform node was in the transform node list - */ - removeTransformNode(toRemove) { - const index = toRemove._indexInSceneTransformNodesArray; - if (index !== -1) { - if (index !== this.transformNodes.length - 1) { - const lastNode = this.transformNodes[this.transformNodes.length - 1]; - this.transformNodes[index] = lastNode; - lastNode._indexInSceneTransformNodesArray = index; - } - toRemove._indexInSceneTransformNodesArray = -1; - this.transformNodes.pop(); - if (!toRemove.parent) { - toRemove._removeFromSceneRootNodes(); - } - } - this.onTransformNodeRemovedObservable.notifyObservers(toRemove); - return index; - } - /** - * Remove a skeleton for the list of scene's skeletons - * @param toRemove defines the skeleton to remove - * @returns the index where the skeleton was in the skeleton list - */ - removeSkeleton(toRemove) { - const index = this.skeletons.indexOf(toRemove); - if (index !== -1) { - // Remove from the scene if found - this.skeletons.splice(index, 1); - this.onSkeletonRemovedObservable.notifyObservers(toRemove); - // Clean active container - this._executeActiveContainerCleanup(this._activeSkeletons); - } - return index; - } - /** - * Remove a morph target for the list of scene's morph targets - * @param toRemove defines the morph target to remove - * @returns the index where the morph target was in the morph target list - */ - removeMorphTargetManager(toRemove) { - const index = this.morphTargetManagers.indexOf(toRemove); - if (index !== -1) { - // Remove from the scene if found - this.morphTargetManagers.splice(index, 1); - } - return index; - } - /** - * Remove a light for the list of scene's lights - * @param toRemove defines the light to remove - * @returns the index where the light was in the light list - */ - removeLight(toRemove) { - const index = this.lights.indexOf(toRemove); - if (index !== -1) { - // Remove from meshes - for (const mesh of this.meshes) { - mesh._removeLightSource(toRemove, false); - } - // Remove from the scene if mesh found - this.lights.splice(index, 1); - this.sortLightsByPriority(); - if (!toRemove.parent) { - toRemove._removeFromSceneRootNodes(); - } - } - this.onLightRemovedObservable.notifyObservers(toRemove); - return index; - } - /** - * Remove a camera for the list of scene's cameras - * @param toRemove defines the camera to remove - * @returns the index where the camera was in the camera list - */ - removeCamera(toRemove) { - const index = this.cameras.indexOf(toRemove); - if (index !== -1) { - // Remove from the scene if mesh found - this.cameras.splice(index, 1); - if (!toRemove.parent) { - toRemove._removeFromSceneRootNodes(); - } - } - // Remove from activeCameras - if (this.activeCameras) { - const index2 = this.activeCameras.indexOf(toRemove); - if (index2 !== -1) { - // Remove from the scene if mesh found - this.activeCameras.splice(index2, 1); - } - } - // Reset the activeCamera - if (this.activeCamera === toRemove) { - if (this.cameras.length > 0) { - this.activeCamera = this.cameras[0]; - } - else { - this.activeCamera = null; - } - } - this.onCameraRemovedObservable.notifyObservers(toRemove); - return index; - } - /** - * Remove a particle system for the list of scene's particle systems - * @param toRemove defines the particle system to remove - * @returns the index where the particle system was in the particle system list - */ - removeParticleSystem(toRemove) { - const index = this.particleSystems.indexOf(toRemove); - if (index !== -1) { - this.particleSystems.splice(index, 1); - // Clean active container - this._executeActiveContainerCleanup(this._activeParticleSystems); - } - return index; - } - /** - * Remove a animation for the list of scene's animations - * @param toRemove defines the animation to remove - * @returns the index where the animation was in the animation list - */ - removeAnimation(toRemove) { - const index = this.animations.indexOf(toRemove); - if (index !== -1) { - this.animations.splice(index, 1); - } - return index; - } - /** - * Will stop the animation of the given target - * @param target - the target - * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty) - * @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) - */ - stopAnimation(target, animationName, targetMask) { - // Do nothing as code will be provided by animation component - } - /** - * Removes the given animation group from this scene. - * @param toRemove The animation group to remove - * @returns The index of the removed animation group - */ - removeAnimationGroup(toRemove) { - const index = this.animationGroups.indexOf(toRemove); - if (index !== -1) { - this.animationGroups.splice(index, 1); - } - return index; - } - /** - * Removes the given multi-material from this scene. - * @param toRemove The multi-material to remove - * @returns The index of the removed multi-material - */ - removeMultiMaterial(toRemove) { - const index = this.multiMaterials.indexOf(toRemove); - if (index !== -1) { - this.multiMaterials.splice(index, 1); - } - this.onMultiMaterialRemovedObservable.notifyObservers(toRemove); - return index; - } - /** - * Removes the given material from this scene. - * @param toRemove The material to remove - * @returns The index of the removed material - */ - removeMaterial(toRemove) { - const index = toRemove._indexInSceneMaterialArray; - if (index !== -1 && index < this.materials.length) { - if (index !== this.materials.length - 1) { - const lastMaterial = this.materials[this.materials.length - 1]; - this.materials[index] = lastMaterial; - lastMaterial._indexInSceneMaterialArray = index; - } - toRemove._indexInSceneMaterialArray = -1; - this.materials.pop(); - } - this.onMaterialRemovedObservable.notifyObservers(toRemove); - return index; - } - /** - * Removes the given action manager from this scene. - * @deprecated - * @param toRemove The action manager to remove - * @returns The index of the removed action manager - */ - removeActionManager(toRemove) { - const index = this.actionManagers.indexOf(toRemove); - if (index !== -1) { - this.actionManagers.splice(index, 1); - } - return index; - } - /** - * Removes the given texture from this scene. - * @param toRemove The texture to remove - * @returns The index of the removed texture - */ - removeTexture(toRemove) { - const index = this.textures.indexOf(toRemove); - if (index !== -1) { - this.textures.splice(index, 1); - } - this.onTextureRemovedObservable.notifyObservers(toRemove); - return index; - } - /** - * Adds the given light to this scene - * @param newLight The light to add - */ - addLight(newLight) { - if (this._blockEntityCollection) { - return; - } - this.lights.push(newLight); - this.sortLightsByPriority(); - if (!newLight.parent) { - newLight._addToSceneRootNodes(); - } - // Add light to all meshes (To support if the light is removed and then re-added) - for (const mesh of this.meshes) { - if (mesh.lightSources.indexOf(newLight) === -1) { - mesh.lightSources.push(newLight); - mesh._resyncLightSources(); - } - } - this.onNewLightAddedObservable.notifyObservers(newLight); - } - /** - * Sorts the list list based on light priorities - */ - sortLightsByPriority() { - if (this.requireLightSorting) { - this.lights.sort(LightConstants.CompareLightsPriority); - } - } - /** - * Adds the given camera to this scene - * @param newCamera The camera to add - */ - addCamera(newCamera) { - if (this._blockEntityCollection) { - return; - } - this.cameras.push(newCamera); - this.onNewCameraAddedObservable.notifyObservers(newCamera); - if (!newCamera.parent) { - newCamera._addToSceneRootNodes(); - } - } - /** - * Adds the given skeleton to this scene - * @param newSkeleton The skeleton to add - */ - addSkeleton(newSkeleton) { - if (this._blockEntityCollection) { - return; - } - this.skeletons.push(newSkeleton); - this.onNewSkeletonAddedObservable.notifyObservers(newSkeleton); - } - /** - * Adds the given particle system to this scene - * @param newParticleSystem The particle system to add - */ - addParticleSystem(newParticleSystem) { - if (this._blockEntityCollection) { - return; - } - this.particleSystems.push(newParticleSystem); - } - /** - * Adds the given animation to this scene - * @param newAnimation The animation to add - */ - addAnimation(newAnimation) { - if (this._blockEntityCollection) { - return; - } - this.animations.push(newAnimation); - } - /** - * Adds the given animation group to this scene. - * @param newAnimationGroup The animation group to add - */ - addAnimationGroup(newAnimationGroup) { - if (this._blockEntityCollection) { - return; - } - this.animationGroups.push(newAnimationGroup); - } - /** - * Adds the given multi-material to this scene - * @param newMultiMaterial The multi-material to add - */ - addMultiMaterial(newMultiMaterial) { - if (this._blockEntityCollection) { - return; - } - this.multiMaterials.push(newMultiMaterial); - this.onNewMultiMaterialAddedObservable.notifyObservers(newMultiMaterial); - } - /** - * Adds the given material to this scene - * @param newMaterial The material to add - */ - addMaterial(newMaterial) { - if (this._blockEntityCollection) { - return; - } - if (newMaterial.getScene() === this && newMaterial._indexInSceneMaterialArray !== -1) { - // Already there?? - return; - } - newMaterial._indexInSceneMaterialArray = this.materials.length; - this.materials.push(newMaterial); - this.onNewMaterialAddedObservable.notifyObservers(newMaterial); - } - /** - * Adds the given morph target to this scene - * @param newMorphTargetManager The morph target to add - */ - addMorphTargetManager(newMorphTargetManager) { - if (this._blockEntityCollection) { - return; - } - this.morphTargetManagers.push(newMorphTargetManager); - } - /** - * Adds the given geometry to this scene - * @param newGeometry The geometry to add - */ - addGeometry(newGeometry) { - if (this._blockEntityCollection) { - return; - } - if (this._geometriesByUniqueId) { - this._geometriesByUniqueId[newGeometry.uniqueId] = this.geometries.length; - } - this.geometries.push(newGeometry); - } - /** - * Adds the given action manager to this scene - * @deprecated - * @param newActionManager The action manager to add - */ - addActionManager(newActionManager) { - this.actionManagers.push(newActionManager); - } - /** - * Adds the given texture to this scene. - * @param newTexture The texture to add - */ - addTexture(newTexture) { - if (this._blockEntityCollection) { - return; - } - this.textures.push(newTexture); - this.onNewTextureAddedObservable.notifyObservers(newTexture); - } - /** - * Switch active camera - * @param newCamera defines the new active camera - * @param attachControl defines if attachControl must be called for the new active camera (default: true) - */ - switchActiveCamera(newCamera, attachControl = true) { - const canvas = this._engine.getInputElement(); - if (!canvas) { - return; - } - if (this.activeCamera) { - this.activeCamera.detachControl(); - } - this.activeCamera = newCamera; - if (attachControl) { - newCamera.attachControl(); - } - } - /** - * sets the active camera of the scene using its Id - * @param id defines the camera's Id - * @returns the new active camera or null if none found. - */ - setActiveCameraById(id) { - const camera = this.getCameraById(id); - if (camera) { - this.activeCamera = camera; - return camera; - } - return null; - } - /** - * sets the active camera of the scene using its name - * @param name defines the camera's name - * @returns the new active camera or null if none found. - */ - setActiveCameraByName(name) { - const camera = this.getCameraByName(name); - if (camera) { - this.activeCamera = camera; - return camera; - } - return null; - } - /** - * get an animation group using its name - * @param name defines the material's name - * @returns the animation group or null if none found. - */ - getAnimationGroupByName(name) { - for (let index = 0; index < this.animationGroups.length; index++) { - if (this.animationGroups[index].name === name) { - return this.animationGroups[index]; - } - } - return null; - } - _getMaterial(allowMultiMaterials, predicate) { - for (let index = 0; index < this.materials.length; index++) { - const material = this.materials[index]; - if (predicate(material)) { - return material; - } - } - if (allowMultiMaterials) { - for (let index = 0; index < this.multiMaterials.length; index++) { - const material = this.multiMaterials[index]; - if (predicate(material)) { - return material; - } - } - } - return null; - } - /** - * Get a material using its unique id - * @param uniqueId defines the material's unique id - * @param allowMultiMaterials determines whether multimaterials should be considered - * @returns the material or null if none found. - */ - getMaterialByUniqueID(uniqueId, allowMultiMaterials = false) { - return this._getMaterial(allowMultiMaterials, (m) => m.uniqueId === uniqueId); - } - /** - * get a material using its id - * @param id defines the material's Id - * @param allowMultiMaterials determines whether multimaterials should be considered - * @returns the material or null if none found. - */ - getMaterialById(id, allowMultiMaterials = false) { - return this._getMaterial(allowMultiMaterials, (m) => m.id === id); - } - /** - * Gets a material using its name - * @param name defines the material's name - * @param allowMultiMaterials determines whether multimaterials should be considered - * @returns the material or null if none found. - */ - getMaterialByName(name, allowMultiMaterials = false) { - return this._getMaterial(allowMultiMaterials, (m) => m.name === name); - } - /** - * Gets a last added material using a given id - * @param id defines the material's id - * @param allowMultiMaterials determines whether multimaterials should be considered - * @returns the last material with the given id or null if none found. - */ - getLastMaterialById(id, allowMultiMaterials = false) { - for (let index = this.materials.length - 1; index >= 0; index--) { - if (this.materials[index].id === id) { - return this.materials[index]; - } - } - if (allowMultiMaterials) { - for (let index = this.multiMaterials.length - 1; index >= 0; index--) { - if (this.multiMaterials[index].id === id) { - return this.multiMaterials[index]; - } - } - } - return null; - } - /** - * Get a texture using its unique id - * @param uniqueId defines the texture's unique id - * @returns the texture or null if none found. - */ - getTextureByUniqueId(uniqueId) { - for (let index = 0; index < this.textures.length; index++) { - if (this.textures[index].uniqueId === uniqueId) { - return this.textures[index]; - } - } - return null; - } - /** - * Gets a texture using its name - * @param name defines the texture's name - * @returns the texture or null if none found. - */ - getTextureByName(name) { - for (let index = 0; index < this.textures.length; index++) { - if (this.textures[index].name === name) { - return this.textures[index]; - } - } - return null; - } - /** - * Gets a camera using its Id - * @param id defines the Id to look for - * @returns the camera or null if not found - */ - getCameraById(id) { - for (let index = 0; index < this.cameras.length; index++) { - if (this.cameras[index].id === id) { - return this.cameras[index]; - } - } - return null; - } - /** - * Gets a camera using its unique Id - * @param uniqueId defines the unique Id to look for - * @returns the camera or null if not found - */ - getCameraByUniqueId(uniqueId) { - for (let index = 0; index < this.cameras.length; index++) { - if (this.cameras[index].uniqueId === uniqueId) { - return this.cameras[index]; - } - } - return null; - } - /** - * Gets a camera using its name - * @param name defines the camera's name - * @returns the camera or null if none found. - */ - getCameraByName(name) { - for (let index = 0; index < this.cameras.length; index++) { - if (this.cameras[index].name === name) { - return this.cameras[index]; - } - } - return null; - } - /** - * Gets a bone using its Id - * @param id defines the bone's Id - * @returns the bone or null if not found - */ - getBoneById(id) { - for (let skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) { - const skeleton = this.skeletons[skeletonIndex]; - for (let boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) { - if (skeleton.bones[boneIndex].id === id) { - return skeleton.bones[boneIndex]; - } - } - } - return null; - } - /** - * Gets a bone using its id - * @param name defines the bone's name - * @returns the bone or null if not found - */ - getBoneByName(name) { - for (let skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) { - const skeleton = this.skeletons[skeletonIndex]; - for (let boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) { - if (skeleton.bones[boneIndex].name === name) { - return skeleton.bones[boneIndex]; - } - } - } - return null; - } - /** - * Gets a light node using its name - * @param name defines the the light's name - * @returns the light or null if none found. - */ - getLightByName(name) { - for (let index = 0; index < this.lights.length; index++) { - if (this.lights[index].name === name) { - return this.lights[index]; - } - } - return null; - } - /** - * Gets a light node using its Id - * @param id defines the light's Id - * @returns the light or null if none found. - */ - getLightById(id) { - for (let index = 0; index < this.lights.length; index++) { - if (this.lights[index].id === id) { - return this.lights[index]; - } - } - return null; - } - /** - * Gets a light node using its scene-generated unique Id - * @param uniqueId defines the light's unique Id - * @returns the light or null if none found. - */ - getLightByUniqueId(uniqueId) { - for (let index = 0; index < this.lights.length; index++) { - if (this.lights[index].uniqueId === uniqueId) { - return this.lights[index]; - } - } - return null; - } - /** - * Gets a particle system by Id - * @param id defines the particle system Id - * @returns the corresponding system or null if none found - */ - getParticleSystemById(id) { - for (let index = 0; index < this.particleSystems.length; index++) { - if (this.particleSystems[index].id === id) { - return this.particleSystems[index]; - } - } - return null; - } - /** - * Gets a geometry using its Id - * @param id defines the geometry's Id - * @returns the geometry or null if none found. - */ - getGeometryById(id) { - for (let index = 0; index < this.geometries.length; index++) { - if (this.geometries[index].id === id) { - return this.geometries[index]; - } - } - return null; - } - _getGeometryByUniqueId(uniqueId) { - if (this._geometriesByUniqueId) { - const index = this._geometriesByUniqueId[uniqueId]; - if (index !== undefined) { - return this.geometries[index]; - } - } - else { - for (let index = 0; index < this.geometries.length; index++) { - if (this.geometries[index].uniqueId === uniqueId) { - return this.geometries[index]; - } - } - } - return null; - } - /** - * Add a new geometry to this scene - * @param geometry defines the geometry to be added to the scene. - * @param force defines if the geometry must be pushed even if a geometry with this id already exists - * @returns a boolean defining if the geometry was added or not - */ - pushGeometry(geometry, force) { - if (!force && this._getGeometryByUniqueId(geometry.uniqueId)) { - return false; - } - this.addGeometry(geometry); - this.onNewGeometryAddedObservable.notifyObservers(geometry); - return true; - } - /** - * Removes an existing geometry - * @param geometry defines the geometry to be removed from the scene - * @returns a boolean defining if the geometry was removed or not - */ - removeGeometry(geometry) { - let index; - if (this._geometriesByUniqueId) { - index = this._geometriesByUniqueId[geometry.uniqueId]; - if (index === undefined) { - return false; - } - } - else { - index = this.geometries.indexOf(geometry); - if (index < 0) { - return false; - } - } - if (index !== this.geometries.length - 1) { - const lastGeometry = this.geometries[this.geometries.length - 1]; - if (lastGeometry) { - this.geometries[index] = lastGeometry; - if (this._geometriesByUniqueId) { - this._geometriesByUniqueId[lastGeometry.uniqueId] = index; - } - } - } - if (this._geometriesByUniqueId) { - this._geometriesByUniqueId[geometry.uniqueId] = undefined; - } - this.geometries.pop(); - this.onGeometryRemovedObservable.notifyObservers(geometry); - return true; - } - /** - * Gets the list of geometries attached to the scene - * @returns an array of Geometry - */ - getGeometries() { - return this.geometries; - } - /** - * Gets the first added mesh found of a given Id - * @param id defines the Id to search for - * @returns the mesh found or null if not found at all - */ - getMeshById(id) { - for (let index = 0; index < this.meshes.length; index++) { - if (this.meshes[index].id === id) { - return this.meshes[index]; - } - } - return null; - } - /** - * Gets a list of meshes using their Id - * @param id defines the Id to search for - * @returns a list of meshes - */ - getMeshesById(id) { - return this.meshes.filter(function (m) { - return m.id === id; - }); - } - /** - * Gets the first added transform node found of a given Id - * @param id defines the Id to search for - * @returns the found transform node or null if not found at all. - */ - getTransformNodeById(id) { - for (let index = 0; index < this.transformNodes.length; index++) { - if (this.transformNodes[index].id === id) { - return this.transformNodes[index]; - } - } - return null; - } - /** - * Gets a transform node with its auto-generated unique Id - * @param uniqueId defines the unique Id to search for - * @returns the found transform node or null if not found at all. - */ - getTransformNodeByUniqueId(uniqueId) { - for (let index = 0; index < this.transformNodes.length; index++) { - if (this.transformNodes[index].uniqueId === uniqueId) { - return this.transformNodes[index]; - } - } - return null; - } - /** - * Gets a list of transform nodes using their Id - * @param id defines the Id to search for - * @returns a list of transform nodes - */ - getTransformNodesById(id) { - return this.transformNodes.filter(function (m) { - return m.id === id; - }); - } - /** - * Gets a mesh with its auto-generated unique Id - * @param uniqueId defines the unique Id to search for - * @returns the found mesh or null if not found at all. - */ - getMeshByUniqueId(uniqueId) { - for (let index = 0; index < this.meshes.length; index++) { - if (this.meshes[index].uniqueId === uniqueId) { - return this.meshes[index]; - } - } - return null; - } - /** - * Gets a the last added mesh using a given Id - * @param id defines the Id to search for - * @returns the found mesh or null if not found at all. - */ - getLastMeshById(id) { - for (let index = this.meshes.length - 1; index >= 0; index--) { - if (this.meshes[index].id === id) { - return this.meshes[index]; - } - } - return null; - } - /** - * Gets a the last transform node using a given Id - * @param id defines the Id to search for - * @returns the found mesh or null if not found at all. - */ - getLastTransformNodeById(id) { - for (let index = this.transformNodes.length - 1; index >= 0; index--) { - if (this.transformNodes[index].id === id) { - return this.transformNodes[index]; - } - } - return null; - } - /** - * Gets a the last added node (Mesh, Camera, Light) using a given Id - * @param id defines the Id to search for - * @returns the found node or null if not found at all - */ - getLastEntryById(id) { - let index; - for (index = this.meshes.length - 1; index >= 0; index--) { - if (this.meshes[index].id === id) { - return this.meshes[index]; - } - } - for (index = this.transformNodes.length - 1; index >= 0; index--) { - if (this.transformNodes[index].id === id) { - return this.transformNodes[index]; - } - } - for (index = this.cameras.length - 1; index >= 0; index--) { - if (this.cameras[index].id === id) { - return this.cameras[index]; - } - } - for (index = this.lights.length - 1; index >= 0; index--) { - if (this.lights[index].id === id) { - return this.lights[index]; - } - } - return null; - } - /** - * Gets a node (Mesh, Camera, Light) using a given Id - * @param id defines the Id to search for - * @returns the found node or null if not found at all - */ - getNodeById(id) { - const mesh = this.getMeshById(id); - if (mesh) { - return mesh; - } - const transformNode = this.getTransformNodeById(id); - if (transformNode) { - return transformNode; - } - const light = this.getLightById(id); - if (light) { - return light; - } - const camera = this.getCameraById(id); - if (camera) { - return camera; - } - const bone = this.getBoneById(id); - if (bone) { - return bone; - } - return null; - } - /** - * Gets a node (Mesh, Camera, Light) using a given name - * @param name defines the name to search for - * @returns the found node or null if not found at all. - */ - getNodeByName(name) { - const mesh = this.getMeshByName(name); - if (mesh) { - return mesh; - } - const transformNode = this.getTransformNodeByName(name); - if (transformNode) { - return transformNode; - } - const light = this.getLightByName(name); - if (light) { - return light; - } - const camera = this.getCameraByName(name); - if (camera) { - return camera; - } - const bone = this.getBoneByName(name); - if (bone) { - return bone; - } - return null; - } - /** - * Gets a mesh using a given name - * @param name defines the name to search for - * @returns the found mesh or null if not found at all. - */ - getMeshByName(name) { - for (let index = 0; index < this.meshes.length; index++) { - if (this.meshes[index].name === name) { - return this.meshes[index]; - } - } - return null; - } - /** - * Gets a transform node using a given name - * @param name defines the name to search for - * @returns the found transform node or null if not found at all. - */ - getTransformNodeByName(name) { - for (let index = 0; index < this.transformNodes.length; index++) { - if (this.transformNodes[index].name === name) { - return this.transformNodes[index]; - } - } - return null; - } - /** - * Gets a skeleton using a given Id (if many are found, this function will pick the last one) - * @param id defines the Id to search for - * @returns the found skeleton or null if not found at all. - */ - getLastSkeletonById(id) { - for (let index = this.skeletons.length - 1; index >= 0; index--) { - if (this.skeletons[index].id === id) { - return this.skeletons[index]; - } - } - return null; - } - /** - * Gets a skeleton using a given auto generated unique id - * @param uniqueId defines the unique id to search for - * @returns the found skeleton or null if not found at all. - */ - getSkeletonByUniqueId(uniqueId) { - for (let index = 0; index < this.skeletons.length; index++) { - if (this.skeletons[index].uniqueId === uniqueId) { - return this.skeletons[index]; - } - } - return null; - } - /** - * Gets a skeleton using a given id (if many are found, this function will pick the first one) - * @param id defines the id to search for - * @returns the found skeleton or null if not found at all. - */ - getSkeletonById(id) { - for (let index = 0; index < this.skeletons.length; index++) { - if (this.skeletons[index].id === id) { - return this.skeletons[index]; - } - } - return null; - } - /** - * Gets a skeleton using a given name - * @param name defines the name to search for - * @returns the found skeleton or null if not found at all. - */ - getSkeletonByName(name) { - for (let index = 0; index < this.skeletons.length; index++) { - if (this.skeletons[index].name === name) { - return this.skeletons[index]; - } - } - return null; - } - /** - * Gets a morph target manager using a given id (if many are found, this function will pick the last one) - * @param id defines the id to search for - * @returns the found morph target manager or null if not found at all. - */ - getMorphTargetManagerById(id) { - for (let index = 0; index < this.morphTargetManagers.length; index++) { - if (this.morphTargetManagers[index].uniqueId === id) { - return this.morphTargetManagers[index]; - } - } - return null; - } - /** - * Gets a morph target using a given id (if many are found, this function will pick the first one) - * @param id defines the id to search for - * @returns the found morph target or null if not found at all. - */ - getMorphTargetById(id) { - for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) { - const morphTargetManager = this.morphTargetManagers[managerIndex]; - for (let index = 0; index < morphTargetManager.numTargets; ++index) { - const target = morphTargetManager.getTarget(index); - if (target.id === id) { - return target; - } - } - } - return null; - } - /** - * Gets a morph target using a given name (if many are found, this function will pick the first one) - * @param name defines the name to search for - * @returns the found morph target or null if not found at all. - */ - getMorphTargetByName(name) { - for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) { - const morphTargetManager = this.morphTargetManagers[managerIndex]; - for (let index = 0; index < morphTargetManager.numTargets; ++index) { - const target = morphTargetManager.getTarget(index); - if (target.name === name) { - return target; - } - } - } - return null; - } - /** - * Gets a post process using a given name (if many are found, this function will pick the first one) - * @param name defines the name to search for - * @returns the found post process or null if not found at all. - */ - getPostProcessByName(name) { - for (let postProcessIndex = 0; postProcessIndex < this.postProcesses.length; ++postProcessIndex) { - const postProcess = this.postProcesses[postProcessIndex]; - if (postProcess.name === name) { - return postProcess; - } - } - return null; - } - /** - * Gets a boolean indicating if the given mesh is active - * @param mesh defines the mesh to look for - * @returns true if the mesh is in the active list - */ - isActiveMesh(mesh) { - return this._activeMeshes.indexOf(mesh) !== -1; - } - /** - * Return a unique id as a string which can serve as an identifier for the scene - */ - get uid() { - if (!this._uid) { - this._uid = tools_Tools.RandomId(); - } - return this._uid; - } - /** - * Add an externally attached data from its key. - * This method call will fail and return false, if such key already exists. - * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method. - * @param key the unique key that identifies the data - * @param data the data object to associate to the key for this Engine instance - * @returns true if no such key were already present and the data was added successfully, false otherwise - */ - addExternalData(key, data) { - if (!this._externalData) { - this._externalData = new StringDictionary(); - } - return this._externalData.add(key, data); - } - /** - * Get an externally attached data from its key - * @param key the unique key that identifies the data - * @returns the associated data, if present (can be null), or undefined if not present - */ - getExternalData(key) { - if (!this._externalData) { - return null; - } - return this._externalData.get(key); - } - /** - * Get an externally attached data from its key, create it using a factory if it's not already present - * @param key the unique key that identifies the data - * @param factory the factory that will be called to create the instance if and only if it doesn't exists - * @returns the associated data, can be null if the factory returned null. - */ - getOrAddExternalDataWithFactory(key, factory) { - if (!this._externalData) { - this._externalData = new StringDictionary(); - } - return this._externalData.getOrAddWithFactory(key, factory); - } - /** - * Remove an externally attached data from the Engine instance - * @param key the unique key that identifies the data - * @returns true if the data was successfully removed, false if it doesn't exist - */ - removeExternalData(key) { - return this._externalData.remove(key); - } - _evaluateSubMesh(subMesh, mesh, initialMesh, forcePush) { - if (forcePush || subMesh.isInFrustum(this._frustumPlanes)) { - for (const step of this._evaluateSubMeshStage) { - step.action(mesh, subMesh); - } - const material = subMesh.getMaterial(); - if (material !== null && material !== undefined) { - // Render targets - if (material.hasRenderTargetTextures && material.getRenderTargetTextures != null) { - if (this._processedMaterials.indexOf(material) === -1) { - this._processedMaterials.push(material); - this._materialsRenderTargets.concatWithNoDuplicate(material.getRenderTargetTextures()); - } - } - // Dispatch - this._renderingManager.dispatch(subMesh, mesh, material); - } - } - } - /** - * Clear the processed materials smart array preventing retention point in material dispose. - */ - freeProcessedMaterials() { - this._processedMaterials.dispose(); - } - /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups - * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance - * when disposing several meshes in a row or a hierarchy of meshes. - * When used, it is the responsibility of the user to blockfreeActiveMeshesAndRenderingGroups back to false. - */ - get blockfreeActiveMeshesAndRenderingGroups() { - return this._preventFreeActiveMeshesAndRenderingGroups; - } - set blockfreeActiveMeshesAndRenderingGroups(value) { - if (this._preventFreeActiveMeshesAndRenderingGroups === value) { - return; - } - if (value) { - this.freeActiveMeshes(); - this.freeRenderingGroups(); - } - this._preventFreeActiveMeshesAndRenderingGroups = value; - } - /** - * Clear the active meshes smart array preventing retention point in mesh dispose. - */ - freeActiveMeshes() { - if (this.blockfreeActiveMeshesAndRenderingGroups) { - return; - } - this._activeMeshes.dispose(); - if (this.activeCamera && this.activeCamera._activeMeshes) { - this.activeCamera._activeMeshes.dispose(); - } - if (this.activeCameras) { - for (let i = 0; i < this.activeCameras.length; i++) { - const activeCamera = this.activeCameras[i]; - if (activeCamera && activeCamera._activeMeshes) { - activeCamera._activeMeshes.dispose(); - } - } - } - } - /** - * Clear the info related to rendering groups preventing retention points during dispose. - */ - freeRenderingGroups() { - if (this.blockfreeActiveMeshesAndRenderingGroups) { - return; - } - if (this._renderingManager) { - this._renderingManager.freeRenderingGroups(); - } - if (this.textures) { - for (let i = 0; i < this.textures.length; i++) { - const texture = this.textures[i]; - if (texture && texture.renderList) { - texture.freeRenderingGroups(); - } - } - } - } - /** @internal */ - _isInIntermediateRendering() { - return this._intermediateRendering; - } - /** - * Use this function to stop evaluating active meshes. The current list will be keep alive between frames - * @param skipEvaluateActiveMeshes defines an optional boolean indicating that the evaluate active meshes step must be completely skipped - * @param onSuccess optional success callback - * @param onError optional error callback - * @param freezeMeshes defines if meshes should be frozen (true by default) - * @param keepFrustumCulling defines if you want to keep running the frustum clipping (false by default) - * @returns the current scene - */ - freezeActiveMeshes(skipEvaluateActiveMeshes = false, onSuccess, onError, freezeMeshes = true, keepFrustumCulling = false) { - this.executeWhenReady(() => { - if (!this.activeCamera) { - onError && onError("No active camera found"); - return; - } - if (!this._frustumPlanes) { - this.updateTransformMatrix(); - } - this._evaluateActiveMeshes(); - this._activeMeshesFrozen = true; - this._activeMeshesFrozenButKeepClipping = keepFrustumCulling; - this._skipEvaluateActiveMeshesCompletely = skipEvaluateActiveMeshes; - if (freezeMeshes) { - for (let index = 0; index < this._activeMeshes.length; index++) { - this._activeMeshes.data[index]._freeze(); - } - } - onSuccess && onSuccess(); - }); - return this; - } - /** - * Use this function to restart evaluating active meshes on every frame - * @returns the current scene - */ - unfreezeActiveMeshes() { - for (let index = 0; index < this.meshes.length; index++) { - const mesh = this.meshes[index]; - if (mesh._internalAbstractMeshDataInfo) { - mesh._internalAbstractMeshDataInfo._isActive = false; - } - } - for (let index = 0; index < this._activeMeshes.length; index++) { - this._activeMeshes.data[index]._unFreeze(); - } - this._activeMeshesFrozen = false; - return this; - } - _executeActiveContainerCleanup(container) { - const isInFastMode = this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1; - if (!isInFastMode && this._activeMeshesFrozen && this._activeMeshes.length) { - return; // Do not execute in frozen mode - } - // We need to ensure we are not in the rendering loop - this.onBeforeRenderObservable.addOnce(() => container.dispose()); - } - _evaluateActiveMeshes() { - var _a; - if (this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1) { - if (this._activeMeshes.length > 0) { - (_a = this.activeCamera) === null || _a === void 0 ? void 0 : _a._activeMeshes.reset(); - this._activeMeshes.reset(); - this._renderingManager.reset(); - this._processedMaterials.reset(); - this._activeParticleSystems.reset(); - this._activeSkeletons.reset(); - this._softwareSkinnedMeshes.reset(); - } - return; - } - if (this._activeMeshesFrozen && this._activeMeshes.length) { - if (!this._skipEvaluateActiveMeshesCompletely) { - const len = this._activeMeshes.length; - for (let i = 0; i < len; i++) { - const mesh = this._activeMeshes.data[i]; - mesh.computeWorldMatrix(); - } - } - if (this._activeParticleSystems) { - const psLength = this._activeParticleSystems.length; - for (let i = 0; i < psLength; i++) { - this._activeParticleSystems.data[i].animate(); - } - } - this._renderingManager.resetSprites(); - return; - } - if (!this.activeCamera) { - return; - } - this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this); - this.activeCamera._activeMeshes.reset(); - this._activeMeshes.reset(); - this._renderingManager.reset(); - this._processedMaterials.reset(); - this._activeParticleSystems.reset(); - this._activeSkeletons.reset(); - this._softwareSkinnedMeshes.reset(); - this._materialsRenderTargets.reset(); - for (const step of this._beforeEvaluateActiveMeshStage) { - step.action(); - } - // Determine mesh candidates - const meshes = this.getActiveMeshCandidates(); - // Check each mesh - const len = meshes.length; - for (let i = 0; i < len; i++) { - const mesh = meshes.data[i]; - mesh._internalAbstractMeshDataInfo._currentLODIsUpToDate = false; - if (mesh.isBlocked) { - continue; - } - this._totalVertices.addCount(mesh.getTotalVertices(), false); - if (!mesh.isReady() || !mesh.isEnabled() || mesh.scaling.hasAZeroComponent) { - continue; - } - mesh.computeWorldMatrix(); - // Intersections - if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(12, 13)) { - this._meshesForIntersections.pushNoDuplicate(mesh); - } - // Switch to current LOD - let meshToRender = this.customLODSelector ? this.customLODSelector(mesh, this.activeCamera) : mesh.getLOD(this.activeCamera); - mesh._internalAbstractMeshDataInfo._currentLOD = meshToRender; - mesh._internalAbstractMeshDataInfo._currentLODIsUpToDate = true; - if (meshToRender === undefined || meshToRender === null) { - continue; - } - // Compute world matrix if LOD is billboard - if (meshToRender !== mesh && meshToRender.billboardMode !== 0) { - meshToRender.computeWorldMatrix(); - } - mesh._preActivate(); - if (mesh.isVisible && - mesh.visibility > 0 && - (mesh.layerMask & this.activeCamera.layerMask) !== 0 && - (this._skipFrustumClipping || mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) { - this._activeMeshes.push(mesh); - this.activeCamera._activeMeshes.push(mesh); - if (meshToRender !== mesh) { - meshToRender._activate(this._renderId, false); - } - for (const step of this._preActiveMeshStage) { - step.action(mesh); - } - if (mesh._activate(this._renderId, false)) { - if (!mesh.isAnInstance) { - meshToRender._internalAbstractMeshDataInfo._onlyForInstances = false; - } - else { - if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) { - meshToRender = mesh; - } - } - meshToRender._internalAbstractMeshDataInfo._isActive = true; - this._activeMesh(mesh, meshToRender); - } - mesh._postActivate(); - } - } - this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this); - // Particle systems - if (this.particlesEnabled) { - this.onBeforeParticlesRenderingObservable.notifyObservers(this); - for (let particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) { - const particleSystem = this.particleSystems[particleIndex]; - if (!particleSystem.isStarted() || !particleSystem.emitter) { - continue; - } - const emitter = particleSystem.emitter; - if (!emitter.position || emitter.isEnabled()) { - this._activeParticleSystems.push(particleSystem); - particleSystem.animate(); - this._renderingManager.dispatchParticles(particleSystem); - } - } - this.onAfterParticlesRenderingObservable.notifyObservers(this); - } - } - _activeMesh(sourceMesh, mesh) { - if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) { - if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) { - mesh.skeleton.prepare(); - this._activeBones.addCount(mesh.skeleton.bones.length, false); - } - if (!mesh.computeBonesUsingShaders) { - this._softwareSkinnedMeshes.pushNoDuplicate(mesh); - } - } - let forcePush = sourceMesh.hasInstances || sourceMesh.isAnInstance || this.dispatchAllSubMeshesOfActiveMeshes || this._skipFrustumClipping || mesh.alwaysSelectAsActiveMesh; - if (mesh && mesh.subMeshes && mesh.subMeshes.length > 0) { - const subMeshes = this.getActiveSubMeshCandidates(mesh); - const len = subMeshes.length; - forcePush = forcePush || len === 1; - for (let i = 0; i < len; i++) { - const subMesh = subMeshes.data[i]; - this._evaluateSubMesh(subMesh, mesh, sourceMesh, forcePush); - } - } - } - /** - * Update the transform matrix to update from the current active camera - * @param force defines a boolean used to force the update even if cache is up to date - */ - updateTransformMatrix(force) { - if (!this.activeCamera) { - return; - } - if (this.activeCamera._renderingMultiview) { - const leftCamera = this.activeCamera._rigCameras[0]; - const rightCamera = this.activeCamera._rigCameras[1]; - this.setTransformMatrix(leftCamera.getViewMatrix(), leftCamera.getProjectionMatrix(force), rightCamera.getViewMatrix(), rightCamera.getProjectionMatrix(force)); - } - else { - this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force)); - } - } - _bindFrameBuffer(camera, clear = true) { - if (camera && camera._multiviewTexture) { - camera._multiviewTexture._bindFrameBuffer(); - } - else if (camera && camera.outputRenderTarget) { - camera.outputRenderTarget._bindFrameBuffer(); - } - else { - if (!this._engine._currentFrameBufferIsDefaultFrameBuffer()) { - this._engine.restoreDefaultFramebuffer(); - } - } - if (clear) { - this._clearFrameBuffer(camera); - } - } - _clearFrameBuffer(camera) { - // we assume the framebuffer currently bound is the right one - if (camera && camera._multiviewTexture) { - // no clearing? - } - else if (camera && camera.outputRenderTarget && !camera._renderingMultiview) { - const rtt = camera.outputRenderTarget; - if (rtt.onClearObservable.hasObservers()) { - rtt.onClearObservable.notifyObservers(this._engine); - } - else if (!rtt.skipInitialClear) { - if (this.autoClear) { - this._engine.clear(rtt.clearColor || this.clearColor, !rtt._cleared, true, true); - } - rtt._cleared = true; - } - } - else { - if (!this._defaultFrameBufferCleared) { - this._defaultFrameBufferCleared = true; - this._clear(); - } - else { - this._engine.clear(null, false, true, true); - } - } - } - /** - * @internal - */ - _renderForCamera(camera, rigParent, bindFrameBuffer = true) { - var _a, _b, _c; - if (camera && camera._skipRendering) { - return; - } - const engine = this._engine; - // Use _activeCamera instead of activeCamera to avoid onActiveCameraChanged - this._activeCamera = camera; - if (!this.activeCamera) { - throw new Error("Active camera not set"); - } - // Viewport - engine.setViewport(this.activeCamera.viewport); - // Camera - this.resetCachedMaterial(); - this._renderId++; - if (!this.prePass && bindFrameBuffer) { - let skipInitialClear = true; - if (camera._renderingMultiview && camera.outputRenderTarget) { - skipInitialClear = camera.outputRenderTarget.skipInitialClear; - if (this.autoClear) { - this._defaultFrameBufferCleared = false; - camera.outputRenderTarget.skipInitialClear = false; - } - } - this._bindFrameBuffer(this._activeCamera); - if (camera._renderingMultiview && camera.outputRenderTarget) { - camera.outputRenderTarget.skipInitialClear = skipInitialClear; - } - } - this.updateTransformMatrix(); - this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera); - // Meshes - this._evaluateActiveMeshes(); - // Software skinning - for (let softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) { - const mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex]; - mesh.applySkeleton(mesh.skeleton); - } - // Render targets - this.onBeforeRenderTargetsRenderObservable.notifyObservers(this); - this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets); - if (camera.customRenderTargets && camera.customRenderTargets.length > 0) { - this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets); - } - if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) { - this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets); - } - if (this.environmentTexture && this.environmentTexture.isRenderTarget) { - this._renderTargets.pushNoDuplicate(this.environmentTexture); - } - // Collects render targets from external components. - for (const step of this._gatherActiveCameraRenderTargetsStage) { - step.action(this._renderTargets); - } - let needRebind = false; - if (this.renderTargetsEnabled) { - this._intermediateRendering = true; - if (this._renderTargets.length > 0) { - tools_Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0); - for (let renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) { - const renderTarget = this._renderTargets.data[renderIndex]; - if (renderTarget._shouldRender()) { - this._renderId++; - const hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera; - renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets); - needRebind = true; - } - } - tools_Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0); - this._renderId++; - } - for (const step of this._cameraDrawRenderTargetStage) { - needRebind = step.action(this.activeCamera) || needRebind; - } - this._intermediateRendering = false; - } - this._engine.currentRenderPassId = (_c = (_b = (_a = camera.outputRenderTarget) === null || _a === void 0 ? void 0 : _a.renderPassId) !== null && _b !== void 0 ? _b : camera.renderPassId) !== null && _c !== void 0 ? _c : 0; - // Restore framebuffer after rendering to targets - if (needRebind && !this.prePass) { - this._bindFrameBuffer(this._activeCamera, false); - } - this.onAfterRenderTargetsRenderObservable.notifyObservers(this); - // Prepare Frame - if (this.postProcessManager && !camera._multiviewTexture && !this.prePass) { - this.postProcessManager._prepareFrame(); - } - // Before Camera Draw - for (const step of this._beforeCameraDrawStage) { - step.action(this.activeCamera); - } - // Render - this.onBeforeDrawPhaseObservable.notifyObservers(this); - if (engine.snapshotRendering && engine.snapshotRenderingMode === 1) { - this.finalizeSceneUbo(); - } - this._renderingManager.render(null, null, true, true); - this.onAfterDrawPhaseObservable.notifyObservers(this); - // After Camera Draw - for (const step of this._afterCameraDrawStage) { - step.action(this.activeCamera); - } - // Finalize frame - if (this.postProcessManager && !camera._multiviewTexture) { - // if the camera has an output render target, render the post process to the render target - const texture = camera.outputRenderTarget ? camera.outputRenderTarget.renderTarget : undefined; - this.postProcessManager._finalizeFrame(camera.isIntermediate, texture); - } - // After post process - for (const step of this._afterCameraPostProcessStage) { - step.action(this.activeCamera); - } - // Reset some special arrays - this._renderTargets.reset(); - this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera); - } - _processSubCameras(camera, bindFrameBuffer = true) { - if (camera.cameraRigMode === 0 || camera._renderingMultiview) { - if (camera._renderingMultiview && !this._multiviewSceneUbo) { - this._createMultiviewUbo(); - } - this._renderForCamera(camera, undefined, bindFrameBuffer); - this.onAfterRenderCameraObservable.notifyObservers(camera); - return; - } - if (camera._useMultiviewToSingleView) { - this._renderMultiviewToSingleView(camera); - } - else { - // rig cameras - this.onBeforeCameraRenderObservable.notifyObservers(camera); - for (let index = 0; index < camera._rigCameras.length; index++) { - this._renderForCamera(camera._rigCameras[index], camera); - } - } - // Use _activeCamera instead of activeCamera to avoid onActiveCameraChanged - this._activeCamera = camera; - this.updateTransformMatrix(); - this.onAfterRenderCameraObservable.notifyObservers(camera); - } - _checkIntersections() { - for (let index = 0; index < this._meshesForIntersections.length; index++) { - const sourceMesh = this._meshesForIntersections.data[index]; - if (!sourceMesh.actionManager) { - continue; - } - for (let actionIndex = 0; sourceMesh.actionManager && actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) { - const action = sourceMesh.actionManager.actions[actionIndex]; - if (action.trigger === 12 || action.trigger === 13) { - const parameters = action.getTriggerParameter(); - const otherMesh = parameters.mesh ? parameters.mesh : parameters; - const areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection); - const currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh); - if (areIntersecting && currentIntersectionInProgress === -1) { - if (action.trigger === 12) { - action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh)); - sourceMesh._intersectionsInProgress.push(otherMesh); - } - else if (action.trigger === 13) { - sourceMesh._intersectionsInProgress.push(otherMesh); - } - } - else if (!areIntersecting && currentIntersectionInProgress > -1) { - //They intersected, and now they don't. - //is this trigger an exit trigger? execute an event. - if (action.trigger === 13) { - action._executeCurrent(ActionEvent.CreateNew(sourceMesh, undefined, otherMesh)); - } - //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array. - if (!sourceMesh.actionManager.hasSpecificTrigger(13, (parameter) => { - const parameterMesh = parameter.mesh ? parameter.mesh : parameter; - return otherMesh === parameterMesh; - }) || - action.trigger === 13) { - sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1); - } - } - } - } - } - } - /** - * @internal - */ - _advancePhysicsEngineStep(step) { - // Do nothing. Code will be replaced if physics engine component is referenced - } - /** @internal */ - _animate() { - // Nothing to do as long as Animatable have not been imported. - } - /** Execute all animations (for a frame) */ - animate() { - if (this._engine.isDeterministicLockStep()) { - let deltaTime = Math.max(scene_Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), scene_Scene.MaxDeltaTime)) + this._timeAccumulator; - const defaultFrameTime = this._engine.getTimeStep(); - const defaultFPS = 1000.0 / defaultFrameTime / 1000.0; - let stepsTaken = 0; - const maxSubSteps = this._engine.getLockstepMaxSteps(); - let internalSteps = Math.floor(deltaTime / defaultFrameTime); - internalSteps = Math.min(internalSteps, maxSubSteps); - while (deltaTime > 0 && stepsTaken < internalSteps) { - this.onBeforeStepObservable.notifyObservers(this); - // Animations - this._animationRatio = defaultFrameTime * defaultFPS; - this._animate(); - this.onAfterAnimationsObservable.notifyObservers(this); - // Physics - if (this.physicsEnabled) { - this._advancePhysicsEngineStep(defaultFrameTime); - } - this.onAfterStepObservable.notifyObservers(this); - this._currentStepId++; - stepsTaken++; - deltaTime -= defaultFrameTime; - } - this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime; - } - else { - // Animations - const deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(scene_Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), scene_Scene.MaxDeltaTime)); - this._animationRatio = deltaTime * (60.0 / 1000.0); - this._animate(); - this.onAfterAnimationsObservable.notifyObservers(this); - // Physics - if (this.physicsEnabled) { - this._advancePhysicsEngineStep(deltaTime); - } - } - } - _clear() { - if (this.autoClearDepthAndStencil || this.autoClear) { - this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil); - } - } - _checkCameraRenderTarget(camera) { - var _a; - if ((camera === null || camera === void 0 ? void 0 : camera.outputRenderTarget) && !(camera === null || camera === void 0 ? void 0 : camera.isRigCamera)) { - camera.outputRenderTarget._cleared = false; - } - if ((_a = camera === null || camera === void 0 ? void 0 : camera.rigCameras) === null || _a === void 0 ? void 0 : _a.length) { - for (let i = 0; i < camera.rigCameras.length; ++i) { - const rtt = camera.rigCameras[i].outputRenderTarget; - if (rtt) { - rtt._cleared = false; - } - } - } - } - /** - * Resets the draw wrappers cache of all meshes - * @param passId If provided, releases only the draw wrapper corresponding to this render pass id - */ - resetDrawCache(passId) { - if (!this.meshes) { - return; - } - for (const mesh of this.meshes) { - mesh.resetDrawCache(passId); - } - } - /** - * Render the scene - * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default) - * @param ignoreAnimations defines a boolean indicating if animations should not be executed (false by default) - */ - render(updateCameras = true, ignoreAnimations = false) { - var _a, _b, _c; - if (this.isDisposed) { - return; - } - if (this.onReadyObservable.hasObservers() && this._executeWhenReadyTimeoutId === null) { - this._checkIsReady(); - } - this._frameId++; - this._defaultFrameBufferCleared = false; - this._checkCameraRenderTarget(this.activeCamera); - if ((_a = this.activeCameras) === null || _a === void 0 ? void 0 : _a.length) { - this.activeCameras.forEach(this._checkCameraRenderTarget); - } - // Register components that have been associated lately to the scene. - this._registerTransientComponents(); - this._activeParticles.fetchNewFrame(); - this._totalVertices.fetchNewFrame(); - this._activeIndices.fetchNewFrame(); - this._activeBones.fetchNewFrame(); - this._meshesForIntersections.reset(); - this.resetCachedMaterial(); - this.onBeforeAnimationsObservable.notifyObservers(this); - // Actions - if (this.actionManager) { - this.actionManager.processTrigger(11); - } - // Animations - if (!ignoreAnimations) { - this.animate(); - } - // Before camera update steps - for (const step of this._beforeCameraUpdateStage) { - step.action(); - } - // Update Cameras - if (updateCameras) { - if (this.activeCameras && this.activeCameras.length > 0) { - for (let cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) { - const camera = this.activeCameras[cameraIndex]; - camera.update(); - if (camera.cameraRigMode !== 0) { - // rig cameras - for (let index = 0; index < camera._rigCameras.length; index++) { - camera._rigCameras[index].update(); - } - } - } - } - else if (this.activeCamera) { - this.activeCamera.update(); - if (this.activeCamera.cameraRigMode !== 0) { - // rig cameras - for (let index = 0; index < this.activeCamera._rigCameras.length; index++) { - this.activeCamera._rigCameras[index].update(); - } - } - } - } - // Before render - this.onBeforeRenderObservable.notifyObservers(this); - const engine = this.getEngine(); - // Customs render targets - this.onBeforeRenderTargetsRenderObservable.notifyObservers(this); - const currentActiveCamera = ((_b = this.activeCameras) === null || _b === void 0 ? void 0 : _b.length) ? this.activeCameras[0] : this.activeCamera; - if (this.renderTargetsEnabled) { - tools_Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0); - this._intermediateRendering = true; - for (let customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) { - const renderTarget = this.customRenderTargets[customIndex]; - if (renderTarget._shouldRender()) { - this._renderId++; - this.activeCamera = renderTarget.activeCamera || this.activeCamera; - if (!this.activeCamera) { - throw new Error("Active camera not set"); - } - // Viewport - engine.setViewport(this.activeCamera.viewport); - // Camera - this.updateTransformMatrix(); - renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets); - } - } - tools_Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0); - this._intermediateRendering = false; - this._renderId++; - } - this._engine.currentRenderPassId = (_c = currentActiveCamera === null || currentActiveCamera === void 0 ? void 0 : currentActiveCamera.renderPassId) !== null && _c !== void 0 ? _c : 0; - // Restore back buffer - this.activeCamera = currentActiveCamera; - if (this._activeCamera && this._activeCamera.cameraRigMode !== 22 && !this.prePass) { - this._bindFrameBuffer(this._activeCamera, false); - } - this.onAfterRenderTargetsRenderObservable.notifyObservers(this); - for (const step of this._beforeClearStage) { - step.action(); - } - // Clear - this._clearFrameBuffer(this.activeCamera); - // Collects render targets from external components. - for (const step of this._gatherRenderTargetsStage) { - step.action(this._renderTargets); - } - // Multi-cameras? - if (this.activeCameras && this.activeCameras.length > 0) { - for (let cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) { - this._processSubCameras(this.activeCameras[cameraIndex], cameraIndex > 0); - } - } - else { - if (!this.activeCamera) { - throw new Error("No camera defined"); - } - this._processSubCameras(this.activeCamera, !!this.activeCamera.outputRenderTarget); - } - // Intersection checks - this._checkIntersections(); - // Executes the after render stage actions. - for (const step of this._afterRenderStage) { - step.action(); - } - // After render - if (this.afterRender) { - this.afterRender(); - } - this.onAfterRenderObservable.notifyObservers(this); - // Cleaning - if (this._toBeDisposed.length) { - for (let index = 0; index < this._toBeDisposed.length; index++) { - const data = this._toBeDisposed[index]; - if (data) { - data.dispose(); - } - } - this._toBeDisposed.length = 0; - } - if (this.dumpNextRenderTargets) { - this.dumpNextRenderTargets = false; - } - this._activeBones.addCount(0, true); - this._activeIndices.addCount(0, true); - this._activeParticles.addCount(0, true); - this._engine.restoreDefaultFramebuffer(); - } - /** - * Freeze all materials - * A frozen material will not be updatable but should be faster to render - * Note: multimaterials will not be frozen, but their submaterials will - */ - freezeMaterials() { - for (let i = 0; i < this.materials.length; i++) { - this.materials[i].freeze(); - } - } - /** - * Unfreeze all materials - * A frozen material will not be updatable but should be faster to render - */ - unfreezeMaterials() { - for (let i = 0; i < this.materials.length; i++) { - this.materials[i].unfreeze(); - } - } - /** - * Releases all held resources - */ - dispose() { - if (this.isDisposed) { - return; - } - this.beforeRender = null; - this.afterRender = null; - this.metadata = null; - this.skeletons.length = 0; - this.morphTargetManagers.length = 0; - this._transientComponents.length = 0; - this._isReadyForMeshStage.clear(); - this._beforeEvaluateActiveMeshStage.clear(); - this._evaluateSubMeshStage.clear(); - this._preActiveMeshStage.clear(); - this._cameraDrawRenderTargetStage.clear(); - this._beforeCameraDrawStage.clear(); - this._beforeRenderTargetDrawStage.clear(); - this._beforeRenderingGroupDrawStage.clear(); - this._beforeRenderingMeshStage.clear(); - this._afterRenderingMeshStage.clear(); - this._afterRenderingGroupDrawStage.clear(); - this._afterCameraDrawStage.clear(); - this._afterRenderTargetDrawStage.clear(); - this._afterRenderStage.clear(); - this._beforeCameraUpdateStage.clear(); - this._beforeClearStage.clear(); - this._gatherRenderTargetsStage.clear(); - this._gatherActiveCameraRenderTargetsStage.clear(); - this._pointerMoveStage.clear(); - this._pointerDownStage.clear(); - this._pointerUpStage.clear(); - this.importedMeshesFiles = new Array(); - if (this.stopAllAnimations) { - // Ensures that no animatable notifies a callback that could start a new animation group, constantly adding new animatables to the active list... - this._activeAnimatables.forEach((animatable) => { - animatable.onAnimationEndObservable.clear(); - animatable.onAnimationEnd = null; - }); - this.stopAllAnimations(); - } - this.resetCachedMaterial(); - // Smart arrays - if (this.activeCamera) { - this.activeCamera._activeMeshes.dispose(); - this.activeCamera = null; - } - this.activeCameras = null; - this._activeMeshes.dispose(); - this._renderingManager.dispose(); - this._processedMaterials.dispose(); - this._activeParticleSystems.dispose(); - this._activeSkeletons.dispose(); - this._softwareSkinnedMeshes.dispose(); - this._renderTargets.dispose(); - this._materialsRenderTargets.dispose(); - this._registeredForLateAnimationBindings.dispose(); - this._meshesForIntersections.dispose(); - this._toBeDisposed.length = 0; - // Abort active requests - const activeRequests = this._activeRequests.slice(); - for (const request of activeRequests) { - request.abort(); - } - this._activeRequests.length = 0; - // Events - try { - this.onDisposeObservable.notifyObservers(this); - } - catch (e) { - console.error("An error occurred while calling onDisposeObservable!", e); - } - this.detachControl(); - // Detach cameras - const canvas = this._engine.getInputElement(); - if (canvas) { - for (let index = 0; index < this.cameras.length; index++) { - this.cameras[index].detachControl(); - } - } - // Release animation groups - this._disposeList(this.animationGroups); - // Release lights - this._disposeList(this.lights); - // Release meshes - this._disposeList(this.meshes, (item) => item.dispose(true)); - this._disposeList(this.transformNodes, (item) => item.dispose(true)); - // Release cameras - const cameras = this.cameras; - this._disposeList(cameras); - // Release materials - if (this._defaultMaterial) { - this._defaultMaterial.dispose(); - } - this._disposeList(this.multiMaterials); - this._disposeList(this.materials); - // Release particles - this._disposeList(this.particleSystems); - // Release postProcesses - this._disposeList(this.postProcesses); - // Release textures - this._disposeList(this.textures); - // Release morph targets - this._disposeList(this.morphTargetManagers); - // Release UBO - this._sceneUbo.dispose(); - if (this._multiviewSceneUbo) { - this._multiviewSceneUbo.dispose(); - } - // Post-processes - this.postProcessManager.dispose(); - // Components - this._disposeList(this._components); - // Remove from engine - let index = this._engine.scenes.indexOf(this); - if (index > -1) { - this._engine.scenes.splice(index, 1); - } - if (engineStore_EngineStore._LastCreatedScene === this) { - if (this._engine.scenes.length > 0) { - engineStore_EngineStore._LastCreatedScene = this._engine.scenes[this._engine.scenes.length - 1]; - } - else { - engineStore_EngineStore._LastCreatedScene = null; - } - } - index = this._engine._virtualScenes.indexOf(this); - if (index > -1) { - this._engine._virtualScenes.splice(index, 1); - } - this._engine.wipeCaches(true); - this.onDisposeObservable.clear(); - this.onBeforeRenderObservable.clear(); - this.onAfterRenderObservable.clear(); - this.onBeforeRenderTargetsRenderObservable.clear(); - this.onAfterRenderTargetsRenderObservable.clear(); - this.onAfterStepObservable.clear(); - this.onBeforeStepObservable.clear(); - this.onBeforeActiveMeshesEvaluationObservable.clear(); - this.onAfterActiveMeshesEvaluationObservable.clear(); - this.onBeforeParticlesRenderingObservable.clear(); - this.onAfterParticlesRenderingObservable.clear(); - this.onBeforeDrawPhaseObservable.clear(); - this.onAfterDrawPhaseObservable.clear(); - this.onBeforeAnimationsObservable.clear(); - this.onAfterAnimationsObservable.clear(); - this.onDataLoadedObservable.clear(); - this.onBeforeRenderingGroupObservable.clear(); - this.onAfterRenderingGroupObservable.clear(); - this.onMeshImportedObservable.clear(); - this.onBeforeCameraRenderObservable.clear(); - this.onAfterCameraRenderObservable.clear(); - this.onAfterRenderCameraObservable.clear(); - this.onReadyObservable.clear(); - this.onNewCameraAddedObservable.clear(); - this.onCameraRemovedObservable.clear(); - this.onNewLightAddedObservable.clear(); - this.onLightRemovedObservable.clear(); - this.onNewGeometryAddedObservable.clear(); - this.onGeometryRemovedObservable.clear(); - this.onNewTransformNodeAddedObservable.clear(); - this.onTransformNodeRemovedObservable.clear(); - this.onNewMeshAddedObservable.clear(); - this.onMeshRemovedObservable.clear(); - this.onNewSkeletonAddedObservable.clear(); - this.onSkeletonRemovedObservable.clear(); - this.onNewMaterialAddedObservable.clear(); - this.onNewMultiMaterialAddedObservable.clear(); - this.onMaterialRemovedObservable.clear(); - this.onMultiMaterialRemovedObservable.clear(); - this.onNewTextureAddedObservable.clear(); - this.onTextureRemovedObservable.clear(); - this.onPrePointerObservable.clear(); - this.onPointerObservable.clear(); - this.onPreKeyboardObservable.clear(); - this.onKeyboardObservable.clear(); - this.onActiveCameraChanged.clear(); - this.onScenePerformancePriorityChangedObservable.clear(); - this._isDisposed = true; - } - _disposeList(items, callback) { - const itemsCopy = items.slice(0); - callback = callback !== null && callback !== void 0 ? callback : ((item) => item.dispose()); - for (const item of itemsCopy) { - callback(item); - } - items.length = 0; - } - /** - * Gets if the scene is already disposed - */ - get isDisposed() { - return this._isDisposed; - } - /** - * Call this function to reduce memory footprint of the scene. - * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly) - */ - clearCachedVertexData() { - for (let meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) { - const mesh = this.meshes[meshIndex]; - const geometry = mesh.geometry; - if (geometry) { - geometry.clearCachedData(); - } - } - } - /** - * This function will remove the local cached buffer data from texture. - * It will save memory but will prevent the texture from being rebuilt - */ - cleanCachedTextureBuffer() { - for (const baseTexture of this.textures) { - const buffer = baseTexture._buffer; - if (buffer) { - baseTexture._buffer = null; - } - } - } - /** - * Get the world extend vectors with an optional filter - * - * @param filterPredicate the predicate - which meshes should be included when calculating the world size - * @returns {{ min: Vector3; max: Vector3 }} min and max vectors - */ - getWorldExtends(filterPredicate) { - const min = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - const max = new math_vector_Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); - filterPredicate = filterPredicate || (() => true); - this.meshes.filter(filterPredicate).forEach((mesh) => { - mesh.computeWorldMatrix(true); - if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) { - return; - } - const boundingInfo = mesh.getBoundingInfo(); - const minBox = boundingInfo.boundingBox.minimumWorld; - const maxBox = boundingInfo.boundingBox.maximumWorld; - math_vector_Vector3.CheckExtends(minBox, min, max); - math_vector_Vector3.CheckExtends(maxBox, min, max); - }); - return { - min: min, - max: max, - }; - } - // Picking - /** - * Creates a ray that can be used to pick in the scene - * @param x defines the x coordinate of the origin (on-screen) - * @param y defines the y coordinate of the origin (on-screen) - * @param world defines the world matrix to use if you want to pick in object space (instead of world space) - * @param camera defines the camera to use for the picking - * @param cameraViewSpace defines if picking will be done in view space (false by default) - * @returns a Ray - */ - createPickingRay(x, y, world, camera, cameraViewSpace = false) { - throw _WarnImport("Ray"); - } - /** - * Creates a ray that can be used to pick in the scene - * @param x defines the x coordinate of the origin (on-screen) - * @param y defines the y coordinate of the origin (on-screen) - * @param world defines the world matrix to use if you want to pick in object space (instead of world space) - * @param result defines the ray where to store the picking ray - * @param camera defines the camera to use for the picking - * @param cameraViewSpace defines if picking will be done in view space (false by default) - * @param enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default) - * @returns the current scene - */ - createPickingRayToRef(x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) { - throw _WarnImport("Ray"); - } - /** - * Creates a ray that can be used to pick in the scene - * @param x defines the x coordinate of the origin (on-screen) - * @param y defines the y coordinate of the origin (on-screen) - * @param camera defines the camera to use for the picking - * @returns a Ray - */ - createPickingRayInCameraSpace(x, y, camera) { - throw _WarnImport("Ray"); - } - /** - * Creates a ray that can be used to pick in the scene - * @param x defines the x coordinate of the origin (on-screen) - * @param y defines the y coordinate of the origin (on-screen) - * @param result defines the ray where to store the picking ray - * @param camera defines the camera to use for the picking - * @returns the current scene - */ - createPickingRayInCameraSpaceToRef(x, y, result, camera) { - throw _WarnImport("Ray"); - } - /** @internal */ - get _pickingAvailable() { - return false; - } - /** Launch a ray to try to pick a mesh in the scene - * @param x position on screen - * @param y position on screen - * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true - * @param fastCheck defines if the first intersection will be used (and not the closest) - * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used - * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected - * @returns a PickingInfo - */ - pick(x, y, predicate, fastCheck, camera, trianglePredicate) { - // Dummy info if picking as not been imported - return new PickingInfo(); - } - /** Launch a ray to try to pick a mesh in the scene using only bounding information of the main mesh (not using submeshes) - * @param x position on screen - * @param y position on screen - * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true - * @param fastCheck defines if the first intersection will be used (and not the closest) - * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used - * @returns a PickingInfo (Please note that some info will not be set like distance, bv, bu and everything that cannot be capture by only using bounding infos) - */ - pickWithBoundingInfo(x, y, predicate, fastCheck, camera) { - // Dummy info if picking as not been imported - return new PickingInfo(); - } - /** - * Use the given ray to pick a mesh in the scene. A mesh triangle can be picked both from its front and back sides, - * irrespective of orientation. - * @param ray The ray to use to pick meshes - * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true - * @param fastCheck defines if the first intersection will be used (and not the closest) - * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected - * @returns a PickingInfo - */ - pickWithRay(ray, predicate, fastCheck, trianglePredicate) { - throw _WarnImport("Ray"); - } - /** - * Launch a ray to try to pick a mesh in the scene. A mesh triangle can be picked both from its front and back sides, - * irrespective of orientation. - * @param x X position on screen - * @param y Y position on screen - * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true - * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used - * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected - * @returns an array of PickingInfo - */ - multiPick(x, y, predicate, camera, trianglePredicate) { - throw _WarnImport("Ray"); - } - /** - * Launch a ray to try to pick a mesh in the scene - * @param ray Ray to use - * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true - * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected - * @returns an array of PickingInfo - */ - multiPickWithRay(ray, predicate, trianglePredicate) { - throw _WarnImport("Ray"); - } - /** - * Force the value of meshUnderPointer - * @param mesh defines the mesh to use - * @param pointerId optional pointer id when using more than one pointer - * @param pickResult optional pickingInfo data used to find mesh - */ - setPointerOverMesh(mesh, pointerId, pickResult) { - this._inputManager.setPointerOverMesh(mesh, pointerId, pickResult); - } - /** - * Gets the mesh under the pointer - * @returns a Mesh or null if no mesh is under the pointer - */ - getPointerOverMesh() { - return this._inputManager.getPointerOverMesh(); - } - // Misc. - /** @internal */ - _rebuildGeometries() { - for (const geometry of this.geometries) { - geometry._rebuild(); - } - for (const mesh of this.meshes) { - mesh._rebuild(); - } - if (this.postProcessManager) { - this.postProcessManager._rebuild(); - } - for (const component of this._components) { - component.rebuild(); - } - for (const system of this.particleSystems) { - system.rebuild(); - } - if (this.spriteManagers) { - for (const spriteMgr of this.spriteManagers) { - spriteMgr.rebuild(); - } - } - } - /** @internal */ - _rebuildTextures() { - for (const texture of this.textures) { - texture._rebuild(); - } - this.markAllMaterialsAsDirty(1); - } - // Tags - _getByTags(list, tagsQuery, forEach) { - if (tagsQuery === undefined) { - // returns the complete list (could be done with Tags.MatchesQuery but no need to have a for-loop here) - return list; - } - const listByTags = []; - forEach = - forEach || - ((item) => { - return; - }); - for (const i in list) { - const item = list[i]; - if (Tags && Tags.MatchesQuery(item, tagsQuery)) { - listByTags.push(item); - forEach(item); - } - } - return listByTags; - } - /** - * Get a list of meshes by tags - * @param tagsQuery defines the tags query to use - * @param forEach defines a predicate used to filter results - * @returns an array of Mesh - */ - getMeshesByTags(tagsQuery, forEach) { - return this._getByTags(this.meshes, tagsQuery, forEach); - } - /** - * Get a list of cameras by tags - * @param tagsQuery defines the tags query to use - * @param forEach defines a predicate used to filter results - * @returns an array of Camera - */ - getCamerasByTags(tagsQuery, forEach) { - return this._getByTags(this.cameras, tagsQuery, forEach); - } - /** - * Get a list of lights by tags - * @param tagsQuery defines the tags query to use - * @param forEach defines a predicate used to filter results - * @returns an array of Light - */ - getLightsByTags(tagsQuery, forEach) { - return this._getByTags(this.lights, tagsQuery, forEach); - } - /** - * Get a list of materials by tags - * @param tagsQuery defines the tags query to use - * @param forEach defines a predicate used to filter results - * @returns an array of Material - */ - getMaterialByTags(tagsQuery, forEach) { - return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach)); - } - /** - * Get a list of transform nodes by tags - * @param tagsQuery defines the tags query to use - * @param forEach defines a predicate used to filter results - * @returns an array of TransformNode - */ - getTransformNodesByTags(tagsQuery, forEach) { - return this._getByTags(this.transformNodes, tagsQuery, forEach); - } - /** - * Overrides the default sort function applied in the rendering group to prepare the meshes. - * This allowed control for front to back rendering or reversly depending of the special needs. - * - * @param renderingGroupId The rendering group id corresponding to its index - * @param opaqueSortCompareFn The opaque queue comparison function use to sort. - * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. - * @param transparentSortCompareFn The transparent queue comparison function use to sort. - */ - setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { - this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn); - } - /** - * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. - * - * @param renderingGroupId The rendering group id corresponding to its index - * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. - * @param depth Automatically clears depth between groups if true and autoClear is true. - * @param stencil Automatically clears stencil between groups if true and autoClear is true. - */ - setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) { - this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil); - } - /** - * Gets the current auto clear configuration for one rendering group of the rendering - * manager. - * @param index the rendering group index to get the information for - * @returns The auto clear setup for the requested rendering group - */ - getAutoClearDepthStencilSetup(index) { - return this._renderingManager.getAutoClearDepthStencilSetup(index); - } - /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */ - get blockMaterialDirtyMechanism() { - return this._blockMaterialDirtyMechanism; - } - set blockMaterialDirtyMechanism(value) { - if (this._blockMaterialDirtyMechanism === value) { - return; - } - this._blockMaterialDirtyMechanism = value; - if (!value) { - // Do a complete update - this.markAllMaterialsAsDirty(63); - } - } - /** - * Will flag all materials as dirty to trigger new shader compilation - * @param flag defines the flag used to specify which material part must be marked as dirty - * @param predicate If not null, it will be used to specify if a material has to be marked as dirty - */ - markAllMaterialsAsDirty(flag, predicate) { - if (this._blockMaterialDirtyMechanism) { - return; - } - for (const material of this.materials) { - if (predicate && !predicate(material)) { - continue; - } - material.markAsDirty(flag); - } - } - /** - * @internal - */ - _loadFile(fileOrUrl, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError, onOpened) { - const request = LoadFile(fileOrUrl, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError, onOpened); - this._activeRequests.push(request); - request.onCompleteObservable.add((request) => { - this._activeRequests.splice(this._activeRequests.indexOf(request), 1); - }); - return request; - } - /** - * @internal - */ - _loadFileAsync(fileOrUrl, onProgress, useOfflineSupport, useArrayBuffer, onOpened) { - return new Promise((resolve, reject) => { - this._loadFile(fileOrUrl, (data) => { - resolve(data); - }, onProgress, useOfflineSupport, useArrayBuffer, (request, exception) => { - reject(exception); - }, onOpened); - }); - } - /** - * @internal - */ - _requestFile(url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError, onOpened) { - const request = RequestFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : undefined, useArrayBuffer, onError, onOpened); - this._activeRequests.push(request); - request.onCompleteObservable.add((request) => { - this._activeRequests.splice(this._activeRequests.indexOf(request), 1); - }); - return request; - } - /** - * @internal - */ - _requestFileAsync(url, onProgress, useOfflineSupport, useArrayBuffer, onOpened) { - return new Promise((resolve, reject) => { - this._requestFile(url, (data) => { - resolve(data); - }, onProgress, useOfflineSupport, useArrayBuffer, (error) => { - reject(error); - }, onOpened); - }); - } - /** - * @internal - */ - _readFile(file, onSuccess, onProgress, useArrayBuffer, onError) { - const request = ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError); - this._activeRequests.push(request); - request.onCompleteObservable.add((request) => { - this._activeRequests.splice(this._activeRequests.indexOf(request), 1); - }); - return request; - } - /** - * @internal - */ - _readFileAsync(file, onProgress, useArrayBuffer) { - return new Promise((resolve, reject) => { - this._readFile(file, (data) => { - resolve(data); - }, onProgress, useArrayBuffer, (error) => { - reject(error); - }); - }); - } - /** - * This method gets the performance collector belonging to the scene, which is generally shared with the inspector. - * @returns the perf collector belonging to the scene. - */ - getPerfCollector() { - throw _WarnImport("performanceViewerSceneExtension"); - } - // deprecated - /** - * Sets the active camera of the scene using its Id - * @param id defines the camera's Id - * @returns the new active camera or null if none found. - * @deprecated Please use setActiveCameraById instead - */ - setActiveCameraByID(id) { - return this.setActiveCameraById(id); - } - /** - * Get a material using its id - * @param id defines the material's Id - * @returns the material or null if none found. - * @deprecated Please use getMaterialById instead - */ - getMaterialByID(id) { - return this.getMaterialById(id); - } - /** - * Gets a the last added material using a given id - * @param id defines the material's Id - * @returns the last material with the given id or null if none found. - * @deprecated Please use getLastMaterialById instead - */ - getLastMaterialByID(id) { - return this.getLastMaterialById(id); - } - /** - * Get a texture using its unique id - * @param uniqueId defines the texture's unique id - * @returns the texture or null if none found. - * @deprecated Please use getTextureByUniqueId instead - */ - getTextureByUniqueID(uniqueId) { - return this.getTextureByUniqueId(uniqueId); - } - /** - * Gets a camera using its Id - * @param id defines the Id to look for - * @returns the camera or null if not found - * @deprecated Please use getCameraById instead - */ - getCameraByID(id) { - return this.getCameraById(id); - } - /** - * Gets a camera using its unique Id - * @param uniqueId defines the unique Id to look for - * @returns the camera or null if not found - * @deprecated Please use getCameraByUniqueId instead - */ - getCameraByUniqueID(uniqueId) { - return this.getCameraByUniqueId(uniqueId); - } - /** - * Gets a bone using its Id - * @param id defines the bone's Id - * @returns the bone or null if not found - * @deprecated Please use getBoneById instead - */ - getBoneByID(id) { - return this.getBoneById(id); - } - /** - * Gets a light node using its Id - * @param id defines the light's Id - * @returns the light or null if none found. - * @deprecated Please use getLightById instead - */ - getLightByID(id) { - return this.getLightById(id); - } - /** - * Gets a light node using its scene-generated unique Id - * @param uniqueId defines the light's unique Id - * @returns the light or null if none found. - * @deprecated Please use getLightByUniqueId instead - */ - getLightByUniqueID(uniqueId) { - return this.getLightByUniqueId(uniqueId); - } - /** - * Gets a particle system by Id - * @param id defines the particle system Id - * @returns the corresponding system or null if none found - * @deprecated Please use getParticleSystemById instead - */ - getParticleSystemByID(id) { - return this.getParticleSystemById(id); - } - /** - * Gets a geometry using its Id - * @param id defines the geometry's Id - * @returns the geometry or null if none found. - * @deprecated Please use getGeometryById instead - */ - getGeometryByID(id) { - return this.getGeometryById(id); - } - /** - * Gets the first added mesh found of a given Id - * @param id defines the Id to search for - * @returns the mesh found or null if not found at all - * @deprecated Please use getMeshById instead - */ - getMeshByID(id) { - return this.getMeshById(id); - } - /** - * Gets a mesh with its auto-generated unique Id - * @param uniqueId defines the unique Id to search for - * @returns the found mesh or null if not found at all. - * @deprecated Please use getMeshByUniqueId instead - */ - getMeshByUniqueID(uniqueId) { - return this.getMeshByUniqueId(uniqueId); - } - /** - * Gets a the last added mesh using a given Id - * @param id defines the Id to search for - * @returns the found mesh or null if not found at all. - * @deprecated Please use getLastMeshById instead - */ - getLastMeshByID(id) { - return this.getLastMeshById(id); - } - /** - * Gets a list of meshes using their Id - * @param id defines the Id to search for - * @returns a list of meshes - * @deprecated Please use getMeshesById instead - */ - getMeshesByID(id) { - return this.getMeshesById(id); - } - /** - * Gets the first added transform node found of a given Id - * @param id defines the Id to search for - * @returns the found transform node or null if not found at all. - * @deprecated Please use getTransformNodeById instead - */ - getTransformNodeByID(id) { - return this.getTransformNodeById(id); - } - /** - * Gets a transform node with its auto-generated unique Id - * @param uniqueId defines the unique Id to search for - * @returns the found transform node or null if not found at all. - * @deprecated Please use getTransformNodeByUniqueId instead - */ - getTransformNodeByUniqueID(uniqueId) { - return this.getTransformNodeByUniqueId(uniqueId); - } - /** - * Gets a list of transform nodes using their Id - * @param id defines the Id to search for - * @returns a list of transform nodes - * @deprecated Please use getTransformNodesById instead - */ - getTransformNodesByID(id) { - return this.getTransformNodesById(id); - } - /** - * Gets a node (Mesh, Camera, Light) using a given Id - * @param id defines the Id to search for - * @returns the found node or null if not found at all - * @deprecated Please use getNodeById instead - */ - getNodeByID(id) { - return this.getNodeById(id); - } - /** - * Gets a the last added node (Mesh, Camera, Light) using a given Id - * @param id defines the Id to search for - * @returns the found node or null if not found at all - * @deprecated Please use getLastEntryById instead - */ - getLastEntryByID(id) { - return this.getLastEntryById(id); - } - /** - * Gets a skeleton using a given Id (if many are found, this function will pick the last one) - * @param id defines the Id to search for - * @returns the found skeleton or null if not found at all. - * @deprecated Please use getLastSkeletonById instead - */ - getLastSkeletonByID(id) { - return this.getLastSkeletonById(id); - } -} -/** The fog is deactivated */ -scene_Scene.FOGMODE_NONE = 0; -/** The fog density is following an exponential function */ -scene_Scene.FOGMODE_EXP = 1; -/** The fog density is following an exponential function faster than FOGMODE_EXP */ -scene_Scene.FOGMODE_EXP2 = 2; -/** The fog density is following a linear function. */ -scene_Scene.FOGMODE_LINEAR = 3; -/** - * Gets or sets the minimum deltatime when deterministic lock step is enabled - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - */ -scene_Scene.MinDeltaTime = 1.0; -/** - * Gets or sets the maximum deltatime when deterministic lock step is enabled - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - */ -scene_Scene.MaxDeltaTime = 1000.0; -//# sourceMappingURL=scene.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.axis.js - -/** Defines supported spaces */ -var math_axis_Space; -(function (Space) { - /** Local (object) space */ - Space[Space["LOCAL"] = 0] = "LOCAL"; - /** World space */ - Space[Space["WORLD"] = 1] = "WORLD"; - /** Bone space */ - Space[Space["BONE"] = 2] = "BONE"; -})(math_axis_Space || (math_axis_Space = {})); -/** Defines the 3 main axes */ -class math_axis_Axis { -} -/** X axis */ -math_axis_Axis.X = new math_vector_Vector3(1.0, 0.0, 0.0); -/** Y axis */ -math_axis_Axis.Y = new math_vector_Vector3(0.0, 1.0, 0.0); -/** Z axis */ -math_axis_Axis.Z = new math_vector_Vector3(0.0, 0.0, 1.0); -/** - * Defines cartesian components. - */ -var Coordinate; -(function (Coordinate) { - /** X axis */ - Coordinate[Coordinate["X"] = 0] = "X"; - /** Y axis */ - Coordinate[Coordinate["Y"] = 1] = "Y"; - /** Z axis */ - Coordinate[Coordinate["Z"] = 2] = "Z"; -})(Coordinate || (Coordinate = {})); -//# sourceMappingURL=math.axis.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Bones/bone.js - - - - -/** - * Class used to store bone information - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons - */ -class Bone extends node_Node { - /** @internal */ - get _matrix() { - this._compose(); - return this._localMatrix; - } - /** @internal */ - set _matrix(value) { - // skip if the matrices are the same - if (value.updateFlag === this._localMatrix.updateFlag && !this._needToCompose) { - return; - } - this._needToCompose = false; // in case there was a pending compose - this._localMatrix.copyFrom(value); - this._markAsDirtyAndDecompose(); - } - /** - * Create a new bone - * @param name defines the bone name - * @param skeleton defines the parent skeleton - * @param parentBone defines the parent (can be null if the bone is the root) - * @param localMatrix defines the local matrix (default: identity) - * @param restMatrix defines the rest matrix (default: localMatrix) - * @param bindMatrix defines the bind matrix (default: localMatrix) - * @param index defines index of the bone in the hierarchy (default: null) - */ - constructor( - /** - * defines the bone name - */ - name, skeleton, parentBone = null, localMatrix = null, restMatrix = null, bindMatrix = null, index = null) { - var _a; - super(name, skeleton.getScene()); - this.name = name; - /** - * Gets the list of child bones - */ - this.children = new Array(); - /** Gets the animations associated with this bone */ - this.animations = new Array(); - /** - * @internal Internal only - * Set this value to map this bone to a different index in the transform matrices - * Set this value to -1 to exclude the bone from the transform matrices - */ - this._index = null; - this._scalingDeterminant = 1; - this._needToDecompose = true; - this._needToCompose = false; - /** @internal */ - this._linkedTransformNode = null; - /** @internal */ - this._waitingTransformNodeId = null; - this._skeleton = skeleton; - this._localMatrix = (_a = localMatrix === null || localMatrix === void 0 ? void 0 : localMatrix.clone()) !== null && _a !== void 0 ? _a : math_vector_Matrix.Identity(); - this._restMatrix = restMatrix !== null && restMatrix !== void 0 ? restMatrix : this._localMatrix.clone(); - this._bindMatrix = bindMatrix !== null && bindMatrix !== void 0 ? bindMatrix : this._localMatrix.clone(); - this._index = index; - this._absoluteMatrix = new math_vector_Matrix(); - this._absoluteBindMatrix = new math_vector_Matrix(); - this._absoluteInverseBindMatrix = new math_vector_Matrix(); - this._finalMatrix = new math_vector_Matrix(); - skeleton.bones.push(this); - this.setParent(parentBone, false); - this._updateAbsoluteBindMatrices(); - } - /** - * Gets the current object class name. - * @returns the class name - */ - getClassName() { - return "Bone"; - } - // Members - /** - * Gets the parent skeleton - * @returns a skeleton - */ - getSkeleton() { - return this._skeleton; - } - get parent() { - return this._parentNode; - } - /** - * Gets parent bone - * @returns a bone or null if the bone is the root of the bone hierarchy - */ - getParent() { - return this.parent; - } - /** - * Returns an array containing the children of the bone - * @returns an array containing the children of the bone (can be empty if the bone has no children) - */ - getChildren() { - return this.children; - } - /** - * Gets the node index in matrix array generated for rendering - * @returns the node index - */ - getIndex() { - return this._index === null ? this.getSkeleton().bones.indexOf(this) : this._index; - } - set parent(newParent) { - this.setParent(newParent); - } - /** - * Sets the parent bone - * @param parent defines the parent (can be null if the bone is the root) - * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be updated - */ - setParent(parent, updateAbsoluteBindMatrices = true) { - if (this.parent === parent) { - return; - } - if (this.parent) { - const index = this.parent.children.indexOf(this); - if (index !== -1) { - this.parent.children.splice(index, 1); - } - } - this._parentNode = parent; - if (this.parent) { - this.parent.children.push(this); - } - if (updateAbsoluteBindMatrices) { - this._updateAbsoluteBindMatrices(); - } - this.markAsDirty(); - } - /** - * Gets the local matrix - * @returns the local matrix - */ - getLocalMatrix() { - this._compose(); - return this._localMatrix; - } - /** - * Gets the bind matrix - * @returns the bind matrix - */ - getBindMatrix() { - return this._bindMatrix; - } - /** - * Gets the bind matrix. - * @returns the bind matrix - * @deprecated Please use getBindMatrix instead - */ - getBaseMatrix() { - return this.getBindMatrix(); - } - /** - * Gets the rest matrix - * @returns the rest matrix - */ - getRestMatrix() { - return this._restMatrix; - } - /** - * Gets the rest matrix - * @returns the rest matrix - * @deprecated Please use getRestMatrix instead - */ - getRestPose() { - return this.getRestMatrix(); - } - /** - * Sets the rest matrix - * @param matrix the local-space rest matrix to set for this bone - */ - setRestMatrix(matrix) { - this._restMatrix.copyFrom(matrix); - } - /** - * Sets the rest matrix - * @param matrix the local-space rest to set for this bone - * @deprecated Please use setRestMatrix instead - */ - setRestPose(matrix) { - this.setRestMatrix(matrix); - } - /** - * Gets the bind matrix - * @returns the bind matrix - * @deprecated Please use getBindMatrix instead - */ - getBindPose() { - return this.getBindMatrix(); - } - /** - * Sets the bind matrix - * This will trigger a recomputation of the absolute bind and absolute inverse bind matrices for this bone and its children - * Note that the local matrix will also be set with the matrix passed in parameter! - * @param matrix the local-space bind matrix to set for this bone - */ - setBindMatrix(matrix) { - this.updateMatrix(matrix); - } - /** - * Sets the bind matrix - * @param matrix the local-space bind to set for this bone - * @deprecated Please use setBindMatrix instead - */ - setBindPose(matrix) { - this.setBindMatrix(matrix); - } - /** - * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders) - */ - getFinalMatrix() { - return this._finalMatrix; - } - /** - * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders) - * @deprecated Please use getFinalMatrix instead - */ - getWorldMatrix() { - return this.getFinalMatrix(); - } - /** - * Sets the local matrix to the rest matrix - */ - returnToRest() { - var _a; - if (this._linkedTransformNode) { - const localScaling = math_vector_TmpVectors.Vector3[0]; - const localRotation = math_vector_TmpVectors.Quaternion[0]; - const localPosition = math_vector_TmpVectors.Vector3[1]; - this.getRestMatrix().decompose(localScaling, localRotation, localPosition); - this._linkedTransformNode.position.copyFrom(localPosition); - this._linkedTransformNode.rotationQuaternion = (_a = this._linkedTransformNode.rotationQuaternion) !== null && _a !== void 0 ? _a : math_vector_Quaternion.Identity(); - this._linkedTransformNode.rotationQuaternion.copyFrom(localRotation); - this._linkedTransformNode.scaling.copyFrom(localScaling); - } - else { - this._matrix = this._restMatrix; - } - } - /** - * Gets the inverse of the bind matrix, in world space (relative to the skeleton root) - * @returns the inverse bind matrix, in world space - */ - getAbsoluteInverseBindMatrix() { - return this._absoluteInverseBindMatrix; - } - /** - * Gets the inverse of the bind matrix, in world space (relative to the skeleton root) - * @returns the inverse bind matrix, in world space - * @deprecated Please use getAbsoluteInverseBindMatrix instead - */ - getInvertedAbsoluteTransform() { - return this.getAbsoluteInverseBindMatrix(); - } - /** - * Gets the bone matrix, in world space (relative to the skeleton root) - * @returns the bone matrix, in world space - */ - getAbsoluteMatrix() { - return this._absoluteMatrix; - } - /** - * Gets the bone matrix, in world space (relative to the skeleton root) - * @returns the bone matrix, in world space - * @deprecated Please use getAbsoluteMatrix instead - */ - getAbsoluteTransform() { - return this._absoluteMatrix; - } - /** - * Links with the given transform node. - * The local matrix of this bone is overwritten by the transform of the node every frame. - * @param transformNode defines the transform node to link to - */ - linkTransformNode(transformNode) { - if (this._linkedTransformNode) { - this._skeleton._numBonesWithLinkedTransformNode--; - } - this._linkedTransformNode = transformNode; - if (this._linkedTransformNode) { - this._skeleton._numBonesWithLinkedTransformNode++; - } - } - // Properties (matches TransformNode properties) - /** - * Gets the node used to drive the bone's transformation - * @returns a transform node or null - */ - getTransformNode() { - return this._linkedTransformNode; - } - /** Gets or sets current position (in local space) */ - get position() { - this._decompose(); - return this._localPosition; - } - set position(newPosition) { - this._decompose(); - this._localPosition.copyFrom(newPosition); - this._markAsDirtyAndCompose(); - } - /** Gets or sets current rotation (in local space) */ - get rotation() { - return this.getRotation(); - } - set rotation(newRotation) { - this.setRotation(newRotation); - } - /** Gets or sets current rotation quaternion (in local space) */ - get rotationQuaternion() { - this._decompose(); - return this._localRotation; - } - set rotationQuaternion(newRotation) { - this.setRotationQuaternion(newRotation); - } - /** Gets or sets current scaling (in local space) */ - get scaling() { - return this.getScale(); - } - set scaling(newScaling) { - this.setScale(newScaling); - } - /** - * Gets the animation properties override - */ - get animationPropertiesOverride() { - return this._skeleton.animationPropertiesOverride; - } - // Methods - _decompose() { - if (!this._needToDecompose) { - return; - } - this._needToDecompose = false; - if (!this._localScaling) { - this._localScaling = math_vector_Vector3.Zero(); - this._localRotation = math_vector_Quaternion.Zero(); - this._localPosition = math_vector_Vector3.Zero(); - } - this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition); - } - _compose() { - if (!this._needToCompose) { - return; - } - if (!this._localScaling) { - this._needToCompose = false; - return; - } - this._needToCompose = false; - math_vector_Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix); - } - /** - * Update the bind (and optionally the local) matrix - * @param bindMatrix defines the new matrix to set to the bind/local matrix, in local space - * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be recomputed (default: true) - * @param updateLocalMatrix defines if the local matrix should also be updated with the matrix passed in parameter (default: true) - */ - updateMatrix(bindMatrix, updateAbsoluteBindMatrices = true, updateLocalMatrix = true) { - this._bindMatrix.copyFrom(bindMatrix); - if (updateAbsoluteBindMatrices) { - this._updateAbsoluteBindMatrices(); - } - if (updateLocalMatrix) { - this._matrix = bindMatrix; - } - else { - this.markAsDirty(); - } - } - /** - * @internal - */ - _updateAbsoluteBindMatrices(bindMatrix, updateChildren = true) { - if (!bindMatrix) { - bindMatrix = this._bindMatrix; - } - if (this.parent) { - bindMatrix.multiplyToRef(this.parent._absoluteBindMatrix, this._absoluteBindMatrix); - } - else { - this._absoluteBindMatrix.copyFrom(bindMatrix); - } - this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix); - if (updateChildren) { - for (let index = 0; index < this.children.length; index++) { - this.children[index]._updateAbsoluteBindMatrices(); - } - } - this._scalingDeterminant = this._absoluteBindMatrix.determinant() < 0 ? -1 : 1; - } - /** - * Flag the bone as dirty (Forcing it to update everything) - * @returns this bone - */ - markAsDirty() { - this._currentRenderId++; - this._childUpdateId++; - this._skeleton._markAsDirty(); - return this; - } - /** @internal */ - _markAsDirtyAndCompose() { - this.markAsDirty(); - this._needToCompose = true; - } - _markAsDirtyAndDecompose() { - this.markAsDirty(); - this._needToDecompose = true; - } - _updatePosition(vec, space = math_axis_Space.LOCAL, tNode, translationMode = true) { - const lm = this.getLocalMatrix(); - if (space == math_axis_Space.LOCAL) { - if (translationMode) { - lm.addAtIndex(12, vec.x); - lm.addAtIndex(13, vec.y); - lm.addAtIndex(14, vec.z); - } - else { - lm.setTranslationFromFloats(vec.x, vec.y, vec.z); - } - } - else { - let wm = null; - //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices() - if (tNode) { - wm = tNode.getWorldMatrix(); - } - this._skeleton.computeAbsoluteMatrices(); - const tmat = Bone._TmpMats[0]; - const tvec = Bone._TmpVecs[0]; - if (this.parent) { - if (tNode && wm) { - tmat.copyFrom(this.parent.getAbsoluteMatrix()); - tmat.multiplyToRef(wm, tmat); - } - else { - tmat.copyFrom(this.parent.getAbsoluteMatrix()); - } - } - else { - math_vector_Matrix.IdentityToRef(tmat); - } - if (translationMode) { - tmat.setTranslationFromFloats(0, 0, 0); - } - tmat.invert(); - math_vector_Vector3.TransformCoordinatesToRef(vec, tmat, tvec); - if (translationMode) { - lm.addAtIndex(12, tvec.x); - lm.addAtIndex(13, tvec.y); - lm.addAtIndex(14, tvec.z); - } - else { - lm.setTranslationFromFloats(tvec.x, tvec.y, tvec.z); - } - } - this._markAsDirtyAndDecompose(); - } - /** - * Translate the bone in local or world space - * @param vec The amount to translate the bone - * @param space The space that the translation is in (default: Space.LOCAL) - * @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 - */ - translate(vec, space = math_axis_Space.LOCAL, tNode) { - this._updatePosition(vec, space, tNode, true); - } - /** - * Set the position of the bone in local or world space - * @param position The position to set the bone - * @param space The space that the position is in (default: Space.LOCAL) - * @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 - */ - setPosition(position, space = math_axis_Space.LOCAL, tNode) { - this._updatePosition(position, space, tNode, false); - } - /** - * Set the absolute position of the bone (world space) - * @param position The position to set the bone - * @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 - */ - setAbsolutePosition(position, tNode) { - this.setPosition(position, math_axis_Space.WORLD, tNode); - } - /** - * Scale the bone on the x, y and z axes (in local space) - * @param x The amount to scale the bone on the x axis - * @param y The amount to scale the bone on the y axis - * @param z The amount to scale the bone on the z axis - * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default) - */ - scale(x, y, z, scaleChildren = false) { - const locMat = this.getLocalMatrix(); - // Apply new scaling on top of current local matrix - const scaleMat = Bone._TmpMats[0]; - math_vector_Matrix.ScalingToRef(x, y, z, scaleMat); - scaleMat.multiplyToRef(locMat, locMat); - // Invert scaling matrix and apply the inverse to all children - scaleMat.invert(); - for (const child of this.children) { - const cm = child.getLocalMatrix(); - cm.multiplyToRef(scaleMat, cm); - cm.multiplyAtIndex(12, x); - cm.multiplyAtIndex(13, y); - cm.multiplyAtIndex(14, z); - child._markAsDirtyAndDecompose(); - } - this._markAsDirtyAndDecompose(); - if (scaleChildren) { - for (const child of this.children) { - child.scale(x, y, z, scaleChildren); - } - } - } - /** - * Set the bone scaling in local space - * @param scale defines the scaling vector - */ - setScale(scale) { - this._decompose(); - this._localScaling.copyFrom(scale); - this._markAsDirtyAndCompose(); - } - /** - * Gets the current scaling in local space - * @returns the current scaling vector - */ - getScale() { - this._decompose(); - return this._localScaling; - } - /** - * Gets the current scaling in local space and stores it in a target vector - * @param result defines the target vector - */ - getScaleToRef(result) { - this._decompose(); - result.copyFrom(this._localScaling); - } - /** - * Set the yaw, pitch, and roll of the bone in local or world space - * @param yaw The rotation of the bone on the y axis - * @param pitch The rotation of the bone on the x axis - * @param roll The rotation of the bone on the z axis - * @param space The space that the axes of rotation are in - * @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 - */ - setYawPitchRoll(yaw, pitch, roll, space = math_axis_Space.LOCAL, tNode) { - if (space === math_axis_Space.LOCAL) { - const quat = Bone._TmpQuat; - math_vector_Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat); - this.setRotationQuaternion(quat, space, tNode); - return; - } - const rotMatInv = Bone._TmpMats[0]; - if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { - return; - } - const rotMat = Bone._TmpMats[1]; - math_vector_Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat); - rotMatInv.multiplyToRef(rotMat, rotMat); - this._rotateWithMatrix(rotMat, space, tNode); - } - /** - * Add a rotation to the bone on an axis in local or world space - * @param axis The axis to rotate the bone on - * @param amount The amount to rotate the bone - * @param space The space that the axis is in - * @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 - */ - rotate(axis, amount, space = math_axis_Space.LOCAL, tNode) { - const rmat = Bone._TmpMats[0]; - rmat.setTranslationFromFloats(0, 0, 0); - math_vector_Matrix.RotationAxisToRef(axis, amount, rmat); - this._rotateWithMatrix(rmat, space, tNode); - } - /** - * Set the rotation of the bone to a particular axis angle in local or world space - * @param axis The axis to rotate the bone on - * @param angle The angle that the bone should be rotated to - * @param space The space that the axis is in - * @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 - */ - setAxisAngle(axis, angle, space = math_axis_Space.LOCAL, tNode) { - if (space === math_axis_Space.LOCAL) { - const quat = Bone._TmpQuat; - math_vector_Quaternion.RotationAxisToRef(axis, angle, quat); - this.setRotationQuaternion(quat, space, tNode); - return; - } - const rotMatInv = Bone._TmpMats[0]; - if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { - return; - } - const rotMat = Bone._TmpMats[1]; - math_vector_Matrix.RotationAxisToRef(axis, angle, rotMat); - rotMatInv.multiplyToRef(rotMat, rotMat); - this._rotateWithMatrix(rotMat, space, tNode); - } - /** - * Set the euler rotation of the bone in local or world space - * @param rotation The euler rotation that the bone should be set to - * @param space The space that the rotation is in - * @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 - */ - setRotation(rotation, space = math_axis_Space.LOCAL, tNode) { - this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, tNode); - } - /** - * Set the quaternion rotation of the bone in local or world space - * @param quat The quaternion rotation that the bone should be set to - * @param space The space that the rotation is in - * @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 - */ - setRotationQuaternion(quat, space = math_axis_Space.LOCAL, tNode) { - if (space === math_axis_Space.LOCAL) { - this._decompose(); - this._localRotation.copyFrom(quat); - this._markAsDirtyAndCompose(); - return; - } - const rotMatInv = Bone._TmpMats[0]; - if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { - return; - } - const rotMat = Bone._TmpMats[1]; - math_vector_Matrix.FromQuaternionToRef(quat, rotMat); - rotMatInv.multiplyToRef(rotMat, rotMat); - this._rotateWithMatrix(rotMat, space, tNode); - } - /** - * Set the rotation matrix of the bone in local or world space - * @param rotMat The rotation matrix that the bone should be set to - * @param space The space that the rotation is in - * @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 - */ - setRotationMatrix(rotMat, space = math_axis_Space.LOCAL, tNode) { - if (space === math_axis_Space.LOCAL) { - const quat = Bone._TmpQuat; - math_vector_Quaternion.FromRotationMatrixToRef(rotMat, quat); - this.setRotationQuaternion(quat, space, tNode); - return; - } - const rotMatInv = Bone._TmpMats[0]; - if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { - return; - } - const rotMat2 = Bone._TmpMats[1]; - rotMat2.copyFrom(rotMat); - rotMatInv.multiplyToRef(rotMat, rotMat2); - this._rotateWithMatrix(rotMat2, space, tNode); - } - _rotateWithMatrix(rmat, space = math_axis_Space.LOCAL, tNode) { - const lmat = this.getLocalMatrix(); - const lx = lmat.m[12]; - const ly = lmat.m[13]; - const lz = lmat.m[14]; - const parent = this.getParent(); - const parentScale = Bone._TmpMats[3]; - const parentScaleInv = Bone._TmpMats[4]; - if (parent && space == math_axis_Space.WORLD) { - if (tNode) { - parentScale.copyFrom(tNode.getWorldMatrix()); - parent.getAbsoluteMatrix().multiplyToRef(parentScale, parentScale); - } - else { - parentScale.copyFrom(parent.getAbsoluteMatrix()); - } - parentScaleInv.copyFrom(parentScale); - parentScaleInv.invert(); - lmat.multiplyToRef(parentScale, lmat); - lmat.multiplyToRef(rmat, lmat); - lmat.multiplyToRef(parentScaleInv, lmat); - } - else { - if (space == math_axis_Space.WORLD && tNode) { - parentScale.copyFrom(tNode.getWorldMatrix()); - parentScaleInv.copyFrom(parentScale); - parentScaleInv.invert(); - lmat.multiplyToRef(parentScale, lmat); - lmat.multiplyToRef(rmat, lmat); - lmat.multiplyToRef(parentScaleInv, lmat); - } - else { - lmat.multiplyToRef(rmat, lmat); - } - } - lmat.setTranslationFromFloats(lx, ly, lz); - this.computeAbsoluteMatrices(); - this._markAsDirtyAndDecompose(); - } - _getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode) { - const scaleMatrix = Bone._TmpMats[2]; - rotMatInv.copyFrom(this.getAbsoluteMatrix()); - if (tNode) { - rotMatInv.multiplyToRef(tNode.getWorldMatrix(), rotMatInv); - math_vector_Matrix.ScalingToRef(tNode.scaling.x, tNode.scaling.y, tNode.scaling.z, scaleMatrix); - } - else { - math_vector_Matrix.IdentityToRef(scaleMatrix); - } - rotMatInv.invert(); - if (isNaN(rotMatInv.m[0])) { - // Matrix failed to invert. - // This can happen if scale is zero for example. - return false; - } - scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant); - rotMatInv.multiplyToRef(scaleMatrix, rotMatInv); - return true; - } - /** - * Get the position of the bone in local or world space - * @param space The space that the returned position is in - * @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 - * @returns The position of the bone - */ - getPosition(space = math_axis_Space.LOCAL, tNode = null) { - const pos = math_vector_Vector3.Zero(); - this.getPositionToRef(space, tNode, pos); - return pos; - } - /** - * Copy the position of the bone to a vector3 in local or world space - * @param space The space that the returned position is in - * @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 - * @param result The vector3 to copy the position to - */ - getPositionToRef(space = math_axis_Space.LOCAL, tNode, result) { - if (space == math_axis_Space.LOCAL) { - const lm = this.getLocalMatrix(); - result.x = lm.m[12]; - result.y = lm.m[13]; - result.z = lm.m[14]; - } - else { - let wm = null; - //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices() - if (tNode) { - wm = tNode.getWorldMatrix(); - } - this._skeleton.computeAbsoluteMatrices(); - let tmat = Bone._TmpMats[0]; - if (tNode && wm) { - tmat.copyFrom(this.getAbsoluteMatrix()); - tmat.multiplyToRef(wm, tmat); - } - else { - tmat = this.getAbsoluteMatrix(); - } - result.x = tmat.m[12]; - result.y = tmat.m[13]; - result.z = tmat.m[14]; - } - } - /** - * Get the absolute position of the bone (world space) - * @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 - * @returns The absolute position of the bone - */ - getAbsolutePosition(tNode = null) { - const pos = math_vector_Vector3.Zero(); - this.getPositionToRef(math_axis_Space.WORLD, tNode, pos); - return pos; - } - /** - * Copy the absolute position of the bone (world space) to the result param - * @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 - * @param result The vector3 to copy the absolute position to - */ - getAbsolutePositionToRef(tNode, result) { - this.getPositionToRef(math_axis_Space.WORLD, tNode, result); - } - /** - * Compute the absolute matrices of this bone and its children - */ - computeAbsoluteMatrices() { - this._compose(); - if (this.parent) { - this._localMatrix.multiplyToRef(this.parent._absoluteMatrix, this._absoluteMatrix); - } - else { - this._absoluteMatrix.copyFrom(this._localMatrix); - const poseMatrix = this._skeleton.getPoseMatrix(); - if (poseMatrix) { - this._absoluteMatrix.multiplyToRef(poseMatrix, this._absoluteMatrix); - } - } - const children = this.children; - const len = children.length; - for (let i = 0; i < len; i++) { - children[i].computeAbsoluteMatrices(); - } - } - /** - * Compute the absolute matrices of this bone and its children - * @deprecated Please use computeAbsoluteMatrices instead - */ - computeAbsoluteTransforms() { - this.computeAbsoluteMatrices(); - } - /** - * Get the world direction from an axis that is in the local space of the bone - * @param localAxis The local direction that is used to compute the world direction - * @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 - * @returns The world direction - */ - getDirection(localAxis, tNode = null) { - const result = math_vector_Vector3.Zero(); - this.getDirectionToRef(localAxis, tNode, result); - return result; - } - /** - * Copy the world direction to a vector3 from an axis that is in the local space of the bone - * @param localAxis The local direction that is used to compute the world direction - * @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 - * @param result The vector3 that the world direction will be copied to - */ - getDirectionToRef(localAxis, tNode = null, result) { - let wm = null; - //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices() - if (tNode) { - wm = tNode.getWorldMatrix(); - } - this._skeleton.computeAbsoluteMatrices(); - const mat = Bone._TmpMats[0]; - mat.copyFrom(this.getAbsoluteMatrix()); - if (tNode && wm) { - mat.multiplyToRef(wm, mat); - } - math_vector_Vector3.TransformNormalToRef(localAxis, mat, result); - result.normalize(); - } - /** - * Get the euler rotation of the bone in local or world space - * @param space The space that the rotation should be in - * @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 - * @returns The euler rotation - */ - getRotation(space = math_axis_Space.LOCAL, tNode = null) { - const result = math_vector_Vector3.Zero(); - this.getRotationToRef(space, tNode, result); - return result; - } - /** - * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space - * @param space The space that the rotation should be in - * @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 - * @param result The vector3 that the rotation should be copied to - */ - getRotationToRef(space = math_axis_Space.LOCAL, tNode = null, result) { - const quat = Bone._TmpQuat; - this.getRotationQuaternionToRef(space, tNode, quat); - quat.toEulerAnglesToRef(result); - } - /** - * Get the quaternion rotation of the bone in either local or world space - * @param space The space that the rotation should be in - * @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 - * @returns The quaternion rotation - */ - getRotationQuaternion(space = math_axis_Space.LOCAL, tNode = null) { - const result = math_vector_Quaternion.Identity(); - this.getRotationQuaternionToRef(space, tNode, result); - return result; - } - /** - * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space - * @param space The space that the rotation should be in - * @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 - * @param result The quaternion that the rotation should be copied to - */ - getRotationQuaternionToRef(space = math_axis_Space.LOCAL, tNode = null, result) { - if (space == math_axis_Space.LOCAL) { - this._decompose(); - result.copyFrom(this._localRotation); - } - else { - const mat = Bone._TmpMats[0]; - const amat = this.getAbsoluteMatrix(); - if (tNode) { - amat.multiplyToRef(tNode.getWorldMatrix(), mat); - } - else { - mat.copyFrom(amat); - } - mat.multiplyAtIndex(0, this._scalingDeterminant); - mat.multiplyAtIndex(1, this._scalingDeterminant); - mat.multiplyAtIndex(2, this._scalingDeterminant); - mat.decompose(undefined, result, undefined); - } - } - /** - * Get the rotation matrix of the bone in local or world space - * @param space The space that the rotation should be in - * @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 - * @returns The rotation matrix - */ - getRotationMatrix(space = math_axis_Space.LOCAL, tNode) { - const result = math_vector_Matrix.Identity(); - this.getRotationMatrixToRef(space, tNode, result); - return result; - } - /** - * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space - * @param space The space that the rotation should be in - * @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 - * @param result The quaternion that the rotation should be copied to - */ - getRotationMatrixToRef(space = math_axis_Space.LOCAL, tNode, result) { - if (space == math_axis_Space.LOCAL) { - this.getLocalMatrix().getRotationMatrixToRef(result); - } - else { - const mat = Bone._TmpMats[0]; - const amat = this.getAbsoluteMatrix(); - if (tNode) { - amat.multiplyToRef(tNode.getWorldMatrix(), mat); - } - else { - mat.copyFrom(amat); - } - mat.multiplyAtIndex(0, this._scalingDeterminant); - mat.multiplyAtIndex(1, this._scalingDeterminant); - mat.multiplyAtIndex(2, this._scalingDeterminant); - mat.getRotationMatrixToRef(result); - } - } - /** - * Get the world position of a point that is in the local space of the bone - * @param position The local position - * @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 - * @returns The world position - */ - getAbsolutePositionFromLocal(position, tNode = null) { - const result = math_vector_Vector3.Zero(); - this.getAbsolutePositionFromLocalToRef(position, tNode, result); - return result; - } - /** - * Get the world position of a point that is in the local space of the bone and copy it to the result param - * @param position The local position - * @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 - * @param result The vector3 that the world position should be copied to - */ - getAbsolutePositionFromLocalToRef(position, tNode = null, result) { - let wm = null; - //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices() - if (tNode) { - wm = tNode.getWorldMatrix(); - } - this._skeleton.computeAbsoluteMatrices(); - const tmat = Bone._TmpMats[0]; - tmat.copyFrom(this.getAbsoluteMatrix()); - if (tNode && wm) { - tmat.multiplyToRef(wm, tmat); - } - math_vector_Vector3.TransformCoordinatesToRef(position, tmat, result); - } - /** - * Get the local position of a point that is in world space - * @param position The world position - * @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 - * @returns The local position - */ - getLocalPositionFromAbsolute(position, tNode = null) { - const result = math_vector_Vector3.Zero(); - this.getLocalPositionFromAbsoluteToRef(position, tNode, result); - return result; - } - /** - * Get the local position of a point that is in world space and copy it to the result param - * @param position The world position - * @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 - * @param result The vector3 that the local position should be copied to - */ - getLocalPositionFromAbsoluteToRef(position, tNode = null, result) { - let wm = null; - //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices() - if (tNode) { - wm = tNode.getWorldMatrix(); - } - this._skeleton.computeAbsoluteMatrices(); - const tmat = Bone._TmpMats[0]; - tmat.copyFrom(this.getAbsoluteMatrix()); - if (tNode && wm) { - tmat.multiplyToRef(wm, tmat); - } - tmat.invert(); - math_vector_Vector3.TransformCoordinatesToRef(position, tmat, result); - } - /** - * Set the current local matrix as the restMatrix for this bone. - */ - setCurrentPoseAsRest() { - this.setRestMatrix(this.getLocalMatrix()); - } -} -Bone._TmpVecs = arrayTools_ArrayTools.BuildArray(2, math_vector_Vector3.Zero); -Bone._TmpQuat = math_vector_Quaternion.Identity(); -Bone._TmpMats = arrayTools_ArrayTools.BuildArray(5, math_vector_Matrix.Identity); -//# sourceMappingURL=bone.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/animatable.js - - - - - - - -/** - * Class used to store an actual running animation - */ -class Animatable { - /** - * Gets the root Animatable used to synchronize and normalize animations - */ - get syncRoot() { - return this._syncRoot; - } - /** - * Gets the current frame of the first RuntimeAnimation - * Used to synchronize Animatables - */ - get masterFrame() { - if (this._runtimeAnimations.length === 0) { - return 0; - } - return this._runtimeAnimations[0].currentFrame; - } - /** - * Gets or sets the animatable weight (-1.0 by default meaning not weighted) - */ - get weight() { - return this._weight; - } - set weight(value) { - if (value === -1) { - // -1 is ok and means no weight - this._weight = -1; - return; - } - // Else weight must be in [0, 1] range - this._weight = Math.min(Math.max(value, 0), 1.0); - } - /** - * Gets or sets the speed ratio to apply to the animatable (1.0 by default) - */ - get speedRatio() { - return this._speedRatio; - } - set speedRatio(value) { - for (let index = 0; index < this._runtimeAnimations.length; index++) { - const animation = this._runtimeAnimations[index]; - animation._prepareForSpeedRatioChange(value); - } - this._speedRatio = value; - // Resync _manualJumpDelay in case goToFrame was called before speedRatio was set. - if (this._goToFrame !== null) { - this.goToFrame(this._goToFrame); - } - } - /** - * Creates a new Animatable - * @param scene defines the hosting scene - * @param target defines the target object - * @param fromFrame defines the starting frame number (default is 0) - * @param toFrame defines the ending frame number (default is 100) - * @param loopAnimation defines if the animation must loop (default is false) - * @param speedRatio defines the factor to apply to animation speed (default is 1) - * @param onAnimationEnd defines a callback to call when animation ends if it is not looping - * @param animations defines a group of animation to add to the new Animatable - * @param onAnimationLoop defines a callback to call when animation loops - * @param isAdditive defines whether the animation should be evaluated additively - * @param playOrder defines the order in which this animatable should be processed in the list of active animatables (default: 0) - */ - constructor(scene, - /** defines the target object */ - target, - /** defines the starting frame number (default is 0) */ - fromFrame = 0, - /** defines the ending frame number (default is 100) */ - toFrame = 100, - /** defines if the animation must loop (default is false) */ - loopAnimation = false, speedRatio = 1.0, - /** defines a callback to call when animation ends if it is not looping */ - onAnimationEnd, animations, - /** defines a callback to call when animation loops */ - onAnimationLoop, - /** defines whether the animation should be evaluated additively */ - isAdditive = false, - /** defines the order in which this animatable should be processed in the list of active animatables (default: 0) */ - playOrder = 0) { - this.target = target; - this.fromFrame = fromFrame; - this.toFrame = toFrame; - this.loopAnimation = loopAnimation; - this.onAnimationEnd = onAnimationEnd; - this.onAnimationLoop = onAnimationLoop; - this.isAdditive = isAdditive; - this.playOrder = playOrder; - this._localDelayOffset = null; - this._pausedDelay = null; - this._manualJumpDelay = null; - /** @hidden */ - this._runtimeAnimations = new Array(); - this._paused = false; - this._speedRatio = 1; - this._weight = -1.0; - this._syncRoot = null; - this._frameToSyncFromJump = null; - this._goToFrame = null; - /** - * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation. - * This will only apply for non looping animation (default is true) - */ - this.disposeOnEnd = true; - /** - * Gets a boolean indicating if the animation has started - */ - this.animationStarted = false; - /** - * Observer raised when the animation ends - */ - this.onAnimationEndObservable = new observable_Observable(); - /** - * Observer raised when the animation loops - */ - this.onAnimationLoopObservable = new observable_Observable(); - this._scene = scene; - if (animations) { - this.appendAnimations(target, animations); - } - this._speedRatio = speedRatio; - scene._activeAnimatables.push(this); - } - // Methods - /** - * Synchronize and normalize current Animatable with a source Animatable - * This is useful when using animation weights and when animations are not of the same length - * @param root defines the root Animatable to synchronize with (null to stop synchronizing) - * @returns the current Animatable - */ - syncWith(root) { - this._syncRoot = root; - if (root) { - // Make sure this animatable will animate after the root - const index = this._scene._activeAnimatables.indexOf(this); - if (index > -1) { - this._scene._activeAnimatables.splice(index, 1); - this._scene._activeAnimatables.push(this); - } - } - return this; - } - /** - * Gets the list of runtime animations - * @returns an array of RuntimeAnimation - */ - getAnimations() { - return this._runtimeAnimations; - } - /** - * Adds more animations to the current animatable - * @param target defines the target of the animations - * @param animations defines the new animations to add - */ - appendAnimations(target, animations) { - for (let index = 0; index < animations.length; index++) { - const animation = animations[index]; - const newRuntimeAnimation = new RuntimeAnimation(target, animation, this._scene, this); - newRuntimeAnimation._onLoop = () => { - this.onAnimationLoopObservable.notifyObservers(this); - if (this.onAnimationLoop) { - this.onAnimationLoop(); - } - }; - this._runtimeAnimations.push(newRuntimeAnimation); - } - } - /** - * Gets the source animation for a specific property - * @param property defines the property to look for - * @returns null or the source animation for the given property - */ - getAnimationByTargetProperty(property) { - const runtimeAnimations = this._runtimeAnimations; - for (let index = 0; index < runtimeAnimations.length; index++) { - if (runtimeAnimations[index].animation.targetProperty === property) { - return runtimeAnimations[index].animation; - } - } - return null; - } - /** - * Gets the runtime animation for a specific property - * @param property defines the property to look for - * @returns null or the runtime animation for the given property - */ - getRuntimeAnimationByTargetProperty(property) { - const runtimeAnimations = this._runtimeAnimations; - for (let index = 0; index < runtimeAnimations.length; index++) { - if (runtimeAnimations[index].animation.targetProperty === property) { - return runtimeAnimations[index]; - } - } - return null; - } - /** - * Resets the animatable to its original state - */ - reset() { - const runtimeAnimations = this._runtimeAnimations; - for (let index = 0; index < runtimeAnimations.length; index++) { - runtimeAnimations[index].reset(true); - } - this._localDelayOffset = null; - this._pausedDelay = null; - } - /** - * Allows the animatable to blend with current running animations - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending - * @param blendingSpeed defines the blending speed to use - */ - enableBlending(blendingSpeed) { - const runtimeAnimations = this._runtimeAnimations; - for (let index = 0; index < runtimeAnimations.length; index++) { - runtimeAnimations[index].animation.enableBlending = true; - runtimeAnimations[index].animation.blendingSpeed = blendingSpeed; - } - } - /** - * Disable animation blending - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending - */ - disableBlending() { - const runtimeAnimations = this._runtimeAnimations; - for (let index = 0; index < runtimeAnimations.length; index++) { - runtimeAnimations[index].animation.enableBlending = false; - } - } - /** - * Jump directly to a given frame - * @param frame defines the frame to jump to - */ - goToFrame(frame) { - var _a; - const runtimeAnimations = this._runtimeAnimations; - if (runtimeAnimations[0]) { - const fps = runtimeAnimations[0].animation.framePerSecond; - this._frameToSyncFromJump = (_a = this._frameToSyncFromJump) !== null && _a !== void 0 ? _a : runtimeAnimations[0].currentFrame; - const delay = this.speedRatio === 0 ? 0 : (((frame - this._frameToSyncFromJump) / fps) * 1000) / this.speedRatio; - this._manualJumpDelay = -delay; - } - for (let index = 0; index < runtimeAnimations.length; index++) { - runtimeAnimations[index].goToFrame(frame); - } - this._goToFrame = frame; - } - /** - * Returns true if the animations for this animatable are paused - */ - get paused() { - return this._paused; - } - /** - * Pause the animation - */ - pause() { - if (this._paused) { - return; - } - this._paused = true; - } - /** - * Restart the animation - */ - restart() { - this._paused = false; - } - _raiseOnAnimationEnd() { - if (this.onAnimationEnd) { - this.onAnimationEnd(); - } - this.onAnimationEndObservable.notifyObservers(this); - } - /** - * Stop and delete the current animation - * @param animationName defines a string used to only stop some of the runtime animations instead of all - * @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) - * @param useGlobalSplice if true, the animatables will be removed by the caller of this function (false by default) - */ - stop(animationName, targetMask, useGlobalSplice = false) { - if (animationName || targetMask) { - const idx = this._scene._activeAnimatables.indexOf(this); - if (idx > -1) { - const runtimeAnimations = this._runtimeAnimations; - for (let index = runtimeAnimations.length - 1; index >= 0; index--) { - const runtimeAnimation = runtimeAnimations[index]; - if (animationName && runtimeAnimation.animation.name != animationName) { - continue; - } - if (targetMask && !targetMask(runtimeAnimation.target)) { - continue; - } - runtimeAnimation.dispose(); - runtimeAnimations.splice(index, 1); - } - if (runtimeAnimations.length == 0) { - if (!useGlobalSplice) { - this._scene._activeAnimatables.splice(idx, 1); - } - this._raiseOnAnimationEnd(); - } - } - } - else { - const index = this._scene._activeAnimatables.indexOf(this); - if (index > -1) { - if (!useGlobalSplice) { - this._scene._activeAnimatables.splice(index, 1); - } - const runtimeAnimations = this._runtimeAnimations; - for (let index = 0; index < runtimeAnimations.length; index++) { - runtimeAnimations[index].dispose(); - } - this._runtimeAnimations.length = 0; - this._raiseOnAnimationEnd(); - } - } - } - /** - * Wait asynchronously for the animation to end - * @returns a promise which will be fulfilled when the animation ends - */ - waitAsync() { - return new Promise((resolve) => { - this.onAnimationEndObservable.add(() => { - resolve(this); - }, undefined, undefined, this, true); - }); - } - /** - * @internal - */ - _animate(delay) { - if (this._paused) { - this.animationStarted = false; - if (this._pausedDelay === null) { - this._pausedDelay = delay; - } - return true; - } - if (this._localDelayOffset === null) { - this._localDelayOffset = delay; - this._pausedDelay = null; - } - else if (this._pausedDelay !== null) { - this._localDelayOffset += delay - this._pausedDelay; - this._pausedDelay = null; - } - if (this._manualJumpDelay !== null) { - this._localDelayOffset += this._manualJumpDelay; - this._manualJumpDelay = null; - this._frameToSyncFromJump = null; - } - this._goToFrame = null; - if (this._weight === 0) { - // We consider that an animatable with a weight === 0 is "actively" paused - return true; - } - // Animating - let running = false; - const runtimeAnimations = this._runtimeAnimations; - let index; - for (index = 0; index < runtimeAnimations.length; index++) { - const animation = runtimeAnimations[index]; - const isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight); - running = running || isRunning; - } - this.animationStarted = running; - if (!running) { - if (this.disposeOnEnd) { - // Remove from active animatables - index = this._scene._activeAnimatables.indexOf(this); - this._scene._activeAnimatables.splice(index, 1); - // Dispose all runtime animations - for (index = 0; index < runtimeAnimations.length; index++) { - runtimeAnimations[index].dispose(); - } - } - this._raiseOnAnimationEnd(); - if (this.disposeOnEnd) { - this.onAnimationEnd = null; - this.onAnimationLoop = null; - this.onAnimationLoopObservable.clear(); - this.onAnimationEndObservable.clear(); - } - } - return running; - } -} -scene_Scene.prototype._animate = function () { - if (!this.animationsEnabled) { - return; - } - // Getting time - const now = precisionDate_PrecisionDate.Now; - if (!this._animationTimeLast) { - if (this._pendingData.length > 0) { - return; - } - this._animationTimeLast = now; - } - this.deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale; - this._animationTimeLast = now; - const animatables = this._activeAnimatables; - if (animatables.length === 0) { - return; - } - this._animationTime += this.deltaTime; - const animationTime = this._animationTime; - for (let index = 0; index < animatables.length; index++) { - const animatable = animatables[index]; - if (!animatable._animate(animationTime) && animatable.disposeOnEnd) { - index--; // Array was updated - } - } - // Late animation bindings - this._processLateAnimationBindings(); -}; -scene_Scene.prototype.sortActiveAnimatables = function () { - this._activeAnimatables.sort((a, b) => { - return a.playOrder - b.playOrder; - }); -}; -scene_Scene.prototype.beginWeightedAnimation = function (target, from, to, weight = 1.0, loop, speedRatio = 1.0, onAnimationEnd, animatable, targetMask, onAnimationLoop, isAdditive = false) { - const returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop, isAdditive); - returnedAnimatable.weight = weight; - return returnedAnimatable; -}; -scene_Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio = 1.0, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) { - if (from > to && speedRatio > 0) { - speedRatio *= -1; - } - if (stopCurrent) { - this.stopAnimation(target, undefined, targetMask); - } - if (!animatable) { - animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, undefined, onAnimationLoop, isAdditive); - } - const shouldRunTargetAnimations = targetMask ? targetMask(target) : true; - // Local animations - if (target.animations && shouldRunTargetAnimations) { - animatable.appendAnimations(target, target.animations); - } - // Children animations - if (target.getAnimatables) { - const animatables = target.getAnimatables(); - for (let index = 0; index < animatables.length; index++) { - this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop); - } - } - animatable.reset(); - return animatable; -}; -scene_Scene.prototype.beginHierarchyAnimation = function (target, directDescendantsOnly, from, to, loop, speedRatio = 1.0, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) { - const children = target.getDescendants(directDescendantsOnly); - const result = []; - result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, undefined, isAdditive)); - for (const child of children) { - result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, undefined, isAdditive)); - } - return result; -}; -scene_Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive = false) { - if (speedRatio === undefined) { - speedRatio = 1.0; - } - if (from > to && speedRatio > 0) { - speedRatio *= -1; - } - else if (to > from && speedRatio < 0) { - const temp = to; - to = from; - from = temp; - } - const animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop, isAdditive); - return animatable; -}; -scene_Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive = false) { - const children = target.getDescendants(directDescendantsOnly); - const result = []; - result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive)); - for (const child of children) { - result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive)); - } - return result; -}; -scene_Scene.prototype.getAnimatableByTarget = function (target) { - for (let index = 0; index < this._activeAnimatables.length; index++) { - if (this._activeAnimatables[index].target === target) { - return this._activeAnimatables[index]; - } - } - return null; -}; -scene_Scene.prototype.getAllAnimatablesByTarget = function (target) { - const result = []; - for (let index = 0; index < this._activeAnimatables.length; index++) { - if (this._activeAnimatables[index].target === target) { - result.push(this._activeAnimatables[index]); - } - } - return result; -}; -/** - * Will stop the animation of the given target - * @param target - the target - * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty) - * @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) - */ -scene_Scene.prototype.stopAnimation = function (target, animationName, targetMask) { - const animatables = this.getAllAnimatablesByTarget(target); - for (const animatable of animatables) { - animatable.stop(animationName, targetMask); - } -}; -/** - * Stops and removes all animations that have been applied to the scene - */ -scene_Scene.prototype.stopAllAnimations = function () { - if (this._activeAnimatables) { - for (let i = 0; i < this._activeAnimatables.length; i++) { - this._activeAnimatables[i].stop(undefined, undefined, true); - } - this._activeAnimatables.length = 0; - } - for (const group of this.animationGroups) { - group.stop(); - } -}; -scene_Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) { - const target = runtimeAnimation.target; - this._registeredForLateAnimationBindings.pushNoDuplicate(target); - if (!target._lateAnimationHolders) { - target._lateAnimationHolders = {}; - } - if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) { - target._lateAnimationHolders[runtimeAnimation.targetPath] = { - totalWeight: 0, - totalAdditiveWeight: 0, - animations: [], - additiveAnimations: [], - originalValue: originalValue, - }; - } - if (runtimeAnimation.isAdditive) { - target._lateAnimationHolders[runtimeAnimation.targetPath].additiveAnimations.push(runtimeAnimation); - target._lateAnimationHolders[runtimeAnimation.targetPath].totalAdditiveWeight += runtimeAnimation.weight; - } - else { - target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation); - target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight; - } -}; -scene_Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) { - if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) { - return holder.originalValue; - } - let normalizer = 1.0; - const finalPosition = math_vector_TmpVectors.Vector3[0]; - const finalScaling = math_vector_TmpVectors.Vector3[1]; - const finalQuaternion = math_vector_TmpVectors.Quaternion[0]; - let startIndex = 0; - const originalAnimation = holder.animations[0]; - const originalValue = holder.originalValue; - let scale = 1; - let skipOverride = false; - if (holder.totalWeight < 1.0) { - // We need to mix the original value in - scale = 1.0 - holder.totalWeight; - originalValue.decompose(finalScaling, finalQuaternion, finalPosition); - } - else { - startIndex = 1; - // We need to normalize the weights - normalizer = holder.totalWeight; - scale = originalAnimation.weight / normalizer; - if (scale == 1) { - if (holder.totalAdditiveWeight) { - skipOverride = true; - } - else { - return originalAnimation.currentValue; - } - } - originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition); - } - // Add up the override animations - if (!skipOverride) { - finalScaling.scaleInPlace(scale); - finalPosition.scaleInPlace(scale); - finalQuaternion.scaleInPlace(scale); - for (let animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { - const runtimeAnimation = holder.animations[animIndex]; - if (runtimeAnimation.weight === 0) { - continue; - } - scale = runtimeAnimation.weight / normalizer; - const currentPosition = math_vector_TmpVectors.Vector3[2]; - const currentScaling = math_vector_TmpVectors.Vector3[3]; - const currentQuaternion = math_vector_TmpVectors.Quaternion[1]; - runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); - currentScaling.scaleAndAddToRef(scale, finalScaling); - currentQuaternion.scaleAndAddToRef(math_vector_Quaternion.Dot(finalQuaternion, currentQuaternion) > 0 ? scale : -scale, finalQuaternion); - currentPosition.scaleAndAddToRef(scale, finalPosition); - } - finalQuaternion.normalize(); - } - // Add up the additive animations - for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) { - const runtimeAnimation = holder.additiveAnimations[animIndex]; - if (runtimeAnimation.weight === 0) { - continue; - } - const currentPosition = math_vector_TmpVectors.Vector3[2]; - const currentScaling = math_vector_TmpVectors.Vector3[3]; - const currentQuaternion = math_vector_TmpVectors.Quaternion[1]; - runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); - currentScaling.multiplyToRef(finalScaling, currentScaling); - math_vector_Vector3.LerpToRef(finalScaling, currentScaling, runtimeAnimation.weight, finalScaling); - finalQuaternion.multiplyToRef(currentQuaternion, currentQuaternion); - math_vector_Quaternion.SlerpToRef(finalQuaternion, currentQuaternion, runtimeAnimation.weight, finalQuaternion); - currentPosition.scaleAndAddToRef(runtimeAnimation.weight, finalPosition); - } - const workValue = originalAnimation ? originalAnimation._animationState.workValue : math_vector_TmpVectors.Matrix[0].clone(); - math_vector_Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, workValue); - return workValue; -}; -scene_Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) { - if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) { - return refQuaternion; - } - const originalAnimation = holder.animations[0]; - const originalValue = holder.originalValue; - let cumulativeQuaternion = refQuaternion; - if (holder.totalWeight === 0 && holder.totalAdditiveWeight > 0) { - cumulativeQuaternion.copyFrom(originalValue); - } - else if (holder.animations.length === 1) { - math_vector_Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), cumulativeQuaternion); - if (holder.totalAdditiveWeight === 0) { - return cumulativeQuaternion; - } - } - else if (holder.animations.length > 1) { - // Add up the override animations - let normalizer = 1.0; - let quaternions; - let weights; - if (holder.totalWeight < 1.0) { - const scale = 1.0 - holder.totalWeight; - quaternions = []; - weights = []; - quaternions.push(originalValue); - weights.push(scale); - } - else { - if (holder.animations.length === 2) { - // Slerp as soon as we can - math_vector_Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion); - if (holder.totalAdditiveWeight === 0) { - return refQuaternion; - } - } - quaternions = []; - weights = []; - normalizer = holder.totalWeight; - } - for (let animIndex = 0; animIndex < holder.animations.length; animIndex++) { - const runtimeAnimation = holder.animations[animIndex]; - quaternions.push(runtimeAnimation.currentValue); - weights.push(runtimeAnimation.weight / normalizer); - } - // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions - let cumulativeAmount = 0; - for (let index = 0; index < quaternions.length;) { - if (!index) { - math_vector_Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion); - cumulativeQuaternion = refQuaternion; - cumulativeAmount = weights[index] + weights[index + 1]; - index += 2; - continue; - } - cumulativeAmount += weights[index]; - math_vector_Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion); - index++; - } - } - // Add up the additive animations - for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) { - const runtimeAnimation = holder.additiveAnimations[animIndex]; - if (runtimeAnimation.weight === 0) { - continue; - } - cumulativeQuaternion.multiplyToRef(runtimeAnimation.currentValue, math_vector_TmpVectors.Quaternion[0]); - math_vector_Quaternion.SlerpToRef(cumulativeQuaternion, math_vector_TmpVectors.Quaternion[0], runtimeAnimation.weight, cumulativeQuaternion); - } - return cumulativeQuaternion; -}; -scene_Scene.prototype._processLateAnimationBindings = function () { - if (!this._registeredForLateAnimationBindings.length) { - return; - } - for (let index = 0; index < this._registeredForLateAnimationBindings.length; index++) { - const target = this._registeredForLateAnimationBindings.data[index]; - for (const path in target._lateAnimationHolders) { - const holder = target._lateAnimationHolders[path]; - const originalAnimation = holder.animations[0]; - const originalValue = holder.originalValue; - if (originalValue === undefined || originalValue === null) { - continue; - } - const matrixDecomposeMode = animation_Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix - let finalValue = target[path]; - if (matrixDecomposeMode) { - finalValue = this._processLateAnimationBindingsForMatrices(holder); - } - else { - const quaternionMode = originalValue.w !== undefined; - if (quaternionMode) { - finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || math_vector_Quaternion.Identity()); - } - else { - let startIndex = 0; - let normalizer = 1.0; - if (holder.totalWeight < 1.0) { - // We need to mix the original value in - if (originalAnimation && originalValue.scale) { - finalValue = originalValue.scale(1.0 - holder.totalWeight); - } - else if (originalAnimation) { - finalValue = originalValue * (1.0 - holder.totalWeight); - } - else if (originalValue.clone) { - finalValue = originalValue.clone(); - } - else { - finalValue = originalValue; - } - } - else if (originalAnimation) { - // We need to normalize the weights - normalizer = holder.totalWeight; - const scale = originalAnimation.weight / normalizer; - if (scale !== 1) { - if (originalAnimation.currentValue.scale) { - finalValue = originalAnimation.currentValue.scale(scale); - } - else { - finalValue = originalAnimation.currentValue * scale; - } - } - else { - finalValue = originalAnimation.currentValue; - } - startIndex = 1; - } - // Add up the override animations - for (let animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { - const runtimeAnimation = holder.animations[animIndex]; - const scale = runtimeAnimation.weight / normalizer; - if (!scale) { - continue; - } - else if (runtimeAnimation.currentValue.scaleAndAddToRef) { - runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue); - } - else { - finalValue += runtimeAnimation.currentValue * scale; - } - } - // Add up the additive animations - for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) { - const runtimeAnimation = holder.additiveAnimations[animIndex]; - const scale = runtimeAnimation.weight; - if (!scale) { - continue; - } - else if (runtimeAnimation.currentValue.scaleAndAddToRef) { - runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue); - } - else { - finalValue += runtimeAnimation.currentValue * scale; - } - } - } - } - target[path] = finalValue; - } - target._lateAnimationHolders = {}; - } - this._registeredForLateAnimationBindings.reset(); -}; -Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired = false, skelDimensionsRatio = null) { - // all animation may be coming from a library skeleton, so may need to create animation - if (this.animations.length === 0) { - this.animations.push(new animation_Animation(this.name, "_matrix", source.animations[0].framePerSecond, animation_Animation.ANIMATIONTYPE_MATRIX, 0)); - this.animations[0].setKeys([]); - } - // get animation info / verify there is such a range from the source bone - const sourceRange = source.animations[0].getRange(rangeName); - if (!sourceRange) { - return false; - } - const from = sourceRange.from; - const to = sourceRange.to; - const sourceKeys = source.animations[0].getKeys(); - // rescaling prep - const sourceBoneLength = source.length; - const sourceParent = source.getParent(); - const parent = this.getParent(); - const parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length; - const parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1; - const dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1); - const destKeys = this.animations[0].getKeys(); - // loop vars declaration - let orig; - let origTranslation; - let mat; - for (let key = 0, nKeys = sourceKeys.length; key < nKeys; key++) { - orig = sourceKeys[key]; - if (orig.frame >= from && orig.frame <= to) { - if (rescaleAsRequired) { - mat = orig.value.clone(); - // scale based on parent ratio, when bone has parent - if (parentScalingReqd) { - origTranslation = mat.getTranslation(); - mat.setTranslation(origTranslation.scaleInPlace(parentRatio)); - // scale based on skeleton dimension ratio when root bone, and value is passed - } - else if (dimensionsScalingReqd && skelDimensionsRatio) { - origTranslation = mat.getTranslation(); - mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio)); - // use original when root bone, and no data for skelDimensionsRatio - } - else { - mat = orig.value; - } - } - else { - mat = orig.value; - } - destKeys.push({ frame: orig.frame + frameOffset, value: mat }); - } - } - this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset); - return true; -}; -//# sourceMappingURL=animatable.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/animationPropertiesOverride.js - -/** - * Class used to override all child animations of a given target - */ -class AnimationPropertiesOverride { - constructor() { - /** - * Gets or sets a value indicating if animation blending must be used - */ - this.enableBlending = false; - /** - * Gets or sets the blending speed to use when enableBlending is true - */ - this.blendingSpeed = 0.01; - /** - * Gets or sets the default loop mode to use - */ - this.loopMode = Animation.ANIMATIONLOOPMODE_CYCLE; - } -} -//# sourceMappingURL=animationPropertiesOverride.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.path.js - - - -/** - * Defines potential orientation for back face culling - */ -var Orientation; -(function (Orientation) { - /** - * Clockwise - */ - Orientation[Orientation["CW"] = 0] = "CW"; - /** Counter clockwise */ - Orientation[Orientation["CCW"] = 1] = "CCW"; -})(Orientation || (Orientation = {})); -/** Class used to represent a Bezier curve */ -class math_path_BezierCurve { - /** - * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats - * @param t defines the time - * @param x1 defines the left coordinate on X axis - * @param y1 defines the left coordinate on Y axis - * @param x2 defines the right coordinate on X axis - * @param y2 defines the right coordinate on Y axis - * @returns the interpolated value - */ - static Interpolate(t, x1, y1, x2, y2) { - // Extract X (which is equal to time here) - const f0 = 1 - 3 * x2 + 3 * x1; - const f1 = 3 * x2 - 6 * x1; - const f2 = 3 * x1; - let refinedT = t; - for (let i = 0; i < 5; i++) { - const refinedT2 = refinedT * refinedT; - const refinedT3 = refinedT2 * refinedT; - const x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT; - const slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2); - refinedT -= (x - t) * slope; - refinedT = Math.min(1, Math.max(0, refinedT)); - } - // Resolve cubic bezier for the given x - return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3); - } -} -/** - * Defines angle representation - */ -class Angle { - /** - * Creates an Angle object of "radians" radians (float). - * @param radians the angle in radians - */ - constructor(radians) { - this._radians = radians; - if (this._radians < 0.0) { - this._radians += 2.0 * Math.PI; - } - } - /** - * Get value in degrees - * @returns the Angle value in degrees (float) - */ - degrees() { - return (this._radians * 180.0) / Math.PI; - } - /** - * Get value in radians - * @returns the Angle value in radians (float) - */ - radians() { - return this._radians; - } - /** - * Gets a new Angle object valued with the gradient angle, in radians, of the line joining two points - * @param a defines first point as the origin - * @param b defines point - * @returns a new Angle - */ - static BetweenTwoPoints(a, b) { - const delta = b.subtract(a); - const theta = Math.atan2(delta.y, delta.x); - return new Angle(theta); - } - /** - * Gets a new Angle object from the given float in radians - * @param radians defines the angle value in radians - * @returns a new Angle - */ - static FromRadians(radians) { - return new Angle(radians); - } - /** - * Gets a new Angle object from the given float in degrees - * @param degrees defines the angle value in degrees - * @returns a new Angle - */ - static FromDegrees(degrees) { - return new Angle((degrees * Math.PI) / 180.0); - } -} -/** - * This represents an arc in a 2d space. - */ -class Arc2 { - /** - * Creates an Arc object from the three given points : start, middle and end. - * @param startPoint Defines the start point of the arc - * @param midPoint Defines the middle point of the arc - * @param endPoint Defines the end point of the arc - */ - constructor( - /** Defines the start point of the arc */ - startPoint, - /** Defines the mid point of the arc */ - midPoint, - /** Defines the end point of the arc */ - endPoint) { - this.startPoint = startPoint; - this.midPoint = midPoint; - this.endPoint = endPoint; - const temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2); - const startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2; - const midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2; - const det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y); - this.centerPoint = new math_vector_Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det); - this.radius = this.centerPoint.subtract(this.startPoint).length(); - this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint); - const a1 = this.startAngle.degrees(); - let a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees(); - let a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees(); - // angles correction - if (a2 - a1 > +180.0) { - a2 -= 360.0; - } - if (a2 - a1 < -180.0) { - a2 += 360.0; - } - if (a3 - a2 > +180.0) { - a3 -= 360.0; - } - if (a3 - a2 < -180.0) { - a3 += 360.0; - } - this.orientation = a2 - a1 < 0 ? Orientation.CW : Orientation.CCW; - this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1); - } -} -/** - * Represents a 2D path made up of multiple 2D points - */ -class math_path_Path2 { - /** - * Creates a Path2 object from the starting 2D coordinates x and y. - * @param x the starting points x value - * @param y the starting points y value - */ - constructor(x, y) { - this._points = new Array(); - this._length = 0.0; - /** - * If the path start and end point are the same - */ - this.closed = false; - this._points.push(new math_vector_Vector2(x, y)); - } - /** - * Adds a new segment until the given coordinates (x, y) to the current Path2. - * @param x the added points x value - * @param y the added points y value - * @returns the updated Path2. - */ - addLineTo(x, y) { - if (this.closed) { - return this; - } - const newPoint = new math_vector_Vector2(x, y); - const previousPoint = this._points[this._points.length - 1]; - this._points.push(newPoint); - this._length += newPoint.subtract(previousPoint).length(); - return this; - } - /** - * 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. - * @param midX middle point x value - * @param midY middle point y value - * @param endX end point x value - * @param endY end point y value - * @param numberOfSegments (default: 36) - * @returns the updated Path2. - */ - addArcTo(midX, midY, endX, endY, numberOfSegments = 36) { - if (this.closed) { - return this; - } - const startPoint = this._points[this._points.length - 1]; - const midPoint = new math_vector_Vector2(midX, midY); - const endPoint = new math_vector_Vector2(endX, endY); - const arc = new Arc2(startPoint, midPoint, endPoint); - let increment = arc.angle.radians() / numberOfSegments; - if (arc.orientation === Orientation.CW) { - increment *= -1; - } - let currentAngle = arc.startAngle.radians() + increment; - for (let i = 0; i < numberOfSegments; i++) { - const x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x; - const y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y; - this.addLineTo(x, y); - currentAngle += increment; - } - return this; - } - /** - * Adds _numberOfSegments_ segments according to the quadratic curve definition to the current Path2. - * @param controlX control point x value - * @param controlY control point y value - * @param endX end point x value - * @param endY end point y value - * @param numberOfSegments (default: 36) - * @returns the updated Path2. - */ - addQuadraticCurveTo(controlX, controlY, endX, endY, numberOfSegments = 36) { - if (this.closed) { - return this; - } - const equation = (t, val0, val1, val2) => { - const res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2; - return res; - }; - const startPoint = this._points[this._points.length - 1]; - for (let i = 0; i <= numberOfSegments; i++) { - const step = i / numberOfSegments; - const x = equation(step, startPoint.x, controlX, endX); - const y = equation(step, startPoint.y, controlY, endY); - this.addLineTo(x, y); - } - return this; - } - /** - * Adds _numberOfSegments_ segments according to the bezier curve definition to the current Path2. - * @param originTangentX tangent vector at the origin point x value - * @param originTangentY tangent vector at the origin point y value - * @param destinationTangentX tangent vector at the destination point x value - * @param destinationTangentY tangent vector at the destination point y value - * @param endX end point x value - * @param endY end point y value - * @param numberOfSegments (default: 36) - * @returns the updated Path2. - */ - addBezierCurveTo(originTangentX, originTangentY, destinationTangentX, destinationTangentY, endX, endY, numberOfSegments = 36) { - if (this.closed) { - return this; - } - const equation = (t, val0, val1, val2, val3) => { - 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; - return res; - }; - const startPoint = this._points[this._points.length - 1]; - for (let i = 0; i <= numberOfSegments; i++) { - const step = i / numberOfSegments; - const x = equation(step, startPoint.x, originTangentX, destinationTangentX, endX); - const y = equation(step, startPoint.y, originTangentY, destinationTangentY, endY); - this.addLineTo(x, y); - } - return this; - } - /** - * Defines if a given point is inside the polygon defines by the path - * @param point defines the point to test - * @returns true if the point is inside - */ - isPointInside(point) { - let isInside = false; - const count = this._points.length; - for (let p = count - 1, q = 0; q < count; p = q++) { - let edgeLow = this._points[p]; - let edgeHigh = this._points[q]; - let edgeDx = edgeHigh.x - edgeLow.x; - let edgeDy = edgeHigh.y - edgeLow.y; - if (Math.abs(edgeDy) > Number.EPSILON) { - // Not parallel - if (edgeDy < 0) { - edgeLow = this._points[q]; - edgeDx = -edgeDx; - edgeHigh = this._points[p]; - edgeDy = -edgeDy; - } - if (point.y < edgeLow.y || point.y > edgeHigh.y) { - continue; - } - if (point.y === edgeLow.y && point.x === edgeLow.x) { - return true; - } - else { - const perpEdge = edgeDy * (point.x - edgeLow.x) - edgeDx * (point.y - edgeLow.y); - if (perpEdge === 0) { - return true; - } - if (perpEdge < 0) { - continue; - } - isInside = !isInside; - } - } - else { - // parallel or collinear - if (point.y !== edgeLow.y) { - continue; - } - if ((edgeHigh.x <= point.x && point.x <= edgeLow.x) || (edgeLow.x <= point.x && point.x <= edgeHigh.x)) { - return true; - } - } - } - return isInside; - } - /** - * Closes the Path2. - * @returns the Path2. - */ - close() { - this.closed = true; - return this; - } - /** - * Gets the sum of the distance between each sequential point in the path - * @returns the Path2 total length (float). - */ - length() { - let result = this._length; - if (this.closed) { - const lastPoint = this._points[this._points.length - 1]; - const firstPoint = this._points[0]; - result += firstPoint.subtract(lastPoint).length(); - } - return result; - } - /** - * Gets the area of the polygon defined by the path - * @returns area value - */ - area() { - const n = this._points.length; - let value = 0.0; - for (let p = n - 1, q = 0; q < n; p = q++) { - value += this._points[p].x * this._points[q].y - this._points[q].x * this._points[p].y; - } - return value * 0.5; - } - /** - * Gets the points which construct the path - * @returns the Path2 internal array of points. - */ - getPoints() { - return this._points; - } - /** - * Retreives the point at the distance aways from the starting point - * @param normalizedLengthPosition the length along the path to retrieve the point from - * @returns a new Vector2 located at a percentage of the Path2 total length on this path. - */ - getPointAtLengthPosition(normalizedLengthPosition) { - if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) { - return math_vector_Vector2.Zero(); - } - const lengthPosition = normalizedLengthPosition * this.length(); - let previousOffset = 0; - for (let i = 0; i < this._points.length; i++) { - const j = (i + 1) % this._points.length; - const a = this._points[i]; - const b = this._points[j]; - const bToA = b.subtract(a); - const nextOffset = bToA.length() + previousOffset; - if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) { - const dir = bToA.normalize(); - const localOffset = lengthPosition - previousOffset; - return new math_vector_Vector2(a.x + dir.x * localOffset, a.y + dir.y * localOffset); - } - previousOffset = nextOffset; - } - return math_vector_Vector2.Zero(); - } - /** - * Creates a new path starting from an x and y position - * @param x starting x value - * @param y starting y value - * @returns a new Path2 starting at the coordinates (x, y). - */ - static StartingAt(x, y) { - return new math_path_Path2(x, y); - } -} -/** - * Represents a 3D path made up of multiple 3D points - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D - */ -class Path3D { - /** - * new Path3D(path, normal, raw) - * Creates a Path3D. A Path3D is a logical math object, so not a mesh. - * please read the description in the tutorial : https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D - * @param path an array of Vector3, the curve axis of the Path3D - * @param firstNormal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal. - * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed. - * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path. - */ - constructor( - /** - * an array of Vector3, the curve axis of the Path3D - */ - path, firstNormal = null, raw, alignTangentsWithPath = false) { - this.path = path; - this._curve = new Array(); - this._distances = new Array(); - this._tangents = new Array(); - this._normals = new Array(); - this._binormals = new Array(); - // holds interpolated point data - this._pointAtData = { - id: 0, - point: math_vector_Vector3.Zero(), - previousPointArrayIndex: 0, - position: 0, - subPosition: 0, - interpolateReady: false, - interpolationMatrix: math_vector_Matrix.Identity(), - }; - for (let p = 0; p < path.length; p++) { - this._curve[p] = path[p].clone(); // hard copy - } - this._raw = raw || false; - this._alignTangentsWithPath = alignTangentsWithPath; - this._compute(firstNormal, alignTangentsWithPath); - } - /** - * Returns the Path3D array of successive Vector3 designing its curve. - * @returns the Path3D array of successive Vector3 designing its curve. - */ - getCurve() { - return this._curve; - } - /** - * Returns the Path3D array of successive Vector3 designing its curve. - * @returns the Path3D array of successive Vector3 designing its curve. - */ - getPoints() { - return this._curve; - } - /** - * @returns the computed length (float) of the path. - */ - length() { - return this._distances[this._distances.length - 1]; - } - /** - * Returns an array populated with tangent vectors on each Path3D curve point. - * @returns an array populated with tangent vectors on each Path3D curve point. - */ - getTangents() { - return this._tangents; - } - /** - * Returns an array populated with normal vectors on each Path3D curve point. - * @returns an array populated with normal vectors on each Path3D curve point. - */ - getNormals() { - return this._normals; - } - /** - * Returns an array populated with binormal vectors on each Path3D curve point. - * @returns an array populated with binormal vectors on each Path3D curve point. - */ - getBinormals() { - return this._binormals; - } - /** - * Returns an array populated with distances (float) of the i-th point from the first curve point. - * @returns an array populated with distances (float) of the i-th point from the first curve point. - */ - getDistances() { - return this._distances; - } - /** - * Returns an interpolated point along this path - * @param position the position of the point along this path, from 0.0 to 1.0 - * @returns a new Vector3 as the point - */ - getPointAt(position) { - return this._updatePointAtData(position).point; - } - /** - * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path. - * @param position the position of the point along this path, from 0.0 to 1.0 - * @param interpolated (optional, default false) : boolean, if true returns an interpolated tangent instead of the tangent of the previous path point. - * @returns a tangent vector corresponding to the interpolated Path3D curve point, if not interpolated, the tangent is taken from the precomputed tangents array. - */ - getTangentAt(position, interpolated = false) { - this._updatePointAtData(position, interpolated); - return interpolated ? math_vector_Vector3.TransformCoordinates(math_vector_Vector3.Forward(), this._pointAtData.interpolationMatrix) : this._tangents[this._pointAtData.previousPointArrayIndex]; - } - /** - * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path. - * @param position the position of the point along this path, from 0.0 to 1.0 - * @param interpolated (optional, default false) : boolean, if true returns an interpolated normal instead of the normal of the previous path point. - * @returns a normal vector corresponding to the interpolated Path3D curve point, if not interpolated, the normal is taken from the precomputed normals array. - */ - getNormalAt(position, interpolated = false) { - this._updatePointAtData(position, interpolated); - return interpolated ? math_vector_Vector3.TransformCoordinates(math_vector_Vector3.Right(), this._pointAtData.interpolationMatrix) : this._normals[this._pointAtData.previousPointArrayIndex]; - } - /** - * Returns the binormal vector of an interpolated Path3D curve point at the specified position along this path. - * @param position the position of the point along this path, from 0.0 to 1.0 - * @param interpolated (optional, default false) : boolean, if true returns an interpolated binormal instead of the binormal of the previous path point. - * @returns a binormal vector corresponding to the interpolated Path3D curve point, if not interpolated, the binormal is taken from the precomputed binormals array. - */ - getBinormalAt(position, interpolated = false) { - this._updatePointAtData(position, interpolated); - return interpolated ? math_vector_Vector3.TransformCoordinates(math_vector_Vector3.UpReadOnly, this._pointAtData.interpolationMatrix) : this._binormals[this._pointAtData.previousPointArrayIndex]; - } - /** - * Returns the distance (float) of an interpolated Path3D curve point at the specified position along this path. - * @param position the position of the point along this path, from 0.0 to 1.0 - * @returns the distance of the interpolated Path3D curve point at the specified position along this path. - */ - getDistanceAt(position) { - return this.length() * position; - } - /** - * Returns the array index of the previous point of an interpolated point along this path - * @param position the position of the point to interpolate along this path, from 0.0 to 1.0 - * @returns the array index - */ - getPreviousPointIndexAt(position) { - this._updatePointAtData(position); - return this._pointAtData.previousPointArrayIndex; - } - /** - * 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) - * @param position the position of the point to interpolate along this path, from 0.0 to 1.0 - * @returns the sub position - */ - getSubPositionAt(position) { - this._updatePointAtData(position); - return this._pointAtData.subPosition; - } - /** - * Returns the position of the closest virtual point on this path to an arbitrary Vector3, from 0.0 to 1.0 - * @param target the vector of which to get the closest position to - * @returns the position of the closest virtual point on this path to the target vector - */ - getClosestPositionTo(target) { - let smallestDistance = Number.MAX_VALUE; - let closestPosition = 0.0; - for (let i = 0; i < this._curve.length - 1; i++) { - const point = this._curve[i + 0]; - const tangent = this._curve[i + 1].subtract(point).normalize(); - const subLength = this._distances[i + 1] - this._distances[i + 0]; - const subPosition = Math.min((Math.max(math_vector_Vector3.Dot(tangent, target.subtract(point).normalize()), 0.0) * math_vector_Vector3.Distance(point, target)) / subLength, 1.0); - const distance = math_vector_Vector3.Distance(point.add(tangent.scale(subPosition * subLength)), target); - if (distance < smallestDistance) { - smallestDistance = distance; - closestPosition = (this._distances[i + 0] + subLength * subPosition) / this.length(); - } - } - return closestPosition; - } - /** - * Returns a sub path (slice) of this path - * @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 - * @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 - * @returns a sub path (slice) of this path - */ - slice(start = 0.0, end = 1.0) { - if (start < 0.0) { - start = 1 - ((start * -1.0) % 1.0); - } - if (end < 0.0) { - end = 1 - ((end * -1.0) % 1.0); - } - if (start > end) { - const _start = start; - start = end; - end = _start; - } - const curvePoints = this.getCurve(); - const startPoint = this.getPointAt(start); - let startIndex = this.getPreviousPointIndexAt(start); - const endPoint = this.getPointAt(end); - const endIndex = this.getPreviousPointIndexAt(end) + 1; - const slicePoints = []; - if (start !== 0.0) { - startIndex++; - slicePoints.push(startPoint); - } - slicePoints.push(...curvePoints.slice(startIndex, endIndex)); - if (end !== 1.0 || start === 1.0) { - slicePoints.push(endPoint); - } - return new Path3D(slicePoints, this.getNormalAt(start), this._raw, this._alignTangentsWithPath); - } - /** - * Forces the Path3D tangent, normal, binormal and distance recomputation. - * @param path path which all values are copied into the curves points - * @param firstNormal which should be projected onto the curve - * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path - * @returns the same object updated. - */ - update(path, firstNormal = null, alignTangentsWithPath = false) { - for (let p = 0; p < path.length; p++) { - this._curve[p].x = path[p].x; - this._curve[p].y = path[p].y; - this._curve[p].z = path[p].z; - } - this._compute(firstNormal, alignTangentsWithPath); - return this; - } - // private function compute() : computes tangents, normals and binormals - _compute(firstNormal, alignTangentsWithPath = false) { - const l = this._curve.length; - if (l < 2) { - return; - } - // first and last tangents - this._tangents[0] = this._getFirstNonNullVector(0); - if (!this._raw) { - this._tangents[0].normalize(); - } - this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]); - if (!this._raw) { - this._tangents[l - 1].normalize(); - } - // normals and binormals at first point : arbitrary vector with _normalVector() - const tg0 = this._tangents[0]; - const pp0 = this._normalVector(tg0, firstNormal); - this._normals[0] = pp0; - if (!this._raw) { - this._normals[0].normalize(); - } - this._binormals[0] = math_vector_Vector3.Cross(tg0, this._normals[0]); - if (!this._raw) { - this._binormals[0].normalize(); - } - this._distances[0] = 0.0; - // normals and binormals : next points - let prev; // previous vector (segment) - let cur; // current vector (segment) - let curTang; // current tangent - // previous normal - let prevNor; // previous normal - let prevBinor; // previous binormal - for (let i = 1; i < l; i++) { - // tangents - prev = this._getLastNonNullVector(i); - if (i < l - 1) { - cur = this._getFirstNonNullVector(i); - this._tangents[i] = alignTangentsWithPath ? cur : prev.add(cur); - this._tangents[i].normalize(); - } - this._distances[i] = this._distances[i - 1] + this._curve[i].subtract(this._curve[i - 1]).length(); - // normals and binormals - // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html - curTang = this._tangents[i]; - prevBinor = this._binormals[i - 1]; - this._normals[i] = math_vector_Vector3.Cross(prevBinor, curTang); - if (!this._raw) { - if (this._normals[i].length() === 0) { - prevNor = this._normals[i - 1]; - this._normals[i] = prevNor.clone(); - } - else { - this._normals[i].normalize(); - } - } - this._binormals[i] = math_vector_Vector3.Cross(curTang, this._normals[i]); - if (!this._raw) { - this._binormals[i].normalize(); - } - } - this._pointAtData.id = NaN; - } - // private function getFirstNonNullVector(index) - // returns the first non null vector from index : curve[index + N].subtract(curve[index]) - _getFirstNonNullVector(index) { - let i = 1; - let nNVector = this._curve[index + i].subtract(this._curve[index]); - while (nNVector.length() === 0 && index + i + 1 < this._curve.length) { - i++; - nNVector = this._curve[index + i].subtract(this._curve[index]); - } - return nNVector; - } - // private function getLastNonNullVector(index) - // returns the last non null vector from index : curve[index].subtract(curve[index - N]) - _getLastNonNullVector(index) { - let i = 1; - let nLVector = this._curve[index].subtract(this._curve[index - i]); - while (nLVector.length() === 0 && index > i + 1) { - i++; - nLVector = this._curve[index].subtract(this._curve[index - i]); - } - return nLVector; - } - // private function normalVector(v0, vt, va) : - // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane - // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0 - _normalVector(vt, va) { - let normal0; - let tgl = vt.length(); - if (tgl === 0.0) { - tgl = 1.0; - } - if (va === undefined || va === null) { - let point; - if (!math_scalar_Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, math_constants_Epsilon)) { - // search for a point in the plane - point = new math_vector_Vector3(0.0, -1.0, 0.0); - } - else if (!math_scalar_Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, math_constants_Epsilon)) { - point = new math_vector_Vector3(1.0, 0.0, 0.0); - } - else if (!math_scalar_Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, math_constants_Epsilon)) { - point = new math_vector_Vector3(0.0, 0.0, 1.0); - } - else { - point = math_vector_Vector3.Zero(); - } - normal0 = math_vector_Vector3.Cross(vt, point); - } - else { - normal0 = math_vector_Vector3.Cross(vt, va); - math_vector_Vector3.CrossToRef(normal0, vt, normal0); - } - normal0.normalize(); - return normal0; - } - /** - * Updates the point at data for an interpolated point along this curve - * @param position the position of the point along this curve, from 0.0 to 1.0 - * @param interpolateTNB - * @interpolateTNB whether to compute the interpolated tangent, normal and binormal - * @returns the (updated) point at data - */ - _updatePointAtData(position, interpolateTNB = false) { - // set an id for caching the result - if (this._pointAtData.id === position) { - if (!this._pointAtData.interpolateReady) { - this._updateInterpolationMatrix(); - } - return this._pointAtData; - } - else { - this._pointAtData.id = position; - } - const curvePoints = this.getPoints(); - // clamp position between 0.0 and 1.0 - if (position <= 0.0) { - return this._setPointAtData(0.0, 0.0, curvePoints[0], 0, interpolateTNB); - } - else if (position >= 1.0) { - return this._setPointAtData(1.0, 1.0, curvePoints[curvePoints.length - 1], curvePoints.length - 1, interpolateTNB); - } - let previousPoint = curvePoints[0]; - let currentPoint; - let currentLength = 0.0; - const targetLength = position * this.length(); - for (let i = 1; i < curvePoints.length; i++) { - currentPoint = curvePoints[i]; - const distance = math_vector_Vector3.Distance(previousPoint, currentPoint); - currentLength += distance; - if (currentLength === targetLength) { - return this._setPointAtData(position, 1.0, currentPoint, i, interpolateTNB); - } - else if (currentLength > targetLength) { - const toLength = currentLength - targetLength; - const diff = toLength / distance; - const dir = previousPoint.subtract(currentPoint); - const point = currentPoint.add(dir.scaleInPlace(diff)); - return this._setPointAtData(position, 1 - diff, point, i - 1, interpolateTNB); - } - previousPoint = currentPoint; - } - return this._pointAtData; - } - /** - * Updates the point at data from the specified parameters - * @param position where along the path the interpolated point is, from 0.0 to 1.0 - * @param subPosition - * @param point the interpolated point - * @param parentIndex the index of an existing curve point that is on, or else positionally the first behind, the interpolated point - * @param interpolateTNB - */ - _setPointAtData(position, subPosition, point, parentIndex, interpolateTNB) { - this._pointAtData.point = point; - this._pointAtData.position = position; - this._pointAtData.subPosition = subPosition; - this._pointAtData.previousPointArrayIndex = parentIndex; - this._pointAtData.interpolateReady = interpolateTNB; - if (interpolateTNB) { - this._updateInterpolationMatrix(); - } - return this._pointAtData; - } - /** - * Updates the point at interpolation matrix for the tangents, normals and binormals - */ - _updateInterpolationMatrix() { - this._pointAtData.interpolationMatrix = math_vector_Matrix.Identity(); - const parentIndex = this._pointAtData.previousPointArrayIndex; - if (parentIndex !== this._tangents.length - 1) { - const index = parentIndex + 1; - const tangentFrom = this._tangents[parentIndex].clone(); - const normalFrom = this._normals[parentIndex].clone(); - const binormalFrom = this._binormals[parentIndex].clone(); - const tangentTo = this._tangents[index].clone(); - const normalTo = this._normals[index].clone(); - const binormalTo = this._binormals[index].clone(); - const quatFrom = math_vector_Quaternion.RotationQuaternionFromAxis(normalFrom, binormalFrom, tangentFrom); - const quatTo = math_vector_Quaternion.RotationQuaternionFromAxis(normalTo, binormalTo, tangentTo); - const quatAt = math_vector_Quaternion.Slerp(quatFrom, quatTo, this._pointAtData.subPosition); - quatAt.toRotationMatrix(this._pointAtData.interpolationMatrix); - } - } -} -/** - * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space. - * A Curve3 is designed from a series of successive Vector3. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves - */ -class Curve3 { - /** - * Returns a Curve3 object along a Quadratic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#quadratic-bezier-curve - * @param v0 (Vector3) the origin point of the Quadratic Bezier - * @param v1 (Vector3) the control point - * @param v2 (Vector3) the end point of the Quadratic Bezier - * @param nbPoints (integer) the wanted number of points in the curve - * @returns the created Curve3 - */ - static CreateQuadraticBezier(v0, v1, v2, nbPoints) { - nbPoints = nbPoints > 2 ? nbPoints : 3; - const bez = new Array(); - const equation = (t, val0, val1, val2) => { - const res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2; - return res; - }; - for (let i = 0; i <= nbPoints; i++) { - bez.push(new math_vector_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))); - } - return new Curve3(bez); - } - /** - * Returns a Curve3 object along a Cubic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#cubic-bezier-curve - * @param v0 (Vector3) the origin point of the Cubic Bezier - * @param v1 (Vector3) the first control point - * @param v2 (Vector3) the second control point - * @param v3 (Vector3) the end point of the Cubic Bezier - * @param nbPoints (integer) the wanted number of points in the curve - * @returns the created Curve3 - */ - static CreateCubicBezier(v0, v1, v2, v3, nbPoints) { - nbPoints = nbPoints > 3 ? nbPoints : 4; - const bez = new Array(); - const equation = (t, val0, val1, val2, val3) => { - 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; - return res; - }; - for (let i = 0; i <= nbPoints; i++) { - bez.push(new math_vector_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))); - } - return new Curve3(bez); - } - /** - * Returns a Curve3 object along a Hermite Spline curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#hermite-spline - * @param p1 (Vector3) the origin point of the Hermite Spline - * @param t1 (Vector3) the tangent vector at the origin point - * @param p2 (Vector3) the end point of the Hermite Spline - * @param t2 (Vector3) the tangent vector at the end point - * @param nSeg (integer) the number of curve segments or nSeg + 1 points in the array - * @returns the created Curve3 - */ - static CreateHermiteSpline(p1, t1, p2, t2, nSeg) { - const hermite = new Array(); - const step = 1.0 / nSeg; - for (let i = 0; i <= nSeg; i++) { - hermite.push(math_vector_Vector3.Hermite(p1, t1, p2, t2, i * step)); - } - return new Curve3(hermite); - } - /** - * Returns a Curve3 object along a CatmullRom Spline curve : - * @param points (array of Vector3) the points the spline must pass through. At least, four points required - * @param nbPoints (integer) the wanted number of points between each curve control points - * @param closed (boolean) optional with default false, when true forms a closed loop from the points - * @returns the created Curve3 - */ - static CreateCatmullRomSpline(points, nbPoints, closed) { - const catmullRom = new Array(); - const step = 1.0 / nbPoints; - let amount = 0.0; - if (closed) { - const pointsCount = points.length; - for (let i = 0; i < pointsCount; i++) { - amount = 0; - for (let c = 0; c < nbPoints; c++) { - catmullRom.push(math_vector_Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount)); - amount += step; - } - } - catmullRom.push(catmullRom[0]); - } - else { - const totalPoints = new Array(); - totalPoints.push(points[0].clone()); - Array.prototype.push.apply(totalPoints, points); - totalPoints.push(points[points.length - 1].clone()); - let i = 0; - for (; i < totalPoints.length - 3; i++) { - amount = 0; - for (let c = 0; c < nbPoints; c++) { - catmullRom.push(math_vector_Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount)); - amount += step; - } - } - i--; - catmullRom.push(math_vector_Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount)); - } - return new Curve3(catmullRom); - } - /** - * Returns a Curve3 object along an arc through three vector3 points: - * The three points should not be colinear. When they are the Curve3 is empty. - * @param first (Vector3) the first point the arc must pass through. - * @param second (Vector3) the second point the arc must pass through. - * @param third (Vector3) the third point the arc must pass through. - * @param steps (number) the larger the number of steps the more detailed the arc. - * @param closed (boolean) optional with default false, when true forms the chord from the first and third point - * @param fullCircle Circle (boolean) optional with default false, when true forms the complete circle through the three points - * @returns the created Curve3 - */ - static ArcThru3Points(first, second, third, steps = 32, closed = false, fullCircle = false) { - const arc = new Array(); - const vec1 = second.subtract(first); - const vec2 = third.subtract(second); - const vec3 = first.subtract(third); - const zAxis = math_vector_Vector3.Cross(vec1, vec2); - const len4 = zAxis.length(); - if (len4 < Math.pow(10, -8)) { - return new Curve3(arc); // colinear points arc is empty - } - const len1_sq = vec1.lengthSquared(); - const len2_sq = vec2.lengthSquared(); - const len3_sq = vec3.lengthSquared(); - const len4_sq = zAxis.lengthSquared(); - const len1 = vec1.length(); - const len2 = vec2.length(); - const len3 = vec3.length(); - const radius = (0.5 * len1 * len2 * len3) / len4; - const dot1 = math_vector_Vector3.Dot(vec1, vec3); - const dot2 = math_vector_Vector3.Dot(vec1, vec2); - const dot3 = math_vector_Vector3.Dot(vec2, vec3); - const a = (-0.5 * len2_sq * dot1) / len4_sq; - const b = (-0.5 * len3_sq * dot2) / len4_sq; - const c = (-0.5 * len1_sq * dot3) / len4_sq; - const center = first.scale(a).add(second.scale(b)).add(third.scale(c)); - const radiusVec = first.subtract(center); - const xAxis = radiusVec.normalize(); - const yAxis = math_vector_Vector3.Cross(zAxis, xAxis).normalize(); - if (fullCircle) { - const dStep = (2 * Math.PI) / steps; - for (let theta = 0; theta <= 2 * Math.PI; theta += dStep) { - arc.push(center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta))))); - } - arc.push(first); - } - else { - const dStep = 1 / steps; - let theta = 0; - let point = math_vector_Vector3.Zero(); - do { - point = center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta)))); - arc.push(point); - theta += dStep; - } while (!point.equalsWithEpsilon(third, radius * dStep * 1.1)); - arc.push(third); - if (closed) { - arc.push(first); - } - } - return new Curve3(arc); - } - /** - * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space. - * A Curve3 is designed from a series of successive Vector3. - * Tuto : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#curve3-object - * @param points points which make up the curve - */ - constructor(points) { - this._length = 0.0; - this._points = points; - this._length = this._computeLength(points); - } - /** - * @returns the Curve3 stored array of successive Vector3 - */ - getPoints() { - return this._points; - } - /** - * @returns the computed length (float) of the curve. - */ - length() { - return this._length; - } - /** - * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB); - * This new Curve3 is built by translating and sticking the curveB at the end of the curveA. - * curveA and curveB keep unchanged. - * @param curve the curve to continue from this curve - * @returns the newly constructed curve - */ - continue(curve) { - const lastPoint = this._points[this._points.length - 1]; - const continuedPoints = this._points.slice(); - const curvePoints = curve.getPoints(); - for (let i = 1; i < curvePoints.length; i++) { - continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint)); - } - const continuedCurve = new Curve3(continuedPoints); - return continuedCurve; - } - _computeLength(path) { - let l = 0; - for (let i = 1; i < path.length; i++) { - l += path[i].subtract(path[i - 1]).length(); - } - return l; - } -} -//# sourceMappingURL=math.path.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/easing.js - -/** - * Base class used for every default easing function. - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class EasingFunction { - constructor() { - this._easingMode = EasingFunction.EASINGMODE_EASEIN; - } - /** - * Sets the easing mode of the current function. - * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT) - */ - setEasingMode(easingMode) { - const n = Math.min(Math.max(easingMode, 0), 2); - this._easingMode = n; - } - /** - * Gets the current easing mode. - * @returns the easing mode - */ - getEasingMode() { - return this._easingMode; - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - easeInCore(gradient) { - throw new Error("You must implement this method"); - } - /** - * Given an input gradient between 0 and 1, this returns the corresponding value - * of the easing function. - * @param gradient Defines the value between 0 and 1 we want the easing value for - * @returns the corresponding value on the curve defined by the easing function - */ - ease(gradient) { - switch (this._easingMode) { - case EasingFunction.EASINGMODE_EASEIN: - return this.easeInCore(gradient); - case EasingFunction.EASINGMODE_EASEOUT: - return 1 - this.easeInCore(1 - gradient); - } - if (gradient >= 0.5) { - return (1 - this.easeInCore((1 - gradient) * 2)) * 0.5 + 0.5; - } - return this.easeInCore(gradient * 2) * 0.5; - } -} -/** - * Interpolation follows the mathematical formula associated with the easing function. - */ -EasingFunction.EASINGMODE_EASEIN = 0; -/** - * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function. - */ -EasingFunction.EASINGMODE_EASEOUT = 1; -/** - * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half. - */ -EasingFunction.EASINGMODE_EASEINOUT = 2; -/** - * Easing function with a circle shape (see link below). - * @see https://easings.net/#easeInCirc - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class CircleEase extends EasingFunction { - /** - * @internal - */ - easeInCore(gradient) { - gradient = Math.max(0, Math.min(1, gradient)); - return 1.0 - Math.sqrt(1.0 - gradient * gradient); - } -} -/** - * Easing function with a ease back shape (see link below). - * @see https://easings.net/#easeInBack - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class BackEase extends EasingFunction { - /** - * Instantiates a back ease easing - * @see https://easings.net/#easeInBack - * @param amplitude Defines the amplitude of the function - */ - constructor( - /** Defines the amplitude of the function */ - amplitude = 1) { - super(); - this.amplitude = amplitude; - } - /** - * @internal - */ - easeInCore(gradient) { - const num = Math.max(0, this.amplitude); - return Math.pow(gradient, 3.0) - gradient * num * Math.sin(3.1415926535897931 * gradient); - } -} -/** - * Easing function with a bouncing shape (see link below). - * @see https://easings.net/#easeInBounce - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class BounceEase extends (/* unused pure expression or super */ null && (EasingFunction)) { - /** - * Instantiates a bounce easing - * @see https://easings.net/#easeInBounce - * @param bounces Defines the number of bounces - * @param bounciness Defines the amplitude of the bounce - */ - constructor( - /** Defines the number of bounces */ - bounces = 3, - /** Defines the amplitude of the bounce */ - bounciness = 2) { - super(); - this.bounces = bounces; - this.bounciness = bounciness; - } - /** - * @internal - */ - easeInCore(gradient) { - const y = Math.max(0.0, this.bounces); - let bounciness = this.bounciness; - if (bounciness <= 1.0) { - bounciness = 1.001; - } - const num9 = Math.pow(bounciness, y); - const num5 = 1.0 - bounciness; - const num4 = (1.0 - num9) / num5 + num9 * 0.5; - const num15 = gradient * num4; - const num65 = Math.log(-num15 * (1.0 - bounciness) + 1.0) / Math.log(bounciness); - const num3 = Math.floor(num65); - const num13 = num3 + 1.0; - const num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4); - const num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4); - const num7 = (num8 + num12) * 0.5; - const num6 = gradient - num7; - const num2 = num7 - num8; - return (-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2) * (num6 + num2); - } -} -/** - * Easing function with a power of 3 shape (see link below). - * @see https://easings.net/#easeInCubic - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class CubicEase extends (/* unused pure expression or super */ null && (EasingFunction)) { - /** - * @internal - */ - easeInCore(gradient) { - return gradient * gradient * gradient; - } -} -/** - * Easing function with an elastic shape (see link below). - * @see https://easings.net/#easeInElastic - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class ElasticEase extends (/* unused pure expression or super */ null && (EasingFunction)) { - /** - * Instantiates an elastic easing function - * @see https://easings.net/#easeInElastic - * @param oscillations Defines the number of oscillations - * @param springiness Defines the amplitude of the oscillations - */ - constructor( - /** Defines the number of oscillations*/ - oscillations = 3, - /** Defines the amplitude of the oscillations*/ - springiness = 3) { - super(); - this.oscillations = oscillations; - this.springiness = springiness; - } - /** - * @internal - */ - easeInCore(gradient) { - let num2; - const num3 = Math.max(0.0, this.oscillations); - const num = Math.max(0.0, this.springiness); - if (num == 0) { - num2 = gradient; - } - else { - num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0); - } - return num2 * Math.sin((6.2831853071795862 * num3 + 1.5707963267948966) * gradient); - } -} -/** - * Easing function with an exponential shape (see link below). - * @see https://easings.net/#easeInExpo - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class ExponentialEase extends EasingFunction { - /** - * Instantiates an exponential easing function - * @see https://easings.net/#easeInExpo - * @param exponent Defines the exponent of the function - */ - constructor( - /** Defines the exponent of the function */ - exponent = 2) { - super(); - this.exponent = exponent; - } - /** - * @internal - */ - easeInCore(gradient) { - if (this.exponent <= 0) { - return gradient; - } - return (Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0); - } -} -/** - * Easing function with a power shape (see link below). - * @see https://easings.net/#easeInQuad - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class PowerEase extends (/* unused pure expression or super */ null && (EasingFunction)) { - /** - * Instantiates an power base easing function - * @see https://easings.net/#easeInQuad - * @param power Defines the power of the function - */ - constructor( - /** Defines the power of the function */ - power = 2) { - super(); - this.power = power; - } - /** - * @internal - */ - easeInCore(gradient) { - const y = Math.max(0.0, this.power); - return Math.pow(gradient, y); - } -} -/** - * Easing function with a power of 2 shape (see link below). - * @see https://easings.net/#easeInQuad - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class QuadraticEase extends EasingFunction { - /** - * @internal - */ - easeInCore(gradient) { - return gradient * gradient; - } -} -/** - * Easing function with a power of 4 shape (see link below). - * @see https://easings.net/#easeInQuart - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class QuarticEase extends (/* unused pure expression or super */ null && (EasingFunction)) { - /** - * @internal - */ - easeInCore(gradient) { - return gradient * gradient * gradient * gradient; - } -} -/** - * Easing function with a power of 5 shape (see link below). - * @see https://easings.net/#easeInQuint - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class QuinticEase extends (/* unused pure expression or super */ null && (EasingFunction)) { - /** - * @internal - */ - easeInCore(gradient) { - return gradient * gradient * gradient * gradient * gradient; - } -} -/** - * Easing function with a sin shape (see link below). - * @see https://easings.net/#easeInSine - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class SineEase extends EasingFunction { - /** - * @internal - */ - easeInCore(gradient) { - return 1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)); - } -} -/** - * Easing function with a bezier shape (see link below). - * @see http://cubic-bezier.com/#.17,.67,.83,.67 - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions - */ -class BezierCurveEase extends (/* unused pure expression or super */ null && (EasingFunction)) { - /** - * Instantiates a bezier function - * @see http://cubic-bezier.com/#.17,.67,.83,.67 - * @param x1 Defines the x component of the start tangent in the bezier curve - * @param y1 Defines the y component of the start tangent in the bezier curve - * @param x2 Defines the x component of the end tangent in the bezier curve - * @param y2 Defines the y component of the end tangent in the bezier curve - */ - constructor( - /** Defines the x component of the start tangent in the bezier curve */ - x1 = 0, - /** Defines the y component of the start tangent in the bezier curve */ - y1 = 0, - /** Defines the x component of the end tangent in the bezier curve */ - x2 = 1, - /** Defines the y component of the end tangent in the bezier curve */ - y2 = 1) { - super(); - this.x1 = x1; - this.y1 = y1; - this.x2 = x2; - this.y2 = y2; - } - /** - * @internal - */ - easeInCore(gradient) { - return BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2); - } -} -//# sourceMappingURL=easing.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/animationEvent.js -/** - * Composed of a frame, and an action function - */ -class AnimationEvent { - /** - * Initializes the animation event - * @param frame The frame for which the event is triggered - * @param action The event to perform when triggered - * @param onlyOnce Specifies if the event should be triggered only once - */ - constructor( - /** The frame for which the event is triggered **/ - frame, - /** The event to perform when triggered **/ - action, - /** Specifies if the event should be triggered only once**/ - onlyOnce) { - this.frame = frame; - this.action = action; - this.onlyOnce = onlyOnce; - /** - * Specifies if the animation event is done - */ - this.isDone = false; - } - /** @internal */ - _clone() { - return new AnimationEvent(this.frame, this.action, this.onlyOnce); - } -} -//# sourceMappingURL=animationEvent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/animationGroup.js - - - - -/** - * This class defines the direct association between an animation and a target - */ -class TargetedAnimation { - /** - * Returns the string "TargetedAnimation" - * @returns "TargetedAnimation" - */ - getClassName() { - return "TargetedAnimation"; - } - /** - * Serialize the object - * @returns the JSON object representing the current entity - */ - serialize() { - const serializationObject = {}; - serializationObject.animation = this.animation.serialize(); - serializationObject.targetId = this.target.id; - return serializationObject; - } -} -/** - * Use this class to create coordinated animations on multiple targets - */ -class AnimationGroup { - /** - * Makes sure that the animations are either played or stopped according to the animation group mask. - * Note however that the call won't have any effect if the animation group has not been started yet. - * You should call this function if you modify the mask after the animation group has been started. - */ - syncWithMask() { - if (!this.mask) { - return; - } - for (let i = 0; i < this._animatables.length; ++i) { - const animatable = this._animatables[i]; - if (this.mask.retainsTarget(animatable.target.name)) { - if (animatable.paused) { - animatable.restart(); - } - } - else { - if (!animatable.paused) { - animatable.pause(); - } - } - } - } - /** - * Removes all animations for the targets not retained by the animation group mask. - * Use this function if you know you won't need those animations anymore and if you want to free memory. - */ - removeUnmaskedAnimations() { - if (!this.mask) { - return; - } - // Removes all animatables (in case the animation group has already been started) - for (let i = 0; i < this._animatables.length; ++i) { - const animatable = this._animatables[i]; - if (!this.mask.retainsTarget(animatable.target.name)) { - animatable.stop(); - this._animatables.splice(i, 1); - --i; - } - } - // Removes the targeted animations - for (let index = 0; index < this._targetedAnimations.length; index++) { - const targetedAnimation = this._targetedAnimations[index]; - if (!this.mask.retainsTarget(targetedAnimation.target.name)) { - this._targetedAnimations.splice(index, 1); - --index; - } - } - } - /** - * Gets the first frame - */ - get from() { - return this._from; - } - /** - * Gets the last frame - */ - get to() { - return this._to; - } - /** - * Define if the animations are started - */ - get isStarted() { - return this._isStarted; - } - /** - * Gets a value indicating that the current group is playing - */ - get isPlaying() { - return this._isStarted && !this._isPaused; - } - /** - * Gets or sets the speed ratio to use for all animations - */ - get speedRatio() { - return this._speedRatio; - } - /** - * Gets or sets the speed ratio to use for all animations - */ - set speedRatio(value) { - if (this._speedRatio === value) { - return; - } - this._speedRatio = value; - for (let index = 0; index < this._animatables.length; index++) { - const animatable = this._animatables[index]; - animatable.speedRatio = this._speedRatio; - } - } - /** - * Gets or sets if all animations should loop or not - */ - get loopAnimation() { - return this._loopAnimation; - } - set loopAnimation(value) { - if (this._loopAnimation === value) { - return; - } - this._loopAnimation = value; - for (let index = 0; index < this._animatables.length; index++) { - const animatable = this._animatables[index]; - animatable.loopAnimation = this._loopAnimation; - } - } - /** - * Gets or sets if all animations should be evaluated additively - */ - get isAdditive() { - return this._isAdditive; - } - set isAdditive(value) { - if (this._isAdditive === value) { - return; - } - this._isAdditive = value; - for (let index = 0; index < this._animatables.length; index++) { - const animatable = this._animatables[index]; - animatable.isAdditive = this._isAdditive; - } - } - /** - * Gets or sets the weight to apply to all animations of the group - */ - get weight() { - return this._weight; - } - set weight(value) { - if (this._weight === value) { - return; - } - this._weight = value; - this.setWeightForAllAnimatables(this._weight); - } - /** - * Gets the targeted animations for this animation group - */ - get targetedAnimations() { - return this._targetedAnimations; - } - /** - * returning the list of animatables controlled by this animation group. - */ - get animatables() { - return this._animatables; - } - /** - * Gets the list of target animations - */ - get children() { - return this._targetedAnimations; - } - /** - * Gets or sets the order of play of the animation group (default: 0) - */ - get playOrder() { - return this._playOrder; - } - set playOrder(value) { - if (this._playOrder === value) { - return; - } - this._playOrder = value; - if (this._animatables.length > 0) { - for (let i = 0; i < this._animatables.length; i++) { - this._animatables[i].playOrder = this._playOrder; - } - this._scene.sortActiveAnimatables(); - } - } - /** - * Allows the animations of the animation group to blend with current running animations - * Note: this method should be called after all targeted animations have been added to the group - * @param blendingSpeed defines the blending speed to use - */ - enableBlending(blendingSpeed) { - for (let i = 0; i < this._targetedAnimations.length; ++i) { - this._targetedAnimations[i].animation.enableBlending = true; - this._targetedAnimations[i].animation.blendingSpeed = blendingSpeed; - } - } - /** - * Disable animation blending - */ - disableBlending() { - for (let i = 0; i < this._targetedAnimations.length; ++i) { - this._targetedAnimations[i].animation.enableBlending = false; - } - } - /** - * Merge the array of animation groups into a new animation group - * @param animationGroups List of animation groups to merge - * @param disposeSource If true, animation groups will be disposed after being merged (default: true) - * @param normalize If true, animation groups will be normalized before being merged, so that all animations have the same "from" and "to" frame (default: false) - * @param weight Weight for the new animation group. If not provided, it will inherit the weight from the first animation group of the array - * @returns The new animation group or null if no animation groups were passed - */ - static MergeAnimationGroups(animationGroups, disposeSource = true, normalize = false, weight) { - if (animationGroups.length === 0) { - return null; - } - weight = weight !== null && weight !== void 0 ? weight : animationGroups[0].weight; - let beginFrame = Number.MAX_VALUE; - let endFrame = Number.MIN_VALUE; - if (normalize) { - for (const animationGroup of animationGroups) { - if (animationGroup.from < beginFrame) { - beginFrame = animationGroup.from; - } - if (animationGroup.to > endFrame) { - endFrame = animationGroup.to; - } - } - } - const mergedAnimationGroup = new AnimationGroup(animationGroups[0].name + "_merged", animationGroups[0]._scene, weight); - for (const animationGroup of animationGroups) { - if (normalize) { - animationGroup.normalize(beginFrame, endFrame); - } - for (const targetedAnimation of animationGroup.targetedAnimations) { - mergedAnimationGroup.addTargetedAnimation(targetedAnimation.animation, targetedAnimation.target); - } - if (disposeSource) { - animationGroup.dispose(); - } - } - return mergedAnimationGroup; - } - /** - * Instantiates a new Animation Group. - * This helps managing several animations at once. - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations - * @param name Defines the name of the group - * @param scene Defines the scene the group belongs to - * @param weight Defines the weight to use for animations in the group (-1.0 by default, meaning "no weight") - * @param playOrder Defines the order of play of the animation group (default is 0) - */ - constructor( - /** The name of the animation group */ - name, scene = null, weight = -1, playOrder = 0) { - this.name = name; - this._targetedAnimations = new Array(); - this._animatables = new Array(); - this._from = Number.MAX_VALUE; - this._to = -Number.MAX_VALUE; - this._speedRatio = 1; - this._loopAnimation = false; - this._isAdditive = false; - this._weight = -1; - this._playOrder = 0; - /** @internal */ - this._parentContainer = null; - /** - * This observable will notify when one animation have ended - */ - this.onAnimationEndObservable = new observable_Observable(); - /** - * Observer raised when one animation loops - */ - this.onAnimationLoopObservable = new observable_Observable(); - /** - * Observer raised when all animations have looped - */ - this.onAnimationGroupLoopObservable = new observable_Observable(); - /** - * This observable will notify when all animations have ended. - */ - this.onAnimationGroupEndObservable = new observable_Observable(); - /** - * This observable will notify when all animations have paused. - */ - this.onAnimationGroupPauseObservable = new observable_Observable(); - /** - * This observable will notify when all animations are playing. - */ - this.onAnimationGroupPlayObservable = new observable_Observable(); - /** - * Gets or sets an object used to store user defined information for the node - */ - this.metadata = null; - this._animationLoopFlags = []; - this._scene = scene || engineStore_EngineStore.LastCreatedScene; - this._weight = weight; - this._playOrder = playOrder; - this.uniqueId = this._scene.getUniqueId(); - this._scene.addAnimationGroup(this); - } - /** - * Add an animation (with its target) in the group - * @param animation defines the animation we want to add - * @param target defines the target of the animation - * @returns the TargetedAnimation object - */ - addTargetedAnimation(animation, target) { - const targetedAnimation = new TargetedAnimation(); - targetedAnimation.animation = animation; - targetedAnimation.target = target; - const keys = animation.getKeys(); - if (this._from > keys[0].frame) { - this._from = keys[0].frame; - } - if (this._to < keys[keys.length - 1].frame) { - this._to = keys[keys.length - 1].frame; - } - this._targetedAnimations.push(targetedAnimation); - return targetedAnimation; - } - /** - * Remove an animation from the group - * @param animation defines the animation we want to remove - */ - removeTargetedAnimation(animation) { - for (let index = this._targetedAnimations.length - 1; index > -1; index--) { - const targetedAnimation = this._targetedAnimations[index]; - if (targetedAnimation.animation === animation) { - this._targetedAnimations.splice(index, 1); - } - } - } - /** - * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame - * It can add constant keys at begin or end - * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null) - * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null) - * @returns the animation group - */ - normalize(beginFrame = null, endFrame = null) { - if (beginFrame == null) { - beginFrame = this._from; - } - if (endFrame == null) { - endFrame = this._to; - } - for (let index = 0; index < this._targetedAnimations.length; index++) { - const targetedAnimation = this._targetedAnimations[index]; - const keys = targetedAnimation.animation.getKeys(); - const startKey = keys[0]; - const endKey = keys[keys.length - 1]; - if (startKey.frame > beginFrame) { - const newKey = { - frame: beginFrame, - value: startKey.value, - inTangent: startKey.inTangent, - outTangent: startKey.outTangent, - interpolation: startKey.interpolation, - }; - keys.splice(0, 0, newKey); - } - if (endKey.frame < endFrame) { - const newKey = { - frame: endFrame, - value: endKey.value, - inTangent: endKey.inTangent, - outTangent: endKey.outTangent, - interpolation: endKey.interpolation, - }; - keys.push(newKey); - } - } - this._from = beginFrame; - this._to = endFrame; - return this; - } - _processLoop(animatable, targetedAnimation, index) { - animatable.onAnimationLoop = () => { - this.onAnimationLoopObservable.notifyObservers(targetedAnimation); - if (this._animationLoopFlags[index]) { - return; - } - this._animationLoopFlags[index] = true; - this._animationLoopCount++; - if (this._animationLoopCount === this._targetedAnimations.length) { - this.onAnimationGroupLoopObservable.notifyObservers(this); - this._animationLoopCount = 0; - this._animationLoopFlags.length = 0; - } - }; - } - /** - * Start all animations on given targets - * @param loop defines if animations must loop - * @param speedRatio defines the ratio to apply to animation speed (1 by default) - * @param from defines the from key (optional) - * @param to defines the to key (optional) - * @param isAdditive defines the additive state for the resulting animatables (optional) - * @returns the current animation group - */ - start(loop = false, speedRatio = 1, from, to, isAdditive) { - if (this._isStarted || this._targetedAnimations.length === 0) { - return this; - } - this._loopAnimation = loop; - this._animationLoopCount = 0; - this._animationLoopFlags.length = 0; - for (let index = 0; index < this._targetedAnimations.length; index++) { - const targetedAnimation = this._targetedAnimations[index]; - 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); - animatable.weight = this._weight; - animatable.playOrder = this._playOrder; - animatable.onAnimationEnd = () => { - this.onAnimationEndObservable.notifyObservers(targetedAnimation); - this._checkAnimationGroupEnded(animatable); - }; - this._processLoop(animatable, targetedAnimation, index); - this._animatables.push(animatable); - } - this.syncWithMask(); - this._scene.sortActiveAnimatables(); - this._speedRatio = speedRatio; - this._isStarted = true; - this._isPaused = false; - this.onAnimationGroupPlayObservable.notifyObservers(this); - return this; - } - /** - * Pause all animations - * @returns the animation group - */ - pause() { - if (!this._isStarted) { - return this; - } - this._isPaused = true; - for (let index = 0; index < this._animatables.length; index++) { - const animatable = this._animatables[index]; - animatable.pause(); - } - this.onAnimationGroupPauseObservable.notifyObservers(this); - return this; - } - /** - * Play all animations to initial state - * This function will start() the animations if they were not started or will restart() them if they were paused - * @param loop defines if animations must loop - * @returns the animation group - */ - play(loop) { - // only if all animatables are ready and exist - if (this.isStarted && this._animatables.length === this._targetedAnimations.length) { - if (loop !== undefined) { - this.loopAnimation = loop; - } - this.restart(); - } - else { - this.stop(); - this.start(loop, this._speedRatio); - } - this._isPaused = false; - return this; - } - /** - * Reset all animations to initial state - * @returns the animation group - */ - reset() { - if (!this._isStarted) { - this.play(); - this.goToFrame(0); - this.stop(); - return this; - } - for (let index = 0; index < this._animatables.length; index++) { - const animatable = this._animatables[index]; - animatable.reset(); - } - return this; - } - /** - * Restart animations from key 0 - * @returns the animation group - */ - restart() { - if (!this._isStarted) { - return this; - } - for (let index = 0; index < this._animatables.length; index++) { - const animatable = this._animatables[index]; - animatable.restart(); - } - this.onAnimationGroupPlayObservable.notifyObservers(this); - return this; - } - /** - * Stop all animations - * @returns the animation group - */ - stop() { - if (!this._isStarted) { - return this; - } - const list = this._animatables.slice(); - for (let index = 0; index < list.length; index++) { - list[index].stop(undefined, undefined, true); - } - // We will take care of removing all stopped animatables - let curIndex = 0; - for (let index = 0; index < this._scene._activeAnimatables.length; index++) { - const animatable = this._scene._activeAnimatables[index]; - if (animatable._runtimeAnimations.length > 0) { - this._scene._activeAnimatables[curIndex++] = animatable; - } - } - this._scene._activeAnimatables.length = curIndex; - this._isStarted = false; - return this; - } - /** - * Set animation weight for all animatables - * - * @since 6.12.4 - * You can pass the weight to the AnimationGroup constructor, or use the weight property to set it after the group has been created, - * making it easier to define the overall animation weight than calling setWeightForAllAnimatables() after the animation group has been started - * @param weight defines the weight to use - * @returns the animationGroup - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-weights - */ - setWeightForAllAnimatables(weight) { - for (let index = 0; index < this._animatables.length; index++) { - const animatable = this._animatables[index]; - animatable.weight = weight; - } - return this; - } - /** - * Synchronize and normalize all animatables with a source animatable - * @param root defines the root animatable to synchronize with (null to stop synchronizing) - * @returns the animationGroup - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-weights - */ - syncAllAnimationsWith(root) { - for (let index = 0; index < this._animatables.length; index++) { - const animatable = this._animatables[index]; - animatable.syncWith(root); - } - return this; - } - /** - * Goes to a specific frame in this animation group - * @param frame the frame number to go to - * @returns the animationGroup - */ - goToFrame(frame) { - if (!this._isStarted) { - return this; - } - for (let index = 0; index < this._animatables.length; index++) { - const animatable = this._animatables[index]; - animatable.goToFrame(frame); - } - return this; - } - /** - * Dispose all associated resources - */ - dispose() { - this._targetedAnimations.length = 0; - this._animatables.length = 0; - // Remove from scene - const index = this._scene.animationGroups.indexOf(this); - if (index > -1) { - this._scene.animationGroups.splice(index, 1); - } - if (this._parentContainer) { - const index = this._parentContainer.animationGroups.indexOf(this); - if (index > -1) { - this._parentContainer.animationGroups.splice(index, 1); - } - this._parentContainer = null; - } - this.onAnimationEndObservable.clear(); - this.onAnimationGroupEndObservable.clear(); - this.onAnimationGroupPauseObservable.clear(); - this.onAnimationGroupPlayObservable.clear(); - this.onAnimationLoopObservable.clear(); - this.onAnimationGroupLoopObservable.clear(); - } - _checkAnimationGroupEnded(animatable) { - // animatable should be taken out of the array - const idx = this._animatables.indexOf(animatable); - if (idx > -1) { - this._animatables.splice(idx, 1); - } - // all animatables were removed? animation group ended! - if (this._animatables.length === 0) { - this._isStarted = false; - this.onAnimationGroupEndObservable.notifyObservers(this); - } - } - /** - * Clone the current animation group and returns a copy - * @param newName defines the name of the new group - * @param targetConverter defines an optional function used to convert current animation targets to new ones - * @param cloneAnimations defines if the animations should be cloned or referenced - * @returns the new animation group - */ - clone(newName, targetConverter, cloneAnimations = false) { - const newGroup = new AnimationGroup(newName || this.name, this._scene); - for (const targetAnimation of this._targetedAnimations) { - newGroup.addTargetedAnimation(cloneAnimations ? targetAnimation.animation.clone() : targetAnimation.animation, targetConverter ? targetConverter(targetAnimation.target) : targetAnimation.target); - } - return newGroup; - } - /** - * Serializes the animationGroup to an object - * @returns Serialized object - */ - serialize() { - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.from = this.from; - serializationObject.to = this.to; - serializationObject.targetedAnimations = []; - for (let targetedAnimationIndex = 0; targetedAnimationIndex < this.targetedAnimations.length; targetedAnimationIndex++) { - const targetedAnimation = this.targetedAnimations[targetedAnimationIndex]; - serializationObject.targetedAnimations[targetedAnimationIndex] = targetedAnimation.serialize(); - } - if (Tags && Tags.HasTags(this)) { - serializationObject.tags = Tags.GetTags(this); - } - // Metadata - if (this.metadata) { - serializationObject.metadata = this.metadata; - } - return serializationObject; - } - // Statics - /** - * Returns a new AnimationGroup object parsed from the source provided. - * @param parsedAnimationGroup defines the source - * @param scene defines the scene that will receive the animationGroup - * @returns a new AnimationGroup - */ - static Parse(parsedAnimationGroup, scene) { - const animationGroup = new AnimationGroup(parsedAnimationGroup.name, scene); - for (let i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) { - const targetedAnimation = parsedAnimationGroup.targetedAnimations[i]; - const animation = animation_Animation.Parse(targetedAnimation.animation); - const id = targetedAnimation.targetId; - if (targetedAnimation.animation.property === "influence") { - // morph target animation - const morphTarget = scene.getMorphTargetById(id); - if (morphTarget) { - animationGroup.addTargetedAnimation(animation, morphTarget); - } - } - else { - const targetNode = scene.getNodeById(id); - if (targetNode != null) { - animationGroup.addTargetedAnimation(animation, targetNode); - } - } - } - if (parsedAnimationGroup.from !== null && parsedAnimationGroup.to !== null) { - animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to); - } - if (Tags) { - Tags.AddTagsTo(animationGroup, parsedAnimationGroup.tags); - } - if (parsedAnimationGroup.metadata !== undefined) { - animationGroup.metadata = parsedAnimationGroup.metadata; - } - return animationGroup; - } - /** - * Convert the keyframes for all animations belonging to the group to be relative to a given reference frame. - * @param sourceAnimationGroup defines the AnimationGroup containing animations to convert - * @param referenceFrame defines the frame that keyframes in the range will be relative to - * @param range defines the name of the AnimationRange belonging to the animations in the group to convert - * @param cloneOriginal defines whether or not to clone the group and convert the clone or convert the original group (default is false) - * @param clonedName defines the name of the resulting cloned AnimationGroup if cloneOriginal is true - * @returns a new AnimationGroup if cloneOriginal is true or the original AnimationGroup if cloneOriginal is false - */ - static MakeAnimationAdditive(sourceAnimationGroup, referenceFrame = 0, range, cloneOriginal = false, clonedName) { - let animationGroup = sourceAnimationGroup; - if (cloneOriginal) { - animationGroup = sourceAnimationGroup.clone(clonedName || animationGroup.name); - } - const targetedAnimations = animationGroup.targetedAnimations; - for (let index = 0; index < targetedAnimations.length; index++) { - const targetedAnimation = targetedAnimations[index]; - animation_Animation.MakeAnimationAdditive(targetedAnimation.animation, referenceFrame, range); - } - animationGroup.isAdditive = true; - return animationGroup; - } - /** - * Returns the string "AnimationGroup" - * @returns "AnimationGroup" - */ - getClassName() { - return "AnimationGroup"; - } - /** - * Creates a detailed string about the object - * @param fullDetails defines if the output string will support multiple levels of logging within scene loading - * @returns a string representing the object - */ - toString(fullDetails) { - let ret = "Name: " + this.name; - ret += ", type: " + this.getClassName(); - if (fullDetails) { - ret += ", from: " + this._from; - ret += ", to: " + this._to; - ret += ", isStarted: " + this._isStarted; - ret += ", speedRatio: " + this._speedRatio; - ret += ", targetedAnimations length: " + this._targetedAnimations.length; - ret += ", animatables length: " + this._animatables; - } - return ret; - } -} -//# sourceMappingURL=animationGroup.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/animatable.interface.js - -//# sourceMappingURL=animatable.interface.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/pathCursor.js - -/** - * A cursor which tracks a point on a path - */ -class PathCursor { - /** - * Initializes the path cursor - * @param _path The path to track - */ - constructor(_path) { - this._path = _path; - /** - * Stores path cursor callbacks for when an onchange event is triggered - */ - this._onchange = new Array(); - /** - * The value of the path cursor - */ - this.value = 0; - /** - * The animation array of the path cursor - */ - this.animations = new Array(); - } - /** - * Gets the cursor point on the path - * @returns A point on the path cursor at the cursor location - */ - getPoint() { - const point = this._path.getPointAtLengthPosition(this.value); - return new Vector3(point.x, 0, point.y); - } - /** - * Moves the cursor ahead by the step amount - * @param step The amount to move the cursor forward - * @returns This path cursor - */ - moveAhead(step = 0.002) { - this.move(step); - return this; - } - /** - * Moves the cursor behind by the step amount - * @param step The amount to move the cursor back - * @returns This path cursor - */ - moveBack(step = 0.002) { - this.move(-step); - return this; - } - /** - * Moves the cursor by the step amount - * If the step amount is greater than one, an exception is thrown - * @param step The amount to move the cursor - * @returns This path cursor - */ - move(step) { - if (Math.abs(step) > 1) { - throw "step size should be less than 1."; - } - this.value += step; - this._ensureLimits(); - this._raiseOnChange(); - return this; - } - /** - * Ensures that the value is limited between zero and one - * @returns This path cursor - */ - _ensureLimits() { - while (this.value > 1) { - this.value -= 1; - } - while (this.value < 0) { - this.value += 1; - } - return this; - } - /** - * Runs onchange callbacks on change (used by the animation engine) - * @returns This path cursor - */ - _raiseOnChange() { - this._onchange.forEach((f) => f(this)); - return this; - } - /** - * Executes a function on change - * @param f A path cursor onchange callback - * @returns This path cursor - */ - onchange(f) { - this._onchange.push(f); - return this; - } -} -//# sourceMappingURL=pathCursor.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/animationGroupMask.js -/** - * Enum used to define the mode for an animation group mask - */ -var AnimationGroupMaskMode; -(function (AnimationGroupMaskMode) { - /** - * The mask defines the animatable target names that should be included - */ - AnimationGroupMaskMode[AnimationGroupMaskMode["Include"] = 0] = "Include"; - /** - * The mask defines the animatable target names in a "exclude" mode: all animatable targets will be animated except the ones defined in the mask - */ - AnimationGroupMaskMode[AnimationGroupMaskMode["Exclude"] = 1] = "Exclude"; -})(AnimationGroupMaskMode || (AnimationGroupMaskMode = {})); -/** - * Defines a mask used to filter animation targets. - * If you apply a mask to an animation group (see the AnimationGroup.mask property), only the animations whose target names match the mask will play. - * Note that a target is defined by its name (string). This means that the same mask can be used for several animation groups, provided that their targets are named in the same way. - */ -class AnimationGroupMask { - /** - * Creates a new mask - * @param names The list of target names to add to the mask (optional) - * @param mode Defines the mode for the mask (default: AnimationGroupMaskMode.Include) - */ - constructor(names, - /** - * Defines the mode for the mask - */ - mode = AnimationGroupMaskMode.Include) { - this.mode = mode; - this._targetNames = new Set(); - if (names) { - this.addTargetName(names); - } - } - /** - * Adds one or several target names to the mask - * @param name The name(s) to add to the mask - */ - addTargetName(name) { - if (Array.isArray(name)) { - for (const n of name) { - this._targetNames.add(n); - } - return; - } - this._targetNames.add(name); - } - /** - * Removes one or several target names from the mask - * @param name The name(s) to remove from the mask - */ - removeTargetName(name) { - if (Array.isArray(name)) { - for (const n of name) { - this._targetNames.delete(n); - } - return; - } - this._targetNames.delete(name); - } - /** - * Checks if the mask includes a target name. - * This method is intended to know if a given target name is included in the mask, not if the name is actually retained by the mask (see retainsTarget() instead). - * @param name The name to check with the mask - * @returns True if the mask includes the name, false otherwise - */ - hasTarget(name) { - return this._targetNames.has(name); - } - /** - * Checks if the mask retains a target name. - * Note that in the "Exclude" mode, this will return false if the mask includes the name, and true otherwise! - * This method is intended to know if a given target name is retained by the mask, not if the name is in the list of target names. - * @param name The name to check with the mask - * @returns True if the mask retains the name, false otherwise - */ - retainsTarget(name) { - return this._targetNames.has(name) === (this.mode === AnimationGroupMaskMode.Include); - } -} -//# sourceMappingURL=animationGroupMask.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Animations/index.js - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/coroutine.js -/* eslint-disable @typescript-eslint/naming-convention */ -// "Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed." -// https://en.wikipedia.org/wiki/Coroutine -// 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. -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function inlineScheduler(coroutine, onStep, onError) { - try { - const step = coroutine.next(); - if (step.done) { - onStep(step); - } - else if (!step.value) { - // 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. - onStep(step); - } - else { - step.value.then(() => { - step.value = undefined; - onStep(step); - }, onError); - } - } - catch (error) { - onError(error); - } -} -// The yielding scheduler steps the coroutine synchronously until the specified time interval has elapsed, then yields control so other operations can be performed. -// A single instance of a yielding scheduler could be shared across multiple coroutines to yield when their collective work exceeds the threshold. -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function createYieldingScheduler(yieldAfterMS = 25) { - let startTime; - return (coroutine, onStep, onError) => { - const currentTime = performance.now(); - if (startTime === undefined || currentTime - startTime > yieldAfterMS) { - // 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. - startTime = currentTime; - setTimeout(() => { - inlineScheduler(coroutine, onStep, onError); - }, 0); - } - else { - // Otherwise it is not time to yield yet, so step the coroutine synchronously. - inlineScheduler(coroutine, onStep, onError); - } - }; -} -// Runs the specified coroutine with the specified scheduler. The success or error callback will be invoked when the coroutine finishes. -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function runCoroutine(coroutine, scheduler, onSuccess, onError, abortSignal) { - const resume = () => { - let reschedule; - const onStep = (stepResult) => { - if (stepResult.done) { - // If the coroutine is done, report success. - onSuccess(stepResult.value); - } - else { - // If the coroutine is not done, resume the coroutine (via the scheduler). - if (reschedule === undefined) { - // If reschedule is undefined at this point, then the coroutine must have stepped synchronously, so just flag another loop iteration. - reschedule = true; - } - else { - // If reschedule is defined at this point, then the coroutine must have stepped asynchronously, so call resume to restart the step loop. - resume(); - } - } - }; - do { - reschedule = undefined; - if (!abortSignal || !abortSignal.aborted) { - scheduler(coroutine, onStep, onError); - } - else { - onError(new Error("Aborted")); - } - if (reschedule === undefined) { - // If reschedule is undefined at this point, then the coroutine must have stepped asynchronously, so stop looping and let the coroutine be resumed later. - reschedule = false; - } - } while (reschedule); - }; - resume(); -} -// Runs the specified coroutine synchronously. -/** - * @internal - */ -function runCoroutineSync(coroutine, abortSignal) { - // 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). - let result; - runCoroutine(coroutine, inlineScheduler, (r) => (result = r), (e) => { - throw e; - }, abortSignal); - // Synchronously return the result of the coroutine. - return result; -} -// Runs the specified coroutine asynchronously with the specified scheduler. -/** - * @internal - */ -function runCoroutineAsync(coroutine, scheduler, abortSignal) { - // Run the coroutine with a yielding scheduler, resolving or rejecting the result promise when the coroutine finishes. - return new Promise((resolve, reject) => { - runCoroutine(coroutine, scheduler, resolve, reject, abortSignal); - }); -} -/** - * Given a function that returns a Coroutine<T>, produce a function with the same parameters that returns a T. - * The returned function runs the coroutine synchronously. - * @param coroutineFactory A function that returns a Coroutine<T>. - * @param abortSignal - * @returns A function that runs the coroutine synchronously. - * @internal - */ -function makeSyncFunction(coroutineFactory, abortSignal) { - return (...params) => { - // Run the coroutine synchronously. - return runCoroutineSync(coroutineFactory(...params), abortSignal); - }; -} -/** - * Given a function that returns a Coroutine<T>, product a function with the same parameters that returns a Promise<T>. - * The returned function runs the coroutine asynchronously, yield control of the execution context occasionally to enable a more responsive experience. - * @param coroutineFactory A function that returns a Coroutine<T>. - * @param scheduler - * @param abortSignal - * @returns A function that runs the coroutine asynchronously. - * @internal - */ -function makeAsyncFunction(coroutineFactory, scheduler, abortSignal) { - return (...params) => { - // Run the coroutine asynchronously. - return runCoroutineAsync(coroutineFactory(...params), scheduler, abortSignal); - }; -} -//# sourceMappingURL=coroutine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.viewport.js -/** - * Class used to represent a viewport on screen - */ -class math_viewport_Viewport { - /** - * Creates a Viewport object located at (x, y) and sized (width, height) - * @param x defines viewport left coordinate - * @param y defines viewport top coordinate - * @param width defines the viewport width - * @param height defines the viewport height - */ - constructor( - /** viewport left coordinate */ - x, - /** viewport top coordinate */ - y, - /**viewport width */ - width, - /** viewport height */ - height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - } - /** - * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1) - * @param renderWidth defines the rendering width - * @param renderHeight defines the rendering height - * @returns a new Viewport - */ - toGlobal(renderWidth, renderHeight) { - return new math_viewport_Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight); - } - /** - * Stores absolute viewport value into a target viewport (from 0-> width, 0-> height instead of 0->1) - * @param renderWidth defines the rendering width - * @param renderHeight defines the rendering height - * @param ref defines the target viewport - * @returns the current viewport - */ - toGlobalToRef(renderWidth, renderHeight, ref) { - ref.x = this.x * renderWidth; - ref.y = this.y * renderHeight; - ref.width = this.width * renderWidth; - ref.height = this.height * renderHeight; - return this; - } - /** - * Returns a new Viewport copied from the current one - * @returns a new Viewport - */ - clone() { - return new math_viewport_Viewport(this.x, this.y, this.width, this.height); - } -} -//# sourceMappingURL=math.viewport.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/camera.js - - - - - - - - - - - - - -/** - * This is the base class of all the camera used in the application. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras - */ -class camera_Camera extends node_Node { - /** - * Define the current local position of the camera in the scene - */ - get position() { - return this._position; - } - set position(newPosition) { - this._position = newPosition; - } - /** - * The vector the camera should consider as up. - * (default is Vector3(0, 1, 0) aka Vector3.Up()) - */ - set upVector(vec) { - this._upVector = vec; - } - get upVector() { - return this._upVector; - } - /** - * The screen area in scene units squared - */ - get screenArea() { - var _a, _b, _c, _d; - let x = 0; - let y = 0; - if (this.mode === camera_Camera.PERSPECTIVE_CAMERA) { - if (this.fovMode === camera_Camera.FOVMODE_VERTICAL_FIXED) { - y = this.minZ * 2 * Math.tan(this.fov / 2); - x = this.getEngine().getAspectRatio(this) * y; - } - else { - x = this.minZ * 2 * Math.tan(this.fov / 2); - y = x / this.getEngine().getAspectRatio(this); - } - } - else { - const halfWidth = this.getEngine().getRenderWidth() / 2.0; - const halfHeight = this.getEngine().getRenderHeight() / 2.0; - x = ((_a = this.orthoRight) !== null && _a !== void 0 ? _a : halfWidth) - ((_b = this.orthoLeft) !== null && _b !== void 0 ? _b : -halfWidth); - y = ((_c = this.orthoTop) !== null && _c !== void 0 ? _c : halfHeight) - ((_d = this.orthoBottom) !== null && _d !== void 0 ? _d : -halfHeight); - } - return x * y; - } - set orthoLeft(value) { - this._orthoLeft = value; - for (const rigCamera of this._rigCameras) { - rigCamera.orthoLeft = value; - } - } - get orthoLeft() { - return this._orthoLeft; - } - set orthoRight(value) { - this._orthoRight = value; - for (const rigCamera of this._rigCameras) { - rigCamera.orthoRight = value; - } - } - get orthoRight() { - return this._orthoRight; - } - set orthoBottom(value) { - this._orthoBottom = value; - for (const rigCamera of this._rigCameras) { - rigCamera.orthoBottom = value; - } - } - get orthoBottom() { - return this._orthoBottom; - } - set orthoTop(value) { - this._orthoTop = value; - for (const rigCamera of this._rigCameras) { - rigCamera.orthoTop = value; - } - } - get orthoTop() { - return this._orthoTop; - } - set mode(mode) { - this._mode = mode; - // Pass the mode down to the rig cameras - for (const rigCamera of this._rigCameras) { - rigCamera.mode = mode; - } - } - get mode() { - return this._mode; - } - /** - * Instantiates a new camera object. - * This should not be used directly but through the inherited cameras: ArcRotate, Free... - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras - * @param name Defines the name of the camera in the scene - * @param position Defines the position of the camera - * @param scene Defines the scene the camera belongs too - * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene - */ - constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) { - super(name, scene); - /** @internal */ - this._position = math_vector_Vector3.Zero(); - this._upVector = math_vector_Vector3.Up(); - /** - * Define the current limit on the left side for an orthographic camera - * In scene unit - */ - this._orthoLeft = null; - /** - * Define the current limit on the right side for an orthographic camera - * In scene unit - */ - this._orthoRight = null; - /** - * Define the current limit on the bottom side for an orthographic camera - * In scene unit - */ - this._orthoBottom = null; - /** - * Define the current limit on the top side for an orthographic camera - * In scene unit - */ - this._orthoTop = null; - /** - * Field Of View is set in Radians. (default is 0.8) - */ - this.fov = 0.8; - /** - * Projection plane tilt around the X axis (horizontal), set in Radians. (default is 0) - * Can be used to make vertical lines in world space actually vertical on the screen. - * See https://forum.babylonjs.com/t/add-vertical-shift-to-3ds-max-exporter-babylon-cameras/17480 - */ - this.projectionPlaneTilt = 0; - /** - * Define the minimum distance the camera can see from. - * This is important to note that the depth buffer are not infinite and the closer it starts - * the more your scene might encounter depth fighting issue. - */ - this.minZ = 1; - /** - * Define the maximum distance the camera can see to. - * This is important to note that the depth buffer are not infinite and the further it end - * the more your scene might encounter depth fighting issue. - */ - this.maxZ = 10000.0; - /** - * Define the default inertia of the camera. - * This helps giving a smooth feeling to the camera movement. - */ - this.inertia = 0.9; - /** - * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.ORTHOGRAPHIC_CAMERA) - */ - this._mode = camera_Camera.PERSPECTIVE_CAMERA; - /** - * Define whether the camera is intermediate. - * This is useful to not present the output directly to the screen in case of rig without post process for instance - */ - this.isIntermediate = false; - /** - * Define the viewport of the camera. - * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit. - */ - this.viewport = new math_viewport_Viewport(0, 0, 1.0, 1.0); - /** - * Restricts the camera to viewing objects with the same layerMask. - * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0 - */ - this.layerMask = 0x0fffffff; - /** - * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED) - */ - this.fovMode = camera_Camera.FOVMODE_VERTICAL_FIXED; - /** - * Rig mode of the camera. - * This is useful to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes. - * This is normally controlled byt the camera themselves as internal use. - */ - this.cameraRigMode = camera_Camera.RIG_MODE_NONE; - /** - * 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 - * This is pretty helpful if you wish to make a camera render to a texture you could reuse somewhere - * else in the scene. (Eg. security camera) - * - * 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) - */ - this.customRenderTargets = new Array(); - /** - * When set, the camera will render to this render target instead of the default canvas - * - * If the desire is to use the output of a camera as a texture in the scene consider using camera.customRenderTargets instead - */ - this.outputRenderTarget = null; - /** - * Observable triggered when the camera view matrix has changed. - */ - this.onViewMatrixChangedObservable = new observable_Observable(); - /** - * Observable triggered when the camera Projection matrix has changed. - */ - this.onProjectionMatrixChangedObservable = new observable_Observable(); - /** - * Observable triggered when the inputs have been processed. - */ - this.onAfterCheckInputsObservable = new observable_Observable(); - /** - * Observable triggered when reset has been called and applied to the camera. - */ - this.onRestoreStateObservable = new observable_Observable(); - /** - * Is this camera a part of a rig system? - */ - this.isRigCamera = false; - /** @internal */ - this._rigCameras = new Array(); - this._webvrViewMatrix = math_vector_Matrix.Identity(); - /** @internal */ - this._skipRendering = false; - /** @internal */ - this._projectionMatrix = new math_vector_Matrix(); - /** @internal */ - this._postProcesses = new Array(); - /** @internal */ - this._activeMeshes = new SmartArray(256); - this._globalPosition = math_vector_Vector3.Zero(); - /** @internal */ - this._computedViewMatrix = math_vector_Matrix.Identity(); - this._doNotComputeProjectionMatrix = false; - this._transformMatrix = math_vector_Matrix.Zero(); - this._refreshFrustumPlanes = true; - this._absoluteRotation = math_vector_Quaternion.Identity(); - /** @internal */ - this._isCamera = true; - /** @internal */ - this._isLeftCamera = false; - /** @internal */ - this._isRightCamera = false; - this.getScene().addCamera(this); - if (setActiveOnSceneIfNoneActive && !this.getScene().activeCamera) { - this.getScene().activeCamera = this; - } - this.position = position; - this.renderPassId = this.getScene().getEngine().createRenderPassId(`Camera ${name}`); - } - /** - * Store current camera state (fov, position, etc..) - * @returns the camera - */ - storeState() { - this._stateStored = true; - this._storedFov = this.fov; - return this; - } - /** - * Restores the camera state values if it has been stored. You must call storeState() first - */ - _restoreStateValues() { - if (!this._stateStored) { - return false; - } - this.fov = this._storedFov; - return true; - } - /** - * Restored camera state. You must call storeState() first. - * @returns true if restored and false otherwise - */ - restoreState() { - if (this._restoreStateValues()) { - this.onRestoreStateObservable.notifyObservers(this); - return true; - } - return false; - } - /** - * Gets the class name of the camera. - * @returns the class name - */ - getClassName() { - return "Camera"; - } - /** - * Gets a string representation of the camera useful for debug purpose. - * @param fullDetails Defines that a more verbose level of logging is required - * @returns the string representation - */ - toString(fullDetails) { - let ret = "Name: " + this.name; - ret += ", type: " + this.getClassName(); - if (this.animations) { - for (let i = 0; i < this.animations.length; i++) { - ret += ", animation[0]: " + this.animations[i].toString(fullDetails); - } - } - return ret; - } - /** - * Automatically tilts the projection plane, using `projectionPlaneTilt`, to correct the perspective effect on vertical lines. - */ - applyVerticalCorrection() { - const rot = this.absoluteRotation.toEulerAngles(); - this.projectionPlaneTilt = this._scene.useRightHandedSystem ? -rot.x : rot.x; - } - /** - * Gets the current world space position of the camera. - */ - get globalPosition() { - return this._globalPosition; - } - /** - * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame) - * @returns the active meshe list - */ - getActiveMeshes() { - return this._activeMeshes; - } - /** - * Check whether a mesh is part of the current active mesh list of the camera - * @param mesh Defines the mesh to check - * @returns true if active, false otherwise - */ - isActiveMesh(mesh) { - return this._activeMeshes.indexOf(mesh) !== -1; - } - /** - * Is this camera ready to be used/rendered - * @param completeCheck defines if a complete check (including post processes) has to be done (false by default) - * @returns true if the camera is ready - */ - isReady(completeCheck = false) { - if (completeCheck) { - for (const pp of this._postProcesses) { - if (pp && !pp.isReady()) { - return false; - } - } - } - return super.isReady(completeCheck); - } - /** @internal */ - _initCache() { - super._initCache(); - this._cache.position = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - this._cache.upVector = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - this._cache.mode = undefined; - this._cache.minZ = undefined; - this._cache.maxZ = undefined; - this._cache.fov = undefined; - this._cache.fovMode = undefined; - this._cache.aspectRatio = undefined; - this._cache.orthoLeft = undefined; - this._cache.orthoRight = undefined; - this._cache.orthoBottom = undefined; - this._cache.orthoTop = undefined; - this._cache.renderWidth = undefined; - this._cache.renderHeight = undefined; - } - /** - * @internal - */ - _updateCache(ignoreParentClass) { - if (!ignoreParentClass) { - super._updateCache(); - } - this._cache.position.copyFrom(this.position); - this._cache.upVector.copyFrom(this.upVector); - } - /** @internal */ - _isSynchronized() { - return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix(); - } - /** @internal */ - _isSynchronizedViewMatrix() { - if (!super._isSynchronized()) { - return false; - } - return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent(); - } - /** @internal */ - _isSynchronizedProjectionMatrix() { - let check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ; - if (!check) { - return false; - } - const engine = this.getEngine(); - if (this.mode === camera_Camera.PERSPECTIVE_CAMERA) { - check = - this._cache.fov === this.fov && - this._cache.fovMode === this.fovMode && - this._cache.aspectRatio === engine.getAspectRatio(this) && - this._cache.projectionPlaneTilt === this.projectionPlaneTilt; - } - else { - check = - this._cache.orthoLeft === this.orthoLeft && - this._cache.orthoRight === this.orthoRight && - this._cache.orthoBottom === this.orthoBottom && - this._cache.orthoTop === this.orthoTop && - this._cache.renderWidth === engine.getRenderWidth() && - this._cache.renderHeight === engine.getRenderHeight(); - } - return check; - } - /** - * Attach the input controls to a specific dom element to get the input from. - * This function is here because typescript removes the typing of the last function. - * @param _ignored defines an ignored parameter kept for backward compatibility. - * @param _noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(_ignored, _noPreventDefault) { } - /** - * Detach the current controls from the specified dom element. - * This function is here because typescript removes the typing of the last function. - * @param _ignored defines an ignored parameter kept for backward compatibility. - */ - detachControl(_ignored) { } - /** - * Update the camera state according to the different inputs gathered during the frame. - */ - update() { - this._checkInputs(); - if (this.cameraRigMode !== camera_Camera.RIG_MODE_NONE) { - this._updateRigCameras(); - } - // Attempt to update the camera's view and projection matrices. - // This call is being made because these matrices are no longer being updated - // as a part of the picking ray process (in addition to scene.render). - this.getViewMatrix(); - this.getProjectionMatrix(); - } - /** @internal */ - _checkInputs() { - this.onAfterCheckInputsObservable.notifyObservers(this); - } - /** @internal */ - get rigCameras() { - return this._rigCameras; - } - /** - * Gets the post process used by the rig cameras - */ - get rigPostProcess() { - return this._rigPostProcess; - } - /** - * Internal, gets the first post process. - * @returns the first post process to be run on this camera. - */ - _getFirstPostProcess() { - for (let ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) { - if (this._postProcesses[ppIndex] !== null) { - return this._postProcesses[ppIndex]; - } - } - return null; - } - _cascadePostProcessesToRigCams() { - // invalidate framebuffer - const firstPostProcess = this._getFirstPostProcess(); - if (firstPostProcess) { - firstPostProcess.markTextureDirty(); - } - // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera - for (let i = 0, len = this._rigCameras.length; i < len; i++) { - const cam = this._rigCameras[i]; - const rigPostProcess = cam._rigPostProcess; - // for VR rig, there does not have to be a post process - if (rigPostProcess) { - const isPass = rigPostProcess.getEffectName() === "pass"; - if (isPass) { - // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses - cam.isIntermediate = this._postProcesses.length === 0; - } - cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess); - rigPostProcess.markTextureDirty(); - } - else { - cam._postProcesses = this._postProcesses.slice(0); - } - } - } - /** - * Attach a post process to the camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess - * @param postProcess The post process to attach to the camera - * @param insertAt The position of the post process in case several of them are in use in the scene - * @returns the position the post process has been inserted at - */ - attachPostProcess(postProcess, insertAt = null) { - if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) { - logger_Logger.Error("You're trying to reuse a post process not defined as reusable."); - return 0; - } - if (insertAt == null || insertAt < 0) { - this._postProcesses.push(postProcess); - } - else if (this._postProcesses[insertAt] === null) { - this._postProcesses[insertAt] = postProcess; - } - else { - this._postProcesses.splice(insertAt, 0, postProcess); - } - this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated - // Update prePass - if (this._scene.prePassRenderer) { - this._scene.prePassRenderer.markAsDirty(); - } - return this._postProcesses.indexOf(postProcess); - } - /** - * Detach a post process to the camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess - * @param postProcess The post process to detach from the camera - */ - detachPostProcess(postProcess) { - const idx = this._postProcesses.indexOf(postProcess); - if (idx !== -1) { - this._postProcesses[idx] = null; - } - // Update prePass - if (this._scene.prePassRenderer) { - this._scene.prePassRenderer.markAsDirty(); - } - this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated - } - /** - * Gets the current world matrix of the camera - */ - getWorldMatrix() { - if (this._isSynchronizedViewMatrix()) { - return this._worldMatrix; - } - // Getting the the view matrix will also compute the world matrix. - this.getViewMatrix(); - return this._worldMatrix; - } - /** @internal */ - _getViewMatrix() { - return math_vector_Matrix.Identity(); - } - /** - * Gets the current view matrix of the camera. - * @param force forces the camera to recompute the matrix without looking at the cached state - * @returns the view matrix - */ - getViewMatrix(force) { - if (!force && this._isSynchronizedViewMatrix()) { - return this._computedViewMatrix; - } - this.updateCache(); - this._computedViewMatrix = this._getViewMatrix(); - this._currentRenderId = this.getScene().getRenderId(); - this._childUpdateId++; - this._refreshFrustumPlanes = true; - if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) { - this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix); - } - // Notify parent camera if rig camera is changed - if (this.parent && this.parent.onViewMatrixChangedObservable) { - this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent); - } - this.onViewMatrixChangedObservable.notifyObservers(this); - this._computedViewMatrix.invertToRef(this._worldMatrix); - return this._computedViewMatrix; - } - /** - * Freeze the projection matrix. - * It will prevent the cache check of the camera projection compute and can speed up perf - * if no parameter of the camera are meant to change - * @param projection Defines manually a projection if necessary - */ - freezeProjectionMatrix(projection) { - this._doNotComputeProjectionMatrix = true; - if (projection !== undefined) { - this._projectionMatrix = projection; - } - } - /** - * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix. - */ - unfreezeProjectionMatrix() { - this._doNotComputeProjectionMatrix = false; - } - /** - * Gets the current projection matrix of the camera. - * @param force forces the camera to recompute the matrix without looking at the cached state - * @returns the projection matrix - */ - getProjectionMatrix(force) { - var _a, _b, _c, _d, _e, _f, _g, _h; - if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) { - return this._projectionMatrix; - } - // Cache - this._cache.mode = this.mode; - this._cache.minZ = this.minZ; - this._cache.maxZ = this.maxZ; - // Matrix - this._refreshFrustumPlanes = true; - const engine = this.getEngine(); - const scene = this.getScene(); - const reverseDepth = engine.useReverseDepthBuffer; - if (this.mode === camera_Camera.PERSPECTIVE_CAMERA) { - this._cache.fov = this.fov; - this._cache.fovMode = this.fovMode; - this._cache.aspectRatio = engine.getAspectRatio(this); - this._cache.projectionPlaneTilt = this.projectionPlaneTilt; - if (this.minZ <= 0) { - this.minZ = 0.1; - } - let getProjectionMatrix; - if (scene.useRightHandedSystem) { - getProjectionMatrix = math_vector_Matrix.PerspectiveFovRHToRef; - } - else { - getProjectionMatrix = math_vector_Matrix.PerspectiveFovLHToRef; - } - getProjectionMatrix(this.fov, engine.getAspectRatio(this), reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, this.fovMode === camera_Camera.FOVMODE_VERTICAL_FIXED, engine.isNDCHalfZRange, this.projectionPlaneTilt, reverseDepth); - } - else { - const halfWidth = engine.getRenderWidth() / 2.0; - const halfHeight = engine.getRenderHeight() / 2.0; - if (scene.useRightHandedSystem) { - math_vector_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); - } - else { - math_vector_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); - } - this._cache.orthoLeft = this.orthoLeft; - this._cache.orthoRight = this.orthoRight; - this._cache.orthoBottom = this.orthoBottom; - this._cache.orthoTop = this.orthoTop; - this._cache.renderWidth = engine.getRenderWidth(); - this._cache.renderHeight = engine.getRenderHeight(); - } - this.onProjectionMatrixChangedObservable.notifyObservers(this); - return this._projectionMatrix; - } - /** - * Gets the transformation matrix (ie. the multiplication of view by projection matrices) - * @returns a Matrix - */ - getTransformationMatrix() { - this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); - return this._transformMatrix; - } - _updateFrustumPlanes() { - if (!this._refreshFrustumPlanes) { - return; - } - this.getTransformationMatrix(); - if (!this._frustumPlanes) { - this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix); - } - else { - Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes); - } - this._refreshFrustumPlanes = false; - } - /** - * Checks if a cullable object (mesh...) is in the camera frustum - * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check - * @param target The object to check - * @param checkRigCameras If the rig cameras should be checked (eg. with webVR camera both eyes should be checked) (Default: false) - * @returns true if the object is in frustum otherwise false - */ - isInFrustum(target, checkRigCameras = false) { - this._updateFrustumPlanes(); - if (checkRigCameras && this.rigCameras.length > 0) { - let result = false; - this.rigCameras.forEach((cam) => { - cam._updateFrustumPlanes(); - result = result || target.isInFrustum(cam._frustumPlanes); - }); - return result; - } - else { - return target.isInFrustum(this._frustumPlanes); - } - } - /** - * Checks if a cullable object (mesh...) is in the camera frustum - * Unlike isInFrustum this checks the full bounding box - * @param target The object to check - * @returns true if the object is in frustum otherwise false - */ - isCompletelyInFrustum(target) { - this._updateFrustumPlanes(); - return target.isCompletelyInFrustum(this._frustumPlanes); - } - /** - * Gets a ray in the forward direction from the camera. - * @param length Defines the length of the ray to create - * @param transform Defines the transform to apply to the ray, by default the world matrix is used to create a workd space ray - * @param origin Defines the start point of the ray which defaults to the camera position - * @returns the forward ray - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getForwardRay(length = 100, transform, origin) { - throw _WarnImport("Ray"); - } - /** - * Gets a ray in the forward direction from the camera. - * @param refRay the ray to (re)use when setting the values - * @param length Defines the length of the ray to create - * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray - * @param origin Defines the start point of the ray which defaults to the camera position - * @returns the forward ray - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getForwardRayToRef(refRay, length = 100, transform, origin) { - throw _WarnImport("Ray"); - } - /** - * Releases resources associated with this node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) - */ - dispose(doNotRecurse, disposeMaterialAndTextures = false) { - // Observables - this.onViewMatrixChangedObservable.clear(); - this.onProjectionMatrixChangedObservable.clear(); - this.onAfterCheckInputsObservable.clear(); - this.onRestoreStateObservable.clear(); - // Inputs - if (this.inputs) { - this.inputs.clear(); - } - // Animations - this.getScene().stopAnimation(this); - // Remove from scene - this.getScene().removeCamera(this); - while (this._rigCameras.length > 0) { - const camera = this._rigCameras.pop(); - if (camera) { - camera.dispose(); - } - } - if (this._parentContainer) { - const index = this._parentContainer.cameras.indexOf(this); - if (index > -1) { - this._parentContainer.cameras.splice(index, 1); - } - this._parentContainer = null; - } - // Postprocesses - if (this._rigPostProcess) { - this._rigPostProcess.dispose(this); - this._rigPostProcess = null; - this._postProcesses.length = 0; - } - else if (this.cameraRigMode !== camera_Camera.RIG_MODE_NONE) { - this._rigPostProcess = null; - this._postProcesses.length = 0; - } - else { - let i = this._postProcesses.length; - while (--i >= 0) { - const postProcess = this._postProcesses[i]; - if (postProcess) { - postProcess.dispose(this); - } - } - } - // Render targets - let i = this.customRenderTargets.length; - while (--i >= 0) { - this.customRenderTargets[i].dispose(); - } - this.customRenderTargets.length = 0; - // Active Meshes - this._activeMeshes.dispose(); - this.getScene().getEngine().releaseRenderPassId(this.renderPassId); - super.dispose(doNotRecurse, disposeMaterialAndTextures); - } - /** - * Gets the left camera of a rig setup in case of Rigged Camera - */ - get isLeftCamera() { - return this._isLeftCamera; - } - /** - * Gets the right camera of a rig setup in case of Rigged Camera - */ - get isRightCamera() { - return this._isRightCamera; - } - /** - * Gets the left camera of a rig setup in case of Rigged Camera - */ - get leftCamera() { - if (this._rigCameras.length < 1) { - return null; - } - return this._rigCameras[0]; - } - /** - * Gets the right camera of a rig setup in case of Rigged Camera - */ - get rightCamera() { - if (this._rigCameras.length < 2) { - return null; - } - return this._rigCameras[1]; - } - /** - * Gets the left camera target of a rig setup in case of Rigged Camera - * @returns the target position - */ - getLeftTarget() { - if (this._rigCameras.length < 1) { - return null; - } - return this._rigCameras[0].getTarget(); - } - /** - * Gets the right camera target of a rig setup in case of Rigged Camera - * @returns the target position - */ - getRightTarget() { - if (this._rigCameras.length < 2) { - return null; - } - return this._rigCameras[1].getTarget(); - } - /** - * @internal - */ - setCameraRigMode(mode, rigParams) { - if (this.cameraRigMode === mode) { - return; - } - while (this._rigCameras.length > 0) { - const camera = this._rigCameras.pop(); - if (camera) { - camera.dispose(); - } - } - this.cameraRigMode = mode; - this._cameraRigParams = {}; - //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target, - //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced - this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637; - this._cameraRigParams.stereoHalfAngle = tools_Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637); - // create the rig cameras, unless none - if (this.cameraRigMode !== camera_Camera.RIG_MODE_NONE) { - const leftCamera = this.createRigCamera(this.name + "_L", 0); - if (leftCamera) { - leftCamera._isLeftCamera = true; - } - const rightCamera = this.createRigCamera(this.name + "_R", 1); - if (rightCamera) { - rightCamera._isRightCamera = true; - } - if (leftCamera && rightCamera) { - this._rigCameras.push(leftCamera); - this._rigCameras.push(rightCamera); - } - } - this._setRigMode(rigParams); - this._cascadePostProcessesToRigCams(); - this.update(); - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _setRigMode(rigParams) { - // no-op - } - /** @internal */ - _getVRProjectionMatrix() { - math_vector_Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix, true, this.getEngine().isNDCHalfZRange); - this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix); - return this._projectionMatrix; - } - _updateCameraRotationMatrix() { - //Here for WebVR - } - _updateWebVRCameraRotationMatrix() { - //Here for WebVR - } - /** - * This function MUST be overwritten by the different WebVR cameras available. - * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right. - * @internal - */ - _getWebVRProjectionMatrix() { - return math_vector_Matrix.Identity(); - } - /** - * This function MUST be overwritten by the different WebVR cameras available. - * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right. - * @internal - */ - _getWebVRViewMatrix() { - return math_vector_Matrix.Identity(); - } - /** - * @internal - */ - setCameraRigParameter(name, value) { - if (!this._cameraRigParams) { - this._cameraRigParams = {}; - } - this._cameraRigParams[name] = value; - //provisionnally: - if (name === "interaxialDistance") { - this._cameraRigParams.stereoHalfAngle = tools_Tools.ToRadians(value / 0.0637); - } - } - /** - * needs to be overridden by children so sub has required properties to be copied - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - createRigCamera(name, cameraIndex) { - return null; - } - /** - * May need to be overridden by children - * @internal - */ - _updateRigCameras() { - for (let i = 0; i < this._rigCameras.length; i++) { - this._rigCameras[i].minZ = this.minZ; - this._rigCameras[i].maxZ = this.maxZ; - this._rigCameras[i].fov = this.fov; - this._rigCameras[i].upVector.copyFrom(this.upVector); - } - // only update viewport when ANAGLYPH - if (this.cameraRigMode === camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) { - this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport; - } - } - /** @internal */ - _setupInputs() { } - /** - * Serialiaze the camera setup to a json representation - * @returns the JSON representation - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.uniqueId = this.uniqueId; - // Type - serializationObject.type = this.getClassName(); - // Parent - if (this.parent) { - this.parent._serializeAsParent(serializationObject); - } - if (this.inputs) { - this.inputs.serialize(serializationObject); - } - // Animations - decorators_SerializationHelper.AppendSerializedAnimations(this, serializationObject); - serializationObject.ranges = this.serializeAnimationRanges(); - serializationObject.isEnabled = this.isEnabled(); - return serializationObject; - } - /** - * Clones the current camera. - * @param name The cloned camera name - * @param newParent The cloned camera's new parent (none by default) - * @returns the cloned camera - */ - clone(name, newParent = null) { - const camera = decorators_SerializationHelper.Clone(camera_Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this); - camera.name = name; - camera.parent = newParent; - this.onClonedObservable.notifyObservers(camera); - return camera; - } - /** - * Gets the direction of the camera relative to a given local axis. - * @param localAxis Defines the reference axis to provide a relative direction. - * @returns the direction - */ - getDirection(localAxis) { - const result = math_vector_Vector3.Zero(); - this.getDirectionToRef(localAxis, result); - return result; - } - /** - * Returns the current camera absolute rotation - */ - get absoluteRotation() { - this.getWorldMatrix().decompose(undefined, this._absoluteRotation); - return this._absoluteRotation; - } - /** - * Gets the direction of the camera relative to a given local axis into a passed vector. - * @param localAxis Defines the reference axis to provide a relative direction. - * @param result Defines the vector to store the result in - */ - getDirectionToRef(localAxis, result) { - math_vector_Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result); - } - /** - * Gets a camera constructor for a given camera type - * @param type The type of the camera to construct (should be equal to one of the camera class name) - * @param name The name of the camera the result will be able to instantiate - * @param scene The scene the result will construct the camera in - * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes - * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side - * @returns a factory method to construct the camera - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static GetConstructorFromName(type, name, scene, interaxial_distance = 0, isStereoscopicSideBySide = true) { - const constructorFunc = node_Node.Construct(type, name, scene, { - // eslint-disable-next-line @typescript-eslint/naming-convention - interaxial_distance: interaxial_distance, - isStereoscopicSideBySide: isStereoscopicSideBySide, - }); - if (constructorFunc) { - return constructorFunc; - } - // Default to universal camera - return () => camera_Camera._CreateDefaultParsedCamera(name, scene); - } - /** - * Compute the world matrix of the camera. - * @returns the camera world matrix - */ - computeWorldMatrix() { - return this.getWorldMatrix(); - } - /** - * Parse a JSON and creates the camera from the parsed information - * @param parsedCamera The JSON to parse - * @param scene The scene to instantiate the camera in - * @returns the newly constructed camera - */ - static Parse(parsedCamera, scene) { - const type = parsedCamera.type; - const construct = camera_Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide); - const camera = decorators_SerializationHelper.Parse(construct, parsedCamera, scene); - // Parent - if (parsedCamera.parentId !== undefined) { - camera._waitingParentId = parsedCamera.parentId; - } - // Parent instance index - if (parsedCamera.parentInstanceIndex !== undefined) { - camera._waitingParentInstanceIndex = parsedCamera.parentInstanceIndex; - } - //If camera has an input manager, let it parse inputs settings - if (camera.inputs) { - camera.inputs.parse(parsedCamera); - camera._setupInputs(); - } - if (parsedCamera.upVector) { - camera.upVector = math_vector_Vector3.FromArray(parsedCamera.upVector); // need to force the upVector - } - if (camera.setPosition) { - // need to force position - camera.position.copyFromFloats(0, 0, 0); - camera.setPosition(math_vector_Vector3.FromArray(parsedCamera.position)); - } - // Target - if (parsedCamera.target) { - if (camera.setTarget) { - camera.setTarget(math_vector_Vector3.FromArray(parsedCamera.target)); - } - } - // Apply 3d rig, when found - if (parsedCamera.cameraRigMode) { - const rigParams = parsedCamera.interaxial_distance ? { interaxialDistance: parsedCamera.interaxial_distance } : {}; - camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams); - } - // Animations - if (parsedCamera.animations) { - for (let animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) { - const parsedAnimation = parsedCamera.animations[animationIndex]; - const internalClass = GetClass("BABYLON.Animation"); - if (internalClass) { - camera.animations.push(internalClass.Parse(parsedAnimation)); - } - } - node_Node.ParseAnimationRanges(camera, parsedCamera, scene); - } - if (parsedCamera.autoAnimate) { - scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0); - } - // Check if isEnabled is defined to be back compatible with prior serialized versions. - if (parsedCamera.isEnabled !== undefined) { - camera.setEnabled(parsedCamera.isEnabled); - } - return camera; - } -} -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -camera_Camera._CreateDefaultParsedCamera = (name, scene) => { - throw _WarnImport("UniversalCamera"); -}; -/** - * This is the default projection mode used by the cameras. - * It helps recreating a feeling of perspective and better appreciate depth. - * This is the best way to simulate real life cameras. - */ -camera_Camera.PERSPECTIVE_CAMERA = 0; -/** - * This helps creating camera with an orthographic mode. - * 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. - */ -camera_Camera.ORTHOGRAPHIC_CAMERA = 1; -/** - * This is the default FOV mode for perspective cameras. - * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum. - */ -camera_Camera.FOVMODE_VERTICAL_FIXED = 0; -/** - * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum. - */ -camera_Camera.FOVMODE_HORIZONTAL_FIXED = 1; -/** - * This specifies there is no need for a camera rig. - * Basically only one eye is rendered corresponding to the camera. - */ -camera_Camera.RIG_MODE_NONE = 0; -/** - * Simulates a camera Rig with one blue eye and one red eye. - * This can be use with 3d blue and red glasses. - */ -camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10; -/** - * Defines that both eyes of the camera will be rendered side by side with a parallel target. - */ -camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11; -/** - * Defines that both eyes of the camera will be rendered side by side with a none parallel target. - */ -camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12; -/** - * Defines that both eyes of the camera will be rendered over under each other. - */ -camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13; -/** - * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors. - */ -camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED = 14; -/** - * Defines that both eyes of the camera should be renderered in a VR mode (carbox). - */ -camera_Camera.RIG_MODE_VR = 20; -/** - * Defines that both eyes of the camera should be renderered in a VR mode (webVR). - */ -camera_Camera.RIG_MODE_WEBVR = 21; -/** - * Custom rig mode allowing rig cameras to be populated manually with any number of cameras - */ -camera_Camera.RIG_MODE_CUSTOM = 22; -/** - * Defines if by default attaching controls should prevent the default javascript event to continue. - */ -camera_Camera.ForceAttachControlToAlwaysPreventDefault = false; -__decorate([ - serializeAsVector3("position") -], camera_Camera.prototype, "_position", void 0); -__decorate([ - serializeAsVector3("upVector") -], camera_Camera.prototype, "_upVector", void 0); -__decorate([ - serialize() -], camera_Camera.prototype, "orthoLeft", null); -__decorate([ - serialize() -], camera_Camera.prototype, "orthoRight", null); -__decorate([ - serialize() -], camera_Camera.prototype, "orthoBottom", null); -__decorate([ - serialize() -], camera_Camera.prototype, "orthoTop", null); -__decorate([ - serialize() -], camera_Camera.prototype, "fov", void 0); -__decorate([ - serialize() -], camera_Camera.prototype, "projectionPlaneTilt", void 0); -__decorate([ - serialize() -], camera_Camera.prototype, "minZ", void 0); -__decorate([ - serialize() -], camera_Camera.prototype, "maxZ", void 0); -__decorate([ - serialize() -], camera_Camera.prototype, "inertia", void 0); -__decorate([ - serialize() -], camera_Camera.prototype, "mode", null); -__decorate([ - serialize() -], camera_Camera.prototype, "layerMask", void 0); -__decorate([ - serialize() -], camera_Camera.prototype, "fovMode", void 0); -__decorate([ - serialize() -], camera_Camera.prototype, "cameraRigMode", void 0); -__decorate([ - serialize() -], camera_Camera.prototype, "interaxialDistance", void 0); -__decorate([ - serialize() -], camera_Camera.prototype, "isStereoscopicSideBySide", void 0); -//# sourceMappingURL=camera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Collisions/intersectionInfo.js -/** - * @internal - */ -class IntersectionInfo { - constructor(bu, bv, distance) { - this.bu = bu; - this.bv = bv; - this.distance = distance; - this.faceId = 0; - this.subMeshId = 0; - } -} -//# sourceMappingURL=intersectionInfo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Culling/boundingBox.js - - - -/** - * Class used to store bounding box information - */ -class boundingBox_BoundingBox { - /** - * Creates a new bounding box - * @param min defines the minimum vector (in local space) - * @param max defines the maximum vector (in local space) - * @param worldMatrix defines the new world matrix - */ - constructor(min, max, worldMatrix) { - /** - * Gets the 8 vectors representing the bounding box in local space - */ - this.vectors = arrayTools_ArrayTools.BuildArray(8, math_vector_Vector3.Zero); - /** - * Gets the center of the bounding box in local space - */ - this.center = math_vector_Vector3.Zero(); - /** - * Gets the center of the bounding box in world space - */ - this.centerWorld = math_vector_Vector3.Zero(); - /** - * Gets the extend size in local space - */ - this.extendSize = math_vector_Vector3.Zero(); - /** - * Gets the extend size in world space - */ - this.extendSizeWorld = math_vector_Vector3.Zero(); - /** - * Gets the OBB (object bounding box) directions - */ - this.directions = arrayTools_ArrayTools.BuildArray(3, math_vector_Vector3.Zero); - /** - * Gets the 8 vectors representing the bounding box in world space - */ - this.vectorsWorld = arrayTools_ArrayTools.BuildArray(8, math_vector_Vector3.Zero); - /** - * Gets the minimum vector in world space - */ - this.minimumWorld = math_vector_Vector3.Zero(); - /** - * Gets the maximum vector in world space - */ - this.maximumWorld = math_vector_Vector3.Zero(); - /** - * Gets the minimum vector in local space - */ - this.minimum = math_vector_Vector3.Zero(); - /** - * Gets the maximum vector in local space - */ - this.maximum = math_vector_Vector3.Zero(); - /** @internal */ - this._drawWrapperFront = null; - /** @internal */ - this._drawWrapperBack = null; - this.reConstruct(min, max, worldMatrix); - } - // Methods - /** - * Recreates the entire bounding box from scratch as if we call the constructor in place - * @param min defines the new minimum vector (in local space) - * @param max defines the new maximum vector (in local space) - * @param worldMatrix defines the new world matrix - */ - reConstruct(min, max, worldMatrix) { - const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; - const vectors = this.vectors; - this.minimum.copyFromFloats(minX, minY, minZ); - this.maximum.copyFromFloats(maxX, maxY, maxZ); - vectors[0].copyFromFloats(minX, minY, minZ); - vectors[1].copyFromFloats(maxX, maxY, maxZ); - vectors[2].copyFromFloats(maxX, minY, minZ); - vectors[3].copyFromFloats(minX, maxY, minZ); - vectors[4].copyFromFloats(minX, minY, maxZ); - vectors[5].copyFromFloats(maxX, maxY, minZ); - vectors[6].copyFromFloats(minX, maxY, maxZ); - vectors[7].copyFromFloats(maxX, minY, maxZ); - // OBB - max.addToRef(min, this.center).scaleInPlace(0.5); - max.subtractToRef(min, this.extendSize).scaleInPlace(0.5); - this._worldMatrix = worldMatrix || math_vector_Matrix.IdentityReadOnly; - this._update(this._worldMatrix); - } - /** - * Scale the current bounding box by applying a scale factor - * @param factor defines the scale factor to apply - * @returns the current bounding box - */ - scale(factor) { - const tmpVectors = boundingBox_BoundingBox._TmpVector3; - const diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]); - const len = diff.length(); - diff.normalizeFromLength(len); - const distance = len * factor; - const newRadius = diff.scaleInPlace(distance * 0.5); - const min = this.center.subtractToRef(newRadius, tmpVectors[1]); - const max = this.center.addToRef(newRadius, tmpVectors[2]); - this.reConstruct(min, max, this._worldMatrix); - return this; - } - /** - * Gets the world matrix of the bounding box - * @returns a matrix - */ - getWorldMatrix() { - return this._worldMatrix; - } - /** - * @internal - */ - _update(world) { - const minWorld = this.minimumWorld; - const maxWorld = this.maximumWorld; - const directions = this.directions; - const vectorsWorld = this.vectorsWorld; - const vectors = this.vectors; - if (!world.isIdentity()) { - minWorld.setAll(Number.MAX_VALUE); - maxWorld.setAll(-Number.MAX_VALUE); - for (let index = 0; index < 8; ++index) { - const v = vectorsWorld[index]; - math_vector_Vector3.TransformCoordinatesToRef(vectors[index], world, v); - minWorld.minimizeInPlace(v); - maxWorld.maximizeInPlace(v); - } - // Extend - maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5); - maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5); - } - else { - minWorld.copyFrom(this.minimum); - maxWorld.copyFrom(this.maximum); - for (let index = 0; index < 8; ++index) { - vectorsWorld[index].copyFrom(vectors[index]); - } - // Extend - this.extendSizeWorld.copyFrom(this.extendSize); - this.centerWorld.copyFrom(this.center); - } - math_vector_Vector3.FromArrayToRef(world.m, 0, directions[0]); - math_vector_Vector3.FromArrayToRef(world.m, 4, directions[1]); - math_vector_Vector3.FromArrayToRef(world.m, 8, directions[2]); - this._worldMatrix = world; - } - /** - * Tests if the bounding box is intersecting the frustum planes - * @param frustumPlanes defines the frustum planes to test - * @returns true if there is an intersection - */ - isInFrustum(frustumPlanes) { - return boundingBox_BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes); - } - /** - * Tests if the bounding box is entirely inside the frustum planes - * @param frustumPlanes defines the frustum planes to test - * @returns true if there is an inclusion - */ - isCompletelyInFrustum(frustumPlanes) { - return boundingBox_BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes); - } - /** - * Tests if a point is inside the bounding box - * @param point defines the point to test - * @returns true if the point is inside the bounding box - */ - intersectsPoint(point) { - const min = this.minimumWorld; - const max = this.maximumWorld; - const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; - const pointX = point.x, pointY = point.y, pointZ = point.z; - const delta = -math_constants_Epsilon; - if (maxX - pointX < delta || delta > pointX - minX) { - return false; - } - if (maxY - pointY < delta || delta > pointY - minY) { - return false; - } - if (maxZ - pointZ < delta || delta > pointZ - minZ) { - return false; - } - return true; - } - /** - * Tests if the bounding box intersects with a bounding sphere - * @param sphere defines the sphere to test - * @returns true if there is an intersection - */ - intersectsSphere(sphere) { - return boundingBox_BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld); - } - /** - * Tests if the bounding box intersects with a box defined by a min and max vectors - * @param min defines the min vector to use - * @param max defines the max vector to use - * @returns true if there is an intersection - */ - intersectsMinMax(min, max) { - const myMin = this.minimumWorld; - const myMax = this.maximumWorld; - const myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z; - const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; - if (myMaxX < minX || myMinX > maxX) { - return false; - } - if (myMaxY < minY || myMinY > maxY) { - return false; - } - if (myMaxZ < minZ || myMinZ > maxZ) { - return false; - } - return true; - } - /** - * Disposes the resources of the class - */ - dispose() { - var _a, _b; - (_a = this._drawWrapperFront) === null || _a === void 0 ? void 0 : _a.dispose(); - (_b = this._drawWrapperBack) === null || _b === void 0 ? void 0 : _b.dispose(); - } - // Statics - /** - * Tests if two bounding boxes are intersections - * @param box0 defines the first box to test - * @param box1 defines the second box to test - * @returns true if there is an intersection - */ - static Intersects(box0, box1) { - return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld); - } - /** - * Tests if a bounding box defines by a min/max vectors intersects a sphere - * @param minPoint defines the minimum vector of the bounding box - * @param maxPoint defines the maximum vector of the bounding box - * @param sphereCenter defines the sphere center - * @param sphereRadius defines the sphere radius - * @returns true if there is an intersection - */ - static IntersectsSphere(minPoint, maxPoint, sphereCenter, sphereRadius) { - const vector = boundingBox_BoundingBox._TmpVector3[0]; - math_vector_Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector); - const num = math_vector_Vector3.DistanceSquared(sphereCenter, vector); - return num <= sphereRadius * sphereRadius; - } - /** - * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes - * @param boundingVectors defines an array of 8 vectors representing a bounding box - * @param frustumPlanes defines the frustum planes to test - * @returns true if there is an inclusion - */ - static IsCompletelyInFrustum(boundingVectors, frustumPlanes) { - for (let p = 0; p < 6; ++p) { - const frustumPlane = frustumPlanes[p]; - for (let i = 0; i < 8; ++i) { - if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) { - return false; - } - } - } - return true; - } - /** - * Tests if a bounding box defined with 8 vectors intersects frustum planes - * @param boundingVectors defines an array of 8 vectors representing a bounding box - * @param frustumPlanes defines the frustum planes to test - * @returns true if there is an intersection - */ - static IsInFrustum(boundingVectors, frustumPlanes) { - for (let p = 0; p < 6; ++p) { - let canReturnFalse = true; - const frustumPlane = frustumPlanes[p]; - for (let i = 0; i < 8; ++i) { - if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) { - canReturnFalse = false; - break; - } - } - if (canReturnFalse) { - return false; - } - } - return true; - } -} -boundingBox_BoundingBox._TmpVector3 = arrayTools_ArrayTools.BuildArray(3, math_vector_Vector3.Zero); -//# sourceMappingURL=boundingBox.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Culling/boundingSphere.js - - -/** - * Class used to store bounding sphere information - */ -class boundingSphere_BoundingSphere { - /** - * Creates a new bounding sphere - * @param min defines the minimum vector (in local space) - * @param max defines the maximum vector (in local space) - * @param worldMatrix defines the new world matrix - */ - constructor(min, max, worldMatrix) { - /** - * Gets the center of the bounding sphere in local space - */ - this.center = math_vector_Vector3.Zero(); - /** - * Gets the center of the bounding sphere in world space - */ - this.centerWorld = math_vector_Vector3.Zero(); - /** - * Gets the minimum vector in local space - */ - this.minimum = math_vector_Vector3.Zero(); - /** - * Gets the maximum vector in local space - */ - this.maximum = math_vector_Vector3.Zero(); - this.reConstruct(min, max, worldMatrix); - } - /** - * Recreates the entire bounding sphere from scratch as if we call the constructor in place - * @param min defines the new minimum vector (in local space) - * @param max defines the new maximum vector (in local space) - * @param worldMatrix defines the new world matrix - */ - reConstruct(min, max, worldMatrix) { - this.minimum.copyFrom(min); - this.maximum.copyFrom(max); - const distance = math_vector_Vector3.Distance(min, max); - max.addToRef(min, this.center).scaleInPlace(0.5); - this.radius = distance * 0.5; - this._update(worldMatrix || math_vector_Matrix.IdentityReadOnly); - } - /** - * Scale the current bounding sphere by applying a scale factor - * @param factor defines the scale factor to apply - * @returns the current bounding box - */ - scale(factor) { - const newRadius = this.radius * factor; - const tmpVectors = boundingSphere_BoundingSphere._TmpVector3; - const tempRadiusVector = tmpVectors[0].setAll(newRadius); - const min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]); - const max = this.center.addToRef(tempRadiusVector, tmpVectors[2]); - this.reConstruct(min, max, this._worldMatrix); - return this; - } - /** - * Gets the world matrix of the bounding box - * @returns a matrix - */ - getWorldMatrix() { - return this._worldMatrix; - } - // Methods - /** - * @internal - */ - _update(worldMatrix) { - if (!worldMatrix.isIdentity()) { - math_vector_Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld); - const tempVector = boundingSphere_BoundingSphere._TmpVector3[0]; - math_vector_Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector); - this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius; - } - else { - this.centerWorld.copyFrom(this.center); - this.radiusWorld = this.radius; - } - } - /** - * Tests if the bounding sphere is intersecting the frustum planes - * @param frustumPlanes defines the frustum planes to test - * @returns true if there is an intersection - */ - isInFrustum(frustumPlanes) { - const center = this.centerWorld; - const radius = this.radiusWorld; - for (let i = 0; i < 6; i++) { - if (frustumPlanes[i].dotCoordinate(center) <= -radius) { - return false; - } - } - return true; - } - /** - * Tests if the bounding sphere center is in between the frustum planes. - * Used for optimistic fast inclusion. - * @param frustumPlanes defines the frustum planes to test - * @returns true if the sphere center is in between the frustum planes - */ - isCenterInFrustum(frustumPlanes) { - const center = this.centerWorld; - for (let i = 0; i < 6; i++) { - if (frustumPlanes[i].dotCoordinate(center) < 0) { - return false; - } - } - return true; - } - /** - * Tests if a point is inside the bounding sphere - * @param point defines the point to test - * @returns true if the point is inside the bounding sphere - */ - intersectsPoint(point) { - const squareDistance = math_vector_Vector3.DistanceSquared(this.centerWorld, point); - if (this.radiusWorld * this.radiusWorld < squareDistance) { - return false; - } - return true; - } - // Statics - /** - * Checks if two sphere intersect - * @param sphere0 sphere 0 - * @param sphere1 sphere 1 - * @returns true if the spheres intersect - */ - static Intersects(sphere0, sphere1) { - const squareDistance = math_vector_Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld); - const radiusSum = sphere0.radiusWorld + sphere1.radiusWorld; - if (radiusSum * radiusSum < squareDistance) { - return false; - } - return true; - } - /** - * Creates a sphere from a center and a radius - * @param center The center - * @param radius radius - * @param matrix Optional worldMatrix - * @returns The sphere - */ - static CreateFromCenterAndRadius(center, radius, matrix) { - this._TmpVector3[0].copyFrom(center); - this._TmpVector3[1].copyFromFloats(0, 0, radius); - this._TmpVector3[2].copyFrom(center); - this._TmpVector3[0].addInPlace(this._TmpVector3[1]); - this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]); - const sphere = new boundingSphere_BoundingSphere(this._TmpVector3[0], this._TmpVector3[2]); - if (matrix) { - sphere._worldMatrix = matrix; - } - else { - sphere._worldMatrix = math_vector_Matrix.Identity(); - } - return sphere; - } -} -boundingSphere_BoundingSphere._TmpVector3 = arrayTools_ArrayTools.BuildArray(3, math_vector_Vector3.Zero); -//# sourceMappingURL=boundingSphere.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Culling/boundingInfo.js - - - - - - -const _result0 = { min: 0, max: 0 }; -const _result1 = { min: 0, max: 0 }; -const computeBoxExtents = (axis, box, result) => { - const p = math_vector_Vector3.Dot(box.centerWorld, axis); - const r0 = Math.abs(math_vector_Vector3.Dot(box.directions[0], axis)) * box.extendSize.x; - const r1 = Math.abs(math_vector_Vector3.Dot(box.directions[1], axis)) * box.extendSize.y; - const r2 = Math.abs(math_vector_Vector3.Dot(box.directions[2], axis)) * box.extendSize.z; - const r = r0 + r1 + r2; - result.min = p - r; - result.max = p + r; -}; -const axisOverlap = (axis, box0, box1) => { - computeBoxExtents(axis, box0, _result0); - computeBoxExtents(axis, box1, _result1); - return !(_result0.min > _result1.max || _result1.min > _result0.max); -}; -/** - * Info for a bounding data of a mesh - */ -class boundingInfo_BoundingInfo { - /** - * Constructs bounding info - * @param minimum min vector of the bounding box/sphere - * @param maximum max vector of the bounding box/sphere - * @param worldMatrix defines the new world matrix - */ - constructor(minimum, maximum, worldMatrix) { - this._isLocked = false; - this.boundingBox = new boundingBox_BoundingBox(minimum, maximum, worldMatrix); - this.boundingSphere = new boundingSphere_BoundingSphere(minimum, maximum, worldMatrix); - } - /** - * Recreates the entire bounding info from scratch as if we call the constructor in place - * @param min defines the new minimum vector (in local space) - * @param max defines the new maximum vector (in local space) - * @param worldMatrix defines the new world matrix - */ - reConstruct(min, max, worldMatrix) { - this.boundingBox.reConstruct(min, max, worldMatrix); - this.boundingSphere.reConstruct(min, max, worldMatrix); - } - /** - * min vector of the bounding box/sphere - */ - get minimum() { - return this.boundingBox.minimum; - } - /** - * max vector of the bounding box/sphere - */ - get maximum() { - return this.boundingBox.maximum; - } - /** - * If the info is locked and won't be updated to avoid perf overhead - */ - get isLocked() { - return this._isLocked; - } - set isLocked(value) { - this._isLocked = value; - } - // Methods - /** - * Updates the bounding sphere and box - * @param world world matrix to be used to update - */ - update(world) { - if (this._isLocked) { - return; - } - this.boundingBox._update(world); - this.boundingSphere._update(world); - } - /** - * Recreate the bounding info to be centered around a specific point given a specific extend. - * @param center New center of the bounding info - * @param extend New extend of the bounding info - * @returns the current bounding info - */ - centerOn(center, extend) { - const minimum = boundingInfo_BoundingInfo._TmpVector3[0].copyFrom(center).subtractInPlace(extend); - const maximum = boundingInfo_BoundingInfo._TmpVector3[1].copyFrom(center).addInPlace(extend); - this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix()); - this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix()); - return this; - } - /** - * Grows the bounding info to include the given point. - * @param point The point that will be included in the current bounding info (in local space) - * @returns the current bounding info - */ - encapsulate(point) { - const minimum = math_vector_Vector3.Minimize(this.minimum, point); - const maximum = math_vector_Vector3.Maximize(this.maximum, point); - this.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix()); - return this; - } - /** - * Grows the bounding info to encapsulate the given bounding info. - * @param toEncapsulate The bounding info that will be encapsulated in the current bounding info - * @returns the current bounding info - */ - encapsulateBoundingInfo(toEncapsulate) { - const invw = math_vector_TmpVectors.Matrix[0]; - this.boundingBox.getWorldMatrix().invertToRef(invw); - const v = math_vector_TmpVectors.Vector3[0]; - math_vector_Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.minimumWorld, invw, v); - this.encapsulate(v); - math_vector_Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.maximumWorld, invw, v); - this.encapsulate(v); - return this; - } - /** - * Scale the current bounding info by applying a scale factor - * @param factor defines the scale factor to apply - * @returns the current bounding info - */ - scale(factor) { - this.boundingBox.scale(factor); - this.boundingSphere.scale(factor); - return this; - } - /** - * Returns `true` if the bounding info is within the frustum defined by the passed array of planes. - * @param frustumPlanes defines the frustum to test - * @param strategy defines the strategy to use for the culling (default is BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD) - * The different strategies available are: - * * BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD most accurate but slower @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_STANDARD - * * BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY faster but less accurate @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY - * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION - * * 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 - * @returns true if the bounding info is in the frustum planes - */ - isInFrustum(frustumPlanes, strategy = 0) { - const inclusionTest = strategy === 2 || strategy === 3; - if (inclusionTest) { - if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) { - return true; - } - } - if (!this.boundingSphere.isInFrustum(frustumPlanes)) { - return false; - } - const bSphereOnlyTest = strategy === 1 || strategy === 3; - if (bSphereOnlyTest) { - return true; - } - return this.boundingBox.isInFrustum(frustumPlanes); - } - /** - * Gets the world distance between the min and max points of the bounding box - */ - get diagonalLength() { - const boundingBox = this.boundingBox; - const diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, boundingInfo_BoundingInfo._TmpVector3[0]); - return diag.length(); - } - /** - * Checks if a cullable object (mesh...) is in the camera frustum - * Unlike isInFrustum this checks the full bounding box - * @param frustumPlanes Camera near/planes - * @returns true if the object is in frustum otherwise false - */ - isCompletelyInFrustum(frustumPlanes) { - return this.boundingBox.isCompletelyInFrustum(frustumPlanes); - } - /** - * @internal - */ - _checkCollision(collider) { - return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld); - } - /** - * Checks if a point is inside the bounding box and bounding sphere or the mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect - * @param point the point to check intersection with - * @returns if the point intersects - */ - intersectsPoint(point) { - if (!this.boundingSphere.centerWorld) { - return false; - } - if (!this.boundingSphere.intersectsPoint(point)) { - return false; - } - if (!this.boundingBox.intersectsPoint(point)) { - return false; - } - return true; - } - /** - * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect - * @param boundingInfo the bounding info to check intersection with - * @param precise if the intersection should be done using OBB - * @returns if the bounding info intersects - */ - intersects(boundingInfo, precise) { - if (!boundingSphere_BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) { - return false; - } - if (!boundingBox_BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) { - return false; - } - if (!precise) { - return true; - } - const box0 = this.boundingBox; - const box1 = boundingInfo.boundingBox; - if (!axisOverlap(box0.directions[0], box0, box1)) { - return false; - } - if (!axisOverlap(box0.directions[1], box0, box1)) { - return false; - } - if (!axisOverlap(box0.directions[2], box0, box1)) { - return false; - } - if (!axisOverlap(box1.directions[0], box0, box1)) { - return false; - } - if (!axisOverlap(box1.directions[1], box0, box1)) { - return false; - } - if (!axisOverlap(box1.directions[2], box0, box1)) { - return false; - } - if (!axisOverlap(math_vector_Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) { - return false; - } - if (!axisOverlap(math_vector_Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) { - return false; - } - if (!axisOverlap(math_vector_Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) { - return false; - } - if (!axisOverlap(math_vector_Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) { - return false; - } - if (!axisOverlap(math_vector_Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) { - return false; - } - if (!axisOverlap(math_vector_Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) { - return false; - } - if (!axisOverlap(math_vector_Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) { - return false; - } - if (!axisOverlap(math_vector_Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) { - return false; - } - if (!axisOverlap(math_vector_Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) { - return false; - } - return true; - } -} -boundingInfo_BoundingInfo._TmpVector3 = arrayTools_ArrayTools.BuildArray(2, math_vector_Vector3.Zero); -//# sourceMappingURL=boundingInfo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.functions.js - - - -// This helper class is only here so we can apply the nativeOverride decorator to functions. -class MathHelpers { - static extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum) { - for (let index = indexStart; index < indexStart + indexCount; index++) { - const offset = indices[index] * 3; - const x = positions[offset]; - const y = positions[offset + 1]; - const z = positions[offset + 2]; - minimum.minimizeInPlaceFromFloats(x, y, z); - maximum.maximizeInPlaceFromFloats(x, y, z); - } - } - static extractMinAndMax(positions, start, count, stride, minimum, maximum) { - for (let index = start, offset = start * stride; index < start + count; index++, offset += stride) { - const x = positions[offset]; - const y = positions[offset + 1]; - const z = positions[offset + 2]; - minimum.minimizeInPlaceFromFloats(x, y, z); - maximum.maximizeInPlaceFromFloats(x, y, z); - } - } -} -__decorate([ - nativeOverride.filter((...[positions, indices]) => !Array.isArray(positions) && !Array.isArray(indices)) - // eslint-disable-next-line @typescript-eslint/naming-convention -], MathHelpers, "extractMinAndMaxIndexed", null); -__decorate([ - nativeOverride.filter((...[positions]) => !Array.isArray(positions)) - // eslint-disable-next-line @typescript-eslint/naming-convention -], MathHelpers, "extractMinAndMax", null); -/** - * Extracts minimum and maximum values from a list of indexed positions - * @param positions defines the positions to use - * @param indices defines the indices to the positions - * @param indexStart defines the start index - * @param indexCount defines the end index - * @param bias defines bias value to add to the result - * @returns minimum and maximum values - */ -function extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, bias = null) { - const minimum = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - const maximum = new math_vector_Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); - MathHelpers.extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum); - if (bias) { - minimum.x -= minimum.x * bias.x + bias.y; - minimum.y -= minimum.y * bias.x + bias.y; - minimum.z -= minimum.z * bias.x + bias.y; - maximum.x += maximum.x * bias.x + bias.y; - maximum.y += maximum.y * bias.x + bias.y; - maximum.z += maximum.z * bias.x + bias.y; - } - return { - minimum: minimum, - maximum: maximum, - }; -} -/** - * Extracts minimum and maximum values from a list of positions - * @param positions defines the positions to use - * @param start defines the start index in the positions array - * @param count defines the number of positions to handle - * @param bias defines bias value to add to the result - * @param stride defines the stride size to use (distance between two positions in the positions array) - * @returns minimum and maximum values - */ -function extractMinAndMax(positions, start, count, bias = null, stride) { - const minimum = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - const maximum = new math_vector_Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); - if (!stride) { - stride = 3; - } - MathHelpers.extractMinAndMax(positions, start, count, stride, minimum, maximum); - if (bias) { - minimum.x -= minimum.x * bias.x + bias.y; - minimum.y -= minimum.y * bias.x + bias.y; - minimum.z -= minimum.z * bias.x + bias.y; - maximum.x += maximum.x * bias.x + bias.y; - maximum.y += maximum.y * bias.x + bias.y; - maximum.z += maximum.z * bias.x + bias.y; - } - return { - minimum: minimum, - maximum: maximum, - }; -} -//# sourceMappingURL=math.functions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/subMesh.js - - - - - - -/** - * Defines a subdivision inside a mesh - */ -class subMesh_SubMesh { - /** - * Gets material defines used by the effect associated to the sub mesh - */ - get materialDefines() { - var _a; - return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.defines : (_a = this._getDrawWrapper()) === null || _a === void 0 ? void 0 : _a.defines; - } - /** - * Sets material defines used by the effect associated to the sub mesh - */ - set materialDefines(defines) { - var _a; - const drawWrapper = (_a = this._mainDrawWrapperOverride) !== null && _a !== void 0 ? _a : this._getDrawWrapper(undefined, true); - drawWrapper.defines = defines; - } - /** - * @internal - */ - _getDrawWrapper(passId, createIfNotExisting = false) { - passId = passId !== null && passId !== void 0 ? passId : this._engine.currentRenderPassId; - let drawWrapper = this._drawWrappers[passId]; - if (!drawWrapper && createIfNotExisting) { - this._drawWrappers[passId] = drawWrapper = new drawWrapper_DrawWrapper(this._mesh.getScene().getEngine()); - } - return drawWrapper; - } - /** - * @internal - */ - _removeDrawWrapper(passId, disposeWrapper = true) { - var _a; - if (disposeWrapper) { - (_a = this._drawWrappers[passId]) === null || _a === void 0 ? void 0 : _a.dispose(); - } - this._drawWrappers[passId] = undefined; - } - /** - * Gets associated (main) effect (possibly the effect override if defined) - */ - get effect() { - var _a, _b; - return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.effect : (_b = (_a = this._getDrawWrapper()) === null || _a === void 0 ? void 0 : _a.effect) !== null && _b !== void 0 ? _b : null; - } - /** @internal */ - get _drawWrapper() { - var _a; - return (_a = this._mainDrawWrapperOverride) !== null && _a !== void 0 ? _a : this._getDrawWrapper(undefined, true); - } - /** @internal */ - get _drawWrapperOverride() { - return this._mainDrawWrapperOverride; - } - /** - * @internal - */ - _setMainDrawWrapperOverride(wrapper) { - this._mainDrawWrapperOverride = wrapper; - } - /** - * Sets associated effect (effect used to render this submesh) - * @param effect defines the effect to associate with - * @param defines defines the set of defines used to compile this effect - * @param materialContext material context associated to the effect - * @param resetContext true to reset the draw context - */ - setEffect(effect, defines = null, materialContext, resetContext = true) { - const drawWrapper = this._drawWrapper; - drawWrapper.setEffect(effect, defines, resetContext); - if (materialContext !== undefined) { - drawWrapper.materialContext = materialContext; - } - if (!effect) { - drawWrapper.defines = null; - drawWrapper.materialContext = undefined; - } - } - /** - * Resets the draw wrappers cache - * @param passId If provided, releases only the draw wrapper corresponding to this render pass id - */ - resetDrawCache(passId) { - if (this._drawWrappers) { - if (passId !== undefined) { - this._removeDrawWrapper(passId); - return; - } - else { - for (const drawWrapper of this._drawWrappers) { - drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.dispose(); - } - } - } - this._drawWrappers = []; - } - /** - * Add a new submesh to a mesh - * @param materialIndex defines the material index to use - * @param verticesStart defines vertex index start - * @param verticesCount defines vertices count - * @param indexStart defines index start - * @param indexCount defines indices count - * @param mesh defines the parent mesh - * @param renderingMesh defines an optional rendering mesh - * @param createBoundingBox defines if bounding box should be created for this submesh - * @returns the new submesh - */ - static AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox = true) { - return new subMesh_SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox); - } - /** - * Creates a new submesh - * @param materialIndex defines the material index to use - * @param verticesStart defines vertex index start - * @param verticesCount defines vertices count - * @param indexStart defines index start - * @param indexCount defines indices count - * @param mesh defines the parent mesh - * @param renderingMesh defines an optional rendering mesh - * @param createBoundingBox defines if bounding box should be created for this submesh - * @param addToMesh defines a boolean indicating that the submesh must be added to the mesh.subMeshes array (true by default) - */ - constructor( - /** the material index to use */ - materialIndex, - /** vertex index start */ - verticesStart, - /** vertices count */ - verticesCount, - /** index start */ - indexStart, - /** indices count */ - indexCount, mesh, renderingMesh, createBoundingBox = true, addToMesh = true) { - this.materialIndex = materialIndex; - this.verticesStart = verticesStart; - this.verticesCount = verticesCount; - this.indexStart = indexStart; - this.indexCount = indexCount; - this._mainDrawWrapperOverride = null; - /** @internal */ - this._linesIndexCount = 0; - this._linesIndexBuffer = null; - /** @internal */ - this._lastColliderWorldVertices = null; - /** @internal */ - this._lastColliderTransformMatrix = null; - /** @internal */ - this._wasDispatched = false; - /** @internal */ - this._renderId = 0; - /** @internal */ - this._alphaIndex = 0; - /** @internal */ - this._distanceToCamera = 0; - this._currentMaterial = null; - this._mesh = mesh; - this._renderingMesh = renderingMesh || mesh; - if (addToMesh) { - mesh.subMeshes.push(this); - } - this._engine = this._mesh.getScene().getEngine(); - this.resetDrawCache(); - this._trianglePlanes = []; - this._id = mesh.subMeshes.length - 1; - if (createBoundingBox) { - this.refreshBoundingInfo(); - mesh.computeWorldMatrix(true); - } - } - /** - * Returns true if this submesh covers the entire parent mesh - * @ignorenaming - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - get IsGlobal() { - return this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices() && this.indexStart === 0 && this.indexCount === this._mesh.getTotalIndices(); - } - /** - * Returns the submesh BoundingInfo object - * @returns current bounding info (or mesh's one if the submesh is global) - */ - getBoundingInfo() { - if (this.IsGlobal) { - return this._mesh.getBoundingInfo(); - } - return this._boundingInfo; - } - /** - * Sets the submesh BoundingInfo - * @param boundingInfo defines the new bounding info to use - * @returns the SubMesh - */ - setBoundingInfo(boundingInfo) { - this._boundingInfo = boundingInfo; - return this; - } - /** - * Returns the mesh of the current submesh - * @returns the parent mesh - */ - getMesh() { - return this._mesh; - } - /** - * Returns the rendering mesh of the submesh - * @returns the rendering mesh (could be different from parent mesh) - */ - getRenderingMesh() { - return this._renderingMesh; - } - /** - * Returns the replacement mesh of the submesh - * @returns the replacement mesh (could be different from parent mesh) - */ - getReplacementMesh() { - return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null; - } - /** - * Returns the effective mesh of the submesh - * @returns the effective mesh (could be different from parent mesh) - */ - getEffectiveMesh() { - const replacementMesh = this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null; - return replacementMesh ? replacementMesh : this._renderingMesh; - } - /** - * Returns the submesh material - * @param getDefaultMaterial Defines whether or not to get the default material if nothing has been defined. - * @returns null or the current material - */ - getMaterial(getDefaultMaterial = true) { - var _a; - const rootMaterial = (_a = this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)) !== null && _a !== void 0 ? _a : this._renderingMesh.material; - if (!rootMaterial) { - return getDefaultMaterial ? this._mesh.getScene().defaultMaterial : null; - } - else if (this._isMultiMaterial(rootMaterial)) { - const effectiveMaterial = rootMaterial.getSubMaterial(this.materialIndex); - if (this._currentMaterial !== effectiveMaterial) { - this._currentMaterial = effectiveMaterial; - this.resetDrawCache(); - } - return effectiveMaterial; - } - return rootMaterial; - } - _isMultiMaterial(material) { - return material.getSubMaterial !== undefined; - } - // Methods - /** - * Sets a new updated BoundingInfo object to the submesh - * @param data defines an optional position array to use to determine the bounding info - * @returns the SubMesh - */ - refreshBoundingInfo(data = null) { - this._lastColliderWorldVertices = null; - if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) { - return this; - } - if (!data) { - data = this._renderingMesh.getVerticesData(buffer_VertexBuffer.PositionKind); - } - if (!data) { - this._boundingInfo = this._mesh.getBoundingInfo(); - return this; - } - const indices = this._renderingMesh.getIndices(); - let extend; - //is this the only submesh? - if (this.indexStart === 0 && this.indexCount === indices.length) { - const boundingInfo = this._renderingMesh.getBoundingInfo(); - //the rendering mesh's bounding info can be used, it is the standard submesh for all indices. - extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() }; - } - else { - extend = extractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias); - } - if (this._boundingInfo) { - this._boundingInfo.reConstruct(extend.minimum, extend.maximum); - } - else { - this._boundingInfo = new boundingInfo_BoundingInfo(extend.minimum, extend.maximum); - } - return this; - } - /** - * @internal - */ - _checkCollision(collider) { - const boundingInfo = this.getBoundingInfo(); - return boundingInfo._checkCollision(collider); - } - /** - * Updates the submesh BoundingInfo - * @param world defines the world matrix to use to update the bounding info - * @returns the submesh - */ - updateBoundingInfo(world) { - let boundingInfo = this.getBoundingInfo(); - if (!boundingInfo) { - this.refreshBoundingInfo(); - boundingInfo = this.getBoundingInfo(); - } - if (boundingInfo) { - boundingInfo.update(world); - } - return this; - } - /** - * True is the submesh bounding box intersects the frustum defined by the passed array of planes. - * @param frustumPlanes defines the frustum planes - * @returns true if the submesh is intersecting with the frustum - */ - isInFrustum(frustumPlanes) { - const boundingInfo = this.getBoundingInfo(); - if (!boundingInfo) { - return false; - } - return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy); - } - /** - * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes - * @param frustumPlanes defines the frustum planes - * @returns true if the submesh is inside the frustum - */ - isCompletelyInFrustum(frustumPlanes) { - const boundingInfo = this.getBoundingInfo(); - if (!boundingInfo) { - return false; - } - return boundingInfo.isCompletelyInFrustum(frustumPlanes); - } - /** - * Renders the submesh - * @param enableAlphaMode defines if alpha needs to be used - * @returns the submesh - */ - render(enableAlphaMode) { - this._renderingMesh.render(this, enableAlphaMode, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : undefined); - return this; - } - /** - * @internal - */ - _getLinesIndexBuffer(indices, engine) { - if (!this._linesIndexBuffer) { - const linesIndices = []; - for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) { - linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]); - } - this._linesIndexBuffer = engine.createIndexBuffer(linesIndices); - this._linesIndexCount = linesIndices.length; - } - return this._linesIndexBuffer; - } - /** - * Checks if the submesh intersects with a ray - * @param ray defines the ray to test - * @returns true is the passed ray intersects the submesh bounding box - */ - canIntersects(ray) { - const boundingInfo = this.getBoundingInfo(); - if (!boundingInfo) { - return false; - } - return ray.intersectsBox(boundingInfo.boundingBox); - } - /** - * Intersects current submesh with a ray - * @param ray defines the ray to test - * @param positions defines mesh's positions array - * @param indices defines mesh's indices array - * @param fastCheck defines if the first intersection will be used (and not the closest) - * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected - * @returns intersection info or null if no intersection - */ - intersects(ray, positions, indices, fastCheck, trianglePredicate) { - const material = this.getMaterial(); - if (!material) { - return null; - } - let step = 3; - let checkStopper = false; - switch (material.fillMode) { - case 3: - case 5: - case 6: - case 8: - return null; - case 7: - step = 1; - checkStopper = true; - break; - default: - break; - } - // LineMesh first as it's also a Mesh... - if (material.fillMode === 4) { - // Check if mesh is unindexed - if (!indices.length) { - return this._intersectUnIndexedLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck); - } - return this._intersectLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck); - } - else { - // Check if mesh is unindexed - if (!indices.length && this._mesh._unIndexed) { - return this._intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate); - } - return this._intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate); - } - } - /** - * @internal - */ - _intersectLines(ray, positions, indices, intersectionThreshold, fastCheck) { - let intersectInfo = null; - // Line test - for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) { - const p0 = positions[indices[index]]; - const p1 = positions[indices[index + 1]]; - const length = ray.intersectionSegment(p0, p1, intersectionThreshold); - if (length < 0) { - continue; - } - if (fastCheck || !intersectInfo || length < intersectInfo.distance) { - intersectInfo = new IntersectionInfo(null, null, length); - intersectInfo.faceId = index / 2; - if (fastCheck) { - break; - } - } - } - return intersectInfo; - } - /** - * @internal - */ - _intersectUnIndexedLines(ray, positions, indices, intersectionThreshold, fastCheck) { - let intersectInfo = null; - // Line test - for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 2) { - const p0 = positions[index]; - const p1 = positions[index + 1]; - const length = ray.intersectionSegment(p0, p1, intersectionThreshold); - if (length < 0) { - continue; - } - if (fastCheck || !intersectInfo || length < intersectInfo.distance) { - intersectInfo = new IntersectionInfo(null, null, length); - intersectInfo.faceId = index / 2; - if (fastCheck) { - break; - } - } - } - return intersectInfo; - } - /** - * @internal - */ - _intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate) { - let intersectInfo = null; - // Triangles test - let faceId = -1; - for (let index = this.indexStart; index < this.indexStart + this.indexCount - (3 - step); index += step) { - faceId++; - const indexA = indices[index]; - const indexB = indices[index + 1]; - const indexC = indices[index + 2]; - if (checkStopper && indexC === 0xffffffff) { - index += 2; - continue; - } - const p0 = positions[indexA]; - const p1 = positions[indexB]; - const p2 = positions[indexC]; - // stay defensive and don't check against undefined positions. - if (!p0 || !p1 || !p2) { - continue; - } - if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, indexA, indexB, indexC)) { - continue; - } - const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2); - if (currentIntersectInfo) { - if (currentIntersectInfo.distance < 0) { - continue; - } - if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { - intersectInfo = currentIntersectInfo; - intersectInfo.faceId = faceId; - if (fastCheck) { - break; - } - } - } - } - return intersectInfo; - } - /** - * @internal - */ - _intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate) { - let intersectInfo = null; - // Triangles test - for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) { - const p0 = positions[index]; - const p1 = positions[index + 1]; - const p2 = positions[index + 2]; - if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, -1, -1, -1)) { - continue; - } - const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2); - if (currentIntersectInfo) { - if (currentIntersectInfo.distance < 0) { - continue; - } - if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { - intersectInfo = currentIntersectInfo; - intersectInfo.faceId = index / 3; - if (fastCheck) { - break; - } - } - } - } - return intersectInfo; - } - /** @internal */ - _rebuild() { - if (this._linesIndexBuffer) { - this._linesIndexBuffer = null; - } - } - // Clone - /** - * Creates a new submesh from the passed mesh - * @param newMesh defines the new hosting mesh - * @param newRenderingMesh defines an optional rendering mesh - * @returns the new submesh - */ - clone(newMesh, newRenderingMesh) { - const result = new subMesh_SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false); - if (!this.IsGlobal) { - const boundingInfo = this.getBoundingInfo(); - if (!boundingInfo) { - return result; - } - result._boundingInfo = new boundingInfo_BoundingInfo(boundingInfo.minimum, boundingInfo.maximum); - } - return result; - } - // Dispose - /** - * Release associated resources - */ - dispose() { - if (this._linesIndexBuffer) { - this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer); - this._linesIndexBuffer = null; - } - // Remove from mesh - const index = this._mesh.subMeshes.indexOf(this); - this._mesh.subMeshes.splice(index, 1); - this.resetDrawCache(); - } - /** - * Gets the class name - * @returns the string "SubMesh". - */ - getClassName() { - return "SubMesh"; - } - // Statics - /** - * Creates a new submesh from indices data - * @param materialIndex the index of the main mesh material - * @param startIndex the index where to start the copy in the mesh indices array - * @param indexCount the number of indices to copy then from the startIndex - * @param mesh the main mesh to create the submesh from - * @param renderingMesh the optional rendering mesh - * @param createBoundingBox defines if bounding box should be created for this submesh - * @returns a new submesh - */ - static CreateFromIndices(materialIndex, startIndex, indexCount, mesh, renderingMesh, createBoundingBox = true) { - let minVertexIndex = Number.MAX_VALUE; - let maxVertexIndex = -Number.MAX_VALUE; - const whatWillRender = renderingMesh || mesh; - const indices = whatWillRender.getIndices(); - for (let index = startIndex; index < startIndex + indexCount; index++) { - const vertexIndex = indices[index]; - if (vertexIndex < minVertexIndex) { - minVertexIndex = vertexIndex; - } - if (vertexIndex > maxVertexIndex) { - maxVertexIndex = vertexIndex; - } - } - return new subMesh_SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh, createBoundingBox); - } -} -//# sourceMappingURL=subMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/mesh.vertexData.js - - - - - - - - - - -/** Class used to attach material info to sub section of a vertex data class */ -class VertexDataMaterialInfo { -} -/** - * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance - */ -class mesh_vertexData_VertexData { - /** - * Creates a new VertexData - */ - constructor() { - /** - * Gets the unique ID of this vertex Data - */ - this.uniqueId = 0; - /** - * Metadata used to store contextual values - */ - this.metadata = {}; - this._applyTo = makeSyncFunction(this._applyToCoroutine.bind(this)); - this.uniqueId = mesh_vertexData_VertexData._UniqueIDGenerator; - mesh_vertexData_VertexData._UniqueIDGenerator++; - } - /** - * Uses the passed data array to set the set the values for the specified kind of data - * @param data a linear array of floating numbers - * @param kind the type of data that is being set, eg positions, colors etc - */ - set(data, kind) { - if (!data.length) { - logger_Logger.Warn(`Setting vertex data kind '${kind}' with an empty array`); - } - switch (kind) { - case buffer_VertexBuffer.PositionKind: - this.positions = data; - break; - case buffer_VertexBuffer.NormalKind: - this.normals = data; - break; - case buffer_VertexBuffer.TangentKind: - this.tangents = data; - break; - case buffer_VertexBuffer.UVKind: - this.uvs = data; - break; - case buffer_VertexBuffer.UV2Kind: - this.uvs2 = data; - break; - case buffer_VertexBuffer.UV3Kind: - this.uvs3 = data; - break; - case buffer_VertexBuffer.UV4Kind: - this.uvs4 = data; - break; - case buffer_VertexBuffer.UV5Kind: - this.uvs5 = data; - break; - case buffer_VertexBuffer.UV6Kind: - this.uvs6 = data; - break; - case buffer_VertexBuffer.ColorKind: - this.colors = data; - break; - case buffer_VertexBuffer.MatricesIndicesKind: - this.matricesIndices = data; - break; - case buffer_VertexBuffer.MatricesWeightsKind: - this.matricesWeights = data; - break; - case buffer_VertexBuffer.MatricesIndicesExtraKind: - this.matricesIndicesExtra = data; - break; - case buffer_VertexBuffer.MatricesWeightsExtraKind: - this.matricesWeightsExtra = data; - break; - } - } - /** - * Associates the vertexData to the passed Mesh. - * Sets it as updatable or not (default `false`) - * @param mesh the mesh the vertexData is applied to - * @param updatable when used and having the value true allows new data to update the vertexData - * @returns the VertexData - */ - applyToMesh(mesh, updatable) { - this._applyTo(mesh, updatable, false); - return this; - } - /** - * Associates the vertexData to the passed Geometry. - * Sets it as updatable or not (default `false`) - * @param geometry the geometry the vertexData is applied to - * @param updatable when used and having the value true allows new data to update the vertexData - * @returns VertexData - */ - applyToGeometry(geometry, updatable) { - this._applyTo(geometry, updatable, false); - return this; - } - /** - * Updates the associated mesh - * @param mesh the mesh to be updated - * @returns VertexData - */ - updateMesh(mesh) { - this._update(mesh); - return this; - } - /** - * Updates the associated geometry - * @param geometry the geometry to be updated - * @returns VertexData. - */ - updateGeometry(geometry) { - this._update(geometry); - return this; - } - /** - * @internal - */ - *_applyToCoroutine(meshOrGeometry, updatable = false, isAsync) { - if (this.positions) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.PositionKind, this.positions, updatable); - if (isAsync) { - yield; - } - } - if (this.normals) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.NormalKind, this.normals, updatable); - if (isAsync) { - yield; - } - } - if (this.tangents) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.TangentKind, this.tangents, updatable); - if (isAsync) { - yield; - } - } - if (this.uvs) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.UVKind, this.uvs, updatable); - if (isAsync) { - yield; - } - } - if (this.uvs2) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.UV2Kind, this.uvs2, updatable); - if (isAsync) { - yield; - } - } - if (this.uvs3) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.UV3Kind, this.uvs3, updatable); - if (isAsync) { - yield; - } - } - if (this.uvs4) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.UV4Kind, this.uvs4, updatable); - if (isAsync) { - yield; - } - } - if (this.uvs5) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.UV5Kind, this.uvs5, updatable); - if (isAsync) { - yield; - } - } - if (this.uvs6) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.UV6Kind, this.uvs6, updatable); - if (isAsync) { - yield; - } - } - if (this.colors) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.ColorKind, this.colors, updatable); - if (isAsync) { - yield; - } - } - if (this.matricesIndices) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable); - if (isAsync) { - yield; - } - } - if (this.matricesWeights) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable); - if (isAsync) { - yield; - } - } - if (this.matricesIndicesExtra) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable); - if (isAsync) { - yield; - } - } - if (this.matricesWeightsExtra) { - meshOrGeometry.setVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable); - if (isAsync) { - yield; - } - } - if (this.indices) { - meshOrGeometry.setIndices(this.indices, null, updatable); - if (isAsync) { - yield; - } - } - else { - meshOrGeometry.setIndices([], null); - } - if (meshOrGeometry.subMeshes && this.materialInfos && this.materialInfos.length > 1) { - const mesh = meshOrGeometry; - mesh.subMeshes = []; - for (const matInfo of this.materialInfos) { - new subMesh_SubMesh(matInfo.materialIndex, matInfo.verticesStart, matInfo.verticesCount, matInfo.indexStart, matInfo.indexCount, mesh); - } - } - return this; - } - _update(meshOrGeometry, updateExtends, makeItUnique) { - if (this.positions) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique); - } - if (this.normals) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique); - } - if (this.tangents) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique); - } - if (this.uvs) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique); - } - if (this.uvs2) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique); - } - if (this.uvs3) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique); - } - if (this.uvs4) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique); - } - if (this.uvs5) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique); - } - if (this.uvs6) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique); - } - if (this.colors) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique); - } - if (this.matricesIndices) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique); - } - if (this.matricesWeights) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique); - } - if (this.matricesIndicesExtra) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique); - } - if (this.matricesWeightsExtra) { - meshOrGeometry.updateVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique); - } - if (this.indices) { - meshOrGeometry.setIndices(this.indices, null); - } - return this; - } - static _TransformVector3Coordinates(coordinates, transformation, offset = 0, length = coordinates.length) { - const coordinate = math_vector_TmpVectors.Vector3[0]; - const transformedCoordinate = math_vector_TmpVectors.Vector3[1]; - for (let index = offset; index < offset + length; index += 3) { - math_vector_Vector3.FromArrayToRef(coordinates, index, coordinate); - math_vector_Vector3.TransformCoordinatesToRef(coordinate, transformation, transformedCoordinate); - coordinates[index] = transformedCoordinate.x; - coordinates[index + 1] = transformedCoordinate.y; - coordinates[index + 2] = transformedCoordinate.z; - } - } - static _TransformVector3Normals(normals, transformation, offset = 0, length = normals.length) { - const normal = math_vector_TmpVectors.Vector3[0]; - const transformedNormal = math_vector_TmpVectors.Vector3[1]; - for (let index = offset; index < offset + length; index += 3) { - math_vector_Vector3.FromArrayToRef(normals, index, normal); - math_vector_Vector3.TransformNormalToRef(normal, transformation, transformedNormal); - normals[index] = transformedNormal.x; - normals[index + 1] = transformedNormal.y; - normals[index + 2] = transformedNormal.z; - } - } - static _TransformVector4Normals(normals, transformation, offset = 0, length = normals.length) { - const normal = math_vector_TmpVectors.Vector4[0]; - const transformedNormal = math_vector_TmpVectors.Vector4[1]; - for (let index = offset; index < offset + length; index += 4) { - math_vector_Vector4.FromArrayToRef(normals, index, normal); - math_vector_Vector4.TransformNormalToRef(normal, transformation, transformedNormal); - normals[index] = transformedNormal.x; - normals[index + 1] = transformedNormal.y; - normals[index + 2] = transformedNormal.z; - normals[index + 3] = transformedNormal.w; - } - } - static _FlipFaces(indices, offset = 0, length = indices.length) { - for (let index = offset; index < offset + length; index += 3) { - const tmp = indices[index + 1]; - indices[index + 1] = indices[index + 2]; - indices[index + 2] = tmp; - } - } - /** - * Transforms each position and each normal of the vertexData according to the passed Matrix - * @param matrix the transforming matrix - * @returns the VertexData - */ - transform(matrix) { - const flip = matrix.determinant() < 0; - if (this.positions) { - mesh_vertexData_VertexData._TransformVector3Coordinates(this.positions, matrix); - } - if (this.normals) { - mesh_vertexData_VertexData._TransformVector3Normals(this.normals, matrix); - } - if (this.tangents) { - mesh_vertexData_VertexData._TransformVector4Normals(this.tangents, matrix); - } - if (flip && this.indices) { - mesh_vertexData_VertexData._FlipFaces(this.indices); - } - return this; - } - /** - * Generates an array of vertex data where each vertex data only has one material info - * @returns An array of VertexData - */ - splitBasedOnMaterialID() { - if (!this.materialInfos || this.materialInfos.length < 2) { - return [this]; - } - const result = new Array(); - for (const materialInfo of this.materialInfos) { - const vertexData = new mesh_vertexData_VertexData(); - if (this.positions) { - vertexData.positions = this.positions.slice(materialInfo.verticesStart * 3, (materialInfo.verticesCount + materialInfo.verticesStart) * 3); - } - if (this.normals) { - vertexData.normals = this.normals.slice(materialInfo.verticesStart * 3, (materialInfo.verticesCount + materialInfo.verticesStart) * 3); - } - if (this.tangents) { - vertexData.tangents = this.tangents.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); - } - if (this.colors) { - vertexData.colors = this.colors.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); - } - if (this.uvs) { - vertexData.uvs = this.uvs.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); - } - if (this.uvs2) { - vertexData.uvs2 = this.uvs2.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); - } - if (this.uvs3) { - vertexData.uvs3 = this.uvs3.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); - } - if (this.uvs4) { - vertexData.uvs4 = this.uvs4.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); - } - if (this.uvs5) { - vertexData.uvs5 = this.uvs5.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); - } - if (this.uvs6) { - vertexData.uvs6 = this.uvs6.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); - } - if (this.matricesIndices) { - vertexData.matricesIndices = this.matricesIndices.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); - } - if (this.matricesIndicesExtra) { - vertexData.matricesIndicesExtra = this.matricesIndicesExtra.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); - } - if (this.matricesWeights) { - vertexData.matricesWeights = this.matricesWeights.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); - } - if (this.matricesWeightsExtra) { - vertexData.matricesWeightsExtra = this.matricesWeightsExtra.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); - } - if (this.indices) { - vertexData.indices = []; - for (let index = materialInfo.indexStart; index < materialInfo.indexStart + materialInfo.indexCount; index++) { - vertexData.indices.push(this.indices[index] - materialInfo.verticesStart); - } - } - const newMaterialInfo = new VertexDataMaterialInfo(); - newMaterialInfo.indexStart = 0; - newMaterialInfo.indexCount = vertexData.indices ? vertexData.indices.length : 0; - newMaterialInfo.materialIndex = materialInfo.materialIndex; - newMaterialInfo.verticesStart = 0; - newMaterialInfo.verticesCount = (vertexData.positions ? vertexData.positions.length : 0) / 3; - vertexData.materialInfos = [newMaterialInfo]; - result.push(vertexData); - } - return result; - } - /** - * Merges the passed VertexData into the current one - * @param others the VertexData to be merged into the current one - * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array - * @param forceCloneIndices defines a boolean indicating if indices are forced to be cloned - * @param mergeMaterialIds defines a boolean indicating if we need to merge the material infos - * @param enableCompletion defines a boolean indicating if the vertex data should be completed to be compatible - * @returns the modified VertexData - */ - merge(others, use32BitsIndices = false, forceCloneIndices = false, mergeMaterialIds = false, enableCompletion = false) { - const vertexDatas = Array.isArray(others) - ? others.map((other) => { - return { vertexData: other }; - }) - : [{ vertexData: others }]; - return runCoroutineSync(this._mergeCoroutine(undefined, vertexDatas, use32BitsIndices, false, forceCloneIndices, mergeMaterialIds, enableCompletion)); - } - /** - * @internal - */ - *_mergeCoroutine(transform, vertexDatas, use32BitsIndices = false, isAsync, forceCloneIndices, mergeMaterialIds = false, enableCompletion = false) { - var _a, _b, _c, _d; - this._validate(); - let others = vertexDatas.map((vertexData) => vertexData.vertexData); - // eslint-disable-next-line @typescript-eslint/no-this-alias - let root = this; - for (const other of others) { - if (!other) { - continue; - } - other._validate(); - if (!enableCompletion) { - if (!this.normals !== !other.normals || - !this.tangents !== !other.tangents || - !this.uvs !== !other.uvs || - !this.uvs2 !== !other.uvs2 || - !this.uvs3 !== !other.uvs3 || - !this.uvs4 !== !other.uvs4 || - !this.uvs5 !== !other.uvs5 || - !this.uvs6 !== !other.uvs6 || - !this.colors !== !other.colors || - !this.matricesIndices !== !other.matricesIndices || - !this.matricesWeights !== !other.matricesWeights || - !this.matricesIndicesExtra !== !other.matricesIndicesExtra || - !this.matricesWeightsExtra !== !other.matricesWeightsExtra) { - throw new Error("Cannot merge vertex data that do not have the same set of attributes"); - } - } - else { - if (!this.normals !== !other.normals) { - if (!this.normals) { - this.normals = Array.from(other.normals); - } - else { - other.normals = Array.from(this.normals); - } - } - if (!this.tangents !== !other.tangents) { - if (!this.tangents) { - this.tangents = Array.from(other.tangents); - } - else { - other.tangents = Array.from(this.tangents); - } - } - if (!this.uvs !== !other.uvs) { - if (!this.uvs) { - this.uvs = Array.from(other.uvs); - } - else { - other.uvs = Array.from(this.uvs); - } - } - if (!this.uvs2 !== !other.uvs2) { - if (!this.uvs2) { - this.uvs2 = Array.from(other.uvs2); - } - else { - other.uvs2 = Array.from(this.uvs2); - } - } - if (!this.uvs3 !== !other.uvs3) { - if (!this.uvs3) { - this.uvs3 = Array.from(other.uvs3); - } - else { - other.uvs3 = Array.from(this.uvs3); - } - } - if (!this.uvs4 !== !other.uvs4) { - if (!this.uvs4) { - this.uvs4 = Array.from(other.uvs4); - } - else { - other.uvs4 = Array.from(this.uvs4); - } - } - if (!this.uvs5 !== !other.uvs5) { - if (!this.uvs5) { - this.uvs5 = Array.from(other.uvs5); - } - else { - other.uvs5 = Array.from(this.uvs5); - } - } - if (!this.uvs6 !== !other.uvs6) { - if (!this.uvs6) { - this.uvs6 = Array.from(other.uvs6); - } - else { - other.uvs6 = Array.from(this.uvs6); - } - } - if (!this.colors !== !other.colors) { - if (!this.colors) { - this.colors = Array.from(other.colors); - } - else { - other.colors = Array.from(this.colors); - } - } - if (!this.matricesIndices !== !other.matricesIndices) { - if (!this.matricesIndices) { - this.matricesIndices = Array.from(other.matricesIndices); - } - else { - other.matricesIndices = Array.from(this.matricesIndices); - } - } - if (!this.matricesWeights !== !other.matricesWeights) { - if (!this.matricesWeights) { - this.matricesWeights = Array.from(other.matricesWeights); - } - else { - other.matricesWeights = Array.from(this.matricesWeights); - } - } - if (!this.matricesIndicesExtra !== !other.matricesIndicesExtra) { - if (!this.matricesIndicesExtra) { - this.matricesIndicesExtra = Array.from(other.matricesIndicesExtra); - } - else { - other.matricesIndicesExtra = Array.from(this.matricesIndicesExtra); - } - } - if (!this.matricesWeightsExtra !== !other.matricesWeightsExtra) { - if (!this.matricesWeightsExtra) { - this.matricesWeightsExtra = Array.from(other.matricesWeightsExtra); - } - else { - other.matricesWeightsExtra = Array.from(this.matricesWeightsExtra); - } - } - } - } - if (mergeMaterialIds) { - // Merge material infos - let materialIndex = 0; - let indexOffset = 0; - let vertexOffset = 0; - const materialInfos = []; - let currentMaterialInfo = null; - const vertexDataList = []; - // We need to split vertexData with more than one materialInfo - for (const split of this.splitBasedOnMaterialID()) { - vertexDataList.push({ vertexData: split, transform: transform }); - } - for (const vertexData of vertexDatas) { - for (const split of vertexData.vertexData.splitBasedOnMaterialID()) { - vertexDataList.push({ vertexData: split, transform: vertexData.transform }); - } - } - // Sort by material IDs - vertexDataList.sort((a, b) => { - const matInfoA = a.vertexData.materialInfos ? a.vertexData.materialInfos[0].materialIndex : 0; - const matInfoB = b.vertexData.materialInfos ? b.vertexData.materialInfos[0].materialIndex : 0; - if (matInfoA > matInfoB) { - return 1; - } - if (matInfoA === matInfoB) { - return 0; - } - return -1; - }); - // Build the new material info - for (const vertexDataSource of vertexDataList) { - const vertexData = vertexDataSource.vertexData; - if (vertexData.materialInfos) { - materialIndex = vertexData.materialInfos[0].materialIndex; - } - else { - materialIndex = 0; - } - if (currentMaterialInfo && currentMaterialInfo.materialIndex === materialIndex) { - currentMaterialInfo.indexCount += vertexData.indices.length; - currentMaterialInfo.verticesCount += vertexData.positions.length / 3; - } - else { - const materialInfo = new VertexDataMaterialInfo(); - materialInfo.materialIndex = materialIndex; - materialInfo.indexStart = indexOffset; - materialInfo.indexCount = vertexData.indices.length; - materialInfo.verticesStart = vertexOffset; - materialInfo.verticesCount = vertexData.positions.length / 3; - materialInfos.push(materialInfo); - currentMaterialInfo = materialInfo; - } - indexOffset += vertexData.indices.length; - vertexOffset += vertexData.positions.length / 3; - } - // Extract sorted values - const first = vertexDataList.splice(0, 1)[0]; - root = first.vertexData; - transform = first.transform; - others = vertexDataList.map((v) => v.vertexData); - vertexDatas = vertexDataList; - this.materialInfos = materialInfos; - } - // Merge geometries - 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 = root.indices) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0); - const sliceIndices = forceCloneIndices || others.some((vertexData) => vertexData.indices === root.indices); - let indices = sliceIndices ? (_c = root.indices) === null || _c === void 0 ? void 0 : _c.slice() : root.indices; - if (totalIndices > 0) { - let indicesOffset = (_d = indices === null || indices === void 0 ? void 0 : indices.length) !== null && _d !== void 0 ? _d : 0; - if (!indices) { - indices = new Array(totalIndices); - } - if (indices.length !== totalIndices) { - if (Array.isArray(indices)) { - indices.length = totalIndices; - } - else { - const temp = use32BitsIndices || indices instanceof Uint32Array ? new Uint32Array(totalIndices) : new Uint16Array(totalIndices); - temp.set(indices); - indices = temp; - } - if (transform && transform.determinant() < 0) { - mesh_vertexData_VertexData._FlipFaces(indices, 0, indicesOffset); - } - } - let positionsOffset = root.positions ? root.positions.length / 3 : 0; - for (const { vertexData: other, transform } of vertexDatas) { - if (other.indices) { - for (let index = 0; index < other.indices.length; index++) { - indices[indicesOffset + index] = other.indices[index] + positionsOffset; - } - if (transform && transform.determinant() < 0) { - mesh_vertexData_VertexData._FlipFaces(indices, indicesOffset, other.indices.length); - } - // The call to _validate already checked for positions - positionsOffset += other.positions.length / 3; - indicesOffset += other.indices.length; - if (isAsync) { - yield; - } - } - } - } - this.indices = indices; - this.positions = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.PositionKind, root.positions, transform, vertexDatas.map((other) => [other.vertexData.positions, other.transform])); - if (isAsync) { - yield; - } - if (root.normals) { - this.normals = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.NormalKind, root.normals, transform, vertexDatas.map((other) => [other.vertexData.normals, other.transform])); - if (isAsync) { - yield; - } - } - if (root.tangents) { - this.tangents = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.TangentKind, root.tangents, transform, vertexDatas.map((other) => [other.vertexData.tangents, other.transform])); - if (isAsync) { - yield; - } - } - if (root.uvs) { - this.uvs = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UVKind, root.uvs, transform, vertexDatas.map((other) => [other.vertexData.uvs, other.transform])); - if (isAsync) { - yield; - } - } - if (root.uvs2) { - this.uvs2 = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV2Kind, root.uvs2, transform, vertexDatas.map((other) => [other.vertexData.uvs2, other.transform])); - if (isAsync) { - yield; - } - } - if (root.uvs3) { - this.uvs3 = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV3Kind, root.uvs3, transform, vertexDatas.map((other) => [other.vertexData.uvs3, other.transform])); - if (isAsync) { - yield; - } - } - if (root.uvs4) { - this.uvs4 = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV4Kind, root.uvs4, transform, vertexDatas.map((other) => [other.vertexData.uvs4, other.transform])); - if (isAsync) { - yield; - } - } - if (root.uvs5) { - this.uvs5 = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV5Kind, root.uvs5, transform, vertexDatas.map((other) => [other.vertexData.uvs5, other.transform])); - if (isAsync) { - yield; - } - } - if (root.uvs6) { - this.uvs6 = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV6Kind, root.uvs6, transform, vertexDatas.map((other) => [other.vertexData.uvs6, other.transform])); - if (isAsync) { - yield; - } - } - if (root.colors) { - this.colors = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.ColorKind, root.colors, transform, vertexDatas.map((other) => [other.vertexData.colors, other.transform])); - if (isAsync) { - yield; - } - } - if (root.matricesIndices) { - this.matricesIndices = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesIndicesKind, root.matricesIndices, transform, vertexDatas.map((other) => [other.vertexData.matricesIndices, other.transform])); - if (isAsync) { - yield; - } - } - if (root.matricesWeights) { - this.matricesWeights = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesWeightsKind, root.matricesWeights, transform, vertexDatas.map((other) => [other.vertexData.matricesWeights, other.transform])); - if (isAsync) { - yield; - } - } - if (root.matricesIndicesExtra) { - this.matricesIndicesExtra = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesIndicesExtraKind, root.matricesIndicesExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesIndicesExtra, other.transform])); - if (isAsync) { - yield; - } - } - if (root.matricesWeightsExtra) { - this.matricesWeightsExtra = mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesWeightsExtraKind, root.matricesWeightsExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesWeightsExtra, other.transform])); - } - return this; - } - static _MergeElement(kind, source, transform, others) { - const nonNullOthers = others.filter((other) => other[0] !== null && other[0] !== undefined); - // If there is no source to copy and no other non-null sources then skip this element. - if (!source && nonNullOthers.length == 0) { - return source; - } - if (!source) { - return this._MergeElement(kind, nonNullOthers[0][0], nonNullOthers[0][1], nonNullOthers.slice(1)); - } - const len = nonNullOthers.reduce((sumLen, elements) => sumLen + elements[0].length, source.length); - const transformRange = kind === buffer_VertexBuffer.PositionKind - ? mesh_vertexData_VertexData._TransformVector3Coordinates - : kind === buffer_VertexBuffer.NormalKind - ? mesh_vertexData_VertexData._TransformVector3Normals - : kind === buffer_VertexBuffer.TangentKind - ? mesh_vertexData_VertexData._TransformVector4Normals - : () => { }; - if (source instanceof Float32Array) { - // use non-loop method when the source is Float32Array - const ret32 = new Float32Array(len); - ret32.set(source); - transform && transformRange(ret32, transform, 0, source.length); - let offset = source.length; - for (const [vertexData, transform] of nonNullOthers) { - ret32.set(vertexData, offset); - transform && transformRange(ret32, transform, offset, vertexData.length); - offset += vertexData.length; - } - return ret32; - } - else { - // don't use concat as it is super slow, just loop for other cases - const ret = new Array(len); - for (let i = 0; i < source.length; i++) { - ret[i] = source[i]; - } - transform && transformRange(ret, transform, 0, source.length); - let offset = source.length; - for (const [vertexData, transform] of nonNullOthers) { - for (let i = 0; i < vertexData.length; i++) { - ret[offset + i] = vertexData[i]; - } - transform && transformRange(ret, transform, offset, vertexData.length); - offset += vertexData.length; - } - return ret; - } - } - _validate() { - if (!this.positions) { - throw new RuntimeError("Positions are required", ErrorCodes.MeshInvalidPositionsError); - } - const getElementCount = (kind, values) => { - const stride = buffer_VertexBuffer.DeduceStride(kind); - if (values.length % stride !== 0) { - throw new Error("The " + kind + "s array count must be a multiple of " + stride); - } - return values.length / stride; - }; - const positionsElementCount = getElementCount(buffer_VertexBuffer.PositionKind, this.positions); - const validateElementCount = (kind, values) => { - const elementCount = getElementCount(kind, values); - if (elementCount !== positionsElementCount) { - throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")"); - } - }; - if (this.normals) { - validateElementCount(buffer_VertexBuffer.NormalKind, this.normals); - } - if (this.tangents) { - validateElementCount(buffer_VertexBuffer.TangentKind, this.tangents); - } - if (this.uvs) { - validateElementCount(buffer_VertexBuffer.UVKind, this.uvs); - } - if (this.uvs2) { - validateElementCount(buffer_VertexBuffer.UV2Kind, this.uvs2); - } - if (this.uvs3) { - validateElementCount(buffer_VertexBuffer.UV3Kind, this.uvs3); - } - if (this.uvs4) { - validateElementCount(buffer_VertexBuffer.UV4Kind, this.uvs4); - } - if (this.uvs5) { - validateElementCount(buffer_VertexBuffer.UV5Kind, this.uvs5); - } - if (this.uvs6) { - validateElementCount(buffer_VertexBuffer.UV6Kind, this.uvs6); - } - if (this.colors) { - validateElementCount(buffer_VertexBuffer.ColorKind, this.colors); - } - if (this.matricesIndices) { - validateElementCount(buffer_VertexBuffer.MatricesIndicesKind, this.matricesIndices); - } - if (this.matricesWeights) { - validateElementCount(buffer_VertexBuffer.MatricesWeightsKind, this.matricesWeights); - } - if (this.matricesIndicesExtra) { - validateElementCount(buffer_VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra); - } - if (this.matricesWeightsExtra) { - validateElementCount(buffer_VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra); - } - } - /** - * Clone the current vertex data - * @returns a copy of the current data - */ - clone() { - const serializationObject = this.serialize(); - return mesh_vertexData_VertexData.Parse(serializationObject); - } - /** - * Serializes the VertexData - * @returns a serialized object - */ - serialize() { - const serializationObject = {}; - if (this.positions) { - serializationObject.positions = Array.from(this.positions); - } - if (this.normals) { - serializationObject.normals = Array.from(this.normals); - } - if (this.tangents) { - serializationObject.tangents = Array.from(this.tangents); - } - if (this.uvs) { - serializationObject.uvs = Array.from(this.uvs); - } - if (this.uvs2) { - serializationObject.uvs2 = Array.from(this.uvs2); - } - if (this.uvs3) { - serializationObject.uvs3 = Array.from(this.uvs3); - } - if (this.uvs4) { - serializationObject.uvs4 = Array.from(this.uvs4); - } - if (this.uvs5) { - serializationObject.uvs5 = Array.from(this.uvs5); - } - if (this.uvs6) { - serializationObject.uvs6 = Array.from(this.uvs6); - } - if (this.colors) { - serializationObject.colors = Array.from(this.colors); - } - if (this.matricesIndices) { - serializationObject.matricesIndices = Array.from(this.matricesIndices); - serializationObject.matricesIndices._isExpanded = true; - } - if (this.matricesWeights) { - serializationObject.matricesWeights = Array.from(this.matricesWeights); - } - if (this.matricesIndicesExtra) { - serializationObject.matricesIndicesExtra = Array.from(this.matricesIndicesExtra); - serializationObject.matricesIndicesExtra._isExpanded = true; - } - if (this.matricesWeightsExtra) { - serializationObject.matricesWeightsExtra = Array.from(this.matricesWeightsExtra); - } - serializationObject.indices = Array.from(this.indices); - if (this.materialInfos) { - serializationObject.materialInfos = []; - for (const materialInfo of this.materialInfos) { - const materialInfoSerializationObject = { - indexStart: materialInfo.indexStart, - indexCount: materialInfo.indexCount, - materialIndex: materialInfo.materialIndex, - verticesStart: materialInfo.verticesStart, - verticesCount: materialInfo.verticesCount, - }; - serializationObject.materialInfos.push(materialInfoSerializationObject); - } - } - return serializationObject; - } - // Statics - /** - * Extracts the vertexData from a mesh - * @param mesh the mesh from which to extract the VertexData - * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false - * @param forceCopy indicating that the VertexData must be cloned, optional, default false - * @returns the object VertexData associated to the passed mesh - */ - static ExtractFromMesh(mesh, copyWhenShared, forceCopy) { - return mesh_vertexData_VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy); - } - /** - * Extracts the vertexData from the geometry - * @param geometry the geometry from which to extract the VertexData - * @param copyWhenShared defines if the VertexData must be cloned when the geometry is shared between multiple meshes, optional, default false - * @param forceCopy indicating that the VertexData must be cloned, optional, default false - * @returns the object VertexData associated to the passed mesh - */ - static ExtractFromGeometry(geometry, copyWhenShared, forceCopy) { - return mesh_vertexData_VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy); - } - static _ExtractFrom(meshOrGeometry, copyWhenShared, forceCopy) { - const result = new mesh_vertexData_VertexData(); - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.PositionKind)) { - result.positions = meshOrGeometry.getVerticesData(buffer_VertexBuffer.PositionKind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)) { - result.normals = meshOrGeometry.getVerticesData(buffer_VertexBuffer.NormalKind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)) { - result.tangents = meshOrGeometry.getVerticesData(buffer_VertexBuffer.TangentKind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - result.uvs = meshOrGeometry.getVerticesData(buffer_VertexBuffer.UVKind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)) { - result.uvs2 = meshOrGeometry.getVerticesData(buffer_VertexBuffer.UV2Kind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.UV3Kind)) { - result.uvs3 = meshOrGeometry.getVerticesData(buffer_VertexBuffer.UV3Kind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.UV4Kind)) { - result.uvs4 = meshOrGeometry.getVerticesData(buffer_VertexBuffer.UV4Kind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.UV5Kind)) { - result.uvs5 = meshOrGeometry.getVerticesData(buffer_VertexBuffer.UV5Kind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.UV6Kind)) { - result.uvs6 = meshOrGeometry.getVerticesData(buffer_VertexBuffer.UV6Kind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.ColorKind)) { - result.colors = meshOrGeometry.getVerticesData(buffer_VertexBuffer.ColorKind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesKind)) { - result.matricesIndices = meshOrGeometry.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)) { - result.matricesWeights = meshOrGeometry.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesExtraKind)) { - result.matricesIndicesExtra = meshOrGeometry.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy); - } - if (meshOrGeometry.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsExtraKind)) { - result.matricesWeightsExtra = meshOrGeometry.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy); - } - result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy); - return result; - } - /** - * Creates the VertexData for a Ribbon - * @param options an object used to set the following optional parameters for the ribbon, required but can be empty - * * pathArray array of paths, each of which an array of successive Vector3 - * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false - * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false - * * 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 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false - * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional - * * colors a linear array, of length 4 * number of vertices, of custom color values, optional - * @param options.pathArray - * @param options.closeArray - * @param options.closePath - * @param options.offset - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.invertUV - * @param options.uvs - * @param options.colors - * @returns the VertexData of the ribbon - * @deprecated use CreateRibbonVertexData instead - */ - static CreateRibbon(options) { - throw _WarnImport("ribbonBuilder"); - } - /** - * Creates the VertexData for a box - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * size sets the width, height and depth of the box to the value of size, optional default 1 - * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size - * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size - * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size - * * faceUV an array of 6 Vector4 elements used to set different images to each box side - * * faceColors an array of 6 Color3 elements used to set different colors to each box side - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.size - * @param options.width - * @param options.height - * @param options.depth - * @param options.faceUV - * @param options.faceColors - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the box - * @deprecated Please use CreateBoxVertexData from the BoxBuilder file instead - */ - static CreateBox(options) { - throw _WarnImport("boxBuilder"); - } - /** - * Creates the VertexData for a tiled box - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * faceTiles sets the pattern, tile size and number of tiles for a face - * * faceUV an array of 6 Vector4 elements used to set different images to each box side - * * faceColors an array of 6 Color3 elements used to set different colors to each box side - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * @param options.pattern - * @param options.width - * @param options.height - * @param options.depth - * @param options.tileSize - * @param options.tileWidth - * @param options.tileHeight - * @param options.alignHorizontal - * @param options.alignVertical - * @param options.faceUV - * @param options.faceColors - * @param options.sideOrientation - * @returns the VertexData of the box - * @deprecated Please use CreateTiledBoxVertexData instead - */ - static CreateTiledBox(options) { - throw _WarnImport("tiledBoxBuilder"); - } - /** - * Creates the VertexData for a tiled plane - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * pattern a limited pattern arrangement depending on the number - * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1 - * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size - * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.pattern - * @param options.tileSize - * @param options.tileWidth - * @param options.tileHeight - * @param options.size - * @param options.width - * @param options.height - * @param options.alignHorizontal - * @param options.alignVertical - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the tiled plane - * @deprecated use CreateTiledPlaneVertexData instead - */ - static CreateTiledPlane(options) { - throw _WarnImport("tiledPlaneBuilder"); - } - /** - * Creates the VertexData for an ellipsoid, defaults to a sphere - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * segments sets the number of horizontal strips optional, default 32 - * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1 - * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter - * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter - * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter - * * 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 - * * 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 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.segments - * @param options.diameter - * @param options.diameterX - * @param options.diameterY - * @param options.diameterZ - * @param options.arc - * @param options.slice - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the ellipsoid - * @deprecated use CreateSphereVertexData instead - */ - static CreateSphere(options) { - throw _WarnImport("sphereBuilder"); - } - /** - * Creates the VertexData for a cylinder, cone or prism - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * height sets the height (y direction) of the cylinder, optional, default 2 - * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter - * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter - * * diameter sets the diameter of the top and bottom of the cone, optional default 1 - * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 - * * subdivisions` the number of rings along the cylinder height, optional, default 1 - * * 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 - * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * * hasRings when true makes each subdivision independently treated as a face for faceUV and faceColors, optional, default false - * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.height - * @param options.diameterTop - * @param options.diameterBottom - * @param options.diameter - * @param options.tessellation - * @param options.subdivisions - * @param options.arc - * @param options.faceColors - * @param options.faceUV - * @param options.hasRings - * @param options.enclose - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the cylinder, cone or prism - * @deprecated please use CreateCylinderVertexData instead - */ - static CreateCylinder(options) { - throw _WarnImport("cylinderBuilder"); - } - /** - * Creates the VertexData for a torus - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * diameter the diameter of the torus, optional default 1 - * * thickness the diameter of the tube forming the torus, optional default 0.5 - * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.diameter - * @param options.thickness - * @param options.tessellation - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the torus - * @deprecated use CreateTorusVertexData instead - */ - static CreateTorus(options) { - throw _WarnImport("torusBuilder"); - } - /** - * Creates the VertexData of the LineSystem - * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty - * - lines an array of lines, each line being an array of successive Vector3 - * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point - * @param options.lines - * @param options.colors - * @returns the VertexData of the LineSystem - * @deprecated use CreateLineSystemVertexData instead - */ - static CreateLineSystem(options) { - throw _WarnImport("linesBuilder"); - } - /** - * Create the VertexData for a DashedLines - * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty - * - points an array successive Vector3 - * - dashSize the size of the dashes relative to the dash number, optional, default 3 - * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1 - * - dashNb the intended total number of dashes, optional, default 200 - * @param options.points - * @param options.dashSize - * @param options.gapSize - * @param options.dashNb - * @returns the VertexData for the DashedLines - * @deprecated use CreateDashedLinesVertexData instead - */ - static CreateDashedLines(options) { - throw _WarnImport("linesBuilder"); - } - /** - * Creates the VertexData for a Ground - * @param options an object used to set the following optional parameters for the Ground, required but can be empty - * - width the width (x direction) of the ground, optional, default 1 - * - height the height (z direction) of the ground, optional, default 1 - * - subdivisions the number of subdivisions per side, optional, default 1 - * @param options.width - * @param options.height - * @param options.subdivisions - * @param options.subdivisionsX - * @param options.subdivisionsY - * @returns the VertexData of the Ground - * @deprecated Please use CreateGroundVertexData instead - */ - static CreateGround(options) { - throw _WarnImport("groundBuilder"); - } - /** - * Creates the VertexData for a TiledGround by subdividing the ground into tiles - * @param options an object used to set the following optional parameters for the Ground, required but can be empty - * * xmin the ground minimum X coordinate, optional, default -1 - * * zmin the ground minimum Z coordinate, optional, default -1 - * * xmax the ground maximum X coordinate, optional, default 1 - * * zmax the ground maximum Z coordinate, optional, default 1 - * * 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} - * * 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} - * @param options.xmin - * @param options.zmin - * @param options.xmax - * @param options.zmax - * @param options.subdivisions - * @param options.subdivisions.w - * @param options.subdivisions.h - * @param options.precision - * @param options.precision.w - * @param options.precision.h - * @returns the VertexData of the TiledGround - * @deprecated use CreateTiledGroundVertexData instead - */ - static CreateTiledGround(options) { - throw _WarnImport("groundBuilder"); - } - /** - * Creates the VertexData of the Ground designed from a heightmap - * @param options an object used to set the following parameters for the Ground, required and provided by CreateGroundFromHeightMap - * * width the width (x direction) of the ground - * * height the height (z direction) of the ground - * * subdivisions the number of subdivisions per side - * * minHeight the minimum altitude on the ground, optional, default 0 - * * maxHeight the maximum altitude on the ground, optional default 1 - * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11) - * * buffer the array holding the image color data - * * bufferWidth the width of image - * * bufferHeight the height of image - * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible) - * @param options.width - * @param options.height - * @param options.subdivisions - * @param options.minHeight - * @param options.maxHeight - * @param options.colorFilter - * @param options.buffer - * @param options.bufferWidth - * @param options.bufferHeight - * @param options.alphaFilter - * @returns the VertexData of the Ground designed from a heightmap - * @deprecated use CreateGroundFromHeightMapVertexData instead - */ - static CreateGroundFromHeightMap(options) { - throw _WarnImport("groundBuilder"); - } - /** - * Creates the VertexData for a Plane - * @param options an object used to set the following optional parameters for the plane, required but can be empty - * * size sets the width and height of the plane to the value of size, optional default 1 - * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size - * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.size - * @param options.width - * @param options.height - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the box - * @deprecated use CreatePlaneVertexData instead - */ - static CreatePlane(options) { - throw _WarnImport("planeBuilder"); - } - /** - * Creates the VertexData of the Disc or regular Polygon - * @param options an object used to set the following optional parameters for the disc, required but can be empty - * * radius the radius of the disc, optional default 0.5 - * * tessellation the number of polygon sides, optional, default 64 - * * 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 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.radius - * @param options.tessellation - * @param options.arc - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the box - * @deprecated use CreateDiscVertexData instead - */ - static CreateDisc(options) { - throw _WarnImport("discBuilder"); - } - /** - * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build() - * All parameters are provided by CreatePolygon as needed - * @param polygon a mesh built from polygonTriangulation.build() - * @param sideOrientation takes the values Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * @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) - * @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) - * @param wrap a boolean, default false, when true and fUVs used texture is wrapped around all sides, when false texture is applied side - * @returns the VertexData of the Polygon - * @deprecated use CreatePolygonVertexData instead - */ - static CreatePolygon(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrap) { - throw _WarnImport("polygonBuilder"); - } - /** - * Creates the VertexData of the IcoSphere - * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty - * * radius the radius of the IcoSphere, optional default 1 - * * radiusX allows stretching in the x direction, optional, default radius - * * radiusY allows stretching in the y direction, optional, default radius - * * radiusZ allows stretching in the z direction, optional, default radius - * * flat when true creates a flat shaded mesh, optional, default true - * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.radius - * @param options.radiusX - * @param options.radiusY - * @param options.radiusZ - * @param options.flat - * @param options.subdivisions - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the IcoSphere - * @deprecated use CreateIcoSphereVertexData instead - */ - static CreateIcoSphere(options) { - throw _WarnImport("icoSphereBuilder"); - } - // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html - /** - * Creates the VertexData for a Polyhedron - * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty - * * type provided types are: - * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) - * * 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) - * * size the size of the IcoSphere, optional default 1 - * * sizeX allows stretching in the x direction, optional, default size - * * sizeY allows stretching in the y direction, optional, default size - * * sizeZ allows stretching in the z direction, optional, default size - * * 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 - * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * * flat when true creates a flat shaded mesh, optional, default true - * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.type - * @param options.size - * @param options.sizeX - * @param options.sizeY - * @param options.sizeZ - * @param options.custom - * @param options.faceUV - * @param options.faceColors - * @param options.flat - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the Polyhedron - * @deprecated use CreatePolyhedronVertexData instead - */ - static CreatePolyhedron(options) { - throw _WarnImport("polyhedronBuilder"); - } - /** - * Creates the VertexData for a Capsule, inspired from https://github.com/maximeq/three-js-capsule-geometry/blob/master/src/CapsuleBufferGeometry.js - * @param options an object used to set the following optional parameters for the capsule, required but can be empty - * @returns the VertexData of the Capsule - * @deprecated Please use CreateCapsuleVertexData from the capsuleBuilder file instead - */ - static CreateCapsule(options = { - orientation: math_vector_Vector3.Up(), - subdivisions: 2, - tessellation: 16, - height: 1, - radius: 0.25, - capSubdivisions: 6, - }) { - throw _WarnImport("capsuleBuilder"); - } - // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473 - /** - * Creates the VertexData for a TorusKnot - * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty - * * radius the radius of the torus knot, optional, default 2 - * * tube the thickness of the tube, optional, default 0.5 - * * radialSegments the number of sides on each tube segments, optional, default 32 - * * tubularSegments the number of tubes to decompose the knot into, optional, default 32 - * * p the number of windings around the z axis, optional, default 2 - * * q the number of windings around the x axis, optional, default 3 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.radius - * @param options.tube - * @param options.radialSegments - * @param options.tubularSegments - * @param options.p - * @param options.q - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the Torus Knot - * @deprecated use CreateTorusKnotVertexData instead - */ - static CreateTorusKnot(options) { - throw _WarnImport("torusKnotBuilder"); - } - // Tools - /** - * Compute normals for given positions and indices - * @param positions an array of vertex positions, [...., x, y, z, ......] - * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......] - * @param normals an array of vertex normals, [...., x, y, z, ......] - * @param options an object used to set the following optional parameters for the TorusKnot, optional - * * facetNormals : optional array of facet normals (vector3) - * * facetPositions : optional array of facet positions (vector3) - * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation - * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation - * * bInfo : optional bounding info, required for facetPartitioning computation - * * bbSize : optional bounding box size data, required for facetPartitioning computation - * * subDiv : optional partitioning data about subdivisions on each axis (int), required for facetPartitioning computation - * * useRightHandedSystem: optional boolean to for right handed system computation - * * depthSort : optional boolean to enable the facet depth sort computation - * * distanceTo : optional Vector3 to compute the facet depth from this location - * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location - * @param options.facetNormals - * @param options.facetPositions - * @param options.facetPartitioning - * @param options.ratio - * @param options.bInfo - * @param options.bbSize - * @param options.subDiv - * @param options.useRightHandedSystem - * @param options.depthSort - * @param options.distanceTo - * @param options.depthSortedFacets - */ - static ComputeNormals(positions, indices, normals, options) { - // temporary scalar variables - let index = 0; // facet index - let p1p2x = 0.0; // p1p2 vector x coordinate - let p1p2y = 0.0; // p1p2 vector y coordinate - let p1p2z = 0.0; // p1p2 vector z coordinate - let p3p2x = 0.0; // p3p2 vector x coordinate - let p3p2y = 0.0; // p3p2 vector y coordinate - let p3p2z = 0.0; // p3p2 vector z coordinate - let faceNormalx = 0.0; // facet normal x coordinate - let faceNormaly = 0.0; // facet normal y coordinate - let faceNormalz = 0.0; // facet normal z coordinate - let length = 0.0; // facet normal length before normalization - let v1x = 0; // vector1 x index in the positions array - let v1y = 0; // vector1 y index in the positions array - let v1z = 0; // vector1 z index in the positions array - let v2x = 0; // vector2 x index in the positions array - let v2y = 0; // vector2 y index in the positions array - let v2z = 0; // vector2 z index in the positions array - let v3x = 0; // vector3 x index in the positions array - let v3y = 0; // vector3 y index in the positions array - let v3z = 0; // vector3 z index in the positions array - let computeFacetNormals = false; - let computeFacetPositions = false; - let computeFacetPartitioning = false; - let computeDepthSort = false; - let faceNormalSign = 1; - let ratio = 0; - let distanceTo = null; - if (options) { - computeFacetNormals = options.facetNormals ? true : false; - computeFacetPositions = options.facetPositions ? true : false; - computeFacetPartitioning = options.facetPartitioning ? true : false; - faceNormalSign = options.useRightHandedSystem === true ? -1 : 1; - ratio = options.ratio || 0; - computeDepthSort = options.depthSort ? true : false; - distanceTo = options.distanceTo; - if (computeDepthSort) { - if (distanceTo === undefined) { - distanceTo = math_vector_Vector3.Zero(); - } - } - } - // facetPartitioning reinit if needed - let xSubRatio = 0; - let ySubRatio = 0; - let zSubRatio = 0; - let subSq = 0; - if (computeFacetPartitioning && options && options.bbSize) { - //let bbSizeMax = options.bbSize.x > options.bbSize.y ? options.bbSize.x : options.bbSize.y; - //bbSizeMax = bbSizeMax > options.bbSize.z ? bbSizeMax : options.bbSize.z; - xSubRatio = (options.subDiv.X * ratio) / options.bbSize.x; - ySubRatio = (options.subDiv.Y * ratio) / options.bbSize.y; - zSubRatio = (options.subDiv.Z * ratio) / options.bbSize.z; - subSq = options.subDiv.max * options.subDiv.max; - options.facetPartitioning.length = 0; - } - // reset the normals - for (index = 0; index < positions.length; index++) { - normals[index] = 0.0; - } - // Loop : 1 indice triplet = 1 facet - const nbFaces = (indices.length / 3) | 0; - for (index = 0; index < nbFaces; index++) { - // get the indexes of the coordinates of each vertex of the facet - v1x = indices[index * 3] * 3; - v1y = v1x + 1; - v1z = v1x + 2; - v2x = indices[index * 3 + 1] * 3; - v2y = v2x + 1; - v2z = v2x + 2; - v3x = indices[index * 3 + 2] * 3; - v3y = v3x + 1; - v3z = v3x + 2; - p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2 - p1p2y = positions[v1y] - positions[v2y]; - p1p2z = positions[v1z] - positions[v2z]; - p3p2x = positions[v3x] - positions[v2x]; - p3p2y = positions[v3y] - positions[v2y]; - p3p2z = positions[v3z] - positions[v2z]; - // compute the face normal with the cross product - faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y); - faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z); - faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x); - // normalize this normal and store it in the array facetData - length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz); - length = length === 0 ? 1.0 : length; - faceNormalx /= length; - faceNormaly /= length; - faceNormalz /= length; - if (computeFacetNormals && options) { - options.facetNormals[index].x = faceNormalx; - options.facetNormals[index].y = faceNormaly; - options.facetNormals[index].z = faceNormalz; - } - if (computeFacetPositions && options) { - // compute and the facet barycenter coordinates in the array facetPositions - options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0; - options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0; - options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0; - } - if (computeFacetPartitioning && options) { - // store the facet indexes in arrays in the main facetPartitioning array : - // compute each facet vertex (+ facet barycenter) index in the partiniong array - const ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio); - const oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio); - const oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio); - const b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio); - const b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio); - const b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio); - const b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio); - const b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio); - const b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio); - const b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio); - const b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio); - const b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio); - const block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z; - const block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z; - const block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z; - const block_idx_o = ox + options.subDiv.max * oy + subSq * oz; - options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array(); - options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array(); - options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array(); - options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array(); - // push each facet index in each block containing the vertex - options.facetPartitioning[block_idx_v1].push(index); - if (block_idx_v2 != block_idx_v1) { - options.facetPartitioning[block_idx_v2].push(index); - } - if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) { - options.facetPartitioning[block_idx_v3].push(index); - } - if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) { - options.facetPartitioning[block_idx_o].push(index); - } - } - if (computeDepthSort && options && options.facetPositions) { - const dsf = options.depthSortedFacets[index]; - dsf.ind = index * 3; - dsf.sqDistance = math_vector_Vector3.DistanceSquared(options.facetPositions[index], distanceTo); - } - // compute the normals anyway - normals[v1x] += faceNormalx; // accumulate all the normals per face - normals[v1y] += faceNormaly; - normals[v1z] += faceNormalz; - normals[v2x] += faceNormalx; - normals[v2y] += faceNormaly; - normals[v2z] += faceNormalz; - normals[v3x] += faceNormalx; - normals[v3y] += faceNormaly; - normals[v3z] += faceNormalz; - } - // last normalization of each normal - for (index = 0; index < normals.length / 3; index++) { - faceNormalx = normals[index * 3]; - faceNormaly = normals[index * 3 + 1]; - faceNormalz = normals[index * 3 + 2]; - length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz); - length = length === 0 ? 1.0 : length; - faceNormalx /= length; - faceNormaly /= length; - faceNormalz /= length; - normals[index * 3] = faceNormalx; - normals[index * 3 + 1] = faceNormaly; - normals[index * 3 + 2] = faceNormalz; - } - } - /** - * @internal - */ - static _ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) { - const li = indices.length; - const ln = normals.length; - let i; - let n; - sideOrientation = sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - switch (sideOrientation) { - case mesh_vertexData_VertexData.FRONTSIDE: - // nothing changed - break; - case mesh_vertexData_VertexData.BACKSIDE: - // indices - for (i = 0; i < li; i += 3) { - const tmp = indices[i]; - indices[i] = indices[i + 2]; - indices[i + 2] = tmp; - } - // normals - for (n = 0; n < ln; n++) { - normals[n] = -normals[n]; - } - break; - case mesh_vertexData_VertexData.DOUBLESIDE: { - // positions - const lp = positions.length; - const l = lp / 3; - for (let p = 0; p < lp; p++) { - positions[lp + p] = positions[p]; - } - // indices - for (i = 0; i < li; i += 3) { - indices[i + li] = indices[i + 2] + l; - indices[i + 1 + li] = indices[i + 1] + l; - indices[i + 2 + li] = indices[i] + l; - } - // normals - for (n = 0; n < ln; n++) { - normals[ln + n] = -normals[n]; - } - // uvs - const lu = uvs.length; - let u = 0; - for (u = 0; u < lu; u++) { - uvs[u + lu] = uvs[u]; - } - frontUVs = frontUVs ? frontUVs : new math_vector_Vector4(0.0, 0.0, 1.0, 1.0); - backUVs = backUVs ? backUVs : new math_vector_Vector4(0.0, 0.0, 1.0, 1.0); - u = 0; - for (i = 0; i < lu / 2; i++) { - uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u]; - uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1]; - uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu]; - uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1]; - u += 2; - } - break; - } - } - } - /** - * Creates a VertexData from serialized data - * @param parsedVertexData the parsed data from an imported file - * @returns a VertexData - */ - static Parse(parsedVertexData) { - const vertexData = new mesh_vertexData_VertexData(); - // positions - const positions = parsedVertexData.positions; - if (positions) { - vertexData.set(positions, buffer_VertexBuffer.PositionKind); - } - // normals - const normals = parsedVertexData.normals; - if (normals) { - vertexData.set(normals, buffer_VertexBuffer.NormalKind); - } - // tangents - const tangents = parsedVertexData.tangents; - if (tangents) { - vertexData.set(tangents, buffer_VertexBuffer.TangentKind); - } - // uvs - const uvs = parsedVertexData.uvs; - if (uvs) { - vertexData.set(uvs, buffer_VertexBuffer.UVKind); - } - // uv2s - const uvs2 = parsedVertexData.uvs2; - if (uvs2) { - vertexData.set(uvs2, buffer_VertexBuffer.UV2Kind); - } - // uv3s - const uvs3 = parsedVertexData.uvs3; - if (uvs3) { - vertexData.set(uvs3, buffer_VertexBuffer.UV3Kind); - } - // uv4s - const uvs4 = parsedVertexData.uvs4; - if (uvs4) { - vertexData.set(uvs4, buffer_VertexBuffer.UV4Kind); - } - // uv5s - const uvs5 = parsedVertexData.uvs5; - if (uvs5) { - vertexData.set(uvs5, buffer_VertexBuffer.UV5Kind); - } - // uv6s - const uvs6 = parsedVertexData.uvs6; - if (uvs6) { - vertexData.set(uvs6, buffer_VertexBuffer.UV6Kind); - } - // colors - const colors = parsedVertexData.colors; - if (colors) { - vertexData.set(math_color_Color4.CheckColors4(colors, positions.length / 3), buffer_VertexBuffer.ColorKind); - } - // matricesIndices - const matricesIndices = parsedVertexData.matricesIndices; - if (matricesIndices) { - vertexData.set(matricesIndices, buffer_VertexBuffer.MatricesIndicesKind); - } - // matricesWeights - const matricesWeights = parsedVertexData.matricesWeights; - if (matricesWeights) { - vertexData.set(matricesWeights, buffer_VertexBuffer.MatricesWeightsKind); - } - // indices - const indices = parsedVertexData.indices; - if (indices) { - vertexData.indices = indices; - } - // MaterialInfos - const materialInfos = parsedVertexData.materialInfos; - if (materialInfos) { - vertexData.materialInfos = []; - for (const materialInfoFromJSON of materialInfos) { - const materialInfo = new VertexDataMaterialInfo(); - materialInfo.indexCount = materialInfoFromJSON.indexCount; - materialInfo.indexStart = materialInfoFromJSON.indexStart; - materialInfo.verticesCount = materialInfoFromJSON.verticesCount; - materialInfo.verticesStart = materialInfoFromJSON.verticesStart; - materialInfo.materialIndex = materialInfoFromJSON.materialIndex; - vertexData.materialInfos.push(materialInfo); - } - } - return vertexData; - } - /** - * Applies VertexData created from the imported parameters to the geometry - * @param parsedVertexData the parsed data from an imported file - * @param geometry the geometry to apply the VertexData to - */ - static ImportVertexData(parsedVertexData, geometry) { - const vertexData = mesh_vertexData_VertexData.Parse(parsedVertexData); - geometry.setAllVerticesData(vertexData, parsedVertexData.updatable); - } -} -/** - * Mesh side orientation : usually the external or front surface - */ -mesh_vertexData_VertexData.FRONTSIDE = 0; -/** - * Mesh side orientation : usually the internal or back surface - */ -mesh_vertexData_VertexData.BACKSIDE = 1; -/** - * Mesh side orientation : both internal and external or front and back surfaces - */ -mesh_vertexData_VertexData.DOUBLESIDE = 2; -/** - * Mesh side orientation : by default, `FRONTSIDE` - */ -mesh_vertexData_VertexData.DEFAULTSIDE = 0; -mesh_vertexData_VertexData._UniqueIDGenerator = 0; -__decorate([ - nativeOverride.filter((...[coordinates]) => !Array.isArray(coordinates)) -], mesh_vertexData_VertexData, "_TransformVector3Coordinates", null); -__decorate([ - nativeOverride.filter((...[normals]) => !Array.isArray(normals)) -], mesh_vertexData_VertexData, "_TransformVector3Normals", null); -__decorate([ - nativeOverride.filter((...[normals]) => !Array.isArray(normals)) -], mesh_vertexData_VertexData, "_TransformVector4Normals", null); -__decorate([ - nativeOverride.filter((...[indices]) => !Array.isArray(indices)) -], mesh_vertexData_VertexData, "_FlipFaces", null); -//# sourceMappingURL=mesh.vertexData.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Loading/sceneLoaderFlags.js - -/** - * Class used to represent data loading progression - */ -class SceneLoaderFlags { - /** - * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data - */ - static get ForceFullSceneLoadingForIncremental() { - return SceneLoaderFlags._ForceFullSceneLoadingForIncremental; - } - static set ForceFullSceneLoadingForIncremental(value) { - SceneLoaderFlags._ForceFullSceneLoadingForIncremental = value; - } - /** - * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene - */ - static get ShowLoadingScreen() { - return SceneLoaderFlags._ShowLoadingScreen; - } - static set ShowLoadingScreen(value) { - SceneLoaderFlags._ShowLoadingScreen = value; - } - /** - * Defines the current logging level (while loading the scene) - * @ignorenaming - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static get loggingLevel() { - return SceneLoaderFlags._LoggingLevel; - } - // eslint-disable-next-line @typescript-eslint/naming-convention - static set loggingLevel(value) { - SceneLoaderFlags._LoggingLevel = value; - } - /** - * Gets or set a boolean indicating if matrix weights must be cleaned upon loading - */ - static get CleanBoneMatrixWeights() { - return SceneLoaderFlags._CleanBoneMatrixWeights; - } - static set CleanBoneMatrixWeights(value) { - SceneLoaderFlags._CleanBoneMatrixWeights = value; - } -} -// Flags -SceneLoaderFlags._ForceFullSceneLoadingForIncremental = false; -SceneLoaderFlags._ShowLoadingScreen = true; -SceneLoaderFlags._CleanBoneMatrixWeights = false; -SceneLoaderFlags._LoggingLevel = 0; -//# sourceMappingURL=sceneLoaderFlags.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Compat/compatibilityOptions.js -/** - * Options used to control default behaviors regarding compatibility support - */ -class CompatibilityOptions { -} -/** - * Defines if the system should use OpenGL convention for UVs when creating geometry or loading .babylon files (false by default) - */ -CompatibilityOptions.UseOpenGLOrientationForUV = false; -//# sourceMappingURL=compatibilityOptions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/geometry.js - - - - - - - - - - - - - -/** - * Class used to store geometry data (vertex buffers + index buffer) - */ -class Geometry { - /** - * 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 - */ - get boundingBias() { - return this._boundingBias; - } - /** - * 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 - */ - set boundingBias(value) { - if (this._boundingBias) { - this._boundingBias.copyFrom(value); - } - else { - this._boundingBias = value.clone(); - } - this._updateBoundingInfo(true, null); - } - /** - * Static function used to attach a new empty geometry to a mesh - * @param mesh defines the mesh to attach the geometry to - * @returns the new Geometry - */ - static CreateGeometryForMesh(mesh) { - const geometry = new Geometry(Geometry.RandomId(), mesh.getScene()); - geometry.applyToMesh(mesh); - return geometry; - } - /** Get the list of meshes using this geometry */ - get meshes() { - return this._meshes; - } - /** - * Creates a new geometry - * @param id defines the unique ID - * @param scene defines the hosting scene - * @param vertexData defines the VertexData used to get geometry data - * @param updatable defines if geometry must be updatable (false by default) - * @param mesh defines the mesh that will be associated with the geometry - */ - constructor(id, scene, vertexData, updatable = false, mesh = null) { - /** - * Gets the delay loading state of the geometry (none by default which means not delayed) - */ - this.delayLoadState = 0; - this._totalVertices = 0; - this._isDisposed = false; - this._indexBufferIsUpdatable = false; - this._positionsCache = []; - /** @internal */ - this._parentContainer = null; - /** - * 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 - * and won't be computed based on the vertex positions (which is what we get when useBoundingInfoFromGeometry = false) - */ - this.useBoundingInfoFromGeometry = false; - this._scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!this._scene) { - return; - } - this.id = id; - this.uniqueId = this._scene.getUniqueId(); - this._engine = this._scene.getEngine(); - this._meshes = []; - //Init vertex buffer cache - this._vertexBuffers = {}; - this._indices = []; - this._updatable = updatable; - // vertexData - if (vertexData) { - this.setAllVerticesData(vertexData, updatable); - } - else { - this._totalVertices = 0; - } - if (this._engine.getCaps().vertexArrayObject) { - this._vertexArrayObjects = {}; - } - // applyToMesh - if (mesh) { - this.applyToMesh(mesh); - mesh.computeWorldMatrix(true); - } - } - /** - * Gets the current extend of the geometry - */ - get extend() { - return this._extend; - } - /** - * Gets the hosting scene - * @returns the hosting Scene - */ - getScene() { - return this._scene; - } - /** - * Gets the hosting engine - * @returns the hosting Engine - */ - getEngine() { - return this._engine; - } - /** - * Defines if the geometry is ready to use - * @returns true if the geometry is ready to be used - */ - isReady() { - return this.delayLoadState === 1 || this.delayLoadState === 0; - } - /** - * Gets a value indicating that the geometry should not be serialized - */ - get doNotSerialize() { - for (let index = 0; index < this._meshes.length; index++) { - if (!this._meshes[index].doNotSerialize) { - return false; - } - } - return true; - } - /** @internal */ - _rebuild() { - if (this._vertexArrayObjects) { - this._vertexArrayObjects = {}; - } - // Index buffer - if (this._meshes.length !== 0 && this._indices) { - this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable); - } - // Vertex buffers - for (const key in this._vertexBuffers) { - const vertexBuffer = this._vertexBuffers[key]; - vertexBuffer._rebuild(); - } - } - /** - * Affects all geometry data in one call - * @param vertexData defines the geometry data - * @param updatable defines if the geometry must be flagged as updatable (false as default) - */ - setAllVerticesData(vertexData, updatable) { - vertexData.applyToGeometry(this, updatable); - this._notifyUpdate(); - } - /** - * Set specific vertex data - * @param kind defines the data kind (Position, normal, etc...) - * @param data defines the vertex data to use - * @param updatable defines if the vertex must be flagged as updatable (false as default) - * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified - */ - setVerticesData(kind, data, updatable = false, stride) { - if (updatable && Array.isArray(data)) { - // to avoid converting to Float32Array at each draw call in engine.updateDynamicVertexBuffer, we make the conversion a single time here - data = new Float32Array(data); - } - const buffer = new buffer_VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride); - this.setVerticesBuffer(buffer); - } - /** - * Removes a specific vertex data - * @param kind defines the data kind (Position, normal, etc...) - */ - removeVerticesData(kind) { - if (this._vertexBuffers[kind]) { - this._vertexBuffers[kind].dispose(); - delete this._vertexBuffers[kind]; - } - if (this._vertexArrayObjects) { - this._disposeVertexArrayObjects(); - } - } - /** - * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data - * @param buffer defines the vertex buffer to use - * @param totalVertices defines the total number of vertices for position kind (could be null) - * @param disposeExistingBuffer disposes the existing buffer, if any (default: true) - */ - setVerticesBuffer(buffer, totalVertices = null, disposeExistingBuffer = true) { - const kind = buffer.getKind(); - if (this._vertexBuffers[kind] && disposeExistingBuffer) { - this._vertexBuffers[kind].dispose(); - } - if (buffer._buffer) { - buffer._buffer._increaseReferences(); - } - this._vertexBuffers[kind] = buffer; - const meshes = this._meshes; - const numOfMeshes = meshes.length; - if (kind === buffer_VertexBuffer.PositionKind) { - const data = buffer.getData(); - if (totalVertices != null) { - this._totalVertices = totalVertices; - } - else { - if (data != null) { - this._totalVertices = data.length / (buffer.type === buffer_VertexBuffer.BYTE ? buffer.byteStride : buffer.byteStride / 4); - } - } - this._updateExtend(data); - this._resetPointsArrayCache(); - for (let index = 0; index < numOfMeshes; index++) { - const mesh = meshes[index]; - mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum); - mesh._createGlobalSubMesh(mesh.isUnIndexed); - mesh.computeWorldMatrix(true); - mesh.synchronizeInstances(); - } - } - this._notifyUpdate(kind); - } - /** - * Update a specific vertex buffer - * This function will directly update the underlying DataBuffer according to the passed numeric array or Float32Array - * It will do nothing if the buffer is not updatable - * @param kind defines the data kind (Position, normal, etc...) - * @param data defines the data to use - * @param offset defines the offset in the target buffer where to store the data - * @param useBytes set to true if the offset is in bytes - */ - updateVerticesDataDirectly(kind, data, offset, useBytes = false) { - const vertexBuffer = this.getVertexBuffer(kind); - if (!vertexBuffer) { - return; - } - vertexBuffer.updateDirectly(data, offset, useBytes); - this._notifyUpdate(kind); - } - /** - * Update a specific vertex buffer - * This function will create a new buffer if the current one is not updatable - * @param kind defines the data kind (Position, normal, etc...) - * @param data defines the data to use - * @param updateExtends defines if the geometry extends must be recomputed (false by default) - */ - updateVerticesData(kind, data, updateExtends = false) { - const vertexBuffer = this.getVertexBuffer(kind); - if (!vertexBuffer) { - return; - } - vertexBuffer.update(data); - if (kind === buffer_VertexBuffer.PositionKind) { - this._updateBoundingInfo(updateExtends, data); - } - this._notifyUpdate(kind); - } - _updateBoundingInfo(updateExtends, data) { - if (updateExtends) { - this._updateExtend(data); - } - this._resetPointsArrayCache(); - if (updateExtends) { - const meshes = this._meshes; - for (const mesh of meshes) { - if (mesh.hasBoundingInfo) { - mesh.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum); - } - else { - mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum); - } - const subMeshes = mesh.subMeshes; - for (const subMesh of subMeshes) { - subMesh.refreshBoundingInfo(); - } - } - } - } - /** - * @internal - */ - _bind(effect, indexToBind, overrideVertexBuffers, overrideVertexArrayObjects) { - if (!effect) { - return; - } - if (indexToBind === undefined) { - indexToBind = this._indexBuffer; - } - const vbs = this.getVertexBuffers(); - if (!vbs) { - return; - } - if (indexToBind != this._indexBuffer || (!this._vertexArrayObjects && !overrideVertexArrayObjects)) { - this._engine.bindBuffers(vbs, indexToBind, effect, overrideVertexBuffers); - return; - } - const vaos = overrideVertexArrayObjects ? overrideVertexArrayObjects : this._vertexArrayObjects; - // Using VAO - if (!vaos[effect.key]) { - vaos[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect, overrideVertexBuffers); - } - this._engine.bindVertexArrayObject(vaos[effect.key], indexToBind); - } - /** - * Gets total number of vertices - * @returns the total number of vertices - */ - getTotalVertices() { - if (!this.isReady()) { - return 0; - } - return this._totalVertices; - } - /** - * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly. - * @param kind defines the data kind (Position, normal, etc...) - * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes - * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it - * @returns a float array containing vertex data - */ - getVerticesData(kind, copyWhenShared, forceCopy) { - const vertexBuffer = this.getVertexBuffer(kind); - if (!vertexBuffer) { - return null; - } - return vertexBuffer.getFloatData(this._totalVertices, forceCopy || (copyWhenShared && this._meshes.length !== 1)); - } - /** - * Returns a boolean defining if the vertex data for the requested `kind` is updatable - * @param kind defines the data kind (Position, normal, etc...) - * @returns true if the vertex buffer with the specified kind is updatable - */ - isVertexBufferUpdatable(kind) { - const vb = this._vertexBuffers[kind]; - if (!vb) { - return false; - } - return vb.isUpdatable(); - } - /** - * Gets a specific vertex buffer - * @param kind defines the data kind (Position, normal, etc...) - * @returns a VertexBuffer - */ - getVertexBuffer(kind) { - if (!this.isReady()) { - return null; - } - return this._vertexBuffers[kind]; - } - /** - * Returns all vertex buffers - * @returns an object holding all vertex buffers indexed by kind - */ - getVertexBuffers() { - if (!this.isReady()) { - return null; - } - return this._vertexBuffers; - } - /** - * Gets a boolean indicating if specific vertex buffer is present - * @param kind defines the data kind (Position, normal, etc...) - * @returns true if data is present - */ - isVerticesDataPresent(kind) { - if (!this._vertexBuffers) { - if (this._delayInfo) { - return this._delayInfo.indexOf(kind) !== -1; - } - return false; - } - return this._vertexBuffers[kind] !== undefined; - } - /** - * Gets a list of all attached data kinds (Position, normal, etc...) - * @returns a list of string containing all kinds - */ - getVerticesDataKinds() { - const result = []; - let kind; - if (!this._vertexBuffers && this._delayInfo) { - for (kind in this._delayInfo) { - result.push(kind); - } - } - else { - for (kind in this._vertexBuffers) { - result.push(kind); - } - } - return result; - } - /** - * Update index buffer - * @param indices defines the indices to store in the index buffer - * @param offset defines the offset in the target buffer where to store the data - * @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) - */ - updateIndices(indices, offset, gpuMemoryOnly = false) { - if (!this._indexBuffer) { - return; - } - if (!this._indexBufferIsUpdatable) { - this.setIndices(indices, null, true); - } - else { - const needToUpdateSubMeshes = indices.length !== this._indices.length; - if (!gpuMemoryOnly) { - this._indices = indices.slice(); - } - this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset); - if (needToUpdateSubMeshes) { - for (const mesh of this._meshes) { - mesh._createGlobalSubMesh(true); - } - } - } - } - /** - * Creates a new index buffer - * @param indices defines the indices to store in the index buffer - * @param totalVertices defines the total number of vertices (could be null) - * @param updatable defines if the index buffer must be flagged as updatable (false by default) - */ - setIndices(indices, totalVertices = null, updatable = false) { - if (this._indexBuffer) { - this._engine._releaseBuffer(this._indexBuffer); - } - this._indices = indices; - this._indexBufferIsUpdatable = updatable; - if (this._meshes.length !== 0 && this._indices) { - this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable); - } - if (totalVertices != undefined) { - // including null and undefined - this._totalVertices = totalVertices; - } - for (const mesh of this._meshes) { - mesh._createGlobalSubMesh(true); - mesh.synchronizeInstances(); - } - this._notifyUpdate(); - } - /** - * Return the total number of indices - * @returns the total number of indices - */ - getTotalIndices() { - if (!this.isReady()) { - return 0; - } - return this._indices.length; - } - /** - * Gets the index buffer array - * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes - * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it - * @returns the index buffer array - */ - getIndices(copyWhenShared, forceCopy) { - if (!this.isReady()) { - return null; - } - const orig = this._indices; - if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) { - return orig; - } - else { - return orig.slice(); - } - } - /** - * Gets the index buffer - * @returns the index buffer - */ - getIndexBuffer() { - if (!this.isReady()) { - return null; - } - return this._indexBuffer; - } - /** - * @internal - */ - _releaseVertexArrayObject(effect = null) { - if (!effect || !this._vertexArrayObjects) { - return; - } - if (this._vertexArrayObjects[effect.key]) { - this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]); - delete this._vertexArrayObjects[effect.key]; - } - } - /** - * Release the associated resources for a specific mesh - * @param mesh defines the source mesh - * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it - */ - releaseForMesh(mesh, shouldDispose) { - const meshes = this._meshes; - const index = meshes.indexOf(mesh); - if (index === -1) { - return; - } - meshes.splice(index, 1); - if (this._vertexArrayObjects) { - mesh._invalidateInstanceVertexArrayObject(); - } - mesh._geometry = null; - if (meshes.length === 0 && shouldDispose) { - this.dispose(); - } - } - /** - * Apply current geometry to a given mesh - * @param mesh defines the mesh to apply geometry to - */ - applyToMesh(mesh) { - if (mesh._geometry === this) { - return; - } - const previousGeometry = mesh._geometry; - if (previousGeometry) { - previousGeometry.releaseForMesh(mesh); - } - if (this._vertexArrayObjects) { - mesh._invalidateInstanceVertexArrayObject(); - } - const meshes = this._meshes; - // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh() - mesh._geometry = this; - mesh._internalAbstractMeshDataInfo._positions = null; - this._scene.pushGeometry(this); - meshes.push(mesh); - if (this.isReady()) { - this._applyToMesh(mesh); - } - else if (this._boundingInfo) { - mesh.setBoundingInfo(this._boundingInfo); - } - } - _updateExtend(data = null) { - if (this.useBoundingInfoFromGeometry && this._boundingInfo) { - this._extend = { - minimum: this._boundingInfo.minimum.clone(), - maximum: this._boundingInfo.maximum.clone(), - }; - } - else { - if (!data) { - data = this.getVerticesData(buffer_VertexBuffer.PositionKind); - // This can happen if the buffer comes from a Hardware Buffer where - // The data have not been uploaded by Babylon. (ex: Compute Shaders and Storage Buffers) - if (!data) { - return; - } - } - this._extend = extractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3); - } - } - _applyToMesh(mesh) { - const numOfMeshes = this._meshes.length; - // vertexBuffers - for (const kind in this._vertexBuffers) { - if (numOfMeshes === 1) { - this._vertexBuffers[kind].create(); - } - if (kind === buffer_VertexBuffer.PositionKind) { - if (!this._extend) { - this._updateExtend(); - } - mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum); - mesh._createGlobalSubMesh(mesh.isUnIndexed); - //bounding info was just created again, world matrix should be applied again. - mesh._updateBoundingInfo(); - } - } - // indexBuffer - if (numOfMeshes === 1 && this._indices && this._indices.length > 0) { - this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable); - } - // morphTargets - mesh._syncGeometryWithMorphTargetManager(); - // instances - mesh.synchronizeInstances(); - } - _notifyUpdate(kind) { - if (this.onGeometryUpdated) { - this.onGeometryUpdated(this, kind); - } - if (this._vertexArrayObjects) { - this._disposeVertexArrayObjects(); - } - for (const mesh of this._meshes) { - mesh._markSubMeshesAsAttributesDirty(); - } - } - /** - * Load the geometry if it was flagged as delay loaded - * @param scene defines the hosting scene - * @param onLoaded defines a callback called when the geometry is loaded - */ - load(scene, onLoaded) { - if (this.delayLoadState === 2) { - return; - } - if (this.isReady()) { - if (onLoaded) { - onLoaded(); - } - return; - } - this.delayLoadState = 2; - this._queueLoad(scene, onLoaded); - } - _queueLoad(scene, onLoaded) { - if (!this.delayLoadingFile) { - return; - } - scene.addPendingData(this); - scene._loadFile(this.delayLoadingFile, (data) => { - if (!this._delayLoadingFunction) { - return; - } - this._delayLoadingFunction(JSON.parse(data), this); - this.delayLoadState = 1; - this._delayInfo = []; - scene.removePendingData(this); - const meshes = this._meshes; - const numOfMeshes = meshes.length; - for (let index = 0; index < numOfMeshes; index++) { - this._applyToMesh(meshes[index]); - } - if (onLoaded) { - onLoaded(); - } - }, undefined, true); - } - /** - * Invert the geometry to move from a right handed system to a left handed one. - */ - toLeftHanded() { - // Flip faces - const tIndices = this.getIndices(false); - if (tIndices != null && tIndices.length > 0) { - for (let i = 0; i < tIndices.length; i += 3) { - const tTemp = tIndices[i + 0]; - tIndices[i + 0] = tIndices[i + 2]; - tIndices[i + 2] = tTemp; - } - this.setIndices(tIndices); - } - // Negate position.z - const tPositions = this.getVerticesData(buffer_VertexBuffer.PositionKind, false); - if (tPositions != null && tPositions.length > 0) { - for (let i = 0; i < tPositions.length; i += 3) { - tPositions[i + 2] = -tPositions[i + 2]; - } - this.setVerticesData(buffer_VertexBuffer.PositionKind, tPositions, false); - } - // Negate normal.z - const tNormals = this.getVerticesData(buffer_VertexBuffer.NormalKind, false); - if (tNormals != null && tNormals.length > 0) { - for (let i = 0; i < tNormals.length; i += 3) { - tNormals[i + 2] = -tNormals[i + 2]; - } - this.setVerticesData(buffer_VertexBuffer.NormalKind, tNormals, false); - } - } - // Cache - /** @internal */ - _resetPointsArrayCache() { - this._positions = null; - } - /** @internal */ - _generatePointsArray() { - if (this._positions) { - return true; - } - const data = this.getVerticesData(buffer_VertexBuffer.PositionKind); - if (!data || data.length === 0) { - return false; - } - for (let index = this._positionsCache.length * 3, arrayIdx = this._positionsCache.length; index < data.length; index += 3, ++arrayIdx) { - this._positionsCache[arrayIdx] = math_vector_Vector3.FromArray(data, index); - } - for (let index = 0, arrayIdx = 0; index < data.length; index += 3, ++arrayIdx) { - this._positionsCache[arrayIdx].set(data[0 + index], data[1 + index], data[2 + index]); - } - // just in case the number of positions was reduced, splice the array - this._positionsCache.length = data.length / 3; - this._positions = this._positionsCache; - return true; - } - /** - * Gets a value indicating if the geometry is disposed - * @returns true if the geometry was disposed - */ - isDisposed() { - return this._isDisposed; - } - _disposeVertexArrayObjects() { - if (this._vertexArrayObjects) { - for (const kind in this._vertexArrayObjects) { - this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]); - } - this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported - const meshes = this._meshes; - const numOfMeshes = meshes.length; - for (let index = 0; index < numOfMeshes; index++) { - meshes[index]._invalidateInstanceVertexArrayObject(); - } - } - } - /** - * Free all associated resources - */ - dispose() { - const meshes = this._meshes; - const numOfMeshes = meshes.length; - let index; - for (index = 0; index < numOfMeshes; index++) { - this.releaseForMesh(meshes[index]); - } - this._meshes.length = 0; - this._disposeVertexArrayObjects(); - for (const kind in this._vertexBuffers) { - this._vertexBuffers[kind].dispose(); - } - this._vertexBuffers = {}; - this._totalVertices = 0; - if (this._indexBuffer) { - this._engine._releaseBuffer(this._indexBuffer); - } - this._indexBuffer = null; - this._indices = []; - this.delayLoadState = 0; - this.delayLoadingFile = null; - this._delayLoadingFunction = null; - this._delayInfo = []; - this._boundingInfo = null; - this._scene.removeGeometry(this); - if (this._parentContainer) { - const index = this._parentContainer.geometries.indexOf(this); - if (index > -1) { - this._parentContainer.geometries.splice(index, 1); - } - this._parentContainer = null; - } - this._isDisposed = true; - } - /** - * Clone the current geometry into a new geometry - * @param id defines the unique ID of the new geometry - * @returns a new geometry object - */ - copy(id) { - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = []; - const indices = this.getIndices(); - if (indices) { - for (let index = 0; index < indices.length; index++) { - vertexData.indices.push(indices[index]); - } - } - let updatable = false; - let stopChecking = false; - let kind; - for (kind in this._vertexBuffers) { - // using slice() to make a copy of the array and not just reference it - const data = this.getVerticesData(kind); - if (data) { - if (data instanceof Float32Array) { - vertexData.set(new Float32Array(data), kind); - } - else { - vertexData.set(data.slice(0), kind); - } - if (!stopChecking) { - const vb = this.getVertexBuffer(kind); - if (vb) { - updatable = vb.isUpdatable(); - stopChecking = !updatable; - } - } - } - } - const geometry = new Geometry(id, this._scene, vertexData, updatable); - geometry.delayLoadState = this.delayLoadState; - geometry.delayLoadingFile = this.delayLoadingFile; - geometry._delayLoadingFunction = this._delayLoadingFunction; - for (kind in this._delayInfo) { - geometry._delayInfo = geometry._delayInfo || []; - geometry._delayInfo.push(kind); - } - // Bounding info - geometry._boundingInfo = new boundingInfo_BoundingInfo(this._extend.minimum, this._extend.maximum); - return geometry; - } - /** - * Serialize the current geometry info (and not the vertices data) into a JSON object - * @returns a JSON representation of the current geometry data (without the vertices data) - */ - serialize() { - const serializationObject = {}; - serializationObject.id = this.id; - serializationObject.uniqueId = this.uniqueId; - serializationObject.updatable = this._updatable; - if (Tags && Tags.HasTags(this)) { - serializationObject.tags = Tags.GetTags(this); - } - return serializationObject; - } - _toNumberArray(origin) { - if (Array.isArray(origin)) { - return origin; - } - else { - return Array.prototype.slice.call(origin); - } - } - /** - * Release any memory retained by the cached data on the Geometry. - * - * Call this function to reduce memory footprint of the mesh. - * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly) - */ - clearCachedData() { - this._indices = []; - this._resetPointsArrayCache(); - for (const vbName in this._vertexBuffers) { - if (!Object.prototype.hasOwnProperty.call(this._vertexBuffers, vbName)) { - continue; - } - this._vertexBuffers[vbName]._buffer._data = null; - } - } - /** - * Serialize all vertices data into a JSON object - * @returns a JSON representation of the current geometry data - */ - serializeVerticeData() { - const serializationObject = this.serialize(); - if (this.isVerticesDataPresent(buffer_VertexBuffer.PositionKind)) { - serializationObject.positions = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.PositionKind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind)) { - serializationObject.positions._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)) { - serializationObject.normals = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.NormalKind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.NormalKind)) { - serializationObject.normals._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)) { - serializationObject.tangents = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.TangentKind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.TangentKind)) { - serializationObject.tangents._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - serializationObject.uvs = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UVKind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.UVKind)) { - serializationObject.uvs._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)) { - serializationObject.uv2s = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UV2Kind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.UV2Kind)) { - serializationObject.uv2s._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.UV3Kind)) { - serializationObject.uv3s = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UV3Kind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.UV3Kind)) { - serializationObject.uv3s._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.UV4Kind)) { - serializationObject.uv4s = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UV4Kind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.UV4Kind)) { - serializationObject.uv4s._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.UV5Kind)) { - serializationObject.uv5s = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UV5Kind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.UV5Kind)) { - serializationObject.uv5s._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.UV6Kind)) { - serializationObject.uv6s = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UV6Kind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.UV6Kind)) { - serializationObject.uv6s._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.ColorKind)) { - serializationObject.colors = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.ColorKind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.ColorKind)) { - serializationObject.colors._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesKind)) { - serializationObject.matricesIndices = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind)); - serializationObject.matricesIndices._isExpanded = true; - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.MatricesIndicesKind)) { - serializationObject.matricesIndices._updatable = true; - } - } - if (this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)) { - serializationObject.matricesWeights = this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind)); - if (this.isVertexBufferUpdatable(buffer_VertexBuffer.MatricesWeightsKind)) { - serializationObject.matricesWeights._updatable = true; - } - } - serializationObject.indices = this._toNumberArray(this.getIndices()); - return serializationObject; - } - // Statics - /** - * Extracts a clone of a mesh geometry - * @param mesh defines the source mesh - * @param id defines the unique ID of the new geometry object - * @returns the new geometry object - */ - static ExtractFromMesh(mesh, id) { - const geometry = mesh._geometry; - if (!geometry) { - return null; - } - return geometry.copy(id); - } - /** - * You should now use Tools.RandomId(), this method is still here for legacy reasons. - * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 - * Be aware Math.random() could cause collisions, but: - * "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" - * @returns a string containing a new GUID - */ - static RandomId() { - return tools_Tools.RandomId(); - } - static _GetGeometryByLoadedUniqueId(uniqueId, scene) { - for (let index = 0; index < scene.geometries.length; index++) { - if (scene.geometries[index]._loadedUniqueId === uniqueId) { - return scene.geometries[index]; - } - } - return null; - } - /** - * @internal - */ - static _ImportGeometry(parsedGeometry, mesh) { - const scene = mesh.getScene(); - // Geometry - const geometryUniqueId = parsedGeometry.geometryUniqueId; - const geometryId = parsedGeometry.geometryId; - if (geometryUniqueId || geometryId) { - const geometry = geometryUniqueId ? this._GetGeometryByLoadedUniqueId(geometryUniqueId, scene) : scene.getGeometryById(geometryId); - if (geometry) { - geometry.applyToMesh(mesh); - } - } - else if (parsedGeometry instanceof ArrayBuffer) { - const binaryInfo = mesh._binaryInfo; - if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) { - const positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count); - mesh.setVerticesData(buffer_VertexBuffer.PositionKind, positionsData, false); - } - if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) { - const normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count); - mesh.setVerticesData(buffer_VertexBuffer.NormalKind, normalsData, false); - } - if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) { - const tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count); - mesh.setVerticesData(buffer_VertexBuffer.TangentKind, tangentsData, false); - } - if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) { - const uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count); - if (CompatibilityOptions.UseOpenGLOrientationForUV) { - for (let index = 1; index < uvsData.length; index += 2) { - uvsData[index] = 1 - uvsData[index]; - } - } - mesh.setVerticesData(buffer_VertexBuffer.UVKind, uvsData, false); - } - if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) { - const uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count); - if (CompatibilityOptions.UseOpenGLOrientationForUV) { - for (let index = 1; index < uvs2Data.length; index += 2) { - uvs2Data[index] = 1 - uvs2Data[index]; - } - } - mesh.setVerticesData(buffer_VertexBuffer.UV2Kind, uvs2Data, false); - } - if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) { - const uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count); - if (CompatibilityOptions.UseOpenGLOrientationForUV) { - for (let index = 1; index < uvs3Data.length; index += 2) { - uvs3Data[index] = 1 - uvs3Data[index]; - } - } - mesh.setVerticesData(buffer_VertexBuffer.UV3Kind, uvs3Data, false); - } - if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) { - const uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count); - if (CompatibilityOptions.UseOpenGLOrientationForUV) { - for (let index = 1; index < uvs4Data.length; index += 2) { - uvs4Data[index] = 1 - uvs4Data[index]; - } - } - mesh.setVerticesData(buffer_VertexBuffer.UV4Kind, uvs4Data, false); - } - if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) { - const uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count); - if (CompatibilityOptions.UseOpenGLOrientationForUV) { - for (let index = 1; index < uvs5Data.length; index += 2) { - uvs5Data[index] = 1 - uvs5Data[index]; - } - } - mesh.setVerticesData(buffer_VertexBuffer.UV5Kind, uvs5Data, false); - } - if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) { - const uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count); - if (CompatibilityOptions.UseOpenGLOrientationForUV) { - for (let index = 1; index < uvs6Data.length; index += 2) { - uvs6Data[index] = 1 - uvs6Data[index]; - } - } - mesh.setVerticesData(buffer_VertexBuffer.UV6Kind, uvs6Data, false); - } - if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) { - const colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count); - mesh.setVerticesData(buffer_VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride); - } - if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) { - const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count); - const floatIndices = []; - for (let i = 0; i < matricesIndicesData.length; i++) { - const index = matricesIndicesData[i]; - floatIndices.push(index & 0x000000ff); - floatIndices.push((index & 0x0000ff00) >> 8); - floatIndices.push((index & 0x00ff0000) >> 16); - floatIndices.push((index >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0 - } - mesh.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind, floatIndices, false); - } - if (binaryInfo.matricesIndicesExtraAttrDesc && binaryInfo.matricesIndicesExtraAttrDesc.count > 0) { - const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesExtraAttrDesc.offset, binaryInfo.matricesIndicesExtraAttrDesc.count); - const floatIndices = []; - for (let i = 0; i < matricesIndicesData.length; i++) { - const index = matricesIndicesData[i]; - floatIndices.push(index & 0x000000ff); - floatIndices.push((index & 0x0000ff00) >> 8); - floatIndices.push((index & 0x00ff0000) >> 16); - floatIndices.push((index >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0 - } - mesh.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind, floatIndices, false); - } - if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) { - const matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count); - mesh.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind, matricesWeightsData, false); - } - if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) { - const indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count); - mesh.setIndices(indicesData, null); - } - if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) { - const subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5); - mesh.subMeshes = []; - for (let i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) { - const materialIndex = subMeshesData[i * 5 + 0]; - const verticesStart = subMeshesData[i * 5 + 1]; - const verticesCount = subMeshesData[i * 5 + 2]; - const indexStart = subMeshesData[i * 5 + 3]; - const indexCount = subMeshesData[i * 5 + 4]; - subMesh_SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh); - } - } - } - else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) { - mesh.setVerticesData(buffer_VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable); - mesh.setVerticesData(buffer_VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable); - if (parsedGeometry.tangents) { - mesh.setVerticesData(buffer_VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable); - } - if (parsedGeometry.uvs) { - mesh.setVerticesData(buffer_VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable); - } - if (parsedGeometry.uvs2) { - mesh.setVerticesData(buffer_VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable); - } - if (parsedGeometry.uvs3) { - mesh.setVerticesData(buffer_VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable); - } - if (parsedGeometry.uvs4) { - mesh.setVerticesData(buffer_VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable); - } - if (parsedGeometry.uvs5) { - mesh.setVerticesData(buffer_VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable); - } - if (parsedGeometry.uvs6) { - mesh.setVerticesData(buffer_VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable); - } - if (parsedGeometry.colors) { - mesh.setVerticesData(buffer_VertexBuffer.ColorKind, math_color_Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable); - } - if (parsedGeometry.matricesIndices) { - if (!parsedGeometry.matricesIndices._isExpanded) { - const floatIndices = []; - for (let i = 0; i < parsedGeometry.matricesIndices.length; i++) { - const matricesIndex = parsedGeometry.matricesIndices[i]; - floatIndices.push(matricesIndex & 0x000000ff); - floatIndices.push((matricesIndex & 0x0000ff00) >> 8); - floatIndices.push((matricesIndex & 0x00ff0000) >> 16); - floatIndices.push((matricesIndex >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0 - } - mesh.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable); - } - else { - delete parsedGeometry.matricesIndices._isExpanded; - mesh.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable); - } - } - if (parsedGeometry.matricesIndicesExtra) { - if (!parsedGeometry.matricesIndicesExtra._isExpanded) { - const floatIndices = []; - for (let i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) { - const matricesIndex = parsedGeometry.matricesIndicesExtra[i]; - floatIndices.push(matricesIndex & 0x000000ff); - floatIndices.push((matricesIndex & 0x0000ff00) >> 8); - floatIndices.push((matricesIndex & 0x00ff0000) >> 16); - floatIndices.push((matricesIndex >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0 - } - mesh.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable); - } - else { - delete parsedGeometry.matricesIndices._isExpanded; - mesh.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable); - } - } - if (parsedGeometry.matricesWeights) { - Geometry._CleanMatricesWeights(parsedGeometry, mesh); - mesh.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable); - } - if (parsedGeometry.matricesWeightsExtra) { - mesh.setVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable); - } - mesh.setIndices(parsedGeometry.indices, null); - } - // SubMeshes - if (parsedGeometry.subMeshes) { - mesh.subMeshes = []; - for (let subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) { - const parsedSubMesh = parsedGeometry.subMeshes[subIndex]; - subMesh_SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh); - } - } - // Flat shading - if (mesh._shouldGenerateFlatShading) { - mesh.convertToFlatShadedMesh(); - mesh._shouldGenerateFlatShading = false; - } - // Update - mesh.computeWorldMatrix(true); - scene.onMeshImportedObservable.notifyObservers(mesh); - } - static _CleanMatricesWeights(parsedGeometry, mesh) { - const epsilon = 1e-3; - if (!SceneLoaderFlags.CleanBoneMatrixWeights) { - return; - } - let noInfluenceBoneIndex = 0.0; - if (parsedGeometry.skeletonId > -1) { - const skeleton = mesh.getScene().getLastSkeletonById(parsedGeometry.skeletonId); - if (!skeleton) { - return; - } - noInfluenceBoneIndex = skeleton.bones.length; - } - else { - return; - } - const matricesIndices = mesh.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind); - const matricesIndicesExtra = mesh.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind); - const matricesWeights = parsedGeometry.matricesWeights; - const matricesWeightsExtra = parsedGeometry.matricesWeightsExtra; - const influencers = parsedGeometry.numBoneInfluencer; - const size = matricesWeights.length; - for (let i = 0; i < size; i += 4) { - let weight = 0.0; - let firstZeroWeight = -1; - for (let j = 0; j < 4; j++) { - const w = matricesWeights[i + j]; - weight += w; - if (w < epsilon && firstZeroWeight < 0) { - firstZeroWeight = j; - } - } - if (matricesWeightsExtra) { - for (let j = 0; j < 4; j++) { - const w = matricesWeightsExtra[i + j]; - weight += w; - if (w < epsilon && firstZeroWeight < 0) { - firstZeroWeight = j + 4; - } - } - } - if (firstZeroWeight < 0 || firstZeroWeight > influencers - 1) { - firstZeroWeight = influencers - 1; - } - if (weight > epsilon) { - const mweight = 1.0 / weight; - for (let j = 0; j < 4; j++) { - matricesWeights[i + j] *= mweight; - } - if (matricesWeightsExtra) { - for (let j = 0; j < 4; j++) { - matricesWeightsExtra[i + j] *= mweight; - } - } - } - else { - if (firstZeroWeight >= 4) { - matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight; - matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex; - } - else { - matricesWeights[i + firstZeroWeight] = 1.0 - weight; - matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex; - } - } - } - mesh.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind, matricesIndices); - if (parsedGeometry.matricesWeightsExtra) { - mesh.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra); - } - } - /** - * Create a new geometry from persisted data (Using .babylon file format) - * @param parsedVertexData defines the persisted data - * @param scene defines the hosting scene - * @param rootUrl defines the root url to use to load assets (like delayed data) - * @returns the new geometry object - */ - static Parse(parsedVertexData, scene, rootUrl) { - const geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable); - geometry._loadedUniqueId = parsedVertexData.uniqueId; - if (Tags) { - Tags.AddTagsTo(geometry, parsedVertexData.tags); - } - if (parsedVertexData.delayLoadingFile) { - geometry.delayLoadState = 4; - geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile; - geometry._boundingInfo = new boundingInfo_BoundingInfo(math_vector_Vector3.FromArray(parsedVertexData.boundingBoxMinimum), math_vector_Vector3.FromArray(parsedVertexData.boundingBoxMaximum)); - geometry._delayInfo = []; - if (parsedVertexData.hasUVs) { - geometry._delayInfo.push(buffer_VertexBuffer.UVKind); - } - if (parsedVertexData.hasUVs2) { - geometry._delayInfo.push(buffer_VertexBuffer.UV2Kind); - } - if (parsedVertexData.hasUVs3) { - geometry._delayInfo.push(buffer_VertexBuffer.UV3Kind); - } - if (parsedVertexData.hasUVs4) { - geometry._delayInfo.push(buffer_VertexBuffer.UV4Kind); - } - if (parsedVertexData.hasUVs5) { - geometry._delayInfo.push(buffer_VertexBuffer.UV5Kind); - } - if (parsedVertexData.hasUVs6) { - geometry._delayInfo.push(buffer_VertexBuffer.UV6Kind); - } - if (parsedVertexData.hasColors) { - geometry._delayInfo.push(buffer_VertexBuffer.ColorKind); - } - if (parsedVertexData.hasMatricesIndices) { - geometry._delayInfo.push(buffer_VertexBuffer.MatricesIndicesKind); - } - if (parsedVertexData.hasMatricesWeights) { - geometry._delayInfo.push(buffer_VertexBuffer.MatricesWeightsKind); - } - geometry._delayLoadingFunction = mesh_vertexData_VertexData.ImportVertexData; - } - else { - mesh_vertexData_VertexData.ImportVertexData(parsedVertexData, geometry); - } - scene.pushGeometry(geometry, true); - return geometry; - } -} -//# sourceMappingURL=geometry.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/performanceMonitor.js - -/** - * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window - */ -class PerformanceMonitor { - /** - * constructor - * @param frameSampleSize The number of samples required to saturate the sliding window - */ - constructor(frameSampleSize = 30) { - this._enabled = true; - this._rollingFrameTime = new RollingAverage(frameSampleSize); - } - /** - * Samples current frame - * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames - */ - sampleFrame(timeMs = precisionDate_PrecisionDate.Now) { - if (!this._enabled) { - return; - } - if (this._lastFrameTimeMs != null) { - const dt = timeMs - this._lastFrameTimeMs; - this._rollingFrameTime.add(dt); - } - this._lastFrameTimeMs = timeMs; - } - /** - * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far) - */ - get averageFrameTime() { - return this._rollingFrameTime.average; - } - /** - * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far) - */ - get averageFrameTimeVariance() { - return this._rollingFrameTime.variance; - } - /** - * Returns the frame time of the most recent frame - */ - get instantaneousFrameTime() { - return this._rollingFrameTime.history(0); - } - /** - * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far) - */ - get averageFPS() { - return 1000.0 / this._rollingFrameTime.average; - } - /** - * Returns the average framerate in frames per second using the most recent frame time - */ - get instantaneousFPS() { - const history = this._rollingFrameTime.history(0); - if (history === 0) { - return 0; - } - return 1000.0 / history; - } - /** - * Returns true if enough samples have been taken to completely fill the sliding window - */ - get isSaturated() { - return this._rollingFrameTime.isSaturated(); - } - /** - * Enables contributions to the sliding window sample set - */ - enable() { - this._enabled = true; - } - /** - * Disables contributions to the sliding window sample set - * Samples will not be interpolated over the disabled period - */ - disable() { - this._enabled = false; - //clear last sample to avoid interpolating over the disabled period when next enabled - this._lastFrameTimeMs = null; - } - /** - * Returns true if sampling is enabled - */ - get isEnabled() { - return this._enabled; - } - /** - * Resets performance monitor - */ - reset() { - //clear last sample to avoid interpolating over the disabled period when next enabled - this._lastFrameTimeMs = null; - //wipe record - this._rollingFrameTime.reset(); - } -} -/** - * RollingAverage - * - * Utility to efficiently compute the rolling average and variance over a sliding window of samples - */ -class RollingAverage { - /** - * constructor - * @param length The number of samples required to saturate the sliding window - */ - constructor(length) { - this._samples = new Array(length); - this.reset(); - } - /** - * Adds a sample to the sample set - * @param v The sample value - */ - add(v) { - //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance - let delta; - //we need to check if we've already wrapped round - if (this.isSaturated()) { - //remove bottom of stack from mean - const bottomValue = this._samples[this._pos]; - delta = bottomValue - this.average; - this.average -= delta / (this._sampleCount - 1); - this._m2 -= delta * (bottomValue - this.average); - } - else { - this._sampleCount++; - } - //add new value to mean - delta = v - this.average; - this.average += delta / this._sampleCount; - this._m2 += delta * (v - this.average); - //set the new variance - this.variance = this._m2 / (this._sampleCount - 1); - this._samples[this._pos] = v; - this._pos++; - this._pos %= this._samples.length; //positive wrap around - } - /** - * Returns previously added values or null if outside of history or outside the sliding window domain - * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that - * @returns Value previously recorded with add() or null if outside of range - */ - history(i) { - if (i >= this._sampleCount || i >= this._samples.length) { - return 0; - } - const i0 = this._wrapPosition(this._pos - 1.0); - return this._samples[this._wrapPosition(i0 - i)]; - } - /** - * Returns true if enough samples have been taken to completely fill the sliding window - * @returns true if sample-set saturated - */ - isSaturated() { - return this._sampleCount >= this._samples.length; - } - /** - * Resets the rolling average (equivalent to 0 samples taken so far) - */ - reset() { - this.average = 0; - this.variance = 0; - this._sampleCount = 0; - this._pos = 0; - this._m2 = 0; - } - /** - * Wraps a value around the sample range boundaries - * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned. - * @returns Wrapped position in sample range - */ - _wrapPosition(i) { - const max = this._samples.length; - return ((i % max) + max) % max; - } -} -//# sourceMappingURL=performanceMonitor.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.alpha.js - - -ThinEngine.prototype.setAlphaConstants = function (r, g, b, a) { - this._alphaState.setAlphaBlendConstants(r, g, b, a); -}; -ThinEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange = false) { - if (this._alphaMode === mode) { - if (!noDepthWriteChange) { - // 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) - const depthMask = mode === 0; - if (this.depthCullingState.depthMask !== depthMask) { - this.depthCullingState.depthMask = depthMask; - } - } - return; - } - switch (mode) { - case 0: - this._alphaState.alphaBlend = false; - break; - case 7: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE); - this._alphaState.alphaBlend = true; - break; - case 8: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); - this._alphaState.alphaBlend = true; - break; - case 2: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE); - this._alphaState.alphaBlend = true; - break; - case 6: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE); - this._alphaState.alphaBlend = true; - break; - case 1: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE); - this._alphaState.alphaBlend = true; - break; - case 3: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE); - this._alphaState.alphaBlend = true; - break; - case 4: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE); - this._alphaState.alphaBlend = true; - break; - case 5: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE); - this._alphaState.alphaBlend = true; - break; - case 9: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA); - this._alphaState.alphaBlend = true; - break; - case 10: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); - this._alphaState.alphaBlend = true; - break; - case 11: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ONE); - this._alphaState.alphaBlend = true; - break; - case 12: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ZERO); - this._alphaState.alphaBlend = true; - break; - case 13: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE_MINUS_DST_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA); - this._alphaState.alphaBlend = true; - break; - case 14: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); - this._alphaState.alphaBlend = true; - break; - case 15: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ZERO); - this._alphaState.alphaBlend = true; - break; - case 16: - this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ZERO, this._gl.ONE); - this._alphaState.alphaBlend = true; - break; - case 17: - // Same as ALPHA_COMBINE but accumulates (1 - alpha) values in the alpha channel for a later readout in order independant transparency - this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); - this._alphaState.alphaBlend = true; - break; - } - if (!noDepthWriteChange) { - this.depthCullingState.depthMask = mode === 0; - } - this._alphaMode = mode; -}; -ThinEngine.prototype.getAlphaMode = function () { - return this._alphaMode; -}; -ThinEngine.prototype.setAlphaEquation = function (equation) { - if (this._alphaEquation === equation) { - return; - } - switch (equation) { - case 0: - this._alphaState.setAlphaEquationParameters(32774, 32774); - break; - case 1: - this._alphaState.setAlphaEquationParameters(32778, 32778); - break; - case 2: - this._alphaState.setAlphaEquationParameters(32779, 32779); - break; - case 3: - this._alphaState.setAlphaEquationParameters(32776, 32776); - break; - case 4: - this._alphaState.setAlphaEquationParameters(32775, 32775); - break; - case 5: - this._alphaState.setAlphaEquationParameters(32775, 32774); - break; - } - this._alphaEquation = equation; -}; -ThinEngine.prototype.getAlphaEquation = function () { - return this._alphaEquation; -}; -//# sourceMappingURL=engine.alpha.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.readTexture.js - - -/** - * Allocate a typed array depending on a texture type. Optionally can copy existing data in the buffer. - * @param type type of the texture - * @param sizeOrDstBuffer size of the array OR an existing buffer that will be used as the destination of the copy (if copyBuffer is provided) - * @param sizeInBytes true if the size of the array is given in bytes, false if it is the number of elements of the array - * @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) - * @returns the allocated buffer or sizeOrDstBuffer if the latter is an ArrayBuffer - */ -function allocateAndCopyTypedBuffer(type, sizeOrDstBuffer, sizeInBytes = false, copyBuffer) { - switch (type) { - case 3: { - const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int8Array(sizeOrDstBuffer) : new Int8Array(sizeOrDstBuffer); - if (copyBuffer) { - buffer.set(new Int8Array(copyBuffer)); - } - return buffer; - } - case 0: { - const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer); - if (copyBuffer) { - buffer.set(new Uint8Array(copyBuffer)); - } - return buffer; - } - case 4: { - const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int16Array(sizeOrDstBuffer) : new Int16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer); - if (copyBuffer) { - buffer.set(new Int16Array(copyBuffer)); - } - return buffer; - } - case 5: - case 8: - case 9: - case 10: - case 2: { - const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint16Array(sizeOrDstBuffer) : new Uint16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer); - if (copyBuffer) { - buffer.set(new Uint16Array(copyBuffer)); - } - return buffer; - } - case 6: { - const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int32Array(sizeOrDstBuffer) : new Int32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer); - if (copyBuffer) { - buffer.set(new Int32Array(copyBuffer)); - } - return buffer; - } - case 7: - case 11: - case 12: - case 13: - case 14: - case 15: { - const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint32Array(sizeOrDstBuffer) : new Uint32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer); - if (copyBuffer) { - buffer.set(new Uint32Array(copyBuffer)); - } - return buffer; - } - case 1: { - const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Float32Array(sizeOrDstBuffer) : new Float32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer); - if (copyBuffer) { - buffer.set(new Float32Array(copyBuffer)); - } - return buffer; - } - } - const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer); - if (copyBuffer) { - buffer.set(new Uint8Array(copyBuffer)); - } - return buffer; -} -ThinEngine.prototype._readTexturePixelsSync = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) { - var _a, _b; - const gl = this._gl; - if (!gl) { - throw new Error("Engine does not have gl rendering context."); - } - if (!this._dummyFramebuffer) { - const dummy = gl.createFramebuffer(); - if (!dummy) { - throw new Error("Unable to create dummy framebuffer"); - } - this._dummyFramebuffer = dummy; - } - gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer); - if (faceIndex > -1) { - 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); - } - else { - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, (_b = texture._hardwareTexture) === null || _b === void 0 ? void 0 : _b.underlyingResource, level); - } - let readType = texture.type !== undefined ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE; - if (!noDataConversion) { - switch (readType) { - case gl.UNSIGNED_BYTE: - if (!buffer) { - buffer = new Uint8Array(4 * width * height); - } - readType = gl.UNSIGNED_BYTE; - break; - default: - if (!buffer) { - buffer = new Float32Array(4 * width * height); - } - readType = gl.FLOAT; - break; - } - } - else if (!buffer) { - buffer = allocateAndCopyTypedBuffer(texture.type, 4 * width * height); - } - if (flushRenderer) { - this.flushFramebuffer(); - } - gl.readPixels(x, y, width, height, gl.RGBA, readType, buffer); - gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer); - return buffer; -}; -ThinEngine.prototype._readTexturePixels = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) { - return Promise.resolve(this._readTexturePixelsSync(texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y)); -}; -//# sourceMappingURL=engine.readTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicBuffer.js - -// eslint-disable-next-line @typescript-eslint/no-unused-vars -ThinEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset = 0) { - // Force cache update - this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null; - this.bindIndexBuffer(indexBuffer); - let view; - if (indexBuffer.is32Bits) { - // anything else than Uint32Array needs to be converted to Uint32Array - view = indices instanceof Uint32Array ? indices : new Uint32Array(indices); - } - else { - // anything else than Uint16Array needs to be converted to Uint16Array - view = indices instanceof Uint16Array ? indices : new Uint16Array(indices); - } - this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, view, this._gl.DYNAMIC_DRAW); - this._resetIndexBufferBinding(); -}; -ThinEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) { - this.bindArrayBuffer(vertexBuffer); - if (byteOffset === undefined) { - byteOffset = 0; - } - const dataLength = data.byteLength || data.length; - if (byteLength === undefined || (byteLength >= dataLength && byteOffset === 0)) { - if (data instanceof Array) { - this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data)); - } - else { - this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data); - } - } - else { - if (data instanceof Array) { - this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength)); - } - else { - if (data instanceof ArrayBuffer) { - data = new Uint8Array(data, byteOffset, byteLength); - } - else { - data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength); - } - this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); - } - } - this._resetVertexBufferBinding(); -}; -//# sourceMappingURL=engine.dynamicBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/engine.js - - - - - - - - - - - - - - - -/** - * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio - */ -class engine_Engine extends ThinEngine { - /** - * Returns the current npm package of the sdk - */ - // Not mixed with Version for tooling purpose. - static get NpmPackage() { - return ThinEngine.NpmPackage; - } - /** - * Returns the current version of the framework - */ - static get Version() { - return ThinEngine.Version; - } - /** Gets the list of created engines */ - static get Instances() { - return engineStore_EngineStore.Instances; - } - /** - * Gets the latest created engine - */ - static get LastCreatedEngine() { - return engineStore_EngineStore.LastCreatedEngine; - } - /** - * Gets the latest created scene - */ - static get LastCreatedScene() { - return engineStore_EngineStore.LastCreatedScene; - } - /** @internal */ - /** - * Engine abstraction for loading and creating an image bitmap from a given source string. - * @param imageSource source to load the image from. - * @param options An object that sets options for the image's extraction. - * @returns ImageBitmap. - */ - _createImageBitmapFromSource(imageSource, options) { - const promise = new Promise((resolve, reject) => { - const image = new Image(); - image.onload = () => { - image.decode().then(() => { - this.createImageBitmap(image, options).then((imageBitmap) => { - resolve(imageBitmap); - }); - }); - }; - image.onerror = () => { - reject(`Error loading image ${image.src}`); - }; - image.src = imageSource; - }); - return promise; - } - /** - * Engine abstraction for createImageBitmap - * @param image source for image - * @param options An object that sets options for the image's extraction. - * @returns ImageBitmap - */ - createImageBitmap(image, options) { - return createImageBitmap(image, options); - } - /** - * Resize an image and returns the image data as an uint8array - * @param image image to resize - * @param bufferWidth destination buffer width - * @param bufferHeight destination buffer height - * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size - */ - resizeImageBitmap(image, bufferWidth, bufferHeight) { - const canvas = this.createCanvas(bufferWidth, bufferHeight); - const context = canvas.getContext("2d"); - if (!context) { - throw new Error("Unable to get 2d context for resizeImageBitmap"); - } - context.drawImage(image, 0, 0); - // Create VertexData from map data - // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949 - const buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data; - return buffer; - } - /** - * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation - * @param flag defines which part of the materials must be marked as dirty - * @param predicate defines a predicate used to filter which materials should be affected - */ - static MarkAllMaterialsAsDirty(flag, predicate) { - for (let engineIndex = 0; engineIndex < engine_Engine.Instances.length; engineIndex++) { - const engine = engine_Engine.Instances[engineIndex]; - for (let sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) { - engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate); - } - } - } - /** - * Method called to create the default loading screen. - * This can be overridden in your own app. - * @param canvas The rendering canvas element - * @returns The loading screen - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static DefaultLoadingScreenFactory(canvas) { - throw _WarnImport("LoadingScreen"); - } - get _supportsHardwareTextureRescaling() { - return !!engine_Engine._RescalePostProcessFactory; - } - /** - * Gets the performance monitor attached to this engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation - */ - get performanceMonitor() { - return this._performanceMonitor; - } - /** - * (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL). - * Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken. - * See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details - */ - get compatibilityMode() { - return this._compatibilityMode; - } - set compatibilityMode(mode) { - // not supported in WebGL - this._compatibilityMode = true; - } - // Events - /** - * Gets the HTML element used to attach event listeners - * @returns a HTML element - */ - getInputElement() { - return this._renderingCanvas; - } - /** - * Creates a new engine - * @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 - * @param antialias defines enable antialiasing (default: false) - * @param options defines further options to be sent to the getContext() function - * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false) - */ - constructor(canvasOrContext, antialias, options, adaptToDeviceRatio = false) { - super(canvasOrContext, antialias, options, adaptToDeviceRatio); - // Members - /** - * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest - **/ - this.enableOfflineSupport = false; - /** - * 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) - **/ - this.disableManifestCheck = false; - /** - * Gets or sets a boolean to enable/disable the context menu (right-click) from appearing on the main canvas - */ - this.disableContextMenu = true; - /** - * Gets the list of created scenes - */ - this.scenes = new Array(); - /** @internal */ - this._virtualScenes = new Array(); - /** - * Event raised when a new scene is created - */ - this.onNewSceneAddedObservable = new observable_Observable(); - /** - * Gets the list of created postprocesses - */ - this.postProcesses = new Array(); - /** - * Gets a boolean indicating if the pointer is currently locked - */ - this.isPointerLock = false; - // Observables - /** - * Observable event triggered each time the rendering canvas is resized - */ - this.onResizeObservable = new observable_Observable(); - /** - * Observable event triggered each time the canvas loses focus - */ - this.onCanvasBlurObservable = new observable_Observable(); - /** - * Observable event triggered each time the canvas gains focus - */ - this.onCanvasFocusObservable = new observable_Observable(); - /** - * Observable event triggered each time the canvas receives pointerout event - */ - this.onCanvasPointerOutObservable = new observable_Observable(); - /** - * Observable raised when the engine begins a new frame - */ - this.onBeginFrameObservable = new observable_Observable(); - /** - * If set, will be used to request the next animation frame for the render loop - */ - this.customAnimationFrameRequester = null; - /** - * Observable raised when the engine ends the current frame - */ - this.onEndFrameObservable = new observable_Observable(); - /** - * Observable raised when the engine is about to compile a shader - */ - this.onBeforeShaderCompilationObservable = new observable_Observable(); - /** - * Observable raised when the engine has just compiled a shader - */ - this.onAfterShaderCompilationObservable = new observable_Observable(); - // Deterministic lockstepMaxSteps - this._deterministicLockstep = false; - this._lockstepMaxSteps = 4; - this._timeStep = 1 / 60; - // FPS - this._fps = 60; - this._deltaTime = 0; - /** @internal */ - this._drawCalls = new perfCounter_PerfCounter(); - /** 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 */ - this.canvasTabIndex = 1; - /** - * Turn this value on if you want to pause FPS computation when in background - */ - this.disablePerformanceMonitorInBackground = false; - this._performanceMonitor = new PerformanceMonitor(); - this._compatibilityMode = true; - /** - * Gets or sets the current render pass id - */ - this.currentRenderPassId = 0; - this._renderPassNames = ["main"]; - engine_Engine.Instances.push(this); - if (!canvasOrContext) { - return; - } - this._features.supportRenderPasses = true; - options = this._creationOptions; - if (canvasOrContext.getContext) { - const canvas = canvasOrContext; - this._sharedInit(canvas); - this._connectVREvents(); - } - // Load WebVR Devices - this._prepareVRComponent(); - if (options.autoEnableWebVR) { - this.initWebVR(); - } - } - _initGLContext() { - super._initGLContext(); - this._rescalePostProcess = null; - } - /** - * Shared initialization across engines types. - * @param canvas The canvas associated with this instance of the engine. - */ - _sharedInit(canvas) { - super._sharedInit(canvas); - this._onCanvasFocus = () => { - this.onCanvasFocusObservable.notifyObservers(this); - }; - this._onCanvasBlur = () => { - this.onCanvasBlurObservable.notifyObservers(this); - }; - this._onCanvasContextMenu = (evt) => { - if (this.disableContextMenu) { - evt.preventDefault(); - } - }; - canvas.addEventListener("focus", this._onCanvasFocus); - canvas.addEventListener("blur", this._onCanvasBlur); - canvas.addEventListener("contextmenu", this._onCanvasContextMenu); - this._onBlur = () => { - if (this.disablePerformanceMonitorInBackground) { - this._performanceMonitor.disable(); - } - this._windowIsBackground = true; - }; - this._onFocus = () => { - if (this.disablePerformanceMonitorInBackground) { - this._performanceMonitor.enable(); - } - this._windowIsBackground = false; - }; - this._onCanvasPointerOut = (ev) => { - // Check that the element at the point of the pointer out isn't the canvas and if it isn't, notify observers - // Note: This is a workaround for a bug with Safari - if (document.elementFromPoint(ev.clientX, ev.clientY) !== canvas) { - this.onCanvasPointerOutObservable.notifyObservers(ev); - } - }; - const hostWindow = this.getHostWindow(); // it calls IsWindowObjectExist() - if (hostWindow && typeof hostWindow.addEventListener === "function") { - hostWindow.addEventListener("blur", this._onBlur); - hostWindow.addEventListener("focus", this._onFocus); - } - canvas.addEventListener("pointerout", this._onCanvasPointerOut); - if (!this._creationOptions.doNotHandleTouchAction) { - this._disableTouchAction(); - } - // Create Audio Engine if needed. - if (!engine_Engine.audioEngine && this._creationOptions.audioEngine && engine_Engine.AudioEngineFactory) { - engine_Engine.audioEngine = engine_Engine.AudioEngineFactory(this.getRenderingCanvas(), this.getAudioContext(), this.getAudioDestination()); - } - if (IsDocumentAvailable()) { - // Fullscreen - this._onFullscreenChange = () => { - this.isFullscreen = !!document.fullscreenElement; - // Pointer lock - if (this.isFullscreen && this._pointerLockRequested && canvas) { - engine_Engine._RequestPointerlock(canvas); - } - }; - document.addEventListener("fullscreenchange", this._onFullscreenChange, false); - document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false); - // Pointer lock - this._onPointerLockChange = () => { - this.isPointerLock = document.pointerLockElement === canvas; - }; - document.addEventListener("pointerlockchange", this._onPointerLockChange, false); - document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false); - } - this.enableOfflineSupport = engine_Engine.OfflineProviderFactory !== undefined; - this._deterministicLockstep = !!this._creationOptions.deterministicLockstep; - this._lockstepMaxSteps = this._creationOptions.lockstepMaxSteps || 0; - this._timeStep = this._creationOptions.timeStep || 1 / 60; - } - /** @internal */ - _verifyPointerLock() { - var _a; - (_a = this._onPointerLockChange) === null || _a === void 0 ? void 0 : _a.call(this); - } - /** - * Gets current aspect ratio - * @param viewportOwner defines the camera to use to get the aspect ratio - * @param useScreen defines if screen size must be used (or the current render target if any) - * @returns a number defining the aspect ratio - */ - getAspectRatio(viewportOwner, useScreen = false) { - const viewport = viewportOwner.viewport; - return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height); - } - /** - * Gets current screen aspect ratio - * @returns a number defining the aspect ratio - */ - getScreenAspectRatio() { - return this.getRenderWidth(true) / this.getRenderHeight(true); - } - /** - * Gets the client rect of the HTML canvas attached with the current webGL context - * @returns a client rectangle - */ - getRenderingCanvasClientRect() { - if (!this._renderingCanvas) { - return null; - } - return this._renderingCanvas.getBoundingClientRect(); - } - /** - * Gets the client rect of the HTML element used for events - * @returns a client rectangle - */ - getInputElementClientRect() { - if (!this._renderingCanvas) { - return null; - } - return this.getInputElement().getBoundingClientRect(); - } - /** - * Gets a boolean indicating that the engine is running in deterministic lock step mode - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - * @returns true if engine is in deterministic lock step mode - */ - isDeterministicLockStep() { - return this._deterministicLockstep; - } - /** - * Gets the max steps when engine is running in deterministic lock step - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - * @returns the max steps - */ - getLockstepMaxSteps() { - return this._lockstepMaxSteps; - } - /** - * Returns the time in ms between steps when using deterministic lock step. - * @returns time step in (ms) - */ - getTimeStep() { - return this._timeStep * 1000; - } - /** - * Force the mipmap generation for the given render target texture - * @param texture defines the render target texture to use - * @param unbind defines whether or not to unbind the texture after generation. Defaults to true. - */ - generateMipMapsForCubemap(texture, unbind = true) { - if (texture.generateMipMaps) { - const gl = this._gl; - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); - gl.generateMipmap(gl.TEXTURE_CUBE_MAP); - if (unbind) { - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); - } - } - } - /** States */ - /** - * Gets a boolean indicating if depth writing is enabled - * @returns the current depth writing state - */ - getDepthWrite() { - return this._depthCullingState.depthMask; - } - /** - * Enable or disable depth writing - * @param enable defines the state to set - */ - setDepthWrite(enable) { - this._depthCullingState.depthMask = enable; - } - /** - * Gets a boolean indicating if stencil buffer is enabled - * @returns the current stencil buffer state - */ - getStencilBuffer() { - return this._stencilState.stencilTest; - } - /** - * Enable or disable the stencil buffer - * @param enable defines if the stencil buffer must be enabled or disabled - */ - setStencilBuffer(enable) { - this._stencilState.stencilTest = enable; - } - /** - * Gets the current stencil mask - * @returns a number defining the new stencil mask to use - */ - getStencilMask() { - return this._stencilState.stencilMask; - } - /** - * Sets the current stencil mask - * @param mask defines the new stencil mask to use - */ - setStencilMask(mask) { - this._stencilState.stencilMask = mask; - } - /** - * Gets the current stencil function - * @returns a number defining the stencil function to use - */ - getStencilFunction() { - return this._stencilState.stencilFunc; - } - /** - * Gets the current stencil reference value - * @returns a number defining the stencil reference value to use - */ - getStencilFunctionReference() { - return this._stencilState.stencilFuncRef; - } - /** - * Gets the current stencil mask - * @returns a number defining the stencil mask to use - */ - getStencilFunctionMask() { - return this._stencilState.stencilFuncMask; - } - /** - * Sets the current stencil function - * @param stencilFunc defines the new stencil function to use - */ - setStencilFunction(stencilFunc) { - this._stencilState.stencilFunc = stencilFunc; - } - /** - * Sets the current stencil reference - * @param reference defines the new stencil reference to use - */ - setStencilFunctionReference(reference) { - this._stencilState.stencilFuncRef = reference; - } - /** - * Sets the current stencil mask - * @param mask defines the new stencil mask to use - */ - setStencilFunctionMask(mask) { - this._stencilState.stencilFuncMask = mask; - } - /** - * Gets the current stencil operation when stencil fails - * @returns a number defining stencil operation to use when stencil fails - */ - getStencilOperationFail() { - return this._stencilState.stencilOpStencilFail; - } - /** - * Gets the current stencil operation when depth fails - * @returns a number defining stencil operation to use when depth fails - */ - getStencilOperationDepthFail() { - return this._stencilState.stencilOpDepthFail; - } - /** - * Gets the current stencil operation when stencil passes - * @returns a number defining stencil operation to use when stencil passes - */ - getStencilOperationPass() { - return this._stencilState.stencilOpStencilDepthPass; - } - /** - * Sets the stencil operation to use when stencil fails - * @param operation defines the stencil operation to use when stencil fails - */ - setStencilOperationFail(operation) { - this._stencilState.stencilOpStencilFail = operation; - } - /** - * Sets the stencil operation to use when depth fails - * @param operation defines the stencil operation to use when depth fails - */ - setStencilOperationDepthFail(operation) { - this._stencilState.stencilOpDepthFail = operation; - } - /** - * Sets the stencil operation to use when stencil passes - * @param operation defines the stencil operation to use when stencil passes - */ - setStencilOperationPass(operation) { - this._stencilState.stencilOpStencilDepthPass = operation; - } - /** - * Sets a boolean indicating if the dithering state is enabled or disabled - * @param value defines the dithering state - */ - setDitheringState(value) { - if (value) { - this._gl.enable(this._gl.DITHER); - } - else { - this._gl.disable(this._gl.DITHER); - } - } - /** - * Sets a boolean indicating if the rasterizer state is enabled or disabled - * @param value defines the rasterizer state - */ - setRasterizerState(value) { - if (value) { - this._gl.disable(this._gl.RASTERIZER_DISCARD); - } - else { - this._gl.enable(this._gl.RASTERIZER_DISCARD); - } - } - /** - * Gets the current depth function - * @returns a number defining the depth function - */ - getDepthFunction() { - return this._depthCullingState.depthFunc; - } - /** - * Sets the current depth function - * @param depthFunc defines the function to use - */ - setDepthFunction(depthFunc) { - this._depthCullingState.depthFunc = depthFunc; - } - /** - * Sets the current depth function to GREATER - */ - setDepthFunctionToGreater() { - this.setDepthFunction(516); - } - /** - * Sets the current depth function to GEQUAL - */ - setDepthFunctionToGreaterOrEqual() { - this.setDepthFunction(518); - } - /** - * Sets the current depth function to LESS - */ - setDepthFunctionToLess() { - this.setDepthFunction(513); - } - /** - * Sets the current depth function to LEQUAL - */ - setDepthFunctionToLessOrEqual() { - this.setDepthFunction(515); - } - /** - * Caches the the state of the stencil buffer - */ - 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(); - } - /** - * Restores the state of the stencil buffer - */ - 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); - } - /** - * Directly set the WebGL Viewport - * @param x defines the x coordinate of the viewport (in screen space) - * @param y defines the y coordinate of the viewport (in screen space) - * @param width defines the width of the viewport (in screen space) - * @param height defines the height of the viewport (in screen space) - * @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 - */ - setDirectViewport(x, y, width, height) { - const currentViewport = this._cachedViewport; - this._cachedViewport = null; - this._viewport(x, y, width, height); - return currentViewport; - } - /** - * Executes a scissor clear (ie. a clear on a specific portion of the screen) - * @param x defines the x-coordinate of the bottom left corner of the clear rectangle - * @param y defines the y-coordinate of the corner of the clear rectangle - * @param width defines the width of the clear rectangle - * @param height defines the height of the clear rectangle - * @param clearColor defines the clear color - */ - scissorClear(x, y, width, height, clearColor) { - this.enableScissor(x, y, width, height); - this.clear(clearColor, true, true, true); - this.disableScissor(); - } - /** - * Enable scissor test on a specific rectangle (ie. render will only be executed on a specific portion of the screen) - * @param x defines the x-coordinate of the bottom left corner of the clear rectangle - * @param y defines the y-coordinate of the corner of the clear rectangle - * @param width defines the width of the clear rectangle - * @param height defines the height of the clear rectangle - */ - enableScissor(x, y, width, height) { - const gl = this._gl; - // Change state - gl.enable(gl.SCISSOR_TEST); - gl.scissor(x, y, width, height); - } - /** - * Disable previously set scissor test rectangle - */ - disableScissor() { - const gl = this._gl; - gl.disable(gl.SCISSOR_TEST); - } - /** - * @internal - */ - _reportDrawCall(numDrawCalls = 1) { - this._drawCalls.addCount(numDrawCalls, false); - } - /** - * Initializes a webVR display and starts listening to display change events - * The onVRDisplayChangedObservable will be notified upon these changes - * @returns The onVRDisplayChangedObservable - */ - initWebVR() { - throw _WarnImport("WebVRCamera"); - } - /** @internal */ - _prepareVRComponent() { - // Do nothing as the engine side effect will overload it - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _connectVREvents(canvas, document) { - // Do nothing as the engine side effect will overload it - } - /** @internal */ - _submitVRFrame() { - // Do nothing as the engine side effect will overload it - } - /** - * Call this function to leave webVR mode - * Will do nothing if webVR is not supported or if there is no webVR device - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRCamera - */ - disableVR() { - // Do nothing as the engine side effect will overload it - } - /** - * Gets a boolean indicating that the system is in VR mode and is presenting - * @returns true if VR mode is engaged - */ - isVRPresenting() { - return false; - } - /** @internal */ - _requestVRFrame() { - // Do nothing as the engine side effect will overload it - } - /** - * @internal - */ - _loadFileAsync(url, offlineProvider, useArrayBuffer) { - return new Promise((resolve, reject) => { - this._loadFile(url, (data) => { - resolve(data); - }, undefined, offlineProvider, useArrayBuffer, (request, exception) => { - reject(exception); - }); - }); - } - /** - * Gets the source code of the vertex shader associated with a specific webGL program - * @param program defines the program to use - * @returns a string containing the source code of the vertex shader associated with the program - */ - getVertexShaderSource(program) { - const shaders = this._gl.getAttachedShaders(program); - if (!shaders) { - return null; - } - return this._gl.getShaderSource(shaders[0]); - } - /** - * Gets the source code of the fragment shader associated with a specific webGL program - * @param program defines the program to use - * @returns a string containing the source code of the fragment shader associated with the program - */ - getFragmentShaderSource(program) { - const shaders = this._gl.getAttachedShaders(program); - if (!shaders) { - return null; - } - return this._gl.getShaderSource(shaders[1]); - } - /** - * Sets a depth stencil texture from a render target to the according uniform. - * @param channel The texture channel - * @param uniform The uniform to set - * @param texture The render target texture containing the depth stencil texture to apply - * @param name The texture name - */ - setDepthStencilTexture(channel, uniform, texture, name) { - if (channel === undefined) { - return; - } - if (uniform) { - this._boundUniforms[channel] = uniform; - } - if (!texture || !texture.depthStencilTexture) { - this._setTexture(channel, null, undefined, undefined, name); - } - else { - this._setTexture(channel, texture, false, true, name); - } - } - /** - * Sets a texture to the webGL context from a postprocess - * @param channel defines the channel to use - * @param postProcess defines the source postprocess - * @param name name of the channel - */ - setTextureFromPostProcess(channel, postProcess, name) { - var _a; - let postProcessInput = null; - if (postProcess) { - if (postProcess._forcedOutputTexture) { - postProcessInput = postProcess._forcedOutputTexture; - } - else if (postProcess._textures.data[postProcess._currentRenderTextureInd]) { - postProcessInput = postProcess._textures.data[postProcess._currentRenderTextureInd]; - } - } - this._bindTexture(channel, (_a = postProcessInput === null || postProcessInput === void 0 ? void 0 : postProcessInput.texture) !== null && _a !== void 0 ? _a : null, name); - } - /** - * Binds the output of the passed in post process to the texture channel specified - * @param channel The channel the texture should be bound to - * @param postProcess The post process which's output should be bound - * @param name name of the channel - */ - setTextureFromPostProcessOutput(channel, postProcess, name) { - var _a, _b; - 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); - } - _rebuildBuffers() { - // Index / Vertex - for (const scene of this.scenes) { - scene.resetCachedMaterial(); - scene._rebuildGeometries(); - scene._rebuildTextures(); - } - for (const scene of this._virtualScenes) { - scene.resetCachedMaterial(); - scene._rebuildGeometries(); - scene._rebuildTextures(); - } - super._rebuildBuffers(); - } - /** @internal */ - _renderFrame() { - for (let index = 0; index < this._activeRenderLoops.length; index++) { - const renderFunction = this._activeRenderLoops[index]; - renderFunction(); - } - } - _cancelFrame() { - if (this._renderingQueueLaunched && this.customAnimationFrameRequester) { - this._renderingQueueLaunched = false; - const { cancelAnimationFrame } = this.customAnimationFrameRequester; - if (cancelAnimationFrame) { - cancelAnimationFrame(this.customAnimationFrameRequester.requestID); - } - } - else { - super._cancelFrame(); - } - } - _renderLoop() { - if (!this._contextWasLost) { - let shouldRender = true; - if (this.isDisposed || (!this.renderEvenInBackground && this._windowIsBackground)) { - shouldRender = false; - } - if (shouldRender) { - // Start new frame - this.beginFrame(); - // Child canvases - if (!this._renderViews()) { - // Main frame - this._renderFrame(); - } - // Present - this.endFrame(); - } - } - if (this._activeRenderLoops.length > 0) { - // Register new frame - if (this.customAnimationFrameRequester) { - this.customAnimationFrameRequester.requestID = this._queueNewFrame(this.customAnimationFrameRequester.renderFunction || this._boundRenderFunction, this.customAnimationFrameRequester); - this._frameHandler = this.customAnimationFrameRequester.requestID; - } - else if (this.isVRPresenting()) { - this._requestVRFrame(); - } - else { - this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()); - } - } - else { - this._renderingQueueLaunched = false; - } - } - /** @internal */ - _renderViews() { - return false; - } - /** - * Toggle full screen mode - * @param requestPointerLock defines if a pointer lock should be requested from the user - */ - switchFullscreen(requestPointerLock) { - if (this.isFullscreen) { - this.exitFullscreen(); - } - else { - this.enterFullscreen(requestPointerLock); - } - } - /** - * Enters full screen mode - * @param requestPointerLock defines if a pointer lock should be requested from the user - */ - enterFullscreen(requestPointerLock) { - if (!this.isFullscreen) { - this._pointerLockRequested = requestPointerLock; - if (this._renderingCanvas) { - engine_Engine._RequestFullscreen(this._renderingCanvas); - } - } - } - /** - * Exits full screen mode - */ - exitFullscreen() { - if (this.isFullscreen) { - engine_Engine._ExitFullscreen(); - } - } - /** - * Enters Pointerlock mode - */ - enterPointerlock() { - if (this._renderingCanvas) { - engine_Engine._RequestPointerlock(this._renderingCanvas); - } - } - /** - * Exits Pointerlock mode - */ - exitPointerlock() { - engine_Engine._ExitPointerlock(); - } - /** - * Begin a new frame - */ - beginFrame() { - this._measureFps(); - this.onBeginFrameObservable.notifyObservers(this); - super.beginFrame(); - } - /** - * End the current frame - */ - endFrame() { - super.endFrame(); - this._submitVRFrame(); - this.onEndFrameObservable.notifyObservers(this); - } - /** - * Resize the view according to the canvas' size - * @param forceSetSize true to force setting the sizes of the underlying canvas - */ - resize(forceSetSize = false) { - // We're not resizing the size of the canvas while in VR mode & presenting - if (this.isVRPresenting()) { - return; - } - super.resize(forceSetSize); - } - /** - * Force a specific size of the canvas - * @param width defines the new canvas' width - * @param height defines the new canvas' height - * @param forceSetSize true to force setting the sizes of the underlying canvas - * @returns true if the size was changed - */ - setSize(width, height, forceSetSize = false) { - if (!this._renderingCanvas) { - return false; - } - if (!super.setSize(width, height, forceSetSize)) { - return false; - } - if (this.scenes) { - for (let index = 0; index < this.scenes.length; index++) { - const scene = this.scenes[index]; - for (let camIndex = 0; camIndex < scene.cameras.length; camIndex++) { - const cam = scene.cameras[camIndex]; - cam._currentRenderId = 0; - } - } - if (this.onResizeObservable.hasObservers()) { - this.onResizeObservable.notifyObservers(this); - } - } - return true; - } - _deletePipelineContext(pipelineContext) { - const webGLPipelineContext = pipelineContext; - if (webGLPipelineContext && webGLPipelineContext.program) { - if (webGLPipelineContext.transformFeedback) { - this.deleteTransformFeedback(webGLPipelineContext.transformFeedback); - webGLPipelineContext.transformFeedback = null; - } - } - super._deletePipelineContext(pipelineContext); - } - createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) { - context = context || this._gl; - this.onBeforeShaderCompilationObservable.notifyObservers(this); - const program = super.createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings); - this.onAfterShaderCompilationObservable.notifyObservers(this); - return program; - } - _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings = null) { - const shaderProgram = context.createProgram(); - pipelineContext.program = shaderProgram; - if (!shaderProgram) { - throw new Error("Unable to create program"); - } - context.attachShader(shaderProgram, vertexShader); - context.attachShader(shaderProgram, fragmentShader); - if (this.webGLVersion > 1 && transformFeedbackVaryings) { - const transformFeedback = this.createTransformFeedback(); - this.bindTransformFeedback(transformFeedback); - this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings); - pipelineContext.transformFeedback = transformFeedback; - } - context.linkProgram(shaderProgram); - if (this.webGLVersion > 1 && transformFeedbackVaryings) { - this.bindTransformFeedback(null); - } - pipelineContext.context = context; - pipelineContext.vertexShader = vertexShader; - pipelineContext.fragmentShader = fragmentShader; - if (!pipelineContext.isParallelCompiled) { - this._finalizePipelineContext(pipelineContext); - } - return shaderProgram; - } - /** - * @internal - */ - _releaseTexture(texture) { - super._releaseTexture(texture); - } - /** - * @internal - */ - _releaseRenderTargetWrapper(rtWrapper) { - super._releaseRenderTargetWrapper(rtWrapper); - // Set output texture of post process to null if the framebuffer has been released/disposed - this.scenes.forEach((scene) => { - scene.postProcesses.forEach((postProcess) => { - if (postProcess._outputTexture === rtWrapper) { - postProcess._outputTexture = null; - } - }); - scene.cameras.forEach((camera) => { - camera._postProcesses.forEach((postProcess) => { - if (postProcess) { - if (postProcess._outputTexture === rtWrapper) { - postProcess._outputTexture = null; - } - } - }); - }); - }); - } - /** - * Gets the names of the render passes that are currently created - * @returns list of the render pass names - */ - getRenderPassNames() { - return this._renderPassNames; - } - /** - * Gets the name of the current render pass - * @returns name of the current render pass - */ - getCurrentRenderPassName() { - return this._renderPassNames[this.currentRenderPassId]; - } - /** - * Creates a render pass id - * @param name Name of the render pass (for debug purpose only) - * @returns the id of the new render pass - */ - createRenderPassId(name) { - // Note: render pass id == 0 is always for the main render pass - const id = ++engine_Engine._RenderPassIdCounter; - this._renderPassNames[id] = name !== null && name !== void 0 ? name : "NONAME"; - return id; - } - /** - * Releases a render pass id - * @param id id of the render pass to release - */ - releaseRenderPassId(id) { - this._renderPassNames[id] = undefined; - for (let s = 0; s < this.scenes.length; ++s) { - const scene = this.scenes[s]; - for (let m = 0; m < scene.meshes.length; ++m) { - const mesh = scene.meshes[m]; - if (mesh.subMeshes) { - for (let b = 0; b < mesh.subMeshes.length; ++b) { - const subMesh = mesh.subMeshes[b]; - subMesh._removeDrawWrapper(id); - } - } - } - } - } - /** - * @internal - * Rescales a texture - * @param source input texture - * @param destination destination texture - * @param scene scene to use to render the resize - * @param internalFormat format to use when resizing - * @param onComplete callback to be called when resize has completed - */ - _rescaleTexture(source, destination, scene, internalFormat, onComplete) { - this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR); - this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR); - this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE); - this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE); - const rtt = this.createRenderTargetTexture({ - width: destination.width, - height: destination.height, - }, { - generateMipMaps: false, - type: 0, - samplingMode: 2, - generateDepthBuffer: false, - generateStencilBuffer: false, - }); - if (!this._rescalePostProcess && engine_Engine._RescalePostProcessFactory) { - this._rescalePostProcess = engine_Engine._RescalePostProcessFactory(this); - } - if (this._rescalePostProcess) { - this._rescalePostProcess.externalTextureSamplerBinding = true; - this._rescalePostProcess.getEffect().executeWhenCompiled(() => { - this._rescalePostProcess.onApply = function (effect) { - effect._bindTexture("textureSampler", source); - }; - let hostingScene = scene; - if (!hostingScene) { - hostingScene = this.scenes[this.scenes.length - 1]; - } - hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true); - this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true); - this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0); - this.unBindFramebuffer(rtt); - rtt.dispose(); - if (onComplete) { - onComplete(); - } - }); - } - } - // FPS - /** - * Gets the current framerate - * @returns a number representing the framerate - */ - getFps() { - return this._fps; - } - /** - * Gets the time spent between current and previous frame - * @returns a number representing the delta time in ms - */ - getDeltaTime() { - return this._deltaTime; - } - _measureFps() { - this._performanceMonitor.sampleFrame(); - this._fps = this._performanceMonitor.averageFPS; - this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0; - } - /** - * Wraps an external web gl texture in a Babylon texture. - * @param texture defines the external texture - * @param hasMipMaps defines whether the external texture has mip maps (default: false) - * @param samplingMode defines the sampling mode for the external texture (default: 3) - * @returns the babylon internal texture - */ - wrapWebGLTexture(texture, hasMipMaps = false, samplingMode = 3) { - const hardwareTexture = new WebGLHardwareTexture(texture, this._gl); - const internalTexture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Unknown, true); - internalTexture._hardwareTexture = hardwareTexture; - internalTexture.isReady = true; - internalTexture.useMipMaps = hasMipMaps; - this.updateTextureSamplingMode(samplingMode, internalTexture); - return internalTexture; - } - /** - * @internal - */ - _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) { - const gl = this._gl; - const textureType = this._getWebGLTextureType(texture.type); - const format = this._getInternalFormat(texture.format); - const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format); - const bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; - this._bindTextureDirectly(bindTarget, texture, true); - this._unpackFlipY(texture.invertY); - let target = gl.TEXTURE_2D; - if (texture.isCube) { - target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; - } - gl.texImage2D(target, lod, internalFormat, format, textureType, image); - this._bindTextureDirectly(bindTarget, null, true); - } - /** - * Updates a depth texture Comparison Mode and Function. - * If the comparison Function is equal to 0, the mode will be set to none. - * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader. - * @param texture The texture to set the comparison function for - * @param comparisonFunction The comparison function to set, 0 if no comparison required - */ - updateTextureComparisonFunction(texture, comparisonFunction) { - if (this.webGLVersion === 1) { - logger_Logger.Error("WebGL 1 does not support texture comparison."); - return; - } - const gl = this._gl; - if (texture.isCube) { - this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true); - if (comparisonFunction === 0) { - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, 515); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE); - } - else { - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE); - } - this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); - } - else { - this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); - if (comparisonFunction === 0) { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, 515); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE); - } - else { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE); - } - this._bindTextureDirectly(this._gl.TEXTURE_2D, null); - } - texture._comparisonFunction = comparisonFunction; - } - /** - * Creates a webGL buffer to use with instantiation - * @param capacity defines the size of the buffer - * @returns the webGL buffer - */ - createInstancesBuffer(capacity) { - const buffer = this._gl.createBuffer(); - if (!buffer) { - throw new Error("Unable to create instance buffer"); - } - const result = new WebGLDataBuffer(buffer); - result.capacity = capacity; - this.bindArrayBuffer(result); - this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW); - result.references = 1; - return result; - } - /** - * Delete a webGL buffer used with instantiation - * @param buffer defines the webGL buffer to delete - */ - deleteInstancesBuffer(buffer) { - this._gl.deleteBuffer(buffer); - } - _clientWaitAsync(sync, flags = 0, intervalms = 10) { - const gl = this._gl; - return new Promise((resolve, reject) => { - const check = () => { - const res = gl.clientWaitSync(sync, flags, 0); - if (res == gl.WAIT_FAILED) { - reject(); - return; - } - if (res == gl.TIMEOUT_EXPIRED) { - setTimeout(check, intervalms); - return; - } - resolve(); - }; - check(); - }); - } - /** - * @internal - */ - _readPixelsAsync(x, y, w, h, format, type, outputBuffer) { - if (this._webGLVersion < 2) { - throw new Error("_readPixelsAsync only work on WebGL2+"); - } - const gl = this._gl; - const buf = gl.createBuffer(); - gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf); - gl.bufferData(gl.PIXEL_PACK_BUFFER, outputBuffer.byteLength, gl.STREAM_READ); - gl.readPixels(x, y, w, h, format, type, 0); - gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null); - const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0); - if (!sync) { - return null; - } - gl.flush(); - return this._clientWaitAsync(sync, 0, 10).then(() => { - gl.deleteSync(sync); - gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf); - gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, outputBuffer); - gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null); - gl.deleteBuffer(buf); - return outputBuffer; - }); - } - dispose() { - this.hideLoadingUI(); - this.onNewSceneAddedObservable.clear(); - // Release postProcesses - while (this.postProcesses.length) { - this.postProcesses[0].dispose(); - } - // Rescale PP - if (this._rescalePostProcess) { - this._rescalePostProcess.dispose(); - } - // Release scenes - while (this.scenes.length) { - this.scenes[0].dispose(); - } - while (this._virtualScenes.length) { - this._virtualScenes[0].dispose(); - } - // Release audio engine - if (engineStore_EngineStore.Instances.length === 1 && engine_Engine.audioEngine) { - engine_Engine.audioEngine.dispose(); - engine_Engine.audioEngine = null; - } - //WebVR - this.disableVR(); - // Events - const hostWindow = this.getHostWindow(); // it calls IsWindowObjectExist() - if (hostWindow && typeof hostWindow.removeEventListener === "function") { - hostWindow.removeEventListener("blur", this._onBlur); - hostWindow.removeEventListener("focus", this._onFocus); - } - if (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); - } - if (IsDocumentAvailable()) { - 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(); - // Remove from Instances - const index = engineStore_EngineStore.Instances.indexOf(this); - if (index >= 0) { - engineStore_EngineStore.Instances.splice(index, 1); - } - // no more engines left in the engine store? Notify! - if (!engine_Engine.Instances.length) { - engineStore_EngineStore.OnEnginesDisposedObservable.notifyObservers(this); - } - // Observables - this.onResizeObservable.clear(); - this.onCanvasBlurObservable.clear(); - this.onCanvasFocusObservable.clear(); - this.onCanvasPointerOutObservable.clear(); - this.onBeginFrameObservable.clear(); - this.onEndFrameObservable.clear(); - } - _disableTouchAction() { - if (!this._renderingCanvas || !this._renderingCanvas.setAttribute) { - return; - } - this._renderingCanvas.setAttribute("touch-action", "none"); - this._renderingCanvas.style.touchAction = "none"; - this._renderingCanvas.style.webkitTapHighlightColor = "transparent"; - } - // Loading screen - /** - * Display the loading screen - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen - */ - displayLoadingUI() { - if (!IsWindowObjectExist()) { - return; - } - const loadingScreen = this.loadingScreen; - if (loadingScreen) { - loadingScreen.displayLoadingUI(); - } - } - /** - * Hide the loading screen - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen - */ - hideLoadingUI() { - if (!IsWindowObjectExist()) { - return; - } - const loadingScreen = this._loadingScreen; - if (loadingScreen) { - loadingScreen.hideLoadingUI(); - } - } - /** - * Gets the current loading screen object - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen - */ - get loadingScreen() { - if (!this._loadingScreen && this._renderingCanvas) { - this._loadingScreen = engine_Engine.DefaultLoadingScreenFactory(this._renderingCanvas); - } - return this._loadingScreen; - } - /** - * Sets the current loading screen object - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen - */ - set loadingScreen(loadingScreen) { - this._loadingScreen = loadingScreen; - } - /** - * Sets the current loading screen text - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen - */ - set loadingUIText(text) { - this.loadingScreen.loadingUIText = text; - } - /** - * Sets the current loading screen background color - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen - */ - set loadingUIBackgroundColor(color) { - this.loadingScreen.loadingUIBackgroundColor = color; - } - /** - * creates and returns a new video element - * @param constraints video constraints - * @returns video element - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - createVideoElement(constraints) { - return document.createElement("video"); - } - /** Pointerlock and fullscreen */ - /** - * Ask the browser to promote the current element to pointerlock mode - * @param element defines the DOM element to promote - */ - static _RequestPointerlock(element) { - if (element.requestPointerLock) { - // In some browsers, requestPointerLock returns a promise. - // Handle possible rejections to avoid an unhandled top-level exception. - const promise = element.requestPointerLock(); - if (promise instanceof Promise) - promise - .then(() => { - element.focus(); - }) - .catch(() => { }); - else - element.focus(); - } - } - /** - * Asks the browser to exit pointerlock mode - */ - static _ExitPointerlock() { - if (document.exitPointerLock) { - document.exitPointerLock(); - } - } - /** - * Ask the browser to promote the current element to fullscreen rendering mode - * @param element defines the DOM element to promote - */ - static _RequestFullscreen(element) { - const requestFunction = element.requestFullscreen || element.webkitRequestFullscreen; - if (!requestFunction) { - return; - } - requestFunction.call(element); - } - /** - * Asks the browser to exit fullscreen mode - */ - static _ExitFullscreen() { - const anyDoc = document; - if (document.exitFullscreen) { - document.exitFullscreen(); - } - else if (anyDoc.webkitCancelFullScreen) { - anyDoc.webkitCancelFullScreen(); - } - } - /** - * Get Font size information - * @param font font name - * @returns an object containing ascent, height and descent - */ - getFontOffset(font) { - const text = document.createElement("span"); - text.innerHTML = "Hg"; - text.setAttribute("style", `font: ${font} !important`); - const block = document.createElement("div"); - block.style.display = "inline-block"; - block.style.width = "1px"; - block.style.height = "0px"; - block.style.verticalAlign = "bottom"; - const div = document.createElement("div"); - div.style.whiteSpace = "nowrap"; - div.appendChild(text); - div.appendChild(block); - document.body.appendChild(div); - let fontAscent = 0; - let fontHeight = 0; - try { - fontHeight = block.getBoundingClientRect().top - text.getBoundingClientRect().top; - block.style.verticalAlign = "baseline"; - fontAscent = block.getBoundingClientRect().top - text.getBoundingClientRect().top; - } - finally { - document.body.removeChild(div); - } - return { ascent: fontAscent, height: fontHeight, descent: fontHeight - fontAscent }; - } -} -// Const statics -/** Defines that alpha blending is disabled */ -engine_Engine.ALPHA_DISABLE = 0; -/** Defines that alpha blending to SRC ALPHA * SRC + DEST */ -engine_Engine.ALPHA_ADD = 1; -/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */ -engine_Engine.ALPHA_COMBINE = 2; -/** Defines that alpha blending to DEST - SRC * DEST */ -engine_Engine.ALPHA_SUBTRACT = 3; -/** Defines that alpha blending to SRC * DEST */ -engine_Engine.ALPHA_MULTIPLY = 4; -/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */ -engine_Engine.ALPHA_MAXIMIZED = 5; -/** Defines that alpha blending to SRC + DEST */ -engine_Engine.ALPHA_ONEONE = 6; -/** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */ -engine_Engine.ALPHA_PREMULTIPLIED = 7; -/** - * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST - * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA - */ -engine_Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8; -/** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */ -engine_Engine.ALPHA_INTERPOLATE = 9; -/** - * Defines that alpha blending to SRC + (1 - SRC) * DEST - * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA - */ -engine_Engine.ALPHA_SCREENMODE = 10; -/** Defines that the resource is not delayed*/ -engine_Engine.DELAYLOADSTATE_NONE = 0; -/** Defines that the resource was successfully delay loaded */ -engine_Engine.DELAYLOADSTATE_LOADED = 1; -/** Defines that the resource is currently delay loading */ -engine_Engine.DELAYLOADSTATE_LOADING = 2; -/** Defines that the resource is delayed and has not started loading */ -engine_Engine.DELAYLOADSTATE_NOTLOADED = 4; -// Depht or Stencil test Constants. -/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */ -engine_Engine.NEVER = 512; -/** 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 */ -engine_Engine.ALWAYS = 519; -/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */ -engine_Engine.LESS = 513; -/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */ -engine_Engine.EQUAL = 514; -/** 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 */ -engine_Engine.LEQUAL = 515; -/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */ -engine_Engine.GREATER = 516; -/** 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 */ -engine_Engine.GEQUAL = 518; -/** 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 */ -engine_Engine.NOTEQUAL = 517; -// Stencil Actions Constants. -/** Passed to stencilOperation to specify that stencil value must be kept */ -engine_Engine.KEEP = 7680; -/** Passed to stencilOperation to specify that stencil value must be replaced */ -engine_Engine.REPLACE = 7681; -/** Passed to stencilOperation to specify that stencil value must be incremented */ -engine_Engine.INCR = 7682; -/** Passed to stencilOperation to specify that stencil value must be decremented */ -engine_Engine.DECR = 7683; -/** Passed to stencilOperation to specify that stencil value must be inverted */ -engine_Engine.INVERT = 5386; -/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */ -engine_Engine.INCR_WRAP = 34055; -/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */ -engine_Engine.DECR_WRAP = 34056; -/** Texture is not repeating outside of 0..1 UVs */ -engine_Engine.TEXTURE_CLAMP_ADDRESSMODE = 0; -/** Texture is repeating outside of 0..1 UVs */ -engine_Engine.TEXTURE_WRAP_ADDRESSMODE = 1; -/** Texture is repeating and mirrored */ -engine_Engine.TEXTURE_MIRROR_ADDRESSMODE = 2; -/** ALPHA */ -engine_Engine.TEXTUREFORMAT_ALPHA = 0; -/** LUMINANCE */ -engine_Engine.TEXTUREFORMAT_LUMINANCE = 1; -/** LUMINANCE_ALPHA */ -engine_Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2; -/** RGB */ -engine_Engine.TEXTUREFORMAT_RGB = 4; -/** RGBA */ -engine_Engine.TEXTUREFORMAT_RGBA = 5; -/** RED */ -engine_Engine.TEXTUREFORMAT_RED = 6; -/** RED (2nd reference) */ -engine_Engine.TEXTUREFORMAT_R = 6; -/** RG */ -engine_Engine.TEXTUREFORMAT_RG = 7; -/** RED_INTEGER */ -engine_Engine.TEXTUREFORMAT_RED_INTEGER = 8; -/** RED_INTEGER (2nd reference) */ -engine_Engine.TEXTUREFORMAT_R_INTEGER = 8; -/** RG_INTEGER */ -engine_Engine.TEXTUREFORMAT_RG_INTEGER = 9; -/** RGB_INTEGER */ -engine_Engine.TEXTUREFORMAT_RGB_INTEGER = 10; -/** RGBA_INTEGER */ -engine_Engine.TEXTUREFORMAT_RGBA_INTEGER = 11; -/** UNSIGNED_BYTE */ -engine_Engine.TEXTURETYPE_UNSIGNED_BYTE = 0; -/** UNSIGNED_BYTE (2nd reference) */ -engine_Engine.TEXTURETYPE_UNSIGNED_INT = 0; -/** FLOAT */ -engine_Engine.TEXTURETYPE_FLOAT = 1; -/** HALF_FLOAT */ -engine_Engine.TEXTURETYPE_HALF_FLOAT = 2; -/** BYTE */ -engine_Engine.TEXTURETYPE_BYTE = 3; -/** SHORT */ -engine_Engine.TEXTURETYPE_SHORT = 4; -/** UNSIGNED_SHORT */ -engine_Engine.TEXTURETYPE_UNSIGNED_SHORT = 5; -/** INT */ -engine_Engine.TEXTURETYPE_INT = 6; -/** UNSIGNED_INT */ -engine_Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7; -/** UNSIGNED_SHORT_4_4_4_4 */ -engine_Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8; -/** UNSIGNED_SHORT_5_5_5_1 */ -engine_Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9; -/** UNSIGNED_SHORT_5_6_5 */ -engine_Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10; -/** UNSIGNED_INT_2_10_10_10_REV */ -engine_Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11; -/** UNSIGNED_INT_24_8 */ -engine_Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12; -/** UNSIGNED_INT_10F_11F_11F_REV */ -engine_Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13; -/** UNSIGNED_INT_5_9_9_9_REV */ -engine_Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14; -/** FLOAT_32_UNSIGNED_INT_24_8_REV */ -engine_Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15; -/** nearest is mag = nearest and min = nearest and mip = none */ -engine_Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1; -/** Bilinear is mag = linear and min = linear and mip = nearest */ -engine_Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2; -/** Trilinear is mag = linear and min = linear and mip = linear */ -engine_Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3; -/** nearest is mag = nearest and min = nearest and mip = linear */ -engine_Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8; -/** Bilinear is mag = linear and min = linear and mip = nearest */ -engine_Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11; -/** Trilinear is mag = linear and min = linear and mip = linear */ -engine_Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3; -/** mag = nearest and min = nearest and mip = nearest */ -engine_Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4; -/** mag = nearest and min = linear and mip = nearest */ -engine_Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5; -/** mag = nearest and min = linear and mip = linear */ -engine_Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6; -/** mag = nearest and min = linear and mip = none */ -engine_Engine.TEXTURE_NEAREST_LINEAR = 7; -/** mag = nearest and min = nearest and mip = none */ -engine_Engine.TEXTURE_NEAREST_NEAREST = 1; -/** mag = linear and min = nearest and mip = nearest */ -engine_Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9; -/** mag = linear and min = nearest and mip = linear */ -engine_Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10; -/** mag = linear and min = linear and mip = none */ -engine_Engine.TEXTURE_LINEAR_LINEAR = 2; -/** mag = linear and min = nearest and mip = none */ -engine_Engine.TEXTURE_LINEAR_NEAREST = 12; -/** Explicit coordinates mode */ -engine_Engine.TEXTURE_EXPLICIT_MODE = 0; -/** Spherical coordinates mode */ -engine_Engine.TEXTURE_SPHERICAL_MODE = 1; -/** Planar coordinates mode */ -engine_Engine.TEXTURE_PLANAR_MODE = 2; -/** Cubic coordinates mode */ -engine_Engine.TEXTURE_CUBIC_MODE = 3; -/** Projection coordinates mode */ -engine_Engine.TEXTURE_PROJECTION_MODE = 4; -/** Skybox coordinates mode */ -engine_Engine.TEXTURE_SKYBOX_MODE = 5; -/** Inverse Cubic coordinates mode */ -engine_Engine.TEXTURE_INVCUBIC_MODE = 6; -/** Equirectangular coordinates mode */ -engine_Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7; -/** Equirectangular Fixed coordinates mode */ -engine_Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8; -/** Equirectangular Fixed Mirrored coordinates mode */ -engine_Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; -// Texture rescaling mode -/** Defines that texture rescaling will use a floor to find the closer power of 2 size */ -engine_Engine.SCALEMODE_FLOOR = 1; -/** Defines that texture rescaling will look for the nearest power of 2 size */ -engine_Engine.SCALEMODE_NEAREST = 2; -/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */ -engine_Engine.SCALEMODE_CEILING = 3; -/** - * Method called to create the default rescale post process on each engine. - */ -engine_Engine._RescalePostProcessFactory = null; -// eslint-disable-next-line @typescript-eslint/naming-convention -engine_Engine._RenderPassIdCounter = 0; -//# sourceMappingURL=engine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/transformNode.js - - - - - - -const convertRHSToLHS = math_vector_Matrix.Compose(math_vector_Vector3.One(), math_vector_Quaternion.FromEulerAngles(0, Math.PI, 0), math_vector_Vector3.Zero()); -/** - * 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. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node - */ -class transformNode_TransformNode extends node_Node { - /** - * Gets or sets the billboard mode. Default is 0. - * - * | Value | Type | Description | - * | --- | --- | --- | - * | 0 | BILLBOARDMODE_NONE | | - * | 1 | BILLBOARDMODE_X | | - * | 2 | BILLBOARDMODE_Y | | - * | 4 | BILLBOARDMODE_Z | | - * | 7 | BILLBOARDMODE_ALL | | - * - */ - get billboardMode() { - return this._billboardMode; - } - set billboardMode(value) { - if (this._billboardMode === value) { - return; - } - this._billboardMode = value; - this._cache.useBillboardPosition = (this._billboardMode & transformNode_TransformNode.BILLBOARDMODE_USE_POSITION) !== 0; - this._computeUseBillboardPath(); - } - /** - * Gets or sets a boolean indicating that parent rotation should be preserved when using billboards. - * This could be useful for glTF objects where parent rotation helps converting from right handed to left handed - */ - get preserveParentRotationForBillboard() { - return this._preserveParentRotationForBillboard; - } - set preserveParentRotationForBillboard(value) { - if (value === this._preserveParentRotationForBillboard) { - return; - } - this._preserveParentRotationForBillboard = value; - this._computeUseBillboardPath(); - } - _computeUseBillboardPath() { - this._cache.useBillboardPath = this._billboardMode !== transformNode_TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard; - } - /** - * Gets or sets the distance of the object to max, often used by skybox - */ - get infiniteDistance() { - return this._infiniteDistance; - } - set infiniteDistance(value) { - if (this._infiniteDistance === value) { - return; - } - this._infiniteDistance = value; - } - constructor(name, scene = null, isPure = true) { - super(name, scene); - this._forward = new math_vector_Vector3(0, 0, 1); - this._up = new math_vector_Vector3(0, 1, 0); - this._right = new math_vector_Vector3(1, 0, 0); - // Properties - this._position = math_vector_Vector3.Zero(); - this._rotation = math_vector_Vector3.Zero(); - this._rotationQuaternion = null; - this._scaling = math_vector_Vector3.One(); - this._transformToBoneReferal = null; - this._isAbsoluteSynced = false; - this._billboardMode = transformNode_TransformNode.BILLBOARDMODE_NONE; - this._preserveParentRotationForBillboard = false; - /** - * 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 - */ - this.scalingDeterminant = 1; - this._infiniteDistance = false; - /** - * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored. - * By default the system will update normals to compensate - */ - this.ignoreNonUniformScaling = false; - /** - * 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 - */ - this.reIntegrateRotationIntoRotationQuaternion = false; - // Cache - /** @internal */ - this._poseMatrix = null; - /** @internal */ - this._localMatrix = math_vector_Matrix.Zero(); - this._usePivotMatrix = false; - this._absolutePosition = math_vector_Vector3.Zero(); - this._absoluteScaling = math_vector_Vector3.Zero(); - this._absoluteRotationQuaternion = math_vector_Quaternion.Identity(); - this._pivotMatrix = math_vector_Matrix.Identity(); - /** @internal */ - this._postMultiplyPivotMatrix = false; - this._isWorldMatrixFrozen = false; - /** @internal */ - this._indexInSceneTransformNodesArray = -1; - /** - * An event triggered after the world matrix is updated - */ - this.onAfterWorldMatrixUpdateObservable = new observable_Observable(); - this._nonUniformScaling = false; - if (isPure) { - this.getScene().addTransformNode(this); - } - } - /** - * Gets a string identifying the name of the class - * @returns "TransformNode" string - */ - getClassName() { - return "TransformNode"; - } - /** - * Gets or set the node position (default is (0.0, 0.0, 0.0)) - */ - get position() { - return this._position; - } - set position(newPosition) { - this._position = newPosition; - this._isDirty = true; - } - /** - * return true if a pivot has been set - * @returns true if a pivot matrix is used - */ - isUsingPivotMatrix() { - return this._usePivotMatrix; - } - /** - * 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)). - * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion - */ - get rotation() { - return this._rotation; - } - set rotation(newRotation) { - this._rotation = newRotation; - this._rotationQuaternion = null; - this._isDirty = true; - } - /** - * 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)). - */ - get scaling() { - return this._scaling; - } - set scaling(newScaling) { - this._scaling = newScaling; - this._isDirty = true; - } - /** - * 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). - * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored) - */ - get rotationQuaternion() { - return this._rotationQuaternion; - } - set rotationQuaternion(quaternion) { - this._rotationQuaternion = quaternion; - //reset the rotation vector. - if (quaternion) { - this._rotation.setAll(0.0); - } - this._isDirty = true; - } - /** - * The forward direction of that transform in world space. - */ - get forward() { - math_vector_Vector3.TransformNormalFromFloatsToRef(0, 0, this.getScene().useRightHandedSystem ? -1.0 : 1.0, this.getWorldMatrix(), this._forward); - return this._forward.normalize(); - } - /** - * The up direction of that transform in world space. - */ - get up() { - math_vector_Vector3.TransformNormalFromFloatsToRef(0, 1, 0, this.getWorldMatrix(), this._up); - return this._up.normalize(); - } - /** - * The right direction of that transform in world space. - */ - get right() { - math_vector_Vector3.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem ? -1.0 : 1.0, 0, 0, this.getWorldMatrix(), this._right); - return this._right.normalize(); - } - /** - * Copies the parameter passed Matrix into the mesh Pose matrix. - * @param matrix the matrix to copy the pose from - * @returns this TransformNode. - */ - updatePoseMatrix(matrix) { - if (!this._poseMatrix) { - this._poseMatrix = matrix.clone(); - return this; - } - this._poseMatrix.copyFrom(matrix); - return this; - } - /** - * Returns the mesh Pose matrix. - * @returns the pose matrix - */ - getPoseMatrix() { - if (!this._poseMatrix) { - this._poseMatrix = math_vector_Matrix.Identity(); - } - return this._poseMatrix; - } - /** @internal */ - _isSynchronized() { - const cache = this._cache; - if (this._billboardMode !== cache.billboardMode || this._billboardMode !== transformNode_TransformNode.BILLBOARDMODE_NONE) { - return false; - } - if (cache.pivotMatrixUpdated) { - return false; - } - if (this._infiniteDistance) { - return false; - } - if (this._position._isDirty) { - return false; - } - if (this._scaling._isDirty) { - return false; - } - if ((this._rotationQuaternion && this._rotationQuaternion._isDirty) || this._rotation._isDirty) { - return false; - } - return true; - } - /** @internal */ - _initCache() { - super._initCache(); - const cache = this._cache; - cache.localMatrixUpdated = false; - cache.billboardMode = -1; - cache.infiniteDistance = false; - cache.useBillboardPosition = false; - cache.useBillboardPath = false; - } - /** - * Returns the current mesh absolute position. - * Returns a Vector3. - */ - get absolutePosition() { - return this.getAbsolutePosition(); - } - /** - * Returns the current mesh absolute scaling. - * Returns a Vector3. - */ - get absoluteScaling() { - this._syncAbsoluteScalingAndRotation(); - return this._absoluteScaling; - } - /** - * Returns the current mesh absolute rotation. - * Returns a Quaternion. - */ - get absoluteRotationQuaternion() { - this._syncAbsoluteScalingAndRotation(); - return this._absoluteRotationQuaternion; - } - /** - * Sets a new matrix to apply before all other transformation - * @param matrix defines the transform matrix - * @returns the current TransformNode - */ - setPreTransformMatrix(matrix) { - return this.setPivotMatrix(matrix, false); - } - /** - * Sets a new pivot matrix to the current node - * @param matrix defines the new pivot matrix to use - * @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 - * @returns the current TransformNode - */ - setPivotMatrix(matrix, postMultiplyPivotMatrix = true) { - this._pivotMatrix.copyFrom(matrix); - this._usePivotMatrix = !this._pivotMatrix.isIdentity(); - this._cache.pivotMatrixUpdated = true; - this._postMultiplyPivotMatrix = postMultiplyPivotMatrix; - if (this._postMultiplyPivotMatrix) { - if (!this._pivotMatrixInverse) { - this._pivotMatrixInverse = math_vector_Matrix.Invert(this._pivotMatrix); - } - else { - this._pivotMatrix.invertToRef(this._pivotMatrixInverse); - } - } - return this; - } - /** - * Returns the mesh pivot matrix. - * Default : Identity. - * @returns the matrix - */ - getPivotMatrix() { - return this._pivotMatrix; - } - /** - * Instantiate (when possible) or clone that node with its hierarchy - * @param newParent defines the new parent to use for the instance (or clone) - * @param options defines options to configure how copy is done - * @param options.doNotInstantiate defines if the model must be instantiated or just cloned - * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created - * @returns an instance (or a clone) of the current node with its hierarchy - */ - instantiateHierarchy(newParent = null, options, onNewNodeCreated) { - const clone = this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true); - if (clone) { - if (onNewNodeCreated) { - onNewNodeCreated(this, clone); - } - } - for (const child of this.getChildTransformNodes(true)) { - child.instantiateHierarchy(clone, options, onNewNodeCreated); - } - return clone; - } - /** - * Prevents the World matrix to be computed any longer - * @param newWorldMatrix defines an optional matrix to use as world matrix - * @param decompose defines whether to decompose the given newWorldMatrix or directly assign - * @returns the TransformNode. - */ - freezeWorldMatrix(newWorldMatrix = null, decompose = false) { - if (newWorldMatrix) { - if (decompose) { - this._rotation.setAll(0); - this._rotationQuaternion = this._rotationQuaternion || math_vector_Quaternion.Identity(); - newWorldMatrix.decompose(this._scaling, this._rotationQuaternion, this._position); - this.computeWorldMatrix(true); - } - else { - this._worldMatrix = newWorldMatrix; - this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]); - this._afterComputeWorldMatrix(); - } - } - else { - this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily - this.computeWorldMatrix(true); - } - this._isDirty = false; - this._isWorldMatrixFrozen = true; - return this; - } - /** - * Allows back the World matrix computation. - * @returns the TransformNode. - */ - unfreezeWorldMatrix() { - this._isWorldMatrixFrozen = false; - this.computeWorldMatrix(true); - return this; - } - /** - * True if the World matrix has been frozen. - */ - get isWorldMatrixFrozen() { - return this._isWorldMatrixFrozen; - } - /** - * Returns the mesh absolute position in the World. - * @returns a Vector3. - */ - getAbsolutePosition() { - this.computeWorldMatrix(); - return this._absolutePosition; - } - /** - * Sets the mesh absolute position in the World from a Vector3 or an Array(3). - * @param absolutePosition the absolute position to set - * @returns the TransformNode. - */ - setAbsolutePosition(absolutePosition) { - if (!absolutePosition) { - return this; - } - let absolutePositionX; - let absolutePositionY; - let absolutePositionZ; - if (absolutePosition.x === undefined) { - if (arguments.length < 3) { - return this; - } - absolutePositionX = arguments[0]; - absolutePositionY = arguments[1]; - absolutePositionZ = arguments[2]; - } - else { - absolutePositionX = absolutePosition.x; - absolutePositionY = absolutePosition.y; - absolutePositionZ = absolutePosition.z; - } - if (this.parent) { - const invertParentWorldMatrix = math_vector_TmpVectors.Matrix[0]; - this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix); - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position); - } - else { - this.position.x = absolutePositionX; - this.position.y = absolutePositionY; - this.position.z = absolutePositionZ; - } - this._absolutePosition.copyFrom(absolutePosition); - return this; - } - /** - * Sets the mesh position in its local space. - * @param vector3 the position to set in localspace - * @returns the TransformNode. - */ - setPositionWithLocalVector(vector3) { - this.computeWorldMatrix(); - this.position = math_vector_Vector3.TransformNormal(vector3, this._localMatrix); - return this; - } - /** - * Returns the mesh position in the local space from the current World matrix values. - * @returns a new Vector3. - */ - getPositionExpressedInLocalSpace() { - this.computeWorldMatrix(); - const invLocalWorldMatrix = math_vector_TmpVectors.Matrix[0]; - this._localMatrix.invertToRef(invLocalWorldMatrix); - return math_vector_Vector3.TransformNormal(this.position, invLocalWorldMatrix); - } - /** - * Translates the mesh along the passed Vector3 in its local space. - * @param vector3 the distance to translate in localspace - * @returns the TransformNode. - */ - locallyTranslate(vector3) { - this.computeWorldMatrix(true); - this.position = math_vector_Vector3.TransformCoordinates(vector3, this._localMatrix); - return this; - } - /** - * Orients a mesh towards a target point. Mesh must be drawn facing user. - * @param targetPoint the position (must be in same space as current mesh) to look at - * @param yawCor optional yaw (y-axis) correction in radians - * @param pitchCor optional pitch (x-axis) correction in radians - * @param rollCor optional roll (z-axis) correction in radians - * @param space the chosen space of the target - * @returns the TransformNode. - */ - lookAt(targetPoint, yawCor = 0, pitchCor = 0, rollCor = 0, space = math_axis_Space.LOCAL) { - const dv = transformNode_TransformNode._LookAtVectorCache; - const pos = space === math_axis_Space.LOCAL ? this.position : this.getAbsolutePosition(); - targetPoint.subtractToRef(pos, dv); - this.setDirection(dv, yawCor, pitchCor, rollCor); - // Correct for parent's rotation offset - if (space === math_axis_Space.WORLD && this.parent) { - if (this.rotationQuaternion) { - // Get local rotation matrix of the looking object - const rotationMatrix = math_vector_TmpVectors.Matrix[0]; - this.rotationQuaternion.toRotationMatrix(rotationMatrix); - // Offset rotation by parent's inverted rotation matrix to correct in world space - const parentRotationMatrix = math_vector_TmpVectors.Matrix[1]; - this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix); - parentRotationMatrix.invert(); - rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix); - this.rotationQuaternion.fromRotationMatrix(rotationMatrix); - } - else { - // Get local rotation matrix of the looking object - const quaternionRotation = math_vector_TmpVectors.Quaternion[0]; - math_vector_Quaternion.FromEulerVectorToRef(this.rotation, quaternionRotation); - const rotationMatrix = math_vector_TmpVectors.Matrix[0]; - quaternionRotation.toRotationMatrix(rotationMatrix); - // Offset rotation by parent's inverted rotation matrix to correct in world space - const parentRotationMatrix = math_vector_TmpVectors.Matrix[1]; - this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix); - parentRotationMatrix.invert(); - rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix); - quaternionRotation.fromRotationMatrix(rotationMatrix); - quaternionRotation.toEulerAnglesToRef(this.rotation); - } - } - return this; - } - /** - * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh. - * This Vector3 is expressed in the World space. - * @param localAxis axis to rotate - * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh. - */ - getDirection(localAxis) { - const result = math_vector_Vector3.Zero(); - this.getDirectionToRef(localAxis, result); - return result; - } - /** - * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh. - * localAxis is expressed in the mesh local space. - * result is computed in the World space from the mesh World matrix. - * @param localAxis axis to rotate - * @param result the resulting transformnode - * @returns this TransformNode. - */ - getDirectionToRef(localAxis, result) { - math_vector_Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result); - return this; - } - /** - * Sets this transform node rotation to the given local axis. - * @param localAxis the axis in local space - * @param yawCor optional yaw (y-axis) correction in radians - * @param pitchCor optional pitch (x-axis) correction in radians - * @param rollCor optional roll (z-axis) correction in radians - * @returns this TransformNode - */ - setDirection(localAxis, yawCor = 0, pitchCor = 0, rollCor = 0) { - const yaw = -Math.atan2(localAxis.z, localAxis.x) + Math.PI / 2; - const len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z); - const pitch = -Math.atan2(localAxis.y, len); - if (this.rotationQuaternion) { - math_vector_Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion); - } - else { - this.rotation.x = pitch + pitchCor; - this.rotation.y = yaw + yawCor; - this.rotation.z = rollCor; - } - return this; - } - /** - * Sets a new pivot point to the current node - * @param point defines the new pivot point to use - * @param space defines if the point is in world or local space (local by default) - * @returns the current TransformNode - */ - setPivotPoint(point, space = math_axis_Space.LOCAL) { - if (this.getScene().getRenderId() == 0) { - this.computeWorldMatrix(true); - } - const wm = this.getWorldMatrix(); - if (space == math_axis_Space.WORLD) { - const tmat = math_vector_TmpVectors.Matrix[0]; - wm.invertToRef(tmat); - point = math_vector_Vector3.TransformCoordinates(point, tmat); - } - return this.setPivotMatrix(math_vector_Matrix.Translation(-point.x, -point.y, -point.z), true); - } - /** - * Returns a new Vector3 set with the mesh pivot point coordinates in the local space. - * @returns the pivot point - */ - getPivotPoint() { - const point = math_vector_Vector3.Zero(); - this.getPivotPointToRef(point); - return point; - } - /** - * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space. - * @param result the vector3 to store the result - * @returns this TransformNode. - */ - getPivotPointToRef(result) { - result.x = -this._pivotMatrix.m[12]; - result.y = -this._pivotMatrix.m[13]; - result.z = -this._pivotMatrix.m[14]; - return this; - } - /** - * Returns a new Vector3 set with the mesh pivot point World coordinates. - * @returns a new Vector3 set with the mesh pivot point World coordinates. - */ - getAbsolutePivotPoint() { - const point = math_vector_Vector3.Zero(); - this.getAbsolutePivotPointToRef(point); - return point; - } - /** - * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates. - * @param result vector3 to store the result - * @returns this TransformNode. - */ - getAbsolutePivotPointToRef(result) { - this.getPivotPointToRef(result); - math_vector_Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result); - return this; - } - /** - * Flag the transform node as dirty (Forcing it to update everything) - * @param property if set to "rotation" the objects rotationQuaternion will be set to null - * @returns this node - */ - markAsDirty(property) { - if (this._isDirty) { - return this; - } - // We need to explicitly update the children - // as the scene.evaluateActiveMeshes will not poll the transform nodes - if (this._children) { - for (const child of this._children) { - child.markAsDirty(property); - } - } - return super.markAsDirty(property); - } - /** - * Defines the passed node as the parent of the current node. - * The node will remain exactly where it is and its position / rotation will be updated accordingly. - * Note that if the mesh has a pivot matrix / point defined it will be applied after the parent was updated. - * In that case the node will not remain in the same space as it is, as the pivot will be applied. - * To avoid this, you can set updatePivot to true and the pivot will be updated to identity - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent - * @param node the node ot set as the parent - * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change. - * @param updatePivot if true, update the pivot matrix to keep the node in the same space as before - * @returns this TransformNode. - */ - setParent(node, preserveScalingSign = false, updatePivot = false) { - if (!node && !this.parent) { - return this; - } - const quatRotation = math_vector_TmpVectors.Quaternion[0]; - const position = math_vector_TmpVectors.Vector3[0]; - const scale = math_vector_TmpVectors.Vector3[1]; - const invParentMatrix = math_vector_TmpVectors.Matrix[1]; - math_vector_Matrix.IdentityToRef(invParentMatrix); - const composedMatrix = math_vector_TmpVectors.Matrix[0]; - this.computeWorldMatrix(true); - let currentRotation = this.rotationQuaternion; - if (!currentRotation) { - currentRotation = transformNode_TransformNode._TmpRotation; - math_vector_Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, currentRotation); - } - // current global transformation without pivot - math_vector_Matrix.ComposeToRef(this.scaling, currentRotation, this.position, composedMatrix); - if (this.parent) { - composedMatrix.multiplyToRef(this.parent.computeWorldMatrix(true), composedMatrix); - } - // is a node was set, calculate the difference between this and the node - if (node) { - node.computeWorldMatrix(true).invertToRef(invParentMatrix); - composedMatrix.multiplyToRef(invParentMatrix, composedMatrix); - } - composedMatrix.decompose(scale, quatRotation, position, preserveScalingSign ? this : undefined); - if (this.rotationQuaternion) { - this.rotationQuaternion.copyFrom(quatRotation); - } - else { - quatRotation.toEulerAnglesToRef(this.rotation); - } - this.scaling.copyFrom(scale); - this.position.copyFrom(position); - this.parent = node; - if (updatePivot) { - this.setPivotMatrix(math_vector_Matrix.Identity()); - } - return this; - } - /** - * True if the scaling property of this object is non uniform eg. (1,2,1) - */ - get nonUniformScaling() { - return this._nonUniformScaling; - } - /** - * @internal - */ - _updateNonUniformScalingState(value) { - if (this._nonUniformScaling === value) { - return false; - } - this._nonUniformScaling = value; - return true; - } - /** - * Attach the current TransformNode to another TransformNode associated with a bone - * @param bone Bone affecting the TransformNode - * @param affectedTransformNode TransformNode associated with the bone - * @returns this object - */ - attachToBone(bone, affectedTransformNode) { - this._currentParentWhenAttachingToBone = this.parent; - this._transformToBoneReferal = affectedTransformNode; - this.parent = bone; - bone.getSkeleton().prepare(true); // make sure bone.getFinalMatrix() is up to date - if (bone.getFinalMatrix().determinant() < 0) { - this.scalingDeterminant *= -1; - } - return this; - } - /** - * Detach the transform node if its associated with a bone - * @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) - * @returns this object - */ - detachFromBone(resetToPreviousParent = false) { - if (!this.parent) { - if (resetToPreviousParent) { - this.parent = this._currentParentWhenAttachingToBone; - } - return this; - } - if (this.parent.getWorldMatrix().determinant() < 0) { - this.scalingDeterminant *= -1; - } - this._transformToBoneReferal = null; - if (resetToPreviousParent) { - this.parent = this._currentParentWhenAttachingToBone; - } - else { - this.parent = null; - } - return this; - } - /** - * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space. - * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD. - * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. - * The passed axis is also normalized. - * @param axis the axis to rotate around - * @param amount the amount to rotate in radians - * @param space Space to rotate in (Default: local) - * @returns the TransformNode. - */ - rotate(axis, amount, space) { - axis.normalize(); - if (!this.rotationQuaternion) { - this.rotationQuaternion = this.rotation.toQuaternion(); - this.rotation.setAll(0); - } - let rotationQuaternion; - if (!space || space === math_axis_Space.LOCAL) { - rotationQuaternion = math_vector_Quaternion.RotationAxisToRef(axis, amount, transformNode_TransformNode._RotationAxisCache); - this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion); - } - else { - if (this.parent) { - const invertParentWorldMatrix = math_vector_TmpVectors.Matrix[0]; - this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix); - axis = math_vector_Vector3.TransformNormal(axis, invertParentWorldMatrix); - } - rotationQuaternion = math_vector_Quaternion.RotationAxisToRef(axis, amount, transformNode_TransformNode._RotationAxisCache); - rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); - } - return this; - } - /** - * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space. - * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. - * The passed axis is also normalized. . - * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm - * @param point the point to rotate around - * @param axis the axis to rotate around - * @param amount the amount to rotate in radians - * @returns the TransformNode - */ - rotateAround(point, axis, amount) { - axis.normalize(); - if (!this.rotationQuaternion) { - this.rotationQuaternion = math_vector_Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z); - this.rotation.setAll(0); - } - const tmpVector = math_vector_TmpVectors.Vector3[0]; - const finalScale = math_vector_TmpVectors.Vector3[1]; - const finalTranslation = math_vector_TmpVectors.Vector3[2]; - const finalRotation = math_vector_TmpVectors.Quaternion[0]; - const translationMatrix = math_vector_TmpVectors.Matrix[0]; // T - const translationMatrixInv = math_vector_TmpVectors.Matrix[1]; // T' - const rotationMatrix = math_vector_TmpVectors.Matrix[2]; // R - const finalMatrix = math_vector_TmpVectors.Matrix[3]; // T' x R x T - point.subtractToRef(this.position, tmpVector); - math_vector_Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T - math_vector_Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T' - math_vector_Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R - translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R - finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T - finalMatrix.decompose(finalScale, finalRotation, finalTranslation); - this.position.addInPlace(finalTranslation); - finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); - return this; - } - /** - * Translates the mesh along the axis vector for the passed distance in the given space. - * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD. - * @param axis the axis to translate in - * @param distance the distance to translate - * @param space Space to rotate in (Default: local) - * @returns the TransformNode. - */ - translate(axis, distance, space) { - const displacementVector = axis.scale(distance); - if (!space || space === math_axis_Space.LOCAL) { - const tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector); - this.setPositionWithLocalVector(tempV3); - } - else { - this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector)); - } - return this; - } - /** - * Adds a rotation step to the mesh current rotation. - * x, y, z are Euler angles expressed in radians. - * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set. - * This means this rotation is made in the mesh local space only. - * It's useful to set a custom rotation order different from the BJS standard one YXZ. - * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis. - * ```javascript - * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3); - * ``` - * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values. - * 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. - * @param x Rotation to add - * @param y Rotation to add - * @param z Rotation to add - * @returns the TransformNode. - */ - addRotation(x, y, z) { - let rotationQuaternion; - if (this.rotationQuaternion) { - rotationQuaternion = this.rotationQuaternion; - } - else { - rotationQuaternion = math_vector_TmpVectors.Quaternion[1]; - math_vector_Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion); - } - const accumulation = math_vector_TmpVectors.Quaternion[0]; - math_vector_Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation); - rotationQuaternion.multiplyInPlace(accumulation); - if (!this.rotationQuaternion) { - rotationQuaternion.toEulerAnglesToRef(this.rotation); - } - return this; - } - /** - * @internal - */ - _getEffectiveParent() { - return this.parent; - } - /** - * Returns whether the transform node world matrix computation needs the camera information to be computed. - * This is the case when the node is a billboard or has an infinite distance for instance. - * @returns true if the world matrix computation needs the camera information to be computed - */ - isWorldMatrixCameraDependent() { - return (this._infiniteDistance && !this.parent) || (this._billboardMode !== transformNode_TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard); - } - /** - * Computes the world matrix of the node - * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch - * @param camera defines the camera used if different from the scene active camera (This is used with modes like Billboard or infinite distance) - * @returns the world matrix - */ - computeWorldMatrix(force = false, camera = null) { - if (this._isWorldMatrixFrozen && !this._isDirty) { - return this._worldMatrix; - } - const currentRenderId = this.getScene().getRenderId(); - if (!this._isDirty && !force && (this._currentRenderId === currentRenderId || this.isSynchronized())) { - this._currentRenderId = currentRenderId; - return this._worldMatrix; - } - camera = camera || this.getScene().activeCamera; - this._updateCache(); - const cache = this._cache; - cache.pivotMatrixUpdated = false; - cache.billboardMode = this.billboardMode; - cache.infiniteDistance = this.infiniteDistance; - cache.parent = this._parentNode; - this._currentRenderId = currentRenderId; - this._childUpdateId += 1; - this._isDirty = false; - this._position._isDirty = false; - this._rotation._isDirty = false; - this._scaling._isDirty = false; - const parent = this._getEffectiveParent(); - // Scaling - const scaling = transformNode_TransformNode._TmpScaling; - let translation = this._position; - // Translation - if (this._infiniteDistance) { - if (!this.parent && camera) { - const cameraWorldMatrix = camera.getWorldMatrix(); - const cameraGlobalPosition = new math_vector_Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]); - translation = transformNode_TransformNode._TmpTranslation; - translation.copyFromFloats(this._position.x + cameraGlobalPosition.x, this._position.y + cameraGlobalPosition.y, this._position.z + cameraGlobalPosition.z); - } - } - // Scaling - scaling.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant); - // Rotation - let rotation; - if (this._rotationQuaternion) { - this._rotationQuaternion._isDirty = false; - rotation = this._rotationQuaternion; - if (this.reIntegrateRotationIntoRotationQuaternion) { - const len = this.rotation.lengthSquared(); - if (len) { - this._rotationQuaternion.multiplyInPlace(math_vector_Quaternion.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z)); - this._rotation.copyFromFloats(0, 0, 0); - } - } - } - else { - rotation = transformNode_TransformNode._TmpRotation; - math_vector_Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, rotation); - } - // Compose - if (this._usePivotMatrix) { - const scaleMatrix = math_vector_TmpVectors.Matrix[1]; - math_vector_Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, scaleMatrix); - // Rotation - const rotationMatrix = math_vector_TmpVectors.Matrix[0]; - rotation.toRotationMatrix(rotationMatrix); - // Composing transformations - this._pivotMatrix.multiplyToRef(scaleMatrix, math_vector_TmpVectors.Matrix[4]); - math_vector_TmpVectors.Matrix[4].multiplyToRef(rotationMatrix, this._localMatrix); - // Post multiply inverse of pivotMatrix - if (this._postMultiplyPivotMatrix) { - this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix); - } - this._localMatrix.addTranslationFromFloats(translation.x, translation.y, translation.z); - } - else { - math_vector_Matrix.ComposeToRef(scaling, rotation, translation, this._localMatrix); - } - // Parent - if (parent && parent.getWorldMatrix) { - if (force) { - parent.computeWorldMatrix(force); - } - if (cache.useBillboardPath) { - if (this._transformToBoneReferal) { - const bone = this.parent; - bone.getSkeleton().prepare(); - bone.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), math_vector_TmpVectors.Matrix[7]); - } - else { - math_vector_TmpVectors.Matrix[7].copyFrom(parent.getWorldMatrix()); - } - // Extract scaling and translation from parent - const translation = math_vector_TmpVectors.Vector3[5]; - const scale = math_vector_TmpVectors.Vector3[6]; - const orientation = math_vector_TmpVectors.Quaternion[0]; - math_vector_TmpVectors.Matrix[7].decompose(scale, orientation, translation); - math_vector_Matrix.ScalingToRef(scale.x, scale.y, scale.z, math_vector_TmpVectors.Matrix[7]); - math_vector_TmpVectors.Matrix[7].setTranslation(translation); - if (transformNode_TransformNode.BillboardUseParentOrientation) { - // set localMatrix translation to be transformed against parent's orientation. - this._position.applyRotationQuaternionToRef(orientation, translation); - this._localMatrix.setTranslation(translation); - } - this._localMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[7], this._worldMatrix); - } - else { - if (this._transformToBoneReferal) { - const bone = this.parent; - bone.getSkeleton().prepare(); - this._localMatrix.multiplyToRef(bone.getFinalMatrix(), math_vector_TmpVectors.Matrix[6]); - math_vector_TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix); - } - else { - this._localMatrix.multiplyToRef(parent.getWorldMatrix(), this._worldMatrix); - } - } - this._markSyncedWithParent(); - } - else { - this._worldMatrix.copyFrom(this._localMatrix); - } - // Billboarding based on camera orientation (testing PG:http://www.babylonjs-playground.com/#UJEIL#13) - if (cache.useBillboardPath && camera && this.billboardMode && !cache.useBillboardPosition) { - const storedTranslation = math_vector_TmpVectors.Vector3[0]; - this._worldMatrix.getTranslationToRef(storedTranslation); // Save translation - // Cancel camera rotation - math_vector_TmpVectors.Matrix[1].copyFrom(camera.getViewMatrix()); - if (this._scene.useRightHandedSystem) { - math_vector_TmpVectors.Matrix[1].multiplyToRef(convertRHSToLHS, math_vector_TmpVectors.Matrix[1]); - } - math_vector_TmpVectors.Matrix[1].setTranslationFromFloats(0, 0, 0); - math_vector_TmpVectors.Matrix[1].invertToRef(math_vector_TmpVectors.Matrix[0]); - if ((this.billboardMode & transformNode_TransformNode.BILLBOARDMODE_ALL) !== transformNode_TransformNode.BILLBOARDMODE_ALL) { - math_vector_TmpVectors.Matrix[0].decompose(undefined, math_vector_TmpVectors.Quaternion[0], undefined); - const eulerAngles = math_vector_TmpVectors.Vector3[1]; - math_vector_TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles); - if ((this.billboardMode & transformNode_TransformNode.BILLBOARDMODE_X) !== transformNode_TransformNode.BILLBOARDMODE_X) { - eulerAngles.x = 0; - } - if ((this.billboardMode & transformNode_TransformNode.BILLBOARDMODE_Y) !== transformNode_TransformNode.BILLBOARDMODE_Y) { - eulerAngles.y = 0; - } - if ((this.billboardMode & transformNode_TransformNode.BILLBOARDMODE_Z) !== transformNode_TransformNode.BILLBOARDMODE_Z) { - eulerAngles.z = 0; - } - math_vector_Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, math_vector_TmpVectors.Matrix[0]); - } - this._worldMatrix.setTranslationFromFloats(0, 0, 0); - this._worldMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[0], this._worldMatrix); - // Restore translation - this._worldMatrix.setTranslation(math_vector_TmpVectors.Vector3[0]); - } - // Billboarding based on camera position - else if (cache.useBillboardPath && camera && cache.useBillboardPosition) { - const storedTranslation = math_vector_TmpVectors.Vector3[0]; - // Save translation - this._worldMatrix.getTranslationToRef(storedTranslation); - // Compute camera position in local space - const cameraPosition = camera.globalPosition; - this._worldMatrix.invertToRef(math_vector_TmpVectors.Matrix[1]); - const camInObjSpace = math_vector_TmpVectors.Vector3[1]; - math_vector_Vector3.TransformCoordinatesToRef(cameraPosition, math_vector_TmpVectors.Matrix[1], camInObjSpace); - camInObjSpace.normalize(); - // Find the lookAt info in local space - const yaw = -Math.atan2(camInObjSpace.z, camInObjSpace.x) + Math.PI / 2; - const len = Math.sqrt(camInObjSpace.x * camInObjSpace.x + camInObjSpace.z * camInObjSpace.z); - const pitch = -Math.atan2(camInObjSpace.y, len); - math_vector_Quaternion.RotationYawPitchRollToRef(yaw, pitch, 0, math_vector_TmpVectors.Quaternion[0]); - if ((this.billboardMode & transformNode_TransformNode.BILLBOARDMODE_ALL) !== transformNode_TransformNode.BILLBOARDMODE_ALL) { - const eulerAngles = math_vector_TmpVectors.Vector3[1]; - math_vector_TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles); - if ((this.billboardMode & transformNode_TransformNode.BILLBOARDMODE_X) !== transformNode_TransformNode.BILLBOARDMODE_X) { - eulerAngles.x = 0; - } - if ((this.billboardMode & transformNode_TransformNode.BILLBOARDMODE_Y) !== transformNode_TransformNode.BILLBOARDMODE_Y) { - eulerAngles.y = 0; - } - if ((this.billboardMode & transformNode_TransformNode.BILLBOARDMODE_Z) !== transformNode_TransformNode.BILLBOARDMODE_Z) { - eulerAngles.z = 0; - } - math_vector_Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, math_vector_TmpVectors.Matrix[0]); - } - else { - math_vector_Matrix.FromQuaternionToRef(math_vector_TmpVectors.Quaternion[0], math_vector_TmpVectors.Matrix[0]); - } - // Cancel translation - this._worldMatrix.setTranslationFromFloats(0, 0, 0); - // Rotate according to lookat (diff from local to lookat) - this._worldMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[0], this._worldMatrix); - // Restore translation - this._worldMatrix.setTranslation(math_vector_TmpVectors.Vector3[0]); - } - // Normal matrix - if (!this.ignoreNonUniformScaling) { - if (this._scaling.isNonUniformWithinEpsilon(0.000001)) { - this._updateNonUniformScalingState(true); - } - else if (parent && parent._nonUniformScaling) { - this._updateNonUniformScalingState(parent._nonUniformScaling); - } - else { - this._updateNonUniformScalingState(false); - } - } - else { - this._updateNonUniformScalingState(false); - } - this._afterComputeWorldMatrix(); - // Absolute position - this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]); - this._isAbsoluteSynced = false; - // Callbacks - this.onAfterWorldMatrixUpdateObservable.notifyObservers(this); - if (!this._poseMatrix) { - this._poseMatrix = math_vector_Matrix.Invert(this._worldMatrix); - } - // Cache the determinant - this._worldMatrixDeterminantIsDirty = true; - return this._worldMatrix; - } - /** - * Resets this nodeTransform's local matrix to Matrix.Identity(). - * @param independentOfChildren indicates if all child nodeTransform's world-space transform should be preserved. - */ - resetLocalMatrix(independentOfChildren = true) { - this.computeWorldMatrix(); - if (independentOfChildren) { - const children = this.getChildren(); - for (let i = 0; i < children.length; ++i) { - const child = children[i]; - if (child) { - child.computeWorldMatrix(); - const bakedMatrix = math_vector_TmpVectors.Matrix[0]; - child._localMatrix.multiplyToRef(this._localMatrix, bakedMatrix); - const tmpRotationQuaternion = math_vector_TmpVectors.Quaternion[0]; - bakedMatrix.decompose(child.scaling, tmpRotationQuaternion, child.position); - if (child.rotationQuaternion) { - child.rotationQuaternion.copyFrom(tmpRotationQuaternion); - } - else { - tmpRotationQuaternion.toEulerAnglesToRef(child.rotation); - } - } - } - } - this.scaling.copyFromFloats(1, 1, 1); - this.position.copyFromFloats(0, 0, 0); - this.rotation.copyFromFloats(0, 0, 0); - //only if quaternion is already set - if (this.rotationQuaternion) { - this.rotationQuaternion = math_vector_Quaternion.Identity(); - } - this._worldMatrix = math_vector_Matrix.Identity(); - } - _afterComputeWorldMatrix() { } - /** - * If you'd like to be called back after the mesh position, rotation or scaling has been updated. - * @param func callback function to add - * - * @returns the TransformNode. - */ - registerAfterWorldMatrixUpdate(func) { - this.onAfterWorldMatrixUpdateObservable.add(func); - return this; - } - /** - * Removes a registered callback function. - * @param func callback function to remove - * @returns the TransformNode. - */ - unregisterAfterWorldMatrixUpdate(func) { - this.onAfterWorldMatrixUpdateObservable.removeCallback(func); - return this; - } - /** - * Gets the position of the current mesh in camera space - * @param camera defines the camera to use - * @returns a position - */ - getPositionInCameraSpace(camera = null) { - if (!camera) { - camera = this.getScene().activeCamera; - } - return math_vector_Vector3.TransformCoordinates(this.getAbsolutePosition(), camera.getViewMatrix()); - } - /** - * Returns the distance from the mesh to the active camera - * @param camera defines the camera to use - * @returns the distance - */ - getDistanceToCamera(camera = null) { - if (!camera) { - camera = this.getScene().activeCamera; - } - return this.getAbsolutePosition().subtract(camera.globalPosition).length(); - } - /** - * Clone the current transform node - * @param name Name of the new clone - * @param newParent New parent for the clone - * @param doNotCloneChildren Do not clone children hierarchy - * @returns the new transform node - */ - clone(name, newParent, doNotCloneChildren) { - const result = decorators_SerializationHelper.Clone(() => new transformNode_TransformNode(name, this.getScene()), this); - result.name = name; - result.id = name; - if (newParent) { - result.parent = newParent; - } - if (!doNotCloneChildren) { - // Children - const directDescendants = this.getDescendants(true); - for (let index = 0; index < directDescendants.length; index++) { - const child = directDescendants[index]; - if (child.clone) { - child.clone(name + "." + child.name, result); - } - } - } - return result; - } - /** - * Serializes the objects information. - * @param currentSerializationObject defines the object to serialize in - * @returns the serialized object - */ - serialize(currentSerializationObject) { - const serializationObject = decorators_SerializationHelper.Serialize(this, currentSerializationObject); - serializationObject.type = this.getClassName(); - serializationObject.uniqueId = this.uniqueId; - // Parent - if (this.parent) { - this.parent._serializeAsParent(serializationObject); - } - serializationObject.localMatrix = this.getPivotMatrix().asArray(); - serializationObject.isEnabled = this.isEnabled(); - return serializationObject; - } - // Statics - /** - * Returns a new TransformNode object parsed from the source provided. - * @param parsedTransformNode is the source. - * @param scene the scene the object belongs to - * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with - * @returns a new TransformNode object parsed from the source provided. - */ - static Parse(parsedTransformNode, scene, rootUrl) { - const transformNode = decorators_SerializationHelper.Parse(() => new transformNode_TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl); - if (parsedTransformNode.localMatrix) { - transformNode.setPreTransformMatrix(math_vector_Matrix.FromArray(parsedTransformNode.localMatrix)); - } - else if (parsedTransformNode.pivotMatrix) { - transformNode.setPivotMatrix(math_vector_Matrix.FromArray(parsedTransformNode.pivotMatrix)); - } - transformNode.setEnabled(parsedTransformNode.isEnabled); - transformNode._waitingParsedUniqueId = parsedTransformNode.uniqueId; - // Parent - if (parsedTransformNode.parentId !== undefined) { - transformNode._waitingParentId = parsedTransformNode.parentId; - } - if (parsedTransformNode.parentInstanceIndex !== undefined) { - transformNode._waitingParentInstanceIndex = parsedTransformNode.parentInstanceIndex; - } - return transformNode; - } - /** - * Get all child-transformNodes of this node - * @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 - * @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 - * @returns an array of TransformNode - */ - getChildTransformNodes(directDescendantsOnly, predicate) { - const results = []; - this._getDescendants(results, directDescendantsOnly, (node) => { - return (!predicate || predicate(node)) && node instanceof transformNode_TransformNode; - }); - return results; - } - /** - * Releases resources associated with this transform node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) - */ - dispose(doNotRecurse, disposeMaterialAndTextures = false) { - // Animations - this.getScene().stopAnimation(this); - // Remove from scene - this.getScene().removeTransformNode(this); - if (this._parentContainer) { - const index = this._parentContainer.transformNodes.indexOf(this); - if (index > -1) { - this._parentContainer.transformNodes.splice(index, 1); - } - this._parentContainer = null; - } - this.onAfterWorldMatrixUpdateObservable.clear(); - if (doNotRecurse) { - const transformNodes = this.getChildTransformNodes(true); - for (const transformNode of transformNodes) { - transformNode.parent = null; - transformNode.computeWorldMatrix(true); - } - } - super.dispose(doNotRecurse, disposeMaterialAndTextures); - } - /** - * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) - * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false - * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false - * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling - * @returns the current mesh - */ - normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) { - let storedRotation = null; - let storedRotationQuaternion = null; - if (ignoreRotation) { - if (this.rotationQuaternion) { - storedRotationQuaternion = this.rotationQuaternion.clone(); - this.rotationQuaternion.copyFromFloats(0, 0, 0, 1); - } - else if (this.rotation) { - storedRotation = this.rotation.clone(); - this.rotation.copyFromFloats(0, 0, 0); - } - } - const boundingVectors = this.getHierarchyBoundingVectors(includeDescendants, predicate); - const sizeVec = boundingVectors.max.subtract(boundingVectors.min); - const maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z); - if (maxDimension === 0) { - return this; - } - const scale = 1 / maxDimension; - this.scaling.scaleInPlace(scale); - if (ignoreRotation) { - if (this.rotationQuaternion && storedRotationQuaternion) { - this.rotationQuaternion.copyFrom(storedRotationQuaternion); - } - else if (this.rotation && storedRotation) { - this.rotation.copyFrom(storedRotation); - } - } - return this; - } - _syncAbsoluteScalingAndRotation() { - if (!this._isAbsoluteSynced) { - this._worldMatrix.decompose(this._absoluteScaling, this._absoluteRotationQuaternion); - this._isAbsoluteSynced = true; - } - } -} -// Statics -/** - * Object will not rotate to face the camera - */ -transformNode_TransformNode.BILLBOARDMODE_NONE = 0; -/** - * Object will rotate to face the camera but only on the x axis - */ -transformNode_TransformNode.BILLBOARDMODE_X = 1; -/** - * Object will rotate to face the camera but only on the y axis - */ -transformNode_TransformNode.BILLBOARDMODE_Y = 2; -/** - * Object will rotate to face the camera but only on the z axis - */ -transformNode_TransformNode.BILLBOARDMODE_Z = 4; -/** - * Object will rotate to face the camera - */ -transformNode_TransformNode.BILLBOARDMODE_ALL = 7; -/** - * Object will rotate to face the camera's position instead of orientation - */ -transformNode_TransformNode.BILLBOARDMODE_USE_POSITION = 128; -/** - * Child transform with Billboard flags should or should not apply parent rotation (default if off) - */ -transformNode_TransformNode.BillboardUseParentOrientation = false; -transformNode_TransformNode._TmpRotation = math_vector_Quaternion.Zero(); -transformNode_TransformNode._TmpScaling = math_vector_Vector3.Zero(); -transformNode_TransformNode._TmpTranslation = math_vector_Vector3.Zero(); -transformNode_TransformNode._LookAtVectorCache = new math_vector_Vector3(0, 0, 0); -transformNode_TransformNode._RotationAxisCache = new math_vector_Quaternion(); -__decorate([ - serializeAsVector3("position") -], transformNode_TransformNode.prototype, "_position", void 0); -__decorate([ - serializeAsVector3("rotation") -], transformNode_TransformNode.prototype, "_rotation", void 0); -__decorate([ - serializeAsQuaternion("rotationQuaternion") -], transformNode_TransformNode.prototype, "_rotationQuaternion", void 0); -__decorate([ - serializeAsVector3("scaling") -], transformNode_TransformNode.prototype, "_scaling", void 0); -__decorate([ - serialize("billboardMode") -], transformNode_TransformNode.prototype, "_billboardMode", void 0); -__decorate([ - serialize() -], transformNode_TransformNode.prototype, "scalingDeterminant", void 0); -__decorate([ - serialize("infiniteDistance") -], transformNode_TransformNode.prototype, "_infiniteDistance", void 0); -__decorate([ - serialize() -], transformNode_TransformNode.prototype, "ignoreNonUniformScaling", void 0); -__decorate([ - serialize() -], transformNode_TransformNode.prototype, "reIntegrateRotationIntoRotationQuaternion", void 0); -//# sourceMappingURL=transformNode.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Collisions/meshCollisionData.js - -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _MeshCollisionData { - constructor() { - this._checkCollisions = false; - this._collisionMask = -1; - this._collisionGroup = -1; - this._surroundingMeshes = null; - this._collider = null; - this._oldPositionForCollisions = new math_vector_Vector3(0, 0, 0); - this._diffPositionForCollisions = new math_vector_Vector3(0, 0, 0); - this._collisionResponse = true; - } -} -//# sourceMappingURL=meshCollisionData.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/abstractMesh.js - - - - - - - - - - - - - - - - - - -/** @internal */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _FacetDataStorage { - constructor() { - this.facetNb = 0; // facet number - this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partitioning space - this.partitioningBBoxRatio = 1.01; // the partitioning array space is by default 1% bigger than the bounding box - this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ? - this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation - this.bbSize = math_vector_Vector3.Zero(); // bbox size approximated for facet data - this.subDiv = { - // actual number of subdivisions per axis for ComputeNormals() - max: 1, - // eslint-disable-next-line @typescript-eslint/naming-convention - X: 1, - // eslint-disable-next-line @typescript-eslint/naming-convention - Y: 1, - // eslint-disable-next-line @typescript-eslint/naming-convention - Z: 1, - }; - this.facetDepthSort = false; // is the facet depth sort to be computed - this.facetDepthSortEnabled = false; // is the facet depth sort initialized - } -} -/** - * @internal - **/ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _InternalAbstractMeshDataInfo { - constructor() { - this._hasVertexAlpha = false; - this._useVertexColors = true; - this._numBoneInfluencers = 4; - this._applyFog = true; - this._receiveShadows = false; - this._facetData = new _FacetDataStorage(); - this._visibility = 1.0; - this._skeleton = null; - this._layerMask = 0x0fffffff; - this._computeBonesUsingShaders = true; - this._isActive = false; - this._onlyForInstances = false; - this._isActiveIntermediate = false; - this._onlyForInstancesIntermediate = false; - this._actAsRegularMesh = false; - this._currentLOD = null; - this._currentLODIsUpToDate = false; - this._collisionRetryCount = 3; - this._morphTargetManager = null; - this._renderingGroupId = 0; - this._bakedVertexAnimationManager = null; - this._material = null; - this._positions = null; - this._pointerOverDisableMeshTesting = false; - // Collisions - this._meshCollisionData = new _MeshCollisionData(); - this._enableDistantPicking = false; - /** @internal - * Bounding info that is unnafected by the addition of thin instances - */ - this._rawBoundingInfo = null; - } -} -/** - * Class used to store all common mesh properties - */ -class abstractMesh_AbstractMesh extends transformNode_TransformNode { - /** - * No billboard - */ - static get BILLBOARDMODE_NONE() { - return transformNode_TransformNode.BILLBOARDMODE_NONE; - } - /** Billboard on X axis */ - static get BILLBOARDMODE_X() { - return transformNode_TransformNode.BILLBOARDMODE_X; - } - /** Billboard on Y axis */ - static get BILLBOARDMODE_Y() { - return transformNode_TransformNode.BILLBOARDMODE_Y; - } - /** Billboard on Z axis */ - static get BILLBOARDMODE_Z() { - return transformNode_TransformNode.BILLBOARDMODE_Z; - } - /** Billboard on all axes */ - static get BILLBOARDMODE_ALL() { - return transformNode_TransformNode.BILLBOARDMODE_ALL; - } - /** Billboard on using position instead of orientation */ - static get BILLBOARDMODE_USE_POSITION() { - return transformNode_TransformNode.BILLBOARDMODE_USE_POSITION; - } - /** - * Gets the number of facets in the mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet - */ - get facetNb() { - return this._internalAbstractMeshDataInfo._facetData.facetNb; - } - /** - * Gets or set the number (integer) of subdivisions per axis in the partitioning space - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning - */ - get partitioningSubdivisions() { - return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions; - } - set partitioningSubdivisions(nb) { - this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions = nb; - } - /** - * The ratio (float) to apply to the bounding box size to set to the partitioning space. - * Ex : 1.01 (default) the partitioning space is 1% bigger than the bounding box - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning - */ - get partitioningBBoxRatio() { - return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio; - } - set partitioningBBoxRatio(ratio) { - this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio = ratio; - } - /** - * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`. - * Works only for updatable meshes. - * Doesn't work with multi-materials - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort - */ - get mustDepthSortFacets() { - return this._internalAbstractMeshDataInfo._facetData.facetDepthSort; - } - set mustDepthSortFacets(sort) { - this._internalAbstractMeshDataInfo._facetData.facetDepthSort = sort; - } - /** - * The location (Vector3) where the facet depth sort must be computed from. - * By default, the active camera position. - * Used only when facet depth sort is enabled - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort - */ - get facetDepthSortFrom() { - return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom; - } - set facetDepthSortFrom(location) { - this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom = location; - } - /** number of collision detection tries. Change this value if not all collisions are detected and handled properly */ - get collisionRetryCount() { - return this._internalAbstractMeshDataInfo._collisionRetryCount; - } - set collisionRetryCount(retryCount) { - this._internalAbstractMeshDataInfo._collisionRetryCount = retryCount; - } - /** - * gets a boolean indicating if facetData is enabled - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet - */ - get isFacetDataEnabled() { - return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled; - } - /** - * Gets or sets the morph target manager - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets - */ - get morphTargetManager() { - return this._internalAbstractMeshDataInfo._morphTargetManager; - } - set morphTargetManager(value) { - if (this._internalAbstractMeshDataInfo._morphTargetManager === value) { - return; - } - this._internalAbstractMeshDataInfo._morphTargetManager = value; - this._syncGeometryWithMorphTargetManager(); - } - /** - * Gets or sets the baked vertex animation manager - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/baked_texture_animations - */ - get bakedVertexAnimationManager() { - return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager; - } - set bakedVertexAnimationManager(value) { - if (this._internalAbstractMeshDataInfo._bakedVertexAnimationManager === value) { - return; - } - this._internalAbstractMeshDataInfo._bakedVertexAnimationManager = value; - this._markSubMeshesAsAttributesDirty(); - } - /** @internal */ - _syncGeometryWithMorphTargetManager() { } - /** - * @internal - */ - _updateNonUniformScalingState(value) { - if (!super._updateNonUniformScalingState(value)) { - return false; - } - this._markSubMeshesAsMiscDirty(); - return true; - } - /** @internal */ - get rawBoundingInfo() { - return this._internalAbstractMeshDataInfo._rawBoundingInfo; - } - set rawBoundingInfo(boundingInfo) { - this._internalAbstractMeshDataInfo._rawBoundingInfo = boundingInfo; - } - /** Set a function to call when this mesh collides with another one */ - set onCollide(callback) { - if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver) { - this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver); - } - this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver = this.onCollideObservable.add(callback); - } - /** Set a function to call when the collision's position changes */ - set onCollisionPositionChange(callback) { - if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver) { - this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver); - } - this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback); - } - /** - * Gets or sets mesh visibility between 0 and 1 (default is 1) - */ - get visibility() { - return this._internalAbstractMeshDataInfo._visibility; - } - /** - * Gets or sets mesh visibility between 0 and 1 (default is 1) - */ - set visibility(value) { - if (this._internalAbstractMeshDataInfo._visibility === value) { - return; - } - const oldValue = this._internalAbstractMeshDataInfo._visibility; - this._internalAbstractMeshDataInfo._visibility = value; - if ((oldValue === 1 && value !== 1) || (oldValue !== 1 && value === 1)) { - this._markSubMeshesAsDirty((defines) => { - defines.markAsMiscDirty(); - defines.markAsPrePassDirty(); - }); - } - } - /** - * 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). - * Set this property to true if you want thin instances picking to be reported accurately when moving over the mesh. - * Note that setting this property to true will incur some performance penalties when dealing with pointer events for this mesh so use it sparingly. - */ - get pointerOverDisableMeshTesting() { - return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting; - } - set pointerOverDisableMeshTesting(disable) { - this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting = disable; - } - /** - * Specifies the rendering group id for this mesh (0 by default) - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#rendering-groups - */ - get renderingGroupId() { - return this._internalAbstractMeshDataInfo._renderingGroupId; - } - set renderingGroupId(value) { - this._internalAbstractMeshDataInfo._renderingGroupId = value; - } - /** Gets or sets current material */ - get material() { - return this._internalAbstractMeshDataInfo._material; - } - set material(value) { - if (this._internalAbstractMeshDataInfo._material === value) { - return; - } - // remove from material mesh map id needed - if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) { - this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined; - } - this._internalAbstractMeshDataInfo._material = value; - if (value && value.meshMap) { - value.meshMap[this.uniqueId] = this; - } - if (this.onMaterialChangedObservable.hasObservers()) { - this.onMaterialChangedObservable.notifyObservers(this); - } - if (!this.subMeshes) { - return; - } - this.resetDrawCache(); - this._unBindEffect(); - } - /** - * Gets the material used to render the mesh in a specific render pass - * @param renderPassId render pass id - * @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) - */ - getMaterialForRenderPass(renderPassId) { - var _a; - return (_a = this._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[renderPassId]; - } - /** - * Sets the material to be used to render the mesh in a specific render pass - * @param renderPassId render pass id - * @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) - */ - setMaterialForRenderPass(renderPassId, material) { - this.resetDrawCache(renderPassId); - if (!this._internalAbstractMeshDataInfo._materialForRenderPass) { - this._internalAbstractMeshDataInfo._materialForRenderPass = []; - } - this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId] = material; - } - /** - * Gets or sets a boolean indicating that this mesh can receive realtime shadows - * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows - */ - get receiveShadows() { - return this._internalAbstractMeshDataInfo._receiveShadows; - } - set receiveShadows(value) { - if (this._internalAbstractMeshDataInfo._receiveShadows === value) { - return; - } - this._internalAbstractMeshDataInfo._receiveShadows = value; - this._markSubMeshesAsLightDirty(); - } - /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */ - get hasVertexAlpha() { - return this._internalAbstractMeshDataInfo._hasVertexAlpha; - } - set hasVertexAlpha(value) { - if (this._internalAbstractMeshDataInfo._hasVertexAlpha === value) { - return; - } - this._internalAbstractMeshDataInfo._hasVertexAlpha = value; - this._markSubMeshesAsAttributesDirty(); - this._markSubMeshesAsMiscDirty(); - } - /** 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) */ - get useVertexColors() { - return this._internalAbstractMeshDataInfo._useVertexColors; - } - set useVertexColors(value) { - if (this._internalAbstractMeshDataInfo._useVertexColors === value) { - return; - } - this._internalAbstractMeshDataInfo._useVertexColors = value; - this._markSubMeshesAsAttributesDirty(); - } - /** - * Gets or sets a boolean indicating that bone animations must be computed by the GPU (true by default) - */ - get computeBonesUsingShaders() { - return this._internalAbstractMeshDataInfo._computeBonesUsingShaders; - } - set computeBonesUsingShaders(value) { - if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) { - return; - } - this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value; - this._markSubMeshesAsAttributesDirty(); - } - /** Gets or sets the number of allowed bone influences per vertex (4 by default) */ - get numBoneInfluencers() { - return this._internalAbstractMeshDataInfo._numBoneInfluencers; - } - set numBoneInfluencers(value) { - if (this._internalAbstractMeshDataInfo._numBoneInfluencers === value) { - return; - } - this._internalAbstractMeshDataInfo._numBoneInfluencers = value; - this._markSubMeshesAsAttributesDirty(); - } - /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */ - get applyFog() { - return this._internalAbstractMeshDataInfo._applyFog; - } - set applyFog(value) { - if (this._internalAbstractMeshDataInfo._applyFog === value) { - return; - } - this._internalAbstractMeshDataInfo._applyFog = value; - this._markSubMeshesAsMiscDirty(); - } - /** When enabled, decompose picking matrices for better precision with large values for mesh position and scling */ - get enableDistantPicking() { - return this._internalAbstractMeshDataInfo._enableDistantPicking; - } - set enableDistantPicking(value) { - this._internalAbstractMeshDataInfo._enableDistantPicking = value; - } - /** - * Gets or sets the current layer mask (default is 0x0FFFFFFF) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/layerMasksAndMultiCam - */ - get layerMask() { - return this._internalAbstractMeshDataInfo._layerMask; - } - set layerMask(value) { - if (value === this._internalAbstractMeshDataInfo._layerMask) { - return; - } - this._internalAbstractMeshDataInfo._layerMask = value; - this._resyncLightSources(); - } - /** - * Gets or sets a collision mask used to mask collisions (default is -1). - * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 - */ - get collisionMask() { - return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask; - } - set collisionMask(mask) { - this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask = !isNaN(mask) ? mask : -1; - } - /** - * Gets or sets a collision response flag (default is true). - * when collisionResponse is false, events are still triggered but colliding entity has no response - * This helps creating trigger volume when user wants collision feedback events but not position/velocity - * to respond to the collision. - */ - get collisionResponse() { - return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse; - } - set collisionResponse(response) { - this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse = response; - } - /** - * Gets or sets the current collision group mask (-1 by default). - * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 - */ - get collisionGroup() { - return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup; - } - set collisionGroup(mask) { - this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup = !isNaN(mask) ? mask : -1; - } - /** - * Gets or sets current surrounding meshes (null by default). - * - * By default collision detection is tested against every mesh in the scene. - * It is possible to set surroundingMeshes to a defined list of meshes and then only these specified - * meshes will be tested for the collision. - * - * Note: if set to an empty array no collision will happen when this mesh is moved. - */ - get surroundingMeshes() { - return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes; - } - set surroundingMeshes(meshes) { - this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes = meshes; - } - /** Gets the list of lights affecting that mesh */ - get lightSources() { - return this._lightSources; - } - /** @internal */ - get _positions() { - return null; - } - /** - * Gets or sets a skeleton to apply skinning transformations - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons - */ - set skeleton(value) { - const skeleton = this._internalAbstractMeshDataInfo._skeleton; - if (skeleton && skeleton.needInitialSkinMatrix) { - skeleton._unregisterMeshWithPoseMatrix(this); - } - if (value && value.needInitialSkinMatrix) { - value._registerMeshWithPoseMatrix(this); - } - this._internalAbstractMeshDataInfo._skeleton = value; - if (!this._internalAbstractMeshDataInfo._skeleton) { - this._bonesTransformMatrices = null; - } - this._markSubMeshesAsAttributesDirty(); - } - get skeleton() { - return this._internalAbstractMeshDataInfo._skeleton; - } - // Constructor - /** - * Creates a new AbstractMesh - * @param name defines the name of the mesh - * @param scene defines the hosting scene - */ - constructor(name, scene = null) { - super(name, scene, false); - // Internal data - /** @internal */ - this._internalAbstractMeshDataInfo = new _InternalAbstractMeshDataInfo(); - /** @internal */ - this._waitingMaterialId = null; - /** - * The culling strategy to use to check whether the mesh must be rendered or not. - * This value can be changed at any time and will be used on the next render mesh selection. - * The possible values are : - * - AbstractMesh.CULLINGSTRATEGY_STANDARD - * - AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY - * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION - * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY - * Please read each static variable documentation to get details about the culling process. - * */ - this.cullingStrategy = abstractMesh_AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY; - // Events - /** - * An event triggered when this mesh collides with another one - */ - this.onCollideObservable = new observable_Observable(); - /** - * An event triggered when the collision's position changes - */ - this.onCollisionPositionChangeObservable = new observable_Observable(); - /** - * An event triggered when material is changed - */ - this.onMaterialChangedObservable = new observable_Observable(); - // Properties - /** - * Gets or sets the orientation for POV movement & rotation - */ - this.definedFacingForward = true; - /** @internal */ - this._occlusionQuery = null; - /** @internal */ - this._renderingGroup = null; - /** Gets or sets the alpha index used to sort transparent meshes - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#alpha-index - */ - this.alphaIndex = Number.MAX_VALUE; - /** - * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true - */ - this.isVisible = true; - /** - * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true - */ - this.isPickable = true; - /** - * Gets or sets a boolean indicating if the mesh can be near picked. Default is false - */ - this.isNearPickable = false; - /** - * Gets or sets a boolean indicating if the mesh can be near grabbed. Default is false - */ - this.isNearGrabbable = false; - /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */ - this.showSubMeshesBoundingBox = false; - /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default) - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare - */ - this.isBlocker = false; - /** - * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default) - */ - this.enablePointerMoveEvents = false; - /** Defines color to use when rendering outline */ - this.outlineColor = math_color_Color3.Red(); - /** Define width to use when rendering outline */ - this.outlineWidth = 0.02; - /** Defines color to use when rendering overlay */ - this.overlayColor = math_color_Color3.Red(); - /** Defines alpha to use when rendering overlay */ - this.overlayAlpha = 0.5; - /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */ - this.useOctreeForRenderingSelection = true; - /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */ - this.useOctreeForPicking = true; - /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */ - this.useOctreeForCollisions = true; - /** - * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase) - */ - this.alwaysSelectAsActiveMesh = false; - /** - * Gets or sets a boolean indicating that the bounding info does not need to be kept in sync (for performance reason) - */ - this.doNotSyncBoundingInfo = false; - /** - * Gets or sets the current action manager - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions - */ - this.actionManager = null; - /** - * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5)) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions - */ - this.ellipsoid = new math_vector_Vector3(0.5, 1, 0.5); - /** - * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0)) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions - */ - this.ellipsoidOffset = new math_vector_Vector3(0, 0, 0); - // Edges - /** - * Defines edge width used when edgesRenderer is enabled - * @see https://www.babylonjs-playground.com/#10OJSG#13 - */ - this.edgesWidth = 1; - /** - * Defines edge color used when edgesRenderer is enabled - * @see https://www.babylonjs-playground.com/#10OJSG#13 - */ - this.edgesColor = new math_color_Color4(1, 0, 0, 1); - /** @internal */ - this._edgesRenderer = null; - /** @internal */ - this._masterMesh = null; - this._boundingInfo = null; - this._boundingInfoIsDirty = true; - /** @internal */ - this._renderId = 0; - /** @internal */ - this._intersectionsInProgress = new Array(); - /** @internal */ - this._unIndexed = false; - /** @internal */ - this._lightSources = new Array(); - // Loading properties - /** @internal */ - this._waitingData = { - lods: null, - actions: null, - freezeWorldMatrix: null, - }; - /** @internal */ - this._bonesTransformMatrices = null; - /** @internal */ - this._transformMatrixTexture = null; - /** - * An event triggered when the mesh is rebuilt. - */ - this.onRebuildObservable = new observable_Observable(); - this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => { - newPosition.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions); - if (this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length() > engine_Engine.CollisionsEpsilon) { - this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions); - } - if (collidedMesh) { - this.onCollideObservable.notifyObservers(collidedMesh); - } - this.onCollisionPositionChangeObservable.notifyObservers(this.position); - }; - scene = this.getScene(); - scene.addMesh(this); - this._resyncLightSources(); - // Mesh Uniform Buffer. - this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name, !this.getScene().getEngine().isWebGPU); - this._buildUniformLayout(); - switch (scene.performancePriority) { - case ScenePerformancePriority.Aggressive: - this.doNotSyncBoundingInfo = true; - // eslint-disable-next-line no-fallthrough - case ScenePerformancePriority.Intermediate: - this.alwaysSelectAsActiveMesh = true; - this.isPickable = false; - break; - } - } - _buildUniformLayout() { - this._uniformBuffer.addUniform("world", 16); - this._uniformBuffer.addUniform("visibility", 1); - this._uniformBuffer.create(); - } - /** - * Transfer the mesh values to its UBO. - * @param world The world matrix associated with the mesh - */ - transferToEffect(world) { - const ubo = this._uniformBuffer; - ubo.updateMatrix("world", world); - ubo.updateFloat("visibility", this._internalAbstractMeshDataInfo._visibility); - ubo.update(); - } - /** - * Gets the mesh uniform buffer. - * @returns the uniform buffer of the mesh. - */ - getMeshUniformBuffer() { - return this._uniformBuffer; - } - /** - * Returns the string "AbstractMesh" - * @returns "AbstractMesh" - */ - getClassName() { - return "AbstractMesh"; - } - /** - * Gets a string representation of the current mesh - * @param fullDetails defines a boolean indicating if full details must be included - * @returns a string representation of the current mesh - */ - toString(fullDetails) { - let ret = "Name: " + this.name + ", isInstance: " + (this.getClassName() !== "InstancedMesh" ? "YES" : "NO"); - ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0); - const skeleton = this._internalAbstractMeshDataInfo._skeleton; - if (skeleton) { - ret += ", skeleton: " + skeleton.name; - } - if (fullDetails) { - ret += ", billboard mode: " + ["NONE", "X", "Y", null, "Z", null, null, "ALL"][this.billboardMode]; - ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingData.freezeWorldMatrix ? "YES" : "NO"); - } - return ret; - } - /** - * @internal - */ - _getEffectiveParent() { - if (this._masterMesh && this.billboardMode !== transformNode_TransformNode.BILLBOARDMODE_NONE) { - return this._masterMesh; - } - return super._getEffectiveParent(); - } - /** - * @internal - */ - _getActionManagerForTrigger(trigger, initialCall = true) { - if (this.actionManager && (initialCall || this.actionManager.isRecursive)) { - if (trigger) { - if (this.actionManager.hasSpecificTrigger(trigger)) { - return this.actionManager; - } - } - else { - return this.actionManager; - } - } - if (!this.parent) { - return null; - } - return this.parent._getActionManagerForTrigger(trigger, false); - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _rebuild(dispose = false) { - this.onRebuildObservable.notifyObservers(this); - if (this._occlusionQuery !== null) { - this._occlusionQuery = null; - } - if (!this.subMeshes) { - return; - } - for (const subMesh of this.subMeshes) { - subMesh._rebuild(); - } - } - /** @internal */ - _resyncLightSources() { - this._lightSources.length = 0; - for (const light of this.getScene().lights) { - if (!light.isEnabled()) { - continue; - } - if (light.canAffectMesh(this)) { - this._lightSources.push(light); - } - } - this._markSubMeshesAsLightDirty(); - } - /** - * @internal - */ - _resyncLightSource(light) { - const isIn = light.isEnabled() && light.canAffectMesh(this); - const index = this._lightSources.indexOf(light); - let removed = false; - if (index === -1) { - if (!isIn) { - return; - } - this._lightSources.push(light); - } - else { - if (isIn) { - return; - } - removed = true; - this._lightSources.splice(index, 1); - } - this._markSubMeshesAsLightDirty(removed); - } - /** @internal */ - _unBindEffect() { - for (const subMesh of this.subMeshes) { - subMesh.setEffect(null); - } - } - /** - * @internal - */ - _removeLightSource(light, dispose) { - const index = this._lightSources.indexOf(light); - if (index === -1) { - return; - } - this._lightSources.splice(index, 1); - this._markSubMeshesAsLightDirty(dispose); - } - _markSubMeshesAsDirty(func) { - if (!this.subMeshes) { - return; - } - for (const subMesh of this.subMeshes) { - for (let i = 0; i < subMesh._drawWrappers.length; ++i) { - const drawWrapper = subMesh._drawWrappers[i]; - if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) { - continue; - } - func(drawWrapper.defines); - } - } - } - /** - * @internal - */ - _markSubMeshesAsLightDirty(dispose = false) { - this._markSubMeshesAsDirty((defines) => defines.markAsLightDirty(dispose)); - } - /** @internal */ - _markSubMeshesAsAttributesDirty() { - this._markSubMeshesAsDirty((defines) => defines.markAsAttributesDirty()); - } - /** @internal */ - _markSubMeshesAsMiscDirty() { - this._markSubMeshesAsDirty((defines) => defines.markAsMiscDirty()); - } - /** - * Flag the AbstractMesh as dirty (Forcing it to update everything) - * @param property if set to "rotation" the objects rotationQuaternion will be set to null - * @returns this AbstractMesh - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - markAsDirty(property) { - this._currentRenderId = Number.MAX_VALUE; - this._isDirty = true; - return this; - } - /** - * Resets the draw wrappers cache for all submeshes of this abstract mesh - * @param passId If provided, releases only the draw wrapper corresponding to this render pass id - */ - resetDrawCache(passId) { - if (!this.subMeshes) { - return; - } - for (const subMesh of this.subMeshes) { - subMesh.resetDrawCache(passId); - } - } - // Methods - /** - * Returns true if the mesh is blocked. Implemented by child classes - */ - get isBlocked() { - return false; - } - /** - * Returns the mesh itself by default. Implemented by child classes - * @param camera defines the camera to use to pick the right LOD level - * @returns the currentAbstractMesh - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getLOD(camera) { - return this; - } - /** - * Returns 0 by default. Implemented by child classes - * @returns an integer - */ - getTotalVertices() { - return 0; - } - /** - * Returns a positive integer : the total number of indices in this mesh geometry. - * @returns the number of indices or zero if the mesh has no geometry. - */ - getTotalIndices() { - return 0; - } - /** - * Returns null by default. Implemented by child classes - * @returns null - */ - getIndices() { - return null; - } - /** - * Returns the array of the requested vertex data kind. Implemented by child classes - * @param kind defines the vertex data kind to use - * @returns null - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getVerticesData(kind) { - return null; - } - /** - * Sets the vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. - * Note that a new underlying VertexBuffer object is created each call. - * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. - * @param kind defines vertex data kind: - * * VertexBuffer.PositionKind - * * VertexBuffer.UVKind - * * VertexBuffer.UV2Kind - * * VertexBuffer.UV3Kind - * * VertexBuffer.UV4Kind - * * VertexBuffer.UV5Kind - * * VertexBuffer.UV6Kind - * * VertexBuffer.ColorKind - * * VertexBuffer.MatricesIndicesKind - * * VertexBuffer.MatricesIndicesExtraKind - * * VertexBuffer.MatricesWeightsKind - * * VertexBuffer.MatricesWeightsExtraKind - * @param data defines the data source - * @param updatable defines if the data must be flagged as updatable (or static) - * @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 - * @returns the current mesh - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - setVerticesData(kind, data, updatable, stride) { - return this; - } - /** - * Updates the existing vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, it is simply returned as it is. - * @param kind defines vertex data kind: - * * VertexBuffer.PositionKind - * * VertexBuffer.UVKind - * * VertexBuffer.UV2Kind - * * VertexBuffer.UV3Kind - * * VertexBuffer.UV4Kind - * * VertexBuffer.UV5Kind - * * VertexBuffer.UV6Kind - * * VertexBuffer.ColorKind - * * VertexBuffer.MatricesIndicesKind - * * VertexBuffer.MatricesIndicesExtraKind - * * VertexBuffer.MatricesWeightsKind - * * VertexBuffer.MatricesWeightsExtraKind - * @param data defines the data source - * @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 - * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh - * @returns the current mesh - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - updateVerticesData(kind, data, updateExtends, makeItUnique) { - return this; - } - /** - * Sets the mesh indices, - * If the mesh has no geometry, a new Geometry object is created and set to the mesh. - * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) - * @param totalVertices Defines the total number of vertices - * @returns the current mesh - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - setIndices(indices, totalVertices) { - return this; - } - /** - * Gets a boolean indicating if specific vertex data is present - * @param kind defines the vertex data kind to use - * @returns true is data kind is present - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - isVerticesDataPresent(kind) { - return false; - } - /** - * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined. - * Note that it returns a shallow bounding of the mesh (i.e. it does not include children). - * 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()`. - * To get the full bounding of all children, call `getHierarchyBoundingVectors` instead. - * @returns a BoundingInfo - */ - getBoundingInfo() { - if (this._masterMesh) { - return this._masterMesh.getBoundingInfo(); - } - if (this._boundingInfoIsDirty) { - this._boundingInfoIsDirty = false; - // this._boundingInfo is being created if undefined - this._updateBoundingInfo(); - } - // cannot be null. - return this._boundingInfo; - } - /** - * Returns the bounding info unnafected by instance data. - * @returns the bounding info of the mesh unaffected by instance data. - */ - getRawBoundingInfo() { - var _a; - return (_a = this.rawBoundingInfo) !== null && _a !== void 0 ? _a : this.getBoundingInfo(); - } - /** - * Overwrite the current bounding info - * @param boundingInfo defines the new bounding info - * @returns the current mesh - */ - setBoundingInfo(boundingInfo) { - this._boundingInfo = boundingInfo; - return this; - } - /** - * Returns true if there is already a bounding info - */ - get hasBoundingInfo() { - return this._boundingInfo !== null; - } - /** - * Creates a new bounding info for the mesh - * @param minimum min vector of the bounding box/sphere - * @param maximum max vector of the bounding box/sphere - * @param worldMatrix defines the new world matrix - * @returns the new bounding info - */ - buildBoundingInfo(minimum, maximum, worldMatrix) { - this._boundingInfo = new boundingInfo_BoundingInfo(minimum, maximum, worldMatrix); - return this._boundingInfo; - } - /** - * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) - * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false - * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false - * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling - * @returns the current mesh - */ - normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) { - return super.normalizeToUnitCube(includeDescendants, ignoreRotation, predicate); - } - /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */ - get useBones() { - return ((this.skeleton && - this.getScene().skeletonsEnabled && - this.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesKind) && - this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind))); - } - /** @internal */ - _preActivate() { } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _preActivateForIntermediateRendering(renderId) { } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _activate(renderId, intermediateRendering) { - this._renderId = renderId; - return true; - } - /** @internal */ - _postActivate() { - // Do nothing - } - /** @internal */ - _freeze() { - // Do nothing - } - /** @internal */ - _unFreeze() { - // Do nothing - } - /** - * Gets the current world matrix - * @returns a Matrix - */ - getWorldMatrix() { - if (this._masterMesh && this.billboardMode === transformNode_TransformNode.BILLBOARDMODE_NONE) { - return this._masterMesh.getWorldMatrix(); - } - return super.getWorldMatrix(); - } - /** @internal */ - _getWorldMatrixDeterminant() { - if (this._masterMesh) { - return this._masterMesh._getWorldMatrixDeterminant(); - } - return super._getWorldMatrixDeterminant(); - } - /** - * Gets a boolean indicating if this mesh is an instance or a regular mesh - */ - get isAnInstance() { - return false; - } - /** - * Gets a boolean indicating if this mesh has instances - */ - get hasInstances() { - return false; - } - /** - * Gets a boolean indicating if this mesh has thin instances - */ - get hasThinInstances() { - return false; - } - // ================================== Point of View Movement ================================= - /** - * Perform relative position change from the point of view of behind the front of the mesh. - * This is performed taking into account the meshes current rotation, so you do not have to care. - * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. - * @param amountRight defines the distance on the right axis - * @param amountUp defines the distance on the up axis - * @param amountForward defines the distance on the forward axis - * @returns the current mesh - */ - movePOV(amountRight, amountUp, amountForward) { - this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward)); - return this; - } - /** - * Calculate relative position change from the point of view of behind the front of the mesh. - * This is performed taking into account the meshes current rotation, so you do not have to care. - * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. - * @param amountRight defines the distance on the right axis - * @param amountUp defines the distance on the up axis - * @param amountForward defines the distance on the forward axis - * @returns the new displacement vector - */ - calcMovePOV(amountRight, amountUp, amountForward) { - const rotMatrix = new math_vector_Matrix(); - const rotQuaternion = this.rotationQuaternion ? this.rotationQuaternion : math_vector_Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z); - rotQuaternion.toRotationMatrix(rotMatrix); - const translationDelta = math_vector_Vector3.Zero(); - const defForwardMult = this.definedFacingForward ? -1 : 1; - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta); - return translationDelta; - } - // ================================== Point of View Rotation ================================= - /** - * Perform relative rotation change from the point of view of behind the front of the mesh. - * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. - * @param flipBack defines the flip - * @param twirlClockwise defines the twirl - * @param tiltRight defines the tilt - * @returns the current mesh - */ - rotatePOV(flipBack, twirlClockwise, tiltRight) { - this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight)); - return this; - } - /** - * Calculate relative rotation change from the point of view of behind the front of the mesh. - * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. - * @param flipBack defines the flip - * @param twirlClockwise defines the twirl - * @param tiltRight defines the tilt - * @returns the new rotation vector - */ - calcRotatePOV(flipBack, twirlClockwise, tiltRight) { - const defForwardMult = this.definedFacingForward ? 1 : -1; - return new math_vector_Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult); - } - /** - * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked. - * This means the mesh underlying bounding box and sphere are recomputed. - * @param applySkeleton defines whether to apply the skeleton before computing the bounding info - * @param applyMorph defines whether to apply the morph target before computing the bounding info - * @returns the current mesh - */ - refreshBoundingInfo(applySkeleton = false, applyMorph = false) { - if (this._boundingInfo && this._boundingInfo.isLocked) { - return this; - } - this._refreshBoundingInfo(this._getPositionData(applySkeleton, applyMorph), null); - return this; - } - /** - * @internal - */ - _refreshBoundingInfo(data, bias) { - if (data) { - const extend = extractMinAndMax(data, 0, this.getTotalVertices(), bias); - if (this._boundingInfo) { - this._boundingInfo.reConstruct(extend.minimum, extend.maximum); - } - else { - this._boundingInfo = new boundingInfo_BoundingInfo(extend.minimum, extend.maximum); - } - } - if (this.subMeshes) { - for (let index = 0; index < this.subMeshes.length; index++) { - this.subMeshes[index].refreshBoundingInfo(data); - } - } - this._updateBoundingInfo(); - } - /** - * Internal function to get buffer data and possibly apply morphs and normals - * @param applySkeleton - * @param applyMorph - * @param data - * @param kind the kind of data you want. Can be Normal or Position - */ - _getData(applySkeleton = false, applyMorph = false, data, kind = buffer_VertexBuffer.PositionKind) { - data = data !== null && data !== void 0 ? data : this.getVerticesData(kind).slice(); - if (data && applyMorph && this.morphTargetManager) { - let faceIndexCount = 0; - let positionIndex = 0; - for (let vertexCount = 0; vertexCount < data.length; vertexCount++) { - for (let targetCount = 0; targetCount < this.morphTargetManager.numTargets; targetCount++) { - const targetMorph = this.morphTargetManager.getTarget(targetCount); - const influence = targetMorph.influence; - if (influence > 0.0) { - const morphTargetPositions = targetMorph.getPositions(); - if (morphTargetPositions) { - data[vertexCount] += (morphTargetPositions[vertexCount] - data[vertexCount]) * influence; - } - } - } - faceIndexCount++; - if (kind === buffer_VertexBuffer.PositionKind) { - if (this._positions && faceIndexCount === 3) { - // We want to merge into positions every 3 indices starting (but not 0) - faceIndexCount = 0; - const index = positionIndex * 3; - this._positions[positionIndex++].copyFromFloats(data[index], data[index + 1], data[index + 2]); - } - } - } - } - if (data && applySkeleton && this.skeleton) { - const matricesIndicesData = this.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind); - const matricesWeightsData = this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind); - if (matricesWeightsData && matricesIndicesData) { - const needExtras = this.numBoneInfluencers > 4; - const matricesIndicesExtraData = needExtras ? this.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind) : null; - const matricesWeightsExtraData = needExtras ? this.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind) : null; - const skeletonMatrices = this.skeleton.getTransformMatrices(this); - const tempVector = math_vector_TmpVectors.Vector3[0]; - const finalMatrix = math_vector_TmpVectors.Matrix[0]; - const tempMatrix = math_vector_TmpVectors.Matrix[1]; - let matWeightIdx = 0; - for (let index = 0; index < data.length; index += 3, matWeightIdx += 4) { - finalMatrix.reset(); - let inf; - let weight; - for (inf = 0; inf < 4; inf++) { - weight = matricesWeightsData[matWeightIdx + inf]; - if (weight > 0) { - math_vector_Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix); - finalMatrix.addToSelf(tempMatrix); - } - } - if (needExtras) { - for (inf = 0; inf < 4; inf++) { - weight = matricesWeightsExtraData[matWeightIdx + inf]; - if (weight > 0) { - math_vector_Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix); - finalMatrix.addToSelf(tempMatrix); - } - } - } - if (kind === buffer_VertexBuffer.NormalKind) { - math_vector_Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector); - } - else { - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector); - } - tempVector.toArray(data, index); - if (kind === buffer_VertexBuffer.PositionKind && this._positions) { - this._positions[index / 3].copyFrom(tempVector); - } - } - } - } - return data; - } - /** - * Get the normals vertex data and optionally apply skeleton and morphing. - * @param applySkeleton defines whether to apply the skeleton - * @param applyMorph defines whether to apply the morph target - * @returns the normals data - */ - getNormalsData(applySkeleton = false, applyMorph = false) { - return this._getData(applySkeleton, applyMorph, null, buffer_VertexBuffer.NormalKind); - } - /** - * Get the position vertex data and optionally apply skeleton and morphing. - * @param applySkeleton defines whether to apply the skeleton - * @param applyMorph defines whether to apply the morph target - * @param data defines the position data to apply the skeleton and morph to - * @returns the position data - */ - getPositionData(applySkeleton = false, applyMorph = false, data) { - return this._getData(applySkeleton, applyMorph, data, buffer_VertexBuffer.PositionKind); - } - /** - * @internal - */ - _getPositionData(applySkeleton, applyMorph) { - var _a; - let data = this.getVerticesData(buffer_VertexBuffer.PositionKind); - if (this._internalAbstractMeshDataInfo._positions) { - this._internalAbstractMeshDataInfo._positions = null; - } - if (data && ((applySkeleton && this.skeleton) || (applyMorph && this.morphTargetManager))) { - data = data.slice(); - this._generatePointsArray(); - if (this._positions) { - const pos = this._positions; - this._internalAbstractMeshDataInfo._positions = new Array(pos.length); - for (let i = 0; i < pos.length; i++) { - this._internalAbstractMeshDataInfo._positions[i] = ((_a = pos[i]) === null || _a === void 0 ? void 0 : _a.clone()) || new math_vector_Vector3(); - } - } - return this.getPositionData(applySkeleton, applyMorph, data); - } - return data; - } - /** @internal */ - _updateBoundingInfo() { - if (this._boundingInfo) { - this._boundingInfo.update(this.worldMatrixFromCache); - } - else { - this._boundingInfo = new boundingInfo_BoundingInfo(math_vector_Vector3.Zero(), math_vector_Vector3.Zero(), this.worldMatrixFromCache); - } - this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache); - return this; - } - /** - * @internal - */ - _updateSubMeshesBoundingInfo(matrix) { - if (!this.subMeshes) { - return this; - } - const count = this.subMeshes.length; - for (let subIndex = 0; subIndex < count; subIndex++) { - const subMesh = this.subMeshes[subIndex]; - if (count > 1 || !subMesh.IsGlobal) { - subMesh.updateBoundingInfo(matrix); - } - } - return this; - } - /** @internal */ - _afterComputeWorldMatrix() { - if (this.doNotSyncBoundingInfo) { - return; - } - // Bounding info - this._boundingInfoIsDirty = true; - } - /** - * Returns `true` if the mesh is within the frustum defined by the passed array of planes. - * A mesh is in the frustum if its bounding box intersects the frustum - * @param frustumPlanes defines the frustum to test - * @returns true if the mesh is in the frustum planes - */ - isInFrustum(frustumPlanes) { - return this.getBoundingInfo().isInFrustum(frustumPlanes, this.cullingStrategy); - } - /** - * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes. - * A mesh is completely in the frustum if its bounding box it completely inside the frustum. - * @param frustumPlanes defines the frustum to test - * @returns true if the mesh is completely in the frustum planes - */ - isCompletelyInFrustum(frustumPlanes) { - return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes); - } - /** - * True if the mesh intersects another mesh or a SolidParticle object - * @param mesh defines a target mesh or SolidParticle to test - * @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) - * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes - * @returns true if there is an intersection - */ - intersectsMesh(mesh, precise = false, includeDescendants) { - const boundingInfo = this.getBoundingInfo(); - const otherBoundingInfo = mesh.getBoundingInfo(); - if (boundingInfo.intersects(otherBoundingInfo, precise)) { - return true; - } - if (includeDescendants) { - for (const child of this.getChildMeshes()) { - if (child.intersectsMesh(mesh, precise, true)) { - return true; - } - } - } - return false; - } - /** - * Returns true if the passed point (Vector3) is inside the mesh bounding box - * @param point defines the point to test - * @returns true if there is an intersection - */ - intersectsPoint(point) { - return this.getBoundingInfo().intersectsPoint(point); - } - // Collisions - /** - * Gets or sets a boolean indicating that this mesh can be used in the collision engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions - */ - get checkCollisions() { - return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions; - } - set checkCollisions(collisionEnabled) { - this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions = collisionEnabled; - } - /** - * Gets Collider object used to compute collisions (not physics) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions - */ - get collider() { - return this._internalAbstractMeshDataInfo._meshCollisionData._collider; - } - /** - * Move the mesh using collision engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions - * @param displacement defines the requested displacement vector - * @returns the current mesh - */ - moveWithCollisions(displacement) { - const globalPosition = this.getAbsolutePosition(); - globalPosition.addToRef(this.ellipsoidOffset, this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions); - const coordinator = this.getScene().collisionCoordinator; - if (!this._internalAbstractMeshDataInfo._meshCollisionData._collider) { - this._internalAbstractMeshDataInfo._meshCollisionData._collider = coordinator.createCollider(); - } - this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius = this.ellipsoid; - coordinator.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, displacement, this._internalAbstractMeshDataInfo._meshCollisionData._collider, this.collisionRetryCount, this, this._onCollisionPositionChange, this.uniqueId); - return this; - } - // Collisions - /** - * @internal - */ - _collideForSubMesh(subMesh, transformMatrix, collider) { - var _a; - this._generatePointsArray(); - if (!this._positions) { - return this; - } - // Transformation - if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) { - subMesh._lastColliderTransformMatrix = transformMatrix.clone(); - subMesh._lastColliderWorldVertices = []; - subMesh._trianglePlanes = []; - const start = subMesh.verticesStart; - const end = subMesh.verticesStart + subMesh.verticesCount; - for (let i = start; i < end; i++) { - subMesh._lastColliderWorldVertices.push(math_vector_Vector3.TransformCoordinates(this._positions[i], transformMatrix)); - } - } - // Collide - 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); - return this; - } - /** - * @internal - */ - _processCollisionsForSubMeshes(collider, transformMatrix) { - const subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider); - const len = subMeshes.length; - for (let index = 0; index < len; index++) { - const subMesh = subMeshes.data[index]; - // Bounding test - if (len > 1 && !subMesh._checkCollision(collider)) { - continue; - } - this._collideForSubMesh(subMesh, transformMatrix, collider); - } - return this; - } - /** @internal */ - _shouldConvertRHS() { - return false; - } - /** - * @internal - */ - _checkCollision(collider) { - // Bounding box test - if (!this.getBoundingInfo()._checkCollision(collider)) { - return this; - } - // Transformation matrix - const collisionsScalingMatrix = math_vector_TmpVectors.Matrix[0]; - const collisionsTransformMatrix = math_vector_TmpVectors.Matrix[1]; - math_vector_Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix); - this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix); - this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix); - return this; - } - // Picking - /** @internal */ - _generatePointsArray() { - return false; - } - /** - * Checks if the passed Ray intersects with the mesh. A mesh triangle can be picked both from its front and back sides, - * irrespective of orientation. - * @param ray defines the ray to use. It should be in the mesh's LOCAL coordinate space. - * @param fastCheck defines if fast mode (but less precise) must be used (false by default) - * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected - * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default) - * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point - * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check - * @returns the picking info - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect - */ - intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) { - const pickingInfo = new PickingInfo(); - const className = this.getClassName(); - const intersectionThreshold = className === "InstancedLinesMesh" || className === "LinesMesh" || className === "GreasedLineMesh" ? this.intersectionThreshold : 0; - const boundingInfo = this.getBoundingInfo(); - if (!this.subMeshes) { - return pickingInfo; - } - if (!skipBoundingInfo && - (!ray.intersectsSphere(boundingInfo.boundingSphere, intersectionThreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionThreshold))) { - return pickingInfo; - } - if (onlyBoundingInfo) { - pickingInfo.hit = skipBoundingInfo ? false : true; - pickingInfo.pickedMesh = skipBoundingInfo ? null : this; - pickingInfo.distance = skipBoundingInfo ? 0 : math_vector_Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center); - pickingInfo.subMeshId = 0; - return pickingInfo; - } - if (!this._generatePointsArray()) { - return pickingInfo; - } - let intersectInfo = null; - const subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray); - const len = subMeshes.length; - // Check if all submeshes are using a material that don't allow picking (point/lines rendering) - // if no submesh can be picked that way, then fallback to BBox picking - let anySubmeshSupportIntersect = false; - for (let index = 0; index < len; index++) { - const subMesh = subMeshes.data[index]; - const material = subMesh.getMaterial(); - if (!material) { - continue; - } - if (material.fillMode == 7 || - material.fillMode == 0 || - material.fillMode == 1 || - material.fillMode == 2 || - material.fillMode == 4) { - anySubmeshSupportIntersect = true; - break; - } - } - // no sub mesh support intersection, fallback to BBox that has already be done - if (!anySubmeshSupportIntersect) { - pickingInfo.hit = true; - pickingInfo.pickedMesh = this; - pickingInfo.distance = math_vector_Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center); - pickingInfo.subMeshId = -1; - return pickingInfo; - } - // at least 1 submesh supports intersection, keep going - for (let index = 0; index < len; index++) { - const subMesh = subMeshes.data[index]; - // Bounding test - if (len > 1 && !subMesh.canIntersects(ray)) { - continue; - } - const currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck, trianglePredicate); - if (currentIntersectInfo) { - if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { - intersectInfo = currentIntersectInfo; - intersectInfo.subMeshId = index; - if (fastCheck) { - break; - } - } - } - } - if (intersectInfo) { - // Get picked point - const world = worldToUse !== null && worldToUse !== void 0 ? worldToUse : this.getWorldMatrix(); - const worldOrigin = math_vector_TmpVectors.Vector3[0]; - const direction = math_vector_TmpVectors.Vector3[1]; - math_vector_Vector3.TransformCoordinatesToRef(ray.origin, world, worldOrigin); - ray.direction.scaleToRef(intersectInfo.distance, direction); - const worldDirection = math_vector_Vector3.TransformNormal(direction, world); - const pickedPoint = worldDirection.addInPlace(worldOrigin); - // Return result - pickingInfo.hit = true; - pickingInfo.distance = math_vector_Vector3.Distance(worldOrigin, pickedPoint); - pickingInfo.pickedPoint = pickedPoint; - pickingInfo.pickedMesh = this; - pickingInfo.bu = intersectInfo.bu || 0; - pickingInfo.bv = intersectInfo.bv || 0; - pickingInfo.subMeshFaceId = intersectInfo.faceId; - pickingInfo.faceId = intersectInfo.faceId + subMeshes.data[intersectInfo.subMeshId].indexStart / (this.getClassName().indexOf("LinesMesh") !== -1 ? 2 : 3); - pickingInfo.subMeshId = intersectInfo.subMeshId; - return pickingInfo; - } - return pickingInfo; - } - /** - * Clones the current mesh - * @param name defines the mesh name - * @param newParent defines the new mesh parent - * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default) - * @returns the new mesh - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - clone(name, newParent, doNotCloneChildren) { - return null; - } - /** - * Disposes all the submeshes of the current meshnp - * @returns the current mesh - */ - releaseSubMeshes() { - if (this.subMeshes) { - while (this.subMeshes.length) { - this.subMeshes[0].dispose(); - } - } - else { - this.subMeshes = new Array(); - } - return this; - } - /** - * Releases resources associated with this abstract mesh. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) - */ - dispose(doNotRecurse, disposeMaterialAndTextures = false) { - let index; - // mesh map release. - if (this._scene.useMaterialMeshMap) { - // remove from material mesh map id needed - if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) { - this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined; - } - } - // Smart Array Retainers. - this.getScene().freeActiveMeshes(); - this.getScene().freeRenderingGroups(); - // Action manager - if (this.actionManager !== undefined && this.actionManager !== null) { - this.actionManager.dispose(); - this.actionManager = null; - } - // Skeleton - this._internalAbstractMeshDataInfo._skeleton = null; - if (this._transformMatrixTexture) { - this._transformMatrixTexture.dispose(); - this._transformMatrixTexture = null; - } - // Intersections in progress - for (index = 0; index < this._intersectionsInProgress.length; index++) { - const other = this._intersectionsInProgress[index]; - const pos = other._intersectionsInProgress.indexOf(this); - other._intersectionsInProgress.splice(pos, 1); - } - this._intersectionsInProgress.length = 0; - // Lights - const lights = this.getScene().lights; - lights.forEach((light) => { - let meshIndex = light.includedOnlyMeshes.indexOf(this); - if (meshIndex !== -1) { - light.includedOnlyMeshes.splice(meshIndex, 1); - } - meshIndex = light.excludedMeshes.indexOf(this); - if (meshIndex !== -1) { - light.excludedMeshes.splice(meshIndex, 1); - } - // Shadow generators - const generators = light.getShadowGenerators(); - if (generators) { - const iterator = generators.values(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const generator = key.value; - const shadowMap = generator.getShadowMap(); - if (shadowMap && shadowMap.renderList) { - meshIndex = shadowMap.renderList.indexOf(this); - if (meshIndex !== -1) { - shadowMap.renderList.splice(meshIndex, 1); - } - } - } - } - }); - // SubMeshes - if (this.getClassName() !== "InstancedMesh" || this.getClassName() !== "InstancedLinesMesh") { - this.releaseSubMeshes(); - } - // Query - const engine = this.getScene().getEngine(); - if (this._occlusionQuery !== null) { - this.isOcclusionQueryInProgress = false; - engine.deleteQuery(this._occlusionQuery); - this._occlusionQuery = null; - } - // Engine - engine.wipeCaches(); - // Remove from scene - this.getScene().removeMesh(this); - if (this._parentContainer) { - const index = this._parentContainer.meshes.indexOf(this); - if (index > -1) { - this._parentContainer.meshes.splice(index, 1); - } - this._parentContainer = null; - } - if (disposeMaterialAndTextures) { - if (this.material) { - if (this.material.getClassName() === "MultiMaterial") { - this.material.dispose(false, true, true); - } - else { - this.material.dispose(false, true); - } - } - } - if (!doNotRecurse) { - // Particles - for (index = 0; index < this.getScene().particleSystems.length; index++) { - if (this.getScene().particleSystems[index].emitter === this) { - this.getScene().particleSystems[index].dispose(); - index--; - } - } - } - // facet data - if (this._internalAbstractMeshDataInfo._facetData.facetDataEnabled) { - this.disableFacetData(); - } - this._uniformBuffer.dispose(); - this.onAfterWorldMatrixUpdateObservable.clear(); - this.onCollideObservable.clear(); - this.onCollisionPositionChangeObservable.clear(); - this.onRebuildObservable.clear(); - super.dispose(doNotRecurse, disposeMaterialAndTextures); - } - /** - * Adds the passed mesh as a child to the current mesh - * @param mesh defines the child mesh - * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change. - * @returns the current mesh - */ - addChild(mesh, preserveScalingSign = false) { - mesh.setParent(this, preserveScalingSign); - return this; - } - /** - * Removes the passed mesh from the current mesh children list - * @param mesh defines the child mesh - * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change. - * @returns the current mesh - */ - removeChild(mesh, preserveScalingSign = false) { - mesh.setParent(null, preserveScalingSign); - return this; - } - // Facet data - /** @internal */ - _initFacetData() { - const data = this._internalAbstractMeshDataInfo._facetData; - if (!data.facetNormals) { - data.facetNormals = new Array(); - } - if (!data.facetPositions) { - data.facetPositions = new Array(); - } - if (!data.facetPartitioning) { - data.facetPartitioning = new Array(); - } - data.facetNb = (this.getIndices().length / 3) | 0; - data.partitioningSubdivisions = data.partitioningSubdivisions ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10 - data.partitioningBBoxRatio = data.partitioningBBoxRatio ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box - for (let f = 0; f < data.facetNb; f++) { - data.facetNormals[f] = math_vector_Vector3.Zero(); - data.facetPositions[f] = math_vector_Vector3.Zero(); - } - data.facetDataEnabled = true; - return this; - } - /** - * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated. - * This method can be called within the render loop. - * 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 - * @returns the current mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - updateFacetData() { - const data = this._internalAbstractMeshDataInfo._facetData; - if (!data.facetDataEnabled) { - this._initFacetData(); - } - const positions = this.getVerticesData(buffer_VertexBuffer.PositionKind); - const indices = this.getIndices(); - const normals = this.getVerticesData(buffer_VertexBuffer.NormalKind); - const bInfo = this.getBoundingInfo(); - if (data.facetDepthSort && !data.facetDepthSortEnabled) { - // init arrays, matrix and sort function on first call - data.facetDepthSortEnabled = true; - if (indices instanceof Uint16Array) { - data.depthSortedIndices = new Uint16Array(indices); - } - else if (indices instanceof Uint32Array) { - data.depthSortedIndices = new Uint32Array(indices); - } - else { - let needs32bits = false; - for (let i = 0; i < indices.length; i++) { - if (indices[i] > 65535) { - needs32bits = true; - break; - } - } - if (needs32bits) { - data.depthSortedIndices = new Uint32Array(indices); - } - else { - data.depthSortedIndices = new Uint16Array(indices); - } - } - data.facetDepthSortFunction = function (f1, f2) { - return f2.sqDistance - f1.sqDistance; - }; - if (!data.facetDepthSortFrom) { - const camera = this.getScene().activeCamera; - data.facetDepthSortFrom = camera ? camera.position : math_vector_Vector3.Zero(); - } - data.depthSortedFacets = []; - for (let f = 0; f < data.facetNb; f++) { - const depthSortedFacet = { ind: f * 3, sqDistance: 0.0 }; - data.depthSortedFacets.push(depthSortedFacet); - } - data.invertedMatrix = math_vector_Matrix.Identity(); - data.facetDepthSortOrigin = math_vector_Vector3.Zero(); - } - data.bbSize.x = bInfo.maximum.x - bInfo.minimum.x > math_constants_Epsilon ? bInfo.maximum.x - bInfo.minimum.x : math_constants_Epsilon; - data.bbSize.y = bInfo.maximum.y - bInfo.minimum.y > math_constants_Epsilon ? bInfo.maximum.y - bInfo.minimum.y : math_constants_Epsilon; - data.bbSize.z = bInfo.maximum.z - bInfo.minimum.z > math_constants_Epsilon ? bInfo.maximum.z - bInfo.minimum.z : math_constants_Epsilon; - let bbSizeMax = data.bbSize.x > data.bbSize.y ? data.bbSize.x : data.bbSize.y; - bbSizeMax = bbSizeMax > data.bbSize.z ? bbSizeMax : data.bbSize.z; - data.subDiv.max = data.partitioningSubdivisions; - data.subDiv.X = Math.floor((data.subDiv.max * data.bbSize.x) / bbSizeMax); // adjust the number of subdivisions per axis - data.subDiv.Y = Math.floor((data.subDiv.max * data.bbSize.y) / bbSizeMax); // according to each bbox size per axis - data.subDiv.Z = Math.floor((data.subDiv.max * data.bbSize.z) / bbSizeMax); - data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision - data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y; - data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z; - // set the parameters for ComputeNormals() - data.facetParameters.facetNormals = this.getFacetLocalNormals(); - data.facetParameters.facetPositions = this.getFacetLocalPositions(); - data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning(); - data.facetParameters.bInfo = bInfo; - data.facetParameters.bbSize = data.bbSize; - data.facetParameters.subDiv = data.subDiv; - data.facetParameters.ratio = this.partitioningBBoxRatio; - data.facetParameters.depthSort = data.facetDepthSort; - if (data.facetDepthSort && data.facetDepthSortEnabled) { - this.computeWorldMatrix(true); - this._worldMatrix.invertToRef(data.invertedMatrix); - math_vector_Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin); - data.facetParameters.distanceTo = data.facetDepthSortOrigin; - } - data.facetParameters.depthSortedFacets = data.depthSortedFacets; - if (normals) { - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals, data.facetParameters); - } - if (data.facetDepthSort && data.facetDepthSortEnabled) { - data.depthSortedFacets.sort(data.facetDepthSortFunction); - const l = (data.depthSortedIndices.length / 3) | 0; - for (let f = 0; f < l; f++) { - const sind = data.depthSortedFacets[f].ind; - data.depthSortedIndices[f * 3] = indices[sind]; - data.depthSortedIndices[f * 3 + 1] = indices[sind + 1]; - data.depthSortedIndices[f * 3 + 2] = indices[sind + 2]; - } - this.updateIndices(data.depthSortedIndices, undefined, true); - } - return this; - } - /** - * Returns the facetLocalNormals array. - * The normals are expressed in the mesh local spac - * @returns an array of Vector3 - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getFacetLocalNormals() { - const facetData = this._internalAbstractMeshDataInfo._facetData; - if (!facetData.facetNormals) { - this.updateFacetData(); - } - return facetData.facetNormals; - } - /** - * Returns the facetLocalPositions array. - * The facet positions are expressed in the mesh local space - * @returns an array of Vector3 - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getFacetLocalPositions() { - const facetData = this._internalAbstractMeshDataInfo._facetData; - if (!facetData.facetPositions) { - this.updateFacetData(); - } - return facetData.facetPositions; - } - /** - * Returns the facetLocalPartitioning array - * @returns an array of array of numbers - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getFacetLocalPartitioning() { - const facetData = this._internalAbstractMeshDataInfo._facetData; - if (!facetData.facetPartitioning) { - this.updateFacetData(); - } - return facetData.facetPartitioning; - } - /** - * Returns the i-th facet position in the world system. - * This method allocates a new Vector3 per call - * @param i defines the facet index - * @returns a new Vector3 - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getFacetPosition(i) { - const pos = math_vector_Vector3.Zero(); - this.getFacetPositionToRef(i, pos); - return pos; - } - /** - * Sets the reference Vector3 with the i-th facet position in the world system - * @param i defines the facet index - * @param ref defines the target vector - * @returns the current mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getFacetPositionToRef(i, ref) { - const localPos = this.getFacetLocalPositions()[i]; - const world = this.getWorldMatrix(); - math_vector_Vector3.TransformCoordinatesToRef(localPos, world, ref); - return this; - } - /** - * Returns the i-th facet normal in the world system. - * This method allocates a new Vector3 per call - * @param i defines the facet index - * @returns a new Vector3 - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getFacetNormal(i) { - const norm = math_vector_Vector3.Zero(); - this.getFacetNormalToRef(i, norm); - return norm; - } - /** - * Sets the reference Vector3 with the i-th facet normal in the world system - * @param i defines the facet index - * @param ref defines the target vector - * @returns the current mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getFacetNormalToRef(i, ref) { - const localNorm = this.getFacetLocalNormals()[i]; - math_vector_Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref); - return this; - } - /** - * 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) - * @param x defines x coordinate - * @param y defines y coordinate - * @param z defines z coordinate - * @returns the array of facet indexes - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getFacetsAtLocalCoordinates(x, y, z) { - const bInfo = this.getBoundingInfo(); - const data = this._internalAbstractMeshDataInfo._facetData; - const ox = Math.floor(((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio) / data.bbSize.x); - const oy = Math.floor(((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio) / data.bbSize.y); - const oz = Math.floor(((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio) / data.bbSize.z); - if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) { - return null; - } - return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz]; - } - /** - * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found - * @param x defines x coordinate - * @param y defines y coordinate - * @param z defines z coordinate - * @param projected sets as the (x,y,z) world projection on the facet - * @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 - * @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 - * @returns the face index if found (or null instead) - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getClosestFacetAtCoordinates(x, y, z, projected, checkFace = false, facing = true) { - const world = this.getWorldMatrix(); - const invMat = math_vector_TmpVectors.Matrix[5]; - world.invertToRef(invMat); - const invVect = math_vector_TmpVectors.Vector3[8]; - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space - const closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing); - if (projected) { - // transform the local computed projected vector to world coordinates - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected); - } - return closest; - } - /** - * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found - * @param x defines x coordinate - * @param y defines y coordinate - * @param z defines z coordinate - * @param projected sets as the (x,y,z) local projection on the facet - * @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 - * @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 - * @returns the face index if found (or null instead) - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getClosestFacetAtLocalCoordinates(x, y, z, projected, checkFace = false, facing = true) { - let closest = null; - let tmpx = 0.0; - let tmpy = 0.0; - let tmpz = 0.0; - let d = 0.0; // tmp dot facet normal * facet position - let t0 = 0.0; - let projx = 0.0; - let projy = 0.0; - let projz = 0.0; - // Get all the facets in the same partitioning block than (x, y, z) - const facetPositions = this.getFacetLocalPositions(); - const facetNormals = this.getFacetLocalNormals(); - const facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z); - if (!facetsInBlock) { - return null; - } - // Get the closest facet to (x, y, z) - let shortest = Number.MAX_VALUE; // init distance vars - let tmpDistance = shortest; - let fib; // current facet in the block - let norm; // current facet normal - let p0; // current facet barycenter position - // loop on all the facets in the current partitioning block - for (let idx = 0; idx < facetsInBlock.length; idx++) { - fib = facetsInBlock[idx]; - norm = facetNormals[fib]; - p0 = facetPositions[fib]; - d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z; - if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) { - // compute (x,y,z) projection on the facet = (projx, projy, projz) - d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z; - t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z); - projx = x + norm.x * t0; - projy = y + norm.y * t0; - projz = z + norm.z * t0; - tmpx = projx - x; - tmpy = projy - y; - tmpz = projz - z; - tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet - if (tmpDistance < shortest) { - // just keep the closest facet to (x, y, z) - shortest = tmpDistance; - closest = fib; - if (projected) { - projected.x = projx; - projected.y = projy; - projected.z = projz; - } - } - } - } - return closest; - } - /** - * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals() - * @returns the parameters - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - getFacetDataParameters() { - return this._internalAbstractMeshDataInfo._facetData.facetParameters; - } - /** - * Disables the feature FacetData and frees the related memory - * @returns the current mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData - */ - disableFacetData() { - const facetData = this._internalAbstractMeshDataInfo._facetData; - if (facetData.facetDataEnabled) { - facetData.facetDataEnabled = false; - facetData.facetPositions = new Array(); - facetData.facetNormals = new Array(); - facetData.facetPartitioning = new Array(); - facetData.facetParameters = null; - facetData.depthSortedIndices = new Uint32Array(0); - } - return this; - } - /** - * Updates the AbstractMesh indices array - * @param indices defines the data source - * @param offset defines the offset in the index buffer where to store the new data (can be null) - * @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) - * @returns the current mesh - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - updateIndices(indices, offset, gpuMemoryOnly = false) { - return this; - } - /** - * Creates new normals data for the mesh - * @param updatable defines if the normal vertex buffer must be flagged as updatable - * @returns the current mesh - */ - createNormals(updatable) { - const positions = this.getVerticesData(buffer_VertexBuffer.PositionKind); - const indices = this.getIndices(); - let normals; - if (this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)) { - normals = this.getVerticesData(buffer_VertexBuffer.NormalKind); - } - else { - normals = []; - } - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem }); - this.setVerticesData(buffer_VertexBuffer.NormalKind, normals, updatable); - return this; - } - /** - * Align the mesh with a normal - * @param normal defines the normal to use - * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default) - * @returns the current mesh - */ - alignWithNormal(normal, upDirection) { - if (!upDirection) { - upDirection = math_axis_Axis.Y; - } - const axisX = math_vector_TmpVectors.Vector3[0]; - const axisZ = math_vector_TmpVectors.Vector3[1]; - math_vector_Vector3.CrossToRef(upDirection, normal, axisZ); - math_vector_Vector3.CrossToRef(normal, axisZ, axisX); - if (this.rotationQuaternion) { - math_vector_Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion); - } - else { - math_vector_Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation); - } - return this; - } - /** @internal */ - _checkOcclusionQuery() { - // Will be replaced by correct code if Occlusion queries are referenced - return false; - } - /** - * Disables the mesh edge rendering mode - * @returns the currentAbstractMesh - */ - disableEdgesRendering() { - throw _WarnImport("EdgesRenderer"); - } - /** - * Enables the edge rendering mode on the mesh. - * This mode makes the mesh edges visible - * @param epsilon defines the maximal distance between two angles to detect a face - * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces - * @param options options to the edge renderer - * @returns the currentAbstractMesh - * @see https://www.babylonjs-playground.com/#19O9TU#0 - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - enableEdgesRendering(epsilon, checkVerticesInsteadOfIndices, options) { - throw _WarnImport("EdgesRenderer"); - } - /** - * This function returns all of the particle systems in the scene that use the mesh as an emitter. - * @returns an array of particle systems in the scene that use the mesh as an emitter - */ - getConnectedParticleSystems() { - return this._scene.particleSystems.filter((particleSystem) => particleSystem.emitter === this); - } -} -/** No occlusion */ -abstractMesh_AbstractMesh.OCCLUSION_TYPE_NONE = 0; -/** Occlusion set to optimistic */ -abstractMesh_AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1; -/** Occlusion set to strict */ -abstractMesh_AbstractMesh.OCCLUSION_TYPE_STRICT = 2; -/** Use an accurate occlusion algorithm */ -abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0; -/** Use a conservative occlusion algorithm */ -abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1; -/** Default culling strategy : this is an exclusion test and it's the more accurate. - * Test order : - * Is the bounding sphere outside the frustum ? - * If not, are the bounding box vertices outside the frustum ? - * It not, then the cullable object is in the frustum. - */ -abstractMesh_AbstractMesh.CULLINGSTRATEGY_STANDARD = 0; -/** Culling strategy : Bounding Sphere Only. - * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested. - * It's also less accurate than the standard because some not visible objects can still be selected. - * Test : is the bounding sphere outside the frustum ? - * If not, then the cullable object is in the frustum. - */ -abstractMesh_AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1; -/** Culling strategy : Optimistic Inclusion. - * This in an inclusion test first, then the standard exclusion test. - * This can be faster when a cullable object is expected to be almost always in the camera frustum. - * 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. - * Anyway, it's as accurate as the standard strategy. - * Test : - * Is the cullable object bounding sphere center in the frustum ? - * If not, apply the default culling strategy. - */ -abstractMesh_AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2; -/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only. - * This in an inclusion test first, then the bounding sphere only exclusion test. - * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum. - * 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. - * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy. - * Test : - * Is the cullable object bounding sphere center in the frustum ? - * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here. - */ -abstractMesh_AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3; -RegisterClass("BABYLON.AbstractMesh", abstractMesh_AbstractMesh); -//# sourceMappingURL=abstractMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/clipPlaneMaterialHelper.js -/** @internal */ -function addClipPlaneUniforms(uniforms) { - if (uniforms.indexOf("vClipPlane") === -1) { - uniforms.push("vClipPlane"); - } - if (uniforms.indexOf("vClipPlane2") === -1) { - uniforms.push("vClipPlane2"); - } - if (uniforms.indexOf("vClipPlane3") === -1) { - uniforms.push("vClipPlane3"); - } - if (uniforms.indexOf("vClipPlane4") === -1) { - uniforms.push("vClipPlane4"); - } - if (uniforms.indexOf("vClipPlane5") === -1) { - uniforms.push("vClipPlane5"); - } - if (uniforms.indexOf("vClipPlane6") === -1) { - uniforms.push("vClipPlane6"); - } -} -/** @internal */ -function prepareStringDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) { - var _a, _b, _c, _d, _e, _f; - const clipPlane = !!((_a = primaryHolder.clipPlane) !== null && _a !== void 0 ? _a : secondaryHolder.clipPlane); - const clipPlane2 = !!((_b = primaryHolder.clipPlane2) !== null && _b !== void 0 ? _b : secondaryHolder.clipPlane2); - const clipPlane3 = !!((_c = primaryHolder.clipPlane3) !== null && _c !== void 0 ? _c : secondaryHolder.clipPlane3); - const clipPlane4 = !!((_d = primaryHolder.clipPlane4) !== null && _d !== void 0 ? _d : secondaryHolder.clipPlane4); - const clipPlane5 = !!((_e = primaryHolder.clipPlane5) !== null && _e !== void 0 ? _e : secondaryHolder.clipPlane5); - const clipPlane6 = !!((_f = primaryHolder.clipPlane6) !== null && _f !== void 0 ? _f : secondaryHolder.clipPlane6); - if (clipPlane) - defines.push("#define CLIPPLANE"); - if (clipPlane2) - defines.push("#define CLIPPLANE2"); - if (clipPlane3) - defines.push("#define CLIPPLANE3"); - if (clipPlane4) - defines.push("#define CLIPPLANE4"); - if (clipPlane5) - defines.push("#define CLIPPLANE5"); - if (clipPlane6) - defines.push("#define CLIPPLANE6"); -} -/** @internal */ -function prepareDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) { - var _a, _b, _c, _d, _e, _f; - let changed = false; - const clipPlane = !!((_a = primaryHolder.clipPlane) !== null && _a !== void 0 ? _a : secondaryHolder.clipPlane); - const clipPlane2 = !!((_b = primaryHolder.clipPlane2) !== null && _b !== void 0 ? _b : secondaryHolder.clipPlane2); - const clipPlane3 = !!((_c = primaryHolder.clipPlane3) !== null && _c !== void 0 ? _c : secondaryHolder.clipPlane3); - const clipPlane4 = !!((_d = primaryHolder.clipPlane4) !== null && _d !== void 0 ? _d : secondaryHolder.clipPlane4); - const clipPlane5 = !!((_e = primaryHolder.clipPlane5) !== null && _e !== void 0 ? _e : secondaryHolder.clipPlane5); - const clipPlane6 = !!((_f = primaryHolder.clipPlane6) !== null && _f !== void 0 ? _f : secondaryHolder.clipPlane6); - // Do not factorize this code, it breaks browsers optimizations. - if (defines["CLIPPLANE"] !== clipPlane) { - defines["CLIPPLANE"] = clipPlane; - changed = true; - } - if (defines["CLIPPLANE2"] !== clipPlane2) { - defines["CLIPPLANE2"] = clipPlane2; - changed = true; - } - if (defines["CLIPPLANE3"] !== clipPlane3) { - defines["CLIPPLANE3"] = clipPlane3; - changed = true; - } - if (defines["CLIPPLANE4"] !== clipPlane4) { - defines["CLIPPLANE4"] = clipPlane4; - changed = true; - } - if (defines["CLIPPLANE5"] !== clipPlane5) { - defines["CLIPPLANE5"] = clipPlane5; - changed = true; - } - if (defines["CLIPPLANE6"] !== clipPlane6) { - defines["CLIPPLANE6"] = clipPlane6; - changed = true; - } - return changed; -} -/** @internal */ -function bindClipPlane(effect, primaryHolder, secondaryHolder) { - var _a, _b, _c, _d, _e, _f; - let clipPlane = (_a = primaryHolder.clipPlane) !== null && _a !== void 0 ? _a : secondaryHolder.clipPlane; - setClipPlane(effect, "vClipPlane", clipPlane); - clipPlane = (_b = primaryHolder.clipPlane2) !== null && _b !== void 0 ? _b : secondaryHolder.clipPlane2; - setClipPlane(effect, "vClipPlane2", clipPlane); - clipPlane = (_c = primaryHolder.clipPlane3) !== null && _c !== void 0 ? _c : secondaryHolder.clipPlane3; - setClipPlane(effect, "vClipPlane3", clipPlane); - clipPlane = (_d = primaryHolder.clipPlane4) !== null && _d !== void 0 ? _d : secondaryHolder.clipPlane4; - setClipPlane(effect, "vClipPlane4", clipPlane); - clipPlane = (_e = primaryHolder.clipPlane5) !== null && _e !== void 0 ? _e : secondaryHolder.clipPlane5; - setClipPlane(effect, "vClipPlane5", clipPlane); - clipPlane = (_f = primaryHolder.clipPlane6) !== null && _f !== void 0 ? _f : secondaryHolder.clipPlane6; - setClipPlane(effect, "vClipPlane6", clipPlane); -} -function setClipPlane(effect, uniformName, clipPlane) { - if (clipPlane) { - effect.setFloat4(uniformName, clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); - } -} -//# sourceMappingURL=clipPlaneMaterialHelper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/materialHelper.js - - - - - - - - - -/** - * "Static Class" containing the most commonly used helper while dealing with material for rendering purpose. - * - * It contains the basic tools to help defining defines, binding uniform for the common part of the materials. - * - * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions. - */ -class MaterialHelper { - /** - * Binds the scene's uniform buffer to the effect. - * @param effect defines the effect to bind to the scene uniform buffer - * @param sceneUbo defines the uniform buffer storing scene data - */ - static BindSceneUniformBuffer(effect, sceneUbo) { - sceneUbo.bindToEffect(effect, "Scene"); - } - /** - * Helps preparing the defines values about the UVs in used in the effect. - * UVs are shared as much as we can across channels in the shaders. - * @param texture The texture we are preparing the UVs for - * @param defines The defines to update - * @param key The channel key "diffuse", "specular"... used in the shader - */ - static PrepareDefinesForMergedUV(texture, defines, key) { - defines._needUVs = true; - defines[key] = true; - if (texture.optimizeUVAllocation && texture.getTextureMatrix().isIdentityAs3x2()) { - defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1; - defines["MAINUV" + (texture.coordinatesIndex + 1)] = true; - } - else { - defines[key + "DIRECTUV"] = 0; - } - } - /** - * Binds a texture matrix value to its corresponding uniform - * @param texture The texture to bind the matrix for - * @param uniformBuffer The uniform buffer receiving the data - * @param key The channel key "diffuse", "specular"... used in the shader - */ - static BindTextureMatrix(texture, uniformBuffer, key) { - const matrix = texture.getTextureMatrix(); - uniformBuffer.updateMatrix(key + "Matrix", matrix); - } - /** - * Gets the current status of the fog (should it be enabled?) - * @param mesh defines the mesh to evaluate for fog support - * @param scene defines the hosting scene - * @returns true if fog must be enabled - */ - static GetFogState(mesh, scene) { - return scene.fogEnabled && mesh.applyFog && scene.fogMode !== scene_Scene.FOGMODE_NONE; - } - /** - * Helper used to prepare the list of defines associated with misc. values for shader compilation - * @param mesh defines the current mesh - * @param scene defines the current scene - * @param useLogarithmicDepth defines if logarithmic depth has to be turned on - * @param pointsCloud defines if point cloud rendering has to be turned on - * @param fogEnabled defines if fog has to be turned on - * @param alphaTest defines if alpha testing has to be turned on - * @param defines defines the current list of defines - * @param applyDecalAfterDetail Defines if the decal is applied after or before the detail - */ - static PrepareDefinesForMisc(mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines, applyDecalAfterDetail = false) { - if (defines._areMiscDirty) { - defines["LOGARITHMICDEPTH"] = useLogarithmicDepth; - defines["POINTSIZE"] = pointsCloud; - defines["FOG"] = fogEnabled && this.GetFogState(mesh, scene); - defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling; - defines["ALPHATEST"] = alphaTest; - defines["DECAL_AFTER_DETAIL"] = applyDecalAfterDetail; - } - } - /** - * Helper used to prepare the defines relative to the active camera - * @param scene defines the current scene - * @param defines specifies the list of active defines - * @returns true if the defines have been updated, else false - */ - static PrepareDefinesForCamera(scene, defines) { - let changed = false; - if (scene.activeCamera) { - const wasOrtho = defines["CAMERA_ORTHOGRAPHIC"] ? 1 : 0; - const wasPersp = defines["CAMERA_PERSPECTIVE"] ? 1 : 0; - const isOrtho = scene.activeCamera.mode === camera_Camera.ORTHOGRAPHIC_CAMERA ? 1 : 0; - const isPersp = scene.activeCamera.mode === camera_Camera.PERSPECTIVE_CAMERA ? 1 : 0; - if (wasOrtho ^ isOrtho || wasPersp ^ isPersp) { - defines["CAMERA_ORTHOGRAPHIC"] = isOrtho === 1; - defines["CAMERA_PERSPECTIVE"] = isPersp === 1; - changed = true; - } - } - return changed; - } - /** - * Helper used to prepare the list of defines associated with frame values for shader compilation - * @param scene defines the current scene - * @param engine defines the current engine - * @param material defines the material we are compiling the shader for - * @param defines specifies the list of active defines - * @param useInstances defines if instances have to be turned on - * @param useClipPlane defines if clip plane have to be turned on - * @param useThinInstances defines if thin instances have to be turned on - */ - static PrepareDefinesForFrameBoundValues(scene, engine, material, defines, useInstances, useClipPlane = null, useThinInstances = false) { - let changed = MaterialHelper.PrepareDefinesForCamera(scene, defines); - if (useClipPlane !== false) { - changed = prepareDefinesForClipPlanes(material, scene, defines); - } - if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) { - defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"]; - changed = true; - } - if (defines["INSTANCES"] !== useInstances) { - defines["INSTANCES"] = useInstances; - changed = true; - } - if (defines["THIN_INSTANCES"] !== useThinInstances) { - defines["THIN_INSTANCES"] = useThinInstances; - changed = true; - } - if (changed) { - defines.markAsUnprocessed(); - } - } - /** - * Prepares the defines for bones - * @param mesh The mesh containing the geometry data we will draw - * @param defines The defines to update - */ - static PrepareDefinesForBones(mesh, defines) { - if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { - defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers; - const materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined; - if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) { - defines["BONETEXTURE"] = true; - } - else { - defines["BonesPerMesh"] = mesh.skeleton.bones.length + 1; - defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined; - const prePassRenderer = mesh.getScene().prePassRenderer; - if (prePassRenderer && prePassRenderer.enabled) { - const nonExcluded = prePassRenderer.excludedSkinnedMesh.indexOf(mesh) === -1; - defines["BONES_VELOCITY_ENABLED"] = nonExcluded; - } - } - } - else { - defines["NUM_BONE_INFLUENCERS"] = 0; - defines["BonesPerMesh"] = 0; - if (defines["BONETEXTURE"] !== undefined) { - defines["BONETEXTURE"] = false; - } - } - } - /** - * Prepares the defines for morph targets - * @param mesh The mesh containing the geometry data we will draw - * @param defines The defines to update - */ - static PrepareDefinesForMorphTargets(mesh, defines) { - const manager = mesh.morphTargetManager; - if (manager) { - defines["MORPHTARGETS_UV"] = manager.supportsUVs && defines["UV1"]; - defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"]; - defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"]; - defines["MORPHTARGETS"] = manager.numInfluencers > 0; - defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers; - defines["MORPHTARGETS_TEXTURE"] = manager.isUsingTextureForTargets; - } - else { - defines["MORPHTARGETS_UV"] = false; - defines["MORPHTARGETS_TANGENT"] = false; - defines["MORPHTARGETS_NORMAL"] = false; - defines["MORPHTARGETS"] = false; - defines["NUM_MORPH_INFLUENCERS"] = 0; - } - } - /** - * Prepares the defines for baked vertex animation - * @param mesh The mesh containing the geometry data we will draw - * @param defines The defines to update - */ - static PrepareDefinesForBakedVertexAnimation(mesh, defines) { - const manager = mesh.bakedVertexAnimationManager; - defines["BAKED_VERTEX_ANIMATION_TEXTURE"] = manager && manager.isEnabled ? true : false; - } - /** - * Prepares the defines used in the shader depending on the attributes data available in the mesh - * @param mesh The mesh containing the geometry data we will draw - * @param defines The defines to update - * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info) - * @param useBones Precise whether bones should be used or not (override mesh info) - * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info) - * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info) - * @param useBakedVertexAnimation Precise whether baked vertex animation should be used or not (override mesh info) - * @returns false if defines are considered not dirty and have not been checked - */ - static PrepareDefinesForAttributes(mesh, defines, useVertexColor, useBones, useMorphTargets = false, useVertexAlpha = true, useBakedVertexAnimation = true) { - if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) { - return false; - } - defines._normals = defines._needNormals; - defines._uvs = defines._needUVs; - defines["NORMAL"] = defines._needNormals && mesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind); - if (defines._needNormals && mesh.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)) { - defines["TANGENT"] = true; - } - for (let i = 1; i <= 6; ++i) { - defines["UV" + i] = defines._needUVs ? mesh.isVerticesDataPresent(`uv${i === 1 ? "" : i}`) : false; - } - if (useVertexColor) { - const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(buffer_VertexBuffer.ColorKind); - defines["VERTEXCOLOR"] = hasVertexColors; - defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha; - } - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.ColorInstanceKind) && (mesh.hasInstances || mesh.hasThinInstances)) { - defines["INSTANCESCOLOR"] = true; - } - if (useBones) { - this.PrepareDefinesForBones(mesh, defines); - } - if (useMorphTargets) { - this.PrepareDefinesForMorphTargets(mesh, defines); - } - if (useBakedVertexAnimation) { - this.PrepareDefinesForBakedVertexAnimation(mesh, defines); - } - return true; - } - /** - * Prepares the defines related to multiview - * @param scene The scene we are intending to draw - * @param defines The defines to update - */ - static PrepareDefinesForMultiview(scene, defines) { - if (scene.activeCamera) { - const previousMultiview = defines.MULTIVIEW; - defines.MULTIVIEW = scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1; - if (defines.MULTIVIEW != previousMultiview) { - defines.markAsUnprocessed(); - } - } - } - /** - * Prepares the defines related to order independant transparency - * @param scene The scene we are intending to draw - * @param defines The defines to update - * @param needAlphaBlending Determines if the material needs alpha blending - */ - static PrepareDefinesForOIT(scene, defines, needAlphaBlending) { - const previousDefine = defines.ORDER_INDEPENDENT_TRANSPARENCY; - const previousDefine16Bits = defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS; - defines.ORDER_INDEPENDENT_TRANSPARENCY = scene.useOrderIndependentTransparency && needAlphaBlending; - defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !scene.getEngine().getCaps().textureFloatLinearFiltering; - if (previousDefine !== defines.ORDER_INDEPENDENT_TRANSPARENCY || previousDefine16Bits !== defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS) { - defines.markAsUnprocessed(); - } - } - /** - * Prepares the defines related to the prepass - * @param scene The scene we are intending to draw - * @param defines The defines to update - * @param canRenderToMRT Indicates if this material renders to several textures in the prepass - */ - static PrepareDefinesForPrePass(scene, defines, canRenderToMRT) { - const previousPrePass = defines.PREPASS; - if (!defines._arePrePassDirty) { - return; - } - const texturesList = [ - { - 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 (scene.prePassRenderer && scene.prePassRenderer.enabled && canRenderToMRT) { - defines.PREPASS = true; - defines.SCENE_MRT_COUNT = scene.prePassRenderer.mrtCount; - for (let i = 0; i < texturesList.length; i++) { - const index = scene.prePassRenderer.getIndex(texturesList[i].type); - if (index !== -1) { - defines[texturesList[i].define] = true; - defines[texturesList[i].index] = index; - } - else { - defines[texturesList[i].define] = false; - } - } - } - else { - defines.PREPASS = false; - for (let i = 0; i < texturesList.length; i++) { - defines[texturesList[i].define] = false; - } - } - if (defines.PREPASS != previousPrePass) { - defines.markAsUnprocessed(); - defines.markAsImageProcessingDirty(); - } - } - /** - * Prepares the defines related to the light information passed in parameter - * @param scene The scene we are intending to draw - * @param mesh The mesh the effect is compiling for - * @param light The light the effect is compiling for - * @param lightIndex The index of the light - * @param defines The defines to update - * @param specularSupported Specifies whether specular is supported or not (override lights data) - * @param state Defines the current state regarding what is needed (normals, etc...) - * @param state.needNormals - * @param state.needRebuild - * @param state.shadowEnabled - * @param state.specularEnabled - * @param state.lightmapMode - */ - static PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state) { - var _a; - state.needNormals = true; - if (defines["LIGHT" + lightIndex] === undefined) { - state.needRebuild = true; - } - defines["LIGHT" + lightIndex] = true; - defines["SPOTLIGHT" + lightIndex] = false; - defines["HEMILIGHT" + lightIndex] = false; - defines["POINTLIGHT" + lightIndex] = false; - defines["DIRLIGHT" + lightIndex] = false; - light.prepareLightSpecificDefines(defines, lightIndex); - // FallOff. - defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false; - defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false; - defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false; - switch (light.falloffType) { - case LightConstants.FALLOFF_GLTF: - defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true; - break; - case LightConstants.FALLOFF_PHYSICAL: - defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true; - break; - case LightConstants.FALLOFF_STANDARD: - defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true; - break; - } - // Specular - if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) { - state.specularEnabled = true; - } - // Shadows - defines["SHADOW" + lightIndex] = false; - defines["SHADOWCSM" + lightIndex] = false; - defines["SHADOWCSMDEBUG" + lightIndex] = false; - defines["SHADOWCSMNUM_CASCADES" + lightIndex] = false; - defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = false; - defines["SHADOWCSMNOBLEND" + lightIndex] = false; - defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = false; - defines["SHADOWPCF" + lightIndex] = false; - defines["SHADOWPCSS" + lightIndex] = false; - defines["SHADOWPOISSON" + lightIndex] = false; - defines["SHADOWESM" + lightIndex] = false; - defines["SHADOWCLOSEESM" + lightIndex] = false; - defines["SHADOWCUBE" + lightIndex] = false; - defines["SHADOWLOWQUALITY" + lightIndex] = false; - defines["SHADOWMEDIUMQUALITY" + lightIndex] = false; - if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) { - const shadowGenerator = (_a = light.getShadowGenerator(scene.activeCamera)) !== null && _a !== void 0 ? _a : light.getShadowGenerator(); - if (shadowGenerator) { - const shadowMap = shadowGenerator.getShadowMap(); - if (shadowMap) { - if (shadowMap.renderList && shadowMap.renderList.length > 0) { - state.shadowEnabled = true; - shadowGenerator.prepareDefines(defines, lightIndex); - } - } - } - } - if (light.lightmapMode != LightConstants.LIGHTMAP_DEFAULT) { - state.lightmapMode = true; - defines["LIGHTMAPEXCLUDED" + lightIndex] = true; - defines["LIGHTMAPNOSPECULAR" + lightIndex] = light.lightmapMode == LightConstants.LIGHTMAP_SHADOWSONLY; - } - else { - defines["LIGHTMAPEXCLUDED" + lightIndex] = false; - defines["LIGHTMAPNOSPECULAR" + lightIndex] = false; - } - } - /** - * Prepares the defines related to the light information passed in parameter - * @param scene The scene we are intending to draw - * @param mesh The mesh the effect is compiling for - * @param defines The defines to update - * @param specularSupported Specifies whether specular is supported or not (override lights data) - * @param maxSimultaneousLights Specifies how manuy lights can be added to the effect at max - * @param disableLighting Specifies whether the lighting is disabled (override scene and light) - * @returns true if normals will be required for the rest of the effect - */ - static PrepareDefinesForLights(scene, mesh, defines, specularSupported, maxSimultaneousLights = 4, disableLighting = false) { - if (!defines._areLightsDirty) { - return defines._needNormals; - } - let lightIndex = 0; - const state = { - needNormals: defines._needNormals, - needRebuild: false, - lightmapMode: false, - shadowEnabled: false, - specularEnabled: false, - }; - if (scene.lightsEnabled && !disableLighting) { - for (const light of mesh.lightSources) { - this.PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state); - lightIndex++; - if (lightIndex === maxSimultaneousLights) { - break; - } - } - } - defines["SPECULARTERM"] = state.specularEnabled; - defines["SHADOWS"] = state.shadowEnabled; - // Resetting all other lights if any - for (let index = lightIndex; index < maxSimultaneousLights; index++) { - if (defines["LIGHT" + index] !== undefined) { - defines["LIGHT" + index] = false; - defines["HEMILIGHT" + index] = false; - defines["POINTLIGHT" + index] = false; - defines["DIRLIGHT" + index] = false; - defines["SPOTLIGHT" + index] = false; - defines["SHADOW" + index] = false; - defines["SHADOWCSM" + index] = false; - defines["SHADOWCSMDEBUG" + index] = false; - defines["SHADOWCSMNUM_CASCADES" + index] = false; - defines["SHADOWCSMUSESHADOWMAXZ" + index] = false; - defines["SHADOWCSMNOBLEND" + index] = false; - defines["SHADOWCSM_RIGHTHANDED" + index] = false; - defines["SHADOWPCF" + index] = false; - defines["SHADOWPCSS" + index] = false; - defines["SHADOWPOISSON" + index] = false; - defines["SHADOWESM" + index] = false; - defines["SHADOWCLOSEESM" + index] = false; - defines["SHADOWCUBE" + index] = false; - defines["SHADOWLOWQUALITY" + index] = false; - defines["SHADOWMEDIUMQUALITY" + index] = false; - } - } - const caps = scene.getEngine().getCaps(); - if (defines["SHADOWFLOAT"] === undefined) { - state.needRebuild = true; - } - defines["SHADOWFLOAT"] = - state.shadowEnabled && ((caps.textureFloatRender && caps.textureFloatLinearFiltering) || (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering)); - defines["LIGHTMAPEXCLUDED"] = state.lightmapMode; - if (state.needRebuild) { - defines.rebuild(); - } - return state.needNormals; - } - /** - * Prepares the uniforms and samplers list to be used in the effect (for a specific light) - * @param lightIndex defines the light index - * @param uniformsList The uniform list - * @param samplersList The sampler list - * @param projectedLightTexture defines if projected texture must be used - * @param uniformBuffersList defines an optional list of uniform buffers - * @param updateOnlyBuffersList True to only update the uniformBuffersList array - */ - static PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, projectedLightTexture, uniformBuffersList = null, updateOnlyBuffersList = false) { - if (uniformBuffersList) { - uniformBuffersList.push("Light" + lightIndex); - } - if (updateOnlyBuffersList) { - return; - } - uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex); - samplersList.push("shadowSampler" + lightIndex); - samplersList.push("depthSampler" + lightIndex); - uniformsList.push("viewFrustumZ" + lightIndex, "cascadeBlendFactor" + lightIndex, "lightSizeUVCorrection" + lightIndex, "depthCorrection" + lightIndex, "penumbraDarkness" + lightIndex, "frustumLengths" + lightIndex); - if (projectedLightTexture) { - samplersList.push("projectionLightSampler" + lightIndex); - uniformsList.push("textureProjectionMatrix" + lightIndex); - } - } - /** - * Prepares the uniforms and samplers list to be used in the effect - * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the list and extra information - * @param samplersList The sampler list - * @param defines The defines helping in the list generation - * @param maxSimultaneousLights The maximum number of simultaneous light allowed in the effect - */ - static PrepareUniformsAndSamplersList(uniformsListOrOptions, samplersList, defines, maxSimultaneousLights = 4) { - let uniformsList; - let uniformBuffersList = null; - if (uniformsListOrOptions.uniformsNames) { - const options = uniformsListOrOptions; - uniformsList = options.uniformsNames; - uniformBuffersList = options.uniformBuffersNames; - samplersList = options.samplers; - defines = options.defines; - maxSimultaneousLights = options.maxSimultaneousLights || 0; - } - else { - uniformsList = uniformsListOrOptions; - if (!samplersList) { - samplersList = []; - } - } - for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) { - if (!defines["LIGHT" + lightIndex]) { - break; - } - this.PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffersList); - } - if (defines["NUM_MORPH_INFLUENCERS"]) { - uniformsList.push("morphTargetInfluences"); - } - if (defines["BAKED_VERTEX_ANIMATION_TEXTURE"]) { - uniformsList.push("bakedVertexAnimationSettings"); - uniformsList.push("bakedVertexAnimationTextureSizeInverted"); - uniformsList.push("bakedVertexAnimationTime"); - samplersList.push("bakedVertexAnimationTexture"); - } - } - /** - * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality) - * @param defines The defines to update while falling back - * @param fallbacks The authorized effect fallbacks - * @param maxSimultaneousLights The maximum number of lights allowed - * @param rank the current rank of the Effect - * @returns The newly affected rank - */ - static HandleFallbacksForShadows(defines, fallbacks, maxSimultaneousLights = 4, rank = 0) { - let lightFallbackRank = 0; - for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) { - if (!defines["LIGHT" + lightIndex]) { - break; - } - if (lightIndex > 0) { - lightFallbackRank = rank + lightIndex; - fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex); - } - if (!defines["SHADOWS"]) { - if (defines["SHADOW" + lightIndex]) { - fallbacks.addFallback(rank, "SHADOW" + lightIndex); - } - if (defines["SHADOWPCF" + lightIndex]) { - fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex); - } - if (defines["SHADOWPCSS" + lightIndex]) { - fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex); - } - if (defines["SHADOWPOISSON" + lightIndex]) { - fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex); - } - if (defines["SHADOWESM" + lightIndex]) { - fallbacks.addFallback(rank, "SHADOWESM" + lightIndex); - } - if (defines["SHADOWCLOSEESM" + lightIndex]) { - fallbacks.addFallback(rank, "SHADOWCLOSEESM" + lightIndex); - } - } - } - return lightFallbackRank++; - } - /** - * Prepares the list of attributes required for morph targets according to the effect defines. - * @param attribs The current list of supported attribs - * @param mesh The mesh to prepare the morph targets attributes for - * @param influencers The number of influencers - */ - static PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, influencers) { - this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers; - this.PrepareAttributesForMorphTargets(attribs, mesh, this._TmpMorphInfluencers); - } - /** - * Prepares the list of attributes required for morph targets according to the effect defines. - * @param attribs The current list of supported attribs - * @param mesh The mesh to prepare the morph targets attributes for - * @param defines The current Defines of the effect - */ - static PrepareAttributesForMorphTargets(attribs, mesh, defines) { - const influencers = defines["NUM_MORPH_INFLUENCERS"]; - if (influencers > 0 && engineStore_EngineStore.LastCreatedEngine) { - const maxAttributesCount = engineStore_EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs; - const manager = mesh.morphTargetManager; - if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) { - return; - } - const normal = manager && manager.supportsNormals && defines["NORMAL"]; - const tangent = manager && manager.supportsTangents && defines["TANGENT"]; - const uv = manager && manager.supportsUVs && defines["UV1"]; - for (let index = 0; index < influencers; index++) { - attribs.push(buffer_VertexBuffer.PositionKind + index); - if (normal) { - attribs.push(buffer_VertexBuffer.NormalKind + index); - } - if (tangent) { - attribs.push(buffer_VertexBuffer.TangentKind + index); - } - if (uv) { - attribs.push(buffer_VertexBuffer.UVKind + "_" + index); - } - if (attribs.length > maxAttributesCount) { - logger_Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name); - } - } - } - } - /** - * Prepares the list of attributes required for baked vertex animations according to the effect defines. - * @param attribs The current list of supported attribs - * @param mesh The mesh to prepare the morph targets attributes for - * @param defines The current Defines of the effect - */ - static PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines) { - const enabled = defines["BAKED_VERTEX_ANIMATION_TEXTURE"] && defines["INSTANCES"]; - if (enabled) { - attribs.push("bakedVertexAnimationSettingsInstanced"); - } - } - /** - * Prepares the list of attributes required for bones according to the effect defines. - * @param attribs The current list of supported attribs - * @param mesh The mesh to prepare the bones attributes for - * @param defines The current Defines of the effect - * @param fallbacks The current effect fallback strategy - */ - static PrepareAttributesForBones(attribs, mesh, defines, fallbacks) { - if (defines["NUM_BONE_INFLUENCERS"] > 0) { - fallbacks.addCPUSkinningFallback(0, mesh); - attribs.push(buffer_VertexBuffer.MatricesIndicesKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsKind); - if (defines["NUM_BONE_INFLUENCERS"] > 4) { - attribs.push(buffer_VertexBuffer.MatricesIndicesExtraKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsExtraKind); - } - } - } - /** - * Check and prepare the list of attributes required for instances according to the effect defines. - * @param attribs The current list of supported attribs - * @param defines The current MaterialDefines of the effect - */ - static PrepareAttributesForInstances(attribs, defines) { - if (defines["INSTANCES"] || defines["THIN_INSTANCES"]) { - this.PushAttributesForInstances(attribs, !!defines["PREPASS_VELOCITY"]); - } - if (defines.INSTANCESCOLOR) { - attribs.push(buffer_VertexBuffer.ColorInstanceKind); - } - } - /** - * Add the list of attributes required for instances to the attribs array. - * @param attribs The current list of supported attribs - * @param needsPreviousMatrices If the shader needs previous matrices - */ - static PushAttributesForInstances(attribs, needsPreviousMatrices = false) { - attribs.push("world0"); - attribs.push("world1"); - attribs.push("world2"); - attribs.push("world3"); - if (needsPreviousMatrices) { - attribs.push("previousWorld0"); - attribs.push("previousWorld1"); - attribs.push("previousWorld2"); - attribs.push("previousWorld3"); - } - } - /** - * Binds the light information to the effect. - * @param light The light containing the generator - * @param effect The effect we are binding the data to - * @param lightIndex The light index in the effect used to render - */ - static BindLightProperties(light, effect, lightIndex) { - light.transferToEffect(effect, lightIndex + ""); - } - /** - * Binds the lights information from the scene to the effect for the given mesh. - * @param light Light to bind - * @param lightIndex Light index - * @param scene The scene where the light belongs to - * @param effect The effect we are binding the data to - * @param useSpecular Defines if specular is supported - * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows - */ - static BindLight(light, lightIndex, scene, effect, useSpecular, receiveShadows = true) { - light._bindLight(lightIndex, scene, effect, useSpecular, receiveShadows); - } - /** - * Binds the lights information from the scene to the effect for the given mesh. - * @param scene The scene the lights belongs to - * @param mesh The mesh we are binding the information to render - * @param effect The effect we are binding the data to - * @param defines The generated defines for the effect - * @param maxSimultaneousLights The maximum number of light that can be bound to the effect - */ - static BindLights(scene, mesh, effect, defines, maxSimultaneousLights = 4) { - const len = Math.min(mesh.lightSources.length, maxSimultaneousLights); - for (let i = 0; i < len; i++) { - const light = mesh.lightSources[i]; - this.BindLight(light, i, scene, effect, typeof defines === "boolean" ? defines : defines["SPECULARTERM"], mesh.receiveShadows); - } - } - /** - * Binds the fog information from the scene to the effect for the given mesh. - * @param scene The scene the lights belongs to - * @param mesh The mesh we are binding the information to render - * @param effect The effect we are binding the data to - * @param linearSpace Defines if the fog effect is applied in linear space - */ - static BindFogParameters(scene, mesh, effect, linearSpace = false) { - if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== scene_Scene.FOGMODE_NONE) { - effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); - // Convert fog color to linear space if used in a linear space computed shader. - if (linearSpace) { - scene.fogColor.toLinearSpaceToRef(this._TempFogColor, scene.getEngine().useExactSrgbConversions); - effect.setColor3("vFogColor", this._TempFogColor); - } - else { - effect.setColor3("vFogColor", scene.fogColor); - } - } - } - /** - * Binds the bones information from the mesh to the effect. - * @param mesh The mesh we are binding the information to render - * @param effect The effect we are binding the data to - * @param prePassConfiguration Configuration for the prepass, in case prepass is activated - */ - static BindBonesParameters(mesh, effect, prePassConfiguration) { - if (!effect || !mesh) { - return; - } - if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) { - mesh.computeBonesUsingShaders = false; - } - if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { - const skeleton = mesh.skeleton; - if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) { - const boneTexture = skeleton.getTransformMatrixTexture(mesh); - effect.setTexture("boneSampler", boneTexture); - effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); - } - else { - const matrices = skeleton.getTransformMatrices(mesh); - if (matrices) { - effect.setMatrices("mBones", matrices); - if (prePassConfiguration && mesh.getScene().prePassRenderer && mesh.getScene().prePassRenderer.getIndex(2)) { - if (!prePassConfiguration.previousBones[mesh.uniqueId]) { - prePassConfiguration.previousBones[mesh.uniqueId] = matrices.slice(); - } - effect.setMatrices("mPreviousBones", prePassConfiguration.previousBones[mesh.uniqueId]); - MaterialHelper._CopyBonesTransformationMatrices(matrices, prePassConfiguration.previousBones[mesh.uniqueId]); - } - } - } - } - } - // Copies the bones transformation matrices into the target array and returns the target's reference - static _CopyBonesTransformationMatrices(source, target) { - target.set(source); - return target; - } - /** - * Binds the morph targets information from the mesh to the effect. - * @param abstractMesh The mesh we are binding the information to render - * @param effect The effect we are binding the data to - */ - static BindMorphTargetParameters(abstractMesh, effect) { - const manager = abstractMesh.morphTargetManager; - if (!abstractMesh || !manager) { - return; - } - effect.setFloatArray("morphTargetInfluences", manager.influences); - } - /** - * Binds the logarithmic depth information from the scene to the effect for the given defines. - * @param defines The generated defines used in the effect - * @param effect The effect we are binding the data to - * @param scene The scene we are willing to render with logarithmic scale for - */ - static BindLogDepth(defines, effect, scene) { - if (!defines || defines["LOGARITHMICDEPTH"] || (defines.indexOf && defines.indexOf("LOGARITHMICDEPTH") >= 0)) { - const camera = scene.activeCamera; - if (camera.mode === camera_Camera.ORTHOGRAPHIC_CAMERA) { - logger_Logger.Error("Logarithmic depth is not compatible with orthographic cameras!", 20); - } - effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(camera.maxZ + 1.0) / Math.LN2)); - } - } -} -// eslint-disable-next-line @typescript-eslint/naming-convention -MaterialHelper._TmpMorphInfluencers = { NUM_MORPH_INFLUENCERS: 0 }; -MaterialHelper._TempFogColor = math_color_Color3.Black(); -//# sourceMappingURL=materialHelper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/materialStencilState.js - - - -/** - * Class that holds the different stencil states of a material - * Usage example: https://playground.babylonjs.com/#CW5PRI#10 - */ -class MaterialStencilState { - /** - * Creates a material stencil state instance - */ - constructor() { - this.reset(); - } - /** - * Resets all the stencil states to default values - */ - reset() { - this.enabled = false; - this.mask = 0xff; - this.func = 519; - this.funcRef = 1; - this.funcMask = 0xff; - this.opStencilFail = 7680; - this.opDepthFail = 7680; - this.opStencilDepthPass = 7681; - } - /** - * Gets or sets the stencil function - */ - get func() { - return this._func; - } - set func(value) { - this._func = value; - } - /** - * Gets or sets the stencil function reference - */ - get funcRef() { - return this._funcRef; - } - set funcRef(value) { - this._funcRef = value; - } - /** - * Gets or sets the stencil function mask - */ - get funcMask() { - return this._funcMask; - } - set funcMask(value) { - this._funcMask = value; - } - /** - * Gets or sets the operation when the stencil test fails - */ - get opStencilFail() { - return this._opStencilFail; - } - set opStencilFail(value) { - this._opStencilFail = value; - } - /** - * Gets or sets the operation when the depth test fails - */ - get opDepthFail() { - return this._opDepthFail; - } - set opDepthFail(value) { - this._opDepthFail = value; - } - /** - * Gets or sets the operation when the stencil+depth test succeeds - */ - get opStencilDepthPass() { - return this._opStencilDepthPass; - } - set opStencilDepthPass(value) { - this._opStencilDepthPass = value; - } - /** - * Gets or sets the stencil mask - */ - get mask() { - return this._mask; - } - set mask(value) { - this._mask = value; - } - /** - * Enables or disables the stencil test - */ - get enabled() { - return this._enabled; - } - set enabled(value) { - this._enabled = value; - } - /** - * Get the current class name, useful for serialization or dynamic coding. - * @returns "MaterialStencilState" - */ - getClassName() { - return "MaterialStencilState"; - } - /** - * Makes a duplicate of the current configuration into another one. - * @param stencilState defines stencil state where to copy the info - */ - copyTo(stencilState) { - decorators_SerializationHelper.Clone(() => stencilState, this); - } - /** - * Serializes this stencil configuration. - * @returns - An object with the serialized config. - */ - serialize() { - return decorators_SerializationHelper.Serialize(this); - } - /** - * Parses a stencil state configuration from a serialized object. - * @param source - Serialized object. - * @param scene Defines the scene we are parsing for - * @param rootUrl Defines the rootUrl to load from - */ - parse(source, scene, rootUrl) { - decorators_SerializationHelper.Parse(() => this, source, scene, rootUrl); - } -} -__decorate([ - serialize() -], MaterialStencilState.prototype, "func", null); -__decorate([ - serialize() -], MaterialStencilState.prototype, "funcRef", null); -__decorate([ - serialize() -], MaterialStencilState.prototype, "funcMask", null); -__decorate([ - serialize() -], MaterialStencilState.prototype, "opStencilFail", null); -__decorate([ - serialize() -], MaterialStencilState.prototype, "opDepthFail", null); -__decorate([ - serialize() -], MaterialStencilState.prototype, "opStencilDepthPass", null); -__decorate([ - serialize() -], MaterialStencilState.prototype, "mask", null); -__decorate([ - serialize() -], MaterialStencilState.prototype, "enabled", null); -//# sourceMappingURL=materialStencilState.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/materialPluginEvent.js -/** - * @internal - */ -var materialPluginEvent_MaterialPluginEvent; -(function (MaterialPluginEvent) { - MaterialPluginEvent[MaterialPluginEvent["Created"] = 1] = "Created"; - MaterialPluginEvent[MaterialPluginEvent["Disposed"] = 2] = "Disposed"; - MaterialPluginEvent[MaterialPluginEvent["GetDefineNames"] = 4] = "GetDefineNames"; - MaterialPluginEvent[MaterialPluginEvent["PrepareUniformBuffer"] = 8] = "PrepareUniformBuffer"; - MaterialPluginEvent[MaterialPluginEvent["IsReadyForSubMesh"] = 16] = "IsReadyForSubMesh"; - MaterialPluginEvent[MaterialPluginEvent["PrepareDefines"] = 32] = "PrepareDefines"; - MaterialPluginEvent[MaterialPluginEvent["BindForSubMesh"] = 64] = "BindForSubMesh"; - MaterialPluginEvent[MaterialPluginEvent["PrepareEffect"] = 128] = "PrepareEffect"; - MaterialPluginEvent[MaterialPluginEvent["GetAnimatables"] = 256] = "GetAnimatables"; - MaterialPluginEvent[MaterialPluginEvent["GetActiveTextures"] = 512] = "GetActiveTextures"; - MaterialPluginEvent[MaterialPluginEvent["HasTexture"] = 1024] = "HasTexture"; - MaterialPluginEvent[MaterialPluginEvent["FillRenderTargetTextures"] = 2048] = "FillRenderTargetTextures"; - MaterialPluginEvent[MaterialPluginEvent["HasRenderTargetTextures"] = 4096] = "HasRenderTargetTextures"; - MaterialPluginEvent[MaterialPluginEvent["HardBindForSubMesh"] = 8192] = "HardBindForSubMesh"; -})(materialPluginEvent_MaterialPluginEvent || (materialPluginEvent_MaterialPluginEvent = {})); -//# sourceMappingURL=materialPluginEvent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/material.js - - - - - - - - - - - - - - - -/** - * Base class for the main features of a material in Babylon.js - */ -class material_Material { - /** - * If the material can be rendered to several textures with MRT extension - */ - get canRenderToMRT() { - // By default, shaders are not compatible with MRTs - // Base classes should override that if their shader supports MRT - return false; - } - /** - * Sets the alpha value of the material - */ - set alpha(value) { - if (this._alpha === value) { - return; - } - const oldValue = this._alpha; - this._alpha = value; - // Only call dirty when there is a state change (no alpha / alpha) - if (oldValue === 1 || value === 1) { - this.markAsDirty(material_Material.MiscDirtyFlag + material_Material.PrePassDirtyFlag); - } - } - /** - * Gets the alpha value of the material - */ - get alpha() { - return this._alpha; - } - /** - * Sets the culling state (true to enable culling, false to disable) - */ - set backFaceCulling(value) { - if (this._backFaceCulling === value) { - return; - } - this._backFaceCulling = value; - this.markAsDirty(material_Material.TextureDirtyFlag); - } - /** - * Gets the culling state - */ - get backFaceCulling() { - return this._backFaceCulling; - } - /** - * Sets the type of faces that should be culled (true for back faces, false for front faces) - */ - set cullBackFaces(value) { - if (this._cullBackFaces === value) { - return; - } - this._cullBackFaces = value; - this.markAsDirty(material_Material.TextureDirtyFlag); - } - /** - * Gets the type of faces that should be culled - */ - get cullBackFaces() { - return this._cullBackFaces; - } - /** - * Block the dirty-mechanism for this specific material - * When set to false after being true the material will be marked as dirty. - */ - get blockDirtyMechanism() { - return this._blockDirtyMechanism; - } - set blockDirtyMechanism(value) { - if (this._blockDirtyMechanism === value) { - return; - } - this._blockDirtyMechanism = value; - if (!value) { - this.markDirty(); - } - } - /** - * This allows you to modify the material without marking it as dirty after every change. - * 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. - * The callback will pass the material as an argument, so you can make your changes to it. - * @param callback the callback to be executed that will update the material - */ - atomicMaterialsUpdate(callback) { - this.blockDirtyMechanism = true; - try { - callback(this); - } - finally { - this.blockDirtyMechanism = false; - } - } - /** - * Gets a boolean indicating that current material needs to register RTT - */ - get hasRenderTargetTextures() { - this._eventInfo.hasRenderTargetTextures = false; - this._callbackPluginEventHasRenderTargetTextures(this._eventInfo); - return this._eventInfo.hasRenderTargetTextures; - } - /** - * Called during a dispose event - */ - set onDispose(callback) { - if (this._onDisposeObserver) { - this.onDisposeObservable.remove(this._onDisposeObserver); - } - this._onDisposeObserver = this.onDisposeObservable.add(callback); - } - /** - * An event triggered when the material is bound - */ - get onBindObservable() { - if (!this._onBindObservable) { - this._onBindObservable = new observable_Observable(); - } - return this._onBindObservable; - } - /** - * Called during a bind event - */ - set onBind(callback) { - if (this._onBindObserver) { - this.onBindObservable.remove(this._onBindObserver); - } - this._onBindObserver = this.onBindObservable.add(callback); - } - /** - * An event triggered when the material is unbound - */ - get onUnBindObservable() { - if (!this._onUnBindObservable) { - this._onUnBindObservable = new observable_Observable(); - } - return this._onUnBindObservable; - } - /** - * An event triggered when the effect is (re)created - */ - get onEffectCreatedObservable() { - if (!this._onEffectCreatedObservable) { - this._onEffectCreatedObservable = new observable_Observable(); - } - return this._onEffectCreatedObservable; - } - /** - * Sets the value of the alpha mode. - * - * | Value | Type | Description | - * | --- | --- | --- | - * | 0 | ALPHA_DISABLE | | - * | 1 | ALPHA_ADD | | - * | 2 | ALPHA_COMBINE | | - * | 3 | ALPHA_SUBTRACT | | - * | 4 | ALPHA_MULTIPLY | | - * | 5 | ALPHA_MAXIMIZED | | - * | 6 | ALPHA_ONEONE | | - * | 7 | ALPHA_PREMULTIPLIED | | - * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | | - * | 9 | ALPHA_INTERPOLATE | | - * | 10 | ALPHA_SCREENMODE | | - * - */ - set alphaMode(value) { - if (this._alphaMode === value) { - return; - } - this._alphaMode = value; - this.markAsDirty(material_Material.TextureDirtyFlag); - } - /** - * Gets the value of the alpha mode - */ - get alphaMode() { - return this._alphaMode; - } - /** - * Sets the need depth pre-pass value - */ - set needDepthPrePass(value) { - if (this._needDepthPrePass === value) { - return; - } - this._needDepthPrePass = value; - if (this._needDepthPrePass) { - this.checkReadyOnEveryCall = true; - } - } - /** - * Gets the depth pre-pass value - */ - get needDepthPrePass() { - return this._needDepthPrePass; - } - /** - * Can this material render to prepass - */ - get isPrePassCapable() { - return false; - } - /** - * Sets the state for enabling fog - */ - set fogEnabled(value) { - if (this._fogEnabled === value) { - return; - } - this._fogEnabled = value; - this.markAsDirty(material_Material.MiscDirtyFlag); - } - /** - * Gets the value of the fog enabled state - */ - get fogEnabled() { - return this._fogEnabled; - } - get wireframe() { - switch (this._fillMode) { - case material_Material.WireFrameFillMode: - case material_Material.LineListDrawMode: - case material_Material.LineLoopDrawMode: - case material_Material.LineStripDrawMode: - return true; - } - return this._scene.forceWireframe; - } - /** - * Sets the state of wireframe mode - */ - set wireframe(value) { - this.fillMode = value ? material_Material.WireFrameFillMode : material_Material.TriangleFillMode; - } - /** - * Gets the value specifying if point clouds are enabled - */ - get pointsCloud() { - switch (this._fillMode) { - case material_Material.PointFillMode: - case material_Material.PointListDrawMode: - return true; - } - return this._scene.forcePointsCloud; - } - /** - * Sets the state of point cloud mode - */ - set pointsCloud(value) { - this.fillMode = value ? material_Material.PointFillMode : material_Material.TriangleFillMode; - } - /** - * Gets the material fill mode - */ - get fillMode() { - return this._fillMode; - } - /** - * Sets the material fill mode - */ - set fillMode(value) { - if (this._fillMode === value) { - return; - } - this._fillMode = value; - this.markAsDirty(material_Material.MiscDirtyFlag); - } - /** @internal */ - _getDrawWrapper() { - return this._drawWrapper; - } - /** - * @internal - */ - _setDrawWrapper(drawWrapper) { - this._drawWrapper = drawWrapper; - } - /** - * Creates a material instance - * @param name defines the name of the material - * @param scene defines the scene to reference - * @param doNotAdd specifies if the material should be added to the scene - */ - constructor(name, scene, doNotAdd) { - /** - * Custom shadow depth material to use for shadow rendering instead of the in-built one - */ - this.shadowDepthWrapper = null; - /** - * Gets or sets a boolean indicating that the material is allowed (if supported) to do shader hot swapping. - * This means that the material can keep using a previous shader while a new one is being compiled. - * This is mostly used when shader parallel compilation is supported (true by default) - */ - this.allowShaderHotSwapping = true; - /** - * Gets or sets user defined metadata - */ - this.metadata = null; - /** - * For internal use only. Please do not use. - */ - this.reservedDataStore = null; - /** - * Specifies if the ready state should be checked on each call - */ - this.checkReadyOnEveryCall = false; - /** - * Specifies if the ready state should be checked once - */ - this.checkReadyOnlyOnce = false; - /** - * The state of the material - */ - this.state = ""; - /** - * The alpha value of the material - */ - this._alpha = 1.0; - /** - * Specifies if back face culling is enabled - */ - this._backFaceCulling = true; - /** - * Specifies if back or front faces should be culled (when culling is enabled) - */ - this._cullBackFaces = true; - this._blockDirtyMechanism = false; - /** - * Callback triggered when the material is compiled - */ - this.onCompiled = null; - /** - * Callback triggered when an error occurs - */ - this.onError = null; - /** - * Callback triggered to get the render target textures - */ - this.getRenderTargetTextures = null; - /** - * Specifies if the material should be serialized - */ - this.doNotSerialize = false; - /** - * @internal - */ - this._storeEffectOnSubMeshes = false; - /** - * Stores the animations for the material - */ - this.animations = null; - /** - * An event triggered when the material is disposed - */ - this.onDisposeObservable = new observable_Observable(); - /** - * An observer which watches for dispose events - */ - this._onDisposeObserver = null; - this._onUnBindObservable = null; - /** - * An observer which watches for bind events - */ - this._onBindObserver = null; - /** - * Stores the value of the alpha mode - */ - this._alphaMode = 2; - /** - * Stores the state of the need depth pre-pass value - */ - this._needDepthPrePass = false; - /** - * Specifies if depth writing should be disabled - */ - this.disableDepthWrite = false; - /** - * Specifies if color writing should be disabled - */ - this.disableColorWrite = false; - /** - * Specifies if depth writing should be forced - */ - this.forceDepthWrite = false; - /** - * Specifies the depth function that should be used. 0 means the default engine function - */ - this.depthFunction = 0; - /** - * Specifies if there should be a separate pass for culling - */ - this.separateCullingPass = false; - /** - * Stores the state specifying if fog should be enabled - */ - this._fogEnabled = true; - /** - * Stores the size of points - */ - this.pointSize = 1.0; - /** - * Stores the z offset Factor value - */ - this.zOffset = 0; - /** - * Stores the z offset Units value - */ - this.zOffsetUnits = 0; - /** - * Gives access to the stencil properties of the material - */ - this.stencil = new MaterialStencilState(); - /** - * Specifies if uniform buffers should be used - */ - this._useUBO = false; - /** - * Stores the fill mode state - */ - this._fillMode = material_Material.TriangleFillMode; - /** - * Specifies if the depth write state should be cached - */ - this._cachedDepthWriteState = false; - /** - * Specifies if the color write state should be cached - */ - this._cachedColorWriteState = false; - /** - * Specifies if the depth function state should be cached - */ - this._cachedDepthFunctionState = 0; - /** @internal */ - this._indexInSceneMaterialArray = -1; - /** @internal */ - this.meshMap = null; - /** @internal */ - this._parentContainer = null; - /** @internal */ - this._uniformBufferLayoutBuilt = false; - this._eventInfo = {}; // will be initialized before each event notification - /** @internal */ - this._callbackPluginEventGeneric = () => void 0; - /** @internal */ - this._callbackPluginEventIsReadyForSubMesh = () => void 0; - /** @internal */ - this._callbackPluginEventPrepareDefines = () => void 0; - /** @internal */ - this._callbackPluginEventPrepareDefinesBeforeAttributes = () => void 0; - /** @internal */ - this._callbackPluginEventHardBindForSubMesh = () => void 0; - /** @internal */ - this._callbackPluginEventBindForSubMesh = () => void 0; - /** @internal */ - this._callbackPluginEventHasRenderTargetTextures = () => void 0; - /** @internal */ - this._callbackPluginEventFillRenderTargetTextures = () => void 0; - /** - * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations. - */ - this._forceAlphaTest = false; - /** - * The transparency mode of the material. - */ - this._transparencyMode = null; - this.name = name; - const setScene = scene || engineStore_EngineStore.LastCreatedScene; - if (!setScene) { - return; - } - this._scene = setScene; - 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 = name || tools_Tools.RandomId(); - this.uniqueId = this._scene.getUniqueId(); - this._materialContext = this._scene.getEngine().createMaterialContext(); - this._drawWrapper = new drawWrapper_DrawWrapper(this._scene.getEngine(), false); - this._drawWrapper.materialContext = this._materialContext; - if (this._scene.useRightHandedSystem) { - this.sideOrientation = material_Material.ClockWiseSideOrientation; - } - else { - this.sideOrientation = material_Material.CounterClockWiseSideOrientation; - } - this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), undefined, undefined, name); - this._useUBO = this.getScene().getEngine().supportsUniformBuffers; - if (!doNotAdd) { - this._scene.addMaterial(this); - } - if (this._scene.useMaterialMeshMap) { - this.meshMap = {}; - } - material_Material.OnEventObservable.notifyObservers(this, materialPluginEvent_MaterialPluginEvent.Created); - } - /** - * Returns a string representation of the current material - * @param fullDetails defines a boolean indicating which levels of logging is desired - * @returns a string with material information - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - toString(fullDetails) { - const ret = "Name: " + this.name; - return ret; - } - /** - * Gets the class name of the material - * @returns a string with the class name of the material - */ - getClassName() { - return "Material"; - } - /** @internal */ - get _isMaterial() { - return true; - } - /** - * Specifies if updates for the material been locked - */ - get isFrozen() { - return this.checkReadyOnlyOnce; - } - /** - * Locks updates for the material - */ - freeze() { - this.markDirty(); - this.checkReadyOnlyOnce = true; - } - /** - * Unlocks updates for the material - */ - unfreeze() { - this.markDirty(); - this.checkReadyOnlyOnce = false; - } - /** - * Specifies if the material is ready to be used - * @param mesh defines the mesh to check - * @param useInstances specifies if instances should be used - * @returns a boolean indicating if the material is ready to be used - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - isReady(mesh, useInstances) { - return true; - } - /** - * Specifies that the submesh is ready to be used - * @param mesh defines the mesh to check - * @param subMesh defines which submesh to check - * @param useInstances specifies that instances should be used - * @returns a boolean indicating that the submesh is ready or not - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - isReadyForSubMesh(mesh, subMesh, useInstances) { - const defines = subMesh.materialDefines; - if (!defines) { - return false; - } - this._eventInfo.isReadyForSubMesh = true; - this._eventInfo.defines = defines; - this._callbackPluginEventIsReadyForSubMesh(this._eventInfo); - return this._eventInfo.isReadyForSubMesh; - } - /** - * Returns the material effect - * @returns the effect associated with the material - */ - getEffect() { - return this._drawWrapper.effect; - } - /** - * Returns the current scene - * @returns a Scene - */ - getScene() { - return this._scene; - } - /** - * Gets the current transparency mode. - */ - get transparencyMode() { - return this._transparencyMode; - } - /** - * Sets the transparency mode of the material. - * - * | Value | Type | Description | - * | ----- | ----------------------------------- | ----------- | - * | 0 | OPAQUE | | - * | 1 | ALPHATEST | | - * | 2 | ALPHABLEND | | - * | 3 | ALPHATESTANDBLEND | | - * - */ - set transparencyMode(value) { - if (this._transparencyMode === value) { - return; - } - this._transparencyMode = value; - this._forceAlphaTest = value === material_Material.MATERIAL_ALPHATESTANDBLEND; - this._markAllSubMeshesAsTexturesAndMiscDirty(); - } - /** - * Returns true if alpha blending should be disabled. - */ - get _disableAlphaBlending() { - return this._transparencyMode === material_Material.MATERIAL_OPAQUE || this._transparencyMode === material_Material.MATERIAL_ALPHATEST; - } - /** - * Specifies whether or not this material should be rendered in alpha blend mode. - * @returns a boolean specifying if alpha blending is needed - */ - needAlphaBlending() { - if (this._disableAlphaBlending) { - return false; - } - return this.alpha < 1.0; - } - /** - * Specifies if the mesh will require alpha blending - * @param mesh defines the mesh to check - * @returns a boolean specifying if alpha blending is needed for the mesh - */ - needAlphaBlendingForMesh(mesh) { - if (mesh.visibility < 1.0) { - return true; - } - if (this._disableAlphaBlending) { - return false; - } - return mesh.hasVertexAlpha || this.needAlphaBlending(); - } - /** - * Specifies whether or not this material should be rendered in alpha test mode. - * @returns a boolean specifying if an alpha test is needed. - */ - needAlphaTesting() { - if (this._forceAlphaTest) { - return true; - } - return false; - } - /** - * Specifies if material alpha testing should be turned on for the mesh - * @param mesh defines the mesh to check - */ - _shouldTurnAlphaTestOn(mesh) { - return !this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting(); - } - /** - * Gets the texture used for the alpha test - * @returns the texture to use for alpha testing - */ - getAlphaTestTexture() { - return null; - } - /** - * Marks the material to indicate that it needs to be re-calculated - * @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. - */ - markDirty(forceMaterialDirty = false) { - const meshes = this.getScene().meshes; - for (const mesh of meshes) { - if (!mesh.subMeshes) { - continue; - } - for (const subMesh of mesh.subMeshes) { - if (subMesh.getMaterial() !== this) { - continue; - } - if (!subMesh.effect) { - continue; - } - subMesh.effect._wasPreviouslyReady = false; - subMesh.effect._wasPreviouslyUsingInstances = null; - subMesh.effect._forceRebindOnNextCall = forceMaterialDirty; - } - } - if (forceMaterialDirty) { - this.markAsDirty(material_Material.AllDirtyFlag); - } - } - /** - * @internal - */ - _preBind(effect, overrideOrientation = null) { - const engine = this._scene.getEngine(); - const orientation = overrideOrientation == null ? this.sideOrientation : overrideOrientation; - const reverse = orientation === material_Material.ClockWiseSideOrientation; - engine.enableEffect(effect ? effect : this._getDrawWrapper()); - engine.setState(this.backFaceCulling, this.zOffset, false, reverse, this._scene._mirroredCameraPosition ? !this.cullBackFaces : this.cullBackFaces, this.stencil, this.zOffsetUnits); - return reverse; - } - /** - * Binds the material to the mesh - * @param world defines the world transformation matrix - * @param mesh defines the mesh to bind the material to - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - bind(world, mesh) { } - /** - * Initializes the uniform buffer layout for the shader. - */ - buildUniformLayout() { - const ubo = this._uniformBuffer; - this._eventInfo.ubo = ubo; - this._callbackPluginEventGeneric(materialPluginEvent_MaterialPluginEvent.PrepareUniformBuffer, this._eventInfo); - ubo.create(); - this._uniformBufferLayoutBuilt = true; - } - /** - * Binds the submesh to the material - * @param world defines the world transformation matrix - * @param mesh defines the mesh containing the submesh - * @param subMesh defines the submesh to bind the material to - */ - bindForSubMesh(world, mesh, subMesh) { - const effect = subMesh.effect; - if (!effect) { - return; - } - this._eventInfo.subMesh = subMesh; - this._callbackPluginEventBindForSubMesh(this._eventInfo); - effect._forceRebindOnNextCall = false; - } - /** - * Binds the world matrix to the material - * @param world defines the world transformation matrix - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - bindOnlyWorldMatrix(world) { } - /** - * Binds the view matrix to the effect - * @param effect defines the effect to bind the view matrix to - */ - bindView(effect) { - if (!this._useUBO) { - effect.setMatrix("view", this.getScene().getViewMatrix()); - } - else { - this._needToBindSceneUbo = true; - } - } - /** - * Binds the view projection and projection matrices to the effect - * @param effect defines the effect to bind the view projection and projection matrices to - */ - bindViewProjection(effect) { - if (!this._useUBO) { - effect.setMatrix("viewProjection", this.getScene().getTransformMatrix()); - effect.setMatrix("projection", this.getScene().getProjectionMatrix()); - } - else { - this._needToBindSceneUbo = true; - } - } - /** - * Binds the view matrix to the effect - * @param effect defines the effect to bind the view matrix to - * @param variableName name of the shader variable that will hold the eye position - */ - bindEyePosition(effect, variableName) { - if (!this._useUBO) { - this._scene.bindEyePosition(effect, variableName); - } - else { - this._needToBindSceneUbo = true; - } - } - /** - * Processes to execute after binding the material to a mesh - * @param mesh defines the rendered mesh - * @param effect - */ - _afterBind(mesh, effect = null) { - this._scene._cachedMaterial = this; - if (this._needToBindSceneUbo) { - if (effect) { - this._needToBindSceneUbo = false; - MaterialHelper.BindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer()); - this._scene.finalizeSceneUbo(); - } - } - if (mesh) { - this._scene._cachedVisibility = mesh.visibility; - } - else { - this._scene._cachedVisibility = 1; - } - if (this._onBindObservable && mesh) { - this._onBindObservable.notifyObservers(mesh); - } - if (this.disableDepthWrite) { - const engine = this._scene.getEngine(); - this._cachedDepthWriteState = engine.getDepthWrite(); - engine.setDepthWrite(false); - } - if (this.disableColorWrite) { - const engine = this._scene.getEngine(); - this._cachedColorWriteState = engine.getColorWrite(); - engine.setColorWrite(false); - } - if (this.depthFunction !== 0) { - const engine = this._scene.getEngine(); - this._cachedDepthFunctionState = engine.getDepthFunction() || 0; - engine.setDepthFunction(this.depthFunction); - } - } - /** - * Unbinds the material from the mesh - */ - unbind() { - if (this._onUnBindObservable) { - this._onUnBindObservable.notifyObservers(this); - } - if (this.depthFunction !== 0) { - const engine = this._scene.getEngine(); - engine.setDepthFunction(this._cachedDepthFunctionState); - } - if (this.disableDepthWrite) { - const engine = this._scene.getEngine(); - engine.setDepthWrite(this._cachedDepthWriteState); - } - if (this.disableColorWrite) { - const engine = this._scene.getEngine(); - engine.setColorWrite(this._cachedColorWriteState); - } - } - /** - * Returns the animatable textures. - * @returns - Array of animatable textures. - */ - getAnimatables() { - this._eventInfo.animatables = []; - this._callbackPluginEventGeneric(materialPluginEvent_MaterialPluginEvent.GetAnimatables, this._eventInfo); - return this._eventInfo.animatables; - } - /** - * Gets the active textures from the material - * @returns an array of textures - */ - getActiveTextures() { - this._eventInfo.activeTextures = []; - this._callbackPluginEventGeneric(materialPluginEvent_MaterialPluginEvent.GetActiveTextures, this._eventInfo); - return this._eventInfo.activeTextures; - } - /** - * Specifies if the material uses a texture - * @param texture defines the texture to check against the material - * @returns a boolean specifying if the material uses the texture - */ - hasTexture(texture) { - this._eventInfo.hasTexture = false; - this._eventInfo.texture = texture; - this._callbackPluginEventGeneric(materialPluginEvent_MaterialPluginEvent.HasTexture, this._eventInfo); - return this._eventInfo.hasTexture; - } - /** - * Makes a duplicate of the material, and gives it a new name - * @param name defines the new name for the duplicated material - * @returns the cloned material - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - clone(name) { - return null; - } - _clonePlugins(targetMaterial, rootUrl) { - const serializationObject = {}; - // Create plugins in targetMaterial in case they don't exist - this._serializePlugins(serializationObject); - material_Material._parsePlugins(serializationObject, targetMaterial, this._scene, rootUrl); - // Copy the properties of the current plugins to the cloned material's plugins - if (this.pluginManager) { - for (const plugin of this.pluginManager._plugins) { - const targetPlugin = targetMaterial.pluginManager.getPlugin(plugin.name); - plugin.copyTo(targetPlugin); - } - } - } - /** - * Gets the meshes bound to the material - * @returns an array of meshes bound to the material - */ - getBindedMeshes() { - if (this.meshMap) { - const result = new Array(); - for (const meshId in this.meshMap) { - const mesh = this.meshMap[meshId]; - if (mesh) { - result.push(mesh); - } - } - return result; - } - else { - const meshes = this._scene.meshes; - return meshes.filter((mesh) => mesh.material === this); - } - } - /** - * Force shader compilation - * @param mesh defines the mesh associated with this material - * @param onCompiled defines a function to execute once the material is compiled - * @param options defines the options to configure the compilation - * @param onError defines a function to execute if the material fails compiling - */ - forceCompilation(mesh, onCompiled, options, onError) { - const localOptions = Object.assign({ clipPlane: false, useInstances: false }, options); - const scene = this.getScene(); - const currentHotSwapingState = this.allowShaderHotSwapping; - this.allowShaderHotSwapping = false; // Turned off to let us evaluate the real compilation state - const checkReady = () => { - if (!this._scene || !this._scene.getEngine()) { - return; - } - const clipPlaneState = scene.clipPlane; - if (localOptions.clipPlane) { - scene.clipPlane = new math_plane_Plane(0, 0, 0, 1); - } - if (this._storeEffectOnSubMeshes) { - let allDone = true, lastError = null; - if (mesh.subMeshes) { - const tempSubMesh = new subMesh_SubMesh(0, 0, 0, 0, 0, mesh, undefined, false, false); - if (tempSubMesh.materialDefines) { - tempSubMesh.materialDefines._renderId = -1; - } - if (!this.isReadyForSubMesh(mesh, tempSubMesh, localOptions.useInstances)) { - if (tempSubMesh.effect && tempSubMesh.effect.getCompilationError() && tempSubMesh.effect.allFallbacksProcessed()) { - lastError = tempSubMesh.effect.getCompilationError(); - } - else { - allDone = false; - setTimeout(checkReady, 16); - } - } - } - if (allDone) { - this.allowShaderHotSwapping = currentHotSwapingState; - if (lastError) { - if (onError) { - onError(lastError); - } - } - if (onCompiled) { - onCompiled(this); - } - } - } - else { - if (this.isReady()) { - this.allowShaderHotSwapping = currentHotSwapingState; - if (onCompiled) { - onCompiled(this); - } - } - else { - setTimeout(checkReady, 16); - } - } - if (localOptions.clipPlane) { - scene.clipPlane = clipPlaneState; - } - }; - checkReady(); - } - /** - * Force shader compilation - * @param mesh defines the mesh that will use this material - * @param options defines additional options for compiling the shaders - * @returns a promise that resolves when the compilation completes - */ - forceCompilationAsync(mesh, options) { - return new Promise((resolve, reject) => { - this.forceCompilation(mesh, () => { - resolve(); - }, options, (reason) => { - reject(reason); - }); - }); - } - /** - * Marks a define in the material to indicate that it needs to be re-computed - * @param flag defines a flag used to determine which parts of the material have to be marked as dirty - */ - markAsDirty(flag) { - if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) { - return; - } - material_Material._DirtyCallbackArray.length = 0; - if (flag & material_Material.TextureDirtyFlag) { - material_Material._DirtyCallbackArray.push(material_Material._TextureDirtyCallBack); - } - if (flag & material_Material.LightDirtyFlag) { - material_Material._DirtyCallbackArray.push(material_Material._LightsDirtyCallBack); - } - if (flag & material_Material.FresnelDirtyFlag) { - material_Material._DirtyCallbackArray.push(material_Material._FresnelDirtyCallBack); - } - if (flag & material_Material.AttributesDirtyFlag) { - material_Material._DirtyCallbackArray.push(material_Material._AttributeDirtyCallBack); - } - if (flag & material_Material.MiscDirtyFlag) { - material_Material._DirtyCallbackArray.push(material_Material._MiscDirtyCallBack); - } - if (flag & material_Material.PrePassDirtyFlag) { - material_Material._DirtyCallbackArray.push(material_Material._PrePassDirtyCallBack); - } - if (material_Material._DirtyCallbackArray.length) { - this._markAllSubMeshesAsDirty(material_Material._RunDirtyCallBacks); - } - this.getScene().resetCachedMaterial(); - } - /** - * Resets the draw wrappers cache for all submeshes that are using this material - */ - resetDrawCache() { - const meshes = this.getScene().meshes; - for (const mesh of meshes) { - if (!mesh.subMeshes) { - continue; - } - for (const subMesh of mesh.subMeshes) { - if (subMesh.getMaterial() !== this) { - continue; - } - subMesh.resetDrawCache(); - } - } - } - /** - * Marks all submeshes of a material to indicate that their material defines need to be re-calculated - * @param func defines a function which checks material defines against the submeshes - */ - _markAllSubMeshesAsDirty(func) { - if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) { - return; - } - const meshes = this.getScene().meshes; - for (const mesh of meshes) { - if (!mesh.subMeshes) { - continue; - } - for (const subMesh of mesh.subMeshes) { - // We want to skip the submeshes which are not using this material or which have not yet rendered at least once - if (subMesh.getMaterial(false) !== this) { - continue; - } - for (const drawWrapper of subMesh._drawWrappers) { - if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) { - continue; - } - if (this._materialContext === drawWrapper.materialContext) { - func(drawWrapper.defines); - } - } - } - } - } - /** - * Indicates that the scene should check if the rendering now needs a prepass - */ - _markScenePrePassDirty() { - if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) { - return; - } - const prePassRenderer = this.getScene().enablePrePassRenderer(); - if (prePassRenderer) { - prePassRenderer.markAsDirty(); - } - } - /** - * Indicates that we need to re-calculated for all submeshes - */ - _markAllSubMeshesAsAllDirty() { - this._markAllSubMeshesAsDirty(material_Material._AllDirtyCallBack); - } - /** - * Indicates that image processing needs to be re-calculated for all submeshes - */ - _markAllSubMeshesAsImageProcessingDirty() { - this._markAllSubMeshesAsDirty(material_Material._ImageProcessingDirtyCallBack); - } - /** - * Indicates that textures need to be re-calculated for all submeshes - */ - _markAllSubMeshesAsTexturesDirty() { - this._markAllSubMeshesAsDirty(material_Material._TextureDirtyCallBack); - } - /** - * Indicates that fresnel needs to be re-calculated for all submeshes - */ - _markAllSubMeshesAsFresnelDirty() { - this._markAllSubMeshesAsDirty(material_Material._FresnelDirtyCallBack); - } - /** - * Indicates that fresnel and misc need to be re-calculated for all submeshes - */ - _markAllSubMeshesAsFresnelAndMiscDirty() { - this._markAllSubMeshesAsDirty(material_Material._FresnelAndMiscDirtyCallBack); - } - /** - * Indicates that lights need to be re-calculated for all submeshes - */ - _markAllSubMeshesAsLightsDirty() { - this._markAllSubMeshesAsDirty(material_Material._LightsDirtyCallBack); - } - /** - * Indicates that attributes need to be re-calculated for all submeshes - */ - _markAllSubMeshesAsAttributesDirty() { - this._markAllSubMeshesAsDirty(material_Material._AttributeDirtyCallBack); - } - /** - * Indicates that misc needs to be re-calculated for all submeshes - */ - _markAllSubMeshesAsMiscDirty() { - this._markAllSubMeshesAsDirty(material_Material._MiscDirtyCallBack); - } - /** - * Indicates that prepass needs to be re-calculated for all submeshes - */ - _markAllSubMeshesAsPrePassDirty() { - this._markAllSubMeshesAsDirty(material_Material._MiscDirtyCallBack); - } - /** - * Indicates that textures and misc need to be re-calculated for all submeshes - */ - _markAllSubMeshesAsTexturesAndMiscDirty() { - this._markAllSubMeshesAsDirty(material_Material._TextureAndMiscDirtyCallBack); - } - _checkScenePerformancePriority() { - if (this._scene.performancePriority !== ScenePerformancePriority.BackwardCompatible) { - this.checkReadyOnlyOnce = true; - // re-set the flag when the perf priority changes - const observer = this._scene.onScenePerformancePriorityChangedObservable.addOnce(() => { - this.checkReadyOnlyOnce = false; - }); - // if this material is disposed before the scene is disposed, cleanup the observer - this.onDisposeObservable.add(() => { - this._scene.onScenePerformancePriorityChangedObservable.remove(observer); - }); - } - } - /** - * Sets the required values to the prepass renderer. - * @param prePassRenderer defines the prepass renderer to setup. - * @returns true if the pre pass is needed. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - setPrePassRenderer(prePassRenderer) { - // Do Nothing by default - return false; - } - /** - * Disposes the material - * @param forceDisposeEffect specifies if effects should be forcefully disposed - * @param forceDisposeTextures specifies if textures should be forcefully disposed - * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh - */ - dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { - const scene = this.getScene(); - // Animations - scene.stopAnimation(this); - scene.freeProcessedMaterials(); - // Remove from scene - scene.removeMaterial(this); - this._eventInfo.forceDisposeTextures = forceDisposeTextures; - this._callbackPluginEventGeneric(materialPluginEvent_MaterialPluginEvent.Disposed, this._eventInfo); - if (this._parentContainer) { - const index = this._parentContainer.materials.indexOf(this); - if (index > -1) { - this._parentContainer.materials.splice(index, 1); - } - this._parentContainer = null; - } - if (notBoundToMesh !== true) { - // Remove from meshes - if (this.meshMap) { - for (const meshId in this.meshMap) { - const mesh = this.meshMap[meshId]; - if (mesh) { - mesh.material = null; // will set the entry in the map to undefined - this.releaseVertexArrayObject(mesh, forceDisposeEffect); - } - } - } - else { - const meshes = scene.meshes; - for (const mesh of meshes) { - if (mesh.material === this && !mesh.sourceMesh) { - mesh.material = null; - this.releaseVertexArrayObject(mesh, forceDisposeEffect); - } - } - } - } - this._uniformBuffer.dispose(); - // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect - if (forceDisposeEffect && this._drawWrapper.effect) { - if (!this._storeEffectOnSubMeshes) { - this._drawWrapper.effect.dispose(); - } - this._drawWrapper.effect = null; - } - this.metadata = null; - // Callback - this.onDisposeObservable.notifyObservers(this); - this.onDisposeObservable.clear(); - if (this._onBindObservable) { - this._onBindObservable.clear(); - } - if (this._onUnBindObservable) { - this._onUnBindObservable.clear(); - } - if (this._onEffectCreatedObservable) { - this._onEffectCreatedObservable.clear(); - } - if (this._eventInfo) { - this._eventInfo = {}; - } - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - releaseVertexArrayObject(mesh, forceDisposeEffect) { - if (mesh.geometry) { - const geometry = mesh.geometry; - if (this._storeEffectOnSubMeshes) { - for (const subMesh of mesh.subMeshes) { - geometry._releaseVertexArrayObject(subMesh.effect); - if (forceDisposeEffect && subMesh.effect) { - subMesh.effect.dispose(); - } - } - } - else { - geometry._releaseVertexArrayObject(this._drawWrapper.effect); - } - } - } - /** - * Serializes this material - * @returns the serialized material object - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.stencil = this.stencil.serialize(); - serializationObject.uniqueId = this.uniqueId; - this._serializePlugins(serializationObject); - return serializationObject; - } - _serializePlugins(serializationObject) { - serializationObject.plugins = {}; - if (this.pluginManager) { - for (const plugin of this.pluginManager._plugins) { - serializationObject.plugins[plugin.getClassName()] = plugin.serialize(); - } - } - } - /** - * Creates a material from parsed material data - * @param parsedMaterial defines parsed material data - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures - * @returns a new material - */ - static Parse(parsedMaterial, scene, rootUrl) { - if (!parsedMaterial.customType) { - parsedMaterial.customType = "BABYLON.StandardMaterial"; - } - else if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) { - parsedMaterial.customType = "BABYLON.LegacyPBRMaterial"; - if (!BABYLON.LegacyPBRMaterial) { - logger_Logger.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."); - return null; - } - } - const materialType = tools_Tools.Instantiate(parsedMaterial.customType); - const material = materialType.Parse(parsedMaterial, scene, rootUrl); - material._loadedUniqueId = parsedMaterial.uniqueId; - return material; - } - static _parsePlugins(serializationObject, material, scene, rootUrl) { - var _a; - if (!serializationObject.plugins) { - return; - } - for (const pluginClassName in serializationObject.plugins) { - const pluginData = serializationObject.plugins[pluginClassName]; - let plugin = (_a = material.pluginManager) === null || _a === void 0 ? void 0 : _a.getPlugin(pluginData.name); - if (!plugin) { - const pluginClassType = tools_Tools.Instantiate("BABYLON." + pluginClassName); - if (pluginClassType) { - plugin = new pluginClassType(material); - } - } - plugin === null || plugin === void 0 ? void 0 : plugin.parse(pluginData, scene, rootUrl); - } - } -} -/** - * Returns the triangle fill mode - */ -material_Material.TriangleFillMode = 0; -/** - * Returns the wireframe mode - */ -material_Material.WireFrameFillMode = 1; -/** - * Returns the point fill mode - */ -material_Material.PointFillMode = 2; -/** - * Returns the point list draw mode - */ -material_Material.PointListDrawMode = 3; -/** - * Returns the line list draw mode - */ -material_Material.LineListDrawMode = 4; -/** - * Returns the line loop draw mode - */ -material_Material.LineLoopDrawMode = 5; -/** - * Returns the line strip draw mode - */ -material_Material.LineStripDrawMode = 6; -/** - * Returns the triangle strip draw mode - */ -material_Material.TriangleStripDrawMode = 7; -/** - * Returns the triangle fan draw mode - */ -material_Material.TriangleFanDrawMode = 8; -/** - * Stores the clock-wise side orientation - */ -material_Material.ClockWiseSideOrientation = 0; -/** - * Stores the counter clock-wise side orientation - */ -material_Material.CounterClockWiseSideOrientation = 1; -/** - * The dirty texture flag value - */ -material_Material.TextureDirtyFlag = 1; -/** - * The dirty light flag value - */ -material_Material.LightDirtyFlag = 2; -/** - * The dirty fresnel flag value - */ -material_Material.FresnelDirtyFlag = 4; -/** - * The dirty attribute flag value - */ -material_Material.AttributesDirtyFlag = 8; -/** - * The dirty misc flag value - */ -material_Material.MiscDirtyFlag = 16; -/** - * The dirty prepass flag value - */ -material_Material.PrePassDirtyFlag = 32; -/** - * The all dirty flag value - */ -material_Material.AllDirtyFlag = 63; -/** - * MaterialTransparencyMode: No transparency mode, Alpha channel is not use. - */ -material_Material.MATERIAL_OPAQUE = 0; -/** - * MaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value. - */ -material_Material.MATERIAL_ALPHATEST = 1; -/** - * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. - */ -material_Material.MATERIAL_ALPHABLEND = 2; -/** - * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. - * They are also discarded below the alpha cutoff threshold to improve performances. - */ -material_Material.MATERIAL_ALPHATESTANDBLEND = 3; -/** - * The Whiteout method is used to blend normals. - * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/ - */ -material_Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0; -/** - * The Reoriented Normal Mapping method is used to blend normals. - * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/ - */ -material_Material.MATERIAL_NORMALBLENDMETHOD_RNM = 1; -/** - * Event observable which raises global events common to all materials (like MaterialPluginEvent.Created) - */ -material_Material.OnEventObservable = new observable_Observable(); -material_Material._AllDirtyCallBack = (defines) => defines.markAllAsDirty(); -material_Material._ImageProcessingDirtyCallBack = (defines) => defines.markAsImageProcessingDirty(); -material_Material._TextureDirtyCallBack = (defines) => defines.markAsTexturesDirty(); -material_Material._FresnelDirtyCallBack = (defines) => defines.markAsFresnelDirty(); -material_Material._MiscDirtyCallBack = (defines) => defines.markAsMiscDirty(); -material_Material._PrePassDirtyCallBack = (defines) => defines.markAsPrePassDirty(); -material_Material._LightsDirtyCallBack = (defines) => defines.markAsLightDirty(); -material_Material._AttributeDirtyCallBack = (defines) => defines.markAsAttributesDirty(); -material_Material._FresnelAndMiscDirtyCallBack = (defines) => { - material_Material._FresnelDirtyCallBack(defines); - material_Material._MiscDirtyCallBack(defines); -}; -material_Material._TextureAndMiscDirtyCallBack = (defines) => { - material_Material._TextureDirtyCallBack(defines); - material_Material._MiscDirtyCallBack(defines); -}; -material_Material._DirtyCallbackArray = []; -material_Material._RunDirtyCallBacks = (defines) => { - for (const cb of material_Material._DirtyCallbackArray) { - cb(defines); - } -}; -__decorate([ - serialize() -], material_Material.prototype, "id", void 0); -__decorate([ - serialize() -], material_Material.prototype, "uniqueId", void 0); -__decorate([ - serialize() -], material_Material.prototype, "name", void 0); -__decorate([ - serialize() -], material_Material.prototype, "metadata", void 0); -__decorate([ - serialize() -], material_Material.prototype, "checkReadyOnEveryCall", void 0); -__decorate([ - serialize() -], material_Material.prototype, "checkReadyOnlyOnce", void 0); -__decorate([ - serialize() -], material_Material.prototype, "state", void 0); -__decorate([ - serialize("alpha") -], material_Material.prototype, "_alpha", void 0); -__decorate([ - serialize("backFaceCulling") -], material_Material.prototype, "_backFaceCulling", void 0); -__decorate([ - serialize("cullBackFaces") -], material_Material.prototype, "_cullBackFaces", void 0); -__decorate([ - serialize() -], material_Material.prototype, "sideOrientation", void 0); -__decorate([ - serialize("alphaMode") -], material_Material.prototype, "_alphaMode", void 0); -__decorate([ - serialize() -], material_Material.prototype, "_needDepthPrePass", void 0); -__decorate([ - serialize() -], material_Material.prototype, "disableDepthWrite", void 0); -__decorate([ - serialize() -], material_Material.prototype, "disableColorWrite", void 0); -__decorate([ - serialize() -], material_Material.prototype, "forceDepthWrite", void 0); -__decorate([ - serialize() -], material_Material.prototype, "depthFunction", void 0); -__decorate([ - serialize() -], material_Material.prototype, "separateCullingPass", void 0); -__decorate([ - serialize("fogEnabled") -], material_Material.prototype, "_fogEnabled", void 0); -__decorate([ - serialize() -], material_Material.prototype, "pointSize", void 0); -__decorate([ - serialize() -], material_Material.prototype, "zOffset", void 0); -__decorate([ - serialize() -], material_Material.prototype, "zOffsetUnits", void 0); -__decorate([ - serialize() -], material_Material.prototype, "pointsCloud", null); -__decorate([ - serialize() -], material_Material.prototype, "fillMode", null); -__decorate([ - serialize() -], material_Material.prototype, "transparencyMode", null); -//# sourceMappingURL=material.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/multiMaterial.js - - - -/** - * A multi-material is used to apply different materials to different parts of the same object without the need of - * separate meshes. This can be use to improve performances. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials - */ -class multiMaterial_MultiMaterial extends material_Material { - /** - * Gets or Sets the list of Materials used within the multi material. - * They need to be ordered according to the submeshes order in the associated mesh - */ - get subMaterials() { - return this._subMaterials; - } - set subMaterials(value) { - this._subMaterials = value; - this._hookArray(value); - } - /** - * Function used to align with Node.getChildren() - * @returns the list of Materials used within the multi material - */ - getChildren() { - return this.subMaterials; - } - /** - * Instantiates a new Multi Material - * A multi-material is used to apply different materials to different parts of the same object without the need of - * separate meshes. This can be use to improve performances. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials - * @param name Define the name in the scene - * @param scene Define the scene the material belongs to - */ - constructor(name, scene) { - super(name, scene, true); - /** @internal */ - this._waitingSubMaterialsUniqueIds = []; - this.getScene().addMultiMaterial(this); - this.subMaterials = new Array(); - this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material - } - _hookArray(array) { - const oldPush = array.push; - array.push = (...items) => { - const result = oldPush.apply(array, items); - this._markAllSubMeshesAsTexturesDirty(); - return result; - }; - const oldSplice = array.splice; - array.splice = (index, deleteCount) => { - const deleted = oldSplice.apply(array, [index, deleteCount]); - this._markAllSubMeshesAsTexturesDirty(); - return deleted; - }; - } - /** - * Get one of the submaterial by its index in the submaterials array - * @param index The index to look the sub material at - * @returns The Material if the index has been defined - */ - getSubMaterial(index) { - if (index < 0 || index >= this.subMaterials.length) { - return this.getScene().defaultMaterial; - } - return this.subMaterials[index]; - } - /** - * Get the list of active textures for the whole sub materials list. - * @returns All the textures that will be used during the rendering - */ - getActiveTextures() { - return super.getActiveTextures().concat(...this.subMaterials.map((subMaterial) => { - if (subMaterial) { - return subMaterial.getActiveTextures(); - } - else { - return []; - } - })); - } - /** - * Specifies if any sub-materials of this multi-material use a given texture. - * @param texture Defines the texture to check against this multi-material's sub-materials. - * @returns A boolean specifying if any sub-material of this multi-material uses the texture. - */ - hasTexture(texture) { - var _a; - if (super.hasTexture(texture)) { - return true; - } - for (let i = 0; i < this.subMaterials.length; i++) { - if ((_a = this.subMaterials[i]) === null || _a === void 0 ? void 0 : _a.hasTexture(texture)) { - return true; - } - } - return false; - } - /** - * Gets the current class name of the material e.g. "MultiMaterial" - * Mainly use in serialization. - * @returns the class name - */ - getClassName() { - return "MultiMaterial"; - } - /** - * Checks if the material is ready to render the requested sub mesh - * @param mesh Define the mesh the submesh belongs to - * @param subMesh Define the sub mesh to look readiness for - * @param useInstances Define whether or not the material is used with instances - * @returns true if ready, otherwise false - */ - isReadyForSubMesh(mesh, subMesh, useInstances) { - for (let index = 0; index < this.subMaterials.length; index++) { - const subMaterial = this.subMaterials[index]; - if (subMaterial) { - if (subMaterial._storeEffectOnSubMeshes) { - if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) { - return false; - } - continue; - } - if (!subMaterial.isReady(mesh)) { - return false; - } - } - } - return true; - } - /** - * Clones the current material and its related sub materials - * @param name Define the name of the newly cloned material - * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance - * @returns the cloned material - */ - clone(name, cloneChildren) { - const newMultiMaterial = new multiMaterial_MultiMaterial(name, this.getScene()); - for (let index = 0; index < this.subMaterials.length; index++) { - let subMaterial = null; - const current = this.subMaterials[index]; - if (cloneChildren && current) { - subMaterial = current.clone(name + "-" + current.name); - } - else { - subMaterial = this.subMaterials[index]; - } - newMultiMaterial.subMaterials.push(subMaterial); - } - return newMultiMaterial; - } - /** - * Serializes the materials into a JSON representation. - * @returns the JSON representation - */ - serialize() { - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.id = this.id; - serializationObject.uniqueId = this.uniqueId; - if (Tags) { - serializationObject.tags = Tags.GetTags(this); - } - serializationObject.materialsUniqueIds = []; - serializationObject.materials = []; - for (let matIndex = 0; matIndex < this.subMaterials.length; matIndex++) { - const subMat = this.subMaterials[matIndex]; - if (subMat) { - serializationObject.materialsUniqueIds.push(subMat.uniqueId); - serializationObject.materials.push(subMat.id); - } - else { - serializationObject.materialsUniqueIds.push(null); - serializationObject.materials.push(null); - } - } - return serializationObject; - } - /** - * Dispose the material and release its associated resources - * @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) - * @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) - * @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) - */ - dispose(forceDisposeEffect, forceDisposeTextures, forceDisposeChildren) { - const scene = this.getScene(); - if (!scene) { - return; - } - if (forceDisposeChildren) { - for (let index = 0; index < this.subMaterials.length; index++) { - const subMaterial = this.subMaterials[index]; - if (subMaterial) { - subMaterial.dispose(forceDisposeEffect, forceDisposeTextures); - } - } - } - const index = scene.multiMaterials.indexOf(this); - if (index >= 0) { - scene.multiMaterials.splice(index, 1); - } - super.dispose(forceDisposeEffect, forceDisposeTextures); - } - /** - * Creates a MultiMaterial from parsed MultiMaterial data. - * @param parsedMultiMaterial defines parsed MultiMaterial data. - * @param scene defines the hosting scene - * @returns a new MultiMaterial - */ - static ParseMultiMaterial(parsedMultiMaterial, scene) { - const multiMaterial = new multiMaterial_MultiMaterial(parsedMultiMaterial.name, scene); - multiMaterial.id = parsedMultiMaterial.id; - multiMaterial._loadedUniqueId = parsedMultiMaterial.uniqueId; - if (Tags) { - Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags); - } - if (parsedMultiMaterial.materialsUniqueIds) { - multiMaterial._waitingSubMaterialsUniqueIds = parsedMultiMaterial.materialsUniqueIds; - } - else { - parsedMultiMaterial.materials.forEach((subMatId) => multiMaterial.subMaterials.push(scene.getLastMaterialById(subMatId))); - } - return multiMaterial; - } -} -RegisterClass("BABYLON.MultiMaterial", multiMaterial_MultiMaterial); -//# sourceMappingURL=multiMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/meshLODLevel.js -/** - * Class used to represent a specific level of detail of a mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD - */ -class MeshLODLevel { - /** - * Creates a new LOD level - * @param distanceOrScreenCoverage defines either the distance or the screen coverage where this level should start being displayed - * @param mesh defines the mesh to use to render this level - */ - constructor( - /** 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*/ - distanceOrScreenCoverage, - /** Defines the mesh to use to render this level */ - mesh) { - this.distanceOrScreenCoverage = distanceOrScreenCoverage; - this.mesh = mesh; - } -} -//# sourceMappingURL=meshLODLevel.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/mesh.js - - - - - - - - - - - - - - - - - - - - - - - - - -/** - * @internal - **/ -class _CreationDataStorage { -} -/** - * @internal - **/ -class _InstanceDataStorage { - constructor() { - this.visibleInstances = {}; - this.batchCache = new _InstancesBatch(); - this.batchCacheReplacementModeInFrozenMode = new _InstancesBatch(); - this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances - } -} -/** - * @internal - **/ -class _InstancesBatch { - constructor() { - this.mustReturn = false; - this.visibleInstances = new Array(); - this.renderSelf = new Array(); - this.hardwareInstancedRendering = new Array(); - } -} -/** - * @internal - **/ -class _ThinInstanceDataStorage { - constructor() { - this.instancesCount = 0; - this.matrixBuffer = null; - this.previousMatrixBuffer = null; - this.matrixBufferSize = 32 * 16; // let's start with a maximum of 32 thin instances - this.matrixData = null; - this.boundingVectors = []; - this.worldMatrices = null; - } -} -/** - * @internal - **/ -class _InternalMeshDataInfo { - constructor() { - this._areNormalsFrozen = false; // Will be used by ribbons mainly - // Will be used to save a source mesh reference, If any - this._source = null; - // Will be used to for fast cloned mesh lookup - this.meshMap = null; - this._preActivateId = -1; - // eslint-disable-next-line @typescript-eslint/naming-convention - this._LODLevels = new Array(); - /** Alternative definition of LOD level, using screen coverage instead of distance */ - this._useLODScreenCoverage = false; - this._effectiveMaterial = null; - this._forcedInstanceCount = 0; - this._overrideRenderingFillMode = null; - } -} -/** - * Class used to represent renderable models - */ -class mesh_Mesh extends abstractMesh_AbstractMesh { - /** - * Gets the default side orientation. - * @param orientation the orientation to value to attempt to get - * @returns the default orientation - * @internal - */ - static _GetDefaultSideOrientation(orientation) { - return orientation || mesh_Mesh.FRONTSIDE; // works as Mesh.FRONTSIDE is 0 - } - /** - * Determines if the LOD levels are intended to be calculated using screen coverage (surface area ratio) instead of distance. - */ - get useLODScreenCoverage() { - return this._internalMeshDataInfo._useLODScreenCoverage; - } - set useLODScreenCoverage(value) { - this._internalMeshDataInfo._useLODScreenCoverage = value; - this._sortLODLevels(); - } - get computeBonesUsingShaders() { - return this._internalAbstractMeshDataInfo._computeBonesUsingShaders; - } - set computeBonesUsingShaders(value) { - if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) { - return; - } - if (value && this._internalMeshDataInfo._sourcePositions) { - // switch from software to GPU computation: we need to reset the vertex and normal buffers that have been updated by the software process - this.setVerticesData(buffer_VertexBuffer.PositionKind, this._internalMeshDataInfo._sourcePositions, true); - if (this._internalMeshDataInfo._sourceNormals) { - this.setVerticesData(buffer_VertexBuffer.NormalKind, this._internalMeshDataInfo._sourceNormals, true); - } - this._internalMeshDataInfo._sourcePositions = null; - this._internalMeshDataInfo._sourceNormals = null; - } - this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value; - this._markSubMeshesAsAttributesDirty(); - } - /** - * An event triggered before rendering the mesh - */ - get onBeforeRenderObservable() { - if (!this._internalMeshDataInfo._onBeforeRenderObservable) { - this._internalMeshDataInfo._onBeforeRenderObservable = new observable_Observable(); - } - return this._internalMeshDataInfo._onBeforeRenderObservable; - } - /** - * An event triggered before binding the mesh - */ - get onBeforeBindObservable() { - if (!this._internalMeshDataInfo._onBeforeBindObservable) { - this._internalMeshDataInfo._onBeforeBindObservable = new observable_Observable(); - } - return this._internalMeshDataInfo._onBeforeBindObservable; - } - /** - * An event triggered after rendering the mesh - */ - get onAfterRenderObservable() { - if (!this._internalMeshDataInfo._onAfterRenderObservable) { - this._internalMeshDataInfo._onAfterRenderObservable = new observable_Observable(); - } - return this._internalMeshDataInfo._onAfterRenderObservable; - } - /** - * An event triggeredbetween rendering pass when using separateCullingPass = true - */ - get onBetweenPassObservable() { - if (!this._internalMeshDataInfo._onBetweenPassObservable) { - this._internalMeshDataInfo._onBetweenPassObservable = new observable_Observable(); - } - return this._internalMeshDataInfo._onBetweenPassObservable; - } - /** - * An event triggered before drawing the mesh - */ - get onBeforeDrawObservable() { - if (!this._internalMeshDataInfo._onBeforeDrawObservable) { - this._internalMeshDataInfo._onBeforeDrawObservable = new observable_Observable(); - } - return this._internalMeshDataInfo._onBeforeDrawObservable; - } - /** - * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead - */ - set onBeforeDraw(callback) { - if (this._onBeforeDrawObserver) { - this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver); - } - this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback); - } - get hasInstances() { - return this.instances.length > 0; - } - get hasThinInstances() { - var _a; - return ((_a = this._thinInstanceDataStorage.instancesCount) !== null && _a !== void 0 ? _a : 0) > 0; - } - /** - * Gets or sets the forced number of instances to display. - * If 0 (default value), the number of instances is not forced and depends on the draw type - * (regular / instance / thin instances mesh) - */ - get forcedInstanceCount() { - return this._internalMeshDataInfo._forcedInstanceCount; - } - set forcedInstanceCount(count) { - this._internalMeshDataInfo._forcedInstanceCount = count; - } - /** - * Use this property to override the Material's fillMode value - */ - get overrideRenderingFillMode() { - return this._internalMeshDataInfo._overrideRenderingFillMode; - } - set overrideRenderingFillMode(fillMode) { - this._internalMeshDataInfo._overrideRenderingFillMode = fillMode; - } - /** - * Gets the source mesh (the one used to clone this one from) - */ - get source() { - return this._internalMeshDataInfo._source; - } - /** - * Gets the list of clones of this mesh - * The scene must have been constructed with useClonedMeshMap=true for this to work! - * Note that useClonedMeshMap=true is the default setting - */ - get cloneMeshMap() { - return this._internalMeshDataInfo.meshMap; - } - /** - * Gets or sets a boolean indicating that this mesh does not use index buffer - */ - get isUnIndexed() { - return this._unIndexed; - } - set isUnIndexed(value) { - if (this._unIndexed !== value) { - this._unIndexed = value; - this._markSubMeshesAsAttributesDirty(); - } - } - /** Gets the array buffer used to store the instanced buffer used for instances' world matrices */ - get worldMatrixInstancedBuffer() { - return this._instanceDataStorage.instancesData; - } - /** Gets the array buffer used to store the instanced buffer used for instances' previous world matrices */ - get previousWorldMatrixInstancedBuffer() { - return this._instanceDataStorage.instancesPreviousData; - } - /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */ - get manualUpdateOfWorldMatrixInstancedBuffer() { - return this._instanceDataStorage.manualUpdate; - } - set manualUpdateOfWorldMatrixInstancedBuffer(value) { - this._instanceDataStorage.manualUpdate = value; - } - /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */ - get manualUpdateOfPreviousWorldMatrixInstancedBuffer() { - return this._instanceDataStorage.previousManualUpdate; - } - set manualUpdateOfPreviousWorldMatrixInstancedBuffer(value) { - this._instanceDataStorage.previousManualUpdate = value; - } - /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices must be performed in all cases (and notably even in frozen mode) */ - get forceWorldMatrixInstancedBufferUpdate() { - return this._instanceDataStorage.forceMatrixUpdates; - } - set forceWorldMatrixInstancedBufferUpdate(value) { - this._instanceDataStorage.forceMatrixUpdates = value; - } - /** - * @constructor - * @param name The value used by scene.getMeshByName() to do a lookup. - * @param scene The scene to add this mesh to. - * @param parent The parent of this mesh, if it has one - * @param source An optional Mesh from which geometry is shared, cloned. - * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False. - * When false, achieved by calling a clone(), also passing False. - * This will make creation of children, recursive. - * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True. - */ - constructor(name, scene = null, parent = null, source = null, doNotCloneChildren, clonePhysicsImpostor = true) { - super(name, scene); - // Internal data - this._internalMeshDataInfo = new _InternalMeshDataInfo(); - // Members - /** - * Gets the delay loading state of the mesh (when delay loading is turned on) - * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/incrementalLoading - */ - this.delayLoadState = 0; - /** - * Gets the list of instances created from this mesh - * it is not supposed to be modified manually. - * Note also that the order of the InstancedMesh wihin the array is not significant and might change. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances - */ - this.instances = new Array(); - // Private - /** @internal */ - this._creationDataStorage = null; - /** @internal */ - this._geometry = null; - /** @internal */ - this._instanceDataStorage = new _InstanceDataStorage(); - /** @internal */ - this._thinInstanceDataStorage = new _ThinInstanceDataStorage(); - /** @internal */ - this._shouldGenerateFlatShading = false; - // Use by builder only to know what orientation were the mesh build in. - /** @internal */ - this._originalBuilderSideOrientation = mesh_Mesh.DEFAULTSIDE; - /** - * Use this property to change the original side orientation defined at construction time - */ - this.overrideMaterialSideOrientation = null; - /** - * Gets or sets a boolean indicating whether to render ignoring the active camera's max z setting. (false by default) - * You should not mix meshes that have this property set to true with meshes that have it set to false if they all write - * to the depth buffer, because the z-values are not comparable in the two cases and you will get rendering artifacts if you do. - * You can set the property to true for meshes that do not write to the depth buffer, or set the same value (either false or true) otherwise. - * Note this will reduce performance when set to true. - */ - this.ignoreCameraMaxZ = false; - scene = this.getScene(); - this._onBeforeDraw = (isInstance, world, effectiveMaterial) => { - if (isInstance && effectiveMaterial) { - if (this._uniformBuffer) { - this.transferToEffect(world); - } - else { - effectiveMaterial.bindOnlyWorldMatrix(world); - } - } - }; - if (source) { - // Geometry - if (source._geometry) { - source._geometry.applyToMesh(this); - } - // Deep copy - DeepCopier.DeepCopy(source, this, [ - "name", - "material", - "skeleton", - "instances", - "parent", - "uniqueId", - "source", - "metadata", - "morphTargetManager", - "hasInstances", - "worldMatrixInstancedBuffer", - "previousWorldMatrixInstancedBuffer", - "hasLODLevels", - "geometry", - "isBlocked", - "areNormalsFrozen", - "facetNb", - "isFacetDataEnabled", - "lightSources", - "useBones", - "isAnInstance", - "collider", - "edgesRenderer", - "forward", - "up", - "right", - "absolutePosition", - "absoluteScaling", - "absoluteRotationQuaternion", - "isWorldMatrixFrozen", - "nonUniformScaling", - "behaviors", - "worldMatrixFromCache", - "hasThinInstances", - "cloneMeshMap", - "hasBoundingInfo", - "physicsBody", - "physicsImpostor", - ], ["_poseMatrix"]); - // Source mesh - this._internalMeshDataInfo._source = source; - if (scene.useClonedMeshMap) { - if (!source._internalMeshDataInfo.meshMap) { - source._internalMeshDataInfo.meshMap = {}; - } - source._internalMeshDataInfo.meshMap[this.uniqueId] = this; - } - // Construction Params - // Clone parameters allowing mesh to be updated in case of parametric shapes. - this._originalBuilderSideOrientation = source._originalBuilderSideOrientation; - this._creationDataStorage = source._creationDataStorage; - // Animation ranges - if (source._ranges) { - const ranges = source._ranges; - for (const name in ranges) { - if (!Object.prototype.hasOwnProperty.call(ranges, name)) { - continue; - } - if (!ranges[name]) { - continue; - } - this.createAnimationRange(name, ranges[name].from, ranges[name].to); - } - } - // Metadata - if (source.metadata && source.metadata.clone) { - this.metadata = source.metadata.clone(); - } - else { - this.metadata = source.metadata; - } - this._internalMetadata = source._internalMetadata; - // Tags - if (Tags && Tags.HasTags(source)) { - Tags.AddTagsTo(this, Tags.GetTags(source, true)); - } - // Enabled. We shouldn't need to check the source's ancestors, as this mesh - // will have the same ones. - this.setEnabled(source.isEnabled(false)); - // Parent - this.parent = source.parent; - // Pivot - this.setPivotMatrix(source.getPivotMatrix()); - this.id = name + "." + source.id; - // Material - this.material = source.material; - if (!doNotCloneChildren) { - // Children - const directDescendants = source.getDescendants(true); - for (let index = 0; index < directDescendants.length; index++) { - const child = directDescendants[index]; - if (child.clone) { - child.clone(name + "." + child.name, this); - } - } - } - // Morphs - if (source.morphTargetManager) { - this.morphTargetManager = source.morphTargetManager; - } - // Physics clone - if (scene.getPhysicsEngine) { - const physicsEngine = scene.getPhysicsEngine(); - if (clonePhysicsImpostor && physicsEngine) { - if (physicsEngine.getPluginVersion() === 1) { - const impostor = physicsEngine.getImpostorForPhysicsObject(source); - if (impostor) { - this.physicsImpostor = impostor.clone(this); - } - } - else if (physicsEngine.getPluginVersion() === 2) { - if (source.physicsBody) { - source.physicsBody.clone(this); - } - } - } - } - // Particles - for (let index = 0; index < scene.particleSystems.length; index++) { - const system = scene.particleSystems[index]; - if (system.emitter === source) { - system.clone(system.name, this); - } - } - // Skeleton - this.skeleton = source.skeleton; - this.refreshBoundingInfo(true, true); - this.computeWorldMatrix(true); - } - // Parent - if (parent !== null) { - this.parent = parent; - } - this._instanceDataStorage.hardwareInstancedRendering = this.getEngine().getCaps().instancedArrays; - this._internalMeshDataInfo._onMeshReadyObserverAdded = (observer) => { - // only notify once! then unregister the observer - observer.unregisterOnNextCall = true; - if (this.isReady(true)) { - this.onMeshReadyObservable.notifyObservers(this); - } - else { - if (!this._internalMeshDataInfo._checkReadinessObserver) { - this._internalMeshDataInfo._checkReadinessObserver = this._scene.onBeforeRenderObservable.add(() => { - // check for complete readiness - if (this.isReady(true)) { - this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver); - this._internalMeshDataInfo._checkReadinessObserver = null; - this.onMeshReadyObservable.notifyObservers(this); - } - }); - } - } - }; - this.onMeshReadyObservable = new observable_Observable(this._internalMeshDataInfo._onMeshReadyObserverAdded); - if (source) { - source.onClonedObservable.notifyObservers(this); - } - } - instantiateHierarchy(newParent = null, options, onNewNodeCreated) { - const instance = this.getTotalVertices() === 0 || (options && options.doNotInstantiate && (options.doNotInstantiate === true || options.doNotInstantiate(this))) - ? this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true) - : this.createInstance("instance of " + (this.name || this.id)); - instance.parent = newParent || this.parent; - instance.position = this.position.clone(); - instance.scaling = this.scaling.clone(); - if (this.rotationQuaternion) { - instance.rotationQuaternion = this.rotationQuaternion.clone(); - } - else { - instance.rotation = this.rotation.clone(); - } - if (onNewNodeCreated) { - onNewNodeCreated(this, instance); - } - for (const child of this.getChildTransformNodes(true)) { - // instancedMesh should have a different sourced mesh - if (child.getClassName() === "InstancedMesh" && instance.getClassName() === "Mesh" && child.sourceMesh === this) { - child.instantiateHierarchy(instance, { - doNotInstantiate: (options && options.doNotInstantiate) || false, - newSourcedMesh: instance, - }, onNewNodeCreated); - } - else { - child.instantiateHierarchy(instance, options, onNewNodeCreated); - } - } - return instance; - } - /** - * Gets the class name - * @returns the string "Mesh". - */ - getClassName() { - return "Mesh"; - } - /** @internal */ - get _isMesh() { - return true; - } - /** - * Returns a description of this mesh - * @param fullDetails define if full details about this mesh must be used - * @returns a descriptive string representing this mesh - */ - toString(fullDetails) { - let ret = super.toString(fullDetails); - ret += ", n vertices: " + this.getTotalVertices(); - ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : this.parent ? this.parent.name : "NONE"); - if (this.animations) { - for (let i = 0; i < this.animations.length; i++) { - ret += ", animation[0]: " + this.animations[i].toString(fullDetails); - } - } - if (fullDetails) { - if (this._geometry) { - const ib = this.getIndices(); - const vb = this.getVerticesData(buffer_VertexBuffer.PositionKind); - if (vb && ib) { - ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO"); - } - } - else { - ret += ", flat shading: UNKNOWN"; - } - } - return ret; - } - /** @internal */ - _unBindEffect() { - super._unBindEffect(); - for (const instance of this.instances) { - instance._unBindEffect(); - } - } - /** - * Gets a boolean indicating if this mesh has LOD - */ - get hasLODLevels() { - return this._internalMeshDataInfo._LODLevels.length > 0; - } - /** - * Gets the list of MeshLODLevel associated with the current mesh - * @returns an array of MeshLODLevel - */ - getLODLevels() { - return this._internalMeshDataInfo._LODLevels; - } - _sortLODLevels() { - const sortingOrderFactor = this._internalMeshDataInfo._useLODScreenCoverage ? -1 : 1; - this._internalMeshDataInfo._LODLevels.sort((a, b) => { - if (a.distanceOrScreenCoverage < b.distanceOrScreenCoverage) { - return sortingOrderFactor; - } - if (a.distanceOrScreenCoverage > b.distanceOrScreenCoverage) { - return -sortingOrderFactor; - } - return 0; - }); - } - /** - * Add a mesh as LOD level triggered at the given distance. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD - * @param distanceOrScreenCoverage Either distance from the center of the object to show this level or the screen coverage if `useScreenCoverage` is set to `true`. - * If screen coverage, value is a fraction of the screen's total surface, between 0 and 1. - * Example Playground for distance https://playground.babylonjs.com/#QE7KM#197 - * Example Playground for screen coverage https://playground.babylonjs.com/#QE7KM#196 - * @param mesh The mesh to be added as LOD level (can be null) - * @returns This mesh (for chaining) - */ - addLODLevel(distanceOrScreenCoverage, mesh) { - if (mesh && mesh._masterMesh) { - logger_Logger.Warn("You cannot use a mesh as LOD level twice"); - return this; - } - const level = new MeshLODLevel(distanceOrScreenCoverage, mesh); - this._internalMeshDataInfo._LODLevels.push(level); - if (mesh) { - mesh._masterMesh = this; - } - this._sortLODLevels(); - return this; - } - /** - * Returns the LOD level mesh at the passed distance or null if not found. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD - * @param distance The distance from the center of the object to show this level - * @returns a Mesh or `null` - */ - getLODLevelAtDistance(distance) { - const internalDataInfo = this._internalMeshDataInfo; - for (let index = 0; index < internalDataInfo._LODLevels.length; index++) { - const level = internalDataInfo._LODLevels[index]; - if (level.distanceOrScreenCoverage === distance) { - return level.mesh; - } - } - return null; - } - /** - * Remove a mesh from the LOD array - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD - * @param mesh defines the mesh to be removed - * @returns This mesh (for chaining) - */ - removeLODLevel(mesh) { - const internalDataInfo = this._internalMeshDataInfo; - for (let index = 0; index < internalDataInfo._LODLevels.length; index++) { - if (internalDataInfo._LODLevels[index].mesh === mesh) { - internalDataInfo._LODLevels.splice(index, 1); - if (mesh) { - mesh._masterMesh = null; - } - } - } - this._sortLODLevels(); - return this; - } - /** - * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD - * @param camera defines the camera to use to compute distance - * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh - * @returns This mesh (for chaining) - */ - getLOD(camera, boundingSphere) { - const internalDataInfo = this._internalMeshDataInfo; - if (!internalDataInfo._LODLevels || internalDataInfo._LODLevels.length === 0) { - return this; - } - const bSphere = boundingSphere || this.getBoundingInfo().boundingSphere; - const distanceToCamera = camera.mode === camera_Camera.ORTHOGRAPHIC_CAMERA ? camera.minZ : bSphere.centerWorld.subtract(camera.globalPosition).length(); - let compareValue = distanceToCamera; - let compareSign = 1; - if (internalDataInfo._useLODScreenCoverage) { - const screenArea = camera.screenArea; - let meshArea = (bSphere.radiusWorld * camera.minZ) / distanceToCamera; - meshArea = meshArea * meshArea * Math.PI; - compareValue = meshArea / screenArea; - compareSign = -1; - } - if (compareSign * internalDataInfo._LODLevels[internalDataInfo._LODLevels.length - 1].distanceOrScreenCoverage > compareSign * compareValue) { - if (this.onLODLevelSelection) { - this.onLODLevelSelection(compareValue, this, this); - } - return this; - } - for (let index = 0; index < internalDataInfo._LODLevels.length; index++) { - const level = internalDataInfo._LODLevels[index]; - if (compareSign * level.distanceOrScreenCoverage < compareSign * compareValue) { - if (level.mesh) { - if (level.mesh.delayLoadState === 4) { - level.mesh._checkDelayState(); - return this; - } - if (level.mesh.delayLoadState === 2) { - return this; - } - level.mesh._preActivate(); - level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache); - } - if (this.onLODLevelSelection) { - this.onLODLevelSelection(compareValue, this, level.mesh); - } - return level.mesh; - } - } - if (this.onLODLevelSelection) { - this.onLODLevelSelection(compareValue, this, this); - } - return this; - } - /** - * Gets the mesh internal Geometry object - */ - get geometry() { - return this._geometry; - } - /** - * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry. - * @returns the total number of vertices - */ - getTotalVertices() { - if (this._geometry === null || this._geometry === undefined) { - return 0; - } - return this._geometry.getTotalVertices(); - } - /** - * Returns the content of an associated vertex buffer - * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values : - * - VertexBuffer.PositionKind - * - VertexBuffer.UVKind - * - VertexBuffer.UV2Kind - * - VertexBuffer.UV3Kind - * - VertexBuffer.UV4Kind - * - VertexBuffer.UV5Kind - * - VertexBuffer.UV6Kind - * - VertexBuffer.ColorKind - * - VertexBuffer.MatricesIndicesKind - * - VertexBuffer.MatricesIndicesExtraKind - * - VertexBuffer.MatricesWeightsKind - * - VertexBuffer.MatricesWeightsExtraKind - * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one - * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is - * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false - * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind. - */ - getVerticesData(kind, copyWhenShared, forceCopy, bypassInstanceData) { - var _a, _b; - if (!this._geometry) { - return null; - } - let data = bypassInstanceData - ? undefined - : (_b = (_a = this._userInstancedBuffersStorage) === null || _a === void 0 ? void 0 : _a.vertexBuffers[kind]) === null || _b === void 0 ? void 0 : _b.getFloatData(this.instances.length + 1, // +1 because the master mesh is not included in the instances array - forceCopy || (copyWhenShared && this._geometry.meshes.length !== 1)); - if (!data) { - data = this._geometry.getVerticesData(kind, copyWhenShared, forceCopy); - } - return data; - } - /** - * Returns the mesh VertexBuffer object from the requested `kind` - * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values : - * - VertexBuffer.PositionKind - * - VertexBuffer.NormalKind - * - VertexBuffer.UVKind - * - VertexBuffer.UV2Kind - * - VertexBuffer.UV3Kind - * - VertexBuffer.UV4Kind - * - VertexBuffer.UV5Kind - * - VertexBuffer.UV6Kind - * - VertexBuffer.ColorKind - * - VertexBuffer.MatricesIndicesKind - * - VertexBuffer.MatricesIndicesExtraKind - * - VertexBuffer.MatricesWeightsKind - * - VertexBuffer.MatricesWeightsExtraKind - * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false - * @returns a FloatArray or null if the mesh has no vertex buffer for this kind. - */ - getVertexBuffer(kind, bypassInstanceData) { - var _a, _b; - if (!this._geometry) { - return null; - } - return (_b = (bypassInstanceData ? undefined : (_a = this._userInstancedBuffersStorage) === null || _a === void 0 ? void 0 : _a.vertexBuffers[kind])) !== null && _b !== void 0 ? _b : this._geometry.getVertexBuffer(kind); - } - /** - * Tests if a specific vertex buffer is associated with this mesh - * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values : - * - VertexBuffer.PositionKind - * - VertexBuffer.NormalKind - * - VertexBuffer.UVKind - * - VertexBuffer.UV2Kind - * - VertexBuffer.UV3Kind - * - VertexBuffer.UV4Kind - * - VertexBuffer.UV5Kind - * - VertexBuffer.UV6Kind - * - VertexBuffer.ColorKind - * - VertexBuffer.MatricesIndicesKind - * - VertexBuffer.MatricesIndicesExtraKind - * - VertexBuffer.MatricesWeightsKind - * - VertexBuffer.MatricesWeightsExtraKind - * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false - * @returns a boolean - */ - isVerticesDataPresent(kind, bypassInstanceData) { - var _a; - if (!this._geometry) { - if (this._delayInfo) { - return this._delayInfo.indexOf(kind) !== -1; - } - return false; - } - return (!bypassInstanceData && ((_a = this._userInstancedBuffersStorage) === null || _a === void 0 ? void 0 : _a.vertexBuffers[kind]) !== undefined) || this._geometry.isVerticesDataPresent(kind); - } - /** - * Returns a boolean defining if the vertex data for the requested `kind` is updatable. - * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values : - * - VertexBuffer.PositionKind - * - VertexBuffer.UVKind - * - VertexBuffer.UV2Kind - * - VertexBuffer.UV3Kind - * - VertexBuffer.UV4Kind - * - VertexBuffer.UV5Kind - * - VertexBuffer.UV6Kind - * - VertexBuffer.ColorKind - * - VertexBuffer.MatricesIndicesKind - * - VertexBuffer.MatricesIndicesExtraKind - * - VertexBuffer.MatricesWeightsKind - * - VertexBuffer.MatricesWeightsExtraKind - * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false - * @returns a boolean - */ - isVertexBufferUpdatable(kind, bypassInstanceData) { - var _a; - if (!this._geometry) { - if (this._delayInfo) { - return this._delayInfo.indexOf(kind) !== -1; - } - return false; - } - if (!bypassInstanceData) { - const buffer = (_a = this._userInstancedBuffersStorage) === null || _a === void 0 ? void 0 : _a.vertexBuffers[kind]; - if (buffer) { - return buffer.isUpdatable(); - } - } - return this._geometry.isVertexBufferUpdatable(kind); - } - /** - * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh. - * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false - * @returns an array of strings - */ - getVerticesDataKinds(bypassInstanceData) { - if (!this._geometry) { - const result = new Array(); - if (this._delayInfo) { - this._delayInfo.forEach(function (kind) { - result.push(kind); - }); - } - return result; - } - const kinds = this._geometry.getVerticesDataKinds(); - if (!bypassInstanceData && this._userInstancedBuffersStorage) { - for (const kind in this._userInstancedBuffersStorage.vertexBuffers) { - if (kinds.indexOf(kind) === -1) { - kinds.push(kind); - } - } - } - return kinds; - } - /** - * Returns a positive integer : the total number of indices in this mesh geometry. - * @returns the numner of indices or zero if the mesh has no geometry. - */ - getTotalIndices() { - if (!this._geometry) { - return 0; - } - return this._geometry.getTotalIndices(); - } - /** - * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices. - * @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. - * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it - * @returns the indices array or an empty array if the mesh has no geometry - */ - getIndices(copyWhenShared, forceCopy) { - if (!this._geometry) { - return []; - } - return this._geometry.getIndices(copyWhenShared, forceCopy); - } - get isBlocked() { - return this._masterMesh !== null && this._masterMesh !== undefined; - } - /** - * Determine if the current mesh is ready to be rendered - * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) - * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default) - * @returns true if all associated assets are ready (material, textures, shaders) - */ - isReady(completeCheck = false, forceInstanceSupport = false) { - var _a, _b, _c, _d, _e, _f, _g; - if (this.delayLoadState === 2) { - return false; - } - if (!super.isReady(completeCheck)) { - return false; - } - if (!this.subMeshes || this.subMeshes.length === 0) { - return true; - } - if (!completeCheck) { - return true; - } - const engine = this.getEngine(); - const scene = this.getScene(); - const hardwareInstancedRendering = forceInstanceSupport || (engine.getCaps().instancedArrays && (this.instances.length > 0 || this.hasThinInstances)); - this.computeWorldMatrix(); - const mat = this.material || scene.defaultMaterial; - if (mat) { - if (mat._storeEffectOnSubMeshes) { - for (const subMesh of this.subMeshes) { - const effectiveMaterial = subMesh.getMaterial(); - if (effectiveMaterial) { - if (effectiveMaterial._storeEffectOnSubMeshes) { - if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) { - return false; - } - } - else { - if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) { - return false; - } - } - } - } - } - else { - if (!mat.isReady(this, hardwareInstancedRendering)) { - return false; - } - } - } - // Shadows - const currentRenderPassId = engine.currentRenderPassId; - for (const light of this.lightSources) { - const generators = light.getShadowGenerators(); - if (!generators) { - continue; - } - const iterator = generators.values(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const generator = key.value; - if (generator && (!((_a = generator.getShadowMap()) === null || _a === void 0 ? void 0 : _a.renderList) || (((_b = generator.getShadowMap()) === null || _b === void 0 ? void 0 : _b.renderList) && ((_d = (_c = generator.getShadowMap()) === null || _c === void 0 ? void 0 : _c.renderList) === null || _d === void 0 ? void 0 : _d.indexOf(this)) !== -1))) { - const shadowMap = generator.getShadowMap(); - const renderPassIds = (_e = shadowMap.renderPassIds) !== null && _e !== void 0 ? _e : [engine.currentRenderPassId]; - for (let p = 0; p < renderPassIds.length; ++p) { - engine.currentRenderPassId = renderPassIds[p]; - for (const subMesh of this.subMeshes) { - if (!generator.isReady(subMesh, hardwareInstancedRendering, (_g = (_f = subMesh.getMaterial()) === null || _f === void 0 ? void 0 : _f.needAlphaBlendingForMesh(this)) !== null && _g !== void 0 ? _g : false)) { - engine.currentRenderPassId = currentRenderPassId; - return false; - } - } - } - engine.currentRenderPassId = currentRenderPassId; - } - } - } - // LOD - for (const lod of this._internalMeshDataInfo._LODLevels) { - if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) { - return false; - } - } - return true; - } - /** - * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes. - */ - get areNormalsFrozen() { - return this._internalMeshDataInfo._areNormalsFrozen; - } - /** - * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update. - * @returns the current mesh - */ - freezeNormals() { - this._internalMeshDataInfo._areNormalsFrozen = true; - return this; - } - /** - * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen - * @returns the current mesh - */ - unfreezeNormals() { - this._internalMeshDataInfo._areNormalsFrozen = false; - return this; - } - /** - * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs - */ - set overridenInstanceCount(count) { - this._instanceDataStorage.overridenInstanceCount = count; - } - // Methods - /** @internal */ - _preActivate() { - const internalDataInfo = this._internalMeshDataInfo; - const sceneRenderId = this.getScene().getRenderId(); - if (internalDataInfo._preActivateId === sceneRenderId) { - return this; - } - internalDataInfo._preActivateId = sceneRenderId; - this._instanceDataStorage.visibleInstances = null; - return this; - } - /** - * @internal - */ - _preActivateForIntermediateRendering(renderId) { - if (this._instanceDataStorage.visibleInstances) { - this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId; - } - return this; - } - /** - * @internal - */ - _registerInstanceForRenderId(instance, renderId) { - if (!this._instanceDataStorage.visibleInstances) { - this._instanceDataStorage.visibleInstances = { - defaultRenderId: renderId, - selfDefaultRenderId: this._renderId, - }; - } - if (!this._instanceDataStorage.visibleInstances[renderId]) { - if (this._instanceDataStorage.previousRenderId !== undefined && this._instanceDataStorage.isFrozen) { - this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId] = null; - } - this._instanceDataStorage.previousRenderId = renderId; - this._instanceDataStorage.visibleInstances[renderId] = new Array(); - } - this._instanceDataStorage.visibleInstances[renderId].push(instance); - return this; - } - _afterComputeWorldMatrix() { - super._afterComputeWorldMatrix(); - if (!this.hasThinInstances) { - return; - } - if (!this.doNotSyncBoundingInfo) { - this.thinInstanceRefreshBoundingInfo(false); - } - } - /** @internal */ - _postActivate() { - if (this.edgesShareWithInstances && this.edgesRenderer && this.edgesRenderer.isEnabled && this._renderingGroup) { - this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer); - this.edgesRenderer.customInstances.push(this.getWorldMatrix()); - } - } - /** - * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked. - * This means the mesh underlying bounding box and sphere are recomputed. - * @param applySkeleton defines whether to apply the skeleton before computing the bounding info - * @param applyMorph defines whether to apply the morph target before computing the bounding info - * @returns the current mesh - */ - refreshBoundingInfo(applySkeleton = false, applyMorph = false) { - if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) { - return this; - } - const bias = this.geometry ? this.geometry.boundingBias : null; - this._refreshBoundingInfo(this._getPositionData(applySkeleton, applyMorph), bias); - return this; - } - /** - * @internal - */ - _createGlobalSubMesh(force) { - const totalVertices = this.getTotalVertices(); - if (!totalVertices || !this.getIndices()) { - return null; - } - // Check if we need to recreate the submeshes - if (this.subMeshes && this.subMeshes.length > 0) { - const ib = this.getIndices(); - if (!ib) { - return null; - } - const totalIndices = ib.length; - let needToRecreate = false; - if (force) { - needToRecreate = true; - } - else { - for (const submesh of this.subMeshes) { - if (submesh.indexStart + submesh.indexCount > totalIndices) { - needToRecreate = true; - break; - } - if (submesh.verticesStart + submesh.verticesCount > totalVertices) { - needToRecreate = true; - break; - } - } - } - if (!needToRecreate) { - return this.subMeshes[0]; - } - } - this.releaseSubMeshes(); - return new subMesh_SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this); - } - /** - * This function will subdivide the mesh into multiple submeshes - * @param count defines the expected number of submeshes - */ - subdivide(count) { - if (count < 1) { - return; - } - const totalIndices = this.getTotalIndices(); - let subdivisionSize = (totalIndices / count) | 0; - let offset = 0; - // Ensure that subdivisionSize is a multiple of 3 - while (subdivisionSize % 3 !== 0) { - subdivisionSize++; - } - this.releaseSubMeshes(); - for (let index = 0; index < count; index++) { - if (offset >= totalIndices) { - break; - } - subMesh_SubMesh.CreateFromIndices(0, offset, index === count - 1 ? totalIndices - offset : subdivisionSize, this, undefined, false); - offset += subdivisionSize; - } - this.refreshBoundingInfo(); - this.synchronizeInstances(); - } - /** - * Copy a FloatArray into a specific associated vertex buffer - * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values : - * - VertexBuffer.PositionKind - * - VertexBuffer.UVKind - * - VertexBuffer.UV2Kind - * - VertexBuffer.UV3Kind - * - VertexBuffer.UV4Kind - * - VertexBuffer.UV5Kind - * - VertexBuffer.UV6Kind - * - VertexBuffer.ColorKind - * - VertexBuffer.MatricesIndicesKind - * - VertexBuffer.MatricesIndicesExtraKind - * - VertexBuffer.MatricesWeightsKind - * - VertexBuffer.MatricesWeightsExtraKind - * @param data defines the data source - * @param updatable defines if the updated vertex buffer must be flagged as updatable - * @param stride defines the data stride size (can be null) - * @returns the current mesh - */ - setVerticesData(kind, data, updatable = false, stride) { - if (!this._geometry) { - const vertexData = new mesh_vertexData_VertexData(); - vertexData.set(data, kind); - const scene = this.getScene(); - new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this); - } - else { - this._geometry.setVerticesData(kind, data, updatable, stride); - } - return this; - } - /** - * Delete a vertex buffer associated with this mesh - * @param kind defines which buffer to delete (positions, indices, normals, etc). Possible `kind` values : - * - VertexBuffer.PositionKind - * - VertexBuffer.UVKind - * - VertexBuffer.UV2Kind - * - VertexBuffer.UV3Kind - * - VertexBuffer.UV4Kind - * - VertexBuffer.UV5Kind - * - VertexBuffer.UV6Kind - * - VertexBuffer.ColorKind - * - VertexBuffer.MatricesIndicesKind - * - VertexBuffer.MatricesIndicesExtraKind - * - VertexBuffer.MatricesWeightsKind - * - VertexBuffer.MatricesWeightsExtraKind - */ - removeVerticesData(kind) { - if (!this._geometry) { - return; - } - this._geometry.removeVerticesData(kind); - } - /** - * Flags an associated vertex buffer as updatable - * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values : - * - VertexBuffer.PositionKind - * - VertexBuffer.UVKind - * - VertexBuffer.UV2Kind - * - VertexBuffer.UV3Kind - * - VertexBuffer.UV4Kind - * - VertexBuffer.UV5Kind - * - VertexBuffer.UV6Kind - * - VertexBuffer.ColorKind - * - VertexBuffer.MatricesIndicesKind - * - VertexBuffer.MatricesIndicesExtraKind - * - VertexBuffer.MatricesWeightsKind - * - VertexBuffer.MatricesWeightsExtraKind - * @param updatable defines if the updated vertex buffer must be flagged as updatable - */ - markVerticesDataAsUpdatable(kind, updatable = true) { - const vb = this.getVertexBuffer(kind); - if (!vb || vb.isUpdatable() === updatable) { - return; - } - this.setVerticesData(kind, this.getVerticesData(kind), updatable); - } - /** - * Sets the mesh global Vertex Buffer - * @param buffer defines the buffer to use - * @param disposeExistingBuffer disposes the existing buffer, if any (default: true) - * @returns the current mesh - */ - setVerticesBuffer(buffer, disposeExistingBuffer = true) { - if (!this._geometry) { - this._geometry = Geometry.CreateGeometryForMesh(this); - } - this._geometry.setVerticesBuffer(buffer, null, disposeExistingBuffer); - return this; - } - /** - * Update a specific associated vertex buffer - * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values : - * - VertexBuffer.PositionKind - * - VertexBuffer.UVKind - * - VertexBuffer.UV2Kind - * - VertexBuffer.UV3Kind - * - VertexBuffer.UV4Kind - * - VertexBuffer.UV5Kind - * - VertexBuffer.UV6Kind - * - VertexBuffer.ColorKind - * - VertexBuffer.MatricesIndicesKind - * - VertexBuffer.MatricesIndicesExtraKind - * - VertexBuffer.MatricesWeightsKind - * - VertexBuffer.MatricesWeightsExtraKind - * @param data defines the data source - * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind - * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry) - * @returns the current mesh - */ - updateVerticesData(kind, data, updateExtends, makeItUnique) { - if (!this._geometry) { - return this; - } - if (!makeItUnique) { - this._geometry.updateVerticesData(kind, data, updateExtends); - } - else { - this.makeGeometryUnique(); - this.updateVerticesData(kind, data, updateExtends, false); - } - return this; - } - /** - * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#other-shapes-updatemeshpositions - * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything - * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update - * @returns the current mesh - */ - updateMeshPositions(positionFunction, computeNormals = true) { - const positions = this.getVerticesData(buffer_VertexBuffer.PositionKind); - if (!positions) { - return this; - } - positionFunction(positions); - this.updateVerticesData(buffer_VertexBuffer.PositionKind, positions, false, false); - if (computeNormals) { - const indices = this.getIndices(); - const normals = this.getVerticesData(buffer_VertexBuffer.NormalKind); - if (!normals) { - return this; - } - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals); - this.updateVerticesData(buffer_VertexBuffer.NormalKind, normals, false, false); - } - return this; - } - /** - * Creates a un-shared specific occurence of the geometry for the mesh. - * @returns the current mesh - */ - makeGeometryUnique() { - if (!this._geometry) { - return this; - } - if (this._geometry.meshes.length === 1) { - return this; - } - const oldGeometry = this._geometry; - const geometry = this._geometry.copy(Geometry.RandomId()); - oldGeometry.releaseForMesh(this, true); - geometry.applyToMesh(this); - return this; - } - /** - * Set the index buffer of this mesh - * @param indices defines the source data - * @param totalVertices defines the total number of vertices referenced by this index data (can be null) - * @param updatable defines if the updated index buffer must be flagged as updatable (default is false) - * @returns the current mesh - */ - setIndices(indices, totalVertices = null, updatable = false) { - if (!this._geometry) { - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - const scene = this.getScene(); - new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this); - } - else { - this._geometry.setIndices(indices, totalVertices, updatable); - } - return this; - } - /** - * Update the current index buffer - * @param indices defines the source data - * @param offset defines the offset in the index buffer where to store the new data (can be null) - * @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) - * @returns the current mesh - */ - updateIndices(indices, offset, gpuMemoryOnly = false) { - if (!this._geometry) { - return this; - } - this._geometry.updateIndices(indices, offset, gpuMemoryOnly); - return this; - } - /** - * Invert the geometry to move from a right handed system to a left handed one. - * @returns the current mesh - */ - toLeftHanded() { - if (!this._geometry) { - return this; - } - this._geometry.toLeftHanded(); - return this; - } - /** - * @internal - */ - _bind(subMesh, effect, fillMode, allowInstancedRendering = true) { - if (!this._geometry) { - return this; - } - const engine = this.getScene().getEngine(); - // Morph targets - if (this.morphTargetManager && this.morphTargetManager.isUsingTextureForTargets) { - this.morphTargetManager._bind(effect); - } - // Wireframe - let indexToBind; - if (this._unIndexed) { - indexToBind = null; - } - else { - switch (this._getRenderingFillMode(fillMode)) { - case material_Material.PointFillMode: - indexToBind = null; - break; - case material_Material.WireFrameFillMode: - indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine); - break; - default: - case material_Material.TriangleFillMode: - indexToBind = this._geometry.getIndexBuffer(); - break; - } - } - // VBOs - if (!allowInstancedRendering || !this._userInstancedBuffersStorage || this.hasThinInstances) { - this._geometry._bind(effect, indexToBind); - } - else { - this._geometry._bind(effect, indexToBind, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects); - } - return this; - } - /** - * @internal - */ - _draw(subMesh, fillMode, instancesCount) { - if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { - return this; - } - if (this._internalMeshDataInfo._onBeforeDrawObservable) { - this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this); - } - const scene = this.getScene(); - const engine = scene.getEngine(); - if (this._unIndexed || fillMode == material_Material.PointFillMode) { - // or triangles as points - engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, this.forcedInstanceCount || instancesCount); - } - else if (fillMode == material_Material.WireFrameFillMode) { - // Triangles as wireframe - engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, this.forcedInstanceCount || instancesCount); - } - else { - engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, this.forcedInstanceCount || instancesCount); - } - return this; - } - /** - * Registers for this mesh a javascript function called just before the rendering process - * @param func defines the function to call before rendering this mesh - * @returns the current mesh - */ - registerBeforeRender(func) { - this.onBeforeRenderObservable.add(func); - return this; - } - /** - * Disposes a previously registered javascript function called before the rendering - * @param func defines the function to remove - * @returns the current mesh - */ - unregisterBeforeRender(func) { - this.onBeforeRenderObservable.removeCallback(func); - return this; - } - /** - * Registers for this mesh a javascript function called just after the rendering is complete - * @param func defines the function to call after rendering this mesh - * @returns the current mesh - */ - registerAfterRender(func) { - this.onAfterRenderObservable.add(func); - return this; - } - /** - * Disposes a previously registered javascript function called after the rendering. - * @param func defines the function to remove - * @returns the current mesh - */ - unregisterAfterRender(func) { - this.onAfterRenderObservable.removeCallback(func); - return this; - } - /** - * @internal - */ - _getInstancesRenderList(subMeshId, isReplacementMode = false) { - if (this._instanceDataStorage.isFrozen) { - if (isReplacementMode) { - this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[subMeshId] = false; - this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[subMeshId] = true; - return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode; - } - if (this._instanceDataStorage.previousBatch) { - return this._instanceDataStorage.previousBatch; - } - } - const scene = this.getScene(); - const isInIntermediateRendering = scene._isInIntermediateRendering(); - const onlyForInstances = isInIntermediateRendering - ? this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate - : this._internalAbstractMeshDataInfo._onlyForInstances; - const batchCache = this._instanceDataStorage.batchCache; - batchCache.mustReturn = false; - batchCache.renderSelf[subMeshId] = isReplacementMode || (!onlyForInstances && this.isEnabled() && this.isVisible); - batchCache.visibleInstances[subMeshId] = null; - if (this._instanceDataStorage.visibleInstances && !isReplacementMode) { - const visibleInstances = this._instanceDataStorage.visibleInstances; - const currentRenderId = scene.getRenderId(); - const defaultRenderId = isInIntermediateRendering ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId; - batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId]; - if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) { - batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId]; - } - } - batchCache.hardwareInstancedRendering[subMeshId] = - !isReplacementMode && - this._instanceDataStorage.hardwareInstancedRendering && - batchCache.visibleInstances[subMeshId] !== null && - batchCache.visibleInstances[subMeshId] !== undefined; - this._instanceDataStorage.previousBatch = batchCache; - return batchCache; - } - /** - * @internal - */ - _renderWithInstances(subMesh, fillMode, batch, effect, engine) { - var _a; - const visibleInstances = batch.visibleInstances[subMesh._id]; - const visibleInstanceCount = visibleInstances ? visibleInstances.length : 0; - const instanceStorage = this._instanceDataStorage; - const currentInstancesBufferSize = instanceStorage.instancesBufferSize; - let instancesBuffer = instanceStorage.instancesBuffer; - let instancesPreviousBuffer = instanceStorage.instancesPreviousBuffer; - const matricesCount = visibleInstanceCount + 1; - const bufferSize = matricesCount * 16 * 4; - while (instanceStorage.instancesBufferSize < bufferSize) { - instanceStorage.instancesBufferSize *= 2; - } - if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) { - instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4); - } - if ((this._scene.needsPreviousWorldMatrices && !instanceStorage.instancesPreviousData) || currentInstancesBufferSize != instanceStorage.instancesBufferSize) { - instanceStorage.instancesPreviousData = new Float32Array(instanceStorage.instancesBufferSize / 4); - } - let offset = 0; - let instancesCount = 0; - const renderSelf = batch.renderSelf[subMesh._id]; - const needUpdateBuffer = !instancesBuffer || - currentInstancesBufferSize !== instanceStorage.instancesBufferSize || - (this._scene.needsPreviousWorldMatrices && !instanceStorage.instancesPreviousBuffer); - if (!this._instanceDataStorage.manualUpdate && (!instanceStorage.isFrozen || needUpdateBuffer)) { - const world = this.getWorldMatrix(); - if (renderSelf) { - if (this._scene.needsPreviousWorldMatrices) { - if (!instanceStorage.masterMeshPreviousWorldMatrix) { - instanceStorage.masterMeshPreviousWorldMatrix = world.clone(); - instanceStorage.masterMeshPreviousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); - } - else { - instanceStorage.masterMeshPreviousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); - instanceStorage.masterMeshPreviousWorldMatrix.copyFrom(world); - } - } - world.copyToArray(instanceStorage.instancesData, offset); - offset += 16; - instancesCount++; - } - if (visibleInstances) { - if (mesh_Mesh.INSTANCEDMESH_SORT_TRANSPARENT && this._scene.activeCamera && ((_a = subMesh.getMaterial()) === null || _a === void 0 ? void 0 : _a.needAlphaBlendingForMesh(subMesh.getRenderingMesh()))) { - const cameraPosition = this._scene.activeCamera.globalPosition; - for (let instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) { - const instanceMesh = visibleInstances[instanceIndex]; - instanceMesh._distanceToCamera = math_vector_Vector3.Distance(instanceMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition); - } - visibleInstances.sort((m1, m2) => { - return m1._distanceToCamera > m2._distanceToCamera ? -1 : m1._distanceToCamera < m2._distanceToCamera ? 1 : 0; - }); - } - for (let instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) { - const instance = visibleInstances[instanceIndex]; - const matrix = instance.getWorldMatrix(); - matrix.copyToArray(instanceStorage.instancesData, offset); - if (this._scene.needsPreviousWorldMatrices) { - if (!instance._previousWorldMatrix) { - instance._previousWorldMatrix = matrix.clone(); - instance._previousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); - } - else { - instance._previousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); - instance._previousWorldMatrix.copyFrom(matrix); - } - } - offset += 16; - instancesCount++; - } - } - } - else { - instancesCount = (renderSelf ? 1 : 0) + visibleInstanceCount; - } - if (needUpdateBuffer) { - if (instancesBuffer) { - instancesBuffer.dispose(); - } - if (instancesPreviousBuffer) { - instancesPreviousBuffer.dispose(); - } - instancesBuffer = new Buffer(engine, instanceStorage.instancesData, true, 16, false, true); - instanceStorage.instancesBuffer = instancesBuffer; - if (!this._userInstancedBuffersStorage) { - this._userInstancedBuffersStorage = { - data: {}, - vertexBuffers: {}, - strides: {}, - sizes: {}, - vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : undefined, - }; - } - this._userInstancedBuffersStorage.vertexBuffers["world0"] = instancesBuffer.createVertexBuffer("world0", 0, 4); - this._userInstancedBuffersStorage.vertexBuffers["world1"] = instancesBuffer.createVertexBuffer("world1", 4, 4); - this._userInstancedBuffersStorage.vertexBuffers["world2"] = instancesBuffer.createVertexBuffer("world2", 8, 4); - this._userInstancedBuffersStorage.vertexBuffers["world3"] = instancesBuffer.createVertexBuffer("world3", 12, 4); - if (this._scene.needsPreviousWorldMatrices) { - instancesPreviousBuffer = new Buffer(engine, instanceStorage.instancesPreviousData, true, 16, false, true); - instanceStorage.instancesPreviousBuffer = instancesPreviousBuffer; - this._userInstancedBuffersStorage.vertexBuffers["previousWorld0"] = instancesPreviousBuffer.createVertexBuffer("previousWorld0", 0, 4); - this._userInstancedBuffersStorage.vertexBuffers["previousWorld1"] = instancesPreviousBuffer.createVertexBuffer("previousWorld1", 4, 4); - this._userInstancedBuffersStorage.vertexBuffers["previousWorld2"] = instancesPreviousBuffer.createVertexBuffer("previousWorld2", 8, 4); - this._userInstancedBuffersStorage.vertexBuffers["previousWorld3"] = instancesPreviousBuffer.createVertexBuffer("previousWorld3", 12, 4); - } - this._invalidateInstanceVertexArrayObject(); - } - else { - if (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) { - instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount); - if (this._scene.needsPreviousWorldMatrices && (!this._instanceDataStorage.manualUpdate || this._instanceDataStorage.previousManualUpdate)) { - instancesPreviousBuffer.updateDirectly(instanceStorage.instancesPreviousData, 0, instancesCount); - } - } - } - this._processInstancedBuffers(visibleInstances, renderSelf); - // Stats - this.getScene()._activeIndices.addCount(subMesh.indexCount * instancesCount, false); - // Draw - if (engine._currentDrawContext) { - engine._currentDrawContext.useInstancing = true; - } - this._bind(subMesh, effect, fillMode); - this._draw(subMesh, fillMode, instancesCount); - // Write current matrices as previous matrices in case of manual update - // Default behaviour when previous matrices are not specified explicitly - // Will break if instances number/order changes - if (this._scene.needsPreviousWorldMatrices && - !needUpdateBuffer && - this._instanceDataStorage.manualUpdate && - (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) && - !this._instanceDataStorage.previousManualUpdate) { - instancesPreviousBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount); - } - engine.unbindInstanceAttributes(); - return this; - } - /** - * @internal - */ - _renderWithThinInstances(subMesh, fillMode, effect, engine) { - var _a, _b; - // Stats - const instancesCount = (_b = (_a = this._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.instancesCount) !== null && _b !== void 0 ? _b : 0; - this.getScene()._activeIndices.addCount(subMesh.indexCount * instancesCount, false); - // Draw - if (engine._currentDrawContext) { - engine._currentDrawContext.useInstancing = true; - } - this._bind(subMesh, effect, fillMode); - this._draw(subMesh, fillMode, instancesCount); - // Write current matrices as previous matrices - // Default behaviour when previous matrices are not specified explicitly - // Will break if instances number/order changes - if (this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData && this._thinInstanceDataStorage.matrixData) { - if (!this._thinInstanceDataStorage.previousMatrixBuffer) { - this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", this._thinInstanceDataStorage.matrixData, false); - } - else { - this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, instancesCount); - } - } - engine.unbindInstanceAttributes(); - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _processInstancedBuffers(visibleInstances, renderSelf) { - // Do nothing - } - /** - * @internal - */ - _processRendering(renderingMesh, subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) { - const scene = this.getScene(); - const engine = scene.getEngine(); - fillMode = this._getRenderingFillMode(fillMode); - if (hardwareInstancedRendering && subMesh.getRenderingMesh().hasThinInstances) { - this._renderWithThinInstances(subMesh, fillMode, effect, engine); - return this; - } - if (hardwareInstancedRendering) { - this._renderWithInstances(subMesh, fillMode, batch, effect, engine); - } - else { - if (engine._currentDrawContext) { - engine._currentDrawContext.useInstancing = false; - } - let instanceCount = 0; - if (batch.renderSelf[subMesh._id]) { - // Draw - if (onBeforeDraw) { - onBeforeDraw(false, renderingMesh.getWorldMatrix(), effectiveMaterial); - } - instanceCount++; - this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount); - } - const visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id]; - if (visibleInstancesForSubMesh) { - const visibleInstanceCount = visibleInstancesForSubMesh.length; - instanceCount += visibleInstanceCount; - // Stats - for (let instanceIndex = 0; instanceIndex < visibleInstanceCount; instanceIndex++) { - const instance = visibleInstancesForSubMesh[instanceIndex]; - // World - const world = instance.getWorldMatrix(); - if (onBeforeDraw) { - onBeforeDraw(true, world, effectiveMaterial); - } - // Draw - this._draw(subMesh, fillMode); - } - } - // Stats - scene._activeIndices.addCount(subMesh.indexCount * instanceCount, false); - } - return this; - } - /** - * @internal - */ - _rebuild(dispose = false) { - if (this._instanceDataStorage.instancesBuffer) { - // Dispose instance buffer to be recreated in _renderWithInstances when rendered - if (dispose) { - this._instanceDataStorage.instancesBuffer.dispose(); - } - this._instanceDataStorage.instancesBuffer = null; - } - if (this._userInstancedBuffersStorage) { - for (const kind in this._userInstancedBuffersStorage.vertexBuffers) { - const buffer = this._userInstancedBuffersStorage.vertexBuffers[kind]; - if (buffer) { - // Dispose instance buffer to be recreated in _renderWithInstances when rendered - if (dispose) { - buffer.dispose(); - } - this._userInstancedBuffersStorage.vertexBuffers[kind] = null; - } - } - if (this._userInstancedBuffersStorage.vertexArrayObjects) { - this._userInstancedBuffersStorage.vertexArrayObjects = {}; - } - } - this._internalMeshDataInfo._effectiveMaterial = null; - super._rebuild(dispose); - } - /** @internal */ - _freeze() { - if (!this.subMeshes) { - return; - } - // Prepare batches - for (let index = 0; index < this.subMeshes.length; index++) { - this._getInstancesRenderList(index); - } - this._internalMeshDataInfo._effectiveMaterial = null; - this._instanceDataStorage.isFrozen = true; - } - /** @internal */ - _unFreeze() { - this._instanceDataStorage.isFrozen = false; - this._instanceDataStorage.previousBatch = null; - } - /** - * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager - * @param subMesh defines the subMesh to render - * @param enableAlphaMode defines if alpha mode can be changed - * @param effectiveMeshReplacement defines an optional mesh used to provide info for the rendering - * @returns the current mesh - */ - render(subMesh, enableAlphaMode, effectiveMeshReplacement) { - var _a, _b, _c; - const scene = this.getScene(); - if (this._internalAbstractMeshDataInfo._isActiveIntermediate) { - this._internalAbstractMeshDataInfo._isActiveIntermediate = false; - } - else { - this._internalAbstractMeshDataInfo._isActive = false; - } - if (this._checkOcclusionQuery() && !this._occlusionDataStorage.forceRenderingWhenOccluded) { - return this; - } - // Managing instances - const batch = this._getInstancesRenderList(subMesh._id, !!effectiveMeshReplacement); - if (batch.mustReturn) { - return this; - } - // Checking geometry state - if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { - return this; - } - const engine = scene.getEngine(); - let oldCameraMaxZ = 0; - let oldCamera = null; - if (this.ignoreCameraMaxZ && scene.activeCamera && !scene._isInIntermediateRendering()) { - oldCameraMaxZ = scene.activeCamera.maxZ; - oldCamera = scene.activeCamera; - scene.activeCamera.maxZ = 0; - scene.updateTransformMatrix(true); - } - if (this._internalMeshDataInfo._onBeforeRenderObservable) { - this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this); - } - const renderingMesh = subMesh.getRenderingMesh(); - const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || - renderingMesh.hasThinInstances || - (!!this._userInstancedBuffersStorage && !subMesh.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh); - const instanceDataStorage = this._instanceDataStorage; - const material = subMesh.getMaterial(); - if (!material) { - if (oldCamera) { - oldCamera.maxZ = oldCameraMaxZ; - scene.updateTransformMatrix(true); - } - return this; - } - // Material - if (!instanceDataStorage.isFrozen || !this._internalMeshDataInfo._effectiveMaterial || this._internalMeshDataInfo._effectiveMaterial !== material) { - if (material._storeEffectOnSubMeshes) { - if (!material.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) { - if (oldCamera) { - oldCamera.maxZ = oldCameraMaxZ; - scene.updateTransformMatrix(true); - } - return this; - } - } - else if (!material.isReady(this, hardwareInstancedRendering)) { - if (oldCamera) { - oldCamera.maxZ = oldCameraMaxZ; - scene.updateTransformMatrix(true); - } - return this; - } - this._internalMeshDataInfo._effectiveMaterial = material; - } - else if ((material._storeEffectOnSubMeshes && !((_a = subMesh.effect) === null || _a === void 0 ? void 0 : _a._wasPreviouslyReady)) || - (!material._storeEffectOnSubMeshes && !((_b = material.getEffect()) === null || _b === void 0 ? void 0 : _b._wasPreviouslyReady))) { - if (oldCamera) { - oldCamera.maxZ = oldCameraMaxZ; - scene.updateTransformMatrix(true); - } - return this; - } - // Alpha mode - if (enableAlphaMode) { - engine.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode); - } - let drawWrapper; - if (this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes) { - drawWrapper = subMesh._drawWrapper; - } - else { - drawWrapper = this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper(); - } - const effect = (_c = drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.effect) !== null && _c !== void 0 ? _c : null; - for (const step of scene._beforeRenderingMeshStage) { - step.action(this, subMesh, batch, effect); - } - if (!drawWrapper || !effect) { - if (oldCamera) { - oldCamera.maxZ = oldCameraMaxZ; - scene.updateTransformMatrix(true); - } - return this; - } - const effectiveMesh = effectiveMeshReplacement || this; - let sideOrientation; - if (!instanceDataStorage.isFrozen && (this._internalMeshDataInfo._effectiveMaterial.backFaceCulling || this.overrideMaterialSideOrientation !== null)) { - const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant(); - sideOrientation = this.overrideMaterialSideOrientation; - if (sideOrientation == null) { - sideOrientation = this._internalMeshDataInfo._effectiveMaterial.sideOrientation; - } - if (mainDeterminant < 0) { - sideOrientation = sideOrientation === material_Material.ClockWiseSideOrientation ? material_Material.CounterClockWiseSideOrientation : material_Material.ClockWiseSideOrientation; - } - instanceDataStorage.sideOrientation = sideOrientation; - } - else { - sideOrientation = instanceDataStorage.sideOrientation; - } - const reverse = this._internalMeshDataInfo._effectiveMaterial._preBind(drawWrapper, sideOrientation); - if (this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite) { - engine.setDepthWrite(true); - } - // Bind - const effectiveMaterial = this._internalMeshDataInfo._effectiveMaterial; - const fillMode = effectiveMaterial.fillMode; - if (this._internalMeshDataInfo._onBeforeBindObservable) { - this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this); - } - if (!hardwareInstancedRendering) { - // Binding will be done later because we need to add more info to the VB - this._bind(subMesh, effect, fillMode, false); - } - const world = effectiveMesh.getWorldMatrix(); - if (effectiveMaterial._storeEffectOnSubMeshes) { - effectiveMaterial.bindForSubMesh(world, this, subMesh); - } - else { - effectiveMaterial.bind(world, this); - } - if (!effectiveMaterial.backFaceCulling && effectiveMaterial.separateCullingPass) { - engine.setState(true, effectiveMaterial.zOffset, false, !reverse, effectiveMaterial.cullBackFaces, effectiveMaterial.stencil, effectiveMaterial.zOffsetUnits); - this._processRendering(this, subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial); - engine.setState(true, effectiveMaterial.zOffset, false, reverse, effectiveMaterial.cullBackFaces, effectiveMaterial.stencil, effectiveMaterial.zOffsetUnits); - if (this._internalMeshDataInfo._onBetweenPassObservable) { - this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(subMesh); - } - } - // Draw - this._processRendering(this, subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial); - // Unbind - this._internalMeshDataInfo._effectiveMaterial.unbind(); - for (const step of scene._afterRenderingMeshStage) { - step.action(this, subMesh, batch, effect); - } - if (this._internalMeshDataInfo._onAfterRenderObservable) { - this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this); - } - if (oldCamera) { - oldCamera.maxZ = oldCameraMaxZ; - scene.updateTransformMatrix(true); - } - if (scene.performancePriority === ScenePerformancePriority.Aggressive && !instanceDataStorage.isFrozen) { - this._freeze(); - } - return this; - } - /** - * Renormalize the mesh and patch it up if there are no weights - * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1. - * However in the case of zero weights then we set just a single influence to 1. - * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version. - */ - cleanMatrixWeights() { - if (this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)) { - if (this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsExtraKind)) { - this._normalizeSkinWeightsAndExtra(); - } - else { - this._normalizeSkinFourWeights(); - } - } - } - // faster 4 weight version. - _normalizeSkinFourWeights() { - const matricesWeights = this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind); - const numWeights = matricesWeights.length; - for (let a = 0; a < numWeights; a += 4) { - // accumulate weights - const t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3]; - // check for invalid weight and just set it to 1. - if (t === 0) { - matricesWeights[a] = 1; - } - else { - // renormalize so everything adds to 1 use reciprocal - const recip = 1 / t; - matricesWeights[a] *= recip; - matricesWeights[a + 1] *= recip; - matricesWeights[a + 2] *= recip; - matricesWeights[a + 3] *= recip; - } - } - this.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind, matricesWeights); - } - // handle special case of extra verts. (in theory gltf can handle 12 influences) - _normalizeSkinWeightsAndExtra() { - const matricesWeightsExtra = this.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind); - const matricesWeights = this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind); - const numWeights = matricesWeights.length; - for (let a = 0; a < numWeights; a += 4) { - // accumulate weights - let t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3]; - t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3]; - // check for invalid weight and just set it to 1. - if (t === 0) { - matricesWeights[a] = 1; - } - else { - // renormalize so everything adds to 1 use reciprocal - const recip = 1 / t; - matricesWeights[a] *= recip; - matricesWeights[a + 1] *= recip; - matricesWeights[a + 2] *= recip; - matricesWeights[a + 3] *= recip; - // same goes for extras - matricesWeightsExtra[a] *= recip; - matricesWeightsExtra[a + 1] *= recip; - matricesWeightsExtra[a + 2] *= recip; - matricesWeightsExtra[a + 3] *= recip; - } - } - this.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind, matricesWeights); - this.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind, matricesWeightsExtra); - } - /** - * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights, - * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let - * the user know there was an issue with importing the mesh - * @returns a validation object with skinned, valid and report string - */ - validateSkinning() { - const matricesWeightsExtra = this.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind); - const matricesWeights = this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind); - if (matricesWeights === null || this.skeleton == null) { - return { skinned: false, valid: true, report: "not skinned" }; - } - const numWeights = matricesWeights.length; - let numberNotSorted = 0; - let missingWeights = 0; - let maxUsedWeights = 0; - let numberNotNormalized = 0; - const numInfluences = matricesWeightsExtra === null ? 4 : 8; - const usedWeightCounts = new Array(); - for (let a = 0; a <= numInfluences; a++) { - usedWeightCounts[a] = 0; - } - const toleranceEpsilon = 0.001; - for (let a = 0; a < numWeights; a += 4) { - let lastWeight = matricesWeights[a]; - let t = lastWeight; - let usedWeights = t === 0 ? 0 : 1; - for (let b = 1; b < numInfluences; b++) { - const d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4]; - if (d > lastWeight) { - numberNotSorted++; - } - if (d !== 0) { - usedWeights++; - } - t += d; - lastWeight = d; - } - // count the buffer weights usage - usedWeightCounts[usedWeights]++; - // max influences - if (usedWeights > maxUsedWeights) { - maxUsedWeights = usedWeights; - } - // check for invalid weight and just set it to 1. - if (t === 0) { - missingWeights++; - } - else { - // renormalize so everything adds to 1 use reciprocal - const recip = 1 / t; - let tolerance = 0; - for (let b = 0; b < numInfluences; b++) { - if (b < 4) { - tolerance += Math.abs(matricesWeights[a + b] - matricesWeights[a + b] * recip); - } - else { - tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - matricesWeightsExtra[a + b - 4] * recip); - } - } - // arbitrary epsilon value for dictating not normalized - if (tolerance > toleranceEpsilon) { - numberNotNormalized++; - } - } - } - // validate bone indices are in range of the skeleton - const numBones = this.skeleton.bones.length; - const matricesIndices = this.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind); - const matricesIndicesExtra = this.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind); - let numBadBoneIndices = 0; - for (let a = 0; a < numWeights; a += 4) { - for (let b = 0; b < numInfluences; b++) { - const index = b < 4 ? matricesIndices[a + b] : matricesIndicesExtra[a + b - 4]; - if (index >= numBones || index < 0) { - numBadBoneIndices++; - } - } - } - // log mesh stats - const output = "Number of Weights = " + - numWeights / 4 + - "\nMaximum influences = " + - maxUsedWeights + - "\nMissing Weights = " + - missingWeights + - "\nNot Sorted = " + - numberNotSorted + - "\nNot Normalized = " + - numberNotNormalized + - "\nWeightCounts = [" + - usedWeightCounts + - "]" + - "\nNumber of bones = " + - numBones + - "\nBad Bone Indices = " + - numBadBoneIndices; - return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output }; - } - /** @internal */ - _checkDelayState() { - const scene = this.getScene(); - if (this._geometry) { - this._geometry.load(scene); - } - else if (this.delayLoadState === 4) { - this.delayLoadState = 2; - this._queueLoad(scene); - } - return this; - } - _queueLoad(scene) { - scene.addPendingData(this); - const getBinaryData = this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1; - tools_Tools.LoadFile(this.delayLoadingFile, (data) => { - if (data instanceof ArrayBuffer) { - this._delayLoadingFunction(data, this); - } - else { - this._delayLoadingFunction(JSON.parse(data), this); - } - this.instances.forEach((instance) => { - instance.refreshBoundingInfo(); - instance._syncSubMeshes(); - }); - this.delayLoadState = 1; - scene.removePendingData(this); - }, () => { }, scene.offlineProvider, getBinaryData); - return this; - } - /** - * Returns `true` if the mesh is within the frustum defined by the passed array of planes. - * A mesh is in the frustum if its bounding box intersects the frustum - * @param frustumPlanes defines the frustum to test - * @returns true if the mesh is in the frustum planes - */ - isInFrustum(frustumPlanes) { - if (this.delayLoadState === 2) { - return false; - } - if (!super.isInFrustum(frustumPlanes)) { - return false; - } - this._checkDelayState(); - return true; - } - /** - * Sets the mesh material by the material or multiMaterial `id` property - * @param id is a string identifying the material or the multiMaterial - * @returns the current mesh - */ - setMaterialById(id) { - const materials = this.getScene().materials; - let index; - for (index = materials.length - 1; index > -1; index--) { - if (materials[index].id === id) { - this.material = materials[index]; - return this; - } - } - // Multi - const multiMaterials = this.getScene().multiMaterials; - for (index = multiMaterials.length - 1; index > -1; index--) { - if (multiMaterials[index].id === id) { - this.material = multiMaterials[index]; - return this; - } - } - return this; - } - /** - * Returns as a new array populated with the mesh material and/or skeleton, if any. - * @returns an array of IAnimatable - */ - getAnimatables() { - const results = new Array(); - if (this.material) { - results.push(this.material); - } - if (this.skeleton) { - results.push(this.skeleton); - } - return results; - } - /** - * Modifies the mesh geometry according to the passed transformation matrix. - * This method returns nothing, but it really modifies the mesh even if it's originally not set as updatable. - * The mesh normals are modified using the same transformation. - * Note that, under the hood, this method sets a new VertexBuffer each call. - * @param transform defines the transform matrix to use - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms - * @returns the current mesh - */ - bakeTransformIntoVertices(transform) { - // Position - if (!this.isVerticesDataPresent(buffer_VertexBuffer.PositionKind)) { - return this; - } - const submeshes = this.subMeshes.splice(0); - this._resetPointsArrayCache(); - let data = this.getVerticesData(buffer_VertexBuffer.PositionKind); - const temp = math_vector_Vector3.Zero(); - let index; - for (index = 0; index < data.length; index += 3) { - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp).toArray(data, index); - } - this.setVerticesData(buffer_VertexBuffer.PositionKind, data, this.getVertexBuffer(buffer_VertexBuffer.PositionKind).isUpdatable()); - // Normals - if (this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)) { - data = this.getVerticesData(buffer_VertexBuffer.NormalKind); - for (index = 0; index < data.length; index += 3) { - math_vector_Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp) - .normalize() - .toArray(data, index); - } - this.setVerticesData(buffer_VertexBuffer.NormalKind, data, this.getVertexBuffer(buffer_VertexBuffer.NormalKind).isUpdatable()); - } - // flip faces? - if (transform.determinant() < 0) { - this.flipFaces(); - } - // Restore submeshes - this.releaseSubMeshes(); - this.subMeshes = submeshes; - return this; - } - /** - * Modifies the mesh geometry according to its own current World Matrix. - * The mesh World Matrix is then reset. - * This method returns nothing but really modifies the mesh even if it's originally not set as updatable. - * Note that, under the hood, this method sets a new VertexBuffer each call. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms - * @param bakeIndependentlyOfChildren indicates whether to preserve all child nodes' World Matrix during baking - * @returns the current mesh - */ - bakeCurrentTransformIntoVertices(bakeIndependentlyOfChildren = true) { - this.bakeTransformIntoVertices(this.computeWorldMatrix(true)); - this.resetLocalMatrix(bakeIndependentlyOfChildren); - return this; - } - // Cache - /** @internal */ - get _positions() { - if (this._internalAbstractMeshDataInfo._positions) { - return this._internalAbstractMeshDataInfo._positions; - } - if (this._geometry) { - return this._geometry._positions; - } - return null; - } - /** @internal */ - _resetPointsArrayCache() { - if (this._geometry) { - this._geometry._resetPointsArrayCache(); - } - return this; - } - /** @internal */ - _generatePointsArray() { - if (this._geometry) { - return this._geometry._generatePointsArray(); - } - return false; - } - /** - * Returns a new Mesh object generated from the current mesh properties. - * This method must not get confused with createInstance() - * @param name is a string, the name given to the new mesh - * @param newParent can be any Node object (default `null`) - * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`) - * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`) - * @returns a new mesh - */ - clone(name = "", newParent = null, doNotCloneChildren, clonePhysicsImpostor = true) { - return new mesh_Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor); - } - /** - * Releases resources associated with this mesh. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) - */ - dispose(doNotRecurse, disposeMaterialAndTextures = false) { - this.morphTargetManager = null; - if (this._geometry) { - this._geometry.releaseForMesh(this, true); - } - const internalDataInfo = this._internalMeshDataInfo; - if (internalDataInfo._onBeforeDrawObservable) { - internalDataInfo._onBeforeDrawObservable.clear(); - } - if (internalDataInfo._onBeforeBindObservable) { - internalDataInfo._onBeforeBindObservable.clear(); - } - if (internalDataInfo._onBeforeRenderObservable) { - internalDataInfo._onBeforeRenderObservable.clear(); - } - if (internalDataInfo._onAfterRenderObservable) { - internalDataInfo._onAfterRenderObservable.clear(); - } - if (internalDataInfo._onBetweenPassObservable) { - internalDataInfo._onBetweenPassObservable.clear(); - } - // Sources - if (this._scene.useClonedMeshMap) { - if (internalDataInfo.meshMap) { - for (const uniqueId in internalDataInfo.meshMap) { - const mesh = internalDataInfo.meshMap[uniqueId]; - if (mesh) { - mesh._internalMeshDataInfo._source = null; - internalDataInfo.meshMap[uniqueId] = undefined; - } - } - } - if (internalDataInfo._source && internalDataInfo._source._internalMeshDataInfo.meshMap) { - internalDataInfo._source._internalMeshDataInfo.meshMap[this.uniqueId] = undefined; - } - } - else { - const meshes = this.getScene().meshes; - for (const abstractMesh of meshes) { - const mesh = abstractMesh; - if (mesh._internalMeshDataInfo && mesh._internalMeshDataInfo._source && mesh._internalMeshDataInfo._source === this) { - mesh._internalMeshDataInfo._source = null; - } - } - } - internalDataInfo._source = null; - this._instanceDataStorage.visibleInstances = {}; - // Instances - this._disposeInstanceSpecificData(); - // Thin instances - this._disposeThinInstanceSpecificData(); - if (this._internalMeshDataInfo._checkReadinessObserver) { - this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver); - } - super.dispose(doNotRecurse, disposeMaterialAndTextures); - } - /** @internal */ - _disposeInstanceSpecificData() { - // Do nothing - } - /** @internal */ - _disposeThinInstanceSpecificData() { - // Do nothing - } - /** @internal */ - _invalidateInstanceVertexArrayObject() { - // Do nothing - } - /** - * Modifies the mesh geometry according to a displacement map. - * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. - * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. - * @param url is a string, the URL from the image file is to be downloaded. - * @param minHeight is the lower limit of the displacement. - * @param maxHeight is the upper limit of the displacement. - * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing. - * @param uvOffset is an optional vector2 used to offset UV. - * @param uvScale is an optional vector2 used to scale UV. - * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance. - * @returns the Mesh. - */ - applyDisplacementMap(url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate = false) { - const scene = this.getScene(); - const onload = (img) => { - // Getting height map data - const heightMapWidth = img.width; - const heightMapHeight = img.height; - const canvas = this.getEngine().createCanvas(heightMapWidth, heightMapHeight); - const context = canvas.getContext("2d"); - context.drawImage(img, 0, 0); - // Create VertexData from map data - //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949 - const buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data; - this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate); - //execute success callback, if set - if (onSuccess) { - onSuccess(this); - } - }; - tools_Tools.LoadImage(url, onload, () => { }, scene.offlineProvider); - return this; - } - /** - * Modifies the mesh geometry according to a displacementMap buffer. - * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. - * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. - * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel. - * @param heightMapWidth is the width of the buffer image. - * @param heightMapHeight is the height of the buffer image. - * @param minHeight is the lower limit of the displacement. - * @param maxHeight is the upper limit of the displacement. - * @param uvOffset is an optional vector2 used to offset UV. - * @param uvScale is an optional vector2 used to scale UV. - * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance. - * @returns the Mesh. - */ - applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate = false) { - if (!this.isVerticesDataPresent(buffer_VertexBuffer.PositionKind) || !this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind) || !this.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - logger_Logger.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"); - return this; - } - const positions = this.getVerticesData(buffer_VertexBuffer.PositionKind, true, true); - const normals = this.getVerticesData(buffer_VertexBuffer.NormalKind); - const uvs = this.getVerticesData(buffer_VertexBuffer.UVKind); - let position = math_vector_Vector3.Zero(); - const normal = math_vector_Vector3.Zero(); - const uv = math_vector_Vector2.Zero(); - uvOffset = uvOffset || math_vector_Vector2.Zero(); - uvScale = uvScale || new math_vector_Vector2(1, 1); - for (let index = 0; index < positions.length; index += 3) { - math_vector_Vector3.FromArrayToRef(positions, index, position); - math_vector_Vector3.FromArrayToRef(normals, index, normal); - math_vector_Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv); - // Compute height - const u = (Math.abs(uv.x * uvScale.x + (uvOffset.x % 1)) * (heightMapWidth - 1)) % heightMapWidth | 0; - const v = (Math.abs(uv.y * uvScale.y + (uvOffset.y % 1)) * (heightMapHeight - 1)) % heightMapHeight | 0; - const pos = (u + v * heightMapWidth) * 4; - const r = buffer[pos] / 255.0; - const g = buffer[pos + 1] / 255.0; - const b = buffer[pos + 2] / 255.0; - const gradient = r * 0.3 + g * 0.59 + b * 0.11; - normal.normalize(); - normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient); - position = position.add(normal); - position.toArray(positions, index); - } - mesh_vertexData_VertexData.ComputeNormals(positions, this.getIndices(), normals); - if (forceUpdate) { - this.setVerticesData(buffer_VertexBuffer.PositionKind, positions); - this.setVerticesData(buffer_VertexBuffer.NormalKind, normals); - this.setVerticesData(buffer_VertexBuffer.UVKind, uvs); - } - else { - this.updateVerticesData(buffer_VertexBuffer.PositionKind, positions); - this.updateVerticesData(buffer_VertexBuffer.NormalKind, normals); - } - return this; - } - _getFlattenedNormals(indices, positions) { - const normals = new Float32Array(indices.length * 3); - let normalsCount = 0; - // Decide if normals should be flipped - const flipNormalGeneration = this.overrideMaterialSideOrientation === - (this._scene.useRightHandedSystem ? 1 : 0); - // Generate new normals - for (let index = 0; index < indices.length; index += 3) { - const p1 = math_vector_Vector3.FromArray(positions, indices[index] * 3); - const p2 = math_vector_Vector3.FromArray(positions, indices[index + 1] * 3); - const p3 = math_vector_Vector3.FromArray(positions, indices[index + 2] * 3); - const p1p2 = p1.subtract(p2); - const p3p2 = p3.subtract(p2); - const normal = math_vector_Vector3.Normalize(math_vector_Vector3.Cross(p1p2, p3p2)); - if (flipNormalGeneration) { - normal.scaleInPlace(-1); - } - // Store same normals for every vertex - for (let localIndex = 0; localIndex < 3; localIndex++) { - normals[normalsCount++] = normal.x; - normals[normalsCount++] = normal.y; - normals[normalsCount++] = normal.z; - } - } - return normals; - } - _convertToUnIndexedMesh(flattenNormals = false) { - const kinds = this.getVerticesDataKinds(); - const indices = this.getIndices(); - const data = {}; - const separateVertices = (data, stride) => { - const newData = new Float32Array(indices.length * stride); - let count = 0; - for (let index = 0; index < indices.length; index++) { - for (let offset = 0; offset < stride; offset++) { - newData[count++] = data[indices[index] * stride + offset]; - } - } - return newData; - }; - // Save previous submeshes - const previousSubmeshes = this.geometry ? this.subMeshes.slice(0) : []; - // Cache vertex data - for (const kind of kinds) { - data[kind] = this.getVerticesData(kind); - } - // Update vertex data - for (const kind of kinds) { - const vertexBuffer = this.getVertexBuffer(kind); - const stride = vertexBuffer.getStrideSize(); - if (flattenNormals && kind === buffer_VertexBuffer.NormalKind) { - const normals = this._getFlattenedNormals(indices, data[buffer_VertexBuffer.PositionKind]); - this.setVerticesData(buffer_VertexBuffer.NormalKind, normals, vertexBuffer.isUpdatable(), stride); - } - else { - this.setVerticesData(kind, separateVertices(data[kind], stride), vertexBuffer.isUpdatable(), stride); - } - } - // Update morph targets - if (this.morphTargetManager) { - for (let targetIndex = 0; targetIndex < this.morphTargetManager.numTargets; targetIndex++) { - const target = this.morphTargetManager.getTarget(targetIndex); - const positions = target.getPositions(); - target.setPositions(separateVertices(positions, 3)); - const normals = target.getNormals(); - if (normals) { - target.setNormals(flattenNormals ? this._getFlattenedNormals(indices, positions) : separateVertices(normals, 3)); - } - const tangents = target.getTangents(); - if (tangents) { - target.setTangents(separateVertices(tangents, 3)); - } - const uvs = target.getUVs(); - if (uvs) { - target.setUVs(separateVertices(uvs, 2)); - } - } - this.morphTargetManager.synchronize(); - } - // Update indices - for (let index = 0; index < indices.length; index++) { - indices[index] = index; - } - this.setIndices(indices); - this._unIndexed = true; - // Update submeshes - this.releaseSubMeshes(); - for (const previousOne of previousSubmeshes) { - subMesh_SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this); - } - this.synchronizeInstances(); - return this; - } - /** - * Modify the mesh to get a flat shading rendering. - * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result. - * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated. - * @returns current mesh - */ - convertToFlatShadedMesh() { - return this._convertToUnIndexedMesh(true); - } - /** - * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers. - * In other words, more vertices, no more indices and a single bigger VBO. - * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated. - * @returns current mesh - */ - convertToUnIndexedMesh() { - return this._convertToUnIndexedMesh(); - } - /** - * Inverses facet orientations. - * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. - * @param flipNormals will also inverts the normals - * @returns current mesh - */ - flipFaces(flipNormals = false) { - const vertex_data = mesh_vertexData_VertexData.ExtractFromMesh(this); - let i; - if (flipNormals && this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind) && vertex_data.normals) { - for (i = 0; i < vertex_data.normals.length; i++) { - vertex_data.normals[i] *= -1; - } - } - if (vertex_data.indices) { - let temp; - for (i = 0; i < vertex_data.indices.length; i += 3) { - // reassign indices - temp = vertex_data.indices[i + 1]; - vertex_data.indices[i + 1] = vertex_data.indices[i + 2]; - vertex_data.indices[i + 2] = temp; - } - } - vertex_data.applyToMesh(this, this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind)); - return this; - } - /** - * Increase the number of facets and hence vertices in a mesh - * Vertex normals are interpolated from existing vertex normals - * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. - * @param numberPerEdge the number of new vertices to add to each edge of a facet, optional default 1 - */ - increaseVertices(numberPerEdge = 1) { - const vertex_data = mesh_vertexData_VertexData.ExtractFromMesh(this); - const currentIndices = vertex_data.indices && !Array.isArray(vertex_data.indices) && Array.from ? Array.from(vertex_data.indices) : vertex_data.indices; - const positions = vertex_data.positions && !Array.isArray(vertex_data.positions) && Array.from ? Array.from(vertex_data.positions) : vertex_data.positions; - const uvs = vertex_data.uvs && !Array.isArray(vertex_data.uvs) && Array.from ? Array.from(vertex_data.uvs) : vertex_data.uvs; - const normals = vertex_data.normals && !Array.isArray(vertex_data.normals) && Array.from ? Array.from(vertex_data.normals) : vertex_data.normals; - if (!currentIndices || !positions) { - logger_Logger.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions"); - } - else { - vertex_data.indices = currentIndices; - vertex_data.positions = positions; - if (uvs) { - vertex_data.uvs = uvs; - } - if (normals) { - vertex_data.normals = normals; - } - const segments = numberPerEdge + 1; //segments per current facet edge, become sides of new facets - const tempIndices = new Array(); - for (let i = 0; i < segments + 1; i++) { - tempIndices[i] = new Array(); - } - let a; //vertex index of one end of a side - let b; //vertex index of other end of the side - const deltaPosition = new math_vector_Vector3(0, 0, 0); - const deltaNormal = new math_vector_Vector3(0, 0, 0); - const deltaUV = new math_vector_Vector2(0, 0); - const indices = new Array(); - const vertexIndex = new Array(); - const side = new Array(); - let len; - let positionPtr = positions.length; - let uvPtr; - if (uvs) { - uvPtr = uvs.length; - } - let normalsPtr; - if (normals) { - normalsPtr = normals.length; - } - for (let i = 0; i < currentIndices.length; i += 3) { - vertexIndex[0] = currentIndices[i]; - vertexIndex[1] = currentIndices[i + 1]; - vertexIndex[2] = currentIndices[i + 2]; - for (let j = 0; j < 3; j++) { - a = vertexIndex[j]; - b = vertexIndex[(j + 1) % 3]; - if (side[a] === undefined && side[b] === undefined) { - side[a] = new Array(); - side[b] = new Array(); - } - else { - if (side[a] === undefined) { - side[a] = new Array(); - } - if (side[b] === undefined) { - side[b] = new Array(); - } - } - if (side[a][b] === undefined && side[b][a] === undefined) { - side[a][b] = []; - deltaPosition.x = (positions[3 * b] - positions[3 * a]) / segments; - deltaPosition.y = (positions[3 * b + 1] - positions[3 * a + 1]) / segments; - deltaPosition.z = (positions[3 * b + 2] - positions[3 * a + 2]) / segments; - if (normals) { - deltaNormal.x = (normals[3 * b] - normals[3 * a]) / segments; - deltaNormal.y = (normals[3 * b + 1] - normals[3 * a + 1]) / segments; - deltaNormal.z = (normals[3 * b + 2] - normals[3 * a + 2]) / segments; - } - if (uvs) { - deltaUV.x = (uvs[2 * b] - uvs[2 * a]) / segments; - deltaUV.y = (uvs[2 * b + 1] - uvs[2 * a + 1]) / segments; - } - side[a][b].push(a); - for (let k = 1; k < segments; k++) { - side[a][b].push(positions.length / 3); - positions[positionPtr++] = positions[3 * a] + k * deltaPosition.x; - positions[positionPtr++] = positions[3 * a + 1] + k * deltaPosition.y; - positions[positionPtr++] = positions[3 * a + 2] + k * deltaPosition.z; - if (normals) { - normals[normalsPtr++] = normals[3 * a] + k * deltaNormal.x; - normals[normalsPtr++] = normals[3 * a + 1] + k * deltaNormal.y; - normals[normalsPtr++] = normals[3 * a + 2] + k * deltaNormal.z; - } - if (uvs) { - uvs[uvPtr++] = uvs[2 * a] + k * deltaUV.x; - uvs[uvPtr++] = uvs[2 * a + 1] + k * deltaUV.y; - } - } - side[a][b].push(b); - side[b][a] = new Array(); - len = side[a][b].length; - for (let idx = 0; idx < len; idx++) { - side[b][a][idx] = side[a][b][len - 1 - idx]; - } - } - } - //Calculate positions, normals and uvs of new internal vertices - tempIndices[0][0] = currentIndices[i]; - tempIndices[1][0] = side[currentIndices[i]][currentIndices[i + 1]][1]; - tempIndices[1][1] = side[currentIndices[i]][currentIndices[i + 2]][1]; - for (let k = 2; k < segments; k++) { - tempIndices[k][0] = side[currentIndices[i]][currentIndices[i + 1]][k]; - tempIndices[k][k] = side[currentIndices[i]][currentIndices[i + 2]][k]; - deltaPosition.x = (positions[3 * tempIndices[k][k]] - positions[3 * tempIndices[k][0]]) / k; - deltaPosition.y = (positions[3 * tempIndices[k][k] + 1] - positions[3 * tempIndices[k][0] + 1]) / k; - deltaPosition.z = (positions[3 * tempIndices[k][k] + 2] - positions[3 * tempIndices[k][0] + 2]) / k; - if (normals) { - deltaNormal.x = (normals[3 * tempIndices[k][k]] - normals[3 * tempIndices[k][0]]) / k; - deltaNormal.y = (normals[3 * tempIndices[k][k] + 1] - normals[3 * tempIndices[k][0] + 1]) / k; - deltaNormal.z = (normals[3 * tempIndices[k][k] + 2] - normals[3 * tempIndices[k][0] + 2]) / k; - } - if (uvs) { - deltaUV.x = (uvs[2 * tempIndices[k][k]] - uvs[2 * tempIndices[k][0]]) / k; - deltaUV.y = (uvs[2 * tempIndices[k][k] + 1] - uvs[2 * tempIndices[k][0] + 1]) / k; - } - for (let j = 1; j < k; j++) { - tempIndices[k][j] = positions.length / 3; - positions[positionPtr++] = positions[3 * tempIndices[k][0]] + j * deltaPosition.x; - positions[positionPtr++] = positions[3 * tempIndices[k][0] + 1] + j * deltaPosition.y; - positions[positionPtr++] = positions[3 * tempIndices[k][0] + 2] + j * deltaPosition.z; - if (normals) { - normals[normalsPtr++] = normals[3 * tempIndices[k][0]] + j * deltaNormal.x; - normals[normalsPtr++] = normals[3 * tempIndices[k][0] + 1] + j * deltaNormal.y; - normals[normalsPtr++] = normals[3 * tempIndices[k][0] + 2] + j * deltaNormal.z; - } - if (uvs) { - uvs[uvPtr++] = uvs[2 * tempIndices[k][0]] + j * deltaUV.x; - uvs[uvPtr++] = uvs[2 * tempIndices[k][0] + 1] + j * deltaUV.y; - } - } - } - tempIndices[segments] = side[currentIndices[i + 1]][currentIndices[i + 2]]; - // reform indices - indices.push(tempIndices[0][0], tempIndices[1][0], tempIndices[1][1]); - for (let k = 1; k < segments; k++) { - let j; - for (j = 0; j < k; j++) { - indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]); - indices.push(tempIndices[k][j], tempIndices[k + 1][j + 1], tempIndices[k][j + 1]); - } - indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]); - } - } - vertex_data.indices = indices; - vertex_data.applyToMesh(this, this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind)); - } - } - /** - * Force adjacent facets to share vertices and remove any facets that have all vertices in a line - * This will undo any application of covertToFlatShadedMesh - * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. - */ - forceSharedVertices() { - const vertex_data = mesh_vertexData_VertexData.ExtractFromMesh(this); - const currentUVs = vertex_data.uvs; - const currentIndices = vertex_data.indices; - const currentPositions = vertex_data.positions; - const currentColors = vertex_data.colors; - const currentMatrixIndices = vertex_data.matricesIndices; - const currentMatrixWeights = vertex_data.matricesWeights; - const currentMatrixIndicesExtra = vertex_data.matricesIndicesExtra; - const currentMatrixWeightsExtra = vertex_data.matricesWeightsExtra; - if (currentIndices === void 0 || currentPositions === void 0 || currentIndices === null || currentPositions === null) { - logger_Logger.Warn("VertexData contains empty entries"); - } - else { - const positions = new Array(); - const indices = new Array(); - const uvs = new Array(); - const colors = new Array(); - const matrixIndices = new Array(); - const matrixWeights = new Array(); - const matrixIndicesExtra = new Array(); - const matrixWeightsExtra = new Array(); - let pstring = new Array(); //lists facet vertex positions (a,b,c) as string "a|b|c" - let indexPtr = 0; // pointer to next available index value - const uniquePositions = {}; // unique vertex positions - let ptr; // pointer to element in uniquePositions - let facet; - for (let i = 0; i < currentIndices.length; i += 3) { - facet = [currentIndices[i], currentIndices[i + 1], currentIndices[i + 2]]; //facet vertex indices - pstring = new Array(); - for (let j = 0; j < 3; j++) { - pstring[j] = ""; - for (let k = 0; k < 3; k++) { - //small values make 0 - if (Math.abs(currentPositions[3 * facet[j] + k]) < 0.00000001) { - currentPositions[3 * facet[j] + k] = 0; - } - pstring[j] += currentPositions[3 * facet[j] + k] + "|"; - } - } - //check facet vertices to see that none are repeated - // do not process any facet that has a repeated vertex, ie is a line - if (!(pstring[0] == pstring[1] || pstring[0] == pstring[2] || pstring[1] == pstring[2])) { - //for each facet position check if already listed in uniquePositions - // if not listed add to uniquePositions and set index pointer - // if listed use its index in uniquePositions and new index pointer - for (let j = 0; j < 3; j++) { - ptr = uniquePositions[pstring[j]]; - if (ptr === undefined) { - uniquePositions[pstring[j]] = indexPtr; - ptr = indexPtr++; - //not listed so add individual x, y, z coordinates to positions - for (let k = 0; k < 3; k++) { - positions.push(currentPositions[3 * facet[j] + k]); - } - if (currentColors !== null && currentColors !== void 0) { - for (let k = 0; k < 4; k++) { - colors.push(currentColors[4 * facet[j] + k]); - } - } - if (currentUVs !== null && currentUVs !== void 0) { - for (let k = 0; k < 2; k++) { - uvs.push(currentUVs[2 * facet[j] + k]); - } - } - if (currentMatrixIndices !== null && currentMatrixIndices !== void 0) { - for (let k = 0; k < 4; k++) { - matrixIndices.push(currentMatrixIndices[4 * facet[j] + k]); - } - } - if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) { - for (let k = 0; k < 4; k++) { - matrixWeights.push(currentMatrixWeights[4 * facet[j] + k]); - } - } - if (currentMatrixIndicesExtra !== null && currentMatrixIndicesExtra !== void 0) { - for (let k = 0; k < 4; k++) { - matrixIndicesExtra.push(currentMatrixIndicesExtra[4 * facet[j] + k]); - } - } - if (currentMatrixWeightsExtra !== null && currentMatrixWeightsExtra !== void 0) { - for (let k = 0; k < 4; k++) { - matrixWeightsExtra.push(currentMatrixWeightsExtra[4 * facet[j] + k]); - } - } - } - // add new index pointer to indices array - indices.push(ptr); - } - } - } - const normals = new Array(); - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals); - //create new vertex data object and update - vertex_data.positions = positions; - vertex_data.indices = indices; - vertex_data.normals = normals; - if (currentUVs !== null && currentUVs !== void 0) { - vertex_data.uvs = uvs; - } - if (currentColors !== null && currentColors !== void 0) { - vertex_data.colors = colors; - } - if (currentMatrixIndices !== null && currentMatrixIndices !== void 0) { - vertex_data.matricesIndices = matrixIndices; - } - if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) { - vertex_data.matricesWeights = matrixWeights; - } - if (currentMatrixIndicesExtra !== null && currentMatrixIndicesExtra !== void 0) { - vertex_data.matricesIndicesExtra = matrixIndicesExtra; - } - if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) { - vertex_data.matricesWeightsExtra = matrixWeightsExtra; - } - vertex_data.applyToMesh(this, this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind)); - } - } - // Instances - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/naming-convention - static _instancedMeshFactory(name, mesh) { - throw _WarnImport("InstancedMesh"); - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static _PhysicsImpostorParser(scene, physicObject, jsonObject) { - throw _WarnImport("PhysicsImpostor"); - } - /** - * Creates a new InstancedMesh object from the mesh model. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances - * @param name defines the name of the new instance - * @returns a new InstancedMesh - */ - createInstance(name) { - return mesh_Mesh._instancedMeshFactory(name, this); - } - /** - * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any. - * After this call, all the mesh instances have the same submeshes than the current mesh. - * @returns the current mesh - */ - synchronizeInstances() { - for (let instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) { - const instance = this.instances[instanceIndex]; - instance._syncSubMeshes(); - } - return this; - } - /** - * Optimization of the mesh's indices, in case a mesh has duplicated vertices. - * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. - * This should be used together with the simplification to avoid disappearing triangles. - * @param successCallback an optional success callback to be called after the optimization finished. - * @returns the current mesh - */ - optimizeIndices(successCallback) { - const indices = this.getIndices(); - const positions = this.getVerticesData(buffer_VertexBuffer.PositionKind); - if (!positions || !indices) { - return this; - } - const vectorPositions = new Array(); - for (let pos = 0; pos < positions.length; pos = pos + 3) { - vectorPositions.push(math_vector_Vector3.FromArray(positions, pos)); - } - const dupes = new Array(); - AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => { - const realPos = vectorPositions.length - 1 - iteration; - const testedPosition = vectorPositions[realPos]; - for (let j = 0; j < realPos; ++j) { - const againstPosition = vectorPositions[j]; - if (testedPosition.equals(againstPosition)) { - dupes[realPos] = j; - break; - } - } - }, () => { - for (let i = 0; i < indices.length; ++i) { - indices[i] = dupes[indices[i]] || indices[i]; - } - //indices are now reordered - const originalSubMeshes = this.subMeshes.slice(0); - this.setIndices(indices); - this.subMeshes = originalSubMeshes; - if (successCallback) { - successCallback(this); - } - }); - return this; - } - /** - * Serialize current mesh - * @param serializationObject defines the object which will receive the serialization data - */ - serialize(serializationObject = {}) { - serializationObject.name = this.name; - serializationObject.id = this.id; - serializationObject.uniqueId = this.uniqueId; - serializationObject.type = this.getClassName(); - if (Tags && Tags.HasTags(this)) { - serializationObject.tags = Tags.GetTags(this); - } - serializationObject.position = this.position.asArray(); - if (this.rotationQuaternion) { - serializationObject.rotationQuaternion = this.rotationQuaternion.asArray(); - } - else if (this.rotation) { - serializationObject.rotation = this.rotation.asArray(); - } - serializationObject.scaling = this.scaling.asArray(); - if (this._postMultiplyPivotMatrix) { - serializationObject.pivotMatrix = this.getPivotMatrix().asArray(); - } - else { - serializationObject.localMatrix = this.getPivotMatrix().asArray(); - } - serializationObject.isEnabled = this.isEnabled(false); - serializationObject.isVisible = this.isVisible; - serializationObject.infiniteDistance = this.infiniteDistance; - serializationObject.pickable = this.isPickable; - serializationObject.receiveShadows = this.receiveShadows; - serializationObject.billboardMode = this.billboardMode; - serializationObject.visibility = this.visibility; - serializationObject.checkCollisions = this.checkCollisions; - serializationObject.isBlocker = this.isBlocker; - serializationObject.overrideMaterialSideOrientation = this.overrideMaterialSideOrientation; - // Parent - if (this.parent) { - this.parent._serializeAsParent(serializationObject); - } - // Geometry - serializationObject.isUnIndexed = this.isUnIndexed; - const geometry = this._geometry; - if (geometry && this.subMeshes) { - serializationObject.geometryUniqueId = geometry.uniqueId; - serializationObject.geometryId = geometry.id; - // SubMeshes - serializationObject.subMeshes = []; - for (let subIndex = 0; subIndex < this.subMeshes.length; subIndex++) { - const subMesh = this.subMeshes[subIndex]; - serializationObject.subMeshes.push({ - materialIndex: subMesh.materialIndex, - verticesStart: subMesh.verticesStart, - verticesCount: subMesh.verticesCount, - indexStart: subMesh.indexStart, - indexCount: subMesh.indexCount, - }); - } - } - // Material - if (this.material) { - if (!this.material.doNotSerialize) { - serializationObject.materialUniqueId = this.material.uniqueId; - serializationObject.materialId = this.material.id; // back compat - } - } - else { - this.material = null; - serializationObject.materialUniqueId = this._scene.defaultMaterial.uniqueId; - serializationObject.materialId = this._scene.defaultMaterial.id; // back compat - } - // Morph targets - if (this.morphTargetManager) { - serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId; - } - // Skeleton - if (this.skeleton) { - serializationObject.skeletonId = this.skeleton.id; - serializationObject.numBoneInfluencers = this.numBoneInfluencers; - } - // Physics - //TODO implement correct serialization for physics impostors. - if (this.getScene()._getComponent(sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE)) { - const impostor = this.getPhysicsImpostor(); - if (impostor) { - serializationObject.physicsMass = impostor.getParam("mass"); - serializationObject.physicsFriction = impostor.getParam("friction"); - serializationObject.physicsRestitution = impostor.getParam("mass"); - serializationObject.physicsImpostor = impostor.type; - } - } - // Metadata - if (this.metadata) { - serializationObject.metadata = this.metadata; - } - // Instances - serializationObject.instances = []; - for (let index = 0; index < this.instances.length; index++) { - const instance = this.instances[index]; - if (instance.doNotSerialize) { - continue; - } - const serializationInstance = { - name: instance.name, - id: instance.id, - isEnabled: instance.isEnabled(false), - isVisible: instance.isVisible, - isPickable: instance.isPickable, - checkCollisions: instance.checkCollisions, - position: instance.position.asArray(), - scaling: instance.scaling.asArray(), - }; - if (instance.parent) { - instance.parent._serializeAsParent(serializationInstance); - } - if (instance.rotationQuaternion) { - serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray(); - } - else if (instance.rotation) { - serializationInstance.rotation = instance.rotation.asArray(); - } - // Physics - //TODO implement correct serialization for physics impostors. - if (this.getScene()._getComponent(sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE)) { - const impostor = instance.getPhysicsImpostor(); - if (impostor) { - serializationInstance.physicsMass = impostor.getParam("mass"); - serializationInstance.physicsFriction = impostor.getParam("friction"); - serializationInstance.physicsRestitution = impostor.getParam("mass"); - serializationInstance.physicsImpostor = impostor.type; - } - } - // Metadata - if (instance.metadata) { - serializationInstance.metadata = instance.metadata; - } - // Action Manager - if (instance.actionManager) { - serializationInstance.actions = instance.actionManager.serialize(instance.name); - } - serializationObject.instances.push(serializationInstance); - // Animations - decorators_SerializationHelper.AppendSerializedAnimations(instance, serializationInstance); - serializationInstance.ranges = instance.serializeAnimationRanges(); - } - // Thin instances - if (this._thinInstanceDataStorage.instancesCount && this._thinInstanceDataStorage.matrixData) { - serializationObject.thinInstances = { - instancesCount: this._thinInstanceDataStorage.instancesCount, - matrixData: Array.from(this._thinInstanceDataStorage.matrixData), - matrixBufferSize: this._thinInstanceDataStorage.matrixBufferSize, - enablePicking: this.thinInstanceEnablePicking, - }; - if (this._userThinInstanceBuffersStorage) { - const userThinInstance = { - data: {}, - sizes: {}, - strides: {}, - }; - for (const kind in this._userThinInstanceBuffersStorage.data) { - userThinInstance.data[kind] = Array.from(this._userThinInstanceBuffersStorage.data[kind]); - userThinInstance.sizes[kind] = this._userThinInstanceBuffersStorage.sizes[kind]; - userThinInstance.strides[kind] = this._userThinInstanceBuffersStorage.strides[kind]; - } - serializationObject.thinInstances.userThinInstance = userThinInstance; - } - } - // Animations - decorators_SerializationHelper.AppendSerializedAnimations(this, serializationObject); - serializationObject.ranges = this.serializeAnimationRanges(); - // Layer mask - serializationObject.layerMask = this.layerMask; - // Alpha - serializationObject.alphaIndex = this.alphaIndex; - serializationObject.hasVertexAlpha = this.hasVertexAlpha; - // Overlay - serializationObject.overlayAlpha = this.overlayAlpha; - serializationObject.overlayColor = this.overlayColor.asArray(); - serializationObject.renderOverlay = this.renderOverlay; - // Fog - serializationObject.applyFog = this.applyFog; - // Action Manager - if (this.actionManager) { - serializationObject.actions = this.actionManager.serialize(this.name); - } - return serializationObject; - } - /** @internal */ - _syncGeometryWithMorphTargetManager() { - if (!this.geometry) { - return; - } - this._markSubMeshesAsAttributesDirty(); - const morphTargetManager = this._internalAbstractMeshDataInfo._morphTargetManager; - if (morphTargetManager && morphTargetManager.vertexCount) { - if (morphTargetManager.vertexCount !== this.getTotalVertices()) { - logger_Logger.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."); - this.morphTargetManager = null; - return; - } - if (morphTargetManager.isUsingTextureForTargets) { - return; - } - for (let index = 0; index < morphTargetManager.numInfluencers; index++) { - const morphTarget = morphTargetManager.getActiveTarget(index); - const positions = morphTarget.getPositions(); - if (!positions) { - logger_Logger.Error("Invalid morph target. Target must have positions."); - return; - } - this.geometry.setVerticesData(buffer_VertexBuffer.PositionKind + index, positions, false, 3); - const normals = morphTarget.getNormals(); - if (normals) { - this.geometry.setVerticesData(buffer_VertexBuffer.NormalKind + index, normals, false, 3); - } - const tangents = morphTarget.getTangents(); - if (tangents) { - this.geometry.setVerticesData(buffer_VertexBuffer.TangentKind + index, tangents, false, 3); - } - const uvs = morphTarget.getUVs(); - if (uvs) { - this.geometry.setVerticesData(buffer_VertexBuffer.UVKind + "_" + index, uvs, false, 2); - } - } - } - else { - let index = 0; - // Positions - while (this.geometry.isVerticesDataPresent(buffer_VertexBuffer.PositionKind + index)) { - this.geometry.removeVerticesData(buffer_VertexBuffer.PositionKind + index); - if (this.geometry.isVerticesDataPresent(buffer_VertexBuffer.NormalKind + index)) { - this.geometry.removeVerticesData(buffer_VertexBuffer.NormalKind + index); - } - if (this.geometry.isVerticesDataPresent(buffer_VertexBuffer.TangentKind + index)) { - this.geometry.removeVerticesData(buffer_VertexBuffer.TangentKind + index); - } - if (this.geometry.isVerticesDataPresent(buffer_VertexBuffer.UVKind + index)) { - this.geometry.removeVerticesData(buffer_VertexBuffer.UVKind + "_" + index); - } - index++; - } - } - } - /** - * Returns a new Mesh object parsed from the source provided. - * @param parsedMesh is the source - * @param scene defines the hosting scene - * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with - * @returns a new Mesh - */ - static Parse(parsedMesh, scene, rootUrl) { - let mesh; - if (parsedMesh.type && parsedMesh.type === "LinesMesh") { - mesh = mesh_Mesh._LinesMeshParser(parsedMesh, scene); - } - else if (parsedMesh.type && parsedMesh.type === "GroundMesh") { - mesh = mesh_Mesh._GroundMeshParser(parsedMesh, scene); - } - else if (parsedMesh.type && parsedMesh.type === "GoldbergMesh") { - mesh = mesh_Mesh._GoldbergMeshParser(parsedMesh, scene); - } - else if (parsedMesh.type && parsedMesh.type === "GreasedLineMesh") { - mesh = mesh_Mesh._GreasedLineMeshParser(parsedMesh, scene); - } - else if (parsedMesh.type && parsedMesh.type === "TrailMesh") { - mesh = mesh_Mesh._TrailMeshParser(parsedMesh, scene); - } - else { - mesh = new mesh_Mesh(parsedMesh.name, scene); - } - mesh.id = parsedMesh.id; - mesh._waitingParsedUniqueId = parsedMesh.uniqueId; - if (Tags) { - Tags.AddTagsTo(mesh, parsedMesh.tags); - } - mesh.position = math_vector_Vector3.FromArray(parsedMesh.position); - if (parsedMesh.metadata !== undefined) { - mesh.metadata = parsedMesh.metadata; - } - if (parsedMesh.rotationQuaternion) { - mesh.rotationQuaternion = math_vector_Quaternion.FromArray(parsedMesh.rotationQuaternion); - } - else if (parsedMesh.rotation) { - mesh.rotation = math_vector_Vector3.FromArray(parsedMesh.rotation); - } - mesh.scaling = math_vector_Vector3.FromArray(parsedMesh.scaling); - if (parsedMesh.localMatrix) { - mesh.setPreTransformMatrix(math_vector_Matrix.FromArray(parsedMesh.localMatrix)); - } - else if (parsedMesh.pivotMatrix) { - mesh.setPivotMatrix(math_vector_Matrix.FromArray(parsedMesh.pivotMatrix)); - } - mesh.setEnabled(parsedMesh.isEnabled); - mesh.isVisible = parsedMesh.isVisible; - mesh.infiniteDistance = parsedMesh.infiniteDistance; - mesh.showBoundingBox = parsedMesh.showBoundingBox; - mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox; - if (parsedMesh.applyFog !== undefined) { - mesh.applyFog = parsedMesh.applyFog; - } - if (parsedMesh.pickable !== undefined) { - mesh.isPickable = parsedMesh.pickable; - } - if (parsedMesh.alphaIndex !== undefined) { - mesh.alphaIndex = parsedMesh.alphaIndex; - } - mesh.receiveShadows = parsedMesh.receiveShadows; - if (parsedMesh.billboardMode !== undefined) { - mesh.billboardMode = parsedMesh.billboardMode; - } - if (parsedMesh.visibility !== undefined) { - mesh.visibility = parsedMesh.visibility; - } - mesh.checkCollisions = parsedMesh.checkCollisions; - mesh.overrideMaterialSideOrientation = parsedMesh.overrideMaterialSideOrientation; - if (parsedMesh.isBlocker !== undefined) { - mesh.isBlocker = parsedMesh.isBlocker; - } - mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading; - // freezeWorldMatrix - if (parsedMesh.freezeWorldMatrix) { - mesh._waitingData.freezeWorldMatrix = parsedMesh.freezeWorldMatrix; - } - // Parent - if (parsedMesh.parentId !== undefined) { - mesh._waitingParentId = parsedMesh.parentId; - } - if (parsedMesh.parentInstanceIndex !== undefined) { - mesh._waitingParentInstanceIndex = parsedMesh.parentInstanceIndex; - } - // Actions - if (parsedMesh.actions !== undefined) { - mesh._waitingData.actions = parsedMesh.actions; - } - // Overlay - if (parsedMesh.overlayAlpha !== undefined) { - mesh.overlayAlpha = parsedMesh.overlayAlpha; - } - if (parsedMesh.overlayColor !== undefined) { - mesh.overlayColor = math_color_Color3.FromArray(parsedMesh.overlayColor); - } - if (parsedMesh.renderOverlay !== undefined) { - mesh.renderOverlay = parsedMesh.renderOverlay; - } - // Geometry - mesh.isUnIndexed = !!parsedMesh.isUnIndexed; - mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha; - if (parsedMesh.delayLoadingFile) { - mesh.delayLoadState = 4; - mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile; - mesh.buildBoundingInfo(math_vector_Vector3.FromArray(parsedMesh.boundingBoxMinimum), math_vector_Vector3.FromArray(parsedMesh.boundingBoxMaximum)); - if (parsedMesh._binaryInfo) { - mesh._binaryInfo = parsedMesh._binaryInfo; - } - mesh._delayInfo = []; - if (parsedMesh.hasUVs) { - mesh._delayInfo.push(buffer_VertexBuffer.UVKind); - } - if (parsedMesh.hasUVs2) { - mesh._delayInfo.push(buffer_VertexBuffer.UV2Kind); - } - if (parsedMesh.hasUVs3) { - mesh._delayInfo.push(buffer_VertexBuffer.UV3Kind); - } - if (parsedMesh.hasUVs4) { - mesh._delayInfo.push(buffer_VertexBuffer.UV4Kind); - } - if (parsedMesh.hasUVs5) { - mesh._delayInfo.push(buffer_VertexBuffer.UV5Kind); - } - if (parsedMesh.hasUVs6) { - mesh._delayInfo.push(buffer_VertexBuffer.UV6Kind); - } - if (parsedMesh.hasColors) { - mesh._delayInfo.push(buffer_VertexBuffer.ColorKind); - } - if (parsedMesh.hasMatricesIndices) { - mesh._delayInfo.push(buffer_VertexBuffer.MatricesIndicesKind); - } - if (parsedMesh.hasMatricesWeights) { - mesh._delayInfo.push(buffer_VertexBuffer.MatricesWeightsKind); - } - mesh._delayLoadingFunction = Geometry._ImportGeometry; - if (SceneLoaderFlags.ForceFullSceneLoadingForIncremental) { - mesh._checkDelayState(); - } - } - else { - Geometry._ImportGeometry(parsedMesh, mesh); - } - // Material - if (parsedMesh.materialUniqueId) { - mesh._waitingMaterialId = parsedMesh.materialUniqueId; - } - else if (parsedMesh.materialId) { - mesh._waitingMaterialId = parsedMesh.materialId; - } - // Morph targets - if (parsedMesh.morphTargetManagerId > -1) { - mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId); - } - // Skeleton - if (parsedMesh.skeletonId !== undefined && parsedMesh.skeletonId !== null) { - mesh.skeleton = scene.getLastSkeletonById(parsedMesh.skeletonId); - if (parsedMesh.numBoneInfluencers) { - mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers; - } - } - // Animations - if (parsedMesh.animations) { - for (let animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) { - const parsedAnimation = parsedMesh.animations[animationIndex]; - const internalClass = GetClass("BABYLON.Animation"); - if (internalClass) { - mesh.animations.push(internalClass.Parse(parsedAnimation)); - } - } - node_Node.ParseAnimationRanges(mesh, parsedMesh, scene); - } - if (parsedMesh.autoAnimate) { - scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0); - } - // Layer Mask - if (parsedMesh.layerMask && !isNaN(parsedMesh.layerMask)) { - mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask)); - } - else { - mesh.layerMask = 0x0fffffff; - } - // Physics - if (parsedMesh.physicsImpostor) { - mesh_Mesh._PhysicsImpostorParser(scene, mesh, parsedMesh); - } - // Levels - if (parsedMesh.lodMeshIds) { - mesh._waitingData.lods = { - ids: parsedMesh.lodMeshIds, - distances: parsedMesh.lodDistances ? parsedMesh.lodDistances : null, - coverages: parsedMesh.lodCoverages ? parsedMesh.lodCoverages : null, - }; - } - // Instances - if (parsedMesh.instances) { - for (let index = 0; index < parsedMesh.instances.length; index++) { - const parsedInstance = parsedMesh.instances[index]; - const instance = mesh.createInstance(parsedInstance.name); - if (parsedInstance.id) { - instance.id = parsedInstance.id; - } - if (Tags) { - if (parsedInstance.tags) { - Tags.AddTagsTo(instance, parsedInstance.tags); - } - else { - Tags.AddTagsTo(instance, parsedMesh.tags); - } - } - instance.position = math_vector_Vector3.FromArray(parsedInstance.position); - if (parsedInstance.metadata !== undefined) { - instance.metadata = parsedInstance.metadata; - } - if (parsedInstance.parentId !== undefined) { - instance._waitingParentId = parsedInstance.parentId; - } - if (parsedInstance.parentInstanceIndex !== undefined) { - instance._waitingParentInstanceIndex = parsedInstance.parentInstanceIndex; - } - if (parsedInstance.isEnabled !== undefined && parsedInstance.isEnabled !== null) { - instance.setEnabled(parsedInstance.isEnabled); - } - if (parsedInstance.isVisible !== undefined && parsedInstance.isVisible !== null) { - instance.isVisible = parsedInstance.isVisible; - } - if (parsedInstance.isPickable !== undefined && parsedInstance.isPickable !== null) { - instance.isPickable = parsedInstance.isPickable; - } - if (parsedInstance.rotationQuaternion) { - instance.rotationQuaternion = math_vector_Quaternion.FromArray(parsedInstance.rotationQuaternion); - } - else if (parsedInstance.rotation) { - instance.rotation = math_vector_Vector3.FromArray(parsedInstance.rotation); - } - instance.scaling = math_vector_Vector3.FromArray(parsedInstance.scaling); - if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) { - instance.checkCollisions = parsedInstance.checkCollisions; - } - if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) { - instance.isPickable = parsedInstance.pickable; - } - if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) { - instance.showBoundingBox = parsedInstance.showBoundingBox; - } - if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) { - instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox; - } - if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) { - instance.alphaIndex = parsedInstance.alphaIndex; - } - // Physics - if (parsedInstance.physicsImpostor) { - mesh_Mesh._PhysicsImpostorParser(scene, instance, parsedInstance); - } - // Actions - if (parsedInstance.actions !== undefined) { - instance._waitingData.actions = parsedInstance.actions; - } - // Animation - if (parsedInstance.animations) { - for (let animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) { - const parsedAnimation = parsedInstance.animations[animationIndex]; - const internalClass = GetClass("BABYLON.Animation"); - if (internalClass) { - instance.animations.push(internalClass.Parse(parsedAnimation)); - } - } - node_Node.ParseAnimationRanges(instance, parsedInstance, scene); - if (parsedInstance.autoAnimate) { - scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0); - } - } - } - } - // Thin instances - if (parsedMesh.thinInstances) { - const thinInstances = parsedMesh.thinInstances; - mesh.thinInstanceEnablePicking = !!thinInstances.enablePicking; - if (thinInstances.matrixData) { - mesh.thinInstanceSetBuffer("matrix", new Float32Array(thinInstances.matrixData), 16, false); - mesh._thinInstanceDataStorage.matrixBufferSize = thinInstances.matrixBufferSize; - mesh._thinInstanceDataStorage.instancesCount = thinInstances.instancesCount; - } - else { - mesh._thinInstanceDataStorage.matrixBufferSize = thinInstances.matrixBufferSize; - } - if (parsedMesh.thinInstances.userThinInstance) { - const userThinInstance = parsedMesh.thinInstances.userThinInstance; - for (const kind in userThinInstance.data) { - mesh.thinInstanceSetBuffer(kind, new Float32Array(userThinInstance.data[kind]), userThinInstance.strides[kind], false); - mesh._userThinInstanceBuffersStorage.sizes[kind] = userThinInstance.sizes[kind]; - } - } - } - return mesh; - } - // Skeletons - /** - * Prepare internal position array for software CPU skinning - * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh - */ - setPositionsForCPUSkinning() { - const internalDataInfo = this._internalMeshDataInfo; - if (!internalDataInfo._sourcePositions) { - const source = this.getVerticesData(buffer_VertexBuffer.PositionKind); - if (!source) { - return internalDataInfo._sourcePositions; - } - internalDataInfo._sourcePositions = new Float32Array(source); - if (!this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind)) { - this.setVerticesData(buffer_VertexBuffer.PositionKind, source, true); - } - } - return internalDataInfo._sourcePositions; - } - /** - * Prepare internal normal array for software CPU skinning - * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. - */ - setNormalsForCPUSkinning() { - const internalDataInfo = this._internalMeshDataInfo; - if (!internalDataInfo._sourceNormals) { - const source = this.getVerticesData(buffer_VertexBuffer.NormalKind); - if (!source) { - return internalDataInfo._sourceNormals; - } - internalDataInfo._sourceNormals = new Float32Array(source); - if (!this.isVertexBufferUpdatable(buffer_VertexBuffer.NormalKind)) { - this.setVerticesData(buffer_VertexBuffer.NormalKind, source, true); - } - } - return internalDataInfo._sourceNormals; - } - /** - * Updates the vertex buffer by applying transformation from the bones - * @param skeleton defines the skeleton to apply to current mesh - * @returns the current mesh - */ - applySkeleton(skeleton) { - if (!this.geometry) { - return this; - } - if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) { - return this; - } - this.geometry._softwareSkinningFrameId = this.getScene().getFrameId(); - if (!this.isVerticesDataPresent(buffer_VertexBuffer.PositionKind)) { - return this; - } - if (!this.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesKind)) { - return this; - } - if (!this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)) { - return this; - } - const hasNormals = this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind); - const internalDataInfo = this._internalMeshDataInfo; - if (!internalDataInfo._sourcePositions) { - const submeshes = this.subMeshes.slice(); - this.setPositionsForCPUSkinning(); - this.subMeshes = submeshes; - } - if (hasNormals && !internalDataInfo._sourceNormals) { - this.setNormalsForCPUSkinning(); - } - // positionsData checks for not being Float32Array will only pass at most once - let positionsData = this.getVerticesData(buffer_VertexBuffer.PositionKind); - if (!positionsData) { - return this; - } - if (!(positionsData instanceof Float32Array)) { - positionsData = new Float32Array(positionsData); - } - // normalsData checks for not being Float32Array will only pass at most once - let normalsData = this.getVerticesData(buffer_VertexBuffer.NormalKind); - if (hasNormals) { - if (!normalsData) { - return this; - } - if (!(normalsData instanceof Float32Array)) { - normalsData = new Float32Array(normalsData); - } - } - const matricesIndicesData = this.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind); - const matricesWeightsData = this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind); - if (!matricesWeightsData || !matricesIndicesData) { - return this; - } - const needExtras = this.numBoneInfluencers > 4; - const matricesIndicesExtraData = needExtras ? this.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind) : null; - const matricesWeightsExtraData = needExtras ? this.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind) : null; - const skeletonMatrices = skeleton.getTransformMatrices(this); - const tempVector3 = math_vector_Vector3.Zero(); - const finalMatrix = new math_vector_Matrix(); - const tempMatrix = new math_vector_Matrix(); - let matWeightIdx = 0; - let inf; - for (let index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) { - let weight; - for (inf = 0; inf < 4; inf++) { - weight = matricesWeightsData[matWeightIdx + inf]; - if (weight > 0) { - math_vector_Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix); - finalMatrix.addToSelf(tempMatrix); - } - } - if (needExtras) { - for (inf = 0; inf < 4; inf++) { - weight = matricesWeightsExtraData[matWeightIdx + inf]; - if (weight > 0) { - math_vector_Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix); - finalMatrix.addToSelf(tempMatrix); - } - } - } - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(internalDataInfo._sourcePositions[index], internalDataInfo._sourcePositions[index + 1], internalDataInfo._sourcePositions[index + 2], finalMatrix, tempVector3); - tempVector3.toArray(positionsData, index); - if (hasNormals) { - math_vector_Vector3.TransformNormalFromFloatsToRef(internalDataInfo._sourceNormals[index], internalDataInfo._sourceNormals[index + 1], internalDataInfo._sourceNormals[index + 2], finalMatrix, tempVector3); - tempVector3.toArray(normalsData, index); - } - finalMatrix.reset(); - } - this.updateVerticesData(buffer_VertexBuffer.PositionKind, positionsData); - if (hasNormals) { - this.updateVerticesData(buffer_VertexBuffer.NormalKind, normalsData); - } - return this; - } - // Tools - /** - * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates - * @param meshes defines the list of meshes to scan - * @returns an object `{min:` Vector3`, max:` Vector3`}` - */ - static MinMax(meshes) { - let minVector = null; - let maxVector = null; - meshes.forEach(function (mesh) { - const boundingInfo = mesh.getBoundingInfo(); - const boundingBox = boundingInfo.boundingBox; - if (!minVector || !maxVector) { - minVector = boundingBox.minimumWorld; - maxVector = boundingBox.maximumWorld; - } - else { - minVector.minimizeInPlace(boundingBox.minimumWorld); - maxVector.maximizeInPlace(boundingBox.maximumWorld); - } - }); - if (!minVector || !maxVector) { - return { - min: math_vector_Vector3.Zero(), - max: math_vector_Vector3.Zero(), - }; - } - return { - min: minVector, - max: maxVector, - }; - } - /** - * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array - * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object - * @returns a vector3 - */ - static Center(meshesOrMinMaxVector) { - const minMaxVector = meshesOrMinMaxVector instanceof Array ? mesh_Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector; - return math_vector_Vector3.Center(minMaxVector.min, minMaxVector.max); - } - /** - * Merge the array of meshes into a single mesh for performance reasons. - * @param meshes array of meshes with the vertices to merge. Entries cannot be empty meshes. - * @param disposeSource when true (default), dispose of the vertices from the source meshes. - * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true. - * @param meshSubclass (optional) can be set to a Mesh where the merged vertices will be inserted. - * @param subdivideWithSubMeshes when true (false default), subdivide mesh into subMeshes. - * @param multiMultiMaterials when true (false default), subdivide mesh into subMeshes with multiple materials, ignores subdivideWithSubMeshes. - * @returns a new mesh - */ - static MergeMeshes(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) { - return runCoroutineSync(mesh_Mesh._MergeMeshesCoroutine(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, false)); - } - /** - * Merge the array of meshes into a single mesh for performance reasons. - * @param meshes array of meshes with the vertices to merge. Entries cannot be empty meshes. - * @param disposeSource when true (default), dispose of the vertices from the source meshes. - * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true. - * @param meshSubclass (optional) can be set to a Mesh where the merged vertices will be inserted. - * @param subdivideWithSubMeshes when true (false default), subdivide mesh into subMeshes. - * @param multiMultiMaterials when true (false default), subdivide mesh into subMeshes with multiple materials, ignores subdivideWithSubMeshes. - * @returns a new mesh - */ - static MergeMeshesAsync(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) { - return runCoroutineAsync(mesh_Mesh._MergeMeshesCoroutine(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, true), createYieldingScheduler()); - } - static *_MergeMeshesCoroutine(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, isAsync) { - // Remove any null/undefined entries from the mesh array - meshes = meshes.filter(Boolean); - if (meshes.length === 0) { - return null; - } - let index; - if (!allow32BitsIndices) { - let totalVertices = 0; - // Counting vertices - for (index = 0; index < meshes.length; index++) { - totalVertices += meshes[index].getTotalVertices(); - if (totalVertices >= 65536) { - logger_Logger.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"); - return null; - } - } - } - if (multiMultiMaterials) { - subdivideWithSubMeshes = false; - } - const materialArray = new Array(); - const materialIndexArray = new Array(); - // Merge - const indiceArray = new Array(); - const currentOverrideMaterialSideOrientation = meshes[0].overrideMaterialSideOrientation; - for (index = 0; index < meshes.length; index++) { - const mesh = meshes[index]; - if (mesh.isAnInstance) { - logger_Logger.Warn("Cannot merge instance meshes."); - return null; - } - if (currentOverrideMaterialSideOrientation !== mesh.overrideMaterialSideOrientation) { - logger_Logger.Warn("Cannot merge meshes with different overrideMaterialSideOrientation values."); - return null; - } - if (subdivideWithSubMeshes) { - indiceArray.push(mesh.getTotalIndices()); - } - if (multiMultiMaterials) { - if (mesh.material) { - const material = mesh.material; - if (material instanceof multiMaterial_MultiMaterial) { - for (let matIndex = 0; matIndex < material.subMaterials.length; matIndex++) { - if (materialArray.indexOf(material.subMaterials[matIndex]) < 0) { - materialArray.push(material.subMaterials[matIndex]); - } - } - for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { - materialIndexArray.push(materialArray.indexOf(material.subMaterials[mesh.subMeshes[subIndex].materialIndex])); - indiceArray.push(mesh.subMeshes[subIndex].indexCount); - } - } - else { - if (materialArray.indexOf(material) < 0) { - materialArray.push(material); - } - for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { - materialIndexArray.push(materialArray.indexOf(material)); - indiceArray.push(mesh.subMeshes[subIndex].indexCount); - } - } - } - else { - for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { - materialIndexArray.push(0); - indiceArray.push(mesh.subMeshes[subIndex].indexCount); - } - } - } - } - const source = meshes[0]; - const getVertexDataFromMesh = (mesh) => { - const wm = mesh.computeWorldMatrix(true); - const vertexData = mesh_vertexData_VertexData.ExtractFromMesh(mesh, false, false); - return { vertexData, transform: wm }; - }; - const { vertexData: sourceVertexData, transform: sourceTransform } = getVertexDataFromMesh(source); - if (isAsync) { - yield; - } - const meshVertexDatas = new Array(meshes.length - 1); - for (let i = 1; i < meshes.length; i++) { - meshVertexDatas[i - 1] = getVertexDataFromMesh(meshes[i]); - if (isAsync) { - yield; - } - } - const mergeCoroutine = sourceVertexData._mergeCoroutine(sourceTransform, meshVertexDatas, allow32BitsIndices, isAsync, !disposeSource); - let mergeCoroutineStep = mergeCoroutine.next(); - while (!mergeCoroutineStep.done) { - if (isAsync) { - yield; - } - mergeCoroutineStep = mergeCoroutine.next(); - } - const vertexData = mergeCoroutineStep.value; - if (!meshSubclass) { - meshSubclass = new mesh_Mesh(source.name + "_merged", source.getScene()); - } - const applyToCoroutine = vertexData._applyToCoroutine(meshSubclass, undefined, isAsync); - let applyToCoroutineStep = applyToCoroutine.next(); - while (!applyToCoroutineStep.done) { - if (isAsync) { - yield; - } - applyToCoroutineStep = applyToCoroutine.next(); - } - // Setting properties - meshSubclass.checkCollisions = source.checkCollisions; - meshSubclass.overrideMaterialSideOrientation = source.overrideMaterialSideOrientation; - // Cleaning - if (disposeSource) { - for (index = 0; index < meshes.length; index++) { - meshes[index].dispose(); - } - } - // Subdivide - if (subdivideWithSubMeshes || multiMultiMaterials) { - //-- removal of global submesh - meshSubclass.releaseSubMeshes(); - index = 0; - let offset = 0; - //-- apply subdivision according to index table - while (index < indiceArray.length) { - subMesh_SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass, undefined, false); - offset += indiceArray[index]; - index++; - } - for (const subMesh of meshSubclass.subMeshes) { - subMesh.refreshBoundingInfo(); - } - meshSubclass.computeWorldMatrix(true); - } - if (multiMultiMaterials) { - const newMultiMaterial = new multiMaterial_MultiMaterial(source.name + "_merged", source.getScene()); - newMultiMaterial.subMaterials = materialArray; - for (let subIndex = 0; subIndex < meshSubclass.subMeshes.length; subIndex++) { - meshSubclass.subMeshes[subIndex].materialIndex = materialIndexArray[subIndex]; - } - meshSubclass.material = newMultiMaterial; - } - else { - meshSubclass.material = source.material; - } - return meshSubclass; - } - /** - * @internal - */ - addInstance(instance) { - instance._indexInSourceMeshInstanceArray = this.instances.length; - this.instances.push(instance); - } - /** - * @internal - */ - removeInstance(instance) { - // Remove from mesh - const index = instance._indexInSourceMeshInstanceArray; - if (index != -1) { - if (index !== this.instances.length - 1) { - const last = this.instances[this.instances.length - 1]; - this.instances[index] = last; - last._indexInSourceMeshInstanceArray = index; - } - instance._indexInSourceMeshInstanceArray = -1; - this.instances.pop(); - } - } - /** @internal */ - _shouldConvertRHS() { - return this.overrideMaterialSideOrientation === material_Material.CounterClockWiseSideOrientation; - } - /** @internal */ - _getRenderingFillMode(fillMode) { - var _a; - const scene = this.getScene(); - if (scene.forcePointsCloud) - return material_Material.PointFillMode; - if (scene.forceWireframe) - return material_Material.WireFrameFillMode; - return (_a = this.overrideRenderingFillMode) !== null && _a !== void 0 ? _a : fillMode; - } - // deprecated methods - /** - * Sets the mesh material by the material or multiMaterial `id` property - * @param id is a string identifying the material or the multiMaterial - * @returns the current mesh - * @deprecated Please use MeshBuilder instead Please use setMaterialById instead - */ - setMaterialByID(id) { - return this.setMaterialById(id); - } - /** - * Creates a ribbon mesh. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param - * @param name defines the name of the mesh to create - * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry. - * @param closeArray creates a seam between the first and the last paths of the path array (default is false) - * @param closePath creates a seam between the first and the last points of each path of the path array - * @param offset is taken in account only if the `pathArray` is containing a single path - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateRibbon(name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a plane polygonal mesh. By default, this is a disc. - * @param name defines the name of the mesh to create - * @param radius sets the radius size (float) of the polygon (default 0.5) - * @param 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 - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateDisc(name, radius, tessellation, scene, updatable, sideOrientation) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a box mesh. - * @param name defines the name of the mesh to create - * @param size sets the size (float) of each box side (default 1) - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateBox(name, size, scene, updatable, sideOrientation) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a sphere mesh. - * @param name defines the name of the mesh to create - * @param segments sets the sphere number of horizontal stripes (positive integer, default 32) - * @param diameter sets the diameter size (float) of the sphere (default 1) - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateSphere(name, segments, diameter, scene, updatable, sideOrientation) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a hemisphere mesh. - * @param name defines the name of the mesh to create - * @param segments sets the sphere number of horizontal stripes (positive integer, default 32) - * @param diameter sets the diameter size (float) of the sphere (default 1) - * @param scene defines the hosting scene - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateHemisphere(name, segments, diameter, scene) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a cylinder or a cone mesh. - * @param name defines the name of the mesh to create - * @param height sets the height size (float) of the cylinder/cone (float, default 2) - * @param diameterTop set the top cap diameter (floats, default 1) - * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero - * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance - * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1) - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateCylinder(name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) { - throw new Error("Import MeshBuilder to populate this function"); - } - // Torus (Code from SharpDX.org) - /** - * Creates a torus mesh. - * @param name defines the name of the mesh to create - * @param diameter sets the diameter size (float) of the torus (default 1) - * @param thickness sets the diameter size of the tube of the torus (float, default 0.5) - * @param tessellation sets the number of torus sides (positive integer, default 16) - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateTorus(name, diameter, thickness, tessellation, scene, updatable, sideOrientation) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a torus knot mesh. - * @param name defines the name of the mesh to create - * @param radius sets the global radius size (float) of the torus knot (default 2) - * @param tube sets the diameter size of the tube of the torus (float, default 0.5) - * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32) - * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32) - * @param p the number of windings on X axis (positive integers, default 2) - * @param q the number of windings on Y axis (positive integers, default 3) - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateTorusKnot(name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a line mesh.. - * @param name defines the name of the mesh to create - * @param points is an array successive Vector3 - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines). - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateLines(name, points, scene, updatable, instance) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a dashed line mesh. - * @param name defines the name of the mesh to create - * @param points is an array successive Vector3 - * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3) - * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1) - * @param dashNb is the intended total number of dashes (positive integer, default 200) - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateDashedLines(name, points, dashSize, gapSize, dashNb, scene, updatable, instance) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead - * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh. - * 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. - * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * Remember you can only change the shape positions, not their number when updating a polygon. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#non-regular-polygon - * @param name defines the name of the mesh to create - * @param 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 - * @param scene defines the hosting scene - * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @param earcutInjection can be used to inject your own earcut reference - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreatePolygon(name, shape, scene, holes, updatable, sideOrientation, earcutInjection) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates an extruded polygon mesh, with depth in the Y direction.. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-non-regular-polygon - * @param name defines the name of the mesh to create - * @param 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 - * @param depth defines the height of extrusion - * @param scene defines the hosting scene - * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @param earcutInjection can be used to inject your own earcut reference - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static ExtrudePolygon(name, shape, depth, scene, holes, updatable, sideOrientation, earcutInjection) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * 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. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes - * @param name defines the name of the mesh to create - * @param 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 - * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along - * @param scale is the value to scale the shape - * @param rotation 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 - * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @param 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/how_to/How_to_dynamically_morph_a_mesh#extruded-shape) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static ExtrudeShape(name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates an custom extruded shape mesh. - * The custom extrusion is a parametric shape. - * It has no predefined shape. Its final shape will depend on the input parameters. - * - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes - * @param name defines the name of the mesh to create - * @param 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 - * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along - * @param scaleFunction is a custom Javascript function called on each path point - * @param rotationFunction is a custom Javascript function called on each path point - * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray` - * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray` - * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @param 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) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static ExtrudeShapeCustom(name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates lathe mesh. - * The lathe is a shape with a symmetry axis : a 2D model shape is rotated around this axis to design the lathe. - * @param name defines the name of the mesh to create - * @param 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 - * @param radius is the radius value of the lathe - * @param tessellation is the side number of the lathe. - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateLathe(name, shape, radius, tessellation, scene, updatable, sideOrientation) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a plane mesh. - * @param name defines the name of the mesh to create - * @param size sets the size (float) of both sides of the plane at once (default 1) - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreatePlane(name, size, scene, updatable, sideOrientation) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a ground mesh. - * @param name defines the name of the mesh to create - * @param width set the width of the ground - * @param height set the height of the ground - * @param subdivisions sets the number of subdivisions per side - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateGround(name, width, height, subdivisions, scene, updatable) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a tiled ground mesh. - * @param name defines the name of the mesh to create - * @param xmin set the ground minimum X coordinate - * @param zmin set the ground minimum Y coordinate - * @param xmax set the ground maximum X coordinate - * @param zmax set the ground maximum Z coordinate - * @param subdivisions is an 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 - * @param precision is an 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 - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateTiledGround(name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a ground mesh from a height map. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/height_map - * @param name defines the name of the mesh to create - * @param url sets the URL of the height map image resource - * @param width set the ground width size - * @param height set the ground height size - * @param subdivisions sets the number of subdivision per side - * @param minHeight is the minimum altitude on the ground - * @param maxHeight is the maximum altitude on the ground - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time) - * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateGroundFromHeightMap(name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a tube mesh. - * The tube is a parametric shape. - * It has no predefined shape. Its final shape will depend on the input parameters. - * - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param - * @param name defines the name of the mesh to create - * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube - * @param radius sets the tube radius size - * @param tessellation is the number of sides on the tubular surface - * @param radiusFunction is a custom function. If it is not null, it overrides the parameter `radius`. 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 - * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL - * @param scene defines the hosting scene - * @param updatable defines if the mesh must be flagged as updatable - * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) - * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube) - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateTube(name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a polyhedron mesh. - *. - * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embedded types. Please refer to the type sheet in the tutorial to choose the wanted type - * * The parameter `size` (positive float, default 1) sets the polygon size - * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value) - * * 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 overwrittes the parameter `type` - * * 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 - * * 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)`) - * * 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 - * * 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 - * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh to create - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreatePolyhedron(name, options, scene) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided - * * The parameter `radius` sets the radius size (float) of the icosphere (default 1) - * * 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 than `radius`) - * * The parameter `subdivisions` sets the number of subdivisions (positive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size - * * 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 - * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra#icosphere - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param scene defines the hosting scene - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateIcoSphere(name, options, scene) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Creates a decal mesh. - *. - * A decal is a mesh usually applied as a model onto the surface of another mesh - * @param name defines the name of the mesh - * @param sourceMesh defines the mesh receiving the decal - * @param position sets the position of the decal in world coordinates - * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates - * @param size sets the decal scaling - * @param angle sets the angle to rotate the decal - * @returns a new Mesh - * @deprecated Please use MeshBuilder instead - */ - static CreateDecal(name, sourceMesh, position, normal, size, angle) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** Creates a Capsule Mesh - * @param name defines the name of the mesh. - * @param options the constructors options used to shape the mesh. - * @param scene defines the scene the mesh is scoped to. - * @returns the capsule mesh - * @see https://doc.babylonjs.com/how_to/capsule_shape - * @deprecated Please use MeshBuilder instead - */ - static CreateCapsule(name, options, scene) { - throw new Error("Import MeshBuilder to populate this function"); - } - /** - * Extends a mesh to a Goldberg mesh - * Warning the mesh to convert MUST be an import of a perviously exported Goldberg mesh - * @param mesh the mesh to convert - * @returns the extended mesh - * @deprecated Please use ExtendMeshToGoldberg instead - */ - static ExtendToGoldberg(mesh) { - throw new Error("Import MeshBuilder to populate this function"); - } -} -// Consts -/** - * Mesh side orientation : usually the external or front surface - */ -mesh_Mesh.FRONTSIDE = mesh_vertexData_VertexData.FRONTSIDE; -/** - * Mesh side orientation : usually the internal or back surface - */ -mesh_Mesh.BACKSIDE = mesh_vertexData_VertexData.BACKSIDE; -/** - * Mesh side orientation : both internal and external or front and back surfaces - */ -mesh_Mesh.DOUBLESIDE = mesh_vertexData_VertexData.DOUBLESIDE; -/** - * Mesh side orientation : by default, `FRONTSIDE` - */ -mesh_Mesh.DEFAULTSIDE = mesh_vertexData_VertexData.DEFAULTSIDE; -/** - * Mesh cap setting : no cap - */ -mesh_Mesh.NO_CAP = 0; -/** - * Mesh cap setting : one cap at the beginning of the mesh - */ -mesh_Mesh.CAP_START = 1; -/** - * Mesh cap setting : one cap at the end of the mesh - */ -mesh_Mesh.CAP_END = 2; -/** - * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh - */ -mesh_Mesh.CAP_ALL = 3; -/** - * Mesh pattern setting : no flip or rotate - */ -mesh_Mesh.NO_FLIP = 0; -/** - * Mesh pattern setting : flip (reflect in y axis) alternate tiles on each row or column - */ -mesh_Mesh.FLIP_TILE = 1; -/** - * Mesh pattern setting : rotate (180degs) alternate tiles on each row or column - */ -mesh_Mesh.ROTATE_TILE = 2; -/** - * Mesh pattern setting : flip (reflect in y axis) all tiles on alternate rows - */ -mesh_Mesh.FLIP_ROW = 3; -/** - * Mesh pattern setting : rotate (180degs) all tiles on alternate rows - */ -mesh_Mesh.ROTATE_ROW = 4; -/** - * Mesh pattern setting : flip and rotate alternate tiles on each row or column - */ -mesh_Mesh.FLIP_N_ROTATE_TILE = 5; -/** - * Mesh pattern setting : rotate pattern and rotate - */ -mesh_Mesh.FLIP_N_ROTATE_ROW = 6; -/** - * Mesh tile positioning : part tiles same on left/right or top/bottom - */ -mesh_Mesh.CENTER = 0; -/** - * Mesh tile positioning : part tiles on left - */ -mesh_Mesh.LEFT = 1; -/** - * Mesh tile positioning : part tiles on right - */ -mesh_Mesh.RIGHT = 2; -/** - * Mesh tile positioning : part tiles on top - */ -mesh_Mesh.TOP = 3; -/** - * Mesh tile positioning : part tiles on bottom - */ -mesh_Mesh.BOTTOM = 4; -/** - * Indicates that the instanced meshes should be sorted from back to front before rendering if their material is transparent - */ -mesh_Mesh.INSTANCEDMESH_SORT_TRANSPARENT = false; -// Statics -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -mesh_Mesh._GroundMeshParser = (parsedMesh, scene) => { - throw _WarnImport("GroundMesh"); -}; -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -mesh_Mesh._GoldbergMeshParser = (parsedMesh, scene) => { - throw _WarnImport("GoldbergMesh"); -}; -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -mesh_Mesh._LinesMeshParser = (parsedMesh, scene) => { - throw _WarnImport("LinesMesh"); -}; -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -mesh_Mesh._GreasedLineMeshParser = (parsedMesh, scene) => { - throw _WarnImport("GreasedLineMesh"); -}; -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -mesh_Mesh._TrailMeshParser = (parsedMesh, scene) => { - throw _WarnImport("TrailMesh"); -}; -RegisterClass("BABYLON.Mesh", mesh_Mesh); -//# sourceMappingURL=mesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/instancedMesh.js - - - - - - - - -mesh_Mesh._instancedMeshFactory = (name, mesh) => { - const instance = new instancedMesh_InstancedMesh(name, mesh); - if (mesh.instancedBuffers) { - instance.instancedBuffers = {}; - for (const key in mesh.instancedBuffers) { - instance.instancedBuffers[key] = mesh.instancedBuffers[key]; - } - } - return instance; -}; -/** - * Creates an instance based on a source mesh. - */ -class instancedMesh_InstancedMesh extends abstractMesh_AbstractMesh { - /** - * Creates a new InstancedMesh object from the mesh source. - * @param name defines the name of the instance - * @param source the mesh to create the instance from - */ - constructor(name, source) { - super(name, source.getScene()); - /** @internal */ - this._indexInSourceMeshInstanceArray = -1; - /** @internal */ - this._distanceToCamera = 0; - source.addInstance(this); - this._sourceMesh = source; - this._unIndexed = source._unIndexed; - this.position.copyFrom(source.position); - this.rotation.copyFrom(source.rotation); - this.scaling.copyFrom(source.scaling); - if (source.rotationQuaternion) { - this.rotationQuaternion = source.rotationQuaternion.clone(); - } - this.animations = source.animations.slice(); - for (const range of source.getAnimationRanges()) { - if (range != null) { - this.createAnimationRange(range.name, range.from, range.to); - } - } - this.infiniteDistance = source.infiniteDistance; - this.setPivotMatrix(source.getPivotMatrix()); - this.refreshBoundingInfo(true, true); - this._syncSubMeshes(); - } - /** - * Returns the string "InstancedMesh". - */ - getClassName() { - return "InstancedMesh"; - } - /** Gets the list of lights affecting that mesh */ - get lightSources() { - return this._sourceMesh._lightSources; - } - _resyncLightSources() { - // Do nothing as all the work will be done by source mesh - } - _resyncLightSource() { - // Do nothing as all the work will be done by source mesh - } - _removeLightSource() { - // Do nothing as all the work will be done by source mesh - } - // Methods - /** - * If the source mesh receives shadows - */ - get receiveShadows() { - return this._sourceMesh.receiveShadows; - } - set receiveShadows(_value) { - var _a; - if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.receiveShadows) !== _value) { - tools_Tools.Warn("Setting receiveShadows on an instanced mesh has no effect"); - } - } - /** - * The material of the source mesh - */ - get material() { - return this._sourceMesh.material; - } - set material(_value) { - var _a; - if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.material) !== _value) { - tools_Tools.Warn("Setting material on an instanced mesh has no effect"); - } - } - /** - * Visibility of the source mesh - */ - get visibility() { - return this._sourceMesh.visibility; - } - set visibility(_value) { - var _a; - if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.visibility) !== _value) { - tools_Tools.Warn("Setting visibility on an instanced mesh has no effect"); - } - } - /** - * Skeleton of the source mesh - */ - get skeleton() { - return this._sourceMesh.skeleton; - } - set skeleton(_value) { - var _a; - if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.skeleton) !== _value) { - tools_Tools.Warn("Setting skeleton on an instanced mesh has no effect"); - } - } - /** - * Rendering ground id of the source mesh - */ - get renderingGroupId() { - return this._sourceMesh.renderingGroupId; - } - set renderingGroupId(value) { - if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) { - return; - } - //no-op with warning - logger_Logger.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene"); - } - /** - * Returns the total number of vertices (integer). - */ - getTotalVertices() { - return this._sourceMesh ? this._sourceMesh.getTotalVertices() : 0; - } - /** - * Returns a positive integer : the total number of indices in this mesh geometry. - * @returns the number of indices or zero if the mesh has no geometry. - */ - getTotalIndices() { - return this._sourceMesh.getTotalIndices(); - } - /** - * The source mesh of the instance - */ - get sourceMesh() { - return this._sourceMesh; - } - /** - * Creates a new InstancedMesh object from the mesh model. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances - * @param name defines the name of the new instance - * @returns a new InstancedMesh - */ - createInstance(name) { - return this._sourceMesh.createInstance(name); - } - /** - * Is this node ready to be used/rendered - * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) - * @returns {boolean} is it ready - */ - isReady(completeCheck = false) { - return this._sourceMesh.isReady(completeCheck, true); - } - /** - * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices. - * @param kind kind of verticies to retrieve (eg. positions, normals, uvs, etc.) - * @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. - * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is - * @returns a float array or a Float32Array of the requested kind of data : positions, normals, uvs, etc. - */ - getVerticesData(kind, copyWhenShared, forceCopy) { - return this._sourceMesh.getVerticesData(kind, copyWhenShared, forceCopy); - } - /** - * Sets the vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. - * The `data` are either a numeric array either a Float32Array. - * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initially none) or updater. - * 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). - * Note that a new underlying VertexBuffer object is created each call. - * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. - * - * Possible `kind` values : - * - VertexBuffer.PositionKind - * - VertexBuffer.UVKind - * - VertexBuffer.UV2Kind - * - VertexBuffer.UV3Kind - * - VertexBuffer.UV4Kind - * - VertexBuffer.UV5Kind - * - VertexBuffer.UV6Kind - * - VertexBuffer.ColorKind - * - VertexBuffer.MatricesIndicesKind - * - VertexBuffer.MatricesIndicesExtraKind - * - VertexBuffer.MatricesWeightsKind - * - VertexBuffer.MatricesWeightsExtraKind - * - * Returns the Mesh. - * @param kind - * @param data - * @param updatable - * @param stride - */ - setVerticesData(kind, data, updatable, stride) { - if (this.sourceMesh) { - this.sourceMesh.setVerticesData(kind, data, updatable, stride); - } - return this.sourceMesh; - } - /** - * Updates the existing vertex data of the mesh geometry for the requested `kind`. - * If the mesh has no geometry, it is simply returned as it is. - * The `data` are either a numeric array either a Float32Array. - * No new underlying VertexBuffer object is created. - * 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. - * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh. - * - * Possible `kind` values : - * - VertexBuffer.PositionKind - * - VertexBuffer.UVKind - * - VertexBuffer.UV2Kind - * - VertexBuffer.UV3Kind - * - VertexBuffer.UV4Kind - * - VertexBuffer.UV5Kind - * - VertexBuffer.UV6Kind - * - VertexBuffer.ColorKind - * - VertexBuffer.MatricesIndicesKind - * - VertexBuffer.MatricesIndicesExtraKind - * - VertexBuffer.MatricesWeightsKind - * - VertexBuffer.MatricesWeightsExtraKind - * - * Returns the Mesh. - * @param kind - * @param data - * @param updateExtends - * @param makeItUnique - */ - updateVerticesData(kind, data, updateExtends, makeItUnique) { - if (this.sourceMesh) { - this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique); - } - return this.sourceMesh; - } - /** - * Sets the mesh indices. - * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array). - * If the mesh has no geometry, a new Geometry object is created and set to the mesh. - * This method creates a new index buffer each call. - * Returns the Mesh. - * @param indices - * @param totalVertices - */ - setIndices(indices, totalVertices = null) { - if (this.sourceMesh) { - this.sourceMesh.setIndices(indices, totalVertices); - } - return this.sourceMesh; - } - /** - * Boolean : True if the mesh owns the requested kind of data. - * @param kind - */ - isVerticesDataPresent(kind) { - return this._sourceMesh.isVerticesDataPresent(kind); - } - /** - * Returns an array of indices (IndicesArray). - */ - getIndices() { - return this._sourceMesh.getIndices(); - } - get _positions() { - return this._sourceMesh._positions; - } - /** - * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked. - * This means the mesh underlying bounding box and sphere are recomputed. - * @param applySkeleton defines whether to apply the skeleton before computing the bounding info - * @param applyMorph defines whether to apply the morph target before computing the bounding info - * @returns the current mesh - */ - refreshBoundingInfo(applySkeleton = false, applyMorph = false) { - if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) { - return this; - } - const bias = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null; - this._refreshBoundingInfo(this._sourceMesh._getPositionData(applySkeleton, applyMorph), bias); - return this; - } - /** @internal */ - _preActivate() { - if (this._currentLOD) { - this._currentLOD._preActivate(); - } - return this; - } - /** - * @internal - */ - _activate(renderId, intermediateRendering) { - super._activate(renderId, intermediateRendering); - if (!this._sourceMesh.subMeshes) { - logger_Logger.Warn("Instances should only be created for meshes with geometry."); - } - if (this._currentLOD) { - const differentSign = this._currentLOD._getWorldMatrixDeterminant() >= 0 !== this._getWorldMatrixDeterminant() >= 0; - if (differentSign) { - this._internalAbstractMeshDataInfo._actAsRegularMesh = true; - return true; - } - this._internalAbstractMeshDataInfo._actAsRegularMesh = false; - this._currentLOD._registerInstanceForRenderId(this, renderId); - if (intermediateRendering) { - if (!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate) { - this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = true; - return true; - } - } - else { - if (!this._currentLOD._internalAbstractMeshDataInfo._isActive) { - this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances = true; - return true; - } - } - } - return false; - } - /** @internal */ - _postActivate() { - if (this._sourceMesh.edgesShareWithInstances && this._sourceMesh._edgesRenderer && this._sourceMesh._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) { - // we are using the edge renderer of the source mesh - this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer); - this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix()); - } - else if (this._edgesRenderer && this._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) { - // we are using the edge renderer defined for this instance - this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer); - } - } - getWorldMatrix() { - if (this._currentLOD && this._currentLOD.billboardMode !== transformNode_TransformNode.BILLBOARDMODE_NONE && this._currentLOD._masterMesh !== this) { - if (!this._billboardWorldMatrix) { - this._billboardWorldMatrix = new math_vector_Matrix(); - } - const tempMaster = this._currentLOD._masterMesh; - this._currentLOD._masterMesh = this; - math_vector_TmpVectors.Vector3[7].copyFrom(this._currentLOD.position); - this._currentLOD.position.set(0, 0, 0); - this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(true)); - this._currentLOD.position.copyFrom(math_vector_TmpVectors.Vector3[7]); - this._currentLOD._masterMesh = tempMaster; - return this._billboardWorldMatrix; - } - return super.getWorldMatrix(); - } - get isAnInstance() { - return true; - } - /** - * Returns the current associated LOD AbstractMesh. - * @param camera - */ - getLOD(camera) { - if (!camera) { - return this; - } - const sourceMeshLODLevels = this.sourceMesh.getLODLevels(); - if (!sourceMeshLODLevels || sourceMeshLODLevels.length === 0) { - this._currentLOD = this.sourceMesh; - } - else { - const boundingInfo = this.getBoundingInfo(); - this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere); - } - return this._currentLOD; - } - /** - * @internal - */ - _preActivateForIntermediateRendering(renderId) { - return this.sourceMesh._preActivateForIntermediateRendering(renderId); - } - /** @internal */ - _syncSubMeshes() { - this.releaseSubMeshes(); - if (this._sourceMesh.subMeshes) { - for (let index = 0; index < this._sourceMesh.subMeshes.length; index++) { - this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh); - } - } - return this; - } - /** @internal */ - _generatePointsArray() { - return this._sourceMesh._generatePointsArray(); - } - /** @internal */ - _updateBoundingInfo() { - if (this.hasBoundingInfo) { - this.getBoundingInfo().update(this.worldMatrixFromCache); - } - else { - this.buildBoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache); - } - this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache); - return this; - } - /** - * Creates a new InstancedMesh from the current mesh. - * - * Returns the clone. - * @param name the cloned mesh name - * @param newParent the optional Node to parent the clone to. - * @param doNotCloneChildren if `true` the model children aren't cloned. - * @param newSourceMesh if set this mesh will be used as the source mesh instead of ths instance's one - * @returns the clone - */ - clone(name, newParent = null, doNotCloneChildren, newSourceMesh) { - const result = (newSourceMesh || this._sourceMesh).createInstance(name); - // Deep copy - DeepCopier.DeepCopy(this, result, [ - "name", - "subMeshes", - "uniqueId", - "parent", - "lightSources", - "receiveShadows", - "material", - "visibility", - "skeleton", - "sourceMesh", - "isAnInstance", - "facetNb", - "isFacetDataEnabled", - "isBlocked", - "useBones", - "hasInstances", - "collider", - "edgesRenderer", - "forward", - "up", - "right", - "absolutePosition", - "absoluteScaling", - "absoluteRotationQuaternion", - "isWorldMatrixFrozen", - "nonUniformScaling", - "behaviors", - "worldMatrixFromCache", - "hasThinInstances", - "hasBoundingInfo", - ], []); - // Bounding info - this.refreshBoundingInfo(); - // Parent - if (newParent) { - result.parent = newParent; - } - if (!doNotCloneChildren) { - // Children - for (let index = 0; index < this.getScene().meshes.length; index++) { - const mesh = this.getScene().meshes[index]; - if (mesh.parent === this) { - mesh.clone(mesh.name, result); - } - } - } - result.computeWorldMatrix(true); - this.onClonedObservable.notifyObservers(result); - return result; - } - /** - * Disposes the InstancedMesh. - * Returns nothing. - * @param doNotRecurse - * @param disposeMaterialAndTextures - */ - dispose(doNotRecurse, disposeMaterialAndTextures = false) { - // Remove from mesh - this._sourceMesh.removeInstance(this); - super.dispose(doNotRecurse, disposeMaterialAndTextures); - } - /** - * @internal - */ - _serializeAsParent(serializationObject) { - super._serializeAsParent(serializationObject); - serializationObject.parentId = this._sourceMesh.uniqueId; - serializationObject.parentInstanceIndex = this._indexInSourceMeshInstanceArray; - } - /** - * Instantiate (when possible) or clone that node with its hierarchy - * @param newParent defines the new parent to use for the instance (or clone) - * @param options defines options to configure how copy is done - * @param options.doNotInstantiate defines if the model must be instantiated or just cloned - * @param options.newSourcedMesh newSourcedMesh the new source mesh for the instance (or clone) - * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created - * @returns an instance (or a clone) of the current node with its hierarchy - */ - instantiateHierarchy(newParent = null, options, onNewNodeCreated) { - const clone = this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true, options && options.newSourcedMesh); - if (clone) { - if (onNewNodeCreated) { - onNewNodeCreated(this, clone); - } - } - for (const child of this.getChildTransformNodes(true)) { - child.instantiateHierarchy(clone, options, onNewNodeCreated); - } - return clone; - } -} -mesh_Mesh.prototype.registerInstancedBuffer = function (kind, stride) { - var _a, _b; - // Remove existing one - (_b = (_a = this._userInstancedBuffersStorage) === null || _a === void 0 ? void 0 : _a.vertexBuffers[kind]) === null || _b === void 0 ? void 0 : _b.dispose(); - // Creates the instancedBuffer field if not present - if (!this.instancedBuffers) { - this.instancedBuffers = {}; - for (const instance of this.instances) { - instance.instancedBuffers = {}; - } - if (!this._userInstancedBuffersStorage) { - this._userInstancedBuffersStorage = { - data: {}, - vertexBuffers: {}, - strides: {}, - sizes: {}, - vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : undefined, - }; - } - } - // Creates an empty property for this kind - this.instancedBuffers[kind] = null; - this._userInstancedBuffersStorage.strides[kind] = stride; - this._userInstancedBuffersStorage.sizes[kind] = stride * 32; // Initial size - this._userInstancedBuffersStorage.data[kind] = new Float32Array(this._userInstancedBuffersStorage.sizes[kind]); - this._userInstancedBuffersStorage.vertexBuffers[kind] = new buffer_VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true); - for (const instance of this.instances) { - instance.instancedBuffers[kind] = null; - } - this._invalidateInstanceVertexArrayObject(); - this._markSubMeshesAsAttributesDirty(); -}; -mesh_Mesh.prototype._processInstancedBuffers = function (visibleInstances, renderSelf) { - const instanceCount = visibleInstances ? visibleInstances.length : 0; - for (const kind in this.instancedBuffers) { - let size = this._userInstancedBuffersStorage.sizes[kind]; - const stride = this._userInstancedBuffersStorage.strides[kind]; - // Resize if required - const expectedSize = (instanceCount + 1) * stride; - while (size < expectedSize) { - size *= 2; - } - if (this._userInstancedBuffersStorage.data[kind].length != size) { - this._userInstancedBuffersStorage.data[kind] = new Float32Array(size); - this._userInstancedBuffersStorage.sizes[kind] = size; - if (this._userInstancedBuffersStorage.vertexBuffers[kind]) { - this._userInstancedBuffersStorage.vertexBuffers[kind].dispose(); - this._userInstancedBuffersStorage.vertexBuffers[kind] = null; - } - } - const data = this._userInstancedBuffersStorage.data[kind]; - // Update data buffer - let offset = 0; - if (renderSelf) { - const value = this.instancedBuffers[kind]; - if (value.toArray) { - value.toArray(data, offset); - } - else if (value.copyToArray) { - value.copyToArray(data, offset); - } - else { - data[offset] = value; - } - offset += stride; - } - for (let instanceIndex = 0; instanceIndex < instanceCount; instanceIndex++) { - const instance = visibleInstances[instanceIndex]; - const value = instance.instancedBuffers[kind]; - if (value.toArray) { - value.toArray(data, offset); - } - else if (value.copyToArray) { - value.copyToArray(data, offset); - } - else { - data[offset] = value; - } - offset += stride; - } - // Update vertex buffer - if (!this._userInstancedBuffersStorage.vertexBuffers[kind]) { - this._userInstancedBuffersStorage.vertexBuffers[kind] = new buffer_VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true); - this._invalidateInstanceVertexArrayObject(); - } - else { - this._userInstancedBuffersStorage.vertexBuffers[kind].updateDirectly(data, 0); - } - } -}; -mesh_Mesh.prototype._invalidateInstanceVertexArrayObject = function () { - if (!this._userInstancedBuffersStorage || this._userInstancedBuffersStorage.vertexArrayObjects === undefined) { - return; - } - for (const kind in this._userInstancedBuffersStorage.vertexArrayObjects) { - this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[kind]); - } - this._userInstancedBuffersStorage.vertexArrayObjects = {}; -}; -mesh_Mesh.prototype._disposeInstanceSpecificData = function () { - if (this._instanceDataStorage.instancesBuffer) { - this._instanceDataStorage.instancesBuffer.dispose(); - this._instanceDataStorage.instancesBuffer = null; - } - while (this.instances.length) { - this.instances[0].dispose(); - } - for (const kind in this.instancedBuffers) { - if (this._userInstancedBuffersStorage.vertexBuffers[kind]) { - this._userInstancedBuffersStorage.vertexBuffers[kind].dispose(); - } - } - this._invalidateInstanceVertexArrayObject(); - this.instancedBuffers = {}; -}; -//# sourceMappingURL=instancedMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/light.js - - - - - - - - -/** - * Base class of all the lights in Babylon. It groups all the generic information about lights. - * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour. - * 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. - */ -class light_Light extends node_Node { - /** - * Defines how far from the source the light is impacting in scene units. - * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff. - */ - get range() { - return this._range; - } - /** - * Defines how far from the source the light is impacting in scene units. - * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff. - */ - set range(value) { - this._range = value; - this._inverseSquaredRange = 1.0 / (this.range * this.range); - } - /** - * Gets the photometric scale used to interpret the intensity. - * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. - */ - get intensityMode() { - return this._intensityMode; - } - /** - * Sets the photometric scale used to interpret the intensity. - * This is only relevant with PBR Materials where the light intensity can be defined in a physical way. - */ - set intensityMode(value) { - this._intensityMode = value; - this._computePhotometricScale(); - } - /** - * Gets the light radius used by PBR Materials to simulate soft area lights. - */ - get radius() { - return this._radius; - } - /** - * sets the light radius used by PBR Materials to simulate soft area lights. - */ - set radius(value) { - this._radius = value; - this._computePhotometricScale(); - } - /** - * Gets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching - * the current shadow generator. - */ - get shadowEnabled() { - return this._shadowEnabled; - } - /** - * Sets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching - * the current shadow generator. - */ - set shadowEnabled(value) { - if (this._shadowEnabled === value) { - return; - } - this._shadowEnabled = value; - this._markMeshesAsLightDirty(); - } - /** - * Gets the only meshes impacted by this light. - */ - get includedOnlyMeshes() { - return this._includedOnlyMeshes; - } - /** - * Sets the only meshes impacted by this light. - */ - set includedOnlyMeshes(value) { - this._includedOnlyMeshes = value; - this._hookArrayForIncludedOnly(value); - } - /** - * Gets the meshes not impacted by this light. - */ - get excludedMeshes() { - return this._excludedMeshes; - } - /** - * Sets the meshes not impacted by this light. - */ - set excludedMeshes(value) { - this._excludedMeshes = value; - this._hookArrayForExcluded(value); - } - /** - * Gets the layer id use to find what meshes are not impacted by the light. - * Inactive if 0 - */ - get excludeWithLayerMask() { - return this._excludeWithLayerMask; - } - /** - * Sets the layer id use to find what meshes are not impacted by the light. - * Inactive if 0 - */ - set excludeWithLayerMask(value) { - this._excludeWithLayerMask = value; - this._resyncMeshes(); - } - /** - * Gets the layer id use to find what meshes are impacted by the light. - * Inactive if 0 - */ - get includeOnlyWithLayerMask() { - return this._includeOnlyWithLayerMask; - } - /** - * Sets the layer id use to find what meshes are impacted by the light. - * Inactive if 0 - */ - set includeOnlyWithLayerMask(value) { - this._includeOnlyWithLayerMask = value; - this._resyncMeshes(); - } - /** - * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) - */ - get lightmapMode() { - return this._lightmapMode; - } - /** - * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) - */ - set lightmapMode(value) { - if (this._lightmapMode === value) { - return; - } - this._lightmapMode = value; - this._markMeshesAsLightDirty(); - } - /** - * Creates a Light object in the scene. - * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction - * @param name The friendly name of the light - * @param scene The scene the light belongs too - */ - constructor(name, scene) { - super(name, scene); - /** - * Diffuse gives the basic color to an object. - */ - this.diffuse = new math_color_Color3(1.0, 1.0, 1.0); - /** - * Specular produces a highlight color on an object. - * Note: This is not affecting PBR materials. - */ - this.specular = new math_color_Color3(1.0, 1.0, 1.0); - /** - * Defines the falloff type for this light. This lets overriding how punctual light are - * falling off base on range or angle. - * This can be set to any values in Light.FALLOFF_x. - * - * Note: This is only useful for PBR Materials at the moment. This could be extended if required to - * other types of materials. - */ - this.falloffType = light_Light.FALLOFF_DEFAULT; - /** - * Strength of the light. - * Note: By default it is define in the framework own unit. - * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in. - */ - this.intensity = 1.0; - this._range = Number.MAX_VALUE; - this._inverseSquaredRange = 0; - /** - * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type - * of light. - */ - this._photometricScale = 1.0; - this._intensityMode = light_Light.INTENSITYMODE_AUTOMATIC; - this._radius = 0.00001; - /** - * Defines the rendering priority of the lights. It can help in case of fallback or number of lights - * exceeding the number allowed of the materials. - */ - this.renderPriority = 0; - this._shadowEnabled = true; - this._excludeWithLayerMask = 0; - this._includeOnlyWithLayerMask = 0; - this._lightmapMode = 0; - /** - * Shadow generators associated to the light. - * @internal Internal use only. - */ - this._shadowGenerators = null; - /** - * @internal Internal use only. - */ - this._excludedMeshesIds = new Array(); - /** - * @internal Internal use only. - */ - this._includedOnlyMeshesIds = new Array(); - /** @internal */ - this._isLight = true; - this.getScene().addLight(this); - this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name); - this._buildUniformLayout(); - this.includedOnlyMeshes = new Array(); - this.excludedMeshes = new Array(); - this._resyncMeshes(); - } - /** - * Sets the passed Effect "effect" with the Light textures. - * @param effect The effect to update - * @param lightIndex The index of the light in the effect to update - * @returns The light - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - transferTexturesToEffect(effect, lightIndex) { - // Do nothing by default. - return this; - } - /** - * Binds the lights information from the scene to the effect for the given mesh. - * @param lightIndex Light index - * @param scene The scene where the light belongs to - * @param effect The effect we are binding the data to - * @param useSpecular Defines if specular is supported - * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows - */ - _bindLight(lightIndex, scene, effect, useSpecular, receiveShadows = true) { - var _a; - const iAsString = lightIndex.toString(); - let needUpdate = false; - this._uniformBuffer.bindToEffect(effect, "Light" + iAsString); - if (this._renderId !== scene.getRenderId() || this._lastUseSpecular !== useSpecular || !this._uniformBuffer.useUbo) { - this._renderId = scene.getRenderId(); - this._lastUseSpecular = useSpecular; - const scaledIntensity = this.getScaledIntensity(); - this.transferToEffect(effect, iAsString); - this.diffuse.scaleToRef(scaledIntensity, TmpColors.Color3[0]); - this._uniformBuffer.updateColor4("vLightDiffuse", TmpColors.Color3[0], this.range, iAsString); - if (useSpecular) { - this.specular.scaleToRef(scaledIntensity, TmpColors.Color3[1]); - this._uniformBuffer.updateColor4("vLightSpecular", TmpColors.Color3[1], this.radius, iAsString); - } - needUpdate = true; - } - // Textures might still need to be rebound. - this.transferTexturesToEffect(effect, iAsString); - // Shadows - if (scene.shadowsEnabled && this.shadowEnabled && receiveShadows) { - const shadowGenerator = (_a = this.getShadowGenerator(scene.activeCamera)) !== null && _a !== void 0 ? _a : this.getShadowGenerator(); - if (shadowGenerator) { - shadowGenerator.bindShadowLight(iAsString, effect); - needUpdate = true; - } - } - if (needUpdate) { - this._uniformBuffer.update(); - } - else { - this._uniformBuffer.bindUniformBuffer(); - } - } - /** - * Returns the string "Light". - * @returns the class name - */ - getClassName() { - return "Light"; - } - /** - * Converts the light information to a readable string for debug purpose. - * @param fullDetails Supports for multiple levels of logging within scene loading - * @returns the human readable light info - */ - toString(fullDetails) { - let ret = "Name: " + this.name; - ret += ", type: " + ["Point", "Directional", "Spot", "Hemispheric"][this.getTypeID()]; - if (this.animations) { - for (let i = 0; i < this.animations.length; i++) { - ret += ", animation[0]: " + this.animations[i].toString(fullDetails); - } - } - return ret; - } - /** @internal */ - _syncParentEnabledState() { - super._syncParentEnabledState(); - if (!this.isDisposed()) { - this._resyncMeshes(); - } - } - /** - * Set the enabled state of this node. - * @param value - the new enabled state - */ - setEnabled(value) { - super.setEnabled(value); - this._resyncMeshes(); - } - /** - * Returns the Light associated shadow generator if any. - * @param camera Camera for which the shadow generator should be retrieved (default: null). If null, retrieves the default shadow generator - * @returns the associated shadow generator. - */ - getShadowGenerator(camera = null) { - var _a; - if (this._shadowGenerators === null) { - return null; - } - return (_a = this._shadowGenerators.get(camera)) !== null && _a !== void 0 ? _a : null; - } - /** - * Returns all the shadow generators associated to this light - * @returns - */ - getShadowGenerators() { - return this._shadowGenerators; - } - /** - * Returns a Vector3, the absolute light position in the World. - * @returns the world space position of the light - */ - getAbsolutePosition() { - return math_vector_Vector3.Zero(); - } - /** - * Specifies if the light will affect the passed mesh. - * @param mesh The mesh to test against the light - * @returns true the mesh is affected otherwise, false. - */ - canAffectMesh(mesh) { - if (!mesh) { - return true; - } - if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) { - return false; - } - if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) { - return false; - } - if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) { - return false; - } - if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) { - return false; - } - return true; - } - /** - * Releases resources associated with this node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) - */ - dispose(doNotRecurse, disposeMaterialAndTextures = false) { - if (this._shadowGenerators) { - const iterator = this._shadowGenerators.values(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const shadowGenerator = key.value; - shadowGenerator.dispose(); - } - this._shadowGenerators = null; - } - // Animations - this.getScene().stopAnimation(this); - if (this._parentContainer) { - const index = this._parentContainer.lights.indexOf(this); - if (index > -1) { - this._parentContainer.lights.splice(index, 1); - } - this._parentContainer = null; - } - // Remove from meshes - for (const mesh of this.getScene().meshes) { - mesh._removeLightSource(this, true); - } - this._uniformBuffer.dispose(); - // Remove from scene - this.getScene().removeLight(this); - super.dispose(doNotRecurse, disposeMaterialAndTextures); - } - /** - * Returns the light type ID (integer). - * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x - */ - getTypeID() { - return 0; - } - /** - * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode. - * @returns the scaled intensity in intensity mode unit - */ - getScaledIntensity() { - return this._photometricScale * this.intensity; - } - /** - * Returns a new Light object, named "name", from the current one. - * @param name The name of the cloned light - * @param newParent The parent of this light, if it has one - * @returns the new created light - */ - clone(name, newParent = null) { - const constructor = light_Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()); - if (!constructor) { - return null; - } - const clonedLight = decorators_SerializationHelper.Clone(constructor, this); - if (name) { - clonedLight.name = name; - } - if (newParent) { - clonedLight.parent = newParent; - } - clonedLight.setEnabled(this.isEnabled()); - this.onClonedObservable.notifyObservers(clonedLight); - return clonedLight; - } - /** - * Serializes the current light into a Serialization object. - * @returns the serialized object. - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.uniqueId = this.uniqueId; - // Type - serializationObject.type = this.getTypeID(); - // Parent - if (this.parent) { - this.parent._serializeAsParent(serializationObject); - } - // Inclusion / exclusions - if (this.excludedMeshes.length > 0) { - serializationObject.excludedMeshesIds = []; - this.excludedMeshes.forEach((mesh) => { - serializationObject.excludedMeshesIds.push(mesh.id); - }); - } - if (this.includedOnlyMeshes.length > 0) { - serializationObject.includedOnlyMeshesIds = []; - this.includedOnlyMeshes.forEach((mesh) => { - serializationObject.includedOnlyMeshesIds.push(mesh.id); - }); - } - // Animations - decorators_SerializationHelper.AppendSerializedAnimations(this, serializationObject); - serializationObject.ranges = this.serializeAnimationRanges(); - serializationObject.isEnabled = this.isEnabled(); - return serializationObject; - } - /** - * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3. - * This new light is named "name" and added to the passed scene. - * @param type Type according to the types available in Light.LIGHTTYPEID_x - * @param name The friendly name of the light - * @param scene The scene the new light will belong to - * @returns the constructor function - */ - static GetConstructorFromName(type, name, scene) { - const constructorFunc = node_Node.Construct("Light_Type_" + type, name, scene); - if (constructorFunc) { - return constructorFunc; - } - // Default to no light for none present once. - return null; - } - /** - * Parses the passed "parsedLight" and returns a new instanced Light from this parsing. - * @param parsedLight The JSON representation of the light - * @param scene The scene to create the parsed light in - * @returns the created light after parsing - */ - static Parse(parsedLight, scene) { - const constructor = light_Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene); - if (!constructor) { - return null; - } - const light = decorators_SerializationHelper.Parse(constructor, parsedLight, scene); - // Inclusion / exclusions - if (parsedLight.excludedMeshesIds) { - light._excludedMeshesIds = parsedLight.excludedMeshesIds; - } - if (parsedLight.includedOnlyMeshesIds) { - light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds; - } - // Parent - if (parsedLight.parentId !== undefined) { - light._waitingParentId = parsedLight.parentId; - } - if (parsedLight.parentInstanceIndex !== undefined) { - light._waitingParentInstanceIndex = parsedLight.parentInstanceIndex; - } - // Falloff - if (parsedLight.falloffType !== undefined) { - light.falloffType = parsedLight.falloffType; - } - // Lightmaps - if (parsedLight.lightmapMode !== undefined) { - light.lightmapMode = parsedLight.lightmapMode; - } - // Animations - if (parsedLight.animations) { - for (let animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) { - const parsedAnimation = parsedLight.animations[animationIndex]; - const internalClass = GetClass("BABYLON.Animation"); - if (internalClass) { - light.animations.push(internalClass.Parse(parsedAnimation)); - } - } - node_Node.ParseAnimationRanges(light, parsedLight, scene); - } - if (parsedLight.autoAnimate) { - scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0); - } - // Check if isEnabled is defined to be back compatible with prior serialized versions. - if (parsedLight.isEnabled !== undefined) { - light.setEnabled(parsedLight.isEnabled); - } - return light; - } - _hookArrayForExcluded(array) { - const oldPush = array.push; - array.push = (...items) => { - const result = oldPush.apply(array, items); - for (const item of items) { - item._resyncLightSource(this); - } - return result; - }; - const oldSplice = array.splice; - array.splice = (index, deleteCount) => { - const deleted = oldSplice.apply(array, [index, deleteCount]); - for (const item of deleted) { - item._resyncLightSource(this); - } - return deleted; - }; - for (const item of array) { - item._resyncLightSource(this); - } - } - _hookArrayForIncludedOnly(array) { - const oldPush = array.push; - array.push = (...items) => { - const result = oldPush.apply(array, items); - this._resyncMeshes(); - return result; - }; - const oldSplice = array.splice; - array.splice = (index, deleteCount) => { - const deleted = oldSplice.apply(array, [index, deleteCount]); - this._resyncMeshes(); - return deleted; - }; - this._resyncMeshes(); - } - _resyncMeshes() { - for (const mesh of this.getScene().meshes) { - mesh._resyncLightSource(this); - } - } - /** - * Forces the meshes to update their light related information in their rendering used effects - * @internal Internal Use Only - */ - _markMeshesAsLightDirty() { - for (const mesh of this.getScene().meshes) { - if (mesh.lightSources.indexOf(this) !== -1) { - mesh._markSubMeshesAsLightDirty(); - } - } - } - /** - * Recomputes the cached photometric scale if needed. - */ - _computePhotometricScale() { - this._photometricScale = this._getPhotometricScale(); - this.getScene().resetCachedMaterial(); - } - /** - * Returns the Photometric Scale according to the light type and intensity mode. - */ - _getPhotometricScale() { - let photometricScale = 0.0; - const lightTypeID = this.getTypeID(); - //get photometric mode - let photometricMode = this.intensityMode; - if (photometricMode === light_Light.INTENSITYMODE_AUTOMATIC) { - if (lightTypeID === light_Light.LIGHTTYPEID_DIRECTIONALLIGHT) { - photometricMode = light_Light.INTENSITYMODE_ILLUMINANCE; - } - else { - photometricMode = light_Light.INTENSITYMODE_LUMINOUSINTENSITY; - } - } - //compute photometric scale - switch (lightTypeID) { - case light_Light.LIGHTTYPEID_POINTLIGHT: - case light_Light.LIGHTTYPEID_SPOTLIGHT: - switch (photometricMode) { - case light_Light.INTENSITYMODE_LUMINOUSPOWER: - photometricScale = 1.0 / (4.0 * Math.PI); - break; - case light_Light.INTENSITYMODE_LUMINOUSINTENSITY: - photometricScale = 1.0; - break; - case light_Light.INTENSITYMODE_LUMINANCE: - photometricScale = this.radius * this.radius; - break; - } - break; - case light_Light.LIGHTTYPEID_DIRECTIONALLIGHT: - switch (photometricMode) { - case light_Light.INTENSITYMODE_ILLUMINANCE: - photometricScale = 1.0; - break; - case light_Light.INTENSITYMODE_LUMINANCE: { - // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance. - // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres). - let apexAngleRadians = this.radius; - // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function). - apexAngleRadians = Math.max(apexAngleRadians, 0.001); - const solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians)); - photometricScale = solidAngle; - break; - } - } - break; - case light_Light.LIGHTTYPEID_HEMISPHERICLIGHT: - // No fall off in hemispheric light. - photometricScale = 1.0; - break; - } - return photometricScale; - } - /** - * Reorder the light in the scene according to their defined priority. - * @internal Internal Use Only - */ - _reorderLightsInScene() { - const scene = this.getScene(); - if (this._renderPriority != 0) { - scene.requireLightSorting = true; - } - this.getScene().sortLightsByPriority(); - } -} -/** - * Falloff Default: light is falling off following the material specification: - * standard material is using standard falloff whereas pbr material can request special falloff per materials. - */ -light_Light.FALLOFF_DEFAULT = LightConstants.FALLOFF_DEFAULT; -/** - * Falloff Physical: light is falling off following the inverse squared distance law. - */ -light_Light.FALLOFF_PHYSICAL = LightConstants.FALLOFF_PHYSICAL; -/** - * Falloff gltf: light is falling off as described in the gltf moving to PBR document - * to enhance interoperability with other engines. - */ -light_Light.FALLOFF_GLTF = LightConstants.FALLOFF_GLTF; -/** - * Falloff Standard: light is falling off like in the standard material - * to enhance interoperability with other materials. - */ -light_Light.FALLOFF_STANDARD = LightConstants.FALLOFF_STANDARD; -//lightmapMode Consts -/** - * If every light affecting the material is in this lightmapMode, - * material.lightmapTexture adds or multiplies - * (depends on material.useLightmapAsShadowmap) - * after every other light calculations. - */ -light_Light.LIGHTMAP_DEFAULT = LightConstants.LIGHTMAP_DEFAULT; -/** - * material.lightmapTexture as only diffuse lighting from this light - * adds only specular lighting from this light - * adds dynamic shadows - */ -light_Light.LIGHTMAP_SPECULAR = LightConstants.LIGHTMAP_SPECULAR; -/** - * material.lightmapTexture as only lighting - * no light calculation from this light - * only adds dynamic shadows from this light - */ -light_Light.LIGHTMAP_SHADOWSONLY = LightConstants.LIGHTMAP_SHADOWSONLY; -// Intensity Mode Consts -/** - * Each light type uses the default quantity according to its type: - * point/spot lights use luminous intensity - * directional lights use illuminance - */ -light_Light.INTENSITYMODE_AUTOMATIC = LightConstants.INTENSITYMODE_AUTOMATIC; -/** - * lumen (lm) - */ -light_Light.INTENSITYMODE_LUMINOUSPOWER = LightConstants.INTENSITYMODE_LUMINOUSPOWER; -/** - * candela (lm/sr) - */ -light_Light.INTENSITYMODE_LUMINOUSINTENSITY = LightConstants.INTENSITYMODE_LUMINOUSINTENSITY; -/** - * lux (lm/m^2) - */ -light_Light.INTENSITYMODE_ILLUMINANCE = LightConstants.INTENSITYMODE_ILLUMINANCE; -/** - * nit (cd/m^2) - */ -light_Light.INTENSITYMODE_LUMINANCE = LightConstants.INTENSITYMODE_LUMINANCE; -// Light types ids const. -/** - * Light type const id of the point light. - */ -light_Light.LIGHTTYPEID_POINTLIGHT = LightConstants.LIGHTTYPEID_POINTLIGHT; -/** - * Light type const id of the directional light. - */ -light_Light.LIGHTTYPEID_DIRECTIONALLIGHT = LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT; -/** - * Light type const id of the spot light. - */ -light_Light.LIGHTTYPEID_SPOTLIGHT = LightConstants.LIGHTTYPEID_SPOTLIGHT; -/** - * Light type const id of the hemispheric light. - */ -light_Light.LIGHTTYPEID_HEMISPHERICLIGHT = LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT; -__decorate([ - serializeAsColor3() -], light_Light.prototype, "diffuse", void 0); -__decorate([ - serializeAsColor3() -], light_Light.prototype, "specular", void 0); -__decorate([ - serialize() -], light_Light.prototype, "falloffType", void 0); -__decorate([ - serialize() -], light_Light.prototype, "intensity", void 0); -__decorate([ - serialize() -], light_Light.prototype, "range", null); -__decorate([ - serialize() -], light_Light.prototype, "intensityMode", null); -__decorate([ - serialize() -], light_Light.prototype, "radius", null); -__decorate([ - serialize() -], light_Light.prototype, "_renderPriority", void 0); -__decorate([ - expandToProperty("_reorderLightsInScene") -], light_Light.prototype, "renderPriority", void 0); -__decorate([ - serialize("shadowEnabled") -], light_Light.prototype, "_shadowEnabled", void 0); -__decorate([ - serialize("excludeWithLayerMask") -], light_Light.prototype, "_excludeWithLayerMask", void 0); -__decorate([ - serialize("includeOnlyWithLayerMask") -], light_Light.prototype, "_includeOnlyWithLayerMask", void 0); -__decorate([ - serialize("lightmapMode") -], light_Light.prototype, "_lightmapMode", void 0); -//# sourceMappingURL=light.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/assetContainer.js - - - - - - - - - -/** - * Set of assets to keep when moving a scene into an asset container. - */ -class KeepAssets extends AbstractScene { -} -/** - * Class used to store the output of the AssetContainer.instantiateAllMeshesToScene function - */ -class InstantiatedEntries { - constructor() { - /** - * List of new root nodes (eg. nodes with no parent) - */ - this.rootNodes = []; - /** - * List of new skeletons - */ - this.skeletons = []; - /** - * List of new animation groups - */ - this.animationGroups = []; - } - /** - * Disposes the instantiated entries from the scene - */ - dispose() { - this.rootNodes.slice(0).forEach((o) => { - o.dispose(); - }); - this.rootNodes.length = 0; - this.skeletons.slice(0).forEach((o) => { - o.dispose(); - }); - this.skeletons.length = 0; - this.animationGroups.slice(0).forEach((o) => { - o.dispose(); - }); - this.animationGroups.length = 0; - } -} -/** - * Container with a set of assets that can be added or removed from a scene. - */ -class AssetContainer extends AbstractScene { - /** - * Instantiates an AssetContainer. - * @param scene The scene the AssetContainer belongs to. - */ - constructor(scene) { - super(); - this._wasAddedToScene = false; - scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!scene) { - return; - } - this.scene = scene; - this["sounds"] = []; - this["effectLayers"] = []; - this["layers"] = []; - this["lensFlareSystems"] = []; - this["proceduralTextures"] = []; - this["reflectionProbes"] = []; - scene.onDisposeObservable.add(() => { - if (!this._wasAddedToScene) { - this.dispose(); - } - }); - this._onContextRestoredObserver = scene.getEngine().onContextRestoredObservable.add(() => { - for (const geometry of this.geometries) { - geometry._rebuild(); - } - for (const mesh of this.meshes) { - mesh._rebuild(); - } - for (const system of this.particleSystems) { - system.rebuild(); - } - for (const texture of this.textures) { - texture._rebuild(); - } - }); - } - /** - * Given a list of nodes, return a topological sorting of them. - * @param nodes - */ - _topologicalSort(nodes) { - const nodesUidMap = new Map(); - for (const node of nodes) { - nodesUidMap.set(node.uniqueId, node); - } - const dependencyGraph = { - dependsOn: new Map(), - dependedBy: new Map(), // given a node id, what are the ids of the nodes that depend on it - }; - // Build the dependency graph given the list of nodes - // First pass: Initialize the empty dependency graph - for (const node of nodes) { - const nodeId = node.uniqueId; - dependencyGraph.dependsOn.set(nodeId, new Set()); - dependencyGraph.dependedBy.set(nodeId, new Set()); - } - // Second pass: Populate the dependency graph. We assume that we - // don't need to check for cycles here, as the scene graph cannot - // contain cycles. Our graph also already contains all transitive - // dependencies because getDescendants returns the transitive - // dependencies by default. - for (const node of nodes) { - const nodeId = node.uniqueId; - const dependsOn = dependencyGraph.dependsOn.get(nodeId); - if (node instanceof instancedMesh_InstancedMesh) { - const masterMesh = node.sourceMesh; - if (nodesUidMap.has(masterMesh.uniqueId)) { - dependsOn.add(masterMesh.uniqueId); - dependencyGraph.dependedBy.get(masterMesh.uniqueId).add(nodeId); - } - } - const dependedBy = dependencyGraph.dependedBy.get(nodeId); - for (const child of node.getDescendants()) { - const childId = child.uniqueId; - if (nodesUidMap.has(childId)) { - dependedBy.add(childId); - const childDependsOn = dependencyGraph.dependsOn.get(childId); - childDependsOn.add(nodeId); - } - } - } - // Third pass: Topological sort - const sortedNodes = []; - // First: Find all nodes that have no dependencies - const leaves = []; - for (const node of nodes) { - const nodeId = node.uniqueId; - if (dependencyGraph.dependsOn.get(nodeId).size === 0) { - leaves.push(node); - nodesUidMap.delete(nodeId); - } - } - const visitList = leaves; - while (visitList.length > 0) { - const nodeToVisit = visitList.shift(); - sortedNodes.push(nodeToVisit); - // Remove the node from the dependency graph - // When a node is visited, we know that dependsOn is empty. - // So we only need to remove the node from dependedBy. - const dependedByVisitedNode = dependencyGraph.dependedBy.get(nodeToVisit.uniqueId); - // Array.from(x.values()) is to make the TS compiler happy - for (const dependedByVisitedNodeId of Array.from(dependedByVisitedNode.values())) { - const dependsOnDependedByVisitedNode = dependencyGraph.dependsOn.get(dependedByVisitedNodeId); - dependsOnDependedByVisitedNode.delete(nodeToVisit.uniqueId); - if (dependsOnDependedByVisitedNode.size === 0 && nodesUidMap.get(dependedByVisitedNodeId)) { - visitList.push(nodesUidMap.get(dependedByVisitedNodeId)); - nodesUidMap.delete(dependedByVisitedNodeId); - } - } - } - if (nodesUidMap.size > 0) { - console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"); - nodesUidMap.forEach((node) => console.error(node.name)); - } - return sortedNodes; - } - _addNodeAndDescendantsToList(list, addedIds, rootNode, predicate) { - if (!rootNode || (predicate && !predicate(rootNode)) || addedIds.has(rootNode.uniqueId)) { - return; - } - list.push(rootNode); - addedIds.add(rootNode.uniqueId); - for (const child of rootNode.getDescendants(true)) { - this._addNodeAndDescendantsToList(list, addedIds, child, predicate); - } - } - /** - * Check if a specific node is contained in this asset container. - * @param node - */ - _isNodeInContainer(node) { - if (node instanceof mesh_Mesh && this.meshes.indexOf(node) !== -1) { - return true; - } - if (node instanceof transformNode_TransformNode && this.transformNodes.indexOf(node) !== -1) { - return true; - } - if (node instanceof light_Light && this.lights.indexOf(node) !== -1) { - return true; - } - if (node instanceof camera_Camera && this.cameras.indexOf(node) !== -1) { - return true; - } - return false; - } - /** - * For every node in the scene, check if its parent node is also in the scene. - */ - _isValidHierarchy() { - for (const node of this.meshes) { - if (node.parent && !this._isNodeInContainer(node.parent)) { - logger_Logger.Warn(`Node ${node.name} has a parent that is not in the container.`); - return false; - } - } - for (const node of this.transformNodes) { - if (node.parent && !this._isNodeInContainer(node.parent)) { - logger_Logger.Warn(`Node ${node.name} has a parent that is not in the container.`); - return false; - } - } - for (const node of this.lights) { - if (node.parent && !this._isNodeInContainer(node.parent)) { - logger_Logger.Warn(`Node ${node.name} has a parent that is not in the container.`); - return false; - } - } - for (const node of this.cameras) { - if (node.parent && !this._isNodeInContainer(node.parent)) { - logger_Logger.Warn(`Node ${node.name} has a parent that is not in the container.`); - return false; - } - } - return true; - } - /** - * Instantiate or clone all meshes and add the new ones to the scene. - * Skeletons and animation groups will all be cloned - * @param nameFunction defines an optional function used to get new names for clones - * @param cloneMaterials defines an optional boolean that defines if materials must be cloned as well (false by default) - * @param options defines an optional list of options to control how to instantiate / clone models - * @param options.doNotInstantiate defines if the model must be instantiated or just cloned - * @param options.predicate defines a predicate used to filter whih mesh to instantiate/clone - * @returns a list of rootNodes, skeletons and animation groups that were duplicated - */ - instantiateModelsToScene(nameFunction, cloneMaterials = false, options) { - if (!this._isValidHierarchy()) { - tools_Tools.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid."); - } - const conversionMap = {}; - const storeMap = {}; - const result = new InstantiatedEntries(); - const alreadySwappedSkeletons = []; - const alreadySwappedMaterials = []; - const localOptions = Object.assign({ doNotInstantiate: true }, options); - const onClone = (source, clone) => { - conversionMap[source.uniqueId] = clone.uniqueId; - storeMap[clone.uniqueId] = clone; - if (nameFunction) { - clone.name = nameFunction(source.name); - } - if (clone instanceof mesh_Mesh) { - const clonedMesh = clone; - if (clonedMesh.morphTargetManager) { - const oldMorphTargetManager = source.morphTargetManager; - clonedMesh.morphTargetManager = oldMorphTargetManager.clone(); - for (let index = 0; index < oldMorphTargetManager.numTargets; index++) { - const oldTarget = oldMorphTargetManager.getTarget(index); - const newTarget = clonedMesh.morphTargetManager.getTarget(index); - conversionMap[oldTarget.uniqueId] = newTarget.uniqueId; - storeMap[newTarget.uniqueId] = newTarget; - } - } - } - }; - const nodesToSort = []; - const idsOnSortList = new Set(); - for (const transformNode of this.transformNodes) { - if (transformNode.parent === null) { - this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, transformNode, localOptions.predicate); - } - } - for (const mesh of this.meshes) { - if (mesh.parent === null) { - this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, mesh, localOptions.predicate); - } - } - // Topologically sort nodes by parenting/instancing relationships so that all resources are in place - // when a given node is instantiated. - const sortedNodes = this._topologicalSort(nodesToSort); - const onNewCreated = (source, clone) => { - onClone(source, clone); - if (source.parent) { - const replicatedParentId = conversionMap[source.parent.uniqueId]; - const replicatedParent = storeMap[replicatedParentId]; - if (replicatedParent) { - clone.parent = replicatedParent; - } - else { - clone.parent = source.parent; - } - } - if (clone.position && source.position) { - clone.position.copyFrom(source.position); - } - if (clone.rotationQuaternion && source.rotationQuaternion) { - clone.rotationQuaternion.copyFrom(source.rotationQuaternion); - } - if (clone.rotation && source.rotation) { - clone.rotation.copyFrom(source.rotation); - } - if (clone.scaling && source.scaling) { - clone.scaling.copyFrom(source.scaling); - } - if (clone.material) { - const mesh = clone; - if (mesh.material) { - if (cloneMaterials) { - const sourceMaterial = source.material; - if (alreadySwappedMaterials.indexOf(sourceMaterial) === -1) { - let swap = sourceMaterial.clone(nameFunction ? nameFunction(sourceMaterial.name) : "Clone of " + sourceMaterial.name); - alreadySwappedMaterials.push(sourceMaterial); - conversionMap[sourceMaterial.uniqueId] = swap.uniqueId; - storeMap[swap.uniqueId] = swap; - if (sourceMaterial.getClassName() === "MultiMaterial") { - const multi = sourceMaterial; - for (const material of multi.subMaterials) { - if (!material) { - continue; - } - swap = material.clone(nameFunction ? nameFunction(material.name) : "Clone of " + material.name); - alreadySwappedMaterials.push(material); - conversionMap[material.uniqueId] = swap.uniqueId; - storeMap[swap.uniqueId] = swap; - } - multi.subMaterials = multi.subMaterials.map((m) => m && storeMap[conversionMap[m.uniqueId]]); - } - } - if (mesh.getClassName() !== "InstancedMesh") { - mesh.material = storeMap[conversionMap[sourceMaterial.uniqueId]]; - } - } - else { - if (mesh.material.getClassName() === "MultiMaterial") { - if (this.scene.multiMaterials.indexOf(mesh.material) === -1) { - this.scene.addMultiMaterial(mesh.material); - } - } - else { - if (this.scene.materials.indexOf(mesh.material) === -1) { - this.scene.addMaterial(mesh.material); - } - } - } - } - } - if (clone.parent === null) { - result.rootNodes.push(clone); - } - }; - sortedNodes.forEach((node) => { - if (node.getClassName() === "InstancedMesh") { - const instancedNode = node; - const sourceMesh = instancedNode.sourceMesh; - const replicatedSourceId = conversionMap[sourceMesh.uniqueId]; - const replicatedSource = typeof replicatedSourceId === "number" ? storeMap[replicatedSourceId] : sourceMesh; - const replicatedInstancedNode = replicatedSource.createInstance(instancedNode.name); - onNewCreated(instancedNode, replicatedInstancedNode); - } - else { - // Mesh or TransformNode - let canInstance = true; - if (node.getClassName() === "TransformNode" || - node.getClassName() === "Node" || - node.skeleton || - !node.getTotalVertices || - node.getTotalVertices() === 0) { - // Transform nodes, skinned meshes, and meshes with no vertices can never be instanced! - canInstance = false; - } - else if (localOptions.doNotInstantiate) { - if (typeof localOptions.doNotInstantiate === "function") { - canInstance = !localOptions.doNotInstantiate(node); - } - else { - canInstance = !localOptions.doNotInstantiate; - } - } - const replicatedNode = canInstance ? node.createInstance(`instance of ${node.name}`) : node.clone(`Clone of ${node.name}`, null, true); - if (!replicatedNode) { - throw new Error(`Could not clone or instantiate node on Asset Container ${node.name}`); - } - onNewCreated(node, replicatedNode); - } - }); - this.skeletons.forEach((s) => { - if (localOptions.predicate && !localOptions.predicate(s)) { - return; - } - const clone = s.clone(nameFunction ? nameFunction(s.name) : "Clone of " + s.name); - for (const m of this.meshes) { - if (m.skeleton === s && !m.isAnInstance) { - const copy = storeMap[conversionMap[m.uniqueId]]; - if (!copy || copy.isAnInstance) { - continue; - } - copy.skeleton = clone; - if (alreadySwappedSkeletons.indexOf(clone) !== -1) { - continue; - } - alreadySwappedSkeletons.push(clone); - // Check if bones are mesh linked - for (const bone of clone.bones) { - if (bone._linkedTransformNode) { - bone._linkedTransformNode = storeMap[conversionMap[bone._linkedTransformNode.uniqueId]]; - } - } - } - } - result.skeletons.push(clone); - }); - this.animationGroups.forEach((o) => { - if (localOptions.predicate && !localOptions.predicate(o)) { - return; - } - const clone = o.clone(nameFunction ? nameFunction(o.name) : "Clone of " + o.name, (oldTarget) => { - const newTarget = storeMap[conversionMap[oldTarget.uniqueId]]; - return newTarget || oldTarget; - }); - result.animationGroups.push(clone); - }); - return result; - } - /** - * Adds all the assets from the container to the scene. - */ - addAllToScene() { - if (this._wasAddedToScene) { - return; - } - if (!this._isValidHierarchy()) { - tools_Tools.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."); - } - this._wasAddedToScene = true; - this.addToScene(null); - if (this.environmentTexture) { - this.scene.environmentTexture = this.environmentTexture; - } - for (const component of this.scene._serializableComponents) { - component.addFromContainer(this); - } - this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver); - this._onContextRestoredObserver = null; - } - /** - * Adds assets from the container to the scene. - * @param predicate defines a predicate used to select which entity will be added (can be null) - */ - addToScene(predicate = null) { - const addedNodes = []; - this.cameras.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addCamera(o); - addedNodes.push(o); - }); - this.lights.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addLight(o); - addedNodes.push(o); - }); - this.meshes.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addMesh(o); - addedNodes.push(o); - }); - this.skeletons.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addSkeleton(o); - }); - this.animations.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addAnimation(o); - }); - this.animationGroups.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addAnimationGroup(o); - }); - this.multiMaterials.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addMultiMaterial(o); - }); - this.materials.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addMaterial(o); - }); - this.morphTargetManagers.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addMorphTargetManager(o); - }); - this.geometries.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addGeometry(o); - }); - this.transformNodes.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addTransformNode(o); - addedNodes.push(o); - }); - this.actionManagers.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addActionManager(o); - }); - this.textures.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addTexture(o); - }); - this.reflectionProbes.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.addReflectionProbe(o); - }); - for (const addedNode of addedNodes) { - // If node was added to the scene, but parent is not in the scene, break the relationship - if (addedNode.parent && this.scene.getNodes().indexOf(addedNode.parent) === -1) { - // Use setParent to keep transform if possible - if (addedNode.setParent) { - addedNode.setParent(null); - } - else { - addedNode.parent = null; - } - } - } - } - /** - * Removes all the assets in the container from the scene - */ - removeAllFromScene() { - if (!this._isValidHierarchy()) { - tools_Tools.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."); - } - this._wasAddedToScene = false; - this.removeFromScene(null); - if (this.environmentTexture === this.scene.environmentTexture) { - this.scene.environmentTexture = null; - } - for (const component of this.scene._serializableComponents) { - component.removeFromContainer(this); - } - } - /** - * Removes assets in the container from the scene - * @param predicate defines a predicate used to select which entity will be added (can be null) - */ - removeFromScene(predicate = null) { - this.cameras.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeCamera(o); - }); - this.lights.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeLight(o); - }); - this.meshes.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeMesh(o); - }); - this.skeletons.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeSkeleton(o); - }); - this.animations.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeAnimation(o); - }); - this.animationGroups.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeAnimationGroup(o); - }); - this.multiMaterials.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeMultiMaterial(o); - }); - this.materials.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeMaterial(o); - }); - this.morphTargetManagers.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeMorphTargetManager(o); - }); - this.geometries.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeGeometry(o); - }); - this.transformNodes.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeTransformNode(o); - }); - this.actionManagers.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeActionManager(o); - }); - this.textures.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeTexture(o); - }); - this.reflectionProbes.forEach((o) => { - if (predicate && !predicate(o)) { - return; - } - this.scene.removeReflectionProbe(o); - }); - } - /** - * Disposes all the assets in the container - */ - dispose() { - this.cameras.slice(0).forEach((o) => { - o.dispose(); - }); - this.cameras.length = 0; - this.lights.slice(0).forEach((o) => { - o.dispose(); - }); - this.lights.length = 0; - this.meshes.slice(0).forEach((o) => { - o.dispose(); - }); - this.meshes.length = 0; - this.skeletons.slice(0).forEach((o) => { - o.dispose(); - }); - this.skeletons.length = 0; - this.animationGroups.slice(0).forEach((o) => { - o.dispose(); - }); - this.animationGroups.length = 0; - this.multiMaterials.slice(0).forEach((o) => { - o.dispose(); - }); - this.multiMaterials.length = 0; - this.materials.slice(0).forEach((o) => { - o.dispose(); - }); - this.materials.length = 0; - this.geometries.slice(0).forEach((o) => { - o.dispose(); - }); - this.geometries.length = 0; - this.transformNodes.slice(0).forEach((o) => { - o.dispose(); - }); - this.transformNodes.length = 0; - this.actionManagers.slice(0).forEach((o) => { - o.dispose(); - }); - this.actionManagers.length = 0; - this.textures.slice(0).forEach((o) => { - o.dispose(); - }); - this.textures.length = 0; - this.reflectionProbes.slice(0).forEach((o) => { - o.dispose(); - }); - this.reflectionProbes.length = 0; - this.morphTargetManagers.slice(0).forEach((o) => { - o.dispose(); - }); - this.morphTargetManagers.length = 0; - if (this.environmentTexture) { - this.environmentTexture.dispose(); - this.environmentTexture = null; - } - for (const component of this.scene._serializableComponents) { - component.removeFromContainer(this, true); - } - if (this._onContextRestoredObserver) { - this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver); - this._onContextRestoredObserver = null; - } - } - _moveAssets(sourceAssets, targetAssets, keepAssets) { - if (!sourceAssets || !targetAssets) { - return; - } - for (const asset of sourceAssets) { - let move = true; - if (keepAssets) { - for (const keepAsset of keepAssets) { - if (asset === keepAsset) { - move = false; - break; - } - } - } - if (move) { - targetAssets.push(asset); - asset._parentContainer = this; - } - } - } - /** - * Removes all the assets contained in the scene and adds them to the container. - * @param keepAssets Set of assets to keep in the scene. (default: empty) - */ - moveAllFromScene(keepAssets) { - this._wasAddedToScene = false; - if (keepAssets === undefined) { - keepAssets = new KeepAssets(); - } - for (const key in this) { - if (Object.prototype.hasOwnProperty.call(this, key)) { - this[key] = this[key] || (key === "_environmentTexture" ? null : []); - this._moveAssets(this.scene[key], this[key], keepAssets[key]); - } - } - this.environmentTexture = this.scene.environmentTexture; - this.removeAllFromScene(); - } - /** - * 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. - * @returns the root mesh - */ - createRootMesh() { - const rootMesh = new mesh_Mesh("assetContainerRootMesh", this.scene); - this.meshes.forEach((m) => { - if (!m.parent) { - rootMesh.addChild(m); - } - }); - this.meshes.unshift(rootMesh); - return rootMesh; - } - /** - * Merge animations (direct and animation groups) from this asset container into a scene - * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) - * @param animatables set of animatables to retarget to a node from the scene - * @param targetConverter defines a function used to convert animation targets from the asset container to the scene (default: search node by name) - * @returns an array of the new AnimationGroup added to the scene (empty array if none) - */ - mergeAnimationsTo(scene = engineStore_EngineStore.LastCreatedScene, animatables, targetConverter = null) { - if (!scene) { - logger_Logger.Error("No scene available to merge animations to"); - return []; - } - const _targetConverter = targetConverter - ? targetConverter - : (target) => { - let node = null; - const targetProperty = target.animations.length ? target.animations[0].targetProperty : ""; - /* - BabylonJS adds special naming to targets that are children of nodes. - This name attempts to remove that special naming to get the parent nodes name in case the target - can't be found in the node tree - - Ex: Torso_primitive0 likely points to a Mesh primitive. We take away primitive0 and are left with "Torso" which is the name - of the primitive's parent. - */ - const name = target.name.split(".").join("").split("_primitive")[0]; - switch (targetProperty) { - case "position": - case "rotationQuaternion": - node = scene.getTransformNodeByName(target.name) || scene.getTransformNodeByName(name); - break; - case "influence": - node = scene.getMorphTargetByName(target.name) || scene.getMorphTargetByName(name); - break; - default: - node = scene.getNodeByName(target.name) || scene.getNodeByName(name); - } - return node; - }; - // Copy new node animations - const nodesInAC = this.getNodes(); - nodesInAC.forEach((nodeInAC) => { - const nodeInScene = _targetConverter(nodeInAC); - if (nodeInScene !== null) { - // Remove old animations with same target property as a new one - for (const animationInAC of nodeInAC.animations) { - // Doing treatment on an array for safety measure - const animationsWithSameProperty = nodeInScene.animations.filter((animationInScene) => { - return animationInScene.targetProperty === animationInAC.targetProperty; - }); - for (const animationWithSameProperty of animationsWithSameProperty) { - const index = nodeInScene.animations.indexOf(animationWithSameProperty, 0); - if (index > -1) { - nodeInScene.animations.splice(index, 1); - } - } - } - // Append new animations - nodeInScene.animations = nodeInScene.animations.concat(nodeInAC.animations); - } - }); - const newAnimationGroups = new Array(); - // Copy new animation groups - this.animationGroups.slice().forEach((animationGroupInAC) => { - // Clone the animation group and all its animatables - newAnimationGroups.push(animationGroupInAC.clone(animationGroupInAC.name, _targetConverter)); - // Remove animatables related to the asset container - animationGroupInAC.animatables.forEach((animatable) => { - animatable.stop(); - }); - }); - // Retarget animatables - animatables.forEach((animatable) => { - const target = _targetConverter(animatable.target); - if (target) { - // Clone the animatable and retarget it - scene.beginAnimation(target, animatable.fromFrame, animatable.toFrame, animatable.loopAnimation, animatable.speedRatio, animatable.onAnimationEnd ? animatable.onAnimationEnd : undefined, undefined, true, undefined, animatable.onAnimationLoop ? animatable.onAnimationLoop : undefined); - // Stop animation for the target in the asset container - scene.stopAnimation(animatable.target); - } - }); - return newAnimationGroups; - } - /** - * @since 6.15.0 - * This method checks for any node that has no parent - * and is not in the rootNodes array, and adds the node - * there, if so. - */ - populateRootNodes() { - this.rootNodes.length = 0; - this.meshes.forEach((m) => { - if (!m.parent && this.rootNodes.indexOf(m) === -1) { - this.rootNodes.push(m); - } - }); - this.transformNodes.forEach((t) => { - if (!t.parent && this.rootNodes.indexOf(t) === -1) { - this.rootNodes.push(t); - } - }); - this.lights.forEach((l) => { - if (!l.parent && this.rootNodes.indexOf(l) === -1) { - this.rootNodes.push(l); - } - }); - this.cameras.forEach((c) => { - if (!c.parent && this.rootNodes.indexOf(c) === -1) { - this.rootNodes.push(c); - } - }); - } -} -//# sourceMappingURL=assetContainer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Audio/Interfaces/IAudioEngine.js - -//# sourceMappingURL=IAudioEngine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Audio/Interfaces/ISoundOptions.js - -//# sourceMappingURL=ISoundOptions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Audio/analyser.js - - - -/** - * Class used to work with sound analyzer using fast fourier transform (FFT) - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic - */ -class Analyser { - /** - * Creates a new analyser - * @param scene defines hosting scene - */ - constructor(scene) { - /** - * Gets or sets the smoothing - * @ignorenaming - */ - this.SMOOTHING = 0.75; - /** - * Gets or sets the FFT table size - * @ignorenaming - */ - this.FFT_SIZE = 512; - /** - * Gets or sets the bar graph amplitude - * @ignorenaming - */ - this.BARGRAPHAMPLITUDE = 256; - /** - * Gets or sets the position of the debug canvas - * @ignorenaming - */ - this.DEBUGCANVASPOS = { x: 20, y: 20 }; - /** - * Gets or sets the debug canvas size - * @ignorenaming - */ - this.DEBUGCANVASSIZE = { width: 320, height: 200 }; - scene = scene || EngineStore.LastCreatedScene; - if (!scene) { - return; - } - this._scene = scene; - if (!Engine.audioEngine) { - Tools.Warn("No audio engine initialized, failed to create an audio analyser"); - return; - } - this._audioEngine = Engine.audioEngine; - if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) { - this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser(); - this._webAudioAnalyser.minDecibels = -140; - this._webAudioAnalyser.maxDecibels = 0; - this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount); - this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount); - this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount); - } - } - /** - * Get the number of data values you will have to play with for the visualization - * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount - * @returns a number - */ - getFrequencyBinCount() { - if (this._audioEngine.canUseWebAudio) { - return this._webAudioAnalyser.frequencyBinCount; - } - else { - return 0; - } - } - /** - * Gets the current frequency data as a byte array - * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData - * @returns a Uint8Array - */ - getByteFrequencyData() { - if (this._audioEngine.canUseWebAudio) { - this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; - this._webAudioAnalyser.fftSize = this.FFT_SIZE; - this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs); - } - return this._byteFreqs; - } - /** - * Gets the current waveform as a byte array - * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData - * @returns a Uint8Array - */ - getByteTimeDomainData() { - if (this._audioEngine.canUseWebAudio) { - this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; - this._webAudioAnalyser.fftSize = this.FFT_SIZE; - this._webAudioAnalyser.getByteTimeDomainData(this._byteTime); - } - return this._byteTime; - } - /** - * Gets the current frequency data as a float array - * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData - * @returns a Float32Array - */ - getFloatFrequencyData() { - if (this._audioEngine.canUseWebAudio) { - this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; - this._webAudioAnalyser.fftSize = this.FFT_SIZE; - this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs); - } - return this._floatFreqs; - } - /** - * Renders the debug canvas - */ - drawDebugCanvas() { - if (this._audioEngine.canUseWebAudio) { - if (!this._debugCanvas) { - this._debugCanvas = document.createElement("canvas"); - this._debugCanvas.width = this.DEBUGCANVASSIZE.width; - this._debugCanvas.height = this.DEBUGCANVASSIZE.height; - this._debugCanvas.style.position = "absolute"; - this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px"; - this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px"; - this._debugCanvasContext = this._debugCanvas.getContext("2d"); - document.body.appendChild(this._debugCanvas); - this._registerFunc = () => { - this.drawDebugCanvas(); - }; - this._scene.registerBeforeRender(this._registerFunc); - } - if (this._registerFunc && this._debugCanvasContext) { - const workingArray = this.getByteFrequencyData(); - this._debugCanvasContext.fillStyle = "rgb(0, 0, 0)"; - this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height); - // Draw the frequency domain chart. - for (let i = 0; i < this.getFrequencyBinCount(); i++) { - const value = workingArray[i]; - const percent = value / this.BARGRAPHAMPLITUDE; - const height = this.DEBUGCANVASSIZE.height * percent; - const offset = this.DEBUGCANVASSIZE.height - height - 1; - const barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount(); - const hue = (i / this.getFrequencyBinCount()) * 360; - this._debugCanvasContext.fillStyle = "hsl(" + hue + ", 100%, 50%)"; - this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height); - } - } - } - } - /** - * Stops rendering the debug canvas and removes it - */ - stopDebugCanvas() { - if (this._debugCanvas) { - if (this._registerFunc) { - this._scene.unregisterBeforeRender(this._registerFunc); - this._registerFunc = null; - } - document.body.removeChild(this._debugCanvas); - this._debugCanvas = null; - this._debugCanvasContext = null; - } - } - /** - * Connects two audio nodes - * @param inputAudioNode defines first node to connect - * @param outputAudioNode defines second node to connect - */ - connectAudioNodes(inputAudioNode, outputAudioNode) { - if (this._audioEngine.canUseWebAudio) { - inputAudioNode.connect(this._webAudioAnalyser); - this._webAudioAnalyser.connect(outputAudioNode); - } - } - /** - * Releases all associated resources - */ - dispose() { - if (this._audioEngine.canUseWebAudio) { - this._webAudioAnalyser.disconnect(); - } - } -} -//# sourceMappingURL=analyser.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Audio/audioEngine.js - - - - -// Sets the default audio engine to Babylon.js -engine_Engine.AudioEngineFactory = (hostElement, audioContext, audioDestination) => { - return new AudioEngine(hostElement, audioContext, audioDestination); -}; -/** - * This represents the default audio engine used in babylon. - * It is responsible to play, synchronize and analyse sounds throughout the application. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic - */ -class AudioEngine { - /** - * Gets the current AudioContext if available. - */ - get audioContext() { - if (!this._audioContextInitialized) { - this._initializeAudioContext(); - } - return this._audioContext; - } - /** - * Instantiates a new audio engine. - * - * There should be only one per page as some browsers restrict the number - * of audio contexts you can create. - * @param hostElement defines the host element where to display the mute icon if necessary - * @param audioContext defines the audio context to be used by the audio engine - * @param audioDestination defines the audio destination node to be used by audio engine - */ - constructor(hostElement = null, audioContext = null, audioDestination = null) { - this._audioContext = null; - this._audioContextInitialized = false; - this._muteButton = null; - this._audioDestination = null; - /** - * Gets whether the current host supports Web Audio and thus could create AudioContexts. - */ - this.canUseWebAudio = false; - /** - * Defines if Babylon should emit a warning if WebAudio is not supported. - * @ignoreNaming - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - this.WarnedWebAudioUnsupported = false; - /** - * Gets whether or not mp3 are supported by your browser. - */ - this.isMP3supported = false; - /** - * Gets whether or not ogg are supported by your browser. - */ - this.isOGGsupported = false; - /** - * Gets whether audio has been unlocked on the device. - * Some Browsers have strong restrictions about Audio and won't autoplay unless - * a user interaction has happened. - */ - this.unlocked = false; - /** - * Defines if the audio engine relies on a custom unlocked button. - * In this case, the embedded button will not be displayed. - */ - this.useCustomUnlockedButton = false; - /** - * Event raised when audio has been unlocked on the browser. - */ - this.onAudioUnlockedObservable = new observable_Observable(); - /** - * Event raised when audio has been locked on the browser. - */ - this.onAudioLockedObservable = new observable_Observable(); - this._tryToRun = false; - this._onResize = () => { - this._moveButtonToTopLeft(); - }; - if (!IsWindowObjectExist()) { - return; - } - if (typeof window.AudioContext !== "undefined") { - this.canUseWebAudio = true; - } - const audioElem = document.createElement("audio"); - this._hostElement = hostElement; - this._audioContext = audioContext; - this._audioDestination = audioDestination; - try { - if (audioElem && - !!audioElem.canPlayType && - (audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, "") || audioElem.canPlayType("audio/mp3").replace(/^no$/, ""))) { - this.isMP3supported = true; - } - } - catch (e) { - // protect error during capability check. - } - try { - if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, "")) { - this.isOGGsupported = true; - } - } - catch (e) { - // protect error during capability check. - } - } - /** - * Flags the audio engine in Locked state. - * This happens due to new browser policies preventing audio to autoplay. - */ - lock() { - this._triggerSuspendedState(); - } - /** - * Unlocks the audio engine once a user action has been done on the dom. - * This is helpful to resume play once browser policies have been satisfied. - */ - unlock() { - var _a, _b; - if (((_a = this._audioContext) === null || _a === void 0 ? void 0 : _a.state) === "running") { - this._hideMuteButton(); - return; - } - // On iOS, if the audio context resume request was sent from an event other than a `click` event, then - // the resume promise will never resolve and the only way to get the audio context unstuck is to - // suspend it and make another resume request. - if (this._tryToRun) { - (_b = this._audioContext) === null || _b === void 0 ? void 0 : _b.suspend().then(() => { - this._tryToRun = false; - this._triggerRunningState(); - }); - } - else { - this._triggerRunningState(); - } - } - _resumeAudioContext() { - var _a; - if ((_a = this._audioContext) === null || _a === void 0 ? void 0 : _a.resume) { - return this._audioContext.resume(); - } - return Promise.resolve(); - } - _initializeAudioContext() { - try { - if (this.canUseWebAudio) { - if (!this._audioContext) { - this._audioContext = new AudioContext(); - } - // create a global volume gain node - this.masterGain = this._audioContext.createGain(); - this.masterGain.gain.value = 1; - if (!this._audioDestination) { - this._audioDestination = this._audioContext.destination; - } - this.masterGain.connect(this._audioDestination); - this._audioContextInitialized = true; - if (this._audioContext.state === "running") { - // Do not wait for the promise to unlock. - this._triggerRunningState(); - } - } - } - catch (e) { - this.canUseWebAudio = false; - logger_Logger.Error("Web Audio: " + e.message); - } - } - _triggerRunningState() { - if (this._tryToRun) { - return; - } - this._tryToRun = true; - this._resumeAudioContext() - .then(() => { - this._tryToRun = false; - if (this._muteButton) { - this._hideMuteButton(); - } - // Notify users that the audio stack is unlocked/unmuted - this.unlocked = true; - this.onAudioUnlockedObservable.notifyObservers(this); - }) - .catch(() => { - this._tryToRun = false; - this.unlocked = false; - }); - } - _triggerSuspendedState() { - this.unlocked = false; - 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 imageUrl = !window.SVGSVGElement - ? "https://cdn.babylonjs.com/Assets/audio.png" - : "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"; - const css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(" + - imageUrl + - "); 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) }"; - const style = document.createElement("style"); - style.appendChild(document.createTextNode(css)); - document.getElementsByTagName("head")[0].appendChild(style); - document.body.appendChild(this._muteButton); - this._moveButtonToTopLeft(); - this._muteButton.addEventListener("touchend", () => { - this._triggerRunningState(); - }, true); - this._muteButton.addEventListener("click", () => { - this.unlock(); - }, true); - window.addEventListener("resize", this._onResize); - } - _moveButtonToTopLeft() { - if (this._hostElement && this._muteButton) { - this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px"; - this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px"; - } - } - _hideMuteButton() { - if (this._muteButton) { - document.body.removeChild(this._muteButton); - this._muteButton = null; - } - } - /** - * Destroy and release the resources associated with the audio context. - */ - dispose() { - if (this.canUseWebAudio && this._audioContextInitialized) { - if (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 = false; - this._hideMuteButton(); - window.removeEventListener("resize", this._onResize); - this.onAudioUnlockedObservable.clear(); - this.onAudioLockedObservable.clear(); - } - /** - * Gets the global volume sets on the master gain. - * @returns the global volume if set or -1 otherwise - */ - getGlobalVolume() { - if (this.canUseWebAudio && this._audioContextInitialized) { - return this.masterGain.gain.value; - } - else { - return -1; - } - } - /** - * Sets the global volume of your experience (sets on the master gain). - * @param newVolume Defines the new global volume of the application - */ - setGlobalVolume(newVolume) { - if (this.canUseWebAudio && this._audioContextInitialized) { - this.masterGain.gain.value = newVolume; - } - } - /** - * Connect the audio engine to an audio analyser allowing some amazing - * synchronization between the sounds/music and your visualization (VuMeter for instance). - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-the-analyser - * @param analyser The analyser to connect to the engine - */ - connectToAnalyser(analyser) { - if (this._connectedAnalyser) { - this._connectedAnalyser.stopDebugCanvas(); - } - if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) { - this._connectedAnalyser = analyser; - this.masterGain.disconnect(); - this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination); - } - } -} -//# sourceMappingURL=audioEngine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Audio/sound.js - - - - - - - -/** - * Defines a sound that can be played in the application. - * The sound can either be an ambient track or a simple sound played in reaction to a user action. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic - */ -class Sound { - /** - * Does the sound loop after it finishes playing once. - */ - get loop() { - return this._loop; - } - set loop(value) { - if (value === this._loop) { - return; - } - this._loop = value; - this.updateOptions({ loop: value }); - } - /** - * Gets the current time for the sound. - */ - get currentTime() { - var _a; - if (this._htmlAudioElement) { - return this._htmlAudioElement.currentTime; - } - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) && (this.isPlaying || this.isPaused)) { - // The `_currentTime` member is only updated when the sound is paused. Add the time since the last start - // to get the actual current time. - const timeSinceLastStart = this.isPaused ? 0 : engine_Engine.audioEngine.audioContext.currentTime - this._startTime; - return this._currentTime + timeSinceLastStart; - } - return 0; - } - /** - * Does this sound enables spatial sound. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound - */ - get spatialSound() { - return this._spatialSound; - } - /** - * Does this sound enables spatial sound. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound - */ - set spatialSound(newValue) { - if (newValue == this._spatialSound) { - return; - } - const wasPlaying = this.isPlaying; - this.pause(); - if (newValue) { - this._spatialSound = newValue; - this._updateSpatialParameters(); - } - else { - this._disableSpatialSound(); - } - if (wasPlaying) { - this.play(); - } - } - /** - * Create a sound and attach it to a scene - * @param name Name of your sound - * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams and AudioBuffers - * @param scene defines the scene the sound belongs to - * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played - * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming - */ - constructor(name, urlOrArrayBuffer, scene, readyToPlayCallback = null, options) { - var _a, _b, _c, _d, _e; - /** - * Does the sound autoplay once loaded. - */ - this.autoplay = false; - this._loop = false; - /** - * Does the sound use a custom attenuation curve to simulate the falloff - * happening when the source gets further away from the camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-your-own-custom-attenuation-function - */ - this.useCustomAttenuation = false; - /** - * Is this sound currently played. - */ - this.isPlaying = false; - /** - * Is this sound currently paused. - */ - this.isPaused = false; - /** - * Define the reference distance the sound should be heard perfectly. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound - */ - this.refDistance = 1; - /** - * Define the roll off factor of spatial sounds. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound - */ - this.rolloffFactor = 1; - /** - * Define the max distance the sound should be heard (intensity just became 0 at this point). - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound - */ - this.maxDistance = 100; - /** - * Define the distance attenuation model the sound will follow. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound - */ - this.distanceModel = "linear"; - /** - * Gets or sets an object used to store user defined information for the sound. - */ - this.metadata = null; - /** - * Observable event when the current playing sound finishes. - */ - this.onEndedObservable = new observable_Observable(); - this._spatialSound = false; - this._panningModel = "equalpower"; - this._playbackRate = 1; - this._streaming = false; - this._startTime = 0; - this._currentTime = 0; - this._position = math_vector_Vector3.Zero(); - this._localDirection = new math_vector_Vector3(1, 0, 0); - this._volume = 1; - this._isReadyToPlay = false; - this._isDirectional = false; - // Used if you'd like to create a directional sound. - // If not set, the sound will be omnidirectional - this._coneInnerAngle = 360; - this._coneOuterAngle = 360; - this._coneOuterGain = 0; - this._isOutputConnected = false; - this._urlType = "Unknown"; - this.name = name; - scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!scene) { - return; - } - this._scene = scene; - Sound._SceneComponentInitialization(scene); - this._readyToPlayCallback = readyToPlayCallback; - // Default custom attenuation function is a linear attenuation - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._customAttenuationFunction = (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) => { - if (currentDistance < maxDistance) { - return currentVolume * (1 - currentDistance / maxDistance); - } - else { - return 0; - } - }; - if (options) { - this.autoplay = options.autoplay || false; - this._loop = options.loop || false; - // if volume === 0, we need another way to check this option - if (options.volume !== undefined) { - this._volume = options.volume; - } - this._spatialSound = (_a = options.spatialSound) !== null && _a !== void 0 ? _a : false; - this.maxDistance = (_b = options.maxDistance) !== null && _b !== void 0 ? _b : 100; - this.useCustomAttenuation = (_c = options.useCustomAttenuation) !== null && _c !== void 0 ? _c : false; - this.rolloffFactor = options.rolloffFactor || 1; - this.refDistance = options.refDistance || 1; - this.distanceModel = options.distanceModel || "linear"; - this._playbackRate = options.playbackRate || 1; - this._streaming = (_d = options.streaming) !== null && _d !== void 0 ? _d : false; - this._length = options.length; - this._offset = options.offset; - } - if (((_e = engine_Engine.audioEngine) === null || _e === void 0 ? void 0 : _e.canUseWebAudio) && engine_Engine.audioEngine.audioContext) { - this._soundGain = engine_Engine.audioEngine.audioContext.createGain(); - this._soundGain.gain.value = this._volume; - this._inputAudioNode = this._soundGain; - this._outputAudioNode = this._soundGain; - if (this._spatialSound) { - this._createSpatialParameters(); - } - this._scene.mainSoundTrack.addSound(this); - let validParameter = true; - // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound - if (urlOrArrayBuffer) { - try { - if (typeof urlOrArrayBuffer === "string") { - this._urlType = "String"; - } - else if (urlOrArrayBuffer instanceof ArrayBuffer) { - this._urlType = "ArrayBuffer"; - } - else if (urlOrArrayBuffer instanceof HTMLMediaElement) { - this._urlType = "MediaElement"; - } - else if (urlOrArrayBuffer instanceof MediaStream) { - this._urlType = "MediaStream"; - } - else if (urlOrArrayBuffer instanceof AudioBuffer) { - this._urlType = "AudioBuffer"; - } - else if (Array.isArray(urlOrArrayBuffer)) { - this._urlType = "Array"; - } - let urls = []; - let codecSupportedFound = false; - switch (this._urlType) { - case "MediaElement": - this._streaming = true; - this._isReadyToPlay = true; - this._streamingSource = engine_Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer); - if (this.autoplay) { - this.play(0, this._offset, this._length); - } - if (this._readyToPlayCallback) { - this._readyToPlayCallback(); - } - break; - case "MediaStream": - this._streaming = true; - this._isReadyToPlay = true; - this._streamingSource = engine_Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer); - if (this.autoplay) { - this.play(0, this._offset, this._length); - } - if (this._readyToPlayCallback) { - this._readyToPlayCallback(); - } - break; - case "ArrayBuffer": - if (urlOrArrayBuffer.byteLength > 0) { - codecSupportedFound = true; - this._soundLoaded(urlOrArrayBuffer); - } - break; - case "AudioBuffer": - this._audioBufferLoaded(urlOrArrayBuffer); - break; - case "String": - urls.push(urlOrArrayBuffer); - // eslint-disable-next-line no-fallthrough - case "Array": - if (urls.length === 0) { - urls = urlOrArrayBuffer; - } - // If we found a supported format, we load it immediately and stop the loop - for (let i = 0; i < urls.length; i++) { - const url = urls[i]; - codecSupportedFound = - (options && options.skipCodecCheck) || - (url.indexOf(".mp3", url.length - 4) !== -1 && engine_Engine.audioEngine.isMP3supported) || - (url.indexOf(".ogg", url.length - 4) !== -1 && engine_Engine.audioEngine.isOGGsupported) || - url.indexOf(".wav", url.length - 4) !== -1 || - url.indexOf(".m4a", url.length - 4) !== -1 || - url.indexOf(".mp4", url.length - 4) !== -1 || - url.indexOf("blob:") !== -1; - if (codecSupportedFound) { - // Loading sound - if (!this._streaming) { - this._scene._loadFile(url, (data) => { - this._soundLoaded(data); - }, undefined, true, true, (exception) => { - if (exception) { - logger_Logger.Error("XHR " + exception.status + " error on: " + url + "."); - } - logger_Logger.Error("Sound creation aborted."); - this._scene.mainSoundTrack.removeSound(this); - }); - } - // Streaming sound using HTML5 Audio tag - else { - this._htmlAudioElement = new Audio(url); - this._htmlAudioElement.controls = false; - this._htmlAudioElement.loop = this.loop; - tools_Tools.SetCorsBehavior(url, this._htmlAudioElement); - this._htmlAudioElement.preload = "auto"; - this._htmlAudioElement.addEventListener("canplaythrough", () => { - this._isReadyToPlay = true; - if (this.autoplay) { - this.play(0, this._offset, this._length); - } - if (this._readyToPlayCallback) { - this._readyToPlayCallback(); - } - }); - document.body.appendChild(this._htmlAudioElement); - this._htmlAudioElement.load(); - } - break; - } - } - break; - default: - validParameter = false; - break; - } - if (!validParameter) { - logger_Logger.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound."); - } - else { - if (!codecSupportedFound) { - this._isReadyToPlay = true; - // Simulating a ready to play event to avoid breaking code path - if (this._readyToPlayCallback) { - setTimeout(() => { - if (this._readyToPlayCallback) { - this._readyToPlayCallback(); - } - }, 1000); - } - } - } - } - catch (ex) { - logger_Logger.Error("Unexpected error. Sound creation aborted."); - this._scene.mainSoundTrack.removeSound(this); - } - } - } - else { - // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers - this._scene.mainSoundTrack.addSound(this); - if (engine_Engine.audioEngine && !engine_Engine.audioEngine.WarnedWebAudioUnsupported) { - logger_Logger.Error("Web Audio is not supported by your browser."); - engine_Engine.audioEngine.WarnedWebAudioUnsupported = true; - } - // Simulating a ready to play event to avoid breaking code for non web audio browsers - if (this._readyToPlayCallback) { - setTimeout(() => { - if (this._readyToPlayCallback) { - this._readyToPlayCallback(); - } - }, 1000); - } - } - } - /** - * Release the sound and its associated resources - */ - dispose() { - var _a; - if ((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) { - if (this.isPlaying) { - this.stop(); - } - this._isReadyToPlay = false; - if (this.soundTrackId === -1) { - this._scene.mainSoundTrack.removeSound(this); - } - else if (this._scene.soundTracks) { - this._scene.soundTracks[this.soundTrackId].removeSound(this); - } - if (this._soundGain) { - this._soundGain.disconnect(); - this._soundGain = null; - } - if (this._soundPanner) { - this._soundPanner.disconnect(); - this._soundPanner = null; - } - if (this._soundSource) { - this._soundSource.disconnect(); - this._soundSource = null; - } - this._audioBuffer = null; - if (this._htmlAudioElement) { - this._htmlAudioElement.pause(); - this._htmlAudioElement.src = ""; - document.body.removeChild(this._htmlAudioElement); - } - if (this._streamingSource) { - this._streamingSource.disconnect(); - } - if (this._connectedTransformNode && this._registerFunc) { - this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); - this._connectedTransformNode = null; - } - this._clearTimeoutsAndObservers(); - } - } - /** - * Gets if the sounds is ready to be played or not. - * @returns true if ready, otherwise false - */ - isReady() { - return this._isReadyToPlay; - } - /** - * Get the current class name. - * @returns current class name - */ - getClassName() { - return "Sound"; - } - _audioBufferLoaded(buffer) { - var _a; - if (!((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext)) { - return; - } - this._audioBuffer = buffer; - this._isReadyToPlay = true; - if (this.autoplay) { - this.play(0, this._offset, this._length); - } - if (this._readyToPlayCallback) { - this._readyToPlayCallback(); - } - } - _soundLoaded(audioData) { - var _a; - if (!((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext)) { - return; - } - engine_Engine.audioEngine.audioContext.decodeAudioData(audioData, (buffer) => { - this._audioBufferLoaded(buffer); - }, (err) => { - logger_Logger.Error("Error while decoding audio data for: " + this.name + " / Error: " + err); - }); - } - /** - * Sets the data of the sound from an audiobuffer - * @param audioBuffer The audioBuffer containing the data - */ - setAudioBuffer(audioBuffer) { - var _a; - if ((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) { - this._audioBuffer = audioBuffer; - this._isReadyToPlay = true; - } - } - /** - * Updates the current sounds options such as maxdistance, loop... - * @param options A JSON object containing values named as the object properties - */ - updateOptions(options) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; - if (options) { - this.loop = (_a = options.loop) !== null && _a !== void 0 ? _a : this.loop; - this.maxDistance = (_b = options.maxDistance) !== null && _b !== void 0 ? _b : this.maxDistance; - this.useCustomAttenuation = (_c = options.useCustomAttenuation) !== null && _c !== void 0 ? _c : this.useCustomAttenuation; - this.rolloffFactor = (_d = options.rolloffFactor) !== null && _d !== void 0 ? _d : this.rolloffFactor; - this.refDistance = (_e = options.refDistance) !== null && _e !== void 0 ? _e : this.refDistance; - this.distanceModel = (_f = options.distanceModel) !== null && _f !== void 0 ? _f : this.distanceModel; - this._playbackRate = (_g = options.playbackRate) !== null && _g !== void 0 ? _g : this._playbackRate; - this._length = (_h = options.length) !== null && _h !== void 0 ? _h : undefined; - this.spatialSound = (_j = options.spatialSound) !== null && _j !== void 0 ? _j : this._spatialSound; - this._setOffset((_k = options.offset) !== null && _k !== void 0 ? _k : undefined); - this.setVolume((_l = options.volume) !== null && _l !== void 0 ? _l : this._volume); - this._updateSpatialParameters(); - if (this.isPlaying) { - if (this._streaming && this._htmlAudioElement) { - this._htmlAudioElement.playbackRate = this._playbackRate; - if (this._htmlAudioElement.loop !== this.loop) { - this._htmlAudioElement.loop = this.loop; - } - } - else { - if (this._soundSource) { - this._soundSource.playbackRate.value = this._playbackRate; - if (this._soundSource.loop !== this.loop) { - this._soundSource.loop = this.loop; - } - if (this._offset !== undefined && this._soundSource.loopStart !== this._offset) { - this._soundSource.loopStart = this._offset; - } - if (this._length !== undefined && this._length !== this._soundSource.loopEnd) { - this._soundSource.loopEnd = (this._offset | 0) + this._length; - } - } - } - } - } - } - _createSpatialParameters() { - var _a, _b; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && engine_Engine.audioEngine.audioContext) { - if (this._scene.headphone) { - this._panningModel = "HRTF"; - } - this._soundPanner = (_b = this._soundPanner) !== null && _b !== void 0 ? _b : engine_Engine.audioEngine.audioContext.createPanner(); - if (this._soundPanner && this._outputAudioNode) { - this._updateSpatialParameters(); - this._soundPanner.connect(this._outputAudioNode); - this._inputAudioNode = this._soundPanner; - } - } - } - _disableSpatialSound() { - var _a; - if (!this._spatialSound) { - return; - } - this._inputAudioNode = this._soundGain; - (_a = this._soundPanner) === null || _a === void 0 ? void 0 : _a.disconnect(); - this._soundPanner = null; - this._spatialSound = false; - } - _updateSpatialParameters() { - if (!this._spatialSound) { - return; - } - if (this._soundPanner) { - if (this.useCustomAttenuation) { - // Tricks to disable in a way embedded Web Audio attenuation - this._soundPanner.distanceModel = "linear"; - this._soundPanner.maxDistance = Number.MAX_VALUE; - this._soundPanner.refDistance = 1; - this._soundPanner.rolloffFactor = 1; - this._soundPanner.panningModel = this._panningModel; - } - else { - 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; - } - } - else { - this._createSpatialParameters(); - } - } - /** - * Switch the panning model to HRTF: - * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound - */ - switchPanningModelToHRTF() { - this._panningModel = "HRTF"; - this._switchPanningModel(); - } - /** - * Switch the panning model to Equal Power: - * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound - */ - switchPanningModelToEqualPower() { - this._panningModel = "equalpower"; - this._switchPanningModel(); - } - _switchPanningModel() { - var _a; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner) { - this._soundPanner.panningModel = this._panningModel; - } - } - /** - * Connect this sound to a sound track audio node like gain... - * @param soundTrackAudioNode the sound track audio node to connect to - */ - connectToSoundTrackAudioNode(soundTrackAudioNode) { - var _a; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) { - if (this._isOutputConnected) { - this._outputAudioNode.disconnect(); - } - this._outputAudioNode.connect(soundTrackAudioNode); - this._isOutputConnected = true; - } - } - /** - * Transform this sound into a directional source - * @param coneInnerAngle Size of the inner cone in degree - * @param coneOuterAngle Size of the outer cone in degree - * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0) - */ - setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) { - if (coneOuterAngle < coneInnerAngle) { - logger_Logger.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."); - return; - } - this._coneInnerAngle = coneInnerAngle; - this._coneOuterAngle = coneOuterAngle; - this._coneOuterGain = coneOuterGain; - this._isDirectional = true; - if (this.isPlaying && this.loop) { - this.stop(); - this.play(0, this._offset, this._length); - } - } - /** - * Gets or sets the inner angle for the directional cone. - */ - get directionalConeInnerAngle() { - return this._coneInnerAngle; - } - /** - * Gets or sets the inner angle for the directional cone. - */ - set directionalConeInnerAngle(value) { - var _a; - if (value != this._coneInnerAngle) { - if (this._coneOuterAngle < value) { - logger_Logger.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle."); - return; - } - this._coneInnerAngle = value; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner) { - this._soundPanner.coneInnerAngle = this._coneInnerAngle; - } - } - } - /** - * Gets or sets the outer angle for the directional cone. - */ - get directionalConeOuterAngle() { - return this._coneOuterAngle; - } - /** - * Gets or sets the outer angle for the directional cone. - */ - set directionalConeOuterAngle(value) { - var _a; - if (value != this._coneOuterAngle) { - if (value < this._coneInnerAngle) { - logger_Logger.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle."); - return; - } - this._coneOuterAngle = value; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner) { - this._soundPanner.coneOuterAngle = this._coneOuterAngle; - } - } - } - /** - * Sets the position of the emitter if spatial sound is enabled - * @param newPosition Defines the new position - */ - setPosition(newPosition) { - var _a; - if (newPosition.equals(this._position)) { - return; - } - this._position.copyFrom(newPosition); - if (((_a = engine_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)) { - this._soundPanner.positionX.value = this._position.x; - this._soundPanner.positionY.value = this._position.y; - this._soundPanner.positionZ.value = this._position.z; - } - } - /** - * Sets the local direction of the emitter if spatial sound is enabled - * @param newLocalDirection Defines the new local direction - */ - setLocalDirectionToMesh(newLocalDirection) { - var _a; - this._localDirection = newLocalDirection; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._connectedTransformNode && this.isPlaying) { - this._updateDirection(); - } - } - _updateDirection() { - if (!this._connectedTransformNode || !this._soundPanner) { - return; - } - const mat = this._connectedTransformNode.getWorldMatrix(); - const direction = math_vector_Vector3.TransformNormal(this._localDirection, mat); - direction.normalize(); - this._soundPanner.orientationX.value = direction.x; - this._soundPanner.orientationY.value = direction.y; - this._soundPanner.orientationZ.value = direction.z; - } - /** @internal */ - updateDistanceFromListener() { - var _a; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) { - const distance = this._scene.audioListenerPositionProvider - ? this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length() - : this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera); - this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor); - } - } - /** - * Sets a new custom attenuation function for the sound. - * @param callback Defines the function used for the attenuation - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-your-own-custom-attenuation-function - */ - setAttenuationFunction(callback) { - this._customAttenuationFunction = callback; - } - /** - * Play the sound - * @param time (optional) Start the sound after X seconds. Start immediately (0) by default. - * @param offset (optional) Start the sound at a specific time in seconds - * @param length (optional) Sound duration (in seconds) - */ - play(time, offset, length) { - var _a, _b, _c, _d; - if (this._isReadyToPlay && this._scene.audioEnabled && ((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext)) { - try { - this._clearTimeoutsAndObservers(); - let startTime = time ? ((_b = engine_Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.audioContext.currentTime) + time : (_c = engine_Engine.audioEngine) === null || _c === void 0 ? void 0 : _c.audioContext.currentTime; - if (!this._soundSource || !this._streamingSource) { - if (this._spatialSound && this._soundPanner) { - if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) { - this._soundPanner.positionX.value = this._position.x; - this._soundPanner.positionY.value = this._position.y; - this._soundPanner.positionZ.value = this._position.z; - } - if (this._isDirectional) { - this._soundPanner.coneInnerAngle = this._coneInnerAngle; - this._soundPanner.coneOuterAngle = this._coneOuterAngle; - this._soundPanner.coneOuterGain = this._coneOuterGain; - if (this._connectedTransformNode) { - this._updateDirection(); - } - else { - this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z); - } - } - } - } - if (this._streaming) { - if (!this._streamingSource) { - this._streamingSource = engine_Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement); - this._htmlAudioElement.onended = () => { - this._onended(); - }; - this._htmlAudioElement.playbackRate = this._playbackRate; - } - this._streamingSource.disconnect(); - if (this._inputAudioNode) { - this._streamingSource.connect(this._inputAudioNode); - } - if (this._htmlAudioElement) { - // required to manage properly the new suspended default state of Chrome - // When the option 'streaming: true' is used, we need first to wait for - // the audio engine to be unlocked by a user gesture before trying to play - // an HTML Audio element - const tryToPlay = () => { - var _a, _b; - if ((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.unlocked) { - const playPromise = this._htmlAudioElement.play(); - // In browsers that don’t yet support this functionality, - // playPromise won’t be defined. - if (playPromise !== undefined) { - playPromise.catch(() => { - var _a, _b; - // Automatic playback failed. - // Waiting for the audio engine to be unlocked by user click on unmute - (_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.lock(); - if (this.loop || this.autoplay) { - this._audioUnlockedObserver = (_b = engine_Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.onAudioUnlockedObservable.addOnce(() => { - tryToPlay(); - }); - } - }); - } - } - else { - if (this.loop || this.autoplay) { - this._audioUnlockedObserver = (_b = engine_Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.onAudioUnlockedObservable.addOnce(() => { - tryToPlay(); - }); - } - } - }; - tryToPlay(); - } - } - else { - const tryToPlay = () => { - var _a, _b, _c, _d; - if ((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) { - length = length || this._length; - if (offset !== undefined) { - this._setOffset(offset); - } - if (this._soundSource) { - const oldSource = this._soundSource; - oldSource.onended = () => { - oldSource.disconnect(); - }; - } - this._soundSource = (_b = engine_Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.audioContext.createBufferSource(); - if (this._soundSource && this._inputAudioNode) { - this._soundSource.buffer = this._audioBuffer; - this._soundSource.connect(this._inputAudioNode); - this._soundSource.loop = this.loop; - if (offset !== undefined) { - this._soundSource.loopStart = offset; - } - if (length !== undefined) { - this._soundSource.loopEnd = (offset | 0) + length; - } - this._soundSource.playbackRate.value = this._playbackRate; - this._soundSource.onended = () => { - this._onended(); - }; - startTime = time ? ((_c = engine_Engine.audioEngine) === null || _c === void 0 ? void 0 : _c.audioContext.currentTime) + time : engine_Engine.audioEngine.audioContext.currentTime; - const actualOffset = ((this.isPaused ? this.currentTime : 0) + ((_d = this._offset) !== null && _d !== void 0 ? _d : 0)) % this._soundSource.buffer.duration; - this._soundSource.start(startTime, actualOffset, this.loop ? undefined : length); - } - } - }; - if (((_d = engine_Engine.audioEngine) === null || _d === void 0 ? void 0 : _d.audioContext.state) === "suspended") { - // Wait a bit for FF as context seems late to be ready. - this._tryToPlayTimeout = setTimeout(() => { - var _a; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext.state) === "suspended") { - // Automatic playback failed. - // Waiting for the audio engine to be unlocked by user click on unmute - engine_Engine.audioEngine.lock(); - if (this.loop || this.autoplay) { - this._audioUnlockedObserver = engine_Engine.audioEngine.onAudioUnlockedObservable.addOnce(() => { - tryToPlay(); - }); - } - } - else { - tryToPlay(); - } - }, 500); - } - else { - tryToPlay(); - } - } - this._startTime = startTime; - this.isPlaying = true; - this.isPaused = false; - } - catch (ex) { - logger_Logger.Error("Error while trying to play audio: " + this.name + ", " + ex.message); - } - } - } - _onended() { - this.isPlaying = false; - this._startTime = 0; - this._currentTime = 0; - if (this.onended) { - this.onended(); - } - this.onEndedObservable.notifyObservers(this); - } - /** - * Stop the sound - * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. - */ - stop(time) { - var _a; - if (this.isPlaying) { - this._clearTimeoutsAndObservers(); - if (this._streaming) { - if (this._htmlAudioElement) { - this._htmlAudioElement.pause(); - // Test needed for Firefox or it will generate an Invalid State Error - if (this._htmlAudioElement.currentTime > 0) { - this._htmlAudioElement.currentTime = 0; - } - } - else { - this._streamingSource.disconnect(); - } - this.isPlaying = false; - } - else if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) && this._soundSource) { - const stopTime = time ? engine_Engine.audioEngine.audioContext.currentTime + time : undefined; - this._soundSource.onended = () => { - this.isPlaying = false; - this.isPaused = false; - this._startTime = 0; - this._currentTime = 0; - if (this._soundSource) { - this._soundSource.onended = () => void 0; - } - this._onended(); - }; - this._soundSource.stop(stopTime); - } - else { - this.isPlaying = false; - } - } - else if (this.isPaused) { - this.isPaused = false; - this._startTime = 0; - this._currentTime = 0; - } - } - /** - * Put the sound in pause - */ - pause() { - var _a; - if (this.isPlaying) { - this._clearTimeoutsAndObservers(); - if (this._streaming) { - if (this._htmlAudioElement) { - this._htmlAudioElement.pause(); - } - else { - this._streamingSource.disconnect(); - } - this.isPlaying = false; - this.isPaused = true; - } - else if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) && this._soundSource) { - this._soundSource.onended = () => void 0; - this._soundSource.stop(); - this.isPlaying = false; - this.isPaused = true; - this._currentTime += engine_Engine.audioEngine.audioContext.currentTime - this._startTime; - } - } - } - /** - * Sets a dedicated volume for this sounds - * @param newVolume Define the new volume of the sound - * @param time Define time for gradual change to new volume - */ - setVolume(newVolume, time) { - var _a; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._soundGain) { - if (time && engine_Engine.audioEngine.audioContext) { - this._soundGain.gain.cancelScheduledValues(engine_Engine.audioEngine.audioContext.currentTime); - this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, engine_Engine.audioEngine.audioContext.currentTime); - this._soundGain.gain.linearRampToValueAtTime(newVolume, engine_Engine.audioEngine.audioContext.currentTime + time); - } - else { - this._soundGain.gain.value = newVolume; - } - } - this._volume = newVolume; - } - /** - * Set the sound play back rate - * @param newPlaybackRate Define the playback rate the sound should be played at - */ - setPlaybackRate(newPlaybackRate) { - this._playbackRate = newPlaybackRate; - if (this.isPlaying) { - if (this._streaming && this._htmlAudioElement) { - this._htmlAudioElement.playbackRate = this._playbackRate; - } - else if (this._soundSource) { - this._soundSource.playbackRate.value = this._playbackRate; - } - } - } - /** - * Gets the sound play back rate. - * @returns the play back rate of the sound - */ - getPlaybackRate() { - return this._playbackRate; - } - /** - * Gets the volume of the sound. - * @returns the volume of the sound - */ - getVolume() { - return this._volume; - } - /** - * Attach the sound to a dedicated mesh - * @param transformNode The transform node to connect the sound with - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#attaching-a-sound-to-a-mesh - */ - attachToMesh(transformNode) { - if (this._connectedTransformNode && this._registerFunc) { - this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); - this._registerFunc = null; - } - this._connectedTransformNode = transformNode; - if (!this._spatialSound) { - this._spatialSound = true; - this._createSpatialParameters(); - if (this.isPlaying && this.loop) { - this.stop(); - this.play(0, this._offset, this._length); - } - } - this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode); - this._registerFunc = (transformNode) => this._onRegisterAfterWorldMatrixUpdate(transformNode); - this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc); - } - /** - * Detach the sound from the previously attached mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#attaching-a-sound-to-a-mesh - */ - detachFromMesh() { - if (this._connectedTransformNode && this._registerFunc) { - this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); - this._registerFunc = null; - this._connectedTransformNode = null; - } - } - _onRegisterAfterWorldMatrixUpdate(node) { - var _a; - if (!node.getBoundingInfo) { - this.setPosition(node.absolutePosition); - } - else { - const mesh = node; - const boundingInfo = mesh.getBoundingInfo(); - this.setPosition(boundingInfo.boundingSphere.centerWorld); - } - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._isDirectional && this.isPlaying) { - this._updateDirection(); - } - } - /** - * Clone the current sound in the scene. - * @returns the new sound clone - */ - clone() { - if (!this._streaming) { - const setBufferAndRun = () => { - if (this._isReadyToPlay) { - clonedSound._audioBuffer = this.getAudioBuffer(); - clonedSound._isReadyToPlay = true; - if (clonedSound.autoplay) { - clonedSound.play(0, this._offset, this._length); - } - } - else { - setTimeout(setBufferAndRun, 300); - } - }; - const currentOptions = { - 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, - }; - const clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions); - if (this.useCustomAttenuation) { - clonedSound.setAttenuationFunction(this._customAttenuationFunction); - } - clonedSound.setPosition(this._position); - clonedSound.setPlaybackRate(this._playbackRate); - setBufferAndRun(); - return clonedSound; - } - // Can't clone a streaming sound - else { - return null; - } - } - /** - * Gets the current underlying audio buffer containing the data - * @returns the audio buffer - */ - getAudioBuffer() { - return this._audioBuffer; - } - /** - * Gets the WebAudio AudioBufferSourceNode, lets you keep track of and stop instances of this Sound. - * @returns the source node - */ - getSoundSource() { - return this._soundSource; - } - /** - * Gets the WebAudio GainNode, gives you precise control over the gain of instances of this Sound. - * @returns the gain node - */ - getSoundGain() { - return this._soundGain; - } - /** - * Serializes the Sound in a JSON representation - * @returns the JSON representation of the sound - */ - serialize() { - const serializationObject = { - 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, - }; - if (this._spatialSound) { - if (this._connectedTransformNode) { - serializationObject.connectedMeshId = this._connectedTransformNode.id; - } - serializationObject.position = this._position.asArray(); - serializationObject.refDistance = this.refDistance; - serializationObject.distanceModel = this.distanceModel; - serializationObject.isDirectional = this._isDirectional; - serializationObject.localDirectionToMesh = this._localDirection.asArray(); - serializationObject.coneInnerAngle = this._coneInnerAngle; - serializationObject.coneOuterAngle = this._coneOuterAngle; - serializationObject.coneOuterGain = this._coneOuterGain; - } - return serializationObject; - } - /** - * Parse a JSON representation of a sound to instantiate in a given scene - * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method) - * @param scene Define the scene the new parsed sound should be created in - * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies - * @param sourceSound Define a sound place holder if do not need to instantiate a new one - * @returns the newly parsed sound - */ - static Parse(parsedSound, scene, rootUrl, sourceSound) { - const soundName = parsedSound.name; - let soundUrl; - if (parsedSound.url) { - soundUrl = rootUrl + parsedSound.url; - } - else { - soundUrl = rootUrl + soundName; - } - const options = { - autoplay: parsedSound.autoplay, - loop: parsedSound.loop, - volume: parsedSound.volume, - spatialSound: parsedSound.spatialSound, - maxDistance: parsedSound.maxDistance, - rolloffFactor: parsedSound.rolloffFactor, - refDistance: parsedSound.refDistance, - distanceModel: parsedSound.distanceModel, - playbackRate: parsedSound.playbackRate, - }; - let newSound; - if (!sourceSound) { - newSound = new Sound(soundName, soundUrl, scene, () => { - scene.removePendingData(newSound); - }, options); - scene.addPendingData(newSound); - } - else { - const setBufferAndRun = () => { - if (sourceSound._isReadyToPlay) { - newSound._audioBuffer = sourceSound.getAudioBuffer(); - newSound._isReadyToPlay = true; - if (newSound.autoplay) { - newSound.play(0, newSound._offset, newSound._length); - } - } - else { - setTimeout(setBufferAndRun, 300); - } - }; - newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options); - setBufferAndRun(); - } - if (parsedSound.position) { - const soundPosition = math_vector_Vector3.FromArray(parsedSound.position); - newSound.setPosition(soundPosition); - } - if (parsedSound.isDirectional) { - newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0); - if (parsedSound.localDirectionToMesh) { - const localDirectionToMesh = math_vector_Vector3.FromArray(parsedSound.localDirectionToMesh); - newSound.setLocalDirectionToMesh(localDirectionToMesh); - } - } - if (parsedSound.connectedMeshId) { - const connectedMesh = scene.getMeshById(parsedSound.connectedMeshId); - if (connectedMesh) { - newSound.attachToMesh(connectedMesh); - } - } - if (parsedSound.metadata) { - newSound.metadata = parsedSound.metadata; - } - return newSound; - } - _setOffset(value) { - if (this._offset === value) { - return; - } - if (this.isPaused) { - this.stop(); - this.isPaused = false; - } - this._offset = value; - } - _clearTimeoutsAndObservers() { - var _a; - if (this._tryToPlayTimeout) { - clearTimeout(this._tryToPlayTimeout); - this._tryToPlayTimeout = null; - } - if (this._audioUnlockedObserver) { - (_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.onAudioUnlockedObservable.remove(this._audioUnlockedObserver); - this._audioUnlockedObserver = null; - } - } -} -/** - * @internal - */ -Sound._SceneComponentInitialization = (_) => { - throw _WarnImport("AudioSceneComponent"); -}; -//# sourceMappingURL=sound.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Audio/soundTrack.js - - -/** - * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds. - * It will be also used in a future release to apply effects on a specific track. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-sound-tracks - */ -class SoundTrack { - /** - * Creates a new sound track. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-sound-tracks - * @param scene Define the scene the sound track belongs to - * @param options - */ - constructor(scene, options = {}) { - /** - * The unique identifier of the sound track in the scene. - */ - this.id = -1; - this._isInitialized = false; - scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!scene) { - return; - } - this._scene = scene; - this.soundCollection = new Array(); - this._options = options; - if (!this._options.mainTrack && this._scene.soundTracks) { - this._scene.soundTracks.push(this); - this.id = this._scene.soundTracks.length - 1; - } - } - _initializeSoundTrackAudioGraph() { - var _a; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && engine_Engine.audioEngine.audioContext) { - this._outputAudioNode = engine_Engine.audioEngine.audioContext.createGain(); - this._outputAudioNode.connect(engine_Engine.audioEngine.masterGain); - if (this._options) { - if (this._options.volume) { - this._outputAudioNode.gain.value = this._options.volume; - } - } - this._isInitialized = true; - } - } - /** - * Release the sound track and its associated resources - */ - dispose() { - if (engine_Engine.audioEngine && engine_Engine.audioEngine.canUseWebAudio) { - if (this._connectedAnalyser) { - this._connectedAnalyser.stopDebugCanvas(); - } - while (this.soundCollection.length) { - this.soundCollection[0].dispose(); - } - if (this._outputAudioNode) { - this._outputAudioNode.disconnect(); - } - this._outputAudioNode = null; - } - } - /** - * Adds a sound to this sound track - * @param sound define the sound to add - * @ignoreNaming - */ - addSound(sound) { - var _a; - if (!this._isInitialized) { - this._initializeSoundTrackAudioGraph(); - } - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) { - sound.connectToSoundTrackAudioNode(this._outputAudioNode); - } - if (sound.soundTrackId) { - if (sound.soundTrackId === -1) { - this._scene.mainSoundTrack.removeSound(sound); - } - else if (this._scene.soundTracks) { - this._scene.soundTracks[sound.soundTrackId].removeSound(sound); - } - } - this.soundCollection.push(sound); - sound.soundTrackId = this.id; - } - /** - * Removes a sound to this sound track - * @param sound define the sound to remove - * @ignoreNaming - */ - removeSound(sound) { - const index = this.soundCollection.indexOf(sound); - if (index !== -1) { - this.soundCollection.splice(index, 1); - } - } - /** - * Set a global volume for the full sound track. - * @param newVolume Define the new volume of the sound track - */ - setVolume(newVolume) { - var _a; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) { - this._outputAudioNode.gain.value = newVolume; - } - } - /** - * Switch the panning model to HRTF: - * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound - */ - switchPanningModelToHRTF() { - var _a; - if ((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) { - for (let i = 0; i < this.soundCollection.length; i++) { - this.soundCollection[i].switchPanningModelToHRTF(); - } - } - } - /** - * Switch the panning model to Equal Power: - * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound - */ - switchPanningModelToEqualPower() { - var _a; - if ((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) { - for (let i = 0; i < this.soundCollection.length; i++) { - this.soundCollection[i].switchPanningModelToEqualPower(); - } - } - } - /** - * Connect the sound track to an audio analyser allowing some amazing - * synchronization between the sounds/music and your visualization (VuMeter for instance). - * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-the-analyser - * @param analyser The analyser to connect to the engine - */ - connectToAnalyser(analyser) { - var _a; - if (this._connectedAnalyser) { - this._connectedAnalyser.stopDebugCanvas(); - } - this._connectedAnalyser = analyser; - if (((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) { - this._outputAudioNode.disconnect(); - this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, engine_Engine.audioEngine.masterGain); - } - } -} -//# sourceMappingURL=soundTrack.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Audio/audioSceneComponent.js - - - - - - - - - - -// Adds the parser to the scene parsers. -AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_AUDIO, (parsedData, scene, container, rootUrl) => { - var _a; - // TODO: add sound - let loadedSounds = []; - let loadedSound; - container.sounds = container.sounds || []; - if (parsedData.sounds !== undefined && parsedData.sounds !== null) { - for (let index = 0, cache = parsedData.sounds.length; index < cache; index++) { - const parsedSound = parsedData.sounds[index]; - if ((_a = engine_Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) { - if (!parsedSound.url) { - parsedSound.url = parsedSound.name; - } - if (!loadedSounds[parsedSound.url]) { - loadedSound = Sound.Parse(parsedSound, scene, rootUrl); - loadedSounds[parsedSound.url] = loadedSound; - container.sounds.push(loadedSound); - } - else { - container.sounds.push(Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url])); - } - } - else { - container.sounds.push(new Sound(parsedSound.name, null, scene)); - } - } - } - loadedSounds = []; -}); -Object.defineProperty(scene_Scene.prototype, "mainSoundTrack", { - get: function () { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - if (!this._mainSoundTrack) { - this._mainSoundTrack = new SoundTrack(this, { mainTrack: true }); - } - return this._mainSoundTrack; - }, - enumerable: true, - configurable: true, -}); -scene_Scene.prototype.getSoundByName = function (name) { - let index; - for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) { - if (this.mainSoundTrack.soundCollection[index].name === name) { - return this.mainSoundTrack.soundCollection[index]; - } - } - if (this.soundTracks) { - for (let sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) { - for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) { - if (this.soundTracks[sdIndex].soundCollection[index].name === name) { - return this.soundTracks[sdIndex].soundCollection[index]; - } - } - } - } - return null; -}; -Object.defineProperty(scene_Scene.prototype, "audioEnabled", { - get: function () { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - return compo.audioEnabled; - }, - set: function (value) { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - if (value) { - compo.enableAudio(); - } - else { - compo.disableAudio(); - } - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(scene_Scene.prototype, "headphone", { - get: function () { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - return compo.headphone; - }, - set: function (value) { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - if (value) { - compo.switchAudioModeForHeadphones(); - } - else { - compo.switchAudioModeForNormalSpeakers(); - } - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(scene_Scene.prototype, "audioListenerPositionProvider", { - get: function () { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - return compo.audioListenerPositionProvider; - }, - set: function (value) { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - if (value && typeof value !== "function") { - throw new Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3"); - } - else { - compo.audioListenerPositionProvider = value; - } - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(scene_Scene.prototype, "audioListenerRotationProvider", { - get: function () { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - return compo.audioListenerRotationProvider; - }, - set: function (value) { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - if (value && typeof value !== "function") { - throw new Error("The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3"); - } - else { - compo.audioListenerRotationProvider = value; - } - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(scene_Scene.prototype, "audioPositioningRefreshRate", { - get: function () { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - return compo.audioPositioningRefreshRate; - }, - set: function (value) { - let compo = this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(this); - this._addComponent(compo); - } - compo.audioPositioningRefreshRate = value; - }, - enumerable: true, - configurable: true, -}); -/** - * Defines the sound scene component responsible to manage any sounds - * in a given scene. - */ -class AudioSceneComponent { - /** - * Gets whether audio is enabled or not. - * Please use related enable/disable method to switch state. - */ - get audioEnabled() { - return this._audioEnabled; - } - /** - * Gets whether audio is outputting to headphone or not. - * Please use the according Switch methods to change output. - */ - get headphone() { - return this._headphone; - } - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_AUDIO; - this._audioEnabled = true; - this._headphone = false; - /** - * Gets or sets a refresh rate when using 3D audio positioning - */ - this.audioPositioningRefreshRate = 500; - /** - * Gets or Sets a custom listener position for all sounds in the scene - * By default, this is the position of the first active camera - */ - this.audioListenerPositionProvider = null; - /** - * Gets or Sets a custom listener rotation for all sounds in the scene - * By default, this is the rotation of the first active camera - */ - this.audioListenerRotationProvider = null; - this._cachedCameraDirection = new math_vector_Vector3(); - this._cachedCameraPosition = new math_vector_Vector3(); - this._lastCheck = 0; - this._invertMatrixTemp = new math_vector_Matrix(); - this._cameraDirectionTemp = new math_vector_Vector3(); - scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!scene) { - return; - } - this.scene = scene; - scene.soundTracks = new Array(); - scene.sounds = new Array(); - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._afterRenderStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing to do here. (Not rendering related) - } - /** - * Serializes the component data to the specified json object - * @param serializationObject The object to serialize to - */ - serialize(serializationObject) { - serializationObject.sounds = []; - if (this.scene.soundTracks) { - for (let index = 0; index < this.scene.soundTracks.length; index++) { - const soundtrack = this.scene.soundTracks[index]; - for (let soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) { - serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize()); - } - } - } - } - /** - * Adds all the elements from the container to the scene - * @param container the container holding the elements - */ - addFromContainer(container) { - if (!container.sounds) { - return; - } - container.sounds.forEach((sound) => { - sound.play(); - sound.autoplay = true; - this.scene.mainSoundTrack.addSound(sound); - }); - } - /** - * Removes all the elements in the container from the scene - * @param container contains the elements to remove - * @param dispose if the removed element should be disposed (default: false) - */ - removeFromContainer(container, dispose = false) { - if (!container.sounds) { - return; - } - container.sounds.forEach((sound) => { - sound.stop(); - sound.autoplay = false; - this.scene.mainSoundTrack.removeSound(sound); - if (dispose) { - sound.dispose(); - } - }); - } - /** - * Disposes the component and the associated resources. - */ - dispose() { - const scene = this.scene; - if (scene._mainSoundTrack) { - scene.mainSoundTrack.dispose(); - } - if (scene.soundTracks) { - for (let scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) { - scene.soundTracks[scIndex].dispose(); - } - } - } - /** - * Disables audio in the associated scene. - */ - disableAudio() { - const scene = this.scene; - this._audioEnabled = false; - if (engine_Engine.audioEngine && engine_Engine.audioEngine.audioContext) { - engine_Engine.audioEngine.audioContext.suspend(); - } - let i; - for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { - scene.mainSoundTrack.soundCollection[i].pause(); - } - if (scene.soundTracks) { - for (i = 0; i < scene.soundTracks.length; i++) { - for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { - scene.soundTracks[i].soundCollection[j].pause(); - } - } - } - } - /** - * Enables audio in the associated scene. - */ - enableAudio() { - const scene = this.scene; - this._audioEnabled = true; - if (engine_Engine.audioEngine && engine_Engine.audioEngine.audioContext) { - engine_Engine.audioEngine.audioContext.resume(); - } - let i; - for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { - if (scene.mainSoundTrack.soundCollection[i].isPaused) { - scene.mainSoundTrack.soundCollection[i].play(); - } - } - if (scene.soundTracks) { - for (i = 0; i < scene.soundTracks.length; i++) { - for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { - if (scene.soundTracks[i].soundCollection[j].isPaused) { - scene.soundTracks[i].soundCollection[j].play(); - } - } - } - } - } - /** - * Switch audio to headphone output. - */ - switchAudioModeForHeadphones() { - const scene = this.scene; - this._headphone = true; - scene.mainSoundTrack.switchPanningModelToHRTF(); - if (scene.soundTracks) { - for (let i = 0; i < scene.soundTracks.length; i++) { - scene.soundTracks[i].switchPanningModelToHRTF(); - } - } - } - /** - * Switch audio to normal speakers. - */ - switchAudioModeForNormalSpeakers() { - const scene = this.scene; - this._headphone = false; - scene.mainSoundTrack.switchPanningModelToEqualPower(); - if (scene.soundTracks) { - for (let i = 0; i < scene.soundTracks.length; i++) { - scene.soundTracks[i].switchPanningModelToEqualPower(); - } - } - } - _afterRender() { - const now = precisionDate_PrecisionDate.Now; - if (this._lastCheck && now - this._lastCheck < this.audioPositioningRefreshRate) { - return; - } - this._lastCheck = now; - const scene = this.scene; - if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) { - return; - } - const audioEngine = engine_Engine.audioEngine; - if (!audioEngine) { - return; - } - if (audioEngine.audioContext) { - let listeningCamera = scene.activeCamera; - if (scene.activeCameras && scene.activeCameras.length > 0) { - listeningCamera = scene.activeCameras[0]; - } - // A custom listener position provider was set - // Use the users provided position instead of camera's - if (this.audioListenerPositionProvider) { - const position = this.audioListenerPositionProvider(); - // Set the listener position - audioEngine.audioContext.listener.setPosition(position.x || 0, position.y || 0, position.z || 0); - // Check if there is a listening camera - } - else if (listeningCamera) { - // Set the listener position to the listening camera global position - if (!this._cachedCameraPosition.equals(listeningCamera.globalPosition)) { - this._cachedCameraPosition.copyFrom(listeningCamera.globalPosition); - audioEngine.audioContext.listener.setPosition(listeningCamera.globalPosition.x, listeningCamera.globalPosition.y, listeningCamera.globalPosition.z); - } - } - // Otherwise set the listener position to 0, 0 ,0 - else { - // Set the listener position - audioEngine.audioContext.listener.setPosition(0, 0, 0); - } - // A custom listener rotation provider was set - // Use the users provided rotation instead of camera's - if (this.audioListenerRotationProvider) { - const rotation = this.audioListenerRotationProvider(); - audioEngine.audioContext.listener.setOrientation(rotation.x || 0, rotation.y || 0, rotation.z || 0, 0, 1, 0); - // Check if there is a listening camera - } - else if (listeningCamera) { - // for VR cameras - if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) { - listeningCamera = listeningCamera.rigCameras[0]; - } - listeningCamera.getViewMatrix().invertToRef(this._invertMatrixTemp); - math_vector_Vector3.TransformNormalToRef(AudioSceneComponent._CameraDirection, this._invertMatrixTemp, this._cameraDirectionTemp); - this._cameraDirectionTemp.normalize(); - // To avoid some errors on GearVR - if (!isNaN(this._cameraDirectionTemp.x) && !isNaN(this._cameraDirectionTemp.y) && !isNaN(this._cameraDirectionTemp.z)) { - if (!this._cachedCameraDirection.equals(this._cameraDirectionTemp)) { - this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp); - audioEngine.audioContext.listener.setOrientation(this._cameraDirectionTemp.x, this._cameraDirectionTemp.y, this._cameraDirectionTemp.z, 0, 1, 0); - } - } - } - // Otherwise set the listener rotation to 0, 0 ,0 - else { - // Set the listener position - audioEngine.audioContext.listener.setOrientation(0, 0, 0, 0, 1, 0); - } - let i; - for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { - const sound = scene.mainSoundTrack.soundCollection[i]; - if (sound.useCustomAttenuation) { - sound.updateDistanceFromListener(); - } - } - if (scene.soundTracks) { - for (i = 0; i < scene.soundTracks.length; i++) { - for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { - const sound = scene.soundTracks[i].soundCollection[j]; - if (sound.useCustomAttenuation) { - sound.updateDistanceFromListener(); - } - } - } - } - } - } -} -AudioSceneComponent._CameraDirection = new math_vector_Vector3(0, 0, -1); -Sound._SceneComponentInitialization = (scene) => { - let compo = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO); - if (!compo) { - compo = new AudioSceneComponent(scene); - scene._addComponent(compo); - } -}; -//# sourceMappingURL=audioSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Audio/weightedsound.js - -/** - * Wraps one or more Sound objects and selects one with random weight for playback. - */ -class WeightedSound { - /** - * Creates a new WeightedSound from the list of sounds given. - * @param loop When true a Sound will be selected and played when the current playing Sound completes. - * @param sounds Array of Sounds that will be selected from. - * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1 - */ - constructor(loop, sounds, weights) { - /** When true a Sound will be selected and played when the current playing Sound completes. */ - this.loop = false; - this._coneInnerAngle = 360; - this._coneOuterAngle = 360; - this._volume = 1; - /** A Sound is currently playing. */ - this.isPlaying = false; - /** A Sound is currently paused. */ - this.isPaused = false; - this._sounds = []; - this._weights = []; - if (sounds.length !== weights.length) { - throw new Error("Sounds length does not equal weights length"); - } - this.loop = loop; - this._weights = weights; - // Normalize the weights - let weightSum = 0; - for (const weight of weights) { - weightSum += weight; - } - const invWeightSum = weightSum > 0 ? 1 / weightSum : 0; - for (let i = 0; i < this._weights.length; i++) { - this._weights[i] *= invWeightSum; - } - this._sounds = sounds; - for (const sound of this._sounds) { - sound.onEndedObservable.add(() => { - this._onended(); - }); - } - } - /** - * The size of cone in degrees for a directional sound in which there will be no attenuation. - */ - get directionalConeInnerAngle() { - return this._coneInnerAngle; - } - /** - * The size of cone in degrees for a directional sound in which there will be no attenuation. - */ - set directionalConeInnerAngle(value) { - if (value !== this._coneInnerAngle) { - if (this._coneOuterAngle < value) { - Logger.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle."); - return; - } - this._coneInnerAngle = value; - for (const sound of this._sounds) { - sound.directionalConeInnerAngle = value; - } - } - } - /** - * Size of cone in degrees for a directional sound outside of which there will be no sound. - * Listener angles between innerAngle and outerAngle will falloff linearly. - */ - get directionalConeOuterAngle() { - return this._coneOuterAngle; - } - /** - * Size of cone in degrees for a directional sound outside of which there will be no sound. - * Listener angles between innerAngle and outerAngle will falloff linearly. - */ - set directionalConeOuterAngle(value) { - if (value !== this._coneOuterAngle) { - if (value < this._coneInnerAngle) { - Logger.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle."); - return; - } - this._coneOuterAngle = value; - for (const sound of this._sounds) { - sound.directionalConeOuterAngle = value; - } - } - } - /** - * Playback volume. - */ - get volume() { - return this._volume; - } - /** - * Playback volume. - */ - set volume(value) { - if (value !== this._volume) { - for (const sound of this._sounds) { - sound.setVolume(value); - } - } - } - _onended() { - if (this._currentIndex !== undefined) { - this._sounds[this._currentIndex].autoplay = false; - } - if (this.loop && this.isPlaying) { - this.play(); - } - else { - this.isPlaying = false; - } - } - /** - * Suspend playback - */ - pause() { - this.isPaused = true; - if (this._currentIndex !== undefined) { - this._sounds[this._currentIndex].pause(); - } - } - /** - * Stop playback - */ - stop() { - this.isPlaying = false; - if (this._currentIndex !== undefined) { - this._sounds[this._currentIndex].stop(); - } - } - /** - * Start playback. - * @param startOffset Position the clip head at a specific time in seconds. - */ - play(startOffset) { - if (!this.isPaused) { - this.stop(); - const randomValue = Math.random(); - let total = 0; - for (let i = 0; i < this._weights.length; i++) { - total += this._weights[i]; - if (randomValue <= total) { - this._currentIndex = i; - break; - } - } - } - const sound = this._sounds[this._currentIndex]; - if (sound.isReady()) { - sound.play(0, this.isPaused ? undefined : startOffset); - } - else { - sound.autoplay = true; - } - this.isPlaying = true; - this.isPaused = false; - } -} -//# sourceMappingURL=weightedsound.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Audio/index.js - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/BakedVertexAnimation/bakedVertexAnimationManager.js - - - - -/** - * This class is used to animate meshes using a baked vertex animation texture - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/baked_texture_animations - * @since 5.0 - */ -class BakedVertexAnimationManager { - /** - * Creates a new BakedVertexAnimationManager - * @param scene defines the current scene - */ - constructor(scene) { - this._texture = null; - this._isEnabled = true; - /** - * Enable or disable the vertex animation manager - */ - this.isEnabled = true; - /** - * The time counter, to pick the correct animation frame. - */ - this.time = 0; - scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!scene) { - return; - } - this._scene = scene; - this.animationParameters = new math_vector_Vector4(0, 0, 0, 30); - } - /** @internal */ - _markSubMeshesAsAttributesDirty() { - for (const mesh of this._scene.meshes) { - if (mesh.bakedVertexAnimationManager === this) { - mesh._markSubMeshesAsAttributesDirty(); - } - } - } - /** - * Binds to the effect. - * @param effect The effect to bind to. - * @param useInstances True when it's an instance. - */ - bind(effect, useInstances = false) { - if (!this._texture || !this._isEnabled) { - return; - } - const size = this._texture.getSize(); - effect.setFloat2("bakedVertexAnimationTextureSizeInverted", 1.0 / size.width, 1.0 / size.height); - effect.setFloat("bakedVertexAnimationTime", this.time); - if (!useInstances) { - effect.setVector4("bakedVertexAnimationSettings", this.animationParameters); - } - effect.setTexture("bakedVertexAnimationTexture", this._texture); - } - /** - * Clone the current manager - * @returns a new BakedVertexAnimationManager - */ - clone() { - const copy = new BakedVertexAnimationManager(this._scene); - this.copyTo(copy); - return copy; - } - /** - * Sets animation parameters. - * @param startFrame The first frame of the animation. - * @param endFrame The last frame of the animation. - * @param offset The offset when starting the animation. - * @param speedFramesPerSecond The frame rate. - */ - setAnimationParameters(startFrame, endFrame, offset = 0, speedFramesPerSecond = 30) { - this.animationParameters = new math_vector_Vector4(startFrame, endFrame, offset, speedFramesPerSecond); - } - /** - * Disposes the resources of the manager. - * @param forceDisposeTextures - Forces the disposal of all textures. - */ - dispose(forceDisposeTextures) { - var _a; - if (forceDisposeTextures) { - (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose(); - } - } - /** - * Get the current class name useful for serialization or dynamic coding. - * @returns "BakedVertexAnimationManager" - */ - getClassName() { - return "BakedVertexAnimationManager"; - } - /** - * Makes a duplicate of the current instance into another one. - * @param vatMap define the instance where to copy the info - */ - copyTo(vatMap) { - decorators_SerializationHelper.Clone(() => vatMap, this); - } - /** - * Serializes this vertex animation instance - * @returns - An object with the serialized instance. - */ - serialize() { - return decorators_SerializationHelper.Serialize(this); - } - /** - * Parses a vertex animation setting from a serialized object. - * @param source - Serialized object. - * @param scene Defines the scene we are parsing for - * @param rootUrl Defines the rootUrl to load from - */ - parse(source, scene, rootUrl) { - decorators_SerializationHelper.Parse(() => this, source, scene, rootUrl); - } -} -__decorate([ - serializeAsTexture(), - expandToProperty("_markSubMeshesAsAttributesDirty") -], BakedVertexAnimationManager.prototype, "texture", void 0); -__decorate([ - serialize(), - expandToProperty("_markSubMeshesAsAttributesDirty") -], BakedVertexAnimationManager.prototype, "isEnabled", void 0); -__decorate([ - serialize() -], BakedVertexAnimationManager.prototype, "animationParameters", void 0); -__decorate([ - serialize() -], BakedVertexAnimationManager.prototype, "time", void 0); -//# sourceMappingURL=bakedVertexAnimationManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/thinTexture.js - - -/** - * Base class of all the textures in babylon. - * It groups all the common properties required to work with Thin Engine. - */ -class thinTexture_ThinTexture { - /** - * | Value | Type | Description | - * | ----- | ------------------ | ----------- | - * | 0 | CLAMP_ADDRESSMODE | | - * | 1 | WRAP_ADDRESSMODE | | - * | 2 | MIRROR_ADDRESSMODE | | - */ - get wrapU() { - return this._wrapU; - } - set wrapU(value) { - this._wrapU = value; - } - /** - * | Value | Type | Description | - * | ----- | ------------------ | ----------- | - * | 0 | CLAMP_ADDRESSMODE | | - * | 1 | WRAP_ADDRESSMODE | | - * | 2 | MIRROR_ADDRESSMODE | | - */ - get wrapV() { - return this._wrapV; - } - set wrapV(value) { - this._wrapV = value; - } - /** - * How a texture is mapped. - * Unused in thin texture mode. - */ - get coordinatesMode() { - return 0; - } - /** - * Define if the texture is a cube texture or if false a 2d texture. - */ - get isCube() { - if (!this._texture) { - return false; - } - return this._texture.isCube; - } - set isCube(value) { - if (!this._texture) { - return; - } - this._texture.isCube = value; - } - /** - * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture. - */ - get is3D() { - if (!this._texture) { - return false; - } - return this._texture.is3D; - } - set is3D(value) { - if (!this._texture) { - return; - } - this._texture.is3D = value; - } - /** - * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture. - */ - get is2DArray() { - if (!this._texture) { - return false; - } - return this._texture.is2DArray; - } - set is2DArray(value) { - if (!this._texture) { - return; - } - this._texture.is2DArray = value; - } - /** - * Get the class name of the texture. - * @returns "ThinTexture" - */ - getClassName() { - return "ThinTexture"; - } - static _IsRenderTargetWrapper(texture) { - return (texture === null || texture === void 0 ? void 0 : texture._shareDepth) !== undefined; - } - /** - * Instantiates a new ThinTexture. - * Base class of all the textures in babylon. - * This can be used as an internal texture wrapper in ThinEngine to benefit from the cache - * @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 - */ - constructor(internalTexture) { - this._wrapU = 1; - this._wrapV = 1; - /** - * | Value | Type | Description | - * | ----- | ------------------ | ----------- | - * | 0 | CLAMP_ADDRESSMODE | | - * | 1 | WRAP_ADDRESSMODE | | - * | 2 | MIRROR_ADDRESSMODE | | - */ - this.wrapR = 1; - /** - * With compliant hardware and browser (supporting anisotropic filtering) - * this defines the level of anisotropic filtering in the texture. - * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff. - */ - this.anisotropicFilteringLevel = 4; - /** - * Define the current state of the loading sequence when in delayed load mode. - */ - this.delayLoadState = 0; - /** @internal */ - this._texture = null; - this._engine = null; - this._cachedSize = Size.Zero(); - this._cachedBaseSize = Size.Zero(); - /** @internal */ - this._initialSamplingMode = 2; - this._texture = thinTexture_ThinTexture._IsRenderTargetWrapper(internalTexture) ? internalTexture.texture : internalTexture; - if (this._texture) { - this._engine = this._texture.getEngine(); - } - } - /** - * Get if the texture is ready to be used (downloaded, converted, mip mapped...). - * @returns true if fully ready - */ - isReady() { - if (this.delayLoadState === 4) { - this.delayLoad(); - return false; - } - if (this._texture) { - return this._texture.isReady; - } - return false; - } - /** - * Triggers the load sequence in delayed load mode. - */ - delayLoad() { } - /** - * Get the underlying lower level texture from Babylon. - * @returns the internal texture - */ - getInternalTexture() { - return this._texture; - } - /** - * Get the size of the texture. - * @returns the texture size. - */ - getSize() { - if (this._texture) { - if (this._texture.width) { - this._cachedSize.width = this._texture.width; - this._cachedSize.height = this._texture.height; - return this._cachedSize; - } - if (this._texture._size) { - this._cachedSize.width = this._texture._size; - this._cachedSize.height = this._texture._size; - return this._cachedSize; - } - } - return this._cachedSize; - } - /** - * Get the base size of the texture. - * It can be different from the size if the texture has been resized for POT for instance - * @returns the base size - */ - getBaseSize() { - if (!this.isReady() || !this._texture) { - this._cachedBaseSize.width = 0; - this._cachedBaseSize.height = 0; - return this._cachedBaseSize; - } - if (this._texture._size) { - this._cachedBaseSize.width = this._texture._size; - this._cachedBaseSize.height = this._texture._size; - return this._cachedBaseSize; - } - this._cachedBaseSize.width = this._texture.baseWidth; - this._cachedBaseSize.height = this._texture.baseHeight; - return this._cachedBaseSize; - } - /** - * Get the current sampling mode associated with the texture. - */ - get samplingMode() { - if (!this._texture) { - return this._initialSamplingMode; - } - return this._texture.samplingMode; - } - /** - * Update the sampling mode of the texture. - * Default is Trilinear mode. - * - * | Value | Type | Description | - * | ----- | ------------------ | ----------- | - * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear | - * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest | - * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear | - * | 4 | NEAREST_NEAREST_MIPNEAREST | | - * | 5 | NEAREST_LINEAR_MIPNEAREST | | - * | 6 | NEAREST_LINEAR_MIPLINEAR | | - * | 7 | NEAREST_LINEAR | | - * | 8 | NEAREST_NEAREST | | - * | 9 | LINEAR_NEAREST_MIPNEAREST | | - * | 10 | LINEAR_NEAREST_MIPLINEAR | | - * | 11 | LINEAR_LINEAR | | - * | 12 | LINEAR_NEAREST | | - * - * > _mag_: magnification filter (close to the viewer) - * > _min_: minification filter (far from the viewer) - * > _mip_: filter used between mip map levels - *@param samplingMode Define the new sampling mode of the texture - */ - updateSamplingMode(samplingMode) { - if (this._texture && this._engine) { - this._engine.updateTextureSamplingMode(samplingMode, this._texture); - } - } - /** - * Release and destroy the underlying lower level texture aka internalTexture. - */ - releaseInternalTexture() { - if (this._texture) { - this._texture.dispose(); - this._texture = null; - } - } - /** - * Dispose the texture and release its associated resources. - */ - dispose() { - if (this._texture) { - this.releaseInternalTexture(); - this._engine = null; - } - } -} -//# sourceMappingURL=thinTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/baseTexture.js - - - - - - - - - -/** - * Base class of all the textures in babylon. - * It groups all the common properties the materials, post process, lights... might need - * in order to make a correct use of the texture. - */ -class baseTexture_BaseTexture extends thinTexture_ThinTexture { - /** - * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance). - */ - set hasAlpha(value) { - if (this._hasAlpha === value) { - return; - } - this._hasAlpha = value; - if (this._scene) { - this._scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this); - }); - } - } - get hasAlpha() { - return this._hasAlpha; - } - /** - * Defines if the alpha value should be determined via the rgb values. - * If true the luminance of the pixel might be used to find the corresponding alpha value. - */ - set getAlphaFromRGB(value) { - if (this._getAlphaFromRGB === value) { - return; - } - this._getAlphaFromRGB = value; - if (this._scene) { - this._scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this); - }); - } - } - get getAlphaFromRGB() { - return this._getAlphaFromRGB; - } - /** - * Define the UV channel to use starting from 0 and defaulting to 0. - * This is part of the texture as textures usually maps to one uv set. - */ - set coordinatesIndex(value) { - if (this._coordinatesIndex === value) { - return; - } - this._coordinatesIndex = value; - if (this._scene) { - this._scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this); - }); - } - } - get coordinatesIndex() { - return this._coordinatesIndex; - } - /** - * How a texture is mapped. - * - * | Value | Type | Description | - * | ----- | ----------------------------------- | ----------- | - * | 0 | EXPLICIT_MODE | | - * | 1 | SPHERICAL_MODE | | - * | 2 | PLANAR_MODE | | - * | 3 | CUBIC_MODE | | - * | 4 | PROJECTION_MODE | | - * | 5 | SKYBOX_MODE | | - * | 6 | INVCUBIC_MODE | | - * | 7 | EQUIRECTANGULAR_MODE | | - * | 8 | FIXED_EQUIRECTANGULAR_MODE | | - * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | | - */ - set coordinatesMode(value) { - if (this._coordinatesMode === value) { - return; - } - this._coordinatesMode = value; - if (this._scene) { - this._scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this); - }); - } - } - get coordinatesMode() { - return this._coordinatesMode; - } - /** - * | Value | Type | Description | - * | ----- | ------------------ | ----------- | - * | 0 | CLAMP_ADDRESSMODE | | - * | 1 | WRAP_ADDRESSMODE | | - * | 2 | MIRROR_ADDRESSMODE | | - */ - get wrapU() { - return this._wrapU; - } - set wrapU(value) { - this._wrapU = value; - } - /** - * | Value | Type | Description | - * | ----- | ------------------ | ----------- | - * | 0 | CLAMP_ADDRESSMODE | | - * | 1 | WRAP_ADDRESSMODE | | - * | 2 | MIRROR_ADDRESSMODE | | - */ - get wrapV() { - return this._wrapV; - } - set wrapV(value) { - this._wrapV = value; - } - /** - * Define if the texture is a cube texture or if false a 2d texture. - */ - get isCube() { - if (!this._texture) { - return this._isCube; - } - return this._texture.isCube; - } - set isCube(value) { - if (!this._texture) { - this._isCube = value; - } - else { - this._texture.isCube = value; - } - } - /** - * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture. - */ - get is3D() { - if (!this._texture) { - return false; - } - return this._texture.is3D; - } - set is3D(value) { - if (!this._texture) { - return; - } - this._texture.is3D = value; - } - /** - * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture. - */ - get is2DArray() { - if (!this._texture) { - return false; - } - return this._texture.is2DArray; - } - set is2DArray(value) { - if (!this._texture) { - return; - } - this._texture.is2DArray = value; - } - /** - * Define if the texture contains data in gamma space (most of the png/jpg aside bump). - * HDR texture are usually stored in linear space. - * This only impacts the PBR and Background materials - */ - get gammaSpace() { - if (!this._texture) { - return this._gammaSpace; - } - else { - if (this._texture._gammaSpace === null) { - this._texture._gammaSpace = this._gammaSpace; - } - } - return this._texture._gammaSpace && !this._texture._useSRGBBuffer; - } - set gammaSpace(gamma) { - if (!this._texture) { - if (this._gammaSpace === gamma) { - return; - } - this._gammaSpace = gamma; - } - else { - if (this._texture._gammaSpace === gamma) { - return; - } - this._texture._gammaSpace = gamma; - } - this._markAllSubMeshesAsTexturesDirty(); - } - /** - * Gets or sets whether or not the texture contains RGBD data. - */ - get isRGBD() { - return this._texture != null && this._texture._isRGBD; - } - set isRGBD(value) { - if (this._texture) { - this._texture._isRGBD = value; - } - } - /** - * Are mip maps generated for this texture or not. - */ - get noMipmap() { - return false; - } - /** - * With prefiltered texture, defined the offset used during the prefiltering steps. - */ - get lodGenerationOffset() { - if (this._texture) { - return this._texture._lodGenerationOffset; - } - return 0.0; - } - set lodGenerationOffset(value) { - if (this._texture) { - this._texture._lodGenerationOffset = value; - } - } - /** - * With prefiltered texture, defined the scale used during the prefiltering steps. - */ - get lodGenerationScale() { - if (this._texture) { - return this._texture._lodGenerationScale; - } - return 0.0; - } - set lodGenerationScale(value) { - if (this._texture) { - this._texture._lodGenerationScale = value; - } - } - /** - * With prefiltered texture, defined if the specular generation is based on a linear ramp. - * By default we are using a log2 of the linear roughness helping to keep a better resolution for - * average roughness values. - */ - get linearSpecularLOD() { - if (this._texture) { - return this._texture._linearSpecularLOD; - } - return false; - } - set linearSpecularLOD(value) { - if (this._texture) { - this._texture._linearSpecularLOD = value; - } - } - /** - * In case a better definition than spherical harmonics is required for the diffuse part of the environment. - * You can set the irradiance texture to rely on a texture instead of the spherical approach. - * This texture need to have the same characteristics than its parent (Cube vs 2d, coordinates mode, Gamma/Linear, RGBD). - */ - get irradianceTexture() { - if (this._texture) { - return this._texture._irradianceTexture; - } - return null; - } - set irradianceTexture(value) { - if (this._texture) { - this._texture._irradianceTexture = value; - } - } - /** - * Define the unique id of the texture in the scene. - */ - get uid() { - if (!this._uid) { - this._uid = guid_RandomGUID(); - } - return this._uid; - } - /** - * Return a string representation of the texture. - * @returns the texture as a string - */ - toString() { - return this.name; - } - /** - * Get the class name of the texture. - * @returns "BaseTexture" - */ - getClassName() { - return "BaseTexture"; - } - /** - * Callback triggered when the texture has been disposed. - * Kept for back compatibility, you can use the onDisposeObservable instead. - */ - set onDispose(callback) { - if (this._onDisposeObserver) { - this.onDisposeObservable.remove(this._onDisposeObserver); - } - this._onDisposeObserver = this.onDisposeObservable.add(callback); - } - /** - * Define if the texture is preventing a material to render or not. - * If not and the texture is not ready, the engine will use a default black texture instead. - */ - get isBlocking() { - return true; - } - /** - * Was there any loading error? - */ - get loadingError() { - return this._loadingError; - } - /** - * If a loading error occurred this object will be populated with information about the error. - */ - get errorObject() { - return this._errorObject; - } - /** - * Instantiates a new BaseTexture. - * Base class of all the textures in babylon. - * It groups all the common properties the materials, post process, lights... might need - * in order to make a correct use of the texture. - * @param sceneOrEngine Define the scene or engine the texture belongs to - * @param internalTexture Define the internal texture associated with the texture - */ - constructor(sceneOrEngine, internalTexture = null) { - super(null); - /** - * Gets or sets an object used to store user defined information. - */ - this.metadata = null; - /** - * For internal use only. Please do not use. - */ - this.reservedDataStore = null; - this._hasAlpha = false; - this._getAlphaFromRGB = false; - /** - * Intensity or strength of the texture. - * It is commonly used by materials to fine tune the intensity of the texture - */ - this.level = 1; - this._coordinatesIndex = 0; - /** - * Gets or sets a boolean indicating that the texture should try to reduce shader code if there is no UV manipulation. - * (ie. when texture.getTextureMatrix().isIdentityAs3x2() returns true) - */ - this.optimizeUVAllocation = true; - this._coordinatesMode = 0; - /** - * | Value | Type | Description | - * | ----- | ------------------ | ----------- | - * | 0 | CLAMP_ADDRESSMODE | | - * | 1 | WRAP_ADDRESSMODE | | - * | 2 | MIRROR_ADDRESSMODE | | - */ - this.wrapR = 1; - /** - * With compliant hardware and browser (supporting anisotropic filtering) - * this defines the level of anisotropic filtering in the texture. - * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff. - */ - this.anisotropicFilteringLevel = baseTexture_BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL; - /** @internal */ - this._isCube = false; - this._gammaSpace = true; - /** - * Is Z inverted in the texture (useful in a cube texture). - */ - this.invertZ = false; - /** - * @internal - */ - this.lodLevelInAlpha = false; - /** - * Define if the texture is a render target. - */ - this.isRenderTarget = false; - /** @internal */ - this._prefiltered = false; - /** @internal */ - this._forceSerialize = false; - /** - * Define the list of animation attached to the texture. - */ - this.animations = new Array(); - /** - * An event triggered when the texture is disposed. - */ - this.onDisposeObservable = new observable_Observable(); - this._onDisposeObserver = null; - this._scene = null; - /** @internal */ - this._uid = null; - /** @internal */ - this._parentContainer = null; - this._loadingError = false; - if (sceneOrEngine) { - if (baseTexture_BaseTexture._IsScene(sceneOrEngine)) { - this._scene = sceneOrEngine; - } - else { - this._engine = sceneOrEngine; - } - } - else { - this._scene = engineStore_EngineStore.LastCreatedScene; - } - if (this._scene) { - this.uniqueId = this._scene.getUniqueId(); - this._scene.addTexture(this); - this._engine = this._scene.getEngine(); - } - this._texture = internalTexture; - this._uid = null; - } - /** - * Get the scene the texture belongs to. - * @returns the scene or null if undefined - */ - getScene() { - return this._scene; - } - /** @internal */ - _getEngine() { - return this._engine; - } - /** - * Checks if the texture has the same transform matrix than another texture - * @param texture texture to check against - * @returns true if the transforms are the same, else false - */ - checkTransformsAreIdentical(texture) { - return texture !== null; - } - /** - * Get the texture transform matrix used to offset tile the texture for instance. - * @returns the transformation matrix - */ - getTextureMatrix() { - return math_vector_Matrix.IdentityReadOnly; - } - /** - * Get the texture reflection matrix used to rotate/transform the reflection. - * @returns the reflection matrix - */ - getReflectionTextureMatrix() { - return math_vector_Matrix.IdentityReadOnly; - } - /** - * Gets a suitable rotate/transform matrix when the texture is used for refraction. - * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode. - * @returns The refraction matrix - */ - getRefractionTextureMatrix() { - return this.getReflectionTextureMatrix(); - } - /** - * Get if the texture is ready to be consumed (either it is ready or it is not blocking) - * @returns true if ready, not blocking or if there was an error loading the texture - */ - isReadyOrNotBlocking() { - return !this.isBlocking || this.isReady() || this.loadingError; - } - /** - * Scales the texture if is `canRescale()` - * @param ratio the resize factor we want to use to rescale - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - scale(ratio) { } - /** - * Get if the texture can rescale. - */ - get canRescale() { - return false; - } - /** - * @internal - */ - _getFromCache(url, noMipmap, sampling, invertY, useSRGBBuffer, isCube) { - const engine = this._getEngine(); - if (!engine) { - return null; - } - const correctedUseSRGBBuffer = engine._getUseSRGBBuffer(!!useSRGBBuffer, noMipmap); - const texturesCache = engine.getLoadedTexturesCache(); - for (let index = 0; index < texturesCache.length; index++) { - const texturesCacheEntry = texturesCache[index]; - if (useSRGBBuffer === undefined || correctedUseSRGBBuffer === texturesCacheEntry._useSRGBBuffer) { - if (invertY === undefined || invertY === texturesCacheEntry.invertY) { - if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) { - if (!sampling || sampling === texturesCacheEntry.samplingMode) { - if (isCube === undefined || isCube === texturesCacheEntry.isCube) { - texturesCacheEntry.incrementReferences(); - return texturesCacheEntry; - } - } - } - } - } - } - return null; - } - /** @internal */ - _rebuild() { } - /** - * Clones the texture. - * @returns the cloned texture - */ - clone() { - return null; - } - /** - * Get the texture underlying type (INT, FLOAT...) - */ - get textureType() { - if (!this._texture) { - return 0; - } - return this._texture.type !== undefined ? this._texture.type : 0; - } - /** - * Get the texture underlying format (RGB, RGBA...) - */ - get textureFormat() { - if (!this._texture) { - return 5; - } - return this._texture.format !== undefined ? this._texture.format : 5; - } - /** - * Indicates that textures need to be re-calculated for all materials - */ - _markAllSubMeshesAsTexturesDirty() { - const scene = this.getScene(); - if (!scene) { - return; - } - scene.markAllMaterialsAsDirty(1); - } - /** - * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer. - * This will returns an RGBA array buffer containing either in values (0-255) or - * float values (0-1) depending of the underlying buffer type. - * @param faceIndex defines the face of the texture to read (in case of cube texture) - * @param level defines the LOD level of the texture to read (in case of Mip Maps) - * @param buffer defines a user defined buffer to fill with data (can be null) - * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels - * @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 - * @param x defines the region x coordinates to start reading from (default to 0) - * @param y defines the region y coordinates to start reading from (default to 0) - * @param width defines the region width to read from (default to the texture size at level) - * @param height defines the region width to read from (default to the texture size at level) - * @returns The Array buffer promise containing the pixels data. - */ - readPixels(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0, width = Number.MAX_VALUE, height = Number.MAX_VALUE) { - if (!this._texture) { - return null; - } - const engine = this._getEngine(); - if (!engine) { - return null; - } - const size = this.getSize(); - let maxWidth = size.width; - let maxHeight = size.height; - if (level !== 0) { - maxWidth = maxWidth / Math.pow(2, level); - maxHeight = maxHeight / Math.pow(2, level); - maxWidth = Math.round(maxWidth); - maxHeight = Math.round(maxHeight); - } - width = Math.min(maxWidth, width); - height = Math.min(maxHeight, height); - try { - if (this._texture.isCube) { - return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y); - } - return engine._readTexturePixels(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion, x, y); - } - catch (e) { - return null; - } - } - /** - * @internal - */ - _readPixelsSync(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false) { - if (!this._texture) { - return null; - } - const size = this.getSize(); - let width = size.width; - let height = size.height; - const engine = this._getEngine(); - if (!engine) { - return null; - } - if (level != 0) { - width = width / Math.pow(2, level); - height = height / Math.pow(2, level); - width = Math.round(width); - height = Math.round(height); - } - try { - if (this._texture.isCube) { - return engine._readTexturePixelsSync(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion); - } - return engine._readTexturePixelsSync(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion); - } - catch (e) { - return null; - } - } - /** @internal */ - get _lodTextureHigh() { - if (this._texture) { - return this._texture._lodTextureHigh; - } - return null; - } - /** @internal */ - get _lodTextureMid() { - if (this._texture) { - return this._texture._lodTextureMid; - } - return null; - } - /** @internal */ - get _lodTextureLow() { - if (this._texture) { - return this._texture._lodTextureLow; - } - return null; - } - /** - * Dispose the texture and release its associated resources. - */ - dispose() { - if (this._scene) { - // Animations - if (this._scene.stopAnimation) { - this._scene.stopAnimation(this); - } - // Remove from scene - this._scene.removePendingData(this); - const index = this._scene.textures.indexOf(this); - if (index >= 0) { - this._scene.textures.splice(index, 1); - } - this._scene.onTextureRemovedObservable.notifyObservers(this); - this._scene = null; - if (this._parentContainer) { - const index = this._parentContainer.textures.indexOf(this); - if (index > -1) { - this._parentContainer.textures.splice(index, 1); - } - this._parentContainer = null; - } - } - // Callback - this.onDisposeObservable.notifyObservers(this); - this.onDisposeObservable.clear(); - this.metadata = null; - super.dispose(); - } - /** - * Serialize the texture into a JSON representation that can be parsed later on. - * @param allowEmptyName True to force serialization even if name is empty. Default: false - * @returns the JSON representation of the texture - */ - serialize(allowEmptyName = false) { - if (!this.name && !allowEmptyName) { - return null; - } - const serializationObject = decorators_SerializationHelper.Serialize(this); - // Animations - decorators_SerializationHelper.AppendSerializedAnimations(this, serializationObject); - return serializationObject; - } - /** - * Helper function to be called back once a list of texture contains only ready textures. - * @param textures Define the list of textures to wait for - * @param callback Define the callback triggered once the entire list will be ready - */ - static WhenAllReady(textures, callback) { - let numRemaining = textures.length; - if (numRemaining === 0) { - callback(); - return; - } - for (let i = 0; i < textures.length; i++) { - const texture = textures[i]; - if (texture.isReady()) { - if (--numRemaining === 0) { - callback(); - } - } - else { - const onLoadObservable = texture.onLoadObservable; - if (onLoadObservable) { - onLoadObservable.addOnce(() => { - if (--numRemaining === 0) { - callback(); - } - }); - } - else { - if (--numRemaining === 0) { - callback(); - } - } - } - } - } - static _IsScene(sceneOrEngine) { - return sceneOrEngine.getClassName() === "Scene"; - } -} -/** - * Default anisotropic filtering level for the application. - * It is set to 4 as a good tradeoff between perf and quality. - */ -baseTexture_BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4; -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "uniqueId", void 0); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "name", void 0); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "metadata", void 0); -__decorate([ - serialize("hasAlpha") -], baseTexture_BaseTexture.prototype, "_hasAlpha", void 0); -__decorate([ - serialize("getAlphaFromRGB") -], baseTexture_BaseTexture.prototype, "_getAlphaFromRGB", void 0); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "level", void 0); -__decorate([ - serialize("coordinatesIndex") -], baseTexture_BaseTexture.prototype, "_coordinatesIndex", void 0); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "optimizeUVAllocation", void 0); -__decorate([ - serialize("coordinatesMode") -], baseTexture_BaseTexture.prototype, "_coordinatesMode", void 0); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "wrapU", null); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "wrapV", null); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "wrapR", void 0); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "anisotropicFilteringLevel", void 0); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "isCube", null); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "is3D", null); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "is2DArray", null); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "gammaSpace", null); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "invertZ", void 0); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "lodLevelInAlpha", void 0); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "lodGenerationOffset", null); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "lodGenerationScale", null); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "linearSpecularLOD", null); -__decorate([ - serializeAsTexture() -], baseTexture_BaseTexture.prototype, "irradianceTexture", null); -__decorate([ - serialize() -], baseTexture_BaseTexture.prototype, "isRenderTarget", void 0); -//# sourceMappingURL=baseTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/copyTools.js -/** - * Transform some pixel data to a base64 string - * @param pixels defines the pixel data to transform to base64 - * @param size defines the width and height of the (texture) data - * @param invertY true if the data must be inverted for the Y coordinate during the conversion - * @returns The base64 encoded string or null - */ -function GenerateBase64StringFromPixelData(pixels, size, invertY = false) { - const width = size.width; - const height = size.height; - if (pixels instanceof Float32Array) { - let len = pixels.byteLength / pixels.BYTES_PER_ELEMENT; - const npixels = new Uint8Array(len); - while (--len >= 0) { - let val = pixels[len]; - if (val < 0) { - val = 0; - } - else if (val > 1) { - val = 1; - } - npixels[len] = val * 255; - } - pixels = npixels; - } - const canvas = document.createElement("canvas"); - canvas.width = width; - canvas.height = height; - const ctx = canvas.getContext("2d"); - if (!ctx) { - return null; - } - const imageData = ctx.createImageData(width, height); - const castData = imageData.data; - castData.set(pixels); - ctx.putImageData(imageData, 0, 0); - if (invertY) { - const canvas2 = document.createElement("canvas"); - canvas2.width = width; - canvas2.height = height; - const ctx2 = canvas2.getContext("2d"); - if (!ctx2) { - return null; - } - ctx2.translate(0, height); - ctx2.scale(1, -1); - ctx2.drawImage(canvas, 0, 0); - return canvas2.toDataURL("image/png"); - } - return canvas.toDataURL("image/png"); -} -/** - * Reads the pixels stored in the webgl texture and returns them as a base64 string - * @param texture defines the texture to read pixels from - * @param faceIndex defines the face of the texture to read (in case of cube texture) - * @param level defines the LOD level of the texture to read (in case of Mip Maps) - * @returns The base64 encoded string or null - */ -function GenerateBase64StringFromTexture(texture, faceIndex = 0, level = 0) { - const internalTexture = texture.getInternalTexture(); - if (!internalTexture) { - return null; - } - const pixels = texture._readPixelsSync(faceIndex, level); - if (!pixels) { - return null; - } - return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY); -} -/** - * Reads the pixels stored in the webgl texture and returns them as a base64 string - * @param texture defines the texture to read pixels from - * @param faceIndex defines the face of the texture to read (in case of cube texture) - * @param level defines the LOD level of the texture to read (in case of Mip Maps) - * @returns The base64 encoded string or null wrapped in a promise - */ -async function GenerateBase64StringFromTextureAsync(texture, faceIndex = 0, level = 0) { - const internalTexture = texture.getInternalTexture(); - if (!internalTexture) { - return null; - } - const pixels = await texture.readPixels(faceIndex, level); - if (!pixels) { - return null; - } - return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY); -} -/** - * Class used to host copy specific utilities - * (Back-compat) - */ -const CopyTools = { - /** - * Transform some pixel data to a base64 string - * @param pixels defines the pixel data to transform to base64 - * @param size defines the width and height of the (texture) data - * @param invertY true if the data must be inverted for the Y coordinate during the conversion - * @returns The base64 encoded string or null - */ - GenerateBase64StringFromPixelData, - /** - * Reads the pixels stored in the webgl texture and returns them as a base64 string - * @param texture defines the texture to read pixels from - * @param faceIndex defines the face of the texture to read (in case of cube texture) - * @param level defines the LOD level of the texture to read (in case of Mip Maps) - * @returns The base64 encoded string or null - */ - GenerateBase64StringFromTexture, - /** - * Reads the pixels stored in the webgl texture and returns them as a base64 string - * @param texture defines the texture to read pixels from - * @param faceIndex defines the face of the texture to read (in case of cube texture) - * @param level defines the LOD level of the texture to read (in case of Mip Maps) - * @returns The base64 encoded string or null wrapped in a promise - */ - GenerateBase64StringFromTextureAsync, -}; -//# sourceMappingURL=copyTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/texture.js - - - - - - - - - - - - - - -/** - * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture - */ -class texture_Texture extends baseTexture_BaseTexture { - /** - * Are mip maps generated for this texture or not. - */ - get noMipmap() { - return this._noMipmap; - } - /** Returns the texture mime type if it was defined by a loader (undefined else) */ - get mimeType() { - return this._mimeType; - } - /** - * Is the texture preventing material to render while loading. - * If false, a default texture will be used instead of the loading one during the preparation step. - */ - set isBlocking(value) { - this._isBlocking = value; - } - get isBlocking() { - return this._isBlocking; - } - /** - * Gets a boolean indicating if the texture needs to be inverted on the y axis during loading - */ - get invertY() { - return this._invertY; - } - /** - * Instantiates a new texture. - * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture - * @param url defines the url of the picture to load as a texture - * @param sceneOrEngine defines the scene or engine the texture will belong to - * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture - * @param invertY defines if the texture needs to be inverted on the y axis during loading - * @param samplingMode defines the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...) - * @param onLoad defines a callback triggered when the texture has been loaded - * @param onError defines a callback triggered when an error occurred during the loading session - * @param buffer defines the buffer to load the texture from in case the texture is loaded from a buffer representation - * @param deleteBuffer defines if the buffer we are loading the texture from should be deleted after load - * @param format defines the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) - * @param mimeType defines an optional mime type information - * @param loaderOptions options to be passed to the loader - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @param forcedExtension defines the extension to use to pick the right loader - */ - constructor(url, sceneOrEngine, noMipmapOrOptions, invertY, samplingMode = texture_Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, buffer = null, deleteBuffer = false, format, mimeType, loaderOptions, creationFlags, forcedExtension) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j; - super(sceneOrEngine); - /** - * Define the url of the texture. - */ - this.url = null; - /** - * Define an offset on the texture to offset the u coordinates of the UVs - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#offsetting - */ - this.uOffset = 0; - /** - * Define an offset on the texture to offset the v coordinates of the UVs - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#offsetting - */ - this.vOffset = 0; - /** - * Define an offset on the texture to scale the u coordinates of the UVs - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#tiling - */ - this.uScale = 1.0; - /** - * Define an offset on the texture to scale the v coordinates of the UVs - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#tiling - */ - this.vScale = 1.0; - /** - * Define an offset on the texture to rotate around the u coordinates of the UVs - * The angle is defined in radians. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials - */ - this.uAng = 0; - /** - * Define an offset on the texture to rotate around the v coordinates of the UVs - * The angle is defined in radians. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials - */ - this.vAng = 0; - /** - * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture) - * The angle is defined in radians. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials - */ - this.wAng = 0; - /** - * Defines the center of rotation (U) - */ - this.uRotationCenter = 0.5; - /** - * Defines the center of rotation (V) - */ - this.vRotationCenter = 0.5; - /** - * Defines the center of rotation (W) - */ - this.wRotationCenter = 0.5; - /** - * Sets this property to true to avoid deformations when rotating the texture with non-uniform scaling - */ - this.homogeneousRotationInUVTransform = false; - /** - * List of inspectable custom properties (used by the Inspector) - * @see https://doc.babylonjs.com/toolsAndResources/inspector#extensibility - */ - this.inspectableCustomProperties = null; - /** @internal */ - this._noMipmap = false; - /** @internal */ - this._invertY = false; - 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 = false; - this._cachedReflectionTextureMatrix = null; - this._cachedReflectionUOffset = -1; - this._cachedReflectionVOffset = -1; - this._cachedReflectionUScale = 0; - this._cachedReflectionVScale = 0; - this._cachedReflectionCoordinatesMode = -1; - /** @internal */ - this._buffer = null; - this._deleteBuffer = false; - this._format = null; - this._delayedOnLoad = null; - this._delayedOnError = null; - /** - * Observable triggered once the texture has been loaded. - */ - this.onLoadObservable = new observable_Observable(); - this._isBlocking = true; - this.name = url || ""; - this.url = url; - let noMipmap; - let useSRGBBuffer = false; - let internalTexture = null; - if (typeof noMipmapOrOptions === "object" && noMipmapOrOptions !== null) { - noMipmap = (_a = noMipmapOrOptions.noMipmap) !== null && _a !== void 0 ? _a : false; - invertY = (_b = noMipmapOrOptions.invertY) !== null && _b !== void 0 ? _b : (CompatibilityOptions.UseOpenGLOrientationForUV ? false : true); - samplingMode = (_c = noMipmapOrOptions.samplingMode) !== null && _c !== void 0 ? _c : texture_Texture.TRILINEAR_SAMPLINGMODE; - onLoad = (_d = noMipmapOrOptions.onLoad) !== null && _d !== void 0 ? _d : null; - onError = (_e = noMipmapOrOptions.onError) !== null && _e !== void 0 ? _e : null; - buffer = (_f = noMipmapOrOptions.buffer) !== null && _f !== void 0 ? _f : null; - deleteBuffer = (_g = noMipmapOrOptions.deleteBuffer) !== null && _g !== void 0 ? _g : false; - format = noMipmapOrOptions.format; - mimeType = noMipmapOrOptions.mimeType; - loaderOptions = noMipmapOrOptions.loaderOptions; - creationFlags = noMipmapOrOptions.creationFlags; - useSRGBBuffer = (_h = noMipmapOrOptions.useSRGBBuffer) !== null && _h !== void 0 ? _h : false; - internalTexture = (_j = noMipmapOrOptions.internalTexture) !== null && _j !== void 0 ? _j : null; - } - else { - noMipmap = !!noMipmapOrOptions; - } - this._noMipmap = noMipmap; - this._invertY = invertY === undefined ? (CompatibilityOptions.UseOpenGLOrientationForUV ? false : true) : invertY; - this._initialSamplingMode = samplingMode; - this._buffer = buffer; - this._deleteBuffer = deleteBuffer; - this._mimeType = mimeType; - this._loaderOptions = loaderOptions; - this._creationFlags = creationFlags; - this._useSRGBBuffer = useSRGBBuffer; - this._forcedExtension = forcedExtension; - if (format) { - this._format = format; - } - const scene = this.getScene(); - const engine = this._getEngine(); - if (!engine) { - return; - } - engine.onBeforeTextureInitObservable.notifyObservers(this); - const load = () => { - if (this._texture) { - if (this._texture._invertVScale) { - this.vScale *= -1; - this.vOffset += 1; - } - // Update texture to match internal texture's wrapping - if (this._texture._cachedWrapU !== null) { - this.wrapU = this._texture._cachedWrapU; - this._texture._cachedWrapU = null; - } - if (this._texture._cachedWrapV !== null) { - this.wrapV = this._texture._cachedWrapV; - this._texture._cachedWrapV = null; - } - if (this._texture._cachedWrapR !== null) { - this.wrapR = this._texture._cachedWrapR; - this._texture._cachedWrapR = null; - } - } - if (this.onLoadObservable.hasObservers()) { - this.onLoadObservable.notifyObservers(this); - } - if (onLoad) { - onLoad(); - } - if (!this.isBlocking && scene) { - scene.resetCachedMaterial(); - } - }; - const errorHandler = (message, exception) => { - this._loadingError = true; - this._errorObject = { message, exception }; - if (onError) { - onError(message, exception); - } - texture_Texture.OnTextureLoadErrorObservable.notifyObservers(this); - }; - if (!this.url && !internalTexture) { - this._delayedOnLoad = load; - this._delayedOnError = errorHandler; - return; - } - this._texture = internalTexture !== null && internalTexture !== void 0 ? internalTexture : this._getFromCache(this.url, noMipmap, samplingMode, this._invertY, useSRGBBuffer); - if (!this._texture) { - if (!scene || !scene.useDelayedTextureLoading) { - try { - this._texture = engine.createTexture(this.url, noMipmap, this._invertY, scene, samplingMode, load, errorHandler, this._buffer, undefined, this._format, this._forcedExtension, mimeType, loaderOptions, creationFlags, useSRGBBuffer); - } - catch (e) { - errorHandler("error loading", e); - throw e; - } - if (deleteBuffer) { - this._buffer = null; - } - } - else { - this.delayLoadState = 4; - this._delayedOnLoad = load; - this._delayedOnError = errorHandler; - } - } - else { - if (this._texture.isReady) { - TimingTools.SetImmediate(() => load()); - } - else { - const loadObserver = this._texture.onLoadedObservable.add(load); - this._texture.onErrorObservable.add((e) => { - var _a; - errorHandler(e.message, e.exception); - (_a = this._texture) === null || _a === void 0 ? void 0 : _a.onLoadedObservable.remove(loadObserver); - }); - } - } - } - /** - * Update the url (and optional buffer) of this texture if url was null during construction. - * @param url the url of the texture - * @param buffer the buffer of the texture (defaults to null) - * @param onLoad callback called when the texture is loaded (defaults to null) - * @param forcedExtension defines the extension to use to pick the right loader - */ - updateURL(url, buffer = null, onLoad, forcedExtension) { - if (this.url) { - this.releaseInternalTexture(); - this.getScene().markAllMaterialsAsDirty(1); - } - if (!this.name || this.name.startsWith("data:")) { - this.name = url; - } - this.url = url; - this._buffer = buffer; - this._forcedExtension = forcedExtension; - this.delayLoadState = 4; - if (onLoad) { - this._delayedOnLoad = onLoad; - } - this.delayLoad(); - } - /** - * Finish the loading sequence of a texture flagged as delayed load. - * @internal - */ - delayLoad() { - if (this.delayLoadState !== 4) { - return; - } - const scene = this.getScene(); - if (!scene) { - return; - } - this.delayLoadState = 1; - this._texture = this._getFromCache(this.url, this._noMipmap, this.samplingMode, this._invertY, this._useSRGBBuffer); - if (!this._texture) { - this._texture = scene - .getEngine() - .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); - if (this._deleteBuffer) { - this._buffer = null; - } - } - else { - if (this._delayedOnLoad) { - if (this._texture.isReady) { - TimingTools.SetImmediate(this._delayedOnLoad); - } - else { - this._texture.onLoadedObservable.add(this._delayedOnLoad); - } - } - } - this._delayedOnLoad = null; - this._delayedOnError = null; - } - _prepareRowForTextureGeneration(x, y, z, t) { - x *= this._cachedUScale; - y *= this._cachedVScale; - x -= this.uRotationCenter * this._cachedUScale; - y -= this.vRotationCenter * this._cachedVScale; - z -= this.wRotationCenter; - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t); - t.x += this.uRotationCenter * this._cachedUScale + this._cachedUOffset; - t.y += this.vRotationCenter * this._cachedVScale + this._cachedVOffset; - t.z += this.wRotationCenter; - } - /** - * Checks if the texture has the same transform matrix than another texture - * @param texture texture to check against - * @returns true if the transforms are the same, else false - */ - checkTransformsAreIdentical(texture) { - return (texture !== null && - this.uOffset === texture.uOffset && - this.vOffset === texture.vOffset && - this.uScale === texture.uScale && - this.vScale === texture.vScale && - this.uAng === texture.uAng && - this.vAng === texture.vAng && - this.wAng === texture.wAng); - } - /** - * Get the current texture matrix which includes the requested offsetting, tiling and rotation components. - * @param uBase - * @returns the transform matrix of the texture. - */ - getTextureMatrix(uBase = 1) { - if (this.uOffset === this._cachedUOffset && - this.vOffset === this._cachedVOffset && - this.uScale * uBase === 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 * uBase; - 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; - if (!this._cachedTextureMatrix || !this._rowGenerationMatrix) { - this._cachedTextureMatrix = math_vector_Matrix.Zero(); - this._rowGenerationMatrix = new math_vector_Matrix(); - this._t0 = math_vector_Vector3.Zero(); - this._t1 = math_vector_Vector3.Zero(); - this._t2 = math_vector_Vector3.Zero(); - } - math_vector_Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix); - if (this.homogeneousRotationInUVTransform) { - math_vector_Matrix.TranslationToRef(-this._cachedURotationCenter, -this._cachedVRotationCenter, -this._cachedWRotationCenter, math_vector_TmpVectors.Matrix[0]); - math_vector_Matrix.TranslationToRef(this._cachedURotationCenter, this._cachedVRotationCenter, this._cachedWRotationCenter, math_vector_TmpVectors.Matrix[1]); - math_vector_Matrix.ScalingToRef(this._cachedUScale, this._cachedVScale, 0, math_vector_TmpVectors.Matrix[2]); - math_vector_Matrix.TranslationToRef(this._cachedUOffset, this._cachedVOffset, 0, math_vector_TmpVectors.Matrix[3]); - math_vector_TmpVectors.Matrix[0].multiplyToRef(this._rowGenerationMatrix, this._cachedTextureMatrix); - this._cachedTextureMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[1], this._cachedTextureMatrix); - this._cachedTextureMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[2], this._cachedTextureMatrix); - this._cachedTextureMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[3], this._cachedTextureMatrix); - // 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) - this._cachedTextureMatrix.setRowFromFloats(2, this._cachedTextureMatrix.m[12], this._cachedTextureMatrix.m[13], this._cachedTextureMatrix.m[14], 1); - } - else { - this._prepareRowForTextureGeneration(0, 0, 0, this._t0); - this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1); - this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2); - this._t1.subtractInPlace(this._t0); - this._t2.subtractInPlace(this._t0); - math_vector_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); - } - const scene = this.getScene(); - if (!scene) { - return this._cachedTextureMatrix; - } - if (this.optimizeUVAllocation) { - // 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 - // will get different values (see MaterialHelper.PrepareDefinesForMergedUV), meaning we should regenerate the effect accordingly - scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this); - }); - } - return this._cachedTextureMatrix; - } - /** - * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance. - * @returns The reflection texture transform - */ - getReflectionTextureMatrix() { - const scene = this.getScene(); - if (!scene) { - 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 === texture_Texture.PROJECTION_MODE) { - if (this._cachedReflectionProjectionMatrixId === scene.getProjectionMatrix().updateFlag) { - return this._cachedReflectionTextureMatrix; - } - } - else { - return this._cachedReflectionTextureMatrix; - } - } - if (!this._cachedReflectionTextureMatrix) { - this._cachedReflectionTextureMatrix = math_vector_Matrix.Zero(); - } - if (!this._projectionModeMatrix) { - this._projectionModeMatrix = math_vector_Matrix.Zero(); - } - const flagMaterialsAsTextureDirty = this._cachedReflectionCoordinatesMode !== this.coordinatesMode; - this._cachedReflectionUOffset = this.uOffset; - this._cachedReflectionVOffset = this.vOffset; - this._cachedReflectionUScale = this.uScale; - this._cachedReflectionVScale = this.vScale; - this._cachedReflectionCoordinatesMode = this.coordinatesMode; - switch (this.coordinatesMode) { - case texture_Texture.PLANAR_MODE: { - math_vector_Matrix.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 texture_Texture.PROJECTION_MODE: { - math_vector_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); - const projectionMatrix = scene.getProjectionMatrix(); - this._cachedReflectionProjectionMatrixId = projectionMatrix.updateFlag; - projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedReflectionTextureMatrix); - break; - } - default: - math_vector_Matrix.IdentityToRef(this._cachedReflectionTextureMatrix); - break; - } - if (flagMaterialsAsTextureDirty) { - // We flag the materials that are using this texture as "texture dirty" if the coordinatesMode has changed. - // 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 - scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.getActiveTextures().indexOf(this) !== -1; - }); - } - return this._cachedReflectionTextureMatrix; - } - /** - * Clones the texture. - * @returns the cloned texture - */ - clone() { - const options = { - noMipmap: this._noMipmap, - invertY: this._invertY, - samplingMode: this.samplingMode, - onLoad: undefined, - onError: undefined, - buffer: this._texture ? this._texture._buffer : undefined, - deleteBuffer: this._deleteBuffer, - format: this.textureFormat, - mimeType: this.mimeType, - loaderOptions: this._loaderOptions, - creationFlags: this._creationFlags, - useSRGBBuffer: this._useSRGBBuffer, - }; - return decorators_SerializationHelper.Clone(() => { - return new texture_Texture(this._texture ? this._texture.url : null, this.getScene(), options); - }, this); - } - /** - * Serialize the texture to a JSON representation we can easily use in the respective Parse function. - * @returns The JSON representation of the texture - */ - serialize() { - var _a, _b; - const savedName = this.name; - if (!texture_Texture.SerializeBuffers) { - if (this.name.startsWith("data:")) { - this.name = ""; - } - } - if (this.name.startsWith("data:") && this.url === this.name) { - this.url = ""; - } - const serializationObject = super.serialize(texture_Texture._SerializeInternalTextureUniqueId); - if (!serializationObject) { - return null; - } - if (texture_Texture.SerializeBuffers || texture_Texture.ForceSerializeBuffers) { - if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") { - serializationObject.base64String = this._buffer; - serializationObject.name = serializationObject.name.replace("data:", ""); - } - else if (this.url && this.url.startsWith("data:") && this._buffer instanceof Uint8Array) { - serializationObject.base64String = "data:image/png;base64," + stringTools_EncodeArrayBufferToBase64(this._buffer); - } - else if (texture_Texture.ForceSerializeBuffers || (this.url && this.url.startsWith("blob:")) || this._forceSerialize) { - serializationObject.base64String = - !this._engine || this._engine._features.supportSyncTextureRead ? GenerateBase64StringFromTexture(this) : GenerateBase64StringFromTextureAsync(this); - } - } - serializationObject.invertY = this._invertY; - serializationObject.samplingMode = this.samplingMode; - serializationObject._creationFlags = this._creationFlags; - serializationObject._useSRGBBuffer = this._useSRGBBuffer; - if (texture_Texture._SerializeInternalTextureUniqueId) { - serializationObject.internalTextureUniqueId = (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : undefined; - } - this.name = savedName; - return serializationObject; - } - /** - * Get the current class name of the texture useful for serialization or dynamic coding. - * @returns "Texture" - */ - getClassName() { - return "Texture"; - } - /** - * Dispose the texture and release its associated resources. - */ - dispose() { - super.dispose(); - this.onLoadObservable.clear(); - this._delayedOnLoad = null; - this._delayedOnError = null; - this._buffer = null; - } - /** - * Parse the JSON representation of a texture in order to recreate the texture in the given scene. - * @param parsedTexture Define the JSON representation of the texture - * @param scene Define the scene the parsed texture should be instantiated in - * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies - * @returns The parsed texture if successful - */ - static Parse(parsedTexture, scene, rootUrl) { - if (parsedTexture.customType) { - const customTexture = InstantiationTools.Instantiate(parsedTexture.customType); - // Update Sampling Mode - const parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl); - if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) { - if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) { - parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode); - } - } - return parsedCustomTexture; - } - if (parsedTexture.isCube && !parsedTexture.isRenderTarget) { - return texture_Texture._CubeTextureParser(parsedTexture, scene, rootUrl); - } - const hasInternalTextureUniqueId = parsedTexture.internalTextureUniqueId !== undefined; - if (!parsedTexture.name && !parsedTexture.isRenderTarget && !hasInternalTextureUniqueId) { - return null; - } - let internalTexture; - if (hasInternalTextureUniqueId) { - const cache = scene.getEngine().getLoadedTexturesCache(); - for (const texture of cache) { - if (texture.uniqueId === parsedTexture.internalTextureUniqueId) { - internalTexture = texture; - break; - } - } - } - const onLoaded = (texture) => { - var _a; - // Clear cache - if (texture && texture._texture) { - texture._texture._cachedWrapU = null; - texture._texture._cachedWrapV = null; - texture._texture._cachedWrapR = null; - } - // Update Sampling Mode - if (parsedTexture.samplingMode) { - const sampling = parsedTexture.samplingMode; - if (texture && texture.samplingMode !== sampling) { - texture.updateSamplingMode(sampling); - } - } - // Animations - if (texture && parsedTexture.animations) { - for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) { - const parsedAnimation = parsedTexture.animations[animationIndex]; - const internalClass = GetClass("BABYLON.Animation"); - if (internalClass) { - texture.animations.push(internalClass.Parse(parsedAnimation)); - } - } - } - if (hasInternalTextureUniqueId && !internalTexture) { - (_a = texture === null || texture === void 0 ? void 0 : texture._texture) === null || _a === void 0 ? void 0 : _a._setUniqueId(parsedTexture.internalTextureUniqueId); - } - }; - const texture = decorators_SerializationHelper.Parse(() => { - var _a, _b, _c; - let generateMipMaps = true; - if (parsedTexture.noMipmap) { - generateMipMaps = false; - } - if (parsedTexture.mirrorPlane) { - const mirrorTexture = texture_Texture._CreateMirror(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps); - mirrorTexture._waitingRenderList = parsedTexture.renderList; - mirrorTexture.mirrorPlane = math_plane_Plane.FromArray(parsedTexture.mirrorPlane); - onLoaded(mirrorTexture); - return mirrorTexture; - } - else if (parsedTexture.isRenderTarget) { - let renderTargetTexture = null; - if (parsedTexture.isCube) { - // Search for an existing reflection probe (which contains a cube render target texture) - if (scene.reflectionProbes) { - for (let index = 0; index < scene.reflectionProbes.length; index++) { - const probe = scene.reflectionProbes[index]; - if (probe.name === parsedTexture.name) { - return probe.cubeTexture; - } - } - } - } - else { - renderTargetTexture = texture_Texture._CreateRenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps, (_a = parsedTexture._creationFlags) !== null && _a !== void 0 ? _a : 0); - renderTargetTexture._waitingRenderList = parsedTexture.renderList; - } - onLoaded(renderTargetTexture); - return renderTargetTexture; - } - else { - let texture; - if (parsedTexture.base64String && !internalTexture) { - // name and url are the same to ensure caching happens from the actual base64 string - texture = texture_Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.base64String, scene, !generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, () => { - onLoaded(texture); - }, (_b = parsedTexture._creationFlags) !== null && _b !== void 0 ? _b : 0, (_c = parsedTexture._useSRGBBuffer) !== null && _c !== void 0 ? _c : false); - // prettier name to fit with the loaded data - texture.name = parsedTexture.name; - } - else { - let url; - if (parsedTexture.name && (parsedTexture.name.indexOf("://") > 0 || parsedTexture.name.startsWith("data:"))) { - url = parsedTexture.name; - } - else { - url = rootUrl + parsedTexture.name; - } - if (parsedTexture.url && (parsedTexture.url.startsWith("data:") || texture_Texture.UseSerializedUrlIfAny)) { - url = parsedTexture.url; - } - const options = { - noMipmap: !generateMipMaps, - invertY: parsedTexture.invertY, - samplingMode: parsedTexture.samplingMode, - onLoad: () => { - onLoaded(texture); - }, - internalTexture, - }; - texture = new texture_Texture(url, scene, options); - } - return texture; - } - }, parsedTexture, scene); - return texture; - } - /** - * Creates a texture from its base 64 representation. - * @param data Define the base64 payload without the data: prefix - * @param name Define the name of the texture in the scene useful fo caching purpose for instance - * @param scene Define the scene the texture should belong to - * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture - * @param invertY define if the texture needs to be inverted on the y axis during loading - * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...) - * @param onLoad define a callback triggered when the texture has been loaded - * @param onError define a callback triggered when an error occurred during the loading session - * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @returns the created texture - */ - static CreateFromBase64String(data, name, scene, noMipmapOrOptions, invertY, samplingMode = texture_Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags) { - return new texture_Texture("data:" + name, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, data, false, format, undefined, undefined, creationFlags); - } - /** - * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in) - * @param name Define the name of the texture in the scene useful fo caching purpose for instance - * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation - * @param scene Define the scene the texture should belong to - * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load - * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture - * @param invertY define if the texture needs to be inverted on the y axis during loading - * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...) - * @param onLoad define a callback triggered when the texture has been loaded - * @param onError define a callback triggered when an error occurred during the loading session - * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @returns the created texture - */ - static LoadFromDataString(name, buffer, scene, deleteBuffer = false, noMipmapOrOptions, invertY = true, samplingMode = texture_Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags) { - if (name.substr(0, 5) !== "data:") { - name = "data:" + name; - } - return new texture_Texture(name, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format, undefined, undefined, creationFlags); - } -} -/** - * Gets or sets a general boolean used to indicate that textures containing direct data (buffers) must be saved as part of the serialization process - */ -texture_Texture.SerializeBuffers = true; -/** - * Gets or sets a general boolean used to indicate that texture buffers must be saved as part of the serialization process. - * If no buffer exists, one will be created as base64 string from the internal webgl data. - */ -texture_Texture.ForceSerializeBuffers = false; -/** - * This observable will notify when any texture had a loading error - */ -texture_Texture.OnTextureLoadErrorObservable = new observable_Observable(); -/** @internal */ -texture_Texture._SerializeInternalTextureUniqueId = false; -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -texture_Texture._CubeTextureParser = (jsonTexture, scene, rootUrl) => { - throw _WarnImport("CubeTexture"); -}; -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -texture_Texture._CreateMirror = (name, renderTargetSize, scene, generateMipMaps) => { - throw _WarnImport("MirrorTexture"); -}; -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -texture_Texture._CreateRenderTargetTexture = (name, renderTargetSize, scene, generateMipMaps, creationFlags) => { - throw _WarnImport("RenderTargetTexture"); -}; -/** nearest is mag = nearest and min = nearest and no mip */ -texture_Texture.NEAREST_SAMPLINGMODE = 1; -/** nearest is mag = nearest and min = nearest and mip = linear */ -texture_Texture.NEAREST_NEAREST_MIPLINEAR = 8; // nearest is mag = nearest and min = nearest and mip = linear -/** Bilinear is mag = linear and min = linear and no mip */ -texture_Texture.BILINEAR_SAMPLINGMODE = 2; -/** Bilinear is mag = linear and min = linear and mip = nearest */ -texture_Texture.LINEAR_LINEAR_MIPNEAREST = 11; // Bilinear is mag = linear and min = linear and mip = nearest -/** Trilinear is mag = linear and min = linear and mip = linear */ -texture_Texture.TRILINEAR_SAMPLINGMODE = 3; -/** Trilinear is mag = linear and min = linear and mip = linear */ -texture_Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear -/** mag = nearest and min = nearest and mip = nearest */ -texture_Texture.NEAREST_NEAREST_MIPNEAREST = 4; -/** mag = nearest and min = linear and mip = nearest */ -texture_Texture.NEAREST_LINEAR_MIPNEAREST = 5; -/** mag = nearest and min = linear and mip = linear */ -texture_Texture.NEAREST_LINEAR_MIPLINEAR = 6; -/** mag = nearest and min = linear and mip = none */ -texture_Texture.NEAREST_LINEAR = 7; -/** mag = nearest and min = nearest and mip = none */ -texture_Texture.NEAREST_NEAREST = 1; -/** mag = linear and min = nearest and mip = nearest */ -texture_Texture.LINEAR_NEAREST_MIPNEAREST = 9; -/** mag = linear and min = nearest and mip = linear */ -texture_Texture.LINEAR_NEAREST_MIPLINEAR = 10; -/** mag = linear and min = linear and mip = none */ -texture_Texture.LINEAR_LINEAR = 2; -/** mag = linear and min = nearest and mip = none */ -texture_Texture.LINEAR_NEAREST = 12; -/** Explicit coordinates mode */ -texture_Texture.EXPLICIT_MODE = 0; -/** Spherical coordinates mode */ -texture_Texture.SPHERICAL_MODE = 1; -/** Planar coordinates mode */ -texture_Texture.PLANAR_MODE = 2; -/** Cubic coordinates mode */ -texture_Texture.CUBIC_MODE = 3; -/** Projection coordinates mode */ -texture_Texture.PROJECTION_MODE = 4; -/** Inverse Cubic coordinates mode */ -texture_Texture.SKYBOX_MODE = 5; -/** Inverse Cubic coordinates mode */ -texture_Texture.INVCUBIC_MODE = 6; -/** Equirectangular coordinates mode */ -texture_Texture.EQUIRECTANGULAR_MODE = 7; -/** Equirectangular Fixed coordinates mode */ -texture_Texture.FIXED_EQUIRECTANGULAR_MODE = 8; -/** Equirectangular Fixed Mirrored coordinates mode */ -texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; -/** Texture is not repeating outside of 0..1 UVs */ -texture_Texture.CLAMP_ADDRESSMODE = 0; -/** Texture is repeating outside of 0..1 UVs */ -texture_Texture.WRAP_ADDRESSMODE = 1; -/** Texture is repeating and mirrored */ -texture_Texture.MIRROR_ADDRESSMODE = 2; -/** - * 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 - */ -texture_Texture.UseSerializedUrlIfAny = false; -__decorate([ - serialize() -], texture_Texture.prototype, "url", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "uOffset", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "vOffset", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "uScale", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "vScale", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "uAng", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "vAng", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "wAng", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "uRotationCenter", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "vRotationCenter", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "wRotationCenter", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "homogeneousRotationInUVTransform", void 0); -__decorate([ - serialize() -], texture_Texture.prototype, "isBlocking", null); -// References the dependencies. -RegisterClass("BABYLON.Texture", texture_Texture); -decorators_SerializationHelper._TextureParser = texture_Texture.Parse; -//# sourceMappingURL=texture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.rawTexture.js - - - - - -ThinEngine.prototype.updateRawTexture = function (texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) { - if (!texture) { - return; - } - // Babylon's internalSizedFomat but gl's texImage2D internalFormat - const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer); - // Babylon's internalFormat but gl's texImage2D format - const internalFormat = this._getInternalFormat(format); - const textureType = this._getWebGLTextureType(type); - this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); - this._unpackFlipY(invertY === undefined ? true : invertY ? true : false); - if (!this._doNotHandleContextLost) { - texture._bufferView = data; - texture.format = format; - texture.type = type; - texture.invertY = invertY; - texture._compression = compression; - } - if (texture.width % 4 !== 0) { - this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1); - } - if (compression && data) { - this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data); - } - else { - this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data); - } - if (texture.generateMipMaps) { - this._gl.generateMipmap(this._gl.TEXTURE_2D); - } - this._bindTextureDirectly(this._gl.TEXTURE_2D, null); - // this.resetTextureCache(); - texture.isReady = true; -}; -ThinEngine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, -// eslint-disable-next-line @typescript-eslint/no-unused-vars -creationFlags = 0, useSRGBBuffer = false) { - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Raw); - texture.baseWidth = width; - texture.baseHeight = height; - texture.width = width; - texture.height = height; - texture.format = format; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.invertY = invertY; - texture._compression = compression; - texture.type = type; - texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps); - if (!this._doNotHandleContextLost) { - texture._bufferView = data; - } - this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer); - this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); - // Filters - const filters = this._getSamplingParameters(samplingMode, generateMipMaps); - this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag); - this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min); - if (generateMipMaps) { - this._gl.generateMipmap(this._gl.TEXTURE_2D); - } - this._bindTextureDirectly(this._gl.TEXTURE_2D, null); - this._internalTexturesCache.push(texture); - return texture; -}; -ThinEngine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) { - const gl = this._gl; - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.CubeRaw); - texture.isCube = true; - texture.format = format; - texture.type = type; - if (!this._doNotHandleContextLost) { - texture._bufferViewArray = data; - } - const textureType = this._getWebGLTextureType(type); - let internalFormat = this._getInternalFormat(format); - if (internalFormat === gl.RGB) { - internalFormat = gl.RGBA; - } - // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable - if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) { - generateMipMaps = false; - samplingMode = 1; - logger_Logger.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."); - } - else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) { - generateMipMaps = false; - samplingMode = 1; - logger_Logger.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."); - } - else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) { - generateMipMaps = false; - logger_Logger.Warn("Render to float textures is not supported. Mipmap generation forced to false."); - } - else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) { - generateMipMaps = false; - logger_Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false."); - } - const width = size; - const height = width; - texture.width = width; - texture.height = height; - texture.invertY = invertY; - texture._compression = compression; - // Double check on POT to generate Mips. - const isPot = !this.needPOTTextures || (tools_Tools.IsExponentOfTwo(texture.width) && tools_Tools.IsExponentOfTwo(texture.height)); - if (!isPot) { - generateMipMaps = false; - } - // Upload data if needed. The texture won't be ready until then. - if (data) { - this.updateRawCubeTexture(texture, data, format, type, invertY, compression); - } - else { - const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); - const level = 0; - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); - for (let faceIndex = 0; faceIndex < 6; faceIndex++) { - if (compression) { - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, undefined); - } - else { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, null); - } - } - this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); - } - this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true); - // Filters - if (data && generateMipMaps) { - this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP); - } - const filters = this._getSamplingParameters(samplingMode, generateMipMaps); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.isReady = true; - return texture; -}; -ThinEngine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression = null, level = 0) { - texture._bufferViewArray = data; - texture.format = format; - texture.type = type; - texture.invertY = invertY; - texture._compression = compression; - const gl = this._gl; - const textureType = this._getWebGLTextureType(type); - let internalFormat = this._getInternalFormat(format); - const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); - let needConversion = false; - if (internalFormat === gl.RGB) { - internalFormat = gl.RGBA; - needConversion = true; - } - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); - this._unpackFlipY(invertY === undefined ? true : invertY ? true : false); - if (texture.width % 4 !== 0) { - gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); - } - // Data are known to be in +X +Y +Z -X -Y -Z - for (let faceIndex = 0; faceIndex < 6; faceIndex++) { - let faceData = data[faceIndex]; - if (compression) { - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData); - } - else { - if (needConversion) { - faceData = _convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type); - } - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData); - } - } - const isPot = !this.needPOTTextures || (tools_Tools.IsExponentOfTwo(texture.width) && tools_Tools.IsExponentOfTwo(texture.height)); - if (isPot && texture.generateMipMaps && level === 0) { - this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP); - } - this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); - // this.resetTextureCache(); - texture.isReady = true; -}; -ThinEngine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) { - const gl = this._gl; - const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null); - scene === null || scene === void 0 ? void 0 : scene.addPendingData(texture); - texture.url = url; - texture.isReady = false; - this._internalTexturesCache.push(texture); - const onerror = (request, exception) => { - scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture); - if (onError && request) { - onError(request.status + " " + request.statusText, exception); - } - }; - const internalCallback = (data) => { - const width = texture.width; - const faceDataArrays = callback(data); - if (!faceDataArrays) { - return; - } - if (mipmapGenerator) { - const textureType = this._getWebGLTextureType(type); - let internalFormat = this._getInternalFormat(format); - const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); - let needConversion = false; - if (internalFormat === gl.RGB) { - internalFormat = gl.RGBA; - needConversion = true; - } - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); - this._unpackFlipY(false); - const mipData = mipmapGenerator(faceDataArrays); - for (let level = 0; level < mipData.length; level++) { - const mipSize = width >> level; - for (let faceIndex = 0; faceIndex < 6; faceIndex++) { - let mipFaceData = mipData[level][faceIndex]; - if (needConversion) { - mipFaceData = _convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type); - } - gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData); - } - } - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); - } - else { - this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY); - } - texture.isReady = true; - // this.resetTextureCache(); - scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture); - texture.onLoadedObservable.notifyObservers(texture); - texture.onLoadedObservable.clear(); - if (onLoad) { - onLoad(); - } - }; - this._loadFile(url, (data) => { - internalCallback(data); - }, undefined, scene === null || scene === void 0 ? void 0 : scene.offlineProvider, true, onerror); - return texture; -}; -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function _convertRGBtoRGBATextureData(rgbData, width, height, textureType) { - // Create new RGBA data container. - let rgbaData; - let val1 = 1; - if (textureType === 1) { - rgbaData = new Float32Array(width * height * 4); - } - else if (textureType === 2) { - rgbaData = new Uint16Array(width * height * 4); - val1 = 15360; // 15360 is the encoding of 1 in half float - } - else if (textureType === 7) { - rgbaData = new Uint32Array(width * height * 4); - } - else { - rgbaData = new Uint8Array(width * height * 4); - } - // Convert each pixel. - for (let x = 0; x < width; x++) { - for (let y = 0; y < height; y++) { - const index = (y * width + x) * 3; - const newIndex = (y * width + x) * 4; - // Map Old Value to new value. - rgbaData[newIndex + 0] = rgbData[index + 0]; - rgbaData[newIndex + 1] = rgbData[index + 1]; - rgbaData[newIndex + 2] = rgbData[index + 2]; - // Add fully opaque alpha channel. - rgbaData[newIndex + 3] = val1; - } - } - return rgbaData; -} -/** - * Create a function for createRawTexture3D/createRawTexture2DArray - * @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function _makeCreateRawTextureFunction(is3D) { - return function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) { - const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY; - const source = is3D ? internalTexture_InternalTextureSource.Raw3D : internalTexture_InternalTextureSource.Raw2DArray; - const texture = new internalTexture_InternalTexture(this, source); - texture.baseWidth = width; - texture.baseHeight = height; - texture.baseDepth = depth; - texture.width = width; - texture.height = height; - texture.depth = depth; - texture.format = format; - texture.type = textureType; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - if (is3D) { - texture.is3D = true; - } - else { - texture.is2DArray = true; - } - if (!this._doNotHandleContextLost) { - texture._bufferView = data; - } - if (is3D) { - this.updateRawTexture3D(texture, data, format, invertY, compression, textureType); - } - else { - this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType); - } - this._bindTextureDirectly(target, texture, true); - // Filters - const filters = this._getSamplingParameters(samplingMode, generateMipMaps); - this._gl.texParameteri(target, this._gl.TEXTURE_MAG_FILTER, filters.mag); - this._gl.texParameteri(target, this._gl.TEXTURE_MIN_FILTER, filters.min); - if (generateMipMaps) { - this._gl.generateMipmap(target); - } - this._bindTextureDirectly(target, null); - this._internalTexturesCache.push(texture); - return texture; - }; -} -ThinEngine.prototype.createRawTexture2DArray = _makeCreateRawTextureFunction(false); -ThinEngine.prototype.createRawTexture3D = _makeCreateRawTextureFunction(true); -/** - * Create a function for updateRawTexture3D/updateRawTexture2DArray - * @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function _makeUpdateRawTextureFunction(is3D) { - return function (texture, data, format, invertY, compression = null, textureType = 0) { - const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY; - const internalType = this._getWebGLTextureType(textureType); - const internalFormat = this._getInternalFormat(format); - const internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format); - this._bindTextureDirectly(target, texture, true); - this._unpackFlipY(invertY === undefined ? true : invertY ? true : false); - if (!this._doNotHandleContextLost) { - texture._bufferView = data; - texture.format = format; - texture.invertY = invertY; - texture._compression = compression; - } - if (texture.width % 4 !== 0) { - this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1); - } - if (compression && data) { - this._gl.compressedTexImage3D(target, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data); - } - else { - this._gl.texImage3D(target, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data); - } - if (texture.generateMipMaps) { - this._gl.generateMipmap(target); - } - this._bindTextureDirectly(target, null); - // this.resetTextureCache(); - texture.isReady = true; - }; -} -ThinEngine.prototype.updateRawTexture2DArray = _makeUpdateRawTextureFunction(false); -ThinEngine.prototype.updateRawTexture3D = _makeUpdateRawTextureFunction(true); -//# sourceMappingURL=engine.rawTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/rawTexture.js - - - -/** - * Raw texture can help creating a texture directly from an array of data. - * This can be super useful if you either get the data from an uncompressed source or - * if you wish to create your texture pixel by pixel. - */ -class rawTexture_RawTexture extends texture_Texture { - /** - * Instantiates a new RawTexture. - * Raw texture can help creating a texture directly from an array of data. - * This can be super useful if you either get the data from an uncompressed source or - * if you wish to create your texture pixel by pixel. - * @param data define the array of data to use to create the texture (null to create an empty texture) - * @param width define the width of the texture - * @param height define the height of the texture - * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx) - * @param sceneOrEngine defines the scene or engine the texture will belong to - * @param generateMipMaps define whether mip maps should be generated or not - * @param invertY define if the data should be flipped on Y when uploaded to the GPU - * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) - * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - */ - constructor(data, width, height, - /** - * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx) - */ - format, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags, useSRGBBuffer) { - super(null, sceneOrEngine, !generateMipMaps, invertY, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, creationFlags); - this.format = format; - if (!this._engine) { - return; - } - if (!this._engine._caps.textureFloatLinearFiltering && type === 1) { - samplingMode = 1; - } - if (!this._engine._caps.textureHalfFloatLinearFiltering && type === 2) { - samplingMode = 1; - } - 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); - this.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - } - /** - * Updates the texture underlying data. - * @param data Define the new data of the texture - */ - update(data) { - this._getEngine().updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type, this._texture._useSRGBBuffer); - } - /** - * Creates a luminance texture from some data. - * @param data Define the texture data - * @param width Define the width of the texture - * @param height Define the height of the texture - * @param sceneOrEngine defines the scene or engine the texture will belong to - * @param generateMipMaps Define whether or not to create mip maps for the texture - * @param invertY define if the data should be flipped on Y when uploaded to the GPU - * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) - * @returns the luminance texture - */ - static CreateLuminanceTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) { - return new rawTexture_RawTexture(data, width, height, 1, sceneOrEngine, generateMipMaps, invertY, samplingMode); - } - /** - * Creates a luminance alpha texture from some data. - * @param data Define the texture data - * @param width Define the width of the texture - * @param height Define the height of the texture - * @param sceneOrEngine defines the scene or engine the texture will belong to - * @param generateMipMaps Define whether or not to create mip maps for the texture - * @param invertY define if the data should be flipped on Y when uploaded to the GPU - * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) - * @returns the luminance alpha texture - */ - static CreateLuminanceAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) { - return new rawTexture_RawTexture(data, width, height, 2, sceneOrEngine, generateMipMaps, invertY, samplingMode); - } - /** - * Creates an alpha texture from some data. - * @param data Define the texture data - * @param width Define the width of the texture - * @param height Define the height of the texture - * @param sceneOrEngine defines the scene or engine the texture will belong to - * @param generateMipMaps Define whether or not to create mip maps for the texture - * @param invertY define if the data should be flipped on Y when uploaded to the GPU - * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) - * @returns the alpha texture - */ - static CreateAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) { - return new rawTexture_RawTexture(data, width, height, 0, sceneOrEngine, generateMipMaps, invertY, samplingMode); - } - /** - * Creates a RGB texture from some data. - * @param data Define the texture data - * @param width Define the width of the texture - * @param height Define the height of the texture - * @param sceneOrEngine defines the scene or engine the texture will belong to - * @param generateMipMaps Define whether or not to create mip maps for the texture - * @param invertY define if the data should be flipped on Y when uploaded to the GPU - * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) - * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - * @returns the RGB alpha texture - */ - static CreateRGBTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false) { - return new rawTexture_RawTexture(data, width, height, 4, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer); - } - /** - * Creates a RGBA texture from some data. - * @param data Define the texture data - * @param width Define the width of the texture - * @param height Define the height of the texture - * @param sceneOrEngine defines the scene or engine the texture will belong to - * @param generateMipMaps Define whether or not to create mip maps for the texture - * @param invertY define if the data should be flipped on Y when uploaded to the GPU - * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) - * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - * @returns the RGBA texture - */ - static CreateRGBATexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false) { - return new rawTexture_RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer); - } - /** - * Creates a RGBA storage texture from some data. - * @param data Define the texture data - * @param width Define the width of the texture - * @param height Define the height of the texture - * @param sceneOrEngine defines the scene or engine the texture will belong to - * @param generateMipMaps Define whether or not to create mip maps for the texture - * @param invertY define if the data should be flipped on Y when uploaded to the GPU - * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) - * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - * @returns the RGBA texture - */ - static CreateRGBAStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, useSRGBBuffer = false) { - return new rawTexture_RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1, useSRGBBuffer); - } - /** - * Creates a R texture from some data. - * @param data Define the texture data - * @param width Define the width of the texture - * @param height Define the height of the texture - * @param sceneOrEngine defines the scene or engine the texture will belong to - * @param generateMipMaps Define whether or not to create mip maps for the texture - * @param invertY define if the data should be flipped on Y when uploaded to the GPU - * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) - * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) - * @returns the R texture - */ - static CreateRTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = texture_Texture.TRILINEAR_SAMPLINGMODE, type = 1) { - return new rawTexture_RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type); - } - /** - * Creates a R storage texture from some data. - * @param data Define the texture data - * @param width Define the width of the texture - * @param height Define the height of the texture - * @param sceneOrEngine defines the scene or engine the texture will belong to - * @param generateMipMaps Define whether or not to create mip maps for the texture - * @param invertY define if the data should be flipped on Y when uploaded to the GPU - * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) - * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) - * @returns the R texture - */ - static CreateRStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = texture_Texture.TRILINEAR_SAMPLINGMODE, type = 1) { - return new rawTexture_RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1); - } -} -//# sourceMappingURL=rawTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/BakedVertexAnimation/vertexAnimationBaker.js - - - - -/** - * Class to bake vertex animation textures. - * @since 5.0 - */ -class VertexAnimationBaker { - /** - * Create a new VertexAnimationBaker object which can help baking animations into a texture. - * @param scene Defines the scene the VAT belongs to - * @param mesh Defines the mesh the VAT belongs to - */ - constructor(scene, mesh) { - this._scene = scene; - this._mesh = mesh; - } - /** - * Bakes the animation into the texture. This should be called once, when the - * scene starts, so the VAT is generated and associated to the mesh. - * @param ranges Defines the ranges in the animation that will be baked. - * @returns The array of matrix transforms for each vertex (columns) and frame (rows), as a Float32Array. - */ - async bakeVertexData(ranges) { - if (!this._mesh.skeleton) { - throw new Error("No skeleton in this mesh."); - } - const boneCount = this._mesh.skeleton.bones.length; - /** total number of frames in our animations */ - const frameCount = ranges.reduce((previous, current) => previous + current.to - current.from + 1, 0); - if (isNaN(frameCount)) { - throw new Error("Invalid animation ranges."); - } - // reset our loop data - let textureIndex = 0; - const textureSize = (boneCount + 1) * 4 * 4 * frameCount; - const vertexData = new Float32Array(textureSize); - this._scene.stopAnimation(this._mesh); - this._mesh.skeleton.returnToRest(); - // render all frames from our slices - for (const range of ranges) { - for (let frameIndex = range.from; frameIndex <= range.to; frameIndex++) { - await this._executeAnimationFrame(vertexData, frameIndex, textureIndex++); - } - } - return vertexData; - } - /** - * Runs an animation frame and stores its vertex data - * - * @param vertexData The array to save data to. - * @param frameIndex Current frame in the skeleton animation to render. - * @param textureIndex Current index of the texture data. - */ - async _executeAnimationFrame(vertexData, frameIndex, textureIndex) { - return new Promise((resolve, _reject) => { - this._scene.beginAnimation(this._mesh.skeleton, frameIndex, frameIndex, false, 1.0, () => { - // generate matrices - const skeletonMatrices = this._mesh.skeleton.getTransformMatrices(this._mesh); - vertexData.set(skeletonMatrices, textureIndex * skeletonMatrices.length); - resolve(); - }); - }); - } - /** - * Builds a vertex animation texture given the vertexData in an array. - * @param vertexData The vertex animation data. You can generate it with bakeVertexData(). - * @returns The vertex animation texture to be used with BakedVertexAnimationManager. - */ - textureFromBakedVertexData(vertexData) { - if (!this._mesh.skeleton) { - throw new Error("No skeleton in this mesh."); - } - const boneCount = this._mesh.skeleton.bones.length; - const texture = RawTexture.CreateRGBATexture(vertexData, (boneCount + 1) * 4, vertexData.length / ((boneCount + 1) * 4 * 4), this._scene, false, false, Texture.NEAREST_NEAREST, 1); - texture.name = "VAT" + this._mesh.skeleton.name; - return texture; - } - /** - * Serializes our vertexData to an object, with a nice string for the vertexData. - * @param vertexData The vertex array data. - * @returns This object serialized to a JS dict. - */ - serializeBakedVertexDataToObject(vertexData) { - if (!this._mesh.skeleton) { - throw new Error("No skeleton in this mesh."); - } - // this converts the float array to a serialized base64 string, ~1.3x larger - // than the original. - const boneCount = this._mesh.skeleton.bones.length; - const width = (boneCount + 1) * 4; - const height = vertexData.length / ((boneCount + 1) * 4 * 4); - const data = { - vertexData: EncodeArrayBufferToBase64(vertexData), - width, - height, - }; - return data; - } - /** - * Loads previously baked data. - * @param data The object as serialized by serializeBakedVertexDataToObject() - * @returns The array of matrix transforms for each vertex (columns) and frame (rows), as a Float32Array. - */ - loadBakedVertexDataFromObject(data) { - return new Float32Array(DecodeBase64ToBinary(data.vertexData)); - } - /** - * Serializes our vertexData to a JSON string, with a nice string for the vertexData. - * Should be called right after bakeVertexData(). - * @param vertexData The vertex array data. - * @returns This object serialized to a safe string. - */ - serializeBakedVertexDataToJSON(vertexData) { - return JSON.stringify(this.serializeBakedVertexDataToObject(vertexData)); - } - /** - * Loads previously baked data in string format. - * @param json The json string as serialized by serializeBakedVertexDataToJSON(). - * @returns The array of matrix transforms for each vertex (columns) and frame (rows), as a Float32Array. - */ - loadBakedVertexDataFromJSON(json) { - return this.loadBakedVertexDataFromObject(JSON.parse(json)); - } -} -//# sourceMappingURL=vertexAnimationBaker.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/BakedVertexAnimation/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/behavior.js - -//# sourceMappingURL=behavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Cameras/autoRotationBehavior.js - - - -/** - * The autoRotation behavior (AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction. - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior - */ -class AutoRotationBehavior { - constructor() { - this._zoomStopsAnimation = false; - this._idleRotationSpeed = 0.05; - this._idleRotationWaitTime = 2000; - this._idleRotationSpinupTime = 2000; - this.targetAlpha = null; - this._isPointerDown = false; - this._lastFrameTime = null; - this._lastInteractionTime = -Infinity; - this._cameraRotationSpeed = 0; - this._lastFrameRadius = 0; - } - /** - * Gets the name of the behavior. - */ - get name() { - return "AutoRotation"; - } - /** - * Sets the flag that indicates if user zooming should stop animation. - */ - set zoomStopsAnimation(flag) { - this._zoomStopsAnimation = flag; - } - /** - * Gets the flag that indicates if user zooming should stop animation. - */ - get zoomStopsAnimation() { - return this._zoomStopsAnimation; - } - /** - * Sets the default speed at which the camera rotates around the model. - */ - set idleRotationSpeed(speed) { - this._idleRotationSpeed = speed; - } - /** - * Gets the default speed at which the camera rotates around the model. - */ - get idleRotationSpeed() { - return this._idleRotationSpeed; - } - /** - * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating. - */ - set idleRotationWaitTime(time) { - this._idleRotationWaitTime = time; - } - /** - * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating. - */ - get idleRotationWaitTime() { - return this._idleRotationWaitTime; - } - /** - * Sets the time (milliseconds) to take to spin up to the full idle rotation speed. - */ - set idleRotationSpinupTime(time) { - this._idleRotationSpinupTime = time; - } - /** - * Gets the time (milliseconds) to take to spin up to the full idle rotation speed. - */ - get idleRotationSpinupTime() { - return this._idleRotationSpinupTime; - } - /** - * Gets a value indicating if the camera is currently rotating because of this behavior - */ - get rotationInProgress() { - return Math.abs(this._cameraRotationSpeed) > 0; - } - /** - * Initializes the behavior. - */ - init() { - // Do nothing - } - /** - * Attaches the behavior to its arc rotate camera. - * @param camera Defines the camera to attach the behavior to - */ - attach(camera) { - this._attachedCamera = camera; - const scene = this._attachedCamera.getScene(); - this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => { - if (pointerInfoPre.type === pointerEvents_PointerEventTypes.POINTERDOWN) { - this._isPointerDown = true; - return; - } - if (pointerInfoPre.type === pointerEvents_PointerEventTypes.POINTERUP) { - this._isPointerDown = false; - } - }); - this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => { - if (this._reachTargetAlpha()) { - return; - } - const now = precisionDate_PrecisionDate.Now; - let dt = 0; - if (this._lastFrameTime != null) { - dt = now - this._lastFrameTime; - } - this._lastFrameTime = now; - // Stop the animation if there is user interaction and the animation should stop for this interaction - this._applyUserInteraction(); - const timeToRotation = now - this._lastInteractionTime - this._idleRotationWaitTime; - const scale = Math.max(Math.min(timeToRotation / this._idleRotationSpinupTime, 1), 0); - this._cameraRotationSpeed = this._idleRotationSpeed * scale; - // Step camera rotation by rotation speed - if (this._attachedCamera) { - this._attachedCamera.alpha -= this._cameraRotationSpeed * (dt / 1000); - } - }); - } - /** - * Detaches the behavior from its current arc rotate camera. - */ - detach() { - if (!this._attachedCamera) { - return; - } - const scene = this._attachedCamera.getScene(); - if (this._onPrePointerObservableObserver) { - scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); - } - this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); - this._attachedCamera = null; - } - /** - * Force-reset the last interaction time - * @param customTime an optional time that will be used instead of the current last interaction time. For example `Date.now()` - */ - resetLastInteractionTime(customTime) { - this._lastInteractionTime = customTime !== null && customTime !== void 0 ? customTime : precisionDate_PrecisionDate.Now; - } - /** - * Returns true if camera alpha reaches the target alpha - * @returns true if camera alpha reaches the target alpha - */ - _reachTargetAlpha() { - if (this._attachedCamera && this.targetAlpha) { - return Math.abs(this._attachedCamera.alpha - this.targetAlpha) < math_constants_Epsilon; - } - return false; - } - /** - * Returns true if user is scrolling. - * @returns true if user is scrolling. - */ - _userIsZooming() { - if (!this._attachedCamera) { - return false; - } - return this._attachedCamera.inertialRadiusOffset !== 0; - } - _shouldAnimationStopForInteraction() { - if (!this._attachedCamera) { - return false; - } - let zoomHasHitLimit = false; - if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) { - zoomHasHitLimit = true; - } - // Update the record of previous radius - works as an approx. indicator of hitting radius limits - this._lastFrameRadius = this._attachedCamera.radius; - return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming(); - } - /** - * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. - */ - _applyUserInteraction() { - if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) { - this._lastInteractionTime = precisionDate_PrecisionDate.Now; - } - } - // Tools - _userIsMoving() { - if (!this._attachedCamera) { - return false; - } - return (this._attachedCamera.inertialAlphaOffset !== 0 || - this._attachedCamera.inertialBetaOffset !== 0 || - this._attachedCamera.inertialRadiusOffset !== 0 || - this._attachedCamera.inertialPanningX !== 0 || - this._attachedCamera.inertialPanningY !== 0 || - this._isPointerDown); - } -} -//# sourceMappingURL=autoRotationBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Cameras/bouncingBehavior.js - - -/** - * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior - */ -class BouncingBehavior { - constructor() { - /** - * The duration of the animation, in milliseconds - */ - this.transitionDuration = 450; - /** - * Length of the distance animated by the transition when lower radius is reached - */ - this.lowerRadiusTransitionRange = 2; - /** - * Length of the distance animated by the transition when upper radius is reached - */ - this.upperRadiusTransitionRange = -2; - this._autoTransitionRange = false; - // Animations - this._radiusIsAnimating = false; - this._radiusBounceTransition = null; - this._animatables = new Array(); - } - /** - * Gets the name of the behavior. - */ - get name() { - return "Bouncing"; - } - /** - * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically - */ - get autoTransitionRange() { - return this._autoTransitionRange; - } - /** - * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically - * Transition ranges will be set to 5% of the bounding box diagonal in world space - */ - set autoTransitionRange(value) { - if (this._autoTransitionRange === value) { - return; - } - this._autoTransitionRange = value; - const camera = this._attachedCamera; - if (!camera) { - return; - } - if (value) { - this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((mesh) => { - if (!mesh) { - return; - } - mesh.computeWorldMatrix(true); - const diagonal = mesh.getBoundingInfo().diagonalLength; - this.lowerRadiusTransitionRange = diagonal * 0.05; - this.upperRadiusTransitionRange = diagonal * 0.05; - }); - } - else if (this._onMeshTargetChangedObserver) { - camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); - } - } - /** - * Initializes the behavior. - */ - init() { - // Do nothing - } - /** - * Attaches the behavior to its arc rotate camera. - * @param camera Defines the camera to attach the behavior to - */ - attach(camera) { - this._attachedCamera = camera; - this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => { - if (!this._attachedCamera) { - return; - } - // Add the bounce animation to the lower radius limit - if (this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)) { - this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange); - } - // Add the bounce animation to the upper radius limit - if (this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)) { - this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange); - } - }); - } - /** - * Detaches the behavior from its current arc rotate camera. - */ - detach() { - if (!this._attachedCamera) { - return; - } - if (this._onAfterCheckInputsObserver) { - this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); - } - if (this._onMeshTargetChangedObserver) { - this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); - } - this._attachedCamera = null; - } - /** - * Checks if the camera radius is at the specified limit. Takes into account animation locks. - * @param radiusLimit The limit to check against. - * @returns Bool to indicate if at limit. - */ - _isRadiusAtLimit(radiusLimit) { - if (!this._attachedCamera) { - return false; - } - if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) { - return true; - } - return false; - } - /** - * Applies an animation to the radius of the camera, extending by the radiusDelta. - * @param radiusDelta The delta by which to animate to. Can be negative. - */ - _applyBoundRadiusAnimation(radiusDelta) { - if (!this._attachedCamera) { - return; - } - if (!this._radiusBounceTransition) { - BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode); - this._radiusBounceTransition = animation_Animation.CreateAnimation("radius", animation_Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction); - } - // Prevent zoom until bounce has completed - this._cachedWheelPrecision = this._attachedCamera.wheelPrecision; - this._attachedCamera.wheelPrecision = Infinity; - this._attachedCamera.inertialRadiusOffset = 0; - // Animate to the radius limit - this.stopAllAnimations(); - this._radiusIsAnimating = true; - const animatable = animation_Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, () => this._clearAnimationLocks()); - if (animatable) { - this._animatables.push(animatable); - } - } - /** - * Removes all animation locks. Allows new animations to be added to any of the camera properties. - */ - _clearAnimationLocks() { - this._radiusIsAnimating = false; - if (this._attachedCamera) { - this._attachedCamera.wheelPrecision = this._cachedWheelPrecision; - } - } - /** - * Stops and removes all animations that have been applied to the camera - */ - stopAllAnimations() { - if (this._attachedCamera) { - this._attachedCamera.animations = []; - } - while (this._animatables.length) { - this._animatables[0].onAnimationEnd = null; - this._animatables[0].stop(); - this._animatables.shift(); - } - } -} -/** - * The easing function used by animations - */ -BouncingBehavior.EasingFunction = new BackEase(0.3); -/** - * The easing mode used by animations - */ -BouncingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEOUT; -//# sourceMappingURL=bouncingBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Cameras/framingBehavior.js - - - - - - -/** - * 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. - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior - */ -class FramingBehavior { - constructor() { - /** - * An event triggered when the animation to zoom on target mesh has ended - */ - this.onTargetFramingAnimationEndObservable = new observable_Observable(); - this._mode = FramingBehavior.FitFrustumSidesMode; - this._radiusScale = 1.0; - this._positionScale = 0.5; - this._defaultElevation = 0.3; - this._elevationReturnTime = 1500; - this._elevationReturnWaitTime = 1000; - this._zoomStopsAnimation = false; - this._framingTime = 1500; - /** - * Define if the behavior should automatically change the configured - * camera limits and sensibilities. - */ - this.autoCorrectCameraLimitsAndSensibility = true; - this._isPointerDown = false; - this._lastInteractionTime = -Infinity; - // Framing control - this._animatables = new Array(); - this._betaIsAnimating = false; - } - /** - * Gets the name of the behavior. - */ - get name() { - return "Framing"; - } - /** - * Sets the current mode used by the behavior - */ - set mode(mode) { - this._mode = mode; - } - /** - * Gets current mode used by the behavior. - */ - get mode() { - return this._mode; - } - /** - * Sets the scale applied to the radius (1 by default) - */ - set radiusScale(radius) { - this._radiusScale = radius; - } - /** - * Gets the scale applied to the radius - */ - get radiusScale() { - return this._radiusScale; - } - /** - * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. - */ - set positionScale(scale) { - this._positionScale = scale; - } - /** - * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. - */ - get positionScale() { - return this._positionScale; - } - /** - * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle - * behaviour is triggered, in radians. - */ - set defaultElevation(elevation) { - this._defaultElevation = elevation; - } - /** - * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle - * behaviour is triggered, in radians. - */ - get defaultElevation() { - return this._defaultElevation; - } - /** - * Sets the time (in milliseconds) taken to return to the default beta position. - * Negative value indicates camera should not return to default. - */ - set elevationReturnTime(speed) { - this._elevationReturnTime = speed; - } - /** - * Gets the time (in milliseconds) taken to return to the default beta position. - * Negative value indicates camera should not return to default. - */ - get elevationReturnTime() { - return this._elevationReturnTime; - } - /** - * Sets the delay (in milliseconds) taken before the camera returns to the default beta position. - */ - set elevationReturnWaitTime(time) { - this._elevationReturnWaitTime = time; - } - /** - * Gets the delay (in milliseconds) taken before the camera returns to the default beta position. - */ - get elevationReturnWaitTime() { - return this._elevationReturnWaitTime; - } - /** - * Sets the flag that indicates if user zooming should stop animation. - */ - set zoomStopsAnimation(flag) { - this._zoomStopsAnimation = flag; - } - /** - * Gets the flag that indicates if user zooming should stop animation. - */ - get zoomStopsAnimation() { - return this._zoomStopsAnimation; - } - /** - * Sets the transition time when framing the mesh, in milliseconds - */ - set framingTime(time) { - this._framingTime = time; - } - /** - * Gets the transition time when framing the mesh, in milliseconds - */ - get framingTime() { - return this._framingTime; - } - /** - * Initializes the behavior. - */ - init() { - // Do nothing - } - /** - * Attaches the behavior to its arc rotate camera. - * @param camera Defines the camera to attach the behavior to - */ - attach(camera) { - this._attachedCamera = camera; - const scene = this._attachedCamera.getScene(); - FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode); - this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => { - if (pointerInfoPre.type === pointerEvents_PointerEventTypes.POINTERDOWN) { - this._isPointerDown = true; - return; - } - if (pointerInfoPre.type === pointerEvents_PointerEventTypes.POINTERUP) { - this._isPointerDown = false; - } - }); - this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((mesh) => { - if (mesh) { - this.zoomOnMesh(mesh, undefined, () => { - this.onTargetFramingAnimationEndObservable.notifyObservers(); - }); - } - }); - this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => { - // Stop the animation if there is user interaction and the animation should stop for this interaction - this._applyUserInteraction(); - // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it - // back to the default position after a given timeout - this._maintainCameraAboveGround(); - }); - } - /** - * Detaches the behavior from its current arc rotate camera. - */ - detach() { - if (!this._attachedCamera) { - return; - } - const scene = this._attachedCamera.getScene(); - if (this._onPrePointerObservableObserver) { - scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); - } - if (this._onAfterCheckInputsObserver) { - this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); - } - if (this._onMeshTargetChangedObserver) { - this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); - } - this._attachedCamera = null; - } - /** - * Targets the given mesh and updates zoom level accordingly. - * @param mesh The mesh to target. - * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh - * @param onAnimationEnd Callback triggered at the end of the framing animation - */ - zoomOnMesh(mesh, focusOnOriginXZ = false, onAnimationEnd = null) { - mesh.computeWorldMatrix(true); - const boundingBox = mesh.getBoundingInfo().boundingBox; - this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd); - } - /** - * Targets the given mesh with its children and updates zoom level accordingly. - * @param mesh The mesh to target. - * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh - * @param onAnimationEnd Callback triggered at the end of the framing animation - */ - zoomOnMeshHierarchy(mesh, focusOnOriginXZ = false, onAnimationEnd = null) { - mesh.computeWorldMatrix(true); - const boundingBox = mesh.getHierarchyBoundingVectors(true); - this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd); - } - /** - * Targets the given meshes with their children and updates zoom level accordingly. - * @param meshes The mesh to target. - * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh - * @param onAnimationEnd Callback triggered at the end of the framing animation - */ - zoomOnMeshesHierarchy(meshes, focusOnOriginXZ = false, onAnimationEnd = null) { - const min = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - const max = new math_vector_Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); - for (let i = 0; i < meshes.length; i++) { - const boundingInfo = meshes[i].getHierarchyBoundingVectors(true); - math_vector_Vector3.CheckExtends(boundingInfo.min, min, max); - math_vector_Vector3.CheckExtends(boundingInfo.max, min, max); - } - this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd); - } - /** - * Targets the bounding box info defined by its extends and updates zoom level accordingly. - * @param minimumWorld Determines the smaller position of the bounding box extend - * @param maximumWorld Determines the bigger position of the bounding box extend - * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh - * @param onAnimationEnd Callback triggered at the end of the framing animation - * @returns true if the zoom was done - */ - zoomOnBoundingInfo(minimumWorld, maximumWorld, focusOnOriginXZ = false, onAnimationEnd = null) { - let zoomTarget; - if (!this._attachedCamera) { - return false; - } - // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY - const bottom = minimumWorld.y; - const top = maximumWorld.y; - const zoomTargetY = bottom + (top - bottom) * this._positionScale; - const radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5); - if (focusOnOriginXZ) { - zoomTarget = new math_vector_Vector3(0, zoomTargetY, 0); - } - else { - const centerWorld = minimumWorld.add(radiusWorld); - zoomTarget = new math_vector_Vector3(centerWorld.x, zoomTargetY, centerWorld.z); - } - if (!this._vectorTransition) { - this._vectorTransition = animation_Animation.CreateAnimation("target", animation_Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction); - } - this._betaIsAnimating = true; - let animatable = animation_Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime); - if (animatable) { - this._animatables.push(animatable); - } - // sets the radius and lower radius bounds - // Small delta ensures camera is not always at lower zoom limit. - let radius = 0; - if (this._mode === FramingBehavior.FitFrustumSidesMode) { - const position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); - if (this.autoCorrectCameraLimitsAndSensibility) { - this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ; - } - radius = position; - } - else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) { - radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); - if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) { - this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ; - } - } - // Set sensibilities - if (this.autoCorrectCameraLimitsAndSensibility) { - const extend = maximumWorld.subtract(minimumWorld).length(); - this._attachedCamera.panningSensibility = 5000 / extend; - this._attachedCamera.wheelPrecision = 100 / radius; - } - // transition to new radius - if (!this._radiusTransition) { - this._radiusTransition = animation_Animation.CreateAnimation("radius", animation_Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); - } - animatable = animation_Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, () => { - this.stopAllAnimations(); - if (onAnimationEnd) { - onAnimationEnd(); - } - if (this._attachedCamera && this._attachedCamera.useInputToRestoreState) { - this._attachedCamera.storeState(); - } - }); - if (animatable) { - this._animatables.push(animatable); - } - return true; - } - /** - * Calculates the lowest radius for the camera based on the bounding box of the mesh. - * @param minimumWorld - * @param maximumWorld - * @returns The minimum distance from the primary mesh's center point at which the camera must be kept in order - * to fully enclose the mesh in the viewing frustum. - */ - _calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld) { - const size = maximumWorld.subtract(minimumWorld); - const boxVectorGlobalDiagonal = size.length(); - const frustumSlope = this._getFrustumSlope(); - // Formula for setting distance - // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene) - const radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5; - // Horizon distance - const radius = radiusWithoutFraming * this._radiusScale; - const distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x)); - const distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y)); - let distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum); - const camera = this._attachedCamera; - if (!camera) { - return 0; - } - if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) { - // Don't exceed the requested limit - distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance; - } - // Don't exceed the upper radius limit - if (camera.upperRadiusLimit) { - distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance; - } - return distance; - } - /** - * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera - * is automatically returned to its default position (expected to be above ground plane). - */ - _maintainCameraAboveGround() { - if (this._elevationReturnTime < 0) { - return; - } - const timeSinceInteraction = precisionDate_PrecisionDate.Now - this._lastInteractionTime; - const defaultBeta = Math.PI * 0.5 - this._defaultElevation; - const limitBeta = Math.PI * 0.5; - // Bring the camera back up if below the ground plane - if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) { - this._betaIsAnimating = true; - //Transition to new position - this.stopAllAnimations(); - if (!this._betaTransition) { - this._betaTransition = animation_Animation.CreateAnimation("beta", animation_Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); - } - const animatabe = animation_Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, () => { - this._clearAnimationLocks(); - this.stopAllAnimations(); - }); - if (animatabe) { - this._animatables.push(animatabe); - } - } - } - /** - * Returns the frustum slope based on the canvas ratio and camera FOV - * @returns The frustum slope represented as a Vector2 with X and Y slopes - */ - _getFrustumSlope() { - // Calculate the viewport ratio - // Aspect Ratio is Height/Width. - const camera = this._attachedCamera; - if (!camera) { - return math_vector_Vector2.Zero(); - } - const engine = camera.getScene().getEngine(); - const aspectRatio = engine.getAspectRatio(camera); - // Camera FOV is the vertical field of view (top-bottom) in radians. - // Slope of the frustum top/bottom planes in view space, relative to the forward vector. - const frustumSlopeY = Math.tan(camera.fov / 2); - // Slope of the frustum left/right planes in view space, relative to the forward vector. - // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit - // along the forward vector. - const frustumSlopeX = frustumSlopeY * aspectRatio; - return new math_vector_Vector2(frustumSlopeX, frustumSlopeY); - } - /** - * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties. - */ - _clearAnimationLocks() { - this._betaIsAnimating = false; - } - /** - * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. - */ - _applyUserInteraction() { - if (this.isUserIsMoving) { - this._lastInteractionTime = precisionDate_PrecisionDate.Now; - this.stopAllAnimations(); - this._clearAnimationLocks(); - } - } - /** - * Stops and removes all animations that have been applied to the camera - */ - stopAllAnimations() { - if (this._attachedCamera) { - this._attachedCamera.animations = []; - } - while (this._animatables.length) { - if (this._animatables[0]) { - this._animatables[0].onAnimationEnd = null; - this._animatables[0].stop(); - } - this._animatables.shift(); - } - } - /** - * Gets a value indicating if the user is moving the camera - */ - get isUserIsMoving() { - if (!this._attachedCamera) { - return false; - } - return (this._attachedCamera.inertialAlphaOffset !== 0 || - this._attachedCamera.inertialBetaOffset !== 0 || - this._attachedCamera.inertialRadiusOffset !== 0 || - this._attachedCamera.inertialPanningX !== 0 || - this._attachedCamera.inertialPanningY !== 0 || - this._isPointerDown); - } -} -/** - * The easing function used by animations - */ -FramingBehavior.EasingFunction = new ExponentialEase(); -/** - * The easing mode used by animations - */ -FramingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEINOUT; -// Statics -/** - * The camera can move all the way towards the mesh. - */ -FramingBehavior.IgnoreBoundsSizeMode = 0; -/** - * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides - */ -FramingBehavior.FitFrustumSidesMode = 1; -//# sourceMappingURL=framingBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Cameras/index.js - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Meshes/attachToBoxBehavior.js - -/** - * @internal - */ -class FaceDirectionInfo { - constructor(direction, rotatedDirection = new Vector3(), diff = 0, ignore = false) { - this.direction = direction; - this.rotatedDirection = rotatedDirection; - this.diff = diff; - this.ignore = ignore; - } -} -/** - * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera - */ -class AttachToBoxBehavior { - /** - * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera - * @param _ui The transform node that should be attached to the mesh - */ - constructor(_ui) { - this._ui = _ui; - /** - * The name of the behavior - */ - this.name = "AttachToBoxBehavior"; - /** - * The distance away from the face of the mesh that the UI should be attached to (default: 0.15) - */ - this.distanceAwayFromFace = 0.15; - /** - * The distance from the bottom of the face that the UI should be attached to (default: 0.15) - */ - this.distanceAwayFromBottomOfFace = 0.15; - this._faceVectors = [ - new FaceDirectionInfo(Vector3.Up()), - new FaceDirectionInfo(Vector3.Down()), - new FaceDirectionInfo(Vector3.Left()), - new FaceDirectionInfo(Vector3.Right()), - new FaceDirectionInfo(Vector3.Forward()), - new FaceDirectionInfo(Vector3.Forward().scaleInPlace(-1)), - ]; - this._tmpMatrix = new Matrix(); - this._tmpVector = new Vector3(); - this._zeroVector = Vector3.Zero(); - this._lookAtTmpMatrix = new Matrix(); - /* Does nothing */ - } - /** - * Initializes the behavior - */ - init() { - /* Does nothing */ - } - _closestFace(targetDirection) { - // Go over each face and calculate the angle between the face's normal and targetDirection - this._faceVectors.forEach((v) => { - if (!this._target.rotationQuaternion) { - this._target.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._target.rotation.y, this._target.rotation.x, this._target.rotation.z); - } - this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix); - Vector3.TransformCoordinatesToRef(v.direction, this._tmpMatrix, v.rotatedDirection); - v.diff = Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, Vector3.Cross(v.rotatedDirection, targetDirection)); - }); - // Return the face information of the one with the normal closest to target direction - return this._faceVectors.reduce((min, p) => { - if (min.ignore) { - return p; - } - else if (p.ignore) { - return min; - } - else { - return min.diff < p.diff ? min : p; - } - }, this._faceVectors[0]); - } - _lookAtToRef(pos, up = new Vector3(0, 1, 0), ref) { - Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix); - this._lookAtTmpMatrix.invert(); - Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref); - } - /** - * Attaches the AttachToBoxBehavior to the passed in mesh - * @param target The mesh that the specified node will be attached to - */ - attach(target) { - this._target = target; - this._scene = this._target.getScene(); - // Every frame, update the app bars position - this._onRenderObserver = this._scene.onBeforeRenderObservable.add(() => { - if (!this._scene.activeCamera) { - return; - } - // Find the face closest to the cameras position - let cameraPos = this._scene.activeCamera.position; - if (this._scene.activeCamera.devicePosition) { - cameraPos = this._scene.activeCamera.devicePosition; - } - const facing = this._closestFace(cameraPos.subtract(target.position)); - if (this._scene.activeCamera.leftCamera) { - this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix); - } - else { - this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix); - } - // Get camera up direction - Vector3.TransformCoordinatesToRef(Vector3.Up(), this._tmpMatrix, this._tmpVector); - // Ignore faces to not select a parallel face for the up vector of the UI - this._faceVectors.forEach((v) => { - if (facing.direction.x && v.direction.x) { - v.ignore = true; - } - if (facing.direction.y && v.direction.y) { - v.ignore = true; - } - if (facing.direction.z && v.direction.z) { - v.ignore = true; - } - }); - const facingUp = this._closestFace(this._tmpVector); - // Unignore faces - this._faceVectors.forEach((v) => { - v.ignore = false; - }); - // Position the app bar on that face - this._ui.position.copyFrom(target.position); - if (facing.direction.x) { - facing.rotatedDirection.scaleToRef(target.scaling.x / 2 + this.distanceAwayFromFace, this._tmpVector); - this._ui.position.addInPlace(this._tmpVector); - } - if (facing.direction.y) { - facing.rotatedDirection.scaleToRef(target.scaling.y / 2 + this.distanceAwayFromFace, this._tmpVector); - this._ui.position.addInPlace(this._tmpVector); - } - if (facing.direction.z) { - facing.rotatedDirection.scaleToRef(target.scaling.z / 2 + this.distanceAwayFromFace, this._tmpVector); - this._ui.position.addInPlace(this._tmpVector); - } - // Rotate to be oriented properly to the camera - if (!this._ui.rotationQuaternion) { - this._ui.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._ui.rotation.y, this._ui.rotation.x, this._ui.rotation.z); - } - facing.rotatedDirection.scaleToRef(-1, this._tmpVector); - this._lookAtToRef(this._tmpVector, facingUp.rotatedDirection, this._ui.rotationQuaternion); - // Place ui the correct distance from the bottom of the mesh - if (facingUp.direction.x) { - this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace - target.scaling.x / 2, this._tmpVector); - } - if (facingUp.direction.y) { - this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace - target.scaling.y / 2, this._tmpVector); - } - if (facingUp.direction.z) { - this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace - target.scaling.z / 2, this._tmpVector); - } - this._ui.position.addInPlace(this._tmpVector); - }); - } - /** - * Detaches the behavior from the mesh - */ - detach() { - this._scene.onBeforeRenderObservable.remove(this._onRenderObserver); - } -} -//# sourceMappingURL=attachToBoxBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Meshes/fadeInOutBehavior.js -/** - * A behavior that when attached to a mesh will allow the mesh to fade in and out - */ -class FadeInOutBehavior { - /** - * Time in milliseconds to delay before fading in (Default: 0) - * Will set both fade in and out delay to the same value - */ - get delay() { - return this.fadeInDelay; - } - set delay(value) { - this.fadeInDelay = value; - this.fadeOutDelay = value; - } - /** - * Instantiates the FadeInOutBehavior - */ - constructor() { - /** - * Time in milliseconds to delay before fading in (Default: 0) - */ - this.fadeInDelay = 0; - /** - * Time in milliseconds to delay before fading out (Default: 0) - */ - this.fadeOutDelay = 0; - /** - * Time in milliseconds for the mesh to fade in (Default: 300) - */ - this.fadeInTime = 300; - /** - * Time in milliseconds for the mesh to fade out (Default: 300) - */ - this.fadeOutTime = 300; - this._millisecondsPerFrame = 1000 / 60; - this._hovered = false; - this._hoverValue = 0; - this._ownerNode = null; - this._delay = 0; - this._time = 300; - this._update = () => { - if (this._ownerNode) { - this._hoverValue += this._hovered ? this._millisecondsPerFrame : -this._millisecondsPerFrame; - this._setAllVisibility(this._ownerNode, (this._hoverValue - this._delay) / this._time); - if (this._ownerNode.visibility > 1) { - this._setAllVisibility(this._ownerNode, 1); - if (this._hoverValue > this._time) { - this._hoverValue = this._time; - this._detachObserver(); - return; - } - } - else if (this._ownerNode.visibility < 0) { - this._setAllVisibility(this._ownerNode, 0); - if (this._hoverValue < 0) { - this._hoverValue = 0; - this._detachObserver(); - return; - } - } - this._attachObserver(); - } - }; - } - /** - * The name of the behavior - */ - get name() { - return "FadeInOut"; - } - /** - * Initializes the behavior - */ - init() { } - /** - * Attaches the fade behavior on the passed in mesh - * @param ownerNode The mesh that will be faded in/out once attached - */ - attach(ownerNode) { - this._ownerNode = ownerNode; - this._setAllVisibility(this._ownerNode, 0); - } - /** - * Detaches the behavior from the mesh - */ - detach() { - this._ownerNode = null; - } - /** - * Triggers the mesh to begin fading in (or out) - * @param fadeIn if the object should fade in or out (true to fade in) - */ - fadeIn(fadeIn = true) { - this._delay = fadeIn ? this.fadeInDelay : this.fadeOutDelay; - this._time = fadeIn ? this.fadeInTime : this.fadeOutTime; - // Cancel any pending updates - this._detachObserver(); - // If fading in and already visible or fading out and already not visible do nothing - if (this._ownerNode && ((fadeIn && this._ownerNode.visibility >= 1) || (!fadeIn && this._ownerNode.visibility <= 0))) { - return; - } - this._hovered = fadeIn; - if (!this._hovered) { - // Make the delay the negative of fadeout delay so the hoverValue is kept above 1 until - // fadeOutDelay has elapsed - this._delay *= -1; - } - // Reset the hoverValue. This is necessary because we may have been fading out, e.g. but not yet reached - // the delay, so the hover value is greater than 1 - if (this._ownerNode.visibility >= 1) { - this._hoverValue = this._time; - } - else if (this._ownerNode.visibility <= 0) { - this._hoverValue = 0; - } - this._update(); - } - /** - * Triggers the mesh to begin fading out - */ - fadeOut() { - this.fadeIn(false); - } - _setAllVisibility(mesh, value) { - mesh.visibility = value; - mesh.getChildMeshes().forEach((c) => { - this._setAllVisibility(c, value); - }); - } - _attachObserver() { - var _a; - if (!this._onBeforeRenderObserver) { - this._onBeforeRenderObserver = (_a = this._ownerNode) === null || _a === void 0 ? void 0 : _a.getScene().onBeforeRenderObservable.add(this._update); - } - } - _detachObserver() { - var _a; - if (this._onBeforeRenderObserver) { - (_a = this._ownerNode) === null || _a === void 0 ? void 0 : _a.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver); - this._onBeforeRenderObserver = null; - } - } -} -//# sourceMappingURL=fadeInOutBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Culling/ray.js - - - - - - - -/** - * Class representing a ray with position and direction - */ -class ray_Ray { - /** - * Creates a new ray - * @param origin origin point - * @param direction direction - * @param length length of the ray - */ - constructor( - /** origin point */ - origin, - /** direction */ - direction, - /** length of the ray */ - length = Number.MAX_VALUE) { - this.origin = origin; - this.direction = direction; - this.length = length; - } - // Methods - /** - * Clone the current ray - * @returns a new ray - */ - clone() { - return new ray_Ray(this.origin.clone(), this.direction.clone(), this.length); - } - /** - * Checks if the ray intersects a box - * This does not account for the ray length by design to improve perfs. - * @param minimum bound of the box - * @param maximum bound of the box - * @param intersectionTreshold extra extend to be added to the box in all direction - * @returns if the box was hit - */ - intersectsBoxMinMax(minimum, maximum, intersectionTreshold = 0) { - const newMinimum = ray_Ray._TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold); - const newMaximum = ray_Ray._TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold); - let d = 0.0; - let maxValue = Number.MAX_VALUE; - let inv; - let min; - let max; - let temp; - if (Math.abs(this.direction.x) < 0.0000001) { - if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) { - return false; - } - } - else { - inv = 1.0 / this.direction.x; - min = (newMinimum.x - this.origin.x) * inv; - max = (newMaximum.x - this.origin.x) * inv; - if (max === -Infinity) { - max = Infinity; - } - if (min > max) { - temp = min; - min = max; - max = temp; - } - d = Math.max(min, d); - maxValue = Math.min(max, maxValue); - if (d > maxValue) { - return false; - } - } - if (Math.abs(this.direction.y) < 0.0000001) { - if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) { - return false; - } - } - else { - inv = 1.0 / this.direction.y; - min = (newMinimum.y - this.origin.y) * inv; - max = (newMaximum.y - this.origin.y) * inv; - if (max === -Infinity) { - max = Infinity; - } - if (min > max) { - temp = min; - min = max; - max = temp; - } - d = Math.max(min, d); - maxValue = Math.min(max, maxValue); - if (d > maxValue) { - return false; - } - } - if (Math.abs(this.direction.z) < 0.0000001) { - if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) { - return false; - } - } - else { - inv = 1.0 / this.direction.z; - min = (newMinimum.z - this.origin.z) * inv; - max = (newMaximum.z - this.origin.z) * inv; - if (max === -Infinity) { - max = Infinity; - } - if (min > max) { - temp = min; - min = max; - max = temp; - } - d = Math.max(min, d); - maxValue = Math.min(max, maxValue); - if (d > maxValue) { - return false; - } - } - return true; - } - /** - * Checks if the ray intersects a box - * This does not account for the ray lenght by design to improve perfs. - * @param box the bounding box to check - * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction - * @returns if the box was hit - */ - intersectsBox(box, intersectionTreshold = 0) { - return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold); - } - /** - * If the ray hits a sphere - * @param sphere the bounding sphere to check - * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction - * @returns true if it hits the sphere - */ - intersectsSphere(sphere, intersectionTreshold = 0) { - const x = sphere.center.x - this.origin.x; - const y = sphere.center.y - this.origin.y; - const z = sphere.center.z - this.origin.z; - const pyth = x * x + y * y + z * z; - const radius = sphere.radius + intersectionTreshold; - const rr = radius * radius; - if (pyth <= rr) { - return true; - } - const dot = x * this.direction.x + y * this.direction.y + z * this.direction.z; - if (dot < 0.0) { - return false; - } - const temp = pyth - dot * dot; - return temp <= rr; - } - /** - * If the ray hits a triange - * @param vertex0 triangle vertex - * @param vertex1 triangle vertex - * @param vertex2 triangle vertex - * @returns intersection information if hit - */ - intersectsTriangle(vertex0, vertex1, vertex2) { - const edge1 = ray_Ray._TmpVector3[0]; - const edge2 = ray_Ray._TmpVector3[1]; - const pvec = ray_Ray._TmpVector3[2]; - const tvec = ray_Ray._TmpVector3[3]; - const qvec = ray_Ray._TmpVector3[4]; - vertex1.subtractToRef(vertex0, edge1); - vertex2.subtractToRef(vertex0, edge2); - math_vector_Vector3.CrossToRef(this.direction, edge2, pvec); - const det = math_vector_Vector3.Dot(edge1, pvec); - if (det === 0) { - return null; - } - const invdet = 1 / det; - this.origin.subtractToRef(vertex0, tvec); - const bv = math_vector_Vector3.Dot(tvec, pvec) * invdet; - if (bv < 0 || bv > 1.0) { - return null; - } - math_vector_Vector3.CrossToRef(tvec, edge1, qvec); - const bw = math_vector_Vector3.Dot(this.direction, qvec) * invdet; - if (bw < 0 || bv + bw > 1.0) { - return null; - } - //check if the distance is longer than the predefined length. - const distance = math_vector_Vector3.Dot(edge2, qvec) * invdet; - if (distance > this.length) { - return null; - } - return new IntersectionInfo(1 - bv - bw, bv, distance); - } - /** - * Checks if ray intersects a plane - * @param plane the plane to check - * @returns the distance away it was hit - */ - intersectsPlane(plane) { - let distance; - const result1 = math_vector_Vector3.Dot(plane.normal, this.direction); - if (Math.abs(result1) < 9.99999997475243e-7) { - return null; - } - else { - const result2 = math_vector_Vector3.Dot(plane.normal, this.origin); - distance = (-plane.d - result2) / result1; - if (distance < 0.0) { - if (distance < -9.99999997475243e-7) { - return null; - } - else { - return 0; - } - } - return distance; - } - } - /** - * Calculate the intercept of a ray on a given axis - * @param axis to check 'x' | 'y' | 'z' - * @param offset from axis interception (i.e. an offset of 1y is intercepted above ground) - * @returns a vector containing the coordinates where 'axis' is equal to zero (else offset), or null if there is no intercept. - */ - intersectsAxis(axis, offset = 0) { - switch (axis) { - case "y": { - const t = (this.origin.y - offset) / this.direction.y; - if (t > 0) { - return null; - } - return new math_vector_Vector3(this.origin.x + this.direction.x * -t, offset, this.origin.z + this.direction.z * -t); - } - case "x": { - const t = (this.origin.x - offset) / this.direction.x; - if (t > 0) { - return null; - } - return new math_vector_Vector3(offset, this.origin.y + this.direction.y * -t, this.origin.z + this.direction.z * -t); - } - case "z": { - const t = (this.origin.z - offset) / this.direction.z; - if (t > 0) { - return null; - } - return new math_vector_Vector3(this.origin.x + this.direction.x * -t, this.origin.y + this.direction.y * -t, offset); - } - default: - return null; - } - } - /** - * 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, - * irrespective of orientation. - * @param mesh the mesh to check - * @param fastCheck defines if the first intersection will be used (and not the closest) - * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected - * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default) - * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point - * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check - * @returns picking info of the intersection - */ - intersectsMesh(mesh, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) { - const tm = math_vector_TmpVectors.Matrix[0]; - mesh.getWorldMatrix().invertToRef(tm); - if (this._tmpRay) { - ray_Ray.TransformToRef(this, tm, this._tmpRay); - } - else { - this._tmpRay = ray_Ray.Transform(this, tm); - } - return mesh.intersects(this._tmpRay, fastCheck, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo); - } - /** - * Checks if ray intersects a mesh - * @param meshes the meshes to check - * @param fastCheck defines if the first intersection will be used (and not the closest) - * @param results array to store result in - * @returns Array of picking infos - */ - intersectsMeshes(meshes, fastCheck, results) { - if (results) { - results.length = 0; - } - else { - results = []; - } - for (let i = 0; i < meshes.length; i++) { - const pickInfo = this.intersectsMesh(meshes[i], fastCheck); - if (pickInfo.hit) { - results.push(pickInfo); - } - } - results.sort(this._comparePickingInfo); - return results; - } - _comparePickingInfo(pickingInfoA, pickingInfoB) { - if (pickingInfoA.distance < pickingInfoB.distance) { - return -1; - } - else if (pickingInfoA.distance > pickingInfoB.distance) { - return 1; - } - else { - return 0; - } - } - /** - * Intersection test between the ray and a given segment within a given tolerance (threshold) - * @param sega the first point of the segment to test the intersection against - * @param segb the second point of the segment to test the intersection against - * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful - * @returns the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection - */ - intersectionSegment(sega, segb, threshold) { - const o = this.origin; - const u = math_vector_TmpVectors.Vector3[0]; - const rsegb = math_vector_TmpVectors.Vector3[1]; - const v = math_vector_TmpVectors.Vector3[2]; - const w = math_vector_TmpVectors.Vector3[3]; - segb.subtractToRef(sega, u); - this.direction.scaleToRef(ray_Ray._Rayl, v); - o.addToRef(v, rsegb); - sega.subtractToRef(o, w); - const a = math_vector_Vector3.Dot(u, u); // always >= 0 - const b = math_vector_Vector3.Dot(u, v); - const c = math_vector_Vector3.Dot(v, v); // always >= 0 - const d = math_vector_Vector3.Dot(u, w); - const e = math_vector_Vector3.Dot(v, w); - const D = a * c - b * b; // always >= 0 - let sN, sD = D; // sc = sN / sD, default sD = D >= 0 - let tN, tD = D; // tc = tN / tD, default tD = D >= 0 - // compute the line parameters of the two closest points - if (D < ray_Ray._Smallnum) { - // the lines are almost parallel - sN = 0.0; // force using point P0 on segment S1 - sD = 1.0; // to prevent possible division by 0.0 later - tN = e; - tD = c; - } - else { - // get the closest points on the infinite lines - sN = b * e - c * d; - tN = a * e - b * d; - if (sN < 0.0) { - // sc < 0 => the s=0 edge is visible - sN = 0.0; - tN = e; - tD = c; - } - else if (sN > sD) { - // sc > 1 => the s=1 edge is visible - sN = sD; - tN = e + b; - tD = c; - } - } - if (tN < 0.0) { - // tc < 0 => the t=0 edge is visible - tN = 0.0; - // recompute sc for this edge - if (-d < 0.0) { - sN = 0.0; - } - else if (-d > a) { - sN = sD; - } - else { - sN = -d; - sD = a; - } - } - else if (tN > tD) { - // tc > 1 => the t=1 edge is visible - tN = tD; - // recompute sc for this edge - if (-d + b < 0.0) { - sN = 0; - } - else if (-d + b > a) { - sN = sD; - } - else { - sN = -d + b; - sD = a; - } - } - // finally do the division to get sc and tc - const sc = Math.abs(sN) < ray_Ray._Smallnum ? 0.0 : sN / sD; - const tc = Math.abs(tN) < ray_Ray._Smallnum ? 0.0 : tN / tD; - // get the difference of the two closest points - const qtc = math_vector_TmpVectors.Vector3[4]; - v.scaleToRef(tc, qtc); - const qsc = math_vector_TmpVectors.Vector3[5]; - u.scaleToRef(sc, qsc); - qsc.addInPlace(w); - const dP = math_vector_TmpVectors.Vector3[6]; - qsc.subtractToRef(qtc, dP); // = S1(sc) - S2(tc) - const isIntersected = tc > 0 && tc <= this.length && dP.lengthSquared() < threshold * threshold; // return intersection result - if (isIntersected) { - return qsc.length(); - } - return -1; - } - /** - * Update the ray from viewport position - * @param x position - * @param y y position - * @param viewportWidth viewport width - * @param viewportHeight viewport height - * @param world world matrix - * @param view view matrix - * @param projection projection matrix - * @param enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default) - * @returns this ray updated - */ - update(x, y, viewportWidth, viewportHeight, world, view, projection, enableDistantPicking = false) { - if (enableDistantPicking) { - // With world matrices having great values (like 8000000000 on 1 or more scaling or position axis), - // multiplying view/projection/world and doing invert will result in loss of float precision in the matrix. - // One way to fix it is to compute the ray with world at identity then transform the ray in object space. - // This is slower (2 matrix inverts instead of 1) but precision is preserved. - // This is hidden behind `EnableDistantPicking` flag (default is false) - if (!ray_Ray._RayDistant) { - ray_Ray._RayDistant = ray_Ray.Zero(); - } - ray_Ray._RayDistant.unprojectRayToRef(x, y, viewportWidth, viewportHeight, math_vector_Matrix.IdentityReadOnly, view, projection); - const tm = math_vector_TmpVectors.Matrix[0]; - world.invertToRef(tm); - ray_Ray.TransformToRef(ray_Ray._RayDistant, tm, this); - } - else { - this.unprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection); - } - return this; - } - // Statics - /** - * Creates a ray with origin and direction of 0,0,0 - * @returns the new ray - */ - static Zero() { - return new ray_Ray(math_vector_Vector3.Zero(), math_vector_Vector3.Zero()); - } - /** - * Creates a new ray from screen space and viewport - * @param x position - * @param y y position - * @param viewportWidth viewport width - * @param viewportHeight viewport height - * @param world world matrix - * @param view view matrix - * @param projection projection matrix - * @returns new ray - */ - static CreateNew(x, y, viewportWidth, viewportHeight, world, view, projection) { - const result = ray_Ray.Zero(); - return result.update(x, y, viewportWidth, viewportHeight, world, view, projection); - } - /** - * 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 - * transformed to the given world matrix. - * @param origin The origin point - * @param end The end point - * @param world a matrix to transform the ray to. Default is the identity matrix. - * @returns the new ray - */ - static CreateNewFromTo(origin, end, world = math_vector_Matrix.IdentityReadOnly) { - const direction = end.subtract(origin); - const length = Math.sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); - direction.normalize(); - return ray_Ray.Transform(new ray_Ray(origin, direction, length), world); - } - /** - * Transforms a ray by a matrix - * @param ray ray to transform - * @param matrix matrix to apply - * @returns the resulting new ray - */ - static Transform(ray, matrix) { - const result = new ray_Ray(new math_vector_Vector3(0, 0, 0), new math_vector_Vector3(0, 0, 0)); - ray_Ray.TransformToRef(ray, matrix, result); - return result; - } - /** - * Transforms a ray by a matrix - * @param ray ray to transform - * @param matrix matrix to apply - * @param result ray to store result in - */ - static TransformToRef(ray, matrix, result) { - math_vector_Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin); - math_vector_Vector3.TransformNormalToRef(ray.direction, matrix, result.direction); - result.length = ray.length; - const dir = result.direction; - const len = dir.length(); - if (!(len === 0 || len === 1)) { - const num = 1.0 / len; - dir.x *= num; - dir.y *= num; - dir.z *= num; - result.length *= len; - } - } - /** - * Unproject a ray from screen space to object space - * @param sourceX defines the screen space x coordinate to use - * @param sourceY defines the screen space y coordinate to use - * @param viewportWidth defines the current width of the viewport - * @param viewportHeight defines the current height of the viewport - * @param world defines the world matrix to use (can be set to Identity to go to world space) - * @param view defines the view matrix to use - * @param projection defines the projection matrix to use - */ - unprojectRayToRef(sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection) { - const matrix = math_vector_TmpVectors.Matrix[0]; - world.multiplyToRef(view, matrix); - matrix.multiplyToRef(projection, matrix); - matrix.invert(); - const engine = engineStore_EngineStore.LastCreatedEngine; - const nearScreenSource = math_vector_TmpVectors.Vector3[0]; - nearScreenSource.x = (sourceX / viewportWidth) * 2 - 1; - nearScreenSource.y = -((sourceY / viewportHeight) * 2 - 1); - nearScreenSource.z = (engine === null || engine === void 0 ? void 0 : engine.useReverseDepthBuffer) ? 1 : (engine === null || engine === void 0 ? void 0 : engine.isNDCHalfZRange) ? 0 : -1; - // far Z need to be close but < to 1 or camera projection matrix with maxZ = 0 will NaN - const farScreenSource = math_vector_TmpVectors.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0 - 1e-8); - const nearVec3 = math_vector_TmpVectors.Vector3[2]; - const farVec3 = math_vector_TmpVectors.Vector3[3]; - math_vector_Vector3._UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3); - math_vector_Vector3._UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3); - this.origin.copyFrom(nearVec3); - farVec3.subtractToRef(nearVec3, this.direction); - this.direction.normalize(); - } -} -ray_Ray._TmpVector3 = arrayTools_ArrayTools.BuildArray(6, math_vector_Vector3.Zero); -ray_Ray._RayDistant = ray_Ray.Zero(); -ray_Ray._Smallnum = 0.00000001; -ray_Ray._Rayl = 10e8; -scene_Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace = false) { - const result = ray_Ray.Zero(); - this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace); - return result; -}; -scene_Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) { - const engine = this.getEngine(); - if (!camera) { - if (!this.activeCamera) { - return this; - } - camera = this.activeCamera; - } - const cameraViewport = camera.viewport; - const viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); - // Moving coordinates to local viewport world - x = x / engine.getHardwareScalingLevel() - viewport.x; - y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height); - result.update(x, y, viewport.width, viewport.height, world ? world : math_vector_Matrix.IdentityReadOnly, cameraViewSpace ? math_vector_Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix(), enableDistantPicking); - return this; -}; -scene_Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) { - const result = ray_Ray.Zero(); - this.createPickingRayInCameraSpaceToRef(x, y, result, camera); - return result; -}; -scene_Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) { - if (!PickingInfo) { - return this; - } - const engine = this.getEngine(); - if (!camera) { - if (!this.activeCamera) { - throw new Error("Active camera not set"); - } - camera = this.activeCamera; - } - const cameraViewport = camera.viewport; - const viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); - const identity = math_vector_Matrix.Identity(); - // Moving coordinates to local viewport world - x = x / engine.getHardwareScalingLevel() - viewport.x; - y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height); - result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix()); - return this; -}; -scene_Scene.prototype._internalPickForMesh = function (pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate, skipBoundingInfo) { - const ray = rayFunction(world, mesh.enableDistantPicking); - const result = mesh.intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo, world, skipBoundingInfo); - if (!result || !result.hit) { - return null; - } - if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) { - return null; - } - return result; -}; -scene_Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck, onlyBoundingInfo, trianglePredicate) { - let pickingInfo = null; - const computeWorldMatrixForCamera = !!(this.activeCameras && this.activeCameras.length > 1 && this.cameraToUseForPointers !== this.activeCamera); - const currentCamera = this.cameraToUseForPointers || this.activeCamera; - for (let meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) { - const mesh = this.meshes[meshIndex]; - if (predicate) { - if (!predicate(mesh)) { - continue; - } - } - else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) { - continue; - } - const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent(); - const world = mesh.computeWorldMatrix(forceCompute, currentCamera); - if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) { - // first check if the ray intersects the whole bounding box/sphere of the mesh - const result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, world, true, true, trianglePredicate); - if (result) { - if (onlyBoundingInfo) { - // the user only asked for a bounding info check so we can return - return result; - } - const tmpMatrix = math_vector_TmpVectors.Matrix[1]; - const thinMatrices = mesh.thinInstanceGetWorldMatrices(); - for (let index = 0; index < thinMatrices.length; index++) { - const thinMatrix = thinMatrices[index]; - thinMatrix.multiplyToRef(world, tmpMatrix); - const result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, tmpMatrix, fastCheck, onlyBoundingInfo, trianglePredicate, true); - if (result) { - pickingInfo = result; - pickingInfo.thinInstanceIndex = index; - if (fastCheck) { - return pickingInfo; - } - } - } - } - } - else { - const result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate); - if (result) { - pickingInfo = result; - if (fastCheck) { - return pickingInfo; - } - } - } - } - return pickingInfo || new PickingInfo(); -}; -scene_Scene.prototype._internalMultiPick = function (rayFunction, predicate, trianglePredicate) { - if (!PickingInfo) { - return null; - } - const pickingInfos = new Array(); - const computeWorldMatrixForCamera = !!(this.activeCameras && this.activeCameras.length > 1 && this.cameraToUseForPointers !== this.activeCamera); - const currentCamera = this.cameraToUseForPointers || this.activeCamera; - for (let meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) { - const mesh = this.meshes[meshIndex]; - if (predicate) { - if (!predicate(mesh)) { - continue; - } - } - else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) { - continue; - } - const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent(); - const world = mesh.computeWorldMatrix(forceCompute, currentCamera); - if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) { - const result = this._internalPickForMesh(null, rayFunction, mesh, world, true, true, trianglePredicate); - if (result) { - const tmpMatrix = math_vector_TmpVectors.Matrix[1]; - const thinMatrices = mesh.thinInstanceGetWorldMatrices(); - for (let index = 0; index < thinMatrices.length; index++) { - const thinMatrix = thinMatrices[index]; - thinMatrix.multiplyToRef(world, tmpMatrix); - const result = this._internalPickForMesh(null, rayFunction, mesh, tmpMatrix, false, false, trianglePredicate, true); - if (result) { - result.thinInstanceIndex = index; - pickingInfos.push(result); - } - } - } - } - else { - const result = this._internalPickForMesh(null, rayFunction, mesh, world, false, false, trianglePredicate); - if (result) { - pickingInfos.push(result); - } - } - } - return pickingInfos; -}; -scene_Scene.prototype.pickWithBoundingInfo = function (x, y, predicate, fastCheck, camera) { - if (!PickingInfo) { - return null; - } - const result = this._internalPick((world) => { - if (!this._tempPickingRay) { - this._tempPickingRay = ray_Ray.Zero(); - } - this.createPickingRayToRef(x, y, world, this._tempPickingRay, camera || null); - return this._tempPickingRay; - }, predicate, fastCheck, true); - if (result) { - result.ray = this.createPickingRay(x, y, math_vector_Matrix.Identity(), camera || null); - } - return result; -}; -Object.defineProperty(scene_Scene.prototype, "_pickingAvailable", { - get: () => true, - enumerable: false, - configurable: false, -}); -scene_Scene.prototype.pick = function (x, y, predicate, fastCheck, camera, trianglePredicate, _enableDistantPicking = false) { - const result = this._internalPick((world, enableDistantPicking) => { - if (!this._tempPickingRay) { - this._tempPickingRay = ray_Ray.Zero(); - } - this.createPickingRayToRef(x, y, world, this._tempPickingRay, camera || null, false, enableDistantPicking); - return this._tempPickingRay; - }, predicate, fastCheck, false, trianglePredicate); - if (result) { - result.ray = this.createPickingRay(x, y, math_vector_Matrix.Identity(), camera || null); - } - return result; -}; -scene_Scene.prototype.pickWithRay = function (ray, predicate, fastCheck, trianglePredicate) { - const result = this._internalPick((world) => { - if (!this._pickWithRayInverseMatrix) { - this._pickWithRayInverseMatrix = math_vector_Matrix.Identity(); - } - world.invertToRef(this._pickWithRayInverseMatrix); - if (!this._cachedRayForTransform) { - this._cachedRayForTransform = ray_Ray.Zero(); - } - ray_Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform); - return this._cachedRayForTransform; - }, predicate, fastCheck, false, trianglePredicate); - if (result) { - result.ray = ray; - } - return result; -}; -scene_Scene.prototype.multiPick = function (x, y, predicate, camera, trianglePredicate) { - return this._internalMultiPick((world) => this.createPickingRay(x, y, world, camera || null), predicate, trianglePredicate); -}; -scene_Scene.prototype.multiPickWithRay = function (ray, predicate, trianglePredicate) { - return this._internalMultiPick((world) => { - if (!this._pickWithRayInverseMatrix) { - this._pickWithRayInverseMatrix = math_vector_Matrix.Identity(); - } - world.invertToRef(this._pickWithRayInverseMatrix); - if (!this._cachedRayForTransform) { - this._cachedRayForTransform = ray_Ray.Zero(); - } - ray_Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform); - return this._cachedRayForTransform; - }, predicate, trianglePredicate); -}; -camera_Camera.prototype.getForwardRay = function (length = 100, transform, origin) { - return this.getForwardRayToRef(new ray_Ray(math_vector_Vector3.Zero(), math_vector_Vector3.Zero(), length), length, transform, origin); -}; -camera_Camera.prototype.getForwardRayToRef = function (refRay, length = 100, transform, origin) { - if (!transform) { - transform = this.getWorldMatrix(); - } - refRay.length = length; - if (!origin) { - refRay.origin.copyFrom(this.position); - } - else { - refRay.origin.copyFrom(origin); - } - math_vector_TmpVectors.Vector3[2].set(0, 0, this._scene.useRightHandedSystem ? -1 : 1); - math_vector_Vector3.TransformNormalToRef(math_vector_TmpVectors.Vector3[2], transform, math_vector_TmpVectors.Vector3[3]); - math_vector_Vector3.NormalizeToRef(math_vector_TmpVectors.Vector3[3], refRay.direction); - return refRay; -}; -//# sourceMappingURL=ray.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/pivotTools.js - -/** - * Class containing a set of static utilities functions for managing Pivots - * @internal - */ -class pivotTools_PivotTools { - /** - * @internal - */ - static _RemoveAndStorePivotPoint(mesh) { - if (mesh && pivotTools_PivotTools._PivotCached === 0) { - // Save old pivot and set pivot to 0,0,0 - mesh.getPivotPointToRef(pivotTools_PivotTools._OldPivotPoint); - pivotTools_PivotTools._PivotPostMultiplyPivotMatrix = mesh._postMultiplyPivotMatrix; - if (!pivotTools_PivotTools._OldPivotPoint.equalsToFloats(0, 0, 0)) { - mesh.setPivotMatrix(math_vector_Matrix.IdentityReadOnly); - pivotTools_PivotTools._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), pivotTools_PivotTools._PivotTranslation); - pivotTools_PivotTools._PivotTmpVector.copyFromFloats(1, 1, 1); - pivotTools_PivotTools._PivotTmpVector.subtractInPlace(mesh.scaling); - pivotTools_PivotTools._PivotTmpVector.multiplyInPlace(pivotTools_PivotTools._PivotTranslation); - mesh.position.addInPlace(pivotTools_PivotTools._PivotTmpVector); - } - } - pivotTools_PivotTools._PivotCached++; - } - /** - * @internal - */ - static _RestorePivotPoint(mesh) { - if (mesh && !pivotTools_PivotTools._OldPivotPoint.equalsToFloats(0, 0, 0) && pivotTools_PivotTools._PivotCached === 1) { - mesh.setPivotPoint(pivotTools_PivotTools._OldPivotPoint); - mesh._postMultiplyPivotMatrix = pivotTools_PivotTools._PivotPostMultiplyPivotMatrix; - pivotTools_PivotTools._PivotTmpVector.copyFromFloats(1, 1, 1); - pivotTools_PivotTools._PivotTmpVector.subtractInPlace(mesh.scaling); - pivotTools_PivotTools._PivotTmpVector.multiplyInPlace(pivotTools_PivotTools._PivotTranslation); - mesh.position.subtractInPlace(pivotTools_PivotTools._PivotTmpVector); - } - this._PivotCached--; - } -} -// Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation) -// store/remove pivot point should only be applied during their outermost calls -pivotTools_PivotTools._PivotCached = 0; -pivotTools_PivotTools._OldPivotPoint = new math_vector_Vector3(); -pivotTools_PivotTools._PivotTranslation = new math_vector_Vector3(); -pivotTools_PivotTools._PivotTmpVector = new math_vector_Vector3(); -pivotTools_PivotTools._PivotPostMultiplyPivotMatrix = false; -//# sourceMappingURL=pivotTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/planeBuilder.js - - - -/** - * Creates the VertexData for a Plane - * @param options an object used to set the following optional parameters for the plane, required but can be empty - * * size sets the width and height of the plane to the value of size, optional default 1 - * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size - * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.size - * @param options.width - * @param options.height - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the box - */ -function CreatePlaneVertexData(options) { - const indices = []; - const positions = []; - const normals = []; - const uvs = []; - const width = options.width || options.size || 1; - const height = options.height || options.size || 1; - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - // Vertices - const halfWidth = width / 2.0; - const halfHeight = height / 2.0; - positions.push(-halfWidth, -halfHeight, 0); - normals.push(0, 0, -1.0); - uvs.push(0.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 : 0.0); - positions.push(halfWidth, -halfHeight, 0); - normals.push(0, 0, -1.0); - uvs.push(1.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 : 0.0); - positions.push(halfWidth, halfHeight, 0); - normals.push(0, 0, -1.0); - uvs.push(1.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 0.0 : 1.0); - positions.push(-halfWidth, halfHeight, 0); - normals.push(0, 0, -1.0); - uvs.push(0.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 0.0 : 1.0); - // Indices - indices.push(0); - indices.push(1); - indices.push(2); - indices.push(0); - indices.push(2); - indices.push(3); - // Sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - return vertexData; -} -/** - * Creates a plane mesh - * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1) - * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`) - * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.size - * @param options.width - * @param options.height - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.updatable - * @param options.sourcePlane - * @param scene defines the hosting scene - * @returns the plane mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#plane - */ -function planeBuilder_CreatePlane(name, options = {}, scene = null) { - const plane = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - plane._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreatePlaneVertexData(options); - vertexData.applyToMesh(plane, options.updatable); - if (options.sourcePlane) { - plane.translate(options.sourcePlane.normal, -options.sourcePlane.d); - plane.setDirection(options.sourcePlane.normal.scale(-1)); - } - return plane; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use the function directly from the module - */ -const PlaneBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreatePlane: planeBuilder_CreatePlane, -}; -mesh_vertexData_VertexData.CreatePlane = CreatePlaneVertexData; -mesh_Mesh.CreatePlane = (name, size, scene, updatable, sideOrientation) => { - const options = { - size, - width: size, - height: size, - sideOrientation, - updatable, - }; - return planeBuilder_CreatePlane(name, options, scene); -}; -//# sourceMappingURL=planeBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Meshes/pointerDragBehavior.js - - - - - - - - -/** - * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events - */ -class pointerDragBehavior_PointerDragBehavior { - /** - * Get or set the currentDraggingPointerId - * @deprecated Please use currentDraggingPointerId instead - */ - get currentDraggingPointerID() { - return this.currentDraggingPointerId; - } - set currentDraggingPointerID(currentDraggingPointerID) { - this.currentDraggingPointerId = currentDraggingPointerID; - } - /** - * If the drag behavior will react to drag events (Default: true) - */ - set enabled(value) { - if (value != this._enabled) { - this.onEnabledObservable.notifyObservers(value); - } - this._enabled = value; - } - get enabled() { - return this._enabled; - } - /** - * Gets the options used by the behavior - */ - get options() { - return this._options; - } - /** - * Sets the options used by the behavior - */ - set options(options) { - this._options = options; - } - /** - * Creates a pointer drag behavior that can be attached to a mesh - * @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) - * @param options.dragAxis - * @param options.dragPlaneNormal - */ - constructor(options) { - this._useAlternatePickedPointAboveMaxDragAngleDragSpeed = -1.1; - this._activeDragButton = -1; - /** - * 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) - */ - this.maxDragAngle = 0; - /** - * Butttons that can be used to initiate a drag - */ - this.dragButtons = [0, 1, 2]; - /** - * @internal - */ - this._useAlternatePickedPointAboveMaxDragAngle = false; - /** - * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active) - */ - this.currentDraggingPointerId = -1; - /** - * If the behavior is currently in a dragging state - */ - this.dragging = false; - /** - * 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) - */ - this.dragDeltaRatio = 0.2; - /** - * If the drag plane orientation should be updated during the dragging (Default: true) - */ - this.updateDragPlane = true; - // Debug mode will display drag planes to help visualize behavior - this._debugMode = false; - this._moving = false; - /** - * Fires each time the attached mesh is dragged with the pointer - * * delta between last drag position and current drag position in world space - * * dragDistance along the drag axis - * * dragPlaneNormal normal of the current drag plane used during the drag - * * dragPlanePoint in world space where the drag intersects the drag plane - * - * (if validatedDrag is used, the position of the attached mesh might not equal dragPlanePoint) - */ - this.onDragObservable = new observable_Observable(); - /** - * Fires each time a drag begins (eg. mouse down on mesh) - * * dragPlanePoint in world space where the drag intersects the drag plane - * - * (if validatedDrag is used, the position of the attached mesh might not equal dragPlanePoint) - */ - this.onDragStartObservable = new observable_Observable(); - /** - * Fires each time a drag ends (eg. mouse release after drag) - * * dragPlanePoint in world space where the drag intersects the drag plane - * - * (if validatedDrag is used, the position of the attached mesh might not equal dragPlanePoint) - */ - this.onDragEndObservable = new observable_Observable(); - /** - * Fires each time behavior enabled state changes - */ - this.onEnabledObservable = new observable_Observable(); - /** - * If the attached mesh should be moved when dragged - */ - this.moveAttached = true; - this._enabled = true; - /** - * If pointer events should start and release the drag (Default: true) - */ - this.startAndReleaseDragOnPointerEvents = true; - /** - * If camera controls should be detached during the drag - */ - this.detachCameraControls = true; - /** - * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true) - */ - this.useObjectOrientationForDragging = true; - /** - * Predicate to determine if it is valid to move the object to a new position when it is moved - * @param targetPosition - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this.validateDrag = (targetPosition) => { - return true; - }; - this._tmpVector = new math_vector_Vector3(0, 0, 0); - this._alternatePickedPoint = new math_vector_Vector3(0, 0, 0); - this._worldDragAxis = new math_vector_Vector3(0, 0, 0); - this._targetPosition = new math_vector_Vector3(0, 0, 0); - this._attachedToElement = false; - this._startDragRay = new ray_Ray(new math_vector_Vector3(), new math_vector_Vector3()); - this._lastPointerRay = {}; - this._dragDelta = new math_vector_Vector3(); - // Variables to avoid instantiation in the below method - this._pointA = new math_vector_Vector3(0, 0, 0); - this._pointC = new math_vector_Vector3(0, 0, 0); - this._localAxis = new math_vector_Vector3(0, 0, 0); - this._lookAt = new math_vector_Vector3(0, 0, 0); - this._options = options ? options : {}; - let optionCount = 0; - if (this._options.dragAxis) { - optionCount++; - } - if (this._options.dragPlaneNormal) { - optionCount++; - } - if (optionCount > 1) { - throw "Multiple drag modes specified in dragBehavior options. Only one expected"; - } - } - /** - * The name of the behavior - */ - get name() { - return "PointerDrag"; - } - /** - * Initializes the behavior - */ - init() { } - /** - * Attaches the drag behavior the passed in mesh - * @param ownerNode The mesh that will be dragged around once attached - * @param predicate Predicate to use for pick filtering - */ - attach(ownerNode, predicate) { - this._scene = ownerNode.getScene(); - ownerNode.isNearGrabbable = true; - this.attachedNode = ownerNode; - // Initialize drag plane to not interfere with existing scene - if (!pointerDragBehavior_PointerDragBehavior._PlaneScene) { - if (this._debugMode) { - pointerDragBehavior_PointerDragBehavior._PlaneScene = this._scene; - } - else { - pointerDragBehavior_PointerDragBehavior._PlaneScene = new scene_Scene(this._scene.getEngine(), { virtual: true }); - pointerDragBehavior_PointerDragBehavior._PlaneScene.detachControl(); - this._scene.onDisposeObservable.addOnce(() => { - pointerDragBehavior_PointerDragBehavior._PlaneScene.dispose(); - pointerDragBehavior_PointerDragBehavior._PlaneScene = null; - }); - } - } - this._dragPlane = planeBuilder_CreatePlane("pointerDragPlane", { size: this._debugMode ? 1 : 10000, updatable: false, sideOrientation: mesh_Mesh.DOUBLESIDE }, pointerDragBehavior_PointerDragBehavior._PlaneScene); - // State of the drag - this.lastDragPosition = new math_vector_Vector3(0, 0, 0); - const pickPredicate = predicate - ? predicate - : (m) => { - return this.attachedNode == m || m.isDescendantOf(this.attachedNode); - }; - this._pointerObserver = this._scene.onPointerObservable.add((pointerInfo) => { - if (!this.enabled) { - // If behavior is disabled before releaseDrag is ever called, call it now. - if (this._attachedToElement) { - this.releaseDrag(); - } - return; - } - if (pointerInfo.type == pointerEvents_PointerEventTypes.POINTERDOWN) { - if (this.startAndReleaseDragOnPointerEvents && - !this.dragging && - pointerInfo.pickInfo && - pointerInfo.pickInfo.hit && - pointerInfo.pickInfo.pickedMesh && - pointerInfo.pickInfo.pickedPoint && - pointerInfo.pickInfo.ray && - pickPredicate(pointerInfo.pickInfo.pickedMesh)) { - if (this._activeDragButton === -1 && this.dragButtons.indexOf(pointerInfo.event.button) !== -1) { - this._activeDragButton = pointerInfo.event.button; - this._activePointerInfo = pointerInfo; - this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint); - } - } - } - else if (pointerInfo.type == pointerEvents_PointerEventTypes.POINTERUP) { - if (this.startAndReleaseDragOnPointerEvents && - this.currentDraggingPointerId == pointerInfo.event.pointerId && - (this._activeDragButton === pointerInfo.event.button || this._activeDragButton === -1)) { - this.releaseDrag(); - } - } - else if (pointerInfo.type == pointerEvents_PointerEventTypes.POINTERMOVE) { - const pointerId = pointerInfo.event.pointerId; - // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved - if (this.currentDraggingPointerId === pointerDragBehavior_PointerDragBehavior._AnyMouseId && pointerId !== pointerDragBehavior_PointerDragBehavior._AnyMouseId) { - const evt = pointerInfo.event; - const isMouseEvent = evt.pointerType === "mouse" || (!this._scene.getEngine().hostInformation.isMobile && evt instanceof MouseEvent); - if (isMouseEvent) { - if (this._lastPointerRay[this.currentDraggingPointerId]) { - this._lastPointerRay[pointerId] = this._lastPointerRay[this.currentDraggingPointerId]; - delete this._lastPointerRay[this.currentDraggingPointerId]; - } - this.currentDraggingPointerId = pointerId; - } - } - // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag() - if (!this._lastPointerRay[pointerId]) { - this._lastPointerRay[pointerId] = new ray_Ray(new math_vector_Vector3(), new math_vector_Vector3()); - } - if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) { - this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin); - this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction); - if (this.currentDraggingPointerId == pointerId && this.dragging) { - this._moveDrag(pointerInfo.pickInfo.ray); - } - } - } - }); - this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(() => { - if (this._moving && this.moveAttached) { - let needMatrixUpdate = false; - pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode); - // Slowly move mesh to avoid jitter - this._targetPosition.subtractToRef(this.attachedNode.absolutePosition, this._tmpVector); - this._tmpVector.scaleInPlace(this.dragDeltaRatio); - this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector, this._tmpVector); - if (this.validateDrag(this._tmpVector)) { - this.attachedNode.setAbsolutePosition(this._tmpVector); - needMatrixUpdate = true; - } - pivotTools_PivotTools._RestorePivotPoint(this.attachedNode); - if (needMatrixUpdate) { - this.attachedNode.computeWorldMatrix(); - } - } - }); - } - /** - * Force release the drag action by code. - */ - releaseDrag() { - if (this.dragging) { - this.dragging = false; - this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerId, pointerInfo: this._activePointerInfo }); - } - this.currentDraggingPointerId = -1; - this._activeDragButton = -1; - this._activePointerInfo = null; - this._moving = false; - // Reattach camera controls - if (this.detachCameraControls && this._attachedToElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) { - if (this._scene.activeCamera.getClassName() === "ArcRotateCamera") { - const arcRotateCamera = this._scene.activeCamera; - arcRotateCamera.attachControl(arcRotateCamera.inputs ? arcRotateCamera.inputs.noPreventDefault : true, arcRotateCamera._useCtrlForPanning, arcRotateCamera._panningMouseButton); - } - else { - this._scene.activeCamera.attachControl(this._scene.activeCamera.inputs ? this._scene.activeCamera.inputs.noPreventDefault : true); - } - this._attachedToElement = false; - } - } - /** - * Simulates the start of a pointer drag event on the behavior - * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID) - * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh) - * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position) - */ - startDrag(pointerId = pointerDragBehavior_PointerDragBehavior._AnyMouseId, fromRay, startPickedPoint) { - this._startDrag(pointerId, fromRay, startPickedPoint); - let lastRay = this._lastPointerRay[pointerId]; - if (pointerId === pointerDragBehavior_PointerDragBehavior._AnyMouseId) { - lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]; - } - if (lastRay) { - // if there was a last pointer ray drag the object there - this._moveDrag(lastRay); - } - } - _startDrag(pointerId, fromRay, startPickedPoint) { - if (!this._scene.activeCamera || this.dragging || !this.attachedNode) { - return; - } - pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode); - // Create start ray from the camera to the object - if (fromRay) { - this._startDragRay.direction.copyFrom(fromRay.direction); - this._startDragRay.origin.copyFrom(fromRay.origin); - } - else { - 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, startPickedPoint ? startPickedPoint : this._tmpVector); - const pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay); - if (pickedPoint) { - this.dragging = true; - this.currentDraggingPointerId = pointerId; - this.lastDragPosition.copyFrom(pickedPoint); - this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerId, pointerInfo: this._activePointerInfo }); - this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()); - // Detatch camera controls - if (this.detachCameraControls && this._scene.activeCamera && this._scene.activeCamera.inputs && !this._scene.activeCamera.leftCamera) { - if (this._scene.activeCamera.inputs.attachedToElement) { - this._scene.activeCamera.detachControl(); - this._attachedToElement = true; - } - else { - this._attachedToElement = false; - } - } - } - else { - this.releaseDrag(); - } - pivotTools_PivotTools._RestorePivotPoint(this.attachedNode); - } - _moveDrag(ray) { - this._moving = true; - const pickedPoint = this._pickWithRayOnDragPlane(ray); - if (pickedPoint) { - pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode); - if (this.updateDragPlane) { - this._updateDragPlanePosition(ray, pickedPoint); - } - let dragLength = 0; - // depending on the drag mode option drag accordingly - if (this._options.dragAxis) { - // Convert local drag axis to world if useObjectOrientationForDragging - this.useObjectOrientationForDragging - ? math_vector_Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis) - : this._worldDragAxis.copyFrom(this._options.dragAxis); - // Project delta drag from the drag plane onto the drag axis - pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector); - dragLength = math_vector_Vector3.Dot(this._tmpVector, this._worldDragAxis); - this._worldDragAxis.scaleToRef(dragLength, this._dragDelta); - } - else { - dragLength = this._dragDelta.length(); - pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta); - } - this._targetPosition.addInPlace(this._dragDelta); - this.onDragObservable.notifyObservers({ - dragDistance: dragLength, - delta: this._dragDelta, - dragPlanePoint: pickedPoint, - dragPlaneNormal: this._dragPlane.forward, - pointerId: this.currentDraggingPointerId, - pointerInfo: this._activePointerInfo, - }); - this.lastDragPosition.copyFrom(pickedPoint); - pivotTools_PivotTools._RestorePivotPoint(this.attachedNode); - } - } - _pickWithRayOnDragPlane(ray) { - if (!ray) { - return null; - } - // Calculate angle between plane normal and ray - let angle = Math.acos(math_vector_Vector3.Dot(this._dragPlane.forward, ray.direction)); - // Correct if ray is casted from oposite side - if (angle > Math.PI / 2) { - angle = Math.PI - angle; - } - // If the angle is too perpendicular to the plane pick another point on the plane where it is looking - if (this.maxDragAngle > 0 && angle > this.maxDragAngle) { - if (this._useAlternatePickedPointAboveMaxDragAngle) { - // Invert ray direction along the towards object axis - this._tmpVector.copyFrom(ray.direction); - this.attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint); - this._alternatePickedPoint.normalize(); - this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed * math_vector_Vector3.Dot(this._alternatePickedPoint, this._tmpVector)); - this._tmpVector.addInPlace(this._alternatePickedPoint); - // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point - const dot = math_vector_Vector3.Dot(this._dragPlane.forward, this._tmpVector); - this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint); - this._alternatePickedPoint.addInPlace(this._tmpVector); - this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition); - return this._alternatePickedPoint; - } - else { - return null; - } - } - const pickResult = pointerDragBehavior_PointerDragBehavior._PlaneScene.pickWithRay(ray, (m) => { - return m == this._dragPlane; - }); - if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) { - return pickResult.pickedPoint; - } - else { - return null; - } - } - // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera - _updateDragPlanePosition(ray, dragPlanePosition) { - this._pointA.copyFrom(dragPlanePosition); - if (this._options.dragAxis) { - this.useObjectOrientationForDragging - ? math_vector_Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) - : this._localAxis.copyFrom(this._options.dragAxis); - // Calculate plane normal that is the cross product of local axis and (eye-dragPlanePosition) - ray.origin.subtractToRef(this._pointA, this._pointC); - this._pointC.normalize(); - if (Math.abs(math_vector_Vector3.Dot(this._localAxis, this._pointC)) > 0.999) { - // the drag axis is colinear with the (eye to position) ray. The cross product will give jittered values. - // A new axis vector need to be computed - if (Math.abs(math_vector_Vector3.Dot(math_vector_Vector3.UpReadOnly, this._pointC)) > 0.999) { - this._lookAt.copyFrom(math_vector_Vector3.Right()); - } - else { - this._lookAt.copyFrom(math_vector_Vector3.UpReadOnly); - } - } - else { - math_vector_Vector3.CrossToRef(this._localAxis, this._pointC, this._lookAt); - // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendicular to camera - math_vector_Vector3.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); - } - else if (this._options.dragPlaneNormal) { - this.useObjectOrientationForDragging - ? math_vector_Vector3.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); - } - else { - this._dragPlane.position.copyFrom(this._pointA); - this._dragPlane.lookAt(ray.origin); - } - // 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) - this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()); - this._dragPlane.computeWorldMatrix(true); - } - /** - * Detaches the behavior from the mesh - */ - detach() { - this._lastPointerRay = {}; - if (this.attachedNode) { - this.attachedNode.isNearGrabbable = false; - } - if (this._pointerObserver) { - this._scene.onPointerObservable.remove(this._pointerObserver); - } - if (this._beforeRenderObserver) { - this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver); - } - if (this._dragPlane) { - this._dragPlane.dispose(); - } - this.releaseDrag(); - } -} -pointerDragBehavior_PointerDragBehavior._AnyMouseId = -2; -//# sourceMappingURL=pointerDragBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Meshes/multiPointerScaleBehavior.js - - -/** - * A behavior that when attached to a mesh will allow the mesh to be scaled - */ -class MultiPointerScaleBehavior { - /** - * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled - */ - constructor() { - this._startDistance = 0; - this._initialScale = new Vector3(0, 0, 0); - this._targetScale = new Vector3(0, 0, 0); - this._sceneRenderObserver = null; - this._dragBehaviorA = new PointerDragBehavior({}); - this._dragBehaviorA.moveAttached = false; - this._dragBehaviorB = new PointerDragBehavior({}); - this._dragBehaviorB.moveAttached = false; - } - /** - * The name of the behavior - */ - get name() { - return "MultiPointerScale"; - } - /** - * Initializes the behavior - */ - init() { } - _getCurrentDistance() { - return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length(); - } - /** - * Attaches the scale behavior the passed in mesh - * @param ownerNode The mesh that will be scaled around once attached - */ - attach(ownerNode) { - this._ownerNode = ownerNode; - // Create 2 drag behaviors such that each will only be triggered by a separate pointer - this._dragBehaviorA.onDragStartObservable.add(() => { - if (this._dragBehaviorA.dragging && this._dragBehaviorB.dragging) { - if (this._dragBehaviorA.currentDraggingPointerId == this._dragBehaviorB.currentDraggingPointerId) { - this._dragBehaviorA.releaseDrag(); - } - else { - this._initialScale.copyFrom(ownerNode.scaling); - this._startDistance = this._getCurrentDistance(); - } - } - }); - this._dragBehaviorB.onDragStartObservable.add(() => { - if (this._dragBehaviorA.dragging && this._dragBehaviorB.dragging) { - if (this._dragBehaviorA.currentDraggingPointerId == this._dragBehaviorB.currentDraggingPointerId) { - this._dragBehaviorB.releaseDrag(); - } - else { - this._initialScale.copyFrom(ownerNode.scaling); - this._startDistance = this._getCurrentDistance(); - } - } - }); - // Once both drag behaviors are active scale based on the distance between the two pointers - [this._dragBehaviorA, this._dragBehaviorB].forEach((behavior) => { - behavior.onDragObservable.add(() => { - if (this._dragBehaviorA.dragging && this._dragBehaviorB.dragging) { - const ratio = this._getCurrentDistance() / this._startDistance; - this._initialScale.scaleToRef(ratio, this._targetScale); - } - }); - }); - ownerNode.addBehavior(this._dragBehaviorA); - ownerNode.addBehavior(this._dragBehaviorB); - // On every frame move towards target scaling to avoid jitter caused by vr controllers - this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(() => { - if (this._dragBehaviorA.dragging && this._dragBehaviorB.dragging) { - const change = this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1); - if (change.length() > 0.01) { - ownerNode.scaling.addInPlace(change); - } - } - }); - } - /** - * Detaches the behavior from the mesh - */ - detach() { - this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver); - [this._dragBehaviorA, this._dragBehaviorB].forEach((behavior) => { - behavior.onDragStartObservable.clear(); - behavior.onDragObservable.clear(); - this._ownerNode.removeBehavior(behavior); - }); - } -} -//# sourceMappingURL=multiPointerScaleBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Meshes/baseSixDofDragBehavior.js - - - - - - -/** - * Base behavior for six degrees of freedom interactions in XR experiences. - * Creates virtual meshes that are dragged around - * And observables for position/rotation changes - */ -class baseSixDofDragBehavior_BaseSixDofDragBehavior { - constructor() { - this._attachedToElement = false; - this._virtualMeshesInfo = {}; - this._tmpVector = new Vector3(); - this._tmpQuaternion = new Quaternion(); - this._dragType = { - NONE: 0, - DRAG: 1, - DRAG_WITH_CONTROLLER: 2, - NEAR_DRAG: 3, - }; - this._moving = false; - this._dragging = this._dragType.NONE; - /** - * The list of child meshes that can receive drag events - * If `null`, all child meshes will receive drag event - */ - this.draggableMeshes = null; - /** - * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3) - */ - this.zDragFactor = 3; - /** - * In case of multipointer interaction, all pointer ids currently active are stored here - */ - this.currentDraggingPointerIds = []; - /** - /** - * If camera controls should be detached during the drag - */ - this.detachCameraControls = true; - /** - * Fires each time a drag starts - */ - this.onDragStartObservable = new Observable(); - /** - * Fires each time a drag happens - */ - this.onDragObservable = new Observable(); - /** - * Fires each time a drag ends (eg. mouse release after drag) - */ - this.onDragEndObservable = new Observable(); - /** - * Should the behavior allow simultaneous pointers to interact with the owner node. - */ - this.allowMultiPointer = true; - } - /** - * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active) - */ - get currentDraggingPointerId() { - if (this.currentDraggingPointerIds[0] !== undefined) { - return this.currentDraggingPointerIds[0]; - } - return -1; - } - set currentDraggingPointerId(value) { - this.currentDraggingPointerIds[0] = value; - } - /** - * Get or set the currentDraggingPointerId - * @deprecated Please use currentDraggingPointerId instead - */ - get currentDraggingPointerID() { - return this.currentDraggingPointerId; - } - set currentDraggingPointerID(currentDraggingPointerID) { - this.currentDraggingPointerId = currentDraggingPointerID; - } - /** - * The name of the behavior - */ - get name() { - return "BaseSixDofDrag"; - } - /** - * Returns true if the attached mesh is currently moving with this behavior - */ - get isMoving() { - return this._moving; - } - /** - * Initializes the behavior - */ - init() { } - /** - * In the case of multiple active cameras, the cameraToUseForPointers should be used if set instead of active camera - */ - get _pointerCamera() { - if (this._scene.cameraToUseForPointers) { - return this._scene.cameraToUseForPointers; - } - else { - return this._scene.activeCamera; - } - } - _createVirtualMeshInfo() { - // Setup virtual meshes to be used for dragging without dirtying the existing scene - const dragMesh = new AbstractMesh("", baseSixDofDragBehavior_BaseSixDofDragBehavior._virtualScene); - dragMesh.rotationQuaternion = new Quaternion(); - const originMesh = new AbstractMesh("", baseSixDofDragBehavior_BaseSixDofDragBehavior._virtualScene); - originMesh.rotationQuaternion = new Quaternion(); - const pivotMesh = new AbstractMesh("", baseSixDofDragBehavior_BaseSixDofDragBehavior._virtualScene); - pivotMesh.rotationQuaternion = new Quaternion(); - return { - dragging: false, - moving: false, - dragMesh, - originMesh, - pivotMesh, - startingPivotPosition: new Vector3(), - startingPivotOrientation: new Quaternion(), - startingPosition: new Vector3(), - startingOrientation: new Quaternion(), - lastOriginPosition: new Vector3(), - lastDragPosition: new Vector3(), - }; - } - _resetVirtualMeshesPosition() { - for (let i = 0; i < this.currentDraggingPointerIds.length; i++) { - this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()); - this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.rotationQuaternion); - this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].startingPivotPosition.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].pivotMesh.position); - this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].startingPivotOrientation.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].pivotMesh.rotationQuaternion); - this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].startingPosition.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].dragMesh.position); - this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].startingOrientation.copyFrom(this._virtualMeshesInfo[this.currentDraggingPointerIds[i]].dragMesh.rotationQuaternion); - } - } - _pointerUpdate2D(ray, pointerId, zDragFactor) { - if (this._pointerCamera && this._pointerCamera.cameraRigMode == Camera.RIG_MODE_NONE && !this._pointerCamera._isLeftCamera && !this._pointerCamera._isRightCamera) { - ray.origin.copyFrom(this._pointerCamera.globalPosition); - zDragFactor = 0; - } - const virtualMeshesInfo = this._virtualMeshesInfo[pointerId]; - // Calculate controller drag distance in controller space - const originDragDifference = TmpVectors.Vector3[0]; - ray.origin.subtractToRef(virtualMeshesInfo.lastOriginPosition, originDragDifference); - virtualMeshesInfo.lastOriginPosition.copyFrom(ray.origin); - const localOriginDragDifference = -Vector3.Dot(originDragDifference, ray.direction); - virtualMeshesInfo.originMesh.addChild(virtualMeshesInfo.dragMesh); - virtualMeshesInfo.originMesh.addChild(virtualMeshesInfo.pivotMesh); - this._applyZOffset(virtualMeshesInfo.dragMesh, localOriginDragDifference, zDragFactor); - this._applyZOffset(virtualMeshesInfo.pivotMesh, localOriginDragDifference, zDragFactor); - // Update the controller position - virtualMeshesInfo.originMesh.position.copyFrom(ray.origin); - const lookAt = TmpVectors.Vector3[0]; - ray.origin.addToRef(ray.direction, lookAt); - virtualMeshesInfo.originMesh.lookAt(lookAt); - virtualMeshesInfo.originMesh.removeChild(virtualMeshesInfo.dragMesh); - virtualMeshesInfo.originMesh.removeChild(virtualMeshesInfo.pivotMesh); - } - _pointerUpdateXR(controllerAimTransform, controllerGripTransform, pointerId, zDragFactor) { - const virtualMeshesInfo = this._virtualMeshesInfo[pointerId]; - virtualMeshesInfo.originMesh.position.copyFrom(controllerAimTransform.position); - if (this._dragging === this._dragType.NEAR_DRAG && controllerGripTransform) { - virtualMeshesInfo.originMesh.rotationQuaternion.copyFrom(controllerGripTransform.rotationQuaternion); - } - else { - virtualMeshesInfo.originMesh.rotationQuaternion.copyFrom(controllerAimTransform.rotationQuaternion); - } - virtualMeshesInfo.pivotMesh.computeWorldMatrix(true); - virtualMeshesInfo.dragMesh.computeWorldMatrix(true); - // Z scaling logic - if (zDragFactor !== 0) { - // Camera.getForwardRay modifies TmpVectors.Vector[0-3], so cache it in advance - const cameraForwardVec = TmpVectors.Vector3[0]; - const originDragDirection = TmpVectors.Vector3[1]; - cameraForwardVec.copyFrom(this._pointerCamera.getForwardRay().direction); - virtualMeshesInfo.originMesh.position.subtractToRef(virtualMeshesInfo.lastOriginPosition, originDragDirection); - virtualMeshesInfo.lastOriginPosition.copyFrom(virtualMeshesInfo.originMesh.position); - const controllerDragDistance = originDragDirection.length(); - originDragDirection.normalize(); - const cameraToDrag = TmpVectors.Vector3[2]; - const controllerToDrag = TmpVectors.Vector3[3]; - virtualMeshesInfo.dragMesh.absolutePosition.subtractToRef(this._pointerCamera.globalPosition, cameraToDrag); - virtualMeshesInfo.dragMesh.absolutePosition.subtractToRef(virtualMeshesInfo.originMesh.position, controllerToDrag); - const controllerToDragDistance = controllerToDrag.length(); - cameraToDrag.normalize(); - controllerToDrag.normalize(); - const controllerDragScaling = Math.abs(Vector3.Dot(originDragDirection, controllerToDrag)) * Vector3.Dot(originDragDirection, cameraForwardVec); - let zOffsetScaling = controllerDragScaling * zDragFactor * controllerDragDistance * controllerToDragDistance; - // Prevent pulling the mesh through the controller - const minDistanceFromControllerToDragMesh = 0.01; - if (zOffsetScaling < 0 && minDistanceFromControllerToDragMesh - controllerToDragDistance > zOffsetScaling) { - zOffsetScaling = Math.min(minDistanceFromControllerToDragMesh - controllerToDragDistance, 0); - } - controllerToDrag.scaleInPlace(zOffsetScaling); - controllerToDrag.addToRef(virtualMeshesInfo.pivotMesh.absolutePosition, this._tmpVector); - virtualMeshesInfo.pivotMesh.setAbsolutePosition(this._tmpVector); - controllerToDrag.addToRef(virtualMeshesInfo.dragMesh.absolutePosition, this._tmpVector); - virtualMeshesInfo.dragMesh.setAbsolutePosition(this._tmpVector); - } - } - /** - * Attaches the scale behavior the passed in mesh - * @param ownerNode The mesh that will be scaled around once attached - */ - attach(ownerNode) { - this._ownerNode = ownerNode; - this._scene = this._ownerNode.getScene(); - if (!baseSixDofDragBehavior_BaseSixDofDragBehavior._virtualScene) { - baseSixDofDragBehavior_BaseSixDofDragBehavior._virtualScene = new Scene(this._scene.getEngine(), { virtual: true }); - baseSixDofDragBehavior_BaseSixDofDragBehavior._virtualScene.detachControl(); - } - const pickPredicate = (m) => { - return this._ownerNode === m || (m.isDescendantOf(this._ownerNode) && (!this.draggableMeshes || this.draggableMeshes.indexOf(m) !== -1)); - }; - this._pointerObserver = this._scene.onPointerObservable.add((pointerInfo) => { - const pointerId = pointerInfo.event.pointerId; - if (!this._virtualMeshesInfo[pointerId]) { - this._virtualMeshesInfo[pointerId] = this._createVirtualMeshInfo(); - } - const virtualMeshesInfo = this._virtualMeshesInfo[pointerId]; - const isXRNearPointer = pointerInfo.event.pointerType === "xr-near"; - if (pointerInfo.type == PointerEventTypes.POINTERDOWN) { - if (!virtualMeshesInfo.dragging && - pointerInfo.pickInfo && - pointerInfo.pickInfo.hit && - pointerInfo.pickInfo.pickedMesh && - pointerInfo.pickInfo.pickedPoint && - pointerInfo.pickInfo.ray && - (!isXRNearPointer || pointerInfo.pickInfo.aimTransform) && - pickPredicate(pointerInfo.pickInfo.pickedMesh)) { - if (!this.allowMultiPointer && this.currentDraggingPointerIds.length > 0) { - return; - } - if (this._pointerCamera && - this._pointerCamera.cameraRigMode === Camera.RIG_MODE_NONE && - !this._pointerCamera._isLeftCamera && - !this._pointerCamera._isRightCamera) { - pointerInfo.pickInfo.ray.origin.copyFrom(this._pointerCamera.globalPosition); - } - this._ownerNode.computeWorldMatrix(true); - const virtualMeshesInfo = this._virtualMeshesInfo[pointerId]; - if (isXRNearPointer) { - this._dragging = pointerInfo.pickInfo.originMesh ? this._dragType.NEAR_DRAG : this._dragType.DRAG_WITH_CONTROLLER; - virtualMeshesInfo.originMesh.position.copyFrom(pointerInfo.pickInfo.aimTransform.position); - if (this._dragging === this._dragType.NEAR_DRAG && pointerInfo.pickInfo.gripTransform) { - virtualMeshesInfo.originMesh.rotationQuaternion.copyFrom(pointerInfo.pickInfo.gripTransform.rotationQuaternion); - } - else { - virtualMeshesInfo.originMesh.rotationQuaternion.copyFrom(pointerInfo.pickInfo.aimTransform.rotationQuaternion); - } - } - else { - this._dragging = this._dragType.DRAG; - virtualMeshesInfo.originMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin); - } - virtualMeshesInfo.lastOriginPosition.copyFrom(virtualMeshesInfo.originMesh.position); - virtualMeshesInfo.dragMesh.position.copyFrom(pointerInfo.pickInfo.pickedPoint); - virtualMeshesInfo.lastDragPosition.copyFrom(pointerInfo.pickInfo.pickedPoint); - virtualMeshesInfo.pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()); - virtualMeshesInfo.pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion); - virtualMeshesInfo.startingPosition.copyFrom(virtualMeshesInfo.dragMesh.position); - virtualMeshesInfo.startingPivotPosition.copyFrom(virtualMeshesInfo.pivotMesh.position); - virtualMeshesInfo.startingOrientation.copyFrom(virtualMeshesInfo.dragMesh.rotationQuaternion); - virtualMeshesInfo.startingPivotOrientation.copyFrom(virtualMeshesInfo.pivotMesh.rotationQuaternion); - if (isXRNearPointer) { - virtualMeshesInfo.originMesh.addChild(virtualMeshesInfo.dragMesh); - virtualMeshesInfo.originMesh.addChild(virtualMeshesInfo.pivotMesh); - } - else { - virtualMeshesInfo.originMesh.lookAt(virtualMeshesInfo.dragMesh.position); - } - // Update state - virtualMeshesInfo.dragging = true; - if (this.currentDraggingPointerIds.indexOf(pointerId) === -1) { - this.currentDraggingPointerIds.push(pointerId); - } - // Detach camera controls - if (this.detachCameraControls && this._pointerCamera && !this._pointerCamera.leftCamera) { - if (this._pointerCamera.inputs && this._pointerCamera.inputs.attachedToElement) { - this._pointerCamera.detachControl(); - this._attachedToElement = true; - } - else { - this._attachedToElement = false; - } - } - this._targetDragStart(virtualMeshesInfo.pivotMesh.position, virtualMeshesInfo.pivotMesh.rotationQuaternion, pointerId); - this.onDragStartObservable.notifyObservers({ position: virtualMeshesInfo.pivotMesh.position }); - } - } - else if (pointerInfo.type == PointerEventTypes.POINTERUP || pointerInfo.type == PointerEventTypes.POINTERDOUBLETAP) { - const registeredPointerIndex = this.currentDraggingPointerIds.indexOf(pointerId); - // Update state - virtualMeshesInfo.dragging = false; - if (registeredPointerIndex !== -1) { - this.currentDraggingPointerIds.splice(registeredPointerIndex, 1); - if (this.currentDraggingPointerIds.length === 0) { - this._moving = false; - this._dragging = this._dragType.NONE; - // Reattach camera controls - if (this.detachCameraControls && this._attachedToElement && this._pointerCamera && !this._pointerCamera.leftCamera) { - this._reattachCameraControls(); - this._attachedToElement = false; - } - } - virtualMeshesInfo.originMesh.removeChild(virtualMeshesInfo.dragMesh); - virtualMeshesInfo.originMesh.removeChild(virtualMeshesInfo.pivotMesh); - this._targetDragEnd(pointerId); - this.onDragEndObservable.notifyObservers({}); - } - } - else if (pointerInfo.type == PointerEventTypes.POINTERMOVE) { - const registeredPointerIndex = this.currentDraggingPointerIds.indexOf(pointerId); - if (registeredPointerIndex !== -1 && virtualMeshesInfo.dragging && pointerInfo.pickInfo && (pointerInfo.pickInfo.ray || pointerInfo.pickInfo.aimTransform)) { - let zDragFactor = this.zDragFactor; - // 2 pointer interaction should not have a z axis drag factor - // as well as near interaction - if (this.currentDraggingPointerIds.length > 1 || pointerInfo.pickInfo.originMesh) { - zDragFactor = 0; - } - this._ownerNode.computeWorldMatrix(true); - if (!isXRNearPointer) { - this._pointerUpdate2D(pointerInfo.pickInfo.ray, pointerId, zDragFactor); - } - else { - this._pointerUpdateXR(pointerInfo.pickInfo.aimTransform, pointerInfo.pickInfo.gripTransform, pointerId, zDragFactor); - } - // Get change in rotation - this._tmpQuaternion.copyFrom(virtualMeshesInfo.startingPivotOrientation); - this._tmpQuaternion.x = -this._tmpQuaternion.x; - this._tmpQuaternion.y = -this._tmpQuaternion.y; - this._tmpQuaternion.z = -this._tmpQuaternion.z; - virtualMeshesInfo.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion, this._tmpQuaternion); - virtualMeshesInfo.pivotMesh.absolutePosition.subtractToRef(virtualMeshesInfo.startingPivotPosition, this._tmpVector); - this.onDragObservable.notifyObservers({ delta: this._tmpVector, position: virtualMeshesInfo.pivotMesh.position, pickInfo: pointerInfo.pickInfo }); - // Notify herited methods and observables - this._targetDrag(this._tmpVector, this._tmpQuaternion, pointerId); - virtualMeshesInfo.lastDragPosition.copyFrom(virtualMeshesInfo.dragMesh.absolutePosition); - this._moving = true; - } - } - }); - } - _applyZOffset(node, localOriginDragDifference, zDragFactor) { - // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away - node.position.z -= node.position.z < 1 ? localOriginDragDifference * zDragFactor : localOriginDragDifference * zDragFactor * node.position.z; - if (node.position.z < 0) { - node.position.z = 0; - } - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _targetDragStart(worldPosition, worldRotation, pointerId) { - // Herited classes can override that - } - _targetDrag(worldDeltaPosition, worldDeltaRotation, pointerId) { - // Herited classes can override that - } - _targetDragEnd(pointerId) { - // Herited classes can override that - } - _reattachCameraControls() { - if (this._pointerCamera) { - // If the camera is an ArcRotateCamera, preserve the settings from the camera - // when reattaching control - if (this._pointerCamera.getClassName() === "ArcRotateCamera") { - const arcRotateCamera = this._pointerCamera; - arcRotateCamera.attachControl(arcRotateCamera.inputs ? arcRotateCamera.inputs.noPreventDefault : true, arcRotateCamera._useCtrlForPanning, arcRotateCamera._panningMouseButton); - } - else { - // preserve the settings from the camera when reattaching control - this._pointerCamera.attachControl(this._pointerCamera.inputs ? this._pointerCamera.inputs.noPreventDefault : true); - } - } - } - /** - * Detaches the behavior from the mesh - */ - detach() { - if (this._scene) { - if (this.detachCameraControls && this._attachedToElement && this._pointerCamera && !this._pointerCamera.leftCamera) { - this._reattachCameraControls(); - this._attachedToElement = false; - } - this._scene.onPointerObservable.remove(this._pointerObserver); - } - for (const pointerId in this._virtualMeshesInfo) { - this._virtualMeshesInfo[pointerId].originMesh.dispose(); - this._virtualMeshesInfo[pointerId].dragMesh.dispose(); - } - this.onDragEndObservable.clear(); - this.onDragObservable.clear(); - this.onDragStartObservable.clear(); - } -} -//# sourceMappingURL=baseSixDofDragBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Meshes/sixDofDragBehavior.js - - - - - -/** - * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray - */ -class sixDofDragBehavior_SixDofDragBehavior extends (/* unused pure expression or super */ null && (BaseSixDofDragBehavior)) { - constructor() { - super(...arguments); - this._sceneRenderObserver = null; - this._targetPosition = new Vector3(0, 0, 0); - this._targetOrientation = new Quaternion(); - this._targetScaling = new Vector3(1, 1, 1); - this._startingPosition = new Vector3(0, 0, 0); - this._startingOrientation = new Quaternion(); - this._startingScaling = new Vector3(1, 1, 1); - /** - * Fires when position is updated - */ - this.onPositionChangedObservable = new Observable(); - /** - * 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) - */ - this.dragDeltaRatio = 0.2; - /** - * If the object should rotate to face the drag origin - */ - this.rotateDraggedObject = true; - /** - * If `rotateDraggedObject` is set to `true`, this parameter determines if we are only rotating around the y axis (yaw) - */ - this.rotateAroundYOnly = false; - /** - * Should the behavior rotate 1:1 with the motion controller, when one is used. - */ - this.rotateWithMotionController = true; - /** - * Use this flag to update the target but not move the owner node towards the target - */ - this.disableMovement = false; - /** - * Should the object rotate towards the camera when we start dragging it - */ - this.faceCameraOnDragStart = false; - } - /** - * The name of the behavior - */ - get name() { - return "SixDofDrag"; - } - /** - * Attaches the six DoF drag behavior - * @param ownerNode The mesh that will be dragged around once attached - */ - attach(ownerNode) { - super.attach(ownerNode); - ownerNode.isNearGrabbable = true; - // Node that will save the owner's transform - this._virtualTransformNode = new TransformNode("virtual_sixDof", BaseSixDofDragBehavior._virtualScene); - this._virtualTransformNode.rotationQuaternion = Quaternion.Identity(); - // On every frame move towards target scaling to avoid jitter caused by vr controllers - this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(() => { - if (this.currentDraggingPointerIds.length === 1 && this._moving && !this.disableMovement) { - // 1 pointer only drags mesh - const oldParent = ownerNode.parent; - ownerNode.setParent(null); - ownerNode.position.addInPlace(this._targetPosition.subtract(ownerNode.position).scale(this.dragDeltaRatio)); - this.onPositionChangedObservable.notifyObservers({ position: ownerNode.absolutePosition }); - // Only rotate the mesh if it's parent has uniform scaling - if (!oldParent || (oldParent.scaling && !oldParent.scaling.isNonUniformWithinEpsilon(0.001))) { - Quaternion.SlerpToRef(ownerNode.rotationQuaternion, this._targetOrientation, this.dragDeltaRatio, ownerNode.rotationQuaternion); - } - ownerNode.setParent(oldParent); - } - }); - } - _getPositionOffsetAround(transformationLocalOrigin, scaling, rotation) { - const translationMatrix = TmpVectors.Matrix[0]; // T - const translationMatrixInv = TmpVectors.Matrix[1]; // T' - const rotationMatrix = TmpVectors.Matrix[2]; // R - const scaleMatrix = TmpVectors.Matrix[3]; // S - const finalMatrix = TmpVectors.Matrix[4]; // T' x R x S x T - Matrix.TranslationToRef(transformationLocalOrigin.x, transformationLocalOrigin.y, transformationLocalOrigin.z, translationMatrix); // T - Matrix.TranslationToRef(-transformationLocalOrigin.x, -transformationLocalOrigin.y, -transformationLocalOrigin.z, translationMatrixInv); // T' - Matrix.FromQuaternionToRef(rotation, rotationMatrix); // R - Matrix.ScalingToRef(scaling, scaling, scaling, scaleMatrix); - translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R - finalMatrix.multiplyToRef(scaleMatrix, finalMatrix); // T' x R x S - finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x S x T - return finalMatrix.getTranslation(); - } - _onePointerPositionUpdated(worldDeltaPosition, worldDeltaRotation) { - const pointerDelta = TmpVectors.Vector3[0]; - pointerDelta.setAll(0); - if (this._dragging === this._dragType.DRAG) { - if (this.rotateDraggedObject) { - if (this.rotateAroundYOnly) { - // Convert change in rotation to only y axis rotation - Quaternion.RotationYawPitchRollToRef(worldDeltaRotation.toEulerAngles().y, 0, 0, TmpVectors.Quaternion[0]); - } - else { - TmpVectors.Quaternion[0].copyFrom(worldDeltaRotation); - } - TmpVectors.Quaternion[0].multiplyToRef(this._startingOrientation, this._targetOrientation); - } - } - else if (this._dragging === this._dragType.NEAR_DRAG || (this._dragging === this._dragType.DRAG_WITH_CONTROLLER && this.rotateWithMotionController)) { - worldDeltaRotation.multiplyToRef(this._startingOrientation, this._targetOrientation); - } - this._targetPosition.copyFrom(this._startingPosition).addInPlace(worldDeltaPosition); - } - _twoPointersPositionUpdated() { - const startingPosition0 = this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition; - const startingPosition1 = this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition; - const startingCenter = TmpVectors.Vector3[0]; - startingPosition0.addToRef(startingPosition1, startingCenter); - startingCenter.scaleInPlace(0.5); - const startingVector = TmpVectors.Vector3[1]; - startingPosition1.subtractToRef(startingPosition0, startingVector); - const currentPosition0 = this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition; - const currentPosition1 = this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition; - const currentCenter = TmpVectors.Vector3[2]; - currentPosition0.addToRef(currentPosition1, currentCenter); - currentCenter.scaleInPlace(0.5); - const currentVector = TmpVectors.Vector3[3]; - currentPosition1.subtractToRef(currentPosition0, currentVector); - const scaling = currentVector.length() / startingVector.length(); - const translation = currentCenter.subtract(startingCenter); - const rotationQuaternion = Quaternion.FromEulerAngles(0, Vector3.GetAngleBetweenVectorsOnPlane(startingVector.normalize(), currentVector.normalize(), Vector3.UpReadOnly), 0); - const oldParent = this._ownerNode.parent; - this._ownerNode.setParent(null); - const positionOffset = this._getPositionOffsetAround(startingCenter.subtract(this._virtualTransformNode.getAbsolutePivotPoint()), scaling, rotationQuaternion); - this._virtualTransformNode.rotationQuaternion.multiplyToRef(rotationQuaternion, this._ownerNode.rotationQuaternion); - this._virtualTransformNode.scaling.scaleToRef(scaling, this._ownerNode.scaling); - this._virtualTransformNode.position.addToRef(translation.addInPlace(positionOffset), this._ownerNode.position); - this.onPositionChangedObservable.notifyObservers({ position: this._ownerNode.position }); - this._ownerNode.setParent(oldParent); - } - _targetDragStart() { - const pointerCount = this.currentDraggingPointerIds.length; - const oldParent = this._ownerNode.parent; - if (!this._ownerNode.rotationQuaternion) { - this._ownerNode.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._ownerNode.rotation.y, this._ownerNode.rotation.x, this._ownerNode.rotation.z); - } - const worldPivot = this._ownerNode.getAbsolutePivotPoint(); - this._ownerNode.setParent(null); - if (pointerCount === 1) { - this._targetPosition.copyFrom(this._ownerNode.position); - this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion); - this._targetScaling.copyFrom(this._ownerNode.scaling); - if (this.faceCameraOnDragStart && this._scene.activeCamera) { - const toCamera = TmpVectors.Vector3[0]; - this._scene.activeCamera.position.subtractToRef(worldPivot, toCamera); - toCamera.normalize(); - const quat = TmpVectors.Quaternion[0]; - if (this._scene.useRightHandedSystem) { - Quaternion.FromLookDirectionRHToRef(toCamera, new Vector3(0, 1, 0), quat); - } - else { - Quaternion.FromLookDirectionLHToRef(toCamera, new Vector3(0, 1, 0), quat); - } - quat.normalize(); - Quaternion.RotationYawPitchRollToRef(quat.toEulerAngles().y, 0, 0, TmpVectors.Quaternion[0]); - this._targetOrientation.copyFrom(TmpVectors.Quaternion[0]); - } - this._startingPosition.copyFrom(this._targetPosition); - this._startingOrientation.copyFrom(this._targetOrientation); - this._startingScaling.copyFrom(this._targetScaling); - } - else if (pointerCount === 2) { - this._virtualTransformNode.setPivotPoint(new Vector3(0, 0, 0), Space.LOCAL); - this._virtualTransformNode.position.copyFrom(this._ownerNode.position); - this._virtualTransformNode.scaling.copyFrom(this._ownerNode.scaling); - this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.rotationQuaternion); - this._virtualTransformNode.setPivotPoint(worldPivot, Space.WORLD); - this._resetVirtualMeshesPosition(); - } - this._ownerNode.setParent(oldParent); - } - _targetDrag(worldDeltaPosition, worldDeltaRotation) { - if (this.currentDraggingPointerIds.length === 1) { - this._onePointerPositionUpdated(worldDeltaPosition, worldDeltaRotation); - } - else if (this.currentDraggingPointerIds.length === 2) { - this._twoPointersPositionUpdated(); - } - } - _targetDragEnd() { - if (this.currentDraggingPointerIds.length === 1) { - // We still have 1 active pointer, we must simulate a dragstart with a reseted position/orientation - this._resetVirtualMeshesPosition(); - const previousFaceCameraFlag = this.faceCameraOnDragStart; - this.faceCameraOnDragStart = false; - this._targetDragStart(); - this.faceCameraOnDragStart = previousFaceCameraFlag; - } - } - /** - * Detaches the behavior from the mesh - */ - detach() { - super.detach(); - if (this._ownerNode) { - this._ownerNode.isNearGrabbable = false; - this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver); - } - if (this._virtualTransformNode) { - this._virtualTransformNode.dispose(); - } - } -} -//# sourceMappingURL=sixDofDragBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Meshes/surfaceMagnetismBehavior.js - - -/** - * A behavior that allows a transform node to stick to a surface position/orientation - * @since 5.0.0 - */ -class SurfaceMagnetismBehavior { - constructor() { - this._attachPointLocalOffset = new Vector3(); - this._workingPosition = new Vector3(); - this._workingQuaternion = new Quaternion(); - this._lastTick = -1; - this._hit = false; - /** - * Distance offset from the hit point to place the target at, along the hit normal. - */ - this.hitNormalOffset = 0.05; - /** - * Spatial mapping meshes to collide with - */ - this.meshes = []; - /** - * Set to false if the node should strictly follow the camera without any interpolation time - */ - this.interpolatePose = true; - /** - * Rate of interpolation of position and rotation of the attached node. - * Higher values will give a slower interpolation. - */ - this.lerpTime = 250; - /** - * If true, pitch and roll are omitted. - */ - this.keepOrientationVertical = true; - /** - * Is this behavior reacting to pointer events - */ - this.enabled = true; - /** - * Maximum distance for the node to stick to the surface - */ - this.maxStickingDistance = 0.8; - } - /** - * Name of the behavior - */ - get name() { - return "SurfaceMagnetism"; - } - /** - * Function called when the behavior needs to be initialized (after attaching it to a target) - */ - init() { } - /** - * Attaches the behavior to a transform node - * @param target defines the target where the behavior is attached to - * @param scene the scene - */ - attach(target, scene) { - this._attachedMesh = target; - this._scene = scene || target.getScene(); - if (!this._attachedMesh.rotationQuaternion) { - this._attachedMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._attachedMesh.rotation.y, this._attachedMesh.rotation.x, this._attachedMesh.rotation.z); - } - this.updateAttachPoint(); - this._workingPosition.copyFrom(this._attachedMesh.position); - this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion); - this._addObservables(); - } - /** - * Detaches the behavior - */ - detach() { - this._attachedMesh = null; - this._removeObservables(); - } - _getTargetPose(pickingInfo) { - if (!this._attachedMesh) { - return null; - } - if (pickingInfo && pickingInfo.hit) { - const pickedNormal = pickingInfo.getNormal(true, true); - const pickedPoint = pickingInfo.pickedPoint; - if (!pickedNormal || !pickedPoint) { - return null; - } - pickedNormal.normalize(); - const worldTarget = TmpVectors.Vector3[0]; - worldTarget.copyFrom(pickedNormal); - worldTarget.scaleInPlace(this.hitNormalOffset); - worldTarget.addInPlace(pickedPoint); - if (this._attachedMesh.parent) { - TmpVectors.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(); - Vector3.TransformNormalToRef(worldTarget, TmpVectors.Matrix[0], worldTarget); - } - return { - position: worldTarget, - quaternion: Quaternion.RotationYawPitchRoll(-Math.atan2(pickedNormal.x, -pickedNormal.z), this.keepOrientationVertical ? 0 : Math.atan2(pickedNormal.y, Math.sqrt(pickedNormal.z * pickedNormal.z + pickedNormal.x * pickedNormal.x)), 0), - }; - } - return null; - } - /** - * Updates the attach point with the current geometry extents of the attached mesh - */ - updateAttachPoint() { - this._getAttachPointOffsetToRef(this._attachPointLocalOffset); - } - /** - * Finds the intersection point of the given ray onto the meshes and updates the target. - * Transformation will be interpolated according to `interpolatePose` and `lerpTime` properties. - * If no mesh of `meshes` are hit, this does nothing. - * @param pickInfo The input pickingInfo that will be used to intersect the meshes - * @returns a boolean indicating if we found a hit to stick to - */ - findAndUpdateTarget(pickInfo) { - this._hit = false; - if (!pickInfo.ray) { - return false; - } - const subPicking = pickInfo.ray.intersectsMeshes(this.meshes)[0]; - if (this._attachedMesh && subPicking && subPicking.hit && subPicking.pickedMesh) { - const pose = this._getTargetPose(subPicking); - if (pose && Vector3.Distance(this._attachedMesh.position, pose.position) < this.maxStickingDistance) { - this._workingPosition.copyFrom(pose.position); - this._workingQuaternion.copyFrom(pose.quaternion); - this._hit = true; - } - } - return this._hit; - } - _getAttachPointOffsetToRef(ref) { - if (!this._attachedMesh) { - ref.setAll(0); - return; - } - const storedQuat = TmpVectors.Quaternion[0]; - storedQuat.copyFrom(this._attachedMesh.rotationQuaternion); - this._attachedMesh.rotationQuaternion.copyFromFloats(0, 0, 0, 1); - this._attachedMesh.computeWorldMatrix(); - const boundingMinMax = this._attachedMesh.getHierarchyBoundingVectors(); - const center = TmpVectors.Vector3[0]; - boundingMinMax.max.addToRef(boundingMinMax.min, center); - center.scaleInPlace(0.5); - center.z = boundingMinMax.max.z; - // We max the z coordinate because we want the attach point to be on the back of the mesh - const invWorld = TmpVectors.Matrix[0]; - this._attachedMesh.getWorldMatrix().invertToRef(invWorld); - Vector3.TransformCoordinatesToRef(center, invWorld, ref); - this._attachedMesh.rotationQuaternion.copyFrom(storedQuat); - } - _updateTransformToGoal(elapsed) { - if (!this._attachedMesh || !this._hit) { - return; - } - const oldParent = this._attachedMesh.parent; - this._attachedMesh.setParent(null); - const worldOffset = TmpVectors.Vector3[0]; - Vector3.TransformNormalToRef(this._attachPointLocalOffset, this._attachedMesh.getWorldMatrix(), worldOffset); - if (!this.interpolatePose) { - this._attachedMesh.position.copyFrom(this._workingPosition).subtractInPlace(worldOffset); - this._attachedMesh.rotationQuaternion.copyFrom(this._workingQuaternion); - return; - } - // position - const interpolatedPosition = new Vector3(); - Vector3.SmoothToRef(this._attachedMesh.position, this._workingPosition, elapsed, this.lerpTime, interpolatedPosition); - this._attachedMesh.position.copyFrom(interpolatedPosition); - // rotation - const currentRotation = new Quaternion(); - currentRotation.copyFrom(this._attachedMesh.rotationQuaternion); - Quaternion.SmoothToRef(currentRotation, this._workingQuaternion, elapsed, this.lerpTime, this._attachedMesh.rotationQuaternion); - this._attachedMesh.setParent(oldParent); - } - _addObservables() { - this._pointerObserver = this._scene.onPointerObservable.add((pointerInfo) => { - if (this.enabled && pointerInfo.type == PointerEventTypes.POINTERMOVE && pointerInfo.pickInfo) { - this.findAndUpdateTarget(pointerInfo.pickInfo); - } - }); - this._lastTick = Date.now(); - this._onBeforeRender = this._scene.onBeforeRenderObservable.add(() => { - const tick = Date.now(); - this._updateTransformToGoal(tick - this._lastTick); - this._lastTick = tick; - }); - } - _removeObservables() { - this._scene.onPointerObservable.remove(this._pointerObserver); - this._scene.onBeforeRenderObservable.remove(this._onBeforeRender); - this._pointerObserver = null; - this._onBeforeRender = null; - } -} -//# sourceMappingURL=surfaceMagnetismBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Meshes/followBehavior.js - - - -/** - * A behavior that when attached to a mesh will follow a camera - * @since 5.0.0 - */ -class FollowBehavior { - constructor() { - // Memory cache to avoid GC usage - this._tmpQuaternion = new Quaternion(); - this._tmpVectors = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()]; - this._tmpMatrix = new Matrix(); - this._tmpInvertView = new Matrix(); - this._tmpForward = new Vector3(); - this._tmpNodeForward = new Vector3(); - this._tmpPosition = new Vector3(); - this._workingPosition = new Vector3(); - this._workingQuaternion = new Quaternion(); - this._lastTick = -1; - this._recenterNextUpdate = true; - /** - * Set to false if the node should strictly follow the camera without any interpolation time - */ - this.interpolatePose = true; - /** - * Rate of interpolation of position and rotation of the attached node. - * Higher values will give a slower interpolation. - */ - this.lerpTime = 500; - /** - * If the behavior should ignore the pitch and roll of the camera. - */ - this.ignoreCameraPitchAndRoll = false; - /** - * Pitch offset from camera (relative to Max Distance) - * Is only effective if `ignoreCameraPitchAndRoll` is set to `true`. - */ - this.pitchOffset = 15; - /** - * The vertical angle from the camera forward axis to the owner will not exceed this value - */ - this.maxViewVerticalDegrees = 30; - /** - * The horizontal angle from the camera forward axis to the owner will not exceed this value - */ - this.maxViewHorizontalDegrees = 30; - /** - * The attached node will not reorient until the angle between its forward vector and the vector to the camera is greater than this value - */ - this.orientToCameraDeadzoneDegrees = 60; - /** - * Option to ignore distance clamping - */ - this.ignoreDistanceClamp = false; - /** - * Option to ignore angle clamping - */ - this.ignoreAngleClamp = false; - /** - * Max vertical distance between the attachedNode and camera - */ - this.verticalMaxDistance = 0; - /** - * Default distance from eye to attached node, i.e. the sphere radius - */ - this.defaultDistance = 0.8; - /** - * Max distance from eye to attached node, i.e. the sphere radius - */ - this.maximumDistance = 2; - /** - * Min distance from eye to attached node, i.e. the sphere radius - */ - this.minimumDistance = 0.3; - /** - * Ignore vertical movement and lock the Y position of the object. - */ - this.useFixedVerticalOffset = false; - /** - * Fixed vertical position offset distance. - */ - this.fixedVerticalOffset = 0; - /** - * Enables/disables the behavior - * @internal - */ - this._enabled = true; - } - /** - * The camera that should be followed by this behavior - */ - get followedCamera() { - return this._followedCamera || this._scene.activeCamera; - } - set followedCamera(camera) { - this._followedCamera = camera; - } - /** - * The name of the behavior - */ - get name() { - return "Follow"; - } - /** - * Initializes the behavior - */ - init() { } - /** - * Attaches the follow behavior - * @param ownerNode The mesh that will be following once attached - * @param followedCamera The camera that should be followed by the node - */ - attach(ownerNode, followedCamera) { - this._scene = ownerNode.getScene(); - this.attachedNode = ownerNode; - if (followedCamera) { - this.followedCamera = followedCamera; - } - this._addObservables(); - } - /** - * Detaches the behavior from the mesh - */ - detach() { - this.attachedNode = null; - this._removeObservables(); - } - /** - * Recenters the attached node in front of the camera on the next update - */ - recenter() { - this._recenterNextUpdate = true; - } - _angleBetweenVectorAndPlane(vector, normal) { - // Work on copies - this._tmpVectors[0].copyFrom(vector); - vector = this._tmpVectors[0]; - this._tmpVectors[1].copyFrom(normal); - normal = this._tmpVectors[1]; - vector.normalize(); - normal.normalize(); - return Math.PI / 2 - Math.acos(Vector3.Dot(vector, normal)); - } - _length2D(vector) { - return Math.sqrt(vector.x * vector.x + vector.z * vector.z); - } - _distanceClamp(currentToTarget, moveToDefault = false) { - let minDistance = this.minimumDistance; - let maxDistance = this.maximumDistance; - const defaultDistance = this.defaultDistance; - const direction = this._tmpVectors[0]; - direction.copyFrom(currentToTarget); - let currentDistance = direction.length(); - direction.normalizeFromLength(currentDistance); - if (this.ignoreCameraPitchAndRoll) { - // If we don't account for pitch offset, the casted object will float up/down as the reference - // gets closer to it because we will still be casting in the direction of the pitched offset. - // To fix this, only modify the XZ position of the object. - minDistance = this._length2D(direction) * minDistance; - maxDistance = this._length2D(direction) * maxDistance; - const currentDistance2D = this._length2D(currentToTarget); - direction.scaleInPlace(currentDistance / currentDistance2D); - currentDistance = currentDistance2D; - } - let clampedDistance = currentDistance; - if (moveToDefault) { - clampedDistance = defaultDistance; - } - else { - clampedDistance = Scalar.Clamp(currentDistance, minDistance, maxDistance); - } - currentToTarget.copyFrom(direction).scaleInPlace(clampedDistance); - return currentDistance !== clampedDistance; - } - _applyVerticalClamp(currentToTarget) { - if (this.verticalMaxDistance !== 0) { - currentToTarget.y = Scalar.Clamp(currentToTarget.y, -this.verticalMaxDistance, this.verticalMaxDistance); - } - } - _toOrientationQuatToRef(vector, quaternion) { - Quaternion.RotationYawPitchRollToRef(Math.atan2(vector.x, vector.z), Math.atan2(vector.y, Math.sqrt(vector.z * vector.z + vector.x * vector.x)), 0, quaternion); - } - _applyPitchOffset(invertView) { - const forward = this._tmpVectors[0]; - const right = this._tmpVectors[1]; - forward.copyFromFloats(0, 0, this._scene.useRightHandedSystem ? -1 : 1); - right.copyFromFloats(1, 0, 0); - Vector3.TransformNormalToRef(forward, invertView, forward); - forward.y = 0; - forward.normalize(); - Vector3.TransformNormalToRef(right, invertView, right); - Quaternion.RotationAxisToRef(right, (this.pitchOffset * Math.PI) / 180, this._tmpQuaternion); - forward.rotateByQuaternionToRef(this._tmpQuaternion, forward); - this._toOrientationQuatToRef(forward, this._tmpQuaternion); - this._tmpQuaternion.toRotationMatrix(this._tmpMatrix); - // Since we already extracted position from the invert view matrix, we can - // disregard the position part of the matrix in the copy - invertView.copyFrom(this._tmpMatrix); - } - _angularClamp(invertView, currentToTarget) { - const forward = this._tmpVectors[5]; - forward.copyFromFloats(0, 0, this._scene.useRightHandedSystem ? -1 : 1); - const right = this._tmpVectors[6]; - right.copyFromFloats(1, 0, 0); - // forward and right are related to camera frame of reference - Vector3.TransformNormalToRef(forward, invertView, forward); - Vector3.TransformNormalToRef(right, invertView, right); - // Up is global Z - const up = Vector3.UpReadOnly; - const dist = currentToTarget.length(); - if (dist < Epsilon) { - return false; - } - let angularClamped = false; - const rotationQuat = this._tmpQuaternion; - // X-axis leashing - if (this.ignoreCameraPitchAndRoll) { - const angle = Vector3.GetAngleBetweenVectorsOnPlane(currentToTarget, forward, right); - Quaternion.RotationAxisToRef(right, angle, rotationQuat); - currentToTarget.rotateByQuaternionToRef(rotationQuat, currentToTarget); - } - else { - const angle = -Vector3.GetAngleBetweenVectorsOnPlane(currentToTarget, forward, right); - const minMaxAngle = ((this.maxViewVerticalDegrees * Math.PI) / 180) * 0.5; - if (angle < -minMaxAngle) { - Quaternion.RotationAxisToRef(right, -angle - minMaxAngle, rotationQuat); - currentToTarget.rotateByQuaternionToRef(rotationQuat, currentToTarget); - angularClamped = true; - } - else if (angle > minMaxAngle) { - Quaternion.RotationAxisToRef(right, -angle + minMaxAngle, rotationQuat); - currentToTarget.rotateByQuaternionToRef(rotationQuat, currentToTarget); - angularClamped = true; - } - } - // Y-axis leashing - const angle = this._angleBetweenVectorAndPlane(currentToTarget, right) * (this._scene.useRightHandedSystem ? -1 : 1); - const minMaxAngle = ((this.maxViewHorizontalDegrees * Math.PI) / 180) * 0.5; - if (angle < -minMaxAngle) { - Quaternion.RotationAxisToRef(up, -angle - minMaxAngle, rotationQuat); - currentToTarget.rotateByQuaternionToRef(rotationQuat, currentToTarget); - angularClamped = true; - } - else if (angle > minMaxAngle) { - Quaternion.RotationAxisToRef(up, -angle + minMaxAngle, rotationQuat); - currentToTarget.rotateByQuaternionToRef(rotationQuat, currentToTarget); - angularClamped = true; - } - return angularClamped; - } - _orientationClamp(currentToTarget, rotationQuaternion) { - var _a; - // Construct a rotation quat from up vector and target vector - const toFollowed = this._tmpVectors[0]; - toFollowed.copyFrom(currentToTarget).scaleInPlace(-1).normalize(); - const up = this._tmpVectors[1]; - const right = this._tmpVectors[2]; - // We use global up vector to orient the following node (global +Y) - up.copyFromFloats(0, 1, 0); - // Gram-Schmidt to create an orthonormal frame - Vector3.CrossToRef(toFollowed, up, right); - const length = right.length(); - if (length < Epsilon) { - return; - } - right.normalizeFromLength(length); - Vector3.CrossToRef(right, toFollowed, up); - if ((_a = this.attachedNode) === null || _a === void 0 ? void 0 : _a.getScene().useRightHandedSystem) { - Quaternion.FromLookDirectionRHToRef(toFollowed, up, rotationQuaternion); - } - else { - Quaternion.FromLookDirectionLHToRef(toFollowed, up, rotationQuaternion); - } - } - _passedOrientationDeadzone(currentToTarget, forward) { - const leashToFollow = this._tmpVectors[5]; - leashToFollow.copyFrom(currentToTarget); - leashToFollow.normalize(); - const angle = Math.abs(Vector3.GetAngleBetweenVectorsOnPlane(forward, leashToFollow, Vector3.UpReadOnly)); - return (angle * 180) / Math.PI > this.orientToCameraDeadzoneDegrees; - } - _updateLeashing(camera) { - if (this.attachedNode && this._enabled) { - const oldParent = this.attachedNode.parent; - this.attachedNode.setParent(null); - const worldMatrix = this.attachedNode.getWorldMatrix(); - const currentToTarget = this._workingPosition; - const rotationQuaternion = this._workingQuaternion; - const pivot = this.attachedNode.getPivotPoint(); - const invertView = this._tmpInvertView; - invertView.copyFrom(camera.getViewMatrix()); - invertView.invert(); - Vector3.TransformCoordinatesToRef(pivot, worldMatrix, currentToTarget); - const position = this._tmpPosition; - position.copyFromFloats(0, 0, 0); - Vector3.TransformCoordinatesToRef(position, worldMatrix, position); - position.scaleInPlace(-1).subtractInPlace(pivot); - currentToTarget.subtractInPlace(camera.globalPosition); - if (this.ignoreCameraPitchAndRoll) { - this._applyPitchOffset(invertView); - } - let angularClamped = false; - const forward = this._tmpForward; - forward.copyFromFloats(0, 0, this._scene.useRightHandedSystem ? -1 : 1); - Vector3.TransformNormalToRef(forward, invertView, forward); - const nodeForward = this._tmpNodeForward; - nodeForward.copyFromFloats(0, 0, this._scene.useRightHandedSystem ? -1 : 1); - Vector3.TransformNormalToRef(nodeForward, worldMatrix, nodeForward); - if (this._recenterNextUpdate) { - currentToTarget.copyFrom(forward).scaleInPlace(this.defaultDistance); - } - else { - if (this.ignoreAngleClamp) { - const currentDistance = currentToTarget.length(); - currentToTarget.copyFrom(forward).scaleInPlace(currentDistance); - } - else { - angularClamped = this._angularClamp(invertView, currentToTarget); - } - } - let distanceClamped = false; - if (!this.ignoreDistanceClamp) { - distanceClamped = this._distanceClamp(currentToTarget, angularClamped); - this._applyVerticalClamp(currentToTarget); - } - if (this.useFixedVerticalOffset) { - currentToTarget.y = position.y - camera.globalPosition.y + this.fixedVerticalOffset; - } - if (angularClamped || distanceClamped || this._passedOrientationDeadzone(currentToTarget, nodeForward) || this._recenterNextUpdate) { - this._orientationClamp(currentToTarget, rotationQuaternion); - } - this._workingPosition.subtractInPlace(pivot); - this._recenterNextUpdate = false; - this.attachedNode.setParent(oldParent); - } - } - _updateTransformToGoal(elapsed) { - if (!this.attachedNode || !this.followedCamera || !this._enabled) { - return; - } - if (!this.attachedNode.rotationQuaternion) { - this.attachedNode.rotationQuaternion = Quaternion.Identity(); - } - const oldParent = this.attachedNode.parent; - this.attachedNode.setParent(null); - if (!this.interpolatePose) { - this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition); - this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion); - return; - } - // position - const currentDirection = new Vector3(); - currentDirection.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition); - Vector3.SmoothToRef(currentDirection, this._workingPosition, elapsed, this.lerpTime, currentDirection); - currentDirection.addInPlace(this.followedCamera.globalPosition); - this.attachedNode.position.copyFrom(currentDirection); - // rotation - const currentRotation = new Quaternion(); - currentRotation.copyFrom(this.attachedNode.rotationQuaternion); - Quaternion.SmoothToRef(currentRotation, this._workingQuaternion, elapsed, this.lerpTime, this.attachedNode.rotationQuaternion); - this.attachedNode.setParent(oldParent); - } - _addObservables() { - this._lastTick = Date.now(); - this._onBeforeRender = this._scene.onBeforeRenderObservable.add(() => { - if (!this.followedCamera) { - return; - } - const tick = Date.now(); - this._updateLeashing(this.followedCamera); - this._updateTransformToGoal(tick - this._lastTick); - this._lastTick = tick; - }); - } - _removeObservables() { - if (this._onBeforeRender) { - this._scene.onBeforeRenderObservable.remove(this._onBeforeRender); - } - } -} -//# sourceMappingURL=followBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRFeaturesManager.js - -/** - * A list of the currently available features without referencing them - */ -class webXRFeaturesManager_WebXRFeatureName { -} -/** - * The name of the anchor system feature - */ -webXRFeaturesManager_WebXRFeatureName.ANCHOR_SYSTEM = "xr-anchor-system"; -/** - * The name of the background remover feature - */ -webXRFeaturesManager_WebXRFeatureName.BACKGROUND_REMOVER = "xr-background-remover"; -/** - * The name of the hit test feature - */ -webXRFeaturesManager_WebXRFeatureName.HIT_TEST = "xr-hit-test"; -/** - * The name of the mesh detection feature - */ -webXRFeaturesManager_WebXRFeatureName.MESH_DETECTION = "xr-mesh-detection"; -/** - * physics impostors for xr controllers feature - */ -webXRFeaturesManager_WebXRFeatureName.PHYSICS_CONTROLLERS = "xr-physics-controller"; -/** - * The name of the plane detection feature - */ -webXRFeaturesManager_WebXRFeatureName.PLANE_DETECTION = "xr-plane-detection"; -/** - * The name of the pointer selection feature - */ -webXRFeaturesManager_WebXRFeatureName.POINTER_SELECTION = "xr-controller-pointer-selection"; -/** - * The name of the teleportation feature - */ -webXRFeaturesManager_WebXRFeatureName.TELEPORTATION = "xr-controller-teleportation"; -/** - * The name of the feature points feature. - */ -webXRFeaturesManager_WebXRFeatureName.FEATURE_POINTS = "xr-feature-points"; -/** - * The name of the hand tracking feature. - */ -webXRFeaturesManager_WebXRFeatureName.HAND_TRACKING = "xr-hand-tracking"; -/** - * The name of the image tracking feature - */ -webXRFeaturesManager_WebXRFeatureName.IMAGE_TRACKING = "xr-image-tracking"; -/** - * The name of the near interaction feature - */ -webXRFeaturesManager_WebXRFeatureName.NEAR_INTERACTION = "xr-near-interaction"; -/** - * The name of the DOM overlay feature - */ -webXRFeaturesManager_WebXRFeatureName.DOM_OVERLAY = "xr-dom-overlay"; -/** - * The name of the movement feature - */ -webXRFeaturesManager_WebXRFeatureName.MOVEMENT = "xr-controller-movement"; -/** - * The name of the light estimation feature - */ -webXRFeaturesManager_WebXRFeatureName.LIGHT_ESTIMATION = "xr-light-estimation"; -/** - * The name of the eye tracking feature - */ -webXRFeaturesManager_WebXRFeatureName.EYE_TRACKING = "xr-eye-tracking"; -/** - * The name of the walking locomotion feature - */ -webXRFeaturesManager_WebXRFeatureName.WALKING_LOCOMOTION = "xr-walking-locomotion"; -/** - * The name of the composition layers feature - */ -webXRFeaturesManager_WebXRFeatureName.LAYERS = "xr-layers"; -/** - * The name of the depth sensing feature - */ -webXRFeaturesManager_WebXRFeatureName.DEPTH_SENSING = "xr-depth-sensing"; -/** - * The name of the WebXR Space Warp feature - */ -webXRFeaturesManager_WebXRFeatureName.SPACE_WARP = "xr-space-warp"; -/** - * The WebXR features manager is responsible of enabling or disabling features required for the current XR session. - * It is mainly used in AR sessions. - * - * A feature can have a version that is defined by Babylon (and does not correspond with the webxr version). - */ -class WebXRFeaturesManager { - /** - * constructs a new features manages. - * - * @param _xrSessionManager an instance of WebXRSessionManager - */ - constructor(_xrSessionManager) { - this._xrSessionManager = _xrSessionManager; - this._features = {}; - // when session starts / initialized - attach - this._xrSessionManager.onXRSessionInit.add(() => { - this.getEnabledFeatures().forEach((featureName) => { - const feature = this._features[featureName]; - if (feature.enabled && !feature.featureImplementation.attached && !feature.featureImplementation.disableAutoAttach) { - this.attachFeature(featureName); - } - }); - }); - // when session ends - detach - this._xrSessionManager.onXRSessionEnded.add(() => { - this.getEnabledFeatures().forEach((featureName) => { - const feature = this._features[featureName]; - if (feature.enabled && feature.featureImplementation.attached) { - // detach, but don't disable! - this.detachFeature(featureName); - } - }); - }); - } - /** - * Used to register a module. After calling this function a developer can use this feature in the scene. - * Mainly used internally. - * - * @param featureName the name of the feature to register - * @param constructorFunction the function used to construct the module - * @param version the (babylon) version of the module - * @param stable is that a stable version of this module - */ - static AddWebXRFeature(featureName, constructorFunction, version = 1, stable = false) { - this._AvailableFeatures[featureName] = this._AvailableFeatures[featureName] || { latest: version }; - if (version > this._AvailableFeatures[featureName].latest) { - this._AvailableFeatures[featureName].latest = version; - } - if (stable) { - this._AvailableFeatures[featureName].stable = version; - } - this._AvailableFeatures[featureName][version] = constructorFunction; - } - /** - * Returns a constructor of a specific feature. - * - * @param featureName the name of the feature to construct - * @param version the version of the feature to load - * @param xrSessionManager the xrSessionManager. Used to construct the module - * @param options optional options provided to the module. - * @returns a function that, when called, will return a new instance of this feature - */ - static ConstructFeature(featureName, version = 1, xrSessionManager, options) { - const constructorFunction = this._AvailableFeatures[featureName][version]; - if (!constructorFunction) { - // throw an error? return nothing? - throw new Error("feature not found"); - } - return constructorFunction(xrSessionManager, options); - } - /** - * Can be used to return the list of features currently registered - * - * @returns an Array of available features - */ - static GetAvailableFeatures() { - return Object.keys(this._AvailableFeatures); - } - /** - * Gets the versions available for a specific feature - * @param featureName the name of the feature - * @returns an array with the available versions - */ - static GetAvailableVersions(featureName) { - return Object.keys(this._AvailableFeatures[featureName]); - } - /** - * Return the latest unstable version of this feature - * @param featureName the name of the feature to search - * @returns the version number. if not found will return -1 - */ - static GetLatestVersionOfFeature(featureName) { - return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].latest) || -1; - } - /** - * Return the latest stable version of this feature - * @param featureName the name of the feature to search - * @returns the version number. if not found will return -1 - */ - static GetStableVersionOfFeature(featureName) { - return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].stable) || -1; - } - /** - * Attach a feature to the current session. Mainly used when session started to start the feature effect. - * Can be used during a session to start a feature - * @param featureName the name of feature to attach - */ - attachFeature(featureName) { - const feature = this._features[featureName]; - if (feature && feature.enabled && !feature.featureImplementation.attached) { - feature.featureImplementation.attach(); - } - } - /** - * Can be used inside a session or when the session ends to detach a specific feature - * @param featureName the name of the feature to detach - */ - detachFeature(featureName) { - const feature = this._features[featureName]; - if (feature && feature.featureImplementation.attached) { - feature.featureImplementation.detach(); - } - } - /** - * Used to disable an already-enabled feature - * The feature will be disposed and will be recreated once enabled. - * @param featureName the feature to disable - * @returns true if disable was successful - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - disableFeature(featureName) { - const name = typeof featureName === "string" ? featureName : featureName.Name; - const feature = this._features[name]; - if (feature && feature.enabled) { - feature.enabled = false; - this.detachFeature(name); - feature.featureImplementation.dispose(); - delete this._features[name]; - return true; - } - return false; - } - /** - * dispose this features manager - */ - dispose() { - this.getEnabledFeatures().forEach((feature) => { - this.disableFeature(feature); - }); - } - /** - * 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. - * 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. - * - * @param featureName the name of the feature to load or the class of the feature - * @param version optional version to load. if not provided the latest version will be enabled - * @param moduleOptions options provided to the module. Ses the module documentation / constructor - * @param attachIfPossible if set to true (default) the feature will be automatically attached, if it is currently possible - * @param required is this feature required to the app. If set to true the session init will fail if the feature is not available. - * @returns a new constructed feature or throws an error if feature not found or conflicts with another enabled feature. - */ - enableFeature( - // eslint-disable-next-line @typescript-eslint/naming-convention - featureName, version = "latest", moduleOptions = {}, attachIfPossible = true, required = true) { - const name = typeof featureName === "string" ? featureName : featureName.Name; - let versionToLoad = 0; - if (typeof version === "string") { - if (!version) { - throw new Error(`Error in provided version - ${name} (${version})`); - } - if (version === "stable") { - versionToLoad = WebXRFeaturesManager.GetStableVersionOfFeature(name); - } - else if (version === "latest") { - versionToLoad = WebXRFeaturesManager.GetLatestVersionOfFeature(name); - } - else { - // try loading the number the string represents - versionToLoad = +version; - } - if (versionToLoad === -1 || isNaN(versionToLoad)) { - throw new Error(`feature not found - ${name} (${version})`); - } - } - else { - versionToLoad = version; - } - // check if there is a feature conflict - const conflictingFeature = WebXRFeaturesManager._ConflictingFeatures[name]; - if (conflictingFeature !== undefined && this.getEnabledFeatures().indexOf(conflictingFeature) !== -1) { - throw new Error(`Feature ${name} cannot be enabled while ${conflictingFeature} is enabled.`); - } - // check if already initialized - const feature = this._features[name]; - const constructFunction = WebXRFeaturesManager.ConstructFeature(name, versionToLoad, this._xrSessionManager, moduleOptions); - if (!constructFunction) { - // report error? - throw new Error(`feature not found - ${name}`); - } - /* If the feature is already enabled, detach and dispose it, and create a new one */ - if (feature) { - this.disableFeature(name); - } - const constructed = constructFunction(); - if (constructed.dependsOn) { - const dependentsFound = constructed.dependsOn.every((featureName) => !!this._features[featureName]); - if (!dependentsFound) { - throw new Error(`Dependant features missing. Make sure the following features are enabled - ${constructed.dependsOn.join(", ")}`); - } - } - if (constructed.isCompatible()) { - this._features[name] = { - featureImplementation: constructed, - enabled: true, - version: versionToLoad, - required, - }; - if (attachIfPossible) { - // if session started already, request and enable - if (this._xrSessionManager.session && !this._features[name].featureImplementation.attached) { - // enable feature - this.attachFeature(name); - } - } - else { - // disable auto-attach when session starts - this._features[name].featureImplementation.disableAutoAttach = true; - } - return this._features[name].featureImplementation; - } - else { - if (required) { - throw new Error("required feature not compatible"); - } - else { - tools_Tools.Warn(`Feature ${name} not compatible with the current environment/browser and was not enabled.`); - return constructed; - } - } - } - /** - * get the implementation of an enabled feature. - * @param featureName the name of the feature to load - * @returns the feature class, if found - */ - getEnabledFeature(featureName) { - return this._features[featureName] && this._features[featureName].featureImplementation; - } - /** - * Get the list of enabled features - * @returns an array of enabled features - */ - getEnabledFeatures() { - return Object.keys(this._features); - } - /** - * This function will extend the session creation configuration object with enabled features. - * If, for example, the anchors feature is enabled, it will be automatically added to the optional or required features list, - * according to the defined "required" variable, provided during enableFeature call - * @param xrSessionInit the xr Session init object to extend - * - * @returns an extended XRSessionInit object - */ - async _extendXRSessionInitObject(xrSessionInit) { - const enabledFeatures = this.getEnabledFeatures(); - for (const featureName of enabledFeatures) { - const feature = this._features[featureName]; - const nativeName = feature.featureImplementation.xrNativeFeatureName; - if (nativeName) { - if (feature.required) { - xrSessionInit.requiredFeatures = xrSessionInit.requiredFeatures || []; - if (xrSessionInit.requiredFeatures.indexOf(nativeName) === -1) { - xrSessionInit.requiredFeatures.push(nativeName); - } - } - else { - xrSessionInit.optionalFeatures = xrSessionInit.optionalFeatures || []; - if (xrSessionInit.optionalFeatures.indexOf(nativeName) === -1) { - xrSessionInit.optionalFeatures.push(nativeName); - } - } - } - if (feature.featureImplementation.getXRSessionInitExtension) { - const extended = await feature.featureImplementation.getXRSessionInitExtension(); - xrSessionInit = Object.assign(Object.assign({}, xrSessionInit), extended); - } - } - return xrSessionInit; - } -} -WebXRFeaturesManager._AvailableFeatures = {}; -/** - * The key is the feature to check and the value is the feature that conflicts. - */ -WebXRFeaturesManager._ConflictingFeatures = { - [webXRFeaturesManager_WebXRFeatureName.TELEPORTATION]: webXRFeaturesManager_WebXRFeatureName.MOVEMENT, - [webXRFeaturesManager_WebXRFeatureName.MOVEMENT]: webXRFeaturesManager_WebXRFeatureName.TELEPORTATION, -}; -//# sourceMappingURL=webXRFeaturesManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRAbstractFeature.js -/** - * This is the base class for all WebXR features. - * Since most features require almost the same resources and callbacks, this class can be used to simplify the development - * Note that since the features manager is using the `IWebXRFeature` you are in no way obligated to use this class - */ -class WebXRAbstractFeature { - /** - * Construct a new (abstract) WebXR feature - * @param _xrSessionManager the xr session manager for this feature - */ - constructor(_xrSessionManager) { - this._xrSessionManager = _xrSessionManager; - this._attached = false; - this._removeOnDetach = []; - /** - * Is this feature disposed? - */ - this.isDisposed = false; - /** - * Should auto-attach be disabled? - */ - this.disableAutoAttach = false; - /** - * The name of the native xr feature name (like anchor, hit-test, or hand-tracking) - */ - this.xrNativeFeatureName = ""; - } - /** - * Is this feature attached - */ - get attached() { - return this._attached; - } - /** - * attach this feature - * - * @param force should attachment be forced (even when already attached) - * @returns true if successful, false is failed or already attached - */ - attach(force) { - // do not attach a disposed feature - if (this.isDisposed) { - return false; - } - if (!force) { - if (this.attached) { - return false; - } - } - else { - if (this.attached) { - // detach first, to be sure - this.detach(); - } - } - this._attached = true; - this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable, (frame) => this._onXRFrame(frame)); - return true; - } - /** - * detach this feature. - * - * @returns true if successful, false if failed or already detached - */ - detach() { - if (!this._attached) { - this.disableAutoAttach = true; - return false; - } - this._attached = false; - this._removeOnDetach.forEach((toRemove) => { - toRemove.observable.remove(toRemove.observer); - }); - return true; - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - this.detach(); - this.isDisposed = true; - } - /** - * This function will be executed during before enabling the feature and can be used to not-allow enabling it. - * Note that at this point the session has NOT started, so this is purely checking if the browser supports it - * - * @returns whether or not the feature is compatible in this environment - */ - isCompatible() { - return true; - } - /** - * This is used to register callbacks that will automatically be removed when detach is called. - * @param observable the observable to which the observer will be attached - * @param callback the callback to register - */ - _addNewAttachObserver(observable, callback) { - this._removeOnDetach.push({ - observable, - observer: observable.add(callback), - }); - } -} -//# sourceMappingURL=WebXRAbstractFeature.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v1/physicsJoint.js -/** - * This is a holder class for the physics joint created by the physics plugin - * It holds a set of functions to control the underlying joint - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -class PhysicsJoint { - /** - * Initializes the physics joint - * @param type The type of the physics joint - * @param jointData The data for the physics joint - */ - constructor( - /** - * The type of the physics joint - */ - type, - /** - * The data for the physics joint - */ - jointData) { - this.type = type; - this.jointData = jointData; - jointData.nativeParams = jointData.nativeParams || {}; - } - /** - * Gets the physics joint - */ - get physicsJoint() { - return this._physicsJoint; - } - /** - * Sets the physics joint - */ - set physicsJoint(newJoint) { - if (this._physicsJoint) { - //remove from the world - } - this._physicsJoint = newJoint; - } - /** - * Sets the physics plugin - */ - set physicsPlugin(physicsPlugin) { - this._physicsPlugin = physicsPlugin; - } - /** - * Execute a function that is physics-plugin specific. - * @param {Function} func the function that will be executed. - * It accepts two parameters: the physics world and the physics joint - */ - executeNativeFunction(func) { - func(this._physicsPlugin.world, this._physicsJoint); - } -} -//TODO check if the native joints are the same -//Joint Types -/** - * Distance-Joint type - */ -PhysicsJoint.DistanceJoint = 0; -/** - * Hinge-Joint type - */ -PhysicsJoint.HingeJoint = 1; -/** - * Ball-and-Socket joint type - */ -PhysicsJoint.BallAndSocketJoint = 2; -/** - * Wheel-Joint type - */ -PhysicsJoint.WheelJoint = 3; -/** - * Slider-Joint type - */ -PhysicsJoint.SliderJoint = 4; -//OIMO -/** - * Prismatic-Joint type - */ -PhysicsJoint.PrismaticJoint = 5; -// -/** - * Universal-Joint type - * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions) - */ -PhysicsJoint.UniversalJoint = 6; -/** - * Hinge-Joint 2 type - */ -PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint; -//Cannon -/** - * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters - */ -PhysicsJoint.PointToPointJoint = 8; -//Cannon only at the moment -/** - * Spring-Joint type - */ -PhysicsJoint.SpringJoint = 9; -/** - * Lock-Joint type - */ -PhysicsJoint.LockJoint = 10; -/** - * A class representing a physics distance joint - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -class DistanceJoint extends (/* unused pure expression or super */ null && (PhysicsJoint)) { - /** - * - * @param jointData The data for the Distance-Joint - */ - constructor(jointData) { - super(PhysicsJoint.DistanceJoint, jointData); - } - /** - * Update the predefined distance. - * @param maxDistance The maximum preferred distance - * @param minDistance The minimum preferred distance - */ - updateDistance(maxDistance, minDistance) { - this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance); - } -} -/** - * Represents a Motor-Enabled Joint - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -class MotorEnabledJoint extends (/* unused pure expression or super */ null && (PhysicsJoint)) { - /** - * Initializes the Motor-Enabled Joint - * @param type The type of the joint - * @param jointData The physical joint data for the joint - */ - constructor(type, jointData) { - super(type, jointData); - } - /** - * Set the motor values. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param force the force to apply - * @param maxForce max force for this motor. - */ - setMotor(force, maxForce) { - this._physicsPlugin.setMotor(this, force || 0, maxForce); - } - /** - * Set the motor's limits. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param upperLimit The upper limit of the motor - * @param lowerLimit The lower limit of the motor - */ - setLimit(upperLimit, lowerLimit) { - this._physicsPlugin.setLimit(this, upperLimit, lowerLimit); - } -} -/** - * This class represents a single physics Hinge-Joint - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -class HingeJoint extends (/* unused pure expression or super */ null && (MotorEnabledJoint)) { - /** - * Initializes the Hinge-Joint - * @param jointData The joint data for the Hinge-Joint - */ - constructor(jointData) { - super(PhysicsJoint.HingeJoint, jointData); - } - /** - * Set the motor values. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param {number} force the force to apply - * @param {number} maxForce max force for this motor. - */ - setMotor(force, maxForce) { - this._physicsPlugin.setMotor(this, force || 0, maxForce); - } - /** - * Set the motor's limits. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param upperLimit The upper limit of the motor - * @param lowerLimit The lower limit of the motor - */ - setLimit(upperLimit, lowerLimit) { - this._physicsPlugin.setLimit(this, upperLimit, lowerLimit); - } -} -/** - * This class represents a dual hinge physics joint (same as wheel joint) - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -class Hinge2Joint extends (/* unused pure expression or super */ null && (MotorEnabledJoint)) { - /** - * Initializes the Hinge2-Joint - * @param jointData The joint data for the Hinge2-Joint - */ - constructor(jointData) { - super(PhysicsJoint.Hinge2Joint, jointData); - } - /** - * Set the motor values. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param targetSpeed the speed the motor is to reach - * @param maxForce max force for this motor. - * @param motorIndex motor's index, 0 or 1. - */ - setMotor(targetSpeed, maxForce, motorIndex = 0) { - this._physicsPlugin.setMotor(this, targetSpeed || 0, maxForce, motorIndex); - } - /** - * Set the motor limits. - * Attention, this function is plugin specific. Engines won't react 100% the same. - * @param upperLimit the upper limit - * @param lowerLimit lower limit - * @param motorIndex the motor's index, 0 or 1. - */ - setLimit(upperLimit, lowerLimit, motorIndex = 0) { - this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex); - } -} -//# sourceMappingURL=physicsJoint.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v1/physicsImpostor.js - - - - - - - -mesh_Mesh._PhysicsImpostorParser = function (scene, physicObject, jsonObject) { - return new physicsImpostor_PhysicsImpostor(physicObject, jsonObject.physicsImpostor, { - mass: jsonObject.physicsMass, - friction: jsonObject.physicsFriction, - restitution: jsonObject.physicsRestitution, - }, scene); -}; -/** - * Represents a physics imposter - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -class physicsImpostor_PhysicsImpostor { - /** - * Specifies if the physics imposter is disposed - */ - get isDisposed() { - return this._isDisposed; - } - /** - * Gets the mass of the physics imposter - */ - get mass() { - return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0; - } - set mass(value) { - this.setMass(value); - } - /** - * Gets the coefficient of friction - */ - get friction() { - return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0; - } - /** - * Sets the coefficient of friction - */ - set friction(value) { - if (!this._physicsEngine) { - return; - } - this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value); - } - /** - * Gets the coefficient of restitution - */ - get restitution() { - return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0; - } - /** - * Sets the coefficient of restitution - */ - set restitution(value) { - if (!this._physicsEngine) { - return; - } - this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value); - } - /** - * Gets the pressure of a soft body; only supported by the AmmoJSPlugin - */ - get pressure() { - if (!this._physicsEngine) { - return 0; - } - const plugin = this._physicsEngine.getPhysicsPlugin(); - if (!plugin.setBodyPressure) { - return 0; - } - return plugin.getBodyPressure(this); - } - /** - * Sets the pressure of a soft body; only supported by the AmmoJSPlugin - */ - set pressure(value) { - if (!this._physicsEngine) { - return; - } - const plugin = this._physicsEngine.getPhysicsPlugin(); - if (!plugin.setBodyPressure) { - return; - } - plugin.setBodyPressure(this, value); - } - /** - * Gets the stiffness of a soft body; only supported by the AmmoJSPlugin - */ - get stiffness() { - if (!this._physicsEngine) { - return 0; - } - const plugin = this._physicsEngine.getPhysicsPlugin(); - if (!plugin.getBodyStiffness) { - return 0; - } - return plugin.getBodyStiffness(this); - } - /** - * Sets the stiffness of a soft body; only supported by the AmmoJSPlugin - */ - set stiffness(value) { - if (!this._physicsEngine) { - return; - } - const plugin = this._physicsEngine.getPhysicsPlugin(); - if (!plugin.setBodyStiffness) { - return; - } - plugin.setBodyStiffness(this, value); - } - /** - * Gets the velocityIterations of a soft body; only supported by the AmmoJSPlugin - */ - get velocityIterations() { - if (!this._physicsEngine) { - return 0; - } - const plugin = this._physicsEngine.getPhysicsPlugin(); - if (!plugin.getBodyVelocityIterations) { - return 0; - } - return plugin.getBodyVelocityIterations(this); - } - /** - * Sets the velocityIterations of a soft body; only supported by the AmmoJSPlugin - */ - set velocityIterations(value) { - if (!this._physicsEngine) { - return; - } - const plugin = this._physicsEngine.getPhysicsPlugin(); - if (!plugin.setBodyVelocityIterations) { - return; - } - plugin.setBodyVelocityIterations(this, value); - } - /** - * Gets the positionIterations of a soft body; only supported by the AmmoJSPlugin - */ - get positionIterations() { - if (!this._physicsEngine) { - return 0; - } - const plugin = this._physicsEngine.getPhysicsPlugin(); - if (!plugin.getBodyPositionIterations) { - return 0; - } - return plugin.getBodyPositionIterations(this); - } - /** - * Sets the positionIterations of a soft body; only supported by the AmmoJSPlugin - */ - set positionIterations(value) { - if (!this._physicsEngine) { - return; - } - const plugin = this._physicsEngine.getPhysicsPlugin(); - if (!plugin.setBodyPositionIterations) { - return; - } - plugin.setBodyPositionIterations(this, value); - } - /** - * Initializes the physics imposter - * @param object The physics-enabled object used as the physics imposter - * @param type The type of the physics imposter. Types are available as static members of this class. - * @param _options The options for the physics imposter - * @param _scene The Babylon scene - */ - constructor( - /** - * The physics-enabled object used as the physics imposter - */ - object, - /** - * The type of the physics imposter - */ - type, _options = { mass: 0 }, _scene) { - this.object = object; - this.type = type; - this._options = _options; - this._scene = _scene; - /** @internal */ - this._pluginData = {}; - this._bodyUpdateRequired = false; - this._onBeforePhysicsStepCallbacks = new Array(); - this._onAfterPhysicsStepCallbacks = new Array(); - /** @internal */ - this._onPhysicsCollideCallbacks = []; - this._deltaPosition = math_vector_Vector3.Zero(); - this._isDisposed = false; - /** - * @internal - */ - this.soft = false; - /** - * @internal - */ - this.segments = 0; - //temp variables for parent rotation calculations - //private _mats: Array<Matrix> = [new Matrix(), new Matrix()]; - this._tmpQuat = new math_vector_Quaternion(); - this._tmpQuat2 = new math_vector_Quaternion(); - /** - * this function is executed by the physics engine. - */ - this.beforeStep = () => { - if (!this._physicsEngine) { - return; - } - this.object.translate(this._deltaPosition, -1); - this._deltaRotationConjugated && - this.object.rotationQuaternion && - this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated, this.object.rotationQuaternion); - this.object.computeWorldMatrix(false); - if (this.object.parent && this.object.rotationQuaternion) { - this.getParentsRotation(); - this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this._tmpQuat); - } - else { - this._tmpQuat.copyFrom(this.object.rotationQuaternion || new math_vector_Quaternion()); - } - if (!this._options.disableBidirectionalTransformation) { - this.object.rotationQuaternion && - this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this, /*bInfo.boundingBox.centerWorld*/ this.object.getAbsolutePosition(), this._tmpQuat); - } - this._onBeforePhysicsStepCallbacks.forEach((func) => { - func(this); - }); - }; - /** - * this function is executed by the physics engine - */ - this.afterStep = () => { - if (!this._physicsEngine) { - return; - } - this._onAfterPhysicsStepCallbacks.forEach((func) => { - func(this); - }); - this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this); - // object has now its world rotation. needs to be converted to local. - if (this.object.parent && this.object.rotationQuaternion) { - this.getParentsRotation(); - this._tmpQuat.conjugateInPlace(); - this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this.object.rotationQuaternion); - } - // take the position set and make it the absolute position of this object. - this.object.setAbsolutePosition(this.object.position); - if (this._deltaRotation) { - this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotation, this.object.rotationQuaternion); - this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation, physicsImpostor_PhysicsImpostor._TmpVecs[0]); - this.object.translate(physicsImpostor_PhysicsImpostor._TmpVecs[0], 1); - } - else { - this.object.translate(this._deltaPosition, 1); - } - this.object.computeWorldMatrix(true); - }; - /** - * Legacy collision detection event support - */ - this.onCollideEvent = null; - /** - * - * @param e - * @returns - */ - this.onCollide = (e) => { - if (!this._onPhysicsCollideCallbacks.length && !this.onCollideEvent) { - return; - } - if (!this._physicsEngine) { - return; - } - const otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body); - if (otherImpostor) { - // Legacy collision detection event support - if (this.onCollideEvent) { - this.onCollideEvent(this, otherImpostor); - } - this._onPhysicsCollideCallbacks - .filter((obj) => { - return obj.otherImpostors.indexOf(otherImpostor) !== -1; - }) - .forEach((obj) => { - obj.callback(this, otherImpostor, e.point, e.distance, e.impulse, e.normal); - }); - } - }; - //sanity check! - if (!this.object) { - logger_Logger.Error("No object was provided. A physics object is obligatory"); - return; - } - if (this.object.parent && _options.mass !== 0) { - logger_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."); - } - // Legacy support for old syntax. - if (!this._scene && object.getScene) { - this._scene = object.getScene(); - } - if (!this._scene) { - return; - } - if (this.type > 100) { - this.soft = true; - } - this._physicsEngine = this._scene.getPhysicsEngine(); - if (!this._physicsEngine) { - logger_Logger.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."); - } - else { - //set the object's quaternion, if not set - if (!this.object.rotationQuaternion) { - if (this.object.rotation) { - this.object.rotationQuaternion = math_vector_Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z); - } - else { - this.object.rotationQuaternion = new math_vector_Quaternion(); - } - } - //default options params - this._options.mass = _options.mass === void 0 ? 0 : _options.mass; - this._options.friction = _options.friction === void 0 ? 0.2 : _options.friction; - this._options.restitution = _options.restitution === void 0 ? 0.2 : _options.restitution; - if (this.soft) { - //softbody mass must be above 0; - this._options.mass = this._options.mass > 0 ? this._options.mass : 1; - this._options.pressure = _options.pressure === void 0 ? 200 : _options.pressure; - this._options.stiffness = _options.stiffness === void 0 ? 1 : _options.stiffness; - this._options.velocityIterations = _options.velocityIterations === void 0 ? 20 : _options.velocityIterations; - this._options.positionIterations = _options.positionIterations === void 0 ? 20 : _options.positionIterations; - this._options.fixedPoints = _options.fixedPoints === void 0 ? 0 : _options.fixedPoints; - this._options.margin = _options.margin === void 0 ? 0 : _options.margin; - this._options.damping = _options.damping === void 0 ? 0 : _options.damping; - this._options.path = _options.path === void 0 ? null : _options.path; - this._options.shape = _options.shape === void 0 ? null : _options.shape; - } - this._joints = []; - //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that. - if (!this.object.parent || this._options.ignoreParent) { - this._init(); - } - else if (this.object.parent.physicsImpostor) { - logger_Logger.Warn("You must affect impostors to children before affecting impostor to parent."); - } - } - } - /** - * This function will completely initialize this impostor. - * It will create a new body - but only if this mesh has no parent. - * If it has, this impostor will not be used other than to define the impostor - * of the child mesh. - * @internal - */ - _init() { - if (!this._physicsEngine) { - return; - } - this._physicsEngine.removeImpostor(this); - this.physicsBody = null; - this._parent = this._parent || this._getPhysicsParent(); - if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) { - this._physicsEngine.addImpostor(this); - } - } - _getPhysicsParent() { - if (this.object.parent instanceof abstractMesh_AbstractMesh) { - const parentMesh = this.object.parent; - return parentMesh.physicsImpostor; - } - return null; - } - /** - * Should a new body be generated. - * @returns boolean specifying if body initialization is required - */ - isBodyInitRequired() { - return this._bodyUpdateRequired || (!this._physicsBody && (!this._parent || !!this._options.ignoreParent)); - } - /** - * Sets the updated scaling - */ - setScalingUpdated() { - this.forceUpdate(); - } - /** - * Force a regeneration of this or the parent's impostor's body. - * Use with caution - This will remove all previously-instantiated joints. - */ - forceUpdate() { - this._init(); - if (this.parent && !this._options.ignoreParent) { - this.parent.forceUpdate(); - } - } - /*public get mesh(): AbstractMesh { - return this._mesh; - }*/ - /** - * Gets the body that holds this impostor. Either its own, or its parent. - */ - get physicsBody() { - return this._parent && !this._options.ignoreParent ? this._parent.physicsBody : this._physicsBody; - } - /** - * Get the parent of the physics imposter - * @returns Physics imposter or null - */ - get parent() { - return !this._options.ignoreParent && this._parent ? this._parent : null; - } - /** - * Sets the parent of the physics imposter - */ - set parent(value) { - this._parent = value; - } - /** - * Set the physics body. Used mainly by the physics engine/plugin - */ - set physicsBody(physicsBody) { - if (this._physicsBody && this._physicsEngine) { - this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this); - } - this._physicsBody = physicsBody; - this.resetUpdateFlags(); - } - /** - * Resets the update flags - */ - resetUpdateFlags() { - this._bodyUpdateRequired = false; - } - /** - * Gets the object extents - * @returns the object extents - */ - getObjectExtents() { - if (this.object.getBoundingInfo) { - const q = this.object.rotationQuaternion; - const scaling = this.object.scaling.clone(); - //reset rotation - this.object.rotationQuaternion = physicsImpostor_PhysicsImpostor.IDENTITY_QUATERNION; - //calculate the world matrix with no rotation - const worldMatrix = this.object.computeWorldMatrix && this.object.computeWorldMatrix(true); - if (worldMatrix) { - worldMatrix.decompose(scaling, undefined, undefined); - } - const boundingInfo = this.object.getBoundingInfo(); - // get the global scaling of the object - const size = boundingInfo.boundingBox.extendSize.scale(2).multiplyInPlace(scaling); - size.x = Math.abs(size.x); - size.y = Math.abs(size.y); - size.z = Math.abs(size.z); - //bring back the rotation - this.object.rotationQuaternion = q; - //calculate the world matrix with the new rotation - this.object.computeWorldMatrix && this.object.computeWorldMatrix(true); - return size; - } - else { - return physicsImpostor_PhysicsImpostor.DEFAULT_OBJECT_SIZE; - } - } - /** - * Gets the object center - * @returns The object center - */ - getObjectCenter() { - if (this.object.getBoundingInfo) { - const boundingInfo = this.object.getBoundingInfo(); - return boundingInfo.boundingBox.centerWorld; - } - else { - return this.object.position; - } - } - /** - * Get a specific parameter from the options parameters - * @param paramName The object parameter name - * @returns The object parameter - */ - getParam(paramName) { - return this._options[paramName]; - } - /** - * Sets a specific parameter in the options given to the physics plugin - * @param paramName The parameter name - * @param value The value of the parameter - */ - setParam(paramName, value) { - this._options[paramName] = value; - this._bodyUpdateRequired = true; - } - /** - * Specifically change the body's mass. Won't recreate the physics body object - * @param mass The mass of the physics imposter - */ - setMass(mass) { - if (this.getParam("mass") !== mass) { - this.setParam("mass", mass); - } - if (this._physicsEngine) { - this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass); - } - } - /** - * Gets the linear velocity - * @returns linear velocity or null - */ - getLinearVelocity() { - return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : math_vector_Vector3.Zero(); - } - /** - * Sets the linear velocity - * @param velocity linear velocity or null - */ - setLinearVelocity(velocity) { - if (this._physicsEngine) { - this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity); - } - } - /** - * Gets the angular velocity - * @returns angular velocity or null - */ - getAngularVelocity() { - return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : math_vector_Vector3.Zero(); - } - /** - * Sets the angular velocity - * @param velocity The velocity or null - */ - setAngularVelocity(velocity) { - if (this._physicsEngine) { - this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity); - } - } - /** - * Execute a function with the physics plugin native code - * Provide a function the will have two variables - the world object and the physics body object - * @param func The function to execute with the physics plugin native code - */ - executeNativeFunction(func) { - if (this._physicsEngine) { - func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody); - } - } - /** - * Register a function that will be executed before the physics world is stepping forward - * @param func The function to execute before the physics world is stepped forward - */ - registerBeforePhysicsStep(func) { - this._onBeforePhysicsStepCallbacks.push(func); - } - /** - * Unregister a function that will be executed before the physics world is stepping forward - * @param func The function to execute before the physics world is stepped forward - */ - unregisterBeforePhysicsStep(func) { - const index = this._onBeforePhysicsStepCallbacks.indexOf(func); - if (index > -1) { - this._onBeforePhysicsStepCallbacks.splice(index, 1); - } - else { - logger_Logger.Warn("Function to remove was not found"); - } - } - /** - * Register a function that will be executed after the physics step - * @param func The function to execute after physics step - */ - registerAfterPhysicsStep(func) { - this._onAfterPhysicsStepCallbacks.push(func); - } - /** - * Unregisters a function that will be executed after the physics step - * @param func The function to execute after physics step - */ - unregisterAfterPhysicsStep(func) { - const index = this._onAfterPhysicsStepCallbacks.indexOf(func); - if (index > -1) { - this._onAfterPhysicsStepCallbacks.splice(index, 1); - } - else { - logger_Logger.Warn("Function to remove was not found"); - } - } - /** - * register a function that will be executed when this impostor collides against a different body - * @param collideAgainst Physics imposter, or array of physics imposters to collide against - * @param func Callback that is executed on collision - */ - registerOnPhysicsCollide(collideAgainst, func) { - const collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst]; - this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList }); - } - /** - * Unregisters the physics imposter's collision callback - * @param collideAgainst The physics object to collide against - * @param func Callback to execute on collision - */ - unregisterOnPhysicsCollide(collideAgainst, func) { - const collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst]; - let index = -1; - const found = this._onPhysicsCollideCallbacks.some((cbDef, idx) => { - if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) { - // chcek the arrays match - const sameList = cbDef.otherImpostors.every((impostor) => { - return collidedAgainstList.indexOf(impostor) > -1; - }); - if (sameList) { - index = idx; - } - return sameList; - } - return false; - }); - if (found) { - this._onPhysicsCollideCallbacks.splice(index, 1); - } - else { - logger_Logger.Warn("Function to remove was not found"); - } - } - /** - * Get the parent rotation - * @returns The parent rotation - */ - getParentsRotation() { - let parent = this.object.parent; - this._tmpQuat.copyFromFloats(0, 0, 0, 1); - while (parent) { - if (parent.rotationQuaternion) { - this._tmpQuat2.copyFrom(parent.rotationQuaternion); - } - else { - math_vector_Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2); - } - this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat); - parent = parent.parent; - } - return this._tmpQuat; - } - /** - * Apply a force - * @param force The force to apply - * @param contactPoint The contact point for the force - * @returns The physics imposter - */ - applyForce(force, contactPoint) { - if (this._physicsEngine) { - this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint); - } - return this; - } - /** - * Apply an impulse - * @param force The impulse force - * @param contactPoint The contact point for the impulse force - * @returns The physics imposter - */ - applyImpulse(force, contactPoint) { - if (this._physicsEngine) { - this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint); - } - return this; - } - /** - * A help function to create a joint - * @param otherImpostor A physics imposter used to create a joint - * @param jointType The type of joint - * @param jointData The data for the joint - * @returns The physics imposter - */ - createJoint(otherImpostor, jointType, jointData) { - const joint = new PhysicsJoint(jointType, jointData); - this.addJoint(otherImpostor, joint); - return this; - } - /** - * Add a joint to this impostor with a different impostor - * @param otherImpostor A physics imposter used to add a joint - * @param joint The joint to add - * @returns The physics imposter - */ - addJoint(otherImpostor, joint) { - this._joints.push({ - otherImpostor: otherImpostor, - joint: joint, - }); - if (this._physicsEngine) { - this._physicsEngine.addJoint(this, otherImpostor, joint); - } - return this; - } - /** - * Add an anchor to a cloth impostor - * @param otherImpostor rigid impostor to anchor to - * @param width ratio across width from 0 to 1 - * @param height ratio up height from 0 to 1 - * @param influence the elasticity between cloth impostor and anchor from 0, very stretchy to 1, little stretch - * @param noCollisionBetweenLinkedBodies when true collisions between cloth impostor and anchor are ignored; default false - * @returns impostor the soft imposter - */ - addAnchor(otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies) { - if (!this._physicsEngine) { - return this; - } - const plugin = this._physicsEngine.getPhysicsPlugin(); - if (!plugin.appendAnchor) { - return this; - } - if (this._physicsEngine) { - plugin.appendAnchor(this, otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies); - } - return this; - } - /** - * Add a hook to a rope impostor - * @param otherImpostor rigid impostor to anchor to - * @param length ratio across rope from 0 to 1 - * @param influence the elasticity between rope impostor and anchor from 0, very stretchy to 1, little stretch - * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false - * @returns impostor the rope imposter - */ - addHook(otherImpostor, length, influence, noCollisionBetweenLinkedBodies) { - if (!this._physicsEngine) { - return this; - } - const plugin = this._physicsEngine.getPhysicsPlugin(); - if (!plugin.appendAnchor) { - return this; - } - if (this._physicsEngine) { - plugin.appendHook(this, otherImpostor, length, influence, noCollisionBetweenLinkedBodies); - } - return this; - } - /** - * Will keep this body still, in a sleep mode. - * @returns the physics imposter - */ - sleep() { - if (this._physicsEngine) { - this._physicsEngine.getPhysicsPlugin().sleepBody(this); - } - return this; - } - /** - * Wake the body up. - * @returns The physics imposter - */ - wakeUp() { - if (this._physicsEngine) { - this._physicsEngine.getPhysicsPlugin().wakeUpBody(this); - } - return this; - } - /** - * Clones the physics imposter - * @param newObject The physics imposter clones to this physics-enabled object - * @returns A nullable physics imposter - */ - clone(newObject) { - if (!newObject) { - return null; - } - return new physicsImpostor_PhysicsImpostor(newObject, this.type, this._options, this._scene); - } - /** - * Disposes the physics imposter - */ - dispose( /*disposeChildren: boolean = true*/) { - //no dispose if no physics engine is available. - if (!this._physicsEngine) { - return; - } - this._joints.forEach((j) => { - if (this._physicsEngine) { - this._physicsEngine.removeJoint(this, j.otherImpostor, j.joint); - } - }); - //dispose the physics body - this._physicsEngine.removeImpostor(this); - if (this.parent) { - this.parent.forceUpdate(); - } - else { - /*this._object.getChildMeshes().forEach(function(mesh) { - if (mesh.physicsImpostor) { - if (disposeChildren) { - mesh.physicsImpostor.dispose(); - mesh.physicsImpostor = null; - } - } - })*/ - } - this._isDisposed = true; - } - /** - * Sets the delta position - * @param position The delta position amount - */ - setDeltaPosition(position) { - this._deltaPosition.copyFrom(position); - } - /** - * Sets the delta rotation - * @param rotation The delta rotation amount - */ - setDeltaRotation(rotation) { - if (!this._deltaRotation) { - this._deltaRotation = new math_vector_Quaternion(); - } - this._deltaRotation.copyFrom(rotation); - this._deltaRotationConjugated = this._deltaRotation.conjugate(); - } - /** - * Gets the box size of the physics imposter and stores the result in the input parameter - * @param result Stores the box size - * @returns The physics imposter - */ - getBoxSizeToRef(result) { - if (this._physicsEngine) { - this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result); - } - return this; - } - /** - * Gets the radius of the physics imposter - * @returns Radius of the physics imposter - */ - getRadius() { - return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0; - } - /** - * Sync a bone with this impostor - * @param bone The bone to sync to the impostor. - * @param boneMesh The mesh that the bone is influencing. - * @param jointPivot The pivot of the joint / bone in local space. - * @param distToJoint Optional distance from the impostor to the joint. - * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. - */ - syncBoneWithImpostor(bone, boneMesh, jointPivot, distToJoint, adjustRotation) { - const tempVec = physicsImpostor_PhysicsImpostor._TmpVecs[0]; - const mesh = this.object; - if (mesh.rotationQuaternion) { - if (adjustRotation) { - const tempQuat = physicsImpostor_PhysicsImpostor._TmpQuat; - mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat); - bone.setRotationQuaternion(tempQuat, math_axis_Space.WORLD, boneMesh); - } - else { - bone.setRotationQuaternion(mesh.rotationQuaternion, math_axis_Space.WORLD, boneMesh); - } - } - tempVec.x = 0; - tempVec.y = 0; - tempVec.z = 0; - if (jointPivot) { - tempVec.x = jointPivot.x; - tempVec.y = jointPivot.y; - tempVec.z = jointPivot.z; - bone.getDirectionToRef(tempVec, boneMesh, tempVec); - if (distToJoint === undefined || distToJoint === null) { - distToJoint = jointPivot.length(); - } - tempVec.x *= distToJoint; - tempVec.y *= distToJoint; - tempVec.z *= distToJoint; - } - if (bone.getParent()) { - tempVec.addInPlace(mesh.getAbsolutePosition()); - bone.setAbsolutePosition(tempVec, boneMesh); - } - else { - boneMesh.setAbsolutePosition(mesh.getAbsolutePosition()); - boneMesh.position.x -= tempVec.x; - boneMesh.position.y -= tempVec.y; - boneMesh.position.z -= tempVec.z; - } - } - /** - * Sync impostor to a bone - * @param bone The bone that the impostor will be synced to. - * @param boneMesh The mesh that the bone is influencing. - * @param jointPivot The pivot of the joint / bone in local space. - * @param distToJoint Optional distance from the impostor to the joint. - * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. - * @param boneAxis Optional vector3 axis the bone is aligned with - */ - syncImpostorWithBone(bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) { - const mesh = this.object; - if (mesh.rotationQuaternion) { - if (adjustRotation) { - const tempQuat = physicsImpostor_PhysicsImpostor._TmpQuat; - bone.getRotationQuaternionToRef(math_axis_Space.WORLD, boneMesh, tempQuat); - tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion); - } - else { - bone.getRotationQuaternionToRef(math_axis_Space.WORLD, boneMesh, mesh.rotationQuaternion); - } - } - const pos = physicsImpostor_PhysicsImpostor._TmpVecs[0]; - const boneDir = physicsImpostor_PhysicsImpostor._TmpVecs[1]; - if (!boneAxis) { - boneAxis = physicsImpostor_PhysicsImpostor._TmpVecs[2]; - boneAxis.x = 0; - boneAxis.y = 1; - boneAxis.z = 0; - } - bone.getDirectionToRef(boneAxis, boneMesh, boneDir); - bone.getAbsolutePositionToRef(boneMesh, pos); - if ((distToJoint === undefined || distToJoint === null) && jointPivot) { - distToJoint = jointPivot.length(); - } - if (distToJoint !== undefined && distToJoint !== null) { - pos.x += boneDir.x * distToJoint; - pos.y += boneDir.y * distToJoint; - pos.z += boneDir.z * distToJoint; - } - mesh.setAbsolutePosition(pos); - } -} -/** - * The default object size of the imposter - */ -physicsImpostor_PhysicsImpostor.DEFAULT_OBJECT_SIZE = new math_vector_Vector3(1, 1, 1); -/** - * The identity quaternion of the imposter - */ -physicsImpostor_PhysicsImpostor.IDENTITY_QUATERNION = math_vector_Quaternion.Identity(); -physicsImpostor_PhysicsImpostor._TmpVecs = arrayTools_ArrayTools.BuildArray(3, math_vector_Vector3.Zero); -physicsImpostor_PhysicsImpostor._TmpQuat = math_vector_Quaternion.Identity(); -//Impostor types -/** - * No-Imposter type - */ -physicsImpostor_PhysicsImpostor.NoImpostor = 0; -/** - * Sphere-Imposter type - */ -physicsImpostor_PhysicsImpostor.SphereImpostor = 1; -/** - * Box-Imposter type - */ -physicsImpostor_PhysicsImpostor.BoxImpostor = 2; -/** - * Plane-Imposter type - */ -physicsImpostor_PhysicsImpostor.PlaneImpostor = 3; -/** - * Mesh-imposter type (Only available to objects with vertices data) - */ -physicsImpostor_PhysicsImpostor.MeshImpostor = 4; -/** - * Capsule-Impostor type (Ammo.js plugin only) - */ -physicsImpostor_PhysicsImpostor.CapsuleImpostor = 6; -/** - * Cylinder-Imposter type - */ -physicsImpostor_PhysicsImpostor.CylinderImpostor = 7; -/** - * Particle-Imposter type - */ -physicsImpostor_PhysicsImpostor.ParticleImpostor = 8; -/** - * Heightmap-Imposter type - */ -physicsImpostor_PhysicsImpostor.HeightmapImpostor = 9; -/** - * ConvexHull-Impostor type (Ammo.js plugin only) - */ -physicsImpostor_PhysicsImpostor.ConvexHullImpostor = 10; -/** - * Custom-Imposter type (Ammo.js plugin only) - */ -physicsImpostor_PhysicsImpostor.CustomImpostor = 100; -/** - * Rope-Imposter type - */ -physicsImpostor_PhysicsImpostor.RopeImpostor = 101; -/** - * Cloth-Imposter type - */ -physicsImpostor_PhysicsImpostor.ClothImpostor = 102; -/** - * Softbody-Imposter type - */ -physicsImpostor_PhysicsImpostor.SoftbodyImpostor = 103; -//# sourceMappingURL=physicsImpostor.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Loading/sceneLoader.js - - - - - - - - - - -/** - * Mode that determines how to handle old animation groups before loading new ones. - */ -var sceneLoader_SceneLoaderAnimationGroupLoadingMode; -(function (SceneLoaderAnimationGroupLoadingMode) { - /** - * Reset all old animations to initial state then dispose them. - */ - SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Clean"] = 0] = "Clean"; - /** - * Stop all old animations. - */ - SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Stop"] = 1] = "Stop"; - /** - * Restart old animations from first frame. - */ - SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Sync"] = 2] = "Sync"; - /** - * Old animations remains untouched. - */ - SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["NoSync"] = 3] = "NoSync"; -})(sceneLoader_SceneLoaderAnimationGroupLoadingMode || (sceneLoader_SceneLoaderAnimationGroupLoadingMode = {})); -/** - * Class used to load scene from various file formats using registered plugins - * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes - */ -class sceneLoader_SceneLoader { - /** - * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data - */ - static get ForceFullSceneLoadingForIncremental() { - return SceneLoaderFlags.ForceFullSceneLoadingForIncremental; - } - static set ForceFullSceneLoadingForIncremental(value) { - SceneLoaderFlags.ForceFullSceneLoadingForIncremental = value; - } - /** - * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene - */ - static get ShowLoadingScreen() { - return SceneLoaderFlags.ShowLoadingScreen; - } - static set ShowLoadingScreen(value) { - SceneLoaderFlags.ShowLoadingScreen = value; - } - /** - * Defines the current logging level (while loading the scene) - * @ignorenaming - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static get loggingLevel() { - return SceneLoaderFlags.loggingLevel; - } - // eslint-disable-next-line @typescript-eslint/naming-convention - static set loggingLevel(value) { - SceneLoaderFlags.loggingLevel = value; - } - /** - * Gets or set a boolean indicating if matrix weights must be cleaned upon loading - */ - static get CleanBoneMatrixWeights() { - return SceneLoaderFlags.CleanBoneMatrixWeights; - } - static set CleanBoneMatrixWeights(value) { - SceneLoaderFlags.CleanBoneMatrixWeights = value; - } - /** - * Gets the default plugin (used to load Babylon files) - * @returns the .babylon plugin - */ - static GetDefaultPlugin() { - return sceneLoader_SceneLoader._RegisteredPlugins[".babylon"]; - } - static _GetPluginForExtension(extension) { - const registeredPlugin = sceneLoader_SceneLoader._RegisteredPlugins[extension]; - if (registeredPlugin) { - return registeredPlugin; - } - logger_Logger.Warn("Unable to find a plugin to load " + - extension + - " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"); - return sceneLoader_SceneLoader.GetDefaultPlugin(); - } - static _GetPluginForDirectLoad(data) { - for (const extension in sceneLoader_SceneLoader._RegisteredPlugins) { - const plugin = sceneLoader_SceneLoader._RegisteredPlugins[extension].plugin; - if (plugin.canDirectLoad && plugin.canDirectLoad(data)) { - return sceneLoader_SceneLoader._RegisteredPlugins[extension]; - } - } - return sceneLoader_SceneLoader.GetDefaultPlugin(); - } - static _GetPluginForFilename(sceneFilename) { - const queryStringPosition = sceneFilename.indexOf("?"); - if (queryStringPosition !== -1) { - sceneFilename = sceneFilename.substring(0, queryStringPosition); - } - const dotPosition = sceneFilename.lastIndexOf("."); - const extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase(); - return sceneLoader_SceneLoader._GetPluginForExtension(extension); - } - static _GetDirectLoad(sceneFilename) { - if (sceneFilename.substr(0, 5) === "data:") { - return sceneFilename.substr(5); - } - return null; - } - static _FormatErrorMessage(fileInfo, message, exception) { - const fromLoad = fileInfo.rawData ? "binary data" : fileInfo.url; - let errorMessage = "Unable to load from " + fromLoad; - if (message) { - errorMessage += `: ${message}`; - } - else if (exception) { - errorMessage += `: ${exception}`; - } - return errorMessage; - } - static _LoadData(fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension, name) { - const directLoad = sceneLoader_SceneLoader._GetDirectLoad(fileInfo.url); - if (fileInfo.rawData && !pluginExtension) { - throw "When using ArrayBufferView to load data the file extension must be provided."; - } - const registeredPlugin = pluginExtension - ? sceneLoader_SceneLoader._GetPluginForExtension(pluginExtension) - : directLoad - ? sceneLoader_SceneLoader._GetPluginForDirectLoad(fileInfo.url) - : sceneLoader_SceneLoader._GetPluginForFilename(fileInfo.url); - if (fileInfo.rawData && !registeredPlugin.isBinary) { - throw "Loading from ArrayBufferView can not be used with plugins that don't support binary loading."; - } - let plugin; - if (registeredPlugin.plugin.createPlugin !== undefined) { - plugin = registeredPlugin.plugin.createPlugin(); - } - else { - plugin = registeredPlugin.plugin; - } - if (!plugin) { - 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."; - } - sceneLoader_SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin); - // Check if we have a direct load url. If the plugin is registered to handle - // it or it's not a base64 data url, then pass it through the direct load path. - if (directLoad && ((plugin.canDirectLoad && plugin.canDirectLoad(fileInfo.url)) || !IsBase64DataUrl(fileInfo.url))) { - if (plugin.directLoad) { - const result = plugin.directLoad(scene, directLoad); - if (result.then) { - result - .then((data) => { - onSuccess(plugin, data); - }) - .catch((error) => { - onError("Error in directLoad of _loadData: " + error, error); - }); - } - else { - onSuccess(plugin, result); - } - } - else { - onSuccess(plugin, directLoad); - } - return plugin; - } - const useArrayBuffer = registeredPlugin.isBinary; - const dataCallback = (data, responseURL) => { - if (scene.isDisposed) { - onError("Scene has been disposed"); - return; - } - onSuccess(plugin, data, responseURL); - }; - let request = null; - let pluginDisposed = false; - const onDisposeObservable = plugin.onDisposeObservable; - if (onDisposeObservable) { - onDisposeObservable.add(() => { - pluginDisposed = true; - if (request) { - request.abort(); - request = null; - } - onDispose(); - }); - } - const manifestChecked = () => { - if (pluginDisposed) { - return; - } - const errorCallback = (request, exception) => { - onError(request === null || request === void 0 ? void 0 : request.statusText, exception); - }; - if (!plugin.loadFile && fileInfo.rawData) { - throw "Plugin does not support loading ArrayBufferView."; - } - request = plugin.loadFile - ? plugin.loadFile(scene, fileInfo.rawData || fileInfo.file || fileInfo.url, fileInfo.rootUrl, dataCallback, onProgress, useArrayBuffer, errorCallback, name) - : scene._loadFile(fileInfo.file || fileInfo.url, dataCallback, onProgress, true, useArrayBuffer, errorCallback); - }; - const engine = scene.getEngine(); - let canUseOfflineSupport = engine.enableOfflineSupport; - if (canUseOfflineSupport) { - // Also check for exceptions - let exceptionFound = false; - for (const regex of scene.disableOfflineSupportExceptionRules) { - if (regex.test(fileInfo.url)) { - exceptionFound = true; - break; - } - } - canUseOfflineSupport = !exceptionFound; - } - if (canUseOfflineSupport && engine_Engine.OfflineProviderFactory) { - // Checking if a manifest file has been set for this scene and if offline mode has been requested - scene.offlineProvider = engine_Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck); - } - else { - manifestChecked(); - } - return plugin; - } - static _GetFileInfo(rootUrl, sceneFilename) { - let url; - let name; - let file = null; - let rawData = null; - if (!sceneFilename) { - url = rootUrl; - name = tools_Tools.GetFilename(rootUrl); - rootUrl = tools_Tools.GetFolderPath(rootUrl); - } - else if (sceneFilename.name) { - const sceneFile = sceneFilename; - url = `file:${sceneFile.name}`; - name = sceneFile.name; - file = sceneFile; - } - else if (ArrayBuffer.isView(sceneFilename)) { - url = ""; - name = "arrayBuffer"; - rawData = sceneFilename; - } - else if (typeof sceneFilename === "string" && sceneFilename.startsWith("data:")) { - url = sceneFilename; - name = ""; - } - else { - const filename = sceneFilename; - if (filename.substr(0, 1) === "/") { - tools_Tools.Error("Wrong sceneFilename parameter"); - return null; - } - url = rootUrl + filename; - name = filename; - } - return { - url: url, - rootUrl: rootUrl, - name: name, - file: file, - rawData, - }; - } - // Public functions - /** - * Gets a plugin that can load the given extension - * @param extension defines the extension to load - * @returns a plugin or null if none works - */ - static GetPluginForExtension(extension) { - return sceneLoader_SceneLoader._GetPluginForExtension(extension).plugin; - } - /** - * Gets a boolean indicating that the given extension can be loaded - * @param extension defines the extension to load - * @returns true if the extension is supported - */ - static IsPluginForExtensionAvailable(extension) { - return !!sceneLoader_SceneLoader._RegisteredPlugins[extension]; - } - /** - * Adds a new plugin to the list of registered plugins - * @param plugin defines the plugin to add - */ - static RegisterPlugin(plugin) { - if (typeof plugin.extensions === "string") { - const extension = plugin.extensions; - sceneLoader_SceneLoader._RegisteredPlugins[extension.toLowerCase()] = { - plugin: plugin, - isBinary: false, - }; - } - else { - const extensions = plugin.extensions; - Object.keys(extensions).forEach((extension) => { - sceneLoader_SceneLoader._RegisteredPlugins[extension.toLowerCase()] = { - plugin: plugin, - isBinary: extensions[extension].isBinary, - }; - }); - } - } - /** - * Import meshes into a scene - * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported - * @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) - * @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) - * @param scene the instance of BABYLON.Scene to append to - * @param onSuccess a callback with a list of imported meshes, particleSystems, skeletons, and animationGroups when import succeeds - * @param onProgress a callback with a progress event for each file being loaded - * @param onError a callback with the scene, a message, and possibly an exception when import fails - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded plugin - */ - static ImportMesh(meshNames, rootUrl, sceneFilename = "", scene = engineStore_EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "") { - if (!scene) { - logger_Logger.Error("No scene available to import mesh to"); - return null; - } - const fileInfo = sceneLoader_SceneLoader._GetFileInfo(rootUrl, sceneFilename); - if (!fileInfo) { - return null; - } - const loadingToken = {}; - scene.addPendingData(loadingToken); - const disposeHandler = () => { - scene.removePendingData(loadingToken); - }; - const errorHandler = (message, exception) => { - const errorMessage = sceneLoader_SceneLoader._FormatErrorMessage(fileInfo, message, exception); - if (onError) { - onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception)); - } - else { - logger_Logger.Error(errorMessage); - // should the exception be thrown? - } - disposeHandler(); - }; - const progressHandler = onProgress - ? (event) => { - try { - onProgress(event); - } - catch (e) { - errorHandler("Error in onProgress callback: " + e, e); - } - } - : undefined; - const successHandler = (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights) => { - scene.importedMeshesFiles.push(fileInfo.url); - if (onSuccess) { - try { - onSuccess(meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights); - } - catch (e) { - errorHandler("Error in onSuccess callback: " + e, e); - } - } - scene.removePendingData(loadingToken); - }; - return sceneLoader_SceneLoader._LoadData(fileInfo, scene, (plugin, data, responseURL) => { - if (plugin.rewriteRootURL) { - fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL); - } - if (plugin.importMesh) { - const syncedPlugin = plugin; - const meshes = new Array(); - const particleSystems = new Array(); - const skeletons = new Array(); - if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) { - return; - } - scene.loadingPluginName = plugin.name; - successHandler(meshes, particleSystems, skeletons, [], [], [], []); - } - else { - const asyncedPlugin = plugin; - asyncedPlugin - .importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name) - .then((result) => { - scene.loadingPluginName = plugin.name; - successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups, result.transformNodes, result.geometries, result.lights); - }) - .catch((error) => { - errorHandler(error.message, error); - }); - } - }, progressHandler, errorHandler, disposeHandler, pluginExtension, name); - } - /** - * Import meshes into a scene - * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported - * @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) - * @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) - * @param scene the instance of BABYLON.Scene to append to - * @param onProgress a callback with a progress event for each file being loaded - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups - */ - static ImportMeshAsync(meshNames, rootUrl, sceneFilename = "", scene = engineStore_EngineStore.LastCreatedScene, onProgress = null, pluginExtension = null, name = "") { - return new Promise((resolve, reject) => { - sceneLoader_SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights) => { - resolve({ - meshes: meshes, - particleSystems: particleSystems, - skeletons: skeletons, - animationGroups: animationGroups, - transformNodes: transformNodes, - geometries: geometries, - lights: lights, - }); - }, onProgress, (scene, message, exception) => { - reject(exception || new Error(message)); - }, pluginExtension, name); - }); - } - /** - * Load a scene - * @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) - * @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) - * @param engine is the instance of BABYLON.Engine to use to create the scene - * @param onSuccess a callback with the scene when import succeeds - * @param onProgress a callback with a progress event for each file being loaded - * @param onError a callback with the scene, a message, and possibly an exception when import fails - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded plugin - */ - static Load(rootUrl, sceneFilename = "", engine = engineStore_EngineStore.LastCreatedEngine, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "") { - if (!engine) { - tools_Tools.Error("No engine available"); - return null; - } - return sceneLoader_SceneLoader.Append(rootUrl, sceneFilename, new scene_Scene(engine), onSuccess, onProgress, onError, pluginExtension, name); - } - /** - * Load a scene - * @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) - * @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) - * @param engine is the instance of BABYLON.Engine to use to create the scene - * @param onProgress a callback with a progress event for each file being loaded - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded scene - */ - static LoadAsync(rootUrl, sceneFilename = "", engine = engineStore_EngineStore.LastCreatedEngine, onProgress = null, pluginExtension = null, name = "") { - return new Promise((resolve, reject) => { - sceneLoader_SceneLoader.Load(rootUrl, sceneFilename, engine, (scene) => { - resolve(scene); - }, onProgress, (scene, message, exception) => { - reject(exception || new Error(message)); - }, pluginExtension, name); - }); - } - /** - * Append a scene - * @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) - * @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) - * @param scene is the instance of BABYLON.Scene to append to - * @param onSuccess a callback with the scene when import succeeds - * @param onProgress a callback with a progress event for each file being loaded - * @param onError a callback with the scene, a message, and possibly an exception when import fails - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded plugin - */ - static Append(rootUrl, sceneFilename = "", scene = engineStore_EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "") { - if (!scene) { - logger_Logger.Error("No scene available to append to"); - return null; - } - const fileInfo = sceneLoader_SceneLoader._GetFileInfo(rootUrl, sceneFilename); - if (!fileInfo) { - return null; - } - const loadingToken = {}; - scene.addPendingData(loadingToken); - const disposeHandler = () => { - scene.removePendingData(loadingToken); - }; - if (sceneLoader_SceneLoader.ShowLoadingScreen && !this._ShowingLoadingScreen) { - this._ShowingLoadingScreen = true; - scene.getEngine().displayLoadingUI(); - scene.executeWhenReady(() => { - scene.getEngine().hideLoadingUI(); - this._ShowingLoadingScreen = false; - }); - } - const errorHandler = (message, exception) => { - const errorMessage = sceneLoader_SceneLoader._FormatErrorMessage(fileInfo, message, exception); - if (onError) { - onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception)); - } - else { - logger_Logger.Error(errorMessage); - // should the exception be thrown? - } - disposeHandler(); - }; - const progressHandler = onProgress - ? (event) => { - try { - onProgress(event); - } - catch (e) { - errorHandler("Error in onProgress callback", e); - } - } - : undefined; - const successHandler = () => { - if (onSuccess) { - try { - onSuccess(scene); - } - catch (e) { - errorHandler("Error in onSuccess callback", e); - } - } - scene.removePendingData(loadingToken); - }; - return sceneLoader_SceneLoader._LoadData(fileInfo, scene, (plugin, data) => { - if (plugin.load) { - const syncedPlugin = plugin; - if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) { - return; - } - scene.loadingPluginName = plugin.name; - successHandler(); - } - else { - const asyncedPlugin = plugin; - asyncedPlugin - .loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name) - .then(() => { - scene.loadingPluginName = plugin.name; - successHandler(); - }) - .catch((error) => { - errorHandler(error.message, error); - }); - } - }, progressHandler, errorHandler, disposeHandler, pluginExtension, name); - } - /** - * Append a scene - * @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) - * @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) - * @param scene is the instance of BABYLON.Scene to append to - * @param onProgress a callback with a progress event for each file being loaded - * @param pluginExtension the extension used to determine the plugin - * @returns The given scene - */ - static AppendAsync(rootUrl, sceneFilename = "", scene = engineStore_EngineStore.LastCreatedScene, onProgress = null, pluginExtension = null, name = "") { - return new Promise((resolve, reject) => { - sceneLoader_SceneLoader.Append(rootUrl, sceneFilename, scene, (scene) => { - resolve(scene); - }, onProgress, (scene, message, exception) => { - reject(exception || new Error(message)); - }, pluginExtension, name); - }); - } - /** - * Load a scene into an asset container - * @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) - * @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) - * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) - * @param onSuccess a callback with the scene when import succeeds - * @param onProgress a callback with a progress event for each file being loaded - * @param onError a callback with the scene, a message, and possibly an exception when import fails - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded plugin - */ - static LoadAssetContainer(rootUrl, sceneFilename = "", scene = engineStore_EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = "") { - if (!scene) { - logger_Logger.Error("No scene available to load asset container to"); - return null; - } - const fileInfo = sceneLoader_SceneLoader._GetFileInfo(rootUrl, sceneFilename); - if (!fileInfo) { - return null; - } - const loadingToken = {}; - scene.addPendingData(loadingToken); - const disposeHandler = () => { - scene.removePendingData(loadingToken); - }; - const errorHandler = (message, exception) => { - const errorMessage = sceneLoader_SceneLoader._FormatErrorMessage(fileInfo, message, exception); - if (onError) { - onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception)); - } - else { - logger_Logger.Error(errorMessage); - // should the exception be thrown? - } - disposeHandler(); - }; - const progressHandler = onProgress - ? (event) => { - try { - onProgress(event); - } - catch (e) { - errorHandler("Error in onProgress callback", e); - } - } - : undefined; - const successHandler = (assets) => { - if (onSuccess) { - try { - onSuccess(assets); - } - catch (e) { - errorHandler("Error in onSuccess callback", e); - } - } - scene.removePendingData(loadingToken); - }; - return sceneLoader_SceneLoader._LoadData(fileInfo, scene, (plugin, data) => { - if (plugin.loadAssetContainer) { - const syncedPlugin = plugin; - const assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler); - if (!assetContainer) { - return; - } - assetContainer.populateRootNodes(); - scene.loadingPluginName = plugin.name; - successHandler(assetContainer); - } - else if (plugin.loadAssetContainerAsync) { - const asyncedPlugin = plugin; - asyncedPlugin - .loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name) - .then((assetContainer) => { - assetContainer.populateRootNodes(); - scene.loadingPluginName = plugin.name; - successHandler(assetContainer); - }) - .catch((error) => { - errorHandler(error.message, error); - }); - } - else { - errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method."); - } - }, progressHandler, errorHandler, disposeHandler, pluginExtension, name); - } - /** - * Load a scene into an asset container - * @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) - * @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) - * @param scene is the instance of Scene to append to - * @param onProgress a callback with a progress event for each file being loaded - * @param pluginExtension the extension used to determine the plugin - * @returns The loaded asset container - */ - static LoadAssetContainerAsync(rootUrl, sceneFilename = "", scene = engineStore_EngineStore.LastCreatedScene, onProgress = null, pluginExtension = null) { - return new Promise((resolve, reject) => { - sceneLoader_SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, (assetContainer) => { - resolve(assetContainer); - }, onProgress, (scene, message, exception) => { - reject(exception || new Error(message)); - }, pluginExtension); - }); - } - /** - * Import animations from a file into a scene - * @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) - * @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) - * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) - * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise - * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones - * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name) - * @param onSuccess a callback with the scene when import succeeds - * @param onProgress a callback with a progress event for each file being loaded - * @param onError a callback with the scene, a message, and possibly an exception when import fails - * @param pluginExtension the extension used to determine the plugin - */ - static ImportAnimations(rootUrl, sceneFilename = "", scene = engineStore_EngineStore.LastCreatedScene, overwriteAnimations = true, animationGroupLoadingMode = sceneLoader_SceneLoaderAnimationGroupLoadingMode.Clean, targetConverter = null, onSuccess = null, onProgress = null, onError = null, pluginExtension = null) { - if (!scene) { - logger_Logger.Error("No scene available to load animations to"); - return; - } - if (overwriteAnimations) { - // Reset, stop and dispose all animations before loading new ones - for (const animatable of scene.animatables) { - animatable.reset(); - } - scene.stopAllAnimations(); - scene.animationGroups.slice().forEach((animationGroup) => { - animationGroup.dispose(); - }); - const nodes = scene.getNodes(); - nodes.forEach((node) => { - if (node.animations) { - node.animations = []; - } - }); - } - else { - switch (animationGroupLoadingMode) { - case sceneLoader_SceneLoaderAnimationGroupLoadingMode.Clean: - scene.animationGroups.slice().forEach((animationGroup) => { - animationGroup.dispose(); - }); - break; - case sceneLoader_SceneLoaderAnimationGroupLoadingMode.Stop: - scene.animationGroups.forEach((animationGroup) => { - animationGroup.stop(); - }); - break; - case sceneLoader_SceneLoaderAnimationGroupLoadingMode.Sync: - scene.animationGroups.forEach((animationGroup) => { - animationGroup.reset(); - animationGroup.restart(); - }); - break; - case sceneLoader_SceneLoaderAnimationGroupLoadingMode.NoSync: - // nothing to do - break; - default: - logger_Logger.Error("Unknown animation group loading mode value '" + animationGroupLoadingMode + "'"); - return; - } - } - const startingIndexForNewAnimatables = scene.animatables.length; - const onAssetContainerLoaded = (container) => { - container.mergeAnimationsTo(scene, scene.animatables.slice(startingIndexForNewAnimatables), targetConverter); - container.dispose(); - scene.onAnimationFileImportedObservable.notifyObservers(scene); - if (onSuccess) { - onSuccess(scene); - } - }; - this.LoadAssetContainer(rootUrl, sceneFilename, scene, onAssetContainerLoaded, onProgress, onError, pluginExtension); - } - /** - * Import animations from a file into a scene - * @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) - * @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) - * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) - * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise - * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones - * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name) - * @param onSuccess a callback with the scene when import succeeds - * @param onProgress a callback with a progress event for each file being loaded - * @param onError a callback with the scene, a message, and possibly an exception when import fails - * @param pluginExtension the extension used to determine the plugin - * @returns the updated scene with imported animations - */ - static ImportAnimationsAsync(rootUrl, sceneFilename = "", scene = engineStore_EngineStore.LastCreatedScene, overwriteAnimations = true, animationGroupLoadingMode = sceneLoader_SceneLoaderAnimationGroupLoadingMode.Clean, targetConverter = null, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onSuccess = null, onProgress = null, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onError = null, pluginExtension = null) { - return new Promise((resolve, reject) => { - sceneLoader_SceneLoader.ImportAnimations(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, (_scene) => { - resolve(_scene); - }, onProgress, (_scene, message, exception) => { - reject(exception || new Error(message)); - }, pluginExtension); - }); - } -} -/** - * No logging while loading - */ -sceneLoader_SceneLoader.NO_LOGGING = 0; -/** - * Minimal logging while loading - */ -sceneLoader_SceneLoader.MINIMAL_LOGGING = 1; -/** - * Summary logging while loading - */ -sceneLoader_SceneLoader.SUMMARY_LOGGING = 2; -/** - * Detailed logging while loading - */ -sceneLoader_SceneLoader.DETAILED_LOGGING = 3; -// Members -/** - * Event raised when a plugin is used to load a scene - */ -sceneLoader_SceneLoader.OnPluginActivatedObservable = new observable_Observable(); -sceneLoader_SceneLoader._RegisteredPlugins = {}; -sceneLoader_SceneLoader._ShowingLoadingScreen = false; -//# sourceMappingURL=sceneLoader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/pushMaterial.js - - -/** - * Base class of materials working in push mode in babylon JS - * @internal - */ -class PushMaterial extends material_Material { - constructor(name, scene, storeEffectOnSubMeshes = true) { - super(name, scene); - this._normalMatrix = new math_vector_Matrix(); - this._storeEffectOnSubMeshes = storeEffectOnSubMeshes; - } - getEffect() { - return this._storeEffectOnSubMeshes ? this._activeEffect : super.getEffect(); - } - isReady(mesh, useInstances) { - if (!mesh) { - return false; - } - if (!this._storeEffectOnSubMeshes) { - return true; - } - if (!mesh.subMeshes || mesh.subMeshes.length === 0) { - return true; - } - return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances); - } - _isReadyForSubMesh(subMesh) { - const defines = subMesh.materialDefines; - if (!this.checkReadyOnEveryCall && subMesh.effect && defines) { - if (defines._renderId === this.getScene().getRenderId()) { - return true; - } - } - return false; - } - /** - * Binds the given world matrix to the active effect - * - * @param world the matrix to bind - */ - bindOnlyWorldMatrix(world) { - this._activeEffect.setMatrix("world", world); - } - /** - * Binds the given normal matrix to the active effect - * - * @param normalMatrix the matrix to bind - */ - bindOnlyNormalMatrix(normalMatrix) { - this._activeEffect.setMatrix("normalMatrix", normalMatrix); - } - bind(world, mesh) { - if (!mesh) { - return; - } - this.bindForSubMesh(world, mesh, mesh.subMeshes[0]); - } - _afterBind(mesh, effect = null) { - super._afterBind(mesh, effect); - this.getScene()._cachedEffect = effect; - if (effect) { - effect._forceRebindOnNextCall = false; - } - } - _mustRebind(scene, effect, visibility = 1) { - return scene.isCachedMaterialInvalid(this, effect, visibility); - } - dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { - this._activeEffect = undefined; - super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh); - } -} -//# sourceMappingURL=pushMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.js -/** - * Defines the kind of connection point for node based material - */ -var NodeMaterialBlockConnectionPointTypes; -(function (NodeMaterialBlockConnectionPointTypes) { - /** Float */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Float"] = 1] = "Float"; - /** Int */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Int"] = 2] = "Int"; - /** Vector2 */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector2"] = 4] = "Vector2"; - /** Vector3 */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector3"] = 8] = "Vector3"; - /** Vector4 */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector4"] = 16] = "Vector4"; - /** Color3 */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Color3"] = 32] = "Color3"; - /** Color4 */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Color4"] = 64] = "Color4"; - /** Matrix */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Matrix"] = 128] = "Matrix"; - /** Custom object */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Object"] = 256] = "Object"; - /** Detect type based on connection */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["AutoDetect"] = 1024] = "AutoDetect"; - /** Output type that will be defined by input type */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["BasedOnInput"] = 2048] = "BasedOnInput"; - /** Bitmask of all types */ - NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["All"] = 4095] = "All"; -})(NodeMaterialBlockConnectionPointTypes || (NodeMaterialBlockConnectionPointTypes = {})); -//# sourceMappingURL=nodeMaterialBlockConnectionPointTypes.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockTargets.js -/** - * Enum used to define the target of a block - */ -var NodeMaterialBlockTargets; -(function (NodeMaterialBlockTargets) { - /** Vertex shader */ - NodeMaterialBlockTargets[NodeMaterialBlockTargets["Vertex"] = 1] = "Vertex"; - /** Fragment shader */ - NodeMaterialBlockTargets[NodeMaterialBlockTargets["Fragment"] = 2] = "Fragment"; - /** Neutral */ - NodeMaterialBlockTargets[NodeMaterialBlockTargets["Neutral"] = 4] = "Neutral"; - /** Vertex and Fragment */ - NodeMaterialBlockTargets[NodeMaterialBlockTargets["VertexAndFragment"] = 3] = "VertexAndFragment"; -})(NodeMaterialBlockTargets || (NodeMaterialBlockTargets = {})); -//# sourceMappingURL=nodeMaterialBlockTargets.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBuildState.js - - - -/** - * Class used to store node based material build state - */ -class NodeMaterialBuildState { - constructor() { - /** Gets or sets a boolean indicating if the current state can emit uniform buffers */ - this.supportUniformBuffers = false; - /** - * Gets the list of emitted attributes - */ - this.attributes = new Array(); - /** - * Gets the list of emitted uniforms - */ - this.uniforms = new Array(); - /** - * Gets the list of emitted constants - */ - this.constants = new Array(); - /** - * Gets the list of emitted samplers - */ - this.samplers = new Array(); - /** - * Gets the list of emitted functions - */ - this.functions = {}; - /** - * Gets the list of emitted extensions - */ - this.extensions = {}; - /** - * Gets the list of emitted counters - */ - this.counters = {}; - /** @internal */ - this._attributeDeclaration = ""; - /** @internal */ - this._uniformDeclaration = ""; - /** @internal */ - this._constantDeclaration = ""; - /** @internal */ - this._samplerDeclaration = ""; - /** @internal */ - this._varyingTransfer = ""; - /** @internal */ - this._injectAtEnd = ""; - this._repeatableContentAnchorIndex = 0; - /** @internal */ - this._builtCompilationString = ""; - /** - * Gets the emitted compilation strings - */ - this.compilationString = ""; - } - /** - * Finalize the compilation strings - * @param state defines the current compilation state - */ - finalize(state) { - const emitComments = state.sharedData.emitComments; - const isFragmentMode = this.target === NodeMaterialBlockTargets.Fragment; - this.compilationString = `\n${emitComments ? "//Entry point\n" : ""}void main(void) {\n${this.compilationString}`; - if (this._constantDeclaration) { - this.compilationString = `\n${emitComments ? "//Constants\n" : ""}${this._constantDeclaration}\n${this.compilationString}`; - } - let functionCode = ""; - for (const functionName in this.functions) { - functionCode += this.functions[functionName] + `\n`; - } - this.compilationString = `\n${functionCode}\n${this.compilationString}`; - if (!isFragmentMode && this._varyingTransfer) { - this.compilationString = `${this.compilationString}\n${this._varyingTransfer}`; - } - if (this._injectAtEnd) { - this.compilationString = `${this.compilationString}\n${this._injectAtEnd}`; - } - this.compilationString = `${this.compilationString}\n}`; - if (this.sharedData.varyingDeclaration) { - this.compilationString = `\n${emitComments ? "//Varyings\n" : ""}${this.sharedData.varyingDeclaration}\n${this.compilationString}`; - } - if (this._samplerDeclaration) { - this.compilationString = `\n${emitComments ? "//Samplers\n" : ""}${this._samplerDeclaration}\n${this.compilationString}`; - } - if (this._uniformDeclaration) { - this.compilationString = `\n${emitComments ? "//Uniforms\n" : ""}${this._uniformDeclaration}\n${this.compilationString}`; - } - if (this._attributeDeclaration && !isFragmentMode) { - this.compilationString = `\n${emitComments ? "//Attributes\n" : ""}${this._attributeDeclaration}\n${this.compilationString}`; - } - this.compilationString = "precision highp float;\n" + this.compilationString; - this.compilationString = "#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n" + this.compilationString; - for (const extensionName in this.extensions) { - const extension = this.extensions[extensionName]; - this.compilationString = `\n${extension}\n${this.compilationString}`; - } - this._builtCompilationString = this.compilationString; - } - /** @internal */ - get _repeatableContentAnchor() { - return `###___ANCHOR${this._repeatableContentAnchorIndex++}___###`; - } - /** - * @internal - */ - _getFreeVariableName(prefix) { - prefix = prefix.replace(/[^a-zA-Z_]+/g, ""); - if (this.sharedData.variableNames[prefix] === undefined) { - this.sharedData.variableNames[prefix] = 0; - // Check reserved words - if (prefix === "output" || prefix === "texture") { - return prefix + this.sharedData.variableNames[prefix]; - } - return prefix; - } - else { - this.sharedData.variableNames[prefix]++; - } - return prefix + this.sharedData.variableNames[prefix]; - } - /** - * @internal - */ - _getFreeDefineName(prefix) { - if (this.sharedData.defineNames[prefix] === undefined) { - this.sharedData.defineNames[prefix] = 0; - } - else { - this.sharedData.defineNames[prefix]++; - } - return prefix + this.sharedData.defineNames[prefix]; - } - /** - * @internal - */ - _excludeVariableName(name) { - this.sharedData.variableNames[name] = 0; - } - /** - * @internal - */ - _emit2DSampler(name) { - if (this.samplers.indexOf(name) < 0) { - this._samplerDeclaration += `uniform sampler2D ${name};\n`; - this.samplers.push(name); - } - } - /** - * @internal - */ - _emit2DArraySampler(name) { - if (this.samplers.indexOf(name) < 0) { - this._samplerDeclaration += `uniform sampler2DArray ${name};\n`; - this.samplers.push(name); - } - } - /** - * @internal - */ - _getGLType(type) { - switch (type) { - case NodeMaterialBlockConnectionPointTypes.Float: - return "float"; - case NodeMaterialBlockConnectionPointTypes.Int: - return "int"; - case NodeMaterialBlockConnectionPointTypes.Vector2: - return "vec2"; - case NodeMaterialBlockConnectionPointTypes.Color3: - case NodeMaterialBlockConnectionPointTypes.Vector3: - return "vec3"; - case NodeMaterialBlockConnectionPointTypes.Color4: - case NodeMaterialBlockConnectionPointTypes.Vector4: - return "vec4"; - case NodeMaterialBlockConnectionPointTypes.Matrix: - return "mat4"; - } - return ""; - } - /** - * @internal - */ - _emitExtension(name, extension, define = "") { - if (this.extensions[name]) { - return; - } - if (define) { - extension = `#if ${define}\n${extension}\n#endif`; - } - this.extensions[name] = extension; - } - /** - * @internal - */ - _emitFunction(name, code, comments) { - if (this.functions[name]) { - return; - } - if (this.sharedData.emitComments) { - code = comments + `\n` + code; - } - this.functions[name] = code; - } - /** - * @internal - */ - _emitCodeFromInclude(includeName, comments, options) { - if (options && options.repeatKey) { - return `#include<${includeName}>${options.substitutionVars ? "(" + options.substitutionVars + ")" : ""}[0..${options.repeatKey}]\n`; - } - let code = effect_Effect.IncludesShadersStore[includeName] + "\n"; - if (this.sharedData.emitComments) { - code = comments + `\n` + code; - } - if (!options) { - return code; - } - if (options.replaceStrings) { - for (let index = 0; index < options.replaceStrings.length; index++) { - const replaceString = options.replaceStrings[index]; - code = code.replace(replaceString.search, replaceString.replace); - } - } - return code; - } - /** - * @internal - */ - _emitFunctionFromInclude(includeName, comments, options, storeKey = "") { - const key = includeName + storeKey; - if (this.functions[key]) { - return; - } - if (!options || (!options.removeAttributes && !options.removeUniforms && !options.removeVaryings && !options.removeIfDef && !options.replaceStrings)) { - if (options && options.repeatKey) { - this.functions[key] = `#include<${includeName}>${options.substitutionVars ? "(" + options.substitutionVars + ")" : ""}[0..${options.repeatKey}]\n`; - } - else { - this.functions[key] = `#include<${includeName}>${(options === null || options === void 0 ? void 0 : options.substitutionVars) ? "(" + (options === null || options === void 0 ? void 0 : options.substitutionVars) + ")" : ""}\n`; - } - if (this.sharedData.emitComments) { - this.functions[key] = comments + `\n` + this.functions[key]; - } - return; - } - this.functions[key] = effect_Effect.IncludesShadersStore[includeName]; - if (this.sharedData.emitComments) { - this.functions[key] = comments + `\n` + this.functions[key]; - } - if (options.removeIfDef) { - this.functions[key] = this.functions[key].replace(/^\s*?#ifdef.+$/gm, ""); - this.functions[key] = this.functions[key].replace(/^\s*?#endif.*$/gm, ""); - this.functions[key] = this.functions[key].replace(/^\s*?#else.*$/gm, ""); - this.functions[key] = this.functions[key].replace(/^\s*?#elif.*$/gm, ""); - } - if (options.removeAttributes) { - this.functions[key] = this.functions[key].replace(/\s*?attribute .+?;/g, "\n"); - } - if (options.removeUniforms) { - this.functions[key] = this.functions[key].replace(/\s*?uniform .*?;/g, "\n"); - } - if (options.removeVaryings) { - this.functions[key] = this.functions[key].replace(/\s*?(varying|in) .+?;/g, "\n"); - } - if (options.replaceStrings) { - for (let index = 0; index < options.replaceStrings.length; index++) { - const replaceString = options.replaceStrings[index]; - this.functions[key] = this.functions[key].replace(replaceString.search, replaceString.replace); - } - } - } - /** - * @internal - */ - _registerTempVariable(name) { - if (this.sharedData.temps.indexOf(name) !== -1) { - return false; - } - this.sharedData.temps.push(name); - return true; - } - /** - * @internal - */ - _emitVaryingFromString(name, type, define = "", notDefine = false) { - if (this.sharedData.varyings.indexOf(name) !== -1) { - return false; - } - this.sharedData.varyings.push(name); - if (define) { - if (define.startsWith("defined(")) { - this.sharedData.varyingDeclaration += `#if ${define}\n`; - } - else { - this.sharedData.varyingDeclaration += `${notDefine ? "#ifndef" : "#ifdef"} ${define}\n`; - } - } - this.sharedData.varyingDeclaration += `varying ${type} ${name};\n`; - if (define) { - this.sharedData.varyingDeclaration += `#endif\n`; - } - return true; - } - /** - * @internal - */ - _emitUniformFromString(name, type, define = "", notDefine = false) { - if (this.uniforms.indexOf(name) !== -1) { - return; - } - this.uniforms.push(name); - if (define) { - if (define.startsWith("defined(")) { - this._uniformDeclaration += `#if ${define}\n`; - } - else { - this._uniformDeclaration += `${notDefine ? "#ifndef" : "#ifdef"} ${define}\n`; - } - } - this._uniformDeclaration += `uniform ${type} ${name};\n`; - if (define) { - this._uniformDeclaration += `#endif\n`; - } - } - /** - * @internal - */ - _emitFloat(value) { - if (value.toString() === value.toFixed(0)) { - return `${value}.0`; - } - return value.toString(); - } -} -//# sourceMappingURL=nodeMaterialBuildState.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBuildStateSharedData.js -/** - * Class used to store shared data between 2 NodeMaterialBuildState - */ -class NodeMaterialBuildStateSharedData { - /** Creates a new shared data */ - constructor() { - /** - * Gets the list of emitted varyings - */ - this.temps = new Array(); - /** - * Gets the list of emitted varyings - */ - this.varyings = new Array(); - /** - * Gets the varying declaration string - */ - this.varyingDeclaration = ""; - /** - * Input blocks - */ - this.inputBlocks = new Array(); - /** - * Input blocks - */ - this.textureBlocks = new Array(); - /** - * Bindable blocks (Blocks that need to set data to the effect) - */ - this.bindableBlocks = new Array(); - /** - * 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 - */ - this.forcedBindableBlocks = new Array(); - /** - * List of blocks that can provide a compilation fallback - */ - this.blocksWithFallbacks = new Array(); - /** - * List of blocks that can provide a define update - */ - this.blocksWithDefines = new Array(); - /** - * List of blocks that can provide a repeatable content - */ - this.repeatableContentBlocks = new Array(); - /** - * List of blocks that can provide a dynamic list of uniforms - */ - this.dynamicUniformBlocks = new Array(); - /** - * List of blocks that can block the isReady function for the material - */ - this.blockingBlocks = new Array(); - /** - * Gets the list of animated inputs - */ - this.animatedInputs = new Array(); - /** List of emitted variables */ - this.variableNames = {}; - /** List of emitted defines */ - this.defineNames = {}; - /** - * Gets the compilation hints emitted at compilation time - */ - this.hints = { - needWorldViewMatrix: false, - needWorldViewProjectionMatrix: false, - needAlphaBlending: false, - needAlphaTesting: false, - }; - /** - * List of compilation checks - */ - this.checks = { - emitVertex: false, - emitFragment: false, - notConnectedNonOptionalInputs: new Array(), - }; - /** - * Is vertex program allowed to be empty? - */ - this.allowEmptyVertexProgram = false; - // Exclude usual attributes from free variable names - this.variableNames["position"] = 0; - this.variableNames["normal"] = 0; - this.variableNames["tangent"] = 0; - this.variableNames["uv"] = 0; - this.variableNames["uv2"] = 0; - this.variableNames["uv3"] = 0; - this.variableNames["uv4"] = 0; - this.variableNames["uv5"] = 0; - this.variableNames["uv6"] = 0; - this.variableNames["color"] = 0; - this.variableNames["matricesIndices"] = 0; - this.variableNames["matricesWeights"] = 0; - this.variableNames["matricesIndicesExtra"] = 0; - this.variableNames["matricesWeightsExtra"] = 0; - this.variableNames["diffuseBase"] = 0; - this.variableNames["specularBase"] = 0; - this.variableNames["worldPos"] = 0; - this.variableNames["shadow"] = 0; - this.variableNames["view"] = 0; - // Exclude known varyings - this.variableNames["vTBN"] = 0; - // Exclude defines - this.defineNames["MAINUV0"] = 0; - this.defineNames["MAINUV1"] = 0; - this.defineNames["MAINUV2"] = 0; - this.defineNames["MAINUV3"] = 0; - this.defineNames["MAINUV4"] = 0; - this.defineNames["MAINUV5"] = 0; - this.defineNames["MAINUV6"] = 0; - this.defineNames["MAINUV7"] = 0; - } - /** - * Emits console errors and exceptions if there is a failing check - */ - emitErrors() { - let errorMessage = ""; - if (!this.checks.emitVertex && !this.allowEmptyVertexProgram) { - errorMessage += "NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\n"; - } - if (!this.checks.emitFragment) { - errorMessage += "NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\n"; - } - for (const notConnectedInput of this.checks.notConnectedNonOptionalInputs) { - errorMessage += `input ${notConnectedInput.name} from block ${notConnectedInput.ownerBlock.name}[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional.\n`; - } - if (errorMessage) { - throw "Build of NodeMaterial failed:\n" + errorMessage; - } - } -} -//# sourceMappingURL=nodeMaterialBuildStateSharedData.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBlockConnectionPoint.js - - - -/** - * Enum used to define the compatibility state between two connection points - */ -var NodeMaterialConnectionPointCompatibilityStates; -(function (NodeMaterialConnectionPointCompatibilityStates) { - /** Points are compatibles */ - NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["Compatible"] = 0] = "Compatible"; - /** Points are incompatible because of their types */ - NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["TypeIncompatible"] = 1] = "TypeIncompatible"; - /** Points are incompatible because of their targets (vertex vs fragment) */ - NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["TargetIncompatible"] = 2] = "TargetIncompatible"; - /** Points are incompatible because they are in the same hierarchy **/ - NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["HierarchyIssue"] = 3] = "HierarchyIssue"; -})(NodeMaterialConnectionPointCompatibilityStates || (NodeMaterialConnectionPointCompatibilityStates = {})); -/** - * Defines the direction of a connection point - */ -var NodeMaterialConnectionPointDirection; -(function (NodeMaterialConnectionPointDirection) { - /** Input */ - NodeMaterialConnectionPointDirection[NodeMaterialConnectionPointDirection["Input"] = 0] = "Input"; - /** Output */ - NodeMaterialConnectionPointDirection[NodeMaterialConnectionPointDirection["Output"] = 1] = "Output"; -})(NodeMaterialConnectionPointDirection || (NodeMaterialConnectionPointDirection = {})); -/** - * Defines a connection point for a block - */ -class NodeMaterialConnectionPoint { - /** - * Checks if two types are equivalent - * @param type1 type 1 to check - * @param type2 type 2 to check - * @returns true if both types are equivalent, else false - */ - static AreEquivalentTypes(type1, type2) { - switch (type1) { - case NodeMaterialBlockConnectionPointTypes.Vector3: { - if (type2 === NodeMaterialBlockConnectionPointTypes.Color3) { - return true; - } - break; - } - case NodeMaterialBlockConnectionPointTypes.Vector4: { - if (type2 === NodeMaterialBlockConnectionPointTypes.Color4) { - return true; - } - break; - } - case NodeMaterialBlockConnectionPointTypes.Color3: { - if (type2 === NodeMaterialBlockConnectionPointTypes.Vector3) { - return true; - } - break; - } - case NodeMaterialBlockConnectionPointTypes.Color4: { - if (type2 === NodeMaterialBlockConnectionPointTypes.Vector4) { - return true; - } - break; - } - } - return false; - } - /** Gets the direction of the point */ - get direction() { - return this._direction; - } - /** - * Gets or sets the associated variable name in the shader - */ - get associatedVariableName() { - if (this._ownerBlock.isInput) { - return this._ownerBlock.associatedVariableName; - } - if ((!this._enforceAssociatedVariableName || !this._associatedVariableName) && this._connectedPoint) { - return this._connectedPoint.associatedVariableName; - } - return this._associatedVariableName; - } - set associatedVariableName(value) { - this._associatedVariableName = value; - } - /** Get the inner type (ie AutoDetect for instance instead of the inferred one) */ - get innerType() { - if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected) { - return this.type; - } - return this._type; - } - /** - * Gets or sets the connection point type (default is float) - */ - get type() { - if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) { - if (this._ownerBlock.isInput) { - return this._ownerBlock.type; - } - if (this._connectedPoint) { - return this._connectedPoint.type; - } - if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected) { - return this._linkedConnectionSource.type; - } - } - if (this._type === NodeMaterialBlockConnectionPointTypes.BasedOnInput) { - if (this._typeConnectionSource) { - if (!this._typeConnectionSource.isConnected && this._defaultConnectionPointType) { - return this._defaultConnectionPointType; - } - return this._typeConnectionSource.type; - } - else if (this._defaultConnectionPointType) { - return this._defaultConnectionPointType; - } - } - return this._type; - } - set type(value) { - this._type = value; - } - /** Gets or sets the target of that connection point */ - get target() { - if (!this._prioritizeVertex || !this._ownerBlock) { - return this._target; - } - if (this._target !== NodeMaterialBlockTargets.VertexAndFragment) { - return this._target; - } - if (this._ownerBlock.target === NodeMaterialBlockTargets.Fragment) { - return NodeMaterialBlockTargets.Fragment; - } - return NodeMaterialBlockTargets.Vertex; - } - set target(value) { - this._target = value; - } - /** - * Gets a boolean indicating that the current point is connected to another NodeMaterialBlock - */ - get isConnected() { - return this.connectedPoint !== null || this.hasEndpoints; - } - /** - * Gets a boolean indicating that the current point is connected to an input block - */ - get isConnectedToInputBlock() { - return this.connectedPoint !== null && this.connectedPoint.ownerBlock.isInput; - } - /** - * Gets a the connected input block (if any) - */ - get connectInputBlock() { - if (!this.isConnectedToInputBlock) { - return null; - } - return this.connectedPoint.ownerBlock; - } - /** Get the other side of the connection (if any) */ - get connectedPoint() { - return this._connectedPoint; - } - /** Get the block that owns this connection point */ - get ownerBlock() { - return this._ownerBlock; - } - /** Get the block connected on the other side of this connection (if any) */ - get sourceBlock() { - if (!this._connectedPoint) { - return null; - } - return this._connectedPoint.ownerBlock; - } - /** Get the block connected on the endpoints of this connection (if any) */ - get connectedBlocks() { - if (this._endpoints.length === 0) { - return []; - } - return this._endpoints.map((e) => e.ownerBlock); - } - /** Gets the list of connected endpoints */ - get endpoints() { - return this._endpoints; - } - /** Gets a boolean indicating if that output point is connected to at least one input */ - get hasEndpoints() { - return this._endpoints && this._endpoints.length > 0; - } - /** Gets a boolean indicating that this connection has a path to the vertex output*/ - get isDirectlyConnectedToVertexOutput() { - if (!this.hasEndpoints) { - return false; - } - for (const endpoint of this._endpoints) { - if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Vertex) { - return true; - } - if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) { - if (endpoint.ownerBlock.outputs.some((o) => o.isDirectlyConnectedToVertexOutput)) { - return true; - } - } - } - return false; - } - /** Gets a boolean indicating that this connection will be used in the vertex shader */ - get isConnectedInVertexShader() { - if (this.target === NodeMaterialBlockTargets.Vertex) { - return true; - } - if (!this.hasEndpoints) { - return false; - } - for (const endpoint of this._endpoints) { - if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Vertex) { - return true; - } - if (endpoint.target === NodeMaterialBlockTargets.Vertex) { - return true; - } - if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) { - if (endpoint.ownerBlock.outputs.some((o) => o.isConnectedInVertexShader)) { - return true; - } - } - } - return false; - } - /** Gets a boolean indicating that this connection will be used in the fragment shader */ - get isConnectedInFragmentShader() { - if (this.target === NodeMaterialBlockTargets.Fragment) { - return true; - } - if (!this.hasEndpoints) { - return false; - } - for (const endpoint of this._endpoints) { - if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { - return true; - } - if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) { - if (endpoint.ownerBlock.isConnectedInFragmentShader()) { - return true; - } - } - } - return false; - } - /** - * Creates a block suitable to be used as an input for this input point. - * If null is returned, a block based on the point type will be created. - * @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 - */ - createCustomInputBlock() { - return null; - } - /** - * Creates a new connection point - * @param name defines the connection point name - * @param ownerBlock defines the block hosting this connection point - * @param direction defines the direction of the connection point - */ - constructor(name, ownerBlock, direction) { - /** @internal */ - this._connectedPoint = null; - this._endpoints = new Array(); - /** @internal */ - this._typeConnectionSource = null; - /** @internal */ - this._defaultConnectionPointType = null; - /** @internal */ - this._linkedConnectionSource = null; - /** @internal */ - this._acceptedConnectionPointType = null; - this._type = NodeMaterialBlockConnectionPointTypes.Float; - /** @internal */ - this._enforceAssociatedVariableName = false; - /** Indicates that this connection point needs dual validation before being connected to another point */ - this.needDualDirectionValidation = false; - /** - * Gets or sets the additional types supported by this connection point - */ - this.acceptedConnectionPointTypes = new Array(); - /** - * Gets or sets the additional types excluded by this connection point - */ - this.excludedConnectionPointTypes = new Array(); - /** - * Observable triggered when this point is connected - */ - this.onConnectionObservable = new observable_Observable(); - /** - * Gets or sets a boolean indicating that this connection point is exposed on a frame - */ - this.isExposedOnFrame = false; - /** - * Gets or sets number indicating the position that the port is exposed to on a frame - */ - this.exposedPortPosition = -1; - /** @internal */ - this._prioritizeVertex = false; - this._target = NodeMaterialBlockTargets.VertexAndFragment; - this._ownerBlock = ownerBlock; - this.name = name; - this._direction = direction; - } - /** - * Gets the current class name e.g. "NodeMaterialConnectionPoint" - * @returns the class name - */ - getClassName() { - return "NodeMaterialConnectionPoint"; - } - /** - * Gets a boolean indicating if the current point can be connected to another point - * @param connectionPoint defines the other connection point - * @returns a boolean - */ - canConnectTo(connectionPoint) { - return this.checkCompatibilityState(connectionPoint) === NodeMaterialConnectionPointCompatibilityStates.Compatible; - } - /** - * Gets a number indicating if the current point can be connected to another point - * @param connectionPoint defines the other connection point - * @returns a number defining the compatibility state - */ - checkCompatibilityState(connectionPoint) { - const ownerBlock = this._ownerBlock; - const otherBlock = connectionPoint.ownerBlock; - if (ownerBlock.target === NodeMaterialBlockTargets.Fragment) { - // Let's check we are not going reverse - if (otherBlock.target === NodeMaterialBlockTargets.Vertex) { - return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible; - } - for (const output of otherBlock.outputs) { - if (output.ownerBlock.target != NodeMaterialBlockTargets.Neutral && output.isConnectedInVertexShader) { - return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible; - } - } - } - if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeMaterialBlockConnectionPointTypes.AutoDetect) { - // Equivalents - if (NodeMaterialConnectionPoint.AreEquivalentTypes(this.type, connectionPoint.type)) { - return NodeMaterialConnectionPointCompatibilityStates.Compatible; - } - // Accepted types - if ((connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) || - (connectionPoint._acceptedConnectionPointType && NodeMaterialConnectionPoint.AreEquivalentTypes(connectionPoint._acceptedConnectionPointType.type, this.type))) { - return NodeMaterialConnectionPointCompatibilityStates.Compatible; - } - else { - return NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible; - } - } - // Excluded - if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) { - return NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible; - } - // Check hierarchy - let targetBlock = otherBlock; - let sourceBlock = ownerBlock; - if (this.direction === NodeMaterialConnectionPointDirection.Input) { - targetBlock = ownerBlock; - sourceBlock = otherBlock; - } - if (targetBlock.isAnAncestorOf(sourceBlock)) { - return NodeMaterialConnectionPointCompatibilityStates.HierarchyIssue; - } - return NodeMaterialConnectionPointCompatibilityStates.Compatible; - } - /** - * Connect this point to another connection point - * @param connectionPoint defines the other connection point - * @param ignoreConstraints defines if the system will ignore connection type constraints (default is false) - * @returns the current connection point - */ - connectTo(connectionPoint, ignoreConstraints = false) { - if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) { - throw "Cannot connect these two connectors."; - } - this._endpoints.push(connectionPoint); - connectionPoint._connectedPoint = this; - this._enforceAssociatedVariableName = false; - this.onConnectionObservable.notifyObservers(connectionPoint); - connectionPoint.onConnectionObservable.notifyObservers(this); - return this; - } - /** - * Disconnect this point from one of his endpoint - * @param endpoint defines the other connection point - * @returns the current connection point - */ - disconnectFrom(endpoint) { - const index = this._endpoints.indexOf(endpoint); - if (index === -1) { - return this; - } - this._endpoints.splice(index, 1); - endpoint._connectedPoint = null; - this._enforceAssociatedVariableName = false; - endpoint._enforceAssociatedVariableName = false; - return this; - } - /** - * Fill the list of excluded connection point types with all types other than those passed in the parameter - * @param mask Types (ORed values of NodeMaterialBlockConnectionPointTypes) that are allowed, and thus will not be pushed to the excluded list - */ - addExcludedConnectionPointFromAllowedTypes(mask) { - let bitmask = 1; - while (bitmask < NodeMaterialBlockConnectionPointTypes.All) { - if (!(mask & bitmask)) { - this.excludedConnectionPointTypes.push(bitmask); - } - bitmask = bitmask << 1; - } - } - /** - * Serializes this point in a JSON representation - * @param isInput defines if the connection point is an input (default is true) - * @returns the serialized point object - */ - serialize(isInput = true) { - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.displayName = this.displayName; - if (isInput && this.connectedPoint) { - serializationObject.inputName = this.name; - serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId; - serializationObject.targetConnectionName = this.connectedPoint.name; - serializationObject.isExposedOnFrame = true; - serializationObject.exposedPortPosition = this.exposedPortPosition; - } - if (this.isExposedOnFrame || this.exposedPortPosition >= 0) { - serializationObject.isExposedOnFrame = true; - serializationObject.exposedPortPosition = this.exposedPortPosition; - } - return serializationObject; - } - /** - * Release resources - */ - dispose() { - this.onConnectionObservable.clear(); - } -} -//# sourceMappingURL=nodeMaterialBlockConnectionPoint.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBlock.js - - - - - -/** - * Defines a block that can be used inside a node based material - */ -class NodeMaterialBlock { - /** - * Gets the name of the block - */ - get name() { - return this._name; - } - /** - * Sets the name of the block. Will check if the name is valid. - */ - set name(newName) { - if (!this.validateBlockName(newName)) { - return; - } - this._name = newName; - } - /** - * Gets a boolean indicating that this block can only be used once per NodeMaterial - */ - get isUnique() { - return this._isUnique; - } - /** - * Gets a boolean indicating that this block is an end block (e.g. it is generating a system value) - */ - get isFinalMerger() { - return this._isFinalMerger; - } - /** - * Gets a boolean indicating that this block is an input (e.g. it sends data to the shader) - */ - get isInput() { - return this._isInput; - } - /** - * Gets a boolean indicating if this block is a teleport out - */ - get isTeleportOut() { - return this._isTeleportOut; - } - /** - * Gets a boolean indicating if this block is a teleport in - */ - get isTeleportIn() { - return this._isTeleportIn; - } - /** - * Gets or sets the build Id - */ - get buildId() { - return this._buildId; - } - set buildId(value) { - this._buildId = value; - } - /** - * Gets or sets the target of the block - */ - get target() { - return this._target; - } - set target(value) { - if ((this._target & value) !== 0) { - return; - } - this._target = value; - } - /** - * Gets the list of input points - */ - get inputs() { - return this._inputs; - } - /** Gets the list of output points */ - get outputs() { - return this._outputs; - } - /** - * Find an input by its name - * @param name defines the name of the input to look for - * @returns the input or null if not found - */ - getInputByName(name) { - const filter = this._inputs.filter((e) => e.name === name); - if (filter.length) { - return filter[0]; - } - return null; - } - /** - * Find an output by its name - * @param name defines the name of the output to look for - * @returns the output or null if not found - */ - getOutputByName(name) { - const filter = this._outputs.filter((e) => e.name === name); - if (filter.length) { - return filter[0]; - } - return null; - } - /** - * Creates a new NodeMaterialBlock - * @param name defines the block name - * @param target defines the target of that block (Vertex by default) - * @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false - */ - constructor(name, target = NodeMaterialBlockTargets.Vertex, isFinalMerger = false) { - this._isFinalMerger = false; - this._isInput = false; - this._isTeleportOut = false; - this._isTeleportIn = false; - this._name = ""; - this._isUnique = false; - /** Gets or sets a boolean indicating that only one input can be connected at a time */ - this.inputsAreExclusive = false; - /** @internal */ - this._codeVariableName = ""; - /** @internal */ - this._inputs = new Array(); - /** @internal */ - this._outputs = new Array(); - /** - * Gets or sets the comments associated with this block - */ - this.comments = ""; - /** Gets or sets a boolean indicating that this input can be edited in the Inspector (false by default) */ - this.visibleInInspector = false; - /** Gets or sets a boolean indicating that this input can be edited from a collapsed frame */ - this.visibleOnFrame = false; - this._target = target; - this._originalTargetIsNeutral = target === NodeMaterialBlockTargets.Neutral; - this._isFinalMerger = isFinalMerger; - this._isInput = this.getClassName() === "InputBlock"; - this._isTeleportOut = this.getClassName() === "NodeMaterialTeleportOutBlock"; - this._isTeleportIn = this.getClassName() === "NodeMaterialTeleportInBlock"; - this._name = name; - this.uniqueId = UniqueIdGenerator.UniqueId; - } - /** @internal */ - _setInitialTarget(target) { - this._target = target; - this._originalTargetIsNeutral = target === NodeMaterialBlockTargets.Neutral; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - initialize(state) { - // Do nothing - } - /** - * Bind data to effect. Will only be called for blocks with isBindable === true - * @param effect defines the effect to bind data to - * @param nodeMaterial defines the hosting NodeMaterial - * @param mesh defines the mesh that will be rendered - * @param subMesh defines the submesh that will be rendered - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - bind(effect, nodeMaterial, mesh, subMesh) { - // Do nothing - } - _declareOutput(output, state) { - return `${state._getGLType(output.type)} ${output.associatedVariableName}`; - } - _writeVariable(currentPoint) { - const connectionPoint = currentPoint.connectedPoint; - if (connectionPoint) { - return `${currentPoint.associatedVariableName}`; - } - return `0.`; - } - _writeFloat(value) { - let stringVersion = value.toString(); - if (stringVersion.indexOf(".") === -1) { - stringVersion += ".0"; - } - return `${stringVersion}`; - } - /** - * Gets the current class name e.g. "NodeMaterialBlock" - * @returns the class name - */ - getClassName() { - return "NodeMaterialBlock"; - } - /** Gets a boolean indicating that this connection will be used in the fragment shader */ - isConnectedInFragmentShader() { - return this.outputs.some((o) => o.isConnectedInFragmentShader); - } - /** - * Register a new input. Must be called inside a block constructor - * @param name defines the connection point name - * @param type defines the connection point type - * @param isOptional defines a boolean indicating that this input can be omitted - * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default) - * @param point an already created connection point. If not provided, create a new one - * @returns the current block - */ - registerInput(name, type, isOptional = false, target, point) { - point = point !== null && point !== void 0 ? point : new NodeMaterialConnectionPoint(name, this, NodeMaterialConnectionPointDirection.Input); - point.type = type; - point.isOptional = isOptional; - if (target) { - point.target = target; - } - this._inputs.push(point); - return this; - } - /** - * Register a new output. Must be called inside a block constructor - * @param name defines the connection point name - * @param type defines the connection point type - * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default) - * @param point an already created connection point. If not provided, create a new one - * @returns the current block - */ - registerOutput(name, type, target, point) { - point = point !== null && point !== void 0 ? point : new NodeMaterialConnectionPoint(name, this, NodeMaterialConnectionPointDirection.Output); - point.type = type; - if (target) { - point.target = target; - } - this._outputs.push(point); - return this; - } - /** - * Will return the first available input e.g. the first one which is not an uniform or an attribute - * @param forOutput defines an optional connection point to check compatibility with - * @returns the first available input or null - */ - getFirstAvailableInput(forOutput = null) { - for (const input of this._inputs) { - if (!input.connectedPoint) { - if (!forOutput || forOutput.type === input.type || input.type === NodeMaterialBlockConnectionPointTypes.AutoDetect) { - return input; - } - } - } - return null; - } - /** - * Will return the first available output e.g. the first one which is not yet connected and not a varying - * @param forBlock defines an optional block to check compatibility with - * @returns the first available input or null - */ - getFirstAvailableOutput(forBlock = null) { - for (const output of this._outputs) { - if (!forBlock || !forBlock.target || forBlock.target === NodeMaterialBlockTargets.Neutral || (forBlock.target & output.target) !== 0) { - return output; - } - } - return null; - } - /** - * Gets the sibling of the given output - * @param current defines the current output - * @returns the next output in the list or null - */ - getSiblingOutput(current) { - const index = this._outputs.indexOf(current); - if (index === -1 || index >= this._outputs.length) { - return null; - } - return this._outputs[index + 1]; - } - /** - * Checks if the current block is an ancestor of a given block - * @param block defines the potential descendant block to check - * @returns true if block is a descendant - */ - isAnAncestorOf(block) { - for (const output of this._outputs) { - if (!output.hasEndpoints) { - continue; - } - for (const endpoint of output.endpoints) { - if (endpoint.ownerBlock === block) { - return true; - } - if (endpoint.ownerBlock.isAnAncestorOf(block)) { - return true; - } - } - } - return false; - } - /** - * Connect current block with another block - * @param other defines the block to connect with - * @param options define the various options to help pick the right connections - * @param options.input - * @param options.output - * @param options.outputSwizzle - * @returns the current block - */ - connectTo(other, options) { - if (this._outputs.length === 0) { - return; - } - let output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other); - let notFound = true; - while (notFound) { - const input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output); - if (output && input && output.canConnectTo(input)) { - output.connectTo(input); - notFound = false; - } - else if (!output) { - throw "Unable to find a compatible match"; - } - else { - output = this.getSiblingOutput(output); - } - } - return this; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _buildBlock(state) { - // Empty. Must be defined by child nodes - } - /** - * Add uniforms, samplers and uniform buffers at compilation time - * @param state defines the state to update - * @param nodeMaterial defines the node material requesting the update - * @param defines defines the material defines to update - * @param uniformBuffers defines the list of uniform buffer names - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) { - // Do nothing - } - /** - * Add potential fallbacks if shader compilation fails - * @param mesh defines the mesh to be rendered - * @param fallbacks defines the current prioritized list of fallbacks - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - provideFallbacks(mesh, fallbacks) { - // Do nothing - } - /** - * Initialize defines for shader compilation - * @param mesh defines the mesh to be rendered - * @param nodeMaterial defines the node material requesting the update - * @param defines defines the material defines to update - * @param useInstances specifies that instances should be used - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - initializeDefines(mesh, nodeMaterial, defines, useInstances = false) { } - /** - * Update defines for shader compilation - * @param mesh defines the mesh to be rendered - * @param nodeMaterial defines the node material requesting the update - * @param defines defines the material defines to update - * @param useInstances specifies that instances should be used - * @param subMesh defines which submesh to render - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - prepareDefines(mesh, nodeMaterial, defines, useInstances = false, subMesh) { - // Do nothing - } - /** - * Lets the block try to connect some inputs automatically - * @param material defines the hosting NodeMaterial - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - autoConfigure(material) { - // Do nothing - } - /** - * Function called when a block is declared as repeatable content generator - * @param vertexShaderState defines the current compilation state for the vertex shader - * @param fragmentShaderState defines the current compilation state for the fragment shader - * @param mesh defines the mesh to be rendered - * @param defines defines the material defines to update - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - replaceRepeatableContent(vertexShaderState, fragmentShaderState, mesh, defines) { - // Do nothing - } - /** Gets a boolean indicating that the code of this block will be promoted to vertex shader even if connected to fragment output */ - get willBeGeneratedIntoVertexShaderFromFragmentShader() { - if (this.isInput || this.isFinalMerger) { - return false; - } - if (this._outputs.some((o) => o.isDirectlyConnectedToVertexOutput)) { - return false; - } - if (this.target === NodeMaterialBlockTargets.Vertex) { - return false; - } - if (this.target === NodeMaterialBlockTargets.VertexAndFragment || this.target === NodeMaterialBlockTargets.Neutral) { - if (this._outputs.some((o) => o.isConnectedInVertexShader)) { - return true; - } - } - return false; - } - /** - * Checks if the block is ready - * @param mesh defines the mesh to be rendered - * @param nodeMaterial defines the node material requesting the update - * @param defines defines the material defines to update - * @param useInstances specifies that instances should be used - * @returns true if the block is ready - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - isReady(mesh, nodeMaterial, defines, useInstances = false) { - return true; - } - _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) { - if (looseCoupling) { - this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0]; - } - else { - this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1]; - } - this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0]; - } - _processBuild(block, state, input, activeBlocks) { - block.build(state, activeBlocks); - const localBlockIsFragment = state._vertexState != null; - const otherBlockWasGeneratedInVertexShader = block._buildTarget === NodeMaterialBlockTargets.Vertex && block.target !== NodeMaterialBlockTargets.VertexAndFragment; - if (localBlockIsFragment && - ((block.target & block._buildTarget) === 0 || - (block.target & input.target) === 0 || - (this.target !== NodeMaterialBlockTargets.VertexAndFragment && otherBlockWasGeneratedInVertexShader))) { - // context switch! We need a varying - if ((!block.isInput && state.target !== block._buildTarget) || // block was already emitted by vertex shader - (block.isInput && block.isAttribute && !block._noContextSwitch) // block is an attribute - ) { - const connectedPoint = input.connectedPoint; - if (state._vertexState._emitVaryingFromString("v_" + connectedPoint.associatedVariableName, state._getGLType(connectedPoint.type))) { - state._vertexState.compilationString += `${"v_" + connectedPoint.associatedVariableName} = ${connectedPoint.associatedVariableName};\n`; - } - input.associatedVariableName = "v_" + connectedPoint.associatedVariableName; - input._enforceAssociatedVariableName = true; - } - } - } - /** - * Validates the new name for the block node. - * @param newName the new name to be given to the node. - * @returns false if the name is a reserve word, else true. - */ - validateBlockName(newName) { - const reservedNames = [ - "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 reservedName of reservedNames) { - if (newName === reservedName) { - return false; - } - } - return true; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _customBuildStep(state, activeBlocks) { - // Must be implemented by children - } - /** - * Compile the current node and generate the shader code - * @param state defines the current compilation state (uniforms, samplers, current string) - * @param activeBlocks defines the list of active blocks (i.e. blocks to compile) - * @returns true if already built - */ - build(state, activeBlocks) { - if (this._buildId === state.sharedData.buildId) { - return true; - } - if (!this.isInput) { - /** Prepare outputs */ - for (const output of this._outputs) { - if (!output.associatedVariableName) { - output.associatedVariableName = state._getFreeVariableName(output.name); - } - } - } - // Check if "parent" blocks are compiled - for (const input of this._inputs) { - if (!input.connectedPoint) { - if (!input.isOptional) { - // Emit a warning - state.sharedData.checks.notConnectedNonOptionalInputs.push(input); - } - continue; - } - if (this.target !== NodeMaterialBlockTargets.Neutral) { - if ((input.target & this.target) === 0) { - continue; - } - if ((input.target & state.target) === 0) { - continue; - } - } - const block = input.connectedPoint.ownerBlock; - if (block && block !== this) { - this._processBuild(block, state, input, activeBlocks); - } - } - this._customBuildStep(state, activeBlocks); - if (this._buildId === state.sharedData.buildId) { - return true; // Need to check again as inputs can be connected multiple time to this endpoint - } - // Logs - if (state.sharedData.verbose) { - console.log(`${state.target === NodeMaterialBlockTargets.Vertex ? "Vertex shader" : "Fragment shader"}: Building ${this.name} [${this.getClassName()}]`); - } - // Checks final outputs - if (this.isFinalMerger) { - switch (state.target) { - case NodeMaterialBlockTargets.Vertex: - state.sharedData.checks.emitVertex = true; - break; - case NodeMaterialBlockTargets.Fragment: - state.sharedData.checks.emitFragment = true; - break; - } - } - if (!this.isInput && state.sharedData.emitComments) { - state.compilationString += `\n//${this.name}\n`; - } - this._buildBlock(state); - this._buildId = state.sharedData.buildId; - this._buildTarget = state.target; - // Compile connected blocks - for (const output of this._outputs) { - if ((output.target & state.target) === 0) { - continue; - } - for (const endpoint of output.endpoints) { - const block = endpoint.ownerBlock; - if (block && (block.target & state.target) !== 0 && activeBlocks.indexOf(block) !== -1) { - this._processBuild(block, state, endpoint, activeBlocks); - } - } - } - return false; - } - _inputRename(name) { - return name; - } - _outputRename(name) { - return name; - } - _dumpPropertiesCode() { - const variableName = this._codeVariableName; - return `${variableName}.visibleInInspector = ${this.visibleInInspector};\n${variableName}.visibleOnFrame = ${this.visibleOnFrame};\n${variableName}.target = ${this.target};\n`; - } - /** - * @internal - */ - _dumpCode(uniqueNames, alreadyDumped) { - alreadyDumped.push(this); - // Get unique name - const nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, ""); - this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`; - if (uniqueNames.indexOf(this._codeVariableName) !== -1) { - let index = 0; - do { - index++; - this._codeVariableName = nameAsVariableName + index; - } while (uniqueNames.indexOf(this._codeVariableName) !== -1); - } - uniqueNames.push(this._codeVariableName); - // Declaration - let codeString = `\n// ${this.getClassName()}\n`; - if (this.comments) { - codeString += `// ${this.comments}\n`; - } - codeString += `var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`; - // Properties - codeString += this._dumpPropertiesCode(); - // Inputs - for (const input of this.inputs) { - if (!input.isConnected) { - continue; - } - const connectedOutput = input.connectedPoint; - const connectedBlock = connectedOutput.ownerBlock; - if (alreadyDumped.indexOf(connectedBlock) === -1) { - codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped); - } - } - // Outputs - for (const output of this.outputs) { - if (!output.hasEndpoints) { - continue; - } - for (const endpoint of output.endpoints) { - const connectedBlock = endpoint.ownerBlock; - if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) { - codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped); - } - } - } - return codeString; - } - /** - * @internal - */ - _dumpCodeForOutputConnections(alreadyDumped) { - let codeString = ""; - if (alreadyDumped.indexOf(this) !== -1) { - return codeString; - } - alreadyDumped.push(this); - for (const input of this.inputs) { - if (!input.isConnected) { - continue; - } - const connectedOutput = input.connectedPoint; - const connectedBlock = connectedOutput.ownerBlock; - codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped); - codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});\n`; - } - return codeString; - } - /** - * Clone the current block to a new identical block - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a copy of the current block - */ - clone(scene, rootUrl = "") { - const serializationObject = this.serialize(); - const blockType = GetClass(serializationObject.customType); - if (blockType) { - const block = new blockType(); - block._deserialize(serializationObject, scene, rootUrl); - return block; - } - return null; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = {}; - serializationObject.customType = "BABYLON." + this.getClassName(); - serializationObject.id = this.uniqueId; - serializationObject.name = this.name; - serializationObject.comments = this.comments; - serializationObject.visibleInInspector = this.visibleInInspector; - serializationObject.visibleOnFrame = this.visibleOnFrame; - serializationObject.target = this.target; - serializationObject.inputs = []; - serializationObject.outputs = []; - for (const input of this.inputs) { - serializationObject.inputs.push(input.serialize()); - } - for (const output of this.outputs) { - serializationObject.outputs.push(output.serialize(false)); - } - return serializationObject; - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _deserialize(serializationObject, scene, rootUrl) { - var _a; - this.name = serializationObject.name; - this.comments = serializationObject.comments; - this.visibleInInspector = !!serializationObject.visibleInInspector; - this.visibleOnFrame = !!serializationObject.visibleOnFrame; - this._target = (_a = serializationObject.target) !== null && _a !== void 0 ? _a : this.target; - this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject); - } - _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) { - const serializedInputs = serializationObject.inputs; - const serializedOutputs = serializationObject.outputs; - if (serializedInputs) { - serializedInputs.forEach((port, i) => { - if (port.displayName) { - this.inputs[i].displayName = port.displayName; - } - if (port.isExposedOnFrame) { - this.inputs[i].isExposedOnFrame = port.isExposedOnFrame; - this.inputs[i].exposedPortPosition = port.exposedPortPosition; - } - }); - } - if (serializedOutputs) { - serializedOutputs.forEach((port, i) => { - if (port.displayName) { - this.outputs[i].displayName = port.displayName; - } - if (port.isExposedOnFrame) { - this.outputs[i].isExposedOnFrame = port.isExposedOnFrame; - this.outputs[i].exposedPortPosition = port.exposedPortPosition; - } - }); - } - } - /** - * Release resources - */ - dispose() { - for (const input of this.inputs) { - input.dispose(); - } - for (const output of this.outputs) { - output.dispose(); - } - } -} -//# sourceMappingURL=nodeMaterialBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/transformBlock.js - - - - -/** - * Block used to transform a vector (2, 3 or 4) with a matrix. It will generate a Vector4 - */ -class TransformBlock extends NodeMaterialBlock { - /** - * Creates a new TransformBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Defines the value to use to complement W value to transform it to a Vector4 - */ - this.complementW = 1; - /** - * Defines the value to use to complement z value to transform it to a Vector4 - */ - this.complementZ = 0; - this.target = NodeMaterialBlockTargets.Vertex; - this.registerInput("vector", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("transform", NodeMaterialBlockConnectionPointTypes.Matrix); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3); - this._inputs[0].onConnectionObservable.add((other) => { - if (other.ownerBlock.isInput) { - const otherAsInput = other.ownerBlock; - if (otherAsInput.name === "normal" || otherAsInput.name === "tangent") { - this.complementW = 0; - } - } - }); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "TransformBlock"; - } - /** - * Gets the vector input - */ - get vector() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets the xyz output component - */ - get xyz() { - return this._outputs[1]; - } - /** - * Gets the matrix transform input - */ - get transform() { - return this._inputs[1]; - } - _buildBlock(state) { - super._buildBlock(state); - const vector = this.vector; - const transform = this.transform; - if (vector.connectedPoint) { - // None uniform scaling case. - if (this.complementW === 0) { - const comments = `//${this.name}`; - state._emitFunctionFromInclude("helperFunctions", comments); - state.sharedData.blocksWithDefines.push(this); - const transformName = state._getFreeVariableName(`${transform.associatedVariableName}_NUS`); - state.compilationString += `mat3 ${transformName} = mat3(${transform.associatedVariableName});\n`; - state.compilationString += `#ifdef NONUNIFORMSCALING\n`; - state.compilationString += `${transformName} = transposeMat3(inverseMat3(${transformName}));\n`; - state.compilationString += `#endif\n`; - switch (vector.connectedPoint.type) { - case NodeMaterialBlockConnectionPointTypes.Vector2: - state.compilationString += - this._declareOutput(this.output, state) + - ` = vec4(${transformName} * vec3(${vector.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\n`; - break; - case NodeMaterialBlockConnectionPointTypes.Vector3: - case NodeMaterialBlockConnectionPointTypes.Color3: - state.compilationString += - this._declareOutput(this.output, state) + ` = vec4(${transformName} * ${vector.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`; - break; - default: - state.compilationString += - this._declareOutput(this.output, state) + ` = vec4(${transformName} * ${vector.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\n`; - break; - } - } - else { - const transformName = transform.associatedVariableName; - switch (vector.connectedPoint.type) { - case NodeMaterialBlockConnectionPointTypes.Vector2: - state.compilationString += - this._declareOutput(this.output, state) + - ` = ${transformName} * vec4(${vector.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\n`; - break; - case NodeMaterialBlockConnectionPointTypes.Vector3: - case NodeMaterialBlockConnectionPointTypes.Color3: - state.compilationString += - this._declareOutput(this.output, state) + ` = ${transformName} * vec4(${vector.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`; - break; - default: - state.compilationString += this._declareOutput(this.output, state) + ` = ${transformName} * ${vector.associatedVariableName};\n`; - break; - } - } - if (this.xyz.hasEndpoints) { - state.compilationString += this._declareOutput(this.xyz, state) + ` = ${this.output.associatedVariableName}.xyz;\n`; - } - } - return this; - } - /** - * Update defines for shader compilation - * @param mesh defines the mesh to be rendered - * @param nodeMaterial defines the node material requesting the update - * @param defines defines the material defines to update - */ - prepareDefines(mesh, nodeMaterial, defines) { - // Do nothing - if (mesh.nonUniformScaling) { - defines.setValue("NONUNIFORMSCALING", true); - } - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.complementZ = this.complementZ; - serializationObject.complementW = this.complementW; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.complementZ = serializationObject.complementZ !== undefined ? serializationObject.complementZ : 0.0; - this.complementW = serializationObject.complementW !== undefined ? serializationObject.complementW : 1.0; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.complementZ = ${this.complementZ};\n`; - codeString += `${this._codeVariableName}.complementW = ${this.complementW};\n`; - return codeString; - } -} -RegisterClass("BABYLON.TransformBlock", TransformBlock); -//# sourceMappingURL=transformBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/vertexOutputBlock.js - - - - -/** - * Block used to output the vertex position - */ -class VertexOutputBlock extends NodeMaterialBlock { - /** - * Creates a new VertexOutputBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Vertex, true); - this.registerInput("vector", NodeMaterialBlockConnectionPointTypes.Vector4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "VertexOutputBlock"; - } - /** - * Gets the vector input component - */ - get vector() { - return this._inputs[0]; - } - _isLogarithmicDepthEnabled(nodeList) { - for (const node of nodeList) { - if (node.useLogarithmicDepth) { - return true; - } - } - return false; - } - _buildBlock(state) { - super._buildBlock(state); - const input = this.vector; - state.compilationString += `gl_Position = ${input.associatedVariableName};\n`; - if (this._isLogarithmicDepthEnabled(state.sharedData.fragmentOutputNodes)) { - state._emitUniformFromString("logarithmicDepthConstant", "float"); - state._emitVaryingFromString("vFragmentDepth", "float"); - state.compilationString += `vFragmentDepth = 1.0 + gl_Position.w;\n`; - state.compilationString += `gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\n`; - } - return this; - } -} -RegisterClass("BABYLON.VertexOutputBlock", VertexOutputBlock); -//# sourceMappingURL=vertexOutputBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Decorators/nodeDecorator.js -/** - * Enum defining the type of properties that can be edited in the property pages in the node editor - */ -var PropertyTypeForEdition; -(function (PropertyTypeForEdition) { - /** property is a boolean */ - PropertyTypeForEdition[PropertyTypeForEdition["Boolean"] = 0] = "Boolean"; - /** property is a float */ - PropertyTypeForEdition[PropertyTypeForEdition["Float"] = 1] = "Float"; - /** property is a int */ - PropertyTypeForEdition[PropertyTypeForEdition["Int"] = 2] = "Int"; - /** property is a Vector2 */ - PropertyTypeForEdition[PropertyTypeForEdition["Vector2"] = 3] = "Vector2"; - /** property is a list of values */ - PropertyTypeForEdition[PropertyTypeForEdition["List"] = 4] = "List"; -})(PropertyTypeForEdition || (PropertyTypeForEdition = {})); -/** - * Decorator that flags a property in a node block as being editable - * @param displayName - * @param propertyType - * @param groupName - * @param options - */ -function editableInPropertyPage(displayName, propertyType = PropertyTypeForEdition.Boolean, groupName = "PROPERTIES", options) { - return (target, propertyKey) => { - let propStore = target._propStore; - if (!propStore) { - propStore = []; - target._propStore = propStore; - } - propStore.push({ - propertyName: propertyKey, - displayName: displayName, - type: propertyType, - groupName: groupName, - options: options !== null && options !== void 0 ? options : {}, - }); - }; -} -//# sourceMappingURL=nodeDecorator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragmentOutputBlock.js - - - - - - - -/** - * Block used to output the final color - */ -class FragmentOutputBlock extends NodeMaterialBlock { - /** - * Create a new FragmentOutputBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment, true); - /** Gets or sets a boolean indicating if content needs to be converted to gamma space */ - this.convertToGammaSpace = false; - /** Gets or sets a boolean indicating if content needs to be converted to linear space */ - this.convertToLinearSpace = false; - /** Gets or sets a boolean indicating if logarithmic depth should be used */ - this.useLogarithmicDepth = false; - this.registerInput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, true); - this.registerInput("rgb", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); - this.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float, true); - this.rgb.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "FragmentOutputBlock"; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("logarithmicDepthConstant"); - state._excludeVariableName("vFragmentDepth"); - } - /** - * Gets the rgba input component - */ - get rgba() { - return this._inputs[0]; - } - /** - * Gets the rgb input component - */ - get rgb() { - return this._inputs[1]; - } - /** - * Gets the a input component - */ - get a() { - return this._inputs[2]; - } - prepareDefines(mesh, nodeMaterial, defines) { - defines.setValue(this._linearDefineName, this.convertToLinearSpace, true); - defines.setValue(this._gammaDefineName, this.convertToGammaSpace, true); - } - bind(effect, nodeMaterial, mesh) { - if (this.useLogarithmicDepth && mesh) { - MaterialHelper.BindLogDepth(undefined, effect, mesh.getScene()); - } - } - _buildBlock(state) { - super._buildBlock(state); - const rgba = this.rgba; - const rgb = this.rgb; - const a = this.a; - state.sharedData.hints.needAlphaBlending = rgba.isConnected || a.isConnected; - state.sharedData.blocksWithDefines.push(this); - if (this.useLogarithmicDepth) { - state._emitUniformFromString("logarithmicDepthConstant", "float"); - state._emitVaryingFromString("vFragmentDepth", "float"); - state.sharedData.bindableBlocks.push(this); - } - this._linearDefineName = state._getFreeDefineName("CONVERTTOLINEAR"); - this._gammaDefineName = state._getFreeDefineName("CONVERTTOGAMMA"); - const comments = `//${this.name}`; - state._emitFunctionFromInclude("helperFunctions", comments); - if (rgba.connectedPoint) { - if (a.isConnected) { - state.compilationString += `gl_FragColor = vec4(${rgba.associatedVariableName}.rgb, ${a.associatedVariableName});\n`; - } - else { - state.compilationString += `gl_FragColor = ${rgba.associatedVariableName};\n`; - } - } - else if (rgb.connectedPoint) { - let aValue = "1.0"; - if (a.connectedPoint) { - aValue = a.associatedVariableName; - } - if (rgb.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float) { - state.compilationString += `gl_FragColor = vec4(${rgb.associatedVariableName}, ${rgb.associatedVariableName}, ${rgb.associatedVariableName}, ${aValue});\n`; - } - else { - state.compilationString += `gl_FragColor = vec4(${rgb.associatedVariableName}, ${aValue});\n`; - } - } - else { - state.sharedData.checks.notConnectedNonOptionalInputs.push(rgba); - } - state.compilationString += `#ifdef ${this._linearDefineName}\n`; - state.compilationString += `gl_FragColor = toLinearSpace(gl_FragColor);\n`; - state.compilationString += `#endif\n`; - state.compilationString += `#ifdef ${this._gammaDefineName}\n`; - state.compilationString += `gl_FragColor = toGammaSpace(gl_FragColor);\n`; - state.compilationString += `#endif\n`; - if (this.useLogarithmicDepth) { - state.compilationString += `gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\n`; - } - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`; - codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`; - codeString += `${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.convertToGammaSpace = this.convertToGammaSpace; - serializationObject.convertToLinearSpace = this.convertToLinearSpace; - serializationObject.useLogarithmicDepth = this.useLogarithmicDepth; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - var _a; - super._deserialize(serializationObject, scene, rootUrl); - this.convertToGammaSpace = serializationObject.convertToGammaSpace; - this.convertToLinearSpace = serializationObject.convertToLinearSpace; - this.useLogarithmicDepth = (_a = serializationObject.useLogarithmicDepth) !== null && _a !== void 0 ? _a : false; - } -} -__decorate([ - editableInPropertyPage("Convert to gamma space", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: true } }) -], FragmentOutputBlock.prototype, "convertToGammaSpace", void 0); -__decorate([ - editableInPropertyPage("Convert to linear space", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: true } }) -], FragmentOutputBlock.prototype, "convertToLinearSpace", void 0); -__decorate([ - editableInPropertyPage("Use logarithmic depth", PropertyTypeForEdition.Boolean, "PROPERTIES") -], FragmentOutputBlock.prototype, "useLogarithmicDepth", void 0); -RegisterClass("BABYLON.FragmentOutputBlock", FragmentOutputBlock); -//# sourceMappingURL=fragmentOutputBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockConnectionPointMode.js -/** - * Enum defining the mode of a NodeMaterialBlockConnectionPoint - */ -var NodeMaterialBlockConnectionPointMode; -(function (NodeMaterialBlockConnectionPointMode) { - /** Value is an uniform */ - NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Uniform"] = 0] = "Uniform"; - /** Value is a mesh attribute */ - NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Attribute"] = 1] = "Attribute"; - /** Value is a varying between vertex and fragment shaders */ - NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Varying"] = 2] = "Varying"; - /** Mode is undefined */ - NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Undefined"] = 3] = "Undefined"; -})(NodeMaterialBlockConnectionPointMode || (NodeMaterialBlockConnectionPointMode = {})); -//# sourceMappingURL=nodeMaterialBlockConnectionPointMode.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialSystemValues.js -/** - * Enum used to define system values e.g. values automatically provided by the system - */ -var NodeMaterialSystemValues; -(function (NodeMaterialSystemValues) { - /** World */ - NodeMaterialSystemValues[NodeMaterialSystemValues["World"] = 1] = "World"; - /** View */ - NodeMaterialSystemValues[NodeMaterialSystemValues["View"] = 2] = "View"; - /** Projection */ - NodeMaterialSystemValues[NodeMaterialSystemValues["Projection"] = 3] = "Projection"; - /** ViewProjection */ - NodeMaterialSystemValues[NodeMaterialSystemValues["ViewProjection"] = 4] = "ViewProjection"; - /** WorldView */ - NodeMaterialSystemValues[NodeMaterialSystemValues["WorldView"] = 5] = "WorldView"; - /** WorldViewProjection */ - NodeMaterialSystemValues[NodeMaterialSystemValues["WorldViewProjection"] = 6] = "WorldViewProjection"; - /** CameraPosition */ - NodeMaterialSystemValues[NodeMaterialSystemValues["CameraPosition"] = 7] = "CameraPosition"; - /** Fog Color */ - NodeMaterialSystemValues[NodeMaterialSystemValues["FogColor"] = 8] = "FogColor"; - /** Delta time */ - NodeMaterialSystemValues[NodeMaterialSystemValues["DeltaTime"] = 9] = "DeltaTime"; - /** Camera parameters */ - NodeMaterialSystemValues[NodeMaterialSystemValues["CameraParameters"] = 10] = "CameraParameters"; - /** Material alpha */ - NodeMaterialSystemValues[NodeMaterialSystemValues["MaterialAlpha"] = 11] = "MaterialAlpha"; -})(NodeMaterialSystemValues || (NodeMaterialSystemValues = {})); -//# sourceMappingURL=nodeMaterialSystemValues.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.vertexFormat.js - -/** - * Contains position and normal vectors for a vertex - */ -class PositionNormalVertex { - /** - * Creates a PositionNormalVertex - * @param position the position of the vertex (defaut: 0,0,0) - * @param normal the normal of the vertex (defaut: 0,1,0) - */ - constructor( - /** the position of the vertex (defaut: 0,0,0) */ - position = Vector3.Zero(), - /** the normal of the vertex (defaut: 0,1,0) */ - normal = Vector3.Up()) { - this.position = position; - this.normal = normal; - } - /** - * Clones the PositionNormalVertex - * @returns the cloned PositionNormalVertex - */ - clone() { - return new PositionNormalVertex(this.position.clone(), this.normal.clone()); - } -} -/** - * Contains position, normal and uv vectors for a vertex - */ -class PositionNormalTextureVertex { - /** - * Creates a PositionNormalTextureVertex - * @param position the position of the vertex (defaut: 0,0,0) - * @param normal the normal of the vertex (defaut: 0,1,0) - * @param uv the uv of the vertex (default: 0,0) - */ - constructor( - /** the position of the vertex (defaut: 0,0,0) */ - position = Vector3.Zero(), - /** the normal of the vertex (defaut: 0,1,0) */ - normal = Vector3.Up(), - /** the uv of the vertex (default: 0,0) */ - uv = Vector2.Zero()) { - this.position = position; - this.normal = normal; - this.uv = uv; - } - /** - * Clones the PositionNormalTextureVertex - * @returns the cloned PositionNormalTextureVertex - */ - clone() { - return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone()); - } -} -//# sourceMappingURL=math.vertexFormat.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.js - - - - - - - - - - -//# sourceMappingURL=math.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Input/animatedInputBlockTypes.js -/** - * Enum defining the type of animations supported by InputBlock - */ -var AnimatedInputBlockTypes; -(function (AnimatedInputBlockTypes) { - /** No animation */ - AnimatedInputBlockTypes[AnimatedInputBlockTypes["None"] = 0] = "None"; - /** Time based animation (is incremented by 0.6 each second). Will only work for floats */ - AnimatedInputBlockTypes[AnimatedInputBlockTypes["Time"] = 1] = "Time"; - /** Time elapsed (in seconds) since the engine was initialized. Will only work for floats */ - AnimatedInputBlockTypes[AnimatedInputBlockTypes["RealTime"] = 2] = "RealTime"; -})(AnimatedInputBlockTypes || (AnimatedInputBlockTypes = {})); -//# sourceMappingURL=animatedInputBlockTypes.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Input/inputBlock.js -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - - - - -const remapAttributeName = { - position2d: "position", - particle_uv: "vUV", - particle_color: "vColor", - particle_texturemask: "textureMask", - particle_positionw: "vPositionW", -}; -const attributeInFragmentOnly = { - particle_uv: true, - particle_color: true, - particle_texturemask: true, - particle_positionw: true, -}; -const attributeAsUniform = { - particle_texturemask: true, -}; -/** - * Block used to expose an input value - */ -class InputBlock extends NodeMaterialBlock { - /** - * Gets or sets the connection point type (default is float) - */ - get type() { - if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) { - if (this.isUniform && this.value != null) { - if (!isNaN(this.value)) { - this._type = NodeMaterialBlockConnectionPointTypes.Float; - return this._type; - } - switch (this.value.getClassName()) { - case "Vector2": - this._type = NodeMaterialBlockConnectionPointTypes.Vector2; - return this._type; - case "Vector3": - this._type = NodeMaterialBlockConnectionPointTypes.Vector3; - return this._type; - case "Vector4": - this._type = NodeMaterialBlockConnectionPointTypes.Vector4; - return this._type; - case "Color3": - this._type = NodeMaterialBlockConnectionPointTypes.Color3; - return this._type; - case "Color4": - this._type = NodeMaterialBlockConnectionPointTypes.Color4; - return this._type; - case "Matrix": - this._type = NodeMaterialBlockConnectionPointTypes.Matrix; - return this._type; - } - } - if (this.isAttribute) { - switch (this.name) { - case "position": - case "normal": - case "particle_positionw": - this._type = NodeMaterialBlockConnectionPointTypes.Vector3; - return this._type; - case "uv": - case "uv2": - case "uv3": - case "uv4": - case "uv5": - case "uv6": - case "position2d": - case "particle_uv": - this._type = NodeMaterialBlockConnectionPointTypes.Vector2; - return this._type; - case "matricesIndices": - case "matricesWeights": - case "matricesIndicesExtra": - case "matricesWeightsExtra": - case "world0": - case "world1": - case "world2": - case "world3": - case "tangent": - this._type = NodeMaterialBlockConnectionPointTypes.Vector4; - return this._type; - case "color": - case "instanceColor": - case "particle_color": - case "particle_texturemask": - this._type = NodeMaterialBlockConnectionPointTypes.Color4; - return this._type; - } - } - if (this.isSystemValue) { - switch (this._systemValue) { - case NodeMaterialSystemValues.World: - case NodeMaterialSystemValues.WorldView: - case NodeMaterialSystemValues.WorldViewProjection: - case NodeMaterialSystemValues.View: - case NodeMaterialSystemValues.ViewProjection: - case NodeMaterialSystemValues.Projection: - this._type = NodeMaterialBlockConnectionPointTypes.Matrix; - return this._type; - case NodeMaterialSystemValues.CameraPosition: - this._type = NodeMaterialBlockConnectionPointTypes.Vector3; - return this._type; - case NodeMaterialSystemValues.FogColor: - this._type = NodeMaterialBlockConnectionPointTypes.Color3; - return this._type; - case NodeMaterialSystemValues.DeltaTime: - case NodeMaterialSystemValues.MaterialAlpha: - this._type = NodeMaterialBlockConnectionPointTypes.Float; - return this._type; - case NodeMaterialSystemValues.CameraParameters: - this._type = NodeMaterialBlockConnectionPointTypes.Vector4; - return this._type; - } - } - } - return this._type; - } - /** - * Creates a new InputBlock - * @param name defines the block name - * @param target defines the target of that block (Vertex by default) - * @param type defines the type of the input (can be set to NodeMaterialBlockConnectionPointTypes.AutoDetect) - */ - constructor(name, target = NodeMaterialBlockTargets.Vertex, type = NodeMaterialBlockConnectionPointTypes.AutoDetect) { - super(name, target, false); - this._mode = NodeMaterialBlockConnectionPointMode.Undefined; - this._animationType = AnimatedInputBlockTypes.None; - /** Gets or set a value used to limit the range of float values */ - this.min = 0; - /** Gets or set a value used to limit the range of float values */ - this.max = 0; - /** Gets or set a value indicating that this input can only get 0 and 1 values */ - this.isBoolean = false; - /** Gets or sets a value used by the Node Material editor to determine how to configure the current value if it is a matrix */ - this.matrixMode = 0; - /** @internal */ - this._systemValue = null; - /** Gets or sets a boolean indicating that the value of this input will not change after a build */ - this.isConstant = false; - /** Gets or sets the group to use to display this block in the Inspector */ - this.groupInInspector = ""; - /** Gets an observable raised when the value is changed */ - this.onValueChangedObservable = new observable_Observable(); - /** Gets or sets a boolean indicating if content needs to be converted to gamma space (for color3/4 only) */ - this.convertToGammaSpace = false; - /** Gets or sets a boolean indicating if content needs to be converted to linear space (for color3/4 only) */ - this.convertToLinearSpace = false; - this._type = type; - this.setDefaultValue(); - this.registerOutput("output", type); - } - /** - * Validates if a name is a reserve word. - * @param newName the new name to be given to the node. - * @returns false if the name is a reserve word, else true. - */ - validateBlockName(newName) { - if (!this.isAttribute) { - return super.validateBlockName(newName); - } - return true; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Set the source of this connection point to a vertex attribute - * @param attributeName defines the attribute name (position, uv, normal, etc...). If not specified it will take the connection point name - * @returns the current connection point - */ - setAsAttribute(attributeName) { - this._mode = NodeMaterialBlockConnectionPointMode.Attribute; - if (attributeName) { - this.name = attributeName; - } - return this; - } - /** - * Set the source of this connection point to a system value - * @param value define the system value to use (world, view, etc...) or null to switch to manual value - * @returns the current connection point - */ - setAsSystemValue(value) { - this.systemValue = value; - return this; - } - /** - * Gets or sets the value of that point. - * Please note that this value will be ignored if valueCallback is defined - */ - get value() { - return this._storedValue; - } - set value(value) { - if (this.type === NodeMaterialBlockConnectionPointTypes.Float) { - if (this.isBoolean) { - value = value ? 1 : 0; - } - else if (this.min !== this.max) { - value = Math.max(this.min, value); - value = Math.min(this.max, value); - } - } - this._storedValue = value; - this._mode = NodeMaterialBlockConnectionPointMode.Uniform; - this.onValueChangedObservable.notifyObservers(this); - } - /** - * Gets or sets a callback used to get the value of that point. - * Please note that setting this value will force the connection point to ignore the value property - */ - get valueCallback() { - return this._valueCallback; - } - set valueCallback(value) { - this._valueCallback = value; - this._mode = NodeMaterialBlockConnectionPointMode.Uniform; - } - /** - * Gets or sets the associated variable name in the shader - */ - get associatedVariableName() { - return this._associatedVariableName; - } - set associatedVariableName(value) { - this._associatedVariableName = value; - } - /** Gets or sets the type of animation applied to the input */ - get animationType() { - return this._animationType; - } - set animationType(value) { - this._animationType = value; - } - /** - * Gets a boolean indicating that this connection point not defined yet - */ - get isUndefined() { - return this._mode === NodeMaterialBlockConnectionPointMode.Undefined; - } - /** - * Gets or sets a boolean indicating that this connection point is coming from an uniform. - * In this case the connection point name must be the name of the uniform to use. - * Can only be set on inputs - */ - get isUniform() { - return this._mode === NodeMaterialBlockConnectionPointMode.Uniform; - } - set isUniform(value) { - this._mode = value ? NodeMaterialBlockConnectionPointMode.Uniform : NodeMaterialBlockConnectionPointMode.Undefined; - this.associatedVariableName = ""; - } - /** - * Gets or sets a boolean indicating that this connection point is coming from an attribute. - * In this case the connection point name must be the name of the attribute to use - * Can only be set on inputs - */ - get isAttribute() { - return this._mode === NodeMaterialBlockConnectionPointMode.Attribute; - } - set isAttribute(value) { - this._mode = value ? NodeMaterialBlockConnectionPointMode.Attribute : NodeMaterialBlockConnectionPointMode.Undefined; - this.associatedVariableName = ""; - } - /** - * Gets or sets a boolean indicating that this connection point is generating a varying variable. - * Can only be set on exit points - */ - get isVarying() { - return this._mode === NodeMaterialBlockConnectionPointMode.Varying; - } - set isVarying(value) { - this._mode = value ? NodeMaterialBlockConnectionPointMode.Varying : NodeMaterialBlockConnectionPointMode.Undefined; - this.associatedVariableName = ""; - } - /** - * Gets a boolean indicating that the current connection point is a system value - */ - get isSystemValue() { - return this._systemValue != null; - } - /** - * Gets or sets the current well known value or null if not defined as a system value - */ - get systemValue() { - return this._systemValue; - } - set systemValue(value) { - this._mode = NodeMaterialBlockConnectionPointMode.Uniform; - this.associatedVariableName = ""; - this._systemValue = value; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "InputBlock"; - } - /** - * Animate the input if animationType !== None - * @param scene defines the rendering scene - */ - animate(scene) { - switch (this._animationType) { - case AnimatedInputBlockTypes.Time: { - if (this.type === NodeMaterialBlockConnectionPointTypes.Float) { - this.value += scene.getAnimationRatio() * 0.01; - } - break; - } - case AnimatedInputBlockTypes.RealTime: { - if (this.type === NodeMaterialBlockConnectionPointTypes.Float) { - this.value = (precisionDate_PrecisionDate.Now - scene.getEngine().startTime) / 1000; - } - break; - } - } - } - _emitDefine(define) { - if (define[0] === "!") { - return `#ifndef ${define.substring(1)}\n`; - } - return `#ifdef ${define}\n`; - } - initialize() { - this.associatedVariableName = ""; - } - /** - * Set the input block to its default value (based on its type) - */ - setDefaultValue() { - switch (this.type) { - case NodeMaterialBlockConnectionPointTypes.Float: - this.value = 0; - break; - case NodeMaterialBlockConnectionPointTypes.Vector2: - this.value = math_vector_Vector2.Zero(); - break; - case NodeMaterialBlockConnectionPointTypes.Vector3: - this.value = math_vector_Vector3.Zero(); - break; - case NodeMaterialBlockConnectionPointTypes.Vector4: - this.value = math_vector_Vector4.Zero(); - break; - case NodeMaterialBlockConnectionPointTypes.Color3: - this.value = math_color_Color3.White(); - break; - case NodeMaterialBlockConnectionPointTypes.Color4: - this.value = new math_color_Color4(1, 1, 1, 1); - break; - case NodeMaterialBlockConnectionPointTypes.Matrix: - this.value = math_vector_Matrix.Identity(); - break; - } - } - _emitConstant(state) { - switch (this.type) { - case NodeMaterialBlockConnectionPointTypes.Float: - return `${state._emitFloat(this.value)}`; - case NodeMaterialBlockConnectionPointTypes.Vector2: - return `vec2(${this.value.x}, ${this.value.y})`; - case NodeMaterialBlockConnectionPointTypes.Vector3: - return `vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`; - case NodeMaterialBlockConnectionPointTypes.Vector4: - return `vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`; - case NodeMaterialBlockConnectionPointTypes.Color3: - TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b); - if (this.convertToGammaSpace) { - TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0], state.sharedData.scene.getEngine().useExactSrgbConversions); - } - if (this.convertToLinearSpace) { - TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0], state.sharedData.scene.getEngine().useExactSrgbConversions); - } - return `vec3(${TmpColors.Color3[0].r}, ${TmpColors.Color3[0].g}, ${TmpColors.Color3[0].b})`; - case NodeMaterialBlockConnectionPointTypes.Color4: - TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a); - if (this.convertToGammaSpace) { - TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0], state.sharedData.scene.getEngine().useExactSrgbConversions); - } - if (this.convertToLinearSpace) { - TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0], state.sharedData.scene.getEngine().useExactSrgbConversions); - } - return `vec4(${TmpColors.Color4[0].r}, ${TmpColors.Color4[0].g}, ${TmpColors.Color4[0].b}, ${TmpColors.Color4[0].a})`; - } - return ""; - } - /** @internal */ - get _noContextSwitch() { - return attributeInFragmentOnly[this.name]; - } - _emit(state, define) { - var _a; - // Uniforms - if (this.isUniform) { - if (!this.associatedVariableName) { - this.associatedVariableName = state._getFreeVariableName("u_" + this.name); - } - if (this.isConstant) { - if (state.constants.indexOf(this.associatedVariableName) !== -1) { - return; - } - state.constants.push(this.associatedVariableName); - state._constantDeclaration += this._declareOutput(this.output, state) + ` = ${this._emitConstant(state)};\n`; - return; - } - if (state.uniforms.indexOf(this.associatedVariableName) !== -1) { - return; - } - state.uniforms.push(this.associatedVariableName); - if (define) { - state._uniformDeclaration += this._emitDefine(define); - } - state._uniformDeclaration += `uniform ${state._getGLType(this.type)} ${this.associatedVariableName};\n`; - if (define) { - state._uniformDeclaration += `#endif\n`; - } - // well known - const hints = state.sharedData.hints; - if (this._systemValue !== null && this._systemValue !== undefined) { - switch (this._systemValue) { - case NodeMaterialSystemValues.WorldView: - hints.needWorldViewMatrix = true; - break; - case NodeMaterialSystemValues.WorldViewProjection: - hints.needWorldViewProjectionMatrix = true; - break; - } - } - else { - if (this._animationType !== AnimatedInputBlockTypes.None) { - state.sharedData.animatedInputs.push(this); - } - } - return; - } - // Attribute - if (this.isAttribute) { - this.associatedVariableName = (_a = remapAttributeName[this.name]) !== null && _a !== void 0 ? _a : this.name; - if (this.target === NodeMaterialBlockTargets.Vertex && state._vertexState) { - // Attribute for fragment need to be carried over by varyings - if (attributeInFragmentOnly[this.name]) { - if (attributeAsUniform[this.name]) { - state._emitUniformFromString(this.associatedVariableName, state._getGLType(this.type), define); - } - else { - state._emitVaryingFromString(this.associatedVariableName, state._getGLType(this.type), define); - } - } - else { - this._emit(state._vertexState, define); - } - return; - } - if (state.attributes.indexOf(this.associatedVariableName) !== -1) { - return; - } - state.attributes.push(this.associatedVariableName); - if (attributeInFragmentOnly[this.name]) { - if (attributeAsUniform[this.name]) { - state._emitUniformFromString(this.associatedVariableName, state._getGLType(this.type), define); - } - else { - state._emitVaryingFromString(this.associatedVariableName, state._getGLType(this.type), define); - } - } - else { - if (define) { - state._attributeDeclaration += this._emitDefine(define); - } - state._attributeDeclaration += `attribute ${state._getGLType(this.type)} ${this.associatedVariableName};\n`; - if (define) { - state._attributeDeclaration += `#endif\n`; - } - } - } - } - /** - * @internal - */ - _transmitWorld(effect, world, worldView, worldViewProjection) { - if (!this._systemValue) { - return; - } - const variableName = this.associatedVariableName; - switch (this._systemValue) { - case NodeMaterialSystemValues.World: - effect.setMatrix(variableName, world); - break; - case NodeMaterialSystemValues.WorldView: - effect.setMatrix(variableName, worldView); - break; - case NodeMaterialSystemValues.WorldViewProjection: - effect.setMatrix(variableName, worldViewProjection); - break; - } - } - /** - * @internal - */ - _transmit(effect, scene, material) { - if (this.isAttribute) { - return; - } - const variableName = this.associatedVariableName; - if (this._systemValue) { - switch (this._systemValue) { - case NodeMaterialSystemValues.World: - case NodeMaterialSystemValues.WorldView: - case NodeMaterialSystemValues.WorldViewProjection: - return; - case NodeMaterialSystemValues.View: - effect.setMatrix(variableName, scene.getViewMatrix()); - break; - case NodeMaterialSystemValues.Projection: - effect.setMatrix(variableName, scene.getProjectionMatrix()); - break; - case NodeMaterialSystemValues.ViewProjection: - effect.setMatrix(variableName, scene.getTransformMatrix()); - break; - case NodeMaterialSystemValues.CameraPosition: - scene.bindEyePosition(effect, variableName, true); - break; - case NodeMaterialSystemValues.FogColor: - effect.setColor3(variableName, scene.fogColor); - break; - case NodeMaterialSystemValues.DeltaTime: - effect.setFloat(variableName, scene.deltaTime / 1000.0); - break; - case NodeMaterialSystemValues.CameraParameters: - if (scene.activeCamera) { - effect.setFloat4(variableName, scene.getEngine().hasOriginBottomLeft ? -1 : 1, scene.activeCamera.minZ, scene.activeCamera.maxZ, 1 / scene.activeCamera.maxZ); - } - break; - case NodeMaterialSystemValues.MaterialAlpha: - effect.setFloat(variableName, material.alpha); - break; - } - return; - } - const value = this._valueCallback ? this._valueCallback() : this._storedValue; - if (value === null) { - return; - } - switch (this.type) { - case NodeMaterialBlockConnectionPointTypes.Float: - effect.setFloat(variableName, value); - break; - case NodeMaterialBlockConnectionPointTypes.Int: - effect.setInt(variableName, value); - break; - case NodeMaterialBlockConnectionPointTypes.Color3: - TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b); - if (this.convertToGammaSpace) { - TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0], scene.getEngine().useExactSrgbConversions); - } - if (this.convertToLinearSpace) { - TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0], scene.getEngine().useExactSrgbConversions); - } - effect.setColor3(variableName, TmpColors.Color3[0]); - break; - case NodeMaterialBlockConnectionPointTypes.Color4: - TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a); - if (this.convertToGammaSpace) { - TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0], scene.getEngine().useExactSrgbConversions); - } - if (this.convertToLinearSpace) { - TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0], scene.getEngine().useExactSrgbConversions); - } - effect.setDirectColor4(variableName, TmpColors.Color4[0]); - break; - case NodeMaterialBlockConnectionPointTypes.Vector2: - effect.setVector2(variableName, value); - break; - case NodeMaterialBlockConnectionPointTypes.Vector3: - effect.setVector3(variableName, value); - break; - case NodeMaterialBlockConnectionPointTypes.Vector4: - effect.setVector4(variableName, value); - break; - case NodeMaterialBlockConnectionPointTypes.Matrix: - effect.setMatrix(variableName, value); - break; - } - } - _buildBlock(state) { - super._buildBlock(state); - if (this.isUniform || this.isSystemValue) { - state.sharedData.inputBlocks.push(this); - } - this._emit(state); - } - _dumpPropertiesCode() { - const variableName = this._codeVariableName; - if (this.isAttribute) { - return super._dumpPropertiesCode() + `${variableName}.setAsAttribute("${this.name}");\n`; - } - if (this.isSystemValue) { - return super._dumpPropertiesCode() + `${variableName}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${NodeMaterialSystemValues[this._systemValue]});\n`; - } - if (this.isUniform) { - const codes = []; - let valueString = ""; - switch (this.type) { - case NodeMaterialBlockConnectionPointTypes.Float: - valueString = `${this.value}`; - break; - case NodeMaterialBlockConnectionPointTypes.Vector2: - valueString = `new BABYLON.Vector2(${this.value.x}, ${this.value.y})`; - break; - case NodeMaterialBlockConnectionPointTypes.Vector3: - valueString = `new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`; - break; - case NodeMaterialBlockConnectionPointTypes.Vector4: - valueString = `new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`; - break; - case NodeMaterialBlockConnectionPointTypes.Color3: - valueString = `new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`; - if (this.convertToGammaSpace) { - valueString += ".toGammaSpace()"; - } - if (this.convertToLinearSpace) { - valueString += ".toLinearSpace()"; - } - break; - case NodeMaterialBlockConnectionPointTypes.Color4: - valueString = `new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`; - if (this.convertToGammaSpace) { - valueString += ".toGammaSpace()"; - } - if (this.convertToLinearSpace) { - valueString += ".toLinearSpace()"; - } - break; - case NodeMaterialBlockConnectionPointTypes.Matrix: - valueString = `BABYLON.Matrix.FromArray([${this.value.m}])`; - break; - } - // Common Property "Value" - codes.push(`${variableName}.value = ${valueString}`); - // Float-Value-Specific Properties - if (this.type === NodeMaterialBlockConnectionPointTypes.Float) { - 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]}`); - } - // Common Property "Type" - codes.push(`${variableName}.isConstant = ${this.isConstant}`); - codes.push(""); - return super._dumpPropertiesCode() + codes.join(";\n"); - } - return super._dumpPropertiesCode(); - } - dispose() { - this.onValueChangedObservable.clear(); - super.dispose(); - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.type = this.type; - serializationObject.mode = this._mode; - serializationObject.systemValue = this._systemValue; - serializationObject.animationType = this._animationType; - serializationObject.min = this.min; - serializationObject.max = this.max; - serializationObject.isBoolean = this.isBoolean; - serializationObject.matrixMode = this.matrixMode; - serializationObject.isConstant = this.isConstant; - serializationObject.groupInInspector = this.groupInInspector; - serializationObject.convertToGammaSpace = this.convertToGammaSpace; - serializationObject.convertToLinearSpace = this.convertToLinearSpace; - if (this._storedValue != null && this._mode === NodeMaterialBlockConnectionPointMode.Uniform) { - if (this._storedValue.asArray) { - serializationObject.valueType = "BABYLON." + this._storedValue.getClassName(); - serializationObject.value = this._storedValue.asArray(); - } - else { - serializationObject.valueType = "number"; - serializationObject.value = this._storedValue; - } - } - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - this._mode = serializationObject.mode; - super._deserialize(serializationObject, scene, rootUrl); - this._type = serializationObject.type; - this._systemValue = serializationObject.systemValue || serializationObject.wellKnownValue; - this._animationType = serializationObject.animationType; - this.min = serializationObject.min || 0; - this.max = serializationObject.max || 0; - this.isBoolean = !!serializationObject.isBoolean; - this.matrixMode = serializationObject.matrixMode || 0; - this.isConstant = !!serializationObject.isConstant; - this.groupInInspector = serializationObject.groupInInspector || ""; - this.convertToGammaSpace = !!serializationObject.convertToGammaSpace; - this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; - // Tangents back compat - if (serializationObject.name === "tangent" && - serializationObject.mode === NodeMaterialBlockConnectionPointMode.Attribute && - serializationObject.type === NodeMaterialBlockConnectionPointTypes.Vector3) { - this._type = NodeMaterialBlockConnectionPointTypes.Vector4; - } - if (!serializationObject.valueType) { - return; - } - if (serializationObject.valueType === "number") { - this._storedValue = serializationObject.value; - } - else { - const valueType = GetClass(serializationObject.valueType); - if (valueType) { - this._storedValue = valueType.FromArray(serializationObject.value); - } - } - } -} -RegisterClass("BABYLON.InputBlock", InputBlock); -//# sourceMappingURL=inputBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/currentScreenBlock.js - - - - - -/** - * Base block used as input for post process - */ -class CurrentScreenBlock extends NodeMaterialBlock { - /** - * Create a new CurrentScreenBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.VertexAndFragment); - this._samplerName = "textureSampler"; - /** - * Gets or sets a boolean indicating if content needs to be converted to gamma space - */ - this.convertToGammaSpace = false; - /** - * Gets or sets a boolean indicating if content needs to be converted to linear space - */ - this.convertToLinearSpace = false; - this._isUnique = false; - this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment); - this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral); - this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral); - this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - this._inputs[0]._prioritizeVertex = false; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "CurrentScreenBlock"; - } - /** - * Gets the uv input component - */ - get uv() { - return this._inputs[0]; - } - /** - * Gets the rgba output component - */ - get rgba() { - return this._outputs[0]; - } - /** - * Gets the rgb output component - */ - get rgb() { - return this._outputs[1]; - } - /** - * Gets the r output component - */ - get r() { - return this._outputs[2]; - } - /** - * Gets the g output component - */ - get g() { - return this._outputs[3]; - } - /** - * Gets the b output component - */ - get b() { - return this._outputs[4]; - } - /** - * Gets the a output component - */ - get a() { - return this._outputs[5]; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("textureSampler"); - } - get target() { - if (!this.uv.isConnected) { - return NodeMaterialBlockTargets.VertexAndFragment; - } - if (this.uv.sourceBlock.isInput) { - return NodeMaterialBlockTargets.VertexAndFragment; - } - return NodeMaterialBlockTargets.Fragment; - } - prepareDefines(mesh, nodeMaterial, defines) { - defines.setValue(this._linearDefineName, this.convertToGammaSpace, true); - defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true); - } - isReady() { - if (this.texture && !this.texture.isReadyOrNotBlocking()) { - return false; - } - return true; - } - _injectVertexCode(state) { - const uvInput = this.uv; - if (uvInput.connectedPoint.ownerBlock.isInput) { - const uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock; - if (!uvInputOwnerBlock.isAttribute) { - state._emitUniformFromString(uvInput.associatedVariableName, "vec2"); - } - } - this._mainUVName = "vMain" + uvInput.associatedVariableName; - state._emitVaryingFromString(this._mainUVName, "vec2"); - state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\n`; - if (!this._outputs.some((o) => o.isConnectedInVertexShader)) { - return; - } - this._writeTextureRead(state, true); - for (const output of this._outputs) { - if (output.hasEndpoints) { - this._writeOutput(state, output, output.name, true); - } - } - } - _writeTextureRead(state, vertexMode = false) { - const uvInput = this.uv; - if (vertexMode) { - if (state.target === NodeMaterialBlockTargets.Fragment) { - return; - } - state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName});\n`; - return; - } - if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { - state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName});\n`; - return; - } - state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`; - } - _writeOutput(state, output, swizzle, vertexMode = false) { - if (vertexMode) { - if (state.target === NodeMaterialBlockTargets.Fragment) { - return; - } - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\n`; - return; - } - if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\n`; - return; - } - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\n`; - state.compilationString += `#ifdef ${this._linearDefineName}\n`; - state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\n`; - state.compilationString += `#endif\n`; - state.compilationString += `#ifdef ${this._gammaDefineName}\n`; - state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\n`; - state.compilationString += `#endif\n`; - } - _buildBlock(state) { - super._buildBlock(state); - this._tempTextureRead = state._getFreeVariableName("tempTextureRead"); - if (state.sharedData.blockingBlocks.indexOf(this) < 0) { - state.sharedData.blockingBlocks.push(this); - } - if (state.sharedData.textureBlocks.indexOf(this) < 0) { - state.sharedData.textureBlocks.push(this); - } - if (state.sharedData.blocksWithDefines.indexOf(this) < 0) { - state.sharedData.blocksWithDefines.push(this); - } - if (state.target !== NodeMaterialBlockTargets.Fragment) { - // Vertex - state._emit2DSampler(this._samplerName); - this._injectVertexCode(state); - return; - } - // Fragment - if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) { - return; - } - state._emit2DSampler(this._samplerName); - this._linearDefineName = state._getFreeDefineName("ISLINEAR"); - this._gammaDefineName = state._getFreeDefineName("ISGAMMA"); - const comments = `//${this.name}`; - state._emitFunctionFromInclude("helperFunctions", comments); - this._writeTextureRead(state); - for (const output of this._outputs) { - if (output.hasEndpoints) { - this._writeOutput(state, output, output.name); - } - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.convertToGammaSpace = this.convertToGammaSpace; - serializationObject.convertToLinearSpace = this.convertToLinearSpace; - if (this.texture && !this.texture.isRenderTarget) { - serializationObject.texture = this.texture.serialize(); - } - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.convertToGammaSpace = serializationObject.convertToGammaSpace; - this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; - if (serializationObject.texture) { - rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; - this.texture = texture_Texture.Parse(serializationObject.texture, scene, rootUrl); - } - } -} -RegisterClass("BABYLON.CurrentScreenBlock", CurrentScreenBlock); -//# sourceMappingURL=currentScreenBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleTextureBlock.js - - - - - - -/** - * Base block used for the particle texture - */ -class ParticleTextureBlock extends NodeMaterialBlock { - /** - * Create a new ParticleTextureBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this._samplerName = "diffuseSampler"; - /** - * Gets or sets a boolean indicating if content needs to be converted to gamma space - */ - this.convertToGammaSpace = false; - /** - * Gets or sets a boolean indicating if content needs to be converted to linear space - */ - this.convertToLinearSpace = false; - this._isUnique = false; - this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment); - this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral); - this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral); - this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ParticleTextureBlock"; - } - /** - * Gets the uv input component - */ - get uv() { - return this._inputs[0]; - } - /** - * Gets the rgba output component - */ - get rgba() { - return this._outputs[0]; - } - /** - * Gets the rgb output component - */ - get rgb() { - return this._outputs[1]; - } - /** - * Gets the r output component - */ - get r() { - return this._outputs[2]; - } - /** - * Gets the g output component - */ - get g() { - return this._outputs[3]; - } - /** - * Gets the b output component - */ - get b() { - return this._outputs[4]; - } - /** - * Gets the a output component - */ - get a() { - return this._outputs[5]; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("diffuseSampler"); - } - autoConfigure(material) { - if (!this.uv.isConnected) { - let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "particle_uv"); - if (!uvInput) { - uvInput = new InputBlock("uv"); - uvInput.setAsAttribute("particle_uv"); - } - uvInput.output.connectTo(this.uv); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - defines.setValue(this._linearDefineName, this.convertToGammaSpace, true); - defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true); - } - isReady() { - if (this.texture && !this.texture.isReadyOrNotBlocking()) { - return false; - } - return true; - } - _writeOutput(state, output, swizzle) { - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\n`; - state.compilationString += `#ifdef ${this._linearDefineName}\n`; - state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\n`; - state.compilationString += `#endif\n`; - state.compilationString += `#ifdef ${this._gammaDefineName}\n`; - state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\n`; - state.compilationString += `#endif\n`; - } - _buildBlock(state) { - super._buildBlock(state); - if (state.target === NodeMaterialBlockTargets.Vertex) { - return; - } - this._tempTextureRead = state._getFreeVariableName("tempTextureRead"); - state._emit2DSampler(this._samplerName); - state.sharedData.blockingBlocks.push(this); - state.sharedData.textureBlocks.push(this); - state.sharedData.blocksWithDefines.push(this); - this._linearDefineName = state._getFreeDefineName("ISLINEAR"); - this._gammaDefineName = state._getFreeDefineName("ISGAMMA"); - const comments = `//${this.name}`; - state._emitFunctionFromInclude("helperFunctions", comments); - state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\n`; - for (const output of this._outputs) { - if (output.hasEndpoints) { - this._writeOutput(state, output, output.name); - } - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.convertToGammaSpace = this.convertToGammaSpace; - serializationObject.convertToLinearSpace = this.convertToLinearSpace; - if (this.texture && !this.texture.isRenderTarget) { - serializationObject.texture = this.texture.serialize(); - } - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.convertToGammaSpace = serializationObject.convertToGammaSpace; - this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; - if (serializationObject.texture) { - rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; - this.texture = texture_Texture.Parse(serializationObject.texture, scene, rootUrl); - } - } -} -RegisterClass("BABYLON.ParticleTextureBlock", ParticleTextureBlock); -//# sourceMappingURL=particleTextureBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleRampGradientBlock.js - - - - -/** - * Block used for the particle ramp gradient section - */ -class ParticleRampGradientBlock extends NodeMaterialBlock { - /** - * Create a new ParticleRampGradientBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this._isUnique = true; - this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment); - this.registerOutput("rampColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ParticleRampGradientBlock"; - } - /** - * Gets the color input component - */ - get color() { - return this._inputs[0]; - } - /** - * Gets the rampColor output component - */ - get rampColor() { - return this._outputs[0]; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("remapRanges"); - state._excludeVariableName("rampSampler"); - state._excludeVariableName("baseColor"); - state._excludeVariableName("alpha"); - state._excludeVariableName("remappedColorIndex"); - state._excludeVariableName("rampColor"); - state._excludeVariableName("finalAlpha"); - } - _buildBlock(state) { - super._buildBlock(state); - if (state.target === NodeMaterialBlockTargets.Vertex) { - return; - } - state._emit2DSampler("rampSampler"); - state._emitVaryingFromString("remapRanges", "vec4", "RAMPGRADIENT"); - state.compilationString += ` - #ifdef RAMPGRADIENT - vec4 baseColor = ${this.color.associatedVariableName}; - float alpha = ${this.color.associatedVariableName}.a; - - float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); - - vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.)); - baseColor.rgb *= rampColor.rgb; - - // Remapped alpha - float finalAlpha = baseColor.a; - baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0); - - ${this._declareOutput(this.rampColor, state)} = baseColor; - #else - ${this._declareOutput(this.rampColor, state)} = ${this.color.associatedVariableName}; - #endif - `; - return this; - } -} -RegisterClass("BABYLON.ParticleRampGradientBlock", ParticleRampGradientBlock); -//# sourceMappingURL=particleRampGradientBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleBlendMultiplyBlock.js - - - - -/** - * Block used for the particle blend multiply section - */ -class ParticleBlendMultiplyBlock extends NodeMaterialBlock { - /** - * Create a new ParticleBlendMultiplyBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this._isUnique = true; - this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("alphaTexture", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("alphaColor", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); - this.registerOutput("blendColor", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ParticleBlendMultiplyBlock"; - } - /** - * Gets the color input component - */ - get color() { - return this._inputs[0]; - } - /** - * Gets the alphaTexture input component - */ - get alphaTexture() { - return this._inputs[1]; - } - /** - * Gets the alphaColor input component - */ - get alphaColor() { - return this._inputs[2]; - } - /** - * Gets the blendColor output component - */ - get blendColor() { - return this._outputs[0]; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("sourceAlpha"); - } - _buildBlock(state) { - super._buildBlock(state); - if (state.target === NodeMaterialBlockTargets.Vertex) { - return; - } - state.compilationString += ` - #ifdef BLENDMULTIPLYMODE - ${this._declareOutput(this.blendColor, state)}; - float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; - ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha); - ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a; - #else - ${this._declareOutput(this.blendColor, state)} = ${this.color.associatedVariableName}; - #endif - `; - return this; - } -} -RegisterClass("BABYLON.ParticleBlendMultiplyBlock", ParticleBlendMultiplyBlock); -//# sourceMappingURL=particleBlendMultiplyBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/effectFallbacks.js -/** - * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance. - * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog) - */ -class EffectFallbacks { - constructor() { - this._defines = {}; - this._currentRank = 32; - this._maxRank = -1; - this._mesh = null; - } - /** - * Removes the fallback from the bound mesh. - */ - unBindMesh() { - this._mesh = null; - } - /** - * Adds a fallback on the specified property. - * @param rank The rank of the fallback (Lower ranks will be fallbacked to first) - * @param define The name of the define in the shader - */ - addFallback(rank, define) { - if (!this._defines[rank]) { - if (rank < this._currentRank) { - this._currentRank = rank; - } - if (rank > this._maxRank) { - this._maxRank = rank; - } - this._defines[rank] = new Array(); - } - this._defines[rank].push(define); - } - /** - * Sets the mesh to use CPU skinning when needing to fallback. - * @param rank The rank of the fallback (Lower ranks will be fallbacked to first) - * @param mesh The mesh to use the fallbacks. - */ - addCPUSkinningFallback(rank, mesh) { - this._mesh = mesh; - if (rank < this._currentRank) { - this._currentRank = rank; - } - if (rank > this._maxRank) { - this._maxRank = rank; - } - } - /** - * Checks to see if more fallbacks are still available. - */ - get hasMoreFallbacks() { - return this._currentRank <= this._maxRank; - } - /** - * Removes the defines that should be removed when falling back. - * @param currentDefines defines the current define statements for the shader. - * @param effect defines the current effect we try to compile - * @returns The resulting defines with defines of the current rank removed. - */ - reduce(currentDefines, effect) { - // First we try to switch to CPU skinning - if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) { - this._mesh.computeBonesUsingShaders = false; - currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0"); - effect._bonesComputationForcedToCPU = true; - const scene = this._mesh.getScene(); - for (let index = 0; index < scene.meshes.length; index++) { - const otherMesh = scene.meshes[index]; - if (!otherMesh.material) { - if (!this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) { - otherMesh.computeBonesUsingShaders = false; - } - continue; - } - if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) { - continue; - } - if (otherMesh.material.getEffect() === effect) { - otherMesh.computeBonesUsingShaders = false; - } - else if (otherMesh.subMeshes) { - for (const subMesh of otherMesh.subMeshes) { - const subMeshEffect = subMesh.effect; - if (subMeshEffect === effect) { - otherMesh.computeBonesUsingShaders = false; - break; - } - } - } - } - } - else { - const currentFallbacks = this._defines[this._currentRank]; - if (currentFallbacks) { - for (let index = 0; index < currentFallbacks.length; index++) { - currentDefines = currentDefines.replace("#define " + currentFallbacks[index], ""); - } - } - this._currentRank++; - } - return currentDefines; - } -} -//# sourceMappingURL=effectFallbacks.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/postprocess.vertex.js -// Do not edit. - -const postprocess_vertex_name = "postprocessVertexShader"; -const shader = `attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[postprocess_vertex_name] = shader; -/** @internal */ -const postprocessVertexShader = { name: postprocess_vertex_name, shader }; -//# sourceMappingURL=postprocess.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/renderTargetWrapper.js - - -/** - * Wrapper around a render target (either single or multi textures) - */ -class renderTargetWrapper_RenderTargetWrapper { - /** - * Gets the depth/stencil texture (if created by a createDepthStencilTexture() call) - */ - get depthStencilTexture() { - return this._depthStencilTexture; - } - /** - * Indicates if the depth/stencil texture has a stencil aspect - */ - get depthStencilTextureWithStencil() { - return this._depthStencilTextureWithStencil; - } - /** - * Defines if the render target wrapper is for a cube texture or if false a 2d texture - */ - get isCube() { - return this._isCube; - } - /** - * Defines if the render target wrapper is for a single or multi target render wrapper - */ - get isMulti() { - return this._isMulti; - } - /** - * Defines if the render target wrapper is for a single or an array of textures - */ - get is2DArray() { - return this.layers > 0; - } - /** - * Gets the size of the render target wrapper (used for cubes, as width=height in this case) - */ - get size() { - return this.width; - } - /** - * Gets the width of the render target wrapper - */ - get width() { - return this._size.width || this._size; - } - /** - * Gets the height of the render target wrapper - */ - get height() { - return this._size.height || this._size; - } - /** - * Gets the number of layers of the render target wrapper (only used if is2DArray is true and wrapper is not a multi render target) - */ - get layers() { - return this._size.layers || 0; - } - /** - * Gets the render texture. If this is a multi render target, gets the first texture - */ - get texture() { - var _a, _b; - return (_b = (_a = this._textures) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : null; - } - /** - * 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) - */ - get textures() { - return this._textures; - } - /** - * 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 - */ - get faceIndices() { - return this._faceIndices; - } - /** - * 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 - */ - get layerIndices() { - return this._layerIndices; - } - /** - * Gets the sample count of the render target - */ - get samples() { - return this._samples; - } - /** - * Sets the sample count of the render target - * @param value sample count - * @param initializeBuffers If set to true, the engine will make an initializing call to drawBuffers (only used when isMulti=true). - * @param force true to force calling the update sample count engine function even if the current sample count is equal to value - * @returns the sample count that has been set - */ - setSamples(value, initializeBuffers = true, force = false) { - if (this.samples === value && !force) { - return value; - } - const result = this._isMulti - ? this._engine.updateMultipleRenderTargetTextureSampleCount(this, value, initializeBuffers) - : this._engine.updateRenderTargetTextureSampleCount(this, value); - this._samples = value; - return result; - } - /** - * Initializes the render target wrapper - * @param isMulti true if the wrapper is a multi render target - * @param isCube true if the wrapper should render to a cube texture - * @param size size of the render target (width/height/layers) - * @param engine engine used to create the render target - */ - constructor(isMulti, isCube, size, engine) { - this._textures = null; - this._faceIndices = null; - this._layerIndices = null; - /** @internal */ - this._samples = 1; - /** @internal */ - this._attachments = null; - /** @internal */ - this._generateStencilBuffer = false; - /** @internal */ - this._generateDepthBuffer = false; - /** @internal */ - this._depthStencilTextureWithStencil = false; - this._isMulti = isMulti; - this._isCube = isCube; - this._size = size; - this._engine = engine; - this._depthStencilTexture = null; - } - /** - * Sets the render target texture(s) - * @param textures texture(s) to set - */ - setTextures(textures) { - if (Array.isArray(textures)) { - this._textures = textures; - } - else if (textures) { - this._textures = [textures]; - } - else { - this._textures = null; - } - } - /** - * Set a texture in the textures array - * @param texture The texture to set - * @param index The index in the textures array to set - * @param disposePrevious If this function should dispose the previous texture - */ - setTexture(texture, index = 0, disposePrevious = true) { - if (!this._textures) { - this._textures = []; - } - if (this._textures[index] && disposePrevious) { - this._textures[index].dispose(); - } - this._textures[index] = texture; - } - /** - * Sets the layer and face indices of every render target texture bound to each color attachment - * @param layers The layers of each texture to be set - * @param faces The faces of each texture to be set - */ - setLayerAndFaceIndices(layers, faces) { - this._layerIndices = layers; - this._faceIndices = faces; - } - /** - * Sets the layer and face indices of a texture in the textures array that should be bound to each color attachment - * @param index The index of the texture in the textures array to modify - * @param layer The layer of the texture to be set - * @param face The face of the texture to be set - */ - setLayerAndFaceIndex(index = 0, layer, face) { - if (!this._layerIndices) { - this._layerIndices = []; - } - if (!this._faceIndices) { - this._faceIndices = []; - } - if (layer !== undefined && layer >= 0) { - this._layerIndices[index] = layer; - } - if (face !== undefined && face >= 0) { - this._faceIndices[index] = face; - } - } - /** - * Creates the depth/stencil texture - * @param comparisonFunction Comparison function to use for the texture - * @param bilinearFiltering true if bilinear filtering should be used when sampling the texture - * @param generateStencil true if the stencil aspect should also be created - * @param samples sample count to use when creating the texture - * @param format format of the depth texture - * @param label defines the label to use for the texture (for debugging purpose only) - * @returns the depth/stencil created texture - */ - createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) { - var _a; - (_a = this._depthStencilTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - this._depthStencilTextureWithStencil = generateStencil; - this._depthStencilTexture = this._engine.createDepthStencilTexture(this._size, { - bilinearFiltering, - comparisonFunction, - generateStencil, - isCube: this._isCube, - samples, - depthTextureFormat: format, - label, - }, this); - return this._depthStencilTexture; - } - /** - * Shares the depth buffer of this render target with another render target. - * @internal - * @param renderTarget Destination renderTarget - */ - _shareDepth(renderTarget) { - if (this._depthStencilTexture) { - if (renderTarget._depthStencilTexture) { - renderTarget._depthStencilTexture.dispose(); - } - renderTarget._depthStencilTexture = this._depthStencilTexture; - this._depthStencilTexture.incrementReferences(); - } - } - /** - * @internal - */ - _swapAndDie(target) { - if (this.texture) { - this.texture._swapAndDie(target); - } - this._textures = null; - this.dispose(true); - } - _cloneRenderTargetWrapper() { - var _a, _b, _c, _d, _e, _f, _g, _h; - let rtw = null; - if (this._isMulti) { - const textureArray = this.textures; - if (textureArray && textureArray.length > 0) { - let generateDepthTexture = false; - let textureCount = textureArray.length; - const lastTextureSource = textureArray[textureArray.length - 1]._source; - if (lastTextureSource === internalTexture_InternalTextureSource.Depth || lastTextureSource === internalTexture_InternalTextureSource.DepthStencil) { - generateDepthTexture = true; - textureCount--; - } - const samplingModes = []; - const types = []; - const formats = []; - const targetTypes = []; - const faceIndex = []; - const layerIndex = []; - const layerCounts = []; - const internalTexture2Index = {}; - for (let i = 0; i < textureCount; ++i) { - const texture = textureArray[i]; - samplingModes.push(texture.samplingMode); - types.push(texture.type); - formats.push(texture.format); - const index = internalTexture2Index[texture.uniqueId]; - if (index !== undefined) { - targetTypes.push(-1); - layerCounts.push(0); - } - else { - internalTexture2Index[texture.uniqueId] = i; - if (texture.is2DArray) { - targetTypes.push(35866); - layerCounts.push(texture.depth); - } - else if (texture.isCube) { - targetTypes.push(34067); - layerCounts.push(0); - } /*else if (texture.isCubeArray) { - targetTypes.push(3735928559); - layerCounts.push(texture.depth); - }*/ - else if (texture.is3D) { - targetTypes.push(32879); - layerCounts.push(texture.depth); - } - else { - targetTypes.push(3553); - layerCounts.push(0); - } - } - if (this._faceIndices) { - faceIndex.push((_a = this._faceIndices[i]) !== null && _a !== void 0 ? _a : 0); - } - if (this._layerIndices) { - layerIndex.push((_b = this._layerIndices[i]) !== null && _b !== void 0 ? _b : 0); - } - } - const optionsMRT = { - samplingModes, - generateMipMaps: textureArray[0].generateMipMaps, - generateDepthBuffer: this._generateDepthBuffer, - generateStencilBuffer: this._generateStencilBuffer, - generateDepthTexture, - types, - formats, - textureCount, - targetTypes, - faceIndex, - layerIndex, - layerCounts, - }; - const size = { - width: this.width, - height: this.height, - }; - rtw = this._engine.createMultipleRenderTarget(size, optionsMRT); - for (let i = 0; i < textureCount; ++i) { - if (targetTypes[i] !== -1) { - continue; - } - const index = internalTexture2Index[textureArray[i].uniqueId]; - rtw.setTexture(rtw.textures[index], i); - } - } - } - else { - const options = {}; - options.generateDepthBuffer = this._generateDepthBuffer; - options.generateMipMaps = (_d = (_c = this.texture) === null || _c === void 0 ? void 0 : _c.generateMipMaps) !== null && _d !== void 0 ? _d : false; - options.generateStencilBuffer = this._generateStencilBuffer; - options.samplingMode = (_e = this.texture) === null || _e === void 0 ? void 0 : _e.samplingMode; - options.type = (_f = this.texture) === null || _f === void 0 ? void 0 : _f.type; - options.format = (_g = this.texture) === null || _g === void 0 ? void 0 : _g.format; - if (this.isCube) { - rtw = this._engine.createRenderTargetCubeTexture(this.width, options); - } - else { - const size = { - width: this.width, - height: this.height, - layers: this.is2DArray ? (_h = this.texture) === null || _h === void 0 ? void 0 : _h.depth : undefined, - }; - rtw = this._engine.createRenderTargetTexture(size, options); - } - rtw.texture.isReady = true; - } - return rtw; - } - _swapRenderTargetWrapper(target) { - if (this._textures && target._textures) { - for (let i = 0; i < this._textures.length; ++i) { - this._textures[i]._swapAndDie(target._textures[i], false); - target._textures[i].isReady = true; - } - } - if (this._depthStencilTexture && target._depthStencilTexture) { - this._depthStencilTexture._swapAndDie(target._depthStencilTexture); - target._depthStencilTexture.isReady = true; - } - this._textures = null; - this._depthStencilTexture = null; - } - /** @internal */ - _rebuild() { - const rtw = this._cloneRenderTargetWrapper(); - if (!rtw) { - return; - } - if (this._depthStencilTexture) { - const samplingMode = this._depthStencilTexture.samplingMode; - const bilinear = samplingMode === 2 || - samplingMode === 3 || - samplingMode === 11; - rtw.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction, bilinear, this._depthStencilTextureWithStencil, this._depthStencilTexture.samples); - } - if (this.samples > 1) { - rtw.setSamples(this.samples); - } - rtw._swapRenderTargetWrapper(this); - rtw.dispose(); - } - /** - * Releases the internal render textures - */ - releaseTextures() { - var _a, _b; - if (this._textures) { - for (let i = 0; (_b = i < ((_a = this._textures) === null || _a === void 0 ? void 0 : _a.length)) !== null && _b !== void 0 ? _b : 0; ++i) { - this._textures[i].dispose(); - } - } - this._textures = null; - } - /** - * Disposes the whole render target wrapper - * @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 - */ - dispose(disposeOnlyFramebuffers = false) { - var _a; - if (!disposeOnlyFramebuffers) { - (_a = this._depthStencilTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - this._depthStencilTexture = null; - this.releaseTextures(); - } - this._engine._releaseRenderTargetWrapper(this); - } -} -//# sourceMappingURL=renderTargetWrapper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGL/webGLRenderTargetWrapper.js - -/** @internal */ -class WebGLRenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper { - constructor(isMulti, isCube, size, engine, context) { - super(isMulti, isCube, size, engine); - /** - * @internal - */ - this._framebuffer = null; - /** - * @internal - */ - this._depthStencilBuffer = null; - // eslint-disable-next-line @typescript-eslint/naming-convention - /** - * @internal - */ - this._MSAAFramebuffer = null; - // Multiview - /** - * @internal - */ - this._colorTextureArray = null; - /** - * @internal - */ - this._depthStencilTextureArray = null; - /** - * @internal - */ - this._disposeOnlyFramebuffers = false; - this._context = context; - } - _cloneRenderTargetWrapper() { - let rtw = null; - if (this._colorTextureArray && this._depthStencilTextureArray) { - rtw = this._engine.createMultiviewRenderTargetTexture(this.width, this.height); - rtw.texture.isReady = true; - } - else { - rtw = super._cloneRenderTargetWrapper(); - } - return rtw; - } - _swapRenderTargetWrapper(target) { - super._swapRenderTargetWrapper(target); - target._framebuffer = this._framebuffer; - target._depthStencilBuffer = this._depthStencilBuffer; - target._MSAAFramebuffer = this._MSAAFramebuffer; - target._colorTextureArray = this._colorTextureArray; - target._depthStencilTextureArray = this._depthStencilTextureArray; - this._framebuffer = this._depthStencilBuffer = this._MSAAFramebuffer = this._colorTextureArray = this._depthStencilTextureArray = null; - } - /** - * Shares the depth buffer of this render target with another render target. - * @internal - * @param renderTarget Destination renderTarget - */ - _shareDepth(renderTarget) { - super._shareDepth(renderTarget); - const gl = this._context; - const depthbuffer = this._depthStencilBuffer; - const framebuffer = renderTarget._MSAAFramebuffer || renderTarget._framebuffer; - if (renderTarget._depthStencilBuffer) { - gl.deleteRenderbuffer(renderTarget._depthStencilBuffer); - } - renderTarget._depthStencilBuffer = this._depthStencilBuffer; - this._engine._bindUnboundFramebuffer(framebuffer); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthbuffer); - this._engine._bindUnboundFramebuffer(null); - } - /** - * Binds a texture to this render target on a specific attachment - * @param texture The texture to bind to the framebuffer - * @param attachmentIndex Index of the attachment - * @param faceIndexOrLayer The face or layer of the texture to render to in case of cube texture or array texture - * @param lodLevel defines the lod level to bind to the frame buffer - */ - _bindTextureRenderTarget(texture, attachmentIndex = 0, faceIndexOrLayer, lodLevel = 0) { - var _a, _b, _c, _d; - if (!texture._hardwareTexture) { - return; - } - const framebuffer = this._framebuffer; - const currentFB = this._engine._currentFramebuffer; - this._engine._bindUnboundFramebuffer(framebuffer); - if (this._engine.webGLVersion > 1) { - const gl = this._context; - const attachment = gl["COLOR_ATTACHMENT" + attachmentIndex]; - if (texture.is2DArray || texture.is3D) { - 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; - gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, texture._hardwareTexture.underlyingResource, lodLevel, faceIndexOrLayer); - } - else if (texture.isCube) { - // if face index is not specified, try to query it from faceIndices - // default is face 0 - 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; - gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer, texture._hardwareTexture.underlyingResource, lodLevel); - } - else { - gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._hardwareTexture.underlyingResource, lodLevel); - } - } - else { - // Default behavior (WebGL) - const gl = this._context; - const attachment = gl["COLOR_ATTACHMENT" + attachmentIndex + "_WEBGL"]; - const target = faceIndexOrLayer !== undefined ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer : gl.TEXTURE_2D; - gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, target, texture._hardwareTexture.underlyingResource, lodLevel); - } - this._engine._bindUnboundFramebuffer(currentFB); - } - /** - * Set a texture in the textures array - * @param texture the texture to set - * @param index the index in the textures array to set - * @param disposePrevious If this function should dispose the previous texture - */ - setTexture(texture, index = 0, disposePrevious = true) { - super.setTexture(texture, index, disposePrevious); - this._bindTextureRenderTarget(texture, index); - } - /** - * Sets the layer and face indices of every render target texture - * @param layers The layer of the texture to be set (make negative to not modify) - * @param faces The face of the texture to be set (make negative to not modify) - */ - setLayerAndFaceIndices(layers, faces) { - var _a, _b; - super.setLayerAndFaceIndices(layers, faces); - if (!this.textures || !this.layerIndices || !this.faceIndices) { - return; - } - // the length of this._attachments is the right one as it does not count the depth texture, in case we generated it - const textureCount = (_b = (_a = this._attachments) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : this.textures.length; - for (let index = 0; index < textureCount; index++) { - const texture = this.textures[index]; - if (!texture) { - // The target type was probably -1 at creation time and setTexture has not been called yet for this index - continue; - } - if (texture.is2DArray || texture.is3D) { - this._bindTextureRenderTarget(texture, index, this.layerIndices[index]); - } - else if (texture.isCube) { - this._bindTextureRenderTarget(texture, index, this.faceIndices[index]); - } - else { - this._bindTextureRenderTarget(texture, index); - } - } - } - /** - * Set the face and layer indices of a texture in the textures array - * @param index The index of the texture in the textures array to modify - * @param layer The layer of the texture to be set - * @param face The face of the texture to be set - */ - setLayerAndFaceIndex(index = 0, layer, face) { - super.setLayerAndFaceIndex(index, layer, face); - if (!this.textures || !this.layerIndices || !this.faceIndices) { - return; - } - const texture = this.textures[index]; - if (texture.is2DArray || texture.is3D) { - this._bindTextureRenderTarget(this.textures[index], index, this.layerIndices[index]); - } - else if (texture.isCube) { - this._bindTextureRenderTarget(this.textures[index], index, this.faceIndices[index]); - } - } - dispose(disposeOnlyFramebuffers = this._disposeOnlyFramebuffers) { - const gl = this._context; - if (!disposeOnlyFramebuffers) { - if (this._colorTextureArray) { - this._context.deleteTexture(this._colorTextureArray); - this._colorTextureArray = null; - } - if (this._depthStencilTextureArray) { - this._context.deleteTexture(this._depthStencilTextureArray); - this._depthStencilTextureArray = null; - } - } - if (this._framebuffer) { - gl.deleteFramebuffer(this._framebuffer); - this._framebuffer = null; - } - if (this._depthStencilBuffer) { - gl.deleteRenderbuffer(this._depthStencilBuffer); - this._depthStencilBuffer = null; - } - if (this._MSAAFramebuffer) { - gl.deleteFramebuffer(this._MSAAFramebuffer); - this._MSAAFramebuffer = null; - } - super.dispose(disposeOnlyFramebuffers); - } -} -//# sourceMappingURL=webGLRenderTargetWrapper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.renderTarget.js - - - - - -ThinEngine.prototype._createHardwareRenderTargetWrapper = function (isMulti, isCube, size) { - const rtWrapper = new WebGLRenderTargetWrapper(isMulti, isCube, size, this, this._gl); - this._renderTargetWrapperCache.push(rtWrapper); - return rtWrapper; -}; -ThinEngine.prototype.createRenderTargetTexture = function (size, options) { - var _a, _b; - const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size); - let generateDepthBuffer = true; - let generateStencilBuffer = false; - let noColorAttachment = false; - let colorAttachment = undefined; - let samples = 1; - if (options !== undefined && typeof options === "object") { - generateDepthBuffer = (_a = options.generateDepthBuffer) !== null && _a !== void 0 ? _a : true; - generateStencilBuffer = !!options.generateStencilBuffer; - noColorAttachment = !!options.noColorAttachment; - colorAttachment = options.colorAttachment; - samples = (_b = options.samples) !== null && _b !== void 0 ? _b : 1; - } - const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, internalTexture_InternalTextureSource.RenderTarget)); - const width = size.width || size; - const height = size.height || size; - const currentFrameBuffer = this._currentFramebuffer; - const gl = this._gl; - // Create the framebuffer - const framebuffer = gl.createFramebuffer(); - this._bindUnboundFramebuffer(framebuffer); - rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height); - // No need to rebind on every frame - if (texture && !texture.is2DArray) { - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._hardwareTexture.underlyingResource, 0); - } - this._bindUnboundFramebuffer(currentFrameBuffer); - rtWrapper._framebuffer = framebuffer; - rtWrapper._generateDepthBuffer = generateDepthBuffer; - rtWrapper._generateStencilBuffer = generateStencilBuffer; - rtWrapper.setTextures(texture); - this.updateRenderTargetTextureSampleCount(rtWrapper, samples); - return rtWrapper; -}; -ThinEngine.prototype.createDepthStencilTexture = function (size, options, rtWrapper) { - if (options.isCube) { - const width = size.width || size; - return this._createDepthStencilCubeTexture(width, options, rtWrapper); - } - else { - return this._createDepthStencilTexture(size, options, rtWrapper); - } -}; -ThinEngine.prototype._createDepthStencilTexture = function (size, options, rtWrapper) { - const gl = this._gl; - const layers = size.layers || 0; - const target = layers !== 0 ? gl.TEXTURE_2D_ARRAY : gl.TEXTURE_2D; - const internalTexture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.DepthStencil); - if (!this._caps.depthTextureExtension) { - logger_Logger.Error("Depth texture is not supported by your browser or hardware."); - return internalTexture; - } - const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options); - this._bindTextureDirectly(target, internalTexture, true); - this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.comparisonFunction === 0 ? false : internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples); - if (internalOptions.depthTextureFormat !== undefined) { - if (internalOptions.depthTextureFormat !== 15 && - internalOptions.depthTextureFormat !== 16 && - internalOptions.depthTextureFormat !== 17 && - internalOptions.depthTextureFormat !== 13 && - internalOptions.depthTextureFormat !== 14 && - internalOptions.depthTextureFormat !== 18) { - logger_Logger.Error("Depth texture format is not supported."); - return internalTexture; - } - internalTexture.format = internalOptions.depthTextureFormat; - } - else { - internalTexture.format = internalOptions.generateStencil ? 13 : 16; - } - const hasStencil = internalTexture.format === 17 || - internalTexture.format === 13 || - internalTexture.format === 18; - rtWrapper._depthStencilTexture = internalTexture; - rtWrapper._depthStencilTextureWithStencil = hasStencil; - let type = gl.UNSIGNED_INT; - if (internalTexture.format === 15) { - type = gl.UNSIGNED_SHORT; - } - else if (internalTexture.format === 17 || internalTexture.format === 13) { - type = gl.UNSIGNED_INT_24_8; - } - else if (internalTexture.format === 14) { - type = gl.FLOAT; - } - else if (internalTexture.format === 18) { - type = gl.FLOAT_32_UNSIGNED_INT_24_8_REV; - } - const format = hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT; - let internalFormat = format; - if (this.webGLVersion > 1) { - if (internalTexture.format === 15) { - internalFormat = gl.DEPTH_COMPONENT16; - } - else if (internalTexture.format === 16) { - internalFormat = gl.DEPTH_COMPONENT24; - } - else if (internalTexture.format === 17 || internalTexture.format === 13) { - internalFormat = gl.DEPTH24_STENCIL8; - } - else if (internalTexture.format === 14) { - internalFormat = gl.DEPTH_COMPONENT32F; - } - else if (internalTexture.format === 18) { - internalFormat = gl.DEPTH32F_STENCIL8; - } - } - if (internalTexture.is2DArray) { - gl.texImage3D(target, 0, internalFormat, internalTexture.width, internalTexture.height, layers, 0, format, type, null); - } - else { - gl.texImage2D(target, 0, internalFormat, internalTexture.width, internalTexture.height, 0, format, type, null); - } - this._bindTextureDirectly(target, null); - this._internalTexturesCache.push(internalTexture); - // Dispose previous depth/stencil render buffers and clear the corresponding attachment. - // Next time this framebuffer is bound, the new depth/stencil texture will be attached. - const glRtWrapper = rtWrapper; - if (glRtWrapper._depthStencilBuffer) { - const currentFrameBuffer = this._currentFramebuffer; - this._bindUnboundFramebuffer(glRtWrapper._framebuffer); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, null); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, null); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, null); - this._bindUnboundFramebuffer(currentFrameBuffer); - gl.deleteRenderbuffer(glRtWrapper._depthStencilBuffer); - glRtWrapper._depthStencilBuffer = null; - } - return internalTexture; -}; -ThinEngine.prototype.updateRenderTargetTextureSampleCount = function (rtWrapper, samples) { - if (this.webGLVersion < 2 || !rtWrapper || !rtWrapper.texture) { - return 1; - } - if (rtWrapper.samples === samples) { - return samples; - } - const gl = this._gl; - samples = Math.min(samples, this.getCaps().maxMSAASamples); - // Dispose previous render buffers - if (rtWrapper._depthStencilBuffer) { - gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer); - rtWrapper._depthStencilBuffer = null; - } - if (rtWrapper._MSAAFramebuffer) { - gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer); - rtWrapper._MSAAFramebuffer = null; - } - const hardwareTexture = rtWrapper.texture._hardwareTexture; - hardwareTexture.releaseMSAARenderBuffers(); - if (samples > 1 && typeof gl.renderbufferStorageMultisample === "function") { - const framebuffer = gl.createFramebuffer(); - if (!framebuffer) { - throw new Error("Unable to create multi sampled framebuffer"); - } - rtWrapper._MSAAFramebuffer = framebuffer; - this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer); - const colorRenderbuffer = this._createRenderBuffer(rtWrapper.texture.width, rtWrapper.texture.height, samples, -1 /* not used */, this._getRGBAMultiSampleBufferFormat(rtWrapper.texture.type), gl.COLOR_ATTACHMENT0, false); - if (!colorRenderbuffer) { - throw new Error("Unable to create multi sampled framebuffer"); - } - hardwareTexture.addMSAARenderBuffer(colorRenderbuffer); - } - else { - this._bindUnboundFramebuffer(rtWrapper._framebuffer); - } - rtWrapper.texture.samples = samples; - rtWrapper._samples = samples; - rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.texture.width, rtWrapper.texture.height, samples); - this._bindUnboundFramebuffer(null); - return samples; -}; -//# sourceMappingURL=engine.renderTarget.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/postProcess.js - - - - - - - - - - - - -/** - * PostProcess can be used to apply a shader to a texture after it has been rendered - * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses - */ -class postProcess_PostProcess { - /** - * Registers a shader code processing with a post process name. - * @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 - * @param customShaderCodeProcessing shader code processing to associate to the post process name - * @returns - */ - static RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing) { - if (!customShaderCodeProcessing) { - delete postProcess_PostProcess._CustomShaderCodeProcessing[postProcessName !== null && postProcessName !== void 0 ? postProcessName : ""]; - return; - } - postProcess_PostProcess._CustomShaderCodeProcessing[postProcessName !== null && postProcessName !== void 0 ? postProcessName : ""] = customShaderCodeProcessing; - } - static _GetShaderCodeProcessing(postProcessName) { - var _a; - return (_a = postProcess_PostProcess._CustomShaderCodeProcessing[postProcessName]) !== null && _a !== void 0 ? _a : postProcess_PostProcess._CustomShaderCodeProcessing[""]; - } - /** - * Number of sample textures (default: 1) - */ - get samples() { - return this._samples; - } - set samples(n) { - this._samples = Math.min(n, this._engine.getCaps().maxMSAASamples); - this._textures.forEach((texture) => { - texture.setSamples(this._samples); - }); - } - /** - * Returns the fragment url or shader name used in the post process. - * @returns the fragment url or name in the shader store. - */ - getEffectName() { - return this._fragmentUrl; - } - /** - * A function that is added to the onActivateObservable - */ - set onActivate(callback) { - if (this._onActivateObserver) { - this.onActivateObservable.remove(this._onActivateObserver); - } - if (callback) { - this._onActivateObserver = this.onActivateObservable.add(callback); - } - } - /** - * A function that is added to the onSizeChangedObservable - */ - set onSizeChanged(callback) { - if (this._onSizeChangedObserver) { - this.onSizeChangedObservable.remove(this._onSizeChangedObserver); - } - this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback); - } - /** - * A function that is added to the onApplyObservable - */ - set onApply(callback) { - if (this._onApplyObserver) { - this.onApplyObservable.remove(this._onApplyObserver); - } - this._onApplyObserver = this.onApplyObservable.add(callback); - } - /** - * A function that is added to the onBeforeRenderObservable - */ - set onBeforeRender(callback) { - if (this._onBeforeRenderObserver) { - this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); - } - this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); - } - /** - * A function that is added to the onAfterRenderObservable - */ - set onAfterRender(callback) { - if (this._onAfterRenderObserver) { - this.onAfterRenderObservable.remove(this._onAfterRenderObserver); - } - this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); - } - /** - * 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 - * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process. - */ - get inputTexture() { - return this._textures.data[this._currentRenderTextureInd]; - } - set inputTexture(value) { - this._forcedOutputTexture = value; - } - /** - * Since inputTexture should always be defined, if we previously manually set `inputTexture`, - * the only way to unset it is to use this function to restore its internal state - */ - restoreDefaultInputTexture() { - if (this._forcedOutputTexture) { - this._forcedOutputTexture = null; - this.markTextureDirty(); - } - } - /** - * Gets the camera which post process is applied to. - * @returns The camera the post process is applied to. - */ - getCamera() { - return this._camera; - } - /** - * Gets the texel size of the postprocess. - * See https://en.wikipedia.org/wiki/Texel_(graphics) - */ - get texelSize() { - if (this._shareOutputWithPostProcess) { - return this._shareOutputWithPostProcess.texelSize; - } - if (this._forcedOutputTexture) { - this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height); - } - return this._texelSize; - } - /** - * Creates a new instance PostProcess - * @param name The name of the PostProcess. - * @param fragmentUrl The url of the fragment shader to be used. - * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader. - * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader. - * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size) - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param defines String of defines that will be set when running the fragment shader. (default: null) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess") - * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx - * @param blockCompilation If the shader should not be compiled immediatly. (default: false) - * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA) - */ - 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) { - /** @internal */ - this._parentContainer = null; - /** - * Width of the texture to apply the post process on - */ - this.width = -1; - /** - * Height of the texture to apply the post process on - */ - this.height = -1; - /** - * Gets the node material used to create this postprocess (null if the postprocess was manually created) - */ - this.nodeMaterialSource = null; - /** - * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain) - * @internal - */ - this._outputTexture = null; - /** - * If the buffer needs to be cleared before applying the post process. (default: true) - * Should be set to false if shader will overwrite all previous pixels. - */ - this.autoClear = true; - /** - * If clearing the buffer should be forced in autoClear mode, even when alpha mode is enabled (default: false). - * By default, the buffer will only be cleared if alpha mode is disabled (and autoClear is true). - */ - this.forceAutoClearInAlphaMode = false; - /** - * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE) - */ - this.alphaMode = 0; - /** - * Animations to be used for the post processing - */ - this.animations = new Array(); - /** - * Enable Pixel Perfect mode where texture is not scaled to be power of 2. - * Can only be used on a single postprocess or on the last one of a chain. (default: false) - */ - this.enablePixelPerfectMode = false; - /** - * Force the postprocess to be applied without taking in account viewport - */ - this.forceFullscreenViewport = true; - /** - * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR) - * - * | Value | Type | Description | - * | ----- | ----------------------------------- | ----------- | - * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) | - * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) | - * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) | - * - */ - this.scaleMode = 1; - /** - * Force textures to be a power of two (default: false) - */ - this.alwaysForcePOT = false; - this._samples = 1; - /** - * Modify the scale of the post process to be the same as the viewport (default: false) - */ - this.adaptScaleToCurrentViewport = false; - this._reusable = false; - this._renderId = 0; - /** - * 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). - * 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 - * internal structures (materialContext) will be dirtified, which may impact performances - */ - this.externalTextureSamplerBinding = false; - /** - * Smart array of input and output textures for the post process. - * @internal - */ - this._textures = new SmartArray(2); - /** - * Smart array of input and output textures for the post process. - * @internal - */ - this._textureCache = []; - /** - * The index in _textures that corresponds to the output texture. - * @internal - */ - this._currentRenderTextureInd = 0; - this._scaleRatio = new math_vector_Vector2(1, 1); - this._texelSize = math_vector_Vector2.Zero(); - // Events - /** - * An event triggered when the postprocess is activated. - */ - this.onActivateObservable = new observable_Observable(); - /** - * An event triggered when the postprocess changes its size. - */ - this.onSizeChangedObservable = new observable_Observable(); - /** - * An event triggered when the postprocess applies its effect. - */ - this.onApplyObservable = new observable_Observable(); - /** - * An event triggered before rendering the postprocess - */ - this.onBeforeRenderObservable = new observable_Observable(); - /** - * An event triggered after rendering the postprocess - */ - this.onAfterRenderObservable = new observable_Observable(); - this.name = name; - if (camera != null) { - this._camera = camera; - this._scene = camera.getScene(); - camera.attachPostProcess(this); - this._engine = this._scene.getEngine(); - this._scene.postProcesses.push(this); - this.uniqueId = this._scene.getUniqueId(); - } - else if (engine) { - this._engine = engine; - this._engine.postProcesses.push(this); - } - this._options = options; - this.renderTargetSamplingMode = samplingMode ? samplingMode : 1; - this._reusable = reusable || false; - this._textureType = textureType; - this._textureFormat = textureFormat; - this._shaderLanguage = shaderLanguage; - this._samplers = samplers || []; - this._samplers.push("textureSampler"); - this._fragmentUrl = fragmentUrl; - this._vertexUrl = vertexUrl; - this._parameters = parameters || []; - this._parameters.push("scale"); - this._indexParameters = indexParameters; - this._drawWrapper = new drawWrapper_DrawWrapper(this._engine); - if (!blockCompilation) { - this.updateEffect(defines); - } - } - /** - * Gets a string identifying the name of the class - * @returns "PostProcess" string - */ - getClassName() { - return "PostProcess"; - } - /** - * Gets the engine which this post process belongs to. - * @returns The engine the post process was enabled with. - */ - getEngine() { - return this._engine; - } - /** - * The effect that is created when initializing the post process. - * @returns The created effect corresponding the the postprocess. - */ - getEffect() { - return this._drawWrapper.effect; - } - /** - * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another. - * @param postProcess The post process to share the output with. - * @returns This post process. - */ - shareOutputWith(postProcess) { - this._disposeTextures(); - this._shareOutputWithPostProcess = postProcess; - return this; - } - /** - * Reverses the effect of calling shareOutputWith and returns the post process back to its original state. - * This should be called if the post process that shares output with this post process is disabled/disposed. - */ - useOwnOutput() { - if (this._textures.length == 0) { - this._textures = new SmartArray(2); - } - this._shareOutputWithPostProcess = null; - } - /** - * Updates the effect with the current post process compile time values and recompiles the shader. - * @param defines Define statements that should be added at the beginning of the shader. (default: null) - * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) - * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) - * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx - * @param onCompiled Called when the shader has been compiled. - * @param onError Called if there is an error when compiling a shader. - * @param vertexUrl The url of the vertex shader to be used (default: the one given at construction time) - * @param fragmentUrl The url of the fragment shader to be used (default: the one given at construction time) - */ - updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl) { - var _a, _b; - const customShaderCodeProcessing = postProcess_PostProcess._GetShaderCodeProcessing(this.name); - if (customShaderCodeProcessing === null || customShaderCodeProcessing === void 0 ? void 0 : customShaderCodeProcessing.defineCustomBindings) { - const newUniforms = (_a = uniforms === null || uniforms === void 0 ? void 0 : uniforms.slice()) !== null && _a !== void 0 ? _a : []; - newUniforms.push(...this._parameters); - const newSamplers = (_b = samplers === null || samplers === void 0 ? void 0 : samplers.slice()) !== null && _b !== void 0 ? _b : []; - newSamplers.push(...this._samplers); - defines = customShaderCodeProcessing.defineCustomBindings(this.name, defines, newUniforms, newSamplers); - uniforms = newUniforms; - samplers = newSamplers; - } - this._postProcessDefines = defines; - this._drawWrapper.effect = this._engine.createEffect({ vertex: vertexUrl !== null && vertexUrl !== void 0 ? vertexUrl : this._vertexUrl, fragment: fragmentUrl !== null && fragmentUrl !== void 0 ? fragmentUrl : this._fragmentUrl }, { - attributes: ["position"], - uniformsNames: uniforms || this._parameters, - uniformBuffersNames: [], - samplers: samplers || this._samplers, - defines: defines !== null ? defines : "", - fallbacks: null, - onCompiled: onCompiled !== null && onCompiled !== void 0 ? onCompiled : null, - onError: onError !== null && onError !== void 0 ? onError : null, - indexParameters: indexParameters || this._indexParameters, - processCodeAfterIncludes: (customShaderCodeProcessing === null || customShaderCodeProcessing === void 0 ? void 0 : customShaderCodeProcessing.processCodeAfterIncludes) - ? (shaderType, code) => customShaderCodeProcessing.processCodeAfterIncludes(this.name, shaderType, code) - : null, - processFinalCode: (customShaderCodeProcessing === null || customShaderCodeProcessing === void 0 ? void 0 : customShaderCodeProcessing.processFinalCode) - ? (shaderType, code) => customShaderCodeProcessing.processFinalCode(this.name, shaderType, code) - : null, - shaderLanguage: this._shaderLanguage, - }, this._engine); - } - /** - * The post process is reusable if it can be used multiple times within one frame. - * @returns If the post process is reusable - */ - isReusable() { - return this._reusable; - } - /** invalidate frameBuffer to hint the postprocess to create a depth buffer */ - markTextureDirty() { - this.width = -1; - } - _createRenderTargetTexture(textureSize, textureOptions, channel = 0) { - for (let i = 0; i < this._textureCache.length; i++) { - if (this._textureCache[i].texture.width === textureSize.width && - this._textureCache[i].texture.height === textureSize.height && - this._textureCache[i].postProcessChannel === channel && - this._textureCache[i].texture._generateDepthBuffer === textureOptions.generateDepthBuffer && - this._textureCache[i].texture.samples === textureOptions.samples) { - return this._textureCache[i].texture; - } - } - const tex = this._engine.createRenderTargetTexture(textureSize, textureOptions); - this._textureCache.push({ texture: tex, postProcessChannel: channel, lastUsedRenderId: -1 }); - return tex; - } - _flushTextureCache() { - const currentRenderId = this._renderId; - for (let i = this._textureCache.length - 1; i >= 0; i--) { - if (currentRenderId - this._textureCache[i].lastUsedRenderId > 100) { - let currentlyUsed = false; - for (let j = 0; j < this._textures.length; j++) { - if (this._textures.data[j] === this._textureCache[i].texture) { - currentlyUsed = true; - break; - } - } - if (!currentlyUsed) { - this._textureCache[i].texture.dispose(); - this._textureCache.splice(i, 1); - } - } - } - } - _resize(width, height, camera, needMipMaps, forceDepthStencil) { - if (this._textures.length > 0) { - this._textures.reset(); - } - this.width = width; - this.height = height; - let firstPP = null; - for (let i = 0; i < camera._postProcesses.length; i++) { - if (camera._postProcesses[i] !== null) { - firstPP = camera._postProcesses[i]; - break; - } - } - const textureSize = { width: this.width, height: this.height }; - const textureOptions = { - generateMipMaps: needMipMaps, - generateDepthBuffer: forceDepthStencil || firstPP === this, - generateStencilBuffer: (forceDepthStencil || firstPP === this) && this._engine.isStencilEnable, - samplingMode: this.renderTargetSamplingMode, - type: this._textureType, - format: this._textureFormat, - samples: this._samples, - label: "PostProcessRTT-" + this.name, - }; - this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 0)); - if (this._reusable) { - this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 1)); - } - this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height); - this.onSizeChangedObservable.notifyObservers(this); - } - /** - * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable. - * 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. - * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable. - * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null) - * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false) - * @returns The render target wrapper that was bound to be written to. - */ - activate(camera, sourceTexture = null, forceDepthStencil) { - var _a, _b; - camera = camera || this._camera; - const scene = camera.getScene(); - const engine = scene.getEngine(); - const maxSize = engine.getCaps().maxTextureSize; - let requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0; - const requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0; - // 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 - const webVRCamera = camera.parent; - if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) { - requiredWidth /= 2; - } - let desiredWidth = this._options.width || requiredWidth; - let desiredHeight = this._options.height || requiredHeight; - const needMipMaps = this.renderTargetSamplingMode !== 7 && - this.renderTargetSamplingMode !== 1 && - this.renderTargetSamplingMode !== 2; - if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) { - if (this.adaptScaleToCurrentViewport) { - const currentViewport = engine.currentViewport; - if (currentViewport) { - desiredWidth *= currentViewport.width; - desiredHeight *= currentViewport.height; - } - } - if (needMipMaps || this.alwaysForcePOT) { - if (!this._options.width) { - desiredWidth = engine.needPOTTextures ? engine_Engine.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth; - } - if (!this._options.height) { - desiredHeight = engine.needPOTTextures ? engine_Engine.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight; - } - } - if (this.width !== desiredWidth || this.height !== desiredHeight) { - this._resize(desiredWidth, desiredHeight, camera, needMipMaps, forceDepthStencil); - } - this._textures.forEach((texture) => { - if (texture.samples !== this.samples) { - this._engine.updateRenderTargetTextureSampleCount(texture, this.samples); - } - }); - this._flushTextureCache(); - this._renderId++; - } - let target; - if (this._shareOutputWithPostProcess) { - target = this._shareOutputWithPostProcess.inputTexture; - } - else if (this._forcedOutputTexture) { - target = this._forcedOutputTexture; - this.width = this._forcedOutputTexture.width; - this.height = this._forcedOutputTexture.height; - } - else { - target = this.inputTexture; - let cache; - for (let i = 0; i < this._textureCache.length; i++) { - if (this._textureCache[i].texture === target) { - cache = this._textureCache[i]; - break; - } - } - if (cache) { - cache.lastUsedRenderId = this._renderId; - } - } - // Bind the input of this post process to be used as the output of the previous post process. - if (this.enablePixelPerfectMode) { - this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight); - this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport); - } - else { - this._scaleRatio.copyFromFloats(1, 1); - this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport); - } - (_b = (_a = this._engine)._debugInsertMarker) === null || _b === void 0 ? void 0 : _b.call(_a, `post process ${this.name} input`); - this.onActivateObservable.notifyObservers(camera); - // Clear - if (this.autoClear && (this.alphaMode === 0 || this.forceAutoClearInAlphaMode)) { - this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true); - } - if (this._reusable) { - this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2; - } - return target; - } - /** - * If the post process is supported. - */ - get isSupported() { - return this._drawWrapper.effect.isSupported; - } - /** - * The aspect ratio of the output texture. - */ - get aspectRatio() { - if (this._shareOutputWithPostProcess) { - return this._shareOutputWithPostProcess.aspectRatio; - } - if (this._forcedOutputTexture) { - return this._forcedOutputTexture.width / this._forcedOutputTexture.height; - } - return this.width / this.height; - } - /** - * Get a value indicating if the post-process is ready to be used - * @returns true if the post-process is ready (shader is compiled) - */ - isReady() { - var _a, _b; - return (_b = (_a = this._drawWrapper.effect) === null || _a === void 0 ? void 0 : _a.isReady()) !== null && _b !== void 0 ? _b : false; - } - /** - * Binds all textures and uniforms to the shader, this will be run on every pass. - * @returns the effect corresponding to this post process. Null if not compiled or not ready. - */ - apply() { - var _a, _b, _c; - // Check - if (!((_a = this._drawWrapper.effect) === null || _a === void 0 ? void 0 : _a.isReady())) { - return null; - } - // States - this._engine.enableEffect(this._drawWrapper); - this._engine.setState(false); - this._engine.setDepthBuffer(false); - this._engine.setDepthWrite(false); - // Alpha - this._engine.setAlphaMode(this.alphaMode); - if (this.alphaConstants) { - this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a); - } - // Bind the output texture of the preivous post process as the input to this post process. - let source; - if (this._shareOutputWithPostProcess) { - source = this._shareOutputWithPostProcess.inputTexture; - } - else if (this._forcedOutputTexture) { - source = this._forcedOutputTexture; - } - else { - source = this.inputTexture; - } - if (!this.externalTextureSamplerBinding) { - this._drawWrapper.effect._bindTexture("textureSampler", source === null || source === void 0 ? void 0 : source.texture); - } - // Parameters - this._drawWrapper.effect.setVector2("scale", this._scaleRatio); - this.onApplyObservable.notifyObservers(this._drawWrapper.effect); - (_c = (_b = postProcess_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); - return this._drawWrapper.effect; - } - _disposeTextures() { - if (this._shareOutputWithPostProcess || this._forcedOutputTexture) { - this._disposeTextureCache(); - return; - } - this._disposeTextureCache(); - this._textures.dispose(); - } - _disposeTextureCache() { - for (let i = this._textureCache.length - 1; i >= 0; i--) { - this._textureCache[i].texture.dispose(); - } - this._textureCache.length = 0; - } - /** - * Sets the required values to the prepass renderer. - * @param prePassRenderer defines the prepass renderer to setup. - * @returns true if the pre pass is needed. - */ - setPrePassRenderer(prePassRenderer) { - if (this._prePassEffectConfiguration) { - this._prePassEffectConfiguration = prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration); - this._prePassEffectConfiguration.enabled = true; - return true; - } - return false; - } - /** - * Disposes the post process. - * @param camera The camera to dispose the post process on. - */ - dispose(camera) { - camera = camera || this._camera; - this._disposeTextures(); - let index; - if (this._scene) { - index = this._scene.postProcesses.indexOf(this); - if (index !== -1) { - this._scene.postProcesses.splice(index, 1); - } - } - if (this._parentContainer) { - const index = this._parentContainer.postProcesses.indexOf(this); - if (index > -1) { - this._parentContainer.postProcesses.splice(index, 1); - } - this._parentContainer = null; - } - index = this._engine.postProcesses.indexOf(this); - if (index !== -1) { - this._engine.postProcesses.splice(index, 1); - } - if (!camera) { - return; - } - camera.detachPostProcess(this); - index = camera._postProcesses.indexOf(this); - if (index === 0 && camera._postProcesses.length > 0) { - const firstPostProcess = this._camera._getFirstPostProcess(); - if (firstPostProcess) { - firstPostProcess.markTextureDirty(); - } - } - this.onActivateObservable.clear(); - this.onAfterRenderObservable.clear(); - this.onApplyObservable.clear(); - this.onBeforeRenderObservable.clear(); - this.onSizeChangedObservable.clear(); - } - /** - * Serializes the post process to a JSON object - * @returns the JSON object - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - const camera = this.getCamera() || (this._scene && this._scene.activeCamera); - serializationObject.customType = "BABYLON." + this.getClassName(); - serializationObject.cameraId = camera ? camera.id : null; - serializationObject.reusable = this._reusable; - serializationObject.textureType = this._textureType; - serializationObject.fragmentUrl = this._fragmentUrl; - serializationObject.parameters = this._parameters; - serializationObject.samplers = this._samplers; - serializationObject.options = this._options; - serializationObject.defines = this._postProcessDefines; - serializationObject.textureFormat = this._textureFormat; - serializationObject.vertexUrl = this._vertexUrl; - serializationObject.indexParameters = this._indexParameters; - return serializationObject; - } - /** - * Clones this post process - * @returns a new post process similar to this one - */ - clone() { - const serializationObject = this.serialize(); - serializationObject._engine = this._engine; - serializationObject.cameraId = null; - const result = postProcess_PostProcess.Parse(serializationObject, this._scene, ""); - if (!result) { - return null; - } - result.onActivateObservable = this.onActivateObservable.clone(); - result.onSizeChangedObservable = this.onSizeChangedObservable.clone(); - result.onApplyObservable = this.onApplyObservable.clone(); - result.onBeforeRenderObservable = this.onBeforeRenderObservable.clone(); - result.onAfterRenderObservable = this.onAfterRenderObservable.clone(); - result._prePassEffectConfiguration = this._prePassEffectConfiguration; - return result; - } - /** - * Creates a material from parsed material data - * @param parsedPostProcess defines parsed post process data - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures - * @returns a new post process - */ - static Parse(parsedPostProcess, scene, rootUrl) { - const postProcessType = GetClass(parsedPostProcess.customType); - if (!postProcessType || !postProcessType._Parse) { - return null; - } - const camera = scene ? scene.getCameraById(parsedPostProcess.cameraId) : null; - return postProcessType._Parse(parsedPostProcess, camera, scene, rootUrl); - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new postProcess_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); - }, parsedPostProcess, scene, rootUrl); - } -} -postProcess_PostProcess._CustomShaderCodeProcessing = {}; -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "uniqueId", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "name", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "width", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "height", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "renderTargetSamplingMode", void 0); -__decorate([ - serializeAsColor4() -], postProcess_PostProcess.prototype, "clearColor", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "autoClear", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "forceAutoClearInAlphaMode", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "alphaMode", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "alphaConstants", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "enablePixelPerfectMode", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "forceFullscreenViewport", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "scaleMode", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "alwaysForcePOT", void 0); -__decorate([ - serialize("samples") -], postProcess_PostProcess.prototype, "_samples", void 0); -__decorate([ - serialize() -], postProcess_PostProcess.prototype, "adaptScaleToCurrentViewport", void 0); -RegisterClass("BABYLON.PostProcess", postProcess_PostProcess); -//# sourceMappingURL=postProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/vectorMergerBlock.js - - - - -/** - * Block used to create a Vector2/3/4 out of individual inputs (one for each component) - */ -class VectorMergerBlock extends NodeMaterialBlock { - /** - * Create a new VectorMergerBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Gets or sets the swizzle for x (meaning which component to affect to the output.x) - */ - this.xSwizzle = "x"; - /** - * Gets or sets the swizzle for y (meaning which component to affect to the output.y) - */ - this.ySwizzle = "y"; - /** - * Gets or sets the swizzle for z (meaning which component to affect to the output.z) - */ - this.zSwizzle = "z"; - /** - * Gets or sets the swizzle for w (meaning which component to affect to the output.w) - */ - this.wSwizzle = "w"; - this.registerInput("xyzw ", NodeMaterialBlockConnectionPointTypes.Vector4, true); - this.registerInput("xyz ", NodeMaterialBlockConnectionPointTypes.Vector3, true); - this.registerInput("xy ", NodeMaterialBlockConnectionPointTypes.Vector2, true); - this.registerInput("zw ", NodeMaterialBlockConnectionPointTypes.Vector2, true); - this.registerInput("x", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("y", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("z", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("w", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerOutput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerOutput("zw", NodeMaterialBlockConnectionPointTypes.Vector2); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "VectorMergerBlock"; - } - /** - * Gets the xyzw component (input) - */ - get xyzwIn() { - return this._inputs[0]; - } - /** - * Gets the xyz component (input) - */ - get xyzIn() { - return this._inputs[1]; - } - /** - * Gets the xy component (input) - */ - get xyIn() { - return this._inputs[2]; - } - /** - * Gets the zw component (input) - */ - get zwIn() { - return this._inputs[3]; - } - /** - * Gets the x component (input) - */ - get x() { - return this._inputs[4]; - } - /** - * Gets the y component (input) - */ - get y() { - return this._inputs[5]; - } - /** - * Gets the z component (input) - */ - get z() { - return this._inputs[6]; - } - /** - * Gets the w component (input) - */ - get w() { - return this._inputs[7]; - } - /** - * Gets the xyzw component (output) - */ - get xyzw() { - return this._outputs[0]; - } - /** - * Gets the xyz component (output) - */ - get xyzOut() { - return this._outputs[1]; - } - /** - * Gets the xy component (output) - */ - get xyOut() { - return this._outputs[2]; - } - /** - * Gets the zw component (output) - */ - get zwOut() { - return this._outputs[3]; - } - /** - * Gets the xy component (output) - * @deprecated Please use xyOut instead. - */ - get xy() { - return this.xyOut; - } - /** - * Gets the xyz component (output) - * @deprecated Please use xyzOut instead. - */ - get xyz() { - return this.xyzOut; - } - _inputRename(name) { - if (name === "xyzw ") { - return "xyzwIn"; - } - if (name === "xyz ") { - return "xyzIn"; - } - if (name === "xy ") { - return "xyIn"; - } - if (name === "zw ") { - return "zwIn"; - } - return name; - } - _buildSwizzle(len) { - const swizzle = this.xSwizzle + this.ySwizzle + this.zSwizzle + this.wSwizzle; - return "." + swizzle.substr(0, len); - } - _buildBlock(state) { - super._buildBlock(state); - const xInput = this.x; - const yInput = this.y; - const zInput = this.z; - const wInput = this.w; - const xyInput = this.xyIn; - const zwInput = this.zwIn; - const xyzInput = this.xyzIn; - const xyzwInput = this.xyzwIn; - const v4Output = this._outputs[0]; - const v3Output = this._outputs[1]; - const v2Output = this._outputs[2]; - const v2CompOutput = this._outputs[3]; - if (xyzwInput.isConnected) { - if (v4Output.hasEndpoints) { - state.compilationString += this._declareOutput(v4Output, state) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(4)};\n`; - } - if (v3Output.hasEndpoints) { - state.compilationString += this._declareOutput(v3Output, state) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(3)};\n`; - } - if (v2Output.hasEndpoints) { - state.compilationString += this._declareOutput(v2Output, state) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(2)};\n`; - } - } - else if (xyzInput.isConnected) { - if (v4Output.hasEndpoints) { - state.compilationString += - this._declareOutput(v4Output, state) + - ` = vec4(${xyzInput.associatedVariableName}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(4)};\n`; - } - if (v3Output.hasEndpoints) { - state.compilationString += this._declareOutput(v3Output, state) + ` = ${xyzInput.associatedVariableName}${this._buildSwizzle(3)};\n`; - } - if (v2Output.hasEndpoints) { - state.compilationString += this._declareOutput(v2Output, state) + ` = ${xyzInput.associatedVariableName}${this._buildSwizzle(2)};\n`; - } - } - else if (xyInput.isConnected) { - if (v4Output.hasEndpoints) { - if (zwInput.isConnected) { - state.compilationString += - this._declareOutput(v4Output, state) + ` = vec4(${xyInput.associatedVariableName}, ${zwInput.associatedVariableName})${this._buildSwizzle(4)};\n`; - } - else { - state.compilationString += - this._declareOutput(v4Output, state) + - ` = vec4(${xyInput.associatedVariableName}, ${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(4)};\n`; - } - } - if (v3Output.hasEndpoints) { - state.compilationString += - this._declareOutput(v3Output, state) + - ` = vec3(${xyInput.associatedVariableName}, ${zInput.isConnected ? this._writeVariable(zInput) : "0.0"})${this._buildSwizzle(3)};\n`; - } - if (v2Output.hasEndpoints) { - state.compilationString += this._declareOutput(v2Output, state) + ` = ${xyInput.associatedVariableName}${this._buildSwizzle(2)};\n`; - } - if (v2CompOutput.hasEndpoints) { - if (zwInput.isConnected) { - state.compilationString += this._declareOutput(v2CompOutput, state) + ` = ${zwInput.associatedVariableName}${this._buildSwizzle(2)};\n`; - } - else { - state.compilationString += - this._declareOutput(v2CompOutput, state) + - ` = vec2(${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(2)};\n`; - } - } - } - else { - if (v4Output.hasEndpoints) { - if (zwInput.isConnected) { - state.compilationString += - this._declareOutput(v4Output, state) + - ` = vec4(${xInput.isConnected ? this._writeVariable(xInput) : "0.0"}, ${yInput.isConnected ? this._writeVariable(yInput) : "0.0"}, ${zwInput.associatedVariableName})${this._buildSwizzle(4)};\n`; - } - else { - state.compilationString += - this._declareOutput(v4Output, state) + - ` = 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)};\n`; - } - } - if (v3Output.hasEndpoints) { - state.compilationString += - this._declareOutput(v3Output, state) + - ` = 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)};\n`; - } - if (v2Output.hasEndpoints) { - state.compilationString += - this._declareOutput(v2Output, state) + - ` = vec2(${xInput.isConnected ? this._writeVariable(xInput) : "0.0"}, ${yInput.isConnected ? this._writeVariable(yInput) : "0.0"})${this._buildSwizzle(2)};\n`; - } - if (v2CompOutput.hasEndpoints) { - if (zwInput.isConnected) { - state.compilationString += this._declareOutput(v2CompOutput, state) + ` = ${zwInput.associatedVariableName}${this._buildSwizzle(2)};\n`; - } - else { - state.compilationString += - this._declareOutput(v2CompOutput, state) + - ` = vec2(${zInput.isConnected ? this._writeVariable(zInput) : "0.0"}, ${wInput.isConnected ? this._writeVariable(wInput) : "0.0"})${this._buildSwizzle(2)};\n`; - } - } - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.xSwizzle = this.xSwizzle; - serializationObject.ySwizzle = this.ySwizzle; - serializationObject.zSwizzle = this.zSwizzle; - serializationObject.wSwizzle = this.wSwizzle; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - var _a, _b, _c, _d; - super._deserialize(serializationObject, scene, rootUrl); - this.xSwizzle = (_a = serializationObject.xSwizzle) !== null && _a !== void 0 ? _a : "x"; - this.ySwizzle = (_b = serializationObject.ySwizzle) !== null && _b !== void 0 ? _b : "y"; - this.zSwizzle = (_c = serializationObject.zSwizzle) !== null && _c !== void 0 ? _c : "z"; - this.wSwizzle = (_d = serializationObject.wSwizzle) !== null && _d !== void 0 ? _d : "w"; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\n`; - codeString += `${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\n`; - codeString += `${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\n`; - codeString += `${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\n`; - return codeString; - } -} -RegisterClass("BABYLON.VectorMergerBlock", VectorMergerBlock); -//# sourceMappingURL=vectorMergerBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/remapBlock.js - - - - - - - -/** - * Block used to remap a float from a range to a new one - */ -class RemapBlock extends NodeMaterialBlock { - /** - * Creates a new RemapBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Gets or sets the source range - */ - this.sourceRange = new math_vector_Vector2(-1, 1); - /** - * Gets or sets the target range - */ - this.targetRange = new math_vector_Vector2(0, 1); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("sourceMin", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("sourceMax", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("targetMin", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("targetMax", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "RemapBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the source min input component - */ - get sourceMin() { - return this._inputs[1]; - } - /** - * Gets the source max input component - */ - get sourceMax() { - return this._inputs[2]; - } - /** - * Gets the target min input component - */ - get targetMin() { - return this._inputs[3]; - } - /** - * Gets the target max input component - */ - get targetMax() { - return this._inputs[4]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - const sourceMin = this.sourceMin.isConnected ? this.sourceMin.associatedVariableName : this._writeFloat(this.sourceRange.x); - const sourceMax = this.sourceMax.isConnected ? this.sourceMax.associatedVariableName : this._writeFloat(this.sourceRange.y); - const targetMin = this.targetMin.isConnected ? this.targetMin.associatedVariableName : this._writeFloat(this.targetRange.x); - const targetMax = this.targetMax.isConnected ? this.targetMax.associatedVariableName : this._writeFloat(this.targetRange.y); - state.compilationString += - this._declareOutput(output, state) + - ` = ${targetMin} + (${this._inputs[0].associatedVariableName} - ${sourceMin}) * (${targetMax} - ${targetMin}) / (${sourceMax} - ${sourceMin});\n`; - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\n`; - codeString += `${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.sourceRange = this.sourceRange.asArray(); - serializationObject.targetRange = this.targetRange.asArray(); - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.sourceRange = math_vector_Vector2.FromArray(serializationObject.sourceRange); - this.targetRange = math_vector_Vector2.FromArray(serializationObject.targetRange); - } -} -__decorate([ - editableInPropertyPage("From", PropertyTypeForEdition.Vector2) -], RemapBlock.prototype, "sourceRange", void 0); -__decorate([ - editableInPropertyPage("To", PropertyTypeForEdition.Vector2) -], RemapBlock.prototype, "targetRange", void 0); -RegisterClass("BABYLON.RemapBlock", RemapBlock); -//# sourceMappingURL=remapBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/multiplyBlock.js - - - - -/** - * Block used to multiply 2 values - */ -class MultiplyBlock extends NodeMaterialBlock { - /** - * Creates a new MultiplyBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MultiplyBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\n`; - return this; - } -} -RegisterClass("BABYLON.MultiplyBlock", MultiplyBlock); -//# sourceMappingURL=multiplyBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialModes.js -/** - * Enum used to define the material modes - */ -var NodeMaterialModes; -(function (NodeMaterialModes) { - /** Regular material */ - NodeMaterialModes[NodeMaterialModes["Material"] = 0] = "Material"; - /** For post process */ - NodeMaterialModes[NodeMaterialModes["PostProcess"] = 1] = "PostProcess"; - /** For particle system */ - NodeMaterialModes[NodeMaterialModes["Particle"] = 2] = "Particle"; - /** For procedural texture */ - NodeMaterialModes[NodeMaterialModes["ProceduralTexture"] = 3] = "ProceduralTexture"; -})(NodeMaterialModes || (NodeMaterialModes = {})); -//# sourceMappingURL=nodeMaterialModes.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/EmitterTypes/boxParticleEmitter.js - - - -/** - * Particle emitter emitting particles from the inside of a box. - * It emits the particles randomly between 2 given directions. - */ -class BoxParticleEmitter { - /** - * Creates a new instance BoxParticleEmitter - */ - constructor() { - /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - */ - this.direction1 = new math_vector_Vector3(0, 1.0, 0); - /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - */ - this.direction2 = new math_vector_Vector3(0, 1.0, 0); - /** - * 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. - */ - this.minEmitBox = new math_vector_Vector3(-0.5, -0.5, -0.5); - /** - * 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. - */ - this.maxEmitBox = new math_vector_Vector3(0.5, 0.5, 0.5); - } - /** - * Called by the particle System when the direction is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param directionToUpdate is the direction vector to update with the result - * @param particle is the particle we are computed the direction for - * @param isLocal defines if the direction should be set in local space - */ - startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { - const randX = math_scalar_Scalar.RandomRange(this.direction1.x, this.direction2.x); - const randY = math_scalar_Scalar.RandomRange(this.direction1.y, this.direction2.y); - const randZ = math_scalar_Scalar.RandomRange(this.direction1.z, this.direction2.z); - if (isLocal) { - directionToUpdate.x = randX; - directionToUpdate.y = randY; - directionToUpdate.z = randZ; - return; - } - math_vector_Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); - } - /** - * Called by the particle System when the position is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param positionToUpdate is the position vector to update with the result - * @param particle is the particle we are computed the position for - * @param isLocal defines if the position should be set in local space - */ - startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { - const randX = math_scalar_Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x); - const randY = math_scalar_Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y); - const randZ = math_scalar_Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z); - if (isLocal) { - positionToUpdate.x = randX; - positionToUpdate.y = randY; - positionToUpdate.z = randZ; - return; - } - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate); - } - /** - * Clones the current emitter and returns a copy of it - * @returns the new emitter - */ - clone() { - const newOne = new BoxParticleEmitter(); - DeepCopier.DeepCopy(this, newOne); - return newOne; - } - /** - * Called by the GPUParticleSystem to setup the update shader - * @param uboOrEffect defines the update shader - */ - applyToShader(uboOrEffect) { - uboOrEffect.setVector3("direction1", this.direction1); - uboOrEffect.setVector3("direction2", this.direction2); - uboOrEffect.setVector3("minEmitBox", this.minEmitBox); - uboOrEffect.setVector3("maxEmitBox", this.maxEmitBox); - } - /** - * Creates the structure of the ubo for this particle emitter - * @param ubo ubo to create the structure for - */ - buildUniformLayout(ubo) { - ubo.addUniform("direction1", 3); - ubo.addUniform("direction2", 3); - ubo.addUniform("minEmitBox", 3); - ubo.addUniform("maxEmitBox", 3); - } - /** - * Returns a string to use to update the GPU particles update shader - * @returns a string containing the defines string - */ - getEffectDefines() { - return "#define BOXEMITTER"; - } - /** - * Returns the string "BoxParticleEmitter" - * @returns a string containing the class name - */ - getClassName() { - return "BoxParticleEmitter"; - } - /** - * Serializes the particle system to a JSON object. - * @returns the JSON object - */ - serialize() { - const serializationObject = {}; - serializationObject.type = this.getClassName(); - serializationObject.direction1 = this.direction1.asArray(); - serializationObject.direction2 = this.direction2.asArray(); - serializationObject.minEmitBox = this.minEmitBox.asArray(); - serializationObject.maxEmitBox = this.maxEmitBox.asArray(); - return serializationObject; - } - /** - * Parse properties from a JSON object - * @param serializationObject defines the JSON object - */ - parse(serializationObject) { - math_vector_Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); - math_vector_Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); - math_vector_Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox); - math_vector_Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox); - } -} -//# sourceMappingURL=boxParticleEmitter.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/EmitterTypes/coneParticleEmitter.js - - - -/** - * Particle emitter emitting particles from the inside of a cone. - * It emits the particles alongside the cone volume from the base to the particle. - * The emission direction might be randomized. - */ -class ConeParticleEmitter { - /** - * Gets or sets the radius of the emission cone - */ - get radius() { - return this._radius; - } - set radius(value) { - this._radius = value; - this._buildHeight(); - } - /** - * Gets or sets the angle of the emission cone - */ - get angle() { - return this._angle; - } - set angle(value) { - this._angle = value; - this._buildHeight(); - } - _buildHeight() { - if (this._angle !== 0) { - this._height = this._radius / Math.tan(this._angle / 2); - } - else { - this._height = 1; - } - } - /** - * Creates a new instance ConeParticleEmitter - * @param radius the radius of the emission cone (1 by default) - * @param angle the cone base angle (PI by default) - * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0) - */ - constructor(radius = 1, angle = Math.PI, - /** defines how much to randomize the particle direction [0-1] (default is 0) */ - directionRandomizer = 0) { - this.directionRandomizer = directionRandomizer; - /** - * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface) - */ - this.radiusRange = 1; - /** - * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface) - */ - this.heightRange = 1; - /** - * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone) - */ - this.emitFromSpawnPointOnly = false; - this.angle = angle; - this.radius = radius; - } - /** - * Called by the particle System when the direction is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param directionToUpdate is the direction vector to update with the result - * @param particle is the particle we are computed the direction for - * @param isLocal defines if the direction should be set in local space - */ - startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { - if (isLocal) { - math_vector_TmpVectors.Vector3[0].copyFrom(particle._localPosition).normalize(); - } - else { - particle.position.subtractToRef(worldMatrix.getTranslation(), math_vector_TmpVectors.Vector3[0]).normalize(); - } - const randX = math_scalar_Scalar.RandomRange(0, this.directionRandomizer); - const randY = math_scalar_Scalar.RandomRange(0, this.directionRandomizer); - const randZ = math_scalar_Scalar.RandomRange(0, this.directionRandomizer); - directionToUpdate.x = math_vector_TmpVectors.Vector3[0].x + randX; - directionToUpdate.y = math_vector_TmpVectors.Vector3[0].y + randY; - directionToUpdate.z = math_vector_TmpVectors.Vector3[0].z + randZ; - directionToUpdate.normalize(); - } - /** - * Called by the particle System when the position is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param positionToUpdate is the position vector to update with the result - * @param particle is the particle we are computed the position for - * @param isLocal defines if the position should be set in local space - */ - startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { - const s = math_scalar_Scalar.RandomRange(0, Math.PI * 2); - let h; - if (!this.emitFromSpawnPointOnly) { - h = math_scalar_Scalar.RandomRange(0, this.heightRange); - // Better distribution in a cone at normal angles. - h = 1 - h * h; - } - else { - h = 0.0001; - } - let radius = this._radius - math_scalar_Scalar.RandomRange(0, this._radius * this.radiusRange); - radius = radius * h; - const randX = radius * Math.sin(s); - const randZ = radius * Math.cos(s); - const randY = h * this._height; - if (isLocal) { - positionToUpdate.x = randX; - positionToUpdate.y = randY; - positionToUpdate.z = randZ; - return; - } - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate); - } - /** - * Clones the current emitter and returns a copy of it - * @returns the new emitter - */ - clone() { - const newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer); - DeepCopier.DeepCopy(this, newOne); - return newOne; - } - /** - * Called by the GPUParticleSystem to setup the update shader - * @param uboOrEffect defines the update shader - */ - applyToShader(uboOrEffect) { - uboOrEffect.setFloat2("radius", this._radius, this.radiusRange); - uboOrEffect.setFloat("coneAngle", this._angle); - uboOrEffect.setFloat2("height", this._height, this.heightRange); - uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); - } - /** - * Creates the structure of the ubo for this particle emitter - * @param ubo ubo to create the structure for - */ - buildUniformLayout(ubo) { - ubo.addUniform("radius", 2); - ubo.addUniform("coneAngle", 1); - ubo.addUniform("height", 2); - ubo.addUniform("directionRandomizer", 1); - } - /** - * Returns a string to use to update the GPU particles update shader - * @returns a string containing the defines string - */ - getEffectDefines() { - let defines = "#define CONEEMITTER"; - if (this.emitFromSpawnPointOnly) { - defines += "\n#define CONEEMITTERSPAWNPOINT"; - } - return defines; - } - /** - * Returns the string "ConeParticleEmitter" - * @returns a string containing the class name - */ - getClassName() { - return "ConeParticleEmitter"; - } - /** - * Serializes the particle system to a JSON object. - * @returns the JSON object - */ - serialize() { - const serializationObject = {}; - serializationObject.type = this.getClassName(); - serializationObject.radius = this._radius; - serializationObject.angle = this._angle; - serializationObject.directionRandomizer = this.directionRandomizer; - serializationObject.radiusRange = this.radiusRange; - serializationObject.heightRange = this.heightRange; - serializationObject.emitFromSpawnPointOnly = this.emitFromSpawnPointOnly; - return serializationObject; - } - /** - * Parse properties from a JSON object - * @param serializationObject defines the JSON object - */ - parse(serializationObject) { - this.radius = serializationObject.radius; - this.angle = serializationObject.angle; - this.directionRandomizer = serializationObject.directionRandomizer; - this.radiusRange = serializationObject.radiusRange !== undefined ? serializationObject.radiusRange : 1; - this.heightRange = serializationObject.radiusRange !== undefined ? serializationObject.heightRange : 1; - this.emitFromSpawnPointOnly = serializationObject.emitFromSpawnPointOnly !== undefined ? serializationObject.emitFromSpawnPointOnly : false; - } -} -//# sourceMappingURL=coneParticleEmitter.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/EmitterTypes/cylinderParticleEmitter.js - - - -/** - * Particle emitter emitting particles from the inside of a cylinder. - * It emits the particles alongside the cylinder radius. The emission direction might be randomized. - */ -class CylinderParticleEmitter { - /** - * Creates a new instance CylinderParticleEmitter - * @param radius the radius of the emission cylinder (1 by default) - * @param height the height of the emission cylinder (1 by default) - * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) - * @param directionRandomizer defines how much to randomize the particle direction [0-1] - */ - constructor( - /** - * The radius of the emission cylinder. - */ - radius = 1, - /** - * The height of the emission cylinder. - */ - height = 1, - /** - * The range of emission [0-1] 0 Surface only, 1 Entire Radius. - */ - radiusRange = 1, - /** - * How much to randomize the particle direction [0-1]. - */ - directionRandomizer = 0) { - this.radius = radius; - this.height = height; - this.radiusRange = radiusRange; - this.directionRandomizer = directionRandomizer; - this._tempVector = math_vector_Vector3.Zero(); - } - /** - * Called by the particle System when the direction is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param directionToUpdate is the direction vector to update with the result - * @param particle is the particle we are computed the direction for - * @param isLocal defines if the direction should be set in local space - * @param inverseWorldMatrix defines the inverted world matrix to use if isLocal is false - */ - startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal, inverseWorldMatrix) { - particle.position.subtractToRef(worldMatrix.getTranslation(), this._tempVector); - this._tempVector.normalize(); - math_vector_Vector3.TransformNormalToRef(this._tempVector, inverseWorldMatrix, this._tempVector); - const randY = math_scalar_Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2); - let angle = Math.atan2(this._tempVector.x, this._tempVector.z); - angle += math_scalar_Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer; - this._tempVector.y = randY; // set direction y to rand y to mirror normal of cylinder surface - this._tempVector.x = Math.sin(angle); - this._tempVector.z = Math.cos(angle); - this._tempVector.normalize(); - if (isLocal) { - directionToUpdate.copyFrom(this._tempVector); - return; - } - math_vector_Vector3.TransformNormalFromFloatsToRef(this._tempVector.x, this._tempVector.y, this._tempVector.z, worldMatrix, directionToUpdate); - } - /** - * Called by the particle System when the position is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param positionToUpdate is the position vector to update with the result - * @param particle is the particle we are computed the position for - * @param isLocal defines if the position should be set in local space - */ - startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { - const yPos = math_scalar_Scalar.RandomRange(-this.height / 2, this.height / 2); - const angle = math_scalar_Scalar.RandomRange(0, 2 * Math.PI); - // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html - const radiusDistribution = math_scalar_Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1); - const positionRadius = Math.sqrt(radiusDistribution) * this.radius; - const xPos = positionRadius * Math.cos(angle); - const zPos = positionRadius * Math.sin(angle); - if (isLocal) { - positionToUpdate.copyFromFloats(xPos, yPos, zPos); - return; - } - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate); - } - /** - * Clones the current emitter and returns a copy of it - * @returns the new emitter - */ - clone() { - const newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer); - DeepCopier.DeepCopy(this, newOne); - return newOne; - } - /** - * Called by the GPUParticleSystem to setup the update shader - * @param uboOrEffect defines the update shader - */ - applyToShader(uboOrEffect) { - uboOrEffect.setFloat("radius", this.radius); - uboOrEffect.setFloat("height", this.height); - uboOrEffect.setFloat("radiusRange", this.radiusRange); - uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); - } - /** - * Creates the structure of the ubo for this particle emitter - * @param ubo ubo to create the structure for - */ - buildUniformLayout(ubo) { - ubo.addUniform("radius", 1); - ubo.addUniform("height", 1); - ubo.addUniform("radiusRange", 1); - ubo.addUniform("directionRandomizer", 1); - } - /** - * Returns a string to use to update the GPU particles update shader - * @returns a string containing the defines string - */ - getEffectDefines() { - return "#define CYLINDEREMITTER"; - } - /** - * Returns the string "CylinderParticleEmitter" - * @returns a string containing the class name - */ - getClassName() { - return "CylinderParticleEmitter"; - } - /** - * Serializes the particle system to a JSON object. - * @returns the JSON object - */ - serialize() { - const serializationObject = {}; - serializationObject.type = this.getClassName(); - serializationObject.radius = this.radius; - serializationObject.height = this.height; - serializationObject.radiusRange = this.radiusRange; - serializationObject.directionRandomizer = this.directionRandomizer; - return serializationObject; - } - /** - * Parse properties from a JSON object - * @param serializationObject defines the JSON object - */ - parse(serializationObject) { - this.radius = serializationObject.radius; - this.height = serializationObject.height; - this.radiusRange = serializationObject.radiusRange; - this.directionRandomizer = serializationObject.directionRandomizer; - } -} -/** - * Particle emitter emitting particles from the inside of a cylinder. - * It emits the particles randomly between two vectors. - */ -class CylinderDirectedParticleEmitter extends CylinderParticleEmitter { - /** - * Creates a new instance CylinderDirectedParticleEmitter - * @param radius the radius of the emission cylinder (1 by default) - * @param height the height of the emission cylinder (1 by default) - * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) - * @param direction1 the min limit of the emission direction (up vector by default) - * @param direction2 the max limit of the emission direction (up vector by default) - */ - constructor(radius = 1, height = 1, radiusRange = 1, - /** - * The min limit of the emission direction. - */ - direction1 = new math_vector_Vector3(0, 1, 0), - /** - * The max limit of the emission direction. - */ - direction2 = new math_vector_Vector3(0, 1, 0)) { - super(radius, height, radiusRange); - this.direction1 = direction1; - this.direction2 = direction2; - } - /** - * Called by the particle System when the direction is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param directionToUpdate is the direction vector to update with the result - */ - startDirectionFunction(worldMatrix, directionToUpdate) { - const randX = math_scalar_Scalar.RandomRange(this.direction1.x, this.direction2.x); - const randY = math_scalar_Scalar.RandomRange(this.direction1.y, this.direction2.y); - const randZ = math_scalar_Scalar.RandomRange(this.direction1.z, this.direction2.z); - math_vector_Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); - } - /** - * Clones the current emitter and returns a copy of it - * @returns the new emitter - */ - clone() { - const newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2); - DeepCopier.DeepCopy(this, newOne); - return newOne; - } - /** - * Called by the GPUParticleSystem to setup the update shader - * @param uboOrEffect defines the update shader - */ - applyToShader(uboOrEffect) { - uboOrEffect.setFloat("radius", this.radius); - uboOrEffect.setFloat("height", this.height); - uboOrEffect.setFloat("radiusRange", this.radiusRange); - uboOrEffect.setVector3("direction1", this.direction1); - uboOrEffect.setVector3("direction2", this.direction2); - } - /** - * Creates the structure of the ubo for this particle emitter - * @param ubo ubo to create the structure for - */ - buildUniformLayout(ubo) { - ubo.addUniform("radius", 1); - ubo.addUniform("height", 1); - ubo.addUniform("radiusRange", 1); - ubo.addUniform("direction1", 3); - ubo.addUniform("direction2", 3); - } - /** - * Returns a string to use to update the GPU particles update shader - * @returns a string containing the defines string - */ - getEffectDefines() { - return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"; - } - /** - * Returns the string "CylinderDirectedParticleEmitter" - * @returns a string containing the class name - */ - getClassName() { - return "CylinderDirectedParticleEmitter"; - } - /** - * Serializes the particle system to a JSON object. - * @returns the JSON object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.direction1 = this.direction1.asArray(); - serializationObject.direction2 = this.direction2.asArray(); - return serializationObject; - } - /** - * Parse properties from a JSON object - * @param serializationObject defines the JSON object - */ - parse(serializationObject) { - super.parse(serializationObject); - this.direction1.copyFrom(serializationObject.direction1); - this.direction2.copyFrom(serializationObject.direction2); - } -} -//# sourceMappingURL=cylinderParticleEmitter.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/EmitterTypes/hemisphericParticleEmitter.js - - - -/** - * Particle emitter emitting particles from the inside of a hemisphere. - * It emits the particles alongside the hemisphere radius. The emission direction might be randomized. - */ -class HemisphericParticleEmitter { - /** - * Creates a new instance HemisphericParticleEmitter - * @param radius the radius of the emission hemisphere (1 by default) - * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default) - * @param directionRandomizer defines how much to randomize the particle direction [0-1] - */ - constructor( - /** - * The radius of the emission hemisphere. - */ - radius = 1, - /** - * The range of emission [0-1] 0 Surface only, 1 Entire Radius. - */ - radiusRange = 1, - /** - * How much to randomize the particle direction [0-1]. - */ - directionRandomizer = 0) { - this.radius = radius; - this.radiusRange = radiusRange; - this.directionRandomizer = directionRandomizer; - } - /** - * Called by the particle System when the direction is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param directionToUpdate is the direction vector to update with the result - * @param particle is the particle we are computed the direction for - * @param isLocal defines if the direction should be set in local space - */ - startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { - const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize(); - const randX = math_scalar_Scalar.RandomRange(0, this.directionRandomizer); - const randY = math_scalar_Scalar.RandomRange(0, this.directionRandomizer); - const randZ = math_scalar_Scalar.RandomRange(0, this.directionRandomizer); - direction.x += randX; - direction.y += randY; - direction.z += randZ; - direction.normalize(); - if (isLocal) { - directionToUpdate.copyFrom(direction); - return; - } - math_vector_Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate); - } - /** - * Called by the particle System when the position is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param positionToUpdate is the position vector to update with the result - * @param particle is the particle we are computed the position for - * @param isLocal defines if the position should be set in local space - */ - startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { - const randRadius = this.radius - math_scalar_Scalar.RandomRange(0, this.radius * this.radiusRange); - const v = math_scalar_Scalar.RandomRange(0, 1.0); - const phi = math_scalar_Scalar.RandomRange(0, 2 * Math.PI); - const theta = Math.acos(2 * v - 1); - const randX = randRadius * Math.cos(phi) * Math.sin(theta); - const randY = randRadius * Math.cos(theta); - const randZ = randRadius * Math.sin(phi) * Math.sin(theta); - if (isLocal) { - positionToUpdate.copyFromFloats(randX, Math.abs(randY), randZ); - return; - } - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate); - } - /** - * Clones the current emitter and returns a copy of it - * @returns the new emitter - */ - clone() { - const newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer); - DeepCopier.DeepCopy(this, newOne); - return newOne; - } - /** - * Called by the GPUParticleSystem to setup the update shader - * @param uboOrEffect defines the update shader - */ - applyToShader(uboOrEffect) { - uboOrEffect.setFloat("radius", this.radius); - uboOrEffect.setFloat("radiusRange", this.radiusRange); - uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); - } - /** - * Creates the structure of the ubo for this particle emitter - * @param ubo ubo to create the structure for - */ - buildUniformLayout(ubo) { - ubo.addUniform("radius", 1); - ubo.addUniform("radiusRange", 1); - ubo.addUniform("directionRandomizer", 1); - } - /** - * Returns a string to use to update the GPU particles update shader - * @returns a string containing the defines string - */ - getEffectDefines() { - return "#define HEMISPHERICEMITTER"; - } - /** - * Returns the string "HemisphericParticleEmitter" - * @returns a string containing the class name - */ - getClassName() { - return "HemisphericParticleEmitter"; - } - /** - * Serializes the particle system to a JSON object. - * @returns the JSON object - */ - serialize() { - const serializationObject = {}; - serializationObject.type = this.getClassName(); - serializationObject.radius = this.radius; - serializationObject.radiusRange = this.radiusRange; - serializationObject.directionRandomizer = this.directionRandomizer; - return serializationObject; - } - /** - * Parse properties from a JSON object - * @param serializationObject defines the JSON object - */ - parse(serializationObject) { - this.radius = serializationObject.radius; - this.radiusRange = serializationObject.radiusRange; - this.directionRandomizer = serializationObject.directionRandomizer; - } -} -//# sourceMappingURL=hemisphericParticleEmitter.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/EmitterTypes/IParticleEmitterType.js - -//# sourceMappingURL=IParticleEmitterType.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/EmitterTypes/pointParticleEmitter.js - - - -/** - * Particle emitter emitting particles from a point. - * It emits the particles randomly between 2 given directions. - */ -class PointParticleEmitter { - /** - * Creates a new instance PointParticleEmitter - */ - constructor() { - /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - */ - this.direction1 = new math_vector_Vector3(0, 1.0, 0); - /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - */ - this.direction2 = new math_vector_Vector3(0, 1.0, 0); - } - /** - * Called by the particle System when the direction is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param directionToUpdate is the direction vector to update with the result - * @param particle is the particle we are computed the direction for - * @param isLocal defines if the direction should be set in local space - */ - startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { - const randX = math_scalar_Scalar.RandomRange(this.direction1.x, this.direction2.x); - const randY = math_scalar_Scalar.RandomRange(this.direction1.y, this.direction2.y); - const randZ = math_scalar_Scalar.RandomRange(this.direction1.z, this.direction2.z); - if (isLocal) { - directionToUpdate.copyFromFloats(randX, randY, randZ); - return; - } - math_vector_Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); - } - /** - * Called by the particle System when the position is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param positionToUpdate is the position vector to update with the result - * @param particle is the particle we are computed the position for - * @param isLocal defines if the position should be set in local space - */ - startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { - if (isLocal) { - positionToUpdate.copyFromFloats(0, 0, 0); - return; - } - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate); - } - /** - * Clones the current emitter and returns a copy of it - * @returns the new emitter - */ - clone() { - const newOne = new PointParticleEmitter(); - DeepCopier.DeepCopy(this, newOne); - return newOne; - } - /** - * Called by the GPUParticleSystem to setup the update shader - * @param uboOrEffect defines the update shader - */ - applyToShader(uboOrEffect) { - uboOrEffect.setVector3("direction1", this.direction1); - uboOrEffect.setVector3("direction2", this.direction2); - } - /** - * Creates the structure of the ubo for this particle emitter - * @param ubo ubo to create the structure for - */ - buildUniformLayout(ubo) { - ubo.addUniform("direction1", 3); - ubo.addUniform("direction2", 3); - } - /** - * Returns a string to use to update the GPU particles update shader - * @returns a string containing the defines string - */ - getEffectDefines() { - return "#define POINTEMITTER"; - } - /** - * Returns the string "PointParticleEmitter" - * @returns a string containing the class name - */ - getClassName() { - return "PointParticleEmitter"; - } - /** - * Serializes the particle system to a JSON object. - * @returns the JSON object - */ - serialize() { - const serializationObject = {}; - serializationObject.type = this.getClassName(); - serializationObject.direction1 = this.direction1.asArray(); - serializationObject.direction2 = this.direction2.asArray(); - return serializationObject; - } - /** - * Parse properties from a JSON object - * @param serializationObject defines the JSON object - */ - parse(serializationObject) { - math_vector_Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); - math_vector_Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); - } -} -//# sourceMappingURL=pointParticleEmitter.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/EmitterTypes/sphereParticleEmitter.js - - - -/** - * Particle emitter emitting particles from the inside of a sphere. - * It emits the particles alongside the sphere radius. The emission direction might be randomized. - */ -class SphereParticleEmitter { - /** - * Creates a new instance SphereParticleEmitter - * @param radius the radius of the emission sphere (1 by default) - * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default) - * @param directionRandomizer defines how much to randomize the particle direction [0-1] - */ - constructor( - /** - * The radius of the emission sphere. - */ - radius = 1, - /** - * The range of emission [0-1] 0 Surface only, 1 Entire Radius. - */ - radiusRange = 1, - /** - * How much to randomize the particle direction [0-1]. - */ - directionRandomizer = 0) { - this.radius = radius; - this.radiusRange = radiusRange; - this.directionRandomizer = directionRandomizer; - } - /** - * Called by the particle System when the direction is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param directionToUpdate is the direction vector to update with the result - * @param particle is the particle we are computed the direction for - * @param isLocal defines if the direction should be set in local space - */ - startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { - const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize(); - const randX = math_scalar_Scalar.RandomRange(0, this.directionRandomizer); - const randY = math_scalar_Scalar.RandomRange(0, this.directionRandomizer); - const randZ = math_scalar_Scalar.RandomRange(0, this.directionRandomizer); - direction.x += randX; - direction.y += randY; - direction.z += randZ; - direction.normalize(); - if (isLocal) { - directionToUpdate.copyFrom(direction); - return; - } - math_vector_Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate); - } - /** - * Called by the particle System when the position is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param positionToUpdate is the position vector to update with the result - * @param particle is the particle we are computed the position for - * @param isLocal defines if the position should be set in local space - */ - startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { - const randRadius = this.radius - math_scalar_Scalar.RandomRange(0, this.radius * this.radiusRange); - const v = math_scalar_Scalar.RandomRange(0, 1.0); - const phi = math_scalar_Scalar.RandomRange(0, 2 * Math.PI); - const theta = Math.acos(2 * v - 1); - const randX = randRadius * Math.cos(phi) * Math.sin(theta); - const randY = randRadius * Math.cos(theta); - const randZ = randRadius * Math.sin(phi) * Math.sin(theta); - if (isLocal) { - positionToUpdate.copyFromFloats(randX, randY, randZ); - return; - } - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate); - } - /** - * Clones the current emitter and returns a copy of it - * @returns the new emitter - */ - clone() { - const newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer); - DeepCopier.DeepCopy(this, newOne); - return newOne; - } - /** - * Called by the GPUParticleSystem to setup the update shader - * @param uboOrEffect defines the update shader - */ - applyToShader(uboOrEffect) { - uboOrEffect.setFloat("radius", this.radius); - uboOrEffect.setFloat("radiusRange", this.radiusRange); - uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); - } - /** - * Creates the structure of the ubo for this particle emitter - * @param ubo ubo to create the structure for - */ - buildUniformLayout(ubo) { - ubo.addUniform("radius", 1); - ubo.addUniform("radiusRange", 1); - ubo.addUniform("directionRandomizer", 1); - } - /** - * Returns a string to use to update the GPU particles update shader - * @returns a string containing the defines string - */ - getEffectDefines() { - return "#define SPHEREEMITTER"; - } - /** - * Returns the string "SphereParticleEmitter" - * @returns a string containing the class name - */ - getClassName() { - return "SphereParticleEmitter"; - } - /** - * Serializes the particle system to a JSON object. - * @returns the JSON object - */ - serialize() { - const serializationObject = {}; - serializationObject.type = this.getClassName(); - serializationObject.radius = this.radius; - serializationObject.radiusRange = this.radiusRange; - serializationObject.directionRandomizer = this.directionRandomizer; - return serializationObject; - } - /** - * Parse properties from a JSON object - * @param serializationObject defines the JSON object - */ - parse(serializationObject) { - this.radius = serializationObject.radius; - this.radiusRange = serializationObject.radiusRange; - this.directionRandomizer = serializationObject.directionRandomizer; - } -} -/** - * Particle emitter emitting particles from the inside of a sphere. - * It emits the particles randomly between two vectors. - */ -class SphereDirectedParticleEmitter extends SphereParticleEmitter { - /** - * Creates a new instance SphereDirectedParticleEmitter - * @param radius the radius of the emission sphere (1 by default) - * @param direction1 the min limit of the emission direction (up vector by default) - * @param direction2 the max limit of the emission direction (up vector by default) - */ - constructor(radius = 1, - /** - * The min limit of the emission direction. - */ - direction1 = new math_vector_Vector3(0, 1, 0), - /** - * The max limit of the emission direction. - */ - direction2 = new math_vector_Vector3(0, 1, 0)) { - super(radius); - this.direction1 = direction1; - this.direction2 = direction2; - } - /** - * Called by the particle System when the direction is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param directionToUpdate is the direction vector to update with the result - */ - startDirectionFunction(worldMatrix, directionToUpdate) { - const randX = math_scalar_Scalar.RandomRange(this.direction1.x, this.direction2.x); - const randY = math_scalar_Scalar.RandomRange(this.direction1.y, this.direction2.y); - const randZ = math_scalar_Scalar.RandomRange(this.direction1.z, this.direction2.z); - math_vector_Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); - } - /** - * Clones the current emitter and returns a copy of it - * @returns the new emitter - */ - clone() { - const newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2); - DeepCopier.DeepCopy(this, newOne); - return newOne; - } - /** - * Called by the GPUParticleSystem to setup the update shader - * @param uboOrEffect defines the update shader - */ - applyToShader(uboOrEffect) { - uboOrEffect.setFloat("radius", this.radius); - uboOrEffect.setFloat("radiusRange", this.radiusRange); - uboOrEffect.setVector3("direction1", this.direction1); - uboOrEffect.setVector3("direction2", this.direction2); - } - /** - * Creates the structure of the ubo for this particle emitter - * @param ubo ubo to create the structure for - */ - buildUniformLayout(ubo) { - ubo.addUniform("radius", 1); - ubo.addUniform("radiusRange", 1); - ubo.addUniform("direction1", 3); - ubo.addUniform("direction2", 3); - } - /** - * Returns a string to use to update the GPU particles update shader - * @returns a string containing the defines string - */ - getEffectDefines() { - return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"; - } - /** - * Returns the string "SphereDirectedParticleEmitter" - * @returns a string containing the class name - */ - getClassName() { - return "SphereDirectedParticleEmitter"; - } - /** - * Serializes the particle system to a JSON object. - * @returns the JSON object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.direction1 = this.direction1.asArray(); - serializationObject.direction2 = this.direction2.asArray(); - return serializationObject; - } - /** - * Parse properties from a JSON object - * @param serializationObject defines the JSON object - */ - parse(serializationObject) { - super.parse(serializationObject); - this.direction1.copyFrom(serializationObject.direction1); - this.direction2.copyFrom(serializationObject.direction2); - } -} -//# sourceMappingURL=sphereParticleEmitter.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/EmitterTypes/customParticleEmitter.js - - -/** - * Particle emitter emitting particles from a custom list of positions. - */ -class CustomParticleEmitter { - /** - * Creates a new instance CustomParticleEmitter - */ - constructor() { - /** - * Gets or sets the position generator that will create the initial position of each particle. - * Index will be provided when used with GPU particle. Particle will be provided when used with CPU particles - */ - this.particlePositionGenerator = () => { }; - /** - * Gets or sets the destination generator that will create the final destination of each particle. - * * Index will be provided when used with GPU particle. Particle will be provided when used with CPU particles - */ - this.particleDestinationGenerator = () => { }; - } - /** - * Called by the particle System when the direction is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param directionToUpdate is the direction vector to update with the result - * @param particle is the particle we are computed the direction for - * @param isLocal defines if the direction should be set in local space - */ - startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { - const tmpVector = math_vector_TmpVectors.Vector3[0]; - if (this.particleDestinationGenerator) { - this.particleDestinationGenerator(-1, particle, tmpVector); - // Get direction - const diffVector = math_vector_TmpVectors.Vector3[1]; - tmpVector.subtractToRef(particle.position, diffVector); - diffVector.scaleToRef(1 / particle.lifeTime, tmpVector); - } - else { - tmpVector.set(0, 0, 0); - } - if (isLocal) { - directionToUpdate.copyFrom(tmpVector); - return; - } - math_vector_Vector3.TransformNormalToRef(tmpVector, worldMatrix, directionToUpdate); - } - /** - * Called by the particle System when the position is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param positionToUpdate is the position vector to update with the result - * @param particle is the particle we are computed the position for - * @param isLocal defines if the position should be set in local space - */ - startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { - const tmpVector = math_vector_TmpVectors.Vector3[0]; - if (this.particlePositionGenerator) { - this.particlePositionGenerator(-1, particle, tmpVector); - } - else { - tmpVector.set(0, 0, 0); - } - if (isLocal) { - positionToUpdate.copyFrom(tmpVector); - return; - } - math_vector_Vector3.TransformCoordinatesToRef(tmpVector, worldMatrix, positionToUpdate); - } - /** - * Clones the current emitter and returns a copy of it - * @returns the new emitter - */ - clone() { - const newOne = new CustomParticleEmitter(); - DeepCopier.DeepCopy(this, newOne); - return newOne; - } - /** - * Called by the GPUParticleSystem to setup the update shader - * @param uboOrEffect defines the update shader - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - applyToShader(uboOrEffect) { } - /** - * Creates the structure of the ubo for this particle emitter - * @param ubo ubo to create the structure for - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - buildUniformLayout(ubo) { } - /** - * Returns a string to use to update the GPU particles update shader - * @returns a string containing the defines string - */ - getEffectDefines() { - return "#define CUSTOMEMITTER"; - } - /** - * Returns the string "PointParticleEmitter" - * @returns a string containing the class name - */ - getClassName() { - return "CustomParticleEmitter"; - } - /** - * Serializes the particle system to a JSON object. - * @returns the JSON object - */ - serialize() { - const serializationObject = {}; - serializationObject.type = this.getClassName(); - return serializationObject; - } - /** - * Parse properties from a JSON object - * @param serializationObject defines the JSON object - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - parse(serializationObject) { } -} -//# sourceMappingURL=customParticleEmitter.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/EmitterTypes/meshParticleEmitter.js - - - - -/** - * Particle emitter emitting particles from the inside of a box. - * It emits the particles randomly between 2 given directions. - */ -class MeshParticleEmitter { - /** Defines the mesh to use as source */ - get mesh() { - return this._mesh; - } - set mesh(value) { - if (this._mesh === value) { - return; - } - this._mesh = value; - if (value) { - this._indices = value.getIndices(); - this._positions = value.getVerticesData(buffer_VertexBuffer.PositionKind); - this._normals = value.getVerticesData(buffer_VertexBuffer.NormalKind); - } - else { - this._indices = null; - this._positions = null; - this._normals = null; - } - } - /** - * Creates a new instance MeshParticleEmitter - * @param mesh defines the mesh to use as source - */ - constructor(mesh = null) { - this._indices = null; - this._positions = null; - this._normals = null; - this._storedNormal = math_vector_Vector3.Zero(); - this._mesh = null; - /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - */ - this.direction1 = new math_vector_Vector3(0, 1.0, 0); - /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - */ - this.direction2 = new math_vector_Vector3(0, 1.0, 0); - /** - * Gets or sets a boolean indicating that particle directions must be built from mesh face normals - */ - this.useMeshNormalsForDirection = true; - this.mesh = mesh; - } - /** - * Called by the particle System when the direction is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param directionToUpdate is the direction vector to update with the result - * @param particle is the particle we are computed the direction for - * @param isLocal defines if the direction should be set in local space - */ - startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { - if (this.useMeshNormalsForDirection && this._normals) { - math_vector_Vector3.TransformNormalToRef(this._storedNormal, worldMatrix, directionToUpdate); - return; - } - const randX = math_scalar_Scalar.RandomRange(this.direction1.x, this.direction2.x); - const randY = math_scalar_Scalar.RandomRange(this.direction1.y, this.direction2.y); - const randZ = math_scalar_Scalar.RandomRange(this.direction1.z, this.direction2.z); - if (isLocal) { - directionToUpdate.copyFromFloats(randX, randY, randZ); - return; - } - math_vector_Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); - } - /** - * Called by the particle System when the position is computed for the created particle. - * @param worldMatrix is the world matrix of the particle system - * @param positionToUpdate is the position vector to update with the result - * @param particle is the particle we are computed the position for - * @param isLocal defines if the position should be set in local space - */ - startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { - if (!this._indices || !this._positions) { - return; - } - const randomFaceIndex = (3 * Math.random() * (this._indices.length / 3)) | 0; - const bu = Math.random(); - const bv = Math.random() * (1.0 - bu); - const bw = 1.0 - bu - bv; - const faceIndexA = this._indices[randomFaceIndex]; - const faceIndexB = this._indices[randomFaceIndex + 1]; - const faceIndexC = this._indices[randomFaceIndex + 2]; - const vertexA = math_vector_TmpVectors.Vector3[0]; - const vertexB = math_vector_TmpVectors.Vector3[1]; - const vertexC = math_vector_TmpVectors.Vector3[2]; - const randomVertex = math_vector_TmpVectors.Vector3[3]; - math_vector_Vector3.FromArrayToRef(this._positions, faceIndexA * 3, vertexA); - math_vector_Vector3.FromArrayToRef(this._positions, faceIndexB * 3, vertexB); - math_vector_Vector3.FromArrayToRef(this._positions, faceIndexC * 3, vertexC); - randomVertex.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x; - randomVertex.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y; - randomVertex.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z; - if (isLocal) { - positionToUpdate.copyFromFloats(randomVertex.x, randomVertex.y, randomVertex.z); - } - else { - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(randomVertex.x, randomVertex.y, randomVertex.z, worldMatrix, positionToUpdate); - } - if (this.useMeshNormalsForDirection && this._normals) { - math_vector_Vector3.FromArrayToRef(this._normals, faceIndexA * 3, vertexA); - math_vector_Vector3.FromArrayToRef(this._normals, faceIndexB * 3, vertexB); - math_vector_Vector3.FromArrayToRef(this._normals, faceIndexC * 3, vertexC); - this._storedNormal.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x; - this._storedNormal.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y; - this._storedNormal.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z; - } - } - /** - * Clones the current emitter and returns a copy of it - * @returns the new emitter - */ - clone() { - const newOne = new MeshParticleEmitter(this.mesh); - DeepCopier.DeepCopy(this, newOne); - return newOne; - } - /** - * Called by the GPUParticleSystem to setup the update shader - * @param uboOrEffect defines the update shader - */ - applyToShader(uboOrEffect) { - uboOrEffect.setVector3("direction1", this.direction1); - uboOrEffect.setVector3("direction2", this.direction2); - } - /** - * Creates the structure of the ubo for this particle emitter - * @param ubo ubo to create the structure for - */ - buildUniformLayout(ubo) { - ubo.addUniform("direction1", 3); - ubo.addUniform("direction2", 3); - } - /** - * Returns a string to use to update the GPU particles update shader - * @returns a string containing the defines string - */ - getEffectDefines() { - return ""; - } - /** - * Returns the string "BoxParticleEmitter" - * @returns a string containing the class name - */ - getClassName() { - return "MeshParticleEmitter"; - } - /** - * Serializes the particle system to a JSON object. - * @returns the JSON object - */ - serialize() { - var _a; - const serializationObject = {}; - serializationObject.type = this.getClassName(); - serializationObject.direction1 = this.direction1.asArray(); - serializationObject.direction2 = this.direction2.asArray(); - serializationObject.meshId = (_a = this.mesh) === null || _a === void 0 ? void 0 : _a.id; - serializationObject.useMeshNormalsForDirection = this.useMeshNormalsForDirection; - return serializationObject; - } - /** - * Parse properties from a JSON object - * @param serializationObject defines the JSON object - * @param scene defines the hosting scene - */ - parse(serializationObject, scene) { - math_vector_Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); - math_vector_Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); - if (serializationObject.meshId && scene) { - this.mesh = scene.getLastMeshById(serializationObject.meshId); - } - this.useMeshNormalsForDirection = serializationObject.useMeshNormalsForDirection; - } -} -//# sourceMappingURL=meshParticleEmitter.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/EmitterTypes/index.js - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/baseParticleSystem.js - - - - - - -/** - * This represents the base class for particle system in Babylon. - * 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. - * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function. - * @example https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro - */ -class BaseParticleSystem { - /** - * Gets or sets a texture used to add random noise to particle positions - */ - get noiseTexture() { - return this._noiseTexture; - } - set noiseTexture(value) { - if (this._noiseTexture === value) { - return; - } - this._noiseTexture = value; - this._reset(); - } - /** - * Gets or sets whether an animation sprite sheet is enabled or not on the particle system - */ - get isAnimationSheetEnabled() { - return this._isAnimationSheetEnabled; - } - set isAnimationSheetEnabled(value) { - if (this._isAnimationSheetEnabled == value) { - return; - } - this._isAnimationSheetEnabled = value; - this._reset(); - } - /** - * Gets or sets a boolean enabling the use of logarithmic depth buffers, which is good for wide depth buffers. - */ - get useLogarithmicDepth() { - return this._useLogarithmicDepth; - } - set useLogarithmicDepth(value) { - this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported; - } - /** - * Get hosting scene - * @returns the scene - */ - getScene() { - return this._scene; - } - _hasTargetStopDurationDependantGradient() { - return ((this._startSizeGradients && this._startSizeGradients.length > 0) || - (this._emitRateGradients && this._emitRateGradients.length > 0) || - (this._lifeTimeGradients && this._lifeTimeGradients.length > 0)); - } - /** - * Gets the current list of drag gradients. - * You must use addDragGradient and removeDragGradient to update this list - * @returns the list of drag gradients - */ - getDragGradients() { - return this._dragGradients; - } - /** - * Gets the current list of limit velocity gradients. - * You must use addLimitVelocityGradient and removeLimitVelocityGradient to update this list - * @returns the list of limit velocity gradients - */ - getLimitVelocityGradients() { - return this._limitVelocityGradients; - } - /** - * Gets the current list of color gradients. - * You must use addColorGradient and removeColorGradient to update this list - * @returns the list of color gradients - */ - getColorGradients() { - return this._colorGradients; - } - /** - * Gets the current list of size gradients. - * You must use addSizeGradient and removeSizeGradient to update this list - * @returns the list of size gradients - */ - getSizeGradients() { - return this._sizeGradients; - } - /** - * Gets the current list of color remap gradients. - * You must use addColorRemapGradient and removeColorRemapGradient to update this list - * @returns the list of color remap gradients - */ - getColorRemapGradients() { - return this._colorRemapGradients; - } - /** - * Gets the current list of alpha remap gradients. - * You must use addAlphaRemapGradient and removeAlphaRemapGradient to update this list - * @returns the list of alpha remap gradients - */ - getAlphaRemapGradients() { - return this._alphaRemapGradients; - } - /** - * Gets the current list of life time gradients. - * You must use addLifeTimeGradient and removeLifeTimeGradient to update this list - * @returns the list of life time gradients - */ - getLifeTimeGradients() { - return this._lifeTimeGradients; - } - /** - * Gets the current list of angular speed gradients. - * You must use addAngularSpeedGradient and removeAngularSpeedGradient to update this list - * @returns the list of angular speed gradients - */ - getAngularSpeedGradients() { - return this._angularSpeedGradients; - } - /** - * Gets the current list of velocity gradients. - * You must use addVelocityGradient and removeVelocityGradient to update this list - * @returns the list of velocity gradients - */ - getVelocityGradients() { - return this._velocityGradients; - } - /** - * Gets the current list of start size gradients. - * You must use addStartSizeGradient and removeStartSizeGradient to update this list - * @returns the list of start size gradients - */ - getStartSizeGradients() { - return this._startSizeGradients; - } - /** - * Gets the current list of emit rate gradients. - * You must use addEmitRateGradient and removeEmitRateGradient to update this list - * @returns the list of emit rate gradients - */ - getEmitRateGradients() { - return this._emitRateGradients; - } - /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - * This only works when particleEmitterTyps is a BoxParticleEmitter - */ - get direction1() { - if (this.particleEmitterType.direction1) { - return this.particleEmitterType.direction1; - } - return math_vector_Vector3.Zero(); - } - set direction1(value) { - if (this.particleEmitterType.direction1) { - this.particleEmitterType.direction1 = value; - } - } - /** - * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. - * This only works when particleEmitterTyps is a BoxParticleEmitter - */ - get direction2() { - if (this.particleEmitterType.direction2) { - return this.particleEmitterType.direction2; - } - return math_vector_Vector3.Zero(); - } - set direction2(value) { - if (this.particleEmitterType.direction2) { - this.particleEmitterType.direction2 = value; - } - } - /** - * 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. - * This only works when particleEmitterTyps is a BoxParticleEmitter - */ - get minEmitBox() { - if (this.particleEmitterType.minEmitBox) { - return this.particleEmitterType.minEmitBox; - } - return math_vector_Vector3.Zero(); - } - set minEmitBox(value) { - if (this.particleEmitterType.minEmitBox) { - this.particleEmitterType.minEmitBox = value; - } - } - /** - * 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. - * This only works when particleEmitterTyps is a BoxParticleEmitter - */ - get maxEmitBox() { - if (this.particleEmitterType.maxEmitBox) { - return this.particleEmitterType.maxEmitBox; - } - return math_vector_Vector3.Zero(); - } - set maxEmitBox(value) { - if (this.particleEmitterType.maxEmitBox) { - this.particleEmitterType.maxEmitBox = value; - } - } - /** - * Gets or sets the billboard mode to use when isBillboardBased = true. - * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED - */ - get billboardMode() { - return this._billboardMode; - } - set billboardMode(value) { - if (this._billboardMode === value) { - return; - } - this._billboardMode = value; - this._reset(); - } - /** - * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction - */ - get isBillboardBased() { - return this._isBillboardBased; - } - set isBillboardBased(value) { - if (this._isBillboardBased === value) { - return; - } - this._isBillboardBased = value; - this._reset(); - } - /** - * Gets the image processing configuration used either in this material. - */ - get imageProcessingConfiguration() { - return this._imageProcessingConfiguration; - } - /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ - set imageProcessingConfiguration(value) { - this._attachImageProcessingConfiguration(value); - } - /** - * Attaches a new image processing configuration to the Standard Material. - * @param configuration - */ - _attachImageProcessingConfiguration(configuration) { - if (configuration === this._imageProcessingConfiguration) { - return; - } - // Pick the scene configuration if needed. - if (!configuration && this._scene) { - this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration; - } - else { - this._imageProcessingConfiguration = configuration; - } - } - /** @internal */ - _reset() { } - /** - * @internal - */ - _removeGradientAndTexture(gradient, gradients, texture) { - if (!gradients) { - return this; - } - let index = 0; - for (const valueGradient of gradients) { - if (valueGradient.gradient === gradient) { - gradients.splice(index, 1); - break; - } - index++; - } - if (texture) { - texture.dispose(); - } - return this; - } - /** - * Instantiates a particle system. - * 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. - * @param name The name of the particle system - */ - constructor(name) { - /** - * List of animations used by the particle system. - */ - this.animations = []; - /** - * The rendering group used by the Particle system to chose when to render. - */ - this.renderingGroupId = 0; - /** - * The emitter represents the Mesh or position we are attaching the particle system to. - */ - this.emitter = math_vector_Vector3.Zero(); - /** - * The maximum number of particles to emit per frame - */ - this.emitRate = 10; - /** - * If you want to launch only a few particles at once, that can be done, as well. - */ - this.manualEmitCount = -1; - /** - * The overall motion speed (0.01 is default update speed, faster updates = faster animation) - */ - this.updateSpeed = 0.01; - /** - * The amount of time the particle system is running (depends of the overall update speed). - */ - this.targetStopDuration = 0; - /** - * Specifies whether the particle system will be disposed once it reaches the end of the animation. - */ - this.disposeOnStop = false; - /** - * Minimum power of emitting particles. - */ - this.minEmitPower = 1; - /** - * Maximum power of emitting particles. - */ - this.maxEmitPower = 1; - /** - * Minimum life time of emitting particles. - */ - this.minLifeTime = 1; - /** - * Maximum life time of emitting particles. - */ - this.maxLifeTime = 1; - /** - * Minimum Size of emitting particles. - */ - this.minSize = 1; - /** - * Maximum Size of emitting particles. - */ - this.maxSize = 1; - /** - * Minimum scale of emitting particles on X axis. - */ - this.minScaleX = 1; - /** - * Maximum scale of emitting particles on X axis. - */ - this.maxScaleX = 1; - /** - * Minimum scale of emitting particles on Y axis. - */ - this.minScaleY = 1; - /** - * Maximum scale of emitting particles on Y axis. - */ - this.maxScaleY = 1; - /** - * Gets or sets the minimal initial rotation in radians. - */ - this.minInitialRotation = 0; - /** - * Gets or sets the maximal initial rotation in radians. - */ - this.maxInitialRotation = 0; - /** - * Minimum angular speed of emitting particles (Z-axis rotation for each particle). - */ - this.minAngularSpeed = 0; - /** - * Maximum angular speed of emitting particles (Z-axis rotation for each particle). - */ - this.maxAngularSpeed = 0; - /** - * The layer mask we are rendering the particles through. - */ - this.layerMask = 0x0fffffff; - /** - * This can help using your own shader to render the particle system. - * The according effect will be created - */ - this.customShader = null; - /** - * By default particle system starts as soon as they are created. This prevents the - * automatic start to happen and let you decide when to start emitting particles. - */ - this.preventAutoStart = false; - /** @internal */ - this._wasDispatched = false; - this._rootUrl = ""; - /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */ - this.noiseStrength = new math_vector_Vector3(10, 10, 10); - /** - * Callback triggered when the particle animation is ending. - */ - this.onAnimationEnd = null; - /** - * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD. - */ - this.blendMode = BaseParticleSystem.BLENDMODE_ONEONE; - /** - * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls - * to override the particles. - */ - this.forceDepthWrite = false; - /** 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 */ - this.preWarmCycles = 0; - /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */ - this.preWarmStepOffset = 1; - /** - * 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) - */ - this.spriteCellChangeSpeed = 1; - /** - * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display - */ - this.startSpriteCellID = 0; - /** - * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display - */ - this.endSpriteCellID = 0; - /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use - */ - this.spriteCellWidth = 0; - /** - * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use - */ - this.spriteCellHeight = 0; - /** - * If using a spritesheet (isAnimationSheetEnabled), defines wether the sprite animation is looping - */ - this.spriteCellLoop = true; - /** - * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID - */ - this.spriteRandomStartCell = false; - /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */ - this.translationPivot = new math_vector_Vector2(0, 0); - /** - * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called - */ - this.beginAnimationOnStart = false; - /** - * Gets or sets the frame to start the animation from when beginAnimationOnStart is true - */ - this.beginAnimationFrom = 0; - /** - * Gets or sets the frame to end the animation on when beginAnimationOnStart is true - */ - this.beginAnimationTo = 60; - /** - * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true - */ - this.beginAnimationLoop = false; - /** - * Gets or sets a world offset applied to all particles - */ - this.worldOffset = new math_vector_Vector3(0, 0, 0); - this._useLogarithmicDepth = false; - /** - * You can use gravity if you want to give an orientation to your particles. - */ - this.gravity = math_vector_Vector3.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; - /** - * Defines the delay in milliseconds before starting the system (0 by default) - */ - this.startDelay = 0; - /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */ - this.limitVelocityDamping = 0.4; - /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors - */ - this.color1 = new math_color_Color4(1.0, 1.0, 1.0, 1.0); - /** - * Random color of each particle after it has been emitted, between color1 and color2 vectors - */ - this.color2 = new math_color_Color4(1.0, 1.0, 1.0, 1.0); - /** - * Color the particle will have at the end of its lifetime - */ - this.colorDead = new math_color_Color4(0, 0, 0, 1.0); - /** - * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel - */ - this.textureMask = new math_color_Color4(1.0, 1.0, 1.0, 1.0); - /** @internal */ - this._isSubEmitter = false; - /** @internal */ - this._billboardMode = 7; - /** @internal */ - this._isBillboardBased = true; - /** - * Local cache of defines for image processing. - */ - this._imageProcessingConfigurationDefines = new ImageProcessingConfigurationDefines(); - this.id = name; - this.name = name; - } - /** - * Creates a Point Emitter for the particle system (emits directly from the emitter position) - * @param direction1 Particles are emitted between the direction1 and direction2 from within the box - * @param direction2 Particles are emitted between the direction1 and direction2 from within the box - * @returns the emitter - */ - createPointEmitter(direction1, direction2) { - const particleEmitter = new PointParticleEmitter(); - particleEmitter.direction1 = direction1; - particleEmitter.direction2 = direction2; - this.particleEmitterType = particleEmitter; - return particleEmitter; - } - /** - * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) - * @param radius The radius of the hemisphere to emit from - * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius - * @returns the emitter - */ - createHemisphericEmitter(radius = 1, radiusRange = 1) { - const particleEmitter = new HemisphericParticleEmitter(radius, radiusRange); - this.particleEmitterType = particleEmitter; - return particleEmitter; - } - /** - * Creates a Sphere Emitter for the particle system (emits along the sphere radius) - * @param radius The radius of the sphere to emit from - * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius - * @returns the emitter - */ - createSphereEmitter(radius = 1, radiusRange = 1) { - const particleEmitter = new SphereParticleEmitter(radius, radiusRange); - this.particleEmitterType = particleEmitter; - return particleEmitter; - } - /** - * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) - * @param radius The radius of the sphere to emit from - * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere - * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere - * @returns the emitter - */ - createDirectedSphereEmitter(radius = 1, direction1 = new math_vector_Vector3(0, 1.0, 0), direction2 = new math_vector_Vector3(0, 1.0, 0)) { - const particleEmitter = new SphereDirectedParticleEmitter(radius, direction1, direction2); - this.particleEmitterType = particleEmitter; - return particleEmitter; - } - /** - * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position) - * @param radius The radius of the emission cylinder - * @param height The height of the emission cylinder - * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius - * @param directionRandomizer How much to randomize the particle direction [0-1] - * @returns the emitter - */ - createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) { - const particleEmitter = new CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer); - this.particleEmitterType = particleEmitter; - return particleEmitter; - } - /** - * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2) - * @param radius The radius of the cylinder to emit from - * @param height The height of the emission cylinder - * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) - * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder - * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder - * @returns the emitter - */ - createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new math_vector_Vector3(0, 1.0, 0), direction2 = new math_vector_Vector3(0, 1.0, 0)) { - const particleEmitter = new CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2); - this.particleEmitterType = particleEmitter; - return particleEmitter; - } - /** - * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) - * @param radius The radius of the cone to emit from - * @param angle The base angle of the cone - * @returns the emitter - */ - createConeEmitter(radius = 1, angle = Math.PI / 4) { - const particleEmitter = new ConeParticleEmitter(radius, angle); - this.particleEmitterType = particleEmitter; - return particleEmitter; - } - /** - * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) - * @param direction1 Particles are emitted between the direction1 and direction2 from within the box - * @param direction2 Particles are emitted between the direction1 and direction2 from within the box - * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox - * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox - * @returns the emitter - */ - createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) { - const particleEmitter = new BoxParticleEmitter(); - this.particleEmitterType = particleEmitter; - this.direction1 = direction1; - this.direction2 = direction2; - this.minEmitBox = minEmitBox; - this.maxEmitBox = maxEmitBox; - return particleEmitter; - } -} -/** - * Source color is added to the destination color without alpha affecting the result - */ -BaseParticleSystem.BLENDMODE_ONEONE = 0; -/** - * Blend current color and particle color using particle’s alpha - */ -BaseParticleSystem.BLENDMODE_STANDARD = 1; -/** - * Add current color and particle color multiplied by particle’s alpha - */ -BaseParticleSystem.BLENDMODE_ADD = 2; -/** - * Multiply current color with particle color - */ -BaseParticleSystem.BLENDMODE_MULTIPLY = 3; -/** - * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha - */ -BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4; -//# sourceMappingURL=baseParticleSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/colorSplitterBlock.js - - - - -/** - * Block used to expand a Color3/4 into 4 outputs (one for each component) - */ -class ColorSplitterBlock extends NodeMaterialBlock { - /** - * Create a new ColorSplitterBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, true); - this.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, true); - this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3); - this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float); - this.inputsAreExclusive = true; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ColorSplitterBlock"; - } - /** - * Gets the rgba component (input) - */ - get rgba() { - return this._inputs[0]; - } - /** - * Gets the rgb component (input) - */ - get rgbIn() { - return this._inputs[1]; - } - /** - * Gets the rgb component (output) - */ - get rgbOut() { - return this._outputs[0]; - } - /** - * Gets the r component (output) - */ - get r() { - return this._outputs[1]; - } - /** - * Gets the g component (output) - */ - get g() { - return this._outputs[2]; - } - /** - * Gets the b component (output) - */ - get b() { - return this._outputs[3]; - } - /** - * Gets the a component (output) - */ - get a() { - return this._outputs[4]; - } - _inputRename(name) { - if (name === "rgb ") { - return "rgbIn"; - } - return name; - } - _outputRename(name) { - if (name === "rgb") { - return "rgbOut"; - } - return name; - } - _buildBlock(state) { - super._buildBlock(state); - const input = this.rgba.isConnected ? this.rgba : this.rgbIn; - if (!input.isConnected) { - return; - } - const rgbOutput = this._outputs[0]; - const rOutput = this._outputs[1]; - const gOutput = this._outputs[2]; - const bOutput = this._outputs[3]; - const aOutput = this._outputs[4]; - if (rgbOutput.hasEndpoints) { - state.compilationString += this._declareOutput(rgbOutput, state) + ` = ${input.associatedVariableName}.rgb;\n`; - } - if (rOutput.hasEndpoints) { - state.compilationString += this._declareOutput(rOutput, state) + ` = ${input.associatedVariableName}.r;\n`; - } - if (gOutput.hasEndpoints) { - state.compilationString += this._declareOutput(gOutput, state) + ` = ${input.associatedVariableName}.g;\n`; - } - if (bOutput.hasEndpoints) { - state.compilationString += this._declareOutput(bOutput, state) + ` = ${input.associatedVariableName}.b;\n`; - } - if (aOutput.hasEndpoints) { - state.compilationString += this._declareOutput(aOutput, state) + ` = ${input.associatedVariableName}.a;\n`; - } - return this; - } -} -RegisterClass("BABYLON.ColorSplitterBlock", ColorSplitterBlock); -//# sourceMappingURL=colorSplitterBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetCube.js - - - - -ThinEngine.prototype.createRenderTargetCubeTexture = function (size, options) { - const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size); - const fullOptions = Object.assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: 0, samplingMode: 3, format: 5 }, options); - fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer; - if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) { - // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE - fullOptions.samplingMode = 1; - } - else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) { - // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE - fullOptions.samplingMode = 1; - } - const gl = this._gl; - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.RenderTarget); - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); - const filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps); - if (fullOptions.type === 1 && !this._caps.textureFloat) { - fullOptions.type = 0; - logger_Logger.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type"); - } - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - for (let face = 0; face < 6; face++) { - 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); - } - // Create the framebuffer - const framebuffer = gl.createFramebuffer(); - this._bindUnboundFramebuffer(framebuffer); - rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size); - // MipMaps - if (fullOptions.generateMipMaps) { - gl.generateMipmap(gl.TEXTURE_CUBE_MAP); - } - // Unbind - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); - this._bindUnboundFramebuffer(null); - rtWrapper._framebuffer = framebuffer; - rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer; - rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer; - texture.width = size; - texture.height = size; - texture.isReady = true; - texture.isCube = true; - texture.samples = 1; - texture.generateMipMaps = fullOptions.generateMipMaps; - texture.samplingMode = fullOptions.samplingMode; - texture.type = fullOptions.type; - texture.format = fullOptions.format; - this._internalTexturesCache.push(texture); - rtWrapper.setTextures(texture); - return rtWrapper; -}; -//# sourceMappingURL=engine.renderTargetCube.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/effectRenderer.js - - - - - - -// Prevents ES6 Crash if not imported. - -// Fullscreen quad buffers by default. -const defaultOptions = { - positions: [1, 1, -1, 1, -1, -1, 1, -1], - indices: [0, 1, 2, 0, 2, 3], -}; -/** - * Helper class to render one or more effects. - * You can access the previous rendering in your shader by declaring a sampler named textureSampler - */ -class EffectRenderer { - /** - * Creates an effect renderer - * @param engine the engine to use for rendering - * @param options defines the options of the effect renderer - */ - constructor(engine, options = defaultOptions) { - var _a, _b; - this._fullscreenViewport = new math_viewport_Viewport(0, 0, 1, 1); - const positions = (_a = options.positions) !== null && _a !== void 0 ? _a : defaultOptions.positions; - const indices = (_b = options.indices) !== null && _b !== void 0 ? _b : defaultOptions.indices; - this.engine = engine; - this._vertexBuffers = { - [buffer_VertexBuffer.PositionKind]: new buffer_VertexBuffer(engine, positions, buffer_VertexBuffer.PositionKind, false, false, 2), - }; - this._indexBuffer = engine.createIndexBuffer(indices); - this._onContextRestoredObserver = engine.onContextRestoredObservable.add(() => { - this._indexBuffer = engine.createIndexBuffer(indices); - for (const key in this._vertexBuffers) { - const vertexBuffer = this._vertexBuffers[key]; - vertexBuffer._rebuild(); - } - }); - } - /** - * Sets the current viewport in normalized coordinates 0-1 - * @param viewport Defines the viewport to set (defaults to 0 0 1 1) - */ - setViewport(viewport = this._fullscreenViewport) { - this.engine.setViewport(viewport); - } - /** - * Binds the embedded attributes buffer to the effect. - * @param effect Defines the effect to bind the attributes for - */ - bindBuffers(effect) { - this.engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); - } - /** - * Sets the current effect wrapper to use during draw. - * The effect needs to be ready before calling this api. - * This also sets the default full screen position attribute. - * @param effectWrapper Defines the effect to draw with - */ - applyEffectWrapper(effectWrapper) { - this.engine.setState(true); - this.engine.depthCullingState.depthTest = false; - this.engine.stencilState.stencilTest = false; - this.engine.enableEffect(effectWrapper._drawWrapper); - this.bindBuffers(effectWrapper.effect); - effectWrapper.onApplyObservable.notifyObservers({}); - } - /** - * Saves engine states - */ - saveStates() { - this._savedStateDepthTest = this.engine.depthCullingState.depthTest; - this._savedStateStencilTest = this.engine.stencilState.stencilTest; - } - /** - * Restores engine states - */ - restoreStates() { - this.engine.depthCullingState.depthTest = this._savedStateDepthTest; - this.engine.stencilState.stencilTest = this._savedStateStencilTest; - } - /** - * Draws a full screen quad. - */ - draw() { - this.engine.drawElementsType(0, 0, 6); - } - _isRenderTargetTexture(texture) { - return texture.renderTarget !== undefined; - } - /** - * renders one or more effects to a specified texture - * @param effectWrapper the effect to renderer - * @param outputTexture texture to draw to, if null it will render to the screen. - */ - render(effectWrapper, outputTexture = null) { - // Ensure effect is ready - if (!effectWrapper.effect.isReady()) { - return; - } - this.saveStates(); - // Reset state - this.setViewport(); - const out = outputTexture === null ? null : this._isRenderTargetTexture(outputTexture) ? outputTexture.renderTarget : outputTexture; - if (out) { - this.engine.bindFramebuffer(out); - } - this.applyEffectWrapper(effectWrapper); - this.draw(); - if (out) { - this.engine.unBindFramebuffer(out); - } - this.restoreStates(); - } - /** - * Disposes of the effect renderer - */ - dispose() { - const vertexBuffer = this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - if (vertexBuffer) { - vertexBuffer.dispose(); - delete this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - } - if (this._indexBuffer) { - this.engine._releaseBuffer(this._indexBuffer); - } - if (this._onContextRestoredObserver) { - this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver); - this._onContextRestoredObserver = null; - } - } -} -/** - * Wraps an effect to be used for rendering - */ -class EffectWrapper { - /** - * The underlying effect - */ - get effect() { - return this._drawWrapper.effect; - } - set effect(effect) { - this._drawWrapper.effect = effect; - } - /** - * Creates an effect to be renderer - * @param creationOptions options to create the effect - */ - constructor(creationOptions) { - /** - * Event that is fired right before the effect is drawn (should be used to update uniforms) - */ - this.onApplyObservable = new observable_Observable(); - let effectCreationOptions; - const uniformNames = creationOptions.uniformNames || []; - if (creationOptions.vertexShader) { - effectCreationOptions = { - fragmentSource: creationOptions.fragmentShader, - vertexSource: creationOptions.vertexShader, - spectorName: creationOptions.name || "effectWrapper", - }; - } - else { - // Default scale to use in post process vertex shader. - uniformNames.push("scale"); - effectCreationOptions = { - fragmentSource: creationOptions.fragmentShader, - vertex: "postprocess", - spectorName: creationOptions.name || "effectWrapper", - }; - // Sets the default scale to identity for the post process vertex shader. - this.onApplyObservable.add(() => { - this.effect.setFloat2("scale", 1, 1); - }); - } - const defines = creationOptions.defines ? creationOptions.defines.join("\n") : ""; - this._drawWrapper = new drawWrapper_DrawWrapper(creationOptions.engine); - if (creationOptions.useShaderStore) { - effectCreationOptions.fragment = effectCreationOptions.fragmentSource; - if (!effectCreationOptions.vertex) { - effectCreationOptions.vertex = effectCreationOptions.vertexSource; - } - delete effectCreationOptions.fragmentSource; - delete effectCreationOptions.vertexSource; - this.effect = creationOptions.engine.createEffect(effectCreationOptions, creationOptions.attributeNames || ["position"], uniformNames, creationOptions.samplerNames, defines, undefined, creationOptions.onCompiled, undefined, undefined, creationOptions.shaderLanguage); - } - else { - this.effect = new effect_Effect(effectCreationOptions, creationOptions.attributeNames || ["position"], uniformNames, creationOptions.samplerNames, creationOptions.engine, defines, undefined, creationOptions.onCompiled, undefined, undefined, undefined, creationOptions.shaderLanguage); - this._onContextRestoredObserver = creationOptions.engine.onContextRestoredObservable.add(() => { - this.effect._pipelineContext = null; // because _prepareEffect will try to dispose this pipeline before recreating it and that would lead to webgl errors - this.effect._wasPreviouslyReady = false; - this.effect._prepareEffect(); - }); - } - } - /** - * Disposes of the effect wrapper - */ - dispose() { - if (this._onContextRestoredObserver) { - this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver); - this._onContextRestoredObserver = null; - } - this.effect.dispose(); - } -} -//# sourceMappingURL=effectRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/pass.fragment.js -// Do not edit. - -const pass_fragment_name = "passPixelShader"; -const pass_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);}`; -// Sideeffect -ShaderStore.ShadersStore[pass_fragment_name] = pass_fragment_shader; -/** @internal */ -const passPixelShader = { name: pass_fragment_name, shader: pass_fragment_shader }; -//# sourceMappingURL=pass.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/dumpTools.js - - - - - - -/** - * Class containing a set of static utilities functions to dump data from a canvas - */ -class DumpTools { - static _CreateDumpRenderer() { - if (!DumpTools._DumpToolsEngine) { - let canvas = new OffscreenCanvas(100, 100); // will be resized later - let engine = null; - const options = { - preserveDrawingBuffer: true, - depth: false, - stencil: false, - alpha: true, - premultipliedAlpha: false, - antialias: false, - failIfMajorPerformanceCaveat: false, - }; - try { - engine = new ThinEngine(canvas, false, options); - } - catch (e) { - // The browser does not support WebGL context in OffscreenCanvas, fallback on a regular canvas - canvas = document.createElement("canvas"); - engine = new ThinEngine(canvas, false, options); - } - engine.getCaps().parallelShaderCompile = undefined; - const renderer = new EffectRenderer(engine); - const wrapper = new EffectWrapper({ - engine, - name: passPixelShader.name, - fragmentShader: passPixelShader.shader, - samplerNames: ["textureSampler"], - }); - DumpTools._DumpToolsEngine = { - canvas, - engine, - renderer, - wrapper, - }; - } - return DumpTools._DumpToolsEngine; - } - /** - * Dumps the current bound framebuffer - * @param width defines the rendering width - * @param height defines the rendering height - * @param engine defines the hosting engine - * @param successCallback defines the callback triggered once the data are available - * @param mimeType defines the mime type of the result - * @param fileName defines the filename to download. If present, the result will automatically be downloaded - * @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. - * @returns a void promise - */ - static async DumpFramebuffer(width, height, engine, successCallback, mimeType = "image/png", fileName, quality) { - // Read the contents of the framebuffer - const bufferView = await engine.readPixels(0, 0, width, height); - const data = new Uint8Array(bufferView.buffer); - DumpTools.DumpData(width, height, data, successCallback, mimeType, fileName, true, undefined, quality); - } - /** - * Dumps an array buffer - * @param width defines the rendering width - * @param height defines the rendering height - * @param data the data array - * @param mimeType defines the mime type of the result - * @param fileName defines the filename to download. If present, the result will automatically be downloaded - * @param invertY true to invert the picture in the Y dimension - * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string - * @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. - * @returns a promise that resolve to the final data - */ - static DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { - return new Promise((resolve) => { - DumpTools.DumpData(width, height, data, (result) => resolve(result), mimeType, fileName, invertY, toArrayBuffer, quality); - }); - } - /** - * Dumps an array buffer - * @param width defines the rendering width - * @param height defines the rendering height - * @param data the data array - * @param successCallback defines the callback triggered once the data are available - * @param mimeType defines the mime type of the result - * @param fileName defines the filename to download. If present, the result will automatically be downloaded - * @param invertY true to invert the picture in the Y dimension - * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string - * @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. - */ - static DumpData(width, height, data, successCallback, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { - const renderer = DumpTools._CreateDumpRenderer(); - renderer.engine.setSize(width, height, true); - // Convert if data are float32 - if (data instanceof Float32Array) { - const data2 = new Uint8Array(data.length); - let n = data.length; - while (n--) { - const v = data[n]; - data2[n] = Math.round(math_scalar_Scalar.Clamp(v) * 255); - } - data = data2; - } - // Create the image - const texture = renderer.engine.createRawTexture(data, width, height, 5, false, !invertY, 1); - renderer.renderer.setViewport(); - renderer.renderer.applyEffectWrapper(renderer.wrapper); - renderer.wrapper.effect._bindTexture("textureSampler", texture); - renderer.renderer.draw(); - if (toArrayBuffer) { - tools_Tools.ToBlob(renderer.canvas, (blob) => { - const fileReader = new FileReader(); - fileReader.onload = (event) => { - const arrayBuffer = event.target.result; - if (successCallback) { - successCallback(arrayBuffer); - } - }; - fileReader.readAsArrayBuffer(blob); - }, mimeType, quality); - } - else { - tools_Tools.EncodeScreenshotCanvasData(renderer.canvas, successCallback, mimeType, fileName, quality); - } - texture.dispose(); - } - /** - * Dispose the dump tools associated resources - */ - static Dispose() { - if (DumpTools._DumpToolsEngine) { - DumpTools._DumpToolsEngine.wrapper.dispose(); - DumpTools._DumpToolsEngine.renderer.dispose(); - DumpTools._DumpToolsEngine.engine.dispose(); - } - DumpTools._DumpToolsEngine = null; - } -} -/** - * This will be executed automatically for UMD and es5. - * If esm dev wants the side effects to execute they will have to run it manually - * Once we build native modules those need to be exported. - * @internal - */ -const dumpTools_initSideEffects = () => { - // References the dependencies. - tools_Tools.DumpData = DumpTools.DumpData; - tools_Tools.DumpDataAsync = DumpTools.DumpDataAsync; - tools_Tools.DumpFramebuffer = DumpTools.DumpFramebuffer; -}; -dumpTools_initSideEffects(); -//# sourceMappingURL=dumpTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/renderTargetTexture.js - - - - - - - - - - - -/** - * This Helps creating a texture that will be created from a camera in your scene. - * It is basically a dynamic texture that could be used to create special effects for instance. - * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines... - */ -class renderTargetTexture_RenderTargetTexture extends texture_Texture { - /** - * Use this list to define the list of mesh you want to render. - */ - get renderList() { - return this._renderList; - } - set renderList(value) { - if (this._unObserveRenderList) { - this._unObserveRenderList(); - this._unObserveRenderList = null; - } - if (value) { - this._unObserveRenderList = _ObserveArray(value, this._renderListHasChanged); - } - this._renderList = value; - } - /** - * Post-processes for this render target - */ - get postProcesses() { - return this._postProcesses; - } - get _prePassEnabled() { - return !!this._prePassRenderTarget && this._prePassRenderTarget.enabled; - } - /** - * Set a after unbind callback in the texture. - * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended. - */ - set onAfterUnbind(callback) { - if (this._onAfterUnbindObserver) { - this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver); - } - this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback); - } - /** - * Set a before render callback in the texture. - * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended. - */ - set onBeforeRender(callback) { - if (this._onBeforeRenderObserver) { - this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); - } - this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); - } - /** - * Set a after render callback in the texture. - * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended. - */ - set onAfterRender(callback) { - if (this._onAfterRenderObserver) { - this.onAfterRenderObservable.remove(this._onAfterRenderObserver); - } - this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); - } - /** - * Set a clear callback in the texture. - * This has been kept for backward compatibility and use of onClearObservable is recommended. - */ - set onClear(callback) { - if (this._onClearObserver) { - this.onClearObservable.remove(this._onClearObserver); - } - this._onClearObserver = this.onClearObservable.add(callback); - } - /** - * 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 - * a 2D texture array it will return an array of ids the size of the 2D texture array - */ - get renderPassIds() { - return this._renderPassIds; - } - /** - * Gets the current value of the refreshId counter - */ - get currentRefreshId() { - return this._currentRefreshId; - } - /** - * Sets a specific material to be used to render a mesh/a list of meshes in this render target texture - * @param mesh mesh or array of meshes - * @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) - */ - setMaterialForRendering(mesh, material) { - let meshes; - if (!Array.isArray(mesh)) { - meshes = [mesh]; - } - else { - meshes = mesh; - } - for (let j = 0; j < meshes.length; ++j) { - for (let i = 0; i < this._renderPassIds.length; ++i) { - meshes[j].setMaterialForRenderPass(this._renderPassIds[i], material !== undefined ? (Array.isArray(material) ? material[i] : material) : undefined); - } - } - } - /** - * Define if the texture has multiple draw buffers or if false a single draw buffer. - */ - get isMulti() { - var _a, _b; - return (_b = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.isMulti) !== null && _b !== void 0 ? _b : false; - } - /** - * Gets render target creation options that were used. - */ - get renderTargetOptions() { - return this._renderTargetOptions; - } - /** - * Gets the render target wrapper associated with this render target - */ - get renderTarget() { - return this._renderTarget; - } - _onRatioRescale() { - if (this._sizeRatio) { - this.resize(this._initialSizeParameter); - } - } - /** - * Gets or sets the size of the bounding box associated with the texture (when in cube mode) - * When defined, the cubemap will switch to local mode - * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity - * @example https://www.babylonjs-playground.com/#RNASML - */ - set boundingBoxSize(value) { - if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { - return; - } - this._boundingBoxSize = value; - const scene = this.getScene(); - if (scene) { - scene.markAllMaterialsAsDirty(1); - } - } - get boundingBoxSize() { - return this._boundingBoxSize; - } - /** - * In case the RTT has been created with a depth texture, get the associated - * depth texture. - * Otherwise, return null. - */ - get depthStencilTexture() { - var _a, _b; - return (_b = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a._depthStencilTexture) !== null && _b !== void 0 ? _b : null; - } - /** @internal */ - constructor(name, size, scene, generateMipMaps = false, doNotChangeAspectRatio = true, type = 0, isCube = false, samplingMode = texture_Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false, format = 5, delayAllocation = false, samples, creationFlags, noColorAttachment = false, useSRGBBuffer = false) { - var _a, _b, _c, _d, _e, _f; - let colorAttachment = undefined; - if (typeof generateMipMaps === "object") { - const options = generateMipMaps; - generateMipMaps = !!options.generateMipMaps; - doNotChangeAspectRatio = (_a = options.doNotChangeAspectRatio) !== null && _a !== void 0 ? _a : true; - type = (_b = options.type) !== null && _b !== void 0 ? _b : 0; - isCube = !!options.isCube; - samplingMode = (_c = options.samplingMode) !== null && _c !== void 0 ? _c : texture_Texture.TRILINEAR_SAMPLINGMODE; - generateDepthBuffer = (_d = options.generateDepthBuffer) !== null && _d !== void 0 ? _d : true; - generateStencilBuffer = !!options.generateStencilBuffer; - isMulti = !!options.isMulti; - format = (_e = options.format) !== null && _e !== void 0 ? _e : 5; - delayAllocation = !!options.delayAllocation; - samples = options.samples; - creationFlags = options.creationFlags; - noColorAttachment = !!options.noColorAttachment; - useSRGBBuffer = !!options.useSRGBBuffer; - colorAttachment = options.colorAttachment; - } - super(null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format); - this._unObserveRenderList = null; - this._renderListHasChanged = (_functionName, previousLength) => { - var _a; - const newLength = this._renderList ? this._renderList.length : 0; - if ((previousLength === 0 && newLength > 0) || newLength === 0) { - (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.meshes.forEach((mesh) => { - mesh._markSubMeshesAsLightDirty(); - }); - } - }; - /** - * Define if particles should be rendered in your texture. - */ - this.renderParticles = true; - /** - * Define if sprites should be rendered in your texture. - */ - this.renderSprites = false; - /** - * Force checking the layerMask property even if a custom list of meshes is provided (ie. if renderList is not undefined) - */ - this.forceLayerMaskCheck = false; - /** - * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture. - */ - this.ignoreCameraViewport = false; - /** - * An event triggered when the texture is unbind. - */ - this.onBeforeBindObservable = new observable_Observable(); - /** - * An event triggered when the texture is unbind. - */ - this.onAfterUnbindObservable = new observable_Observable(); - /** - * An event triggered before rendering the texture - */ - this.onBeforeRenderObservable = new observable_Observable(); - /** - * An event triggered after rendering the texture - */ - this.onAfterRenderObservable = new observable_Observable(); - /** - * An event triggered after the texture clear - */ - this.onClearObservable = new observable_Observable(); - /** - * An event triggered when the texture is resized. - */ - this.onResizeObservable = new observable_Observable(); - /** @internal */ - this._cleared = false; - /** - * Skip the initial clear of the rtt at the beginning of the frame render loop - */ - this.skipInitialClear = false; - this._currentRefreshId = -1; - this._refreshRate = 1; - this._samples = 1; - this._canRescale = true; - this._renderTarget = null; - /** - * Gets or sets the center of the bounding box associated with the texture (when in cube mode) - * It must define where the camera used to render the texture is set - */ - this.boundingBoxPosition = math_vector_Vector3.Zero(); - scene = this.getScene(); - if (!scene) { - return; - } - const engine = this.getScene().getEngine(); - this._coordinatesMode = texture_Texture.PROJECTION_MODE; - this.renderList = new Array(); - this.name = name; - this.isRenderTarget = true; - this._initialSizeParameter = size; - this._renderPassIds = []; - this._isCubeData = isCube; - this._processSizeParameter(size); - this.renderPassId = this._renderPassIds[0]; - this._resizeObserver = engine.onResizeObservable.add(() => { }); - this._generateMipMaps = generateMipMaps ? true : false; - this._doNotChangeAspectRatio = doNotChangeAspectRatio; - // Rendering groups - this._renderingManager = new RenderingManager(scene); - this._renderingManager._useSceneAutoClearSetup = true; - if (isMulti) { - return; - } - this._renderTargetOptions = { - generateMipMaps: generateMipMaps, - type: type, - format: (_f = this._format) !== null && _f !== void 0 ? _f : undefined, - samplingMode: this.samplingMode, - generateDepthBuffer: generateDepthBuffer, - generateStencilBuffer: generateStencilBuffer, - samples, - creationFlags, - noColorAttachment: noColorAttachment, - useSRGBBuffer, - colorAttachment: colorAttachment, - label: this.name, - }; - if (this.samplingMode === texture_Texture.NEAREST_SAMPLINGMODE) { - this.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - } - if (!delayAllocation) { - if (isCube) { - this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions); - this.coordinatesMode = texture_Texture.INVCUBIC_MODE; - this._textureMatrix = math_vector_Matrix.Identity(); - } - else { - this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions); - } - this._texture = this._renderTarget.texture; - if (samples !== undefined) { - this.samples = samples; - } - } - } - /** - * Creates a depth stencil texture. - * This is only available in WebGL 2 or with the depth texture extension available. - * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode (default: 0) - * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture (default: true) - * @param generateStencil Specifies whether or not a stencil should be allocated in the texture (default: false) - * @param samples sample count of the depth/stencil texture (default: 1) - * @param format format of the depth texture (default: 14) - */ - createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14) { - var _a; - (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.createDepthStencilTexture(comparisonFunction, bilinearFiltering, generateStencil, samples, format); - } - _releaseRenderPassId() { - if (this._scene) { - const engine = this._scene.getEngine(); - for (let i = 0; i < this._renderPassIds.length; ++i) { - engine.releaseRenderPassId(this._renderPassIds[i]); - } - } - this._renderPassIds = []; - } - _createRenderPassId() { - this._releaseRenderPassId(); - const engine = this._scene.getEngine(); // scene can't be null in a RenderTargetTexture, see constructor - const numPasses = this._isCubeData ? 6 : this.getRenderLayers() || 1; - for (let i = 0; i < numPasses; ++i) { - this._renderPassIds[i] = engine.createRenderPassId(`RenderTargetTexture - ${this.name}#${i}`); - } - } - _processSizeParameter(size, createRenderPassIds = true) { - if (size.ratio) { - this._sizeRatio = size.ratio; - const engine = this._getEngine(); - this._size = { - width: this._bestReflectionRenderTargetDimension(engine.getRenderWidth(), this._sizeRatio), - height: this._bestReflectionRenderTargetDimension(engine.getRenderHeight(), this._sizeRatio), - }; - } - else { - this._size = size; - } - if (createRenderPassIds) { - this._createRenderPassId(); - } - } - /** - * Define the number of samples to use in case of MSAA. - * It defaults to one meaning no MSAA has been enabled. - */ - get samples() { - var _a, _b; - return (_b = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.samples) !== null && _b !== void 0 ? _b : this._samples; - } - set samples(value) { - if (this._renderTarget) { - this._samples = this._renderTarget.setSamples(value); - } - } - /** - * Resets the refresh counter of the texture and start bak from scratch. - * Could be useful to regenerate the texture if it is setup to render only once. - */ - resetRefreshCounter() { - this._currentRefreshId = -1; - } - /** - * Define the refresh rate of the texture or the rendering frequency. - * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... - */ - get refreshRate() { - return this._refreshRate; - } - set refreshRate(value) { - this._refreshRate = value; - this.resetRefreshCounter(); - } - /** - * Adds a post process to the render target rendering passes. - * @param postProcess define the post process to add - */ - addPostProcess(postProcess) { - if (!this._postProcessManager) { - const scene = this.getScene(); - if (!scene) { - return; - } - this._postProcessManager = new PostProcessManager(scene); - this._postProcesses = new Array(); - } - this._postProcesses.push(postProcess); - this._postProcesses[0].autoClear = false; - } - /** - * Clear all the post processes attached to the render target - * @param dispose define if the cleared post processes should also be disposed (false by default) - */ - clearPostProcesses(dispose = false) { - if (!this._postProcesses) { - return; - } - if (dispose) { - for (const postProcess of this._postProcesses) { - postProcess.dispose(); - } - } - this._postProcesses = []; - } - /** - * Remove one of the post process from the list of attached post processes to the texture - * @param postProcess define the post process to remove from the list - */ - removePostProcess(postProcess) { - if (!this._postProcesses) { - return; - } - const index = this._postProcesses.indexOf(postProcess); - if (index === -1) { - return; - } - this._postProcesses.splice(index, 1); - if (this._postProcesses.length > 0) { - this._postProcesses[0].autoClear = false; - } - } - /** @internal */ - _shouldRender() { - if (this._currentRefreshId === -1) { - // At least render once - this._currentRefreshId = 1; - return true; - } - if (this.refreshRate === this._currentRefreshId) { - this._currentRefreshId = 1; - return true; - } - this._currentRefreshId++; - return false; - } - /** - * Gets the actual render size of the texture. - * @returns the width of the render size - */ - getRenderSize() { - return this.getRenderWidth(); - } - /** - * Gets the actual render width of the texture. - * @returns the width of the render size - */ - getRenderWidth() { - if (this._size.width) { - return this._size.width; - } - return this._size; - } - /** - * Gets the actual render height of the texture. - * @returns the height of the render size - */ - getRenderHeight() { - if (this._size.width) { - return this._size.height; - } - return this._size; - } - /** - * Gets the actual number of layers of the texture. - * @returns the number of layers - */ - getRenderLayers() { - const layers = this._size.layers; - if (layers) { - return layers; - } - return 0; - } - /** - * Don't allow this render target texture to rescale. Mainly used to prevent rescaling by the scene optimizer. - */ - disableRescaling() { - this._canRescale = false; - } - /** - * Get if the texture can be rescaled or not. - */ - get canRescale() { - return this._canRescale; - } - /** - * Resize the texture using a ratio. - * @param ratio the ratio to apply to the texture size in order to compute the new target size - */ - scale(ratio) { - const newSize = Math.max(1, this.getRenderSize() * ratio); - this.resize(newSize); - } - /** - * Get the texture reflection matrix used to rotate/transform the reflection. - * @returns the reflection matrix - */ - getReflectionTextureMatrix() { - if (this.isCube) { - return this._textureMatrix; - } - return super.getReflectionTextureMatrix(); - } - /** - * Resize the texture to a new desired size. - * Be careful as it will recreate all the data in the new texture. - * @param size Define the new size. It can be: - * - a number for squared texture, - * - an object containing { width: number, height: number } - * - or an object containing a ratio { ratio: number } - */ - resize(size) { - var _a; - const wasCube = this.isCube; - (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose(); - this._renderTarget = null; - const scene = this.getScene(); - if (!scene) { - return; - } - this._processSizeParameter(size, false); - if (wasCube) { - this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions); - } - else { - this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions); - } - this._texture = this._renderTarget.texture; - if (this._renderTargetOptions.samples !== undefined) { - this.samples = this._renderTargetOptions.samples; - } - if (this.onResizeObservable.hasObservers()) { - this.onResizeObservable.notifyObservers(this); - } - } - /** - * Renders all the objects from the render list into the texture. - * @param useCameraPostProcess Define if camera post processes should be used during the rendering - * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose - */ - render(useCameraPostProcess = false, dumpForDebug = false) { - this._render(useCameraPostProcess, dumpForDebug); - } - /** - * This function will check if the render target texture can be rendered (textures are loaded, shaders are compiled) - * @returns true if all required resources are ready - */ - isReadyForRendering() { - return this._render(false, false, true); - } - _render(useCameraPostProcess = false, dumpForDebug = false, checkReadiness = false) { - var _a; - const scene = this.getScene(); - if (!scene) { - return checkReadiness; - } - const engine = scene.getEngine(); - if (this.useCameraPostProcesses !== undefined) { - useCameraPostProcess = this.useCameraPostProcesses; - } - if (this._waitingRenderList) { - this.renderList = []; - for (let index = 0; index < this._waitingRenderList.length; index++) { - const id = this._waitingRenderList[index]; - const mesh = scene.getMeshById(id); - if (mesh) { - this.renderList.push(mesh); - } - } - this._waitingRenderList = undefined; - } - // Is predicate defined? - if (this.renderListPredicate) { - if (this.renderList) { - this.renderList.length = 0; // Clear previous renderList - } - else { - this.renderList = []; - } - const scene = this.getScene(); - if (!scene) { - return checkReadiness; - } - const sceneMeshes = scene.meshes; - for (let index = 0; index < sceneMeshes.length; index++) { - const mesh = sceneMeshes[index]; - if (this.renderListPredicate(mesh)) { - this.renderList.push(mesh); - } - } - } - const currentRenderPassId = engine.currentRenderPassId; - this.onBeforeBindObservable.notifyObservers(this); - // Set custom projection. - // Needs to be before binding to prevent changing the aspect ratio. - const camera = (_a = this.activeCamera) !== null && _a !== void 0 ? _a : scene.activeCamera; - const sceneCamera = scene.activeCamera; - if (camera) { - if (camera !== scene.activeCamera) { - scene.setTransformMatrix(camera.getViewMatrix(), camera.getProjectionMatrix(true)); - scene.activeCamera = camera; - } - engine.setViewport(camera.rigParent ? camera.rigParent.viewport : camera.viewport, this.getRenderWidth(), this.getRenderHeight()); - } - this._defaultRenderListPrepared = false; - let returnValue = checkReadiness; - if (!checkReadiness) { - if (this.is2DArray && !this.isMulti) { - for (let layer = 0; layer < this.getRenderLayers(); layer++) { - this._renderToTarget(0, useCameraPostProcess, dumpForDebug, layer, camera); - scene.incrementRenderId(); - scene.resetCachedMaterial(); - } - } - else if (this.isCube && !this.isMulti) { - for (let face = 0; face < 6; face++) { - this._renderToTarget(face, useCameraPostProcess, dumpForDebug, undefined, camera); - scene.incrementRenderId(); - scene.resetCachedMaterial(); - } - } - else { - this._renderToTarget(0, useCameraPostProcess, dumpForDebug, undefined, camera); - } - } - else { - if (!scene.getViewMatrix()) { - // We probably didn't execute scene.render() yet, so make sure we have a view/projection matrix setup for the scene - scene.updateTransformMatrix(); - } - const numLayers = this.is2DArray ? this.getRenderLayers() : this.isCube ? 6 : 1; - for (let layer = 0; layer < numLayers && returnValue; layer++) { - let currentRenderList = null; - const defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data; - const defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length; - engine.currentRenderPassId = this._renderPassIds[layer]; - this.onBeforeRenderObservable.notifyObservers(layer); - if (this.getCustomRenderList) { - currentRenderList = this.getCustomRenderList(layer, defaultRenderList, defaultRenderListLength); - } - if (!currentRenderList) { - currentRenderList = defaultRenderList; - } - if (!this._doNotChangeAspectRatio) { - scene.updateTransformMatrix(true); - } - for (let i = 0; i < currentRenderList.length && returnValue; ++i) { - const mesh = currentRenderList[i]; - if (!mesh.isEnabled() || mesh.isBlocked || !mesh.isVisible || !mesh.subMeshes) { - continue; - } - if (this.customIsReadyFunction) { - if (!this.customIsReadyFunction(mesh, this.refreshRate, checkReadiness)) { - returnValue = false; - continue; - } - } - else if (!mesh.isReady(true)) { - returnValue = false; - continue; - } - } - this.onAfterRenderObservable.notifyObservers(layer); - if (this.is2DArray || this.isCube) { - scene.incrementRenderId(); - scene.resetCachedMaterial(); - } - } - } - this.onAfterUnbindObservable.notifyObservers(this); - engine.currentRenderPassId = currentRenderPassId; - if (sceneCamera) { - scene.activeCamera = sceneCamera; - // Do not avoid setting uniforms when multiple scenes are active as another camera may have overwrite these - if (scene.getEngine().scenes.length > 1 || (this.activeCamera && this.activeCamera !== scene.activeCamera)) { - scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true)); - } - engine.setViewport(scene.activeCamera.viewport); - } - scene.resetCachedMaterial(); - return returnValue; - } - _bestReflectionRenderTargetDimension(renderDimension, scale) { - const minimum = 128; - const x = renderDimension * scale; - const curved = engine_Engine.NearestPOT(x + (minimum * minimum) / (minimum + x)); - // Ensure we don't exceed the render dimension (while staying POT) - return Math.min(engine_Engine.FloorPOT(renderDimension), curved); - } - _prepareRenderingManager(currentRenderList, currentRenderListLength, camera, checkLayerMask) { - const scene = this.getScene(); - if (!scene) { - return; - } - this._renderingManager.reset(); - const sceneRenderId = scene.getRenderId(); - for (let meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) { - const mesh = currentRenderList[meshIndex]; - if (mesh && !mesh.isBlocked) { - if (this.customIsReadyFunction) { - if (!this.customIsReadyFunction(mesh, this.refreshRate, false)) { - this.resetRefreshCounter(); - continue; - } - } - else if (!mesh.isReady(this.refreshRate === 0)) { - this.resetRefreshCounter(); - continue; - } - if (!mesh._internalAbstractMeshDataInfo._currentLODIsUpToDate && scene.activeCamera) { - mesh._internalAbstractMeshDataInfo._currentLOD = scene.customLODSelector - ? scene.customLODSelector(mesh, this.activeCamera || scene.activeCamera) - : mesh.getLOD(this.activeCamera || scene.activeCamera); - mesh._internalAbstractMeshDataInfo._currentLODIsUpToDate = true; - } - if (!mesh._internalAbstractMeshDataInfo._currentLOD) { - continue; - } - let meshToRender = mesh._internalAbstractMeshDataInfo._currentLOD; - meshToRender._preActivateForIntermediateRendering(sceneRenderId); - let isMasked; - if (checkLayerMask && camera) { - isMasked = (mesh.layerMask & camera.layerMask) === 0; - } - else { - isMasked = false; - } - if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) { - if (meshToRender !== mesh) { - meshToRender._activate(sceneRenderId, true); - } - if (mesh._activate(sceneRenderId, true) && mesh.subMeshes.length) { - if (!mesh.isAnInstance) { - meshToRender._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = false; - } - else { - if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) { - meshToRender = mesh; - } - } - meshToRender._internalAbstractMeshDataInfo._isActiveIntermediate = true; - for (let subIndex = 0; subIndex < meshToRender.subMeshes.length; subIndex++) { - const subMesh = meshToRender.subMeshes[subIndex]; - this._renderingManager.dispatch(subMesh, meshToRender); - } - } - } - } - } - for (let particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) { - const particleSystem = scene.particleSystems[particleIndex]; - const emitter = particleSystem.emitter; - if (!particleSystem.isStarted() || !emitter || (emitter.position && !emitter.isEnabled())) { - continue; - } - this._renderingManager.dispatchParticles(particleSystem); - } - } - /** - * @internal - * @param faceIndex face index to bind to if this is a cubetexture - * @param layer defines the index of the texture to bind in the array - */ - _bindFrameBuffer(faceIndex = 0, layer = 0) { - const scene = this.getScene(); - if (!scene) { - return; - } - const engine = scene.getEngine(); - if (this._renderTarget) { - engine.bindFramebuffer(this._renderTarget, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, 0, layer); - } - } - _unbindFrameBuffer(engine, faceIndex) { - if (!this._renderTarget) { - return; - } - engine.unBindFramebuffer(this._renderTarget, this.isCube, () => { - this.onAfterRenderObservable.notifyObservers(faceIndex); - }); - } - /** - * @internal - */ - _prepareFrame(scene, faceIndex, layer, useCameraPostProcess) { - if (this._postProcessManager) { - if (!this._prePassEnabled) { - this._postProcessManager._prepareFrame(this._texture, this._postProcesses); - } - } - else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) { - this._bindFrameBuffer(faceIndex, layer); - } - } - _renderToTarget(faceIndex, useCameraPostProcess, dumpForDebug, layer = 0, camera = null) { - var _a, _b, _c, _d, _e, _f; - const scene = this.getScene(); - if (!scene) { - return; - } - const engine = scene.getEngine(); - (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `render to face #${faceIndex} layer #${layer}`, 1); - // Bind - this._prepareFrame(scene, faceIndex, layer, useCameraPostProcess); - if (this.is2DArray) { - engine.currentRenderPassId = this._renderPassIds[layer]; - this.onBeforeRenderObservable.notifyObservers(layer); - } - else { - engine.currentRenderPassId = this._renderPassIds[faceIndex]; - this.onBeforeRenderObservable.notifyObservers(faceIndex); - } - const fastPath = engine.snapshotRendering && engine.snapshotRenderingMode === 1; - if (!fastPath) { - // Get the list of meshes to render - let currentRenderList = null; - const defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data; - const defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length; - if (this.getCustomRenderList) { - currentRenderList = this.getCustomRenderList(this.is2DArray ? layer : faceIndex, defaultRenderList, defaultRenderListLength); - } - if (!currentRenderList) { - // No custom render list provided, we prepare the rendering for the default list, but check - // first if we did not already performed the preparation before so as to avoid re-doing it several times - if (!this._defaultRenderListPrepared) { - this._prepareRenderingManager(defaultRenderList, defaultRenderListLength, camera, !this.renderList || this.forceLayerMaskCheck); - this._defaultRenderListPrepared = true; - } - currentRenderList = defaultRenderList; - } - else { - // Prepare the rendering for the custom render list provided - this._prepareRenderingManager(currentRenderList, currentRenderList.length, camera, this.forceLayerMaskCheck); - } - // Before clear - for (const step of scene._beforeRenderTargetClearStage) { - step.action(this, faceIndex, layer); - } - // Clear - if (this.onClearObservable.hasObservers()) { - this.onClearObservable.notifyObservers(engine); - } - else { - if (!this.skipInitialClear) { - engine.clear(this.clearColor || scene.clearColor, true, true, true); - } - } - if (!this._doNotChangeAspectRatio) { - scene.updateTransformMatrix(true); - } - // Before Camera Draw - for (const step of scene._beforeRenderTargetDrawStage) { - step.action(this, faceIndex, layer); - } - // Render - this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites); - // After Camera Draw - for (const step of scene._afterRenderTargetDrawStage) { - step.action(this, faceIndex, layer); - } - const saveGenerateMipMaps = (_c = (_b = this._texture) === null || _b === void 0 ? void 0 : _b.generateMipMaps) !== null && _c !== void 0 ? _c : false; - if (this._texture) { - 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, - // 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 - // trigger the generation of the final mipmaps - } - if (this._postProcessManager) { - this._postProcessManager._finalizeFrame(false, (_d = this._renderTarget) !== null && _d !== void 0 ? _d : undefined, faceIndex, this._postProcesses, this.ignoreCameraViewport); - } - else if (useCameraPostProcess) { - scene.postProcessManager._finalizeFrame(false, (_e = this._renderTarget) !== null && _e !== void 0 ? _e : undefined, faceIndex); - } - for (const step of scene._afterRenderTargetPostProcessStage) { - step.action(this, faceIndex, layer); - } - if (this._texture) { - this._texture.generateMipMaps = saveGenerateMipMaps; - } - if (!this._doNotChangeAspectRatio) { - scene.updateTransformMatrix(true); - } - // Dump ? - if (dumpForDebug) { - DumpTools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine); - } - } - else { - // Clear - if (this.onClearObservable.hasObservers()) { - this.onClearObservable.notifyObservers(engine); - } - else { - if (!this.skipInitialClear) { - engine.clear(this.clearColor || scene.clearColor, true, true, true); - } - } - } - // Unbind - this._unbindFrameBuffer(engine, faceIndex); - if (this._texture && this.isCube && faceIndex === 5) { - engine.generateMipMapsForCubemap(this._texture); - } - (_f = engine._debugPopGroup) === null || _f === void 0 ? void 0 : _f.call(engine, 1); - } - /** - * Overrides the default sort function applied in the rendering group to prepare the meshes. - * This allowed control for front to back rendering or reversely depending of the special needs. - * - * @param renderingGroupId The rendering group id corresponding to its index - * @param opaqueSortCompareFn The opaque queue comparison function use to sort. - * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. - * @param transparentSortCompareFn The transparent queue comparison function use to sort. - */ - setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { - this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn); - } - /** - * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. - * - * @param renderingGroupId The rendering group id corresponding to its index - * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. - */ - setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) { - this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); - this._renderingManager._useSceneAutoClearSetup = false; - } - /** - * Clones the texture. - * @returns the cloned texture - */ - clone() { - const textureSize = this.getSize(); - const newTexture = new renderTargetTexture_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); - // Base texture - newTexture.hasAlpha = this.hasAlpha; - newTexture.level = this.level; - // RenderTarget Texture - newTexture.coordinatesMode = this.coordinatesMode; - if (this.renderList) { - newTexture.renderList = this.renderList.slice(0); - } - return newTexture; - } - /** - * Serialize the texture to a JSON representation we can easily use in the respective Parse function. - * @returns The JSON representation of the texture - */ - serialize() { - if (!this.name) { - return null; - } - const serializationObject = super.serialize(); - serializationObject.renderTargetSize = this.getRenderSize(); - serializationObject.renderList = []; - if (this.renderList) { - for (let index = 0; index < this.renderList.length; index++) { - serializationObject.renderList.push(this.renderList[index].id); - } - } - return serializationObject; - } - /** - * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore - */ - disposeFramebufferObjects() { - var _a; - (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose(true); - } - /** - * Release and destroy the underlying lower level texture aka internalTexture. - */ - releaseInternalTexture() { - var _a; - (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.releaseTextures(); - this._texture = null; - } - /** - * Dispose the texture and release its associated resources. - */ - dispose() { - var _a; - this.onResizeObservable.clear(); - this.onClearObservable.clear(); - this.onAfterRenderObservable.clear(); - this.onAfterUnbindObservable.clear(); - this.onBeforeBindObservable.clear(); - this.onBeforeRenderObservable.clear(); - if (this._postProcessManager) { - this._postProcessManager.dispose(); - this._postProcessManager = null; - } - if (this._prePassRenderTarget) { - this._prePassRenderTarget.dispose(); - } - this._releaseRenderPassId(); - this.clearPostProcesses(true); - if (this._resizeObserver) { - this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver); - this._resizeObserver = null; - } - this.renderList = null; - // Remove from custom render targets - const scene = this.getScene(); - if (!scene) { - return; - } - let index = scene.customRenderTargets.indexOf(this); - if (index >= 0) { - scene.customRenderTargets.splice(index, 1); - } - for (const camera of scene.cameras) { - index = camera.customRenderTargets.indexOf(this); - if (index >= 0) { - camera.customRenderTargets.splice(index, 1); - } - } - (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose(); - this._renderTarget = null; - this._texture = null; - super.dispose(); - } - /** @internal */ - _rebuild() { - if (this.refreshRate === renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE) { - this.refreshRate = renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE; - } - if (this._postProcessManager) { - this._postProcessManager._rebuild(); - } - } - /** - * Clear the info related to rendering groups preventing retention point in material dispose. - */ - freeRenderingGroups() { - if (this._renderingManager) { - this._renderingManager.freeRenderingGroups(); - } - } - /** - * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1) - * @returns the view count - */ - getViewCount() { - return 1; - } -} -/** - * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance. - */ -renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0; -/** - * The texture will only be rendered rendered every frame and is recommended for dynamic contents. - */ -renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1; -/** - * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not - * the central point of your effect and can save a lot of performances. - */ -renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -texture_Texture._CreateRenderTargetTexture = (name, renderTargetSize, scene, generateMipMaps, creationFlags) => { - return new renderTargetTexture_RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps); -}; -//# sourceMappingURL=renderTargetTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Procedurals/proceduralTextureSceneComponent.js - - -/** - * Defines the Procedural Texture scene component responsible to manage any Procedural Texture - * in a given scene. - */ -class ProceduralTextureSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_PROCEDURALTEXTURE; - this.scene = scene; - this.scene.proceduralTextures = new Array(); - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._beforeClearStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing to do here. - } - /** - * Disposes the component and the associated resources. - */ - dispose() { - // Nothing to do here. - } - _beforeClear() { - if (this.scene.proceduralTexturesEnabled) { - tools_Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0); - for (let proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) { - const proceduralTexture = this.scene.proceduralTextures[proceduralIndex]; - if (proceduralTexture._shouldRender()) { - proceduralTexture.render(); - } - } - tools_Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0); - } - } -} -//# sourceMappingURL=proceduralTextureSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/procedural.vertex.js -// Do not edit. - -const procedural_vertex_name = "proceduralVertexShader"; -const procedural_vertex_shader = `attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[procedural_vertex_name] = procedural_vertex_shader; -/** @internal */ -const proceduralVertexShader = { name: procedural_vertex_name, shader: procedural_vertex_shader }; -//# sourceMappingURL=procedural.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Procedurals/proceduralTexture.js - - - - - - - - - - - - - - - - -/** - * 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. - * This is the base class of any Procedural texture and contains most of the shareable code. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures - */ -class proceduralTexture_ProceduralTexture extends texture_Texture { - /** - * Instantiates a new procedural texture. - * 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. - * This is the base class of any Procedural texture and contains most of the shareable code. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures - * @param name Define the name of the texture - * @param size Define the size of the texture to create - * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later - * @param scene Define the scene the texture belongs to - * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture - * @param generateMipMaps Define if the texture should creates mip maps or not - * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube) - * @param textureType The FBO internal texture type - */ - constructor(name, size, fragment, scene, fallbackTexture = null, generateMipMaps = true, isCube = false, textureType = 0) { - super(null, scene, !generateMipMaps); - /** - * Define if the texture is enabled or not (disabled texture will not render) - */ - this.isEnabled = true; - /** - * Define if the texture must be cleared before rendering (default is true) - */ - this.autoClear = true; - /** - * Event raised when the texture is generated - */ - this.onGeneratedObservable = new observable_Observable(); - /** - * Event raised before the texture is generated - */ - this.onBeforeGenerationObservable = new observable_Observable(); - /** - * Gets or sets the node material used to create this texture (null if the texture was manually created) - */ - this.nodeMaterialSource = null; - /** @internal */ - 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 = false; - this._cachedDefines = null; - this._contentUpdateId = -1; - this._rtWrapper = null; - scene = this.getScene() || engineStore_EngineStore.LastCreatedScene; - let component = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_PROCEDURALTEXTURE); - if (!component) { - component = new ProceduralTextureSceneComponent(scene); - scene._addComponent(component); - } - scene.proceduralTextures.push(this); - this._fullEngine = scene.getEngine(); - this.name = name; - this.isRenderTarget = true; - this._size = size; - this._textureType = textureType; - this._generateMipMaps = generateMipMaps; - this._drawWrapper = new drawWrapper_DrawWrapper(this._fullEngine); - this.setFragment(fragment); - this._fallbackTexture = fallbackTexture; - const rtWrapper = this._createRtWrapper(isCube, size, generateMipMaps, textureType); - this._texture = rtWrapper.texture; - // VBO - const vertices = []; - vertices.push(1, 1); - vertices.push(-1, 1); - vertices.push(-1, -1); - vertices.push(1, -1); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = new buffer_VertexBuffer(this._fullEngine, vertices, buffer_VertexBuffer.PositionKind, false, false, 2); - this._createIndexBuffer(); - } - _createRtWrapper(isCube, size, generateMipMaps, textureType) { - if (isCube) { - this._rtWrapper = this._fullEngine.createRenderTargetCubeTexture(size, { - generateMipMaps: generateMipMaps, - generateDepthBuffer: false, - generateStencilBuffer: false, - type: textureType, - }); - this.setFloat("face", 0); - } - else { - this._rtWrapper = this._fullEngine.createRenderTargetTexture(size, { - generateMipMaps: generateMipMaps, - generateDepthBuffer: false, - generateStencilBuffer: false, - type: textureType, - }); - } - return this._rtWrapper; - } - /** - * The effect that is created when initializing the post process. - * @returns The created effect corresponding the the postprocess. - */ - getEffect() { - return this._drawWrapper.effect; - } - /** - * @internal* - */ - _setEffect(effect) { - this._drawWrapper.effect = effect; - } - /** - * Gets texture content (Use this function wisely as reading from a texture can be slow) - * @returns an ArrayBufferView promise (Uint8Array or Float32Array) - */ - getContent() { - if (this._contentData && this._frameId === this._contentUpdateId) { - return this._contentData; - } - if (this._contentData) { - this._contentData.then((buffer) => { - this._contentData = this.readPixels(0, 0, buffer); - this._contentUpdateId = this._frameId; - }); - } - else { - this._contentData = this.readPixels(0, 0); - this._contentUpdateId = this._frameId; - } - return this._contentData; - } - _createIndexBuffer() { - const engine = this._fullEngine; - // Indices - const indices = []; - indices.push(0); - indices.push(1); - indices.push(2); - indices.push(0); - indices.push(2); - indices.push(3); - this._indexBuffer = engine.createIndexBuffer(indices); - } - /** @internal */ - _rebuild() { - const vb = this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - if (vb) { - vb._rebuild(); - } - this._createIndexBuffer(); - if (this.refreshRate === renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE) { - this.refreshRate = renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE; - } - } - /** - * Resets the texture in order to recreate its associated resources. - * This can be called in case of context loss - */ - reset() { - var _a; - (_a = this._drawWrapper.effect) === null || _a === void 0 ? void 0 : _a.dispose(); - } - _getDefines() { - return ""; - } - /** - * Is the texture ready to be used ? (rendered at least once) - * @returns true if ready, otherwise, false. - */ - isReady() { - const engine = this._fullEngine; - let shaders; - if (this.nodeMaterialSource) { - return this._drawWrapper.effect.isReady(); - } - if (!this._fragment) { - return false; - } - if (this._fallbackTextureUsed) { - return true; - } - if (!this._texture) { - return false; - } - const defines = this._getDefines(); - if (this._drawWrapper.effect && defines === this._cachedDefines && this._drawWrapper.effect.isReady()) { - return true; - } - if (this._fragment.fragmentElement !== undefined) { - shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement }; - } - else { - shaders = { vertex: "procedural", fragment: this._fragment }; - } - if (this._cachedDefines !== defines) { - this._cachedDefines = defines; - this._drawWrapper.effect = engine.createEffect(shaders, [buffer_VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, () => { - var _a; - (_a = this._rtWrapper) === null || _a === void 0 ? void 0 : _a.dispose(); - this._rtWrapper = this._texture = null; - if (this._fallbackTexture) { - this._texture = this._fallbackTexture._texture; - if (this._texture) { - this._texture.incrementReferences(); - } - } - this._fallbackTextureUsed = true; - }); - } - return this._drawWrapper.effect.isReady(); - } - /** - * Resets the refresh counter of the texture and start bak from scratch. - * Could be useful to regenerate the texture if it is setup to render only once. - */ - resetRefreshCounter() { - this._currentRefreshId = -1; - } - /** - * Set the fragment shader to use in order to render the texture. - * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property. - */ - setFragment(fragment) { - this._fragment = fragment; - } - /** - * Define the refresh rate of the texture or the rendering frequency. - * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... - */ - get refreshRate() { - return this._refreshRate; - } - set refreshRate(value) { - this._refreshRate = value; - this.resetRefreshCounter(); - } - /** @internal */ - _shouldRender() { - if (!this.isEnabled || !this.isReady() || !this._texture) { - if (this._texture) { - this._texture.isReady = false; - } - return false; - } - if (this._fallbackTextureUsed) { - return false; - } - if (this._currentRefreshId === -1) { - // At least render once - this._currentRefreshId = 1; - this._frameId++; - return true; - } - if (this.refreshRate === this._currentRefreshId) { - this._currentRefreshId = 1; - this._frameId++; - return true; - } - this._currentRefreshId++; - return false; - } - /** - * Get the size the texture is rendering at. - * @returns the size (on cube texture it is always squared) - */ - getRenderSize() { - return this._size; - } - /** - * Resize the texture to new value. - * @param size Define the new size the texture should have - * @param generateMipMaps Define whether the new texture should create mip maps - */ - resize(size, generateMipMaps) { - if (this._fallbackTextureUsed || !this._rtWrapper || !this._texture) { - return; - } - const isCube = this._texture.isCube; - this._rtWrapper.dispose(); - const rtWrapper = this._createRtWrapper(isCube, size, generateMipMaps, this._textureType); - this._texture = rtWrapper.texture; - // Update properties - this._size = size; - this._generateMipMaps = generateMipMaps; - } - _checkUniform(uniformName) { - if (this._uniforms.indexOf(uniformName) === -1) { - this._uniforms.push(uniformName); - } - } - /** - * Set a texture in the shader program used to render. - * @param name Define the name of the uniform samplers as defined in the shader - * @param texture Define the texture to bind to this sampler - * @returns the texture itself allowing "fluent" like uniform updates - */ - setTexture(name, texture) { - if (this._samplers.indexOf(name) === -1) { - this._samplers.push(name); - } - this._textures[name] = texture; - return this; - } - /** - * Set a float in the shader. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the texture itself allowing "fluent" like uniform updates - */ - setFloat(name, value) { - this._checkUniform(name); - this._floats[name] = value; - return this; - } - /** - * Set a int in the shader. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the texture itself allowing "fluent" like uniform updates - */ - setInt(name, value) { - this._checkUniform(name); - this._ints[name] = value; - return this; - } - /** - * Set an array of floats in the shader. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the texture itself allowing "fluent" like uniform updates - */ - setFloats(name, value) { - this._checkUniform(name); - this._floatsArrays[name] = value; - return this; - } - /** - * Set a vec3 in the shader from a Color3. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the texture itself allowing "fluent" like uniform updates - */ - setColor3(name, value) { - this._checkUniform(name); - this._colors3[name] = value; - return this; - } - /** - * Set a vec4 in the shader from a Color4. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the texture itself allowing "fluent" like uniform updates - */ - setColor4(name, value) { - this._checkUniform(name); - this._colors4[name] = value; - return this; - } - /** - * Set a vec2 in the shader from a Vector2. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the texture itself allowing "fluent" like uniform updates - */ - setVector2(name, value) { - this._checkUniform(name); - this._vectors2[name] = value; - return this; - } - /** - * Set a vec3 in the shader from a Vector3. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the texture itself allowing "fluent" like uniform updates - */ - setVector3(name, value) { - this._checkUniform(name); - this._vectors3[name] = value; - return this; - } - /** - * Set a mat4 in the shader from a MAtrix. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the texture itself allowing "fluent" like uniform updates - */ - setMatrix(name, value) { - this._checkUniform(name); - this._matrices[name] = value; - return this; - } - /** - * Render the texture to its associated render target. - * @param useCameraPostProcess Define if camera post process should be applied to the texture - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - render(useCameraPostProcess) { - var _a, _b; - const scene = this.getScene(); - if (!scene) { - return; - } - const engine = this._fullEngine; - // Render - engine.enableEffect(this._drawWrapper); - this.onBeforeGenerationObservable.notifyObservers(this); - engine.setState(false); - if (!this.nodeMaterialSource) { - // Texture - for (const name in this._textures) { - this._drawWrapper.effect.setTexture(name, this._textures[name]); - } - // Float - for (const name in this._ints) { - this._drawWrapper.effect.setInt(name, this._ints[name]); - } - // Float - for (const name in this._floats) { - this._drawWrapper.effect.setFloat(name, this._floats[name]); - } - // Floats - for (const name in this._floatsArrays) { - this._drawWrapper.effect.setArray(name, this._floatsArrays[name]); - } - // Color3 - for (const name in this._colors3) { - this._drawWrapper.effect.setColor3(name, this._colors3[name]); - } - // Color4 - for (const name in this._colors4) { - const color = this._colors4[name]; - this._drawWrapper.effect.setFloat4(name, color.r, color.g, color.b, color.a); - } - // Vector2 - for (const name in this._vectors2) { - this._drawWrapper.effect.setVector2(name, this._vectors2[name]); - } - // Vector3 - for (const name in this._vectors3) { - this._drawWrapper.effect.setVector3(name, this._vectors3[name]); - } - // Matrix - for (const name in this._matrices) { - this._drawWrapper.effect.setMatrix(name, this._matrices[name]); - } - } - if (!this._texture || !this._rtWrapper) { - return; - } - (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `procedural texture generation for ${this.name}`, 1); - const viewPort = engine.currentViewport; - if (this.isCube) { - for (let face = 0; face < 6; face++) { - engine.bindFramebuffer(this._rtWrapper, face, undefined, undefined, true); - // VBOs - engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect); - this._drawWrapper.effect.setFloat("face", face); - // Clear - if (this.autoClear) { - engine.clear(scene.clearColor, true, false, false); - } - // Draw order - engine.drawElementsType(material_Material.TriangleFillMode, 0, 6); - } - } - else { - engine.bindFramebuffer(this._rtWrapper, 0, undefined, undefined, true); - // VBOs - engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect); - // Clear - if (this.autoClear) { - engine.clear(scene.clearColor, true, false, false); - } - // Draw order - engine.drawElementsType(material_Material.TriangleFillMode, 0, 6); - } - // Unbind and restore viewport - engine.unBindFramebuffer(this._rtWrapper, this.isCube); - if (viewPort) { - engine.setViewport(viewPort); - } - // Mipmaps - if (this.isCube) { - engine.generateMipMapsForCubemap(this._texture); - } - (_b = engine._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(engine, 1); - if (this.onGenerated) { - this.onGenerated(); - } - this.onGeneratedObservable.notifyObservers(this); - } - /** - * Clone the texture. - * @returns the cloned texture - */ - clone() { - const textureSize = this.getSize(); - const newTexture = new proceduralTexture_ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps); - // Base texture - newTexture.hasAlpha = this.hasAlpha; - newTexture.level = this.level; - // RenderTarget Texture - newTexture.coordinatesMode = this.coordinatesMode; - return newTexture; - } - /** - * Dispose the texture and release its associated resources. - */ - dispose() { - const scene = this.getScene(); - if (!scene) { - return; - } - const index = scene.proceduralTextures.indexOf(this); - if (index >= 0) { - scene.proceduralTextures.splice(index, 1); - } - const vertexBuffer = this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - if (vertexBuffer) { - vertexBuffer.dispose(); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = null; - } - if (this._indexBuffer && this._fullEngine._releaseBuffer(this._indexBuffer)) { - this._indexBuffer = null; - } - this.onGeneratedObservable.clear(); - this.onBeforeGenerationObservable.clear(); - super.dispose(); - } -} -__decorate([ - serialize() -], proceduralTexture_ProceduralTexture.prototype, "isEnabled", void 0); -__decorate([ - serialize() -], proceduralTexture_ProceduralTexture.prototype, "autoClear", void 0); -__decorate([ - serialize() -], proceduralTexture_ProceduralTexture.prototype, "_generateMipMaps", void 0); -__decorate([ - serialize() -], proceduralTexture_ProceduralTexture.prototype, "_size", void 0); -__decorate([ - serialize() -], proceduralTexture_ProceduralTexture.prototype, "refreshRate", null); -RegisterClass("BABYLON.ProceduralTexture", proceduralTexture_ProceduralTexture); -//# sourceMappingURL=proceduralTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/trigonometryBlock.js - - - - -/** - * Operations supported by the Trigonometry block - */ -var TrigonometryBlockOperations; -(function (TrigonometryBlockOperations) { - /** Cos */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Cos"] = 0] = "Cos"; - /** Sin */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Sin"] = 1] = "Sin"; - /** Abs */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Abs"] = 2] = "Abs"; - /** Exp */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Exp"] = 3] = "Exp"; - /** Exp2 */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Exp2"] = 4] = "Exp2"; - /** Round */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Round"] = 5] = "Round"; - /** Floor */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Floor"] = 6] = "Floor"; - /** Ceiling */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Ceiling"] = 7] = "Ceiling"; - /** Square root */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Sqrt"] = 8] = "Sqrt"; - /** Log */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Log"] = 9] = "Log"; - /** Tangent */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Tan"] = 10] = "Tan"; - /** Arc tangent */ - TrigonometryBlockOperations[TrigonometryBlockOperations["ArcTan"] = 11] = "ArcTan"; - /** Arc cosinus */ - TrigonometryBlockOperations[TrigonometryBlockOperations["ArcCos"] = 12] = "ArcCos"; - /** Arc sinus */ - TrigonometryBlockOperations[TrigonometryBlockOperations["ArcSin"] = 13] = "ArcSin"; - /** Fraction */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Fract"] = 14] = "Fract"; - /** Sign */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Sign"] = 15] = "Sign"; - /** To radians (from degrees) */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Radians"] = 16] = "Radians"; - /** To degrees (from radians) */ - TrigonometryBlockOperations[TrigonometryBlockOperations["Degrees"] = 17] = "Degrees"; -})(TrigonometryBlockOperations || (TrigonometryBlockOperations = {})); -/** - * Block used to apply trigonometry operation to floats - */ -class TrigonometryBlock extends NodeMaterialBlock { - /** - * Creates a new TrigonometryBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Gets or sets the operation applied by the block - */ - this.operation = TrigonometryBlockOperations.Cos; - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "TrigonometryBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - let operation = ""; - switch (this.operation) { - case TrigonometryBlockOperations.Cos: { - operation = "cos"; - break; - } - case TrigonometryBlockOperations.Sin: { - operation = "sin"; - break; - } - case TrigonometryBlockOperations.Abs: { - operation = "abs"; - break; - } - case TrigonometryBlockOperations.Exp: { - operation = "exp"; - break; - } - case TrigonometryBlockOperations.Exp2: { - operation = "exp2"; - break; - } - case TrigonometryBlockOperations.Round: { - operation = "round"; - break; - } - case TrigonometryBlockOperations.Floor: { - operation = "floor"; - break; - } - case TrigonometryBlockOperations.Ceiling: { - operation = "ceil"; - break; - } - case TrigonometryBlockOperations.Sqrt: { - operation = "sqrt"; - break; - } - case TrigonometryBlockOperations.Log: { - operation = "log"; - break; - } - case TrigonometryBlockOperations.Tan: { - operation = "tan"; - break; - } - case TrigonometryBlockOperations.ArcTan: { - operation = "atan"; - break; - } - case TrigonometryBlockOperations.ArcCos: { - operation = "acos"; - break; - } - case TrigonometryBlockOperations.ArcSin: { - operation = "asin"; - break; - } - case TrigonometryBlockOperations.Fract: { - operation = "fract"; - break; - } - case TrigonometryBlockOperations.Sign: { - operation = "sign"; - break; - } - case TrigonometryBlockOperations.Radians: { - operation = "radians"; - break; - } - case TrigonometryBlockOperations.Degrees: { - operation = "degrees"; - break; - } - } - state.compilationString += this._declareOutput(output, state) + ` = ${operation}(${this.input.associatedVariableName});\n`; - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.operation = this.operation; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.operation = serializationObject.operation; - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${TrigonometryBlockOperations[this.operation]};\n`; - return codeString; - } -} -RegisterClass("BABYLON.TrigonometryBlock", TrigonometryBlock); -//# sourceMappingURL=trigonometryBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -const onCreatedEffectParameters = { effect: null, subMesh: null }; -/** @internal */ -class NodeMaterialDefines extends MaterialDefines { - constructor() { - super(); - this.NORMAL = false; - this.TANGENT = false; - this.VERTEXCOLOR_NME = false; - this.UV1 = false; - this.UV2 = false; - this.UV3 = false; - this.UV4 = false; - this.UV5 = false; - this.UV6 = false; - /** BONES */ - this.NUM_BONE_INFLUENCERS = 0; - this.BonesPerMesh = 0; - this.BONETEXTURE = false; - /** MORPH TARGETS */ - this.MORPHTARGETS = false; - this.MORPHTARGETS_NORMAL = false; - this.MORPHTARGETS_TANGENT = false; - this.MORPHTARGETS_UV = false; - this.NUM_MORPH_INFLUENCERS = 0; - this.MORPHTARGETS_TEXTURE = false; - /** IMAGE PROCESSING */ - this.IMAGEPROCESSING = false; - this.VIGNETTE = false; - this.VIGNETTEBLENDMODEMULTIPLY = false; - this.VIGNETTEBLENDMODEOPAQUE = false; - this.TONEMAPPING = false; - this.TONEMAPPING_ACES = false; - this.CONTRAST = false; - this.EXPOSURE = false; - this.COLORCURVES = false; - this.COLORGRADING = false; - this.COLORGRADING3D = false; - this.SAMPLER3DGREENDEPTH = false; - this.SAMPLER3DBGRMAP = false; - this.DITHER = false; - this.IMAGEPROCESSINGPOSTPROCESS = false; - this.SKIPFINALCOLORCLAMP = false; - /** MISC. */ - this.BUMPDIRECTUV = 0; - this.CAMERA_ORTHOGRAPHIC = false; - this.CAMERA_PERSPECTIVE = false; - this.rebuild(); - } - setValue(name, value, markAsUnprocessedIfDirty = false) { - if (this[name] === undefined) { - this._keys.push(name); - } - if (markAsUnprocessedIfDirty && this[name] !== value) { - this.markAsUnprocessed(); - } - this[name] = value; - } -} -/** - * Class used to create a node based material built by assembling shader blocks - */ -class NodeMaterial extends PushMaterial { - /** - * Checks if a block is a texture block - * @param block The block to check - * @returns True if the block is a texture block - */ - static _BlockIsTextureBlock(block) { - return (block.getClassName() === "TextureBlock" || - block.getClassName() === "ReflectionTextureBaseBlock" || - block.getClassName() === "RefractionBlock" || - block.getClassName() === "CurrentScreenBlock" || - block.getClassName() === "ParticleTextureBlock" || - block.getClassName() === "ImageSourceBlock" || - block.getClassName() === "TriPlanarBlock" || - block.getClassName() === "BiPlanarBlock"); - } - /** Get the inspector from bundle or global */ - _getGlobalNodeMaterialEditor() { - // UMD Global name detection from Webpack Bundle UMD Name. - if (typeof NODEEDITOR !== "undefined") { - return NODEEDITOR; - } - // In case of module let's check the global emitted from the editor entry point. - if (typeof BABYLON !== "undefined" && typeof BABYLON.NodeEditor !== "undefined") { - return BABYLON; - } - return undefined; - } - /** Gets or sets options to control the node material overall behavior */ - get options() { - return this._options; - } - set options(options) { - this._options = options; - } - /** - * Gets the image processing configuration used either in this material. - */ - get imageProcessingConfiguration() { - return this._imageProcessingConfiguration; - } - /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ - set imageProcessingConfiguration(value) { - this._attachImageProcessingConfiguration(value); - // Ensure the effect will be rebuilt. - this._markAllSubMeshesAsTexturesDirty(); - } - /** - * Gets or sets the mode property - */ - get mode() { - return this._mode; - } - set mode(value) { - this._mode = value; - } - /** Gets or sets the unique identifier used to identified the effect associated with the material */ - get buildId() { - return this._buildId; - } - set buildId(value) { - this._buildId = value; - } - /** - * Create a new node based material - * @param name defines the material name - * @param scene defines the hosting scene - * @param options defines creation option - */ - constructor(name, scene, options = {}) { - super(name, scene || engineStore_EngineStore.LastCreatedScene); - this._buildId = NodeMaterial._BuildIdGenerator++; - this._buildWasSuccessful = false; - this._cachedWorldViewMatrix = new math_vector_Matrix(); - this._cachedWorldViewProjectionMatrix = new math_vector_Matrix(); - this._optimizers = new Array(); - this._animationFrame = -1; - this.BJSNODEMATERIALEDITOR = this._getGlobalNodeMaterialEditor(); - /** - * Gets or sets data used by visual editor - * @see https://nme.babylonjs.com - */ - this.editorData = null; - /** - * 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) - */ - this.ignoreAlpha = false; - /** - * Defines the maximum number of lights that can be used in the material - */ - this.maxSimultaneousLights = 4; - /** - * Observable raised when the material is built - */ - this.onBuildObservable = new observable_Observable(); - /** - * Gets or sets the root nodes of the material vertex shader - */ - this._vertexOutputNodes = new Array(); - /** - * Gets or sets the root nodes of the material fragment (pixel) shader - */ - this._fragmentOutputNodes = new Array(); - /** - * Gets an array of blocks that needs to be serialized even if they are not yet connected - */ - this.attachedBlocks = new Array(); - /** - * Specifies the mode of the node material - * @internal - */ - this._mode = NodeMaterialModes.Material; - /** - * Gets or sets a boolean indicating that alpha blending must be enabled no matter what alpha value or alpha channel of the FragmentBlock are - */ - this.forceAlphaBlending = false; - this._options = Object.assign({ emitComments: false }, options); - // Setup the default processing configuration to the scene. - this._attachImageProcessingConfiguration(null); - } - /** - * Gets the current class name of the material e.g. "NodeMaterial" - * @returns the class name - */ - getClassName() { - return "NodeMaterial"; - } - /** - * Attaches a new image processing configuration to the Standard Material. - * @param configuration - */ - _attachImageProcessingConfiguration(configuration) { - if (configuration === this._imageProcessingConfiguration) { - return; - } - // Detaches observer. - if (this._imageProcessingConfiguration && this._imageProcessingObserver) { - this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); - } - // Pick the scene configuration if needed. - if (!configuration) { - this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; - } - else { - this._imageProcessingConfiguration = configuration; - } - // Attaches observer. - if (this._imageProcessingConfiguration) { - this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { - this._markAllSubMeshesAsImageProcessingDirty(); - }); - } - } - /** - * Get a block by its name - * @param name defines the name of the block to retrieve - * @returns the required block or null if not found - */ - getBlockByName(name) { - let result = null; - for (const block of this.attachedBlocks) { - if (block.name === name) { - if (!result) { - result = block; - } - else { - tools_Tools.Warn("More than one block was found with the name `" + name + "`"); - return result; - } - } - } - return result; - } - /** - * Get a block by its name - * @param predicate defines the predicate used to find the good candidate - * @returns the required block or null if not found - */ - getBlockByPredicate(predicate) { - for (const block of this.attachedBlocks) { - if (predicate(block)) { - return block; - } - } - return null; - } - /** - * Get an input block by its name - * @param predicate defines the predicate used to find the good candidate - * @returns the required input block or null if not found - */ - getInputBlockByPredicate(predicate) { - for (const block of this.attachedBlocks) { - if (block.isInput && predicate(block)) { - return block; - } - } - return null; - } - /** - * Gets the list of input blocks attached to this material - * @returns an array of InputBlocks - */ - getInputBlocks() { - const blocks = []; - for (const block of this.attachedBlocks) { - if (block.isInput) { - blocks.push(block); - } - } - return blocks; - } - /** - * Adds a new optimizer to the list of optimizers - * @param optimizer defines the optimizers to add - * @returns the current material - */ - registerOptimizer(optimizer) { - const index = this._optimizers.indexOf(optimizer); - if (index > -1) { - return; - } - this._optimizers.push(optimizer); - return this; - } - /** - * Remove an optimizer from the list of optimizers - * @param optimizer defines the optimizers to remove - * @returns the current material - */ - unregisterOptimizer(optimizer) { - const index = this._optimizers.indexOf(optimizer); - if (index === -1) { - return; - } - this._optimizers.splice(index, 1); - return this; - } - /** - * Add a new block to the list of output nodes - * @param node defines the node to add - * @returns the current material - */ - addOutputNode(node) { - if (node.target === null) { - throw "This node is not meant to be an output node. You may want to explicitly set its target value."; - } - if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) { - this._addVertexOutputNode(node); - } - if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) { - this._addFragmentOutputNode(node); - } - return this; - } - /** - * Remove a block from the list of root nodes - * @param node defines the node to remove - * @returns the current material - */ - removeOutputNode(node) { - if (node.target === null) { - return this; - } - if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) { - this._removeVertexOutputNode(node); - } - if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) { - this._removeFragmentOutputNode(node); - } - return this; - } - _addVertexOutputNode(node) { - if (this._vertexOutputNodes.indexOf(node) !== -1) { - return; - } - node.target = NodeMaterialBlockTargets.Vertex; - this._vertexOutputNodes.push(node); - return this; - } - _removeVertexOutputNode(node) { - const index = this._vertexOutputNodes.indexOf(node); - if (index === -1) { - return; - } - this._vertexOutputNodes.splice(index, 1); - return this; - } - _addFragmentOutputNode(node) { - if (this._fragmentOutputNodes.indexOf(node) !== -1) { - return; - } - node.target = NodeMaterialBlockTargets.Fragment; - this._fragmentOutputNodes.push(node); - return this; - } - _removeFragmentOutputNode(node) { - const index = this._fragmentOutputNodes.indexOf(node); - if (index === -1) { - return; - } - this._fragmentOutputNodes.splice(index, 1); - return this; - } - /** - * Specifies if the material will require alpha blending - * @returns a boolean specifying if alpha blending is needed - */ - needAlphaBlending() { - if (this.ignoreAlpha) { - return false; - } - return this.forceAlphaBlending || this.alpha < 1.0 || (this._sharedData && this._sharedData.hints.needAlphaBlending); - } - /** - * Specifies if this material should be rendered in alpha test mode - * @returns a boolean specifying if an alpha test is needed. - */ - needAlphaTesting() { - return this._sharedData && this._sharedData.hints.needAlphaTesting; - } - _processInitializeOnLink(block, state, nodesToProcessForOtherBuildState, autoConfigure = true) { - if (block.target === NodeMaterialBlockTargets.VertexAndFragment) { - nodesToProcessForOtherBuildState.push(block); - } - else if (state.target === NodeMaterialBlockTargets.Fragment && block.target === NodeMaterialBlockTargets.Vertex && block._preparationId !== this._buildId) { - nodesToProcessForOtherBuildState.push(block); - } - this._initializeBlock(block, state, nodesToProcessForOtherBuildState, autoConfigure); - } - _initializeBlock(node, state, nodesToProcessForOtherBuildState, autoConfigure = true) { - node.initialize(state); - if (autoConfigure) { - node.autoConfigure(this); - } - node._preparationId = this._buildId; - if (this.attachedBlocks.indexOf(node) === -1) { - if (node.isUnique) { - const className = node.getClassName(); - for (const other of this.attachedBlocks) { - if (other.getClassName() === className) { - throw `Cannot have multiple blocks of type ${className} in the same NodeMaterial`; - } - } - } - this.attachedBlocks.push(node); - } - for (const input of node.inputs) { - input.associatedVariableName = ""; - const connectedPoint = input.connectedPoint; - if (connectedPoint) { - const block = connectedPoint.ownerBlock; - if (block !== node) { - this._processInitializeOnLink(block, state, nodesToProcessForOtherBuildState, autoConfigure); - } - } - } - // Teleportation - if (node.isTeleportOut) { - const teleport = node; - if (teleport.entryPoint) { - this._processInitializeOnLink(teleport.entryPoint, state, nodesToProcessForOtherBuildState, autoConfigure); - } - } - for (const output of node.outputs) { - output.associatedVariableName = ""; - } - } - _resetDualBlocks(node, id) { - if (node.target === NodeMaterialBlockTargets.VertexAndFragment) { - node.buildId = id; - } - for (const inputs of node.inputs) { - const connectedPoint = inputs.connectedPoint; - if (connectedPoint) { - const block = connectedPoint.ownerBlock; - if (block !== node) { - this._resetDualBlocks(block, id); - } - } - } - // If this is a teleport out, we need to reset the connected block - if (node.isTeleportOut) { - const teleportOut = node; - if (teleportOut.entryPoint) { - this._resetDualBlocks(teleportOut.entryPoint, id); - } - } - } - /** - * Remove a block from the current node material - * @param block defines the block to remove - */ - removeBlock(block) { - const attachedBlockIndex = this.attachedBlocks.indexOf(block); - if (attachedBlockIndex > -1) { - this.attachedBlocks.splice(attachedBlockIndex, 1); - } - if (block.isFinalMerger) { - this.removeOutputNode(block); - } - } - /** - * Build the material and generates the inner effect - * @param verbose defines if the build should log activity - * @param updateBuildId defines if the internal build Id should be updated (default is true) - * @param autoConfigure defines if the autoConfigure method should be called when initializing blocks (default is false) - */ - build(verbose = false, updateBuildId = true, autoConfigure = false) { - // First time? - if (!this._vertexCompilationState && !autoConfigure) { - autoConfigure = true; - } - this._buildWasSuccessful = false; - const engine = this.getScene().getEngine(); - const allowEmptyVertexProgram = this._mode === NodeMaterialModes.Particle; - if (this._vertexOutputNodes.length === 0 && !allowEmptyVertexProgram) { - throw "You must define at least one vertexOutputNode"; - } - if (this._fragmentOutputNodes.length === 0) { - throw "You must define at least one fragmentOutputNode"; - } - // Compilation state - this._vertexCompilationState = new NodeMaterialBuildState(); - this._vertexCompilationState.supportUniformBuffers = engine.supportsUniformBuffers; - this._vertexCompilationState.target = NodeMaterialBlockTargets.Vertex; - this._fragmentCompilationState = new NodeMaterialBuildState(); - this._fragmentCompilationState.supportUniformBuffers = engine.supportsUniformBuffers; - this._fragmentCompilationState.target = NodeMaterialBlockTargets.Fragment; - // Shared data - this._sharedData = new NodeMaterialBuildStateSharedData(); - 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 = verbose; - this._sharedData.scene = this.getScene(); - this._sharedData.allowEmptyVertexProgram = allowEmptyVertexProgram; - // Initialize blocks - const vertexNodes = []; - const fragmentNodes = []; - for (const vertexOutputNode of this._vertexOutputNodes) { - vertexNodes.push(vertexOutputNode); - this._initializeBlock(vertexOutputNode, this._vertexCompilationState, fragmentNodes, autoConfigure); - } - for (const fragmentOutputNode of this._fragmentOutputNodes) { - fragmentNodes.push(fragmentOutputNode); - this._initializeBlock(fragmentOutputNode, this._fragmentCompilationState, vertexNodes, autoConfigure); - } - // Optimize - this.optimize(); - // Vertex - for (const vertexOutputNode of vertexNodes) { - vertexOutputNode.build(this._vertexCompilationState, vertexNodes); - } - // Fragment - 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 fragmentOutputNode of fragmentNodes) { - this._resetDualBlocks(fragmentOutputNode, this._buildId - 1); - } - for (const fragmentOutputNode of fragmentNodes) { - fragmentOutputNode.build(this._fragmentCompilationState, fragmentNodes); - } - // Finalize - this._vertexCompilationState.finalize(this._vertexCompilationState); - this._fragmentCompilationState.finalize(this._fragmentCompilationState); - if (updateBuildId) { - this._buildId = NodeMaterial._BuildIdGenerator++; - } - // Errors - this._sharedData.emitErrors(); - if (verbose) { - console.log("Vertex shader:"); - console.log(this._vertexCompilationState.compilationString); - console.log("Fragment shader:"); - console.log(this._fragmentCompilationState.compilationString); - } - this._buildWasSuccessful = true; - this.onBuildObservable.notifyObservers(this); - // Wipe defines - const meshes = this.getScene().meshes; - for (const mesh of meshes) { - if (!mesh.subMeshes) { - continue; - } - for (const subMesh of mesh.subMeshes) { - if (subMesh.getMaterial() !== this) { - continue; - } - if (!subMesh.materialDefines) { - continue; - } - const defines = subMesh.materialDefines; - defines.markAllAsDirty(); - defines.reset(); - } - } - } - /** - * Runs an otpimization phase to try to improve the shader code - */ - optimize() { - for (const optimizer of this._optimizers) { - optimizer.optimize(this._vertexOutputNodes, this._fragmentOutputNodes); - } - } - _prepareDefinesForAttributes(mesh, defines) { - const oldNormal = defines["NORMAL"]; - const oldTangent = defines["TANGENT"]; - const oldColor = defines["VERTEXCOLOR_NME"]; - defines["NORMAL"] = mesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind); - defines["TANGENT"] = mesh.isVerticesDataPresent(buffer_VertexBuffer.TangentKind); - const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(buffer_VertexBuffer.ColorKind); - defines["VERTEXCOLOR_NME"] = hasVertexColors; - let uvChanged = false; - for (let i = 1; i <= 6; ++i) { - const oldUV = defines["UV" + i]; - defines["UV" + i] = mesh.isVerticesDataPresent(`uv${i === 1 ? "" : i}`); - uvChanged = uvChanged || defines["UV" + i] !== oldUV; - } - if (oldNormal !== defines["NORMAL"] || oldTangent !== defines["TANGENT"] || oldColor !== defines["VERTEXCOLOR_NME"] || uvChanged) { - defines.markAsAttributesDirty(); - } - } - /** - * Create a post process from the material - * @param camera The camera to apply the render pass to. - * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size) - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA) - * @returns the post process created - */ - createPostProcess(camera, options = 1, samplingMode = 1, engine, reusable, textureType = 0, textureFormat = 5) { - if (this.mode !== NodeMaterialModes.PostProcess) { - console.log("Incompatible material mode"); - return null; - } - return this._createEffectForPostProcess(null, camera, options, samplingMode, engine, reusable, textureType, textureFormat); - } - /** - * Create the post process effect from the material - * @param postProcess The post process to create the effect for - */ - createEffectForPostProcess(postProcess) { - this._createEffectForPostProcess(postProcess); - } - _createEffectForPostProcess(postProcess, camera, options = 1, samplingMode = 1, engine, reusable, textureType = 0, textureFormat = 5) { - let tempName = this.name + this._buildId; - const defines = new NodeMaterialDefines(); - const dummyMesh = new abstractMesh_AbstractMesh(tempName + "PostProcess", this.getScene()); - let buildId = this._buildId; - this._processDefines(dummyMesh, defines); - effect_Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString); - if (!postProcess) { - postProcess = new postProcess_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); - } - else { - postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName); - } - postProcess.nodeMaterialSource = this; - postProcess.onApplyObservable.add((effect) => { - if (buildId !== this._buildId) { - delete effect_Effect.ShadersStore[tempName + "VertexShader"]; - delete effect_Effect.ShadersStore[tempName + "PixelShader"]; - tempName = this.name + this._buildId; - defines.markAllAsDirty(); - buildId = this._buildId; - } - const result = this._processDefines(dummyMesh, defines); - if (result) { - effect_Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString); - TimingTools.SetImmediate(() => postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName)); - } - this._checkInternals(effect); - }); - return postProcess; - } - /** - * Create a new procedural texture based on this node material - * @param size defines the size of the texture - * @param scene defines the hosting scene - * @returns the new procedural texture attached to this node material - */ - createProceduralTexture(size, scene) { - if (this.mode !== NodeMaterialModes.ProceduralTexture) { - console.log("Incompatible material mode"); - return null; - } - let tempName = this.name + this._buildId; - const proceduralTexture = new proceduralTexture_ProceduralTexture(tempName, size, null, scene); - const dummyMesh = new abstractMesh_AbstractMesh(tempName + "Procedural", this.getScene()); - dummyMesh.reservedDataStore = { - hidden: true, - }; - const defines = new NodeMaterialDefines(); - const result = this._processDefines(dummyMesh, defines); - effect_Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString); - let effect = this.getScene().getEngine().createEffect({ - vertexElement: tempName, - fragmentElement: tempName, - }, [buffer_VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString(), result === null || result === void 0 ? void 0 : result.fallbacks, undefined); - proceduralTexture.nodeMaterialSource = this; - proceduralTexture._setEffect(effect); - let buildId = this._buildId; - proceduralTexture.onBeforeGenerationObservable.add(() => { - if (buildId !== this._buildId) { - delete effect_Effect.ShadersStore[tempName + "VertexShader"]; - delete effect_Effect.ShadersStore[tempName + "PixelShader"]; - tempName = this.name + this._buildId; - defines.markAllAsDirty(); - buildId = this._buildId; - } - const result = this._processDefines(dummyMesh, defines); - if (result) { - effect_Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString); - TimingTools.SetImmediate(() => { - effect = this.getScene().getEngine().createEffect({ - vertexElement: tempName, - fragmentElement: tempName, - }, [buffer_VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString(), result === null || result === void 0 ? void 0 : result.fallbacks, undefined); - proceduralTexture._setEffect(effect); - }); - } - this._checkInternals(effect); - }); - return proceduralTexture; - } - _createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined = "") { - let tempName = this.name + this._buildId + "_" + blendMode; - if (!defines) { - defines = new NodeMaterialDefines(); - } - if (!dummyMesh) { - dummyMesh = this.getScene().getMeshByName(this.name + "Particle"); - if (!dummyMesh) { - dummyMesh = new abstractMesh_AbstractMesh(this.name + "Particle", this.getScene()); - dummyMesh.reservedDataStore = { - hidden: true, - }; - } - } - let buildId = this._buildId; - const particleSystemDefines = []; - let join = particleSystemDefinesJoined; - if (!effect) { - const result = this._processDefines(dummyMesh, defines); - effect_Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString); - particleSystem.fillDefines(particleSystemDefines, blendMode); - join = particleSystemDefines.join("\n"); - effect = this.getScene() - .getEngine() - .createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + "\n" + join, result === null || result === void 0 ? void 0 : result.fallbacks, onCompiled, onError, particleSystem); - particleSystem.setCustomEffect(effect, blendMode); - } - effect.onBindObservable.add((effect) => { - if (buildId !== this._buildId) { - delete effect_Effect.ShadersStore[tempName + "PixelShader"]; - tempName = this.name + this._buildId + "_" + blendMode; - defines.markAllAsDirty(); - buildId = this._buildId; - } - particleSystemDefines.length = 0; - particleSystem.fillDefines(particleSystemDefines, blendMode); - const particleSystemDefinesJoinedCurrent = particleSystemDefines.join("\n"); - if (particleSystemDefinesJoinedCurrent !== join) { - defines.markAllAsDirty(); - join = particleSystemDefinesJoinedCurrent; - } - const result = this._processDefines(dummyMesh, defines); - if (result) { - effect_Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString); - effect = this.getScene() - .getEngine() - .createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + "\n" + join, result === null || result === void 0 ? void 0 : result.fallbacks, onCompiled, onError, particleSystem); - particleSystem.setCustomEffect(effect, blendMode); - this._createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined); // add the effect.onBindObservable observer - return; - } - this._checkInternals(effect); - }); - } - _checkInternals(effect) { - // Animated blocks - if (this._sharedData.animatedInputs) { - const scene = this.getScene(); - const frameId = scene.getFrameId(); - if (this._animationFrame !== frameId) { - for (const input of this._sharedData.animatedInputs) { - input.animate(scene); - } - this._animationFrame = frameId; - } - } - // Bindable blocks - for (const block of this._sharedData.bindableBlocks) { - block.bind(effect, this); - } - // Connection points - for (const inputBlock of this._sharedData.inputBlocks) { - inputBlock._transmit(effect, this.getScene(), this); - } - } - /** - * Create the effect to be used as the custom effect for a particle system - * @param particleSystem Particle system to create the effect for - * @param onCompiled defines a function to call when the effect creation is successful - * @param onError defines a function to call when the effect creation has failed - */ - createEffectForParticles(particleSystem, onCompiled, onError) { - if (this.mode !== NodeMaterialModes.Particle) { - console.log("Incompatible material mode"); - return; - } - this._createEffectForParticles(particleSystem, BaseParticleSystem.BLENDMODE_ONEONE, onCompiled, onError); - this._createEffectForParticles(particleSystem, BaseParticleSystem.BLENDMODE_MULTIPLY, onCompiled, onError); - } - /** - * Use this material as the shadow depth wrapper of a target material - * @param targetMaterial defines the target material - */ - createAsShadowDepthWrapper(targetMaterial) { - if (this.mode !== NodeMaterialModes.Material) { - console.log("Incompatible material mode"); - return; - } - targetMaterial.shadowDepthWrapper = new BABYLON.ShadowDepthWrapper(this, this.getScene()); - } - _processDefines(mesh, defines, useInstances = false, subMesh) { - let result = null; - // Global defines - const scene = this.getScene(); - if (MaterialHelper.PrepareDefinesForCamera(scene, defines)) { - defines.markAsMiscDirty(); - } - // Shared defines - this._sharedData.blocksWithDefines.forEach((b) => { - b.initializeDefines(mesh, this, defines, useInstances); - }); - this._sharedData.blocksWithDefines.forEach((b) => { - b.prepareDefines(mesh, this, defines, useInstances, subMesh); - }); - // Need to recompile? - if (defines.isDirty) { - const lightDisposed = defines._areLightsDisposed; - defines.markAsProcessed(); - // Repeatable content generators - this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString; - this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString; - this._sharedData.repeatableContentBlocks.forEach((b) => { - b.replaceRepeatableContent(this._vertexCompilationState, this._fragmentCompilationState, mesh, defines); - }); - // Uniforms - const uniformBuffers = []; - this._sharedData.dynamicUniformBlocks.forEach((b) => { - b.updateUniformsAndSamples(this._vertexCompilationState, this, defines, uniformBuffers); - }); - const mergedUniforms = this._vertexCompilationState.uniforms; - this._fragmentCompilationState.uniforms.forEach((u) => { - const index = mergedUniforms.indexOf(u); - if (index === -1) { - mergedUniforms.push(u); - } - }); - // Samplers - const mergedSamplers = this._vertexCompilationState.samplers; - this._fragmentCompilationState.samplers.forEach((s) => { - const index = mergedSamplers.indexOf(s); - if (index === -1) { - mergedSamplers.push(s); - } - }); - const fallbacks = new EffectFallbacks(); - this._sharedData.blocksWithFallbacks.forEach((b) => { - b.provideFallbacks(mesh, fallbacks); - }); - result = { - lightDisposed, - uniformBuffers, - mergedUniforms, - mergedSamplers, - fallbacks, - }; - } - return result; - } - /** - * Get if the submesh is ready to be used and all its information available. - * Child classes can use it to update shaders - * @param mesh defines the mesh to check - * @param subMesh defines which submesh to check - * @param useInstances specifies that instances should be used - * @returns a boolean indicating that the submesh is ready or not - */ - isReadyForSubMesh(mesh, subMesh, useInstances = false) { - if (!this._buildWasSuccessful) { - return false; - } - const scene = this.getScene(); - if (this._sharedData.animatedInputs) { - const frameId = scene.getFrameId(); - if (this._animationFrame !== frameId) { - for (const input of this._sharedData.animatedInputs) { - input.animate(scene); - } - this._animationFrame = frameId; - } - } - if (subMesh.effect && this.isFrozen) { - if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) { - return true; - } - } - if (!subMesh.materialDefines) { - subMesh.materialDefines = new NodeMaterialDefines(); - } - const defines = subMesh.materialDefines; - if (this._isReadyForSubMesh(subMesh)) { - return true; - } - const engine = scene.getEngine(); - this._prepareDefinesForAttributes(mesh, defines); - // Check if blocks are ready - if (this._sharedData.blockingBlocks.some((b) => !b.isReady(mesh, this, defines, useInstances))) { - return false; - } - const result = this._processDefines(mesh, defines, useInstances, subMesh); - if (result) { - const previousEffect = subMesh.effect; - // Compilation - const join = defines.toString(); - let effect = engine.createEffect({ - vertex: "nodeMaterial" + this._buildId, - fragment: "nodeMaterial" + this._buildId, - vertexSource: this._vertexCompilationState.compilationString, - fragmentSource: this._fragmentCompilationState.compilationString, - }, { - attributes: this._vertexCompilationState.attributes, - uniformsNames: result.mergedUniforms, - uniformBuffersNames: result.uniformBuffers, - samplers: result.mergedSamplers, - defines: join, - fallbacks: result.fallbacks, - onCompiled: this.onCompiled, - onError: this.onError, - indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }, - }, engine); - if (effect) { - if (this._onEffectCreatedObservable) { - onCreatedEffectParameters.effect = effect; - onCreatedEffectParameters.subMesh = subMesh; - this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters); - } - // Use previous effect while new one is compiling - if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) { - effect = previousEffect; - defines.markAsUnprocessed(); - if (result.lightDisposed) { - // re register in case it takes more than one frame. - defines._areLightsDisposed = true; - return false; - } - } - else { - scene.resetCachedMaterial(); - subMesh.setEffect(effect, defines, this._materialContext); - } - } - } - if (!subMesh.effect || !subMesh.effect.isReady()) { - return false; - } - defines._renderId = scene.getRenderId(); - subMesh.effect._wasPreviouslyReady = true; - subMesh.effect._wasPreviouslyUsingInstances = useInstances; - this._checkScenePerformancePriority(); - return true; - } - /** - * Get a string representing the shaders built by the current node graph - */ - get compiledShaders() { - return `// Vertex shader\n${this._vertexCompilationState.compilationString}\n\n// Fragment shader\n${this._fragmentCompilationState.compilationString}`; - } - /** - * Binds the world matrix to the material - * @param world defines the world transformation matrix - */ - bindOnlyWorldMatrix(world) { - const scene = this.getScene(); - if (!this._activeEffect) { - return; - } - const hints = this._sharedData.hints; - if (hints.needWorldViewMatrix) { - world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix); - } - if (hints.needWorldViewProjectionMatrix) { - world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix); - } - // Connection points - for (const inputBlock of this._sharedData.inputBlocks) { - inputBlock._transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix); - } - } - /** - * Binds the submesh to this material by preparing the effect and shader to draw - * @param world defines the world transformation matrix - * @param mesh defines the mesh containing the submesh - * @param subMesh defines the submesh to bind the material to - */ - bindForSubMesh(world, mesh, subMesh) { - const scene = this.getScene(); - const effect = subMesh.effect; - if (!effect) { - return; - } - this._activeEffect = effect; - // Matrices - this.bindOnlyWorldMatrix(world); - const mustRebind = this._mustRebind(scene, effect, mesh.visibility); - const sharedData = this._sharedData; - if (mustRebind) { - // Bindable blocks - for (const block of sharedData.bindableBlocks) { - block.bind(effect, this, mesh, subMesh); - } - for (const block of sharedData.forcedBindableBlocks) { - block.bind(effect, this, mesh, subMesh); - } - // Connection points - for (const inputBlock of sharedData.inputBlocks) { - inputBlock._transmit(effect, scene, this); - } - } - else if (!this.isFrozen) { - for (const block of sharedData.forcedBindableBlocks) { - block.bind(effect, this, mesh, subMesh); - } - } - this._afterBind(mesh, this._activeEffect); - } - /** - * Gets the active textures from the material - * @returns an array of textures - */ - getActiveTextures() { - const activeTextures = super.getActiveTextures(); - if (this._sharedData) { - activeTextures.push(...this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture)); - } - return activeTextures; - } - /** - * Gets the list of texture blocks - * Note that this method will only return blocks that are reachable from the final block(s) and only after the material has been built! - * @returns an array of texture blocks - */ - getTextureBlocks() { - if (!this._sharedData) { - return []; - } - return this._sharedData.textureBlocks; - } - /** - * Gets the list of all texture blocks - * Note that this method will scan all attachedBlocks and return blocks that are texture blocks - * @returns - */ - getAllTextureBlocks() { - const textureBlocks = []; - for (const block of this.attachedBlocks) { - if (NodeMaterial._BlockIsTextureBlock(block)) { - textureBlocks.push(block); - } - } - return textureBlocks; - } - /** - * Specifies if the material uses a texture - * @param texture defines the texture to check against the material - * @returns a boolean specifying if the material uses the texture - */ - hasTexture(texture) { - if (super.hasTexture(texture)) { - return true; - } - if (!this._sharedData) { - return false; - } - for (const t of this._sharedData.textureBlocks) { - if (t.texture === texture) { - return true; - } - } - return false; - } - /** - * Disposes the material - * @param forceDisposeEffect specifies if effects should be forcefully disposed - * @param forceDisposeTextures specifies if textures should be forcefully disposed - * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh - */ - dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { - if (forceDisposeTextures) { - for (const texture of this.getTextureBlocks() - .filter((tb) => tb.texture) - .map((tb) => tb.texture)) { - texture.dispose(); - } - } - for (const block of this.attachedBlocks) { - block.dispose(); - } - this.attachedBlocks.length = 0; - this._sharedData = null; - this._vertexCompilationState = null; - this._fragmentCompilationState = null; - this.onBuildObservable.clear(); - if (this._imageProcessingObserver) { - this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); - this._imageProcessingObserver = null; - } - super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh); - } - /** Creates the node editor window. */ - _createNodeEditor(additionalConfig) { - const nodeEditorConfig = Object.assign({ nodeMaterial: this }, additionalConfig); - this.BJSNODEMATERIALEDITOR.NodeEditor.Show(nodeEditorConfig); - } - /** - * Launch the node material editor - * @param config Define the configuration of the editor - * @returns a promise fulfilled when the node editor is visible - */ - edit(config) { - return new Promise((resolve) => { - this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor(); - if (typeof this.BJSNODEMATERIALEDITOR == "undefined") { - const editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL; - // Load editor and add it to the DOM - tools_Tools.LoadScript(editorUrl, () => { - this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor(); - this._createNodeEditor(config === null || config === void 0 ? void 0 : config.nodeEditorConfig); - resolve(); - }); - } - else { - // Otherwise creates the editor - this._createNodeEditor(config === null || config === void 0 ? void 0 : config.nodeEditorConfig); - resolve(); - } - }); - } - /** - * Clear the current material - */ - clear() { - this._vertexOutputNodes.length = 0; - this._fragmentOutputNodes.length = 0; - this.attachedBlocks.length = 0; - } - /** - * Clear the current material and set it to a default state - */ - setToDefault() { - this.clear(); - this.editorData = null; - const positionInput = new InputBlock("Position"); - positionInput.setAsAttribute("position"); - const worldInput = new InputBlock("World"); - worldInput.setAsSystemValue(NodeMaterialSystemValues.World); - const worldPos = new TransformBlock("WorldPos"); - positionInput.connectTo(worldPos); - worldInput.connectTo(worldPos); - const viewProjectionInput = new InputBlock("ViewProjection"); - viewProjectionInput.setAsSystemValue(NodeMaterialSystemValues.ViewProjection); - const worldPosdMultipliedByViewProjection = new TransformBlock("WorldPos * ViewProjectionTransform"); - worldPos.connectTo(worldPosdMultipliedByViewProjection); - viewProjectionInput.connectTo(worldPosdMultipliedByViewProjection); - const vertexOutput = new VertexOutputBlock("VertexOutput"); - worldPosdMultipliedByViewProjection.connectTo(vertexOutput); - // Pixel - const pixelColor = new InputBlock("color"); - pixelColor.value = new math_color_Color4(0.8, 0.8, 0.8, 1); - const fragmentOutput = new FragmentOutputBlock("FragmentOutput"); - pixelColor.connectTo(fragmentOutput); - // Add to nodes - this.addOutputNode(vertexOutput); - this.addOutputNode(fragmentOutput); - this._mode = NodeMaterialModes.Material; - } - /** - * Clear the current material and set it to a default state for post process - */ - setToDefaultPostProcess() { - this.clear(); - this.editorData = null; - const position = new InputBlock("Position"); - position.setAsAttribute("position2d"); - const const1 = new InputBlock("Constant1"); - const1.isConstant = true; - const1.value = 1; - const vmerger = new VectorMergerBlock("Position3D"); - position.connectTo(vmerger); - const1.connectTo(vmerger, { input: "w" }); - const vertexOutput = new VertexOutputBlock("VertexOutput"); - vmerger.connectTo(vertexOutput); - // Pixel - const scale = new InputBlock("Scale"); - scale.visibleInInspector = true; - scale.value = new math_vector_Vector2(1, 1); - const uv0 = new RemapBlock("uv0"); - position.connectTo(uv0); - const uv = new MultiplyBlock("UV scale"); - uv0.connectTo(uv); - scale.connectTo(uv); - const currentScreen = new CurrentScreenBlock("CurrentScreen"); - uv.connectTo(currentScreen); - currentScreen.texture = new texture_Texture("https://assets.babylonjs.com/nme/currentScreenPostProcess.png", this.getScene()); - const fragmentOutput = new FragmentOutputBlock("FragmentOutput"); - currentScreen.connectTo(fragmentOutput, { output: "rgba" }); - // Add to nodes - this.addOutputNode(vertexOutput); - this.addOutputNode(fragmentOutput); - this._mode = NodeMaterialModes.PostProcess; - } - /** - * Clear the current material and set it to a default state for procedural texture - */ - setToDefaultProceduralTexture() { - this.clear(); - this.editorData = null; - const position = new InputBlock("Position"); - position.setAsAttribute("position2d"); - const const1 = new InputBlock("Constant1"); - const1.isConstant = true; - const1.value = 1; - const vmerger = new VectorMergerBlock("Position3D"); - position.connectTo(vmerger); - const1.connectTo(vmerger, { input: "w" }); - const vertexOutput = new VertexOutputBlock("VertexOutput"); - vmerger.connectTo(vertexOutput); - // Pixel - const time = new InputBlock("Time"); - time.value = 0; - time.min = 0; - time.max = 0; - time.isBoolean = false; - time.matrixMode = 0; - time.animationType = AnimatedInputBlockTypes.Time; - time.isConstant = false; - const color = new InputBlock("Color3"); - color.value = new math_color_Color3(1, 1, 1); - color.isConstant = false; - const fragmentOutput = new FragmentOutputBlock("FragmentOutput"); - const vectorMerger = new VectorMergerBlock("VectorMerger"); - vectorMerger.visibleInInspector = false; - const cos = new TrigonometryBlock("Cos"); - cos.operation = TrigonometryBlockOperations.Cos; - position.connectTo(vectorMerger); - time.output.connectTo(cos.input); - cos.output.connectTo(vectorMerger.z); - vectorMerger.xyzOut.connectTo(fragmentOutput.rgb); - // Add to nodes - this.addOutputNode(vertexOutput); - this.addOutputNode(fragmentOutput); - this._mode = NodeMaterialModes.ProceduralTexture; - } - /** - * Clear the current material and set it to a default state for particle - */ - setToDefaultParticle() { - this.clear(); - this.editorData = null; - // Pixel - const uv = new InputBlock("uv"); - uv.setAsAttribute("particle_uv"); - const texture = new ParticleTextureBlock("ParticleTexture"); - uv.connectTo(texture); - const color = new InputBlock("Color"); - color.setAsAttribute("particle_color"); - const multiply = new MultiplyBlock("Texture * Color"); - texture.connectTo(multiply); - color.connectTo(multiply); - const rampGradient = new ParticleRampGradientBlock("ParticleRampGradient"); - multiply.connectTo(rampGradient); - const cSplitter = new ColorSplitterBlock("ColorSplitter"); - color.connectTo(cSplitter); - const blendMultiply = new ParticleBlendMultiplyBlock("ParticleBlendMultiply"); - rampGradient.connectTo(blendMultiply); - texture.connectTo(blendMultiply, { output: "a" }); - cSplitter.connectTo(blendMultiply, { output: "a" }); - const fragmentOutput = new FragmentOutputBlock("FragmentOutput"); - blendMultiply.connectTo(fragmentOutput); - // Add to nodes - this.addOutputNode(fragmentOutput); - this._mode = NodeMaterialModes.Particle; - } - /** - * Loads the current Node Material from a url pointing to a file save by the Node Material Editor - * @deprecated Please use NodeMaterial.ParseFromFileAsync instead - * @param url defines the url to load from - * @param rootUrl defines the root URL for nested url in the node material - * @returns a promise that will fulfil when the material is fully loaded - */ - async loadAsync(url, rootUrl = "") { - return NodeMaterial.ParseFromFileAsync("", url, this.getScene(), rootUrl, true, this); - } - _gatherBlocks(rootNode, list) { - if (list.indexOf(rootNode) !== -1) { - return; - } - list.push(rootNode); - for (const input of rootNode.inputs) { - const connectedPoint = input.connectedPoint; - if (connectedPoint) { - const block = connectedPoint.ownerBlock; - if (block !== rootNode) { - this._gatherBlocks(block, list); - } - } - } - // Teleportation - if (rootNode.isTeleportOut) { - const block = rootNode; - if (block.entryPoint) { - this._gatherBlocks(block.entryPoint, list); - } - } - } - /** - * Generate a string containing the code declaration required to create an equivalent of this material - * @returns a string - */ - generateCode() { - let alreadyDumped = []; - const vertexBlocks = []; - const uniqueNames = ["const", "var", "let"]; - // Gets active blocks - for (const outputNode of this._vertexOutputNodes) { - this._gatherBlocks(outputNode, vertexBlocks); - } - const fragmentBlocks = []; - for (const outputNode of this._fragmentOutputNodes) { - this._gatherBlocks(outputNode, fragmentBlocks); - } - // Generate vertex shader - let codeString = `var nodeMaterial = new BABYLON.NodeMaterial("${this.name || "node material"}");\n`; - codeString += `nodeMaterial.mode = BABYLON.NodeMaterialModes.${NodeMaterialModes[this.mode]};\n`; - for (const node of vertexBlocks) { - if (node.isInput && alreadyDumped.indexOf(node) === -1) { - codeString += node._dumpCode(uniqueNames, alreadyDumped); - } - } - // Generate fragment shader - for (const node of fragmentBlocks) { - if (node.isInput && alreadyDumped.indexOf(node) === -1) { - codeString += node._dumpCode(uniqueNames, alreadyDumped); - } - } - // Connections - alreadyDumped = []; - codeString += "\n// Connections\n"; - for (const node of this._vertexOutputNodes) { - codeString += node._dumpCodeForOutputConnections(alreadyDumped); - } - for (const node of this._fragmentOutputNodes) { - codeString += node._dumpCodeForOutputConnections(alreadyDumped); - } - // Output nodes - codeString += "\n// Output nodes\n"; - for (const node of this._vertexOutputNodes) { - codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\n`; - } - for (const node of this._fragmentOutputNodes) { - codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\n`; - } - codeString += `nodeMaterial.build();\n`; - return codeString; - } - /** - * Serializes this material in a JSON representation - * @param selectedBlocks - * @returns the serialized material object - */ - serialize(selectedBlocks) { - const serializationObject = selectedBlocks ? {} : decorators_SerializationHelper.Serialize(this); - serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy - let blocks = []; - if (selectedBlocks) { - blocks = selectedBlocks; - } - else { - serializationObject.customType = "BABYLON.NodeMaterial"; - serializationObject.outputNodes = []; - // Outputs - for (const outputNode of this._vertexOutputNodes) { - this._gatherBlocks(outputNode, blocks); - serializationObject.outputNodes.push(outputNode.uniqueId); - } - for (const outputNode of this._fragmentOutputNodes) { - this._gatherBlocks(outputNode, blocks); - if (serializationObject.outputNodes.indexOf(outputNode.uniqueId) === -1) { - serializationObject.outputNodes.push(outputNode.uniqueId); - } - } - } - // Blocks - serializationObject.blocks = []; - for (const block of blocks) { - serializationObject.blocks.push(block.serialize()); - } - if (!selectedBlocks) { - for (const block of this.attachedBlocks) { - if (blocks.indexOf(block) !== -1) { - continue; - } - serializationObject.blocks.push(block.serialize()); - } - } - return serializationObject; - } - _restoreConnections(block, source, map) { - for (const outputPoint of block.outputs) { - for (const candidate of source.blocks) { - const target = map[candidate.id]; - if (!target) { - continue; - } - for (const input of candidate.inputs) { - if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) { - const inputPoint = target.getInputByName(input.inputName); - if (!inputPoint || inputPoint.isConnected) { - continue; - } - outputPoint.connectTo(inputPoint, true); - this._restoreConnections(target, source, map); - continue; - } - } - } - } - } - /** - * Clear the current graph and load a new one from a serialization object - * @param source defines the JSON representation of the material - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @param merge defines whether or not the source must be merged or replace the current content - */ - parseSerializedObject(source, rootUrl = "", merge = false) { - var _a; - if (!merge) { - this.clear(); - } - const map = {}; - // Create blocks - for (const parsedBlock of source.blocks) { - const blockType = GetClass(parsedBlock.customType); - if (blockType) { - const block = new blockType(); - block._deserialize(parsedBlock, this.getScene(), rootUrl); - map[parsedBlock.id] = block; - this.attachedBlocks.push(block); - } - } - // Reconnect teleportation - for (const block of this.attachedBlocks) { - if (block.isTeleportOut) { - const teleportOut = block; - const id = teleportOut._tempEntryPointUniqueId; - if (id) { - const source = map[id]; - source.attachToEndpoint(teleportOut); - } - } - } - // Connections - Starts with input blocks only (except if in "merge" mode where we scan all blocks) - for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) { - const parsedBlock = source.blocks[blockIndex]; - const block = map[parsedBlock.id]; - if (!block) { - continue; - } - if (block.inputs.length && !merge) { - continue; - } - this._restoreConnections(block, source, map); - } - // Outputs - if (source.outputNodes) { - for (const outputNodeId of source.outputNodes) { - this.addOutputNode(map[outputNodeId]); - } - } - // UI related info - if (source.locations || (source.editorData && source.editorData.locations)) { - const locations = source.locations || source.editorData.locations; - for (const location of locations) { - if (map[location.blockId]) { - location.blockId = map[location.blockId].uniqueId; - } - } - if (merge && this.editorData && this.editorData.locations) { - locations.concat(this.editorData.locations); - } - if (source.locations) { - this.editorData = { - locations: locations, - }; - } - else { - this.editorData = source.editorData; - this.editorData.locations = locations; - } - const blockMap = []; - for (const key in map) { - blockMap[key] = map[key].uniqueId; - } - this.editorData.map = blockMap; - } - this.comment = source.comment; - if (source.forceAlphaBlending !== undefined) { - this.forceAlphaBlending = source.forceAlphaBlending; - } - if (!merge) { - this._mode = (_a = source.mode) !== null && _a !== void 0 ? _a : NodeMaterialModes.Material; - } - } - /** - * Clear the current graph and load a new one from a serialization object - * @param source defines the JSON representation of the material - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @param merge defines whether or not the source must be merged or replace the current content - * @deprecated Please use the parseSerializedObject method instead - */ - loadFromSerialization(source, rootUrl = "", merge = false) { - this.parseSerializedObject(source, rootUrl, merge); - } - /** - * Makes a duplicate of the current material. - * @param name defines the name to use for the new material - * @param shareEffect defines if the clone material should share the same effect (default is false) - */ - clone(name, shareEffect = false) { - const serializationObject = this.serialize(); - const clone = decorators_SerializationHelper.Clone(() => new NodeMaterial(name, this.getScene(), this.options), this); - clone.id = name; - clone.name = name; - clone.parseSerializedObject(serializationObject); - clone._buildId = this._buildId; - clone.build(false, !shareEffect); - return clone; - } - /** - * Creates a node material from parsed material data - * @param source defines the JSON representation of the material - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a new node material - */ - static Parse(source, scene, rootUrl = "") { - const nodeMaterial = decorators_SerializationHelper.Parse(() => new NodeMaterial(source.name, scene), source, scene, rootUrl); - nodeMaterial.parseSerializedObject(source, rootUrl); - nodeMaterial.build(); - return nodeMaterial; - } - /** - * Creates a node material from a snippet saved in a remote file - * @param name defines the name of the material to create - * @param url defines the url to load from - * @param scene defines the hosting scene - * @param rootUrl defines the root URL for nested url in the node material - * @param skipBuild defines whether to build the node material - * @param targetMaterial defines a material to use instead of creating a new one - * @returns a promise that will resolve to the new node material - */ - static async ParseFromFileAsync(name, url, scene, rootUrl = "", skipBuild = false, targetMaterial) { - const material = targetMaterial !== null && targetMaterial !== void 0 ? targetMaterial : new NodeMaterial(name, scene); - const data = await scene._loadFileAsync(url); - const serializationObject = JSON.parse(data); - material.parseSerializedObject(serializationObject, rootUrl); - if (!skipBuild) { - material.build(); - } - return material; - } - /** - * Creates a node material from a snippet saved by the node material editor - * @param snippetId defines the snippet to load - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @param nodeMaterial defines a node material to update (instead of creating a new one) - * @param skipBuild defines whether to build the node material - * @returns a promise that will resolve to the new node material - */ - static ParseFromSnippetAsync(snippetId, scene = engineStore_EngineStore.LastCreatedScene, rootUrl = "", nodeMaterial, skipBuild = false) { - if (snippetId === "_BLANK") { - return Promise.resolve(NodeMaterial.CreateDefault("blank", scene)); - } - return new Promise((resolve, reject) => { - const request = new webRequest_WebRequest(); - request.addEventListener("readystatechange", () => { - if (request.readyState == 4) { - if (request.status == 200) { - const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); - const serializationObject = JSON.parse(snippet.nodeMaterial); - if (!nodeMaterial) { - nodeMaterial = decorators_SerializationHelper.Parse(() => new NodeMaterial(snippetId, scene), serializationObject, scene, rootUrl); - nodeMaterial.uniqueId = scene.getUniqueId(); - } - nodeMaterial.parseSerializedObject(serializationObject); - nodeMaterial.snippetId = snippetId; - try { - if (!skipBuild) { - nodeMaterial.build(); - } - resolve(nodeMaterial); - } - catch (err) { - reject(err); - } - } - else { - reject("Unable to load the snippet " + snippetId); - } - } - }); - request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); - request.send(); - }); - } - /** - * Creates a new node material set to default basic configuration - * @param name defines the name of the material - * @param scene defines the hosting scene - * @returns a new NodeMaterial - */ - static CreateDefault(name, scene) { - const newMaterial = new NodeMaterial(name, scene); - newMaterial.setToDefault(); - newMaterial.build(); - return newMaterial; - } -} -NodeMaterial._BuildIdGenerator = 0; -/** Define the Url to load node editor script */ -NodeMaterial.EditorURL = `https://unpkg.com/babylonjs-node-editor@${engine_Engine.Version}/babylon.nodeEditor.js`; -/** Define the Url to load snippets */ -NodeMaterial.SnippetUrl = `https://snippet.babylonjs.com`; -/** Gets or sets a boolean indicating that node materials should not deserialize textures from json / snippet content */ -NodeMaterial.IgnoreTexturesAtLoadTime = false; -__decorate([ - serialize() -], NodeMaterial.prototype, "ignoreAlpha", void 0); -__decorate([ - serialize() -], NodeMaterial.prototype, "maxSimultaneousLights", void 0); -__decorate([ - serialize("mode") -], NodeMaterial.prototype, "_mode", void 0); -__decorate([ - serialize("comment") -], NodeMaterial.prototype, "comment", void 0); -__decorate([ - serialize() -], NodeMaterial.prototype, "forceAlphaBlending", void 0); -RegisterClass("BABYLON.NodeMaterial", NodeMaterial); -//# sourceMappingURL=nodeMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/icoSphereBuilder.js - - - - -/** - * Creates the VertexData of the IcoSphere - * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty - * * radius the radius of the IcoSphere, optional default 1 - * * radiusX allows stretching in the x direction, optional, default radius - * * radiusY allows stretching in the y direction, optional, default radius - * * radiusZ allows stretching in the z direction, optional, default radius - * * flat when true creates a flat shaded mesh, optional, default true - * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.radius - * @param options.radiusX - * @param options.radiusY - * @param options.radiusZ - * @param options.flat - * @param options.subdivisions - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the IcoSphere - */ -function CreateIcoSphereVertexData(options) { - const sideOrientation = options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - const radius = options.radius || 1; - const flat = options.flat === undefined ? true : options.flat; - const subdivisions = (options.subdivisions || 4) | 0; - const radiusX = options.radiusX || radius; - const radiusY = options.radiusY || radius; - const radiusZ = options.radiusZ || radius; - const t = (1 + Math.sqrt(5)) / 2; - // 12 vertex x,y,z - const icoVertices = [ - -1, - t, - -0, - 1, - t, - 0, - -1, - -t, - 0, - 1, - -t, - 0, - 0, - -1, - -t, - 0, - 1, - -t, - 0, - -1, - t, - 0, - 1, - t, - t, - 0, - 1, - t, - 0, - -1, - -t, - 0, - 1, - -t, - 0, - -1, // v8-11 - ]; - // index of 3 vertex makes a face of icopshere - const ico_indices = [ - 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, - ]; - // vertex for uv have aliased position, not for UV - const vertices_unalias_id = [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - // vertex alias - 0, - 2, - 3, - 3, - 3, - 4, - 7, - 8, - 9, - 9, - 10, - 11, // 23: B + 12 - ]; - // uv as integer step (not pixels !) - const ico_vertexuv = [ - 5, - 1, - 3, - 1, - 6, - 4, - 0, - 0, - 5, - 3, - 4, - 2, - 2, - 2, - 4, - 0, - 2, - 0, - 1, - 1, - 6, - 0, - 6, - 2, - // vertex alias (for same vertex on different faces) - 0, - 4, - 3, - 3, - 4, - 4, - 3, - 1, - 4, - 2, - 4, - 4, - 0, - 2, - 1, - 1, - 2, - 2, - 3, - 3, - 1, - 3, - 2, - 4, // 23: B + 12 - ]; - // Vertices[0, 1, ...9, A, B] : position on UV plane - // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B) - // First island of uv mapping - // v = 4h 3+ 2 - // v = 3h 9+ 4 - // v = 2h 9+ 5 B - // v = 1h 9 1 0 - // v = 0h 3 8 7 A - // u = 0 1 2 3 4 5 6 *a - // Second island of uv mapping - // v = 4h 0+ B+ 4+ - // v = 3h A+ 2+ - // v = 2h 7+ 6 3+ - // v = 1h 8+ 3+ - // v = 0h - // u = 0 1 2 3 4 5 6 *a - // Face layout on texture UV mapping - // ============ - // \ 4 /\ 16 / ====== - // \ / \ / /\ 11 / - // \/ 7 \/ / \ / - // ======= / 10 \/ - // /\ 17 /\ ======= - // / \ / \ \ 15 /\ - // / 8 \/ 12 \ \ / \ - // ============ \/ 6 \ - // \ 18 /\ ============ - // \ / \ \ 5 /\ 0 / - // \/ 13 \ \ / \ / - // ======= \/ 1 \/ - // ============= - // /\ 19 /\ 2 /\ - // / \ / \ / \ - // / 14 \/ 9 \/ 3 \ - // =================== - // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97 - const ustep = 138 / 1024; - const vstep = 239 / 1024; - const uoffset = 60 / 1024; - const voffset = 26 / 1024; - // Second island should have margin, not to touch the first island - // avoid any borderline artefact in pixel rounding - const island_u_offset = -40 / 1024; - const island_v_offset = +20 / 1024; - // face is either island 0 or 1 : - // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18] - const island = [ - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 1, - 1, - 0, - 0, - 0, - 1, - 1, - 0, - 0, - 1, - 1, - 1, - 0, // 15 - 19 - ]; - const indices = new Array(); - const positions = new Array(); - const normals = new Array(); - const uvs = new Array(); - let current_indice = 0; - // prepare array of 3 vector (empty) (to be worked in place, shared for each face) - const face_vertex_pos = new Array(3); - const face_vertex_uv = new Array(3); - let v012; - for (v012 = 0; v012 < 3; v012++) { - face_vertex_pos[v012] = math_vector_Vector3.Zero(); - face_vertex_uv[v012] = math_vector_Vector2.Zero(); - } - // create all with normals - for (let face = 0; face < 20; face++) { - // 3 vertex per face - for (v012 = 0; v012 < 3; v012++) { - // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias) - const v_id = ico_indices[3 * face + v012]; - // vertex have 3D position (x,y,z) - 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]); - // Normalize to get normal - face_vertex_pos[v012].normalize(); - // uv Coordinates from vertex ID - 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); - } - // Subdivide the face (interpolate pos, norm, uv) - // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere) - // - norm is linear interpolation of vertex corner normal - // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? ) - // - uv is linear interpolation - // - // Topology is as below for sub-divide by 2 - // vertex shown as v0,v1,v2 - // interp index is i1 to progress in range [v0,v1[ - // interp index is i2 to progress in range [v0,v2[ - // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1) - // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1) - // - // - // i2 v2 - // ^ ^ - // / / \ - // / / \ - // / / \ - // / / (0,1) \ - // / #---------\ - // / / \ (0,0)'/ \ - // / / \ / \ - // / / \ / \ - // / / (0,0) \ / (1,0) \ - // / #---------#---------\ - // v0 v1 - // - // --------------------> i1 - // - // interp of (i1,i2): - // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S) - // along i1 : lerp(x0,x1, i1/(S-i2)) - // - // centroid of triangle is needed to get help normal computation - // (c1,c2) are used for centroid location - const interp_vertex = (i1, i2, c1, c2) => { - // vertex is interpolated from - // - face_vertex_pos[0..2] - // - face_vertex_uv[0..2] - const pos_x0 = math_vector_Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions); - const pos_x1 = math_vector_Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions); - const pos_interp = subdivisions === i2 ? face_vertex_pos[2] : math_vector_Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2)); - pos_interp.normalize(); - let vertex_normal; - if (flat) { - // in flat mode, recalculate normal as face centroid normal - const centroid_x0 = math_vector_Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions); - const centroid_x1 = math_vector_Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions); - vertex_normal = math_vector_Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2)); - } - else { - // in smooth mode, recalculate normal from each single vertex position - vertex_normal = new math_vector_Vector3(pos_interp.x, pos_interp.y, pos_interp.z); - } - // Vertex normal need correction due to X,Y,Z radius scaling - vertex_normal.x /= radiusX; - vertex_normal.y /= radiusY; - vertex_normal.z /= radiusZ; - vertex_normal.normalize(); - const uv_x0 = math_vector_Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions); - const uv_x1 = math_vector_Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions); - const uv_interp = subdivisions === i2 ? face_vertex_uv[2] : math_vector_Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2)); - positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ); - normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z); - uvs.push(uv_interp.x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - uv_interp.y : uv_interp.y); - // push each vertex has member of a face - // Same vertex can belong to multiple face, it is pushed multiple time (duplicate vertex are present) - indices.push(current_indice); - current_indice++; - }; - for (let i2 = 0; i2 < subdivisions; i2++) { - for (let i1 = 0; i1 + i2 < subdivisions; i1++) { - // face : (i1,i2) for /\ : - // interp for : (i1,i2),(i1+1,i2),(i1,i2+1) - interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3); - interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3); - interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3); - if (i1 + i2 + 1 < subdivisions) { - // face : (i1,i2)' for \/ : - // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1) - interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3); - interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3); - interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3); - } - } - } - } - // Sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - return vertexData; -} -/** - * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided - * * The parameter `radius` sets the radius size (float) of the icosphere (default 1) - * * 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`) - * * The parameter `subdivisions` sets the number of subdivisions (positive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size - * * 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 - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.radius - * @param options.radiusX - * @param options.radiusY - * @param options.radiusZ - * @param options.flat - * @param options.subdivisions - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.updatable - * @param scene defines the hosting scene - * @returns the icosahedron mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra#icosphere - */ -function CreateIcoSphere(name, options = {}, scene = null) { - const sphere = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - sphere._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreateIcoSphereVertexData(options); - vertexData.applyToMesh(sphere, options.updatable); - return sphere; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use the function directly from the module - */ -const IcoSphereBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateIcoSphere, -}; -mesh_vertexData_VertexData.CreateIcoSphere = CreateIcoSphereVertexData; -mesh_Mesh.CreateIcoSphere = (name, options, scene) => { - return CreateIcoSphere(name, options, scene); -}; -//# sourceMappingURL=icoSphereBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRHandTracking.js - - - - - - - - - - - - - - -/** - * Parts of the hands divided to writs and finger names - */ -var HandPart; -(function (HandPart) { - /** - * HandPart - Wrist - */ - HandPart["WRIST"] = "wrist"; - /** - * HandPart - The thumb - */ - HandPart["THUMB"] = "thumb"; - /** - * HandPart - Index finger - */ - HandPart["INDEX"] = "index"; - /** - * HandPart - Middle finger - */ - HandPart["MIDDLE"] = "middle"; - /** - * HandPart - Ring finger - */ - HandPart["RING"] = "ring"; - /** - * HandPart - Little finger - */ - HandPart["LITTLE"] = "little"; -})(HandPart || (HandPart = {})); -/** - * Joints of the hand as defined by the WebXR specification. - * https://immersive-web.github.io/webxr-hand-input/#skeleton-joints-section - */ -var WebXRHandTracking_WebXRHandJoint; -(function (WebXRHandJoint) { - /** Wrist */ - WebXRHandJoint["WRIST"] = "wrist"; - /** Thumb near wrist */ - WebXRHandJoint["THUMB_METACARPAL"] = "thumb-metacarpal"; - /** Thumb first knuckle */ - WebXRHandJoint["THUMB_PHALANX_PROXIMAL"] = "thumb-phalanx-proximal"; - /** Thumb second knuckle */ - WebXRHandJoint["THUMB_PHALANX_DISTAL"] = "thumb-phalanx-distal"; - /** Thumb tip */ - WebXRHandJoint["THUMB_TIP"] = "thumb-tip"; - /** Index finger near wrist */ - WebXRHandJoint["INDEX_FINGER_METACARPAL"] = "index-finger-metacarpal"; - /** Index finger first knuckle */ - WebXRHandJoint["INDEX_FINGER_PHALANX_PROXIMAL"] = "index-finger-phalanx-proximal"; - /** Index finger second knuckle */ - WebXRHandJoint["INDEX_FINGER_PHALANX_INTERMEDIATE"] = "index-finger-phalanx-intermediate"; - /** Index finger third knuckle */ - WebXRHandJoint["INDEX_FINGER_PHALANX_DISTAL"] = "index-finger-phalanx-distal"; - /** Index finger tip */ - WebXRHandJoint["INDEX_FINGER_TIP"] = "index-finger-tip"; - /** Middle finger near wrist */ - WebXRHandJoint["MIDDLE_FINGER_METACARPAL"] = "middle-finger-metacarpal"; - /** Middle finger first knuckle */ - WebXRHandJoint["MIDDLE_FINGER_PHALANX_PROXIMAL"] = "middle-finger-phalanx-proximal"; - /** Middle finger second knuckle */ - WebXRHandJoint["MIDDLE_FINGER_PHALANX_INTERMEDIATE"] = "middle-finger-phalanx-intermediate"; - /** Middle finger third knuckle */ - WebXRHandJoint["MIDDLE_FINGER_PHALANX_DISTAL"] = "middle-finger-phalanx-distal"; - /** Middle finger tip */ - WebXRHandJoint["MIDDLE_FINGER_TIP"] = "middle-finger-tip"; - /** Ring finger near wrist */ - WebXRHandJoint["RING_FINGER_METACARPAL"] = "ring-finger-metacarpal"; - /** Ring finger first knuckle */ - WebXRHandJoint["RING_FINGER_PHALANX_PROXIMAL"] = "ring-finger-phalanx-proximal"; - /** Ring finger second knuckle */ - WebXRHandJoint["RING_FINGER_PHALANX_INTERMEDIATE"] = "ring-finger-phalanx-intermediate"; - /** Ring finger third knuckle */ - WebXRHandJoint["RING_FINGER_PHALANX_DISTAL"] = "ring-finger-phalanx-distal"; - /** Ring finger tip */ - WebXRHandJoint["RING_FINGER_TIP"] = "ring-finger-tip"; - /** Pinky finger near wrist */ - WebXRHandJoint["PINKY_FINGER_METACARPAL"] = "pinky-finger-metacarpal"; - /** Pinky finger first knuckle */ - WebXRHandJoint["PINKY_FINGER_PHALANX_PROXIMAL"] = "pinky-finger-phalanx-proximal"; - /** Pinky finger second knuckle */ - WebXRHandJoint["PINKY_FINGER_PHALANX_INTERMEDIATE"] = "pinky-finger-phalanx-intermediate"; - /** Pinky finger third knuckle */ - WebXRHandJoint["PINKY_FINGER_PHALANX_DISTAL"] = "pinky-finger-phalanx-distal"; - /** Pinky finger tip */ - WebXRHandJoint["PINKY_FINGER_TIP"] = "pinky-finger-tip"; -})(WebXRHandTracking_WebXRHandJoint || (WebXRHandTracking_WebXRHandJoint = {})); -const handJointReferenceArray = [ - WebXRHandTracking_WebXRHandJoint.WRIST, - WebXRHandTracking_WebXRHandJoint.THUMB_METACARPAL, - WebXRHandTracking_WebXRHandJoint.THUMB_PHALANX_PROXIMAL, - WebXRHandTracking_WebXRHandJoint.THUMB_PHALANX_DISTAL, - WebXRHandTracking_WebXRHandJoint.THUMB_TIP, - WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_METACARPAL, - WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL, - WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE, - WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL, - WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_TIP, - WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_METACARPAL, - WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL, - WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE, - WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL, - WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_TIP, - WebXRHandTracking_WebXRHandJoint.RING_FINGER_METACARPAL, - WebXRHandTracking_WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL, - WebXRHandTracking_WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE, - WebXRHandTracking_WebXRHandJoint.RING_FINGER_PHALANX_DISTAL, - WebXRHandTracking_WebXRHandJoint.RING_FINGER_TIP, - WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_METACARPAL, - WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL, - WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE, - WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL, - WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_TIP, -]; -const handPartsDefinition = { - [HandPart.WRIST]: [WebXRHandTracking_WebXRHandJoint.WRIST], - [HandPart.THUMB]: [WebXRHandTracking_WebXRHandJoint.THUMB_METACARPAL, WebXRHandTracking_WebXRHandJoint.THUMB_PHALANX_PROXIMAL, WebXRHandTracking_WebXRHandJoint.THUMB_PHALANX_DISTAL, WebXRHandTracking_WebXRHandJoint.THUMB_TIP], - [HandPart.INDEX]: [ - WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_METACARPAL, - WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL, - WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE, - WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL, - WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_TIP, - ], - [HandPart.MIDDLE]: [ - WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_METACARPAL, - WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL, - WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE, - WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL, - WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_TIP, - ], - [HandPart.RING]: [ - WebXRHandTracking_WebXRHandJoint.RING_FINGER_METACARPAL, - WebXRHandTracking_WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL, - WebXRHandTracking_WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE, - WebXRHandTracking_WebXRHandJoint.RING_FINGER_PHALANX_DISTAL, - WebXRHandTracking_WebXRHandJoint.RING_FINGER_TIP, - ], - [HandPart.LITTLE]: [ - WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_METACARPAL, - WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL, - WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE, - WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL, - WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_TIP, - ], -}; -/** - * Representing a single hand (with its corresponding native XRHand object) - */ -class WebXRHand { - /** - * Get the hand mesh. - */ - get handMesh() { - return this._handMesh; - } - /** - * Get meshes of part of the hand. - * @param part The part of hand to get. - * @returns An array of meshes that correlate to the hand part requested. - */ - getHandPartMeshes(part) { - return handPartsDefinition[part].map((name) => this._jointMeshes[handJointReferenceArray.indexOf(name)]); - } - /** - * Retrieves a mesh linked to a named joint in the hand. - * @param jointName The name of the joint. - * @returns An AbstractMesh whose position corresponds with the joint position. - */ - getJointMesh(jointName) { - return this._jointMeshes[handJointReferenceArray.indexOf(jointName)]; - } - /** - * Construct a new hand object - * @param xrController The controller to which the hand correlates. - * @param _jointMeshes The meshes to be used to track the hand joints. - * @param _handMesh An optional hand mesh. - * @param rigMapping An optional rig mapping for the hand mesh. - * If not provided (but a hand mesh is provided), - * it will be assumed that the hand mesh's bones are named - * directly after the WebXR bone names. - * @param _leftHandedMeshes Are the hand meshes left-handed-system meshes - * @param _jointsInvisible Are the tracked joint meshes visible - * @param _jointScaleFactor Scale factor for all joint meshes - */ - constructor( - /** The controller to which the hand correlates. */ - xrController, _jointMeshes, _handMesh, - /** An optional rig mapping for the hand mesh. If not provided (but a hand mesh is provided), - * it will be assumed that the hand mesh's bones are named directly after the WebXR bone names. */ - rigMapping, _leftHandedMeshes = false, _jointsInvisible = false, _jointScaleFactor = 1) { - this.xrController = xrController; - this._jointMeshes = _jointMeshes; - this._handMesh = _handMesh; - this.rigMapping = rigMapping; - this._leftHandedMeshes = _leftHandedMeshes; - this._jointsInvisible = _jointsInvisible; - this._jointScaleFactor = _jointScaleFactor; - /** - * Transform nodes that will directly receive the transforms from the WebXR matrix data. - */ - this._jointTransforms = new Array(handJointReferenceArray.length); - /** - * The float array that will directly receive the transform matrix data from WebXR. - */ - this._jointTransformMatrices = new Float32Array(handJointReferenceArray.length * 16); - this._tempJointMatrix = new math_vector_Matrix(); - /** - * The float array that will directly receive the joint radii from WebXR. - */ - this._jointRadii = new Float32Array(handJointReferenceArray.length); - this._scene = _jointMeshes[0].getScene(); - // Initialize the joint transform quaternions and link the transforms to the bones. - for (let jointIdx = 0; jointIdx < this._jointTransforms.length; jointIdx++) { - const jointTransform = (this._jointTransforms[jointIdx] = new transformNode_TransformNode(handJointReferenceArray[jointIdx], this._scene)); - jointTransform.rotationQuaternion = new math_vector_Quaternion(); - // Set the rotation quaternion so we can use it later for tracking. - _jointMeshes[jointIdx].rotationQuaternion = new math_vector_Quaternion(); - } - if (_handMesh) { - // Note that this logic needs to happen after we initialize the joint tracking transform nodes. - this.setHandMesh(_handMesh, rigMapping); - } - // hide the motion controller, if available/loaded - if (this.xrController.motionController) { - if (this.xrController.motionController.rootMesh) { - this.xrController.motionController.rootMesh.setEnabled(false); - } - else { - this.xrController.motionController.onModelLoadedObservable.add((controller) => { - if (controller.rootMesh) { - controller.rootMesh.setEnabled(false); - } - }); - } - } - this.xrController.onMotionControllerInitObservable.add((motionController) => { - motionController.onModelLoadedObservable.add((controller) => { - if (controller.rootMesh) { - controller.rootMesh.setEnabled(false); - } - }); - if (motionController.rootMesh) { - motionController.rootMesh.setEnabled(false); - } - }); - } - /** - * Sets the current hand mesh to render for the WebXRHand. - * @param handMesh The rigged hand mesh that will be tracked to the user's hand. - * @param rigMapping The mapping from XRHandJoint to bone names to use with the mesh. - */ - setHandMesh(handMesh, rigMapping) { - this._handMesh = handMesh; - // Avoid any strange frustum culling. We will manually control visibility via attach and detach. - handMesh.alwaysSelectAsActiveMesh = true; - handMesh.getChildMeshes().forEach((mesh) => (mesh.alwaysSelectAsActiveMesh = true)); - // Link the bones in the hand mesh to the transform nodes that will be bound to the WebXR tracked joints. - if (this._handMesh.skeleton) { - const handMeshSkeleton = this._handMesh.skeleton; - handJointReferenceArray.forEach((jointName, jointIdx) => { - const jointBoneIdx = handMeshSkeleton.getBoneIndexByName(rigMapping ? rigMapping[jointName] : jointName); - if (jointBoneIdx !== -1) { - handMeshSkeleton.bones[jointBoneIdx].linkTransformNode(this._jointTransforms[jointIdx]); - } - }); - } - } - /** - * Update this hand from the latest xr frame. - * @param xrFrame The latest frame received from WebXR. - * @param referenceSpace The current viewer reference space. - */ - updateFromXRFrame(xrFrame, referenceSpace) { - const hand = this.xrController.inputSource.hand; - if (!hand) { - return; - } - // TODO: Modify webxr.d.ts to better match WebXR IDL so we don't need this any cast. - const anyHand = hand; - const jointSpaces = handJointReferenceArray.map((jointName) => anyHand[jointName] || hand.get(jointName)); - let trackingSuccessful = false; - if (xrFrame.fillPoses && xrFrame.fillJointRadii) { - trackingSuccessful = xrFrame.fillPoses(jointSpaces, referenceSpace, this._jointTransformMatrices) && xrFrame.fillJointRadii(jointSpaces, this._jointRadii); - } - else if (xrFrame.getJointPose) { - trackingSuccessful = true; - // Warning: This codepath is slow by comparison, only here for compat. - for (let jointIdx = 0; jointIdx < jointSpaces.length; jointIdx++) { - const jointPose = xrFrame.getJointPose(jointSpaces[jointIdx], referenceSpace); - if (jointPose) { - this._jointTransformMatrices.set(jointPose.transform.matrix, jointIdx * 16); - this._jointRadii[jointIdx] = jointPose.radius || 0.008; - } - else { - trackingSuccessful = false; - break; - } - } - } - if (!trackingSuccessful) { - return; - } - handJointReferenceArray.forEach((_jointName, jointIdx) => { - const jointTransform = this._jointTransforms[jointIdx]; - math_vector_Matrix.FromArrayToRef(this._jointTransformMatrices, jointIdx * 16, this._tempJointMatrix); - this._tempJointMatrix.decompose(undefined, jointTransform.rotationQuaternion, jointTransform.position); - // The radius we need to make the joint in order for it to roughly cover the joints of the user's real hand. - const scaledJointRadius = this._jointRadii[jointIdx] * this._jointScaleFactor; - const jointMesh = this._jointMeshes[jointIdx]; - jointMesh.isVisible = !this._handMesh && !this._jointsInvisible; - jointMesh.position.copyFrom(jointTransform.position); - jointMesh.rotationQuaternion.copyFrom(jointTransform.rotationQuaternion); - jointMesh.scaling.setAll(scaledJointRadius); - // The WebXR data comes as right-handed, so we might need to do some conversions. - if (!this._scene.useRightHandedSystem) { - jointMesh.position.z *= -1; - jointMesh.rotationQuaternion.z *= -1; - jointMesh.rotationQuaternion.w *= -1; - if (this._leftHandedMeshes && this._handMesh) { - jointTransform.position.z *= -1; - jointTransform.rotationQuaternion.z *= -1; - jointTransform.rotationQuaternion.w *= -1; - } - } - }); - if (this._handMesh) { - this._handMesh.isVisible = true; - } - } - /** - * Dispose this Hand object - */ - dispose() { - if (this._handMesh) { - this._handMesh.isVisible = false; - } - } -} -/** - * WebXR Hand Joint tracking feature, available for selected browsers and devices - */ -class WebXRHandTracking extends WebXRAbstractFeature { - static _GenerateTrackedJointMeshes(featureOptions) { - const meshes = {}; - ["left", "right"].map((handedness) => { - var _a, _b, _c, _d, _e; - const trackedMeshes = []; - const originalMesh = ((_a = featureOptions.jointMeshes) === null || _a === void 0 ? void 0 : _a.sourceMesh) || CreateIcoSphere("jointParent", WebXRHandTracking._ICOSPHERE_PARAMS); - originalMesh.isVisible = !!((_b = featureOptions.jointMeshes) === null || _b === void 0 ? void 0 : _b.keepOriginalVisible); - for (let i = 0; i < handJointReferenceArray.length; ++i) { - let newInstance = originalMesh.createInstance(`${handedness}-handJoint-${i}`); - if ((_c = featureOptions.jointMeshes) === null || _c === void 0 ? void 0 : _c.onHandJointMeshGenerated) { - const returnedMesh = featureOptions.jointMeshes.onHandJointMeshGenerated(newInstance, i, handedness); - if (returnedMesh) { - if (returnedMesh !== newInstance) { - newInstance.dispose(); - newInstance = returnedMesh; - } - } - } - newInstance.isPickable = false; - if ((_d = featureOptions.jointMeshes) === null || _d === void 0 ? void 0 : _d.enablePhysics) { - const props = ((_e = featureOptions.jointMeshes) === null || _e === void 0 ? void 0 : _e.physicsProps) || {}; - // downscale the instances so that physics will be initialized correctly - newInstance.scaling.setAll(0.02); - const type = props.impostorType !== undefined ? props.impostorType : physicsImpostor_PhysicsImpostor.SphereImpostor; - newInstance.physicsImpostor = new physicsImpostor_PhysicsImpostor(newInstance, type, Object.assign({ mass: 0 }, props)); - } - newInstance.rotationQuaternion = new math_vector_Quaternion(); - newInstance.isVisible = false; - trackedMeshes.push(newInstance); - } - meshes[handedness] = trackedMeshes; - }); - return { left: meshes.left, right: meshes.right }; - } - static _GenerateDefaultHandMeshesAsync(scene, options) { - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve) => { - var _a, _b, _c, _d, _e; - const riggedMeshes = {}; - // check the cache, defensive - if ((_b = (_a = WebXRHandTracking._RightHandGLB) === null || _a === void 0 ? void 0 : _a.meshes[1]) === null || _b === void 0 ? void 0 : _b.isDisposed()) { - WebXRHandTracking._RightHandGLB = null; - } - if ((_d = (_c = WebXRHandTracking._LeftHandGLB) === null || _c === void 0 ? void 0 : _c.meshes[1]) === null || _d === void 0 ? void 0 : _d.isDisposed()) { - WebXRHandTracking._LeftHandGLB = null; - } - const handsDefined = !!(WebXRHandTracking._RightHandGLB && WebXRHandTracking._LeftHandGLB); - // load them in parallel - const handGLBs = await Promise.all([ - WebXRHandTracking._RightHandGLB || - sceneLoader_SceneLoader.ImportMeshAsync("", WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL, WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME, scene), - WebXRHandTracking._LeftHandGLB || - sceneLoader_SceneLoader.ImportMeshAsync("", WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL, WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME, scene), - ]); - WebXRHandTracking._RightHandGLB = handGLBs[0]; - WebXRHandTracking._LeftHandGLB = handGLBs[1]; - const handShader = new NodeMaterial("handShader", scene, { emitComments: false }); - await handShader.loadAsync(WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL); - // depth prepass and alpha mode - handShader.needDepthPrePass = true; - handShader.transparencyMode = material_Material.MATERIAL_ALPHABLEND; - handShader.alphaMode = 2; - // build node materials - handShader.build(false); - // shader - const handColors = Object.assign({ base: math_color_Color3.FromInts(116, 63, 203), fresnel: math_color_Color3.FromInts(149, 102, 229), fingerColor: math_color_Color3.FromInts(177, 130, 255), tipFresnel: math_color_Color3.FromInts(220, 200, 255) }, (_e = options === null || options === void 0 ? void 0 : options.handMeshes) === null || _e === void 0 ? void 0 : _e.customColors); - const handNodes = { - base: handShader.getBlockByName("baseColor"), - fresnel: handShader.getBlockByName("fresnelColor"), - fingerColor: handShader.getBlockByName("fingerColor"), - tipFresnel: handShader.getBlockByName("tipFresnelColor"), - }; - handNodes.base.value = handColors.base; - handNodes.fresnel.value = handColors.fresnel; - handNodes.fingerColor.value = handColors.fingerColor; - handNodes.tipFresnel.value = handColors.tipFresnel; - ["left", "right"].forEach((handedness) => { - const handGLB = handedness == "left" ? WebXRHandTracking._LeftHandGLB : WebXRHandTracking._RightHandGLB; - if (!handGLB) { - // this should never happen! - throw new Error("Could not load hand model"); - } - const handMesh = handGLB.meshes[1]; - handMesh._internalAbstractMeshDataInfo._computeBonesUsingShaders = true; - handMesh.material = handShader.clone(`${handedness}HandShaderClone`, true); - handMesh.isVisible = false; - riggedMeshes[handedness] = handMesh; - // single change for left handed systems - if (!handsDefined && !scene.useRightHandedSystem) { - handGLB.meshes[1].rotate(math_axis_Axis.Y, Math.PI); - } - }); - handShader.dispose(); - resolve({ left: riggedMeshes.left, right: riggedMeshes.right }); - }); - } - /** - * Generates a mapping from XRHandJoint to bone name for the default hand mesh. - * @param handedness The handedness being mapped for. - */ - static _GenerateDefaultHandMeshRigMapping(handedness) { - const H = handedness == "right" ? "R" : "L"; - return { - [WebXRHandTracking_WebXRHandJoint.WRIST]: `wrist_${H}`, - [WebXRHandTracking_WebXRHandJoint.THUMB_METACARPAL]: `thumb_metacarpal_${H}`, - [WebXRHandTracking_WebXRHandJoint.THUMB_PHALANX_PROXIMAL]: `thumb_proxPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.THUMB_PHALANX_DISTAL]: `thumb_distPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.THUMB_TIP]: `thumb_tip_${H}`, - [WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_METACARPAL]: `index_metacarpal_${H}`, - [WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL]: `index_proxPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE]: `index_intPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL]: `index_distPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.INDEX_FINGER_TIP]: `index_tip_${H}`, - [WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_METACARPAL]: `middle_metacarpal_${H}`, - [WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL]: `middle_proxPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE]: `middle_intPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL]: `middle_distPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.MIDDLE_FINGER_TIP]: `middle_tip_${H}`, - [WebXRHandTracking_WebXRHandJoint.RING_FINGER_METACARPAL]: `ring_metacarpal_${H}`, - [WebXRHandTracking_WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL]: `ring_proxPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE]: `ring_intPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.RING_FINGER_PHALANX_DISTAL]: `ring_distPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.RING_FINGER_TIP]: `ring_tip_${H}`, - [WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_METACARPAL]: `little_metacarpal_${H}`, - [WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL]: `little_proxPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE]: `little_intPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL]: `little_distPhalanx_${H}`, - [WebXRHandTracking_WebXRHandJoint.PINKY_FINGER_TIP]: `little_tip_${H}`, - }; - } - /** - * Check if the needed objects are defined. - * This does not mean that the feature is enabled, but that the objects needed are well defined. - */ - isCompatible() { - return typeof XRHand !== "undefined"; - } - /** - * Get the hand object according to the controller id - * @param controllerId the controller id to which we want to get the hand - * @returns null if not found or the WebXRHand object if found - */ - getHandByControllerId(controllerId) { - return this._attachedHands[controllerId]; - } - /** - * Get a hand object according to the requested handedness - * @param handedness the handedness to request - * @returns null if not found or the WebXRHand object if found - */ - getHandByHandedness(handedness) { - if (handedness == "none") { - return null; - } - return this._trackingHands[handedness]; - } - /** - * Creates a new instance of the XR hand tracking feature. - * @param _xrSessionManager An instance of WebXRSessionManager. - * @param options Options to use when constructing this feature. - */ - constructor(_xrSessionManager, - /** Options to use when constructing this feature. */ - options) { - super(_xrSessionManager); - this.options = options; - this._attachedHands = {}; - this._trackingHands = { left: null, right: null }; - this._handResources = { jointMeshes: null, handMeshes: null, rigMappings: null }; - /** - * This observable will notify registered observers when a new hand object was added and initialized - */ - this.onHandAddedObservable = new observable_Observable(); - /** - * This observable will notify its observers right before the hand object is disposed - */ - this.onHandRemovedObservable = new observable_Observable(); - this._attachHand = (xrController) => { - var _a, _b, _c; - if (!xrController.inputSource.hand || xrController.inputSource.handedness == "none" || !this._handResources.jointMeshes) { - return; - } - const handedness = xrController.inputSource.handedness; - 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); - this._attachedHands[xrController.uniqueId] = webxrHand; - this._trackingHands[handedness] = webxrHand; - this.onHandAddedObservable.notifyObservers(webxrHand); - }; - this._detachHand = (xrController) => { - this._detachHandById(xrController.uniqueId); - }; - this.xrNativeFeatureName = "hand-tracking"; - // Support legacy versions of the options object by copying over joint mesh properties - const anyOptions = options; - const anyJointMeshOptions = anyOptions.jointMeshes; - if (anyJointMeshOptions) { - if (typeof anyJointMeshOptions.disableDefaultHandMesh !== "undefined") { - options.handMeshes = options.handMeshes || {}; - options.handMeshes.disableDefaultMeshes = anyJointMeshOptions.disableDefaultHandMesh; - } - if (typeof anyJointMeshOptions.handMeshes !== "undefined") { - options.handMeshes = options.handMeshes || {}; - options.handMeshes.customMeshes = anyJointMeshOptions.handMeshes; - } - if (typeof anyJointMeshOptions.leftHandedSystemMeshes !== "undefined") { - options.handMeshes = options.handMeshes || {}; - options.handMeshes.meshesUseLeftHandedCoordinates = anyJointMeshOptions.leftHandedSystemMeshes; - } - if (typeof anyJointMeshOptions.rigMapping !== "undefined") { - options.handMeshes = options.handMeshes || {}; - const leftRigMapping = {}; - const rightRigMapping = {}; - [ - [anyJointMeshOptions.rigMapping.left, leftRigMapping], - [anyJointMeshOptions.rigMapping.right, rightRigMapping], - ].forEach((rigMappingTuple) => { - const legacyRigMapping = rigMappingTuple[0]; - const rigMapping = rigMappingTuple[1]; - legacyRigMapping.forEach((modelJointName, index) => { - rigMapping[handJointReferenceArray[index]] = modelJointName; - }); - }); - options.handMeshes.customRigMappings = { - left: leftRigMapping, - right: rightRigMapping, - }; - } - } - } - /** - * Attach this feature. - * Will usually be called by the features manager. - * - * @returns true if successful. - */ - attach() { - var _a, _b, _c, _d; - if (!super.attach()) { - return false; - } - this._handResources = { - jointMeshes: WebXRHandTracking._GenerateTrackedJointMeshes(this.options), - handMeshes: ((_a = this.options.handMeshes) === null || _a === void 0 ? void 0 : _a.customMeshes) || null, - rigMappings: ((_b = this.options.handMeshes) === null || _b === void 0 ? void 0 : _b.customRigMappings) || null, - }; - // If they didn't supply custom meshes and are not disabling the default meshes... - 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)) { - WebXRHandTracking._GenerateDefaultHandMeshesAsync(engineStore_EngineStore.LastCreatedScene, this.options).then((defaultHandMeshes) => { - var _a, _b; - this._handResources.handMeshes = defaultHandMeshes; - this._handResources.rigMappings = { - left: WebXRHandTracking._GenerateDefaultHandMeshRigMapping("left"), - right: WebXRHandTracking._GenerateDefaultHandMeshRigMapping("right"), - }; - // Apply meshes to existing hands if already tracking. - (_a = this._trackingHands.left) === null || _a === void 0 ? void 0 : _a.setHandMesh(this._handResources.handMeshes.left, this._handResources.rigMappings.left); - (_b = this._trackingHands.right) === null || _b === void 0 ? void 0 : _b.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); - return true; - } - _onXRFrame(_xrFrame) { - var _a, _b; - (_a = this._trackingHands.left) === null || _a === void 0 ? void 0 : _a.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace); - (_b = this._trackingHands.right) === null || _b === void 0 ? void 0 : _b.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace); - } - _detachHandById(controllerId) { - var _a; - const hand = this.getHandByControllerId(controllerId); - if (hand) { - const handedness = hand.xrController.inputSource.handedness == "left" ? "left" : "right"; - if (((_a = this._trackingHands[handedness]) === null || _a === void 0 ? void 0 : _a.xrController.uniqueId) === controllerId) { - this._trackingHands[handedness] = null; - } - this.onHandRemovedObservable.notifyObservers(hand); - hand.dispose(); - delete this._attachedHands[controllerId]; - } - } - /** - * Detach this feature. - * Will usually be called by the features manager. - * - * @returns true if successful. - */ - detach() { - if (!super.detach()) { - return false; - } - Object.keys(this._attachedHands).forEach((uniqueId) => this._detachHandById(uniqueId)); - return true; - } - /** - * Dispose this feature and all of the resources attached. - */ - dispose() { - var _a; - super.dispose(); - this.onHandAddedObservable.clear(); - this.onHandRemovedObservable.clear(); - if (this._handResources.handMeshes && !((_a = this.options.handMeshes) === null || _a === void 0 ? void 0 : _a.customMeshes)) { - // this will dispose the cached meshes - this._handResources.handMeshes.left.dispose(); - this._handResources.handMeshes.right.dispose(); - // remove the cached meshes - WebXRHandTracking._RightHandGLB = null; - WebXRHandTracking._LeftHandGLB = null; - } - if (this._handResources.jointMeshes) { - this._handResources.jointMeshes.left.forEach((trackedMesh) => trackedMesh.dispose()); - this._handResources.jointMeshes.right.forEach((trackedMesh) => trackedMesh.dispose()); - } - } -} -/** - * The module's name - */ -WebXRHandTracking.Name = webXRFeaturesManager_WebXRFeatureName.HAND_TRACKING; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRHandTracking.Version = 1; -/** The base URL for the default hand model. */ -WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL = "https://assets.babylonjs.com/meshes/HandMeshes/"; -/** The filename to use for the default right hand model. */ -WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME = "r_hand_rhs.glb"; -/** The filename to use for the default left hand model. */ -WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME = "l_hand_rhs.glb"; -/** The URL pointing to the default hand model NodeMaterial shader. */ -WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL = "https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json"; -// We want to use lightweight models, diameter will initially be 1 but scaled to the values returned from WebXR. -WebXRHandTracking._ICOSPHERE_PARAMS = { radius: 0.5, flat: false, subdivisions: 2 }; -WebXRHandTracking._RightHandGLB = null; -WebXRHandTracking._LeftHandGLB = null; -//register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRHandTracking.Name, (xrSessionManager, options) => { - return () => new WebXRHandTracking(xrSessionManager, options); -}, WebXRHandTracking.Version, false); -//# sourceMappingURL=WebXRHandTracking.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Meshes/handConstraintBehavior.js - - - - -/** - * Zones around the hand - */ -var HandConstraintZone; -(function (HandConstraintZone) { - /** - * Above finger tips - */ - HandConstraintZone[HandConstraintZone["ABOVE_FINGER_TIPS"] = 0] = "ABOVE_FINGER_TIPS"; - /** - * Next to the thumb - */ - HandConstraintZone[HandConstraintZone["RADIAL_SIDE"] = 1] = "RADIAL_SIDE"; - /** - * Next to the pinky finger - */ - HandConstraintZone[HandConstraintZone["ULNAR_SIDE"] = 2] = "ULNAR_SIDE"; - /** - * Below the wrist - */ - HandConstraintZone[HandConstraintZone["BELOW_WRIST"] = 3] = "BELOW_WRIST"; -})(HandConstraintZone || (HandConstraintZone = {})); -/** - * Orientations for the hand zones and for the attached node - */ -var HandConstraintOrientation; -(function (HandConstraintOrientation) { - /** - * Orientation is towards the camera - */ - HandConstraintOrientation[HandConstraintOrientation["LOOK_AT_CAMERA"] = 0] = "LOOK_AT_CAMERA"; - /** - * Orientation is determined by the rotation of the palm - */ - HandConstraintOrientation[HandConstraintOrientation["HAND_ROTATION"] = 1] = "HAND_ROTATION"; -})(HandConstraintOrientation || (HandConstraintOrientation = {})); -/** - * Orientations for the hand zones and for the attached node - */ -var HandConstraintVisibility; -(function (HandConstraintVisibility) { - /** - * Constraint is always visible - */ - HandConstraintVisibility[HandConstraintVisibility["ALWAYS_VISIBLE"] = 0] = "ALWAYS_VISIBLE"; - /** - * Constraint is only visible when the palm is up - */ - HandConstraintVisibility[HandConstraintVisibility["PALM_UP"] = 1] = "PALM_UP"; - /** - * Constraint is only visible when the user is looking at the constraint. - * Uses XR Eye Tracking if enabled/available, otherwise uses camera direction - */ - HandConstraintVisibility[HandConstraintVisibility["GAZE_FOCUS"] = 2] = "GAZE_FOCUS"; - /** - * Constraint is only visible when the palm is up and the user is looking at it - */ - HandConstraintVisibility[HandConstraintVisibility["PALM_AND_GAZE"] = 3] = "PALM_AND_GAZE"; -})(HandConstraintVisibility || (HandConstraintVisibility = {})); -/** - * Hand constraint behavior that makes the attached `TransformNode` follow hands in XR experiences. - * @since 5.0.0 - */ -class HandConstraintBehavior { - /** - * Builds a hand constraint behavior - */ - constructor() { - this._sceneRenderObserver = null; - this._zoneAxis = {}; - /** - * Sets the HandConstraintVisibility level for the hand constraint - */ - this.handConstraintVisibility = HandConstraintVisibility.PALM_AND_GAZE; - /** - * A number from 0.0 to 1.0, marking how restricted the direction the palm faces is for the attached node to be enabled. - * A 1 means the palm must be directly facing the user before the node is enabled, a 0 means it is always enabled. - * Used with HandConstraintVisibility.PALM_UP - */ - this.palmUpStrictness = 0.95; - /** - * 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. - * Used with HandConstraintVisibility.GAZE_FOCUS - */ - this.gazeProximityRadius = 0.15; - /** - * Offset distance from the hand in meters - */ - this.targetOffset = 0.1; - /** - * Where to place the node regarding the center of the hand. - */ - this.targetZone = HandConstraintZone.ULNAR_SIDE; - /** - * Orientation mode of the 4 zones around the hand - */ - this.zoneOrientationMode = HandConstraintOrientation.HAND_ROTATION; - /** - * Orientation mode of the node attached to this behavior - */ - this.nodeOrientationMode = HandConstraintOrientation.HAND_ROTATION; - /** - * Set the hand this behavior should follow. If set to "none", it will follow any visible hand (prioritising the left one). - */ - this.handedness = "none"; - /** - * Rate of interpolation of position and rotation of the attached node. - * Higher values will give a slower interpolation. - */ - this.lerpTime = 100; - // For a right hand - this._zoneAxis[HandConstraintZone.ABOVE_FINGER_TIPS] = new Vector3(0, 1, 0); - this._zoneAxis[HandConstraintZone.RADIAL_SIDE] = new Vector3(-1, 0, 0); - this._zoneAxis[HandConstraintZone.ULNAR_SIDE] = new Vector3(1, 0, 0); - this._zoneAxis[HandConstraintZone.BELOW_WRIST] = new Vector3(0, -1, 0); - } - /** gets or sets behavior's name */ - get name() { - return "HandConstraint"; - } - /** Enable the behavior */ - enable() { - this._node.setEnabled(true); - } - /** Disable the behavior */ - disable() { - this._node.setEnabled(false); - } - _getHandPose() { - if (!this._handTracking) { - return null; - } - // Retrieve any available hand, starting by the left - let hand; - if (this.handedness === "none") { - hand = this._handTracking.getHandByHandedness("left") || this._handTracking.getHandByHandedness("right"); - } - else { - hand = this._handTracking.getHandByHandedness(this.handedness); - } - if (hand) { - const pinkyMetacarpal = hand.getJointMesh(WebXRHandJoint.PINKY_FINGER_METACARPAL); - const middleMetacarpal = hand.getJointMesh(WebXRHandJoint.MIDDLE_FINGER_METACARPAL); - const wrist = hand.getJointMesh(WebXRHandJoint.WRIST); - if (wrist && middleMetacarpal && pinkyMetacarpal) { - const handPose = { position: middleMetacarpal.absolutePosition, quaternion: new Quaternion(), id: hand.xrController.uniqueId }; - // palm forward - const up = TmpVectors.Vector3[0]; - const forward = TmpVectors.Vector3[1]; - const left = TmpVectors.Vector3[2]; - up.copyFrom(middleMetacarpal.absolutePosition).subtractInPlace(wrist.absolutePosition).normalize(); - forward.copyFrom(pinkyMetacarpal.absolutePosition).subtractInPlace(middleMetacarpal.absolutePosition).normalize(); - // Create vectors for a rotation quaternion, where forward points out from the palm - Vector3.CrossToRef(up, forward, forward); - Vector3.CrossToRef(forward, up, left); - Quaternion.FromLookDirectionLHToRef(forward, up, handPose.quaternion); - return handPose; - } - } - return null; - } - /** - * Initializes the hand constraint behavior - */ - init() { } - /** - * Attaches the hand constraint to a `TransformNode` - * @param node defines the node to attach the behavior to - */ - attach(node) { - this._node = node; - this._scene = node.getScene(); - if (!this._node.rotationQuaternion) { - this._node.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._node.rotation.y, this._node.rotation.x, this._node.rotation.z); - } - let lastTick = Date.now(); - this._sceneRenderObserver = this._scene.onBeforeRenderObservable.add(() => { - const pose = this._getHandPose(); - this._node.reservedDataStore = this._node.reservedDataStore || {}; - this._node.reservedDataStore.nearInteraction = this._node.reservedDataStore.nearInteraction || {}; - this._node.reservedDataStore.nearInteraction.excludedControllerId = null; - if (pose) { - const zoneOffset = TmpVectors.Vector3[0]; - const camera = this._scene.activeCamera; - zoneOffset.copyFrom(this._zoneAxis[this.targetZone]); - const cameraLookAtQuaternion = TmpVectors.Quaternion[0]; - if (camera && (this.zoneOrientationMode === HandConstraintOrientation.LOOK_AT_CAMERA || this.nodeOrientationMode === HandConstraintOrientation.LOOK_AT_CAMERA)) { - const toCamera = TmpVectors.Vector3[1]; - toCamera.copyFrom(camera.position).subtractInPlace(pose.position).normalize(); - if (this._scene.useRightHandedSystem) { - Quaternion.FromLookDirectionRHToRef(toCamera, Vector3.UpReadOnly, cameraLookAtQuaternion); - } - else { - Quaternion.FromLookDirectionLHToRef(toCamera, Vector3.UpReadOnly, cameraLookAtQuaternion); - } - } - if (this.zoneOrientationMode === HandConstraintOrientation.HAND_ROTATION) { - pose.quaternion.toRotationMatrix(TmpVectors.Matrix[0]); - } - else { - cameraLookAtQuaternion.toRotationMatrix(TmpVectors.Matrix[0]); - } - Vector3.TransformNormalToRef(zoneOffset, TmpVectors.Matrix[0], zoneOffset); - zoneOffset.scaleInPlace(this.targetOffset); - const targetPosition = TmpVectors.Vector3[2]; - const targetRotation = TmpVectors.Quaternion[1]; - targetPosition.copyFrom(pose.position).addInPlace(zoneOffset); - if (this.nodeOrientationMode === HandConstraintOrientation.HAND_ROTATION) { - targetRotation.copyFrom(pose.quaternion); - } - else { - targetRotation.copyFrom(cameraLookAtQuaternion); - } - const elapsed = Date.now() - lastTick; - Vector3.SmoothToRef(this._node.position, targetPosition, elapsed, this.lerpTime, this._node.position); - Quaternion.SmoothToRef(this._node.rotationQuaternion, targetRotation, elapsed, this.lerpTime, this._node.rotationQuaternion); - this._node.reservedDataStore.nearInteraction.excludedControllerId = pose.id; - } - this._setVisibility(pose); - lastTick = Date.now(); - }); - } - _setVisibility(pose) { - let palmVisible = true; - let gazeVisible = true; - const camera = this._scene.activeCamera; - if (camera) { - const cameraForward = camera.getForwardRay(); - if (this.handConstraintVisibility === HandConstraintVisibility.GAZE_FOCUS || this.handConstraintVisibility === HandConstraintVisibility.PALM_AND_GAZE) { - gazeVisible = false; - let gaze; - if (this._eyeTracking) { - gaze = this._eyeTracking.getEyeGaze(); - } - gaze = gaze || cameraForward; - const gazeToBehavior = TmpVectors.Vector3[0]; - if (pose) { - pose.position.subtractToRef(gaze.origin, gazeToBehavior); - } - else { - this._node.getAbsolutePosition().subtractToRef(gaze.origin, gazeToBehavior); - } - const projectedDistance = Vector3.Dot(gazeToBehavior, gaze.direction); - const projectedSquared = projectedDistance * projectedDistance; - if (projectedDistance > 0) { - const radiusSquared = gazeToBehavior.lengthSquared() - projectedSquared; - if (radiusSquared < this.gazeProximityRadius * this.gazeProximityRadius) { - gazeVisible = true; - } - } - } - if (this.handConstraintVisibility === HandConstraintVisibility.PALM_UP || this.handConstraintVisibility === HandConstraintVisibility.PALM_AND_GAZE) { - palmVisible = false; - if (pose) { - const palmDirection = TmpVectors.Vector3[0]; - Vector3.LeftHandedForwardReadOnly.rotateByQuaternionToRef(pose.quaternion, palmDirection); - if (Vector3.Dot(palmDirection, cameraForward.direction) > this.palmUpStrictness * 2 - 1) { - palmVisible = true; - } - } - } - } - this._node.setEnabled(palmVisible && gazeVisible); - } - /** - * Detaches the behavior from the `TransformNode` - */ - detach() { - this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver); - } - /** - * Links the behavior to the XR experience in which to retrieve hand transform information. - * @param xr xr experience - */ - linkToXRExperience(xr) { - const featuresManager = xr.featuresManager ? xr.featuresManager : xr; - if (!featuresManager) { - Tools.Error("XR features manager must be available or provided directly for the Hand Menu to work"); - } - else { - try { - this._eyeTracking = featuresManager.getEnabledFeature(WebXRFeatureName.EYE_TRACKING); - } - catch (_a) { } - try { - this._handTracking = featuresManager.getEnabledFeature(WebXRFeatureName.HAND_TRACKING); - } - catch (_b) { - Tools.Error("Hand tracking must be enabled for the Hand Menu to work"); - } - } - } -} -//# sourceMappingURL=handConstraintBehavior.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/Meshes/index.js - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Behaviors/index.js -/* eslint-disable import/no-internal-modules */ - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Bones/boneIKController.js - - - -/** - * Class used to apply inverse kinematics to bones - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons#boneikcontroller - */ -class BoneIKController { - /** - * Gets or sets maximum allowed angle - */ - get maxAngle() { - return this._maxAngle; - } - set maxAngle(value) { - this._setMaxAngle(value); - } - /** - * Creates a new BoneIKController - * @param mesh defines the TransformNode to control - * @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. - * @param options defines options to set up the controller - * @param options.targetMesh - * @param options.poleTargetMesh - * @param options.poleTargetBone - * @param options.poleTargetLocalOffset - * @param options.poleAngle - * @param options.bendAxis - * @param options.maxAngle - * @param options.slerpAmount - */ - constructor(mesh, bone, options) { - /** - * Gets or sets the target position - */ - this.targetPosition = math_vector_Vector3.Zero(); - /** - * Gets or sets the pole target position - */ - this.poleTargetPosition = math_vector_Vector3.Zero(); - /** - * Gets or sets the pole target local offset - */ - this.poleTargetLocalOffset = math_vector_Vector3.Zero(); - /** - * Gets or sets the pole angle - */ - this.poleAngle = 0; - /** - * 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) - */ - this.slerpAmount = 1; - this._bone1Quat = math_vector_Quaternion.Identity(); - this._bone1Mat = math_vector_Matrix.Identity(); - this._bone2Ang = Math.PI; - this._maxAngle = Math.PI; - this._rightHandedSystem = false; - this._bendAxis = math_vector_Vector3.Right(); - this._slerping = false; - this._adjustRoll = 0; - this._notEnoughInformation = false; - this._bone2 = bone; - const bone1 = bone.getParent(); - if (!bone1) { - this._notEnoughInformation = true; - logger_Logger.Error("BoneIKController: bone must have a parent for IK to work."); - return; - } - this._bone1 = bone1; - if (this._bone2.children.length === 0 && !this._bone2.length) { - this._notEnoughInformation = true; - logger_Logger.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work."); - return; - } - this.mesh = mesh; - bone.getSkeleton().computeAbsoluteMatrices(); - const bonePos = bone.getPosition(); - if (bone.getAbsoluteMatrix().determinant() > 0) { - this._rightHandedSystem = true; - this._bendAxis.x = 0; - this._bendAxis.y = 0; - this._bendAxis.z = -1; - if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) { - this._adjustRoll = Math.PI * 0.5; - this._bendAxis.z = 1; - } - } - if (this._bone1.length && this._bone2.length) { - const boneScale1 = this._bone1.getScale(); - const boneScale2 = this._bone2.getScale(); - this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y; - this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y; - } - else if (this._bone2.children[0]) { - mesh.computeWorldMatrix(true); - const pos1 = this._bone2.children[0].getAbsolutePosition(mesh); - const pos2 = this._bone2.getAbsolutePosition(mesh); - const pos3 = this._bone1.getAbsolutePosition(mesh); - this._bone2Length = math_vector_Vector3.Distance(pos1, pos2); - this._bone1Length = math_vector_Vector3.Distance(pos2, pos3); - } - else { - mesh.computeWorldMatrix(true); - const boneScale2 = this._bone2.getScale(); - this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y; - const pos2 = this._bone2.getAbsolutePosition(mesh); - const pos3 = this._bone1.getAbsolutePosition(mesh); - this._bone1Length = math_vector_Vector3.Distance(pos2, pos3); - } - this._bone1.getRotationMatrixToRef(math_axis_Space.WORLD, mesh, this._bone1Mat); - this.maxAngle = Math.PI; - if (options) { - if (options.targetMesh) { - this.targetMesh = options.targetMesh; - this.targetMesh.computeWorldMatrix(true); - } - if (options.poleTargetMesh) { - this.poleTargetMesh = options.poleTargetMesh; - this.poleTargetMesh.computeWorldMatrix(true); - } - else if (options.poleTargetBone) { - this.poleTargetBone = options.poleTargetBone; - } - else if (this._bone1.getParent()) { - this.poleTargetBone = this._bone1.getParent(); - } - if (options.poleTargetLocalOffset) { - this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset); - } - if (options.poleAngle) { - this.poleAngle = options.poleAngle; - } - if (options.bendAxis) { - this._bendAxis.copyFrom(options.bendAxis); - } - if (options.maxAngle) { - this.maxAngle = options.maxAngle; - } - if (options.slerpAmount) { - this.slerpAmount = options.slerpAmount; - } - } - } - _setMaxAngle(ang) { - if (ang < 0) { - ang = 0; - } - if (ang > Math.PI || ang == undefined) { - ang = Math.PI; - } - this._maxAngle = ang; - const a = this._bone1Length; - const b = this._bone2Length; - this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang)); - } - /** - * Force the controller to update the bones - */ - update() { - if (this._notEnoughInformation) { - return; - } - const target = this.targetPosition; - const poleTarget = this.poleTargetPosition; - const mat1 = BoneIKController._TmpMats[0]; - const mat2 = BoneIKController._TmpMats[1]; - if (this.targetMesh) { - target.copyFrom(this.targetMesh.getAbsolutePosition()); - } - if (this.poleTargetBone) { - this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget); - } - else if (this.poleTargetMesh) { - math_vector_Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget); - } - const bonePos = BoneIKController._TmpVecs[0]; - const zaxis = BoneIKController._TmpVecs[1]; - const xaxis = BoneIKController._TmpVecs[2]; - const yaxis = BoneIKController._TmpVecs[3]; - const upAxis = BoneIKController._TmpVecs[4]; - const tmpQuat = BoneIKController._TmpQuat; - this._bone1.getAbsolutePositionToRef(this.mesh, bonePos); - poleTarget.subtractToRef(bonePos, upAxis); - if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) { - upAxis.y = 1; - } - else { - upAxis.normalize(); - } - target.subtractToRef(bonePos, yaxis); - yaxis.normalize(); - math_vector_Vector3.CrossToRef(yaxis, upAxis, zaxis); - zaxis.normalize(); - math_vector_Vector3.CrossToRef(yaxis, zaxis, xaxis); - xaxis.normalize(); - math_vector_Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1); - const a = this._bone1Length; - const b = this._bone2Length; - let c = math_vector_Vector3.Distance(bonePos, target); - if (this._maxReach > 0) { - c = Math.min(this._maxReach, c); - } - let acosa = (b * b + c * c - a * a) / (2 * b * c); - let acosb = (c * c + a * a - b * b) / (2 * c * a); - if (acosa > 1) { - acosa = 1; - } - if (acosb > 1) { - acosb = 1; - } - if (acosa < -1) { - acosa = -1; - } - if (acosb < -1) { - acosb = -1; - } - const angA = Math.acos(acosa); - const angB = Math.acos(acosb); - let angC = -angA - angB; - if (this._rightHandedSystem) { - math_vector_Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2); - mat2.multiplyToRef(mat1, mat1); - math_vector_Matrix.RotationAxisToRef(this._bendAxis, angB, mat2); - mat2.multiplyToRef(mat1, mat1); - } - else { - const _tmpVec = BoneIKController._TmpVecs[5]; - _tmpVec.copyFrom(this._bendAxis); - _tmpVec.x *= -1; - math_vector_Matrix.RotationAxisToRef(_tmpVec, -angB, mat2); - mat2.multiplyToRef(mat1, mat1); - } - if (this.poleAngle) { - math_vector_Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2); - mat1.multiplyToRef(mat2, mat1); - } - if (this._bone1) { - if (this.slerpAmount < 1) { - if (!this._slerping) { - math_vector_Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat); - } - math_vector_Quaternion.FromRotationMatrixToRef(mat1, tmpQuat); - math_vector_Quaternion.SlerpToRef(this._bone1Quat, tmpQuat, this.slerpAmount, this._bone1Quat); - angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount; - this._bone1.setRotationQuaternion(this._bone1Quat, math_axis_Space.WORLD, this.mesh); - this._slerping = true; - } - else { - this._bone1.setRotationMatrix(mat1, math_axis_Space.WORLD, this.mesh); - this._bone1Mat.copyFrom(mat1); - this._slerping = false; - } - this._updateLinkedTransformRotation(this._bone1); - } - this._bone2.setAxisAngle(this._bendAxis, angC, math_axis_Space.LOCAL); - this._updateLinkedTransformRotation(this._bone2); - this._bone2Ang = angC; - } - _updateLinkedTransformRotation(bone) { - if (bone._linkedTransformNode) { - if (!bone._linkedTransformNode.rotationQuaternion) { - bone._linkedTransformNode.rotationQuaternion = new math_vector_Quaternion(); - } - bone.getRotationQuaternionToRef(math_axis_Space.LOCAL, null, bone._linkedTransformNode.rotationQuaternion); - } - } -} -BoneIKController._TmpVecs = [math_vector_Vector3.Zero(), math_vector_Vector3.Zero(), math_vector_Vector3.Zero(), math_vector_Vector3.Zero(), math_vector_Vector3.Zero(), math_vector_Vector3.Zero()]; -BoneIKController._TmpQuat = math_vector_Quaternion.Identity(); -BoneIKController._TmpMats = [math_vector_Matrix.Identity(), math_vector_Matrix.Identity()]; -//# sourceMappingURL=boneIKController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Bones/boneLookController.js - - - -/** - * Class used to make a bone look toward a point in space - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons#bonelookcontroller - */ -class BoneLookController { - /** - * Gets or sets the minimum yaw angle that the bone can look to - */ - get minYaw() { - return this._minYaw; - } - set minYaw(value) { - this._minYaw = value; - this._minYawSin = Math.sin(value); - this._minYawCos = Math.cos(value); - if (this._maxYaw != null) { - this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * 0.5 + this._minYaw; - this._yawRange = this._maxYaw - this._minYaw; - } - } - /** - * Gets or sets the maximum yaw angle that the bone can look to - */ - get maxYaw() { - return this._maxYaw; - } - set maxYaw(value) { - this._maxYaw = value; - this._maxYawSin = Math.sin(value); - this._maxYawCos = Math.cos(value); - if (this._minYaw != null) { - this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * 0.5 + this._minYaw; - this._yawRange = this._maxYaw - this._minYaw; - } - } - /** - * Gets or sets the minimum pitch angle that the bone can look to - */ - get minPitch() { - return this._minPitch; - } - set minPitch(value) { - this._minPitch = value; - this._minPitchTan = Math.tan(value); - } - /** - * Gets or sets the maximum pitch angle that the bone can look to - */ - get maxPitch() { - return this._maxPitch; - } - set maxPitch(value) { - this._maxPitch = value; - this._maxPitchTan = Math.tan(value); - } - /** - * Create a BoneLookController - * @param mesh the TransformNode that the bone belongs to - * @param bone the bone that will be looking to the target - * @param target the target Vector3 to look at - * @param options optional settings: - * * maxYaw: the maximum angle the bone will yaw to - * * minYaw: the minimum angle the bone will yaw to - * * maxPitch: the maximum angle the bone will pitch to - * * minPitch: the minimum angle the bone will yaw to - * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target. - * * upAxis: the up axis of the coordinate system - * * upAxisSpace: the space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD. - * * yawAxis: set yawAxis if the bone does not yaw on the y axis - * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis - * * adjustYaw: used to make an adjustment to the yaw of the bone - * * adjustPitch: used to make an adjustment to the pitch of the bone - * * adjustRoll: used to make an adjustment to the roll of the bone - * @param options.maxYaw - * @param options.minYaw - * @param options.maxPitch - * @param options.minPitch - * @param options.slerpAmount - * @param options.upAxis - * @param options.upAxisSpace - * @param options.yawAxis - * @param options.pitchAxis - * @param options.adjustYaw - * @param options.adjustPitch - * @param options.adjustRoll - **/ - constructor(mesh, bone, target, options) { - /** - * The up axis of the coordinate system that is used when the bone is rotated - */ - this.upAxis = math_vector_Vector3.Up(); - /** - * The space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD - */ - this.upAxisSpace = math_axis_Space.LOCAL; - /** - * Used to make an adjustment to the yaw of the bone - */ - this.adjustYaw = 0; - /** - * Used to make an adjustment to the pitch of the bone - */ - this.adjustPitch = 0; - /** - * Used to make an adjustment to the roll of the bone - */ - this.adjustRoll = 0; - /** - * 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) - */ - this.slerpAmount = 1; - this._boneQuat = math_vector_Quaternion.Identity(); - this._slerping = false; - this._firstFrameSkipped = false; - this._fowardAxis = math_vector_Vector3.Forward(); - /** - * Use the absolute value for yaw when checking the min/max constraints - */ - this.useAbsoluteValueForYaw = false; - this.mesh = mesh; - this.bone = bone; - this.target = target; - if (options) { - if (options.adjustYaw) { - this.adjustYaw = options.adjustYaw; - } - if (options.adjustPitch) { - this.adjustPitch = options.adjustPitch; - } - if (options.adjustRoll) { - this.adjustRoll = options.adjustRoll; - } - if (options.maxYaw != null) { - this.maxYaw = options.maxYaw; - } - else { - this.maxYaw = Math.PI; - } - if (options.minYaw != null) { - this.minYaw = options.minYaw; - } - else { - this.minYaw = -Math.PI; - } - if (options.maxPitch != null) { - this.maxPitch = options.maxPitch; - } - else { - this.maxPitch = Math.PI; - } - if (options.minPitch != null) { - this.minPitch = options.minPitch; - } - else { - this.minPitch = -Math.PI; - } - if (options.slerpAmount != null) { - this.slerpAmount = options.slerpAmount; - } - if (options.upAxis != null) { - this.upAxis = options.upAxis; - } - if (options.upAxisSpace != null) { - this.upAxisSpace = options.upAxisSpace; - } - if (options.yawAxis != null || options.pitchAxis != null) { - let newYawAxis = math_axis_Axis.Y; - let newPitchAxis = math_axis_Axis.X; - if (options.yawAxis != null) { - newYawAxis = options.yawAxis.clone(); - newYawAxis.normalize(); - } - if (options.pitchAxis != null) { - newPitchAxis = options.pitchAxis.clone(); - newPitchAxis.normalize(); - } - const newRollAxis = math_vector_Vector3.Cross(newPitchAxis, newYawAxis); - this._transformYawPitch = math_vector_Matrix.Identity(); - math_vector_Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch); - this._transformYawPitchInv = this._transformYawPitch.clone(); - this._transformYawPitch.invert(); - } - if (options.useAbsoluteValueForYaw !== undefined) { - this.useAbsoluteValueForYaw = options.useAbsoluteValueForYaw; - } - } - if (!bone.getParent() && this.upAxisSpace == math_axis_Space.BONE) { - this.upAxisSpace = math_axis_Space.LOCAL; - } - } - /** - * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()) - */ - update() { - //skip the first frame when slerping so that the TransformNode rotation is correct - if (this.slerpAmount < 1 && !this._firstFrameSkipped) { - this._firstFrameSkipped = true; - return; - } - const bone = this.bone; - const bonePos = BoneLookController._TmpVecs[0]; - bone.getAbsolutePositionToRef(this.mesh, bonePos); - let target = this.target; - const _tmpMat1 = BoneLookController._TmpMats[0]; - const _tmpMat2 = BoneLookController._TmpMats[1]; - const mesh = this.mesh; - const parentBone = bone.getParent(); - const upAxis = BoneLookController._TmpVecs[1]; - upAxis.copyFrom(this.upAxis); - if (this.upAxisSpace == math_axis_Space.BONE && parentBone) { - if (this._transformYawPitch) { - math_vector_Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis); - } - parentBone.getDirectionToRef(upAxis, this.mesh, upAxis); - } - else if (this.upAxisSpace == math_axis_Space.LOCAL) { - mesh.getDirectionToRef(upAxis, upAxis); - if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) { - upAxis.normalize(); - } - } - let checkYaw = false; - let checkPitch = false; - if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) { - checkYaw = true; - } - if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) { - checkPitch = true; - } - if (checkYaw || checkPitch) { - const spaceMat = BoneLookController._TmpMats[2]; - const spaceMatInv = BoneLookController._TmpMats[3]; - if (this.upAxisSpace == math_axis_Space.BONE && upAxis.y == 1 && parentBone) { - parentBone.getRotationMatrixToRef(math_axis_Space.WORLD, this.mesh, spaceMat); - } - else if (this.upAxisSpace == math_axis_Space.LOCAL && upAxis.y == 1 && !parentBone) { - spaceMat.copyFrom(mesh.getWorldMatrix()); - } - else { - let forwardAxis = BoneLookController._TmpVecs[2]; - forwardAxis.copyFrom(this._fowardAxis); - if (this._transformYawPitch) { - math_vector_Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis); - } - if (parentBone) { - parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis); - } - else { - mesh.getDirectionToRef(forwardAxis, forwardAxis); - } - const rightAxis = math_vector_Vector3.Cross(upAxis, forwardAxis); - rightAxis.normalize(); - forwardAxis = math_vector_Vector3.Cross(rightAxis, upAxis); - math_vector_Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat); - } - spaceMat.invertToRef(spaceMatInv); - let xzlen = null; - if (checkPitch) { - const localTarget = BoneLookController._TmpVecs[3]; - target.subtractToRef(bonePos, localTarget); - math_vector_Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget); - xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); - const pitch = Math.atan2(localTarget.y, xzlen); - let newPitch = pitch; - if (pitch > this._maxPitch) { - localTarget.y = this._maxPitchTan * xzlen; - newPitch = this._maxPitch; - } - else if (pitch < this._minPitch) { - localTarget.y = this._minPitchTan * xzlen; - newPitch = this._minPitch; - } - if (pitch != newPitch) { - math_vector_Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget); - localTarget.addInPlace(bonePos); - target = localTarget; - } - } - if (checkYaw) { - const localTarget = BoneLookController._TmpVecs[4]; - target.subtractToRef(bonePos, localTarget); - math_vector_Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget); - const yaw = Math.atan2(localTarget.x, localTarget.z); - const yawCheck = this.useAbsoluteValueForYaw ? Math.abs(yaw) : yaw; - let newYaw = yaw; - if (yawCheck > this._maxYaw || yawCheck < this._minYaw) { - if (xzlen == null) { - xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); - } - if (this._yawRange > Math.PI) { - if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) { - localTarget.z = this._maxYawCos * xzlen; - localTarget.x = this._maxYawSin * xzlen; - newYaw = this._maxYaw; - } - else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) { - localTarget.z = this._minYawCos * xzlen; - localTarget.x = this._minYawSin * xzlen; - newYaw = this._minYaw; - } - } - else { - if (yawCheck > this._maxYaw) { - localTarget.z = this._maxYawCos * xzlen; - localTarget.x = this._maxYawSin * xzlen; - if (yaw < 0 && this.useAbsoluteValueForYaw) { - localTarget.x *= -1; - } - newYaw = this._maxYaw; - } - else if (yawCheck < this._minYaw) { - localTarget.z = this._minYawCos * xzlen; - localTarget.x = this._minYawSin * xzlen; - if (yaw < 0 && this.useAbsoluteValueForYaw) { - localTarget.x *= -1; - } - newYaw = this._minYaw; - } - } - } - if (this._slerping && this._yawRange > Math.PI) { - //are we going to be crossing into the min/max region? - const boneFwd = BoneLookController._TmpVecs[8]; - boneFwd.copyFrom(math_axis_Axis.Z); - if (this._transformYawPitch) { - math_vector_Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd); - } - const boneRotMat = BoneLookController._TmpMats[4]; - this._boneQuat.toRotationMatrix(boneRotMat); - this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat); - math_vector_Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd); - math_vector_Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd); - const boneYaw = Math.atan2(boneFwd.x, boneFwd.z); - const angBtwTar = this._getAngleBetween(boneYaw, yaw); - const angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint); - if (angBtwTar > angBtwMidYaw) { - if (xzlen == null) { - xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); - } - const angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw); - const angBtwMin = this._getAngleBetween(boneYaw, this._minYaw); - if (angBtwMin < angBtwMax) { - newYaw = boneYaw + Math.PI * 0.75; - localTarget.z = Math.cos(newYaw) * xzlen; - localTarget.x = Math.sin(newYaw) * xzlen; - } - else { - newYaw = boneYaw - Math.PI * 0.75; - localTarget.z = Math.cos(newYaw) * xzlen; - localTarget.x = Math.sin(newYaw) * xzlen; - } - } - } - if (yaw != newYaw) { - math_vector_Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget); - localTarget.addInPlace(bonePos); - target = localTarget; - } - } - } - const zaxis = BoneLookController._TmpVecs[5]; - const xaxis = BoneLookController._TmpVecs[6]; - const yaxis = BoneLookController._TmpVecs[7]; - const tmpQuat = BoneLookController._TmpQuat; - target.subtractToRef(bonePos, zaxis); - zaxis.normalize(); - math_vector_Vector3.CrossToRef(upAxis, zaxis, xaxis); - xaxis.normalize(); - math_vector_Vector3.CrossToRef(zaxis, xaxis, yaxis); - yaxis.normalize(); - math_vector_Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1); - if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) { - return; - } - if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) { - return; - } - if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) { - return; - } - if (this.adjustYaw || this.adjustPitch || this.adjustRoll) { - math_vector_Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2); - _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1); - } - if (this.slerpAmount < 1) { - if (!this._slerping) { - this.bone.getRotationQuaternionToRef(math_axis_Space.WORLD, this.mesh, this._boneQuat); - } - if (this._transformYawPitch) { - this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1); - } - math_vector_Quaternion.FromRotationMatrixToRef(_tmpMat1, tmpQuat); - math_vector_Quaternion.SlerpToRef(this._boneQuat, tmpQuat, this.slerpAmount, this._boneQuat); - this.bone.setRotationQuaternion(this._boneQuat, math_axis_Space.WORLD, this.mesh); - this._slerping = true; - } - else { - if (this._transformYawPitch) { - this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1); - } - this.bone.setRotationMatrix(_tmpMat1, math_axis_Space.WORLD, this.mesh); - this._slerping = false; - } - this._updateLinkedTransformRotation(); - } - _getAngleDiff(ang1, ang2) { - let angDiff = ang2 - ang1; - angDiff %= Math.PI * 2; - if (angDiff > Math.PI) { - angDiff -= Math.PI * 2; - } - else if (angDiff < -Math.PI) { - angDiff += Math.PI * 2; - } - return angDiff; - } - _getAngleBetween(ang1, ang2) { - ang1 %= 2 * Math.PI; - ang1 = ang1 < 0 ? ang1 + 2 * Math.PI : ang1; - ang2 %= 2 * Math.PI; - ang2 = ang2 < 0 ? ang2 + 2 * Math.PI : ang2; - let ab = 0; - if (ang1 < ang2) { - ab = ang2 - ang1; - } - else { - ab = ang1 - ang2; - } - if (ab > Math.PI) { - ab = Math.PI * 2 - ab; - } - return ab; - } - _isAngleBetween(ang, ang1, ang2) { - ang %= 2 * Math.PI; - ang = ang < 0 ? ang + 2 * Math.PI : ang; - ang1 %= 2 * Math.PI; - ang1 = ang1 < 0 ? ang1 + 2 * Math.PI : ang1; - ang2 %= 2 * Math.PI; - ang2 = ang2 < 0 ? ang2 + 2 * Math.PI : ang2; - if (ang1 < ang2) { - if (ang > ang1 && ang < ang2) { - return true; - } - } - else { - if (ang > ang2 && ang < ang1) { - return true; - } - } - return false; - } - _updateLinkedTransformRotation() { - const bone = this.bone; - if (bone._linkedTransformNode) { - if (!bone._linkedTransformNode.rotationQuaternion) { - bone._linkedTransformNode.rotationQuaternion = new math_vector_Quaternion(); - } - bone.getRotationQuaternionToRef(math_axis_Space.LOCAL, null, bone._linkedTransformNode.rotationQuaternion); - } - } -} -BoneLookController._TmpVecs = arrayTools_ArrayTools.BuildArray(10, math_vector_Vector3.Zero); -BoneLookController._TmpQuat = math_vector_Quaternion.Identity(); -BoneLookController._TmpMats = arrayTools_ArrayTools.BuildArray(5, math_vector_Matrix.Identity); -//# sourceMappingURL=boneLookController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Bones/skeleton.js - - - - - - - - - - -/** - * Class used to handle skinning animations - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons - */ -class skeleton_Skeleton { - /** - * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true). - * Please note that this option is not available if the hardware does not support it - */ - get useTextureToStoreBoneMatrices() { - return this._useTextureToStoreBoneMatrices; - } - set useTextureToStoreBoneMatrices(value) { - this._useTextureToStoreBoneMatrices = value; - this._markAsDirty(); - } - /** - * Gets or sets the animation properties override - */ - get animationPropertiesOverride() { - if (!this._animationPropertiesOverride) { - return this._scene.animationPropertiesOverride; - } - return this._animationPropertiesOverride; - } - set animationPropertiesOverride(value) { - this._animationPropertiesOverride = value; - } - /** - * Gets a boolean indicating that the skeleton effectively stores matrices into a texture - */ - get isUsingTextureForMatrices() { - return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones; - } - /** - * Gets the unique ID of this skeleton - */ - get uniqueId() { - return this._uniqueId; - } - /** - * Creates a new skeleton - * @param name defines the skeleton name - * @param id defines the skeleton Id - * @param scene defines the hosting scene - */ - constructor( - /** defines the skeleton name */ - name, - /** defines the skeleton Id */ - id, scene) { - this.name = name; - this.id = id; - /** - * Defines the list of child bones - */ - this.bones = new Array(); - /** - * Defines a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value) - */ - this.needInitialSkinMatrix = false; - this._isDirty = true; - this._meshesWithPoseMatrix = new Array(); - this._identity = math_vector_Matrix.Identity(); - this._currentRenderId = -1; - this._ranges = {}; - this._absoluteTransformIsDirty = true; - this._canUseTextureForBones = false; - this._uniqueId = 0; - /** @internal */ - this._numBonesWithLinkedTransformNode = 0; - /** @internal */ - this._hasWaitingData = null; - /** @internal */ - this._parentContainer = null; - /** - * Specifies if the skeleton should be serialized - */ - this.doNotSerialize = false; - this._useTextureToStoreBoneMatrices = true; - this._animationPropertiesOverride = null; - // Events - /** - * An observable triggered before computing the skeleton's matrices - */ - this.onBeforeComputeObservable = new observable_Observable(); - this.bones = []; - this._scene = scene || engineStore_EngineStore.LastCreatedScene; - this._uniqueId = this._scene.getUniqueId(); - this._scene.addSkeleton(this); - //make sure it will recalculate the matrix next time prepare is called. - this._isDirty = true; - const engineCaps = this._scene.getEngine().getCaps(); - this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0; - } - /** - * Gets the current object class name. - * @returns the class name - */ - getClassName() { - return "Skeleton"; - } - /** - * Returns an array containing the root bones - * @returns an array containing the root bones - */ - getChildren() { - return this.bones.filter((b) => !b.getParent()); - } - // Members - /** - * Gets the list of transform matrices to send to shaders (one matrix per bone) - * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true) - * @returns a Float32Array containing matrices data - */ - getTransformMatrices(mesh) { - if (this.needInitialSkinMatrix) { - if (!mesh._bonesTransformMatrices) { - this.prepare(); - } - return mesh._bonesTransformMatrices; - } - if (!this._transformMatrices || this._isDirty) { - this.prepare(); - } - return this._transformMatrices; - } - /** - * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone) - * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true) - * @returns a raw texture containing the data - */ - getTransformMatrixTexture(mesh) { - if (this.needInitialSkinMatrix && mesh._transformMatrixTexture) { - return mesh._transformMatrixTexture; - } - return this._transformMatrixTexture; - } - /** - * Gets the current hosting scene - * @returns a scene object - */ - getScene() { - return this._scene; - } - // Methods - /** - * Gets a string representing the current skeleton data - * @param fullDetails defines a boolean indicating if we want a verbose version - * @returns a string representing the current skeleton data - */ - toString(fullDetails) { - let ret = `Name: ${this.name}, nBones: ${this.bones.length}`; - ret += `, nAnimationRanges: ${this._ranges ? Object.keys(this._ranges).length : "none"}`; - if (fullDetails) { - ret += ", Ranges: {"; - let first = true; - for (const name in this._ranges) { - if (first) { - ret += ", "; - first = false; - } - ret += name; - } - ret += "}"; - } - return ret; - } - /** - * Get bone's index searching by name - * @param name defines bone's name to search for - * @returns the indice of the bone. Returns -1 if not found - */ - getBoneIndexByName(name) { - for (let boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) { - if (this.bones[boneIndex].name === name) { - return boneIndex; - } - } - return -1; - } - /** - * Create a new animation range - * @param name defines the name of the range - * @param from defines the start key - * @param to defines the end key - */ - createAnimationRange(name, from, to) { - // check name not already in use - if (!this._ranges[name]) { - this._ranges[name] = new AnimationRange(name, from, to); - for (let i = 0, nBones = this.bones.length; i < nBones; i++) { - if (this.bones[i].animations[0]) { - this.bones[i].animations[0].createRange(name, from, to); - } - } - } - } - /** - * Delete a specific animation range - * @param name defines the name of the range - * @param deleteFrames defines if frames must be removed as well - */ - deleteAnimationRange(name, deleteFrames = true) { - for (let i = 0, nBones = this.bones.length; i < nBones; i++) { - if (this.bones[i].animations[0]) { - this.bones[i].animations[0].deleteRange(name, deleteFrames); - } - } - this._ranges[name] = null; // said much faster than 'delete this._range[name]' - } - /** - * Gets a specific animation range - * @param name defines the name of the range to look for - * @returns the requested animation range or null if not found - */ - getAnimationRange(name) { - return this._ranges[name] || null; - } - /** - * Gets the list of all animation ranges defined on this skeleton - * @returns an array - */ - getAnimationRanges() { - const animationRanges = []; - let name; - for (name in this._ranges) { - animationRanges.push(this._ranges[name]); - } - return animationRanges; - } - /** - * Copy animation range from a source skeleton. - * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences - * @param source defines the source skeleton - * @param name defines the name of the range to copy - * @param rescaleAsRequired defines if rescaling must be applied if required - * @returns true if operation was successful - */ - copyAnimationRange(source, name, rescaleAsRequired = false) { - if (this._ranges[name] || !source.getAnimationRange(name)) { - return false; - } - let ret = true; - const frameOffset = this._getHighestAnimationFrame() + 1; - // make a dictionary of source skeleton's bones, so exact same order or doubly nested loop is not required - const boneDict = {}; - const sourceBones = source.bones; - let nBones; - let i; - for (i = 0, nBones = sourceBones.length; i < nBones; i++) { - boneDict[sourceBones[i].name] = sourceBones[i]; - } - if (this.bones.length !== sourceBones.length) { - logger_Logger.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${sourceBones.length}`); - ret = false; - } - const skelDimensionsRatio = rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null; - for (i = 0, nBones = this.bones.length; i < nBones; i++) { - const boneName = this.bones[i].name; - const sourceBone = boneDict[boneName]; - if (sourceBone) { - ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio); - } - else { - logger_Logger.Warn("copyAnimationRange: not same rig, missing source bone " + boneName); - ret = false; - } - } - // do not call createAnimationRange(), since it also is done to bones, which was already done - const range = source.getAnimationRange(name); - if (range) { - this._ranges[name] = new AnimationRange(name, range.from + frameOffset, range.to + frameOffset); - } - return ret; - } - /** - * Forces the skeleton to go to rest pose - */ - returnToRest() { - for (const bone of this.bones) { - if (bone._index !== -1) { - bone.returnToRest(); - } - } - } - _getHighestAnimationFrame() { - let ret = 0; - for (let i = 0, nBones = this.bones.length; i < nBones; i++) { - if (this.bones[i].animations[0]) { - const highest = this.bones[i].animations[0].getHighestFrame(); - if (ret < highest) { - ret = highest; - } - } - } - return ret; - } - /** - * Begin a specific animation range - * @param name defines the name of the range to start - * @param loop defines if looping must be turned on (false by default) - * @param speedRatio defines the speed ratio to apply (1 by default) - * @param onAnimationEnd defines a callback which will be called when animation will end - * @returns a new animatable - */ - beginAnimation(name, loop, speedRatio, onAnimationEnd) { - const range = this.getAnimationRange(name); - if (!range) { - return null; - } - return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd); - } - /** - * Convert the keyframes for a range of animation on a skeleton to be relative to a given reference frame. - * @param skeleton defines the Skeleton containing the animation range to convert - * @param referenceFrame defines the frame that keyframes in the range will be relative to - * @param range defines the name of the AnimationRange belonging to the Skeleton to convert - * @returns the original skeleton - */ - static MakeAnimationAdditive(skeleton, referenceFrame = 0, range) { - const rangeValue = skeleton.getAnimationRange(range); - // We can't make a range additive if it doesn't exist - if (!rangeValue) { - return null; - } - // Find any current scene-level animatable belonging to the target that matches the range - const sceneAnimatables = skeleton._scene.getAllAnimatablesByTarget(skeleton); - let rangeAnimatable = null; - for (let index = 0; index < sceneAnimatables.length; index++) { - const sceneAnimatable = sceneAnimatables[index]; - if (sceneAnimatable.fromFrame === (rangeValue === null || rangeValue === void 0 ? void 0 : rangeValue.from) && sceneAnimatable.toFrame === (rangeValue === null || rangeValue === void 0 ? void 0 : rangeValue.to)) { - rangeAnimatable = sceneAnimatable; - break; - } - } - // Convert the animations belonging to the skeleton to additive keyframes - const animatables = skeleton.getAnimatables(); - for (let index = 0; index < animatables.length; index++) { - const animatable = animatables[index]; - const animations = animatable.animations; - if (!animations) { - continue; - } - for (let animIndex = 0; animIndex < animations.length; animIndex++) { - animation_Animation.MakeAnimationAdditive(animations[animIndex], referenceFrame, range); - } - } - // Mark the scene-level animatable as additive - if (rangeAnimatable) { - rangeAnimatable.isAdditive = true; - } - return skeleton; - } - /** @internal */ - _markAsDirty() { - this._isDirty = true; - this._absoluteTransformIsDirty = true; - } - /** - * @internal - */ - _registerMeshWithPoseMatrix(mesh) { - this._meshesWithPoseMatrix.push(mesh); - } - /** - * @internal - */ - _unregisterMeshWithPoseMatrix(mesh) { - const index = this._meshesWithPoseMatrix.indexOf(mesh); - if (index > -1) { - this._meshesWithPoseMatrix.splice(index, 1); - } - } - _computeTransformMatrices(targetMatrix, initialSkinMatrix) { - this.onBeforeComputeObservable.notifyObservers(this); - for (let index = 0; index < this.bones.length; index++) { - const bone = this.bones[index]; - bone._childUpdateId++; - const parentBone = bone.getParent(); - if (parentBone) { - bone.getLocalMatrix().multiplyToRef(parentBone.getFinalMatrix(), bone.getFinalMatrix()); - } - else { - if (initialSkinMatrix) { - bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getFinalMatrix()); - } - else { - bone.getFinalMatrix().copyFrom(bone.getLocalMatrix()); - } - } - if (bone._index !== -1) { - const mappedIndex = bone._index === null ? index : bone._index; - bone.getAbsoluteInverseBindMatrix().multiplyToArray(bone.getFinalMatrix(), targetMatrix, mappedIndex * 16); - } - } - this._identity.copyToArray(targetMatrix, this.bones.length * 16); - } - /** - * Build all resources required to render a skeleton - * @param dontCheckFrameId defines a boolean indicating if prepare should be run without checking first the current frame id (default: false) - */ - prepare(dontCheckFrameId = false) { - if (!dontCheckFrameId) { - const currentRenderId = this.getScene().getRenderId(); - if (this._currentRenderId === currentRenderId) { - return; - } - this._currentRenderId = currentRenderId; - } - // Update the local matrix of bones with linked transform nodes. - if (this._numBonesWithLinkedTransformNode > 0) { - for (const bone of this.bones) { - if (bone._linkedTransformNode) { - const node = bone._linkedTransformNode; - bone.position = node.position; - if (node.rotationQuaternion) { - bone.rotationQuaternion = node.rotationQuaternion; - } - else { - bone.rotation = node.rotation; - } - bone.scaling = node.scaling; - } - } - } - if (this.needInitialSkinMatrix) { - for (const mesh of this._meshesWithPoseMatrix) { - const poseMatrix = mesh.getPoseMatrix(); - let needsUpdate = this._isDirty; - if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) { - mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1)); - needsUpdate = true; - } - if (!needsUpdate) { - continue; - } - if (this._synchronizedWithMesh !== mesh) { - this._synchronizedWithMesh = mesh; - // Prepare bones - for (const bone of this.bones) { - if (!bone.getParent()) { - const matrix = bone.getBindMatrix(); - matrix.multiplyToRef(poseMatrix, math_vector_TmpVectors.Matrix[1]); - bone._updateAbsoluteBindMatrices(math_vector_TmpVectors.Matrix[1]); - } - } - if (this.isUsingTextureForMatrices) { - const textureWidth = (this.bones.length + 1) * 4; - if (!mesh._transformMatrixTexture || mesh._transformMatrixTexture.getSize().width !== textureWidth) { - if (mesh._transformMatrixTexture) { - mesh._transformMatrixTexture.dispose(); - } - mesh._transformMatrixTexture = rawTexture_RawTexture.CreateRGBATexture(mesh._bonesTransformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1); - } - } - } - this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix); - if (this.isUsingTextureForMatrices && mesh._transformMatrixTexture) { - mesh._transformMatrixTexture.update(mesh._bonesTransformMatrices); - } - } - } - else { - if (!this._isDirty) { - return; - } - if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) { - this._transformMatrices = new Float32Array(16 * (this.bones.length + 1)); - if (this.isUsingTextureForMatrices) { - if (this._transformMatrixTexture) { - this._transformMatrixTexture.dispose(); - } - this._transformMatrixTexture = rawTexture_RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1); - } - } - this._computeTransformMatrices(this._transformMatrices, null); - if (this.isUsingTextureForMatrices && this._transformMatrixTexture) { - this._transformMatrixTexture.update(this._transformMatrices); - } - } - this._isDirty = false; - } - /** - * Gets the list of animatables currently running for this skeleton - * @returns an array of animatables - */ - getAnimatables() { - if (!this._animatables || this._animatables.length !== this.bones.length) { - this._animatables = []; - for (let index = 0; index < this.bones.length; index++) { - this._animatables.push(this.bones[index]); - } - } - return this._animatables; - } - /** - * Clone the current skeleton - * @param name defines the name of the new skeleton - * @param id defines the id of the new skeleton - * @returns the new skeleton - */ - clone(name, id) { - const result = new skeleton_Skeleton(name, id || name, this._scene); - result.needInitialSkinMatrix = this.needInitialSkinMatrix; - for (let index = 0; index < this.bones.length; index++) { - const source = this.bones[index]; - let parentBone = null; - const parent = source.getParent(); - if (parent) { - const parentIndex = this.bones.indexOf(parent); - parentBone = result.bones[parentIndex]; - } - const bone = new Bone(source.name, result, parentBone, source.getBindMatrix().clone(), source.getRestMatrix().clone()); - bone._index = source._index; - if (source._linkedTransformNode) { - bone.linkTransformNode(source._linkedTransformNode); - } - DeepCopier.DeepCopy(source.animations, bone.animations); - } - if (this._ranges) { - result._ranges = {}; - for (const rangeName in this._ranges) { - const range = this._ranges[rangeName]; - if (range) { - result._ranges[rangeName] = range.clone(); - } - } - } - this._isDirty = true; - result.prepare(true); - return result; - } - /** - * Enable animation blending for this skeleton - * @param blendingSpeed defines the blending speed to apply - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending - */ - enableBlending(blendingSpeed = 0.01) { - this.bones.forEach((bone) => { - bone.animations.forEach((animation) => { - animation.enableBlending = true; - animation.blendingSpeed = blendingSpeed; - }); - }); - } - /** - * Releases all resources associated with the current skeleton - */ - dispose() { - this._meshesWithPoseMatrix.length = 0; - // Animations - this.getScene().stopAnimation(this); - // Remove from scene - this.getScene().removeSkeleton(this); - if (this._parentContainer) { - const index = this._parentContainer.skeletons.indexOf(this); - if (index > -1) { - this._parentContainer.skeletons.splice(index, 1); - } - this._parentContainer = null; - } - if (this._transformMatrixTexture) { - this._transformMatrixTexture.dispose(); - this._transformMatrixTexture = null; - } - } - /** - * Serialize the skeleton in a JSON object - * @returns a JSON object - */ - serialize() { - var _a; - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.id = this.id; - if (this.dimensionsAtRest) { - serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray(); - } - serializationObject.bones = []; - serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix; - for (let index = 0; index < this.bones.length; index++) { - const bone = this.bones[index]; - const parent = bone.getParent(); - const serializedBone = { - parentBoneIndex: parent ? this.bones.indexOf(parent) : -1, - index: bone.getIndex(), - name: bone.name, - id: bone.id, - matrix: bone.getBindMatrix().toArray(), - rest: bone.getRestMatrix().toArray(), - linkedTransformNodeId: (_a = bone.getTransformNode()) === null || _a === void 0 ? void 0 : _a.id, - }; - serializationObject.bones.push(serializedBone); - if (bone.length) { - serializedBone.length = bone.length; - } - if (bone.metadata) { - serializedBone.metadata = bone.metadata; - } - if (bone.animations && bone.animations.length > 0) { - serializedBone.animation = bone.animations[0].serialize(); - } - serializationObject.ranges = []; - for (const name in this._ranges) { - const source = this._ranges[name]; - if (!source) { - continue; - } - const range = {}; - range.name = name; - range.from = source.from; - range.to = source.to; - serializationObject.ranges.push(range); - } - } - return serializationObject; - } - /** - * Creates a new skeleton from serialized data - * @param parsedSkeleton defines the serialized data - * @param scene defines the hosting scene - * @returns a new skeleton - */ - static Parse(parsedSkeleton, scene) { - const skeleton = new skeleton_Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene); - if (parsedSkeleton.dimensionsAtRest) { - skeleton.dimensionsAtRest = math_vector_Vector3.FromArray(parsedSkeleton.dimensionsAtRest); - } - skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix; - let index; - for (index = 0; index < parsedSkeleton.bones.length; index++) { - const parsedBone = parsedSkeleton.bones[index]; - const parsedBoneIndex = parsedSkeleton.bones[index].index; - let parentBone = null; - if (parsedBone.parentBoneIndex > -1) { - parentBone = skeleton.bones[parsedBone.parentBoneIndex]; - } - const rest = parsedBone.rest ? math_vector_Matrix.FromArray(parsedBone.rest) : null; - const bone = new Bone(parsedBone.name, skeleton, parentBone, math_vector_Matrix.FromArray(parsedBone.matrix), rest, null, parsedBoneIndex); - if (parsedBone.id !== undefined && parsedBone.id !== null) { - bone.id = parsedBone.id; - } - if (parsedBone.length) { - bone.length = parsedBone.length; - } - if (parsedBone.metadata) { - bone.metadata = parsedBone.metadata; - } - if (parsedBone.animation) { - bone.animations.push(animation_Animation.Parse(parsedBone.animation)); - } - if (parsedBone.linkedTransformNodeId !== undefined && parsedBone.linkedTransformNodeId !== null) { - skeleton._hasWaitingData = true; - bone._waitingTransformNodeId = parsedBone.linkedTransformNodeId; - } - } - // placed after bones, so createAnimationRange can cascade down - if (parsedSkeleton.ranges) { - for (index = 0; index < parsedSkeleton.ranges.length; index++) { - const data = parsedSkeleton.ranges[index]; - skeleton.createAnimationRange(data.name, data.from, data.to); - } - } - return skeleton; - } - /** - * Compute all node absolute matrices - * @param forceUpdate defines if computation must be done even if cache is up to date - */ - computeAbsoluteMatrices(forceUpdate = false) { - if (this._absoluteTransformIsDirty || forceUpdate) { - this.bones[0].computeAbsoluteMatrices(); - this._absoluteTransformIsDirty = false; - } - } - /** - * Compute all node absolute matrices - * @param forceUpdate defines if computation must be done even if cache is up to date - * @deprecated Please use computeAbsoluteMatrices instead - */ - computeAbsoluteTransforms(forceUpdate = false) { - this.computeAbsoluteMatrices(forceUpdate); - } - /** - * Gets the root pose matrix - * @returns a matrix - */ - getPoseMatrix() { - let poseMatrix = null; - if (this._meshesWithPoseMatrix.length > 0) { - poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix(); - } - return poseMatrix; - } - /** - * Sorts bones per internal index - */ - sortBones() { - const bones = new Array(); - const visited = new Array(this.bones.length); - for (let index = 0; index < this.bones.length; index++) { - this._sortBones(index, bones, visited); - } - this.bones = bones; - } - _sortBones(index, bones, visited) { - if (visited[index]) { - return; - } - visited[index] = true; - const bone = this.bones[index]; - if (!bone) - return; - if (bone._index === undefined) { - bone._index = index; - } - const parentBone = bone.getParent(); - if (parentBone) { - this._sortBones(this.bones.indexOf(parentBone), bones, visited); - } - bones.push(bone); - } - /** - * Set the current local matrix as the restPose for all bones in the skeleton. - */ - setCurrentPoseAsRest() { - this.bones.forEach((b) => { - b.setCurrentPoseAsRest(); - }); - } -} -//# sourceMappingURL=skeleton.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Bones/index.js - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Buffers/storageBuffer.js - -/** - * This class is a small wrapper around a native buffer that can be read and/or written - */ -class StorageBuffer { - /** - * Creates a new storage buffer instance - * @param engine The engine the buffer will be created inside - * @param size The size of the buffer in bytes - * @param creationFlags flags to use when creating the buffer (see undefined). The BUFFER_CREATIONFLAG_STORAGE flag will be automatically added. - */ - constructor(engine, size, creationFlags = 3) { - this._engine = engine; - this._engine._storageBuffers.push(this); - this._create(size, creationFlags); - } - _create(size, creationFlags) { - this._bufferSize = size; - this._creationFlags = creationFlags; - this._buffer = this._engine.createStorageBuffer(size, creationFlags); - } - /** @internal */ - _rebuild() { - this._create(this._bufferSize, this._creationFlags); - } - /** - * Gets underlying native buffer - * @returns underlying native buffer - */ - getBuffer() { - return this._buffer; - } - /** - * Updates the storage buffer - * @param data the data used to update the storage buffer - * @param byteOffset the byte offset of the data (optional) - * @param byteLength the byte length of the data (optional) - */ - update(data, byteOffset, byteLength) { - if (!this._buffer) { - return; - } - this._engine.updateStorageBuffer(this._buffer, data, byteOffset, byteLength); - } - /** - * Reads data from the storage buffer - * @param offset The offset in the storage buffer to start reading from (default: 0) - * @param size The number of bytes to read from the storage buffer (default: capacity of the buffer) - * @param buffer The buffer to write the data we have read from the storage buffer to (optional) - * @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 - */ - read(offset, size, buffer) { - return this._engine.readFromStorageBuffer(this._buffer, offset, size, buffer); - } - /** - * Disposes the storage buffer - */ - dispose() { - const storageBuffers = this._engine._storageBuffers; - const index = storageBuffers.indexOf(this); - if (index !== -1) { - storageBuffers[index] = storageBuffers[storageBuffers.length - 1]; - storageBuffers.pop(); - } - this._engine._releaseBuffer(this._buffer); - this._buffer = null; - } -} -//# sourceMappingURL=storageBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Buffers/index.js - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/BaseCameraMouseWheelInput.js - - - - - - -/** - * Base class for mouse wheel input.. - * See FollowCameraMouseWheelInput in src/Cameras/Inputs/freeCameraMouseWheelInput.ts - * for example usage. - */ -class BaseCameraMouseWheelInput { - constructor() { - /** - * How fast is the camera moves in relation to X axis mouseWheel events. - * Use negative value to reverse direction. - */ - this.wheelPrecisionX = 3.0; - /** - * How fast is the camera moves in relation to Y axis mouseWheel events. - * Use negative value to reverse direction. - */ - this.wheelPrecisionY = 3.0; - /** - * How fast is the camera moves in relation to Z axis mouseWheel events. - * Use negative value to reverse direction. - */ - this.wheelPrecisionZ = 3.0; - /** - * Observable for when a mouse wheel move event occurs. - */ - this.onChangedObservable = new observable_Observable(); - /** - * Incremental value of multiple mouse wheel movements of the X axis. - * Should be zero-ed when read. - */ - this._wheelDeltaX = 0; - /** - * Incremental value of multiple mouse wheel movements of the Y axis. - * Should be zero-ed when read. - */ - this._wheelDeltaY = 0; - /** - * Incremental value of multiple mouse wheel movements of the Z axis. - * Should be zero-ed when read. - */ - this._wheelDeltaZ = 0; - /** - * Firefox uses a different scheme to report scroll distances to other - * browsers. Rather than use complicated methods to calculate the exact - * multiple we need to apply, let's just cheat and use a constant. - * https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode - * https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line - */ - this._ffMultiplier = 12; - /** - * Different event attributes for wheel data fall into a few set ranges. - * Some relevant but dated date here: - * https://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers - */ - this._normalize = 120; - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls - * should call preventdefault(). - * (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - this._wheel = (pointer) => { - // sanity check - this should be a PointerWheel event. - if (pointer.type !== pointerEvents_PointerEventTypes.POINTERWHEEL) { - return; - } - const event = pointer.event; - const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? this._ffMultiplier : 1; // If this happens to be set to DOM_DELTA_LINE, adjust accordingly - this._wheelDeltaX += (this.wheelPrecisionX * platformScale * event.deltaX) / this._normalize; - this._wheelDeltaY -= (this.wheelPrecisionY * platformScale * event.deltaY) / this._normalize; - this._wheelDeltaZ += (this.wheelPrecisionZ * platformScale * event.deltaZ) / this._normalize; - if (event.preventDefault) { - if (!noPreventDefault) { - event.preventDefault(); - } - } - }; - this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, pointerEvents_PointerEventTypes.POINTERWHEEL); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (this._observer) { - this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); - this._observer = null; - this._wheel = null; - } - if (this.onChangedObservable) { - this.onChangedObservable.clear(); - } - } - /** - * Called for each rendered frame. - */ - checkInputs() { - this.onChangedObservable.notifyObservers({ - wheelDeltaX: this._wheelDeltaX, - wheelDeltaY: this._wheelDeltaY, - wheelDeltaZ: this._wheelDeltaZ, - }); - // Clear deltas. - this._wheelDeltaX = 0; - this._wheelDeltaY = 0; - this._wheelDeltaZ = 0; - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "BaseCameraMouseWheelInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "mousewheel"; - } -} -__decorate([ - serialize() -], BaseCameraMouseWheelInput.prototype, "wheelPrecisionX", void 0); -__decorate([ - serialize() -], BaseCameraMouseWheelInput.prototype, "wheelPrecisionY", void 0); -__decorate([ - serialize() -], BaseCameraMouseWheelInput.prototype, "wheelPrecisionZ", void 0); -//# sourceMappingURL=BaseCameraMouseWheelInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/BaseCameraPointersInput.js - - - - -/** - * Base class for Camera Pointer Inputs. - * See FollowCameraPointersInput in src/Cameras/Inputs/followCameraPointersInput.ts - * for example usage. - */ -class BaseCameraPointersInput { - constructor() { - this._currentActiveButton = -1; - /** - * Defines the buttons associated with the input to handle camera move. - */ - this.buttons = [0, 1, 2]; - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - const engine = this.camera.getEngine(); - const element = engine.getInputElement(); - let previousPinchSquaredDistance = 0; - let previousMultiTouchPanPosition = null; - this._pointA = null; - this._pointB = null; - this._altKey = false; - this._ctrlKey = false; - this._metaKey = false; - this._shiftKey = false; - this._buttonsPressed = 0; - this._pointerInput = (p) => { - var _a, _b; - const evt = p.event; - const isTouch = evt.pointerType === "touch"; - if (engine.isInVRExclusivePointerMode) { - return; - } - if (p.type !== pointerEvents_PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) { - return; - } - const srcElement = evt.target; - this._altKey = evt.altKey; - this._ctrlKey = evt.ctrlKey; - this._metaKey = evt.metaKey; - this._shiftKey = evt.shiftKey; - this._buttonsPressed = evt.buttons; - if (engine.isPointerLock) { - const offsetX = evt.movementX; - const offsetY = evt.movementY; - this.onTouch(null, offsetX, offsetY); - this._pointA = null; - this._pointB = null; - } - else if (p.type !== pointerEvents_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) { - return; // If we get a non-down event for a touch that we're not tracking, ignore it - } - else if (p.type === pointerEvents_PointerEventTypes.POINTERDOWN && (this._currentActiveButton === -1 || isTouch)) { - try { - srcElement === null || srcElement === void 0 ? void 0 : srcElement.setPointerCapture(evt.pointerId); - } - catch (e) { - //Nothing to do with the error. Execution will continue. - } - if (this._pointA === null) { - this._pointA = { - x: evt.clientX, - y: evt.clientY, - pointerId: evt.pointerId, - type: evt.pointerType, - }; - } - else if (this._pointB === null) { - this._pointB = { - x: evt.clientX, - y: evt.clientY, - pointerId: evt.pointerId, - type: evt.pointerType, - }; - } - else { - return; // We are already tracking two pointers so ignore this one - } - if (this._currentActiveButton === -1 && !isTouch) { - this._currentActiveButton = evt.button; - } - this.onButtonDown(evt); - if (!noPreventDefault) { - evt.preventDefault(); - element && element.focus(); - } - } - else if (p.type === pointerEvents_PointerEventTypes.POINTERDOUBLETAP) { - this.onDoubleTap(evt.pointerType); - } - else if (p.type === pointerEvents_PointerEventTypes.POINTERUP && (this._currentActiveButton === evt.button || isTouch)) { - try { - srcElement === null || srcElement === void 0 ? void 0 : srcElement.releasePointerCapture(evt.pointerId); - } - catch (e) { - //Nothing to do with the error. - } - if (!isTouch) { - this._pointB = null; // Mouse and pen are mono pointer - } - //would be better to use pointers.remove(evt.pointerId) for multitouch gestures, - //but emptying completely pointers collection is required to fix a bug on iPhone : - //when changing orientation while pinching camera, - //one pointer stay pressed forever if we don't release all pointers - //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected - if (engine._badOS) { - this._pointA = this._pointB = null; - } - else { - //only remove the impacted pointer in case of multitouch allowing on most - //platforms switching from rotate to zoom and pan seamlessly. - if (this._pointB && this._pointA && this._pointA.pointerId == evt.pointerId) { - this._pointA = this._pointB; - this._pointB = null; - } - else if (this._pointA && this._pointB && this._pointB.pointerId == evt.pointerId) { - this._pointB = null; - } - else { - this._pointA = this._pointB = null; - } - } - if (previousPinchSquaredDistance !== 0 || previousMultiTouchPanPosition) { - // Previous pinch data is populated but a button has been lifted - // so pinch has ended. - this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, 0, // pinchSquaredDistance - previousMultiTouchPanPosition, null // multiTouchPanPosition - ); - previousPinchSquaredDistance = 0; - previousMultiTouchPanPosition = null; - } - this._currentActiveButton = -1; - this.onButtonUp(evt); - if (!noPreventDefault) { - evt.preventDefault(); - } - } - else if (p.type === pointerEvents_PointerEventTypes.POINTERMOVE) { - if (!noPreventDefault) { - evt.preventDefault(); - } - // One button down - if (this._pointA && this._pointB === null) { - const offsetX = evt.clientX - this._pointA.x; - const offsetY = evt.clientY - this._pointA.y; - this.onTouch(this._pointA, offsetX, offsetY); - this._pointA.x = evt.clientX; - this._pointA.y = evt.clientY; - } - // Two buttons down: pinch - else if (this._pointA && this._pointB) { - const ed = this._pointA.pointerId === evt.pointerId ? this._pointA : this._pointB; - ed.x = evt.clientX; - ed.y = evt.clientY; - const distX = this._pointA.x - this._pointB.x; - const distY = this._pointA.y - this._pointB.y; - const pinchSquaredDistance = distX * distX + distY * distY; - const multiTouchPanPosition = { - x: (this._pointA.x + this._pointB.x) / 2, - y: (this._pointA.y + this._pointB.y) / 2, - pointerId: evt.pointerId, - type: p.type, - }; - this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition); - previousMultiTouchPanPosition = multiTouchPanPosition; - previousPinchSquaredDistance = pinchSquaredDistance; - } - } - }; - this._observer = this.camera - .getScene() - ._inputManager._addCameraPointerObserver(this._pointerInput, pointerEvents_PointerEventTypes.POINTERDOWN | pointerEvents_PointerEventTypes.POINTERUP | pointerEvents_PointerEventTypes.POINTERMOVE | pointerEvents_PointerEventTypes.POINTERDOUBLETAP); - this._onLostFocus = () => { - this._pointA = this._pointB = null; - previousPinchSquaredDistance = 0; - previousMultiTouchPanPosition = null; - this.onLostFocus(); - }; - this._contextMenuBind = this.onContextMenu.bind(this); - element && element.addEventListener("contextmenu", this._contextMenuBind, false); - const hostWindow = this.camera.getScene().getEngine().getHostWindow(); - if (hostWindow) { - tools_Tools.RegisterTopRootEvents(hostWindow, [{ name: "blur", handler: this._onLostFocus }]); - } - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (this._onLostFocus) { - const hostWindow = this.camera.getScene().getEngine().getHostWindow(); - if (hostWindow) { - tools_Tools.UnregisterTopRootEvents(hostWindow, [{ name: "blur", handler: this._onLostFocus }]); - } - } - if (this._observer) { - this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); - this._observer = null; - if (this._contextMenuBind) { - const inputElement = this.camera.getScene().getEngine().getInputElement(); - inputElement && inputElement.removeEventListener("contextmenu", this._contextMenuBind); - } - this._onLostFocus = null; - } - this._altKey = false; - this._ctrlKey = false; - this._metaKey = false; - this._shiftKey = false; - this._buttonsPressed = 0; - this._currentActiveButton = -1; - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "BaseCameraPointersInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "pointers"; - } - /** - * Called on pointer POINTERDOUBLETAP event. - * Override this method to provide functionality on POINTERDOUBLETAP event. - * @param type - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onDoubleTap(type) { } - /** - * Called on pointer POINTERMOVE event if only a single touch is active. - * Override this method to provide functionality. - * @param point - * @param offsetX - * @param offsetY - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onTouch(point, offsetX, offsetY) { } - /** - * Called on pointer POINTERMOVE event if multiple touches are active. - * Override this method to provide functionality. - * @param _pointA - * @param _pointB - * @param previousPinchSquaredDistance - * @param pinchSquaredDistance - * @param previousMultiTouchPanPosition - * @param multiTouchPanPosition - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onMultiTouch(_pointA, _pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { } - /** - * Called on JS contextmenu event. - * Override this method to provide functionality. - * @param evt - */ - onContextMenu(evt) { - evt.preventDefault(); - } - /** - * Called each time a new POINTERDOWN event occurs. Ie, for each button - * press. - * Override this method to provide functionality. - * @param evt - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onButtonDown(evt) { } - /** - * Called each time a new POINTERUP event occurs. Ie, for each button - * release. - * Override this method to provide functionality. - * @param evt - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - onButtonUp(evt) { } - /** - * Called when window becomes inactive. - * Override this method to provide functionality. - */ - onLostFocus() { } -} -__decorate([ - serialize() -], BaseCameraPointersInput.prototype, "buttons", void 0); -//# sourceMappingURL=BaseCameraPointersInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/cameraInputsManager.js - - - -/** - * @ignore - * This is a list of all the different input types that are available in the application. - * Fo instance: ArcRotateCameraGamepadInput... - */ -// eslint-disable-next-line no-var, @typescript-eslint/naming-convention -var CameraInputTypes = {}; -/** - * This represents the input manager used within a camera. - * It helps dealing with all the different kind of input attached to a camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class CameraInputsManager { - /** - * Instantiate a new Camera Input Manager. - * @param camera Defines the camera the input manager belongs to - */ - constructor(camera) { - /** - * Defines the dom element the camera is collecting inputs from. - * This is null if the controls have not been attached. - */ - this.attachedToElement = false; - this.attached = {}; - this.camera = camera; - this.checkInputs = () => { }; - } - /** - * Add an input method to a camera - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - * @param input Camera input method - */ - add(input) { - const type = input.getSimpleName(); - if (this.attached[type]) { - logger_Logger.Warn("camera input of type " + type + " already exists on camera"); - return; - } - this.attached[type] = input; - input.camera = this.camera; - // for checkInputs, we are dynamically creating a function - // the goal is to avoid the performance penalty of looping for inputs in the render loop - if (input.checkInputs) { - this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input)); - } - if (this.attachedToElement) { - input.attachControl(this.noPreventDefault); - } - } - /** - * Remove a specific input method from a camera - * example: camera.inputs.remove(camera.inputs.attached.mouse); - * @param inputToRemove camera input method - */ - remove(inputToRemove) { - for (const cam in this.attached) { - const input = this.attached[cam]; - if (input === inputToRemove) { - input.detachControl(); - input.camera = null; - delete this.attached[cam]; - this.rebuildInputCheck(); - return; - } - } - } - /** - * Remove a specific input type from a camera - * example: camera.inputs.remove("ArcRotateCameraGamepadInput"); - * @param inputType the type of the input to remove - */ - removeByType(inputType) { - for (const cam in this.attached) { - const input = this.attached[cam]; - if (input.getClassName() === inputType) { - input.detachControl(); - input.camera = null; - delete this.attached[cam]; - this.rebuildInputCheck(); - } - } - } - _addCheckInputs(fn) { - const current = this.checkInputs; - return () => { - current(); - fn(); - }; - } - /** - * Attach the input controls to the currently attached dom element to listen the events from. - * @param input Defines the input to attach - */ - attachInput(input) { - if (this.attachedToElement) { - input.attachControl(this.noPreventDefault); - } - } - /** - * Attach the current manager inputs controls to a specific dom element to listen the events from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachElement(noPreventDefault = false) { - if (this.attachedToElement) { - return; - } - noPreventDefault = camera_Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault; - this.attachedToElement = true; - this.noPreventDefault = noPreventDefault; - for (const cam in this.attached) { - this.attached[cam].attachControl(noPreventDefault); - } - } - /** - * Detach the current manager inputs controls from a specific dom element. - * @param disconnect Defines whether the input should be removed from the current list of attached inputs - */ - detachElement(disconnect = false) { - for (const cam in this.attached) { - this.attached[cam].detachControl(); - if (disconnect) { - this.attached[cam].camera = null; - } - } - this.attachedToElement = false; - } - /** - * Rebuild the dynamic inputCheck function from the current list of - * defined inputs in the manager. - */ - rebuildInputCheck() { - this.checkInputs = () => { }; - for (const cam in this.attached) { - const input = this.attached[cam]; - if (input.checkInputs) { - this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input)); - } - } - } - /** - * Remove all attached input methods from a camera - */ - clear() { - if (this.attachedToElement) { - this.detachElement(true); - } - this.attached = {}; - this.attachedToElement = false; - this.checkInputs = () => { }; - } - /** - * Serialize the current input manager attached to a camera. - * This ensures than once parsed, - * the input associated to the camera will be identical to the current ones - * @param serializedCamera Defines the camera serialization JSON the input serialization should write to - */ - serialize(serializedCamera) { - const inputs = {}; - for (const cam in this.attached) { - const input = this.attached[cam]; - const res = decorators_SerializationHelper.Serialize(input); - inputs[input.getClassName()] = res; - } - serializedCamera.inputsmgr = inputs; - } - /** - * Parses an input manager serialized JSON to restore the previous list of inputs - * and states associated to a camera. - * @param parsedCamera Defines the JSON to parse - */ - parse(parsedCamera) { - const parsedInputs = parsedCamera.inputsmgr; - if (parsedInputs) { - this.clear(); - for (const n in parsedInputs) { - const construct = CameraInputTypes[n]; - if (construct) { - const parsedinput = parsedInputs[n]; - const input = decorators_SerializationHelper.Parse(() => { - return new construct(); - }, parsedinput, null); - this.add(input); - } - } - } - else { - //2016-03-08 this part is for managing backward compatibility - for (const n in this.attached) { - const construct = CameraInputTypes[this.attached[n].getClassName()]; - if (construct) { - const input = decorators_SerializationHelper.Parse(() => { - return new construct(); - }, parsedCamera, null); - this.remove(this.attached[n]); - this.add(input); - } - } - } - } -} -//# sourceMappingURL=cameraInputsManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/gamepad.js - -/** - * Represents a gamepad control stick position - */ -class StickValues { - /** - * Initializes the gamepad x and y control stick values - * @param x The x component of the gamepad control stick value - * @param y The y component of the gamepad control stick value - */ - constructor( - /** - * The x component of the control stick - */ - x, - /** - * The y component of the control stick - */ - y) { - this.x = x; - this.y = y; - } -} -/** - * Represents a gamepad - */ -class Gamepad { - /** - * Specifies if the gamepad has been connected - */ - get isConnected() { - return this._isConnected; - } - /** - * Initializes the gamepad - * @param id The id of the gamepad - * @param index The index of the gamepad - * @param browserGamepad The browser gamepad - * @param leftStickX The x component of the left joystick - * @param leftStickY The y component of the left joystick - * @param rightStickX The x component of the right joystick - * @param rightStickY The y component of the right joystick - */ - constructor( - /** - * The id of the gamepad - */ - id, - /** - * The index of the gamepad - */ - index, - /** - * The browser gamepad - */ - browserGamepad, leftStickX = 0, leftStickY = 1, rightStickX = 2, rightStickY = 3) { - this.id = id; - this.index = index; - this.browserGamepad = browserGamepad; - this._leftStick = { x: 0, y: 0 }; - this._rightStick = { x: 0, y: 0 }; - /** @internal */ - this._isConnected = true; - /** - * Specifies whether the left control stick should be Y-inverted - */ - this._invertLeftStickY = false; - this.type = Gamepad.GAMEPAD; - this._leftStickAxisX = leftStickX; - this._leftStickAxisY = leftStickY; - this._rightStickAxisX = rightStickX; - this._rightStickAxisY = rightStickY; - if (this.browserGamepad.axes.length >= 2) { - this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] }; - } - if (this.browserGamepad.axes.length >= 4) { - this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] }; - } - } - /** - * Callback triggered when the left joystick has changed - * @param callback - */ - onleftstickchanged(callback) { - this._onleftstickchanged = callback; - } - /** - * Callback triggered when the right joystick has changed - * @param callback - */ - onrightstickchanged(callback) { - this._onrightstickchanged = callback; - } - /** - * Gets the left joystick - */ - get leftStick() { - return this._leftStick; - } - /** - * Sets the left joystick values - */ - set leftStick(newValues) { - if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) { - this._onleftstickchanged(newValues); - } - this._leftStick = newValues; - } - /** - * Gets the right joystick - */ - get rightStick() { - return this._rightStick; - } - /** - * Sets the right joystick value - */ - set rightStick(newValues) { - if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) { - this._onrightstickchanged(newValues); - } - this._rightStick = newValues; - } - /** - * Updates the gamepad joystick positions - */ - update() { - if (this._leftStick) { - this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] }; - if (this._invertLeftStickY) { - this.leftStick.y *= -1; - } - } - if (this._rightStick) { - this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] }; - } - } - /** - * Disposes the gamepad - */ - dispose() { } -} -/** - * Represents a gamepad controller - */ -Gamepad.GAMEPAD = 0; -/** - * Represents a generic controller - */ -Gamepad.GENERIC = 1; -/** - * Represents an XBox controller - */ -Gamepad.XBOX = 2; -/** - * Represents a pose-enabled controller - */ -Gamepad.POSE_ENABLED = 3; -/** - * Represents an Dual Shock controller - */ -Gamepad.DUALSHOCK = 4; -/** - * Represents a generic gamepad - */ -class GenericPad extends Gamepad { - /** - * Callback triggered when a button has been pressed - * @param callback Called when a button has been pressed - */ - onbuttondown(callback) { - this._onbuttondown = callback; - } - /** - * Callback triggered when a button has been released - * @param callback Called when a button has been released - */ - onbuttonup(callback) { - this._onbuttonup = callback; - } - /** - * Initializes the generic gamepad - * @param id The id of the generic gamepad - * @param index The index of the generic gamepad - * @param browserGamepad The browser gamepad - */ - constructor(id, index, browserGamepad) { - super(id, index, browserGamepad); - /** - * Observable triggered when a button has been pressed - */ - this.onButtonDownObservable = new observable_Observable(); - /** - * Observable triggered when a button has been released - */ - this.onButtonUpObservable = new observable_Observable(); - this.type = Gamepad.GENERIC; - this._buttons = new Array(browserGamepad.buttons.length); - } - _setButtonValue(newValue, currentValue, buttonIndex) { - if (newValue !== currentValue) { - if (newValue === 1) { - if (this._onbuttondown) { - this._onbuttondown(buttonIndex); - } - this.onButtonDownObservable.notifyObservers(buttonIndex); - } - if (newValue === 0) { - if (this._onbuttonup) { - this._onbuttonup(buttonIndex); - } - this.onButtonUpObservable.notifyObservers(buttonIndex); - } - } - return newValue; - } - /** - * Updates the generic gamepad - */ - update() { - super.update(); - for (let index = 0; index < this._buttons.length; index++) { - this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index); - } - } - /** - * Disposes the generic gamepad - */ - dispose() { - super.dispose(); - this.onButtonDownObservable.clear(); - this.onButtonUpObservable.clear(); - } -} -//# sourceMappingURL=gamepad.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraGamepadInput.js - - - - -/** - * Manage the gamepad inputs to control an arc rotate camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class ArcRotateCameraGamepadInput { - constructor() { - /** - * Defines the gamepad rotation sensibility. - * This is the threshold from when rotation starts to be accounted for to prevent jittering. - */ - this.gamepadRotationSensibility = 80; - /** - * Defines the gamepad move sensibility. - * This is the threshold from when moving starts to be accounted for for to prevent jittering. - */ - this.gamepadMoveSensibility = 40; - this._yAxisScale = 1.0; - } - /** - * Gets or sets a boolean indicating that Yaxis (for right stick) should be inverted - */ - get invertYAxis() { - return this._yAxisScale !== 1.0; - } - set invertYAxis(value) { - this._yAxisScale = value ? -1.0 : 1.0; - } - /** - * Attach the input controls to a specific dom element to get the input from. - */ - attachControl() { - const manager = this.camera.getScene().gamepadManager; - this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => { - if (gamepad.type !== Gamepad.POSE_ENABLED) { - // prioritize XBOX gamepads. - if (!this.gamepad || gamepad.type === Gamepad.XBOX) { - this.gamepad = gamepad; - } - } - }); - this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => { - if (this.gamepad === gamepad) { - this.gamepad = null; - } - }); - this.gamepad = manager.getGamepadByType(Gamepad.XBOX); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); - this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); - this.gamepad = null; - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - if (this.gamepad) { - const camera = this.camera; - const rsValues = this.gamepad.rightStick; - if (rsValues) { - if (rsValues.x != 0) { - const normalizedRX = rsValues.x / this.gamepadRotationSensibility; - if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) { - camera.inertialAlphaOffset += normalizedRX; - } - } - if (rsValues.y != 0) { - const normalizedRY = (rsValues.y / this.gamepadRotationSensibility) * this._yAxisScale; - if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) { - camera.inertialBetaOffset += normalizedRY; - } - } - } - const lsValues = this.gamepad.leftStick; - if (lsValues && lsValues.y != 0) { - const normalizedLY = lsValues.y / this.gamepadMoveSensibility; - if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) { - this.camera.inertialRadiusOffset -= normalizedLY; - } - } - } - } - /** - * Gets the class name of the current intput. - * @returns the class name - */ - getClassName() { - return "ArcRotateCameraGamepadInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "gamepad"; - } -} -__decorate([ - serialize() -], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0); -__decorate([ - serialize() -], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); -CameraInputTypes.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput; -//# sourceMappingURL=arcRotateCameraGamepadInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraKeyboardMoveInput.js - - - - - -/** - * Manage the keyboard inputs to control the movement of an arc rotate camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class ArcRotateCameraKeyboardMoveInput { - constructor() { - /** - * Defines the list of key codes associated with the up action (increase alpha) - */ - this.keysUp = [38]; - /** - * Defines the list of key codes associated with the down action (decrease alpha) - */ - this.keysDown = [40]; - /** - * Defines the list of key codes associated with the left action (increase beta) - */ - this.keysLeft = [37]; - /** - * Defines the list of key codes associated with the right action (decrease beta) - */ - this.keysRight = [39]; - /** - * Defines the list of key codes associated with the reset action. - * Those keys reset the camera to its last stored state (with the method camera.storeState()) - */ - this.keysReset = [220]; - /** - * Defines the panning sensibility of the inputs. - * (How fast is the camera panning) - */ - this.panningSensibility = 50.0; - /** - * Defines the zooming sensibility of the inputs. - * (How fast is the camera zooming) - */ - this.zoomingSensibility = 25.0; - /** - * Defines whether maintaining the alt key down switch the movement mode from - * orientation to zoom. - */ - this.useAltToZoom = true; - /** - * Rotation speed of the camera - */ - this.angularSpeed = 0.01; - this._keys = new Array(); - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - // was there a second variable defined? - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - if (this._onCanvasBlurObserver) { - return; - } - 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((info) => { - const evt = info.event; - if (!evt.metaKey) { - if (info.type === KeyboardEventTypes.KEYDOWN) { - this._ctrlPressed = evt.ctrlKey; - this._altPressed = evt.altKey; - if (this.keysUp.indexOf(evt.keyCode) !== -1 || - this.keysDown.indexOf(evt.keyCode) !== -1 || - this.keysLeft.indexOf(evt.keyCode) !== -1 || - this.keysRight.indexOf(evt.keyCode) !== -1 || - this.keysReset.indexOf(evt.keyCode) !== -1) { - const index = this._keys.indexOf(evt.keyCode); - if (index === -1) { - this._keys.push(evt.keyCode); - } - if (evt.preventDefault) { - if (!noPreventDefault) { - evt.preventDefault(); - } - } - } - } - else { - if (this.keysUp.indexOf(evt.keyCode) !== -1 || - this.keysDown.indexOf(evt.keyCode) !== -1 || - this.keysLeft.indexOf(evt.keyCode) !== -1 || - this.keysRight.indexOf(evt.keyCode) !== -1 || - this.keysReset.indexOf(evt.keyCode) !== -1) { - const index = this._keys.indexOf(evt.keyCode); - if (index >= 0) { - this._keys.splice(index, 1); - } - if (evt.preventDefault) { - if (!noPreventDefault) { - evt.preventDefault(); - } - } - } - } - } - }); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (this._scene) { - if (this._onKeyboardObserver) { - this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); - } - if (this._onCanvasBlurObserver) { - this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); - } - this._onKeyboardObserver = null; - this._onCanvasBlurObserver = null; - } - this._keys.length = 0; - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - if (this._onKeyboardObserver) { - const camera = this.camera; - for (let index = 0; index < this._keys.length; index++) { - const keyCode = this._keys[index]; - if (this.keysLeft.indexOf(keyCode) !== -1) { - if (this._ctrlPressed && this.camera._useCtrlForPanning) { - camera.inertialPanningX -= 1 / this.panningSensibility; - } - else { - camera.inertialAlphaOffset -= this.angularSpeed; - } - } - else if (this.keysUp.indexOf(keyCode) !== -1) { - if (this._ctrlPressed && this.camera._useCtrlForPanning) { - camera.inertialPanningY += 1 / this.panningSensibility; - } - else if (this._altPressed && this.useAltToZoom) { - camera.inertialRadiusOffset += 1 / this.zoomingSensibility; - } - else { - camera.inertialBetaOffset -= this.angularSpeed; - } - } - else if (this.keysRight.indexOf(keyCode) !== -1) { - if (this._ctrlPressed && this.camera._useCtrlForPanning) { - camera.inertialPanningX += 1 / this.panningSensibility; - } - else { - camera.inertialAlphaOffset += this.angularSpeed; - } - } - else if (this.keysDown.indexOf(keyCode) !== -1) { - if (this._ctrlPressed && this.camera._useCtrlForPanning) { - camera.inertialPanningY -= 1 / this.panningSensibility; - } - else if (this._altPressed && this.useAltToZoom) { - camera.inertialRadiusOffset -= 1 / this.zoomingSensibility; - } - else { - camera.inertialBetaOffset += this.angularSpeed; - } - } - else if (this.keysReset.indexOf(keyCode) !== -1) { - if (camera.useInputToRestoreState) { - camera.restoreState(); - } - } - } - } - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "ArcRotateCameraKeyboardMoveInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "keyboard"; - } -} -__decorate([ - serialize() -], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0); -__decorate([ - serialize() -], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0); -__decorate([ - serialize() -], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0); -__decorate([ - serialize() -], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0); -__decorate([ - serialize() -], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0); -__decorate([ - serialize() -], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0); -__decorate([ - serialize() -], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0); -__decorate([ - serialize() -], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0); -__decorate([ - serialize() -], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0); -CameraInputTypes.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput; -//# sourceMappingURL=arcRotateCameraKeyboardMoveInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraMouseWheelInput.js - - - - - - - - - - -/** - * Firefox uses a different scheme to report scroll distances to other - * browsers. Rather than use complicated methods to calculate the exact - * multiple we need to apply, let's just cheat and use a constant. - * https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode - * https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line - */ -const ffMultiplier = 40; -/** - * Manage the mouse wheel inputs to control an arc rotate camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class ArcRotateCameraMouseWheelInput { - constructor() { - /** - * Gets or Set the mouse wheel precision or how fast is the camera zooming. - */ - this.wheelPrecision = 3.0; - /** - * Gets or Set the boolean value that controls whether or not the mouse wheel - * zooms to the location of the mouse pointer or not. The default is false. - */ - this.zoomToMouseLocation = false; - /** - * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0. - * It defines the percentage of current camera.radius to use as delta when wheel is used. - */ - this.wheelDeltaPercentage = 0; - /** - * If set, this function will be used to set the radius delta that will be added to the current camera radius - */ - this.customComputeDeltaFromMouseWheel = null; - this._inertialPanning = math_vector_Vector3.Zero(); - } - _computeDeltaFromMouseWheelLegacyEvent(mouseWheelDelta, radius) { - let delta = 0; - const wheelDelta = mouseWheelDelta * 0.01 * this.wheelDeltaPercentage * radius; - if (mouseWheelDelta > 0) { - delta = wheelDelta / (1.0 + this.wheelDeltaPercentage); - } - else { - delta = wheelDelta * (1.0 + this.wheelDeltaPercentage); - } - return delta; - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - this._wheel = (p) => { - //sanity check - this should be a PointerWheel event. - if (p.type !== pointerEvents_PointerEventTypes.POINTERWHEEL) { - return; - } - const event = p.event; - let delta = 0; - const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? ffMultiplier : 1; // If this happens to be set to DOM_DELTA_LINE, adjust accordingly - const wheelDelta = -(event.deltaY * platformScale); - if (this.customComputeDeltaFromMouseWheel) { - delta = this.customComputeDeltaFromMouseWheel(wheelDelta, this, event); - } - else { - if (this.wheelDeltaPercentage) { - delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, this.camera.radius); - // If zooming in, estimate the target radius and use that to compute the delta for inertia - // this will stop multiple scroll events zooming in from adding too much inertia - if (delta > 0) { - let estimatedTargetRadius = this.camera.radius; - let targetInertia = this.camera.inertialRadiusOffset + delta; - for (let i = 0; i < 20 && Math.abs(targetInertia) > 0.001; i++) { - estimatedTargetRadius -= targetInertia; - targetInertia *= this.camera.inertia; - } - estimatedTargetRadius = math_scalar_Scalar.Clamp(estimatedTargetRadius, 0, Number.MAX_VALUE); - delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, estimatedTargetRadius); - } - } - else { - delta = wheelDelta / (this.wheelPrecision * 40); - } - } - if (delta) { - if (this.zoomToMouseLocation) { - // 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 - // The hit plane is normally calculated after the first motion and each time there's motion so if we don't do this first, - // the first zoom will be to the center of the screen - if (!this._hitPlane) { - this._updateHitPlane(); - } - this._zoomToMouse(delta); - } - else { - this.camera.inertialRadiusOffset += delta; - } - } - if (event.preventDefault) { - if (!noPreventDefault) { - event.preventDefault(); - } - } - }; - this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, pointerEvents_PointerEventTypes.POINTERWHEEL); - if (this.zoomToMouseLocation) { - this._inertialPanning.setAll(0); - } - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (this._observer) { - this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); - this._observer = null; - this._wheel = null; - } - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - if (!this.zoomToMouseLocation) { - return; - } - const camera = this.camera; - const motion = 0.0 + camera.inertialAlphaOffset + camera.inertialBetaOffset + camera.inertialRadiusOffset; - if (motion) { - // if zooming is still happening as a result of inertia, then we also need to update - // the hit plane. - this._updateHitPlane(); - // Note we cannot use arcRotateCamera.inertialPlanning here because arcRotateCamera panning - // uses a different panningInertia which could cause this panning to get out of sync with - // the zooming, and for this to work they must be exactly in sync. - camera.target.addInPlace(this._inertialPanning); - this._inertialPanning.scaleInPlace(camera.inertia); - this._zeroIfClose(this._inertialPanning); - } - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "ArcRotateCameraMouseWheelInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "mousewheel"; - } - _updateHitPlane() { - const camera = this.camera; - const direction = camera.target.subtract(camera.position); - this._hitPlane = math_plane_Plane.FromPositionAndNormal(camera.target, direction); - } - // Get position on the hit plane - _getPosition() { - var _a; - const camera = this.camera; - const scene = camera.getScene(); - // since the _hitPlane is always updated to be orthogonal to the camera position vector - // we don't have to worry about this ray shooting off to infinity. This ray creates - // a vector defining where we want to zoom to. - const ray = scene.createPickingRay(scene.pointerX, scene.pointerY, math_vector_Matrix.Identity(), camera, false); - // Since the camera is the origin of the picking ray, we need to offset it by the camera's offset manually - ray.origin.x -= camera.targetScreenOffset.x; - ray.origin.y -= camera.targetScreenOffset.y; - let distance = 0; - if (this._hitPlane) { - distance = (_a = ray.intersectsPlane(this._hitPlane)) !== null && _a !== void 0 ? _a : 0; - } - // not using this ray again, so modifying its vectors here is fine - return ray.origin.addInPlace(ray.direction.scaleInPlace(distance)); - } - _zoomToMouse(delta) { - var _a, _b; - const camera = this.camera; - const inertiaComp = 1 - camera.inertia; - if (camera.lowerRadiusLimit) { - const lowerLimit = (_a = camera.lowerRadiusLimit) !== null && _a !== void 0 ? _a : 0; - if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp < lowerLimit) { - delta = (camera.radius - lowerLimit) * inertiaComp - camera.inertialRadiusOffset; - } - } - if (camera.upperRadiusLimit) { - const upperLimit = (_b = camera.upperRadiusLimit) !== null && _b !== void 0 ? _b : 0; - if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp > upperLimit) { - delta = (camera.radius - upperLimit) * inertiaComp - camera.inertialRadiusOffset; - } - } - const zoomDistance = delta / inertiaComp; - const ratio = zoomDistance / camera.radius; - const vec = this._getPosition(); - // Now this vector tells us how much we also need to pan the camera - // so the targeted mouse location becomes the center of zooming. - const directionToZoomLocation = math_vector_TmpVectors.Vector3[6]; - vec.subtractToRef(camera.target, directionToZoomLocation); - directionToZoomLocation.scaleInPlace(ratio); - directionToZoomLocation.scaleInPlace(inertiaComp); - this._inertialPanning.addInPlace(directionToZoomLocation); - camera.inertialRadiusOffset += delta; - } - // Sets x y or z of passed in vector to zero if less than Epsilon. - _zeroIfClose(vec) { - if (Math.abs(vec.x) < math_constants_Epsilon) { - vec.x = 0; - } - if (Math.abs(vec.y) < math_constants_Epsilon) { - vec.y = 0; - } - if (Math.abs(vec.z) < math_constants_Epsilon) { - vec.z = 0; - } - } -} -__decorate([ - serialize() -], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0); -__decorate([ - serialize() -], ArcRotateCameraMouseWheelInput.prototype, "zoomToMouseLocation", void 0); -__decorate([ - serialize() -], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0); -CameraInputTypes.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput; -//# sourceMappingURL=arcRotateCameraMouseWheelInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraPointersInput.js - - - - -/** - * Manage the pointers inputs to control an arc rotate camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class ArcRotateCameraPointersInput extends BaseCameraPointersInput { - constructor() { - super(...arguments); - /** - * Defines the buttons associated with the input to handle camera move. - */ - this.buttons = [0, 1, 2]; - /** - * Defines the pointer angular sensibility along the X axis or how fast is - * the camera rotating. - */ - this.angularSensibilityX = 1000.0; - /** - * Defines the pointer angular sensibility along the Y axis or how fast is - * the camera rotating. - */ - this.angularSensibilityY = 1000.0; - /** - * Defines the pointer pinch precision or how fast is the camera zooming. - */ - this.pinchPrecision = 12.0; - /** - * pinchDeltaPercentage will be used instead of pinchPrecision if different - * from 0. - * It defines the percentage of current camera.radius to use as delta when - * pinch zoom is used. - */ - this.pinchDeltaPercentage = 0; - /** - * When useNaturalPinchZoom is true, multi touch zoom will zoom in such - * that any object in the plane at the camera's target point will scale - * perfectly with finger motion. - * Overrides pinchDeltaPercentage and pinchPrecision. - */ - this.useNaturalPinchZoom = false; - /** - * Defines whether zoom (2 fingers pinch) is enabled through multitouch - */ - this.pinchZoom = true; - /** - * Defines the pointer panning sensibility or how fast is the camera moving. - */ - this.panningSensibility = 1000.0; - /** - * Defines whether panning (2 fingers swipe) is enabled through multitouch. - */ - this.multiTouchPanning = true; - /** - * Defines whether panning is enabled for both pan (2 fingers swipe) and - * zoom (pinch) through multitouch. - */ - this.multiTouchPanAndZoom = true; - /** - * Revers pinch action direction. - */ - this.pinchInwards = true; - this._isPanClick = false; - this._twoFingerActivityCount = 0; - this._isPinching = false; - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "ArcRotateCameraPointersInput"; - } - /** - * Move camera from multi touch panning positions. - * @param previousMultiTouchPanPosition - * @param multiTouchPanPosition - */ - _computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition) { - if (this.panningSensibility !== 0 && previousMultiTouchPanPosition && multiTouchPanPosition) { - const moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x; - const moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y; - this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility; - this.camera.inertialPanningY += moveDeltaY / this.panningSensibility; - } - } - /** - * Move camera from pinch zoom distances. - * @param previousPinchSquaredDistance - * @param pinchSquaredDistance - */ - _computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance) { - const radius = this.camera.radius || ArcRotateCameraPointersInput.MinimumRadiusForPinch; - if (this.useNaturalPinchZoom) { - this.camera.radius = (radius * Math.sqrt(previousPinchSquaredDistance)) / Math.sqrt(pinchSquaredDistance); - } - else if (this.pinchDeltaPercentage) { - this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * radius * this.pinchDeltaPercentage; - } - else { - this.camera.inertialRadiusOffset += - (pinchSquaredDistance - previousPinchSquaredDistance) / - ((this.pinchPrecision * (this.pinchInwards ? 1 : -1) * (this.angularSensibilityX + this.angularSensibilityY)) / 2); - } - } - /** - * Called on pointer POINTERMOVE event if only a single touch is active. - * @param point - * @param offsetX - * @param offsetY - */ - onTouch(point, offsetX, offsetY) { - if (this.panningSensibility !== 0 && ((this._ctrlKey && this.camera._useCtrlForPanning) || this._isPanClick)) { - this.camera.inertialPanningX += -offsetX / this.panningSensibility; - this.camera.inertialPanningY += offsetY / this.panningSensibility; - } - else { - this.camera.inertialAlphaOffset -= offsetX / this.angularSensibilityX; - this.camera.inertialBetaOffset -= offsetY / this.angularSensibilityY; - } - } - /** - * Called on pointer POINTERDOUBLETAP event. - */ - onDoubleTap() { - if (this.camera.useInputToRestoreState) { - this.camera.restoreState(); - } - } - /** - * Called on pointer POINTERMOVE event if multiple touches are active. - * @param pointA - * @param pointB - * @param previousPinchSquaredDistance - * @param pinchSquaredDistance - * @param previousMultiTouchPanPosition - * @param multiTouchPanPosition - */ - onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { - if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) { - // First time this method is called for new pinch. - // Next time this is called there will be a - // previousPinchSquaredDistance and pinchSquaredDistance to compare. - return; - } - if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) { - // Last time this method is called at the end of a pinch. - return; - } - // Zoom and panning enabled together - if (this.multiTouchPanAndZoom) { - this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance); - this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition); - // Zoom and panning enabled but only one at a time - } - else if (this.multiTouchPanning && this.pinchZoom) { - this._twoFingerActivityCount++; - if (this._isPinching || - (this._twoFingerActivityCount < 20 && Math.abs(Math.sqrt(pinchSquaredDistance) - Math.sqrt(previousPinchSquaredDistance)) > this.camera.pinchToPanMaxDistance)) { - // Since pinch has not been active long, assume we intend to zoom. - this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance); - // Since we are pinching, remain pinching on next iteration. - this._isPinching = true; - } - else { - // Pause between pinch starting and moving implies not a zoom event. Pan instead. - this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition); - } - // Panning enabled, zoom disabled - } - else if (this.multiTouchPanning) { - this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition); - // Zoom enabled, panning disabled - } - else if (this.pinchZoom) { - this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance); - } - } - /** - * Called each time a new POINTERDOWN event occurs. Ie, for each button - * press. - * @param evt - */ - onButtonDown(evt) { - this._isPanClick = evt.button === this.camera._panningMouseButton; - } - /** - * Called each time a new POINTERUP event occurs. Ie, for each button - * release. - */ - onButtonUp() { - this._twoFingerActivityCount = 0; - this._isPinching = false; - } - /** - * Called when window becomes inactive. - */ - onLostFocus() { - this._isPanClick = false; - this._twoFingerActivityCount = 0; - this._isPinching = false; - } -} -/** - * The minimum radius used for pinch, to avoid radius lock at 0 - */ -ArcRotateCameraPointersInput.MinimumRadiusForPinch = 0.001; -__decorate([ - serialize() -], ArcRotateCameraPointersInput.prototype, "buttons", void 0); -__decorate([ - serialize() -], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0); -__decorate([ - serialize() -], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0); -__decorate([ - serialize() -], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0); -__decorate([ - serialize() -], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0); -__decorate([ - serialize() -], ArcRotateCameraPointersInput.prototype, "useNaturalPinchZoom", void 0); -__decorate([ - serialize() -], ArcRotateCameraPointersInput.prototype, "pinchZoom", void 0); -__decorate([ - serialize() -], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0); -__decorate([ - serialize() -], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0); -__decorate([ - serialize() -], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0); -CameraInputTypes.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput; -//# sourceMappingURL=arcRotateCameraPointersInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/arcRotateCameraInputsManager.js - - - - -/** - * Default Inputs manager for the ArcRotateCamera. - * It groups all the default supported inputs for ease of use. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class ArcRotateCameraInputsManager extends CameraInputsManager { - /** - * Instantiates a new ArcRotateCameraInputsManager. - * @param camera Defines the camera the inputs belong to - */ - constructor(camera) { - super(camera); - } - /** - * Add mouse wheel input support to the input manager. - * @returns the current input manager - */ - addMouseWheel() { - this.add(new ArcRotateCameraMouseWheelInput()); - return this; - } - /** - * Add pointers input support to the input manager. - * @returns the current input manager - */ - addPointers() { - this.add(new ArcRotateCameraPointersInput()); - return this; - } - /** - * Add keyboard input support to the input manager. - * @returns the current input manager - */ - addKeyboard() { - this.add(new ArcRotateCameraKeyboardMoveInput()); - return this; - } -} -//# sourceMappingURL=arcRotateCameraInputsManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.js - - - -/** - * Add orientation input support to the input manager. - * @returns the current input manager - */ -ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () { - this.add(new ArcRotateCameraVRDeviceOrientationInput()); - return this; -}; -/** - * Manage the device orientation inputs (gyroscope) to control an arc rotate camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class ArcRotateCameraVRDeviceOrientationInput { - /** - * Instantiate a new ArcRotateCameraVRDeviceOrientationInput. - */ - constructor() { - /** - * Defines a correction factor applied on the alpha value retrieved from the orientation events. - */ - this.alphaCorrection = 1; - /** - * Defines a correction factor applied on the gamma value retrieved from the orientation events. - */ - this.gammaCorrection = 1; - this._alpha = 0; - this._gamma = 0; - this._dirty = false; - this._deviceOrientationHandler = this._onOrientationEvent.bind(this); - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - this.camera.attachControl(noPreventDefault); - const hostWindow = this.camera.getScene().getEngine().getHostWindow(); - if (hostWindow) { - // check iOS 13+ support - if (typeof DeviceOrientationEvent !== "undefined" && typeof DeviceOrientationEvent.requestPermission === "function") { - DeviceOrientationEvent - .requestPermission() - .then((response) => { - if (response === "granted") { - hostWindow.addEventListener("deviceorientation", this._deviceOrientationHandler); - } - else { - tools_Tools.Warn("Permission not granted."); - } - }) - .catch((error) => { - tools_Tools.Error(error); - }); - } - else { - hostWindow.addEventListener("deviceorientation", this._deviceOrientationHandler); - } - } - } - /** - * @internal - */ - _onOrientationEvent(evt) { - if (evt.alpha !== null) { - this._alpha = (+evt.alpha | 0) * this.alphaCorrection; - } - if (evt.gamma !== null) { - this._gamma = (+evt.gamma | 0) * this.gammaCorrection; - } - this._dirty = true; - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - if (this._dirty) { - this._dirty = false; - if (this._gamma < 0) { - this._gamma = 180 + this._gamma; - } - this.camera.alpha = (((-this._alpha / 180.0) * Math.PI) % Math.PI) * 2; - this.camera.beta = (this._gamma / 180.0) * Math.PI; - } - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - window.removeEventListener("deviceorientation", this._deviceOrientationHandler); - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "ArcRotateCameraVRDeviceOrientationInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "VRDeviceOrientation"; - } -} -CameraInputTypes.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput; -//# sourceMappingURL=arcRotateCameraVRDeviceOrientationInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/flyCameraKeyboardInput.js - - - - - - -/** - * Listen to keyboard events to control the camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FlyCameraKeyboardInput { - constructor() { - /** - * The list of keyboard keys used to control the forward move of the camera. - */ - this.keysForward = [87]; - /** - * The list of keyboard keys used to control the backward move of the camera. - */ - this.keysBackward = [83]; - /** - * The list of keyboard keys used to control the forward move of the camera. - */ - this.keysUp = [69]; - /** - * The list of keyboard keys used to control the backward move of the camera. - */ - this.keysDown = [81]; - /** - * The list of keyboard keys used to control the right strafe move of the camera. - */ - this.keysRight = [68]; - /** - * The list of keyboard keys used to control the left strafe move of the camera. - */ - this.keysLeft = [65]; - this._keys = new Array(); - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - if (this._onCanvasBlurObserver) { - return; - } - 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((info) => { - const evt = info.event; - if (info.type === KeyboardEventTypes.KEYDOWN) { - if (this.keysForward.indexOf(evt.keyCode) !== -1 || - this.keysBackward.indexOf(evt.keyCode) !== -1 || - this.keysUp.indexOf(evt.keyCode) !== -1 || - this.keysDown.indexOf(evt.keyCode) !== -1 || - this.keysLeft.indexOf(evt.keyCode) !== -1 || - this.keysRight.indexOf(evt.keyCode) !== -1) { - const index = this._keys.indexOf(evt.keyCode); - if (index === -1) { - this._keys.push(evt.keyCode); - } - if (!noPreventDefault) { - evt.preventDefault(); - } - } - } - else { - if (this.keysForward.indexOf(evt.keyCode) !== -1 || - this.keysBackward.indexOf(evt.keyCode) !== -1 || - this.keysUp.indexOf(evt.keyCode) !== -1 || - this.keysDown.indexOf(evt.keyCode) !== -1 || - this.keysLeft.indexOf(evt.keyCode) !== -1 || - this.keysRight.indexOf(evt.keyCode) !== -1) { - const index = this._keys.indexOf(evt.keyCode); - if (index >= 0) { - this._keys.splice(index, 1); - } - if (!noPreventDefault) { - evt.preventDefault(); - } - } - } - }); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (this._scene) { - if (this._onKeyboardObserver) { - this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); - } - if (this._onCanvasBlurObserver) { - this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); - } - this._onKeyboardObserver = null; - this._onCanvasBlurObserver = null; - } - this._keys.length = 0; - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "FlyCameraKeyboardInput"; - } - /** - * @internal - */ - _onLostFocus() { - this._keys.length = 0; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "keyboard"; - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - if (this._onKeyboardObserver) { - const camera = this.camera; - // Keyboard - for (let index = 0; index < this._keys.length; index++) { - const keyCode = this._keys[index]; - const speed = camera._computeLocalCameraSpeed(); - if (this.keysForward.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, 0, speed); - } - else if (this.keysBackward.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, 0, -speed); - } - else if (this.keysUp.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, speed, 0); - } - else if (this.keysDown.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, -speed, 0); - } - else if (this.keysRight.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(speed, 0, 0); - } - else if (this.keysLeft.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(-speed, 0, 0); - } - if (camera.getScene().useRightHandedSystem) { - camera._localDirection.z *= -1; - } - camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); - math_vector_Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); - camera.cameraDirection.addInPlace(camera._transformedDirection); - } - } - } -} -__decorate([ - serialize() -], FlyCameraKeyboardInput.prototype, "keysForward", void 0); -__decorate([ - serialize() -], FlyCameraKeyboardInput.prototype, "keysBackward", void 0); -__decorate([ - serialize() -], FlyCameraKeyboardInput.prototype, "keysUp", void 0); -__decorate([ - serialize() -], FlyCameraKeyboardInput.prototype, "keysDown", void 0); -__decorate([ - serialize() -], FlyCameraKeyboardInput.prototype, "keysRight", void 0); -__decorate([ - serialize() -], FlyCameraKeyboardInput.prototype, "keysLeft", void 0); -CameraInputTypes.FlyCameraKeyboardInput = FlyCameraKeyboardInput; -//# sourceMappingURL=flyCameraKeyboardInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/flyCameraMouseInput.js - - - - - - - -/** - * Listen to mouse events to control the camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FlyCameraMouseInput { - /** - * Listen to mouse events to control the camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ - constructor() { - /** - * Defines the buttons associated with the input to handle camera rotation. - */ - this.buttons = [0, 1, 2]; - /** - * Assign buttons for Yaw control. - */ - this.buttonsYaw = [-1, 0, 1]; - /** - * Assign buttons for Pitch control. - */ - this.buttonsPitch = [-1, 0, 1]; - /** - * Assign buttons for Roll control. - */ - this.buttonsRoll = [2]; - /** - * Detect if any button is being pressed while mouse is moved. - * -1 = Mouse locked. - * 0 = Left button. - * 1 = Middle Button. - * 2 = Right Button. - */ - this.activeButton = -1; - /** - * Defines the pointer's angular sensibility, to control the camera rotation speed. - * Higher values reduce its sensitivity. - */ - this.angularSensibility = 1000.0; - this._previousPosition = null; - } - /** - * Attach the mouse control to the HTML DOM element. - * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). - */ - attachControl(noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - this._noPreventDefault = noPreventDefault; - this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver((p) => { - this._pointerInput(p); - }, pointerEvents_PointerEventTypes.POINTERDOWN | pointerEvents_PointerEventTypes.POINTERUP | pointerEvents_PointerEventTypes.POINTERMOVE); - // Correct Roll by rate, if enabled. - this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(() => { - if (this.camera.rollCorrect) { - this.camera.restoreRoll(this.camera.rollCorrect); - } - }); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (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 = undefined; - } - } - /** - * Gets the class name of the current input. - * @returns the class name. - */ - getClassName() { - return "FlyCameraMouseInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input's friendly name. - */ - getSimpleName() { - return "mouse"; - } - // Track mouse movement, when the pointer is not locked. - _pointerInput(p) { - const e = p.event; - const camera = this.camera; - const engine = camera.getEngine(); - if (engine.isInVRExclusivePointerMode) { - return; - } - if (!this.touchEnabled && e.pointerType === "touch") { - return; - } - // Mouse is moved but an unknown mouse button is pressed. - if (p.type !== pointerEvents_PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) { - return; - } - const srcElement = e.target; - // Mouse down. - if (p.type === pointerEvents_PointerEventTypes.POINTERDOWN) { - try { - srcElement === null || srcElement === void 0 ? void 0 : srcElement.setPointerCapture(e.pointerId); - } - catch (e) { - // Nothing to do with the error. Execution continues. - } - this._previousPosition = { - x: e.clientX, - y: e.clientY, - }; - this.activeButton = e.button; - if (!this._noPreventDefault) { - e.preventDefault(); - this._element.focus(); - } - // This is required to move while pointer button is down - if (engine.isPointerLock) { - this._onMouseMove(p.event); - } - } - // Mouse up. - else if (p.type === pointerEvents_PointerEventTypes.POINTERUP) { - try { - srcElement === null || srcElement === void 0 ? void 0 : srcElement.releasePointerCapture(e.pointerId); - } - catch (e) { - // Nothing to do with the error. Execution continues. - } - this.activeButton = -1; - this._previousPosition = null; - if (!this._noPreventDefault) { - e.preventDefault(); - } - } - // Mouse move. - else if (p.type === pointerEvents_PointerEventTypes.POINTERMOVE) { - if (!this._previousPosition) { - if (engine.isPointerLock) { - this._onMouseMove(p.event); - } - return; - } - const offsetX = e.clientX - this._previousPosition.x; - const offsetY = e.clientY - this._previousPosition.y; - this._rotateCamera(offsetX, offsetY); - this._previousPosition = { - x: e.clientX, - y: e.clientY, - }; - if (!this._noPreventDefault) { - e.preventDefault(); - } - } - } - // Track mouse movement, when pointer is locked. - _onMouseMove(e) { - const camera = this.camera; - const engine = camera.getEngine(); - if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) { - return; - } - const offsetX = e.movementX; - const offsetY = e.movementY; - this._rotateCamera(offsetX, offsetY); - this._previousPosition = null; - if (!this._noPreventDefault) { - e.preventDefault(); - } - } - /** - * Rotate camera by mouse offset. - * @param offsetX - * @param offsetY - */ - _rotateCamera(offsetX, offsetY) { - const camera = this.camera; - const scene = this.camera.getScene(); - if (scene.useRightHandedSystem) { - offsetX *= -1; - } - if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) { - offsetX *= -1; - } - const x = offsetX / this.angularSensibility; - const y = offsetY / this.angularSensibility; - // Initialize to current rotation. - const currentRotation = math_vector_Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z); - let rotationChange; - // Pitch. - if (this.buttonsPitch.some((v) => { - return v === this.activeButton; - })) { - // Apply change in Radians to vector Angle. - rotationChange = math_vector_Quaternion.RotationAxis(math_axis_Axis.X, y); - // Apply Pitch to quaternion. - currentRotation.multiplyInPlace(rotationChange); - } - // Yaw. - if (this.buttonsYaw.some((v) => { - return v === this.activeButton; - })) { - // Apply change in Radians to vector Angle. - rotationChange = math_vector_Quaternion.RotationAxis(math_axis_Axis.Y, x); - // Apply Yaw to quaternion. - currentRotation.multiplyInPlace(rotationChange); - // Add Roll, if banked turning is enabled, within Roll limit. - const limit = camera.bankedTurnLimit + camera._trackRoll; // Defaults to 90° plus manual roll. - if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) { - const bankingDelta = camera.bankedTurnMultiplier * -x; - // Apply change in Radians to vector Angle. - rotationChange = math_vector_Quaternion.RotationAxis(math_axis_Axis.Z, bankingDelta); - // Apply Yaw to quaternion. - currentRotation.multiplyInPlace(rotationChange); - } - } - // Roll. - if (this.buttonsRoll.some((v) => { - return v === this.activeButton; - })) { - // Apply change in Radians to vector Angle. - rotationChange = math_vector_Quaternion.RotationAxis(math_axis_Axis.Z, -x); - // Track Rolling. - camera._trackRoll -= x; - // Apply Pitch to quaternion. - currentRotation.multiplyInPlace(rotationChange); - } - // Apply rotationQuaternion to Euler camera.rotation. - currentRotation.toEulerAnglesToRef(camera.rotation); - } -} -__decorate([ - serialize() -], FlyCameraMouseInput.prototype, "buttons", void 0); -__decorate([ - serialize() -], FlyCameraMouseInput.prototype, "angularSensibility", void 0); -CameraInputTypes.FlyCameraMouseInput = FlyCameraMouseInput; -//# sourceMappingURL=flyCameraMouseInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/followCameraKeyboardMoveInput.js - - - - - -/** - * Manage the keyboard inputs to control the movement of a follow camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FollowCameraKeyboardMoveInput { - constructor() { - /** - * Defines the list of key codes associated with the up action (increase heightOffset) - */ - this.keysHeightOffsetIncr = [38]; - /** - * Defines the list of key codes associated with the down action (decrease heightOffset) - */ - this.keysHeightOffsetDecr = [40]; - /** - * Defines whether the Alt modifier key is required to move up/down (alter heightOffset) - */ - this.keysHeightOffsetModifierAlt = false; - /** - * Defines whether the Ctrl modifier key is required to move up/down (alter heightOffset) - */ - this.keysHeightOffsetModifierCtrl = false; - /** - * Defines whether the Shift modifier key is required to move up/down (alter heightOffset) - */ - this.keysHeightOffsetModifierShift = false; - /** - * Defines the list of key codes associated with the left action (increase rotationOffset) - */ - this.keysRotationOffsetIncr = [37]; - /** - * Defines the list of key codes associated with the right action (decrease rotationOffset) - */ - this.keysRotationOffsetDecr = [39]; - /** - * Defines whether the Alt modifier key is required to move left/right (alter rotationOffset) - */ - this.keysRotationOffsetModifierAlt = false; - /** - * Defines whether the Ctrl modifier key is required to move left/right (alter rotationOffset) - */ - this.keysRotationOffsetModifierCtrl = false; - /** - * Defines whether the Shift modifier key is required to move left/right (alter rotationOffset) - */ - this.keysRotationOffsetModifierShift = false; - /** - * Defines the list of key codes associated with the zoom-in action (decrease radius) - */ - this.keysRadiusIncr = [40]; - /** - * Defines the list of key codes associated with the zoom-out action (increase radius) - */ - this.keysRadiusDecr = [38]; - /** - * Defines whether the Alt modifier key is required to zoom in/out (alter radius value) - */ - this.keysRadiusModifierAlt = true; - /** - * Defines whether the Ctrl modifier key is required to zoom in/out (alter radius value) - */ - this.keysRadiusModifierCtrl = false; - /** - * Defines whether the Shift modifier key is required to zoom in/out (alter radius value) - */ - this.keysRadiusModifierShift = false; - /** - * Defines the rate of change of heightOffset. - */ - this.heightSensibility = 1; - /** - * Defines the rate of change of rotationOffset. - */ - this.rotationSensibility = 1; - /** - * Defines the rate of change of radius. - */ - this.radiusSensibility = 1; - this._keys = new Array(); - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - if (this._onCanvasBlurObserver) { - return; - } - 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((info) => { - const evt = info.event; - if (!evt.metaKey) { - if (info.type === KeyboardEventTypes.KEYDOWN) { - this._ctrlPressed = evt.ctrlKey; - this._altPressed = evt.altKey; - this._shiftPressed = evt.shiftKey; - if (this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || - this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || - this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || - this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || - this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || - this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) { - const index = this._keys.indexOf(evt.keyCode); - if (index === -1) { - this._keys.push(evt.keyCode); - } - if (evt.preventDefault) { - if (!noPreventDefault) { - evt.preventDefault(); - } - } - } - } - else { - if (this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || - this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || - this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || - this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || - this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || - this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) { - const index = this._keys.indexOf(evt.keyCode); - if (index >= 0) { - this._keys.splice(index, 1); - } - if (evt.preventDefault) { - if (!noPreventDefault) { - evt.preventDefault(); - } - } - } - } - } - }); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (this._scene) { - if (this._onKeyboardObserver) { - this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); - } - if (this._onCanvasBlurObserver) { - this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); - } - this._onKeyboardObserver = null; - this._onCanvasBlurObserver = null; - } - this._keys.length = 0; - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - if (this._onKeyboardObserver) { - this._keys.forEach((keyCode) => { - if (this.keysHeightOffsetIncr.indexOf(keyCode) !== -1 && this._modifierHeightOffset()) { - this.camera.heightOffset += this.heightSensibility; - } - else if (this.keysHeightOffsetDecr.indexOf(keyCode) !== -1 && this._modifierHeightOffset()) { - this.camera.heightOffset -= this.heightSensibility; - } - else if (this.keysRotationOffsetIncr.indexOf(keyCode) !== -1 && this._modifierRotationOffset()) { - this.camera.rotationOffset += this.rotationSensibility; - this.camera.rotationOffset %= 360; - } - else if (this.keysRotationOffsetDecr.indexOf(keyCode) !== -1 && this._modifierRotationOffset()) { - this.camera.rotationOffset -= this.rotationSensibility; - this.camera.rotationOffset %= 360; - } - else if (this.keysRadiusIncr.indexOf(keyCode) !== -1 && this._modifierRadius()) { - this.camera.radius += this.radiusSensibility; - } - else if (this.keysRadiusDecr.indexOf(keyCode) !== -1 && this._modifierRadius()) { - this.camera.radius -= this.radiusSensibility; - } - }); - } - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "FollowCameraKeyboardMoveInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "keyboard"; - } - /** - * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to - * allow modification of the heightOffset value. - */ - _modifierHeightOffset() { - return (this.keysHeightOffsetModifierAlt === this._altPressed && - this.keysHeightOffsetModifierCtrl === this._ctrlPressed && - this.keysHeightOffsetModifierShift === this._shiftPressed); - } - /** - * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to - * allow modification of the rotationOffset value. - */ - _modifierRotationOffset() { - return (this.keysRotationOffsetModifierAlt === this._altPressed && - this.keysRotationOffsetModifierCtrl === this._ctrlPressed && - this.keysRotationOffsetModifierShift === this._shiftPressed); - } - /** - * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to - * allow modification of the radius value. - */ - _modifierRadius() { - return this.keysRadiusModifierAlt === this._altPressed && this.keysRadiusModifierCtrl === this._ctrlPressed && this.keysRadiusModifierShift === this._shiftPressed; - } -} -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetIncr", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetDecr", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierAlt", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierCtrl", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierShift", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetIncr", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetDecr", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierAlt", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierCtrl", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierShift", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysRadiusIncr", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysRadiusDecr", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierAlt", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierCtrl", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierShift", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "heightSensibility", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "rotationSensibility", void 0); -__decorate([ - serialize() -], FollowCameraKeyboardMoveInput.prototype, "radiusSensibility", void 0); -CameraInputTypes.FollowCameraKeyboardMoveInput = FollowCameraKeyboardMoveInput; -//# sourceMappingURL=followCameraKeyboardMoveInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/followCameraMouseWheelInput.js - - - - - -/** - * Manage the mouse wheel inputs to control a follow camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FollowCameraMouseWheelInput { - constructor() { - /** - * Moue wheel controls zoom. (Mouse wheel modifies camera.radius value.) - */ - this.axisControlRadius = true; - /** - * Moue wheel controls height. (Mouse wheel modifies camera.heightOffset value.) - */ - this.axisControlHeight = false; - /** - * Moue wheel controls angle. (Mouse wheel modifies camera.rotationOffset value.) - */ - this.axisControlRotation = false; - /** - * Gets or Set the mouse wheel precision or how fast is the camera moves in - * relation to mouseWheel events. - */ - this.wheelPrecision = 3.0; - /** - * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0. - * It defines the percentage of current camera.radius to use as delta when wheel is used. - */ - this.wheelDeltaPercentage = 0; - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - this._wheel = (p) => { - // sanity check - this should be a PointerWheel event. - if (p.type !== pointerEvents_PointerEventTypes.POINTERWHEEL) { - return; - } - const event = p.event; - let delta = 0; - const wheelDelta = Math.max(-1, Math.min(1, event.deltaY)); - if (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); - if (this.axisControlRadius) { - delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.radius; - } - else if (this.axisControlHeight) { - delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.heightOffset; - } - else if (this.axisControlRotation) { - delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.rotationOffset; - } - } - else { - delta = wheelDelta * this.wheelPrecision; - } - if (delta) { - if (this.axisControlRadius) { - this.camera.radius += delta; - } - else if (this.axisControlHeight) { - this.camera.heightOffset -= delta; - } - else if (this.axisControlRotation) { - this.camera.rotationOffset -= delta; - } - } - if (event.preventDefault) { - if (!noPreventDefault) { - event.preventDefault(); - } - } - }; - this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, pointerEvents_PointerEventTypes.POINTERWHEEL); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (this._observer) { - this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); - this._observer = null; - this._wheel = null; - } - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "ArcRotateCameraMouseWheelInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "mousewheel"; - } -} -__decorate([ - serialize() -], FollowCameraMouseWheelInput.prototype, "axisControlRadius", void 0); -__decorate([ - serialize() -], FollowCameraMouseWheelInput.prototype, "axisControlHeight", void 0); -__decorate([ - serialize() -], FollowCameraMouseWheelInput.prototype, "axisControlRotation", void 0); -__decorate([ - serialize() -], FollowCameraMouseWheelInput.prototype, "wheelPrecision", void 0); -__decorate([ - serialize() -], FollowCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0); -CameraInputTypes.FollowCameraMouseWheelInput = FollowCameraMouseWheelInput; -//# sourceMappingURL=followCameraMouseWheelInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/followCameraPointersInput.js - - - - -/** - * Manage the pointers inputs to control an follow camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FollowCameraPointersInput extends BaseCameraPointersInput { - constructor() { - super(...arguments); - /** - * Defines the pointer angular sensibility along the X axis or how fast is - * the camera rotating. - * A negative number will reverse the axis direction. - */ - this.angularSensibilityX = 1; - /** - * Defines the pointer angular sensibility along the Y axis or how fast is - * the camera rotating. - * A negative number will reverse the axis direction. - */ - this.angularSensibilityY = 1; - /** - * Defines the pointer pinch precision or how fast is the camera zooming. - * A negative number will reverse the axis direction. - */ - this.pinchPrecision = 10000.0; - /** - * pinchDeltaPercentage will be used instead of pinchPrecision if different - * from 0. - * It defines the percentage of current camera.radius to use as delta when - * pinch zoom is used. - */ - this.pinchDeltaPercentage = 0; - /** - * Pointer X axis controls zoom. (X axis modifies camera.radius value.) - */ - this.axisXControlRadius = false; - /** - * Pointer X axis controls height. (X axis modifies camera.heightOffset value.) - */ - this.axisXControlHeight = false; - /** - * Pointer X axis controls angle. (X axis modifies camera.rotationOffset value.) - */ - this.axisXControlRotation = true; - /** - * Pointer Y axis controls zoom. (Y axis modifies camera.radius value.) - */ - this.axisYControlRadius = false; - /** - * Pointer Y axis controls height. (Y axis modifies camera.heightOffset value.) - */ - this.axisYControlHeight = true; - /** - * Pointer Y axis controls angle. (Y axis modifies camera.rotationOffset value.) - */ - this.axisYControlRotation = false; - /** - * Pinch controls zoom. (Pinch modifies camera.radius value.) - */ - this.axisPinchControlRadius = true; - /** - * Pinch controls height. (Pinch modifies camera.heightOffset value.) - */ - this.axisPinchControlHeight = false; - /** - * Pinch controls angle. (Pinch modifies camera.rotationOffset value.) - */ - this.axisPinchControlRotation = false; - /** - * Log error messages if basic misconfiguration has occurred. - */ - this.warningEnable = true; - /* Check for obvious misconfiguration. */ - this._warningCounter = 0; - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "FollowCameraPointersInput"; - } - onTouch(pointA, offsetX, offsetY) { - this._warning(); - if (this.axisXControlRotation) { - this.camera.rotationOffset += offsetX / this.angularSensibilityX; - } - else if (this.axisYControlRotation) { - this.camera.rotationOffset += offsetY / this.angularSensibilityX; - } - if (this.axisXControlHeight) { - this.camera.heightOffset += offsetX / this.angularSensibilityY; - } - else if (this.axisYControlHeight) { - this.camera.heightOffset += offsetY / this.angularSensibilityY; - } - if (this.axisXControlRadius) { - this.camera.radius -= offsetX / this.angularSensibilityY; - } - else if (this.axisYControlRadius) { - this.camera.radius -= offsetY / this.angularSensibilityY; - } - } - onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { - if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) { - // First time this method is called for new pinch. - // Next time this is called there will be a - // previousPinchSquaredDistance and pinchSquaredDistance to compare. - return; - } - if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) { - // Last time this method is called at the end of a pinch. - return; - } - let pinchDelta = (pinchSquaredDistance - previousPinchSquaredDistance) / ((this.pinchPrecision * (this.angularSensibilityX + this.angularSensibilityY)) / 2); - if (this.pinchDeltaPercentage) { - pinchDelta *= 0.01 * this.pinchDeltaPercentage; - if (this.axisPinchControlRotation) { - this.camera.rotationOffset += pinchDelta * this.camera.rotationOffset; - } - if (this.axisPinchControlHeight) { - this.camera.heightOffset += pinchDelta * this.camera.heightOffset; - } - if (this.axisPinchControlRadius) { - this.camera.radius -= pinchDelta * this.camera.radius; - } - } - else { - if (this.axisPinchControlRotation) { - this.camera.rotationOffset += pinchDelta; - } - if (this.axisPinchControlHeight) { - this.camera.heightOffset += pinchDelta; - } - if (this.axisPinchControlRadius) { - this.camera.radius -= pinchDelta; - } - } - } - _warning() { - if (!this.warningEnable || this._warningCounter++ % 100 !== 0) { - return; - } - 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: "; - console.assert(this.axisXControlRotation + this.axisXControlHeight + this.axisXControlRadius <= 1, warn + "axisXControlRotation: " + this.axisXControlRotation + ", axisXControlHeight: " + this.axisXControlHeight + ", axisXControlRadius: " + this.axisXControlRadius); - console.assert(this.axisYControlRotation + this.axisYControlHeight + this.axisYControlRadius <= 1, warn + "axisYControlRotation: " + this.axisYControlRotation + ", axisYControlHeight: " + this.axisYControlHeight + ", axisYControlRadius: " + this.axisYControlRadius); - console.assert(this.axisPinchControlRotation + this.axisPinchControlHeight + this.axisPinchControlRadius <= 1, warn + - "axisPinchControlRotation: " + - this.axisPinchControlRotation + - ", axisPinchControlHeight: " + - this.axisPinchControlHeight + - ", axisPinchControlRadius: " + - this.axisPinchControlRadius); - } -} -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "angularSensibilityX", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "angularSensibilityY", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "pinchPrecision", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "pinchDeltaPercentage", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "axisXControlRadius", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "axisXControlHeight", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "axisXControlRotation", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "axisYControlRadius", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "axisYControlHeight", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "axisYControlRotation", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "axisPinchControlRadius", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "axisPinchControlHeight", void 0); -__decorate([ - serialize() -], FollowCameraPointersInput.prototype, "axisPinchControlRotation", void 0); -CameraInputTypes.FollowCameraPointersInput = FollowCameraPointersInput; -//# sourceMappingURL=followCameraPointersInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraKeyboardMoveInput.js - - - - - - -/** - * Manage the keyboard inputs to control the movement of a free camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FreeCameraKeyboardMoveInput { - constructor() { - /** - * Gets or Set the list of keyboard keys used to control the forward move of the camera. - */ - this.keysUp = [38]; - /** - * Gets or Set the list of keyboard keys used to control the upward move of the camera. - */ - this.keysUpward = [33]; - /** - * Gets or Set the list of keyboard keys used to control the backward move of the camera. - */ - this.keysDown = [40]; - /** - * Gets or Set the list of keyboard keys used to control the downward move of the camera. - */ - this.keysDownward = [34]; - /** - * Gets or Set the list of keyboard keys used to control the left strafe move of the camera. - */ - this.keysLeft = [37]; - /** - * Gets or Set the list of keyboard keys used to control the right strafe move of the camera. - */ - this.keysRight = [39]; - /** - * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating. - */ - this.rotationSpeed = 0.5; - /** - * Gets or Set the list of keyboard keys used to control the left rotation move of the camera. - */ - this.keysRotateLeft = []; - /** - * Gets or Set the list of keyboard keys used to control the right rotation move of the camera. - */ - this.keysRotateRight = []; - /** - * Gets or Set the list of keyboard keys used to control the up rotation move of the camera. - */ - this.keysRotateUp = []; - /** - * Gets or Set the list of keyboard keys used to control the down rotation move of the camera. - */ - this.keysRotateDown = []; - this._keys = new Array(); - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - if (this._onCanvasBlurObserver) { - return; - } - 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((info) => { - const evt = info.event; - if (!evt.metaKey) { - if (info.type === KeyboardEventTypes.KEYDOWN) { - if (this.keysUp.indexOf(evt.keyCode) !== -1 || - this.keysDown.indexOf(evt.keyCode) !== -1 || - this.keysLeft.indexOf(evt.keyCode) !== -1 || - this.keysRight.indexOf(evt.keyCode) !== -1 || - this.keysUpward.indexOf(evt.keyCode) !== -1 || - this.keysDownward.indexOf(evt.keyCode) !== -1 || - this.keysRotateLeft.indexOf(evt.keyCode) !== -1 || - this.keysRotateRight.indexOf(evt.keyCode) !== -1 || - this.keysRotateUp.indexOf(evt.keyCode) !== -1 || - this.keysRotateDown.indexOf(evt.keyCode) !== -1) { - const index = this._keys.indexOf(evt.keyCode); - if (index === -1) { - this._keys.push(evt.keyCode); - } - if (!noPreventDefault) { - evt.preventDefault(); - } - } - } - else { - if (this.keysUp.indexOf(evt.keyCode) !== -1 || - this.keysDown.indexOf(evt.keyCode) !== -1 || - this.keysLeft.indexOf(evt.keyCode) !== -1 || - this.keysRight.indexOf(evt.keyCode) !== -1 || - this.keysUpward.indexOf(evt.keyCode) !== -1 || - this.keysDownward.indexOf(evt.keyCode) !== -1 || - this.keysRotateLeft.indexOf(evt.keyCode) !== -1 || - this.keysRotateRight.indexOf(evt.keyCode) !== -1 || - this.keysRotateUp.indexOf(evt.keyCode) !== -1 || - this.keysRotateDown.indexOf(evt.keyCode) !== -1) { - const index = this._keys.indexOf(evt.keyCode); - if (index >= 0) { - this._keys.splice(index, 1); - } - if (!noPreventDefault) { - evt.preventDefault(); - } - } - } - } - }); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (this._scene) { - if (this._onKeyboardObserver) { - this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); - } - if (this._onCanvasBlurObserver) { - this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); - } - this._onKeyboardObserver = null; - this._onCanvasBlurObserver = null; - } - this._keys.length = 0; - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - if (this._onKeyboardObserver) { - const camera = this.camera; - // Keyboard - for (let index = 0; index < this._keys.length; index++) { - const keyCode = this._keys[index]; - const speed = camera._computeLocalCameraSpeed(); - if (this.keysLeft.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(-speed, 0, 0); - } - else if (this.keysUp.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, 0, speed); - } - else if (this.keysRight.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(speed, 0, 0); - } - else if (this.keysDown.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, 0, -speed); - } - else if (this.keysUpward.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, speed, 0); - } - else if (this.keysDownward.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, -speed, 0); - } - else if (this.keysRotateLeft.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, 0, 0); - camera.cameraRotation.y -= this._getLocalRotation(); - } - else if (this.keysRotateRight.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, 0, 0); - camera.cameraRotation.y += this._getLocalRotation(); - } - else if (this.keysRotateUp.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, 0, 0); - camera.cameraRotation.x -= this._getLocalRotation(); - } - else if (this.keysRotateDown.indexOf(keyCode) !== -1) { - camera._localDirection.copyFromFloats(0, 0, 0); - camera.cameraRotation.x += this._getLocalRotation(); - } - if (camera.getScene().useRightHandedSystem) { - camera._localDirection.z *= -1; - } - camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); - math_vector_Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); - camera.cameraDirection.addInPlace(camera._transformedDirection); - } - } - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "FreeCameraKeyboardMoveInput"; - } - /** @internal */ - _onLostFocus() { - this._keys.length = 0; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "keyboard"; - } - _getLocalRotation() { - let rotation = (this.rotationSpeed * this._engine.getDeltaTime()) / 1000; - if (this.camera.getScene().useRightHandedSystem) { - rotation *= -1; - } - if (this.camera.parent && this.camera.parent._getWorldMatrixDeterminant() < 0) { - rotation *= -1; - } - return rotation; - } -} -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0); -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "keysUpward", void 0); -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0); -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "keysDownward", void 0); -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0); -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0); -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "rotationSpeed", void 0); -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "keysRotateLeft", void 0); -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "keysRotateRight", void 0); -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "keysRotateUp", void 0); -__decorate([ - serialize() -], FreeCameraKeyboardMoveInput.prototype, "keysRotateDown", void 0); -CameraInputTypes.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput; -//# sourceMappingURL=freeCameraKeyboardMoveInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraMouseInput.js - - - - - - -/** - * Manage the mouse inputs to control the movement of a free camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FreeCameraMouseInput { - /** - * Manage the mouse inputs to control the movement of a free camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - * @param touchEnabled Defines if touch is enabled or not - */ - constructor( - /** - * Define if touch is enabled in the mouse input - */ - touchEnabled = true) { - this.touchEnabled = touchEnabled; - /** - * Defines the buttons associated with the input to handle camera move. - */ - this.buttons = [0, 1, 2]; - /** - * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating. - */ - this.angularSensibility = 2000.0; - this._previousPosition = null; - /** - * Observable for when a pointer move event occurs containing the move offset - */ - this.onPointerMovedObservable = new observable_Observable(); - /** - * @internal - * If the camera should be rotated automatically based on pointer movement - */ - this._allowCameraRotation = true; - this._currentActiveButton = -1; - this._activePointerId = -1; - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - const engine = this.camera.getEngine(); - const element = engine.getInputElement(); - if (!this._pointerInput) { - this._pointerInput = (p) => { - const evt = p.event; - const isTouch = evt.pointerType === "touch"; - if (engine.isInVRExclusivePointerMode) { - return; - } - if (!this.touchEnabled && isTouch) { - return; - } - if (p.type !== pointerEvents_PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) { - return; - } - const srcElement = evt.target; - if (p.type === pointerEvents_PointerEventTypes.POINTERDOWN) { - // If the input is touch with more than one touch OR if the input is mouse and there is already an active button, return - if ((isTouch && this._activePointerId !== -1) || (!isTouch && this._currentActiveButton !== -1)) { - return; - } - this._activePointerId = evt.pointerId; - try { - srcElement === null || srcElement === void 0 ? void 0 : srcElement.setPointerCapture(evt.pointerId); - } - catch (e) { - //Nothing to do with the error. Execution will continue. - } - if (this._currentActiveButton === -1) { - this._currentActiveButton = evt.button; - } - this._previousPosition = { - x: evt.clientX, - y: evt.clientY, - }; - if (!noPreventDefault) { - evt.preventDefault(); - element && element.focus(); - } - // This is required to move while pointer button is down - if (engine.isPointerLock && this._onMouseMove) { - this._onMouseMove(p.event); - } - } - else if (p.type === pointerEvents_PointerEventTypes.POINTERUP) { - // If input is touch with a different touch id OR if input is mouse with a different button, return - if ((isTouch && this._activePointerId !== evt.pointerId) || (!isTouch && this._currentActiveButton !== evt.button)) { - return; - } - try { - srcElement === null || srcElement === void 0 ? void 0 : srcElement.releasePointerCapture(evt.pointerId); - } - catch (e) { - //Nothing to do with the error. - } - this._currentActiveButton = -1; - this._previousPosition = null; - if (!noPreventDefault) { - evt.preventDefault(); - } - this._activePointerId = -1; - } - else if (p.type === pointerEvents_PointerEventTypes.POINTERMOVE && (this._activePointerId === evt.pointerId || !isTouch)) { - if (engine.isPointerLock && this._onMouseMove) { - this._onMouseMove(p.event); - } - else if (this._previousPosition) { - let offsetX = evt.clientX - this._previousPosition.x; - const offsetY = evt.clientY - this._previousPosition.y; - if (this.camera.getScene().useRightHandedSystem) { - offsetX *= -1; - } - if (this.camera.parent && this.camera.parent._getWorldMatrixDeterminant() < 0) { - offsetX *= -1; - } - if (this._allowCameraRotation) { - this.camera.cameraRotation.y += offsetX / this.angularSensibility; - this.camera.cameraRotation.x += offsetY / this.angularSensibility; - } - this.onPointerMovedObservable.notifyObservers({ offsetX: offsetX, offsetY: offsetY }); - this._previousPosition = { - x: evt.clientX, - y: evt.clientY, - }; - if (!noPreventDefault) { - evt.preventDefault(); - } - } - } - }; - } - this._onMouseMove = (evt) => { - if (!engine.isPointerLock) { - return; - } - if (engine.isInVRExclusivePointerMode) { - return; - } - let offsetX = evt.movementX; - if (this.camera.getScene().useRightHandedSystem) { - offsetX *= -1; - } - if (this.camera.parent && this.camera.parent._getWorldMatrixDeterminant() < 0) { - offsetX *= -1; - } - this.camera.cameraRotation.y += offsetX / this.angularSensibility; - const offsetY = evt.movementY; - this.camera.cameraRotation.x += offsetY / this.angularSensibility; - this._previousPosition = null; - if (!noPreventDefault) { - evt.preventDefault(); - } - }; - this._observer = this.camera - .getScene() - ._inputManager._addCameraPointerObserver(this._pointerInput, pointerEvents_PointerEventTypes.POINTERDOWN | pointerEvents_PointerEventTypes.POINTERUP | pointerEvents_PointerEventTypes.POINTERMOVE); - if (element) { - this._contextMenuBind = this.onContextMenu.bind(this); - element.addEventListener("contextmenu", this._contextMenuBind, false); // TODO: We need to figure out how to handle this for Native - } - } - /** - * Called on JS contextmenu event. - * Override this method to provide functionality. - * @param evt - */ - onContextMenu(evt) { - evt.preventDefault(); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (this._observer) { - this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); - if (this._contextMenuBind) { - const engine = this.camera.getEngine(); - const element = engine.getInputElement(); - element && element.removeEventListener("contextmenu", this._contextMenuBind); - } - if (this.onPointerMovedObservable) { - this.onPointerMovedObservable.clear(); - } - this._observer = null; - this._onMouseMove = null; - this._previousPosition = null; - } - this._activePointerId = -1; - this._currentActiveButton = -1; - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "FreeCameraMouseInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "mouse"; - } -} -__decorate([ - serialize() -], FreeCameraMouseInput.prototype, "buttons", void 0); -__decorate([ - serialize() -], FreeCameraMouseInput.prototype, "angularSensibility", void 0); -CameraInputTypes.FreeCameraMouseInput = FreeCameraMouseInput; -//# sourceMappingURL=freeCameraMouseInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraMouseWheelInput.js - - - - - - -// eslint-disable-next-line @typescript-eslint/naming-convention -var _CameraProperty; -(function (_CameraProperty) { - _CameraProperty[_CameraProperty["MoveRelative"] = 0] = "MoveRelative"; - _CameraProperty[_CameraProperty["RotateRelative"] = 1] = "RotateRelative"; - _CameraProperty[_CameraProperty["MoveScene"] = 2] = "MoveScene"; -})(_CameraProperty || (_CameraProperty = {})); -/** - * Manage the mouse wheel inputs to control a free camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FreeCameraMouseWheelInput extends BaseCameraMouseWheelInput { - constructor() { - super(...arguments); - this._moveRelative = math_vector_Vector3.Zero(); - this._rotateRelative = math_vector_Vector3.Zero(); - this._moveScene = math_vector_Vector3.Zero(); - /** - * These are set to the desired default behaviour. - */ - this._wheelXAction = _CameraProperty.MoveRelative; - this._wheelXActionCoordinate = Coordinate.X; - this._wheelYAction = _CameraProperty.MoveRelative; - this._wheelYActionCoordinate = Coordinate.Z; - this._wheelZAction = null; - this._wheelZActionCoordinate = null; - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "FreeCameraMouseWheelInput"; - } - /** - * Set which movement axis (relative to camera's orientation) the mouse - * wheel's X axis controls. - * @param axis The axis to be moved. Set null to clear. - */ - set wheelXMoveRelative(axis) { - if (axis === null && this._wheelXAction !== _CameraProperty.MoveRelative) { - // Attempting to clear different _wheelXAction. - return; - } - this._wheelXAction = _CameraProperty.MoveRelative; - this._wheelXActionCoordinate = axis; - } - /** - * Get the configured movement axis (relative to camera's orientation) the - * mouse wheel's X axis controls. - * @returns The configured axis or null if none. - */ - get wheelXMoveRelative() { - if (this._wheelXAction !== _CameraProperty.MoveRelative) { - return null; - } - return this._wheelXActionCoordinate; - } - /** - * Set which movement axis (relative to camera's orientation) the mouse - * wheel's Y axis controls. - * @param axis The axis to be moved. Set null to clear. - */ - set wheelYMoveRelative(axis) { - if (axis === null && this._wheelYAction !== _CameraProperty.MoveRelative) { - // Attempting to clear different _wheelYAction. - return; - } - this._wheelYAction = _CameraProperty.MoveRelative; - this._wheelYActionCoordinate = axis; - } - /** - * Get the configured movement axis (relative to camera's orientation) the - * mouse wheel's Y axis controls. - * @returns The configured axis or null if none. - */ - get wheelYMoveRelative() { - if (this._wheelYAction !== _CameraProperty.MoveRelative) { - return null; - } - return this._wheelYActionCoordinate; - } - /** - * Set which movement axis (relative to camera's orientation) the mouse - * wheel's Z axis controls. - * @param axis The axis to be moved. Set null to clear. - */ - set wheelZMoveRelative(axis) { - if (axis === null && this._wheelZAction !== _CameraProperty.MoveRelative) { - // Attempting to clear different _wheelZAction. - return; - } - this._wheelZAction = _CameraProperty.MoveRelative; - this._wheelZActionCoordinate = axis; - } - /** - * Get the configured movement axis (relative to camera's orientation) the - * mouse wheel's Z axis controls. - * @returns The configured axis or null if none. - */ - get wheelZMoveRelative() { - if (this._wheelZAction !== _CameraProperty.MoveRelative) { - return null; - } - return this._wheelZActionCoordinate; - } - /** - * Set which rotation axis (relative to camera's orientation) the mouse - * wheel's X axis controls. - * @param axis The axis to be moved. Set null to clear. - */ - set wheelXRotateRelative(axis) { - if (axis === null && this._wheelXAction !== _CameraProperty.RotateRelative) { - // Attempting to clear different _wheelXAction. - return; - } - this._wheelXAction = _CameraProperty.RotateRelative; - this._wheelXActionCoordinate = axis; - } - /** - * Get the configured rotation axis (relative to camera's orientation) the - * mouse wheel's X axis controls. - * @returns The configured axis or null if none. - */ - get wheelXRotateRelative() { - if (this._wheelXAction !== _CameraProperty.RotateRelative) { - return null; - } - return this._wheelXActionCoordinate; - } - /** - * Set which rotation axis (relative to camera's orientation) the mouse - * wheel's Y axis controls. - * @param axis The axis to be moved. Set null to clear. - */ - set wheelYRotateRelative(axis) { - if (axis === null && this._wheelYAction !== _CameraProperty.RotateRelative) { - // Attempting to clear different _wheelYAction. - return; - } - this._wheelYAction = _CameraProperty.RotateRelative; - this._wheelYActionCoordinate = axis; - } - /** - * Get the configured rotation axis (relative to camera's orientation) the - * mouse wheel's Y axis controls. - * @returns The configured axis or null if none. - */ - get wheelYRotateRelative() { - if (this._wheelYAction !== _CameraProperty.RotateRelative) { - return null; - } - return this._wheelYActionCoordinate; - } - /** - * Set which rotation axis (relative to camera's orientation) the mouse - * wheel's Z axis controls. - * @param axis The axis to be moved. Set null to clear. - */ - set wheelZRotateRelative(axis) { - if (axis === null && this._wheelZAction !== _CameraProperty.RotateRelative) { - // Attempting to clear different _wheelZAction. - return; - } - this._wheelZAction = _CameraProperty.RotateRelative; - this._wheelZActionCoordinate = axis; - } - /** - * Get the configured rotation axis (relative to camera's orientation) the - * mouse wheel's Z axis controls. - * @returns The configured axis or null if none. - */ - get wheelZRotateRelative() { - if (this._wheelZAction !== _CameraProperty.RotateRelative) { - return null; - } - return this._wheelZActionCoordinate; - } - /** - * Set which movement axis (relative to the scene) the mouse wheel's X axis - * controls. - * @param axis The axis to be moved. Set null to clear. - */ - set wheelXMoveScene(axis) { - if (axis === null && this._wheelXAction !== _CameraProperty.MoveScene) { - // Attempting to clear different _wheelXAction. - return; - } - this._wheelXAction = _CameraProperty.MoveScene; - this._wheelXActionCoordinate = axis; - } - /** - * Get the configured movement axis (relative to the scene) the mouse wheel's - * X axis controls. - * @returns The configured axis or null if none. - */ - get wheelXMoveScene() { - if (this._wheelXAction !== _CameraProperty.MoveScene) { - return null; - } - return this._wheelXActionCoordinate; - } - /** - * Set which movement axis (relative to the scene) the mouse wheel's Y axis - * controls. - * @param axis The axis to be moved. Set null to clear. - */ - set wheelYMoveScene(axis) { - if (axis === null && this._wheelYAction !== _CameraProperty.MoveScene) { - // Attempting to clear different _wheelYAction. - return; - } - this._wheelYAction = _CameraProperty.MoveScene; - this._wheelYActionCoordinate = axis; - } - /** - * Get the configured movement axis (relative to the scene) the mouse wheel's - * Y axis controls. - * @returns The configured axis or null if none. - */ - get wheelYMoveScene() { - if (this._wheelYAction !== _CameraProperty.MoveScene) { - return null; - } - return this._wheelYActionCoordinate; - } - /** - * Set which movement axis (relative to the scene) the mouse wheel's Z axis - * controls. - * @param axis The axis to be moved. Set null to clear. - */ - set wheelZMoveScene(axis) { - if (axis === null && this._wheelZAction !== _CameraProperty.MoveScene) { - // Attempting to clear different _wheelZAction. - return; - } - this._wheelZAction = _CameraProperty.MoveScene; - this._wheelZActionCoordinate = axis; - } - /** - * Get the configured movement axis (relative to the scene) the mouse wheel's - * Z axis controls. - * @returns The configured axis or null if none. - */ - get wheelZMoveScene() { - if (this._wheelZAction !== _CameraProperty.MoveScene) { - return null; - } - return this._wheelZActionCoordinate; - } - /** - * Called for each rendered frame. - */ - checkInputs() { - if (this._wheelDeltaX === 0 && this._wheelDeltaY === 0 && this._wheelDeltaZ == 0) { - return; - } - // Clear the camera properties that we might be updating. - this._moveRelative.setAll(0); - this._rotateRelative.setAll(0); - this._moveScene.setAll(0); - // Set the camera properties that are to be updated. - this._updateCamera(); - if (this.camera.getScene().useRightHandedSystem) { - // TODO: Does this need done for worldUpdate too? - this._moveRelative.z *= -1; - } - // Convert updates relative to camera to world position update. - const cameraTransformMatrix = math_vector_Matrix.Zero(); - this.camera.getViewMatrix().invertToRef(cameraTransformMatrix); - const transformedDirection = math_vector_Vector3.Zero(); - math_vector_Vector3.TransformNormalToRef(this._moveRelative, cameraTransformMatrix, transformedDirection); - // Apply updates to camera position. - this.camera.cameraRotation.x += this._rotateRelative.x / 200; - this.camera.cameraRotation.y += this._rotateRelative.y / 200; - this.camera.cameraDirection.addInPlace(transformedDirection); - this.camera.cameraDirection.addInPlace(this._moveScene); - // Call the base class implementation to handle observers and do cleanup. - super.checkInputs(); - } - /** - * Update the camera according to any configured properties for the 3 - * mouse-wheel axis. - */ - _updateCamera() { - // Do the camera updates for each of the 3 touch-wheel axis. - this._updateCameraProperty(this._wheelDeltaX, this._wheelXAction, this._wheelXActionCoordinate); - this._updateCameraProperty(this._wheelDeltaY, this._wheelYAction, this._wheelYActionCoordinate); - this._updateCameraProperty(this._wheelDeltaZ, this._wheelZAction, this._wheelZActionCoordinate); - } - /** - * Update one property of the camera. - * @param value - * @param cameraProperty - * @param coordinate - */ - _updateCameraProperty( - /* Mouse-wheel delta. */ - value, - /* Camera property to be changed. */ - cameraProperty, - /* Axis of Camera property to be changed. */ - coordinate) { - if (value === 0) { - // Mouse wheel has not moved. - return; - } - if (cameraProperty === null || coordinate === null) { - // Mouse wheel axis not configured. - return; - } - let action = null; - switch (cameraProperty) { - case _CameraProperty.MoveRelative: - action = this._moveRelative; - break; - case _CameraProperty.RotateRelative: - action = this._rotateRelative; - break; - case _CameraProperty.MoveScene: - action = this._moveScene; - break; - } - switch (coordinate) { - case Coordinate.X: - action.set(value, 0, 0); - break; - case Coordinate.Y: - action.set(0, value, 0); - break; - case Coordinate.Z: - action.set(0, 0, value); - break; - } - } -} -__decorate([ - serialize() -], FreeCameraMouseWheelInput.prototype, "wheelXMoveRelative", null); -__decorate([ - serialize() -], FreeCameraMouseWheelInput.prototype, "wheelYMoveRelative", null); -__decorate([ - serialize() -], FreeCameraMouseWheelInput.prototype, "wheelZMoveRelative", null); -__decorate([ - serialize() -], FreeCameraMouseWheelInput.prototype, "wheelXRotateRelative", null); -__decorate([ - serialize() -], FreeCameraMouseWheelInput.prototype, "wheelYRotateRelative", null); -__decorate([ - serialize() -], FreeCameraMouseWheelInput.prototype, "wheelZRotateRelative", null); -__decorate([ - serialize() -], FreeCameraMouseWheelInput.prototype, "wheelXMoveScene", null); -__decorate([ - serialize() -], FreeCameraMouseWheelInput.prototype, "wheelYMoveScene", null); -__decorate([ - serialize() -], FreeCameraMouseWheelInput.prototype, "wheelZMoveScene", null); -CameraInputTypes.FreeCameraMouseWheelInput = FreeCameraMouseWheelInput; -//# sourceMappingURL=freeCameraMouseWheelInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraTouchInput.js - - - - - - -/** - * Manage the touch inputs to control the movement of a free camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FreeCameraTouchInput { - /** - * Manage the touch inputs to control the movement of a free camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - * @param allowMouse Defines if mouse events can be treated as touch events - */ - constructor( - /** - * Define if mouse events can be treated as touch events - */ - allowMouse = false) { - this.allowMouse = allowMouse; - /** - * Defines the touch sensibility for rotation. - * The lower the faster. - */ - this.touchAngularSensibility = 200000.0; - /** - * Defines the touch sensibility for move. - * The lower the faster. - */ - this.touchMoveSensibility = 250.0; - /** - * Swap touch actions so that one touch is used for rotation and multiple for movement - */ - this.singleFingerRotate = false; - this._offsetX = null; - this._offsetY = null; - this._pointerPressed = new Array(); - this._isSafari = tools_Tools.IsSafari(); - } - /** - * Attach the input controls to a specific dom element to get the input from. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - let previousPosition = null; - if (this._pointerInput === undefined) { - this._onLostFocus = () => { - this._offsetX = null; - this._offsetY = null; - }; - this._pointerInput = (p) => { - const evt = p.event; - const isMouseEvent = evt.pointerType === "mouse" || (this._isSafari && typeof evt.pointerType === "undefined"); - if (!this.allowMouse && isMouseEvent) { - return; - } - if (p.type === pointerEvents_PointerEventTypes.POINTERDOWN) { - if (!noPreventDefault) { - evt.preventDefault(); - } - this._pointerPressed.push(evt.pointerId); - if (this._pointerPressed.length !== 1) { - return; - } - previousPosition = { - x: evt.clientX, - y: evt.clientY, - }; - } - else if (p.type === pointerEvents_PointerEventTypes.POINTERUP) { - if (!noPreventDefault) { - evt.preventDefault(); - } - const index = this._pointerPressed.indexOf(evt.pointerId); - if (index === -1) { - return; - } - this._pointerPressed.splice(index, 1); - if (index != 0) { - return; - } - previousPosition = null; - this._offsetX = null; - this._offsetY = null; - } - else if (p.type === pointerEvents_PointerEventTypes.POINTERMOVE) { - if (!noPreventDefault) { - evt.preventDefault(); - } - if (!previousPosition) { - return; - } - const index = this._pointerPressed.indexOf(evt.pointerId); - if (index != 0) { - return; - } - this._offsetX = evt.clientX - previousPosition.x; - this._offsetY = -(evt.clientY - previousPosition.y); - } - }; - } - this._observer = this.camera - .getScene() - ._inputManager._addCameraPointerObserver(this._pointerInput, pointerEvents_PointerEventTypes.POINTERDOWN | pointerEvents_PointerEventTypes.POINTERUP | pointerEvents_PointerEventTypes.POINTERMOVE); - if (this._onLostFocus) { - const engine = this.camera.getEngine(); - const element = engine.getInputElement(); - element && element.addEventListener("blur", this._onLostFocus); - } - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - if (this._pointerInput) { - if (this._observer) { - this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer); - this._observer = null; - } - if (this._onLostFocus) { - const engine = this.camera.getEngine(); - const element = engine.getInputElement(); - element && element.removeEventListener("blur", this._onLostFocus); - this._onLostFocus = null; - } - this._pointerPressed.length = 0; - this._offsetX = null; - this._offsetY = null; - } - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - if (this._offsetX === null || this._offsetY === null) { - return; - } - if (this._offsetX === 0 && this._offsetY === 0) { - return; - } - const camera = this.camera; - camera.cameraRotation.y = this._offsetX / this.touchAngularSensibility; - const rotateCamera = (this.singleFingerRotate && this._pointerPressed.length === 1) || (!this.singleFingerRotate && this._pointerPressed.length > 1); - if (rotateCamera) { - camera.cameraRotation.x = -this._offsetY / this.touchAngularSensibility; - } - else { - const speed = camera._computeLocalCameraSpeed(); - const direction = new math_vector_Vector3(0, 0, this.touchMoveSensibility !== 0 ? (speed * this._offsetY) / this.touchMoveSensibility : 0); - math_vector_Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix); - camera.cameraDirection.addInPlace(math_vector_Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix)); - } - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "FreeCameraTouchInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "touch"; - } -} -__decorate([ - serialize() -], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0); -__decorate([ - serialize() -], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0); -CameraInputTypes.FreeCameraTouchInput = FreeCameraTouchInput; -//# sourceMappingURL=freeCameraTouchInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/freeCameraInputsManager.js - - - - - -/** - * Default Inputs manager for the FreeCamera. - * It groups all the default supported inputs for ease of use. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FreeCameraInputsManager extends CameraInputsManager { - /** - * Instantiates a new FreeCameraInputsManager. - * @param camera Defines the camera the inputs belong to - */ - constructor(camera) { - super(camera); - /** - * @internal - */ - this._mouseInput = null; - /** - * @internal - */ - this._mouseWheelInput = null; - } - /** - * Add keyboard input support to the input manager. - * @returns the current input manager - */ - addKeyboard() { - this.add(new FreeCameraKeyboardMoveInput()); - return this; - } - /** - * Add mouse input support to the input manager. - * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true) - * @returns the current input manager - */ - addMouse(touchEnabled = true) { - if (!this._mouseInput) { - this._mouseInput = new FreeCameraMouseInput(touchEnabled); - this.add(this._mouseInput); - } - return this; - } - /** - * Removes the mouse input support from the manager - * @returns the current input manager - */ - removeMouse() { - if (this._mouseInput) { - this.remove(this._mouseInput); - } - return this; - } - /** - * Add mouse wheel input support to the input manager. - * @returns the current input manager - */ - addMouseWheel() { - if (!this._mouseWheelInput) { - this._mouseWheelInput = new FreeCameraMouseWheelInput(); - this.add(this._mouseWheelInput); - } - return this; - } - /** - * Removes the mouse wheel input support from the manager - * @returns the current input manager - */ - removeMouseWheel() { - if (this._mouseWheelInput) { - this.remove(this._mouseWheelInput); - } - return this; - } - /** - * Add touch input support to the input manager. - * @returns the current input manager - */ - addTouch() { - this.add(new FreeCameraTouchInput()); - return this; - } - /** - * Remove all attached input methods from a camera - */ - clear() { - super.clear(); - this._mouseInput = null; - } -} -//# sourceMappingURL=freeCameraInputsManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraDeviceOrientationInput.js - - - - - -/** - * Add orientation input support to the input manager. - * @param smoothFactor deviceOrientation smoothing. 0: no smoothing, 1: new data ignored, 0.9 recommended for smoothing - * @returns the current input manager - */ -FreeCameraInputsManager.prototype.addDeviceOrientation = function (smoothFactor) { - if (!this._deviceOrientationInput) { - this._deviceOrientationInput = new FreeCameraDeviceOrientationInput(); - if (smoothFactor) { - this._deviceOrientationInput.smoothFactor = smoothFactor; - } - this.add(this._deviceOrientationInput); - } - return this; -}; -/** - * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera. - * Screen rotation is taken into account. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FreeCameraDeviceOrientationInput { - /** - * Can be used to detect if a device orientation sensor is available on a device - * @param timeout amount of time in milliseconds to wait for a response from the sensor (default: infinite) - * @returns a promise that will resolve on orientation change - */ - static WaitForOrientationChangeAsync(timeout) { - return new Promise((res, rej) => { - let gotValue = false; - const eventHandler = () => { - window.removeEventListener("deviceorientation", eventHandler); - gotValue = true; - res(); - }; - // If timeout is populated reject the promise - if (timeout) { - setTimeout(() => { - if (!gotValue) { - window.removeEventListener("deviceorientation", eventHandler); - rej("WaitForOrientationChangeAsync timed out"); - } - }, timeout); - } - if (typeof DeviceOrientationEvent !== "undefined" && typeof DeviceOrientationEvent.requestPermission === "function") { - DeviceOrientationEvent - .requestPermission() - .then((response) => { - if (response == "granted") { - window.addEventListener("deviceorientation", eventHandler); - } - else { - tools_Tools.Warn("Permission not granted."); - } - }) - .catch((error) => { - tools_Tools.Error(error); - }); - } - else { - window.addEventListener("deviceorientation", eventHandler); - } - }); - } - /** - * Instantiates a new input - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ - constructor() { - this._screenOrientationAngle = 0; - this._screenQuaternion = new math_vector_Quaternion(); - this._alpha = 0; - this._beta = 0; - this._gamma = 0; - /** alpha+beta+gamma smoothing. 0: no smoothing, 1: new data ignored, 0.9 recommended for smoothing */ - this.smoothFactor = 0; - /** - * @internal - */ - this._onDeviceOrientationChangedObservable = new observable_Observable(); - this._orientationChanged = () => { - this._screenOrientationAngle = - window.orientation !== undefined - ? +window.orientation - : window.screen.orientation && window.screen.orientation["angle"] - ? window.screen.orientation.angle - : 0; - this._screenOrientationAngle = -tools_Tools.ToRadians(this._screenOrientationAngle / 2); - this._screenQuaternion.copyFromFloats(0, Math.sin(this._screenOrientationAngle), 0, Math.cos(this._screenOrientationAngle)); - }; - this._deviceOrientation = (evt) => { - if (this.smoothFactor) { - this._alpha = evt.alpha !== null ? tools_Tools.SmoothAngleChange(this._alpha, evt.alpha, this.smoothFactor) : 0; - this._beta = evt.beta !== null ? tools_Tools.SmoothAngleChange(this._beta, evt.beta, this.smoothFactor) : 0; - this._gamma = evt.gamma !== null ? tools_Tools.SmoothAngleChange(this._gamma, evt.gamma, this.smoothFactor) : 0; - } - else { - this._alpha = evt.alpha !== null ? evt.alpha : 0; - this._beta = evt.beta !== null ? evt.beta : 0; - this._gamma = evt.gamma !== null ? evt.gamma : 0; - } - if (evt.alpha !== null) { - this._onDeviceOrientationChangedObservable.notifyObservers(); - } - }; - this._constantTranform = new math_vector_Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); - this._orientationChanged(); - } - /** - * Define the camera controlled by the input. - */ - get camera() { - return this._camera; - } - set camera(camera) { - this._camera = camera; - if (this._camera != null && !this._camera.rotationQuaternion) { - this._camera.rotationQuaternion = new math_vector_Quaternion(); - } - if (this._camera) { - this._camera.onDisposeObservable.add(() => { - this._onDeviceOrientationChangedObservable.clear(); - }); - } - } - /** - * Attach the input controls to a specific dom element to get the input from. - */ - attachControl() { - const hostWindow = this.camera.getScene().getEngine().getHostWindow(); - if (hostWindow) { - const eventHandler = () => { - hostWindow.addEventListener("orientationchange", this._orientationChanged); - hostWindow.addEventListener("deviceorientation", this._deviceOrientation); - //In certain cases, the attach control is called AFTER orientation was changed, - //So this is needed. - this._orientationChanged(); - }; - if (typeof DeviceOrientationEvent !== "undefined" && typeof DeviceOrientationEvent.requestPermission === "function") { - DeviceOrientationEvent - .requestPermission() - .then((response) => { - if (response === "granted") { - eventHandler(); - } - else { - tools_Tools.Warn("Permission not granted."); - } - }) - .catch((error) => { - tools_Tools.Error(error); - }); - } - else { - eventHandler(); - } - } - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - window.removeEventListener("orientationchange", this._orientationChanged); - window.removeEventListener("deviceorientation", this._deviceOrientation); - this._alpha = 0; - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - //if no device orientation provided, don't update the rotation. - //Only testing against alpha under the assumption thatnorientation will never be so exact when set. - if (!this._alpha) { - return; - } - math_vector_Quaternion.RotationYawPitchRollToRef(tools_Tools.ToRadians(this._alpha), tools_Tools.ToRadians(this._beta), -tools_Tools.ToRadians(this._gamma), this.camera.rotationQuaternion); - this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion); - this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform); - //Mirror on XY Plane - this._camera.rotationQuaternion.z *= -1; - this._camera.rotationQuaternion.w *= -1; - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "FreeCameraDeviceOrientationInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "deviceOrientation"; - } -} -CameraInputTypes.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput; -//# sourceMappingURL=freeCameraDeviceOrientationInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraGamepadInput.js - - - - - -/** - * Manage the gamepad inputs to control a free camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FreeCameraGamepadInput { - constructor() { - /** - * Defines the gamepad rotation sensibility. - * This is the threshold from when rotation starts to be accounted for to prevent jittering. - */ - this.gamepadAngularSensibility = 200; - /** - * Defines the gamepad move sensibility. - * This is the threshold from when moving starts to be accounted for for to prevent jittering. - */ - this.gamepadMoveSensibility = 40; - /** - * Defines the minimum value at which any analog stick input is ignored. - * Note: This value should only be a value between 0 and 1. - */ - this.deadzoneDelta = 0.1; - this._yAxisScale = 1.0; - this._cameraTransform = math_vector_Matrix.Identity(); - this._deltaTransform = math_vector_Vector3.Zero(); - this._vector3 = math_vector_Vector3.Zero(); - this._vector2 = math_vector_Vector2.Zero(); - } - /** - * Gets or sets a boolean indicating that Yaxis (for right stick) should be inverted - */ - get invertYAxis() { - return this._yAxisScale !== 1.0; - } - set invertYAxis(value) { - this._yAxisScale = value ? -1.0 : 1.0; - } - /** - * Attach the input controls to a specific dom element to get the input from. - */ - attachControl() { - const manager = this.camera.getScene().gamepadManager; - this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => { - if (gamepad.type !== Gamepad.POSE_ENABLED) { - // prioritize XBOX gamepads. - if (!this.gamepad || gamepad.type === Gamepad.XBOX) { - this.gamepad = gamepad; - } - } - }); - this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => { - if (this.gamepad === gamepad) { - this.gamepad = null; - } - }); - // check if there are already other controllers connected - this.gamepad = manager.getGamepadByType(Gamepad.XBOX); - // if no xbox controller was found, but there are gamepad controllers, take the first one - if (!this.gamepad && manager.gamepads.length) { - this.gamepad = manager.gamepads[0]; - } - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); - this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); - this.gamepad = null; - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - if (this.gamepad && this.gamepad.leftStick) { - const camera = this.camera; - const lsValues = this.gamepad.leftStick; - if (this.gamepadMoveSensibility !== 0) { - lsValues.x = Math.abs(lsValues.x) > this.deadzoneDelta ? lsValues.x / this.gamepadMoveSensibility : 0; - lsValues.y = Math.abs(lsValues.y) > this.deadzoneDelta ? lsValues.y / this.gamepadMoveSensibility : 0; - } - let rsValues = this.gamepad.rightStick; - if (rsValues && this.gamepadAngularSensibility !== 0) { - rsValues.x = Math.abs(rsValues.x) > this.deadzoneDelta ? rsValues.x / this.gamepadAngularSensibility : 0; - rsValues.y = (Math.abs(rsValues.y) > this.deadzoneDelta ? rsValues.y / this.gamepadAngularSensibility : 0) * this._yAxisScale; - } - else { - rsValues = { x: 0, y: 0 }; - } - if (!camera.rotationQuaternion) { - math_vector_Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform); - } - else { - camera.rotationQuaternion.toRotationMatrix(this._cameraTransform); - } - const speed = camera._computeLocalCameraSpeed() * 50.0; - this._vector3.copyFromFloats(lsValues.x * speed, 0, -lsValues.y * speed); - math_vector_Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform); - camera.cameraDirection.addInPlace(this._deltaTransform); - this._vector2.copyFromFloats(rsValues.y, rsValues.x); - camera.cameraRotation.addInPlace(this._vector2); - } - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "FreeCameraGamepadInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "gamepad"; - } -} -__decorate([ - serialize() -], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0); -__decorate([ - serialize() -], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); -CameraInputTypes.FreeCameraGamepadInput = FreeCameraGamepadInput; -//# sourceMappingURL=freeCameraGamepadInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/virtualJoystick.js - - -// Mainly based on these 2 articles : -// 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 -// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/ -/** - * Defines the potential axis of a Joystick - */ -var JoystickAxis; -(function (JoystickAxis) { - /** X axis */ - JoystickAxis[JoystickAxis["X"] = 0] = "X"; - /** Y axis */ - JoystickAxis[JoystickAxis["Y"] = 1] = "Y"; - /** Z axis */ - JoystickAxis[JoystickAxis["Z"] = 2] = "Z"; -})(JoystickAxis || (JoystickAxis = {})); -/** - * Class used to define virtual joystick (used in touch mode) - */ -class VirtualJoystick { - static _GetDefaultOptions() { - return { - puckSize: 40, - containerSize: 60, - color: "cyan", - puckImage: undefined, - containerImage: undefined, - position: undefined, - alwaysVisible: false, - limitToContainer: false, - }; - } - /** - * Creates a new virtual joystick - * @param leftJoystick defines that the joystick is for left hand (false by default) - * @param customizations Defines the options we want to customize the VirtualJoystick - */ - constructor(leftJoystick, customizations) { - this._released = false; - const options = Object.assign(Object.assign({}, VirtualJoystick._GetDefaultOptions()), customizations); - if (leftJoystick) { - this._leftJoystick = true; - } - else { - this._leftJoystick = false; - } - VirtualJoystick._GlobalJoystickIndex++; - // By default left & right arrow keys are moving the X - // and up & down keys are moving the Y - this._axisTargetedByLeftAndRight = JoystickAxis.X; - this._axisTargetedByUpAndDown = JoystickAxis.Y; - this.reverseLeftRight = false; - this.reverseUpDown = false; - // collections of pointers - this._touches = new StringDictionary(); - this.deltaPosition = math_vector_Vector3.Zero(); - this._joystickSensibility = 25; - this._inversedSensibility = 1 / (this._joystickSensibility / 1000); - this._onResize = () => { - VirtualJoystick._VJCanvasWidth = window.innerWidth; - VirtualJoystick._VJCanvasHeight = window.innerHeight; - if (VirtualJoystick.Canvas) { - VirtualJoystick.Canvas.width = VirtualJoystick._VJCanvasWidth; - VirtualJoystick.Canvas.height = VirtualJoystick._VJCanvasHeight; - } - VirtualJoystick._HalfWidth = VirtualJoystick._VJCanvasWidth / 2; - }; - // injecting a canvas element on top of the canvas 3D game - if (!VirtualJoystick.Canvas) { - window.addEventListener("resize", this._onResize, false); - VirtualJoystick.Canvas = document.createElement("canvas"); - VirtualJoystick._VJCanvasWidth = window.innerWidth; - VirtualJoystick._VJCanvasHeight = window.innerHeight; - VirtualJoystick.Canvas.width = window.innerWidth; - VirtualJoystick.Canvas.height = window.innerHeight; - VirtualJoystick.Canvas.style.width = "100%"; - VirtualJoystick.Canvas.style.height = "100%"; - VirtualJoystick.Canvas.style.position = "absolute"; - VirtualJoystick.Canvas.style.backgroundColor = "transparent"; - VirtualJoystick.Canvas.style.top = "0px"; - VirtualJoystick.Canvas.style.left = "0px"; - VirtualJoystick.Canvas.style.zIndex = "5"; - VirtualJoystick.Canvas.style.touchAction = "none"; // fix https://forum.babylonjs.com/t/virtualjoystick-needs-to-set-style-touch-action-none-explicitly/9562 - // Support for jQuery PEP polyfill - VirtualJoystick.Canvas.setAttribute("touch-action", "none"); - const context = VirtualJoystick.Canvas.getContext("2d"); - if (!context) { - throw new Error("Unable to create canvas for virtual joystick"); - } - VirtualJoystick._VJCanvasContext = context; - VirtualJoystick._VJCanvasContext.strokeStyle = "#ffffff"; - VirtualJoystick._VJCanvasContext.lineWidth = 2; - document.body.appendChild(VirtualJoystick.Canvas); - } - VirtualJoystick._HalfWidth = VirtualJoystick.Canvas.width / 2; - this.pressed = false; - this.limitToContainer = options.limitToContainer; - // default joystick color - this._joystickColor = options.color; - // default joystick size - this.containerSize = options.containerSize; - this.puckSize = options.puckSize; - if (options.position) { - this.setPosition(options.position.x, options.position.y); - } - if (options.puckImage) { - this.setPuckImage(options.puckImage); - } - if (options.containerImage) { - this.setContainerImage(options.containerImage); - } - if (options.alwaysVisible) { - VirtualJoystick._AlwaysVisibleSticks++; - } - // must come after position potentially set - this.alwaysVisible = options.alwaysVisible; - this._joystickPointerId = -1; - // current joystick position - this._joystickPointerPos = new math_vector_Vector2(0, 0); - this._joystickPreviousPointerPos = new math_vector_Vector2(0, 0); - // origin joystick position - this._joystickPointerStartPos = new math_vector_Vector2(0, 0); - this._deltaJoystickVector = new math_vector_Vector2(0, 0); - this._onPointerDownHandlerRef = (evt) => { - this._onPointerDown(evt); - }; - this._onPointerMoveHandlerRef = (evt) => { - this._onPointerMove(evt); - }; - this._onPointerUpHandlerRef = (evt) => { - this._onPointerUp(evt); - }; - VirtualJoystick.Canvas.addEventListener("pointerdown", this._onPointerDownHandlerRef, false); - VirtualJoystick.Canvas.addEventListener("pointermove", this._onPointerMoveHandlerRef, false); - VirtualJoystick.Canvas.addEventListener("pointerup", this._onPointerUpHandlerRef, false); - VirtualJoystick.Canvas.addEventListener("pointerout", this._onPointerUpHandlerRef, false); - VirtualJoystick.Canvas.addEventListener("contextmenu", (evt) => { - evt.preventDefault(); // Disables system menu - }, false); - requestAnimationFrame(() => { - this._drawVirtualJoystick(); - }); - } - /** - * Defines joystick sensibility (ie. the ratio between a physical move and virtual joystick position change) - * @param newJoystickSensibility defines the new sensibility - */ - setJoystickSensibility(newJoystickSensibility) { - this._joystickSensibility = newJoystickSensibility; - this._inversedSensibility = 1 / (this._joystickSensibility / 1000); - } - _onPointerDown(e) { - let positionOnScreenCondition; - e.preventDefault(); - if (this._leftJoystick === true) { - positionOnScreenCondition = e.clientX < VirtualJoystick._HalfWidth; - } - else { - positionOnScreenCondition = e.clientX > VirtualJoystick._HalfWidth; - } - if (positionOnScreenCondition && this._joystickPointerId < 0) { - // First contact will be dedicated to the virtual joystick - this._joystickPointerId = e.pointerId; - if (this._joystickPosition) { - this._joystickPointerStartPos = this._joystickPosition.clone(); - this._joystickPointerPos = this._joystickPosition.clone(); - this._joystickPreviousPointerPos = this._joystickPosition.clone(); - // in case the user only clicks down && doesn't move: - // this ensures the delta is properly set - this._onPointerMove(e); - } - else { - 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 = true; - this._touches.add(e.pointerId.toString(), e); - } - else { - // You can only trigger the action buttons with a joystick declared - if (VirtualJoystick._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 the current pointer is the one associated to the joystick (first touch contact) - if (this._joystickPointerId == e.pointerId) { - // limit to container if need be - if (this.limitToContainer) { - const vector = new math_vector_Vector2(e.clientX - this._joystickPointerStartPos.x, e.clientY - this._joystickPointerStartPos.y); - const distance = vector.length(); - if (distance > this.containerSize) { - vector.scaleInPlace(this.containerSize / distance); - } - this._joystickPointerPos.x = this._joystickPointerStartPos.x + vector.x; - this._joystickPointerPos.y = this._joystickPointerStartPos.y + vector.y; - } - else { - this._joystickPointerPos.x = e.clientX; - this._joystickPointerPos.y = e.clientY; - } - // create delta vector - this._deltaJoystickVector = this._joystickPointerPos.clone(); - this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos); - // if a joystick is always visible, there will be clipping issues if - // you drag the puck from one over the container of the other - if (0 < VirtualJoystick._AlwaysVisibleSticks) { - if (this._leftJoystick) { - this._joystickPointerPos.x = Math.min(VirtualJoystick._HalfWidth, this._joystickPointerPos.x); - } - else { - this._joystickPointerPos.x = Math.max(VirtualJoystick._HalfWidth, this._joystickPointerPos.x); - } - } - const directionLeftRight = this.reverseLeftRight ? -1 : 1; - const deltaJoystickX = (directionLeftRight * this._deltaJoystickVector.x) / this._inversedSensibility; - switch (this._axisTargetedByLeftAndRight) { - case JoystickAxis.X: - this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX)); - break; - case JoystickAxis.Y: - this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX)); - break; - case JoystickAxis.Z: - this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX)); - break; - } - const directionUpDown = this.reverseUpDown ? 1 : -1; - const deltaJoystickY = (directionUpDown * this._deltaJoystickVector.y) / this._inversedSensibility; - switch (this._axisTargetedByUpAndDown) { - case JoystickAxis.X: - this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY)); - break; - case JoystickAxis.Y: - this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY)); - break; - case JoystickAxis.Z: - this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY)); - break; - } - } - else { - const data = this._touches.get(e.pointerId.toString()); - if (data) { - data.x = e.clientX; - data.y = e.clientY; - } - } - } - _onPointerUp(e) { - if (this._joystickPointerId == e.pointerId) { - this._clearPreviousDraw(); - this._joystickPointerId = -1; - this.pressed = false; - } - else { - const touch = this._touches.get(e.pointerId.toString()); - if (touch) { - VirtualJoystick._VJCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88); - } - } - this._deltaJoystickVector.x = 0; - this._deltaJoystickVector.y = 0; - this._touches.remove(e.pointerId.toString()); - } - /** - * Change the color of the virtual joystick - * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000") - */ - setJoystickColor(newColor) { - this._joystickColor = newColor; - } - /** - * Size of the joystick's container - */ - set containerSize(newSize) { - this._joystickContainerSize = newSize; - this._clearContainerSize = ~~(this._joystickContainerSize * 2.1); - this._clearContainerSizeOffset = ~~(this._clearContainerSize / 2); - } - get containerSize() { - return this._joystickContainerSize; - } - /** - * Size of the joystick's puck - */ - set puckSize(newSize) { - this._joystickPuckSize = newSize; - this._clearPuckSize = ~~(this._joystickPuckSize * 2.1); - this._clearPuckSizeOffset = ~~(this._clearPuckSize / 2); - } - get puckSize() { - return this._joystickPuckSize; - } - /** - * Clears the set position of the joystick - */ - clearPosition() { - this.alwaysVisible = false; - this._joystickPosition = null; - } - /** - * Defines whether or not the joystick container is always visible - */ - set alwaysVisible(value) { - if (this._alwaysVisible === value) { - return; - } - if (value && this._joystickPosition) { - VirtualJoystick._AlwaysVisibleSticks++; - this._alwaysVisible = true; - } - else { - VirtualJoystick._AlwaysVisibleSticks--; - this._alwaysVisible = false; - } - } - get alwaysVisible() { - return this._alwaysVisible; - } - /** - * Sets the constant position of the Joystick container - * @param x X axis coordinate - * @param y Y axis coordinate - */ - setPosition(x, y) { - // just in case position is moved while the container is visible - if (this._joystickPointerStartPos) { - this._clearPreviousDraw(); - } - this._joystickPosition = new math_vector_Vector2(x, y); - } - /** - * Defines a callback to call when the joystick is touched - * @param action defines the callback - */ - setActionOnTouch(action) { - this._action = action; - } - /** - * Defines which axis you'd like to control for left & right - * @param axis defines the axis to use - */ - setAxisForLeftRight(axis) { - switch (axis) { - case JoystickAxis.X: - case JoystickAxis.Y: - case JoystickAxis.Z: - this._axisTargetedByLeftAndRight = axis; - break; - default: - this._axisTargetedByLeftAndRight = JoystickAxis.X; - break; - } - } - /** - * Defines which axis you'd like to control for up & down - * @param axis defines the axis to use - */ - setAxisForUpDown(axis) { - switch (axis) { - case JoystickAxis.X: - case JoystickAxis.Y: - case JoystickAxis.Z: - this._axisTargetedByUpAndDown = axis; - break; - default: - this._axisTargetedByUpAndDown = JoystickAxis.Y; - break; - } - } - /** - * Clears the canvas from the previous puck / container draw - */ - _clearPreviousDraw() { - const jp = this._joystickPosition || this._joystickPointerStartPos; - // clear container pixels - VirtualJoystick._VJCanvasContext.clearRect(jp.x - this._clearContainerSizeOffset, jp.y - this._clearContainerSizeOffset, this._clearContainerSize, this._clearContainerSize); - // clear puck pixels + 1 pixel for the change made before it moved - VirtualJoystick._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x - this._clearPuckSizeOffset - 1, this._joystickPreviousPointerPos.y - this._clearPuckSizeOffset - 1, this._clearPuckSize + 2, this._clearPuckSize + 2); - } - /** - * Loads `urlPath` to be used for the container's image - * @param urlPath defines the urlPath of an image to use - */ - setContainerImage(urlPath) { - const image = new Image(); - image.src = urlPath; - image.onload = () => (this._containerImage = image); - } - /** - * Loads `urlPath` to be used for the puck's image - * @param urlPath defines the urlPath of an image to use - */ - setPuckImage(urlPath) { - const image = new Image(); - image.src = urlPath; - image.onload = () => (this._puckImage = image); - } - /** - * Draws the Virtual Joystick's container - */ - _drawContainer() { - const jp = this._joystickPosition || this._joystickPointerStartPos; - this._clearPreviousDraw(); - if (this._containerImage) { - VirtualJoystick._VJCanvasContext.drawImage(this._containerImage, jp.x - this.containerSize, jp.y - this.containerSize, this.containerSize * 2, this.containerSize * 2); - } - else { - // outer container - VirtualJoystick._VJCanvasContext.beginPath(); - VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor; - VirtualJoystick._VJCanvasContext.lineWidth = 2; - VirtualJoystick._VJCanvasContext.arc(jp.x, jp.y, this.containerSize, 0, Math.PI * 2, true); - VirtualJoystick._VJCanvasContext.stroke(); - VirtualJoystick._VJCanvasContext.closePath(); - // inner container - VirtualJoystick._VJCanvasContext.beginPath(); - VirtualJoystick._VJCanvasContext.lineWidth = 6; - VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor; - VirtualJoystick._VJCanvasContext.arc(jp.x, jp.y, this.puckSize, 0, Math.PI * 2, true); - VirtualJoystick._VJCanvasContext.stroke(); - VirtualJoystick._VJCanvasContext.closePath(); - } - } - /** - * Draws the Virtual Joystick's puck - */ - _drawPuck() { - if (this._puckImage) { - VirtualJoystick._VJCanvasContext.drawImage(this._puckImage, this._joystickPointerPos.x - this.puckSize, this._joystickPointerPos.y - this.puckSize, this.puckSize * 2, this.puckSize * 2); - } - else { - VirtualJoystick._VJCanvasContext.beginPath(); - VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor; - VirtualJoystick._VJCanvasContext.lineWidth = 2; - VirtualJoystick._VJCanvasContext.arc(this._joystickPointerPos.x, this._joystickPointerPos.y, this.puckSize, 0, Math.PI * 2, true); - VirtualJoystick._VJCanvasContext.stroke(); - VirtualJoystick._VJCanvasContext.closePath(); - } - } - _drawVirtualJoystick() { - // canvas released? don't continue iterating - if (this._released) { - return; - } - if (this.alwaysVisible) { - this._drawContainer(); - } - if (this.pressed) { - this._touches.forEach((key, touch) => { - if (touch.pointerId === this._joystickPointerId) { - if (!this.alwaysVisible) { - this._drawContainer(); - } - this._drawPuck(); - // store current pointer for next clear - this._joystickPreviousPointerPos = this._joystickPointerPos.clone(); - } - else { - VirtualJoystick._VJCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88); - VirtualJoystick._VJCanvasContext.beginPath(); - VirtualJoystick._VJCanvasContext.fillStyle = "white"; - VirtualJoystick._VJCanvasContext.beginPath(); - VirtualJoystick._VJCanvasContext.strokeStyle = "red"; - VirtualJoystick._VJCanvasContext.lineWidth = 6; - VirtualJoystick._VJCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true); - VirtualJoystick._VJCanvasContext.stroke(); - VirtualJoystick._VJCanvasContext.closePath(); - touch.prevX = touch.x; - touch.prevY = touch.y; - } - }); - } - requestAnimationFrame(() => { - this._drawVirtualJoystick(); - }); - } - /** - * Release internal HTML canvas - */ - releaseCanvas() { - if (VirtualJoystick.Canvas) { - VirtualJoystick.Canvas.removeEventListener("pointerdown", this._onPointerDownHandlerRef); - VirtualJoystick.Canvas.removeEventListener("pointermove", this._onPointerMoveHandlerRef); - VirtualJoystick.Canvas.removeEventListener("pointerup", this._onPointerUpHandlerRef); - VirtualJoystick.Canvas.removeEventListener("pointerout", this._onPointerUpHandlerRef); - window.removeEventListener("resize", this._onResize); - document.body.removeChild(VirtualJoystick.Canvas); - VirtualJoystick.Canvas = null; - } - this._released = true; - } -} -// Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas -VirtualJoystick._GlobalJoystickIndex = 0; -VirtualJoystick._AlwaysVisibleSticks = 0; -//# sourceMappingURL=virtualJoystick.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraVirtualJoystickInput.js - - - - -/** - * Add virtual joystick input support to the input manager. - * @returns the current input manager - */ -FreeCameraInputsManager.prototype.addVirtualJoystick = function () { - this.add(new FreeCameraVirtualJoystickInput()); - return this; -}; -/** - * Manage the Virtual Joystick inputs to control the movement of a free camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FreeCameraVirtualJoystickInput { - /** - * Gets the left stick of the virtual joystick. - * @returns The virtual Joystick - */ - getLeftJoystick() { - return this._leftjoystick; - } - /** - * Gets the right stick of the virtual joystick. - * @returns The virtual Joystick - */ - getRightJoystick() { - return this._rightjoystick; - } - /** - * Update the current camera state depending on the inputs that have been used this frame. - * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. - */ - checkInputs() { - if (this._leftjoystick) { - const camera = this.camera; - const speed = camera._computeLocalCameraSpeed() * 50; - const cameraTransform = math_vector_Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0); - const deltaTransform = math_vector_Vector3.TransformCoordinates(new math_vector_Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform); - camera.cameraDirection = camera.cameraDirection.add(deltaTransform); - camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition); - if (!this._leftjoystick.pressed) { - this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9); - } - if (!this._rightjoystick.pressed) { - this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9); - } - } - } - /** - * Attach the input controls to a specific dom element to get the input from. - */ - attachControl() { - this._leftjoystick = new VirtualJoystick(true); - this._leftjoystick.setAxisForUpDown(JoystickAxis.Z); - this._leftjoystick.setAxisForLeftRight(JoystickAxis.X); - this._leftjoystick.setJoystickSensibility(0.15); - this._rightjoystick = new VirtualJoystick(false); - this._rightjoystick.setAxisForUpDown(JoystickAxis.X); - this._rightjoystick.setAxisForLeftRight(JoystickAxis.Y); - this._rightjoystick.reverseUpDown = true; - this._rightjoystick.setJoystickSensibility(0.05); - this._rightjoystick.setJoystickColor("yellow"); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - this._leftjoystick.releaseCanvas(); - this._rightjoystick.releaseCanvas(); - } - /** - * Gets the class name of the current input. - * @returns the class name - */ - getClassName() { - return "FreeCameraVirtualJoystickInput"; - } - /** - * Get the friendly name associated with the input class. - * @returns the input friendly name - */ - getSimpleName() { - return "virtualJoystick"; - } -} -CameraInputTypes.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput; -//# sourceMappingURL=freeCameraVirtualJoystickInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Inputs/index.js - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/targetCamera.js - - - - - - -/** - * A target camera takes a mesh or position as a target and continues to look at it while it moves. - * This is the base of the follow, arc rotate cameras and Free camera - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras - */ -class targetCamera_TargetCamera extends camera_Camera { - /** - * Instantiates a target camera that takes a mesh or position as a target and continues to look at it while it moves. - * This is the base of the follow, arc rotate cameras and Free camera - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras - * @param name Defines the name of the camera in the scene - * @param position Defines the start position of the camera in the scene - * @param scene Defines the scene the camera belongs to - * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined - */ - constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) { - super(name, position, scene, setActiveOnSceneIfNoneActive); - this._tmpUpVector = math_vector_Vector3.Zero(); - this._tmpTargetVector = math_vector_Vector3.Zero(); - /** - * Define the current direction the camera is moving to - */ - this.cameraDirection = new math_vector_Vector3(0, 0, 0); - /** - * Define the current rotation the camera is rotating to - */ - this.cameraRotation = new math_vector_Vector2(0, 0); - /** Gets or sets a boolean indicating that the scaling of the parent hierarchy will not be taken in account by the camera */ - this.ignoreParentScaling = false; - /** - * When set, the up vector of the camera will be updated by the rotation of the camera - */ - this.updateUpVectorFromRotation = false; - this._tmpQuaternion = new math_vector_Quaternion(); - /** - * Define the current rotation of the camera - */ - this.rotation = new math_vector_Vector3(0, 0, 0); - /** - * Define the current speed of the camera - */ - this.speed = 2.0; - /** - * Add constraint to the camera to prevent it to move freely in all directions and - * around all axis. - */ - this.noRotationConstraint = false; - /** - * Reverses mouselook direction to 'natural' panning as opposed to traditional direct - * panning - */ - this.invertRotation = false; - /** - * Speed multiplier for inverse camera panning - */ - this.inverseRotationSpeed = 0.2; - /** - * Define the current target of the camera as an object or a position. - * Please note that locking a target will disable panning. - */ - this.lockedTarget = null; - /** @internal */ - this._currentTarget = math_vector_Vector3.Zero(); - /** @internal */ - this._initialFocalDistance = 1; - /** @internal */ - this._viewMatrix = math_vector_Matrix.Zero(); - /** @internal */ - this._camMatrix = math_vector_Matrix.Zero(); - /** @internal */ - this._cameraTransformMatrix = math_vector_Matrix.Zero(); - /** @internal */ - this._cameraRotationMatrix = math_vector_Matrix.Zero(); - /** @internal */ - this._referencePoint = new math_vector_Vector3(0, 0, 1); - /** @internal */ - this._transformedReferencePoint = math_vector_Vector3.Zero(); - this._deferredPositionUpdate = new math_vector_Vector3(); - this._deferredRotationQuaternionUpdate = new math_vector_Quaternion(); - this._deferredRotationUpdate = new math_vector_Vector3(); - this._deferredUpdated = false; - this._deferOnly = false; - this._defaultUp = math_vector_Vector3.Up(); - this._cachedRotationZ = 0; - this._cachedQuaternionRotationZ = 0; - } - /** - * Gets the position in front of the camera at a given distance. - * @param distance The distance from the camera we want the position to be - * @returns the position - */ - getFrontPosition(distance) { - this.getWorldMatrix(); - const direction = this.getTarget().subtract(this.position); - direction.normalize(); - direction.scaleInPlace(distance); - return this.globalPosition.add(direction); - } - /** @internal */ - _getLockedTargetPosition() { - if (!this.lockedTarget) { - return null; - } - if (this.lockedTarget.absolutePosition) { - const lockedTarget = this.lockedTarget; - const m = lockedTarget.computeWorldMatrix(); - // in some cases the absolute position resets externally, but doesn't update since the matrix is cached. - m.getTranslationToRef(lockedTarget.absolutePosition); - } - return this.lockedTarget.absolutePosition || this.lockedTarget; - } - /** - * Store current camera state of the camera (fov, position, rotation, etc..) - * @returns the camera - */ - storeState() { - this._storedPosition = this.position.clone(); - this._storedRotation = this.rotation.clone(); - if (this.rotationQuaternion) { - this._storedRotationQuaternion = this.rotationQuaternion.clone(); - } - return super.storeState(); - } - /** - * Restored camera state. You must call storeState() first - * @returns whether it was successful or not - * @internal - */ - _restoreStateValues() { - if (!super._restoreStateValues()) { - return false; - } - this.position = this._storedPosition.clone(); - this.rotation = this._storedRotation.clone(); - if (this.rotationQuaternion) { - this.rotationQuaternion = this._storedRotationQuaternion.clone(); - } - this.cameraDirection.copyFromFloats(0, 0, 0); - this.cameraRotation.copyFromFloats(0, 0); - return true; - } - /** @internal */ - _initCache() { - super._initCache(); - this._cache.lockedTarget = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - this._cache.rotation = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - this._cache.rotationQuaternion = new math_vector_Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - } - /** - * @internal - */ - _updateCache(ignoreParentClass) { - if (!ignoreParentClass) { - super._updateCache(); - } - const lockedTargetPosition = this._getLockedTargetPosition(); - if (!lockedTargetPosition) { - this._cache.lockedTarget = null; - } - else { - if (!this._cache.lockedTarget) { - this._cache.lockedTarget = lockedTargetPosition.clone(); - } - else { - this._cache.lockedTarget.copyFrom(lockedTargetPosition); - } - } - this._cache.rotation.copyFrom(this.rotation); - if (this.rotationQuaternion) { - this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion); - } - } - // Synchronized - /** @internal */ - _isSynchronizedViewMatrix() { - if (!super._isSynchronizedViewMatrix()) { - return false; - } - const lockedTargetPosition = this._getLockedTargetPosition(); - return ((this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && - (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation))); - } - // Methods - /** @internal */ - _computeLocalCameraSpeed() { - const engine = this.getEngine(); - return this.speed * Math.sqrt(engine.getDeltaTime() / (engine.getFps() * 100.0)); - } - // Target - /** - * Defines the target the camera should look at. - * @param target Defines the new target as a Vector - */ - setTarget(target) { - this.upVector.normalize(); - this._initialFocalDistance = target.subtract(this.position).length(); - if (this.position.z === target.z) { - this.position.z += math_constants_Epsilon; - } - this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance); - math_vector_Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix); - this._camMatrix.invert(); - this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]); - const vDir = target.subtract(this.position); - if (vDir.x >= 0.0) { - this.rotation.y = -Math.atan(vDir.z / vDir.x) + Math.PI / 2.0; - } - else { - this.rotation.y = -Math.atan(vDir.z / vDir.x) - Math.PI / 2.0; - } - this.rotation.z = 0; - if (isNaN(this.rotation.x)) { - this.rotation.x = 0; - } - if (isNaN(this.rotation.y)) { - this.rotation.y = 0; - } - if (isNaN(this.rotation.z)) { - this.rotation.z = 0; - } - if (this.rotationQuaternion) { - math_vector_Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion); - } - } - /** - * Defines the target point of the camera. - * The camera looks towards it form the radius distance. - */ - get target() { - return this.getTarget(); - } - set target(value) { - this.setTarget(value); - } - /** - * Return the current target position of the camera. This value is expressed in local space. - * @returns the target position - */ - getTarget() { - return this._currentTarget; - } - /** @internal */ - _decideIfNeedsToMove() { - return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; - } - /** @internal */ - _updatePosition() { - if (this.parent) { - this.parent.getWorldMatrix().invertToRef(math_vector_TmpVectors.Matrix[0]); - math_vector_Vector3.TransformNormalToRef(this.cameraDirection, math_vector_TmpVectors.Matrix[0], math_vector_TmpVectors.Vector3[0]); - this._deferredPositionUpdate.addInPlace(math_vector_TmpVectors.Vector3[0]); - if (!this._deferOnly) { - this.position.copyFrom(this._deferredPositionUpdate); - } - else { - this._deferredUpdated = true; - } - return; - } - this._deferredPositionUpdate.addInPlace(this.cameraDirection); - if (!this._deferOnly) { - this.position.copyFrom(this._deferredPositionUpdate); - } - else { - this._deferredUpdated = true; - } - } - /** @internal */ - _checkInputs() { - const directionMultiplier = this.invertRotation ? -this.inverseRotationSpeed : 1.0; - const needToMove = this._decideIfNeedsToMove(); - const needToRotate = this.cameraRotation.x || this.cameraRotation.y; - this._deferredUpdated = false; - this._deferredRotationUpdate.copyFrom(this.rotation); - this._deferredPositionUpdate.copyFrom(this.position); - if (this.rotationQuaternion) { - this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion); - } - // Move - if (needToMove) { - this._updatePosition(); - } - // Rotate - if (needToRotate) { - //rotate, if quaternion is set and rotation was used - if (this.rotationQuaternion) { - this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate); - } - this._deferredRotationUpdate.x += this.cameraRotation.x * directionMultiplier; - this._deferredRotationUpdate.y += this.cameraRotation.y * directionMultiplier; - // Apply constraints - if (!this.noRotationConstraint) { - const limit = 1.570796; - if (this._deferredRotationUpdate.x > limit) { - this._deferredRotationUpdate.x = limit; - } - if (this._deferredRotationUpdate.x < -limit) { - this._deferredRotationUpdate.x = -limit; - } - } - if (!this._deferOnly) { - this.rotation.copyFrom(this._deferredRotationUpdate); - } - else { - this._deferredUpdated = true; - } - //rotate, if quaternion is set and rotation was used - if (this.rotationQuaternion) { - const len = this._deferredRotationUpdate.lengthSquared(); - if (len) { - math_vector_Quaternion.RotationYawPitchRollToRef(this._deferredRotationUpdate.y, this._deferredRotationUpdate.x, this._deferredRotationUpdate.z, this._deferredRotationQuaternionUpdate); - if (!this._deferOnly) { - this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate); - } - else { - this._deferredUpdated = true; - } - } - } - } - // Inertia - if (needToMove) { - if (Math.abs(this.cameraDirection.x) < this.speed * math_constants_Epsilon) { - this.cameraDirection.x = 0; - } - if (Math.abs(this.cameraDirection.y) < this.speed * math_constants_Epsilon) { - this.cameraDirection.y = 0; - } - if (Math.abs(this.cameraDirection.z) < this.speed * math_constants_Epsilon) { - this.cameraDirection.z = 0; - } - this.cameraDirection.scaleInPlace(this.inertia); - } - if (needToRotate) { - if (Math.abs(this.cameraRotation.x) < this.speed * math_constants_Epsilon) { - this.cameraRotation.x = 0; - } - if (Math.abs(this.cameraRotation.y) < this.speed * math_constants_Epsilon) { - this.cameraRotation.y = 0; - } - this.cameraRotation.scaleInPlace(this.inertia); - } - super._checkInputs(); - } - _updateCameraRotationMatrix() { - if (this.rotationQuaternion) { - this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix); - } - else { - math_vector_Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix); - } - } - /** - * 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) - * @returns the current camera - */ - _rotateUpVectorWithCameraRotationMatrix() { - math_vector_Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector); - return this; - } - /** @internal */ - _getViewMatrix() { - if (this.lockedTarget) { - this.setTarget(this._getLockedTargetPosition()); - } - // Compute - this._updateCameraRotationMatrix(); - // Apply the changed rotation to the upVector - if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) { - this._rotateUpVectorWithCameraRotationMatrix(); - this._cachedQuaternionRotationZ = this.rotationQuaternion.z; - } - else if (this._cachedRotationZ !== this.rotation.z) { - this._rotateUpVectorWithCameraRotationMatrix(); - this._cachedRotationZ = this.rotation.z; - } - math_vector_Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint); - // Computing target and final matrix - this.position.addToRef(this._transformedReferencePoint, this._currentTarget); - if (this.updateUpVectorFromRotation) { - if (this.rotationQuaternion) { - math_axis_Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector); - } - else { - math_vector_Quaternion.FromEulerVectorToRef(this.rotation, this._tmpQuaternion); - math_axis_Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector); - } - } - this._computeViewMatrix(this.position, this._currentTarget, this.upVector); - return this._viewMatrix; - } - _computeViewMatrix(position, target, up) { - if (this.ignoreParentScaling) { - if (this.parent) { - const parentWorldMatrix = this.parent.getWorldMatrix(); - math_vector_Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition); - math_vector_Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._tmpTargetVector); - math_vector_Vector3.TransformNormalToRef(up, parentWorldMatrix, this._tmpUpVector); - this._markSyncedWithParent(); - } - else { - this._globalPosition.copyFrom(position); - this._tmpTargetVector.copyFrom(target); - this._tmpUpVector.copyFrom(up); - } - if (this.getScene().useRightHandedSystem) { - math_vector_Matrix.LookAtRHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix); - } - else { - math_vector_Matrix.LookAtLHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix); - } - return; - } - if (this.getScene().useRightHandedSystem) { - math_vector_Matrix.LookAtRHToRef(position, target, up, this._viewMatrix); - } - else { - math_vector_Matrix.LookAtLHToRef(position, target, up, this._viewMatrix); - } - if (this.parent) { - const parentWorldMatrix = this.parent.getWorldMatrix(); - this._viewMatrix.invert(); - this._viewMatrix.multiplyToRef(parentWorldMatrix, this._viewMatrix); - this._viewMatrix.getTranslationToRef(this._globalPosition); - this._viewMatrix.invert(); - this._markSyncedWithParent(); - } - else { - this._globalPosition.copyFrom(position); - } - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - createRigCamera(name, cameraIndex) { - if (this.cameraRigMode !== camera_Camera.RIG_MODE_NONE) { - const rigCamera = new targetCamera_TargetCamera(name, this.position.clone(), this.getScene()); - rigCamera.isRigCamera = true; - rigCamera.rigParent = this; - if (this.cameraRigMode === camera_Camera.RIG_MODE_VR || this.cameraRigMode === camera_Camera.RIG_MODE_WEBVR) { - if (!this.rotationQuaternion) { - this.rotationQuaternion = new math_vector_Quaternion(); - } - rigCamera._cameraRigParams = {}; - rigCamera.rotationQuaternion = new math_vector_Quaternion(); - } - rigCamera.mode = this.mode; - rigCamera.orthoLeft = this.orthoLeft; - rigCamera.orthoRight = this.orthoRight; - rigCamera.orthoTop = this.orthoTop; - rigCamera.orthoBottom = this.orthoBottom; - return rigCamera; - } - return null; - } - /** - * @internal - */ - _updateRigCameras() { - const camLeft = this._rigCameras[0]; - const camRight = this._rigCameras[1]; - this.computeWorldMatrix(); - switch (this.cameraRigMode) { - case camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH: - case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: - case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: - case camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER: - case camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED: { - //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance: - const leftSign = this.cameraRigMode === camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? 1 : -1; - const rightSign = this.cameraRigMode === camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? -1 : 1; - this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft); - this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * rightSign, camRight); - break; - } - case camera_Camera.RIG_MODE_VR: - if (camLeft.rotationQuaternion) { - camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion); - camRight.rotationQuaternion.copyFrom(this.rotationQuaternion); - } - else { - camLeft.rotation.copyFrom(this.rotation); - camRight.rotation.copyFrom(this.rotation); - } - camLeft.position.copyFrom(this.position); - camRight.position.copyFrom(this.position); - break; - } - super._updateRigCameras(); - } - _getRigCamPositionAndTarget(halfSpace, rigCamera) { - const target = this.getTarget(); - target.subtractToRef(this.position, targetCamera_TargetCamera._TargetFocalPoint); - targetCamera_TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance); - const newFocalTarget = targetCamera_TargetCamera._TargetFocalPoint.addInPlace(this.position); - math_vector_Matrix.TranslationToRef(-newFocalTarget.x, -newFocalTarget.y, -newFocalTarget.z, targetCamera_TargetCamera._TargetTransformMatrix); - targetCamera_TargetCamera._TargetTransformMatrix.multiplyToRef(math_vector_Matrix.RotationAxis(rigCamera.upVector, halfSpace), targetCamera_TargetCamera._RigCamTransformMatrix); - math_vector_Matrix.TranslationToRef(newFocalTarget.x, newFocalTarget.y, newFocalTarget.z, targetCamera_TargetCamera._TargetTransformMatrix); - targetCamera_TargetCamera._RigCamTransformMatrix.multiplyToRef(targetCamera_TargetCamera._TargetTransformMatrix, targetCamera_TargetCamera._RigCamTransformMatrix); - math_vector_Vector3.TransformCoordinatesToRef(this.position, targetCamera_TargetCamera._RigCamTransformMatrix, rigCamera.position); - rigCamera.setTarget(newFocalTarget); - } - /** - * Gets the current object class name. - * @returns the class name - */ - getClassName() { - return "TargetCamera"; - } -} -targetCamera_TargetCamera._RigCamTransformMatrix = new math_vector_Matrix(); -targetCamera_TargetCamera._TargetTransformMatrix = new math_vector_Matrix(); -targetCamera_TargetCamera._TargetFocalPoint = new math_vector_Vector3(); -__decorate([ - serializeAsVector3() -], targetCamera_TargetCamera.prototype, "rotation", void 0); -__decorate([ - serialize() -], targetCamera_TargetCamera.prototype, "speed", void 0); -__decorate([ - serializeAsMeshReference("lockedTargetId") -], targetCamera_TargetCamera.prototype, "lockedTarget", void 0); -//# sourceMappingURL=targetCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/freeCamera.js - - - - - - - -/** - * This represents a free type of camera. It can be useful in First Person Shooter game for instance. - * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera - */ -class FreeCamera extends targetCamera_TargetCamera { - /** - * Gets the input sensibility for a mouse input. (default is 2000.0) - * Higher values reduce sensitivity. - */ - get angularSensibility() { - const mouse = this.inputs.attached["mouse"]; - if (mouse) { - return mouse.angularSensibility; - } - return 0; - } - /** - * Sets the input sensibility for a mouse input. (default is 2000.0) - * Higher values reduce sensitivity. - */ - set angularSensibility(value) { - const mouse = this.inputs.attached["mouse"]; - if (mouse) { - mouse.angularSensibility = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control the forward move of the camera. - */ - get keysUp() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysUp; - } - return []; - } - set keysUp(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysUp = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control the upward move of the camera. - */ - get keysUpward() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysUpward; - } - return []; - } - set keysUpward(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysUpward = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control the backward move of the camera. - */ - get keysDown() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysDown; - } - return []; - } - set keysDown(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysDown = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control the downward move of the camera. - */ - get keysDownward() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysDownward; - } - return []; - } - set keysDownward(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysDownward = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control the left strafe move of the camera. - */ - get keysLeft() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysLeft; - } - return []; - } - set keysLeft(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysLeft = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control the right strafe move of the camera. - */ - get keysRight() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysRight; - } - return []; - } - set keysRight(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysRight = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control the left rotation move of the camera. - */ - get keysRotateLeft() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysRotateLeft; - } - return []; - } - set keysRotateLeft(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysRotateLeft = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control the right rotation move of the camera. - */ - get keysRotateRight() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysRotateRight; - } - return []; - } - set keysRotateRight(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysRotateRight = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control the up rotation move of the camera. - */ - get keysRotateUp() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysRotateUp; - } - return []; - } - set keysRotateUp(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysRotateUp = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control the down rotation move of the camera. - */ - get keysRotateDown() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysRotateDown; - } - return []; - } - set keysRotateDown(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysRotateDown = value; - } - } - /** - * Instantiates a Free Camera. - * This represents a free type of camera. It can be useful in First Person Shooter game for instance. - * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera - * @param name Define the name of the camera in the scene - * @param position Define the start position of the camera in the scene - * @param scene Define the scene the camera belongs to - * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined - */ - constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) { - super(name, position, scene, setActiveOnSceneIfNoneActive); - /** - * Define the collision ellipsoid of the camera. - * This is helpful to simulate a camera body like the player body around the camera - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera - */ - this.ellipsoid = new math_vector_Vector3(0.5, 1, 0.5); - /** - * Define an offset for the position of the ellipsoid around the camera. - * This can be helpful to determine the center of the body near the gravity center of the body - * instead of its head. - */ - this.ellipsoidOffset = new math_vector_Vector3(0, 0, 0); - /** - * Enable or disable collisions of the camera with the rest of the scene objects. - */ - this.checkCollisions = false; - /** - * Enable or disable gravity on the camera. - */ - this.applyGravity = false; - this._needMoveForGravity = false; - this._oldPosition = math_vector_Vector3.Zero(); - this._diffPosition = math_vector_Vector3.Zero(); - this._newPosition = math_vector_Vector3.Zero(); - // Collisions - this._collisionMask = -1; - this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => { - this._newPosition.copyFrom(newPosition); - this._newPosition.subtractToRef(this._oldPosition, this._diffPosition); - if (this._diffPosition.length() > engine_Engine.CollisionsEpsilon) { - this.position.addToRef(this._diffPosition, this._deferredPositionUpdate); - if (!this._deferOnly) { - this.position.copyFrom(this._deferredPositionUpdate); - } - else { - this._deferredUpdated = true; - } - // call onCollide, if defined. Note that in case of deferred update, the actual position change might happen in the next frame. - if (this.onCollide && collidedMesh) { - this.onCollide(collidedMesh); - } - } - }; - this.inputs = new FreeCameraInputsManager(this); - this.inputs.addKeyboard().addMouse(); - } - /** - * Attached controls to the current camera. - * @param ignored defines an ignored parameter kept for backward compatibility. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(ignored, noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - this.inputs.attachElement(noPreventDefault); - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - this.inputs.detachElement(); - this.cameraDirection = new math_vector_Vector3(0, 0, 0); - this.cameraRotation = new math_vector_Vector2(0, 0); - } - /** - * Define a collision mask to limit the list of object the camera can collide with - */ - get collisionMask() { - return this._collisionMask; - } - set collisionMask(mask) { - this._collisionMask = !isNaN(mask) ? mask : -1; - } - /** - * @internal - */ - _collideWithWorld(displacement) { - let globalPosition; - if (this.parent) { - globalPosition = math_vector_Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix()); - } - else { - globalPosition = this.position; - } - globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition); - this._oldPosition.addInPlace(this.ellipsoidOffset); - const coordinator = this.getScene().collisionCoordinator; - if (!this._collider) { - this._collider = coordinator.createCollider(); - } - this._collider._radius = this.ellipsoid; - this._collider.collisionMask = this._collisionMask; - //no need for clone, as long as gravity is not on. - let actualDisplacement = displacement; - //add gravity to the direction to prevent the dual-collision checking - if (this.applyGravity) { - //this prevents mending with cameraDirection, a global variable of the free camera class. - actualDisplacement = displacement.add(this.getScene().gravity); - } - coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); - } - /** @internal */ - _checkInputs() { - if (!this._localDirection) { - this._localDirection = math_vector_Vector3.Zero(); - this._transformedDirection = math_vector_Vector3.Zero(); - } - this.inputs.checkInputs(); - super._checkInputs(); - } - /** - * Enable movement without a user input. This allows gravity to always be applied. - */ - set needMoveForGravity(value) { - this._needMoveForGravity = value; - } - /** - * When true, gravity is applied whether there is user input or not. - */ - get needMoveForGravity() { - return this._needMoveForGravity; - } - /** @internal */ - _decideIfNeedsToMove() { - return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; - } - /** @internal */ - _updatePosition() { - if (this.checkCollisions && this.getScene().collisionsEnabled) { - this._collideWithWorld(this.cameraDirection); - } - else { - super._updatePosition(); - } - } - /** - * Destroy the camera and release the current resources hold by it. - */ - dispose() { - this.inputs.clear(); - super.dispose(); - } - /** - * Gets the current object class name. - * @returns the class name - */ - getClassName() { - return "FreeCamera"; - } -} -__decorate([ - serializeAsVector3() -], FreeCamera.prototype, "ellipsoid", void 0); -__decorate([ - serializeAsVector3() -], FreeCamera.prototype, "ellipsoidOffset", void 0); -__decorate([ - serialize() -], FreeCamera.prototype, "checkCollisions", void 0); -__decorate([ - serialize() -], FreeCamera.prototype, "applyGravity", void 0); -//# sourceMappingURL=freeCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/touchCamera.js - - - -node_Node.AddNodeConstructor("TouchCamera", (name, scene) => { - return () => new TouchCamera(name, math_vector_Vector3.Zero(), scene); -}); -/** - * This represents a FPS type of camera controlled by touch. - * This is like a universal camera minus the Gamepad controls. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera - */ -class TouchCamera extends FreeCamera { - /** - * Defines the touch sensibility for rotation. - * The higher the faster. - */ - get touchAngularSensibility() { - const touch = this.inputs.attached["touch"]; - if (touch) { - return touch.touchAngularSensibility; - } - return 0; - } - set touchAngularSensibility(value) { - const touch = this.inputs.attached["touch"]; - if (touch) { - touch.touchAngularSensibility = value; - } - } - /** - * Defines the touch sensibility for move. - * The higher the faster. - */ - get touchMoveSensibility() { - const touch = this.inputs.attached["touch"]; - if (touch) { - return touch.touchMoveSensibility; - } - return 0; - } - set touchMoveSensibility(value) { - const touch = this.inputs.attached["touch"]; - if (touch) { - touch.touchMoveSensibility = value; - } - } - /** - * Instantiates a new touch camera. - * This represents a FPS type of camera controlled by touch. - * This is like a universal camera minus the Gamepad controls. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera - * @param name Define the name of the camera in the scene - * @param position Define the start position of the camera in the scene - * @param scene Define the scene the camera belongs to - */ - constructor(name, position, scene) { - super(name, position, scene); - this.inputs.addTouch(); - this._setupInputs(); - } - /** - * Gets the current object class name. - * @returns the class name - */ - getClassName() { - return "TouchCamera"; - } - /** @internal */ - _setupInputs() { - const touch = this.inputs.attached["touch"]; - const mouse = this.inputs.attached["mouse"]; - if (mouse) { - mouse.touchEnabled = false; - } - else { - touch.allowMouse = true; - } - } -} -//# sourceMappingURL=touchCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/arcRotateCamera.js - - - - - - - - - - - - - - -node_Node.AddNodeConstructor("ArcRotateCamera", (name, scene) => { - return () => new ArcRotateCamera(name, 0, 0, 1.0, math_vector_Vector3.Zero(), scene); -}); -/** - * This represents an orbital type of camera. - * - * 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. - * 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. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#arc-rotate-camera - */ -class ArcRotateCamera extends targetCamera_TargetCamera { - /** - * Defines the target point of the camera. - * The camera looks towards it from the radius distance. - */ - get target() { - return this._target; - } - set target(value) { - this.setTarget(value); - } - /** - * Defines the target mesh of the camera. - * The camera looks towards it from the radius distance. - * Please note that setting a target host will disable panning. - */ - get targetHost() { - return this._targetHost; - } - set targetHost(value) { - if (value) { - this.setTarget(value); - } - } - /** - * Return the current target position of the camera. This value is expressed in local space. - * @returns the target position - */ - getTarget() { - return this.target; - } - /** - * Define the current local position of the camera in the scene - */ - get position() { - return this._position; - } - set position(newPosition) { - this.setPosition(newPosition); - } - /** - * The vector the camera should consider as up. (default is Vector3(0, 1, 0) as returned by Vector3.Up()) - * Setting this will copy the given vector to the camera's upVector, and set rotation matrices to and from Y up. - * DO NOT set the up vector using copyFrom or copyFromFloats, as this bypasses setting the above matrices. - */ - set upVector(vec) { - if (!this._upToYMatrix) { - this._yToUpMatrix = new math_vector_Matrix(); - this._upToYMatrix = new math_vector_Matrix(); - this._upVector = math_vector_Vector3.Zero(); - } - vec.normalize(); - this._upVector.copyFrom(vec); - this.setMatUp(); - } - get upVector() { - return this._upVector; - } - /** - * Sets the Y-up to camera up-vector rotation matrix, and the up-vector to Y-up rotation matrix. - */ - setMatUp() { - // from y-up to custom-up (used in _getViewMatrix) - math_vector_Matrix.RotationAlignToRef(math_vector_Vector3.UpReadOnly, this._upVector, this._yToUpMatrix); - // from custom-up to y-up (used in rebuildAnglesAndRadius) - math_vector_Matrix.RotationAlignToRef(this._upVector, math_vector_Vector3.UpReadOnly, this._upToYMatrix); - } - //-- begin properties for backward compatibility for inputs - /** - * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating. - */ - get angularSensibilityX() { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - return pointers.angularSensibilityX; - } - return 0; - } - set angularSensibilityX(value) { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - pointers.angularSensibilityX = value; - } - } - /** - * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating. - */ - get angularSensibilityY() { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - return pointers.angularSensibilityY; - } - return 0; - } - set angularSensibilityY(value) { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - pointers.angularSensibilityY = value; - } - } - /** - * Gets or Set the pointer pinch precision or how fast is the camera zooming. - */ - get pinchPrecision() { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - return pointers.pinchPrecision; - } - return 0; - } - set pinchPrecision(value) { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - pointers.pinchPrecision = value; - } - } - /** - * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming. - * It will be used instead of pinchDeltaPrecision if different from 0. - * It defines the percentage of current camera.radius to use as delta when pinch zoom is used. - */ - get pinchDeltaPercentage() { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - return pointers.pinchDeltaPercentage; - } - return 0; - } - set pinchDeltaPercentage(value) { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - pointers.pinchDeltaPercentage = value; - } - } - /** - * Gets or Set the pointer use natural pinch zoom to override the pinch precision - * and pinch delta percentage. - * When useNaturalPinchZoom is true, multi touch zoom will zoom in such - * that any object in the plane at the camera's target point will scale - * perfectly with finger motion. - */ - get useNaturalPinchZoom() { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - return pointers.useNaturalPinchZoom; - } - return false; - } - set useNaturalPinchZoom(value) { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - pointers.useNaturalPinchZoom = value; - } - } - /** - * Gets or Set the pointer panning sensibility or how fast is the camera moving. - */ - get panningSensibility() { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - return pointers.panningSensibility; - } - return 0; - } - set panningSensibility(value) { - const pointers = this.inputs.attached["pointers"]; - if (pointers) { - pointers.panningSensibility = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control beta angle in a positive direction. - */ - get keysUp() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysUp; - } - return []; - } - set keysUp(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysUp = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control beta angle in a negative direction. - */ - get keysDown() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysDown; - } - return []; - } - set keysDown(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysDown = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction. - */ - get keysLeft() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysLeft; - } - return []; - } - set keysLeft(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysLeft = value; - } - } - /** - * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction. - */ - get keysRight() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysRight; - } - return []; - } - set keysRight(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysRight = value; - } - } - /** - * Gets or Set the mouse wheel precision or how fast is the camera zooming. - */ - get wheelPrecision() { - const mousewheel = this.inputs.attached["mousewheel"]; - if (mousewheel) { - return mousewheel.wheelPrecision; - } - return 0; - } - set wheelPrecision(value) { - const mousewheel = this.inputs.attached["mousewheel"]; - if (mousewheel) { - mousewheel.wheelPrecision = value; - } - } - /** - * Gets or Set the boolean value that controls whether or not the mouse wheel - * zooms to the location of the mouse pointer or not. The default is false. - */ - get zoomToMouseLocation() { - const mousewheel = this.inputs.attached["mousewheel"]; - if (mousewheel) { - return mousewheel.zoomToMouseLocation; - } - return false; - } - set zoomToMouseLocation(value) { - const mousewheel = this.inputs.attached["mousewheel"]; - if (mousewheel) { - mousewheel.zoomToMouseLocation = value; - } - } - /** - * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming. - * It will be used instead of pinchDeltaPrecision if different from 0. - * It defines the percentage of current camera.radius to use as delta when pinch zoom is used. - */ - get wheelDeltaPercentage() { - const mousewheel = this.inputs.attached["mousewheel"]; - if (mousewheel) { - return mousewheel.wheelDeltaPercentage; - } - return 0; - } - set wheelDeltaPercentage(value) { - const mousewheel = this.inputs.attached["mousewheel"]; - if (mousewheel) { - mousewheel.wheelDeltaPercentage = value; - } - } - /** - * Gets the bouncing behavior of the camera if it has been enabled. - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior - */ - get bouncingBehavior() { - return this._bouncingBehavior; - } - /** - * Defines if the bouncing behavior of the camera is enabled on the camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior - */ - get useBouncingBehavior() { - return this._bouncingBehavior != null; - } - set useBouncingBehavior(value) { - if (value === this.useBouncingBehavior) { - return; - } - if (value) { - this._bouncingBehavior = new BouncingBehavior(); - this.addBehavior(this._bouncingBehavior); - } - else if (this._bouncingBehavior) { - this.removeBehavior(this._bouncingBehavior); - this._bouncingBehavior = null; - } - } - /** - * Gets the framing behavior of the camera if it has been enabled. - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior - */ - get framingBehavior() { - return this._framingBehavior; - } - /** - * Defines if the framing behavior of the camera is enabled on the camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior - */ - get useFramingBehavior() { - return this._framingBehavior != null; - } - set useFramingBehavior(value) { - if (value === this.useFramingBehavior) { - return; - } - if (value) { - this._framingBehavior = new FramingBehavior(); - this.addBehavior(this._framingBehavior); - } - else if (this._framingBehavior) { - this.removeBehavior(this._framingBehavior); - this._framingBehavior = null; - } - } - /** - * Gets the auto rotation behavior of the camera if it has been enabled. - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior - */ - get autoRotationBehavior() { - return this._autoRotationBehavior; - } - /** - * Defines if the auto rotation behavior of the camera is enabled on the camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior - */ - get useAutoRotationBehavior() { - return this._autoRotationBehavior != null; - } - set useAutoRotationBehavior(value) { - if (value === this.useAutoRotationBehavior) { - return; - } - if (value) { - this._autoRotationBehavior = new AutoRotationBehavior(); - this.addBehavior(this._autoRotationBehavior); - } - else if (this._autoRotationBehavior) { - this.removeBehavior(this._autoRotationBehavior); - this._autoRotationBehavior = null; - } - } - /** - * Instantiates a new ArcRotateCamera in a given scene - * @param name Defines the name of the camera - * @param alpha Defines the camera rotation along the longitudinal axis - * @param beta Defines the camera rotation along the latitudinal axis - * @param radius Defines the camera distance from its target - * @param target Defines the camera target - * @param scene Defines the scene the camera belongs to - * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined - */ - constructor(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive = true) { - super(name, math_vector_Vector3.Zero(), scene, setActiveOnSceneIfNoneActive); - /** - * Current inertia value on the longitudinal axis. - * The bigger this number the longer it will take for the camera to stop. - */ - this.inertialAlphaOffset = 0; - /** - * Current inertia value on the latitudinal axis. - * The bigger this number the longer it will take for the camera to stop. - */ - this.inertialBetaOffset = 0; - /** - * Current inertia value on the radius axis. - * The bigger this number the longer it will take for the camera to stop. - */ - this.inertialRadiusOffset = 0; - /** - * Minimum allowed angle on the longitudinal axis. - * This can help limiting how the Camera is able to move in the scene. - */ - this.lowerAlphaLimit = null; - /** - * Maximum allowed angle on the longitudinal axis. - * This can help limiting how the Camera is able to move in the scene. - */ - this.upperAlphaLimit = null; - /** - * Minimum allowed angle on the latitudinal axis. - * This can help limiting how the Camera is able to move in the scene. - */ - this.lowerBetaLimit = 0.01; - /** - * Maximum allowed angle on the latitudinal axis. - * This can help limiting how the Camera is able to move in the scene. - */ - this.upperBetaLimit = Math.PI - 0.01; - /** - * Minimum allowed distance of the camera to the target (The camera can not get closer). - * This can help limiting how the Camera is able to move in the scene. - */ - this.lowerRadiusLimit = null; - /** - * Maximum allowed distance of the camera to the target (The camera can not get further). - * This can help limiting how the Camera is able to move in the scene. - */ - this.upperRadiusLimit = null; - /** - * Defines the current inertia value used during panning of the camera along the X axis. - */ - this.inertialPanningX = 0; - /** - * Defines the current inertia value used during panning of the camera along the Y axis. - */ - this.inertialPanningY = 0; - /** - * Defines the distance used to consider the camera in pan mode vs pinch/zoom. - * Basically if your fingers moves away from more than this distance you will be considered - * in pinch mode. - */ - this.pinchToPanMaxDistance = 20; - /** - * Defines the maximum distance the camera can pan. - * This could help keeping the camera always in your scene. - */ - this.panningDistanceLimit = null; - /** - * Defines the target of the camera before panning. - */ - this.panningOriginTarget = math_vector_Vector3.Zero(); - /** - * Defines the value of the inertia used during panning. - * 0 would mean stop inertia and one would mean no deceleration at all. - */ - this.panningInertia = 0.9; - //-- end properties for backward compatibility for inputs - /** - * Defines how much the radius should be scaled while zooming on a particular mesh (through the zoomOn function) - */ - this.zoomOnFactor = 1; - /** - * Defines a screen offset for the camera position. - */ - this.targetScreenOffset = math_vector_Vector2.Zero(); - /** - * Allows the camera to be completely reversed. - * If false the camera can not arrive upside down. - */ - this.allowUpsideDown = true; - /** - * Define if double tap/click is used to restore the previously saved state of the camera. - */ - this.useInputToRestoreState = true; - /** @internal */ - this._viewMatrix = new math_vector_Matrix(); - /** - * Defines the allowed panning axis. - */ - this.panningAxis = new math_vector_Vector3(1, 1, 0); - this._transformedDirection = new math_vector_Vector3(); - /** - * Defines if camera will eliminate transform on y axis. - */ - this.mapPanning = false; - /** - * Observable triggered when the mesh target has been changed on the camera. - */ - this.onMeshTargetChangedObservable = new observable_Observable(); - /** - * Defines whether the camera should check collision with the objects oh the scene. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#how-can-i-do-this- - */ - this.checkCollisions = false; - /** - * Defines the collision radius of the camera. - * This simulates a sphere around the camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera - */ - this.collisionRadius = new math_vector_Vector3(0.5, 0.5, 0.5); - this._previousPosition = math_vector_Vector3.Zero(); - this._collisionVelocity = math_vector_Vector3.Zero(); - this._newPosition = math_vector_Vector3.Zero(); - this._computationVector = math_vector_Vector3.Zero(); - this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => { - if (!collidedMesh) { - this._previousPosition.copyFrom(this._position); - } - else { - this.setPosition(newPosition); - if (this.onCollide) { - this.onCollide(collidedMesh); - } - } - // Recompute because of constraints - const cosa = Math.cos(this.alpha); - const sina = Math.sin(this.alpha); - const cosb = Math.cos(this.beta); - let sinb = Math.sin(this.beta); - if (sinb === 0) { - sinb = 0.0001; - } - const target = this._getTargetPosition(); - this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb); - target.addToRef(this._computationVector, this._newPosition); - this._position.copyFrom(this._newPosition); - let up = this.upVector; - if (this.allowUpsideDown && this.beta < 0) { - up = up.clone(); - up = up.negate(); - } - this._computeViewMatrix(this._position, target, up); - this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x); - this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y); - this._collisionTriggered = false; - }; - this._target = math_vector_Vector3.Zero(); - if (target) { - this.setTarget(target); - } - this.alpha = alpha; - this.beta = beta; - this.radius = radius; - this.getViewMatrix(); - this.inputs = new ArcRotateCameraInputsManager(this); - this.inputs.addKeyboard().addMouseWheel().addPointers(); - } - // Cache - /** @internal */ - _initCache() { - super._initCache(); - this._cache._target = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - this._cache.alpha = undefined; - this._cache.beta = undefined; - this._cache.radius = undefined; - this._cache.targetScreenOffset = math_vector_Vector2.Zero(); - } - /** - * @internal - */ - _updateCache(ignoreParentClass) { - if (!ignoreParentClass) { - 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 pos = this._targetHost.getAbsolutePosition(); - if (this._targetBoundingCenter) { - pos.addToRef(this._targetBoundingCenter, this._target); - } - else { - this._target.copyFrom(pos); - } - } - const lockedTargetPosition = this._getLockedTargetPosition(); - if (lockedTargetPosition) { - return lockedTargetPosition; - } - return this._target; - } - /** - * Stores the current state of the camera (alpha, beta, radius and target) - * @returns the camera itself - */ - storeState() { - this._storedAlpha = this.alpha; - this._storedBeta = this.beta; - this._storedRadius = this.radius; - this._storedTarget = this._getTargetPosition().clone(); - this._storedTargetScreenOffset = this.targetScreenOffset.clone(); - return super.storeState(); - } - /** - * @internal - * Restored camera state. You must call storeState() first - */ - _restoreStateValues() { - if (!super._restoreStateValues()) { - return false; - } - 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; - return true; - } - // Synchronized - /** @internal */ - _isSynchronizedViewMatrix() { - if (!super._isSynchronizedViewMatrix()) { - return false; - } - return (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)); - } - /** - * Attached controls to the current camera. - * @param ignored defines an ignored parameter kept for backward compatibility. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - * @param useCtrlForPanning Defines whether ctrl is used for panning within the controls - * @param panningMouseButton Defines whether panning is allowed through mouse click button - */ - attachControl(ignored, noPreventDefault, useCtrlForPanning = true, panningMouseButton = 2) { - // eslint-disable-next-line prefer-rest-params - const args = arguments; - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(args); - this._useCtrlForPanning = useCtrlForPanning; - this._panningMouseButton = panningMouseButton; - // backwards compatibility - if (typeof args[0] === "boolean") { - if (args.length > 1) { - this._useCtrlForPanning = args[1]; - } - if (args.length > 2) { - this._panningMouseButton = args[2]; - } - } - this.inputs.attachElement(noPreventDefault); - this._reset = () => { - this.inertialAlphaOffset = 0; - this.inertialBetaOffset = 0; - this.inertialRadiusOffset = 0; - this.inertialPanningX = 0; - this.inertialPanningY = 0; - }; - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - this.inputs.detachElement(); - if (this._reset) { - this._reset(); - } - } - /** @internal */ - _checkInputs() { - //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called. - if (this._collisionTriggered) { - return; - } - this.inputs.checkInputs(); - // Inertia - if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) { - const directionModifier = this.invertRotation ? -1 : 1; - let inertialAlphaOffset = this.inertialAlphaOffset; - if (this.beta <= 0) { - inertialAlphaOffset *= -1; - } - if (this.getScene().useRightHandedSystem) { - inertialAlphaOffset *= -1; - } - if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) { - inertialAlphaOffset *= -1; - } - this.alpha += inertialAlphaOffset * directionModifier; - this.beta += this.inertialBetaOffset * directionModifier; - this.radius -= this.inertialRadiusOffset; - this.inertialAlphaOffset *= this.inertia; - this.inertialBetaOffset *= this.inertia; - this.inertialRadiusOffset *= this.inertia; - if (Math.abs(this.inertialAlphaOffset) < math_constants_Epsilon) { - this.inertialAlphaOffset = 0; - } - if (Math.abs(this.inertialBetaOffset) < math_constants_Epsilon) { - this.inertialBetaOffset = 0; - } - if (Math.abs(this.inertialRadiusOffset) < this.speed * math_constants_Epsilon) { - this.inertialRadiusOffset = 0; - } - } - // Panning inertia - if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) { - const localDirection = new math_vector_Vector3(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY); - this._viewMatrix.invertToRef(this._cameraTransformMatrix); - localDirection.multiplyInPlace(this.panningAxis); - math_vector_Vector3.TransformNormalToRef(localDirection, this._cameraTransformMatrix, this._transformedDirection); - // Eliminate y if mapPanning is enabled - if (this.mapPanning || !this.panningAxis.y) { - this._transformedDirection.y = 0; - } - if (!this._targetHost) { - if (this.panningDistanceLimit) { - this._transformedDirection.addInPlace(this._target); - const distanceSquared = math_vector_Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget); - if (distanceSquared <= this.panningDistanceLimit * this.panningDistanceLimit) { - this._target.copyFrom(this._transformedDirection); - } - } - else { - this._target.addInPlace(this._transformedDirection); - } - } - this.inertialPanningX *= this.panningInertia; - this.inertialPanningY *= this.panningInertia; - if (Math.abs(this.inertialPanningX) < this.speed * math_constants_Epsilon) { - this.inertialPanningX = 0; - } - if (Math.abs(this.inertialPanningY) < this.speed * math_constants_Epsilon) { - this.inertialPanningY = 0; - } - } - // Limits - this._checkLimits(); - super._checkInputs(); - } - _checkLimits() { - if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) { - if (this.allowUpsideDown && this.beta > Math.PI) { - this.beta = this.beta - 2 * Math.PI; - } - } - else { - if (this.beta < this.lowerBetaLimit) { - this.beta = this.lowerBetaLimit; - } - } - if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) { - if (this.allowUpsideDown && this.beta < -Math.PI) { - this.beta = this.beta + 2 * Math.PI; - } - } - else { - if (this.beta > this.upperBetaLimit) { - this.beta = this.upperBetaLimit; - } - } - if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) { - this.alpha = this.lowerAlphaLimit; - } - if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) { - this.alpha = this.upperAlphaLimit; - } - if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) { - this.radius = this.lowerRadiusLimit; - this.inertialRadiusOffset = 0; - } - if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) { - this.radius = this.upperRadiusLimit; - this.inertialRadiusOffset = 0; - } - } - /** - * Rebuilds angles (alpha, beta) and radius from the give position and target - */ - rebuildAnglesAndRadius() { - this._position.subtractToRef(this._getTargetPosition(), this._computationVector); - // need to rotate to Y up equivalent if up vector not Axis.Y - if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) { - math_vector_Vector3.TransformCoordinatesToRef(this._computationVector, this._upToYMatrix, this._computationVector); - } - this.radius = this._computationVector.length(); - if (this.radius === 0) { - this.radius = 0.0001; // Just to avoid division by zero - } - // Alpha - const previousAlpha = this.alpha; - if (this._computationVector.x === 0 && this._computationVector.z === 0) { - this.alpha = Math.PI / 2; // avoid division by zero when looking along up axis, and set to acos(0) - } - else { - this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2))); - } - if (this._computationVector.z < 0) { - this.alpha = 2 * Math.PI - this.alpha; - } - // Calculate the number of revolutions between the new and old alpha values. - const alphaCorrectionTurns = Math.round((previousAlpha - this.alpha) / (2.0 * Math.PI)); - // Adjust alpha so that its numerical representation is the closest one to the old value. - this.alpha += alphaCorrectionTurns * 2.0 * Math.PI; - // Beta - this.beta = Math.acos(this._computationVector.y / this.radius); - this._checkLimits(); - } - /** - * Use a position to define the current camera related information like alpha, beta and radius - * @param position Defines the position to set the camera at - */ - setPosition(position) { - if (this._position.equals(position)) { - return; - } - this._position.copyFrom(position); - this.rebuildAnglesAndRadius(); - } - /** - * Defines the target the camera should look at. - * This will automatically adapt alpha beta and radius to fit within the new target. - * Please note that setting a target as a mesh will disable panning. - * @param target Defines the new target as a Vector or a mesh - * @param toBoundingCenter In case of a mesh target, defines whether to target the mesh position or its bounding information center - * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim) - * @param cloneAlphaBetaRadius If true, replicate the current setup (alpha, beta, radius) on the new target - */ - setTarget(target, toBoundingCenter = false, allowSamePosition = false, cloneAlphaBetaRadius = false) { - var _a; - cloneAlphaBetaRadius = (_a = this.overrideCloneAlphaBetaRadius) !== null && _a !== void 0 ? _a : cloneAlphaBetaRadius; - if (target.getBoundingInfo) { - if (toBoundingCenter) { - this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone(); - } - else { - this._targetBoundingCenter = null; - } - target.computeWorldMatrix(); - this._targetHost = target; - this._target = this._getTargetPosition(); - this.onMeshTargetChangedObservable.notifyObservers(this._targetHost); - } - else { - const newTarget = target; - const currentTarget = this._getTargetPosition(); - if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) { - return; - } - this._targetHost = null; - this._target = newTarget; - this._targetBoundingCenter = null; - this.onMeshTargetChangedObservable.notifyObservers(null); - } - if (!cloneAlphaBetaRadius) { - this.rebuildAnglesAndRadius(); - } - } - /** @internal */ - _getViewMatrix() { - // Compute - const cosa = Math.cos(this.alpha); - const sina = Math.sin(this.alpha); - const cosb = Math.cos(this.beta); - let sinb = Math.sin(this.beta); - if (sinb === 0) { - sinb = 0.0001; - } - if (this.radius === 0) { - this.radius = 0.0001; // Just to avoid division by zero - } - const target = this._getTargetPosition(); - this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb); - // Rotate according to up vector - if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) { - math_vector_Vector3.TransformCoordinatesToRef(this._computationVector, this._yToUpMatrix, this._computationVector); - } - target.addToRef(this._computationVector, this._newPosition); - if (this.getScene().collisionsEnabled && this.checkCollisions) { - const coordinator = this.getScene().collisionCoordinator; - if (!this._collider) { - this._collider = coordinator.createCollider(); - } - this._collider._radius = this.collisionRadius; - this._newPosition.subtractToRef(this._position, this._collisionVelocity); - this._collisionTriggered = true; - coordinator.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); - } - else { - this._position.copyFrom(this._newPosition); - let up = this.upVector; - if (this.allowUpsideDown && sinb < 0) { - up = up.negate(); - } - this._computeViewMatrix(this._position, target, up); - this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x); - this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y); - } - this._currentTarget = target; - return this._viewMatrix; - } - /** - * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport. - * @param meshes Defines the mesh to zoom on - * @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) - */ - zoomOn(meshes, doNotUpdateMaxZ = false) { - meshes = meshes || this.getScene().meshes; - const minMaxVector = mesh_Mesh.MinMax(meshes); - const distance = math_vector_Vector3.Distance(minMaxVector.min, minMaxVector.max); - this.radius = distance * this.zoomOnFactor; - this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ); - } - /** - * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius. - * The target will be changed but the radius - * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on - * @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) - */ - focusOn(meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ = false) { - let meshesOrMinMaxVector; - let distance; - if (meshesOrMinMaxVectorAndDistance.min === undefined) { - // meshes - const meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes; - meshesOrMinMaxVector = mesh_Mesh.MinMax(meshes); - distance = math_vector_Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max); - } - else { - //minMaxVector and distance - const minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance; - meshesOrMinMaxVector = minMaxVectorAndDistance; - distance = minMaxVectorAndDistance.distance; - } - this._target = mesh_Mesh.Center(meshesOrMinMaxVector); - if (!doNotUpdateMaxZ) { - this.maxZ = distance * 2; - } - } - /** - * @override - * Override Camera.createRigCamera - */ - createRigCamera(name, cameraIndex) { - let alphaShift = 0; - switch (this.cameraRigMode) { - case camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH: - case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: - case camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER: - case camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED: - case camera_Camera.RIG_MODE_VR: - alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1); - break; - case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: - alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1); - break; - } - const rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene()); - rigCam._cameraRigParams = {}; - rigCam.isRigCamera = true; - rigCam.rigParent = this; - rigCam.upVector = this.upVector; - rigCam.mode = this.mode; - rigCam.orthoLeft = this.orthoLeft; - rigCam.orthoRight = this.orthoRight; - rigCam.orthoBottom = this.orthoBottom; - rigCam.orthoTop = this.orthoTop; - return rigCam; - } - /** - * @internal - * @override - * Override Camera._updateRigCameras - */ - _updateRigCameras() { - const camLeft = this._rigCameras[0]; - const camRight = this._rigCameras[1]; - camLeft.beta = camRight.beta = this.beta; - switch (this.cameraRigMode) { - case camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH: - case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: - case camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER: - case camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED: - case camera_Camera.RIG_MODE_VR: - camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle; - camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle; - break; - case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: - camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle; - camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle; - break; - } - super._updateRigCameras(); - } - /** - * Destroy the camera and release the current resources hold by it. - */ - dispose() { - this.inputs.clear(); - super.dispose(); - } - /** - * Gets the current object class name. - * @returns the class name - */ - getClassName() { - return "ArcRotateCamera"; - } -} -__decorate([ - serialize() -], ArcRotateCamera.prototype, "alpha", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "beta", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "radius", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "overrideCloneAlphaBetaRadius", void 0); -__decorate([ - serializeAsVector3("target") -], ArcRotateCamera.prototype, "_target", void 0); -__decorate([ - serializeAsMeshReference("targetHost") -], ArcRotateCamera.prototype, "_targetHost", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "inertialBetaOffset", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "upperAlphaLimit", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "lowerBetaLimit", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "upperBetaLimit", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "upperRadiusLimit", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "inertialPanningX", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "inertialPanningY", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "panningDistanceLimit", void 0); -__decorate([ - serializeAsVector3() -], ArcRotateCamera.prototype, "panningOriginTarget", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "panningInertia", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "zoomToMouseLocation", null); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "zoomOnFactor", void 0); -__decorate([ - serializeAsVector2() -], ArcRotateCamera.prototype, "targetScreenOffset", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "allowUpsideDown", void 0); -__decorate([ - serialize() -], ArcRotateCamera.prototype, "useInputToRestoreState", void 0); -//# sourceMappingURL=arcRotateCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/deviceOrientationCamera.js - - - - - -node_Node.AddNodeConstructor("DeviceOrientationCamera", (name, scene) => { - return () => new DeviceOrientationCamera(name, math_vector_Vector3.Zero(), scene); -}); -// We're mainly based on the logic defined into the FreeCamera code -/** - * This is a camera specifically designed to react to device orientation events such as a modern mobile device - * being tilted forward or back and left or right. - */ -class DeviceOrientationCamera extends FreeCamera { - /** - * Creates a new device orientation camera - * @param name The name of the camera - * @param position The start position camera - * @param scene The scene the camera belongs to - */ - constructor(name, position, scene) { - super(name, position, scene); - this._tmpDragQuaternion = new math_vector_Quaternion(); - this._disablePointerInputWhenUsingDeviceOrientation = true; - this._dragFactor = 0; - this._quaternionCache = new math_vector_Quaternion(); - this.inputs.addDeviceOrientation(); - // When the orientation sensor fires it's first event, disable mouse input - if (this.inputs._deviceOrientationInput) { - this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(() => { - if (this._disablePointerInputWhenUsingDeviceOrientation) { - if (this.inputs._mouseInput) { - this.inputs._mouseInput._allowCameraRotation = false; - this.inputs._mouseInput.onPointerMovedObservable.add((e) => { - if (this._dragFactor != 0) { - if (!this._initialQuaternion) { - this._initialQuaternion = new math_vector_Quaternion(); - } - // Rotate the initial space around the y axis to allow users to "turn around" via touch/mouse - math_vector_Quaternion.FromEulerAnglesToRef(0, e.offsetX * this._dragFactor, 0, this._tmpDragQuaternion); - this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion, this._initialQuaternion); - } - }); - } - } - }); - } - } - /** - * Gets or sets a boolean indicating that pointer input must be disabled on first orientation sensor update (Default: true) - */ - get disablePointerInputWhenUsingDeviceOrientation() { - return this._disablePointerInputWhenUsingDeviceOrientation; - } - set disablePointerInputWhenUsingDeviceOrientation(value) { - this._disablePointerInputWhenUsingDeviceOrientation = value; - } - /** - * Enabled turning on the y axis when the orientation sensor is active - * @param dragFactor the factor that controls the turn speed (default: 1/300) - */ - enableHorizontalDragging(dragFactor = 1 / 300) { - this._dragFactor = dragFactor; - } - /** - * Gets the current instance class name ("DeviceOrientationCamera"). - * This helps avoiding instanceof at run time. - * @returns the class name - */ - getClassName() { - return "DeviceOrientationCamera"; - } - /** - * @internal - * Checks and applies the current values of the inputs to the camera. (Internal use only) - */ - _checkInputs() { - super._checkInputs(); - this._quaternionCache.copyFrom(this.rotationQuaternion); - if (this._initialQuaternion) { - this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); - } - } - /** - * Reset the camera to its default orientation on the specified axis only. - * @param axis The axis to reset - */ - resetToCurrentRotation(axis = math_axis_Axis.Y) { - //can only work if this camera has a rotation quaternion already. - if (!this.rotationQuaternion) { - return; - } - if (!this._initialQuaternion) { - this._initialQuaternion = new math_vector_Quaternion(); - } - this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion); - ["x", "y", "z"].forEach((axisName) => { - if (!axis[axisName]) { - this._initialQuaternion[axisName] = 0; - } - else { - this._initialQuaternion[axisName] *= -1; - } - }); - this._initialQuaternion.normalize(); - //force rotation update - this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); - } -} -//# sourceMappingURL=deviceOrientationCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/flyCameraInputsManager.js - - - -/** - * Default Inputs manager for the FlyCamera. - * It groups all the default supported inputs for ease of use. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FlyCameraInputsManager extends CameraInputsManager { - /** - * Instantiates a new FlyCameraInputsManager. - * @param camera Defines the camera the inputs belong to. - */ - constructor(camera) { - super(camera); - } - /** - * Add keyboard input support to the input manager. - * @returns the new FlyCameraKeyboardMoveInput(). - */ - addKeyboard() { - this.add(new FlyCameraKeyboardInput()); - return this; - } - /** - * Add mouse input support to the input manager. - * @returns the new FlyCameraMouseInput(). - */ - addMouse() { - this.add(new FlyCameraMouseInput()); - return this; - } -} -//# sourceMappingURL=flyCameraInputsManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/flyCamera.js - - - - - - - -/** - * This is a flying camera, designed for 3D movement and rotation in all directions, - * such as in a 3D Space Shooter or a Flight Simulator. - */ -class FlyCamera extends targetCamera_TargetCamera { - /** - * Gets the input sensibility for mouse input. - * Higher values reduce sensitivity. - */ - get angularSensibility() { - const mouse = this.inputs.attached["mouse"]; - if (mouse) { - return mouse.angularSensibility; - } - return 0; - } - /** - * Sets the input sensibility for a mouse input. - * Higher values reduce sensitivity. - */ - set angularSensibility(value) { - const mouse = this.inputs.attached["mouse"]; - if (mouse) { - mouse.angularSensibility = value; - } - } - /** - * Get the keys for camera movement forward. - */ - get keysForward() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysForward; - } - return []; - } - /** - * Set the keys for camera movement forward. - */ - set keysForward(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysForward = value; - } - } - /** - * Get the keys for camera movement backward. - */ - get keysBackward() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysBackward; - } - return []; - } - set keysBackward(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysBackward = value; - } - } - /** - * Get the keys for camera movement up. - */ - get keysUp() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysUp; - } - return []; - } - /** - * Set the keys for camera movement up. - */ - set keysUp(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysUp = value; - } - } - /** - * Get the keys for camera movement down. - */ - get keysDown() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysDown; - } - return []; - } - /** - * Set the keys for camera movement down. - */ - set keysDown(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysDown = value; - } - } - /** - * Get the keys for camera movement left. - */ - get keysLeft() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysLeft; - } - return []; - } - /** - * Set the keys for camera movement left. - */ - set keysLeft(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysLeft = value; - } - } - /** - * Set the keys for camera movement right. - */ - get keysRight() { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - return keyboard.keysRight; - } - return []; - } - /** - * Set the keys for camera movement right. - */ - set keysRight(value) { - const keyboard = this.inputs.attached["keyboard"]; - if (keyboard) { - keyboard.keysRight = value; - } - } - /** - * Instantiates a FlyCamera. - * This is a flying camera, designed for 3D movement and rotation in all directions, - * such as in a 3D Space Shooter or a Flight Simulator. - * @param name Define the name of the camera in the scene. - * @param position Define the starting position of the camera in the scene. - * @param scene Define the scene the camera belongs to. - * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active, if no other camera has been defined as active. - */ - constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) { - super(name, position, scene, setActiveOnSceneIfNoneActive); - /** - * Define the collision ellipsoid of the camera. - * This is helpful for simulating a camera body, like a player's body. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera - */ - this.ellipsoid = new math_vector_Vector3(1, 1, 1); - /** - * Define an offset for the position of the ellipsoid around the camera. - * This can be helpful if the camera is attached away from the player's body center, - * such as at its head. - */ - this.ellipsoidOffset = new math_vector_Vector3(0, 0, 0); - /** - * Enable or disable collisions of the camera with the rest of the scene objects. - */ - this.checkCollisions = false; - /** - * Enable or disable gravity on the camera. - */ - this.applyGravity = false; - /** - * Define the current direction the camera is moving to. - */ - this.cameraDirection = math_vector_Vector3.Zero(); - /** - * Track Roll to maintain the wanted Rolling when looking around. - */ - this._trackRoll = 0; - /** - * Slowly correct the Roll to its original value after a Pitch+Yaw rotation. - */ - this.rollCorrect = 100; - /** - * Mimic a banked turn, Rolling the camera when Yawing. - * It's recommended to use rollCorrect = 10 for faster banking correction. - */ - this.bankedTurn = false; - /** - * Limit in radians for how much Roll banking will add. (Default: 90°) - */ - this.bankedTurnLimit = Math.PI / 2; - /** - * Value of 0 disables the banked Roll. - * Value of 1 is equal to the Yaw angle in radians. - */ - this.bankedTurnMultiplier = 1; - this._needMoveForGravity = false; - this._oldPosition = math_vector_Vector3.Zero(); - this._diffPosition = math_vector_Vector3.Zero(); - this._newPosition = math_vector_Vector3.Zero(); - // Collisions. - this._collisionMask = -1; - /** - * @internal - */ - this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => { - const updatePosition = (newPos) => { - this._newPosition.copyFrom(newPos); - this._newPosition.subtractToRef(this._oldPosition, this._diffPosition); - if (this._diffPosition.length() > engine_Engine.CollisionsEpsilon) { - this.position.addInPlace(this._diffPosition); - if (this.onCollide && collidedMesh) { - this.onCollide(collidedMesh); - } - } - }; - updatePosition(newPosition); - }; - this.inputs = new FlyCameraInputsManager(this); - this.inputs.addKeyboard().addMouse(); - } - /** - * Attached controls to the current camera. - * @param ignored defines an ignored parameter kept for backward compatibility. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(ignored, noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - this.inputs.attachElement(noPreventDefault); - } - /** - * Detach a control from the HTML DOM element. - * The camera will stop reacting to that input. - */ - detachControl() { - this.inputs.detachElement(); - this.cameraDirection = new math_vector_Vector3(0, 0, 0); - } - /** - * Get the mask that the camera ignores in collision events. - */ - get collisionMask() { - return this._collisionMask; - } - /** - * Set the mask that the camera ignores in collision events. - */ - set collisionMask(mask) { - this._collisionMask = !isNaN(mask) ? mask : -1; - } - /** - * @internal - */ - _collideWithWorld(displacement) { - let globalPosition; - if (this.parent) { - globalPosition = math_vector_Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix()); - } - else { - globalPosition = this.position; - } - globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition); - this._oldPosition.addInPlace(this.ellipsoidOffset); - const coordinator = this.getScene().collisionCoordinator; - if (!this._collider) { - this._collider = coordinator.createCollider(); - } - this._collider._radius = this.ellipsoid; - this._collider.collisionMask = this._collisionMask; - // No need for clone, as long as gravity is not on. - let actualDisplacement = displacement; - // Add gravity to direction to prevent dual-collision checking. - if (this.applyGravity) { - // This prevents mending with cameraDirection, a global variable of the fly camera class. - actualDisplacement = displacement.add(this.getScene().gravity); - } - coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); - } - /** @internal */ - _checkInputs() { - if (!this._localDirection) { - this._localDirection = math_vector_Vector3.Zero(); - this._transformedDirection = math_vector_Vector3.Zero(); - } - this.inputs.checkInputs(); - super._checkInputs(); - } - /** - * Enable movement without a user input. This allows gravity to always be applied. - */ - set needMoveForGravity(value) { - this._needMoveForGravity = value; - } - /** - * When true, gravity is applied whether there is user input or not. - */ - get needMoveForGravity() { - return this._needMoveForGravity; - } - /** @internal */ - _decideIfNeedsToMove() { - return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; - } - /** @internal */ - _updatePosition() { - if (this.checkCollisions && this.getScene().collisionsEnabled) { - this._collideWithWorld(this.cameraDirection); - } - else { - super._updatePosition(); - } - } - /** - * Restore the Roll to its target value at the rate specified. - * @param rate - Higher means slower restoring. - * @internal - */ - restoreRoll(rate) { - const limit = this._trackRoll; // Target Roll. - const z = this.rotation.z; // Current Roll. - const delta = limit - z; // Difference in Roll. - const minRad = 0.001; // Tenth of a radian is a barely noticable difference. - // If the difference is noticable, restore the Roll. - if (Math.abs(delta) >= minRad) { - // Change Z rotation towards the target Roll. - this.rotation.z += delta / rate; - // Match when near enough. - if (Math.abs(limit - this.rotation.z) <= minRad) { - this.rotation.z = limit; - } - } - } - /** - * Destroy the camera and release the current resources held by it. - */ - dispose() { - this.inputs.clear(); - super.dispose(); - } - /** - * Get the current object class name. - * @returns the class name. - */ - getClassName() { - return "FlyCamera"; - } -} -__decorate([ - serializeAsVector3() -], FlyCamera.prototype, "ellipsoid", void 0); -__decorate([ - serializeAsVector3() -], FlyCamera.prototype, "ellipsoidOffset", void 0); -__decorate([ - serialize() -], FlyCamera.prototype, "checkCollisions", void 0); -__decorate([ - serialize() -], FlyCamera.prototype, "applyGravity", void 0); -//# sourceMappingURL=flyCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/followCameraInputsManager.js - - - - -/** - * Default Inputs manager for the FollowCamera. - * It groups all the default supported inputs for ease of use. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs - */ -class FollowCameraInputsManager extends CameraInputsManager { - /** - * Instantiates a new FollowCameraInputsManager. - * @param camera Defines the camera the inputs belong to - */ - constructor(camera) { - super(camera); - } - /** - * Add keyboard input support to the input manager. - * @returns the current input manager - */ - addKeyboard() { - this.add(new FollowCameraKeyboardMoveInput()); - return this; - } - /** - * Add mouse wheel input support to the input manager. - * @returns the current input manager - */ - addMouseWheel() { - this.add(new FollowCameraMouseWheelInput()); - return this; - } - /** - * Add pointers input support to the input manager. - * @returns the current input manager - */ - addPointers() { - this.add(new FollowCameraPointersInput()); - return this; - } - /** - * Add orientation input support to the input manager. - * @returns the current input manager - */ - addVRDeviceOrientation() { - console.warn("DeviceOrientation support not yet implemented for FollowCamera."); - return this; - } -} -//# sourceMappingURL=followCameraInputsManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/followCamera.js - - - - - - - -node_Node.AddNodeConstructor("FollowCamera", (name, scene) => { - return () => new FollowCamera(name, math_vector_Vector3.Zero(), scene); -}); -node_Node.AddNodeConstructor("ArcFollowCamera", (name, scene) => { - return () => new ArcFollowCamera(name, 0, 0, 1.0, null, scene); -}); -/** - * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and - * an arc rotate version arcFollowCamera are available. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera - */ -class FollowCamera extends targetCamera_TargetCamera { - /** - * Instantiates the follow camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera - * @param name Define the name of the camera in the scene - * @param position Define the position of the camera - * @param scene Define the scene the camera belong to - * @param lockedTarget Define the target of the camera - */ - constructor(name, position, scene, lockedTarget = null) { - super(name, position, scene); - /** - * Distance the follow camera should follow an object at - */ - this.radius = 12; - /** - * Minimum allowed distance of the camera to the axis of rotation - * (The camera can not get closer). - * This can help limiting how the Camera is able to move in the scene. - */ - this.lowerRadiusLimit = null; - /** - * Maximum allowed distance of the camera to the axis of rotation - * (The camera can not get further). - * This can help limiting how the Camera is able to move in the scene. - */ - this.upperRadiusLimit = null; - /** - * Define a rotation offset between the camera and the object it follows - */ - this.rotationOffset = 0; - /** - * Minimum allowed angle to camera position relative to target object. - * This can help limiting how the Camera is able to move in the scene. - */ - this.lowerRotationOffsetLimit = null; - /** - * Maximum allowed angle to camera position relative to target object. - * This can help limiting how the Camera is able to move in the scene. - */ - this.upperRotationOffsetLimit = null; - /** - * Define a height offset between the camera and the object it follows. - * It can help following an object from the top (like a car chasing a plane) - */ - this.heightOffset = 4; - /** - * Minimum allowed height of camera position relative to target object. - * This can help limiting how the Camera is able to move in the scene. - */ - this.lowerHeightOffsetLimit = null; - /** - * Maximum allowed height of camera position relative to target object. - * This can help limiting how the Camera is able to move in the scene. - */ - this.upperHeightOffsetLimit = null; - /** - * Define how fast the camera can accelerate to follow it s target. - */ - this.cameraAcceleration = 0.05; - /** - * Define the speed limit of the camera following an object. - */ - this.maxCameraSpeed = 20; - this.lockedTarget = lockedTarget; - this.inputs = new FollowCameraInputsManager(this); - this.inputs.addKeyboard().addMouseWheel().addPointers(); - // Uncomment the following line when the relevant handlers have been implemented. - // this.inputs.addKeyboard().addMouseWheel().addPointers().addVRDeviceOrientation(); - } - _follow(cameraTarget) { - if (!cameraTarget) { - return; - } - const rotMatrix = math_vector_TmpVectors.Matrix[0]; - cameraTarget.absoluteRotationQuaternion.toRotationMatrix(rotMatrix); - const yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]); - const radians = tools_Tools.ToRadians(this.rotationOffset) + yRotation; - const targetPosition = cameraTarget.getAbsolutePosition(); - const targetX = targetPosition.x + Math.sin(radians) * this.radius; - const targetZ = targetPosition.z + Math.cos(radians) * this.radius; - const dx = targetX - this.position.x; - const dy = targetPosition.y + this.heightOffset - this.position.y; - const dz = targetZ - this.position.z; - let vx = dx * this.cameraAcceleration * 2; //this is set to .05 - let vy = dy * this.cameraAcceleration; - let vz = dz * this.cameraAcceleration * 2; - if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) { - vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; - } - if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) { - vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; - } - if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) { - vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; - } - this.position = new math_vector_Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz); - this.setTarget(targetPosition); - } - /** - * Attached controls to the current camera. - * @param ignored defines an ignored parameter kept for backward compatibility. - * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) - */ - attachControl(ignored, noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - this.inputs.attachElement(noPreventDefault); - this._reset = () => { }; - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - this.inputs.detachElement(); - if (this._reset) { - this._reset(); - } - } - /** @internal */ - _checkInputs() { - this.inputs.checkInputs(); - this._checkLimits(); - super._checkInputs(); - if (this.lockedTarget) { - this._follow(this.lockedTarget); - } - } - _checkLimits() { - if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) { - this.radius = this.lowerRadiusLimit; - } - if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) { - this.radius = this.upperRadiusLimit; - } - if (this.lowerHeightOffsetLimit !== null && this.heightOffset < this.lowerHeightOffsetLimit) { - this.heightOffset = this.lowerHeightOffsetLimit; - } - if (this.upperHeightOffsetLimit !== null && this.heightOffset > this.upperHeightOffsetLimit) { - this.heightOffset = this.upperHeightOffsetLimit; - } - if (this.lowerRotationOffsetLimit !== null && this.rotationOffset < this.lowerRotationOffsetLimit) { - this.rotationOffset = this.lowerRotationOffsetLimit; - } - if (this.upperRotationOffsetLimit !== null && this.rotationOffset > this.upperRotationOffsetLimit) { - this.rotationOffset = this.upperRotationOffsetLimit; - } - } - /** - * Gets the camera class name. - * @returns the class name - */ - getClassName() { - return "FollowCamera"; - } -} -__decorate([ - serialize() -], FollowCamera.prototype, "radius", void 0); -__decorate([ - serialize() -], FollowCamera.prototype, "lowerRadiusLimit", void 0); -__decorate([ - serialize() -], FollowCamera.prototype, "upperRadiusLimit", void 0); -__decorate([ - serialize() -], FollowCamera.prototype, "rotationOffset", void 0); -__decorate([ - serialize() -], FollowCamera.prototype, "lowerRotationOffsetLimit", void 0); -__decorate([ - serialize() -], FollowCamera.prototype, "upperRotationOffsetLimit", void 0); -__decorate([ - serialize() -], FollowCamera.prototype, "heightOffset", void 0); -__decorate([ - serialize() -], FollowCamera.prototype, "lowerHeightOffsetLimit", void 0); -__decorate([ - serialize() -], FollowCamera.prototype, "upperHeightOffsetLimit", void 0); -__decorate([ - serialize() -], FollowCamera.prototype, "cameraAcceleration", void 0); -__decorate([ - serialize() -], FollowCamera.prototype, "maxCameraSpeed", void 0); -__decorate([ - serializeAsMeshReference("lockedTargetId") -], FollowCamera.prototype, "lockedTarget", void 0); -/** - * Arc Rotate version of the follow camera. - * It still follows a Defined mesh but in an Arc Rotate Camera fashion. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera - */ -class ArcFollowCamera extends targetCamera_TargetCamera { - /** - * Instantiates a new ArcFollowCamera - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera - * @param name Define the name of the camera - * @param alpha Define the rotation angle of the camera around the longitudinal axis - * @param beta Define the rotation angle of the camera around the elevation axis - * @param radius Define the radius of the camera from its target point - * @param target Define the target of the camera - * @param scene Define the scene the camera belongs to - */ - constructor(name, - /** The longitudinal angle of the camera */ - alpha, - /** The latitudinal angle of the camera */ - beta, - /** The radius of the camera from its target */ - radius, - /** Define the camera target (the mesh it should follow) */ - target, scene) { - super(name, math_vector_Vector3.Zero(), scene); - this.alpha = alpha; - this.beta = beta; - this.radius = radius; - this._cartesianCoordinates = math_vector_Vector3.Zero(); - this.setMeshTarget(target); - } - /** - * Sets the mesh to follow with this camera. - * @param target the target to follow - */ - setMeshTarget(target) { - this._meshTarget = target; - 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 targetPosition = this._meshTarget.getAbsolutePosition(); - this.position = targetPosition.add(this._cartesianCoordinates); - this.setTarget(targetPosition); - } - /** @internal */ - _checkInputs() { - super._checkInputs(); - this._follow(); - } - /** - * Returns the class name of the object. - * It is mostly used internally for serialization purposes. - */ - getClassName() { - return "ArcFollowCamera"; - } -} -//# sourceMappingURL=followCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/Controllers/poseEnabledController.js - - - - - -/** - * Defines the types of pose enabled controllers that are supported - */ -var PoseEnabledControllerType; -(function (PoseEnabledControllerType) { - /** - * HTC Vive - */ - PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE"; - /** - * Oculus Rift - */ - PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS"; - /** - * Windows mixed reality - */ - PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS"; - /** - * Samsung gear VR - */ - PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR"; - /** - * Google Daydream - */ - PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM"; - /** - * Generic - */ - PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC"; -})(PoseEnabledControllerType || (PoseEnabledControllerType = {})); -/** - * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller) - */ -class PoseEnabledControllerHelper { - /** - * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller) - * @param vrGamepad the gamepad to initialized - * @returns a vr controller of the type the gamepad identified as - */ - static InitiateController(vrGamepad) { - for (const factory of this._ControllerFactories) { - if (factory.canCreate(vrGamepad)) { - return factory.create(vrGamepad); - } - } - if (this._DefaultControllerFactory) { - return this._DefaultControllerFactory(vrGamepad); - } - throw "The type of gamepad you are trying to load needs to be imported first or is not supported."; - } -} -/** @internal */ -PoseEnabledControllerHelper._ControllerFactories = []; -/** @internal */ -PoseEnabledControllerHelper._DefaultControllerFactory = null; -/** - * Defines the PoseEnabledController object that contains state of a vr capable controller - */ -class poseEnabledController_PoseEnabledController extends Gamepad { - /** - * @internal - */ - _disableTrackPosition(fixedPosition) { - if (this._trackPosition) { - this._calculatedPosition.copyFrom(fixedPosition); - this._trackPosition = false; - } - } - /** - * Creates a new PoseEnabledController from a gamepad - * @param browserGamepad the gamepad that the PoseEnabledController should be created from - */ - constructor(browserGamepad) { - super(browserGamepad.id, browserGamepad.index, browserGamepad); - /** - * If the controller is used in a webXR session - */ - this.isXR = false; - // Represents device position and rotation in room space. Should only be used to help calculate babylon space values - this._deviceRoomPosition = math_vector_Vector3.Zero(); - this._deviceRoomRotationQuaternion = new math_vector_Quaternion(); - /** - * The device position in babylon space - */ - this.devicePosition = math_vector_Vector3.Zero(); - /** - * The device rotation in babylon space - */ - this.deviceRotationQuaternion = new math_vector_Quaternion(); - /** - * The scale factor of the device in babylon space - */ - this.deviceScaleFactor = 1; - // Used to convert 6dof controllers to 3dof - this._trackPosition = true; - this._maxRotationDistFromHeadset = Math.PI / 5; - this._draggedRoomRotation = 0; - this._leftHandSystemQuaternion = new math_vector_Quaternion(); - /** - * Internal, matrix used to convert room space to babylon space - * @internal - */ - this._deviceToWorld = math_vector_Matrix.Identity(); - /** - * Node to be used when casting a ray from the controller - * @internal - */ - this._pointingPoseNode = null; - this._workingMatrix = math_vector_Matrix.Identity(); - /** - * @internal - */ - this._meshAttachedObservable = new observable_Observable(); - this.type = Gamepad.POSE_ENABLED; - this.controllerType = PoseEnabledControllerType.GENERIC; - this.position = math_vector_Vector3.Zero(); - this.rotationQuaternion = new math_vector_Quaternion(); - this._calculatedPosition = math_vector_Vector3.Zero(); - this._calculatedRotation = new math_vector_Quaternion(); - math_vector_Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, this._leftHandSystemQuaternion); - } - /** - * Updates the state of the pose enabled controller and mesh based on the current position and rotation of the controller - */ - update() { - super.update(); - this._updatePoseAndMesh(); - } - /** - * Updates only the pose device and mesh without doing any button event checking - */ - _updatePoseAndMesh() { - if (this.isXR) { - return; - } - const pose = this.browserGamepad.pose; - this.updateFromDevice(pose); - if (!this._trackPosition && - engineStore_EngineStore.LastCreatedScene && - engineStore_EngineStore.LastCreatedScene.activeCamera && - engineStore_EngineStore.LastCreatedScene.activeCamera.devicePosition) { - const camera = engineStore_EngineStore.LastCreatedScene.activeCamera; - camera._computeDevicePosition(); - this._deviceToWorld.setTranslation(camera.devicePosition); - if (camera.deviceRotationQuaternion) { - camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(math_vector_TmpVectors.Vector3[0]); - // Find the radian distance away that the headset is from the controllers rotation - const distanceAway = Math.atan2(Math.sin(math_vector_TmpVectors.Vector3[0].y - this._draggedRoomRotation), Math.cos(math_vector_TmpVectors.Vector3[0].y - this._draggedRoomRotation)); - if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) { - // Only rotate enouph to be within the _maxRotationDistFromHeadset - const rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset); - this._draggedRoomRotation += rotationAmount; - // Rotate controller around headset - const sin = Math.sin(-rotationAmount); - const cos = Math.cos(-rotationAmount); - this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin; - this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos; - } - } - } - math_vector_Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition); - this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix); - math_vector_Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion); - this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation); - if (this._mesh) { - this._mesh.position.copyFrom(this.devicePosition); - if (this._mesh.rotationQuaternion) { - this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion); - } - } - } - /** - * Updates the state of the pose enbaled controller based on the raw pose data from the device - * @param poseData raw pose fromthe device - */ - updateFromDevice(poseData) { - if (this.isXR) { - return; - } - if (poseData) { - this.rawPose = poseData; - if (poseData.position) { - this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]); - if (this._mesh && this._mesh.getScene().useRightHandedSystem) { - this._deviceRoomPosition.z *= -1; - } - if (this._trackPosition) { - this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition); - } - this._calculatedPosition.addInPlace(this.position); - } - const pose = this.rawPose; - if (poseData.orientation && pose.orientation && pose.orientation.length === 4) { - this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]); - if (this._mesh) { - if (this._mesh.getScene().useRightHandedSystem) { - this._deviceRoomRotationQuaternion.z *= -1; - this._deviceRoomRotationQuaternion.w *= -1; - } - else { - this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion); - } - } - // if the camera is set, rotate to the camera's rotation - this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation); - } - } - } - /** - * Attaches a mesh to the controller - * @param mesh the mesh to be attached - */ - attachToMesh(mesh) { - if (this._mesh) { - this._mesh.parent = null; - } - this._mesh = mesh; - if (this._poseControlledCamera) { - this._mesh.parent = this._poseControlledCamera; - } - if (!this._mesh.rotationQuaternion) { - this._mesh.rotationQuaternion = new math_vector_Quaternion(); - } - // 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 - if (!this.isXR) { - this._updatePoseAndMesh(); - if (this._pointingPoseNode) { - const parents = []; - let obj = this._pointingPoseNode; - while (obj.parent) { - parents.push(obj.parent); - obj = obj.parent; - } - parents.reverse().forEach((p) => { - p.computeWorldMatrix(true); - }); - } - } - this._meshAttachedObservable.notifyObservers(mesh); - } - /** - * Attaches the controllers mesh to a camera - * @param camera the camera the mesh should be attached to - */ - attachToPoseControlledCamera(camera) { - this._poseControlledCamera = camera; - if (this._mesh) { - this._mesh.parent = this._poseControlledCamera; - } - } - /** - * Disposes of the controller - */ - dispose() { - if (this._mesh) { - this._mesh.dispose(); - } - this._mesh = null; - super.dispose(); - } - /** - * The mesh that is attached to the controller - */ - get mesh() { - return this._mesh; - } - /** - * Gets the ray of the controller in the direction the controller is pointing - * @param length the length the resulting ray should be - * @returns a ray in the direction the controller is pointing - */ - getForwardRay(length = 100) { - if (!this.mesh) { - return new ray_Ray(math_vector_Vector3.Zero(), new math_vector_Vector3(0, 0, 1), length); - } - const m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix(); - const origin = m.getTranslation(); - const forward = new math_vector_Vector3(0, 0, -1); - const forwardWorld = math_vector_Vector3.TransformNormal(forward, m); - const direction = math_vector_Vector3.Normalize(forwardWorld); - return new ray_Ray(origin, direction, length); - } -} -/** - * Name of the child mesh that can be used to cast a ray from the controller - */ -poseEnabledController_PoseEnabledController.POINTING_POSE = "POINTING_POSE"; -//# sourceMappingURL=poseEnabledController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/xboxGamepad.js - - -/** - * Defines supported buttons for XBox360 compatible gamepads - */ -var Xbox360Button; -(function (Xbox360Button) { - /** A */ - Xbox360Button[Xbox360Button["A"] = 0] = "A"; - /** B */ - Xbox360Button[Xbox360Button["B"] = 1] = "B"; - /** X */ - Xbox360Button[Xbox360Button["X"] = 2] = "X"; - /** Y */ - Xbox360Button[Xbox360Button["Y"] = 3] = "Y"; - /** Left button */ - Xbox360Button[Xbox360Button["LB"] = 4] = "LB"; - /** Right button */ - Xbox360Button[Xbox360Button["RB"] = 5] = "RB"; - /** Back */ - Xbox360Button[Xbox360Button["Back"] = 8] = "Back"; - /** Start */ - Xbox360Button[Xbox360Button["Start"] = 9] = "Start"; - /** Left stick */ - Xbox360Button[Xbox360Button["LeftStick"] = 10] = "LeftStick"; - /** Right stick */ - Xbox360Button[Xbox360Button["RightStick"] = 11] = "RightStick"; -})(Xbox360Button || (Xbox360Button = {})); -/** Defines values for XBox360 DPad */ -var Xbox360Dpad; -(function (Xbox360Dpad) { - /** Up */ - Xbox360Dpad[Xbox360Dpad["Up"] = 12] = "Up"; - /** Down */ - Xbox360Dpad[Xbox360Dpad["Down"] = 13] = "Down"; - /** Left */ - Xbox360Dpad[Xbox360Dpad["Left"] = 14] = "Left"; - /** Right */ - Xbox360Dpad[Xbox360Dpad["Right"] = 15] = "Right"; -})(Xbox360Dpad || (Xbox360Dpad = {})); -/** - * Defines a XBox360 gamepad - */ -class Xbox360Pad extends Gamepad { - /** - * Creates a new XBox360 gamepad object - * @param id defines the id of this gamepad - * @param index defines its index - * @param gamepad defines the internal HTML gamepad object - * @param xboxOne defines if it is a XBox One gamepad - */ - constructor(id, index, gamepad, xboxOne = false) { - super(id, index, gamepad, 0, 1, 2, 3); - this._leftTrigger = 0; - this._rightTrigger = 0; - /** Observable raised when a button is pressed */ - this.onButtonDownObservable = new observable_Observable(); - /** Observable raised when a button is released */ - this.onButtonUpObservable = new observable_Observable(); - /** Observable raised when a pad is pressed */ - this.onPadDownObservable = new observable_Observable(); - /** Observable raised when a pad is released */ - this.onPadUpObservable = new observable_Observable(); - 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 = false; - this.type = Gamepad.XBOX; - this._isXboxOnePad = xboxOne; - } - /** - * Defines the callback to call when left trigger is pressed - * @param callback defines the callback to use - */ - onlefttriggerchanged(callback) { - this._onlefttriggerchanged = callback; - } - /** - * Defines the callback to call when right trigger is pressed - * @param callback defines the callback to use - */ - onrighttriggerchanged(callback) { - this._onrighttriggerchanged = callback; - } - /** - * Gets the left trigger value - */ - get leftTrigger() { - return this._leftTrigger; - } - /** - * Sets the left trigger value - */ - set leftTrigger(newValue) { - if (this._onlefttriggerchanged && this._leftTrigger !== newValue) { - this._onlefttriggerchanged(newValue); - } - this._leftTrigger = newValue; - } - /** - * Gets the right trigger value - */ - get rightTrigger() { - return this._rightTrigger; - } - /** - * Sets the right trigger value - */ - set rightTrigger(newValue) { - if (this._onrighttriggerchanged && this._rightTrigger !== newValue) { - this._onrighttriggerchanged(newValue); - } - this._rightTrigger = newValue; - } - /** - * Defines the callback to call when a button is pressed - * @param callback defines the callback to use - */ - onbuttondown(callback) { - this._onbuttondown = callback; - } - /** - * Defines the callback to call when a button is released - * @param callback defines the callback to use - */ - onbuttonup(callback) { - this._onbuttonup = callback; - } - /** - * Defines the callback to call when a pad is pressed - * @param callback defines the callback to use - */ - ondpaddown(callback) { - this._ondpaddown = callback; - } - /** - * Defines the callback to call when a pad is released - * @param callback defines the callback to use - */ - ondpadup(callback) { - this._ondpadup = callback; - } - _setButtonValue(newValue, currentValue, buttonType) { - if (newValue !== currentValue) { - if (newValue === 1) { - if (this._onbuttondown) { - this._onbuttondown(buttonType); - } - this.onButtonDownObservable.notifyObservers(buttonType); - } - if (newValue === 0) { - if (this._onbuttonup) { - this._onbuttonup(buttonType); - } - this.onButtonUpObservable.notifyObservers(buttonType); - } - } - return newValue; - } - _setDPadValue(newValue, currentValue, buttonType) { - if (newValue !== currentValue) { - if (newValue === 1) { - if (this._ondpaddown) { - this._ondpaddown(buttonType); - } - this.onPadDownObservable.notifyObservers(buttonType); - } - if (newValue === 0) { - if (this._ondpadup) { - this._ondpadup(buttonType); - } - this.onPadUpObservable.notifyObservers(buttonType); - } - } - return newValue; - } - /** - * Gets the value of the `A` button - */ - get buttonA() { - return this._buttonA; - } - /** - * Sets the value of the `A` button - */ - set buttonA(value) { - this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A); - } - /** - * Gets the value of the `B` button - */ - get buttonB() { - return this._buttonB; - } - /** - * Sets the value of the `B` button - */ - set buttonB(value) { - this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B); - } - /** - * Gets the value of the `X` button - */ - get buttonX() { - return this._buttonX; - } - /** - * Sets the value of the `X` button - */ - set buttonX(value) { - this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X); - } - /** - * Gets the value of the `Y` button - */ - get buttonY() { - return this._buttonY; - } - /** - * Sets the value of the `Y` button - */ - set buttonY(value) { - this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y); - } - /** - * Gets the value of the `Start` button - */ - get buttonStart() { - return this._buttonStart; - } - /** - * Sets the value of the `Start` button - */ - set buttonStart(value) { - this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start); - } - /** - * Gets the value of the `Back` button - */ - get buttonBack() { - return this._buttonBack; - } - /** - * Sets the value of the `Back` button - */ - set buttonBack(value) { - this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back); - } - /** - * Gets the value of the `Left` button - */ - get buttonLB() { - return this._buttonLB; - } - /** - * Sets the value of the `Left` button - */ - set buttonLB(value) { - this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB); - } - /** - * Gets the value of the `Right` button - */ - get buttonRB() { - return this._buttonRB; - } - /** - * Sets the value of the `Right` button - */ - set buttonRB(value) { - this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB); - } - /** - * Gets the value of the Left joystick - */ - get buttonLeftStick() { - return this._buttonLeftStick; - } - /** - * Sets the value of the Left joystick - */ - set buttonLeftStick(value) { - this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick); - } - /** - * Gets the value of the Right joystick - */ - get buttonRightStick() { - return this._buttonRightStick; - } - /** - * Sets the value of the Right joystick - */ - set buttonRightStick(value) { - this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick); - } - /** - * Gets the value of D-pad up - */ - get dPadUp() { - return this._dPadUp; - } - /** - * Sets the value of D-pad up - */ - set dPadUp(value) { - this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up); - } - /** - * Gets the value of D-pad down - */ - get dPadDown() { - return this._dPadDown; - } - /** - * Sets the value of D-pad down - */ - set dPadDown(value) { - this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down); - } - /** - * Gets the value of D-pad left - */ - get dPadLeft() { - return this._dPadLeft; - } - /** - * Sets the value of D-pad left - */ - set dPadLeft(value) { - this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left); - } - /** - * Gets the value of D-pad right - */ - get dPadRight() { - return this._dPadRight; - } - /** - * Sets the value of D-pad right - */ - set dPadRight(value) { - this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right); - } - /** - * Force the gamepad to synchronize with device values - */ - update() { - super.update(); - if (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; - } - else { - 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; - } - } - /** - * Disposes the gamepad - */ - dispose() { - super.dispose(); - this.onButtonDownObservable.clear(); - this.onButtonUpObservable.clear(); - this.onPadDownObservable.clear(); - this.onPadUpObservable.clear(); - } -} -//# sourceMappingURL=xboxGamepad.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/dualShockGamepad.js - - -/** - * Defines supported buttons for DualShock compatible gamepads - */ -var DualShockButton; -(function (DualShockButton) { - /** Cross */ - DualShockButton[DualShockButton["Cross"] = 0] = "Cross"; - /** Circle */ - DualShockButton[DualShockButton["Circle"] = 1] = "Circle"; - /** Square */ - DualShockButton[DualShockButton["Square"] = 2] = "Square"; - /** Triangle */ - DualShockButton[DualShockButton["Triangle"] = 3] = "Triangle"; - /** L1 */ - DualShockButton[DualShockButton["L1"] = 4] = "L1"; - /** R1 */ - DualShockButton[DualShockButton["R1"] = 5] = "R1"; - /** Share */ - DualShockButton[DualShockButton["Share"] = 8] = "Share"; - /** Options */ - DualShockButton[DualShockButton["Options"] = 9] = "Options"; - /** Left stick */ - DualShockButton[DualShockButton["LeftStick"] = 10] = "LeftStick"; - /** Right stick */ - DualShockButton[DualShockButton["RightStick"] = 11] = "RightStick"; -})(DualShockButton || (DualShockButton = {})); -/** Defines values for DualShock DPad */ -var DualShockDpad; -(function (DualShockDpad) { - /** Up */ - DualShockDpad[DualShockDpad["Up"] = 12] = "Up"; - /** Down */ - DualShockDpad[DualShockDpad["Down"] = 13] = "Down"; - /** Left */ - DualShockDpad[DualShockDpad["Left"] = 14] = "Left"; - /** Right */ - DualShockDpad[DualShockDpad["Right"] = 15] = "Right"; -})(DualShockDpad || (DualShockDpad = {})); -/** - * Defines a DualShock gamepad - */ -class DualShockPad extends Gamepad { - /** - * Creates a new DualShock gamepad object - * @param id defines the id of this gamepad - * @param index defines its index - * @param gamepad defines the internal HTML gamepad object - */ - constructor(id, index, gamepad) { - super(id.replace("STANDARD GAMEPAD", "SONY PLAYSTATION DUALSHOCK"), index, gamepad, 0, 1, 2, 3); - this._leftTrigger = 0; - this._rightTrigger = 0; - /** Observable raised when a button is pressed */ - this.onButtonDownObservable = new observable_Observable(); - /** Observable raised when a button is released */ - this.onButtonUpObservable = new observable_Observable(); - /** Observable raised when a pad is pressed */ - this.onPadDownObservable = new observable_Observable(); - /** Observable raised when a pad is released */ - this.onPadUpObservable = new observable_Observable(); - 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 = Gamepad.DUALSHOCK; - } - /** - * Defines the callback to call when left trigger is pressed - * @param callback defines the callback to use - */ - onlefttriggerchanged(callback) { - this._onlefttriggerchanged = callback; - } - /** - * Defines the callback to call when right trigger is pressed - * @param callback defines the callback to use - */ - onrighttriggerchanged(callback) { - this._onrighttriggerchanged = callback; - } - /** - * Gets the left trigger value - */ - get leftTrigger() { - return this._leftTrigger; - } - /** - * Sets the left trigger value - */ - set leftTrigger(newValue) { - if (this._onlefttriggerchanged && this._leftTrigger !== newValue) { - this._onlefttriggerchanged(newValue); - } - this._leftTrigger = newValue; - } - /** - * Gets the right trigger value - */ - get rightTrigger() { - return this._rightTrigger; - } - /** - * Sets the right trigger value - */ - set rightTrigger(newValue) { - if (this._onrighttriggerchanged && this._rightTrigger !== newValue) { - this._onrighttriggerchanged(newValue); - } - this._rightTrigger = newValue; - } - /** - * Defines the callback to call when a button is pressed - * @param callback defines the callback to use - */ - onbuttondown(callback) { - this._onbuttondown = callback; - } - /** - * Defines the callback to call when a button is released - * @param callback defines the callback to use - */ - onbuttonup(callback) { - this._onbuttonup = callback; - } - /** - * Defines the callback to call when a pad is pressed - * @param callback defines the callback to use - */ - ondpaddown(callback) { - this._ondpaddown = callback; - } - /** - * Defines the callback to call when a pad is released - * @param callback defines the callback to use - */ - ondpadup(callback) { - this._ondpadup = callback; - } - _setButtonValue(newValue, currentValue, buttonType) { - if (newValue !== currentValue) { - if (newValue === 1) { - if (this._onbuttondown) { - this._onbuttondown(buttonType); - } - this.onButtonDownObservable.notifyObservers(buttonType); - } - if (newValue === 0) { - if (this._onbuttonup) { - this._onbuttonup(buttonType); - } - this.onButtonUpObservable.notifyObservers(buttonType); - } - } - return newValue; - } - _setDPadValue(newValue, currentValue, buttonType) { - if (newValue !== currentValue) { - if (newValue === 1) { - if (this._ondpaddown) { - this._ondpaddown(buttonType); - } - this.onPadDownObservable.notifyObservers(buttonType); - } - if (newValue === 0) { - if (this._ondpadup) { - this._ondpadup(buttonType); - } - this.onPadUpObservable.notifyObservers(buttonType); - } - } - return newValue; - } - /** - * Gets the value of the `Cross` button - */ - get buttonCross() { - return this._buttonCross; - } - /** - * Sets the value of the `Cross` button - */ - set buttonCross(value) { - this._buttonCross = this._setButtonValue(value, this._buttonCross, DualShockButton.Cross); - } - /** - * Gets the value of the `Circle` button - */ - get buttonCircle() { - return this._buttonCircle; - } - /** - * Sets the value of the `Circle` button - */ - set buttonCircle(value) { - this._buttonCircle = this._setButtonValue(value, this._buttonCircle, DualShockButton.Circle); - } - /** - * Gets the value of the `Square` button - */ - get buttonSquare() { - return this._buttonSquare; - } - /** - * Sets the value of the `Square` button - */ - set buttonSquare(value) { - this._buttonSquare = this._setButtonValue(value, this._buttonSquare, DualShockButton.Square); - } - /** - * Gets the value of the `Triangle` button - */ - get buttonTriangle() { - return this._buttonTriangle; - } - /** - * Sets the value of the `Triangle` button - */ - set buttonTriangle(value) { - this._buttonTriangle = this._setButtonValue(value, this._buttonTriangle, DualShockButton.Triangle); - } - /** - * Gets the value of the `Options` button - */ - get buttonOptions() { - return this._buttonOptions; - } - /** - * Sets the value of the `Options` button - */ - set buttonOptions(value) { - this._buttonOptions = this._setButtonValue(value, this._buttonOptions, DualShockButton.Options); - } - /** - * Gets the value of the `Share` button - */ - get buttonShare() { - return this._buttonShare; - } - /** - * Sets the value of the `Share` button - */ - set buttonShare(value) { - this._buttonShare = this._setButtonValue(value, this._buttonShare, DualShockButton.Share); - } - /** - * Gets the value of the `L1` button - */ - get buttonL1() { - return this._buttonL1; - } - /** - * Sets the value of the `L1` button - */ - set buttonL1(value) { - this._buttonL1 = this._setButtonValue(value, this._buttonL1, DualShockButton.L1); - } - /** - * Gets the value of the `R1` button - */ - get buttonR1() { - return this._buttonR1; - } - /** - * Sets the value of the `R1` button - */ - set buttonR1(value) { - this._buttonR1 = this._setButtonValue(value, this._buttonR1, DualShockButton.R1); - } - /** - * Gets the value of the Left joystick - */ - get buttonLeftStick() { - return this._buttonLeftStick; - } - /** - * Sets the value of the Left joystick - */ - set buttonLeftStick(value) { - this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, DualShockButton.LeftStick); - } - /** - * Gets the value of the Right joystick - */ - get buttonRightStick() { - return this._buttonRightStick; - } - /** - * Sets the value of the Right joystick - */ - set buttonRightStick(value) { - this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, DualShockButton.RightStick); - } - /** - * Gets the value of D-pad up - */ - get dPadUp() { - return this._dPadUp; - } - /** - * Sets the value of D-pad up - */ - set dPadUp(value) { - this._dPadUp = this._setDPadValue(value, this._dPadUp, DualShockDpad.Up); - } - /** - * Gets the value of D-pad down - */ - get dPadDown() { - return this._dPadDown; - } - /** - * Sets the value of D-pad down - */ - set dPadDown(value) { - this._dPadDown = this._setDPadValue(value, this._dPadDown, DualShockDpad.Down); - } - /** - * Gets the value of D-pad left - */ - get dPadLeft() { - return this._dPadLeft; - } - /** - * Sets the value of D-pad left - */ - set dPadLeft(value) { - this._dPadLeft = this._setDPadValue(value, this._dPadLeft, DualShockDpad.Left); - } - /** - * Gets the value of D-pad right - */ - get dPadRight() { - return this._dPadRight; - } - /** - * Sets the value of D-pad right - */ - set dPadRight(value) { - this._dPadRight = this._setDPadValue(value, this._dPadRight, DualShockDpad.Right); - } - /** - * Force the gamepad to synchronize with device values - */ - 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; - } - /** - * Disposes the gamepad - */ - dispose() { - super.dispose(); - this.onButtonDownObservable.clear(); - this.onButtonUpObservable.clear(); - this.onPadDownObservable.clear(); - this.onPadUpObservable.clear(); - } -} -//# sourceMappingURL=dualShockGamepad.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/gamepadManager.js - - - - - - - - -/** - * Manager for handling gamepads - */ -class GamepadManager { - /** - * Initializes the gamepad manager - * @param _scene BabylonJS scene - */ - constructor(_scene) { - this._scene = _scene; - this._babylonGamepads = []; - this._oneGamepadConnected = false; - /** @internal */ - this._isMonitoring = false; - /** - * observable to be triggered when the gamepad controller has been disconnected - */ - this.onGamepadDisconnectedObservable = new observable_Observable(); - if (!IsWindowObjectExist()) { - this._gamepadEventSupported = false; - } - else { - this._gamepadEventSupported = "GamepadEvent" in window; - this._gamepadSupport = navigator && navigator.getGamepads; - } - this.onGamepadConnectedObservable = new observable_Observable((observer) => { - // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected - for (const i in this._babylonGamepads) { - const gamepad = this._babylonGamepads[i]; - if (gamepad && gamepad._isConnected) { - this.onGamepadConnectedObservable.notifyObserver(observer, gamepad); - } - } - }); - this._onGamepadConnectedEvent = (evt) => { - const gamepad = evt.gamepad; - if (gamepad.index in this._babylonGamepads) { - if (this._babylonGamepads[gamepad.index].isConnected) { - return; - } - } - let newGamepad; - if (this._babylonGamepads[gamepad.index]) { - newGamepad = this._babylonGamepads[gamepad.index]; - newGamepad.browserGamepad = gamepad; - newGamepad._isConnected = true; - } - else { - newGamepad = this._addNewGamepad(gamepad); - } - this.onGamepadConnectedObservable.notifyObservers(newGamepad); - this._startMonitoringGamepads(); - }; - this._onGamepadDisconnectedEvent = (evt) => { - const gamepad = evt.gamepad; - // Remove the gamepad from the list of gamepads to monitor. - for (const i in this._babylonGamepads) { - if (this._babylonGamepads[i].index === gamepad.index) { - const disconnectedGamepad = this._babylonGamepads[i]; - disconnectedGamepad._isConnected = false; - this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad); - disconnectedGamepad.dispose && disconnectedGamepad.dispose(); - break; - } - } - }; - if (this._gamepadSupport) { - //first add already-connected gamepads - this._updateGamepadObjects(); - if (this._babylonGamepads.length) { - this._startMonitoringGamepads(); - } - // Checking if the gamepad connected event is supported (like in Firefox) - if (this._gamepadEventSupported) { - const hostWindow = this._scene ? this._scene.getEngine().getHostWindow() : window; - if (hostWindow) { - hostWindow.addEventListener("gamepadconnected", this._onGamepadConnectedEvent, false); - hostWindow.addEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent, false); - } - } - else { - this._startMonitoringGamepads(); - } - } - } - /** - * The gamepads in the game pad manager - */ - get gamepads() { - return this._babylonGamepads; - } - /** - * Get the gamepad controllers based on type - * @param type The type of gamepad controller - * @returns Nullable gamepad - */ - getGamepadByType(type = Gamepad.XBOX) { - for (const gamepad of this._babylonGamepads) { - if (gamepad && gamepad.type === type) { - return gamepad; - } - } - return null; - } - /** - * Disposes the gamepad manager - */ - dispose() { - if (this._gamepadEventSupported) { - if (this._onGamepadConnectedEvent) { - window.removeEventListener("gamepadconnected", this._onGamepadConnectedEvent); - } - if (this._onGamepadDisconnectedEvent) { - window.removeEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent); - } - this._onGamepadConnectedEvent = null; - this._onGamepadDisconnectedEvent = null; - } - this._babylonGamepads.forEach((gamepad) => { - gamepad.dispose(); - }); - this.onGamepadConnectedObservable.clear(); - this.onGamepadDisconnectedObservable.clear(); - this._oneGamepadConnected = false; - this._stopMonitoringGamepads(); - this._babylonGamepads = []; - } - _addNewGamepad(gamepad) { - if (!this._oneGamepadConnected) { - this._oneGamepadConnected = true; - } - let newGamepad; - const dualShock = gamepad.id.search("054c") !== -1 && gamepad.id.search("0ce6") === -1; - const xboxOne = gamepad.id.search("Xbox One") !== -1; - if (xboxOne || - gamepad.id.search("Xbox 360") !== -1 || - gamepad.id.search("xinput") !== -1 || - (gamepad.id.search("045e") !== -1 && gamepad.id.search("Surface Dock") === -1)) { - // make sure the Surface Dock Extender is not detected as an xbox controller - newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne); - } - else if (dualShock) { - newGamepad = new DualShockPad(gamepad.id, gamepad.index, gamepad); - } - // if pose is supported, use the (WebVR) pose enabled controller - else if (gamepad.pose) { - newGamepad = PoseEnabledControllerHelper.InitiateController(gamepad); - } - else { - newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad); - } - this._babylonGamepads[newGamepad.index] = newGamepad; - return newGamepad; - } - _startMonitoringGamepads() { - if (!this._isMonitoring) { - this._isMonitoring = true; - //back-comp - this._checkGamepadsStatus(); - } - } - _stopMonitoringGamepads() { - this._isMonitoring = false; - } - /** @internal */ - _checkGamepadsStatus() { - // Hack to be compatible Chrome - this._updateGamepadObjects(); - for (const i in this._babylonGamepads) { - const gamepad = this._babylonGamepads[i]; - if (!gamepad || !gamepad.isConnected) { - continue; - } - try { - gamepad.update(); - } - catch (_a) { - if (this._loggedErrors.indexOf(gamepad.index) === -1) { - tools_Tools.Warn(`Error updating gamepad ${gamepad.id}`); - this._loggedErrors.push(gamepad.index); - } - } - } - if (this._isMonitoring) { - engine_Engine.QueueNewFrame(() => { - this._checkGamepadsStatus(); - }); - } - } - // This function is called only on Chrome, which does not properly support - // connection/disconnection events and forces you to recopy again the gamepad object - _updateGamepadObjects() { - const gamepads = navigator.getGamepads ? navigator.getGamepads() : []; - for (let i = 0; i < gamepads.length; i++) { - const gamepad = gamepads[i]; - if (gamepad) { - if (!this._babylonGamepads[gamepad.index]) { - const newGamepad = this._addNewGamepad(gamepad); - this.onGamepadConnectedObservable.notifyObservers(newGamepad); - } - else { - // Forced to copy again this object for Chrome for unknown reason - this._babylonGamepads[i].browserGamepad = gamepad; - if (!this._babylonGamepads[i].isConnected) { - this._babylonGamepads[i]._isConnected = true; - this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]); - } - } - } - } - } -} -//# sourceMappingURL=gamepadManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/gamepadSceneComponent.js - - - - - - - -Object.defineProperty(scene_Scene.prototype, "gamepadManager", { - get: function () { - if (!this._gamepadManager) { - this._gamepadManager = new GamepadManager(this); - let component = this._getComponent(sceneComponent_SceneComponentConstants.NAME_GAMEPAD); - if (!component) { - component = new GamepadSystemSceneComponent(this); - this._addComponent(component); - } - } - return this._gamepadManager; - }, - enumerable: true, - configurable: true, -}); -/** - * Adds a gamepad to the free camera inputs manager - */ -FreeCameraInputsManager.prototype.addGamepad = function () { - this.add(new FreeCameraGamepadInput()); - return this; -}; -/** - * Adds a gamepad to the arc rotate camera inputs manager - */ -ArcRotateCameraInputsManager.prototype.addGamepad = function () { - this.add(new ArcRotateCameraGamepadInput()); - return this; -}; -/** - * Defines the gamepad scene component responsible to manage gamepads in a given scene - */ -class GamepadSystemSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpfull to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_GAMEPAD; - this.scene = scene; - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._beforeCameraUpdateStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing to do for gamepads - } - /** - * Disposes the component and the associated resources - */ - dispose() { - const gamepadManager = this.scene._gamepadManager; - if (gamepadManager) { - gamepadManager.dispose(); - this.scene._gamepadManager = null; - } - } - _beforeCameraUpdate() { - const gamepadManager = this.scene._gamepadManager; - if (gamepadManager && gamepadManager._isMonitoring) { - gamepadManager._checkGamepadsStatus(); - } - } -} -//# sourceMappingURL=gamepadSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/universalCamera.js - - - - - -node_Node.AddNodeConstructor("FreeCamera", (name, scene) => { - // Forcing to use the Universal camera - return () => new universalCamera_UniversalCamera(name, math_vector_Vector3.Zero(), scene); -}); -/** - * 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, - * which still works and will still be found in many Playgrounds. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera - */ -class universalCamera_UniversalCamera extends TouchCamera { - /** - * Defines the gamepad rotation sensibility. - * This is the threshold from when rotation starts to be accounted for to prevent jittering. - */ - get gamepadAngularSensibility() { - const gamepad = this.inputs.attached["gamepad"]; - if (gamepad) { - return gamepad.gamepadAngularSensibility; - } - return 0; - } - set gamepadAngularSensibility(value) { - const gamepad = this.inputs.attached["gamepad"]; - if (gamepad) { - gamepad.gamepadAngularSensibility = value; - } - } - /** - * Defines the gamepad move sensibility. - * This is the threshold from when moving starts to be accounted for to prevent jittering. - */ - get gamepadMoveSensibility() { - const gamepad = this.inputs.attached["gamepad"]; - if (gamepad) { - return gamepad.gamepadMoveSensibility; - } - return 0; - } - set gamepadMoveSensibility(value) { - const gamepad = this.inputs.attached["gamepad"]; - if (gamepad) { - gamepad.gamepadMoveSensibility = value; - } - } - /** - * 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, - * which still works and will still be found in many Playgrounds. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera - * @param name Define the name of the camera in the scene - * @param position Define the start position of the camera in the scene - * @param scene Define the scene the camera belongs to - */ - constructor(name, position, scene) { - super(name, position, scene); - this.inputs.addGamepad(); - } - /** - * Gets the current object class name. - * @returns the class name - */ - getClassName() { - return "UniversalCamera"; - } -} -camera_Camera._CreateDefaultParsedCamera = (name, scene) => { - return new universalCamera_UniversalCamera(name, math_vector_Vector3.Zero(), scene); -}; -//# sourceMappingURL=universalCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/gamepadCamera.js - - - -node_Node.AddNodeConstructor("GamepadCamera", (name, scene) => { - return () => new GamepadCamera(name, math_vector_Vector3.Zero(), scene); -}); -/** - * This represents a FPS type of camera. This is only here for back compat purpose. - * Please use the UniversalCamera instead as both are identical. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera - */ -class GamepadCamera extends universalCamera_UniversalCamera { - /** - * Instantiates a new Gamepad Camera - * This represents a FPS type of camera. This is only here for back compat purpose. - * Please use the UniversalCamera instead as both are identical. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera - * @param name Define the name of the camera in the scene - * @param position Define the start position of the camera in the scene - * @param scene Define the scene the camera belongs to - */ - constructor(name, position, scene) { - super(name, position, scene); - } - /** - * Gets the current object class name. - * @returns the class name - */ - getClassName() { - return "GamepadCamera"; - } -} -//# sourceMappingURL=gamepadCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/passCube.fragment.js -// Do not edit. - -const passCube_fragment_name = "passCubePixelShader"; -const passCube_fragment_shader = `varying vec2 vUV;uniform samplerCube textureSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 uv=vUV*2.0-1.0; -#ifdef POSITIVEX -gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); -#endif -#ifdef NEGATIVEX -gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); -#endif -#ifdef POSITIVEY -gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); -#endif -#ifdef NEGATIVEY -gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); -#endif -#ifdef POSITIVEZ -gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); -#endif -#ifdef NEGATIVEZ -gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); -#endif -}`; -// Sideeffect -ShaderStore.ShadersStore[passCube_fragment_name] = passCube_fragment_shader; -/** @internal */ -const passCubePixelShader = { name: passCube_fragment_name, shader: passCube_fragment_shader }; -//# sourceMappingURL=passCube.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/passPostProcess.js - - - - - - - -/** - * PassPostProcess which produces an output the same as it's input - */ -class PassPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "PassPostProcess" string - */ - getClassName() { - return "PassPostProcess"; - } - /** - * Creates the PassPostProcess - * @param name The name of the effect. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType The type of texture to be used when performing the post processing. - * @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) - */ - constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { - super(name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation); - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new PassPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -RegisterClass("BABYLON.PassPostProcess", PassPostProcess); -/** - * PassCubePostProcess which produces an output the same as it's input (which must be a cube texture) - */ -class PassCubePostProcess extends (/* unused pure expression or super */ null && (PostProcess)) { - /** - * Gets or sets the cube face to display. - * * 0 is +X - * * 1 is -X - * * 2 is +Y - * * 3 is -Y - * * 4 is +Z - * * 5 is -Z - */ - get face() { - return this._face; - } - set face(value) { - if (value < 0 || value > 5) { - return; - } - this._face = value; - switch (this._face) { - case 0: - this.updateEffect("#define POSITIVEX"); - break; - case 1: - this.updateEffect("#define NEGATIVEX"); - break; - case 2: - this.updateEffect("#define POSITIVEY"); - break; - case 3: - this.updateEffect("#define NEGATIVEY"); - break; - case 4: - this.updateEffect("#define POSITIVEZ"); - break; - case 5: - this.updateEffect("#define NEGATIVEZ"); - break; - } - } - /** - * Gets a string identifying the name of the class - * @returns "PassCubePostProcess" string - */ - getClassName() { - return "PassCubePostProcess"; - } - /** - * Creates the PassCubePostProcess - * @param name The name of the effect. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType The type of texture to be used when performing the post processing. - * @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) - */ - constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { - super(name, "passCube", null, null, options, camera, samplingMode, engine, reusable, "#define POSITIVEX", textureType, undefined, null, blockCompilation); - this._face = 0; - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return SerializationHelper.Parse(() => { - return new PassCubePostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -engine_Engine._RescalePostProcessFactory = (engine) => { - return new PassPostProcess("rescale", 1, null, 2, engine, false, 0); -}; -//# sourceMappingURL=passPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/anaglyph.fragment.js -// Do not edit. - -const anaglyph_fragment_name = "anaglyphPixelShader"; -const anaglyph_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`; -// Sideeffect -ShaderStore.ShadersStore[anaglyph_fragment_name] = anaglyph_fragment_shader; -/** @internal */ -const anaglyphPixelShader = { name: anaglyph_fragment_name, shader: anaglyph_fragment_shader }; -//# sourceMappingURL=anaglyph.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/anaglyphPostProcess.js - - - -/** - * Postprocess used to generate anaglyphic rendering - */ -class AnaglyphPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "AnaglyphPostProcess" string - */ - getClassName() { - return "AnaglyphPostProcess"; - } - /** - * Creates a new AnaglyphPostProcess - * @param name defines postprocess name - * @param options defines creation options or target ratio scale - * @param rigCameras defines cameras using this postprocess - * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default) - * @param engine defines hosting engine - * @param reusable defines if the postprocess will be reused multiple times per frame - */ - constructor(name, options, rigCameras, samplingMode, engine, reusable) { - super(name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable); - this._passedProcess = rigCameras[0]._rigPostProcess; - this.onApplyObservable.add((effect) => { - effect.setTextureFromPostProcess("leftSampler", this._passedProcess); - }); - } -} -RegisterClass("BABYLON.AnaglyphPostProcess", AnaglyphPostProcess); -//# sourceMappingURL=anaglyphPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicAnaglyphRigMode.js - - -/** - * @internal - */ -function setStereoscopicAnaglyphRigMode(camera) { - camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + "_passthru", 1.0, camera._rigCameras[0]); - camera._rigCameras[1]._rigPostProcess = new AnaglyphPostProcess(camera.name + "_anaglyph", 1.0, camera._rigCameras); -} -//# sourceMappingURL=stereoscopicAnaglyphRigMode.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphArcRotateCamera.js - - - - - -node_Node.AddNodeConstructor("AnaglyphArcRotateCamera", (name, scene, options) => { - return () => new AnaglyphArcRotateCamera(name, 0, 0, 1.0, math_vector_Vector3.Zero(), options.interaxial_distance, scene); -}); -/** - * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras - */ -class AnaglyphArcRotateCamera extends ArcRotateCamera { - /** - * Creates a new AnaglyphArcRotateCamera - * @param name defines camera name - * @param alpha defines alpha angle (in radians) - * @param beta defines beta angle (in radians) - * @param radius defines radius - * @param target defines camera target - * @param interaxialDistance defines distance between each color axis - * @param scene defines the hosting scene - */ - constructor(name, alpha, beta, radius, target, interaxialDistance, scene) { - super(name, alpha, beta, radius, target, scene); - this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this); - this.interaxialDistance = interaxialDistance; - this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); - } - /** - * Gets camera class name - * @returns AnaglyphArcRotateCamera - */ - getClassName() { - return "AnaglyphArcRotateCamera"; - } -} -//# sourceMappingURL=anaglyphArcRotateCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphFreeCamera.js - - - - - -node_Node.AddNodeConstructor("AnaglyphFreeCamera", (name, scene, options) => { - return () => new AnaglyphFreeCamera(name, math_vector_Vector3.Zero(), options.interaxial_distance, scene); -}); -/** - * Camera used to simulate anaglyphic rendering (based on FreeCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras - */ -class AnaglyphFreeCamera extends FreeCamera { - /** - * Creates a new AnaglyphFreeCamera - * @param name defines camera name - * @param position defines initial position - * @param interaxialDistance defines distance between each color axis - * @param scene defines the hosting scene - */ - constructor(name, position, interaxialDistance, scene) { - super(name, position, scene); - this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this); - this.interaxialDistance = interaxialDistance; - this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); - } - /** - * Gets camera class name - * @returns AnaglyphFreeCamera - */ - getClassName() { - return "AnaglyphFreeCamera"; - } -} -//# sourceMappingURL=anaglyphFreeCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphGamepadCamera.js - - - - - -node_Node.AddNodeConstructor("AnaglyphGamepadCamera", (name, scene, options) => { - return () => new AnaglyphGamepadCamera(name, math_vector_Vector3.Zero(), options.interaxial_distance, scene); -}); -/** - * Camera used to simulate anaglyphic rendering (based on GamepadCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras - */ -class AnaglyphGamepadCamera extends GamepadCamera { - /** - * Creates a new AnaglyphGamepadCamera - * @param name defines camera name - * @param position defines initial position - * @param interaxialDistance defines distance between each color axis - * @param scene defines the hosting scene - */ - constructor(name, position, interaxialDistance, scene) { - super(name, position, scene); - this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this); - this.interaxialDistance = interaxialDistance; - this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); - } - /** - * Gets camera class name - * @returns AnaglyphGamepadCamera - */ - getClassName() { - return "AnaglyphGamepadCamera"; - } -} -//# sourceMappingURL=anaglyphGamepadCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphUniversalCamera.js - - - - - -node_Node.AddNodeConstructor("AnaglyphUniversalCamera", (name, scene, options) => { - return () => new AnaglyphUniversalCamera(name, math_vector_Vector3.Zero(), options.interaxial_distance, scene); -}); -/** - * Camera used to simulate anaglyphic rendering (based on UniversalCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras - */ -class AnaglyphUniversalCamera extends universalCamera_UniversalCamera { - /** - * Creates a new AnaglyphUniversalCamera - * @param name defines camera name - * @param position defines initial position - * @param interaxialDistance defines distance between each color axis - * @param scene defines the hosting scene - */ - constructor(name, position, interaxialDistance, scene) { - super(name, position, scene); - this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this); - this.interaxialDistance = interaxialDistance; - this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); - } - /** - * Gets camera class name - * @returns AnaglyphUniversalCamera - */ - getClassName() { - return "AnaglyphUniversalCamera"; - } -} -//# sourceMappingURL=anaglyphUniversalCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/stereoscopicInterlace.fragment.js -// Do not edit. - -const stereoscopicInterlace_fragment_name = "stereoscopicInterlacePixelShader"; -const stereoscopicInterlace_fragment_shader = `const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; -#ifdef IS_STEREOSCOPIC_HORIZ -useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); -#else -#ifdef IS_STEREOSCOPIC_INTERLACED -float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); -#else -useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); -#endif -#endif -if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} -gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} -`; -// Sideeffect -ShaderStore.ShadersStore[stereoscopicInterlace_fragment_name] = stereoscopicInterlace_fragment_shader; -/** @internal */ -const stereoscopicInterlacePixelShader = { name: stereoscopicInterlace_fragment_name, shader: stereoscopicInterlace_fragment_shader }; -//# sourceMappingURL=stereoscopicInterlace.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/stereoscopicInterlacePostProcess.js - - - -/** - * StereoscopicInterlacePostProcessI used to render stereo views from a rigged camera with support for alternate line interlacing - */ -class StereoscopicInterlacePostProcessI extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "StereoscopicInterlacePostProcessI" string - */ - getClassName() { - return "StereoscopicInterlacePostProcessI"; - } - /** - * Initializes a StereoscopicInterlacePostProcessI - * @param name The name of the effect. - * @param rigCameras The rig cameras to be applied to the post process - * @param isStereoscopicHoriz If the rendered results are horizontal or vertical - * @param isStereoscopicInterlaced If the rendered results are alternate line interlaced - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - */ - constructor(name, rigCameras, isStereoscopicHoriz, isStereoscopicInterlaced, samplingMode, engine, reusable) { - super(name, "stereoscopicInterlace", ["stepSize"], ["camASampler"], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicInterlaced ? "#define IS_STEREOSCOPIC_INTERLACED 1" : isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined); - this._passedProcess = rigCameras[0]._rigPostProcess; - this._stepSize = new math_vector_Vector2(1 / this.width, 1 / this.height); - this.onSizeChangedObservable.add(() => { - this._stepSize = new math_vector_Vector2(1 / this.width, 1 / this.height); - }); - this.onApplyObservable.add((effect) => { - effect.setTextureFromPostProcess("camASampler", this._passedProcess); - effect.setFloat2("stepSize", this._stepSize.x, this._stepSize.y); - }); - } -} -/** - * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera - */ -class StereoscopicInterlacePostProcess extends (/* unused pure expression or super */ null && (PostProcess)) { - /** - * Gets a string identifying the name of the class - * @returns "StereoscopicInterlacePostProcess" string - */ - getClassName() { - return "StereoscopicInterlacePostProcess"; - } - /** - * Initializes a StereoscopicInterlacePostProcess - * @param name The name of the effect. - * @param rigCameras The rig cameras to be applied to the post process - * @param isStereoscopicHoriz If the rendered results are horizontal or vertical - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - */ - constructor(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) { - super(name, "stereoscopicInterlace", ["stepSize"], ["camASampler"], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined); - this._passedProcess = rigCameras[0]._rigPostProcess; - this._stepSize = new Vector2(1 / this.width, 1 / this.height); - this.onSizeChangedObservable.add(() => { - this._stepSize = new Vector2(1 / this.width, 1 / this.height); - }); - this.onApplyObservable.add((effect) => { - effect.setTextureFromPostProcess("camASampler", this._passedProcess); - effect.setFloat2("stepSize", this._stepSize.x, this._stepSize.y); - }); - } -} -//# sourceMappingURL=stereoscopicInterlacePostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicRigMode.js - - - - -/** - * @internal - */ -function setStereoscopicRigMode(camera) { - const isStereoscopicHoriz = camera.cameraRigMode === camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || camera.cameraRigMode === camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; - const isCrossEye = camera.cameraRigMode === camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; - const isInterlaced = camera.cameraRigMode === camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED; - // Use post-processors for interlacing - if (isInterlaced) { - camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + "_passthru", 1.0, camera._rigCameras[0]); - camera._rigCameras[1]._rigPostProcess = new StereoscopicInterlacePostProcessI(camera.name + "_stereoInterlace", camera._rigCameras, false, true); - } - // Otherwise, create appropriate viewports - else { - camera._rigCameras[isCrossEye ? 1 : 0].viewport = new math_viewport_Viewport(0, 0, isStereoscopicHoriz ? 0.5 : 1.0, isStereoscopicHoriz ? 1.0 : 0.5); - camera._rigCameras[isCrossEye ? 0 : 1].viewport = new math_viewport_Viewport(isStereoscopicHoriz ? 0.5 : 0, isStereoscopicHoriz ? 0 : 0.5, isStereoscopicHoriz ? 0.5 : 1.0, isStereoscopicHoriz ? 1.0 : 0.5); - } -} -//# sourceMappingURL=stereoscopicRigMode.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicArcRotateCamera.js - - - - - -node_Node.AddNodeConstructor("StereoscopicArcRotateCamera", (name, scene, options) => { - return () => new StereoscopicArcRotateCamera(name, 0, 0, 1.0, math_vector_Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); -}); -/** - * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras - */ -class StereoscopicArcRotateCamera extends ArcRotateCamera { - /** - * Creates a new StereoscopicArcRotateCamera - * @param name defines camera name - * @param alpha defines alpha angle (in radians) - * @param beta defines beta angle (in radians) - * @param radius defines radius - * @param target defines camera target - * @param interaxialDistance defines distance between each color axis - * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under - * @param scene defines the hosting scene - */ - constructor(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) { - super(name, alpha, beta, radius, target, scene); - this._setRigMode = setStereoscopicRigMode.bind(null, this); - this.interaxialDistance = interaxialDistance; - this.isStereoscopicSideBySide = isStereoscopicSideBySide; - this.setCameraRigMode(isStereoscopicSideBySide ? camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { - interaxialDistance: interaxialDistance, - }); - } - /** - * Gets camera class name - * @returns StereoscopicArcRotateCamera - */ - getClassName() { - return "StereoscopicArcRotateCamera"; - } -} -//# sourceMappingURL=stereoscopicArcRotateCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicFreeCamera.js - - - - - -node_Node.AddNodeConstructor("StereoscopicFreeCamera", (name, scene, options) => { - return () => new StereoscopicFreeCamera(name, math_vector_Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); -}); -/** - * Camera used to simulate stereoscopic rendering (based on FreeCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras - */ -class StereoscopicFreeCamera extends FreeCamera { - /** - * Creates a new StereoscopicFreeCamera - * @param name defines camera name - * @param position defines initial position - * @param interaxialDistance defines distance between each color axis - * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under - * @param scene defines the hosting scene - */ - constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { - super(name, position, scene); - this._setRigMode = setStereoscopicRigMode.bind(null, this); - this.interaxialDistance = interaxialDistance; - this.isStereoscopicSideBySide = isStereoscopicSideBySide; - this.setCameraRigMode(isStereoscopicSideBySide ? camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { - interaxialDistance: interaxialDistance, - }); - } - /** - * Gets camera class name - * @returns StereoscopicFreeCamera - */ - getClassName() { - return "StereoscopicFreeCamera"; - } -} -//# sourceMappingURL=stereoscopicFreeCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicGamepadCamera.js - - - - - -node_Node.AddNodeConstructor("StereoscopicGamepadCamera", (name, scene, options) => { - return () => new StereoscopicGamepadCamera(name, math_vector_Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); -}); -/** - * Camera used to simulate stereoscopic rendering (based on GamepadCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras - */ -class StereoscopicGamepadCamera extends GamepadCamera { - /** - * Creates a new StereoscopicGamepadCamera - * @param name defines camera name - * @param position defines initial position - * @param interaxialDistance defines distance between each color axis - * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under - * @param scene defines the hosting scene - */ - constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { - super(name, position, scene); - this._setRigMode = setStereoscopicRigMode.bind(null, this); - this.interaxialDistance = interaxialDistance; - this.isStereoscopicSideBySide = isStereoscopicSideBySide; - this.setCameraRigMode(isStereoscopicSideBySide ? camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { - interaxialDistance: interaxialDistance, - }); - } - /** - * Gets camera class name - * @returns StereoscopicGamepadCamera - */ - getClassName() { - return "StereoscopicGamepadCamera"; - } -} -//# sourceMappingURL=stereoscopicGamepadCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicUniversalCamera.js - - - - - -node_Node.AddNodeConstructor("StereoscopicFreeCamera", (name, scene, options) => { - return () => new StereoscopicUniversalCamera(name, math_vector_Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); -}); -/** - * Camera used to simulate stereoscopic rendering (based on UniversalCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras - */ -class StereoscopicUniversalCamera extends universalCamera_UniversalCamera { - /** - * Creates a new StereoscopicUniversalCamera - * @param name defines camera name - * @param position defines initial position - * @param interaxialDistance defines distance between each color axis - * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under - * @param scene defines the hosting scene - */ - constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { - super(name, position, scene); - this._setRigMode = setStereoscopicRigMode.bind(null, this); - this.interaxialDistance = interaxialDistance; - this.isStereoscopicSideBySide = isStereoscopicSideBySide; - this.setCameraRigMode(isStereoscopicSideBySide ? camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { - interaxialDistance: interaxialDistance, - }); - } - /** - * Gets camera class name - * @returns StereoscopicUniversalCamera - */ - getClassName() { - return "StereoscopicUniversalCamera"; - } -} -//# sourceMappingURL=stereoscopicUniversalCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicScreenUniversalCamera.js - - - - - - -/** - * Camera used to simulate stereoscopic rendering on real screens (based on UniversalCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras - */ -class StereoscopicScreenUniversalCamera extends (/* unused pure expression or super */ null && (UniversalCamera)) { - set distanceBetweenEyes(newValue) { - this._distanceBetweenEyes = newValue; - } - /** - * distance between the eyes - */ - get distanceBetweenEyes() { - return this._distanceBetweenEyes; - } - set distanceToProjectionPlane(newValue) { - this._distanceToProjectionPlane = newValue; - } - /** - * Distance to projection plane (should be the same units the like distance between the eyes) - */ - get distanceToProjectionPlane() { - return this._distanceToProjectionPlane; - } - /** - * Creates a new StereoscopicScreenUniversalCamera - * @param name defines camera name - * @param position defines initial position - * @param scene defines the hosting scene - * @param distanceToProjectionPlane defines distance between each color axis. The rig cameras will receive this as their negative z position! - * @param distanceBetweenEyes defines is stereoscopic is done side by side or over under - */ - constructor(name, position, scene, distanceToProjectionPlane = 1, distanceBetweenEyes = 0.065) { - super(name, position, scene); - this._distanceBetweenEyes = distanceBetweenEyes; - this._distanceToProjectionPlane = distanceToProjectionPlane; - this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL, { - stereoHalfAngle: 0, - }); - this._cameraRigParams.stereoHalfAngle = 0; - this._cameraRigParams.interaxialDistance = distanceBetweenEyes; - } - /** - * Gets camera class name - * @returns StereoscopicScreenUniversalCamera - */ - getClassName() { - return "StereoscopicUniversalCamera"; - } - /** - * @internal - */ - createRigCamera(name) { - const camera = new TargetCamera(name, Vector3.Zero(), this.getScene()); - const transform = new TransformNode("tm_" + name, this.getScene()); - camera.parent = transform; - transform.setPivotMatrix(Matrix.Identity(), false); - camera.isRigCamera = true; - camera.rigParent = this; - return camera; - } - /** - * @internal - */ - _updateRigCameras() { - for (let cameraIndex = 0; cameraIndex < this._rigCameras.length; cameraIndex++) { - const cam = this._rigCameras[cameraIndex]; - cam.minZ = this.minZ; - cam.maxZ = this.maxZ; - cam.fov = this.fov; - cam.upVector.copyFrom(this.upVector); - if (cam.rotationQuaternion) { - cam.rotationQuaternion.copyFrom(this.rotationQuaternion); - } - else { - cam.rotation.copyFrom(this.rotation); - } - this._updateCamera(this._rigCameras[cameraIndex], cameraIndex); - } - } - _updateCamera(camera, cameraIndex) { - const b = this.distanceBetweenEyes / 2; - const z = b / this.distanceToProjectionPlane; - camera.position.copyFrom(this.position); - camera.position.addInPlaceFromFloats(cameraIndex === 0 ? -b : b, 0, -this._distanceToProjectionPlane); - const transform = camera.parent; - const m = transform.getPivotMatrix(); - m.setTranslationFromFloats(cameraIndex === 0 ? b : -b, 0, 0); - m.setRowFromFloats(2, cameraIndex === 0 ? z : -z, 0, 1, 0); - transform.setPivotMatrix(m, false); - } - _setRigMode() { - this._rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1); - this._rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0); - for (let cameraIndex = 0; cameraIndex < this._rigCameras.length; cameraIndex++) { - this._updateCamera(this._rigCameras[cameraIndex], cameraIndex); - } - } -} -//# sourceMappingURL=stereoscopicScreenUniversalCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/Stereoscopic/index.js - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/virtualJoysticksCamera.js - - - - -node_Node.AddNodeConstructor("VirtualJoysticksCamera", (name, scene) => { - return () => new VirtualJoysticksCamera(name, math_vector_Vector3.Zero(), scene); -}); -/** - * This represents a free type of camera. It can be useful in First Person Shooter game for instance. - * It is identical to the Free Camera and simply adds by default a virtual joystick. - * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#virtual-joysticks-camera - */ -class VirtualJoysticksCamera extends FreeCamera { - /** - * Instantiates a VirtualJoysticksCamera. It can be useful in First Person Shooter game for instance. - * It is identical to the Free Camera and simply adds by default a virtual joystick. - * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#virtual-joysticks-camera - * @param name Define the name of the camera in the scene - * @param position Define the start position of the camera in the scene - * @param scene Define the scene the camera belongs to - */ - constructor(name, position, scene) { - super(name, position, scene); - this.inputs.addVirtualJoystick(); - } - /** - * Gets the current object class name. - * @returns the class name - */ - getClassName() { - return "VirtualJoysticksCamera"; - } -} -//# sourceMappingURL=virtualJoysticksCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/VR/vrCameraMetrics.js - -/** - * This represents all the required metrics to create a VR camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#device-orientation-camera - */ -class VRCameraMetrics { - constructor() { - /** - * Define if the current vr camera should compensate the distortion of the lens or not. - */ - this.compensateDistortion = true; - /** - * Defines if multiview should be enabled when rendering (Default: false) - */ - this.multiviewEnabled = false; - } - /** - * Gets the rendering aspect ratio based on the provided resolutions. - */ - get aspectRatio() { - return this.hResolution / (2 * this.vResolution); - } - /** - * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes. - */ - get aspectRatioFov() { - return 2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)); - } - /** - * @internal - */ - get leftHMatrix() { - const meters = this.hScreenSize / 4 - this.lensSeparationDistance / 2; - const h = (4 * meters) / this.hScreenSize; - return math_vector_Matrix.Translation(h, 0, 0); - } - /** - * @internal - */ - get rightHMatrix() { - const meters = this.hScreenSize / 4 - this.lensSeparationDistance / 2; - const h = (4 * meters) / this.hScreenSize; - return math_vector_Matrix.Translation(-h, 0, 0); - } - /** - * @internal - */ - get leftPreViewMatrix() { - return math_vector_Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0); - } - /** - * @internal - */ - get rightPreViewMatrix() { - return math_vector_Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0); - } - /** - * Get the default VRMetrics based on the most generic setup. - * @returns the default vr metrics - */ - static GetDefault() { - const result = new VRCameraMetrics(); - result.hResolution = 1280; - result.vResolution = 800; - result.hScreenSize = 0.149759993; - result.vScreenSize = 0.0935999975; - result.vScreenCenter = 0.0467999987; - result.eyeToScreenDistance = 0.0410000011; - result.lensSeparationDistance = 0.063500002; - result.interpupillaryDistance = 0.064000003; - result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0]; - result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0]; - result.postProcessScaleFactor = 1.714605507808412; - result.lensCenterOffset = 0.151976421; - return result; - } -} -//# sourceMappingURL=vrCameraMetrics.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/vrDistortionCorrection.fragment.js -// Do not edit. - -const vrDistortionCorrection_fragment_name = "vrDistortionCorrectionPixelShader"; -const vrDistortionCorrection_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; -float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) -gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`; -// Sideeffect -ShaderStore.ShadersStore[vrDistortionCorrection_fragment_name] = vrDistortionCorrection_fragment_shader; -/** @internal */ -const vrDistortionCorrectionPixelShader = { name: vrDistortionCorrection_fragment_name, shader: vrDistortionCorrection_fragment_shader }; -//# sourceMappingURL=vrDistortionCorrection.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/vrDistortionCorrectionPostProcess.js - - - - -/** - * VRDistortionCorrectionPostProcess used for mobile VR - */ -class VRDistortionCorrectionPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "VRDistortionCorrectionPostProcess" string - */ - getClassName() { - return "VRDistortionCorrectionPostProcess"; - } - /** - * Initializes the VRDistortionCorrectionPostProcess - * @param name The name of the effect. - * @param camera The camera to apply the render pass to. - * @param isRightEye If this is for the right eye distortion - * @param vrMetrics All the required metrics for the VR camera - */ - constructor(name, camera, isRightEye, vrMetrics) { - super(name, "vrDistortionCorrection", ["LensCenter", "Scale", "ScaleIn", "HmdWarpParam"], null, vrMetrics.postProcessScaleFactor, camera, texture_Texture.BILINEAR_SAMPLINGMODE); - this._isRightEye = isRightEye; - this._distortionFactors = vrMetrics.distortionK; - this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor; - this._lensCenterOffset = vrMetrics.lensCenterOffset; - this.adaptScaleToCurrentViewport = true; - this.onSizeChangedObservable.add(() => { - this._scaleIn = new math_vector_Vector2(2, 2 / this.aspectRatio); - this._scaleFactor = new math_vector_Vector2(0.5 * (1 / this._postProcessScaleFactor), 0.5 * (1 / this._postProcessScaleFactor) * this.aspectRatio); - this._lensCenter = new math_vector_Vector2(this._isRightEye ? 0.5 - this._lensCenterOffset * 0.5 : 0.5 + this._lensCenterOffset * 0.5, 0.5); - }); - this.onApplyObservable.add((effect) => { - effect.setFloat2("LensCenter", this._lensCenter.x, this._lensCenter.y); - effect.setFloat2("Scale", this._scaleFactor.x, this._scaleFactor.y); - effect.setFloat2("ScaleIn", this._scaleIn.x, this._scaleIn.y); - effect.setFloat4("HmdWarpParam", this._distortionFactors[0], this._distortionFactors[1], this._distortionFactors[2], this._distortionFactors[3]); - }); - } -} -//# sourceMappingURL=vrDistortionCorrectionPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/vrMultiviewToSingleview.fragment.js -// Do not edit. - -const vrMultiviewToSingleview_fragment_name = "vrMultiviewToSingleviewPixelShader"; -const vrMultiviewToSingleview_fragment_shader = `precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`; -// Sideeffect -ShaderStore.ShadersStore[vrMultiviewToSingleview_fragment_name] = vrMultiviewToSingleview_fragment_shader; -/** @internal */ -const vrMultiviewToSingleviewPixelShader = { name: vrMultiviewToSingleview_fragment_name, shader: vrMultiviewToSingleview_fragment_shader }; -//# sourceMappingURL=vrMultiviewToSingleview.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/MultiviewRenderTarget.js - - -/** - * Renders to multiple views with a single draw call - * @see https://www.khronos.org/registry/webgl/extensions/OVR_multiview2/ - */ -class MultiviewRenderTarget extends renderTargetTexture_RenderTargetTexture { - set samples(value) { - // We override this setter because multisampling is handled by framebufferTextureMultisampleMultiviewOVR - this._samples = value; - } - get samples() { - return this._samples; - } - /** - * Creates a multiview render target - * @param scene scene used with the render target - * @param size the size of the render target (used for each view) - */ - constructor(scene, size = 512) { - super("multiview rtt", size, scene, false, true, 0, false, undefined, false, false, true, undefined, true); - this._renderTarget = this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight()); - this._texture = this._renderTarget.texture; - this._texture.isMultiview = true; - this._texture.format = 5; - this.samples = this._getEngine().getCaps().maxSamples || this.samples; - this._texture.samples = this._samples; - } - /** - * @internal - */ - _bindFrameBuffer() { - if (!this._renderTarget) { - return; - } - this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget); - } - /** - * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1) - * @returns the view count - */ - getViewCount() { - return 2; - } -} -//# sourceMappingURL=MultiviewRenderTarget.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.multiview.js - - - - - - - - -engine_Engine.prototype.createMultiviewRenderTargetTexture = function (width, height, colorTexture, depthStencilTexture) { - const gl = this._gl; - if (!this.getCaps().multiview) { - throw "Multiview is not supported"; - } - const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, { width, height }); - rtWrapper._framebuffer = gl.createFramebuffer(); - const internalTexture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Unknown, true); - internalTexture.width = width; - internalTexture.height = height; - internalTexture.isMultiview = true; - if (!colorTexture) { - colorTexture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D_ARRAY, colorTexture); - gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, width, height, 2); - } - rtWrapper._colorTextureArray = colorTexture; - if (!depthStencilTexture) { - depthStencilTexture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D_ARRAY, depthStencilTexture); - gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.DEPTH24_STENCIL8, width, height, 2); - } - rtWrapper._depthStencilTextureArray = depthStencilTexture; - internalTexture.isReady = true; - rtWrapper.setTextures(internalTexture); - rtWrapper._depthStencilTexture = internalTexture; - return rtWrapper; -}; -engine_Engine.prototype.bindMultiviewFramebuffer = function (_multiviewTexture) { - const multiviewTexture = _multiviewTexture; - const gl = this._gl; - const ext = this.getCaps().oculusMultiview || this.getCaps().multiview; - this.bindFramebuffer(multiviewTexture, undefined, undefined, undefined, true); - gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, multiviewTexture._framebuffer); - if (multiviewTexture._colorTextureArray && multiviewTexture._depthStencilTextureArray) { - if (this.getCaps().oculusMultiview) { - ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, multiviewTexture.samples, 0, 2); - ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, multiviewTexture.samples, 0, 2); - } - else { - ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, 0, 2); - ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, 0, 2); - } - } - else { - throw "Invalid multiview frame buffer"; - } -}; -engine_Engine.prototype.bindSpaceWarpFramebuffer = function (_spaceWarpTexture) { - const spaceWarpTexture = _spaceWarpTexture; - const gl = this._gl; - const ext = this.getCaps().oculusMultiview || this.getCaps().multiview; - this.bindFramebuffer(spaceWarpTexture, undefined, undefined, undefined, true); - gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, spaceWarpTexture._framebuffer); - if (spaceWarpTexture._colorTextureArray && spaceWarpTexture._depthStencilTextureArray) { - ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, spaceWarpTexture._colorTextureArray, 0, 0, 2); - ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_ATTACHMENT, spaceWarpTexture._depthStencilTextureArray, 0, 0, 2); - } - else { - throw new Error("Invalid Space Warp framebuffer"); - } -}; -camera_Camera.prototype._useMultiviewToSingleView = false; -camera_Camera.prototype._multiviewTexture = null; -camera_Camera.prototype._resizeOrCreateMultiviewTexture = function (width, height) { - if (!this._multiviewTexture) { - this._multiviewTexture = new MultiviewRenderTarget(this.getScene(), { width: width, height: height }); - } - else if (this._multiviewTexture.getRenderWidth() != width || this._multiviewTexture.getRenderHeight() != height) { - this._multiviewTexture.dispose(); - this._multiviewTexture = new MultiviewRenderTarget(this.getScene(), { width: width, height: height }); - } -}; -function createMultiviewUbo(engine, name) { - const ubo = new UniformBuffer(engine, undefined, true, name); - ubo.addUniform("viewProjection", 16); - ubo.addUniform("viewProjectionR", 16); - ubo.addUniform("view", 16); - ubo.addUniform("projection", 16); - ubo.addUniform("vEyePosition", 4); - return ubo; -} -const currentCreateSceneUniformBuffer = scene_Scene.prototype.createSceneUniformBuffer; -scene_Scene.prototype._transformMatrixR = math_vector_Matrix.Zero(); -scene_Scene.prototype._multiviewSceneUbo = null; -scene_Scene.prototype._createMultiviewUbo = function () { - this._multiviewSceneUbo = createMultiviewUbo(this.getEngine(), "scene_multiview"); -}; -scene_Scene.prototype.createSceneUniformBuffer = function (name) { - if (this._multiviewSceneUbo) { - return createMultiviewUbo(this.getEngine(), name); - } - return currentCreateSceneUniformBuffer.bind(this)(name); -}; -scene_Scene.prototype._updateMultiviewUbo = function (viewR, projectionR) { - if (viewR && projectionR) { - viewR.multiplyToRef(projectionR, this._transformMatrixR); - } - if (viewR && projectionR) { - viewR.multiplyToRef(projectionR, math_vector_TmpVectors.Matrix[0]); - Frustum.GetRightPlaneToRef(math_vector_TmpVectors.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane - } - if (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); - } -}; -scene_Scene.prototype._renderMultiviewToSingleView = function (camera) { - // Multiview is only able to be displayed directly for API's such as webXR - // This displays a multiview image by rendering to the multiview image and then - // copying the result into the sub cameras instead of rendering them and proceeding as normal from there - // Render to a multiview texture - 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)); - if (!this._multiviewSceneUbo) { - this._createMultiviewUbo(); - } - camera.outputRenderTarget = camera._multiviewTexture; - this._renderForCamera(camera); - camera.outputRenderTarget = null; - // Consume the multiview texture through a shader for each eye - for (let index = 0; index < camera._rigCameras.length; index++) { - const engine = this.getEngine(); - this._activeCamera = camera._rigCameras[index]; - engine.setViewport(this._activeCamera.viewport); - if (this.postProcessManager) { - this.postProcessManager._prepareFrame(); - this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate); - } - } -}; -//# sourceMappingURL=engine.multiview.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/vrMultiviewToSingleviewPostProcess.js - - - - -/** - * VRMultiviewToSingleview used to convert multiview texture arrays to standard textures for scenarios such as webVR - * This will not be used for webXR as it supports displaying texture arrays directly - */ -class VRMultiviewToSingleviewPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "VRMultiviewToSingleviewPostProcess" string - */ - getClassName() { - return "VRMultiviewToSingleviewPostProcess"; - } - /** - * Initializes a VRMultiviewToSingleview - * @param name name of the post process - * @param camera camera to be applied to - * @param scaleFactor scaling factor to the size of the output texture - */ - constructor(name, camera, scaleFactor) { - super(name, "vrMultiviewToSingleview", ["imageIndex"], ["multiviewSampler"], scaleFactor, camera, texture_Texture.BILINEAR_SAMPLINGMODE); - const cam = camera !== null && camera !== void 0 ? camera : this.getCamera(); - this.onSizeChangedObservable.add(() => { }); - this.onApplyObservable.add((effect) => { - if (cam._scene.activeCamera && cam._scene.activeCamera.isLeftCamera) { - effect.setInt("imageIndex", 0); - } - else { - effect.setInt("imageIndex", 1); - } - effect.setTexture("multiviewSampler", cam._multiviewTexture); - }); - } -} -//# sourceMappingURL=vrMultiviewToSingleviewPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/RigModes/vrRigMode.js - - - - - - -/** - * @internal - */ -function setVRRigMode(camera, rigParams) { - const metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault(); - camera._rigCameras[0]._cameraRigParams.vrMetrics = metrics; - camera._rigCameras[0].viewport = new math_viewport_Viewport(0, 0, 0.5, 1.0); - camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new math_vector_Matrix(); - camera._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix; - camera._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix; - camera._rigCameras[0].getProjectionMatrix = camera._rigCameras[0]._getVRProjectionMatrix; - camera._rigCameras[1]._cameraRigParams.vrMetrics = metrics; - camera._rigCameras[1].viewport = new math_viewport_Viewport(0.5, 0, 0.5, 1.0); - camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new math_vector_Matrix(); - camera._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix; - camera._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix; - camera._rigCameras[1].getProjectionMatrix = camera._rigCameras[1]._getVRProjectionMatrix; - // For multiview on a webVR camera - // First multiview will be rendered to camera._multiviewTexture - // Then this postprocess will run on each eye to copy the right texture to each eye - if (metrics.multiviewEnabled) { - if (!camera.getScene().getEngine().getCaps().multiview) { - logger_Logger.Warn("Multiview is not supported, falling back to standard rendering"); - metrics.multiviewEnabled = false; - } - else { - camera._useMultiviewToSingleView = true; - camera._rigPostProcess = new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview", camera, metrics.postProcessScaleFactor); - } - } - if (metrics.compensateDistortion) { - camera._rigCameras[0]._rigPostProcess = new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", camera._rigCameras[0], false, metrics); - camera._rigCameras[1]._rigPostProcess = new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", camera._rigCameras[1], true, metrics); - } -} -//# sourceMappingURL=vrRigMode.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationArcRotateCamera.js - - - - - - - -node_Node.AddNodeConstructor("VRDeviceOrientationArcRotateCamera", (name, scene) => { - return () => new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, math_vector_Vector3.Zero(), scene); -}); -/** - * Camera used to simulate VR rendering (based on ArcRotateCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras - */ -class VRDeviceOrientationArcRotateCamera extends ArcRotateCamera { - /** - * Creates a new VRDeviceOrientationArcRotateCamera - * @param name defines camera name - * @param alpha defines the camera rotation along the longitudinal axis - * @param beta defines the camera rotation along the latitudinal axis - * @param radius defines the camera distance from its target - * @param target defines the camera target - * @param scene defines the scene the camera belongs to - * @param compensateDistortion defines if the camera needs to compensate the lens distortion - * @param vrCameraMetrics defines the vr metrics associated to the camera - */ - constructor(name, alpha, beta, radius, target, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) { - super(name, alpha, beta, radius, target, scene); - this._setRigMode = setVRRigMode.bind(null, this); - vrCameraMetrics.compensateDistortion = compensateDistortion; - this.setCameraRigMode(camera_Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); - this.inputs.addVRDeviceOrientation(); - } - /** - * Gets camera class name - * @returns VRDeviceOrientationArcRotateCamera - */ - getClassName() { - return "VRDeviceOrientationArcRotateCamera"; - } -} -//# sourceMappingURL=vrDeviceOrientationArcRotateCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationFreeCamera.js - - - - - - -node_Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", (name, scene) => { - return () => new VRDeviceOrientationFreeCamera(name, math_vector_Vector3.Zero(), scene); -}); -/** - * Camera used to simulate VR rendering (based on FreeCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras - */ -class VRDeviceOrientationFreeCamera extends DeviceOrientationCamera { - /** - * Creates a new VRDeviceOrientationFreeCamera - * @param name defines camera name - * @param position defines the start position of the camera - * @param scene defines the scene the camera belongs to - * @param compensateDistortion defines if the camera needs to compensate the lens distortion - * @param vrCameraMetrics defines the vr metrics associated to the camera - */ - constructor(name, position, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) { - super(name, position, scene); - this._setRigMode = setVRRigMode.bind(null, this); - vrCameraMetrics.compensateDistortion = compensateDistortion; - this.setCameraRigMode(camera_Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); - } - /** - * Gets camera class name - * @returns VRDeviceOrientationFreeCamera - */ - getClassName() { - return "VRDeviceOrientationFreeCamera"; - } -} -//# sourceMappingURL=vrDeviceOrientationFreeCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationGamepadCamera.js - - - - - - -node_Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", (name, scene) => { - return () => new VRDeviceOrientationGamepadCamera(name, math_vector_Vector3.Zero(), scene); -}); -/** - * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera) - * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras - */ -class VRDeviceOrientationGamepadCamera extends VRDeviceOrientationFreeCamera { - /** - * Creates a new VRDeviceOrientationGamepadCamera - * @param name defines camera name - * @param position defines the start position of the camera - * @param scene defines the scene the camera belongs to - * @param compensateDistortion defines if the camera needs to compensate the lens distortion - * @param vrCameraMetrics defines the vr metrics associated to the camera - */ - constructor(name, position, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) { - super(name, position, scene, compensateDistortion, vrCameraMetrics); - this._setRigMode = setVRRigMode.bind(null, this); - this.inputs.addGamepad(); - } - /** - * Gets camera class name - * @returns VRDeviceOrientationGamepadCamera - */ - getClassName() { - return "VRDeviceOrientationGamepadCamera"; - } -} -//# sourceMappingURL=vrDeviceOrientationGamepadCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/hemisphericLight.js - - - - - - -node_Node.AddNodeConstructor("Light_Type_3", (name, scene) => { - return () => new HemisphericLight(name, math_vector_Vector3.Zero(), scene); -}); -/** - * The HemisphericLight simulates the ambient environment light, - * so the passed direction is the light reflection direction, not the incoming direction. - */ -class HemisphericLight extends light_Light { - /** - * Creates a HemisphericLight object in the scene according to the passed direction (Vector3). - * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction. - * The HemisphericLight can't cast shadows. - * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction - * @param name The friendly name of the light - * @param direction The direction of the light reflection - * @param scene The scene the light belongs to - */ - constructor(name, direction, scene) { - super(name, scene); - /** - * The groundColor is the light in the opposite direction to the one specified during creation. - * 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. - */ - this.groundColor = new math_color_Color3(0.0, 0.0, 0.0); - this.direction = direction || math_vector_Vector3.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(); - } - /** - * Returns the string "HemisphericLight". - * @returns The class name - */ - getClassName() { - return "HemisphericLight"; - } - /** - * Sets the HemisphericLight direction towards the passed target (Vector3). - * Returns the updated direction. - * @param target The target the direction should point to - * @returns The computed direction - */ - setDirectionToTarget(target) { - this.direction = math_vector_Vector3.Normalize(target.subtract(math_vector_Vector3.Zero())); - return this.direction; - } - /** - * Returns the shadow generator associated to the light. - * @returns Always null for hemispheric lights because it does not support shadows. - */ - getShadowGenerator() { - return null; - } - /** - * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string). - * @param _effect The effect to update - * @param lightIndex The index of the light in the effect to update - * @returns The hemispheric light - */ - transferToEffect(_effect, lightIndex) { - const normalizeDirection = math_vector_Vector3.Normalize(this.direction); - this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex); - this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex); - return this; - } - transferToNodeMaterialEffect(effect, lightDataUniformName) { - const normalizeDirection = math_vector_Vector3.Normalize(this.direction); - effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z); - return this; - } - /** - * Computes the world matrix of the node - * @returns the world matrix - */ - computeWorldMatrix() { - if (!this._worldMatrix) { - this._worldMatrix = math_vector_Matrix.Identity(); - } - return this._worldMatrix; - } - /** - * Returns the integer 3. - * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x - */ - getTypeID() { - return light_Light.LIGHTTYPEID_HEMISPHERICLIGHT; - } - /** - * Prepares the list of defines specific to the light type. - * @param defines the list of defines - * @param lightIndex defines the index of the light for the effect - */ - prepareLightSpecificDefines(defines, lightIndex) { - defines["HEMILIGHT" + lightIndex] = true; - } -} -__decorate([ - serializeAsColor3() -], HemisphericLight.prototype, "groundColor", void 0); -__decorate([ - serializeAsVector3() -], HemisphericLight.prototype, "direction", void 0); -//# sourceMappingURL=hemisphericLight.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/RigModes/webVRRigMode.js - - -/** - * @internal - */ -function setWebVRRigMode(camera, rigParams) { - if (rigParams.vrDisplay) { - const leftEye = rigParams.vrDisplay.getEyeParameters("left"); - const rightEye = rigParams.vrDisplay.getEyeParameters("right"); - //Left eye - camera._rigCameras[0].viewport = new math_viewport_Viewport(0, 0, 0.5, 1.0); - camera._rigCameras[0].setCameraRigParameter("left", true); - //leaving this for future reference - camera._rigCameras[0].setCameraRigParameter("specs", rigParams.specs); - camera._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye); - camera._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData); - camera._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera); - camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new math_vector_Matrix(); - camera._rigCameras[0].getProjectionMatrix = camera._getWebVRProjectionMatrix; - camera._rigCameras[0].parent = camera; - camera._rigCameras[0]._getViewMatrix = camera._getWebVRViewMatrix; - //Right eye - camera._rigCameras[1].viewport = new math_viewport_Viewport(0.5, 0, 0.5, 1.0); - camera._rigCameras[1].setCameraRigParameter("eyeParameters", rightEye); - camera._rigCameras[1].setCameraRigParameter("specs", rigParams.specs); - camera._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData); - camera._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera); - camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new math_vector_Matrix(); - camera._rigCameras[1].getProjectionMatrix = camera._getWebVRProjectionMatrix; - camera._rigCameras[1].parent = camera; - camera._rigCameras[1]._getViewMatrix = camera._getWebVRViewMatrix; - } -} -//# sourceMappingURL=webVRRigMode.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.webVR.js - - - - - -Object.defineProperty(engine_Engine.prototype, "isInVRExclusivePointerMode", { - get: function () { - return this._vrExclusivePointerMode; - }, - enumerable: true, - configurable: true, -}); -engine_Engine.prototype._prepareVRComponent = function () { - this._vrSupported = false; - this._vrExclusivePointerMode = false; - this.onVRDisplayChangedObservable = new observable_Observable(); - this.onVRRequestPresentComplete = new observable_Observable(); - this.onVRRequestPresentStart = new observable_Observable(); -}; -engine_Engine.prototype.isVRDevicePresent = function () { - return !!this._vrDisplay; -}; -engine_Engine.prototype.getVRDevice = function () { - return this._vrDisplay; -}; -engine_Engine.prototype.initWebVR = function () { - this.initWebVRAsync(); - return this.onVRDisplayChangedObservable; -}; -engine_Engine.prototype.initWebVRAsync = function () { - const notifyObservers = () => { - const eventArgs = { - vrDisplay: this._vrDisplay, - vrSupported: this._vrSupported, - }; - this.onVRDisplayChangedObservable.notifyObservers(eventArgs); - this._webVRInitPromise = new Promise((res) => { - res(eventArgs); - }); - }; - if (!this._onVrDisplayConnect) { - this._onVrDisplayConnect = (event) => { - this._vrDisplay = event.display; - notifyObservers(); - }; - this._onVrDisplayDisconnect = () => { - this._vrDisplay.cancelAnimationFrame(this._frameHandler); - this._vrDisplay = undefined; - this._frameHandler = engine_Engine.QueueNewFrame(this._boundRenderFunction); - notifyObservers(); - }; - this._onVrDisplayPresentChange = () => { - this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting; - }; - const hostWindow = this.getHostWindow(); - if (hostWindow) { - hostWindow.addEventListener("vrdisplayconnect", this._onVrDisplayConnect); - hostWindow.addEventListener("vrdisplaydisconnect", this._onVrDisplayDisconnect); - hostWindow.addEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChange); - } - } - this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync(); - this._webVRInitPromise.then(notifyObservers); - return this._webVRInitPromise; -}; -engine_Engine.prototype._getVRDisplaysAsync = function () { - return new Promise((res) => { - if (navigator.getVRDisplays) { - navigator.getVRDisplays().then((devices) => { - this._vrSupported = true; - // note that devices may actually be an empty array. This is fine; - // we expect this._vrDisplay to be undefined in this case. - this._vrDisplay = devices[0]; - res({ - vrDisplay: this._vrDisplay, - vrSupported: this._vrSupported, - }); - }); - } - else { - this._vrDisplay = undefined; - this._vrSupported = false; - res({ - vrDisplay: this._vrDisplay, - vrSupported: this._vrSupported, - }); - } - }); -}; -engine_Engine.prototype.enableVR = function (options) { - if (this._vrDisplay && !this._vrDisplay.isPresenting) { - const onResolved = () => { - this.onVRRequestPresentComplete.notifyObservers(true); - this._onVRFullScreenTriggered(); - }; - const onRejected = () => { - this.onVRRequestPresentComplete.notifyObservers(false); - }; - this.onVRRequestPresentStart.notifyObservers(this); - const presentationAttributes = { - highRefreshRate: this.vrPresentationAttributes ? this.vrPresentationAttributes.highRefreshRate : false, - foveationLevel: this.vrPresentationAttributes ? this.vrPresentationAttributes.foveationLevel : 1, - multiview: (this.getCaps().multiview || this.getCaps().oculusMultiview) && options.useMultiview, - }; - this._vrDisplay - .requestPresent([ - Object.assign({ source: this.getRenderingCanvas(), attributes: presentationAttributes }, presentationAttributes), - ]) - .then(onResolved) - .catch(onRejected); - } -}; -engine_Engine.prototype._onVRFullScreenTriggered = function () { - if (this._vrDisplay && this._vrDisplay.isPresenting) { - //get the old size before we change - this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight()); - this._oldHardwareScaleFactor = this.getHardwareScalingLevel(); - //get the width and height, change the render size - const leftEye = this._vrDisplay.getEyeParameters("left"); - this.setHardwareScalingLevel(1); - this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight); - } - else { - this.setHardwareScalingLevel(this._oldHardwareScaleFactor); - this.setSize(this._oldSize.width, this._oldSize.height); - } -}; -engine_Engine.prototype.disableVR = function () { - if (this._vrDisplay && this._vrDisplay.isPresenting) { - this._vrDisplay - .exitPresent() - .then(() => this._onVRFullScreenTriggered()) - .catch(() => this._onVRFullScreenTriggered()); - } - if (IsWindowObjectExist()) { - window.removeEventListener("vrdisplaypointerrestricted", this._onVRDisplayPointerRestricted); - window.removeEventListener("vrdisplaypointerunrestricted", this._onVRDisplayPointerUnrestricted); - if (this._onVrDisplayConnect) { - window.removeEventListener("vrdisplayconnect", this._onVrDisplayConnect); - if (this._onVrDisplayDisconnect) { - window.removeEventListener("vrdisplaydisconnect", this._onVrDisplayDisconnect); - } - if (this._onVrDisplayPresentChange) { - window.removeEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChange); - } - this._onVrDisplayConnect = null; - this._onVrDisplayDisconnect = null; - } - } -}; -engine_Engine.prototype._connectVREvents = function (canvas, document) { - this._onVRDisplayPointerRestricted = () => { - if (canvas) { - canvas.requestPointerLock(); - } - }; - this._onVRDisplayPointerUnrestricted = () => { - // Edge fix - for some reason document is not present and this is window - if (!document) { - const hostWindow = this.getHostWindow(); - if (hostWindow.document && hostWindow.document.exitPointerLock) { - hostWindow.document.exitPointerLock(); - } - return; - } - if (!document.exitPointerLock) { - return; - } - document.exitPointerLock(); - }; - if (IsWindowObjectExist()) { - const hostWindow = this.getHostWindow(); - hostWindow.addEventListener("vrdisplaypointerrestricted", this._onVRDisplayPointerRestricted, false); - hostWindow.addEventListener("vrdisplaypointerunrestricted", this._onVRDisplayPointerUnrestricted, false); - } -}; -engine_Engine.prototype._submitVRFrame = function () { - // Submit frame to the vr device, if enabled - if (this._vrDisplay && this._vrDisplay.isPresenting) { - // TODO: We should only submit the frame if we read frameData successfully. - try { - this._vrDisplay.submitFrame(); - } - catch (e) { - tools_Tools.Warn("webVR submitFrame has had an unexpected failure: " + e); - } - } -}; -engine_Engine.prototype.isVRPresenting = function () { - return this._vrDisplay && this._vrDisplay.isPresenting; -}; -engine_Engine.prototype._requestVRFrame = function () { - this._frameHandler = engine_Engine.QueueNewFrame(this._boundRenderFunction, this._vrDisplay); -}; -//# sourceMappingURL=engine.webVR.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/VR/webVRCamera.js - - - - - - - - - - - - -// Side effect import to add webvr support to engine - -node_Node.AddNodeConstructor("WebVRFreeCamera", (name, scene) => { - return () => new WebVRFreeCamera(name, math_vector_Vector3.Zero(), scene); -}); -node_Node.AddNodeConstructor("WebVRGamepadCamera", (name, scene) => { - return () => new WebVRFreeCamera(name, math_vector_Vector3.Zero(), scene); -}); -/** - * This represents a WebVR camera. - * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift. - * @deprecated Use WebXR instead - https://doc.babylonjs.com/features/featuresDeepDive/webXR - * @example https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRCamera - */ -class WebVRFreeCamera extends FreeCamera { - /** - * Instantiates a WebVRFreeCamera. - * @param name The name of the WebVRFreeCamera - * @param position The starting anchor position for the camera - * @param scene The scene the camera belongs to - * @param _webVROptions a set of customizable options for the webVRCamera - */ - constructor(name, position, scene, _webVROptions = {}) { - super(name, position, scene); - this._webVROptions = _webVROptions; - /** - * @internal - * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay - */ - this._vrDevice = null; - /** - * The rawPose of the vrDevice. - */ - this.rawPose = null; - this._specsVersion = "1.1"; - this._attached = false; - this._descendants = []; - // Represents device position and rotation in room space. Should only be used to help calculate babylon space values - this._deviceRoomPosition = math_vector_Vector3.Zero(); - /** @internal */ - this._deviceRoomRotationQuaternion = math_vector_Quaternion.Identity(); - this._standingMatrix = null; - /** - * Represents device position in babylon space. - */ - this.devicePosition = math_vector_Vector3.Zero(); - /** - * Represents device rotation in babylon space. - */ - this.deviceRotationQuaternion = math_vector_Quaternion.Identity(); - /** - * The scale of the device to be used when translating from device space to babylon space. - */ - this.deviceScaleFactor = 1; - this._deviceToWorld = math_vector_Matrix.Identity(); - this._worldToDevice = math_vector_Matrix.Identity(); - /** - * References to the webVR controllers for the vrDevice. - */ - this.controllers = []; - /** - * Emits an event when a controller is attached. - */ - this.onControllersAttachedObservable = new observable_Observable(); - /** - * Emits an event when a controller's mesh has been loaded; - */ - this.onControllerMeshLoadedObservable = new observable_Observable(); - /** - * Emits an event when the HMD's pose has been updated. - */ - this.onPoseUpdatedFromDeviceObservable = new observable_Observable(); - this._poseSet = false; - /** - * If the rig cameras be used as parent instead of this camera. - */ - this.rigParenting = true; - this._defaultHeight = undefined; - this._setRigMode = setWebVRRigMode.bind(null, this); - this._detachIfAttached = () => { - const vrDisplay = this.getEngine().getVRDevice(); - if (vrDisplay && !vrDisplay.isPresenting) { - this.detachControl(); - } - }; - this._workingVector = math_vector_Vector3.Zero(); - this._oneVector = math_vector_Vector3.One(); - this._workingMatrix = math_vector_Matrix.Identity(); - this._tmpMatrix = new math_vector_Matrix(); - this._cache.position = math_vector_Vector3.Zero(); - if (_webVROptions.defaultHeight) { - this._defaultHeight = _webVROptions.defaultHeight; - this.position.y = this._defaultHeight; - } - this.minZ = 0.1; - //legacy support - the compensation boolean was removed. - if (arguments.length === 5) { - // eslint-disable-next-line prefer-rest-params - this._webVROptions = arguments[4]; - } - // default webVR options - if (this._webVROptions.trackPosition == undefined) { - this._webVROptions.trackPosition = true; - } - if (this._webVROptions.controllerMeshes == undefined) { - this._webVROptions.controllerMeshes = true; - } - if (this._webVROptions.defaultLightingOnControllers == undefined) { - this._webVROptions.defaultLightingOnControllers = true; - } - this.rotationQuaternion = new math_vector_Quaternion(); - if (this._webVROptions && this._webVROptions.positionScale) { - this.deviceScaleFactor = this._webVROptions.positionScale; - } - //enable VR - const engine = this.getEngine(); - this._onVREnabled = (success) => { - if (success) { - this.initControllers(); - } - }; - engine.onVRRequestPresentComplete.add(this._onVREnabled); - engine.initWebVR().add((event) => { - if (!event.vrDisplay || this._vrDevice === event.vrDisplay) { - return; - } - this._vrDevice = event.vrDisplay; - //reset the rig parameters. - this.setCameraRigMode(camera_Camera.RIG_MODE_WEBVR, { parentCamera: this, vrDisplay: this._vrDevice, frameData: this._frameData, specs: this._specsVersion }); - if (this._attached) { - this.getEngine().enableVR(this._webVROptions); - } - }); - if (typeof VRFrameData !== "undefined") { - this._frameData = new VRFrameData(); - } - if (_webVROptions.useMultiview) { - if (!this.getScene().getEngine().getCaps().multiview) { - logger_Logger.Warn("Multiview is not supported, falling back to standard rendering"); - this._useMultiviewToSingleView = false; - } - else { - this._useMultiviewToSingleView = true; - this._rigPostProcess = new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview", this, 1.0); - } - } - /** - * The idea behind the following lines: - * objects that have the camera as parent should actually have the rig cameras as a parent. - * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera, - * the second will not show it correctly. - * - * To solve this - each object that has the camera as parent will be added to a protected array. - * When the rig camera renders, it will take this array and set all of those to be its children. - * This way, the right camera will be used as a parent, and the mesh will be rendered correctly. - * Amazing! - */ - this.getScene().onBeforeCameraRenderObservable.add((camera) => { - if (camera.parent === this && this.rigParenting) { - this._descendants = this.getDescendants(true, (n) => { - // don't take the cameras or the controllers! - const isController = this.controllers.some((controller) => { - return controller._mesh === n; - }); - const isRigCamera = this._rigCameras.indexOf(n) !== -1; - return !isController && !isRigCamera; - }); - this._descendants.forEach((node) => { - node.parent = camera; - }); - } - }); - this.getScene().onAfterCameraRenderObservable.add((camera) => { - if (camera.parent === this && this.rigParenting) { - this._descendants.forEach((node) => { - node.parent = this; - }); - } - }); - } - /** - * Gets the device distance from the ground in meters. - * @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. - */ - deviceDistanceToRoomGround() { - if (this._standingMatrix) { - // Add standing matrix offset to get real offset from ground in room - this._standingMatrix.getTranslationToRef(this._workingVector); - return this._deviceRoomPosition.y + this._workingVector.y; - } - //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero. - return this._defaultHeight || 0; - } - /** - * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground. - * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - useStandingMatrix(callback = (bool) => { }) { - // Use standing matrix if available - this.getEngine() - .initWebVRAsync() - .then((result) => { - if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !this._webVROptions.trackPosition) { - callback(false); - } - else { - this._standingMatrix = new math_vector_Matrix(); - math_vector_Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, this._standingMatrix); - if (!this.getScene().useRightHandedSystem) { - if (this._standingMatrix) { - this._standingMatrix.toggleModelMatrixHandInPlace(); - } - } - callback(true); - } - }); - } - /** - * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground. - * @returns A promise with a boolean set to if the standing matrix is supported. - */ - useStandingMatrixAsync() { - return new Promise((res) => { - this.useStandingMatrix((supported) => { - res(supported); - }); - }); - } - /** - * Disposes the camera - */ - dispose() { - this._detachIfAttached(); - this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled); - if (this._updateCacheWhenTrackingDisabledObserver) { - this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver); - } - super.dispose(); - } - /** - * Gets a vrController by name. - * @param name The name of the controller to retrieve - * @returns the controller matching the name specified or null if not found - */ - getControllerByName(name) { - for (const gp of this.controllers) { - if (gp.hand === name) { - return gp; - } - } - return null; - } - /** - * The controller corresponding to the users left hand. - */ - get leftController() { - if (!this._leftController) { - this._leftController = this.getControllerByName("left"); - } - return this._leftController; - } - /** - * The controller corresponding to the users right hand. - */ - get rightController() { - if (!this._rightController) { - this._rightController = this.getControllerByName("right"); - } - return this._rightController; - } - /** - * Casts a ray forward from the vrCamera's gaze. - * @param length Length of the ray (default: 100) - * @returns the ray corresponding to the gaze - */ - getForwardRay(length = 100) { - if (this.leftCamera) { - // Use left eye to avoid computation to compute center on every call - return super.getForwardRay(length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera - } - else { - return super.getForwardRay(length); - } - } - /** - * @internal - * Updates the camera based on device's frame data - */ - _checkInputs() { - if (this._vrDevice && this._vrDevice.isPresenting) { - this._vrDevice.getFrameData(this._frameData); - this.updateFromDevice(this._frameData.pose); - } - super._checkInputs(); - } - /** - * Updates the poseControlled values based on the input device pose. - * @param poseData Pose coming from the device - */ - updateFromDevice(poseData) { - if (poseData && poseData.orientation && poseData.orientation.length === 4) { - this.rawPose = poseData; - this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]); - if (this.getScene().useRightHandedSystem) { - this._deviceRoomRotationQuaternion.z *= -1; - this._deviceRoomRotationQuaternion.w *= -1; - } - if (this._webVROptions.trackPosition && this.rawPose.position) { - this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]); - if (this.getScene().useRightHandedSystem) { - this._deviceRoomPosition.z *= -1; - } - } - this._poseSet = true; - } - } - /** - * WebVR's attach control will start broadcasting frames to the device. - * Note that in certain browsers (chrome for example) this function must be called - * within a user-interaction callback. Example: - * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre> - * - * @param noPreventDefault prevent the default html element operation when attaching the vrDevice - */ - attachControl(noPreventDefault) { - // eslint-disable-next-line prefer-rest-params - noPreventDefault = tools_Tools.BackCompatCameraNoPreventDefault(arguments); - super.attachControl(noPreventDefault); - this._attached = true; - noPreventDefault = camera_Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault; - if (this._vrDevice) { - this.getEngine().enableVR(this._webVROptions); - } - const hostWindow = this._scene.getEngine().getHostWindow(); - if (hostWindow) { - hostWindow.addEventListener("vrdisplaypresentchange", this._detachIfAttached); - } - } - /** - * Detach the current controls from the specified dom element. - */ - detachControl() { - this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); - this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); - super.detachControl(); - this._attached = false; - this.getEngine().disableVR(); - window.removeEventListener("vrdisplaypresentchange", this._detachIfAttached); - } - /** - * @returns the name of this class - */ - getClassName() { - return "WebVRFreeCamera"; - } - /** - * Calls resetPose on the vrDisplay - * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose - */ - resetToCurrentRotation() { - //uses the vrDisplay's "resetPose()". - //pitch and roll won't be affected. - this._vrDevice.resetPose(); - } - /** - * @internal - * Updates the rig cameras (left and right eye) - */ - _updateRigCameras() { - const camLeft = this._rigCameras[0]; - const camRight = this._rigCameras[1]; - camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion); - camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion); - camLeft.position.copyFrom(this._deviceRoomPosition); - camRight.position.copyFrom(this._deviceRoomPosition); - } - // Remove translation from 6dof headset if trackposition is set to false - _correctPositionIfNotTrackPosition(matrix, isViewMatrix = false) { - if (this.rawPose && this.rawPose.position && !this._webVROptions.trackPosition) { - math_vector_Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix); - if (!isViewMatrix) { - this._tmpMatrix.invert(); - } - this._tmpMatrix.multiplyToRef(matrix, matrix); - } - } - /** - * @internal - * Updates the cached values of the camera - * @param ignoreParentClass ignores updating the parent class's cache (default: false) - */ - _updateCache(ignoreParentClass) { - if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) { - // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition - if (!this._updateCacheCalled) { - // make sure it is only called once per loop. this.update() might cause an infinite loop. - this._updateCacheCalled = true; - this.update(); - } - // Set working vector to the device position in room space rotated by the new rotation - this.rotationQuaternion.toRotationMatrix(this._workingMatrix); - math_vector_Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector); - // Subtract this vector from the current device position in world to get the translation for the device world matrix - this.devicePosition.subtractToRef(this._workingVector, this._workingVector); - math_vector_Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld); - // Add translation from anchor position - this._deviceToWorld.getTranslationToRef(this._workingVector); - this._workingVector.addInPlace(this.position); - this._workingVector.subtractInPlace(this._cache.position); - this._deviceToWorld.setTranslation(this._workingVector); - // Set an inverted matrix to be used when updating the camera - this._deviceToWorld.invertToRef(this._worldToDevice); - // Update the gamepad to ensure the mesh is updated on the same frame as camera - this.controllers.forEach((controller) => { - controller._deviceToWorld.copyFrom(this._deviceToWorld); - this._correctPositionIfNotTrackPosition(controller._deviceToWorld); - controller.update(); - }); - } - if (!ignoreParentClass) { - super._updateCache(); - } - this._updateCacheCalled = false; - } - /** - * @internal - * Get current device position in babylon world - */ - _computeDevicePosition() { - math_vector_Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition); - } - /** - * Updates the current device position and rotation in the babylon world - */ - update() { - this._computeDevicePosition(); - // Get current device rotation in babylon world - math_vector_Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix); - this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix); - math_vector_Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion); - if (this._poseSet) { - this.onPoseUpdatedFromDeviceObservable.notifyObservers(null); - } - super.update(); - } - /** - * @internal - * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix) - * @returns an identity matrix - */ - _getViewMatrix() { - return math_vector_Matrix.Identity(); - } - /** - * This function is called by the two RIG cameras. - * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance) - * @internal - */ - _getWebVRViewMatrix() { - // Update the parent camera prior to using a child camera to avoid desynchronization - const parentCamera = this._cameraRigParams["parentCamera"]; - parentCamera._updateCache(); - //WebVR 1.1 - const viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix; - math_vector_Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix); - if (!this.getScene().useRightHandedSystem) { - this._webvrViewMatrix.toggleModelMatrixHandInPlace(); - } - // update the camera rotation matrix - this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix); - math_vector_Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint); - // Computing target and final matrix - this.position.addToRef(this._transformedReferencePoint, this._currentTarget); - // should the view matrix be updated with scale and position offset? - if (parentCamera.deviceScaleFactor !== 1) { - this._webvrViewMatrix.invert(); - // scale the position, if set - if (parentCamera.deviceScaleFactor) { - this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor); - this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor); - this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor); - } - this._webvrViewMatrix.invert(); - } - // Remove translation from 6dof headset if trackposition is set to false - parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true); - parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix); - // Compute global position - this._workingMatrix = this._workingMatrix || math_vector_Matrix.Identity(); - this._webvrViewMatrix.invertToRef(this._workingMatrix); - this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix); - this._workingMatrix.getTranslationToRef(this._globalPosition); - this._markSyncedWithParent(); - return this._webvrViewMatrix; - } - /** @internal */ - _getWebVRProjectionMatrix() { - const parentCamera = this.parent; - parentCamera._vrDevice.depthNear = parentCamera.minZ; - parentCamera._vrDevice.depthFar = parentCamera.maxZ; - const projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix; - math_vector_Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix); - //babylon compatible matrix - if (!this.getScene().useRightHandedSystem) { - this._projectionMatrix.toggleProjectionMatrixHandInPlace(); - } - return this._projectionMatrix; - } - /** - * Initializes the controllers and their meshes - */ - initControllers() { - this.controllers.length = 0; - const manager = this.getScene().gamepadManager; - this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => { - if (gamepad.type === Gamepad.POSE_ENABLED) { - const webVrController = gamepad; - if (webVrController.defaultModel) { - webVrController.defaultModel.setEnabled(false); - } - if (webVrController.hand === "right") { - this._rightController = null; - } - if (webVrController.hand === "left") { - this._leftController = null; - } - const controllerIndex = this.controllers.indexOf(webVrController); - if (controllerIndex !== -1) { - this.controllers.splice(controllerIndex, 1); - } - } - }); - this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => { - if (gamepad.type === Gamepad.POSE_ENABLED) { - const webVrController = gamepad; - if (!this._webVROptions.trackPosition) { - webVrController._disableTrackPosition(new math_vector_Vector3(webVrController.hand == "left" ? -0.15 : 0.15, -0.5, 0.25)); - // Cache must be updated before rendering controllers to avoid them being one frame behind - if (!this._updateCacheWhenTrackingDisabledObserver) { - this._updateCacheWhenTrackingDisabledObserver = this._scene.onBeforeRenderObservable.add(() => { - this._updateCache(); - }); - } - } - webVrController.deviceScaleFactor = this.deviceScaleFactor; - webVrController._deviceToWorld.copyFrom(this._deviceToWorld); - this._correctPositionIfNotTrackPosition(webVrController._deviceToWorld); - if (this._webVROptions.controllerMeshes) { - if (webVrController.defaultModel) { - webVrController.defaultModel.setEnabled(true); - } - else { - // Load the meshes - webVrController.initControllerMesh(this.getScene(), (loadedMesh) => { - loadedMesh.scaling.scaleInPlace(this.deviceScaleFactor); - this.onControllerMeshLoadedObservable.notifyObservers(webVrController); - if (this._webVROptions.defaultLightingOnControllers) { - if (!this._lightOnControllers) { - this._lightOnControllers = new HemisphericLight("vrControllersLight", new math_vector_Vector3(0, 1, 0), this.getScene()); - } - const activateLightOnSubMeshes = function (mesh, light) { - const children = mesh.getChildren(); - if (children && children.length !== 0) { - children.forEach((mesh) => { - light.includedOnlyMeshes.push(mesh); - activateLightOnSubMeshes(mesh, light); - }); - } - }; - this._lightOnControllers.includedOnlyMeshes.push(loadedMesh); - activateLightOnSubMeshes(loadedMesh, this._lightOnControllers); - } - }); - } - } - webVrController.attachToPoseControlledCamera(this); - // since this is async - sanity check. Is the controller already stored? - if (this.controllers.indexOf(webVrController) === -1) { - //add to the controllers array - this.controllers.push(webVrController); - // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property - // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them... - // So we're overriding setting left & right manually to be sure - let firstViveWandDetected = false; - for (let i = 0; i < this.controllers.length; i++) { - if (this.controllers[i].controllerType === PoseEnabledControllerType.VIVE) { - if (!firstViveWandDetected) { - firstViveWandDetected = true; - this.controllers[i].hand = "left"; - } - else { - this.controllers[i].hand = "right"; - } - } - } - //did we find enough controllers? Great! let the developer know. - if (this.controllers.length >= 2) { - this.onControllersAttachedObservable.notifyObservers(this.controllers); - } - } - } - }); - } -} -//# sourceMappingURL=webVRCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/Controllers/webVRController.js - - -/** - * Defines the WebVRController object that represents controllers tracked in 3D space - * @deprecated Use WebXR instead - */ -class WebVRController extends poseEnabledController_PoseEnabledController { - /** - * Fired when a controller button's state has changed - * @param callback the callback containing the button that was modified - */ - onButtonStateChange(callback) { - this._onButtonStateChange = callback; - } - /** - * The default controller model for the controller - */ - get defaultModel() { - return this._defaultModel; - } - /** - * Creates a new WebVRController from a gamepad - * @param vrGamepad the gamepad that the WebVRController should be created from - */ - constructor(vrGamepad) { - super(vrGamepad); - // Observables - /** - * Fired when the trigger state has changed - */ - this.onTriggerStateChangedObservable = new observable_Observable(); - /** - * Fired when the main button state has changed - */ - this.onMainButtonStateChangedObservable = new observable_Observable(); - /** - * Fired when the secondary button state has changed - */ - this.onSecondaryButtonStateChangedObservable = new observable_Observable(); - /** - * Fired when the pad state has changed - */ - this.onPadStateChangedObservable = new observable_Observable(); - /** - * Fired when controllers stick values have changed - */ - this.onPadValuesChangedObservable = new observable_Observable(); - /** - * X and Y axis corresponding to the controllers joystick - */ - this.pad = { x: 0, y: 0 }; - // avoid GC, store state in a tmp object - this._changes = { - pressChanged: false, - touchChanged: false, - valueChanged: false, - changed: false, - }; - this._buttons = new Array(vrGamepad.buttons.length); - this.hand = vrGamepad.hand; - } - /** - * Updates the state of the controller and mesh based on the current position and rotation of the controller - */ - update() { - super.update(); - for (let index = 0; index < this._buttons.length; index++) { - this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index); - } - if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) { - this.pad.x = this.leftStick.x; - this.pad.y = this.leftStick.y; - this.onPadValuesChangedObservable.notifyObservers(this.pad); - } - } - _setButtonValue(newState, currentState, buttonIndex) { - if (!newState) { - newState = { - pressed: false, - touched: false, - value: 0, - }; - } - if (!currentState) { - this._buttons[buttonIndex] = { - pressed: newState.pressed, - touched: newState.touched, - value: newState.value, - }; - return; - } - this._checkChanges(newState, currentState); - if (this._changes.changed) { - this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState); - this._handleButtonChange(buttonIndex, newState, this._changes); - } - this._buttons[buttonIndex].pressed = newState.pressed; - this._buttons[buttonIndex].touched = newState.touched; - // oculus triggers are never 0, thou not touched. - this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value; - } - _checkChanges(newState, currentState) { - this._changes.pressChanged = newState.pressed !== currentState.pressed; - this._changes.touchChanged = newState.touched !== currentState.touched; - this._changes.valueChanged = newState.value !== currentState.value; - this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged; - return this._changes; - } - /** - * Disposes of th webVRController - */ - dispose() { - super.dispose(); - this._defaultModel = null; - this.onTriggerStateChangedObservable.clear(); - this.onMainButtonStateChangedObservable.clear(); - this.onSecondaryButtonStateChangedObservable.clear(); - this.onPadStateChangedObservable.clear(); - this.onPadValuesChangedObservable.clear(); - } -} -//# sourceMappingURL=webVRController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/prePassConfiguration.js - -/** - * Configuration needed for prepass-capable materials - */ -class PrePassConfiguration { - constructor() { - /** - * Previous world matrices of meshes carrying this material - * Used for computing velocity - */ - this.previousWorldMatrices = {}; - /** - * Previous bones of meshes carrying this material - * Used for computing velocity - */ - this.previousBones = {}; - } - /** - * Add the required uniforms to the current list. - * @param uniforms defines the current uniform list. - */ - static AddUniforms(uniforms) { - uniforms.push("previousWorld", "previousViewProjection", "mPreviousBones"); - } - /** - * Add the required samplers to the current list. - * @param samplers defines the current sampler list. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static AddSamplers(samplers) { - // pass - } - /** - * Binds the material data. - * @param effect defines the effect to update - * @param scene defines the scene the material belongs to. - * @param mesh The mesh - * @param world World matrix of this mesh - * @param isFrozen Is the material frozen - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - bindForSubMesh(effect, scene, mesh, world, isFrozen) { - if (scene.prePassRenderer && scene.prePassRenderer.enabled && scene.prePassRenderer.currentRTisSceneRT) { - if (scene.prePassRenderer.getIndex(2) !== -1) { - if (!this.previousWorldMatrices[mesh.uniqueId]) { - this.previousWorldMatrices[mesh.uniqueId] = world.clone(); - } - if (!this.previousViewProjection) { - this.previousViewProjection = scene.getTransformMatrix().clone(); - this.currentViewProjection = scene.getTransformMatrix().clone(); - } - const engine = scene.getEngine(); - if (this.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) { - // First update of the prepass configuration for this rendering pass - this._lastUpdateFrameId = engine.frameId; - this.previousViewProjection.copyFrom(this.currentViewProjection); - this.currentViewProjection.copyFrom(scene.getTransformMatrix()); - } - else if (this._lastUpdateFrameId !== engine.frameId) { - // The scene transformation did not change from the previous frame (so no camera motion), we must update previousViewProjection accordingly - this._lastUpdateFrameId = engine.frameId; - this.previousViewProjection.copyFrom(this.currentViewProjection); - } - effect.setMatrix("previousWorld", this.previousWorldMatrices[mesh.uniqueId]); - effect.setMatrix("previousViewProjection", this.previousViewProjection); - this.previousWorldMatrices[mesh.uniqueId] = world.clone(); - } - } - } -} -//# sourceMappingURL=prePassConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/materialFlags.js - - -/** - * This groups all the flags used to control the materials channel. - */ -class MaterialFlags { - /** - * Are diffuse textures enabled in the application. - */ - static get DiffuseTextureEnabled() { - return this._DiffuseTextureEnabled; - } - static set DiffuseTextureEnabled(value) { - if (this._DiffuseTextureEnabled === value) { - return; - } - this._DiffuseTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are detail textures enabled in the application. - */ - static get DetailTextureEnabled() { - return this._DetailTextureEnabled; - } - static set DetailTextureEnabled(value) { - if (this._DetailTextureEnabled === value) { - return; - } - this._DetailTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are decal maps enabled in the application. - */ - static get DecalMapEnabled() { - return this._DecalMapEnabled; - } - static set DecalMapEnabled(value) { - if (this._DecalMapEnabled === value) { - return; - } - this._DecalMapEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are ambient textures enabled in the application. - */ - static get AmbientTextureEnabled() { - return this._AmbientTextureEnabled; - } - static set AmbientTextureEnabled(value) { - if (this._AmbientTextureEnabled === value) { - return; - } - this._AmbientTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are opacity textures enabled in the application. - */ - static get OpacityTextureEnabled() { - return this._OpacityTextureEnabled; - } - static set OpacityTextureEnabled(value) { - if (this._OpacityTextureEnabled === value) { - return; - } - this._OpacityTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are reflection textures enabled in the application. - */ - static get ReflectionTextureEnabled() { - return this._ReflectionTextureEnabled; - } - static set ReflectionTextureEnabled(value) { - if (this._ReflectionTextureEnabled === value) { - return; - } - this._ReflectionTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are emissive textures enabled in the application. - */ - static get EmissiveTextureEnabled() { - return this._EmissiveTextureEnabled; - } - static set EmissiveTextureEnabled(value) { - if (this._EmissiveTextureEnabled === value) { - return; - } - this._EmissiveTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are specular textures enabled in the application. - */ - static get SpecularTextureEnabled() { - return this._SpecularTextureEnabled; - } - static set SpecularTextureEnabled(value) { - if (this._SpecularTextureEnabled === value) { - return; - } - this._SpecularTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are bump textures enabled in the application. - */ - static get BumpTextureEnabled() { - return this._BumpTextureEnabled; - } - static set BumpTextureEnabled(value) { - if (this._BumpTextureEnabled === value) { - return; - } - this._BumpTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are lightmap textures enabled in the application. - */ - static get LightmapTextureEnabled() { - return this._LightmapTextureEnabled; - } - static set LightmapTextureEnabled(value) { - if (this._LightmapTextureEnabled === value) { - return; - } - this._LightmapTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are refraction textures enabled in the application. - */ - static get RefractionTextureEnabled() { - return this._RefractionTextureEnabled; - } - static set RefractionTextureEnabled(value) { - if (this._RefractionTextureEnabled === value) { - return; - } - this._RefractionTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are color grading textures enabled in the application. - */ - static get ColorGradingTextureEnabled() { - return this._ColorGradingTextureEnabled; - } - static set ColorGradingTextureEnabled(value) { - if (this._ColorGradingTextureEnabled === value) { - return; - } - this._ColorGradingTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are fresnels enabled in the application. - */ - static get FresnelEnabled() { - return this._FresnelEnabled; - } - static set FresnelEnabled(value) { - if (this._FresnelEnabled === value) { - return; - } - this._FresnelEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(4); - } - /** - * Are clear coat textures enabled in the application. - */ - static get ClearCoatTextureEnabled() { - return this._ClearCoatTextureEnabled; - } - static set ClearCoatTextureEnabled(value) { - if (this._ClearCoatTextureEnabled === value) { - return; - } - this._ClearCoatTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are clear coat bump textures enabled in the application. - */ - static get ClearCoatBumpTextureEnabled() { - return this._ClearCoatBumpTextureEnabled; - } - static set ClearCoatBumpTextureEnabled(value) { - if (this._ClearCoatBumpTextureEnabled === value) { - return; - } - this._ClearCoatBumpTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are clear coat tint textures enabled in the application. - */ - static get ClearCoatTintTextureEnabled() { - return this._ClearCoatTintTextureEnabled; - } - static set ClearCoatTintTextureEnabled(value) { - if (this._ClearCoatTintTextureEnabled === value) { - return; - } - this._ClearCoatTintTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are sheen textures enabled in the application. - */ - static get SheenTextureEnabled() { - return this._SheenTextureEnabled; - } - static set SheenTextureEnabled(value) { - if (this._SheenTextureEnabled === value) { - return; - } - this._SheenTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are anisotropic textures enabled in the application. - */ - static get AnisotropicTextureEnabled() { - return this._AnisotropicTextureEnabled; - } - static set AnisotropicTextureEnabled(value) { - if (this._AnisotropicTextureEnabled === value) { - return; - } - this._AnisotropicTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are thickness textures enabled in the application. - */ - static get ThicknessTextureEnabled() { - return this._ThicknessTextureEnabled; - } - static set ThicknessTextureEnabled(value) { - if (this._ThicknessTextureEnabled === value) { - return; - } - this._ThicknessTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are refraction intensity textures enabled in the application. - */ - static get RefractionIntensityTextureEnabled() { - return this._ThicknessTextureEnabled; - } - static set RefractionIntensityTextureEnabled(value) { - if (this._RefractionIntensityTextureEnabled === value) { - return; - } - this._RefractionIntensityTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are translucency intensity textures enabled in the application. - */ - static get TranslucencyIntensityTextureEnabled() { - return this._ThicknessTextureEnabled; - } - static set TranslucencyIntensityTextureEnabled(value) { - if (this._TranslucencyIntensityTextureEnabled === value) { - return; - } - this._TranslucencyIntensityTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } - /** - * Are translucency intensity textures enabled in the application. - */ - static get IridescenceTextureEnabled() { - return this._IridescenceTextureEnabled; - } - static set IridescenceTextureEnabled(value) { - if (this._IridescenceTextureEnabled === value) { - return; - } - this._IridescenceTextureEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(1); - } -} -// Flags used to enable or disable a type of texture for all Standard Materials -MaterialFlags._DiffuseTextureEnabled = true; -MaterialFlags._DetailTextureEnabled = true; -MaterialFlags._DecalMapEnabled = true; -MaterialFlags._AmbientTextureEnabled = true; -MaterialFlags._OpacityTextureEnabled = true; -MaterialFlags._ReflectionTextureEnabled = true; -MaterialFlags._EmissiveTextureEnabled = true; -MaterialFlags._SpecularTextureEnabled = true; -MaterialFlags._BumpTextureEnabled = true; -MaterialFlags._LightmapTextureEnabled = true; -MaterialFlags._RefractionTextureEnabled = true; -MaterialFlags._ColorGradingTextureEnabled = true; -MaterialFlags._FresnelEnabled = true; -MaterialFlags._ClearCoatTextureEnabled = true; -MaterialFlags._ClearCoatBumpTextureEnabled = true; -MaterialFlags._ClearCoatTintTextureEnabled = true; -MaterialFlags._SheenTextureEnabled = true; -MaterialFlags._AnisotropicTextureEnabled = true; -MaterialFlags._ThicknessTextureEnabled = true; -MaterialFlags._RefractionIntensityTextureEnabled = true; -MaterialFlags._TranslucencyIntensityTextureEnabled = true; -MaterialFlags._IridescenceTextureEnabled = true; -//# sourceMappingURL=materialFlags.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragmentDeclaration.js -// Do not edit. - -const decalFragmentDeclaration_name = "decalFragmentDeclaration"; -const decalFragmentDeclaration_shader = `#ifdef DECAL -uniform vec4 vDecalInfos; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[decalFragmentDeclaration_name] = decalFragmentDeclaration_shader; -/** @internal */ -const decalFragmentDeclaration = { name: decalFragmentDeclaration_name, shader: decalFragmentDeclaration_shader }; -//# sourceMappingURL=decalFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultFragmentDeclaration.js -// Do not edit. - - -const defaultFragmentDeclaration_name = "defaultFragmentDeclaration"; -const defaultFragmentDeclaration_shader = `uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; -#ifdef SPECULARTERM -uniform vec4 vSpecularColor; -#endif -uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; -#ifdef DIFFUSE -uniform vec2 vDiffuseInfos; -#endif -#ifdef AMBIENT -uniform vec2 vAmbientInfos; -#endif -#ifdef OPACITY -uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#ifdef ALPHATEST -uniform float alphaCutOff; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) -uniform mat4 view; -#endif -#ifdef REFRACTION -uniform vec4 vRefractionInfos; -#ifndef REFRACTIONMAP_3D -uniform mat4 refractionMatrix; -#endif -#ifdef REFRACTIONFRESNEL -uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; -#endif -#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) -uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; -#endif -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) -uniform vec2 vSpecularInfos; -#endif -#ifdef DIFFUSEFRESNEL -uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; -#endif -#ifdef OPACITYFRESNEL -uniform vec4 opacityParts; -#endif -#ifdef EMISSIVEFRESNEL -uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos; -#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) -uniform mat4 reflectionMatrix; -#endif -#ifndef REFLECTIONMAP_SKYBOX -#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -#ifdef REFLECTIONFRESNEL -uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; -#endif -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos; -#endif -#include<decalFragmentDeclaration> -#define ADDITIONAL_FRAGMENT_DECLARATION -`; -// Sideeffect -ShaderStore.IncludesShadersStore[defaultFragmentDeclaration_name] = defaultFragmentDeclaration_shader; -/** @internal */ -const defaultFragmentDeclaration = { name: defaultFragmentDeclaration_name, shader: defaultFragmentDeclaration_shader }; -//# sourceMappingURL=defaultFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneUboDeclaration.js -// Do not edit. - -const sceneUboDeclaration_name = "sceneUboDeclaration"; -const sceneUboDeclaration_shader = `layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; -#ifdef MULTIVIEW -mat4 viewProjectionR; -#endif -mat4 view;mat4 projection;vec4 vEyePosition;}; -`; -// Sideeffect -ShaderStore.IncludesShadersStore[sceneUboDeclaration_name] = sceneUboDeclaration_shader; -/** @internal */ -const sceneUboDeclaration = { name: sceneUboDeclaration_name, shader: sceneUboDeclaration_shader }; -//# sourceMappingURL=sceneUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/meshUboDeclaration.js -// Do not edit. - -const meshUboDeclaration_name = "meshUboDeclaration"; -const meshUboDeclaration_shader = `#ifdef WEBGL2 -uniform mat4 world;uniform float visibility; -#else -layout(std140,column_major) uniform;uniform Mesh -{mat4 world;float visibility;}; -#endif -#define WORLD_UBO -`; -// Sideeffect -ShaderStore.IncludesShadersStore[meshUboDeclaration_name] = meshUboDeclaration_shader; -/** @internal */ -const meshUboDeclaration = { name: meshUboDeclaration_name, shader: meshUboDeclaration_shader }; -//# sourceMappingURL=meshUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultUboDeclaration.js -// Do not edit. - - - -const defaultUboDeclaration_name = "defaultUboDeclaration"; -const defaultUboDeclaration_shader = `layout(std140,column_major) uniform;uniform Material -{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; -#define ADDITIONAL_UBO_DECLARATION -}; -#include<sceneUboDeclaration> -#include<meshUboDeclaration> -`; -// Sideeffect -ShaderStore.IncludesShadersStore[defaultUboDeclaration_name] = defaultUboDeclaration_shader; -/** @internal */ -const defaultUboDeclaration = { name: defaultUboDeclaration_name, shader: defaultUboDeclaration_shader }; -//# sourceMappingURL=defaultUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassDeclaration.js -// Do not edit. - -const prePassDeclaration_name = "prePassDeclaration"; -const prePassDeclaration_shader = `#ifdef PREPASS -#extension GL_EXT_draw_buffers : require -layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; -#ifdef PREPASS_DEPTH -varying highp vec3 vViewPos; -#endif -#ifdef PREPASS_VELOCITY -varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[prePassDeclaration_name] = prePassDeclaration_shader; -/** @internal */ -const prePassDeclaration = { name: prePassDeclaration_name, shader: prePassDeclaration_shader }; -//# sourceMappingURL=prePassDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/oitDeclaration.js -// Do not edit. - -const oitDeclaration_name = "oitDeclaration"; -const oitDeclaration_shader = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY -#extension GL_EXT_draw_buffers : require -layout(location=0) out vec2 depth; -layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; -#define MAX_DEPTH 99999.0 -highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[oitDeclaration_name] = oitDeclaration_shader; -/** @internal */ -const oitDeclaration = { name: oitDeclaration_name, shader: oitDeclaration_shader }; -//# sourceMappingURL=oitDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/mainUVVaryingDeclaration.js -// Do not edit. - -const mainUVVaryingDeclaration_name = "mainUVVaryingDeclaration"; -const mainUVVaryingDeclaration_shader = `#ifdef MAINUV{X} -varying vec2 vMainUV{X}; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[mainUVVaryingDeclaration_name] = mainUVVaryingDeclaration_shader; -/** @internal */ -const mainUVVaryingDeclaration = { name: mainUVVaryingDeclaration_name, shader: mainUVVaryingDeclaration_shader }; -//# sourceMappingURL=mainUVVaryingDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/helperFunctions.js -// Do not edit. - -const helperFunctions_name = "helperFunctions"; -const helperFunctions_shader = `const float PI=3.1415926535897932384626433832795;const float HALF_MIN=5.96046448e-08; -const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; -#define saturate(x) clamp(x,0.0,1.0) -#define absEps(x) abs(x)+Epsilon -#define maxEps(x) max(x,Epsilon) -#define saturateEps(x) clamp(x,Epsilon,1.0) -mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( -vec3(i0.x,i1.x,i2.x), -vec3(i0.y,i1.y,i2.y), -vec3(i0.z,i1.z,i2.z) -);return outMatrix;} -mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), -b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), -b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} -#if USE_EXACT_SRGB_CONVERSIONS -vec3 toLinearSpaceExact(vec3 color) -{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); -#else -return -vec3( -color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, -color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, -color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); -#endif -} -vec3 toGammaSpaceExact(vec3 color) -{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); -#else -return -vec3( -color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, -color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, -color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); -#endif -} -#endif -float toLinearSpace(float color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; -#else -return pow(color,LinearEncodePowerApprox); -#endif -} -vec3 toLinearSpace(vec3 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return toLinearSpaceExact(color); -#else -return pow(color,vec3(LinearEncodePowerApprox)); -#endif -} -vec4 toLinearSpace(vec4 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return vec4(toLinearSpaceExact(color.rgb),color.a); -#else -return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); -#endif -} -float toGammaSpace(float color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; -#else -return pow(color,GammaEncodePowerApprox); -#endif -} -vec3 toGammaSpace(vec3 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return toGammaSpaceExact(color); -#else -return pow(color,vec3(GammaEncodePowerApprox)); -#endif -} -vec4 toGammaSpace(vec4 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return vec4(toGammaSpaceExact(color.rgb),color.a); -#else -return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); -#endif -} -float square(float value) -{return value*value;} -vec3 square(vec3 value) -{return value*value;} -float pow5(float value) {float sq=value*value;return sq*sq*value;} -float getLuminance(vec3 color) -{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} -float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} -float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} -const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); } -vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} -vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} -`; -// Sideeffect -ShaderStore.IncludesShadersStore[helperFunctions_name] = helperFunctions_shader; -/** @internal */ -const helperFunctions = { name: helperFunctions_name, shader: helperFunctions_shader }; -//# sourceMappingURL=helperFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragmentDeclaration.js -// Do not edit. - -const lightFragmentDeclaration_name = "lightFragmentDeclaration"; -const lightFragmentDeclaration_shader = `#ifdef LIGHT{X} -uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; -#ifdef SPECULARTERM -uniform vec4 vLightSpecular{X}; -#else -vec4 vLightSpecular{X}=vec4(0.); -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DArrayShadow shadowSampler{X}; -#else -uniform highp sampler2DArray shadowSampler{X}; -#endif -#ifdef SHADOWCSMDEBUG{X} -const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] -( -vec3 ( 1.5,0.0,0.0 ), -vec3 ( 0.0,1.5,0.0 ), -vec3 ( 0.0,0.0,5.5 ), -vec3 ( 1.5,0.0,5.5 ), -vec3 ( 1.5,1.5,0.0 ), -vec3 ( 1.0,1.0,1.0 ), -vec3 ( 0.0,1.0,5.5 ), -vec3 ( 0.5,3.5,0.75 ) -);vec3 shadowDebug{X}; -#endif -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -int index{X}=-1; -#else -int index{X}=SHADOWCSMNUM_CASCADES{X}-1; -#endif -float diff{X}=0.; -#elif defined(SHADOWCUBE{X}) -uniform samplerCube shadowSampler{X}; -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DShadow shadowSampler{X}; -#else -uniform sampler2D shadowSampler{X}; -#endif -uniform mat4 lightMatrix{X}; -#endif -uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; -#endif -#ifdef SPOTLIGHT{X} -uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; -#elif defined(POINTLIGHT{X}) -uniform vec4 vLightFalloff{X}; -#elif defined(HEMILIGHT{X}) -uniform vec3 vLightGround{X}; -#endif -#ifdef PROJECTEDLIGHTTEXTURE{X} -uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[lightFragmentDeclaration_name] = lightFragmentDeclaration_shader; -/** @internal */ -const lightFragmentDeclaration = { name: lightFragmentDeclaration_name, shader: lightFragmentDeclaration_shader }; -//# sourceMappingURL=lightFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightUboDeclaration.js -// Do not edit. - -const lightUboDeclaration_name = "lightUboDeclaration"; -const lightUboDeclaration_shader = `#ifdef LIGHT{X} -uniform Light{X} -{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; -#ifdef SPOTLIGHT{X} -vec4 vLightDirection;vec4 vLightFalloff; -#elif defined(POINTLIGHT{X}) -vec4 vLightFalloff; -#elif defined(HEMILIGHT{X}) -vec3 vLightGround; -#endif -vec4 shadowsInfo;vec2 depthValues;} light{X}; -#ifdef PROJECTEDLIGHTTEXTURE{X} -uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DArrayShadow shadowSampler{X}; -#else -uniform highp sampler2DArray shadowSampler{X}; -#endif -#ifdef SHADOWCSMDEBUG{X} -const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] -( -vec3 ( 1.5,0.0,0.0 ), -vec3 ( 0.0,1.5,0.0 ), -vec3 ( 0.0,0.0,5.5 ), -vec3 ( 1.5,0.0,5.5 ), -vec3 ( 1.5,1.5,0.0 ), -vec3 ( 1.0,1.0,1.0 ), -vec3 ( 0.0,1.0,5.5 ), -vec3 ( 0.5,3.5,0.75 ) -);vec3 shadowDebug{X}; -#endif -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -int index{X}=-1; -#else -int index{X}=SHADOWCSMNUM_CASCADES{X}-1; -#endif -float diff{X}=0.; -#elif defined(SHADOWCUBE{X}) -uniform samplerCube shadowSampler{X}; -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DShadow shadowSampler{X}; -#else -uniform sampler2D shadowSampler{X}; -#endif -uniform mat4 lightMatrix{X}; -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[lightUboDeclaration_name] = lightUboDeclaration_shader; -/** @internal */ -const lightUboDeclaration = { name: lightUboDeclaration_name, shader: lightUboDeclaration_shader }; -//# sourceMappingURL=lightUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightsFragmentFunctions.js -// Do not edit. - -const lightsFragmentFunctions_name = "lightsFragmentFunctions"; -const lightsFragmentFunctions_shader = `struct lightingInfo -{vec3 diffuse; -#ifdef SPECULARTERM -vec3 specular; -#endif -#ifdef NDOTL -float ndl; -#endif -};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) -{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} -else -{lightVectorW=normalize(-lightData.xyz);} -float ndl=max(0.,dot(vNormal,lightVectorW)); -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=ndl*diffuseColor*attenuation; -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; -#endif -return result;} -lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) -{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW)); -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=ndl*diffuseColor*attenuation; -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; -#endif -return result;} -result.diffuse=vec3(0.); -#ifdef SPECULARTERM -result.specular=vec3(0.); -#endif -#ifdef NDOTL -result.ndl=0.; -#endif -return result;} -lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=mix(groundColor,diffuseColor,ndl); -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; -#endif -return result;} -#define inline -vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`; -// Sideeffect -ShaderStore.IncludesShadersStore[lightsFragmentFunctions_name] = lightsFragmentFunctions_shader; -/** @internal */ -const lightsFragmentFunctions = { name: lightsFragmentFunctions_name, shader: lightsFragmentFunctions_shader }; -//# sourceMappingURL=lightsFragmentFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowsFragmentFunctions.js -// Do not edit. - -const shadowsFragmentFunctions_name = "shadowsFragmentFunctions"; -const shadowsFragmentFunctions_shader = `#ifdef SHADOWS -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -#ifndef SHADOWFLOAT -float unpack(vec4 color) -{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} -#endif -float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) -{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} -#define inline -float computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) -{vec3 directionToLight=vPositionW-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; -#ifndef SHADOWFLOAT -float shadow=unpack(textureCube(shadowSampler,directionToLight)); -#else -float shadow=textureCube(shadowSampler,directionToLight).x; -#endif -return depth>shadow ? darkness : 1.0;} -#define inline -float computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) -{vec3 directionToLight=vPositionW-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); -#ifndef SHADOWFLOAT -if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25; -#else -if (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25; -#endif -return min(1.0,visibility+darkness);} -#define inline -float computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues) -{vec3 directionToLight=vPositionW-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight)); -#else -float shadowMapSample=textureCube(shadowSampler,directionToLight).x; -#endif -float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); -return esm;} -#define inline -float computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues) -{vec3 directionToLight=vPositionW-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight)); -#else -float shadowMapSample=textureCube(shadowSampler,directionToLight).x; -#endif -float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;} -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define inline -float computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);vec3 uvLayer=vec3(uv.x,uv.y,layer);float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadow=unpack(texture2D(shadowSampler,uvLayer)); -#else -float shadow=texture2D(shadowSampler,uvLayer).x; -#endif -return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} -#endif -#define inline -float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} -#define inline -float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); -#ifndef SHADOWFLOAT -if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25; -#else -if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25; -#endif -return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} -#ifdef IS_NDC_HALF_ZRANGE -#define ZINCLIP clipSpace.z -#else -#define ZINCLIP uvDepth.z -#endif -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define GREATEST_LESS_THAN_ONE 0.99999994 -#define inline -float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -const vec3 PoissonSamplers32[64]=vec3[64]( -vec3(0.06407013,0.05409927,0.), -vec3(0.7366577,0.5789394,0.), -vec3(-0.6270542,-0.5320278,0.), -vec3(-0.4096107,0.8411095,0.), -vec3(0.6849564,-0.4990818,0.), -vec3(-0.874181,-0.04579735,0.), -vec3(0.9989998,0.0009880066,0.), -vec3(-0.004920578,-0.9151649,0.), -vec3(0.1805763,0.9747483,0.), -vec3(-0.2138451,0.2635818,0.), -vec3(0.109845,0.3884785,0.), -vec3(0.06876755,-0.3581074,0.), -vec3(0.374073,-0.7661266,0.), -vec3(0.3079132,-0.1216763,0.), -vec3(-0.3794335,-0.8271583,0.), -vec3(-0.203878,-0.07715034,0.), -vec3(0.5912697,0.1469799,0.), -vec3(-0.88069,0.3031784,0.), -vec3(0.5040108,0.8283722,0.), -vec3(-0.5844124,0.5494877,0.), -vec3(0.6017799,-0.1726654,0.), -vec3(-0.5554981,0.1559997,0.), -vec3(-0.3016369,-0.3900928,0.), -vec3(-0.5550632,-0.1723762,0.), -vec3(0.925029,0.2995041,0.), -vec3(-0.2473137,0.5538505,0.), -vec3(0.9183037,-0.2862392,0.), -vec3(0.2469421,0.6718712,0.), -vec3(0.3916397,-0.4328209,0.), -vec3(-0.03576927,-0.6220032,0.), -vec3(-0.04661255,0.7995201,0.), -vec3(0.4402924,0.3640312,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.) -);const vec3 PoissonSamplers64[64]=vec3[64]( -vec3(-0.613392,0.617481,0.), -vec3(0.170019,-0.040254,0.), -vec3(-0.299417,0.791925,0.), -vec3(0.645680,0.493210,0.), -vec3(-0.651784,0.717887,0.), -vec3(0.421003,0.027070,0.), -vec3(-0.817194,-0.271096,0.), -vec3(-0.705374,-0.668203,0.), -vec3(0.977050,-0.108615,0.), -vec3(0.063326,0.142369,0.), -vec3(0.203528,0.214331,0.), -vec3(-0.667531,0.326090,0.), -vec3(-0.098422,-0.295755,0.), -vec3(-0.885922,0.215369,0.), -vec3(0.566637,0.605213,0.), -vec3(0.039766,-0.396100,0.), -vec3(0.751946,0.453352,0.), -vec3(0.078707,-0.715323,0.), -vec3(-0.075838,-0.529344,0.), -vec3(0.724479,-0.580798,0.), -vec3(0.222999,-0.215125,0.), -vec3(-0.467574,-0.405438,0.), -vec3(-0.248268,-0.814753,0.), -vec3(0.354411,-0.887570,0.), -vec3(0.175817,0.382366,0.), -vec3(0.487472,-0.063082,0.), -vec3(-0.084078,0.898312,0.), -vec3(0.488876,-0.783441,0.), -vec3(0.470016,0.217933,0.), -vec3(-0.696890,-0.549791,0.), -vec3(-0.149693,0.605762,0.), -vec3(0.034211,0.979980,0.), -vec3(0.503098,-0.308878,0.), -vec3(-0.016205,-0.872921,0.), -vec3(0.385784,-0.393902,0.), -vec3(-0.146886,-0.859249,0.), -vec3(0.643361,0.164098,0.), -vec3(0.634388,-0.049471,0.), -vec3(-0.688894,0.007843,0.), -vec3(0.464034,-0.188818,0.), -vec3(-0.440840,0.137486,0.), -vec3(0.364483,0.511704,0.), -vec3(0.034028,0.325968,0.), -vec3(0.099094,-0.308023,0.), -vec3(0.693960,-0.366253,0.), -vec3(0.678884,-0.204688,0.), -vec3(0.001801,0.780328,0.), -vec3(0.145177,-0.898984,0.), -vec3(0.062655,-0.611866,0.), -vec3(0.315226,-0.604297,0.), -vec3(-0.780145,0.486251,0.), -vec3(-0.371868,0.882138,0.), -vec3(0.200476,0.494430,0.), -vec3(-0.494552,-0.711051,0.), -vec3(0.612476,0.705252,0.), -vec3(-0.578845,-0.768792,0.), -vec3(-0.772454,-0.090976,0.), -vec3(0.504440,0.372295,0.), -vec3(0.155736,0.065157,0.), -vec3(0.391522,0.849605,0.), -vec3(-0.620106,-0.328104,0.), -vec3(0.789239,-0.419965,0.), -vec3(-0.545396,0.538133,0.), -vec3(-0.178564,-0.596057,0.) -); -#define inline -float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}} -float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec4 offset=vec4(poissonSamplers[i],0.);offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);} -shadow/=float(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);if (numBlocker<1.0) {return 1.0;} -else -{return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}} -if (numBlocker<1.0) {return 1.0;} -else -{float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec3 offset=poissonSamplers[i];offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);shadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);} -shadow/=float(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}} -#define inline -float computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) -{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);} -#define inline -float computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) -{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);} -#define inline -float computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) -{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);} -#define inline -float computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) -{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} -#define inline -float computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) -{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} -#define inline -float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) -{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[shadowsFragmentFunctions_name] = shadowsFragmentFunctions_shader; -/** @internal */ -const shadowsFragmentFunctions = { name: shadowsFragmentFunctions_name, shader: shadowsFragmentFunctions_shader }; -//# sourceMappingURL=shadowsFragmentFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerFragmentDeclaration.js -// Do not edit. - -const samplerFragmentDeclaration_name = "samplerFragmentDeclaration"; -const samplerFragmentDeclaration_shader = `#ifdef _DEFINENAME_ -#if _DEFINENAME_DIRECTUV==1 -#define v_VARYINGNAME_UV vMainUV1 -#elif _DEFINENAME_DIRECTUV==2 -#define v_VARYINGNAME_UV vMainUV2 -#elif _DEFINENAME_DIRECTUV==3 -#define v_VARYINGNAME_UV vMainUV3 -#elif _DEFINENAME_DIRECTUV==4 -#define v_VARYINGNAME_UV vMainUV4 -#elif _DEFINENAME_DIRECTUV==5 -#define v_VARYINGNAME_UV vMainUV5 -#elif _DEFINENAME_DIRECTUV==6 -#define v_VARYINGNAME_UV vMainUV6 -#else -varying vec2 v_VARYINGNAME_UV; -#endif -uniform sampler2D _SAMPLERNAME_Sampler; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[samplerFragmentDeclaration_name] = samplerFragmentDeclaration_shader; -/** @internal */ -const samplerFragmentDeclaration = { name: samplerFragmentDeclaration_name, shader: samplerFragmentDeclaration_shader }; -//# sourceMappingURL=samplerFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/fresnelFunction.js -// Do not edit. - -const fresnelFunction_name = "fresnelFunction"; -const fresnelFunction_shader = `#ifdef FRESNEL -float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power) -{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[fresnelFunction_name] = fresnelFunction_shader; -/** @internal */ -const fresnelFunction = { name: fresnelFunction_name, shader: fresnelFunction_shader }; -//# sourceMappingURL=fresnelFunction.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/reflectionFunction.js -// Do not edit. - -const reflectionFunction_name = "reflectionFunction"; -const reflectionFunction_shader = `vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) -{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); } -vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) -{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); } -vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) -{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);} -vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix) -{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);} -vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) -{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));} -vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) -{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0)); -#ifdef INVERTCUBICMAP -coords.y*=-1.0; -#endif -return coords;} -vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition) -{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0)); -#ifdef INVERTCUBICMAP -coords.y*=-1.0; -#endif -return coords;} -vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix) -{return vec3(reflectionMatrix*(view*worldPos));} -vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix) -{return vec3(reflectionMatrix*vec4(positionW,1.));} -#ifdef REFLECTION -vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal) -{ -#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED -vec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction); -#endif -#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED -vec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction); -#endif -#ifdef REFLECTIONMAP_EQUIRECTANGULAR -return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); -#endif -#ifdef REFLECTIONMAP_SPHERICAL -return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix); -#endif -#ifdef REFLECTIONMAP_PLANAR -return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); -#endif -#ifdef REFLECTIONMAP_CUBIC -#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC -return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition); -#else -return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); -#endif -#endif -#ifdef REFLECTIONMAP_PROJECTION -return computeProjectionCoords(worldPos,view,reflectionMatrix); -#endif -#ifdef REFLECTIONMAP_SKYBOX -return computeSkyBoxCoords(vPositionUVW,reflectionMatrix); -#endif -#ifdef REFLECTIONMAP_EXPLICIT -return vec3(0,0,0); -#endif -} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[reflectionFunction_name] = reflectionFunction_shader; -/** @internal */ -const reflectionFunction = { name: reflectionFunction_name, shader: reflectionFunction_shader }; -//# sourceMappingURL=reflectionFunction.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingDeclaration.js -// Do not edit. - -const imageProcessingDeclaration_name = "imageProcessingDeclaration"; -const imageProcessingDeclaration_shader = `#ifdef EXPOSURE -uniform float exposureLinear; -#endif -#ifdef CONTRAST -uniform float contrast; -#endif -#if defined(VIGNETTE) || defined(DITHER) -uniform vec2 vInverseScreenSize; -#endif -#ifdef VIGNETTE -uniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2; -#endif -#ifdef COLORCURVES -uniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive; -#endif -#ifdef COLORGRADING -#ifdef COLORGRADING3D -uniform highp sampler3D txColorTransform; -#else -uniform sampler2D txColorTransform; -#endif -uniform vec4 colorTransformSettings; -#endif -#ifdef DITHER -uniform float ditherIntensity; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[imageProcessingDeclaration_name] = imageProcessingDeclaration_shader; -/** @internal */ -const imageProcessingDeclaration = { name: imageProcessingDeclaration_name, shader: imageProcessingDeclaration_shader }; -//# sourceMappingURL=imageProcessingDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingFunctions.js -// Do not edit. - -const imageProcessingFunctions_name = "imageProcessingFunctions"; -const imageProcessingFunctions_shader = `#if defined(COLORGRADING) && !defined(COLORGRADING3D) -/** -* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL. -* sampler3dSetting.x=textureOffset (0.5/textureSize). -* sampler3dSetting.y=textureSize. -*/ -#define inline -vec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting) -{float sliceSize=2.0*sampler3dSetting.x; -#ifdef SAMPLER3DGREENDEPTH -float sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y; -#else -float sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y; -#endif -float sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger; -#ifdef SAMPLER3DGREENDEPTH -vec2 sliceUV=color.rb; -#else -vec2 sliceUV=color.rg; -#endif -sliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction); -#ifdef SAMPLER3DBGRMAP -color.rgb=result.rgb; -#else -color.rgb=result.bgr; -#endif -return color;} -#endif -#ifdef TONEMAPPING_ACES -const mat3 ACESInputMat=mat3( -vec3(0.59719,0.07600,0.02840), -vec3(0.35458,0.90834,0.13383), -vec3(0.04823,0.01566,0.83777) -);const mat3 ACESOutputMat=mat3( -vec3( 1.60475,-0.10208,-0.00327), -vec3(-0.53108, 1.10813,-0.07276), -vec3(-0.07367,-0.00605, 1.07602) -);vec3 RRTAndODTFit(vec3 v) -{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;} -vec3 ACESFitted(vec3 color) -{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;} -#endif -#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS -vec4 applyImageProcessing(vec4 result) { -#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART -#ifdef EXPOSURE -result.rgb*=exposureLinear; -#endif -#ifdef VIGNETTE -vec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb; -#ifdef VIGNETTEBLENDMODEMULTIPLY -vec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier; -#endif -#ifdef VIGNETTEBLENDMODEOPAQUE -result.rgb=mix(vignetteColor,result.rgb,vignette); -#endif -#endif -#ifdef TONEMAPPING -#ifdef TONEMAPPING_ACES -result.rgb=ACESFitted(result.rgb); -#else -const float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb); -#endif -#endif -result.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb); -#ifdef CONTRAST -vec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);} -#endif -#ifdef COLORGRADING -vec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy; -#ifdef COLORGRADING3D -vec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb; -#else -vec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb; -#endif -result.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www); -#endif -#ifdef COLORCURVES -float luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a); -#endif -#ifdef DITHER -float rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither)); -#endif -#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND -return result;}`; -// Sideeffect -ShaderStore.IncludesShadersStore[imageProcessingFunctions_name] = imageProcessingFunctions_shader; -/** @internal */ -const imageProcessingFunctions = { name: imageProcessingFunctions_name, shader: imageProcessingFunctions_shader }; -//# sourceMappingURL=imageProcessingFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpFragmentMainFunctions.js -// Do not edit. - -const bumpFragmentMainFunctions_name = "bumpFragmentMainFunctions"; -const bumpFragmentMainFunctions_shader = `#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) -#if defined(TANGENT) && defined(NORMAL) -varying mat3 vTBN; -#endif -#ifdef OBJECTSPACE_NORMALMAP -uniform mat4 normalMatrix; -#if defined(WEBGL2) || defined(WEBGPU) -mat4 toNormalMatrix(mat4 wMatrix) -{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;} -#else -mat4 toNormalMatrix(mat4 m) -{float -a00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3], -a10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3], -a20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3], -a30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3], -b00=a00*a11-a01*a10, -b01=a00*a12-a02*a10, -b02=a00*a13-a03*a10, -b03=a01*a12-a02*a11, -b04=a01*a13-a03*a11, -b05=a02*a13-a03*a12, -b06=a20*a31-a21*a30, -b07=a20*a32-a22*a30, -b08=a20*a33-a23*a30, -b09=a21*a32-a22*a31, -b10=a21*a33-a23*a31, -b11=a22*a33-a23*a32, -det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4( -a11*b11-a12*b10+a13*b09, -a02*b10-a01*b11-a03*b09, -a31*b05-a32*b04+a33*b03, -a22*b04-a21*b05-a23*b03, -a12*b08-a10*b11-a13*b07, -a00*b11-a02*b08+a03*b07, -a32*b02-a30*b05-a33*b01, -a20*b05-a22*b02+a23*b01, -a10*b10-a11*b08+a13*b06, -a01*b08-a00*b10-a03*b06, -a30*b04-a31*b02+a33*b00, -a21*b02-a20*b04-a23*b00, -a11*b07-a10*b09-a12*b06, -a00*b09-a01*b07+a02*b06, -a31*b01-a30*b03-a32*b00, -a20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0], -mi[0][1],mi[1][1],mi[2][1],mi[3][1], -mi[0][2],mi[1][2],mi[2][2],mi[3][2], -mi[0][3],mi[1][3],mi[2][3],mi[3][3]);} -#endif -#endif -vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale) -{ -#ifdef NORMALXYSCALE -normal=normalize(normal*vec3(scale,scale,1.0)); -#endif -return normalize(cotangentFrame*normal);} -vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale) -{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);} -mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams) -{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[bumpFragmentMainFunctions_name] = bumpFragmentMainFunctions_shader; -/** @internal */ -const bumpFragmentMainFunctions = { name: bumpFragmentMainFunctions_name, shader: bumpFragmentMainFunctions_shader }; -//# sourceMappingURL=bumpFragmentMainFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpFragmentFunctions.js -// Do not edit. - - -const bumpFragmentFunctions_name = "bumpFragmentFunctions"; -const bumpFragmentFunctions_shader = `#if defined(BUMP) -#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) -#endif -#if defined(DETAIL) -#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) -#endif -#if defined(BUMP) && defined(PARALLAX) -const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; i<iMaxSamples; i++) -{currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;if (!keepWorking) -{} -else if (currSampledHeight>currRayHeight) -{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} -else -{currRayHeight-=stepSize;vLastOffset=vCurrOffset;vCurrOffset+=stepSize*vMaxOffset;lastSampledHeight=currSampledHeight;}} -return vCurrOffset;} -vec2 parallaxOffset(vec3 viewDir,float heightScale) -{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;return -texCoordOffset;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[bumpFragmentFunctions_name] = bumpFragmentFunctions_shader; -/** @internal */ -const bumpFragmentFunctions = { name: bumpFragmentFunctions_name, shader: bumpFragmentFunctions_shader }; -//# sourceMappingURL=bumpFragmentFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragmentDeclaration.js -// Do not edit. - -const clipPlaneFragmentDeclaration_name = "clipPlaneFragmentDeclaration"; -const clipPlaneFragmentDeclaration_shader = `#ifdef CLIPPLANE -varying float fClipDistance; -#endif -#ifdef CLIPPLANE2 -varying float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -varying float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -varying float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -varying float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -varying float fClipDistance6; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[clipPlaneFragmentDeclaration_name] = clipPlaneFragmentDeclaration_shader; -/** @internal */ -const clipPlaneFragmentDeclaration = { name: clipPlaneFragmentDeclaration_name, shader: clipPlaneFragmentDeclaration_shader }; -//# sourceMappingURL=clipPlaneFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/logDepthDeclaration.js -// Do not edit. - -const logDepthDeclaration_name = "logDepthDeclaration"; -const logDepthDeclaration_shader = `#ifdef LOGARITHMICDEPTH -uniform float logarithmicDepthConstant;varying float vFragmentDepth; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[logDepthDeclaration_name] = logDepthDeclaration_shader; -/** @internal */ -const logDepthDeclaration = { name: logDepthDeclaration_name, shader: logDepthDeclaration_shader }; -//# sourceMappingURL=logDepthDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/fogFragmentDeclaration.js -// Do not edit. - -const fogFragmentDeclaration_name = "fogFragmentDeclaration"; -const fogFragmentDeclaration_shader = `#ifdef FOG -#define FOGMODE_NONE 0. -#define FOGMODE_EXP 1. -#define FOGMODE_EXP2 2. -#define FOGMODE_LINEAR 3. -#define E 2.71828 -uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() -{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) -{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} -else if (FOGMODE_EXP==vFogInfos.x) -{fogCoeff=1.0/pow(E,fogDistance*fogDensity);} -else if (FOGMODE_EXP2==vFogInfos.x) -{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} -return clamp(fogCoeff,0.0,1.0);} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[fogFragmentDeclaration_name] = fogFragmentDeclaration_shader; -/** @internal */ -const fogFragmentDeclaration = { name: fogFragmentDeclaration_name, shader: fogFragmentDeclaration_shader }; -//# sourceMappingURL=fogFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragment.js -// Do not edit. - -const clipPlaneFragment_name = "clipPlaneFragment"; -const clipPlaneFragment_shader = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -if (false) {} -#endif -#ifdef CLIPPLANE -else if (fClipDistance>0.0) -{discard;} -#endif -#ifdef CLIPPLANE2 -else if (fClipDistance2>0.0) -{discard;} -#endif -#ifdef CLIPPLANE3 -else if (fClipDistance3>0.0) -{discard;} -#endif -#ifdef CLIPPLANE4 -else if (fClipDistance4>0.0) -{discard;} -#endif -#ifdef CLIPPLANE5 -else if (fClipDistance5>0.0) -{discard;} -#endif -#ifdef CLIPPLANE6 -else if (fClipDistance6>0.0) -{discard;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[clipPlaneFragment_name] = clipPlaneFragment_shader; -/** @internal */ -const clipPlaneFragment = { name: clipPlaneFragment_name, shader: clipPlaneFragment_shader }; -//# sourceMappingURL=clipPlaneFragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpFragment.js -// Do not edit. - -const bumpFragment_name = "bumpFragment"; -const bumpFragment_shader = `vec2 uvOffset=vec2(0.0,0.0); -#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) -#ifdef NORMALXYSCALE -float normalScale=1.0; -#elif defined(BUMP) -float normalScale=vBumpInfos.y; -#else -float normalScale=1.0; -#endif -#if defined(TANGENT) && defined(NORMAL) -mat3 TBN=vTBN; -#elif defined(BUMP) -vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); -#else -vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); -#endif -#elif defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -mat3 TBN=vTBN; -#else -vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); -#endif -#endif -#ifdef PARALLAX -mat3 invTBN=transposeMat3(TBN); -#ifdef PARALLAXOCCLUSION -uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); -#else -uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); -#endif -#endif -#ifdef DETAIL -vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); -#endif -#ifdef BUMP -#ifdef OBJECTSPACE_NORMALMAP -#define CUSTOM_FRAGMENT_BUMP_FRAGMENT -normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); -#elif !defined(DETAIL) -normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); -#else -vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; -#if DETAIL_NORMALBLENDMETHOD==0 -detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); -#elif DETAIL_NORMALBLENDMETHOD==1 -detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; -#endif -normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); -#endif -#elif defined(DETAIL) -detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[bumpFragment_name] = bumpFragment_shader; -/** @internal */ -const bumpFragment = { name: bumpFragment_name, shader: bumpFragment_shader }; -//# sourceMappingURL=bumpFragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragment.js -// Do not edit. - -const decalFragment_name = "decalFragment"; -const decalFragment_shader = `#ifdef DECAL -#ifdef GAMMADECAL -decalColor.rgb=toLinearSpace(decalColor.rgb); -#endif -#ifdef DECAL_SMOOTHALPHA -decalColor.a*=decalColor.a; -#endif -surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[decalFragment_name] = decalFragment_shader; -/** @internal */ -const decalFragment = { name: decalFragment_name, shader: decalFragment_shader }; -//# sourceMappingURL=decalFragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/depthPrePass.js -// Do not edit. - -const depthPrePass_name = "depthPrePass"; -const depthPrePass_shader = `#ifdef DEPTHPREPASS -gl_FragColor=vec4(0.,0.,0.,1.0);return; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[depthPrePass_name] = depthPrePass_shader; -/** @internal */ -const depthPrePass = { name: depthPrePass_name, shader: depthPrePass_shader }; -//# sourceMappingURL=depthPrePass.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragment.js -// Do not edit. - -const lightFragment_name = "lightFragment"; -const lightFragment_shader = `#ifdef LIGHT{X} -#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) -#else -#ifdef PBR -#ifdef SPOTLIGHT{X} -preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(POINTLIGHT{X}) -preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(HEMILIGHT{X}) -preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(DIRLIGHT{X}) -preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#endif -preInfo.NdotV=NdotV; -#ifdef SPOTLIGHT{X} -#ifdef LIGHT_FALLOFF_GLTF{X} -preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); -#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) -preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); -#elif defined(LIGHT_FALLOFF_STANDARD{X}) -preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); -#else -preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); -#endif -#elif defined(POINTLIGHT{X}) -#ifdef LIGHT_FALLOFF_GLTF{X} -preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); -#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) -preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); -#elif defined(LIGHT_FALLOFF_STANDARD{X}) -preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); -#else -preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); -#endif -#else -preInfo.attenuation=1.0; -#endif -#ifdef HEMILIGHT{X} -preInfo.roughness=roughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -#ifdef IRIDESCENCE -preInfo.iridescenceIntensity=iridescenceIntensity; -#endif -#ifdef HEMILIGHT{X} -info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); -#elif defined(SS_TRANSLUCENCY) -info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); -#else -info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); -#endif -#ifdef SPECULARTERM -#ifdef ANISOTROPIC -info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#else -info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#endif -#endif -#ifdef SHEEN -#ifdef SHEEN_LINKWITHALBEDO -preInfo.roughness=sheenOut.sheenIntensity; -#else -#ifdef HEMILIGHT{X} -preInfo.roughness=sheenOut.sheenRoughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -#endif -info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#endif -#ifdef CLEARCOAT -#ifdef HEMILIGHT{X} -preInfo.roughness=clearcoatOut.clearCoatRoughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); -#ifdef CLEARCOAT_TINT -absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; -#ifdef SPECULARTERM -info.specular*=absorption; -#endif -#endif -info.diffuse*=info.clearCoat.w; -#ifdef SPECULARTERM -info.specular*=info.clearCoat.w; -#endif -#ifdef SHEEN -info.sheen*=info.clearCoat.w; -#endif -#endif -#else -#ifdef SPOTLIGHT{X} -info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); -#elif defined(HEMILIGHT{X}) -info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); -#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) -info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); -#endif -#endif -#ifdef PROJECTEDLIGHTTEXTURE{X} -info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X}); -#endif -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) -{ -#ifdef SHADOWCSM_RIGHTHANDED{X} -diff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z; -#else -diff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z; -#endif -if (diff{X}>=0.) {index{X}=i;break;}} -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -if (index{X}>=0) -#endif -{ -#if defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#else -shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#endif -#else -shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#ifdef SHADOWCSMDEBUG{X} -shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; -#endif -#ifndef SHADOWCSMNOBLEND{X} -float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) -{index{X}+=1;float nextShadow=0.; -#if defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#elif defined(SHADOWMEDIUMQUALITY{X}) -nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#else -nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#endif -#else -nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -shadow=mix(nextShadow,shadow,diffRatio); -#ifdef SHADOWCSMDEBUG{X} -shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); -#endif -} -#endif -} -#elif defined(SHADOWCLOSEESM{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); -#else -shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWESM{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); -#else -shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPOISSON{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); -#else -shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#else -#if defined(SHADOWCUBE{X}) -shadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues); -#else -shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#endif -#ifdef SHADOWONLY -#ifndef SHADOWINUSE -#define SHADOWINUSE -#endif -globalShadow+=shadow;shadowLightCount+=1.0; -#endif -#else -shadow=1.; -#endif -#ifndef SHADOWONLY -#ifdef CUSTOMUSERLIGHTING -diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); -#ifdef SPECULARTERM -specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); -#endif -#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) -diffuseBase+=lightmapColor.rgb*shadow; -#ifdef SPECULARTERM -#ifndef LIGHTMAPNOSPECULAR{X} -specularBase+=info.specular*shadow*lightmapColor.rgb; -#endif -#endif -#ifdef CLEARCOAT -#ifndef LIGHTMAPNOSPECULAR{X} -clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; -#endif -#endif -#ifdef SHEEN -#ifndef LIGHTMAPNOSPECULAR{X} -sheenBase+=info.sheen.rgb*shadow; -#endif -#endif -#else -#ifdef SHADOWCSMDEBUG{X} -diffuseBase+=info.diffuse*shadowDebug{X}; -#else -diffuseBase+=info.diffuse*shadow; -#endif -#ifdef SPECULARTERM -specularBase+=info.specular*shadow; -#endif -#ifdef CLEARCOAT -clearCoatBase+=info.clearCoat.rgb*shadow; -#endif -#ifdef SHEEN -sheenBase+=info.sheen.rgb*shadow; -#endif -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[lightFragment_name] = lightFragment_shader; -/** @internal */ -const lightFragment = { name: lightFragment_name, shader: lightFragment_shader }; -//# sourceMappingURL=lightFragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/logDepthFragment.js -// Do not edit. - -const logDepthFragment_name = "logDepthFragment"; -const logDepthFragment_shader = `#ifdef LOGARITHMICDEPTH -gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[logDepthFragment_name] = logDepthFragment_shader; -/** @internal */ -const logDepthFragment = { name: logDepthFragment_name, shader: logDepthFragment_shader }; -//# sourceMappingURL=logDepthFragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/fogFragment.js -// Do not edit. - -const fogFragment_name = "fogFragment"; -const fogFragment_shader = `#ifdef FOG -float fog=CalcFogFactor(); -#ifdef PBR -fog=toLinearSpace(fog); -#endif -color.rgb=mix(vFogColor,color.rgb,fog); -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[fogFragment_name] = fogFragment_shader; -/** @internal */ -const fogFragment = { name: fogFragment_name, shader: fogFragment_shader }; -//# sourceMappingURL=fogFragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/oitFragment.js -// Do not edit. - -const oitFragment_name = "oitFragment"; -const oitFragment_shader = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY -float fragDepth=gl_FragCoord.z; -#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS -uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; -#endif -ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); -#ifdef USE_REVERSE_DEPTHBUFFER -float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; -#else -float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; -#endif -float alphaMultiplier=1.0-lastFrontColor.a; -#ifdef USE_REVERSE_DEPTHBUFFER -if (fragDepth>nearestDepth || fragDepth<furthestDepth) { -#else -if (fragDepth<nearestDepth || fragDepth>furthestDepth) { -#endif -return;} -#ifdef USE_REVERSE_DEPTHBUFFER -if (fragDepth<nearestDepth && fragDepth>furthestDepth) { -#else -if (fragDepth>nearestDepth && fragDepth<furthestDepth) { -#endif -depth.rg=vec2(-fragDepth,fragDepth);return;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[oitFragment_name] = oitFragment_shader; -/** @internal */ -const oitFragment = { name: oitFragment_name, shader: oitFragment_shader }; -//# sourceMappingURL=oitFragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/default.fragment.js -// Do not edit. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -const default_fragment_name = "defaultPixelShader"; -const default_fragment_shader = `#include<__decl__defaultFragment> -#if defined(BUMP) || !defined(NORMAL) -#extension GL_OES_standard_derivatives : enable -#endif -#include<prePassDeclaration>[SCENE_MRT_COUNT] -#include<oitDeclaration> -#define CUSTOM_FRAGMENT_BEGIN -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -#define RECIPROCAL_PI2 0.15915494 -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include<mainUVVaryingDeclaration>[1..7] -#include<helperFunctions> -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include<lightsFragmentFunctions> -#include<shadowsFragmentFunctions> -#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) -#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) -#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) -#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) -#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) -#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) -#ifdef REFRACTION -#ifdef REFRACTIONMAP_3D -uniform samplerCube refractionCubeSampler; -#else -uniform sampler2D refraction2DSampler; -#endif -#endif -#if defined(SPECULARTERM) -#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) -#endif -#include<fresnelFunction> -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -uniform samplerCube reflectionCubeSampler; -#else -uniform sampler2D reflection2DSampler; -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#include<reflectionFunction> -#endif -#include<imageProcessingDeclaration> -#include<imageProcessingFunctions> -#include<bumpFragmentMainFunctions> -#include<bumpFragmentFunctions> -#include<clipPlaneFragmentDeclaration> -#include<logDepthDeclaration> -#include<fogFragmentDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); -#endif -#include<bumpFragment> -#ifdef TWOSIDEDLIGHTING -normalW=gl_FrontFacing ? normalW : -normalW; -#endif -#ifdef DIFFUSE -baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); -#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) -if (baseColor.a<alphaCutOff) -discard; -#endif -#ifdef ALPHAFROMDIFFUSE -alpha*=baseColor.a; -#endif -#define CUSTOM_FRAGMENT_UPDATE_ALPHA -baseColor.rgb*=vDiffuseInfos.y; -#endif -#if defined(DECAL) && !defined(DECAL_AFTER_DETAIL) -vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); -#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) -#endif -#include<depthPrePass> -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -baseColor.rgb*=vColor.rgb; -#endif -#ifdef DETAIL -baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); -#endif -#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) -vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); -#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) -#endif -#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE -vec3 baseAmbientColor=vec3(1.,1.,1.); -#ifdef AMBIENT -baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; -#endif -#define CUSTOM_FRAGMENT_BEFORE_LIGHTS -#ifdef SPECULARTERM -float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; -#ifdef SPECULAR -vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; -#ifdef GLOSSINESS -glossiness=glossiness*specularMapColor.a; -#endif -#endif -#else -float glossiness=0.; -#endif -vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; -#ifdef SPECULARTERM -vec3 specularBase=vec3(0.,0.,0.); -#endif -float shadow=1.; -#ifdef LIGHTMAP -vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); -#ifdef RGBDLIGHTMAP -lightmapColor.rgb=fromRGBD(lightmapColor); -#endif -lightmapColor.rgb*=vLightmapInfos.y; -#endif -#include<lightFragment>[0..maxSimultaneousLights] -vec4 refractionColor=vec4(0.,0.,0.,1.); -#ifdef REFRACTION -vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); -#ifdef REFRACTIONMAP_3D -#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC -refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); -#endif -refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} -#else -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); -#endif -#ifdef RGBDREFRACTION -refractionColor.rgb=fromRGBD(refractionColor); -#endif -#ifdef IS_REFRACTION_LINEAR -refractionColor.rgb=toGammaSpace(refractionColor.rgb); -#endif -refractionColor.rgb*=vRefractionInfos.x; -#endif -vec4 reflectionColor=vec4(0.,0.,0.,1.); -#ifdef REFLECTION -vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#ifdef REFLECTIONMAP_OPPOSITEZ -vReflectionUVW.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -#ifdef ROUGHNESS -float bias=vReflectionInfos.y; -#ifdef SPECULARTERM -#ifdef SPECULAR -#ifdef GLOSSINESS -bias*=(1.0-specularMapColor.a); -#endif -#endif -#endif -reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); -#else -reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); -#endif -#else -vec2 coords=vReflectionUVW.xy; -#ifdef REFLECTIONMAP_PROJECTION -coords/=vReflectionUVW.z; -#endif -coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); -#endif -#ifdef RGBDREFLECTION -reflectionColor.rgb=fromRGBD(reflectionColor); -#endif -#ifdef IS_REFLECTION_LINEAR -reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); -#endif -reflectionColor.rgb*=vReflectionInfos.x; -#ifdef REFLECTIONFRESNEL -float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); -#ifdef REFLECTIONFRESNELFROMSPECULAR -#ifdef SPECULARTERM -reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#else -reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#endif -#else -reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#endif -#endif -#endif -#ifdef REFRACTIONFRESNEL -float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); -#ifdef OPACITYRGB -opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; -#else -alpha*=opacityMap.a*vOpacityInfos.y; -#endif -#endif -#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) -alpha*=vColor.a; -#endif -#ifdef OPACITYFRESNEL -float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; -#endif -#ifdef ALPHATEST -#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS -if (alpha<alphaCutOff) -discard; -#endif -#ifndef ALPHABLEND -alpha=1.0; -#endif -#endif -vec3 emissiveColor=vEmissiveColor; -#ifdef EMISSIVE -emissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y; -#endif -#ifdef EMISSIVEFRESNEL -float emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb; -#endif -#ifdef DIFFUSEFRESNEL -float diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);diffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb; -#endif -#ifdef EMISSIVEASILLUMINATION -vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb; -#else -#ifdef LINKEMISSIVEWITHDIFFUSE -vec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb; -#else -vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb; -#endif -#endif -#ifdef SPECULARTERM -vec3 finalSpecular=specularBase*specularColor; -#ifdef SPECULAROVERALPHA -alpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.); -#endif -#else -vec3 finalSpecular=vec3(0.0); -#endif -#ifdef REFLECTIONOVERALPHA -alpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.); -#endif -#ifdef EMISSIVEASILLUMINATION -vec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha); -#else -vec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha); -#endif -#ifdef LIGHTMAP -#ifndef LIGHTMAPEXCLUDED -#ifdef USELIGHTMAPASSHADOWMAP -color.rgb*=lightmapColor.rgb; -#else -color.rgb+=lightmapColor.rgb; -#endif -#endif -#endif -#define CUSTOM_FRAGMENT_BEFORE_FOG -color.rgb=max(color.rgb,0.); -#include<logDepthFragment> -#include<fogFragment> -#ifdef IMAGEPROCESSINGPOSTPROCESS -color.rgb=toLinearSpace(color.rgb); -#else -#ifdef IMAGEPROCESSING -color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); -#endif -#endif -color.a*=visibility; -#ifdef PREMULTIPLYALPHA -color.rgb*=color.a; -#endif -#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR -#ifdef PREPASS -float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; -#ifdef PREPASS_POSITION -gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); -#endif -#ifdef PREPASS_VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_IRRADIANCE -gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_DEPTH -gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_NORMAL -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); -#endif -#ifdef PREPASS_ALBEDO_SQRT -gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_REFLECTIVITY -#if defined(SPECULARTERM) -#if defined(SPECULAR) -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; -#endif -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; -#endif -#endif -#endif -#if !defined(PREPASS) || defined(WEBGL2) -gl_FragColor=color; -#endif -#include<oitFragment> -#if ORDER_INDEPENDENT_TRANSPARENCY -if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} -#endif -#define CUSTOM_FRAGMENT_MAIN_END -} -`; -// Sideeffect -ShaderStore.ShadersStore[default_fragment_name] = default_fragment_shader; -/** @internal */ -const defaultPixelShader = { name: default_fragment_name, shader: default_fragment_shader }; -//# sourceMappingURL=default.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/decalVertexDeclaration.js -// Do not edit. - -const decalVertexDeclaration_name = "decalVertexDeclaration"; -const decalVertexDeclaration_shader = `#ifdef DECAL -uniform vec4 vDecalInfos;uniform mat4 decalMatrix; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[decalVertexDeclaration_name] = decalVertexDeclaration_shader; -/** @internal */ -const decalVertexDeclaration = { name: decalVertexDeclaration_name, shader: decalVertexDeclaration_shader }; -//# sourceMappingURL=decalVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultVertexDeclaration.js -// Do not edit. - - -const defaultVertexDeclaration_name = "defaultVertexDeclaration"; -const defaultVertexDeclaration_shader = `uniform mat4 viewProjection;uniform mat4 view; -#ifdef DIFFUSE -uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; -#endif -#ifdef AMBIENT -uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; -#endif -#ifdef OPACITY -uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) -uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; -#endif -#ifdef REFLECTION -uniform mat4 reflectionMatrix; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos;uniform mat4 detailMatrix; -#endif -#include<decalVertexDeclaration> -#define ADDITIONAL_VERTEX_DECLARATION -`; -// Sideeffect -ShaderStore.IncludesShadersStore[defaultVertexDeclaration_name] = defaultVertexDeclaration_shader; -/** @internal */ -const defaultVertexDeclaration = { name: defaultVertexDeclaration_name, shader: defaultVertexDeclaration_shader }; -//# sourceMappingURL=defaultVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/uvAttributeDeclaration.js -// Do not edit. - -const uvAttributeDeclaration_name = "uvAttributeDeclaration"; -const uvAttributeDeclaration_shader = `#ifdef UV{X} -attribute vec2 uv{X}; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[uvAttributeDeclaration_name] = uvAttributeDeclaration_shader; -/** @internal */ -const uvAttributeDeclaration = { name: uvAttributeDeclaration_name, shader: uvAttributeDeclaration_shader }; -//# sourceMappingURL=uvAttributeDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesDeclaration.js -// Do not edit. - -const bonesDeclaration_name = "bonesDeclaration"; -const bonesDeclaration_shader = `#if NUM_BONE_INFLUENCERS>0 -attribute vec4 matricesIndices;attribute vec4 matricesWeights; -#if NUM_BONE_INFLUENCERS>4 -attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; -#endif -#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#ifdef BONETEXTURE -uniform sampler2D boneSampler;uniform float boneTextureWidth; -#else -uniform mat4 mBones[BonesPerMesh]; -#ifdef BONES_VELOCITY_ENABLED -uniform mat4 mPreviousBones[BonesPerMesh]; -#endif -#endif -#ifdef BONETEXTURE -#define inline -mat4 readMatrixFromRawSampler(sampler2D smp,float index) -{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[bonesDeclaration_name] = bonesDeclaration_shader; -/** @internal */ -const bonesDeclaration = { name: bonesDeclaration_name, shader: bonesDeclaration_shader }; -//# sourceMappingURL=bonesDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimationDeclaration.js -// Do not edit. - -const bakedVertexAnimationDeclaration_name = "bakedVertexAnimationDeclaration"; -const bakedVertexAnimationDeclaration_shader = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; -#ifdef INSTANCES -attribute vec4 bakedVertexAnimationSettingsInstanced; -#endif -#define inline -mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) -{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[bakedVertexAnimationDeclaration_name] = bakedVertexAnimationDeclaration_shader; -/** @internal */ -const bakedVertexAnimationDeclaration = { name: bakedVertexAnimationDeclaration_name, shader: bakedVertexAnimationDeclaration_shader }; -//# sourceMappingURL=bakedVertexAnimationDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesDeclaration.js -// Do not edit. - -const instancesDeclaration_name = "instancesDeclaration"; -const instancesDeclaration_shader = `#ifdef INSTANCES -attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; -#ifdef INSTANCESCOLOR -attribute vec4 instanceColor; -#endif -#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) -uniform mat4 world; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; -#ifdef THIN_INSTANCES -uniform mat4 previousWorld; -#endif -#endif -#else -#if !defined(WORLD_UBO) -uniform mat4 world; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -uniform mat4 previousWorld; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[instancesDeclaration_name] = instancesDeclaration_shader; -/** @internal */ -const instancesDeclaration = { name: instancesDeclaration_name, shader: instancesDeclaration_shader }; -//# sourceMappingURL=instancesDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassVertexDeclaration.js -// Do not edit. - -const prePassVertexDeclaration_name = "prePassVertexDeclaration"; -const prePassVertexDeclaration_shader = `#ifdef PREPASS -#ifdef PREPASS_DEPTH -varying vec3 vViewPos; -#endif -#ifdef PREPASS_VELOCITY -uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[prePassVertexDeclaration_name] = prePassVertexDeclaration_shader; -/** @internal */ -const prePassVertexDeclaration = { name: prePassVertexDeclaration_name, shader: prePassVertexDeclaration_shader }; -//# sourceMappingURL=prePassVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerVertexDeclaration.js -// Do not edit. - -const samplerVertexDeclaration_name = "samplerVertexDeclaration"; -const samplerVertexDeclaration_shader = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 -varying vec2 v_VARYINGNAME_UV; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[samplerVertexDeclaration_name] = samplerVertexDeclaration_shader; -/** @internal */ -const samplerVertexDeclaration = { name: samplerVertexDeclaration_name, shader: samplerVertexDeclaration_shader }; -//# sourceMappingURL=samplerVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpVertexDeclaration.js -// Do not edit. - -const bumpVertexDeclaration_name = "bumpVertexDeclaration"; -const bumpVertexDeclaration_shader = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -varying mat3 vTBN; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[bumpVertexDeclaration_name] = bumpVertexDeclaration_shader; -/** @internal */ -const bumpVertexDeclaration = { name: bumpVertexDeclaration_name, shader: bumpVertexDeclaration_shader }; -//# sourceMappingURL=bumpVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertexDeclaration.js -// Do not edit. - -const clipPlaneVertexDeclaration_name = "clipPlaneVertexDeclaration"; -const clipPlaneVertexDeclaration_shader = `#ifdef CLIPPLANE -uniform vec4 vClipPlane;varying float fClipDistance; -#endif -#ifdef CLIPPLANE2 -uniform vec4 vClipPlane2;varying float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -uniform vec4 vClipPlane3;varying float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -uniform vec4 vClipPlane4;varying float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -uniform vec4 vClipPlane5;varying float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -uniform vec4 vClipPlane6;varying float fClipDistance6; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[clipPlaneVertexDeclaration_name] = clipPlaneVertexDeclaration_shader; -/** @internal */ -const clipPlaneVertexDeclaration = { name: clipPlaneVertexDeclaration_name, shader: clipPlaneVertexDeclaration_shader }; -//# sourceMappingURL=clipPlaneVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/fogVertexDeclaration.js -// Do not edit. - -const fogVertexDeclaration_name = "fogVertexDeclaration"; -const fogVertexDeclaration_shader = `#ifdef FOG -varying vec3 vFogDistance; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[fogVertexDeclaration_name] = fogVertexDeclaration_shader; -/** @internal */ -const fogVertexDeclaration = { name: fogVertexDeclaration_name, shader: fogVertexDeclaration_shader }; -//# sourceMappingURL=fogVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxFragmentDeclaration.js -// Do not edit. - -const lightVxFragmentDeclaration_name = "lightVxFragmentDeclaration"; -const lightVxFragmentDeclaration_shader = `#ifdef LIGHT{X} -uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; -#ifdef SPECULARTERM -uniform vec4 vLightSpecular{X}; -#else -vec4 vLightSpecular{X}=vec4(0.); -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#elif defined(SHADOWCUBE{X}) -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; -#endif -uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; -#endif -#ifdef SPOTLIGHT{X} -uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; -#elif defined(POINTLIGHT{X}) -uniform vec4 vLightFalloff{X}; -#elif defined(HEMILIGHT{X}) -uniform vec3 vLightGround{X}; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[lightVxFragmentDeclaration_name] = lightVxFragmentDeclaration_shader; -/** @internal */ -const lightVxFragmentDeclaration = { name: lightVxFragmentDeclaration_name, shader: lightVxFragmentDeclaration_shader }; -//# sourceMappingURL=lightVxFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxUboDeclaration.js -// Do not edit. - -const lightVxUboDeclaration_name = "lightVxUboDeclaration"; -const lightVxUboDeclaration_shader = `#ifdef LIGHT{X} -uniform Light{X} -{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; -#ifdef SPOTLIGHT{X} -vec4 vLightDirection;vec4 vLightFalloff; -#elif defined(POINTLIGHT{X}) -vec4 vLightFalloff; -#elif defined(HEMILIGHT{X}) -vec3 vLightGround; -#endif -vec4 shadowsInfo;vec2 depthValues;} light{X}; -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#elif defined(SHADOWCUBE{X}) -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[lightVxUboDeclaration_name] = lightVxUboDeclaration_shader; -/** @internal */ -const lightVxUboDeclaration = { name: lightVxUboDeclaration_name, shader: lightVxUboDeclaration_shader }; -//# sourceMappingURL=lightVxUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.js -// Do not edit. - -const morphTargetsVertexGlobalDeclaration_name = "morphTargetsVertexGlobalDeclaration"; -const morphTargetsVertexGlobalDeclaration_shader = `#ifdef MORPHTARGETS -uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; -#ifdef MORPHTARGETS_TEXTURE -precision mediump sampler2DArray; -uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) -{ -float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[morphTargetsVertexGlobalDeclaration_name] = morphTargetsVertexGlobalDeclaration_shader; -/** @internal */ -const morphTargetsVertexGlobalDeclaration = { name: morphTargetsVertexGlobalDeclaration_name, shader: morphTargetsVertexGlobalDeclaration_shader }; -//# sourceMappingURL=morphTargetsVertexGlobalDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexDeclaration.js -// Do not edit. - -const morphTargetsVertexDeclaration_name = "morphTargetsVertexDeclaration"; -const morphTargetsVertexDeclaration_shader = `#ifdef MORPHTARGETS -#ifndef MORPHTARGETS_TEXTURE -attribute vec3 position{X}; -#ifdef MORPHTARGETS_NORMAL -attribute vec3 normal{X}; -#endif -#ifdef MORPHTARGETS_TANGENT -attribute vec3 tangent{X}; -#endif -#ifdef MORPHTARGETS_UV -attribute vec2 uv_{X}; -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[morphTargetsVertexDeclaration_name] = morphTargetsVertexDeclaration_shader; -/** @internal */ -const morphTargetsVertexDeclaration = { name: morphTargetsVertexDeclaration_name, shader: morphTargetsVertexDeclaration_shader }; -//# sourceMappingURL=morphTargetsVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobal.js -// Do not edit. - -const morphTargetsVertexGlobal_name = "morphTargetsVertexGlobal"; -const morphTargetsVertexGlobal_shader = `#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -float vertexID; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[morphTargetsVertexGlobal_name] = morphTargetsVertexGlobal_shader; -/** @internal */ -const morphTargetsVertexGlobal = { name: morphTargetsVertexGlobal_name, shader: morphTargetsVertexGlobal_shader }; -//# sourceMappingURL=morphTargetsVertexGlobal.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertex.js -// Do not edit. - -const morphTargetsVertex_name = "morphTargetsVertex"; -const morphTargetsVertex_shader = `#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];vertexID+=1.0; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];vertexID+=1.0; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];vertexID+=1.0; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}]; -#endif -#else -positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[morphTargetsVertex_name] = morphTargetsVertex_shader; -/** @internal */ -const morphTargetsVertex = { name: morphTargetsVertex_name, shader: morphTargetsVertex_shader }; -//# sourceMappingURL=morphTargetsVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesVertex.js -// Do not edit. - -const instancesVertex_name = "instancesVertex"; -const instancesVertex_shader = `#ifdef INSTANCES -mat4 finalWorld=mat4(world0,world1,world2,world3); -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); -#endif -#ifdef THIN_INSTANCES -finalWorld=world*finalWorld; -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -finalPreviousWorld=previousWorld*finalPreviousWorld; -#endif -#endif -#else -mat4 finalWorld=world; -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -mat4 finalPreviousWorld=previousWorld; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[instancesVertex_name] = instancesVertex_shader; -/** @internal */ -const instancesVertex = { name: instancesVertex_name, shader: instancesVertex_shader }; -//# sourceMappingURL=instancesVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesVertex.js -// Do not edit. - -const bonesVertex_name = "bonesVertex"; -const bonesVertex_shader = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#if NUM_BONE_INFLUENCERS>0 -mat4 influence; -#ifdef BONETEXTURE -influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; -#endif -#else -influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -#endif -finalWorld=finalWorld*influence; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[bonesVertex_name] = bonesVertex_shader; -/** @internal */ -const bonesVertex = { name: bonesVertex_name, shader: bonesVertex_shader }; -//# sourceMappingURL=bonesVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimation.js -// Do not edit. - -const bakedVertexAnimation_name = "bakedVertexAnimation"; -const bakedVertexAnimation_shader = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -{ -#ifdef INSTANCES -#define BVASNAME bakedVertexAnimationSettingsInstanced -#else -#define BVASNAME bakedVertexAnimationSettings -#endif -float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; -#endif -finalWorld=finalWorld*VATInfluence;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[bakedVertexAnimation_name] = bakedVertexAnimation_shader; -/** @internal */ -const bakedVertexAnimation = { name: bakedVertexAnimation_name, shader: bakedVertexAnimation_shader }; -//# sourceMappingURL=bakedVertexAnimation.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassVertex.js -// Do not edit. - -const prePassVertex_name = "prePassVertex"; -const prePassVertex_shader = `#ifdef PREPASS_DEPTH -vViewPos=(view*worldPos).rgb; -#endif -#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*worldPos; -#if NUM_BONE_INFLUENCERS>0 -mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); -#else -vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[prePassVertex_name] = prePassVertex_shader; -/** @internal */ -const prePassVertex = { name: prePassVertex_name, shader: prePassVertex_shader }; -//# sourceMappingURL=prePassVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/uvVariableDeclaration.js -// Do not edit. - -const uvVariableDeclaration_name = "uvVariableDeclaration"; -const uvVariableDeclaration_shader = `#if !defined(UV{X}) && defined(MAINUV{X}) -vec2 uv{X}=vec2(0.,0.); -#endif -#ifdef MAINUV{X} -vMainUV{X}=uv{X}; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[uvVariableDeclaration_name] = uvVariableDeclaration_shader; -/** @internal */ -const uvVariableDeclaration = { name: uvVariableDeclaration_name, shader: uvVariableDeclaration_shader }; -//# sourceMappingURL=uvVariableDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerVertexImplementation.js -// Do not edit. - -const samplerVertexImplementation_name = "samplerVertexImplementation"; -const samplerVertexImplementation_shader = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 -if (v_INFONAME_==0.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} -#ifdef UV2 -else if (v_INFONAME_==1.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));} -#endif -#ifdef UV3 -else if (v_INFONAME_==2.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} -#endif -#ifdef UV4 -else if (v_INFONAME_==3.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} -#endif -#ifdef UV5 -else if (v_INFONAME_==4.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} -#endif -#ifdef UV6 -else if (v_INFONAME_==5.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[samplerVertexImplementation_name] = samplerVertexImplementation_shader; -/** @internal */ -const samplerVertexImplementation = { name: samplerVertexImplementation_name, shader: samplerVertexImplementation_shader }; -//# sourceMappingURL=samplerVertexImplementation.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpVertex.js -// Do not edit. - -const bumpVertex_name = "bumpVertex"; -const bumpVertex_shader = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[bumpVertex_name] = bumpVertex_shader; -/** @internal */ -const bumpVertex = { name: bumpVertex_name, shader: bumpVertex_shader }; -//# sourceMappingURL=bumpVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertex.js -// Do not edit. - -const clipPlaneVertex_name = "clipPlaneVertex"; -const clipPlaneVertex_shader = `#ifdef CLIPPLANE -fClipDistance=dot(worldPos,vClipPlane); -#endif -#ifdef CLIPPLANE2 -fClipDistance2=dot(worldPos,vClipPlane2); -#endif -#ifdef CLIPPLANE3 -fClipDistance3=dot(worldPos,vClipPlane3); -#endif -#ifdef CLIPPLANE4 -fClipDistance4=dot(worldPos,vClipPlane4); -#endif -#ifdef CLIPPLANE5 -fClipDistance5=dot(worldPos,vClipPlane5); -#endif -#ifdef CLIPPLANE6 -fClipDistance6=dot(worldPos,vClipPlane6); -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[clipPlaneVertex_name] = clipPlaneVertex_shader; -/** @internal */ -const clipPlaneVertex = { name: clipPlaneVertex_name, shader: clipPlaneVertex_shader }; -//# sourceMappingURL=clipPlaneVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/fogVertex.js -// Do not edit. - -const fogVertex_name = "fogVertex"; -const fogVertex_shader = `#ifdef FOG -vFogDistance=(view*worldPos).xyz; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[fogVertex_name] = fogVertex_shader; -/** @internal */ -const fogVertex = { name: fogVertex_name, shader: fogVertex_shader }; -//# sourceMappingURL=fogVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowsVertex.js -// Do not edit. - -const shadowsVertex_name = "shadowsVertex"; -const shadowsVertex_shader = `#ifdef SHADOWS -#if defined(SHADOWCSM{X}) -vPositionFromCamera{X}=view*worldPos;for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos; -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y; -#else -vDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y; -#endif -} -#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X}) -vPositionFromLight{X}=lightMatrix{X}*worldPos; -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; -#else -vDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[shadowsVertex_name] = shadowsVertex_shader; -/** @internal */ -const shadowsVertex = { name: shadowsVertex_name, shader: shadowsVertex_shader }; -//# sourceMappingURL=shadowsVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/vertexColorMixing.js -// Do not edit. - -const vertexColorMixing_name = "vertexColorMixing"; -const vertexColorMixing_shader = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -vColor=vec4(1.0); -#ifdef VERTEXCOLOR -#ifdef VERTEXALPHA -vColor*=color; -#else -vColor.rgb*=color.rgb; -#endif -#endif -#ifdef INSTANCESCOLOR -vColor*=instanceColor; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[vertexColorMixing_name] = vertexColorMixing_shader; -/** @internal */ -const vertexColorMixing = { name: vertexColorMixing_name, shader: vertexColorMixing_shader }; -//# sourceMappingURL=vertexColorMixing.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertex.js -// Do not edit. - -const pointCloudVertex_name = "pointCloudVertex"; -const pointCloudVertex_shader = `#if defined(POINTSIZE) && !defined(WEBGPU) -gl_PointSize=pointSize; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pointCloudVertex_name] = pointCloudVertex_shader; -/** @internal */ -const pointCloudVertex = { name: pointCloudVertex_name, shader: pointCloudVertex_shader }; -//# sourceMappingURL=pointCloudVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/logDepthVertex.js -// Do not edit. - -const logDepthVertex_name = "logDepthVertex"; -const logDepthVertex_shader = `#ifdef LOGARITHMICDEPTH -vFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[logDepthVertex_name] = logDepthVertex_shader; -/** @internal */ -const logDepthVertex = { name: logDepthVertex_name, shader: logDepthVertex_shader }; -//# sourceMappingURL=logDepthVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/default.vertex.js -// Do not edit. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -const default_vertex_name = "defaultVertexShader"; -const default_vertex_shader = `#include<__decl__defaultVertex> -#define CUSTOM_VERTEX_BEGIN -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#ifdef TANGENT -attribute vec4 tangent; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#include<uvAttributeDeclaration>[2..7] -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include<helperFunctions> -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<instancesDeclaration> -#include<prePassVertexDeclaration> -#include<mainUVVaryingDeclaration>[1..7] -#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) -#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) -#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) -#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) -#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) -#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) -#if defined(SPECULARTERM) -#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) -#endif -#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) -#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include<bumpVertexDeclaration> -#include<clipPlaneVertexDeclaration> -#include<fogVertexDeclaration> -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#include<logDepthDeclaration> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#ifdef TANGENT -vec4 tangentUpdated=tangent; -#endif -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=positionUpdated; -#endif -#define CUSTOM_VERTEX_UPDATE_POSITION -#define CUSTOM_VERTEX_UPDATE_NORMAL -#include<instancesVertex> -#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normalUpdated); -#endif -#endif -#define CUSTOM_VERTEX_UPDATE_WORLDPOS -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -vPositionW=vec3(worldPos); -#include<prePassVertex> -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); -#endif -#ifndef UV1 -vec2 uvUpdated=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uvUpdated; -#endif -#include<uvVariableDeclaration>[2..7] -#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) -#if defined(SPECULARTERM) -#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) -#endif -#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) -#include<bumpVertex> -#include<clipPlaneVertex> -#include<fogVertex> -#include<shadowsVertex>[0..maxSimultaneousLights] -#include<vertexColorMixing> -#include<pointCloudVertex> -#include<logDepthVertex> -#define CUSTOM_VERTEX_MAIN_END -} -`; -// Sideeffect -ShaderStore.ShadersStore[default_vertex_name] = default_vertex_shader; -/** @internal */ -const defaultVertexShader = { name: default_vertex_name, shader: default_vertex_shader }; -//# sourceMappingURL=default.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/materialPluginManager.js - - - - - - -const rxOption = new RegExp("^([gimus]+)!"); -/** - * Class that manages the plugins of a material - * @since 5.0 - */ -class MaterialPluginManager { - /** - * Creates a new instance of the plugin manager - * @param material material that this manager will manage the plugins for - */ - constructor(material) { - /** @internal */ - this._plugins = []; - this._activePlugins = []; - this._activePluginsForExtraEvents = []; - this._material = material; - this._scene = material.getScene(); - this._engine = this._scene.getEngine(); - } - /** - * @internal - */ - _addPlugin(plugin) { - for (let i = 0; i < this._plugins.length; ++i) { - if (this._plugins[i].name === plugin.name) { - return false; - } - } - if (this._material._uniformBufferLayoutBuilt) { - 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.`; - } - const pluginClassName = plugin.getClassName(); - if (!MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]) { - MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName] = "MATERIALPLUGIN_" + ++MaterialPluginManager._MaterialPluginCounter; - } - this._material._callbackPluginEventGeneric = this._handlePluginEvent.bind(this); - this._plugins.push(plugin); - this._plugins.sort((a, b) => a.priority - b.priority); - this._codeInjectionPoints = {}; - const defineNamesFromPlugins = {}; - defineNamesFromPlugins[MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]] = { - type: "boolean", - default: true, - }; - for (const plugin of this._plugins) { - plugin.collectDefines(defineNamesFromPlugins); - this._collectPointNames("vertex", plugin.getCustomCode("vertex")); - this._collectPointNames("fragment", plugin.getCustomCode("fragment")); - } - this._defineNamesFromPlugins = defineNamesFromPlugins; - return true; - } - /** - * @internal - */ - _activatePlugin(plugin) { - if (this._activePlugins.indexOf(plugin) === -1) { - this._activePlugins.push(plugin); - this._activePlugins.sort((a, b) => a.priority - b.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); - if (plugin.registerForExtraEvents) { - this._activePluginsForExtraEvents.push(plugin); - this._activePluginsForExtraEvents.sort((a, b) => a.priority - b.priority); - this._material._callbackPluginEventHasRenderTargetTextures = this._handlePluginEventHasRenderTargetTextures.bind(this); - this._material._callbackPluginEventFillRenderTargetTextures = this._handlePluginEventFillRenderTargetTextures.bind(this); - this._material._callbackPluginEventHardBindForSubMesh = this._handlePluginEventHardBindForSubMesh.bind(this); - } - } - } - /** - * Gets a plugin from the list of plugins managed by this manager - * @param name name of the plugin - * @returns the plugin if found, else null - */ - getPlugin(name) { - for (let i = 0; i < this._plugins.length; ++i) { - if (this._plugins[i].name === name) { - return this._plugins[i]; - } - } - return null; - } - _handlePluginEventIsReadyForSubMesh(eventData) { - let isReady = true; - for (const plugin of this._activePlugins) { - isReady = isReady && plugin.isReadyForSubMesh(eventData.defines, this._scene, this._engine, eventData.subMesh); - } - eventData.isReadyForSubMesh = isReady; - } - _handlePluginEventPrepareDefinesBeforeAttributes(eventData) { - for (const plugin of this._activePlugins) { - plugin.prepareDefinesBeforeAttributes(eventData.defines, this._scene, eventData.mesh); - } - } - _handlePluginEventPrepareDefines(eventData) { - for (const plugin of this._activePlugins) { - plugin.prepareDefines(eventData.defines, this._scene, eventData.mesh); - } - } - _handlePluginEventHardBindForSubMesh(eventData) { - for (const plugin of this._activePluginsForExtraEvents) { - plugin.hardBindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh); - } - } - _handlePluginEventBindForSubMesh(eventData) { - for (const plugin of this._activePlugins) { - plugin.bindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh); - } - } - _handlePluginEventHasRenderTargetTextures(eventData) { - let hasRenderTargetTextures = false; - for (const plugin of this._activePluginsForExtraEvents) { - hasRenderTargetTextures = plugin.hasRenderTargetTextures(); - if (hasRenderTargetTextures) { - break; - } - } - eventData.hasRenderTargetTextures = hasRenderTargetTextures; - } - _handlePluginEventFillRenderTargetTextures(eventData) { - for (const plugin of this._activePluginsForExtraEvents) { - plugin.fillRenderTargetTextures(eventData.renderTargets); - } - } - _handlePluginEvent(id, info) { - var _a; - switch (id) { - case materialPluginEvent_MaterialPluginEvent.GetActiveTextures: { - const eventData = info; - for (const plugin of this._activePlugins) { - plugin.getActiveTextures(eventData.activeTextures); - } - break; - } - case materialPluginEvent_MaterialPluginEvent.GetAnimatables: { - const eventData = info; - for (const plugin of this._activePlugins) { - plugin.getAnimatables(eventData.animatables); - } - break; - } - case materialPluginEvent_MaterialPluginEvent.HasTexture: { - const eventData = info; - let hasTexture = false; - for (const plugin of this._activePlugins) { - hasTexture = plugin.hasTexture(eventData.texture); - if (hasTexture) { - break; - } - } - eventData.hasTexture = hasTexture; - break; - } - case materialPluginEvent_MaterialPluginEvent.Disposed: { - const eventData = info; - for (const plugin of this._plugins) { - plugin.dispose(eventData.forceDisposeTextures); - } - break; - } - case materialPluginEvent_MaterialPluginEvent.GetDefineNames: { - const eventData = info; - eventData.defineNames = this._defineNamesFromPlugins; - break; - } - case materialPluginEvent_MaterialPluginEvent.PrepareEffect: { - const eventData = info; - for (const plugin of this._activePlugins) { - eventData.fallbackRank = plugin.addFallbacks(eventData.defines, eventData.fallbacks, eventData.fallbackRank); - plugin.getAttributes(eventData.attributes, this._scene, eventData.mesh); - } - if (this._uniformList.length > 0) { - eventData.uniforms.push(...this._uniformList); - } - if (this._samplerList.length > 0) { - eventData.samplers.push(...this._samplerList); - } - if (this._uboList.length > 0) { - eventData.uniformBuffersNames.push(...this._uboList); - } - eventData.customCode = this._injectCustomCode(eventData, eventData.customCode); - break; - } - case materialPluginEvent_MaterialPluginEvent.PrepareUniformBuffer: { - const eventData = info; - this._uboDeclaration = ""; - this._vertexDeclaration = ""; - this._fragmentDeclaration = ""; - this._uniformList = []; - this._samplerList = []; - this._uboList = []; - for (const plugin of this._plugins) { - const uniforms = plugin.getUniforms(); - if (uniforms) { - if (uniforms.ubo) { - for (const uniform of uniforms.ubo) { - if (uniform.size && uniform.type) { - const arraySize = (_a = uniform.arraySize) !== null && _a !== void 0 ? _a : 0; - eventData.ubo.addUniform(uniform.name, uniform.size, arraySize); - this._uboDeclaration += `${uniform.type} ${uniform.name}${arraySize > 0 ? `[${arraySize}]` : ""};\n`; - } - this._uniformList.push(uniform.name); - } - } - if (uniforms.vertex) { - this._vertexDeclaration += uniforms.vertex + "\n"; - } - if (uniforms.fragment) { - this._fragmentDeclaration += uniforms.fragment + "\n"; - } - } - plugin.getSamplers(this._samplerList); - plugin.getUniformBuffersNames(this._uboList); - } - break; - } - } - } - _collectPointNames(shaderType, customCode) { - if (!customCode) { - return; - } - for (const pointName in customCode) { - if (!this._codeInjectionPoints[shaderType]) { - this._codeInjectionPoints[shaderType] = {}; - } - this._codeInjectionPoints[shaderType][pointName] = true; - } - } - _injectCustomCode(eventData, existingCallback) { - return (shaderType, code) => { - var _a, _b; - if (existingCallback) { - code = existingCallback(shaderType, code); - } - if (this._uboDeclaration) { - code = code.replace("#define ADDITIONAL_UBO_DECLARATION", this._uboDeclaration); - } - if (this._vertexDeclaration) { - code = code.replace("#define ADDITIONAL_VERTEX_DECLARATION", this._vertexDeclaration); - } - if (this._fragmentDeclaration) { - code = code.replace("#define ADDITIONAL_FRAGMENT_DECLARATION", this._fragmentDeclaration); - } - const points = (_a = this._codeInjectionPoints) === null || _a === void 0 ? void 0 : _a[shaderType]; - if (!points) { - return code; - } - let processorOptions = null; - for (let pointName in points) { - let injectedCode = ""; - for (const plugin of this._activePlugins) { - let customCode = (_b = plugin.getCustomCode(shaderType)) === null || _b === void 0 ? void 0 : _b[pointName]; - if (!customCode) { - continue; - } - if (plugin.resolveIncludes) { - if (processorOptions === null) { - const shaderLanguage = ShaderLanguage.GLSL; - processorOptions = { - defines: [], - indexParameters: eventData.indexParameters, - isFragment: false, - shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader, - processor: undefined, - supportsUniformBuffers: this._engine.supportsUniformBuffers, - shadersRepository: ShaderStore.GetShadersRepository(shaderLanguage), - includesShadersStore: ShaderStore.GetIncludesShadersStore(shaderLanguage), - version: undefined, - platformName: this._engine.shaderPlatformName, - processingContext: undefined, - isNDCHalfZRange: this._engine.isNDCHalfZRange, - useReverseDepthBuffer: this._engine.useReverseDepthBuffer, - processCodeAfterIncludes: undefined, // not used by _ProcessIncludes - }; - } - processorOptions.isFragment = shaderType === "fragment"; - ShaderProcessor._ProcessIncludes(customCode, processorOptions, (code) => (customCode = code)); - } - injectedCode += customCode + "\n"; - } - if (injectedCode.length > 0) { - if (pointName.charAt(0) === "!") { - // pointName is a regular expression - pointName = pointName.substring(1); - let regexFlags = "g"; - if (pointName.charAt(0) === "!") { - // no flags - regexFlags = ""; - pointName = pointName.substring(1); - } - else { - // get the flag(s) - const matchOption = rxOption.exec(pointName); - if (matchOption && matchOption.length >= 2) { - regexFlags = matchOption[1]; - pointName = pointName.substring(regexFlags.length + 1); - } - } - if (regexFlags.indexOf("g") < 0) { - // we force the "g" flag so that the regexp object is stateful! - regexFlags += "g"; - } - const sourceCode = code; - const rx = new RegExp(pointName, regexFlags); - let match = rx.exec(sourceCode); - while (match !== null) { - let newCode = injectedCode; - for (let i = 0; i < match.length; ++i) { - newCode = newCode.replace("$" + i, match[i]); - } - code = code.replace(match[0], newCode); - match = rx.exec(sourceCode); - } - } - else { - const fullPointName = "#define " + pointName; - code = code.replace(fullPointName, "\n" + injectedCode + "\n" + fullPointName); - } - } - } - return code; - }; - } -} -/** Map a plugin class name to a #define name (used in the vertex/fragment shaders as a marker of the plugin usage) */ -MaterialPluginManager._MaterialPluginClassToMainDefine = {}; -MaterialPluginManager._MaterialPluginCounter = 0; -(() => { - engineStore_EngineStore.OnEnginesDisposedObservable.add(() => { - UnregisterAllMaterialPlugins(); - }); -})(); -const plugins = []; -let inited = false; -let observer = null; -/** - * Registers a new material plugin through a factory, or updates it. This makes the plugin available to all materials instantiated after its registration. - * @param pluginName The plugin name - * @param factory The factory function which allows to create the plugin - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function RegisterMaterialPlugin(pluginName, factory) { - if (!inited) { - observer = Material.OnEventObservable.add((material) => { - for (const [, factory] of plugins) { - factory(material); - } - }, MaterialPluginEvent.Created); - inited = true; - } - const existing = plugins.filter(([name, _factory]) => name === pluginName); - if (existing.length > 0) { - existing[0][1] = factory; - } - else { - plugins.push([pluginName, factory]); - } -} -/** - * Removes a material plugin from the list of global plugins. - * @param pluginName The plugin name - * @returns true if the plugin has been removed, else false - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function UnregisterMaterialPlugin(pluginName) { - for (let i = 0; i < plugins.length; ++i) { - if (plugins[i][0] === pluginName) { - plugins.splice(i, 1); - if (plugins.length === 0) { - UnregisterAllMaterialPlugins(); - } - return true; - } - } - return false; -} -/** - * Clear the list of global material plugins - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function UnregisterAllMaterialPlugins() { - plugins.length = 0; - inited = false; - material_Material.OnEventObservable.remove(observer); - observer = null; -} -//# sourceMappingURL=materialPluginManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/materialPluginBase.js - - - - -/** - * Base class for material plugins. - * @since 5.0 - */ -class MaterialPluginBase { - _enable(enable) { - if (enable) { - this._pluginManager._activatePlugin(this); - } - } - /** - * Creates a new material plugin - * @param material parent material of the plugin - * @param name name of the plugin - * @param priority priority of the plugin - * @param defines list of defines used by the plugin. The value of the property is the default value for this property - * @param addToPluginList true to add the plugin to the list of plugins managed by the material plugin manager of the material (default: true) - * @param enable true to enable the plugin (it is handy if the plugin does not handle properties to switch its current activation) - * @param resolveIncludes Indicates that any #include directive in the plugin code must be replaced by the corresponding code (default: false) - */ - constructor(material, name, priority, defines, addToPluginList = true, enable = false, resolveIncludes = false) { - /** - * Defines the priority of the plugin. Lower numbers run first. - */ - this.priority = 500; - /** - * Indicates that any #include directive in the plugin code must be replaced by the corresponding code. - */ - this.resolveIncludes = false; - /** - * Indicates that this plugin should be notified for the extra events (HasRenderTargetTextures / FillRenderTargetTextures / HardBindForSubMesh) - */ - this.registerForExtraEvents = false; - this._material = material; - this.name = name; - this.priority = priority; - this.resolveIncludes = resolveIncludes; - if (!material.pluginManager) { - material.pluginManager = new MaterialPluginManager(material); - material.onDisposeObservable.add(() => { - material.pluginManager = undefined; - }); - } - this._pluginDefineNames = defines; - this._pluginManager = material.pluginManager; - if (addToPluginList) { - this._pluginManager._addPlugin(this); - } - if (enable) { - this._enable(true); - } - this.markAllDefinesAsDirty = material._dirtyCallbacks[63]; - } - /** - * Gets the current class name useful for serialization or dynamic coding. - * @returns The class name. - */ - getClassName() { - return "MaterialPluginBase"; - } - /** - * Specifies that the submesh is ready to be used. - * @param defines the list of "defines" to update. - * @param scene defines the scene the material belongs to. - * @param engine the engine this scene belongs to. - * @param subMesh the submesh to check for readiness - * @returns - boolean indicating that the submesh is ready or not. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - isReadyForSubMesh(defines, scene, engine, subMesh) { - return true; - } - /** - * Binds the material data (this function is called even if mustRebind() returns false) - * @param uniformBuffer defines the Uniform buffer to fill in. - * @param scene defines the scene the material belongs to. - * @param engine defines the engine the material belongs to. - * @param subMesh the submesh to bind data for - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - hardBindForSubMesh(uniformBuffer, scene, engine, subMesh) { } - /** - * Binds the material data. - * @param uniformBuffer defines the Uniform buffer to fill in. - * @param scene defines the scene the material belongs to. - * @param engine the engine this scene belongs to. - * @param subMesh the submesh to bind data for - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - bindForSubMesh(uniformBuffer, scene, engine, subMesh) { } - /** - * Disposes the resources of the material. - * @param forceDisposeTextures - Forces the disposal of all textures. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - dispose(forceDisposeTextures) { } - /** - * Returns a list of custom shader code fragments to customize the shader. - * @param shaderType "vertex" or "fragment" - * @returns null if no code to be added, or a list of pointName =\> code. - * Note that `pointName` can also be a regular expression if it starts with a `!`. - * In that case, the string found by the regular expression (if any) will be - * replaced by the code provided. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getCustomCode(shaderType) { - return null; - } - /** - * Collects all defines. - * @param defines The object to append to. - */ - collectDefines(defines) { - if (!this._pluginDefineNames) { - return; - } - for (const key of Object.keys(this._pluginDefineNames)) { - if (key[0] === "_") { - continue; - } - const type = typeof this._pluginDefineNames[key]; - defines[key] = { - type: type === "number" ? "number" : type === "string" ? "string" : type === "boolean" ? "boolean" : "object", - default: this._pluginDefineNames[key], - }; - } - } - /** - * Sets the defines for the next rendering. Called before MaterialHelper.PrepareDefinesForAttributes is called. - * @param defines the list of "defines" to update. - * @param scene defines the scene to the material belongs to. - * @param mesh the mesh being rendered - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - prepareDefinesBeforeAttributes(defines, scene, mesh) { } - /** - * Sets the defines for the next rendering - * @param defines the list of "defines" to update. - * @param scene defines the scene to the material belongs to. - * @param mesh the mesh being rendered - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - prepareDefines(defines, scene, mesh) { } - /** - * Checks to see if a texture is used in the material. - * @param texture - Base texture to use. - * @returns - Boolean specifying if a texture is used in the material. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - hasTexture(texture) { - return false; - } - /** - * Gets a boolean indicating that current material needs to register RTT - * @returns true if this uses a render target otherwise false. - */ - hasRenderTargetTextures() { - return false; - } - /** - * Fills the list of render target textures. - * @param renderTargets the list of render targets to update - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - fillRenderTargetTextures(renderTargets) { } - /** - * Returns an array of the actively used textures. - * @param activeTextures Array of BaseTextures - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getActiveTextures(activeTextures) { } - /** - * Returns the animatable textures. - * @param animatables Array of animatable textures. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getAnimatables(animatables) { } - /** - * Add fallbacks to the effect fallbacks list. - * @param defines defines the Base texture to use. - * @param fallbacks defines the current fallback list. - * @param currentRank defines the current fallback rank. - * @returns the new fallback rank. - */ - addFallbacks(defines, fallbacks, currentRank) { - return currentRank; - } - /** - * Gets the samplers used by the plugin. - * @param samplers list that the sampler names should be added to. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getSamplers(samplers) { } - /** - * Gets the attributes used by the plugin. - * @param attributes list that the attribute names should be added to. - * @param scene the scene that the material belongs to. - * @param mesh the mesh being rendered. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getAttributes(attributes, scene, mesh) { } - /** - * Gets the uniform buffers names added by the plugin. - * @param ubos list that the ubo names should be added to. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getUniformBuffersNames(ubos) { } - /** - * 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) - * @returns the description of the uniforms - */ - getUniforms() { - return {}; - } - /** - * Makes a duplicate of the current configuration into another one. - * @param plugin define the config where to copy the info - */ - copyTo(plugin) { - decorators_SerializationHelper.Clone(() => plugin, this); - } - /** - * Serializes this plugin configuration. - * @returns - An object with the serialized config. - */ - serialize() { - return decorators_SerializationHelper.Serialize(this); - } - /** - * Parses a plugin configuration from a serialized object. - * @param source - Serialized object. - * @param scene Defines the scene we are parsing for - * @param rootUrl Defines the rootUrl to load from - */ - parse(source, scene, rootUrl) { - decorators_SerializationHelper.Parse(() => this, source, scene, rootUrl); - } -} -__decorate([ - serialize() -], MaterialPluginBase.prototype, "name", void 0); -__decorate([ - serialize() -], MaterialPluginBase.prototype, "priority", void 0); -__decorate([ - serialize() -], MaterialPluginBase.prototype, "resolveIncludes", void 0); -__decorate([ - serialize() -], MaterialPluginBase.prototype, "registerForExtraEvents", void 0); -//# sourceMappingURL=materialPluginBase.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/material.detailMapConfiguration.js - - - - - - - - -/** - * @internal - */ -class MaterialDetailMapDefines extends MaterialDefines { - constructor() { - super(...arguments); - this.DETAIL = false; - this.DETAILDIRECTUV = 0; - this.DETAIL_NORMALBLENDMETHOD = 0; - } -} -/** - * Plugin that implements the detail map component of a material - * - * Inspired from: - * 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 - * Unreal: https://docs.unrealengine.com/en-US/Engine/Rendering/Materials/HowTo/DetailTexturing/index.html - * Cryengine: https://docs.cryengine.com/display/SDKDOC2/Detail+Maps - */ -class material_detailMapConfiguration_DetailMapConfiguration extends MaterialPluginBase { - /** @internal */ - _markAllSubMeshesAsTexturesDirty() { - this._enable(this._isEnabled); - this._internalMarkAllSubMeshesAsTexturesDirty(); - } - constructor(material, addToPluginList = true) { - super(material, "DetailMap", 140, new MaterialDetailMapDefines(), addToPluginList); - this._texture = null; - /** - * Defines how strongly the detail diffuse/albedo channel is blended with the regular diffuse/albedo texture - * Bigger values mean stronger blending - */ - this.diffuseBlendLevel = 1; - /** - * Defines how strongly the detail roughness channel is blended with the regular roughness value - * Bigger values mean stronger blending. Only used with PBR materials - */ - this.roughnessBlendLevel = 1; - /** - * Defines how strong the bump effect from the detail map is - * Bigger values mean stronger effect - */ - this.bumpLevel = 1; - this._normalBlendMethod = material_Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT; - this._isEnabled = false; - /** - * Enable or disable the detail map on this material - */ - this.isEnabled = false; - this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; - } - isReadyForSubMesh(defines, scene, engine) { - if (!this._isEnabled) { - return true; - } - if (defines._areTexturesDirty && scene.texturesEnabled) { - if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled) { - // Detail texture cannot be not blocking. - if (!this._texture.isReady()) { - return false; - } - } - } - return true; - } - prepareDefines(defines, scene) { - if (this._isEnabled) { - defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod; - const engine = scene.getEngine(); - if (defines._areTexturesDirty) { - if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled && this._isEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, "DETAIL"); - defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod; - } - else { - defines.DETAIL = false; - } - } - } - else { - defines.DETAIL = false; - } - } - bindForSubMesh(uniformBuffer, scene) { - if (!this._isEnabled) { - return; - } - const isFrozen = this._material.isFrozen; - if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { - if (this._texture && MaterialFlags.DetailTextureEnabled) { - uniformBuffer.updateFloat4("vDetailInfos", this._texture.coordinatesIndex, this.diffuseBlendLevel, this.bumpLevel, this.roughnessBlendLevel); - MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, "detail"); - } - } - // Textures - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.DetailTextureEnabled) { - uniformBuffer.setTexture("detailSampler", this._texture); - } - } - } - hasTexture(texture) { - if (this._texture === texture) { - return true; - } - return false; - } - getActiveTextures(activeTextures) { - if (this._texture) { - activeTextures.push(this._texture); - } - } - getAnimatables(animatables) { - if (this._texture && this._texture.animations && this._texture.animations.length > 0) { - animatables.push(this._texture); - } - } - dispose(forceDisposeTextures) { - var _a; - if (forceDisposeTextures) { - (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose(); - } - } - getClassName() { - return "DetailMapConfiguration"; - } - getSamplers(samplers) { - samplers.push("detailSampler"); - } - getUniforms() { - return { - ubo: [ - { name: "vDetailInfos", size: 4, type: "vec4" }, - { name: "detailMatrix", size: 16, type: "mat4" }, - ], - }; - } -} -__decorate([ - serializeAsTexture("detailTexture"), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], material_detailMapConfiguration_DetailMapConfiguration.prototype, "texture", void 0); -__decorate([ - serialize() -], material_detailMapConfiguration_DetailMapConfiguration.prototype, "diffuseBlendLevel", void 0); -__decorate([ - serialize() -], material_detailMapConfiguration_DetailMapConfiguration.prototype, "roughnessBlendLevel", void 0); -__decorate([ - serialize() -], material_detailMapConfiguration_DetailMapConfiguration.prototype, "bumpLevel", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], material_detailMapConfiguration_DetailMapConfiguration.prototype, "normalBlendMethod", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], material_detailMapConfiguration_DetailMapConfiguration.prototype, "isEnabled", void 0); -//# sourceMappingURL=material.detailMapConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/standardMaterial.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - - - - - - - - - - - - - - - -const standardMaterial_onCreatedEffectParameters = { effect: null, subMesh: null }; -/** @internal */ -class StandardMaterialDefines extends MaterialDefines { - /** - * Initializes the Standard Material defines. - * @param externalProperties The external properties - */ - constructor(externalProperties) { - super(externalProperties); - this.MAINUV1 = false; - this.MAINUV2 = false; - this.MAINUV3 = false; - this.MAINUV4 = false; - this.MAINUV5 = false; - this.MAINUV6 = false; - this.DIFFUSE = false; - this.DIFFUSEDIRECTUV = 0; - this.BAKED_VERTEX_ANIMATION_TEXTURE = false; - this.AMBIENT = false; - this.AMBIENTDIRECTUV = 0; - this.OPACITY = false; - this.OPACITYDIRECTUV = 0; - this.OPACITYRGB = false; - this.REFLECTION = false; - this.EMISSIVE = false; - this.EMISSIVEDIRECTUV = 0; - this.SPECULAR = false; - this.SPECULARDIRECTUV = 0; - this.BUMP = false; - this.BUMPDIRECTUV = 0; - this.PARALLAX = false; - this.PARALLAXOCCLUSION = false; - this.SPECULAROVERALPHA = false; - this.CLIPPLANE = false; - this.CLIPPLANE2 = false; - this.CLIPPLANE3 = false; - this.CLIPPLANE4 = false; - this.CLIPPLANE5 = false; - this.CLIPPLANE6 = false; - this.ALPHATEST = false; - this.DEPTHPREPASS = false; - this.ALPHAFROMDIFFUSE = false; - this.POINTSIZE = false; - this.FOG = false; - this.SPECULARTERM = false; - this.DIFFUSEFRESNEL = false; - this.OPACITYFRESNEL = false; - this.REFLECTIONFRESNEL = false; - this.REFRACTIONFRESNEL = false; - this.EMISSIVEFRESNEL = false; - this.FRESNEL = false; - this.NORMAL = false; - this.TANGENT = false; - this.UV1 = false; - this.UV2 = false; - this.UV3 = false; - this.UV4 = false; - this.UV5 = false; - this.UV6 = false; - this.VERTEXCOLOR = false; - this.VERTEXALPHA = false; - this.NUM_BONE_INFLUENCERS = 0; - this.BonesPerMesh = 0; - this.BONETEXTURE = false; - this.BONES_VELOCITY_ENABLED = false; - this.INSTANCES = false; - this.THIN_INSTANCES = false; - this.INSTANCESCOLOR = false; - this.GLOSSINESS = false; - this.ROUGHNESS = false; - this.EMISSIVEASILLUMINATION = false; - this.LINKEMISSIVEWITHDIFFUSE = false; - this.REFLECTIONFRESNELFROMSPECULAR = false; - this.LIGHTMAP = false; - this.LIGHTMAPDIRECTUV = 0; - this.OBJECTSPACE_NORMALMAP = false; - this.USELIGHTMAPASSHADOWMAP = false; - this.REFLECTIONMAP_3D = false; - this.REFLECTIONMAP_SPHERICAL = false; - this.REFLECTIONMAP_PLANAR = false; - this.REFLECTIONMAP_CUBIC = false; - this.USE_LOCAL_REFLECTIONMAP_CUBIC = false; - this.USE_LOCAL_REFRACTIONMAP_CUBIC = false; - this.REFLECTIONMAP_PROJECTION = false; - this.REFLECTIONMAP_SKYBOX = false; - this.REFLECTIONMAP_EXPLICIT = false; - this.REFLECTIONMAP_EQUIRECTANGULAR = false; - this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; - this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; - this.REFLECTIONMAP_OPPOSITEZ = false; - this.INVERTCUBICMAP = false; - this.LOGARITHMICDEPTH = false; - this.REFRACTION = false; - this.REFRACTIONMAP_3D = false; - this.REFLECTIONOVERALPHA = false; - this.TWOSIDEDLIGHTING = false; - this.SHADOWFLOAT = false; - this.MORPHTARGETS = false; - this.MORPHTARGETS_NORMAL = false; - this.MORPHTARGETS_TANGENT = false; - this.MORPHTARGETS_UV = false; - this.NUM_MORPH_INFLUENCERS = 0; - this.MORPHTARGETS_TEXTURE = false; - this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH - this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7 - this.ALPHATEST_AFTERALLALPHACOMPUTATIONS = false; - this.ALPHABLEND = true; - this.PREPASS = false; - this.PREPASS_IRRADIANCE = false; - this.PREPASS_IRRADIANCE_INDEX = -1; - this.PREPASS_ALBEDO_SQRT = false; - this.PREPASS_ALBEDO_SQRT_INDEX = -1; - this.PREPASS_DEPTH = false; - this.PREPASS_DEPTH_INDEX = -1; - this.PREPASS_NORMAL = false; - this.PREPASS_NORMAL_INDEX = -1; - this.PREPASS_POSITION = false; - this.PREPASS_POSITION_INDEX = -1; - this.PREPASS_VELOCITY = false; - this.PREPASS_VELOCITY_INDEX = -1; - this.PREPASS_REFLECTIVITY = false; - this.PREPASS_REFLECTIVITY_INDEX = -1; - this.SCENE_MRT_COUNT = 0; - this.RGBDLIGHTMAP = false; - this.RGBDREFLECTION = false; - this.RGBDREFRACTION = false; - this.IMAGEPROCESSING = false; - this.VIGNETTE = false; - this.VIGNETTEBLENDMODEMULTIPLY = false; - this.VIGNETTEBLENDMODEOPAQUE = false; - this.TONEMAPPING = false; - this.TONEMAPPING_ACES = false; - this.CONTRAST = false; - this.COLORCURVES = false; - this.COLORGRADING = false; - this.COLORGRADING3D = false; - this.SAMPLER3DGREENDEPTH = false; - this.SAMPLER3DBGRMAP = false; - this.DITHER = false; - this.IMAGEPROCESSINGPOSTPROCESS = false; - this.SKIPFINALCOLORCLAMP = false; - this.MULTIVIEW = false; - this.ORDER_INDEPENDENT_TRANSPARENCY = false; - this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false; - this.CAMERA_ORTHOGRAPHIC = false; - this.CAMERA_PERSPECTIVE = false; - /** - * If the reflection texture on this material is in linear color space - * @internal - */ - this.IS_REFLECTION_LINEAR = false; - /** - * If the refraction texture on this material is in linear color space - * @internal - */ - this.IS_REFRACTION_LINEAR = false; - this.EXPOSURE = false; - this.DECAL_AFTER_DETAIL = false; - this.rebuild(); - } - setReflectionMode(modeToEnable) { - const modes = [ - "REFLECTIONMAP_CUBIC", - "REFLECTIONMAP_EXPLICIT", - "REFLECTIONMAP_PLANAR", - "REFLECTIONMAP_PROJECTION", - "REFLECTIONMAP_PROJECTION", - "REFLECTIONMAP_SKYBOX", - "REFLECTIONMAP_SPHERICAL", - "REFLECTIONMAP_EQUIRECTANGULAR", - "REFLECTIONMAP_EQUIRECTANGULAR_FIXED", - "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED", - ]; - for (const mode of modes) { - this[mode] = mode === modeToEnable; - } - } -} -/** - * This is the default material used in Babylon. It is the best trade off between quality - * and performances. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction - */ -class standardMaterial_StandardMaterial extends PushMaterial { - /** - * Gets the image processing configuration used either in this material. - */ - get imageProcessingConfiguration() { - return this._imageProcessingConfiguration; - } - /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ - set imageProcessingConfiguration(value) { - this._attachImageProcessingConfiguration(value); - // Ensure the effect will be rebuilt. - this._markAllSubMeshesAsTexturesDirty(); - } - /** - * Attaches a new image processing configuration to the Standard Material. - * @param configuration - */ - _attachImageProcessingConfiguration(configuration) { - if (configuration === this._imageProcessingConfiguration) { - return; - } - // Detaches observer - if (this._imageProcessingConfiguration && this._imageProcessingObserver) { - this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); - } - // Pick the scene configuration if needed - if (!configuration) { - this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; - } - else { - this._imageProcessingConfiguration = configuration; - } - // Attaches observer - if (this._imageProcessingConfiguration) { - this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { - this._markAllSubMeshesAsImageProcessingDirty(); - }); - } - } - /** - * Can this material render to prepass - */ - get isPrePassCapable() { - return !this.disableDepthWrite; - } - /** - * Gets whether the color curves effect is enabled. - */ - get cameraColorCurvesEnabled() { - return this.imageProcessingConfiguration.colorCurvesEnabled; - } - /** - * Sets whether the color curves effect is enabled. - */ - set cameraColorCurvesEnabled(value) { - this.imageProcessingConfiguration.colorCurvesEnabled = value; - } - /** - * Gets whether the color grading effect is enabled. - */ - get cameraColorGradingEnabled() { - return this.imageProcessingConfiguration.colorGradingEnabled; - } - /** - * Gets whether the color grading effect is enabled. - */ - set cameraColorGradingEnabled(value) { - this.imageProcessingConfiguration.colorGradingEnabled = value; - } - /** - * Gets whether tonemapping is enabled or not. - */ - get cameraToneMappingEnabled() { - return this._imageProcessingConfiguration.toneMappingEnabled; - } - /** - * Sets whether tonemapping is enabled or not - */ - set cameraToneMappingEnabled(value) { - this._imageProcessingConfiguration.toneMappingEnabled = value; - } - /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ - get cameraExposure() { - return this._imageProcessingConfiguration.exposure; - } - /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ - set cameraExposure(value) { - this._imageProcessingConfiguration.exposure = value; - } - /** - * Gets The camera contrast used on this material. - */ - get cameraContrast() { - return this._imageProcessingConfiguration.contrast; - } - /** - * Sets The camera contrast used on this material. - */ - set cameraContrast(value) { - this._imageProcessingConfiguration.contrast = value; - } - /** - * Gets the Color Grading 2D Lookup Texture. - */ - get cameraColorGradingTexture() { - return this._imageProcessingConfiguration.colorGradingTexture; - } - /** - * Sets the Color Grading 2D Lookup Texture. - */ - set cameraColorGradingTexture(value) { - this._imageProcessingConfiguration.colorGradingTexture = value; - } - /** - * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * 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; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ - get cameraColorCurves() { - return this._imageProcessingConfiguration.colorCurves; - } - /** - * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * 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; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ - set cameraColorCurves(value) { - this._imageProcessingConfiguration.colorCurves = value; - } - /** - * Can this material render to several textures at once - */ - get canRenderToMRT() { - return true; - } - /** - * Instantiates a new standard material. - * This is the default material used in Babylon. It is the best trade off between quality - * and performances. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction - * @param name Define the name of the material in the scene - * @param scene Define the scene the material belong to - */ - constructor(name, scene) { - super(name, scene); - 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; - /** - * The color of the material lit by the environmental background lighting. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#ambient-color-example - */ - this.ambientColor = new math_color_Color3(0, 0, 0); - /** - * The basic color of the material as viewed under a light. - */ - this.diffuseColor = new math_color_Color3(1, 1, 1); - /** - * Define how the color and intensity of the highlight given by the light in the material. - */ - this.specularColor = new math_color_Color3(1, 1, 1); - /** - * Define the color of the material as if self lit. - * This will be mixed in the final result even in the absence of light. - */ - this.emissiveColor = new math_color_Color3(0, 0, 0); - /** - * Defines how sharp are the highlights in the material. - * The bigger the value the sharper giving a more glossy feeling to the result. - * Reversely, the smaller the value the blurrier giving a more rough feeling to the result. - */ - this.specularPower = 64; - this._useAlphaFromDiffuseTexture = false; - this._useEmissiveAsIllumination = false; - this._linkEmissiveWithDiffuse = false; - this._useSpecularOverAlpha = false; - this._useReflectionOverAlpha = false; - this._disableLighting = false; - this._useObjectSpaceNormalMap = false; - this._useParallax = false; - this._useParallaxOcclusion = false; - /** - * 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. - */ - this.parallaxScaleBias = 0.05; - this._roughness = 0; - /** - * In case of refraction, define the value of the index of refraction. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#how-to-obtain-reflections-and-refractions - */ - this.indexOfRefraction = 0.98; - /** - * Invert the refraction texture alongside the y axis. - * It can be useful with procedural textures or probe for instance. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#how-to-obtain-reflections-and-refractions - */ - this.invertRefractionY = true; - /** - * Defines the alpha limits in alpha test mode. - */ - this.alphaCutOff = 0.4; - this._useLightmapAsShadowmap = false; - this._useReflectionFresnelFromSpecular = false; - this._useGlossinessFromSpecularMapAlpha = false; - this._maxSimultaneousLights = 4; - this._invertNormalMapX = false; - this._invertNormalMapY = false; - this._twoSidedLighting = false; - this._applyDecalMapAfterDetailMap = false; - this._renderTargets = new SmartArray(16); - this._worldViewProjectionMatrix = math_vector_Matrix.Zero(); - this._globalAmbientColor = new math_color_Color3(0, 0, 0); - this._cacheHasRenderTargetTextures = false; - this.detailMap = new material_detailMapConfiguration_DetailMapConfiguration(this); - // Setup the default processing configuration to the scene. - this._attachImageProcessingConfiguration(null); - this.prePassConfiguration = new PrePassConfiguration(); - this.getRenderTargetTextures = () => { - this._renderTargets.reset(); - if (standardMaterial_StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { - this._renderTargets.push(this._reflectionTexture); - } - if (standardMaterial_StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { - this._renderTargets.push(this._refractionTexture); - } - this._eventInfo.renderTargets = this._renderTargets; - this._callbackPluginEventFillRenderTargetTextures(this._eventInfo); - return this._renderTargets; - }; - } - /** - * Gets a boolean indicating that current material needs to register RTT - */ - get hasRenderTargetTextures() { - if (standardMaterial_StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { - return true; - } - if (standardMaterial_StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { - return true; - } - return this._cacheHasRenderTargetTextures; - } - /** - * Gets the current class name of the material e.g. "StandardMaterial" - * Mainly use in serialization. - * @returns the class name - */ - getClassName() { - return "StandardMaterial"; - } - /** - * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes) - * You can try switching to logarithmic depth. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/logarithmicDepthBuffer - */ - get useLogarithmicDepth() { - return this._useLogarithmicDepth; - } - set useLogarithmicDepth(value) { - this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported; - this._markAllSubMeshesAsMiscDirty(); - } - /** - * Specifies if the material will require alpha blending - * @returns a boolean specifying if alpha blending is needed - */ - needAlphaBlending() { - if (this._disableAlphaBlending) { - return false; - } - return (this.alpha < 1.0 || - this._opacityTexture != null || - this._shouldUseAlphaFromDiffuseTexture() || - (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled)); - } - /** - * Specifies if this material should be rendered in alpha test mode - * @returns a boolean specifying if an alpha test is needed. - */ - needAlphaTesting() { - if (this._forceAlphaTest) { - return true; - } - return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === material_Material.MATERIAL_ALPHATEST); - } - /** - * Specifies whether or not the alpha value of the diffuse texture should be used for alpha blending. - */ - _shouldUseAlphaFromDiffuseTexture() { - return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture && this._transparencyMode !== material_Material.MATERIAL_OPAQUE; - } - /** - * Specifies whether or not there is a usable alpha channel for transparency. - */ - _hasAlphaChannel() { - return (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._opacityTexture != null; - } - /** - * Get the texture used for alpha test purpose. - * @returns the diffuse texture in case of the standard material. - */ - getAlphaTestTexture() { - return this._diffuseTexture; - } - /** - * Get if the submesh is ready to be used and all its information available. - * Child classes can use it to update shaders - * @param mesh defines the mesh to check - * @param subMesh defines which submesh to check - * @param useInstances specifies that instances should be used - * @returns a boolean indicating that the submesh is ready or not - */ - isReadyForSubMesh(mesh, subMesh, useInstances = false) { - if (!this._uniformBufferLayoutBuilt) { - this.buildUniformLayout(); - } - if (subMesh.effect && this.isFrozen) { - if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) { - return true; - } - } - if (!subMesh.materialDefines) { - this._callbackPluginEventGeneric(materialPluginEvent_MaterialPluginEvent.GetDefineNames, this._eventInfo); - subMesh.materialDefines = new StandardMaterialDefines(this._eventInfo.defineNames); - } - const scene = this.getScene(); - const defines = subMesh.materialDefines; - if (this._isReadyForSubMesh(subMesh)) { - return true; - } - const engine = scene.getEngine(); - // Lights - defines._needNormals = MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting); - // Multiview - MaterialHelper.PrepareDefinesForMultiview(scene, defines); - // PrePass - const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency; - MaterialHelper.PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit); - // Order independant transparency - MaterialHelper.PrepareDefinesForOIT(scene, defines, oit); - // Textures - if (defines._areTexturesDirty) { - this._eventInfo.hasRenderTargetTextures = false; - this._callbackPluginEventHasRenderTargetTextures(this._eventInfo); - this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures; - defines._needUVs = false; - for (let i = 1; i <= 6; ++i) { - defines["MAINUV" + i] = false; - } - if (scene.texturesEnabled) { - defines.DIFFUSEDIRECTUV = 0; - defines.BUMPDIRECTUV = 0; - defines.AMBIENTDIRECTUV = 0; - defines.OPACITYDIRECTUV = 0; - defines.EMISSIVEDIRECTUV = 0; - defines.SPECULARDIRECTUV = 0; - defines.LIGHTMAPDIRECTUV = 0; - if (this._diffuseTexture && standardMaterial_StandardMaterial.DiffuseTextureEnabled) { - if (!this._diffuseTexture.isReadyOrNotBlocking()) { - return false; - } - else { - MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE"); - } - } - else { - defines.DIFFUSE = false; - } - if (this._ambientTexture && standardMaterial_StandardMaterial.AmbientTextureEnabled) { - if (!this._ambientTexture.isReadyOrNotBlocking()) { - return false; - } - else { - MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT"); - } - } - else { - defines.AMBIENT = false; - } - if (this._opacityTexture && standardMaterial_StandardMaterial.OpacityTextureEnabled) { - if (!this._opacityTexture.isReadyOrNotBlocking()) { - return false; - } - else { - MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY"); - defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB; - } - } - else { - defines.OPACITY = false; - } - if (this._reflectionTexture && standardMaterial_StandardMaterial.ReflectionTextureEnabled) { - if (!this._reflectionTexture.isReadyOrNotBlocking()) { - return false; - } - else { - defines._needNormals = true; - defines.REFLECTION = true; - defines.ROUGHNESS = this._roughness > 0; - defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha; - defines.INVERTCUBICMAP = this._reflectionTexture.coordinatesMode === texture_Texture.INVCUBIC_MODE; - defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube; - defines.REFLECTIONMAP_OPPOSITEZ = - defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !this._reflectionTexture.invertZ : this._reflectionTexture.invertZ; - defines.RGBDREFLECTION = this._reflectionTexture.isRGBD; - switch (this._reflectionTexture.coordinatesMode) { - case texture_Texture.EXPLICIT_MODE: - defines.setReflectionMode("REFLECTIONMAP_EXPLICIT"); - break; - case texture_Texture.PLANAR_MODE: - defines.setReflectionMode("REFLECTIONMAP_PLANAR"); - break; - case texture_Texture.PROJECTION_MODE: - defines.setReflectionMode("REFLECTIONMAP_PROJECTION"); - break; - case texture_Texture.SKYBOX_MODE: - defines.setReflectionMode("REFLECTIONMAP_SKYBOX"); - break; - case texture_Texture.SPHERICAL_MODE: - defines.setReflectionMode("REFLECTIONMAP_SPHERICAL"); - break; - case texture_Texture.EQUIRECTANGULAR_MODE: - defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR"); - break; - case texture_Texture.FIXED_EQUIRECTANGULAR_MODE: - defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"); - break; - case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE: - defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"); - break; - case texture_Texture.CUBIC_MODE: - case texture_Texture.INVCUBIC_MODE: - default: - defines.setReflectionMode("REFLECTIONMAP_CUBIC"); - break; - } - defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false; - } - } - else { - defines.REFLECTION = false; - defines.REFLECTIONMAP_OPPOSITEZ = false; - } - if (this._emissiveTexture && standardMaterial_StandardMaterial.EmissiveTextureEnabled) { - if (!this._emissiveTexture.isReadyOrNotBlocking()) { - return false; - } - else { - MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE"); - } - } - else { - defines.EMISSIVE = false; - } - if (this._lightmapTexture && standardMaterial_StandardMaterial.LightmapTextureEnabled) { - if (!this._lightmapTexture.isReadyOrNotBlocking()) { - return false; - } - else { - MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP"); - defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap; - defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD; - } - } - else { - defines.LIGHTMAP = false; - } - if (this._specularTexture && standardMaterial_StandardMaterial.SpecularTextureEnabled) { - if (!this._specularTexture.isReadyOrNotBlocking()) { - return false; - } - else { - MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR"); - defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha; - } - } - else { - defines.SPECULAR = false; - } - if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && standardMaterial_StandardMaterial.BumpTextureEnabled) { - // Bump texture can not be not blocking. - if (!this._bumpTexture.isReady()) { - return false; - } - else { - MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP"); - defines.PARALLAX = this._useParallax; - defines.PARALLAXOCCLUSION = this._useParallaxOcclusion; - } - defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap; - } - else { - defines.BUMP = false; - defines.PARALLAX = false; - defines.PARALLAXOCCLUSION = false; - } - if (this._refractionTexture && standardMaterial_StandardMaterial.RefractionTextureEnabled) { - if (!this._refractionTexture.isReadyOrNotBlocking()) { - return false; - } - else { - defines._needUVs = true; - defines.REFRACTION = true; - defines.REFRACTIONMAP_3D = this._refractionTexture.isCube; - defines.RGBDREFRACTION = this._refractionTexture.isRGBD; - defines.USE_LOCAL_REFRACTIONMAP_CUBIC = this._refractionTexture.boundingBoxSize ? true : false; - } - } - else { - defines.REFRACTION = false; - } - defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting; - } - else { - defines.DIFFUSE = false; - defines.AMBIENT = false; - defines.OPACITY = false; - defines.REFLECTION = false; - defines.EMISSIVE = false; - defines.LIGHTMAP = false; - defines.BUMP = false; - defines.REFRACTION = false; - } - defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture(); - defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination; - defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse; - defines.SPECULAROVERALPHA = this._useSpecularOverAlpha; - defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8; - defines.ALPHATEST_AFTERALLALPHACOMPUTATIONS = this.transparencyMode !== null; - defines.ALPHABLEND = this.transparencyMode === null || this.needAlphaBlendingForMesh(mesh); // check on null for backward compatibility - } - this._eventInfo.isReadyForSubMesh = true; - this._eventInfo.defines = defines; - this._eventInfo.subMesh = subMesh; - this._callbackPluginEventIsReadyForSubMesh(this._eventInfo); - if (!this._eventInfo.isReadyForSubMesh) { - return false; - } - if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { - if (!this._imageProcessingConfiguration.isReady()) { - return false; - } - this._imageProcessingConfiguration.prepareDefines(defines); - defines.IS_REFLECTION_LINEAR = this.reflectionTexture != null && !this.reflectionTexture.gammaSpace; - defines.IS_REFRACTION_LINEAR = this.refractionTexture != null && !this.refractionTexture.gammaSpace; - } - if (defines._areFresnelDirty) { - if (standardMaterial_StandardMaterial.FresnelEnabled) { - // Fresnel - if (this._diffuseFresnelParameters || - this._opacityFresnelParameters || - this._emissiveFresnelParameters || - this._refractionFresnelParameters || - this._reflectionFresnelParameters) { - defines.DIFFUSEFRESNEL = this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled; - defines.OPACITYFRESNEL = this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled; - defines.REFLECTIONFRESNEL = this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled; - defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular; - defines.REFRACTIONFRESNEL = this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled; - defines.EMISSIVEFRESNEL = this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled; - defines._needNormals = true; - defines.FRESNEL = true; - } - } - else { - defines.FRESNEL = false; - } - } - // Misc. - MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines, this._applyDecalMapAfterDetailMap); - // Values that need to be evaluated on every frame - MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances); - // External config - this._eventInfo.defines = defines; - this._eventInfo.mesh = mesh; - this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo); - // Attribs - MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true); - // External config - this._callbackPluginEventPrepareDefines(this._eventInfo); - // Get correct effect - let forceWasNotReadyPreviously = false; - if (defines.isDirty) { - const lightDisposed = defines._areLightsDisposed; - defines.markAsProcessed(); - // Fallbacks - const fallbacks = new EffectFallbacks(); - if (defines.REFLECTION) { - fallbacks.addFallback(0, "REFLECTION"); - } - if (defines.SPECULAR) { - fallbacks.addFallback(0, "SPECULAR"); - } - if (defines.BUMP) { - fallbacks.addFallback(0, "BUMP"); - } - if (defines.PARALLAX) { - fallbacks.addFallback(1, "PARALLAX"); - } - if (defines.PARALLAXOCCLUSION) { - fallbacks.addFallback(0, "PARALLAXOCCLUSION"); - } - if (defines.SPECULAROVERALPHA) { - fallbacks.addFallback(0, "SPECULAROVERALPHA"); - } - if (defines.FOG) { - fallbacks.addFallback(1, "FOG"); - } - if (defines.POINTSIZE) { - fallbacks.addFallback(0, "POINTSIZE"); - } - if (defines.LOGARITHMICDEPTH) { - fallbacks.addFallback(0, "LOGARITHMICDEPTH"); - } - MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights); - if (defines.SPECULARTERM) { - fallbacks.addFallback(0, "SPECULARTERM"); - } - if (defines.DIFFUSEFRESNEL) { - fallbacks.addFallback(1, "DIFFUSEFRESNEL"); - } - if (defines.OPACITYFRESNEL) { - fallbacks.addFallback(2, "OPACITYFRESNEL"); - } - if (defines.REFLECTIONFRESNEL) { - fallbacks.addFallback(3, "REFLECTIONFRESNEL"); - } - if (defines.EMISSIVEFRESNEL) { - fallbacks.addFallback(4, "EMISSIVEFRESNEL"); - } - if (defines.FRESNEL) { - fallbacks.addFallback(4, "FRESNEL"); - } - if (defines.MULTIVIEW) { - fallbacks.addFallback(0, "MULTIVIEW"); - } - //Attributes - const attribs = [buffer_VertexBuffer.PositionKind]; - if (defines.NORMAL) { - attribs.push(buffer_VertexBuffer.NormalKind); - } - if (defines.TANGENT) { - attribs.push(buffer_VertexBuffer.TangentKind); - } - for (let i = 1; i <= 6; ++i) { - if (defines["UV" + i]) { - attribs.push(`uv${i === 1 ? "" : i}`); - } - } - if (defines.VERTEXCOLOR) { - attribs.push(buffer_VertexBuffer.ColorKind); - } - MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks); - MaterialHelper.PrepareAttributesForInstances(attribs, defines); - MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines); - MaterialHelper.PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines); - let shaderName = "default"; - const uniforms = [ - "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", - ]; - const samplers = [ - "diffuseSampler", - "ambientSampler", - "opacitySampler", - "reflectionCubeSampler", - "reflection2DSampler", - "emissiveSampler", - "specularSampler", - "bumpSampler", - "lightmapSampler", - "refractionCubeSampler", - "refraction2DSampler", - "boneSampler", - "morphTargets", - "oitDepthSampler", - "oitFrontColorSampler", - ]; - const uniformBuffers = ["Material", "Scene", "Mesh"]; - const indexParameters = { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }; - this._eventInfo.fallbacks = fallbacks; - this._eventInfo.fallbackRank = 0; - this._eventInfo.defines = defines; - this._eventInfo.uniforms = uniforms; - this._eventInfo.attributes = attribs; - this._eventInfo.samplers = samplers; - this._eventInfo.uniformBuffersNames = uniformBuffers; - this._eventInfo.customCode = undefined; - this._eventInfo.mesh = mesh; - this._eventInfo.indexParameters = indexParameters; - this._callbackPluginEventGeneric(materialPluginEvent_MaterialPluginEvent.PrepareEffect, this._eventInfo); - PrePassConfiguration.AddUniforms(uniforms); - PrePassConfiguration.AddSamplers(samplers); - if (ImageProcessingConfiguration) { - ImageProcessingConfiguration.PrepareUniforms(uniforms, defines); - ImageProcessingConfiguration.PrepareSamplers(samplers, defines); - } - MaterialHelper.PrepareUniformsAndSamplersList({ - uniformsNames: uniforms, - uniformBuffersNames: uniformBuffers, - samplers: samplers, - defines: defines, - maxSimultaneousLights: this._maxSimultaneousLights, - }); - addClipPlaneUniforms(uniforms); - const csnrOptions = {}; - if (this.customShaderNameResolve) { - shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions); - } - const join = defines.toString(); - const previousEffect = subMesh.effect; - let effect = scene.getEngine().createEffect(shaderName, { - attributes: attribs, - uniformsNames: uniforms, - uniformBuffersNames: uniformBuffers, - samplers: samplers, - defines: join, - fallbacks: fallbacks, - onCompiled: this.onCompiled, - onError: this.onError, - indexParameters, - processFinalCode: csnrOptions.processFinalCode, - processCodeAfterIncludes: this._eventInfo.customCode, - multiTarget: defines.PREPASS, - }, engine); - this._eventInfo.customCode = undefined; - if (effect) { - if (this._onEffectCreatedObservable) { - standardMaterial_onCreatedEffectParameters.effect = effect; - standardMaterial_onCreatedEffectParameters.subMesh = subMesh; - this._onEffectCreatedObservable.notifyObservers(standardMaterial_onCreatedEffectParameters); - } - // Use previous effect while new one is compiling - if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) { - effect = previousEffect; - defines.markAsUnprocessed(); - forceWasNotReadyPreviously = this.isFrozen; - if (lightDisposed) { - // re register in case it takes more than one frame. - defines._areLightsDisposed = true; - return false; - } - } - else { - scene.resetCachedMaterial(); - subMesh.setEffect(effect, defines, this._materialContext); - } - } - } - if (!subMesh.effect || !subMesh.effect.isReady()) { - return false; - } - defines._renderId = scene.getRenderId(); - subMesh.effect._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true; - subMesh.effect._wasPreviouslyUsingInstances = useInstances; - this._checkScenePerformancePriority(); - return true; - } - /** - * Builds the material UBO layouts. - * Used internally during the effect preparation. - */ - buildUniformLayout() { - // Order is important ! - const ubo = this._uniformBuffer; - ubo.addUniform("diffuseLeftColor", 4); - ubo.addUniform("diffuseRightColor", 4); - ubo.addUniform("opacityParts", 4); - ubo.addUniform("reflectionLeftColor", 4); - ubo.addUniform("reflectionRightColor", 4); - ubo.addUniform("refractionLeftColor", 4); - ubo.addUniform("refractionRightColor", 4); - ubo.addUniform("emissiveLeftColor", 4); - ubo.addUniform("emissiveRightColor", 4); - ubo.addUniform("vDiffuseInfos", 2); - ubo.addUniform("vAmbientInfos", 2); - ubo.addUniform("vOpacityInfos", 2); - ubo.addUniform("vReflectionInfos", 2); - ubo.addUniform("vReflectionPosition", 3); - ubo.addUniform("vReflectionSize", 3); - ubo.addUniform("vEmissiveInfos", 2); - ubo.addUniform("vLightmapInfos", 2); - ubo.addUniform("vSpecularInfos", 2); - ubo.addUniform("vBumpInfos", 3); - ubo.addUniform("diffuseMatrix", 16); - ubo.addUniform("ambientMatrix", 16); - ubo.addUniform("opacityMatrix", 16); - ubo.addUniform("reflectionMatrix", 16); - ubo.addUniform("emissiveMatrix", 16); - ubo.addUniform("lightmapMatrix", 16); - ubo.addUniform("specularMatrix", 16); - ubo.addUniform("bumpMatrix", 16); - ubo.addUniform("vTangentSpaceParams", 2); - ubo.addUniform("pointSize", 1); - ubo.addUniform("alphaCutOff", 1); - ubo.addUniform("refractionMatrix", 16); - ubo.addUniform("vRefractionInfos", 4); - ubo.addUniform("vRefractionPosition", 3); - ubo.addUniform("vRefractionSize", 3); - ubo.addUniform("vSpecularColor", 4); - ubo.addUniform("vEmissiveColor", 3); - ubo.addUniform("vDiffuseColor", 4); - ubo.addUniform("vAmbientColor", 3); - super.buildUniformLayout(); - } - /** - * Binds the submesh to this material by preparing the effect and shader to draw - * @param world defines the world transformation matrix - * @param mesh defines the mesh containing the submesh - * @param subMesh defines the submesh to bind the material to - */ - bindForSubMesh(world, mesh, subMesh) { - var _a; - const scene = this.getScene(); - const defines = subMesh.materialDefines; - if (!defines) { - return; - } - const effect = subMesh.effect; - if (!effect) { - return; - } - this._activeEffect = effect; - // Matrices Mesh. - mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); - mesh.transferToEffect(world); - // Binding unconditionally - this._uniformBuffer.bindToEffect(effect, "Material"); - this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen); - this._eventInfo.subMesh = subMesh; - this._callbackPluginEventHardBindForSubMesh(this._eventInfo); - // Normal Matrix - if (defines.OBJECTSPACE_NORMALMAP) { - world.toNormalMatrix(this._normalMatrix); - this.bindOnlyNormalMatrix(this._normalMatrix); - } - const mustRebind = effect._forceRebindOnNextCall || this._mustRebind(scene, effect, mesh.visibility); - // Bones - MaterialHelper.BindBonesParameters(mesh, effect); - const ubo = this._uniformBuffer; - if (mustRebind) { - this.bindViewProjection(effect); - if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || effect._forceRebindOnNextCall) { - if (standardMaterial_StandardMaterial.FresnelEnabled && defines.FRESNEL) { - // Fresnel - if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) { - ubo.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power); - ubo.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias); - } - if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) { - ubo.updateColor4("opacityParts", new math_color_Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power); - } - if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) { - ubo.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power); - ubo.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias); - } - if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) { - ubo.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power); - ubo.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias); - } - if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) { - ubo.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power); - ubo.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias); - } - } - // Textures - if (scene.texturesEnabled) { - if (this._diffuseTexture && standardMaterial_StandardMaterial.DiffuseTextureEnabled) { - ubo.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level); - MaterialHelper.BindTextureMatrix(this._diffuseTexture, ubo, "diffuse"); - } - if (this._ambientTexture && standardMaterial_StandardMaterial.AmbientTextureEnabled) { - ubo.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level); - MaterialHelper.BindTextureMatrix(this._ambientTexture, ubo, "ambient"); - } - if (this._opacityTexture && standardMaterial_StandardMaterial.OpacityTextureEnabled) { - ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level); - MaterialHelper.BindTextureMatrix(this._opacityTexture, ubo, "opacity"); - } - if (this._hasAlphaChannel()) { - ubo.updateFloat("alphaCutOff", this.alphaCutOff); - } - if (this._reflectionTexture && standardMaterial_StandardMaterial.ReflectionTextureEnabled) { - ubo.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness); - ubo.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix()); - if (this._reflectionTexture.boundingBoxSize) { - const cubeTexture = this._reflectionTexture; - ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition); - ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize); - } - } - if (this._emissiveTexture && standardMaterial_StandardMaterial.EmissiveTextureEnabled) { - ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level); - MaterialHelper.BindTextureMatrix(this._emissiveTexture, ubo, "emissive"); - } - if (this._lightmapTexture && standardMaterial_StandardMaterial.LightmapTextureEnabled) { - ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level); - MaterialHelper.BindTextureMatrix(this._lightmapTexture, ubo, "lightmap"); - } - if (this._specularTexture && standardMaterial_StandardMaterial.SpecularTextureEnabled) { - ubo.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level); - MaterialHelper.BindTextureMatrix(this._specularTexture, ubo, "specular"); - } - if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && standardMaterial_StandardMaterial.BumpTextureEnabled) { - ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias); - MaterialHelper.BindTextureMatrix(this._bumpTexture, ubo, "bump"); - if (scene._mirroredCameraPosition) { - ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0); - } - else { - ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0); - } - } - if (this._refractionTexture && standardMaterial_StandardMaterial.RefractionTextureEnabled) { - let depth = 1.0; - if (!this._refractionTexture.isCube) { - ubo.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix()); - if (this._refractionTexture.depth) { - depth = this._refractionTexture.depth; - } - } - ubo.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1); - if (this._refractionTexture.boundingBoxSize) { - const cubeTexture = this._refractionTexture; - ubo.updateVector3("vRefractionPosition", cubeTexture.boundingBoxPosition); - ubo.updateVector3("vRefractionSize", cubeTexture.boundingBoxSize); - } - } - } - // Point size - if (this.pointsCloud) { - ubo.updateFloat("pointSize", this.pointSize); - } - if (defines.SPECULARTERM) { - ubo.updateColor4("vSpecularColor", this.specularColor, this.specularPower); - } - ubo.updateColor3("vEmissiveColor", standardMaterial_StandardMaterial.EmissiveTextureEnabled ? this.emissiveColor : math_color_Color3.BlackReadOnly); - ubo.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha); - scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor); - ubo.updateColor3("vAmbientColor", this._globalAmbientColor); - } - // Textures - if (scene.texturesEnabled) { - if (this._diffuseTexture && standardMaterial_StandardMaterial.DiffuseTextureEnabled) { - effect.setTexture("diffuseSampler", this._diffuseTexture); - } - if (this._ambientTexture && standardMaterial_StandardMaterial.AmbientTextureEnabled) { - effect.setTexture("ambientSampler", this._ambientTexture); - } - if (this._opacityTexture && standardMaterial_StandardMaterial.OpacityTextureEnabled) { - effect.setTexture("opacitySampler", this._opacityTexture); - } - if (this._reflectionTexture && standardMaterial_StandardMaterial.ReflectionTextureEnabled) { - if (this._reflectionTexture.isCube) { - effect.setTexture("reflectionCubeSampler", this._reflectionTexture); - } - else { - effect.setTexture("reflection2DSampler", this._reflectionTexture); - } - } - if (this._emissiveTexture && standardMaterial_StandardMaterial.EmissiveTextureEnabled) { - effect.setTexture("emissiveSampler", this._emissiveTexture); - } - if (this._lightmapTexture && standardMaterial_StandardMaterial.LightmapTextureEnabled) { - effect.setTexture("lightmapSampler", this._lightmapTexture); - } - if (this._specularTexture && standardMaterial_StandardMaterial.SpecularTextureEnabled) { - effect.setTexture("specularSampler", this._specularTexture); - } - if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && standardMaterial_StandardMaterial.BumpTextureEnabled) { - effect.setTexture("bumpSampler", this._bumpTexture); - } - if (this._refractionTexture && standardMaterial_StandardMaterial.RefractionTextureEnabled) { - if (this._refractionTexture.isCube) { - effect.setTexture("refractionCubeSampler", this._refractionTexture); - } - else { - effect.setTexture("refraction2DSampler", this._refractionTexture); - } - } - } - // OIT with depth peeling - if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) { - this.getScene().depthPeelingRenderer.bind(effect); - } - this._eventInfo.subMesh = subMesh; - this._callbackPluginEventBindForSubMesh(this._eventInfo); - // Clip plane - bindClipPlane(effect, this, scene); - // Colors - this.bindEyePosition(effect); - } - else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) { - this._needToBindSceneUbo = true; - } - if (mustRebind || !this.isFrozen) { - // Lights - if (scene.lightsEnabled && !this._disableLighting) { - MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights); - } - // View - if ((scene.fogEnabled && mesh.applyFog && scene.fogMode !== scene_Scene.FOGMODE_NONE) || - this._reflectionTexture || - this._refractionTexture || - mesh.receiveShadows || - defines.PREPASS) { - this.bindView(effect); - } - // Fog - MaterialHelper.BindFogParameters(scene, mesh, effect); - // Morph targets - if (defines.NUM_MORPH_INFLUENCERS) { - MaterialHelper.BindMorphTargetParameters(mesh, effect); - } - if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) { - (_a = mesh.bakedVertexAnimationManager) === null || _a === void 0 ? void 0 : _a.bind(effect, defines.INSTANCES); - } - // Log. depth - if (this.useLogarithmicDepth) { - MaterialHelper.BindLogDepth(defines, effect, scene); - } - // image processing - if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) { - this._imageProcessingConfiguration.bind(this._activeEffect); - } - } - this._afterBind(mesh, this._activeEffect); - ubo.update(); - } - /** - * Get the list of animatables in the material. - * @returns the list of animatables object used in the material - */ - getAnimatables() { - const results = super.getAnimatables(); - if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) { - results.push(this._diffuseTexture); - } - if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) { - results.push(this._ambientTexture); - } - if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) { - results.push(this._opacityTexture); - } - if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) { - results.push(this._reflectionTexture); - } - if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) { - results.push(this._emissiveTexture); - } - if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) { - results.push(this._specularTexture); - } - if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { - results.push(this._bumpTexture); - } - if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) { - results.push(this._lightmapTexture); - } - if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) { - results.push(this._refractionTexture); - } - return results; - } - /** - * Gets the active textures from the material - * @returns an array of textures - */ - getActiveTextures() { - const activeTextures = super.getActiveTextures(); - if (this._diffuseTexture) { - activeTextures.push(this._diffuseTexture); - } - if (this._ambientTexture) { - activeTextures.push(this._ambientTexture); - } - if (this._opacityTexture) { - activeTextures.push(this._opacityTexture); - } - if (this._reflectionTexture) { - activeTextures.push(this._reflectionTexture); - } - if (this._emissiveTexture) { - activeTextures.push(this._emissiveTexture); - } - if (this._specularTexture) { - activeTextures.push(this._specularTexture); - } - if (this._bumpTexture) { - activeTextures.push(this._bumpTexture); - } - if (this._lightmapTexture) { - activeTextures.push(this._lightmapTexture); - } - if (this._refractionTexture) { - activeTextures.push(this._refractionTexture); - } - return activeTextures; - } - /** - * Specifies if the material uses a texture - * @param texture defines the texture to check against the material - * @returns a boolean specifying if the material uses the texture - */ - hasTexture(texture) { - if (super.hasTexture(texture)) { - return true; - } - if (this._diffuseTexture === texture) { - return true; - } - if (this._ambientTexture === texture) { - return true; - } - if (this._opacityTexture === texture) { - return true; - } - if (this._reflectionTexture === texture) { - return true; - } - if (this._emissiveTexture === texture) { - return true; - } - if (this._specularTexture === texture) { - return true; - } - if (this._bumpTexture === texture) { - return true; - } - if (this._lightmapTexture === texture) { - return true; - } - if (this._refractionTexture === texture) { - return true; - } - return false; - } - /** - * Disposes the material - * @param forceDisposeEffect specifies if effects should be forcefully disposed - * @param forceDisposeTextures specifies if textures should be forcefully disposed - */ - dispose(forceDisposeEffect, forceDisposeTextures) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j; - if (forceDisposeTextures) { - (_a = this._diffuseTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - (_b = this._ambientTexture) === null || _b === void 0 ? void 0 : _b.dispose(); - (_c = this._opacityTexture) === null || _c === void 0 ? void 0 : _c.dispose(); - (_d = this._reflectionTexture) === null || _d === void 0 ? void 0 : _d.dispose(); - (_e = this._emissiveTexture) === null || _e === void 0 ? void 0 : _e.dispose(); - (_f = this._specularTexture) === null || _f === void 0 ? void 0 : _f.dispose(); - (_g = this._bumpTexture) === null || _g === void 0 ? void 0 : _g.dispose(); - (_h = this._lightmapTexture) === null || _h === void 0 ? void 0 : _h.dispose(); - (_j = this._refractionTexture) === null || _j === void 0 ? void 0 : _j.dispose(); - } - if (this._imageProcessingConfiguration && this._imageProcessingObserver) { - this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); - } - super.dispose(forceDisposeEffect, forceDisposeTextures); - } - /** - * Makes a duplicate of the material, and gives it a new name - * @param name defines the new name for the duplicated material - * @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. - * @param rootUrl defines the root URL to use to load textures - * @returns the cloned material - */ - clone(name, cloneTexturesOnlyOnce = true, rootUrl = "") { - const result = decorators_SerializationHelper.Clone(() => new standardMaterial_StandardMaterial(name, this.getScene()), this, { cloneTexturesOnlyOnce }); - result.name = name; - result.id = name; - this.stencil.copyTo(result.stencil); - this._clonePlugins(result, rootUrl); - return result; - } - /** - * Creates a standard material from parsed material data - * @param source defines the JSON representation of the material - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a new standard material - */ - static Parse(source, scene, rootUrl) { - const material = decorators_SerializationHelper.Parse(() => new standardMaterial_StandardMaterial(source.name, scene), source, scene, rootUrl); - if (source.stencil) { - material.stencil.parse(source.stencil, scene, rootUrl); - } - material_Material._parsePlugins(source, material, scene, rootUrl); - return material; - } - // Flags used to enable or disable a type of texture for all Standard Materials - /** - * Are diffuse textures enabled in the application. - */ - static get DiffuseTextureEnabled() { - return MaterialFlags.DiffuseTextureEnabled; - } - static set DiffuseTextureEnabled(value) { - MaterialFlags.DiffuseTextureEnabled = value; - } - /** - * Are detail textures enabled in the application. - */ - static get DetailTextureEnabled() { - return MaterialFlags.DetailTextureEnabled; - } - static set DetailTextureEnabled(value) { - MaterialFlags.DetailTextureEnabled = value; - } - /** - * Are ambient textures enabled in the application. - */ - static get AmbientTextureEnabled() { - return MaterialFlags.AmbientTextureEnabled; - } - static set AmbientTextureEnabled(value) { - MaterialFlags.AmbientTextureEnabled = value; - } - /** - * Are opacity textures enabled in the application. - */ - static get OpacityTextureEnabled() { - return MaterialFlags.OpacityTextureEnabled; - } - static set OpacityTextureEnabled(value) { - MaterialFlags.OpacityTextureEnabled = value; - } - /** - * Are reflection textures enabled in the application. - */ - static get ReflectionTextureEnabled() { - return MaterialFlags.ReflectionTextureEnabled; - } - static set ReflectionTextureEnabled(value) { - MaterialFlags.ReflectionTextureEnabled = value; - } - /** - * Are emissive textures enabled in the application. - */ - static get EmissiveTextureEnabled() { - return MaterialFlags.EmissiveTextureEnabled; - } - static set EmissiveTextureEnabled(value) { - MaterialFlags.EmissiveTextureEnabled = value; - } - /** - * Are specular textures enabled in the application. - */ - static get SpecularTextureEnabled() { - return MaterialFlags.SpecularTextureEnabled; - } - static set SpecularTextureEnabled(value) { - MaterialFlags.SpecularTextureEnabled = value; - } - /** - * Are bump textures enabled in the application. - */ - static get BumpTextureEnabled() { - return MaterialFlags.BumpTextureEnabled; - } - static set BumpTextureEnabled(value) { - MaterialFlags.BumpTextureEnabled = value; - } - /** - * Are lightmap textures enabled in the application. - */ - static get LightmapTextureEnabled() { - return MaterialFlags.LightmapTextureEnabled; - } - static set LightmapTextureEnabled(value) { - MaterialFlags.LightmapTextureEnabled = value; - } - /** - * Are refraction textures enabled in the application. - */ - static get RefractionTextureEnabled() { - return MaterialFlags.RefractionTextureEnabled; - } - static set RefractionTextureEnabled(value) { - MaterialFlags.RefractionTextureEnabled = value; - } - /** - * Are color grading textures enabled in the application. - */ - static get ColorGradingTextureEnabled() { - return MaterialFlags.ColorGradingTextureEnabled; - } - static set ColorGradingTextureEnabled(value) { - MaterialFlags.ColorGradingTextureEnabled = value; - } - /** - * Are fresnels enabled in the application. - */ - static get FresnelEnabled() { - return MaterialFlags.FresnelEnabled; - } - static set FresnelEnabled(value) { - MaterialFlags.FresnelEnabled = value; - } -} -__decorate([ - serializeAsTexture("diffuseTexture") -], standardMaterial_StandardMaterial.prototype, "_diffuseTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") -], standardMaterial_StandardMaterial.prototype, "diffuseTexture", void 0); -__decorate([ - serializeAsTexture("ambientTexture") -], standardMaterial_StandardMaterial.prototype, "_ambientTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "ambientTexture", void 0); -__decorate([ - serializeAsTexture("opacityTexture") -], standardMaterial_StandardMaterial.prototype, "_opacityTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") -], standardMaterial_StandardMaterial.prototype, "opacityTexture", void 0); -__decorate([ - serializeAsTexture("reflectionTexture") -], standardMaterial_StandardMaterial.prototype, "_reflectionTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "reflectionTexture", void 0); -__decorate([ - serializeAsTexture("emissiveTexture") -], standardMaterial_StandardMaterial.prototype, "_emissiveTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "emissiveTexture", void 0); -__decorate([ - serializeAsTexture("specularTexture") -], standardMaterial_StandardMaterial.prototype, "_specularTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "specularTexture", void 0); -__decorate([ - serializeAsTexture("bumpTexture") -], standardMaterial_StandardMaterial.prototype, "_bumpTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "bumpTexture", void 0); -__decorate([ - serializeAsTexture("lightmapTexture") -], standardMaterial_StandardMaterial.prototype, "_lightmapTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "lightmapTexture", void 0); -__decorate([ - serializeAsTexture("refractionTexture") -], standardMaterial_StandardMaterial.prototype, "_refractionTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "refractionTexture", void 0); -__decorate([ - serializeAsColor3("ambient") -], standardMaterial_StandardMaterial.prototype, "ambientColor", void 0); -__decorate([ - serializeAsColor3("diffuse") -], standardMaterial_StandardMaterial.prototype, "diffuseColor", void 0); -__decorate([ - serializeAsColor3("specular") -], standardMaterial_StandardMaterial.prototype, "specularColor", void 0); -__decorate([ - serializeAsColor3("emissive") -], standardMaterial_StandardMaterial.prototype, "emissiveColor", void 0); -__decorate([ - serialize() -], standardMaterial_StandardMaterial.prototype, "specularPower", void 0); -__decorate([ - serialize("useAlphaFromDiffuseTexture") -], standardMaterial_StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") -], standardMaterial_StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0); -__decorate([ - serialize("useEmissiveAsIllumination") -], standardMaterial_StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "useEmissiveAsIllumination", void 0); -__decorate([ - serialize("linkEmissiveWithDiffuse") -], standardMaterial_StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0); -__decorate([ - serialize("useSpecularOverAlpha") -], standardMaterial_StandardMaterial.prototype, "_useSpecularOverAlpha", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "useSpecularOverAlpha", void 0); -__decorate([ - serialize("useReflectionOverAlpha") -], standardMaterial_StandardMaterial.prototype, "_useReflectionOverAlpha", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "useReflectionOverAlpha", void 0); -__decorate([ - serialize("disableLighting") -], standardMaterial_StandardMaterial.prototype, "_disableLighting", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsLightsDirty") -], standardMaterial_StandardMaterial.prototype, "disableLighting", void 0); -__decorate([ - serialize("useObjectSpaceNormalMap") -], standardMaterial_StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0); -__decorate([ - serialize("useParallax") -], standardMaterial_StandardMaterial.prototype, "_useParallax", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "useParallax", void 0); -__decorate([ - serialize("useParallaxOcclusion") -], standardMaterial_StandardMaterial.prototype, "_useParallaxOcclusion", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "useParallaxOcclusion", void 0); -__decorate([ - serialize() -], standardMaterial_StandardMaterial.prototype, "parallaxScaleBias", void 0); -__decorate([ - serialize("roughness") -], standardMaterial_StandardMaterial.prototype, "_roughness", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "roughness", void 0); -__decorate([ - serialize() -], standardMaterial_StandardMaterial.prototype, "indexOfRefraction", void 0); -__decorate([ - serialize() -], standardMaterial_StandardMaterial.prototype, "invertRefractionY", void 0); -__decorate([ - serialize() -], standardMaterial_StandardMaterial.prototype, "alphaCutOff", void 0); -__decorate([ - serialize("useLightmapAsShadowmap") -], standardMaterial_StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "useLightmapAsShadowmap", void 0); -__decorate([ - serializeAsFresnelParameters("diffuseFresnelParameters") -], standardMaterial_StandardMaterial.prototype, "_diffuseFresnelParameters", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsFresnelDirty") -], standardMaterial_StandardMaterial.prototype, "diffuseFresnelParameters", void 0); -__decorate([ - serializeAsFresnelParameters("opacityFresnelParameters") -], standardMaterial_StandardMaterial.prototype, "_opacityFresnelParameters", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty") -], standardMaterial_StandardMaterial.prototype, "opacityFresnelParameters", void 0); -__decorate([ - serializeAsFresnelParameters("reflectionFresnelParameters") -], standardMaterial_StandardMaterial.prototype, "_reflectionFresnelParameters", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsFresnelDirty") -], standardMaterial_StandardMaterial.prototype, "reflectionFresnelParameters", void 0); -__decorate([ - serializeAsFresnelParameters("refractionFresnelParameters") -], standardMaterial_StandardMaterial.prototype, "_refractionFresnelParameters", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsFresnelDirty") -], standardMaterial_StandardMaterial.prototype, "refractionFresnelParameters", void 0); -__decorate([ - serializeAsFresnelParameters("emissiveFresnelParameters") -], standardMaterial_StandardMaterial.prototype, "_emissiveFresnelParameters", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsFresnelDirty") -], standardMaterial_StandardMaterial.prototype, "emissiveFresnelParameters", void 0); -__decorate([ - serialize("useReflectionFresnelFromSpecular") -], standardMaterial_StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsFresnelDirty") -], standardMaterial_StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0); -__decorate([ - serialize("useGlossinessFromSpecularMapAlpha") -], standardMaterial_StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0); -__decorate([ - serialize("maxSimultaneousLights") -], standardMaterial_StandardMaterial.prototype, "_maxSimultaneousLights", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsLightsDirty") -], standardMaterial_StandardMaterial.prototype, "maxSimultaneousLights", void 0); -__decorate([ - serialize("invertNormalMapX") -], standardMaterial_StandardMaterial.prototype, "_invertNormalMapX", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "invertNormalMapX", void 0); -__decorate([ - serialize("invertNormalMapY") -], standardMaterial_StandardMaterial.prototype, "_invertNormalMapY", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "invertNormalMapY", void 0); -__decorate([ - serialize("twoSidedLighting") -], standardMaterial_StandardMaterial.prototype, "_twoSidedLighting", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], standardMaterial_StandardMaterial.prototype, "twoSidedLighting", void 0); -__decorate([ - serialize("applyDecalMapAfterDetailMap") -], standardMaterial_StandardMaterial.prototype, "_applyDecalMapAfterDetailMap", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsMiscDirty") -], standardMaterial_StandardMaterial.prototype, "applyDecalMapAfterDetailMap", void 0); -__decorate([ - serialize() -], standardMaterial_StandardMaterial.prototype, "useLogarithmicDepth", null); -RegisterClass("BABYLON.StandardMaterial", standardMaterial_StandardMaterial); -scene_Scene.DefaultMaterialFactory = (scene) => { - return new standardMaterial_StandardMaterial("default material", scene); -}; -//# sourceMappingURL=standardMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicTexture.js - - -ThinEngine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) { - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Dynamic); - texture.baseWidth = width; - texture.baseHeight = height; - if (generateMipMaps) { - width = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(width, this._caps.maxTextureSize) : width; - height = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(height, this._caps.maxTextureSize) : height; - } - // this.resetTextureCache(); - texture.width = width; - texture.height = height; - texture.isReady = false; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - this.updateTextureSamplingMode(samplingMode, texture); - this._internalTexturesCache.push(texture); - return texture; -}; -ThinEngine.prototype.updateDynamicTexture = function (texture, source, invertY, premulAlpha = false, format, forceBindTexture = false, -// eslint-disable-next-line @typescript-eslint/no-unused-vars -allowGPUOptimization = false) { - if (!texture) { - return; - } - const gl = this._gl; - const target = gl.TEXTURE_2D; - const wasPreviouslyBound = this._bindTextureDirectly(target, texture, true, forceBindTexture); - this._unpackFlipY(invertY === undefined ? texture.invertY : invertY); - if (premulAlpha) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); - } - const textureType = this._getWebGLTextureType(texture.type); - const glformat = this._getInternalFormat(format ? format : texture.format); - const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, glformat); - gl.texImage2D(target, 0, internalFormat, glformat, textureType, source); - if (texture.generateMipMaps) { - gl.generateMipmap(target); - } - if (!wasPreviouslyBound) { - this._bindTextureDirectly(target, null); - } - if (premulAlpha) { - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); - } - texture.isReady = true; -}; -//# sourceMappingURL=engine.dynamicTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/dynamicTexture.js - - - - -/** - * A class extending Texture allowing drawing on a texture - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/dynamicTexture - */ -class dynamicTexture_DynamicTexture extends texture_Texture { - /** - * Creates a DynamicTexture - * @param name defines the name of the texture - * @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 - * @param scene defines the scene where you want the texture - * @param generateMipMaps defines the use of MinMaps or not (default is false) - * @param samplingMode defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE) - * @param format defines the texture format to use (default is Engine.TEXTUREFORMAT_RGBA) - * @param invertY defines if the texture needs to be inverted on the y axis during loading - */ - constructor(name, options, scene = null, generateMipMaps = false, samplingMode = 3, format = 5, invertY) { - super(null, scene, !generateMipMaps, invertY, samplingMode, undefined, undefined, undefined, undefined, format); - this.name = name; - this.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._generateMipMaps = generateMipMaps; - const engine = this._getEngine(); - if (!engine) { - return; - } - if (options.getContext) { - this._canvas = options; - this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode); - } - else { - this._canvas = engine.createCanvas(1, 1); - if (options.width || options.width === 0) { - this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode); - } - else { - this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode); - } - } - const textureSize = this.getSize(); - if (this._canvas.width !== textureSize.width) { - this._canvas.width = textureSize.width; - } - if (this._canvas.height !== textureSize.height) { - this._canvas.height = textureSize.height; - } - this._context = this._canvas.getContext("2d"); - } - /** - * Get the current class name of the texture useful for serialization or dynamic coding. - * @returns "DynamicTexture" - */ - getClassName() { - return "DynamicTexture"; - } - /** - * Gets the current state of canRescale - */ - get canRescale() { - return true; - } - _recreate(textureSize) { - this._canvas.width = textureSize.width; - this._canvas.height = textureSize.height; - this.releaseInternalTexture(); - this._texture = this._getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this.samplingMode); - } - /** - * Scales the texture - * @param ratio the scale factor to apply to both width and height - */ - scale(ratio) { - const textureSize = this.getSize(); - textureSize.width *= ratio; - textureSize.height *= ratio; - this._recreate(textureSize); - } - /** - * Resizes the texture - * @param width the new width - * @param height the new height - */ - scaleTo(width, height) { - const textureSize = this.getSize(); - textureSize.width = width; - textureSize.height = height; - this._recreate(textureSize); - } - /** - * Gets the context of the canvas used by the texture - * @returns the canvas context of the dynamic texture - */ - getContext() { - return this._context; - } - /** - * Clears the texture - */ - clear() { - const size = this.getSize(); - this._context.fillRect(0, 0, size.width, size.height); - } - /** - * Updates the texture - * @param invertY defines the direction for the Y axis (default is true - y increases downwards) - * @param premulAlpha defines if alpha is stored as premultiplied (default is false) - * @param allowGPUOptimization true to allow some specific GPU optimizations (subject to engine feature "allowGPUOptimizationsForGUI" being true) - */ - update(invertY, premulAlpha = false, allowGPUOptimization = false) { - this._getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined, undefined, allowGPUOptimization); - } - /** - * Draws text onto the texture - * @param text defines the text to be drawn - * @param x defines the placement of the text from the left - * @param y defines the placement of the text from the top when invertY is true and from the bottom when false - * @param font defines the font to be used with font-style, font-size, font-name - * @param color defines the color used for the text - * @param clearColor defines the color for the canvas, use null to not overwrite canvas - * @param invertY defines the direction for the Y axis (default is true - y increases downwards) - * @param update defines whether texture is immediately update (default is true) - */ - drawText(text, x, y, font, color, clearColor, invertY, update = true) { - const size = this.getSize(); - if (clearColor) { - this._context.fillStyle = clearColor; - this._context.fillRect(0, 0, size.width, size.height); - } - this._context.font = font; - if (x === null || x === undefined) { - const textSize = this._context.measureText(text); - x = (size.width - textSize.width) / 2; - } - if (y === null || y === undefined) { - const fontSize = parseInt(font.replace(/\D/g, "")); - y = size.height / 2 + fontSize / 3.65; - } - this._context.fillStyle = color || ""; - this._context.fillText(text, x, y); - if (update) { - this.update(invertY); - } - } - /** - * Clones the texture - * @returns the clone of the texture. - */ - clone() { - const scene = this.getScene(); - if (!scene) { - return this; - } - const textureSize = this.getSize(); - const newTexture = new dynamicTexture_DynamicTexture(this.name, textureSize, scene, this._generateMipMaps); - // Base texture - newTexture.hasAlpha = this.hasAlpha; - newTexture.level = this.level; - // Dynamic Texture - newTexture.wrapU = this.wrapU; - newTexture.wrapV = this.wrapV; - return newTexture; - } - /** - * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized - * @returns a serialized dynamic texture object - */ - serialize() { - const scene = this.getScene(); - if (scene && !scene.isReady()) { - logger_Logger.Warn("The scene must be ready before serializing the dynamic texture"); - } - const serializationObject = super.serialize(); - if (dynamicTexture_DynamicTexture._IsCanvasElement(this._canvas)) { - serializationObject.base64String = this._canvas.toDataURL(); - } - serializationObject.invertY = this._invertY; - serializationObject.samplingMode = this.samplingMode; - return serializationObject; - } - static _IsCanvasElement(canvas) { - return canvas.toDataURL !== undefined; - } - /** @internal */ - _rebuild() { - this.update(); - } -} -//# sourceMappingURL=dynamicTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/imageProcessing.fragment.js -// Do not edit. - - - - -const imageProcessing_fragment_name = "imageProcessingPixelShader"; -const imageProcessing_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler; -#include<imageProcessingDeclaration> -#include<helperFunctions> -#include<imageProcessingFunctions> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 result=texture2D(textureSampler,vUV); -#ifdef IMAGEPROCESSING -#ifndef FROMLINEARSPACE -result.rgb=toLinearSpace(result.rgb); -#endif -result=applyImageProcessing(result); -#else -#ifdef FROMLINEARSPACE -result=applyImageProcessing(result); -#endif -#endif -gl_FragColor=result;}`; -// Sideeffect -ShaderStore.ShadersStore[imageProcessing_fragment_name] = imageProcessing_fragment_shader; -/** @internal */ -const imageProcessingPixelShader = { name: imageProcessing_fragment_name, shader: imageProcessing_fragment_shader }; -//# sourceMappingURL=imageProcessing.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/imageProcessingPostProcess.js - - - - - - - - -/** - * ImageProcessingPostProcess - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#imageprocessing - */ -class ImageProcessingPostProcess extends postProcess_PostProcess { - /** - * Gets the image processing configuration used either in this material. - */ - get imageProcessingConfiguration() { - return this._imageProcessingConfiguration; - } - /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ - set imageProcessingConfiguration(value) { - // We are almost sure it is applied by post process as - // We are in the post process :-) - value.applyByPostProcess = true; - this._attachImageProcessingConfiguration(value); - } - /** - * Attaches a new image processing configuration to the PBR Material. - * @param configuration - * @param doNotBuild - */ - _attachImageProcessingConfiguration(configuration, doNotBuild = false) { - if (configuration === this._imageProcessingConfiguration) { - return; - } - // Detaches observer. - if (this._imageProcessingConfiguration && this._imageProcessingObserver) { - this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); - } - // Pick the scene configuration if needed. - if (!configuration) { - let scene = null; - const engine = this.getEngine(); - const camera = this.getCamera(); - if (camera) { - scene = camera.getScene(); - } - else if (engine && engine.scenes) { - const scenes = engine.scenes; - scene = scenes[scenes.length - 1]; - } - else { - scene = engineStore_EngineStore.LastCreatedScene; - } - if (scene) { - this._imageProcessingConfiguration = scene.imageProcessingConfiguration; - } - else { - this._imageProcessingConfiguration = new ImageProcessingConfiguration(); - } - } - else { - this._imageProcessingConfiguration = configuration; - } - // Attaches observer. - if (this._imageProcessingConfiguration) { - this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { - this._updateParameters(); - }); - } - // Ensure the effect will be rebuilt. - if (!doNotBuild) { - this._updateParameters(); - } - } - /** - * If the post process is supported. - */ - get isSupported() { - const effect = this.getEffect(); - return !effect || effect.isSupported; - } - /** - * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true . - */ - get colorCurves() { - return this.imageProcessingConfiguration.colorCurves; - } - /** - * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true . - */ - set colorCurves(value) { - this.imageProcessingConfiguration.colorCurves = value; - } - /** - * Gets whether the color curves effect is enabled. - */ - get colorCurvesEnabled() { - return this.imageProcessingConfiguration.colorCurvesEnabled; - } - /** - * Sets whether the color curves effect is enabled. - */ - set colorCurvesEnabled(value) { - this.imageProcessingConfiguration.colorCurvesEnabled = value; - } - /** - * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. - */ - get colorGradingTexture() { - return this.imageProcessingConfiguration.colorGradingTexture; - } - /** - * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. - */ - set colorGradingTexture(value) { - this.imageProcessingConfiguration.colorGradingTexture = value; - } - /** - * Gets whether the color grading effect is enabled. - */ - get colorGradingEnabled() { - return this.imageProcessingConfiguration.colorGradingEnabled; - } - /** - * Gets whether the color grading effect is enabled. - */ - set colorGradingEnabled(value) { - this.imageProcessingConfiguration.colorGradingEnabled = value; - } - /** - * Gets exposure used in the effect. - */ - get exposure() { - return this.imageProcessingConfiguration.exposure; - } - /** - * Sets exposure used in the effect. - */ - set exposure(value) { - this.imageProcessingConfiguration.exposure = value; - } - /** - * Gets whether tonemapping is enabled or not. - */ - get toneMappingEnabled() { - return this._imageProcessingConfiguration.toneMappingEnabled; - } - /** - * Sets whether tonemapping is enabled or not - */ - set toneMappingEnabled(value) { - this._imageProcessingConfiguration.toneMappingEnabled = value; - } - /** - * Gets the type of tone mapping effect. - */ - get toneMappingType() { - return this._imageProcessingConfiguration.toneMappingType; - } - /** - * Sets the type of tone mapping effect. - */ - set toneMappingType(value) { - this._imageProcessingConfiguration.toneMappingType = value; - } - /** - * Gets contrast used in the effect. - */ - get contrast() { - return this.imageProcessingConfiguration.contrast; - } - /** - * Sets contrast used in the effect. - */ - set contrast(value) { - this.imageProcessingConfiguration.contrast = value; - } - /** - * Gets Vignette stretch size. - */ - get vignetteStretch() { - return this.imageProcessingConfiguration.vignetteStretch; - } - /** - * Sets Vignette stretch size. - */ - set vignetteStretch(value) { - this.imageProcessingConfiguration.vignetteStretch = value; - } - /** - * Gets Vignette center X Offset. - * @deprecated use vignetteCenterX instead - */ - get vignetteCentreX() { - return this.imageProcessingConfiguration.vignetteCenterX; - } - /** - * Sets Vignette center X Offset. - * @deprecated use vignetteCenterX instead - */ - set vignetteCentreX(value) { - this.imageProcessingConfiguration.vignetteCenterX = value; - } - /** - * Gets Vignette center Y Offset. - * @deprecated use vignetteCenterY instead - */ - get vignetteCentreY() { - return this.imageProcessingConfiguration.vignetteCenterY; - } - /** - * Sets Vignette center Y Offset. - * @deprecated use vignetteCenterY instead - */ - set vignetteCentreY(value) { - this.imageProcessingConfiguration.vignetteCenterY = value; - } - /** - * Vignette center Y Offset. - */ - get vignetteCenterY() { - return this.imageProcessingConfiguration.vignetteCenterY; - } - set vignetteCenterY(value) { - this.imageProcessingConfiguration.vignetteCenterY = value; - } - /** - * Vignette center X Offset. - */ - get vignetteCenterX() { - return this.imageProcessingConfiguration.vignetteCenterX; - } - set vignetteCenterX(value) { - this.imageProcessingConfiguration.vignetteCenterX = value; - } - /** - * Gets Vignette weight or intensity of the vignette effect. - */ - get vignetteWeight() { - return this.imageProcessingConfiguration.vignetteWeight; - } - /** - * Sets Vignette weight or intensity of the vignette effect. - */ - set vignetteWeight(value) { - this.imageProcessingConfiguration.vignetteWeight = value; - } - /** - * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) - * if vignetteEnabled is set to true. - */ - get vignetteColor() { - return this.imageProcessingConfiguration.vignetteColor; - } - /** - * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) - * if vignetteEnabled is set to true. - */ - set vignetteColor(value) { - this.imageProcessingConfiguration.vignetteColor = value; - } - /** - * Gets Camera field of view used by the Vignette effect. - */ - get vignetteCameraFov() { - return this.imageProcessingConfiguration.vignetteCameraFov; - } - /** - * Sets Camera field of view used by the Vignette effect. - */ - set vignetteCameraFov(value) { - this.imageProcessingConfiguration.vignetteCameraFov = value; - } - /** - * Gets the vignette blend mode allowing different kind of effect. - */ - get vignetteBlendMode() { - return this.imageProcessingConfiguration.vignetteBlendMode; - } - /** - * Sets the vignette blend mode allowing different kind of effect. - */ - set vignetteBlendMode(value) { - this.imageProcessingConfiguration.vignetteBlendMode = value; - } - /** - * Gets whether the vignette effect is enabled. - */ - get vignetteEnabled() { - return this.imageProcessingConfiguration.vignetteEnabled; - } - /** - * Sets whether the vignette effect is enabled. - */ - set vignetteEnabled(value) { - this.imageProcessingConfiguration.vignetteEnabled = value; - } - /** - * Gets intensity of the dithering effect. - */ - get ditheringIntensity() { - return this.imageProcessingConfiguration.ditheringIntensity; - } - /** - * Sets intensity of the dithering effect. - */ - set ditheringIntensity(value) { - this.imageProcessingConfiguration.ditheringIntensity = value; - } - /** - * Gets whether the dithering effect is enabled. - */ - get ditheringEnabled() { - return this.imageProcessingConfiguration.ditheringEnabled; - } - /** - * Sets whether the dithering effect is enabled. - */ - set ditheringEnabled(value) { - this.imageProcessingConfiguration.ditheringEnabled = value; - } - /** - * Gets whether the input of the processing is in Gamma or Linear Space. - */ - get fromLinearSpace() { - return this._fromLinearSpace; - } - /** - * Sets whether the input of the processing is in Gamma or Linear Space. - */ - set fromLinearSpace(value) { - if (this._fromLinearSpace === value) { - return; - } - this._fromLinearSpace = value; - this._updateParameters(); - } - constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, imageProcessingConfiguration) { - super(name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true); - this._fromLinearSpace = true; - /** - * Defines cache preventing GC. - */ - this._defines = { - IMAGEPROCESSING: false, - VIGNETTE: false, - VIGNETTEBLENDMODEMULTIPLY: false, - VIGNETTEBLENDMODEOPAQUE: false, - TONEMAPPING: false, - TONEMAPPING_ACES: false, - CONTRAST: false, - COLORCURVES: false, - COLORGRADING: false, - COLORGRADING3D: false, - FROMLINEARSPACE: false, - SAMPLER3DGREENDEPTH: false, - SAMPLER3DBGRMAP: false, - DITHER: false, - IMAGEPROCESSINGPOSTPROCESS: false, - EXPOSURE: false, - SKIPFINALCOLORCLAMP: false, - }; - // Setup the configuration as forced by the constructor. This would then not force the - // scene materials output in linear space and let untouched the default forward pass. - if (imageProcessingConfiguration) { - imageProcessingConfiguration.applyByPostProcess = true; - this._attachImageProcessingConfiguration(imageProcessingConfiguration, true); - // This will cause the shader to be compiled - this._updateParameters(); - } - // Setup the default processing configuration to the scene. - else { - this._attachImageProcessingConfiguration(null, true); - this.imageProcessingConfiguration.applyByPostProcess = true; - } - this.onApply = (effect) => { - this.imageProcessingConfiguration.bind(effect, this.aspectRatio); - }; - } - /** - * "ImageProcessingPostProcess" - * @returns "ImageProcessingPostProcess" - */ - getClassName() { - return "ImageProcessingPostProcess"; - } - /** - * @internal - */ - _updateParameters() { - this._defines.FROMLINEARSPACE = this._fromLinearSpace; - this.imageProcessingConfiguration.prepareDefines(this._defines, true); - let defines = ""; - for (const define in this._defines) { - if (this._defines[define]) { - defines += `#define ${define};\n`; - } - } - const samplers = ["textureSampler"]; - const uniforms = ["scale"]; - if (ImageProcessingConfiguration) { - ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines); - ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines); - } - this.updateEffect(defines, uniforms, samplers); - } - dispose(camera) { - super.dispose(camera); - if (this._imageProcessingConfiguration && this._imageProcessingObserver) { - this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); - } - if (this._imageProcessingConfiguration) { - this.imageProcessingConfiguration.applyByPostProcess = false; - } - } -} -__decorate([ - serialize() -], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0); -//# sourceMappingURL=imageProcessingPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRLayerWrapper.js -/** - * Wrapper over subclasses of XRLayer. - * @internal - */ -class WebXRLayerWrapper { - /** - * Check if fixed foveation is supported on this device - */ - get isFixedFoveationSupported() { - return this.layerType == "XRWebGLLayer" && typeof this.layer.fixedFoveation == "number"; - } - /** - * Get the fixed foveation currently set, as specified by the webxr specs - * If this returns null, then fixed foveation is not supported - */ - get fixedFoveation() { - if (this.isFixedFoveationSupported) { - return this.layer.fixedFoveation; - } - return null; - } - /** - * Set the fixed foveation to the specified value, as specified by the webxr specs - * This value will be normalized to be between 0 and 1, 1 being max foveation, 0 being no foveation - */ - set fixedFoveation(value) { - if (this.isFixedFoveationSupported) { - const val = Math.max(0, Math.min(1, value || 0)); - this.layer.fixedFoveation = val; - } - } - constructor( - /** The width of the layer's framebuffer. */ - getWidth, - /** The height of the layer's framebuffer. */ - getHeight, - /** The XR layer that this WebXRLayerWrapper wraps. */ - layer, - /** The type of XR layer that is being wrapped. */ - layerType, - /** Create a render target provider for the wrapped layer. */ - createRenderTargetTextureProvider) { - this.getWidth = getWidth; - this.getHeight = getHeight; - this.layer = layer; - this.layerType = layerType; - this.createRenderTargetTextureProvider = createRenderTargetTextureProvider; - } -} -//# sourceMappingURL=webXRLayerWrapper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRRenderTargetTextureProvider.js - - - - -/** - * Provides render target textures and other important rendering information for a given XRLayer. - * @internal - */ -class WebXRLayerRenderTargetTextureProvider { - constructor(_scene, layerWrapper) { - this._scene = _scene; - this.layerWrapper = layerWrapper; - this._renderTargetTextures = new Array(); - this._engine = _scene.getEngine(); - } - _createInternalTexture(textureSize, texture) { - const internalTexture = new internalTexture_InternalTexture(this._engine, internalTexture_InternalTextureSource.Unknown, true); - internalTexture.width = textureSize.width; - internalTexture.height = textureSize.height; - internalTexture._hardwareTexture = new WebGLHardwareTexture(texture, this._engine._gl); - internalTexture.isReady = true; - return internalTexture; - } - _createRenderTargetTexture(width, height, framebuffer, colorTexture, depthStencilTexture, multiview) { - if (!this._engine) { - throw new Error("Engine is disposed"); - } - const textureSize = { width, height }; - // Create render target texture from the internal texture - const renderTargetTexture = multiview ? new MultiviewRenderTarget(this._scene, textureSize) : new renderTargetTexture_RenderTargetTexture("XR renderTargetTexture", textureSize, this._scene); - const renderTargetWrapper = renderTargetTexture.renderTarget; - renderTargetWrapper._samples = renderTargetTexture.samples; - // Set the framebuffer, make sure it works in all scenarios - emulator, no layers and layers - if (framebuffer || !colorTexture) { - renderTargetWrapper._framebuffer = framebuffer; - } - // Create internal texture - if (colorTexture) { - if (multiview) { - renderTargetWrapper._colorTextureArray = colorTexture; - } - else { - const internalTexture = this._createInternalTexture(textureSize, colorTexture); - renderTargetWrapper.setTexture(internalTexture, 0); - renderTargetTexture._texture = internalTexture; - } - } - if (depthStencilTexture) { - if (multiview) { - renderTargetWrapper._depthStencilTextureArray = depthStencilTexture; - } - else { - renderTargetWrapper._depthStencilTexture = this._createInternalTexture(textureSize, depthStencilTexture); - } - } - renderTargetTexture.disableRescaling(); - // Firefox reality fails if skipInitialClear is set to true, so make sure only modern XR implementations set it. - if (typeof XRWebGLBinding !== "undefined") { - // WebXR pre-clears textures - renderTargetTexture.skipInitialClear = true; - } - this._renderTargetTextures.push(renderTargetTexture); - return renderTargetTexture; - } - _destroyRenderTargetTexture(renderTargetTexture) { - this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(renderTargetTexture), 1); - renderTargetTexture.dispose(); - } - getFramebufferDimensions() { - return this._framebufferDimensions; - } - dispose() { - this._renderTargetTextures.forEach((rtt) => rtt.dispose()); - this._renderTargetTextures.length = 0; - } -} -//# sourceMappingURL=webXRRenderTargetTextureProvider.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRWebGLLayer.js - - -/** - * Wraps xr webgl layers. - * @internal - */ -class WebXRWebGLLayerWrapper extends WebXRLayerWrapper { - /** - * @param layer is the layer to be wrapped. - * @returns a new WebXRLayerWrapper wrapping the provided XRWebGLLayer. - */ - constructor(layer) { - super(() => layer.framebufferWidth, () => layer.framebufferHeight, layer, "XRWebGLLayer", (sessionManager) => new WebXRWebGLLayerRenderTargetTextureProvider(sessionManager.scene, this)); - this.layer = layer; - } -} -/** - * Provides render target textures and other important rendering information for a given XRWebGLLayer. - * @internal - */ -class WebXRWebGLLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider { - constructor(scene, layerWrapper) { - super(scene, layerWrapper); - this.layerWrapper = layerWrapper; - this._layer = layerWrapper.layer; - this._framebufferDimensions = { - framebufferWidth: this._layer.framebufferWidth, - framebufferHeight: this._layer.framebufferHeight, - }; - } - trySetViewportForView(viewport, view) { - const xrViewport = this._layer.getViewport(view); - if (!xrViewport) { - return false; - } - const framebufferWidth = this._framebufferDimensions.framebufferWidth; - const framebufferHeight = this._framebufferDimensions.framebufferHeight; - viewport.x = xrViewport.x / framebufferWidth; - viewport.y = xrViewport.y / framebufferHeight; - viewport.width = xrViewport.width / framebufferWidth; - viewport.height = xrViewport.height / framebufferHeight; - return true; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getRenderTargetTextureForEye(eye) { - const layerWidth = this._layer.framebufferWidth; - const layerHeight = this._layer.framebufferHeight; - const framebuffer = this._layer.framebuffer; - if (!this._rtt || - layerWidth !== this._framebufferDimensions.framebufferWidth || - layerHeight !== this._framebufferDimensions.framebufferHeight || - framebuffer !== this._framebuffer) { - this._rtt = this._createRenderTargetTexture(layerWidth, layerHeight, framebuffer); - this._framebufferDimensions.framebufferWidth = layerWidth; - this._framebufferDimensions.framebufferHeight = layerHeight; - this._framebuffer = framebuffer; - } - return this._rtt; - } - getRenderTargetTextureForView(view) { - return this.getRenderTargetTextureForEye(view.eye); - } -} -//# sourceMappingURL=webXRWebGLLayer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRManagedOutputCanvas.js - - - -/** - * Configuration object for WebXR output canvas - */ -class WebXRManagedOutputCanvasOptions { - /** - * Get the default values of the configuration object - * @param engine defines the engine to use (can be null) - * @returns default values of this configuration object - */ - static GetDefaults(engine) { - const defaults = new WebXRManagedOutputCanvasOptions(); - defaults.canvasOptions = { - antialias: true, - depth: true, - stencil: engine ? engine.isStencilEnable : true, - alpha: true, - framebufferScaleFactor: 1, - }; - defaults.newCanvasCssStyle = "position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;"; - return defaults; - } -} -/** - * Creates a canvas that is added/removed from the webpage when entering/exiting XR - */ -class WebXRManagedOutputCanvas { - /** - * Initializes the canvas to be added/removed upon entering/exiting xr - * @param _xrSessionManager The XR Session manager - * @param _options optional configuration for this canvas output. defaults will be used if not provided - */ - constructor(_xrSessionManager, _options = WebXRManagedOutputCanvasOptions.GetDefaults()) { - this._options = _options; - this._canvas = null; - this._engine = null; - /** - * xr layer for the canvas - */ - this.xrLayer = null; - this._xrLayerWrapper = null; - /** - * Observers registered here will be triggered when the xr layer was initialized - */ - this.onXRLayerInitObservable = new observable_Observable(); - this._engine = _xrSessionManager.scene.getEngine(); - this._engine.onDisposeObservable.addOnce(() => { - this._engine = null; - }); - if (!_options.canvasElement) { - const canvas = document.createElement("canvas"); - canvas.style.cssText = this._options.newCanvasCssStyle || "position:absolute; bottom:0px;right:0px;"; - this._setManagedOutputCanvas(canvas); - } - else { - this._setManagedOutputCanvas(_options.canvasElement); - } - _xrSessionManager.onXRSessionInit.add(() => { - this._addCanvas(); - }); - _xrSessionManager.onXRSessionEnded.add(() => { - this._removeCanvas(); - }); - } - /** - * Disposes of the object - */ - dispose() { - this._removeCanvas(); - this._setManagedOutputCanvas(null); - } - /** - * Initializes a XRWebGLLayer to be used as the session's baseLayer. - * @param xrSession xr session - * @returns a promise that will resolve once the XR Layer has been created - */ - async initializeXRLayerAsync(xrSession) { - const createLayer = () => { - this.xrLayer = new XRWebGLLayer(xrSession, this.canvasContext, this._options.canvasOptions); - this._xrLayerWrapper = new WebXRWebGLLayerWrapper(this.xrLayer); - this.onXRLayerInitObservable.notifyObservers(this.xrLayer); - return this.xrLayer; - }; - // support canvases without makeXRCompatible - if (!this.canvasContext.makeXRCompatible) { - return Promise.resolve(createLayer()); - } - return this.canvasContext - .makeXRCompatible() - .then( - // catch any error and continue. When using the emulator is throws this error for no apparent reason. - () => { }, () => { - // log the error, continue nonetheless! - tools_Tools.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly."); - }) - .then(() => { - return createLayer(); - }); - } - _addCanvas() { - if (this._canvas && this._engine && this._canvas !== this._engine.getRenderingCanvas()) { - document.body.appendChild(this._canvas); - } - if (this.xrLayer) { - this._setCanvasSize(true); - } - else { - this.onXRLayerInitObservable.addOnce(() => { - this._setCanvasSize(true); - }); - } - } - _removeCanvas() { - if (this._canvas && this._engine && document.body.contains(this._canvas) && this._canvas !== this._engine.getRenderingCanvas()) { - document.body.removeChild(this._canvas); - } - this._setCanvasSize(false); - } - _setCanvasSize(init = true, xrLayer = this._xrLayerWrapper) { - if (!this._canvas || !this._engine) { - return; - } - if (init) { - if (xrLayer) { - if (this._canvas !== this._engine.getRenderingCanvas()) { - this._canvas.style.width = xrLayer.getWidth() + "px"; - this._canvas.style.height = xrLayer.getHeight() + "px"; - } - else { - this._engine.setSize(xrLayer.getWidth(), xrLayer.getHeight()); - } - } - } - else { - if (this._originalCanvasSize) { - if (this._canvas !== this._engine.getRenderingCanvas()) { - this._canvas.style.width = this._originalCanvasSize.width + "px"; - this._canvas.style.height = this._originalCanvasSize.height + "px"; - } - else { - this._engine.setSize(this._originalCanvasSize.width, this._originalCanvasSize.height); - } - } - } - } - _setManagedOutputCanvas(canvas) { - this._removeCanvas(); - if (!canvas) { - this._canvas = null; - this.canvasContext = null; - } - else { - this._originalCanvasSize = { - width: canvas.offsetWidth, - height: canvas.offsetHeight, - }; - this._canvas = canvas; - this.canvasContext = this._canvas.getContext("webgl2"); - if (!this.canvasContext) { - this.canvasContext = this._canvas.getContext("webgl"); - } - } - } -} -//# sourceMappingURL=webXRManagedOutputCanvas.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/native/nativeXRRenderTarget.js - - -/** - * Wraps XRWebGLLayer's created by Babylon Native. - * @internal - */ -class NativeXRLayerWrapper extends WebXRLayerWrapper { - constructor(layer) { - super(() => layer.framebufferWidth, () => layer.framebufferHeight, layer, "XRWebGLLayer", (sessionManager) => new NativeXRLayerRenderTargetTextureProvider(sessionManager, this)); - this.layer = layer; - } -} -/** - * Provides render target textures for layers created by Babylon Native. - * @internal - */ -class NativeXRLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider { - constructor(sessionManager, layerWrapper) { - super(sessionManager.scene, layerWrapper); - this.layerWrapper = layerWrapper; - this._nativeRTTProvider = navigator.xr.getNativeRenderTargetProvider(sessionManager.session, this._createRenderTargetTexture.bind(this), this._destroyRenderTargetTexture.bind(this)); - this._nativeLayer = layerWrapper.layer; - } - trySetViewportForView(viewport) { - viewport.x = 0; - viewport.y = 0; - viewport.width = 1; - viewport.height = 1; - return true; - } - getRenderTargetTextureForEye(eye) { - // TODO (rgerd): Update the contract on the BabylonNative side to call this "getRenderTargetTextureForEye" - return this._nativeRTTProvider.getRenderTargetForEye(eye); - } - getRenderTargetTextureForView(view) { - return this._nativeRTTProvider.getRenderTargetForEye(view.eye); - } - getFramebufferDimensions() { - return { - framebufferWidth: this._nativeLayer.framebufferWidth, - framebufferHeight: this._nativeLayer.framebufferHeight, - }; - } -} -/** - * Creates the xr layer that will be used as the xr session's base layer. - * @internal - */ -class NativeXRRenderTarget { - constructor(_xrSessionManager) { - this._nativeRenderTarget = navigator.xr.getWebXRRenderTarget(_xrSessionManager.scene.getEngine()); - } - async initializeXRLayerAsync(xrSession) { - await this._nativeRenderTarget.initializeXRLayerAsync(xrSession); - this.xrLayer = this._nativeRenderTarget.xrLayer; - return this.xrLayer; - } - dispose() { - /* empty */ - } -} -//# sourceMappingURL=nativeXRRenderTarget.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRSessionManager.js - - - - - -/** - * Manages an XRSession to work with Babylon's engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRSessionManagers - */ -class WebXRSessionManager { - /** - * Constructs a WebXRSessionManager, this must be initialized within a user action before usage - * @param scene The scene which the session should be created for - */ - constructor( - /** The scene which the session should be created for */ - scene) { - this.scene = scene; - /** WebXR timestamp updated every frame */ - this.currentTimestamp = -1; - /** - * Used just in case of a failure to initialize an immersive session. - * The viewer reference space is compensated using this height, creating a kind of "viewer-floor" reference space - */ - this.defaultHeightCompensation = 1.7; - /** - * Fires every time a new xrFrame arrives which can be used to update the camera - */ - this.onXRFrameObservable = new observable_Observable(); - /** - * Fires when the reference space changed - */ - this.onXRReferenceSpaceChanged = new observable_Observable(); - /** - * Fires when the xr session is ended either by the device or manually done - */ - this.onXRSessionEnded = new observable_Observable(); - /** - * Fires when the xr session is initialized: right after requestSession was called and returned with a successful result - */ - this.onXRSessionInit = new observable_Observable(); - /** - * Are we currently in the XR loop? - */ - this.inXRFrameLoop = false; - /** - * Are we in an XR session? - */ - this.inXRSession = false; - this._engine = scene.getEngine(); - this._onEngineDisposedObserver = this._engine.onDisposeObservable.addOnce(() => { - this._engine = null; - }); - scene.onDisposeObservable.addOnce(() => { - this.dispose(); - }); - } - /** - * The current reference space used in this session. This reference space can constantly change! - * It is mainly used to offset the camera's position. - */ - get referenceSpace() { - return this._referenceSpace; - } - /** - * Set a new reference space and triggers the observable - */ - set referenceSpace(newReferenceSpace) { - this._referenceSpace = newReferenceSpace; - this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace); - } - /** - * The mode for the managed XR session - */ - get sessionMode() { - return this._sessionMode; - } - /** - * Disposes of the session manager - * This should be called explicitly by the dev, if required. - */ - dispose() { - var _a; - // disposing without leaving XR? Exit XR first - if (this.inXRSession) { - this.exitXRAsync(); - } - this.onXRFrameObservable.clear(); - this.onXRSessionEnded.clear(); - this.onXRReferenceSpaceChanged.clear(); - this.onXRSessionInit.clear(); - (_a = this._engine) === null || _a === void 0 ? void 0 : _a.onDisposeObservable.remove(this._onEngineDisposedObserver); - this._engine = null; - } - /** - * Stops the xrSession and restores the render loop - * @returns Promise which resolves after it exits XR - */ - exitXRAsync() { - if (this.session && this.inXRSession) { - this.inXRSession = false; - return this.session.end().catch(() => { - logger_Logger.Warn("Could not end XR session."); - }); - } - return Promise.resolve(); - } - /** - * Attempts to set the framebuffer-size-normalized viewport to be rendered this frame for this view. - * In the event of a failure, the supplied viewport is not updated. - * @param viewport the viewport to which the view will be rendered - * @param view the view for which to set the viewport - * @returns whether the operation was successful - */ - trySetViewportForView(viewport, view) { - var _a; - return ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.trySetViewportForView(viewport, view)) || false; - } - /** - * Gets the correct render target texture to be rendered this frame for this eye - * @param eye the eye for which to get the render target - * @returns the render target for the specified eye or null if not available - */ - getRenderTargetTextureForEye(eye) { - var _a; - return ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getRenderTargetTextureForEye(eye)) || null; - } - /** - * Gets the correct render target texture to be rendered this frame for this view - * @param view the view for which to get the render target - * @returns the render target for the specified view or null if not available - */ - getRenderTargetTextureForView(view) { - var _a; - return ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getRenderTargetTextureForView(view)) || null; - } - /** - * Creates a WebXRRenderTarget object for the XR session - * @param options optional options to provide when creating a new render target - * @returns a WebXR render target to which the session can render - */ - getWebXRRenderTarget(options) { - const engine = this.scene.getEngine(); - if (this._xrNavigator.xr.native) { - return new NativeXRRenderTarget(this); - } - else { - options = options || WebXRManagedOutputCanvasOptions.GetDefaults(engine); - options.canvasElement = options.canvasElement || engine.getRenderingCanvas() || undefined; - return new WebXRManagedOutputCanvas(this, options); - } - } - /** - * Initializes the manager - * After initialization enterXR can be called to start an XR session - * @returns Promise which resolves after it is initialized - */ - initializeAsync() { - // Check if the browser supports webXR - this._xrNavigator = navigator; - if (!this._xrNavigator.xr) { - return Promise.reject("WebXR not available"); - } - return Promise.resolve(); - } - /** - * Initializes an xr session - * @param xrSessionMode mode to initialize - * @param xrSessionInit defines optional and required values to pass to the session builder - * @returns a promise which will resolve once the session has been initialized - */ - initializeSessionAsync(xrSessionMode = "immersive-vr", xrSessionInit = {}) { - return this._xrNavigator.xr.requestSession(xrSessionMode, xrSessionInit).then((session) => { - this.session = session; - this._sessionMode = xrSessionMode; - this.onXRSessionInit.notifyObservers(session); - this.inXRSession = true; - // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone) - this.session.addEventListener("end", () => { - var _a; - this.inXRSession = false; - // Notify frame observers - this.onXRSessionEnded.notifyObservers(null); - if (this._engine) { - // make sure dimensions object is restored - this._engine.framebufferDimensionsObject = null; - // Restore frame buffer to avoid clear on xr framebuffer after session end - this._engine.restoreDefaultFramebuffer(); - // Need to restart render loop as after the session is ended the last request for new frame will never call callback - this._engine.customAnimationFrameRequester = null; - this._engine._renderLoop(); - } - // Dispose render target textures. - // Only dispose on native because we can't destroy opaque textures on browser. - if (this.isNative) { - (_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.dispose(); - } - this._baseLayerRTTProvider = null; - this._baseLayerWrapper = null; - }, { once: true }); - return this.session; - }); - } - /** - * Checks if a session would be supported for the creation options specified - * @param sessionMode session mode to check if supported eg. immersive-vr - * @returns A Promise that resolves to true if supported and false if not - */ - isSessionSupportedAsync(sessionMode) { - return WebXRSessionManager.IsSessionSupportedAsync(sessionMode); - } - /** - * Resets the reference space to the one started the session - */ - resetReferenceSpace() { - this.referenceSpace = this.baseReferenceSpace; - } - /** - * Starts rendering to the xr layer - */ - runXRRenderLoop() { - var _a; - if (!this.inXRSession || !this._engine) { - return; - } - // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information - this._engine.customAnimationFrameRequester = { - requestAnimationFrame: this.session.requestAnimationFrame.bind(this.session), - renderFunction: (timestamp, xrFrame) => { - var _a; - if (!this.inXRSession || !this._engine) { - return; - } - // Store the XR frame and timestamp in the session manager - this.currentFrame = xrFrame; - this.currentTimestamp = timestamp; - if (xrFrame) { - this.inXRFrameLoop = true; - this._engine.framebufferDimensionsObject = ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getFramebufferDimensions()) || null; - this.onXRFrameObservable.notifyObservers(xrFrame); - this._engine._renderLoop(); - this._engine.framebufferDimensionsObject = null; - this.inXRFrameLoop = false; - } - }, - }; - this._engine.framebufferDimensionsObject = ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getFramebufferDimensions()) || null; - // Stop window's animation frame and trigger sessions animation frame - if (typeof window !== "undefined" && window.cancelAnimationFrame) { - window.cancelAnimationFrame(this._engine._frameHandler); - } - this._engine._renderLoop(); - } - /** - * Sets the reference space on the xr session - * @param referenceSpaceType space to set - * @returns a promise that will resolve once the reference space has been set - */ - setReferenceSpaceTypeAsync(referenceSpaceType = "local-floor") { - return this.session - .requestReferenceSpace(referenceSpaceType) - .then((referenceSpace) => { - return referenceSpace; - }, (rejectionReason) => { - logger_Logger.Error("XR.requestReferenceSpace failed for the following reason: "); - logger_Logger.Error(rejectionReason); - logger_Logger.Log('Defaulting to universally-supported "viewer" reference space type.'); - return this.session.requestReferenceSpace("viewer").then((referenceSpace) => { - const heightCompensation = new XRRigidTransform({ x: 0, y: -this.defaultHeightCompensation, z: 0 }); - return referenceSpace.getOffsetReferenceSpace(heightCompensation); - }, (rejectionReason) => { - logger_Logger.Error(rejectionReason); - throw 'XR initialization failed: required "viewer" reference space type not supported.'; - }); - }) - .then((referenceSpace) => { - // create viewer reference space before setting the first reference space - return this.session.requestReferenceSpace("viewer").then((viewerReferenceSpace) => { - this.viewerReferenceSpace = viewerReferenceSpace; - return referenceSpace; - }); - }) - .then((referenceSpace) => { - // initialize the base and offset (currently the same) - this.referenceSpace = this.baseReferenceSpace = referenceSpace; - return this.referenceSpace; - }); - } - /** - * Updates the render state of the session. - * Note that this is deprecated in favor of WebXRSessionManager.updateRenderState(). - * @param state state to set - * @returns a promise that resolves once the render state has been updated - * @deprecated - */ - updateRenderStateAsync(state) { - return Promise.resolve(this.session.updateRenderState(state)); - } - /** - * @internal - */ - _setBaseLayerWrapper(baseLayerWrapper) { - var _a, _b; - if (this.isNative) { - (_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.dispose(); - } - this._baseLayerWrapper = baseLayerWrapper; - this._baseLayerRTTProvider = ((_b = this._baseLayerWrapper) === null || _b === void 0 ? void 0 : _b.createRenderTargetTextureProvider(this)) || null; - } - /** - * @internal - */ - _getBaseLayerWrapper() { - return this._baseLayerWrapper; - } - /** - * Updates the render state of the session - * @param state state to set - */ - updateRenderState(state) { - if (state.baseLayer) { - this._setBaseLayerWrapper(this.isNative ? new NativeXRLayerWrapper(state.baseLayer) : new WebXRWebGLLayerWrapper(state.baseLayer)); - } - this.session.updateRenderState(state); - } - /** - * Returns a promise that resolves with a boolean indicating if the provided session mode is supported by this browser - * @param sessionMode defines the session to test - * @returns a promise with boolean as final value - */ - static IsSessionSupportedAsync(sessionMode) { - if (!navigator.xr) { - return Promise.resolve(false); - } - // When the specs are final, remove supportsSession! - const functionToUse = navigator.xr.isSessionSupported || navigator.xr.supportsSession; - if (!functionToUse) { - return Promise.resolve(false); - } - else { - return functionToUse - .call(navigator.xr, sessionMode) - .then((result) => { - const returnValue = typeof result === "undefined" ? true : result; - return Promise.resolve(returnValue); - }) - .catch((e) => { - logger_Logger.Warn(e); - return Promise.resolve(false); - }); - } - } - /** - * Returns true if Babylon.js is using the BabylonNative backend, otherwise false - */ - get isNative() { - var _a; - return (_a = this._xrNavigator.xr.native) !== null && _a !== void 0 ? _a : false; - } - /** - * The current frame rate as reported by the device - */ - get currentFrameRate() { - var _a; - return (_a = this.session) === null || _a === void 0 ? void 0 : _a.frameRate; - } - /** - * A list of supported frame rates (only available in-session! - */ - get supportedFrameRates() { - var _a; - return (_a = this.session) === null || _a === void 0 ? void 0 : _a.supportedFrameRates; - } - /** - * Set the framerate of the session. - * @param rate the new framerate. This value needs to be in the supportedFrameRates array - * @returns a promise that resolves once the framerate has been set - */ - updateTargetFrameRate(rate) { - return this.session.updateTargetFrameRate(rate); - } - /** - * Run a callback in the xr render loop - * @param callback the callback to call when in XR Frame - * @param ignoreIfNotInSession if no session is currently running, run it first thing on the next session - */ - runInXRFrame(callback, ignoreIfNotInSession = true) { - if (this.inXRFrameLoop) { - callback(); - } - else if (this.inXRSession || !ignoreIfNotInSession) { - this.onXRFrameObservable.addOnce(callback); - } - } - /** - * Check if fixed foveation is supported on this device - */ - get isFixedFoveationSupported() { - var _a; - return ((_a = this._baseLayerWrapper) === null || _a === void 0 ? void 0 : _a.isFixedFoveationSupported) || false; - } - /** - * Get the fixed foveation currently set, as specified by the webxr specs - * If this returns null, then fixed foveation is not supported - */ - get fixedFoveation() { - var _a; - return ((_a = this._baseLayerWrapper) === null || _a === void 0 ? void 0 : _a.fixedFoveation) || null; - } - /** - * Set the fixed foveation to the specified value, as specified by the webxr specs - * This value will be normalized to be between 0 and 1, 1 being max foveation, 0 being no foveation - */ - set fixedFoveation(value) { - const val = Math.max(0, Math.min(1, value || 0)); - if (this._baseLayerWrapper) { - this._baseLayerWrapper.fixedFoveation = val; - } - } - /** - * Get the features enabled on the current session - * This is only available in-session! - * @see https://www.w3.org/TR/webxr/#dom-xrsession-enabledfeatures - */ - get enabledFeatures() { - var _a, _b; - return (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.enabledFeatures) !== null && _b !== void 0 ? _b : null; - } -} -//# sourceMappingURL=webXRSessionManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRTypes.js -/** - * States of the webXR experience - */ -var WebXRState; -(function (WebXRState) { - /** - * Transitioning to being in XR mode - */ - WebXRState[WebXRState["ENTERING_XR"] = 0] = "ENTERING_XR"; - /** - * Transitioning to non XR mode - */ - WebXRState[WebXRState["EXITING_XR"] = 1] = "EXITING_XR"; - /** - * In XR mode and presenting - */ - WebXRState[WebXRState["IN_XR"] = 2] = "IN_XR"; - /** - * Not entered XR mode - */ - WebXRState[WebXRState["NOT_IN_XR"] = 3] = "NOT_IN_XR"; -})(WebXRState || (WebXRState = {})); -/** - * The state of the XR camera's tracking - */ -var WebXRTrackingState; -(function (WebXRTrackingState) { - /** - * No transformation received, device is not being tracked - */ - WebXRTrackingState[WebXRTrackingState["NOT_TRACKING"] = 0] = "NOT_TRACKING"; - /** - * Tracking lost - using emulated position - */ - WebXRTrackingState[WebXRTrackingState["TRACKING_LOST"] = 1] = "TRACKING_LOST"; - /** - * Transformation tracking works normally - */ - WebXRTrackingState[WebXRTrackingState["TRACKING"] = 2] = "TRACKING"; -})(WebXRTrackingState || (WebXRTrackingState = {})); -//# sourceMappingURL=webXRTypes.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/cylinderBuilder.js - - - - - - - -/** - * Creates the VertexData for a cylinder, cone or prism - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * height sets the height (y direction) of the cylinder, optional, default 2 - * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter - * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter - * * diameter sets the diameter of the top and bottom of the cone, optional default 1 - * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 - * * subdivisions` the number of rings along the cylinder height, optional, default 1 - * * 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 - * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * * hasRings when true makes each subdivision independently treated as a face for faceUV and faceColors, optional, default false - * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.height - * @param options.diameterTop - * @param options.diameterBottom - * @param options.diameter - * @param options.tessellation - * @param options.subdivisions - * @param options.arc - * @param options.faceColors - * @param options.faceUV - * @param options.hasRings - * @param options.enclose - * @param options.cap - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the cylinder, cone or prism - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function CreateCylinderVertexData(options) { - const height = options.height || 2; - let diameterTop = options.diameterTop === 0 ? 0 : options.diameterTop || options.diameter || 1; - let diameterBottom = options.diameterBottom === 0 ? 0 : options.diameterBottom || options.diameter || 1; - diameterTop = diameterTop || 0.00001; // Prevent broken normals - diameterBottom = diameterBottom || 0.00001; // Prevent broken normals - const tessellation = (options.tessellation || 24) | 0; - const subdivisions = (options.subdivisions || 1) | 0; - const hasRings = options.hasRings ? true : false; - const enclose = options.enclose ? true : false; - const cap = options.cap === 0 ? 0 : options.cap || mesh_Mesh.CAP_ALL; - const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0; - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - const faceUV = options.faceUV || new Array(3); - const faceColors = options.faceColors; - // default face colors and UV if undefined - const quadNb = arc !== 1 && enclose ? 2 : 0; - const ringNb = hasRings ? subdivisions : 1; - const surfaceNb = 2 + (1 + quadNb) * ringNb; - let f; - for (f = 0; f < surfaceNb; f++) { - if (faceColors && faceColors[f] === undefined) { - faceColors[f] = new math_color_Color4(1, 1, 1, 1); - } - } - for (f = 0; f < surfaceNb; f++) { - if (faceUV && faceUV[f] === undefined) { - faceUV[f] = new math_vector_Vector4(0, 0, 1, 1); - } - } - const indices = new Array(); - const positions = new Array(); - const normals = new Array(); - const uvs = new Array(); - const colors = new Array(); - const angleStep = (Math.PI * 2 * arc) / tessellation; - let angle; - let h; - let radius; - const tan = (diameterBottom - diameterTop) / 2 / height; - const ringVertex = math_vector_Vector3.Zero(); - const ringNormal = math_vector_Vector3.Zero(); - const ringFirstVertex = math_vector_Vector3.Zero(); - const ringFirstNormal = math_vector_Vector3.Zero(); - const quadNormal = math_vector_Vector3.Zero(); - const Y = math_axis_Axis.Y; - // positions, normals, uvs - let i; - let j; - let r; - let ringIdx = 1; - let s = 1; // surface index - let cs = 0; - let v = 0; - for (i = 0; i <= subdivisions; i++) { - h = i / subdivisions; - radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2; - ringIdx = hasRings && i !== 0 && i !== subdivisions ? 2 : 1; - for (r = 0; r < ringIdx; r++) { - if (hasRings) { - s += r; - } - if (enclose) { - s += 2 * r; - } - for (j = 0; j <= tessellation; j++) { - angle = j * angleStep; - // position - ringVertex.x = Math.cos(-angle) * radius; - ringVertex.y = -height / 2 + h * height; - ringVertex.z = Math.sin(-angle) * radius; - // normal - if (diameterTop === 0 && i === subdivisions) { - // if no top cap, reuse former normals - ringNormal.x = normals[normals.length - (tessellation + 1) * 3]; - ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1]; - ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2]; - } - else { - ringNormal.x = ringVertex.x; - ringNormal.z = ringVertex.z; - ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan; - ringNormal.normalize(); - } - // keep first ring vertex values for enclose - if (j === 0) { - ringFirstVertex.copyFrom(ringVertex); - ringFirstNormal.copyFrom(ringNormal); - } - positions.push(ringVertex.x, ringVertex.y, ringVertex.z); - normals.push(ringNormal.x, ringNormal.y, ringNormal.z); - if (hasRings) { - v = cs !== s ? faceUV[s].y : faceUV[s].w; - } - else { - v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h; - } - uvs.push(faceUV[s].x + ((faceUV[s].z - faceUV[s].x) * j) / tessellation, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v); - if (faceColors) { - colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a); - } - } - // if enclose, add four vertices and their dedicated normals - if (arc !== 1 && enclose) { - positions.push(ringVertex.x, ringVertex.y, ringVertex.z); - positions.push(0, ringVertex.y, 0); - positions.push(0, ringVertex.y, 0); - positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z); - math_vector_Vector3.CrossToRef(Y, ringNormal, quadNormal); - quadNormal.normalize(); - normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z); - math_vector_Vector3.CrossToRef(ringFirstNormal, Y, quadNormal); - quadNormal.normalize(); - normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z); - if (hasRings) { - v = cs !== s ? faceUV[s + 1].y : faceUV[s + 1].w; - } - else { - v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h; - } - uvs.push(faceUV[s + 1].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v); - uvs.push(faceUV[s + 1].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v); - if (hasRings) { - v = cs !== s ? faceUV[s + 2].y : faceUV[s + 2].w; - } - else { - v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h; - } - uvs.push(faceUV[s + 2].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v); - uvs.push(faceUV[s + 2].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v); - if (faceColors) { - colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a); - colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a); - colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a); - colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a); - } - } - if (cs !== s) { - cs = s; - } - } - } - // indices - const e = arc !== 1 && enclose ? tessellation + 4 : tessellation; // correction of number of iteration if enclose - i = 0; - for (s = 0; s < subdivisions; s++) { - let i0 = 0; - let i1 = 0; - let i2 = 0; - let i3 = 0; - for (j = 0; j < tessellation; j++) { - i0 = i * (e + 1) + j; - i1 = (i + 1) * (e + 1) + j; - i2 = i * (e + 1) + (j + 1); - i3 = (i + 1) * (e + 1) + (j + 1); - indices.push(i0, i1, i2); - indices.push(i3, i2, i1); - } - if (arc !== 1 && enclose) { - // if enclose, add two quads - indices.push(i0 + 2, i1 + 2, i2 + 2); - indices.push(i3 + 2, i2 + 2, i1 + 2); - indices.push(i0 + 4, i1 + 4, i2 + 4); - indices.push(i3 + 4, i2 + 4, i1 + 4); - } - i = hasRings ? i + 2 : i + 1; - } - // Caps - const createCylinderCap = (isTop) => { - const radius = isTop ? diameterTop / 2 : diameterBottom / 2; - if (radius === 0) { - return; - } - // Cap positions, normals & uvs - let angle; - let circleVector; - let i; - const u = isTop ? faceUV[surfaceNb - 1] : faceUV[0]; - let c = null; - if (faceColors) { - c = isTop ? faceColors[surfaceNb - 1] : faceColors[0]; - } - // cap center - const vbase = positions.length / 3; - const offset = isTop ? height / 2 : -height / 2; - const center = new math_vector_Vector3(0, offset, 0); - positions.push(center.x, center.y, center.z); - normals.push(0, isTop ? 1 : -1, 0); - const v = u.y + (u.w - u.y) * 0.5; - uvs.push(u.x + (u.z - u.x) * 0.5, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v); - if (c) { - colors.push(c.r, c.g, c.b, c.a); - } - const textureScale = new math_vector_Vector2(0.5, 0.5); - for (i = 0; i <= tessellation; i++) { - angle = (Math.PI * 2 * i * arc) / tessellation; - const cos = Math.cos(-angle); - const sin = Math.sin(-angle); - circleVector = new math_vector_Vector3(cos * radius, offset, sin * radius); - const textureCoordinate = new math_vector_Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5); - positions.push(circleVector.x, circleVector.y, circleVector.z); - normals.push(0, isTop ? 1 : -1, 0); - const v = u.y + (u.w - u.y) * textureCoordinate.y; - uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v); - if (c) { - colors.push(c.r, c.g, c.b, c.a); - } - } - // Cap indices - for (i = 0; i < tessellation; i++) { - if (!isTop) { - indices.push(vbase); - indices.push(vbase + (i + 1)); - indices.push(vbase + (i + 2)); - } - else { - indices.push(vbase); - indices.push(vbase + (i + 2)); - indices.push(vbase + (i + 1)); - } - } - }; - // add caps to geometry based on cap parameter - if (cap === mesh_Mesh.CAP_START || cap === mesh_Mesh.CAP_ALL) { - createCylinderCap(false); - } - if (cap === mesh_Mesh.CAP_END || cap === mesh_Mesh.CAP_ALL) { - createCylinderCap(true); - } - // Sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - if (faceColors) { - vertexData.colors = colors; - } - return vertexData; -} -/** - * Creates a cylinder or a cone mesh - * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). - * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). - * * 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. - * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. - * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). - * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces. - * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis. - * * 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). - * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder. - * * 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). - * * 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 - * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7 - * * 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 - * * 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. - * * If `enclose` is false, a ring surface is one element. - * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces. - * * 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 - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.height - * @param options.diameterTop - * @param options.diameterBottom - * @param options.diameter - * @param options.tessellation - * @param options.subdivisions - * @param options.arc - * @param options.faceColors - * @param options.faceUV - * @param options.updatable - * @param options.hasRings - * @param options.enclose - * @param options.cap - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param scene defines the hosting scene - * @returns the cylinder mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#cylinder-or-cone - */ -function cylinderBuilder_CreateCylinder(name, options = {}, scene) { - const cylinder = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - cylinder._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreateCylinderVertexData(options); - vertexData.applyToMesh(cylinder, options.updatable); - return cylinder; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated Please use CreateCylinder directly - */ -const CylinderBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateCylinder: cylinderBuilder_CreateCylinder, -}; -mesh_vertexData_VertexData.CreateCylinder = CreateCylinderVertexData; -mesh_Mesh.CreateCylinder = (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) => { - if (scene === undefined || !(scene instanceof scene_Scene)) { - if (scene !== undefined) { - sideOrientation = updatable || mesh_Mesh.DEFAULTSIDE; - updatable = scene; - } - scene = subdivisions; - subdivisions = 1; - } - const options = { - height, - diameterTop, - diameterBottom, - tessellation, - subdivisions, - sideOrientation, - updatable, - }; - return cylinderBuilder_CreateCylinder(name, options, scene); -}; -//# sourceMappingURL=cylinderBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/torusBuilder.js - - - - -/** - * Creates the VertexData for a torus - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * diameter the diameter of the torus, optional default 1 - * * thickness the diameter of the tube forming the torus, optional default 0.5 - * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.diameter - * @param options.thickness - * @param options.tessellation - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the torus - */ -function CreateTorusVertexData(options) { - const indices = []; - const positions = []; - const normals = []; - const uvs = []; - const diameter = options.diameter || 1; - const thickness = options.thickness || 0.5; - const tessellation = (options.tessellation || 16) | 0; - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - const stride = tessellation + 1; - for (let i = 0; i <= tessellation; i++) { - const u = i / tessellation; - const outerAngle = (i * Math.PI * 2.0) / tessellation - Math.PI / 2.0; - const transform = math_vector_Matrix.Translation(diameter / 2.0, 0, 0).multiply(math_vector_Matrix.RotationY(outerAngle)); - for (let j = 0; j <= tessellation; j++) { - const v = 1 - j / tessellation; - const innerAngle = (j * Math.PI * 2.0) / tessellation + Math.PI; - const dx = Math.cos(innerAngle); - const dy = Math.sin(innerAngle); - // Create a vertex. - let normal = new math_vector_Vector3(dx, dy, 0); - let position = normal.scale(thickness / 2); - const textureCoordinate = new math_vector_Vector2(u, v); - position = math_vector_Vector3.TransformCoordinates(position, transform); - normal = math_vector_Vector3.TransformNormal(normal, transform); - positions.push(position.x, position.y, position.z); - normals.push(normal.x, normal.y, normal.z); - uvs.push(textureCoordinate.x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - textureCoordinate.y : textureCoordinate.y); - // And create indices for two triangles. - const nextI = (i + 1) % stride; - const nextJ = (j + 1) % stride; - indices.push(i * stride + j); - indices.push(i * stride + nextJ); - indices.push(nextI * stride + j); - indices.push(i * stride + nextJ); - indices.push(nextI * stride + nextJ); - indices.push(nextI * stride + j); - } - } - // Sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - return vertexData; -} -/** - * Creates a torus mesh - * * The parameter `diameter` sets the diameter size (float) of the torus (default 1) - * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5) - * * The parameter `tessellation` sets the number of torus sides (positive integer, default 16) - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.diameter - * @param options.thickness - * @param options.tessellation - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param scene defines the hosting scene - * @returns the torus mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#torus - */ -function CreateTorus(name, options = {}, scene) { - const torus = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - torus._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreateTorusVertexData(options); - vertexData.applyToMesh(torus, options.updatable); - return torus; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use CreateTorus instead - */ -const TorusBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateTorus, -}; -mesh_vertexData_VertexData.CreateTorus = CreateTorusVertexData; -mesh_Mesh.CreateTorus = (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) => { - const options = { - diameter, - thickness, - tessellation, - sideOrientation, - updatable, - }; - return CreateTorus(name, options, scene); -}; -//# sourceMappingURL=torusBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/groundMesh.js - - - -mesh_Mesh._GroundMeshParser = (parsedMesh, scene) => { - return GroundMesh.Parse(parsedMesh, scene); -}; -/** - * Mesh representing the ground - */ -class GroundMesh extends mesh_Mesh { - constructor(name, scene) { - super(name, scene); - /** If octree should be generated */ - this.generateOctree = false; - } - /** - * "GroundMesh" - * @returns "GroundMesh" - */ - getClassName() { - return "GroundMesh"; - } - /** - * The minimum of x and y subdivisions - */ - get subdivisions() { - return Math.min(this._subdivisionsX, this._subdivisionsY); - } - /** - * X subdivisions - */ - get subdivisionsX() { - return this._subdivisionsX; - } - /** - * Y subdivisions - */ - get subdivisionsY() { - return this._subdivisionsY; - } - /** - * This function will divide the mesh into submeshes and update an octree to help to select the right submeshes - * for rendering, picking and collision computations. Please note that you must have a decent number of submeshes - * to get performance improvements when using an octree. - * @param chunksCount the number of submeshes the mesh will be divided into - * @param octreeBlocksSize the maximum size of the octree blocks (Default: 32) - */ - optimize(chunksCount, octreeBlocksSize = 32) { - this._subdivisionsX = chunksCount; - this._subdivisionsY = chunksCount; - this.subdivide(chunksCount); - // Call the octree system optimization if it is defined. - const thisAsAny = this; - if (thisAsAny.createOrUpdateSubmeshesOctree) { - thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize); - } - } - /** - * Returns a height (y) value in the World system : - * the ground altitude at the coordinates (x, z) expressed in the World system. - * @param x x coordinate - * @param z z coordinate - * @returns the ground y position if (x, z) are outside the ground surface. - */ - getHeightAtCoordinates(x, z) { - const world = this.getWorldMatrix(); - const invMat = math_vector_TmpVectors.Matrix[5]; - world.invertToRef(invMat); - const tmpVect = math_vector_TmpVectors.Vector3[8]; - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space - x = tmpVect.x; - z = tmpVect.z; - if (x < this._minX || x >= this._maxX || z <= this._minZ || z > this._maxZ) { - return this.position.y; - } - if (!this._heightQuads || this._heightQuads.length == 0) { - this._initHeightQuads(); - this._computeHeightQuads(); - } - const facet = this._getFacetAt(x, z); - const y = -(facet.x * x + facet.z * z + facet.w) / facet.y; - // return y in the World system - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect); - return tmpVect.y; - } - /** - * Returns a normalized vector (Vector3) orthogonal to the ground - * at the ground coordinates (x, z) expressed in the World system. - * @param x x coordinate - * @param z z coordinate - * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface. - */ - getNormalAtCoordinates(x, z) { - const normal = new math_vector_Vector3(0.0, 1.0, 0.0); - this.getNormalAtCoordinatesToRef(x, z, normal); - return normal; - } - /** - * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground - * at the ground coordinates (x, z) expressed in the World system. - * Doesn't update the reference Vector3 if (x, z) are outside the ground surface. - * @param x x coordinate - * @param z z coordinate - * @param ref vector to store the result - * @returns the GroundMesh. - */ - getNormalAtCoordinatesToRef(x, z, ref) { - const world = this.getWorldMatrix(); - const tmpMat = math_vector_TmpVectors.Matrix[5]; - world.invertToRef(tmpMat); - const tmpVect = math_vector_TmpVectors.Vector3[8]; - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space - x = tmpVect.x; - z = tmpVect.z; - if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) { - return this; - } - if (!this._heightQuads || this._heightQuads.length == 0) { - this._initHeightQuads(); - this._computeHeightQuads(); - } - const facet = this._getFacetAt(x, z); - math_vector_Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref); - return this; - } - /** - * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates() - * if the ground has been updated. - * This can be used in the render loop. - * @returns the GroundMesh. - */ - updateCoordinateHeights() { - if (!this._heightQuads || this._heightQuads.length == 0) { - this._initHeightQuads(); - } - this._computeHeightQuads(); - return this; - } - // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates - _getFacetAt(x, z) { - // retrieve col and row from x, z coordinates in the ground local system - const col = Math.floor(((x + this._maxX) * this._subdivisionsX) / this._width); - const row = Math.floor((-(z + this._maxZ) * this._subdivisionsY) / this._height + this._subdivisionsY); - const quad = this._heightQuads[row * this._subdivisionsX + col]; - let facet; - if (z < quad.slope.x * x + quad.slope.y) { - facet = quad.facet1; - } - else { - facet = quad.facet2; - } - return facet; - } - // Creates and populates the heightMap array with "facet" elements : - // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets - // slope : Vector2(c, h) = 2D diagonal line equation setting apart two triangular facets in a quad : z = cx + h - // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0 - // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 - // Returns the GroundMesh. - _initHeightQuads() { - const subdivisionsX = this._subdivisionsX; - const subdivisionsY = this._subdivisionsY; - this._heightQuads = new Array(); - for (let row = 0; row < subdivisionsY; row++) { - for (let col = 0; col < subdivisionsX; col++) { - const quad = { slope: math_vector_Vector2.Zero(), facet1: new math_vector_Vector4(0.0, 0.0, 0.0, 0.0), facet2: new math_vector_Vector4(0.0, 0.0, 0.0, 0.0) }; - this._heightQuads[row * subdivisionsX + col] = quad; - } - } - return this; - } - // Compute each quad element values and update the the heightMap array : - // slope : Vector2(c, h) = 2D diagonal line equation setting apart two triangular facets in a quad : z = cx + h - // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0 - // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 - // Returns the GroundMesh. - _computeHeightQuads() { - const positions = this.getVerticesData(buffer_VertexBuffer.PositionKind); - if (!positions) { - return this; - } - const v1 = math_vector_TmpVectors.Vector3[3]; - const v2 = math_vector_TmpVectors.Vector3[2]; - const v3 = math_vector_TmpVectors.Vector3[1]; - const v4 = math_vector_TmpVectors.Vector3[0]; - const v1v2 = math_vector_TmpVectors.Vector3[4]; - const v1v3 = math_vector_TmpVectors.Vector3[5]; - const v1v4 = math_vector_TmpVectors.Vector3[6]; - const norm1 = math_vector_TmpVectors.Vector3[7]; - const norm2 = math_vector_TmpVectors.Vector3[8]; - let i = 0; - let j = 0; - let k = 0; - let cd = 0; // 2D slope coefficient : z = cd * x + h - let h = 0; - let d1 = 0; // facet plane equation : ax + by + cz + d = 0 - let d2 = 0; - const subdivisionsX = this._subdivisionsX; - const subdivisionsY = this._subdivisionsY; - for (let row = 0; row < subdivisionsY; row++) { - for (let col = 0; col < subdivisionsX; col++) { - i = col * 3; - j = row * (subdivisionsX + 1) * 3; - k = (row + 1) * (subdivisionsX + 1) * 3; - v1.x = positions[j + i]; - v1.y = positions[j + i + 1]; - v1.z = positions[j + i + 2]; - v2.x = positions[j + i + 3]; - v2.y = positions[j + i + 4]; - v2.z = positions[j + i + 5]; - v3.x = positions[k + i]; - v3.y = positions[k + i + 1]; - v3.z = positions[k + i + 2]; - v4.x = positions[k + i + 3]; - v4.y = positions[k + i + 4]; - v4.z = positions[k + i + 5]; - // 2D slope V1V4 - cd = (v4.z - v1.z) / (v4.x - v1.x); - h = v1.z - cd * v1.x; // v1 belongs to the slope - // facet equations : - // we compute each facet normal vector - // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0 - // we compute the value d by applying the equation to v1 which belongs to the plane - // then we store the facet equation in a Vector4 - v2.subtractToRef(v1, v1v2); - v3.subtractToRef(v1, v1v3); - v4.subtractToRef(v1, v1v4); - math_vector_Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class - math_vector_Vector3.CrossToRef(v1v2, v1v4, norm2); - norm1.normalize(); - norm2.normalize(); - d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z); - d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z); - const quad = this._heightQuads[row * subdivisionsX + col]; - quad.slope.copyFromFloats(cd, h); - quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1); - quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2); - } - } - return this; - } - /** - * Serializes this ground mesh - * @param serializationObject object to write serialization to - */ - serialize(serializationObject) { - super.serialize(serializationObject); - serializationObject.subdivisionsX = this._subdivisionsX; - serializationObject.subdivisionsY = this._subdivisionsY; - serializationObject.minX = this._minX; - serializationObject.maxX = this._maxX; - serializationObject.minZ = this._minZ; - serializationObject.maxZ = this._maxZ; - serializationObject.width = this._width; - serializationObject.height = this._height; - } - /** - * Parses a serialized ground mesh - * @param parsedMesh the serialized mesh - * @param scene the scene to create the ground mesh in - * @returns the created ground mesh - */ - static Parse(parsedMesh, scene) { - const result = new GroundMesh(parsedMesh.name, scene); - result._subdivisionsX = parsedMesh.subdivisionsX || 1; - result._subdivisionsY = parsedMesh.subdivisionsY || 1; - result._minX = parsedMesh.minX; - result._maxX = parsedMesh.maxX; - result._minZ = parsedMesh.minZ; - result._maxZ = parsedMesh.maxZ; - result._width = parsedMesh.width; - result._height = parsedMesh.height; - return result; - } -} -//# sourceMappingURL=groundMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/groundBuilder.js - - - - - - - - - -/** - * Creates the VertexData for a Ground - * @param options an object used to set the following optional parameters for the Ground, required but can be empty - * - width the width (x direction) of the ground, optional, default 1 - * - height the height (z direction) of the ground, optional, default 1 - * - subdivisions the number of subdivisions per side, optional, default 1 - * @param options.width - * @param options.height - * @param options.subdivisions - * @param options.subdivisionsX - * @param options.subdivisionsY - * @returns the VertexData of the Ground - */ -function CreateGroundVertexData(options) { - const indices = []; - const positions = []; - const normals = []; - const uvs = []; - let row, col; - const width = options.width || 1; - const height = options.height || 1; - const subdivisionsX = (options.subdivisionsX || options.subdivisions || 1) | 0; - const subdivisionsY = (options.subdivisionsY || options.subdivisions || 1) | 0; - for (row = 0; row <= subdivisionsY; row++) { - for (col = 0; col <= subdivisionsX; col++) { - const position = new math_vector_Vector3((col * width) / subdivisionsX - width / 2.0, 0, ((subdivisionsY - row) * height) / subdivisionsY - height / 2.0); - const normal = new math_vector_Vector3(0, 1.0, 0); - positions.push(position.x, position.y, position.z); - normals.push(normal.x, normal.y, normal.z); - uvs.push(col / subdivisionsX, CompatibilityOptions.UseOpenGLOrientationForUV ? row / subdivisionsY : 1.0 - row / subdivisionsY); - } - } - for (row = 0; row < subdivisionsY; row++) { - for (col = 0; col < subdivisionsX; col++) { - indices.push(col + 1 + (row + 1) * (subdivisionsX + 1)); - indices.push(col + 1 + row * (subdivisionsX + 1)); - indices.push(col + row * (subdivisionsX + 1)); - indices.push(col + (row + 1) * (subdivisionsX + 1)); - indices.push(col + 1 + (row + 1) * (subdivisionsX + 1)); - indices.push(col + row * (subdivisionsX + 1)); - } - } - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - return vertexData; -} -/** - * Creates the VertexData for a TiledGround by subdividing the ground into tiles - * @param options an object used to set the following optional parameters for the Ground, required but can be empty - * * xmin the ground minimum X coordinate, optional, default -1 - * * zmin the ground minimum Z coordinate, optional, default -1 - * * xmax the ground maximum X coordinate, optional, default 1 - * * zmax the ground maximum Z coordinate, optional, default 1 - * * 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} - * * 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} - * @param options.xmin - * @param options.zmin - * @param options.xmax - * @param options.zmax - * @param options.subdivisions - * @param options.subdivisions.w - * @param options.subdivisions.h - * @param options.precision - * @param options.precision.w - * @param options.precision.h - * @returns the VertexData of the TiledGround - */ -function CreateTiledGroundVertexData(options) { - const xmin = options.xmin !== undefined && options.xmin !== null ? options.xmin : -1.0; - const zmin = options.zmin !== undefined && options.zmin !== null ? options.zmin : -1.0; - const xmax = options.xmax !== undefined && options.xmax !== null ? options.xmax : 1.0; - const zmax = options.zmax !== undefined && options.zmax !== null ? options.zmax : 1.0; - const subdivisions = options.subdivisions || { w: 1, h: 1 }; - const precision = options.precision || { w: 1, h: 1 }; - const indices = new Array(); - const positions = new Array(); - const normals = new Array(); - const uvs = new Array(); - let row, col, tileRow, tileCol; - subdivisions.h = subdivisions.h < 1 ? 1 : subdivisions.h; - subdivisions.w = subdivisions.w < 1 ? 1 : subdivisions.w; - precision.w = precision.w < 1 ? 1 : precision.w; - precision.h = precision.h < 1 ? 1 : precision.h; - const tileSize = { - w: (xmax - xmin) / subdivisions.w, - h: (zmax - zmin) / subdivisions.h, - }; - function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) { - // Indices - const base = positions.length / 3; - const rowLength = precision.w + 1; - for (row = 0; row < precision.h; row++) { - for (col = 0; col < precision.w; col++) { - const square = [base + col + row * rowLength, base + (col + 1) + row * rowLength, base + (col + 1) + (row + 1) * rowLength, base + col + (row + 1) * rowLength]; - indices.push(square[1]); - indices.push(square[2]); - indices.push(square[3]); - indices.push(square[0]); - indices.push(square[1]); - indices.push(square[3]); - } - } - // Position, normals and uvs - const position = math_vector_Vector3.Zero(); - const normal = new math_vector_Vector3(0, 1.0, 0); - for (row = 0; row <= precision.h; row++) { - position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin; - for (col = 0; col <= precision.w; col++) { - position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin; - position.y = 0; - positions.push(position.x, position.y, position.z); - normals.push(normal.x, normal.y, normal.z); - uvs.push(col / precision.w, row / precision.h); - } - } - } - for (tileRow = 0; tileRow < subdivisions.h; tileRow++) { - for (tileCol = 0; tileCol < subdivisions.w; tileCol++) { - applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h); - } - } - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - return vertexData; -} -/** - * Creates the VertexData of the Ground designed from a heightmap - * @param options an object used to set the following parameters for the Ground, required and provided by CreateGroundFromHeightMap - * * width the width (x direction) of the ground - * * height the height (z direction) of the ground - * * subdivisions the number of subdivisions per side - * * minHeight the minimum altitude on the ground, optional, default 0 - * * maxHeight the maximum altitude on the ground, optional default 1 - * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11) - * * buffer the array holding the image color data - * * bufferWidth the width of image - * * bufferHeight the height of image - * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible) - * @param options.width - * @param options.height - * @param options.subdivisions - * @param options.minHeight - * @param options.maxHeight - * @param options.colorFilter - * @param options.buffer - * @param options.bufferWidth - * @param options.bufferHeight - * @param options.alphaFilter - * @returns the VertexData of the Ground designed from a heightmap - */ -function CreateGroundFromHeightMapVertexData(options) { - const indices = []; - const positions = []; - const normals = []; - const uvs = []; - let row, col; - const filter = options.colorFilter || new math_color_Color3(0.3, 0.59, 0.11); - const alphaFilter = options.alphaFilter || 0.0; - let invert = false; - if (options.minHeight > options.maxHeight) { - invert = true; - const temp = options.maxHeight; - options.maxHeight = options.minHeight; - options.minHeight = temp; - } - // Vertices - for (row = 0; row <= options.subdivisions; row++) { - for (col = 0; col <= options.subdivisions; col++) { - const position = new math_vector_Vector3((col * options.width) / options.subdivisions - options.width / 2.0, 0, ((options.subdivisions - row) * options.height) / options.subdivisions - options.height / 2.0); - // Compute height - const heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0; - const heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0; - const pos = (heightMapX + heightMapY * options.bufferWidth) * 4; - let r = options.buffer[pos] / 255.0; - let g = options.buffer[pos + 1] / 255.0; - let b = options.buffer[pos + 2] / 255.0; - const a = options.buffer[pos + 3] / 255.0; - if (invert) { - r = 1.0 - r; - g = 1.0 - g; - b = 1.0 - b; - } - const gradient = r * filter.r + g * filter.g + b * filter.b; - // If our alpha channel is not within our filter then we will assign a 'special' height - // Then when building the indices, we will ignore any vertex that is using the special height - if (a >= alphaFilter) { - position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient; - } - else { - position.y = options.minHeight - math_constants_Epsilon; // We can't have a height below minHeight, normally. - } - // Add vertex - positions.push(position.x, position.y, position.z); - normals.push(0, 0, 0); - uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions); - } - } - // Indices - for (row = 0; row < options.subdivisions; row++) { - for (col = 0; col < options.subdivisions; col++) { - // Calculate Indices - const idx1 = col + 1 + (row + 1) * (options.subdivisions + 1); - const idx2 = col + 1 + row * (options.subdivisions + 1); - const idx3 = col + row * (options.subdivisions + 1); - const idx4 = col + (row + 1) * (options.subdivisions + 1); - // Check that all indices are visible (based on our special height) - // Only display the vertex if all Indices are visible - // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height - const isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight; - const isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight; - const isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight; - if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) { - indices.push(idx1); - indices.push(idx2); - indices.push(idx3); - } - const isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight; - if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) { - indices.push(idx4); - indices.push(idx1); - indices.push(idx3); - } - } - } - // Normals - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals); - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - return vertexData; -} -/** - * Creates a ground mesh - * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground - * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.width - * @param options.height - * @param options.subdivisions - * @param options.subdivisionsX - * @param options.subdivisionsY - * @param options.updatable - * @param scene defines the hosting scene - * @returns the ground mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#ground - */ -function CreateGround(name, options = {}, scene) { - const ground = new GroundMesh(name, scene); - ground._setReady(false); - ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1; - ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1; - ground._width = options.width || 1; - ground._height = options.height || 1; - ground._maxX = ground._width / 2; - ground._maxZ = ground._height / 2; - ground._minX = -ground._maxX; - ground._minZ = -ground._maxZ; - const vertexData = CreateGroundVertexData(options); - vertexData.applyToMesh(ground, options.updatable); - ground._setReady(true); - return ground; -} -/** - * Creates a tiled ground mesh - * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates - * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates - * * 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 - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.xmin - * @param options.zmin - * @param options.xmax - * @param options.zmax - * @param options.subdivisions - * @param options.subdivisions.w - * @param options.subdivisions.h - * @param options.precision - * @param options.precision.w - * @param options.precision.h - * @param options.updatable - * @param scene defines the hosting scene - * @returns the tiled ground mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#tiled-ground - */ -function CreateTiledGround(name, options, scene = null) { - const tiledGround = new mesh_Mesh(name, scene); - const vertexData = CreateTiledGroundVertexData(options); - vertexData.applyToMesh(tiledGround, options.updatable); - return tiledGround; -} -/** - * Creates a ground mesh from a height map - * * The parameter `url` sets the URL of the height map image resource. - * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. - * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. - * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. - * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. - * * 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. - * * 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). - * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible) - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param url defines the url to the height map - * @param options defines the options used to create the mesh - * @param options.width - * @param options.height - * @param options.subdivisions - * @param options.minHeight - * @param options.maxHeight - * @param options.colorFilter - * @param options.alphaFilter - * @param options.updatable - * @param options.onReady - * @param scene defines the hosting scene - * @returns the ground mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/height_map - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#ground-from-a-height-map - */ -function CreateGroundFromHeightMap(name, url, options = {}, scene = null) { - const width = options.width || 10.0; - const height = options.height || 10.0; - const subdivisions = options.subdivisions || 1 | 0; - const minHeight = options.minHeight || 0.0; - const maxHeight = options.maxHeight || 1.0; - const filter = options.colorFilter || new math_color_Color3(0.3, 0.59, 0.11); - const alphaFilter = options.alphaFilter || 0.0; - const updatable = options.updatable; - const onReady = options.onReady; - scene = scene || engineStore_EngineStore.LastCreatedScene; - const ground = new GroundMesh(name, scene); - ground._subdivisionsX = subdivisions; - ground._subdivisionsY = subdivisions; - ground._width = width; - ground._height = height; - ground._maxX = ground._width / 2.0; - ground._maxZ = ground._height / 2.0; - ground._minX = -ground._maxX; - ground._minZ = -ground._maxZ; - ground._setReady(false); - const onload = (img) => { - const bufferWidth = img.width; - const bufferHeight = img.height; - if (scene.isDisposed) { - return; - } - const buffer = scene === null || scene === void 0 ? void 0 : scene.getEngine().resizeImageBitmap(img, bufferWidth, bufferHeight); - const vertexData = CreateGroundFromHeightMapVertexData({ - width: width, - height: height, - subdivisions: subdivisions, - minHeight: minHeight, - maxHeight: maxHeight, - colorFilter: filter, - buffer: buffer, - bufferWidth: bufferWidth, - bufferHeight: bufferHeight, - alphaFilter: alphaFilter, - }); - vertexData.applyToMesh(ground, updatable); - //execute ready callback, if set - if (onReady) { - onReady(ground); - } - ground._setReady(true); - }; - tools_Tools.LoadImage(url, onload, () => { }, scene.offlineProvider); - return ground; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use the functions directly from the module - */ -const GroundBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateGround, - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateGroundFromHeightMap, - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateTiledGround, -}; -mesh_vertexData_VertexData.CreateGround = CreateGroundVertexData; -mesh_vertexData_VertexData.CreateTiledGround = CreateTiledGroundVertexData; -mesh_vertexData_VertexData.CreateGroundFromHeightMap = CreateGroundFromHeightMapVertexData; -mesh_Mesh.CreateGround = (name, width, height, subdivisions, scene, updatable) => { - const options = { - width, - height, - subdivisions, - updatable, - }; - return CreateGround(name, options, scene); -}; -mesh_Mesh.CreateTiledGround = (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) => { - const options = { - xmin, - zmin, - xmax, - zmax, - subdivisions, - precision, - updatable, - }; - return CreateTiledGround(name, options, scene); -}; -mesh_Mesh.CreateGroundFromHeightMap = (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) => { - const options = { - width, - height, - subdivisions, - minHeight, - maxHeight, - updatable, - onReady, - alphaFilter, - }; - return CreateGroundFromHeightMap(name, url, options, scene); -}; -//# sourceMappingURL=groundBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/VR/vrExperienceHelper.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -class VRExperienceHelperGazer { - constructor(scene, gazeTrackerToClone = null) { - this.scene = scene; - /** @internal */ - this._pointerDownOnMeshAsked = false; - /** @internal */ - this._isActionableMesh = false; - /** @internal */ - this._teleportationRequestInitiated = false; - /** @internal */ - this._teleportationBackRequestInitiated = false; - /** @internal */ - this._rotationRightAsked = false; - /** @internal */ - this._rotationLeftAsked = false; - /** @internal */ - this._dpadPressed = true; - /** @internal */ - this._activePointer = false; - this._id = VRExperienceHelperGazer._IdCounter++; - // Gaze tracker - if (!gazeTrackerToClone) { - this._gazeTracker = CreateTorus("gazeTracker", { - diameter: 0.0035, - thickness: 0.0025, - tessellation: 20, - updatable: false, - }, scene); - this._gazeTracker.bakeCurrentTransformIntoVertices(); - this._gazeTracker.isPickable = false; - this._gazeTracker.isVisible = false; - const targetMat = new standardMaterial_StandardMaterial("targetMat", scene); - targetMat.specularColor = math_color_Color3.Black(); - targetMat.emissiveColor = new math_color_Color3(0.7, 0.7, 0.7); - targetMat.backFaceCulling = false; - this._gazeTracker.material = targetMat; - } - else { - this._gazeTracker = gazeTrackerToClone.clone("gazeTracker"); - } - } - /** - * @internal - */ - _getForwardRay(length) { - return new ray_Ray(math_vector_Vector3.Zero(), new math_vector_Vector3(0, 0, length)); - } - /** @internal */ - _selectionPointerDown() { - this._pointerDownOnMeshAsked = true; - if (this._currentHit) { - this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id }); - } - } - /** @internal */ - _selectionPointerUp() { - if (this._currentHit) { - this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id }); - } - this._pointerDownOnMeshAsked = false; - } - /** @internal */ - _activatePointer() { - this._activePointer = true; - } - /** @internal */ - _deactivatePointer() { - this._activePointer = false; - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _updatePointerDistance(distance = 100) { } - dispose() { - this._interactionsEnabled = false; - this._teleportationEnabled = false; - if (this._gazeTracker) { - this._gazeTracker.dispose(); - } - } -} -VRExperienceHelperGazer._IdCounter = 0; -class VRExperienceHelperControllerGazer extends VRExperienceHelperGazer { - constructor(webVRController, scene, gazeTrackerToClone) { - super(scene, gazeTrackerToClone); - this.webVRController = webVRController; - // Laser pointer - this._laserPointer = cylinderBuilder_CreateCylinder("laserPointer", { - updatable: false, - height: 1, - diameterTop: 0.004, - diameterBottom: 0.0002, - tessellation: 20, - subdivisions: 1, - }, scene); - const laserPointerMaterial = new standardMaterial_StandardMaterial("laserPointerMat", scene); - laserPointerMaterial.emissiveColor = new math_color_Color3(0.7, 0.7, 0.7); - laserPointerMaterial.alpha = 0.6; - this._laserPointer.material = laserPointerMaterial; - this._laserPointer.rotation.x = Math.PI / 2; - this._laserPointer.position.z = -0.5; - this._laserPointer.isVisible = false; - this._laserPointer.isPickable = false; - if (!webVRController.mesh) { - // Create an empty mesh that is used prior to loading the high quality model - const preloadMesh = new mesh_Mesh("preloadControllerMesh", scene); - const preloadPointerPose = new mesh_Mesh(poseEnabledController_PoseEnabledController.POINTING_POSE, scene); - preloadPointerPose.rotation.x = -0.7; - preloadMesh.addChild(preloadPointerPose); - webVRController.attachToMesh(preloadMesh); - } - this._setLaserPointerParent(webVRController.mesh); - this._meshAttachedObserver = webVRController._meshAttachedObservable.add((mesh) => { - this._setLaserPointerParent(mesh); - }); - } - _getForwardRay(length) { - return this.webVRController.getForwardRay(length); - } - /** @internal */ - _activatePointer() { - super._activatePointer(); - this._laserPointer.isVisible = true; - } - /** @internal */ - _deactivatePointer() { - super._deactivatePointer(); - this._laserPointer.isVisible = false; - } - /** - * @internal - */ - _setLaserPointerColor(color) { - this._laserPointer.material.emissiveColor = color; - } - /** - * @internal - */ - _setLaserPointerLightingDisabled(disabled) { - this._laserPointer.material.disableLighting = disabled; - } - /** - * @internal - */ - _setLaserPointerParent(mesh) { - const makeNotPick = (root) => { - root.isPickable = false; - root.getChildMeshes().forEach((c) => { - makeNotPick(c); - }); - }; - makeNotPick(mesh); - const meshChildren = mesh.getChildren(undefined, false); - let laserParent = mesh; - this.webVRController._pointingPoseNode = null; - for (let i = 0; i < meshChildren.length; i++) { - if (meshChildren[i].name && meshChildren[i].name.indexOf(poseEnabledController_PoseEnabledController.POINTING_POSE) >= 0) { - laserParent = meshChildren[i]; - this.webVRController._pointingPoseNode = laserParent; - break; - } - } - this._laserPointer.parent = laserParent; - } - _updatePointerDistance(distance = 100) { - this._laserPointer.scaling.y = distance; - this._laserPointer.position.z = -distance / 2; - } - dispose() { - super.dispose(); - this._laserPointer.dispose(); - if (this._meshAttachedObserver) { - this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver); - } - } -} -class VRExperienceHelperCameraGazer extends VRExperienceHelperGazer { - constructor(_getCamera, scene) { - super(scene); - this._getCamera = _getCamera; - } - _getForwardRay(length) { - const camera = this._getCamera(); - if (camera) { - return camera.getForwardRay(length); - } - else { - return new ray_Ray(math_vector_Vector3.Zero(), math_vector_Vector3.Forward()); - } - } -} -/** - * Event containing information after VR has been entered - */ -class OnAfterEnteringVRObservableEvent { -} -/** - * Helps to quickly add VR support to an existing scene. - * See https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRHelper - * @deprecated - */ -class VRExperienceHelper { - /** Return this.onEnteringVRObservable - * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly - */ - get onEnteringVR() { - return this.onEnteringVRObservable; - } - /** Return this.onExitingVRObservable - * Note: This one is for backward compatibility. Please use onExitingVRObservable directly - */ - get onExitingVR() { - return this.onExitingVRObservable; - } - /** Return this.onControllerMeshLoadedObservable - * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly - */ - get onControllerMeshLoaded() { - return this.onControllerMeshLoadedObservable; - } - /** - * The mesh used to display where the user is going to teleport. - */ - get teleportationTarget() { - return this._teleportationTarget; - } - /** - * Sets the mesh to be used to display where the user is going to teleport. - */ - set teleportationTarget(value) { - if (value) { - value.name = "teleportationTarget"; - this._isDefaultTeleportationTarget = false; - this._teleportationTarget = value; - } - } - /** - * 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 - * when set bakeCurrentTransformIntoVertices will be called on the mesh. - * See https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms - */ - get gazeTrackerMesh() { - return this._cameraGazer._gazeTracker; - } - set gazeTrackerMesh(value) { - if (value) { - // Dispose of existing meshes - if (this._cameraGazer._gazeTracker) { - this._cameraGazer._gazeTracker.dispose(); - } - if (this._leftController && this._leftController._gazeTracker) { - this._leftController._gazeTracker.dispose(); - } - if (this._rightController && this._rightController._gazeTracker) { - this._rightController._gazeTracker.dispose(); - } - // Set and create gaze trackers on head and controllers - this._cameraGazer._gazeTracker = value; - this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(); - this._cameraGazer._gazeTracker.isPickable = false; - this._cameraGazer._gazeTracker.isVisible = false; - this._cameraGazer._gazeTracker.name = "gazeTracker"; - if (this._leftController) { - this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker"); - } - if (this._rightController) { - this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker"); - } - } - } - /** - * The gaze tracking mesh corresponding to the left controller - */ - get leftControllerGazeTrackerMesh() { - if (this._leftController) { - return this._leftController._gazeTracker; - } - return null; - } - /** - * The gaze tracking mesh corresponding to the right controller - */ - get rightControllerGazeTrackerMesh() { - if (this._rightController) { - return this._rightController._gazeTracker; - } - return null; - } - /** - * If the ray of the gaze should be displayed. - */ - get displayGaze() { - return this._displayGaze; - } - /** - * Sets if the ray of the gaze should be displayed. - */ - set displayGaze(value) { - this._displayGaze = value; - if (!value) { - this._cameraGazer._gazeTracker.isVisible = false; - if (this._leftController) { - this._leftController._gazeTracker.isVisible = false; - } - if (this._rightController) { - this._rightController._gazeTracker.isVisible = false; - } - } - } - /** - * If the ray of the LaserPointer should be displayed. - */ - get displayLaserPointer() { - return this._displayLaserPointer; - } - /** - * Sets if the ray of the LaserPointer should be displayed. - */ - set displayLaserPointer(value) { - this._displayLaserPointer = value; - if (!value) { - if (this._rightController) { - this._rightController._deactivatePointer(); - this._rightController._gazeTracker.isVisible = false; - } - if (this._leftController) { - this._leftController._deactivatePointer(); - this._leftController._gazeTracker.isVisible = false; - } - } - else { - if (this._rightController) { - this._rightController._activatePointer(); - } - if (this._leftController) { - this._leftController._activatePointer(); - } - } - } - /** - * The deviceOrientationCamera used as the camera when not in VR. - */ - get deviceOrientationCamera() { - return this._deviceOrientationCamera; - } - /** - * Based on the current WebVR support, returns the current VR camera used. - */ - get currentVRCamera() { - if (this._webVRready) { - return this._webVRCamera; - } - else { - return this._scene.activeCamera; - } - } - /** - * The webVRCamera which is used when in VR. - */ - get webVRCamera() { - return this._webVRCamera; - } - /** - * The deviceOrientationCamera that is used as a fallback when vr device is not connected. - */ - get vrDeviceOrientationCamera() { - return this._vrDeviceOrientationCamera; - } - /** - * The html button that is used to trigger entering into VR. - */ - get vrButton() { - return this._btnVR; - } - get _teleportationRequestInitiated() { - const result = this._cameraGazer._teleportationRequestInitiated || - (this._leftController !== null && this._leftController._teleportationRequestInitiated) || - (this._rightController !== null && this._rightController._teleportationRequestInitiated); - return result; - } - /** - * Instantiates a VRExperienceHelper. - * Helps to quickly add VR support to an existing scene. - * @param scene The scene the VRExperienceHelper belongs to. - * @param webVROptions Options to modify the vr experience helper's behavior. - */ - constructor(scene, - /** Options to modify the vr experience helper's behavior. */ - webVROptions = {}) { - this.webVROptions = webVROptions; - // Can the system support WebVR, even if a headset isn't plugged in? - this._webVRsupported = false; - // If WebVR is supported, is a headset plugged in and are we ready to present? - this._webVRready = false; - // Are we waiting for the requestPresent callback to complete? - this._webVRrequesting = false; - // Are we presenting to the headset right now? (this is the vrDevice state) - this._webVRpresenting = false; - // Are we presenting in the fullscreen fallback? - this._fullscreenVRpresenting = false; - /** - * 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) - */ - this.enableGazeEvenWhenNoPointerLock = false; - /** - * Gets or sets a boolean indicating that the VREXperienceHelper will exit VR if double tap is detected - */ - this.exitVROnDoubleTap = true; - /** - * Observable raised right before entering VR. - */ - this.onEnteringVRObservable = new observable_Observable(); - /** - * Observable raised when entering VR has completed. - */ - this.onAfterEnteringVRObservable = new observable_Observable(); - /** - * Observable raised when exiting VR. - */ - this.onExitingVRObservable = new observable_Observable(); - /** - * Observable raised when controller mesh is loaded. - */ - this.onControllerMeshLoadedObservable = new observable_Observable(); - this._useCustomVRButton = false; - this._teleportationRequested = false; - this._teleportActive = false; - this._floorMeshesCollection = []; - this._teleportationMode = VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME; - this._teleportationTime = 122; - this._teleportationSpeed = 20; - this._rotationAllowed = true; - this._teleportBackwardsVector = new math_vector_Vector3(0, -1, -1); - this._isDefaultTeleportationTarget = true; - this._teleportationFillColor = "#444444"; - this._teleportationBorderColor = "#FFFFFF"; - this._rotationAngle = 0; - this._haloCenter = new math_vector_Vector3(0, 0, 0); - this._padSensibilityUp = 0.65; - this._padSensibilityDown = 0.35; - this._leftController = null; - this._rightController = null; - this._gazeColor = new math_color_Color3(0.7, 0.7, 0.7); - this._laserColor = new math_color_Color3(0.7, 0.7, 0.7); - this._pickedLaserColor = new math_color_Color3(0.2, 0.2, 1); - this._pickedGazeColor = new math_color_Color3(0, 0, 1); - /** - * Observable raised when a new mesh is selected based on meshSelectionPredicate - */ - this.onNewMeshSelected = new observable_Observable(); - /** - * Observable raised when a new mesh is selected based on meshSelectionPredicate. - * This observable will provide the mesh and the controller used to select the mesh - */ - this.onMeshSelectedWithController = new observable_Observable(); - /** - * Observable raised when a new mesh is picked based on meshSelectionPredicate - */ - this.onNewMeshPicked = new observable_Observable(); - /** - * Observable raised before camera teleportation - */ - this.onBeforeCameraTeleport = new observable_Observable(); - /** - * Observable raised after camera teleportation - */ - this.onAfterCameraTeleport = new observable_Observable(); - /** - * Observable raised when current selected mesh gets unselected - */ - this.onSelectedMeshUnselected = new observable_Observable(); - /** - * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept. - */ - this.teleportationEnabled = true; - this._teleportationInitialized = false; - this._interactionsEnabled = false; - this._interactionsRequested = false; - this._displayGaze = true; - this._displayLaserPointer = true; - /** - * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes - */ - this.updateGazeTrackerScale = true; - /** - * If the gaze trackers color should be updated when selecting meshes - */ - this.updateGazeTrackerColor = true; - /** - * If the controller laser color should be updated when selecting meshes - */ - this.updateControllerLaserColor = true; - /** - * Defines whether or not Pointer lock should be requested when switching to - * full screen. - */ - this.requestPointerLockOnFullScreen = true; - /** - * Was the XR test done already. If this is true AND this.xr exists, xr is initialized. - * If this is true and no this.xr, xr exists but is not supported, using WebVR. - */ - this.xrTestDone = false; - this._onResize = () => { - this._moveButtonToBottomRight(); - if (this._fullscreenVRpresenting && this._webVRready) { - this.exitVR(); - } - }; - this._onFullscreenChange = () => { - this._fullscreenVRpresenting = !!document.fullscreenElement; - if (!this._fullscreenVRpresenting && this._inputElement) { - this.exitVR(); - if (!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"; - // make sure the button is visible after setting its position - this._updateButtonVisibility(); - } - } - }; - this._cachedAngularSensibility = { angularSensibilityX: null, angularSensibilityY: null, angularSensibility: null }; - this._beforeRender = () => { - if (this._leftController && this._leftController._activePointer) { - this._castRayAndSelectObject(this._leftController); - } - if (this._rightController && this._rightController._activePointer) { - this._castRayAndSelectObject(this._rightController); - } - if (this._noControllerIsActive && (this._scene.getEngine().isPointerLock || this.enableGazeEvenWhenNoPointerLock)) { - this._castRayAndSelectObject(this._cameraGazer); - } - else { - this._cameraGazer._gazeTracker.isVisible = false; - } - }; - this._onNewGamepadConnected = (gamepad) => { - if (gamepad.type !== Gamepad.POSE_ENABLED) { - if (gamepad.leftStick) { - gamepad.onleftstickchanged((stickValues) => { - if (this._teleportationInitialized && this.teleportationEnabled) { - // Listening to classic/xbox gamepad only if no VR controller is active - if ((!this._leftController && !this._rightController) || - (this._leftController && !this._leftController._activePointer && this._rightController && !this._rightController._activePointer)) { - this._checkTeleportWithRay(stickValues, this._cameraGazer); - this._checkTeleportBackwards(stickValues, this._cameraGazer); - } - } - }); - } - if (gamepad.rightStick) { - gamepad.onrightstickchanged((stickValues) => { - if (this._teleportationInitialized) { - this._checkRotate(stickValues, this._cameraGazer); - } - }); - } - if (gamepad.type === Gamepad.XBOX) { - gamepad.onbuttondown((buttonPressed) => { - if (this._interactionsEnabled && buttonPressed === Xbox360Button.A) { - this._cameraGazer._selectionPointerDown(); - } - }); - gamepad.onbuttonup((buttonPressed) => { - if (this._interactionsEnabled && buttonPressed === Xbox360Button.A) { - this._cameraGazer._selectionPointerUp(); - } - }); - } - } - else { - const webVRController = gamepad; - const controller = new VRExperienceHelperControllerGazer(webVRController, this._scene, this._cameraGazer._gazeTracker); - if (webVRController.hand === "right" || (this._leftController && this._leftController.webVRController != webVRController)) { - this._rightController = controller; - } - else { - this._leftController = controller; - } - this._tryEnableInteractionOnController(controller); - } - }; - // 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 - this._tryEnableInteractionOnController = (controller) => { - if (this._interactionsRequested && !controller._interactionsEnabled) { - this._enableInteractionOnController(controller); - } - if (this._teleportationRequested && !controller._teleportationEnabled) { - this._enableTeleportationOnController(controller); - } - }; - this._onNewGamepadDisconnected = (gamepad) => { - if (gamepad instanceof WebVRController) { - if (gamepad.hand === "left" && this._leftController != null) { - this._leftController.dispose(); - this._leftController = null; - } - if (gamepad.hand === "right" && this._rightController != null) { - this._rightController.dispose(); - this._rightController = null; - } - } - }; - this._workingVector = math_vector_Vector3.Zero(); - this._workingQuaternion = math_vector_Quaternion.Identity(); - this._workingMatrix = math_vector_Matrix.Identity(); - logger_Logger.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"); - this._scene = scene; - this._inputElement = scene.getEngine().getInputElement(); - // check for VR support: - const vrSupported = "getVRDisplays" in navigator; - // no VR support? force XR but only when it is not set because web vr can work without the getVRDisplays - if (!vrSupported && webVROptions.useXR === undefined) { - webVROptions.useXR = true; - } - // Parse options - if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) { - webVROptions.createFallbackVRDeviceOrientationFreeCamera = true; - } - if (webVROptions.createDeviceOrientationCamera === undefined) { - webVROptions.createDeviceOrientationCamera = true; - } - if (webVROptions.laserToggle === undefined) { - webVROptions.laserToggle = true; - } - if (webVROptions.defaultHeight === undefined) { - webVROptions.defaultHeight = 1.7; - } - if (webVROptions.useCustomVRButton) { - this._useCustomVRButton = true; - if (webVROptions.customVRButton) { - this._btnVR = webVROptions.customVRButton; - } - } - if (webVROptions.rayLength) { - this._rayLength = webVROptions.rayLength; - } - this._defaultHeight = webVROptions.defaultHeight; - if (webVROptions.positionScale) { - this._rayLength *= webVROptions.positionScale; - this._defaultHeight *= webVROptions.positionScale; - } - this._hasEnteredVR = false; - // Set position - if (this._scene.activeCamera) { - this._position = this._scene.activeCamera.position.clone(); - } - else { - this._position = new math_vector_Vector3(0, this._defaultHeight, 0); - } - // Set non-vr camera - if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) { - this._deviceOrientationCamera = new DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene); - // Copy data from existing camera - if (this._scene.activeCamera) { - this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ; - this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ; - // Set rotation from previous camera - if (this._scene.activeCamera instanceof targetCamera_TargetCamera && this._scene.activeCamera.rotation) { - const targetCamera = this._scene.activeCamera; - if (targetCamera.rotationQuaternion) { - this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion); - } - else { - this._deviceOrientationCamera.rotationQuaternion.copyFrom(math_vector_Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z)); - } - this._deviceOrientationCamera.rotation = targetCamera.rotation.clone(); - } - } - this._scene.activeCamera = this._deviceOrientationCamera; - if (this._inputElement) { - this._scene.activeCamera.attachControl(); - } - } - else { - this._existingCamera = this._scene.activeCamera; - } - if (this.webVROptions.useXR && navigator.xr) { - // force-check XR session support - WebXRSessionManager.IsSessionSupportedAsync("immersive-vr").then((supported) => { - if (supported) { - logger_Logger.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"); - // it is possible to use XR, let's do it! - scene - .createDefaultXRExperienceAsync({ - floorMeshes: webVROptions.floorMeshes || [], - }) - .then((xr) => { - this.xr = xr; - // connect observables - this.xrTestDone = true; - this._cameraGazer = new VRExperienceHelperCameraGazer(() => { - return this.xr.baseExperience.camera; - }, scene); - this.xr.baseExperience.onStateChangedObservable.add((state) => { - // support for entering / exiting - switch (state) { - case WebXRState.ENTERING_XR: - this.onEnteringVRObservable.notifyObservers(this); - if (!this._interactionsEnabled) { - this.xr.pointerSelection.detach(); - } - this.xr.pointerSelection.displayLaserPointer = this._displayLaserPointer; - break; - case WebXRState.EXITING_XR: - this.onExitingVRObservable.notifyObservers(this); - // resize to update width and height when exiting vr exits fullscreen - this._scene.getEngine().resize(); - break; - case WebXRState.IN_XR: - this._hasEnteredVR = true; - break; - case WebXRState.NOT_IN_XR: - this._hasEnteredVR = false; - break; - } - }); - }); - } - else { - // XR not supported (thou exists), continue WebVR init - this._completeVRInit(scene, webVROptions); - } - }); - } - else { - // no XR, continue init synchronous - this._completeVRInit(scene, webVROptions); - } - } - _completeVRInit(scene, webVROptions) { - this.xrTestDone = true; - // Create VR cameras - if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) { - if (webVROptions.useMultiview) { - if (!webVROptions.vrDeviceOrientationCameraMetrics) { - webVROptions.vrDeviceOrientationCameraMetrics = VRCameraMetrics.GetDefault(); - } - webVROptions.vrDeviceOrientationCameraMetrics.multiviewEnabled = true; - } - this._vrDeviceOrientationCamera = new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene, true, webVROptions.vrDeviceOrientationCameraMetrics); - this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE; - } - this._webVRCamera = new WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions); - this._webVRCamera.useStandingMatrix(); - this._cameraGazer = new VRExperienceHelperCameraGazer(() => { - return this.currentVRCamera; - }, scene); - // Create default button - if (!this._useCustomVRButton) { - this._btnVR = document.createElement("BUTTON"); - this._btnVR.className = "babylonVRicon"; - this._btnVR.id = "babylonVRiconbtn"; - this._btnVR.title = "Click to switch to VR"; - const url = !window.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"; - let css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(" + - url + - "); 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) }"; - css += ".babylonVRicon.vrdisplaypresenting { display: none; }"; - // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR) - // css += ".babylonVRicon.vrdisplaysupported { }"; - // css += ".babylonVRicon.vrdisplayready { }"; - // css += ".babylonVRicon.vrdisplayrequesting { }"; - const style = document.createElement("style"); - style.appendChild(document.createTextNode(css)); - document.getElementsByTagName("head")[0].appendChild(style); - this._moveButtonToBottomRight(); - } - // VR button click event - if (this._btnVR) { - this._btnVR.addEventListener("click", () => { - if (!this.isInVRMode) { - this.enterVR(); - } - else { - this._scene.getEngine().disableVR(); - } - }); - } - // Window events - const hostWindow = this._scene.getEngine().getHostWindow(); - if (!hostWindow) { - return; - } - hostWindow.addEventListener("resize", this._onResize); - document.addEventListener("fullscreenchange", this._onFullscreenChange, false); - // Display vr button when headset is connected - if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) { - this._displayVRButton(); - } - else { - this._scene.getEngine().onVRDisplayChangedObservable.add((e) => { - if (e.vrDisplay) { - this._displayVRButton(); - } - }); - } - // Exiting VR mode using 'ESC' key on desktop - this._onKeyDown = (event) => { - if (event.keyCode === 27 && this.isInVRMode) { - this.exitVR(); - } - }; - document.addEventListener("keydown", this._onKeyDown); - // Exiting VR mode double tapping the touch screen - this._scene.onPrePointerObservable.add(() => { - if (this._hasEnteredVR && this.exitVROnDoubleTap) { - this.exitVR(); - if (this._fullscreenVRpresenting) { - this._scene.getEngine().exitFullscreen(); - } - } - }, pointerEvents_PointerEventTypes.POINTERDOUBLETAP, false); - // Listen for WebVR display changes - this._onVRDisplayChangedBind = (eventArgs) => this._onVRDisplayChanged(eventArgs); - this._onVrDisplayPresentChangeBind = () => this._onVrDisplayPresentChange(); - this._onVRRequestPresentStart = () => { - this._webVRrequesting = true; - this._updateButtonVisibility(); - }; - this._onVRRequestPresentComplete = () => { - this._webVRrequesting = false; - this._updateButtonVisibility(); - }; - scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChangedBind); - scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart); - scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete); - hostWindow.addEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChangeBind); - scene.onDisposeObservable.add(() => { - this.dispose(); - }); - // Gamepad connection events - this._webVRCamera.onControllerMeshLoadedObservable.add((webVRController) => this._onDefaultMeshLoaded(webVRController)); - this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected); - this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected); - this._updateButtonVisibility(); - //create easing functions - this._circleEase = new CircleEase(); - this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT); - this._teleportationEasing = this._circleEase; - // Allow clicking in the vrDeviceOrientationCamera - scene.onPointerObservable.add((e) => { - if (this._interactionsEnabled) { - if (scene.activeCamera === this.vrDeviceOrientationCamera && e.event.pointerType === "mouse") { - if (e.type === pointerEvents_PointerEventTypes.POINTERDOWN) { - this._cameraGazer._selectionPointerDown(); - } - else if (e.type === pointerEvents_PointerEventTypes.POINTERUP) { - this._cameraGazer._selectionPointerUp(); - } - } - } - }); - if (this.webVROptions.floorMeshes) { - this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes }); - } - } - // Raised when one of the controller has loaded successfully its associated default mesh - _onDefaultMeshLoaded(webVRController) { - if (this._leftController && this._leftController.webVRController == webVRController) { - if (webVRController.mesh) { - this._leftController._setLaserPointerParent(webVRController.mesh); - } - } - if (this._rightController && this._rightController.webVRController == webVRController) { - if (webVRController.mesh) { - this._rightController._setLaserPointerParent(webVRController.mesh); - } - } - try { - this.onControllerMeshLoadedObservable.notifyObservers(webVRController); - } - catch (err) { - logger_Logger.Warn("Error in your custom logic onControllerMeshLoaded: " + err); - } - } - /** - * Gets a value indicating if we are currently in VR mode. - */ - get isInVRMode() { - return (this.xr && this.webVROptions.useXR && this.xr.baseExperience.state === WebXRState.IN_XR) || this._webVRpresenting || this._fullscreenVRpresenting; - } - _onVrDisplayPresentChange() { - const vrDisplay = this._scene.getEngine().getVRDevice(); - if (vrDisplay) { - const wasPresenting = this._webVRpresenting; - this._webVRpresenting = vrDisplay.isPresenting; - if (wasPresenting && !this._webVRpresenting) { - this.exitVR(); - } - } - else { - logger_Logger.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?"); - } - this._updateButtonVisibility(); - } - _onVRDisplayChanged(eventArgs) { - this._webVRsupported = eventArgs.vrSupported; - this._webVRready = !!eventArgs.vrDisplay; - this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting; - this._updateButtonVisibility(); - } - _moveButtonToBottomRight() { - if (this._inputElement && !this._useCustomVRButton && this._btnVR) { - const rect = this._inputElement.getBoundingClientRect(); - this._btnVR.style.top = rect.top + rect.height - 70 + "px"; - this._btnVR.style.left = rect.left + rect.width - 100 + "px"; - } - } - _displayVRButton() { - if (!this._useCustomVRButton && !this._btnVRDisplayed && this._btnVR) { - document.body.appendChild(this._btnVR); - this._btnVRDisplayed = true; - } - } - _updateButtonVisibility() { - if (!this._btnVR || this._useCustomVRButton) { - return; - } - this._btnVR.className = "babylonVRicon"; - if (this.isInVRMode) { - this._btnVR.className += " vrdisplaypresenting"; - } - else { - if (this._webVRready) { - this._btnVR.className += " vrdisplayready"; - } - if (this._webVRsupported) { - this._btnVR.className += " vrdisplaysupported"; - } - if (this._webVRrequesting) { - this._btnVR.className += " vrdisplayrequesting"; - } - } - } - /** - * Attempt to enter VR. If a headset is connected and ready, will request present on that. - * Otherwise, will use the fullscreen API. - */ - enterVR() { - if (this.xr) { - this.xr.baseExperience.enterXRAsync("immersive-vr", "local-floor", this.xr.renderTarget); - return; - } - if (this.onEnteringVRObservable) { - try { - this.onEnteringVRObservable.notifyObservers(this); - } - catch (err) { - logger_Logger.Warn("Error in your custom logic onEnteringVR: " + err); - } - } - if (this._scene.activeCamera) { - this._position = this._scene.activeCamera.position.clone(); - if (this.vrDeviceOrientationCamera) { - this.vrDeviceOrientationCamera.rotation = math_vector_Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(); - this.vrDeviceOrientationCamera.angularSensibility = 2000; - } - if (this.webVRCamera) { - const currentYRotation = this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y; - const desiredYRotation = math_vector_Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y; - const delta = desiredYRotation - currentYRotation; - const currentGlobalRotation = this.webVRCamera.rotationQuaternion.toEulerAngles().y; - this.webVRCamera.rotationQuaternion = math_vector_Quaternion.FromEulerAngles(0, currentGlobalRotation + delta, 0); - } - // make sure that we return to the last active camera - this._existingCamera = this._scene.activeCamera; - // Remove and cache angular sensability to avoid camera rotation when in VR - if (this._existingCamera.angularSensibilityX) { - this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX; - this._existingCamera.angularSensibilityX = Number.MAX_VALUE; - } - if (this._existingCamera.angularSensibilityY) { - this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY; - this._existingCamera.angularSensibilityY = Number.MAX_VALUE; - } - if (this._existingCamera.angularSensibility) { - this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility; - this._existingCamera.angularSensibility = Number.MAX_VALUE; - } - } - if (this._webVRrequesting) { - return; - } - // If WebVR is supported and a headset is connected - if (this._webVRready) { - if (!this._webVRpresenting) { - this._scene.getEngine().onVRRequestPresentComplete.addOnce((result) => { - this.onAfterEnteringVRObservable.notifyObservers({ success: result }); - }); - this._webVRCamera.position = this._position; - this._scene.activeCamera = this._webVRCamera; - } - } - else if (this._vrDeviceOrientationCamera) { - this._vrDeviceOrientationCamera.position = this._position; - if (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: true }); - }); - } - if (this._scene.activeCamera && this._inputElement) { - this._scene.activeCamera.attachControl(); - } - if (this._interactionsEnabled) { - this._scene.registerBeforeRender(this._beforeRender); - } - if (this._displayLaserPointer) { - [this._leftController, this._rightController].forEach((controller) => { - if (controller) { - controller._activatePointer(); - } - }); - } - this._hasEnteredVR = true; - } - /** - * Attempt to exit VR, or fullscreen. - */ - exitVR() { - if (this.xr) { - this.xr.baseExperience.exitXRAsync(); - return; - } - if (this._hasEnteredVR) { - if (this.onExitingVRObservable) { - try { - this.onExitingVRObservable.notifyObservers(this); - } - catch (err) { - logger_Logger.Warn("Error in your custom logic onExitingVR: " + err); - } - } - if (this._webVRpresenting) { - this._scene.getEngine().disableVR(); - } - if (this._scene.activeCamera) { - this._position = this._scene.activeCamera.position.clone(); - } - if (this.vrDeviceOrientationCamera) { - this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE; - } - if (this._deviceOrientationCamera) { - this._deviceOrientationCamera.position = this._position; - this._scene.activeCamera = this._deviceOrientationCamera; - // Restore angular sensibility - if (this._cachedAngularSensibility.angularSensibilityX) { - this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX; - this._cachedAngularSensibility.angularSensibilityX = null; - } - if (this._cachedAngularSensibility.angularSensibilityY) { - this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY; - this._cachedAngularSensibility.angularSensibilityY = null; - } - if (this._cachedAngularSensibility.angularSensibility) { - this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility; - this._cachedAngularSensibility.angularSensibility = null; - } - } - else if (this._existingCamera) { - this._existingCamera.position = this._position; - this._scene.activeCamera = this._existingCamera; - if (this._inputElement) { - this._scene.activeCamera.attachControl(); - } - // Restore angular sensibility - if (this._cachedAngularSensibility.angularSensibilityX) { - this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX; - this._cachedAngularSensibility.angularSensibilityX = null; - } - if (this._cachedAngularSensibility.angularSensibilityY) { - this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY; - this._cachedAngularSensibility.angularSensibilityY = null; - } - if (this._cachedAngularSensibility.angularSensibility) { - this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility; - this._cachedAngularSensibility.angularSensibility = null; - } - } - this._updateButtonVisibility(); - if (this._interactionsEnabled) { - this._scene.unregisterBeforeRender(this._beforeRender); - this._cameraGazer._gazeTracker.isVisible = false; - if (this._leftController) { - this._leftController._gazeTracker.isVisible = false; - } - if (this._rightController) { - this._rightController._gazeTracker.isVisible = false; - } - } - // resize to update width and height when exiting vr exits fullscreen - this._scene.getEngine().resize(); - [this._leftController, this._rightController].forEach((controller) => { - if (controller) { - controller._deactivatePointer(); - } - }); - this._hasEnteredVR = false; - // Update engine state to re enable non-vr camera input - const engine = this._scene.getEngine(); - if (engine._onVrDisplayPresentChange) { - engine._onVrDisplayPresentChange(); - } - } - } - /** - * The position of the vr experience helper. - */ - get position() { - return this._position; - } - /** - * Sets the position of the vr experience helper. - */ - set position(value) { - this._position = value; - if (this._scene.activeCamera) { - this._scene.activeCamera.position = value; - } - } - /** - * Enables controllers and user interactions such as selecting and object or clicking on an object. - */ - enableInteractions() { - if (!this._interactionsEnabled) { - this._interactionsRequested = true; - // in XR it is enabled by default, but just to make sure, re-attach - if (this.xr) { - if (this.xr.baseExperience.state === WebXRState.IN_XR) { - this.xr.pointerSelection.attach(); - } - return; - } - if (this._leftController) { - this._enableInteractionOnController(this._leftController); - } - if (this._rightController) { - this._enableInteractionOnController(this._rightController); - } - this.raySelectionPredicate = (mesh) => { - return mesh.isVisible && (mesh.isPickable || mesh.name === this._floorMeshName); - }; - this.meshSelectionPredicate = () => { - return true; - }; - this._raySelectionPredicate = (mesh) => { - if (this._isTeleportationFloor(mesh) || - (mesh.name.indexOf("gazeTracker") === -1 && mesh.name.indexOf("teleportationTarget") === -1 && mesh.name.indexOf("torusTeleportation") === -1)) { - return this.raySelectionPredicate(mesh); - } - return false; - }; - this._interactionsEnabled = true; - } - } - get _noControllerIsActive() { - return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer); - } - _isTeleportationFloor(mesh) { - for (let i = 0; i < this._floorMeshesCollection.length; i++) { - if (this._floorMeshesCollection[i].id === mesh.id) { - return true; - } - } - if (this._floorMeshName && mesh.name === this._floorMeshName) { - return true; - } - return false; - } - /** - * Adds a floor mesh to be used for teleportation. - * @param floorMesh the mesh to be used for teleportation. - */ - addFloorMesh(floorMesh) { - if (!this._floorMeshesCollection) { - return; - } - if (this._floorMeshesCollection.indexOf(floorMesh) > -1) { - return; - } - this._floorMeshesCollection.push(floorMesh); - } - /** - * Removes a floor mesh from being used for teleportation. - * @param floorMesh the mesh to be removed. - */ - removeFloorMesh(floorMesh) { - if (!this._floorMeshesCollection) { - return; - } - const meshIndex = this._floorMeshesCollection.indexOf(floorMesh); - if (meshIndex !== -1) { - this._floorMeshesCollection.splice(meshIndex, 1); - } - } - /** - * Enables interactions and teleportation using the VR controllers and gaze. - * @param vrTeleportationOptions options to modify teleportation behavior. - */ - enableTeleportation(vrTeleportationOptions = {}) { - if (!this._teleportationInitialized) { - this._teleportationRequested = true; - this.enableInteractions(); - if (this.webVROptions.useXR && (vrTeleportationOptions.floorMeshes || vrTeleportationOptions.floorMeshName)) { - const floorMeshes = vrTeleportationOptions.floorMeshes || []; - if (!floorMeshes.length) { - const floorMesh = this._scene.getMeshByName(vrTeleportationOptions.floorMeshName); - if (floorMesh) { - floorMeshes.push(floorMesh); - } - } - if (this.xr) { - floorMeshes.forEach((mesh) => { - this.xr.teleportation.addFloorMesh(mesh); - }); - if (!this.xr.teleportation.attached) { - this.xr.teleportation.attach(); - } - return; - } - else if (!this.xrTestDone) { - const waitForXr = () => { - if (this.xrTestDone) { - this._scene.unregisterBeforeRender(waitForXr); - if (this.xr) { - if (!this.xr.teleportation.attached) { - this.xr.teleportation.attach(); - } - } - else { - this.enableTeleportation(vrTeleportationOptions); - } - } - }; - this._scene.registerBeforeRender(waitForXr); - return; - } - } - if (vrTeleportationOptions.floorMeshName) { - this._floorMeshName = vrTeleportationOptions.floorMeshName; - } - if (vrTeleportationOptions.floorMeshes) { - this._floorMeshesCollection = vrTeleportationOptions.floorMeshes; - } - if (vrTeleportationOptions.teleportationMode) { - this._teleportationMode = vrTeleportationOptions.teleportationMode; - } - if (vrTeleportationOptions.teleportationTime && vrTeleportationOptions.teleportationTime > 0) { - this._teleportationTime = vrTeleportationOptions.teleportationTime; - } - if (vrTeleportationOptions.teleportationSpeed && vrTeleportationOptions.teleportationSpeed > 0) { - this._teleportationSpeed = vrTeleportationOptions.teleportationSpeed; - } - if (vrTeleportationOptions.easingFunction !== undefined) { - this._teleportationEasing = vrTeleportationOptions.easingFunction; - } - if (this._leftController != null) { - this._enableTeleportationOnController(this._leftController); - } - if (this._rightController != null) { - this._enableTeleportationOnController(this._rightController); - } - // Creates an image processing post process for the vignette not relying - // on the main scene configuration for image processing to reduce setup and spaces - // (gamma/linear) conflicts. - const imageProcessingConfiguration = new ImageProcessingConfiguration(); - imageProcessingConfiguration.vignetteColor = new math_color_Color4(0, 0, 0, 0); - imageProcessingConfiguration.vignetteEnabled = true; - this._postProcessMove = new ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration); - this._webVRCamera.detachPostProcess(this._postProcessMove); - this._teleportationInitialized = true; - if (this._isDefaultTeleportationTarget) { - this._createTeleportationCircles(); - this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor); - } - } - } - _enableInteractionOnController(controller) { - const controllerMesh = controller.webVRController.mesh; - if (controllerMesh) { - controller._interactionsEnabled = true; - if (this.isInVRMode && this._displayLaserPointer) { - controller._activatePointer(); - } - if (this.webVROptions.laserToggle) { - controller.webVRController.onMainButtonStateChangedObservable.add((stateObject) => { - // Enabling / disabling laserPointer - if (this._displayLaserPointer && stateObject.value === 1) { - if (controller._activePointer) { - controller._deactivatePointer(); - } - else { - controller._activatePointer(); - } - if (this.displayGaze) { - controller._gazeTracker.isVisible = controller._activePointer; - } - } - }); - } - controller.webVRController.onTriggerStateChangedObservable.add((stateObject) => { - let gazer = controller; - if (this._noControllerIsActive) { - gazer = this._cameraGazer; - } - if (!gazer._pointerDownOnMeshAsked) { - if (stateObject.value > this._padSensibilityUp) { - gazer._selectionPointerDown(); - } - } - else if (stateObject.value < this._padSensibilityDown) { - gazer._selectionPointerUp(); - } - }); - } - } - _checkTeleportWithRay(stateObject, gazer) { - // Dont teleport if another gaze already requested teleportation - if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) { - return; - } - if (!gazer._teleportationRequestInitiated) { - if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) { - gazer._activatePointer(); - gazer._teleportationRequestInitiated = true; - } - } - else { - // Listening to the proper controller values changes to confirm teleportation - if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) { - if (this._teleportActive) { - this.teleportCamera(this._haloCenter); - } - gazer._teleportationRequestInitiated = false; - } - } - } - _checkRotate(stateObject, gazer) { - // Only rotate when user is not currently selecting a teleportation location - if (gazer._teleportationRequestInitiated) { - return; - } - if (!gazer._rotationLeftAsked) { - if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) { - gazer._rotationLeftAsked = true; - if (this._rotationAllowed) { - this._rotateCamera(false); - } - } - } - else { - if (stateObject.x > -this._padSensibilityDown) { - gazer._rotationLeftAsked = false; - } - } - if (!gazer._rotationRightAsked) { - if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) { - gazer._rotationRightAsked = true; - if (this._rotationAllowed) { - this._rotateCamera(true); - } - } - } - else { - if (stateObject.x < this._padSensibilityDown) { - gazer._rotationRightAsked = false; - } - } - } - _checkTeleportBackwards(stateObject, gazer) { - // Only teleport backwards when user is not currently selecting a teleportation location - if (gazer._teleportationRequestInitiated) { - return; - } - // Teleport backwards - if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) { - if (!gazer._teleportationBackRequestInitiated) { - if (!this.currentVRCamera) { - return; - } - // Get rotation and position of the current camera - let rotation = math_vector_Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()); - let position = this.currentVRCamera.position; - // If the camera has device position, use that instead - if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) { - rotation = this.currentVRCamera.deviceRotationQuaternion; - position = this.currentVRCamera.devicePosition; - } - // Get matrix with only the y rotation of the device rotation - rotation.toEulerAnglesToRef(this._workingVector); - this._workingVector.z = 0; - this._workingVector.x = 0; - math_vector_Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion); - this._workingQuaternion.toRotationMatrix(this._workingMatrix); - // Rotate backwards ray by device rotation to cast at the ground behind the user - math_vector_Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector); - // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff - const ray = new ray_Ray(position, this._workingVector); - const hit = this._scene.pickWithRay(ray, this._raySelectionPredicate); - if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) { - this.teleportCamera(hit.pickedPoint); - } - gazer._teleportationBackRequestInitiated = true; - } - } - else { - gazer._teleportationBackRequestInitiated = false; - } - } - _enableTeleportationOnController(controller) { - const controllerMesh = controller.webVRController.mesh; - if (controllerMesh) { - if (!controller._interactionsEnabled) { - this._enableInteractionOnController(controller); - } - controller._interactionsEnabled = true; - controller._teleportationEnabled = true; - if (controller.webVRController.controllerType === PoseEnabledControllerType.VIVE) { - controller._dpadPressed = false; - controller.webVRController.onPadStateChangedObservable.add((stateObject) => { - controller._dpadPressed = stateObject.pressed; - if (!controller._dpadPressed) { - controller._rotationLeftAsked = false; - controller._rotationRightAsked = false; - controller._teleportationBackRequestInitiated = false; - } - }); - } - controller.webVRController.onPadValuesChangedObservable.add((stateObject) => { - if (this.teleportationEnabled) { - this._checkTeleportBackwards(stateObject, controller); - this._checkTeleportWithRay(stateObject, controller); - } - this._checkRotate(stateObject, controller); - }); - } - } - _createTeleportationCircles() { - this._teleportationTarget = CreateGround("teleportationTarget", { width: 2, height: 2, subdivisions: 2 }, this._scene); - this._teleportationTarget.isPickable = false; - const length = 512; - const dynamicTexture = new dynamicTexture_DynamicTexture("DynamicTexture", length, this._scene, true); - dynamicTexture.hasAlpha = true; - const context = dynamicTexture.getContext(); - const centerX = length / 2; - const centerY = length / 2; - const radius = 200; - context.beginPath(); - context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); - context.fillStyle = this._teleportationFillColor; - context.fill(); - context.lineWidth = 10; - context.strokeStyle = this._teleportationBorderColor; - context.stroke(); - context.closePath(); - dynamicTexture.update(); - const teleportationCircleMaterial = new standardMaterial_StandardMaterial("TextPlaneMaterial", this._scene); - teleportationCircleMaterial.diffuseTexture = dynamicTexture; - this._teleportationTarget.material = teleportationCircleMaterial; - const torus = CreateTorus("torusTeleportation", { - diameter: 0.75, - thickness: 0.1, - tessellation: 25, - updatable: false, - }, this._scene); - torus.isPickable = false; - torus.parent = this._teleportationTarget; - const animationInnerCircle = new animation_Animation("animationInnerCircle", "position.y", 30, animation_Animation.ANIMATIONTYPE_FLOAT, animation_Animation.ANIMATIONLOOPMODE_CYCLE); - const keys = []; - keys.push({ - frame: 0, - value: 0, - }); - keys.push({ - frame: 30, - value: 0.4, - }); - keys.push({ - frame: 60, - value: 0, - }); - animationInnerCircle.setKeys(keys); - const easingFunction = new SineEase(); - easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT); - animationInnerCircle.setEasingFunction(easingFunction); - torus.animations = []; - torus.animations.push(animationInnerCircle); - this._scene.beginAnimation(torus, 0, 60, true); - this._hideTeleportationTarget(); - } - _displayTeleportationTarget() { - this._teleportActive = true; - if (this._teleportationInitialized) { - this._teleportationTarget.isVisible = true; - if (this._isDefaultTeleportationTarget) { - this._teleportationTarget.getChildren()[0].isVisible = true; - } - } - } - _hideTeleportationTarget() { - this._teleportActive = false; - if (this._teleportationInitialized) { - this._teleportationTarget.isVisible = false; - if (this._isDefaultTeleportationTarget) { - this._teleportationTarget.getChildren()[0].isVisible = false; - } - } - } - _rotateCamera(right) { - if (!(this.currentVRCamera instanceof FreeCamera)) { - return; - } - if (right) { - this._rotationAngle++; - } - else { - this._rotationAngle--; - } - this.currentVRCamera.animations = []; - const target = math_vector_Quaternion.FromRotationMatrix(math_vector_Matrix.RotationY((Math.PI / 4) * this._rotationAngle)); - const animationRotation = new animation_Animation("animationRotation", "rotationQuaternion", 90, animation_Animation.ANIMATIONTYPE_QUATERNION, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - const animationRotationKeys = []; - animationRotationKeys.push({ - frame: 0, - value: this.currentVRCamera.rotationQuaternion, - }); - animationRotationKeys.push({ - frame: 6, - value: target, - }); - animationRotation.setKeys(animationRotationKeys); - animationRotation.setEasingFunction(this._circleEase); - this.currentVRCamera.animations.push(animationRotation); - this._postProcessMove.animations = []; - const animationPP = new animation_Animation("animationPP", "vignetteWeight", 90, animation_Animation.ANIMATIONTYPE_FLOAT, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - const vignetteWeightKeys = []; - vignetteWeightKeys.push({ - frame: 0, - value: 0, - }); - vignetteWeightKeys.push({ - frame: 3, - value: 4, - }); - vignetteWeightKeys.push({ - frame: 6, - value: 0, - }); - animationPP.setKeys(vignetteWeightKeys); - animationPP.setEasingFunction(this._circleEase); - this._postProcessMove.animations.push(animationPP); - const animationPP2 = new animation_Animation("animationPP2", "vignetteStretch", 90, animation_Animation.ANIMATIONTYPE_FLOAT, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - const vignetteStretchKeys = []; - vignetteStretchKeys.push({ - frame: 0, - value: 0, - }); - vignetteStretchKeys.push({ - frame: 3, - value: 10, - }); - vignetteStretchKeys.push({ - frame: 6, - value: 0, - }); - animationPP2.setKeys(vignetteStretchKeys); - animationPP2.setEasingFunction(this._circleEase); - this._postProcessMove.animations.push(animationPP2); - 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, false, 1, () => { - this._webVRCamera.detachPostProcess(this._postProcessMove); - }); - this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1); - } - _moveTeleportationSelectorTo(hit, gazer, ray) { - if (hit.pickedPoint) { - if (gazer._teleportationRequestInitiated) { - this._displayTeleportationTarget(); - this._haloCenter.copyFrom(hit.pickedPoint); - this._teleportationTarget.position.copyFrom(hit.pickedPoint); - } - const pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray); - if (pickNormal) { - const axis1 = math_vector_Vector3.Cross(math_axis_Axis.Y, pickNormal); - const axis2 = math_vector_Vector3.Cross(pickNormal, axis1); - math_vector_Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation); - } - this._teleportationTarget.position.y += 0.1; - } - } - /** - * Teleports the users feet to the desired location - * @param location The location where the user's feet should be placed - */ - teleportCamera(location) { - if (!(this.currentVRCamera instanceof FreeCamera)) { - return; - } - // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the - // offset of the headset from the anchor. - if (this.webVRCamera.leftCamera) { - this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition); - this._workingVector.subtractInPlace(this.webVRCamera.position); - location.subtractToRef(this._workingVector, this._workingVector); - } - else { - this._workingVector.copyFrom(location); - } - // Add height to account for user's height offset - if (this.isInVRMode) { - this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor; - } - else { - this._workingVector.y += this._defaultHeight; - } - this.onBeforeCameraTeleport.notifyObservers(this._workingVector); - // Animations FPS - const FPS = 90; - let speedRatio, lastFrame; - if (this._teleportationMode == VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED) { - lastFrame = FPS; - const dist = math_vector_Vector3.Distance(this.currentVRCamera.position, this._workingVector); - speedRatio = this._teleportationSpeed / dist; - } - else { - // teleportationMode is TELEPORTATIONMODE_CONSTANTTIME - lastFrame = Math.round((this._teleportationTime * FPS) / 1000); - speedRatio = 1; - } - // Create animation from the camera's position to the new location - this.currentVRCamera.animations = []; - const animationCameraTeleportation = new animation_Animation("animationCameraTeleportation", "position", FPS, animation_Animation.ANIMATIONTYPE_VECTOR3, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - const animationCameraTeleportationKeys = [ - { - frame: 0, - value: this.currentVRCamera.position, - }, - { - frame: lastFrame, - value: this._workingVector, - }, - ]; - animationCameraTeleportation.setKeys(animationCameraTeleportationKeys); - animationCameraTeleportation.setEasingFunction(this._teleportationEasing); - this.currentVRCamera.animations.push(animationCameraTeleportation); - this._postProcessMove.animations = []; - // Calculate the mid frame for vignette animations - const midFrame = Math.round(lastFrame / 2); - const animationPP = new animation_Animation("animationPP", "vignetteWeight", FPS, animation_Animation.ANIMATIONTYPE_FLOAT, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - const vignetteWeightKeys = []; - vignetteWeightKeys.push({ - frame: 0, - value: 0, - }); - vignetteWeightKeys.push({ - frame: midFrame, - value: 8, - }); - vignetteWeightKeys.push({ - frame: lastFrame, - value: 0, - }); - animationPP.setKeys(vignetteWeightKeys); - this._postProcessMove.animations.push(animationPP); - const animationPP2 = new animation_Animation("animationPP2", "vignetteStretch", FPS, animation_Animation.ANIMATIONTYPE_FLOAT, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - const vignetteStretchKeys = []; - vignetteStretchKeys.push({ - frame: 0, - value: 0, - }); - vignetteStretchKeys.push({ - frame: midFrame, - value: 10, - }); - vignetteStretchKeys.push({ - frame: lastFrame, - value: 0, - }); - animationPP2.setKeys(vignetteStretchKeys); - this._postProcessMove.animations.push(animationPP2); - this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0; - this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0; - this._webVRCamera.attachPostProcess(this._postProcessMove); - this._scene.beginAnimation(this._postProcessMove, 0, lastFrame, false, speedRatio, () => { - this._webVRCamera.detachPostProcess(this._postProcessMove); - }); - this._scene.beginAnimation(this.currentVRCamera, 0, lastFrame, false, speedRatio, () => { - this.onAfterCameraTeleport.notifyObservers(this._workingVector); - }); - this._hideTeleportationTarget(); - } - _convertNormalToDirectionOfRay(normal, ray) { - if (normal) { - const angle = Math.acos(math_vector_Vector3.Dot(normal, ray.direction)); - if (angle < Math.PI / 2) { - normal.scaleInPlace(-1); - } - } - return normal; - } - _castRayAndSelectObject(gazer) { - if (!(this.currentVRCamera instanceof FreeCamera)) { - return; - } - const ray = gazer._getForwardRay(this._rayLength); - const hit = this._scene.pickWithRay(ray, this._raySelectionPredicate); - if (hit) { - this._scene.simulatePointerMove(hit, { pointerId: gazer._id }); - } - gazer._currentHit = hit; - // Moving the gazeTracker on the mesh face targetted - if (hit && hit.pickedPoint) { - if (this._displayGaze) { - let multiplier = 1; - gazer._gazeTracker.isVisible = true; - if (gazer._isActionableMesh) { - multiplier = 3; - } - if (this.updateGazeTrackerScale) { - gazer._gazeTracker.scaling.x = hit.distance * multiplier; - gazer._gazeTracker.scaling.y = hit.distance * multiplier; - gazer._gazeTracker.scaling.z = hit.distance * multiplier; - } - const pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray); - // To avoid z-fighting - const deltaFighting = 0.002; - if (pickNormal) { - const axis1 = math_vector_Vector3.Cross(math_axis_Axis.Y, pickNormal); - const axis2 = math_vector_Vector3.Cross(pickNormal, axis1); - math_vector_Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation); - } - gazer._gazeTracker.position.copyFrom(hit.pickedPoint); - if (gazer._gazeTracker.position.x < 0) { - gazer._gazeTracker.position.x += deltaFighting; - } - else { - gazer._gazeTracker.position.x -= deltaFighting; - } - if (gazer._gazeTracker.position.y < 0) { - gazer._gazeTracker.position.y += deltaFighting; - } - else { - gazer._gazeTracker.position.y -= deltaFighting; - } - if (gazer._gazeTracker.position.z < 0) { - gazer._gazeTracker.position.z += deltaFighting; - } - else { - gazer._gazeTracker.position.z -= deltaFighting; - } - } - // Changing the size of the laser pointer based on the distance from the targetted point - gazer._updatePointerDistance(hit.distance); - } - else { - gazer._updatePointerDistance(); - gazer._gazeTracker.isVisible = false; - } - if (hit && hit.pickedMesh) { - // The object selected is the floor, we're in a teleportation scenario - if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) { - // Moving the teleportation area to this targetted point - //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected - if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) { - this._notifySelectedMeshUnselected(gazer._currentMeshSelected); - } - gazer._currentMeshSelected = null; - if (gazer._teleportationRequestInitiated) { - this._moveTeleportationSelectorTo(hit, gazer, ray); - } - return; - } - // If not, we're in a selection scenario - //this._teleportationAllowed = false; - if (hit.pickedMesh !== gazer._currentMeshSelected) { - if (this.meshSelectionPredicate(hit.pickedMesh)) { - this.onNewMeshPicked.notifyObservers(hit); - gazer._currentMeshSelected = hit.pickedMesh; - if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) { - this.changeGazeColor(this._pickedGazeColor); - this.changeLaserColor(this._pickedLaserColor); - gazer._isActionableMesh = true; - } - else { - this.changeGazeColor(this._gazeColor); - this.changeLaserColor(this._laserColor); - gazer._isActionableMesh = false; - } - try { - this.onNewMeshSelected.notifyObservers(hit.pickedMesh); - const gazerAsControllerGazer = gazer; - if (gazerAsControllerGazer.webVRController) { - this.onMeshSelectedWithController.notifyObservers({ mesh: hit.pickedMesh, controller: gazerAsControllerGazer.webVRController }); - } - } - catch (err) { - logger_Logger.Warn("Error while raising onNewMeshSelected or onMeshSelectedWithController: " + err); - } - } - else { - this._notifySelectedMeshUnselected(gazer._currentMeshSelected); - gazer._currentMeshSelected = null; - this.changeGazeColor(this._gazeColor); - this.changeLaserColor(this._laserColor); - } - } - } - else { - this._notifySelectedMeshUnselected(gazer._currentMeshSelected); - gazer._currentMeshSelected = null; - //this._teleportationAllowed = false; - this.changeGazeColor(this._gazeColor); - this.changeLaserColor(this._laserColor); - } - } - _notifySelectedMeshUnselected(mesh) { - if (mesh) { - this.onSelectedMeshUnselected.notifyObservers(mesh); - } - } - /** - * Permanently set new colors for the laser pointer - * @param color the new laser color - * @param pickedColor the new laser color when picked mesh detected - */ - setLaserColor(color, pickedColor = this._pickedLaserColor) { - this._laserColor = color; - this._pickedLaserColor = pickedColor; - } - /** - * Set lighting enabled / disabled on the laser pointer of both controllers - * @param enabled should the lighting be enabled on the laser pointer - */ - setLaserLightingState(enabled = true) { - if (this._leftController) { - this._leftController._setLaserPointerLightingDisabled(!enabled); - } - if (this._rightController) { - this._rightController._setLaserPointerLightingDisabled(!enabled); - } - } - /** - * Permanently set new colors for the gaze pointer - * @param color the new gaze color - * @param pickedColor the new gaze color when picked mesh detected - */ - setGazeColor(color, pickedColor = this._pickedGazeColor) { - this._gazeColor = color; - this._pickedGazeColor = pickedColor; - } - /** - * Sets the color of the laser ray from the vr controllers. - * @param color new color for the ray. - */ - changeLaserColor(color) { - if (!this.updateControllerLaserColor) { - return; - } - if (this._leftController) { - this._leftController._setLaserPointerColor(color); - } - if (this._rightController) { - this._rightController._setLaserPointerColor(color); - } - } - /** - * Sets the color of the ray from the vr headsets gaze. - * @param color new color for the ray. - */ - changeGazeColor(color) { - if (!this.updateGazeTrackerColor) { - return; - } - if (!this._cameraGazer._gazeTracker.material) { - return; - } - this._cameraGazer._gazeTracker.material.emissiveColor = color; - if (this._leftController) { - this._leftController._gazeTracker.material.emissiveColor = color; - } - if (this._rightController) { - this._rightController._gazeTracker.material.emissiveColor = color; - } - } - /** - * Exits VR and disposes of the vr experience helper - */ - dispose() { - if (this.isInVRMode) { - this.exitVR(); - } - if (this._postProcessMove) { - this._postProcessMove.dispose(); - } - if (this._webVRCamera) { - this._webVRCamera.dispose(); - } - if (this._vrDeviceOrientationCamera) { - this._vrDeviceOrientationCamera.dispose(); - } - if (!this._useCustomVRButton && this._btnVR && this._btnVR.parentNode) { - document.body.removeChild(this._btnVR); - } - if (this._deviceOrientationCamera && this._scene.activeCamera != this._deviceOrientationCamera) { - this._deviceOrientationCamera.dispose(); - } - if (this._cameraGazer) { - this._cameraGazer.dispose(); - } - if (this._leftController) { - this._leftController.dispose(); - } - if (this._rightController) { - this._rightController.dispose(); - } - if (this._teleportationTarget) { - this._teleportationTarget.dispose(); - } - if (this.xr) { - this.xr.dispose(); - } - this._floorMeshesCollection.length = 0; - document.removeEventListener("keydown", this._onKeyDown); - window.removeEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChangeBind); - window.removeEventListener("resize", this._onResize); - document.removeEventListener("fullscreenchange", this._onFullscreenChange); - this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChangedBind); - this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart); - this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete); - this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected); - this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected); - this._scene.unregisterBeforeRender(this._beforeRender); - } - /** - * Gets the name of the VRExperienceHelper class - * @returns "VRExperienceHelper" - */ - getClassName() { - return "VRExperienceHelper"; - } -} -/** - * Time Constant Teleportation Mode - */ -VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME = 0; -/** - * Speed Constant Teleportation Mode - */ -VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED = 1; -//# sourceMappingURL=vrExperienceHelper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/VR/index.js - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/RigModes/index.js - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Cameras/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Collisions/collider.js - - -const intersectBoxAASphere = (boxMin, boxMax, sphereCenter, sphereRadius) => { - if (boxMin.x > sphereCenter.x + sphereRadius) { - return false; - } - if (sphereCenter.x - sphereRadius > boxMax.x) { - return false; - } - if (boxMin.y > sphereCenter.y + sphereRadius) { - return false; - } - if (sphereCenter.y - sphereRadius > boxMax.y) { - return false; - } - if (boxMin.z > sphereCenter.z + sphereRadius) { - return false; - } - if (sphereCenter.z - sphereRadius > boxMax.z) { - return false; - } - return true; -}; -const getLowestRoot = (function () { - const result = { root: 0, found: false }; - return function (a, b, c, maxR) { - result.root = 0; - result.found = false; - const determinant = b * b - 4.0 * a * c; - if (determinant < 0) { - return result; - } - const sqrtD = Math.sqrt(determinant); - let r1 = (-b - sqrtD) / (2.0 * a); - let r2 = (-b + sqrtD) / (2.0 * a); - if (r1 > r2) { - const temp = r2; - r2 = r1; - r1 = temp; - } - if (r1 > 0 && r1 < maxR) { - result.root = r1; - result.found = true; - return result; - } - if (r2 > 0 && r2 < maxR) { - result.root = r2; - result.found = true; - return result; - } - return result; - }; -})(); -/** @internal */ -class Collider { - constructor() { - // Implementation of the "Improved Collision detection and Response" algorithm proposed by Kasper Fauerby - // https://www.peroxide.dk/papers/collision/collision.pdf - this._collisionPoint = math_vector_Vector3.Zero(); - this._planeIntersectionPoint = math_vector_Vector3.Zero(); - this._tempVector = math_vector_Vector3.Zero(); - this._tempVector2 = math_vector_Vector3.Zero(); - this._tempVector3 = math_vector_Vector3.Zero(); - this._tempVector4 = math_vector_Vector3.Zero(); - this._edge = math_vector_Vector3.Zero(); - this._baseToVertex = math_vector_Vector3.Zero(); - this._destinationPoint = math_vector_Vector3.Zero(); - this._slidePlaneNormal = math_vector_Vector3.Zero(); - this._displacementVector = math_vector_Vector3.Zero(); - /** @internal */ - this._radius = math_vector_Vector3.One(); - /** @internal */ - this._retry = 0; - /** @internal */ - this._basePointWorld = math_vector_Vector3.Zero(); - this._velocityWorld = math_vector_Vector3.Zero(); - this._normalizedVelocity = math_vector_Vector3.Zero(); - this._collisionMask = -1; - } - get collisionMask() { - return this._collisionMask; - } - set collisionMask(mask) { - this._collisionMask = !isNaN(mask) ? mask : -1; - } - /** - * Gets the plane normal used to compute the sliding response (in local space) - */ - get slidePlaneNormal() { - return this._slidePlaneNormal; - } - // Methods - /** - * @internal - */ - _initialize(source, dir, e) { - this._velocity = dir; - this._velocitySquaredLength = this._velocity.lengthSquared(); - const len = Math.sqrt(this._velocitySquaredLength); - if (len === 0 || len === 1.0) { - this._normalizedVelocity.copyFromFloats(dir._x, dir._y, dir._z); - } - else { - dir.scaleToRef(1.0 / len, this._normalizedVelocity); - } - this._basePoint = source; - source.multiplyToRef(this._radius, this._basePointWorld); - dir.multiplyToRef(this._radius, this._velocityWorld); - this._velocityWorldLength = this._velocityWorld.length(); - this._epsilon = e; - this.collisionFound = false; - } - /** - * @internal - */ - _checkPointInTriangle(point, pa, pb, pc, n) { - pa.subtractToRef(point, this._tempVector); - pb.subtractToRef(point, this._tempVector2); - math_vector_Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4); - let d = math_vector_Vector3.Dot(this._tempVector4, n); - if (d < 0) { - return false; - } - pc.subtractToRef(point, this._tempVector3); - math_vector_Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4); - d = math_vector_Vector3.Dot(this._tempVector4, n); - if (d < 0) { - return false; - } - math_vector_Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4); - d = math_vector_Vector3.Dot(this._tempVector4, n); - return d >= 0; - } - /** - * @internal - */ - _canDoCollision(sphereCenter, sphereRadius, vecMin, vecMax) { - const distance = math_vector_Vector3.Distance(this._basePointWorld, sphereCenter); - const max = Math.max(this._radius.x, this._radius.y, this._radius.z); - if (distance > this._velocityWorldLength + max + sphereRadius) { - return false; - } - if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) { - return false; - } - return true; - } - /** - * @internal - */ - _testTriangle(faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh) { - let t0; - let embeddedInPlane = false; - //defensive programming, actually not needed. - if (!trianglePlaneArray) { - trianglePlaneArray = []; - } - if (!trianglePlaneArray[faceIndex]) { - trianglePlaneArray[faceIndex] = new math_plane_Plane(0, 0, 0, 0); - trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3); - } - const trianglePlane = trianglePlaneArray[faceIndex]; - if (!hasMaterial && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) { - return; - } - const signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint); - const normalDotVelocity = math_vector_Vector3.Dot(trianglePlane.normal, this._velocity); - // if DoubleSidedCheck is false(default), a double sided face will be consided 2 times. - // if true, it discard the faces having normal not facing velocity - if (Collider.DoubleSidedCheck && normalDotVelocity > 0.0001) { - return; - } - if (normalDotVelocity == 0) { - if (Math.abs(signedDistToTrianglePlane) >= 1.0) { - return; - } - embeddedInPlane = true; - t0 = 0; - } - else { - t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity; - let t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity; - if (t0 > t1) { - const temp = t1; - t1 = t0; - t0 = temp; - } - if (t0 > 1.0 || t1 < 0.0) { - return; - } - if (t0 < 0) { - t0 = 0; - } - if (t0 > 1.0) { - t0 = 1.0; - } - } - this._collisionPoint.copyFromFloats(0, 0, 0); - let found = false; - let t = 1.0; - if (!embeddedInPlane) { - this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint); - this._velocity.scaleToRef(t0, this._tempVector); - this._planeIntersectionPoint.addInPlace(this._tempVector); - if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) { - found = true; - t = t0; - this._collisionPoint.copyFrom(this._planeIntersectionPoint); - } - } - if (!found) { - let a = this._velocitySquaredLength; - this._basePoint.subtractToRef(p1, this._tempVector); - let b = 2.0 * math_vector_Vector3.Dot(this._velocity, this._tempVector); - let c = this._tempVector.lengthSquared() - 1.0; - let lowestRoot = getLowestRoot(a, b, c, t); - if (lowestRoot.found) { - t = lowestRoot.root; - found = true; - this._collisionPoint.copyFrom(p1); - } - this._basePoint.subtractToRef(p2, this._tempVector); - b = 2.0 * math_vector_Vector3.Dot(this._velocity, this._tempVector); - c = this._tempVector.lengthSquared() - 1.0; - lowestRoot = getLowestRoot(a, b, c, t); - if (lowestRoot.found) { - t = lowestRoot.root; - found = true; - this._collisionPoint.copyFrom(p2); - } - this._basePoint.subtractToRef(p3, this._tempVector); - b = 2.0 * math_vector_Vector3.Dot(this._velocity, this._tempVector); - c = this._tempVector.lengthSquared() - 1.0; - lowestRoot = getLowestRoot(a, b, c, t); - if (lowestRoot.found) { - t = lowestRoot.root; - found = true; - this._collisionPoint.copyFrom(p3); - } - p2.subtractToRef(p1, this._edge); - p1.subtractToRef(this._basePoint, this._baseToVertex); - let edgeSquaredLength = this._edge.lengthSquared(); - let edgeDotVelocity = math_vector_Vector3.Dot(this._edge, this._velocity); - let edgeDotBaseToVertex = math_vector_Vector3.Dot(this._edge, this._baseToVertex); - a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity; - b = 2 * (edgeSquaredLength * math_vector_Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex); - c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; - lowestRoot = getLowestRoot(a, b, c, t); - if (lowestRoot.found) { - const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; - if (f >= 0.0 && f <= 1.0) { - t = lowestRoot.root; - found = true; - this._edge.scaleInPlace(f); - p1.addToRef(this._edge, this._collisionPoint); - } - } - p3.subtractToRef(p2, this._edge); - p2.subtractToRef(this._basePoint, this._baseToVertex); - edgeSquaredLength = this._edge.lengthSquared(); - edgeDotVelocity = math_vector_Vector3.Dot(this._edge, this._velocity); - edgeDotBaseToVertex = math_vector_Vector3.Dot(this._edge, this._baseToVertex); - a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity; - b = 2 * (edgeSquaredLength * math_vector_Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex); - c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; - lowestRoot = getLowestRoot(a, b, c, t); - if (lowestRoot.found) { - const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; - if (f >= 0.0 && f <= 1.0) { - t = lowestRoot.root; - found = true; - this._edge.scaleInPlace(f); - p2.addToRef(this._edge, this._collisionPoint); - } - } - p1.subtractToRef(p3, this._edge); - p3.subtractToRef(this._basePoint, this._baseToVertex); - edgeSquaredLength = this._edge.lengthSquared(); - edgeDotVelocity = math_vector_Vector3.Dot(this._edge, this._velocity); - edgeDotBaseToVertex = math_vector_Vector3.Dot(this._edge, this._baseToVertex); - a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity; - b = 2 * (edgeSquaredLength * math_vector_Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex); - c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; - lowestRoot = getLowestRoot(a, b, c, t); - if (lowestRoot.found) { - const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; - if (f >= 0.0 && f <= 1.0) { - t = lowestRoot.root; - found = true; - this._edge.scaleInPlace(f); - p3.addToRef(this._edge, this._collisionPoint); - } - } - } - if (found) { - const distToCollisionSquared = t * t * this._velocitySquaredLength; - if (!this.collisionFound || distToCollisionSquared < this._nearestDistanceSquared) { - // if collisionResponse is false, collision is not found but the collidedMesh is set anyway. - // onCollide observable are triggered if collideMesh is set - // this allow trigger volumes to be created. - if (hostMesh.collisionResponse) { - if (!this.intersectionPoint) { - this.intersectionPoint = this._collisionPoint.clone(); - } - else { - this.intersectionPoint.copyFrom(this._collisionPoint); - } - this._nearestDistanceSquared = distToCollisionSquared; - this._nearestDistance = Math.sqrt(distToCollisionSquared); - this.collisionFound = true; - } - this.collidedMesh = hostMesh; - } - } - } - /** - * @internal - */ - _collide(trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial, hostMesh, invertTriangles, triangleStrip = false) { - if (triangleStrip) { - if (!indices || indices.length === 0) { - for (let i = 0; i < pts.length - 2; i += 1) { - const p1 = pts[i]; - const p2 = pts[i + 1]; - const p3 = pts[i + 2]; - // stay defensive and don't check against undefined positions. - if (!p1 || !p2 || !p3) { - continue; - } - // Handles strip faces one on two is reversed - if ((invertTriangles ? 1 : 0) ^ i % 2) { - this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh); - } - else { - this._testTriangle(i, trianglePlaneArray, p2, p1, p3, hasMaterial, hostMesh); - } - } - } - else { - for (let i = indexStart; i < indexEnd - 2; i += 1) { - const indexA = indices[i]; - const indexB = indices[i + 1]; - const indexC = indices[i + 2]; - if (indexC === 0xffffffff) { - i += 2; - continue; - } - const p1 = pts[indexA]; - const p2 = pts[indexB]; - const p3 = pts[indexC]; - // stay defensive and don't check against undefined positions. - if (!p1 || !p2 || !p3) { - continue; - } - // Handles strip faces one on two is reversed - if ((invertTriangles ? 1 : 0) ^ i % 2) { - this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh); - } - else { - this._testTriangle(i, trianglePlaneArray, p2, p1, p3, hasMaterial, hostMesh); - } - } - } - } - else if (!indices || indices.length === 0) { - for (let i = 0; i < pts.length; i += 3) { - const p1 = pts[i]; - const p2 = pts[i + 1]; - const p3 = pts[i + 2]; - if (invertTriangles) { - this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh); - } - else { - this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh); - } - } - } - else { - for (let i = indexStart; i < indexEnd; i += 3) { - const p1 = pts[indices[i] - decal]; - const p2 = pts[indices[i + 1] - decal]; - const p3 = pts[indices[i + 2] - decal]; - if (invertTriangles) { - this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh); - } - else { - this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh); - } - } - } - } - /** - * @internal - */ - _getResponse(pos, vel) { - pos.addToRef(vel, this._destinationPoint); - vel.scaleInPlace(this._nearestDistance / vel.length()); - this._basePoint.addToRef(vel, pos); - pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal); - this._slidePlaneNormal.normalize(); - this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector); - pos.addInPlace(this._displacementVector); - this.intersectionPoint.addInPlace(this._displacementVector); - this._slidePlaneNormal.scaleInPlace(math_plane_Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint)); - this._destinationPoint.subtractInPlace(this._slidePlaneNormal); - this._destinationPoint.subtractToRef(this.intersectionPoint, vel); - } -} -/** - * If true, it check for double sided faces and only returns 1 collision instead of 2 - */ -Collider.DoubleSidedCheck = false; -//# sourceMappingURL=collider.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Collisions/collisionCoordinator.js - - - - -/** @internal */ -class DefaultCollisionCoordinator { - constructor() { - this._scaledPosition = math_vector_Vector3.Zero(); - this._scaledVelocity = math_vector_Vector3.Zero(); - this._finalPosition = math_vector_Vector3.Zero(); - } - getNewPosition(position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) { - position.divideToRef(collider._radius, this._scaledPosition); - displacement.divideToRef(collider._radius, this._scaledVelocity); - collider.collidedMesh = null; - collider._retry = 0; - collider._initialVelocity = this._scaledVelocity; - collider._initialPosition = this._scaledPosition; - this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh); - this._finalPosition.multiplyInPlace(collider._radius); - //run the callback - onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh); - } - createCollider() { - return new Collider(); - } - init(scene) { - this._scene = scene; - } - _collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh = null) { - const closeDistance = engine_Engine.CollisionsEpsilon * 10.0; - if (collider._retry >= maximumRetry) { - finalPosition.copyFrom(position); - return; - } - // Check if this is a mesh else camera or -1 - const collisionMask = excludedMesh ? excludedMesh.collisionMask : collider.collisionMask; - collider._initialize(position, velocity, closeDistance); - // Check if collision detection should happen against specified list of meshes or, - // if not specified, against all meshes in the scene - const meshes = (excludedMesh && excludedMesh.surroundingMeshes) || this._scene.meshes; - for (let index = 0; index < meshes.length; index++) { - const mesh = meshes[index]; - if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && (collisionMask & mesh.collisionGroup) !== 0) { - mesh._checkCollision(collider); - } - } - if (!collider.collisionFound) { - position.addToRef(velocity, finalPosition); - return; - } - if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) { - collider._getResponse(position, velocity); - } - if (velocity.length() <= closeDistance) { - finalPosition.copyFrom(position); - return; - } - collider._retry++; - this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh); - } -} -scene_Scene.CollisionCoordinatorFactory = () => { - return new DefaultCollisionCoordinator(); -}; -//# sourceMappingURL=collisionCoordinator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Collisions/index.js - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Compute/computeEffect.js - - - - - - -/** - * Effect wrapping a compute shader and let execute (dispatch) the shader - */ -class ComputeEffect { - /** - * Creates a compute effect that can be used to execute a compute shader - * @param baseName Name of the effect - * @param options Set of all options to create the effect - * @param engine The engine the effect is created for - * @param key Effect Key identifying uniquely compiled shader variants - */ - constructor(baseName, options, engine, key = "") { - var _a, _b; - /** - * Name of the effect. - */ - this.name = null; - /** - * String container all the define statements that should be set on the shader. - */ - this.defines = ""; - /** - * Callback that will be called when the shader is compiled. - */ - this.onCompiled = null; - /** - * Callback that will be called if an error occurs during shader compilation. - */ - this.onError = null; - /** - * Unique ID of the effect. - */ - this.uniqueId = 0; - /** - * Observable that will be called when the shader is compiled. - * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised. - */ - this.onCompileObservable = new observable_Observable(); - /** - * Observable that will be called if an error occurs during shader compilation. - */ - this.onErrorObservable = new observable_Observable(); - /** - * Observable that will be called when effect is bound. - */ - this.onBindObservable = new observable_Observable(); - /** - * @internal - * Specifies if the effect was previously ready - */ - this._wasPreviouslyReady = false; - this._isReady = false; - this._compilationError = ""; - /** @internal */ - this._key = ""; - this._computeSourceCodeOverride = ""; - /** @internal */ - this._pipelineContext = null; - /** @internal */ - this._computeSourceCode = ""; - this._rawComputeSourceCode = ""; - this._shaderLanguage = ShaderLanguage.WGSL; - this.name = baseName; - this._key = key; - this._engine = engine; - this.uniqueId = ComputeEffect._UniqueIdSeed++; - this.defines = (_a = options.defines) !== null && _a !== void 0 ? _a : ""; - this.onError = options.onError; - this.onCompiled = options.onCompiled; - this._entryPoint = (_b = options.entryPoint) !== null && _b !== void 0 ? _b : "main"; - this._shaderStore = ShaderStore.GetShadersStore(this._shaderLanguage); - this._shaderRepository = ShaderStore.GetShadersRepository(this._shaderLanguage); - this._includeShaderStore = ShaderStore.GetIncludesShadersStore(this._shaderLanguage); - let computeSource; - const hostDocument = IsWindowObjectExist() ? this._engine.getHostDocument() : null; - if (baseName.computeSource) { - computeSource = "source:" + baseName.computeSource; - } - else if (baseName.computeElement) { - computeSource = hostDocument ? hostDocument.getElementById(baseName.computeElement) : null; - if (!computeSource) { - computeSource = baseName.computeElement; - } - } - else { - computeSource = baseName.compute || baseName; - } - const processorOptions = { - defines: this.defines.split("\n"), - indexParameters: undefined, - isFragment: false, - shouldUseHighPrecisionShader: false, - processor: null, - supportsUniformBuffers: this._engine.supportsUniformBuffers, - shadersRepository: this._shaderRepository, - includesShadersStore: this._includeShaderStore, - version: (this._engine.version * 100).toString(), - platformName: this._engine.shaderPlatformName, - processingContext: null, - isNDCHalfZRange: this._engine.isNDCHalfZRange, - useReverseDepthBuffer: this._engine.useReverseDepthBuffer, - }; - this._loadShader(computeSource, "Compute", "", (computeCode) => { - ShaderProcessor.Initialize(processorOptions); - ShaderProcessor.PreProcess(computeCode, processorOptions, (migratedCommputeCode) => { - this._rawComputeSourceCode = computeCode; - if (options.processFinalCode) { - migratedCommputeCode = options.processFinalCode(migratedCommputeCode); - } - const finalShaders = ShaderProcessor.Finalize(migratedCommputeCode, "", processorOptions); - this._useFinalCode(finalShaders.vertexCode, baseName); - }, this._engine); - }); - } - _useFinalCode(migratedCommputeCode, baseName) { - if (baseName) { - const compute = baseName.computeElement || baseName.compute || baseName.spectorName || baseName; - this._computeSourceCode = "//#define SHADER_NAME compute:" + compute + "\n" + migratedCommputeCode; - } - else { - this._computeSourceCode = migratedCommputeCode; - } - this._prepareEffect(); - } - /** - * Unique key for this effect - */ - get key() { - return this._key; - } - /** - * If the effect has been compiled and prepared. - * @returns if the effect is compiled and prepared. - */ - isReady() { - try { - return this._isReadyInternal(); - } - catch (_a) { - return false; - } - } - _isReadyInternal() { - if (this._isReady) { - return true; - } - if (this._pipelineContext) { - return this._pipelineContext.isReady; - } - return false; - } - /** - * The engine the effect was initialized with. - * @returns the engine. - */ - getEngine() { - return this._engine; - } - /** - * The pipeline context for this effect - * @returns the associated pipeline context - */ - getPipelineContext() { - return this._pipelineContext; - } - /** - * The error from the last compilation. - * @returns the error string. - */ - getCompilationError() { - return this._compilationError; - } - /** - * Adds a callback to the onCompiled observable and call the callback immediately if already ready. - * @param func The callback to be used. - */ - executeWhenCompiled(func) { - if (this.isReady()) { - func(this); - return; - } - this.onCompileObservable.add((effect) => { - func(effect); - }); - if (!this._pipelineContext || this._pipelineContext.isAsync) { - setTimeout(() => { - this._checkIsReady(null); - }, 16); - } - } - _checkIsReady(previousPipelineContext) { - try { - if (this._isReadyInternal()) { - return; - } - } - catch (e) { - this._processCompilationErrors(e, previousPipelineContext); - return; - } - setTimeout(() => { - this._checkIsReady(previousPipelineContext); - }, 16); - } - _loadShader(shader, key, optionalKey, callback) { - if (typeof HTMLElement !== "undefined") { - // DOM element ? - if (shader instanceof HTMLElement) { - const shaderCode = GetDOMTextContent(shader); - callback(shaderCode); - return; - } - } - // Direct source ? - if (shader.substr(0, 7) === "source:") { - callback(shader.substr(7)); - return; - } - // Base64 encoded ? - if (shader.substr(0, 7) === "base64:") { - const shaderBinary = window.atob(shader.substr(7)); - callback(shaderBinary); - return; - } - // Is in local store ? - if (this._shaderStore[shader + key + "Shader"]) { - callback(this._shaderStore[shader + key + "Shader"]); - return; - } - if (optionalKey && this._shaderStore[shader + optionalKey + "Shader"]) { - callback(this._shaderStore[shader + optionalKey + "Shader"]); - return; - } - let shaderUrl; - if (shader[0] === "." || shader[0] === "/" || shader.indexOf("http") > -1) { - shaderUrl = shader; - } - else { - shaderUrl = this._shaderRepository + shader; - } - this._engine._loadFile(shaderUrl + "." + key.toLowerCase() + ".fx", callback); - } - /** - * Gets the compute shader source code of this effect - */ - get computeSourceCode() { - var _a, _b; - return this._computeSourceCodeOverride ? this._computeSourceCodeOverride : (_b = (_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getComputeShaderCode()) !== null && _b !== void 0 ? _b : this._computeSourceCode; - } - /** - * Gets the compute shader source code before it has been processed by the preprocessor - */ - get rawComputeSourceCode() { - return this._rawComputeSourceCode; - } - /** - * Prepares the effect - * @internal - */ - _prepareEffect() { - const defines = this.defines; - const previousPipelineContext = this._pipelineContext; - this._isReady = false; - try { - const engine = this._engine; - this._pipelineContext = engine.createComputePipelineContext(); - this._pipelineContext._name = this._key; - engine._prepareComputePipelineContext(this._pipelineContext, this._computeSourceCodeOverride ? this._computeSourceCodeOverride : this._computeSourceCode, this._rawComputeSourceCode, this._computeSourceCodeOverride ? null : defines, this._entryPoint); - engine._executeWhenComputeStateIsCompiled(this._pipelineContext, () => { - this._compilationError = ""; - this._isReady = true; - if (this.onCompiled) { - this.onCompiled(this); - } - this.onCompileObservable.notifyObservers(this); - this.onCompileObservable.clear(); - if (previousPipelineContext) { - this.getEngine()._deleteComputePipelineContext(previousPipelineContext); - } - }); - if (this._pipelineContext.isAsync) { - this._checkIsReady(previousPipelineContext); - } - } - catch (e) { - this._processCompilationErrors(e, previousPipelineContext); - } - } - _getShaderCodeAndErrorLine(code, error) { - const regexp = /COMPUTE SHADER ERROR: 0:(\d+?):/; - let errorLine = null; - if (error && code) { - const res = error.match(regexp); - if (res && res.length === 2) { - const lineNumber = parseInt(res[1]); - const lines = code.split("\n", -1); - if (lines.length >= lineNumber) { - errorLine = `Offending line [${lineNumber}] in compute code: ${lines[lineNumber - 1]}`; - } - } - } - return [code, errorLine]; - } - _processCompilationErrors(e, previousPipelineContext = null) { - var _a; - this._compilationError = e.message; - // Let's go through fallbacks then - logger_Logger.Error("Unable to compile compute effect:"); - logger_Logger.Error("Defines:\n" + this.defines); - if (ComputeEffect.LogShaderCodeOnCompilationError) { - let lineErrorVertex = null, code = null; - if ((_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getComputeShaderCode()) { - [code, lineErrorVertex] = this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(), this._compilationError); - if (code) { - logger_Logger.Error("Compute code:"); - logger_Logger.Error(code); - } - } - if (lineErrorVertex) { - logger_Logger.Error(lineErrorVertex); - } - } - logger_Logger.Error("Error: " + this._compilationError); - if (previousPipelineContext) { - this._pipelineContext = previousPipelineContext; - this._isReady = true; - if (this.onError) { - this.onError(this, this._compilationError); - } - this.onErrorObservable.notifyObservers(this); - } - } - /** - * Release all associated resources. - **/ - dispose() { - if (this._pipelineContext) { - this._pipelineContext.dispose(); - } - this._engine._releaseComputeEffect(this); - } - /** - * This function will add a new compute shader to the shader store - * @param name the name of the shader - * @param computeShader compute shader content - */ - static RegisterShader(name, computeShader) { - ShaderStore.GetShadersStore(ShaderLanguage.WGSL)[`${name}ComputeShader`] = computeShader; - } -} -ComputeEffect._UniqueIdSeed = 0; -/** - * Enable logging of the shader code when a compilation error occurs - */ -ComputeEffect.LogShaderCodeOnCompilationError = true; -//# sourceMappingURL=computeEffect.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.computeShader.js - -/** @internal */ -var ComputeBindingType; -(function (ComputeBindingType) { - ComputeBindingType[ComputeBindingType["Texture"] = 0] = "Texture"; - ComputeBindingType[ComputeBindingType["StorageTexture"] = 1] = "StorageTexture"; - ComputeBindingType[ComputeBindingType["UniformBuffer"] = 2] = "UniformBuffer"; - ComputeBindingType[ComputeBindingType["StorageBuffer"] = 3] = "StorageBuffer"; - ComputeBindingType[ComputeBindingType["TextureWithoutSampler"] = 4] = "TextureWithoutSampler"; - ComputeBindingType[ComputeBindingType["Sampler"] = 5] = "Sampler"; -})(ComputeBindingType || (ComputeBindingType = {})); -ThinEngine.prototype.createComputeEffect = function (baseName, options) { - throw new Error("createComputeEffect: This engine does not support compute shaders!"); -}; -ThinEngine.prototype.createComputePipelineContext = function () { - throw new Error("createComputePipelineContext: This engine does not support compute shaders!"); -}; -ThinEngine.prototype.createComputeContext = function () { - return undefined; -}; -ThinEngine.prototype.computeDispatch = function (effect, context, bindings, x, y, z, bindingsMapping) { - throw new Error("computeDispatch: This engine does not support compute shaders!"); -}; -ThinEngine.prototype.areAllComputeEffectsReady = function () { - return true; -}; -ThinEngine.prototype.releaseComputeEffects = function () { }; -ThinEngine.prototype._prepareComputePipelineContext = function (pipelineContext, computeSourceCode, rawComputeSourceCode, defines, entryPoint) { }; -ThinEngine.prototype._rebuildComputeEffects = function () { }; -ThinEngine.prototype._executeWhenComputeStateIsCompiled = function (pipelineContext, action) { - action(); -}; -ThinEngine.prototype._releaseComputeEffect = function (effect) { }; -ThinEngine.prototype._deleteComputePipelineContext = function (pipelineContext) { }; -//# sourceMappingURL=engine.computeShader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Compute/computeShader.js - - - - - - - - -/** - * The ComputeShader object lets you execute a compute shader on your GPU (if supported by the engine) - */ -class ComputeShader { - /** - * The options used to create the shader - */ - get options() { - return this._options; - } - /** - * The shaderPath used to create the shader - */ - get shaderPath() { - return this._shaderPath; - } - /** - * Instantiates a new compute shader. - * @param name Defines the name of the compute shader in the scene - * @param engine Defines the engine the compute shader belongs to - * @param shaderPath Defines the route to the shader code in one of three ways: - * * object: \{ compute: "custom" \}, used with ShaderStore.ShadersStoreWGSL["customComputeShader"] - * * object: \{ computeElement: "HTMLElementId" \}, used with shader code in script tags - * * object: \{ computeSource: "compute shader code string" \}, where the string contains the shader code - * * 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. - * @param options Define the options used to create the shader - */ - constructor(name, engine, shaderPath, options = {}) { - this._bindings = {}; - this._samplers = {}; - this._contextIsDirty = false; - /** - * Callback triggered when the shader is compiled - */ - this.onCompiled = null; - /** - * Callback triggered when an error occurs - */ - this.onError = null; - this.name = name; - this._engine = engine; - this.uniqueId = UniqueIdGenerator.UniqueId; - if (!this._engine.getCaps().supportComputeShaders) { - logger_Logger.Error("This engine does not support compute shaders!"); - return; - } - if (!options.bindingsMapping) { - logger_Logger.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!"); - return; - } - this._context = engine.createComputeContext(); - this._shaderPath = shaderPath; - this._options = Object.assign({ bindingsMapping: {}, defines: [] }, options); - } - /** - * Gets the current class name of the material e.g. "ComputeShader" - * Mainly use in serialization. - * @returns the class name - */ - getClassName() { - return "ComputeShader"; - } - /** - * Binds a texture to the shader - * @param name Binding name of the texture - * @param texture Texture to bind - * @param bindSampler Bind the sampler corresponding to the texture (default: true). The sampler will be bound just before the binding index of the texture - */ - setTexture(name, texture, bindSampler = true) { - const current = this._bindings[name]; - this._bindings[name] = { - type: bindSampler ? ComputeBindingType.Texture : ComputeBindingType.TextureWithoutSampler, - object: texture, - indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries, - }; - this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture || current.type !== this._bindings[name].type); - } - /** - * Binds a storage texture to the shader - * @param name Binding name of the texture - * @param texture Texture to bind - */ - setStorageTexture(name, texture) { - const current = this._bindings[name]; - this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture); - this._bindings[name] = { - type: ComputeBindingType.StorageTexture, - object: texture, - indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries, - }; - } - /** - * Binds a uniform buffer to the shader - * @param name Binding name of the buffer - * @param buffer Buffer to bind - */ - setUniformBuffer(name, buffer) { - const current = this._bindings[name]; - this._contextIsDirty || (this._contextIsDirty = !current || current.object !== buffer); - this._bindings[name] = { - type: ComputeBindingType.UniformBuffer, - object: buffer, - indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries, - }; - } - /** - * Binds a storage buffer to the shader - * @param name Binding name of the buffer - * @param buffer Buffer to bind - */ - setStorageBuffer(name, buffer) { - const current = this._bindings[name]; - this._contextIsDirty || (this._contextIsDirty = !current || current.object !== buffer); - this._bindings[name] = { - type: ComputeBindingType.StorageBuffer, - object: buffer, - indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries, - }; - } - /** - * Binds a texture sampler to the shader - * @param name Binding name of the sampler - * @param sampler Sampler to bind - */ - setTextureSampler(name, sampler) { - const current = this._bindings[name]; - this._contextIsDirty || (this._contextIsDirty = !current || !sampler.compareSampler(current.object)); - this._bindings[name] = { - type: ComputeBindingType.Sampler, - object: sampler, - indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries, - }; - } - /** - * Specifies that the compute shader is ready to be executed (the compute effect and all the resources are ready) - * @returns true if the compute shader is ready to be executed - */ - isReady() { - let effect = this._effect; - for (const key in this._bindings) { - const binding = this._bindings[key], type = binding.type, object = binding.object; - switch (type) { - case ComputeBindingType.Texture: - case ComputeBindingType.TextureWithoutSampler: - case ComputeBindingType.StorageTexture: { - const texture = object; - if (!texture.isReady()) { - return false; - } - break; - } - } - } - const defines = []; - const shaderName = this._shaderPath; - if (this._options.defines) { - for (let index = 0; index < this._options.defines.length; index++) { - defines.push(this._options.defines[index]); - } - } - const join = defines.join("\n"); - if (this._cachedDefines !== join) { - this._cachedDefines = join; - effect = this._engine.createComputeEffect(shaderName, { - defines: join, - entryPoint: this._options.entryPoint, - onCompiled: this.onCompiled, - onError: this.onError, - }); - this._effect = effect; - } - if (!effect.isReady()) { - return false; - } - return true; - } - /** - * Dispatches (executes) the compute shader - * @param x Number of workgroups to execute on the X dimension - * @param y Number of workgroups to execute on the Y dimension (default: 1) - * @param z Number of workgroups to execute on the Z dimension (default: 1) - * @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) - */ - dispatch(x, y, z) { - var _a; - if (!this.isReady()) { - return false; - } - // 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 - // 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 - for (const key in this._bindings) { - const binding = this._bindings[key]; - if (!this._options.bindingsMapping[key]) { - throw new Error("ComputeShader ('" + this.name + "'): No binding mapping has been provided for the property '" + key + "'"); - } - switch (binding.type) { - case ComputeBindingType.Texture: { - const sampler = this._samplers[key]; - const texture = binding.object; - if (!sampler || !texture._texture || !sampler.compareSampler(texture._texture)) { - 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); - this._contextIsDirty = true; - } - break; - } - case ComputeBindingType.UniformBuffer: { - const ubo = binding.object; - if (ubo.getBuffer() !== binding.buffer) { - binding.buffer = ubo.getBuffer(); - this._contextIsDirty = true; - } - break; - } - } - } - if (this._contextIsDirty) { - this._contextIsDirty = false; - this._context.clear(); - } - this._engine.computeDispatch(this._effect, this._context, this._bindings, x, y, z, this._options.bindingsMapping); - return true; - } - /** - * Waits for the compute shader to be ready and executes it - * @param x Number of workgroups to execute on the X dimension - * @param y Number of workgroups to execute on the Y dimension (default: 1) - * @param z Number of workgroups to execute on the Z dimension (default: 1) - * @param delay Delay between the retries while the shader is not ready (in milliseconds - 10 by default) - * @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! - */ - dispatchWhenReady(x, y, z, delay = 10) { - return new Promise((resolve) => { - const check = () => { - if (!this.dispatch(x, y, z)) { - setTimeout(check, delay); - } - else { - resolve(); - } - }; - check(); - }); - } - /** - * Serializes this compute shader in a JSON representation - * @returns the serialized compute shader object - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.options = this._options; - serializationObject.shaderPath = this._shaderPath; - serializationObject.bindings = {}; - serializationObject.textures = {}; - for (const key in this._bindings) { - const binding = this._bindings[key]; - const object = binding.object; - switch (binding.type) { - case ComputeBindingType.Texture: - case ComputeBindingType.TextureWithoutSampler: - case ComputeBindingType.StorageTexture: { - const serializedData = object.serialize(); - if (serializedData) { - serializationObject.textures[key] = serializedData; - serializationObject.bindings[key] = { - type: binding.type, - }; - } - break; - } - case ComputeBindingType.UniformBuffer: { - break; - } - } - } - return serializationObject; - } - /** - * Creates a compute shader from parsed compute shader data - * @param source defines the JSON representation of the compute shader - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a new compute shader - */ - static Parse(source, scene, rootUrl) { - const compute = decorators_SerializationHelper.Parse(() => new ComputeShader(source.name, scene.getEngine(), source.shaderPath, source.options), source, scene, rootUrl); - for (const key in source.textures) { - const binding = source.bindings[key]; - const texture = texture_Texture.Parse(source.textures[key], scene, rootUrl); - if (binding.type === ComputeBindingType.Texture) { - compute.setTexture(key, texture); - } - else if (binding.type === ComputeBindingType.TextureWithoutSampler) { - compute.setTexture(key, texture, false); - } - else { - compute.setStorageTexture(key, texture); - } - } - return compute; - } -} -__decorate([ - serialize() -], ComputeShader.prototype, "name", void 0); -RegisterClass("BABYLON.ComputeShader", ComputeShader); -//# sourceMappingURL=computeShader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Compute/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Culling/Octrees/octreeBlock.js - - -/** - * Class used to store a cell in an octree - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees - */ -class OctreeBlock { - /** - * Creates a new block - * @param minPoint defines the minimum vector (in world space) of the block's bounding box - * @param maxPoint defines the maximum vector (in world space) of the block's bounding box - * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks) - * @param depth defines the current depth of this block in the octree - * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored) - * @param creationFunc defines a callback to call when an element is added to the block - */ - constructor(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) { - /** - * Gets the content of the current block - */ - this.entries = new Array(); - this._boundingVectors = new Array(); - this._capacity = capacity; - this._depth = depth; - this._maxDepth = maxDepth; - this._creationFunc = creationFunc; - this._minPoint = minPoint; - this._maxPoint = maxPoint; - this._boundingVectors.push(minPoint.clone()); - this._boundingVectors.push(maxPoint.clone()); - this._boundingVectors.push(minPoint.clone()); - this._boundingVectors[2].x = maxPoint.x; - this._boundingVectors.push(minPoint.clone()); - this._boundingVectors[3].y = maxPoint.y; - this._boundingVectors.push(minPoint.clone()); - this._boundingVectors[4].z = maxPoint.z; - this._boundingVectors.push(maxPoint.clone()); - this._boundingVectors[5].z = minPoint.z; - this._boundingVectors.push(maxPoint.clone()); - this._boundingVectors[6].x = minPoint.x; - this._boundingVectors.push(maxPoint.clone()); - this._boundingVectors[7].y = minPoint.y; - } - // Property - /** - * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks) - */ - get capacity() { - return this._capacity; - } - /** - * Gets the minimum vector (in world space) of the block's bounding box - */ - get minPoint() { - return this._minPoint; - } - /** - * Gets the maximum vector (in world space) of the block's bounding box - */ - get maxPoint() { - return this._maxPoint; - } - // Methods - /** - * Add a new element to this block - * @param entry defines the element to add - */ - addEntry(entry) { - if (this.blocks) { - for (let index = 0; index < this.blocks.length; index++) { - const block = this.blocks[index]; - block.addEntry(entry); - } - return; - } - this._creationFunc(entry, this); - if (this.entries.length > this.capacity && this._depth < this._maxDepth) { - this.createInnerBlocks(); - } - } - /** - * Remove an element from this block - * @param entry defines the element to remove - */ - removeEntry(entry) { - if (this.blocks) { - for (let index = 0; index < this.blocks.length; index++) { - const block = this.blocks[index]; - block.removeEntry(entry); - } - return; - } - const entryIndex = this.entries.indexOf(entry); - if (entryIndex > -1) { - this.entries.splice(entryIndex, 1); - } - } - /** - * Add an array of elements to this block - * @param entries defines the array of elements to add - */ - addEntries(entries) { - for (let index = 0; index < entries.length; index++) { - const mesh = entries[index]; - this.addEntry(mesh); - } - } - /** - * Test if the current block intersects the frustum planes and if yes, then add its content to the selection array - * @param frustumPlanes defines the frustum planes to test - * @param selection defines the array to store current content if selection is positive - * @param allowDuplicate defines if the selection array can contains duplicated entries - */ - select(frustumPlanes, selection, allowDuplicate) { - if (boundingBox_BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) { - if (this.blocks) { - for (let index = 0; index < this.blocks.length; index++) { - const block = this.blocks[index]; - block.select(frustumPlanes, selection, allowDuplicate); - } - return; - } - if (allowDuplicate) { - selection.concat(this.entries); - } - else { - selection.concatWithNoDuplicate(this.entries); - } - } - } - /** - * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array - * @param sphereCenter defines the bounding sphere center - * @param sphereRadius defines the bounding sphere radius - * @param selection defines the array to store current content if selection is positive - * @param allowDuplicate defines if the selection array can contains duplicated entries - */ - intersects(sphereCenter, sphereRadius, selection, allowDuplicate) { - if (boundingBox_BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) { - if (this.blocks) { - for (let index = 0; index < this.blocks.length; index++) { - const block = this.blocks[index]; - block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate); - } - return; - } - if (allowDuplicate) { - selection.concat(this.entries); - } - else { - selection.concatWithNoDuplicate(this.entries); - } - } - } - /** - * Test if the current block intersect with the given ray and if yes, then add its content to the selection array - * @param ray defines the ray to test with - * @param selection defines the array to store current content if selection is positive - */ - intersectsRay(ray, selection) { - if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) { - if (this.blocks) { - for (let index = 0; index < this.blocks.length; index++) { - const block = this.blocks[index]; - block.intersectsRay(ray, selection); - } - return; - } - selection.concatWithNoDuplicate(this.entries); - } - } - /** - * Subdivide the content into child blocks (this block will then be empty) - */ - createInnerBlocks() { - OctreeBlock._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc); - this.entries.splice(0); - } - /** - * @internal - */ - static _CreateBlocks(worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) { - target.blocks = new Array(); - const blockSize = new math_vector_Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); - // Segmenting space - for (let x = 0; x < 2; x++) { - for (let y = 0; y < 2; y++) { - for (let z = 0; z < 2; z++) { - const localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z)); - const localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1)); - const block = new OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc); - block.addEntries(entries); - target.blocks.push(block); - } - } - } - } -} -//# sourceMappingURL=octreeBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Culling/Octrees/octree.js - - -/** - * Octrees are a really powerful data structure that can quickly select entities based on space coordinates. - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees - */ -class Octree { - /** - * Creates a octree - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees - * @param creationFunc function to be used to instantiate the octree - * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64) - * @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.) - */ - constructor(creationFunc, maxBlockCapacity, - /** 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.) */ - maxDepth = 2) { - this.maxDepth = maxDepth; - /** - * Content stored in the octree - */ - this.dynamicContent = new Array(); - this._maxBlockCapacity = maxBlockCapacity || 64; - this._selectionContent = new SmartArrayNoDuplicate(1024); - this._creationFunc = creationFunc; - } - // Methods - /** - * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters - * @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); - * @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); - * @param entries meshes to be added to the octree blocks - */ - update(worldMin, worldMax, entries) { - OctreeBlock._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc); - } - /** - * Adds a mesh to the octree - * @param entry Mesh to add to the octree - */ - addMesh(entry) { - for (let index = 0; index < this.blocks.length; index++) { - const block = this.blocks[index]; - block.addEntry(entry); - } - } - /** - * Remove an element from the octree - * @param entry defines the element to remove - */ - removeMesh(entry) { - for (let index = 0; index < this.blocks.length; index++) { - const block = this.blocks[index]; - block.removeEntry(entry); - } - } - /** - * Selects an array of meshes within the frustum - * @param frustumPlanes The frustum planes to use which will select all meshes within it - * @param allowDuplicate If duplicate objects are allowed in the resulting object array - * @returns array of meshes within the frustum - */ - select(frustumPlanes, allowDuplicate) { - this._selectionContent.reset(); - for (let index = 0; index < this.blocks.length; index++) { - const block = this.blocks[index]; - block.select(frustumPlanes, this._selectionContent, allowDuplicate); - } - if (allowDuplicate) { - this._selectionContent.concat(this.dynamicContent); - } - else { - this._selectionContent.concatWithNoDuplicate(this.dynamicContent); - } - return this._selectionContent; - } - /** - * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array - * @param sphereCenter defines the bounding sphere center - * @param sphereRadius defines the bounding sphere radius - * @param allowDuplicate defines if the selection array can contains duplicated entries - * @returns an array of objects that intersect the sphere - */ - intersects(sphereCenter, sphereRadius, allowDuplicate) { - this._selectionContent.reset(); - for (let index = 0; index < this.blocks.length; index++) { - const block = this.blocks[index]; - block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate); - } - if (allowDuplicate) { - this._selectionContent.concat(this.dynamicContent); - } - else { - this._selectionContent.concatWithNoDuplicate(this.dynamicContent); - } - return this._selectionContent; - } - /** - * Test if the octree intersect with the given ray and if yes, then add its content to resulting array - * @param ray defines the ray to test with - * @returns array of intersected objects - */ - intersectsRay(ray) { - this._selectionContent.reset(); - for (let index = 0; index < this.blocks.length; index++) { - const block = this.blocks[index]; - block.intersectsRay(ray, this._selectionContent); - } - this._selectionContent.concatWithNoDuplicate(this.dynamicContent); - return this._selectionContent; - } -} -/** - * Adds a mesh into the octree block if it intersects the block - * @param entry - * @param block - */ -Octree.CreationFuncForMeshes = (entry, block) => { - const boundingInfo = entry.getBoundingInfo(); - if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) { - block.entries.push(entry); - } -}; -/** - * Adds a submesh into the octree block if it intersects the block - * @param entry - * @param block - */ -Octree.CreationFuncForSubMeshes = (entry, block) => { - const boundingInfo = entry.getBoundingInfo(); - if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) { - block.entries.push(entry); - } -}; -//# sourceMappingURL=octree.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Culling/Octrees/octreeSceneComponent.js - - - - - - - -scene_Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity = 64, maxDepth = 2) { - let component = this._getComponent(sceneComponent_SceneComponentConstants.NAME_OCTREE); - if (!component) { - component = new OctreeSceneComponent(this); - this._addComponent(component); - } - if (!this._selectionOctree) { - this._selectionOctree = new Octree(Octree.CreationFuncForMeshes, maxCapacity, maxDepth); - } - const worldExtends = this.getWorldExtends(); - // Update octree - this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes); - return this._selectionOctree; -}; -Object.defineProperty(scene_Scene.prototype, "selectionOctree", { - get: function () { - return this._selectionOctree; - }, - enumerable: true, - configurable: true, -}); -/** - * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations. - * Please note that you must have a decent number of submeshes to get performance improvements when using an octree - * @param maxCapacity defines the maximum size of each block (64 by default) - * @param maxDepth defines the maximum depth to use (no more than 2 levels by default) - * @returns the new octree - * @see https://www.babylonjs-playground.com/#NA4OQ#12 - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees - */ -abstractMesh_AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity = 64, maxDepth = 2) { - const scene = this.getScene(); - let component = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_OCTREE); - if (!component) { - component = new OctreeSceneComponent(scene); - scene._addComponent(component); - } - if (!this._submeshesOctree) { - this._submeshesOctree = new Octree(Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth); - } - this.computeWorldMatrix(true); - const boundingInfo = this.getBoundingInfo(); - // Update octree - const bbox = boundingInfo.boundingBox; - this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes); - return this._submeshesOctree; -}; -/** - * Defines the octree scene component responsible to manage any octrees - * in a given scene. - */ -class OctreeSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name help to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_OCTREE; - /** - * Indicates if the meshes have been checked to make sure they are isEnabled() - */ - this.checksIsEnabled = true; - this._tempRay = new ray_Ray(math_vector_Vector3.Zero(), new math_vector_Vector3(1, 1, 1)); - scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!scene) { - return; - } - this.scene = scene; - 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); - } - /** - * Registers the component in a given scene - */ - register() { - this.scene.onMeshRemovedObservable.add((mesh) => { - const sceneOctree = this.scene.selectionOctree; - if (sceneOctree !== undefined && sceneOctree !== null) { - const index = sceneOctree.dynamicContent.indexOf(mesh); - if (index !== -1) { - sceneOctree.dynamicContent.splice(index, 1); - } - } - }); - this.scene.onMeshImportedObservable.add((mesh) => { - const sceneOctree = this.scene.selectionOctree; - if (sceneOctree !== undefined && sceneOctree !== null) { - sceneOctree.addMesh(mesh); - } - }); - } - /** - * Return the list of active meshes - * @returns the list of active meshes - */ - getActiveMeshCandidates() { - var _a; - return ((_a = this.scene._selectionOctree) === null || _a === void 0 ? void 0 : _a.select(this.scene.frustumPlanes)) || this.scene._getDefaultMeshCandidates(); - } - /** - * Return the list of active sub meshes - * @param mesh The mesh to get the candidates sub meshes from - * @returns the list of active sub meshes - */ - getActiveSubMeshCandidates(mesh) { - if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) { - const intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes); - return intersections; - } - return this.scene._getDefaultSubMeshCandidates(mesh); - } - /** - * Return the list of sub meshes intersecting with a given local ray - * @param mesh defines the mesh to find the submesh for - * @param localRay defines the ray in local space - * @returns the list of intersecting sub meshes - */ - getIntersectingSubMeshCandidates(mesh, localRay) { - if (mesh._submeshesOctree && mesh.useOctreeForPicking) { - ray_Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay); - const intersections = mesh._submeshesOctree.intersectsRay(this._tempRay); - return intersections; - } - return this.scene._getDefaultSubMeshCandidates(mesh); - } - /** - * Return the list of sub meshes colliding with a collider - * @param mesh defines the mesh to find the submesh for - * @param collider defines the collider to evaluate the collision against - * @returns the list of colliding sub meshes - */ - getCollidingSubMeshCandidates(mesh, collider) { - if (mesh._submeshesOctree && mesh.useOctreeForCollisions) { - const radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z); - const intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius); - return intersections; - } - return this.scene._getDefaultSubMeshCandidates(mesh); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing to do here. - } - /** - * Disposes the component and the associated resources. - */ - dispose() { - // Nothing to do here. - } -} -//# sourceMappingURL=octreeSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Culling/Octrees/index.js - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Culling/index.js -/* eslint-disable import/no-internal-modules */ - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/utilityLayerRenderer.js - - - - - - - - -/** - * Renders a layer on top of an existing scene - */ -class utilityLayerRenderer_UtilityLayerRenderer { - /** - * Gets the camera that is used to render the utility layer (when not set, this will be the last active camera) - * @param getRigParentIfPossible if the current active camera is a rig camera, should its parent camera be returned - * @returns the camera that is used when rendering the utility layer - */ - getRenderCamera(getRigParentIfPossible) { - if (this._renderCamera) { - return this._renderCamera; - } - else { - let activeCam; - if (this.originalScene.activeCameras && this.originalScene.activeCameras.length > 1) { - activeCam = this.originalScene.activeCameras[this.originalScene.activeCameras.length - 1]; - } - else { - activeCam = this.originalScene.activeCamera; - } - if (getRigParentIfPossible && activeCam && activeCam.isRigCamera) { - return activeCam.rigParent; - } - return activeCam; - } - } - /** - * Sets the camera that should be used when rendering the utility layer (If set to null the last active camera will be used) - * @param cam the camera that should be used when rendering the utility layer - */ - setRenderCamera(cam) { - this._renderCamera = cam; - } - /** - * @internal - * Light which used by gizmos to get light shading - */ - _getSharedGizmoLight() { - if (!this._sharedGizmoLight) { - this._sharedGizmoLight = new HemisphericLight("shared gizmo light", new math_vector_Vector3(0, 1, 0), this.utilityLayerScene); - this._sharedGizmoLight.intensity = 2; - this._sharedGizmoLight.groundColor = math_color_Color3.Gray(); - } - return this._sharedGizmoLight; - } - /** - * 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) - */ - static get DefaultUtilityLayer() { - if (utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer == null) { - return utilityLayerRenderer_UtilityLayerRenderer._CreateDefaultUtilityLayerFromScene(engineStore_EngineStore.LastCreatedScene); - } - return utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer; - } - /** - * Creates an utility layer, and set it as a default utility layer - * @param scene associated scene - * @internal - */ - static _CreateDefaultUtilityLayerFromScene(scene) { - utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer = new utilityLayerRenderer_UtilityLayerRenderer(scene); - utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(() => { - utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer = null; - }); - return utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer; - } - /** - * 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) - */ - static get DefaultKeepDepthUtilityLayer() { - if (utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) { - utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new utilityLayerRenderer_UtilityLayerRenderer(engineStore_EngineStore.LastCreatedScene); - utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false; - utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(() => { - utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null; - }); - } - return utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer; - } - /** - * Instantiates a UtilityLayerRenderer - * @param originalScene the original scene that will be rendered on top of - * @param handleEvents boolean indicating if the utility layer should handle events - */ - constructor( - /** the original scene that will be rendered on top of */ - originalScene, handleEvents = true) { - this.originalScene = originalScene; - this._pointerCaptures = {}; - this._lastPointerEvents = {}; - this._sharedGizmoLight = null; - this._renderCamera = null; - /** - * If the picking should be done on the utility layer prior to the actual scene (Default: true) - */ - this.pickUtilitySceneFirst = true; - /** - * If the utility layer should automatically be rendered on top of existing scene - */ - this.shouldRender = true; - /** - * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene - */ - this.onlyCheckPointerDownEvents = true; - /** - * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default) - */ - this.processAllEvents = false; - /** - * Set to false to disable picking - */ - this.pickingEnabled = true; - /** - * Observable raised when the pointer moves from the utility layer scene to the main scene - */ - this.onPointerOutObservable = new observable_Observable(); - // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app - this.utilityLayerScene = new scene_Scene(originalScene.getEngine(), { virtual: true }); - this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem; - this.utilityLayerScene._allowPostProcessClearColor = false; - // Deactivate post processes - this.utilityLayerScene.postProcessesEnabled = false; - // Detach controls on utility scene, events will be fired by logic below to handle picking priority - this.utilityLayerScene.detachControl(); - if (handleEvents) { - this._originalPointerObserver = originalScene.onPrePointerObservable.add((prePointerInfo) => { - if (!this.utilityLayerScene.activeCamera) { - return; - } - if (!this.pickingEnabled) { - return; - } - if (!this.processAllEvents) { - if (prePointerInfo.type !== pointerEvents_PointerEventTypes.POINTERMOVE && - prePointerInfo.type !== pointerEvents_PointerEventTypes.POINTERUP && - prePointerInfo.type !== pointerEvents_PointerEventTypes.POINTERDOWN && - prePointerInfo.type !== pointerEvents_PointerEventTypes.POINTERDOUBLETAP) { - return; - } - } - this.utilityLayerScene.pointerX = originalScene.pointerX; - this.utilityLayerScene.pointerY = originalScene.pointerY; - const pointerEvent = prePointerInfo.event; - if (originalScene.isPointerCaptured(pointerEvent.pointerId)) { - this._pointerCaptures[pointerEvent.pointerId] = false; - return; - } - const getNearPickDataForScene = (scene) => { - let scenePick = null; - if (prePointerInfo.nearInteractionPickingInfo) { - if (prePointerInfo.nearInteractionPickingInfo.pickedMesh.getScene() == scene) { - scenePick = prePointerInfo.nearInteractionPickingInfo; - } - else { - scenePick = new PickingInfo(); - } - } - else if (scene !== this.utilityLayerScene && prePointerInfo.originalPickingInfo) { - scenePick = prePointerInfo.originalPickingInfo; - } - else { - let previousActiveCamera = null; - // If a camera is set for rendering with this layer - // it will also be used for the ray computation - // To preserve back compat and because scene.pick always use activeCamera - // it's substituted temporarily and a new scenePick is forced. - // otherwise, the ray with previously active camera is always used. - // It's set back to previous activeCamera after operation. - if (this._renderCamera) { - previousActiveCamera = scene._activeCamera; - scene._activeCamera = this._renderCamera; - prePointerInfo.ray = null; - } - scenePick = prePointerInfo.ray ? scene.pickWithRay(prePointerInfo.ray) : scene.pick(originalScene.pointerX, originalScene.pointerY); - if (previousActiveCamera) { - scene._activeCamera = previousActiveCamera; - } - } - return scenePick; - }; - const utilityScenePick = getNearPickDataForScene(this.utilityLayerScene); - if (!prePointerInfo.ray && utilityScenePick) { - prePointerInfo.ray = utilityScenePick.ray; - } - // always fire the prepointer observable - this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo); - // allow every non pointer down event to flow to the utility layer - if (this.onlyCheckPointerDownEvents && prePointerInfo.type != pointerEvents_PointerEventTypes.POINTERDOWN) { - if (!prePointerInfo.skipOnPointerObservable) { - this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick), prePointerInfo.type); - } - if (prePointerInfo.type === pointerEvents_PointerEventTypes.POINTERUP && this._pointerCaptures[pointerEvent.pointerId]) { - this._pointerCaptures[pointerEvent.pointerId] = false; - } - return; - } - if (this.utilityLayerScene.autoClearDepthAndStencil || this.pickUtilitySceneFirst) { - // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene - if (utilityScenePick && utilityScenePick.hit) { - if (!prePointerInfo.skipOnPointerObservable) { - this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick), prePointerInfo.type); - } - prePointerInfo.skipOnPointerObservable = true; - } - } - else { - const originalScenePick = getNearPickDataForScene(originalScene); - const pointerEvent = prePointerInfo.event; - // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray - if (originalScenePick && utilityScenePick) { - // No pick in utility scene - if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) { - if (this.mainSceneTrackerPredicate && this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) { - // We touched an utility mesh present in the main scene - this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent); - prePointerInfo.skipOnPointerObservable = true; - } - else if (prePointerInfo.type === pointerEvents_PointerEventTypes.POINTERDOWN) { - this._pointerCaptures[pointerEvent.pointerId] = true; - } - else if (prePointerInfo.type === pointerEvents_PointerEventTypes.POINTERMOVE || prePointerInfo.type === pointerEvents_PointerEventTypes.POINTERUP) { - if (this._lastPointerEvents[pointerEvent.pointerId]) { - // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete - this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId); - delete this._lastPointerEvents[pointerEvent.pointerId]; - } - this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent); - } - } - else if (!this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) { - // We pick something in utility scene or the pick in utility is closer than the one in main scene - this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent); - // If a previous utility layer set this, do not unset this - if (!prePointerInfo.skipOnPointerObservable) { - prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0; - } - } - else if (!this._pointerCaptures[pointerEvent.pointerId] && utilityScenePick.distance >= originalScenePick.distance) { - // We have a pick in both scenes but main is closer than utility - // We touched an utility mesh present in the main scene - if (this.mainSceneTrackerPredicate && this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) { - this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent); - prePointerInfo.skipOnPointerObservable = true; - } - else { - if (prePointerInfo.type === pointerEvents_PointerEventTypes.POINTERMOVE || prePointerInfo.type === pointerEvents_PointerEventTypes.POINTERUP) { - if (this._lastPointerEvents[pointerEvent.pointerId]) { - // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete - this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId); - delete this._lastPointerEvents[pointerEvent.pointerId]; - } - } - this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent); - } - } - if (prePointerInfo.type === pointerEvents_PointerEventTypes.POINTERUP && this._pointerCaptures[pointerEvent.pointerId]) { - this._pointerCaptures[pointerEvent.pointerId] = false; - } - } - } - }); - // As a newly added utility layer will be rendered over the screen last, it's pointer events should be processed first - if (this._originalPointerObserver) { - originalScene.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver); - } - } - // Render directly on top of existing scene without clearing - this.utilityLayerScene.autoClear = false; - this._afterRenderObserver = this.originalScene.onAfterRenderCameraObservable.add((camera) => { - // Only render when the render camera finishes rendering - if (this.shouldRender && camera == this.getRenderCamera()) { - this.render(); - } - }); - this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(() => { - this.dispose(); - }); - this._updateCamera(); - } - _notifyObservers(prePointerInfo, pickInfo, pointerEvent) { - if (!prePointerInfo.skipOnPointerObservable) { - this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo), prePointerInfo.type); - this._lastPointerEvents[pointerEvent.pointerId] = true; - } - } - /** - * Renders the utility layers scene on top of the original scene - */ - render() { - this._updateCamera(); - if (this.utilityLayerScene.activeCamera) { - // Set the camera's scene to utility layers scene - const oldScene = this.utilityLayerScene.activeCamera.getScene(); - const camera = this.utilityLayerScene.activeCamera; - camera._scene = this.utilityLayerScene; - if (camera.leftCamera) { - camera.leftCamera._scene = this.utilityLayerScene; - } - if (camera.rightCamera) { - camera.rightCamera._scene = this.utilityLayerScene; - } - this.utilityLayerScene.render(false); - // Reset camera's scene back to original - camera._scene = oldScene; - if (camera.leftCamera) { - camera.leftCamera._scene = oldScene; - } - if (camera.rightCamera) { - camera.rightCamera._scene = oldScene; - } - } - } - /** - * Disposes of the renderer - */ - dispose() { - this.onPointerOutObservable.clear(); - if (this._afterRenderObserver) { - this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver); - } - if (this._sceneDisposeObserver) { - this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver); - } - if (this._originalPointerObserver) { - this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver); - } - this.utilityLayerScene.dispose(); - } - _updateCamera() { - this.utilityLayerScene.cameraToUseForPointers = this.getRenderCamera(); - this.utilityLayerScene.activeCamera = this.getRenderCamera(); - } -} -/** @internal */ -utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer = null; -/** @internal */ -utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null; -//# sourceMappingURL=utilityLayerRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/gizmo.js - - - - - - -/** - * Anchor options where the Gizmo can be positioned in relation to its anchored node - */ -var GizmoAnchorPoint; -(function (GizmoAnchorPoint) { - /** The origin of the attached node */ - GizmoAnchorPoint[GizmoAnchorPoint["Origin"] = 0] = "Origin"; - /** The pivot point of the attached node*/ - GizmoAnchorPoint[GizmoAnchorPoint["Pivot"] = 1] = "Pivot"; -})(GizmoAnchorPoint || (GizmoAnchorPoint = {})); -/** - * Coordinates mode: Local or World. Defines how axis is aligned: either on world axis or transform local axis - */ -var gizmo_GizmoCoordinatesMode; -(function (GizmoCoordinatesMode) { - GizmoCoordinatesMode[GizmoCoordinatesMode["World"] = 0] = "World"; - GizmoCoordinatesMode[GizmoCoordinatesMode["Local"] = 1] = "Local"; -})(gizmo_GizmoCoordinatesMode || (gizmo_GizmoCoordinatesMode = {})); -/** - * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc. - */ -class gizmo_Gizmo { - /** - * Ratio for the scale of the gizmo (Default: 1) - */ - set scaleRatio(value) { - this._scaleRatio = value; - } - get scaleRatio() { - return this._scaleRatio; - } - /** - * True when the mouse pointer is hovered a gizmo mesh - */ - get isHovered() { - return this._isHovered; - } - /** - * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged) - * * When set, interactions will be enabled - */ - get attachedMesh() { - return this._attachedMesh; - } - set attachedMesh(value) { - this._attachedMesh = value; - if (value) { - this._attachedNode = value; - } - this._rootMesh.setEnabled(value ? true : false); - this._attachedNodeChanged(value); - } - /** - * Node that the gizmo will be attached to. (eg. on a drag gizmo the mesh, bone or NodeTransform that will be dragged) - * * When set, interactions will be enabled - */ - get attachedNode() { - return this._attachedNode; - } - set attachedNode(value) { - this._attachedNode = value; - this._attachedMesh = null; - this._rootMesh.setEnabled(value ? true : false); - this._attachedNodeChanged(value); - } - /** - * Disposes and replaces the current meshes in the gizmo with the specified mesh - * @param mesh The mesh to replace the default mesh of the gizmo - */ - setCustomMesh(mesh) { - if (mesh.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((c) => { - c.dispose(); - }); - mesh.parent = this._rootMesh; - this._customMeshSet = true; - } - /** - * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true) - * NOTE: This is only possible for meshes with uniform scaling, as otherwise it's not possible to decompose the rotation - */ - set updateGizmoRotationToMatchAttachedMesh(value) { - this._updateGizmoRotationToMatchAttachedMesh = value; - } - get updateGizmoRotationToMatchAttachedMesh() { - return this._updateGizmoRotationToMatchAttachedMesh; - } - /** - * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true) - */ - set updateGizmoPositionToMatchAttachedMesh(value) { - this._updateGizmoPositionToMatchAttachedMesh = value; - } - get updateGizmoPositionToMatchAttachedMesh() { - return this._updateGizmoPositionToMatchAttachedMesh; - } - /** - * Defines where the gizmo will be positioned if `updateGizmoPositionToMatchAttachedMesh` is enabled. - * (Default: GizmoAnchorPoint.Origin) - */ - set anchorPoint(value) { - this._anchorPoint = value; - } - get anchorPoint() { - return this._anchorPoint; - } - /** - * Set the coordinate system to use. By default it's local. - * But it's possible for a user to tweak so its local for translation and world for rotation. - * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh` - */ - set coordinatesMode(coordinatesMode) { - this._coordinatesMode = coordinatesMode; - const local = coordinatesMode == gizmo_GizmoCoordinatesMode.Local; - this.updateGizmoRotationToMatchAttachedMesh = local; - this.updateGizmoPositionToMatchAttachedMesh = local; - } - get coordinatesMode() { - return this._coordinatesMode; - } - /** - * When set, the gizmo will always appear the same size no matter where the camera is (default: true) - */ - set updateScale(value) { - this._updateScale = value; - } - get updateScale() { - return this._updateScale; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _attachedNodeChanged(value) { } - /** - * Creates a gizmo - * @param gizmoLayer The utility layer the gizmo will be added to - */ - constructor( - /** The utility layer the gizmo will be added to */ - gizmoLayer = utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer) { - this.gizmoLayer = gizmoLayer; - this._attachedMesh = null; - this._attachedNode = null; - this._customRotationQuaternion = null; - /** - * Ratio for the scale of the gizmo (Default: 1) - */ - this._scaleRatio = 1; - /** - * boolean updated by pointermove when a gizmo mesh is hovered - */ - this._isHovered = false; - /** - * If a custom mesh has been set (Default: false) - */ - this._customMeshSet = false; - this._updateGizmoRotationToMatchAttachedMesh = true; - this._updateGizmoPositionToMatchAttachedMesh = true; - this._anchorPoint = GizmoAnchorPoint.Origin; - this._updateScale = true; - this._coordinatesMode = gizmo_GizmoCoordinatesMode.Local; - this._interactionsEnabled = true; - this._rightHandtoLeftHandMatrix = math_vector_Matrix.RotationY(Math.PI); - this._rootMesh = new mesh_Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene); - this._rootMesh.rotationQuaternion = math_vector_Quaternion.Identity(); - this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(() => { - this._update(); - }); - } - /** - * posture that the gizmo will be display - * When set null, default value will be used (Quaternion(0, 0, 0, 1)) - */ - get customRotationQuaternion() { - return this._customRotationQuaternion; - } - set customRotationQuaternion(customRotationQuaternion) { - this._customRotationQuaternion = customRotationQuaternion; - } - /** - * Updates the gizmo to match the attached mesh's position/rotation - */ - _update() { - if (this.attachedNode) { - let effectiveNode = this.attachedNode; - if (this.attachedMesh) { - effectiveNode = this.attachedMesh || this.attachedNode; - } - // Position - if (this.updateGizmoPositionToMatchAttachedMesh) { - if (this.anchorPoint == GizmoAnchorPoint.Pivot && effectiveNode.getAbsolutePivotPoint) { - const position = effectiveNode.getAbsolutePivotPoint(); - this._rootMesh.position.copyFrom(position); - } - else { - const row = effectiveNode.getWorldMatrix().getRow(3); - const position = row ? row.toVector3() : new math_vector_Vector3(0, 0, 0); - this._rootMesh.position.copyFrom(position); - } - } - // Rotation - if (this.updateGizmoRotationToMatchAttachedMesh) { - const supportedNode = effectiveNode._isMesh || - effectiveNode.getClassName() === "AbstractMesh" || - effectiveNode.getClassName() === "TransformNode" || - effectiveNode.getClassName() === "InstancedMesh"; - const transformNode = supportedNode ? effectiveNode : undefined; - effectiveNode.getWorldMatrix().decompose(undefined, this._rootMesh.rotationQuaternion, undefined, gizmo_Gizmo.PreserveScaling ? transformNode : undefined); - } - else { - if (this._customRotationQuaternion) { - this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion); - } - else { - this._rootMesh.rotationQuaternion.set(0, 0, 0, 1); - } - } - // Scale - if (this.updateScale) { - const activeCamera = this.gizmoLayer.utilityLayerScene.activeCamera; - let cameraPosition = activeCamera.globalPosition; - if (activeCamera.devicePosition) { - cameraPosition = activeCamera.devicePosition; - } - this._rootMesh.position.subtractToRef(cameraPosition, math_vector_TmpVectors.Vector3[0]); - let scale = this.scaleRatio; - if (activeCamera.mode == camera_Camera.ORTHOGRAPHIC_CAMERA) { - if (activeCamera.orthoTop && activeCamera.orthoBottom) { - const orthoHeight = activeCamera.orthoTop - activeCamera.orthoBottom; - scale *= orthoHeight; - } - } - else { - const camForward = activeCamera.getScene().useRightHandedSystem ? math_vector_Vector3.RightHandedForwardReadOnly : math_vector_Vector3.LeftHandedForwardReadOnly; - const direction = activeCamera.getDirection(camForward); - scale *= math_vector_Vector3.Dot(math_vector_TmpVectors.Vector3[0], direction); - } - this._rootMesh.scaling.setAll(scale); - // Account for handedness, similar to Matrix.decompose - if (effectiveNode._getWorldMatrixDeterminant() < 0 && !gizmo_Gizmo.PreserveScaling) { - this._rootMesh.scaling.y *= -1; - } - } - else { - this._rootMesh.scaling.setAll(this.scaleRatio); - } - } - } - /** - * Handle position/translation when using an attached node using pivot - */ - _handlePivot() { - const attachedNodeTransform = this._attachedNode; - // check there is an active pivot for the TransformNode attached - if (attachedNodeTransform.isUsingPivotMatrix && attachedNodeTransform.isUsingPivotMatrix() && attachedNodeTransform.position) { - // When a TransformNode has an active pivot, even without parenting, - // translation from the world matrix is different from TransformNode.position. - // Pivot works like a virtual parent that's using the node orientation. - // As the world matrix is transformed by the gizmo and then decomposed to TRS - // its translation part must be set to the Node's position. - attachedNodeTransform.getWorldMatrix().setTranslation(attachedNodeTransform.position); - } - } - /** - * computes the rotation/scaling/position of the transform once the Node world matrix has changed. - */ - _matrixChanged() { - if (!this._attachedNode) { - return; - } - if (this._attachedNode._isCamera) { - const camera = this._attachedNode; - let worldMatrix; - let worldMatrixUC; - if (camera.parent) { - const parentInv = math_vector_TmpVectors.Matrix[1]; - camera.parent._worldMatrix.invertToRef(parentInv); - this._attachedNode._worldMatrix.multiplyToRef(parentInv, math_vector_TmpVectors.Matrix[0]); - worldMatrix = math_vector_TmpVectors.Matrix[0]; - } - else { - worldMatrix = this._attachedNode._worldMatrix; - } - if (camera.getScene().useRightHandedSystem) { - // 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. - this._rightHandtoLeftHandMatrix.multiplyToRef(worldMatrix, math_vector_TmpVectors.Matrix[1]); - worldMatrixUC = math_vector_TmpVectors.Matrix[1]; - } - else { - worldMatrixUC = worldMatrix; - } - worldMatrixUC.decompose(math_vector_TmpVectors.Vector3[1], math_vector_TmpVectors.Quaternion[0], math_vector_TmpVectors.Vector3[0]); - const inheritsTargetCamera = this._attachedNode.getClassName() === "FreeCamera" || - this._attachedNode.getClassName() === "FlyCamera" || - this._attachedNode.getClassName() === "ArcFollowCamera" || - this._attachedNode.getClassName() === "TargetCamera" || - this._attachedNode.getClassName() === "TouchCamera" || - this._attachedNode.getClassName() === "UniversalCamera"; - if (inheritsTargetCamera) { - const targetCamera = this._attachedNode; - targetCamera.rotation = math_vector_TmpVectors.Quaternion[0].toEulerAngles(); - if (targetCamera.rotationQuaternion) { - targetCamera.rotationQuaternion.copyFrom(math_vector_TmpVectors.Quaternion[0]); - targetCamera.rotationQuaternion.normalize(); - } - } - camera.position.copyFrom(math_vector_TmpVectors.Vector3[0]); - } - else if (this._attachedNode._isMesh || - this._attachedNode.getClassName() === "AbstractMesh" || - this._attachedNode.getClassName() === "TransformNode" || - this._attachedNode.getClassName() === "InstancedMesh") { - const transform = this._attachedNode; - if (transform.parent) { - const parentInv = math_vector_TmpVectors.Matrix[0]; - const localMat = math_vector_TmpVectors.Matrix[1]; - transform.parent.getWorldMatrix().invertToRef(parentInv); - this._attachedNode.getWorldMatrix().multiplyToRef(parentInv, localMat); - localMat.decompose(math_vector_TmpVectors.Vector3[0], math_vector_TmpVectors.Quaternion[0], transform.position, gizmo_Gizmo.PreserveScaling ? transform : undefined); - } - else { - this._attachedNode._worldMatrix.decompose(math_vector_TmpVectors.Vector3[0], math_vector_TmpVectors.Quaternion[0], transform.position, gizmo_Gizmo.PreserveScaling ? transform : undefined); - } - math_vector_TmpVectors.Vector3[0].scaleInPlace(1.0 / transform.scalingDeterminant); - transform.scaling.copyFrom(math_vector_TmpVectors.Vector3[0]); - if (!transform.billboardMode) { - if (transform.rotationQuaternion) { - transform.rotationQuaternion.copyFrom(math_vector_TmpVectors.Quaternion[0]); - transform.rotationQuaternion.normalize(); - } - else { - transform.rotation = math_vector_TmpVectors.Quaternion[0].toEulerAngles(); - } - } - } - else if (this._attachedNode.getClassName() === "Bone") { - const bone = this._attachedNode; - const parent = bone.getParent(); - if (parent) { - const invParent = math_vector_TmpVectors.Matrix[0]; - const boneLocalMatrix = math_vector_TmpVectors.Matrix[1]; - parent.getFinalMatrix().invertToRef(invParent); - bone.getFinalMatrix().multiplyToRef(invParent, boneLocalMatrix); - const lmat = bone.getLocalMatrix(); - lmat.copyFrom(boneLocalMatrix); - } - else { - const lmat = bone.getLocalMatrix(); - lmat.copyFrom(bone.getFinalMatrix()); - } - bone.markAsDirty(); - } - else { - const light = this._attachedNode; - if (light.getTypeID) { - const type = light.getTypeID(); - if (type === light_Light.LIGHTTYPEID_DIRECTIONALLIGHT || type === light_Light.LIGHTTYPEID_SPOTLIGHT || type === light_Light.LIGHTTYPEID_POINTLIGHT) { - const parent = light.parent; - if (parent) { - const invParent = math_vector_TmpVectors.Matrix[0]; - const nodeLocalMatrix = math_vector_TmpVectors.Matrix[1]; - parent.getWorldMatrix().invertToRef(invParent); - light.getWorldMatrix().multiplyToRef(invParent, nodeLocalMatrix); - nodeLocalMatrix.decompose(undefined, math_vector_TmpVectors.Quaternion[0], math_vector_TmpVectors.Vector3[0]); - } - else { - this._attachedNode._worldMatrix.decompose(undefined, math_vector_TmpVectors.Quaternion[0], math_vector_TmpVectors.Vector3[0]); - } - // setter doesn't copy values. Need a new Vector3 - light.position = new math_vector_Vector3(math_vector_TmpVectors.Vector3[0].x, math_vector_TmpVectors.Vector3[0].y, math_vector_TmpVectors.Vector3[0].z); - if (light.direction) { - light.direction = new math_vector_Vector3(light.direction.x, light.direction.y, light.direction.z); - } - } - } - } - } - /** - * refresh gizmo mesh material - * @param gizmoMeshes - * @param material material to apply - */ - _setGizmoMeshMaterial(gizmoMeshes, material) { - if (gizmoMeshes) { - gizmoMeshes.forEach((m) => { - m.material = material; - if (m.color) { - m.color = material.diffuseColor; - } - }); - } - } - /** - * Subscribes to pointer up, down, and hover events. Used for responsive gizmos. - * @param gizmoLayer The utility layer the gizmo will be added to - * @param gizmoAxisCache Gizmo axis definition used for reactive gizmo UI - * @returns {Observer<PointerInfo>} pointerObserver - */ - static GizmoAxisPointerObserver(gizmoLayer, gizmoAxisCache) { - let dragging = false; - const pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => { - var _a, _b; - if (pointerInfo.pickInfo) { - // On Hover Logic - if (pointerInfo.type === pointerEvents_PointerEventTypes.POINTERMOVE) { - if (dragging) { - return; - } - gizmoAxisCache.forEach((cache) => { - var _a, _b; - if (cache.colliderMeshes && cache.gizmoMeshes) { - 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; - const material = cache.dragBehavior.enabled ? (isHovered || cache.active ? cache.hoverMaterial : cache.material) : cache.disableMaterial; - cache.gizmoMeshes.forEach((m) => { - m.material = material; - if (m.color) { - m.color = material.diffuseColor; - } - }); - } - }); - } - // On Mouse Down - if (pointerInfo.type === pointerEvents_PointerEventTypes.POINTERDOWN) { - // If user Clicked Gizmo - if (gizmoAxisCache.has((_a = pointerInfo.pickInfo.pickedMesh) === null || _a === void 0 ? void 0 : _a.parent)) { - dragging = true; - const statusMap = gizmoAxisCache.get((_b = pointerInfo.pickInfo.pickedMesh) === null || _b === void 0 ? void 0 : _b.parent); - statusMap.active = true; - gizmoAxisCache.forEach((cache) => { - var _a, _b; - 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; - const material = (isHovered || cache.active) && cache.dragBehavior.enabled ? cache.hoverMaterial : cache.disableMaterial; - cache.gizmoMeshes.forEach((m) => { - m.material = material; - if (m.color) { - m.color = material.diffuseColor; - } - }); - }); - } - } - // On Mouse Up - if (pointerInfo.type === pointerEvents_PointerEventTypes.POINTERUP) { - gizmoAxisCache.forEach((cache) => { - cache.active = false; - dragging = false; - cache.gizmoMeshes.forEach((m) => { - m.material = cache.dragBehavior.enabled ? cache.material : cache.disableMaterial; - if (m.color) { - m.color = cache.material.diffuseColor; - } - }); - }); - } - } - }); - return pointerObserver; - } - /** - * Disposes of the gizmo - */ - dispose() { - this._rootMesh.dispose(); - if (this._beforeRenderObserver) { - this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver); - } - } -} -/** - * When enabled, any gizmo operation will perserve scaling sign. Default is off. - * Only valid for TransformNode derived classes (Mesh, AbstractMesh, ...) - */ -gizmo_Gizmo.PreserveScaling = false; -//# sourceMappingURL=gizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/axisDragGizmo.js - - - - - - - - - - -/** - * Single axis drag gizmo - */ -class axisDragGizmo_AxisDragGizmo extends (/* unused pure expression or super */ null && (Gizmo)) { - /** Default material used to render when gizmo is not disabled or hovered */ - get coloredMaterial() { - return this._coloredMaterial; - } - /** Material used to render when gizmo is hovered with mouse*/ - get hoverMaterial() { - return this._hoverMaterial; - } - /** Material used to render when gizmo is disabled. typically grey.*/ - get disableMaterial() { - return this._disableMaterial; - } - /** - * @internal - */ - static _CreateArrow(scene, material, thickness = 1, isCollider = false) { - const arrow = new TransformNode("arrow", scene); - const cylinder = CreateCylinder("cylinder", { diameterTop: 0, height: 0.075, diameterBottom: 0.0375 * (1 + (thickness - 1) / 4), tessellation: 96 }, scene); - const line = CreateCylinder("cylinder", { diameterTop: 0.005 * thickness, height: 0.275, diameterBottom: 0.005 * thickness, tessellation: 96 }, scene); - // Position arrow pointing in its drag axis - cylinder.parent = arrow; - cylinder.material = material; - cylinder.rotation.x = Math.PI / 2; - cylinder.position.z += 0.3; - line.parent = arrow; - line.material = material; - line.position.z += 0.275 / 2; - line.rotation.x = Math.PI / 2; - if (isCollider) { - line.visibility = 0; - cylinder.visibility = 0; - } - return arrow; - } - /** - * @internal - */ - static _CreateArrowInstance(scene, arrow) { - const instance = new TransformNode("arrow", scene); - for (const mesh of arrow.getChildMeshes()) { - const childInstance = mesh.createInstance(mesh.name); - childInstance.parent = instance; - } - return instance; - } - /** - * Creates an AxisDragGizmo - * @param dragAxis The axis which the gizmo will be able to drag on - * @param color The color of the gizmo - * @param gizmoLayer The utility layer the gizmo will be added to - * @param parent - * @param thickness display gizmo axis thickness - */ - constructor(dragAxis, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, parent = null, thickness = 1) { - var _a; - super(gizmoLayer); - this._pointerObserver = null; - /** - * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) - */ - this.snapDistance = 0; - /** - * Event that fires each time the gizmo snaps to a new location. - * * snapDistance is the the change in distance - */ - this.onSnapObservable = new Observable(); - this._isEnabled = true; - this._parent = null; - this._dragging = false; - this._parent = parent; - // Create Material - this._coloredMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._coloredMaterial.diffuseColor = color; - this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1)); - this._hoverMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._hoverMaterial.diffuseColor = Color3.Yellow(); - this._disableMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._disableMaterial.diffuseColor = Color3.Gray(); - this._disableMaterial.alpha = 0.4; - // Build Mesh + Collider - const arrow = axisDragGizmo_AxisDragGizmo._CreateArrow(gizmoLayer.utilityLayerScene, this._coloredMaterial, thickness); - const collider = axisDragGizmo_AxisDragGizmo._CreateArrow(gizmoLayer.utilityLayerScene, this._coloredMaterial, thickness + 4, true); - // Add to Root Node - this._gizmoMesh = new Mesh("", gizmoLayer.utilityLayerScene); - this._gizmoMesh.addChild(arrow); - this._gizmoMesh.addChild(collider); - this._gizmoMesh.lookAt(this._rootMesh.position.add(dragAxis)); - this._gizmoMesh.scaling.scaleInPlace(1 / 3); - this._gizmoMesh.parent = this._rootMesh; - let currentSnapDragDistance = 0; - const tmpSnapEvent = { snapDistance: 0 }; - // Add drag behavior to handle events when the gizmo is dragged - this.dragBehavior = new PointerDragBehavior({ dragAxis: dragAxis }); - this.dragBehavior.moveAttached = false; - this.dragBehavior.updateDragPlane = false; - this._rootMesh.addBehavior(this.dragBehavior); - this.dragBehavior.onDragObservable.add((event) => { - if (this.attachedNode) { - this._handlePivot(); - // Keep world translation and use it to update world transform - // if the node has parent, the local transform properties (position, rotation, scale) - // will be recomputed in _matrixChanged function - let matrixChanged = false; - // Snapping logic - if (this.snapDistance == 0) { - this.attachedNode.getWorldMatrix().getTranslationToRef(TmpVectors.Vector3[2]); - TmpVectors.Vector3[2].addInPlace(event.delta); - if (this.dragBehavior.validateDrag(TmpVectors.Vector3[2])) { - if (this.attachedNode.position) { - // Required for nodes like lights - this.attachedNode.position.addInPlaceFromFloats(event.delta.x, event.delta.y, event.delta.z); - } - // use _worldMatrix to not force a matrix update when calling GetWorldMatrix especially with Cameras - this.attachedNode.getWorldMatrix().addTranslationFromFloats(event.delta.x, event.delta.y, event.delta.z); - this.attachedNode.updateCache(); - matrixChanged = true; - } - } - else { - currentSnapDragDistance += event.dragDistance; - if (Math.abs(currentSnapDragDistance) > this.snapDistance) { - const dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance); - currentSnapDragDistance = currentSnapDragDistance % this.snapDistance; - event.delta.normalizeToRef(TmpVectors.Vector3[1]); - TmpVectors.Vector3[1].scaleInPlace(this.snapDistance * dragSteps); - this.attachedNode.getWorldMatrix().getTranslationToRef(TmpVectors.Vector3[2]); - TmpVectors.Vector3[2].addInPlace(TmpVectors.Vector3[1]); - if (this.dragBehavior.validateDrag(TmpVectors.Vector3[2])) { - this.attachedNode.getWorldMatrix().addTranslationFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[1].z); - this.attachedNode.updateCache(); - tmpSnapEvent.snapDistance = this.snapDistance * dragSteps; - this.onSnapObservable.notifyObservers(tmpSnapEvent); - matrixChanged = true; - } - } - } - if (matrixChanged) { - this._matrixChanged(); - } - } - }); - this.dragBehavior.onDragStartObservable.add(() => { - this._dragging = true; - }); - this.dragBehavior.onDragEndObservable.add(() => { - this._dragging = false; - }); - const light = gizmoLayer._getSharedGizmoLight(); - light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(false)); - const cache = { - gizmoMeshes: arrow.getChildMeshes(), - colliderMeshes: collider.getChildMeshes(), - material: this._coloredMaterial, - hoverMaterial: this._hoverMaterial, - disableMaterial: this._disableMaterial, - active: false, - dragBehavior: this.dragBehavior, - }; - (_a = this._parent) === null || _a === void 0 ? void 0 : _a.addToAxisCache(collider, cache); - this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => { - var _a; - if (this._customMeshSet) { - return; - } - this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1); - if (!this._parent) { - const material = this.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial; - this._setGizmoMeshMaterial(cache.gizmoMeshes, material); - } - }); - this.dragBehavior.onEnabledObservable.add((newState) => { - this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? cache.material : cache.disableMaterial); - }); - } - _attachedNodeChanged(value) { - if (this.dragBehavior) { - this.dragBehavior.enabled = value ? true : false; - } - } - /** - * If the gizmo is enabled - */ - set isEnabled(value) { - this._isEnabled = value; - if (!value) { - this.attachedMesh = null; - this.attachedNode = null; - } - else { - if (this._parent) { - this.attachedMesh = this._parent.attachedMesh; - this.attachedNode = this._parent.attachedNode; - } - } - } - get isEnabled() { - return this._isEnabled; - } - /** - * Disposes of the gizmo - */ - dispose() { - this.onSnapObservable.clear(); - this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); - this.dragBehavior.detach(); - if (this._gizmoMesh) { - this._gizmoMesh.dispose(); - } - [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => { - if (matl) { - matl.dispose(); - } - }); - super.dispose(); - } -} -//# sourceMappingURL=axisDragGizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Debug/axesViewer.js - - - - - -/** - * The Axes viewer will show 3 axes in a specific point in space - * @see https://doc.babylonjs.com/toolsAndResources/utilities/World_Axes - */ -class axesViewer_AxesViewer { - /** Gets the node hierarchy used to render x-axis */ - get xAxis() { - return this._xAxis; - } - /** Gets the node hierarchy used to render y-axis */ - get yAxis() { - return this._yAxis; - } - /** Gets the node hierarchy used to render z-axis */ - get zAxis() { - return this._zAxis; - } - /** - * Creates a new AxesViewer - * @param scene defines the hosting scene - * @param scaleLines defines a number used to scale line length (1 by default) - * @param renderingGroupId defines a number used to set the renderingGroupId of the meshes (2 by default) - * @param xAxis defines the node hierarchy used to render the x-axis - * @param yAxis defines the node hierarchy used to render the y-axis - * @param zAxis defines the node hierarchy used to render the z-axis - * @param lineThickness The line thickness to use when creating the arrow. defaults to 1. - */ - constructor(scene, scaleLines = 1, renderingGroupId = 2, xAxis, yAxis, zAxis, lineThickness = 1) { - this._scaleLinesFactor = 4; - this._instanced = false; - /** - * Gets the hosting scene - */ - this.scene = null; - /** - * Gets or sets a number used to scale line length - */ - this.scaleLines = 1; - scene = scene || EngineStore.LastCreatedScene; - if (!scene) { - return; - } - this.scaleLines = scaleLines; - if (!xAxis) { - const redColoredMaterial = new StandardMaterial("xAxisMaterial", scene); - redColoredMaterial.disableLighting = true; - redColoredMaterial.emissiveColor = Color3.Red().scale(0.5); - xAxis = AxisDragGizmo._CreateArrow(scene, redColoredMaterial, lineThickness); - } - if (!yAxis) { - const greenColoredMaterial = new StandardMaterial("yAxisMaterial", scene); - greenColoredMaterial.disableLighting = true; - greenColoredMaterial.emissiveColor = Color3.Green().scale(0.5); - yAxis = AxisDragGizmo._CreateArrow(scene, greenColoredMaterial, lineThickness); - } - if (!zAxis) { - const blueColoredMaterial = new StandardMaterial("zAxisMaterial", scene); - blueColoredMaterial.disableLighting = true; - blueColoredMaterial.emissiveColor = Color3.Blue().scale(0.5); - zAxis = AxisDragGizmo._CreateArrow(scene, blueColoredMaterial, lineThickness); - } - this._xAxis = xAxis; - this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); - this._yAxis = yAxis; - this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); - this._zAxis = zAxis; - this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); - if (renderingGroupId != null) { - axesViewer_AxesViewer._SetRenderingGroupId(this._xAxis, renderingGroupId); - axesViewer_AxesViewer._SetRenderingGroupId(this._yAxis, renderingGroupId); - axesViewer_AxesViewer._SetRenderingGroupId(this._zAxis, renderingGroupId); - } - this.scene = scene; - this.update(new Vector3(), Vector3.Right(), Vector3.Up(), Vector3.Forward()); - } - /** - * Force the viewer to update - * @param position defines the position of the viewer - * @param xaxis defines the x axis of the viewer - * @param yaxis defines the y axis of the viewer - * @param zaxis defines the z axis of the viewer - */ - update(position, xaxis, yaxis, zaxis) { - this._xAxis.position.copyFrom(position); - this._xAxis.setDirection(xaxis); - this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); - this._yAxis.position.copyFrom(position); - this._yAxis.setDirection(yaxis); - this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); - this._zAxis.position.copyFrom(position); - this._zAxis.setDirection(zaxis); - this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); - } - /** - * Creates an instance of this axes viewer. - * @returns a new axes viewer with instanced meshes - */ - createInstance() { - const xAxis = AxisDragGizmo._CreateArrowInstance(this.scene, this._xAxis); - const yAxis = AxisDragGizmo._CreateArrowInstance(this.scene, this._yAxis); - const zAxis = AxisDragGizmo._CreateArrowInstance(this.scene, this._zAxis); - const axesViewer = new axesViewer_AxesViewer(this.scene, this.scaleLines, null, xAxis, yAxis, zAxis); - axesViewer._instanced = true; - return axesViewer; - } - /** Releases resources */ - dispose() { - if (this._xAxis) { - this._xAxis.dispose(false, !this._instanced); - } - if (this._yAxis) { - this._yAxis.dispose(false, !this._instanced); - } - if (this._zAxis) { - this._zAxis.dispose(false, !this._instanced); - } - this.scene = null; - } - static _SetRenderingGroupId(node, id) { - node.getChildMeshes().forEach((mesh) => { - mesh.renderingGroupId = id; - }); - } -} -//# sourceMappingURL=axesViewer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Debug/boneAxesViewer.js - - - -/** - * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh - * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8 - */ -class BoneAxesViewer extends (/* unused pure expression or super */ null && (AxesViewer)) { - /** - * Creates a new BoneAxesViewer - * @param scene defines the hosting scene - * @param bone defines the target bone - * @param mesh defines the target mesh - * @param scaleLines defines a scaling factor for line length (1 by default) - */ - constructor(scene, bone, mesh, scaleLines = 1) { - super(scene, scaleLines); - /** Gets current position */ - this.pos = Vector3.Zero(); - /** Gets direction of X axis */ - this.xaxis = Vector3.Zero(); - /** Gets direction of Y axis */ - this.yaxis = Vector3.Zero(); - /** Gets direction of Z axis */ - this.zaxis = Vector3.Zero(); - this.mesh = mesh; - this.bone = bone; - } - /** - * Force the viewer to update - */ - update() { - if (!this.mesh || !this.bone) { - return; - } - const bone = this.bone; - bone.getAbsolutePositionToRef(this.mesh, this.pos); - bone.getDirectionToRef(Axis.X, this.mesh, this.xaxis); - bone.getDirectionToRef(Axis.Y, this.mesh, this.yaxis); - bone.getDirectionToRef(Axis.Z, this.mesh, this.zaxis); - super.update(this.pos, this.xaxis, this.yaxis, this.zaxis); - } - /** Releases resources */ - dispose() { - if (this.mesh) { - this.mesh = null; - this.bone = null; - super.dispose(); - } - } -} -//# sourceMappingURL=boneAxesViewer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Debug/debugLayer.js - - - - - -Object.defineProperty(scene_Scene.prototype, "debugLayer", { - get: function () { - if (!this._debugLayer) { - this._debugLayer = new DebugLayer(this); - } - return this._debugLayer; - }, - enumerable: true, - configurable: true, -}); -/** - * Enum of inspector action tab - */ -var DebugLayerTab; -(function (DebugLayerTab) { - /** - * Properties tag (default) - */ - DebugLayerTab[DebugLayerTab["Properties"] = 0] = "Properties"; - /** - * Debug tab - */ - DebugLayerTab[DebugLayerTab["Debug"] = 1] = "Debug"; - /** - * Statistics tab - */ - DebugLayerTab[DebugLayerTab["Statistics"] = 2] = "Statistics"; - /** - * Tools tab - */ - DebugLayerTab[DebugLayerTab["Tools"] = 3] = "Tools"; - /** - * Settings tab - */ - DebugLayerTab[DebugLayerTab["Settings"] = 4] = "Settings"; -})(DebugLayerTab || (DebugLayerTab = {})); -/** - * The debug layer (aka Inspector) is the go to tool in order to better understand - * what is happening in your scene - * @see https://doc.babylonjs.com/toolsAndResources/inspector - */ -class DebugLayer { - /** - * Observable triggered when a property is changed through the inspector. - */ - get onPropertyChangedObservable() { - if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) { - return this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable; - } - if (!this._onPropertyChangedObservable) { - this._onPropertyChangedObservable = new observable_Observable(); - } - return this._onPropertyChangedObservable; - } - /** - * Observable triggered when the selection is changed through the inspector. - */ - get onSelectionChangedObservable() { - if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) { - return this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable; - } - if (!this._onSelectionChangedObservable) { - this._onSelectionChangedObservable = new observable_Observable(); - } - return this._onSelectionChangedObservable; - } - /** - * Instantiates a new debug layer. - * The debug layer (aka Inspector) is the go to tool in order to better understand - * what is happening in your scene - * @see https://doc.babylonjs.com/toolsAndResources/inspector - * @param scene Defines the scene to inspect - */ - constructor(scene) { - // eslint-disable-next-line @typescript-eslint/naming-convention - this.BJSINSPECTOR = this._getGlobalInspector(); - this._scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!this._scene) { - return; - } - this._scene.onDisposeObservable.add(() => { - // Debug layer - if (this._scene._debugLayer) { - this._scene._debugLayer.hide(); - } - }); - } - /** - * Creates the inspector window. - * @param config - */ - _createInspector(config) { - if (this.isVisible()) { - return; - } - if (this._onPropertyChangedObservable) { - for (const observer of this._onPropertyChangedObservable.observers) { - this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(observer); - } - this._onPropertyChangedObservable.clear(); - this._onPropertyChangedObservable = undefined; - } - if (this._onSelectionChangedObservable) { - for (const observer of this._onSelectionChangedObservable.observers) { - this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(observer); - } - this._onSelectionChangedObservable.clear(); - this._onSelectionChangedObservable = undefined; - } - const userOptions = Object.assign({ overlay: false, showExplorer: true, showInspector: true, embedMode: false, handleResize: true, enablePopup: true }, config); - this.BJSINSPECTOR = this.BJSINSPECTOR || this._getGlobalInspector(); - this.BJSINSPECTOR.Inspector.Show(this._scene, userOptions); - } - /** - * Select a specific entity in the scene explorer and highlight a specific block in that entity property grid - * @param entity defines the entity to select - * @param lineContainerTitles defines the specific blocks to highlight (could be a string or an array of strings) - */ - select(entity, lineContainerTitles) { - if (this.BJSINSPECTOR) { - if (lineContainerTitles) { - if (Object.prototype.toString.call(lineContainerTitles) == "[object String]") { - this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(lineContainerTitles); - } - else { - this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(lineContainerTitles); - } - } - this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(entity); - } - } - /** Get the inspector from bundle or global */ - _getGlobalInspector() { - // UMD Global name detection from Webpack Bundle UMD Name. - if (typeof INSPECTOR !== "undefined") { - return INSPECTOR; - } - // In case of module let s check the global emitted from the Inspector entry point. - if (typeof BABYLON !== "undefined" && typeof BABYLON.Inspector !== "undefined") { - return BABYLON; - } - return undefined; - } - /** - * Get if the inspector is visible or not. - * @returns true if visible otherwise, false - */ - isVisible() { - return this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector.IsVisible; - } - /** - * Hide the inspector and close its window. - */ - hide() { - if (this.BJSINSPECTOR) { - this.BJSINSPECTOR.Inspector.Hide(); - } - } - /** - * Update the scene in the inspector - */ - setAsActiveScene() { - if (this.BJSINSPECTOR) { - this.BJSINSPECTOR.Inspector._SetNewScene(this._scene); - } - } - /** - * Launch the debugLayer. - * @param config Define the configuration of the inspector - * @returns a promise fulfilled when the debug layer is visible - */ - show(config) { - return new Promise((resolve) => { - if (typeof this.BJSINSPECTOR == "undefined") { - const inspectorUrl = config && config.inspectorURL ? config.inspectorURL : DebugLayer.InspectorURL; - // Load inspector and add it to the DOM - tools_Tools.LoadScript(inspectorUrl, () => { - this._createInspector(config); - resolve(this); - }); - } - else { - // Otherwise creates the inspector - this._createInspector(config); - resolve(this); - } - }); - } -} -/** - * Define the url to get the inspector script from. - * By default it uses the babylonjs CDN. - * @ignoreNaming - */ -DebugLayer.InspectorURL = `https://unpkg.com/babylonjs-inspector@${engine_Engine.Version}/babylon.inspector.bundle.js`; -//# sourceMappingURL=debugLayer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/boxBuilder.js - - - - - - -/** - * Creates the VertexData for a box - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * size sets the width, height and depth of the box to the value of size, optional default 1 - * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size - * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size - * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size - * * faceUV an array of 6 Vector4 elements used to set different images to each box side - * * faceColors an array of 6 Color3 elements used to set different colors to each box side - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.size - * @param options.width - * @param options.height - * @param options.depth - * @param options.faceUV - * @param options.faceColors - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.wrap - * @param options.topBaseAt - * @param options.bottomBaseAt - * @returns the VertexData of the box - */ -function CreateBoxVertexData(options) { - const nbFaces = 6; - 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]; - const normals = [ - 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, - ]; - const uvs = []; - let positions = []; - const width = options.width || options.size || 1; - const height = options.height || options.size || 1; - const depth = options.depth || options.size || 1; - const wrap = options.wrap || false; - let topBaseAt = options.topBaseAt === void 0 ? 1 : options.topBaseAt; - let bottomBaseAt = options.bottomBaseAt === void 0 ? 0 : options.bottomBaseAt; - topBaseAt = (topBaseAt + 4) % 4; // places values as 0 to 3 - bottomBaseAt = (bottomBaseAt + 4) % 4; // places values as 0 to 3 - const topOrder = [2, 0, 3, 1]; - const bottomOrder = [2, 0, 1, 3]; - let topIndex = topOrder[topBaseAt]; - let bottomIndex = bottomOrder[bottomBaseAt]; - let basePositions = [ - 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -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 (wrap) { - 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]; - basePositions = [ - -1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 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 topFaceBase = [ - [1, 1, 1], - [-1, 1, 1], - [-1, 1, -1], - [1, 1, -1], - ]; - let bottomFaceBase = [ - [-1, -1, 1], - [1, -1, 1], - [1, -1, -1], - [-1, -1, -1], - ]; - const topFaceOrder = [17, 18, 19, 16]; - const bottomFaceOrder = [22, 23, 20, 21]; - while (topIndex > 0) { - topFaceBase.unshift(topFaceBase.pop()); - topFaceOrder.unshift(topFaceOrder.pop()); - topIndex--; - } - while (bottomIndex > 0) { - bottomFaceBase.unshift(bottomFaceBase.pop()); - bottomFaceOrder.unshift(bottomFaceOrder.pop()); - bottomIndex--; - } - topFaceBase = topFaceBase.flat(); - bottomFaceBase = bottomFaceBase.flat(); - basePositions = basePositions.concat(topFaceBase).concat(bottomFaceBase); - indices.push(topFaceOrder[0], topFaceOrder[2], topFaceOrder[3], topFaceOrder[0], topFaceOrder[1], topFaceOrder[2]); - indices.push(bottomFaceOrder[0], bottomFaceOrder[2], bottomFaceOrder[3], bottomFaceOrder[0], bottomFaceOrder[1], bottomFaceOrder[2]); - } - const scaleArray = [width / 2, height / 2, depth / 2]; - positions = basePositions.reduce((accumulator, currentValue, currentIndex) => accumulator.concat(currentValue * scaleArray[currentIndex % 3]), []); - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - const faceUV = options.faceUV || new Array(6); - const faceColors = options.faceColors; - const colors = []; - // default face colors and UV if undefined - for (let f = 0; f < 6; f++) { - if (faceUV[f] === undefined) { - faceUV[f] = new math_vector_Vector4(0, 0, 1, 1); - } - if (faceColors && faceColors[f] === undefined) { - faceColors[f] = new math_color_Color4(1, 1, 1, 1); - } - } - // Create each face in turn. - for (let index = 0; index < nbFaces; index++) { - uvs.push(faceUV[index].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].w : faceUV[index].w); - uvs.push(faceUV[index].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].w : faceUV[index].w); - uvs.push(faceUV[index].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].y : faceUV[index].y); - uvs.push(faceUV[index].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].y : faceUV[index].y); - if (faceColors) { - for (let c = 0; c < 4; c++) { - colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a); - } - } - } - // sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - if (faceColors) { - const totalColors = sideOrientation === mesh_vertexData_VertexData.DOUBLESIDE ? colors.concat(colors) : colors; - vertexData.colors = totalColors; - } - return vertexData; -} -/** - * Creates the VertexData for a segmented box - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * size sets the width, height and depth of the box to the value of size, optional default 1 - * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size - * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size - * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size - * * segments sets the number of segments on the all axis (1 by default) - * * widthSegments sets the number of segments on the x axis (1 by default) - * * heightSegments sets the number of segments on the y axis (1 by default) - * * depthSegments sets the number of segments on the z axis (1 by default) - * @param options.size - * @param options.width - * @param options.height - * @param options.depth - * @param options.segments - * @param options.widthSegments - * @param options.heightSegments - * @param options.depthSegments - * @returns the VertexData of the box - */ -function CreateSegmentedBoxVertexData(options) { - const width = options.width || options.size || 1; - const height = options.height || options.size || 1; - const depth = options.depth || options.size || 1; - const widthSegments = (options.widthSegments || options.segments || 1) | 0; - const heightSegments = (options.heightSegments || options.segments || 1) | 0; - const depthSegments = (options.depthSegments || options.segments || 1) | 0; - const rotationMatrix = new math_vector_Matrix(); - const translationMatrix = new math_vector_Matrix(); - const transformMatrix = new math_vector_Matrix(); - const bottomPlane = CreateGroundVertexData({ width: width, height: depth, subdivisionsX: widthSegments, subdivisionsY: depthSegments }); - math_vector_Matrix.TranslationToRef(0, -height / 2, 0, translationMatrix); - math_vector_Matrix.RotationZToRef(Math.PI, rotationMatrix); - rotationMatrix.multiplyToRef(translationMatrix, transformMatrix); - bottomPlane.transform(transformMatrix); - const topPlane = CreateGroundVertexData({ width: width, height: depth, subdivisionsX: widthSegments, subdivisionsY: depthSegments }); - math_vector_Matrix.TranslationToRef(0, height / 2, 0, transformMatrix); - topPlane.transform(transformMatrix); - const negXPlane = CreateGroundVertexData({ width: height, height: depth, subdivisionsX: heightSegments, subdivisionsY: depthSegments }); - math_vector_Matrix.TranslationToRef(-width / 2, 0, 0, translationMatrix); - math_vector_Matrix.RotationZToRef(Math.PI / 2, rotationMatrix); - rotationMatrix.multiplyToRef(translationMatrix, transformMatrix); - negXPlane.transform(transformMatrix); - const posXPlane = CreateGroundVertexData({ width: height, height: depth, subdivisionsX: heightSegments, subdivisionsY: depthSegments }); - math_vector_Matrix.TranslationToRef(width / 2, 0, 0, translationMatrix); - math_vector_Matrix.RotationZToRef(-Math.PI / 2, rotationMatrix); - rotationMatrix.multiplyToRef(translationMatrix, transformMatrix); - posXPlane.transform(transformMatrix); - const negZPlane = CreateGroundVertexData({ width: width, height: height, subdivisionsX: widthSegments, subdivisionsY: heightSegments }); - math_vector_Matrix.TranslationToRef(0, 0, -depth / 2, translationMatrix); - math_vector_Matrix.RotationXToRef(-Math.PI / 2, rotationMatrix); - rotationMatrix.multiplyToRef(translationMatrix, transformMatrix); - negZPlane.transform(transformMatrix); - const posZPlane = CreateGroundVertexData({ width: width, height: height, subdivisionsX: widthSegments, subdivisionsY: heightSegments }); - math_vector_Matrix.TranslationToRef(0, 0, depth / 2, translationMatrix); - math_vector_Matrix.RotationXToRef(Math.PI / 2, rotationMatrix); - rotationMatrix.multiplyToRef(translationMatrix, transformMatrix); - posZPlane.transform(transformMatrix); - // Result - bottomPlane.merge([topPlane, posXPlane, negXPlane, negZPlane, posZPlane], true); - return bottomPlane; -} -/** - * Creates a box mesh - * * The parameter `size` sets the size (float) of each box side (default 1) - * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`) - * * 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) - * * Please read this tutorial : https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#box - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.size - * @param options.width - * @param options.height - * @param options.depth - * @param options.faceUV - * @param options.faceColors - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.wrap - * @param options.topBaseAt - * @param options.bottomBaseAt - * @param options.updatable - * @param scene defines the hosting scene - * @returns the box mesh - */ -function boxBuilder_CreateBox(name, options = {}, scene = null) { - const box = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - box._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreateBoxVertexData(options); - vertexData.applyToMesh(box, options.updatable); - return box; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated please use CreateBox directly - */ -const BoxBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateBox: boxBuilder_CreateBox, -}; -// Side effects -mesh_vertexData_VertexData.CreateBox = CreateBoxVertexData; -mesh_Mesh.CreateBox = (name, size, scene = null, updatable, sideOrientation) => { - const options = { - size, - sideOrientation, - updatable, - }; - return boxBuilder_CreateBox(name, options, scene); -}; -//# sourceMappingURL=boxBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/sphereBuilder.js - - - - -/** - * Creates the VertexData for an ellipsoid, defaults to a sphere - * @param options an object used to set the following optional parameters for the box, required but can be empty - * * segments sets the number of horizontal strips optional, default 32 - * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1 - * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter - * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter - * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter - * * 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 - * * 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 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.segments - * @param options.diameter - * @param options.diameterX - * @param options.diameterY - * @param options.diameterZ - * @param options.arc - * @param options.slice - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.dedupTopBottomIndices - * @returns the VertexData of the ellipsoid - */ -function CreateSphereVertexData(options) { - const segments = (options.segments || 32) | 0; - const diameterX = options.diameterX || options.diameter || 1; - const diameterY = options.diameterY || options.diameter || 1; - const diameterZ = options.diameterZ || options.diameter || 1; - const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0; - const slice = options.slice && options.slice <= 0 ? 1.0 : options.slice || 1.0; - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - const dedupTopBottomIndices = !!options.dedupTopBottomIndices; - const radius = new math_vector_Vector3(diameterX / 2, diameterY / 2, diameterZ / 2); - const totalZRotationSteps = 2 + segments; - const totalYRotationSteps = 2 * totalZRotationSteps; - const indices = []; - const positions = []; - const normals = []; - const uvs = []; - for (let zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) { - const normalizedZ = zRotationStep / totalZRotationSteps; - const angleZ = normalizedZ * Math.PI * slice; - for (let yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) { - const normalizedY = yRotationStep / totalYRotationSteps; - const angleY = normalizedY * Math.PI * 2 * arc; - const rotationZ = math_vector_Matrix.RotationZ(-angleZ); - const rotationY = math_vector_Matrix.RotationY(angleY); - const afterRotZ = math_vector_Vector3.TransformCoordinates(math_vector_Vector3.Up(), rotationZ); - const complete = math_vector_Vector3.TransformCoordinates(afterRotZ, rotationY); - const vertex = complete.multiply(radius); - const normal = complete.divide(radius).normalize(); - positions.push(vertex.x, vertex.y, vertex.z); - normals.push(normal.x, normal.y, normal.z); - uvs.push(normalizedY, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - normalizedZ : normalizedZ); - } - if (zRotationStep > 0) { - const verticesCount = positions.length / 3; - for (let firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); firstIndex + totalYRotationSteps + 2 < verticesCount; firstIndex++) { - if (dedupTopBottomIndices) { - if (zRotationStep > 1) { - indices.push(firstIndex); - indices.push(firstIndex + 1); - indices.push(firstIndex + totalYRotationSteps + 1); - } - if (zRotationStep < totalZRotationSteps || slice < 1.0) { - indices.push(firstIndex + totalYRotationSteps + 1); - indices.push(firstIndex + 1); - indices.push(firstIndex + totalYRotationSteps + 2); - } - } - else { - indices.push(firstIndex); - indices.push(firstIndex + 1); - indices.push(firstIndex + totalYRotationSteps + 1); - indices.push(firstIndex + totalYRotationSteps + 1); - indices.push(firstIndex + 1); - indices.push(firstIndex + totalYRotationSteps + 2); - } - } - } - } - // Sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - return vertexData; -} -/** - * Creates a sphere mesh - * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1) - * * 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`) - * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32) - * * 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 - * * 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) - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.segments - * @param options.diameter - * @param options.diameterX - * @param options.diameterY - * @param options.diameterZ - * @param options.arc - * @param options.slice - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.updatable - * @param scene defines the hosting scene - * @returns the sphere mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#sphere - */ -function sphereBuilder_CreateSphere(name, options = {}, scene = null) { - const sphere = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - sphere._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreateSphereVertexData(options); - vertexData.applyToMesh(sphere, options.updatable); - return sphere; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use CreateSphere directly - */ -const SphereBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateSphere: sphereBuilder_CreateSphere, -}; -mesh_vertexData_VertexData.CreateSphere = CreateSphereVertexData; -mesh_Mesh.CreateSphere = (name, segments, diameter, scene, updatable, sideOrientation) => { - const options = { - segments: segments, - diameterX: diameter, - diameterY: diameter, - diameterZ: diameter, - sideOrientation: sideOrientation, - updatable: updatable, - }; - return sphereBuilder_CreateSphere(name, options, scene); -}; -//# sourceMappingURL=sphereBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/capsuleBuilder.js - - - - -/** - * Scripts based off of https://github.com/maximeq/three-js-capsule-geometry/blob/master/src/CapsuleBufferGeometry.js - * @param options the constructors options used to shape the mesh. - * @returns the capsule VertexData - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/capsule - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function CreateCapsuleVertexData(options = { - subdivisions: 2, - tessellation: 16, - height: 1, - radius: 0.25, - capSubdivisions: 6, -}) { - const subdivisions = Math.max(options.subdivisions ? options.subdivisions : 2, 1) | 0; - const tessellation = Math.max(options.tessellation ? options.tessellation : 16, 3) | 0; - const height = Math.max(options.height ? options.height : 1, 0); - const radius = Math.max(options.radius ? options.radius : 0.25, 0); - const capDetail = Math.max(options.capSubdivisions ? options.capSubdivisions : 6, 1) | 0; - const radialSegments = tessellation; - const heightSegments = subdivisions; - const radiusTop = Math.max(options.radiusTop ? options.radiusTop : radius, 0); - const radiusBottom = Math.max(options.radiusBottom ? options.radiusBottom : radius, 0); - const heightMinusCaps = height - (radiusTop + radiusBottom); - const thetaStart = 0.0; - const thetaLength = 2.0 * Math.PI; - const capsTopSegments = Math.max(options.topCapSubdivisions ? options.topCapSubdivisions : capDetail, 1); - const capsBottomSegments = Math.max(options.bottomCapSubdivisions ? options.bottomCapSubdivisions : capDetail, 1); - const alpha = Math.acos((radiusBottom - radiusTop) / height); - let indices = []; - const vertices = []; - const normals = []; - const uvs = []; - let index = 0; - const indexArray = [], halfHeight = heightMinusCaps * 0.5; - const pi2 = Math.PI * 0.5; - let x, y; - const normal = math_vector_Vector3.Zero(); - const vertex = math_vector_Vector3.Zero(); - const cosAlpha = Math.cos(alpha); - const sinAlpha = Math.sin(alpha); - const coneLength = new math_vector_Vector2(radiusTop * sinAlpha, halfHeight + radiusTop * cosAlpha) - .subtract(new math_vector_Vector2(radiusBottom * sinAlpha, -halfHeight + radiusBottom * cosAlpha)) - .length(); - // Total length for v texture coord - const vl = radiusTop * alpha + coneLength + radiusBottom * (pi2 - alpha); - let v = 0; - for (y = 0; y <= capsTopSegments; y++) { - const indexRow = []; - const a = pi2 - alpha * (y / capsTopSegments); - v += (radiusTop * alpha) / capsTopSegments; - const cosA = Math.cos(a); - const sinA = Math.sin(a); - // calculate the radius of the current row - const _radius = cosA * radiusTop; - for (x = 0; x <= radialSegments; x++) { - const u = x / radialSegments; - const theta = u * thetaLength + thetaStart; - const sinTheta = Math.sin(theta); - const cosTheta = Math.cos(theta); - // vertex - vertex.x = _radius * sinTheta; - vertex.y = halfHeight + sinA * radiusTop; - vertex.z = _radius * cosTheta; - vertices.push(vertex.x, vertex.y, vertex.z); - // normal - normal.set(cosA * sinTheta, sinA, cosA * cosTheta); - normals.push(normal.x, normal.y, normal.z); - // uv - uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? v / vl : 1 - v / vl); - // save index of vertex in respective row - indexRow.push(index); - // increase index - index++; - } - // now save vertices of the row in our index array - indexArray.push(indexRow); - } - const coneHeight = height - radiusTop - radiusBottom + cosAlpha * radiusTop - cosAlpha * radiusBottom; - const slope = (sinAlpha * (radiusBottom - radiusTop)) / coneHeight; - for (y = 1; y <= heightSegments; y++) { - const indexRow = []; - v += coneLength / heightSegments; - // calculate the radius of the current row - const _radius = sinAlpha * ((y * (radiusBottom - radiusTop)) / heightSegments + radiusTop); - for (x = 0; x <= radialSegments; x++) { - const u = x / radialSegments; - const theta = u * thetaLength + thetaStart; - const sinTheta = Math.sin(theta); - const cosTheta = Math.cos(theta); - // vertex - vertex.x = _radius * sinTheta; - vertex.y = halfHeight + cosAlpha * radiusTop - (y * coneHeight) / heightSegments; - vertex.z = _radius * cosTheta; - vertices.push(vertex.x, vertex.y, vertex.z); - // normal - normal.set(sinTheta, slope, cosTheta).normalize(); - normals.push(normal.x, normal.y, normal.z); - // uv - uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? v / vl : 1 - v / vl); - // save index of vertex in respective row - indexRow.push(index); - // increase index - index++; - } - // now save vertices of the row in our index array - indexArray.push(indexRow); - } - for (y = 1; y <= capsBottomSegments; y++) { - const indexRow = []; - const a = pi2 - alpha - (Math.PI - alpha) * (y / capsBottomSegments); - v += (radiusBottom * alpha) / capsBottomSegments; - const cosA = Math.cos(a); - const sinA = Math.sin(a); - // calculate the radius of the current row - const _radius = cosA * radiusBottom; - for (x = 0; x <= radialSegments; x++) { - const u = x / radialSegments; - const theta = u * thetaLength + thetaStart; - const sinTheta = Math.sin(theta); - const cosTheta = Math.cos(theta); - // vertex - vertex.x = _radius * sinTheta; - vertex.y = -halfHeight + sinA * radiusBottom; - vertex.z = _radius * cosTheta; - vertices.push(vertex.x, vertex.y, vertex.z); - // normal - normal.set(cosA * sinTheta, sinA, cosA * cosTheta); - normals.push(normal.x, normal.y, normal.z); - // uv - uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? v / vl : 1 - v / vl); - // save index of vertex in respective row - indexRow.push(index); - // increase index - index++; - } - // now save vertices of the row in our index array - indexArray.push(indexRow); - } - // generate indices - for (x = 0; x < radialSegments; x++) { - for (y = 0; y < capsTopSegments + heightSegments + capsBottomSegments; y++) { - // we use the index array to access the correct indices - const i1 = indexArray[y][x]; - const i2 = indexArray[y + 1][x]; - const i3 = indexArray[y + 1][x + 1]; - const i4 = indexArray[y][x + 1]; - // face one - indices.push(i1); - indices.push(i2); - indices.push(i4); - // face two - indices.push(i2); - indices.push(i3); - indices.push(i4); - } - } - indices = indices.reverse(); - if (options.orientation && !options.orientation.equals(math_vector_Vector3.Up())) { - const m = new math_vector_Matrix(); - options.orientation - .clone() - .scale(Math.PI * 0.5) - .cross(math_vector_Vector3.Up()) - .toQuaternion() - .toRotationMatrix(m); - const v = math_vector_Vector3.Zero(); - for (let i = 0; i < vertices.length; i += 3) { - v.set(vertices[i], vertices[i + 1], vertices[i + 2]); - math_vector_Vector3.TransformCoordinatesToRef(v.clone(), m, v); - vertices[i] = v.x; - vertices[i + 1] = v.y; - vertices[i + 2] = v.z; - } - } - const vDat = new mesh_vertexData_VertexData(); - vDat.positions = vertices; - vDat.normals = normals; - vDat.uvs = uvs; - vDat.indices = indices; - return vDat; -} -/** - * Creates a capsule or a pill mesh - * @param name defines the name of the mesh - * @param options The constructors options. - * @param scene The scene the mesh is scoped to. - * @returns Capsule Mesh - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function capsuleBuilder_CreateCapsule(name, options = { - orientation: math_vector_Vector3.Up(), - subdivisions: 2, - tessellation: 16, - height: 1, - radius: 0.25, - capSubdivisions: 6, - updatable: false, -}, scene = null) { - const capsule = new mesh_Mesh(name, scene); - const vertexData = CreateCapsuleVertexData(options); - vertexData.applyToMesh(capsule, options.updatable); - return capsule; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated please use CreateCapsule directly - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -const CapsuleBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateCapsule: capsuleBuilder_CreateCapsule, -}; -/** - * Creates a capsule or a pill mesh - * @param name defines the name of the mesh. - * @param options the constructors options used to shape the mesh. - * @param scene defines the scene the mesh is scoped to. - * @returns the capsule mesh - * @see https://doc.babylonjs.com/how_to/capsule_shape - */ -mesh_Mesh.CreateCapsule = (name, options, scene) => { - return capsuleBuilder_CreateCapsule(name, options, scene); -}; -mesh_vertexData_VertexData.CreateCapsule = CreateCapsuleVertexData; -//# sourceMappingURL=capsuleBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/ribbonBuilder.js - - - - - -/** - * Creates the VertexData for a Ribbon - * @param options an object used to set the following optional parameters for the ribbon, required but can be empty - * * pathArray array of paths, each of which an array of successive Vector3 - * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false - * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false - * * 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 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false - * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional - * * colors a linear array, of length 4 * number of vertices, of custom color values, optional - * @param options.pathArray - * @param options.closeArray - * @param options.closePath - * @param options.offset - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.invertUV - * @param options.uvs - * @param options.colors - * @returns the VertexData of the ribbon - */ -function CreateRibbonVertexData(options) { - let pathArray = options.pathArray; - const closeArray = options.closeArray || false; - const closePath = options.closePath || false; - const invertUV = options.invertUV || false; - const defaultOffset = Math.floor(pathArray[0].length / 2); - let offset = options.offset || defaultOffset; - offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - const customUV = options.uvs; - const customColors = options.colors; - const positions = []; - const indices = []; - const normals = []; - const uvs = []; - const us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id - const vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutive paths from pathArray - const uTotalDistance = []; // uTotalDistance[p] : total distance of path p - const vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray - let minlg; // minimal length among all paths from pathArray - const lg = []; // array of path lengths : nb of vertex per path - const idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number - let p; // path iterator - let i; // point iterator - let j; // point iterator - // if single path in pathArray - if (pathArray.length < 2) { - const ar1 = []; - const ar2 = []; - for (i = 0; i < pathArray[0].length - offset; i++) { - ar1.push(pathArray[0][i]); - ar2.push(pathArray[0][i + offset]); - } - pathArray = [ar1, ar2]; - } - // positions and horizontal distances (u) - let idc = 0; - const closePathCorr = closePath ? 1 : 0; // the final index will be +1 if closePath - let path; - let l; - minlg = pathArray[0].length; - let vectlg; - let dist; - for (p = 0; p < pathArray.length; p++) { - uTotalDistance[p] = 0; - us[p] = [0]; - path = pathArray[p]; - l = path.length; - minlg = minlg < l ? minlg : l; - j = 0; - while (j < l) { - positions.push(path[j].x, path[j].y, path[j].z); - if (j > 0) { - vectlg = path[j].subtract(path[j - 1]).length(); - dist = vectlg + uTotalDistance[p]; - us[p].push(dist); - uTotalDistance[p] = dist; - } - j++; - } - if (closePath) { - // an extra hidden vertex is added in the "positions" array - j--; - positions.push(path[0].x, path[0].y, path[0].z); - vectlg = path[j].subtract(path[0]).length(); - dist = vectlg + uTotalDistance[p]; - us[p].push(dist); - uTotalDistance[p] = dist; - } - lg[p] = l + closePathCorr; - idx[p] = idc; - idc += l + closePathCorr; - } - // vertical distances (v) - let path1; - let path2; - let vertex1 = null; - let vertex2 = null; - for (i = 0; i < minlg + closePathCorr; i++) { - vTotalDistance[i] = 0; - vs[i] = [0]; - for (p = 0; p < pathArray.length - 1; p++) { - path1 = pathArray[p]; - path2 = pathArray[p + 1]; - if (i === minlg) { - // closePath - vertex1 = path1[0]; - vertex2 = path2[0]; - } - else { - vertex1 = path1[i]; - vertex2 = path2[i]; - } - vectlg = vertex2.subtract(vertex1).length(); - dist = vectlg + vTotalDistance[i]; - vs[i].push(dist); - vTotalDistance[i] = dist; - } - if (closeArray && vertex2 && vertex1) { - path1 = pathArray[p]; - path2 = pathArray[0]; - if (i === minlg) { - // closePath - vertex2 = path2[0]; - } - vectlg = vertex2.subtract(vertex1).length(); - dist = vectlg + vTotalDistance[i]; - vTotalDistance[i] = dist; - } - } - // uvs - let u; - let v; - if (customUV) { - for (p = 0; p < customUV.length; p++) { - uvs.push(customUV[p].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - customUV[p].y : customUV[p].y); - } - } - else { - for (p = 0; p < pathArray.length; p++) { - for (i = 0; i < minlg + closePathCorr; i++) { - u = uTotalDistance[p] != 0.0 ? us[p][i] / uTotalDistance[p] : 0.0; - v = vTotalDistance[i] != 0.0 ? vs[i][p] / vTotalDistance[i] : 0.0; - if (invertUV) { - uvs.push(v, u); - } - else { - uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - v : v); - } - } - } - } - // indices - p = 0; // path index - let pi = 0; // positions array index - let l1 = lg[p] - 1; // path1 length - let l2 = lg[p + 1] - 1; // path2 length - let min = l1 < l2 ? l1 : l2; // current path stop index - let shft = idx[1] - idx[0]; // shift - const path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on - while (pi <= min && p < path1nb) { - // stay under min and don't go over next to last path - // 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 - indices.push(pi, pi + shft, pi + 1); - indices.push(pi + shft + 1, pi + 1, pi + shft); - pi += 1; - if (pi === min) { - // if end of one of two consecutive paths reached, go to next existing path - p++; - if (p === lg.length - 1) { - // last path of pathArray reached <=> closeArray == true - shft = idx[0] - idx[p]; - l1 = lg[p] - 1; - l2 = lg[0] - 1; - } - else { - shft = idx[p + 1] - idx[p]; - l1 = lg[p] - 1; - l2 = lg[p + 1] - 1; - } - pi = idx[p]; - min = l1 < l2 ? l1 + pi : l2 + pi; - } - } - // normals - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals); - if (closePath) { - // update both the first and last vertex normals to their average value - let indexFirst = 0; - let indexLast = 0; - for (p = 0; p < pathArray.length; p++) { - indexFirst = idx[p] * 3; - if (p + 1 < pathArray.length) { - indexLast = (idx[p + 1] - 1) * 3; - } - else { - indexLast = normals.length - 3; - } - normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5; - normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5; - normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5; - normals[indexLast] = normals[indexFirst]; - normals[indexLast + 1] = normals[indexFirst + 1]; - normals[indexLast + 2] = normals[indexFirst + 2]; - } - } - // sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - // Colors - let colors = null; - if (customColors) { - colors = new Float32Array(customColors.length * 4); - for (let c = 0; c < customColors.length; c++) { - colors[c * 4] = customColors[c].r; - colors[c * 4 + 1] = customColors[c].g; - colors[c * 4 + 2] = customColors[c].b; - colors[c * 4 + 3] = customColors[c].a; - } - } - // Result - const vertexData = new mesh_vertexData_VertexData(); - const positions32 = new Float32Array(positions); - const normals32 = new Float32Array(normals); - const uvs32 = new Float32Array(uvs); - vertexData.indices = indices; - vertexData.positions = positions32; - vertexData.normals = normals32; - vertexData.uvs = uvs32; - if (colors) { - vertexData.set(colors, buffer_VertexBuffer.ColorKind); - } - if (closePath) { - vertexData._idx = idx; - } - return vertexData; -} -/** - * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters - * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry - * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array - * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array - * * 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 - * * 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 - * * 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 - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * 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 - * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values - * * 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 - * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.pathArray - * @param options.closeArray - * @param options.closePath - * @param options.offset - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.instance - * @param options.invertUV - * @param options.uvs - * @param options.colors - * @param scene defines the hosting scene - * @returns the ribbon mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/ribbon_extra - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param - */ -function CreateRibbon(name, options, scene = null) { - const pathArray = options.pathArray; - const closeArray = options.closeArray; - const closePath = options.closePath; - const sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - const instance = options.instance; - const updatable = options.updatable; - if (instance) { - // existing ribbon instance update - // positionFunction : ribbon case - // only pathArray and sideOrientation parameters are taken into account for positions update - const minimum = math_vector_TmpVectors.Vector3[0].setAll(Number.MAX_VALUE); - const maximum = math_vector_TmpVectors.Vector3[1].setAll(-Number.MAX_VALUE); - const positionFunction = (positions) => { - let minlg = pathArray[0].length; - const mesh = instance; - let i = 0; - const ns = mesh._originalBuilderSideOrientation === mesh_Mesh.DOUBLESIDE ? 2 : 1; - for (let si = 1; si <= ns; ++si) { - for (let p = 0; p < pathArray.length; ++p) { - const path = pathArray[p]; - const l = path.length; - minlg = minlg < l ? minlg : l; - for (let j = 0; j < minlg; ++j) { - const pathPoint = path[j]; - positions[i] = pathPoint.x; - positions[i + 1] = pathPoint.y; - positions[i + 2] = pathPoint.z; - minimum.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z); - maximum.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z); - i += 3; - } - if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) { - const pathPoint = path[0]; - positions[i] = pathPoint.x; - positions[i + 1] = pathPoint.y; - positions[i + 2] = pathPoint.z; - i += 3; - } - } - } - }; - const positions = instance.getVerticesData(buffer_VertexBuffer.PositionKind); - positionFunction(positions); - if (instance.hasBoundingInfo) { - instance.getBoundingInfo().reConstruct(minimum, maximum, instance._worldMatrix); - } - else { - instance.buildBoundingInfo(minimum, maximum, instance._worldMatrix); - } - instance.updateVerticesData(buffer_VertexBuffer.PositionKind, positions, false, false); - if (options.colors) { - const colors = instance.getVerticesData(buffer_VertexBuffer.ColorKind); - for (let c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) { - const color = options.colors[c]; - colors[colorIndex] = color.r; - colors[colorIndex + 1] = color.g; - colors[colorIndex + 2] = color.b; - colors[colorIndex + 3] = color.a; - } - instance.updateVerticesData(buffer_VertexBuffer.ColorKind, colors, false, false); - } - if (options.uvs) { - const uvs = instance.getVerticesData(buffer_VertexBuffer.UVKind); - for (let i = 0; i < options.uvs.length; i++) { - uvs[i * 2] = options.uvs[i].x; - uvs[i * 2 + 1] = CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - options.uvs[i].y : options.uvs[i].y; - } - instance.updateVerticesData(buffer_VertexBuffer.UVKind, uvs, false, false); - } - if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) { - const indices = instance.getIndices(); - const normals = instance.getVerticesData(buffer_VertexBuffer.NormalKind); - const params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null; - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals, params); - if (instance._creationDataStorage && instance._creationDataStorage.closePath) { - let indexFirst = 0; - let indexLast = 0; - for (let p = 0; p < pathArray.length; p++) { - indexFirst = instance._creationDataStorage.idx[p] * 3; - if (p + 1 < pathArray.length) { - indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3; - } - else { - indexLast = normals.length - 3; - } - normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5; - normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5; - normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5; - normals[indexLast] = normals[indexFirst]; - normals[indexLast + 1] = normals[indexFirst + 1]; - normals[indexLast + 2] = normals[indexFirst + 2]; - } - } - if (!instance.areNormalsFrozen) { - instance.updateVerticesData(buffer_VertexBuffer.NormalKind, normals, false, false); - } - } - return instance; - } - else { - // new ribbon creation - const ribbon = new mesh_Mesh(name, scene); - ribbon._originalBuilderSideOrientation = sideOrientation; - ribbon._creationDataStorage = new _CreationDataStorage(); - const vertexData = CreateRibbonVertexData(options); - if (closePath) { - ribbon._creationDataStorage.idx = vertexData._idx; - } - ribbon._creationDataStorage.closePath = closePath; - ribbon._creationDataStorage.closeArray = closeArray; - vertexData.applyToMesh(ribbon, updatable); - return ribbon; - } -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use CreateRibbon directly - */ -const RibbonBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateRibbon, -}; -mesh_vertexData_VertexData.CreateRibbon = CreateRibbonVertexData; -mesh_Mesh.CreateRibbon = (name, pathArray, closeArray = false, closePath, offset, scene, updatable = false, sideOrientation, instance) => { - return CreateRibbon(name, { - pathArray: pathArray, - closeArray: closeArray, - closePath: closePath, - offset: offset, - updatable: updatable, - sideOrientation: sideOrientation, - instance: instance, - }, scene); -}; -//# sourceMappingURL=ribbonBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/discBuilder.js - - - -/** - * Creates the VertexData of the Disc or regular Polygon - * @param options an object used to set the following optional parameters for the disc, required but can be empty - * * radius the radius of the disc, optional default 0.5 - * * tessellation the number of polygon sides, optional, default 64 - * * 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 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.radius - * @param options.tessellation - * @param options.arc - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the box - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function CreateDiscVertexData(options) { - const positions = new Array(); - const indices = new Array(); - const normals = new Array(); - const uvs = new Array(); - const radius = options.radius || 0.5; - const tessellation = options.tessellation || 64; - const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0; - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - // positions and uvs - positions.push(0, 0, 0); // disc center first - uvs.push(0.5, 0.5); - const theta = Math.PI * 2 * arc; - const step = arc === 1 ? theta / tessellation : theta / (tessellation - 1); - let a = 0; - for (let t = 0; t < tessellation; t++) { - const x = Math.cos(a); - const y = Math.sin(a); - const u = (x + 1) / 2; - const v = (1 - y) / 2; - positions.push(radius * x, radius * y, 0); - uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v); - a += step; - } - if (arc === 1) { - positions.push(positions[3], positions[4], positions[5]); // close the circle - uvs.push(uvs[2], CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - uvs[3] : uvs[3]); - } - //indices - const vertexNb = positions.length / 3; - for (let i = 1; i < vertexNb - 1; i++) { - indices.push(i + 1, 0, i); - } - // result - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals); - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - return vertexData; -} -/** - * Creates a plane polygonal mesh. By default, this is a disc - * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5) - * * 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 - * * 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 - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.radius - * @param options.tessellation - * @param options.arc - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param scene defines the hosting scene - * @returns the plane polygonal mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#disc-or-regular-polygon - */ -function discBuilder_CreateDisc(name, options = {}, scene = null) { - const disc = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - disc._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreateDiscVertexData(options); - vertexData.applyToMesh(disc, options.updatable); - return disc; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated please use CreateDisc directly - */ -const DiscBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateDisc: discBuilder_CreateDisc, -}; -mesh_vertexData_VertexData.CreateDisc = CreateDiscVertexData; -mesh_Mesh.CreateDisc = (name, radius, tessellation, scene = null, updatable, sideOrientation) => { - const options = { - radius, - tessellation, - sideOrientation, - updatable, - }; - return discBuilder_CreateDisc(name, options, scene); -}; -//# sourceMappingURL=discBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/tiledPlaneBuilder.js - - -/** - * Creates the VertexData for a tiled plane - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_plane - * @param options an object used to set the following optional parameters for the tiled plane, required but can be empty - * * pattern a limited pattern arrangement depending on the number - * * size of the box - * * width of the box, overwrites size - * * height of the box, overwrites size - * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1 - * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size - * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * alignHorizontal places whole tiles aligned to the center, left or right of a row - * * alignVertical places whole tiles aligned to the center, left or right of a column - * * 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) - * @param options.pattern - * @param options.tileSize - * @param options.tileWidth - * @param options.tileHeight - * @param options.size - * @param options.width - * @param options.height - * @param options.alignHorizontal - * @param options.alignVertical - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * * 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) - * @returns the VertexData of the tiled plane - */ -function CreateTiledPlaneVertexData(options) { - const flipTile = options.pattern || mesh_Mesh.NO_FLIP; - const tileWidth = options.tileWidth || options.tileSize || 1; - const tileHeight = options.tileHeight || options.tileSize || 1; - const alignH = options.alignHorizontal || 0; - const alignV = options.alignVertical || 0; - const width = options.width || options.size || 1; - const tilesX = Math.floor(width / tileWidth); - let offsetX = width - tilesX * tileWidth; - const height = options.height || options.size || 1; - const tilesY = Math.floor(height / tileHeight); - let offsetY = height - tilesY * tileHeight; - const halfWidth = (tileWidth * tilesX) / 2; - const halfHeight = (tileHeight * tilesY) / 2; - let adjustX = 0; - let adjustY = 0; - let startX = 0; - let startY = 0; - let endX = 0; - let endY = 0; - //Part Tiles - if (offsetX > 0 || offsetY > 0) { - startX = -halfWidth; - startY = -halfHeight; - endX = halfWidth; - endY = halfHeight; - switch (alignH) { - case mesh_Mesh.CENTER: - offsetX /= 2; - startX -= offsetX; - endX += offsetX; - break; - case mesh_Mesh.LEFT: - endX += offsetX; - adjustX = -offsetX / 2; - break; - case mesh_Mesh.RIGHT: - startX -= offsetX; - adjustX = offsetX / 2; - break; - } - switch (alignV) { - case mesh_Mesh.CENTER: - offsetY /= 2; - startY -= offsetY; - endY += offsetY; - break; - case mesh_Mesh.BOTTOM: - endY += offsetY; - adjustY = -offsetY / 2; - break; - case mesh_Mesh.TOP: - startY -= offsetY; - adjustY = offsetY / 2; - break; - } - } - const positions = []; - const normals = []; - const uvBase = []; - uvBase[0] = [0, 0, 1, 0, 1, 1, 0, 1]; - uvBase[1] = [0, 0, 1, 0, 1, 1, 0, 1]; - if (flipTile === mesh_Mesh.ROTATE_TILE || flipTile === mesh_Mesh.ROTATE_ROW) { - uvBase[1] = [1, 1, 0, 1, 0, 0, 1, 0]; - } - if (flipTile === mesh_Mesh.FLIP_TILE || flipTile === mesh_Mesh.FLIP_ROW) { - uvBase[1] = [1, 0, 0, 0, 0, 1, 1, 1]; - } - if (flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE || flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvBase[1] = [0, 1, 1, 1, 1, 0, 0, 0]; - } - let uvs = []; - const colors = []; - const indices = []; - let index = 0; - for (let y = 0; y < tilesY; y++) { - for (let x = 0; x < tilesX; x++) { - positions.push(-halfWidth + x * tileWidth + adjustX, -halfHeight + y * tileHeight + adjustY, 0); - positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, -halfHeight + y * tileHeight + adjustY, 0); - positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); - positions.push(-halfWidth + x * tileWidth + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); - indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); - if (flipTile === mesh_Mesh.FLIP_TILE || flipTile === mesh_Mesh.ROTATE_TILE || flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE) { - uvs = uvs.concat(uvBase[((x % 2) + (y % 2)) % 2]); - } - else if (flipTile === mesh_Mesh.FLIP_ROW || flipTile === mesh_Mesh.ROTATE_ROW || flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvs = uvs.concat(uvBase[y % 2]); - } - else { - uvs = uvs.concat(uvBase[0]); - } - colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); - normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - index += 4; - } - } - //Part Tiles - if (offsetX > 0 || offsetY > 0) { - const partialBottomRow = offsetY > 0 && (alignV === mesh_Mesh.CENTER || alignV === mesh_Mesh.TOP); - const partialTopRow = offsetY > 0 && (alignV === mesh_Mesh.CENTER || alignV === mesh_Mesh.BOTTOM); - const partialLeftCol = offsetX > 0 && (alignH === mesh_Mesh.CENTER || alignH === mesh_Mesh.RIGHT); - const partialRightCol = offsetX > 0 && (alignH === mesh_Mesh.CENTER || alignH === mesh_Mesh.LEFT); - let uvPart = []; - let a, b, c, d; - //corners - if (partialBottomRow && partialLeftCol) { - //bottom left corner - positions.push(startX + adjustX, startY + adjustY, 0); - positions.push(-halfWidth + adjustX, startY + adjustY, 0); - positions.push(-halfWidth + adjustX, startY + offsetY + adjustY, 0); - positions.push(startX + adjustX, startY + offsetY + adjustY, 0); - indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); - index += 4; - a = 1 - offsetX / tileWidth; - b = 1 - offsetY / tileHeight; - c = 1; - d = 1; - uvPart = [a, b, c, b, c, d, a, d]; - if (flipTile === mesh_Mesh.ROTATE_ROW) { - uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; - } - if (flipTile === mesh_Mesh.FLIP_ROW) { - uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; - } - if (flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; - } - uvs = uvs.concat(uvPart); - colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); - normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - } - if (partialBottomRow && partialRightCol) { - //bottom right corner - positions.push(halfWidth + adjustX, startY + adjustY, 0); - positions.push(endX + adjustX, startY + adjustY, 0); - positions.push(endX + adjustX, startY + offsetY + adjustY, 0); - positions.push(halfWidth + adjustX, startY + offsetY + adjustY, 0); - indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); - index += 4; - a = 0; - b = 1 - offsetY / tileHeight; - c = offsetX / tileWidth; - d = 1; - uvPart = [a, b, c, b, c, d, a, d]; - if (flipTile === mesh_Mesh.ROTATE_ROW || (flipTile === mesh_Mesh.ROTATE_TILE && tilesX % 2 === 0)) { - uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; - } - if (flipTile === mesh_Mesh.FLIP_ROW || (flipTile === mesh_Mesh.FLIP_TILE && tilesX % 2 === 0)) { - uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; - } - if (flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW || (flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE && tilesX % 2 === 0)) { - uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; - } - uvs = uvs.concat(uvPart); - colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); - normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - } - if (partialTopRow && partialLeftCol) { - //top left corner - positions.push(startX + adjustX, halfHeight + adjustY, 0); - positions.push(-halfWidth + adjustX, halfHeight + adjustY, 0); - positions.push(-halfWidth + adjustX, endY + adjustY, 0); - positions.push(startX + adjustX, endY + adjustY, 0); - indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); - index += 4; - a = 1 - offsetX / tileWidth; - b = 0; - c = 1; - d = offsetY / tileHeight; - uvPart = [a, b, c, b, c, d, a, d]; - if ((flipTile === mesh_Mesh.ROTATE_ROW && tilesY % 2 === 1) || (flipTile === mesh_Mesh.ROTATE_TILE && tilesY % 1 === 0)) { - uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; - } - if ((flipTile === mesh_Mesh.FLIP_ROW && tilesY % 2 === 1) || (flipTile === mesh_Mesh.FLIP_TILE && tilesY % 2 === 0)) { - uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; - } - if ((flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW && tilesY % 2 === 1) || (flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE && tilesY % 2 === 0)) { - uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; - } - uvs = uvs.concat(uvPart); - colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); - normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - } - if (partialTopRow && partialRightCol) { - //top right corner - positions.push(halfWidth + adjustX, halfHeight + adjustY, 0); - positions.push(endX + adjustX, halfHeight + adjustY, 0); - positions.push(endX + adjustX, endY + adjustY, 0); - positions.push(halfWidth + adjustX, endY + adjustY, 0); - indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); - index += 4; - a = 0; - b = 0; - c = offsetX / tileWidth; - d = offsetY / tileHeight; - uvPart = [a, b, c, b, c, d, a, d]; - if ((flipTile === mesh_Mesh.ROTATE_ROW && tilesY % 2 === 1) || (flipTile === mesh_Mesh.ROTATE_TILE && (tilesY + tilesX) % 2 === 1)) { - uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; - } - if ((flipTile === mesh_Mesh.FLIP_ROW && tilesY % 2 === 1) || (flipTile === mesh_Mesh.FLIP_TILE && (tilesY + tilesX) % 2 === 1)) { - uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; - } - if ((flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW && tilesY % 2 === 1) || (flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE && (tilesY + tilesX) % 2 === 1)) { - uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; - } - uvs = uvs.concat(uvPart); - colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); - normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - } - //part rows - if (partialBottomRow) { - const uvBaseBR = []; - a = 0; - b = 1 - offsetY / tileHeight; - c = 1; - d = 1; - uvBaseBR[0] = [a, b, c, b, c, d, a, d]; - uvBaseBR[1] = [a, b, c, b, c, d, a, d]; - if (flipTile === mesh_Mesh.ROTATE_TILE || flipTile === mesh_Mesh.ROTATE_ROW) { - uvBaseBR[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; - } - if (flipTile === mesh_Mesh.FLIP_TILE || flipTile === mesh_Mesh.FLIP_ROW) { - uvBaseBR[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; - } - if (flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE || flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvBaseBR[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; - } - for (let x = 0; x < tilesX; x++) { - positions.push(-halfWidth + x * tileWidth + adjustX, startY + adjustY, 0); - positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, startY + adjustY, 0); - positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, startY + offsetY + adjustY, 0); - positions.push(-halfWidth + x * tileWidth + adjustX, startY + offsetY + adjustY, 0); - indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); - index += 4; - if (flipTile === mesh_Mesh.FLIP_TILE || flipTile === mesh_Mesh.ROTATE_TILE || flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE) { - uvs = uvs.concat(uvBaseBR[(x + 1) % 2]); - } - else if (flipTile === mesh_Mesh.FLIP_ROW || flipTile === mesh_Mesh.ROTATE_ROW || flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvs = uvs.concat(uvBaseBR[1]); - } - else { - uvs = uvs.concat(uvBaseBR[0]); - } - colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); - normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - } - } - if (partialTopRow) { - const uvBaseTR = []; - a = 0; - b = 0; - c = 1; - d = offsetY / tileHeight; - uvBaseTR[0] = [a, b, c, b, c, d, a, d]; - uvBaseTR[1] = [a, b, c, b, c, d, a, d]; - if (flipTile === mesh_Mesh.ROTATE_TILE || flipTile === mesh_Mesh.ROTATE_ROW) { - uvBaseTR[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; - } - if (flipTile === mesh_Mesh.FLIP_TILE || flipTile === mesh_Mesh.FLIP_ROW) { - uvBaseTR[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; - } - if (flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE || flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvBaseTR[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; - } - for (let x = 0; x < tilesX; x++) { - positions.push(-halfWidth + x * tileWidth + adjustX, endY - offsetY + adjustY, 0); - positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, endY - offsetY + adjustY, 0); - positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, endY + adjustY, 0); - positions.push(-halfWidth + x * tileWidth + adjustX, endY + adjustY, 0); - indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); - index += 4; - if (flipTile === mesh_Mesh.FLIP_TILE || flipTile === mesh_Mesh.ROTATE_TILE || flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE) { - uvs = uvs.concat(uvBaseTR[(x + tilesY) % 2]); - } - else if (flipTile === mesh_Mesh.FLIP_ROW || flipTile === mesh_Mesh.ROTATE_ROW || flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvs = uvs.concat(uvBaseTR[tilesY % 2]); - } - else { - uvs = uvs.concat(uvBaseTR[0]); - } - colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); - normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - } - } - if (partialLeftCol) { - const uvBaseLC = []; - a = 1 - offsetX / tileWidth; - b = 0; - c = 1; - d = 1; - uvBaseLC[0] = [a, b, c, b, c, d, a, d]; - uvBaseLC[1] = [a, b, c, b, c, d, a, d]; - if (flipTile === mesh_Mesh.ROTATE_TILE || flipTile === mesh_Mesh.ROTATE_ROW) { - uvBaseLC[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; - } - if (flipTile === mesh_Mesh.FLIP_TILE || flipTile === mesh_Mesh.FLIP_ROW) { - uvBaseLC[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; - } - if (flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE || flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvBaseLC[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; - } - for (let y = 0; y < tilesY; y++) { - positions.push(startX + adjustX, -halfHeight + y * tileHeight + adjustY, 0); - positions.push(startX + offsetX + adjustX, -halfHeight + y * tileHeight + adjustY, 0); - positions.push(startX + offsetX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); - positions.push(startX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); - indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); - index += 4; - if (flipTile === mesh_Mesh.FLIP_TILE || flipTile === mesh_Mesh.ROTATE_TILE || flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE) { - uvs = uvs.concat(uvBaseLC[(y + 1) % 2]); - } - else if (flipTile === mesh_Mesh.FLIP_ROW || flipTile === mesh_Mesh.ROTATE_ROW || flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvs = uvs.concat(uvBaseLC[y % 2]); - } - else { - uvs = uvs.concat(uvBaseLC[0]); - } - colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); - normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - } - } - if (partialRightCol) { - const uvBaseRC = []; - a = 0; - b = 0; - c = offsetX / tileHeight; - d = 1; - uvBaseRC[0] = [a, b, c, b, c, d, a, d]; - uvBaseRC[1] = [a, b, c, b, c, d, a, d]; - if (flipTile === mesh_Mesh.ROTATE_TILE || flipTile === mesh_Mesh.ROTATE_ROW) { - uvBaseRC[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d]; - } - if (flipTile === mesh_Mesh.FLIP_TILE || flipTile === mesh_Mesh.FLIP_ROW) { - uvBaseRC[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d]; - } - if (flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE || flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvBaseRC[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d]; - } - for (let y = 0; y < tilesY; y++) { - positions.push(endX - offsetX + adjustX, -halfHeight + y * tileHeight + adjustY, 0); - positions.push(endX + adjustX, -halfHeight + y * tileHeight + adjustY, 0); - positions.push(endX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); - positions.push(endX - offsetX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0); - indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3); - index += 4; - if (flipTile === mesh_Mesh.FLIP_TILE || flipTile === mesh_Mesh.ROTATE_TILE || flipTile === mesh_Mesh.FLIP_N_ROTATE_TILE) { - uvs = uvs.concat(uvBaseRC[(y + tilesX) % 2]); - } - else if (flipTile === mesh_Mesh.FLIP_ROW || flipTile === mesh_Mesh.ROTATE_ROW || flipTile === mesh_Mesh.FLIP_N_ROTATE_ROW) { - uvs = uvs.concat(uvBaseRC[y % 2]); - } - else { - uvs = uvs.concat(uvBaseRC[0]); - } - colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); - normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - } - } - } - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - // sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - const totalColors = sideOrientation === mesh_vertexData_VertexData.DOUBLESIDE ? colors.concat(colors) : colors; - vertexData.colors = totalColors; - return vertexData; -} -/** - * Creates a tiled plane mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_plane - * @param name defines the name of the mesh - * @param options an object used to set the following optional parameters for the tiled plane, required but can be empty - * * pattern a limited pattern arrangement depending on the number - * * size of the box - * * width of the box, overwrites size - * * height of the box, overwrites size - * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1 - * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size - * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * alignHorizontal places whole tiles aligned to the center, left or right of a row - * * alignVertical places whole tiles aligned to the center, left or right of a column - * * 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) - * * 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) - * @param options.pattern - * @param options.tileSize - * @param options.tileWidth - * @param options.tileHeight - * @param options.size - * @param options.width - * @param options.height - * @param options.alignHorizontal - * @param options.alignVertical - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.updatable - * @param scene defines the hosting scene - * @returns the box mesh - */ -function CreateTiledPlane(name, options, scene = null) { - const plane = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - plane._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreateTiledPlaneVertexData(options); - vertexData.applyToMesh(plane, options.updatable); - return plane; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use CreateTiledPlane instead - */ -const TiledPlaneBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateTiledPlane, -}; -mesh_vertexData_VertexData.CreateTiledPlane = CreateTiledPlaneVertexData; -//# sourceMappingURL=tiledPlaneBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/tiledBoxBuilder.js - - - - - - -/** - * Creates the VertexData for a tiled box - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_box - * @param options an object used to set the following optional parameters for the tiled box, required but can be empty - * * pattern sets the rotation or reflection pattern for the tiles, - * * size of the box - * * width of the box, overwrites size - * * height of the box, overwrites size - * * depth of the box, overwrites size - * * tileSize sets the size of a tile - * * tileWidth sets the tile width and overwrites tileSize - * * tileHeight sets the tile width and overwrites tileSize - * * faceUV an array of 6 Vector4 elements used to set different images to each box side - * * faceColors an array of 6 Color3 elements used to set different colors to each box side - * * alignHorizontal places whole tiles aligned to the center, left or right of a row - * * alignVertical places whole tiles aligned to the center, left or right of a column - * @param options.pattern - * @param options.size - * @param options.width - * @param options.height - * @param options.depth - * @param options.tileSize - * @param options.tileWidth - * @param options.tileHeight - * @param options.faceUV - * @param options.faceColors - * @param options.alignHorizontal - * @param options.alignVertical - * @param options.sideOrientation - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * @returns the VertexData of the TiledBox - */ -function CreateTiledBoxVertexData(options) { - const nbFaces = 6; - const faceUV = options.faceUV || new Array(6); - const faceColors = options.faceColors; - const flipTile = options.pattern || mesh_Mesh.NO_FLIP; - const width = options.width || options.size || 1; - const height = options.height || options.size || 1; - const depth = options.depth || options.size || 1; - const tileWidth = options.tileWidth || options.tileSize || 1; - const tileHeight = options.tileHeight || options.tileSize || 1; - const alignH = options.alignHorizontal || 0; - const alignV = options.alignVertical || 0; - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - // default face colors and UV if undefined - for (let f = 0; f < nbFaces; f++) { - if (faceUV[f] === undefined) { - faceUV[f] = new math_vector_Vector4(0, 0, 1, 1); - } - if (faceColors && faceColors[f] === undefined) { - faceColors[f] = new math_color_Color4(1, 1, 1, 1); - } - } - const halfWidth = width / 2; - const halfHeight = height / 2; - const halfDepth = depth / 2; - const faceVertexData = []; - for (let f = 0; f < 2; f++) { - //front and back - faceVertexData[f] = CreateTiledPlaneVertexData({ - pattern: flipTile, - tileWidth: tileWidth, - tileHeight: tileHeight, - width: width, - height: height, - alignVertical: alignV, - alignHorizontal: alignH, - sideOrientation: sideOrientation, - }); - } - for (let f = 2; f < 4; f++) { - //sides - faceVertexData[f] = CreateTiledPlaneVertexData({ - pattern: flipTile, - tileWidth: tileWidth, - tileHeight: tileHeight, - width: depth, - height: height, - alignVertical: alignV, - alignHorizontal: alignH, - sideOrientation: sideOrientation, - }); - } - let baseAlignV = alignV; - if (alignV === mesh_Mesh.BOTTOM) { - baseAlignV = mesh_Mesh.TOP; - } - else if (alignV === mesh_Mesh.TOP) { - baseAlignV = mesh_Mesh.BOTTOM; - } - for (let f = 4; f < 6; f++) { - //top and bottom - faceVertexData[f] = CreateTiledPlaneVertexData({ - pattern: flipTile, - tileWidth: tileWidth, - tileHeight: tileHeight, - width: width, - height: depth, - alignVertical: baseAlignV, - alignHorizontal: alignH, - sideOrientation: sideOrientation, - }); - } - let positions = []; - let normals = []; - let uvs = []; - let indices = []; - const colors = []; - const facePositions = []; - const faceNormals = []; - const newFaceUV = []; - let lu = 0; - let li = 0; - for (let f = 0; f < nbFaces; f++) { - const len = faceVertexData[f].positions.length; - facePositions[f] = []; - faceNormals[f] = []; - for (let p = 0; p < len / 3; p++) { - facePositions[f].push(new math_vector_Vector3(faceVertexData[f].positions[3 * p], faceVertexData[f].positions[3 * p + 1], faceVertexData[f].positions[3 * p + 2])); - faceNormals[f].push(new math_vector_Vector3(faceVertexData[f].normals[3 * p], faceVertexData[f].normals[3 * p + 1], faceVertexData[f].normals[3 * p + 2])); - } - // uvs - lu = faceVertexData[f].uvs.length; - newFaceUV[f] = []; - for (let i = 0; i < lu; i += 2) { - newFaceUV[f][i] = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * faceVertexData[f].uvs[i]; - newFaceUV[f][i + 1] = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * faceVertexData[f].uvs[i + 1]; - if (CompatibilityOptions.UseOpenGLOrientationForUV) { - newFaceUV[f][i + 1] = 1.0 - newFaceUV[f][i + 1]; - } - } - uvs = uvs.concat(newFaceUV[f]); - indices = indices.concat(faceVertexData[f].indices.map((x) => x + li)); - li += facePositions[f].length; - if (faceColors) { - for (let c = 0; c < 4; c++) { - colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a); - } - } - } - const vec0 = new math_vector_Vector3(0, 0, halfDepth); - const mtrx0 = math_vector_Matrix.RotationY(Math.PI); - positions = facePositions[0] - .map((entry) => math_vector_Vector3.TransformNormal(entry, mtrx0).add(vec0)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); - normals = faceNormals[0] - .map((entry) => math_vector_Vector3.TransformNormal(entry, mtrx0)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); - positions = positions.concat(facePositions[1] - .map((entry) => entry.subtract(vec0)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); - normals = normals.concat(faceNormals[1].map((entry) => [entry.x, entry.y, entry.z]).reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); - const vec2 = new math_vector_Vector3(halfWidth, 0, 0); - const mtrx2 = math_vector_Matrix.RotationY(-Math.PI / 2); - positions = positions.concat(facePositions[2] - .map((entry) => math_vector_Vector3.TransformNormal(entry, mtrx2).add(vec2)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); - normals = normals.concat(faceNormals[2] - .map((entry) => math_vector_Vector3.TransformNormal(entry, mtrx2)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); - const mtrx3 = math_vector_Matrix.RotationY(Math.PI / 2); - positions = positions.concat(facePositions[3] - .map((entry) => math_vector_Vector3.TransformNormal(entry, mtrx3).subtract(vec2)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); - normals = normals.concat(faceNormals[3] - .map((entry) => math_vector_Vector3.TransformNormal(entry, mtrx3)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); - const vec4 = new math_vector_Vector3(0, halfHeight, 0); - const mtrx4 = math_vector_Matrix.RotationX(Math.PI / 2); - positions = positions.concat(facePositions[4] - .map((entry) => math_vector_Vector3.TransformNormal(entry, mtrx4).add(vec4)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); - normals = normals.concat(faceNormals[4] - .map((entry) => math_vector_Vector3.TransformNormal(entry, mtrx4)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); - const mtrx5 = math_vector_Matrix.RotationX(-Math.PI / 2); - positions = positions.concat(facePositions[5] - .map((entry) => math_vector_Vector3.TransformNormal(entry, mtrx5).subtract(vec4)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); - normals = normals.concat(faceNormals[5] - .map((entry) => math_vector_Vector3.TransformNormal(entry, mtrx5)) - .map((entry) => [entry.x, entry.y, entry.z]) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])); - // sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs); - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - if (faceColors) { - const totalColors = sideOrientation === mesh_vertexData_VertexData.DOUBLESIDE ? colors.concat(colors) : colors; - vertexData.colors = totalColors; - } - return vertexData; -} -/** - * Creates a tiled box mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_box - * @param name defines the name of the mesh - * @param options an object used to set the following optional parameters for the tiled box, required but can be empty - * * pattern sets the rotation or reflection pattern for the tiles, - * * size of the box - * * width of the box, overwrites size - * * height of the box, overwrites size - * * depth of the box, overwrites size - * * tileSize sets the size of a tile - * * tileWidth sets the tile width and overwrites tileSize - * * tileHeight sets the tile width and overwrites tileSize - * * faceUV an array of 6 Vector4 elements used to set different images to each box side - * * faceColors an array of 6 Color3 elements used to set different colors to each box side - * * alignHorizontal places whole tiles aligned to the center, left or right of a row - * * alignVertical places whole tiles aligned to the center, left or right of a column - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * @param options.pattern - * @param options.width - * @param options.height - * @param options.depth - * @param options.tileSize - * @param options.tileWidth - * @param options.tileHeight - * @param options.alignHorizontal - * @param options.alignVertical - * @param options.faceUV - * @param options.faceColors - * @param options.sideOrientation - * @param options.updatable - * @param scene defines the hosting scene - * @returns the box mesh - */ -function CreateTiledBox(name, options, scene = null) { - const box = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - box._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreateTiledBoxVertexData(options); - vertexData.applyToMesh(box, options.updatable); - return box; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use CreateTiledBox instead - */ -const TiledBoxBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateTiledBox, -}; -mesh_vertexData_VertexData.CreateTiledBox = CreateTiledBoxVertexData; -//# sourceMappingURL=tiledBoxBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/torusKnotBuilder.js - - - - -// based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473 -/** - * Creates the VertexData for a TorusKnot - * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty - * * radius the radius of the torus knot, optional, default 2 - * * tube the thickness of the tube, optional, default 0.5 - * * radialSegments the number of sides on each tube segments, optional, default 32 - * * tubularSegments the number of tubes to decompose the knot into, optional, default 32 - * * p the number of windings around the z axis, optional, default 2 - * * q the number of windings around the x axis, optional, default 3 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.radius - * @param options.tube - * @param options.radialSegments - * @param options.tubularSegments - * @param options.p - * @param options.q - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the Torus Knot - */ -function CreateTorusKnotVertexData(options) { - const indices = new Array(); - const positions = new Array(); - const normals = new Array(); - const uvs = new Array(); - const radius = options.radius || 2; - const tube = options.tube || 0.5; - const radialSegments = options.radialSegments || 32; - const tubularSegments = options.tubularSegments || 32; - const p = options.p || 2; - const q = options.q || 3; - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - // Helper - const getPos = (angle) => { - const cu = Math.cos(angle); - const su = Math.sin(angle); - const quOverP = (q / p) * angle; - const cs = Math.cos(quOverP); - const tx = radius * (2 + cs) * 0.5 * cu; - const ty = radius * (2 + cs) * su * 0.5; - const tz = radius * Math.sin(quOverP) * 0.5; - return new math_vector_Vector3(tx, ty, tz); - }; - // Vertices - let i; - let j; - for (i = 0; i <= radialSegments; i++) { - const modI = i % radialSegments; - const u = (modI / radialSegments) * 2 * p * Math.PI; - const p1 = getPos(u); - const p2 = getPos(u + 0.01); - const tang = p2.subtract(p1); - let n = p2.add(p1); - const bitan = math_vector_Vector3.Cross(tang, n); - n = math_vector_Vector3.Cross(bitan, tang); - bitan.normalize(); - n.normalize(); - for (j = 0; j < tubularSegments; j++) { - const modJ = j % tubularSegments; - const v = (modJ / tubularSegments) * 2 * Math.PI; - const cx = -tube * Math.cos(v); - const cy = tube * Math.sin(v); - positions.push(p1.x + cx * n.x + cy * bitan.x); - positions.push(p1.y + cx * n.y + cy * bitan.y); - positions.push(p1.z + cx * n.z + cy * bitan.z); - uvs.push(i / radialSegments); - uvs.push(CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - j / tubularSegments : j / tubularSegments); - } - } - for (i = 0; i < radialSegments; i++) { - for (j = 0; j < tubularSegments; j++) { - const jNext = (j + 1) % tubularSegments; - const a = i * tubularSegments + j; - const b = (i + 1) * tubularSegments + j; - const c = (i + 1) * tubularSegments + jNext; - const d = i * tubularSegments + jNext; - indices.push(d); - indices.push(b); - indices.push(a); - indices.push(d); - indices.push(c); - indices.push(b); - } - } - // Normals - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals); - // Sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - return vertexData; -} -/** - * Creates a torus knot mesh - * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2) - * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32) - * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32) - * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3) - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.radius - * @param options.tube - * @param options.radialSegments - * @param options.tubularSegments - * @param options.p - * @param options.q - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param scene defines the hosting scene - * @returns the torus knot mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#torus-knot - */ -function CreateTorusKnot(name, options = {}, scene) { - const torusKnot = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - torusKnot._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreateTorusKnotVertexData(options); - vertexData.applyToMesh(torusKnot, options.updatable); - return torusKnot; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use CreateTorusKnot instead - */ -const TorusKnotBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateTorusKnot, -}; -mesh_vertexData_VertexData.CreateTorusKnot = CreateTorusKnotVertexData; -mesh_Mesh.CreateTorusKnot = (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) => { - const options = { - radius, - tube, - radialSegments, - tubularSegments, - p, - q, - sideOrientation, - updatable, - }; - return CreateTorusKnot(name, options, scene); -}; -//# sourceMappingURL=torusKnotBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/shaderMaterial.js - - - - - - - - - - - - - -const shaderMaterial_onCreatedEffectParameters = { effect: null, subMesh: null }; -/** - * 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. - * - * This returned material effects how the mesh will look based on the code in the shaders. - * - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial - */ -class shaderMaterial_ShaderMaterial extends PushMaterial { - /** - * Instantiate a new shader material. - * 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. - * This returned material effects how the mesh will look based on the code in the shaders. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial - * @param name Define the name of the material in the scene - * @param scene Define the scene the material belongs to - * @param shaderPath Defines the route to the shader code in one of three ways: - * * object: \{ vertex: "custom", fragment: "custom" \}, used with Effect.ShadersStore["customVertexShader"] and Effect.ShadersStore["customFragmentShader"] - * * object: \{ vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" \}, used with shader code in script tags - * * object: \{ vertexSource: "vertex shader code string", fragmentSource: "fragment shader code string" \} using with strings containing the shaders code - * * string: "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder. - * @param options Define the options used to create the shader - * @param storeEffectOnSubMeshes true to store effect on submeshes, false to store the effect directly in the material class. - */ - constructor(name, scene, shaderPath, options = {}, storeEffectOnSubMeshes = true) { - super(name, scene, storeEffectOnSubMeshes); - 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 math_vector_Matrix(); - this._cachedWorldViewProjectionMatrix = new math_vector_Matrix(); - this._multiview = false; - /** - * @internal - */ - this._materialHelperNeedsPreviousMatrices = false; - this._shaderPath = shaderPath; - this._options = Object.assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], externalTextures: [], samplerObjects: [], storageBuffers: [], defines: [], useClipPlane: false }, options); - } - /** - * Gets the shader path used to define the shader code - * It can be modified to trigger a new compilation - */ - get shaderPath() { - return this._shaderPath; - } - /** - * Sets the shader path used to define the shader code - * It can be modified to trigger a new compilation - */ - set shaderPath(shaderPath) { - this._shaderPath = shaderPath; - } - /** - * Gets the options used to compile the shader. - * They can be modified to trigger a new compilation - */ - get options() { - return this._options; - } - /** - * is multiview set to true? - */ - get isMultiview() { - return this._multiview; - } - /** - * Gets the current class name of the material e.g. "ShaderMaterial" - * Mainly use in serialization. - * @returns the class name - */ - getClassName() { - return "ShaderMaterial"; - } - /** - * Specifies if the material will require alpha blending - * @returns a boolean specifying if alpha blending is needed - */ - needAlphaBlending() { - return this.alpha < 1.0 || this._options.needAlphaBlending; - } - /** - * Specifies if this material should be rendered in alpha test mode - * @returns a boolean specifying if an alpha test is needed. - */ - needAlphaTesting() { - return this._options.needAlphaTesting; - } - _checkUniform(uniformName) { - if (this._options.uniforms.indexOf(uniformName) === -1) { - this._options.uniforms.push(uniformName); - } - } - /** - * Set a texture in the shader. - * @param name Define the name of the uniform samplers as defined in the shader - * @param texture Define the texture to bind to this sampler - * @returns the material itself allowing "fluent" like uniform updates - */ - setTexture(name, texture) { - if (this._options.samplers.indexOf(name) === -1) { - this._options.samplers.push(name); - } - this._textures[name] = texture; - return this; - } - /** - * Set a texture array in the shader. - * @param name Define the name of the uniform sampler array as defined in the shader - * @param textures Define the list of textures to bind to this sampler - * @returns the material itself allowing "fluent" like uniform updates - */ - setTextureArray(name, textures) { - if (this._options.samplers.indexOf(name) === -1) { - this._options.samplers.push(name); - } - this._checkUniform(name); - this._textureArrays[name] = textures; - return this; - } - /** - * Set an internal texture in the shader. - * @param name Define the name of the uniform samplers as defined in the shader - * @param texture Define the texture to bind to this sampler - * @returns the material itself allowing "fluent" like uniform updates - */ - setExternalTexture(name, texture) { - if (this._options.externalTextures.indexOf(name) === -1) { - this._options.externalTextures.push(name); - } - this._externalTextures[name] = texture; - return this; - } - /** - * Set a float in the shader. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setFloat(name, value) { - this._checkUniform(name); - this._floats[name] = value; - return this; - } - /** - * Set a int in the shader. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setInt(name, value) { - this._checkUniform(name); - this._ints[name] = value; - return this; - } - /** - * Set a unsigned int in the shader. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setUInt(name, value) { - this._checkUniform(name); - this._uints[name] = value; - return this; - } - /** - * Set an array of floats in the shader. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setFloats(name, value) { - this._checkUniform(name); - this._floatsArrays[name] = value; - return this; - } - /** - * Set a vec3 in the shader from a Color3. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setColor3(name, value) { - this._checkUniform(name); - this._colors3[name] = value; - return this; - } - /** - * Set a vec3 array in the shader from a Color3 array. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setColor3Array(name, value) { - this._checkUniform(name); - this._colors3Arrays[name] = value.reduce((arr, color) => { - color.toArray(arr, arr.length); - return arr; - }, []); - return this; - } - /** - * Set a vec4 in the shader from a Color4. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setColor4(name, value) { - this._checkUniform(name); - this._colors4[name] = value; - return this; - } - /** - * Set a vec4 array in the shader from a Color4 array. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setColor4Array(name, value) { - this._checkUniform(name); - this._colors4Arrays[name] = value.reduce((arr, color) => { - color.toArray(arr, arr.length); - return arr; - }, []); - return this; - } - /** - * Set a vec2 in the shader from a Vector2. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setVector2(name, value) { - this._checkUniform(name); - this._vectors2[name] = value; - return this; - } - /** - * Set a vec3 in the shader from a Vector3. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setVector3(name, value) { - this._checkUniform(name); - this._vectors3[name] = value; - return this; - } - /** - * Set a vec4 in the shader from a Vector4. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setVector4(name, value) { - this._checkUniform(name); - this._vectors4[name] = value; - return this; - } - /** - * Set a vec4 in the shader from a Quaternion. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setQuaternion(name, value) { - this._checkUniform(name); - this._quaternions[name] = value; - return this; - } - /** - * Set a vec4 array in the shader from a Quaternion array. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setQuaternionArray(name, value) { - this._checkUniform(name); - this._quaternionsArrays[name] = value.reduce((arr, quaternion) => { - quaternion.toArray(arr, arr.length); - return arr; - }, []); - return this; - } - /** - * Set a mat4 in the shader from a Matrix. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setMatrix(name, value) { - this._checkUniform(name); - this._matrices[name] = value; - return this; - } - /** - * Set a float32Array in the shader from a matrix array. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setMatrices(name, value) { - this._checkUniform(name); - const float32Array = new Float32Array(value.length * 16); - for (let index = 0; index < value.length; index++) { - const matrix = value[index]; - matrix.copyToArray(float32Array, index * 16); - } - this._matrixArrays[name] = float32Array; - return this; - } - /** - * Set a mat3 in the shader from a Float32Array. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setMatrix3x3(name, value) { - this._checkUniform(name); - this._matrices3x3[name] = value; - return this; - } - /** - * Set a mat2 in the shader from a Float32Array. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setMatrix2x2(name, value) { - this._checkUniform(name); - this._matrices2x2[name] = value; - return this; - } - /** - * Set a vec2 array in the shader from a number array. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setArray2(name, value) { - this._checkUniform(name); - this._vectors2Arrays[name] = value; - return this; - } - /** - * Set a vec3 array in the shader from a number array. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setArray3(name, value) { - this._checkUniform(name); - this._vectors3Arrays[name] = value; - return this; - } - /** - * Set a vec4 array in the shader from a number array. - * @param name Define the name of the uniform as defined in the shader - * @param value Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setArray4(name, value) { - this._checkUniform(name); - this._vectors4Arrays[name] = value; - return this; - } - /** - * Set a uniform buffer in the shader - * @param name Define the name of the uniform as defined in the shader - * @param buffer Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setUniformBuffer(name, buffer) { - if (this._options.uniformBuffers.indexOf(name) === -1) { - this._options.uniformBuffers.push(name); - } - this._uniformBuffers[name] = buffer; - return this; - } - /** - * Set a texture sampler in the shader - * @param name Define the name of the uniform as defined in the shader - * @param sampler Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setTextureSampler(name, sampler) { - if (this._options.samplerObjects.indexOf(name) === -1) { - this._options.samplerObjects.push(name); - } - this._textureSamplers[name] = sampler; - return this; - } - /** - * Set a storage buffer in the shader - * @param name Define the name of the storage buffer as defined in the shader - * @param buffer Define the value to give to the uniform - * @returns the material itself allowing "fluent" like uniform updates - */ - setStorageBuffer(name, buffer) { - if (this._options.storageBuffers.indexOf(name) === -1) { - this._options.storageBuffers.push(name); - } - this._storageBuffers[name] = buffer; - return this; - } - /** - * Adds, removes, or replaces the specified shader define and value. - * * setDefine("MY_DEFINE", true); // enables a boolean define - * * 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) - * * setDefine("MY_DEFINE", false); // disables and removes the define - * Note if the active defines do change, the shader will be recompiled and this can be expensive. - * @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. - * @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 - * @returns the material itself allowing "fluent" like uniform updates - */ - setDefine(define, value) { - // First remove any existing define with this name. - const defineName = define.trimEnd() + " "; - const existingDefineIdx = this.options.defines.findIndex((x) => x === define || x.startsWith(defineName)); - if (existingDefineIdx >= 0) { - this.options.defines.splice(existingDefineIdx, 1); - } - // Then add the new define value. (If it's a boolean value and false, don't add it.) - if (typeof value !== "boolean" || value) { - this.options.defines.push(defineName + value); - } - return this; - } - /** - * Specifies that the submesh is ready to be used - * @param mesh defines the mesh to check - * @param subMesh defines which submesh to check - * @param useInstances specifies that instances should be used - * @returns a boolean indicating that the submesh is ready or not - */ - isReadyForSubMesh(mesh, subMesh, useInstances) { - return this.isReady(mesh, useInstances, subMesh); - } - /** - * Checks if the material is ready to render the requested mesh - * @param mesh Define the mesh to render - * @param useInstances Define whether or not the material is used with instances - * @param subMesh defines which submesh to render - * @returns true if ready, otherwise false - */ - isReady(mesh, useInstances, subMesh) { - var _a, _b, _c, _d; - const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes; - if (this.isFrozen) { - if (storeEffectOnSubMeshes) { - if (subMesh.effect && subMesh.effect._wasPreviouslyReady) { - return true; - } - } - else { - const effect = this._drawWrapper.effect; - if (effect && effect._wasPreviouslyReady && effect._wasPreviouslyUsingInstances === useInstances) { - return true; - } - } - } - const scene = this.getScene(); - const engine = scene.getEngine(); - // Instances - const defines = []; - const attribs = []; - const fallbacks = new EffectFallbacks(); - let shaderName = this._shaderPath, uniforms = this._options.uniforms, uniformBuffers = this._options.uniformBuffers, samplers = this._options.samplers; - // global multiview - if (engine.getCaps().multiview && scene.activeCamera && scene.activeCamera.outputRenderTarget && scene.activeCamera.outputRenderTarget.getViewCount() > 1) { - this._multiview = true; - defines.push("#define MULTIVIEW"); - if (this._options.uniforms.indexOf("viewProjection") !== -1 && this._options.uniforms.indexOf("viewProjectionR") === -1) { - this._options.uniforms.push("viewProjectionR"); - } - } - for (let index = 0; index < this._options.defines.length; index++) { - const defineToAdd = this._options.defines[index].indexOf("#define") === 0 ? this._options.defines[index] : `#define ${this._options.defines[index]}`; - defines.push(defineToAdd); - } - for (let index = 0; index < this._options.attributes.length; index++) { - attribs.push(this._options.attributes[index]); - } - if (mesh && mesh.isVerticesDataPresent(buffer_VertexBuffer.ColorKind)) { - attribs.push(buffer_VertexBuffer.ColorKind); - defines.push("#define VERTEXCOLOR"); - } - if (useInstances) { - defines.push("#define INSTANCES"); - MaterialHelper.PushAttributesForInstances(attribs, this._materialHelperNeedsPreviousMatrices); - if (mesh === null || mesh === void 0 ? void 0 : mesh.hasThinInstances) { - defines.push("#define THIN_INSTANCES"); - if (mesh && mesh.isVerticesDataPresent(buffer_VertexBuffer.ColorInstanceKind)) { - attribs.push(buffer_VertexBuffer.ColorInstanceKind); - defines.push("#define INSTANCESCOLOR"); - } - } - } - // Bones - if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { - attribs.push(buffer_VertexBuffer.MatricesIndicesKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsKind); - if (mesh.numBoneInfluencers > 4) { - attribs.push(buffer_VertexBuffer.MatricesIndicesExtraKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsExtraKind); - } - const skeleton = mesh.skeleton; - defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); - fallbacks.addCPUSkinningFallback(0, mesh); - if (skeleton.isUsingTextureForMatrices) { - defines.push("#define BONETEXTURE"); - if (this._options.uniforms.indexOf("boneTextureWidth") === -1) { - this._options.uniforms.push("boneTextureWidth"); - } - if (this._options.samplers.indexOf("boneSampler") === -1) { - this._options.samplers.push("boneSampler"); - } - } - else { - defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); - if (this._options.uniforms.indexOf("mBones") === -1) { - this._options.uniforms.push("mBones"); - } - } - } - else { - defines.push("#define NUM_BONE_INFLUENCERS 0"); - } - // Morph - let numInfluencers = 0; - const manager = mesh ? mesh.morphTargetManager : null; - if (manager) { - const uv = manager.supportsUVs && defines.indexOf("#define UV1") !== -1; - const tangent = manager.supportsTangents && defines.indexOf("#define TANGENT") !== -1; - const normal = manager.supportsNormals && defines.indexOf("#define NORMAL") !== -1; - numInfluencers = manager.numInfluencers; - if (uv) { - defines.push("#define MORPHTARGETS_UV"); - } - if (tangent) { - defines.push("#define MORPHTARGETS_TANGENT"); - } - if (normal) { - defines.push("#define MORPHTARGETS_NORMAL"); - } - if (numInfluencers > 0) { - defines.push("#define MORPHTARGETS"); - } - if (manager.isUsingTextureForTargets) { - defines.push("#define MORPHTARGETS_TEXTURE"); - if (this._options.uniforms.indexOf("morphTargetTextureIndices") === -1) { - this._options.uniforms.push("morphTargetTextureIndices"); - } - if (this._options.samplers.indexOf("morphTargets") === -1) { - this._options.samplers.push("morphTargets"); - } - } - defines.push("#define NUM_MORPH_INFLUENCERS " + numInfluencers); - for (let index = 0; index < numInfluencers; index++) { - attribs.push(buffer_VertexBuffer.PositionKind + index); - if (normal) { - attribs.push(buffer_VertexBuffer.NormalKind + index); - } - if (tangent) { - attribs.push(buffer_VertexBuffer.TangentKind + index); - } - if (uv) { - attribs.push(buffer_VertexBuffer.UVKind + "_" + index); - } - } - if (numInfluencers > 0) { - uniforms = uniforms.slice(); - uniforms.push("morphTargetInfluences"); - uniforms.push("morphTargetTextureInfo"); - uniforms.push("morphTargetTextureIndices"); - } - } - else { - defines.push("#define NUM_MORPH_INFLUENCERS 0"); - } - // Baked Vertex Animation - if (mesh) { - const bvaManager = mesh.bakedVertexAnimationManager; - if (bvaManager && bvaManager.isEnabled) { - defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"); - if (this._options.uniforms.indexOf("bakedVertexAnimationSettings") === -1) { - this._options.uniforms.push("bakedVertexAnimationSettings"); - } - if (this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted") === -1) { - this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"); - } - if (this._options.uniforms.indexOf("bakedVertexAnimationTime") === -1) { - this._options.uniforms.push("bakedVertexAnimationTime"); - } - if (this._options.samplers.indexOf("bakedVertexAnimationTexture") === -1) { - this._options.samplers.push("bakedVertexAnimationTexture"); - } - } - MaterialHelper.PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines); - } - // Textures - for (const name in this._textures) { - if (!this._textures[name].isReady()) { - return false; - } - } - // Alpha test - if (mesh && this._shouldTurnAlphaTestOn(mesh)) { - defines.push("#define ALPHATEST"); - } - // Clip planes - if (this._options.useClipPlane !== false) { - addClipPlaneUniforms(uniforms); - prepareStringDefinesForClipPlanes(this, scene, defines); - } - if (this.customShaderNameResolve) { - uniforms = uniforms.slice(); - uniformBuffers = uniformBuffers.slice(); - samplers = samplers.slice(); - shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs); - } - const drawWrapper = storeEffectOnSubMeshes ? subMesh._getDrawWrapper() : this._drawWrapper; - const previousEffect = (_a = drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.effect) !== null && _a !== void 0 ? _a : null; - const previousDefines = (_b = drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.defines) !== null && _b !== void 0 ? _b : null; - const join = defines.join("\n"); - let effect = previousEffect; - if (previousDefines !== join) { - effect = engine.createEffect(shaderName, { - attributes: attribs, - uniformsNames: uniforms, - uniformBuffersNames: uniformBuffers, - samplers: samplers, - defines: join, - fallbacks: fallbacks, - onCompiled: this.onCompiled, - onError: this.onError, - indexParameters: { maxSimultaneousMorphTargets: numInfluencers }, - shaderLanguage: this._options.shaderLanguage, - }, engine); - if (storeEffectOnSubMeshes) { - subMesh.setEffect(effect, join, this._materialContext); - } - else if (drawWrapper) { - drawWrapper.setEffect(effect, join); - } - if (this._onEffectCreatedObservable) { - shaderMaterial_onCreatedEffectParameters.effect = effect; - shaderMaterial_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; - this._onEffectCreatedObservable.notifyObservers(shaderMaterial_onCreatedEffectParameters); - } - } - effect._wasPreviouslyUsingInstances = !!useInstances; - if ((_d = !(effect === null || effect === void 0 ? void 0 : effect.isReady())) !== null && _d !== void 0 ? _d : true) { - return false; - } - if (previousEffect !== effect) { - scene.resetCachedMaterial(); - } - effect._wasPreviouslyReady = true; - return true; - } - /** - * Binds the world matrix to the material - * @param world defines the world transformation matrix - * @param effectOverride - If provided, use this effect instead of internal effect - */ - bindOnlyWorldMatrix(world, effectOverride) { - const scene = this.getScene(); - const effect = effectOverride !== null && effectOverride !== void 0 ? effectOverride : this.getEffect(); - if (!effect) { - return; - } - if (this._options.uniforms.indexOf("world") !== -1) { - effect.setMatrix("world", world); - } - if (this._options.uniforms.indexOf("worldView") !== -1) { - world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix); - effect.setMatrix("worldView", this._cachedWorldViewMatrix); - } - if (this._options.uniforms.indexOf("worldViewProjection") !== -1) { - world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix); - effect.setMatrix("worldViewProjection", this._cachedWorldViewProjectionMatrix); - } - } - /** - * Binds the submesh to this material by preparing the effect and shader to draw - * @param world defines the world transformation matrix - * @param mesh defines the mesh containing the submesh - * @param subMesh defines the submesh to bind the material to - */ - bindForSubMesh(world, mesh, subMesh) { - var _a; - this.bind(world, mesh, (_a = subMesh._drawWrapperOverride) === null || _a === void 0 ? void 0 : _a.effect, subMesh); - } - /** - * Binds the material to the mesh - * @param world defines the world transformation matrix - * @param mesh defines the mesh to bind the material to - * @param effectOverride - If provided, use this effect instead of internal effect - * @param subMesh defines the submesh to bind the material to - */ - bind(world, mesh, effectOverride, subMesh) { - var _a; - // Std values - const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes; - const effect = effectOverride !== null && effectOverride !== void 0 ? effectOverride : (storeEffectOnSubMeshes ? subMesh.effect : this.getEffect()); - if (!effect) { - return; - } - this._activeEffect = effect; - this.bindOnlyWorldMatrix(world, effectOverride); - const uniformBuffers = this._options.uniformBuffers; - let useSceneUBO = false; - if (effect && uniformBuffers && uniformBuffers.length > 0 && this.getScene().getEngine().supportsUniformBuffers) { - for (let i = 0; i < uniformBuffers.length; ++i) { - const bufferName = uniformBuffers[i]; - switch (bufferName) { - case "Mesh": - if (mesh) { - mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); - mesh.transferToEffect(world); - } - break; - case "Scene": - MaterialHelper.BindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer()); - this.getScene().finalizeSceneUbo(); - useSceneUBO = true; - break; - } - } - } - const mustRebind = mesh && storeEffectOnSubMeshes ? this._mustRebind(this.getScene(), effect, mesh.visibility) : this.getScene().getCachedMaterial() !== this; - if (effect && mustRebind) { - if (!useSceneUBO && this._options.uniforms.indexOf("view") !== -1) { - effect.setMatrix("view", this.getScene().getViewMatrix()); - } - if (!useSceneUBO && this._options.uniforms.indexOf("projection") !== -1) { - effect.setMatrix("projection", this.getScene().getProjectionMatrix()); - } - if (!useSceneUBO && this._options.uniforms.indexOf("viewProjection") !== -1) { - effect.setMatrix("viewProjection", this.getScene().getTransformMatrix()); - if (this._multiview) { - effect.setMatrix("viewProjectionR", this.getScene()._transformMatrixR); - } - } - if (this.getScene().activeCamera && this._options.uniforms.indexOf("cameraPosition") !== -1) { - effect.setVector3("cameraPosition", this.getScene().activeCamera.globalPosition); - } - // Bones - MaterialHelper.BindBonesParameters(mesh, effect); - // Clip plane - bindClipPlane(effect, this, this.getScene()); - let name; - // Texture - for (name in this._textures) { - effect.setTexture(name, this._textures[name]); - } - // Texture arrays - for (name in this._textureArrays) { - effect.setTextureArray(name, this._textureArrays[name]); - } - // External texture - for (name in this._externalTextures) { - effect.setExternalTexture(name, this._externalTextures[name]); - } - // Int - for (name in this._ints) { - effect.setInt(name, this._ints[name]); - } - // UInt - for (name in this._uints) { - effect.setUInt(name, this._uints[name]); - } - // Float - for (name in this._floats) { - effect.setFloat(name, this._floats[name]); - } - // Floats - for (name in this._floatsArrays) { - effect.setArray(name, this._floatsArrays[name]); - } - // Color3 - for (name in this._colors3) { - effect.setColor3(name, this._colors3[name]); - } - // Color3Array - for (name in this._colors3Arrays) { - effect.setArray3(name, this._colors3Arrays[name]); - } - // Color4 - for (name in this._colors4) { - const color = this._colors4[name]; - effect.setFloat4(name, color.r, color.g, color.b, color.a); - } - // Color4Array - for (name in this._colors4Arrays) { - effect.setArray4(name, this._colors4Arrays[name]); - } - // Vector2 - for (name in this._vectors2) { - effect.setVector2(name, this._vectors2[name]); - } - // Vector3 - for (name in this._vectors3) { - effect.setVector3(name, this._vectors3[name]); - } - // Vector4 - for (name in this._vectors4) { - effect.setVector4(name, this._vectors4[name]); - } - // Quaternion - for (name in this._quaternions) { - effect.setQuaternion(name, this._quaternions[name]); - } - // Matrix - for (name in this._matrices) { - effect.setMatrix(name, this._matrices[name]); - } - // MatrixArray - for (name in this._matrixArrays) { - effect.setMatrices(name, this._matrixArrays[name]); - } - // Matrix 3x3 - for (name in this._matrices3x3) { - effect.setMatrix3x3(name, this._matrices3x3[name]); - } - // Matrix 2x2 - for (name in this._matrices2x2) { - effect.setMatrix2x2(name, this._matrices2x2[name]); - } - // Vector2Array - for (name in this._vectors2Arrays) { - effect.setArray2(name, this._vectors2Arrays[name]); - } - // Vector3Array - for (name in this._vectors3Arrays) { - effect.setArray3(name, this._vectors3Arrays[name]); - } - // Vector4Array - for (name in this._vectors4Arrays) { - effect.setArray4(name, this._vectors4Arrays[name]); - } - // QuaternionArray - for (name in this._quaternionsArrays) { - effect.setArray4(name, this._quaternionsArrays[name]); - } - // Uniform buffers - for (name in this._uniformBuffers) { - const buffer = this._uniformBuffers[name].getBuffer(); - if (buffer) { - effect.bindUniformBuffer(buffer, name); - } - } - // Samplers - for (name in this._textureSamplers) { - effect.setTextureSampler(name, this._textureSamplers[name]); - } - // Storage buffers - for (name in this._storageBuffers) { - effect.setStorageBuffer(name, this._storageBuffers[name]); - } - } - if (effect && mesh && (mustRebind || !this.isFrozen)) { - // Morph targets - const manager = mesh.morphTargetManager; - if (manager && manager.numInfluencers > 0) { - MaterialHelper.BindMorphTargetParameters(mesh, effect); - } - const bvaManager = mesh.bakedVertexAnimationManager; - if (bvaManager && bvaManager.isEnabled) { - (_a = mesh.bakedVertexAnimationManager) === null || _a === void 0 ? void 0 : _a.bind(effect, !!effect._wasPreviouslyUsingInstances); - } - } - this._afterBind(mesh, effect); - } - /** - * Gets the active textures from the material - * @returns an array of textures - */ - getActiveTextures() { - const activeTextures = super.getActiveTextures(); - for (const name in this._textures) { - activeTextures.push(this._textures[name]); - } - for (const name in this._textureArrays) { - const array = this._textureArrays[name]; - for (let index = 0; index < array.length; index++) { - activeTextures.push(array[index]); - } - } - return activeTextures; - } - /** - * Specifies if the material uses a texture - * @param texture defines the texture to check against the material - * @returns a boolean specifying if the material uses the texture - */ - hasTexture(texture) { - if (super.hasTexture(texture)) { - return true; - } - for (const name in this._textures) { - if (this._textures[name] === texture) { - return true; - } - } - for (const name in this._textureArrays) { - const array = this._textureArrays[name]; - for (let index = 0; index < array.length; index++) { - if (array[index] === texture) { - return true; - } - } - } - return false; - } - /** - * Makes a duplicate of the material, and gives it a new name - * @param name defines the new name for the duplicated material - * @returns the cloned material - */ - clone(name) { - const result = decorators_SerializationHelper.Clone(() => new shaderMaterial_ShaderMaterial(name, this.getScene(), this._shaderPath, this._options, this._storeEffectOnSubMeshes), this); - result.name = name; - result.id = name; - // Shader code path - if (typeof result._shaderPath === "object") { - result._shaderPath = Object.assign({}, result._shaderPath); - } - // Options - this._options = Object.assign({}, this._options); - Object.keys(this._options).forEach((propName) => { - const propValue = this._options[propName]; - if (Array.isArray(propValue)) { - this._options[propName] = propValue.slice(0); - } - }); - // Stencil - this.stencil.copyTo(result.stencil); - // Texture - for (const key in this._textures) { - result.setTexture(key, this._textures[key]); - } - // TextureArray - for (const key in this._textureArrays) { - result.setTextureArray(key, this._textureArrays[key]); - } - // External texture - for (const key in this._externalTextures) { - result.setExternalTexture(key, this._externalTextures[key]); - } - // Int - for (const key in this._ints) { - result.setInt(key, this._ints[key]); - } - // UInt - for (const key in this._uints) { - result.setUInt(key, this._uints[key]); - } - // Float - for (const key in this._floats) { - result.setFloat(key, this._floats[key]); - } - // Floats - for (const key in this._floatsArrays) { - result.setFloats(key, this._floatsArrays[key]); - } - // Color3 - for (const key in this._colors3) { - result.setColor3(key, this._colors3[key]); - } - // Color3Array - for (const key in this._colors3Arrays) { - result._colors3Arrays[key] = this._colors3Arrays[key]; - } - // Color4 - for (const key in this._colors4) { - result.setColor4(key, this._colors4[key]); - } - // Color4Array - for (const key in this._colors4Arrays) { - result._colors4Arrays[key] = this._colors4Arrays[key]; - } - // Vector2 - for (const key in this._vectors2) { - result.setVector2(key, this._vectors2[key]); - } - // Vector3 - for (const key in this._vectors3) { - result.setVector3(key, this._vectors3[key]); - } - // Vector4 - for (const key in this._vectors4) { - result.setVector4(key, this._vectors4[key]); - } - // Quaternion - for (const key in this._quaternions) { - result.setQuaternion(key, this._quaternions[key]); - } - // QuaternionArray - for (const key in this._quaternionsArrays) { - result._quaternionsArrays[key] = this._quaternionsArrays[key]; - } - // Matrix - for (const key in this._matrices) { - result.setMatrix(key, this._matrices[key]); - } - // MatrixArray - for (const key in this._matrixArrays) { - result._matrixArrays[key] = this._matrixArrays[key].slice(); - } - // Matrix 3x3 - for (const key in this._matrices3x3) { - result.setMatrix3x3(key, this._matrices3x3[key]); - } - // Matrix 2x2 - for (const key in this._matrices2x2) { - result.setMatrix2x2(key, this._matrices2x2[key]); - } - // Vector2Array - for (const key in this._vectors2Arrays) { - result.setArray2(key, this._vectors2Arrays[key]); - } - // Vector3Array - for (const key in this._vectors3Arrays) { - result.setArray3(key, this._vectors3Arrays[key]); - } - // Vector4Array - for (const key in this._vectors4Arrays) { - result.setArray4(key, this._vectors4Arrays[key]); - } - // Uniform buffers - for (const key in this._uniformBuffers) { - result.setUniformBuffer(key, this._uniformBuffers[key]); - } - // Samplers - for (const key in this._textureSamplers) { - result.setTextureSampler(key, this._textureSamplers[key]); - } - // Storag buffers - for (const key in this._storageBuffers) { - result.setStorageBuffer(key, this._storageBuffers[key]); - } - return result; - } - /** - * Disposes the material - * @param forceDisposeEffect specifies if effects should be forcefully disposed - * @param forceDisposeTextures specifies if textures should be forcefully disposed - * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh - */ - dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { - if (forceDisposeTextures) { - let name; - for (name in this._textures) { - this._textures[name].dispose(); - } - for (name in this._textureArrays) { - const array = this._textureArrays[name]; - for (let index = 0; index < array.length; index++) { - array[index].dispose(); - } - } - } - this._textures = {}; - super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh); - } - /** - * Serializes this material in a JSON representation - * @returns the serialized material object - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.customType = "BABYLON.ShaderMaterial"; - serializationObject.uniqueId = this.uniqueId; - serializationObject.options = this._options; - serializationObject.shaderPath = this._shaderPath; - serializationObject.storeEffectOnSubMeshes = this._storeEffectOnSubMeshes; - let name; - // Stencil - serializationObject.stencil = this.stencil.serialize(); - // Texture - serializationObject.textures = {}; - for (name in this._textures) { - serializationObject.textures[name] = this._textures[name].serialize(); - } - // Texture arrays - serializationObject.textureArrays = {}; - for (name in this._textureArrays) { - serializationObject.textureArrays[name] = []; - const array = this._textureArrays[name]; - for (let index = 0; index < array.length; index++) { - serializationObject.textureArrays[name].push(array[index].serialize()); - } - } - // Int - serializationObject.ints = {}; - for (name in this._ints) { - serializationObject.ints[name] = this._ints[name]; - } - // UInt - serializationObject.uints = {}; - for (name in this._uints) { - serializationObject.uints[name] = this._uints[name]; - } - // Float - serializationObject.floats = {}; - for (name in this._floats) { - serializationObject.floats[name] = this._floats[name]; - } - // Floats - serializationObject.FloatArrays = {}; - for (name in this._floatsArrays) { - serializationObject.FloatArrays[name] = this._floatsArrays[name]; - } - // Color3 - serializationObject.colors3 = {}; - for (name in this._colors3) { - serializationObject.colors3[name] = this._colors3[name].asArray(); - } - // Color3 array - serializationObject.colors3Arrays = {}; - for (name in this._colors3Arrays) { - serializationObject.colors3Arrays[name] = this._colors3Arrays[name]; - } - // Color4 - serializationObject.colors4 = {}; - for (name in this._colors4) { - serializationObject.colors4[name] = this._colors4[name].asArray(); - } - // Color4 array - serializationObject.colors4Arrays = {}; - for (name in this._colors4Arrays) { - serializationObject.colors4Arrays[name] = this._colors4Arrays[name]; - } - // Vector2 - serializationObject.vectors2 = {}; - for (name in this._vectors2) { - serializationObject.vectors2[name] = this._vectors2[name].asArray(); - } - // Vector3 - serializationObject.vectors3 = {}; - for (name in this._vectors3) { - serializationObject.vectors3[name] = this._vectors3[name].asArray(); - } - // Vector4 - serializationObject.vectors4 = {}; - for (name in this._vectors4) { - serializationObject.vectors4[name] = this._vectors4[name].asArray(); - } - // Quaternion - serializationObject.quaternions = {}; - for (name in this._quaternions) { - serializationObject.quaternions[name] = this._quaternions[name].asArray(); - } - // Matrix - serializationObject.matrices = {}; - for (name in this._matrices) { - serializationObject.matrices[name] = this._matrices[name].asArray(); - } - // MatrixArray - serializationObject.matrixArray = {}; - for (name in this._matrixArrays) { - serializationObject.matrixArray[name] = this._matrixArrays[name]; - } - // Matrix 3x3 - serializationObject.matrices3x3 = {}; - for (name in this._matrices3x3) { - serializationObject.matrices3x3[name] = this._matrices3x3[name]; - } - // Matrix 2x2 - serializationObject.matrices2x2 = {}; - for (name in this._matrices2x2) { - serializationObject.matrices2x2[name] = this._matrices2x2[name]; - } - // Vector2Array - serializationObject.vectors2Arrays = {}; - for (name in this._vectors2Arrays) { - serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name]; - } - // Vector3Array - serializationObject.vectors3Arrays = {}; - for (name in this._vectors3Arrays) { - serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name]; - } - // Vector4Array - serializationObject.vectors4Arrays = {}; - for (name in this._vectors4Arrays) { - serializationObject.vectors4Arrays[name] = this._vectors4Arrays[name]; - } - // QuaternionArray - serializationObject.quaternionsArrays = {}; - for (name in this._quaternionsArrays) { - serializationObject.quaternionsArrays[name] = this._quaternionsArrays[name]; - } - return serializationObject; - } - /** - * Creates a shader material from parsed shader material data - * @param source defines the JSON representation of the material - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a new material - */ - static Parse(source, scene, rootUrl) { - const material = decorators_SerializationHelper.Parse(() => new shaderMaterial_ShaderMaterial(source.name, scene, source.shaderPath, source.options, source.storeEffectOnSubMeshes), source, scene, rootUrl); - let name; - // Stencil - if (source.stencil) { - material.stencil.parse(source.stencil, scene, rootUrl); - } - // Texture - for (name in source.textures) { - material.setTexture(name, texture_Texture.Parse(source.textures[name], scene, rootUrl)); - } - // Texture arrays - for (name in source.textureArrays) { - const array = source.textureArrays[name]; - const textureArray = new Array(); - for (let index = 0; index < array.length; index++) { - textureArray.push(texture_Texture.Parse(array[index], scene, rootUrl)); - } - material.setTextureArray(name, textureArray); - } - // Int - for (name in source.ints) { - material.setInt(name, source.ints[name]); - } - // UInt - for (name in source.uints) { - material.setUInt(name, source.uints[name]); - } - // Float - for (name in source.floats) { - material.setFloat(name, source.floats[name]); - } - // Floats - for (name in source.floatsArrays) { - material.setFloats(name, source.floatsArrays[name]); - } - // Color3 - for (name in source.colors3) { - material.setColor3(name, math_color_Color3.FromArray(source.colors3[name])); - } - // Color3 arrays - for (name in source.colors3Arrays) { - const colors = source.colors3Arrays[name] - .reduce((arr, num, i) => { - if (i % 3 === 0) { - arr.push([num]); - } - else { - arr[arr.length - 1].push(num); - } - return arr; - }, []) - .map((color) => math_color_Color3.FromArray(color)); - material.setColor3Array(name, colors); - } - // Color4 - for (name in source.colors4) { - material.setColor4(name, math_color_Color4.FromArray(source.colors4[name])); - } - // Color4 arrays - for (name in source.colors4Arrays) { - const colors = source.colors4Arrays[name] - .reduce((arr, num, i) => { - if (i % 4 === 0) { - arr.push([num]); - } - else { - arr[arr.length - 1].push(num); - } - return arr; - }, []) - .map((color) => math_color_Color4.FromArray(color)); - material.setColor4Array(name, colors); - } - // Vector2 - for (name in source.vectors2) { - material.setVector2(name, math_vector_Vector2.FromArray(source.vectors2[name])); - } - // Vector3 - for (name in source.vectors3) { - material.setVector3(name, math_vector_Vector3.FromArray(source.vectors3[name])); - } - // Vector4 - for (name in source.vectors4) { - material.setVector4(name, math_vector_Vector4.FromArray(source.vectors4[name])); - } - // Quaternion - for (name in source.quaternions) { - material.setQuaternion(name, math_vector_Quaternion.FromArray(source.quaternions[name])); - } - // Matrix - for (name in source.matrices) { - material.setMatrix(name, math_vector_Matrix.FromArray(source.matrices[name])); - } - // MatrixArray - for (name in source.matrixArray) { - material._matrixArrays[name] = new Float32Array(source.matrixArray[name]); - } - // Matrix 3x3 - for (name in source.matrices3x3) { - material.setMatrix3x3(name, source.matrices3x3[name]); - } - // Matrix 2x2 - for (name in source.matrices2x2) { - material.setMatrix2x2(name, source.matrices2x2[name]); - } - // Vector2Array - for (name in source.vectors2Arrays) { - material.setArray2(name, source.vectors2Arrays[name]); - } - // Vector3Array - for (name in source.vectors3Arrays) { - material.setArray3(name, source.vectors3Arrays[name]); - } - // Vector4Array - for (name in source.vectors4Arrays) { - material.setArray4(name, source.vectors4Arrays[name]); - } - // QuaternionArray - for (name in source.quaternionsArrays) { - material.setArray4(name, source.quaternionsArrays[name]); - } - return material; - } - /** - * Creates a new ShaderMaterial from a snippet saved in a remote file - * @param name defines the name of the ShaderMaterial to create (can be null or empty to use the one from the json data) - * @param url defines the url to load from - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a promise that will resolve to the new ShaderMaterial - */ - static ParseFromFileAsync(name, url, scene, rootUrl = "") { - return new Promise((resolve, reject) => { - const request = new webRequest_WebRequest(); - request.addEventListener("readystatechange", () => { - if (request.readyState == 4) { - if (request.status == 200) { - const serializationObject = JSON.parse(request.responseText); - const output = this.Parse(serializationObject, scene || engineStore_EngineStore.LastCreatedScene, rootUrl); - if (name) { - output.name = name; - } - resolve(output); - } - else { - reject("Unable to load the ShaderMaterial"); - } - } - }); - request.open("GET", url); - request.send(); - }); - } - /** - * Creates a ShaderMaterial from a snippet saved by the Inspector - * @param snippetId defines the snippet to load - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a promise that will resolve to the new ShaderMaterial - */ - static ParseFromSnippetAsync(snippetId, scene, rootUrl = "") { - return new Promise((resolve, reject) => { - const request = new webRequest_WebRequest(); - request.addEventListener("readystatechange", () => { - if (request.readyState == 4) { - if (request.status == 200) { - const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); - const serializationObject = JSON.parse(snippet.shaderMaterial); - const output = this.Parse(serializationObject, scene || engineStore_EngineStore.LastCreatedScene, rootUrl); - output.snippetId = snippetId; - resolve(output); - } - else { - reject("Unable to load the snippet " + snippetId); - } - } - }); - request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); - request.send(); - }); - } -} -/** Define the Url to load snippets */ -shaderMaterial_ShaderMaterial.SnippetUrl = `https://snippet.babylonjs.com`; -/** - * Creates a ShaderMaterial from a snippet saved by the Inspector - * @deprecated Please use ParseFromSnippetAsync instead - * @param snippetId defines the snippet to load - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a promise that will resolve to the new ShaderMaterial - */ -shaderMaterial_ShaderMaterial.CreateFromSnippetAsync = shaderMaterial_ShaderMaterial.ParseFromSnippetAsync; -RegisterClass("BABYLON.ShaderMaterial", shaderMaterial_ShaderMaterial); -//# sourceMappingURL=shaderMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/color.fragment.js -// Do not edit. - - - -const color_fragment_name = "colorPixelShader"; -const color_fragment_shader = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -#define VERTEXCOLOR -varying vec4 vColor; -#else -uniform vec4 color; -#endif -#include<clipPlaneFragmentDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -gl_FragColor=vColor; -#else -gl_FragColor=color; -#endif -#define CUSTOM_FRAGMENT_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[color_fragment_name] = color_fragment_shader; -/** @internal */ -const colorPixelShader = { name: color_fragment_name, shader: color_fragment_shader }; -//# sourceMappingURL=color.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/color.vertex.js -// Do not edit. - - - - - - - - - - -const color_vertex_name = "colorVertexShader"; -const color_vertex_shader = `attribute vec3 position; -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<clipPlaneVertexDeclaration> -#include<instancesDeclaration> -uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(position,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#include<clipPlaneVertex> -#include<vertexColorMixing> -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[color_vertex_name] = color_vertex_shader; -/** @internal */ -const colorVertexShader = { name: color_vertex_name, shader: color_vertex_shader }; -//# sourceMappingURL=color.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/linesMesh.js - - - - - - - - -mesh_Mesh._LinesMeshParser = (parsedMesh, scene) => { - return LinesMesh.Parse(parsedMesh, scene); -}; -/** - * Line mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param - */ -class LinesMesh extends mesh_Mesh { - _isShaderMaterial(shader) { - return shader.getClassName() === "ShaderMaterial"; - } - /** - * Creates a new LinesMesh - * @param name defines the name - * @param scene defines the hosting scene - * @param parent defines the parent mesh if any - * @param source defines the optional source LinesMesh used to clone data from - * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False. - * When false, achieved by calling a clone(), also passing False. - * This will make creation of children, recursive. - * @param useVertexColor defines if this LinesMesh supports vertex color - * @param useVertexAlpha defines if this LinesMesh supports vertex alpha - * @param material material to use to draw the line. If not provided, will create a new one - */ - constructor(name, scene = null, parent = null, source = null, doNotCloneChildren, - /** - * If vertex color should be applied to the mesh - */ - useVertexColor, - /** - * If vertex alpha should be applied to the mesh - */ - useVertexAlpha, material) { - super(name, scene, parent, source, doNotCloneChildren); - this.useVertexColor = useVertexColor; - this.useVertexAlpha = useVertexAlpha; - /** - * Color of the line (Default: White) - */ - this.color = new math_color_Color3(1, 1, 1); - /** - * Alpha of the line (Default: 1) - */ - this.alpha = 1; - if (source) { - this.color = source.color.clone(); - this.alpha = source.alpha; - this.useVertexColor = source.useVertexColor; - this.useVertexAlpha = source.useVertexAlpha; - } - this.intersectionThreshold = 0.1; - const defines = []; - const options = { - attributes: [buffer_VertexBuffer.PositionKind], - uniforms: ["world", "viewProjection"], - needAlphaBlending: true, - defines: defines, - useClipPlane: null, - }; - if (useVertexAlpha === false) { - options.needAlphaBlending = false; - } - else { - options.defines.push("#define VERTEXALPHA"); - } - if (!useVertexColor) { - options.uniforms.push("color"); - this._color4 = new math_color_Color4(); - } - else { - options.defines.push("#define VERTEXCOLOR"); - options.attributes.push(buffer_VertexBuffer.ColorKind); - } - if (material) { - this.material = material; - } - else { - this.material = new shaderMaterial_ShaderMaterial("colorShader", this.getScene(), "color", options, false); - this.material.doNotSerialize = true; - } - } - isReady() { - if (!this._lineMaterial.isReady(this, !!this._userInstancedBuffersStorage)) { - return false; - } - return super.isReady(); - } - /** - * Returns the string "LineMesh" - */ - getClassName() { - return "LinesMesh"; - } - /** - * @internal - */ - get material() { - return this._lineMaterial; - } - /** - * @internal - */ - set material(value) { - this._lineMaterial = value; - this._lineMaterial.fillMode = material_Material.LineListDrawMode; - } - /** - * @internal - */ - get checkCollisions() { - return false; - } - set checkCollisions(value) { - // Just ignore it - } - /** - * @internal - */ - _bind(_subMesh, colorEffect) { - if (!this._geometry) { - return this; - } - // VBOs - const indexToBind = this.isUnIndexed ? null : this._geometry.getIndexBuffer(); - if (!this._userInstancedBuffersStorage) { - this._geometry._bind(colorEffect, indexToBind); - } - else { - this._geometry._bind(colorEffect, indexToBind, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects); - } - // Color - if (!this.useVertexColor && this._isShaderMaterial(this._lineMaterial)) { - const { r, g, b } = this.color; - this._color4.set(r, g, b, this.alpha); - this._lineMaterial.setColor4("color", this._color4); - } - return this; - } - /** - * @internal - */ - _draw(subMesh, fillMode, instancesCount) { - if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { - return this; - } - const engine = this.getScene().getEngine(); - // Draw order - if (this._unIndexed) { - engine.drawArraysType(material_Material.LineListDrawMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount); - } - else { - engine.drawElementsType(material_Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount); - } - return this; - } - /** - * Disposes of the line mesh - * @param doNotRecurse If children should be disposed - * @param disposeMaterialAndTextures This parameter is not used by the LineMesh class - * @param doNotDisposeMaterial If the material should not be disposed (default: false, meaning the material is disposed) - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - dispose(doNotRecurse, disposeMaterialAndTextures = false, doNotDisposeMaterial) { - if (!doNotDisposeMaterial) { - this._lineMaterial.dispose(false, false, true); - } - super.dispose(doNotRecurse); - } - /** - * Returns a new LineMesh object cloned from the current one. - * @param name - * @param newParent - * @param doNotCloneChildren - */ - clone(name, newParent = null, doNotCloneChildren) { - return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren); - } - /** - * Creates a new InstancedLinesMesh object from the mesh model. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances - * @param name defines the name of the new instance - * @returns a new InstancedLinesMesh - */ - createInstance(name) { - const instance = new InstancedLinesMesh(name, this); - if (this.instancedBuffers) { - instance.instancedBuffers = {}; - for (const key in this.instancedBuffers) { - instance.instancedBuffers[key] = this.instancedBuffers[key]; - } - } - return instance; - } - /** - * Serializes this ground mesh - * @param serializationObject object to write serialization to - */ - serialize(serializationObject) { - super.serialize(serializationObject); - serializationObject.color = this.color.asArray(); - serializationObject.alpha = this.alpha; - } - /** - * Parses a serialized ground mesh - * @param parsedMesh the serialized mesh - * @param scene the scene to create the ground mesh in - * @returns the created ground mesh - */ - static Parse(parsedMesh, scene) { - const result = new LinesMesh(parsedMesh.name, scene); - result.color = math_color_Color3.FromArray(parsedMesh.color); - result.alpha = parsedMesh.alpha; - return result; - } -} -/** - * Creates an instance based on a source LinesMesh - */ -class InstancedLinesMesh extends instancedMesh_InstancedMesh { - constructor(name, source) { - super(name, source); - this.intersectionThreshold = source.intersectionThreshold; - } - /** - * Returns the string "InstancedLinesMesh". - */ - getClassName() { - return "InstancedLinesMesh"; - } -} -//# sourceMappingURL=linesMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/linesBuilder.js -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - -/** - * Creates the VertexData of the LineSystem - * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty - * - lines an array of lines, each line being an array of successive Vector3 - * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point - * @param options.lines - * @param options.colors - * @returns the VertexData of the LineSystem - */ -function CreateLineSystemVertexData(options) { - const indices = []; - const positions = []; - const lines = options.lines; - const colors = options.colors; - const vertexColors = []; - let idx = 0; - for (let l = 0; l < lines.length; l++) { - const points = lines[l]; - for (let index = 0; index < points.length; index++) { - positions.push(points[index].x, points[index].y, points[index].z); - if (colors) { - const color = colors[l]; - vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a); - } - if (index > 0) { - indices.push(idx - 1); - indices.push(idx); - } - idx++; - } - } - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - if (colors) { - vertexData.colors = vertexColors; - } - return vertexData; -} -/** - * Create the VertexData for a DashedLines - * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty - * - points an array successive Vector3 - * - dashSize the size of the dashes relative to the dash number, optional, default 3 - * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1 - * - dashNb the intended total number of dashes, optional, default 200 - * @param options.points - * @param options.dashSize - * @param options.gapSize - * @param options.dashNb - * @returns the VertexData for the DashedLines - */ -function CreateDashedLinesVertexData(options) { - const dashSize = options.dashSize || 3; - const gapSize = options.gapSize || 1; - const dashNb = options.dashNb || 200; - const points = options.points; - const positions = new Array(); - const indices = new Array(); - const curvect = math_vector_Vector3.Zero(); - let lg = 0; - let nb = 0; - let shft = 0; - let dashshft = 0; - let curshft = 0; - let idx = 0; - let i = 0; - for (i = 0; i < points.length - 1; i++) { - points[i + 1].subtractToRef(points[i], curvect); - lg += curvect.length(); - } - shft = lg / dashNb; - dashshft = (dashSize * shft) / (dashSize + gapSize); - for (i = 0; i < points.length - 1; i++) { - points[i + 1].subtractToRef(points[i], curvect); - nb = Math.floor(curvect.length() / shft); - curvect.normalize(); - for (let j = 0; j < nb; j++) { - curshft = shft * j; - positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z); - positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z); - indices.push(idx, idx + 1); - idx += 2; - } - } - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.positions = positions; - vertexData.indices = indices; - return vertexData; -} -/** - * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh - * * 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 - * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function - * * The parameter `lines` is an array of lines, each line being an array of successive Vector3 - * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter - * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point - * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster) - * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created - * * 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 - * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#line-system - * @param name defines the name of the new line system - * @param options defines the options used to create the line system - * @param options.lines - * @param options.updatable - * @param options.instance - * @param options.colors - * @param options.useVertexAlpha - * @param options.material - * @param scene defines the hosting scene - * @returns a new line system mesh - */ -function CreateLineSystem(name, options, scene = null) { - const instance = options.instance; - const lines = options.lines; - const colors = options.colors; - if (instance) { - // lines update - const positions = instance.getVerticesData(buffer_VertexBuffer.PositionKind); - let vertexColor; - let lineColors; - if (colors) { - vertexColor = instance.getVerticesData(buffer_VertexBuffer.ColorKind); - } - let i = 0; - let c = 0; - for (let l = 0; l < lines.length; l++) { - const points = lines[l]; - for (let p = 0; p < points.length; p++) { - positions[i] = points[p].x; - positions[i + 1] = points[p].y; - positions[i + 2] = points[p].z; - if (colors && vertexColor) { - lineColors = colors[l]; - vertexColor[c] = lineColors[p].r; - vertexColor[c + 1] = lineColors[p].g; - vertexColor[c + 2] = lineColors[p].b; - vertexColor[c + 3] = lineColors[p].a; - c += 4; - } - i += 3; - } - } - instance.updateVerticesData(buffer_VertexBuffer.PositionKind, positions, false, false); - if (colors && vertexColor) { - instance.updateVerticesData(buffer_VertexBuffer.ColorKind, vertexColor, false, false); - } - return instance; - } - // line system creation - const useVertexColor = colors ? true : false; - const lineSystem = new LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha, options.material); - const vertexData = CreateLineSystemVertexData(options); - vertexData.applyToMesh(lineSystem, options.updatable); - return lineSystem; -} -/** - * Creates a line mesh - * 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 - * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function - * * The parameter `points` is an array successive Vector3 - * * 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 - * * The optional parameter `colors` is an array of successive Color4, one per line point - * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster) - * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created - * * When updating an instance, remember that only point positions can change, not the number of points - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#lines - * @param name defines the name of the new line system - * @param options defines the options used to create the line system - * @param options.points - * @param options.updatable - * @param options.instance - * @param options.colors - * @param options.useVertexAlpha - * @param options.material - * @param scene defines the hosting scene - * @returns a new line mesh - */ -function linesBuilder_CreateLines(name, options, scene = null) { - const colors = options.colors ? [options.colors] : null; - const lines = CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha, material: options.material }, scene); - return lines; -} -/** - * Creates a dashed line mesh - * * 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 - * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function - * * The parameter `points` is an array successive Vector3 - * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200) - * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3) - * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1) - * * 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 - * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster) - * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created - * * When updating an instance, remember that only point positions can change, not the number of points - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.points - * @param options.dashSize - * @param options.gapSize - * @param options.dashNb - * @param options.updatable - * @param options.instance - * @param options.useVertexAlpha - * @param options.material - * @param scene defines the hosting scene - * @returns the dashed line mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#dashed-lines - */ -function CreateDashedLines(name, options, scene = null) { - const points = options.points; - const instance = options.instance; - const gapSize = options.gapSize || 1; - const dashSize = options.dashSize || 3; - if (instance) { - // dashed lines update - const positionFunction = (positions) => { - const curvect = math_vector_Vector3.Zero(); - const nbSeg = positions.length / 6; - let lg = 0; - let nb = 0; - let shft = 0; - let dashshft = 0; - let curshft = 0; - let p = 0; - let i = 0; - let j = 0; - for (i = 0; i < points.length - 1; i++) { - points[i + 1].subtractToRef(points[i], curvect); - lg += curvect.length(); - } - shft = lg / nbSeg; - const dashSize = instance._creationDataStorage.dashSize; - const gapSize = instance._creationDataStorage.gapSize; - dashshft = (dashSize * shft) / (dashSize + gapSize); - for (i = 0; i < points.length - 1; i++) { - points[i + 1].subtractToRef(points[i], curvect); - nb = Math.floor(curvect.length() / shft); - curvect.normalize(); - j = 0; - while (j < nb && p < positions.length) { - curshft = shft * j; - positions[p] = points[i].x + curshft * curvect.x; - positions[p + 1] = points[i].y + curshft * curvect.y; - positions[p + 2] = points[i].z + curshft * curvect.z; - positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x; - positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y; - positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z; - p += 6; - j++; - } - } - while (p < positions.length) { - positions[p] = points[i].x; - positions[p + 1] = points[i].y; - positions[p + 2] = points[i].z; - p += 3; - } - }; - if (options.dashNb || options.dashSize || options.gapSize || options.useVertexAlpha || options.material) { - logger_Logger.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."); - } - instance.updateMeshPositions(positionFunction, false); - return instance; - } - // dashed lines creation - const dashedLines = new LinesMesh(name, scene, null, undefined, undefined, undefined, options.useVertexAlpha, options.material); - const vertexData = CreateDashedLinesVertexData(options); - vertexData.applyToMesh(dashedLines, options.updatable); - dashedLines._creationDataStorage = new _CreationDataStorage(); - dashedLines._creationDataStorage.dashSize = dashSize; - dashedLines._creationDataStorage.gapSize = gapSize; - return dashedLines; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use the functions directly from the module - */ -const LinesBuilder = { - CreateDashedLines, - CreateLineSystem, - CreateLines: linesBuilder_CreateLines, -}; -mesh_vertexData_VertexData.CreateLineSystem = CreateLineSystemVertexData; -mesh_vertexData_VertexData.CreateDashedLines = CreateDashedLinesVertexData; -mesh_Mesh.CreateLines = (name, points, scene = null, updatable = false, instance = null) => { - const options = { - points, - updatable, - instance, - }; - return linesBuilder_CreateLines(name, options, scene); -}; -mesh_Mesh.CreateDashedLines = (name, points, dashSize, gapSize, dashNb, scene = null, updatable, instance) => { - const options = { - points, - dashSize, - gapSize, - dashNb, - updatable, - instance, - }; - return CreateDashedLines(name, options, scene); -}; -//# sourceMappingURL=linesBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/polygonMesh.js - - - - - - - - -/** - * Vector2 wth index property - */ -class IndexedVector2 extends math_vector_Vector2 { - constructor(original, - /** Index of the vector2 */ - index) { - super(original.x, original.y); - this.index = index; - } -} -/** - * Defines points to create a polygon - */ -class PolygonPoints { - constructor() { - this.elements = new Array(); - } - add(originalPoints) { - const result = new Array(); - originalPoints.forEach((point) => { - const newPoint = new IndexedVector2(point, this.elements.length); - result.push(newPoint); - this.elements.push(newPoint); - }); - return result; - } - computeBounds() { - const lmin = new math_vector_Vector2(this.elements[0].x, this.elements[0].y); - const lmax = new math_vector_Vector2(this.elements[0].x, this.elements[0].y); - this.elements.forEach((point) => { - // x - if (point.x < lmin.x) { - lmin.x = point.x; - } - else if (point.x > lmax.x) { - lmax.x = point.x; - } - // y - if (point.y < lmin.y) { - lmin.y = point.y; - } - else if (point.y > lmax.y) { - lmax.y = point.y; - } - }); - return { - min: lmin, - max: lmax, - width: lmax.x - lmin.x, - height: lmax.y - lmin.y, - }; - } -} -/** - * Polygon - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#non-regular-polygon - */ -class Polygon { - /** - * Creates a rectangle - * @param xmin bottom X coord - * @param ymin bottom Y coord - * @param xmax top X coord - * @param ymax top Y coord - * @returns points that make the resulting rectangle - */ - static Rectangle(xmin, ymin, xmax, ymax) { - return [new Vector2(xmin, ymin), new Vector2(xmax, ymin), new Vector2(xmax, ymax), new Vector2(xmin, ymax)]; - } - /** - * Creates a circle - * @param radius radius of circle - * @param cx scale in x - * @param cy scale in y - * @param numberOfSides number of sides that make up the circle - * @returns points that make the resulting circle - */ - static Circle(radius, cx = 0, cy = 0, numberOfSides = 32) { - const result = new Array(); - let angle = 0; - const increment = (Math.PI * 2) / numberOfSides; - for (let i = 0; i < numberOfSides; i++) { - result.push(new Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius)); - angle -= increment; - } - return result; - } - /** - * Creates a polygon from input string - * @param input Input polygon data - * @returns the parsed points - */ - static Parse(input) { - const floats = input - .split(/[^-+eE.\d]+/) - .map(parseFloat) - .filter((val) => !isNaN(val)); - let i; - const result = []; - for (i = 0; i < (floats.length & 0x7ffffffe); i += 2) { - result.push(new Vector2(floats[i], floats[i + 1])); - } - return result; - } - /** - * Starts building a polygon from x and y coordinates - * @param x x coordinate - * @param y y coordinate - * @returns the started path2 - */ - static StartingAt(x, y) { - return Path2.StartingAt(x, y); - } -} -/** - * Builds a polygon - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/polyMeshBuilder - */ -class PolygonMeshBuilder { - _addToepoint(points) { - for (const p of points) { - this._epoints.push(p.x, p.y); - } - } - /** - * Creates a PolygonMeshBuilder - * @param name name of the builder - * @param contours Path of the polygon - * @param scene scene to add to when creating the mesh - * @param earcutInjection can be used to inject your own earcut reference - */ - constructor(name, contours, scene, earcutInjection = earcut) { - this._points = new PolygonPoints(); - this._outlinepoints = new PolygonPoints(); - this._holes = new Array(); - this._epoints = new Array(); - this._eholes = new Array(); - this.bjsEarcut = earcutInjection; - this._name = name; - this._scene = scene || engineStore_EngineStore.LastCreatedScene; - let points; - if (contours instanceof math_path_Path2) { - points = contours.getPoints(); - } - else { - points = contours; - } - this._addToepoint(points); - this._points.add(points); - this._outlinepoints.add(points); - if (typeof this.bjsEarcut === "undefined") { - logger_Logger.Warn("Earcut was not found, the polygon will not be built."); - } - } - /** - * Adds a hole within the polygon - * @param hole Array of points defining the hole - * @returns this - */ - addHole(hole) { - this._points.add(hole); - const holepoints = new PolygonPoints(); - holepoints.add(hole); - this._holes.push(holepoints); - this._eholes.push(this._epoints.length / 2); - this._addToepoint(hole); - return this; - } - /** - * Creates the polygon - * @param updatable If the mesh should be updatable - * @param depth The depth of the mesh created - * @param smoothingThreshold Dot product threshold for smoothed normals - * @returns the created mesh - */ - build(updatable = false, depth = 0, smoothingThreshold = 2) { - const result = new mesh_Mesh(this._name, this._scene); - const vertexData = this.buildVertexData(depth, smoothingThreshold); - result.setVerticesData(buffer_VertexBuffer.PositionKind, vertexData.positions, updatable); - result.setVerticesData(buffer_VertexBuffer.NormalKind, vertexData.normals, updatable); - result.setVerticesData(buffer_VertexBuffer.UVKind, vertexData.uvs, updatable); - result.setIndices(vertexData.indices); - return result; - } - /** - * Creates the polygon - * @param depth The depth of the mesh created - * @param smoothingThreshold Dot product threshold for smoothed normals - * @returns the created VertexData - */ - buildVertexData(depth = 0, smoothingThreshold = 2) { - const result = new mesh_vertexData_VertexData(); - const normals = new Array(); - const positions = new Array(); - const uvs = new Array(); - const bounds = this._points.computeBounds(); - this._points.elements.forEach((p) => { - normals.push(0, 1.0, 0); - positions.push(p.x, 0, p.y); - uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height); - }); - const indices = new Array(); - const res = this.bjsEarcut(this._epoints, this._eholes, 2); - for (let i = 0; i < res.length; i++) { - indices.push(res[i]); - } - if (depth > 0) { - const positionscount = positions.length / 3; //get the current pointcount - this._points.elements.forEach((p) => { - //add the elements at the depth - normals.push(0, -1.0, 0); - positions.push(p.x, -depth, p.y); - uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height); - }); - const totalCount = indices.length; - for (let i = 0; i < totalCount; i += 3) { - const i0 = indices[i + 0]; - const i1 = indices[i + 1]; - const i2 = indices[i + 2]; - indices.push(i2 + positionscount); - indices.push(i1 + positionscount); - indices.push(i0 + positionscount); - } - //Add the sides - this._addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false, smoothingThreshold); - this._holes.forEach((hole) => { - this._addSide(positions, normals, uvs, indices, bounds, hole, depth, true, smoothingThreshold); - }); - } - result.indices = indices; - result.positions = positions; - result.normals = normals; - result.uvs = uvs; - return result; - } - /** - * Adds a side to the polygon - * @param positions points that make the polygon - * @param normals normals of the polygon - * @param uvs uvs of the polygon - * @param indices indices of the polygon - * @param bounds bounds of the polygon - * @param points points of the polygon - * @param depth depth of the polygon - * @param flip flip of the polygon - * @param smoothingThreshold - */ - _addSide(positions, normals, uvs, indices, bounds, points, depth, flip, smoothingThreshold) { - let startIndex = positions.length / 3; - let ulength = 0; - for (let i = 0; i < points.elements.length; i++) { - const p = points.elements[i]; - const p1 = points.elements[(i + 1) % points.elements.length]; - positions.push(p.x, 0, p.y); - positions.push(p.x, -depth, p.y); - positions.push(p1.x, 0, p1.y); - positions.push(p1.x, -depth, p1.y); - const p0 = points.elements[(i + points.elements.length - 1) % points.elements.length]; - const p2 = points.elements[(i + 2) % points.elements.length]; - let vc = new math_vector_Vector3(-(p1.y - p.y), 0, p1.x - p.x); - let vp = new math_vector_Vector3(-(p.y - p0.y), 0, p.x - p0.x); - let vn = new math_vector_Vector3(-(p2.y - p1.y), 0, p2.x - p1.x); - if (!flip) { - vc = vc.scale(-1); - vp = vp.scale(-1); - vn = vn.scale(-1); - } - const vc_norm = vc.normalizeToNew(); - let vp_norm = vp.normalizeToNew(); - let vn_norm = vn.normalizeToNew(); - const dotp = math_vector_Vector3.Dot(vp_norm, vc_norm); - if (dotp > smoothingThreshold) { - if (dotp < math_constants_Epsilon - 1) { - vp_norm = new math_vector_Vector3(p.x, 0, p.y).subtract(new math_vector_Vector3(p1.x, 0, p1.y)).normalize(); - } - else { - // cheap average weighed by side length - vp_norm = vp.add(vc).normalize(); - } - } - else { - vp_norm = vc_norm; - } - const dotn = math_vector_Vector3.Dot(vn, vc); - if (dotn > smoothingThreshold) { - if (dotn < math_constants_Epsilon - 1) { - // back to back - vn_norm = new math_vector_Vector3(p1.x, 0, p1.y).subtract(new math_vector_Vector3(p.x, 0, p.y)).normalize(); - } - else { - // cheap average weighed by side length - vn_norm = vn.add(vc).normalize(); - } - } - else { - vn_norm = vc_norm; - } - uvs.push(ulength / bounds.width, 0); - uvs.push(ulength / bounds.width, 1); - ulength += vc.length(); - uvs.push(ulength / bounds.width, 0); - uvs.push(ulength / bounds.width, 1); - normals.push(vp_norm.x, vp_norm.y, vp_norm.z); - normals.push(vp_norm.x, vp_norm.y, vp_norm.z); - normals.push(vn_norm.x, vn_norm.y, vn_norm.z); - normals.push(vn_norm.x, vn_norm.y, vn_norm.z); - if (!flip) { - indices.push(startIndex); - indices.push(startIndex + 1); - indices.push(startIndex + 2); - indices.push(startIndex + 1); - indices.push(startIndex + 3); - indices.push(startIndex + 2); - } - else { - indices.push(startIndex); - indices.push(startIndex + 2); - indices.push(startIndex + 1); - indices.push(startIndex + 1); - indices.push(startIndex + 2); - indices.push(startIndex + 3); - } - startIndex += 4; - } - } -} -//# sourceMappingURL=polygonMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/polygonBuilder.js - - - - - - - - -/** - * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build() - * All parameters are provided by CreatePolygon as needed - * @param polygon a mesh built from polygonTriangulation.build() - * @param sideOrientation takes the values Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * @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) - * @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) - * @param wrp a boolean, default false, when true and fUVs used texture is wrapped around all sides, when false texture is applied side - * @returns the VertexData of the Polygon - */ -function CreatePolygonVertexData(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrp) { - const faceUV = fUV || new Array(3); - const faceColors = fColors; - const colors = []; - const wrap = wrp || false; - // default face colors and UV if undefined - for (let f = 0; f < 3; f++) { - if (faceUV[f] === undefined) { - faceUV[f] = new math_vector_Vector4(0, 0, 1, 1); - } - if (faceColors && faceColors[f] === undefined) { - faceColors[f] = new math_color_Color4(1, 1, 1, 1); - } - } - const positions = polygon.getVerticesData(buffer_VertexBuffer.PositionKind); - const normals = polygon.getVerticesData(buffer_VertexBuffer.NormalKind); - const uvs = polygon.getVerticesData(buffer_VertexBuffer.UVKind); - const indices = polygon.getIndices(); - const startIndex = positions.length / 9; - let disp = 0; - let distX = 0; - let distZ = 0; - let dist = 0; - let totalLen = 0; - const cumulate = [0]; - if (wrap) { - for (let idx = startIndex; idx < positions.length / 3; idx += 4) { - distX = positions[3 * (idx + 2)] - positions[3 * idx]; - distZ = positions[3 * (idx + 2) + 2] - positions[3 * idx + 2]; - dist = Math.sqrt(distX * distX + distZ * distZ); - totalLen += dist; - cumulate.push(totalLen); - } - } - // set face colours and textures - let idx = 0; - let face = 0; - for (let index = 0; index < normals.length; index += 3) { - //Edge Face no. 1 - if (Math.abs(normals[index + 1]) < 0.001) { - face = 1; - } - //Top Face no. 0 - if (Math.abs(normals[index + 1] - 1) < 0.001) { - face = 0; - } - //Bottom Face no. 2 - if (Math.abs(normals[index + 1] + 1) < 0.001) { - face = 2; - } - idx = index / 3; - if (face === 1) { - disp = idx - startIndex; - if (disp % 4 < 1.5) { - if (wrap) { - uvs[2 * idx] = faceUV[face].x + ((faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4)]) / totalLen; - } - else { - uvs[2 * idx] = faceUV[face].x; - } - } - else { - if (wrap) { - uvs[2 * idx] = faceUV[face].x + ((faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4) + 1]) / totalLen; - } - else { - uvs[2 * idx] = faceUV[face].z; - } - } - if (disp % 2 === 0) { - uvs[2 * idx + 1] = CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[face].w : faceUV[face].w; - } - else { - uvs[2 * idx + 1] = CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[face].y : faceUV[face].y; - } - } - else { - uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z; - uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w; - if (CompatibilityOptions.UseOpenGLOrientationForUV) { - uvs[2 * idx + 1] = 1.0 - uvs[2 * idx + 1]; - } - } - if (faceColors) { - colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a); - } - } - // sides - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs); - // Result - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.normals = normals; - vertexData.uvs = uvs; - if (faceColors) { - const totalColors = sideOrientation === mesh_vertexData_VertexData.DOUBLESIDE ? colors.concat(colors) : colors; - vertexData.colors = totalColors; - } - return vertexData; -} -/** - * Creates a polygon mesh - * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh - * * 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 - * * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * * 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) - * * Remember you can only change the shape positions, not their number when updating a polygon - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.shape - * @param options.holes - * @param options.depth - * @param options.smoothingThreshold - * @param options.faceUV - * @param options.faceColors - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.wrap - * @param scene defines the hosting scene - * @param earcutInjection can be used to inject your own earcut reference - * @returns the polygon mesh - */ -function CreatePolygon(name, options, scene = null, earcutInjection = earcut) { - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - const shape = options.shape; - const holes = options.holes || []; - const depth = options.depth || 0; - const smoothingThreshold = options.smoothingThreshold || 2; - const contours = []; - let hole = []; - for (let i = 0; i < shape.length; i++) { - contours[i] = new math_vector_Vector2(shape[i].x, shape[i].z); - } - const epsilon = 0.00000001; - if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) { - contours.pop(); - } - const polygonTriangulation = new PolygonMeshBuilder(name, contours, scene || engineStore_EngineStore.LastCreatedScene, earcutInjection); - for (let hNb = 0; hNb < holes.length; hNb++) { - hole = []; - for (let hPoint = 0; hPoint < holes[hNb].length; hPoint++) { - hole.push(new math_vector_Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z)); - } - polygonTriangulation.addHole(hole); - } - //updatability is set during applyToMesh; setting to true in triangulation build produces errors - const polygon = polygonTriangulation.build(false, depth, smoothingThreshold); - polygon._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreatePolygonVertexData(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs, options.wrap); - vertexData.applyToMesh(polygon, options.updatable); - return polygon; -} -/** - * Creates an extruded polygon mesh, with depth in the Y direction. - * * 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) - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.shape - * @param options.holes - * @param options.depth - * @param options.faceUV - * @param options.faceColors - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.wrap - * @param scene defines the hosting scene - * @param earcutInjection can be used to inject your own earcut reference - * @returns the polygon mesh - */ -function ExtrudePolygon(name, options, scene = null, earcutInjection = earcut) { - return CreatePolygon(name, options, scene, earcutInjection); -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use the functions directly from the module - */ -const PolygonBuilder = { - ExtrudePolygon, - CreatePolygon, -}; -mesh_vertexData_VertexData.CreatePolygon = CreatePolygonVertexData; -mesh_Mesh.CreatePolygon = (name, shape, scene, holes, updatable, sideOrientation, earcutInjection = earcut) => { - const options = { - shape: shape, - holes: holes, - updatable: updatable, - sideOrientation: sideOrientation, - }; - return CreatePolygon(name, options, scene, earcutInjection); -}; -mesh_Mesh.ExtrudePolygon = (name, shape, depth, scene, holes, updatable, sideOrientation, earcutInjection = earcut) => { - const options = { - shape: shape, - holes: holes, - depth: depth, - updatable: updatable, - sideOrientation: sideOrientation, - }; - return ExtrudePolygon(name, options, scene, earcutInjection); -}; -//# sourceMappingURL=polygonBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/shapeBuilder.js - - - - -/** - * 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. - * * 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. - * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. - * * 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. - * * The parameter `scale` (float, default 1) is the value to scale the shape. - * * The parameter `closeShape` (boolean, default false) closes the shape when true, since v5.0.0. - * * The parameter `closePath` (boolean, default false) closes the path when true and no caps, since v5.0.0. - * * 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 - * * 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 - * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. - * * 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 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. - * * 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. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.shape - * @param options.path - * @param options.scale - * @param options.rotation - * @param options.closeShape - * @param options.closePath - * @param options.cap - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.instance - * @param options.invertUV - * @param options.firstNormal - * @param options.adjustFrame - * @param scene defines the hosting scene - * @returns the extruded shape mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes - */ -function ExtrudeShape(name, options, scene = null) { - const path = options.path; - const shape = options.shape; - const scale = options.scale || 1; - const rotation = options.rotation || 0; - const cap = options.cap === 0 ? 0 : options.cap || mesh_Mesh.NO_CAP; - const updatable = options.updatable; - const sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - const instance = options.instance || null; - const invertUV = options.invertUV || false; - const closeShape = options.closeShape || false; - const closePath = options.closePath || false; - 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); -} -/** - * Creates an custom extruded shape mesh. - * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. - * * 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. - * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. - * * 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 - * * It must returns a float value that will be the rotation in radians applied to the shape on each path point. - * * 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 - * * It must returns a float value that will be the scale value applied to the shape on each path point - * * The parameter `closeShape` (boolean, default false) closes the shape when true, since v5.0.0. - * * The parameter `closePath` (boolean, default false) closes the path when true and no caps, since v5.0.0. - * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray` - depreciated in favor of closeShape - * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray` - depreciated in favor of closePath - * * 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 - * * 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 - * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * 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 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. - * * 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. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.shape - * @param options.path - * @param options.scaleFunction - * @param options.rotationFunction - * @param options.ribbonCloseArray - * @param options.ribbonClosePath - * @param options.closeShape - * @param options.closePath - * @param options.cap - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.instance - * @param options.invertUV - * @param options.firstNormal - * @param options.adjustFrame - * @param scene defines the hosting scene - * @returns the custom extruded shape mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#custom-extruded-shapes - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes - */ -function ExtrudeShapeCustom(name, options, scene = null) { - const path = options.path; - const shape = options.shape; - const scaleFunction = options.scaleFunction || - (() => { - return 1; - }); - const rotationFunction = options.rotationFunction || - (() => { - return 0; - }); - const ribbonCloseArray = options.closePath || options.ribbonCloseArray || false; - const ribbonClosePath = options.closeShape || options.ribbonClosePath || false; - const cap = options.cap === 0 ? 0 : options.cap || mesh_Mesh.NO_CAP; - const updatable = options.updatable; - const firstNormal = options.firstNormal || null; - const adjustFrame = options.adjustFrame || false; - const sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - const instance = options.instance; - const invertUV = options.invertUV || false; - 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); -} -function _ExtrudeShapeGeneric(name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs, firstNormal, adjustFrame) { - // extrusion geometry - const extrusionPathArray = (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom, adjustFrame) => { - const tangents = path3D.getTangents(); - const normals = path3D.getNormals(); - const binormals = path3D.getBinormals(); - const distances = path3D.getDistances(); - if (adjustFrame) { - /* fix tangents,normals, binormals */ - for (let i = 0; i < tangents.length; i++) { - if (tangents[i].x == 0 && tangents[i].y == 0 && tangents[i].z == 0) { - tangents[i].copyFrom(tangents[i - 1]); - } - if (normals[i].x == 0 && normals[i].y == 0 && normals[i].z == 0) { - normals[i].copyFrom(normals[i - 1]); - } - if (binormals[i].x == 0 && binormals[i].y == 0 && binormals[i].z == 0) { - binormals[i].copyFrom(binormals[i - 1]); - } - if (i > 0) { - let v = tangents[i - 1]; - if (math_vector_Vector3.Dot(v, tangents[i]) < 0) { - tangents[i].scaleInPlace(-1); - } - v = normals[i - 1]; - if (math_vector_Vector3.Dot(v, normals[i]) < 0) { - normals[i].scaleInPlace(-1); - } - v = binormals[i - 1]; - if (math_vector_Vector3.Dot(v, binormals[i]) < 0) { - binormals[i].scaleInPlace(-1); - } - } - } - } - let angle = 0; - const returnScale = () => { - return scale !== null ? scale : 1; - }; - const returnRotation = () => { - return rotation !== null ? rotation : 0; - }; - const rotate = custom && rotateFunction ? rotateFunction : returnRotation; - const scl = custom && scaleFunction ? scaleFunction : returnScale; - let index = cap === mesh_Mesh.NO_CAP || cap === mesh_Mesh.CAP_END ? 0 : 2; - const rotationMatrix = math_vector_TmpVectors.Matrix[0]; - for (let i = 0; i < curve.length; i++) { - const shapePath = new Array(); - const angleStep = rotate(i, distances[i]); - const scaleRatio = scl(i, distances[i]); - math_vector_Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix); - for (let p = 0; p < shape.length; p++) { - const planed = tangents[i].scale(shape[p].z).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)); - const rotated = math_vector_Vector3.Zero(); - math_vector_Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated); - rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]); - shapePath[p] = rotated; - } - shapePaths[index] = shapePath; - angle += angleStep; - index++; - } - // cap - const capPath = (shapePath) => { - const pointCap = Array(); - const barycenter = math_vector_Vector3.Zero(); - let i; - for (i = 0; i < shapePath.length; i++) { - barycenter.addInPlace(shapePath[i]); - } - barycenter.scaleInPlace(1.0 / shapePath.length); - for (i = 0; i < shapePath.length; i++) { - pointCap.push(barycenter); - } - return pointCap; - }; - switch (cap) { - case mesh_Mesh.NO_CAP: - break; - case mesh_Mesh.CAP_START: - shapePaths[0] = capPath(shapePaths[2]); - shapePaths[1] = shapePaths[2]; - break; - case mesh_Mesh.CAP_END: - shapePaths[index] = shapePaths[index - 1]; - shapePaths[index + 1] = capPath(shapePaths[index - 1]); - break; - case mesh_Mesh.CAP_ALL: - shapePaths[0] = capPath(shapePaths[2]); - shapePaths[1] = shapePaths[2]; - shapePaths[index] = shapePaths[index - 1]; - shapePaths[index + 1] = capPath(shapePaths[index - 1]); - break; - default: - break; - } - return shapePaths; - }; - let path3D; - let pathArray; - if (instance) { - // instance update - const storage = instance._creationDataStorage; - path3D = firstNormal ? storage.path3D.update(curve, firstNormal) : storage.path3D.update(curve); - pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom, adjustFrame); - instance = CreateRibbon("", { pathArray, closeArray: false, closePath: false, offset: 0, updatable: false, sideOrientation: 0, instance }, scene || undefined); - return instance; - } - // extruded shape creation - path3D = firstNormal ? new Path3D(curve, firstNormal) : new Path3D(curve); - const newShapePaths = new Array(); - cap = cap < 0 || cap > 3 ? 0 : cap; - pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom, adjustFrame); - const extrudedGeneric = CreateRibbon(name, { - pathArray: pathArray, - closeArray: rbCA, - closePath: rbCP, - updatable: updtbl, - sideOrientation: side, - invertUV: invertUV, - frontUVs: frontUVs || undefined, - backUVs: backUVs || undefined, - }, scene); - extrudedGeneric._creationDataStorage.pathArray = pathArray; - extrudedGeneric._creationDataStorage.path3D = path3D; - extrudedGeneric._creationDataStorage.cap = cap; - return extrudedGeneric; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated please use the functions directly from the module - */ -const ShapeBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - ExtrudeShape, - // eslint-disable-next-line @typescript-eslint/naming-convention - ExtrudeShapeCustom, -}; -mesh_Mesh.ExtrudeShape = (name, shape, path, scale, rotation, cap, scene = null, updatable, sideOrientation, instance) => { - const options = { - shape: shape, - path: path, - scale: scale, - rotation: rotation, - cap: cap === 0 ? 0 : cap || mesh_Mesh.NO_CAP, - sideOrientation: sideOrientation, - instance: instance, - updatable: updatable, - }; - return ExtrudeShape(name, options, scene); -}; -mesh_Mesh.ExtrudeShapeCustom = (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) => { - const options = { - shape: shape, - path: path, - scaleFunction: scaleFunction, - rotationFunction: rotationFunction, - ribbonCloseArray: ribbonCloseArray, - ribbonClosePath: ribbonClosePath, - cap: cap === 0 ? 0 : cap || mesh_Mesh.NO_CAP, - sideOrientation: sideOrientation, - instance: instance, - updatable: updatable, - }; - return ExtrudeShapeCustom(name, options, scene); -}; -//# sourceMappingURL=shapeBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/latheBuilder.js - - - -/** - * Creates lathe mesh. - * The lathe is a shape with a symmetry axis : a 2D model shape is rotated around this axis to design the lathe - * * 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 - * * The parameter `radius` (positive float, default 1) is the radius value of the lathe - * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe - * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides - * * 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 - * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc" - * * 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 - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.shape - * @param options.radius - * @param options.tessellation - * @param options.clip - * @param options.arc - * @param options.closed - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.cap - * @param options.invertUV - * @param scene defines the hosting scene - * @returns the lathe mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#lathe - */ -function CreateLathe(name, options, scene = null) { - const arc = options.arc ? (options.arc <= 0 || options.arc > 1 ? 1.0 : options.arc) : 1.0; - const closed = options.closed === undefined ? true : options.closed; - const shape = options.shape; - const radius = options.radius || 1; - const tessellation = options.tessellation || 64; - const clip = options.clip || 0; - const updatable = options.updatable; - const sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - const cap = options.cap || mesh_Mesh.NO_CAP; - const pi2 = Math.PI * 2; - const paths = new Array(); - const invertUV = options.invertUV || false; - let i = 0; - let p = 0; - const step = (pi2 / tessellation) * arc; - let rotated; - let path; - for (i = 0; i <= tessellation - clip; i++) { - path = []; - if (cap == mesh_Mesh.CAP_START || cap == mesh_Mesh.CAP_ALL) { - path.push(new math_vector_Vector3(0, shape[0].y, 0)); - path.push(new math_vector_Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius)); - } - for (p = 0; p < shape.length; p++) { - rotated = new math_vector_Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius); - path.push(rotated); - } - if (cap == mesh_Mesh.CAP_END || cap == mesh_Mesh.CAP_ALL) { - path.push(new math_vector_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)); - path.push(new math_vector_Vector3(0, shape[shape.length - 1].y, 0)); - } - paths.push(path); - } - // lathe ribbon - const lathe = CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene); - return lathe; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use the function direction from the module - */ -const LatheBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateLathe, -}; -mesh_Mesh.CreateLathe = (name, shape, radius, tessellation, scene, updatable, sideOrientation) => { - const options = { - shape: shape, - radius: radius, - tessellation: tessellation, - sideOrientation: sideOrientation, - updatable: updatable, - }; - return CreateLathe(name, options, scene); -}; -//# sourceMappingURL=latheBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/tubeBuilder.js - - - - -/** - * Creates a tube mesh. - * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters - * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube - * * The parameter `radius` (positive float, default 1) sets the tube radius size - * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface - * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overrides the parameter `radius` - * * 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) - * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc - * * 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 - * * 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 - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture - * * 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. - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.path - * @param options.radius - * @param options.tessellation - * @param options.radiusFunction - * @param options.cap - * @param options.arc - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.instance - * @param options.invertUV - * @param scene defines the hosting scene - * @returns the tube mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#tube - */ -function CreateTube(name, options, scene = null) { - const path = options.path; - let instance = options.instance; - let radius = 1.0; - if (options.radius !== undefined) { - radius = options.radius; - } - else if (instance) { - radius = instance._creationDataStorage.radius; - } - const tessellation = options.tessellation || 64 | 0; - const radiusFunction = options.radiusFunction || null; - let cap = options.cap || mesh_Mesh.NO_CAP; - const invertUV = options.invertUV || false; - const updatable = options.updatable; - const sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0; - // tube geometry - const tubePathArray = (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) => { - const tangents = path3D.getTangents(); - const normals = path3D.getNormals(); - const distances = path3D.getDistances(); - const pi2 = Math.PI * 2; - const step = (pi2 / tessellation) * arc; - const returnRadius = () => radius; - const radiusFunctionFinal = radiusFunction || returnRadius; - let circlePath; - let rad; - let normal; - let rotated; - const rotationMatrix = math_vector_TmpVectors.Matrix[0]; - let index = cap === mesh_Mesh.NO_CAP || cap === mesh_Mesh.CAP_END ? 0 : 2; - for (let i = 0; i < path.length; i++) { - rad = radiusFunctionFinal(i, distances[i]); // current radius - circlePath = Array(); // current circle array - normal = normals[i]; // current normal - for (let t = 0; t < tessellation; t++) { - math_vector_Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix); - rotated = circlePath[t] ? circlePath[t] : math_vector_Vector3.Zero(); - math_vector_Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated); - rotated.scaleInPlace(rad).addInPlace(path[i]); - circlePath[t] = rotated; - } - circlePaths[index] = circlePath; - index++; - } - // cap - const capPath = (nbPoints, pathIndex) => { - const pointCap = Array(); - for (let i = 0; i < nbPoints; i++) { - pointCap.push(path[pathIndex]); - } - return pointCap; - }; - switch (cap) { - case mesh_Mesh.NO_CAP: - break; - case mesh_Mesh.CAP_START: - circlePaths[0] = capPath(tessellation, 0); - circlePaths[1] = circlePaths[2].slice(0); - break; - case mesh_Mesh.CAP_END: - circlePaths[index] = circlePaths[index - 1].slice(0); - circlePaths[index + 1] = capPath(tessellation, path.length - 1); - break; - case mesh_Mesh.CAP_ALL: - circlePaths[0] = capPath(tessellation, 0); - circlePaths[1] = circlePaths[2].slice(0); - circlePaths[index] = circlePaths[index - 1].slice(0); - circlePaths[index + 1] = capPath(tessellation, path.length - 1); - break; - default: - break; - } - return circlePaths; - }; - let path3D; - let pathArray; - if (instance) { - // tube update - const storage = instance._creationDataStorage; - const arc = options.arc || storage.arc; - path3D = storage.path3D.update(path); - pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc); - instance = CreateRibbon("", { pathArray: pathArray, instance: instance }); - // Update mode, no need to recreate the storage. - storage.path3D = path3D; - storage.pathArray = pathArray; - storage.arc = arc; - storage.radius = radius; - return instance; - } - // tube creation - path3D = new Path3D(path); - const newPathArray = new Array(); - cap = cap < 0 || cap > 3 ? 0 : cap; - pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc); - const tube = CreateRibbon(name, { - pathArray: pathArray, - closePath: true, - closeArray: false, - updatable: updatable, - sideOrientation: sideOrientation, - invertUV: invertUV, - frontUVs: options.frontUVs, - backUVs: options.backUVs, - }, scene); - tube._creationDataStorage.pathArray = pathArray; - tube._creationDataStorage.path3D = path3D; - tube._creationDataStorage.tessellation = tessellation; - tube._creationDataStorage.cap = cap; - tube._creationDataStorage.arc = options.arc; - tube._creationDataStorage.radius = radius; - return tube; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use CreateTube directly - */ -const TubeBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateTube, -}; -mesh_Mesh.CreateTube = (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) => { - const options = { - path: path, - radius: radius, - tessellation: tessellation, - radiusFunction: radiusFunction, - arc: 1, - cap: cap, - updatable: updatable, - sideOrientation: sideOrientation, - instance: instance, - }; - return CreateTube(name, options, scene); -}; -//# sourceMappingURL=tubeBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/polyhedronBuilder.js - - - - - -// inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html -/** - * Creates the VertexData for a Polyhedron - * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty - * * type provided types are: - * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) - * * 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) - * * size the size of the IcoSphere, optional default 1 - * * sizeX allows stretching in the x direction, optional, default size - * * sizeY allows stretching in the y direction, optional, default size - * * sizeZ allows stretching in the z direction, optional, default size - * * 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 - * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * * flat when true creates a flat shaded mesh, optional, default true - * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.type - * @param options.size - * @param options.sizeX - * @param options.sizeY - * @param options.sizeZ - * @param options.custom - * @param options.faceUV - * @param options.faceColors - * @param options.flat - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @returns the VertexData of the Polyhedron - */ -function CreatePolyhedronVertexData(options) { - // provided polyhedron types : - // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) - // 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) - const polyhedra = []; - polyhedra[0] = { - vertex: [ - [0, 0, 1.732051], - [1.632993, 0, -0.5773503], - [-0.8164966, 1.414214, -0.5773503], - [-0.8164966, -1.414214, -0.5773503], - ], - face: [ - [0, 1, 2], - [0, 2, 3], - [0, 3, 1], - [1, 3, 2], - ], - }; - polyhedra[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], - ], - }; - polyhedra[2] = { - vertex: [ - [0, 0, 1.070466], - [0.7136442, 0, 0.7978784], - [-0.3568221, 0.618034, 0.7978784], - [-0.3568221, -0.618034, 0.7978784], - [0.7978784, 0.618034, 0.3568221], - [0.7978784, -0.618034, 0.3568221], - [-0.9341724, 0.381966, 0.3568221], - [0.1362939, 1, 0.3568221], - [0.1362939, -1, 0.3568221], - [-0.9341724, -0.381966, 0.3568221], - [0.9341724, 0.381966, -0.3568221], - [0.9341724, -0.381966, -0.3568221], - [-0.7978784, 0.618034, -0.3568221], - [-0.1362939, 1, -0.3568221], - [-0.1362939, -1, -0.3568221], - [-0.7978784, -0.618034, -0.3568221], - [0.3568221, 0.618034, -0.7978784], - [0.3568221, -0.618034, -0.7978784], - [-0.7136442, 0, -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], - ], - }; - polyhedra[3] = { - vertex: [ - [0, 0, 1.175571], - [1.051462, 0, 0.5257311], - [0.3249197, 1, 0.5257311], - [-0.8506508, 0.618034, 0.5257311], - [-0.8506508, -0.618034, 0.5257311], - [0.3249197, -1, 0.5257311], - [0.8506508, 0.618034, -0.5257311], - [0.8506508, -0.618034, -0.5257311], - [-0.3249197, 1, -0.5257311], - [-1.051462, 0, -0.5257311], - [-0.3249197, -1, -0.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], - ], - }; - polyhedra[4] = { - vertex: [ - [0, 0, 1.070722], - [0.7148135, 0, 0.7971752], - [-0.104682, 0.7071068, 0.7971752], - [-0.6841528, 0.2071068, 0.7971752], - [-0.104682, -0.7071068, 0.7971752], - [0.6101315, 0.7071068, 0.5236279], - [1.04156, 0.2071068, 0.1367736], - [0.6101315, -0.7071068, 0.5236279], - [-0.3574067, 1, 0.1367736], - [-0.7888348, -0.5, 0.5236279], - [-0.9368776, 0.5, 0.1367736], - [-0.3574067, -1, 0.1367736], - [0.3574067, 1, -0.1367736], - [0.9368776, -0.5, -0.1367736], - [0.7888348, 0.5, -0.5236279], - [0.3574067, -1, -0.1367736], - [-0.6101315, 0.7071068, -0.5236279], - [-1.04156, -0.2071068, -0.1367736], - [-0.6101315, -0.7071068, -0.5236279], - [0.104682, 0.7071068, -0.7971752], - [0.6841528, -0.2071068, -0.7971752], - [0.104682, -0.7071068, -0.7971752], - [-0.7148135, 0, -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], - ], - }; - polyhedra[5] = { - vertex: [ - [0, 0, 1.322876], - [1.309307, 0, 0.1889822], - [-0.9819805, 0.8660254, 0.1889822], - [0.1636634, -1.299038, 0.1889822], - [0.3273268, 0.8660254, -0.9449112], - [-0.8183171, -0.4330127, -0.9449112], - ], - face: [ - [0, 3, 1], - [2, 4, 5], - [0, 1, 4, 2], - [0, 2, 5, 3], - [1, 3, 5, 4], - ], - }; - polyhedra[6] = { - vertex: [ - [0, 0, 1.159953], - [1.013464, 0, 0.5642542], - [-0.3501431, 0.9510565, 0.5642542], - [-0.7715208, -0.6571639, 0.5642542], - [0.6633206, 0.9510565, -0.03144481], - [0.8682979, -0.6571639, -0.3996071], - [-1.121664, 0.2938926, -0.03144481], - [-0.2348831, -1.063314, -0.3996071], - [0.5181548, 0.2938926, -0.9953061], - [-0.5850262, -0.112257, -0.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], - ], - }; - polyhedra[7] = { - vertex: [ - [0, 0, 1.118034], - [0.8944272, 0, 0.6708204], - [-0.2236068, 0.8660254, 0.6708204], - [-0.7826238, -0.4330127, 0.6708204], - [0.6708204, 0.8660254, 0.2236068], - [1.006231, -0.4330127, -0.2236068], - [-1.006231, 0.4330127, 0.2236068], - [-0.6708204, -0.8660254, -0.2236068], - [0.7826238, 0.4330127, -0.6708204], - [0.2236068, -0.8660254, -0.6708204], - [-0.8944272, 0, -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], - ], - }; - polyhedra[8] = { - vertex: [ - [-0.729665, 0.670121, 0.319155], - [-0.655235, -0.29213, -0.754096], - [-0.093922, -0.607123, 0.537818], - [0.702196, 0.595691, 0.485187], - [0.776626, -0.36656, -0.588064], - ], - face: [ - [1, 4, 2], - [0, 1, 2], - [3, 0, 2], - [4, 3, 2], - [4, 1, 0, 3], - ], - }; - polyhedra[9] = { - vertex: [ - [-0.868849, -0.100041, 0.61257], - [-0.329458, 0.976099, 0.28078], - [-0.26629, -0.013796, -0.477654], - [-0.13392, -1.034115, 0.229829], - [0.738834, 0.707117, -0.307018], - [0.859683, -0.535264, -0.338508], - ], - face: [ - [3, 0, 2], - [5, 3, 2], - [4, 5, 2], - [1, 4, 2], - [0, 1, 2], - [0, 3, 5, 4, 1], - ], - }; - polyhedra[10] = { - vertex: [ - [-0.610389, 0.243975, 0.531213], - [-0.187812, -0.48795, -0.664016], - [-0.187812, 0.9759, -0.664016], - [0.187812, -0.9759, 0.664016], - [0.798201, 0.243975, 0.132803], - ], - face: [ - [1, 3, 0], - [3, 4, 0], - [3, 1, 4], - [0, 2, 1], - [0, 4, 2], - [2, 4, 1], - ], - }; - polyhedra[11] = { - vertex: [ - [-1.028778, 0.392027, -0.048786], - [-0.640503, -0.646161, 0.621837], - [-0.125162, -0.395663, -0.540059], - [0.004683, 0.888447, -0.651988], - [0.125161, 0.395663, 0.540059], - [0.632925, -0.791376, 0.433102], - [1.031672, 0.157063, -0.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], - ], - }; - polyhedra[12] = { - vertex: [ - [-0.669867, 0.334933, -0.529576], - [-0.669867, 0.334933, 0.529577], - [-0.4043, 1.212901, 0], - [-0.334933, -0.669867, -0.529576], - [-0.334933, -0.669867, 0.529577], - [0.334933, 0.669867, -0.529576], - [0.334933, 0.669867, 0.529577], - [0.4043, -1.212901, 0], - [0.669867, -0.334933, -0.529576], - [0.669867, -0.334933, 0.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], - ], - }; - polyhedra[13] = { - vertex: [ - [-0.931836, 0.219976, -0.264632], - [-0.636706, 0.318353, 0.692816], - [-0.613483, -0.735083, -0.264632], - [-0.326545, 0.979634, 0], - [-0.318353, -0.636706, 0.692816], - [-0.159176, 0.477529, -0.856368], - [0.159176, -0.477529, -0.856368], - [0.318353, 0.636706, 0.692816], - [0.326545, -0.979634, 0], - [0.613482, 0.735082, -0.264632], - [0.636706, -0.318353, 0.692816], - [0.931835, -0.219977, -0.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], - ], - }; - polyhedra[14] = { - vertex: [ - [-0.93465, 0.300459, -0.271185], - [-0.838689, -0.260219, -0.516017], - [-0.711319, 0.717591, 0.128359], - [-0.710334, -0.156922, 0.080946], - [-0.599799, 0.556003, -0.725148], - [-0.503838, -0.004675, -0.969981], - [-0.487004, 0.26021, 0.48049], - [-0.460089, -0.750282, -0.512622], - [-0.376468, 0.973135, -0.325605], - [-0.331735, -0.646985, 0.084342], - [-0.254001, 0.831847, 0.530001], - [-0.125239, -0.494738, -0.966586], - [0.029622, 0.027949, 0.730817], - [0.056536, -0.982543, -0.262295], - [0.08085, 1.087391, 0.076037], - [0.125583, -0.532729, 0.485984], - [0.262625, 0.599586, 0.780328], - [0.391387, -0.726999, -0.716259], - [0.513854, -0.868287, 0.139347], - [0.597475, 0.85513, 0.326364], - [0.641224, 0.109523, 0.783723], - [0.737185, -0.451155, 0.538891], - [0.848705, -0.612742, -0.314616], - [0.976075, 0.365067, 0.32976], - [1.072036, -0.19561, 0.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 type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0; - const size = options.size; - const sizeX = options.sizeX || size || 1; - const sizeY = options.sizeY || size || 1; - const sizeZ = options.sizeZ || size || 1; - const data = options.custom || polyhedra[type]; - const nbfaces = data.face.length; - const faceUV = options.faceUV || new Array(nbfaces); - const faceColors = options.faceColors; - const flat = options.flat === undefined ? true : options.flat; - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - const positions = new Array(); - const indices = new Array(); - const normals = new Array(); - const uvs = new Array(); - const colors = new Array(); - let index = 0; - let faceIdx = 0; // face cursor in the array "indexes" - const indexes = new Array(); - let i = 0; - let f = 0; - let u, v, ang, x, y, tmp; - // default face colors and UV if undefined - if (flat) { - for (f = 0; f < nbfaces; f++) { - if (faceColors && faceColors[f] === undefined) { - faceColors[f] = new math_color_Color4(1, 1, 1, 1); - } - if (faceUV && faceUV[f] === undefined) { - faceUV[f] = new math_vector_Vector4(0, 0, 1, 1); - } - } - } - if (!flat) { - for (i = 0; i < data.vertex.length; i++) { - positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ); - uvs.push(0, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 : 0); - } - for (f = 0; f < nbfaces; f++) { - for (i = 0; i < data.face[f].length - 2; i++) { - indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]); - } - } - } - else { - for (f = 0; f < nbfaces; f++) { - const fl = data.face[f].length; // number of vertices of the current face - ang = (2 * Math.PI) / fl; - x = 0.5 * Math.tan(ang / 2); - y = 0.5; - // positions, uvs, colors - for (i = 0; i < fl; i++) { - // positions - 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); - indexes.push(index); - index++; - // uvs - u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x); - v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5); - uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - v : v); - tmp = x * Math.cos(ang) - y * Math.sin(ang); - y = x * Math.sin(ang) + y * Math.cos(ang); - x = tmp; - // colors - if (faceColors) { - colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a); - } - } - // indices from indexes - for (i = 0; i < fl - 2; i++) { - indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]); - } - faceIdx += fl; - } - } - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals); - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); - const vertexData = new mesh_vertexData_VertexData(); - vertexData.positions = positions; - vertexData.indices = indices; - vertexData.normals = normals; - vertexData.uvs = uvs; - if (faceColors && flat) { - vertexData.colors = colors; - } - return vertexData; -} -/** - * Creates a polyhedron mesh - * * 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 - * * The parameter `size` (positive float, default 1) sets the polygon size - * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value) - * * 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` - * * 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 - * * 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)`) - * * 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 - * * 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 - * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE - * * 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 - * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.type - * @param options.size - * @param options.sizeX - * @param options.sizeY - * @param options.sizeZ - * @param options.custom - * @param options.faceUV - * @param options.faceColors - * @param options.flat - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param scene defines the hosting scene - * @returns the polyhedron mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra - */ -function polyhedronBuilder_CreatePolyhedron(name, options = {}, scene = null) { - const polyhedron = new mesh_Mesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - polyhedron._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreatePolyhedronVertexData(options); - vertexData.applyToMesh(polyhedron, options.updatable); - return polyhedron; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use the function directly from the module - */ -const PolyhedronBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreatePolyhedron: polyhedronBuilder_CreatePolyhedron, -}; -mesh_vertexData_VertexData.CreatePolyhedron = CreatePolyhedronVertexData; -mesh_Mesh.CreatePolyhedron = (name, options, scene) => { - return polyhedronBuilder_CreatePolyhedron(name, options, scene); -}; -//# sourceMappingURL=polyhedronBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/decalBuilder.js - - - - - - -const xpAxis = new math_vector_Vector3(1, 0, 0); -const xnAxis = new math_vector_Vector3(-1, 0, 0); -const ypAxis = new math_vector_Vector3(0, 1, 0); -const ynAxis = new math_vector_Vector3(0, -1, 0); -const zpAxis = new math_vector_Vector3(0, 0, 1); -const znAxis = new math_vector_Vector3(0, 0, -1); -/** @internal */ -class DecalVertex { - constructor(position = math_vector_Vector3.Zero(), normal = math_vector_Vector3.Up(), uv = math_vector_Vector2.Zero(), vertexIdx = 0, vertexIdxForBones = 0, localPositionOverride = null, localNormalOverride = null, matrixIndicesOverride = null, matrixWeightsOverride = null) { - this.position = position; - this.normal = normal; - this.uv = uv; - this.vertexIdx = vertexIdx; - this.vertexIdxForBones = vertexIdxForBones; - this.localPositionOverride = localPositionOverride; - this.localNormalOverride = localNormalOverride; - this.matrixIndicesOverride = matrixIndicesOverride; - this.matrixWeightsOverride = matrixWeightsOverride; - } - clone() { - var _a, _b, _c, _d; - 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()); - } -} -/** - * Creates a decal mesh. - * 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 - * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates - * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates - * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling - * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal - * * The parameter `captureUVS` defines if we need to capture the uvs or compute them - * * The parameter `cullBackFaces` defines if the back faces should be removed from the decal mesh - * * The parameter `localMode` defines that the computations should be done with the local mesh coordinates instead of the world space coordinates. - * * Use this mode if you want the decal to be parented to the sourceMesh and move/rotate with it. - * Note: Meshes with morph targets are not supported! - * @param name defines the name of the mesh - * @param sourceMesh defines the mesh where the decal must be applied - * @param options defines the options used to create the mesh - * @param options.position - * @param options.normal - * @param options.size - * @param options.angle - * @param options.captureUVS - * @param options.cullBackFaces - * @param options.localMode - * @returns the decal mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/decals - */ -function CreateDecal(name, sourceMesh, options) { - var _a, _b, _c, _d; - const hasSkeleton = !!sourceMesh.skeleton; - const useLocalComputation = options.localMode || hasSkeleton; - const meshHasOverridenMaterial = sourceMesh.overrideMaterialSideOrientation !== null && sourceMesh.overrideMaterialSideOrientation !== undefined; - const indices = sourceMesh.getIndices(); - const positions = hasSkeleton ? sourceMesh.getPositionData(true, true) : sourceMesh.getVerticesData(buffer_VertexBuffer.PositionKind); - const normals = hasSkeleton ? sourceMesh.getNormalsData(true, true) : sourceMesh.getVerticesData(buffer_VertexBuffer.NormalKind); - const localPositions = useLocalComputation ? (hasSkeleton ? sourceMesh.getVerticesData(buffer_VertexBuffer.PositionKind) : positions) : null; - const localNormals = useLocalComputation ? (hasSkeleton ? sourceMesh.getVerticesData(buffer_VertexBuffer.NormalKind) : normals) : null; - const uvs = sourceMesh.getVerticesData(buffer_VertexBuffer.UVKind); - const matIndices = hasSkeleton ? sourceMesh.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind) : null; - const matWeights = hasSkeleton ? sourceMesh.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind) : null; - const matIndicesExtra = hasSkeleton ? sourceMesh.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind) : null; - const matWeightsExtra = hasSkeleton ? sourceMesh.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind) : null; - const position = options.position || math_vector_Vector3.Zero(); - let normal = options.normal || math_vector_Vector3.Up(); - const size = options.size || math_vector_Vector3.One(); - const angle = options.angle || 0; - // Getting correct rotation - if (!normal) { - const target = new math_vector_Vector3(0, 0, 1); - const camera = sourceMesh.getScene().activeCamera; - const cameraWorldTarget = math_vector_Vector3.TransformCoordinates(target, camera.getWorldMatrix()); - normal = camera.globalPosition.subtract(cameraWorldTarget); - } - const yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2; - const len = Math.sqrt(normal.x * normal.x + normal.z * normal.z); - const pitch = Math.atan2(normal.y, len); - const vertexData = new mesh_vertexData_VertexData(); - vertexData.indices = []; - vertexData.positions = []; - vertexData.normals = []; - vertexData.uvs = []; - vertexData.matricesIndices = hasSkeleton ? [] : null; - vertexData.matricesWeights = hasSkeleton ? [] : null; - vertexData.matricesIndicesExtra = matIndicesExtra ? [] : null; - vertexData.matricesWeightsExtra = matWeightsExtra ? [] : null; - let currentVertexDataIndex = 0; - const extractDecalVector3 = (indexId, transformMatrix) => { - const result = new DecalVertex(); - if (!indices || !positions || !normals) { - return result; - } - const vertexId = indices[indexId]; - result.vertexIdx = vertexId * 3; - result.vertexIdxForBones = vertexId * 4; - // Send vector to decal local world - result.position = new math_vector_Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]); - math_vector_Vector3.TransformCoordinatesToRef(result.position, transformMatrix, result.position); - // Get normal - result.normal = new math_vector_Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]); - math_vector_Vector3.TransformNormalToRef(result.normal, transformMatrix, result.normal); - if (options.captureUVS && uvs) { - const v = uvs[vertexId * 2 + 1]; - result.uv = new math_vector_Vector2(uvs[vertexId * 2], CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v); - } - return result; - }; - const emptyArray = [0, 0, 0, 0]; - // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js - const clip = (vertices, axis) => { - if (vertices.length === 0) { - return vertices; - } - const clipSize = 0.5 * Math.abs(math_vector_Vector3.Dot(size, axis)); - const indexOf = (arr, val, start, num) => { - for (let i = 0; i < num; ++i) { - if (arr[start + i] === val) { - return start + i; - } - } - return -1; - }; - const clipVertices = (v0, v1) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - const clipFactor = math_vector_Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize); - let indices = emptyArray; - let weights = emptyArray; - if (matIndices && matWeights) { - const mat0Index = v0.matrixIndicesOverride ? 0 : v0.vertexIdxForBones; - const v0Indices = (_a = v0.matrixIndicesOverride) !== null && _a !== void 0 ? _a : matIndices; - const v0Weights = (_b = v0.matrixWeightsOverride) !== null && _b !== void 0 ? _b : matWeights; - const mat1Index = v1.matrixIndicesOverride ? 0 : v1.vertexIdxForBones; - const v1Indices = (_c = v1.matrixIndicesOverride) !== null && _c !== void 0 ? _c : matIndices; - const v1Weights = (_d = v1.matrixWeightsOverride) !== null && _d !== void 0 ? _d : matWeights; - indices = [0, 0, 0, 0]; - weights = [0, 0, 0, 0]; - let index = 0; - for (let i = 0; i < 4; ++i) { - if (v0Weights[mat0Index + i] > 0) { - const idx = indexOf(v1Indices, v0Indices[mat0Index + i], mat1Index, 4); - indices[index] = v0Indices[mat0Index + i]; - weights[index] = math_scalar_Scalar.Lerp(v0Weights[mat0Index + i], idx >= 0 ? v1Weights[idx] : 0, clipFactor); - index++; - } - } - for (let i = 0; i < 4 && index < 4; ++i) { - const ind = v1Indices[mat1Index + i]; - if (indexOf(v0Indices, ind, mat0Index, 4) !== -1) - continue; - indices[index] = ind; - weights[index] = math_scalar_Scalar.Lerp(0, v1Weights[mat1Index + i], clipFactor); - index++; - } - const sumw = weights[0] + weights[1] + weights[2] + weights[3]; - weights[0] /= sumw; - weights[1] /= sumw; - weights[2] /= sumw; - weights[3] /= sumw; - } - const v0LocalPositionX = v0.localPositionOverride ? v0.localPositionOverride[0] : (_e = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v0.vertexIdx]) !== null && _e !== void 0 ? _e : 0; - 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; - 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; - const v1LocalPositionX = v1.localPositionOverride ? v1.localPositionOverride[0] : (_h = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v1.vertexIdx]) !== null && _h !== void 0 ? _h : 0; - 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; - 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; - const v0LocalNormalX = v0.localNormalOverride ? v0.localNormalOverride[0] : (_l = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v0.vertexIdx]) !== null && _l !== void 0 ? _l : 0; - 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; - 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; - const v1LocalNormalX = v1.localNormalOverride ? v1.localNormalOverride[0] : (_p = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v1.vertexIdx]) !== null && _p !== void 0 ? _p : 0; - 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; - 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; - const interpNormalX = v0LocalNormalX + (v1LocalNormalX - v0LocalNormalX) * clipFactor; - const interpNormalY = v0LocalNormalY + (v1LocalNormalY - v0LocalNormalY) * clipFactor; - const interpNormalZ = v0LocalNormalZ + (v1LocalNormalZ - v0LocalNormalZ) * clipFactor; - const norm = Math.sqrt(interpNormalX * interpNormalX + interpNormalY * interpNormalY + interpNormalZ * interpNormalZ); - return new DecalVertex(math_vector_Vector3.Lerp(v0.position, v1.position, clipFactor), math_vector_Vector3.Lerp(v0.normal, v1.normal, clipFactor).normalize(), math_vector_Vector2.Lerp(v0.uv, v1.uv, clipFactor), -1, -1, localPositions - ? [ - v0LocalPositionX + (v1LocalPositionX - v0LocalPositionX) * clipFactor, - v0LocalPositionY + (v1LocalPositionY - v0LocalPositionY) * clipFactor, - v0LocalPositionZ + (v1LocalPositionZ - v0LocalPositionZ) * clipFactor, - ] - : null, localNormals ? [interpNormalX / norm, interpNormalY / norm, interpNormalZ / norm] : null, indices, weights); - }; - let clipResult = null; - if (vertices.length > 3) { - clipResult = new Array(); - } - for (let index = 0; index < vertices.length; index += 3) { - let total = 0; - let nV1 = null; - let nV2 = null; - let nV3 = null; - let nV4 = null; - const d1 = math_vector_Vector3.Dot(vertices[index].position, axis) - clipSize; - const d2 = math_vector_Vector3.Dot(vertices[index + 1].position, axis) - clipSize; - const d3 = math_vector_Vector3.Dot(vertices[index + 2].position, axis) - clipSize; - const v1Out = d1 > 0; - const v2Out = d2 > 0; - const v3Out = d3 > 0; - total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0); - switch (total) { - case 0: - if (vertices.length > 3) { - clipResult.push(vertices[index]); - clipResult.push(vertices[index + 1]); - clipResult.push(vertices[index + 2]); - } - else { - clipResult = vertices; - } - break; - case 1: - clipResult = clipResult !== null && clipResult !== void 0 ? clipResult : new Array(); - if (v1Out) { - nV1 = vertices[index + 1]; - nV2 = vertices[index + 2]; - nV3 = clipVertices(vertices[index], nV1); - nV4 = clipVertices(vertices[index], nV2); - } - if (v2Out) { - nV1 = vertices[index]; - nV2 = vertices[index + 2]; - nV3 = clipVertices(vertices[index + 1], nV1); - nV4 = clipVertices(vertices[index + 1], nV2); - clipResult.push(nV3); - clipResult.push(nV2.clone()); - clipResult.push(nV1.clone()); - clipResult.push(nV2.clone()); - clipResult.push(nV3.clone()); - clipResult.push(nV4); - break; - } - if (v3Out) { - nV1 = vertices[index]; - nV2 = vertices[index + 1]; - nV3 = clipVertices(vertices[index + 2], nV1); - nV4 = clipVertices(vertices[index + 2], nV2); - } - if (nV1 && nV2 && nV3 && nV4) { - clipResult.push(nV1.clone()); - clipResult.push(nV2.clone()); - clipResult.push(nV3); - clipResult.push(nV4); - clipResult.push(nV3.clone()); - clipResult.push(nV2.clone()); - } - break; - case 2: - clipResult = clipResult !== null && clipResult !== void 0 ? clipResult : new Array(); - if (!v1Out) { - nV1 = vertices[index].clone(); - nV2 = clipVertices(nV1, vertices[index + 1]); - nV3 = clipVertices(nV1, vertices[index + 2]); - clipResult.push(nV1); - clipResult.push(nV2); - clipResult.push(nV3); - } - if (!v2Out) { - nV1 = vertices[index + 1].clone(); - nV2 = clipVertices(nV1, vertices[index + 2]); - nV3 = clipVertices(nV1, vertices[index]); - clipResult.push(nV1); - clipResult.push(nV2); - clipResult.push(nV3); - } - if (!v3Out) { - nV1 = vertices[index + 2].clone(); - nV2 = clipVertices(nV1, vertices[index]); - nV3 = clipVertices(nV1, vertices[index + 1]); - clipResult.push(nV1); - clipResult.push(nV2); - clipResult.push(nV3); - } - break; - case 3: - break; - } - } - return clipResult; - }; - const sourceMeshAsMesh = sourceMesh instanceof mesh_Mesh ? sourceMesh : null; - const matrixData = sourceMeshAsMesh === null || sourceMeshAsMesh === void 0 ? void 0 : sourceMeshAsMesh._thinInstanceDataStorage.matrixData; - const numMatrices = (sourceMeshAsMesh === null || sourceMeshAsMesh === void 0 ? void 0 : sourceMeshAsMesh.thinInstanceCount) || 1; - const thinInstanceMatrix = math_vector_TmpVectors.Matrix[0]; - thinInstanceMatrix.copyFrom(math_vector_Matrix.IdentityReadOnly); - for (let m = 0; m < numMatrices; ++m) { - if ((sourceMeshAsMesh === null || sourceMeshAsMesh === void 0 ? void 0 : sourceMeshAsMesh.hasThinInstances) && matrixData) { - const ofst = m * 16; - thinInstanceMatrix.setRowFromFloats(0, matrixData[ofst + 0], matrixData[ofst + 1], matrixData[ofst + 2], matrixData[ofst + 3]); - thinInstanceMatrix.setRowFromFloats(1, matrixData[ofst + 4], matrixData[ofst + 5], matrixData[ofst + 6], matrixData[ofst + 7]); - thinInstanceMatrix.setRowFromFloats(2, matrixData[ofst + 8], matrixData[ofst + 9], matrixData[ofst + 10], matrixData[ofst + 11]); - thinInstanceMatrix.setRowFromFloats(3, matrixData[ofst + 12], matrixData[ofst + 13], matrixData[ofst + 14], matrixData[ofst + 15]); - } - // Matrix - const decalWorldMatrix = math_vector_Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(math_vector_Matrix.Translation(position.x, position.y, position.z)); - const inverseDecalWorldMatrix = math_vector_Matrix.Invert(decalWorldMatrix); - const meshWorldMatrix = sourceMesh.getWorldMatrix(); - const transformMatrix = thinInstanceMatrix.multiply(meshWorldMatrix).multiply(inverseDecalWorldMatrix); - const oneFaceVertices = new Array(3); - for (let index = 0; index < indices.length; index += 3) { - let faceVertices = oneFaceVertices; - faceVertices[0] = extractDecalVector3(index, transformMatrix); - if (meshHasOverridenMaterial && useLocalComputation) { - faceVertices[1] = extractDecalVector3(index + 2, transformMatrix); - faceVertices[2] = extractDecalVector3(index + 1, transformMatrix); - } - else { - faceVertices[1] = extractDecalVector3(index + 1, transformMatrix); - faceVertices[2] = extractDecalVector3(index + 2, transformMatrix); - } - if (options.cullBackFaces) { - // If all the normals of the vertices of the face are pointing away from the view direction we discard the face. - // 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 - if (-faceVertices[0].normal.z <= 0 && -faceVertices[1].normal.z <= 0 && -faceVertices[2].normal.z <= 0) { - continue; - } - } - // Clip - faceVertices = clip(faceVertices, xpAxis); - if (!faceVertices) - continue; - faceVertices = clip(faceVertices, xnAxis); - if (!faceVertices) - continue; - faceVertices = clip(faceVertices, ypAxis); - if (!faceVertices) - continue; - faceVertices = clip(faceVertices, ynAxis); - if (!faceVertices) - continue; - faceVertices = clip(faceVertices, zpAxis); - if (!faceVertices) - continue; - faceVertices = clip(faceVertices, znAxis); - if (!faceVertices) - continue; - // Add UVs and get back to world - for (let vIndex = 0; vIndex < faceVertices.length; vIndex++) { - const vertex = faceVertices[vIndex]; - //TODO check for Int32Array | Uint32Array | Uint16Array - vertexData.indices.push(currentVertexDataIndex); - if (useLocalComputation) { - if (vertex.localPositionOverride) { - vertexData.positions[currentVertexDataIndex * 3] = vertex.localPositionOverride[0]; - vertexData.positions[currentVertexDataIndex * 3 + 1] = vertex.localPositionOverride[1]; - vertexData.positions[currentVertexDataIndex * 3 + 2] = vertex.localPositionOverride[2]; - } - else if (localPositions) { - vertexData.positions[currentVertexDataIndex * 3] = localPositions[vertex.vertexIdx]; - vertexData.positions[currentVertexDataIndex * 3 + 1] = localPositions[vertex.vertexIdx + 1]; - vertexData.positions[currentVertexDataIndex * 3 + 2] = localPositions[vertex.vertexIdx + 2]; - } - if (vertex.localNormalOverride) { - vertexData.normals[currentVertexDataIndex * 3] = vertex.localNormalOverride[0]; - vertexData.normals[currentVertexDataIndex * 3 + 1] = vertex.localNormalOverride[1]; - vertexData.normals[currentVertexDataIndex * 3 + 2] = vertex.localNormalOverride[2]; - } - else if (localNormals) { - vertexData.normals[currentVertexDataIndex * 3] = localNormals[vertex.vertexIdx]; - vertexData.normals[currentVertexDataIndex * 3 + 1] = localNormals[vertex.vertexIdx + 1]; - vertexData.normals[currentVertexDataIndex * 3 + 2] = localNormals[vertex.vertexIdx + 2]; - } - } - else { - vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3); - vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3); - } - if (vertexData.matricesIndices && vertexData.matricesWeights) { - if (vertex.matrixIndicesOverride) { - vertexData.matricesIndices[currentVertexDataIndex * 4] = vertex.matrixIndicesOverride[0]; - vertexData.matricesIndices[currentVertexDataIndex * 4 + 1] = vertex.matrixIndicesOverride[1]; - vertexData.matricesIndices[currentVertexDataIndex * 4 + 2] = vertex.matrixIndicesOverride[2]; - vertexData.matricesIndices[currentVertexDataIndex * 4 + 3] = vertex.matrixIndicesOverride[3]; - } - else { - if (matIndices) { - vertexData.matricesIndices[currentVertexDataIndex * 4] = matIndices[vertex.vertexIdxForBones]; - vertexData.matricesIndices[currentVertexDataIndex * 4 + 1] = matIndices[vertex.vertexIdxForBones + 1]; - vertexData.matricesIndices[currentVertexDataIndex * 4 + 2] = matIndices[vertex.vertexIdxForBones + 2]; - vertexData.matricesIndices[currentVertexDataIndex * 4 + 3] = matIndices[vertex.vertexIdxForBones + 3]; - } - if (matIndicesExtra && vertexData.matricesIndicesExtra) { - vertexData.matricesIndicesExtra[currentVertexDataIndex * 4] = matIndicesExtra[vertex.vertexIdxForBones]; - vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 1] = matIndicesExtra[vertex.vertexIdxForBones + 1]; - vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 2] = matIndicesExtra[vertex.vertexIdxForBones + 2]; - vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 3] = matIndicesExtra[vertex.vertexIdxForBones + 3]; - } - } - if (vertex.matrixWeightsOverride) { - vertexData.matricesWeights[currentVertexDataIndex * 4] = vertex.matrixWeightsOverride[0]; - vertexData.matricesWeights[currentVertexDataIndex * 4 + 1] = vertex.matrixWeightsOverride[1]; - vertexData.matricesWeights[currentVertexDataIndex * 4 + 2] = vertex.matrixWeightsOverride[2]; - vertexData.matricesWeights[currentVertexDataIndex * 4 + 3] = vertex.matrixWeightsOverride[3]; - } - else { - if (matWeights) { - vertexData.matricesWeights[currentVertexDataIndex * 4] = matWeights[vertex.vertexIdxForBones]; - vertexData.matricesWeights[currentVertexDataIndex * 4 + 1] = matWeights[vertex.vertexIdxForBones + 1]; - vertexData.matricesWeights[currentVertexDataIndex * 4 + 2] = matWeights[vertex.vertexIdxForBones + 2]; - vertexData.matricesWeights[currentVertexDataIndex * 4 + 3] = matWeights[vertex.vertexIdxForBones + 3]; - } - if (matWeightsExtra && vertexData.matricesWeightsExtra) { - vertexData.matricesWeightsExtra[currentVertexDataIndex * 4] = matWeightsExtra[vertex.vertexIdxForBones]; - vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 1] = matWeightsExtra[vertex.vertexIdxForBones + 1]; - vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 2] = matWeightsExtra[vertex.vertexIdxForBones + 2]; - vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 3] = matWeightsExtra[vertex.vertexIdxForBones + 3]; - } - } - } - if (!options.captureUVS) { - vertexData.uvs.push(0.5 + vertex.position.x / size.x); - const v = 0.5 + vertex.position.y / size.y; - vertexData.uvs.push(CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v); - } - else { - vertex.uv.toArray(vertexData.uvs, currentVertexDataIndex * 2); - } - currentVertexDataIndex++; - } - } - } - // Avoid the "Setting vertex data kind 'XXX' with an empty array" warning when calling vertexData.applyToMesh - if (vertexData.indices.length === 0) - vertexData.indices = null; - if (vertexData.positions.length === 0) - vertexData.positions = null; - if (vertexData.normals.length === 0) - vertexData.normals = null; - if (vertexData.uvs.length === 0) - vertexData.uvs = null; - if (((_a = vertexData.matricesIndices) === null || _a === void 0 ? void 0 : _a.length) === 0) - vertexData.matricesIndices = null; - if (((_b = vertexData.matricesWeights) === null || _b === void 0 ? void 0 : _b.length) === 0) - vertexData.matricesWeights = null; - if (((_c = vertexData.matricesIndicesExtra) === null || _c === void 0 ? void 0 : _c.length) === 0) - vertexData.matricesIndicesExtra = null; - if (((_d = vertexData.matricesWeightsExtra) === null || _d === void 0 ? void 0 : _d.length) === 0) - vertexData.matricesWeightsExtra = null; - // Return mesh - const decal = new mesh_Mesh(name, sourceMesh.getScene()); - vertexData.applyToMesh(decal); - if (useLocalComputation) { - decal.skeleton = sourceMesh.skeleton; - decal.parent = sourceMesh; - } - else { - decal.position = position.clone(); - decal.rotation = new math_vector_Vector3(pitch, yaw, angle); - } - decal.computeWorldMatrix(true); - decal.refreshBoundingInfo(true, true); - return decal; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use the function directly from the module - */ -const DecalBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateDecal, -}; -mesh_Mesh.CreateDecal = (name, sourceMesh, position, normal, size, angle) => { - const options = { - position, - normal, - size, - angle, - }; - return CreateDecal(name, sourceMesh, options); -}; -//# sourceMappingURL=decalBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.isovector.js - - -/** - * Class representing an isovector a vector containing 2 INTEGER coordinates - * x axis is horizontal - * y axis is 60 deg counter clockwise from positive y axis - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _IsoVector { - /** - * Creates a new isovector from the given x and y coordinates - * @param x defines the first coordinate, must be an integer - * @param y defines the second coordinate, must be an integer - */ - constructor( - /** defines the first coordinate */ - x = 0, - /** defines the second coordinate */ - y = 0) { - this.x = x; - this.y = y; - if (x !== Math.floor(x)) { - x === Math.floor(x); - logger_Logger.Warn("x is not an integer, floor(x) used"); - } - if (y !== Math.floor(y)) { - y === Math.floor(y); - logger_Logger.Warn("y is not an integer, floor(y) used"); - } - } - // Operators - /** - * Gets a new IsoVector copied from the IsoVector - * @returns a new IsoVector - */ - clone() { - return new _IsoVector(this.x, this.y); - } - /** - * Rotates one IsoVector 60 degrees counter clockwise about another - * Please note that this is an in place operation - * @param other an IsoVector a center of rotation - * @returns the rotated IsoVector - */ - rotate60About(other) { - //other IsoVector - const x = this.x; - this.x = other.x + other.y - this.y; - this.y = x + this.y - other.x; - return this; - } - /** - * Rotates one IsoVector 60 degrees clockwise about another - * Please note that this is an in place operation - * @param other an IsoVector as center of rotation - * @returns the rotated IsoVector - */ - rotateNeg60About(other) { - const x = this.x; - this.x = x + this.y - other.y; - this.y = other.x + other.y - x; - return this; - } - /** - * For an equilateral triangle OAB with O at isovector (0, 0) and A at isovector (m, n) - * Rotates one IsoVector 120 degrees counter clockwise about the center of the triangle - * Please note that this is an in place operation - * @param m integer a measure a Primary triangle of order (m, n) m > n - * @param n >= 0 integer a measure for a Primary triangle of order (m, n) - * @returns the rotated IsoVector - */ - rotate120(m, n) { - //m, n integers - if (m !== Math.floor(m)) { - m === Math.floor(m); - logger_Logger.Warn("m not an integer only floor(m) used"); - } - if (n !== Math.floor(n)) { - n === Math.floor(n); - logger_Logger.Warn("n not an integer only floor(n) used"); - } - const x = this.x; - this.x = m - x - this.y; - this.y = n + x; - return this; - } - /** - * For an equilateral triangle OAB with O at isovector (0, 0) and A at isovector (m, n) - * Rotates one IsoVector 120 degrees clockwise about the center of the triangle - * Please note that this is an in place operation - * @param m integer a measure a Primary triangle of order (m, n) m > n - * @param n >= 0 integer a measure for a Primary triangle of order (m, n) - * @returns the rotated IsoVector - */ - rotateNeg120(m, n) { - //m, n integers - if (m !== Math.floor(m)) { - m === Math.floor(m); - logger_Logger.Warn("m is not an integer, floor(m) used"); - } - if (n !== Math.floor(n)) { - n === Math.floor(n); - logger_Logger.Warn("n is not an integer, floor(n) used"); - } - const x = this.x; - this.x = this.y - n; - this.y = m + n - x - this.y; - return this; - } - /** - * Transforms an IsoVector to one in Cartesian 3D space based on an isovector - * @param origin an IsoVector - * @param isoGridSize - * @returns Point as a Vector3 - */ - toCartesianOrigin(origin, isoGridSize) { - const point = math_vector_Vector3.Zero(); - point.x = origin.x + 2 * this.x * isoGridSize + this.y * isoGridSize; - point.y = origin.y + Math.sqrt(3) * this.y * isoGridSize; - return point; - } - // Statics - /** - * Gets a new IsoVector(0, 0) - * @returns a new IsoVector - */ - static Zero() { - return new _IsoVector(0, 0); - } -} -//# sourceMappingURL=math.isovector.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/geodesicMesh.js - - - - -/** - * Class representing data for one face OAB of an equilateral icosahedron - * When O is the isovector (0, 0), A is isovector (m, n) - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _PrimaryIsoTriangle { - constructor() { - this.cartesian = []; - this.vertices = []; - this.max = []; - this.min = []; - this.closestTo = []; - this.innerFacets = []; - this.isoVecsABOB = []; - this.isoVecsOBOA = []; - this.isoVecsBAOA = []; - this.vertexTypes = []; - // eslint-disable-next-line @typescript-eslint/naming-convention - this.IDATA = new PolyhedronData("icosahedron", "Regular", [ - [0, PHI, -1], - [-PHI, 1, 0], - [-1, 0, -PHI], - [1, 0, -PHI], - [PHI, 1, 0], - [0, PHI, 1], - [-1, 0, PHI], - [-PHI, -1, 0], - [0, -PHI, -1], - [PHI, -1, 0], - [1, 0, PHI], - [0, -PHI, 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], - ]); - } - /** - * Creates the PrimaryIsoTriangle Triangle OAB - * @param m an integer - * @param n an integer - */ - //operators - setIndices() { - let indexCount = 12; // 12 vertices already assigned - const vecToidx = {}; //maps iso-vectors to indexCount; - const m = this.m; - const n = this.n; - let g = m; // hcf of m, n when n != 0 - let m1 = 1; - let n1 = 0; - if (n !== 0) { - g = math_scalar_Scalar.HCF(m, n); - } - m1 = m / g; - n1 = n / g; - let fr; //face to the right of current face - let rot; //rotation about which vertex for fr - let O; - let A; - let B; - const oVec = _IsoVector.Zero(); - const aVec = new _IsoVector(m, n); - const bVec = new _IsoVector(-n, m + n); - const oaVec = _IsoVector.Zero(); - const abVec = _IsoVector.Zero(); - const obVec = _IsoVector.Zero(); - let verts = []; - let idx; - let idxR; - let isoId; - let isoIdR; - const closestTo = []; - const vDist = this.vertByDist; - const matchIdx = (f, fr, isoId, isoIdR) => { - idx = f + "|" + isoId; - idxR = fr + "|" + isoIdR; - if (!(idx in vecToidx || idxR in vecToidx)) { - vecToidx[idx] = indexCount; - vecToidx[idxR] = indexCount; - indexCount++; - } - else if (idx in vecToidx && !(idxR in vecToidx)) { - vecToidx[idxR] = vecToidx[idx]; - } - else if (idxR in vecToidx && !(idx in vecToidx)) { - vecToidx[idx] = vecToidx[idxR]; - } - if (vDist[isoId][0] > 2) { - closestTo[vecToidx[idx]] = [-vDist[isoId][0], vDist[isoId][1], vecToidx[idx]]; - } - else { - closestTo[vecToidx[idx]] = [verts[vDist[isoId][0]], vDist[isoId][1], vecToidx[idx]]; - } - }; - 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"], - ]; - /***edges AB to OB***** rotation about B*/ - for (let f = 0; f < 20; f++) { - //f current face - verts = this.IDATA.face[f]; - O = verts[2]; - A = verts[1]; - B = verts[0]; - isoId = oVec.x + "|" + oVec.y; - idx = f + "|" + isoId; - if (!(idx in vecToidx)) { - vecToidx[idx] = O; - closestTo[O] = [verts[vDist[isoId][0]], vDist[isoId][1]]; - } - isoId = aVec.x + "|" + aVec.y; - idx = f + "|" + isoId; - if (!(idx in vecToidx)) { - vecToidx[idx] = A; - closestTo[A] = [verts[vDist[isoId][0]], vDist[isoId][1]]; - } - isoId = bVec.x + "|" + bVec.y; - idx = f + "|" + isoId; - if (!(idx in vecToidx)) { - vecToidx[idx] = B; - closestTo[B] = [verts[vDist[isoId][0]], vDist[isoId][1]]; - } - //for edge vertices - fr = this.IDATA.edgematch[f][0]; - rot = this.IDATA.edgematch[f][1]; - if (rot === "B") { - for (let i = 1; i < g; i++) { - abVec.x = m - i * (m1 + n1); - abVec.y = n + i * m1; - obVec.x = -i * n1; - obVec.y = i * (m1 + n1); - isoId = abVec.x + "|" + abVec.y; - isoIdR = obVec.x + "|" + obVec.y; - matchIdx(f, fr, isoId, isoIdR); - } - } - if (rot === "O") { - for (let i = 1; i < g; i++) { - obVec.x = -i * n1; - obVec.y = i * (m1 + n1); - oaVec.x = i * m1; - oaVec.y = i * n1; - isoId = obVec.x + "|" + obVec.y; - isoIdR = oaVec.x + "|" + oaVec.y; - matchIdx(f, fr, isoId, isoIdR); - } - } - fr = this.IDATA.edgematch[f][2]; - rot = this.IDATA.edgematch[f][3]; - if (rot && rot === "A") { - for (let i = 1; i < g; i++) { - oaVec.x = i * m1; - oaVec.y = i * n1; - abVec.x = m - (g - i) * (m1 + n1); //reversed for BA - abVec.y = n + (g - i) * m1; //reversed for BA - isoId = oaVec.x + "|" + oaVec.y; - isoIdR = abVec.x + "|" + abVec.y; - matchIdx(f, fr, isoId, isoIdR); - } - } - for (let i = 0; i < this.vertices.length; i++) { - isoId = this.vertices[i].x + "|" + this.vertices[i].y; - idx = f + "|" + isoId; - if (!(idx in vecToidx)) { - vecToidx[idx] = indexCount++; - if (vDist[isoId][0] > 2) { - closestTo[vecToidx[idx]] = [-vDist[isoId][0], vDist[isoId][1], vecToidx[idx]]; - } - else { - closestTo[vecToidx[idx]] = [verts[vDist[isoId][0]], vDist[isoId][1], vecToidx[idx]]; - } - } - } - } - this.closestTo = closestTo; - this.vecToidx = vecToidx; - } - calcCoeffs() { - const m = this.m; - const n = this.n; - const thirdR3 = Math.sqrt(3) / 3; - const LSQD = m * m + n * n + m * n; - this.coau = (m + n) / LSQD; - this.cobu = -n / LSQD; - this.coav = (-thirdR3 * (m - n)) / LSQD; - this.cobv = (thirdR3 * (2 * m + n)) / LSQD; - } - createInnerFacets() { - const m = this.m; - const n = this.n; - for (let y = 0; y < n + m + 1; y++) { - for (let x = this.min[y]; x < this.max[y] + 1; x++) { - if (x < this.max[y] && x < this.max[y + 1] + 1) { - this.innerFacets.push(["|" + x + "|" + y, "|" + x + "|" + (y + 1), "|" + (x + 1) + "|" + y]); - } - if (y > 0 && x < this.max[y - 1] && x + 1 < this.max[y] + 1) { - this.innerFacets.push(["|" + x + "|" + y, "|" + (x + 1) + "|" + y, "|" + (x + 1) + "|" + (y - 1)]); - } - } - } - } - edgeVecsABOB() { - const m = this.m; - const n = this.n; - const B = new _IsoVector(-n, m + n); - for (let y = 1; y < m + n; y++) { - const point = new _IsoVector(this.min[y], y); - const prev = new _IsoVector(this.min[y - 1], y - 1); - const next = new _IsoVector(this.min[y + 1], y + 1); - const pointR = point.clone(); - const prevR = prev.clone(); - const nextR = next.clone(); - pointR.rotate60About(B); - prevR.rotate60About(B); - nextR.rotate60About(B); - const maxPoint = new _IsoVector(this.max[pointR.y], pointR.y); - const maxPrev = new _IsoVector(this.max[pointR.y - 1], pointR.y - 1); - const maxLeftPrev = new _IsoVector(this.max[pointR.y - 1] - 1, pointR.y - 1); - if (pointR.x !== maxPoint.x || pointR.y !== maxPoint.y) { - if (pointR.x !== maxPrev.x) { - // type2 - //up - this.vertexTypes.push([1, 0, 0]); - this.isoVecsABOB.push([point, maxPrev, maxLeftPrev]); - //down - this.vertexTypes.push([1, 0, 0]); - this.isoVecsABOB.push([point, maxLeftPrev, maxPoint]); - } - else if (pointR.y === nextR.y) { - // type1 - //up - this.vertexTypes.push([1, 1, 0]); - this.isoVecsABOB.push([point, prev, maxPrev]); - //down - this.vertexTypes.push([1, 0, 1]); - this.isoVecsABOB.push([point, maxPrev, next]); - } - else { - // type 0 - //up - this.vertexTypes.push([1, 1, 0]); - this.isoVecsABOB.push([point, prev, maxPrev]); - //down - this.vertexTypes.push([1, 0, 0]); - this.isoVecsABOB.push([point, maxPrev, maxPoint]); - } - } - } - } - mapABOBtoOBOA() { - const point = new _IsoVector(0, 0); - for (let i = 0; i < this.isoVecsABOB.length; i++) { - const temp = []; - for (let j = 0; j < 3; j++) { - point.x = this.isoVecsABOB[i][j].x; - point.y = this.isoVecsABOB[i][j].y; - if (this.vertexTypes[i][j] === 0) { - point.rotateNeg120(this.m, this.n); - } - temp.push(point.clone()); - } - this.isoVecsOBOA.push(temp); - } - } - mapABOBtoBAOA() { - const point = new _IsoVector(0, 0); - for (let i = 0; i < this.isoVecsABOB.length; i++) { - const temp = []; - for (let j = 0; j < 3; j++) { - point.x = this.isoVecsABOB[i][j].x; - point.y = this.isoVecsABOB[i][j].y; - if (this.vertexTypes[i][j] === 1) { - point.rotate120(this.m, this.n); - } - temp.push(point.clone()); - } - this.isoVecsBAOA.push(temp); - } - } - // eslint-disable-next-line @typescript-eslint/naming-convention - MapToFace(faceNb, geodesicData) { - const F = this.IDATA.face[faceNb]; - const oidx = F[2]; - const aidx = F[1]; - const bidx = F[0]; - const O = math_vector_Vector3.FromArray(this.IDATA.vertex[oidx]); - const A = math_vector_Vector3.FromArray(this.IDATA.vertex[aidx]); - const B = math_vector_Vector3.FromArray(this.IDATA.vertex[bidx]); - const OA = A.subtract(O); - const OB = B.subtract(O); - const x = OA.scale(this.coau).add(OB.scale(this.cobu)); - const y = OA.scale(this.coav).add(OB.scale(this.cobv)); - const mapped = []; - let idx; - let tempVec = math_vector_TmpVectors.Vector3[0]; - for (let i = 0; i < this.cartesian.length; i++) { - tempVec = x.scale(this.cartesian[i].x).add(y.scale(this.cartesian[i].y)).add(O); - mapped[i] = [tempVec.x, tempVec.y, tempVec.z]; - idx = faceNb + "|" + this.vertices[i].x + "|" + this.vertices[i].y; - geodesicData.vertex[this.vecToidx[idx]] = [tempVec.x, tempVec.y, tempVec.z]; - } - } - //statics - /**Creates a primary triangle - * @internal - */ - build(m, n) { - const vertices = new Array(); - const O = _IsoVector.Zero(); - const A = new _IsoVector(m, n); - const B = new _IsoVector(-n, m + n); - vertices.push(O, A, B); - //max internal isoceles triangle vertices - for (let y = n; y < m + 1; y++) { - for (let x = 0; x < m + 1 - y; x++) { - vertices.push(new _IsoVector(x, y)); - } - } - //shared vertices along edges when needed - if (n > 0) { - const g = math_scalar_Scalar.HCF(m, n); - const m1 = m / g; - const n1 = n / g; - for (let i = 1; i < g; i++) { - vertices.push(new _IsoVector(i * m1, i * n1)); //OA - vertices.push(new _IsoVector(-i * n1, i * (m1 + n1))); //OB - vertices.push(new _IsoVector(m - i * (m1 + n1), n + i * m1)); // AB - } - //lower rows vertices and their rotations - const ratio = m / n; - for (let y = 1; y < n; y++) { - for (let x = 0; x < y * ratio; x++) { - vertices.push(new _IsoVector(x, y)); - vertices.push(new _IsoVector(x, y).rotate120(m, n)); - vertices.push(new _IsoVector(x, y).rotateNeg120(m, n)); - } - } - } - //order vertices by x and then y - vertices.sort((a, b) => { - return a.x - b.x; - }); - vertices.sort((a, b) => { - return a.y - b.y; - }); - const min = new Array(m + n + 1); - const max = new Array(m + n + 1); - for (let i = 0; i < min.length; i++) { - min[i] = Infinity; - max[i] = -Infinity; - } - let y = 0; - let x = 0; - const len = vertices.length; - for (let i = 0; i < len; i++) { - x = vertices[i].x; - y = vertices[i].y; - min[y] = Math.min(x, min[y]); - max[y] = Math.max(x, max[y]); - } - //calculates the distance of a vertex from a given primary vertex - const distFrom = (vert, primVert) => { - const v = vert.clone(); - if (primVert === "A") { - v.rotateNeg120(m, n); - } - if (primVert === "B") { - v.rotate120(m, n); - } - if (v.x < 0) { - return v.y; - } - return v.x + v.y; - }; - const cartesian = []; - const distFromO = []; - const distFromA = []; - const distFromB = []; - const vertByDist = {}; - const vertData = []; - let closest = -1; - let dist = -1; - for (let i = 0; i < len; i++) { - cartesian[i] = vertices[i].toCartesianOrigin(new _IsoVector(0, 0), 0.5); - distFromO[i] = distFrom(vertices[i], "O"); - distFromA[i] = distFrom(vertices[i], "A"); - distFromB[i] = distFrom(vertices[i], "B"); - if (distFromO[i] === distFromA[i] && distFromA[i] === distFromB[i]) { - closest = 3; - dist = distFromO[i]; - } - else if (distFromO[i] === distFromA[i]) { - closest = 4; - dist = distFromO[i]; - } - else if (distFromA[i] === distFromB[i]) { - closest = 5; - dist = distFromA[i]; - } - else if (distFromB[i] === distFromO[i]) { - closest = 6; - dist = distFromO[i]; - } - if (distFromO[i] < distFromA[i] && distFromO[i] < distFromB[i]) { - closest = 2; - dist = distFromO[i]; - } - if (distFromA[i] < distFromO[i] && distFromA[i] < distFromB[i]) { - closest = 1; - dist = distFromA[i]; - } - if (distFromB[i] < distFromA[i] && distFromB[i] < distFromO[i]) { - closest = 0; - dist = distFromB[i]; - } - vertData.push([closest, dist, vertices[i].x, vertices[i].y]); - } - vertData.sort((a, b) => { - return a[2] - b[2]; - }); - vertData.sort((a, b) => { - return a[3] - b[3]; - }); - vertData.sort((a, b) => { - return a[1] - b[1]; - }); - vertData.sort((a, b) => { - return a[0] - b[0]; - }); - for (let v = 0; v < vertData.length; v++) { - vertByDist[vertData[v][2] + "|" + vertData[v][3]] = [vertData[v][0], vertData[v][1], v]; - } - this.m = m; - this.n = n; - this.vertices = vertices; - this.vertByDist = vertByDist; - this.cartesian = cartesian; - this.min = min; - this.max = max; - return this; - } -} -/** Builds Polyhedron Data - * @internal - */ -class PolyhedronData { - constructor(name, category, vertex, face) { - this.name = name; - this.category = category; - this.vertex = vertex; - this.face = face; - } -} -/** - * This class Extends the PolyhedronData Class to provide measures for a Geodesic Polyhedron - */ -class GeodesicData extends PolyhedronData { - /** - * @internal - */ - innerToData(face, primTri) { - for (let i = 0; i < primTri.innerFacets.length; i++) { - this.face.push(primTri.innerFacets[i].map((el) => primTri.vecToidx[face + el])); - } - } - /** - * @internal - */ - mapABOBtoDATA(faceNb, primTri) { - const fr = primTri.IDATA.edgematch[faceNb][0]; - for (let i = 0; i < primTri.isoVecsABOB.length; i++) { - const temp = []; - for (let j = 0; j < 3; j++) { - if (primTri.vertexTypes[i][j] === 0) { - temp.push(faceNb + "|" + primTri.isoVecsABOB[i][j].x + "|" + primTri.isoVecsABOB[i][j].y); - } - else { - temp.push(fr + "|" + primTri.isoVecsABOB[i][j].x + "|" + primTri.isoVecsABOB[i][j].y); - } - } - this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]); - } - } - /** - * @internal - */ - mapOBOAtoDATA(faceNb, primTri) { - const fr = primTri.IDATA.edgematch[faceNb][0]; - for (let i = 0; i < primTri.isoVecsOBOA.length; i++) { - const temp = []; - for (let j = 0; j < 3; j++) { - if (primTri.vertexTypes[i][j] === 1) { - temp.push(faceNb + "|" + primTri.isoVecsOBOA[i][j].x + "|" + primTri.isoVecsOBOA[i][j].y); - } - else { - temp.push(fr + "|" + primTri.isoVecsOBOA[i][j].x + "|" + primTri.isoVecsOBOA[i][j].y); - } - } - this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]); - } - } - /** - * @internal - */ - mapBAOAtoDATA(faceNb, primTri) { - const fr = primTri.IDATA.edgematch[faceNb][2]; - for (let i = 0; i < primTri.isoVecsBAOA.length; i++) { - const temp = []; - for (let j = 0; j < 3; j++) { - if (primTri.vertexTypes[i][j] === 1) { - temp.push(faceNb + "|" + primTri.isoVecsBAOA[i][j].x + "|" + primTri.isoVecsBAOA[i][j].y); - } - else { - temp.push(fr + "|" + primTri.isoVecsBAOA[i][j].x + "|" + primTri.isoVecsBAOA[i][j].y); - } - } - this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]); - } - } - /** - * @internal - */ - orderData(primTri) { - const nearTo = []; - for (let i = 0; i < 13; i++) { - nearTo[i] = []; - } - const close = primTri.closestTo; - for (let i = 0; i < close.length; i++) { - if (close[i][0] > -1) { - if (close[i][1] > 0) { - nearTo[close[i][0]].push([i, close[i][1]]); - } - } - else { - nearTo[12].push([i, close[i][0]]); - } - } - const near = []; - for (let i = 0; i < 12; i++) { - near[i] = i; - } - let nearIndex = 12; - for (let i = 0; i < 12; i++) { - nearTo[i].sort((a, b) => { - return a[1] - b[1]; - }); - for (let j = 0; j < nearTo[i].length; j++) { - near[nearTo[i][j][0]] = nearIndex++; - } - } - for (let j = 0; j < nearTo[12].length; j++) { - near[nearTo[12][j][0]] = nearIndex++; - } - for (let i = 0; i < this.vertex.length; i++) { - this.vertex[i].push(near[i]); - } - this.vertex.sort((a, b) => { - return a[3] - b[3]; - }); - for (let i = 0; i < this.vertex.length; i++) { - this.vertex[i].pop(); - } - for (let i = 0; i < this.face.length; i++) { - for (let j = 0; j < this.face[i].length; j++) { - this.face[i][j] = near[this.face[i][j]]; - } - } - this.sharedNodes = nearTo[12].length; - this.poleNodes = this.vertex.length - this.sharedNodes; - } - /** - * @internal - */ - setOrder(m, faces) { - const adjVerts = []; - const dualFaces = []; - let face = faces.pop(); - dualFaces.push(face); - let index = this.face[face].indexOf(m); - index = (index + 2) % 3; - let v = this.face[face][index]; - adjVerts.push(v); - let f = 0; - while (faces.length > 0) { - face = faces[f]; - if (this.face[face].indexOf(v) > -1) { - // v is a vertex of face f - index = (this.face[face].indexOf(v) + 1) % 3; - v = this.face[face][index]; - adjVerts.push(v); - dualFaces.push(face); - faces.splice(f, 1); - f = 0; - } - else { - f++; - } - } - this.adjacentFaces.push(adjVerts); - return dualFaces; - } - /** - * @internal - */ - toGoldbergPolyhedronData() { - const goldbergPolyhedronData = new PolyhedronData("GeoDual", "Goldberg", [], []); - goldbergPolyhedronData.name = "GD dual"; - const verticesNb = this.vertex.length; - const map = new Array(verticesNb); - for (let v = 0; v < verticesNb; v++) { - map[v] = []; - } - for (let f = 0; f < this.face.length; f++) { - for (let i = 0; i < 3; i++) { - map[this.face[f][i]].push(f); - } - } - let cx = 0; - let cy = 0; - let cz = 0; - let face = []; - let vertex = []; - this.adjacentFaces = []; - for (let m = 0; m < map.length; m++) { - goldbergPolyhedronData.face[m] = this.setOrder(m, map[m].concat([])); - map[m].forEach((el) => { - cx = 0; - cy = 0; - cz = 0; - face = this.face[el]; - for (let i = 0; i < 3; i++) { - vertex = this.vertex[face[i]]; - cx += vertex[0]; - cy += vertex[1]; - cz += vertex[2]; - } - goldbergPolyhedronData.vertex[el] = [cx / 3, cy / 3, cz / 3]; - }); - } - return goldbergPolyhedronData; - } - //statics - /**Builds the data for a Geodesic Polyhedron from a primary triangle - * @param primTri the primary triangle - * @internal - */ - static BuildGeodesicData(primTri) { - const geodesicData = new GeodesicData("Geodesic-m-n", "Geodesic", [ - [0, PHI, -1], - [-PHI, 1, 0], - [-1, 0, -PHI], - [1, 0, -PHI], - [PHI, 1, 0], - [0, PHI, 1], - [-1, 0, PHI], - [-PHI, -1, 0], - [0, -PHI, -1], - [PHI, -1, 0], - [1, 0, PHI], - [0, -PHI, 1], - ], []); - primTri.setIndices(); - primTri.calcCoeffs(); - primTri.createInnerFacets(); - primTri.edgeVecsABOB(); - primTri.mapABOBtoOBOA(); - primTri.mapABOBtoBAOA(); - for (let f = 0; f < primTri.IDATA.face.length; f++) { - primTri.MapToFace(f, geodesicData); - geodesicData.innerToData(f, primTri); - if (primTri.IDATA.edgematch[f][1] === "B") { - geodesicData.mapABOBtoDATA(f, primTri); - } - if (primTri.IDATA.edgematch[f][1] === "O") { - geodesicData.mapOBOAtoDATA(f, primTri); - } - if (primTri.IDATA.edgematch[f][3] === "A") { - geodesicData.mapBAOAtoDATA(f, primTri); - } - } - geodesicData.orderData(primTri); - const radius = 1; - geodesicData.vertex = geodesicData.vertex.map(function (el) { - const a = el[0]; - const b = el[1]; - const c = el[2]; - const d = Math.sqrt(a * a + b * b + c * c); - el[0] *= radius / d; - el[1] *= radius / d; - el[2] *= radius / d; - return el; - }); - return geodesicData; - } -} -//# sourceMappingURL=geodesicMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/geodesicBuilder.js - - - -/** - * Creates the Mesh for a Geodesic Polyhedron - * @see https://en.wikipedia.org/wiki/Geodesic_polyhedron - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra/geodesic_poly - * @param name defines the name of the mesh - * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty - * * m number of horizontal steps along an isogrid - * * n number of angled steps along an isogrid - * * size the size of the Geodesic, optional default 1 - * * sizeX allows stretching in the x direction, optional, default size - * * sizeY allows stretching in the y direction, optional, default size - * * sizeZ allows stretching in the z direction, optional, default size - * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively - * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively - * * flat when true creates a flat shaded mesh, optional, default true - * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 - * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE - * * 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) - * * 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) - * @param options.n - * @param options.size - * @param options.sizeX - * @param options.sizeY - * @param options.sizeZ - * @param options.faceUV - * @param options.faceColors - * @param options.flat - * @param options.updatable - * @param options.sideOrientation - * @param options.frontUVs - * @param options.backUVs - * @param options.m - * @param scene defines the hosting scene - * @returns Geodesic mesh - */ -function CreateGeodesic(name, options, scene = null) { - let m = options.m || 1; - if (m !== Math.floor(m)) { - m === Math.floor(m); - logger_Logger.Warn("m not an integer only floor(m) used"); - } - let n = options.n || 0; - if (n !== Math.floor(n)) { - n === Math.floor(n); - logger_Logger.Warn("n not an integer only floor(n) used"); - } - if (n > m) { - const temp = n; - n = m; - m = temp; - logger_Logger.Warn("n > m therefore m and n swapped"); - } - const primTri = new _PrimaryIsoTriangle(); - primTri.build(m, n); - const geodesicData = GeodesicData.BuildGeodesicData(primTri); - const geoOptions = { - custom: geodesicData, - size: options.size, - sizeX: options.sizeX, - sizeY: options.sizeY, - sizeZ: options.sizeZ, - faceUV: options.faceUV, - faceColors: options.faceColors, - flat: options.flat, - updatable: options.updatable, - sideOrientation: options.sideOrientation, - frontUVs: options.frontUVs, - backUVs: options.backUVs, - }; - const geodesic = polyhedronBuilder_CreatePolyhedron(name, geoOptions, scene); - return geodesic; -} -//# sourceMappingURL=geodesicBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/goldbergMesh.js - - - - - -mesh_Mesh._GoldbergMeshParser = (parsedMesh, scene) => { - return GoldbergMesh.Parse(parsedMesh, scene); -}; -/** - * Mesh for a Goldberg Polyhedron which is made from 12 pentagonal and the rest hexagonal faces - * @see https://en.wikipedia.org/wiki/Goldberg_polyhedron - */ -class GoldbergMesh extends mesh_Mesh { - constructor() { - super(...arguments); - /** - * Defines the specific Goldberg data used in this mesh construction. - */ - this.goldbergData = { - faceColors: [], - faceCenters: [], - faceZaxis: [], - faceXaxis: [], - faceYaxis: [], - nbSharedFaces: 0, - nbUnsharedFaces: 0, - nbFaces: 0, - nbFacesAtPole: 0, - adjacentFaces: [], - }; - } - /** - * Gets the related Goldberg face from pole infos - * @param poleOrShared Defines the pole index or the shared face index if the fromPole parameter is passed in - * @param fromPole Defines an optional pole index to find the related info from - * @returns the goldberg face number - */ - relatedGoldbergFace(poleOrShared, fromPole) { - if (fromPole === void 0) { - if (poleOrShared > this.goldbergData.nbUnsharedFaces - 1) { - logger_Logger.Warn("Maximum number of unshared faces used"); - poleOrShared = this.goldbergData.nbUnsharedFaces - 1; - } - return this.goldbergData.nbUnsharedFaces + poleOrShared; - } - if (poleOrShared > 11) { - logger_Logger.Warn("Last pole used"); - poleOrShared = 11; - } - if (fromPole > this.goldbergData.nbFacesAtPole - 1) { - logger_Logger.Warn("Maximum number of faces at a pole used"); - fromPole = this.goldbergData.nbFacesAtPole - 1; - } - return 12 + poleOrShared * this.goldbergData.nbFacesAtPole + fromPole; - } - _changeGoldbergFaceColors(colorRange) { - for (let i = 0; i < colorRange.length; i++) { - const min = colorRange[i][0]; - const max = colorRange[i][1]; - const col = colorRange[i][2]; - for (let f = min; f < max + 1; f++) { - this.goldbergData.faceColors[f] = col; - } - } - const newCols = []; - for (let f = 0; f < 12; f++) { - for (let i = 0; i < 5; i++) { - newCols.push(this.goldbergData.faceColors[f].r, this.goldbergData.faceColors[f].g, this.goldbergData.faceColors[f].b, this.goldbergData.faceColors[f].a); - } - } - for (let f = 12; f < this.goldbergData.faceColors.length; f++) { - for (let i = 0; i < 6; i++) { - newCols.push(this.goldbergData.faceColors[f].r, this.goldbergData.faceColors[f].g, this.goldbergData.faceColors[f].b, this.goldbergData.faceColors[f].a); - } - } - return newCols; - } - /** - * Set new goldberg face colors - * @param colorRange the new color to apply to the mesh - */ - setGoldbergFaceColors(colorRange) { - const newCols = this._changeGoldbergFaceColors(colorRange); - this.setVerticesData(buffer_VertexBuffer.ColorKind, newCols); - } - /** - * Updates new goldberg face colors - * @param colorRange the new color to apply to the mesh - */ - updateGoldbergFaceColors(colorRange) { - const newCols = this._changeGoldbergFaceColors(colorRange); - this.updateVerticesData(buffer_VertexBuffer.ColorKind, newCols); - } - _changeGoldbergFaceUVs(uvRange) { - const uvs = this.getVerticesData(buffer_VertexBuffer.UVKind); - for (let i = 0; i < uvRange.length; i++) { - const min = uvRange[i][0]; - const max = uvRange[i][1]; - const center = uvRange[i][2]; - const radius = uvRange[i][3]; - const angle = uvRange[i][4]; - const points5 = []; - const points6 = []; - let u; - let v; - for (let p = 0; p < 5; p++) { - u = center.x + radius * Math.cos(angle + (p * Math.PI) / 2.5); - v = center.y + radius * Math.sin(angle + (p * Math.PI) / 2.5); - if (u < 0) { - u = 0; - } - if (u > 1) { - u = 1; - } - points5.push(u, v); - } - for (let p = 0; p < 6; p++) { - u = center.x + radius * Math.cos(angle + (p * Math.PI) / 3); - v = center.y + radius * Math.sin(angle + (p * Math.PI) / 3); - if (u < 0) { - u = 0; - } - if (u > 1) { - u = 1; - } - points6.push(u, v); - } - for (let f = min; f < Math.min(12, max + 1); f++) { - for (let p = 0; p < 5; p++) { - uvs[10 * f + 2 * p] = points5[2 * p]; - uvs[10 * f + 2 * p + 1] = points5[2 * p + 1]; - } - } - for (let f = Math.max(12, min); f < max + 1; f++) { - for (let p = 0; p < 6; p++) { - //120 + 12 * (f - 12) = 12 * f - 24 - uvs[12 * f - 24 + 2 * p] = points6[2 * p]; - uvs[12 * f - 23 + 2 * p] = points6[2 * p + 1]; - } - } - } - return uvs; - } - /** - * set new goldberg face UVs - * @param uvRange the new UVs to apply to the mesh - */ - setGoldbergFaceUVs(uvRange) { - const newUVs = this._changeGoldbergFaceUVs(uvRange); - this.setVerticesData(buffer_VertexBuffer.UVKind, newUVs); - } - /** - * Updates new goldberg face UVs - * @param uvRange the new UVs to apply to the mesh - */ - updateGoldbergFaceUVs(uvRange) { - const newUVs = this._changeGoldbergFaceUVs(uvRange); - this.updateVerticesData(buffer_VertexBuffer.UVKind, newUVs); - } - /** - * Places a mesh on a particular face of the goldberg polygon - * @param mesh Defines the mesh to position - * @param face Defines the face to position onto - * @param position Defines the position relative to the face we are positioning the mesh onto - */ - placeOnGoldbergFaceAt(mesh, face, position) { - const orientation = math_vector_Vector3.RotationFromAxis(this.goldbergData.faceXaxis[face], this.goldbergData.faceYaxis[face], this.goldbergData.faceZaxis[face]); - mesh.rotation = orientation; - mesh.position = this.goldbergData.faceCenters[face] - .add(this.goldbergData.faceXaxis[face].scale(position.x)) - .add(this.goldbergData.faceYaxis[face].scale(position.y)) - .add(this.goldbergData.faceZaxis[face].scale(position.z)); - } - /** - * Serialize current mesh - * @param serializationObject defines the object which will receive the serialization data - */ - serialize(serializationObject) { - super.serialize(serializationObject); - serializationObject.type = "GoldbergMesh"; - const goldbergData = {}; - goldbergData.adjacentFaces = this.goldbergData.adjacentFaces; - goldbergData.nbSharedFaces = this.goldbergData.nbSharedFaces; - goldbergData.nbUnsharedFaces = this.goldbergData.nbUnsharedFaces; - goldbergData.nbFaces = this.goldbergData.nbFaces; - goldbergData.nbFacesAtPole = this.goldbergData.nbFacesAtPole; - if (this.goldbergData.faceColors) { - goldbergData.faceColors = []; - for (const color of this.goldbergData.faceColors) { - goldbergData.faceColors.push(color.asArray()); - } - } - if (this.goldbergData.faceCenters) { - goldbergData.faceCenters = []; - for (const vector of this.goldbergData.faceCenters) { - goldbergData.faceCenters.push(vector.asArray()); - } - } - if (this.goldbergData.faceZaxis) { - goldbergData.faceZaxis = []; - for (const vector of this.goldbergData.faceZaxis) { - goldbergData.faceZaxis.push(vector.asArray()); - } - } - if (this.goldbergData.faceYaxis) { - goldbergData.faceYaxis = []; - for (const vector of this.goldbergData.faceYaxis) { - goldbergData.faceYaxis.push(vector.asArray()); - } - } - if (this.goldbergData.faceXaxis) { - goldbergData.faceXaxis = []; - for (const vector of this.goldbergData.faceXaxis) { - goldbergData.faceXaxis.push(vector.asArray()); - } - } - serializationObject.goldbergData = goldbergData; - } - /** - * Parses a serialized goldberg mesh - * @param parsedMesh the serialized mesh - * @param scene the scene to create the goldberg mesh in - * @returns the created goldberg mesh - */ - static Parse(parsedMesh, scene) { - const goldbergData = parsedMesh.goldbergData; - goldbergData.faceColors = goldbergData.faceColors.map((el) => math_color_Color4.FromArray(el)); - goldbergData.faceCenters = goldbergData.faceCenters.map((el) => math_vector_Vector3.FromArray(el)); - goldbergData.faceZaxis = goldbergData.faceZaxis.map((el) => math_vector_Vector3.FromArray(el)); - goldbergData.faceXaxis = goldbergData.faceXaxis.map((el) => math_vector_Vector3.FromArray(el)); - goldbergData.faceYaxis = goldbergData.faceYaxis.map((el) => math_vector_Vector3.FromArray(el)); - const goldberg = new GoldbergMesh(parsedMesh.name, scene); - goldberg.goldbergData = goldbergData; - return goldberg; - } -} -//# sourceMappingURL=goldbergMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/goldbergBuilder.js - - - - - - - - -/** - * Creates the Mesh for a Goldberg Polyhedron - * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty - * @param goldbergData polyhedronData defining the Goldberg polyhedron - * @returns GoldbergSphere mesh - */ -function CreateGoldbergVertexData(options, goldbergData) { - const size = options.size; - const sizeX = options.sizeX || size || 1; - const sizeY = options.sizeY || size || 1; - const sizeZ = options.sizeZ || size || 1; - const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || mesh_vertexData_VertexData.DEFAULTSIDE; - const positions = new Array(); - const indices = new Array(); - const normals = new Array(); - const uvs = new Array(); - let minX = Infinity; - let maxX = -Infinity; - let minY = Infinity; - let maxY = -Infinity; - for (let v = 0; v < goldbergData.vertex.length; v++) { - minX = Math.min(minX, goldbergData.vertex[v][0] * sizeX); - maxX = Math.max(maxX, goldbergData.vertex[v][0] * sizeX); - minY = Math.min(minY, goldbergData.vertex[v][1] * sizeY); - maxY = Math.max(maxY, goldbergData.vertex[v][1] * sizeY); - } - let index = 0; - for (let f = 0; f < goldbergData.face.length; f++) { - const verts = goldbergData.face[f]; - const a = math_vector_Vector3.FromArray(goldbergData.vertex[verts[0]]); - const b = math_vector_Vector3.FromArray(goldbergData.vertex[verts[2]]); - const c = math_vector_Vector3.FromArray(goldbergData.vertex[verts[1]]); - const ba = b.subtract(a); - const ca = c.subtract(a); - const norm = math_vector_Vector3.Cross(ca, ba).normalize(); - for (let v = 0; v < verts.length; v++) { - normals.push(norm.x, norm.y, norm.z); - const pdata = goldbergData.vertex[verts[v]]; - positions.push(pdata[0] * sizeX, pdata[1] * sizeY, pdata[2] * sizeZ); - const vCoord = (pdata[1] * sizeY - minY) / (maxY - minY); - uvs.push((pdata[0] * sizeX - minX) / (maxX - minX), CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - vCoord : vCoord); - } - for (let v = 0; v < verts.length - 2; v++) { - indices.push(index, index + v + 2, index + v + 1); - } - index += verts.length; - } - mesh_vertexData_VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs); - const vertexData = new mesh_vertexData_VertexData(); - vertexData.positions = positions; - vertexData.indices = indices; - vertexData.normals = normals; - vertexData.uvs = uvs; - return vertexData; -} -/** - * Creates the Mesh for a Goldberg Polyhedron which is made from 12 pentagonal and the rest hexagonal faces - * @see https://en.wikipedia.org/wiki/Goldberg_polyhedron - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra/goldberg_poly - * @param name defines the name of the mesh - * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty - * @param scene defines the hosting scene - * @returns Goldberg mesh - */ -function CreateGoldberg(name, options, scene = null) { - const size = options.size; - const sizeX = options.sizeX || size || 1; - const sizeY = options.sizeY || size || 1; - const sizeZ = options.sizeZ || size || 1; - let m = options.m || 1; - if (m !== Math.floor(m)) { - m === Math.floor(m); - logger_Logger.Warn("m not an integer only floor(m) used"); - } - let n = options.n || 0; - if (n !== Math.floor(n)) { - n === Math.floor(n); - logger_Logger.Warn("n not an integer only floor(n) used"); - } - if (n > m) { - const temp = n; - n = m; - m = temp; - logger_Logger.Warn("n > m therefore m and n swapped"); - } - const primTri = new _PrimaryIsoTriangle(); - primTri.build(m, n); - const geodesicData = GeodesicData.BuildGeodesicData(primTri); - const goldbergData = geodesicData.toGoldbergPolyhedronData(); - const goldberg = new GoldbergMesh(name, scene); - options.sideOrientation = mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation); - goldberg._originalBuilderSideOrientation = options.sideOrientation; - const vertexData = CreateGoldbergVertexData(options, goldbergData); - vertexData.applyToMesh(goldberg, options.updatable); - goldberg.goldbergData.nbSharedFaces = geodesicData.sharedNodes; - goldberg.goldbergData.nbUnsharedFaces = geodesicData.poleNodes; - goldberg.goldbergData.adjacentFaces = geodesicData.adjacentFaces; - goldberg.goldbergData.nbFaces = goldberg.goldbergData.nbSharedFaces + goldberg.goldbergData.nbUnsharedFaces; - goldberg.goldbergData.nbFacesAtPole = (goldberg.goldbergData.nbUnsharedFaces - 12) / 12; - for (let f = 0; f < geodesicData.vertex.length; f++) { - goldberg.goldbergData.faceCenters.push(math_vector_Vector3.FromArray(geodesicData.vertex[f])); - goldberg.goldbergData.faceCenters[f].x *= sizeX; - goldberg.goldbergData.faceCenters[f].y *= sizeY; - goldberg.goldbergData.faceCenters[f].z *= sizeZ; - goldberg.goldbergData.faceColors.push(new math_color_Color4(1, 1, 1, 1)); - } - for (let f = 0; f < goldbergData.face.length; f++) { - const verts = goldbergData.face[f]; - const a = math_vector_Vector3.FromArray(goldbergData.vertex[verts[0]]); - const b = math_vector_Vector3.FromArray(goldbergData.vertex[verts[2]]); - const c = math_vector_Vector3.FromArray(goldbergData.vertex[verts[1]]); - const ba = b.subtract(a); - const ca = c.subtract(a); - const norm = math_vector_Vector3.Cross(ca, ba).normalize(); - const z = math_vector_Vector3.Cross(ca, norm).normalize(); - goldberg.goldbergData.faceXaxis.push(ca.normalize()); - goldberg.goldbergData.faceYaxis.push(norm); - goldberg.goldbergData.faceZaxis.push(z); - } - return goldberg; -} -//# sourceMappingURL=goldbergBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/textBuilder.js - - - - -// Shape functions -class ShapePath { - /** Create the ShapePath used to support glyphs */ - constructor(resolution) { - this._paths = []; - this._tempPaths = []; - this._holes = []; - this._resolution = resolution; - } - /** Move the virtual cursor to a coordinate */ - moveTo(x, y) { - this._currentPath = new math_path_Path2(x, y); - this._tempPaths.push(this._currentPath); - } - /** Draw a line from the virtual cursor to a given coordinate */ - lineTo(x, y) { - this._currentPath.addLineTo(x, y); - } - /** Create a quadratic curve from the virtual cursor to a given coordinate */ - quadraticCurveTo(cpx, cpy, x, y) { - this._currentPath.addQuadraticCurveTo(cpx, cpy, x, y, this._resolution); - } - /** Create a bezier curve from the virtual cursor to a given coordinate */ - bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y) { - this._currentPath.addBezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y, this._resolution); - } - /** Extract holes based on CW / CCW */ - extractHoles() { - for (const path of this._tempPaths) { - if (path.area() > 0) { - this._holes.push(path); - } - else { - this._paths.push(path); - } - } - if (!this._paths.length && this._holes.length) { - const temp = this._holes; - this._holes = this._paths; - this._paths = temp; - } - this._tempPaths.length = 0; - } - /** Gets the list of paths */ - get paths() { - return this._paths; - } - /** Gets the list of holes */ - get holes() { - return this._holes; - } -} -// Utility functions -function CreateShapePath(char, scale, offsetX, offsetY, resolution, fontData) { - const glyph = fontData.glyphs[char] || fontData.glyphs["?"]; - if (!glyph) { - // return if there is no glyph data - return null; - } - const shapePath = new ShapePath(resolution); - if (glyph.o) { - const outline = glyph.o.split(" "); - for (let i = 0, l = outline.length; i < l;) { - const action = outline[i++]; - switch (action) { - case "m": { - // moveTo - const x = parseInt(outline[i++]) * scale + offsetX; - const y = parseInt(outline[i++]) * scale + offsetY; - shapePath.moveTo(x, y); - break; - } - case "l": { - // lineTo - const x = parseInt(outline[i++]) * scale + offsetX; - const y = parseInt(outline[i++]) * scale + offsetY; - shapePath.lineTo(x, y); - break; - } - case "q": { - // quadraticCurveTo - const cpx = parseInt(outline[i++]) * scale + offsetX; - const cpy = parseInt(outline[i++]) * scale + offsetY; - const cpx1 = parseInt(outline[i++]) * scale + offsetX; - const cpy1 = parseInt(outline[i++]) * scale + offsetY; - shapePath.quadraticCurveTo(cpx1, cpy1, cpx, cpy); - break; - } - case "b": { - // bezierCurveTo - const cpx = parseInt(outline[i++]) * scale + offsetX; - const cpy = parseInt(outline[i++]) * scale + offsetY; - const cpx1 = parseInt(outline[i++]) * scale + offsetX; - const cpy1 = parseInt(outline[i++]) * scale + offsetY; - const cpx2 = parseInt(outline[i++]) * scale + offsetX; - const cpy2 = parseInt(outline[i++]) * scale + offsetY; - shapePath.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy); - break; - } - } - } - } - // Extract holes (based on clockwise data) - shapePath.extractHoles(); - return { offsetX: glyph.ha * scale, shapePath: shapePath }; -} -/** - * Creates shape paths from a text and font - * @param text the text - * @param size size of the font - * @param resolution resolution of the font - * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/) - * @returns array of ShapePath objects - */ -function CreateTextShapePaths(text, size, resolution, fontData) { - const chars = Array.from(text); - const scale = size / fontData.resolution; - const line_height = (fontData.boundingBox.yMax - fontData.boundingBox.yMin + fontData.underlineThickness) * scale; - const shapePaths = []; - let offsetX = 0, offsetY = 0; - for (let i = 0; i < chars.length; i++) { - const char = chars[i]; - if (char === "\n") { - offsetX = 0; - offsetY -= line_height; - } - else { - const ret = CreateShapePath(char, scale, offsetX, offsetY, resolution, fontData); - if (ret) { - offsetX += ret.offsetX; - shapePaths.push(ret.shapePath); - } - } - } - return shapePaths; -} -/** - * Create a text mesh - * @param name defines the name of the mesh - * @param text defines the text to use to build the mesh - * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/) - * @param options defines options used to create the mesh - * @param scene defines the hosting scene - * @param earcutInjection can be used to inject your own earcut reference - * @returns a new Mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/text - */ -function CreateText(name, text, fontData, options = { - size: 50, - resolution: 8, - depth: 1.0, -}, scene = null, earcutInjection = earcut) { - var _a, _b; - // First we need to generate the paths - const shapePaths = CreateTextShapePaths(text, options.size || 50, options.resolution || 8, fontData); - // And extrude them - const meshes = []; - let letterIndex = 0; - for (const shapePath of shapePaths) { - if (!shapePath.paths.length) { - continue; - } - const holes = shapePath.holes.slice(); // Copy it as we will update the copy - for (const path of shapePath.paths) { - const holeVectors = []; - const shapeVectors = []; - const points = path.getPoints(); - for (const point of points) { - shapeVectors.push(new math_vector_Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane - } - // Holes - const localHolesCopy = holes.slice(); - for (const hole of localHolesCopy) { - const points = hole.getPoints(); - let found = false; - for (const point of points) { - if (path.isPointInside(point)) { - found = true; - break; - } - } - if (!found) { - continue; - } - const holePoints = []; - for (const point of points) { - holePoints.push(new math_vector_Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane - } - holeVectors.push(holePoints); - // Remove the hole as it was already used - holes.splice(holes.indexOf(hole), 1); - } - // There is at least a hole but it was unaffected - if (!holeVectors.length && holes.length) { - for (const hole of holes) { - const points = hole.getPoints(); - const holePoints = []; - for (const point of points) { - holePoints.push(new math_vector_Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane - } - holeVectors.push(holePoints); - } - } - // Extrusion! - const mesh = ExtrudePolygon(name, { - shape: shapeVectors, - holes: holeVectors.length ? holeVectors : undefined, - depth: options.depth || 1.0, - faceUV: options.faceUV || ((_a = options.perLetterFaceUV) === null || _a === void 0 ? void 0 : _a.call(options, letterIndex)), - faceColors: options.faceColors || ((_b = options.perLetterFaceColors) === null || _b === void 0 ? void 0 : _b.call(options, letterIndex)), - sideOrientation: mesh_Mesh._GetDefaultSideOrientation(options.sideOrientation || mesh_Mesh.DOUBLESIDE), - }, scene, earcutInjection); - meshes.push(mesh); - letterIndex++; - } - } - // Then we can merge everyone into one single mesh - const newMesh = mesh_Mesh.MergeMeshes(meshes, true, true); - if (newMesh) { - // Move pivot to center - const bbox = newMesh === null || newMesh === void 0 ? void 0 : newMesh.getBoundingInfo(); - newMesh.position.x = -(bbox === null || bbox === void 0 ? void 0 : bbox.boundingBox.extendSizeWorld._x); - newMesh.position.y = -(bbox === null || bbox === void 0 ? void 0 : bbox.boundingBox.extendSizeWorld._y); - newMesh.position.z = -(bbox === null || bbox === void 0 ? void 0 : bbox.boundingBox.extendSizeWorld._z); - newMesh.name = name; - newMesh.rotation.x = -Math.PI / 2; - newMesh.bakeCurrentTransformIntoVertices(); - } - return newMesh; -} -//# sourceMappingURL=textBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/meshBuilder.js -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - - - - - - - - - - - - - - - - -/** - * Class containing static functions to help procedurally build meshes - */ -const meshBuilder_MeshBuilder = { - CreateBox: boxBuilder_CreateBox, - CreateTiledBox: CreateTiledBox, - CreateSphere: sphereBuilder_CreateSphere, - CreateDisc: discBuilder_CreateDisc, - CreateIcoSphere: CreateIcoSphere, - CreateRibbon: CreateRibbon, - CreateCylinder: cylinderBuilder_CreateCylinder, - CreateTorus: CreateTorus, - CreateTorusKnot: CreateTorusKnot, - CreateLineSystem: CreateLineSystem, - CreateLines: linesBuilder_CreateLines, - CreateDashedLines: CreateDashedLines, - ExtrudeShape: ExtrudeShape, - ExtrudeShapeCustom: ExtrudeShapeCustom, - CreateLathe: CreateLathe, - CreateTiledPlane: CreateTiledPlane, - CreatePlane: planeBuilder_CreatePlane, - CreateGround: CreateGround, - CreateTiledGround: CreateTiledGround, - CreateGroundFromHeightMap: CreateGroundFromHeightMap, - CreatePolygon: CreatePolygon, - ExtrudePolygon: ExtrudePolygon, - CreateTube: CreateTube, - CreatePolyhedron: polyhedronBuilder_CreatePolyhedron, - CreateGeodesic: CreateGeodesic, - CreateGoldberg: CreateGoldberg, - CreateDecal: CreateDecal, - CreateCapsule: capsuleBuilder_CreateCapsule, - CreateText: CreateText, -}; -//# sourceMappingURL=meshBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Debug/physicsViewer.js - - - - - - - - - - - - - - -/** - * Used to show the physics impostor around the specific mesh - */ -class PhysicsViewer { - /** - * Creates a new PhysicsViewer - * @param scene defines the hosting scene - */ - constructor(scene) { - /** @internal */ - this._impostors = []; - /** @internal */ - this._meshes = []; - /** @internal */ - this._bodies = []; - this._inertiaBodies = []; - /** @internal */ - this._bodyMeshes = []; - /** @internal */ - this._inertiaMeshes = []; - /** @internal */ - this._numMeshes = 0; - /** @internal */ - this._numBodies = 0; - this._numInertiaBodies = 0; - this._debugMeshMeshes = new Array(); - this._scene = scene || EngineStore.LastCreatedScene; - if (!this._scene) { - return; - } - const physicEngine = this._scene.getPhysicsEngine(); - if (physicEngine) { - this._physicsEnginePlugin = physicEngine.getPhysicsPlugin(); - } - this._utilityLayer = new UtilityLayerRenderer(this._scene, false); - this._utilityLayer.pickUtilitySceneFirst = false; - this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true; - } - /** - * Updates the debug meshes of the physics engine. - * - * This code is useful for synchronizing the debug meshes of the physics engine with the physics impostor and mesh. - * It checks if the impostor is disposed and if the plugin version is 1, then it syncs the mesh with the impostor. - * This ensures that the debug meshes are up to date with the physics engine. - */ - _updateDebugMeshes() { - const plugin = this._physicsEnginePlugin; - if ((plugin === null || plugin === void 0 ? void 0 : plugin.getPluginVersion()) === 1) { - this._updateDebugMeshesV1(); - } - else { - this._updateDebugMeshesV2(); - } - } - /** - * Updates the debug meshes of the physics engine. - * - * This method is useful for synchronizing the debug meshes with the physics impostors. - * It iterates through the impostors and meshes, and if the plugin version is 1, it syncs the mesh with the impostor. - * This ensures that the debug meshes accurately reflect the physics impostors, which is important for debugging the physics engine. - */ - _updateDebugMeshesV1() { - const plugin = this._physicsEnginePlugin; - for (let i = 0; i < this._numMeshes; i++) { - const impostor = this._impostors[i]; - if (!impostor) { - continue; - } - if (impostor.isDisposed) { - this.hideImpostor(this._impostors[i--]); - } - else { - if (impostor.type === PhysicsImpostor.MeshImpostor) { - continue; - } - const mesh = this._meshes[i]; - if (mesh && plugin) { - plugin.syncMeshWithImpostor(mesh, impostor); - } - } - } - } - /** - * Updates the debug meshes of the physics engine for V2 plugin. - * - * This method is useful for synchronizing the debug meshes of the physics engine with the current state of the bodies. - * It iterates through the bodies array and updates the debug meshes with the current transform of each body. - * This ensures that the debug meshes accurately reflect the current state of the physics engine. - */ - _updateDebugMeshesV2() { - const plugin = this._physicsEnginePlugin; - for (let i = 0; i < this._numBodies; i++) { - const body = this._bodies[i]; - const transform = this._bodyMeshes[i]; - if (body && transform) { - plugin.syncTransform(body, transform); - } - } - } - _updateInertiaMeshes() { - for (let i = 0; i < this._numInertiaBodies; i++) { - const body = this._inertiaBodies[i]; - const mesh = this._inertiaMeshes[i]; - if (body && mesh) { - this._updateDebugInertia(body, mesh); - } - } - } - _updateDebugInertia(body, inertiaMesh) { - var _a; - const inertiaMatrixRef = Matrix.Identity(); - const transformMatrixRef = Matrix.Identity(); - const finalMatrixRef = Matrix.Identity(); - if (body._pluginDataInstances.length) { - const inertiaAsMesh = inertiaMesh; - const inertiaMeshMatrixData = inertiaAsMesh._thinInstanceDataStorage.matrixData; - const bodyTransformMatrixData = body.transformNode._thinInstanceDataStorage.matrixData; - for (let i = 0; i < body._pluginDataInstances.length; i++) { - const props = body.getMassProperties(i); - this._getMeshDebugInertiaMatrixToRef(props, inertiaMatrixRef); - Matrix.FromArrayToRef(bodyTransformMatrixData, i * 16, transformMatrixRef); - inertiaMatrixRef.multiplyToRef(transformMatrixRef, finalMatrixRef); - finalMatrixRef.copyToArray(inertiaMeshMatrixData, i * 16); - } - inertiaAsMesh.thinInstanceBufferUpdated("matrix"); - } - else { - const props = body.getMassProperties(); - this._getMeshDebugInertiaMatrixToRef(props, inertiaMatrixRef); - (_a = body.transformNode.rotationQuaternion) === null || _a === void 0 ? void 0 : _a.toRotationMatrix(transformMatrixRef); - transformMatrixRef.setTranslation(body.transformNode.position); - if (body.transformNode.parent) { - const parentTransform = body.transformNode.parent.computeWorldMatrix(true); - transformMatrixRef.multiplyToRef(parentTransform, transformMatrixRef); - } - inertiaMatrixRef.multiplyToRef(transformMatrixRef, inertiaMatrixRef); - inertiaMatrixRef.decomposeToTransformNode(inertiaMesh); - } - } - /** - * Renders a specified physic impostor - * @param impostor defines the impostor to render - * @param targetMesh defines the mesh represented by the impostor - * @returns the new debug mesh used to render the impostor - */ - showImpostor(impostor, targetMesh) { - if (!this._scene) { - return null; - } - for (let i = 0; i < this._numMeshes; i++) { - if (this._impostors[i] == impostor) { - return null; - } - } - const debugMesh = this._getDebugMesh(impostor, targetMesh); - if (debugMesh) { - this._impostors[this._numMeshes] = impostor; - this._meshes[this._numMeshes] = debugMesh; - if (this._numMeshes === 0) { - this._renderFunction = this._updateDebugMeshes.bind(this); - this._scene.registerBeforeRender(this._renderFunction); - } - this._numMeshes++; - } - return debugMesh; - } - /** - * Shows a debug mesh for a given physics body. - * @param body The physics body to show. - * @returns The debug mesh, or null if the body is already shown. - * - * This function is useful for visualizing the physics body in the scene. - * It creates a debug mesh for the given body and adds it to the scene. - * It also registers a before render function to update the debug mesh position and rotation. - */ - showBody(body) { - if (!this._scene) { - return null; - } - for (let i = 0; i < this._numBodies; i++) { - if (this._bodies[i] == body) { - return null; - } - } - const debugMesh = this._getDebugBodyMesh(body); - if (debugMesh) { - this._bodies[this._numBodies] = body; - this._bodyMeshes[this._numBodies] = debugMesh; - if (this._numBodies === 0) { - this._renderFunction = this._updateDebugMeshes.bind(this); - this._scene.registerBeforeRender(this._renderFunction); - } - this._numBodies++; - } - return debugMesh; - } - /** - * Shows a debug box corresponding to the inertia of a given body - * @param body - */ - showInertia(body) { - if (!this._scene) { - return null; - } - for (let i = 0; i < this._numInertiaBodies; i++) { - if (this._inertiaBodies[i] == body) { - return null; - } - } - const debugMesh = this._getDebugInertiaMesh(body); - if (debugMesh) { - this._inertiaBodies[this._numInertiaBodies] = body; - this._inertiaMeshes[this._numInertiaBodies] = debugMesh; - if (this._numInertiaBodies === 0) { - this._inertiaRenderFunction = this._updateInertiaMeshes.bind(this); - this._scene.registerBeforeRender(this._inertiaRenderFunction); - } - this._numInertiaBodies++; - } - return debugMesh; - } - /** - * Hides an impostor from the scene. - * @param impostor - The impostor to hide. - * - * This method is useful for hiding an impostor from the scene. It removes the - * impostor from the utility layer scene, disposes the mesh, and removes the - * impostor from the list of impostors. If the impostor is the last one in the - * list, it also unregisters the render function. - */ - hideImpostor(impostor) { - if (!impostor || !this._scene || !this._utilityLayer) { - return; - } - let removed = false; - const utilityLayerScene = this._utilityLayer.utilityLayerScene; - for (let i = 0; i < this._numMeshes; i++) { - if (this._impostors[i] == impostor) { - const mesh = this._meshes[i]; - if (!mesh) { - continue; - } - utilityLayerScene.removeMesh(mesh); - mesh.dispose(); - const index = this._debugMeshMeshes.indexOf(mesh); - if (index > -1) { - this._debugMeshMeshes.splice(index, 1); - } - this._numMeshes--; - if (this._numMeshes > 0) { - this._meshes[i] = this._meshes[this._numMeshes]; - this._impostors[i] = this._impostors[this._numMeshes]; - this._meshes[this._numMeshes] = null; - this._impostors[this._numMeshes] = null; - } - else { - this._meshes[0] = null; - this._impostors[0] = null; - } - removed = true; - break; - } - } - if (removed && this._numMeshes === 0) { - this._scene.unregisterBeforeRender(this._renderFunction); - } - } - /** - * Hides a body from the physics engine. - * @param body - The body to hide. - * - * This function is useful for hiding a body from the physics engine. - * It removes the body from the utility layer scene and disposes the mesh associated with it. - * It also unregisters the render function if the number of bodies is 0. - * This is useful for hiding a body from the physics engine without deleting it. - */ - hideBody(body) { - if (!body || !this._scene || !this._utilityLayer) { - return; - } - let removed = false; - const utilityLayerScene = this._utilityLayer.utilityLayerScene; - for (let i = 0; i < this._numBodies; i++) { - if (this._bodies[i] === body) { - const mesh = this._bodyMeshes[i]; - if (!mesh) { - continue; - } - utilityLayerScene.removeMesh(mesh); - mesh.dispose(); - this._numBodies--; - if (this._numBodies > 0) { - this._bodyMeshes[i] = this._bodyMeshes[this._numBodies]; - this._bodies[i] = this._bodies[this._numBodies]; - this._bodyMeshes[this._numBodies] = null; - this._bodies[this._numBodies] = null; - } - else { - this._bodyMeshes[0] = null; - this._bodies[0] = null; - } - removed = true; - break; - } - } - if (removed && this._numBodies === 0) { - this._scene.unregisterBeforeRender(this._renderFunction); - } - } - hideInertia(body) { - if (!body || !this._scene || !this._utilityLayer) { - return; - } - let removed = false; - const utilityLayerScene = this._utilityLayer.utilityLayerScene; - for (let i = 0; i < this._numInertiaBodies; i++) { - if (this._inertiaBodies[i] === body) { - const mesh = this._inertiaMeshes[i]; - if (!mesh) { - continue; - } - utilityLayerScene.removeMesh(mesh); - mesh.dispose(); - this._inertiaBodies.splice(i, 1); - this._inertiaMeshes.splice(i, 1); - this._numInertiaBodies--; - removed = true; - break; - } - } - if (removed && this._numInertiaBodies === 0) { - this._scene.unregisterBeforeRender(this._inertiaRenderFunction); - } - } - _getDebugMaterial(scene) { - if (!this._debugMaterial) { - this._debugMaterial = new StandardMaterial("", scene); - this._debugMaterial.wireframe = true; - this._debugMaterial.emissiveColor = Color3.White(); - this._debugMaterial.disableLighting = true; - } - return this._debugMaterial; - } - _getDebugInertiaMaterial(scene) { - if (!this._debugInertiaMaterial) { - this._debugInertiaMaterial = new StandardMaterial("", scene); - this._debugInertiaMaterial.disableLighting = true; - this._debugInertiaMaterial.alpha = 0.0; - } - return this._debugInertiaMaterial; - } - _getDebugBoxMesh(scene) { - if (!this._debugBoxMesh) { - this._debugBoxMesh = CreateBox("physicsBodyBoxViewMesh", { size: 1 }, scene); - this._debugBoxMesh.rotationQuaternion = Quaternion.Identity(); - this._debugBoxMesh.material = this._getDebugMaterial(scene); - this._debugBoxMesh.setEnabled(false); - } - return this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance"); - } - _getDebugSphereMesh(scene) { - if (!this._debugSphereMesh) { - this._debugSphereMesh = CreateSphere("physicsBodySphereViewMesh", { diameter: 1 }, scene); - this._debugSphereMesh.rotationQuaternion = Quaternion.Identity(); - this._debugSphereMesh.material = this._getDebugMaterial(scene); - this._debugSphereMesh.setEnabled(false); - } - return this._debugSphereMesh.createInstance("physicsBodySphereViewInstance"); - } - _getDebugCapsuleMesh(scene) { - if (!this._debugCapsuleMesh) { - this._debugCapsuleMesh = CreateCapsule("physicsBodyCapsuleViewMesh", { height: 1 }, scene); - this._debugCapsuleMesh.rotationQuaternion = Quaternion.Identity(); - this._debugCapsuleMesh.material = this._getDebugMaterial(scene); - this._debugCapsuleMesh.setEnabled(false); - } - return this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance"); - } - _getDebugCylinderMesh(scene) { - if (!this._debugCylinderMesh) { - this._debugCylinderMesh = CreateCylinder("physicsBodyCylinderViewMesh", { diameterTop: 1, diameterBottom: 1, height: 1 }, scene); - this._debugCylinderMesh.rotationQuaternion = Quaternion.Identity(); - this._debugCylinderMesh.material = this._getDebugMaterial(scene); - this._debugCylinderMesh.setEnabled(false); - } - return this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance"); - } - _getDebugMeshMesh(mesh, scene) { - const wireframeOver = new Mesh(mesh.name, scene, null, mesh); - wireframeOver.setParent(mesh); - wireframeOver.position = Vector3.Zero(); - wireframeOver.material = this._getDebugMaterial(scene); - this._debugMeshMeshes.push(wireframeOver); - return wireframeOver; - } - _getDebugMesh(impostor, targetMesh) { - if (!this._utilityLayer) { - return null; - } - // Only create child impostor debug meshes when evaluating the parent - if (targetMesh && targetMesh.parent && targetMesh.parent.physicsImpostor) { - return null; - } - let mesh = null; - const utilityLayerScene = this._utilityLayer.utilityLayerScene; - if (!impostor.physicsBody) { - Logger.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."); - return null; - } - switch (impostor.type) { - case PhysicsImpostor.BoxImpostor: - mesh = this._getDebugBoxMesh(utilityLayerScene); - impostor.getBoxSizeToRef(mesh.scaling); - break; - case PhysicsImpostor.SphereImpostor: { - mesh = this._getDebugSphereMesh(utilityLayerScene); - const radius = impostor.getRadius(); - mesh.scaling.x = radius * 2; - mesh.scaling.y = radius * 2; - mesh.scaling.z = radius * 2; - break; - } - case PhysicsImpostor.CapsuleImpostor: { - mesh = this._getDebugCapsuleMesh(utilityLayerScene); - const bi = impostor.object.getBoundingInfo(); - mesh.scaling.x = (bi.boundingBox.maximum.x - bi.boundingBox.minimum.x) * 2 * impostor.object.scaling.x; - mesh.scaling.y = (bi.boundingBox.maximum.y - bi.boundingBox.minimum.y) * impostor.object.scaling.y; - mesh.scaling.z = (bi.boundingBox.maximum.z - bi.boundingBox.minimum.z) * 2 * impostor.object.scaling.z; - break; - } - case PhysicsImpostor.MeshImpostor: - if (targetMesh) { - mesh = this._getDebugMeshMesh(targetMesh, utilityLayerScene); - } - break; - case PhysicsImpostor.NoImpostor: - if (targetMesh) { - // Handle compound impostors - const childMeshes = targetMesh.getChildMeshes().filter((c) => { - return c.physicsImpostor ? 1 : 0; - }); - childMeshes.forEach((m) => { - if (m.physicsImpostor && m.getClassName() === "Mesh") { - const boundingInfo = m.getBoundingInfo(); - const min = boundingInfo.boundingBox.minimum; - const max = boundingInfo.boundingBox.maximum; - switch (m.physicsImpostor.type) { - case PhysicsImpostor.BoxImpostor: - mesh = this._getDebugBoxMesh(utilityLayerScene); - mesh.position.copyFrom(min); - mesh.position.addInPlace(max); - mesh.position.scaleInPlace(0.5); - break; - case PhysicsImpostor.SphereImpostor: - mesh = this._getDebugSphereMesh(utilityLayerScene); - break; - case PhysicsImpostor.CylinderImpostor: - mesh = this._getDebugCylinderMesh(utilityLayerScene); - break; - default: - mesh = null; - break; - } - if (mesh) { - mesh.scaling.x = max.x - min.x; - mesh.scaling.y = max.y - min.y; - mesh.scaling.z = max.z - min.z; - mesh.parent = m; - } - } - }); - } - else { - Logger.Warn("No target mesh parameter provided for NoImpostor. Skipping."); - } - mesh = null; - break; - case PhysicsImpostor.CylinderImpostor: { - mesh = this._getDebugCylinderMesh(utilityLayerScene); - const bi = impostor.object.getBoundingInfo(); - mesh.scaling.x = (bi.boundingBox.maximum.x - bi.boundingBox.minimum.x) * impostor.object.scaling.x; - mesh.scaling.y = (bi.boundingBox.maximum.y - bi.boundingBox.minimum.y) * impostor.object.scaling.y; - mesh.scaling.z = (bi.boundingBox.maximum.z - bi.boundingBox.minimum.z) * impostor.object.scaling.z; - break; - } - } - return mesh; - } - /** - * Creates a debug mesh for a given physics body - * @param body The physics body to create the debug mesh for - * @returns The created debug mesh or null if the utility layer is not available - * - * This code is useful for creating a debug mesh for a given physics body. - * It creates a Mesh object with a VertexData object containing the positions and indices - * of the geometry of the body. The mesh is then assigned a debug material from the utility layer scene. - * This allows for visualizing the physics body in the scene. - */ - _getDebugBodyMesh(body) { - if (!this._utilityLayer) { - return null; - } - const utilityLayerScene = this._utilityLayer.utilityLayerScene; - const mesh = new Mesh("custom", utilityLayerScene); - const vertexData = new VertexData(); - const geometry = body.getGeometry(); - vertexData.positions = geometry.positions; - vertexData.indices = geometry.indices; - vertexData.applyToMesh(mesh); - if (body._pluginDataInstances) { - const instanceBuffer = new Float32Array(body._pluginDataInstances.length * 16); - mesh.thinInstanceSetBuffer("matrix", instanceBuffer, 16); - } - mesh.material = this._getDebugMaterial(utilityLayerScene); - return mesh; - } - _getMeshDebugInertiaMatrixToRef(massProps, matrix) { - var _a, _b, _c; - const orientation = (_a = massProps.inertiaOrientation) !== null && _a !== void 0 ? _a : Quaternion.Identity(); - const inertiaLocal = (_b = massProps.inertia) !== null && _b !== void 0 ? _b : Vector3.Zero(); - const center = (_c = massProps.centerOfMass) !== null && _c !== void 0 ? _c : Vector3.Zero(); - const betaSqrd = (inertiaLocal.x - inertiaLocal.y + inertiaLocal.z) * 6; - const beta = Math.sqrt(Math.max(betaSqrd, 0)); // Safety check for zeroed elements! - const gammaSqrd = inertiaLocal.x * 12 - betaSqrd; - const gamma = Math.sqrt(Math.max(gammaSqrd, 0)); // Safety check for zeroed elements! - const alphaSqrd = inertiaLocal.z * 12 - betaSqrd; - const alpha = Math.sqrt(Math.max(alphaSqrd, 0)); // Safety check for zeroed elements! - const extents = TmpVectors.Vector3[0]; - extents.set(alpha, beta, gamma); - const scaling = Matrix.ScalingToRef(extents.x, extents.y, extents.z, TmpVectors.Matrix[0]); - const rotation = orientation.toRotationMatrix(TmpVectors.Matrix[1]); - const translation = Matrix.TranslationToRef(center.x, center.y, center.z, TmpVectors.Matrix[2]); - scaling.multiplyToRef(rotation, matrix); - matrix.multiplyToRef(translation, matrix); - return matrix; - } - _getDebugInertiaMesh(body) { - if (!this._utilityLayer) { - return null; - } - const utilityLayerScene = this._utilityLayer.utilityLayerScene; - // The base inertia mesh is going to be a 1x1 cube that's scaled and rotated according to the inertia - const inertiaBoxMesh = MeshBuilder.CreateBox("custom", { size: 1 }, utilityLayerScene); - const matrixRef = Matrix.Identity(); - if (body._pluginDataInstances.length) { - const instanceBuffer = new Float32Array(body._pluginDataInstances.length * 16); - for (let i = 0; i < body._pluginDataInstances.length; ++i) { - const props = body.getMassProperties(i); - this._getMeshDebugInertiaMatrixToRef(props, matrixRef); - matrixRef.copyToArray(instanceBuffer, i * 16); - } - inertiaBoxMesh.thinInstanceSetBuffer("matrix", instanceBuffer, 16); - } - else { - const props = body.getMassProperties(); - this._getMeshDebugInertiaMatrixToRef(props, matrixRef); - matrixRef.decomposeToTransformNode(inertiaBoxMesh); - } - inertiaBoxMesh.enableEdgesRendering(); - inertiaBoxMesh.edgesWidth = 2.0; - inertiaBoxMesh.edgesColor = new Color4(1, 0, 1, 1); - inertiaBoxMesh.material = this._getDebugInertiaMaterial(utilityLayerScene); - return inertiaBoxMesh; - } - /** - * Clean up physics debug display - */ - dispose() { - // impostors - for (let index = this._numMeshes - 1; index >= 0; index--) { - this.hideImpostor(this._impostors[0]); - } - // bodies - for (let index = this._numBodies - 1; index >= 0; index--) { - this.hideBody(this._bodies[0]); - } - // inertia - for (let index = this._numInertiaBodies - 1; index >= 0; index--) { - this.hideInertia(this._inertiaBodies[0]); - } - if (this._debugBoxMesh) { - this._debugBoxMesh.dispose(); - } - if (this._debugSphereMesh) { - this._debugSphereMesh.dispose(); - } - if (this._debugCylinderMesh) { - this._debugCylinderMesh.dispose(); - } - if (this._debugMaterial) { - this._debugMaterial.dispose(); - } - this._impostors.length = 0; - this._scene = null; - this._physicsEnginePlugin = null; - if (this._utilityLayer) { - this._utilityLayer.dispose(); - this._utilityLayer = null; - } - } -} -//# sourceMappingURL=physicsViewer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Debug/rayHelper.js - - -/** - * As raycast might be hard to debug, the RayHelper can help rendering the different rays - * in order to better appreciate the issue one might have. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions#debugging - */ -class RayHelper { - /** - * Helper function to create a colored helper in a scene in one line. - * @param ray Defines the ray we are currently tryin to visualize - * @param scene Defines the scene the ray is used in - * @param color Defines the color we want to see the ray in - * @returns The newly created ray helper. - */ - static CreateAndShow(ray, scene, color) { - const helper = new RayHelper(ray); - helper.show(scene, color); - return helper; - } - /** - * Instantiate a new ray helper. - * As raycast might be hard to debug, the RayHelper can help rendering the different rays - * in order to better appreciate the issue one might have. - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions#debugging - * @param ray Defines the ray we are currently tryin to visualize - */ - constructor(ray) { - this.ray = ray; - } - /** - * Shows the ray we are willing to debug. - * @param scene Defines the scene the ray needs to be rendered in - * @param color Defines the color the ray needs to be rendered in - */ - show(scene, color) { - if (!this._renderFunction && this.ray) { - const ray = this.ray; - this._renderFunction = this._render.bind(this); - this._scene = scene; - this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))]; - this._renderLine = CreateLines("ray", { points: this._renderPoints, updatable: true }, scene); - this._renderLine.isPickable = false; - if (this._renderFunction) { - this._scene.registerBeforeRender(this._renderFunction); - } - } - if (color && this._renderLine) { - this._renderLine.color.copyFrom(color); - } - } - /** - * Hides the ray we are debugging. - */ - hide() { - if (this._renderFunction && this._scene) { - this._scene.unregisterBeforeRender(this._renderFunction); - this._scene = null; - this._renderFunction = null; - if (this._renderLine) { - this._renderLine.dispose(); - this._renderLine = null; - } - this._renderPoints = []; - } - } - _render() { - var _a; - const ray = this.ray; - if (!ray) { - return; - } - const point = this._renderPoints[1]; - const len = Math.min(ray.length, 1000000); - point.copyFrom(ray.direction); - point.scaleInPlace(len); - point.addInPlace(ray.origin); - this._renderPoints[0].copyFrom(ray.origin); - CreateLines("ray", { points: this._renderPoints, updatable: true, instance: this._renderLine }, this._scene); - (_a = this._renderLine) === null || _a === void 0 ? void 0 : _a.refreshBoundingInfo(); - } - /** - * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals. - * @param mesh Defines the mesh we want the helper attached to - * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node) - * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node) - * @param length Defines the length of the ray - */ - attachToMesh(mesh, meshSpaceDirection, meshSpaceOrigin, length) { - this._attachedToMesh = mesh; - const ray = this.ray; - if (!ray) { - return; - } - if (!ray.direction) { - ray.direction = Vector3.Zero(); - } - if (!ray.origin) { - ray.origin = Vector3.Zero(); - } - if (length) { - ray.length = length; - } - if (!meshSpaceOrigin) { - meshSpaceOrigin = Vector3.Zero(); - } - if (!meshSpaceDirection) { - // -1 so that this will work with Mesh.lookAt - meshSpaceDirection = new Vector3(0, 0, -1); - } - if (!this._scene) { - this._scene = mesh.getScene(); - } - if (!this._meshSpaceDirection) { - this._meshSpaceDirection = meshSpaceDirection.clone(); - this._meshSpaceOrigin = meshSpaceOrigin.clone(); - } - else { - this._meshSpaceDirection.copyFrom(meshSpaceDirection); - this._meshSpaceOrigin.copyFrom(meshSpaceOrigin); - } - if (!this._onAfterRenderObserver) { - this._onAfterRenderObserver = this._scene.onBeforeRenderObservable.add(() => this._updateToMesh()); - this._onAfterStepObserver = this._scene.onAfterStepObservable.add(() => this._updateToMesh()); - } - // force world matrix computation before the first ray helper computation - this._attachedToMesh.computeWorldMatrix(true); - this._updateToMesh(); - } - /** - * Detach the ray helper from the mesh it has previously been attached to. - */ - detachFromMesh() { - if (this._attachedToMesh && this._scene) { - if (this._onAfterRenderObserver) { - this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver); - this._scene.onAfterStepObservable.remove(this._onAfterStepObserver); - } - this._attachedToMesh = null; - this._onAfterRenderObserver = null; - this._onAfterStepObserver = null; - this._scene = null; - } - } - _updateToMesh() { - const ray = this.ray; - if (!this._attachedToMesh || !ray) { - return; - } - if (this._attachedToMesh.isDisposed()) { - this.detachFromMesh(); - return; - } - this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction); - Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin); - } - /** - * Dispose the helper and release its associated resources. - */ - dispose() { - this.hide(); - this.detachFromMesh(); - this.ray = null; - } -} -//# sourceMappingURL=rayHelper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Debug/skeletonViewer.js - - - - - - - - - - - - -/** - * Class used to render a debug view of a given skeleton - * @see http://www.babylonjs-playground.com/#1BZJVJ#8 - */ -class SkeletonViewer { - /** public static method to create a BoneWeight Shader - * @param options The constructor options - * @param scene The scene that the shader is scoped to - * @returns The created ShaderMaterial - * @see http://www.babylonjs-playground.com/#1BZJVJ#395 - */ - static CreateBoneWeightShader(options, scene) { - var _a, _c, _d, _e, _f, _g; - const skeleton = options.skeleton; - const colorBase = (_a = options.colorBase) !== null && _a !== void 0 ? _a : math_color_Color3.Black(); - const colorZero = (_c = options.colorZero) !== null && _c !== void 0 ? _c : math_color_Color3.Blue(); - const colorQuarter = (_d = options.colorQuarter) !== null && _d !== void 0 ? _d : math_color_Color3.Green(); - const colorHalf = (_e = options.colorHalf) !== null && _e !== void 0 ? _e : math_color_Color3.Yellow(); - const colorFull = (_f = options.colorFull) !== null && _f !== void 0 ? _f : math_color_Color3.Red(); - const targetBoneIndex = (_g = options.targetBoneIndex) !== null && _g !== void 0 ? _g : 0; - effect_Effect.ShadersStore["boneWeights:" + skeleton.name + "VertexShader"] = `precision highp float; - - attribute vec3 position; - attribute vec2 uv; - - uniform mat4 view; - uniform mat4 projection; - uniform mat4 worldViewProjection; - - #include<bonesDeclaration> - #if NUM_BONE_INFLUENCERS == 0 - attribute vec4 matricesIndices; - attribute vec4 matricesWeights; - #endif - #include<bakedVertexAnimationDeclaration> - - #include<instancesDeclaration> - - varying vec3 vColor; - - uniform vec3 colorBase; - uniform vec3 colorZero; - uniform vec3 colorQuarter; - uniform vec3 colorHalf; - uniform vec3 colorFull; - - uniform float targetBoneIndex; - - void main() { - vec3 positionUpdated = position; - - #include<instancesVertex> - #include<bonesVertex> - #include<bakedVertexAnimation> - - vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); - - vec3 color = colorBase; - float totalWeight = 0.; - if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){ - totalWeight += matricesWeights[0]; - } - if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){ - totalWeight += matricesWeights[1]; - } - if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){ - totalWeight += matricesWeights[2]; - } - if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){ - totalWeight += matricesWeights[3]; - } - - color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight)); - color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight)); - color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight)); - color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight)); - vColor = color; - - gl_Position = projection * view * worldPos; - }`; - effect_Effect.ShadersStore["boneWeights:" + skeleton.name + "FragmentShader"] = ` - precision highp float; - varying vec3 vPosition; - - varying vec3 vColor; - - void main() { - vec4 color = vec4(vColor, 1.0); - gl_FragColor = color; - } - `; - const shader = new shaderMaterial_ShaderMaterial("boneWeight:" + skeleton.name, scene, { - vertex: "boneWeights:" + skeleton.name, - fragment: "boneWeights:" + skeleton.name, - }, { - attributes: ["position", "normal", "matricesIndices", "matricesWeights"], - uniforms: [ - "world", - "worldView", - "worldViewProjection", - "view", - "projection", - "viewProjection", - "colorBase", - "colorZero", - "colorQuarter", - "colorHalf", - "colorFull", - "targetBoneIndex", - ], - }); - shader.setColor3("colorBase", colorBase); - shader.setColor3("colorZero", colorZero); - shader.setColor3("colorQuarter", colorQuarter); - shader.setColor3("colorHalf", colorHalf); - shader.setColor3("colorFull", colorFull); - shader.setFloat("targetBoneIndex", targetBoneIndex); - shader.getClassName = () => { - return "BoneWeightShader"; - }; - shader.transparencyMode = material_Material.MATERIAL_OPAQUE; - return shader; - } - /** public static method to create a BoneWeight Shader - * @param options The constructor options - * @param scene The scene that the shader is scoped to - * @returns The created ShaderMaterial - */ - static CreateSkeletonMapShader(options, scene) { - var _a; - const skeleton = options.skeleton; - const colorMap = (_a = options.colorMap) !== null && _a !== void 0 ? _a : [ - { - color: new math_color_Color3(1, 0.38, 0.18), - location: 0, - }, - { - color: new math_color_Color3(0.59, 0.18, 1.0), - location: 0.2, - }, - { - color: new math_color_Color3(0.59, 1, 0.18), - location: 0.4, - }, - { - color: new math_color_Color3(1, 0.87, 0.17), - location: 0.6, - }, - { - color: new math_color_Color3(1, 0.17, 0.42), - location: 0.8, - }, - { - color: new math_color_Color3(0.17, 0.68, 1.0), - location: 1.0, - }, - ]; - const bufferWidth = skeleton.bones.length + 1; - const colorMapBuffer = SkeletonViewer._CreateBoneMapColorBuffer(bufferWidth, colorMap, scene); - const shader = new shaderMaterial_ShaderMaterial("boneWeights:" + skeleton.name, scene, { - vertexSource: `precision highp float; - - attribute vec3 position; - attribute vec2 uv; - - uniform mat4 view; - uniform mat4 projection; - uniform mat4 worldViewProjection; - uniform float colorMap[` + - skeleton.bones.length * 4 + - `]; - - #include<bonesDeclaration> - #if NUM_BONE_INFLUENCERS == 0 - attribute vec4 matricesIndices; - attribute vec4 matricesWeights; - #endif - #include<bakedVertexAnimationDeclaration> - #include<instancesDeclaration> - - varying vec3 vColor; - - void main() { - vec3 positionUpdated = position; - - #include<instancesVertex> - #include<bonesVertex> - #include<bakedVertexAnimation> - - vec3 color = vec3(0.); - bool first = true; - - for (int i = 0; i < 4; i++) { - int boneIdx = int(matricesIndices[i]); - float boneWgt = matricesWeights[i]; - - vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]); - - if (boneWgt > 0.) { - if (first) { - first = false; - color = c; - } else { - color = mix(color, c, boneWgt); - } - } - } - - vColor = color; - - vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); - - gl_Position = projection * view * worldPos; - }`, - fragmentSource: ` - precision highp float; - varying vec3 vColor; - - void main() { - vec4 color = vec4( vColor, 1.0 ); - gl_FragColor = color; - } - `, - }, { - attributes: ["position", "normal", "matricesIndices", "matricesWeights"], - uniforms: ["world", "worldView", "worldViewProjection", "view", "projection", "viewProjection", "colorMap"], - }); - shader.setFloats("colorMap", colorMapBuffer); - shader.getClassName = () => { - return "SkeletonMapShader"; - }; - shader.transparencyMode = material_Material.MATERIAL_OPAQUE; - return shader; - } - /** private static method to create a BoneWeight Shader - * @param size The size of the buffer to create (usually the bone count) - * @param colorMap The gradient data to generate - * @param scene The scene that the shader is scoped to - * @returns an Array of floats from the color gradient values - */ - static _CreateBoneMapColorBuffer(size, colorMap, scene) { - const tempGrad = new dynamicTexture_DynamicTexture("temp", { width: size, height: 1 }, scene, false); - const ctx = tempGrad.getContext(); - const grad = ctx.createLinearGradient(0, 0, size, 0); - colorMap.forEach((stop) => { - grad.addColorStop(stop.location, stop.color.toHexString()); - }); - ctx.fillStyle = grad; - ctx.fillRect(0, 0, size, 1); - tempGrad.update(); - const buffer = []; - const data = ctx.getImageData(0, 0, size, 1).data; - const rUnit = 1 / 255; - for (let i = 0; i < data.length; i++) { - buffer.push(data[i] * rUnit); - } - tempGrad.dispose(); - return buffer; - } - /** Gets the Scene. */ - get scene() { - return this._scene; - } - /** Gets the utilityLayer. */ - get utilityLayer() { - return this._utilityLayer; - } - /** Checks Ready Status. */ - get isReady() { - return this._ready; - } - /** Sets Ready Status. */ - set ready(value) { - this._ready = value; - } - /** Gets the debugMesh */ - get debugMesh() { - return this._debugMesh; - } - /** Sets the debugMesh */ - set debugMesh(value) { - this._debugMesh = value; - } - /** Gets the displayMode */ - get displayMode() { - return this.options.displayMode || SkeletonViewer.DISPLAY_LINES; - } - /** Sets the displayMode */ - set displayMode(value) { - if (value > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) { - value = SkeletonViewer.DISPLAY_LINES; - } - this.options.displayMode = value; - } - /** - * Creates a new SkeletonViewer - * @param skeleton defines the skeleton to render - * @param mesh defines the mesh attached to the skeleton - * @param scene defines the hosting scene - * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) - * @param renderingGroupId defines the rendering group id to use with the viewer - * @param options All of the extra constructor options for the SkeletonViewer - */ - constructor( - /** defines the skeleton to render */ - skeleton, - /** defines the mesh attached to the skeleton */ - mesh, - /** The Scene scope*/ - scene, - /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ - autoUpdateBonesMatrices = true, - /** defines the rendering group id to use with the viewer */ - renderingGroupId = 3, - /** is the options for the viewer */ - options = {}) { - var _a, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; - this.skeleton = skeleton; - this.mesh = mesh; - this.autoUpdateBonesMatrices = autoUpdateBonesMatrices; - this.renderingGroupId = renderingGroupId; - this.options = options; - /** Gets or sets the color used to render the skeleton */ - this.color = math_color_Color3.White(); - /** Array of the points of the skeleton fo the line view. */ - this._debugLines = new Array(); - /** The local axes Meshes. */ - this._localAxes = null; - /** If SkeletonViewer is enabled. */ - this._isEnabled = true; - /** SkeletonViewer render observable. */ - this._obs = null; - this._scene = scene; - this._ready = false; - //Defaults - options.pauseAnimations = (_a = options.pauseAnimations) !== null && _a !== void 0 ? _a : true; - options.returnToRest = (_c = options.returnToRest) !== null && _c !== void 0 ? _c : false; - options.displayMode = (_d = options.displayMode) !== null && _d !== void 0 ? _d : SkeletonViewer.DISPLAY_LINES; - options.displayOptions = (_e = options.displayOptions) !== null && _e !== void 0 ? _e : {}; - options.displayOptions.midStep = (_f = options.displayOptions.midStep) !== null && _f !== void 0 ? _f : 0.235; - options.displayOptions.midStepFactor = (_g = options.displayOptions.midStepFactor) !== null && _g !== void 0 ? _g : 0.155; - options.displayOptions.sphereBaseSize = (_h = options.displayOptions.sphereBaseSize) !== null && _h !== void 0 ? _h : 0.15; - options.displayOptions.sphereScaleUnit = (_j = options.displayOptions.sphereScaleUnit) !== null && _j !== void 0 ? _j : 2; - options.displayOptions.sphereFactor = (_k = options.displayOptions.sphereFactor) !== null && _k !== void 0 ? _k : 0.865; - options.displayOptions.spurFollowsChild = (_l = options.displayOptions.spurFollowsChild) !== null && _l !== void 0 ? _l : false; - options.displayOptions.showLocalAxes = (_m = options.displayOptions.showLocalAxes) !== null && _m !== void 0 ? _m : false; - options.displayOptions.localAxesSize = (_o = options.displayOptions.localAxesSize) !== null && _o !== void 0 ? _o : 0.075; - options.computeBonesUsingShaders = (_p = options.computeBonesUsingShaders) !== null && _p !== void 0 ? _p : true; - options.useAllBones = (_q = options.useAllBones) !== null && _q !== void 0 ? _q : true; - const initialMeshBoneIndices = mesh.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind); - const initialMeshBoneWeights = mesh.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind); - this._boneIndices = new Set(); - if (!options.useAllBones) { - if (initialMeshBoneIndices && initialMeshBoneWeights) { - for (let i = 0; i < initialMeshBoneIndices.length; ++i) { - const index = initialMeshBoneIndices[i], weight = initialMeshBoneWeights[i]; - if (weight !== 0) { - this._boneIndices.add(index); - } - } - } - } - /* Create Utility Layer */ - this._utilityLayer = new utilityLayerRenderer_UtilityLayerRenderer(this._scene, false); - this._utilityLayer.pickUtilitySceneFirst = false; - this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true; - let displayMode = this.options.displayMode || 0; - if (displayMode > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) { - displayMode = SkeletonViewer.DISPLAY_LINES; - } - this.displayMode = displayMode; - //Prep the Systems - this.update(); - this._bindObs(); - } - /** The Dynamic bindings for the update functions */ - _bindObs() { - switch (this.displayMode) { - case SkeletonViewer.DISPLAY_LINES: { - this._obs = this.scene.onBeforeRenderObservable.add(() => { - this._displayLinesUpdate(); - }); - break; - } - } - } - /** Update the viewer to sync with current skeleton state, only used to manually update. */ - update() { - switch (this.displayMode) { - case SkeletonViewer.DISPLAY_LINES: { - this._displayLinesUpdate(); - break; - } - case SkeletonViewer.DISPLAY_SPHERES: { - this._buildSpheresAndSpurs(true); - break; - } - case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS: { - this._buildSpheresAndSpurs(false); - break; - } - } - this._buildLocalAxes(); - } - /** Gets or sets a boolean indicating if the viewer is enabled */ - set isEnabled(value) { - if (this.isEnabled === value) { - return; - } - this._isEnabled = value; - if (this.debugMesh) { - this.debugMesh.setEnabled(value); - } - if (value && !this._obs) { - this._bindObs(); - } - else if (!value && this._obs) { - this.scene.onBeforeRenderObservable.remove(this._obs); - this._obs = null; - } - } - get isEnabled() { - return this._isEnabled; - } - _getBonePosition(position, bone, meshMat, x = 0, y = 0, z = 0) { - const tmat = math_vector_TmpVectors.Matrix[0]; - const parentBone = bone.getParent(); - tmat.copyFrom(bone.getLocalMatrix()); - if (x !== 0 || y !== 0 || z !== 0) { - const tmat2 = math_vector_TmpVectors.Matrix[1]; - math_vector_Matrix.IdentityToRef(tmat2); - tmat2.setTranslationFromFloats(x, y, z); - tmat2.multiplyToRef(tmat, tmat); - } - if (parentBone) { - tmat.multiplyToRef(parentBone.getAbsoluteMatrix(), tmat); - } - tmat.multiplyToRef(meshMat, tmat); - position.x = tmat.m[12]; - position.y = tmat.m[13]; - position.z = tmat.m[14]; - } - _getLinesForBonesWithLength(bones, meshMat) { - const len = bones.length; - const mesh = this.mesh; - const meshPos = mesh.position; - let idx = 0; - for (let i = 0; i < len; i++) { - const bone = bones[i]; - let points = this._debugLines[idx]; - if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) { - continue; - } - if (!points) { - points = [math_vector_Vector3.Zero(), math_vector_Vector3.Zero()]; - this._debugLines[idx] = points; - } - this._getBonePosition(points[0], bone, meshMat); - this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0); - points[0].subtractInPlace(meshPos); - points[1].subtractInPlace(meshPos); - idx++; - } - } - _getLinesForBonesNoLength(bones) { - const len = bones.length; - let boneNum = 0; - const mesh = this.mesh; - const meshPos = mesh.position; - for (let i = len - 1; i >= 0; i--) { - const childBone = bones[i]; - const parentBone = childBone.getParent(); - if (!parentBone || (!this._boneIndices.has(childBone.getIndex()) && !this.options.useAllBones)) { - continue; - } - let points = this._debugLines[boneNum]; - if (!points) { - points = [math_vector_Vector3.Zero(), math_vector_Vector3.Zero()]; - this._debugLines[boneNum] = points; - } - childBone.getAbsolutePositionToRef(mesh, points[0]); - parentBone.getAbsolutePositionToRef(mesh, points[1]); - points[0].subtractInPlace(meshPos); - points[1].subtractInPlace(meshPos); - boneNum++; - } - } - /** - * function to revert the mesh and scene back to the initial state. - * @param animationState - */ - _revert(animationState) { - if (this.options.pauseAnimations) { - this.scene.animationsEnabled = animationState; - this.utilityLayer.utilityLayerScene.animationsEnabled = animationState; - } - } - /** - * function to get the absolute bind pose of a bone by accumulating transformations up the bone hierarchy. - * @param bone - * @param matrix - */ - _getAbsoluteBindPoseToRef(bone, matrix) { - if (bone === null || bone._index === -1) { - matrix.copyFrom(math_vector_Matrix.Identity()); - return; - } - this._getAbsoluteBindPoseToRef(bone.getParent(), matrix); - bone.getBindMatrix().multiplyToRef(matrix, matrix); - return; - } - /** - * function to build and bind sphere joint points and spur bone representations. - * @param spheresOnly - */ - _buildSpheresAndSpurs(spheresOnly = true) { - var _a, _c; - if (this._debugMesh) { - this._debugMesh.dispose(); - this._debugMesh = null; - this.ready = false; - } - this._ready = false; - const utilityLayerScene = (_a = this.utilityLayer) === null || _a === void 0 ? void 0 : _a.utilityLayerScene; - const bones = this.skeleton.bones; - const spheres = []; - const spurs = []; - const animationState = this.scene.animationsEnabled; - try { - if (this.options.pauseAnimations) { - this.scene.animationsEnabled = false; - utilityLayerScene.animationsEnabled = false; - } - if (this.options.returnToRest) { - this.skeleton.returnToRest(); - } - if (this.autoUpdateBonesMatrices) { - this.skeleton.computeAbsoluteMatrices(); - } - let longestBoneLength = Number.NEGATIVE_INFINITY; - const displayOptions = this.options.displayOptions || {}; - for (let i = 0; i < bones.length; i++) { - const bone = bones[i]; - if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) { - continue; - } - const boneAbsoluteBindPoseTransform = new math_vector_Matrix(); - this._getAbsoluteBindPoseToRef(bone, boneAbsoluteBindPoseTransform); - const anchorPoint = new math_vector_Vector3(); - boneAbsoluteBindPoseTransform.decompose(undefined, undefined, anchorPoint); - bone.children.forEach((bc) => { - const childAbsoluteBindPoseTransform = new math_vector_Matrix(); - bc.getLocalMatrix().multiplyToRef(boneAbsoluteBindPoseTransform, childAbsoluteBindPoseTransform); - const childPoint = new math_vector_Vector3(); - childAbsoluteBindPoseTransform.decompose(undefined, undefined, childPoint); - const distanceFromParent = math_vector_Vector3.Distance(anchorPoint, childPoint); - if (distanceFromParent > longestBoneLength) { - longestBoneLength = distanceFromParent; - } - if (spheresOnly) { - return; - } - const dir = childPoint.clone().subtract(anchorPoint.clone()); - const h = dir.length(); - const up = dir.normalize().scale(h); - const midStep = displayOptions.midStep || 0.165; - const midStepFactor = displayOptions.midStepFactor || 0.215; - const up0 = up.scale(midStep); - const spur = ExtrudeShapeCustom("skeletonViewer", { - shape: [new math_vector_Vector3(1, -1, 0), new math_vector_Vector3(1, 1, 0), new math_vector_Vector3(-1, 1, 0), new math_vector_Vector3(-1, -1, 0), new math_vector_Vector3(1, -1, 0)], - path: [math_vector_Vector3.Zero(), up0, up], - scaleFunction: (i) => { - switch (i) { - case 0: - case 2: - return 0; - case 1: - return h * midStepFactor; - } - return 0; - }, - sideOrientation: mesh_Mesh.DEFAULTSIDE, - updatable: false, - }, utilityLayerScene); - const numVertices = spur.getTotalVertices(); - const mwk = [], mik = []; - for (let i = 0; i < numVertices; i++) { - mwk.push(1, 0, 0, 0); - // Select verts at end of spur (ie vert 10 to 14) and bind to child - // bone if spurFollowsChild is enabled. - if (displayOptions.spurFollowsChild && i > 9) { - mik.push(bc.getIndex(), 0, 0, 0); - } - else { - mik.push(bone.getIndex(), 0, 0, 0); - } - } - spur.position = anchorPoint.clone(); - spur.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind, mwk, false); - spur.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind, mik, false); - spur.convertToFlatShadedMesh(); - spurs.push(spur); - }); - const sphereBaseSize = displayOptions.sphereBaseSize || 0.2; - const sphere = sphereBuilder_CreateSphere("skeletonViewer", { - segments: 6, - diameter: sphereBaseSize, - updatable: true, - }, utilityLayerScene); - const numVertices = sphere.getTotalVertices(); - const mwk = [], mik = []; - for (let i = 0; i < numVertices; i++) { - mwk.push(1, 0, 0, 0); - mik.push(bone.getIndex(), 0, 0, 0); - } - sphere.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind, mwk, false); - sphere.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind, mik, false); - sphere.position = anchorPoint.clone(); - spheres.push([sphere, bone]); - } - const sphereScaleUnit = displayOptions.sphereScaleUnit || 2; - const sphereFactor = displayOptions.sphereFactor || 0.85; - const meshes = []; - for (let i = 0; i < spheres.length; i++) { - const [sphere, bone] = spheres[i]; - const scale = 1 / (sphereScaleUnit / longestBoneLength); - let _stepsOut = 0; - let _b = bone; - while (_b.getParent() && _b.getParent().getIndex() !== -1) { - _stepsOut++; - _b = _b.getParent(); - } - sphere.scaling.scaleInPlace(scale * Math.pow(sphereFactor, _stepsOut)); - meshes.push(sphere); - } - this.debugMesh = mesh_Mesh.MergeMeshes(meshes.concat(spurs), true, true); - if (this.debugMesh) { - this.debugMesh.renderingGroupId = this.renderingGroupId; - this.debugMesh.skeleton = this.skeleton; - this.debugMesh.parent = this.mesh; - this.debugMesh.computeBonesUsingShaders = (_c = this.options.computeBonesUsingShaders) !== null && _c !== void 0 ? _c : true; - this.debugMesh.alwaysSelectAsActiveMesh = true; - } - const light = this.utilityLayer._getSharedGizmoLight(); - light.intensity = 0.7; - this._revert(animationState); - this.ready = true; - } - catch (err) { - console.error(err); - this._revert(animationState); - this.dispose(); - } - } - _buildLocalAxes() { - var _a; - if (this._localAxes) { - this._localAxes.dispose(); - } - this._localAxes = null; - const displayOptions = this.options.displayOptions || {}; - if (!displayOptions.showLocalAxes) { - return; - } - const targetScene = this._utilityLayer.utilityLayerScene; - const size = displayOptions.localAxesSize || 0.075; - const lines = []; - const colors = []; - const red = new math_color_Color4(1, 0, 0, 1); - const green = new math_color_Color4(0, 1, 0, 1); - const blue = new math_color_Color4(0, 0, 1, 1); - const mwk = []; - const mik = []; - const vertsPerBone = 6; - for (const i in this.skeleton.bones) { - const bone = this.skeleton.bones[i]; - if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) { - continue; - } - const boneAbsoluteBindPoseTransform = new math_vector_Matrix(); - const boneOrigin = new math_vector_Vector3(); - this._getAbsoluteBindPoseToRef(bone, boneAbsoluteBindPoseTransform); - boneAbsoluteBindPoseTransform.decompose(undefined, math_vector_TmpVectors.Quaternion[0], boneOrigin); - const m = new math_vector_Matrix(); - math_vector_TmpVectors.Quaternion[0].toRotationMatrix(m); - const boneAxisX = math_vector_Vector3.TransformCoordinates(new math_vector_Vector3(0 + size, 0, 0), m); - const boneAxisY = math_vector_Vector3.TransformCoordinates(new math_vector_Vector3(0, 0 + size, 0), m); - const boneAxisZ = math_vector_Vector3.TransformCoordinates(new math_vector_Vector3(0, 0, 0 + size), m); - const axisX = [boneOrigin, boneOrigin.add(boneAxisX)]; - const axisY = [boneOrigin, boneOrigin.add(boneAxisY)]; - const axisZ = [boneOrigin, boneOrigin.add(boneAxisZ)]; - const linePoints = [axisX, axisY, axisZ]; - const lineColors = [ - [red, red], - [green, green], - [blue, blue], - ]; - lines.push(...linePoints); - colors.push(...lineColors); - for (let j = 0; j < vertsPerBone; j++) { - mwk.push(1, 0, 0, 0); - mik.push(bone.getIndex(), 0, 0, 0); - } - } - this._localAxes = CreateLineSystem("localAxes", { lines: lines, colors: colors, updatable: true }, targetScene); - this._localAxes.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind, mwk, false); - this._localAxes.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind, mik, false); - this._localAxes.skeleton = this.skeleton; - this._localAxes.renderingGroupId = this.renderingGroupId + 1; - this._localAxes.parent = this.mesh; - this._localAxes.computeBonesUsingShaders = (_a = this.options.computeBonesUsingShaders) !== null && _a !== void 0 ? _a : true; - } - /** Update the viewer to sync with current skeleton state, only used for the line display. */ - _displayLinesUpdate() { - if (!this._utilityLayer) { - return; - } - if (this.autoUpdateBonesMatrices) { - this.skeleton.computeAbsoluteMatrices(); - } - if (this.skeleton.bones[0].length === undefined) { - this._getLinesForBonesNoLength(this.skeleton.bones); - } - else { - this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix()); - } - const targetScene = this._utilityLayer.utilityLayerScene; - if (targetScene) { - if (!this._debugMesh) { - this._debugMesh = CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene); - this._debugMesh.renderingGroupId = this.renderingGroupId; - } - else { - CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene); - } - this._debugMesh.position.copyFrom(this.mesh.position); - this._debugMesh.color = this.color; - } - } - /** Changes the displayMode of the skeleton viewer - * @param mode The displayMode numerical value - */ - changeDisplayMode(mode) { - const wasEnabled = this.isEnabled ? true : false; - if (this.displayMode !== mode) { - this.isEnabled = false; - if (this._debugMesh) { - this._debugMesh.dispose(); - this._debugMesh = null; - this.ready = false; - } - this.displayMode = mode; - this.update(); - this._bindObs(); - this.isEnabled = wasEnabled; - } - } - /** Sets a display option of the skeleton viewer - * - * | Option | Type | Default | Description | - * | ---------------- | ------- | ------- | ----------- | - * | 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`. | - * | 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`. | - * | sphereBaseSize | float | 2 | Sphere base size. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. | - * | 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`. | - * | spurFollowsChild | boolean | false | Whether a spur should attach its far end to the child bone. | - * | showLocalAxes | boolean | false | Displays local axes on all bones. | - * | localAxesSize | float | 0.075 | Determines the length of each local axis. | - * - * @param option String of the option name - * @param value The numerical option value - */ - changeDisplayOptions(option, value) { - const wasEnabled = this.isEnabled ? true : false; - this.options.displayOptions[option] = value; - this.isEnabled = false; - if (this._debugMesh) { - this._debugMesh.dispose(); - this._debugMesh = null; - this.ready = false; - } - this.update(); - this._bindObs(); - this.isEnabled = wasEnabled; - } - /** Release associated resources */ - dispose() { - this.isEnabled = false; - if (this._debugMesh) { - this._debugMesh.dispose(); - this._debugMesh = null; - } - if (this._utilityLayer) { - this._utilityLayer.dispose(); - this._utilityLayer = null; - } - this.ready = false; - } -} -/** public Display constants BABYLON.SkeletonViewer.DISPLAY_LINES */ -SkeletonViewer.DISPLAY_LINES = 0; -/** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERES */ -SkeletonViewer.DISPLAY_SPHERES = 1; -/** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERE_AND_SPURS */ -SkeletonViewer.DISPLAY_SPHERE_AND_SPURS = 2; -//# sourceMappingURL=skeletonViewer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Debug/ISkeletonViewer.js - -//# sourceMappingURL=ISkeletonViewer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Debug/directionalLightFrustumViewer.js - - - - - - - -/** - * Class used to render a debug view of the frustum for a directional light - * @see https://playground.babylonjs.com/#7EFGSG#4 - * @since 5.0.0 - */ -class DirectionalLightFrustumViewer { - /** - * Gets or sets the transparency of the frustum planes - */ - get transparency() { - return this._transparency; - } - set transparency(alpha) { - this._transparency = alpha; - for (let i = 6; i < 12; ++i) { - this._lightHelperFrustumMeshes[i].material.alpha = alpha; - } - } - /** - * true to display the edges of the frustum - */ - get showLines() { - return this._showLines; - } - set showLines(show) { - if (this._showLines === show) { - return; - } - this._showLines = show; - for (let i = 0; i < 6; ++i) { - this._lightHelperFrustumMeshes[i].setEnabled(show); - } - } - /** - * true to display the planes of the frustum - */ - get showPlanes() { - return this._showPlanes; - } - set showPlanes(show) { - if (this._showPlanes === show) { - return; - } - this._showPlanes = show; - for (let i = 6; i < 12; ++i) { - this._lightHelperFrustumMeshes[i].setEnabled(show); - } - } - /** - * Creates a new frustum viewer - * @param light directional light to display the frustum for - * @param camera camera used to retrieve the minZ / maxZ values if the shadowMinZ/shadowMaxZ values of the light are not setup - */ - constructor(light, camera) { - this._oldPosition = new Vector3(Number.NaN, Number.NaN, Number.NaN); - this._oldDirection = new Vector3(Number.NaN, Number.NaN, Number.NaN); - this._transparency = 0.3; - this._showLines = true; - this._showPlanes = true; - this._scene = light.getScene(); - this._light = light; - this._camera = camera; - this._inverseViewMatrix = Matrix.Identity(); - this._lightHelperFrustumMeshes = []; - this._createGeometry(); - this.show(); - this.update(); - } - /** - * Shows the frustum - */ - show() { - this._lightHelperFrustumMeshes.forEach((mesh, index) => { - mesh.setEnabled((index < 6 && this._showLines) || (index >= 6 && this._showPlanes)); - }); - this._oldPosition.set(Number.NaN, Number.NaN, Number.NaN); - this._visible = true; - } - /** - * Hides the frustum - */ - hide() { - this._lightHelperFrustumMeshes.forEach((mesh) => { - mesh.setEnabled(false); - }); - this._visible = false; - } - /** - * Updates the frustum. - * Call this method to update the frustum view if the light has changed position/direction - */ - update() { - var _a, _b, _c, _d, _e, _f; - if (!this._visible) { - return; - } - if (this._oldPosition.equals(this._light.position) && - this._oldDirection.equals(this._light.direction) && - this._oldAutoCalc === this._light.autoCalcShadowZBounds && - this._oldMinZ === this._light.shadowMinZ && - this._oldMaxZ === this._light.shadowMaxZ) { - return; - } - this._oldPosition.copyFrom(this._light.position); - this._oldDirection.copyFrom(this._light.direction); - this._oldAutoCalc = this._light.autoCalcShadowZBounds; - this._oldMinZ = this._light.shadowMinZ; - this._oldMaxZ = this._light.shadowMaxZ; - TmpVectors.Vector3[0].set(this._light.orthoLeft, this._light.orthoBottom, this._light.shadowMinZ !== undefined ? this._light.shadowMinZ : this._camera.minZ); // min light extents - TmpVectors.Vector3[1].set(this._light.orthoRight, this._light.orthoTop, this._light.shadowMaxZ !== undefined ? this._light.shadowMaxZ : this._camera.maxZ); // max light extents - const invLightView = this._getInvertViewMatrix(); - TmpVectors.Vector3[2].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[0].z); // n1 - TmpVectors.Vector3[3].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z); // n2 - TmpVectors.Vector3[4].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z); // n3 - TmpVectors.Vector3[5].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[0].z); // n4 - Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[2], invLightView, TmpVectors.Vector3[2]); // near1 - Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[3], invLightView, TmpVectors.Vector3[3]); // near2 - Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[4], invLightView, TmpVectors.Vector3[4]); // near3 - Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[5], invLightView, TmpVectors.Vector3[5]); // near4 - TmpVectors.Vector3[6].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[1].z); // f1 - TmpVectors.Vector3[7].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[1].z); // f2 - TmpVectors.Vector3[8].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[1].z); // f3 - TmpVectors.Vector3[9].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[1].z); // f4 - Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[6], invLightView, TmpVectors.Vector3[6]); // far1 - Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[7], invLightView, TmpVectors.Vector3[7]); // far2 - Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[8], invLightView, TmpVectors.Vector3[8]); // far3 - Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[9], invLightView, TmpVectors.Vector3[9]); // far4 - CreateLines("nearlines", { updatable: true, points: this._nearLinesPoints, instance: this._lightHelperFrustumMeshes[0] }, this._scene); - CreateLines("farlines", { updatable: true, points: this._farLinesPoints, instance: this._lightHelperFrustumMeshes[1] }, this._scene); - CreateLines("trlines", { updatable: true, points: this._trLinesPoints, instance: this._lightHelperFrustumMeshes[2] }, this._scene); - CreateLines("brlines", { updatable: true, points: this._brLinesPoints, instance: this._lightHelperFrustumMeshes[3] }, this._scene); - CreateLines("tllines", { updatable: true, points: this._tlLinesPoints, instance: this._lightHelperFrustumMeshes[4] }, this._scene); - CreateLines("bllines", { updatable: true, points: this._blLinesPoints, instance: this._lightHelperFrustumMeshes[5] }, this._scene); - TmpVectors.Vector3[2].toArray(this._nearPlaneVertices, 0); - TmpVectors.Vector3[3].toArray(this._nearPlaneVertices, 3); - TmpVectors.Vector3[4].toArray(this._nearPlaneVertices, 6); - TmpVectors.Vector3[5].toArray(this._nearPlaneVertices, 9); - (_a = this._lightHelperFrustumMeshes[6].geometry) === null || _a === void 0 ? void 0 : _a.updateVerticesDataDirectly("position", this._nearPlaneVertices, 0); - TmpVectors.Vector3[6].toArray(this._farPlaneVertices, 0); - TmpVectors.Vector3[7].toArray(this._farPlaneVertices, 3); - TmpVectors.Vector3[8].toArray(this._farPlaneVertices, 6); - TmpVectors.Vector3[9].toArray(this._farPlaneVertices, 9); - (_b = this._lightHelperFrustumMeshes[7].geometry) === null || _b === void 0 ? void 0 : _b.updateVerticesDataDirectly("position", this._farPlaneVertices, 0); - TmpVectors.Vector3[2].toArray(this._rightPlaneVertices, 0); - TmpVectors.Vector3[6].toArray(this._rightPlaneVertices, 3); - TmpVectors.Vector3[7].toArray(this._rightPlaneVertices, 6); - TmpVectors.Vector3[3].toArray(this._rightPlaneVertices, 9); - (_c = this._lightHelperFrustumMeshes[8].geometry) === null || _c === void 0 ? void 0 : _c.updateVerticesDataDirectly("position", this._rightPlaneVertices, 0); - TmpVectors.Vector3[5].toArray(this._leftPlaneVertices, 0); - TmpVectors.Vector3[9].toArray(this._leftPlaneVertices, 3); - TmpVectors.Vector3[8].toArray(this._leftPlaneVertices, 6); - TmpVectors.Vector3[4].toArray(this._leftPlaneVertices, 9); - (_d = this._lightHelperFrustumMeshes[9].geometry) === null || _d === void 0 ? void 0 : _d.updateVerticesDataDirectly("position", this._leftPlaneVertices, 0); - TmpVectors.Vector3[2].toArray(this._topPlaneVertices, 0); - TmpVectors.Vector3[6].toArray(this._topPlaneVertices, 3); - TmpVectors.Vector3[9].toArray(this._topPlaneVertices, 6); - TmpVectors.Vector3[5].toArray(this._topPlaneVertices, 9); - (_e = this._lightHelperFrustumMeshes[10].geometry) === null || _e === void 0 ? void 0 : _e.updateVerticesDataDirectly("position", this._topPlaneVertices, 0); - TmpVectors.Vector3[3].toArray(this._bottomPlaneVertices, 0); - TmpVectors.Vector3[7].toArray(this._bottomPlaneVertices, 3); - TmpVectors.Vector3[8].toArray(this._bottomPlaneVertices, 6); - TmpVectors.Vector3[4].toArray(this._bottomPlaneVertices, 9); - (_f = this._lightHelperFrustumMeshes[11].geometry) === null || _f === void 0 ? void 0 : _f.updateVerticesDataDirectly("position", this._bottomPlaneVertices, 0); - } - /** - * Dispose of the class / remove the frustum view - */ - dispose() { - this._lightHelperFrustumMeshes.forEach((mesh) => { - var _a; - (_a = mesh.material) === null || _a === void 0 ? void 0 : _a.dispose(); - mesh.dispose(); - }); - this._rootNode.dispose(); - } - _createGeometry() { - this._rootNode = new TransformNode("directionalLightHelperRoot_" + this._light.name, this._scene); - this._rootNode.parent = this._light.parent; - this._nearLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly]; - const nearLines = CreateLines("nearlines", { updatable: true, points: this._nearLinesPoints }, this._scene); - nearLines.parent = this._rootNode; - nearLines.alwaysSelectAsActiveMesh = true; - this._farLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly]; - const farLines = CreateLines("farlines", { updatable: true, points: this._farLinesPoints }, this._scene); - farLines.parent = this._rootNode; - farLines.alwaysSelectAsActiveMesh = true; - this._trLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly]; - const trLines = CreateLines("trlines", { updatable: true, points: this._trLinesPoints }, this._scene); - trLines.parent = this._rootNode; - trLines.alwaysSelectAsActiveMesh = true; - this._brLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly]; - const brLines = CreateLines("brlines", { updatable: true, points: this._brLinesPoints }, this._scene); - brLines.parent = this._rootNode; - brLines.alwaysSelectAsActiveMesh = true; - this._tlLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly]; - const tlLines = CreateLines("tllines", { updatable: true, points: this._tlLinesPoints }, this._scene); - tlLines.parent = this._rootNode; - tlLines.alwaysSelectAsActiveMesh = true; - this._blLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly]; - const blLines = CreateLines("bllines", { updatable: true, points: this._blLinesPoints }, this._scene); - blLines.parent = this._rootNode; - blLines.alwaysSelectAsActiveMesh = true; - this._lightHelperFrustumMeshes.push(nearLines, farLines, trLines, brLines, tlLines, blLines); - const makePlane = (name, color, positions) => { - const plane = new Mesh(name + "plane", this._scene); - const mat = new StandardMaterial(name + "PlaneMat", this._scene); - plane.material = mat; - plane.parent = this._rootNode; - plane.alwaysSelectAsActiveMesh = true; - mat.emissiveColor = color; - mat.alpha = this.transparency; - mat.backFaceCulling = false; - mat.disableLighting = true; - const indices = [0, 1, 2, 0, 2, 3]; - const vertexData = new VertexData(); - vertexData.positions = positions; - vertexData.indices = indices; - vertexData.applyToMesh(plane, true); - this._lightHelperFrustumMeshes.push(plane); - }; - this._nearPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - this._farPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - this._rightPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - this._leftPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - this._topPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - this._bottomPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - makePlane("near", new Color3(1, 0, 0), this._nearPlaneVertices); - makePlane("far", new Color3(0.3, 0, 0), this._farPlaneVertices); - makePlane("right", new Color3(0, 1, 0), this._rightPlaneVertices); - makePlane("left", new Color3(0, 0.3, 0), this._leftPlaneVertices); - makePlane("top", new Color3(0, 0, 1), this._topPlaneVertices); - makePlane("bottom", new Color3(0, 0, 0.3), this._bottomPlaneVertices); - this._nearLinesPoints[0] = TmpVectors.Vector3[2]; - this._nearLinesPoints[1] = TmpVectors.Vector3[3]; - this._nearLinesPoints[2] = TmpVectors.Vector3[4]; - this._nearLinesPoints[3] = TmpVectors.Vector3[5]; - this._nearLinesPoints[4] = TmpVectors.Vector3[2]; - this._farLinesPoints[0] = TmpVectors.Vector3[6]; - this._farLinesPoints[1] = TmpVectors.Vector3[7]; - this._farLinesPoints[2] = TmpVectors.Vector3[8]; - this._farLinesPoints[3] = TmpVectors.Vector3[9]; - this._farLinesPoints[4] = TmpVectors.Vector3[6]; - this._trLinesPoints[0] = TmpVectors.Vector3[2]; - this._trLinesPoints[1] = TmpVectors.Vector3[6]; - this._brLinesPoints[0] = TmpVectors.Vector3[3]; - this._brLinesPoints[1] = TmpVectors.Vector3[7]; - this._tlLinesPoints[0] = TmpVectors.Vector3[4]; - this._tlLinesPoints[1] = TmpVectors.Vector3[8]; - this._blLinesPoints[0] = TmpVectors.Vector3[5]; - this._blLinesPoints[1] = TmpVectors.Vector3[9]; - } - _getInvertViewMatrix() { - Matrix.LookAtLHToRef(this._light.position, this._light.position.add(this._light.direction), Vector3.UpReadOnly, this._inverseViewMatrix); - this._inverseViewMatrix.invertToRef(this._inverseViewMatrix); - return this._inverseViewMatrix; - } -} -//# sourceMappingURL=directionalLightFrustumViewer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Debug/index.js - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceTypes.js - -//# sourceMappingURL=deviceTypes.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/DeviceInput/index.js - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/constants.js -/* eslint-disable @typescript-eslint/naming-convention */ -/** Defines the cross module used constants to avoid circular dependencies */ -class Constants { -} -/** Defines that alpha blending is disabled */ -Constants.ALPHA_DISABLE = 0; -/** Defines that alpha blending is SRC ALPHA * SRC + DEST */ -Constants.ALPHA_ADD = 1; -/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */ -Constants.ALPHA_COMBINE = 2; -/** Defines that alpha blending is DEST - SRC * DEST */ -Constants.ALPHA_SUBTRACT = 3; -/** Defines that alpha blending is SRC * DEST */ -Constants.ALPHA_MULTIPLY = 4; -/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC) * DEST */ -Constants.ALPHA_MAXIMIZED = 5; -/** Defines that alpha blending is SRC + DEST */ -Constants.ALPHA_ONEONE = 6; -/** Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST */ -Constants.ALPHA_PREMULTIPLIED = 7; -/** - * Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST - * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA - */ -Constants.ALPHA_PREMULTIPLIED_PORTERDUFF = 8; -/** Defines that alpha blending is CST * SRC + (1 - CST) * DEST */ -Constants.ALPHA_INTERPOLATE = 9; -/** - * Defines that alpha blending is SRC + (1 - SRC) * DEST - * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA - */ -Constants.ALPHA_SCREENMODE = 10; -/** - * Defines that alpha blending is SRC + DST - * Alpha will be set to SRC ALPHA + DST ALPHA - */ -Constants.ALPHA_ONEONE_ONEONE = 11; -/** - * Defines that alpha blending is SRC * DST ALPHA + DST - * Alpha will be set to 0 - */ -Constants.ALPHA_ALPHATOCOLOR = 12; -/** - * Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC) - */ -Constants.ALPHA_REVERSEONEMINUS = 13; -/** - * Defines that alpha blending is SRC + DST * (1 - SRC ALPHA) - * Alpha will be set to SRC ALPHA + DST ALPHA * (1 - SRC ALPHA) - */ -Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA = 14; -/** - * Defines that alpha blending is SRC + DST - * Alpha will be set to SRC ALPHA - */ -Constants.ALPHA_ONEONE_ONEZERO = 15; -/** - * Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC) - * Alpha will be set to DST ALPHA - */ -Constants.ALPHA_EXCLUSION = 16; -/** - * Defines that alpha blending is SRC * SRC ALPHA + DST * (1 - SRC ALPHA) - * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DST ALPHA - */ -Constants.ALPHA_LAYER_ACCUMULATE = 17; -/** Defines that alpha blending equation a SUM */ -Constants.ALPHA_EQUATION_ADD = 0; -/** Defines that alpha blending equation a SUBSTRACTION */ -Constants.ALPHA_EQUATION_SUBSTRACT = 1; -/** Defines that alpha blending equation a REVERSE SUBSTRACTION */ -Constants.ALPHA_EQUATION_REVERSE_SUBTRACT = 2; -/** Defines that alpha blending equation a MAX operation */ -Constants.ALPHA_EQUATION_MAX = 3; -/** Defines that alpha blending equation a MIN operation */ -Constants.ALPHA_EQUATION_MIN = 4; -/** - * Defines that alpha blending equation a DARKEN operation: - * It takes the min of the src and sums the alpha channels. - */ -Constants.ALPHA_EQUATION_DARKEN = 5; -/** Defines that the resource is not delayed*/ -Constants.DELAYLOADSTATE_NONE = 0; -/** Defines that the resource was successfully delay loaded */ -Constants.DELAYLOADSTATE_LOADED = 1; -/** Defines that the resource is currently delay loading */ -Constants.DELAYLOADSTATE_LOADING = 2; -/** Defines that the resource is delayed and has not started loading */ -Constants.DELAYLOADSTATE_NOTLOADED = 4; -// Depth or Stencil test Constants. -/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */ -Constants.NEVER = 0x0200; -/** 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 */ -Constants.ALWAYS = 0x0207; -/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */ -Constants.LESS = 0x0201; -/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */ -Constants.EQUAL = 0x0202; -/** 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 */ -Constants.LEQUAL = 0x0203; -/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */ -Constants.GREATER = 0x0204; -/** 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 */ -Constants.GEQUAL = 0x0206; -/** 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 */ -Constants.NOTEQUAL = 0x0205; -// Stencil Actions Constants. -/** Passed to stencilOperation to specify that stencil value must be kept */ -Constants.KEEP = 0x1e00; -/** Passed to stencilOperation to specify that stencil value must be zero */ -Constants.ZERO = 0x0000; -/** Passed to stencilOperation to specify that stencil value must be replaced */ -Constants.REPLACE = 0x1e01; -/** Passed to stencilOperation to specify that stencil value must be incremented */ -Constants.INCR = 0x1e02; -/** Passed to stencilOperation to specify that stencil value must be decremented */ -Constants.DECR = 0x1e03; -/** Passed to stencilOperation to specify that stencil value must be inverted */ -Constants.INVERT = 0x150a; -/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */ -Constants.INCR_WRAP = 0x8507; -/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */ -Constants.DECR_WRAP = 0x8508; -/** Texture is not repeating outside of 0..1 UVs */ -Constants.TEXTURE_CLAMP_ADDRESSMODE = 0; -/** Texture is repeating outside of 0..1 UVs */ -Constants.TEXTURE_WRAP_ADDRESSMODE = 1; -/** Texture is repeating and mirrored */ -Constants.TEXTURE_MIRROR_ADDRESSMODE = 2; -/** Flag to create a storage texture */ -Constants.TEXTURE_CREATIONFLAG_STORAGE = 1; -/** ALPHA */ -Constants.TEXTUREFORMAT_ALPHA = 0; -/** LUMINANCE */ -Constants.TEXTUREFORMAT_LUMINANCE = 1; -/** LUMINANCE_ALPHA */ -Constants.TEXTUREFORMAT_LUMINANCE_ALPHA = 2; -/** RGB */ -Constants.TEXTUREFORMAT_RGB = 4; -/** RGBA */ -Constants.TEXTUREFORMAT_RGBA = 5; -/** RED */ -Constants.TEXTUREFORMAT_RED = 6; -/** RED (2nd reference) */ -Constants.TEXTUREFORMAT_R = 6; -/** RG */ -Constants.TEXTUREFORMAT_RG = 7; -/** RED_INTEGER */ -Constants.TEXTUREFORMAT_RED_INTEGER = 8; -/** RED_INTEGER (2nd reference) */ -Constants.TEXTUREFORMAT_R_INTEGER = 8; -/** RG_INTEGER */ -Constants.TEXTUREFORMAT_RG_INTEGER = 9; -/** RGB_INTEGER */ -Constants.TEXTUREFORMAT_RGB_INTEGER = 10; -/** RGBA_INTEGER */ -Constants.TEXTUREFORMAT_RGBA_INTEGER = 11; -/** BGRA */ -Constants.TEXTUREFORMAT_BGRA = 12; -/** Depth 24 bits + Stencil 8 bits */ -Constants.TEXTUREFORMAT_DEPTH24_STENCIL8 = 13; -/** Depth 32 bits float */ -Constants.TEXTUREFORMAT_DEPTH32_FLOAT = 14; -/** Depth 16 bits */ -Constants.TEXTUREFORMAT_DEPTH16 = 15; -/** Depth 24 bits */ -Constants.TEXTUREFORMAT_DEPTH24 = 16; -/** Depth 24 bits unorm + Stencil 8 bits */ -Constants.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8 = 17; -/** Depth 32 bits float + Stencil 8 bits */ -Constants.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8 = 18; -/** Stencil 8 bits */ -Constants.TEXTUREFORMAT_STENCIL8 = 19; -/** Compressed BC7 */ -Constants.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM = 36492; -/** Compressed BC7 (SRGB) */ -Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM = 36493; -/** Compressed BC6 unsigned float */ -Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 36495; -/** Compressed BC6 signed float */ -Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 36494; -/** Compressed BC3 */ -Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5 = 33779; -/** Compressed BC3 (SRGB) */ -Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 35919; -/** Compressed BC2 */ -Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3 = 33778; -/** Compressed BC2 (SRGB) */ -Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 35918; -/** Compressed BC1 (RGBA) */ -Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1 = 33777; -/** Compressed BC1 (RGB) */ -Constants.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1 = 33776; -/** Compressed BC1 (SRGB+A) */ -Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 35917; -/** Compressed BC1 (SRGB) */ -Constants.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT = 35916; -/** Compressed ASTC 4x4 */ -Constants.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4 = 37808; -/** Compressed ASTC 4x4 (SRGB) */ -Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 37840; -/** Compressed ETC1 (RGB) */ -Constants.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL = 36196; -/** Compressed ETC2 (RGB) */ -Constants.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2 = 37492; -/** Compressed ETC2 (SRGB) */ -Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2 = 37493; -/** Compressed ETC2 (RGB+A1) */ -Constants.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37494; -/** Compressed ETC2 (SRGB+A1)*/ -Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37495; -/** Compressed ETC2 (RGB+A) */ -Constants.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC = 37496; -/** Compressed ETC2 (SRGB+1) */ -Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 37497; -/** UNSIGNED_BYTE */ -Constants.TEXTURETYPE_UNSIGNED_BYTE = 0; -/** UNSIGNED_BYTE (2nd reference) */ -Constants.TEXTURETYPE_UNSIGNED_INT = 0; -/** FLOAT */ -Constants.TEXTURETYPE_FLOAT = 1; -/** HALF_FLOAT */ -Constants.TEXTURETYPE_HALF_FLOAT = 2; -/** BYTE */ -Constants.TEXTURETYPE_BYTE = 3; -/** SHORT */ -Constants.TEXTURETYPE_SHORT = 4; -/** UNSIGNED_SHORT */ -Constants.TEXTURETYPE_UNSIGNED_SHORT = 5; -/** INT */ -Constants.TEXTURETYPE_INT = 6; -/** UNSIGNED_INT */ -Constants.TEXTURETYPE_UNSIGNED_INTEGER = 7; -/** UNSIGNED_SHORT_4_4_4_4 */ -Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8; -/** UNSIGNED_SHORT_5_5_5_1 */ -Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9; -/** UNSIGNED_SHORT_5_6_5 */ -Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10; -/** UNSIGNED_INT_2_10_10_10_REV */ -Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11; -/** UNSIGNED_INT_24_8 */ -Constants.TEXTURETYPE_UNSIGNED_INT_24_8 = 12; -/** UNSIGNED_INT_10F_11F_11F_REV */ -Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13; -/** UNSIGNED_INT_5_9_9_9_REV */ -Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14; -/** FLOAT_32_UNSIGNED_INT_24_8_REV */ -Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15; -/** UNDEFINED */ -Constants.TEXTURETYPE_UNDEFINED = 16; -/** 2D Texture target*/ -Constants.TEXTURE_2D = 3553; -/** 2D Array Texture target */ -Constants.TEXTURE_2D_ARRAY = 35866; -/** Cube Map Texture target */ -Constants.TEXTURE_CUBE_MAP = 34067; -/** Cube Map Array Texture target */ -Constants.TEXTURE_CUBE_MAP_ARRAY = 0xdeadbeef; -/** 3D Texture target */ -Constants.TEXTURE_3D = 32879; -/** nearest is mag = nearest and min = nearest and no mip */ -Constants.TEXTURE_NEAREST_SAMPLINGMODE = 1; -/** mag = nearest and min = nearest and mip = none */ -Constants.TEXTURE_NEAREST_NEAREST = 1; -/** Bilinear is mag = linear and min = linear and no mip */ -Constants.TEXTURE_BILINEAR_SAMPLINGMODE = 2; -/** mag = linear and min = linear and mip = none */ -Constants.TEXTURE_LINEAR_LINEAR = 2; -/** Trilinear is mag = linear and min = linear and mip = linear */ -Constants.TEXTURE_TRILINEAR_SAMPLINGMODE = 3; -/** Trilinear is mag = linear and min = linear and mip = linear */ -Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3; -/** mag = nearest and min = nearest and mip = nearest */ -Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4; -/** mag = nearest and min = linear and mip = nearest */ -Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5; -/** mag = nearest and min = linear and mip = linear */ -Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6; -/** mag = nearest and min = linear and mip = none */ -Constants.TEXTURE_NEAREST_LINEAR = 7; -/** nearest is mag = nearest and min = nearest and mip = linear */ -Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8; -/** mag = linear and min = nearest and mip = nearest */ -Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9; -/** mag = linear and min = nearest and mip = linear */ -Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10; -/** Bilinear is mag = linear and min = linear and mip = nearest */ -Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11; -/** mag = linear and min = nearest and mip = none */ -Constants.TEXTURE_LINEAR_NEAREST = 12; -/** Explicit coordinates mode */ -Constants.TEXTURE_EXPLICIT_MODE = 0; -/** Spherical coordinates mode */ -Constants.TEXTURE_SPHERICAL_MODE = 1; -/** Planar coordinates mode */ -Constants.TEXTURE_PLANAR_MODE = 2; -/** Cubic coordinates mode */ -Constants.TEXTURE_CUBIC_MODE = 3; -/** Projection coordinates mode */ -Constants.TEXTURE_PROJECTION_MODE = 4; -/** Skybox coordinates mode */ -Constants.TEXTURE_SKYBOX_MODE = 5; -/** Inverse Cubic coordinates mode */ -Constants.TEXTURE_INVCUBIC_MODE = 6; -/** Equirectangular coordinates mode */ -Constants.TEXTURE_EQUIRECTANGULAR_MODE = 7; -/** Equirectangular Fixed coordinates mode */ -Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8; -/** Equirectangular Fixed Mirrored coordinates mode */ -Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; -/** Offline (baking) quality for texture filtering */ -Constants.TEXTURE_FILTERING_QUALITY_OFFLINE = 4096; -/** High quality for texture filtering */ -Constants.TEXTURE_FILTERING_QUALITY_HIGH = 64; -/** Medium quality for texture filtering */ -Constants.TEXTURE_FILTERING_QUALITY_MEDIUM = 16; -/** Low quality for texture filtering */ -Constants.TEXTURE_FILTERING_QUALITY_LOW = 8; -// Texture rescaling mode -/** Defines that texture rescaling will use a floor to find the closer power of 2 size */ -Constants.SCALEMODE_FLOOR = 1; -/** Defines that texture rescaling will look for the nearest power of 2 size */ -Constants.SCALEMODE_NEAREST = 2; -/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */ -Constants.SCALEMODE_CEILING = 3; -/** - * The dirty texture flag value - */ -Constants.MATERIAL_TextureDirtyFlag = 1; -/** - * The dirty light flag value - */ -Constants.MATERIAL_LightDirtyFlag = 2; -/** - * The dirty fresnel flag value - */ -Constants.MATERIAL_FresnelDirtyFlag = 4; -/** - * The dirty attribute flag value - */ -Constants.MATERIAL_AttributesDirtyFlag = 8; -/** - * The dirty misc flag value - */ -Constants.MATERIAL_MiscDirtyFlag = 16; -/** - * The dirty prepass flag value - */ -Constants.MATERIAL_PrePassDirtyFlag = 32; -/** - * The all dirty flag value - */ -Constants.MATERIAL_AllDirtyFlag = 63; -/** - * Returns the triangle fill mode - */ -Constants.MATERIAL_TriangleFillMode = 0; -/** - * Returns the wireframe mode - */ -Constants.MATERIAL_WireFrameFillMode = 1; -/** - * Returns the point fill mode - */ -Constants.MATERIAL_PointFillMode = 2; -/** - * Returns the point list draw mode - */ -Constants.MATERIAL_PointListDrawMode = 3; -/** - * Returns the line list draw mode - */ -Constants.MATERIAL_LineListDrawMode = 4; -/** - * Returns the line loop draw mode - */ -Constants.MATERIAL_LineLoopDrawMode = 5; -/** - * Returns the line strip draw mode - */ -Constants.MATERIAL_LineStripDrawMode = 6; -/** - * Returns the triangle strip draw mode - */ -Constants.MATERIAL_TriangleStripDrawMode = 7; -/** - * Returns the triangle fan draw mode - */ -Constants.MATERIAL_TriangleFanDrawMode = 8; -/** - * Stores the clock-wise side orientation - */ -Constants.MATERIAL_ClockWiseSideOrientation = 0; -/** - * Stores the counter clock-wise side orientation - */ -Constants.MATERIAL_CounterClockWiseSideOrientation = 1; -/** - * Nothing - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_NothingTrigger = 0; -/** - * On pick - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnPickTrigger = 1; -/** - * On left pick - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnLeftPickTrigger = 2; -/** - * On right pick - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnRightPickTrigger = 3; -/** - * On center pick - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnCenterPickTrigger = 4; -/** - * On pick down - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnPickDownTrigger = 5; -/** - * On double pick - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnDoublePickTrigger = 6; -/** - * On pick up - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnPickUpTrigger = 7; -/** - * On pick out. - * This trigger will only be raised if you also declared a OnPickDown - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnPickOutTrigger = 16; -/** - * On long press - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnLongPressTrigger = 8; -/** - * On pointer over - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnPointerOverTrigger = 9; -/** - * On pointer out - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnPointerOutTrigger = 10; -/** - * On every frame - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnEveryFrameTrigger = 11; -/** - * On intersection enter - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnIntersectionEnterTrigger = 12; -/** - * On intersection exit - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnIntersectionExitTrigger = 13; -/** - * On key down - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnKeyDownTrigger = 14; -/** - * On key up - * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers - */ -Constants.ACTION_OnKeyUpTrigger = 15; -/** - * Billboard mode will only apply to Y axis - */ -Constants.PARTICLES_BILLBOARDMODE_Y = 2; -/** - * Billboard mode will apply to all axes - */ -Constants.PARTICLES_BILLBOARDMODE_ALL = 7; -/** - * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction - */ -Constants.PARTICLES_BILLBOARDMODE_STRETCHED = 8; -/** - * Special billboard mode where the particle will be billboard to the camera but only around the axis of the direction of particle emission - */ -Constants.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL = 9; -/** Default culling strategy : this is an exclusion test and it's the more accurate. - * Test order : - * Is the bounding sphere outside the frustum ? - * If not, are the bounding box vertices outside the frustum ? - * It not, then the cullable object is in the frustum. - */ -Constants.MESHES_CULLINGSTRATEGY_STANDARD = 0; -/** Culling strategy : Bounding Sphere Only. - * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested. - * It's also less accurate than the standard because some not visible objects can still be selected. - * Test : is the bounding sphere outside the frustum ? - * If not, then the cullable object is in the frustum. - */ -Constants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1; -/** Culling strategy : Optimistic Inclusion. - * This in an inclusion test first, then the standard exclusion test. - * This can be faster when a cullable object is expected to be almost always in the camera frustum. - * 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. - * Anyway, it's as accurate as the standard strategy. - * Test : - * Is the cullable object bounding sphere center in the frustum ? - * If not, apply the default culling strategy. - */ -Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2; -/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only. - * This in an inclusion test first, then the bounding sphere only exclusion test. - * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum. - * 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. - * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy. - * Test : - * Is the cullable object bounding sphere center in the frustum ? - * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here. - */ -Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3; -/** - * No logging while loading - */ -Constants.SCENELOADER_NO_LOGGING = 0; -/** - * Minimal logging while loading - */ -Constants.SCENELOADER_MINIMAL_LOGGING = 1; -/** - * Summary logging while loading - */ -Constants.SCENELOADER_SUMMARY_LOGGING = 2; -/** - * Detailed logging while loading - */ -Constants.SCENELOADER_DETAILED_LOGGING = 3; -/** - * Constant used to retrieve the irradiance texture index in the textures array in the prepass - * using getIndex(Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE) - */ -Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE = 0; -/** - * Constant used to retrieve the position texture index in the textures array in the prepass - * using getIndex(Constants.PREPASS_POSITION_TEXTURE_INDEX) - */ -Constants.PREPASS_POSITION_TEXTURE_TYPE = 1; -/** - * Constant used to retrieve the velocity texture index in the textures array in the prepass - * using getIndex(Constants.PREPASS_VELOCITY_TEXTURE_INDEX) - */ -Constants.PREPASS_VELOCITY_TEXTURE_TYPE = 2; -/** - * Constant used to retrieve the reflectivity texture index in the textures array in the prepass - * using the getIndex(Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE) - */ -Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE = 3; -/** - * Constant used to retrieve the lit color texture index in the textures array in the prepass - * using the getIndex(Constants.PREPASS_COLOR_TEXTURE_TYPE) - */ -Constants.PREPASS_COLOR_TEXTURE_TYPE = 4; -/** - * Constant used to retrieve depth index in the textures array in the prepass - * using the getIndex(Constants.PREPASS_DEPTH_TEXTURE_TYPE) - */ -Constants.PREPASS_DEPTH_TEXTURE_TYPE = 5; -/** - * Constant used to retrieve normal index in the textures array in the prepass - * using the getIndex(Constants.PREPASS_NORMAL_TEXTURE_TYPE) - */ -Constants.PREPASS_NORMAL_TEXTURE_TYPE = 6; -/** - * Constant used to retrieve albedo index in the textures array in the prepass - * using the getIndex(Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE) - */ -Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE = 7; -/** Flag to create a readable buffer (the buffer can be the source of a copy) */ -Constants.BUFFER_CREATIONFLAG_READ = 1; -/** Flag to create a writable buffer (the buffer can be the destination of a copy) */ -Constants.BUFFER_CREATIONFLAG_WRITE = 2; -/** Flag to create a readable and writable buffer */ -Constants.BUFFER_CREATIONFLAG_READWRITE = 3; -/** Flag to create a buffer suitable to be used as a uniform buffer */ -Constants.BUFFER_CREATIONFLAG_UNIFORM = 4; -/** Flag to create a buffer suitable to be used as a vertex buffer */ -Constants.BUFFER_CREATIONFLAG_VERTEX = 8; -/** Flag to create a buffer suitable to be used as an index buffer */ -Constants.BUFFER_CREATIONFLAG_INDEX = 16; -/** Flag to create a buffer suitable to be used as a storage buffer */ -Constants.BUFFER_CREATIONFLAG_STORAGE = 32; -/** - * Prefixes used by the engine for sub mesh draw wrappers - */ -/** @internal */ -Constants.RENDERPASS_MAIN = 0; -/** - * Constant used as key code for Alt key - */ -Constants.INPUT_ALT_KEY = 18; -/** - * Constant used as key code for Ctrl key - */ -Constants.INPUT_CTRL_KEY = 17; -/** - * Constant used as key code for Meta key (Left Win, Left Cmd) - */ -Constants.INPUT_META_KEY1 = 91; -/** - * Constant used as key code for Meta key (Right Win) - */ -Constants.INPUT_META_KEY2 = 92; -/** - * Constant used as key code for Meta key (Right Win, Right Cmd) - */ -Constants.INPUT_META_KEY3 = 93; -/** - * Constant used as key code for Shift key - */ -Constants.INPUT_SHIFT_KEY = 16; -/** Standard snapshot rendering. In this mode, some form of dynamic behavior is possible (for eg, uniform buffers are still updated) */ -Constants.SNAPSHOTRENDERING_STANDARD = 0; -/** Fast snapshot rendering. In this mode, everything is static and only some limited form of dynamic behaviour is possible */ -Constants.SNAPSHOTRENDERING_FAST = 1; -/** - * This is the default projection mode used by the cameras. - * It helps recreating a feeling of perspective and better appreciate depth. - * This is the best way to simulate real life cameras. - */ -Constants.PERSPECTIVE_CAMERA = 0; -/** - * This helps creating camera with an orthographic mode. - * 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. - */ -Constants.ORTHOGRAPHIC_CAMERA = 1; -/** - * This is the default FOV mode for perspective cameras. - * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum. - */ -Constants.FOVMODE_VERTICAL_FIXED = 0; -/** - * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum. - */ -Constants.FOVMODE_HORIZONTAL_FIXED = 1; -/** - * This specifies there is no need for a camera rig. - * Basically only one eye is rendered corresponding to the camera. - */ -Constants.RIG_MODE_NONE = 0; -/** - * Simulates a camera Rig with one blue eye and one red eye. - * This can be use with 3d blue and red glasses. - */ -Constants.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10; -/** - * Defines that both eyes of the camera will be rendered side by side with a parallel target. - */ -Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11; -/** - * Defines that both eyes of the camera will be rendered side by side with a none parallel target. - */ -Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12; -/** - * Defines that both eyes of the camera will be rendered over under each other. - */ -Constants.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13; -/** - * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors. - */ -Constants.RIG_MODE_STEREOSCOPIC_INTERLACED = 14; -/** - * Defines that both eyes of the camera should be renderered in a VR mode (carbox). - */ -Constants.RIG_MODE_VR = 20; -/** - * Defines that both eyes of the camera should be renderered in a VR mode (webVR). - */ -Constants.RIG_MODE_WEBVR = 21; -/** - * Custom rig mode allowing rig cameras to be populated manually with any number of cameras - */ -Constants.RIG_MODE_CUSTOM = 22; -/** - * Maximum number of uv sets supported - */ -Constants.MAX_SUPPORTED_UV_SETS = 6; -/** - * GL constants - */ -/** Alpha blend equation: ADD */ -Constants.GL_ALPHA_EQUATION_ADD = 0x8006; -/** Alpha equation: MIN */ -Constants.GL_ALPHA_EQUATION_MIN = 0x8007; -/** Alpha equation: MAX */ -Constants.GL_ALPHA_EQUATION_MAX = 0x8008; -/** Alpha equation: SUBTRACT */ -Constants.GL_ALPHA_EQUATION_SUBTRACT = 0x800a; -/** Alpha equation: REVERSE_SUBTRACT */ -Constants.GL_ALPHA_EQUATION_REVERSE_SUBTRACT = 0x800b; -/** Alpha blend function: SRC */ -Constants.GL_ALPHA_FUNCTION_SRC = 0x0300; -/** Alpha blend function: ONE_MINUS_SRC */ -Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR = 0x0301; -/** Alpha blend function: SRC_ALPHA */ -Constants.GL_ALPHA_FUNCTION_SRC_ALPHA = 0x0302; -/** Alpha blend function: ONE_MINUS_SRC_ALPHA */ -Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA = 0x0303; -/** Alpha blend function: DST_ALPHA */ -Constants.GL_ALPHA_FUNCTION_DST_ALPHA = 0x0304; -/** Alpha blend function: ONE_MINUS_DST_ALPHA */ -Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA = 0x0305; -/** Alpha blend function: ONE_MINUS_DST */ -Constants.GL_ALPHA_FUNCTION_DST_COLOR = 0x0306; -/** Alpha blend function: ONE_MINUS_DST */ -Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR = 0x0307; -/** Alpha blend function: SRC_ALPHA_SATURATED */ -Constants.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED = 0x0308; -/** Alpha blend function: CONSTANT */ -Constants.GL_ALPHA_FUNCTION_CONSTANT_COLOR = 0x8001; -/** Alpha blend function: ONE_MINUS_CONSTANT */ -Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR = 0x8002; -/** Alpha blend function: CONSTANT_ALPHA */ -Constants.GL_ALPHA_FUNCTION_CONSTANT_ALPHA = 0x8003; -/** Alpha blend function: ONE_MINUS_CONSTANT_ALPHA */ -Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA = 0x8004; -/** URL to the snippet server. Points to the public snippet server by default */ -Constants.SnippetUrl = "https://snippet.babylonjs.com"; -//# sourceMappingURL=constants.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/engineCapabilities.js - -//# sourceMappingURL=engineCapabilities.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/instancingAttributeInfo.js - -//# sourceMappingURL=instancingAttributeInfo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/nullEngine.js -/* eslint-disable @typescript-eslint/no-unused-vars */ - - - - - - - - -/** - * Options to create the null engine - */ -class NullEngineOptions { - constructor() { - /** - * Render width (Default: 512) - */ - this.renderWidth = 512; - /** - * Render height (Default: 256) - */ - this.renderHeight = 256; - /** - * Texture size (Default: 512) - */ - this.textureSize = 512; - /** - * If delta time between frames should be constant - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - */ - this.deterministicLockstep = false; - /** - * Maximum about of steps between frames (Default: 4) - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - */ - this.lockstepMaxSteps = 4; - } -} -/** - * The null engine class provides support for headless version of babylon.js. - * This can be used in server side scenario or for testing purposes - */ -class nullEngine_NullEngine extends (/* unused pure expression or super */ null && (Engine)) { - /** - * Gets a boolean indicating that the engine is running in deterministic lock step mode - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - * @returns true if engine is in deterministic lock step mode - */ - isDeterministicLockStep() { - return this._options.deterministicLockstep; - } - /** - * Gets the max steps when engine is running in deterministic lock step - * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep - * @returns the max steps - */ - getLockstepMaxSteps() { - return this._options.lockstepMaxSteps; - } - /** - * Gets the current hardware scaling level. - * By default the hardware scaling level is computed from the window device ratio. - * 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. - * @returns a number indicating the current hardware scaling level - */ - getHardwareScalingLevel() { - return 1.0; - } - constructor(options = new NullEngineOptions()) { - super(null); - Engine.Instances.push(this); - if (options.deterministicLockstep === undefined) { - options.deterministicLockstep = false; - } - if (options.lockstepMaxSteps === undefined) { - options.lockstepMaxSteps = 4; - } - this._options = options; - PerformanceConfigurator.SetMatrixPrecision(!!options.useHighPrecisionMatrix); - // Init caps - // We consider we are on a webgl1 capable device - this._caps = { - maxTexturesImageUnits: 16, - maxVertexTextureImageUnits: 16, - maxCombinedTexturesImageUnits: 32, - maxTextureSize: 512, - maxCubemapTextureSize: 512, - maxRenderTextureSize: 512, - maxVertexAttribs: 16, - maxVaryingVectors: 16, - maxFragmentUniformVectors: 16, - maxVertexUniformVectors: 16, - standardDerivatives: false, - astc: null, - pvrtc: null, - etc1: null, - etc2: null, - bptc: null, - maxAnisotropy: 0, - uintIndices: false, - fragmentDepthSupported: false, - highPrecisionShaderSupported: true, - colorBufferFloat: false, - textureFloat: false, - textureFloatLinearFiltering: false, - textureFloatRender: false, - textureHalfFloat: false, - textureHalfFloatLinearFiltering: false, - textureHalfFloatRender: false, - textureLOD: false, - texelFetch: false, - drawBuffersExtension: false, - depthTextureExtension: false, - vertexArrayObject: false, - instancedArrays: false, - supportOcclusionQuery: false, - canUseTimestampForTimerQuery: false, - maxMSAASamples: 1, - blendMinMax: false, - canUseGLInstanceID: false, - canUseGLVertexID: false, - supportComputeShaders: false, - supportSRGBBuffers: false, - supportTransformFeedbacks: false, - textureMaxLevel: false, - texture2DArrayMaxLayerCount: 128, - disableMorphTargetTexture: false, - }; - this._features = { - forceBitmapOverHTMLImageElement: false, - supportRenderAndCopyToLodForFloatTextures: false, - supportDepthStencilTexture: false, - supportShadowSamplers: false, - uniformBufferHardCheckMatrix: false, - allowTexturePrefiltering: false, - trackUbosInFrame: false, - checkUbosContentBeforeUpload: false, - supportCSM: false, - basisNeedsPOT: false, - support3DTextures: false, - needTypeSuffixInShaderConstants: false, - supportMSAA: false, - supportSSAO2: false, - supportExtendedTextureFormats: false, - supportSwitchCaseInShader: false, - supportSyncTextureRead: false, - needsInvertingBitmap: false, - useUBOBindingCache: false, - needShaderCodeInlining: false, - needToAlwaysBindUniformBuffers: false, - supportRenderPasses: true, - supportSpriteInstancing: false, - _collectUbosUpdatedInFrame: false, - }; - Logger.Log(`Babylon.js v${Engine.Version} - Null engine`); - // Wrappers - const theCurrentGlobal = typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : window; - if (typeof URL === "undefined") { - theCurrentGlobal.URL = { - createObjectURL: function () { }, - revokeObjectURL: function () { }, - }; - } - if (typeof Blob === "undefined") { - theCurrentGlobal.Blob = function () { }; - } - } - /** - * Creates a vertex buffer - * @param vertices the data for the vertex buffer - * @returns the new WebGL static buffer - */ - createVertexBuffer(vertices) { - const buffer = new DataBuffer(); - buffer.references = 1; - return buffer; - } - /** - * Creates a new index buffer - * @param indices defines the content of the index buffer - * @returns a new webGL buffer - */ - createIndexBuffer(indices) { - const buffer = new DataBuffer(); - buffer.references = 1; - return buffer; - } - /** - * Clear the current render buffer or the current render target (if any is set up) - * @param color defines the color to use - * @param backBuffer defines if the back buffer must be cleared - * @param depth defines if the depth buffer must be cleared - * @param stencil defines if the stencil buffer must be cleared - */ - clear(color, backBuffer, depth, stencil = false) { } - /** - * Gets the current render width - * @param useScreen defines if screen size must be used (or the current render target if any) - * @returns a number defining the current render width - */ - getRenderWidth(useScreen = false) { - if (!useScreen && this._currentRenderTarget) { - return this._currentRenderTarget.width; - } - return this._options.renderWidth; - } - /** - * Gets the current render height - * @param useScreen defines if screen size must be used (or the current render target if any) - * @returns a number defining the current render height - */ - getRenderHeight(useScreen = false) { - if (!useScreen && this._currentRenderTarget) { - return this._currentRenderTarget.height; - } - return this._options.renderHeight; - } - /** - * Set the WebGL's viewport - * @param viewport defines the viewport element to be used - * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used - * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used - */ - setViewport(viewport, requiredWidth, requiredHeight) { - this._cachedViewport = viewport; - } - createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context) { - return { - // eslint-disable-next-line @typescript-eslint/naming-convention - __SPECTOR_rebuildProgram: null, - }; - } - /** - * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names - * @param pipelineContext defines the pipeline context to use - * @param uniformsNames defines the list of uniform names - * @returns an array of webGL uniform locations - */ - getUniforms(pipelineContext, uniformsNames) { - return []; - } - /** - * Gets the lsit of active attributes for a given webGL program - * @param pipelineContext defines the pipeline context to use - * @param attributesNames defines the list of attribute names to get - * @returns an array of indices indicating the offset of each attribute - */ - getAttributes(pipelineContext, attributesNames) { - return []; - } - /** - * Binds an effect to the webGL context - * @param effect defines the effect to bind - */ - bindSamplers(effect) { - this._currentEffect = null; - } - /** - * Activates an effect, making it the current one (ie. the one used for rendering) - * @param effect defines the effect to activate - */ - enableEffect(effect) { - effect = effect !== null && DrawWrapper.IsWrapper(effect) ? effect.effect : effect; // get only the effect, we don't need a Wrapper in the WebGL engine - this._currentEffect = effect; - if (!effect) { - return; - } - if (effect.onBind) { - effect.onBind(effect); - } - if (effect._onBindObservable) { - effect._onBindObservable.notifyObservers(effect); - } - } - /** - * Set various states to the webGL context - * @param culling defines culling state: true to enable culling, false to disable it - * @param zOffset defines the value to apply to zOffset (0 by default) - * @param force defines if states must be applied even if cache is up to date - * @param reverseSide defines if culling must be reversed (CCW if false, CW if true) - * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled) - * @param stencil stencil states to set - * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default) - */ - setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) { } - /** - * Set the value of an uniform to an array of int32 - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of int32 to store - * @returns true if value was set - */ - setIntArray(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of int32 (stored as vec2) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of int32 to store - * @returns true if value was set - */ - setIntArray2(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of int32 (stored as vec3) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of int32 to store - * @returns true if value was set - */ - setIntArray3(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of int32 (stored as vec4) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of int32 to store - * @returns true if value was set - */ - setIntArray4(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of float32 - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of float32 to store - * @returns true if value was set - */ - setFloatArray(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of float32 (stored as vec2) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of float32 to store - * @returns true if value was set - */ - setFloatArray2(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of float32 (stored as vec3) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of float32 to store - * @returns true if value was set - */ - setFloatArray3(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of float32 (stored as vec4) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of float32 to store - * @returns true if value was set - */ - setFloatArray4(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of number - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of number to store - * @returns true if value was set - */ - setArray(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of number (stored as vec2) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of number to store - * @returns true if value was set - */ - setArray2(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of number (stored as vec3) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of number to store - * @returns true if value was set - */ - setArray3(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of number (stored as vec4) - * @param uniform defines the webGL uniform location where to store the value - * @param array defines the array of number to store - * @returns true if value was set - */ - setArray4(uniform, array) { - return true; - } - /** - * Set the value of an uniform to an array of float32 (stored as matrices) - * @param uniform defines the webGL uniform location where to store the value - * @param matrices defines the array of float32 to store - * @returns true if value was set - */ - setMatrices(uniform, matrices) { - return true; - } - /** - * Set the value of an uniform to a matrix (3x3) - * @param uniform defines the webGL uniform location where to store the value - * @param matrix defines the Float32Array representing the 3x3 matrix to store - * @returns true if value was set - */ - setMatrix3x3(uniform, matrix) { - return true; - } - /** - * Set the value of an uniform to a matrix (2x2) - * @param uniform defines the webGL uniform location where to store the value - * @param matrix defines the Float32Array representing the 2x2 matrix to store - * @returns true if value was set - */ - setMatrix2x2(uniform, matrix) { - return true; - } - /** - * Set the value of an uniform to a number (float) - * @param uniform defines the webGL uniform location where to store the value - * @param value defines the float number to store - * @returns true if value was set - */ - setFloat(uniform, value) { - return true; - } - /** - * Set the value of an uniform to a vec2 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @returns true if value was set - */ - setFloat2(uniform, x, y) { - return true; - } - /** - * Set the value of an uniform to a vec3 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @param z defines the 3rd component of the value - * @returns true if value was set - */ - setFloat3(uniform, x, y, z) { - return true; - } - /** - * Set the value of an uniform to a boolean - * @param uniform defines the webGL uniform location where to store the value - * @param bool defines the boolean to store - * @returns true if value was set - */ - setBool(uniform, bool) { - return true; - } - /** - * Set the value of an uniform to a vec4 - * @param uniform defines the webGL uniform location where to store the value - * @param x defines the 1st component of the value - * @param y defines the 2nd component of the value - * @param z defines the 3rd component of the value - * @param w defines the 4th component of the value - * @returns true if value was set - */ - setFloat4(uniform, x, y, z, w) { - return true; - } - /** - * Sets the current alpha mode - * @param mode defines the mode to use (one of the Engine.ALPHA_XXX) - * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default) - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering - */ - setAlphaMode(mode, noDepthWriteChange = false) { - if (this._alphaMode === mode) { - return; - } - this.alphaState.alphaBlend = mode !== 0; - if (!noDepthWriteChange) { - this.setDepthWrite(mode === 0); - } - this._alphaMode = mode; - } - /** - * Bind webGl buffers directly to the webGL context - * @param vertexBuffers defines the vertex buffer to bind - * @param indexBuffer defines the index buffer to bind - * @param effect defines the effect associated with the vertex buffer - */ - bindBuffers(vertexBuffers, indexBuffer, effect) { } - /** - * Force the entire cache to be cleared - * You should not have to use this function unless your engine needs to share the webGL context with another engine - * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states) - */ - wipeCaches(bruteForce) { - if (this.preventCacheWipeBetweenFrames) { - return; - } - this.resetTextureCache(); - this._currentEffect = null; - if (bruteForce) { - this._currentProgram = null; - this._stencilStateComposer.reset(); - this.depthCullingState.reset(); - this.alphaState.reset(); - } - this._cachedVertexBuffers = null; - this._cachedIndexBuffer = null; - this._cachedEffectForVertexBuffers = null; - } - /** - * Send a draw order - * @param useTriangles defines if triangles must be used to draw (else wireframe will be used) - * @param indexStart defines the starting index - * @param indexCount defines the number of index to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - draw(useTriangles, indexStart, indexCount, instancesCount) { } - /** - * Draw a list of indexed primitives - * @param fillMode defines the primitive to use - * @param indexStart defines the starting index - * @param indexCount defines the number of index to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - drawElementsType(fillMode, indexStart, indexCount, instancesCount) { } - /** - * Draw a list of unindexed primitives - * @param fillMode defines the primitive to use - * @param verticesStart defines the index of first vertex to draw - * @param verticesCount defines the count of vertices to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) { } - /** @internal */ - _createTexture() { - return {}; - } - /** - * @internal - */ - _releaseTexture(texture) { } - /** - * Usually called from Texture.ts. - * Passed information to create a WebGLTexture - * @param urlArg defines a value which contains one of the following: - * * A conventional http URL, e.g. 'http://...' or 'file://...' - * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...' - * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg' - * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file - * @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) - * @param scene needed for loading to the correct scene - * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE) - * @param onLoad optional callback to be called upon successful completion - * @param onError optional callback to be called upon failure - * @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 - * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities - * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures - * @param forcedExtension defines the extension to use to pick the right loader - * @param mimeType defines an optional mime type - * @returns a InternalTexture for assignment back into BABYLON.Texture - */ - createTexture(urlArg, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType) { - const texture = new InternalTexture(this, InternalTextureSource.Url); - const url = String(urlArg); - texture.url = url; - texture.generateMipMaps = !noMipmap; - texture.samplingMode = samplingMode; - texture.invertY = invertY; - texture.baseWidth = this._options.textureSize; - texture.baseHeight = this._options.textureSize; - texture.width = this._options.textureSize; - texture.height = this._options.textureSize; - if (format) { - texture.format = format; - } - texture.isReady = true; - if (onLoad) { - setTimeout(() => { - onLoad(texture); - }); - } - this._internalTexturesCache.push(texture); - return texture; - } - /** - * @internal - */ - _createHardwareRenderTargetWrapper(isMulti, isCube, size) { - const rtWrapper = new RenderTargetWrapper(isMulti, isCube, size, this); - this._renderTargetWrapperCache.push(rtWrapper); - return rtWrapper; - } - /** - * Creates a new render target wrapper - * @param size defines the size of the texture - * @param options defines the options used to create the texture - * @returns a new render target wrapper - */ - createRenderTargetTexture(size, options) { - const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size); - const fullOptions = {}; - if (options !== undefined && typeof options === "object") { - fullOptions.generateMipMaps = options.generateMipMaps; - fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; - fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer; - fullOptions.type = options.type === undefined ? 0 : options.type; - fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode; - } - else { - fullOptions.generateMipMaps = options; - fullOptions.generateDepthBuffer = true; - fullOptions.generateStencilBuffer = false; - fullOptions.type = 0; - fullOptions.samplingMode = 3; - } - const texture = new InternalTexture(this, InternalTextureSource.RenderTarget); - const width = size.width || size; - const height = size.height || size; - rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer; - rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false; - texture.baseWidth = width; - texture.baseHeight = height; - texture.width = width; - texture.height = height; - texture.isReady = true; - texture.samples = 1; - texture.generateMipMaps = fullOptions.generateMipMaps ? true : false; - texture.samplingMode = fullOptions.samplingMode; - texture.type = fullOptions.type; - this._internalTexturesCache.push(texture); - return rtWrapper; - } - /** - * Creates a new render target wrapper - * @param size defines the size of the texture - * @param options defines the options used to create the texture - * @returns a new render target wrapper - */ - createRenderTargetCubeTexture(size, options) { - const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size); - const fullOptions = Object.assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: 0, samplingMode: 3, format: 5 }, options); - fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer; - if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) { - // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE - fullOptions.samplingMode = 1; - } - else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) { - // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE - fullOptions.samplingMode = 1; - } - rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer; - rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false; - const texture = new InternalTexture(this, InternalTextureSource.RenderTarget); - texture.baseWidth = size; - texture.baseHeight = size; - texture.width = size; - texture.height = size; - texture.isReady = true; - texture.isCube = true; - texture.samples = 1; - texture.generateMipMaps = fullOptions.generateMipMaps ? true : false; - texture.samplingMode = fullOptions.samplingMode; - texture.type = fullOptions.type; - this._internalTexturesCache.push(texture); - return rtWrapper; - } - /** - * Update the sampling mode of a given texture - * @param samplingMode defines the required sampling mode - * @param texture defines the texture to update - */ - updateTextureSamplingMode(samplingMode, texture) { - texture.samplingMode = samplingMode; - } - /** - * Creates a raw texture - * @param data defines the data to store in the texture - * @param width defines the width of the texture - * @param height defines the height of the texture - * @param format defines the format of the data - * @param generateMipMaps defines if the engine should generate the mip levels - * @param invertY defines if data must be stored with Y axis inverted - * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default) - * @param compression defines the compression used (null by default) - * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default) - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - * @returns the raw texture inside an InternalTexture - */ - createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) { - const texture = new InternalTexture(this, InternalTextureSource.Raw); - texture.baseWidth = width; - texture.baseHeight = height; - texture.width = width; - texture.height = height; - texture.format = format; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.invertY = invertY; - texture._compression = compression; - texture.type = type; - texture._useSRGBBuffer = useSRGBBuffer; - if (!this._doNotHandleContextLost) { - texture._bufferView = data; - } - return texture; - } - /** - * Update a raw texture - * @param texture defines the texture to update - * @param data defines the data to store in the texture - * @param format defines the format of the data - * @param invertY defines if data must be stored with Y axis inverted - * @param compression defines the compression used (null by default) - * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default) - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - */ - updateRawTexture(texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) { - if (texture) { - texture._bufferView = data; - texture.format = format; - texture.invertY = invertY; - texture._compression = compression; - texture.type = type; - texture._useSRGBBuffer = useSRGBBuffer; - } - } - /** - * Binds the frame buffer to the specified texture. - * @param rtWrapper The render target wrapper to render to - * @param faceIndex The face of the texture to render to in case of cube texture - * @param requiredWidth The width of the target to render to - * @param requiredHeight The height of the target to render to - * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true - */ - bindFramebuffer(rtWrapper, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) { - if (this._currentRenderTarget) { - this.unBindFramebuffer(this._currentRenderTarget); - } - this._currentRenderTarget = rtWrapper; - this._currentFramebuffer = null; - if (this._cachedViewport && !forceFullscreenViewport) { - this.setViewport(this._cachedViewport, requiredWidth, requiredHeight); - } - } - /** - * Unbind the current render target texture from the webGL context - * @param rtWrapper defines the render target wrapper to unbind - * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated - * @param onBeforeUnbind defines a function which will be called before the effective unbind - */ - unBindFramebuffer(rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) { - this._currentRenderTarget = null; - if (onBeforeUnbind) { - onBeforeUnbind(); - } - this._currentFramebuffer = null; - } - /** - * Creates a dynamic vertex buffer - * @param vertices the data for the dynamic vertex buffer - * @returns the new WebGL dynamic buffer - */ - createDynamicVertexBuffer(vertices) { - const buffer = new DataBuffer(); - buffer.references = 1; - buffer.capacity = 1; - return buffer; - } - /** - * Update the content of a dynamic texture - * @param texture defines the texture to update - * @param canvas defines the canvas containing the source - * @param invertY defines if data must be stored with Y axis inverted - * @param premulAlpha defines if alpha is stored as premultiplied - * @param format defines the format of the data - */ - updateDynamicTexture(texture, canvas, invertY, premulAlpha = false, format) { } - /** - * Gets a boolean indicating if all created effects are ready - * @returns true if all effects are ready - */ - areAllEffectsReady() { - return true; - } - /** - * @internal - * Get the current error code of the webGL context - * @returns the error code - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError - */ - getError() { - return 0; - } - /** @internal */ - _getUnpackAlignement() { - return 1; - } - /** - * @internal - */ - _unpackFlipY(value) { } - /** - * Update a dynamic index buffer - * @param indexBuffer defines the target index buffer - * @param indices defines the data to update - * @param offset defines the offset in the target index buffer where update should start - */ - updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) { } - /** - * Updates a dynamic vertex buffer. - * @param vertexBuffer the vertex buffer to update - * @param vertices the data used to update the vertex buffer - * @param byteOffset the byte offset of the data (optional) - * @param byteLength the byte length of the data (optional) - */ - updateDynamicVertexBuffer(vertexBuffer, vertices, byteOffset, byteLength) { } - /** - * @internal - */ - _bindTextureDirectly(target, texture) { - if (this._boundTexturesCache[this._activeChannel] !== texture) { - this._boundTexturesCache[this._activeChannel] = texture; - return true; - } - return false; - } - /** - * @internal - */ - _bindTexture(channel, texture) { - if (channel < 0) { - return; - } - this._bindTextureDirectly(0, texture); - } - _deleteBuffer(buffer) { } - /** - * 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 - */ - releaseEffects() { } - displayLoadingUI() { } - hideLoadingUI() { } - set loadingUIText(_) { } - /** - * @internal - */ - _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) { } - /** - * @internal - */ - _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0) { } - /** - * @internal - */ - _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) { } - /** - * @internal - */ - _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) { } -} -//# sourceMappingURL=nullEngine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.debugging.js -/* eslint-disable @typescript-eslint/no-unused-vars */ - -ThinEngine.prototype._debugPushGroup = function (groupName, targetObject) { }; -ThinEngine.prototype._debugPopGroup = function (targetObject) { }; -ThinEngine.prototype._debugInsertMarker = function (text, targetObject) { }; -ThinEngine.prototype._debugFlushPendingCommands = function () { }; -//# sourceMappingURL=engine.debugging.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Instrumentation/timeToken.js -/** - * @internal - **/ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _TimeToken { - constructor() { - this._timeElapsedQueryEnded = false; - } -} -//# sourceMappingURL=timeToken.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.query.js - - - - -/** @internal */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _OcclusionDataStorage { - constructor() { - /** @internal */ - this.occlusionInternalRetryCounter = 0; - /** @internal */ - this.isOcclusionQueryInProgress = false; - /** @internal */ - this.isOccluded = false; - /** @internal */ - this.occlusionRetryCount = -1; - /** @internal */ - this.occlusionType = abstractMesh_AbstractMesh.OCCLUSION_TYPE_NONE; - /** @internal */ - this.occlusionQueryAlgorithmType = abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE; - /** @internal */ - this.forceRenderingWhenOccluded = false; - } -} -engine_Engine.prototype.createQuery = function () { - const query = this._gl.createQuery(); - if (!query) { - throw new Error("Unable to create Occlusion Query"); - } - return query; -}; -engine_Engine.prototype.deleteQuery = function (query) { - this._gl.deleteQuery(query); - return this; -}; -engine_Engine.prototype.isQueryResultAvailable = function (query) { - return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE); -}; -engine_Engine.prototype.getQueryResult = function (query) { - return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT); -}; -engine_Engine.prototype.beginOcclusionQuery = function (algorithmType, query) { - const glAlgorithm = this._getGlAlgorithmType(algorithmType); - this._gl.beginQuery(glAlgorithm, query); - return true; -}; -engine_Engine.prototype.endOcclusionQuery = function (algorithmType) { - const glAlgorithm = this._getGlAlgorithmType(algorithmType); - this._gl.endQuery(glAlgorithm); - return this; -}; -engine_Engine.prototype._createTimeQuery = function () { - const timerQuery = this.getCaps().timerQuery; - if (timerQuery.createQueryEXT) { - return timerQuery.createQueryEXT(); - } - return this.createQuery(); -}; -engine_Engine.prototype._deleteTimeQuery = function (query) { - const timerQuery = this.getCaps().timerQuery; - if (timerQuery.deleteQueryEXT) { - timerQuery.deleteQueryEXT(query); - return; - } - this.deleteQuery(query); -}; -engine_Engine.prototype._getTimeQueryResult = function (query) { - const timerQuery = this.getCaps().timerQuery; - if (timerQuery.getQueryObjectEXT) { - return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT); - } - return this.getQueryResult(query); -}; -engine_Engine.prototype._getTimeQueryAvailability = function (query) { - const timerQuery = this.getCaps().timerQuery; - if (timerQuery.getQueryObjectEXT) { - return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT); - } - return this.isQueryResultAvailable(query); -}; -engine_Engine.prototype.startTimeQuery = function () { - const caps = this.getCaps(); - const timerQuery = caps.timerQuery; - if (!timerQuery) { - return null; - } - const token = new _TimeToken(); - this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT); - if (caps.canUseTimestampForTimerQuery) { - token._startTimeQuery = this._createTimeQuery(); - timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT); - } - else { - if (this._currentNonTimestampToken) { - return this._currentNonTimestampToken; - } - token._timeElapsedQuery = this._createTimeQuery(); - if (timerQuery.beginQueryEXT) { - timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery); - } - else { - this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery); - } - this._currentNonTimestampToken = token; - } - return token; -}; -engine_Engine.prototype.endTimeQuery = function (token) { - const caps = this.getCaps(); - const timerQuery = caps.timerQuery; - if (!timerQuery || !token) { - return -1; - } - if (caps.canUseTimestampForTimerQuery) { - if (!token._startTimeQuery) { - return -1; - } - if (!token._endTimeQuery) { - token._endTimeQuery = this._createTimeQuery(); - timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT); - } - } - else if (!token._timeElapsedQueryEnded) { - if (!token._timeElapsedQuery) { - return -1; - } - if (timerQuery.endQueryEXT) { - timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT); - } - else { - this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT); - this._currentNonTimestampToken = null; - } - token._timeElapsedQueryEnded = true; - } - const disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT); - let available = false; - if (token._endTimeQuery) { - available = this._getTimeQueryAvailability(token._endTimeQuery); - } - else if (token._timeElapsedQuery) { - available = this._getTimeQueryAvailability(token._timeElapsedQuery); - } - if (available && !disjoint) { - let result = 0; - if (caps.canUseTimestampForTimerQuery) { - if (!token._startTimeQuery || !token._endTimeQuery) { - return -1; - } - const timeStart = this._getTimeQueryResult(token._startTimeQuery); - const timeEnd = this._getTimeQueryResult(token._endTimeQuery); - result = timeEnd - timeStart; - this._deleteTimeQuery(token._startTimeQuery); - this._deleteTimeQuery(token._endTimeQuery); - token._startTimeQuery = null; - token._endTimeQuery = null; - } - else { - if (!token._timeElapsedQuery) { - return -1; - } - result = this._getTimeQueryResult(token._timeElapsedQuery); - this._deleteTimeQuery(token._timeElapsedQuery); - token._timeElapsedQuery = null; - token._timeElapsedQueryEnded = false; - } - return result; - } - return -1; -}; -engine_Engine.prototype._captureGPUFrameTime = false; -engine_Engine.prototype._gpuFrameTime = new perfCounter_PerfCounter(); -engine_Engine.prototype.getGPUFrameTimeCounter = function () { - return this._gpuFrameTime; -}; -engine_Engine.prototype.captureGPUFrameTime = function (value) { - if (value === this._captureGPUFrameTime) { - return; - } - this._captureGPUFrameTime = value; - if (value) { - this._onBeginFrameObserver = this.onBeginFrameObservable.add(() => { - if (!this._gpuFrameTimeToken) { - this._gpuFrameTimeToken = this.startTimeQuery(); - } - }); - this._onEndFrameObserver = this.onEndFrameObservable.add(() => { - if (!this._gpuFrameTimeToken) { - return; - } - const time = this.endTimeQuery(this._gpuFrameTimeToken); - if (time > -1) { - this._gpuFrameTimeToken = null; - this._gpuFrameTime.fetchNewFrame(); - this._gpuFrameTime.addCount(time, true); - } - }); - } - else { - this.onBeginFrameObservable.remove(this._onBeginFrameObserver); - this._onBeginFrameObserver = null; - this.onEndFrameObservable.remove(this._onEndFrameObserver); - this._onEndFrameObserver = null; - } -}; -engine_Engine.prototype._getGlAlgorithmType = function (algorithmType) { - return algorithmType === abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED; -}; -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "isOcclusionQueryInProgress", { - get: function () { - return this._occlusionDataStorage.isOcclusionQueryInProgress; - }, - set: function (value) { - this._occlusionDataStorage.isOcclusionQueryInProgress = value; - }, - enumerable: false, - configurable: true, -}); -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "_occlusionDataStorage", { - get: function () { - if (!this.__occlusionDataStorage) { - this.__occlusionDataStorage = new _OcclusionDataStorage(); - } - return this.__occlusionDataStorage; - }, - enumerable: false, - configurable: true, -}); -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "isOccluded", { - get: function () { - return this._occlusionDataStorage.isOccluded; - }, - set: function (value) { - this._occlusionDataStorage.isOccluded = value; - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "occlusionQueryAlgorithmType", { - get: function () { - return this._occlusionDataStorage.occlusionQueryAlgorithmType; - }, - set: function (value) { - this._occlusionDataStorage.occlusionQueryAlgorithmType = value; - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "occlusionType", { - get: function () { - return this._occlusionDataStorage.occlusionType; - }, - set: function (value) { - this._occlusionDataStorage.occlusionType = value; - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "occlusionRetryCount", { - get: function () { - return this._occlusionDataStorage.occlusionRetryCount; - }, - set: function (value) { - this._occlusionDataStorage.occlusionRetryCount = value; - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "forceRenderingWhenOccluded", { - get: function () { - return this._occlusionDataStorage.forceRenderingWhenOccluded; - }, - set: function (value) { - this._occlusionDataStorage.forceRenderingWhenOccluded = value; - }, - enumerable: true, - configurable: true, -}); -// We also need to update AbstractMesh as there is a portion of the code there -abstractMesh_AbstractMesh.prototype._checkOcclusionQuery = function () { - const dataStorage = this._occlusionDataStorage; - if (dataStorage.occlusionType === abstractMesh_AbstractMesh.OCCLUSION_TYPE_NONE) { - dataStorage.isOccluded = false; - return false; - } - const engine = this.getEngine(); - if (!engine.getCaps().supportOcclusionQuery) { - dataStorage.isOccluded = false; - return false; - } - if (!engine.isQueryResultAvailable) { - // Occlusion query where not referenced - dataStorage.isOccluded = false; - return false; - } - if (this.isOcclusionQueryInProgress && this._occlusionQuery) { - const isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery); - if (isOcclusionQueryAvailable) { - const occlusionQueryResult = engine.getQueryResult(this._occlusionQuery); - dataStorage.isOcclusionQueryInProgress = false; - dataStorage.occlusionInternalRetryCounter = 0; - dataStorage.isOccluded = occlusionQueryResult > 0 ? false : true; - } - else { - dataStorage.occlusionInternalRetryCounter++; - if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) { - dataStorage.isOcclusionQueryInProgress = false; - dataStorage.occlusionInternalRetryCounter = 0; - // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop) - // if strict continue the last state of the object. - dataStorage.isOccluded = dataStorage.occlusionType === abstractMesh_AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded; - } - else { - return dataStorage.occlusionType === abstractMesh_AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded; - } - } - } - const scene = this.getScene(); - if (scene.getBoundingBoxRenderer) { - const occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer(); - if (this._occlusionQuery === null) { - this._occlusionQuery = engine.createQuery(); - } - if (engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery)) { - occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this); - engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType); - this._occlusionDataStorage.isOcclusionQueryInProgress = true; - } - } - return dataStorage.isOccluded; -}; -//# sourceMappingURL=engine.query.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.transformFeedback.js - -/** @internal */ -// eslint-disable-next-line no-var -var _forceTransformFeedbackToBundle = true; -engine_Engine.prototype.createTransformFeedback = function () { - const transformFeedback = this._gl.createTransformFeedback(); - if (!transformFeedback) { - throw new Error("Unable to create Transform Feedback"); - } - return transformFeedback; -}; -engine_Engine.prototype.deleteTransformFeedback = function (value) { - this._gl.deleteTransformFeedback(value); -}; -engine_Engine.prototype.bindTransformFeedback = function (value) { - this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value); -}; -engine_Engine.prototype.beginTransformFeedback = function (usePoints = true) { - this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES); -}; -engine_Engine.prototype.endTransformFeedback = function () { - this._gl.endTransformFeedback(); -}; -engine_Engine.prototype.setTranformFeedbackVaryings = function (program, value) { - this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS); -}; -engine_Engine.prototype.bindTransformFeedbackBuffer = function (value) { - this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value ? value.underlyingResource : null); -}; -//# sourceMappingURL=engine.transformFeedback.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.externalTexture.js - -// eslint-disable-next-line @typescript-eslint/no-unused-vars -ThinEngine.prototype.createExternalTexture = function (video) { - return null; -}; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -ThinEngine.prototype.setExternalTexture = function (name, texture) { - throw new Error("setExternalTexture: This engine does not support external textures!"); -}; -//# sourceMappingURL=engine.externalTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.videoTexture.js - - -ThinEngine.prototype.updateVideoTexture = function (texture, video, invertY) { - if (!texture || texture._isDisabled) { - return; - } - const glformat = this._getInternalFormat(texture.format); - const internalFormat = this._getRGBABufferInternalSizedFormat(0, texture.format); - const wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); - this._unpackFlipY(!invertY); // Video are upside down by default - try { - // Testing video texture support - if (this._videoTextureSupported === undefined) { - // clear old errors just in case. - this._gl.getError(); - this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, video); - if (this._gl.getError() !== 0) { - this._videoTextureSupported = false; - } - else { - this._videoTextureSupported = true; - } - } - // Copy video through the current working canvas if video texture is not supported - if (!this._videoTextureSupported) { - if (!texture._workingCanvas) { - texture._workingCanvas = this.createCanvas(texture.width, texture.height); - const context = texture._workingCanvas.getContext("2d"); - if (!context) { - throw new Error("Unable to get 2d context"); - } - texture._workingContext = context; - texture._workingCanvas.width = texture.width; - texture._workingCanvas.height = texture.height; - } - texture._workingContext.clearRect(0, 0, texture.width, texture.height); - texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height); - this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, texture._workingCanvas); - } - else { - this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, video); - } - if (texture.generateMipMaps) { - this._gl.generateMipmap(this._gl.TEXTURE_2D); - } - if (!wasPreviouslyBound) { - this._bindTextureDirectly(this._gl.TEXTURE_2D, null); - } - // this.resetTextureCache(); - texture.isReady = true; - } - catch (ex) { - // Something unexpected - // Let's disable the texture - texture._isDisabled = true; - } -}; -//# sourceMappingURL=engine.videoTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.multiRender.js - - - - -ThinEngine.prototype.restoreSingleAttachment = function () { - const gl = this._gl; - this.bindAttachments([gl.BACK]); -}; -ThinEngine.prototype.restoreSingleAttachmentForRenderTarget = function () { - const gl = this._gl; - this.bindAttachments([gl.COLOR_ATTACHMENT0]); -}; -ThinEngine.prototype.buildTextureLayout = function (textureStatus) { - const gl = this._gl; - const result = []; - for (let i = 0; i < textureStatus.length; i++) { - if (textureStatus[i]) { - result.push(gl["COLOR_ATTACHMENT" + i]); - } - else { - result.push(gl.NONE); - } - } - return result; -}; -ThinEngine.prototype.bindAttachments = function (attachments) { - const gl = this._gl; - gl.drawBuffers(attachments); -}; -ThinEngine.prototype.unBindMultiColorAttachmentFramebuffer = function (rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) { - this._currentRenderTarget = null; - // If MSAA, we need to bitblt back to main texture - const gl = this._gl; - const attachments = rtWrapper._attachments; - const count = attachments.length; - if (rtWrapper._MSAAFramebuffer) { - gl.bindFramebuffer(gl.READ_FRAMEBUFFER, rtWrapper._MSAAFramebuffer); - gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, rtWrapper._framebuffer); - for (let i = 0; i < count; i++) { - const texture = rtWrapper.textures[i]; - for (let j = 0; j < count; j++) { - attachments[j] = gl.NONE; - } - attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; - gl.readBuffer(attachments[i]); - gl.drawBuffers(attachments); - gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST); - } - for (let i = 0; i < count; i++) { - attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; - } - gl.drawBuffers(attachments); - } - for (let i = 0; i < count; i++) { - const texture = rtWrapper.textures[i]; - if ((texture === null || texture === void 0 ? void 0 : texture.generateMipMaps) && !disableGenerateMipMaps && !texture.isCube) { - this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); - gl.generateMipmap(gl.TEXTURE_2D); - this._bindTextureDirectly(gl.TEXTURE_2D, null); - } - } - if (onBeforeUnbind) { - if (rtWrapper._MSAAFramebuffer) { - // Bind the correct framebuffer - this._bindUnboundFramebuffer(rtWrapper._framebuffer); - } - onBeforeUnbind(); - } - this._bindUnboundFramebuffer(null); -}; -ThinEngine.prototype.createMultipleRenderTarget = function (size, options, initializeBuffers = true) { - var _a; - let generateMipMaps = false; - let generateDepthBuffer = true; - let generateStencilBuffer = false; - let generateDepthTexture = false; - let depthTextureFormat = 15; - let textureCount = 1; - const defaultType = 0; - const defaultSamplingMode = 3; - const defaultUseSRGBBuffer = false; - const defaultFormat = 5; - const defaultTarget = 3553; - let types = new Array(); - let samplingModes = new Array(); - let useSRGBBuffers = new Array(); - let formats = new Array(); - let targets = new Array(); - let faceIndex = new Array(); - let layerIndex = new Array(); - let layers = new Array(); - const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size); - if (options !== undefined) { - generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps; - generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; - generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer; - generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture; - textureCount = options.textureCount || 1; - if (options.types) { - types = options.types; - } - if (options.samplingModes) { - samplingModes = options.samplingModes; - } - if (options.useSRGBBuffers) { - useSRGBBuffers = options.useSRGBBuffers; - } - if (options.formats) { - formats = options.formats; - } - if (options.targetTypes) { - targets = options.targetTypes; - } - if (options.faceIndex) { - faceIndex = options.faceIndex; - } - if (options.layerIndex) { - layerIndex = options.layerIndex; - } - if (options.layerCounts) { - layers = options.layerCounts; - } - if (this.webGLVersion > 1 && - (options.depthTextureFormat === 13 || - options.depthTextureFormat === 17 || - options.depthTextureFormat === 16 || - options.depthTextureFormat === 14 || - options.depthTextureFormat === 18)) { - depthTextureFormat = options.depthTextureFormat; - } - } - const gl = this._gl; - // Create the framebuffer - const framebuffer = gl.createFramebuffer(); - this._bindUnboundFramebuffer(framebuffer); - const width = size.width || size; - const height = size.height || size; - const textures = []; - const attachments = []; - const useStencilTexture = this.webGLVersion > 1 && - generateDepthTexture && - (options.depthTextureFormat === 13 || - options.depthTextureFormat === 17 || - options.depthTextureFormat === 18); - const depthStencilBuffer = this._setupFramebufferDepthAttachments(!useStencilTexture && generateStencilBuffer, !generateDepthTexture && generateDepthBuffer, width, height); - rtWrapper._framebuffer = framebuffer; - rtWrapper._depthStencilBuffer = depthStencilBuffer; - rtWrapper._generateDepthBuffer = !generateDepthTexture && generateDepthBuffer; - rtWrapper._generateStencilBuffer = !useStencilTexture && generateStencilBuffer; - rtWrapper._attachments = attachments; - for (let i = 0; i < textureCount; i++) { - let samplingMode = samplingModes[i] || defaultSamplingMode; - let type = types[i] || defaultType; - let useSRGBBuffer = useSRGBBuffers[i] || defaultUseSRGBBuffer; - const format = formats[i] || defaultFormat; - const target = targets[i] || defaultTarget; - const layerCount = (_a = layers[i]) !== null && _a !== void 0 ? _a : 1; - if (type === 1 && !this._caps.textureFloatLinearFiltering) { - // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE - samplingMode = 1; - } - else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { - // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE - samplingMode = 1; - } - const filters = this._getSamplingParameters(samplingMode, generateMipMaps); - if (type === 1 && !this._caps.textureFloat) { - type = 0; - logger_Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"); - } - useSRGBBuffer = useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU); - const isWebGL2 = this.webGLVersion > 1; - const attachment = gl[isWebGL2 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; - attachments.push(attachment); - if (target === -1) { - continue; - } - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.MultiRenderTarget); - textures[i] = texture; - gl.activeTexture(gl["TEXTURE" + i]); - gl.bindTexture(target, texture._hardwareTexture.underlyingResource); - gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filters.mag); - gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filters.min); - gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - const internalSizedFormat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer); - const internalFormat = this._getInternalFormat(format); - const webGLTextureType = this._getWebGLTextureType(type); - if (isWebGL2 && (target === 35866 || target === 32879)) { - if (target === 35866) { - texture.is2DArray = true; - } - else { - texture.is3D = true; - } - texture.baseDepth = texture.depth = layerCount; - gl.texImage3D(target, 0, internalSizedFormat, width, height, layerCount, 0, internalFormat, webGLTextureType, null); - } - else if (target === 34067) { - // We have to generate all faces to complete the framebuffer - for (let i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null); - } - texture.isCube = true; - } - else { - gl.texImage2D(gl.TEXTURE_2D, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null); - } - if (generateMipMaps) { - gl.generateMipmap(target); - } - // Unbind - this._bindTextureDirectly(target, null); - texture.baseWidth = width; - texture.baseHeight = height; - texture.width = width; - texture.height = height; - texture.isReady = true; - texture.samples = 1; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.type = type; - texture._useSRGBBuffer = useSRGBBuffer; - texture.format = format; - this._internalTexturesCache.push(texture); - } - if (generateDepthTexture && this._caps.depthTextureExtension) { - // Depth texture - const depthTexture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Depth); - let depthTextureType = 5; - let glDepthTextureInternalFormat = gl.DEPTH_COMPONENT16; - let glDepthTextureFormat = gl.DEPTH_COMPONENT; - let glDepthTextureType = gl.UNSIGNED_SHORT; - let glDepthTextureAttachment = gl.DEPTH_ATTACHMENT; - if (this.webGLVersion < 2) { - glDepthTextureInternalFormat = gl.DEPTH_COMPONENT; - } - else { - if (depthTextureFormat === 14) { - depthTextureType = 1; - glDepthTextureType = gl.FLOAT; - glDepthTextureInternalFormat = gl.DEPTH_COMPONENT32F; - } - else if (depthTextureFormat === 18) { - depthTextureType = 0; - glDepthTextureType = gl.FLOAT_32_UNSIGNED_INT_24_8_REV; - glDepthTextureInternalFormat = gl.DEPTH32F_STENCIL8; - glDepthTextureFormat = gl.DEPTH_STENCIL; - glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT; - } - else if (depthTextureFormat === 16) { - depthTextureType = 0; - glDepthTextureType = gl.UNSIGNED_INT; - glDepthTextureInternalFormat = gl.DEPTH_COMPONENT24; - glDepthTextureAttachment = gl.DEPTH_ATTACHMENT; - } - else if (depthTextureFormat === 13 || depthTextureFormat === 17) { - depthTextureType = 12; - glDepthTextureType = gl.UNSIGNED_INT_24_8; - glDepthTextureInternalFormat = gl.DEPTH24_STENCIL8; - glDepthTextureFormat = gl.DEPTH_STENCIL; - glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT; - } - } - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, depthTexture._hardwareTexture.underlyingResource); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - gl.texImage2D(gl.TEXTURE_2D, 0, glDepthTextureInternalFormat, width, height, 0, glDepthTextureFormat, glDepthTextureType, null); - gl.framebufferTexture2D(gl.FRAMEBUFFER, glDepthTextureAttachment, gl.TEXTURE_2D, depthTexture._hardwareTexture.underlyingResource, 0); - depthTexture.baseWidth = width; - depthTexture.baseHeight = height; - depthTexture.width = width; - depthTexture.height = height; - depthTexture.isReady = true; - depthTexture.samples = 1; - depthTexture.generateMipMaps = generateMipMaps; - depthTexture.samplingMode = 1; - depthTexture.format = depthTextureFormat; - depthTexture.type = depthTextureType; - textures[textureCount] = depthTexture; - this._internalTexturesCache.push(depthTexture); - } - rtWrapper.setTextures(textures); - if (initializeBuffers) { - gl.drawBuffers(attachments); - } - this._bindUnboundFramebuffer(null); - rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex); - this.resetTextureCache(); - return rtWrapper; -}; -ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function (rtWrapper, samples, initializeBuffers = true) { - if (this.webGLVersion < 2 || !rtWrapper || !rtWrapper.texture) { - return 1; - } - if (rtWrapper.samples === samples) { - return samples; - } - const count = rtWrapper._attachments.length; - if (count === 0) { - return 1; - } - const gl = this._gl; - samples = Math.min(samples, this.getCaps().maxMSAASamples); - // Dispose previous render buffers - const useDepthStencil = !!rtWrapper._depthStencilBuffer; - if (useDepthStencil) { - gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer); - rtWrapper._depthStencilBuffer = null; - } - if (rtWrapper._MSAAFramebuffer) { - gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer); - rtWrapper._MSAAFramebuffer = null; - } - if (samples > 1 && typeof gl.renderbufferStorageMultisample === "function") { - const framebuffer = gl.createFramebuffer(); - if (!framebuffer) { - throw new Error("Unable to create multi sampled framebuffer"); - } - rtWrapper._MSAAFramebuffer = framebuffer; - this._bindUnboundFramebuffer(framebuffer); - const attachments = []; - for (let i = 0; i < count; i++) { - const texture = rtWrapper.textures[i]; - const hardwareTexture = texture._hardwareTexture; - hardwareTexture.releaseMSAARenderBuffers(); - } - for (let i = 0; i < count; i++) { - const texture = rtWrapper.textures[i]; - const hardwareTexture = texture._hardwareTexture; - const attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; - const colorRenderbuffer = this._createRenderBuffer(texture.width, texture.height, samples, -1 /* not used */, this._getRGBAMultiSampleBufferFormat(texture.type, texture.format), attachment); - if (!colorRenderbuffer) { - throw new Error("Unable to create multi sampled framebuffer"); - } - hardwareTexture.addMSAARenderBuffer(colorRenderbuffer); - texture.samples = samples; - attachments.push(attachment); - } - if (initializeBuffers) { - gl.drawBuffers(attachments); - } - } - else { - this._bindUnboundFramebuffer(rtWrapper._framebuffer); - } - if (useDepthStencil) { - rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.texture.width, rtWrapper.texture.height, samples); - } - this._bindUnboundFramebuffer(null); - return samples; -}; -//# sourceMappingURL=engine.multiRender.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.cubeTexture.js - - - - - - -ThinEngine.prototype._createDepthStencilCubeTexture = function (size, options, rtWrapper) { - const internalTexture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.DepthStencil); - internalTexture.isCube = true; - if (this.webGLVersion === 1) { - logger_Logger.Error("Depth cube texture is not supported by WebGL 1."); - return internalTexture; - } - const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options); - const gl = this._gl; - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true); - this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction); - rtWrapper._depthStencilTexture = internalTexture; - rtWrapper._depthStencilTextureWithStencil = internalOptions.generateStencil; - // Create the depth/stencil buffer - for (let face = 0; face < 6; face++) { - if (internalOptions.generateStencil) { - 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); - } - else { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null); - } - } - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); - this._internalTexturesCache.push(internalTexture); - return internalTexture; -}; -ThinEngine.prototype._partialLoadFile = function (url, index, loadedFiles, onfinish, onErrorCallBack = null) { - const onload = (data) => { - loadedFiles[index] = data; - loadedFiles._internalCount++; - if (loadedFiles._internalCount === 6) { - onfinish(loadedFiles); - } - }; - const onerror = (request, exception) => { - if (onErrorCallBack && request) { - onErrorCallBack(request.status + " " + request.statusText, exception); - } - }; - this._loadFile(url, onload, undefined, undefined, true, onerror); -}; -ThinEngine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError = null) { - const loadedFiles = []; - loadedFiles._internalCount = 0; - for (let index = 0; index < 6; index++) { - this._partialLoadFile(files[index], index, loadedFiles, onfinish, onError); - } -}; -ThinEngine.prototype._cascadeLoadImgs = function (scene, texture, onfinish, files, onError = null, mimeType) { - const loadedImages = []; - loadedImages._internalCount = 0; - for (let index = 0; index < 6; index++) { - this._partialLoadImg(files[index], index, loadedImages, scene, texture, onfinish, onError, mimeType); - } -}; -ThinEngine.prototype._partialLoadImg = function (url, index, loadedImages, scene, texture, onfinish, onErrorCallBack = null, mimeType) { - const tokenPendingData = guid_RandomGUID(); - const onload = (img) => { - loadedImages[index] = img; - loadedImages._internalCount++; - if (scene) { - scene.removePendingData(tokenPendingData); - } - if (loadedImages._internalCount === 6 && onfinish) { - onfinish(texture, loadedImages); - } - }; - const onerror = (message, exception) => { - if (scene) { - scene.removePendingData(tokenPendingData); - } - if (onErrorCallBack) { - onErrorCallBack(message, exception); - } - }; - LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null, mimeType); - if (scene) { - scene.addPendingData(tokenPendingData); - } -}; -ThinEngine.prototype._setCubeMapTextureParams = function (texture, loadMipmap, maxLevel) { - const gl = this._gl; - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - texture.samplingMode = loadMipmap ? 3 : 2; - if (loadMipmap && this.getCaps().textureMaxLevel && maxLevel !== undefined && maxLevel > 0) { - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAX_LEVEL, maxLevel); - texture._maxLodLevel = maxLevel; - } - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); -}; -ThinEngine.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) { - const texture = fallback ? fallback : new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Cube); - texture.isCube = true; - texture.url = rootUrl; - texture.generateMipMaps = !noMipmap; - texture._lodGenerationScale = lodScale; - texture._lodGenerationOffset = lodOffset; - texture._useSRGBBuffer = !!useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU || !!noMipmap); - if (texture !== fallback) { - texture.label = rootUrl.substring(0, 60); // default label, can be overriden by the caller - } - if (!this._doNotHandleContextLost) { - texture._extension = forcedExtension; - texture._files = files; - } - const originalRootUrl = rootUrl; - if (this._transformTextureUrl && !fallback) { - rootUrl = this._transformTextureUrl(rootUrl); - } - const rootUrlWithoutUriParams = rootUrl.split("?")[0]; - const lastDot = rootUrlWithoutUriParams.lastIndexOf("."); - const extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrlWithoutUriParams.substring(lastDot).toLowerCase() : ""; - let loader = null; - for (const availableLoader of ThinEngine._TextureLoaders) { - if (availableLoader.canLoad(extension)) { - loader = availableLoader; - break; - } - } - const onInternalError = (request, exception) => { - if (rootUrl === originalRootUrl) { - if (onError && request) { - onError(request.status + " " + request.statusText, exception); - } - } - else { - // fall back to the original url if the transformed url fails to load - logger_Logger.Warn(`Failed to load ${rootUrl}, falling back to the ${originalRootUrl}`); - this.createCubeTextureBase(originalRootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, texture, beforeLoadCubeDataCallback, imageHandler, useSRGBBuffer); - } - }; - if (loader) { - const onloaddata = (data) => { - if (beforeLoadCubeDataCallback) { - beforeLoadCubeDataCallback(texture, data); - } - loader.loadCubeData(data, texture, createPolynomials, onLoad, onError); - }; - if (files && files.length === 6) { - if (loader.supportCascades) { - this._cascadeLoadFiles(scene, (images) => onloaddata(images.map((image) => new Uint8Array(image))), files, onError); - } - else { - if (onError) { - onError("Textures type does not support cascades."); - } - else { - logger_Logger.Warn("Texture loader does not support cascades."); - } - } - } - else { - this._loadFile(rootUrl, (data) => onloaddata(new Uint8Array(data)), undefined, undefined, true, onInternalError); - } - } - else { - if (!files) { - throw new Error("Cannot load cubemap because files were not defined"); - } - this._cascadeLoadImgs(scene, texture, (texture, imgs) => { - if (imageHandler) { - imageHandler(texture, imgs); - } - }, files, onError); - } - this._internalTexturesCache.push(texture); - return texture; -}; -ThinEngine.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) { - const gl = this._gl; - 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) => { - const width = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width; - const height = width; - const faces = [ - gl.TEXTURE_CUBE_MAP_POSITIVE_X, - gl.TEXTURE_CUBE_MAP_POSITIVE_Y, - gl.TEXTURE_CUBE_MAP_POSITIVE_Z, - gl.TEXTURE_CUBE_MAP_NEGATIVE_X, - gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, - gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, - ]; - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); - this._unpackFlipY(false); - const internalFormat = format ? this._getInternalFormat(format, texture._useSRGBBuffer) : texture._useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : gl.RGBA; - let texelFormat = format ? this._getInternalFormat(format) : gl.RGBA; - if (texture._useSRGBBuffer && this.webGLVersion === 1) { - texelFormat = internalFormat; - } - for (let index = 0; index < faces.length; index++) { - if (imgs[index].width !== width || imgs[index].height !== height) { - this._prepareWorkingCanvas(); - if (!this._workingCanvas || !this._workingContext) { - logger_Logger.Warn("Cannot create canvas to resize texture."); - return; - } - this._workingCanvas.width = width; - this._workingCanvas.height = height; - this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height); - gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, this._workingCanvas); - } - else { - gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, imgs[index]); - } - } - if (!noMipmap) { - gl.generateMipmap(gl.TEXTURE_CUBE_MAP); - } - this._setCubeMapTextureParams(texture, !noMipmap); - texture.width = width; - texture.height = height; - texture.isReady = true; - if (format) { - texture.format = format; - } - texture.onLoadedObservable.notifyObservers(texture); - texture.onLoadedObservable.clear(); - if (onLoad) { - onLoad(); - } - }, !!useSRGBBuffer); -}; -//# sourceMappingURL=engine.cubeTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.textureSampler.js - -// eslint-disable-next-line @typescript-eslint/no-unused-vars -ThinEngine.prototype.setTextureSampler = function (name, sampler) { - throw new Error("setTextureSampler: This engine does not support separate texture sampler objects!"); -}; -//# sourceMappingURL=engine.textureSampler.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.views.js - - -/** - * Class used to define an additional view for the engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/multiCanvas - */ -class EngineView { -} -const _onBeforeViewRenderObservable = new observable_Observable(); -const _onAfterViewRenderObservable = new observable_Observable(); -Object.defineProperty(engine_Engine.prototype, "onBeforeViewRenderObservable", { - get: function () { - return _onBeforeViewRenderObservable; - }, -}); -Object.defineProperty(engine_Engine.prototype, "onAfterViewRenderObservable", { - get: function () { - return _onAfterViewRenderObservable; - }, -}); -Object.defineProperty(engine_Engine.prototype, "inputElement", { - get: function () { - return this._inputElement; - }, - set: function (value) { - var _a; - if (this._inputElement !== value) { - this._inputElement = value; - (_a = this._onEngineViewChanged) === null || _a === void 0 ? void 0 : _a.call(this); - } - }, -}); -engine_Engine.prototype.getInputElement = function () { - return this.inputElement || this.getRenderingCanvas(); -}; -engine_Engine.prototype.registerView = function (canvas, camera, clearBeforeCopy) { - if (!this.views) { - this.views = []; - } - for (const view of this.views) { - if (view.target === canvas) { - return view; - } - } - const masterCanvas = this.getRenderingCanvas(); - if (masterCanvas) { - canvas.width = masterCanvas.width; - canvas.height = masterCanvas.height; - } - const newView = { target: canvas, camera, clearBeforeCopy, enabled: true, id: (Math.random() * 100000).toFixed() }; - this.views.push(newView); - if (camera) { - camera.onDisposeObservable.add(() => { - this.unRegisterView(canvas); - }); - } - return newView; -}; -engine_Engine.prototype.unRegisterView = function (canvas) { - if (!this.views || this.views.length === 0) { - return this; - } - for (const view of this.views) { - if (view.target === canvas) { - const index = this.views.indexOf(view); - if (index !== -1) { - this.views.splice(index, 1); - } - break; - } - } - return this; -}; -engine_Engine.prototype._renderViewStep = function (view) { - const canvas = view.target; - const context = canvas.getContext("2d"); - if (!context) { - return true; - } - const parent = this.getRenderingCanvas(); - _onBeforeViewRenderObservable.notifyObservers(view); - const camera = view.camera; - let previewCamera = null; - let scene = null; - if (camera) { - scene = camera.getScene(); - if (!scene || (scene.activeCameras && scene.activeCameras.length)) { - return true; - } - this.activeView = view; - previewCamera = scene.activeCamera; - scene.activeCamera = camera; - } - if (view.customResize) { - view.customResize(canvas); - } - else { - // Set sizes - const width = Math.floor(canvas.clientWidth / this._hardwareScalingLevel); - const height = Math.floor(canvas.clientHeight / this._hardwareScalingLevel); - const dimsChanged = width !== canvas.width || parent.width !== canvas.width || height !== canvas.height || parent.height !== canvas.height; - if (canvas.clientWidth && canvas.clientHeight && dimsChanged) { - canvas.width = width; - canvas.height = height; - this.setSize(width, height); - } - } - if (!parent.width || !parent.height) { - return false; - } - // Render the frame - this._renderFrame(); - this.flushFramebuffer(); - // Copy to target - if (view.clearBeforeCopy) { - context.clearRect(0, 0, parent.width, parent.height); - } - context.drawImage(parent, 0, 0); - // Restore - if (previewCamera && scene) { - scene.activeCamera = previewCamera; - } - _onAfterViewRenderObservable.notifyObservers(view); - return true; -}; -engine_Engine.prototype._renderViews = function () { - if (!this.views || this.views.length === 0) { - return false; - } - const parent = this.getRenderingCanvas(); - if (!parent) { - return false; - } - let inputElementView; - for (const view of this.views) { - if (!view.enabled) { - continue; - } - const canvas = view.target; - // Always render the view correspondent to the inputElement for last - if (canvas === this.inputElement) { - inputElementView = view; - continue; - } - if (!this._renderViewStep(view)) { - return false; - } - } - if (inputElementView) { - if (!this._renderViewStep(inputElementView)) { - return false; - } - } - this.activeView = null; - return true; -}; -//# sourceMappingURL=engine.views.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.storageBuffer.js - -// eslint-disable-next-line @typescript-eslint/no-unused-vars -ThinEngine.prototype.createStorageBuffer = function (data, creationFlags) { - throw new Error("createStorageBuffer: Unsupported method in this engine!"); -}; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -ThinEngine.prototype.updateStorageBuffer = function (buffer, data, byteOffset, byteLength) { }; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -ThinEngine.prototype.readFromStorageBuffer = function (storageBuffer, offset, size, buffer) { - throw new Error("readFromStorageBuffer: Unsupported method in this engine!"); -}; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -ThinEngine.prototype.setStorageBuffer = function (name, buffer) { - throw new Error("setStorageBuffer: Unsupported method in this engine!"); -}; -//# sourceMappingURL=engine.storageBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/engine.textureSelector.js - -function transformTextureUrl(url) { - const excludeFn = (entry) => { - const strRegExPattern = "\\b" + entry + "\\b"; - return url && (url === entry || url.match(new RegExp(strRegExPattern, "g"))); - }; - if (this._excludedCompressedTextures && this._excludedCompressedTextures.some(excludeFn)) { - return url; - } - const lastDot = url.lastIndexOf("."); - const lastQuestionMark = url.lastIndexOf("?"); - const querystring = lastQuestionMark > -1 ? url.substring(lastQuestionMark, url.length) : ""; - return (lastDot > -1 ? url.substring(0, lastDot) : url) + this._textureFormatInUse + querystring; -} -Object.defineProperty(engine_Engine.prototype, "texturesSupported", { - get: function () { - // Intelligently add supported compressed formats in order to check for. - // Check for ASTC support first as it is most powerful and to be very cross platform. - // Next PVRTC & DXT, which are probably superior to ETC1/2. - // Likely no hardware which supports both PVR & DXT, so order matters little. - // ETC2 is newer and handles ETC1 (no alpha capability), so check for first. - const texturesSupported = new Array(); - if (this._caps.astc) { - texturesSupported.push("-astc.ktx"); - } - if (this._caps.s3tc) { - texturesSupported.push("-dxt.ktx"); - } - if (this._caps.pvrtc) { - texturesSupported.push("-pvrtc.ktx"); - } - if (this._caps.etc2) { - texturesSupported.push("-etc2.ktx"); - } - if (this._caps.etc1) { - texturesSupported.push("-etc1.ktx"); - } - return texturesSupported; - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(engine_Engine.prototype, "textureFormatInUse", { - get: function () { - return this._textureFormatInUse || null; - }, - enumerable: true, - configurable: true, -}); -engine_Engine.prototype.setCompressedTextureExclusions = function (skippedFiles) { - this._excludedCompressedTextures = skippedFiles; -}; -engine_Engine.prototype.setTextureFormatToUse = function (formatsAvailable) { - const texturesSupported = this.texturesSupported; - for (let i = 0, len1 = texturesSupported.length; i < len1; i++) { - for (let j = 0, len2 = formatsAvailable.length; j < len2; j++) { - if (texturesSupported[i] === formatsAvailable[j].toLowerCase()) { - this._transformTextureUrl = transformTextureUrl.bind(this); - return (this._textureFormatInUse = texturesSupported[i]); - } - } - } - // actively set format to nothing, to allow this to be called more than once - // and possibly fail the 2nd time - this._textureFormatInUse = ""; - this._transformTextureUrl = null; - return null; -}; -//# sourceMappingURL=engine.textureSelector.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Extensions/index.js -/* eslint-disable import/export */ - - - - - - - - - - - - - - - - - - - - - -// must import first since nothing references the exports - -// eslint-disable-next-line no-duplicate-imports - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Native/nativeDataStream.js -/** @internal */ -class NativeDataStream { - constructor() { - const buffer = new ArrayBuffer(NativeDataStream.DEFAULT_BUFFER_SIZE); - this._uint32s = new Uint32Array(buffer); - this._int32s = new Int32Array(buffer); - this._float32s = new Float32Array(buffer); - this._length = NativeDataStream.DEFAULT_BUFFER_SIZE / 4; - this._position = 0; - this._nativeDataStream = new _native.NativeDataStream(() => { - this._flush(); - }); - } - writeUint32(value) { - this._flushIfNecessary(1); - this._uint32s[this._position++] = value; - } - writeInt32(value) { - this._flushIfNecessary(1); - this._int32s[this._position++] = value; - } - writeFloat32(value) { - this._flushIfNecessary(1); - this._float32s[this._position++] = value; - } - writeUint32Array(values) { - this._flushIfNecessary(1 + values.length); - this._uint32s[this._position++] = values.length; - this._uint32s.set(values, this._position); - this._position += values.length; - } - writeInt32Array(values) { - this._flushIfNecessary(1 + values.length); - this._uint32s[this._position++] = values.length; - this._int32s.set(values, this._position); - this._position += values.length; - } - writeFloat32Array(values) { - this._flushIfNecessary(1 + values.length); - this._uint32s[this._position++] = values.length; - this._float32s.set(values, this._position); - this._position += values.length; - } - writeNativeData(handle) { - this._flushIfNecessary(handle.length); - this._uint32s.set(handle, this._position); - this._position += handle.length; - } - writeBoolean(value) { - this.writeUint32(value ? 1 : 0); - } - _flushIfNecessary(required) { - if (this._position + required > this._length) { - this._flush(); - } - } - _flush() { - this._nativeDataStream.writeBuffer(this._uint32s.buffer, this._position); - this._position = 0; - } -} -// Must be multiple of 4! -// eslint-disable-next-line @typescript-eslint/naming-convention -NativeDataStream.DEFAULT_BUFFER_SIZE = 65536; -//# sourceMappingURL=nativeDataStream.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/sphericalPolynomial.js -/* eslint-disable @typescript-eslint/naming-convention */ - - -// https://dickyjim.wordpress.com/2013/09/04/spherical-harmonics-for-beginners/ -// http://silviojemma.com/public/papers/lighting/spherical-harmonic-lighting.pdf -// https://www.ppsloan.org/publications/StupidSH36.pdf -// http://cseweb.ucsd.edu/~ravir/papers/envmap/envmap.pdf -// https://www.ppsloan.org/publications/SHJCGT.pdf -// https://www.ppsloan.org/publications/shdering.pdf -// https://google.github.io/filament/Filament.md.html#annex/sphericalharmonics -// https://patapom.com/blog/SHPortal/ -// https://imdoingitwrong.wordpress.com/2011/04/14/spherical-harmonics-wtf/ -// Using real SH basis: -// m>0 m m -// y = sqrt(2) * K * P * cos(m*phi) * cos(theta) -// l l l -// -// m<0 m |m| -// y = sqrt(2) * K * P * sin(m*phi) * cos(theta) -// l l l -// -// m=0 0 0 -// y = K * P * trigono terms -// l l l -// -// m (2l + 1)(l - |m|)! -// K = sqrt(------------------) -// l 4pi(l + |m|)! -// -// and P by recursion: -// -// P00(x) = 1 -// P01(x) = x -// Pll(x) = (-1^l)(2l - 1)!!(1-x*x)^(1/2) -// ((2l - 1)x[Pl-1/m]-(l + m - 1)[Pl-2/m]) -// Plm(x) = --------------------------------------- -// l - m -// Leaving the trigonometric terms aside we can precompute the constants to : -const SH3ylmBasisConstants = [ - 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)), // l22 -]; -// cm = cos(m * phi) -// sm = sin(m * phi) -// {x,y,z} = {cos(phi)sin(theta), sin(phi)sin(theta), cos(theta)} -// By recursion on using trigo identities: -const SH3ylmBasisTrigonometricTerms = [ - () => 1, - (direction) => direction.y, - (direction) => direction.z, - (direction) => direction.x, - (direction) => direction.x * direction.y, - (direction) => direction.y * direction.z, - (direction) => 3 * direction.z * direction.z - 1, - (direction) => direction.x * direction.z, - (direction) => direction.x * direction.x - direction.y * direction.y, // l22 -]; -// Wrap the full compute -const applySH3 = (lm, direction) => { - return SH3ylmBasisConstants[lm] * SH3ylmBasisTrigonometricTerms[lm](direction); -}; -// Derived from the integration of the a kernel convolution to SH. -// Great explanation here: https://patapom.com/blog/SHPortal/#about-distant-radiance-and-irradiance-environments -const SHCosKernelConvolution = [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 representing spherical harmonics coefficients to the 3rd degree - */ -class SphericalHarmonics { - constructor() { - /** - * Defines whether or not the harmonics have been prescaled for rendering. - */ - this.preScaled = false; - /** - * The l0,0 coefficients of the spherical harmonics - */ - this.l00 = math_vector_Vector3.Zero(); - /** - * The l1,-1 coefficients of the spherical harmonics - */ - this.l1_1 = math_vector_Vector3.Zero(); - /** - * The l1,0 coefficients of the spherical harmonics - */ - this.l10 = math_vector_Vector3.Zero(); - /** - * The l1,1 coefficients of the spherical harmonics - */ - this.l11 = math_vector_Vector3.Zero(); - /** - * The l2,-2 coefficients of the spherical harmonics - */ - this.l2_2 = math_vector_Vector3.Zero(); - /** - * The l2,-1 coefficients of the spherical harmonics - */ - this.l2_1 = math_vector_Vector3.Zero(); - /** - * The l2,0 coefficients of the spherical harmonics - */ - this.l20 = math_vector_Vector3.Zero(); - /** - * The l2,1 coefficients of the spherical harmonics - */ - this.l21 = math_vector_Vector3.Zero(); - /** - * The l2,2 coefficients of the spherical harmonics - */ - this.l22 = math_vector_Vector3.Zero(); - } - /** - * Adds a light to the spherical harmonics - * @param direction the direction of the light - * @param color the color of the light - * @param deltaSolidAngle the delta solid angle of the light - */ - addLight(direction, color, deltaSolidAngle) { - math_vector_TmpVectors.Vector3[0].set(color.r, color.g, color.b); - const colorVector = math_vector_TmpVectors.Vector3[0]; - const c = math_vector_TmpVectors.Vector3[1]; - colorVector.scaleToRef(deltaSolidAngle, c); - c.scaleToRef(applySH3(0, direction), math_vector_TmpVectors.Vector3[2]); - this.l00.addInPlace(math_vector_TmpVectors.Vector3[2]); - c.scaleToRef(applySH3(1, direction), math_vector_TmpVectors.Vector3[2]); - this.l1_1.addInPlace(math_vector_TmpVectors.Vector3[2]); - c.scaleToRef(applySH3(2, direction), math_vector_TmpVectors.Vector3[2]); - this.l10.addInPlace(math_vector_TmpVectors.Vector3[2]); - c.scaleToRef(applySH3(3, direction), math_vector_TmpVectors.Vector3[2]); - this.l11.addInPlace(math_vector_TmpVectors.Vector3[2]); - c.scaleToRef(applySH3(4, direction), math_vector_TmpVectors.Vector3[2]); - this.l2_2.addInPlace(math_vector_TmpVectors.Vector3[2]); - c.scaleToRef(applySH3(5, direction), math_vector_TmpVectors.Vector3[2]); - this.l2_1.addInPlace(math_vector_TmpVectors.Vector3[2]); - c.scaleToRef(applySH3(6, direction), math_vector_TmpVectors.Vector3[2]); - this.l20.addInPlace(math_vector_TmpVectors.Vector3[2]); - c.scaleToRef(applySH3(7, direction), math_vector_TmpVectors.Vector3[2]); - this.l21.addInPlace(math_vector_TmpVectors.Vector3[2]); - c.scaleToRef(applySH3(8, direction), math_vector_TmpVectors.Vector3[2]); - this.l22.addInPlace(math_vector_TmpVectors.Vector3[2]); - } - /** - * Scales the spherical harmonics by the given amount - * @param scale the amount to scale - */ - scaleInPlace(scale) { - this.l00.scaleInPlace(scale); - this.l1_1.scaleInPlace(scale); - this.l10.scaleInPlace(scale); - this.l11.scaleInPlace(scale); - this.l2_2.scaleInPlace(scale); - this.l2_1.scaleInPlace(scale); - this.l20.scaleInPlace(scale); - this.l21.scaleInPlace(scale); - this.l22.scaleInPlace(scale); - } - /** - * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere. - * - * ``` - * E_lm = A_l * L_lm - * ``` - * - * In spherical harmonics this convolution amounts to scaling factors for each frequency band. - * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where - * the scaling factors are given in equation 9. - */ - convertIncidentRadianceToIrradiance() { - // Constant (Band 0) - this.l00.scaleInPlace(SHCosKernelConvolution[0]); - // Linear (Band 1) - this.l1_1.scaleInPlace(SHCosKernelConvolution[1]); - this.l10.scaleInPlace(SHCosKernelConvolution[2]); - this.l11.scaleInPlace(SHCosKernelConvolution[3]); - // Quadratic (Band 2) - this.l2_2.scaleInPlace(SHCosKernelConvolution[4]); - this.l2_1.scaleInPlace(SHCosKernelConvolution[5]); - this.l20.scaleInPlace(SHCosKernelConvolution[6]); - this.l21.scaleInPlace(SHCosKernelConvolution[7]); - this.l22.scaleInPlace(SHCosKernelConvolution[8]); - } - /** - * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation. - * - * ``` - * L = (1/pi) * E * rho - * ``` - * - * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually. - */ - convertIrradianceToLambertianRadiance() { - this.scaleInPlace(1.0 / Math.PI); - // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied - // (The pixel shader must apply albedo after texture fetches, etc). - } - /** - * Integrates the reconstruction coefficients directly in to the SH preventing further - * required operations at run time. - * - * This is simply done by scaling back the SH with Ylm constants parameter. - * The trigonometric part being applied by the shader at run time. - */ - preScaleForRendering() { - this.preScaled = true; - this.l00.scaleInPlace(SH3ylmBasisConstants[0]); - this.l1_1.scaleInPlace(SH3ylmBasisConstants[1]); - this.l10.scaleInPlace(SH3ylmBasisConstants[2]); - this.l11.scaleInPlace(SH3ylmBasisConstants[3]); - this.l2_2.scaleInPlace(SH3ylmBasisConstants[4]); - this.l2_1.scaleInPlace(SH3ylmBasisConstants[5]); - this.l20.scaleInPlace(SH3ylmBasisConstants[6]); - this.l21.scaleInPlace(SH3ylmBasisConstants[7]); - this.l22.scaleInPlace(SH3ylmBasisConstants[8]); - } - /** - * update the spherical harmonics coefficients from the given array - * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22) - * @returns the spherical harmonics (this) - */ - updateFromArray(data) { - math_vector_Vector3.FromArrayToRef(data[0], 0, this.l00); - math_vector_Vector3.FromArrayToRef(data[1], 0, this.l1_1); - math_vector_Vector3.FromArrayToRef(data[2], 0, this.l10); - math_vector_Vector3.FromArrayToRef(data[3], 0, this.l11); - math_vector_Vector3.FromArrayToRef(data[4], 0, this.l2_2); - math_vector_Vector3.FromArrayToRef(data[5], 0, this.l2_1); - math_vector_Vector3.FromArrayToRef(data[6], 0, this.l20); - math_vector_Vector3.FromArrayToRef(data[7], 0, this.l21); - math_vector_Vector3.FromArrayToRef(data[8], 0, this.l22); - return this; - } - /** - * update the spherical harmonics coefficients from the given floats array - * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22) - * @returns the spherical harmonics (this) - */ - updateFromFloatsArray(data) { - math_vector_Vector3.FromFloatsToRef(data[0], data[1], data[2], this.l00); - math_vector_Vector3.FromFloatsToRef(data[3], data[4], data[5], this.l1_1); - math_vector_Vector3.FromFloatsToRef(data[6], data[7], data[8], this.l10); - math_vector_Vector3.FromFloatsToRef(data[9], data[10], data[11], this.l11); - math_vector_Vector3.FromFloatsToRef(data[12], data[13], data[14], this.l2_2); - math_vector_Vector3.FromFloatsToRef(data[15], data[16], data[17], this.l2_1); - math_vector_Vector3.FromFloatsToRef(data[18], data[19], data[20], this.l20); - math_vector_Vector3.FromFloatsToRef(data[21], data[22], data[23], this.l21); - math_vector_Vector3.FromFloatsToRef(data[24], data[25], data[26], this.l22); - return this; - } - /** - * Constructs a spherical harmonics from an array. - * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22) - * @returns the spherical harmonics - */ - static FromArray(data) { - const sh = new SphericalHarmonics(); - return sh.updateFromArray(data); - } - // Keep for references. - /** - * Gets the spherical harmonics from polynomial - * @param polynomial the spherical polynomial - * @returns the spherical harmonics - */ - static FromPolynomial(polynomial) { - const result = new SphericalHarmonics(); - result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126)); - result.l1_1 = polynomial.y.scale(0.977204); - result.l10 = polynomial.z.scale(0.977204); - result.l11 = polynomial.x.scale(0.977204); - result.l2_2 = polynomial.xy.scale(1.16538); - result.l2_1 = polynomial.yz.scale(1.16538); - result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834)); - result.l21 = polynomial.zx.scale(1.16538); - result.l22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538)); - result.l1_1.scaleInPlace(-1); - result.l11.scaleInPlace(-1); - result.l2_1.scaleInPlace(-1); - result.l21.scaleInPlace(-1); - result.scaleInPlace(Math.PI); - return result; - } -} -/** - * Class representing spherical polynomial coefficients to the 3rd degree - */ -class SphericalPolynomial { - constructor() { - /** - * The x coefficients of the spherical polynomial - */ - this.x = math_vector_Vector3.Zero(); - /** - * The y coefficients of the spherical polynomial - */ - this.y = math_vector_Vector3.Zero(); - /** - * The z coefficients of the spherical polynomial - */ - this.z = math_vector_Vector3.Zero(); - /** - * The xx coefficients of the spherical polynomial - */ - this.xx = math_vector_Vector3.Zero(); - /** - * The yy coefficients of the spherical polynomial - */ - this.yy = math_vector_Vector3.Zero(); - /** - * The zz coefficients of the spherical polynomial - */ - this.zz = math_vector_Vector3.Zero(); - /** - * The xy coefficients of the spherical polynomial - */ - this.xy = math_vector_Vector3.Zero(); - /** - * The yz coefficients of the spherical polynomial - */ - this.yz = math_vector_Vector3.Zero(); - /** - * The zx coefficients of the spherical polynomial - */ - this.zx = math_vector_Vector3.Zero(); - } - /** - * The spherical harmonics used to create the polynomials. - */ - get preScaledHarmonics() { - if (!this._harmonics) { - this._harmonics = SphericalHarmonics.FromPolynomial(this); - } - if (!this._harmonics.preScaled) { - this._harmonics.preScaleForRendering(); - } - return this._harmonics; - } - /** - * Adds an ambient color to the spherical polynomial - * @param color the color to add - */ - addAmbient(color) { - math_vector_TmpVectors.Vector3[0].copyFromFloats(color.r, color.g, color.b); - const colorVector = math_vector_TmpVectors.Vector3[0]; - this.xx.addInPlace(colorVector); - this.yy.addInPlace(colorVector); - this.zz.addInPlace(colorVector); - } - /** - * Scales the spherical polynomial by the given amount - * @param scale the amount to scale - */ - scaleInPlace(scale) { - this.x.scaleInPlace(scale); - this.y.scaleInPlace(scale); - this.z.scaleInPlace(scale); - this.xx.scaleInPlace(scale); - this.yy.scaleInPlace(scale); - this.zz.scaleInPlace(scale); - this.yz.scaleInPlace(scale); - this.zx.scaleInPlace(scale); - this.xy.scaleInPlace(scale); - } - /** - * Updates the spherical polynomial from harmonics - * @param harmonics the spherical harmonics - * @returns the spherical polynomial - */ - updateFromHarmonics(harmonics) { - this._harmonics = harmonics; - this.x.copyFrom(harmonics.l11); - this.x.scaleInPlace(1.02333).scaleInPlace(-1); - this.y.copyFrom(harmonics.l1_1); - this.y.scaleInPlace(1.02333).scaleInPlace(-1); - this.z.copyFrom(harmonics.l10); - this.z.scaleInPlace(1.02333); - this.xx.copyFrom(harmonics.l00); - math_vector_TmpVectors.Vector3[0].copyFrom(harmonics.l20).scaleInPlace(0.247708); - math_vector_TmpVectors.Vector3[1].copyFrom(harmonics.l22).scaleInPlace(0.429043); - this.xx.scaleInPlace(0.886277).subtractInPlace(math_vector_TmpVectors.Vector3[0]).addInPlace(math_vector_TmpVectors.Vector3[1]); - this.yy.copyFrom(harmonics.l00); - this.yy.scaleInPlace(0.886277).subtractInPlace(math_vector_TmpVectors.Vector3[0]).subtractInPlace(math_vector_TmpVectors.Vector3[1]); - this.zz.copyFrom(harmonics.l00); - math_vector_TmpVectors.Vector3[0].copyFrom(harmonics.l20).scaleInPlace(0.495417); - this.zz.scaleInPlace(0.886277).addInPlace(math_vector_TmpVectors.Vector3[0]); - this.yz.copyFrom(harmonics.l2_1); - this.yz.scaleInPlace(0.858086).scaleInPlace(-1); - this.zx.copyFrom(harmonics.l21); - this.zx.scaleInPlace(0.858086).scaleInPlace(-1); - this.xy.copyFrom(harmonics.l2_2); - this.xy.scaleInPlace(0.858086); - this.scaleInPlace(1.0 / Math.PI); - return this; - } - /** - * Gets the spherical polynomial from harmonics - * @param harmonics the spherical harmonics - * @returns the spherical polynomial - */ - static FromHarmonics(harmonics) { - const result = new SphericalPolynomial(); - return result.updateFromHarmonics(harmonics); - } - /** - * Constructs a spherical polynomial from an array. - * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy) - * @returns the spherical polynomial - */ - static FromArray(data) { - const sp = new SphericalPolynomial(); - math_vector_Vector3.FromArrayToRef(data[0], 0, sp.x); - math_vector_Vector3.FromArrayToRef(data[1], 0, sp.y); - math_vector_Vector3.FromArrayToRef(data[2], 0, sp.z); - math_vector_Vector3.FromArrayToRef(data[3], 0, sp.xx); - math_vector_Vector3.FromArrayToRef(data[4], 0, sp.yy); - math_vector_Vector3.FromArrayToRef(data[5], 0, sp.zz); - math_vector_Vector3.FromArrayToRef(data[6], 0, sp.yz); - math_vector_Vector3.FromArrayToRef(data[7], 0, sp.zx); - math_vector_Vector3.FromArrayToRef(data[8], 0, sp.xy); - return sp; - } -} -//# sourceMappingURL=sphericalPolynomial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/rgbdDecode.fragment.js -// Do not edit. - - -const rgbdDecode_fragment_name = "rgbdDecodePixelShader"; -const rgbdDecode_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler; -#include<helperFunctions> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`; -// Sideeffect -ShaderStore.ShadersStore[rgbdDecode_fragment_name] = rgbdDecode_fragment_shader; -/** @internal */ -const rgbdDecodePixelShader = { name: rgbdDecode_fragment_name, shader: rgbdDecode_fragment_shader }; -//# sourceMappingURL=rgbdDecode.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/textureTools.js - - - - - -/** - * Uses the GPU to create a copy texture rescaled at a given size - * @param texture Texture to copy from - * @param width defines the desired width - * @param height defines the desired height - * @param useBilinearMode defines if bilinear mode has to be used - * @returns the generated texture - */ -function CreateResizedCopy(texture, width, height, useBilinearMode = true) { - const scene = texture.getScene(); - const engine = scene.getEngine(); - const rtt = new renderTargetTexture_RenderTargetTexture("resized" + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture.samplingMode, false); - rtt.wrapU = texture.wrapU; - rtt.wrapV = texture.wrapV; - rtt.uOffset = texture.uOffset; - rtt.vOffset = texture.vOffset; - rtt.uScale = texture.uScale; - rtt.vScale = texture.vScale; - rtt.uAng = texture.uAng; - rtt.vAng = texture.vAng; - rtt.wAng = texture.wAng; - rtt.coordinatesIndex = texture.coordinatesIndex; - rtt.level = texture.level; - rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel; - rtt._texture.isReady = false; - texture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - texture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - const passPostProcess = new PassPostProcess("pass", 1, null, useBilinearMode ? texture_Texture.BILINEAR_SAMPLINGMODE : texture_Texture.NEAREST_SAMPLINGMODE, engine, false, 0); - passPostProcess.externalTextureSamplerBinding = true; - passPostProcess.getEffect().executeWhenCompiled(() => { - passPostProcess.onApply = function (effect) { - effect.setTexture("textureSampler", texture); - }; - const internalTexture = rtt.renderTarget; - if (internalTexture) { - scene.postProcessManager.directRender([passPostProcess], internalTexture); - engine.unBindFramebuffer(internalTexture); - rtt.disposeFramebufferObjects(); - passPostProcess.dispose(); - rtt.getInternalTexture().isReady = true; - } - }); - return rtt; -} -/** - * Apply a post process to a texture - * @param postProcessName name of the fragment post process - * @param internalTexture the texture to encode - * @param scene the scene hosting the texture - * @param type type of the output texture. If not provided, use the one from internalTexture - * @param samplingMode sampling mode to use to sample the source texture. If not provided, use the one from internalTexture - * @param format format of the output texture. If not provided, use the one from internalTexture - * @returns a promise with the internalTexture having its texture replaced by the result of the processing - */ -function ApplyPostProcess(postProcessName, internalTexture, scene, type, samplingMode, format, width, height) { - // Gets everything ready. - const engine = internalTexture.getEngine(); - internalTexture.isReady = false; - samplingMode = samplingMode !== null && samplingMode !== void 0 ? samplingMode : internalTexture.samplingMode; - type = type !== null && type !== void 0 ? type : internalTexture.type; - format = format !== null && format !== void 0 ? format : internalTexture.format; - width = width !== null && width !== void 0 ? width : internalTexture.width; - height = height !== null && height !== void 0 ? height : internalTexture.height; - if (type === -1) { - type = 0; - } - return new Promise((resolve) => { - // Create the post process - const postProcess = new postProcess_PostProcess("postprocess", postProcessName, null, null, 1, null, samplingMode, engine, false, undefined, type, undefined, null, false, format); - postProcess.externalTextureSamplerBinding = true; - // Hold the output of the decoding. - const encodedTexture = engine.createRenderTargetTexture({ width: width, height: height }, { - generateDepthBuffer: false, - generateMipMaps: false, - generateStencilBuffer: false, - samplingMode, - type, - format, - }); - postProcess.getEffect().executeWhenCompiled(() => { - // PP Render Pass - postProcess.onApply = (effect) => { - effect._bindTexture("textureSampler", internalTexture); - effect.setFloat2("scale", 1, 1); - }; - scene.postProcessManager.directRender([postProcess], encodedTexture, true); - // Cleanup - engine.restoreDefaultFramebuffer(); - engine._releaseTexture(internalTexture); - if (postProcess) { - postProcess.dispose(); - } - // Internal Swap - encodedTexture._swapAndDie(internalTexture); - // Ready to get rolling again. - internalTexture.type = type; - internalTexture.format = 5; - internalTexture.isReady = true; - resolve(internalTexture); - }); - }); -} -// ref: http://stackoverflow.com/questions/32633585/how-do-you-convert-to-half-floats-in-javascript -let floatView; -let int32View; -/** - * Converts a number to half float - * @param value number to convert - * @returns converted number - */ -function ToHalfFloat(value) { - if (!floatView) { - floatView = new Float32Array(1); - int32View = new Int32Array(floatView.buffer); - } - floatView[0] = value; - const x = int32View[0]; - let bits = (x >> 16) & 0x8000; /* Get the sign */ - let m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */ - const e = (x >> 23) & 0xff; /* Using int is faster here */ - /* If zero, or denormal, or exponent underflows too much for a denormal - * half, return signed zero. */ - if (e < 103) { - return bits; - } - /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */ - if (e > 142) { - bits |= 0x7c00; - /* If exponent was 0xff and one mantissa bit was set, it means NaN, - * not Inf, so make sure we set one mantissa bit too. */ - bits |= (e == 255 ? 0 : 1) && x & 0x007fffff; - return bits; - } - /* If exponent underflows but not too much, return a denormal */ - if (e < 113) { - m |= 0x0800; - /* Extra rounding may overflow and set mantissa to 0 and exponent - * to 1, which is OK. */ - bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1); - return bits; - } - bits |= ((e - 112) << 10) | (m >> 1); - bits += m & 1; - return bits; -} -/** - * Converts a half float to a number - * @param value half float to convert - * @returns converted half float - */ -function FromHalfFloat(value) { - const s = (value & 0x8000) >> 15; - const e = (value & 0x7c00) >> 10; - const f = value & 0x03ff; - if (e === 0) { - return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10)); - } - else if (e == 0x1f) { - return f ? NaN : (s ? -1 : 1) * Infinity; - } - return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + f / Math.pow(2, 10)); -} -/** - * Class used to host texture specific utilities - */ -const TextureTools = { - /** - * Uses the GPU to create a copy texture rescaled at a given size - * @param texture Texture to copy from - * @param width defines the desired width - * @param height defines the desired height - * @param useBilinearMode defines if bilinear mode has to be used - * @returns the generated texture - */ - CreateResizedCopy, - /** - * Apply a post process to a texture - * @param postProcessName name of the fragment post process - * @param internalTexture the texture to encode - * @param scene the scene hosting the texture - * @param type type of the output texture. If not provided, use the one from internalTexture - * @param samplingMode sampling mode to use to sample the source texture. If not provided, use the one from internalTexture - * @param format format of the output texture. If not provided, use the one from internalTexture - * @returns a promise with the internalTexture having its texture replaced by the result of the processing - */ - ApplyPostProcess, - /** - * Converts a number to half float - * @param value number to convert - * @returns converted number - */ - ToHalfFloat, - /** - * Converts a half float to a number - * @param value half float to convert - * @returns converted half float - */ - FromHalfFloat, -}; -//# sourceMappingURL=textureTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/rgbdTextureTools.js - - - - - -/** - * Class used to host RGBD texture specific utilities - */ -class RGBDTextureTools { - /** - * Expand the RGBD Texture from RGBD to Half Float if possible. - * @param texture the texture to expand. - */ - static ExpandRGBDTexture(texture) { - const internalTexture = texture._texture; - if (!internalTexture || !texture.isRGBD) { - return; - } - // Gets everything ready. - const engine = internalTexture.getEngine(); - const caps = engine.getCaps(); - const isReady = internalTexture.isReady; - let expandTexture = false; - // If half float available we can uncompress the texture - if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { - expandTexture = true; - internalTexture.type = 2; - } - // If full float available we can uncompress the texture - else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { - expandTexture = true; - internalTexture.type = 1; - } - if (expandTexture) { - // Do not use during decode. - internalTexture.isReady = false; - internalTexture._isRGBD = false; - internalTexture.invertY = false; - } - const expandRGBDTexture = () => { - // Expand the texture if possible - if (expandTexture) { - // Simply run through the decode PP. - const rgbdPostProcess = new postProcess_PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, 3, engine, false, undefined, internalTexture.type, undefined, null, false); - rgbdPostProcess.externalTextureSamplerBinding = true; - // Hold the output of the decoding. - const expandedTexture = engine.createRenderTargetTexture(internalTexture.width, { - generateDepthBuffer: false, - generateMipMaps: false, - generateStencilBuffer: false, - samplingMode: internalTexture.samplingMode, - type: internalTexture.type, - format: 5, - }); - rgbdPostProcess.getEffect().executeWhenCompiled(() => { - // PP Render Pass - rgbdPostProcess.onApply = (effect) => { - effect._bindTexture("textureSampler", internalTexture); - effect.setFloat2("scale", 1, 1); - }; - texture.getScene().postProcessManager.directRender([rgbdPostProcess], expandedTexture, true); - // Cleanup - engine.restoreDefaultFramebuffer(); - engine._releaseTexture(internalTexture); - if (rgbdPostProcess) { - rgbdPostProcess.dispose(); - } - // Internal Swap - expandedTexture._swapAndDie(internalTexture); - // Ready to get rolling again. - internalTexture.isReady = true; - }); - } - }; - if (isReady) { - expandRGBDTexture(); - } - else { - texture.onLoadObservable.addOnce(expandRGBDTexture); - } - } - /** - * Encode the texture to RGBD if possible. - * @param internalTexture the texture to encode - * @param scene the scene hosting the texture - * @param outputTextureType type of the texture in which the encoding is performed - * @returns a promise with the internalTexture having its texture replaced by the result of the processing - */ - static EncodeTextureToRGBD(internalTexture, scene, outputTextureType = 0) { - return ApplyPostProcess("rgbdEncode", internalTexture, scene, outputTextureType, 1, 5); - } -} -//# sourceMappingURL=rgbdTextureTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/HighDynamicRange/cubemapToSphericalPolynomial.js - - - - - - -class FileFaceOrientation { - constructor(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) { - this.name = name; - this.worldAxisForNormal = worldAxisForNormal; - this.worldAxisForFileX = worldAxisForFileX; - this.worldAxisForFileY = worldAxisForFileY; - } -} -/** - * Helper class dealing with the extraction of spherical polynomial dataArray - * from a cube map. - */ -class CubeMapToSphericalPolynomialTools { - /** - * Converts a texture to the according Spherical Polynomial data. - * This extracts the first 3 orders only as they are the only one used in the lighting. - * - * @param texture The texture to extract the information from. - * @returns The Spherical Polynomial data. - */ - static ConvertCubeMapTextureToSphericalPolynomial(texture) { - var _a; - if (!texture.isCube) { - // Only supports cube Textures currently. - return null; - } - (_a = texture.getScene()) === null || _a === void 0 ? void 0 : _a.getEngine().flushFramebuffer(); - const size = texture.getSize().width; - const rightPromise = texture.readPixels(0, undefined, undefined, false); - const leftPromise = texture.readPixels(1, undefined, undefined, false); - let upPromise; - let downPromise; - if (texture.isRenderTarget) { - upPromise = texture.readPixels(3, undefined, undefined, false); - downPromise = texture.readPixels(2, undefined, undefined, false); - } - else { - upPromise = texture.readPixels(2, undefined, undefined, false); - downPromise = texture.readPixels(3, undefined, undefined, false); - } - const frontPromise = texture.readPixels(4, undefined, undefined, false); - const backPromise = texture.readPixels(5, undefined, undefined, false); - const gammaSpace = texture.gammaSpace; - // Always read as RGBA. - const format = 5; - let type = 0; - if (texture.textureType == 1 || texture.textureType == 2) { - type = 1; - } - return new Promise((resolve) => { - Promise.all([leftPromise, rightPromise, upPromise, downPromise, frontPromise, backPromise]).then(([left, right, up, down, front, back]) => { - const cubeInfo = { - size, - right, - left, - up, - down, - front, - back, - format, - type, - gammaSpace, - }; - resolve(this.ConvertCubeMapToSphericalPolynomial(cubeInfo)); - }); - }); - } - /** - * Compute the area on the unit sphere of the rectangle defined by (x,y) and the origin - * See https://www.rorydriscoll.com/2012/01/15/cubemap-texel-solid-angle/ - * @param x - * @param y - */ - static _AreaElement(x, y) { - return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1)); - } - /** - * Converts a cubemap to the according Spherical Polynomial data. - * This extracts the first 3 orders only as they are the only one used in the lighting. - * - * @param cubeInfo The Cube map to extract the information from. - * @returns The Spherical Polynomial data. - */ - static ConvertCubeMapToSphericalPolynomial(cubeInfo) { - const sphericalHarmonics = new SphericalHarmonics(); - let totalSolidAngle = 0.0; - // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size. - const du = 2.0 / cubeInfo.size; - const dv = du; - const halfTexel = 0.5 * du; - // The (u,v) of the first texel is half a texel from the corner (-1,-1). - const minUV = halfTexel - 1.0; - for (let faceIndex = 0; faceIndex < 6; faceIndex++) { - const fileFace = this._FileFaces[faceIndex]; - const dataArray = cubeInfo[fileFace.name]; - let v = minUV; - // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH). - // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality. - // Because SP is still linear, so summation is fine in that basis. - const stride = cubeInfo.format === 5 ? 4 : 3; - for (let y = 0; y < cubeInfo.size; y++) { - let u = minUV; - for (let x = 0; x < cubeInfo.size; x++) { - // World direction (not normalised) - const worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal); - worldDirection.normalize(); - const deltaSolidAngle = this._AreaElement(u - halfTexel, v - halfTexel) - - this._AreaElement(u - halfTexel, v + halfTexel) - - this._AreaElement(u + halfTexel, v - halfTexel) + - this._AreaElement(u + halfTexel, v + halfTexel); - let r = dataArray[y * cubeInfo.size * stride + x * stride + 0]; - let g = dataArray[y * cubeInfo.size * stride + x * stride + 1]; - let b = dataArray[y * cubeInfo.size * stride + x * stride + 2]; - // Prevent NaN harmonics with extreme HDRI data. - if (isNaN(r)) { - r = 0; - } - if (isNaN(g)) { - g = 0; - } - if (isNaN(b)) { - b = 0; - } - // Handle Integer types. - if (cubeInfo.type === 0) { - r /= 255; - g /= 255; - b /= 255; - } - // Handle Gamma space textures. - if (cubeInfo.gammaSpace) { - r = Math.pow(math_scalar_Scalar.Clamp(r), ToLinearSpace); - g = Math.pow(math_scalar_Scalar.Clamp(g), ToLinearSpace); - b = Math.pow(math_scalar_Scalar.Clamp(b), ToLinearSpace); - } - // Prevent to explode in case of really high dynamic ranges. - // sh 3 would not be enough to accurately represent it. - const max = this.MAX_HDRI_VALUE; - if (this.PRESERVE_CLAMPED_COLORS) { - const currentMax = Math.max(r, g, b); - if (currentMax > max) { - const factor = max / currentMax; - r *= factor; - g *= factor; - b *= factor; - } - } - else { - r = math_scalar_Scalar.Clamp(r, 0, max); - g = math_scalar_Scalar.Clamp(g, 0, max); - b = math_scalar_Scalar.Clamp(b, 0, max); - } - const color = new math_color_Color3(r, g, b); - sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle); - totalSolidAngle += deltaSolidAngle; - u += du; - } - v += dv; - } - } - // Solid angle for entire sphere is 4*pi - const sphereSolidAngle = 4.0 * Math.PI; - // Adjust the solid angle to allow for how many faces we processed. - const facesProcessed = 6.0; - const expectedSolidAngle = (sphereSolidAngle * facesProcessed) / 6.0; - // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle. - // This is needed because the numerical integration over the cube uses a - // small angle approximation of solid angle for each texel (see deltaSolidAngle), - // and also to compensate for accumulative error due to float precision in the summation. - const correctionFactor = expectedSolidAngle / totalSolidAngle; - sphericalHarmonics.scaleInPlace(correctionFactor); - sphericalHarmonics.convertIncidentRadianceToIrradiance(); - sphericalHarmonics.convertIrradianceToLambertianRadiance(); - return SphericalPolynomial.FromHarmonics(sphericalHarmonics); - } -} -CubeMapToSphericalPolynomialTools._FileFaces = [ - new FileFaceOrientation("right", new math_vector_Vector3(1, 0, 0), new math_vector_Vector3(0, 0, -1), new math_vector_Vector3(0, -1, 0)), - new FileFaceOrientation("left", new math_vector_Vector3(-1, 0, 0), new math_vector_Vector3(0, 0, 1), new math_vector_Vector3(0, -1, 0)), - new FileFaceOrientation("up", new math_vector_Vector3(0, 1, 0), new math_vector_Vector3(1, 0, 0), new math_vector_Vector3(0, 0, 1)), - new FileFaceOrientation("down", new math_vector_Vector3(0, -1, 0), new math_vector_Vector3(1, 0, 0), new math_vector_Vector3(0, 0, -1)), - new FileFaceOrientation("front", new math_vector_Vector3(0, 0, 1), new math_vector_Vector3(1, 0, 0), new math_vector_Vector3(0, -1, 0)), - new FileFaceOrientation("back", new math_vector_Vector3(0, 0, -1), new math_vector_Vector3(-1, 0, 0), new math_vector_Vector3(0, -1, 0)), // -Z bottom -]; -/** @internal */ -CubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE = 4096; -/** @internal */ -CubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS = false; -//# sourceMappingURL=cubemapToSphericalPolynomial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/baseTexture.polynomial.js - - -baseTexture_BaseTexture.prototype.forceSphericalPolynomialsRecompute = function () { - if (this._texture) { - this._texture._sphericalPolynomial = null; - this._texture._sphericalPolynomialPromise = null; - this._texture._sphericalPolynomialComputed = false; - } -}; -Object.defineProperty(baseTexture_BaseTexture.prototype, "sphericalPolynomial", { - get: function () { - if (this._texture) { - if (this._texture._sphericalPolynomial || this._texture._sphericalPolynomialComputed) { - return this._texture._sphericalPolynomial; - } - if (this._texture.isReady) { - if (!this._texture._sphericalPolynomialPromise) { - this._texture._sphericalPolynomialPromise = CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this); - if (this._texture._sphericalPolynomialPromise === null) { - this._texture._sphericalPolynomialComputed = true; - } - else { - this._texture._sphericalPolynomialPromise.then((sphericalPolynomial) => { - this._texture._sphericalPolynomial = sphericalPolynomial; - this._texture._sphericalPolynomialComputed = true; - }); - } - } - return null; - } - } - return null; - }, - set: function (value) { - if (this._texture) { - this._texture._sphericalPolynomial = value; - } - }, - enumerable: true, - configurable: true, -}); -//# sourceMappingURL=baseTexture.polynomial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/rgbdEncode.fragment.js -// Do not edit. - - -const rgbdEncode_fragment_name = "rgbdEncodePixelShader"; -const rgbdEncode_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler; -#include<helperFunctions> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`; -// Sideeffect -ShaderStore.ShadersStore[rgbdEncode_fragment_name] = rgbdEncode_fragment_shader; -/** @internal */ -const rgbdEncodePixelShader = { name: rgbdEncode_fragment_name, shader: rgbdEncode_fragment_shader }; -//# sourceMappingURL=rgbdEncode.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/environmentTextureTools.js - - - - - - - - - - - - - - - - - -const DefaultEnvironmentTextureImageType = "image/png"; -const CurrentVersion = 2; -/** - * Magic number identifying the env file. - */ -const MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36]; -/** - * Gets the environment info from an env file. - * @param data The array buffer containing the .env bytes. - * @returns the environment file info (the json header) if successfully parsed, normalized to the latest supported version. - */ -function GetEnvInfo(data) { - const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); - let pos = 0; - for (let i = 0; i < MagicBytes.length; i++) { - if (dataView.getUint8(pos++) !== MagicBytes[i]) { - logger_Logger.Error("Not a babylon environment map"); - return null; - } - } - // Read json manifest - collect characters up to null terminator - let manifestString = ""; - let charCode = 0x00; - while ((charCode = dataView.getUint8(pos++))) { - manifestString += String.fromCharCode(charCode); - } - let manifest = JSON.parse(manifestString); - manifest = normalizeEnvInfo(manifest); - if (manifest.specular) { - // Extend the header with the position of the payload. - manifest.specular.specularDataPosition = pos; - // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility. - manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8; - } - return manifest; -} -/** - * Normalizes any supported version of the environment file info to the latest version - * @param info environment file info on any supported version - * @returns environment file info in the latest supported version - * @private - */ -function normalizeEnvInfo(info) { - if (info.version > CurrentVersion) { - throw new Error(`Unsupported babylon environment map version "${info.version}". Latest supported version is "${CurrentVersion}".`); - } - if (info.version === 2) { - return info; - } - // Migrate a v1 info to v2 - info = Object.assign(Object.assign({}, info), { version: 2, imageType: DefaultEnvironmentTextureImageType }); - return info; -} -/** - * Creates an environment texture from a loaded cube texture. - * @param texture defines the cube texture to convert in env file - * @param options options for the conversion process - * @param options.imageType the mime type for the encoded images, with support for "image/png" (default) and "image/webp" - * @param options.imageQuality the image quality of encoded WebP images. - * @returns a promise containing the environment data if successful. - */ -async function CreateEnvTextureAsync(texture, options = {}) { - var _a, _b; - const internalTexture = texture.getInternalTexture(); - if (!internalTexture) { - return Promise.reject("The cube texture is invalid."); - } - const imageType = (_a = options.imageType) !== null && _a !== void 0 ? _a : DefaultEnvironmentTextureImageType; - const engine = internalTexture.getEngine(); - if (texture.textureType !== 2 && - texture.textureType !== 1 && - texture.textureType !== 0 && - texture.textureType !== 0 && - texture.textureType !== 7 && - texture.textureType !== -1) { - return Promise.reject("The cube texture should allow HDR (Full Float or Half Float)."); - } - let textureType = 1; - if (!engine.getCaps().textureFloatRender) { - textureType = 2; - if (!engine.getCaps().textureHalfFloatRender) { - return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering."); - } - } - // sphericalPolynomial is lazy loaded so simply accessing it should trigger the computation. - texture.sphericalPolynomial; - // Lets keep track of the polynomial promise so we can wait for it to be ready before generating the pixels. - const sphericalPolynomialPromise = (_b = texture.getInternalTexture()) === null || _b === void 0 ? void 0 : _b._sphericalPolynomialPromise; - const cubeWidth = internalTexture.width; - const hostingScene = new scene_Scene(engine); - const specularTextures = {}; - // 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! - engine.flushFramebuffer(); - // Read and collect all mipmaps data from the cube. - const mipmapsCount = math_scalar_Scalar.ILog2(internalTexture.width); - for (let i = 0; i <= mipmapsCount; i++) { - const faceWidth = Math.pow(2, mipmapsCount - i); - // All faces of the cube. - for (let face = 0; face < 6; face++) { - let faceData = await texture.readPixels(face, i, undefined, false); - if (faceData && faceData.byteLength === faceData.length) { - const faceDataFloat = new Float32Array(faceData.byteLength * 4); - for (let i = 0; i < faceData.byteLength; i++) { - faceDataFloat[i] = faceData[i] / 255; - // Gamma to linear - faceDataFloat[i] = Math.pow(faceDataFloat[i], 2.2); - } - faceData = faceDataFloat; - } - else if (faceData && texture.gammaSpace) { - const floatData = faceData; - for (let i = 0; i < floatData.length; i++) { - // Gamma to linear - floatData[i] = Math.pow(floatData[i], 2.2); - } - } - const tempTexture = engine.createRawTexture(faceData, faceWidth, faceWidth, 5, false, true, 1, null, textureType); - await RGBDTextureTools.EncodeTextureToRGBD(tempTexture, hostingScene, textureType); - const rgbdEncodedData = await engine._readTexturePixels(tempTexture, faceWidth, faceWidth); - const imageEncodedData = await DumpTools.DumpDataAsync(faceWidth, faceWidth, rgbdEncodedData, imageType, undefined, false, true, options.imageQuality); - specularTextures[i * 6 + face] = imageEncodedData; - tempTexture.dispose(); - } - } - // We can delete the hosting scene keeping track of all the creation objects - hostingScene.dispose(); - // Ensure completion of the polynomial creation promise. - if (sphericalPolynomialPromise) { - await sphericalPolynomialPromise; - } - // Creates the json header for the env texture - const info = { - version: CurrentVersion, - width: cubeWidth, - imageType, - irradiance: _CreateEnvTextureIrradiance(texture), - specular: { - mipmaps: [], - lodGenerationScale: texture.lodGenerationScale, - }, - }; - // Sets the specular image data information - let position = 0; - for (let i = 0; i <= mipmapsCount; i++) { - for (let face = 0; face < 6; face++) { - const byteLength = specularTextures[i * 6 + face].byteLength; - info.specular.mipmaps.push({ - length: byteLength, - position: position, - }); - position += byteLength; - } - } - // Encode the JSON as an array buffer - const infoString = JSON.stringify(info); - const infoBuffer = new ArrayBuffer(infoString.length + 1); - const infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode. - for (let i = 0, strLen = infoString.length; i < strLen; i++) { - infoView[i] = infoString.charCodeAt(i); - } - // Ends up with a null terminator for easier parsing - infoView[infoString.length] = 0x00; - // Computes the final required size and creates the storage - const totalSize = MagicBytes.length + position + infoBuffer.byteLength; - const finalBuffer = new ArrayBuffer(totalSize); - const finalBufferView = new Uint8Array(finalBuffer); - const dataView = new DataView(finalBuffer); - // Copy the magic bytes identifying the file in - let pos = 0; - for (let i = 0; i < MagicBytes.length; i++) { - dataView.setUint8(pos++, MagicBytes[i]); - } - // Add the json info - finalBufferView.set(new Uint8Array(infoBuffer), pos); - pos += infoBuffer.byteLength; - // Finally inserts the texture data - for (let i = 0; i <= mipmapsCount; i++) { - for (let face = 0; face < 6; face++) { - const dataBuffer = specularTextures[i * 6 + face]; - finalBufferView.set(new Uint8Array(dataBuffer), pos); - pos += dataBuffer.byteLength; - } - } - // Voila - return finalBuffer; -} -/** - * Creates a JSON representation of the spherical data. - * @param texture defines the texture containing the polynomials - * @returns the JSON representation of the spherical info - */ -function _CreateEnvTextureIrradiance(texture) { - const polynmials = texture.sphericalPolynomial; - if (polynmials == null) { - return null; - } - return { - x: [polynmials.x.x, polynmials.x.y, polynmials.x.z], - y: [polynmials.y.x, polynmials.y.y, polynmials.y.z], - z: [polynmials.z.x, polynmials.z.y, polynmials.z.z], - xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z], - yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z], - zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z], - yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z], - zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z], - xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z], - }; -} -/** - * Creates the ArrayBufferViews used for initializing environment texture image data. - * @param data the image data - * @param info parameters that determine what views will be created for accessing the underlying buffer - * @returns the views described by info providing access to the underlying buffer - */ -function CreateImageDataArrayBufferViews(data, info) { - info = normalizeEnvInfo(info); - const specularInfo = info.specular; - // Double checks the enclosed info - let mipmapsCount = math_scalar_Scalar.Log2(info.width); - mipmapsCount = Math.round(mipmapsCount) + 1; - if (specularInfo.mipmaps.length !== 6 * mipmapsCount) { - throw new Error(`Unsupported specular mipmaps number "${specularInfo.mipmaps.length}"`); - } - const imageData = new Array(mipmapsCount); - for (let i = 0; i < mipmapsCount; i++) { - imageData[i] = new Array(6); - for (let face = 0; face < 6; face++) { - const imageInfo = specularInfo.mipmaps[i * 6 + face]; - imageData[i][face] = new Uint8Array(data.buffer, data.byteOffset + specularInfo.specularDataPosition + imageInfo.position, imageInfo.length); - } - } - return imageData; -} -/** - * Uploads the texture info contained in the env file to the GPU. - * @param texture defines the internal texture to upload to - * @param data defines the data to load - * @param info defines the texture info retrieved through the GetEnvInfo method - * @returns a promise - */ -function UploadEnvLevelsAsync(texture, data, info) { - info = normalizeEnvInfo(info); - const specularInfo = info.specular; - if (!specularInfo) { - // Nothing else parsed so far - return Promise.resolve(); - } - texture._lodGenerationScale = specularInfo.lodGenerationScale; - const imageData = CreateImageDataArrayBufferViews(data, info); - return UploadLevelsAsync(texture, imageData, info.imageType); -} -function _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture) { - return new Promise((resolve, reject) => { - if (expandTexture) { - const tempTexture = engine.createTexture(null, true, true, null, 1, null, (message) => { - reject(message); - }, image); - rgbdPostProcess.getEffect().executeWhenCompiled(() => { - // Uncompress the data to a RTT - rgbdPostProcess.externalTextureSamplerBinding = true; - rgbdPostProcess.onApply = (effect) => { - effect._bindTexture("textureSampler", tempTexture); - effect.setFloat2("scale", 1, engine._features.needsInvertingBitmap && image instanceof ImageBitmap ? -1 : 1); - }; - if (!engine.scenes.length) { - return; - } - engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i); - // Cleanup - engine.restoreDefaultFramebuffer(); - tempTexture.dispose(); - URL.revokeObjectURL(url); - resolve(); - }); - } - else { - engine._uploadImageToTexture(texture, image, face, i); - // Upload the face to the non lod texture support - if (generateNonLODTextures) { - const lodTexture = lodTextures[i]; - if (lodTexture) { - engine._uploadImageToTexture(lodTexture._texture, image, face, 0); - } - } - resolve(); - } - }); -} -/** - * Uploads the levels of image data to the GPU. - * @param texture defines the internal texture to upload to - * @param imageData defines the array buffer views of image data [mipmap][face] - * @param imageType the mime type of the image data - * @returns a promise - */ -function UploadLevelsAsync(texture, imageData, imageType = DefaultEnvironmentTextureImageType) { - if (!tools_Tools.IsExponentOfTwo(texture.width)) { - throw new Error("Texture size must be a power of two"); - } - const mipmapsCount = math_scalar_Scalar.ILog2(texture.width) + 1; - // Gets everything ready. - const engine = texture.getEngine(); - let expandTexture = false; - let generateNonLODTextures = false; - let rgbdPostProcess = null; - let cubeRtt = null; - let lodTextures = null; - const caps = engine.getCaps(); - texture.format = 5; - texture.type = 0; - texture.generateMipMaps = true; - texture._cachedAnisotropicFilteringLevel = null; - engine.updateTextureSamplingMode(3, texture); - // Add extra process if texture lod is not supported - if (!caps.textureLOD) { - expandTexture = false; - generateNonLODTextures = true; - lodTextures = {}; - } - // in webgl 1 there are no ways to either render or copy lod level information for float textures. - else if (!engine._features.supportRenderAndCopyToLodForFloatTextures) { - expandTexture = false; - } - // If half float available we can uncompress the texture - else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { - expandTexture = true; - texture.type = 2; - } - // If full float available we can uncompress the texture - else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { - expandTexture = true; - texture.type = 1; - } - // Expand the texture if possible - if (expandTexture) { - // Simply run through the decode PP - rgbdPostProcess = new postProcess_PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, 3, engine, false, undefined, texture.type, undefined, null, false); - texture._isRGBD = false; - texture.invertY = false; - cubeRtt = engine.createRenderTargetCubeTexture(texture.width, { - generateDepthBuffer: false, - generateMipMaps: true, - generateStencilBuffer: false, - samplingMode: 3, - type: texture.type, - format: 5, - }); - } - else { - texture._isRGBD = true; - texture.invertY = true; - // In case of missing support, applies the same patch than DDS files. - if (generateNonLODTextures) { - const mipSlices = 3; - const scale = texture._lodGenerationScale; - const offset = texture._lodGenerationOffset; - for (let i = 0; i < mipSlices; i++) { - //compute LOD from even spacing in smoothness (matching shader calculation) - const smoothness = i / (mipSlices - 1); - const roughness = 1 - smoothness; - const minLODIndex = offset; // roughness = 0 - const maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0) - const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness; - const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex)); - const glTextureFromLod = new internalTexture_InternalTexture(engine, internalTexture_InternalTextureSource.Temp); - glTextureFromLod.isCube = true; - glTextureFromLod.invertY = true; - glTextureFromLod.generateMipMaps = false; - engine.updateTextureSamplingMode(2, glTextureFromLod); - // Wrap in a base texture for easy binding. - const lodTexture = new baseTexture_BaseTexture(null); - lodTexture._isCube = true; - lodTexture._texture = glTextureFromLod; - lodTextures[mipmapIndex] = lodTexture; - switch (i) { - case 0: - texture._lodTextureLow = lodTexture; - break; - case 1: - texture._lodTextureMid = lodTexture; - break; - case 2: - texture._lodTextureHigh = lodTexture; - break; - } - } - } - } - const promises = []; - // All mipmaps up to provided number of images - for (let i = 0; i < imageData.length; i++) { - // All faces - for (let face = 0; face < 6; face++) { - // Constructs an image element from image data - const bytes = imageData[i][face]; - const blob = new Blob([bytes], { type: imageType }); - const url = URL.createObjectURL(blob); - let promise; - if (typeof Image === "undefined" || engine._features.forceBitmapOverHTMLImageElement) { - promise = engine.createImageBitmap(blob, { premultiplyAlpha: "none" }).then((img) => { - return _OnImageReadyAsync(img, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture); - }); - } - else { - const image = new Image(); - image.src = url; - // Enqueue promise to upload to the texture. - promise = new Promise((resolve, reject) => { - image.onload = () => { - _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture) - .then(() => resolve()) - .catch((reason) => { - reject(reason); - }); - }; - image.onerror = (error) => { - reject(error); - }; - }); - } - promises.push(promise); - } - } - // Fill remaining mipmaps with black textures. - if (imageData.length < mipmapsCount) { - let data; - const size = Math.pow(2, mipmapsCount - 1 - imageData.length); - const dataLength = size * size * 4; - switch (texture.type) { - case 0: { - data = new Uint8Array(dataLength); - break; - } - case 2: { - data = new Uint16Array(dataLength); - break; - } - case 1: { - data = new Float32Array(dataLength); - break; - } - } - for (let i = imageData.length; i < mipmapsCount; i++) { - for (let face = 0; face < 6; face++) { - engine._uploadArrayBufferViewToTexture(texture, data, face, i); - } - } - } - // Once all done, finishes the cleanup and return - return Promise.all(promises).then(() => { - // Release temp RTT. - if (cubeRtt) { - engine._releaseTexture(texture); - cubeRtt._swapAndDie(texture); - } - // Release temp Post Process. - if (rgbdPostProcess) { - rgbdPostProcess.dispose(); - } - // Flag internal texture as ready in case they are in use. - if (generateNonLODTextures) { - if (texture._lodTextureHigh && texture._lodTextureHigh._texture) { - texture._lodTextureHigh._texture.isReady = true; - } - if (texture._lodTextureMid && texture._lodTextureMid._texture) { - texture._lodTextureMid._texture.isReady = true; - } - if (texture._lodTextureLow && texture._lodTextureLow._texture) { - texture._lodTextureLow._texture.isReady = true; - } - } - }); -} -/** - * Uploads spherical polynomials information to the texture. - * @param texture defines the texture we are trying to upload the information to - * @param info defines the environment texture info retrieved through the GetEnvInfo method - */ -function UploadEnvSpherical(texture, info) { - info = normalizeEnvInfo(info); - const irradianceInfo = info.irradiance; - if (!irradianceInfo) { - return; - } - const sp = new SphericalPolynomial(); - math_vector_Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x); - math_vector_Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y); - math_vector_Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z); - math_vector_Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx); - math_vector_Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy); - math_vector_Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz); - math_vector_Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz); - math_vector_Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx); - math_vector_Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy); - texture._sphericalPolynomial = sp; -} -/** - * @internal - */ -function _UpdateRGBDAsync(internalTexture, data, sphericalPolynomial, lodScale, lodOffset) { - const proxy = internalTexture - .getEngine() - .createRawCubeTexture(null, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression); - const proxyPromise = UploadLevelsAsync(proxy, data).then(() => internalTexture); - internalTexture.onRebuildCallback = (_internalTexture) => { - return { - proxy: proxyPromise, - isReady: true, - isAsync: true, - }; - }; - internalTexture._source = InternalTextureSource.CubeRawRGBD; - internalTexture._bufferViewArrayArray = data; - internalTexture._lodGenerationScale = lodScale; - internalTexture._lodGenerationOffset = lodOffset; - internalTexture._sphericalPolynomial = sphericalPolynomial; - return UploadLevelsAsync(internalTexture, data).then(() => { - internalTexture.isReady = true; - return internalTexture; - }); -} -/** - * Sets of helpers addressing the serialization and deserialization of environment texture - * stored in a BabylonJS env file. - * Those files are usually stored as .env files. - */ -const EnvironmentTextureTools = { - /** - * Gets the environment info from an env file. - * @param data The array buffer containing the .env bytes. - * @returns the environment file info (the json header) if successfully parsed, normalized to the latest supported version. - */ - GetEnvInfo, - /** - * Creates an environment texture from a loaded cube texture. - * @param texture defines the cube texture to convert in env file - * @param options options for the conversion process - * @param options.imageType the mime type for the encoded images, with support for "image/png" (default) and "image/webp" - * @param options.imageQuality the image quality of encoded WebP images. - * @returns a promise containing the environment data if successful. - */ - CreateEnvTextureAsync, - /** - * Creates the ArrayBufferViews used for initializing environment texture image data. - * @param data the image data - * @param info parameters that determine what views will be created for accessing the underlying buffer - * @returns the views described by info providing access to the underlying buffer - */ - CreateImageDataArrayBufferViews, - /** - * Uploads the texture info contained in the env file to the GPU. - * @param texture defines the internal texture to upload to - * @param data defines the data to load - * @param info defines the texture info retrieved through the GetEnvInfo method - * @returns a promise - */ - UploadEnvLevelsAsync, - /** - * Uploads the levels of image data to the GPU. - * @param texture defines the internal texture to upload to - * @param imageData defines the array buffer views of image data [mipmap][face] - * @param imageType the mime type of the image data - * @returns a promise - */ - UploadLevelsAsync, - /** - * Uploads spherical polynomials information to the texture. - * @param texture defines the texture we are trying to upload the information to - * @param info defines the environment texture info retrieved through the GetEnvInfo method - */ - UploadEnvSpherical, -}; -//# sourceMappingURL=environmentTextureTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/codeStringParsingTools.js -/** - * 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 - * @param markerOpen opening marker - * @param markerClose closing marker - * @param block code block to parse - * @param startIndex starting index in block where the extraction must start. The character at block[startIndex] should be the markerOpen character! - * @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) - */ -function ExtractBetweenMarkers(markerOpen, markerClose, block, startIndex) { - let currPos = startIndex, openMarkers = 0, waitForChar = ""; - while (currPos < block.length) { - const currChar = block.charAt(currPos); - if (!waitForChar) { - switch (currChar) { - case markerOpen: - openMarkers++; - break; - case markerClose: - openMarkers--; - break; - case '"': - case "'": - case "`": - waitForChar = currChar; - break; - case "/": - if (currPos + 1 < block.length) { - const nextChar = block.charAt(currPos + 1); - if (nextChar === "/") { - waitForChar = "\n"; - } - else if (nextChar === "*") { - waitForChar = "*/"; - } - } - break; - } - } - else { - if (currChar === waitForChar) { - if (waitForChar === '"' || waitForChar === "'") { - block.charAt(currPos - 1) !== "\\" && (waitForChar = ""); - } - else { - waitForChar = ""; - } - } - else if (waitForChar === "*/" && currChar === "*" && currPos + 1 < block.length) { - block.charAt(currPos + 1) === "/" && (waitForChar = ""); - if (waitForChar === "") { - currPos++; - } - } - } - currPos++; - if (openMarkers === 0) { - break; - } - } - return openMarkers === 0 ? currPos - 1 : -1; -} -/** - * Parses a string and skip whitespaces - * @param s string to parse - * @param index index where to start parsing - * @returns the index after all whitespaces have been skipped - */ -function SkipWhitespaces(s, index) { - while (index < s.length) { - const c = s[index]; - if (c !== " " && c !== "\n" && c !== "\r" && c !== "\t" && c !== "\u000a" && c !== "\u00a0") { - break; - } - index++; - } - return index; -} -/** - * Checks if a character is an identifier character (meaning, if it is 0-9, A-Z, a-z or _) - * @param c character to check - * @returns true if the character is an identifier character - */ -function IsIdentifierChar(c) { - const v = c.charCodeAt(0); - return ((v >= 48 && v <= 57) || // 0-9 - (v >= 65 && v <= 90) || // A-Z - (v >= 97 && v <= 122) || // a-z - v == 95); // _ -} -/** - * Removes the comments of a code block - * @param block code block to parse - * @returns block with the comments removed - */ -function RemoveComments(block) { - let currPos = 0, waitForChar = "", inComments = false; - const s = []; - while (currPos < block.length) { - const currChar = block.charAt(currPos); - if (!waitForChar) { - switch (currChar) { - case '"': - case "'": - case "`": - waitForChar = currChar; - break; - case "/": - if (currPos + 1 < block.length) { - const nextChar = block.charAt(currPos + 1); - if (nextChar === "/") { - waitForChar = "\n"; - inComments = true; - } - else if (nextChar === "*") { - waitForChar = "*/"; - inComments = true; - } - } - break; - } - if (!inComments) { - s.push(currChar); - } - } - else { - if (currChar === waitForChar) { - if (waitForChar === '"' || waitForChar === "'") { - block.charAt(currPos - 1) !== "\\" && (waitForChar = ""); - s.push(currChar); - } - else { - waitForChar = ""; - inComments = false; - } - } - else if (waitForChar === "*/" && currChar === "*" && currPos + 1 < block.length) { - block.charAt(currPos + 1) === "/" && (waitForChar = ""); - if (waitForChar === "") { - inComments = false; - currPos++; - } - } - else { - if (!inComments) { - s.push(currChar); - } - } - } - currPos++; - } - return s.join(""); -} -/** - * Finds the first occurrence of a character in a string going backward - * @param s the string to parse - * @param index starting index in the string - * @param c the character to find - * @returns the index of the character if found, else -1 - */ -function FindBackward(s, index, c) { - while (index >= 0 && s.charAt(index) !== c) { - index--; - } - return index; -} -/** - * Escapes a string so that it is usable as a regular expression - * @param s string to escape - * @returns escaped string - */ -function EscapeRegExp(s) { - return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -//# sourceMappingURL=codeStringParsingTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/shaderCodeInliner.js - -/** - * Class used to inline functions in shader code - */ -class ShaderCodeInliner { - /** Gets the code after the inlining process */ - get code() { - return this._sourceCode; - } - /** - * Initializes the inliner - * @param sourceCode shader code source to inline - * @param numMaxIterations maximum number of iterations (used to detect recursive calls) - */ - constructor(sourceCode, numMaxIterations = 20) { - /** Gets or sets the debug mode */ - this.debug = false; - this._sourceCode = sourceCode; - this._numMaxIterations = numMaxIterations; - this._functionDescr = []; - this.inlineToken = "#define inline"; - } - /** - * Start the processing of the shader code - */ - processCode() { - if (this.debug) { - console.log(`Start inlining process (code size=${this._sourceCode.length})...`); - } - this._collectFunctions(); - this._processInlining(this._numMaxIterations); - if (this.debug) { - console.log("End of inlining process."); - } - } - _collectFunctions() { - let startIndex = 0; - while (startIndex < this._sourceCode.length) { - // locate the function to inline and extract its name - const inlineTokenIndex = this._sourceCode.indexOf(this.inlineToken, startIndex); - if (inlineTokenIndex < 0) { - break; - } - const funcParamsStartIndex = this._sourceCode.indexOf("(", inlineTokenIndex + this.inlineToken.length); - if (funcParamsStartIndex < 0) { - if (this.debug) { - console.warn(`Could not find the opening parenthesis after the token. startIndex=${startIndex}`); - } - startIndex = inlineTokenIndex + this.inlineToken.length; - continue; - } - const funcNameMatch = ShaderCodeInliner._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex)); - if (!funcNameMatch) { - if (this.debug) { - console.warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex)}`); - } - startIndex = inlineTokenIndex + this.inlineToken.length; - continue; - } - const [funcType, funcName] = [funcNameMatch[3], funcNameMatch[4]]; - // extract the parameters of the function as a whole string (without the leading / trailing parenthesis) - const funcParamsEndIndex = ExtractBetweenMarkers("(", ")", this._sourceCode, funcParamsStartIndex); - if (funcParamsEndIndex < 0) { - if (this.debug) { - console.warn(`Could not extract the parameters the function '${funcName}' (type=${funcType}). funcParamsStartIndex=${funcParamsStartIndex}`); - } - startIndex = inlineTokenIndex + this.inlineToken.length; - continue; - } - const funcParams = this._sourceCode.substring(funcParamsStartIndex + 1, funcParamsEndIndex); - // extract the body of the function (with the curly brackets) - const funcBodyStartIndex = SkipWhitespaces(this._sourceCode, funcParamsEndIndex + 1); - if (funcBodyStartIndex === this._sourceCode.length) { - if (this.debug) { - console.warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcParamsEndIndex=${funcParamsEndIndex}`); - } - startIndex = inlineTokenIndex + this.inlineToken.length; - continue; - } - const funcBodyEndIndex = ExtractBetweenMarkers("{", "}", this._sourceCode, funcBodyStartIndex); - if (funcBodyEndIndex < 0) { - if (this.debug) { - console.warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcBodyStartIndex=${funcBodyStartIndex}`); - } - startIndex = inlineTokenIndex + this.inlineToken.length; - continue; - } - const funcBody = this._sourceCode.substring(funcBodyStartIndex, funcBodyEndIndex + 1); - // process the parameters: extract each names - const params = RemoveComments(funcParams).split(","); - const paramNames = []; - for (let p = 0; p < params.length; ++p) { - const param = params[p].trim(); - const idx = param.lastIndexOf(" "); - if (idx >= 0) { - paramNames.push(param.substring(idx + 1)); - } - } - if (funcType !== "void") { - // for functions that return a value, we will replace "return" by "tempvarname = ", tempvarname being a unique generated name - paramNames.push("return"); - } - // collect the function - this._functionDescr.push({ - name: funcName, - type: funcType, - parameters: paramNames, - body: funcBody, - callIndex: 0, - }); - startIndex = funcBodyEndIndex + 1; - // remove the function from the source code - const partBefore = inlineTokenIndex > 0 ? this._sourceCode.substring(0, inlineTokenIndex) : ""; - const partAfter = funcBodyEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(funcBodyEndIndex + 1) : ""; - this._sourceCode = partBefore + partAfter; - startIndex -= funcBodyEndIndex + 1 - inlineTokenIndex; - } - if (this.debug) { - console.log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=`, this._functionDescr); - } - } - _processInlining(numMaxIterations = 20) { - while (numMaxIterations-- >= 0) { - if (!this._replaceFunctionCallsByCode()) { - break; - } - } - if (this.debug) { - console.log(`numMaxIterations is ${numMaxIterations} after inlining process`); - } - return numMaxIterations >= 0; - } - _replaceFunctionCallsByCode() { - let doAgain = false; - for (const func of this._functionDescr) { - const { name, type, parameters, body } = func; - let startIndex = 0; - while (startIndex < this._sourceCode.length) { - // Look for the function name in the source code - const functionCallIndex = this._sourceCode.indexOf(name, startIndex); - if (functionCallIndex < 0) { - break; - } - // Make sure "name" is not part of a bigger string - if (functionCallIndex === 0 || IsIdentifierChar(this._sourceCode.charAt(functionCallIndex - 1))) { - startIndex = functionCallIndex + name.length; - continue; - } - // Find the opening parenthesis - const callParamsStartIndex = SkipWhitespaces(this._sourceCode, functionCallIndex + name.length); - if (callParamsStartIndex === this._sourceCode.length || this._sourceCode.charAt(callParamsStartIndex) !== "(") { - startIndex = functionCallIndex + name.length; - continue; - } - // extract the parameters of the function call as a whole string (without the leading / trailing parenthesis) - const callParamsEndIndex = ExtractBetweenMarkers("(", ")", this._sourceCode, callParamsStartIndex); - if (callParamsEndIndex < 0) { - if (this.debug) { - console.warn(`Could not extract the parameters of the function call. Function '${name}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}`); - } - startIndex = functionCallIndex + name.length; - continue; - } - const callParams = this._sourceCode.substring(callParamsStartIndex + 1, callParamsEndIndex); - // process the parameter call: extract each names - // this function split the parameter list used in the function call at ',' boundaries by taking care of potential parenthesis like in: - // myfunc(a, vec2(1., 0.), 4.) - const splitParameterCall = (s) => { - const parameters = []; - let curIdx = 0, startParamIdx = 0; - while (curIdx < s.length) { - if (s.charAt(curIdx) === "(") { - const idx2 = ExtractBetweenMarkers("(", ")", s, curIdx); - if (idx2 < 0) { - return null; - } - curIdx = idx2; - } - else if (s.charAt(curIdx) === ",") { - parameters.push(s.substring(startParamIdx, curIdx)); - startParamIdx = curIdx + 1; - } - curIdx++; - } - if (startParamIdx < curIdx) { - parameters.push(s.substring(startParamIdx, curIdx)); - } - return parameters; - }; - const params = splitParameterCall(RemoveComments(callParams)); - if (params === null) { - if (this.debug) { - console.warn(`Invalid function call: can't extract the parameters of the function call. Function '${name}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}, callParams=` + - callParams); - } - startIndex = functionCallIndex + name.length; - continue; - } - const paramNames = []; - for (let p = 0; p < params.length; ++p) { - const param = params[p].trim(); - paramNames.push(param); - } - const retParamName = type !== "void" ? name + "_" + func.callIndex++ : null; - if (retParamName) { - paramNames.push(retParamName + " ="); - } - if (paramNames.length !== parameters.length) { - if (this.debug) { - 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}`); - } - startIndex = functionCallIndex + name.length; - continue; - } - startIndex = callParamsEndIndex + 1; - // replace the function call by the body function - const funcBody = this._replaceNames(body, parameters, paramNames); - let partBefore = functionCallIndex > 0 ? this._sourceCode.substring(0, functionCallIndex) : ""; - const partAfter = callParamsEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(callParamsEndIndex + 1) : ""; - if (retParamName) { - // case where the function returns a value. We generate: - // FUNCTYPE retParamName; - // {function body} - // and replace the function call by retParamName - const injectDeclarationIndex = FindBackward(this._sourceCode, functionCallIndex - 1, "\n"); - partBefore = this._sourceCode.substring(0, injectDeclarationIndex + 1); - const partBetween = this._sourceCode.substring(injectDeclarationIndex + 1, functionCallIndex); - this._sourceCode = partBefore + type + " " + retParamName + ";\n" + funcBody + "\n" + partBetween + retParamName + partAfter; - if (this.debug) { - console.log(`Replace function call by code. Function '${name}' (type=${type}). injectDeclarationIndex=${injectDeclarationIndex}, call parameters=${paramNames}`); - } - } - else { - // simple case where the return value of the function is "void" - this._sourceCode = partBefore + funcBody + partAfter; - startIndex += funcBody.length - (callParamsEndIndex + 1 - functionCallIndex); - if (this.debug) { - console.log(`Replace function call by code. Function '${name}' (type=${type}). functionCallIndex=${functionCallIndex}, call parameters=${paramNames}`); - } - } - doAgain = true; - } - } - return doAgain; - } - _replaceNames(code, sources, destinations) { - for (let i = 0; i < sources.length; ++i) { - const source = new RegExp(EscapeRegExp(sources[i]), "g"), sourceLen = sources[i].length, destination = destinations[i]; - code = code.replace(source, (match, ...args) => { - const offset = args[0]; - // Make sure "source" is not part of a bigger identifier (for eg, if source=view and we matched it with viewDirection) - if (IsIdentifierChar(code.charAt(offset - 1)) || IsIdentifierChar(code.charAt(offset + sourceLen))) { - return sources[i]; - } - return destination; - }); - } - return code; - } -} -ShaderCodeInliner._RegexpFindFunctionNameAndType = /((\s+?)(\w+)\s+(\w+)\s*?)$/; -//# sourceMappingURL=shaderCodeInliner.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Native/nativePipelineContext.js -class NativePipelineContext { - get isAsync() { - return this.isParallelCompiled; - } - get isReady() { - if (this.compilationError) { - const message = this.compilationError.message; - throw new Error("SHADER ERROR" + (typeof message === "string" ? "\n" + message : "")); - } - return this.isCompiled; - } - _getVertexShaderCode() { - return null; - } - _getFragmentShaderCode() { - return null; - } - // TODO: what should this do? - _handlesSpectorRebuildCallback(onCompiled) { - throw new Error("Not implemented"); - } - constructor(engine) { - this.isParallelCompiled = true; - this.isCompiled = false; - this._valueCache = {}; - this._engine = engine; - } - _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) { - const engine = this._engine; - if (engine.supportsUniformBuffers) { - for (const name in uniformBuffersNames) { - effect.bindUniformBlock(name, uniformBuffersNames[name]); - } - } - const effectAvailableUniforms = this._engine.getUniforms(this, uniformsNames); - effectAvailableUniforms.forEach((uniform, index) => { - uniforms[uniformsNames[index]] = uniform; - }); - this._uniforms = uniforms; - let index; - for (index = 0; index < samplerList.length; index++) { - const sampler = effect.getUniform(samplerList[index]); - if (sampler == null) { - samplerList.splice(index, 1); - index--; - } - } - samplerList.forEach((name, index) => { - samplers[name] = index; - }); - attributes.push(...engine.getAttributes(this, attributesNames)); - } - /** - * Release all associated resources. - **/ - dispose() { - this._uniforms = {}; - } - /** - * @internal - */ - _cacheMatrix(uniformName, matrix) { - const cache = this._valueCache[uniformName]; - const flag = matrix.updateFlag; - if (cache !== undefined && cache === flag) { - return false; - } - this._valueCache[uniformName] = flag; - return true; - } - /** - * @internal - */ - _cacheFloat2(uniformName, x, y) { - let cache = this._valueCache[uniformName]; - if (!cache) { - cache = [x, y]; - this._valueCache[uniformName] = cache; - return true; - } - let changed = false; - if (cache[0] !== x) { - cache[0] = x; - changed = true; - } - if (cache[1] !== y) { - cache[1] = y; - changed = true; - } - return changed; - } - /** - * @internal - */ - _cacheFloat3(uniformName, x, y, z) { - let cache = this._valueCache[uniformName]; - if (!cache) { - cache = [x, y, z]; - this._valueCache[uniformName] = cache; - return true; - } - let changed = false; - if (cache[0] !== x) { - cache[0] = x; - changed = true; - } - if (cache[1] !== y) { - cache[1] = y; - changed = true; - } - if (cache[2] !== z) { - cache[2] = z; - changed = true; - } - return changed; - } - /** - * @internal - */ - _cacheFloat4(uniformName, x, y, z, w) { - let cache = this._valueCache[uniformName]; - if (!cache) { - cache = [x, y, z, w]; - this._valueCache[uniformName] = cache; - return true; - } - let changed = false; - if (cache[0] !== x) { - cache[0] = x; - changed = true; - } - if (cache[1] !== y) { - cache[1] = y; - changed = true; - } - if (cache[2] !== z) { - cache[2] = z; - changed = true; - } - if (cache[3] !== w) { - cache[3] = w; - changed = true; - } - return changed; - } - /** - * Sets an integer value on a uniform variable. - * @param uniformName Name of the variable. - * @param value Value to be set. - */ - setInt(uniformName, value) { - const cache = this._valueCache[uniformName]; - if (cache !== undefined && cache === value) { - return; - } - if (this._engine.setInt(this._uniforms[uniformName], value)) { - this._valueCache[uniformName] = value; - } - } - /** - * Sets a int2 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int2. - * @param y Second int in int2. - */ - setInt2(uniformName, x, y) { - if (this._cacheFloat2(uniformName, x, y)) { - if (!this._engine.setInt2(this._uniforms[uniformName], x, y)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a int3 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int3. - * @param y Second int in int3. - * @param z Third int in int3. - */ - setInt3(uniformName, x, y, z) { - if (this._cacheFloat3(uniformName, x, y, z)) { - if (!this._engine.setInt3(this._uniforms[uniformName], x, y, z)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a int4 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int4. - * @param y Second int in int4. - * @param z Third int in int4. - * @param w Fourth int in int4. - */ - setInt4(uniformName, x, y, z, w) { - if (this._cacheFloat4(uniformName, x, y, z, w)) { - if (!this._engine.setInt4(this._uniforms[uniformName], x, y, z, w)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets an int array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setIntArray(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray2(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setIntArray2(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray3(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setIntArray3(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray4(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setIntArray4(this._uniforms[uniformName], array); - } - /** - * Sets an unsigned integer value on a uniform variable. - * @param uniformName Name of the variable. - * @param value Value to be set. - */ - setUInt(uniformName, value) { - const cache = this._valueCache[uniformName]; - if (cache !== undefined && cache === value) { - return; - } - if (this._engine.setUInt(this._uniforms[uniformName], value)) { - this._valueCache[uniformName] = value; - } - } - /** - * Sets a unsigned int2 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint2. - * @param y Second unsigned int in uint2. - */ - setUInt2(uniformName, x, y) { - if (this._cacheFloat2(uniformName, x, y)) { - if (!this._engine.setUInt2(this._uniforms[uniformName], x, y)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a unsigned int3 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint3. - * @param y Second unsigned int in uint3. - * @param z Third unsigned int in uint3. - */ - setUInt3(uniformName, x, y, z) { - if (this._cacheFloat3(uniformName, x, y, z)) { - if (!this._engine.setUInt3(this._uniforms[uniformName], x, y, z)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a unsigned int4 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint4. - * @param y Second unsigned int in uint4. - * @param z Third unsigned int in uint4. - * @param w Fourth unsigned int in uint4. - */ - setUInt4(uniformName, x, y, z, w) { - if (this._cacheFloat4(uniformName, x, y, z, w)) { - if (!this._engine.setUInt4(this._uniforms[uniformName], x, y, z, w)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets an unsigned int array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setUIntArray(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray2(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setUIntArray2(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray3(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setUIntArray3(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray4(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setUIntArray4(this._uniforms[uniformName], array); - } - /** - * Sets an float array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setFloatArray(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setFloatArray(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setFloatArray2(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setFloatArray2(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setFloatArray3(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setFloatArray3(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setFloatArray4(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setFloatArray4(this._uniforms[uniformName], array); - } - /** - * Sets an array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setArray(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setArray(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setArray2(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setArray2(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setArray3(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setArray3(this._uniforms[uniformName], array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setArray4(uniformName, array) { - this._valueCache[uniformName] = null; - this._engine.setArray4(this._uniforms[uniformName], array); - } - /** - * Sets matrices on a uniform variable. - * @param uniformName Name of the variable. - * @param matrices matrices to be set. - */ - setMatrices(uniformName, matrices) { - if (!matrices) { - return; - } - this._valueCache[uniformName] = null; - this._engine.setMatrices(this._uniforms[uniformName], matrices); - } - /** - * Sets matrix on a uniform variable. - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - */ - setMatrix(uniformName, matrix) { - if (this._cacheMatrix(uniformName, matrix)) { - if (!this._engine.setMatrices(this._uniforms[uniformName], matrix.toArray())) { - this._valueCache[uniformName] = null; - } - } - } - /** - * 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) - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - */ - setMatrix3x3(uniformName, matrix) { - this._valueCache[uniformName] = null; - this._engine.setMatrix3x3(this._uniforms[uniformName], matrix); - } - /** - * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix) - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - */ - setMatrix2x2(uniformName, matrix) { - this._valueCache[uniformName] = null; - this._engine.setMatrix2x2(this._uniforms[uniformName], matrix); - } - /** - * Sets a float on a uniform variable. - * @param uniformName Name of the variable. - * @param value value to be set. - * @returns this effect. - */ - setFloat(uniformName, value) { - const cache = this._valueCache[uniformName]; - if (cache !== undefined && cache === value) { - return; - } - if (this._engine.setFloat(this._uniforms[uniformName], value)) { - this._valueCache[uniformName] = value; - } - } - /** - * Sets a boolean on a uniform variable. - * @param uniformName Name of the variable. - * @param bool value to be set. - */ - setBool(uniformName, bool) { - const cache = this._valueCache[uniformName]; - if (cache !== undefined && cache === bool) { - return; - } - if (this._engine.setInt(this._uniforms[uniformName], bool ? 1 : 0)) { - this._valueCache[uniformName] = bool ? 1 : 0; - } - } - /** - * Sets a Vector2 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector2 vector2 to be set. - */ - setVector2(uniformName, vector2) { - if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) { - if (!this._engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a float2 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float2. - * @param y Second float in float2. - */ - setFloat2(uniformName, x, y) { - if (this._cacheFloat2(uniformName, x, y)) { - if (!this._engine.setFloat2(this._uniforms[uniformName], x, y)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Vector3 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector3 Value to be set. - */ - setVector3(uniformName, vector3) { - if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) { - if (!this._engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a float3 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float3. - * @param y Second float in float3. - * @param z Third float in float3. - */ - setFloat3(uniformName, x, y, z) { - if (this._cacheFloat3(uniformName, x, y, z)) { - if (!this._engine.setFloat3(this._uniforms[uniformName], x, y, z)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Vector4 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector4 Value to be set. - */ - setVector4(uniformName, vector4) { - if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) { - if (!this._engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Quaternion on a uniform variable. - * @param uniformName Name of the variable. - * @param quaternion Value to be set. - */ - setQuaternion(uniformName, quaternion) { - if (this._cacheFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w)) { - if (!this._engine.setFloat4(this._uniforms[uniformName], quaternion.x, quaternion.y, quaternion.z, quaternion.w)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a float4 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float4. - * @param y Second float in float4. - * @param z Third float in float4. - * @param w Fourth float in float4. - * @returns this effect. - */ - setFloat4(uniformName, x, y, z, w) { - if (this._cacheFloat4(uniformName, x, y, z, w)) { - if (!this._engine.setFloat4(this._uniforms[uniformName], x, y, z, w)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Color3 on a uniform variable. - * @param uniformName Name of the variable. - * @param color3 Value to be set. - */ - setColor3(uniformName, color3) { - if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) { - if (!this._engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Color4 on a uniform variable. - * @param uniformName Name of the variable. - * @param color3 Value to be set. - * @param alpha Alpha value to be set. - */ - setColor4(uniformName, color3, alpha) { - if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) { - if (!this._engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha)) { - this._valueCache[uniformName] = null; - } - } - } - /** - * Sets a Color4 on a uniform variable - * @param uniformName defines the name of the variable - * @param color4 defines the value to be set - */ - setDirectColor4(uniformName, color4) { - if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) { - if (!this._engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a)) { - this._valueCache[uniformName] = null; - } - } - } -} -//# sourceMappingURL=nativePipelineContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Native/nativeRenderTargetWrapper.js - -class NativeRenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper { - get _framebuffer() { - return this.__framebuffer; - } - set _framebuffer(framebuffer) { - if (this.__framebuffer) { - this._engine._releaseFramebufferObjects(this.__framebuffer); - } - this.__framebuffer = framebuffer; - } - get _framebufferDepthStencil() { - return this.__framebufferDepthStencil; - } - set _framebufferDepthStencil(framebufferDepthStencil) { - if (this.__framebufferDepthStencil) { - this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil); - } - this.__framebufferDepthStencil = framebufferDepthStencil; - } - constructor(isMulti, isCube, size, engine) { - super(isMulti, isCube, size, engine); - this.__framebuffer = null; - this.__framebufferDepthStencil = null; - this._engine = engine; - } - dispose(disposeOnlyFramebuffers = false) { - this._framebuffer = null; - this._framebufferDepthStencil = null; - super.dispose(disposeOnlyFramebuffers); - } -} -//# sourceMappingURL=nativeRenderTargetWrapper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Native/nativeHardwareTexture.js -/** @internal */ -class NativeHardwareTexture { - get underlyingResource() { - return this._nativeTexture; - } - constructor(existingTexture, engine) { - this._engine = engine; - this.set(existingTexture); - } - setUsage() { } - set(hardwareTexture) { - this._nativeTexture = hardwareTexture; - } - reset() { - this._nativeTexture = null; - } - release() { - if (this._nativeTexture) { - this._engine.deleteTexture(this._nativeTexture); - } - this.reset(); - } -} -//# sourceMappingURL=nativeHardwareTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/nativeEngine.js - - - - - - - - - - - - - - - - - - - -const onNativeObjectInitialized = new observable_Observable(); -if (typeof self !== "undefined" && !Object.prototype.hasOwnProperty.call(self, "_native")) { - let __native; - Object.defineProperty(self, "_native", { - get: () => __native, - set: (value) => { - __native = value; - if (__native) { - onNativeObjectInitialized.notifyObservers(__native); - } - }, - }); -} -/** - * Returns _native only after it has been defined by BabylonNative. - * @internal - */ -function AcquireNativeObjectAsync() { - return new Promise((resolve) => { - if (typeof _native === "undefined") { - onNativeObjectInitialized.addOnce((nativeObject) => resolve(nativeObject)); - } - else { - resolve(_native); - } - }); -} -/** - * Registers a constructor on the _native object. See NativeXRFrame for an example. - * @internal - */ -async function RegisterNativeTypeAsync(typeName, constructor) { - (await AcquireNativeObjectAsync())[typeName] = constructor; -} -/** - * Container for accessors for natively-stored mesh data buffers. - */ -class NativeDataBuffer extends dataBuffer_DataBuffer { -} -/** @internal */ -class CommandBufferEncoder { - constructor(_engine) { - this._engine = _engine; - this._pending = new Array(); - this._isCommandBufferScopeActive = false; - this._commandStream = NativeEngine._createNativeDataStream(); - this._engine.setCommandDataStream(this._commandStream); - } - beginCommandScope() { - if (this._isCommandBufferScopeActive) { - throw new Error("Command scope already active."); - } - this._isCommandBufferScopeActive = true; - } - endCommandScope() { - if (!this._isCommandBufferScopeActive) { - throw new Error("Command scope is not active."); - } - this._isCommandBufferScopeActive = false; - this._submit(); - } - startEncodingCommand(command) { - this._commandStream.writeNativeData(command); - } - encodeCommandArgAsUInt32(commandArg) { - this._commandStream.writeUint32(commandArg); - } - encodeCommandArgAsUInt32s(commandArg) { - this._commandStream.writeUint32Array(commandArg); - } - encodeCommandArgAsInt32(commandArg) { - this._commandStream.writeInt32(commandArg); - } - encodeCommandArgAsInt32s(commandArg) { - this._commandStream.writeInt32Array(commandArg); - } - encodeCommandArgAsFloat32(commandArg) { - this._commandStream.writeFloat32(commandArg); - } - encodeCommandArgAsFloat32s(commandArg) { - this._commandStream.writeFloat32Array(commandArg); - } - encodeCommandArgAsNativeData(commandArg) { - this._commandStream.writeNativeData(commandArg); - this._pending.push(commandArg); - } - finishEncodingCommand() { - if (!this._isCommandBufferScopeActive) { - this._submit(); - } - } - _submit() { - this._engine.submitCommands(); - this._pending.length = 0; - } -} -/** @internal */ -class NativeEngine extends engine_Engine { - setHardwareScalingLevel(level) { - super.setHardwareScalingLevel(level); - this._engine.setHardwareScalingLevel(level); - } - constructor(options = {}) { - super(null, false, undefined, options.adaptToDeviceRatio); - this._engine = new _native.Engine(); - this._camera = _native.Camera ? new _native.Camera() : null; - this._commandBufferEncoder = new CommandBufferEncoder(this._engine); - this._boundBuffersVertexArray = null; - this._currentDepthTest = _native.Engine.DEPTH_TEST_LEQUAL; - this._stencilTest = false; - 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 = true; - if (_native.Engine.PROTOCOL_VERSION !== NativeEngine.PROTOCOL_VERSION) { - throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${NativeEngine.PROTOCOL_VERSION} (JS)`); - } - this._webGLVersion = 2; - this.disableUniformBuffers = true; - this._shaderPlatformName = "NATIVE"; - // TODO: Initialize this more correctly based on the hardware capabilities. - // Init caps - 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: true, - astc: null, - pvrtc: null, - etc1: null, - etc2: null, - bptc: null, - maxAnisotropy: 16, - uintIndices: true, - fragmentDepthSupported: false, - highPrecisionShaderSupported: true, - colorBufferFloat: false, - textureFloat: true, - textureFloatLinearFiltering: false, - textureFloatRender: true, - textureHalfFloat: true, - textureHalfFloatLinearFiltering: false, - textureHalfFloatRender: true, - textureLOD: true, - texelFetch: false, - drawBuffersExtension: false, - depthTextureExtension: false, - vertexArrayObject: true, - instancedArrays: true, - supportOcclusionQuery: false, - canUseTimestampForTimerQuery: false, - blendMinMax: false, - maxMSAASamples: 16, - canUseGLInstanceID: true, - canUseGLVertexID: true, - supportComputeShaders: false, - supportSRGBBuffers: true, - supportTransformFeedbacks: false, - textureMaxLevel: false, - texture2DArrayMaxLayerCount: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS, - disableMorphTargetTexture: false, - }; - this._features = { - forceBitmapOverHTMLImageElement: false, - supportRenderAndCopyToLodForFloatTextures: false, - supportDepthStencilTexture: false, - supportShadowSamplers: false, - uniformBufferHardCheckMatrix: false, - allowTexturePrefiltering: false, - trackUbosInFrame: false, - checkUbosContentBeforeUpload: false, - supportCSM: false, - basisNeedsPOT: false, - support3DTextures: false, - needTypeSuffixInShaderConstants: false, - supportMSAA: false, - supportSSAO2: false, - supportExtendedTextureFormats: false, - supportSwitchCaseInShader: false, - supportSyncTextureRead: false, - needsInvertingBitmap: true, - useUBOBindingCache: true, - needShaderCodeInlining: true, - needToAlwaysBindUniformBuffers: false, - supportRenderPasses: true, - supportSpriteInstancing: false, - _collectUbosUpdatedInFrame: false, - }; - tools_Tools.Log("Babylon Native (v" + engine_Engine.Version + ") launched"); - tools_Tools.LoadScript = function (scriptUrl, onSuccess, onError, scriptId) { - tools_Tools.LoadFile(scriptUrl, (data) => { - Function(data).apply(null); - if (onSuccess) { - onSuccess(); - } - }, undefined, undefined, false, (request, exception) => { - if (onError) { - onError("LoadScript Error", exception); - } - }); - }; - // Wrappers - if (typeof URL === "undefined") { - window.URL = { - createObjectURL: function () { }, - revokeObjectURL: function () { }, - }; - } - if (typeof Blob === "undefined") { - window.Blob = function (v) { - return v; - }; - } - // polyfill for Chakra - if (!Array.prototype.flat) { - Object.defineProperty(Array.prototype, "flat", { - configurable: true, - value: function flat() { - const depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]); - return depth - ? Array.prototype.reduce.call(this, function (acc, cur) { - if (Array.isArray(cur)) { - acc.push.apply(acc, flat.call(cur, depth - 1)); - } - else { - acc.push(cur); - } - return acc; - }, []) - : Array.prototype.slice.call(this); - }, - writable: true, - }); - } - // Currently we do not fully configure the ThinEngine on construction of NativeEngine. - // Setup resolution scaling based on display settings. - const devicePixelRatio = window ? window.devicePixelRatio || 1.0 : 1.0; - this._hardwareScalingLevel = options.adaptToDeviceRatio ? 1.0 / devicePixelRatio : 1.0; - this._engine.setHardwareScalingLevel(this._hardwareScalingLevel); - this._lastDevicePixelRatio = devicePixelRatio; - this.resize(); - const currentDepthFunction = this.getDepthFunction(); - if (currentDepthFunction) { - this.setDepthFunction(currentDepthFunction); - } - // Shader processor - this._shaderProcessor = new WebGL2ShaderProcessor(); - this.onNewSceneAddedObservable.add((scene) => { - const originalRender = scene.render; - scene.render = (...args) => { - this._commandBufferEncoder.beginCommandScope(); - originalRender.apply(scene, args); - this._commandBufferEncoder.endCommandScope(); - }; - }); - } - dispose() { - super.dispose(); - if (this._boundBuffersVertexArray) { - this._deleteVertexArray(this._boundBuffersVertexArray); - } - this._engine.dispose(); - } - /** @internal */ - static _createNativeDataStream() { - return new NativeDataStream(); - } - /** - * Can be used to override the current requestAnimationFrame requester. - * @internal - */ - _queueNewFrame(bindedRenderFunction, requester) { - // Use the provided requestAnimationFrame, unless the requester is the window. In that case, we will default to the Babylon Native version of requestAnimationFrame. - if (requester.requestAnimationFrame && requester !== window) { - requester.requestAnimationFrame(bindedRenderFunction); - } - else { - this._engine.requestAnimationFrame(bindedRenderFunction); - } - return 0; - } - /** - * Override default engine behavior. - * @param framebuffer - */ - _bindUnboundFramebuffer(framebuffer) { - if (this._currentFramebuffer !== framebuffer) { - if (this._currentFramebuffer) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER); - this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer); - this._commandBufferEncoder.finishEncodingCommand(); - } - if (framebuffer) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER); - this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer); - this._commandBufferEncoder.finishEncodingCommand(); - } - this._currentFramebuffer = framebuffer; - } - } - /** - * Gets host document - * @returns the host document object - */ - getHostDocument() { - return null; - } - clear(color, backBuffer, depth, stencil = false) { - if (this.useReverseDepthBuffer) { - throw new Error("reverse depth buffer is not currently implemented"); - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR); - this._commandBufferEncoder.encodeCommandArgAsUInt32(backBuffer && color ? 1 : 0); - this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.r : 0); - this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.g : 0); - this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.b : 0); - this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.a : 1); - this._commandBufferEncoder.encodeCommandArgAsUInt32(depth ? 1 : 0); - this._commandBufferEncoder.encodeCommandArgAsFloat32(1); - this._commandBufferEncoder.encodeCommandArgAsUInt32(stencil ? 1 : 0); - this._commandBufferEncoder.encodeCommandArgAsUInt32(0); - this._commandBufferEncoder.finishEncodingCommand(); - } - createIndexBuffer(indices, updateable) { - const data = this._normalizeIndexData(indices); - const buffer = new NativeDataBuffer(); - buffer.references = 1; - buffer.is32Bits = data.BYTES_PER_ELEMENT === 4; - if (data.byteLength) { - buffer.nativeIndexBuffer = this._engine.createIndexBuffer(data.buffer, data.byteOffset, data.byteLength, buffer.is32Bits, updateable !== null && updateable !== void 0 ? updateable : false); - } - return buffer; - } - createVertexBuffer(vertices, updateable) { - const data = ArrayBuffer.isView(vertices) ? vertices : new Float32Array(vertices); - const buffer = new NativeDataBuffer(); - buffer.references = 1; - if (data.byteLength) { - buffer.nativeVertexBuffer = this._engine.createVertexBuffer(data.buffer, data.byteOffset, data.byteLength, updateable !== null && updateable !== void 0 ? updateable : false); - } - return buffer; - } - _recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { - if (indexBuffer) { - this._engine.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer); - } - const attributes = effect.getAttributesNames(); - for (let index = 0; index < attributes.length; index++) { - const location = effect.getAttributeLocation(index); - if (location >= 0) { - const kind = attributes[index]; - let vertexBuffer = null; - if (overrideVertexBuffers) { - vertexBuffer = overrideVertexBuffers[kind]; - } - if (!vertexBuffer) { - vertexBuffer = vertexBuffers[kind]; - } - if (vertexBuffer) { - const buffer = vertexBuffer.getBuffer(); - if (buffer && buffer.nativeVertexBuffer) { - this._engine.recordVertexBuffer(vertexArray, buffer.nativeVertexBuffer, location, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.getSize(), this._getNativeAttribType(vertexBuffer.type), vertexBuffer.normalized, vertexBuffer.getInstanceDivisor()); - } - } - } - } - } - bindBuffers(vertexBuffers, indexBuffer, effect) { - if (this._boundBuffersVertexArray) { - this._deleteVertexArray(this._boundBuffersVertexArray); - } - this._boundBuffersVertexArray = this._engine.createVertexArray(); - this._recordVertexArrayObject(this._boundBuffersVertexArray, vertexBuffers, indexBuffer, effect); - this.bindVertexArrayObject(this._boundBuffersVertexArray); - } - recordVertexArrayObject(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { - const vertexArray = this._engine.createVertexArray(); - this._recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers); - return vertexArray; - } - _deleteVertexArray(vertexArray) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY); - this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray); - this._commandBufferEncoder.finishEncodingCommand(); - } - bindVertexArrayObject(vertexArray) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY); - this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray); - this._commandBufferEncoder.finishEncodingCommand(); - } - releaseVertexArrayObject(vertexArray) { - this._deleteVertexArray(vertexArray); - } - getAttributes(pipelineContext, attributesNames) { - const nativePipelineContext = pipelineContext; - return this._engine.getAttributes(nativePipelineContext.nativeProgram, attributesNames); - } - /** - * Draw a list of indexed primitives - * @param fillMode defines the primitive to use - * @param indexStart defines the starting index - * @param indexCount defines the number of index to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - drawElementsType(fillMode, indexStart, indexCount, instancesCount) { - // Apply states - this._drawCalls.addCount(1, false); - // TODO: Make this implementation more robust like core Engine version. - // Render - //var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT; - //var mult = this._uintIndicesCurrentlySet ? 4 : 2; - // if (instancesCount) { - // this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount); - // } else { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED); - this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode); - this._commandBufferEncoder.encodeCommandArgAsUInt32(indexStart); - this._commandBufferEncoder.encodeCommandArgAsUInt32(indexCount); - this._commandBufferEncoder.finishEncodingCommand(); - // } - } - /** - * Draw a list of unindexed primitives - * @param fillMode defines the primitive to use - * @param verticesStart defines the index of first vertex to draw - * @param verticesCount defines the count of vertices to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) { - // Apply states - this._drawCalls.addCount(1, false); - // TODO: Make this implementation more robust like core Engine version. - // if (instancesCount) { - // this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount); - // } else { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW); - this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode); - this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesStart); - this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesCount); - this._commandBufferEncoder.finishEncodingCommand(); - // } - } - createPipelineContext() { - return new NativePipelineContext(this); - } - createMaterialContext() { - return undefined; - } - createDrawContext() { - return undefined; - } - _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, _rawVertexSourceCode, _rawFragmentSourceCode, _rebuildRebind, defines) { - const nativePipelineContext = pipelineContext; - if (createAsRaw) { - nativePipelineContext.nativeProgram = this.createRawShaderProgram(); - } - else { - nativePipelineContext.nativeProgram = this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines); - } - } - isAsync(pipelineContext) { - return !!(pipelineContext.isAsync && this._engine.createProgramAsync); - } - /** - * @internal - */ - _executeWhenRenderingStateIsCompiled(pipelineContext, action) { - const nativePipelineContext = pipelineContext; - if (!this.isAsync(pipelineContext)) { - action(); - return; - } - const oldHandler = nativePipelineContext.onCompiled; - if (oldHandler) { - nativePipelineContext.onCompiled = () => { - oldHandler(); - action(); - }; - } - else { - nativePipelineContext.onCompiled = action; - } - } - createRawShaderProgram() { - throw new Error("Not Supported"); - } - createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines) { - const nativePipelineContext = pipelineContext; - if (nativePipelineContext.nativeProgram) { - throw new Error("Tried to create a second program in the same NativePipelineContext"); - } - this.onBeforeShaderCompilationObservable.notifyObservers(this); - const vertexInliner = new ShaderCodeInliner(vertexCode); - vertexInliner.processCode(); - vertexCode = vertexInliner.code; - const fragmentInliner = new ShaderCodeInliner(fragmentCode); - fragmentInliner.processCode(); - fragmentCode = fragmentInliner.code; - vertexCode = ThinEngine._ConcatenateShader(vertexCode, defines); - fragmentCode = ThinEngine._ConcatenateShader(fragmentCode, defines); - const onSuccess = () => { - var _a; - nativePipelineContext.isCompiled = true; - (_a = nativePipelineContext.onCompiled) === null || _a === void 0 ? void 0 : _a.call(nativePipelineContext); - this.onAfterShaderCompilationObservable.notifyObservers(this); - }; - if (this.isAsync(pipelineContext)) { - return this._engine.createProgramAsync(vertexCode, fragmentCode, onSuccess, (error) => { - nativePipelineContext.compilationError = error; - }); - } - else { - try { - const program = (nativePipelineContext.nativeProgram = this._engine.createProgram(vertexCode, fragmentCode)); - onSuccess(); - return program; - } - catch (e) { - const message = e === null || e === void 0 ? void 0 : e.message; - throw new Error("SHADER ERROR" + (typeof message === "string" ? "\n" + message : "")); - } - } - } - /** - * Inline functions in shader code that are marked to be inlined - * @param code code to inline - * @returns inlined code - */ - inlineShaderCode(code) { - const sci = new ShaderCodeInliner(code); - sci.debug = false; - sci.processCode(); - return sci.code; - } - _setProgram(program) { - if (this._currentProgram !== program) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM); - this._commandBufferEncoder.encodeCommandArgAsNativeData(program); - this._commandBufferEncoder.finishEncodingCommand(); - this._currentProgram = program; - } - } - _deletePipelineContext(pipelineContext) { - const nativePipelineContext = pipelineContext; - if (nativePipelineContext && nativePipelineContext.nativeProgram) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM); - this._commandBufferEncoder.encodeCommandArgAsNativeData(nativePipelineContext.nativeProgram); - this._commandBufferEncoder.finishEncodingCommand(); - } - } - getUniforms(pipelineContext, uniformsNames) { - const nativePipelineContext = pipelineContext; - return this._engine.getUniforms(nativePipelineContext.nativeProgram, uniformsNames); - } - bindUniformBlock(pipelineContext, blockName, index) { - // TODO - throw new Error("Not Implemented"); - } - bindSamplers(effect) { - const nativePipelineContext = effect.getPipelineContext(); - this._setProgram(nativePipelineContext.nativeProgram); - // TODO: share this with engine? - const samplers = effect.getSamplers(); - for (let index = 0; index < samplers.length; index++) { - const uniform = effect.getUniform(samplers[index]); - if (uniform) { - this._boundUniforms[index] = uniform; - } - } - this._currentEffect = null; - } - getRenderWidth(useScreen = false) { - if (!useScreen && this._currentRenderTarget) { - return this._currentRenderTarget.width; - } - return this._engine.getRenderWidth(); - } - getRenderHeight(useScreen = false) { - if (!useScreen && this._currentRenderTarget) { - return this._currentRenderTarget.height; - } - return this._engine.getRenderHeight(); - } - setViewport(viewport, requiredWidth, requiredHeight) { - this._cachedViewport = viewport; - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT); - this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.x); - this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.y); - this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.width); - this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.height); - this._commandBufferEncoder.finishEncodingCommand(); - } - enableScissor(x, y, width, height) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR); - this._commandBufferEncoder.encodeCommandArgAsFloat32(x); - this._commandBufferEncoder.encodeCommandArgAsFloat32(y); - this._commandBufferEncoder.encodeCommandArgAsFloat32(width); - this._commandBufferEncoder.encodeCommandArgAsFloat32(height); - this._commandBufferEncoder.finishEncodingCommand(); - } - disableScissor() { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR); - this._commandBufferEncoder.encodeCommandArgAsFloat32(0); - this._commandBufferEncoder.encodeCommandArgAsFloat32(0); - this._commandBufferEncoder.encodeCommandArgAsFloat32(0); - this._commandBufferEncoder.encodeCommandArgAsFloat32(0); - this._commandBufferEncoder.finishEncodingCommand(); - } - setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) { - var _a, _b; - this._zOffset = zOffset; - this._zOffsetUnits = zOffsetUnits; - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE); - this._commandBufferEncoder.encodeCommandArgAsUInt32(culling ? 1 : 0); - this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffset); - this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffsetUnits); - this._commandBufferEncoder.encodeCommandArgAsUInt32(((_b = (_a = this.cullBackFaces) !== null && _a !== void 0 ? _a : cullBackFaces) !== null && _b !== void 0 ? _b : true) ? 1 : 0); - this._commandBufferEncoder.encodeCommandArgAsUInt32(reverseSide ? 1 : 0); - this._commandBufferEncoder.finishEncodingCommand(); - } - /** - * Gets the client rect of native canvas. Needed for InputManager. - * @returns a client rectangle - */ - getInputElementClientRect() { - const rect = { - bottom: this.getRenderHeight(), - height: this.getRenderHeight(), - left: 0, - right: this.getRenderWidth(), - top: 0, - width: this.getRenderWidth(), - x: 0, - y: 0, - toJSON: () => { }, - }; - return rect; - } - /** - * Set the z offset Factor to apply to current rendering - * @param value defines the offset to apply - */ - setZOffset(value) { - if (value !== this._zOffset) { - this._zOffset = value; - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET); - this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value); - this._commandBufferEncoder.finishEncodingCommand(); - } - } - /** - * Gets the current value of the zOffset Factor - * @returns the current zOffset Factor state - */ - getZOffset() { - return this._zOffset; - } - /** - * Set the z offset Units to apply to current rendering - * @param value defines the offset to apply - */ - setZOffsetUnits(value) { - if (value !== this._zOffsetUnits) { - this._zOffsetUnits = value; - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS); - this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value); - this._commandBufferEncoder.finishEncodingCommand(); - } - } - /** - * Gets the current value of the zOffset Units - * @returns the current zOffset Units state - */ - getZOffsetUnits() { - return this._zOffsetUnits; - } - /** - * Enable or disable depth buffering - * @param enable defines the state to set - */ - setDepthBuffer(enable) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST); - this._commandBufferEncoder.encodeCommandArgAsUInt32(enable ? this._currentDepthTest : _native.Engine.DEPTH_TEST_ALWAYS); - this._commandBufferEncoder.finishEncodingCommand(); - } - /** - * Gets a boolean indicating if depth writing is enabled - * @returns the current depth writing state - */ - 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(depthFunc) { - let nativeDepthFunc = 0; - switch (depthFunc) { - case 512: - nativeDepthFunc = _native.Engine.DEPTH_TEST_NEVER; - break; - case 519: - nativeDepthFunc = _native.Engine.DEPTH_TEST_ALWAYS; - break; - case 516: - nativeDepthFunc = _native.Engine.DEPTH_TEST_GREATER; - break; - case 518: - nativeDepthFunc = _native.Engine.DEPTH_TEST_GEQUAL; - break; - case 517: - nativeDepthFunc = _native.Engine.DEPTH_TEST_NOTEQUAL; - break; - case 514: - nativeDepthFunc = _native.Engine.DEPTH_TEST_EQUAL; - break; - case 513: - nativeDepthFunc = _native.Engine.DEPTH_TEST_LESS; - break; - case 515: - nativeDepthFunc = _native.Engine.DEPTH_TEST_LEQUAL; - break; - } - this._currentDepthTest = nativeDepthFunc; - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST); - this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest); - this._commandBufferEncoder.finishEncodingCommand(); - } - /** - * Enable or disable depth writing - * @param enable defines the state to set - */ - setDepthWrite(enable) { - this._depthWrite = enable; - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE); - this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable)); - this._commandBufferEncoder.finishEncodingCommand(); - } - /** - * Enable or disable color writing - * @param enable defines the state to set - */ - setColorWrite(enable) { - this._colorWrite = enable; - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE); - this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable)); - this._commandBufferEncoder.finishEncodingCommand(); - } - /** - * Gets a boolean indicating if color writing is enabled - * @returns the current color writing state - */ - 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(mask, stencilOpFail, depthOpFail, depthOpPass, func, ref) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL); - this._commandBufferEncoder.encodeCommandArgAsUInt32(mask); - this._commandBufferEncoder.encodeCommandArgAsUInt32(stencilOpFail); - this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpFail); - this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpPass); - this._commandBufferEncoder.encodeCommandArgAsUInt32(func); - this._commandBufferEncoder.encodeCommandArgAsUInt32(ref); - this._commandBufferEncoder.finishEncodingCommand(); - } - /** - * Enable or disable the stencil buffer - * @param enable defines if the stencil buffer must be enabled or disabled - */ - setStencilBuffer(enable) { - this._stencilTest = enable; - if (enable) { - this.applyStencil(); - } - else { - 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); - } - } - /** - * Gets a boolean indicating if stencil buffer is enabled - * @returns the current stencil buffer state - */ - getStencilBuffer() { - return this._stencilTest; - } - /** - * Gets the current stencil operation when stencil passes - * @returns a number defining stencil operation to use when stencil passes - */ - getStencilOperationPass() { - return this._stencilOpStencilDepthPass; - } - /** - * Sets the stencil operation to use when stencil passes - * @param operation defines the stencil operation to use when stencil passes - */ - setStencilOperationPass(operation) { - this._stencilOpStencilDepthPass = operation; - this.applyStencil(); - } - /** - * Sets the current stencil mask - * @param mask defines the new stencil mask to use - */ - setStencilMask(mask) { - this._stencilMask = mask; - this.applyStencil(); - } - /** - * Sets the current stencil function - * @param stencilFunc defines the new stencil function to use - */ - setStencilFunction(stencilFunc) { - this._stencilFunc = stencilFunc; - this.applyStencil(); - } - /** - * Sets the current stencil reference - * @param reference defines the new stencil reference to use - */ - setStencilFunctionReference(reference) { - this._stencilFuncRef = reference; - this.applyStencil(); - } - /** - * Sets the current stencil mask - * @param mask defines the new stencil mask to use - */ - setStencilFunctionMask(mask) { - this._stencilFuncMask = mask; - } - /** - * Sets the stencil operation to use when stencil fails - * @param operation defines the stencil operation to use when stencil fails - */ - setStencilOperationFail(operation) { - this._stencilOpStencilFail = operation; - this.applyStencil(); - } - /** - * Sets the stencil operation to use when depth fails - * @param operation defines the stencil operation to use when depth fails - */ - setStencilOperationDepthFail(operation) { - this._stencilOpDepthFail = operation; - this.applyStencil(); - } - /** - * Gets the current stencil mask - * @returns a number defining the new stencil mask to use - */ - getStencilMask() { - return this._stencilMask; - } - /** - * Gets the current stencil function - * @returns a number defining the stencil function to use - */ - getStencilFunction() { - return this._stencilFunc; - } - /** - * Gets the current stencil reference value - * @returns a number defining the stencil reference value to use - */ - getStencilFunctionReference() { - return this._stencilFuncRef; - } - /** - * Gets the current stencil mask - * @returns a number defining the stencil mask to use - */ - getStencilFunctionMask() { - return this._stencilFuncMask; - } - /** - * Gets the current stencil operation when stencil fails - * @returns a number defining stencil operation to use when stencil fails - */ - getStencilOperationFail() { - return this._stencilOpStencilFail; - } - /** - * Gets the current stencil operation when depth fails - * @returns a number defining stencil operation to use when depth fails - */ - getStencilOperationDepthFail() { - return this._stencilOpDepthFail; - } - /** - * Sets alpha constants used by some alpha blending modes - * @param r defines the red component - * @param g defines the green component - * @param b defines the blue component - * @param a defines the alpha component - */ - setAlphaConstants(r, g, b, a) { - throw new Error("Setting alpha blend constant color not yet implemented."); - } - /** - * Sets the current alpha mode - * @param mode defines the mode to use (one of the BABYLON.undefined) - * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default) - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering - */ - setAlphaMode(mode, noDepthWriteChange = false) { - if (this._alphaMode === mode) { - return; - } - const nativeMode = this._getNativeAlphaMode(mode); - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE); - this._commandBufferEncoder.encodeCommandArgAsUInt32(nativeMode); - this._commandBufferEncoder.finishEncodingCommand(); - if (!noDepthWriteChange) { - this.setDepthWrite(mode === 0); - } - this._alphaMode = mode; - } - /** - * Gets the current alpha mode - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering - * @returns the current alpha mode - */ - getAlphaMode() { - return this._alphaMode; - } - setInt(uniform, int) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsInt32(int); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setIntArray(uniform, array) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsInt32s(array); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setIntArray2(uniform, array) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsInt32s(array); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setIntArray3(uniform, array) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsInt32s(array); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setIntArray4(uniform, array) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsInt32s(array); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setFloatArray(uniform, array) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32s(array); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setFloatArray2(uniform, array) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32s(array); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setFloatArray3(uniform, array) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32s(array); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setFloatArray4(uniform, array) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32s(array); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setArray(uniform, array) { - if (!uniform) { - return false; - } - return this.setFloatArray(uniform, new Float32Array(array)); - } - setArray2(uniform, array) { - if (!uniform) { - return false; - } - return this.setFloatArray2(uniform, new Float32Array(array)); - } - setArray3(uniform, array) { - if (!uniform) { - return false; - } - return this.setFloatArray3(uniform, new Float32Array(array)); - } - setArray4(uniform, array) { - if (!uniform) { - return false; - } - return this.setFloatArray4(uniform, new Float32Array(array)); - } - setMatrices(uniform, matrices) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrices); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setMatrix3x3(uniform, matrix) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setMatrix2x2(uniform, matrix) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setFloat(uniform, value) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32(value); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setFloat2(uniform, x, y) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32(x); - this._commandBufferEncoder.encodeCommandArgAsFloat32(y); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setFloat3(uniform, x, y, z) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32(x); - this._commandBufferEncoder.encodeCommandArgAsFloat32(y); - this._commandBufferEncoder.encodeCommandArgAsFloat32(z); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setFloat4(uniform, x, y, z, w) { - if (!uniform) { - return false; - } - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsFloat32(x); - this._commandBufferEncoder.encodeCommandArgAsFloat32(y); - this._commandBufferEncoder.encodeCommandArgAsFloat32(z); - this._commandBufferEncoder.encodeCommandArgAsFloat32(w); - this._commandBufferEncoder.finishEncodingCommand(); - return true; - } - setColor3(uniform, color3) { - if (!uniform) { - return false; - } - this.setFloat3(uniform, color3.r, color3.g, color3.b); - return true; - } - setColor4(uniform, color3, alpha) { - if (!uniform) { - return false; - } - this.setFloat4(uniform, color3.r, color3.g, color3.b, alpha); - return true; - } - wipeCaches(bruteForce) { - if (this.preventCacheWipeBetweenFrames) { - return; - } - this.resetTextureCache(); - this._currentEffect = null; - if (bruteForce) { - 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(texture) { - if (texture) { - this._engine.deleteTexture(texture); - } - } - /** - * Update the content of a dynamic texture - * @param texture defines the texture to update - * @param canvas defines the canvas containing the source - * @param invertY defines if data must be stored with Y axis inverted - * @param premulAlpha defines if alpha is stored as premultiplied - * @param format defines the format of the data - */ - updateDynamicTexture(texture, canvas, invertY, premulAlpha = false, format) { - if (premulAlpha === void 0) { - premulAlpha = false; - } - if (!!texture && !!texture._hardwareTexture) { - const source = canvas.getCanvasTexture(); - const destination = texture._hardwareTexture.underlyingResource; - this._engine.copyTexture(destination, source); - texture.isReady = true; - } - } - createDynamicTexture(width, height, generateMipMaps, samplingMode) { - // it's not possible to create 0x0 texture sized. Many bgfx methods assume texture size is at least 1x1(best case). - // Worst case is getting a crash/assert. - width = Math.max(width, 1); - height = Math.max(height, 1); - return this.createRawTexture(new Uint8Array(width * height * 4), width, height, 5, false, false, samplingMode); - } - createVideoElement(constraints) { - // create native object depending on stream. Only NativeCamera is supported for now. - if (this._camera) { - return this._camera.createVideo(constraints); - } - return null; - } - updateVideoTexture(texture, video, invertY) { - if (texture && texture._hardwareTexture && this._camera) { - const webGLTexture = texture._hardwareTexture.underlyingResource; - this._camera.updateVideoTexture(webGLTexture, video, invertY); - } - } - createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) { - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Raw); - texture.format = format; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.invertY = invertY; - texture.baseWidth = width; - texture.baseHeight = height; - texture.width = texture.baseWidth; - texture.height = texture.baseHeight; - texture._compression = compression; - texture.type = type; - texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps); - this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer); - if (texture._hardwareTexture) { - const webGLTexture = texture._hardwareTexture.underlyingResource; - const filter = this._getNativeSamplingMode(samplingMode); - this._setTextureSampling(webGLTexture, filter); - } - this._internalTexturesCache.push(texture); - return texture; - } - createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) { - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Raw2DArray); - texture.baseWidth = width; - texture.baseHeight = height; - texture.baseDepth = depth; - texture.width = width; - texture.height = height; - texture.depth = depth; - texture.format = format; - texture.type = textureType; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.is2DArray = true; - if (texture._hardwareTexture) { - const nativeTexture = texture._hardwareTexture.underlyingResource; - this._engine.loadRawTexture2DArray(nativeTexture, data, width, height, depth, this._getNativeTextureFormat(format, textureType), generateMipMaps, invertY); - const filter = this._getNativeSamplingMode(samplingMode); - this._setTextureSampling(nativeTexture, filter); - } - texture.isReady = true; - this._internalTexturesCache.push(texture); - return texture; - } - updateRawTexture(texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) { - if (!texture) { - return; - } - if (bufferView && texture._hardwareTexture) { - const underlyingResource = texture._hardwareTexture.underlyingResource; - this._engine.loadRawTexture(underlyingResource, bufferView, texture.width, texture.height, this._getNativeTextureFormat(format, type), texture.generateMipMaps, texture.invertY); - } - texture.isReady = true; - } - // TODO: Refactor to share more logic with babylon.engine.ts version. - /** - * Usually called from Texture.ts. - * Passed information to create a NativeTexture - * @param url defines a value which contains one of the following: - * * A conventional http URL, e.g. 'http://...' or 'file://...' - * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...' - * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg' - * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file - * @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) - * @param scene needed for loading to the correct scene - * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE) - * @param onLoad optional callback to be called upon successful completion - * @param onError optional callback to be called upon failure - * @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 - * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities - * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures - * @param forcedExtension defines the extension to use to pick the right loader - * @param mimeType defines an optional mime type - * @param loaderOptions options to be passed to the loader - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - * @returns a InternalTexture for assignment back into BABYLON.Texture - */ - createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer = false) { - url = url || ""; - const fromData = url.substr(0, 5) === "data:"; - //const fromBlob = url.substr(0, 5) === "blob:"; - const isBase64 = fromData && url.indexOf(";base64,") !== -1; - const texture = fallback ? fallback : new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Url); - const originalUrl = url; - if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) { - url = this._transformTextureUrl(url); - } - // establish the file extension, if possible - const lastDot = url.lastIndexOf("."); - const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : ""; - let loader = null; - for (const availableLoader of engine_Engine._TextureLoaders) { - if (availableLoader.canLoad(extension)) { - loader = availableLoader; - break; - } - } - if (scene) { - scene.addPendingData(texture); - } - texture.url = url; - texture.generateMipMaps = !noMipmap; - texture.samplingMode = samplingMode; - texture.invertY = invertY; - texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, noMipmap); - if (!this.doNotHandleContextLost) { - // Keep a link to the buffer only if we plan to handle context lost - texture._buffer = buffer; - } - let onLoadObserver = null; - if (onLoad && !fallback) { - onLoadObserver = texture.onLoadedObservable.add(onLoad); - } - if (!fallback) { - this._internalTexturesCache.push(texture); - } - const onInternalError = (message, exception) => { - if (scene) { - scene.removePendingData(texture); - } - if (url === originalUrl) { - if (onLoadObserver) { - texture.onLoadedObservable.remove(onLoadObserver); - } - if (engineStore_EngineStore.UseFallbackTexture) { - this.createTexture(engineStore_EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture); - } - if (onError) { - onError((message || "Unknown error") + (engineStore_EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""), exception); - } - } - else { - // fall back to the original url if the transformed url fails to load - logger_Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`); - this.createTexture(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, buffer, texture, format, forcedExtension, mimeType, loaderOptions); - } - }; - // processing for non-image formats - if (loader) { - throw new Error("Loading textures from IInternalTextureLoader not yet implemented."); - } - else { - const onload = (data) => { - if (!texture._hardwareTexture) { - if (scene) { - scene.removePendingData(texture); - } - return; - } - const underlyingResource = texture._hardwareTexture.underlyingResource; - this._engine.loadTexture(underlyingResource, data, !noMipmap, invertY, texture._useSRGBBuffer, () => { - texture.baseWidth = this._engine.getTextureWidth(underlyingResource); - texture.baseHeight = this._engine.getTextureHeight(underlyingResource); - texture.width = texture.baseWidth; - texture.height = texture.baseHeight; - texture.isReady = true; - const filter = this._getNativeSamplingMode(samplingMode); - this._setTextureSampling(underlyingResource, filter); - if (scene) { - scene.removePendingData(texture); - } - texture.onLoadedObservable.notifyObservers(texture); - texture.onLoadedObservable.clear(); - }, () => { - throw new Error("Could not load a native texture."); - }); - }; - if (fromData && buffer) { - if (buffer instanceof ArrayBuffer) { - onload(new Uint8Array(buffer)); - } - else if (ArrayBuffer.isView(buffer)) { - onload(buffer); - } - else if (typeof buffer === "string") { - onload(new Uint8Array(tools_Tools.DecodeBase64(buffer))); - } - else { - throw new Error("Unsupported buffer type"); - } - } - else { - if (isBase64) { - onload(new Uint8Array(tools_Tools.DecodeBase64(url))); - } - else { - this._loadFile(url, (data) => onload(new Uint8Array(data)), undefined, undefined, true, (request, exception) => { - onInternalError("Unable to load " + (request ? request.responseURL : url, exception)); - }); - } - } - } - return texture; - } - /** - * Wraps an external native texture in a Babylon texture. - * @param texture defines the external texture - * @param hasMipMaps defines whether the external texture has mip maps - * @param samplingMode defines the sampling mode for the external texture (default: 3) - * @returns the babylon internal texture - */ - wrapNativeTexture(texture, hasMipMaps = false, samplingMode = 3) { - const hardwareTexture = new NativeHardwareTexture(texture, this._engine); - const internalTexture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Unknown, true); - internalTexture._hardwareTexture = hardwareTexture; - internalTexture.isReady = true; - internalTexture.useMipMaps = hasMipMaps; - this.updateTextureSamplingMode(samplingMode, internalTexture); - return internalTexture; - } - /** - * Wraps an external web gl texture in a Babylon texture. - * @returns the babylon internal texture - */ - wrapWebGLTexture() { - throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead."); - } - _createDepthStencilTexture(size, options, rtWrapper) { - var _a, _b; - // TODO: handle other options? - const generateStencil = options.generateStencil || false; - const samples = options.samples || 1; - const nativeRTWrapper = rtWrapper; - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.DepthStencil); - const width = (_a = size.width) !== null && _a !== void 0 ? _a : size; - const height = (_b = size.height) !== null && _b !== void 0 ? _b : size; - const framebuffer = this._engine.createFrameBuffer(texture._hardwareTexture.underlyingResource, width, height, generateStencil, true, samples); - nativeRTWrapper._framebufferDepthStencil = framebuffer; - return texture; - } - /** - * @internal - */ - _releaseFramebufferObjects(framebuffer) { - if (framebuffer) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER); - this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer); - this._commandBufferEncoder.finishEncodingCommand(); - } - } - /** - * @internal Engine abstraction for loading and creating an image bitmap from a given source string. - * @param imageSource source to load the image from. - * @param options An object that sets options for the image's extraction. - * @returns ImageBitmap - */ - _createImageBitmapFromSource(imageSource, options) { - const promise = new Promise((resolve, reject) => { - const image = this.createCanvasImage(); - image.onload = () => { - try { - const imageBitmap = this._engine.createImageBitmap(image); - resolve(imageBitmap); - } - catch (error) { - reject(`Error loading image ${image.src} with exception: ${error}`); - } - }; - image.onerror = (error) => { - reject(`Error loading image ${image.src} with exception: ${error}`); - }; - image.src = imageSource; - }); - return promise; - } - /** - * Engine abstraction for createImageBitmap - * @param image source for image - * @param options An object that sets options for the image's extraction. - * @returns ImageBitmap - */ - createImageBitmap(image, options) { - return new Promise((resolve, reject) => { - if (Array.isArray(image)) { - const arr = image; - if (arr.length) { - const image = this._engine.createImageBitmap(arr[0]); - if (image) { - resolve(image); - return; - } - } - } - reject(`Unsupported data for createImageBitmap.`); - }); - } - /** - * Resize an image and returns the image data as an uint8array - * @param image image to resize - * @param bufferWidth destination buffer width - * @param bufferHeight destination buffer height - * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size - */ - resizeImageBitmap(image, bufferWidth, bufferHeight) { - return this._engine.resizeImageBitmap(image, bufferWidth, bufferHeight); - } - /** - * Creates a cube texture - * @param rootUrl defines the url where the files to load is located - * @param scene defines the current scene - * @param files defines the list of files to load (1 per face) - * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default) - * @param onLoad defines an optional callback raised when the texture is loaded - * @param onError defines an optional callback raised if there is an issue to load the texture - * @param format defines the format of the data - * @param forcedExtension defines the extension to use to pick the right loader - * @param createPolynomials if a polynomial sphere should be created for the cube texture - * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness - * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness - * @param fallback defines texture to use while falling back when (compressed) texture file not found. - * @param loaderOptions options to be passed to the loader - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - * @returns the cube texture as an InternalTexture - */ - createCubeTexture(rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false) { - const texture = fallback ? fallback : new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Cube); - texture.isCube = true; - texture.url = rootUrl; - texture.generateMipMaps = !noMipmap; - texture._lodGenerationScale = lodScale; - texture._lodGenerationOffset = lodOffset; - texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !!noMipmap); - if (!this._doNotHandleContextLost) { - texture._extension = forcedExtension; - texture._files = files; - } - const lastDot = rootUrl.lastIndexOf("."); - const extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : ""; - // TODO: use texture loader to load env files? - if (extension === ".env") { - const onloaddata = (data) => { - const info = GetEnvInfo(data); - texture.width = info.width; - texture.height = info.width; - UploadEnvSpherical(texture, info); - const specularInfo = info.specular; - if (!specularInfo) { - throw new Error(`Nothing else parsed so far`); - } - texture._lodGenerationScale = specularInfo.lodGenerationScale; - const imageData = CreateImageDataArrayBufferViews(data, info); - texture.format = 5; - texture.type = 0; - texture.generateMipMaps = true; - texture.getEngine().updateTextureSamplingMode(texture_Texture.TRILINEAR_SAMPLINGMODE, texture); - texture._isRGBD = true; - texture.invertY = true; - this._engine.loadCubeTextureWithMips(texture._hardwareTexture.underlyingResource, imageData, false, texture._useSRGBBuffer, () => { - texture.isReady = true; - if (onLoad) { - onLoad(); - } - }, () => { - throw new Error("Could not load a native cube texture."); - }); - }; - if (files && files.length === 6) { - throw new Error(`Multi-file loading not allowed on env files.`); - } - else { - const onInternalError = (request, exception) => { - if (onError && request) { - onError(request.status + " " + request.statusText, exception); - } - }; - this._loadFile(rootUrl, (data) => onloaddata(new Uint8Array(data)), undefined, undefined, true, onInternalError); - } - } - else { - if (!files || files.length !== 6) { - throw new Error("Cannot load cubemap because 6 files were not defined"); - } - // Reorder from [+X, +Y, +Z, -X, -Y, -Z] to [+X, -X, +Y, -Y, +Z, -Z]. - const reorderedFiles = [files[0], files[3], files[1], files[4], files[2], files[5]]; - Promise.all(reorderedFiles.map((file) => tools_Tools.LoadFileAsync(file).then((data) => new Uint8Array(data)))) - .then((data) => { - return new Promise((resolve, reject) => { - this._engine.loadCubeTexture(texture._hardwareTexture.underlyingResource, data, !noMipmap, true, texture._useSRGBBuffer, resolve, reject); - }); - }) - .then(() => { - texture.isReady = true; - if (onLoad) { - onLoad(); - } - }, (error) => { - if (onError) { - onError(`Failed to load cubemap: ${error.message}`, error); - } - }); - } - this._internalTexturesCache.push(texture); - return texture; - } - /** @internal */ - _createHardwareTexture() { - return new NativeHardwareTexture(this._createTexture(), this._engine); - } - /** @internal */ - _createHardwareRenderTargetWrapper(isMulti, isCube, size) { - const rtWrapper = new NativeRenderTargetWrapper(isMulti, isCube, size, this); - this._renderTargetWrapperCache.push(rtWrapper); - return rtWrapper; - } - /** @internal */ - _createInternalTexture(size, options, _delayGPUTextureCreation = true, source = internalTexture_InternalTextureSource.Unknown) { - var _a, _b, _c; - let generateMipMaps = false; - let type = 0; - let samplingMode = 3; - let format = 5; - let useSRGBBuffer = false; - let samples = 1; - let label; - if (options !== undefined && typeof options === "object") { - generateMipMaps = !!options.generateMipMaps; - type = options.type === undefined ? 0 : options.type; - samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode; - format = options.format === undefined ? 5 : options.format; - useSRGBBuffer = options.useSRGBBuffer === undefined ? false : options.useSRGBBuffer; - samples = (_a = options.samples) !== null && _a !== void 0 ? _a : 1; - label = options.label; - } - else { - generateMipMaps = !!options; - } - useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps); - if (type === 1 && !this._caps.textureFloatLinearFiltering) { - // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE - samplingMode = 1; - } - else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { - // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE - samplingMode = 1; - } - if (type === 1 && !this._caps.textureFloat) { - type = 0; - logger_Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"); - } - const texture = new internalTexture_InternalTexture(this, source); - const width = (_b = size.width) !== null && _b !== void 0 ? _b : size; - const height = (_c = size.height) !== null && _c !== void 0 ? _c : size; - const layers = size.layers || 0; - if (layers !== 0) { - throw new Error("Texture layers are not supported in Babylon Native"); - } - const nativeTexture = texture._hardwareTexture.underlyingResource; - const nativeTextureFormat = this._getNativeTextureFormat(format, type); - // REVIEW: We are always setting the renderTarget flag as we don't know whether the texture will be used as a render target. - this._engine.initializeTexture(nativeTexture, width, height, generateMipMaps, nativeTextureFormat, true, useSRGBBuffer, samples); - this._setTextureSampling(nativeTexture, this._getNativeSamplingMode(samplingMode)); - texture._useSRGBBuffer = useSRGBBuffer; - texture.baseWidth = width; - texture.baseHeight = height; - texture.width = width; - texture.height = height; - texture.depth = layers; - texture.isReady = true; - texture.samples = samples; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.type = type; - texture.format = format; - texture.label = label; - this._internalTexturesCache.push(texture); - return texture; - } - createRenderTargetTexture(size, options) { - var _a, _b, _c, _d; - const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size); - let generateDepthBuffer = true; - let generateStencilBuffer = false; - let noColorAttachment = false; - let colorAttachment = undefined; - let samples = 1; - if (options !== undefined && typeof options === "object") { - generateDepthBuffer = (_a = options.generateDepthBuffer) !== null && _a !== void 0 ? _a : true; - generateStencilBuffer = !!options.generateStencilBuffer; - noColorAttachment = !!options.noColorAttachment; - colorAttachment = options.colorAttachment; - samples = (_b = options.samples) !== null && _b !== void 0 ? _b : 1; - } - const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, internalTexture_InternalTextureSource.RenderTarget)); - const width = (_c = size.width) !== null && _c !== void 0 ? _c : size; - const height = (_d = size.height) !== null && _d !== void 0 ? _d : size; - const framebuffer = this._engine.createFrameBuffer(texture ? texture._hardwareTexture.underlyingResource : null, width, height, generateStencilBuffer, generateDepthBuffer, samples); - rtWrapper._framebuffer = framebuffer; - rtWrapper._generateDepthBuffer = generateDepthBuffer; - rtWrapper._generateStencilBuffer = generateStencilBuffer; - rtWrapper._samples = samples; - rtWrapper.setTextures(texture); - return rtWrapper; - } - updateRenderTargetTextureSampleCount(rtWrapper, samples) { - logger_Logger.Warn("Updating render target sample count is not currently supported"); - return rtWrapper.samples; - } - updateTextureSamplingMode(samplingMode, texture) { - if (texture._hardwareTexture) { - const filter = this._getNativeSamplingMode(samplingMode); - this._setTextureSampling(texture._hardwareTexture.underlyingResource, filter); - } - texture.samplingMode = samplingMode; - } - bindFramebuffer(texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) { - const nativeRTWrapper = texture; - if (this._currentRenderTarget) { - this.unBindFramebuffer(this._currentRenderTarget); - } - this._currentRenderTarget = texture; - if (faceIndex) { - throw new Error("Cuboid frame buffers are not yet supported in NativeEngine."); - } - if (requiredWidth || requiredHeight) { - throw new Error("Required width/height for frame buffers not yet supported in NativeEngine."); - } - if (forceFullscreenViewport) { - //Not supported yet but don't stop rendering - } - if (nativeRTWrapper._framebufferDepthStencil) { - this._bindUnboundFramebuffer(nativeRTWrapper._framebufferDepthStencil); - } - else { - this._bindUnboundFramebuffer(nativeRTWrapper._framebuffer); - } - } - unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) { - // NOTE: Disabling mipmap generation is not yet supported in NativeEngine. - this._currentRenderTarget = null; - if (onBeforeUnbind) { - onBeforeUnbind(); - } - this._bindUnboundFramebuffer(null); - } - createDynamicVertexBuffer(data) { - return this.createVertexBuffer(data, true); - } - updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) { - const buffer = indexBuffer; - const data = this._normalizeIndexData(indices); - buffer.is32Bits = data.BYTES_PER_ELEMENT === 4; - this._engine.updateDynamicIndexBuffer(buffer.nativeIndexBuffer, data.buffer, data.byteOffset, data.byteLength, offset); - } - updateDynamicVertexBuffer(vertexBuffer, verticies, byteOffset, byteLength) { - const buffer = vertexBuffer; - const data = ArrayBuffer.isView(verticies) ? verticies : new Float32Array(verticies); - this._engine.updateDynamicVertexBuffer(buffer.nativeVertexBuffer, data.buffer, data.byteOffset + (byteOffset !== null && byteOffset !== void 0 ? byteOffset : 0), byteLength !== null && byteLength !== void 0 ? byteLength : data.byteLength); - } - // TODO: Refactor to share more logic with base Engine implementation. - _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false) { - const uniform = this._boundUniforms[channel]; - if (!uniform) { - return false; - } - // Not ready? - if (!texture) { - if (this._boundTexturesCache[channel] != null) { - this._activeChannel = channel; - this._boundTexturesCache[channel] = null; - } - return false; - } - // Video - if (texture.video) { - this._activeChannel = channel; - texture.update(); - } - else if (texture.delayLoadState === 4) { - // Delay loading - texture.delayLoad(); - return false; - } - let internalTexture; - if (depthStencilTexture) { - internalTexture = texture.depthStencilTexture; - } - else if (texture.isReady()) { - internalTexture = texture.getInternalTexture(); - } - else if (texture.isCube) { - internalTexture = this.emptyCubeTexture; - } - else if (texture.is3D) { - internalTexture = this.emptyTexture3D; - } - else if (texture.is2DArray) { - internalTexture = this.emptyTexture2DArray; - } - else { - internalTexture = this.emptyTexture; - } - this._activeChannel = channel; - if (!internalTexture || !internalTexture._hardwareTexture) { - return false; - } - this._setTextureWrapMode(internalTexture._hardwareTexture.underlyingResource, this._getAddressMode(texture.wrapU), this._getAddressMode(texture.wrapV), this._getAddressMode(texture.wrapR)); - this._updateAnisotropicLevel(texture); - this._setTextureCore(uniform, internalTexture._hardwareTexture.underlyingResource); - return true; - } - // filter is a NativeFilter.XXXX value. - _setTextureSampling(texture, filter) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING); - this._commandBufferEncoder.encodeCommandArgAsNativeData(texture); - this._commandBufferEncoder.encodeCommandArgAsUInt32(filter); - this._commandBufferEncoder.finishEncodingCommand(); - } - // addressModes are NativeAddressMode.XXXX values. - _setTextureWrapMode(texture, addressModeU, addressModeV, addressModeW) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE); - this._commandBufferEncoder.encodeCommandArgAsNativeData(texture); - this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeU); - this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeV); - this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeW); - this._commandBufferEncoder.finishEncodingCommand(); - } - _setTextureCore(uniform, texture) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE); - this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform); - this._commandBufferEncoder.encodeCommandArgAsNativeData(texture); - this._commandBufferEncoder.finishEncodingCommand(); - } - // TODO: Share more of this logic with the base implementation. - // TODO: Rename to match naming in base implementation once refactoring allows different parameters. - _updateAnisotropicLevel(texture) { - const internalTexture = texture.getInternalTexture(); - const value = texture.anisotropicFilteringLevel; - if (!internalTexture || !internalTexture._hardwareTexture) { - return; - } - if (internalTexture._cachedAnisotropicFilteringLevel !== value) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL); - this._commandBufferEncoder.encodeCommandArgAsNativeData(internalTexture._hardwareTexture.underlyingResource); - this._commandBufferEncoder.encodeCommandArgAsUInt32(value); - this._commandBufferEncoder.finishEncodingCommand(); - internalTexture._cachedAnisotropicFilteringLevel = value; - } - } - // Returns a NativeAddressMode.XXX value. - _getAddressMode(wrapMode) { - switch (wrapMode) { - 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: " + wrapMode + "."); - } - } - /** - * @internal - */ - _bindTexture(channel, texture) { - const uniform = this._boundUniforms[channel]; - if (!uniform) { - return; - } - if (texture && texture._hardwareTexture) { - const underlyingResource = texture._hardwareTexture.underlyingResource; - this._setTextureCore(uniform, underlyingResource); - } - } - _deleteBuffer(buffer) { - if (buffer.nativeIndexBuffer) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER); - this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer.nativeIndexBuffer); - this._commandBufferEncoder.finishEncodingCommand(); - delete buffer.nativeIndexBuffer; - } - if (buffer.nativeVertexBuffer) { - this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER); - this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer.nativeVertexBuffer); - this._commandBufferEncoder.finishEncodingCommand(); - delete buffer.nativeVertexBuffer; - } - } - /** - * Create a canvas - * @param width width - * @param height height - * @returns ICanvas interface - */ - createCanvas(width, height) { - if (!_native.Canvas) { - throw new Error("Native Canvas plugin not available."); - } - const canvas = new _native.Canvas(); - canvas.width = width; - canvas.height = height; - return canvas; - } - /** - * Create an image to use with canvas - * @returns IImage interface - */ - createCanvasImage() { - if (!_native.Canvas) { - throw new Error("Native Canvas plugin not available."); - } - const image = new _native.Image(); - return image; - } - /** - * Update a portion of an internal texture - * @param texture defines the texture to update - * @param imageData defines the data to store into the texture - * @param xOffset defines the x coordinates of the update rectangle - * @param yOffset defines the y coordinates of the update rectangle - * @param width defines the width of the update rectangle - * @param height defines the height of the update rectangle - * @param faceIndex defines the face index if texture is a cube (0 by default) - * @param lod defines the lod level to update (0 by default) - * @param generateMipMaps defines whether to generate mipmaps or not - */ - updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) { - throw new Error("updateTextureData not implemented."); - } - /** - * @internal - */ - _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) { - throw new Error("_uploadCompressedDataToTextureDirectly not implemented."); - } - /** - * @internal - */ - _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0) { - throw new Error("_uploadDataToTextureDirectly not implemented."); - } - /** - * @internal - */ - _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) { - throw new Error("_uploadArrayBufferViewToTexture not implemented."); - } - /** - * @internal - */ - _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) { - throw new Error("_uploadArrayBufferViewToTexture not implemented."); - } - // JavaScript-to-Native conversion helper functions. - _getNativeSamplingMode(samplingMode) { - switch (samplingMode) { - 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: ${samplingMode}.`); - } - } - _getStencilFunc(func) { - switch (func) { - 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: ${func}.`); - } - } - _getStencilOpFail(opFail) { - switch (opFail) { - 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: ${opFail}.`); - } - } - _getStencilDepthFail(depthFail) { - switch (depthFail) { - 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: ${depthFail}.`); - } - } - _getStencilDepthPass(opPass) { - switch (opPass) { - 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: ${opPass}.`); - } - } - _getNativeTextureFormat(format, type) { - if (format == 4 && type == 0) { - return _native.Engine.TEXTURE_FORMAT_RGB8; - } - else if (format == 5 && type == 0) { - return _native.Engine.TEXTURE_FORMAT_RGBA8; - } - else if (format == 5 && type == 2) { - return _native.Engine.TEXTURE_FORMAT_RGBA16F; - } - else if (format == 5 && type == 1) { - return _native.Engine.TEXTURE_FORMAT_RGBA32F; - } - else { - throw new RuntimeError(`Unsupported texture format or type: format ${format}, type ${type}.`, ErrorCodes.UnsupportedTextureError); - } - } - _getNativeAlphaMode(mode) { - switch (mode) { - 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: ${mode}.`); - } - } - _getNativeAttribType(type) { - switch (type) { - case buffer_VertexBuffer.BYTE: - return _native.Engine.ATTRIB_TYPE_INT8; - case buffer_VertexBuffer.UNSIGNED_BYTE: - return _native.Engine.ATTRIB_TYPE_UINT8; - case buffer_VertexBuffer.SHORT: - return _native.Engine.ATTRIB_TYPE_INT16; - case buffer_VertexBuffer.UNSIGNED_SHORT: - return _native.Engine.ATTRIB_TYPE_UINT16; - case buffer_VertexBuffer.FLOAT: - return _native.Engine.ATTRIB_TYPE_FLOAT; - default: - throw new Error(`Unsupported attribute type: ${type}.`); - } - } - getFontOffset(font) { - // TODO - const result = { ascent: 0, height: 0, descent: 0 }; - return result; - } - _readTexturePixels(texture, width, height, faceIndex, level, buffer, _flushRenderer, _noDataConversion, x, y) { - var _a, _b, _c, _d; - if (faceIndex !== undefined && faceIndex !== -1) { - throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${faceIndex}.`); - } - return this._engine - .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) - .then((rawBuffer) => { - if (!buffer) { - buffer = new Uint8Array(rawBuffer); - } - return buffer; - }); - } -} -// This must match the protocol version in NativeEngine.cpp -NativeEngine.PROTOCOL_VERSION = 8; -//# sourceMappingURL=nativeEngine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Native/validatedNativeDataStream.js - - -NativeEngine._createNativeDataStream = function () { - if (_native.NativeDataStream.VALIDATION_ENABLED) { - return new ValidatedNativeDataStream(); - } - else { - return new NativeDataStream(); - } -}; -class ValidatedNativeDataStream extends NativeDataStream { - constructor() { - super(); - } - writeUint32(value) { - super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32); - super.writeUint32(value); - } - writeInt32(value) { - super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32); - super.writeInt32(value); - } - writeFloat32(value) { - super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32); - super.writeFloat32(value); - } - writeUint32Array(values) { - super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY); - super.writeUint32Array(values); - } - writeInt32Array(values) { - super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY); - super.writeInt32Array(values); - } - writeFloat32Array(values) { - super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY); - super.writeFloat32Array(values); - } - writeNativeData(handle) { - super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA); - super.writeNativeData(handle); - } - writeBoolean(value) { - super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN); - super.writeBoolean(value); - } -} -//# sourceMappingURL=validatedNativeDataStream.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Native/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuConstants.js -/** @internal */ -// eslint-disable-next-line import/export -var PowerPreference; -(function (PowerPreference) { - PowerPreference["LowPower"] = "low-power"; - PowerPreference["HighPerformance"] = "high-performance"; -})(PowerPreference || (PowerPreference = {})); -/** @internal */ -var FeatureName; -(function (FeatureName) { - FeatureName["DepthClipControl"] = "depth-clip-control"; - FeatureName["Depth32FloatStencil8"] = "depth32float-stencil8"; - FeatureName["TextureCompressionBC"] = "texture-compression-bc"; - FeatureName["TextureCompressionETC2"] = "texture-compression-etc2"; - FeatureName["TextureCompressionASTC"] = "texture-compression-astc"; - FeatureName["TimestampQuery"] = "timestamp-query"; - FeatureName["IndirectFirstInstance"] = "indirect-first-instance"; - FeatureName["ShaderF16"] = "shader-f16"; - FeatureName["RG11B10UFloatRenderable"] = "rg11b10ufloat-renderable"; - FeatureName["BGRA8UnormStorage"] = "bgra8unorm-storage"; - FeatureName["Float32Filterable"] = "float32-filterable"; -})(FeatureName || (FeatureName = {})); -/** @internal */ -var BufferMapState; -(function (BufferMapState) { - BufferMapState["Unmapped"] = "unmapped"; - BufferMapState["Pending"] = "pending"; - BufferMapState["Mapped"] = "mapped"; -})(BufferMapState || (BufferMapState = {})); -/** @internal */ -var BufferUsage; -(function (BufferUsage) { - BufferUsage[BufferUsage["MapRead"] = 1] = "MapRead"; - BufferUsage[BufferUsage["MapWrite"] = 2] = "MapWrite"; - BufferUsage[BufferUsage["CopySrc"] = 4] = "CopySrc"; - BufferUsage[BufferUsage["CopyDst"] = 8] = "CopyDst"; - BufferUsage[BufferUsage["Index"] = 16] = "Index"; - BufferUsage[BufferUsage["Vertex"] = 32] = "Vertex"; - BufferUsage[BufferUsage["Uniform"] = 64] = "Uniform"; - BufferUsage[BufferUsage["Storage"] = 128] = "Storage"; - BufferUsage[BufferUsage["Indirect"] = 256] = "Indirect"; - BufferUsage[BufferUsage["QueryResolve"] = 512] = "QueryResolve"; -})(BufferUsage || (BufferUsage = {})); -/** @internal */ -var MapMode; -(function (MapMode) { - MapMode[MapMode["Read"] = 1] = "Read"; - MapMode[MapMode["Write"] = 2] = "Write"; -})(MapMode || (MapMode = {})); -/** @internal */ -var TextureDimension; -(function (TextureDimension) { - TextureDimension["E1d"] = "1d"; - TextureDimension["E2d"] = "2d"; - TextureDimension["E3d"] = "3d"; -})(TextureDimension || (TextureDimension = {})); -/** @internal */ -var TextureUsage; -(function (TextureUsage) { - TextureUsage[TextureUsage["CopySrc"] = 1] = "CopySrc"; - TextureUsage[TextureUsage["CopyDst"] = 2] = "CopyDst"; - TextureUsage[TextureUsage["TextureBinding"] = 4] = "TextureBinding"; - TextureUsage[TextureUsage["StorageBinding"] = 8] = "StorageBinding"; - TextureUsage[TextureUsage["RenderAttachment"] = 16] = "RenderAttachment"; -})(TextureUsage || (TextureUsage = {})); -/** @internal */ -var TextureViewDimension; -(function (TextureViewDimension) { - TextureViewDimension["E1d"] = "1d"; - TextureViewDimension["E2d"] = "2d"; - TextureViewDimension["E2dArray"] = "2d-array"; - TextureViewDimension["Cube"] = "cube"; - TextureViewDimension["CubeArray"] = "cube-array"; - TextureViewDimension["E3d"] = "3d"; -})(TextureViewDimension || (TextureViewDimension = {})); -/** @internal */ -var TextureAspect; -(function (TextureAspect) { - TextureAspect["All"] = "all"; - TextureAspect["StencilOnly"] = "stencil-only"; - TextureAspect["DepthOnly"] = "depth-only"; -})(TextureAspect || (TextureAspect = {})); -/** - * Comments taken from https://github.com/gfx-rs/wgpu/blob/master/wgpu-types/src/lib.rs - * @internal - */ -var TextureFormat; -(function (TextureFormat) { - // 8-bit formats - TextureFormat["R8Unorm"] = "r8unorm"; - TextureFormat["R8Snorm"] = "r8snorm"; - TextureFormat["R8Uint"] = "r8uint"; - TextureFormat["R8Sint"] = "r8sint"; - // 16-bit formats - TextureFormat["R16Uint"] = "r16uint"; - TextureFormat["R16Sint"] = "r16sint"; - TextureFormat["R16Float"] = "r16float"; - TextureFormat["RG8Unorm"] = "rg8unorm"; - TextureFormat["RG8Snorm"] = "rg8snorm"; - TextureFormat["RG8Uint"] = "rg8uint"; - TextureFormat["RG8Sint"] = "rg8sint"; - // 32-bit formats - TextureFormat["R32Uint"] = "r32uint"; - TextureFormat["R32Sint"] = "r32sint"; - TextureFormat["R32Float"] = "r32float"; - TextureFormat["RG16Uint"] = "rg16uint"; - TextureFormat["RG16Sint"] = "rg16sint"; - TextureFormat["RG16Float"] = "rg16float"; - TextureFormat["RGBA8Unorm"] = "rgba8unorm"; - TextureFormat["RGBA8UnormSRGB"] = "rgba8unorm-srgb"; - TextureFormat["RGBA8Snorm"] = "rgba8snorm"; - TextureFormat["RGBA8Uint"] = "rgba8uint"; - TextureFormat["RGBA8Sint"] = "rgba8sint"; - TextureFormat["BGRA8Unorm"] = "bgra8unorm"; - TextureFormat["BGRA8UnormSRGB"] = "bgra8unorm-srgb"; - // Packed 32-bit formats - TextureFormat["RGB9E5UFloat"] = "rgb9e5ufloat"; - TextureFormat["RGB10A2Unorm"] = "rgb10a2unorm"; - TextureFormat["RG11B10UFloat"] = "rg11b10ufloat"; - // 64-bit formats - TextureFormat["RG32Uint"] = "rg32uint"; - TextureFormat["RG32Sint"] = "rg32sint"; - TextureFormat["RG32Float"] = "rg32float"; - TextureFormat["RGBA16Uint"] = "rgba16uint"; - TextureFormat["RGBA16Sint"] = "rgba16sint"; - TextureFormat["RGBA16Float"] = "rgba16float"; - // 128-bit formats - TextureFormat["RGBA32Uint"] = "rgba32uint"; - TextureFormat["RGBA32Sint"] = "rgba32sint"; - TextureFormat["RGBA32Float"] = "rgba32float"; - // Depth and stencil formats - TextureFormat["Stencil8"] = "stencil8"; - TextureFormat["Depth16Unorm"] = "depth16unorm"; - TextureFormat["Depth24Plus"] = "depth24plus"; - TextureFormat["Depth24PlusStencil8"] = "depth24plus-stencil8"; - TextureFormat["Depth32Float"] = "depth32float"; - // BC compressed formats usable if "texture-compression-bc" is both - // supported by the device/user agent and enabled in requestDevice. - TextureFormat["BC1RGBAUnorm"] = "bc1-rgba-unorm"; - TextureFormat["BC1RGBAUnormSRGB"] = "bc1-rgba-unorm-srgb"; - TextureFormat["BC2RGBAUnorm"] = "bc2-rgba-unorm"; - TextureFormat["BC2RGBAUnormSRGB"] = "bc2-rgba-unorm-srgb"; - TextureFormat["BC3RGBAUnorm"] = "bc3-rgba-unorm"; - TextureFormat["BC3RGBAUnormSRGB"] = "bc3-rgba-unorm-srgb"; - TextureFormat["BC4RUnorm"] = "bc4-r-unorm"; - TextureFormat["BC4RSnorm"] = "bc4-r-snorm"; - TextureFormat["BC5RGUnorm"] = "bc5-rg-unorm"; - TextureFormat["BC5RGSnorm"] = "bc5-rg-snorm"; - TextureFormat["BC6HRGBUFloat"] = "bc6h-rgb-ufloat"; - TextureFormat["BC6HRGBFloat"] = "bc6h-rgb-float"; - TextureFormat["BC7RGBAUnorm"] = "bc7-rgba-unorm"; - TextureFormat["BC7RGBAUnormSRGB"] = "bc7-rgba-unorm-srgb"; - // ETC2 compressed formats usable if "texture-compression-etc2" is both - // supported by the device/user agent and enabled in requestDevice. - TextureFormat["ETC2RGB8Unorm"] = "etc2-rgb8unorm"; - TextureFormat["ETC2RGB8UnormSRGB"] = "etc2-rgb8unorm-srgb"; - TextureFormat["ETC2RGB8A1Unorm"] = "etc2-rgb8a1unorm"; - TextureFormat["ETC2RGB8A1UnormSRGB"] = "etc2-rgb8a1unorm-srgb"; - TextureFormat["ETC2RGBA8Unorm"] = "etc2-rgba8unorm"; - TextureFormat["ETC2RGBA8UnormSRGB"] = "etc2-rgba8unorm-srgb"; - TextureFormat["EACR11Unorm"] = "eac-r11unorm"; - TextureFormat["EACR11Snorm"] = "eac-r11snorm"; - TextureFormat["EACRG11Unorm"] = "eac-rg11unorm"; - TextureFormat["EACRG11Snorm"] = "eac-rg11snorm"; - // ASTC compressed formats usable if "texture-compression-astc" is both - // supported by the device/user agent and enabled in requestDevice. - TextureFormat["ASTC4x4Unorm"] = "astc-4x4-unorm"; - TextureFormat["ASTC4x4UnormSRGB"] = "astc-4x4-unorm-srgb"; - TextureFormat["ASTC5x4Unorm"] = "astc-5x4-unorm"; - TextureFormat["ASTC5x4UnormSRGB"] = "astc-5x4-unorm-srgb"; - TextureFormat["ASTC5x5Unorm"] = "astc-5x5-unorm"; - TextureFormat["ASTC5x5UnormSRGB"] = "astc-5x5-unorm-srgb"; - TextureFormat["ASTC6x5Unorm"] = "astc-6x5-unorm"; - TextureFormat["ASTC6x5UnormSRGB"] = "astc-6x5-unorm-srgb"; - TextureFormat["ASTC6x6Unorm"] = "astc-6x6-unorm"; - TextureFormat["ASTC6x6UnormSRGB"] = "astc-6x6-unorm-srgb"; - TextureFormat["ASTC8x5Unorm"] = "astc-8x5-unorm"; - TextureFormat["ASTC8x5UnormSRGB"] = "astc-8x5-unorm-srgb"; - TextureFormat["ASTC8x6Unorm"] = "astc-8x6-unorm"; - TextureFormat["ASTC8x6UnormSRGB"] = "astc-8x6-unorm-srgb"; - TextureFormat["ASTC8x8Unorm"] = "astc-8x8-unorm"; - TextureFormat["ASTC8x8UnormSRGB"] = "astc-8x8-unorm-srgb"; - TextureFormat["ASTC10x5Unorm"] = "astc-10x5-unorm"; - TextureFormat["ASTC10x5UnormSRGB"] = "astc-10x5-unorm-srgb"; - TextureFormat["ASTC10x6Unorm"] = "astc-10x6-unorm"; - TextureFormat["ASTC10x6UnormSRGB"] = "astc-10x6-unorm-srgb"; - TextureFormat["ASTC10x8Unorm"] = "astc-10x8-unorm"; - TextureFormat["ASTC10x8UnormSRGB"] = "astc-10x8-unorm-srgb"; - TextureFormat["ASTC10x10Unorm"] = "astc-10x10-unorm"; - TextureFormat["ASTC10x10UnormSRGB"] = "astc-10x10-unorm-srgb"; - TextureFormat["ASTC12x10Unorm"] = "astc-12x10-unorm"; - TextureFormat["ASTC12x10UnormSRGB"] = "astc-12x10-unorm-srgb"; - TextureFormat["ASTC12x12Unorm"] = "astc-12x12-unorm"; - TextureFormat["ASTC12x12UnormSRGB"] = "astc-12x12-unorm-srgb"; - // "depth24unorm-stencil8" feature - TextureFormat["Depth24UnormStencil8"] = "depth24unorm-stencil8"; - // "depth32float-stencil8" feature - TextureFormat["Depth32FloatStencil8"] = "depth32float-stencil8"; -})(TextureFormat || (TextureFormat = {})); -/** @internal */ -var AddressMode; -(function (AddressMode) { - AddressMode["ClampToEdge"] = "clamp-to-edge"; - AddressMode["Repeat"] = "repeat"; - AddressMode["MirrorRepeat"] = "mirror-repeat"; -})(AddressMode || (AddressMode = {})); -/** @internal */ -var FilterMode; -(function (FilterMode) { - FilterMode["Nearest"] = "nearest"; - FilterMode["Linear"] = "linear"; -})(FilterMode || (FilterMode = {})); -/** @internal */ -var MipmapFilterMode; -(function (MipmapFilterMode) { - MipmapFilterMode["Nearest"] = "nearest"; - MipmapFilterMode["Linear"] = "linear"; -})(MipmapFilterMode || (MipmapFilterMode = {})); -/** @internal */ -var CompareFunction; -(function (CompareFunction) { - CompareFunction["Never"] = "never"; - CompareFunction["Less"] = "less"; - CompareFunction["Equal"] = "equal"; - CompareFunction["LessEqual"] = "less-equal"; - CompareFunction["Greater"] = "greater"; - CompareFunction["NotEqual"] = "not-equal"; - CompareFunction["GreaterEqual"] = "greater-equal"; - CompareFunction["Always"] = "always"; -})(CompareFunction || (CompareFunction = {})); -/** @internal */ -var ShaderStage; -(function (ShaderStage) { - ShaderStage[ShaderStage["Vertex"] = 1] = "Vertex"; - ShaderStage[ShaderStage["Fragment"] = 2] = "Fragment"; - ShaderStage[ShaderStage["Compute"] = 4] = "Compute"; -})(ShaderStage || (ShaderStage = {})); -/** @internal */ -var BufferBindingType; -(function (BufferBindingType) { - BufferBindingType["Uniform"] = "uniform"; - BufferBindingType["Storage"] = "storage"; - BufferBindingType["ReadOnlyStorage"] = "read-only-storage"; -})(BufferBindingType || (BufferBindingType = {})); -/** @internal */ -var SamplerBindingType; -(function (SamplerBindingType) { - SamplerBindingType["Filtering"] = "filtering"; - SamplerBindingType["NonFiltering"] = "non-filtering"; - SamplerBindingType["Comparison"] = "comparison"; -})(SamplerBindingType || (SamplerBindingType = {})); -/** @internal */ -var TextureSampleType; -(function (TextureSampleType) { - TextureSampleType["Float"] = "float"; - TextureSampleType["UnfilterableFloat"] = "unfilterable-float"; - TextureSampleType["Depth"] = "depth"; - TextureSampleType["Sint"] = "sint"; - TextureSampleType["Uint"] = "uint"; -})(TextureSampleType || (TextureSampleType = {})); -/** @internal */ -var StorageTextureAccess; -(function (StorageTextureAccess) { - StorageTextureAccess["WriteOnly"] = "write-only"; -})(StorageTextureAccess || (StorageTextureAccess = {})); -/** @internal */ -var CompilationMessageType; -(function (CompilationMessageType) { - CompilationMessageType["Error"] = "error"; - CompilationMessageType["Warning"] = "warning"; - CompilationMessageType["Info"] = "info"; -})(CompilationMessageType || (CompilationMessageType = {})); -/** @internal */ -var PipelineErrorReason; -(function (PipelineErrorReason) { - PipelineErrorReason["Validation"] = "validation"; - PipelineErrorReason["Internal"] = "internal"; -})(PipelineErrorReason || (PipelineErrorReason = {})); -/** @internal */ -var AutoLayoutMode; -(function (AutoLayoutMode) { - AutoLayoutMode["Auto"] = "auto"; -})(AutoLayoutMode || (AutoLayoutMode = {})); -/** @internal */ -var PrimitiveTopology; -(function (PrimitiveTopology) { - PrimitiveTopology["PointList"] = "point-list"; - PrimitiveTopology["LineList"] = "line-list"; - PrimitiveTopology["LineStrip"] = "line-strip"; - PrimitiveTopology["TriangleList"] = "triangle-list"; - PrimitiveTopology["TriangleStrip"] = "triangle-strip"; -})(PrimitiveTopology || (PrimitiveTopology = {})); -/** @internal */ -var FrontFace; -(function (FrontFace) { - FrontFace["CCW"] = "ccw"; - FrontFace["CW"] = "cw"; -})(FrontFace || (FrontFace = {})); -/** @internal */ -var CullMode; -(function (CullMode) { - CullMode["None"] = "none"; - CullMode["Front"] = "front"; - CullMode["Back"] = "back"; -})(CullMode || (CullMode = {})); -/** @internal */ -var ColorWriteFlags; -(function (ColorWriteFlags) { - ColorWriteFlags[ColorWriteFlags["Red"] = 1] = "Red"; - ColorWriteFlags[ColorWriteFlags["Green"] = 2] = "Green"; - ColorWriteFlags[ColorWriteFlags["Blue"] = 4] = "Blue"; - ColorWriteFlags[ColorWriteFlags["Alpha"] = 8] = "Alpha"; - ColorWriteFlags[ColorWriteFlags["All"] = 15] = "All"; -})(ColorWriteFlags || (ColorWriteFlags = {})); -/** @internal */ -var BlendFactor; -(function (BlendFactor) { - BlendFactor["Zero"] = "zero"; - BlendFactor["One"] = "one"; - BlendFactor["Src"] = "src"; - BlendFactor["OneMinusSrc"] = "one-minus-src"; - BlendFactor["SrcAlpha"] = "src-alpha"; - BlendFactor["OneMinusSrcAlpha"] = "one-minus-src-alpha"; - BlendFactor["Dst"] = "dst"; - BlendFactor["OneMinusDst"] = "one-minus-dst"; - BlendFactor["DstAlpha"] = "dst-alpha"; - BlendFactor["OneMinusDstAlpha"] = "one-minus-dst-alpha"; - BlendFactor["SrcAlphaSaturated"] = "src-alpha-saturated"; - BlendFactor["Constant"] = "constant"; - BlendFactor["OneMinusConstant"] = "one-minus-constant"; -})(BlendFactor || (BlendFactor = {})); -/** @internal */ -var BlendOperation; -(function (BlendOperation) { - BlendOperation["Add"] = "add"; - BlendOperation["Subtract"] = "subtract"; - BlendOperation["ReverseSubtract"] = "reverse-subtract"; - BlendOperation["Min"] = "min"; - BlendOperation["Max"] = "max"; -})(BlendOperation || (BlendOperation = {})); -/** @internal */ -var StencilOperation; -(function (StencilOperation) { - StencilOperation["Keep"] = "keep"; - StencilOperation["Zero"] = "zero"; - StencilOperation["Replace"] = "replace"; - StencilOperation["Invert"] = "invert"; - StencilOperation["IncrementClamp"] = "increment-clamp"; - StencilOperation["DecrementClamp"] = "decrement-clamp"; - StencilOperation["IncrementWrap"] = "increment-wrap"; - StencilOperation["DecrementWrap"] = "decrement-wrap"; -})(StencilOperation || (StencilOperation = {})); -/** @internal */ -var IndexFormat; -(function (IndexFormat) { - IndexFormat["Uint16"] = "uint16"; - IndexFormat["Uint32"] = "uint32"; -})(IndexFormat || (IndexFormat = {})); -/** @internal */ -var VertexFormat; -(function (VertexFormat) { - VertexFormat["Uint8x2"] = "uint8x2"; - VertexFormat["Uint8x4"] = "uint8x4"; - VertexFormat["Sint8x2"] = "sint8x2"; - VertexFormat["Sint8x4"] = "sint8x4"; - VertexFormat["Unorm8x2"] = "unorm8x2"; - VertexFormat["Unorm8x4"] = "unorm8x4"; - VertexFormat["Snorm8x2"] = "snorm8x2"; - VertexFormat["Snorm8x4"] = "snorm8x4"; - VertexFormat["Uint16x2"] = "uint16x2"; - VertexFormat["Uint16x4"] = "uint16x4"; - VertexFormat["Sint16x2"] = "sint16x2"; - VertexFormat["Sint16x4"] = "sint16x4"; - VertexFormat["Unorm16x2"] = "unorm16x2"; - VertexFormat["Unorm16x4"] = "unorm16x4"; - VertexFormat["Snorm16x2"] = "snorm16x2"; - VertexFormat["Snorm16x4"] = "snorm16x4"; - VertexFormat["Float16x2"] = "float16x2"; - VertexFormat["Float16x4"] = "float16x4"; - VertexFormat["Float32"] = "float32"; - VertexFormat["Float32x2"] = "float32x2"; - VertexFormat["Float32x3"] = "float32x3"; - VertexFormat["Float32x4"] = "float32x4"; - VertexFormat["Uint32"] = "uint32"; - VertexFormat["Uint32x2"] = "uint32x2"; - VertexFormat["Uint32x3"] = "uint32x3"; - VertexFormat["Uint32x4"] = "uint32x4"; - VertexFormat["Sint32"] = "sint32"; - VertexFormat["Sint32x2"] = "sint32x2"; - VertexFormat["Sint32x3"] = "sint32x3"; - VertexFormat["Sint32x4"] = "sint32x4"; -})(VertexFormat || (VertexFormat = {})); -/** @internal */ -var InputStepMode; -(function (InputStepMode) { - InputStepMode["Vertex"] = "vertex"; - InputStepMode["Instance"] = "instance"; -})(InputStepMode || (InputStepMode = {})); -/** @internal */ -var ComputePassTimestampLocation; -(function (ComputePassTimestampLocation) { - ComputePassTimestampLocation["Beginning"] = "beginning"; - ComputePassTimestampLocation["End"] = "end"; -})(ComputePassTimestampLocation || (ComputePassTimestampLocation = {})); -/** @internal */ -var RenderPassTimestampLocation; -(function (RenderPassTimestampLocation) { - RenderPassTimestampLocation["Beginning"] = "beginning"; - RenderPassTimestampLocation["End"] = "end"; -})(RenderPassTimestampLocation || (RenderPassTimestampLocation = {})); -/** @internal */ -var LoadOp; -(function (LoadOp) { - LoadOp["Load"] = "load"; - LoadOp["Clear"] = "clear"; -})(LoadOp || (LoadOp = {})); -/** @internal */ -var StoreOp; -(function (StoreOp) { - StoreOp["Store"] = "store"; - StoreOp["Discard"] = "discard"; -})(StoreOp || (StoreOp = {})); -/** @internal */ -var QueryType; -(function (QueryType) { - QueryType["Occlusion"] = "occlusion"; - QueryType["Timestamp"] = "timestamp"; -})(QueryType || (QueryType = {})); -/** @internal */ -var CanvasAlphaMode; -(function (CanvasAlphaMode) { - CanvasAlphaMode["Opaque"] = "opaque"; - CanvasAlphaMode["Premultiplied"] = "premultiplied"; -})(CanvasAlphaMode || (CanvasAlphaMode = {})); -/** @internal */ -var DeviceLostReason; -(function (DeviceLostReason) { - DeviceLostReason["Unknown"] = "unknown"; - DeviceLostReason["Destroyed"] = "destroyed"; -})(DeviceLostReason || (DeviceLostReason = {})); -/** @internal */ -var ErrorFilter; -(function (ErrorFilter) { - ErrorFilter["Validation"] = "validation"; - ErrorFilter["OutOfMemory"] = "out-of-memory"; - ErrorFilter["Internal"] = "internal"; -})(ErrorFilter || (ErrorFilter = {})); -//# sourceMappingURL=webgpuConstants.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessor.js - - -/** @internal */ -class WebGPUShaderProcessor { - constructor() { - this.shaderLanguage = ShaderLanguage.GLSL; - } - _addUniformToLeftOverUBO(name, uniformType, preProcessors) { - let length = 0; - [name, uniformType, length] = this._getArraySize(name, uniformType, preProcessors); - for (let i = 0; i < this._webgpuProcessingContext.leftOverUniforms.length; i++) { - if (this._webgpuProcessingContext.leftOverUniforms[i].name === name) { - return; - } - } - this._webgpuProcessingContext.leftOverUniforms.push({ - name, - type: uniformType, - length, - }); - } - _buildLeftOverUBO() { - if (!this._webgpuProcessingContext.leftOverUniforms.length) { - return ""; - } - const name = WebGPUShaderProcessor.LeftOvertUBOName; - let availableUBO = this._webgpuProcessingContext.availableBuffers[name]; - if (!availableUBO) { - availableUBO = { - binding: this._webgpuProcessingContext.getNextFreeUBOBinding(), - }; - this._webgpuProcessingContext.availableBuffers[name] = availableUBO; - this._addBufferBindingDescription(name, availableUBO, BufferBindingType.Uniform, true); - this._addBufferBindingDescription(name, availableUBO, BufferBindingType.Uniform, false); - } - return this._generateLeftOverUBOCode(name, availableUBO); - } - _collectBindingNames() { - // collect all the binding names for faster processing in WebGPUCacheBindGroup - for (let i = 0; i < this._webgpuProcessingContext.bindGroupLayoutEntries.length; i++) { - const setDefinition = this._webgpuProcessingContext.bindGroupLayoutEntries[i]; - if (setDefinition === undefined) { - this._webgpuProcessingContext.bindGroupLayoutEntries[i] = []; - continue; - } - for (let j = 0; j < setDefinition.length; j++) { - const entry = this._webgpuProcessingContext.bindGroupLayoutEntries[i][j]; - const name = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].name; - const nameInArrayOfTexture = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].nameInArrayOfTexture; - if (entry) { - if (entry.texture || entry.externalTexture || entry.storageTexture) { - this._webgpuProcessingContext.textureNames.push(nameInArrayOfTexture); - } - else if (entry.sampler) { - this._webgpuProcessingContext.samplerNames.push(name); - } - else if (entry.buffer) { - this._webgpuProcessingContext.bufferNames.push(name); - } - } - } - } - } - _preCreateBindGroupEntries() { - const bindGroupEntries = this._webgpuProcessingContext.bindGroupEntries; - for (let i = 0; i < this._webgpuProcessingContext.bindGroupLayoutEntries.length; i++) { - const setDefinition = this._webgpuProcessingContext.bindGroupLayoutEntries[i]; - const entries = []; - for (let j = 0; j < setDefinition.length; j++) { - const entry = this._webgpuProcessingContext.bindGroupLayoutEntries[i][j]; - if (entry.sampler || entry.texture || entry.storageTexture || entry.externalTexture) { - entries.push({ - binding: entry.binding, - resource: undefined, - }); - } - else if (entry.buffer) { - entries.push({ - binding: entry.binding, - resource: { - buffer: undefined, - offset: 0, - size: 0, - }, - }); - } - } - bindGroupEntries[i] = entries; - } - } - _addTextureBindingDescription(name, textureInfo, textureIndex, dimension, format, isVertex) { - // eslint-disable-next-line prefer-const - let { groupIndex, bindingIndex } = textureInfo.textures[textureIndex]; - if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) { - this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = []; - this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = []; - } - if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) { - let len; - if (dimension === null) { - len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({ - binding: bindingIndex, - visibility: 0, - externalTexture: {}, - }); - } - else if (format) { - len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({ - binding: bindingIndex, - visibility: 0, - storageTexture: { - access: StorageTextureAccess.WriteOnly, - format, - viewDimension: dimension, - }, - }); - } - else { - len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({ - binding: bindingIndex, - visibility: 0, - texture: { - sampleType: textureInfo.sampleType, - viewDimension: dimension, - multisampled: false, - }, - }); - } - const textureName = textureInfo.isTextureArray ? name + textureIndex : name; - this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1, nameInArrayOfTexture: textureName }; - } - bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index; - if (isVertex) { - this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= ShaderStage.Vertex; - } - else { - this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= ShaderStage.Fragment; - } - } - _addSamplerBindingDescription(name, samplerInfo, isVertex) { - // eslint-disable-next-line prefer-const - let { groupIndex, bindingIndex } = samplerInfo.binding; - if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) { - this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = []; - this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = []; - } - if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) { - const len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({ - binding: bindingIndex, - visibility: 0, - sampler: { - type: samplerInfo.type, - }, - }); - this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1 }; - } - bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index; - if (isVertex) { - this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= ShaderStage.Vertex; - } - else { - this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= ShaderStage.Fragment; - } - } - _addBufferBindingDescription(name, uniformBufferInfo, bufferType, isVertex) { - // eslint-disable-next-line prefer-const - let { groupIndex, bindingIndex } = uniformBufferInfo.binding; - if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) { - this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = []; - this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = []; - } - if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) { - const len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({ - binding: bindingIndex, - visibility: 0, - buffer: { - type: bufferType, - }, - }); - this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1 }; - } - bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index; - if (isVertex) { - this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= ShaderStage.Vertex; - } - else { - this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= ShaderStage.Fragment; - } - } - _injectStartingAndEndingCode(code, mainFuncDecl, startingCode, endingCode) { - let idx = code.indexOf(mainFuncDecl); - if (idx < 0) { - console.error(`No "main" function found in shader code! Processing aborted.`); - return code; - } - if (startingCode) { - // eslint-disable-next-line no-empty - while (idx++ < code.length && code.charAt(idx) != "{") { } - if (idx < code.length) { - const part1 = code.substring(0, idx + 1); - const part2 = code.substring(idx + 1); - code = part1 + startingCode + part2; - } - } - if (endingCode) { - const lastClosingCurly = code.lastIndexOf("}"); - code = code.substring(0, lastClosingCurly); - code += endingCode + "\n}"; - } - return code; - } -} -WebGPUShaderProcessor.AutoSamplerSuffix = "Sampler"; -WebGPUShaderProcessor.LeftOvertUBOName = "LeftOver"; -WebGPUShaderProcessor.InternalsUBOName = "Internals"; -WebGPUShaderProcessor.UniformSizes = { - // GLSL types - bool: 1, - int: 1, - float: 1, - vec2: 2, - ivec2: 2, - uvec2: 2, - vec3: 3, - ivec3: 3, - uvec3: 3, - vec4: 4, - ivec4: 4, - uvec4: 4, - mat2: 4, - mat3: 12, - mat4: 16, - // WGSL types - i32: 1, - u32: 1, - f32: 1, - mat2x2: 4, - mat3x3: 12, - mat4x4: 16, -}; -// eslint-disable-next-line @typescript-eslint/naming-convention -WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType = { - sampler2D: "sampler2D", - sampler2DArray: "sampler2DArray", - sampler2DShadow: "sampler2DShadow", - sampler2DArrayShadow: "sampler2DArrayShadow", - samplerCube: "samplerCube", - sampler3D: "sampler3D", -}; -// eslint-disable-next-line @typescript-eslint/naming-convention -WebGPUShaderProcessor._TextureTypeByWebGLSamplerType = { - sampler2D: "texture2D", - sampler2DArray: "texture2DArray", - sampler2DShadow: "texture2D", - sampler2DArrayShadow: "texture2DArray", - samplerCube: "textureCube", - samplerCubeArray: "textureCubeArray", - sampler3D: "texture3D", -}; -// eslint-disable-next-line @typescript-eslint/naming-convention -WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType = { - textureCube: TextureViewDimension.Cube, - textureCubeArray: TextureViewDimension.CubeArray, - texture2D: TextureViewDimension.E2d, - texture2DArray: TextureViewDimension.E2dArray, - texture3D: TextureViewDimension.E3d, -}; -// if the webgl sampler type is not listed in this array, "sampler" is taken by default -// eslint-disable-next-line @typescript-eslint/naming-convention -WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType = { - sampler2DShadow: "samplerShadow", - sampler2DArrayShadow: "samplerShadow", -}; -// eslint-disable-next-line @typescript-eslint/naming-convention -WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType = { - samplerShadow: true, - samplerArrayShadow: true, - sampler: false, -}; -//# sourceMappingURL=webgpuShaderProcessor.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuPipelineContext.js - - -/** @internal */ -class WebGPUPipelineContext { - get isAsync() { - return false; - } - get isReady() { - if (this.stages) { - return true; - } - return false; - } - constructor(shaderProcessingContext, engine) { - // The field is indexed by textureState. See @WebGPUMaterialContext.textureState for more information. - this.bindGroupLayouts = {}; - this._name = "unnamed"; - this.shaderProcessingContext = shaderProcessingContext; - this._leftOverUniformsByName = {}; - this.engine = engine; - } - _handlesSpectorRebuildCallback() { - // Nothing to do yet for spector. - } - _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) { - const engine = this.engine; - // Prevent Memory Leak by reducing the number of string, refer to the string instead of copy. - effect._fragmentSourceCode = ""; - effect._vertexSourceCode = ""; - // this._fragmentSourceCodeOverride = ""; - // this._vertexSourceCodeOverride = ""; - const foundSamplers = this.shaderProcessingContext.availableTextures; - let index; - for (index = 0; index < samplerList.length; index++) { - const name = samplerList[index]; - const sampler = foundSamplers[samplerList[index]]; - if (sampler == null || sampler == undefined) { - samplerList.splice(index, 1); - index--; - } - else { - samplers[name] = index; - } - } - for (const attr of engine.getAttributes(this, attributesNames)) { - attributes.push(attr); - } - // Build the uniform layout for the left over uniforms. - this.buildUniformLayout(); - const attributeNamesFromEffect = []; - const attributeLocationsFromEffect = []; - for (index = 0; index < attributesNames.length; index++) { - const location = attributes[index]; - if (location >= 0) { - attributeNamesFromEffect.push(attributesNames[index]); - attributeLocationsFromEffect.push(location); - } - } - this.shaderProcessingContext.attributeNamesFromEffect = attributeNamesFromEffect; - this.shaderProcessingContext.attributeLocationsFromEffect = attributeLocationsFromEffect; - } - /** @internal */ - /** - * Build the uniform buffer used in the material. - */ - buildUniformLayout() { - if (!this.shaderProcessingContext.leftOverUniforms.length) { - return; - } - this.uniformBuffer = new UniformBuffer(this.engine, undefined, undefined, "leftOver-" + this._name); - for (const leftOverUniform of this.shaderProcessingContext.leftOverUniforms) { - const type = leftOverUniform.type.replace(/^(.*?)(<.*>)?$/, "$1"); - const size = WebGPUShaderProcessor.UniformSizes[type]; - this.uniformBuffer.addUniform(leftOverUniform.name, size, leftOverUniform.length); - this._leftOverUniformsByName[leftOverUniform.name] = leftOverUniform.type; - } - this.uniformBuffer.create(); - } - /** - * Release all associated resources. - **/ - dispose() { - if (this.uniformBuffer) { - this.uniformBuffer.dispose(); - } - } - /** - * Sets an integer value on a uniform variable. - * @param uniformName Name of the variable. - * @param value Value to be set. - */ - setInt(uniformName, value) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateInt(uniformName, value); - } - /** - * Sets an int2 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int2. - * @param y Second int in int2. - */ - setInt2(uniformName, x, y) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateInt2(uniformName, x, y); - } - /** - * Sets an int3 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int3. - * @param y Second int in int3. - * @param z Third int in int3. - */ - setInt3(uniformName, x, y, z) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateInt3(uniformName, x, y, z); - } - /** - * Sets an int4 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First int in int4. - * @param y Second int in int4. - * @param z Third int in int4. - * @param w Fourth int in int4. - */ - setInt4(uniformName, x, y, z, w) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateInt4(uniformName, x, y, z, w); - } - /** - * Sets an int array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray(uniformName, array) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateIntArray(uniformName, array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray2(uniformName, array) { - this.setIntArray(uniformName, array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray3(uniformName, array) { - this.setIntArray(uniformName, array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setIntArray4(uniformName, array) { - this.setIntArray(uniformName, array); - } - /** - * Sets an unsigned integer value on a uniform variable. - * @param uniformName Name of the variable. - * @param value Value to be set. - */ - setUInt(uniformName, value) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateUInt(uniformName, value); - } - /** - * Sets an unsigned int2 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint2. - * @param y Second unsigned int in uint2. - */ - setUInt2(uniformName, x, y) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateUInt2(uniformName, x, y); - } - /** - * Sets an unsigned int3 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint3. - * @param y Second unsigned int in uint3. - * @param z Third unsigned int in uint3. - */ - setUInt3(uniformName, x, y, z) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateUInt3(uniformName, x, y, z); - } - /** - * Sets an unsigned int4 value on a uniform variable. - * @param uniformName Name of the variable. - * @param x First unsigned int in uint4. - * @param y Second unsigned int in uint4. - * @param z Third unsigned int in uint4. - * @param w Fourth unsigned int in uint4. - */ - setUInt4(uniformName, x, y, z, w) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateUInt4(uniformName, x, y, z, w); - } - /** - * Sets an unsigned int array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray(uniformName, array) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateUIntArray(uniformName, array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray2(uniformName, array) { - this.setUIntArray(uniformName, array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray3(uniformName, array) { - this.setUIntArray(uniformName, array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setUIntArray4(uniformName, array) { - this.setUIntArray(uniformName, array); - } - /** - * Sets an array on a uniform variable. - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setArray(uniformName, array) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateArray(uniformName, array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setArray2(uniformName, array) { - this.setArray(uniformName, array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - * @returns this effect. - */ - setArray3(uniformName, array) { - this.setArray(uniformName, array); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param array array to be set. - */ - setArray4(uniformName, array) { - this.setArray(uniformName, array); - } - /** - * Sets matrices on a uniform variable. - * @param uniformName Name of the variable. - * @param matrices matrices to be set. - */ - setMatrices(uniformName, matrices) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateMatrices(uniformName, matrices); - } - /** - * Sets matrix on a uniform variable. - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - */ - setMatrix(uniformName, matrix) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateMatrix(uniformName, matrix); - } - /** - * 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) - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - */ - setMatrix3x3(uniformName, matrix) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateMatrix3x3(uniformName, matrix); - } - /** - * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix) - * @param uniformName Name of the variable. - * @param matrix matrix to be set. - */ - setMatrix2x2(uniformName, matrix) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateMatrix2x2(uniformName, matrix); - } - /** - * Sets a float on a uniform variable. - * @param uniformName Name of the variable. - * @param value value to be set. - * @returns this effect. - */ - setFloat(uniformName, value) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateFloat(uniformName, value); - } - /** - * Sets a Vector2 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector2 vector2 to be set. - */ - setVector2(uniformName, vector2) { - this.setFloat2(uniformName, vector2.x, vector2.y); - } - /** - * Sets a float2 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float2. - * @param y Second float in float2. - */ - setFloat2(uniformName, x, y) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateFloat2(uniformName, x, y); - } - /** - * Sets a Vector3 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector3 Value to be set. - */ - setVector3(uniformName, vector3) { - this.setFloat3(uniformName, vector3.x, vector3.y, vector3.z); - } - /** - * Sets a float3 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float3. - * @param y Second float in float3. - * @param z Third float in float3. - */ - setFloat3(uniformName, x, y, z) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateFloat3(uniformName, x, y, z); - } - /** - * Sets a Vector4 on a uniform variable. - * @param uniformName Name of the variable. - * @param vector4 Value to be set. - */ - setVector4(uniformName, vector4) { - this.setFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w); - } - /** - * Sets a Quaternion on a uniform variable. - * @param uniformName Name of the variable. - * @param quaternion Value to be set. - */ - setQuaternion(uniformName, quaternion) { - this.setFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w); - } - /** - * Sets a float4 on a uniform variable. - * @param uniformName Name of the variable. - * @param x First float in float4. - * @param y Second float in float4. - * @param z Third float in float4. - * @param w Fourth float in float4. - * @returns this effect. - */ - setFloat4(uniformName, x, y, z, w) { - if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) { - return; - } - this.uniformBuffer.updateFloat4(uniformName, x, y, z, w); - } - /** - * Sets a Color3 on a uniform variable. - * @param uniformName Name of the variable. - * @param color3 Value to be set. - */ - setColor3(uniformName, color3) { - this.setFloat3(uniformName, color3.r, color3.g, color3.b); - } - /** - * Sets a Color4 on a uniform variable. - * @param uniformName Name of the variable. - * @param color3 Value to be set. - * @param alpha Alpha value to be set. - */ - setColor4(uniformName, color3, alpha) { - this.setFloat4(uniformName, color3.r, color3.g, color3.b, alpha); - } - /** - * Sets a Color4 on a uniform variable - * @param uniformName defines the name of the variable - * @param color4 defines the value to be set - */ - setDirectColor4(uniformName, color4) { - this.setFloat4(uniformName, color4.r, color4.g, color4.b, color4.a); - } - _getVertexShaderCode() { - var _a; - return (_a = this.sources) === null || _a === void 0 ? void 0 : _a.vertex; - } - _getFragmentShaderCode() { - var _a; - return (_a = this.sources) === null || _a === void 0 ? void 0 : _a.fragment; - } -} -//# sourceMappingURL=webgpuPipelineContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessingContext.js -const _maxGroups = 4; -const _maxBindingsPerGroup = 1 << 16; -// all types not listed are assumed to consume 1 location -const _typeToLocationSize = { - // GLSL types - mat2: 2, - mat3: 3, - mat4: 4, - // WGSL types - mat2x2: 2, - mat3x3: 3, - mat4x4: 4, -}; -/** - * @internal - */ -class WebGPUShaderProcessingContext { - static get KnownUBOs() { - return WebGPUShaderProcessingContext._SimplifiedKnownBindings ? WebGPUShaderProcessingContext._SimplifiedKnownUBOs : WebGPUShaderProcessingContext._KnownUBOs; - } - constructor(shaderLanguage) { - this.shaderLanguage = shaderLanguage; - 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 knownUBOs = WebGPUShaderProcessingContext.KnownUBOs; - const groups = []; - for (const name in knownUBOs) { - const binding = knownUBOs[name].binding; - if (binding.groupIndex === -1) { - continue; - } - if (groups[binding.groupIndex] === undefined) { - groups[binding.groupIndex] = binding.bindingIndex; - } - else { - groups[binding.groupIndex] = Math.max(groups[binding.groupIndex], binding.bindingIndex); - } - } - this.freeGroupIndex = groups.length - 1; - if (this.freeGroupIndex === 0) { - this.freeGroupIndex++; - this.freeBindingIndex = 0; - } - else { - this.freeBindingIndex = groups[groups.length - 1] + 1; - } - } - getAttributeNextLocation(dataType, arrayLength = 0) { - var _a; - const index = this._attributeNextLocation; - this._attributeNextLocation += ((_a = _typeToLocationSize[dataType]) !== null && _a !== void 0 ? _a : 1) * (arrayLength || 1); - return index; - } - getVaryingNextLocation(dataType, arrayLength = 0) { - var _a; - const index = this._varyingNextLocation; - this._varyingNextLocation += ((_a = _typeToLocationSize[dataType]) !== null && _a !== void 0 ? _a : 1) * (arrayLength || 1); - return index; - } - getNextFreeUBOBinding() { - return this._getNextFreeBinding(1); - } - _getNextFreeBinding(bindingCount) { - if (this.freeBindingIndex > _maxBindingsPerGroup - bindingCount) { - this.freeGroupIndex++; - this.freeBindingIndex = 0; - } - if (this.freeGroupIndex === _maxGroups) { - throw "Too many textures or UBOs have been declared and it is not supported in WebGPU."; - } - const returnValue = { - groupIndex: this.freeGroupIndex, - bindingIndex: this.freeBindingIndex, - }; - this.freeBindingIndex += bindingCount; - return returnValue; - } -} -/** @internal */ -WebGPUShaderProcessingContext._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 -// if false, see _KnownUBOs for the known groups/bindings used -WebGPUShaderProcessingContext._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 } }, -}; -WebGPUShaderProcessingContext._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 } }, -}; -//# sourceMappingURL=webgpuShaderProcessingContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessorsGLSL.js - - - - - -/** @internal */ -class WebGPUShaderProcessorGLSL extends WebGPUShaderProcessor { - constructor() { - super(...arguments); - this._missingVaryings = []; - this._textureArrayProcessing = []; - this._vertexIsGLES3 = false; - this._fragmentIsGLES3 = false; - this.shaderLanguage = ShaderLanguage.GLSL; - this.parseGLES3 = true; - } - _getArraySize(name, type, preProcessors) { - let length = 0; - const startArray = name.indexOf("["); - const endArray = name.indexOf("]"); - if (startArray > 0 && endArray > 0) { - const lengthInString = name.substring(startArray + 1, endArray); - length = +lengthInString; - if (isNaN(length)) { - length = +preProcessors[lengthInString.trim()]; - } - name = name.substr(0, startArray); - } - return [name, type, length]; - } - initializeShaders(processingContext) { - this._webgpuProcessingContext = processingContext; - this._missingVaryings.length = 0; - this._textureArrayProcessing.length = 0; - this.attributeKeywordName = undefined; - this.varyingVertexKeywordName = undefined; - this.varyingFragmentKeywordName = undefined; - } - preProcessShaderCode(code, isFragment) { - const ubDeclaration = `// Internals UBO\nuniform ${WebGPUShaderProcessor.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`; - const alreadyInjected = code.indexOf("// Internals UBO") !== -1; - if (isFragment) { - this._fragmentIsGLES3 = code.indexOf("#version 3") !== -1; - if (this._fragmentIsGLES3) { - this.varyingFragmentKeywordName = "in"; - } - return alreadyInjected ? code : ubDeclaration + "##INJECTCODE##\n" + code; - } - this._vertexIsGLES3 = code.indexOf("#version 3") !== -1; - if (this._vertexIsGLES3) { - this.attributeKeywordName = "in"; - this.varyingVertexKeywordName = "out"; - } - return alreadyInjected ? code : ubDeclaration + code; - } - varyingCheck(varying, isFragment) { - const outRegex = /(flat\s)?\s*\bout\b/; - const inRegex = /(flat\s)?\s*\bin\b/; - const varyingRegex = /(flat\s)?\s*\bvarying\b/; - const regex = isFragment && this._fragmentIsGLES3 ? inRegex : !isFragment && this._vertexIsGLES3 ? outRegex : varyingRegex; - return regex.test(varying); - } - varyingProcessor(varying, isFragment, preProcessors) { - var _a; - this._preProcessors = preProcessors; - const outRegex = /\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm; - const inRegex = /\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm; - const varyingRegex = /\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm; - const regex = isFragment && this._fragmentIsGLES3 ? inRegex : !isFragment && this._vertexIsGLES3 ? outRegex : varyingRegex; - const match = regex.exec(varying); - if (match !== null) { - const interpolationQualifier = (_a = match[1]) !== null && _a !== void 0 ? _a : ""; - const varyingType = match[2]; - const name = match[3]; - let location; - if (isFragment) { - location = this._webgpuProcessingContext.availableVaryings[name]; - this._missingVaryings[location] = ""; - if (location === undefined) { - logger_Logger.Warn(`Invalid fragment shader: The varying named "${name}" is not declared in the vertex shader! This declaration will be ignored.`); - } - } - else { - location = this._webgpuProcessingContext.getVaryingNextLocation(varyingType, this._getArraySize(name, varyingType, preProcessors)[2]); - this._webgpuProcessingContext.availableVaryings[name] = location; - this._missingVaryings[location] = `layout(location = ${location}) ${interpolationQualifier} in ${varyingType} ${name};`; - } - varying = varying.replace(match[0], location === undefined ? "" : `layout(location = ${location}) ${interpolationQualifier} ${isFragment ? "in" : "out"} ${varyingType} ${name};`); - } - return varying; - } - attributeProcessor(attribute, preProcessors) { - this._preProcessors = preProcessors; - const inRegex = /\s*in\s+(\S+)\s+(\S+)\s*;/gm; - const attribRegex = /\s*attribute\s+(\S+)\s+(\S+)\s*;/gm; - const regex = this._vertexIsGLES3 ? inRegex : attribRegex; - const match = regex.exec(attribute); - if (match !== null) { - const attributeType = match[1]; - const name = match[2]; - const location = this._webgpuProcessingContext.getAttributeNextLocation(attributeType, this._getArraySize(name, attributeType, preProcessors)[2]); - this._webgpuProcessingContext.availableAttributes[name] = location; - this._webgpuProcessingContext.orderedAttributes[location] = name; - attribute = attribute.replace(match[0], `layout(location = ${location}) in ${attributeType} ${name};`); - } - return attribute; - } - uniformProcessor(uniform, isFragment, preProcessors) { - var _a; - this._preProcessors = preProcessors; - const uniformRegex = /\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm; - const match = uniformRegex.exec(uniform); - if (match !== null) { - let uniformType = match[1]; - let name = match[2]; - if (uniformType.indexOf("sampler") === 0 || uniformType.indexOf("sampler") === 1) { - let arraySize = 0; // 0 means the texture is not declared as an array - [name, uniformType, arraySize] = this._getArraySize(name, uniformType, preProcessors); - let textureInfo = this._webgpuProcessingContext.availableTextures[name]; - if (!textureInfo) { - textureInfo = { - autoBindSampler: true, - isTextureArray: arraySize > 0, - isStorageTexture: false, - textures: [], - sampleType: TextureSampleType.Float, - }; - for (let i = 0; i < (arraySize || 1); ++i) { - textureInfo.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding()); - } - } - const samplerType = (_a = WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[uniformType]) !== null && _a !== void 0 ? _a : "sampler"; - const isComparisonSampler = !!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[samplerType]; - const samplerBindingType = isComparisonSampler ? SamplerBindingType.Comparison : SamplerBindingType.Filtering; - const samplerName = name + WebGPUShaderProcessor.AutoSamplerSuffix; - let samplerInfo = this._webgpuProcessingContext.availableSamplers[samplerName]; - if (!samplerInfo) { - samplerInfo = { - binding: this._webgpuProcessingContext.getNextFreeUBOBinding(), - type: samplerBindingType, - }; - } - const componentType = uniformType.charAt(0) === "u" ? "u" : uniformType.charAt(0) === "i" ? "i" : ""; - if (componentType) { - uniformType = uniformType.substr(1); - } - const sampleType = isComparisonSampler - ? TextureSampleType.Depth - : componentType === "u" - ? TextureSampleType.Uint - : componentType === "i" - ? TextureSampleType.Sint - : TextureSampleType.Float; - textureInfo.sampleType = sampleType; - const isTextureArray = arraySize > 0; - const samplerGroupIndex = samplerInfo.binding.groupIndex; - const samplerBindingIndex = samplerInfo.binding.bindingIndex; - const samplerFunction = WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[uniformType]; - const textureType = WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[uniformType]; - const textureDimension = WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[textureType]; - // Manage textures and samplers. - if (!isTextureArray) { - arraySize = 1; - uniform = `layout(set = ${samplerGroupIndex}, binding = ${samplerBindingIndex}) uniform ${samplerType} ${samplerName}; - layout(set = ${textureInfo.textures[0].groupIndex}, binding = ${textureInfo.textures[0].bindingIndex}) uniform ${componentType}${textureType} ${name}Texture; - #define ${name} ${componentType}${samplerFunction}(${name}Texture, ${samplerName})`; - } - else { - const layouts = []; - layouts.push(`layout(set = ${samplerGroupIndex}, binding = ${samplerBindingIndex}) uniform ${componentType}${samplerType} ${samplerName};`); - uniform = `\n`; - for (let i = 0; i < arraySize; ++i) { - const textureSetIndex = textureInfo.textures[i].groupIndex; - const textureBindingIndex = textureInfo.textures[i].bindingIndex; - layouts.push(`layout(set = ${textureSetIndex}, binding = ${textureBindingIndex}) uniform ${textureType} ${name}Texture${i};`); - uniform += `${i > 0 ? "\n" : ""}#define ${name}${i} ${componentType}${samplerFunction}(${name}Texture${i}, ${samplerName})`; - } - uniform = layouts.join("\n") + uniform; - this._textureArrayProcessing.push(name); - } - this._webgpuProcessingContext.availableTextures[name] = textureInfo; - this._webgpuProcessingContext.availableSamplers[samplerName] = samplerInfo; - this._addSamplerBindingDescription(samplerName, samplerInfo, !isFragment); - for (let i = 0; i < arraySize; ++i) { - this._addTextureBindingDescription(name, textureInfo, i, textureDimension, null, !isFragment); - } - } - else { - this._addUniformToLeftOverUBO(name, uniformType, preProcessors); - uniform = ""; - } - } - return uniform; - } - uniformBufferProcessor(uniformBuffer, isFragment) { - const uboRegex = /uniform\s+(\w+)/gm; - const match = uboRegex.exec(uniformBuffer); - if (match !== null) { - const name = match[1]; - let uniformBufferInfo = this._webgpuProcessingContext.availableBuffers[name]; - if (!uniformBufferInfo) { - const knownUBO = WebGPUShaderProcessingContext.KnownUBOs[name]; - let binding; - if (knownUBO && knownUBO.binding.groupIndex !== -1) { - binding = knownUBO.binding; - } - else { - binding = this._webgpuProcessingContext.getNextFreeUBOBinding(); - } - uniformBufferInfo = { binding }; - this._webgpuProcessingContext.availableBuffers[name] = uniformBufferInfo; - } - this._addBufferBindingDescription(name, uniformBufferInfo, BufferBindingType.Uniform, !isFragment); - uniformBuffer = uniformBuffer.replace("uniform", `layout(set = ${uniformBufferInfo.binding.groupIndex}, binding = ${uniformBufferInfo.binding.bindingIndex}) uniform`); - } - return uniformBuffer; - } - postProcessor(code, defines, isFragment, processingContext, engine) { - const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1; - // Remove extensions - 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; - code = code.replace(regex, ""); - // Replace instructions - code = code.replace(/texture2D\s*\(/g, "texture("); - if (isFragment) { - const hasFragCoord = code.indexOf("gl_FragCoord") >= 0; - const fragCoordCode = ` - glFragCoord_ = gl_FragCoord; - if (yFactor_ == 1.) { - glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; - } - `; - const injectCode = hasFragCoord ? "vec4 glFragCoord_;\n" : ""; - const hasOutput = code.search(/layout *\(location *= *0\) *out/g) !== -1; - code = code.replace(/texture2DLodEXT\s*\(/g, "textureLod("); - code = code.replace(/textureCubeLodEXT\s*\(/g, "textureLod("); - code = code.replace(/textureCube\s*\(/g, "texture("); - code = code.replace(/gl_FragDepthEXT/g, "gl_FragDepth"); - code = code.replace(/gl_FragColor/g, "glFragColor"); - code = code.replace(/gl_FragData/g, "glFragData"); - code = code.replace(/gl_FragCoord/g, "glFragCoord_"); - if (!this._fragmentIsGLES3) { - code = code.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension || hasOutput ? "" : "layout(location = 0) out vec4 glFragColor;\n") + "void main("); - } - else { - const match = /^\s*out\s+\S+\s+\S+\s*;/gm.exec(code); - if (match !== null) { - code = code.substring(0, match.index) + "layout(location = 0) " + code.substring(match.index); - } - } - code = code.replace(/dFdy/g, "(-yFactor_)*dFdy"); // will also handle dFdyCoarse and dFdyFine - code = code.replace("##INJECTCODE##", injectCode); - if (hasFragCoord) { - code = this._injectStartingAndEndingCode(code, "void main", fragCoordCode); - } - } - else { - code = code.replace(/gl_InstanceID/g, "gl_InstanceIndex"); - code = code.replace(/gl_VertexID/g, "gl_VertexIndex"); - const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1; - if (hasMultiviewExtension) { - return "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n" + code; - } - } - // Flip Y + convert z range from [-1,1] to [0,1] - if (!isFragment) { - const lastClosingCurly = code.lastIndexOf("}"); - code = code.substring(0, lastClosingCurly); - code += "gl_Position.y *= yFactor_;\n"; - if (!engine.isNDCHalfZRange) { - code += "gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"; - } - code += "}"; - } - return code; - } - _applyTextureArrayProcessing(code, name) { - // Replaces the occurrences of name[XX] by nameXX - const regex = new RegExp(name + "\\s*\\[(.+)?\\]", "gm"); - let match = regex.exec(code); - while (match !== null) { - const index = match[1]; - let iindex = +index; - if (this._preProcessors && isNaN(iindex)) { - iindex = +this._preProcessors[index.trim()]; - } - code = code.replace(match[0], name + iindex); - match = regex.exec(code); - } - return code; - } - _generateLeftOverUBOCode(name, uniformBufferDescription) { - let ubo = `layout(set = ${uniformBufferDescription.binding.groupIndex}, binding = ${uniformBufferDescription.binding.bindingIndex}) uniform ${name} {\n `; - for (const leftOverUniform of this._webgpuProcessingContext.leftOverUniforms) { - if (leftOverUniform.length > 0) { - ubo += ` ${leftOverUniform.type} ${leftOverUniform.name}[${leftOverUniform.length}];\n`; - } - else { - ubo += ` ${leftOverUniform.type} ${leftOverUniform.name};\n`; - } - } - ubo += "};\n\n"; - return ubo; - } - finalizeShaders(vertexCode, fragmentCode) { - // make replacements for texture names in the texture array case - for (let i = 0; i < this._textureArrayProcessing.length; ++i) { - const name = this._textureArrayProcessing[i]; - vertexCode = this._applyTextureArrayProcessing(vertexCode, name); - fragmentCode = this._applyTextureArrayProcessing(fragmentCode, name); - } - // inject the missing varying in the fragment shader - for (let i = 0; i < this._missingVaryings.length; ++i) { - const decl = this._missingVaryings[i]; - if (decl && decl.length > 0) { - fragmentCode = decl + "\n" + fragmentCode; - } - } - // Builds the leftover UBOs. - const leftOverUBO = this._buildLeftOverUBO(); - vertexCode = leftOverUBO + vertexCode; - fragmentCode = leftOverUBO + fragmentCode; - this._collectBindingNames(); - this._preCreateBindGroupEntries(); - this._preProcessors = null; - return { vertexCode, fragmentCode }; - } -} -//# sourceMappingURL=webgpuShaderProcessorsGLSL.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesDeclaration.js -// Do not edit. - -const ShadersInclude_bonesDeclaration_name = "bonesDeclaration"; -const ShadersInclude_bonesDeclaration_shader = `#if NUM_BONE_INFLUENCERS>0 -attribute matricesIndices : vec4<f32>;attribute matricesWeights : vec4<f32>; -#if NUM_BONE_INFLUENCERS>4 -attribute matricesIndicesExtra : vec4<f32>;attribute matricesWeightsExtra : vec4<f32>; -#endif -#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#ifdef BONETEXTURE -var boneSampler : texture_2d<f32>;uniform boneTextureWidth : f32; -#else -uniform mBones : array<mat4x4,BonesPerMesh>; -#ifdef BONES_VELOCITY_ENABLED -uniform mPreviousBones : array<mat4x4,BonesPerMesh>; -#endif -#endif -#ifdef BONETEXTURE -fn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4<f32> -{let offset=i32(index) *4; -let m0=textureLoad(smp,vec2<i32>(offset+0,0),0);let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);return mat4x4<f32>(m0,m1,m2,m3);} -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_bonesDeclaration_name] = ShadersInclude_bonesDeclaration_shader; -/** @internal */ -const bonesDeclaration_bonesDeclaration = { name: ShadersInclude_bonesDeclaration_name, shader: ShadersInclude_bonesDeclaration_shader }; -//# sourceMappingURL=bonesDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesVertex.js -// Do not edit. - -const ShadersInclude_bonesVertex_name = "bonesVertex"; -const ShadersInclude_bonesVertex_shader = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#if NUM_BONE_INFLUENCERS>0 -var influence : mat4x4<f32>; -#ifdef BONETEXTURE -influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; -#endif -#else -influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; -#endif -#endif -finalWorld=finalWorld*influence; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_bonesVertex_name] = ShadersInclude_bonesVertex_shader; -/** @internal */ -const bonesVertex_bonesVertex = { name: ShadersInclude_bonesVertex_name, shader: ShadersInclude_bonesVertex_shader }; -//# sourceMappingURL=bonesVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimationDeclaration.js -// Do not edit. - -const ShadersInclude_bakedVertexAnimationDeclaration_name = "bakedVertexAnimationDeclaration"; -const ShadersInclude_bakedVertexAnimationDeclaration_shader = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2<f32>;uniform bakedVertexAnimationSettings: vec4<f32>;var bakedVertexAnimationTexture : texture_2d<f32>; -#ifdef INSTANCES -attribute bakedVertexAnimationSettingsInstanced : vec4<f32>; -#endif -fn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32)->mat4x4<f32> -{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);return mat4x4<f32>(m0,m1,m2,m3);} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_bakedVertexAnimationDeclaration_name] = ShadersInclude_bakedVertexAnimationDeclaration_shader; -/** @internal */ -const bakedVertexAnimationDeclaration_bakedVertexAnimationDeclaration = { name: ShadersInclude_bakedVertexAnimationDeclaration_name, shader: ShadersInclude_bakedVertexAnimationDeclaration_shader }; -//# sourceMappingURL=bakedVertexAnimationDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimation.js -// Do not edit. - -const ShadersInclude_bakedVertexAnimation_name = "bakedVertexAnimation"; -const ShadersInclude_bakedVertexAnimation_shader = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -{ -#ifdef INSTANCES -let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; -#else -let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; -#endif -let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4<f32>;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; -#endif -finalWorld=finalWorld*VATInfluence;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_bakedVertexAnimation_name] = ShadersInclude_bakedVertexAnimation_shader; -/** @internal */ -const bakedVertexAnimation_bakedVertexAnimation = { name: ShadersInclude_bakedVertexAnimation_name, shader: ShadersInclude_bakedVertexAnimation_shader }; -//# sourceMappingURL=bakedVertexAnimation.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragment.js -// Do not edit. - -const ShadersInclude_clipPlaneFragment_name = "clipPlaneFragment"; -const ShadersInclude_clipPlaneFragment_shader = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -if (false) {} -#endif -#ifdef CLIPPLANE -else if (fragmentInputs.fClipDistance>0.0) -{discard;} -#endif -#ifdef CLIPPLANE2 -else if (fragmentInputs.fClipDistance2>0.0) -{discard;} -#endif -#ifdef CLIPPLANE3 -else if (fragmentInputs.fClipDistance3>0.0) -{discard;} -#endif -#ifdef CLIPPLANE4 -else if (fragmentInputs.fClipDistance4>0.0) -{discard;} -#endif -#ifdef CLIPPLANE5 -else if (fragmentInputs.fClipDistance5>0.0) -{discard;} -#endif -#ifdef CLIPPLANE6 -else if (fragmentInputs.fClipDistance6>0.0) -{discard;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_clipPlaneFragment_name] = ShadersInclude_clipPlaneFragment_shader; -/** @internal */ -const clipPlaneFragment_clipPlaneFragment = { name: ShadersInclude_clipPlaneFragment_name, shader: ShadersInclude_clipPlaneFragment_shader }; -//# sourceMappingURL=clipPlaneFragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragmentDeclaration.js -// Do not edit. - -const ShadersInclude_clipPlaneFragmentDeclaration_name = "clipPlaneFragmentDeclaration"; -const ShadersInclude_clipPlaneFragmentDeclaration_shader = `#ifdef CLIPPLANE -varying fClipDistance: f32; -#endif -#ifdef CLIPPLANE2 -varying fClipDistance2: f32; -#endif -#ifdef CLIPPLANE3 -varying fClipDistance3: f32; -#endif -#ifdef CLIPPLANE4 -varying fClipDistance4: f32; -#endif -#ifdef CLIPPLANE5 -varying fClipDistance5: f32; -#endif -#ifdef CLIPPLANE6 -varying fClipDistance6: f32; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_clipPlaneFragmentDeclaration_name] = ShadersInclude_clipPlaneFragmentDeclaration_shader; -/** @internal */ -const clipPlaneFragmentDeclaration_clipPlaneFragmentDeclaration = { name: ShadersInclude_clipPlaneFragmentDeclaration_name, shader: ShadersInclude_clipPlaneFragmentDeclaration_shader }; -//# sourceMappingURL=clipPlaneFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertex.js -// Do not edit. - -const ShadersInclude_clipPlaneVertex_name = "clipPlaneVertex"; -const ShadersInclude_clipPlaneVertex_shader = `#ifdef CLIPPLANE -vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); -#endif -#ifdef CLIPPLANE2 -vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); -#endif -#ifdef CLIPPLANE3 -vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); -#endif -#ifdef CLIPPLANE4 -vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); -#endif -#ifdef CLIPPLANE5 -vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); -#endif -#ifdef CLIPPLANE6 -vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_clipPlaneVertex_name] = ShadersInclude_clipPlaneVertex_shader; -/** @internal */ -const clipPlaneVertex_clipPlaneVertex = { name: ShadersInclude_clipPlaneVertex_name, shader: ShadersInclude_clipPlaneVertex_shader }; -//# sourceMappingURL=clipPlaneVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertexDeclaration.js -// Do not edit. - -const ShadersInclude_clipPlaneVertexDeclaration_name = "clipPlaneVertexDeclaration"; -const ShadersInclude_clipPlaneVertexDeclaration_shader = `#ifdef CLIPPLANE -uniform vClipPlane: vec4<f32>;varying fClipDistance: f32; -#endif -#ifdef CLIPPLANE2 -uniform vClipPlane2: vec4<f32>;varying fClipDistance2: f32; -#endif -#ifdef CLIPPLANE3 -uniform vClipPlane3: vec4<f32>;varying fClipDistance3: f32; -#endif -#ifdef CLIPPLANE4 -uniform vClipPlane4: vec4<f32>;varying fClipDistance4: f32; -#endif -#ifdef CLIPPLANE5 -uniform vClipPlane5: vec4<f32>;varying fClipDistance5: f32; -#endif -#ifdef CLIPPLANE6 -uniform vClipPlane6: vec4<f32>;varying fClipDistance6: f32; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_clipPlaneVertexDeclaration_name] = ShadersInclude_clipPlaneVertexDeclaration_shader; -/** @internal */ -const clipPlaneVertexDeclaration_clipPlaneVertexDeclaration = { name: ShadersInclude_clipPlaneVertexDeclaration_name, shader: ShadersInclude_clipPlaneVertexDeclaration_shader }; -//# sourceMappingURL=clipPlaneVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesDeclaration.js -// Do not edit. - -const ShadersInclude_instancesDeclaration_name = "instancesDeclaration"; -const ShadersInclude_instancesDeclaration_shader = `#ifdef INSTANCES -attribute world0 : vec4<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>; -#ifdef INSTANCESCOLOR -attribute instanceColor : vec4<f32>; -#endif -#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) -uniform world : mat4x4<f32>; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -attribute previousWorld0 : vec4<f32>;attribute previousWorld1 : vec4<f32>;attribute previousWorld2 : vec4<f32>;attribute previousWorld3 : vec4<f32>; -#ifdef THIN_INSTANCES -uniform previousWorld : mat4x4<f32>; -#endif -#endif -#else -#if !defined(WORLD_UBO) -uniform world : mat4x4<f32>; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -uniform previousWorld : mat4x4<f32>; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_instancesDeclaration_name] = ShadersInclude_instancesDeclaration_shader; -/** @internal */ -const instancesDeclaration_instancesDeclaration = { name: ShadersInclude_instancesDeclaration_name, shader: ShadersInclude_instancesDeclaration_shader }; -//# sourceMappingURL=instancesDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesVertex.js -// Do not edit. - -const ShadersInclude_instancesVertex_name = "instancesVertex"; -const ShadersInclude_instancesVertex_shader = `#ifdef INSTANCES -var finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -var finalPreviousWorld=mat4x4<f32>(previousWorld0,previousWorld1,previousWorld2,previousWorld3); -#endif -#ifdef THIN_INSTANCES -#if !defined(WORLD_UBO) -finalWorld=uniforms.world*finalWorld; -#else -finalWorld=mesh.world*finalWorld; -#endif -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -finalPreviousWorld=previousWorld*finalPreviousWorld; -#endif -#endif -#else -#if !defined(WORLD_UBO) -var finalWorld=uniforms.world; -#else -var finalWorld=mesh.world; -#endif -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -var finalPreviousWorld=previousWorld; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_instancesVertex_name] = ShadersInclude_instancesVertex_shader; -/** @internal */ -const instancesVertex_instancesVertex = { name: ShadersInclude_instancesVertex_name, shader: ShadersInclude_instancesVertex_shader }; -//# sourceMappingURL=instancesVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/meshUboDeclaration.js -// Do not edit. - -const ShadersInclude_meshUboDeclaration_name = "meshUboDeclaration"; -const ShadersInclude_meshUboDeclaration_shader = `struct Mesh {world : mat4x4<f32>, -visibility : f32,};var<uniform> mesh : Mesh; -#define WORLD_UBO -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_meshUboDeclaration_name] = ShadersInclude_meshUboDeclaration_shader; -/** @internal */ -const meshUboDeclaration_meshUboDeclaration = { name: ShadersInclude_meshUboDeclaration_name, shader: ShadersInclude_meshUboDeclaration_shader }; -//# sourceMappingURL=meshUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertex.js -// Do not edit. - -const ShadersInclude_morphTargetsVertex_name = "morphTargetsVertex"; -const ShadersInclude_morphTargetsVertex_shader = `#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#ifdef MORPHTARGETS_NORMAL -normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; -#endif -#else -positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_morphTargetsVertex_name] = ShadersInclude_morphTargetsVertex_shader; -/** @internal */ -const morphTargetsVertex_morphTargetsVertex = { name: ShadersInclude_morphTargetsVertex_name, shader: ShadersInclude_morphTargetsVertex_shader }; -//# sourceMappingURL=morphTargetsVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexDeclaration.js -// Do not edit. - -const ShadersInclude_morphTargetsVertexDeclaration_name = "morphTargetsVertexDeclaration"; -const ShadersInclude_morphTargetsVertexDeclaration_shader = `#ifdef MORPHTARGETS -#ifndef MORPHTARGETS_TEXTURE -attribute position{X} : vec3<f32>; -#ifdef MORPHTARGETS_NORMAL -attribute normal{X} : vec3<f32>; -#endif -#ifdef MORPHTARGETS_TANGENT -attribute tangent{X} : vec3<f32>; -#endif -#ifdef MORPHTARGETS_UV -attribute uv_{X} : vec2<f32>; -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_morphTargetsVertexDeclaration_name] = ShadersInclude_morphTargetsVertexDeclaration_shader; -/** @internal */ -const morphTargetsVertexDeclaration_morphTargetsVertexDeclaration = { name: ShadersInclude_morphTargetsVertexDeclaration_name, shader: ShadersInclude_morphTargetsVertexDeclaration_shader }; -//# sourceMappingURL=morphTargetsVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobal.js -// Do not edit. - -const ShadersInclude_morphTargetsVertexGlobal_name = "morphTargetsVertexGlobal"; -const ShadersInclude_morphTargetsVertexGlobal_shader = `#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -var vertexID : f32; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_morphTargetsVertexGlobal_name] = ShadersInclude_morphTargetsVertexGlobal_shader; -/** @internal */ -const morphTargetsVertexGlobal_morphTargetsVertexGlobal = { name: ShadersInclude_morphTargetsVertexGlobal_name, shader: ShadersInclude_morphTargetsVertexGlobal_shader }; -//# sourceMappingURL=morphTargetsVertexGlobal.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobalDeclaration.js -// Do not edit. - -const ShadersInclude_morphTargetsVertexGlobalDeclaration_name = "morphTargetsVertexGlobalDeclaration"; -const ShadersInclude_morphTargetsVertexGlobalDeclaration_shader = `#ifdef MORPHTARGETS -uniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>; -#ifdef MORPHTARGETS_TEXTURE -uniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;uniform morphTargetTextureInfo : vec3<f32>;var morphTargets : texture_2d_array<f32>;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3<f32> -{ -let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2<f32>((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_morphTargetsVertexGlobalDeclaration_name] = ShadersInclude_morphTargetsVertexGlobalDeclaration_shader; -/** @internal */ -const morphTargetsVertexGlobalDeclaration_morphTargetsVertexGlobalDeclaration = { name: ShadersInclude_morphTargetsVertexGlobalDeclaration_name, shader: ShadersInclude_morphTargetsVertexGlobalDeclaration_shader }; -//# sourceMappingURL=morphTargetsVertexGlobalDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/sceneUboDeclaration.js -// Do not edit. - -const ShadersInclude_sceneUboDeclaration_name = "sceneUboDeclaration"; -const ShadersInclude_sceneUboDeclaration_shader = `struct Scene {viewProjection : mat4x4<f32>, -#ifdef MULTIVIEW -viewProjectionR : mat4x4<f32>, -#endif -view : mat4x4<f32>, -projection : mat4x4<f32>, -vEyePosition : vec4<f32>,};var<uniform> scene : Scene; -`; -// Sideeffect -ShaderStore.IncludesShadersStoreWGSL[ShadersInclude_sceneUboDeclaration_name] = ShadersInclude_sceneUboDeclaration_shader; -/** @internal */ -const sceneUboDeclaration_sceneUboDeclaration = { name: ShadersInclude_sceneUboDeclaration_name, shader: ShadersInclude_sceneUboDeclaration_shader }; -//# sourceMappingURL=sceneUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessorsWGSL.js - - - - - - - - - - - - - - - - - - - - - - -const builtInName_frag_depth = "fragmentOutputs.fragDepth"; -const leftOverVarName = "uniforms"; -const internalsVarName = "internals"; -const gpuTextureViewDimensionByWebGPUTextureFunction = { - texture_1d: TextureViewDimension.E1d, - texture_2d: TextureViewDimension.E2d, - texture_2d_array: TextureViewDimension.E2dArray, - texture_3d: TextureViewDimension.E3d, - texture_cube: TextureViewDimension.Cube, - texture_cube_array: TextureViewDimension.CubeArray, - texture_multisampled_2d: TextureViewDimension.E2d, - texture_depth_2d: TextureViewDimension.E2d, - texture_depth_2d_array: TextureViewDimension.E2dArray, - texture_depth_cube: TextureViewDimension.Cube, - texture_depth_cube_array: TextureViewDimension.CubeArray, - texture_depth_multisampled_2d: TextureViewDimension.E2d, - texture_storage_1d: TextureViewDimension.E1d, - texture_storage_2d: TextureViewDimension.E2d, - texture_storage_2d_array: TextureViewDimension.E2dArray, - texture_storage_3d: TextureViewDimension.E3d, - texture_external: null, -}; -/** @internal */ -class WebGPUShaderProcessorWGSL extends WebGPUShaderProcessor { - constructor() { - super(...arguments); - this.shaderLanguage = ShaderLanguage.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 = true; - } - _getArraySize(name, uniformType, preProcessors) { - let length = 0; - const endArray = uniformType.lastIndexOf(">"); - if (uniformType.indexOf("array") >= 0 && endArray > 0) { - let startArray = endArray; - while (startArray > 0 && uniformType.charAt(startArray) !== " " && uniformType.charAt(startArray) !== ",") { - startArray--; - } - const lengthInString = uniformType.substring(startArray + 1, endArray); - length = +lengthInString; - if (isNaN(length)) { - length = +preProcessors[lengthInString.trim()]; - } - while (startArray > 0 && (uniformType.charAt(startArray) === " " || uniformType.charAt(startArray) === ",")) { - startArray--; - } - uniformType = uniformType.substring(uniformType.indexOf("<") + 1, startArray + 1); - } - return [name, uniformType, length]; - } - initializeShaders(processingContext) { - this._webgpuProcessingContext = processingContext; - this._attributesWGSL = []; - this._varyingsWGSL = []; - this._varyingNamesWGSL = []; - this._stridedUniformArrays = []; - } - preProcessShaderCode(code) { - return (`struct ${WebGPUShaderProcessor.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar<uniform> ${internalsVarName} : ${WebGPUShaderProcessor.InternalsUBOName};\n` + - RemoveComments(code)); - } - varyingProcessor(varying, isFragment, preProcessors) { - const varyingRegex = /\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm; - const match = varyingRegex.exec(varying); - if (match !== null) { - const varyingType = match[2]; - const name = match[1]; - let location; - if (isFragment) { - location = this._webgpuProcessingContext.availableVaryings[name]; - if (location === undefined) { - logger_Logger.Warn(`Invalid fragment shader: The varying named "${name}" is not declared in the vertex shader! This declaration will be ignored.`); - } - } - else { - location = this._webgpuProcessingContext.getVaryingNextLocation(varyingType, this._getArraySize(name, varyingType, preProcessors)[2]); - this._webgpuProcessingContext.availableVaryings[name] = location; - this._varyingsWGSL.push(` @location(${location}) ${name} : ${varyingType},`); - this._varyingNamesWGSL.push(name); - } - varying = ""; - } - return varying; - } - attributeProcessor(attribute, preProcessors) { - const attribRegex = /\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm; - const match = attribRegex.exec(attribute); - if (match !== null) { - const attributeType = match[2]; - const name = match[1]; - const location = this._webgpuProcessingContext.getAttributeNextLocation(attributeType, this._getArraySize(name, attributeType, preProcessors)[2]); - this._webgpuProcessingContext.availableAttributes[name] = location; - this._webgpuProcessingContext.orderedAttributes[location] = name; - this._attributesWGSL.push(`@location(${location}) ${name} : ${attributeType},`); - attribute = ""; - } - return attribute; - } - uniformProcessor(uniform, isFragment, preProcessors) { - const match = this.uniformRegexp.exec(uniform); - if (match !== null) { - const uniformType = match[2]; - const name = match[1]; - this._addUniformToLeftOverUBO(name, uniformType, preProcessors); - uniform = ""; - } - return uniform; - } - textureProcessor(texture, isFragment, preProcessors) { - const match = this.textureRegexp.exec(texture); - if (match !== null) { - const name = match[1]; // name of the variable - const type = match[2]; // texture_2d<f32> or array<texture_2d_array<f32>, 5> for eg - const isArrayOfTexture = !!match[3]; - const textureFunc = match[4]; // texture_2d, texture_depth_2d, etc - const isStorageTexture = textureFunc.indexOf("storage") > 0; - const componentType = match[6]; // f32 or i32 or u32 or undefined - const storageTextureFormat = isStorageTexture ? componentType.substring(0, componentType.indexOf(",")).trim() : null; - let arraySize = isArrayOfTexture ? this._getArraySize(name, type, preProcessors)[2] : 0; - let textureInfo = this._webgpuProcessingContext.availableTextures[name]; - if (!textureInfo) { - textureInfo = { - isTextureArray: arraySize > 0, - isStorageTexture, - textures: [], - sampleType: TextureSampleType.Float, - }; - arraySize = arraySize || 1; - for (let i = 0; i < arraySize; ++i) { - textureInfo.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding()); - } - } - else { - arraySize = textureInfo.textures.length; - } - this._webgpuProcessingContext.availableTextures[name] = textureInfo; - const isDepthTexture = textureFunc.indexOf("depth") > 0; - const textureDimension = gpuTextureViewDimensionByWebGPUTextureFunction[textureFunc]; - const sampleType = isDepthTexture - ? TextureSampleType.Depth - : componentType === "u32" - ? TextureSampleType.Uint - : componentType === "i32" - ? TextureSampleType.Sint - : TextureSampleType.Float; - textureInfo.sampleType = sampleType; - if (textureDimension === undefined) { - throw `Can't get the texture dimension corresponding to the texture function "${textureFunc}"!`; - } - for (let i = 0; i < arraySize; ++i) { - const { groupIndex, bindingIndex } = textureInfo.textures[i]; - if (i === 0) { - texture = `@group(${groupIndex}) @binding(${bindingIndex}) ${texture}`; - } - this._addTextureBindingDescription(name, textureInfo, i, textureDimension, storageTextureFormat, !isFragment); - } - } - return texture; - } - postProcessor(code) { - return code; - } - finalizeShaders(vertexCode, fragmentCode) { - const fragCoordCode = fragmentCode.indexOf("fragmentInputs.position") >= 0 - ? ` - if (internals.yFactor_ == 1.) { - fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; - } - ` - : ""; - // Add the group/binding info to the sampler declaration (var xxx: sampler|sampler_comparison) - vertexCode = this._processSamplers(vertexCode, true); - fragmentCode = this._processSamplers(fragmentCode, false); - // Add the group/binding info to the uniform/storage buffer declarations (var<uniform> XXX:YYY or var<storage(,read_write|read)> XXX:YYY) - vertexCode = this._processCustomBuffers(vertexCode, true); - fragmentCode = this._processCustomBuffers(fragmentCode, false); - // Builds the leftover UBOs. - const leftOverUBO = this._buildLeftOverUBO(); - vertexCode = leftOverUBO + vertexCode; - fragmentCode = leftOverUBO + fragmentCode; - // Vertex code - vertexCode = vertexCode.replace(/#define /g, "//#define "); - vertexCode = this._processStridedUniformArrays(vertexCode); - let vertexInputs = "struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n"; - if (this._attributesWGSL.length > 0) { - vertexInputs += this._attributesWGSL.join("\n"); - } - vertexInputs += "\n};\nvar<private> vertexInputs : VertexInputs;\n"; - let vertexOutputs = "struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n"; - if (this._varyingsWGSL.length > 0) { - vertexOutputs += this._varyingsWGSL.join("\n"); - } - vertexOutputs += "\n};\nvar<private> vertexOutputs : FragmentInputs;\n"; - vertexCode = vertexInputs + vertexOutputs + vertexCode; - const vertexMainStartingCode = `\n vertexInputs = input;\n`; - const vertexMainEndingCode = ` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;`; - vertexCode = this._injectStartingAndEndingCode(vertexCode, "fn main", vertexMainStartingCode, vertexMainEndingCode); - // fragment code - fragmentCode = fragmentCode.replace(/#define /g, "//#define "); - fragmentCode = this._processStridedUniformArrays(fragmentCode); - fragmentCode = fragmentCode.replace(/dpdy/g, "(-internals.yFactor_)*dpdy"); // will also handle dpdyCoarse and dpdyFine - let fragmentInputs = "struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n @builtin(front_facing) frontFacing : bool,\n"; - if (this._varyingsWGSL.length > 0) { - fragmentInputs += this._varyingsWGSL.join("\n"); - } - fragmentInputs += "\n};\nvar<private> fragmentInputs : FragmentInputs;\n"; - let fragmentOutputs = "struct FragmentOutputs {\n @location(0) color : vec4<f32>,\n"; - let hasFragDepth = false; - let idx = 0; - while (!hasFragDepth) { - idx = fragmentCode.indexOf(builtInName_frag_depth, idx); - if (idx < 0) { - break; - } - const saveIndex = idx; - hasFragDepth = true; - while (idx > 1 && fragmentCode.charAt(idx) !== "\n") { - if (fragmentCode.charAt(idx) === "/" && fragmentCode.charAt(idx - 1) === "/") { - hasFragDepth = false; - break; - } - idx--; - } - idx = saveIndex + builtInName_frag_depth.length; - } - if (hasFragDepth) { - fragmentOutputs += " @builtin(frag_depth) fragDepth: f32,\n"; - } - fragmentOutputs += "};\nvar<private> fragmentOutputs : FragmentOutputs;\n"; - fragmentCode = fragmentInputs + fragmentOutputs + fragmentCode; - const fragmentStartingCode = " fragmentInputs = input;\n " + fragCoordCode; - const fragmentEndingCode = " return fragmentOutputs;"; - fragmentCode = this._injectStartingAndEndingCode(fragmentCode, "fn main", fragmentStartingCode, fragmentEndingCode); - this._collectBindingNames(); - this._preCreateBindGroupEntries(); - return { vertexCode, fragmentCode }; - } - _generateLeftOverUBOCode(name, uniformBufferDescription) { - let stridedArrays = ""; - let ubo = `struct ${name} {\n`; - for (const leftOverUniform of this._webgpuProcessingContext.leftOverUniforms) { - const type = leftOverUniform.type.replace(/^(.*?)(<.*>)?$/, "$1"); - const size = WebGPUShaderProcessor.UniformSizes[type]; - if (leftOverUniform.length > 0) { - if (size <= 2) { - const stridedArrayType = `${name}_${this._stridedUniformArrays.length}_strided_arr`; - stridedArrays += `struct ${stridedArrayType} { - @size(16) - el: ${type}, - }`; - this._stridedUniformArrays.push(leftOverUniform.name); - ubo += ` @align(16) ${leftOverUniform.name} : array<${stridedArrayType}, ${leftOverUniform.length}>,\n`; - } - else { - ubo += ` ${leftOverUniform.name} : array<${leftOverUniform.type}, ${leftOverUniform.length}>,\n`; - } - } - else { - ubo += ` ${leftOverUniform.name} : ${leftOverUniform.type},\n`; - } - } - ubo += "};\n"; - ubo = `${stridedArrays}\n${ubo}`; - ubo += `@group(${uniformBufferDescription.binding.groupIndex}) @binding(${uniformBufferDescription.binding.bindingIndex}) var<uniform> ${leftOverVarName} : ${name};\n`; - return ubo; - } - _processSamplers(code, isVertex) { - const samplerRegexp = /var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm; - // eslint-disable-next-line no-constant-condition - while (true) { - const match = samplerRegexp.exec(code); - if (match === null) { - break; - } - const name = match[1]; // name of the variable - const samplerType = match[2]; // sampler or sampler_comparison - const textureName = name.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix) === name.length - WebGPUShaderProcessor.AutoSamplerSuffix.length - ? name.substring(0, name.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)) - : null; - const samplerBindingType = samplerType === "sampler_comparison" ? SamplerBindingType.Comparison : SamplerBindingType.Filtering; - if (textureName) { - const textureInfo = this._webgpuProcessingContext.availableTextures[textureName]; - if (textureInfo) { - textureInfo.autoBindSampler = true; - } - } - let samplerInfo = this._webgpuProcessingContext.availableSamplers[name]; - if (!samplerInfo) { - samplerInfo = { - binding: this._webgpuProcessingContext.getNextFreeUBOBinding(), - type: samplerBindingType, - }; - this._webgpuProcessingContext.availableSamplers[name] = samplerInfo; - } - this._addSamplerBindingDescription(name, samplerInfo, isVertex); - const part1 = code.substring(0, match.index); - const insertPart = `@group(${samplerInfo.binding.groupIndex}) @binding(${samplerInfo.binding.bindingIndex}) `; - const part2 = code.substring(match.index); - code = part1 + insertPart + part2; - samplerRegexp.lastIndex += insertPart.length; - } - return code; - } - _processCustomBuffers(code, isVertex) { - const instantiateBufferRegexp = /var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm; - // eslint-disable-next-line no-constant-condition - while (true) { - const match = instantiateBufferRegexp.exec(code); - if (match === null) { - break; - } - const type = match[1]; - const decoration = match[3]; - let name = match[4]; - const structName = match[5]; - let bufferInfo = this._webgpuProcessingContext.availableBuffers[name]; - if (!bufferInfo) { - const knownUBO = type === "uniform" ? WebGPUShaderProcessingContext.KnownUBOs[structName] : null; - let binding; - if (knownUBO) { - name = structName; - binding = knownUBO.binding; - if (binding.groupIndex === -1) { - binding = this._webgpuProcessingContext.getNextFreeUBOBinding(); - } - } - else { - binding = this._webgpuProcessingContext.getNextFreeUBOBinding(); - } - bufferInfo = { binding }; - this._webgpuProcessingContext.availableBuffers[name] = bufferInfo; - } - this._addBufferBindingDescription(name, this._webgpuProcessingContext.availableBuffers[name], decoration === "read_write" - ? BufferBindingType.Storage - : type === "storage" - ? BufferBindingType.ReadOnlyStorage - : BufferBindingType.Uniform, isVertex); - const groupIndex = bufferInfo.binding.groupIndex; - const bindingIndex = bufferInfo.binding.bindingIndex; - const part1 = code.substring(0, match.index); - const insertPart = `@group(${groupIndex}) @binding(${bindingIndex}) `; - const part2 = code.substring(match.index); - code = part1 + insertPart + part2; - instantiateBufferRegexp.lastIndex += insertPart.length; - } - return code; - } - _processStridedUniformArrays(code) { - for (const uniformArrayName of this._stridedUniformArrays) { - code = code.replace(new RegExp(`${uniformArrayName}\\s*\\[(.*)\\]`, "g"), `${uniformArrayName}[$1].el`); - } - return code; - } -} -//# sourceMappingURL=webgpuShaderProcessorsWGSL.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuHardwareTexture.js - - -/** @internal */ -class WebGPUHardwareTexture { - get underlyingResource() { - return this._webgpuTexture; - } - getMSAATexture(index = 0) { - var _a, _b; - return (_b = (_a = this._webgpuMSAATexture) === null || _a === void 0 ? void 0 : _a[index]) !== null && _b !== void 0 ? _b : null; - } - setMSAATexture(texture, index = -1) { - if (!this._webgpuMSAATexture) { - this._webgpuMSAATexture = []; - } - if (index === -1) { - index = this._webgpuMSAATexture.length; - } - this._webgpuMSAATexture[index] = texture; - } - releaseMSAATexture() { - if (this._webgpuMSAATexture) { - for (const texture of this._webgpuMSAATexture) { - texture === null || texture === void 0 ? void 0 : texture.destroy(); - } - this._webgpuMSAATexture = null; - } - } - constructor(existingTexture = null) { - this.format = TextureFormat.RGBA8Unorm; - this.textureUsages = 0; - this.textureAdditionalUsages = 0; - this._webgpuTexture = existingTexture; - this._webgpuMSAATexture = null; - this.view = null; - this.viewForWriting = null; - } - set(hardwareTexture) { - this._webgpuTexture = hardwareTexture; - } - setUsage(_textureSource, generateMipMaps, isCube, width, height) { - this.createView({ - format: this.format, - dimension: isCube ? TextureViewDimension.Cube : TextureViewDimension.E2d, - mipLevelCount: generateMipMaps ? math_scalar_Scalar.ILog2(Math.max(width, height)) + 1 : 1, - baseArrayLayer: 0, - baseMipLevel: 0, - arrayLayerCount: isCube ? 6 : 1, - aspect: TextureAspect.All, - }); - } - createView(descriptor, createViewForWriting = false) { - this.view = this._webgpuTexture.createView(descriptor); - if (createViewForWriting && descriptor) { - const saveNumMipMaps = descriptor.mipLevelCount; - descriptor.mipLevelCount = 1; - this.viewForWriting = this._webgpuTexture.createView(descriptor); - descriptor.mipLevelCount = saveNumMipMaps; - } - } - reset() { - this._webgpuTexture = null; - this._webgpuMSAATexture = null; - this.view = null; - this.viewForWriting = null; - } - release() { - var _a, _b; - (_a = this._webgpuTexture) === null || _a === void 0 ? void 0 : _a.destroy(); - this.releaseMSAATexture(); - (_b = this._copyInvertYTempTexture) === null || _b === void 0 ? void 0 : _b.destroy(); - this.reset(); - } -} -//# sourceMappingURL=webgpuHardwareTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuTextureHelper.js -/* eslint-disable @typescript-eslint/naming-convention */ -// License for the mipmap generation code: -// -// Copyright 2020 Brandon Jones -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - - - - - -// TODO WEBGPU improve mipmap generation by using compute shaders -// TODO WEBGPU use WGSL instead of GLSL -const mipmapVertexSource = ` - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); - - layout(location = 0) out vec2 vTex; - - void main() { - vTex = tex[gl_VertexIndex]; - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `; -const mipmapFragmentSource = ` - layout(set = 0, binding = 0) uniform sampler imgSampler; - layout(set = 0, binding = 1) uniform texture2D img; - - layout(location = 0) in vec2 vTex; - layout(location = 0) out vec4 outColor; - - void main() { - outColor = texture(sampler2D(img, imgSampler), vTex); - } - `; -const invertYPreMultiplyAlphaVertexSource = ` - #extension GL_EXT_samplerless_texture_functions : enable - - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); - - layout(set = 0, binding = 0) uniform texture2D img; - - #ifdef INVERTY - layout(location = 0) out flat ivec2 vTextureSize; - #endif - - void main() { - #ifdef INVERTY - vTextureSize = textureSize(img, 0); - #endif - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `; -const invertYPreMultiplyAlphaFragmentSource = ` - #extension GL_EXT_samplerless_texture_functions : enable - - layout(set = 0, binding = 0) uniform texture2D img; - - #ifdef INVERTY - layout(location = 0) in flat ivec2 vTextureSize; - #endif - layout(location = 0) out vec4 outColor; - - void main() { - #ifdef INVERTY - vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0); - #else - vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); - #endif - #ifdef PREMULTIPLYALPHA - color.rgb *= color.a; - #endif - outColor = color; - } - `; -const invertYPreMultiplyAlphaWithOfstVertexSource = invertYPreMultiplyAlphaVertexSource; -const invertYPreMultiplyAlphaWithOfstFragmentSource = ` - #extension GL_EXT_samplerless_texture_functions : enable - - layout(set = 0, binding = 0) uniform texture2D img; - layout(set = 0, binding = 1) uniform Params { - float ofstX; - float ofstY; - float width; - float height; - }; - - #ifdef INVERTY - layout(location = 0) in flat ivec2 vTextureSize; - #endif - layout(location = 0) out vec4 outColor; - - void main() { - if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) { - discard; - } - if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) { - discard; - } - #ifdef INVERTY - vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0); - #else - vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); - #endif - #ifdef PREMULTIPLYALPHA - color.rgb *= color.a; - #endif - outColor = color; - } - `; -const clearVertexSource = ` - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - - void main() { - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `; -const clearFragmentSource = ` - layout(set = 0, binding = 0) uniform Uniforms { - uniform vec4 color; - }; - - layout(location = 0) out vec4 outColor; - - void main() { - outColor = color; - } - `; -const copyVideoToTextureVertexSource = ` - struct VertexOutput { - @builtin(position) Position : vec4<f32>, - @location(0) fragUV : vec2<f32> - } - - @vertex - fn main( - @builtin(vertex_index) VertexIndex : u32 - ) -> VertexOutput { - var pos = array<vec2<f32>, 4>( - vec2(-1.0, 1.0), - vec2( 1.0, 1.0), - vec2(-1.0, -1.0), - vec2( 1.0, -1.0) - ); - var tex = array<vec2<f32>, 4>( - vec2(0.0, 0.0), - vec2(1.0, 0.0), - vec2(0.0, 1.0), - vec2(1.0, 1.0) - ); - - var output: VertexOutput; - - output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0); - output.fragUV = tex[VertexIndex]; - - return output; - } - `; -const copyVideoToTextureFragmentSource = ` - @group(0) @binding(0) var videoSampler: sampler; - @group(0) @binding(1) var videoTexture: texture_external; - - @fragment - fn main( - @location(0) fragUV: vec2<f32> - ) -> @location(0) vec4<f32> { - return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); - } - `; -const copyVideoToTextureInvertYFragmentSource = ` - @group(0) @binding(0) var videoSampler: sampler; - @group(0) @binding(1) var videoTexture: texture_external; - - @fragment - fn main( - @location(0) fragUV: vec2<f32> - ) -> @location(0) vec4<f32> { - return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2<f32>(fragUV.x, 1.0 - fragUV.y)); - } - `; -var PipelineType; -(function (PipelineType) { - PipelineType[PipelineType["MipMap"] = 0] = "MipMap"; - PipelineType[PipelineType["InvertYPremultiplyAlpha"] = 1] = "InvertYPremultiplyAlpha"; - PipelineType[PipelineType["Clear"] = 2] = "Clear"; - PipelineType[PipelineType["InvertYPremultiplyAlphaWithOfst"] = 3] = "InvertYPremultiplyAlphaWithOfst"; -})(PipelineType || (PipelineType = {})); -var VideoPipelineType; -(function (VideoPipelineType) { - VideoPipelineType[VideoPipelineType["DontInvertY"] = 0] = "DontInvertY"; - VideoPipelineType[VideoPipelineType["InvertY"] = 1] = "InvertY"; -})(VideoPipelineType || (VideoPipelineType = {})); -const shadersForPipelineType = [ - { vertex: mipmapVertexSource, fragment: mipmapFragmentSource }, - { vertex: invertYPreMultiplyAlphaVertexSource, fragment: invertYPreMultiplyAlphaFragmentSource }, - { vertex: clearVertexSource, fragment: clearFragmentSource }, - { vertex: invertYPreMultiplyAlphaWithOfstVertexSource, fragment: invertYPreMultiplyAlphaWithOfstFragmentSource }, -]; -/** - * Map a (renderable) texture format (GPUTextureFormat) to an index for fast lookup (in caches for eg) - */ -const renderableTextureFormatToIndex = { - "": 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, -}; -/** @internal */ -class WebGPUTextureHelper { - static ComputeNumMipmapLevels(width, height) { - return math_scalar_Scalar.ILog2(Math.max(width, height)) + 1; - } - //------------------------------------------------------------------------------ - // Initialization / Helpers - //------------------------------------------------------------------------------ - constructor(device, glslang, tintWASM, bufferManager, enabledExtensions) { - this._pipelines = {}; - this._compiledShaders = []; - this._videoPipelines = {}; - this._videoCompiledShaders = []; - this._deferredReleaseTextures = []; - this._device = device; - this._glslang = glslang; - this._tintWASM = tintWASM; - this._bufferManager = bufferManager; - if (enabledExtensions.indexOf(FeatureName.RG11B10UFloatRenderable) !== -1) { - const keys = Object.keys(renderableTextureFormatToIndex); - renderableTextureFormatToIndex[TextureFormat.RG11B10UFloat] = renderableTextureFormatToIndex[keys[keys.length - 1]] + 1; - } - this._mipmapSampler = device.createSampler({ minFilter: FilterMode.Linear }); - this._videoSampler = device.createSampler({ minFilter: FilterMode.Linear }); - this._ubCopyWithOfst = this._bufferManager.createBuffer(4 * 4, BufferUsage.Uniform | BufferUsage.CopyDst).underlyingResource; - this._getPipeline(TextureFormat.RGBA8Unorm); - this._getVideoPipeline(TextureFormat.RGBA8Unorm); - } - _getPipeline(format, type = PipelineType.MipMap, params) { - const index = type === PipelineType.MipMap - ? 1 << 0 - : type === PipelineType.InvertYPremultiplyAlpha - ? ((params.invertY ? 1 : 0) << 1) + ((params.premultiplyAlpha ? 1 : 0) << 2) - : type === PipelineType.Clear - ? 1 << 3 - : type === PipelineType.InvertYPremultiplyAlphaWithOfst - ? ((params.invertY ? 1 : 0) << 4) + ((params.premultiplyAlpha ? 1 : 0) << 5) - : 0; - if (!this._pipelines[format]) { - this._pipelines[format] = []; - } - let pipelineAndBGL = this._pipelines[format][index]; - if (!pipelineAndBGL) { - let defines = "#version 450\n"; - if (type === PipelineType.InvertYPremultiplyAlpha || type === PipelineType.InvertYPremultiplyAlphaWithOfst) { - if (params.invertY) { - defines += "#define INVERTY\n"; - } - if (params.premultiplyAlpha) { - defines += "#define PREMULTIPLYALPHA\n"; - } - } - let modules = this._compiledShaders[index]; - if (!modules) { - let vertexCode = this._glslang.compileGLSL(defines + shadersForPipelineType[type].vertex, "vertex"); - let fragmentCode = this._glslang.compileGLSL(defines + shadersForPipelineType[type].fragment, "fragment"); - if (this._tintWASM) { - vertexCode = this._tintWASM.convertSpirV2WGSL(vertexCode); - fragmentCode = this._tintWASM.convertSpirV2WGSL(fragmentCode); - } - const vertexModule = this._device.createShaderModule({ - code: vertexCode, - }); - const fragmentModule = this._device.createShaderModule({ - code: fragmentCode, - }); - modules = this._compiledShaders[index] = [vertexModule, fragmentModule]; - } - const pipeline = this._device.createRenderPipeline({ - layout: AutoLayoutMode.Auto, - vertex: { - module: modules[0], - entryPoint: "main", - }, - fragment: { - module: modules[1], - entryPoint: "main", - targets: [ - { - format, - }, - ], - }, - primitive: { - topology: PrimitiveTopology.TriangleStrip, - stripIndexFormat: IndexFormat.Uint16, - }, - }); - pipelineAndBGL = this._pipelines[format][index] = [pipeline, pipeline.getBindGroupLayout(0)]; - } - return pipelineAndBGL; - } - _getVideoPipeline(format, type = VideoPipelineType.DontInvertY) { - const index = type === VideoPipelineType.InvertY ? 1 << 0 : 0; - if (!this._videoPipelines[format]) { - this._videoPipelines[format] = []; - } - let pipelineAndBGL = this._videoPipelines[format][index]; - if (!pipelineAndBGL) { - let modules = this._videoCompiledShaders[index]; - if (!modules) { - const vertexModule = this._device.createShaderModule({ - code: copyVideoToTextureVertexSource, - }); - const fragmentModule = this._device.createShaderModule({ - code: index === 0 ? copyVideoToTextureFragmentSource : copyVideoToTextureInvertYFragmentSource, - }); - modules = this._videoCompiledShaders[index] = [vertexModule, fragmentModule]; - } - const pipeline = this._device.createRenderPipeline({ - label: `CopyVideoToTexture_${format}_${index === 0 ? "DontInvertY" : "InvertY"}`, - layout: AutoLayoutMode.Auto, - vertex: { - module: modules[0], - entryPoint: "main", - }, - fragment: { - module: modules[1], - entryPoint: "main", - targets: [ - { - format, - }, - ], - }, - primitive: { - topology: PrimitiveTopology.TriangleStrip, - stripIndexFormat: IndexFormat.Uint16, - }, - }); - pipelineAndBGL = this._videoPipelines[format][index] = [pipeline, pipeline.getBindGroupLayout(0)]; - } - return pipelineAndBGL; - } - static _GetTextureTypeFromFormat(format) { - switch (format) { - // One Component = 8 bits - case TextureFormat.R8Unorm: - case TextureFormat.R8Snorm: - case TextureFormat.R8Uint: - case TextureFormat.R8Sint: - case TextureFormat.RG8Unorm: - case TextureFormat.RG8Snorm: - case TextureFormat.RG8Uint: - case TextureFormat.RG8Sint: - case TextureFormat.RGBA8Unorm: - case TextureFormat.RGBA8UnormSRGB: - case TextureFormat.RGBA8Snorm: - case TextureFormat.RGBA8Uint: - case TextureFormat.RGBA8Sint: - case TextureFormat.BGRA8Unorm: - case TextureFormat.BGRA8UnormSRGB: - case TextureFormat.RGB10A2Unorm: // composite format - let's say it's byte... - case TextureFormat.RGB9E5UFloat: // composite format - let's say it's byte... - case TextureFormat.RG11B10UFloat: // composite format - let's say it's byte... - case TextureFormat.Depth24UnormStencil8: // composite format - let's say it's byte... - case TextureFormat.Depth32FloatStencil8: // composite format - let's say it's byte... - case TextureFormat.BC7RGBAUnorm: - case TextureFormat.BC7RGBAUnormSRGB: - case TextureFormat.BC6HRGBUFloat: - case TextureFormat.BC6HRGBFloat: - case TextureFormat.BC5RGUnorm: - case TextureFormat.BC5RGSnorm: - case TextureFormat.BC3RGBAUnorm: - case TextureFormat.BC3RGBAUnormSRGB: - case TextureFormat.BC2RGBAUnorm: - case TextureFormat.BC2RGBAUnormSRGB: - case TextureFormat.BC4RUnorm: - case TextureFormat.BC4RSnorm: - case TextureFormat.BC1RGBAUnorm: - case TextureFormat.BC1RGBAUnormSRGB: - case TextureFormat.ETC2RGB8Unorm: - case TextureFormat.ETC2RGB8UnormSRGB: - case TextureFormat.ETC2RGB8A1Unorm: - case TextureFormat.ETC2RGB8A1UnormSRGB: - case TextureFormat.ETC2RGBA8Unorm: - case TextureFormat.ETC2RGBA8UnormSRGB: - case TextureFormat.EACR11Unorm: - case TextureFormat.EACR11Snorm: - case TextureFormat.EACRG11Unorm: - case TextureFormat.EACRG11Snorm: - case TextureFormat.ASTC4x4Unorm: - case TextureFormat.ASTC4x4UnormSRGB: - case TextureFormat.ASTC5x4Unorm: - case TextureFormat.ASTC5x4UnormSRGB: - case TextureFormat.ASTC5x5Unorm: - case TextureFormat.ASTC5x5UnormSRGB: - case TextureFormat.ASTC6x5Unorm: - case TextureFormat.ASTC6x5UnormSRGB: - case TextureFormat.ASTC6x6Unorm: - case TextureFormat.ASTC6x6UnormSRGB: - case TextureFormat.ASTC8x5Unorm: - case TextureFormat.ASTC8x5UnormSRGB: - case TextureFormat.ASTC8x6Unorm: - case TextureFormat.ASTC8x6UnormSRGB: - case TextureFormat.ASTC8x8Unorm: - case TextureFormat.ASTC8x8UnormSRGB: - case TextureFormat.ASTC10x5Unorm: - case TextureFormat.ASTC10x5UnormSRGB: - case TextureFormat.ASTC10x6Unorm: - case TextureFormat.ASTC10x6UnormSRGB: - case TextureFormat.ASTC10x8Unorm: - case TextureFormat.ASTC10x8UnormSRGB: - case TextureFormat.ASTC10x10Unorm: - case TextureFormat.ASTC10x10UnormSRGB: - case TextureFormat.ASTC12x10Unorm: - case TextureFormat.ASTC12x10UnormSRGB: - case TextureFormat.ASTC12x12Unorm: - case TextureFormat.ASTC12x12UnormSRGB: - return 0; - // One component = 16 bits - case TextureFormat.R16Uint: - case TextureFormat.R16Sint: - case TextureFormat.RG16Uint: - case TextureFormat.RG16Sint: - case TextureFormat.RGBA16Uint: - case TextureFormat.RGBA16Sint: - case TextureFormat.Depth16Unorm: - return 5; - case TextureFormat.R16Float: - case TextureFormat.RG16Float: - case TextureFormat.RGBA16Float: - return 2; - // One component = 32 bits - case TextureFormat.R32Uint: - case TextureFormat.R32Sint: - case TextureFormat.RG32Uint: - case TextureFormat.RG32Sint: - case TextureFormat.RGBA32Uint: - case TextureFormat.RGBA32Sint: - return 7; - case TextureFormat.R32Float: - case TextureFormat.RG32Float: - case TextureFormat.RGBA32Float: - case TextureFormat.Depth32Float: - return 1; - case TextureFormat.Stencil8: - throw "No fixed size for Stencil8 format!"; - case TextureFormat.Depth24Plus: - throw "No fixed size for Depth24Plus format!"; - case TextureFormat.Depth24PlusStencil8: - throw "No fixed size for Depth24PlusStencil8 format!"; - } - return 0; - } - static _GetBlockInformationFromFormat(format) { - switch (format) { - // 8 bits formats - case TextureFormat.R8Unorm: - case TextureFormat.R8Snorm: - case TextureFormat.R8Uint: - case TextureFormat.R8Sint: - return { width: 1, height: 1, length: 1 }; - // 16 bits formats - case TextureFormat.R16Uint: - case TextureFormat.R16Sint: - case TextureFormat.R16Float: - case TextureFormat.RG8Unorm: - case TextureFormat.RG8Snorm: - case TextureFormat.RG8Uint: - case TextureFormat.RG8Sint: - return { width: 1, height: 1, length: 2 }; - // 32 bits formats - case TextureFormat.R32Uint: - case TextureFormat.R32Sint: - case TextureFormat.R32Float: - case TextureFormat.RG16Uint: - case TextureFormat.RG16Sint: - case TextureFormat.RG16Float: - case TextureFormat.RGBA8Unorm: - case TextureFormat.RGBA8UnormSRGB: - case TextureFormat.RGBA8Snorm: - case TextureFormat.RGBA8Uint: - case TextureFormat.RGBA8Sint: - case TextureFormat.BGRA8Unorm: - case TextureFormat.BGRA8UnormSRGB: - case TextureFormat.RGB9E5UFloat: - case TextureFormat.RGB10A2Unorm: - case TextureFormat.RG11B10UFloat: - return { width: 1, height: 1, length: 4 }; - // 64 bits formats - case TextureFormat.RG32Uint: - case TextureFormat.RG32Sint: - case TextureFormat.RG32Float: - case TextureFormat.RGBA16Uint: - case TextureFormat.RGBA16Sint: - case TextureFormat.RGBA16Float: - return { width: 1, height: 1, length: 8 }; - // 128 bits formats - case TextureFormat.RGBA32Uint: - case TextureFormat.RGBA32Sint: - case TextureFormat.RGBA32Float: - return { width: 1, height: 1, length: 16 }; - // Depth and stencil formats - case TextureFormat.Stencil8: - throw "No fixed size for Stencil8 format!"; - case TextureFormat.Depth16Unorm: - return { width: 1, height: 1, length: 2 }; - case TextureFormat.Depth24Plus: - throw "No fixed size for Depth24Plus format!"; - case TextureFormat.Depth24PlusStencil8: - throw "No fixed size for Depth24PlusStencil8 format!"; - case TextureFormat.Depth32Float: - return { width: 1, height: 1, length: 4 }; - case TextureFormat.Depth24UnormStencil8: - return { width: 1, height: 1, length: 4 }; - case TextureFormat.Depth32FloatStencil8: - return { width: 1, height: 1, length: 5 }; - // BC compressed formats usable if "texture-compression-bc" is both - // supported by the device/user agent and enabled in requestDevice. - case TextureFormat.BC7RGBAUnorm: - case TextureFormat.BC7RGBAUnormSRGB: - case TextureFormat.BC6HRGBUFloat: - case TextureFormat.BC6HRGBFloat: - case TextureFormat.BC5RGUnorm: - case TextureFormat.BC5RGSnorm: - case TextureFormat.BC3RGBAUnorm: - case TextureFormat.BC3RGBAUnormSRGB: - case TextureFormat.BC2RGBAUnorm: - case TextureFormat.BC2RGBAUnormSRGB: - return { width: 4, height: 4, length: 16 }; - case TextureFormat.BC4RUnorm: - case TextureFormat.BC4RSnorm: - case TextureFormat.BC1RGBAUnorm: - case TextureFormat.BC1RGBAUnormSRGB: - return { width: 4, height: 4, length: 8 }; - // ETC2 compressed formats usable if "texture-compression-etc2" is both - // supported by the device/user agent and enabled in requestDevice. - case TextureFormat.ETC2RGB8Unorm: - case TextureFormat.ETC2RGB8UnormSRGB: - case TextureFormat.ETC2RGB8A1Unorm: - case TextureFormat.ETC2RGB8A1UnormSRGB: - case TextureFormat.EACR11Unorm: - case TextureFormat.EACR11Snorm: - return { width: 4, height: 4, length: 8 }; - case TextureFormat.ETC2RGBA8Unorm: - case TextureFormat.ETC2RGBA8UnormSRGB: - case TextureFormat.EACRG11Unorm: - case TextureFormat.EACRG11Snorm: - return { width: 4, height: 4, length: 16 }; - // ASTC compressed formats usable if "texture-compression-astc" is both - // supported by the device/user agent and enabled in requestDevice. - case TextureFormat.ASTC4x4Unorm: - case TextureFormat.ASTC4x4UnormSRGB: - return { width: 4, height: 4, length: 16 }; - case TextureFormat.ASTC5x4Unorm: - case TextureFormat.ASTC5x4UnormSRGB: - return { width: 5, height: 4, length: 16 }; - case TextureFormat.ASTC5x5Unorm: - case TextureFormat.ASTC5x5UnormSRGB: - return { width: 5, height: 5, length: 16 }; - case TextureFormat.ASTC6x5Unorm: - case TextureFormat.ASTC6x5UnormSRGB: - return { width: 6, height: 5, length: 16 }; - case TextureFormat.ASTC6x6Unorm: - case TextureFormat.ASTC6x6UnormSRGB: - return { width: 6, height: 6, length: 16 }; - case TextureFormat.ASTC8x5Unorm: - case TextureFormat.ASTC8x5UnormSRGB: - return { width: 8, height: 5, length: 16 }; - case TextureFormat.ASTC8x6Unorm: - case TextureFormat.ASTC8x6UnormSRGB: - return { width: 8, height: 6, length: 16 }; - case TextureFormat.ASTC8x8Unorm: - case TextureFormat.ASTC8x8UnormSRGB: - return { width: 8, height: 8, length: 16 }; - case TextureFormat.ASTC10x5Unorm: - case TextureFormat.ASTC10x5UnormSRGB: - return { width: 10, height: 5, length: 16 }; - case TextureFormat.ASTC10x6Unorm: - case TextureFormat.ASTC10x6UnormSRGB: - return { width: 10, height: 6, length: 16 }; - case TextureFormat.ASTC10x8Unorm: - case TextureFormat.ASTC10x8UnormSRGB: - return { width: 10, height: 8, length: 16 }; - case TextureFormat.ASTC10x10Unorm: - case TextureFormat.ASTC10x10UnormSRGB: - return { width: 10, height: 10, length: 16 }; - case TextureFormat.ASTC12x10Unorm: - case TextureFormat.ASTC12x10UnormSRGB: - return { width: 12, height: 10, length: 16 }; - case TextureFormat.ASTC12x12Unorm: - case TextureFormat.ASTC12x12UnormSRGB: - return { width: 12, height: 12, length: 16 }; - } - return { width: 1, height: 1, length: 4 }; - } - static _IsHardwareTexture(texture) { - return !!texture.release; - } - static _IsInternalTexture(texture) { - return !!texture.dispose; - } - static IsImageBitmap(imageBitmap) { - return imageBitmap.close !== undefined; - } - static IsImageBitmapArray(imageBitmap) { - return Array.isArray(imageBitmap) && imageBitmap[0].close !== undefined; - } - setCommandEncoder(encoder) { - this._commandEncoderForCreation = encoder; - } - static IsCompressedFormat(format) { - switch (format) { - case TextureFormat.BC7RGBAUnormSRGB: - case TextureFormat.BC7RGBAUnorm: - case TextureFormat.BC6HRGBFloat: - case TextureFormat.BC6HRGBUFloat: - case TextureFormat.BC5RGSnorm: - case TextureFormat.BC5RGUnorm: - case TextureFormat.BC4RSnorm: - case TextureFormat.BC4RUnorm: - case TextureFormat.BC3RGBAUnormSRGB: - case TextureFormat.BC3RGBAUnorm: - case TextureFormat.BC2RGBAUnormSRGB: - case TextureFormat.BC2RGBAUnorm: - case TextureFormat.BC1RGBAUnormSRGB: - case TextureFormat.BC1RGBAUnorm: - case TextureFormat.ETC2RGB8Unorm: - case TextureFormat.ETC2RGB8UnormSRGB: - case TextureFormat.ETC2RGB8A1Unorm: - case TextureFormat.ETC2RGB8A1UnormSRGB: - case TextureFormat.ETC2RGBA8Unorm: - case TextureFormat.ETC2RGBA8UnormSRGB: - case TextureFormat.EACR11Unorm: - case TextureFormat.EACR11Snorm: - case TextureFormat.EACRG11Unorm: - case TextureFormat.EACRG11Snorm: - case TextureFormat.ASTC4x4Unorm: - case TextureFormat.ASTC4x4UnormSRGB: - case TextureFormat.ASTC5x4Unorm: - case TextureFormat.ASTC5x4UnormSRGB: - case TextureFormat.ASTC5x5Unorm: - case TextureFormat.ASTC5x5UnormSRGB: - case TextureFormat.ASTC6x5Unorm: - case TextureFormat.ASTC6x5UnormSRGB: - case TextureFormat.ASTC6x6Unorm: - case TextureFormat.ASTC6x6UnormSRGB: - case TextureFormat.ASTC8x5Unorm: - case TextureFormat.ASTC8x5UnormSRGB: - case TextureFormat.ASTC8x6Unorm: - case TextureFormat.ASTC8x6UnormSRGB: - case TextureFormat.ASTC8x8Unorm: - case TextureFormat.ASTC8x8UnormSRGB: - case TextureFormat.ASTC10x5Unorm: - case TextureFormat.ASTC10x5UnormSRGB: - case TextureFormat.ASTC10x6Unorm: - case TextureFormat.ASTC10x6UnormSRGB: - case TextureFormat.ASTC10x8Unorm: - case TextureFormat.ASTC10x8UnormSRGB: - case TextureFormat.ASTC10x10Unorm: - case TextureFormat.ASTC10x10UnormSRGB: - case TextureFormat.ASTC12x10Unorm: - case TextureFormat.ASTC12x10UnormSRGB: - case TextureFormat.ASTC12x12Unorm: - case TextureFormat.ASTC12x12UnormSRGB: - return true; - } - return false; - } - static GetWebGPUTextureFormat(type, format, useSRGBBuffer = false) { - switch (format) { - case 15: - return TextureFormat.Depth16Unorm; - case 16: - return TextureFormat.Depth24Plus; - case 13: - return TextureFormat.Depth24PlusStencil8; - case 14: - return TextureFormat.Depth32Float; - case 17: - return TextureFormat.Depth24UnormStencil8; - case 18: - return TextureFormat.Depth32FloatStencil8; - case 19: - return TextureFormat.Stencil8; - case 36492: - return useSRGBBuffer ? TextureFormat.BC7RGBAUnormSRGB : TextureFormat.BC7RGBAUnorm; - case 36495: - return TextureFormat.BC6HRGBUFloat; - case 36494: - return TextureFormat.BC6HRGBFloat; - case 33779: - return useSRGBBuffer ? TextureFormat.BC3RGBAUnormSRGB : TextureFormat.BC3RGBAUnorm; - case 33778: - return useSRGBBuffer ? TextureFormat.BC2RGBAUnormSRGB : TextureFormat.BC2RGBAUnorm; - case 33777: - case 33776: - return useSRGBBuffer ? TextureFormat.BC1RGBAUnormSRGB : TextureFormat.BC1RGBAUnorm; - case 37808: - return useSRGBBuffer ? TextureFormat.ASTC4x4UnormSRGB : TextureFormat.ASTC4x4Unorm; - case 36196: - case 37492: - return useSRGBBuffer ? TextureFormat.ETC2RGB8UnormSRGB : TextureFormat.ETC2RGB8Unorm; - case 37496: - return useSRGBBuffer ? TextureFormat.ETC2RGBA8UnormSRGB : TextureFormat.ETC2RGBA8Unorm; - } - switch (type) { - case 3: - switch (format) { - case 6: - return TextureFormat.R8Snorm; - case 7: - return TextureFormat.RG8Snorm; - case 4: - throw "RGB format not supported in WebGPU"; - case 8: - return TextureFormat.R8Sint; - case 9: - return TextureFormat.RG8Sint; - case 10: - throw "RGB_INTEGER format not supported in WebGPU"; - case 11: - return TextureFormat.RGBA8Sint; - default: - return TextureFormat.RGBA8Snorm; - } - case 0: - switch (format) { - case 6: - return TextureFormat.R8Unorm; - case 7: - return TextureFormat.RG8Unorm; - case 4: - throw "TEXTUREFORMAT_RGB format not supported in WebGPU"; - case 5: - return useSRGBBuffer ? TextureFormat.RGBA8UnormSRGB : TextureFormat.RGBA8Unorm; - case 12: - return useSRGBBuffer ? TextureFormat.BGRA8UnormSRGB : TextureFormat.BGRA8Unorm; - case 8: - return TextureFormat.R8Uint; - case 9: - return TextureFormat.RG8Uint; - case 10: - throw "RGB_INTEGER format not supported in WebGPU"; - case 11: - return TextureFormat.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 TextureFormat.RGBA8Unorm; - } - case 4: - switch (format) { - case 8: - return TextureFormat.R16Sint; - case 9: - return TextureFormat.RG16Sint; - case 10: - throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU"; - case 11: - return TextureFormat.RGBA16Sint; - default: - return TextureFormat.RGBA16Sint; - } - case 5: - switch (format) { - case 8: - return TextureFormat.R16Uint; - case 9: - return TextureFormat.RG16Uint; - case 10: - throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU"; - case 11: - return TextureFormat.RGBA16Uint; - default: - return TextureFormat.RGBA16Uint; - } - case 6: - switch (format) { - case 8: - return TextureFormat.R32Sint; - case 9: - return TextureFormat.RG32Sint; - case 10: - throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU"; - case 11: - return TextureFormat.RGBA32Sint; - default: - return TextureFormat.RGBA32Sint; - } - case 7: // Refers to UNSIGNED_INT - switch (format) { - case 8: - return TextureFormat.R32Uint; - case 9: - return TextureFormat.RG32Uint; - case 10: - throw "TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU"; - case 11: - return TextureFormat.RGBA32Uint; - default: - return TextureFormat.RGBA32Uint; - } - case 1: - switch (format) { - case 6: - return TextureFormat.R32Float; // By default. Other possibility is R16Float. - case 7: - return TextureFormat.RG32Float; // By default. Other possibility is RG16Float. - case 4: - throw "TEXTUREFORMAT_RGB format not supported in WebGPU"; - case 5: - return TextureFormat.RGBA32Float; // By default. Other possibility is RGBA16Float. - default: - return TextureFormat.RGBA32Float; - } - case 2: - switch (format) { - case 6: - return TextureFormat.R16Float; - case 7: - return TextureFormat.RG16Float; - case 4: - throw "TEXTUREFORMAT_RGB format not supported in WebGPU"; - case 5: - return TextureFormat.RGBA16Float; - default: - return TextureFormat.RGBA16Float; - } - case 10: - throw "TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU"; - case 13: - switch (format) { - case 5: - return TextureFormat.RG11B10UFloat; - case 11: - throw "TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"; - default: - return TextureFormat.RG11B10UFloat; - } - case 14: - switch (format) { - case 5: - return TextureFormat.RGB9E5UFloat; - case 11: - throw "TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"; - default: - return TextureFormat.RGB9E5UFloat; - } - case 8: - throw "TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU"; - case 9: - throw "TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU"; - case 11: - switch (format) { - case 5: - return TextureFormat.RGB10A2Unorm; - case 11: - throw "TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV"; - default: - return TextureFormat.RGB10A2Unorm; - } - } - return useSRGBBuffer ? TextureFormat.RGBA8UnormSRGB : TextureFormat.RGBA8Unorm; - } - static GetNumChannelsFromWebGPUTextureFormat(format) { - switch (format) { - case TextureFormat.R8Unorm: - case TextureFormat.R8Snorm: - case TextureFormat.R8Uint: - case TextureFormat.R8Sint: - case TextureFormat.BC4RUnorm: - case TextureFormat.BC4RSnorm: - case TextureFormat.R16Uint: - case TextureFormat.R16Sint: - case TextureFormat.Depth16Unorm: - case TextureFormat.R16Float: - case TextureFormat.R32Uint: - case TextureFormat.R32Sint: - case TextureFormat.R32Float: - case TextureFormat.Depth32Float: - case TextureFormat.Stencil8: - case TextureFormat.Depth24Plus: - case TextureFormat.EACR11Unorm: - case TextureFormat.EACR11Snorm: - return 1; - case TextureFormat.RG8Unorm: - case TextureFormat.RG8Snorm: - case TextureFormat.RG8Uint: - case TextureFormat.RG8Sint: - case TextureFormat.Depth24UnormStencil8: // composite format - let's say it's byte... - case TextureFormat.Depth32FloatStencil8: // composite format - let's say it's byte... - case TextureFormat.BC5RGUnorm: - case TextureFormat.BC5RGSnorm: - case TextureFormat.RG16Uint: - case TextureFormat.RG16Sint: - case TextureFormat.RG16Float: - case TextureFormat.RG32Uint: - case TextureFormat.RG32Sint: - case TextureFormat.RG32Float: - case TextureFormat.Depth24PlusStencil8: - case TextureFormat.EACRG11Unorm: - case TextureFormat.EACRG11Snorm: - return 2; - case TextureFormat.RGB9E5UFloat: // composite format - let's say it's byte... - case TextureFormat.RG11B10UFloat: // composite format - let's say it's byte... - case TextureFormat.BC6HRGBUFloat: - case TextureFormat.BC6HRGBFloat: - case TextureFormat.ETC2RGB8Unorm: - case TextureFormat.ETC2RGB8UnormSRGB: - return 3; - case TextureFormat.RGBA8Unorm: - case TextureFormat.RGBA8UnormSRGB: - case TextureFormat.RGBA8Snorm: - case TextureFormat.RGBA8Uint: - case TextureFormat.RGBA8Sint: - case TextureFormat.BGRA8Unorm: - case TextureFormat.BGRA8UnormSRGB: - case TextureFormat.RGB10A2Unorm: // composite format - let's say it's byte... - case TextureFormat.BC7RGBAUnorm: - case TextureFormat.BC7RGBAUnormSRGB: - case TextureFormat.BC3RGBAUnorm: - case TextureFormat.BC3RGBAUnormSRGB: - case TextureFormat.BC2RGBAUnorm: - case TextureFormat.BC2RGBAUnormSRGB: - case TextureFormat.BC1RGBAUnorm: - case TextureFormat.BC1RGBAUnormSRGB: - case TextureFormat.RGBA16Uint: - case TextureFormat.RGBA16Sint: - case TextureFormat.RGBA16Float: - case TextureFormat.RGBA32Uint: - case TextureFormat.RGBA32Sint: - case TextureFormat.RGBA32Float: - case TextureFormat.ETC2RGB8A1Unorm: - case TextureFormat.ETC2RGB8A1UnormSRGB: - case TextureFormat.ETC2RGBA8Unorm: - case TextureFormat.ETC2RGBA8UnormSRGB: - case TextureFormat.ASTC4x4Unorm: - case TextureFormat.ASTC4x4UnormSRGB: - case TextureFormat.ASTC5x4Unorm: - case TextureFormat.ASTC5x4UnormSRGB: - case TextureFormat.ASTC5x5Unorm: - case TextureFormat.ASTC5x5UnormSRGB: - case TextureFormat.ASTC6x5Unorm: - case TextureFormat.ASTC6x5UnormSRGB: - case TextureFormat.ASTC6x6Unorm: - case TextureFormat.ASTC6x6UnormSRGB: - case TextureFormat.ASTC8x5Unorm: - case TextureFormat.ASTC8x5UnormSRGB: - case TextureFormat.ASTC8x6Unorm: - case TextureFormat.ASTC8x6UnormSRGB: - case TextureFormat.ASTC8x8Unorm: - case TextureFormat.ASTC8x8UnormSRGB: - case TextureFormat.ASTC10x5Unorm: - case TextureFormat.ASTC10x5UnormSRGB: - case TextureFormat.ASTC10x6Unorm: - case TextureFormat.ASTC10x6UnormSRGB: - case TextureFormat.ASTC10x8Unorm: - case TextureFormat.ASTC10x8UnormSRGB: - case TextureFormat.ASTC10x10Unorm: - case TextureFormat.ASTC10x10UnormSRGB: - case TextureFormat.ASTC12x10Unorm: - case TextureFormat.ASTC12x10UnormSRGB: - case TextureFormat.ASTC12x12Unorm: - case TextureFormat.ASTC12x12UnormSRGB: - return 4; - } - throw `Unknown format ${format}!`; - } - static HasStencilAspect(format) { - switch (format) { - case TextureFormat.Stencil8: - case TextureFormat.Depth24UnormStencil8: - case TextureFormat.Depth32FloatStencil8: - case TextureFormat.Depth24PlusStencil8: - return true; - } - return false; - } - static HasDepthAndStencilAspects(format) { - switch (format) { - case TextureFormat.Depth24UnormStencil8: - case TextureFormat.Depth32FloatStencil8: - case TextureFormat.Depth24PlusStencil8: - return true; - } - return false; - } - static GetDepthFormatOnly(format) { - switch (format) { - case TextureFormat.Depth16Unorm: - return TextureFormat.Depth16Unorm; - case TextureFormat.Depth24Plus: - return TextureFormat.Depth24Plus; - case TextureFormat.Depth24PlusStencil8: - return TextureFormat.Depth24Plus; - case TextureFormat.Depth24UnormStencil8: - return TextureFormat.Depth24Plus; - case TextureFormat.Depth32Float: - return TextureFormat.Depth32Float; - case TextureFormat.Depth32FloatStencil8: - return TextureFormat.Depth32Float; - } - return format; - } - copyVideoToTexture(video, texture, format, invertY = false, commandEncoder) { - var _a, _b, _c, _d; - const useOwnCommandEncoder = commandEncoder === undefined; - const [pipeline, bindGroupLayout] = this._getVideoPipeline(format, invertY ? VideoPipelineType.InvertY : VideoPipelineType.DontInvertY); - if (useOwnCommandEncoder) { - commandEncoder = this._device.createCommandEncoder({}); - } - (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `copy video to texture - invertY=${invertY}`); - const webgpuHardwareTexture = texture._hardwareTexture; - const renderPassDescriptor = { - colorAttachments: [ - { - view: webgpuHardwareTexture.underlyingResource.createView({ - format, - dimension: TextureViewDimension.E2d, - mipLevelCount: 1, - baseArrayLayer: 0, - baseMipLevel: 0, - arrayLayerCount: 1, - aspect: TextureAspect.All, - }), - loadOp: LoadOp.Load, - storeOp: StoreOp.Store, - }, - ], - }; - const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); - const descriptor = { - layout: bindGroupLayout, - entries: [ - { - binding: 0, - resource: this._videoSampler, - }, - { - binding: 1, - resource: this._device.importExternalTexture({ - source: video.underlyingResource, - }), - }, - ], - }; - const bindGroup = this._device.createBindGroup(descriptor); - passEncoder.setPipeline(pipeline); - passEncoder.setBindGroup(0, bindGroup); - passEncoder.draw(4, 1, 0, 0); - passEncoder.end(); - (_d = (_c = commandEncoder).popDebugGroup) === null || _d === void 0 ? void 0 : _d.call(_c); - if (useOwnCommandEncoder) { - this._device.queue.submit([commandEncoder.finish()]); - commandEncoder = null; - } - } - invertYPreMultiplyAlpha(gpuOrHdwTexture, width, height, format, invertY = false, premultiplyAlpha = false, faceIndex = 0, mipLevel = 0, layers = 1, ofstX = 0, ofstY = 0, rectWidth = 0, rectHeight = 0, commandEncoder, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - allowGPUOptimization) { - var _a, _b, _c, _d, _e, _f; - const useRect = rectWidth !== 0; - const useOwnCommandEncoder = commandEncoder === undefined; - const [pipeline, bindGroupLayout] = this._getPipeline(format, useRect ? PipelineType.InvertYPremultiplyAlphaWithOfst : PipelineType.InvertYPremultiplyAlpha, { - invertY, - premultiplyAlpha, - }); - faceIndex = Math.max(faceIndex, 0); - if (useOwnCommandEncoder) { - commandEncoder = this._device.createCommandEncoder({}); - } - (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `internal process texture - invertY=${invertY} premultiplyAlpha=${premultiplyAlpha}`); - let gpuTexture; - if (WebGPUTextureHelper._IsHardwareTexture(gpuOrHdwTexture)) { - gpuTexture = gpuOrHdwTexture.underlyingResource; - if (!(invertY && !premultiplyAlpha && layers === 1 && faceIndex === 0)) { - // we optimize only for the most likely case (invertY=true, premultiplyAlpha=false, layers=1, faceIndex=0) to avoid dealing with big caches - gpuOrHdwTexture = undefined; - } - } - else { - gpuTexture = gpuOrHdwTexture; - gpuOrHdwTexture = undefined; - } - if (!gpuTexture) { - return; - } - if (useRect) { - this._bufferManager.setRawData(this._ubCopyWithOfst, 0, new Float32Array([ofstX, ofstY, rectWidth, rectHeight]), 0, 4 * 4); - } - const webgpuHardwareTexture = gpuOrHdwTexture; - 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, TextureUsage.CopySrc | TextureUsage.RenderAttachment | TextureUsage.TextureBinding, undefined, "TempTextureForCopyWithInvertY"); - const renderPassDescriptor = (_d = webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYRenderPassDescr) !== null && _d !== void 0 ? _d : { - colorAttachments: [ - { - view: outputTexture.createView({ - format, - dimension: TextureViewDimension.E2d, - baseMipLevel: 0, - mipLevelCount: 1, - arrayLayerCount: 1, - baseArrayLayer: 0, - }), - loadOp: LoadOp.Load, - storeOp: StoreOp.Store, - }, - ], - }; - const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); - let bindGroup = useRect ? webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYBindGroupWithOfst : webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYBindGroup; - if (!bindGroup) { - const descriptor = { - layout: bindGroupLayout, - entries: [ - { - binding: 0, - resource: gpuTexture.createView({ - format, - dimension: TextureViewDimension.E2d, - baseMipLevel: mipLevel, - mipLevelCount: 1, - arrayLayerCount: layers, - baseArrayLayer: faceIndex, - }), - }, - ], - }; - if (useRect) { - descriptor.entries.push({ - binding: 1, - resource: { - buffer: this._ubCopyWithOfst, - }, - }); - } - bindGroup = this._device.createBindGroup(descriptor); - } - passEncoder.setPipeline(pipeline); - passEncoder.setBindGroup(0, bindGroup); - passEncoder.draw(4, 1, 0, 0); - passEncoder.end(); - commandEncoder.copyTextureToTexture({ - texture: outputTexture, - }, { - texture: gpuTexture, - mipLevel, - origin: { - x: 0, - y: 0, - z: faceIndex, - }, - }, { - width, - height, - depthOrArrayLayers: 1, - }); - if (webgpuHardwareTexture) { - webgpuHardwareTexture._copyInvertYTempTexture = outputTexture; - webgpuHardwareTexture._copyInvertYRenderPassDescr = renderPassDescriptor; - if (useRect) { - webgpuHardwareTexture._copyInvertYBindGroupWithOfst = bindGroup; - } - else { - webgpuHardwareTexture._copyInvertYBindGroup = bindGroup; - } - } - else { - this._deferredReleaseTextures.push([outputTexture, null]); - } - (_f = (_e = commandEncoder).popDebugGroup) === null || _f === void 0 ? void 0 : _f.call(_e); - if (useOwnCommandEncoder) { - this._device.queue.submit([commandEncoder.finish()]); - commandEncoder = null; - } - } - copyWithInvertY(srcTextureView, format, renderPassDescriptor, commandEncoder) { - var _a, _b, _c, _d; - const useOwnCommandEncoder = commandEncoder === undefined; - const [pipeline, bindGroupLayout] = this._getPipeline(format, PipelineType.InvertYPremultiplyAlpha, { invertY: true, premultiplyAlpha: false }); - if (useOwnCommandEncoder) { - commandEncoder = this._device.createCommandEncoder({}); - } - (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `internal copy texture with invertY`); - const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); - const bindGroup = this._device.createBindGroup({ - layout: bindGroupLayout, - entries: [ - { - binding: 0, - resource: srcTextureView, - }, - ], - }); - passEncoder.setPipeline(pipeline); - passEncoder.setBindGroup(0, bindGroup); - passEncoder.draw(4, 1, 0, 0); - passEncoder.end(); - (_d = (_c = commandEncoder).popDebugGroup) === null || _d === void 0 ? void 0 : _d.call(_c); - if (useOwnCommandEncoder) { - this._device.queue.submit([commandEncoder.finish()]); - commandEncoder = null; - } - } - //------------------------------------------------------------------------------ - // Creation - //------------------------------------------------------------------------------ - createTexture(imageBitmap, hasMipmaps = false, generateMipmaps = false, invertY = false, premultiplyAlpha = false, is3D = false, format = TextureFormat.RGBA8Unorm, sampleCount = 1, commandEncoder, usage = -1, additionalUsages = 0, label) { - if (sampleCount > 1) { - // WebGPU only supports 1 or 4 - sampleCount = 4; - } - const layerCount = imageBitmap.layers || 1; - const textureSize = { - width: imageBitmap.width, - height: imageBitmap.height, - depthOrArrayLayers: layerCount, - }; - const renderAttachmentFlag = renderableTextureFormatToIndex[format] ? TextureUsage.RenderAttachment : 0; - const isCompressedFormat = WebGPUTextureHelper.IsCompressedFormat(format); - const mipLevelCount = hasMipmaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(imageBitmap.width, imageBitmap.height) : 1; - const usages = usage >= 0 ? usage : TextureUsage.CopySrc | TextureUsage.CopyDst | TextureUsage.TextureBinding; - additionalUsages |= hasMipmaps && !isCompressedFormat ? TextureUsage.CopySrc | renderAttachmentFlag : 0; - if (!isCompressedFormat && !is3D) { - // 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 - additionalUsages |= renderAttachmentFlag | TextureUsage.CopyDst; - } - const gpuTexture = this._device.createTexture({ - label: `Texture${is3D ? "3D" : "2D"}_${label ? label + "_" : ""}${textureSize.width}x${textureSize.height}x${textureSize.depthOrArrayLayers}_${hasMipmaps ? "wmips" : "womips"}_${format}_samples${sampleCount}`, - size: textureSize, - dimension: is3D ? TextureDimension.E3d : TextureDimension.E2d, - format, - usage: usages | additionalUsages, - sampleCount, - mipLevelCount, - }); - if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) { - this.updateTexture(imageBitmap, gpuTexture, imageBitmap.width, imageBitmap.height, layerCount, format, 0, 0, invertY, premultiplyAlpha, 0, 0); - if (hasMipmaps && generateMipmaps) { - this.generateMipmaps(gpuTexture, format, mipLevelCount, 0, commandEncoder); - } - } - return gpuTexture; - } - createCubeTexture(imageBitmaps, hasMipmaps = false, generateMipmaps = false, invertY = false, premultiplyAlpha = false, format = TextureFormat.RGBA8Unorm, sampleCount = 1, commandEncoder, usage = -1, additionalUsages = 0, label) { - if (sampleCount > 1) { - // WebGPU only supports 1 or 4 - sampleCount = 4; - } - const width = WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps) ? imageBitmaps[0].width : imageBitmaps.width; - const height = WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps) ? imageBitmaps[0].height : imageBitmaps.height; - const renderAttachmentFlag = renderableTextureFormatToIndex[format] ? TextureUsage.RenderAttachment : 0; - const isCompressedFormat = WebGPUTextureHelper.IsCompressedFormat(format); - const mipLevelCount = hasMipmaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(width, height) : 1; - const usages = usage >= 0 ? usage : TextureUsage.CopySrc | TextureUsage.CopyDst | TextureUsage.TextureBinding; - additionalUsages |= hasMipmaps && !isCompressedFormat ? TextureUsage.CopySrc | renderAttachmentFlag : 0; - if (!isCompressedFormat) { - // 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 - additionalUsages |= renderAttachmentFlag | TextureUsage.CopyDst; - } - const gpuTexture = this._device.createTexture({ - label: `TextureCube_${label ? label + "_" : ""}${width}x${height}x6_${hasMipmaps ? "wmips" : "womips"}_${format}_samples${sampleCount}`, - size: { - width, - height, - depthOrArrayLayers: 6, - }, - dimension: TextureDimension.E2d, - format, - usage: usages | additionalUsages, - sampleCount, - mipLevelCount, - }); - if (WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps)) { - this.updateCubeTextures(imageBitmaps, gpuTexture, width, height, format, invertY, premultiplyAlpha, 0, 0); - if (hasMipmaps && generateMipmaps) { - this.generateCubeMipmaps(gpuTexture, format, mipLevelCount, commandEncoder); - } - } - return gpuTexture; - } - generateCubeMipmaps(gpuTexture, format, mipLevelCount, commandEncoder) { - var _a, _b, _c, _d; - const useOwnCommandEncoder = commandEncoder === undefined; - if (useOwnCommandEncoder) { - commandEncoder = this._device.createCommandEncoder({}); - } - (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `create cube mipmaps - ${mipLevelCount} levels`); - for (let f = 0; f < 6; ++f) { - this.generateMipmaps(gpuTexture, format, mipLevelCount, f, commandEncoder); - } - (_d = (_c = commandEncoder).popDebugGroup) === null || _d === void 0 ? void 0 : _d.call(_c); - if (useOwnCommandEncoder) { - this._device.queue.submit([commandEncoder.finish()]); - commandEncoder = null; - } - } - generateMipmaps(gpuOrHdwTexture, format, mipLevelCount, faceIndex = 0, commandEncoder) { - var _a, _b, _c, _d, _e, _f, _g, _h; - const useOwnCommandEncoder = commandEncoder === undefined; - const [pipeline, bindGroupLayout] = this._getPipeline(format); - faceIndex = Math.max(faceIndex, 0); - if (useOwnCommandEncoder) { - commandEncoder = this._device.createCommandEncoder({}); - } - (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `create mipmaps for face #${faceIndex} - ${mipLevelCount} levels`); - let gpuTexture; - if (WebGPUTextureHelper._IsHardwareTexture(gpuOrHdwTexture)) { - gpuTexture = gpuOrHdwTexture.underlyingResource; - gpuOrHdwTexture._mipmapGenRenderPassDescr = gpuOrHdwTexture._mipmapGenRenderPassDescr || []; - gpuOrHdwTexture._mipmapGenBindGroup = gpuOrHdwTexture._mipmapGenBindGroup || []; - } - else { - gpuTexture = gpuOrHdwTexture; - gpuOrHdwTexture = undefined; - } - if (!gpuTexture) { - return; - } - const webgpuHardwareTexture = gpuOrHdwTexture; - for (let i = 1; i < mipLevelCount; ++i) { - 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 : { - colorAttachments: [ - { - view: gpuTexture.createView({ - format, - dimension: TextureViewDimension.E2d, - baseMipLevel: i, - mipLevelCount: 1, - arrayLayerCount: 1, - baseArrayLayer: faceIndex, - }), - loadOp: LoadOp.Load, - storeOp: StoreOp.Store, - }, - ], - }; - if (webgpuHardwareTexture) { - webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex] = webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex] || []; - webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex][i - 1] = renderPassDescriptor; - } - const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); - 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({ - layout: bindGroupLayout, - entries: [ - { - binding: 0, - resource: this._mipmapSampler, - }, - { - binding: 1, - resource: gpuTexture.createView({ - format, - dimension: TextureViewDimension.E2d, - baseMipLevel: i - 1, - mipLevelCount: 1, - arrayLayerCount: 1, - baseArrayLayer: faceIndex, - }), - }, - ], - }); - if (webgpuHardwareTexture) { - webgpuHardwareTexture._mipmapGenBindGroup[faceIndex] = webgpuHardwareTexture._mipmapGenBindGroup[faceIndex] || []; - webgpuHardwareTexture._mipmapGenBindGroup[faceIndex][i - 1] = bindGroup; - } - passEncoder.setPipeline(pipeline); - passEncoder.setBindGroup(0, bindGroup); - passEncoder.draw(4, 1, 0, 0); - passEncoder.end(); - } - (_h = (_g = commandEncoder).popDebugGroup) === null || _h === void 0 ? void 0 : _h.call(_g); - if (useOwnCommandEncoder) { - this._device.queue.submit([commandEncoder.finish()]); - commandEncoder = null; - } - } - createGPUTextureForInternalTexture(texture, width, height, depth, creationFlags) { - if (!texture._hardwareTexture) { - texture._hardwareTexture = new WebGPUHardwareTexture(); - } - if (width === undefined) { - width = texture.width; - } - if (height === undefined) { - height = texture.height; - } - if (depth === undefined) { - depth = texture.depth; - } - const gpuTextureWrapper = texture._hardwareTexture; - const isStorageTexture = ((creationFlags !== null && creationFlags !== void 0 ? creationFlags : 0) & 1) !== 0; - gpuTextureWrapper.format = WebGPUTextureHelper.GetWebGPUTextureFormat(texture.type, texture.format, texture._useSRGBBuffer); - gpuTextureWrapper.textureUsages = - texture._source === internalTexture_InternalTextureSource.RenderTarget || texture.source === internalTexture_InternalTextureSource.MultiRenderTarget - ? TextureUsage.TextureBinding | TextureUsage.CopySrc | TextureUsage.RenderAttachment - : texture._source === internalTexture_InternalTextureSource.DepthStencil - ? TextureUsage.TextureBinding | TextureUsage.RenderAttachment - : -1; - gpuTextureWrapper.textureAdditionalUsages = isStorageTexture ? TextureUsage.StorageBinding : 0; - const hasMipMaps = texture.generateMipMaps; - const layerCount = depth || 1; - let mipmapCount; - if (texture._maxLodLevel !== null) { - mipmapCount = texture._maxLodLevel; - } - else { - mipmapCount = hasMipMaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(width, height) : 1; - } - if (texture.isCube) { - const gpuTexture = this.createCubeTexture({ width, height }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, gpuTextureWrapper.format, 1, this._commandEncoderForCreation, gpuTextureWrapper.textureUsages, gpuTextureWrapper.textureAdditionalUsages, texture.label); - gpuTextureWrapper.set(gpuTexture); - gpuTextureWrapper.createView({ - format: WebGPUTextureHelper.GetDepthFormatOnly(gpuTextureWrapper.format), - dimension: TextureViewDimension.Cube, - mipLevelCount: mipmapCount, - baseArrayLayer: 0, - baseMipLevel: 0, - arrayLayerCount: 6, - aspect: WebGPUTextureHelper.HasDepthAndStencilAspects(gpuTextureWrapper.format) ? TextureAspect.DepthOnly : TextureAspect.All, - }, isStorageTexture); - } - else { - 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); - gpuTextureWrapper.set(gpuTexture); - gpuTextureWrapper.createView({ - format: WebGPUTextureHelper.GetDepthFormatOnly(gpuTextureWrapper.format), - dimension: texture.is2DArray - ? TextureViewDimension.E2dArray - : texture.is3D - ? TextureDimension.E3d - : TextureViewDimension.E2d, - mipLevelCount: mipmapCount, - baseArrayLayer: 0, - baseMipLevel: 0, - arrayLayerCount: texture.is3D ? 1 : layerCount, - aspect: WebGPUTextureHelper.HasDepthAndStencilAspects(gpuTextureWrapper.format) ? TextureAspect.DepthOnly : TextureAspect.All, - }, isStorageTexture); - } - texture.width = texture.baseWidth = width; - texture.height = texture.baseHeight = height; - texture.depth = texture.baseDepth = depth; - this.createMSAATexture(texture, texture.samples); - return gpuTextureWrapper; - } - createMSAATexture(texture, samples, releaseExisting = true, index = -1) { - const gpuTextureWrapper = texture._hardwareTexture; - if (releaseExisting) { - gpuTextureWrapper === null || gpuTextureWrapper === void 0 ? void 0 : gpuTextureWrapper.releaseMSAATexture(); - } - if (!gpuTextureWrapper || (samples !== null && samples !== void 0 ? samples : 1) <= 1) { - return; - } - const width = texture.width; - const height = texture.height; - const gpuMSAATexture = this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, gpuTextureWrapper.format, samples, this._commandEncoderForCreation, TextureUsage.RenderAttachment, 0, texture.label ? "MSAA" + texture.label : undefined); - gpuTextureWrapper.setMSAATexture(gpuMSAATexture, index); - } - //------------------------------------------------------------------------------ - // Update - //------------------------------------------------------------------------------ - updateCubeTextures(imageBitmaps, gpuTexture, width, height, format, invertY = false, premultiplyAlpha = false, offsetX = 0, offsetY = 0) { - const faces = [0, 3, 1, 4, 2, 5]; - for (let f = 0; f < faces.length; ++f) { - const imageBitmap = imageBitmaps[faces[f]]; - this.updateTexture(imageBitmap, gpuTexture, width, height, 1, format, f, 0, invertY, premultiplyAlpha, offsetX, offsetY); - } - } - // TODO WEBGPU handle data source not being in the same format than the destination texture? - updateTexture(imageBitmap, texture, width, height, layers, format, faceIndex = 0, mipLevel = 0, invertY = false, premultiplyAlpha = false, offsetX = 0, offsetY = 0, allowGPUOptimization) { - const gpuTexture = WebGPUTextureHelper._IsInternalTexture(texture) ? texture._hardwareTexture.underlyingResource : texture; - const blockInformation = WebGPUTextureHelper._GetBlockInformationFromFormat(format); - const gpuOrHdwTexture = WebGPUTextureHelper._IsInternalTexture(texture) ? texture._hardwareTexture : texture; - const textureCopyView = { - texture: gpuTexture, - origin: { - x: offsetX, - y: offsetY, - z: Math.max(faceIndex, 0), - }, - mipLevel: mipLevel, - premultipliedAlpha: premultiplyAlpha, - }; - const textureExtent = { - width: Math.ceil(width / blockInformation.width) * blockInformation.width, - height: Math.ceil(height / blockInformation.height) * blockInformation.height, - depthOrArrayLayers: layers || 1, - }; - if (imageBitmap.byteLength !== undefined) { - imageBitmap = imageBitmap; - const bytesPerRow = Math.ceil(width / blockInformation.width) * blockInformation.length; - const aligned = Math.ceil(bytesPerRow / 256) * 256 === bytesPerRow; - if (aligned) { - const commandEncoder = this._device.createCommandEncoder({}); - const buffer = this._bufferManager.createRawBuffer(imageBitmap.byteLength, BufferUsage.MapWrite | BufferUsage.CopySrc, true); - const arrayBuffer = buffer.getMappedRange(); - new Uint8Array(arrayBuffer).set(imageBitmap); - buffer.unmap(); - commandEncoder.copyBufferToTexture({ - buffer: buffer, - offset: 0, - bytesPerRow, - rowsPerImage: height, - }, textureCopyView, textureExtent); - this._device.queue.submit([commandEncoder.finish()]); - this._bufferManager.releaseBuffer(buffer); - } - else { - this._device.queue.writeTexture(textureCopyView, imageBitmap, { - offset: 0, - bytesPerRow, - rowsPerImage: height, - }, textureExtent); - } - if (invertY || premultiplyAlpha) { - if (WebGPUTextureHelper._IsInternalTexture(texture)) { - const dontUseRect = offsetX === 0 && offsetY === 0 && width === texture.width && height === texture.height; - this.invertYPreMultiplyAlpha(gpuOrHdwTexture, texture.width, texture.height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, offsetX, offsetY, dontUseRect ? 0 : width, dontUseRect ? 0 : height, undefined, allowGPUOptimization); - } - else { - // we should never take this code path - throw "updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!"; - } - } - } - else { - imageBitmap = imageBitmap; - if (invertY) { - textureCopyView.premultipliedAlpha = false; // we are going to handle premultiplyAlpha ourselves - // we must preprocess the image - if (WebGPUTextureHelper._IsInternalTexture(texture) && offsetX === 0 && offsetY === 0 && width === texture.width && height === texture.height) { - // optimization when the source image is the same size than the destination texture and offsets X/Y == 0: - // we simply copy the source to the destination and we apply the preprocessing on the destination - this._device.queue.copyExternalImageToTexture({ source: imageBitmap }, textureCopyView, textureExtent); - this.invertYPreMultiplyAlpha(gpuOrHdwTexture, width, height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, 0, 0, 0, 0, undefined, allowGPUOptimization); - } - else { - // we must apply the preprocessing on the source image before copying it into the destination texture - const commandEncoder = this._device.createCommandEncoder({}); - // create a temp texture and copy the image to it - const srcTexture = this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, format, 1, commandEncoder, TextureUsage.CopySrc | TextureUsage.TextureBinding, undefined, "TempTextureForUpdateTexture"); - this._deferredReleaseTextures.push([srcTexture, null]); - textureExtent.depthOrArrayLayers = 1; - this._device.queue.copyExternalImageToTexture({ source: imageBitmap }, { texture: srcTexture }, textureExtent); - textureExtent.depthOrArrayLayers = layers || 1; - // apply the preprocessing to this temp texture - this.invertYPreMultiplyAlpha(srcTexture, width, height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, 0, 0, 0, 0, commandEncoder, allowGPUOptimization); - // copy the temp texture to the destination texture - commandEncoder.copyTextureToTexture({ texture: srcTexture }, textureCopyView, textureExtent); - this._device.queue.submit([commandEncoder.finish()]); - } - } - else { - // no preprocessing: direct copy to destination texture - this._device.queue.copyExternalImageToTexture({ source: imageBitmap }, textureCopyView, textureExtent); - } - } - } - readPixels(texture, x, y, width, height, format, faceIndex = 0, mipLevel = 0, buffer = null, noDataConversion = false) { - const blockInformation = WebGPUTextureHelper._GetBlockInformationFromFormat(format); - const bytesPerRow = Math.ceil(width / blockInformation.width) * blockInformation.length; - const bytesPerRowAligned = Math.ceil(bytesPerRow / 256) * 256; - const size = bytesPerRowAligned * height; - const gpuBuffer = this._bufferManager.createRawBuffer(size, BufferUsage.MapRead | BufferUsage.CopyDst); - const commandEncoder = this._device.createCommandEncoder({}); - commandEncoder.copyTextureToBuffer({ - texture, - mipLevel, - origin: { - x, - y, - z: Math.max(faceIndex, 0), - }, - }, { - buffer: gpuBuffer, - offset: 0, - bytesPerRow: bytesPerRowAligned, - }, { - width, - height, - depthOrArrayLayers: 1, - }); - this._device.queue.submit([commandEncoder.finish()]); - return this._bufferManager.readDataFromBuffer(gpuBuffer, size, width, height, bytesPerRow, bytesPerRowAligned, WebGPUTextureHelper._GetTextureTypeFromFormat(format), 0, buffer, true, noDataConversion); - } - //------------------------------------------------------------------------------ - // Dispose - //------------------------------------------------------------------------------ - releaseTexture(texture) { - if (WebGPUTextureHelper._IsInternalTexture(texture)) { - const hardwareTexture = texture._hardwareTexture; - const irradianceTexture = texture._irradianceTexture; - // 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 - this._deferredReleaseTextures.push([hardwareTexture, irradianceTexture]); - } - else { - this._deferredReleaseTextures.push([texture, null]); - } - } - destroyDeferredTextures() { - for (let i = 0; i < this._deferredReleaseTextures.length; ++i) { - const [hardwareTexture, irradianceTexture] = this._deferredReleaseTextures[i]; - if (hardwareTexture) { - if (WebGPUTextureHelper._IsHardwareTexture(hardwareTexture)) { - hardwareTexture.release(); - } - else { - hardwareTexture.destroy(); - } - } - irradianceTexture === null || irradianceTexture === void 0 ? void 0 : irradianceTexture.dispose(); - } - this._deferredReleaseTextures.length = 0; - } -} -//# sourceMappingURL=webgpuTextureHelper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/WebGPU/webgpuDataBuffer.js - -/** @internal */ -class WebGPUDataBuffer extends dataBuffer_DataBuffer { - constructor(resource, capacity = 0) { - super(); - this.capacity = capacity; - this._buffer = resource; - } - get underlyingResource() { - return this._buffer; - } -} -//# sourceMappingURL=webgpuDataBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuBufferManager.js - - - - - -/** @internal */ -class WebGPUBufferManager { - static _IsGPUBuffer(buffer) { - return buffer.underlyingResource === undefined; - } - constructor(device) { - this._deferredReleaseBuffers = []; - this._device = device; - } - createRawBuffer(viewOrSize, flags, mappedAtCreation = false) { - const alignedLength = viewOrSize.byteLength !== undefined ? (viewOrSize.byteLength + 3) & ~3 : (viewOrSize + 3) & ~3; // 4 bytes alignments (because of the upload which requires this) - const verticesBufferDescriptor = { - mappedAtCreation, - size: alignedLength, - usage: flags, - }; - return this._device.createBuffer(verticesBufferDescriptor); - } - createBuffer(viewOrSize, flags) { - const isView = viewOrSize.byteLength !== undefined; - const buffer = this.createRawBuffer(viewOrSize, flags); - const dataBuffer = new WebGPUDataBuffer(buffer); - dataBuffer.references = 1; - dataBuffer.capacity = isView ? viewOrSize.byteLength : viewOrSize; - if (isView) { - this.setSubData(dataBuffer, 0, viewOrSize); - } - return dataBuffer; - } - setRawData(buffer, dstByteOffset, src, srcByteOffset, byteLength) { - this._device.queue.writeBuffer(buffer, dstByteOffset, src.buffer, srcByteOffset, byteLength); - } - setSubData(dataBuffer, dstByteOffset, src, srcByteOffset = 0, byteLength = 0) { - const buffer = dataBuffer.underlyingResource; - byteLength = byteLength || src.byteLength; - byteLength = Math.min(byteLength, dataBuffer.capacity - dstByteOffset); - // After Migration to Canary - let chunkStart = src.byteOffset + srcByteOffset; - let chunkEnd = chunkStart + byteLength; - // 4 bytes alignments for upload - const alignedLength = (byteLength + 3) & ~3; - if (alignedLength !== byteLength) { - const tempView = new Uint8Array(src.buffer.slice(chunkStart, chunkEnd)); - src = new Uint8Array(alignedLength); - src.set(tempView); - srcByteOffset = 0; - chunkStart = 0; - chunkEnd = alignedLength; - byteLength = alignedLength; - } - // Chunk - const maxChunk = 1024 * 1024 * 15; - let offset = 0; - while (chunkEnd - (chunkStart + offset) > maxChunk) { - this._device.queue.writeBuffer(buffer, dstByteOffset + offset, src.buffer, chunkStart + offset, maxChunk); - offset += maxChunk; - } - this._device.queue.writeBuffer(buffer, dstByteOffset + offset, src.buffer, chunkStart + offset, byteLength - offset); - } - _getHalfFloatAsFloatRGBAArrayBuffer(dataLength, arrayBuffer, destArray) { - if (!destArray) { - destArray = new Float32Array(dataLength); - } - const srcData = new Uint16Array(arrayBuffer); - while (dataLength--) { - destArray[dataLength] = FromHalfFloat(srcData[dataLength]); - } - return destArray; - } - readDataFromBuffer(gpuBuffer, size, width, height, bytesPerRow, bytesPerRowAligned, type = 0, offset = 0, buffer = null, destroyBuffer = true, noDataConversion = false) { - const floatFormat = type === 1 ? 2 : type === 2 ? 1 : 0; - return new Promise((resolve, reject) => { - gpuBuffer.mapAsync(MapMode.Read, offset, size).then(() => { - const copyArrayBuffer = gpuBuffer.getMappedRange(offset, size); - let data = buffer; - if (noDataConversion) { - if (data === null) { - data = allocateAndCopyTypedBuffer(type, size, true, copyArrayBuffer); - } - else { - data = allocateAndCopyTypedBuffer(type, data.buffer, undefined, copyArrayBuffer); - } - } - else { - if (data === null) { - switch (floatFormat) { - case 0: // byte format - data = new Uint8Array(size); - data.set(new Uint8Array(copyArrayBuffer)); - break; - case 1: // half float - // TODO WEBGPU use computer shaders (or render pass) to make the conversion? - data = this._getHalfFloatAsFloatRGBAArrayBuffer(size / 2, copyArrayBuffer); - break; - case 2: // float - data = new Float32Array(size / 4); - data.set(new Float32Array(copyArrayBuffer)); - break; - } - } - else { - switch (floatFormat) { - case 0: // byte format - data = new Uint8Array(data.buffer); - data.set(new Uint8Array(copyArrayBuffer)); - break; - case 1: // half float - // TODO WEBGPU use computer shaders (or render pass) to make the conversion? - data = this._getHalfFloatAsFloatRGBAArrayBuffer(size / 2, copyArrayBuffer, buffer); - break; - case 2: // float - data = new Float32Array(data.buffer); - data.set(new Float32Array(copyArrayBuffer)); - break; - } - } - } - if (bytesPerRow !== bytesPerRowAligned) { - // TODO WEBGPU use computer shaders (or render pass) to build the final buffer data? - if (floatFormat === 1 && !noDataConversion) { - // half float have been converted to float above - bytesPerRow *= 2; - bytesPerRowAligned *= 2; - } - const data2 = new Uint8Array(data.buffer); - let offset = bytesPerRow, offset2 = 0; - for (let y = 1; y < height; ++y) { - offset2 = y * bytesPerRowAligned; - for (let x = 0; x < bytesPerRow; ++x) { - data2[offset++] = data2[offset2++]; - } - } - if (floatFormat !== 0 && !noDataConversion) { - data = new Float32Array(data2.buffer, 0, offset / 4); - } - else { - data = new Uint8Array(data2.buffer, 0, offset); - } - } - gpuBuffer.unmap(); - if (destroyBuffer) { - this.releaseBuffer(gpuBuffer); - } - resolve(data); - }, (reason) => reject(reason)); - }); - } - releaseBuffer(buffer) { - if (WebGPUBufferManager._IsGPUBuffer(buffer)) { - this._deferredReleaseBuffers.push(buffer); - return true; - } - buffer.references--; - if (buffer.references === 0) { - this._deferredReleaseBuffers.push(buffer.underlyingResource); - return true; - } - return false; - } - destroyDeferredBuffers() { - for (let i = 0; i < this._deferredReleaseBuffers.length; ++i) { - this._deferredReleaseBuffers[i].destroy(); - } - this._deferredReleaseBuffers.length = 0; - } -} -//# sourceMappingURL=webgpuBufferManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuRenderPassWrapper.js -/** @internal */ -class WebGPURenderPassWrapper { - constructor() { - this.colorAttachmentGPUTextures = []; - this.reset(); - } - reset(fullReset = false) { - this.renderPass = null; - if (fullReset) { - this.renderPassDescriptor = null; - this.colorAttachmentViewDescriptor = null; - this.depthAttachmentViewDescriptor = null; - this.colorAttachmentGPUTextures = []; - this.depthTextureFormat = undefined; - } - } -} -//# sourceMappingURL=webgpuRenderPassWrapper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheSampler.js - - -const filterToBits = [ - 0 | (0 << 1) | (0 << 2), - 0 | (0 << 1) | (0 << 2), - 1 | (1 << 1) | (0 << 2), - 1 | (1 << 1) | (1 << 2), - 0 | (0 << 1) | (0 << 2), - 0 | (1 << 1) | (0 << 2), - 0 | (1 << 1) | (1 << 2), - 0 | (1 << 1) | (0 << 2), - 0 | (0 << 1) | (1 << 2), - 1 | (0 << 1) | (0 << 2), - 1 | (0 << 1) | (1 << 2), - 1 | (1 << 1) | (0 << 2), - 1 | (0 << 1) | (0 << 2), // TEXTURE_LINEAR_NEAREST -]; -// subtract 0x01FF from the comparison function value before indexing this array! -const comparisonFunctionToBits = [ - (0 << 3) | (0 << 4) | (0 << 5) | (0 << 6), - (0 << 3) | (0 << 4) | (0 << 5) | (1 << 6), - (0 << 3) | (0 << 4) | (1 << 5) | (0 << 6), - (0 << 3) | (0 << 4) | (1 << 5) | (1 << 6), - (0 << 3) | (1 << 4) | (0 << 5) | (0 << 6), - (0 << 3) | (1 << 4) | (0 << 5) | (1 << 6), - (0 << 3) | (1 << 4) | (1 << 5) | (0 << 6), - (0 << 3) | (1 << 4) | (1 << 5) | (1 << 6), - (1 << 3) | (0 << 4) | (0 << 5) | (0 << 6), // ALWAYS -]; -const filterNoMipToBits = [ - 0 << 7, - 1 << 7, - 1 << 7, - 0 << 7, - 0 << 7, - 0 << 7, - 0 << 7, - 1 << 7, - 0 << 7, - 0 << 7, - 0 << 7, - 0 << 7, - 1 << 7, // TEXTURE_LINEAR_NEAREST -]; -/** @internal */ -class WebGPUCacheSampler { - constructor(device) { - this._samplers = {}; - this._device = device; - this.disabled = false; - } - static GetSamplerHashCode(sampler) { - var _a, _b, _c; - // The WebGPU spec currently only allows values 1 and 4 for anisotropy - const anisotropy = sampler._cachedAnisotropicFilteringLevel && sampler._cachedAnisotropicFilteringLevel > 1 ? 4 : 1; - const code = filterToBits[sampler.samplingMode] + - comparisonFunctionToBits[(sampler._comparisonFunction || 0x0202) - 0x0200 + 1] + - filterNoMipToBits[sampler.samplingMode] + // handle the lodMinClamp = lodMaxClamp = 0 case when no filter used for mip mapping - (((_a = sampler._cachedWrapU) !== null && _a !== void 0 ? _a : 1) << 8) + - (((_b = sampler._cachedWrapV) !== null && _b !== void 0 ? _b : 1) << 10) + - (((_c = sampler._cachedWrapR) !== null && _c !== void 0 ? _c : 1) << 12) + - ((sampler.useMipMaps ? 1 : 0) << 14) + // need to factor this in because _getSamplerFilterDescriptor depends on samplingMode AND useMipMaps! - (anisotropy << 15); - return code; - } - static _GetSamplerFilterDescriptor(sampler, anisotropy) { - let magFilter, minFilter, mipmapFilter, lodMinClamp, lodMaxClamp; - const useMipMaps = sampler.useMipMaps; - switch (sampler.samplingMode) { - case 11: - magFilter = FilterMode.Linear; - minFilter = FilterMode.Linear; - mipmapFilter = FilterMode.Nearest; - if (!useMipMaps) { - lodMinClamp = lodMaxClamp = 0; - } - break; - case 3: - case 3: - magFilter = FilterMode.Linear; - minFilter = FilterMode.Linear; - if (!useMipMaps) { - mipmapFilter = FilterMode.Nearest; - lodMinClamp = lodMaxClamp = 0; - } - else { - mipmapFilter = FilterMode.Linear; - } - break; - case 8: - magFilter = FilterMode.Nearest; - minFilter = FilterMode.Nearest; - if (!useMipMaps) { - mipmapFilter = FilterMode.Nearest; - lodMinClamp = lodMaxClamp = 0; - } - else { - mipmapFilter = FilterMode.Linear; - } - break; - case 4: - magFilter = FilterMode.Nearest; - minFilter = FilterMode.Nearest; - mipmapFilter = FilterMode.Nearest; - if (!useMipMaps) { - lodMinClamp = lodMaxClamp = 0; - } - break; - case 5: - magFilter = FilterMode.Nearest; - minFilter = FilterMode.Linear; - mipmapFilter = FilterMode.Nearest; - if (!useMipMaps) { - lodMinClamp = lodMaxClamp = 0; - } - break; - case 6: - magFilter = FilterMode.Nearest; - minFilter = FilterMode.Linear; - if (!useMipMaps) { - mipmapFilter = FilterMode.Nearest; - lodMinClamp = lodMaxClamp = 0; - } - else { - mipmapFilter = FilterMode.Linear; - } - break; - case 7: - magFilter = FilterMode.Nearest; - minFilter = FilterMode.Linear; - mipmapFilter = FilterMode.Nearest; - lodMinClamp = lodMaxClamp = 0; - break; - case 1: - case 1: - magFilter = FilterMode.Nearest; - minFilter = FilterMode.Nearest; - mipmapFilter = FilterMode.Nearest; - lodMinClamp = lodMaxClamp = 0; - break; - case 9: - magFilter = FilterMode.Linear; - minFilter = FilterMode.Nearest; - mipmapFilter = FilterMode.Nearest; - if (!useMipMaps) { - lodMinClamp = lodMaxClamp = 0; - } - break; - case 10: - magFilter = FilterMode.Linear; - minFilter = FilterMode.Nearest; - if (!useMipMaps) { - mipmapFilter = FilterMode.Nearest; - lodMinClamp = lodMaxClamp = 0; - } - else { - mipmapFilter = FilterMode.Linear; - } - break; - case 2: - case 2: - magFilter = FilterMode.Linear; - minFilter = FilterMode.Linear; - mipmapFilter = FilterMode.Nearest; - lodMinClamp = lodMaxClamp = 0; - break; - case 12: - magFilter = FilterMode.Linear; - minFilter = FilterMode.Nearest; - mipmapFilter = FilterMode.Nearest; - lodMinClamp = lodMaxClamp = 0; - break; - default: - magFilter = FilterMode.Nearest; - minFilter = FilterMode.Nearest; - mipmapFilter = FilterMode.Nearest; - lodMinClamp = lodMaxClamp = 0; - break; - } - if (anisotropy > 1 && (lodMinClamp !== 0 || lodMaxClamp !== 0)) { - return { - magFilter: FilterMode.Linear, - minFilter: FilterMode.Linear, - mipmapFilter: FilterMode.Linear, - anisotropyEnabled: true, - }; - } - return { - magFilter, - minFilter, - mipmapFilter, - lodMinClamp, - lodMaxClamp, - }; - } - static _GetWrappingMode(mode) { - switch (mode) { - case 1: - return AddressMode.Repeat; - case 0: - return AddressMode.ClampToEdge; - case 2: - return AddressMode.MirrorRepeat; - } - return AddressMode.Repeat; - } - static _GetSamplerWrappingDescriptor(sampler) { - return { - addressModeU: this._GetWrappingMode(sampler._cachedWrapU), - addressModeV: this._GetWrappingMode(sampler._cachedWrapV), - addressModeW: this._GetWrappingMode(sampler._cachedWrapR), - }; - } - static _GetSamplerDescriptor(sampler) { - // The WebGPU spec currently only allows values 1 and 4 for anisotropy - const anisotropy = sampler.useMipMaps && sampler._cachedAnisotropicFilteringLevel && sampler._cachedAnisotropicFilteringLevel > 1 ? 4 : 1; - const filterDescriptor = this._GetSamplerFilterDescriptor(sampler, anisotropy); - return Object.assign(Object.assign(Object.assign({}, filterDescriptor), this._GetSamplerWrappingDescriptor(sampler)), { compare: sampler._comparisonFunction ? WebGPUCacheSampler.GetCompareFunction(sampler._comparisonFunction) : undefined, maxAnisotropy: filterDescriptor.anisotropyEnabled ? anisotropy : 1 }); - } - static GetCompareFunction(compareFunction) { - switch (compareFunction) { - case 519: - return CompareFunction.Always; - case 514: - return CompareFunction.Equal; - case 516: - return CompareFunction.Greater; - case 518: - return CompareFunction.GreaterEqual; - case 513: - return CompareFunction.Less; - case 515: - return CompareFunction.LessEqual; - case 512: - return CompareFunction.Never; - case 517: - return CompareFunction.NotEqual; - default: - return CompareFunction.Less; - } - } - getSampler(sampler, bypassCache = false, hash = 0) { - if (this.disabled) { - return this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(sampler)); - } - if (bypassCache) { - hash = 0; - } - else if (hash === 0) { - hash = WebGPUCacheSampler.GetSamplerHashCode(sampler); - } - let gpuSampler = bypassCache ? undefined : this._samplers[hash]; - if (!gpuSampler) { - gpuSampler = this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(sampler)); - if (!bypassCache) { - this._samplers[hash] = gpuSampler; - } - } - return gpuSampler; - } -} -//# sourceMappingURL=webgpuCacheSampler.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheRenderPipeline.js -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - -var StatePosition; -(function (StatePosition) { - StatePosition[StatePosition["StencilReadMask"] = 0] = "StencilReadMask"; - StatePosition[StatePosition["StencilWriteMask"] = 1] = "StencilWriteMask"; - //DepthBiasClamp = 1, // not used, so remove it to improve perf - StatePosition[StatePosition["DepthBias"] = 2] = "DepthBias"; - StatePosition[StatePosition["DepthBiasSlopeScale"] = 3] = "DepthBiasSlopeScale"; - StatePosition[StatePosition["DepthStencilState"] = 4] = "DepthStencilState"; - StatePosition[StatePosition["MRTAttachments1"] = 5] = "MRTAttachments1"; - StatePosition[StatePosition["MRTAttachments2"] = 6] = "MRTAttachments2"; - StatePosition[StatePosition["RasterizationState"] = 7] = "RasterizationState"; - StatePosition[StatePosition["ColorStates"] = 8] = "ColorStates"; - StatePosition[StatePosition["ShaderStage"] = 9] = "ShaderStage"; - StatePosition[StatePosition["TextureStage"] = 10] = "TextureStage"; - StatePosition[StatePosition["VertexState"] = 11] = "VertexState"; - StatePosition[StatePosition["NumStates"] = 12] = "NumStates"; -})(StatePosition || (StatePosition = {})); -const alphaBlendFactorToIndex = { - 0: 1, - 1: 2, - 0x0300: 3, - 0x0301: 4, - 0x0302: 5, - 0x0303: 6, - 0x0304: 7, - 0x0305: 8, - 0x0306: 9, - 0x0307: 10, - 0x0308: 11, - 0x8001: 12, - 0x8002: 13, - 0x8003: 12, - 0x8004: 13, // OneMinusBlendColor (alpha) -}; -const stencilOpToIndex = { - 0x0000: 0, - 0x1e00: 1, - 0x1e01: 2, - 0x1e02: 3, - 0x1e03: 4, - 0x150a: 5, - 0x8507: 6, - 0x8508: 7, // DECR_WRAP -}; -/** @internal */ -class WebGPUCacheRenderPipeline { - constructor(device, emptyVertexBuffer, useTextureStage) { - this.mrtTextureCount = 0; - this._device = device; - this._useTextureStage = useTextureStage; - this._states = new Array(30); // pre-allocate enough room so that no new allocation will take place afterwards - this._statesLength = 0; - this._stateDirtyLowestIndex = 0; - this._emptyVertexBuffer = emptyVertexBuffer; - this._mrtFormats = []; - this._parameter = { token: undefined, pipeline: null }; - this.disabled = false; - this.vertexBuffers = []; - this._kMaxVertexBufferStride = device.limits.maxVertexBufferArrayStride || 2048; - this.reset(); - } - reset() { - this._isDirty = true; - this.vertexBuffers.length = 0; - this.setAlphaToCoverage(false); - this.resetDepthCullingState(); - this.setClampDepth(false); - this.setDepthBias(0); - //this.setDepthBiasClamp(0); - this._webgpuColorFormat = [TextureFormat.BGRA8Unorm]; - this.setColorFormat(TextureFormat.BGRA8Unorm); - this.setMRT([]); - this.setAlphaBlendEnabled(false); - this.setAlphaBlendFactors([null, null, null, null], [null, null]); - this.setWriteMask(0xf); - this.setDepthStencilFormat(TextureFormat.Depth24PlusStencil8); - this.setStencilEnabled(false); - this.resetStencilState(); - this.setBuffers(null, null, null); - this._setTextureState(0); - } - get colorFormats() { - return this._mrtAttachments1 > 0 ? this._mrtFormats : this._webgpuColorFormat; - } - getRenderPipeline(fillMode, effect, sampleCount, textureState = 0) { - if (sampleCount > 1) { - // WebGPU only supports 1 or 4 - sampleCount = 4; - } - if (this.disabled) { - const topology = WebGPUCacheRenderPipeline._GetTopology(fillMode); - this._setVertexState(effect); // to fill this.vertexBuffers with correct data - this._setTextureState(textureState); - this._parameter.pipeline = this._createRenderPipeline(effect, topology, sampleCount); - WebGPUCacheRenderPipeline.NumCacheMiss++; - WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++; - return this._parameter.pipeline; - } - this._setShaderStage(effect.uniqueId); - this._setRasterizationState(fillMode, sampleCount); - this._setColorStates(); - this._setDepthStencilState(); - this._setVertexState(effect); - this._setTextureState(textureState); - this.lastStateDirtyLowestIndex = this._stateDirtyLowestIndex; - if (!this._isDirty && this._parameter.pipeline) { - this._stateDirtyLowestIndex = this._statesLength; - WebGPUCacheRenderPipeline.NumCacheHitWithoutHash++; - return this._parameter.pipeline; - } - this._getRenderPipeline(this._parameter); - this._isDirty = false; - this._stateDirtyLowestIndex = this._statesLength; - if (this._parameter.pipeline) { - WebGPUCacheRenderPipeline.NumCacheHitWithHash++; - return this._parameter.pipeline; - } - const topology = WebGPUCacheRenderPipeline._GetTopology(fillMode); - this._parameter.pipeline = this._createRenderPipeline(effect, topology, sampleCount); - this._setRenderPipeline(this._parameter); - WebGPUCacheRenderPipeline.NumCacheMiss++; - WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++; - return this._parameter.pipeline; - } - endFrame() { - WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame = WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame; - WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame = 0; - } - setAlphaToCoverage(enabled) { - this._alphaToCoverageEnabled = enabled; - } - setFrontFace(frontFace) { - this._frontFace = frontFace; - } - setCullEnabled(enabled) { - this._cullEnabled = enabled; - } - setCullFace(cullFace) { - this._cullFace = cullFace; - } - setClampDepth(clampDepth) { - this._clampDepth = clampDepth; - } - resetDepthCullingState() { - this.setDepthCullingState(false, 2, 1, 0, 0, true, true, 519); - } - setDepthCullingState(cullEnabled, frontFace, cullFace, zOffset, zOffsetUnits, depthTestEnabled, depthWriteEnabled, depthCompare) { - this._depthWriteEnabled = depthWriteEnabled; - this._depthTestEnabled = depthTestEnabled; - this._depthCompare = (depthCompare !== null && depthCompare !== void 0 ? depthCompare : 519) - 0x0200; - this._cullFace = cullFace; - this._cullEnabled = cullEnabled; - this._frontFace = frontFace; - this.setDepthBiasSlopeScale(zOffset); - this.setDepthBias(zOffsetUnits); - } - setDepthBias(depthBias) { - if (this._depthBias !== depthBias) { - this._depthBias = depthBias; - this._states[StatePosition.DepthBias] = depthBias; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBias); - } - } - /*public setDepthBiasClamp(depthBiasClamp: number): void { - if (this._depthBiasClamp !== depthBiasClamp) { - this._depthBiasClamp = depthBiasClamp; - this._states[StatePosition.DepthBiasClamp] = depthBiasClamp.toString(); - this._isDirty = true; - } - }*/ - setDepthBiasSlopeScale(depthBiasSlopeScale) { - if (this._depthBiasSlopeScale !== depthBiasSlopeScale) { - this._depthBiasSlopeScale = depthBiasSlopeScale; - this._states[StatePosition.DepthBiasSlopeScale] = depthBiasSlopeScale; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBiasSlopeScale); - } - } - setColorFormat(format) { - this._webgpuColorFormat[0] = format; - this._colorFormat = renderableTextureFormatToIndex[format !== null && format !== void 0 ? format : ""]; - } - setMRTAttachments(attachments) { - this.mrtAttachments = attachments; - let mask = 0; - for (let i = 0; i < attachments.length; ++i) { - if (attachments[i] !== 0) { - mask += 1 << i; - } - } - if (this._mrtEnabledMask !== mask) { - this._mrtEnabledMask = mask; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1); - } - } - setMRT(textureArray, textureCount) { - var _a, _b; - textureCount = textureCount !== null && textureCount !== void 0 ? textureCount : textureArray.length; - if (textureCount > 10) { - // 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)! - // 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 - // We are using 2x32 bit values to handle 10 textures - throw "Can't handle more than 10 attachments for a MRT in cache render pipeline!"; - } - this.mrtTextureArray = textureArray; - this.mrtTextureCount = textureCount; - this._mrtEnabledMask = 0xffff; // all textures are enabled at start (meaning we can write to them). Calls to setMRTAttachments may disable some - const bits = [0, 0]; - let indexBits = 0, mask = 0, numRT = 0; - for (let i = 0; i < textureCount; ++i) { - const texture = textureArray[i]; - const gpuWrapper = texture === null || texture === void 0 ? void 0 : texture._hardwareTexture; - this._mrtFormats[numRT] = (_a = gpuWrapper === null || gpuWrapper === void 0 ? void 0 : gpuWrapper.format) !== null && _a !== void 0 ? _a : this._webgpuColorFormat[0]; - bits[indexBits] += renderableTextureFormatToIndex[(_b = this._mrtFormats[numRT]) !== null && _b !== void 0 ? _b : ""] << mask; - mask += 6; - numRT++; - if (mask >= 32) { - mask = 0; - indexBits++; - } - } - this._mrtFormats.length = numRT; - if (this._mrtAttachments1 !== bits[0] || this._mrtAttachments2 !== bits[1]) { - this._mrtAttachments1 = bits[0]; - this._mrtAttachments2 = bits[1]; - this._states[StatePosition.MRTAttachments1] = bits[0]; - this._states[StatePosition.MRTAttachments2] = bits[1]; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1); - } - } - setAlphaBlendEnabled(enabled) { - this._alphaBlendEnabled = enabled; - } - setAlphaBlendFactors(factors, operations) { - this._alphaBlendFuncParams = factors; - this._alphaBlendEqParams = operations; - } - setWriteMask(mask) { - this._writeMask = mask; - } - setDepthStencilFormat(format) { - this._webgpuDepthStencilFormat = format; - this._depthStencilFormat = format === undefined ? 0 : renderableTextureFormatToIndex[format]; - } - setDepthTestEnabled(enabled) { - this._depthTestEnabled = enabled; - } - setDepthWriteEnabled(enabled) { - this._depthWriteEnabled = enabled; - } - setDepthCompare(func) { - this._depthCompare = (func !== null && func !== void 0 ? func : 519) - 0x0200; - } - setStencilEnabled(enabled) { - this._stencilEnabled = enabled; - } - setStencilCompare(func) { - this._stencilFrontCompare = (func !== null && func !== void 0 ? func : 519) - 0x0200; - } - setStencilDepthFailOp(op) { - this._stencilFrontDepthFailOp = op === null ? 1 /* KEEP */ : stencilOpToIndex[op]; - } - setStencilPassOp(op) { - this._stencilFrontPassOp = op === null ? 2 /* REPLACE */ : stencilOpToIndex[op]; - } - setStencilFailOp(op) { - this._stencilFrontFailOp = op === null ? 1 /* KEEP */ : stencilOpToIndex[op]; - } - setStencilReadMask(mask) { - if (this._stencilReadMask !== mask) { - this._stencilReadMask = mask; - this._states[StatePosition.StencilReadMask] = mask; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilReadMask); - } - } - setStencilWriteMask(mask) { - if (this._stencilWriteMask !== mask) { - this._stencilWriteMask = mask; - this._states[StatePosition.StencilWriteMask] = mask; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilWriteMask); - } - } - resetStencilState() { - this.setStencilState(false, 519, 7680, 7681, 7680, 0xff, 0xff); - } - setStencilState(stencilEnabled, compare, depthFailOp, passOp, failOp, readMask, writeMask) { - this._stencilEnabled = stencilEnabled; - this._stencilFrontCompare = (compare !== null && compare !== void 0 ? compare : 519) - 0x0200; - this._stencilFrontDepthFailOp = depthFailOp === null ? 1 /* KEEP */ : stencilOpToIndex[depthFailOp]; - this._stencilFrontPassOp = passOp === null ? 2 /* REPLACE */ : stencilOpToIndex[passOp]; - this._stencilFrontFailOp = failOp === null ? 1 /* KEEP */ : stencilOpToIndex[failOp]; - this.setStencilReadMask(readMask); - this.setStencilWriteMask(writeMask); - } - setBuffers(vertexBuffers, indexBuffer, overrideVertexBuffers) { - this._vertexBuffers = vertexBuffers; - this._overrideVertexBuffers = overrideVertexBuffers; - this._indexBuffer = indexBuffer; - } - static _GetTopology(fillMode) { - switch (fillMode) { - // Triangle views - case 0: - return PrimitiveTopology.TriangleList; - case 2: - return PrimitiveTopology.PointList; - case 1: - return PrimitiveTopology.LineList; - // Draw modes - case 3: - return PrimitiveTopology.PointList; - case 4: - return PrimitiveTopology.LineList; - case 5: - // return this._gl.LINE_LOOP; - // TODO WEBGPU. Line Loop Mode Fallback at buffer load time. - throw "LineLoop is an unsupported fillmode in WebGPU"; - case 6: - return PrimitiveTopology.LineStrip; - case 7: - return PrimitiveTopology.TriangleStrip; - case 8: - // return this._gl.TRIANGLE_FAN; - // TODO WEBGPU. Triangle Fan Mode Fallback at buffer load time. - throw "TriangleFan is an unsupported fillmode in WebGPU"; - default: - return PrimitiveTopology.TriangleList; - } - } - static _GetAphaBlendOperation(operation) { - switch (operation) { - case 32774: - return BlendOperation.Add; - case 32778: - return BlendOperation.Subtract; - case 32779: - return BlendOperation.ReverseSubtract; - case 32775: - return BlendOperation.Min; - case 32776: - return BlendOperation.Max; - default: - return BlendOperation.Add; - } - } - static _GetAphaBlendFactor(factor) { - switch (factor) { - case 0: - return BlendFactor.Zero; - case 1: - return BlendFactor.One; - case 768: - return BlendFactor.Src; - case 769: - return BlendFactor.OneMinusSrc; - case 770: - return BlendFactor.SrcAlpha; - case 771: - return BlendFactor.OneMinusSrcAlpha; - case 772: - return BlendFactor.DstAlpha; - case 773: - return BlendFactor.OneMinusDstAlpha; - case 774: - return BlendFactor.Dst; - case 775: - return BlendFactor.OneMinusDst; - case 776: - return BlendFactor.SrcAlphaSaturated; - case 32769: - return BlendFactor.Constant; - case 32770: - return BlendFactor.OneMinusConstant; - case 32771: - return BlendFactor.Constant; - case 32772: - return BlendFactor.OneMinusConstant; - default: - return BlendFactor.One; - } - } - static _GetCompareFunction(compareFunction) { - switch (compareFunction) { - case 0: // NEVER - return CompareFunction.Never; - case 1: // LESS - return CompareFunction.Less; - case 2: // EQUAL - return CompareFunction.Equal; - case 3: // LEQUAL - return CompareFunction.LessEqual; - case 4: // GREATER - return CompareFunction.Greater; - case 5: // NOTEQUAL - return CompareFunction.NotEqual; - case 6: // GEQUAL - return CompareFunction.GreaterEqual; - case 7: // ALWAYS - return CompareFunction.Always; - } - return CompareFunction.Never; - } - static _GetStencilOpFunction(operation) { - switch (operation) { - case 0: - return StencilOperation.Zero; - case 1: - return StencilOperation.Keep; - case 2: - return StencilOperation.Replace; - case 3: - return StencilOperation.IncrementClamp; - case 4: - return StencilOperation.DecrementClamp; - case 5: - return StencilOperation.Invert; - case 6: - return StencilOperation.IncrementWrap; - case 7: - return StencilOperation.DecrementWrap; - } - return StencilOperation.Keep; - } - static _GetVertexInputDescriptorFormat(vertexBuffer) { - const type = vertexBuffer.type; - const normalized = vertexBuffer.normalized; - const size = vertexBuffer.getSize(); - switch (type) { - case buffer_VertexBuffer.BYTE: - switch (size) { - case 1: - case 2: - return normalized ? VertexFormat.Snorm8x2 : VertexFormat.Sint8x2; - case 3: - case 4: - return normalized ? VertexFormat.Snorm8x4 : VertexFormat.Sint8x4; - } - break; - case buffer_VertexBuffer.UNSIGNED_BYTE: - switch (size) { - case 1: - case 2: - return normalized ? VertexFormat.Unorm8x2 : VertexFormat.Uint8x2; - case 3: - case 4: - return normalized ? VertexFormat.Unorm8x4 : VertexFormat.Uint8x4; - } - break; - case buffer_VertexBuffer.SHORT: - switch (size) { - case 1: - case 2: - return normalized ? VertexFormat.Snorm16x2 : VertexFormat.Sint16x2; - case 3: - case 4: - return normalized ? VertexFormat.Snorm16x4 : VertexFormat.Sint16x4; - } - break; - case buffer_VertexBuffer.UNSIGNED_SHORT: - switch (size) { - case 1: - case 2: - return normalized ? VertexFormat.Unorm16x2 : VertexFormat.Uint16x2; - case 3: - case 4: - return normalized ? VertexFormat.Unorm16x4 : VertexFormat.Uint16x4; - } - break; - case buffer_VertexBuffer.INT: - switch (size) { - case 1: - return VertexFormat.Sint32; - case 2: - return VertexFormat.Sint32x2; - case 3: - return VertexFormat.Sint32x3; - case 4: - return VertexFormat.Sint32x4; - } - break; - case buffer_VertexBuffer.UNSIGNED_INT: - switch (size) { - case 1: - return VertexFormat.Uint32; - case 2: - return VertexFormat.Uint32x2; - case 3: - return VertexFormat.Uint32x3; - case 4: - return VertexFormat.Uint32x4; - } - break; - case buffer_VertexBuffer.FLOAT: - switch (size) { - case 1: - return VertexFormat.Float32; - case 2: - return VertexFormat.Float32x2; - case 3: - return VertexFormat.Float32x3; - case 4: - return VertexFormat.Float32x4; - } - break; - } - throw new Error(`Invalid Format '${vertexBuffer.getKind()}' - type=${type}, normalized=${normalized}, size=${size}`); - } - _getAphaBlendState() { - if (!this._alphaBlendEnabled) { - return null; - } - return { - srcFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[2]), - dstFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[3]), - operation: WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[1]), - }; - } - _getColorBlendState() { - if (!this._alphaBlendEnabled) { - return null; - } - return { - srcFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[0]), - dstFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[1]), - operation: WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[0]), - }; - } - _setShaderStage(id) { - if (this._shaderId !== id) { - this._shaderId = id; - this._states[StatePosition.ShaderStage] = id; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ShaderStage); - } - } - _setRasterizationState(topology, sampleCount) { - const frontFace = this._frontFace; - const cullMode = this._cullEnabled ? this._cullFace : 0; - const clampDepth = this._clampDepth ? 1 : 0; - const alphaToCoverage = this._alphaToCoverageEnabled ? 1 : 0; - const rasterizationState = frontFace - 1 + (cullMode << 1) + (clampDepth << 3) + (alphaToCoverage << 4) + (topology << 5) + (sampleCount << 8); - if (this._rasterizationState !== rasterizationState) { - this._rasterizationState = rasterizationState; - this._states[StatePosition.RasterizationState] = this._rasterizationState; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.RasterizationState); - } - } - _setColorStates() { - 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) - if (this._alphaBlendEnabled) { - colorStates += - ((this._alphaBlendFuncParams[0] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[0]]) << 0) + - ((this._alphaBlendFuncParams[1] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[1]]) << 4) + - ((this._alphaBlendFuncParams[2] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[2]]) << 8) + - ((this._alphaBlendFuncParams[3] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[3]]) << 12) + - ((this._alphaBlendEqParams[0] === null ? 1 : this._alphaBlendEqParams[0] - 0x8005) << 16) + - ((this._alphaBlendEqParams[1] === null ? 1 : this._alphaBlendEqParams[1] - 0x8005) << 19); - } - if (colorStates !== this._colorStates) { - this._colorStates = colorStates; - this._states[StatePosition.ColorStates] = this._colorStates; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ColorStates); - } - } - _setDepthStencilState() { - const stencilState = !this._stencilEnabled - ? 7 /* ALWAYS */ + (1 /* KEEP */ << 3) + (1 /* KEEP */ << 6) + (1 /* KEEP */ << 9) - : this._stencilFrontCompare + (this._stencilFrontDepthFailOp << 3) + (this._stencilFrontPassOp << 6) + (this._stencilFrontFailOp << 9); - const depthStencilState = this._depthStencilFormat + ((this._depthTestEnabled ? this._depthCompare : 7) /* ALWAYS */ << 6) + (stencilState << 10); // stencil front - stencil back is the same - if (this._depthStencilState !== depthStencilState) { - this._depthStencilState = depthStencilState; - this._states[StatePosition.DepthStencilState] = this._depthStencilState; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthStencilState); - } - } - _setVertexState(effect) { - var _a, _b; - const currStateLen = this._statesLength; - let newNumStates = StatePosition.VertexState; - const webgpuPipelineContext = effect._pipelineContext; - const attributes = webgpuPipelineContext.shaderProcessingContext.attributeNamesFromEffect; - const locations = webgpuPipelineContext.shaderProcessingContext.attributeLocationsFromEffect; - let currentGPUBuffer; - let numVertexBuffers = 0; - for (let index = 0; index < attributes.length; index++) { - const location = locations[index]; - let vertexBuffer = (_a = (this._overrideVertexBuffers && this._overrideVertexBuffers[attributes[index]])) !== null && _a !== void 0 ? _a : this._vertexBuffers[attributes[index]]; - if (!vertexBuffer) { - // In WebGL it's valid to not bind a vertex buffer to an attribute, but it's not valid in WebGPU - // So we must bind a dummy buffer when we are not given one for a specific attribute - vertexBuffer = this._emptyVertexBuffer; - } - const buffer = (_b = vertexBuffer.getBuffer()) === null || _b === void 0 ? void 0 : _b.underlyingResource; - // 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 - // 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 - // See _getVertexInputDescriptor() below - if (vertexBuffer._validOffsetRange === undefined) { - const offset = vertexBuffer.byteOffset; - const formatSize = vertexBuffer.getSize(true); - const byteStride = vertexBuffer.byteStride; - vertexBuffer._validOffsetRange = offset <= this._kMaxVertexBufferStride - formatSize && (byteStride === 0 || offset + formatSize <= byteStride); - } - if (!(currentGPUBuffer && currentGPUBuffer === buffer && vertexBuffer._validOffsetRange)) { - // we can't combine the previous vertexBuffer with the current one - this.vertexBuffers[numVertexBuffers++] = vertexBuffer; - currentGPUBuffer = vertexBuffer._validOffsetRange ? buffer : null; - } - const vid = vertexBuffer.hashCode + (location << 7); - this._isDirty = this._isDirty || this._states[newNumStates] !== vid; - this._states[newNumStates++] = vid; - } - this.vertexBuffers.length = numVertexBuffers; - this._statesLength = newNumStates; - this._isDirty = this._isDirty || newNumStates !== currStateLen; - if (this._isDirty) { - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.VertexState); - } - } - _setTextureState(textureState) { - if (this._textureState !== textureState) { - this._textureState = textureState; - this._states[StatePosition.TextureStage] = this._textureState; - this._isDirty = true; - this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.TextureStage); - } - } - _createPipelineLayout(webgpuPipelineContext) { - if (this._useTextureStage) { - return this._createPipelineLayoutWithTextureStage(webgpuPipelineContext); - } - const bindGroupLayouts = []; - const bindGroupLayoutEntries = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries; - for (let i = 0; i < bindGroupLayoutEntries.length; i++) { - const setDefinition = bindGroupLayoutEntries[i]; - bindGroupLayouts[i] = this._device.createBindGroupLayout({ - entries: setDefinition, - }); - } - webgpuPipelineContext.bindGroupLayouts[0] = bindGroupLayouts; - return this._device.createPipelineLayout({ bindGroupLayouts }); - } - _createPipelineLayoutWithTextureStage(webgpuPipelineContext) { - var _a; - const shaderProcessingContext = webgpuPipelineContext.shaderProcessingContext; - const bindGroupLayoutEntries = shaderProcessingContext.bindGroupLayoutEntries; - let bitVal = 1; - for (let i = 0; i < bindGroupLayoutEntries.length; i++) { - const setDefinition = bindGroupLayoutEntries[i]; - for (let j = 0; j < setDefinition.length; j++) { - const entry = bindGroupLayoutEntries[i][j]; - if (entry.texture) { - const name = shaderProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].name; - const textureInfo = shaderProcessingContext.availableTextures[name]; - const samplerInfo = textureInfo.autoBindSampler ? shaderProcessingContext.availableSamplers[name + WebGPUShaderProcessor.AutoSamplerSuffix] : null; - let sampleType = textureInfo.sampleType; - let samplerType = (_a = samplerInfo === null || samplerInfo === void 0 ? void 0 : samplerInfo.type) !== null && _a !== void 0 ? _a : SamplerBindingType.Filtering; - if (this._textureState & bitVal && sampleType !== TextureSampleType.Depth) { - // The texture is a 32 bits float texture but the system does not support linear filtering for them: - // we set the sampler to "non-filtering" and the texture sample type to "unfilterable-float" - if (textureInfo.autoBindSampler) { - samplerType = SamplerBindingType.NonFiltering; - } - sampleType = TextureSampleType.UnfilterableFloat; - } - entry.texture.sampleType = sampleType; - if (samplerInfo) { - const binding = shaderProcessingContext.bindGroupLayoutEntryInfo[samplerInfo.binding.groupIndex][samplerInfo.binding.bindingIndex].index; - bindGroupLayoutEntries[samplerInfo.binding.groupIndex][binding].sampler.type = samplerType; - } - bitVal = bitVal << 1; - } - } - } - const bindGroupLayouts = []; - for (let i = 0; i < bindGroupLayoutEntries.length; ++i) { - bindGroupLayouts[i] = this._device.createBindGroupLayout({ - entries: bindGroupLayoutEntries[i], - }); - } - webgpuPipelineContext.bindGroupLayouts[this._textureState] = bindGroupLayouts; - return this._device.createPipelineLayout({ bindGroupLayouts }); - } - _getVertexInputDescriptor(effect) { - var _a, _b; - const descriptors = []; - const webgpuPipelineContext = effect._pipelineContext; - const attributes = webgpuPipelineContext.shaderProcessingContext.attributeNamesFromEffect; - const locations = webgpuPipelineContext.shaderProcessingContext.attributeLocationsFromEffect; - let currentGPUBuffer; - let currentGPUAttributes; - for (let index = 0; index < attributes.length; index++) { - const location = locations[index]; - let vertexBuffer = (_a = (this._overrideVertexBuffers && this._overrideVertexBuffers[attributes[index]])) !== null && _a !== void 0 ? _a : this._vertexBuffers[attributes[index]]; - if (!vertexBuffer) { - // In WebGL it's valid to not bind a vertex buffer to an attribute, but it's not valid in WebGPU - // So we must bind a dummy buffer when we are not given one for a specific attribute - vertexBuffer = this._emptyVertexBuffer; - } - let buffer = (_b = vertexBuffer.getBuffer()) === null || _b === void 0 ? void 0 : _b.underlyingResource; - // 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) - let offset = vertexBuffer.byteOffset; - const invalidOffsetRange = !vertexBuffer._validOffsetRange; - if (!(currentGPUBuffer && currentGPUAttributes && currentGPUBuffer === buffer) || invalidOffsetRange) { - const vertexBufferDescriptor = { - arrayStride: vertexBuffer.byteStride, - stepMode: vertexBuffer.getIsInstanced() ? InputStepMode.Instance : InputStepMode.Vertex, - attributes: [], - }; - descriptors.push(vertexBufferDescriptor); - currentGPUAttributes = vertexBufferDescriptor.attributes; - if (invalidOffsetRange) { - offset = 0; // the offset will be set directly in the setVertexBuffer call - buffer = null; // buffer can't be reused - } - } - currentGPUAttributes.push({ - shaderLocation: location, - offset, - format: WebGPUCacheRenderPipeline._GetVertexInputDescriptorFormat(vertexBuffer), - }); - currentGPUBuffer = buffer; - } - return descriptors; - } - _createRenderPipeline(effect, topology, sampleCount) { - var _a, _b, _c; - const webgpuPipelineContext = effect._pipelineContext; - const inputStateDescriptor = this._getVertexInputDescriptor(effect); - const pipelineLayout = this._createPipelineLayout(webgpuPipelineContext); - const colorStates = []; - const alphaBlend = this._getAphaBlendState(); - const colorBlend = this._getColorBlendState(); - if (this._mrtAttachments1 > 0) { - for (let i = 0; i < this._mrtFormats.length; ++i) { - const format = this._mrtFormats[i]; - if (format) { - const descr = { - format, - writeMask: (this._mrtEnabledMask & (1 << i)) !== 0 ? this._writeMask : 0, - }; - if (alphaBlend && colorBlend) { - descr.blend = { - alpha: alphaBlend, - color: colorBlend, - }; - } - colorStates.push(descr); - } - else { - colorStates.push(null); - } - } - } - else { - if (this._webgpuColorFormat[0]) { - const descr = { - format: this._webgpuColorFormat[0], - writeMask: this._writeMask, - }; - if (alphaBlend && colorBlend) { - descr.blend = { - alpha: alphaBlend, - color: colorBlend, - }; - } - colorStates.push(descr); - } - else { - colorStates.push(null); - } - } - const stencilFrontBack = { - compare: WebGPUCacheRenderPipeline._GetCompareFunction(this._stencilEnabled ? this._stencilFrontCompare : 7 /* ALWAYS */), - depthFailOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontDepthFailOp : 1 /* KEEP */), - failOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontFailOp : 1 /* KEEP */), - passOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontPassOp : 1 /* KEEP */), - }; - let stripIndexFormat = undefined; - if (topology === PrimitiveTopology.LineStrip || topology === PrimitiveTopology.TriangleStrip) { - stripIndexFormat = !this._indexBuffer || this._indexBuffer.is32Bits ? IndexFormat.Uint32 : IndexFormat.Uint16; - } - const depthStencilFormatHasStencil = this._webgpuDepthStencilFormat ? WebGPUTextureHelper.HasStencilAspect(this._webgpuDepthStencilFormat) : false; - return this._device.createRenderPipeline({ - 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}`, - layout: pipelineLayout, - vertex: { - module: webgpuPipelineContext.stages.vertexStage.module, - entryPoint: webgpuPipelineContext.stages.vertexStage.entryPoint, - buffers: inputStateDescriptor, - }, - primitive: { - topology, - stripIndexFormat, - frontFace: this._frontFace === 1 ? FrontFace.CCW : FrontFace.CW, - cullMode: !this._cullEnabled ? CullMode.None : this._cullFace === 2 ? CullMode.Front : CullMode.Back, - }, - fragment: !webgpuPipelineContext.stages.fragmentStage - ? undefined - : { - module: webgpuPipelineContext.stages.fragmentStage.module, - entryPoint: webgpuPipelineContext.stages.fragmentStage.entryPoint, - targets: colorStates, - }, - multisample: { - count: sampleCount, - /*mask, - alphaToCoverageEnabled,*/ - }, - depthStencil: this._webgpuDepthStencilFormat === undefined - ? undefined - : { - depthWriteEnabled: this._depthWriteEnabled, - depthCompare: this._depthTestEnabled ? WebGPUCacheRenderPipeline._GetCompareFunction(this._depthCompare) : CompareFunction.Always, - format: this._webgpuDepthStencilFormat, - stencilFront: this._stencilEnabled && depthStencilFormatHasStencil ? stencilFrontBack : undefined, - stencilBack: this._stencilEnabled && depthStencilFormatHasStencil ? stencilFrontBack : undefined, - stencilReadMask: this._stencilEnabled && depthStencilFormatHasStencil ? this._stencilReadMask : undefined, - stencilWriteMask: this._stencilEnabled && depthStencilFormatHasStencil ? this._stencilWriteMask : undefined, - depthBias: this._depthBias, - depthBiasClamp: this._depthBiasClamp, - depthBiasSlopeScale: this._depthBiasSlopeScale, - }, - }); - } -} -WebGPUCacheRenderPipeline.NumCacheHitWithoutHash = 0; -WebGPUCacheRenderPipeline.NumCacheHitWithHash = 0; -WebGPUCacheRenderPipeline.NumCacheMiss = 0; -WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame = 0; -WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame = 0; -//# sourceMappingURL=webgpuCacheRenderPipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheRenderPipelineTree.js - -/** @internal */ -class NodeState { - constructor() { - this.values = {}; - } - count() { - let countNode = 0, countPipeline = this.pipeline ? 1 : 0; - for (const value in this.values) { - const node = this.values[value]; - const [childCountNodes, childCoundPipeline] = node.count(); - countNode += childCountNodes; - countPipeline += childCoundPipeline; - countNode++; - } - return [countNode, countPipeline]; - } -} -/** @internal */ -class WebGPUCacheRenderPipelineTree extends WebGPUCacheRenderPipeline { - static GetNodeCounts() { - const counts = WebGPUCacheRenderPipelineTree._Cache.count(); - return { nodeCount: counts[0], pipelineCount: counts[1] }; - } - static _GetPipelines(node, pipelines, curPath, curPathLen) { - if (node.pipeline) { - const path = curPath.slice(); - path.length = curPathLen; - pipelines.push(path); - } - for (const value in node.values) { - const nnode = node.values[value]; - curPath[curPathLen] = parseInt(value); - WebGPUCacheRenderPipelineTree._GetPipelines(nnode, pipelines, curPath, curPathLen + 1); - } - } - static GetPipelines() { - const pipelines = []; - WebGPUCacheRenderPipelineTree._GetPipelines(WebGPUCacheRenderPipelineTree._Cache, pipelines, [], 0); - return pipelines; - } - constructor(device, emptyVertexBuffer, useTextureStage) { - super(device, emptyVertexBuffer, useTextureStage); - this._nodeStack = []; - this._nodeStack[0] = WebGPUCacheRenderPipelineTree._Cache; - } - _getRenderPipeline(param) { - let node = this._nodeStack[this._stateDirtyLowestIndex]; - for (let i = this._stateDirtyLowestIndex; i < this._statesLength; ++i) { - let nn = node.values[this._states[i]]; - if (!nn) { - nn = new NodeState(); - node.values[this._states[i]] = nn; - } - node = nn; - this._nodeStack[i + 1] = node; - } - param.token = node; - param.pipeline = node.pipeline; - } - _setRenderPipeline(param) { - param.token.pipeline = param.pipeline; - } -} -WebGPUCacheRenderPipelineTree._Cache = new NodeState(); -//# sourceMappingURL=webgpuCacheRenderPipelineTree.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuStencilStateComposer.js - -/** - * @internal - **/ -class WebGPUStencilStateComposer extends StencilStateComposer { - constructor(cache) { - super(false); - this._cache = cache; - this.reset(); - } - get func() { - return this._func; - } - set func(value) { - if (this._func === value) { - return; - } - this._func = value; - this._cache.setStencilCompare(value); - } - get funcMask() { - return this._funcMask; - } - set funcMask(value) { - if (this._funcMask === value) { - return; - } - this._funcMask = value; - this._cache.setStencilReadMask(value); - } - get opStencilFail() { - return this._opStencilFail; - } - set opStencilFail(value) { - if (this._opStencilFail === value) { - return; - } - this._opStencilFail = value; - this._cache.setStencilFailOp(value); - } - get opDepthFail() { - return this._opDepthFail; - } - set opDepthFail(value) { - if (this._opDepthFail === value) { - return; - } - this._opDepthFail = value; - this._cache.setStencilDepthFailOp(value); - } - get opStencilDepthPass() { - return this._opStencilDepthPass; - } - set opStencilDepthPass(value) { - if (this._opStencilDepthPass === value) { - return; - } - this._opStencilDepthPass = value; - this._cache.setStencilPassOp(value); - } - get mask() { - return this._mask; - } - set mask(value) { - if (this._mask === value) { - return; - } - this._mask = value; - this._cache.setStencilWriteMask(value); - } - get enabled() { - return this._enabled; - } - set enabled(value) { - if (this._enabled === value) { - return; - } - this._enabled = value; - this._cache.setStencilEnabled(value); - } - reset() { - super.reset(); - this._cache.resetStencilState(); - } - apply() { - var _a; - const stencilMaterialEnabled = (_a = this.stencilMaterial) === null || _a === void 0 ? void 0 : _a.enabled; - this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled; - if (!this.enabled) { - return; - } - this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func; - this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef; - this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask; - this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail; - this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail; - this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass; - this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask; - } -} -//# sourceMappingURL=webgpuStencilStateComposer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuDepthCullingState.js - -/** - * @internal - **/ -class WebGPUDepthCullingState extends DepthCullingState { - /** - * Initializes the state. - * @param cache - */ - constructor(cache) { - super(false); - this._cache = cache; - this.reset(); - } - get zOffset() { - return this._zOffset; - } - set zOffset(value) { - if (this._zOffset === value) { - return; - } - this._zOffset = value; - this._isZOffsetDirty = true; - this._cache.setDepthBiasSlopeScale(value); - } - get zOffsetUnits() { - return this._zOffsetUnits; - } - set zOffsetUnits(value) { - if (this._zOffsetUnits === value) { - return; - } - this._zOffsetUnits = value; - this._isZOffsetDirty = true; - this._cache.setDepthBias(value); - } - get cullFace() { - return this._cullFace; - } - set cullFace(value) { - if (this._cullFace === value) { - return; - } - this._cullFace = value; - this._isCullFaceDirty = true; - this._cache.setCullFace(value !== null && value !== void 0 ? value : 1); - } - get cull() { - return this._cull; - } - set cull(value) { - if (this._cull === value) { - return; - } - this._cull = value; - this._isCullDirty = true; - this._cache.setCullEnabled(!!value); - } - get depthFunc() { - return this._depthFunc; - } - set depthFunc(value) { - if (this._depthFunc === value) { - return; - } - this._depthFunc = value; - this._isDepthFuncDirty = true; - this._cache.setDepthCompare(value); - } - get depthMask() { - return this._depthMask; - } - set depthMask(value) { - if (this._depthMask === value) { - return; - } - this._depthMask = value; - this._isDepthMaskDirty = true; - this._cache.setDepthWriteEnabled(value); - } - get depthTest() { - return this._depthTest; - } - set depthTest(value) { - if (this._depthTest === value) { - return; - } - this._depthTest = value; - this._isDepthTestDirty = true; - this._cache.setDepthTestEnabled(value); - } - get frontFace() { - return this._frontFace; - } - set frontFace(value) { - if (this._frontFace === value) { - return; - } - this._frontFace = value; - this._isFrontFaceDirty = true; - this._cache.setFrontFace(value !== null && value !== void 0 ? value : 2); - } - reset() { - super.reset(); - this._cache.resetDepthCullingState(); - } - apply() { - // nothing to do - } -} -//# sourceMappingURL=webgpuDepthCullingState.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/externalTexture.js - - -/** - * Class used to store an external texture (like GPUExternalTexture in WebGPU) - */ -class ExternalTexture { - /** - * Checks if a texture is an external or internal texture - * @param texture the external or internal texture - * @returns true if the texture is an external texture, else false - */ - static IsExternalTexture(texture) { - return texture.underlyingResource !== undefined; - } - /** - * Get the class name of the texture. - * @returns "ExternalTexture" - */ - getClassName() { - return "ExternalTexture"; - } - /** - * Gets the underlying texture object - */ - get underlyingResource() { - return this._video; - } - /** - * Constructs the texture - * @param video The video the texture should be wrapped around - */ - constructor(video) { - /** - * Gets a boolean indicating if the texture uses mipmaps - */ - this.useMipMaps = false; - /** - * The type of the underlying texture is implementation dependent, so return "UNDEFINED" for the type - */ - this.type = 16; - this._video = video; - this.uniqueId = internalTexture_InternalTexture._Counter++; - } - /** - * Get if the texture is ready to be used (downloaded, converted, mip mapped...). - * @returns true if fully ready - */ - isReady() { - return this._video.readyState >= this._video.HAVE_CURRENT_DATA; - } - /** - * Dispose the texture and release its associated resources. - */ - dispose() { } -} -//# sourceMappingURL=externalTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuMaterialContext.js - - - -/** @internal */ -class WebGPUMaterialContext { - get forceBindGroupCreation() { - // If there is at least one external texture to bind, we must recreate the bind groups each time - // because we need to retrieve a new texture each frame (by calling device.importExternalTexture) - return this._numExternalTextures > 0; - } - get hasFloatTextures() { - return this._numFloatTextures > 0; - } - constructor() { - this.uniqueId = WebGPUMaterialContext._Counter++; - this.updateId = 0; - this.textureState = 0; - this.reset(); - } - reset() { - this.samplers = {}; - this.textures = {}; - this.isDirty = true; - this._numFloatTextures = 0; - this._numExternalTextures = 0; - } - setSampler(name, sampler) { - let samplerCache = this.samplers[name]; - let currentHashCode = -1; - if (!samplerCache) { - this.samplers[name] = samplerCache = { sampler, hashCode: 0 }; - } - else { - currentHashCode = samplerCache.hashCode; - } - samplerCache.sampler = sampler; - samplerCache.hashCode = sampler ? WebGPUCacheSampler.GetSamplerHashCode(sampler) : 0; - const isDirty = currentHashCode !== samplerCache.hashCode; - if (isDirty) { - this.updateId++; - } - this.isDirty || (this.isDirty = isDirty); - } - setTexture(name, texture) { - var _a, _b, _c; - let textureCache = this.textures[name]; - let currentTextureId = -1; - if (!textureCache) { - this.textures[name] = textureCache = { texture, isFloatTexture: false, isExternalTexture: false }; - } - else { - currentTextureId = (_b = (_a = textureCache.texture) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : -1; - } - if (textureCache.isExternalTexture) { - this._numExternalTextures--; - } - if (textureCache.isFloatTexture) { - this._numFloatTextures--; - } - if (texture) { - textureCache.isFloatTexture = texture.type === 1; - textureCache.isExternalTexture = ExternalTexture.IsExternalTexture(texture); - if (textureCache.isFloatTexture) { - this._numFloatTextures++; - } - if (textureCache.isExternalTexture) { - this._numExternalTextures++; - } - } - else { - textureCache.isFloatTexture = false; - textureCache.isExternalTexture = false; - } - textureCache.texture = texture; - const isDirty = currentTextureId !== ((_c = texture === null || texture === void 0 ? void 0 : texture.uniqueId) !== null && _c !== void 0 ? _c : -1); - if (isDirty) { - this.updateId++; - } - this.isDirty || (this.isDirty = isDirty); - } -} -WebGPUMaterialContext._Counter = 0; -//# sourceMappingURL=webgpuMaterialContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuDrawContext.js - -/** @internal */ -class WebGPUDrawContext { - isDirty(materialContextUpdateId) { - return this._isDirty || this._materialContextUpdateId !== materialContextUpdateId; - } - resetIsDirty(materialContextUpdateId) { - this._isDirty = false; - this._materialContextUpdateId = materialContextUpdateId; - } - get useInstancing() { - return this._useInstancing; - } - set useInstancing(use) { - if (this._useInstancing === use) { - return; - } - if (!use) { - if (this.indirectDrawBuffer) { - this._bufferManager.releaseBuffer(this.indirectDrawBuffer); - } - this.indirectDrawBuffer = undefined; - this._indirectDrawData = undefined; - } - else { - this.indirectDrawBuffer = this._bufferManager.createRawBuffer(20, BufferUsage.CopyDst | BufferUsage.Indirect | BufferUsage.Storage); - this._indirectDrawData = new Uint32Array(5); - this._indirectDrawData[3] = 0; - this._indirectDrawData[4] = 0; - } - this._useInstancing = use; - this._currentInstanceCount = -1; - } - constructor(bufferManager) { - this._bufferManager = bufferManager; - this.uniqueId = WebGPUDrawContext._Counter++; - this._useInstancing = false; - this._currentInstanceCount = 0; - this.reset(); - } - reset() { - this.buffers = {}; - this._isDirty = true; - this._materialContextUpdateId = 0; - this.fastBundle = undefined; - this.bindGroups = undefined; - } - setBuffer(name, buffer) { - var _a; - 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)); - this.buffers[name] = buffer; - } - setIndirectData(indexOrVertexCount, instanceCount, firstIndexOrVertex) { - if (instanceCount === this._currentInstanceCount || !this.indirectDrawBuffer || !this._indirectDrawData) { - // The current buffer is already up to date so do nothing - // Note that we only check for instanceCount and not indexOrVertexCount nor firstIndexOrVertex because those values - // are supposed to not change during the lifetime of a draw context - return; - } - this._currentInstanceCount = instanceCount; - this._indirectDrawData[0] = indexOrVertexCount; - this._indirectDrawData[1] = instanceCount; - this._indirectDrawData[2] = firstIndexOrVertex; - this._bufferManager.setRawData(this.indirectDrawBuffer, 0, this._indirectDrawData, 0, 20); - } - dispose() { - if (this.indirectDrawBuffer) { - this._bufferManager.releaseBuffer(this.indirectDrawBuffer); - this.indirectDrawBuffer = undefined; - this._indirectDrawData = undefined; - } - this.fastBundle = undefined; - this.bindGroups = undefined; - this.buffers = undefined; - } -} -WebGPUDrawContext._Counter = 0; -//# sourceMappingURL=webgpuDrawContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheBindGroups.js - -class WebGPUBindGroupCacheNode { - constructor() { - this.values = {}; - } -} -/** @internal */ -class WebGPUCacheBindGroups { - static get Statistics() { - return { - totalCreated: WebGPUCacheBindGroups.NumBindGroupsCreatedTotal, - lastFrameCreated: WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame, - lookupLastFrame: WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame, - noLookupLastFrame: WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame, - }; - } - constructor(device, cacheSampler, engine) { - this.disabled = false; - this._device = device; - this._cacheSampler = cacheSampler; - this._engine = engine; - } - endFrame() { - WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame; - WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame; - WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame; - WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0; - WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0; - WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0; - } - /** - * Cache is currently based on the uniform/storage buffers, samplers and textures used by the binding groups. - * 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: - * that means we don't need to factor in the offset/size of the buffer in the cache, only the id - * @param webgpuPipelineContext - * @param drawContext - * @param materialContext - */ - getBindGroups(webgpuPipelineContext, drawContext, materialContext) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; - let bindGroups = undefined; - let node = WebGPUCacheBindGroups._Cache; - const cacheIsDisabled = this.disabled || materialContext.forceBindGroupCreation; - if (!cacheIsDisabled) { - if (!drawContext.isDirty(materialContext.updateId) && !materialContext.isDirty) { - WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame++; - return drawContext.bindGroups; - } - for (const bufferName of webgpuPipelineContext.shaderProcessingContext.bufferNames) { - const uboId = (_b = (_a = drawContext.buffers[bufferName]) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : 0; - let nextNode = node.values[uboId]; - if (!nextNode) { - nextNode = new WebGPUBindGroupCacheNode(); - node.values[uboId] = nextNode; - } - node = nextNode; - } - for (const samplerName of webgpuPipelineContext.shaderProcessingContext.samplerNames) { - const samplerHashCode = (_d = (_c = materialContext.samplers[samplerName]) === null || _c === void 0 ? void 0 : _c.hashCode) !== null && _d !== void 0 ? _d : 0; - let nextNode = node.values[samplerHashCode]; - if (!nextNode) { - nextNode = new WebGPUBindGroupCacheNode(); - node.values[samplerHashCode] = nextNode; - } - node = nextNode; - } - for (const textureName of webgpuPipelineContext.shaderProcessingContext.textureNames) { - 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; - let nextNode = node.values[textureId]; - if (!nextNode) { - nextNode = new WebGPUBindGroupCacheNode(); - node.values[textureId] = nextNode; - } - node = nextNode; - } - bindGroups = node.bindGroups; - } - drawContext.resetIsDirty(materialContext.updateId); - materialContext.isDirty = false; - if (bindGroups) { - drawContext.bindGroups = bindGroups; - WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame++; - return bindGroups; - } - bindGroups = []; - drawContext.bindGroups = bindGroups; - if (!cacheIsDisabled) { - node.bindGroups = bindGroups; - } - WebGPUCacheBindGroups.NumBindGroupsCreatedTotal++; - WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame++; - const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts[materialContext.textureState]; - for (let i = 0; i < webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries.length; i++) { - const setDefinition = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries[i]; - const entries = webgpuPipelineContext.shaderProcessingContext.bindGroupEntries[i]; - for (let j = 0; j < setDefinition.length; j++) { - const entry = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries[i][j]; - const entryInfo = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding]; - const name = (_h = entryInfo.nameInArrayOfTexture) !== null && _h !== void 0 ? _h : entryInfo.name; - if (entry.sampler) { - const bindingInfo = materialContext.samplers[name]; - if (bindingInfo) { - const sampler = bindingInfo.sampler; - if (!sampler) { - if (this._engine.dbgSanityChecks) { - logger_Logger.Error(`Trying to bind a null sampler! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === "texture" ? "<no dump>" : value))}, materialContext.uniqueId=${materialContext.uniqueId}`, 50); - } - continue; - } - entries[j].resource = this._cacheSampler.getSampler(sampler, false, bindingInfo.hashCode); - } - else { - logger_Logger.Error(`Sampler "${name}" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === "texture" || key === "sampler" ? "<no dump>" : value)}`, 50); - } - } - else if (entry.texture || entry.storageTexture) { - const bindingInfo = materialContext.textures[name]; - if (bindingInfo) { - if (this._engine.dbgSanityChecks && bindingInfo.texture === null) { - logger_Logger.Error(`Trying to bind a null texture! entry=${JSON.stringify(entry)}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => key === "texture" ? "<no dump>" : value)}, materialContext.uniqueId=${materialContext.uniqueId}`, 50); - continue; - } - const hardwareTexture = bindingInfo.texture._hardwareTexture; - if (this._engine.dbgSanityChecks && - (!hardwareTexture || (entry.texture && !hardwareTexture.view) || (entry.storageTexture && !hardwareTexture.viewForWriting))) { - logger_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" ? "<no dump>" : value))}, isReady=${(_j = bindingInfo.texture) === null || _j === void 0 ? void 0 : _j.isReady}, materialContext.uniqueId=${materialContext.uniqueId}`, 50); - continue; - } - entries[j].resource = entry.storageTexture ? hardwareTexture.viewForWriting : hardwareTexture.view; - } - else { - logger_Logger.Error(`Texture "${name}" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === "texture" || key === "sampler" ? "<no dump>" : value)}`, 50); - } - } - else if (entry.externalTexture) { - const bindingInfo = materialContext.textures[name]; - if (bindingInfo) { - if (this._engine.dbgSanityChecks && bindingInfo.texture === null) { - logger_Logger.Error(`Trying to bind a null external texture! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === "texture" ? "<no dump>" : value))}, materialContext.uniqueId=${materialContext.uniqueId}`, 50); - continue; - } - const externalTexture = bindingInfo.texture.underlyingResource; - if (this._engine.dbgSanityChecks && !externalTexture) { - logger_Logger.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === "texture" ? "<no dump>" : value))}, isReady=${(_k = bindingInfo.texture) === null || _k === void 0 ? void 0 : _k.isReady}, materialContext.uniqueId=${materialContext.uniqueId}`, 50); - continue; - } - entries[j].resource = this._device.importExternalTexture({ source: externalTexture }); - } - else { - logger_Logger.Error(`Texture "${name}" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === "texture" || key === "sampler" ? "<no dump>" : value)}`, 50); - } - } - else if (entry.buffer) { - const dataBuffer = drawContext.buffers[name]; - if (dataBuffer) { - const webgpuBuffer = dataBuffer.underlyingResource; - entries[j].resource.buffer = webgpuBuffer; - entries[j].resource.size = dataBuffer.capacity; - } - else { - logger_Logger.Error(`Can't find buffer "${name}". entry=${JSON.stringify(entry)}, buffers=${JSON.stringify(drawContext.buffers)}, drawContext.uniqueId=${drawContext.uniqueId}`, 50); - } - } - } - const groupLayout = bindGroupLayouts[i]; - bindGroups[i] = this._device.createBindGroup({ - layout: groupLayout, - entries, - }); - } - return bindGroups; - } -} -WebGPUCacheBindGroups.NumBindGroupsCreatedTotal = 0; -WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = 0; -WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = 0; -WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = 0; -WebGPUCacheBindGroups._Cache = new WebGPUBindGroupCacheNode(); -WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0; -WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0; -WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0; -//# sourceMappingURL=webgpuCacheBindGroups.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/clearQuad.vertex.js -// Do not edit. - -const clearQuad_vertex_name = "clearQuadVertexShader"; -const clearQuad_vertex_shader = `uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0), -vec2(1.0,1.0), -vec2(-1.0,-1.0), -vec2(1.0,-1.0)}; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -gl_Position=vec4(pos[gl_VertexID],depthValue,1.0); -#define CUSTOM_VERTEX_MAIN_END -} -`; -// Sideeffect -ShaderStore.ShadersStore[clearQuad_vertex_name] = clearQuad_vertex_shader; -/** @internal */ -const clearQuadVertexShader = { name: clearQuad_vertex_name, shader: clearQuad_vertex_shader }; -//# sourceMappingURL=clearQuad.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/clearQuad.fragment.js -// Do not edit. - -const clearQuad_fragment_name = "clearQuadPixelShader"; -const clearQuad_fragment_shader = `uniform vec4 color;void main() {gl_FragColor=color;} -`; -// Sideeffect -ShaderStore.ShadersStore[clearQuad_fragment_name] = clearQuad_fragment_shader; -/** @internal */ -const clearQuadPixelShader = { name: clearQuad_fragment_name, shader: clearQuad_fragment_shader }; -//# sourceMappingURL=clearQuad.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuClearQuad.js - - - - - - -/** @internal */ -class WebGPUClearQuad { - setDepthStencilFormat(format) { - this._depthTextureFormat = format; - this._cacheRenderPipeline.setDepthStencilFormat(format); - } - setColorFormat(format) { - this._cacheRenderPipeline.setColorFormat(format); - } - setMRTAttachments(attachments, textureArray, textureCount) { - this._cacheRenderPipeline.setMRT(textureArray, textureCount); - this._cacheRenderPipeline.setMRTAttachments(attachments); - } - constructor(device, engine, emptyVertexBuffer) { - this._bindGroups = {}; - this._bundleCache = {}; - this._keyTemp = []; - this._device = device; - this._engine = engine; - this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, emptyVertexBuffer, !engine._caps.textureFloatLinearFiltering); - this._cacheRenderPipeline.setDepthTestEnabled(false); - this._cacheRenderPipeline.setStencilReadMask(0xff); - this._effect = engine.createEffect("clearQuad", [], ["color", "depthValue"]); - } - clear(renderPass, clearColor, clearDepth, clearStencil, sampleCount = 1) { - var _a, _b; - let renderPass2; - let bundle = null; - let bundleKey; - const isRTTPass = !!this._engine._currentRenderTarget; - if (renderPass) { - renderPass2 = renderPass; - } - else { - let idx = 0; - this._keyTemp.length = 0; - for (let i = 0; i < this._cacheRenderPipeline.colorFormats.length; ++i) { - this._keyTemp[idx++] = renderableTextureFormatToIndex[(_a = this._cacheRenderPipeline.colorFormats[i]) !== null && _a !== void 0 ? _a : ""]; - } - const depthStencilFormatIndex = renderableTextureFormatToIndex[(_b = this._depthTextureFormat) !== null && _b !== void 0 ? _b : 0]; - this._keyTemp[idx] = - (clearColor ? clearColor.r + clearColor.g * 256 + clearColor.b * 256 * 256 + clearColor.a * 256 * 256 * 256 : 0) + - (clearDepth ? 2 ** 32 : 0) + - (clearStencil ? 2 ** 33 : 0) + - (this._engine.useReverseDepthBuffer ? 2 ** 34 : 0) + - (isRTTPass ? 2 ** 35 : 0) + - (sampleCount > 1 ? 2 ** 36 : 0) + - depthStencilFormatIndex * 2 ** 37; - bundleKey = this._keyTemp.join("_"); - bundle = this._bundleCache[bundleKey]; - if (bundle) { - return bundle; - } - renderPass2 = this._device.createRenderBundleEncoder({ - colorFormats: this._cacheRenderPipeline.colorFormats, - depthStencilFormat: this._depthTextureFormat, - sampleCount, - }); - } - this._cacheRenderPipeline.setDepthWriteEnabled(!!clearDepth); - this._cacheRenderPipeline.setStencilEnabled(!!clearStencil && !!this._depthTextureFormat && WebGPUTextureHelper.HasStencilAspect(this._depthTextureFormat)); - this._cacheRenderPipeline.setStencilWriteMask(clearStencil ? 0xff : 0); - this._cacheRenderPipeline.setStencilCompare(clearStencil ? 519 : 512); - this._cacheRenderPipeline.setStencilPassOp(clearStencil ? 7681 : 7680); - this._cacheRenderPipeline.setWriteMask(clearColor ? 0xf : 0); - const pipeline = this._cacheRenderPipeline.getRenderPipeline(7, this._effect, sampleCount); - const webgpuPipelineContext = this._effect._pipelineContext; - if (clearColor) { - this._effect.setDirectColor4("color", clearColor); - } - this._effect.setFloat("depthValue", this._engine.useReverseDepthBuffer ? this._engine._clearReverseDepthValue : this._engine._clearDepthValue); - webgpuPipelineContext.uniformBuffer.update(); - const bufferInternals = isRTTPass ? this._engine._ubInvertY : this._engine._ubDontInvertY; - const bufferLeftOver = webgpuPipelineContext.uniformBuffer.getBuffer(); - const key = bufferLeftOver.uniqueId + "-" + bufferInternals.uniqueId; - let bindGroups = this._bindGroups[key]; - if (!bindGroups) { - const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts[0]; - bindGroups = this._bindGroups[key] = []; - bindGroups.push(this._device.createBindGroup({ - layout: bindGroupLayouts[0], - entries: [], - })); - if (!WebGPUShaderProcessingContext._SimplifiedKnownBindings) { - bindGroups.push(this._device.createBindGroup({ - layout: bindGroupLayouts[1], - entries: [], - })); - } - bindGroups.push(this._device.createBindGroup({ - layout: bindGroupLayouts[WebGPUShaderProcessingContext._SimplifiedKnownBindings ? 1 : 2], - entries: [ - { - binding: 0, - resource: { - buffer: bufferInternals.underlyingResource, - size: bufferInternals.capacity, - }, - }, - { - binding: 1, - resource: { - buffer: bufferLeftOver.underlyingResource, - size: bufferLeftOver.capacity, - }, - }, - ], - })); - } - renderPass2.setPipeline(pipeline); - for (let i = 0; i < bindGroups.length; ++i) { - renderPass2.setBindGroup(i, bindGroups[i]); - } - renderPass2.draw(4, 1, 0, 0); - if (!renderPass) { - bundle = renderPass2.finish(); - this._bundleCache[bundleKey] = bundle; - } - return bundle; - } -} -//# sourceMappingURL=webgpuClearQuad.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuBundleList.js -/** @internal */ -class WebGPURenderItemViewport { - constructor(x, y, w, h) { - this.x = Math.floor(x); - this.y = Math.floor(y); - this.w = Math.floor(w); - this.h = Math.floor(h); - } - run(renderPass) { - renderPass.setViewport(this.x, this.y, this.w, this.h, 0, 1); - } - clone() { - return new WebGPURenderItemViewport(this.x, this.y, this.w, this.h); - } -} -/** @internal */ -class WebGPURenderItemScissor { - constructor(x, y, w, h) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; - } - run(renderPass) { - renderPass.setScissorRect(this.x, this.y, this.w, this.h); - } - clone() { - return new WebGPURenderItemScissor(this.x, this.y, this.w, this.h); - } -} -/** @internal */ -class WebGPURenderItemStencilRef { - constructor(ref) { - this.ref = ref; - } - run(renderPass) { - renderPass.setStencilReference(this.ref); - } - clone() { - return new WebGPURenderItemStencilRef(this.ref); - } -} -/** @internal */ -class WebGPURenderItemBlendColor { - constructor(color) { - this.color = color; - } - run(renderPass) { - renderPass.setBlendConstant(this.color); - } - clone() { - return new WebGPURenderItemBlendColor(this.color); - } -} -/** @internal */ -class WebGPURenderItemBeginOcclusionQuery { - constructor(query) { - this.query = query; - } - run(renderPass) { - renderPass.beginOcclusionQuery(this.query); - } - clone() { - return new WebGPURenderItemBeginOcclusionQuery(this.query); - } -} -/** @internal */ -class WebGPURenderItemEndOcclusionQuery { - constructor() { } - run(renderPass) { - renderPass.endOcclusionQuery(); - } - clone() { - return new WebGPURenderItemEndOcclusionQuery(); - } -} -class WebGPURenderItemBundles { - constructor() { - this.bundles = []; - } - run(renderPass) { - renderPass.executeBundles(this.bundles); - } - clone() { - const cloned = new WebGPURenderItemBundles(); - cloned.bundles = this.bundles; - return cloned; - } -} -/** @internal */ -class WebGPUBundleList { - constructor(device) { - this.numDrawCalls = 0; - this._device = device; - this._list = new Array(10); - this._listLength = 0; - } - addBundle(bundle) { - if (!this._currentItemIsBundle) { - const item = new WebGPURenderItemBundles(); - this._list[this._listLength++] = item; - this._currentBundleList = item.bundles; - this._currentItemIsBundle = true; - } - if (bundle) { - this._currentBundleList.push(bundle); - } - } - _finishBundle() { - if (this._currentItemIsBundle && this._bundleEncoder) { - this._currentBundleList.push(this._bundleEncoder.finish()); - this._bundleEncoder = undefined; - this._currentItemIsBundle = false; - } - } - addItem(item) { - this._finishBundle(); - this._list[this._listLength++] = item; - this._currentItemIsBundle = false; - } - getBundleEncoder(colorFormats, depthStencilFormat, sampleCount) { - if (!this._currentItemIsBundle) { - this.addBundle(); - this._bundleEncoder = this._device.createRenderBundleEncoder({ - colorFormats, - depthStencilFormat, - sampleCount, - }); - } - return this._bundleEncoder; - } - close() { - this._finishBundle(); - } - run(renderPass) { - this.close(); - for (let i = 0; i < this._listLength; ++i) { - this._list[i].run(renderPass); - } - } - reset() { - this._listLength = 0; - this._currentItemIsBundle = false; - this.numDrawCalls = 0; - } - clone() { - this.close(); - const cloned = new WebGPUBundleList(this._device); - cloned._list = new Array(this._listLength); - cloned._listLength = this._listLength; - cloned.numDrawCalls = this.numDrawCalls; - for (let i = 0; i < this._listLength; ++i) { - cloned._list[i] = this._list[i].clone(); - } - return cloned; - } -} -//# sourceMappingURL=webgpuBundleList.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuQuerySet.js - -/** @internal */ -class WebGPUQuerySet { - get querySet() { - return this._querySet; - } - constructor(count, type, device, bufferManager, canUseMultipleBuffers = true) { - this._dstBuffers = []; - this._device = device; - this._bufferManager = bufferManager; - this._count = count; - this._canUseMultipleBuffers = canUseMultipleBuffers; - this._querySet = device.createQuerySet({ - type, - count, - }); - this._queryBuffer = bufferManager.createRawBuffer(8 * count, BufferUsage.QueryResolve | BufferUsage.CopySrc); - if (!canUseMultipleBuffers) { - this._dstBuffers.push(this._bufferManager.createRawBuffer(8 * this._count, BufferUsage.MapRead | BufferUsage.CopyDst)); - } - } - _getBuffer(firstQuery, queryCount) { - if (!this._canUseMultipleBuffers && this._dstBuffers.length === 0) { - return null; - } - const encoderResult = this._device.createCommandEncoder(); - let buffer; - if (this._dstBuffers.length === 0) { - buffer = this._bufferManager.createRawBuffer(8 * this._count, BufferUsage.MapRead | BufferUsage.CopyDst); - } - else { - buffer = this._dstBuffers[this._dstBuffers.length - 1]; - this._dstBuffers.length--; - } - encoderResult.resolveQuerySet(this._querySet, firstQuery, queryCount, this._queryBuffer, 0); - encoderResult.copyBufferToBuffer(this._queryBuffer, 0, buffer, 0, 8 * queryCount); - this._device.queue.submit([encoderResult.finish()]); - return buffer; - } - async readValues(firstQuery = 0, queryCount = 1) { - const buffer = this._getBuffer(firstQuery, queryCount); - if (buffer === null) { - return null; - } - await buffer.mapAsync(MapMode.Read); - const arrayBuf = new BigUint64Array(buffer.getMappedRange()).slice(); - buffer.unmap(); - this._dstBuffers[this._dstBuffers.length] = buffer; - return arrayBuf; - } - async readValue(firstQuery = 0) { - const buffer = this._getBuffer(firstQuery, 1); - if (buffer === null) { - return null; - } - await buffer.mapAsync(MapMode.Read); - const arrayBuf = new BigUint64Array(buffer.getMappedRange()); - const value = Number(arrayBuf[0]); - buffer.unmap(); - this._dstBuffers[this._dstBuffers.length] = buffer; - return value; - } - async readTwoValuesAndSubtract(firstQuery = 0) { - const buffer = this._getBuffer(firstQuery, 2); - if (buffer === null) { - return null; - } - await buffer.mapAsync(MapMode.Read); - const arrayBuf = new BigUint64Array(buffer.getMappedRange()); - const value = Number(arrayBuf[1] - arrayBuf[0]); - buffer.unmap(); - this._dstBuffers[this._dstBuffers.length] = buffer; - return value; - } - dispose() { - this._querySet.destroy(); - this._bufferManager.releaseBuffer(this._queryBuffer); - for (let i = 0; i < this._dstBuffers.length; ++i) { - this._bufferManager.releaseBuffer(this._dstBuffers[i]); - } - } -} -//# sourceMappingURL=webgpuQuerySet.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuTimestampQuery.js - - - -/** @internal */ -class WebGPUTimestampQuery { - get gpuFrameTimeCounter() { - return this._gpuFrameTimeCounter; - } - constructor(device, bufferManager) { - this._enabled = false; - this._gpuFrameTimeCounter = new perfCounter_PerfCounter(); - this._measureDurationState = 0; - this._device = device; - this._bufferManager = bufferManager; - } - get enable() { - return this._enabled; - } - set enable(value) { - if (this._enabled === value) { - return; - } - this._enabled = value; - this._measureDurationState = 0; - if (value) { - this._measureDuration = new WebGPUDurationMeasure(this._device, this._bufferManager); - } - else { - this._measureDuration.dispose(); - } - } - startFrame(commandEncoder) { - if (this._enabled && this._measureDurationState === 0) { - this._measureDuration.start(commandEncoder); - this._measureDurationState = 1; - } - } - endFrame(commandEncoder) { - if (this._measureDurationState === 1) { - this._measureDurationState = 2; - this._measureDuration.stop(commandEncoder).then((duration) => { - if (duration !== null && duration >= 0) { - this._gpuFrameTimeCounter.fetchNewFrame(); - this._gpuFrameTimeCounter.addCount(duration, true); - } - this._measureDurationState = 0; - }); - } - } -} -/** @internal */ -class WebGPUDurationMeasure { - constructor(device, bufferManager) { - this._querySet = new WebGPUQuerySet(2, QueryType.Timestamp, device, bufferManager); - } - start(encoder) { - encoder.writeTimestamp(this._querySet.querySet, 0); - } - async stop(encoder) { - encoder.writeTimestamp(this._querySet.querySet, 1); - return this._querySet.readTwoValuesAndSubtract(0); - } - dispose() { - this._querySet.dispose(); - } -} -//# sourceMappingURL=webgpuTimestampQuery.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuOcclusionQuery.js - - -/** @internal */ -class WebGPUOcclusionQuery { - get querySet() { - return this._querySet.querySet; - } - get hasQueries() { - return this._currentTotalIndices !== this._availableIndices.length; - } - get canBeginQuery() { - const passIndex = this._engine._getCurrentRenderPassIndex(); - switch (passIndex) { - case 0: { - return this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet !== undefined; - } - case 1: { - return this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet !== undefined; - } - } - return false; - } - constructor(engine, device, bufferManager, startCount = 50, incrementCount = 100) { - this._availableIndices = []; - this._engine = engine; - this._device = device; - this._bufferManager = bufferManager; - this._frameLastBuffer = -1; - this._currentTotalIndices = 0; - this._countIncrement = incrementCount; - this._allocateNewIndices(startCount); - } - createQuery() { - if (this._availableIndices.length === 0) { - this._allocateNewIndices(); - } - const index = this._availableIndices[this._availableIndices.length - 1]; - this._availableIndices.length--; - return index; - } - deleteQuery(index) { - this._availableIndices[this._availableIndices.length - 1] = index; - } - isQueryResultAvailable(index) { - this._retrieveQueryBuffer(); - return !!this._lastBuffer && index < this._lastBuffer.length; - } - getQueryResult(index) { - var _a, _b; - return Number((_b = (_a = this._lastBuffer) === null || _a === void 0 ? void 0 : _a[index]) !== null && _b !== void 0 ? _b : -1); - } - _retrieveQueryBuffer() { - if (this._lastBuffer && this._frameLastBuffer === this._engine.frameId) { - return; - } - if (this._frameLastBuffer !== this._engine.frameId) { - this._frameLastBuffer = this._engine.frameId; - this._querySet.readValues(0, this._currentTotalIndices).then((arrayBuffer) => { - this._lastBuffer = arrayBuffer; - }); - } - } - _allocateNewIndices(numIndices) { - numIndices = numIndices !== null && numIndices !== void 0 ? numIndices : this._countIncrement; - this._delayQuerySetDispose(); - for (let i = 0; i < numIndices; ++i) { - this._availableIndices.push(this._currentTotalIndices + i); - } - this._currentTotalIndices += numIndices; - this._querySet = new WebGPUQuerySet(this._currentTotalIndices, QueryType.Occlusion, this._device, this._bufferManager, false); - } - _delayQuerySetDispose() { - const querySet = this._querySet; - if (querySet) { - // Wait a bit before disposing of the queryset, in case some queries are still running for it - setTimeout(() => querySet.dispose, 1000); - } - } - dispose() { - var _a; - (_a = this._querySet) === null || _a === void 0 ? void 0 : _a.dispose(); - this._availableIndices.length = 0; - } -} -//# sourceMappingURL=webgpuOcclusionQuery.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuTintWASM.js - - -/** @internal */ -class WebGPUTintWASM { - async initTwgsl(twgslOptions) { - if (WebGPUTintWASM._twgsl) { - return; - } - twgslOptions = twgslOptions || {}; - twgslOptions = Object.assign(Object.assign({}, WebGPUTintWASM._TWgslDefaultOptions), twgslOptions); - if (twgslOptions.twgsl) { - WebGPUTintWASM._twgsl = twgslOptions.twgsl; - return Promise.resolve(); - } - if (twgslOptions.jsPath && twgslOptions.wasmPath) { - if (IsWindowObjectExist()) { - await tools_Tools.LoadScriptAsync(twgslOptions.jsPath); - } - else { - importScripts(twgslOptions.jsPath); - } - } - if (self.twgsl) { - WebGPUTintWASM._twgsl = await self.twgsl(twgslOptions.wasmPath); - return Promise.resolve(); - } - return Promise.reject("twgsl is not available."); - } - convertSpirV2WGSL(code, disableUniformityAnalysis = false) { - const ccode = WebGPUTintWASM._twgsl.convertSpirV2WGSL(code); - if (WebGPUTintWASM.ShowWGSLShaderCode) { - console.log(ccode); - console.log("***********************************************"); - } - return WebGPUTintWASM.DisableUniformityAnalysis || disableUniformityAnalysis ? "diagnostic(off, derivative_uniformity);\n" + ccode : ccode; - } -} -// Default twgsl options. -WebGPUTintWASM._TWgslDefaultOptions = { - jsPath: "https://preview.babylonjs.com/twgsl/twgsl.js", - wasmPath: "https://preview.babylonjs.com/twgsl/twgsl.wasm", -}; -WebGPUTintWASM.ShowWGSLShaderCode = false; -WebGPUTintWASM.DisableUniformityAnalysis = false; -WebGPUTintWASM._twgsl = null; -//# sourceMappingURL=webgpuTintWASM.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuSnapshotRendering.js - -/** @internal */ -class WebGPUSnapshotRendering { - constructor(engine, renderingMode, bundleList, bundleListRenderTarget) { - this._record = false; - this._play = false; - this._mainPassBundleList = []; - this._enabled = false; - this._engine = engine; - this._mode = renderingMode; - this._bundleList = bundleList; - this._bundleListRenderTarget = bundleListRenderTarget; - } - get enabled() { - return this._enabled; - } - get play() { - return this._play; - } - get record() { - return this._record; - } - set enabled(activate) { - this._mainPassBundleList.length = 0; - this._record = this._enabled = activate; - this._play = false; - if (activate) { - this._modeSaved = this._mode; - this._mode = 0; // need to reset to standard for the recording pass to avoid some code being bypassed - } - } - get mode() { - return this._mode; - } - set mode(mode) { - if (this._record) { - this._modeSaved = mode; - } - else { - this._mode = mode; - } - } - endMainRenderPass() { - if (this._record) { - this._mainPassBundleList.push(this._bundleList.clone()); - } - } - endRenderTargetPass(currentRenderPass, gpuWrapper) { - var _a, _b, _c, _d; - if (this._play) { - (_b = (_a = gpuWrapper._bundleLists) === null || _a === void 0 ? void 0 : _a[gpuWrapper._currentLayer]) === null || _b === void 0 ? void 0 : _b.run(currentRenderPass); - if (this._mode === 1) { - this._engine._reportDrawCall((_d = (_c = gpuWrapper._bundleLists) === null || _c === void 0 ? void 0 : _c[gpuWrapper._currentLayer]) === null || _d === void 0 ? void 0 : _d.numDrawCalls); - } - } - else if (this._record) { - if (!gpuWrapper._bundleLists) { - gpuWrapper._bundleLists = []; - } - gpuWrapper._bundleLists[gpuWrapper._currentLayer] = this._bundleListRenderTarget.clone(); - gpuWrapper._bundleLists[gpuWrapper._currentLayer].run(currentRenderPass); - this._bundleListRenderTarget.reset(); - } - else { - return false; - } - return true; - } - endFrame(mainRenderPass) { - if (this._record) { - this._mainPassBundleList.push(this._bundleList.clone()); - this._record = false; - this._play = true; - this._mode = this._modeSaved; - } - if (mainRenderPass !== null && this._play) { - for (let i = 0; i < this._mainPassBundleList.length; ++i) { - this._mainPassBundleList[i].run(mainRenderPass); - if (this._mode === 1) { - this._engine._reportDrawCall(this._mainPassBundleList[i].numDrawCalls); - } - } - } - } - reset() { - this.enabled = false; - this.enabled = true; - } -} -//# sourceMappingURL=webgpuSnapshotRendering.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/postprocess.vertex.js -// Do not edit. - -const ShadersWGSL_postprocess_vertex_name = "postprocessVertexShader"; -const postprocess_vertex_shader = `attribute position: vec2<f32>;uniform scale: vec2<f32>;varying vUV: vec2<f32>;const madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -@vertex -fn main(input : VertexInputs)->FragmentInputs { -#define CUSTOM_VERTEX_MAIN_BEGIN -vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -} -`; -// Sideeffect -ShaderStore.ShadersStoreWGSL[ShadersWGSL_postprocess_vertex_name] = postprocess_vertex_shader; -/** @internal */ -const postprocess_vertex_postprocessVertexShader = { name: ShadersWGSL_postprocess_vertex_name, shader: postprocess_vertex_shader }; -//# sourceMappingURL=postprocess.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/webgpuEngine.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -const viewDescriptorSwapChainAntialiasing = { - label: `TextureView_SwapChain_ResolveTarget`, - dimension: TextureDimension.E2d, - format: undefined, - mipLevelCount: 1, - arrayLayerCount: 1, -}; -const viewDescriptorSwapChain = { - label: `TextureView_SwapChain`, - dimension: TextureDimension.E2d, - format: undefined, - mipLevelCount: 1, - arrayLayerCount: 1, -}; -const disableUniformityAnalysisMarker = "/* disable_uniformity_analysis */"; -const tempColor4 = new math_color_Color4(); -/** - * The web GPU engine class provides support for WebGPU version of babylon.js. - * @since 5.0.0 - */ -class webgpuEngine_WebGPUEngine extends engine_Engine { - /** - * Gets or sets the snapshot rendering mode - */ - get snapshotRenderingMode() { - return this._snapshotRendering.mode; - } - set snapshotRenderingMode(mode) { - this._snapshotRendering.mode = mode; - } - /** - * Creates a new snapshot at the next frame using the current snapshotRenderingMode - */ - snapshotRenderingReset() { - this._snapshotRendering.reset(); - } - /** - * Enables or disables the snapshot rendering mode - * Note that the WebGL engine does not support snapshot rendering so setting the value won't have any effect for this engine - */ - get snapshotRendering() { - return this._snapshotRendering.enabled; - } - set snapshotRendering(activate) { - this._snapshotRendering.enabled = activate; - } - /** - * Sets this to true to disable the cache for the samplers. You should do it only for testing purpose! - */ - get disableCacheSamplers() { - return this._cacheSampler ? this._cacheSampler.disabled : false; - } - set disableCacheSamplers(disable) { - if (this._cacheSampler) { - this._cacheSampler.disabled = disable; - } - } - /** - * Sets this to true to disable the cache for the render pipelines. You should do it only for testing purpose! - */ - get disableCacheRenderPipelines() { - return this._cacheRenderPipeline ? this._cacheRenderPipeline.disabled : false; - } - set disableCacheRenderPipelines(disable) { - if (this._cacheRenderPipeline) { - this._cacheRenderPipeline.disabled = disable; - } - } - /** - * Sets this to true to disable the cache for the bind groups. You should do it only for testing purpose! - */ - get disableCacheBindGroups() { - return this._cacheBindGroups ? this._cacheBindGroups.disabled : false; - } - set disableCacheBindGroups(disable) { - if (this._cacheBindGroups) { - this._cacheBindGroups.disabled = disable; - } - } - /** - * Gets a Promise<boolean> indicating if the engine can be instantiated (ie. if a WebGPU context can be found) - */ - static get IsSupportedAsync() { - return !navigator.gpu - ? Promise.resolve(false) - : navigator.gpu - .requestAdapter() - .then((adapter) => !!adapter, () => false) - .catch(() => false); - } - /** - * Not supported by WebGPU, you should call IsSupportedAsync instead! - */ - static get IsSupported() { - logger_Logger.Warn("You must call IsSupportedAsync for WebGPU!"); - return false; - } - /** - * Gets a boolean indicating that the engine supports uniform buffers - */ - get supportsUniformBuffers() { - return true; - } - /** Gets the supported extensions by the WebGPU adapter */ - get supportedExtensions() { - return this._adapterSupportedExtensions; - } - /** Gets the currently enabled extensions on the WebGPU device */ - get enabledExtensions() { - return this._deviceEnabledExtensions; - } - /** Gets the supported limits by the WebGPU adapter */ - get supportedLimits() { - return this._adapterSupportedLimits; - } - /** Gets the current limits of the WebGPU device */ - get currentLimits() { - return this._deviceLimits; - } - /** - * Returns a string describing the current engine - */ - get description() { - const description = this.name + this.version; - return description; - } - /** - * Returns the version of the engine - */ - get version() { - return 1; - } - /** - * Gets an object containing information about the current engine context - * @returns an object containing the vendor, the renderer and the version of the current engine context - */ - getInfo() { - return { - vendor: this._adapterInfo.vendor || "unknown vendor", - renderer: this._adapterInfo.architecture || "unknown renderer", - version: this._adapterInfo.description || "unknown version", - }; - } - /** - * (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL). - * Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken. - * See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details - */ - get compatibilityMode() { - return this._compatibilityMode; - } - set compatibilityMode(mode) { - this._compatibilityMode = mode; - } - /** @internal */ - get currentSampleCount() { - return this._currentRenderTarget ? this._currentRenderTarget.samples : this._mainPassSampleCount; - } - /** - * Create a new instance of the gpu engine asynchronously - * @param canvas Defines the canvas to use to display the result - * @param options Defines the options passed to the engine to create the GPU context dependencies - * @returns a promise that resolves with the created engine - */ - static CreateAsync(canvas, options = {}) { - const engine = new webgpuEngine_WebGPUEngine(canvas, options); - return new Promise((resolve) => { - engine.initAsync(options.glslangOptions, options.twgslOptions).then(() => resolve(engine)); - }); - } - /** - * Create a new instance of the gpu engine. - * @param canvas Defines the canvas to use to display the result - * @param options Defines the options passed to the engine to create the GPU context dependencies - */ - constructor(canvas, options = {}) { - var _a, _b; - super(null, (_a = options.antialias) !== null && _a !== void 0 ? _a : true, options); - // Page Life cycle and constants - this._uploadEncoderDescriptor = { label: "upload" }; - this._renderEncoderDescriptor = { label: "render" }; - this._renderTargetEncoderDescriptor = { label: "renderTarget" }; - /** @internal */ - this._clearDepthValue = 1; - /** @internal */ - this._clearReverseDepthValue = 0; - /** @internal */ - this._clearStencilValue = 0; - this._defaultSampleCount = 4; // Only supported value for now. - this._glslang = null; - this._tintWASM = null; - this._adapterInfo = { - vendor: "", - architecture: "", - device: "", - description: "", - }; - /** @internal */ - this._compiledComputeEffects = {}; - /** @internal */ - this._counters = { - numEnableEffects: 0, - numEnableDrawWrapper: 0, - numBundleCreationNonCompatMode: 0, - numBundleReuseNonCompatMode: 0, - }; - /** - * Counters from last frame - */ - this.countersLastFrame = { - numEnableEffects: 0, - numEnableDrawWrapper: 0, - numBundleCreationNonCompatMode: 0, - numBundleReuseNonCompatMode: 0, - }; - /** - * Max number of uncaptured error messages to log - */ - this.numMaxUncapturedErrors = 20; - this._commandBuffers = [null, null, null]; - // Frame Buffer Life Cycle (recreated for each render target pass) - /** @internal */ - this._currentRenderPass = null; - /** @internal */ - this._mainRenderPassWrapper = new WebGPURenderPassWrapper(); - /** @internal */ - this._rttRenderPassWrapper = new WebGPURenderPassWrapper(); - /** @internal */ - this._pendingDebugCommands = []; - /** @internal */ - this._onAfterUnbindFrameBufferObservable = new observable_Observable(); - this._currentOverrideVertexBuffers = null; - this._currentIndexBuffer = null; - this._colorWriteLocal = true; - this._forceEnableEffect = false; - // TODO WEBGPU remove those variables when code stabilized - /** @internal */ - this.dbgShowShaderCode = false; - /** @internal */ - this.dbgSanityChecks = true; - /** @internal */ - this.dbgVerboseLogsForFirstFrames = false; - /** @internal */ - this.dbgVerboseLogsNumFrames = 10; - /** @internal */ - this.dbgLogIfNotDrawWrapper = true; - /** @internal */ - this.dbgShowEmptyEnableEffectCalls = true; - /** - * Indicates if the z range in NDC space is 0..1 (value: true) or -1..1 (value: false) - */ - this.isNDCHalfZRange = true; - /** - * Indicates that the origin of the texture/framebuffer space is the bottom left corner. If false, the origin is top left - */ - this.hasOriginBottomLeft = false; - //------------------------------------------------------------------------------ - // Dynamic WebGPU States - //------------------------------------------------------------------------------ - // index 0 is for main render pass, 1 for RTT render pass - 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"; - options.deviceDescriptor = options.deviceDescriptor || {}; - options.enableGPUDebugMarkers = (_b = options.enableGPUDebugMarkers) !== null && _b !== void 0 ? _b : false; - logger_Logger.Log(`Babylon.js v${engine_Engine.Version} - ${this.description} engine`); - if (!navigator.gpu) { - logger_Logger.Error("WebGPU is not supported by your browser."); - return; - } - options.swapChainFormat = options.swapChainFormat || navigator.gpu.getPreferredCanvasFormat(); - this._isWebGPU = true; - this._shaderPlatformName = "WEBGPU"; - this._renderingCanvas = canvas; - this._options = options; - this._mainPassSampleCount = options.antialias ? this._defaultSampleCount : 1; - this._setupMobileChecks(); - this._sharedInit(canvas); - this._shaderProcessor = new WebGPUShaderProcessorGLSL(); - this._shaderProcessorWGSL = new WebGPUShaderProcessorWGSL(); - } - //------------------------------------------------------------------------------ - // Initialization - //------------------------------------------------------------------------------ - /** - * Initializes the WebGPU context and dependencies. - * @param glslangOptions Defines the GLSLang compiler options if necessary - * @param twgslOptions Defines the Twgsl compiler options if necessary - * @returns a promise notifying the readiness of the engine. - */ - initAsync(glslangOptions, twgslOptions) { - var _a; - return this._initGlslang(glslangOptions !== null && glslangOptions !== void 0 ? glslangOptions : (_a = this._options) === null || _a === void 0 ? void 0 : _a.glslangOptions) - .then((glslang) => { - var _a; - this._glslang = glslang; - this._tintWASM = webgpuEngine_WebGPUEngine.UseTWGSL ? new WebGPUTintWASM() : null; - return this._tintWASM - ? this._tintWASM.initTwgsl(twgslOptions !== null && twgslOptions !== void 0 ? twgslOptions : (_a = this._options) === null || _a === void 0 ? void 0 : _a.twgslOptions).then(() => { - return navigator.gpu.requestAdapter(this._options); - }, (msg) => { - logger_Logger.Error("Can not initialize twgsl!"); - logger_Logger.Error(msg); - throw Error("WebGPU initializations stopped."); - }) - : navigator.gpu.requestAdapter(this._options); - }, (msg) => { - logger_Logger.Error("Can not initialize glslang!"); - logger_Logger.Error(msg); - throw Error("WebGPU initializations stopped."); - }) - .then((adapter) => { - var _a, _b, _c; - if (!adapter) { - throw "Could not retrieve a WebGPU adapter (adapter is null)."; - } - else { - this._adapter = adapter; - this._adapterSupportedExtensions = []; - (_a = this._adapter.features) === null || _a === void 0 ? void 0 : _a.forEach((feature) => this._adapterSupportedExtensions.push(feature)); - this._adapterSupportedLimits = this._adapter.limits; - this._adapter.requestAdapterInfo().then((adapterInfo) => { - this._adapterInfo = adapterInfo; - }); - const deviceDescriptor = (_b = this._options.deviceDescriptor) !== null && _b !== void 0 ? _b : {}; - const requiredFeatures = (_c = deviceDescriptor === null || deviceDescriptor === void 0 ? void 0 : deviceDescriptor.requiredFeatures) !== null && _c !== void 0 ? _c : (this._options.enableAllFeatures ? this._adapterSupportedExtensions : undefined); - if (requiredFeatures) { - const requestedExtensions = requiredFeatures; - const validExtensions = []; - for (const extension of requestedExtensions) { - if (this._adapterSupportedExtensions.indexOf(extension) !== -1) { - validExtensions.push(extension); - } - } - deviceDescriptor.requiredFeatures = validExtensions; - } - if (this._options.setMaximumLimits && !deviceDescriptor.requiredLimits) { - deviceDescriptor.requiredLimits = {}; - for (const name in this._adapterSupportedLimits) { - deviceDescriptor.requiredLimits[name] = this._adapterSupportedLimits[name]; - } - } - return this._adapter.requestDevice(deviceDescriptor); - } - }) - .then((device) => { - var _a, _b; - this._device = device; - this._deviceEnabledExtensions = []; - (_a = this._device.features) === null || _a === void 0 ? void 0 : _a.forEach((feature) => this._deviceEnabledExtensions.push(feature)); - this._deviceLimits = device.limits; - let numUncapturedErrors = -1; - this._device.addEventListener("uncapturederror", (event) => { - if (++numUncapturedErrors < this.numMaxUncapturedErrors) { - logger_Logger.Warn(`WebGPU uncaptured error (${numUncapturedErrors + 1}): ${event.error} - ${event.error.message}`); - } - else if (numUncapturedErrors++ === this.numMaxUncapturedErrors) { - logger_Logger.Warn(`WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`); - } - }); - if (!this._doNotHandleContextLost) { - (_b = this._device.lost) === null || _b === void 0 ? void 0 : _b.then((info) => { - if (this._isDisposed) { - return; - } - this._contextWasLost = true; - logger_Logger.Warn("WebGPU context lost. " + info); - this.onContextLostObservable.notifyObservers(this); - this._restoreEngineAfterContextLost(this.initAsync.bind(this)); - }); - } - }, (e) => { - logger_Logger.Error("Could not retrieve a WebGPU device."); - logger_Logger.Error(e); - }) - .then(() => { - this._bufferManager = new WebGPUBufferManager(this._device); - this._textureHelper = new WebGPUTextureHelper(this._device, this._glslang, this._tintWASM, this._bufferManager, this._deviceEnabledExtensions); - this._cacheSampler = new WebGPUCacheSampler(this._device); - this._cacheBindGroups = new WebGPUCacheBindGroups(this._device, this._cacheSampler, this); - this._timestampQuery = new WebGPUTimestampQuery(this._device, this._bufferManager); - this._occlusionQuery = this._device.createQuerySet ? new WebGPUOcclusionQuery(this, this._device, this._bufferManager) : undefined; - this._bundleList = new WebGPUBundleList(this._device); - this._bundleListRenderTarget = new WebGPUBundleList(this._device); - this._snapshotRendering = new WebGPUSnapshotRendering(this, this._snapshotRenderingMode, this._bundleList, this._bundleListRenderTarget); - this._ubInvertY = this._bufferManager.createBuffer(new Float32Array([-1, 0]), BufferUsage.Uniform | BufferUsage.CopyDst); - this._ubDontInvertY = this._bufferManager.createBuffer(new Float32Array([1, 0]), BufferUsage.Uniform | BufferUsage.CopyDst); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - 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 buffer_VertexBuffer(this, [0], "", false, false, 1, false, 0, 1); - this._initializeLimits(); - this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, this._emptyVertexBuffer, !this._caps.textureFloatLinearFiltering); - this._depthCullingState = new WebGPUDepthCullingState(this._cacheRenderPipeline); - this._stencilStateComposer = new WebGPUStencilStateComposer(this._cacheRenderPipeline); - this._stencilStateComposer.stencilGlobal = this._stencilState; - this._depthCullingState.depthTest = true; - this._depthCullingState.depthFunc = 515; - this._depthCullingState.depthMask = true; - this._textureHelper.setCommandEncoder(this._uploadEncoder); - this._clearQuad = new WebGPUClearQuad(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) => { - logger_Logger.Error("Can not create WebGPU Device and/or context."); - logger_Logger.Error(e); - if (console.trace) { - console.trace(); - } - }); - } - _initGlslang(glslangOptions) { - glslangOptions = glslangOptions || {}; - glslangOptions = Object.assign(Object.assign({}, webgpuEngine_WebGPUEngine._GLSLslangDefaultOptions), glslangOptions); - if (glslangOptions.glslang) { - return Promise.resolve(glslangOptions.glslang); - } - if (self.glslang) { - return self.glslang(glslangOptions.wasmPath); - } - if (glslangOptions.jsPath && glslangOptions.wasmPath) { - if (IsWindowObjectExist()) { - return tools_Tools.LoadScriptAsync(glslangOptions.jsPath).then(() => { - return self.glslang(glslangOptions.wasmPath); - }); - } - else { - importScripts(glslangOptions.jsPath); - return self.glslang(glslangOptions.wasmPath); - } - } - return Promise.reject("gslang is not available."); - } - _initializeLimits() { - // Init caps - // TODO WEBGPU Real Capability check once limits will be working. - this._caps = { - maxTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage, - maxVertexTextureImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage, - maxCombinedTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage * 2, - maxTextureSize: this._deviceLimits.maxTextureDimension2D, - maxCubemapTextureSize: this._deviceLimits.maxTextureDimension2D, - maxRenderTextureSize: this._deviceLimits.maxTextureDimension2D, - maxVertexAttribs: this._deviceLimits.maxVertexAttributes, - maxVaryingVectors: this._deviceLimits.maxInterStageShaderVariables, - maxFragmentUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4), - maxVertexUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4), - standardDerivatives: true, - astc: (this._deviceEnabledExtensions.indexOf(FeatureName.TextureCompressionASTC) >= 0 ? true : undefined), - s3tc: (this._deviceEnabledExtensions.indexOf(FeatureName.TextureCompressionBC) >= 0 ? true : undefined), - pvrtc: null, - etc1: null, - etc2: (this._deviceEnabledExtensions.indexOf(FeatureName.TextureCompressionETC2) >= 0 ? true : undefined), - bptc: this._deviceEnabledExtensions.indexOf(FeatureName.TextureCompressionBC) >= 0 ? true : undefined, - maxAnisotropy: 16, - uintIndices: true, - fragmentDepthSupported: true, - highPrecisionShaderSupported: true, - colorBufferFloat: true, - textureFloat: true, - textureFloatLinearFiltering: this._deviceEnabledExtensions.indexOf(FeatureName.Float32Filterable) >= 0, - textureFloatRender: true, - textureHalfFloat: true, - textureHalfFloatLinearFiltering: true, - textureHalfFloatRender: true, - textureLOD: true, - texelFetch: true, - drawBuffersExtension: true, - depthTextureExtension: true, - vertexArrayObject: false, - instancedArrays: true, - timerQuery: typeof BigUint64Array !== "undefined" && this._deviceEnabledExtensions.indexOf(FeatureName.TimestampQuery) !== -1 ? true : undefined, - supportOcclusionQuery: typeof BigUint64Array !== "undefined", - canUseTimestampForTimerQuery: true, - multiview: false, - oculusMultiview: false, - parallelShaderCompile: undefined, - blendMinMax: true, - maxMSAASamples: 4, - canUseGLInstanceID: true, - canUseGLVertexID: true, - supportComputeShaders: true, - supportSRGBBuffers: true, - supportTransformFeedbacks: false, - textureMaxLevel: true, - texture2DArrayMaxLayerCount: this._deviceLimits.maxTextureArrayLayers, - disableMorphTargetTexture: false, - }; - this._caps.parallelShaderCompile = null; - this._features = { - forceBitmapOverHTMLImageElement: true, - supportRenderAndCopyToLodForFloatTextures: true, - supportDepthStencilTexture: true, - supportShadowSamplers: true, - uniformBufferHardCheckMatrix: false, - allowTexturePrefiltering: true, - trackUbosInFrame: true, - checkUbosContentBeforeUpload: true, - supportCSM: true, - basisNeedsPOT: false, - support3DTextures: true, - needTypeSuffixInShaderConstants: true, - supportMSAA: true, - supportSSAO2: true, - supportExtendedTextureFormats: true, - supportSwitchCaseInShader: true, - supportSyncTextureRead: false, - needsInvertingBitmap: false, - useUBOBindingCache: false, - needShaderCodeInlining: true, - needToAlwaysBindUniformBuffers: true, - supportRenderPasses: true, - supportSpriteInstancing: true, - _collectUbosUpdatedInFrame: false, - }; - } - _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 WebGPUHardwareTexture()]; - this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format = this._colorFormat; - } - // Set default values as WebGL with depth and stencil attachment for the broadest Compat. - _initializeMainAttachments() { - if (!this._bufferManager) { - return; - } - this.flushFramebuffer(false); - this._mainTextureExtends = { - width: this.getRenderWidth(true), - height: this.getRenderHeight(true), - depthOrArrayLayers: 1, - }; - const bufferDataUpdate = new Float32Array([this.getRenderHeight(true)]); - this._bufferManager.setSubData(this._ubInvertY, 4, bufferDataUpdate); - this._bufferManager.setSubData(this._ubDontInvertY, 4, bufferDataUpdate); - let mainColorAttachments; - if (this._options.antialias) { - const mainTextureDescriptor = { - label: `Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`, - size: this._mainTextureExtends, - mipLevelCount: 1, - sampleCount: this._mainPassSampleCount, - dimension: TextureDimension.E2d, - format: this._options.swapChainFormat, - usage: TextureUsage.RenderAttachment, - }; - if (this._mainTexture) { - this._textureHelper.releaseTexture(this._mainTexture); - } - this._mainTexture = this._device.createTexture(mainTextureDescriptor); - mainColorAttachments = [ - { - view: this._mainTexture.createView({ - label: "TextureView_MainColor_antialiasing", - dimension: TextureDimension.E2d, - format: this._options.swapChainFormat, - mipLevelCount: 1, - arrayLayerCount: 1, - }), - clearValue: new math_color_Color4(0, 0, 0, 1), - loadOp: LoadOp.Clear, - storeOp: 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! - }, - ]; - } - else { - mainColorAttachments = [ - { - view: undefined, - clearValue: new math_color_Color4(0, 0, 0, 1), - loadOp: LoadOp.Clear, - storeOp: StoreOp.Store, - }, - ]; - } - this._mainRenderPassWrapper.depthTextureFormat = this.isStencilEnable ? TextureFormat.Depth24PlusStencil8 : TextureFormat.Depth32Float; - this._setDepthTextureFormat(this._mainRenderPassWrapper); - const depthTextureDescriptor = { - label: `Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`, - size: this._mainTextureExtends, - mipLevelCount: 1, - sampleCount: this._mainPassSampleCount, - dimension: TextureDimension.E2d, - format: this._mainRenderPassWrapper.depthTextureFormat, - usage: TextureUsage.RenderAttachment, - }; - if (this._depthTexture) { - this._textureHelper.releaseTexture(this._depthTexture); - } - this._depthTexture = this._device.createTexture(depthTextureDescriptor); - const mainDepthAttachment = { - view: this._depthTexture.createView({ - label: `TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`, - dimension: TextureDimension.E2d, - format: this._depthTexture.format, - mipLevelCount: 1, - arrayLayerCount: 1, - }), - depthClearValue: this._clearDepthValue, - depthLoadOp: LoadOp.Clear, - depthStoreOp: StoreOp.Store, - stencilClearValue: this._clearStencilValue, - stencilLoadOp: !this.isStencilEnable ? undefined : LoadOp.Clear, - stencilStoreOp: !this.isStencilEnable ? undefined : StoreOp.Store, - }; - this._mainRenderPassWrapper.renderPassDescriptor = { - colorAttachments: mainColorAttachments, - depthStencilAttachment: mainDepthAttachment, - }; - } - _configureContext() { - this._context.configure({ - device: this._device, - format: this._options.swapChainFormat, - usage: TextureUsage.RenderAttachment | TextureUsage.CopySrc, - alphaMode: this.premultipliedAlpha ? CanvasAlphaMode.Premultiplied : CanvasAlphaMode.Opaque, - }); - } - /** - * Force a specific size of the canvas - * @param width defines the new canvas' width - * @param height defines the new canvas' height - * @param forceSetSize true to force setting the sizes of the underlying canvas - * @returns true if the size was changed - */ - setSize(width, height, forceSetSize = false) { - if (!super.setSize(width, height, forceSetSize)) { - return false; - } - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - console.log("frame #" + this._count + " - setSize called -", width, height); - } - } - this._initializeMainAttachments(); - if (this.snapshotRendering) { - // reset snapshot rendering so that the next frame will record a new list of bundles - this.snapshotRenderingReset(); - } - return true; - } - /** - * @internal - */ - _getShaderProcessor(shaderLanguage) { - if (shaderLanguage === ShaderLanguage.WGSL) { - return this._shaderProcessorWGSL; - } - return this._shaderProcessor; - } - /** - * @internal - */ - _getShaderProcessingContext(shaderLanguage) { - return new WebGPUShaderProcessingContext(shaderLanguage); - } - //------------------------------------------------------------------------------ - // Static Pipeline WebGPU States - //------------------------------------------------------------------------------ - /** @internal */ - applyStates() { - this._stencilStateComposer.apply(); - this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend); - } - /** - * Force the entire cache to be cleared - * You should not have to use this function unless your engine needs to share the WebGPU context with another engine - * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states) - */ - wipeCaches(bruteForce) { - if (this.preventCacheWipeBetweenFrames && !bruteForce) { - return; - } - //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) - // _forceEnableEffect = true assumes the role of _currentEffect = null - this._forceEnableEffect = true; - this._currentIndexBuffer = null; - this._currentOverrideVertexBuffers = null; - this._cacheRenderPipeline.setBuffers(null, null, null); - if (bruteForce) { - this._stencilStateComposer.reset(); - this._depthCullingState.reset(); - this._depthCullingState.depthFunc = 515; - this._alphaState.reset(); - this._alphaMode = 1; - this._alphaEquation = 0; - this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters); - this._cacheRenderPipeline.setAlphaBlendEnabled(false); - this.setColorWrite(true); - } - this._cachedVertexBuffers = null; - this._cachedIndexBuffer = null; - this._cachedEffectForVertexBuffers = null; - } - /** - * Enable or disable color writing - * @param enable defines the state to set - */ - setColorWrite(enable) { - this._colorWriteLocal = enable; - this._cacheRenderPipeline.setWriteMask(enable ? 0xf : 0); - } - /** - * Gets a boolean indicating if color writing is enabled - * @returns the current color writing state - */ - getColorWrite() { - return this._colorWriteLocal; - } - _resetCurrentViewport(index) { - this._viewportsCurrent[index].x = 0; - this._viewportsCurrent[index].y = 0; - this._viewportsCurrent[index].w = 0; - this._viewportsCurrent[index].h = 0; - } - _mustUpdateViewport(renderPass) { - const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1; - const x = this._viewportCached.x, y = this._viewportCached.y, w = this._viewportCached.z, h = this._viewportCached.w; - const update = this._viewportsCurrent[index].x !== x || this._viewportsCurrent[index].y !== y || this._viewportsCurrent[index].w !== w || this._viewportsCurrent[index].h !== h; - if (update) { - this._viewportsCurrent[index].x = this._viewportCached.x; - this._viewportsCurrent[index].y = this._viewportCached.y; - this._viewportsCurrent[index].w = this._viewportCached.z; - this._viewportsCurrent[index].h = this._viewportCached.w; - } - return update; - } - _applyViewport(renderPass) { - let y = Math.floor(this._viewportCached.y); - const h = Math.floor(this._viewportCached.w); - if (!this._currentRenderTarget) { - y = this.getRenderHeight(true) - y - h; - } - renderPass.setViewport(Math.floor(this._viewportCached.x), y, Math.floor(this._viewportCached.z), h, 0, 1); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - 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)); - } - } - } - /** - * @internal - */ - _viewport(x, y, width, height) { - this._viewportCached.x = x; - this._viewportCached.y = y; - this._viewportCached.z = width; - this._viewportCached.w = height; - } - _resetCurrentScissor(index) { - this._scissorsCurrent[index].x = 0; - this._scissorsCurrent[index].y = 0; - this._scissorsCurrent[index].w = 0; - this._scissorsCurrent[index].h = 0; - } - _mustUpdateScissor(renderPass) { - const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1; - const x = this._scissorCached.x, y = this._scissorCached.y, w = this._scissorCached.z, h = this._scissorCached.w; - const update = this._scissorsCurrent[index].x !== x || this._scissorsCurrent[index].y !== y || this._scissorsCurrent[index].w !== w || this._scissorsCurrent[index].h !== h; - if (update) { - this._scissorsCurrent[index].x = this._scissorCached.x; - this._scissorsCurrent[index].y = this._scissorCached.y; - this._scissorsCurrent[index].w = this._scissorCached.z; - this._scissorsCurrent[index].h = this._scissorCached.w; - } - return update; - } - _applyScissor(renderPass) { - renderPass.setScissorRect(this._scissorCached.x, this._currentRenderTarget ? this._scissorCached.y : this.getRenderHeight() - this._scissorCached.w - this._scissorCached.y, this._scissorCached.z, this._scissorCached.w); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - 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)); - } - } - } - _scissorIsActive() { - return this._scissorCached.x !== 0 || this._scissorCached.y !== 0 || this._scissorCached.z !== 0 || this._scissorCached.w !== 0; - } - enableScissor(x, y, width, height) { - this._scissorCached.x = x; - this._scissorCached.y = y; - this._scissorCached.z = width; - this._scissorCached.w = height; - } - disableScissor() { - this._scissorCached.x = 0; - this._scissorCached.y = 0; - this._scissorCached.z = 0; - this._scissorCached.w = 0; - this._resetCurrentScissor(0); - this._resetCurrentScissor(1); - } - _resetCurrentStencilRef(index) { - this._stencilRefsCurrent[index] = -1; - } - _mustUpdateStencilRef(renderPass) { - const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1; - const update = this._stencilStateComposer.funcRef !== this._stencilRefsCurrent[index]; - if (update) { - this._stencilRefsCurrent[index] = this._stencilStateComposer.funcRef; - } - return update; - } - /** - * @internal - */ - _applyStencilRef(renderPass) { - var _a; - renderPass.setStencilReference((_a = this._stencilStateComposer.funcRef) !== null && _a !== void 0 ? _a : 0); - } - _resetCurrentColorBlend(index) { - this._blendColorsCurrent[index][0] = this._blendColorsCurrent[index][1] = this._blendColorsCurrent[index][2] = this._blendColorsCurrent[index][3] = null; - } - _mustUpdateBlendColor(renderPass) { - const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1; - const colorBlend = this._alphaState._blendConstants; - const update = colorBlend[0] !== this._blendColorsCurrent[index][0] || - colorBlend[1] !== this._blendColorsCurrent[index][1] || - colorBlend[2] !== this._blendColorsCurrent[index][2] || - colorBlend[3] !== this._blendColorsCurrent[index][3]; - if (update) { - this._blendColorsCurrent[index][0] = colorBlend[0]; - this._blendColorsCurrent[index][1] = colorBlend[1]; - this._blendColorsCurrent[index][2] = colorBlend[2]; - this._blendColorsCurrent[index][3] = colorBlend[3]; - } - return update; - } - _applyBlendColor(renderPass) { - renderPass.setBlendConstant(this._alphaState._blendConstants); - } - /** - * Clear the current render buffer or the current render target (if any is set up) - * @param color defines the color to use - * @param backBuffer defines if the back buffer must be cleared - * @param depth defines if the depth buffer must be cleared - * @param stencil defines if the stencil buffer must be cleared - */ - clear(color, backBuffer, depth, stencil = false) { - // Some PGs are using color3... - if (color && color.a === undefined) { - color.a = 1; - } - const hasScissor = this._scissorIsActive(); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - console.log("frame #" + this._count + " - clear called - backBuffer=", backBuffer, " depth=", depth, " stencil=", stencil, " scissor is active=", hasScissor); - } - } - // We need to recreate the render pass so that the new parameters for clear color / depth / stencil are taken into account - if (this._currentRenderTarget) { - if (hasScissor) { - if (!this._rttRenderPassWrapper.renderPass) { - this._startRenderTargetRenderPass(this._currentRenderTarget, false, backBuffer ? color : null, depth, stencil); - } - if (!this.compatibilityMode) { - this._bundleListRenderTarget.addItem(new WebGPURenderItemScissor(this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w)); - } - else { - this._applyScissor(this._currentRenderPass); - } - this._clearFullQuad(backBuffer ? color : null, depth, stencil); - } - else { - if (this._currentRenderPass) { - this._endRenderTargetRenderPass(); - } - this._startRenderTargetRenderPass(this._currentRenderTarget, true, backBuffer ? color : null, depth, stencil); - } - } - else { - if (!this._mainRenderPassWrapper.renderPass || !hasScissor) { - this._startMainRenderPass(!hasScissor, backBuffer ? color : null, depth, stencil); - } - if (hasScissor) { - if (!this.compatibilityMode) { - this._bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w)); - } - else { - this._applyScissor(this._currentRenderPass); - } - this._clearFullQuad(backBuffer ? color : null, depth, stencil); - } - } - } - _clearFullQuad(clearColor, clearDepth, clearStencil) { - var _a, _b, _c; - const renderPass = !this.compatibilityMode ? null : this._getCurrentRenderPass(); - const renderPassIndex = this._getCurrentRenderPassIndex(); - const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget; - this._clearQuad.setColorFormat(this._colorFormat); - this._clearQuad.setDepthStencilFormat(this._depthTextureFormat); - this._clearQuad.setMRTAttachments((_a = this._cacheRenderPipeline.mrtAttachments) !== null && _a !== void 0 ? _a : [], (_b = this._cacheRenderPipeline.mrtTextureArray) !== null && _b !== void 0 ? _b : [], this._cacheRenderPipeline.mrtTextureCount); - if (!this.compatibilityMode) { - bundleList.addItem(new WebGPURenderItemStencilRef(this._clearStencilValue)); - } - else { - renderPass.setStencilReference(this._clearStencilValue); - } - const bundle = this._clearQuad.clear(renderPass, clearColor, clearDepth, clearStencil, this.currentSampleCount); - if (!this.compatibilityMode) { - bundleList.addBundle(bundle); - bundleList.addItem(new WebGPURenderItemStencilRef((_c = this._stencilStateComposer.funcRef) !== null && _c !== void 0 ? _c : 0)); - this._reportDrawCall(); - } - else { - this._applyStencilRef(renderPass); - } - } - //------------------------------------------------------------------------------ - // Vertex/Index/Storage Buffers - //------------------------------------------------------------------------------ - /** - * Creates a vertex buffer - * @param data the data for the vertex buffer - * @returns the new buffer - */ - createVertexBuffer(data) { - let view; - if (data instanceof Array) { - view = new Float32Array(data); - } - else if (data instanceof ArrayBuffer) { - view = new Uint8Array(data); - } - else { - view = data; - } - const dataBuffer = this._bufferManager.createBuffer(view, BufferUsage.Vertex | BufferUsage.CopyDst); - return dataBuffer; - } - /** - * Creates a vertex buffer - * @param data the data for the dynamic vertex buffer - * @returns the new buffer - */ - createDynamicVertexBuffer(data) { - return this.createVertexBuffer(data); - } - /** - * Creates a new index buffer - * @param indices defines the content of the index buffer - * @returns a new buffer - */ - createIndexBuffer(indices) { - let is32Bits = true; - let view; - if (indices instanceof Uint32Array || indices instanceof Int32Array) { - view = indices; - } - else if (indices instanceof Uint16Array) { - view = indices; - is32Bits = false; - } - else { - if (indices.length > 65535) { - view = new Uint32Array(indices); - } - else { - view = new Uint16Array(indices); - is32Bits = false; - } - } - const dataBuffer = this._bufferManager.createBuffer(view, BufferUsage.Index | BufferUsage.CopyDst); - dataBuffer.is32Bits = is32Bits; - return dataBuffer; - } - /** - * @internal - */ - _createBuffer(data, creationFlags) { - let view; - if (data instanceof Array) { - view = new Float32Array(data); - } - else if (data instanceof ArrayBuffer) { - view = new Uint8Array(data); - } - else { - view = data; - } - let flags = 0; - if (creationFlags & 1) { - flags |= BufferUsage.CopySrc; - } - if (creationFlags & 2) { - flags |= BufferUsage.CopyDst; - } - if (creationFlags & 4) { - flags |= BufferUsage.Uniform; - } - if (creationFlags & 8) { - flags |= BufferUsage.Vertex; - } - if (creationFlags & 16) { - flags |= BufferUsage.Index; - } - if (creationFlags & 32) { - flags |= BufferUsage.Storage; - } - return this._bufferManager.createBuffer(view, flags); - } - /** - * @internal - */ - bindBuffersDirectly() { - throw "Not implemented on WebGPU"; - } - /** - * @internal - */ - updateAndBindInstancesBuffer() { - throw "Not implemented on WebGPU"; - } - /** - * Bind a list of vertex buffers with the engine - * @param vertexBuffers defines the list of vertex buffers to bind - * @param indexBuffer defines the index buffer to bind - * @param effect defines the effect associated with the vertex buffers - * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers - */ - bindBuffers(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { - this._currentIndexBuffer = indexBuffer; - this._currentOverrideVertexBuffers = overrideVertexBuffers !== null && overrideVertexBuffers !== void 0 ? overrideVertexBuffers : null; - this._cacheRenderPipeline.setBuffers(vertexBuffers, indexBuffer, this._currentOverrideVertexBuffers); - } - /** - * @internal - */ - _releaseBuffer(buffer) { - return this._bufferManager.releaseBuffer(buffer); - } - //------------------------------------------------------------------------------ - // Effects - //------------------------------------------------------------------------------ - /** - * Create a new effect (used to store vertex/fragment shaders) - * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx) - * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object - * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use - * @param samplers defines an array of string used to represent textures - * @param defines defines the string containing the defines to use to compile the shaders - * @param fallbacks defines the list of potential fallbacks to use if shader compilation fails - * @param onCompiled defines a function to call when the effect creation is successful - * @param onError defines a function to call when the effect creation has failed - * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights) - * @param shaderLanguage the language the shader is written in (default: GLSL) - * @returns the new Effect - */ - createEffect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters, shaderLanguage = ShaderLanguage.GLSL) { - var _a; - const vertex = baseName.vertexElement || baseName.vertex || baseName.vertexToken || baseName.vertexSource || baseName; - const fragment = baseName.fragmentElement || baseName.fragment || baseName.fragmentToken || baseName.fragmentSource || baseName; - const globalDefines = this._getGlobalDefines(); - let fullDefines = (_a = defines !== null && defines !== void 0 ? defines : attributesNamesOrOptions.defines) !== null && _a !== void 0 ? _a : ""; - if (globalDefines) { - fullDefines += "\n" + globalDefines; - } - const name = vertex + "+" + fragment + "@" + fullDefines; - if (this._compiledEffects[name]) { - const compiledEffect = this._compiledEffects[name]; - if (onCompiled && compiledEffect.isReady()) { - onCompiled(compiledEffect); - } - return compiledEffect; - } - const effect = new effect_Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, shaderLanguage); - this._compiledEffects[name] = effect; - return effect; - } - _compileRawShaderToSpirV(source, type) { - return this._glslang.compileGLSL(source, type); - } - _compileShaderToSpirV(source, type, defines, shaderVersion) { - return this._compileRawShaderToSpirV(shaderVersion + (defines ? defines + "\n" : "") + source, type); - } - _getWGSLShader(source, type, defines) { - if (defines) { - defines = "//" + defines.split("\n").join("\n//") + "\n"; - } - else { - defines = ""; - } - return defines + source; - } - _createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment) { - if (this._tintWASM && shaderLanguage === ShaderLanguage.GLSL) { - vertexShader = this._tintWASM.convertSpirV2WGSL(vertexShader, disableUniformityAnalysisInVertex); - fragmentShader = this._tintWASM.convertSpirV2WGSL(fragmentShader, disableUniformityAnalysisInFragment); - } - return { - vertexStage: { - module: this._device.createShaderModule({ - code: vertexShader, - }), - entryPoint: "main", - }, - fragmentStage: { - module: this._device.createShaderModule({ - code: fragmentShader, - }), - entryPoint: "main", - }, - }; - } - _compileRawPipelineStageDescriptor(vertexCode, fragmentCode, shaderLanguage) { - const disableUniformityAnalysisInVertex = vertexCode.indexOf(disableUniformityAnalysisMarker) >= 0; - const disableUniformityAnalysisInFragment = fragmentCode.indexOf(disableUniformityAnalysisMarker) >= 0; - const vertexShader = shaderLanguage === ShaderLanguage.GLSL ? this._compileRawShaderToSpirV(vertexCode, "vertex") : vertexCode; - const fragmentShader = shaderLanguage === ShaderLanguage.GLSL ? this._compileRawShaderToSpirV(fragmentCode, "fragment") : fragmentCode; - return this._createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment); - } - _compilePipelineStageDescriptor(vertexCode, fragmentCode, defines, shaderLanguage) { - this.onBeforeShaderCompilationObservable.notifyObservers(this); - const disableUniformityAnalysisInVertex = vertexCode.indexOf(disableUniformityAnalysisMarker) >= 0; - const disableUniformityAnalysisInFragment = fragmentCode.indexOf(disableUniformityAnalysisMarker) >= 0; - const shaderVersion = "#version 450\n"; - const vertexShader = shaderLanguage === ShaderLanguage.GLSL ? this._compileShaderToSpirV(vertexCode, "vertex", defines, shaderVersion) : this._getWGSLShader(vertexCode, "vertex", defines); - const fragmentShader = shaderLanguage === ShaderLanguage.GLSL - ? this._compileShaderToSpirV(fragmentCode, "fragment", defines, shaderVersion) - : this._getWGSLShader(fragmentCode, "fragment", defines); - const program = this._createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment); - this.onAfterShaderCompilationObservable.notifyObservers(this); - return program; - } - /** - * @internal - */ - createRawShaderProgram() { - throw "Not available on WebGPU"; - } - /** - * @internal - */ - createShaderProgram() { - throw "Not available on WebGPU"; - } - /** - * Inline functions in shader code that are marked to be inlined - * @param code code to inline - * @returns inlined code - */ - inlineShaderCode(code) { - const sci = new ShaderCodeInliner(code); - sci.debug = false; - sci.processCode(); - return sci.code; - } - /** - * Creates a new pipeline context - * @param shaderProcessingContext defines the shader processing context used during the processing if available - * @returns the new pipeline - */ - createPipelineContext(shaderProcessingContext) { - return new WebGPUPipelineContext(shaderProcessingContext, this); - } - /** - * Creates a new material context - * @returns the new context - */ - createMaterialContext() { - return new WebGPUMaterialContext(); - } - /** - * Creates a new draw context - * @returns the new context - */ - createDrawContext() { - return new WebGPUDrawContext(this._bufferManager); - } - /** - * @internal - */ - _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, rebuildRebind, defines) { - const webGpuContext = pipelineContext; - const shaderLanguage = webGpuContext.shaderProcessingContext.shaderLanguage; - if (this.dbgShowShaderCode) { - console.log(defines); - console.log(vertexSourceCode); - console.log(fragmentSourceCode); - console.log("***********************************************"); - } - webGpuContext.sources = { - fragment: fragmentSourceCode, - vertex: vertexSourceCode, - rawVertex: rawVertexSourceCode, - rawFragment: rawFragmentSourceCode, - }; - if (createAsRaw) { - webGpuContext.stages = this._compileRawPipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, shaderLanguage); - } - else { - webGpuContext.stages = this._compilePipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, defines, shaderLanguage); - } - } - /** - * Gets the list of active attributes for a given WebGPU program - * @param pipelineContext defines the pipeline context to use - * @param attributesNames defines the list of attribute names to get - * @returns an array of indices indicating the offset of each attribute - */ - getAttributes(pipelineContext, attributesNames) { - const results = new Array(attributesNames.length); - const gpuPipelineContext = pipelineContext; - for (let i = 0; i < attributesNames.length; i++) { - const attributeName = attributesNames[i]; - const attributeLocation = gpuPipelineContext.shaderProcessingContext.availableAttributes[attributeName]; - if (attributeLocation === undefined) { - continue; - } - results[i] = attributeLocation; - } - return results; - } - /** - * Activates an effect, making it the current one (ie. the one used for rendering) - * @param effect defines the effect to activate - */ - enableEffect(effect) { - if (!effect) { - return; - } - let isNewEffect = true; - if (!drawWrapper_DrawWrapper.IsWrapper(effect)) { - isNewEffect = effect !== this._currentEffect; - this._currentEffect = effect; - this._currentMaterialContext = this._defaultMaterialContext; - this._currentDrawContext = this._defaultDrawContext; - this._counters.numEnableEffects++; - if (this.dbgLogIfNotDrawWrapper) { - logger_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); - } - } - else if (!effect.effect || - (effect.effect === this._currentEffect && - effect.materialContext === this._currentMaterialContext && - effect.drawContext === this._currentDrawContext && - !this._forceEnableEffect)) { - if (!effect.effect && this.dbgShowEmptyEnableEffectCalls) { - console.error("drawWrapper=", effect); - throw "Invalid call to enableEffect: the effect property is empty!"; - } - return; - } - else { - isNewEffect = effect.effect !== this._currentEffect; - this._currentEffect = effect.effect; - this._currentMaterialContext = effect.materialContext; - this._currentDrawContext = effect.drawContext; - this._counters.numEnableDrawWrapper++; - if (!this._currentMaterialContext) { - console.error("drawWrapper=", effect); - throw `Invalid call to enableEffect: the materialContext property is empty!`; - } - } - this._stencilStateComposer.stencilMaterial = undefined; - this._forceEnableEffect = isNewEffect || this._forceEnableEffect ? false : this._forceEnableEffect; - if (isNewEffect) { - if (this._currentEffect.onBind) { - this._currentEffect.onBind(this._currentEffect); - } - if (this._currentEffect._onBindObservable) { - this._currentEffect._onBindObservable.notifyObservers(this._currentEffect); - } - } - } - /** - * @internal - */ - _releaseEffect(effect) { - if (this._compiledEffects[effect._key]) { - delete this._compiledEffects[effect._key]; - this._deletePipelineContext(effect.getPipelineContext()); - } - } - /** - * 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 - */ - releaseEffects() { - for (const name in this._compiledEffects) { - const webGPUPipelineContext = this._compiledEffects[name].getPipelineContext(); - this._deletePipelineContext(webGPUPipelineContext); - } - this._compiledEffects = {}; - } - _deletePipelineContext(pipelineContext) { - const webgpuPipelineContext = pipelineContext; - if (webgpuPipelineContext) { - pipelineContext.dispose(); - } - } - //------------------------------------------------------------------------------ - // Textures - //------------------------------------------------------------------------------ - /** - * Gets a boolean indicating that only power of 2 textures are supported - * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them - */ - get needPOTTextures() { - return false; - } - /** @internal */ - _createHardwareTexture() { - return new WebGPUHardwareTexture(); - } - /** - * @internal - */ - _releaseTexture(texture) { - const index = this._internalTexturesCache.indexOf(texture); - if (index !== -1) { - this._internalTexturesCache.splice(index, 1); - } - this._textureHelper.releaseTexture(texture); - } - /** - * @internal - */ - _getRGBABufferInternalSizedFormat() { - return 5; - } - updateTextureComparisonFunction(texture, comparisonFunction) { - texture._comparisonFunction = comparisonFunction; - } - /** - * Creates an internal texture without binding it to a framebuffer - * @internal - * @param size defines the size of the texture - * @param options defines the options used to create the texture - * @param delayGPUTextureCreation true to delay the texture creation the first time it is really needed. false to create it right away - * @param source source type of the texture - * @returns a new internal texture - */ - _createInternalTexture(size, options, delayGPUTextureCreation = true, source = internalTexture_InternalTextureSource.Unknown) { - var _a, _b, _c; - const fullOptions = {}; - if (options !== undefined && typeof options === "object") { - fullOptions.generateMipMaps = options.generateMipMaps; - fullOptions.type = options.type === undefined ? 0 : options.type; - fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode; - fullOptions.format = options.format === undefined ? 5 : options.format; - fullOptions.samples = (_a = options.samples) !== null && _a !== void 0 ? _a : 1; - fullOptions.creationFlags = (_b = options.creationFlags) !== null && _b !== void 0 ? _b : 0; - fullOptions.useSRGBBuffer = (_c = options.useSRGBBuffer) !== null && _c !== void 0 ? _c : false; - fullOptions.label = options.label; - } - else { - fullOptions.generateMipMaps = options; - fullOptions.type = 0; - fullOptions.samplingMode = 3; - fullOptions.format = 5; - fullOptions.samples = 1; - fullOptions.creationFlags = 0; - fullOptions.useSRGBBuffer = false; - } - if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) { - fullOptions.samplingMode = 1; - } - else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) { - fullOptions.samplingMode = 1; - } - if (fullOptions.type === 1 && !this._caps.textureFloat) { - fullOptions.type = 0; - logger_Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"); - } - const texture = new internalTexture_InternalTexture(this, source); - const width = size.width || size; - const height = size.height || size; - const layers = size.layers || 0; - texture.baseWidth = width; - texture.baseHeight = height; - texture.width = width; - texture.height = height; - texture.depth = layers; - texture.isReady = true; - texture.samples = fullOptions.samples; - texture.generateMipMaps = fullOptions.generateMipMaps ? true : false; - texture.samplingMode = fullOptions.samplingMode; - texture.type = fullOptions.type; - texture.format = fullOptions.format; - texture.is2DArray = layers > 0; - texture._cachedWrapU = 0; - texture._cachedWrapV = 0; - texture._useSRGBBuffer = fullOptions.useSRGBBuffer; - texture.label = fullOptions.label; - this._internalTexturesCache.push(texture); - if (!delayGPUTextureCreation) { - this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, layers || 1, fullOptions.creationFlags); - } - return texture; - } - /** - * Usually called from Texture.ts. - * Passed information to create a hardware texture - * @param url defines a value which contains one of the following: - * * A conventional http URL, e.g. 'http://...' or 'file://...' - * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...' - * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg' - * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file - * @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) - * @param scene needed for loading to the correct scene - * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE) - * @param onLoad optional callback to be called upon successful completion - * @param onError optional callback to be called upon failure - * @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 - * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities - * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures - * @param forcedExtension defines the extension to use to pick the right loader - * @param mimeType defines an optional mime type - * @param loaderOptions options to be passed to the loader - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). - * @returns a InternalTexture for assignment back into BABYLON.Texture - */ - createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer) { - return this._createTextureBase(url, noMipmap, invertY, scene, samplingMode, onLoad, onError, (texture, extension, scene, img, invertY, noMipmap, isCompressed, processFunction) => { - var _a; - const imageBitmap = img; // we will never get an HTMLImageElement in WebGPU - texture.baseWidth = imageBitmap.width; - texture.baseHeight = imageBitmap.height; - texture.width = imageBitmap.width; - texture.height = imageBitmap.height; - texture.format = format !== null && format !== void 0 ? format : -1; - processFunction(texture.width, texture.height, imageBitmap, extension, texture, () => { }); - if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) { - // the texture could have been created before reaching this point so don't recreate it if already existing - const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, imageBitmap.width, imageBitmap.height, undefined, creationFlags); - if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) { - this._textureHelper.updateTexture(imageBitmap, texture, imageBitmap.width, imageBitmap.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0); - if (!noMipmap && !isCompressed) { - this._generateMipmaps(texture, this._uploadEncoder); - } - } - } - else if (!noMipmap && !isCompressed) { - this._generateMipmaps(texture, this._uploadEncoder); - } - if (scene) { - scene.removePendingData(texture); - } - texture.isReady = true; - texture.onLoadedObservable.notifyObservers(texture); - texture.onLoadedObservable.clear(); - }, () => false, buffer, fallback, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer); - } - /** - * Wraps an external web gpu texture in a Babylon texture. - * @param texture defines the external texture - * @returns the babylon internal texture - */ - wrapWebGPUTexture(texture) { - const hardwareTexture = new WebGPUHardwareTexture(texture); - const internalTexture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Unknown, true); - internalTexture._hardwareTexture = hardwareTexture; - internalTexture.isReady = true; - return internalTexture; - } - /** - * Wraps an external web gl texture in a Babylon texture. - * @returns the babylon internal texture - */ - wrapWebGLTexture() { - throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead."); - } - generateMipMapsForCubemap(texture) { - var _a; - if (texture.generateMipMaps) { - const gpuTexture = (_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource; - if (!gpuTexture) { - this._textureHelper.createGPUTextureForInternalTexture(texture); - } - this._generateMipmaps(texture, texture.source === internalTexture_InternalTextureSource.RenderTarget || texture.source === internalTexture_InternalTextureSource.MultiRenderTarget ? this._renderTargetEncoder : undefined); - } - } - /** - * Update the sampling mode of a given texture - * @param samplingMode defines the required sampling mode - * @param texture defines the texture to update - * @param generateMipMaps defines whether to generate mipmaps for the texture - */ - updateTextureSamplingMode(samplingMode, texture, generateMipMaps = false) { - if (generateMipMaps) { - texture.generateMipMaps = true; - this._generateMipmaps(texture); - } - texture.samplingMode = samplingMode; - } - /** - * Update the sampling mode of a given texture - * @param texture defines the texture to update - * @param wrapU defines the texture wrap mode of the u coordinates - * @param wrapV defines the texture wrap mode of the v coordinates - * @param wrapR defines the texture wrap mode of the r coordinates - */ - updateTextureWrappingMode(texture, wrapU, wrapV = null, wrapR = null) { - if (wrapU !== null) { - texture._cachedWrapU = wrapU; - } - if (wrapV !== null) { - texture._cachedWrapV = wrapV; - } - if ((texture.is2DArray || texture.is3D) && wrapR !== null) { - texture._cachedWrapR = wrapR; - } - } - /** - * Update the dimensions of a texture - * @param texture texture to update - * @param width new width of the texture - * @param height new height of the texture - * @param depth new depth of the texture - */ - updateTextureDimensions(texture, width, height, depth = 1) { - if (!texture._hardwareTexture) { - // the gpu texture is not created yet, so when it is it will be created with the right dimensions - return; - } - if (texture.width === width && texture.height === height && texture.depth === depth) { - return; - } - const additionalUsages = texture._hardwareTexture.textureAdditionalUsages; - 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... - this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth, additionalUsages); - } - /** - * @internal - */ - _setInternalTexture(name, texture, baseName) { - baseName = baseName !== null && baseName !== void 0 ? baseName : name; - if (this._currentEffect) { - const webgpuPipelineContext = this._currentEffect._pipelineContext; - const availableTexture = webgpuPipelineContext.shaderProcessingContext.availableTextures[baseName]; - this._currentMaterialContext.setTexture(name, texture); - if (availableTexture && availableTexture.autoBindSampler) { - const samplerName = baseName + WebGPUShaderProcessor.AutoSamplerSuffix; - this._currentMaterialContext.setSampler(samplerName, texture); // we can safely cast to InternalTexture because ExternalTexture always has autoBindSampler = false - } - } - } - /** - * Sets a texture to the according uniform. - * @param channel The texture channel - * @param unused unused parameter - * @param texture The texture to apply - * @param name The name of the uniform in the effect - */ - setTexture(channel, unused, texture, name) { - this._setTexture(channel, texture, false, false, name, name); - } - /** - * Sets an array of texture to the WebGPU context - * @param channel defines the channel where the texture array must be set - * @param unused unused parameter - * @param textures defines the array of textures to bind - * @param name name of the channel - */ - setTextureArray(channel, unused, textures, name) { - for (let index = 0; index < textures.length; index++) { - this._setTexture(-1, textures[index], true, false, name + index.toString(), name); - } - } - _setTexture(channel, texture, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - isPartOfTextureArray = false, depthStencilTexture = false, name = "", baseName) { - // name == baseName for a texture that is not part of a texture array - // Else, name is something like 'myTexture0' / 'myTexture1' / ... and baseName is 'myTexture' - // baseName is used to look up the texture in the shaderProcessingContext.availableTextures map - // name is used to look up the texture in the _currentMaterialContext.textures map - baseName = baseName !== null && baseName !== void 0 ? baseName : name; - if (this._currentEffect) { - if (!texture) { - this._currentMaterialContext.setTexture(name, null); - return false; - } - // Video - if (texture.video) { - texture.update(); - } - else if (texture.delayLoadState === 4) { - // Delay loading - texture.delayLoad(); - return false; - } - let internalTexture = null; - if (depthStencilTexture) { - internalTexture = texture.depthStencilTexture; - } - else if (texture.isReady()) { - internalTexture = texture.getInternalTexture(); - } - else if (texture.isCube) { - internalTexture = this.emptyCubeTexture; - } - else if (texture.is3D) { - internalTexture = this.emptyTexture3D; - } - else if (texture.is2DArray) { - internalTexture = this.emptyTexture2DArray; - } - else { - internalTexture = this.emptyTexture; - } - if (internalTexture && !internalTexture.isMultiview) { - // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT. - if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) { - internalTexture._cachedCoordinatesMode = texture.coordinatesMode; - const textureWrapMode = texture.coordinatesMode !== 3 && texture.coordinatesMode !== 5 - ? 1 - : 0; - texture.wrapU = textureWrapMode; - texture.wrapV = textureWrapMode; - } - internalTexture._cachedWrapU = texture.wrapU; - internalTexture._cachedWrapV = texture.wrapV; - if (internalTexture.is3D) { - internalTexture._cachedWrapR = texture.wrapR; - } - this._setAnisotropicLevel(0, internalTexture, texture.anisotropicFilteringLevel); - } - this._setInternalTexture(name, internalTexture, baseName); - } - else { - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - console.log("frame #" + this._count + " - _setTexture called with a null _currentEffect! texture=", texture); - } - } - } - return true; - } - /** - * @internal - */ - _setAnisotropicLevel(target, internalTexture, anisotropicFilteringLevel) { - if (internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) { - internalTexture._cachedAnisotropicFilteringLevel = Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy); - } - } - /** - * @internal - */ - _bindTexture(channel, texture, name) { - if (channel === undefined) { - return; - } - this._setInternalTexture(name, texture); - } - /** - * Generates the mipmaps for a texture - * @param texture texture to generate the mipmaps for - */ - generateMipmaps(texture) { - this._generateMipmaps(texture, this._renderTargetEncoder); - } - /** - * @internal - */ - _generateMipmaps(texture, commandEncoder) { - const gpuHardwareTexture = texture._hardwareTexture; - if (!gpuHardwareTexture) { - return; - } - // try as much as possible to use the command encoder corresponding to the current pass. - // 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 - commandEncoder = - commandEncoder !== null && commandEncoder !== void 0 ? commandEncoder : (this._currentRenderTarget && !this._currentRenderPass ? this._renderTargetEncoder : !this._currentRenderPass ? this._renderEncoder : this._uploadEncoder); - const format = texture._hardwareTexture.format; - const mipmapCount = WebGPUTextureHelper.ComputeNumMipmapLevels(texture.width, texture.height); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - console.log("frame #" + this._count + " - generate mipmaps called - width=", texture.width, "height=", texture.height, "isCube=", texture.isCube); - } - } - if (texture.isCube) { - this._textureHelper.generateCubeMipmaps(gpuHardwareTexture, format, mipmapCount, commandEncoder); - } - else { - this._textureHelper.generateMipmaps(gpuHardwareTexture, format, mipmapCount, 0, commandEncoder); - } - } - /** - * Update a portion of an internal texture - * @param texture defines the texture to update - * @param imageData defines the data to store into the texture - * @param xOffset defines the x coordinates of the update rectangle - * @param yOffset defines the y coordinates of the update rectangle - * @param width defines the width of the update rectangle - * @param height defines the height of the update rectangle - * @param faceIndex defines the face index if texture is a cube (0 by default) - * @param lod defines the lod level to update (0 by default) - * @param generateMipMaps defines whether to generate mipmaps or not - */ - updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) { - var _a; - let gpuTextureWrapper = texture._hardwareTexture; - if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) { - gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture); - } - const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength); - this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, xOffset, yOffset); - if (generateMipMaps) { - this._generateMipmaps(texture, this._renderTargetEncoder); - } - } - /** - * @internal - */ - _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, imageData, faceIndex = 0, lod = 0) { - var _a; - let gpuTextureWrapper = texture._hardwareTexture; - if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) { - texture.format = internalFormat; - gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height); - } - const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength); - this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, false, false, 0, 0); - } - /** - * @internal - */ - _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0, babylonInternalFormat, useTextureWidthAndHeight = false) { - var _a; - const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E); - const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E); - const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0)); - const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0)); - let gpuTextureWrapper = texture._hardwareTexture; - if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) { - gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height); - } - const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength); - this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0); - } - /** - * @internal - */ - _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) { - this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod); - } - /** - * @internal - */ - _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) { - var _a; - let gpuTextureWrapper = texture._hardwareTexture; - if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) { - gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture); - } - if (image instanceof HTMLImageElement) { - throw "WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!"; - } - const bitmap = image; // in WebGPU we will always get an ImageBitmap, not an HTMLImageElement - const width = Math.ceil(texture.width / (1 << lod)); - const height = Math.ceil(texture.height / (1 << lod)); - this._textureHelper.updateTexture(bitmap, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0); - } - /** - * Reads pixels from the current frame buffer. Please note that this function can be slow - * @param x defines the x coordinate of the rectangle where pixels must be read - * @param y defines the y coordinate of the rectangle where pixels must be read - * @param width defines the width of the rectangle where pixels must be read - * @param height defines the height of the rectangle where pixels must be read - * @param hasAlpha defines whether the output should have alpha or not (defaults to true) - * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels - * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - readPixels(x, y, width, height, hasAlpha = true, flushRenderer = true) { - const renderPassWrapper = this._rttRenderPassWrapper.renderPass ? this._rttRenderPassWrapper : this._mainRenderPassWrapper; - const hardwareTexture = renderPassWrapper.colorAttachmentGPUTextures[0]; - if (!hardwareTexture) { - // we are calling readPixels for a render pass with no color texture bound - return Promise.resolve(new Uint8Array(0)); - } - const gpuTexture = hardwareTexture.underlyingResource; - const gpuTextureFormat = hardwareTexture.format; - if (!gpuTexture) { - // we are calling readPixels before startMainRenderPass has been called and no RTT is bound, so swapChainTexture is not setup yet! - return Promise.resolve(new Uint8Array(0)); - } - if (flushRenderer) { - this.flushFramebuffer(); - } - return this._textureHelper.readPixels(gpuTexture, x, y, width, height, gpuTextureFormat); - } - //------------------------------------------------------------------------------ - // Frame management - //------------------------------------------------------------------------------ - /** - * Begin a new frame - */ - beginFrame() { - super.beginFrame(); - } - /** - * End the current frame - */ - endFrame() { - this._snapshotRendering.endFrame(this._mainRenderPassWrapper.renderPass); - this._endMainRenderPass(); - this._timestampQuery.endFrame(this._renderEncoder); - this.flushFramebuffer(false); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - console.log("frame #" + this._count + " - counters"); - } - } - this._textureHelper.destroyDeferredTextures(); - this._bufferManager.destroyDeferredBuffers(); - if (this._features._collectUbosUpdatedInFrame) { - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - const list = []; - for (const name in UniformBuffer._UpdatedUbosInFrame) { - list.push(name + ":" + UniformBuffer._UpdatedUbosInFrame[name]); - } - console.log("frame #" + this._count + " - updated ubos -", list.join(", ")); - } - } - UniformBuffer._UpdatedUbosInFrame = {}; - } - this.countersLastFrame.numEnableEffects = this._counters.numEnableEffects; - this.countersLastFrame.numEnableDrawWrapper = this._counters.numEnableDrawWrapper; - this.countersLastFrame.numBundleCreationNonCompatMode = this._counters.numBundleCreationNonCompatMode; - this.countersLastFrame.numBundleReuseNonCompatMode = this._counters.numBundleReuseNonCompatMode; - this._counters.numEnableEffects = 0; - this._counters.numEnableDrawWrapper = 0; - this._counters.numBundleCreationNonCompatMode = 0; - this._counters.numBundleReuseNonCompatMode = 0; - this._cacheRenderPipeline.endFrame(); - this._cacheBindGroups.endFrame(); - this._pendingDebugCommands.length = 0; - super.endFrame(); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (this._count < this.dbgVerboseLogsNumFrames) { - console.log("%c frame #" + this._count + " - end", "background: #ffff00"); - } - if (this._count < this.dbgVerboseLogsNumFrames) { - this._count++; - if (this._count !== this.dbgVerboseLogsNumFrames) { - console.log("%c frame #" + this._count + " - begin", "background: #ffff00"); - } - } - } - } - /** - * Force a WebGPU flush (ie. a flush of all waiting commands) - * @param reopenPass true to reopen at the end of the function the pass that was active when entering the function - */ - flushFramebuffer(reopenPass = true) { - // 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 - const currentRenderPassIsNULL = !this._currentRenderPass; - let currentPasses = 0; // 0 if no pass, 1 for rtt, 2 for main pass - if (this._currentRenderPass && this._currentRenderTarget) { - currentPasses |= 1; - this._endRenderTargetRenderPass(); - } - if (this._mainRenderPassWrapper.renderPass) { - currentPasses |= 2; - this._endMainRenderPass(); - } - this._commandBuffers[0] = this._uploadEncoder.finish(); - this._commandBuffers[1] = this._renderTargetEncoder.finish(); - this._commandBuffers[2] = this._renderEncoder.finish(); - this._device.queue.submit(this._commandBuffers); - this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor); - this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor); - this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor); - this._timestampQuery.startFrame(this._uploadEncoder); - this._textureHelper.setCommandEncoder(this._uploadEncoder); - this._bundleList.reset(); - this._bundleListRenderTarget.reset(); - // restart the render pass - if (reopenPass) { - if (currentPasses & 2) { - this._startMainRenderPass(false); - } - if (currentPasses & 1) { - this._startRenderTargetRenderPass(this._currentRenderTarget, false, null, false, false); - } - if (currentRenderPassIsNULL && this._currentRenderTarget) { - this._currentRenderPass = null; - } - } - } - /** @internal */ - _currentFrameBufferIsDefaultFrameBuffer() { - return this._currentRenderTarget === null; - } - //------------------------------------------------------------------------------ - // Render Pass - //------------------------------------------------------------------------------ - _startRenderTargetRenderPass(renderTargetWrapper, setClearStates, clearColor, clearDepth, clearStencil) { - var _a, _b, _c, _d, _e, _f, _g; - const rtWrapper = renderTargetWrapper; - const depthStencilTexture = rtWrapper._depthStencilTexture; - const gpuDepthStencilWrapper = depthStencilTexture === null || depthStencilTexture === void 0 ? void 0 : depthStencilTexture._hardwareTexture; - const gpuDepthStencilTexture = gpuDepthStencilWrapper === null || gpuDepthStencilWrapper === void 0 ? void 0 : gpuDepthStencilWrapper.underlyingResource; - const gpuDepthStencilMSAATexture = gpuDepthStencilWrapper === null || gpuDepthStencilWrapper === void 0 ? void 0 : gpuDepthStencilWrapper.getMSAATexture(); - const depthTextureView = gpuDepthStencilTexture === null || gpuDepthStencilTexture === void 0 ? void 0 : gpuDepthStencilTexture.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor); - const depthMSAATextureView = gpuDepthStencilMSAATexture === null || gpuDepthStencilMSAATexture === void 0 ? void 0 : gpuDepthStencilMSAATexture.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor); - const depthTextureHasStencil = gpuDepthStencilWrapper ? WebGPUTextureHelper.HasStencilAspect(gpuDepthStencilWrapper.format) : false; - const colorAttachments = []; - if (this.useReverseDepthBuffer) { - this.setDepthFunctionToGreaterOrEqual(); - } - const clearColorForIntegerRT = tempColor4; - if (clearColor) { - clearColorForIntegerRT.r = clearColor.r * 255; - clearColorForIntegerRT.g = clearColor.g * 255; - clearColorForIntegerRT.b = clearColor.b * 255; - clearColorForIntegerRT.a = clearColor.a * 255; - } - const mustClearColor = setClearStates && clearColor; - const mustClearDepth = setClearStates && clearDepth; - const mustClearStencil = setClearStates && clearStencil; - if (rtWrapper._attachments && rtWrapper.isMulti) { - // multi render targets - if (!this._mrtAttachments || this._mrtAttachments.length === 0) { - this._mrtAttachments = rtWrapper._defaultAttachments; - } - for (let i = 0; i < this._mrtAttachments.length; ++i) { - 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 - const mrtTexture = rtWrapper.textures[i]; - const gpuMRTWrapper = mrtTexture === null || mrtTexture === void 0 ? void 0 : mrtTexture._hardwareTexture; - const gpuMRTTexture = gpuMRTWrapper === null || gpuMRTWrapper === void 0 ? void 0 : gpuMRTWrapper.underlyingResource; - if (gpuMRTWrapper && gpuMRTTexture) { - const gpuMSAATexture = gpuMRTWrapper.getMSAATexture(i); - const layerIndex = (_b = (_a = rtWrapper.layerIndices) === null || _a === void 0 ? void 0 : _a[i]) !== null && _b !== void 0 ? _b : 0; - const faceIndex = (_d = (_c = rtWrapper.faceIndices) === null || _c === void 0 ? void 0 : _c[i]) !== null && _d !== void 0 ? _d : 0; - const viewDescriptor = Object.assign(Object.assign({}, this._rttRenderPassWrapper.colorAttachmentViewDescriptor), { format: gpuMRTWrapper.format, baseArrayLayer: mrtTexture.isCube ? layerIndex * 6 + faceIndex : layerIndex }); - const msaaViewDescriptor = Object.assign(Object.assign({}, this._rttRenderPassWrapper.colorAttachmentViewDescriptor), { format: gpuMRTWrapper.format, baseArrayLayer: 0 }); - const isRTInteger = mrtTexture.type === 7 || mrtTexture.type === 5; - const colorTextureView = gpuMRTTexture.createView(viewDescriptor); - const colorMSAATextureView = gpuMSAATexture === null || gpuMSAATexture === void 0 ? void 0 : gpuMSAATexture.createView(msaaViewDescriptor); - colorAttachments.push({ - view: colorMSAATextureView ? colorMSAATextureView : colorTextureView, - resolveTarget: gpuMSAATexture ? colorTextureView : undefined, - clearValue: index !== 0 && mustClearColor ? (isRTInteger ? clearColorForIntegerRT : clearColor) : undefined, - loadOp: index !== 0 && mustClearColor ? LoadOp.Clear : LoadOp.Load, - storeOp: StoreOp.Store, - }); - } - } - this._cacheRenderPipeline.setMRT(rtWrapper.textures, this._mrtAttachments.length); - this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments); - } - else { - // single render target - const internalTexture = rtWrapper.texture; - if (internalTexture) { - const gpuWrapper = internalTexture._hardwareTexture; - const gpuTexture = gpuWrapper.underlyingResource; - const gpuMSAATexture = gpuWrapper.getMSAATexture(); - const colorTextureView = gpuTexture.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor); - const colorMSAATextureView = gpuMSAATexture === null || gpuMSAATexture === void 0 ? void 0 : gpuMSAATexture.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor); - const isRTInteger = internalTexture.type === 7 || internalTexture.type === 5; - colorAttachments.push({ - view: colorMSAATextureView ? colorMSAATextureView : colorTextureView, - resolveTarget: gpuMSAATexture ? colorTextureView : undefined, - clearValue: mustClearColor ? (isRTInteger ? clearColorForIntegerRT : clearColor) : undefined, - loadOp: mustClearColor ? LoadOp.Clear : LoadOp.Load, - storeOp: StoreOp.Store, - }); - } - else { - colorAttachments.push(null); - } - } - (_e = this._debugPushGroup) === null || _e === void 0 ? void 0 : _e.call(this, "render target pass", 1); - this._rttRenderPassWrapper.renderPassDescriptor = { - colorAttachments, - depthStencilAttachment: depthStencilTexture && gpuDepthStencilTexture - ? { - view: depthMSAATextureView ? depthMSAATextureView : depthTextureView, - depthClearValue: mustClearDepth ? (this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue) : undefined, - depthLoadOp: mustClearDepth ? LoadOp.Clear : LoadOp.Load, - depthStoreOp: StoreOp.Store, - stencilClearValue: rtWrapper._depthStencilTextureWithStencil && mustClearStencil ? this._clearStencilValue : undefined, - stencilLoadOp: !depthTextureHasStencil - ? undefined - : rtWrapper._depthStencilTextureWithStencil && mustClearStencil - ? LoadOp.Clear - : LoadOp.Load, - stencilStoreOp: !depthTextureHasStencil ? undefined : StoreOp.Store, - } - : undefined, - occlusionQuerySet: ((_f = this._occlusionQuery) === null || _f === void 0 ? void 0 : _f.hasQueries) ? this._occlusionQuery.querySet : undefined, - }; - this._rttRenderPassWrapper.renderPass = this._renderTargetEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - const internalTexture = rtWrapper.texture; - console.log("frame #" + this._count + " - render target begin pass - internalTexture.uniqueId=", internalTexture.uniqueId, "width=", internalTexture.width, "height=", internalTexture.height, this._rttRenderPassWrapper.renderPassDescriptor); - } - } - this._currentRenderPass = this._rttRenderPassWrapper.renderPass; - (_g = this._debugFlushPendingCommands) === null || _g === void 0 ? void 0 : _g.call(this); - this._resetCurrentViewport(1); - this._resetCurrentScissor(1); - this._resetCurrentStencilRef(1); - this._resetCurrentColorBlend(1); - if (!gpuDepthStencilWrapper || !WebGPUTextureHelper.HasStencilAspect(gpuDepthStencilWrapper.format)) { - this._stencilStateComposer.enabled = false; - } - } - /** @internal */ - _endRenderTargetRenderPass() { - var _a, _b, _c, _d; - if (this._currentRenderPass) { - const gpuWrapper = (_a = this._currentRenderTarget.texture) === null || _a === void 0 ? void 0 : _a._hardwareTexture; - if (gpuWrapper && !this._snapshotRendering.endRenderTargetPass(this._currentRenderPass, gpuWrapper) && !this.compatibilityMode) { - this._bundleListRenderTarget.run(this._currentRenderPass); - this._bundleListRenderTarget.reset(); - } - this._currentRenderPass.end(); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - 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); - } - } - (_d = this._debugPopGroup) === null || _d === void 0 ? void 0 : _d.call(this, 1); - this._resetCurrentViewport(1); - this._viewport(0, 0, 0, 0); - this._resetCurrentScissor(1); - this._resetCurrentStencilRef(1); - this._resetCurrentColorBlend(1); - this._currentRenderPass = null; - this._rttRenderPassWrapper.reset(); - } - } - _getCurrentRenderPass() { - if (this._currentRenderTarget && !this._currentRenderPass) { - // delayed creation of the render target pass, but we now need to create it as we are requested the render pass - this._startRenderTargetRenderPass(this._currentRenderTarget, false, null, false, false); - } - else if (!this._currentRenderPass) { - this._startMainRenderPass(false); - } - return this._currentRenderPass; - } - /** @internal */ - _getCurrentRenderPassIndex() { - return this._currentRenderPass === null ? -1 : this._currentRenderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1; - } - _startMainRenderPass(setClearStates, clearColor, clearDepth, clearStencil) { - var _a, _b, _c; - if (this._mainRenderPassWrapper.renderPass) { - this.flushFramebuffer(false); - } - if (this.useReverseDepthBuffer) { - this.setDepthFunctionToGreaterOrEqual(); - } - const mustClearColor = setClearStates && clearColor; - const mustClearDepth = setClearStates && clearDepth; - const mustClearStencil = setClearStates && clearStencil; - this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue = mustClearColor ? clearColor : undefined; - this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp = mustClearColor ? LoadOp.Clear : LoadOp.Load; - this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue = mustClearDepth - ? this.useReverseDepthBuffer - ? this._clearReverseDepthValue - : this._clearDepthValue - : undefined; - this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp = mustClearDepth ? LoadOp.Clear : LoadOp.Load; - this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue = mustClearStencil ? this._clearStencilValue : undefined; - this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp = !this.isStencilEnable - ? undefined - : mustClearStencil - ? LoadOp.Clear - : LoadOp.Load; - this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet = ((_a = this._occlusionQuery) === null || _a === void 0 ? void 0 : _a.hasQueries) ? this._occlusionQuery.querySet : undefined; - const swapChainTexture = this._context.getCurrentTexture(); - this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(swapChainTexture); - // Resolve in case of MSAA - if (this._options.antialias) { - viewDescriptorSwapChainAntialiasing.format = swapChainTexture.format; - this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget = swapChainTexture.createView(viewDescriptorSwapChainAntialiasing); - } - else { - viewDescriptorSwapChain.format = swapChainTexture.format; - this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view = swapChainTexture.createView(viewDescriptorSwapChain); - } - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - console.log("frame #" + this._count + " - main begin pass - texture width=" + this._mainTextureExtends.width, " height=" + this._mainTextureExtends.height, this._mainRenderPassWrapper.renderPassDescriptor); - } - } - (_b = this._debugPushGroup) === null || _b === void 0 ? void 0 : _b.call(this, "main pass", 0); - this._currentRenderPass = this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor); - this._mainRenderPassWrapper.renderPass = this._currentRenderPass; - (_c = this._debugFlushPendingCommands) === null || _c === void 0 ? void 0 : _c.call(this); - this._resetCurrentViewport(0); - this._resetCurrentScissor(0); - this._resetCurrentStencilRef(0); - this._resetCurrentColorBlend(0); - if (!this._isStencilEnable) { - this._stencilStateComposer.enabled = false; - } - } - _endMainRenderPass() { - var _a; - if (this._mainRenderPassWrapper.renderPass !== null) { - this._snapshotRendering.endMainRenderPass(); - if (!this.compatibilityMode && !this._snapshotRendering.play) { - this._bundleList.run(this._mainRenderPassWrapper.renderPass); - this._bundleList.reset(); - } - this._mainRenderPassWrapper.renderPass.end(); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - console.log("frame #" + this._count + " - main end pass"); - } - } - (_a = this._debugPopGroup) === null || _a === void 0 ? void 0 : _a.call(this, 0); - this._resetCurrentViewport(0); - this._resetCurrentScissor(0); - this._resetCurrentStencilRef(0); - this._resetCurrentColorBlend(0); - if (this._mainRenderPassWrapper.renderPass === this._currentRenderPass) { - this._currentRenderPass = null; - } - this._mainRenderPassWrapper.reset(false); - } - } - /** - * Binds the frame buffer to the specified texture. - * @param texture The render target wrapper to render to - * @param faceIndex The face of the texture to render to in case of cube texture - * @param requiredWidth The width of the target to render to - * @param requiredHeight The height of the target to render to - * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true - * @param lodLevel defines the lod level to bind to the frame buffer - * @param layer defines the 2d array index to bind to frame buffer to - */ - bindFramebuffer(texture, faceIndex = 0, requiredWidth, requiredHeight, forceFullscreenViewport, lodLevel = 0, layer = 0) { - var _a, _b; - const hardwareTexture = (_a = texture.texture) === null || _a === void 0 ? void 0 : _a._hardwareTexture; - if (this._currentRenderTarget) { - this.unBindFramebuffer(this._currentRenderTarget); - } - this._currentRenderTarget = texture; - if (hardwareTexture) { - hardwareTexture._currentLayer = texture.isCube ? layer * 6 + faceIndex : layer; - } - this._rttRenderPassWrapper.colorAttachmentGPUTextures[0] = hardwareTexture; - this._rttRenderPassWrapper.depthTextureFormat = this._currentRenderTarget._depthStencilTexture - ? WebGPUTextureHelper.GetWebGPUTextureFormat(-1, this._currentRenderTarget._depthStencilTexture.format) - : undefined; - this._setDepthTextureFormat(this._rttRenderPassWrapper); - this._setColorFormat(this._rttRenderPassWrapper); - this._rttRenderPassWrapper.colorAttachmentViewDescriptor = { - format: this._colorFormat, - dimension: TextureViewDimension.E2d, - mipLevelCount: 1, - baseArrayLayer: texture.isCube ? layer * 6 + faceIndex : layer, - baseMipLevel: lodLevel, - arrayLayerCount: 1, - aspect: TextureAspect.All, - }; - this._rttRenderPassWrapper.depthAttachmentViewDescriptor = { - format: this._depthTextureFormat, - dimension: TextureViewDimension.E2d, - mipLevelCount: 1, - baseArrayLayer: texture.isCube ? layer * 6 + faceIndex : layer, - baseMipLevel: 0, - arrayLayerCount: 1, - aspect: TextureAspect.All, - }; - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - 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); - } - } - this._currentRenderPass = null; // lazy creation of the render pass, hoping the render pass will be created by a call to clear()... - if (this.snapshotRendering && this.snapshotRenderingMode === 1) { - // force the creation of the render pass as we know in fast snapshot rendering mode clear() won't be called - this._getCurrentRenderPass(); - } - if (this._cachedViewport && !forceFullscreenViewport) { - this.setViewport(this._cachedViewport, requiredWidth, requiredHeight); - } - else { - if (!requiredWidth) { - requiredWidth = texture.width; - if (lodLevel) { - requiredWidth = requiredWidth / Math.pow(2, lodLevel); - } - } - if (!requiredHeight) { - requiredHeight = texture.height; - if (lodLevel) { - requiredHeight = requiredHeight / Math.pow(2, lodLevel); - } - } - this._viewport(0, 0, requiredWidth, requiredHeight); - } - this.wipeCaches(); - } - /** - * Unbind the current render target texture from the WebGPU context - * @param texture defines the render target wrapper to unbind - * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated - * @param onBeforeUnbind defines a function which will be called before the effective unbind - */ - unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) { - var _a, _b; - const saveCRT = this._currentRenderTarget; - this._currentRenderTarget = null; // to be iso with thinEngine, this._currentRenderTarget must be null when onBeforeUnbind is called - if (onBeforeUnbind) { - onBeforeUnbind(); - } - this._currentRenderTarget = saveCRT; - if (this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass) { - this._endRenderTargetRenderPass(); - } - if (((_a = texture.texture) === null || _a === void 0 ? void 0 : _a.generateMipMaps) && !disableGenerateMipMaps && !texture.isCube) { - this._generateMipmaps(texture.texture); - } - this._currentRenderTarget = null; - this._onAfterUnbindFrameBufferObservable.notifyObservers(this); - if (this.dbgVerboseLogsForFirstFrames) { - if (this._count === undefined) { - this._count = 0; - } - if (!this._count || this._count < this.dbgVerboseLogsNumFrames) { - console.log("frame #" + this._count + " - unBindFramebuffer called - internalTexture.uniqueId=", (_b = texture.texture) === null || _b === void 0 ? void 0 : _b.uniqueId); - } - } - this._mrtAttachments = []; - this._cacheRenderPipeline.setMRT([]); - this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments); - this._currentRenderPass = this._mainRenderPassWrapper.renderPass; - this._setDepthTextureFormat(this._mainRenderPassWrapper); - this._setColorFormat(this._mainRenderPassWrapper); - } - /** - * Unbind the current render target and bind the default framebuffer - */ - restoreDefaultFramebuffer() { - if (this._currentRenderTarget) { - this.unBindFramebuffer(this._currentRenderTarget); - } - else { - this._currentRenderPass = this._mainRenderPassWrapper.renderPass; - this._setDepthTextureFormat(this._mainRenderPassWrapper); - this._setColorFormat(this._mainRenderPassWrapper); - } - if (this._currentRenderPass) { - if (this._cachedViewport) { - this.setViewport(this._cachedViewport); - } - } - this.wipeCaches(); - } - //------------------------------------------------------------------------------ - // Render - //------------------------------------------------------------------------------ - /** - * @internal - */ - _setColorFormat(wrapper) { - var _a, _b; - const format = (_b = (_a = wrapper.colorAttachmentGPUTextures[0]) === null || _a === void 0 ? void 0 : _a.format) !== null && _b !== void 0 ? _b : null; - this._cacheRenderPipeline.setColorFormat(format); - if (this._colorFormat === format) { - return; - } - this._colorFormat = format; - } - /** - * @internal - */ - _setDepthTextureFormat(wrapper) { - this._cacheRenderPipeline.setDepthStencilFormat(wrapper.depthTextureFormat); - if (this._depthTextureFormat === wrapper.depthTextureFormat) { - return; - } - this._depthTextureFormat = wrapper.depthTextureFormat; - } - setDitheringState() { - // Does not exist in WebGPU - } - setRasterizerState() { - // Does not exist in WebGPU - } - /** - * Set various states to the webGL context - * @param culling defines culling state: true to enable culling, false to disable it - * @param zOffset defines the value to apply to zOffset (0 by default) - * @param force defines if states must be applied even if cache is up to date - * @param reverseSide defines if culling must be reversed (CCW if false, CW if true) - * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled) - * @param stencil stencil states to set - * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default) - */ - setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) { - var _a, _b; - // Culling - if (this._depthCullingState.cull !== culling || force) { - this._depthCullingState.cull = culling; - } - // Cull face - const cullFace = ((_b = (_a = this.cullBackFaces) !== null && _a !== void 0 ? _a : cullBackFaces) !== null && _b !== void 0 ? _b : true) ? 1 : 2; - if (this._depthCullingState.cullFace !== cullFace || force) { - this._depthCullingState.cullFace = cullFace; - } - // Z offset - this.setZOffset(zOffset); - this.setZOffsetUnits(zOffsetUnits); - // Front face - const frontFace = reverseSide ? (this._currentRenderTarget ? 1 : 2) : this._currentRenderTarget ? 2 : 1; - if (this._depthCullingState.frontFace !== frontFace || force) { - this._depthCullingState.frontFace = frontFace; - } - this._stencilStateComposer.stencilMaterial = stencil; - } - _applyRenderPassChanges(renderPass, bundleList) { - var _a; - const mustUpdateViewport = this._mustUpdateViewport(renderPass); - const mustUpdateScissor = this._mustUpdateScissor(renderPass); - const mustUpdateStencilRef = !this._stencilStateComposer.enabled ? false : this._mustUpdateStencilRef(renderPass); - const mustUpdateBlendColor = !this._alphaState.alphaBlend ? false : this._mustUpdateBlendColor(renderPass); - if (bundleList) { - if (mustUpdateViewport) { - bundleList.addItem(new WebGPURenderItemViewport(this._viewportCached.x, this._viewportCached.y, this._viewportCached.z, this._viewportCached.w)); - } - if (mustUpdateScissor) { - bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w)); - } - if (mustUpdateStencilRef) { - bundleList.addItem(new WebGPURenderItemStencilRef((_a = this._stencilStateComposer.funcRef) !== null && _a !== void 0 ? _a : 0)); - } - if (mustUpdateBlendColor) { - bundleList.addItem(new WebGPURenderItemBlendColor(this._alphaState._blendConstants.slice())); - } - } - else { - if (mustUpdateViewport) { - this._applyViewport(renderPass); - } - if (mustUpdateScissor) { - this._applyScissor(renderPass); - } - if (mustUpdateStencilRef) { - this._applyStencilRef(renderPass); - } - if (mustUpdateBlendColor) { - this._applyBlendColor(renderPass); - } - } - } - _draw(drawType, fillMode, start, count, instancesCount) { - var _a; - const renderPass = this._getCurrentRenderPass(); - const renderPassIndex = this._getCurrentRenderPassIndex(); - const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget; - this.applyStates(); - const webgpuPipelineContext = this._currentEffect._pipelineContext; - this.bindUniformBufferBase(this._currentRenderTarget ? this._ubInvertY : this._ubDontInvertY, 0, WebGPUShaderProcessor.InternalsUBOName); - if (webgpuPipelineContext.uniformBuffer) { - webgpuPipelineContext.uniformBuffer.update(); - this.bindUniformBufferBase(webgpuPipelineContext.uniformBuffer.getBuffer(), 0, WebGPUShaderProcessor.LeftOvertUBOName); - } - if (this._snapshotRendering.play) { - this._reportDrawCall(); - return; - } - if (!this.compatibilityMode && - (this._currentDrawContext.isDirty(this._currentMaterialContext.updateId) || this._currentMaterialContext.isDirty || this._currentMaterialContext.forceBindGroupCreation)) { - this._currentDrawContext.fastBundle = undefined; - } - const useFastPath = !this.compatibilityMode && this._currentDrawContext.fastBundle; - let renderPass2 = renderPass; - if (useFastPath || this._snapshotRendering.record) { - this._applyRenderPassChanges(renderPass, bundleList); - if (!this._snapshotRendering.record) { - this._counters.numBundleReuseNonCompatMode++; - if (this._currentDrawContext.indirectDrawBuffer) { - this._currentDrawContext.setIndirectData(count, instancesCount || 1, start); - } - bundleList.addBundle(this._currentDrawContext.fastBundle); - this._reportDrawCall(); - return; - } - renderPass2 = bundleList.getBundleEncoder(this._cacheRenderPipeline.colorFormats, this._depthTextureFormat, this.currentSampleCount); // for snapshot recording mode - bundleList.numDrawCalls++; - } - let textureState = 0; - if (!this._caps.textureFloatLinearFiltering && this._currentMaterialContext.hasFloatTextures) { - let bitVal = 1; - for (let i = 0; i < webgpuPipelineContext.shaderProcessingContext.textureNames.length; ++i) { - const textureName = webgpuPipelineContext.shaderProcessingContext.textureNames[i]; - const texture = (_a = this._currentMaterialContext.textures[textureName]) === null || _a === void 0 ? void 0 : _a.texture; - if ((texture === null || texture === void 0 ? void 0 : texture.type) === 1) { - textureState |= bitVal; - } - bitVal = bitVal << 1; - } - } - this._currentMaterialContext.textureState = textureState; - const pipeline = this._cacheRenderPipeline.getRenderPipeline(fillMode, this._currentEffect, this.currentSampleCount, textureState); - const bindGroups = this._cacheBindGroups.getBindGroups(webgpuPipelineContext, this._currentDrawContext, this._currentMaterialContext); - if (!this._snapshotRendering.record) { - this._applyRenderPassChanges(renderPass, !this.compatibilityMode ? bundleList : null); - if (!this.compatibilityMode) { - this._counters.numBundleCreationNonCompatMode++; - renderPass2 = this._device.createRenderBundleEncoder({ - colorFormats: this._cacheRenderPipeline.colorFormats, - depthStencilFormat: this._depthTextureFormat, - sampleCount: this.currentSampleCount, - }); - } - } - // bind pipeline - renderPass2.setPipeline(pipeline); - // bind index/vertex buffers - if (this._currentIndexBuffer) { - renderPass2.setIndexBuffer(this._currentIndexBuffer.underlyingResource, this._currentIndexBuffer.is32Bits ? IndexFormat.Uint32 : IndexFormat.Uint16, 0); - } - const vertexBuffers = this._cacheRenderPipeline.vertexBuffers; - for (let index = 0; index < vertexBuffers.length; index++) { - const vertexBuffer = vertexBuffers[index]; - const buffer = vertexBuffer.getBuffer(); - if (buffer) { - renderPass2.setVertexBuffer(index, buffer.underlyingResource, vertexBuffer._validOffsetRange ? 0 : vertexBuffer.byteOffset); - } - } - // bind bind groups - for (let i = 0; i < bindGroups.length; i++) { - renderPass2.setBindGroup(i, bindGroups[i]); - } - // draw - const nonCompatMode = !this.compatibilityMode && !this._snapshotRendering.record; - if (nonCompatMode && this._currentDrawContext.indirectDrawBuffer) { - this._currentDrawContext.setIndirectData(count, instancesCount || 1, start); - if (drawType === 0) { - renderPass2.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer, 0); - } - else { - renderPass2.drawIndirect(this._currentDrawContext.indirectDrawBuffer, 0); - } - } - else if (drawType === 0) { - renderPass2.drawIndexed(count, instancesCount || 1, start, 0, 0); - } - else { - renderPass2.draw(count, instancesCount || 1, start, 0); - } - if (nonCompatMode) { - this._currentDrawContext.fastBundle = renderPass2.finish(); - bundleList.addBundle(this._currentDrawContext.fastBundle); - } - this._reportDrawCall(); - } - /** - * Draw a list of indexed primitives - * @param fillMode defines the primitive to use - * @param indexStart defines the starting index - * @param indexCount defines the number of index to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - drawElementsType(fillMode, indexStart, indexCount, instancesCount = 1) { - this._draw(0, fillMode, indexStart, indexCount, instancesCount); - } - /** - * Draw a list of unindexed primitives - * @param fillMode defines the primitive to use - * @param verticesStart defines the index of first vertex to draw - * @param verticesCount defines the count of vertices to draw - * @param instancesCount defines the number of instances to draw (if instantiation is enabled) - */ - drawArraysType(fillMode, verticesStart, verticesCount, instancesCount = 1) { - this._currentIndexBuffer = null; - this._draw(1, fillMode, verticesStart, verticesCount, instancesCount); - } - //------------------------------------------------------------------------------ - // Dispose - //------------------------------------------------------------------------------ - /** - * Dispose and release all associated resources - */ - dispose() { - var _a, _b; - this._isDisposed = true; - (_a = this._mainTexture) === null || _a === void 0 ? void 0 : _a.destroy(); - (_b = this._depthTexture) === null || _b === void 0 ? void 0 : _b.destroy(); - this._device.destroy(); - super.dispose(); - } - //------------------------------------------------------------------------------ - // Misc - //------------------------------------------------------------------------------ - /** - * Gets the current render width - * @param useScreen defines if screen size must be used (or the current render target if any) - * @returns a number defining the current render width - */ - getRenderWidth(useScreen = false) { - var _a, _b; - if (!useScreen && this._currentRenderTarget) { - return this._currentRenderTarget.width; - } - return (_b = (_a = this._renderingCanvas) === null || _a === void 0 ? void 0 : _a.width) !== null && _b !== void 0 ? _b : 0; - } - /** - * Gets the current render height - * @param useScreen defines if screen size must be used (or the current render target if any) - * @returns a number defining the current render height - */ - getRenderHeight(useScreen = false) { - var _a, _b; - if (!useScreen && this._currentRenderTarget) { - return this._currentRenderTarget.height; - } - return (_b = (_a = this._renderingCanvas) === null || _a === void 0 ? void 0 : _a.height) !== null && _b !== void 0 ? _b : 0; - } - //------------------------------------------------------------------------------ - // Errors - //------------------------------------------------------------------------------ - /** - * Get the current error code of the WebGPU context - * @returns the error code - */ - getError() { - // TODO WEBGPU. from the webgpu errors. - return 0; - } - //------------------------------------------------------------------------------ - // Unused WebGPU - //------------------------------------------------------------------------------ - /** - * @internal - */ - bindSamplers() { } - /** - * @internal - */ - _bindTextureDirectly() { - return false; - } - /** - * Gets a boolean indicating if all created effects are ready - * @returns always true - No parallel shader compilation - */ - areAllEffectsReady() { - return true; - } - /** - * @internal - */ - _executeWhenRenderingStateIsCompiled(pipelineContext, action) { - // No parallel shader compilation. - // No Async, so direct launch - action(); - } - /** - * @internal - */ - _isRenderingStateCompiled() { - // No parallel shader compilation. - return true; - } - /** @internal */ - _getUnpackAlignement() { - return 1; - } - /** - * @internal - */ - _unpackFlipY() { } - /** - * @internal - */ - _bindUnboundFramebuffer() { - throw "_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead"; - } - // TODO WEBGPU. All of the below should go once engine split with baseEngine. - /** - * @internal - */ - _getSamplingParameters() { - throw "_getSamplingParameters is not available in WebGPU"; - } - /** - * @internal - */ - getUniforms() { - return []; - } - /** - * @internal - */ - setIntArray() { - return false; - } - /** - * @internal - */ - setIntArray2() { - return false; - } - /** - * @internal - */ - setIntArray3() { - return false; - } - /** - * @internal - */ - setIntArray4() { - return false; - } - /** - * @internal - */ - setArray() { - return false; - } - /** - * @internal - */ - setArray2() { - return false; - } - /** - * @internal - */ - setArray3() { - return false; - } - /** - * @internal - */ - setArray4() { - return false; - } - /** - * @internal - */ - setMatrices() { - return false; - } - /** - * @internal - */ - setMatrix3x3() { - return false; - } - /** - * @internal - */ - setMatrix2x2() { - return false; - } - /** - * @internal - */ - setFloat() { - return false; - } - /** - * @internal - */ - setFloat2() { - return false; - } - /** - * @internal - */ - setFloat3() { - return false; - } - /** - * @internal - */ - setFloat4() { - return false; - } -} -// Default glslang options. -webgpuEngine_WebGPUEngine._GLSLslangDefaultOptions = { - jsPath: "https://preview.babylonjs.com/glslang/glslang.js", - wasmPath: "https://preview.babylonjs.com/glslang/glslang.wasm", -}; -/** true to enable using TintWASM to convert Spir-V to WGSL */ -webgpuEngine_WebGPUEngine.UseTWGSL = true; -//# sourceMappingURL=webgpuEngine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.alpha.js - - - -webgpuEngine_WebGPUEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange = false) { - if (this._alphaMode === mode && ((mode === 0 && !this._alphaState.alphaBlend) || (mode !== 0 && this._alphaState.alphaBlend))) { - if (!noDepthWriteChange) { - // 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) - const depthMask = mode === 0; - if (this.depthCullingState.depthMask !== depthMask) { - this.setDepthWrite(depthMask); - this._cacheRenderPipeline.setDepthWriteEnabled(depthMask); - } - } - return; - } - switch (mode) { - case 0: - this._alphaState.alphaBlend = false; - break; - case 7: - this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 1); - this._alphaState.alphaBlend = true; - break; - case 8: - this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771); - this._alphaState.alphaBlend = true; - break; - case 2: - this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 1); - this._alphaState.alphaBlend = true; - break; - case 6: - this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1); - this._alphaState.alphaBlend = true; - break; - case 1: - this._alphaState.setAlphaBlendFunctionParameters(770, 1, 0, 1); - this._alphaState.alphaBlend = true; - break; - case 3: - this._alphaState.setAlphaBlendFunctionParameters(0, 769, 1, 1); - this._alphaState.alphaBlend = true; - break; - case 4: - this._alphaState.setAlphaBlendFunctionParameters(774, 0, 1, 1); - this._alphaState.alphaBlend = true; - break; - case 5: - this._alphaState.setAlphaBlendFunctionParameters(770, 769, 1, 1); - this._alphaState.alphaBlend = true; - break; - case 9: - this._alphaState.setAlphaBlendFunctionParameters(32769, 32770, 32771, 32772); - this._alphaState.alphaBlend = true; - break; - case 10: - this._alphaState.setAlphaBlendFunctionParameters(1, 769, 1, 771); - this._alphaState.alphaBlend = true; - break; - case 11: - this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 1); - this._alphaState.alphaBlend = true; - break; - case 12: - this._alphaState.setAlphaBlendFunctionParameters(772, 1, 0, 0); - this._alphaState.alphaBlend = true; - break; - case 13: - this._alphaState.setAlphaBlendFunctionParameters(775, 769, 773, 771); - this._alphaState.alphaBlend = true; - break; - case 14: - this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771); - this._alphaState.alphaBlend = true; - break; - case 15: - this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 0); - this._alphaState.alphaBlend = true; - break; - case 16: - this._alphaState.setAlphaBlendFunctionParameters(775, 769, 0, 1); - this._alphaState.alphaBlend = true; - break; - case 17: - // Same as ALPHA_COMBINE but accumulates (1 - alpha) values in the alpha channel for a later readout in order independant transparency - this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 771); - this._alphaState.alphaBlend = true; - break; - } - if (!noDepthWriteChange) { - this.setDepthWrite(mode === engine_Engine.ALPHA_DISABLE); - this._cacheRenderPipeline.setDepthWriteEnabled(mode === engine_Engine.ALPHA_DISABLE); - } - this._alphaMode = mode; - this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend); - this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters); -}; -webgpuEngine_WebGPUEngine.prototype.setAlphaEquation = function (equation) { - engine_Engine.prototype.setAlphaEquation.call(this, equation); - this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters); -}; -//# sourceMappingURL=engine.alpha.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuComputeContext.js - - - -/** @internal */ -class WebGPUComputeContext { - getBindGroups(bindings, computePipeline, bindingsMapping) { - if (!bindingsMapping) { - throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!"); - } - if (this._bindGroups.length === 0) { - const bindGroupEntriesExist = this._bindGroupEntries.length > 0; - for (const key in bindings) { - const binding = bindings[key], location = bindingsMapping[key], group = location.group, index = location.binding, type = binding.type, object = binding.object; - let indexInGroupEntries = binding.indexInGroupEntries; - let entries = this._bindGroupEntries[group]; - if (!entries) { - entries = this._bindGroupEntries[group] = []; - } - switch (type) { - case ComputeBindingType.Sampler: { - const sampler = object; - if (indexInGroupEntries !== undefined && bindGroupEntriesExist) { - entries[indexInGroupEntries].resource = this._cacheSampler.getSampler(sampler); - } - else { - binding.indexInGroupEntries = entries.length; - entries.push({ - binding: index, - resource: this._cacheSampler.getSampler(sampler), - }); - } - break; - } - case ComputeBindingType.Texture: - case ComputeBindingType.TextureWithoutSampler: { - const texture = object; - const hardwareTexture = texture._texture._hardwareTexture; - if (indexInGroupEntries !== undefined && bindGroupEntriesExist) { - if (type === ComputeBindingType.Texture) { - entries[indexInGroupEntries++].resource = this._cacheSampler.getSampler(texture._texture); - } - entries[indexInGroupEntries].resource = hardwareTexture.view; - } - else { - binding.indexInGroupEntries = entries.length; - if (type === ComputeBindingType.Texture) { - entries.push({ - binding: index - 1, - resource: this._cacheSampler.getSampler(texture._texture), - }); - } - entries.push({ - binding: index, - resource: hardwareTexture.view, - }); - } - break; - } - case ComputeBindingType.StorageTexture: { - const texture = object; - const hardwareTexture = texture._texture._hardwareTexture; - if ((hardwareTexture.textureAdditionalUsages & TextureUsage.StorageBinding) === 0) { - logger_Logger.Error(`computeDispatch: The texture (name=${texture.name}, uniqueId=${texture.uniqueId}) is not a storage texture!`, 50); - } - if (indexInGroupEntries !== undefined && bindGroupEntriesExist) { - entries[indexInGroupEntries].resource = hardwareTexture.viewForWriting; - } - else { - binding.indexInGroupEntries = entries.length; - entries.push({ - binding: index, - resource: hardwareTexture.viewForWriting, - }); - } - break; - } - case ComputeBindingType.UniformBuffer: - case ComputeBindingType.StorageBuffer: { - const buffer = type === ComputeBindingType.UniformBuffer ? object : object; - const dataBuffer = buffer.getBuffer(); - const webgpuBuffer = dataBuffer.underlyingResource; - if (indexInGroupEntries !== undefined && bindGroupEntriesExist) { - entries[indexInGroupEntries].resource.buffer = webgpuBuffer; - entries[indexInGroupEntries].resource.size = dataBuffer.capacity; - } - else { - binding.indexInGroupEntries = entries.length; - entries.push({ - binding: index, - resource: { - buffer: webgpuBuffer, - offset: 0, - size: dataBuffer.capacity, - }, - }); - } - break; - } - } - } - for (let i = 0; i < this._bindGroupEntries.length; ++i) { - const entries = this._bindGroupEntries[i]; - if (!entries) { - this._bindGroups[i] = undefined; - continue; - } - this._bindGroups[i] = this._device.createBindGroup({ - layout: computePipeline.getBindGroupLayout(i), - entries, - }); - } - this._bindGroups.length = this._bindGroupEntries.length; - } - return this._bindGroups; - } - constructor(device, cacheSampler) { - this._device = device; - this._cacheSampler = cacheSampler; - this.uniqueId = WebGPUComputeContext._Counter++; - this._bindGroupEntries = []; - this.clear(); - } - clear() { - this._bindGroups = []; - // 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) - } -} -WebGPUComputeContext._Counter = 0; -//# sourceMappingURL=webgpuComputeContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuComputePipelineContext.js -/** @internal */ -class WebGPUComputePipelineContext { - get isAsync() { - return false; - } - get isReady() { - if (this.stage) { - return true; - } - return false; - } - constructor(engine) { - this._name = "unnamed"; - this.engine = engine; - } - _getComputeShaderCode() { - var _a; - return (_a = this.sources) === null || _a === void 0 ? void 0 : _a.compute; - } - dispose() { } -} -//# sourceMappingURL=webgpuComputePipelineContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.computeShader.js - - - - - -webgpuEngine_WebGPUEngine.prototype.createComputeContext = function () { - return new WebGPUComputeContext(this._device, this._cacheSampler); -}; -webgpuEngine_WebGPUEngine.prototype.createComputeEffect = function (baseName, options) { - const compute = baseName.computeElement || baseName.compute || baseName.computeToken || baseName.computeSource || baseName; - const name = compute + "@" + options.defines; - if (this._compiledComputeEffects[name]) { - const compiledEffect = this._compiledComputeEffects[name]; - if (options.onCompiled && compiledEffect.isReady()) { - options.onCompiled(compiledEffect); - } - return compiledEffect; - } - const effect = new ComputeEffect(baseName, options, this, name); - this._compiledComputeEffects[name] = effect; - return effect; -}; -webgpuEngine_WebGPUEngine.prototype.createComputePipelineContext = function () { - return new WebGPUComputePipelineContext(this); -}; -webgpuEngine_WebGPUEngine.prototype.areAllComputeEffectsReady = function () { - for (const key in this._compiledComputeEffects) { - const effect = this._compiledComputeEffects[key]; - if (!effect.isReady()) { - return false; - } - } - return true; -}; -webgpuEngine_WebGPUEngine.prototype.computeDispatch = function (effect, context, bindings, x, y, z, bindingsMapping) { - if (this._currentRenderTarget) { - // 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 - // 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 - this._onAfterUnbindFrameBufferObservable.addOnce(() => { - this.computeDispatch(effect, context, bindings, x, y, z, bindingsMapping); - }); - return; - } - const contextPipeline = effect._pipelineContext; - const computeContext = context; - if (!contextPipeline.computePipeline) { - contextPipeline.computePipeline = this._device.createComputePipeline({ - layout: AutoLayoutMode.Auto, - compute: contextPipeline.stage, - }); - } - const commandEncoder = this._renderTargetEncoder; - const computePass = commandEncoder.beginComputePass(); - computePass.setPipeline(contextPipeline.computePipeline); - const bindGroups = computeContext.getBindGroups(bindings, contextPipeline.computePipeline, bindingsMapping); - for (let i = 0; i < bindGroups.length; ++i) { - const bindGroup = bindGroups[i]; - if (!bindGroup) { - continue; - } - computePass.setBindGroup(i, bindGroup); - } - computePass.dispatchWorkgroups(x, y, z); - computePass.end(); -}; -webgpuEngine_WebGPUEngine.prototype.releaseComputeEffects = function () { - for (const name in this._compiledComputeEffects) { - const webGPUPipelineContextCompute = this._compiledComputeEffects[name].getPipelineContext(); - this._deleteComputePipelineContext(webGPUPipelineContextCompute); - } - this._compiledComputeEffects = {}; -}; -webgpuEngine_WebGPUEngine.prototype._prepareComputePipelineContext = function (pipelineContext, computeSourceCode, rawComputeSourceCode, defines, entryPoint) { - const webGpuContext = pipelineContext; - if (this.dbgShowShaderCode) { - console.log(defines); - console.log(computeSourceCode); - } - webGpuContext.sources = { - compute: computeSourceCode, - rawCompute: rawComputeSourceCode, - }; - webGpuContext.stage = this._createComputePipelineStageDescriptor(computeSourceCode, defines, entryPoint); -}; -webgpuEngine_WebGPUEngine.prototype._releaseComputeEffect = function (effect) { - if (this._compiledComputeEffects[effect._key]) { - delete this._compiledComputeEffects[effect._key]; - this._deleteComputePipelineContext(effect.getPipelineContext()); - } -}; -webgpuEngine_WebGPUEngine.prototype._rebuildComputeEffects = function () { - for (const key in this._compiledComputeEffects) { - const effect = this._compiledComputeEffects[key]; - effect._pipelineContext = null; - effect._wasPreviouslyReady = false; - effect._prepareEffect(); - } -}; -webgpuEngine_WebGPUEngine.prototype._deleteComputePipelineContext = function (pipelineContext) { - const webgpuPipelineContext = pipelineContext; - if (webgpuPipelineContext) { - pipelineContext.dispose(); - } -}; -webgpuEngine_WebGPUEngine.prototype._createComputePipelineStageDescriptor = function (computeShader, defines, entryPoint) { - if (defines) { - defines = "//" + defines.split("\n").join("\n//") + "\n"; - } - else { - defines = ""; - } - return { - module: this._device.createShaderModule({ - code: defines + computeShader, - }), - entryPoint, - }; -}; -//# sourceMappingURL=engine.computeShader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.cubeTexture.js - - - -webgpuEngine_WebGPUEngine.prototype._createDepthStencilCubeTexture = function (size, options) { - const internalTexture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.DepthStencil); - internalTexture.isCube = true; - const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false, samples: 1 }, options); - // TODO WEBGPU allow to choose the format? - internalTexture.format = internalOptions.generateStencil ? 13 : 14; - this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples); - this._textureHelper.createGPUTextureForInternalTexture(internalTexture); - this._internalTexturesCache.push(internalTexture); - return internalTexture; -}; -webgpuEngine_WebGPUEngine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, useSRGBBuffer = false) { - return this.createCubeTextureBase(rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, null, (texture, imgs) => { - const imageBitmaps = imgs; // we will always get an ImageBitmap array in WebGPU - const width = imageBitmaps[0].width; - const height = width; - this._setCubeMapTextureParams(texture, !noMipmap); - texture.format = format !== null && format !== void 0 ? format : -1; - const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height); - this._textureHelper.updateCubeTextures(imageBitmaps, gpuTextureWrapper.underlyingResource, width, height, gpuTextureWrapper.format, false, false, 0, 0); - if (!noMipmap) { - this._generateMipmaps(texture, this._uploadEncoder); - } - texture.isReady = true; - texture.onLoadedObservable.notifyObservers(texture); - texture.onLoadedObservable.clear(); - if (onLoad) { - onLoad(); - } - }, !!useSRGBBuffer); -}; -webgpuEngine_WebGPUEngine.prototype._setCubeMapTextureParams = function (texture, loadMipmap, maxLevel) { - texture.samplingMode = loadMipmap ? 3 : 2; - texture._cachedWrapU = 0; - texture._cachedWrapV = 0; - if (maxLevel) { - texture._maxLodLevel = maxLevel; - } -}; -//# sourceMappingURL=engine.cubeTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.debugging.js - -webgpuEngine_WebGPUEngine.prototype._debugPushGroup = function (groupName, targetObject) { - if (!this._options.enableGPUDebugMarkers) { - return; - } - if (targetObject === 0 || targetObject === 1) { - const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder; - encoder.pushDebugGroup(groupName); - } - else if (this._currentRenderPass) { - this._currentRenderPass.pushDebugGroup(groupName); - } - else { - this._pendingDebugCommands.push(["push", groupName]); - } -}; -webgpuEngine_WebGPUEngine.prototype._debugPopGroup = function (targetObject) { - if (!this._options.enableGPUDebugMarkers) { - return; - } - if (targetObject === 0 || targetObject === 1) { - const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder; - encoder.popDebugGroup(); - } - else if (this._currentRenderPass) { - this._currentRenderPass.popDebugGroup(); - } - else { - this._pendingDebugCommands.push(["pop", null]); - } -}; -webgpuEngine_WebGPUEngine.prototype._debugInsertMarker = function (text, targetObject) { - if (!this._options.enableGPUDebugMarkers) { - return; - } - if (targetObject === 0 || targetObject === 1) { - const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder; - encoder.insertDebugMarker(text); - } - else if (this._currentRenderPass) { - this._currentRenderPass.insertDebugMarker(text); - } - else { - this._pendingDebugCommands.push(["insert", text]); - } -}; -webgpuEngine_WebGPUEngine.prototype._debugFlushPendingCommands = function () { - for (let i = 0; i < this._pendingDebugCommands.length; ++i) { - const [name, param] = this._pendingDebugCommands[i]; - switch (name) { - case "push": - this._debugPushGroup(param); - break; - case "pop": - this._debugPopGroup(); - break; - case "insert": - this._debugInsertMarker(param); - break; - } - } - this._pendingDebugCommands.length = 0; -}; -//# sourceMappingURL=engine.debugging.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.dynamicBuffer.js - -webgpuEngine_WebGPUEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset = 0) { - const gpuBuffer = indexBuffer; - let view; - if (indexBuffer.is32Bits) { - view = indices instanceof Uint32Array ? indices : new Uint32Array(indices); - } - else { - view = indices instanceof Uint16Array ? indices : new Uint16Array(indices); - } - this._bufferManager.setSubData(gpuBuffer, offset, view); -}; -webgpuEngine_WebGPUEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) { - const dataBuffer = vertexBuffer; - if (byteOffset === undefined) { - byteOffset = 0; - } - let view; - if (byteLength === undefined) { - if (data instanceof Array) { - view = new Float32Array(data); - } - else if (data instanceof ArrayBuffer) { - view = new Uint8Array(data); - } - else { - view = data; - } - byteLength = view.byteLength; - } - else { - if (data instanceof Array) { - view = new Float32Array(data); - } - else if (data instanceof ArrayBuffer) { - view = new Uint8Array(data); - } - else { - view = data; - } - } - this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength); -}; -//# sourceMappingURL=engine.dynamicBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.dynamicTexture.js - -webgpuEngine_WebGPUEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha = false, format, forceBindTexture, allowGPUOptimization) { - var _a; - if (!texture) { - return; - } - const width = canvas.width, height = canvas.height; - let gpuTextureWrapper = texture._hardwareTexture; - if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) { - gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height); - } - this._textureHelper.updateTexture(canvas, texture, width, height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, premulAlpha, 0, 0, allowGPUOptimization); - if (texture.generateMipMaps) { - this._generateMipmaps(texture, this._uploadEncoder); - } - texture.isReady = true; -}; -//# sourceMappingURL=engine.dynamicTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuExternalTexture.js - -/** - * Nothing specific to WebGPU in this class, but the spec is not final yet so let's remove it later on - * if it is not needed - * @internal - **/ -class WebGPUExternalTexture extends ExternalTexture { - constructor(video) { - super(video); - } -} -//# sourceMappingURL=webgpuExternalTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.externalTexture.js - - - -effect_Effect.prototype.setExternalTexture = function (name, texture) { - this._engine.setExternalTexture(name, texture); -}; -webgpuEngine_WebGPUEngine.prototype.createExternalTexture = function (video) { - const texture = new WebGPUExternalTexture(video); - return texture; -}; -webgpuEngine_WebGPUEngine.prototype.setExternalTexture = function (name, texture) { - if (!texture) { - this._currentMaterialContext.setTexture(name, null); - return; - } - this._setInternalTexture(name, texture); -}; -//# sourceMappingURL=engine.externalTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.multiRender.js - - - - -webgpuEngine_WebGPUEngine.prototype.unBindMultiColorAttachmentFramebuffer = function (rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) { - if (onBeforeUnbind) { - onBeforeUnbind(); - } - const attachments = rtWrapper._attachments; - const count = attachments.length; - if (this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass) { - this._endRenderTargetRenderPass(); - } - for (let i = 0; i < count; i++) { - const texture = rtWrapper.textures[i]; - if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) { - this._generateMipmaps(texture); - } - } - this._currentRenderTarget = null; - this._mrtAttachments = []; - this._cacheRenderPipeline.setMRT([]); - this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments); - this._currentRenderPass = this._mainRenderPassWrapper.renderPass; - this._setDepthTextureFormat(this._mainRenderPassWrapper); - this._setColorFormat(this._mainRenderPassWrapper); -}; -webgpuEngine_WebGPUEngine.prototype.createMultipleRenderTarget = function (size, options, initializeBuffers) { - var _a, _b; - let generateMipMaps = false; - let generateDepthBuffer = true; - let generateStencilBuffer = false; - let generateDepthTexture = false; - let depthTextureFormat = 15; - let textureCount = 1; - const defaultType = 0; - const defaultSamplingMode = 3; - const defaultUseSRGBBuffer = false; - const defaultFormat = 5; - const defaultTarget = 3553; - let types = new Array(); - let samplingModes = new Array(); - let useSRGBBuffers = new Array(); - let formats = new Array(); - let targets = new Array(); - let faceIndex = new Array(); - let layerIndex = new Array(); - let layers = new Array(); - const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size); - if (options !== undefined) { - generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps; - generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; - generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer; - generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture; - textureCount = options.textureCount || 1; - depthTextureFormat = (_a = options.depthTextureFormat) !== null && _a !== void 0 ? _a : 15; - if (options.types) { - types = options.types; - } - if (options.samplingModes) { - samplingModes = options.samplingModes; - } - if (options.useSRGBBuffers) { - useSRGBBuffers = options.useSRGBBuffers; - } - if (options.formats) { - formats = options.formats; - } - if (options.targetTypes) { - targets = options.targetTypes; - } - if (options.faceIndex) { - faceIndex = options.faceIndex; - } - if (options.layerIndex) { - layerIndex = options.layerIndex; - } - if (options.layerCounts) { - layers = options.layerCounts; - } - } - const width = size.width || size; - const height = size.height || size; - let depthStencilTexture = null; - if (generateDepthBuffer || generateStencilBuffer || generateDepthTexture) { - if (!generateDepthTexture) { - // The caller doesn't want a depth texture, so we are free to use the depth texture format we want. - // So, we will align with what the WebGL engine does - if (generateDepthBuffer && generateStencilBuffer) { - depthTextureFormat = 13; - } - else if (generateDepthBuffer) { - depthTextureFormat = 14; - } - else { - depthTextureFormat = 19; - } - } - depthStencilTexture = rtWrapper.createDepthStencilTexture(0, false, generateStencilBuffer, 1, depthTextureFormat); - } - const textures = []; - const attachments = []; - const defaultAttachments = []; - rtWrapper._generateDepthBuffer = generateDepthBuffer; - rtWrapper._generateStencilBuffer = generateStencilBuffer; - rtWrapper._attachments = attachments; - rtWrapper._defaultAttachments = defaultAttachments; - for (let i = 0; i < textureCount; i++) { - let samplingMode = samplingModes[i] || defaultSamplingMode; - let type = types[i] || defaultType; - const format = formats[i] || defaultFormat; - const useSRGBBuffer = (useSRGBBuffers[i] || defaultUseSRGBBuffer) && this._caps.supportSRGBBuffers; - const target = targets[i] || defaultTarget; - const layerCount = (_b = layers[i]) !== null && _b !== void 0 ? _b : 1; - if (type === 1 && !this._caps.textureFloatLinearFiltering) { - // if floating point linear (FLOAT) then force to NEAREST_SAMPLINGMODE - samplingMode = 1; - } - else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { - // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE - samplingMode = 1; - } - if (type === 1 && !this._caps.textureFloat) { - type = 0; - logger_Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"); - } - attachments.push(i + 1); - defaultAttachments.push(initializeBuffers ? i + 1 : i === 0 ? 1 : 0); - if (target === -1) { - continue; - } - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.MultiRenderTarget); - textures[i] = texture; - switch (target) { - case 34067: - texture.isCube = true; - break; - case 32879: - texture.is3D = true; - texture.baseDepth = texture.depth = layerCount; - break; - case 35866: - texture.is2DArray = true; - texture.baseDepth = texture.depth = layerCount; - break; - } - texture.baseWidth = width; - texture.baseHeight = height; - texture.width = width; - texture.height = height; - texture.isReady = true; - texture.samples = 1; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.type = type; - texture._cachedWrapU = 0; - texture._cachedWrapV = 0; - texture._useSRGBBuffer = useSRGBBuffer; - texture.format = format; - this._internalTexturesCache.push(texture); - this._textureHelper.createGPUTextureForInternalTexture(texture); - } - if (depthStencilTexture) { - depthStencilTexture.incrementReferences(); - textures[textureCount] = depthStencilTexture; - this._internalTexturesCache.push(depthStencilTexture); - } - rtWrapper.setTextures(textures); - rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex); - return rtWrapper; -}; -webgpuEngine_WebGPUEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function (rtWrapper, samples) { - if (!rtWrapper || !rtWrapper.textures || rtWrapper.textures[0].samples === samples) { - return samples; - } - const count = rtWrapper.textures.length; - if (count === 0) { - return 1; - } - samples = Math.min(samples, this.getCaps().maxMSAASamples); - for (let i = 0; i < count; ++i) { - const texture = rtWrapper.textures[i]; - const gpuTextureWrapper = texture._hardwareTexture; - gpuTextureWrapper === null || gpuTextureWrapper === void 0 ? void 0 : gpuTextureWrapper.releaseMSAATexture(); - } - // Note that rtWrapper.textures can't have null textures, lastTextureIsDepthTexture can't be true if rtWrapper._depthStencilTexture is null - const lastTextureIsDepthTexture = rtWrapper._depthStencilTexture === rtWrapper.textures[count - 1]; - for (let i = 0; i < count; ++i) { - const texture = rtWrapper.textures[i]; - this._textureHelper.createMSAATexture(texture, samples, false, i === count - 1 && lastTextureIsDepthTexture ? 0 : i); - texture.samples = samples; - } - // 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 - // 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 - // because rtWrapper._depthStencilTexture is the same texture than the depth texture - if (rtWrapper._depthStencilTexture && !lastTextureIsDepthTexture) { - this._textureHelper.createMSAATexture(rtWrapper._depthStencilTexture, samples); - rtWrapper._depthStencilTexture.samples = samples; - } - return samples; -}; -webgpuEngine_WebGPUEngine.prototype.bindAttachments = function (attachments) { - if (attachments.length === 0 || !this._currentRenderTarget) { - return; - } - this._mrtAttachments = attachments; - if (this._currentRenderPass) { - // the render pass has already been created, we need to call setMRTAttachments to update the state of the attachments - this._cacheRenderPipeline.setMRTAttachments(attachments); - } - else { - // 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) - } -}; -webgpuEngine_WebGPUEngine.prototype.buildTextureLayout = function (textureStatus) { - const result = []; - for (let i = 0; i < textureStatus.length; i++) { - if (textureStatus[i]) { - result.push(i + 1); - } - else { - result.push(0); - } - } - return result; -}; -webgpuEngine_WebGPUEngine.prototype.restoreSingleAttachment = function () { - // 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 -}; -webgpuEngine_WebGPUEngine.prototype.restoreSingleAttachmentForRenderTarget = function () { - // 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 -}; -//# sourceMappingURL=engine.multiRender.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.query.js - - -webgpuEngine_WebGPUEngine.prototype.getGPUFrameTimeCounter = function () { - return this._timestampQuery.gpuFrameTimeCounter; -}; -webgpuEngine_WebGPUEngine.prototype.captureGPUFrameTime = function (value) { - this._timestampQuery.enable = value && !!this._caps.timerQuery; -}; -webgpuEngine_WebGPUEngine.prototype.createQuery = function () { - return this._occlusionQuery.createQuery(); -}; -webgpuEngine_WebGPUEngine.prototype.deleteQuery = function (query) { - this._occlusionQuery.deleteQuery(query); - return this; -}; -webgpuEngine_WebGPUEngine.prototype.isQueryResultAvailable = function (query) { - return this._occlusionQuery.isQueryResultAvailable(query); -}; -webgpuEngine_WebGPUEngine.prototype.getQueryResult = function (query) { - return this._occlusionQuery.getQueryResult(query); -}; -webgpuEngine_WebGPUEngine.prototype.beginOcclusionQuery = function (algorithmType, query) { - var _a; - if (this.compatibilityMode) { - if (this._occlusionQuery.canBeginQuery) { - (_a = this._currentRenderPass) === null || _a === void 0 ? void 0 : _a.beginOcclusionQuery(query); - return true; - } - } - else { - const renderPassIndex = this._getCurrentRenderPassIndex(); - const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget; - bundleList.addItem(new WebGPURenderItemBeginOcclusionQuery(query)); - return true; - } - return false; -}; -webgpuEngine_WebGPUEngine.prototype.endOcclusionQuery = function () { - var _a; - if (this.compatibilityMode) { - (_a = this._currentRenderPass) === null || _a === void 0 ? void 0 : _a.endOcclusionQuery(); - } - else { - const renderPassIndex = this._getCurrentRenderPassIndex(); - const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget; - bundleList.addItem(new WebGPURenderItemEndOcclusionQuery()); - } - return this; -}; -//# sourceMappingURL=engine.query.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.rawTexture.js - - - - -webgpuEngine_WebGPUEngine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) { - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Raw); - texture.baseWidth = width; - texture.baseHeight = height; - texture.width = width; - texture.height = height; - texture.format = format; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.invertY = invertY; - texture._compression = compression; - texture.type = type; - texture._useSRGBBuffer = useSRGBBuffer; - if (!this._doNotHandleContextLost) { - texture._bufferView = data; - } - this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, undefined, creationFlags); - this.updateRawTexture(texture, data, format, invertY, compression, type, useSRGBBuffer); - this._internalTexturesCache.push(texture); - return texture; -}; -webgpuEngine_WebGPUEngine.prototype.updateRawTexture = function (texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) { - if (!texture) { - return; - } - if (!this._doNotHandleContextLost) { - texture._bufferView = bufferView; - texture.invertY = invertY; - texture._compression = compression; - texture._useSRGBBuffer = useSRGBBuffer; - } - if (bufferView) { - const gpuTextureWrapper = texture._hardwareTexture; - const needConversion = format === 4; - if (needConversion) { - bufferView = engine_rawTexture_convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, type); - } - const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength); - this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0); - if (texture.generateMipMaps) { - this._generateMipmaps(texture, this._uploadEncoder); - } - } - texture.isReady = true; -}; -webgpuEngine_WebGPUEngine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) { - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.CubeRaw); - if (type === 1 && !this._caps.textureFloatLinearFiltering) { - generateMipMaps = false; - samplingMode = 1; - logger_Logger.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."); - } - else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { - generateMipMaps = false; - samplingMode = 1; - logger_Logger.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."); - } - else if (type === 1 && !this._caps.textureFloatRender) { - generateMipMaps = false; - logger_Logger.Warn("Render to float textures is not supported. Mipmap generation forced to false."); - } - else if (type === 2 && !this._caps.colorBufferFloat) { - generateMipMaps = false; - logger_Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false."); - } - texture.isCube = true; - texture.format = format === 4 ? 5 : format; - texture.type = type; - texture.generateMipMaps = generateMipMaps; - texture.width = size; - texture.height = size; - texture.samplingMode = samplingMode; - if (!this._doNotHandleContextLost) { - texture._bufferViewArray = data; - } - texture.invertY = invertY; - texture._compression = compression; - texture._cachedWrapU = 0; - texture._cachedWrapV = 0; - this._textureHelper.createGPUTextureForInternalTexture(texture); - if (data) { - this.updateRawCubeTexture(texture, data, format, type, invertY, compression); - } - texture.isReady = true; - return texture; -}; -webgpuEngine_WebGPUEngine.prototype.updateRawCubeTexture = function (texture, bufferView, format, type, invertY, compression = null) { - texture._bufferViewArray = bufferView; - texture.invertY = invertY; - texture._compression = compression; - const gpuTextureWrapper = texture._hardwareTexture; - const needConversion = format === 4; - const data = []; - for (let i = 0; i < bufferView.length; ++i) { - let faceData = bufferView[i]; - if (needConversion) { - faceData = engine_rawTexture_convertRGBtoRGBATextureData(bufferView[i], texture.width, texture.height, type); - } - data.push(new Uint8Array(faceData.buffer, faceData.byteOffset, faceData.byteLength)); - } - this._textureHelper.updateCubeTextures(data, gpuTextureWrapper.underlyingResource, texture.width, texture.height, gpuTextureWrapper.format, invertY, false, 0, 0); - if (texture.generateMipMaps) { - this._generateMipmaps(texture, this._uploadEncoder); - } - texture.isReady = true; -}; -webgpuEngine_WebGPUEngine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) { - const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null); - scene === null || scene === void 0 ? void 0 : scene.addPendingData(texture); - texture.url = url; - this._internalTexturesCache.push(texture); - const onerror = (request, exception) => { - scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture); - if (onError && request) { - onError(request.status + " " + request.statusText, exception); - } - }; - const internalCallback = (data) => { - const width = texture.width; - const faceDataArrays = callback(data); - if (!faceDataArrays) { - return; - } - const faces = [0, 2, 4, 1, 3, 5]; - if (mipmapGenerator) { - const needConversion = format === 4; - const mipData = mipmapGenerator(faceDataArrays); - const gpuTextureWrapper = texture._hardwareTexture; - const faces = [0, 1, 2, 3, 4, 5]; - for (let level = 0; level < mipData.length; level++) { - const mipSize = width >> level; - const allFaces = []; - for (let faceIndex = 0; faceIndex < 6; faceIndex++) { - let mipFaceData = mipData[level][faces[faceIndex]]; - if (needConversion) { - mipFaceData = engine_rawTexture_convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type); - } - allFaces.push(new Uint8Array(mipFaceData.buffer, mipFaceData.byteOffset, mipFaceData.byteLength)); - } - this._textureHelper.updateCubeTextures(allFaces, gpuTextureWrapper.underlyingResource, mipSize, mipSize, gpuTextureWrapper.format, invertY, false, 0, 0); - } - } - else { - const allFaces = []; - for (let faceIndex = 0; faceIndex < 6; faceIndex++) { - allFaces.push(faceDataArrays[faces[faceIndex]]); - } - this.updateRawCubeTexture(texture, allFaces, format, type, invertY); - } - texture.isReady = true; - scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture); - if (onLoad) { - onLoad(); - } - }; - this._loadFile(url, (data) => { - internalCallback(data); - }, undefined, scene === null || scene === void 0 ? void 0 : scene.offlineProvider, true, onerror); - return texture; -}; -webgpuEngine_WebGPUEngine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0, creationFlags = 0) { - const source = internalTexture_InternalTextureSource.Raw3D; - const texture = new internalTexture_InternalTexture(this, source); - texture.baseWidth = width; - texture.baseHeight = height; - texture.baseDepth = depth; - texture.width = width; - texture.height = height; - texture.depth = depth; - texture.format = format; - texture.type = textureType; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.is3D = true; - if (!this._doNotHandleContextLost) { - texture._bufferView = data; - } - this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, undefined, creationFlags); - this.updateRawTexture3D(texture, data, format, invertY, compression, textureType); - this._internalTexturesCache.push(texture); - return texture; -}; -webgpuEngine_WebGPUEngine.prototype.updateRawTexture3D = function (texture, bufferView, format, invertY, compression = null, textureType = 0) { - if (!this._doNotHandleContextLost) { - texture._bufferView = bufferView; - texture.format = format; - texture.invertY = invertY; - texture._compression = compression; - } - if (bufferView) { - const gpuTextureWrapper = texture._hardwareTexture; - const needConversion = format === 4; - if (needConversion) { - bufferView = engine_rawTexture_convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, textureType); - } - const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength); - this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0); - if (texture.generateMipMaps) { - this._generateMipmaps(texture, this._uploadEncoder); - } - } - texture.isReady = true; -}; -webgpuEngine_WebGPUEngine.prototype.createRawTexture2DArray = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0, creationFlags = 0) { - const source = internalTexture_InternalTextureSource.Raw2DArray; - const texture = new internalTexture_InternalTexture(this, source); - texture.baseWidth = width; - texture.baseHeight = height; - texture.baseDepth = depth; - texture.width = width; - texture.height = height; - texture.depth = depth; - texture.format = format; - texture.type = textureType; - texture.generateMipMaps = generateMipMaps; - texture.samplingMode = samplingMode; - texture.is2DArray = true; - if (!this._doNotHandleContextLost) { - texture._bufferView = data; - } - this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth, creationFlags); - this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType); - this._internalTexturesCache.push(texture); - return texture; -}; -webgpuEngine_WebGPUEngine.prototype.updateRawTexture2DArray = function (texture, bufferView, format, invertY, compression = null, textureType = 0) { - if (!this._doNotHandleContextLost) { - texture._bufferView = bufferView; - texture.format = format; - texture.invertY = invertY; - texture._compression = compression; - } - if (bufferView) { - const gpuTextureWrapper = texture._hardwareTexture; - const needConversion = format === 4; - if (needConversion) { - bufferView = engine_rawTexture_convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, textureType); - } - const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength); - this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0); - if (texture.generateMipMaps) { - this._generateMipmaps(texture, this._uploadEncoder); - } - } - texture.isReady = true; -}; -/** - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -function engine_rawTexture_convertRGBtoRGBATextureData(rgbData, width, height, textureType) { - // Create new RGBA data container. - let rgbaData; - let val1 = 1; - if (textureType === 1) { - rgbaData = new Float32Array(width * height * 4); - } - else if (textureType === 2) { - rgbaData = new Uint16Array(width * height * 4); - val1 = 15360; // 15360 is the encoding of 1 in half float - } - else if (textureType === 7) { - rgbaData = new Uint32Array(width * height * 4); - } - else { - rgbaData = new Uint8Array(width * height * 4); - } - // Convert each pixel. - for (let x = 0; x < width; x++) { - for (let y = 0; y < height; y++) { - const index = (y * width + x) * 3; - const newIndex = (y * width + x) * 4; - // Map Old Value to new value. - rgbaData[newIndex + 0] = rgbData[index + 0]; - rgbaData[newIndex + 1] = rgbData[index + 1]; - rgbaData[newIndex + 2] = rgbData[index + 2]; - // Add fully opaque alpha channel. - rgbaData[newIndex + 3] = val1; - } - } - return rgbaData; -} -//# sourceMappingURL=engine.rawTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.readTexture.js - -webgpuEngine_WebGPUEngine.prototype._readTexturePixels = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) { - const gpuTextureWrapper = texture._hardwareTexture; - if (flushRenderer) { - this.flushFramebuffer(); - } - return this._textureHelper.readPixels(gpuTextureWrapper.underlyingResource, x, y, width, height, gpuTextureWrapper.format, faceIndex, level, buffer, noDataConversion); -}; -webgpuEngine_WebGPUEngine.prototype._readTexturePixelsSync = function () { - throw "_readTexturePixelsSync is unsupported in WebGPU!"; -}; -//# sourceMappingURL=engine.readTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/webgpuRenderTargetWrapper.js - -/** @internal */ -class WebGPURenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper { -} -//# sourceMappingURL=webgpuRenderTargetWrapper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.renderTarget.js - - - - -webgpuEngine_WebGPUEngine.prototype._createHardwareRenderTargetWrapper = function (isMulti, isCube, size) { - const rtWrapper = new WebGPURenderTargetWrapper(isMulti, isCube, size, this); - this._renderTargetWrapperCache.push(rtWrapper); - return rtWrapper; -}; -webgpuEngine_WebGPUEngine.prototype.createRenderTargetTexture = function (size, options) { - var _a, _b; - const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size); - const fullOptions = {}; - if (options !== undefined && typeof options === "object") { - fullOptions.generateMipMaps = options.generateMipMaps; - fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; - fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer; - fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode; - fullOptions.creationFlags = (_a = options.creationFlags) !== null && _a !== void 0 ? _a : 0; - fullOptions.noColorAttachment = !!options.noColorAttachment; - fullOptions.samples = options.samples; - fullOptions.label = options.label; - } - else { - fullOptions.generateMipMaps = options; - fullOptions.generateDepthBuffer = true; - fullOptions.generateStencilBuffer = false; - fullOptions.samplingMode = 3; - fullOptions.creationFlags = 0; - fullOptions.noColorAttachment = false; - } - const texture = fullOptions.noColorAttachment ? null : this._createInternalTexture(size, options, true, internalTexture_InternalTextureSource.RenderTarget); - rtWrapper._samples = (_b = fullOptions.samples) !== null && _b !== void 0 ? _b : 1; - rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer; - rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false; - rtWrapper.setTextures(texture); - if (rtWrapper._generateDepthBuffer || rtWrapper._generateStencilBuffer) { - rtWrapper.createDepthStencilTexture(0, this._caps.textureFloatLinearFiltering && - (fullOptions.samplingMode === undefined || - fullOptions.samplingMode === 2 || - fullOptions.samplingMode === 2 || - fullOptions.samplingMode === 3 || - fullOptions.samplingMode === 3 || - fullOptions.samplingMode === 5 || - fullOptions.samplingMode === 6 || - fullOptions.samplingMode === 7 || - fullOptions.samplingMode === 11), rtWrapper._generateStencilBuffer, rtWrapper.samples, fullOptions.generateStencilBuffer ? 13 : 14, fullOptions.label ? fullOptions.label + "-DepthStencil" : undefined); - } - if (texture) { - if (options !== undefined && typeof options === "object" && options.createMipMaps && !fullOptions.generateMipMaps) { - texture.generateMipMaps = true; - } - this._textureHelper.createGPUTextureForInternalTexture(texture, undefined, undefined, undefined, fullOptions.creationFlags); - if (options !== undefined && typeof options === "object" && options.createMipMaps && !fullOptions.generateMipMaps) { - texture.generateMipMaps = false; - } - } - return rtWrapper; -}; -webgpuEngine_WebGPUEngine.prototype._createDepthStencilTexture = function (size, options) { - const internalTexture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.DepthStencil); - internalTexture.label = options.label; - const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false, samples: 1, depthTextureFormat: options.generateStencil ? 13 : 14 }, options); - internalTexture.format = internalOptions.depthTextureFormat; - this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples); - this._textureHelper.createGPUTextureForInternalTexture(internalTexture); - this._internalTexturesCache.push(internalTexture); - return internalTexture; -}; -webgpuEngine_WebGPUEngine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction, samples = 1) { - const width = size.width || size; - const height = size.height || size; - const layers = size.layers || 0; - internalTexture.baseWidth = width; - internalTexture.baseHeight = height; - internalTexture.width = width; - internalTexture.height = height; - internalTexture.is2DArray = layers > 0; - internalTexture.depth = layers; - internalTexture.isReady = true; - internalTexture.samples = samples; - internalTexture.generateMipMaps = false; - internalTexture.samplingMode = bilinearFiltering ? 2 : 1; - internalTexture.type = 1; - internalTexture._comparisonFunction = comparisonFunction; - internalTexture._cachedWrapU = 0; - internalTexture._cachedWrapV = 0; -}; -webgpuEngine_WebGPUEngine.prototype.updateRenderTargetTextureSampleCount = function (rtWrapper, samples) { - if (!rtWrapper || !rtWrapper.texture || rtWrapper.samples === samples) { - return samples; - } - samples = Math.min(samples, this.getCaps().maxMSAASamples); - this._textureHelper.createMSAATexture(rtWrapper.texture, samples); - if (rtWrapper._depthStencilTexture) { - this._textureHelper.createMSAATexture(rtWrapper._depthStencilTexture, samples); - rtWrapper._depthStencilTexture.samples = samples; - } - rtWrapper._samples = samples; - rtWrapper.texture.samples = samples; - return samples; -}; -//# sourceMappingURL=engine.renderTarget.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.renderTargetCube.js - - - -webgpuEngine_WebGPUEngine.prototype.createRenderTargetCubeTexture = function (size, options) { - const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size); - const fullOptions = Object.assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: 0, samplingMode: 3, format: 5, samples: 1 }, options); - fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer; - rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer; - rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer; - const texture = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.RenderTarget); - texture.width = size; - texture.height = size; - texture.depth = 0; - texture.isReady = true; - texture.isCube = true; - texture.samples = fullOptions.samples; - texture.generateMipMaps = fullOptions.generateMipMaps; - texture.samplingMode = fullOptions.samplingMode; - texture.type = fullOptions.type; - texture.format = fullOptions.format; - this._internalTexturesCache.push(texture); - rtWrapper.setTextures(texture); - if (rtWrapper._generateDepthBuffer || rtWrapper._generateStencilBuffer) { - rtWrapper.createDepthStencilTexture(0, fullOptions.samplingMode === undefined || - fullOptions.samplingMode === 2 || - fullOptions.samplingMode === 2 || - fullOptions.samplingMode === 3 || - fullOptions.samplingMode === 3 || - fullOptions.samplingMode === 5 || - fullOptions.samplingMode === 6 || - fullOptions.samplingMode === 7 || - fullOptions.samplingMode === 11, rtWrapper._generateStencilBuffer, rtWrapper.samples); - } - if (options && options.createMipMaps && !fullOptions.generateMipMaps) { - texture.generateMipMaps = true; - } - this._textureHelper.createGPUTextureForInternalTexture(texture); - if (options && options.createMipMaps && !fullOptions.generateMipMaps) { - texture.generateMipMaps = false; - } - return rtWrapper; -}; -//# sourceMappingURL=engine.renderTargetCube.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.textureSampler.js - - -effect_Effect.prototype.setTextureSampler = function (name, sampler) { - this._engine.setTextureSampler(name, sampler); -}; -webgpuEngine_WebGPUEngine.prototype.setTextureSampler = function (name, sampler) { - var _a; - (_a = this._currentMaterialContext) === null || _a === void 0 ? void 0 : _a.setSampler(name, sampler); -}; -//# sourceMappingURL=engine.textureSampler.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.storageBuffer.js - - - - -effect_Effect.prototype.setStorageBuffer = function (name, buffer) { - this._engine.setStorageBuffer(name, buffer); -}; -webgpuEngine_WebGPUEngine.prototype.createStorageBuffer = function (data, creationFlags) { - return this._createBuffer(data, creationFlags | 32); -}; -webgpuEngine_WebGPUEngine.prototype.updateStorageBuffer = function (buffer, data, byteOffset, byteLength) { - const dataBuffer = buffer; - if (byteOffset === undefined) { - byteOffset = 0; - } - let view; - if (byteLength === undefined) { - if (data instanceof Array) { - view = new Float32Array(data); - } - else if (data instanceof ArrayBuffer) { - view = new Uint8Array(data); - } - else { - view = data; - } - byteLength = view.byteLength; - } - else { - if (data instanceof Array) { - view = new Float32Array(data); - } - else if (data instanceof ArrayBuffer) { - view = new Uint8Array(data); - } - else { - view = data; - } - } - this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength); -}; -webgpuEngine_WebGPUEngine.prototype.readFromStorageBuffer = function (storageBuffer, offset, size, buffer) { - size = size || storageBuffer.capacity; - const gpuBuffer = this._bufferManager.createRawBuffer(size, BufferUsage.MapRead | BufferUsage.CopyDst); - this._renderTargetEncoder.copyBufferToBuffer(storageBuffer.underlyingResource, offset !== null && offset !== void 0 ? offset : 0, gpuBuffer, 0, size); - return new Promise((resolve, reject) => { - // we are using onEndFrameObservable because we need to map the gpuBuffer AFTER the command buffers - // have been submitted, else we get the error: "Buffer used in a submit while mapped" - this.onEndFrameObservable.addOnce(() => { - gpuBuffer.mapAsync(MapMode.Read, 0, size).then(() => { - const copyArrayBuffer = gpuBuffer.getMappedRange(0, size); - let data = buffer; - if (data === undefined) { - data = new Uint8Array(size); - data.set(new Uint8Array(copyArrayBuffer)); - } - else { - const ctor = data.constructor; // we want to create result data with the same type as buffer (Uint8Array, Float32Array, ...) - data = new ctor(data.buffer); - data.set(new ctor(copyArrayBuffer)); - } - gpuBuffer.unmap(); - this._bufferManager.releaseBuffer(gpuBuffer); - resolve(data); - }, (reason) => reject(reason)); - }); - }); -}; -webgpuEngine_WebGPUEngine.prototype.setStorageBuffer = function (name, buffer) { - var _a, _b; - (_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); -}; -//# sourceMappingURL=engine.storageBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.uniformBuffer.js - - -webgpuEngine_WebGPUEngine.prototype.createUniformBuffer = function (elements) { - let view; - if (elements instanceof Array) { - view = new Float32Array(elements); - } - else { - view = elements; - } - const dataBuffer = this._bufferManager.createBuffer(view, BufferUsage.Uniform | BufferUsage.CopyDst); - return dataBuffer; -}; -webgpuEngine_WebGPUEngine.prototype.createDynamicUniformBuffer = function (elements) { - return this.createUniformBuffer(elements); -}; -webgpuEngine_WebGPUEngine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) { - if (offset === undefined) { - offset = 0; - } - const dataBuffer = uniformBuffer; - let view; - if (count === undefined) { - if (elements instanceof Float32Array) { - view = elements; - } - else { - view = new Float32Array(elements); - } - count = view.byteLength; - } - else { - if (elements instanceof Float32Array) { - view = elements; - } - else { - view = new Float32Array(elements); - } - } - this._bufferManager.setSubData(dataBuffer, offset, view, 0, count); -}; -webgpuEngine_WebGPUEngine.prototype.bindUniformBufferBase = function (buffer, location, name) { - this._currentDrawContext.setBuffer(name, buffer); -}; -webgpuEngine_WebGPUEngine.prototype.bindUniformBlock = function () { }; -//# sourceMappingURL=engine.uniformBuffer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.videoTexture.js - -function IsExternalTexture(texture) { - return texture && texture.underlyingResource !== undefined ? true : false; -} -webgpuEngine_WebGPUEngine.prototype.updateVideoTexture = function (texture, video, invertY) { - var _a; - if (!texture || texture._isDisabled) { - return; - } - if (this._videoTextureSupported === undefined) { - this._videoTextureSupported = true; - } - let gpuTextureWrapper = texture._hardwareTexture; - if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) { - gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture); - } - if (IsExternalTexture(video)) { - this._textureHelper.copyVideoToTexture(video, texture, gpuTextureWrapper.format, !invertY); - if (texture.generateMipMaps) { - this._generateMipmaps(texture, this._uploadEncoder); - } - texture.isReady = true; - } - else if (video) { - this.createImageBitmap(video) - .then((bitmap) => { - this._textureHelper.updateTexture(bitmap, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, !invertY, false, 0, 0); - if (texture.generateMipMaps) { - this._generateMipmaps(texture, this._uploadEncoder); - } - texture.isReady = true; - }) - .catch(() => { - // Sometimes createImageBitmap(video) fails with "Failed to execute 'createImageBitmap' on 'Window': The provided element's player has no current data." - // Just keep going on - texture.isReady = true; - }); - } -}; -//# sourceMappingURL=engine.videoTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/index.js - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/IPipelineContext.js - -//# sourceMappingURL=IPipelineContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/ICanvas.js - -//# sourceMappingURL=ICanvas.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/engineFeatures.js - -//# sourceMappingURL=engineFeatures.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/engineFactory.js - - - -/** - * Helper class to create the best engine depending on the current hardware - */ -class EngineFactory { - /** - * Creates an engine based on the capabilities of the underlying hardware - * @param canvas Defines the canvas to use to display the result - * @param options Defines the options passed to the engine to create the context dependencies - * @returns a promise that resolves with the created engine - */ - static CreateAsync(canvas, options) { - return WebGPUEngine.IsSupportedAsync.then((supported) => { - if (supported) { - return WebGPUEngine.CreateAsync(canvas, options); - } - else if (Engine.IsSupported) { - return new Promise((resolve) => { - resolve(new Engine(canvas, undefined, options)); - }); - } - return new Promise((resolve) => { - resolve(new NullEngine(options)); - }); - }); - } -} -//# sourceMappingURL=engineFactory.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/IMaterialContext.js - -//# sourceMappingURL=IMaterialContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/IDrawContext.js - -//# sourceMappingURL=IDrawContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/Processors/iShaderProcessor.js - -//# sourceMappingURL=iShaderProcessor.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Engines/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Events/clipboardEvents.js -/** - * Gather the list of clipboard event types as constants. - */ -class ClipboardEventTypes { -} -/** - * The clipboard event is fired when a copy command is active (pressed). - */ -ClipboardEventTypes.COPY = 0x01; // -/** - * The clipboard event is fired when a cut command is active (pressed). - */ -ClipboardEventTypes.CUT = 0x02; -/** - * The clipboard event is fired when a paste command is active (pressed). - */ -ClipboardEventTypes.PASTE = 0x03; -/** - * This class is used to store clipboard related info for the onClipboardObservable event. - */ -class ClipboardInfo { - /** - *Creates an instance of ClipboardInfo. - * @param type Defines the type of event (BABYLON.ClipboardEventTypes) - * @param event Defines the related dom event - */ - constructor( - /** - * Defines the type of event (BABYLON.ClipboardEventTypes) - */ - type, - /** - * Defines the related dom event - */ - event) { - this.type = type; - this.event = event; - } - /** - * Get the clipboard event's type from the keycode. - * @param keyCode Defines the keyCode for the current keyboard event. - * @returns {number} - */ - static GetTypeFromCharacter(keyCode) { - const charCode = keyCode; - //TODO: add codes for extended ASCII - switch (charCode) { - case 67: - return ClipboardEventTypes.COPY; - case 86: - return ClipboardEventTypes.PASTE; - case 88: - return ClipboardEventTypes.CUT; - default: - return -1; - } - } -} -//# sourceMappingURL=clipboardEvents.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Events/index.js - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/Controllers/daydreamController.js - - - - -/** - * Google Daydream controller - */ -class DaydreamController extends WebVRController { - /** - * Creates a new DaydreamController from a gamepad - * @param vrGamepad the gamepad that the controller should be created from - */ - constructor(vrGamepad) { - super(vrGamepad); - this.controllerType = PoseEnabledControllerType.DAYDREAM; - } - /** - * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. - * @param scene scene in which to add meshes - * @param meshLoaded optional callback function that will be called if the mesh loads successfully. - */ - initControllerMesh(scene, meshLoaded) { - sceneLoader_SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, (newMeshes) => { - this._defaultModel = newMeshes[1]; - this.attachToMesh(this._defaultModel); - if (meshLoaded) { - meshLoaded(this._defaultModel); - } - }); - } - /** - * Called once for each button that changed state since the last frame - * @param buttonIdx Which button index changed - * @param state New state of the button - */ - _handleButtonChange(buttonIdx, state) { - // Daydream controller only has 1 GamepadButton (on the trackpad). - if (buttonIdx === 0) { - const observable = this.onTriggerStateChangedObservable; - if (observable) { - observable.notifyObservers(state); - } - } - else { - // If the app or home buttons are ever made available - logger_Logger.Warn(`Unrecognized Daydream button index: ${buttonIdx}`); - } - } -} -/** - * Base Url for the controller model. - */ -DaydreamController.MODEL_BASE_URL = "https://controllers.babylonjs.com/generic/"; -/** - * File name for the controller model. - */ -DaydreamController.MODEL_FILENAME = "generic.babylon"; -/** - * Gamepad Id prefix used to identify Daydream Controller. - */ -DaydreamController.GAMEPAD_ID_PREFIX = "Daydream"; // id is 'Daydream Controller' -PoseEnabledControllerHelper._ControllerFactories.push({ - canCreate: (gamepadInfo) => { - return gamepadInfo.id.indexOf(DaydreamController.GAMEPAD_ID_PREFIX) === 0; - }, - create: (gamepadInfo) => { - return new DaydreamController(gamepadInfo); - }, -}); -//# sourceMappingURL=daydreamController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/Controllers/gearVRController.js - - - - - -/** - * Gear VR Controller - */ -class GearVRController extends WebVRController { - /** - * Creates a new GearVRController from a gamepad - * @param vrGamepad the gamepad that the controller should be created from - */ - constructor(vrGamepad) { - super(vrGamepad); - this._buttonIndexToObservableNameMap = [ - "onPadStateChangedObservable", - "onTriggerStateChangedObservable", // Trigger - ]; - this.controllerType = PoseEnabledControllerType.GEAR_VR; - // Initial starting position defaults to where hand would be (incase of only 3dof controller) - this._calculatedPosition = new math_vector_Vector3(this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25); - this._disableTrackPosition(this._calculatedPosition); - } - /** - * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. - * @param scene scene in which to add meshes - * @param meshLoaded optional callback function that will be called if the mesh loads successfully. - */ - initControllerMesh(scene, meshLoaded) { - sceneLoader_SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, (newMeshes) => { - // Offset the controller so it will rotate around the users wrist - const mesh = new mesh_Mesh("", scene); - newMeshes[1].parent = mesh; - newMeshes[1].position.z = -0.15; - this._defaultModel = mesh; - this.attachToMesh(this._defaultModel); - if (meshLoaded) { - meshLoaded(this._defaultModel); - } - }); - } - /** - * Called once for each button that changed state since the last frame - * @param buttonIdx Which button index changed - * @param state New state of the button - */ - _handleButtonChange(buttonIdx, state) { - if (buttonIdx < this._buttonIndexToObservableNameMap.length) { - const observableName = this._buttonIndexToObservableNameMap[buttonIdx]; - // Only emit events for buttons that we know how to map from index to observable - const observable = this[observableName]; - if (observable) { - observable.notifyObservers(state); - } - } - } -} -/** - * Base Url for the controller model. - */ -GearVRController.MODEL_BASE_URL = "https://controllers.babylonjs.com/generic/"; -/** - * File name for the controller model. - */ -GearVRController.MODEL_FILENAME = "generic.babylon"; -/** - * Gamepad Id prefix used to identify this controller. - */ -GearVRController.GAMEPAD_ID_PREFIX = "Gear VR"; // id is 'Gear VR Controller' -PoseEnabledControllerHelper._ControllerFactories.push({ - canCreate: (gamepadInfo) => { - return gamepadInfo.id.indexOf(GearVRController.GAMEPAD_ID_PREFIX) === 0 || gamepadInfo.id.indexOf("Oculus Go") !== -1 || gamepadInfo.id.indexOf("Vive Focus") !== -1; - }, - create: (gamepadInfo) => { - return new GearVRController(gamepadInfo); - }, -}); -//# sourceMappingURL=gearVRController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/Controllers/genericController.js - - - -/** - * Generic Controller - */ -class GenericController extends WebVRController { - /** - * Creates a new GenericController from a gamepad - * @param vrGamepad the gamepad that the controller should be created from - */ - constructor(vrGamepad) { - super(vrGamepad); - } - /** - * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. - * @param scene scene in which to add meshes - * @param meshLoaded optional callback function that will be called if the mesh loads successfully. - */ - initControllerMesh(scene, meshLoaded) { - sceneLoader_SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, (newMeshes) => { - this._defaultModel = newMeshes[1]; - this.attachToMesh(this._defaultModel); - if (meshLoaded) { - meshLoaded(this._defaultModel); - } - }); - } - /** - * Called once for each button that changed state since the last frame - * @param buttonIdx Which button index changed - * @param state New state of the button - */ - _handleButtonChange(buttonIdx, state) { - console.log("Button id: " + buttonIdx + "state: "); - console.dir(state); - } -} -/** - * Base Url for the controller model. - */ -GenericController.MODEL_BASE_URL = "https://controllers.babylonjs.com/generic/"; -/** - * File name for the controller model. - */ -GenericController.MODEL_FILENAME = "generic.babylon"; -PoseEnabledControllerHelper._DefaultControllerFactory = (gamepadInfo) => new GenericController(gamepadInfo); -//# sourceMappingURL=genericController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/Controllers/oculusTouchController.js - - - - - -/** - * Oculus Touch Controller - */ -class OculusTouchController extends WebVRController { - /** - * Creates a new OculusTouchController from a gamepad - * @param vrGamepad the gamepad that the controller should be created from - */ - constructor(vrGamepad) { - super(vrGamepad); - /** - * Fired when the secondary trigger on this controller is modified - */ - this.onSecondaryTriggerStateChangedObservable = new observable_Observable(); - /** - * Fired when the thumb rest on this controller is modified - */ - this.onThumbRestChangedObservable = new observable_Observable(); - this.controllerType = PoseEnabledControllerType.OCULUS; - } - /** - * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. - * @param scene scene in which to add meshes - * @param meshLoaded optional callback function that will be called if the mesh loads successfully. - */ - initControllerMesh(scene, meshLoaded) { - let meshName; - // Hand - if (this.hand === "left") { - meshName = OculusTouchController.MODEL_LEFT_FILENAME; - } - else { - // Right is the default if no hand is specified - meshName = OculusTouchController.MODEL_RIGHT_FILENAME; - } - sceneLoader_SceneLoader.ImportMesh("", OculusTouchController._IsQuest ? OculusTouchController.QUEST_MODEL_BASE_URL : OculusTouchController.MODEL_BASE_URL, meshName, scene, (newMeshes) => { - /* - Parent Mesh name: oculus_touch_left - - body - - trigger - - thumbstick - - grip - - button_y - - button_x - - button_enter - */ - this._defaultModel = OculusTouchController._IsQuest ? newMeshes[0] : newMeshes[1]; - this.attachToMesh(this._defaultModel); - if (meshLoaded) { - meshLoaded(this._defaultModel); - } - }); - } - /** - * Fired when the A button on this controller is modified - */ - get onAButtonStateChangedObservable() { - if (this.hand === "right") { - return this.onMainButtonStateChangedObservable; - } - else { - throw new Error("No A button on left hand"); - } - } - /** - * Fired when the B button on this controller is modified - */ - get onBButtonStateChangedObservable() { - if (this.hand === "right") { - return this.onSecondaryButtonStateChangedObservable; - } - else { - throw new Error("No B button on left hand"); - } - } - /** - * Fired when the X button on this controller is modified - */ - get onXButtonStateChangedObservable() { - if (this.hand === "left") { - return this.onMainButtonStateChangedObservable; - } - else { - throw new Error("No X button on right hand"); - } - } - /** - * Fired when the Y button on this controller is modified - */ - get onYButtonStateChangedObservable() { - if (this.hand === "left") { - return this.onSecondaryButtonStateChangedObservable; - } - else { - throw new Error("No Y button on right hand"); - } - } - /** - * Called once for each button that changed state since the last frame - * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick - * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1) - * 2) secondary trigger (same) - * 3) A (right) X (left), touch, pressed = value - * 4) B / Y - * 5) thumb rest - * @param buttonIdx Which button index changed - * @param state New state of the button - */ - _handleButtonChange(buttonIdx, state) { - const notifyObject = state; //{ state: state, changes: changes }; - const triggerDirection = this.hand === "right" ? -1 : 1; - switch (buttonIdx) { - case 0: - this.onPadStateChangedObservable.notifyObservers(notifyObject); - return; - case 1: // index trigger - if (!OculusTouchController._IsQuest && this._defaultModel) { - this._defaultModel.getChildren()[3].rotation.x = -notifyObject.value * 0.2; - this._defaultModel.getChildren()[3].position.y = -notifyObject.value * 0.005; - this._defaultModel.getChildren()[3].position.z = -notifyObject.value * 0.005; - } - this.onTriggerStateChangedObservable.notifyObservers(notifyObject); - return; - case 2: // secondary trigger - if (!OculusTouchController._IsQuest && this._defaultModel) { - this._defaultModel.getChildren()[4].position.x = triggerDirection * notifyObject.value * 0.0035; - } - this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject); - return; - case 3: - if (!OculusTouchController._IsQuest && this._defaultModel) { - if (notifyObject.pressed) { - this._defaultModel.getChildren()[1].position.y = -0.001; - } - else { - this._defaultModel.getChildren()[1].position.y = 0; - } - } - this.onMainButtonStateChangedObservable.notifyObservers(notifyObject); - return; - case 4: - if (!OculusTouchController._IsQuest && this._defaultModel) { - if (notifyObject.pressed) { - this._defaultModel.getChildren()[2].position.y = -0.001; - } - else { - this._defaultModel.getChildren()[2].position.y = 0; - } - } - this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject); - return; - case 5: - this.onThumbRestChangedObservable.notifyObservers(notifyObject); - return; - } - } -} -/** - * Base Url for the controller model. - */ -OculusTouchController.MODEL_BASE_URL = "https://controllers.babylonjs.com/oculus/"; -/** - * File name for the left controller model. - */ -OculusTouchController.MODEL_LEFT_FILENAME = "left.babylon"; -/** - * File name for the right controller model. - */ -OculusTouchController.MODEL_RIGHT_FILENAME = "right.babylon"; -/** - * Base Url for the Quest controller model. - */ -OculusTouchController.QUEST_MODEL_BASE_URL = "https://controllers.babylonjs.com/oculusQuest/"; -/** - * @internal - * If the controllers are running on a device that needs the updated Quest controller models - */ -OculusTouchController._IsQuest = false; -PoseEnabledControllerHelper._ControllerFactories.push({ - canCreate: (gamepadInfo) => { - // If the headset reports being an Oculus Quest, use the Quest controller models - if (engineStore_EngineStore.LastCreatedEngine && engineStore_EngineStore.LastCreatedEngine._vrDisplay && engineStore_EngineStore.LastCreatedEngine._vrDisplay.displayName === "Oculus Quest") { - OculusTouchController._IsQuest = true; - } - return gamepadInfo.id.indexOf("Oculus Touch") !== -1; - }, - create: (gamepadInfo) => { - return new OculusTouchController(gamepadInfo); - }, -}); -//# sourceMappingURL=oculusTouchController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/Controllers/viveController.js - - - -/** - * Vive Controller - */ -class ViveController extends WebVRController { - /** - * Creates a new ViveController from a gamepad - * @param vrGamepad the gamepad that the controller should be created from - */ - constructor(vrGamepad) { - super(vrGamepad); - this.controllerType = PoseEnabledControllerType.VIVE; - this._invertLeftStickY = true; - } - /** - * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. - * @param scene scene in which to add meshes - * @param meshLoaded optional callback function that will be called if the mesh loads successfully. - */ - initControllerMesh(scene, meshLoaded) { - sceneLoader_SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, (newMeshes) => { - /* - Parent Mesh name: ViveWand - - body - - r_gripper - - l_gripper - - menu_button - - system_button - - trackpad - - trigger - - LED - */ - this._defaultModel = newMeshes[1]; - this.attachToMesh(this._defaultModel); - if (meshLoaded) { - meshLoaded(this._defaultModel); - } - }); - } - /** - * Fired when the left button on this controller is modified - */ - get onLeftButtonStateChangedObservable() { - return this.onMainButtonStateChangedObservable; - } - /** - * Fired when the right button on this controller is modified - */ - get onRightButtonStateChangedObservable() { - return this.onMainButtonStateChangedObservable; - } - /** - * Fired when the menu button on this controller is modified - */ - get onMenuButtonStateChangedObservable() { - return this.onSecondaryButtonStateChangedObservable; - } - /** - * Called once for each button that changed state since the last frame - * Vive mapping: - * 0: touchpad - * 1: trigger - * 2: left AND right buttons - * 3: menu button - * @param buttonIdx Which button index changed - * @param state New state of the button - */ - _handleButtonChange(buttonIdx, state) { - const notifyObject = state; //{ state: state, changes: changes }; - switch (buttonIdx) { - case 0: - this.onPadStateChangedObservable.notifyObservers(notifyObject); - return; - case 1: // index trigger - if (this._defaultModel) { - this._defaultModel.getChildren()[6].rotation.x = -notifyObject.value * 0.15; - } - this.onTriggerStateChangedObservable.notifyObservers(notifyObject); - return; - case 2: // left AND right button - this.onMainButtonStateChangedObservable.notifyObservers(notifyObject); - return; - case 3: - if (this._defaultModel) { - if (notifyObject.pressed) { - this._defaultModel.getChildren()[2].position.y = -0.001; - } - else { - this._defaultModel.getChildren()[2].position.y = 0; - } - } - this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject); - return; - } - } -} -/** - * Base Url for the controller model. - */ -ViveController.MODEL_BASE_URL = "https://controllers.babylonjs.com/vive/"; -/** - * File name for the controller model. - */ -ViveController.MODEL_FILENAME = "wand.babylon"; -PoseEnabledControllerHelper._ControllerFactories.push({ - canCreate: (gamepadInfo) => { - return gamepadInfo.id.toLowerCase().indexOf("openvr") !== -1; - }, - create: (gamepadInfo) => { - return new ViveController(gamepadInfo); - }, -}); -//# sourceMappingURL=viveController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/Controllers/windowsMotionController.js - - - - - - - - - -/** - * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh - */ -class LoadedMeshInfo { - constructor() { - /** - * Map of the button meshes contained in the controller - */ - this.buttonMeshes = {}; - /** - * Map of the axis meshes contained in the controller - */ - this.axisMeshes = {}; - } -} -/** - * Defines the WindowsMotionController object that the state of the windows motion controller - */ -class WindowsMotionController extends WebVRController { - /** - * Creates a new WindowsMotionController from a gamepad - * @param vrGamepad the gamepad that the controller should be created from - */ - constructor(vrGamepad) { - super(vrGamepad); - this._mapping = { - // Semantic button names - buttons: ["thumbstick", "trigger", "grip", "menu", "trackpad"], - // trigger, grip, trackpad, thumbstick, menu - // A mapping of the button name to glTF model node name - // that should be transformed by button value. - buttonMeshNames: { - trigger: "SELECT", - menu: "MENU", - grip: "GRASP", - thumbstick: "THUMBSTICK_PRESS", - trackpad: "TOUCHPAD_PRESS", - }, - // This mapping is used to translate from the Motion Controller to Babylon semantics - buttonObservableNames: { - trigger: "onTriggerStateChangedObservable", - menu: "onSecondaryButtonStateChangedObservable", - grip: "onMainButtonStateChangedObservable", - thumbstick: "onPadStateChangedObservable", - trackpad: "onTrackpadChangedObservable", - }, - // A mapping of the axis name to glTF model node name - // that should be transformed by axis value. - // This array mirrors the browserGamepad.axes array, such that - // the mesh corresponding to axis 0 is in this array index 0. - axisMeshNames: ["THUMBSTICK_X", "THUMBSTICK_Y", "TOUCHPAD_TOUCH_X", "TOUCHPAD_TOUCH_Y"], - // upside down in webxr - pointingPoseMeshName: poseEnabledController_PoseEnabledController.POINTING_POSE, - }; - /** - * Fired when the trackpad on this controller is clicked - */ - this.onTrackpadChangedObservable = new observable_Observable(); - /** - * Fired when the trackpad on this controller is modified - */ - this.onTrackpadValuesChangedObservable = new observable_Observable(); - /** - * The current x and y values of this controller's trackpad - */ - this.trackpad = { x: 0, y: 0 }; - this.controllerType = PoseEnabledControllerType.WINDOWS; - this._loadedMeshInfo = null; - } - /** - * Fired when the trigger on this controller is modified - */ - get onTriggerButtonStateChangedObservable() { - return this.onTriggerStateChangedObservable; - } - /** - * Fired when the menu button on this controller is modified - */ - get onMenuButtonStateChangedObservable() { - return this.onSecondaryButtonStateChangedObservable; - } - /** - * Fired when the grip button on this controller is modified - */ - get onGripButtonStateChangedObservable() { - return this.onMainButtonStateChangedObservable; - } - /** - * Fired when the thumbstick button on this controller is modified - */ - get onThumbstickButtonStateChangedObservable() { - return this.onPadStateChangedObservable; - } - /** - * Fired when the touchpad button on this controller is modified - */ - get onTouchpadButtonStateChangedObservable() { - return this.onTrackpadChangedObservable; - } - /** - * Fired when the touchpad values on this controller are modified - */ - get onTouchpadValuesChangedObservable() { - return this.onTrackpadValuesChangedObservable; - } - _updateTrackpad() { - if (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); - } - } - /** - * Called once per frame by the engine. - */ - update() { - super.update(); - if (this.browserGamepad.axes) { - this._updateTrackpad(); - // Only need to animate axes if there is a loaded mesh - if (this._loadedMeshInfo) { - for (let axis = 0; axis < this._mapping.axisMeshNames.length; axis++) { - this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]); - } - } - } - } - /** - * Called once for each button that changed state since the last frame - * @param buttonIdx Which button index changed - * @param state New state of the button - */ - _handleButtonChange(buttonIdx, state) { - const buttonName = this._mapping.buttons[buttonIdx]; - if (!buttonName) { - return; - } - // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames - this._updateTrackpad(); - // Only emit events for buttons that we know how to map from index to name - const observable = this[this._mapping.buttonObservableNames[buttonName]]; - if (observable) { - observable.notifyObservers(state); - } - this._lerpButtonTransform(buttonName, state.value); - } - /** - * Moves the buttons on the controller mesh based on their current state - * @param buttonName the name of the button to move - * @param buttonValue the value of the button which determines the buttons new position - */ - _lerpButtonTransform(buttonName, buttonValue) { - // If there is no loaded mesh, there is nothing to transform. - if (!this._loadedMeshInfo) { - return; - } - const meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName]; - if (!meshInfo || !meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) { - return; - } - math_vector_Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion); - math_vector_Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position); - } - /** - * Moves the axis on the controller mesh based on its current state - * @param axis the index of the axis - * @param axisValue the value of the axis which determines the meshes new position - * @internal - */ - _lerpAxisTransform(axis, axisValue) { - if (!this._loadedMeshInfo) { - return; - } - const meshInfo = this._loadedMeshInfo.axisMeshes[axis]; - if (!meshInfo) { - return; - } - if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) { - return; - } - // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1) - const lerpValue = axisValue * 0.5 + 0.5; - math_vector_Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion); - math_vector_Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position); - } - /** - * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. - * @param scene scene in which to add meshes - * @param meshLoaded optional callback function that will be called if the mesh loads successfully. - * @param forceDefault - */ - initControllerMesh(scene, meshLoaded, forceDefault = false) { - let path; - let filename; - // Checking if GLB loader is present - if (sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb")) { - // Determine the device specific folder based on the ID suffix - let device = "default"; - if (this.id && !forceDefault) { - const match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN); - device = (match && match[0]) || device; - } - // Hand - if (this.hand === "left") { - filename = WindowsMotionController.MODEL_LEFT_FILENAME; - } - else { - // Right is the default if no hand is specified - filename = WindowsMotionController.MODEL_RIGHT_FILENAME; - } - path = WindowsMotionController.MODEL_BASE_URL + device + "/"; - } - else { - logger_Logger.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models"); - path = GenericController.MODEL_BASE_URL; - filename = GenericController.MODEL_FILENAME; - } - sceneLoader_SceneLoader.ImportMesh("", path, filename, scene, (meshes) => { - // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format. - this._loadedMeshInfo = this._processModel(scene, meshes); - if (!this._loadedMeshInfo) { - return; - } - this._defaultModel = this._loadedMeshInfo.rootNode; - this.attachToMesh(this._defaultModel); - if (meshLoaded) { - meshLoaded(this._defaultModel); - } - }, null, (scene, message) => { - logger_Logger.Log(message); - logger_Logger.Warn("Failed to retrieve controller model from the remote server: " + path + filename); - if (!forceDefault) { - this.initControllerMesh(scene, meshLoaded, true); - } - }); - } - /** - * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that - * can be transformed by button presses and axes values, based on this._mapping. - * - * @param scene scene in which the meshes exist - * @param meshes list of meshes that make up the controller model to process - * @returns structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed. - */ - _processModel(scene, meshes) { - let loadedMeshInfo = null; - // Create a new mesh to contain the glTF hierarchy - const parentMesh = new mesh_Mesh(this.id + " " + this.hand, scene); - // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh' - let childMesh = null; - for (let i = 0; i < meshes.length; i++) { - const mesh = meshes[i]; - if (!mesh.parent) { - // Exclude controller meshes from picking results - mesh.isPickable = false; - // Handle root node, attach to the new parentMesh - childMesh = mesh; - break; - } - } - if (childMesh) { - childMesh.setParent(parentMesh); - // Create our mesh info. Note that this method will always return non-null. - loadedMeshInfo = this._createMeshInfo(parentMesh); - } - else { - logger_Logger.Warn("Could not find root node in model file."); - } - return loadedMeshInfo; - } - _createMeshInfo(rootNode) { - const loadedMeshInfo = new LoadedMeshInfo(); - let i; - loadedMeshInfo.rootNode = rootNode; - // Reset the caches - loadedMeshInfo.buttonMeshes = {}; - loadedMeshInfo.axisMeshes = {}; - // Button Meshes - for (i = 0; i < this._mapping.buttons.length; i++) { - const buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]]; - if (!buttonMeshName) { - logger_Logger.Log("Skipping unknown button at index: " + i + " with mapped name: " + this._mapping.buttons[i]); - continue; - } - const buttonMesh = getChildByName(rootNode, buttonMeshName); - if (!buttonMesh) { - logger_Logger.Warn("Missing button mesh with name: " + buttonMeshName); - continue; - } - const buttonMeshInfo = { - index: i, - value: getImmediateChildByName(buttonMesh, "VALUE"), - pressed: getImmediateChildByName(buttonMesh, "PRESSED"), - unpressed: getImmediateChildByName(buttonMesh, "UNPRESSED"), - }; - if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) { - loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo; - } - else { - // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes. - logger_Logger.Warn("Missing button submesh under mesh with name: " + - buttonMeshName + - "(VALUE: " + - !!buttonMeshInfo.value + - ", PRESSED: " + - !!buttonMeshInfo.pressed + - ", UNPRESSED:" + - !!buttonMeshInfo.unpressed + - ")"); - } - } - // Axis Meshes - for (i = 0; i < this._mapping.axisMeshNames.length; i++) { - const axisMeshName = this._mapping.axisMeshNames[i]; - if (!axisMeshName) { - logger_Logger.Log("Skipping unknown axis at index: " + i); - continue; - } - const axisMesh = getChildByName(rootNode, axisMeshName); - if (!axisMesh) { - logger_Logger.Warn("Missing axis mesh with name: " + axisMeshName); - continue; - } - const axisMeshInfo = { - index: i, - value: getImmediateChildByName(axisMesh, "VALUE"), - min: getImmediateChildByName(axisMesh, "MIN"), - max: getImmediateChildByName(axisMesh, "MAX"), - }; - if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) { - loadedMeshInfo.axisMeshes[i] = axisMeshInfo; - } - else { - // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change. - logger_Logger.Warn("Missing axis submesh under mesh with name: " + - axisMeshName + - "(VALUE: " + - !!axisMeshInfo.value + - ", MIN: " + - !!axisMeshInfo.min + - ", MAX:" + - !!axisMeshInfo.max + - ")"); - } - } - // Pointing Ray - loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName); - if (!loadedMeshInfo.pointingPoseNode) { - logger_Logger.Warn("Missing pointing pose mesh with name: " + this._mapping.pointingPoseMeshName); - } - else { - this._pointingPoseNode = loadedMeshInfo.pointingPoseNode; - } - return loadedMeshInfo; - // Look through all children recursively. This will return null if no mesh exists with the given name. - function getChildByName(node, name) { - return node.getChildren((n) => n.name === name, false)[0]; - } - // Look through only immediate children. This will return null if no mesh exists with the given name. - function getImmediateChildByName(node, name) { - return node.getChildren((n) => n.name == name, true)[0]; - } - } - /** - * Gets the ray of the controller in the direction the controller is pointing - * @param length the length the resulting ray should be - * @returns a ray in the direction the controller is pointing - */ - getForwardRay(length = 100) { - if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) { - return super.getForwardRay(length); - } - const m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix(); - const origin = m.getTranslation(); - const forward = new math_vector_Vector3(0, 0, -1); - const forwardWorld = math_vector_Vector3.TransformNormal(forward, m); - const direction = math_vector_Vector3.Normalize(forwardWorld); - return new ray_Ray(origin, direction, length); - } - /** - * Disposes of the controller - */ - dispose() { - super.dispose(); - this.onTrackpadChangedObservable.clear(); - this.onTrackpadValuesChangedObservable.clear(); - } -} -/** - * The base url used to load the left and right controller models - */ -WindowsMotionController.MODEL_BASE_URL = "https://controllers.babylonjs.com/microsoft/"; -/** - * The name of the left controller model file - */ -WindowsMotionController.MODEL_LEFT_FILENAME = "left.glb"; -/** - * The name of the right controller model file - */ -WindowsMotionController.MODEL_RIGHT_FILENAME = "right.glb"; -/** - * The controller name prefix for this controller type - */ -WindowsMotionController.GAMEPAD_ID_PREFIX = "Spatial Controller (Spatial Interaction Source) "; -/** - * The controller id pattern for this controller type - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/; -/** - * This class represents a new windows motion controller in XR. - */ -class XRWindowsMotionController extends (/* unused pure expression or super */ null && (WindowsMotionController)) { - /** - * Construct a new XR-Based windows motion controller - * - * @param gamepadInfo the gamepad object from the browser - */ - constructor(gamepadInfo) { - super(gamepadInfo); - /** - * Changing the original WIndowsMotionController mapping to fir the new mapping - */ - this._mapping = { - // Semantic button names - buttons: ["trigger", "grip", "trackpad", "thumbstick", "menu"], - // trigger, grip, trackpad, thumbstick, menu - // A mapping of the button name to glTF model node name - // that should be transformed by button value. - buttonMeshNames: { - trigger: "SELECT", - menu: "MENU", - grip: "GRASP", - thumbstick: "THUMBSTICK_PRESS", - trackpad: "TOUCHPAD_PRESS", - }, - // This mapping is used to translate from the Motion Controller to Babylon semantics - buttonObservableNames: { - trigger: "onTriggerStateChangedObservable", - menu: "onSecondaryButtonStateChangedObservable", - grip: "onMainButtonStateChangedObservable", - thumbstick: "onThumbstickStateChangedObservable", - trackpad: "onTrackpadChangedObservable", - }, - // A mapping of the axis name to glTF model node name - // that should be transformed by axis value. - // This array mirrors the browserGamepad.axes array, such that - // the mesh corresponding to axis 0 is in this array index 0. - axisMeshNames: ["TOUCHPAD_TOUCH_X", "TOUCHPAD_TOUCH_Y", "THUMBSTICK_X", "THUMBSTICK_Y"], - // upside down in webxr - pointingPoseMeshName: PoseEnabledController.POINTING_POSE, - }; - /** - * holds the thumbstick values (X,Y) - */ - this.thumbstickValues = { x: 0, y: 0 }; - /** - * Fired when the thumbstick on this controller is clicked - */ - this.onThumbstickStateChangedObservable = new Observable(); - /** - * Fired when the thumbstick on this controller is modified - */ - this.onThumbstickValuesChangedObservable = new Observable(); - /** - * Fired when the touchpad button on this controller is modified - */ - this.onTrackpadChangedObservable = this.onPadStateChangedObservable; - /** - * Fired when the touchpad values on this controller are modified - */ - this.onTrackpadValuesChangedObservable = this.onPadValuesChangedObservable; - } - /** - * Fired when the thumbstick button on this controller is modified - * here to prevent breaking changes - */ - get onThumbstickButtonStateChangedObservable() { - return this.onThumbstickStateChangedObservable; - } - /** - * updating the thumbstick(!) and not the trackpad. - * This is named this way due to the difference between WebVR and XR and to avoid - * changing the parent class. - */ - _updateTrackpad() { - if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.thumbstickValues.x || this.browserGamepad.axes[3] != this.thumbstickValues.y)) { - this.trackpad.x = this.browserGamepad["axes"][2]; - this.trackpad.y = this.browserGamepad["axes"][3]; - this.onThumbstickValuesChangedObservable.notifyObservers(this.trackpad); - } - } - /** - * Disposes the class with joy - */ - dispose() { - super.dispose(); - this.onThumbstickStateChangedObservable.clear(); - this.onThumbstickValuesChangedObservable.clear(); - } -} -PoseEnabledControllerHelper._ControllerFactories.push({ - canCreate: (gamepadInfo) => { - return gamepadInfo.id.indexOf(WindowsMotionController.GAMEPAD_ID_PREFIX) === 0; - }, - create: (gamepadInfo) => { - return new WindowsMotionController(gamepadInfo); - }, -}); -//# sourceMappingURL=windowsMotionController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/Controllers/index.js - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gamepads/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/axisScaleGizmo.js - - - - - - - - - - -/** - * Single axis scale gizmo - */ -class axisScaleGizmo_AxisScaleGizmo extends (/* unused pure expression or super */ null && (Gizmo)) { - /** Default material used to render when gizmo is not disabled or hovered */ - get coloredMaterial() { - return this._coloredMaterial; - } - /** Material used to render when gizmo is hovered with mouse*/ - get hoverMaterial() { - return this._hoverMaterial; - } - /** Material used to render when gizmo is disabled. typically grey.*/ - get disableMaterial() { - return this._disableMaterial; - } - /** - * Creates an AxisScaleGizmo - * @param dragAxis The axis which the gizmo will be able to scale on - * @param color The color of the gizmo - * @param gizmoLayer The utility layer the gizmo will be added to - * @param parent - * @param thickness display gizmo axis thickness - */ - constructor(dragAxis, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, parent = null, thickness = 1) { - var _a, _b, _c, _d, _e, _f, _g; - super(gizmoLayer); - this._pointerObserver = null; - /** - * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0) - */ - this.snapDistance = 0; - /** - * Event that fires each time the gizmo snaps to a new location. - * * snapDistance is the the change in distance - */ - this.onSnapObservable = new Observable(); - /** - * If the scaling operation should be done on all axis (default: false) - */ - this.uniformScaling = false; - /** - * Custom sensitivity value for the drag strength - */ - this.sensitivity = 1; - /** - * The magnitude of the drag strength (scaling factor) - */ - this.dragScale = 1; - this._isEnabled = true; - this._parent = null; - this._dragging = false; - this._tmpVector = new Vector3(0, 0, 0); - this._parent = parent; - // Create Material - this._coloredMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._coloredMaterial.diffuseColor = color; - this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1)); - this._hoverMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._hoverMaterial.diffuseColor = Color3.Yellow(); - this._disableMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._disableMaterial.diffuseColor = Color3.Gray(); - this._disableMaterial.alpha = 0.4; - // Build mesh + Collider - this._gizmoMesh = new Mesh("axis", gizmoLayer.utilityLayerScene); - const { arrowMesh, arrowTail } = this._createGizmoMesh(this._gizmoMesh, thickness); - const collider = this._createGizmoMesh(this._gizmoMesh, thickness + 4, true); - this._gizmoMesh.lookAt(this._rootMesh.position.add(dragAxis)); - this._rootMesh.addChild(this._gizmoMesh, Gizmo.PreserveScaling); - this._gizmoMesh.scaling.scaleInPlace(1 / 3); - // Closure of initial prop values for resetting - const nodePosition = arrowMesh.position.clone(); - const linePosition = arrowTail.position.clone(); - const lineScale = arrowTail.scaling.clone(); - const increaseGizmoMesh = (dragDistance) => { - const dragStrength = dragDistance * (3 / this._rootMesh.scaling.length()) * 6; - arrowMesh.position.z += dragStrength / 3.5; - arrowTail.scaling.y += dragStrength; - this.dragScale = arrowTail.scaling.y; - arrowTail.position.z = arrowMesh.position.z / 2; - }; - const resetGizmoMesh = () => { - arrowMesh.position.set(nodePosition.x, nodePosition.y, nodePosition.z); - arrowTail.position.set(linePosition.x, linePosition.y, linePosition.z); - arrowTail.scaling.set(lineScale.x, lineScale.y, lineScale.z); - this.dragScale = arrowTail.scaling.y; - this._dragging = false; - }; - // Add drag behavior to handle events when the gizmo is dragged - this.dragBehavior = new PointerDragBehavior({ dragAxis: dragAxis }); - this.dragBehavior.moveAttached = false; - this.dragBehavior.updateDragPlane = false; - this._rootMesh.addBehavior(this.dragBehavior); - let currentSnapDragDistance = 0; - const tmpSnapEvent = { snapDistance: 0 }; - this.dragBehavior.onDragObservable.add((event) => { - if (this.attachedNode) { - this._handlePivot(); - // 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) - const dragStrength = this.sensitivity * event.dragDistance * ((this.scaleRatio * 3) / this._rootMesh.scaling.length()); - const tmpVector = this._tmpVector; - // Snapping logic - let snapped = false; - let dragSteps = 0; - if (this.uniformScaling) { - tmpVector.setAll(0.57735); // 1 / sqrt(3) - } - else { - tmpVector.copyFrom(dragAxis); - } - if (this.snapDistance == 0) { - tmpVector.scaleToRef(dragStrength, tmpVector); - } - else { - currentSnapDragDistance += dragStrength; - if (Math.abs(currentSnapDragDistance) > this.snapDistance) { - dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance); - if (currentSnapDragDistance < 0) { - dragSteps *= -1; - } - currentSnapDragDistance = currentSnapDragDistance % this.snapDistance; - tmpVector.scaleToRef(this.snapDistance * dragSteps, tmpVector); - snapped = true; - } - else { - tmpVector.scaleInPlace(0); - } - } - Matrix.ScalingToRef(1 + tmpVector.x, 1 + tmpVector.y, 1 + tmpVector.z, TmpVectors.Matrix[2]); - TmpVectors.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(), TmpVectors.Matrix[1]); - const transformNode = this.attachedNode._isMesh ? this.attachedNode : undefined; - TmpVectors.Matrix[1].decompose(TmpVectors.Vector3[1], undefined, undefined, Gizmo.PreserveScaling ? transformNode : undefined); - const maxScale = 100000; - if (Math.abs(TmpVectors.Vector3[1].x) < maxScale && Math.abs(TmpVectors.Vector3[1].y) < maxScale && Math.abs(TmpVectors.Vector3[1].z) < maxScale) { - this.attachedNode.getWorldMatrix().copyFrom(TmpVectors.Matrix[1]); - } - if (snapped) { - tmpSnapEvent.snapDistance = this.snapDistance * dragSteps; - this.onSnapObservable.notifyObservers(tmpSnapEvent); - } - this._matrixChanged(); - } - }); - // On Drag Listener: to move gizmo mesh with user action - this.dragBehavior.onDragStartObservable.add(() => { - this._dragging = true; - }); - this.dragBehavior.onDragObservable.add((e) => increaseGizmoMesh(e.dragDistance)); - this.dragBehavior.onDragEndObservable.add(resetGizmoMesh); - // Listeners for Universal Scalar - (_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)); - (_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); - const cache = { - gizmoMeshes: [arrowMesh, arrowTail], - colliderMeshes: [collider.arrowMesh, collider.arrowTail], - material: this._coloredMaterial, - hoverMaterial: this._hoverMaterial, - disableMaterial: this._disableMaterial, - active: false, - dragBehavior: this.dragBehavior, - }; - (_g = this._parent) === null || _g === void 0 ? void 0 : _g.addToAxisCache(this._gizmoMesh, cache); - this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => { - var _a; - if (this._customMeshSet) { - return; - } - this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1); - if (!this._parent) { - const material = this.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial; - this._setGizmoMeshMaterial(cache.gizmoMeshes, material); - } - }); - this.dragBehavior.onEnabledObservable.add((newState) => { - this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial); - }); - const light = gizmoLayer._getSharedGizmoLight(); - light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes()); - } - /** - * Create Geometry for Gizmo - * @param parentMesh - * @param thickness - * @param isCollider - */ - _createGizmoMesh(parentMesh, thickness, isCollider = false) { - const arrowMesh = CreateBox("yPosMesh", { size: 0.4 * (1 + (thickness - 1) / 4) }, this.gizmoLayer.utilityLayerScene); - const arrowTail = CreateCylinder("cylinder", { diameterTop: 0.005 * thickness, height: 0.275, diameterBottom: 0.005 * thickness, tessellation: 96 }, this.gizmoLayer.utilityLayerScene); - // Position arrow pointing in its drag axis - arrowMesh.scaling.scaleInPlace(0.1); - arrowMesh.material = this._coloredMaterial; - arrowMesh.rotation.x = Math.PI / 2; - arrowMesh.position.z += 0.3; - arrowTail.material = this._coloredMaterial; - arrowTail.position.z += 0.275 / 2; - arrowTail.rotation.x = Math.PI / 2; - if (isCollider) { - arrowMesh.visibility = 0; - arrowTail.visibility = 0; - } - parentMesh.addChild(arrowMesh); - parentMesh.addChild(arrowTail); - return { arrowMesh, arrowTail }; - } - _attachedNodeChanged(value) { - if (this.dragBehavior) { - this.dragBehavior.enabled = value ? true : false; - } - } - /** - * If the gizmo is enabled - */ - set isEnabled(value) { - this._isEnabled = value; - if (!value) { - this.attachedMesh = null; - this.attachedNode = null; - } - else { - if (this._parent) { - this.attachedMesh = this._parent.attachedMesh; - this.attachedNode = this._parent.attachedNode; - } - } - } - get isEnabled() { - return this._isEnabled; - } - /** - * Disposes of the gizmo - */ - dispose() { - this.onSnapObservable.clear(); - this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); - this.dragBehavior.detach(); - if (this._gizmoMesh) { - this._gizmoMesh.dispose(); - } - [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => { - if (matl) { - matl.dispose(); - } - }); - super.dispose(); - } - /** - * Disposes and replaces the current meshes in the gizmo with the specified mesh - * @param mesh The mesh to replace the default mesh of the gizmo - * @param useGizmoMaterial If the gizmo's default material should be used (default: false) - */ - setCustomMesh(mesh, useGizmoMaterial = false) { - super.setCustomMesh(mesh); - if (useGizmoMaterial) { - this._rootMesh.getChildMeshes().forEach((m) => { - m.material = this._coloredMaterial; - if (m.color) { - m.color = this._coloredMaterial.diffuseColor; - } - }); - this._customMeshSet = false; - } - } -} -//# sourceMappingURL=axisScaleGizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/boundingBoxGizmo.js - - - - - - - - - - - - - - -/** - * Bounding box gizmo - */ -class boundingBoxGizmo_BoundingBoxGizmo extends (/* unused pure expression or super */ null && (Gizmo)) { - /** - * Sets the axis factor - * @param factor the Vector3 value - */ - set axisFactor(factor) { - this._axisFactor = factor; - // update scale cube visibility - const scaleBoxes = this._scaleBoxesParent.getChildMeshes(); - let index = 0; - for (let i = 0; i < 3; i++) { - for (let j = 0; j < 3; j++) { - for (let k = 0; k < 3; k++) { - const zeroAxisCount = (i === 1 ? 1 : 0) + (j === 1 ? 1 : 0) + (k === 1 ? 1 : 0); - if (zeroAxisCount === 1 || zeroAxisCount === 3) { - continue; - } - if (scaleBoxes[index]) { - const dragAxis = new Vector3(i - 1, j - 1, k - 1); - dragAxis.multiplyInPlace(this._axisFactor); - scaleBoxes[index].setEnabled(dragAxis.lengthSquared() > Epsilon); - } - index++; - } - } - } - } - /** - * Gets the axis factor - * @returns the Vector3 factor value - */ - get axisFactor() { - return this._axisFactor; - } - /** - * Sets scale drag speed value - * @param value the new speed value - */ - set scaleDragSpeed(value) { - this._scaleDragSpeed = value; - } - /** - * Gets scale drag speed - * @returns the scale speed number - */ - get scaleDragSpeed() { - return this._scaleDragSpeed; - } - /** Default material used to render when gizmo is not disabled or hovered */ - get coloredMaterial() { - return this._coloredMaterial; - } - /** Material used to render when gizmo is hovered with mouse*/ - get hoverMaterial() { - return this._hoverColoredMaterial; - } - /** - * Get the pointerDragBehavior - */ - get pointerDragBehavior() { - return this._pointerDragBehavior; - } - /** - * Sets the color of the bounding box gizmo - * @param color the color to set - */ - setColor(color) { - this._coloredMaterial.emissiveColor = color; - this._hoverColoredMaterial.emissiveColor = color.clone().add(new Color3(0.3, 0.3, 0.3)); - this._lineBoundingBox.getChildren().forEach((l) => { - if (l.color) { - l.color = color; - } - }); - } - /** - * Creates an BoundingBoxGizmo - * @param color The color of the gizmo - * @param gizmoLayer The utility layer the gizmo will be added to - */ - constructor(color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultKeepDepthUtilityLayer) { - super(gizmoLayer); - this._boundingDimensions = new Vector3(1, 1, 1); - this._renderObserver = null; - this._pointerObserver = null; - this._scaleDragSpeed = 0.2; - this._tmpQuaternion = new Quaternion(); - this._tmpVector = new Vector3(0, 0, 0); - this._tmpRotationMatrix = new Matrix(); - /** - * 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) - */ - this.ignoreChildren = false; - /** - * 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) - */ - this.includeChildPredicate = null; - /** - * The size of the rotation spheres attached to the bounding box (Default: 0.1) - */ - this.rotationSphereSize = 0.1; - /** - * The size of the scale boxes attached to the bounding box (Default: 0.1) - */ - this.scaleBoxSize = 0.1; - /** - * 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) - * Note : fixedDragMeshScreenSize takes precedence over fixedDragMeshBoundsSize if both are true - */ - this.fixedDragMeshScreenSize = false; - /** - * If set, the rotation spheres and scale boxes will increase in size based on the size of the bounding box - * Note : fixedDragMeshScreenSize takes precedence over fixedDragMeshBoundsSize if both are true - */ - this.fixedDragMeshBoundsSize = false; - /** - * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10) - */ - this.fixedDragMeshScreenSizeDistanceFactor = 10; - /** - * Fired when a rotation sphere or scale box is dragged - */ - this.onDragStartObservable = new Observable(); - /** - * Fired when a scale box is dragged - */ - this.onScaleBoxDragObservable = new Observable(); - /** - * Fired when a scale box drag is ended - */ - this.onScaleBoxDragEndObservable = new Observable(); - /** - * Fired when a rotation sphere is dragged - */ - this.onRotationSphereDragObservable = new Observable(); - /** - * Fired when a rotation sphere drag is ended - */ - this.onRotationSphereDragEndObservable = new Observable(); - /** - * 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) - */ - this.scalePivot = null; - /** - * Scale factor used for masking some axis - */ - this._axisFactor = new Vector3(1, 1, 1); - this._existingMeshScale = new Vector3(); - // Dragging - this._dragMesh = null; - this._pointerDragBehavior = new PointerDragBehavior(); - // Do not update the gizmo's scale so it has a fixed size to the object its attached to - this.updateScale = false; - this._anchorMesh = new AbstractMesh("anchor", gizmoLayer.utilityLayerScene); - // Create Materials - this._coloredMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._coloredMaterial.disableLighting = true; - this._hoverColoredMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._hoverColoredMaterial.disableLighting = true; - // Build bounding box out of lines - this._lineBoundingBox = new AbstractMesh("", gizmoLayer.utilityLayerScene); - this._lineBoundingBox.rotationQuaternion = new Quaternion(); - const lines = []; - lines.push(CreateLines("lines", { points: [new Vector3(0, 0, 0), new Vector3(this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { points: [new Vector3(0, 0, 0), new Vector3(0, this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { points: [new Vector3(0, 0, 0), new Vector3(0, 0, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { points: [new Vector3(this._boundingDimensions.x, 0, 0), new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { points: [new Vector3(this._boundingDimensions.x, 0, 0), new Vector3(this._boundingDimensions.x, 0, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { points: [new Vector3(0, this._boundingDimensions.y, 0), new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { points: [new Vector3(0, this._boundingDimensions.y, 0), new Vector3(0, this._boundingDimensions.y, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { points: [new Vector3(0, 0, this._boundingDimensions.z), new Vector3(this._boundingDimensions.x, 0, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { points: [new Vector3(0, 0, this._boundingDimensions.z), new Vector3(0, this._boundingDimensions.y, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { - points: [ - new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, this._boundingDimensions.z), - new Vector3(0, this._boundingDimensions.y, this._boundingDimensions.z), - ], - }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { - points: [ - new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, this._boundingDimensions.z), - new Vector3(this._boundingDimensions.x, 0, this._boundingDimensions.z), - ], - }, gizmoLayer.utilityLayerScene)); - lines.push(CreateLines("lines", { - points: [ - new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, this._boundingDimensions.z), - new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, 0), - ], - }, gizmoLayer.utilityLayerScene)); - lines.forEach((l) => { - l.color = color; - l.position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); - l.isPickable = false; - this._lineBoundingBox.addChild(l); - }); - this._rootMesh.addChild(this._lineBoundingBox); - this.setColor(color); - // Create rotation spheres - this._rotateSpheresParent = new AbstractMesh("", gizmoLayer.utilityLayerScene); - this._rotateSpheresParent.rotationQuaternion = new Quaternion(); - for (let i = 0; i < 12; i++) { - const sphere = CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene); - sphere.rotationQuaternion = new Quaternion(); - sphere.material = this._coloredMaterial; - sphere.isNearGrabbable = true; - // Drag behavior - const _dragBehavior = new PointerDragBehavior({}); - _dragBehavior.moveAttached = false; - _dragBehavior.updateDragPlane = false; - sphere.addBehavior(_dragBehavior); - const startingTurnDirection = new Vector3(1, 0, 0); - let totalTurnAmountOfDrag = 0; - _dragBehavior.onDragStartObservable.add(() => { - startingTurnDirection.copyFrom(sphere.forward); - totalTurnAmountOfDrag = 0; - }); - _dragBehavior.onDragObservable.add((event) => { - this.onRotationSphereDragObservable.notifyObservers({}); - if (this.attachedMesh) { - const originalParent = this.attachedMesh.parent; - if (originalParent && originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001)) { - Logger.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling"); - return; - } - PivotTools._RemoveAndStorePivotPoint(this.attachedMesh); - const worldDragDirection = startingTurnDirection; - // Project the world right on to the drag plane - const toSub = event.dragPlaneNormal.scale(Vector3.Dot(event.dragPlaneNormal, worldDragDirection)); - const dragAxis = worldDragDirection.subtract(toSub).normalizeToNew(); - // project drag delta on to the resulting drag axis and rotate based on that - let projectDist = Vector3.Dot(dragAxis, event.delta) < 0 ? Math.abs(event.delta.length()) : -Math.abs(event.delta.length()); - // Make rotation relative to size of mesh. - projectDist = (projectDist / this._boundingDimensions.length()) * this._anchorMesh.scaling.length(); - // Rotate based on axis - if (!this.attachedMesh.rotationQuaternion) { - this.attachedMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z); - } - if (!this._anchorMesh.rotationQuaternion) { - this._anchorMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z); - } - // Do not allow the object to turn more than a full circle - totalTurnAmountOfDrag += projectDist; - if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) { - if (i >= 8) { - Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, this._tmpQuaternion); - } - else if (i >= 4) { - Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, this._tmpQuaternion); - } - else { - Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, this._tmpQuaternion); - } - // Rotate around center of bounding box - this._anchorMesh.addChild(this.attachedMesh, Gizmo.PreserveScaling); - if (this._anchorMesh.getScene().useRightHandedSystem) { - this._tmpQuaternion.conjugateInPlace(); - } - this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion, this._anchorMesh.rotationQuaternion); - this._anchorMesh.removeChild(this.attachedMesh, Gizmo.PreserveScaling); - this.attachedMesh.setParent(originalParent, Gizmo.PreserveScaling); - } - this.updateBoundingBox(); - PivotTools._RestorePivotPoint(this.attachedMesh); - } - this._updateDummy(); - }); - // Selection/deselection - _dragBehavior.onDragStartObservable.add(() => { - this.onDragStartObservable.notifyObservers({}); - this._selectNode(sphere); - }); - _dragBehavior.onDragEndObservable.add((event) => { - this.onRotationSphereDragEndObservable.notifyObservers({}); - this._selectNode(null); - this._updateDummy(); - this._unhoverMeshOnTouchUp(event.pointerInfo, sphere); - }); - this._rotateSpheresParent.addChild(sphere); - } - this._rootMesh.addChild(this._rotateSpheresParent); - // Create scale cubes - this._scaleBoxesParent = new AbstractMesh("", gizmoLayer.utilityLayerScene); - this._scaleBoxesParent.rotationQuaternion = new Quaternion(); - for (let i = 0; i < 3; i++) { - for (let j = 0; j < 3; j++) { - for (let k = 0; k < 3; k++) { - // create box for relevant axis - const zeroAxisCount = (i === 1 ? 1 : 0) + (j === 1 ? 1 : 0) + (k === 1 ? 1 : 0); - if (zeroAxisCount === 1 || zeroAxisCount === 3) { - continue; - } - const box = CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene); - box.material = this._coloredMaterial; - box._internalMetadata = zeroAxisCount === 2; // None homogenous scale handle - box.isNearGrabbable = true; - // Dragging logic - const dragAxis = new Vector3(i - 1, j - 1, k - 1).normalize(); - const _dragBehavior = new PointerDragBehavior({ dragAxis: dragAxis }); - _dragBehavior.updateDragPlane = false; - _dragBehavior.moveAttached = false; - box.addBehavior(_dragBehavior); - _dragBehavior.onDragObservable.add((event) => { - this.onScaleBoxDragObservable.notifyObservers({}); - if (this.attachedMesh) { - const originalParent = this.attachedMesh.parent; - if (originalParent && originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001)) { - Logger.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling"); - return; - } - PivotTools._RemoveAndStorePivotPoint(this.attachedMesh); - const relativeDragDistance = (event.dragDistance / this._boundingDimensions.length()) * this._anchorMesh.scaling.length(); - const deltaScale = new Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance); - if (zeroAxisCount === 2) { - // scale on 1 axis when using the anchor box in the face middle - deltaScale.x *= Math.abs(dragAxis.x); - deltaScale.y *= Math.abs(dragAxis.y); - deltaScale.z *= Math.abs(dragAxis.z); - } - deltaScale.scaleInPlace(this._scaleDragSpeed); - deltaScale.multiplyInPlace(this._axisFactor); - this.updateBoundingBox(); - if (this.scalePivot) { - this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix); - // Move anchor to desired pivot point (Bottom left corner + dimension/2) - this._boundingDimensions.scaleToRef(0.5, this._tmpVector); - Vector3.TransformCoordinatesToRef(this._tmpVector, this._tmpRotationMatrix, this._tmpVector); - this._anchorMesh.position.subtractInPlace(this._tmpVector); - this._boundingDimensions.multiplyToRef(this.scalePivot, this._tmpVector); - Vector3.TransformCoordinatesToRef(this._tmpVector, this._tmpRotationMatrix, this._tmpVector); - this._anchorMesh.position.addInPlace(this._tmpVector); - } - else { - // Scale from the position of the opposite corner - box.absolutePosition.subtractToRef(this._anchorMesh.position, this._tmpVector); - this._anchorMesh.position.subtractInPlace(this._tmpVector); - } - this._anchorMesh.addChild(this.attachedMesh, Gizmo.PreserveScaling); - this._anchorMesh.scaling.addInPlace(deltaScale); - if (this._anchorMesh.scaling.x < 0 || this._anchorMesh.scaling.y < 0 || this._anchorMesh.scaling.z < 0) { - this._anchorMesh.scaling.subtractInPlace(deltaScale); - } - this._anchorMesh.removeChild(this.attachedMesh, Gizmo.PreserveScaling); - this.attachedMesh.setParent(originalParent, Gizmo.PreserveScaling); - PivotTools._RestorePivotPoint(this.attachedMesh); - } - this._updateDummy(); - }); - // Selection/deselection - _dragBehavior.onDragStartObservable.add(() => { - this.onDragStartObservable.notifyObservers({}); - this._selectNode(box); - }); - _dragBehavior.onDragEndObservable.add((event) => { - this.onScaleBoxDragEndObservable.notifyObservers({}); - this._selectNode(null); - this._updateDummy(); - this._unhoverMeshOnTouchUp(event.pointerInfo, box); - }); - this._scaleBoxesParent.addChild(box); - } - } - } - this._rootMesh.addChild(this._scaleBoxesParent); - // Hover color change - const pointerIds = new Array(); - this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => { - if (!pointerIds[pointerInfo.event.pointerId]) { - this._rotateSpheresParent - .getChildMeshes() - .concat(this._scaleBoxesParent.getChildMeshes()) - .forEach((mesh) => { - if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) { - pointerIds[pointerInfo.event.pointerId] = mesh; - mesh.material = this._hoverColoredMaterial; - } - }); - } - else { - if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) { - pointerIds[pointerInfo.event.pointerId].material = this._coloredMaterial; - delete pointerIds[pointerInfo.event.pointerId]; - } - } - }); - // Update bounding box positions - this._renderObserver = this.gizmoLayer.originalScene.onBeforeRenderObservable.add(() => { - // Only update the bounding box if scaling has changed - if (this.attachedMesh && !this._existingMeshScale.equals(this.attachedMesh.scaling)) { - this.updateBoundingBox(); - } - else if (this.fixedDragMeshScreenSize || this.fixedDragMeshBoundsSize) { - this._updateRotationSpheres(); - this._updateScaleBoxes(); - } - // If drag mesh is enabled and dragging, update the attached mesh pose to match the drag mesh - if (this._dragMesh && this.attachedMesh && this._pointerDragBehavior.dragging) { - this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion, this._tmpVector); - this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1))); - } - }); - this.updateBoundingBox(); - } - _attachedNodeChanged(value) { - if (value) { - // Reset anchor mesh to match attached mesh's scale - // This is needed to avoid invalid box/sphere position on first drag - this._anchorMesh.scaling.setAll(1); - PivotTools._RemoveAndStorePivotPoint(value); - const originalParent = value.parent; - this._anchorMesh.addChild(value, Gizmo.PreserveScaling); - this._anchorMesh.removeChild(value, Gizmo.PreserveScaling); - value.setParent(originalParent, Gizmo.PreserveScaling); - PivotTools._RestorePivotPoint(value); - this.updateBoundingBox(); - value.getChildMeshes(false).forEach((m) => { - m.markAsDirty("scaling"); - }); - this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(() => { - this._updateDummy(); - }); - } - } - _selectNode(selectedMesh) { - this._rotateSpheresParent - .getChildMeshes() - .concat(this._scaleBoxesParent.getChildMeshes()) - .forEach((m) => { - m.isVisible = !selectedMesh || m == selectedMesh; - }); - } - _unhoverMeshOnTouchUp(pointerInfo, selectedMesh) { - // force unhover mesh if not a mouse event - if ((pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.event) instanceof PointerEvent && (pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.event.pointerType) === "touch") { - selectedMesh.material = this._coloredMaterial; - } - } - /** - * returns an array containing all boxes used for scaling (in increasing x, y and z orders) - */ - getScaleBoxes() { - return this._scaleBoxesParent.getChildMeshes(); - } - /** - * Updates the bounding box information for the Gizmo - */ - updateBoundingBox() { - if (this.attachedMesh) { - PivotTools._RemoveAndStorePivotPoint(this.attachedMesh); - // Store original parent - const originalParent = this.attachedMesh.parent; - this.attachedMesh.setParent(null, Gizmo.PreserveScaling); - this._update(); - // Rotate based on axis - if (!this.attachedMesh.rotationQuaternion) { - this.attachedMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z); - } - if (!this._anchorMesh.rotationQuaternion) { - this._anchorMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z); - } - this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion); - // Store original position and reset mesh to origin before computing the bounding box - this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion); - this._tmpVector.copyFrom(this.attachedMesh.position); - this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1); - this.attachedMesh.position.set(0, 0, 0); - // Update bounding dimensions/positions - const boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate); - boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions); - // Update gizmo to match bounding box scaling and rotation - // The position set here is the offset from the origin for the boundingbox when the attached mesh is at the origin - // The position of the gizmo is then set to the attachedMesh in gizmo._update - this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions); - 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); - this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position); - this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position); - this._lineBoundingBox.computeWorldMatrix(); - this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition); - // Restore position/rotation values - this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion); - this.attachedMesh.position.copyFrom(this._tmpVector); - // Restore original parent - this.attachedMesh.setParent(originalParent, Gizmo.PreserveScaling); - } - this._updateRotationSpheres(); - this._updateScaleBoxes(); - if (this.attachedMesh) { - this._existingMeshScale.copyFrom(this.attachedMesh.scaling); - PivotTools._RestorePivotPoint(this.attachedMesh); - } - } - _updateRotationSpheres() { - const rotateSpheres = this._rotateSpheresParent.getChildMeshes(); - for (let i = 0; i < 3; i++) { - for (let j = 0; j < 2; j++) { - for (let k = 0; k < 2; k++) { - const index = i * 4 + j * 2 + k; - if (i == 0) { - rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k); - rotateSpheres[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); - rotateSpheres[index].lookAt(Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), Vector3.Right()).normalizeToNew().add(rotateSpheres[index].position)); - } - if (i == 1) { - rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k); - rotateSpheres[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); - rotateSpheres[index].lookAt(Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), Vector3.Up()).normalizeToNew().add(rotateSpheres[index].position)); - } - if (i == 2) { - rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2); - rotateSpheres[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); - rotateSpheres[index].lookAt(Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), Vector3.Forward()).normalizeToNew().add(rotateSpheres[index].position)); - } - if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) { - rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector); - const distanceFromCamera = (this.rotationSphereSize * this._tmpVector.length()) / this.fixedDragMeshScreenSizeDistanceFactor; - rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera); - } - else if (this.fixedDragMeshBoundsSize) { - rotateSpheres[index].scaling.set(this.rotationSphereSize * this._boundingDimensions.x, this.rotationSphereSize * this._boundingDimensions.y, this.rotationSphereSize * this._boundingDimensions.z); - } - else { - rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize); - } - } - } - } - } - _updateScaleBoxes() { - const scaleBoxes = this._scaleBoxesParent.getChildMeshes(); - let index = 0; - for (let i = 0; i < 3; i++) { - for (let j = 0; j < 3; j++) { - for (let k = 0; k < 3; k++) { - const zeroAxisCount = (i === 1 ? 1 : 0) + (j === 1 ? 1 : 0) + (k === 1 ? 1 : 0); - if (zeroAxisCount === 1 || zeroAxisCount === 3) { - continue; - } - if (scaleBoxes[index]) { - scaleBoxes[index].position.set(this._boundingDimensions.x * (i / 2), this._boundingDimensions.y * (j / 2), this._boundingDimensions.z * (k / 2)); - scaleBoxes[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); - if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) { - scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector); - const distanceFromCamera = (this.scaleBoxSize * this._tmpVector.length()) / this.fixedDragMeshScreenSizeDistanceFactor; - scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera); - } - else if (this.fixedDragMeshBoundsSize) { - scaleBoxes[index].scaling.set(this.scaleBoxSize * this._boundingDimensions.x, this.scaleBoxSize * this._boundingDimensions.y, this.scaleBoxSize * this._boundingDimensions.z); - } - else { - scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize); - } - } - index++; - } - } - } - } - /** - * Enables rotation on the specified axis and disables rotation on the others - * @param axis The list of axis that should be enabled (eg. "xy" or "xyz") - */ - setEnabledRotationAxis(axis) { - this._rotateSpheresParent.getChildMeshes().forEach((m, i) => { - if (i < 4) { - m.setEnabled(axis.indexOf("x") != -1); - } - else if (i < 8) { - m.setEnabled(axis.indexOf("y") != -1); - } - else { - m.setEnabled(axis.indexOf("z") != -1); - } - }); - } - /** - * Enables/disables scaling - * @param enable if scaling should be enabled - * @param homogeneousScaling defines if scaling should only be homogeneous - */ - setEnabledScaling(enable, homogeneousScaling = false) { - this._scaleBoxesParent.getChildMeshes().forEach((m) => { - let enableMesh = enable; - // Disable heterogeneous scale handles if requested. - if (homogeneousScaling && m._internalMetadata === true) { - enableMesh = false; - } - m.setEnabled(enableMesh); - }); - } - _updateDummy() { - if (this._dragMesh) { - this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()); - this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling); - this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion); - } - } - /** - * Enables a pointer drag behavior on the bounding box of the gizmo - */ - enableDragBehavior() { - this._dragMesh = CreateBox("dummy", { size: 1 }, this.gizmoLayer.utilityLayerScene); - this._dragMesh.visibility = 0; - this._dragMesh.rotationQuaternion = new Quaternion(); - this._pointerDragBehavior.useObjectOrientationForDragging = false; - this._dragMesh.addBehavior(this._pointerDragBehavior); - } - /** - * Disposes of the gizmo - */ - dispose() { - this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); - this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver); - this._lineBoundingBox.dispose(); - this._rotateSpheresParent.dispose(); - this._scaleBoxesParent.dispose(); - if (this._dragMesh) { - this._dragMesh.dispose(); - } - super.dispose(); - } - /** - * 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) - * @param mesh the mesh to wrap in the bounding box mesh and make not pickable - * @returns the bounding box mesh with the passed in mesh as a child - */ - static MakeNotPickableAndWrapInBoundingBox(mesh) { - const makeNotPickable = (root) => { - root.isPickable = false; - root.getChildMeshes().forEach((c) => { - makeNotPickable(c); - }); - }; - makeNotPickable(mesh); - // Reset position to get bounding box from origin with no rotation - if (!mesh.rotationQuaternion) { - mesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z); - } - const oldPos = mesh.position.clone(); - const oldRot = mesh.rotationQuaternion.clone(); - mesh.rotationQuaternion.set(0, 0, 0, 1); - mesh.position.set(0, 0, 0); - // Update bounding dimensions/positions - const box = CreateBox("box", { size: 1 }, mesh.getScene()); - const boundingMinMax = mesh.getHierarchyBoundingVectors(); - boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling); - // Adjust scale to avoid undefined behavior when adding child - if (box.scaling.y === 0) { - box.scaling.y = Epsilon; - } - if (box.scaling.x === 0) { - box.scaling.x = Epsilon; - } - if (box.scaling.z === 0) { - box.scaling.z = Epsilon; - } - box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2); - // Restore original positions - mesh.addChild(box); - mesh.rotationQuaternion.copyFrom(oldRot); - mesh.position.copyFrom(oldPos); - // Reverse parenting - mesh.removeChild(box); - box.addChild(mesh); - box.visibility = 0; - return box; - } - /** - * CustomMeshes are not supported by this gizmo - */ - setCustomMesh() { - Logger.Error("Custom meshes are not supported on this gizmo"); - } -} -//# sourceMappingURL=boundingBoxGizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/planeRotationGizmo.js - - - - - - - - - - - - - - - -/** - * Single plane rotation gizmo - */ -class planeRotationGizmo_PlaneRotationGizmo extends gizmo_Gizmo { - /** Default material used to render when gizmo is not disabled or hovered */ - get coloredMaterial() { - return this._coloredMaterial; - } - /** Material used to render when gizmo is hovered with mouse*/ - get hoverMaterial() { - return this._hoverMaterial; - } - /** Material used to render when gizmo is disabled. typically grey.*/ - get disableMaterial() { - return this._disableMaterial; - } - /** - * Creates a PlaneRotationGizmo - * @param planeNormal The normal of the plane which the gizmo will be able to rotate on - * @param color The color of the gizmo - * @param gizmoLayer The utility layer the gizmo will be added to - * @param tessellation Amount of tessellation to be used when creating rotation circles - * @param parent - * @param useEulerRotation Use and update Euler angle instead of quaternion - * @param thickness display gizmo axis thickness - */ - constructor(planeNormal, color = math_color_Color3.Gray(), gizmoLayer = utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer, tessellation = 32, parent = null, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - useEulerRotation = false, thickness = 1) { - var _a; - super(gizmoLayer); - this._pointerObserver = null; - /** - * Rotation distance in radians that the gizmo will snap to (Default: 0) - */ - this.snapDistance = 0; - /** - * Event that fires each time the gizmo snaps to a new location. - * * snapDistance is the the change in distance - */ - this.onSnapObservable = new observable_Observable(); - /** - * Accumulated relative angle value for rotation on the axis. Reset to 0 when a dragStart occurs - */ - this.angle = 0; - /** - * Custom sensitivity value for the drag strength - */ - this.sensitivity = 1; - this._isEnabled = true; - this._parent = null; - this._dragging = false; - this._angles = new math_vector_Vector3(); - this._parent = parent; - // Create Material - this._coloredMaterial = new standardMaterial_StandardMaterial("", gizmoLayer.utilityLayerScene); - this._coloredMaterial.diffuseColor = color; - this._coloredMaterial.specularColor = color.subtract(new math_color_Color3(0.1, 0.1, 0.1)); - this._hoverMaterial = new standardMaterial_StandardMaterial("", gizmoLayer.utilityLayerScene); - this._hoverMaterial.diffuseColor = math_color_Color3.Yellow(); - this._disableMaterial = new standardMaterial_StandardMaterial("", gizmoLayer.utilityLayerScene); - this._disableMaterial.diffuseColor = math_color_Color3.Gray(); - this._disableMaterial.alpha = 0.4; - // Build mesh on root node - this._gizmoMesh = new mesh_Mesh("", gizmoLayer.utilityLayerScene); - const { rotationMesh, collider } = this._createGizmoMesh(this._gizmoMesh, thickness, tessellation); - // Setup Rotation Circle - this._rotationDisplayPlane = planeBuilder_CreatePlane("rotationDisplay", { size: 0.6, updatable: false }, this.gizmoLayer.utilityLayerScene); - this._rotationDisplayPlane.rotation.z = Math.PI * 0.5; - this._rotationDisplayPlane.parent = this._gizmoMesh; - this._rotationDisplayPlane.setEnabled(false); - effect_Effect.ShadersStore.rotationGizmoVertexShader = planeRotationGizmo_PlaneRotationGizmo._RotationGizmoVertexShader; - effect_Effect.ShadersStore.rotationGizmoFragmentShader = planeRotationGizmo_PlaneRotationGizmo._RotationGizmoFragmentShader; - this._rotationShaderMaterial = new shaderMaterial_ShaderMaterial("shader", this.gizmoLayer.utilityLayerScene, { - vertex: "rotationGizmo", - fragment: "rotationGizmo", - }, { - attributes: ["position", "uv"], - uniforms: ["worldViewProjection", "angles"], - }); - this._rotationShaderMaterial.backFaceCulling = false; - this._rotationDisplayPlane.material = this._rotationShaderMaterial; - this._rotationDisplayPlane.visibility = 0.999; - this._gizmoMesh.lookAt(this._rootMesh.position.add(planeNormal)); - this._rootMesh.addChild(this._gizmoMesh, gizmo_Gizmo.PreserveScaling); - this._gizmoMesh.scaling.scaleInPlace(1 / 3); - // Add drag behavior to handle events when the gizmo is dragged - this.dragBehavior = new pointerDragBehavior_PointerDragBehavior({ dragPlaneNormal: planeNormal }); - this.dragBehavior.moveAttached = false; - this.dragBehavior.maxDragAngle = planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle; - this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true; - this._rootMesh.addBehavior(this.dragBehavior); - // Closures for drag logic - const lastDragPosition = new math_vector_Vector3(); - const rotationMatrix = new math_vector_Matrix(); - const planeNormalTowardsCamera = new math_vector_Vector3(); - let localPlaneNormalTowardsCamera = new math_vector_Vector3(); - this.dragBehavior.onDragStartObservable.add((e) => { - if (this.attachedNode) { - lastDragPosition.copyFrom(e.dragPlanePoint); - this._rotationDisplayPlane.setEnabled(true); - this._rotationDisplayPlane.getWorldMatrix().invertToRef(rotationMatrix); - math_vector_Vector3.TransformCoordinatesToRef(e.dragPlanePoint, rotationMatrix, lastDragPosition); - this._angles.x = Math.atan2(lastDragPosition.y, lastDragPosition.x) + Math.PI; - this._angles.y = 0; - this._angles.z = this.updateGizmoRotationToMatchAttachedMesh ? 1 : 0; - this._dragging = true; - lastDragPosition.copyFrom(e.dragPlanePoint); - this._rotationShaderMaterial.setVector3("angles", this._angles); - this.angle = 0; - } - }); - this.dragBehavior.onDragEndObservable.add(() => { - this._dragging = false; - this._rotationDisplayPlane.setEnabled(false); - }); - const tmpSnapEvent = { snapDistance: 0 }; - let currentSnapDragDistance = 0; - const tmpMatrix = new math_vector_Matrix(); - const amountToRotate = new math_vector_Quaternion(); - this.dragBehavior.onDragObservable.add((event) => { - if (this.attachedNode) { - // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360) - const nodeScale = new math_vector_Vector3(1, 1, 1); - const nodeQuaternion = new math_vector_Quaternion(0, 0, 0, 1); - const nodeTranslation = new math_vector_Vector3(0, 0, 0); - this._handlePivot(); - this.attachedNode.getWorldMatrix().decompose(nodeScale, nodeQuaternion, nodeTranslation); - // uniform scaling of absolute value of components - // (-1,1,1) is uniform but (1,1.001,1) is not - const uniformScaling = Math.abs(Math.abs(nodeScale.x) - Math.abs(nodeScale.y)) <= math_constants_Epsilon && Math.abs(Math.abs(nodeScale.x) - Math.abs(nodeScale.z)) <= math_constants_Epsilon; - if (!uniformScaling && this.updateGizmoRotationToMatchAttachedMesh) { - logger_Logger.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false."); - return; - } - nodeQuaternion.normalize(); - const nodeTranslationForOperation = this.updateGizmoPositionToMatchAttachedMesh ? nodeTranslation : this._rootMesh.absolutePosition; - const newVector = event.dragPlanePoint.subtract(nodeTranslationForOperation).normalize(); - const originalVector = lastDragPosition.subtract(nodeTranslationForOperation).normalize(); - const cross = math_vector_Vector3.Cross(newVector, originalVector); - const dot = math_vector_Vector3.Dot(newVector, originalVector); - let angle = Math.atan2(cross.length(), dot) * this.sensitivity; - planeNormalTowardsCamera.copyFrom(planeNormal); - localPlaneNormalTowardsCamera.copyFrom(planeNormal); - if (this.updateGizmoRotationToMatchAttachedMesh) { - nodeQuaternion.toRotationMatrix(rotationMatrix); - localPlaneNormalTowardsCamera = math_vector_Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix); - } - // Flip up vector depending on which side the camera is on - let cameraFlipped = false; - if (gizmoLayer.utilityLayerScene.activeCamera) { - const camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(nodeTranslationForOperation).normalize(); - if (math_vector_Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) { - planeNormalTowardsCamera.scaleInPlace(-1); - localPlaneNormalTowardsCamera.scaleInPlace(-1); - cameraFlipped = true; - } - } - const halfCircleSide = math_vector_Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0; - if (halfCircleSide) { - angle = -angle; - } - // Snapping logic - let snapped = false; - if (this.snapDistance != 0) { - currentSnapDragDistance += angle; - if (Math.abs(currentSnapDragDistance) > this.snapDistance) { - let dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance); - if (currentSnapDragDistance < 0) { - dragSteps *= -1; - } - currentSnapDragDistance = currentSnapDragDistance % this.snapDistance; - angle = this.snapDistance * dragSteps; - snapped = true; - } - else { - angle = 0; - } - } - // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm) - const quaternionCoefficient = Math.sin(angle / 2); - amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2)); - // 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 - if (tmpMatrix.determinant() > 0) { - const tmpVector = new math_vector_Vector3(); - amountToRotate.toEulerAnglesToRef(tmpVector); - math_vector_Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate); - } - if (this.updateGizmoRotationToMatchAttachedMesh) { - // Rotate selected mesh quaternion over fixed axis - nodeQuaternion.multiplyToRef(amountToRotate, nodeQuaternion); - // recompose matrix - math_vector_Matrix.ComposeToRef(nodeScale, nodeQuaternion, nodeTranslation, this.attachedNode.getWorldMatrix()); - } - else { - // Rotate selected mesh quaternion over rotated axis - amountToRotate.toRotationMatrix(math_vector_TmpVectors.Matrix[0]); - const translation = this.attachedNode.getWorldMatrix().getTranslation(); - this.attachedNode.getWorldMatrix().multiplyToRef(math_vector_TmpVectors.Matrix[0], this.attachedNode.getWorldMatrix()); - this.attachedNode.getWorldMatrix().setTranslation(translation); - } - lastDragPosition.copyFrom(event.dragPlanePoint); - if (snapped) { - tmpSnapEvent.snapDistance = angle; - this.onSnapObservable.notifyObservers(tmpSnapEvent); - } - this._angles.y += angle; - this.angle += cameraFlipped ? -angle : angle; - this._rotationShaderMaterial.setVector3("angles", this._angles); - this._matrixChanged(); - } - }); - const light = gizmoLayer._getSharedGizmoLight(); - light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(false)); - const cache = { - colliderMeshes: [collider], - gizmoMeshes: [rotationMesh], - material: this._coloredMaterial, - hoverMaterial: this._hoverMaterial, - disableMaterial: this._disableMaterial, - active: false, - dragBehavior: this.dragBehavior, - }; - (_a = this._parent) === null || _a === void 0 ? void 0 : _a.addToAxisCache(this._gizmoMesh, cache); - this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => { - var _a; - if (this._customMeshSet) { - return; - } - // updating here the maxangle because ondragstart is too late (value already used) and the updated value is not taken into account - this.dragBehavior.maxDragAngle = planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle; - this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1); - if (!this._parent) { - const material = cache.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial; - this._setGizmoMeshMaterial(cache.gizmoMeshes, material); - } - }); - this.dragBehavior.onEnabledObservable.add((newState) => { - this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial); - }); - } - /** - * Create Geometry for Gizmo - * @param parentMesh - * @param thickness - * @param tessellation - */ - _createGizmoMesh(parentMesh, thickness, tessellation) { - const collider = CreateTorus("ignore", { - diameter: 0.6, - thickness: 0.03 * thickness, - tessellation, - }, this.gizmoLayer.utilityLayerScene); - collider.visibility = 0; - const rotationMesh = CreateTorus("", { - diameter: 0.6, - thickness: 0.005 * thickness, - tessellation, - }, this.gizmoLayer.utilityLayerScene); - rotationMesh.material = this._coloredMaterial; - // Position arrow pointing in its drag axis - rotationMesh.rotation.x = Math.PI / 2; - collider.rotation.x = Math.PI / 2; - parentMesh.addChild(rotationMesh, gizmo_Gizmo.PreserveScaling); - parentMesh.addChild(collider, gizmo_Gizmo.PreserveScaling); - return { rotationMesh, collider }; - } - _attachedNodeChanged(value) { - if (this.dragBehavior) { - this.dragBehavior.enabled = value ? true : false; - } - } - /** - * If the gizmo is enabled - */ - set isEnabled(value) { - this._isEnabled = value; - if (!value) { - this.attachedMesh = null; - } - else { - if (this._parent) { - this.attachedMesh = this._parent.attachedMesh; - } - } - } - get isEnabled() { - return this._isEnabled; - } - /** - * Disposes of the gizmo - */ - dispose() { - this.onSnapObservable.clear(); - this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); - this.dragBehavior.detach(); - if (this._gizmoMesh) { - this._gizmoMesh.dispose(); - } - if (this._rotationDisplayPlane) { - this._rotationDisplayPlane.dispose(); - } - if (this._rotationShaderMaterial) { - this._rotationShaderMaterial.dispose(); - } - [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => { - if (matl) { - matl.dispose(); - } - }); - super.dispose(); - } -} -/** - * The maximum angle between the camera and the rotation allowed for interaction - * If a rotation plane appears 'flat', a lower value allows interaction. - */ -planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle = (Math.PI * 9) / 20; -planeRotationGizmo_PlaneRotationGizmo._RotationGizmoVertexShader = ` - precision highp float; - attribute vec3 position; - attribute vec2 uv; - uniform mat4 worldViewProjection; - varying vec3 vPosition; - varying vec2 vUV; - void main(void) { - gl_Position = worldViewProjection * vec4(position, 1.0); - vUV = uv; - }`; -planeRotationGizmo_PlaneRotationGizmo._RotationGizmoFragmentShader = ` - precision highp float; - varying vec2 vUV; - varying vec3 vPosition; - uniform vec3 angles; - #define twopi 6.283185307 - void main(void) { - vec2 uv = vUV - vec2(0.5); - float angle = atan(uv.y, uv.x) + 3.141592; - float delta = gl_FrontFacing ? angles.y : -angles.y; - float begin = angles.x - delta * angles.z; - float start = (begin < (begin + delta)) ? begin : (begin + delta); - float end = (begin > (begin + delta)) ? begin : (begin + delta); - float len = sqrt(dot(uv,uv)); - float opacity = 1. - step(0.5, len); - - float base = abs(floor(start / twopi)) * twopi; - start += base; - end += base; - - float intensity = 0.; - for (int i = 0; i < 5; i++) - { - intensity += max(step(start, angle) - step(end, angle), 0.); - angle += twopi; - } - gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity; - }`; -//# sourceMappingURL=planeRotationGizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/rotationGizmo.js - - - - - - - -/** - * Gizmo that enables rotating a mesh along 3 axis - */ -class rotationGizmo_RotationGizmo extends (/* unused pure expression or super */ null && (Gizmo)) { - get attachedMesh() { - return this._meshAttached; - } - set attachedMesh(mesh) { - this._meshAttached = mesh; - this._nodeAttached = mesh; - this._checkBillboardTransform(); - [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => { - if (gizmo.isEnabled) { - gizmo.attachedMesh = mesh; - } - else { - gizmo.attachedMesh = null; - } - }); - } - get attachedNode() { - return this._nodeAttached; - } - set attachedNode(node) { - this._meshAttached = null; - this._nodeAttached = node; - this._checkBillboardTransform(); - [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => { - if (gizmo.isEnabled) { - gizmo.attachedNode = node; - } - else { - gizmo.attachedNode = null; - } - }); - } - _checkBillboardTransform() { - if (this._nodeAttached && this._nodeAttached.billboardMode) { - console.log("Rotation Gizmo will not work with transforms in billboard mode."); - } - } - /** - * Sensitivity factor for dragging (Default: 1) - */ - set sensitivity(value) { - this._sensitivity = value; - [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.sensitivity = value; - } - }); - } - get sensitivity() { - return this._sensitivity; - } - /** - * True when the mouse pointer is hovering a gizmo mesh - */ - get isHovered() { - let hovered = false; - [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => { - hovered = hovered || gizmo.isHovered; - }); - return hovered; - } - /** - * Creates a RotationGizmo - * @param gizmoLayer The utility layer the gizmo will be added to - * @param tessellation Amount of tessellation to be used when creating rotation circles - * @param useEulerRotation Use and update Euler angle instead of quaternion - * @param thickness display gizmo axis thickness - * @param gizmoManager Gizmo manager - * @param options More options - */ - constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, tessellation = 32, useEulerRotation = false, thickness = 1, gizmoManager, options) { - super(gizmoLayer); - /** Fires an event when any of it's sub gizmos are dragged */ - this.onDragStartObservable = new Observable(); - /** Fires an event when any of it's sub gizmos are released from dragging */ - this.onDragEndObservable = new Observable(); - this._observables = []; - this._sensitivity = 1; - /** Node Caching for quick lookup */ - this._gizmoAxisCache = new Map(); - const xColor = options && options.xOptions && options.xOptions.color ? options.xOptions.color : Color3.Red().scale(0.5); - const yColor = options && options.yOptions && options.yOptions.color ? options.yOptions.color : Color3.Green().scale(0.5); - const zColor = options && options.zOptions && options.zOptions.color ? options.zOptions.color : Color3.Blue().scale(0.5); - this.xGizmo = new PlaneRotationGizmo(new Vector3(1, 0, 0), xColor, gizmoLayer, tessellation, this, useEulerRotation, thickness); - this.yGizmo = new PlaneRotationGizmo(new Vector3(0, 1, 0), yColor, gizmoLayer, tessellation, this, useEulerRotation, thickness); - this.zGizmo = new PlaneRotationGizmo(new Vector3(0, 0, 1), zColor, gizmoLayer, tessellation, this, useEulerRotation, thickness); - // Relay drag events and set update scale - [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => { - //must set updateScale on each gizmo, as setting it on root RotationGizmo doesnt prevent individual gizmos from updating - //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 - if (options && options.updateScale != undefined) { - gizmo.updateScale = options.updateScale; - } - gizmo.dragBehavior.onDragStartObservable.add(() => { - this.onDragStartObservable.notifyObservers({}); - }); - gizmo.dragBehavior.onDragEndObservable.add(() => { - this.onDragEndObservable.notifyObservers({}); - }); - }); - this.attachedMesh = null; - this.attachedNode = null; - if (gizmoManager) { - gizmoManager.addToAxisCache(this._gizmoAxisCache); - } - else { - // Only subscribe to pointer event if gizmoManager isnt - Gizmo.GizmoAxisPointerObserver(gizmoLayer, this._gizmoAxisCache); - } - } - /** - * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true) - * NOTE: This is only possible for meshes with uniform scaling, as otherwise it's not possible to decompose the rotation - */ - set updateGizmoRotationToMatchAttachedMesh(value) { - if (this.xGizmo) { - this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value; - this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value; - this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value; - } - } - get updateGizmoRotationToMatchAttachedMesh() { - return this.xGizmo.updateGizmoRotationToMatchAttachedMesh; - } - set updateGizmoPositionToMatchAttachedMesh(value) { - if (this.xGizmo) { - this.xGizmo.updateGizmoPositionToMatchAttachedMesh = value; - this.yGizmo.updateGizmoPositionToMatchAttachedMesh = value; - this.zGizmo.updateGizmoPositionToMatchAttachedMesh = value; - } - } - get updateGizmoPositionToMatchAttachedMesh() { - return this.xGizmo.updateGizmoPositionToMatchAttachedMesh; - } - set anchorPoint(value) { - this._anchorPoint = value; - [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => { - gizmo.anchorPoint = value; - }); - } - get anchorPoint() { - return this._anchorPoint; - } - /** - * Set the coordinate system to use. By default it's local. - * But it's possible for a user to tweak so its local for translation and world for rotation. - * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh` - */ - set coordinatesMode(coordinatesMode) { - [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => { - gizmo.coordinatesMode = coordinatesMode; - }); - } - set updateScale(value) { - if (this.xGizmo) { - this.xGizmo.updateScale = value; - this.yGizmo.updateScale = value; - this.zGizmo.updateScale = value; - } - } - get updateScale() { - return this.xGizmo.updateScale; - } - /** - * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) - */ - set snapDistance(value) { - if (this.xGizmo) { - this.xGizmo.snapDistance = value; - this.yGizmo.snapDistance = value; - this.zGizmo.snapDistance = value; - } - } - get snapDistance() { - return this.xGizmo.snapDistance; - } - /** - * Ratio for the scale of the gizmo (Default: 1) - */ - set scaleRatio(value) { - if (this.xGizmo) { - this.xGizmo.scaleRatio = value; - this.yGizmo.scaleRatio = value; - this.zGizmo.scaleRatio = value; - } - } - get scaleRatio() { - return this.xGizmo.scaleRatio; - } - /** - * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation - * @param mesh Axis gizmo mesh - * @param cache Gizmo axis definition used for reactive gizmo UI - */ - addToAxisCache(mesh, cache) { - this._gizmoAxisCache.set(mesh, cache); - } - /** - * Disposes of the gizmo - */ - dispose() { - this.xGizmo.dispose(); - this.yGizmo.dispose(); - this.zGizmo.dispose(); - this.onDragStartObservable.clear(); - this.onDragEndObservable.clear(); - this._observables.forEach((obs) => { - this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(obs); - }); - } - /** - * CustomMeshes are not supported by this gizmo - */ - setCustomMesh() { - 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)"); - } -} -//# sourceMappingURL=rotationGizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/planeDragGizmo.js - - - - - - - - - -/** - * Single plane drag gizmo - */ -class planeDragGizmo_PlaneDragGizmo extends (/* unused pure expression or super */ null && (Gizmo)) { - /** Default material used to render when gizmo is not disabled or hovered */ - get coloredMaterial() { - return this._coloredMaterial; - } - /** Material used to render when gizmo is hovered with mouse*/ - get hoverMaterial() { - return this._hoverMaterial; - } - /** Material used to render when gizmo is disabled. typically grey.*/ - get disableMaterial() { - return this._disableMaterial; - } - /** - * @internal - */ - static _CreatePlane(scene, material) { - const plane = new TransformNode("plane", scene); - //make sure plane is double sided - const dragPlane = CreatePlane("dragPlane", { width: 0.1375, height: 0.1375, sideOrientation: 2 }, scene); - dragPlane.material = material; - dragPlane.parent = plane; - return plane; - } - /** - * Creates a PlaneDragGizmo - * @param dragPlaneNormal The axis normal to which the gizmo will be able to drag on - * @param color The color of the gizmo - * @param gizmoLayer The utility layer the gizmo will be added to - * @param parent - */ - constructor(dragPlaneNormal, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, parent = null) { - var _a; - super(gizmoLayer); - this._pointerObserver = null; - /** - * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) - */ - this.snapDistance = 0; - /** - * Event that fires each time the gizmo snaps to a new location. - * * snapDistance is the the change in distance - */ - this.onSnapObservable = new Observable(); - this._isEnabled = false; - this._parent = null; - this._dragging = false; - this._parent = parent; - // Create Material - this._coloredMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._coloredMaterial.diffuseColor = color; - this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1)); - this._hoverMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._hoverMaterial.diffuseColor = Color3.Yellow(); - this._disableMaterial = new StandardMaterial("", gizmoLayer.utilityLayerScene); - this._disableMaterial.diffuseColor = Color3.Gray(); - this._disableMaterial.alpha = 0.4; - // Build plane mesh on root node - this._gizmoMesh = planeDragGizmo_PlaneDragGizmo._CreatePlane(gizmoLayer.utilityLayerScene, this._coloredMaterial); - this._gizmoMesh.lookAt(this._rootMesh.position.add(dragPlaneNormal)); - this._gizmoMesh.scaling.scaleInPlace(1 / 3); - this._gizmoMesh.parent = this._rootMesh; - let currentSnapDragDistance = 0; - const tmpVector = new Vector3(); - const tmpSnapEvent = { snapDistance: 0 }; - // Add dragPlaneNormal drag behavior to handle events when the gizmo is dragged - this.dragBehavior = new PointerDragBehavior({ dragPlaneNormal: dragPlaneNormal }); - this.dragBehavior.moveAttached = false; - this._rootMesh.addBehavior(this.dragBehavior); - this.dragBehavior.onDragObservable.add((event) => { - if (this.attachedNode) { - this._handlePivot(); - // Keep world translation and use it to update world transform - // if the node has parent, the local transform properties (position, rotation, scale) - // will be recomputed in _matrixChanged function - // Snapping logic - if (this.snapDistance == 0) { - this.attachedNode.getWorldMatrix().getTranslationToRef(TmpVectors.Vector3[0]); - TmpVectors.Vector3[0].addToRef(event.delta, TmpVectors.Vector3[0]); - if (this.dragBehavior.validateDrag(TmpVectors.Vector3[0])) { - this.attachedNode.getWorldMatrix().addTranslationFromFloats(event.delta.x, event.delta.y, event.delta.z); - } - } - else { - currentSnapDragDistance += event.dragDistance; - if (Math.abs(currentSnapDragDistance) > this.snapDistance) { - const dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance); - currentSnapDragDistance = currentSnapDragDistance % this.snapDistance; - event.delta.normalizeToRef(tmpVector); - tmpVector.scaleInPlace(this.snapDistance * dragSteps); - this.attachedNode.getWorldMatrix().getTranslationToRef(TmpVectors.Vector3[0]); - TmpVectors.Vector3[0].addToRef(tmpVector, TmpVectors.Vector3[0]); - if (this.dragBehavior.validateDrag(TmpVectors.Vector3[0])) { - this.attachedNode.getWorldMatrix().addTranslationFromFloats(tmpVector.x, tmpVector.y, tmpVector.z); - tmpSnapEvent.snapDistance = this.snapDistance * dragSteps; - this.onSnapObservable.notifyObservers(tmpSnapEvent); - } - } - } - this._matrixChanged(); - } - }); - this.dragBehavior.onDragStartObservable.add(() => { - this._dragging = true; - }); - this.dragBehavior.onDragEndObservable.add(() => { - this._dragging = false; - }); - const light = gizmoLayer._getSharedGizmoLight(); - light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(false)); - const cache = { - gizmoMeshes: this._gizmoMesh.getChildMeshes(), - colliderMeshes: this._gizmoMesh.getChildMeshes(), - material: this._coloredMaterial, - hoverMaterial: this._hoverMaterial, - disableMaterial: this._disableMaterial, - active: false, - dragBehavior: this.dragBehavior, - }; - (_a = this._parent) === null || _a === void 0 ? void 0 : _a.addToAxisCache(this._gizmoMesh, cache); - this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => { - var _a; - if (this._customMeshSet) { - return; - } - this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1); - if (!this._parent) { - const material = cache.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial; - this._setGizmoMeshMaterial(cache.gizmoMeshes, material); - } - }); - this.dragBehavior.onEnabledObservable.add((newState) => { - this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial); - }); - } - _attachedNodeChanged(value) { - if (this.dragBehavior) { - this.dragBehavior.enabled = value ? true : false; - } - } - /** - * If the gizmo is enabled - */ - set isEnabled(value) { - this._isEnabled = value; - if (!value) { - this.attachedNode = null; - } - else { - if (this._parent) { - this.attachedNode = this._parent.attachedNode; - } - } - } - get isEnabled() { - return this._isEnabled; - } - /** - * Disposes of the gizmo - */ - dispose() { - this.onSnapObservable.clear(); - this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); - this.dragBehavior.detach(); - super.dispose(); - if (this._gizmoMesh) { - this._gizmoMesh.dispose(); - } - [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => { - if (matl) { - matl.dispose(); - } - }); - } -} -//# sourceMappingURL=planeDragGizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/positionGizmo.js - - - - - - - - -/** - * Gizmo that enables dragging a mesh along 3 axis - */ -class positionGizmo_PositionGizmo extends (/* unused pure expression or super */ null && (Gizmo)) { - get attachedMesh() { - return this._meshAttached; - } - set attachedMesh(mesh) { - this._meshAttached = mesh; - this._nodeAttached = mesh; - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - if (gizmo.isEnabled) { - gizmo.attachedMesh = mesh; - } - else { - gizmo.attachedMesh = null; - } - }); - } - get attachedNode() { - return this._nodeAttached; - } - set attachedNode(node) { - this._meshAttached = null; - this._nodeAttached = node; - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - if (gizmo.isEnabled) { - gizmo.attachedNode = node; - } - else { - gizmo.attachedNode = null; - } - }); - } - /** - * True when the mouse pointer is hovering a gizmo mesh - */ - get isHovered() { - let hovered = false; - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - hovered = hovered || gizmo.isHovered; - }); - return hovered; - } - /** - * Creates a PositionGizmo - * @param gizmoLayer The utility layer the gizmo will be added to - @param thickness display gizmo axis thickness - * @param gizmoManager - */ - constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, thickness = 1, gizmoManager) { - super(gizmoLayer); - /** - * protected variables - */ - this._meshAttached = null; - this._nodeAttached = null; - this._observables = []; - /** Node Caching for quick lookup */ - this._gizmoAxisCache = new Map(); - /** Fires an event when any of it's sub gizmos are dragged */ - this.onDragStartObservable = new Observable(); - /** Fires an event when any of it's sub gizmos are released from dragging */ - this.onDragEndObservable = new Observable(); - /** - * If set to true, planar drag is enabled - */ - this._planarGizmoEnabled = false; - this.xGizmo = new AxisDragGizmo(new Vector3(1, 0, 0), Color3.Red().scale(0.5), gizmoLayer, this, thickness); - this.yGizmo = new AxisDragGizmo(new Vector3(0, 1, 0), Color3.Green().scale(0.5), gizmoLayer, this, thickness); - this.zGizmo = new AxisDragGizmo(new Vector3(0, 0, 1), Color3.Blue().scale(0.5), gizmoLayer, this, thickness); - this.xPlaneGizmo = new PlaneDragGizmo(new Vector3(1, 0, 0), Color3.Red().scale(0.5), this.gizmoLayer, this); - this.yPlaneGizmo = new PlaneDragGizmo(new Vector3(0, 1, 0), Color3.Green().scale(0.5), this.gizmoLayer, this); - this.zPlaneGizmo = new PlaneDragGizmo(new Vector3(0, 0, 1), Color3.Blue().scale(0.5), this.gizmoLayer, this); - // Relay drag events - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - gizmo.dragBehavior.onDragStartObservable.add(() => { - this.onDragStartObservable.notifyObservers({}); - }); - gizmo.dragBehavior.onDragEndObservable.add(() => { - this.onDragEndObservable.notifyObservers({}); - }); - }); - this.attachedMesh = null; - if (gizmoManager) { - gizmoManager.addToAxisCache(this._gizmoAxisCache); - } - else { - // Only subscribe to pointer event if gizmoManager isnt - Gizmo.GizmoAxisPointerObserver(gizmoLayer, this._gizmoAxisCache); - } - } - /** - * If the planar drag gizmo is enabled - * setting this will enable/disable XY, XZ and YZ planes regardless of individual gizmo settings. - */ - set planarGizmoEnabled(value) { - this._planarGizmoEnabled = value; - [this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.isEnabled = value; - if (value) { - if (gizmo.attachedMesh) { - gizmo.attachedMesh = this.attachedMesh; - } - else { - gizmo.attachedNode = this.attachedNode; - } - } - } - }, this); - } - get planarGizmoEnabled() { - return this._planarGizmoEnabled; - } - /** - * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true) - * NOTE: This is only possible for meshes with uniform scaling, as otherwise it's not possible to decompose the rotation - */ - set updateGizmoRotationToMatchAttachedMesh(value) { - this._updateGizmoRotationToMatchAttachedMesh = value; - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.updateGizmoRotationToMatchAttachedMesh = value; - } - }); - } - get updateGizmoRotationToMatchAttachedMesh() { - return this._updateGizmoRotationToMatchAttachedMesh; - } - set updateGizmoPositionToMatchAttachedMesh(value) { - this._updateGizmoPositionToMatchAttachedMesh = value; - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.updateGizmoPositionToMatchAttachedMesh = value; - } - }); - } - get updateGizmoPositionToMatchAttachedMesh() { - return this._updateGizmoPositionToMatchAttachedMesh; - } - set anchorPoint(value) { - this._anchorPoint = value; - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - gizmo.anchorPoint = value; - }); - } - get anchorPoint() { - return this._anchorPoint; - } - /** - * Set the coordinate system to use. By default it's local. - * But it's possible for a user to tweak so its local for translation and world for rotation. - * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh` - */ - set coordinatesMode(coordinatesMode) { - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - gizmo.coordinatesMode = coordinatesMode; - }); - } - set updateScale(value) { - if (this.xGizmo) { - this.xGizmo.updateScale = value; - this.yGizmo.updateScale = value; - this.zGizmo.updateScale = value; - } - } - get updateScale() { - return this.xGizmo.updateScale; - } - /** - * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) - */ - set snapDistance(value) { - this._snapDistance = value; - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.snapDistance = value; - } - }); - } - get snapDistance() { - return this._snapDistance; - } - /** - * Ratio for the scale of the gizmo (Default: 1) - */ - set scaleRatio(value) { - this._scaleRatio = value; - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.scaleRatio = value; - } - }); - } - get scaleRatio() { - return this._scaleRatio; - } - /** - * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation - * @param mesh Axis gizmo mesh - * @param cache Gizmo axis definition used for reactive gizmo UI - */ - addToAxisCache(mesh, cache) { - this._gizmoAxisCache.set(mesh, cache); - } - /** - * Disposes of the gizmo - */ - dispose() { - [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.dispose(); - } - }); - this._observables.forEach((obs) => { - this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(obs); - }); - this.onDragStartObservable.clear(); - this.onDragEndObservable.clear(); - } - /** - * CustomMeshes are not supported by this gizmo - */ - setCustomMesh() { - 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)"); - } -} -//# sourceMappingURL=positionGizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/scaleGizmo.js - - - - - - - - - -/** - * Gizmo that enables scaling a mesh along 3 axis - */ -class scaleGizmo_ScaleGizmo extends (/* unused pure expression or super */ null && (Gizmo)) { - /** Default material used to render when gizmo is not disabled or hovered */ - get coloredMaterial() { - return this._coloredMaterial; - } - /** Material used to render when gizmo is hovered with mouse*/ - get hoverMaterial() { - return this._hoverMaterial; - } - /** Material used to render when gizmo is disabled. typically grey.*/ - get disableMaterial() { - return this._disableMaterial; - } - get attachedMesh() { - return this._meshAttached; - } - set attachedMesh(mesh) { - this._meshAttached = mesh; - this._nodeAttached = mesh; - [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => { - if (gizmo.isEnabled) { - gizmo.attachedMesh = mesh; - } - else { - gizmo.attachedMesh = null; - } - }); - } - get attachedNode() { - return this._nodeAttached; - } - set attachedNode(node) { - this._meshAttached = null; - this._nodeAttached = node; - [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => { - if (gizmo.isEnabled) { - gizmo.attachedNode = node; - } - else { - gizmo.attachedNode = null; - } - }); - } - set updateScale(value) { - if (this.xGizmo) { - this.xGizmo.updateScale = value; - this.yGizmo.updateScale = value; - this.zGizmo.updateScale = value; - } - } - get updateScale() { - return this.xGizmo.updateScale; - } - /** - * True when the mouse pointer is hovering a gizmo mesh - */ - get isHovered() { - let hovered = false; - [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => { - hovered = hovered || gizmo.isHovered; - }); - return hovered; - } - /** - * Creates a ScaleGizmo - * @param gizmoLayer The utility layer the gizmo will be added to - * @param thickness display gizmo axis thickness - * @param gizmoManager - */ - constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, thickness = 1, gizmoManager) { - super(gizmoLayer); - this._meshAttached = null; - this._nodeAttached = null; - this._sensitivity = 1; - this._observables = []; - /** Node Caching for quick lookup */ - this._gizmoAxisCache = new Map(); - /** Fires an event when any of it's sub gizmos are dragged */ - this.onDragStartObservable = new Observable(); - /** Fires an event when any of it's sub gizmos are released from dragging */ - this.onDragEndObservable = new Observable(); - this.uniformScaleGizmo = this._createUniformScaleMesh(); - this.xGizmo = new AxisScaleGizmo(new Vector3(1, 0, 0), Color3.Red().scale(0.5), gizmoLayer, this, thickness); - this.yGizmo = new AxisScaleGizmo(new Vector3(0, 1, 0), Color3.Green().scale(0.5), gizmoLayer, this, thickness); - this.zGizmo = new AxisScaleGizmo(new Vector3(0, 0, 1), Color3.Blue().scale(0.5), gizmoLayer, this, thickness); - // Relay drag events - [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => { - gizmo.dragBehavior.onDragStartObservable.add(() => { - this.onDragStartObservable.notifyObservers({}); - }); - gizmo.dragBehavior.onDragEndObservable.add(() => { - this.onDragEndObservable.notifyObservers({}); - }); - }); - this.attachedMesh = null; - this.attachedNode = null; - if (gizmoManager) { - gizmoManager.addToAxisCache(this._gizmoAxisCache); - } - else { - // Only subscribe to pointer event if gizmoManager isnt - Gizmo.GizmoAxisPointerObserver(gizmoLayer, this._gizmoAxisCache); - } - } - /** Create Geometry for Gizmo */ - _createUniformScaleMesh() { - this._coloredMaterial = new StandardMaterial("", this.gizmoLayer.utilityLayerScene); - this._coloredMaterial.diffuseColor = Color3.Gray(); - this._hoverMaterial = new StandardMaterial("", this.gizmoLayer.utilityLayerScene); - this._hoverMaterial.diffuseColor = Color3.Yellow(); - this._disableMaterial = new StandardMaterial("", this.gizmoLayer.utilityLayerScene); - this._disableMaterial.diffuseColor = Color3.Gray(); - this._disableMaterial.alpha = 0.4; - const uniformScaleGizmo = new AxisScaleGizmo(new Vector3(0, 1, 0), Color3.Gray().scale(0.5), this.gizmoLayer, this); - uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false; - uniformScaleGizmo.uniformScaling = true; - this._uniformScalingMesh = CreatePolyhedron("uniform", { type: 1 }, uniformScaleGizmo.gizmoLayer.utilityLayerScene); - this._uniformScalingMesh.scaling.scaleInPlace(0.01); - this._uniformScalingMesh.visibility = 0; - this._octahedron = CreatePolyhedron("", { type: 1 }, uniformScaleGizmo.gizmoLayer.utilityLayerScene); - this._octahedron.scaling.scaleInPlace(0.007); - this._uniformScalingMesh.addChild(this._octahedron); - uniformScaleGizmo.setCustomMesh(this._uniformScalingMesh, true); - const light = this.gizmoLayer._getSharedGizmoLight(); - light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._octahedron); - const cache = { - gizmoMeshes: [this._octahedron, this._uniformScalingMesh], - colliderMeshes: [this._uniformScalingMesh], - material: this._coloredMaterial, - hoverMaterial: this._hoverMaterial, - disableMaterial: this._disableMaterial, - active: false, - dragBehavior: uniformScaleGizmo.dragBehavior, - }; - this.addToAxisCache(uniformScaleGizmo._rootMesh, cache); - return uniformScaleGizmo; - } - set updateGizmoRotationToMatchAttachedMesh(value) { - if (!value) { - Logger.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported."); - } - else { - this._updateGizmoRotationToMatchAttachedMesh = value; - [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.updateGizmoRotationToMatchAttachedMesh = value; - } - }); - } - } - get updateGizmoRotationToMatchAttachedMesh() { - return this._updateGizmoRotationToMatchAttachedMesh; - } - set anchorPoint(value) { - this._anchorPoint = value; - [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.anchorPoint = value; - } - }); - } - get anchorPoint() { - return this._anchorPoint; - } - /** - * Set the coordinate system to use. By default it's local. - * But it's possible for a user to tweak so its local for translation and world for rotation. - * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh` - */ - set coordinatesMode(coordinatesMode) { - [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => { - gizmo.coordinatesMode = coordinatesMode; - }); - } - /** - * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) - */ - set snapDistance(value) { - this._snapDistance = value; - [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.snapDistance = value; - } - }); - } - get snapDistance() { - return this._snapDistance; - } - /** - * Ratio for the scale of the gizmo (Default: 1) - */ - set scaleRatio(value) { - this._scaleRatio = value; - [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.scaleRatio = value; - } - }); - } - get scaleRatio() { - return this._scaleRatio; - } - /** - * Sensitivity factor for dragging (Default: 1) - */ - set sensitivity(value) { - this._sensitivity = value; - [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.sensitivity = value; - } - }); - } - get sensitivity() { - return this._sensitivity; - } - /** - * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation - * @param mesh Axis gizmo mesh - * @param cache Gizmo axis definition used for reactive gizmo UI - */ - addToAxisCache(mesh, cache) { - this._gizmoAxisCache.set(mesh, cache); - } - /** - * Disposes of the gizmo - */ - dispose() { - [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.dispose(); - } - }); - this._observables.forEach((obs) => { - this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(obs); - }); - this.onDragStartObservable.clear(); - this.onDragEndObservable.clear(); - [this._uniformScalingMesh, this._octahedron].forEach((msh) => { - if (msh) { - msh.dispose(); - } - }); - [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => { - if (matl) { - matl.dispose(); - } - }); - } -} -//# sourceMappingURL=scaleGizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/gizmoManager.js - - - - - - - - - - - -/** - * Helps setup gizmo's in the scene to rotate/scale/position nodes - */ -class GizmoManager { - /** - * Utility layer that the bounding box gizmo belongs to - */ - get keepDepthUtilityLayer() { - return this._defaultKeepDepthUtilityLayer; - } - /** - * Utility layer that all gizmos besides bounding box belong to - */ - get utilityLayer() { - return this._defaultUtilityLayer; - } - /** - * True when the mouse pointer is hovering a gizmo mesh - */ - get isHovered() { - let hovered = false; - for (const key in this.gizmos) { - const gizmo = this.gizmos[key]; - if (gizmo && gizmo.isHovered) { - hovered = true; - break; - } - } - return hovered; - } - /** - * Ratio for the scale of the gizmo (Default: 1) - */ - set scaleRatio(value) { - this._scaleRatio = value; - [this.gizmos.positionGizmo, this.gizmos.rotationGizmo, this.gizmos.scaleGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.scaleRatio = value; - } - }); - } - get scaleRatio() { - return this._scaleRatio; - } - /** - * Set the coordinate system to use. By default it's local. - * But it's possible for a user to tweak so its local for translation and world for rotation. - * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh` - */ - set coordinatesMode(coordinatesMode) { - this._coordinatesMode = coordinatesMode; - [this.gizmos.positionGizmo, this.gizmos.rotationGizmo, this.gizmos.scaleGizmo].forEach((gizmo) => { - if (gizmo) { - gizmo.coordinatesMode = coordinatesMode; - } - }); - } - get coordinatesMode() { - return this._coordinatesMode; - } - /** - * Instantiates a gizmo manager - * @param _scene the scene to overlay the gizmos on top of - * @param thickness display gizmo axis thickness - * @param utilityLayer the layer where gizmos are rendered - * @param keepDepthUtilityLayer the layer where occluded gizmos are rendered - */ - constructor(_scene, thickness = 1, utilityLayer = UtilityLayerRenderer.DefaultUtilityLayer, keepDepthUtilityLayer = UtilityLayerRenderer.DefaultKeepDepthUtilityLayer) { - this._scene = _scene; - /** When true, the gizmo will be detached from the current object when a pointer down occurs with an empty picked mesh */ - this.clearGizmoOnEmptyPointerEvent = false; - /** When true (default), picking to attach a new mesh is enabled. This works in sync with inspector autopicking. */ - this.enableAutoPicking = true; - /** Fires an event when the manager is attached to a mesh */ - this.onAttachedToMeshObservable = new Observable(); - /** Fires an event when the manager is attached to a node */ - this.onAttachedToNodeObservable = new Observable(); - this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false }; - this._pointerObservers = []; - this._attachedMesh = null; - this._attachedNode = null; - this._boundingBoxColor = Color3.FromHexString("#0984e3"); - this._thickness = 1; - this._scaleRatio = 1; - this._coordinatesMode = GizmoCoordinatesMode.Local; - /** Node Caching for quick lookup */ - this._gizmoAxisCache = new Map(); - /** - * When bounding box gizmo is enabled, this can be used to track drag/end events - */ - this.boundingBoxDragBehavior = new SixDofDragBehavior(); - /** - * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null) - */ - this.attachableMeshes = null; - /** - * Array of nodes which will have the gizmo attached when a pointer selected them. If null, all nodes are attachable. (Default: null) - */ - this.attachableNodes = null; - /** - * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh/attachToNode. (Default: true) - */ - this.usePointerToAttachGizmos = true; - this._defaultUtilityLayer = utilityLayer; - this._defaultKeepDepthUtilityLayer = keepDepthUtilityLayer; - this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false; - this._thickness = thickness; - this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null }; - const attachToMeshPointerObserver = this._attachToMeshPointerObserver(_scene); - const gizmoAxisPointerObserver = Gizmo.GizmoAxisPointerObserver(this._defaultUtilityLayer, this._gizmoAxisCache); - this._pointerObservers = [attachToMeshPointerObserver, gizmoAxisPointerObserver]; - } - /** - * Subscribes to pointer down events, for attaching and detaching mesh - * @param scene The scene layer the observer will be added to - */ - _attachToMeshPointerObserver(scene) { - // Instantiate/dispose gizmos based on pointer actions - const pointerObserver = scene.onPointerObservable.add((pointerInfo) => { - if (!this.usePointerToAttachGizmos) { - return; - } - if (pointerInfo.type == PointerEventTypes.POINTERDOWN) { - if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) { - if (this.enableAutoPicking) { - let node = pointerInfo.pickInfo.pickedMesh; - if (this.attachableMeshes == null) { - // Attach to the most parent node - while (node && node.parent != null) { - node = node.parent; - } - } - else { - // Attach to the parent node that is an attachableMesh - let found = false; - this.attachableMeshes.forEach((mesh) => { - if (node && (node == mesh || node.isDescendantOf(mesh))) { - node = mesh; - found = true; - } - }); - if (!found) { - node = null; - } - } - if (node instanceof AbstractMesh) { - if (this._attachedMesh != node) { - this.attachToMesh(node); - } - } - else { - if (this.clearGizmoOnEmptyPointerEvent) { - this.attachToMesh(null); - } - } - } - } - else { - if (this.clearGizmoOnEmptyPointerEvent) { - this.attachToMesh(null); - } - } - } - }); - return pointerObserver; - } - /** - * Attaches a set of gizmos to the specified mesh - * @param mesh The mesh the gizmo's should be attached to - */ - attachToMesh(mesh) { - if (this._attachedMesh) { - this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior); - } - if (this._attachedNode) { - this._attachedNode.removeBehavior(this.boundingBoxDragBehavior); - } - this._attachedMesh = mesh; - this._attachedNode = null; - for (const key in this.gizmos) { - const gizmo = this.gizmos[key]; - if (gizmo && this._gizmosEnabled[key]) { - gizmo.attachedMesh = mesh; - } - } - if (this.boundingBoxGizmoEnabled && this._attachedMesh) { - this._attachedMesh.addBehavior(this.boundingBoxDragBehavior); - } - this.onAttachedToMeshObservable.notifyObservers(mesh); - } - /** - * Attaches a set of gizmos to the specified node - * @param node The node the gizmo's should be attached to - */ - attachToNode(node) { - if (this._attachedMesh) { - this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior); - } - if (this._attachedNode) { - this._attachedNode.removeBehavior(this.boundingBoxDragBehavior); - } - this._attachedMesh = null; - this._attachedNode = node; - for (const key in this.gizmos) { - const gizmo = this.gizmos[key]; - if (gizmo && this._gizmosEnabled[key]) { - gizmo.attachedNode = node; - } - } - if (this.boundingBoxGizmoEnabled && this._attachedNode) { - this._attachedNode.addBehavior(this.boundingBoxDragBehavior); - } - this.onAttachedToNodeObservable.notifyObservers(node); - } - /** - * If the position gizmo is enabled - */ - set positionGizmoEnabled(value) { - if (value) { - if (!this.gizmos.positionGizmo) { - this.gizmos.positionGizmo = new PositionGizmo(this._defaultUtilityLayer, this._thickness, this); - } - if (this._attachedNode) { - this.gizmos.positionGizmo.attachedNode = this._attachedNode; - } - else { - this.gizmos.positionGizmo.attachedMesh = this._attachedMesh; - } - } - else if (this.gizmos.positionGizmo) { - this.gizmos.positionGizmo.attachedNode = null; - } - this._gizmosEnabled.positionGizmo = value; - } - get positionGizmoEnabled() { - return this._gizmosEnabled.positionGizmo; - } - /** - * If the rotation gizmo is enabled - */ - set rotationGizmoEnabled(value) { - if (value) { - if (!this.gizmos.rotationGizmo) { - this.gizmos.rotationGizmo = new RotationGizmo(this._defaultUtilityLayer, 32, false, this._thickness, this); - } - if (this._attachedNode) { - this.gizmos.rotationGizmo.attachedNode = this._attachedNode; - } - else { - this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh; - } - } - else if (this.gizmos.rotationGizmo) { - this.gizmos.rotationGizmo.attachedNode = null; - } - this._gizmosEnabled.rotationGizmo = value; - } - get rotationGizmoEnabled() { - return this._gizmosEnabled.rotationGizmo; - } - /** - * If the scale gizmo is enabled - */ - set scaleGizmoEnabled(value) { - if (value) { - this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new ScaleGizmo(this._defaultUtilityLayer, this._thickness, this); - if (this._attachedNode) { - this.gizmos.scaleGizmo.attachedNode = this._attachedNode; - } - else { - this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh; - } - } - else if (this.gizmos.scaleGizmo) { - this.gizmos.scaleGizmo.attachedNode = null; - } - this._gizmosEnabled.scaleGizmo = value; - } - get scaleGizmoEnabled() { - return this._gizmosEnabled.scaleGizmo; - } - /** - * If the boundingBox gizmo is enabled - */ - set boundingBoxGizmoEnabled(value) { - if (value) { - this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer); - if (this._attachedMesh) { - this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh; - } - else { - this.gizmos.boundingBoxGizmo.attachedNode = this._attachedNode; - } - if (this._attachedMesh) { - this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior); - this._attachedMesh.addBehavior(this.boundingBoxDragBehavior); - } - else if (this._attachedNode) { - this._attachedNode.removeBehavior(this.boundingBoxDragBehavior); - this._attachedNode.addBehavior(this.boundingBoxDragBehavior); - } - } - else if (this.gizmos.boundingBoxGizmo) { - if (this._attachedMesh) { - this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior); - } - else if (this._attachedNode) { - this._attachedNode.removeBehavior(this.boundingBoxDragBehavior); - } - this.gizmos.boundingBoxGizmo.attachedNode = null; - } - this._gizmosEnabled.boundingBoxGizmo = value; - } - get boundingBoxGizmoEnabled() { - return this._gizmosEnabled.boundingBoxGizmo; - } - /** - * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation - * @param gizmoAxisCache Gizmo axis definition used for reactive gizmo UI - */ - addToAxisCache(gizmoAxisCache) { - if (gizmoAxisCache.size > 0) { - gizmoAxisCache.forEach((v, k) => { - this._gizmoAxisCache.set(k, v); - }); - } - } - /** - * Disposes of the gizmo manager - */ - dispose() { - var _a, _b; - this._pointerObservers.forEach((observer) => { - this._scene.onPointerObservable.remove(observer); - }); - for (const key in this.gizmos) { - const gizmo = this.gizmos[key]; - if (gizmo) { - gizmo.dispose(); - } - } - if (this._defaultKeepDepthUtilityLayer !== UtilityLayerRenderer._DefaultKeepDepthUtilityLayer) { - (_a = this._defaultKeepDepthUtilityLayer) === null || _a === void 0 ? void 0 : _a.dispose(); - } - if (this._defaultUtilityLayer !== UtilityLayerRenderer._DefaultUtilityLayer) { - (_b = this._defaultUtilityLayer) === null || _b === void 0 ? void 0 : _b.dispose(); - } - this.boundingBoxDragBehavior.detach(); - this.onAttachedToMeshObservable.clear(); - } -} -//# sourceMappingURL=gizmoManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/shadowLight.js - - - - - -/** - * Base implementation IShadowLight - * It groups all the common behaviour in order to reduce duplication and better follow the DRY pattern. - */ -class ShadowLight extends light_Light { - constructor() { - super(...arguments); - this._needProjectionMatrixCompute = true; - } - _setPosition(value) { - this._position = value; - } - /** - * Sets the position the shadow will be casted from. Also use as the light position for both - * point and spot lights. - */ - get position() { - return this._position; - } - /** - * Sets the position the shadow will be casted from. Also use as the light position for both - * point and spot lights. - */ - set position(value) { - this._setPosition(value); - } - _setDirection(value) { - this._direction = value; - } - /** - * In 2d mode (needCube being false), gets the direction used to cast the shadow. - * Also use as the light direction on spot and directional lights. - */ - get direction() { - return this._direction; - } - /** - * In 2d mode (needCube being false), sets the direction used to cast the shadow. - * Also use as the light direction on spot and directional lights. - */ - set direction(value) { - this._setDirection(value); - } - /** - * Gets the shadow projection clipping minimum z value. - */ - get shadowMinZ() { - return this._shadowMinZ; - } - /** - * Sets the shadow projection clipping minimum z value. - */ - set shadowMinZ(value) { - this._shadowMinZ = value; - this.forceProjectionMatrixCompute(); - } - /** - * Sets the shadow projection clipping maximum z value. - */ - get shadowMaxZ() { - return this._shadowMaxZ; - } - /** - * Gets the shadow projection clipping maximum z value. - */ - set shadowMaxZ(value) { - this._shadowMaxZ = value; - this.forceProjectionMatrixCompute(); - } - /** - * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light - * @returns true if the information has been computed, false if it does not need to (no parenting) - */ - computeTransformedInformation() { - if (this.parent && this.parent.getWorldMatrix) { - if (!this.transformedPosition) { - this.transformedPosition = math_vector_Vector3.Zero(); - } - math_vector_Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition); - // In case the direction is present. - if (this.direction) { - if (!this.transformedDirection) { - this.transformedDirection = math_vector_Vector3.Zero(); - } - math_vector_Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection); - } - return true; - } - return false; - } - /** - * Return the depth scale used for the shadow map. - * @returns the depth scale. - */ - getDepthScale() { - return 50.0; - } - /** - * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed. - * @param faceIndex The index of the face we are computed the direction to generate shadow - * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getShadowDirection(faceIndex) { - return this.transformedDirection ? this.transformedDirection : this.direction; - } - /** - * Returns the ShadowLight absolute position in the World. - * @returns the position vector in world space - */ - getAbsolutePosition() { - return this.transformedPosition ? this.transformedPosition : this.position; - } - /** - * Sets the ShadowLight direction toward the passed target. - * @param target The point to target in local space - * @returns the updated ShadowLight direction - */ - setDirectionToTarget(target) { - this.direction = math_vector_Vector3.Normalize(target.subtract(this.position)); - return this.direction; - } - /** - * Returns the light rotation in euler definition. - * @returns the x y z rotation in local space. - */ - getRotation() { - this.direction.normalize(); - const xaxis = math_vector_Vector3.Cross(this.direction, math_axis_Axis.Y); - const yaxis = math_vector_Vector3.Cross(xaxis, this.direction); - return math_vector_Vector3.RotationFromAxis(xaxis, yaxis, this.direction); - } - /** - * Returns whether or not the shadow generation require a cube texture or a 2d texture. - * @returns true if a cube texture needs to be use - */ - needCube() { - return false; - } - /** - * Detects if the projection matrix requires to be recomputed this frame. - * @returns true if it requires to be recomputed otherwise, false. - */ - needProjectionMatrixCompute() { - return this._needProjectionMatrixCompute; - } - /** - * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed. - */ - forceProjectionMatrixCompute() { - this._needProjectionMatrixCompute = true; - } - /** @internal */ - _initCache() { - super._initCache(); - this._cache.position = math_vector_Vector3.Zero(); - } - /** @internal */ - _isSynchronized() { - if (!this._cache.position.equals(this.position)) { - return false; - } - return true; - } - /** - * Computes the world matrix of the node - * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch - * @returns the world matrix - */ - computeWorldMatrix(force) { - if (!force && this.isSynchronized()) { - this._currentRenderId = this.getScene().getRenderId(); - return this._worldMatrix; - } - this._updateCache(); - this._cache.position.copyFrom(this.position); - if (!this._worldMatrix) { - this._worldMatrix = math_vector_Matrix.Identity(); - } - math_vector_Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix); - if (this.parent && this.parent.getWorldMatrix) { - this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix); - this._markSyncedWithParent(); - } - // Cache the determinant - this._worldMatrixDeterminantIsDirty = true; - return this._worldMatrix; - } - /** - * Gets the minZ used for shadow according to both the scene and the light. - * @param activeCamera The camera we are returning the min for - * @returns the depth min z - */ - getDepthMinZ(activeCamera) { - return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ; - } - /** - * Gets the maxZ used for shadow according to both the scene and the light. - * @param activeCamera The camera we are returning the max for - * @returns the depth max z - */ - getDepthMaxZ(activeCamera) { - return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ; - } - /** - * Sets the shadow projection matrix in parameter to the generated projection matrix. - * @param matrix The matrix to updated with the projection information - * @param viewMatrix The transform matrix of the light - * @param renderList The list of mesh to render in the map - * @returns The current light - */ - setShadowProjectionMatrix(matrix, viewMatrix, renderList) { - if (this.customProjectionMatrixBuilder) { - this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix); - } - else { - this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList); - } - return this; - } - /** @internal */ - _syncParentEnabledState() { - super._syncParentEnabledState(); - if (!this.parent || !this.parent.getWorldMatrix) { - this.transformedPosition = null; - this.transformedDirection = null; - } - } -} -__decorate([ - serializeAsVector3() -], ShadowLight.prototype, "position", null); -__decorate([ - serializeAsVector3() -], ShadowLight.prototype, "direction", null); -__decorate([ - serialize() -], ShadowLight.prototype, "shadowMinZ", null); -__decorate([ - serialize() -], ShadowLight.prototype, "shadowMaxZ", null); -//# sourceMappingURL=shadowLight.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/directionalLight.js - - - - - - -node_Node.AddNodeConstructor("Light_Type_1", (name, scene) => { - return () => new DirectionalLight(name, math_vector_Vector3.Zero(), scene); -}); -/** - * A directional light is defined by a direction (what a surprise!). - * The light is emitted from everywhere in the specified direction, and has an infinite range. - * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object. - * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction - */ -class DirectionalLight extends ShadowLight { - /** - * Fix frustum size for the shadow generation. This is disabled if the value is 0. - */ - get shadowFrustumSize() { - return this._shadowFrustumSize; - } - /** - * Specifies a fix frustum size for the shadow generation. - */ - set shadowFrustumSize(value) { - this._shadowFrustumSize = value; - this.forceProjectionMatrixCompute(); - } - /** - * Gets the shadow projection scale against the optimal computed one. - * 0.1 by default which means that the projection window is increase by 10% from the optimal size. - * This does not impact in fixed frustum size (shadowFrustumSize being set) - */ - get shadowOrthoScale() { - return this._shadowOrthoScale; - } - /** - * Sets the shadow projection scale against the optimal computed one. - * 0.1 by default which means that the projection window is increase by 10% from the optimal size. - * This does not impact in fixed frustum size (shadowFrustumSize being set) - */ - set shadowOrthoScale(value) { - this._shadowOrthoScale = value; - this.forceProjectionMatrixCompute(); - } - /** - * Gets or sets the orthoLeft property used to build the light frustum - */ - get orthoLeft() { - return this._orthoLeft; - } - set orthoLeft(left) { - this._orthoLeft = left; - } - /** - * Gets or sets the orthoRight property used to build the light frustum - */ - get orthoRight() { - return this._orthoRight; - } - set orthoRight(right) { - this._orthoRight = right; - } - /** - * Gets or sets the orthoTop property used to build the light frustum - */ - get orthoTop() { - return this._orthoTop; - } - set orthoTop(top) { - this._orthoTop = top; - } - /** - * Gets or sets the orthoBottom property used to build the light frustum - */ - get orthoBottom() { - return this._orthoBottom; - } - set orthoBottom(bottom) { - this._orthoBottom = bottom; - } - /** - * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3). - * The directional light is emitted from everywhere in the given direction. - * It can cast shadows. - * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction - * @param name The friendly name of the light - * @param direction The direction of the light - * @param scene The scene the light belongs to - */ - constructor(name, direction, scene) { - super(name, scene); - this._shadowFrustumSize = 0; - this._shadowOrthoScale = 0.1; - /** - * Automatically compute the projection matrix to best fit (including all the casters) - * on each frame. - */ - this.autoUpdateExtends = true; - /** - * Automatically compute the shadowMinZ and shadowMaxZ for the projection matrix to best fit (including all the casters) - * on each frame. autoUpdateExtends must be set to true for this to work - */ - this.autoCalcShadowZBounds = false; - // Cache - this._orthoLeft = Number.MAX_VALUE; - this._orthoRight = Number.MIN_VALUE; - this._orthoTop = Number.MIN_VALUE; - this._orthoBottom = Number.MAX_VALUE; - this.position = direction.scale(-1.0); - this.direction = direction; - } - /** - * Returns the string "DirectionalLight". - * @returns The class name - */ - getClassName() { - return "DirectionalLight"; - } - /** - * Returns the integer 1. - * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x - */ - getTypeID() { - return light_Light.LIGHTTYPEID_DIRECTIONALLIGHT; - } - /** - * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix. - * Returns the DirectionalLight Shadow projection matrix. - * @param matrix - * @param viewMatrix - * @param renderList - */ - _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) { - if (this.shadowFrustumSize > 0) { - this._setDefaultFixedFrustumShadowProjectionMatrix(matrix); - } - else { - this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList); - } - } - /** - * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix. - * Returns the DirectionalLight Shadow projection matrix. - * @param matrix - */ - _setDefaultFixedFrustumShadowProjectionMatrix(matrix) { - const activeCamera = this.getScene().activeCamera; - if (!activeCamera) { - return; - } - math_vector_Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix, this.getScene().getEngine().isNDCHalfZRange); - } - /** - * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix. - * Returns the DirectionalLight Shadow projection matrix. - * @param matrix - * @param viewMatrix - * @param renderList - */ - _setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList) { - const activeCamera = this.getScene().activeCamera; - if (!activeCamera) { - return; - } - // Check extends - if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) { - const tempVector3 = math_vector_Vector3.Zero(); - this._orthoLeft = Number.MAX_VALUE; - this._orthoRight = Number.MIN_VALUE; - this._orthoTop = Number.MIN_VALUE; - this._orthoBottom = Number.MAX_VALUE; - let shadowMinZ = Number.MAX_VALUE; - let shadowMaxZ = Number.MIN_VALUE; - for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) { - const mesh = renderList[meshIndex]; - if (!mesh) { - continue; - } - const boundingInfo = mesh.getBoundingInfo(); - const boundingBox = boundingInfo.boundingBox; - for (let index = 0; index < boundingBox.vectorsWorld.length; index++) { - math_vector_Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3); - if (tempVector3.x < this._orthoLeft) { - this._orthoLeft = tempVector3.x; - } - if (tempVector3.y < this._orthoBottom) { - this._orthoBottom = tempVector3.y; - } - if (tempVector3.x > this._orthoRight) { - this._orthoRight = tempVector3.x; - } - if (tempVector3.y > this._orthoTop) { - this._orthoTop = tempVector3.y; - } - if (this.autoCalcShadowZBounds) { - if (tempVector3.z < shadowMinZ) { - shadowMinZ = tempVector3.z; - } - if (tempVector3.z > shadowMaxZ) { - shadowMaxZ = tempVector3.z; - } - } - } - } - if (this.autoCalcShadowZBounds) { - this._shadowMinZ = shadowMinZ; - this._shadowMaxZ = shadowMaxZ; - } - } - const xOffset = this._orthoRight - this._orthoLeft; - const yOffset = this._orthoTop - this._orthoBottom; - const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ; - const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ; - const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer; - math_vector_Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, 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(); - } - /** - * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name. - * @param effect The effect to update - * @param lightIndex The index of the light in the effect to update - * @returns The directional light - */ - transferToEffect(effect, lightIndex) { - if (this.computeTransformedInformation()) { - this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex); - return this; - } - this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex); - return this; - } - transferToNodeMaterialEffect(effect, lightDataUniformName) { - if (this.computeTransformedInformation()) { - effect.setFloat3(lightDataUniformName, this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z); - return this; - } - effect.setFloat3(lightDataUniformName, this.direction.x, this.direction.y, this.direction.z); - return this; - } - /** - * Gets the minZ used for shadow according to both the scene and the light. - * - * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being - * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5. - * (when not using reverse depth buffer / NDC half Z range) - * @param activeCamera The camera we are returning the min for - * @returns the depth min z - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getDepthMinZ(activeCamera) { - const engine = this._scene.getEngine(); - return !engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1; - } - /** - * Gets the maxZ used for shadow according to both the scene and the light. - * - * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being - * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5. - * (when not using reverse depth buffer / NDC half Z range) - * @param activeCamera The camera we are returning the max for - * @returns the depth max z - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getDepthMaxZ(activeCamera) { - const engine = this._scene.getEngine(); - return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1; - } - /** - * Prepares the list of defines specific to the light type. - * @param defines the list of defines - * @param lightIndex defines the index of the light for the effect - */ - prepareLightSpecificDefines(defines, lightIndex) { - defines["DIRLIGHT" + lightIndex] = true; - } -} -__decorate([ - serialize() -], DirectionalLight.prototype, "shadowFrustumSize", null); -__decorate([ - serialize() -], DirectionalLight.prototype, "shadowOrthoScale", null); -__decorate([ - serialize() -], DirectionalLight.prototype, "autoUpdateExtends", void 0); -__decorate([ - serialize() -], DirectionalLight.prototype, "autoCalcShadowZBounds", void 0); -__decorate([ - serialize("orthoLeft") -], DirectionalLight.prototype, "_orthoLeft", void 0); -__decorate([ - serialize("orthoRight") -], DirectionalLight.prototype, "_orthoRight", void 0); -__decorate([ - serialize("orthoTop") -], DirectionalLight.prototype, "_orthoTop", void 0); -__decorate([ - serialize("orthoBottom") -], DirectionalLight.prototype, "_orthoBottom", void 0); -//# sourceMappingURL=directionalLight.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/hemisphereBuilder.js - - - -/** - * Creates a hemisphere mesh - * @param name defines the name of the mesh - * @param options defines the options used to create the mesh - * @param options.segments - * @param options.diameter - * @param options.sideOrientation - * @param scene defines the hosting scene - * @returns the hemisphere mesh - */ -function CreateHemisphere(name, options = {}, scene) { - if (!options.diameter) { - options.diameter = 1; - } - if (!options.segments) { - options.segments = 16; - } - const halfSphere = sphereBuilder_CreateSphere("", { slice: 0.5, diameter: options.diameter, segments: options.segments }, scene); - const disc = discBuilder_CreateDisc("", { radius: options.diameter / 2, tessellation: options.segments * 3 + (4 - options.segments) }, scene); - disc.rotation.x = -Math.PI / 2; - disc.parent = halfSphere; - const merged = mesh_Mesh.MergeMeshes([disc, halfSphere], true); - merged.name = name; - return merged; -} -/** - * Class containing static functions to help procedurally build meshes - * @deprecated use the function directly from the module - */ -const HemisphereBuilder = { - // eslint-disable-next-line @typescript-eslint/naming-convention - CreateHemisphere, -}; -/** - * Creates a hemispheric light - * @param name - * @param segments - * @param diameter - * @param scene - */ -mesh_Mesh.CreateHemisphere = (name, segments, diameter, scene) => { - const options = { - segments: segments, - diameter: diameter, - }; - return CreateHemisphere(name, options, scene); -}; -//# sourceMappingURL=hemisphereBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/spotLight.js - - - - - - - -node_Node.AddNodeConstructor("Light_Type_2", (name, scene) => { - return () => new SpotLight(name, math_vector_Vector3.Zero(), math_vector_Vector3.Zero(), 0, 0, scene); -}); -/** - * A spot light is defined by a position, a direction, an angle, and an exponent. - * These values define a cone of light starting from the position, emitting toward the direction. - * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam, - * and the exponent defines the speed of the decay of the light with distance (reach). - * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction - */ -class SpotLight extends ShadowLight { - /** - * Gets the cone angle of the spot light in Radians. - */ - get angle() { - return this._angle; - } - /** - * Sets the cone angle of the spot light in Radians. - */ - set angle(value) { - this._angle = value; - this._cosHalfAngle = Math.cos(value * 0.5); - this._projectionTextureProjectionLightDirty = true; - this.forceProjectionMatrixCompute(); - this._computeAngleValues(); - } - /** - * Only used in gltf falloff mode, this defines the angle where - * the directional falloff will start before cutting at angle which could be seen - * as outer angle. - */ - get innerAngle() { - return this._innerAngle; - } - /** - * Only used in gltf falloff mode, this defines the angle where - * the directional falloff will start before cutting at angle which could be seen - * as outer angle. - */ - set innerAngle(value) { - this._innerAngle = value; - this._computeAngleValues(); - } - /** - * Allows scaling the angle of the light for shadow generation only. - */ - get shadowAngleScale() { - return this._shadowAngleScale; - } - /** - * Allows scaling the angle of the light for shadow generation only. - */ - set shadowAngleScale(value) { - this._shadowAngleScale = value; - this.forceProjectionMatrixCompute(); - } - /** - * Allows reading the projection texture - */ - get projectionTextureMatrix() { - return this._projectionTextureMatrix; - } - /** - * Gets the near clip of the Spotlight for texture projection. - */ - get projectionTextureLightNear() { - return this._projectionTextureLightNear; - } - /** - * Sets the near clip of the Spotlight for texture projection. - */ - set projectionTextureLightNear(value) { - this._projectionTextureLightNear = value; - this._projectionTextureProjectionLightDirty = true; - } - /** - * Gets the far clip of the Spotlight for texture projection. - */ - get projectionTextureLightFar() { - return this._projectionTextureLightFar; - } - /** - * Sets the far clip of the Spotlight for texture projection. - */ - set projectionTextureLightFar(value) { - this._projectionTextureLightFar = value; - this._projectionTextureProjectionLightDirty = true; - } - /** - * Gets the Up vector of the Spotlight for texture projection. - */ - get projectionTextureUpDirection() { - return this._projectionTextureUpDirection; - } - /** - * Sets the Up vector of the Spotlight for texture projection. - */ - set projectionTextureUpDirection(value) { - this._projectionTextureUpDirection = value; - this._projectionTextureProjectionLightDirty = true; - } - /** - * Gets the projection texture of the light. - */ - get projectionTexture() { - return this._projectionTexture; - } - /** - * Sets the projection texture of the light. - */ - set projectionTexture(value) { - if (this._projectionTexture === value) { - return; - } - this._projectionTexture = value; - this._projectionTextureDirty = true; - if (this._projectionTexture && !this._projectionTexture.isReady()) { - if (SpotLight._IsProceduralTexture(this._projectionTexture)) { - this._projectionTexture.getEffect().executeWhenCompiled(() => { - this._markMeshesAsLightDirty(); - }); - } - else if (SpotLight._IsTexture(this._projectionTexture)) { - this._projectionTexture.onLoadObservable.addOnce(() => { - this._markMeshesAsLightDirty(); - }); - } - } - } - static _IsProceduralTexture(texture) { - return texture.onGeneratedObservable !== undefined; - } - static _IsTexture(texture) { - return texture.onLoadObservable !== undefined; - } - /** - * Gets or sets the light projection matrix as used by the projection texture - */ - get projectionTextureProjectionLightMatrix() { - return this._projectionTextureProjectionLightMatrix; - } - set projectionTextureProjectionLightMatrix(projection) { - this._projectionTextureProjectionLightMatrix = projection; - this._projectionTextureProjectionLightDirty = false; - this._projectionTextureDirty = true; - } - /** - * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone. - * It can cast shadows. - * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction - * @param name The light friendly name - * @param position The position of the spot light in the scene - * @param direction The direction of the light in the scene - * @param angle The cone angle of the light in Radians - * @param exponent The light decay speed with the distance from the emission spot - * @param scene The scene the lights belongs to - */ - constructor(name, position, direction, angle, exponent, scene) { - super(name, scene); - this._innerAngle = 0; - this._projectionTextureMatrix = math_vector_Matrix.Zero(); - this._projectionTextureLightNear = 1e-6; - this._projectionTextureLightFar = 1000.0; - this._projectionTextureUpDirection = math_vector_Vector3.Up(); - this._projectionTextureViewLightDirty = true; - this._projectionTextureProjectionLightDirty = true; - this._projectionTextureDirty = true; - this._projectionTextureViewTargetVector = math_vector_Vector3.Zero(); - this._projectionTextureViewLightMatrix = math_vector_Matrix.Zero(); - this._projectionTextureProjectionLightMatrix = math_vector_Matrix.Zero(); - this._projectionTextureScalingMatrix = math_vector_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); - this.position = position; - this.direction = direction; - this.angle = angle; - this.exponent = exponent; - } - /** - * Returns the string "SpotLight". - * @returns the class name - */ - getClassName() { - return "SpotLight"; - } - /** - * Returns the integer 2. - * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x - */ - getTypeID() { - return light_Light.LIGHTTYPEID_SPOTLIGHT; - } - /** - * Overrides the direction setter to recompute the projection texture view light Matrix. - * @param value - */ - _setDirection(value) { - super._setDirection(value); - this._projectionTextureViewLightDirty = true; - } - /** - * Overrides the position setter to recompute the projection texture view light Matrix. - * @param value - */ - _setPosition(value) { - super._setPosition(value); - this._projectionTextureViewLightDirty = true; - } - /** - * 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. - * Returns the SpotLight. - * @param matrix - * @param viewMatrix - * @param renderList - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) { - const activeCamera = this.getScene().activeCamera; - if (!activeCamera) { - return; - } - this._shadowAngleScale = this._shadowAngleScale || 1; - const angle = this._shadowAngleScale * this._angle; - const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ; - const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ; - const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer; - math_vector_Matrix.PerspectiveFovLHToRef(angle, 1.0, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer); - } - _computeProjectionTextureViewLightMatrix() { - this._projectionTextureViewLightDirty = false; - this._projectionTextureDirty = true; - this.getAbsolutePosition().addToRef(this.direction, this._projectionTextureViewTargetVector); - math_vector_Matrix.LookAtLHToRef(this.getAbsolutePosition(), this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix); - } - _computeProjectionTextureProjectionLightMatrix() { - this._projectionTextureProjectionLightDirty = false; - this._projectionTextureDirty = true; - const lightFar = this.projectionTextureLightFar; - const lightNear = this.projectionTextureLightNear; - const P = lightFar / (lightFar - lightNear); - const Q = -P * lightNear; - const S = 1.0 / Math.tan(this._angle / 2.0); - const A = 1.0; - math_vector_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); - } - /** - * Main function for light texture projection matrix computing. - */ - _computeProjectionTextureMatrix() { - this._projectionTextureDirty = false; - this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix); - if (this._projectionTexture instanceof texture_Texture) { - const u = this._projectionTexture.uScale / 2.0; - const v = this._projectionTexture.vScale / 2.0; - math_vector_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); - } - 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.0 / Math.max(0.001, Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle); - this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale; - } - /** - * Sets the passed Effect "effect" with the Light textures. - * @param effect The effect to update - * @param lightIndex The index of the light in the effect to update - * @returns The light - */ - transferTexturesToEffect(effect, lightIndex) { - if (this.projectionTexture && this.projectionTexture.isReady()) { - if (this._projectionTextureViewLightDirty) { - this._computeProjectionTextureViewLightMatrix(); - } - if (this._projectionTextureProjectionLightDirty) { - this._computeProjectionTextureProjectionLightMatrix(); - } - if (this._projectionTextureDirty) { - this._computeProjectionTextureMatrix(); - } - effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix); - effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture); - } - return this; - } - /** - * Sets the passed Effect object with the SpotLight transformed position (or position if not parented) and normalized direction. - * @param effect The effect to update - * @param lightIndex The index of the light in the effect to update - * @returns The spot light - */ - transferToEffect(effect, lightIndex) { - let normalizeDirection; - if (this.computeTransformedInformation()) { - this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex); - normalizeDirection = math_vector_Vector3.Normalize(this.transformedDirection); - } - else { - this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex); - normalizeDirection = math_vector_Vector3.Normalize(this.direction); - } - this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex); - this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex); - return this; - } - transferToNodeMaterialEffect(effect, lightDataUniformName) { - let normalizeDirection; - if (this.computeTransformedInformation()) { - normalizeDirection = math_vector_Vector3.Normalize(this.transformedDirection); - } - else { - normalizeDirection = math_vector_Vector3.Normalize(this.direction); - } - if (this.getScene().useRightHandedSystem) { - effect.setFloat3(lightDataUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z); - } - else { - effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z); - } - return this; - } - /** - * Disposes the light and the associated resources. - */ - dispose() { - super.dispose(); - if (this._projectionTexture) { - this._projectionTexture.dispose(); - } - } - /** - * Gets the minZ used for shadow according to both the scene and the light. - * @param activeCamera The camera we are returning the min for - * @returns the depth min z - */ - getDepthMinZ(activeCamera) { - const engine = this._scene.getEngine(); - const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ; - return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? minZ : this._scene.getEngine().isNDCHalfZRange ? 0 : minZ; - } - /** - * Gets the maxZ used for shadow according to both the scene and the light. - * @param activeCamera The camera we are returning the max for - * @returns the depth max z - */ - getDepthMaxZ(activeCamera) { - const engine = this._scene.getEngine(); - const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ; - return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : maxZ; - } - /** - * Prepares the list of defines specific to the light type. - * @param defines the list of defines - * @param lightIndex defines the index of the light for the effect - */ - prepareLightSpecificDefines(defines, lightIndex) { - defines["SPOTLIGHT" + lightIndex] = true; - defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture && this.projectionTexture.isReady() ? true : false; - } -} -__decorate([ - serialize() -], SpotLight.prototype, "angle", null); -__decorate([ - serialize() -], SpotLight.prototype, "innerAngle", null); -__decorate([ - serialize() -], SpotLight.prototype, "shadowAngleScale", null); -__decorate([ - serialize() -], SpotLight.prototype, "exponent", void 0); -__decorate([ - serialize() -], SpotLight.prototype, "projectionTextureLightNear", null); -__decorate([ - serialize() -], SpotLight.prototype, "projectionTextureLightFar", null); -__decorate([ - serialize() -], SpotLight.prototype, "projectionTextureUpDirection", null); -__decorate([ - serializeAsTexture("projectedLightTexture") -], SpotLight.prototype, "_projectionTexture", void 0); -//# sourceMappingURL=spotLight.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/lightGizmo.js - - - - - - - - - - - - - - - - -/** - * Gizmo that enables viewing a light - */ -class LightGizmo extends gizmo_Gizmo { - /** - * Creates a LightGizmo - * @param gizmoLayer The utility layer the gizmo will be added to - */ - constructor(gizmoLayer = utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer) { - super(gizmoLayer); - this._cachedPosition = new math_vector_Vector3(); - this._cachedForward = new math_vector_Vector3(0, 0, 1); - this._pointerObserver = null; - /** - * Event that fires each time the gizmo is clicked - */ - this.onClickedObservable = new observable_Observable(); - this._light = null; - this.attachedMesh = new abstractMesh_AbstractMesh("", this.gizmoLayer.utilityLayerScene); - this._attachedMeshParent = new transformNode_TransformNode("parent", this.gizmoLayer.utilityLayerScene); - this.attachedMesh.parent = this._attachedMeshParent; - this._material = new standardMaterial_StandardMaterial("light", this.gizmoLayer.utilityLayerScene); - this._material.diffuseColor = new math_color_Color3(0.5, 0.5, 0.5); - this._material.specularColor = new math_color_Color3(0.1, 0.1, 0.1); - this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => { - if (!this._light) { - return; - } - this._isHovered = !!(pointerInfo.pickInfo && this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1); - if (this._isHovered && pointerInfo.event.button === 0) { - this.onClickedObservable.notifyObservers(this._light); - } - }, pointerEvents_PointerEventTypes.POINTERDOWN); - } - /** - * Override attachedNode because lightgizmo only support attached mesh - * It will return the attached mesh (if any) and setting an attached node will log - * a warning - */ - get attachedNode() { - return this.attachedMesh; - } - set attachedNode(value) { - console.warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead."); - } - /** - * The light that the gizmo is attached to - */ - set light(light) { - this._light = light; - if (light) { - // Create the mesh for the given light type - if (this._lightMesh) { - this._lightMesh.dispose(); - } - if (light instanceof HemisphericLight) { - this._lightMesh = LightGizmo._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene); - } - else if (light instanceof DirectionalLight) { - this._lightMesh = LightGizmo._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene); - } - else if (light instanceof SpotLight) { - this._lightMesh = LightGizmo._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene); - } - else { - this._lightMesh = LightGizmo._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene); - } - this._lightMesh.getChildMeshes(false).forEach((m) => { - m.material = this._material; - }); - this._lightMesh.parent = this._rootMesh; - // Add lighting to the light gizmo - const gizmoLight = this.gizmoLayer._getSharedGizmoLight(); - gizmoLight.includedOnlyMeshes = gizmoLight.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(false)); - this._lightMesh.rotationQuaternion = new math_vector_Quaternion(); - if (!this.attachedMesh.reservedDataStore) { - this.attachedMesh.reservedDataStore = {}; - } - this.attachedMesh.reservedDataStore.lightGizmo = this; - if (light.parent) { - this._attachedMeshParent.freezeWorldMatrix(light.parent.getWorldMatrix()); - } - // Get update position and direction if the light has it - if (light.position) { - this.attachedMesh.position.copyFrom(light.position); - this.attachedMesh.computeWorldMatrix(true); - this._cachedPosition.copyFrom(this.attachedMesh.position); - } - if (light.direction) { - this.attachedMesh.setDirection(light.direction); - this.attachedMesh.computeWorldMatrix(true); - const forward = this._getMeshForward(); - this._cachedForward.copyFrom(forward); - } - this._update(); - } - } - get light() { - return this._light; - } - /** - * Gets the material used to render the light gizmo - */ - get material() { - return this._material; - } - /** - * @internal - * returns mesh forward - */ - _getMeshForward() { - let forward = this.attachedMesh.forward; - if (this.attachedMesh.getScene().useRightHandedSystem) { - forward.negateToRef(math_vector_TmpVectors.Vector3[0]); - forward = math_vector_TmpVectors.Vector3[0]; - } - return forward; - } - /** - * @internal - * Updates the gizmo to match the attached mesh's position/rotation - */ - _update() { - super._update(); - if (!this._light) { - return; - } - if (this._light.parent) { - this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()); - } - // For light position and direction, a dirty flag is set to true in the setter - // It means setting values individually or copying values will not call setter and - // dirty flag will not be set to true. Hence creating a new Vector3. - if (this._light.position) { - // If the gizmo is moved update the light otherwise update the gizmo to match the light - if (!this.attachedMesh.position.equals(this._cachedPosition)) { - // update light to match gizmo - const position = this.attachedMesh.position; - this._light.position = new math_vector_Vector3(position.x, position.y, position.z); - this._cachedPosition.copyFrom(this.attachedMesh.position); - } - else { - // update gizmo to match light - this.attachedMesh.position.copyFrom(this._light.position); - this.attachedMesh.computeWorldMatrix(true); - this._cachedPosition.copyFrom(this.attachedMesh.position); - } - } - if (this._light.direction) { - // If the gizmo is moved update the light otherwise update the gizmo to match the light - const forward = this._getMeshForward(); - if (math_vector_Vector3.DistanceSquared(forward, this._cachedForward) > 0.0001) { - // update light to match gizmo - const direction = forward; - this._light.direction = new math_vector_Vector3(direction.x, direction.y, direction.z); - this._cachedForward.copyFrom(forward); - } - else if (math_vector_Vector3.DistanceSquared(forward, this._light.direction) > 0.0001) { - // update gizmo to match light - this.attachedMesh.setDirection(this._light.direction); - this.attachedMesh.computeWorldMatrix(true); - this._cachedForward.copyFrom(forward); - } - } - } - /** - * Disposes of the light gizmo - */ - dispose() { - this.onClickedObservable.clear(); - this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); - this._material.dispose(); - super.dispose(); - this._attachedMeshParent.dispose(); - } - static _CreateHemisphericLightMesh(scene) { - const root = new mesh_Mesh("hemisphereLight", scene); - const hemisphere = CreateHemisphere(root.name, { segments: 10, diameter: 1 }, scene); - hemisphere.position.z = -0.15; - hemisphere.rotation.x = Math.PI / 2; - hemisphere.parent = root; - const lines = this._CreateLightLines(3, scene); - lines.parent = root; - root.scaling.scaleInPlace(LightGizmo._Scale); - root.rotation.x = Math.PI / 2; - return root; - } - static _CreatePointLightMesh(scene) { - const root = new mesh_Mesh("pointLight", scene); - const sphere = sphereBuilder_CreateSphere(root.name, { segments: 10, diameter: 1 }, scene); - sphere.rotation.x = Math.PI / 2; - sphere.parent = root; - const lines = this._CreateLightLines(5, scene); - lines.parent = root; - root.scaling.scaleInPlace(LightGizmo._Scale); - root.rotation.x = Math.PI / 2; - return root; - } - static _CreateSpotLightMesh(scene) { - const root = new mesh_Mesh("spotLight", scene); - const sphere = sphereBuilder_CreateSphere(root.name, { segments: 10, diameter: 1 }, scene); - sphere.parent = root; - const hemisphere = CreateHemisphere(root.name, { segments: 10, diameter: 2 }, scene); - hemisphere.parent = root; - hemisphere.rotation.x = -Math.PI / 2; - const lines = this._CreateLightLines(2, scene); - lines.parent = root; - root.scaling.scaleInPlace(LightGizmo._Scale); - root.rotation.x = Math.PI / 2; - return root; - } - static _CreateDirectionalLightMesh(scene) { - const root = new mesh_Mesh("directionalLight", scene); - const mesh = new mesh_Mesh(root.name, scene); - mesh.parent = root; - const sphere = sphereBuilder_CreateSphere(root.name, { diameter: 1.2, segments: 10 }, scene); - sphere.parent = mesh; - const line = cylinderBuilder_CreateCylinder(root.name, { - updatable: false, - height: 6, - diameterTop: 0.3, - diameterBottom: 0.3, - tessellation: 6, - subdivisions: 1, - }, scene); - line.parent = mesh; - let left = line.clone(root.name); - left.scaling.y = 0.5; - left.position.x += 1.25; - let right = line.clone(root.name); - right.scaling.y = 0.5; - right.position.x += -1.25; - const arrowHead = cylinderBuilder_CreateCylinder(root.name, { - updatable: false, - height: 1, - diameterTop: 0, - diameterBottom: 0.6, - tessellation: 6, - subdivisions: 1, - }, scene); - arrowHead.position.y += 3; - arrowHead.parent = mesh; - left = arrowHead.clone(root.name); - left.position.y = 1.5; - left.position.x += 1.25; - right = arrowHead.clone(root.name); - right.position.y = 1.5; - right.position.x += -1.25; - mesh.scaling.scaleInPlace(LightGizmo._Scale); - mesh.rotation.z = Math.PI / 2; - mesh.rotation.y = Math.PI / 2; - return root; - } -} -// Static helper methods -LightGizmo._Scale = 0.007; -/** - * Creates the lines for a light mesh - * @param levels - * @param scene - */ -LightGizmo._CreateLightLines = (levels, scene) => { - const distFromSphere = 1.2; - const root = new mesh_Mesh("root", scene); - root.rotation.x = Math.PI / 2; - // Create the top line, this will be cloned for all other lines - const linePivot = new mesh_Mesh("linePivot", scene); - linePivot.parent = root; - const line = cylinderBuilder_CreateCylinder("line", { - updatable: false, - height: 2, - diameterTop: 0.2, - diameterBottom: 0.3, - tessellation: 6, - subdivisions: 1, - }, scene); - line.position.y = line.scaling.y / 2 + distFromSphere; - line.parent = linePivot; - if (levels < 2) { - return linePivot; - } - for (let i = 0; i < 4; i++) { - const l = linePivot.clone("lineParentClone"); - l.rotation.z = Math.PI / 4; - l.rotation.y = Math.PI / 2 + (Math.PI / 2) * i; - l.getChildMeshes()[0].scaling.y = 0.5; - l.getChildMeshes()[0].scaling.x = l.getChildMeshes()[0].scaling.z = 0.8; - l.getChildMeshes()[0].position.y = l.getChildMeshes()[0].scaling.y / 2 + distFromSphere; - } - if (levels < 3) { - return root; - } - for (let i = 0; i < 4; i++) { - const l = linePivot.clone("linePivotClone"); - l.rotation.z = Math.PI / 2; - l.rotation.y = (Math.PI / 2) * i; - } - if (levels < 4) { - return root; - } - for (let i = 0; i < 4; i++) { - const l = linePivot.clone("linePivotClone"); - l.rotation.z = Math.PI + Math.PI / 4; - l.rotation.y = Math.PI / 2 + (Math.PI / 2) * i; - l.getChildMeshes()[0].scaling.y = 0.5; - l.getChildMeshes()[0].scaling.x = l.getChildMeshes()[0].scaling.z = 0.8; - l.getChildMeshes()[0].position.y = l.getChildMeshes()[0].scaling.y / 2 + distFromSphere; - } - if (levels < 5) { - return root; - } - const l = linePivot.clone("linePivotClone"); - l.rotation.z = Math.PI; - return root; -}; -//# sourceMappingURL=lightGizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/cameraGizmo.js - - - - - - - - - - - - -/** - * Gizmo that enables viewing a camera - */ -class CameraGizmo extends gizmo_Gizmo { - /** - * Creates a CameraGizmo - * @param gizmoLayer The utility layer the gizmo will be added to - */ - constructor(gizmoLayer = utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer) { - super(gizmoLayer); - this._pointerObserver = null; - /** - * Event that fires each time the gizmo is clicked - */ - this.onClickedObservable = new observable_Observable(); - this._camera = null; - this._invProjection = new math_vector_Matrix(); - this._material = new standardMaterial_StandardMaterial("cameraGizmoMaterial", this.gizmoLayer.utilityLayerScene); - this._material.diffuseColor = new math_color_Color3(0.5, 0.5, 0.5); - this._material.specularColor = new math_color_Color3(0.1, 0.1, 0.1); - this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => { - if (!this._camera) { - return; - } - this._isHovered = !!(pointerInfo.pickInfo && this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1); - if (this._isHovered && pointerInfo.event.button === 0) { - this.onClickedObservable.notifyObservers(this._camera); - } - }, pointerEvents_PointerEventTypes.POINTERDOWN); - } - /** Gets or sets a boolean indicating if frustum lines must be rendered (true by default)) */ - get displayFrustum() { - return this._cameraLinesMesh.isEnabled(); - } - set displayFrustum(value) { - this._cameraLinesMesh.setEnabled(value); - } - /** - * The camera that the gizmo is attached to - */ - set camera(camera) { - this._camera = camera; - this.attachedNode = camera; - if (camera) { - // Create the mesh for the given camera - if (this._cameraMesh) { - this._cameraMesh.dispose(); - } - if (this._cameraLinesMesh) { - this._cameraLinesMesh.dispose(); - } - this._cameraMesh = CameraGizmo._CreateCameraMesh(this.gizmoLayer.utilityLayerScene); - this._cameraLinesMesh = CameraGizmo._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene); - this._cameraMesh.getChildMeshes(false).forEach((m) => { - m.material = this._material; - }); - this._cameraMesh.parent = this._rootMesh; - this._cameraLinesMesh.parent = this._rootMesh; - if (this.gizmoLayer.utilityLayerScene.activeCamera && this.gizmoLayer.utilityLayerScene.activeCamera.maxZ < camera.maxZ * 1.5) { - this.gizmoLayer.utilityLayerScene.activeCamera.maxZ = camera.maxZ * 1.5; - } - if (!this.attachedNode.reservedDataStore) { - this.attachedNode.reservedDataStore = {}; - } - this.attachedNode.reservedDataStore.cameraGizmo = this; - // Add lighting to the camera gizmo - const gizmoLight = this.gizmoLayer._getSharedGizmoLight(); - gizmoLight.includedOnlyMeshes = gizmoLight.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(false)); - this._update(); - } - } - get camera() { - return this._camera; - } - /** - * Gets the material used to render the camera gizmo - */ - get material() { - return this._material; - } - /** - * @internal - * Updates the gizmo to match the attached mesh's position/rotation - */ - _update() { - super._update(); - if (!this._camera) { - return; - } - // frustum matrix - this._camera.getProjectionMatrix().invertToRef(this._invProjection); - this._cameraLinesMesh.setPivotMatrix(this._invProjection, false); - 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; - // take care of coordinate system in camera scene to properly display the mesh with the good Y axis orientation in this scene - this._cameraMesh.parent = null; - this._cameraMesh.rotation.y = Math.PI * 0.5 * (this._camera.getScene().useRightHandedSystem ? 1 : -1); - this._cameraMesh.parent = this._rootMesh; - } - /** - * Disposes of the camera gizmo - */ - dispose() { - this.onClickedObservable.clear(); - this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); - if (this._cameraMesh) { - this._cameraMesh.dispose(); - } - if (this._cameraLinesMesh) { - this._cameraLinesMesh.dispose(); - } - this._material.dispose(); - super.dispose(); - } - static _CreateCameraMesh(scene) { - const root = new mesh_Mesh("rootCameraGizmo", scene); - const mesh = new mesh_Mesh(root.name, scene); - mesh.parent = root; - const box = boxBuilder_CreateBox(root.name, { width: 1.0, height: 0.8, depth: 0.5 }, scene); - box.parent = mesh; - const cyl1 = cylinderBuilder_CreateCylinder(root.name, { height: 0.5, diameterTop: 0.8, diameterBottom: 0.8 }, scene); - cyl1.parent = mesh; - cyl1.position.y = 0.3; - cyl1.position.x = -0.6; - cyl1.rotation.x = Math.PI * 0.5; - const cyl2 = cylinderBuilder_CreateCylinder(root.name, { height: 0.5, diameterTop: 0.6, diameterBottom: 0.6 }, scene); - cyl2.parent = mesh; - cyl2.position.y = 0.5; - cyl2.position.x = 0.4; - cyl2.rotation.x = Math.PI * 0.5; - const cyl3 = cylinderBuilder_CreateCylinder(root.name, { height: 0.5, diameterTop: 0.5, diameterBottom: 0.5 }, scene); - cyl3.parent = mesh; - cyl3.position.y = 0.0; - cyl3.position.x = 0.6; - cyl3.rotation.z = Math.PI * 0.5; - root.scaling.scaleInPlace(CameraGizmo._Scale); - mesh.position.x = -0.9; - return root; - } - static _CreateCameraFrustum(scene) { - const root = new mesh_Mesh("rootCameraGizmo", scene); - const mesh = new mesh_Mesh(root.name, scene); - mesh.parent = root; - for (let y = 0; y < 4; y += 2) { - for (let x = 0; x < 4; x += 2) { - let line = linesBuilder_CreateLines("lines", { points: [new math_vector_Vector3(-1 + x, -1 + y, -1), new math_vector_Vector3(-1 + x, -1 + y, 1)] }, scene); - line.parent = mesh; - line.alwaysSelectAsActiveMesh = true; - line.isPickable = false; - line = linesBuilder_CreateLines("lines", { points: [new math_vector_Vector3(-1, -1 + x, -1 + y), new math_vector_Vector3(1, -1 + x, -1 + y)] }, scene); - line.parent = mesh; - line.alwaysSelectAsActiveMesh = true; - line.isPickable = false; - line = linesBuilder_CreateLines("lines", { points: [new math_vector_Vector3(-1 + x, -1, -1 + y), new math_vector_Vector3(-1 + x, 1, -1 + y)] }, scene); - line.parent = mesh; - line.alwaysSelectAsActiveMesh = true; - line.isPickable = false; - } - } - return root; - } -} -// Static helper methods -CameraGizmo._Scale = 0.05; -//# sourceMappingURL=cameraGizmo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Gizmos/index.js - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVaryingDeclaration.js -// Do not edit. - -const kernelBlurVaryingDeclaration_name = "kernelBlurVaryingDeclaration"; -const kernelBlurVaryingDeclaration_shader = `varying vec2 sampleCoord{X};`; -// Sideeffect -ShaderStore.IncludesShadersStore[kernelBlurVaryingDeclaration_name] = kernelBlurVaryingDeclaration_shader; -/** @internal */ -const kernelBlurVaryingDeclaration = { name: kernelBlurVaryingDeclaration_name, shader: kernelBlurVaryingDeclaration_shader }; -//# sourceMappingURL=kernelBlurVaryingDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/packingFunctions.js -// Do not edit. - -const packingFunctions_name = "packingFunctions"; -const packingFunctions_shader = `vec4 pack(float depth) -{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} -float unpack(vec4 color) -{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`; -// Sideeffect -ShaderStore.IncludesShadersStore[packingFunctions_name] = packingFunctions_shader; -/** @internal */ -const packingFunctions = { name: packingFunctions_name, shader: packingFunctions_shader }; -//# sourceMappingURL=packingFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment.js -// Do not edit. - -const kernelBlurFragment_name = "kernelBlurFragment"; -const kernelBlurFragment_shader = `#ifdef DOF -factor=sampleCoC(sampleCoord{X}); -computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; -#else -computedWeight=KERNEL_WEIGHT{X}; -#endif -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; -#else -blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[kernelBlurFragment_name] = kernelBlurFragment_shader; -/** @internal */ -const kernelBlurFragment = { name: kernelBlurFragment_name, shader: kernelBlurFragment_shader }; -//# sourceMappingURL=kernelBlurFragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment2.js -// Do not edit. - -const kernelBlurFragment2_name = "kernelBlurFragment2"; -const kernelBlurFragment2_shader = `#ifdef DOF -factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; -#else -computedWeight=KERNEL_DEP_WEIGHT{X}; -#endif -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; -#else -blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[kernelBlurFragment2_name] = kernelBlurFragment2_shader; -/** @internal */ -const kernelBlurFragment2 = { name: kernelBlurFragment2_name, shader: kernelBlurFragment2_shader }; -//# sourceMappingURL=kernelBlurFragment2.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/kernelBlur.fragment.js -// Do not edit. - - - - - -const kernelBlur_fragment_name = "kernelBlurPixelShader"; -const kernelBlur_fragment_shader = `uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; -#ifdef DOF -uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } -#endif -#include<kernelBlurVaryingDeclaration>[0..varyingCount] -#ifdef PACKEDFLOAT -#include<packingFunctions> -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float computedWeight=0.0; -#ifdef PACKEDFLOAT -float blend=0.; -#else -vec4 blend=vec4(0.); -#endif -#ifdef DOF -float sumOfWeights=CENTER_WEIGHT; -float factor=0.0; -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; -#else -blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; -#endif -#endif -#include<kernelBlurFragment>[0..varyingCount] -#include<kernelBlurFragment2>[0..depCount] -#ifdef PACKEDFLOAT -gl_FragColor=pack(blend); -#else -gl_FragColor=blend; -#endif -#ifdef DOF -gl_FragColor/=sumOfWeights; -#endif -}`; -// Sideeffect -ShaderStore.ShadersStore[kernelBlur_fragment_name] = kernelBlur_fragment_shader; -/** @internal */ -const kernelBlurPixelShader = { name: kernelBlur_fragment_name, shader: kernelBlur_fragment_shader }; -//# sourceMappingURL=kernelBlur.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVertex.js -// Do not edit. - -const kernelBlurVertex_name = "kernelBlurVertex"; -const kernelBlurVertex_shader = `sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};`; -// Sideeffect -ShaderStore.IncludesShadersStore[kernelBlurVertex_name] = kernelBlurVertex_shader; -/** @internal */ -const kernelBlurVertex = { name: kernelBlurVertex_name, shader: kernelBlurVertex_shader }; -//# sourceMappingURL=kernelBlurVertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/kernelBlur.vertex.js -// Do not edit. - - - -const kernelBlur_vertex_name = "kernelBlurVertexShader"; -const kernelBlur_vertex_shader = `attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; -#include<kernelBlurVaryingDeclaration>[0..varyingCount] -const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -sampleCenter=(position*madd+madd); -#include<kernelBlurVertex>[0..varyingCount] -gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[kernelBlur_vertex_name] = kernelBlur_vertex_shader; -/** @internal */ -const kernelBlurVertexShader = { name: kernelBlur_vertex_name, shader: kernelBlur_vertex_shader }; -//# sourceMappingURL=kernelBlur.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/blurPostProcess.js - - - - - - - - -/** - * The Blur Post Process which blurs an image based on a kernel and direction. - * Can be used twice in x and y directions to perform a gaussian blur in two passes. - */ -class BlurPostProcess extends postProcess_PostProcess { - /** - * Sets the length in pixels of the blur sample region - */ - set kernel(v) { - if (this._idealKernel === v) { - return; - } - v = Math.max(v, 1); - this._idealKernel = v; - this._kernel = this._nearestBestKernel(v); - if (!this._blockCompilation) { - this._updateParameters(); - } - } - /** - * Gets the length in pixels of the blur sample region - */ - get kernel() { - return this._idealKernel; - } - /** - * Sets whether or not the blur needs to unpack/repack floats - */ - set packedFloat(v) { - if (this._packedFloat === v) { - return; - } - this._packedFloat = v; - if (!this._blockCompilation) { - this._updateParameters(); - } - } - /** - * Gets whether or not the blur is unpacking/repacking floats - */ - get packedFloat() { - return this._packedFloat; - } - /** - * Gets a string identifying the name of the class - * @returns "BlurPostProcess" string - */ - getClassName() { - return "BlurPostProcess"; - } - /** - * Creates a new instance BlurPostProcess - * @param name The name of the effect. - * @param direction The direction in which to blur the image. - * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it. - * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size) - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @param defines - * @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) - * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA) - */ - constructor(name, direction, kernel, options, camera, samplingMode = texture_Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = 0, defines = "", _blockCompilation = false, textureFormat = 5) { - super(name, "kernelBlur", ["delta", "direction"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true, textureFormat); - this._blockCompilation = _blockCompilation; - this._packedFloat = false; - this._staticDefines = ""; - this._staticDefines = defines; - this.direction = direction; - this.onApplyObservable.add((effect) => { - if (this._outputTexture) { - effect.setFloat2("delta", (1 / this._outputTexture.width) * this.direction.x, (1 / this._outputTexture.height) * this.direction.y); - } - else { - effect.setFloat2("delta", (1 / this.width) * this.direction.x, (1 / this.height) * this.direction.y); - } - }); - this.kernel = kernel; - } - /** - * Updates the effect with the current post process compile time values and recompiles the shader. - * @param defines Define statements that should be added at the beginning of the shader. (default: null) - * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) - * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) - * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx - * @param onCompiled Called when the shader has been compiled. - * @param onError Called if there is an error when compiling a shader. - */ - updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError) { - this._updateParameters(onCompiled, onError); - } - _updateParameters(onCompiled, onError) { - // Generate sampling offsets and weights - const N = this._kernel; - const centerIndex = (N - 1) / 2; - // Generate Gaussian sampling weights over kernel - let offsets = []; - let weights = []; - let totalWeight = 0; - for (let i = 0; i < N; i++) { - const u = i / (N - 1); - const w = this._gaussianWeight(u * 2.0 - 1); - offsets[i] = i - centerIndex; - weights[i] = w; - totalWeight += w; - } - // Normalize weights - for (let i = 0; i < weights.length; i++) { - weights[i] /= totalWeight; - } - // Optimize: combine samples to take advantage of hardware linear sampling - // Walk from left to center, combining pairs (symmetrically) - const linearSamplingWeights = []; - const linearSamplingOffsets = []; - const linearSamplingMap = []; - for (let i = 0; i <= centerIndex; i += 2) { - const j = Math.min(i + 1, Math.floor(centerIndex)); - const singleCenterSample = i === j; - if (singleCenterSample) { - linearSamplingMap.push({ o: offsets[i], w: weights[i] }); - } - else { - const sharedCell = j === centerIndex; - const weightLinear = weights[i] + weights[j] * (sharedCell ? 0.5 : 1); - const offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]); - if (offsetLinear === 0) { - linearSamplingMap.push({ o: offsets[i], w: weights[i] }); - linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] }); - } - else { - linearSamplingMap.push({ o: offsetLinear, w: weightLinear }); - linearSamplingMap.push({ o: -offsetLinear, w: weightLinear }); - } - } - } - for (let i = 0; i < linearSamplingMap.length; i++) { - linearSamplingOffsets[i] = linearSamplingMap[i].o; - linearSamplingWeights[i] = linearSamplingMap[i].w; - } - // Replace with optimized - offsets = linearSamplingOffsets; - weights = linearSamplingWeights; - // Generate shaders - const maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors; - const freeVaryingVec2 = Math.max(maxVaryingRows, 0) - 1; // Because of sampleCenter - let varyingCount = Math.min(offsets.length, freeVaryingVec2); - let defines = ""; - defines += this._staticDefines; - // The DOF fragment should ignore the center pixel when looping as it is handled manually in the fragment shader. - if (this._staticDefines.indexOf("DOF") != -1) { - defines += `#define CENTER_WEIGHT ${this._glslFloat(weights[varyingCount - 1])}\n`; - varyingCount--; - } - for (let i = 0; i < varyingCount; i++) { - defines += `#define KERNEL_OFFSET${i} ${this._glslFloat(offsets[i])}\n`; - defines += `#define KERNEL_WEIGHT${i} ${this._glslFloat(weights[i])}\n`; - } - let depCount = 0; - for (let i = freeVaryingVec2; i < offsets.length; i++) { - defines += `#define KERNEL_DEP_OFFSET${depCount} ${this._glslFloat(offsets[i])}\n`; - defines += `#define KERNEL_DEP_WEIGHT${depCount} ${this._glslFloat(weights[i])}\n`; - depCount++; - } - if (this.packedFloat) { - defines += `#define PACKEDFLOAT 1`; - } - this._blockCompilation = false; - super.updateEffect(defines, null, null, { - varyingCount: varyingCount, - depCount: depCount, - }, onCompiled, onError); - } - /** - * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13. - * Other odd kernels optimize correctly but require proportionally more samples, even kernels are - * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we - * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard. - * The gaps between physical kernels are compensated for in the weighting of the samples - * @param idealKernel Ideal blur kernel. - * @returns Nearest best kernel. - */ - _nearestBestKernel(idealKernel) { - const v = Math.round(idealKernel); - for (const k of [v, v - 1, v + 1, v - 2, v + 2]) { - if (k % 2 !== 0 && Math.floor(k / 2) % 2 === 0 && k > 0) { - return Math.max(k, 3); - } - } - return Math.max(v, 3); - } - /** - * Calculates the value of a Gaussian distribution with sigma 3 at a given point. - * @param x The point on the Gaussian distribution to sample. - * @returns the value of the Gaussian function at x. - */ - _gaussianWeight(x) { - //reference: Engines/ImageProcessingBlur.cpp #dcc760 - // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1], - // so we truncate at three standard deviations by setting stddev (sigma) to 1/3. - // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is - // truncated at around 1.3% of peak strength. - //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size - const sigma = 1 / 3; - const denominator = Math.sqrt(2.0 * Math.PI) * sigma; - const exponent = -((x * x) / (2.0 * sigma * sigma)); - const weight = (1.0 / denominator) * Math.exp(exponent); - return weight; - } - /** - * Generates a string that can be used as a floating point number in GLSL. - * @param x Value to print. - * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s). - * @returns GLSL float string. - */ - _glslFloat(x, decimalFigures = 8) { - return x.toFixed(decimalFigures).replace(/0+$/, ""); - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new BlurPostProcess(parsedPostProcess.name, parsedPostProcess.direction, parsedPostProcess.kernel, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, undefined, false); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serialize("kernel") -], BlurPostProcess.prototype, "_kernel", void 0); -__decorate([ - serialize("packedFloat") -], BlurPostProcess.prototype, "_packedFloat", void 0); -__decorate([ - serializeAsVector2() -], BlurPostProcess.prototype, "direction", void 0); -RegisterClass("BABYLON.BlurPostProcess", BlurPostProcess); -//# sourceMappingURL=blurPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/mirrorTexture.js - - - - - - -/** - * Mirror texture can be used to simulate the view from a mirror in a scene. - * It will dynamically be rendered every frame to adapt to the camera point of view. - * You can then easily use it as a reflectionTexture on a flat surface. - * In case the surface is not a plane, please consider relying on reflection probes. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#mirrortexture - */ -class MirrorTexture extends renderTargetTexture_RenderTargetTexture { - /** - * Define the blur ratio used to blur the reflection if needed. - */ - set blurRatio(value) { - if (this._blurRatio === value) { - return; - } - this._blurRatio = value; - this._preparePostProcesses(); - } - get blurRatio() { - return this._blurRatio; - } - /** - * Define the adaptive blur kernel used to blur the reflection if needed. - * This will autocompute the closest best match for the `blurKernel` - */ - set adaptiveBlurKernel(value) { - this._adaptiveBlurKernel = value; - this._autoComputeBlurKernel(); - } - /** - * Define the blur kernel used to blur the reflection if needed. - * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. - */ - set blurKernel(value) { - this.blurKernelX = value; - this.blurKernelY = value; - } - /** - * Define the blur kernel on the X Axis used to blur the reflection if needed. - * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. - */ - set blurKernelX(value) { - if (this._blurKernelX === value) { - return; - } - this._blurKernelX = value; - this._preparePostProcesses(); - } - get blurKernelX() { - return this._blurKernelX; - } - /** - * Define the blur kernel on the Y Axis used to blur the reflection if needed. - * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. - */ - set blurKernelY(value) { - if (this._blurKernelY === value) { - return; - } - this._blurKernelY = value; - this._preparePostProcesses(); - } - get blurKernelY() { - return this._blurKernelY; - } - _autoComputeBlurKernel() { - const engine = this.getScene().getEngine(); - const dw = this.getRenderWidth() / engine.getRenderWidth(); - const dh = this.getRenderHeight() / engine.getRenderHeight(); - this.blurKernelX = this._adaptiveBlurKernel * dw; - this.blurKernelY = this._adaptiveBlurKernel * dh; - } - _onRatioRescale() { - if (this._sizeRatio) { - this.resize(this._initialSizeParameter); - if (!this._adaptiveBlurKernel) { - this._preparePostProcesses(); - } - } - if (this._adaptiveBlurKernel) { - this._autoComputeBlurKernel(); - } - } - _updateGammaSpace() { - const scene = this.getScene(); - if (!scene) { - return; - } - this.gammaSpace = !scene.imageProcessingConfiguration.isEnabled || !scene.imageProcessingConfiguration.applyByPostProcess; - } - /** - * Instantiates a Mirror Texture. - * Mirror texture can be used to simulate the view from a mirror in a scene. - * It will dynamically be rendered every frame to adapt to the camera point of view. - * You can then easily use it as a reflectionTexture on a flat surface. - * In case the surface is not a plane, please consider relying on reflection probes. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#mirrors - * @param name - * @param size - * @param scene - * @param generateMipMaps - * @param type - * @param samplingMode - * @param generateDepthBuffer - */ - constructor(name, size, scene, generateMipMaps, type = 0, samplingMode = texture_Texture.BILINEAR_SAMPLINGMODE, generateDepthBuffer = true) { - super(name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer); - /** - * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector. - * It is possible to directly set the mirrorPlane 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 mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#mirrors - */ - this.mirrorPlane = new math_plane_Plane(0, 1, 0, 1); - this._transformMatrix = math_vector_Matrix.Zero(); - this._mirrorMatrix = math_vector_Matrix.Zero(); - this._adaptiveBlurKernel = 0; - this._blurKernelX = 0; - this._blurKernelY = 0; - this._blurRatio = 1.0; - scene = this.getScene(); - if (!scene) { - return this; - } - this.ignoreCameraViewport = true; - this._updateGammaSpace(); - this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(() => { - this._updateGammaSpace(); - }); - const engine = scene.getEngine(); - if (engine.supportsUniformBuffers) { - this._sceneUBO = scene.createSceneUniformBuffer(`Scene for Mirror Texture (name "${name}")`); - } - this.onBeforeBindObservable.add(() => { - var _a; - (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `mirror generation for ${name}`, 1); - }); - this.onAfterUnbindObservable.add(() => { - var _a; - (_a = engine._debugPopGroup) === null || _a === void 0 ? void 0 : _a.call(engine, 1); - }); - let saveClipPlane; - this.onBeforeRenderObservable.add(() => { - if (this._sceneUBO) { - this._currentSceneUBO = scene.getSceneUniformBuffer(); - scene.setSceneUniformBuffer(this._sceneUBO); - scene.getSceneUniformBuffer().unbindEffect(); - } - math_vector_Matrix.ReflectionToRef(this.mirrorPlane, this._mirrorMatrix); - this._mirrorMatrix.multiplyToRef(scene.getViewMatrix(), this._transformMatrix); - scene.setTransformMatrix(this._transformMatrix, scene.getProjectionMatrix()); - saveClipPlane = scene.clipPlane; - scene.clipPlane = this.mirrorPlane; - scene._mirroredCameraPosition = math_vector_Vector3.TransformCoordinates(scene.activeCamera.globalPosition, this._mirrorMatrix); - }); - this.onAfterRenderObservable.add(() => { - if (this._sceneUBO) { - scene.setSceneUniformBuffer(this._currentSceneUBO); - } - scene.updateTransformMatrix(); - scene._mirroredCameraPosition = null; - scene.clipPlane = saveClipPlane; - }); - } - _preparePostProcesses() { - this.clearPostProcesses(true); - if (this._blurKernelX && this._blurKernelY) { - const engine = this.getScene().getEngine(); - const textureType = engine.getCaps().textureFloatRender && engine.getCaps().textureFloatLinearFiltering ? 1 : 2; - this._blurX = new BlurPostProcess("horizontal blur", new math_vector_Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType); - this._blurX.autoClear = false; - if (this._blurRatio === 1 && this.samples < 2 && this._texture) { - this._blurX.inputTexture = this._renderTarget; - } - else { - this._blurX.alwaysForcePOT = true; - } - this._blurY = new BlurPostProcess("vertical blur", new math_vector_Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType); - this._blurY.autoClear = false; - this._blurY.alwaysForcePOT = this._blurRatio !== 1; - this.addPostProcess(this._blurX); - this.addPostProcess(this._blurY); - } - else { - if (this._blurY) { - this.removePostProcess(this._blurY); - this._blurY.dispose(); - this._blurY = null; - } - if (this._blurX) { - this.removePostProcess(this._blurX); - this._blurX.dispose(); - this._blurX = null; - } - } - } - /** - * Clone the mirror texture. - * @returns the cloned texture - */ - clone() { - const scene = this.getScene(); - if (!scene) { - return this; - } - const textureSize = this.getSize(); - const newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer); - // Base texture - newTexture.hasAlpha = this.hasAlpha; - newTexture.level = this.level; - // Mirror Texture - newTexture.mirrorPlane = this.mirrorPlane.clone(); - if (this.renderList) { - newTexture.renderList = this.renderList.slice(0); - } - return newTexture; - } - /** - * Serialize the texture to a JSON representation you could use in Parse later on - * @returns the serialized JSON representation - */ - serialize() { - if (!this.name) { - return null; - } - const serializationObject = super.serialize(); - serializationObject.mirrorPlane = this.mirrorPlane.asArray(); - return serializationObject; - } - /** - * Dispose the texture and release its associated resources. - */ - dispose() { - var _a; - super.dispose(); - const scene = this.getScene(); - if (scene) { - scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver); - } - (_a = this._sceneUBO) === null || _a === void 0 ? void 0 : _a.dispose(); - } -} -texture_Texture._CreateMirror = (name, renderTargetSize, scene, generateMipMaps) => { - return new MirrorTexture(name, renderTargetSize, scene, generateMipMaps); -}; -//# sourceMappingURL=mirrorTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/cubeTexture.js - - - - - - - - - - -/** - * Class for creating a cube texture - */ -class cubeTexture_CubeTexture extends baseTexture_BaseTexture { - /** - * Gets or sets the size of the bounding box associated with the cube texture - * When defined, the cubemap will switch to local mode - * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity - * @example https://www.babylonjs-playground.com/#RNASML - */ - set boundingBoxSize(value) { - if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { - return; - } - this._boundingBoxSize = value; - const scene = this.getScene(); - if (scene) { - scene.markAllMaterialsAsDirty(1); - } - } - /** - * Returns the bounding box size - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#using-local-cubemap-mode - */ - get boundingBoxSize() { - return this._boundingBoxSize; - } - /** - * Sets texture matrix rotation angle around Y axis in radians. - */ - set rotationY(value) { - this._rotationY = value; - this.setReflectionTextureMatrix(math_vector_Matrix.RotationY(this._rotationY)); - } - /** - * Gets texture matrix rotation angle around Y axis radians. - */ - get rotationY() { - return this._rotationY; - } - /** - * Are mip maps generated for this texture or not. - */ - get noMipmap() { - return this._noMipmap; - } - /** - * Gets the forced extension (if any) - */ - get forcedExtension() { - return this._forcedExtension; - } - /** - * Creates a cube texture from an array of image urls - * @param files defines an array of image urls - * @param scene defines the hosting scene - * @param noMipmap specifies if mip maps are not used - * @returns a cube texture - */ - static CreateFromImages(files, scene, noMipmap) { - let rootUrlKey = ""; - files.forEach((url) => (rootUrlKey += url)); - return new cubeTexture_CubeTexture(rootUrlKey, scene, null, noMipmap, files); - } - /** - * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys. - * @param url defines the url of the prefiltered texture - * @param scene defines the scene the texture is attached to - * @param forcedExtension defines the extension of the file if different from the url - * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary - * @returns the prefiltered texture - */ - static CreateFromPrefilteredData(url, scene, forcedExtension = null, createPolynomials = true) { - const oldValue = scene.useDelayedTextureLoading; - scene.useDelayedTextureLoading = false; - const result = new cubeTexture_CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials); - scene.useDelayedTextureLoading = oldValue; - return result; - } - /** - * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well - * as prefiltered data. - * @param rootUrl defines the url of the texture or the root name of the six images - * @param sceneOrEngine defines the scene or engine the texture is attached to - * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg... - * @param noMipmap defines if mipmaps should be created or not - * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz - * @param onLoad defines a callback triggered at the end of the file load if no errors occurred - * @param onError defines a callback triggered in case of error during load - * @param format defines the internal format to use for the texture once loaded - * @param prefiltered defines whether or not the texture is created from prefiltered data - * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name - * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary - * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness - * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness - * @param loaderOptions options to be passed to the loader - * @param useSRGBBuffer Defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU) (default: false) - * @returns the cube texture - */ - 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) { - var _a; - super(sceneOrEngine); - this._lodScale = 0.8; - this._lodOffset = 0; - /** - * Observable triggered once the texture has been loaded. - */ - this.onLoadObservable = new observable_Observable(); - /** - * Gets or sets the center of the bounding box associated with the cube texture. - * It must define where the camera used to render the texture was set - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#using-local-cubemap-mode - */ - this.boundingBoxPosition = math_vector_Vector3.Zero(); - this._rotationY = 0; - /** @internal */ - this._files = null; - this._forcedExtension = null; - this._extensions = null; - this._textureMatrixRefraction = new math_vector_Matrix(); - this.name = rootUrl; - this.url = rootUrl; - this._noMipmap = noMipmap; - this.hasAlpha = false; - this._format = format; - this.isCube = true; - this._textureMatrix = math_vector_Matrix.Identity(); - this._createPolynomials = createPolynomials; - this.coordinatesMode = texture_Texture.CUBIC_MODE; - this._extensions = extensions; - this._files = files; - this._forcedExtension = forcedExtension; - this._loaderOptions = loaderOptions; - this._useSRGBBuffer = useSRGBBuffer; - this._lodScale = lodScale; - this._lodOffset = lodOffset; - if (!rootUrl && !files) { - return; - } - this.updateURL(rootUrl, forcedExtension, onLoad, prefiltered, onError, extensions, (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.useDelayedTextureLoading, files); - } - /** - * Get the current class name of the texture useful for serialization or dynamic coding. - * @returns "CubeTexture" - */ - getClassName() { - return "CubeTexture"; - } - /** - * Update the url (and optional buffer) of this texture if url was null during construction. - * @param url the url of the texture - * @param forcedExtension defines the extension to use - * @param onLoad callback called when the texture is loaded (defaults to null) - * @param prefiltered Defines whether the updated texture is prefiltered or not - * @param onError callback called if there was an error during the loading process (defaults to null) - * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg... - * @param delayLoad defines if the texture should be loaded now (false by default) - * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz - */ - updateURL(url, forcedExtension, onLoad = null, prefiltered = false, onError = null, extensions = null, delayLoad = false, files = null) { - if (!this.name || this.name.startsWith("data:")) { - this.name = url; - } - this.url = url; - if (forcedExtension) { - this._forcedExtension = forcedExtension; - } - const lastDot = url.lastIndexOf("."); - const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : ""; - const isDDS = extension.indexOf(".dds") === 0; - const isEnv = extension.indexOf(".env") === 0; - const isBasis = extension.indexOf(".basis") === 0; - if (isEnv) { - this.gammaSpace = false; - this._prefiltered = false; - this.anisotropicFilteringLevel = 1; - } - else { - this._prefiltered = prefiltered; - if (prefiltered) { - this.gammaSpace = false; - this.anisotropicFilteringLevel = 1; - } - } - if (files) { - this._files = files; - } - else { - if (!isBasis && !isEnv && !isDDS && !extensions) { - extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"]; - } - this._files = this._files || []; - this._files.length = 0; - if (extensions) { - for (let index = 0; index < extensions.length; index++) { - this._files.push(url + extensions[index]); - } - this._extensions = extensions; - } - } - if (delayLoad) { - this.delayLoadState = 4; - this._delayedOnLoad = onLoad; - this._delayedOnError = onError; - } - else { - this._loadTexture(onLoad, onError); - } - } - /** - * Delays loading of the cube texture - * @param forcedExtension defines the extension to use - */ - delayLoad(forcedExtension) { - if (this.delayLoadState !== 4) { - return; - } - if (forcedExtension) { - this._forcedExtension = forcedExtension; - } - this.delayLoadState = 1; - this._loadTexture(this._delayedOnLoad, this._delayedOnError); - } - /** - * Returns the reflection texture matrix - * @returns the reflection texture matrix - */ - getReflectionTextureMatrix() { - return this._textureMatrix; - } - /** - * Sets the reflection texture matrix - * @param value Reflection texture matrix - */ - setReflectionTextureMatrix(value) { - var _a, _b; - if (value.updateFlag === this._textureMatrix.updateFlag) { - return; - } - if (value.isIdentity() !== this._textureMatrix.isIdentity()) { - (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1); - } - this._textureMatrix = value; - if (!((_b = this.getScene()) === null || _b === void 0 ? void 0 : _b.useRightHandedSystem)) { - return; - } - const scale = math_vector_TmpVectors.Vector3[0]; - const quat = math_vector_TmpVectors.Quaternion[0]; - const trans = math_vector_TmpVectors.Vector3[1]; - this._textureMatrix.decompose(scale, quat, trans); - quat.z *= -1; // these two operations correspond to negating the x and y euler angles - quat.w *= -1; - math_vector_Matrix.ComposeToRef(scale, quat, trans, this._textureMatrixRefraction); - } - /** - * Gets a suitable rotate/transform matrix when the texture is used for refraction. - * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode. - * @returns The refraction matrix - */ - getRefractionTextureMatrix() { - var _a; - return ((_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.useRightHandedSystem) ? this._textureMatrixRefraction : this._textureMatrix; - } - _loadTexture(onLoad = null, onError = null) { - var _a; - const scene = this.getScene(); - const oldTexture = this._texture; - this._texture = this._getFromCache(this.url, this._noMipmap, undefined, undefined, this._useSRGBBuffer, this.isCube); - const onLoadProcessing = () => { - var _a; - this.onLoadObservable.notifyObservers(this); - if (oldTexture) { - oldTexture.dispose(); - (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.markAllMaterialsAsDirty(1); - } - if (onLoad) { - onLoad(); - } - }; - const errorHandler = (message, exception) => { - this._loadingError = true; - this._errorObject = { message, exception }; - if (onError) { - onError(message, exception); - } - texture_Texture.OnTextureLoadErrorObservable.notifyObservers(this); - }; - if (!this._texture) { - if (this._prefiltered) { - this._texture = this._getEngine().createPrefilteredCubeTexture(this.url, scene, this._lodScale, this._lodOffset, onLoad, errorHandler, this._format, this._forcedExtension, this._createPolynomials); - } - else { - 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); - } - (_a = this._texture) === null || _a === void 0 ? void 0 : _a.onLoadedObservable.add(() => this.onLoadObservable.notifyObservers(this)); - } - else { - if (this._texture.isReady) { - tools_Tools.SetImmediate(() => onLoadProcessing()); - } - else { - this._texture.onLoadedObservable.add(() => onLoadProcessing()); - } - } - } - /** - * Parses text to create a cube texture - * @param parsedTexture define the serialized text to read from - * @param scene defines the hosting scene - * @param rootUrl defines the root url of the cube texture - * @returns a cube texture - */ - static Parse(parsedTexture, scene, rootUrl) { - const texture = decorators_SerializationHelper.Parse(() => { - var _a; - let prefiltered = false; - if (parsedTexture.prefiltered) { - prefiltered = parsedTexture.prefiltered; - } - return new cubeTexture_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); - }, parsedTexture, scene); - // Local Cubemaps - if (parsedTexture.boundingBoxPosition) { - texture.boundingBoxPosition = math_vector_Vector3.FromArray(parsedTexture.boundingBoxPosition); - } - if (parsedTexture.boundingBoxSize) { - texture.boundingBoxSize = math_vector_Vector3.FromArray(parsedTexture.boundingBoxSize); - } - // Animations - if (parsedTexture.animations) { - for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) { - const parsedAnimation = parsedTexture.animations[animationIndex]; - const internalClass = GetClass("BABYLON.Animation"); - if (internalClass) { - texture.animations.push(internalClass.Parse(parsedAnimation)); - } - } - } - return texture; - } - /** - * Makes a clone, or deep copy, of the cube texture - * @returns a new cube texture - */ - clone() { - let uniqueId = 0; - const newCubeTexture = decorators_SerializationHelper.Clone(() => { - const cubeTexture = new cubeTexture_CubeTexture(this.url, this.getScene() || this._getEngine(), this._extensions, this._noMipmap, this._files); - uniqueId = cubeTexture.uniqueId; - return cubeTexture; - }, this); - newCubeTexture.uniqueId = uniqueId; - return newCubeTexture; - } -} -__decorate([ - serialize() -], cubeTexture_CubeTexture.prototype, "url", void 0); -__decorate([ - serializeAsVector3() -], cubeTexture_CubeTexture.prototype, "boundingBoxPosition", void 0); -__decorate([ - serializeAsVector3() -], cubeTexture_CubeTexture.prototype, "boundingBoxSize", null); -__decorate([ - serialize("rotationY") -], cubeTexture_CubeTexture.prototype, "rotationY", null); -__decorate([ - serialize("files") -], cubeTexture_CubeTexture.prototype, "_files", void 0); -__decorate([ - serialize("forcedExtension") -], cubeTexture_CubeTexture.prototype, "_forcedExtension", void 0); -__decorate([ - serialize("extensions") -], cubeTexture_CubeTexture.prototype, "_extensions", void 0); -__decorate([ - serializeAsMatrix("textureMatrix") -], cubeTexture_CubeTexture.prototype, "_textureMatrix", void 0); -__decorate([ - serializeAsMatrix("textureMatrixRefraction") -], cubeTexture_CubeTexture.prototype, "_textureMatrixRefraction", void 0); -texture_Texture._CubeTextureParser = cubeTexture_CubeTexture.Parse; -// Some exporters relies on Tools.Instantiate -RegisterClass("BABYLON.CubeTexture", cubeTexture_CubeTexture); -//# sourceMappingURL=cubeTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundFragmentDeclaration.js -// Do not edit. - -const backgroundFragmentDeclaration_name = "backgroundFragmentDeclaration"; -const backgroundFragmentDeclaration_shader = `uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; -#ifdef USEHIGHLIGHTANDSHADOWCOLORS -uniform vec4 vPrimaryColorShadow; -#endif -uniform float shadowLevel;uniform float alpha; -#ifdef DIFFUSE -uniform vec2 vDiffuseInfos; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; -#endif -#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) -uniform vec3 vBackgroundCenter; -#endif -#ifdef REFLECTIONFRESNEL -uniform vec4 vReflectionControl; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) -uniform mat4 view; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[backgroundFragmentDeclaration_name] = backgroundFragmentDeclaration_shader; -/** @internal */ -const backgroundFragmentDeclaration = { name: backgroundFragmentDeclaration_name, shader: backgroundFragmentDeclaration_shader }; -//# sourceMappingURL=backgroundFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundUboDeclaration.js -// Do not edit. - - -const backgroundUboDeclaration_name = "backgroundUboDeclaration"; -const backgroundUboDeclaration_shader = `layout(std140,column_major) uniform;uniform Material -{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha; -#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) -uniform vec3 vBackgroundCenter; -#endif -#ifdef REFLECTIONFRESNEL -uniform vec4 vReflectionControl; -#endif -}; -#include<sceneUboDeclaration> -`; -// Sideeffect -ShaderStore.IncludesShadersStore[backgroundUboDeclaration_name] = backgroundUboDeclaration_shader; -/** @internal */ -const backgroundUboDeclaration = { name: backgroundUboDeclaration_name, shader: backgroundUboDeclaration_shader }; -//# sourceMappingURL=backgroundUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/background.fragment.js -// Do not edit. - - - - - - - - - - - - - - - - -const background_fragment_name = "backgroundPixelShader"; -const background_fragment_shader = `#ifdef TEXTURELODSUPPORT -#extension GL_EXT_shader_texture_lod : enable -#endif -precision highp float; -#include<__decl__backgroundFragment> -#include<helperFunctions> -#define RECIPROCAL_PI2 0.15915494 -varying vec3 vPositionW; -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef DIFFUSE -#if DIFFUSEDIRECTUV==1 -#define vDiffuseUV vMainUV1 -#elif DIFFUSEDIRECTUV==2 -#define vDiffuseUV vMainUV2 -#else -varying vec2 vDiffuseUV; -#endif -uniform sampler2D diffuseSampler; -#endif -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -#define sampleReflection(s,c) textureCube(s,c) -uniform samplerCube reflectionSampler; -#ifdef TEXTURELODSUPPORT -#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#else -#define sampleReflection(s,c) texture2D(s,c) -uniform sampler2D reflectionSampler; -#ifdef TEXTURELODSUPPORT -#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#include<reflectionFunction> -#endif -#ifndef FROMLINEARSPACE -#define FROMLINEARSPACE; -#endif -#ifndef SHADOWONLY -#define SHADOWONLY; -#endif -#include<imageProcessingDeclaration> -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include<lightsFragmentFunctions> -#include<shadowsFragmentFunctions> -#include<imageProcessingFunctions> -#include<clipPlaneFragmentDeclaration> -#include<fogFragmentDeclaration> -#ifdef REFLECTIONFRESNEL -#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 -vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) -{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=vec3(0.0,1.0,0.0); -#endif -float shadow=1.;float globalShadow=0.;float shadowLightCount=0.; -#include<lightFragment>[0..maxSimultaneousLights] -#ifdef SHADOWINUSE -globalShadow/=shadowLightCount; -#else -globalShadow=1.0; -#endif -#ifndef BACKMAT_SHADOWONLY -vec4 reflectionColor=vec4(1.,1.,1.,1.); -#ifdef REFLECTION -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords=reflectionVector; -#else -vec2 reflectionCoords=reflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -reflectionCoords/=reflectionVector.z; -#endif -reflectionCoords.y=1.0-reflectionCoords.y; -#endif -#ifdef REFLECTIONBLUR -float reflectionLOD=vReflectionInfos.y; -#ifdef TEXTURELODSUPPORT -reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); -#else -float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( -sampleReflection(reflectionSamplerHigh,reflectionCoords), -reflectionSpecularMid, -lodReflectionNormalizedDoubled -);} else {reflectionColor=mix( -reflectionSpecularMid, -sampleReflection(reflectionSamplerLow,reflectionCoords), -lodReflectionNormalizedDoubled-1.0 -);} -#endif -#else -vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; -#endif -#ifdef RGBDREFLECTION -reflectionColor.rgb=fromRGBD(reflectionColor); -#endif -#ifdef GAMMAREFLECTION -reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); -#endif -#ifdef REFLECTIONBGR -reflectionColor.rgb=reflectionColor.bgr; -#endif -reflectionColor.rgb*=vReflectionInfos.x; -#endif -vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; -#ifdef DIFFUSE -vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); -#ifdef GAMMADIFFUSE -diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); -#endif -diffuseMap.rgb*=vDiffuseInfos.y; -#ifdef DIFFUSEHASALPHA -finalAlpha*=diffuseMap.a; -#endif -diffuseColor=diffuseMap.rgb; -#endif -#ifdef REFLECTIONFRESNEL -vec3 colorBase=diffuseColor; -#else -vec3 colorBase=reflectionColor.rgb*diffuseColor; -#endif -colorBase=max(colorBase,0.0); -#ifdef USERGBCOLOR -vec3 finalColor=colorBase; -#else -#ifdef USEHIGHLIGHTANDSHADOWCOLORS -vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); -#else -vec3 mainColor=vPrimaryColor.rgb; -#endif -vec3 finalColor=colorBase*mainColor; -#endif -#ifdef REFLECTIONFRESNEL -vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; -#ifdef REFLECTIONFALLOFF -float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; -#endif -finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); -#endif -#ifdef OPACITYFRESNEL -float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; -#endif -#ifdef SHADOWINUSE -finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); -#endif -vec4 color=vec4(finalColor,finalAlpha); -#else -vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); -#endif -#include<fogFragment> -#ifdef IMAGEPROCESSINGPOSTPROCESS -#if !defined(SKIPFINALCOLORCLAMP) -color.rgb=clamp(color.rgb,0.,30.0); -#endif -#else -color=applyImageProcessing(color); -#endif -#ifdef PREMULTIPLYALPHA -color.rgb*=color.a; -#endif -#ifdef NOISE -color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); -#endif -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -} -`; -// Sideeffect -ShaderStore.ShadersStore[background_fragment_name] = background_fragment_shader; -/** @internal */ -const backgroundPixelShader = { name: background_fragment_name, shader: background_fragment_shader }; -//# sourceMappingURL=background.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundVertexDeclaration.js -// Do not edit. - -const backgroundVertexDeclaration_name = "backgroundVertexDeclaration"; -const backgroundVertexDeclaration_shader = `uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; -#ifdef DIFFUSE -uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[backgroundVertexDeclaration_name] = backgroundVertexDeclaration_shader; -/** @internal */ -const backgroundVertexDeclaration = { name: backgroundVertexDeclaration_name, shader: backgroundVertexDeclaration_shader }; -//# sourceMappingURL=backgroundVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/background.vertex.js -// Do not edit. - - - - - - - - - - - - - - - - - -const background_vertex_name = "backgroundVertexShader"; -const background_vertex_shader = `precision highp float; -#include<__decl__backgroundVertex> -#include<helperFunctions> -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<instancesDeclaration> -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 -varying vec2 vDiffuseUV; -#endif -#include<clipPlaneVertexDeclaration> -#include<fogVertexDeclaration> -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=position; -#endif -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} -#else -gl_Position=viewProjection*finalWorld*vec4(position,1.0); -#endif -vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normal); -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); -#ifdef EQUIRECTANGULAR_RELFECTION_FOV -mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} -#endif -#endif -#ifndef UV1 -vec2 uv=vec2(0.,0.); -#endif -#ifndef UV2 -vec2 uv2=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uv; -#endif -#ifdef MAINUV2 -vMainUV2=uv2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 -if (vDiffuseInfos.x==0.) -{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} -else -{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} -#endif -#include<clipPlaneVertex> -#include<fogVertex> -#include<shadowsVertex>[0..maxSimultaneousLights] -#ifdef VERTEXCOLOR -vColor=color; -#endif -#if defined(POINTSIZE) && !defined(WEBGPU) -gl_PointSize=pointSize; -#endif -#define CUSTOM_VERTEX_MAIN_END -} -`; -// Sideeffect -ShaderStore.ShadersStore[background_vertex_name] = background_vertex_shader; -/** @internal */ -const backgroundVertexShader = { name: background_vertex_name, shader: background_vertex_shader }; -//# sourceMappingURL=background.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Background/backgroundMaterial.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - - - - - - - - - - - -/** - * Background material defines definition. - * @internal Mainly internal Use - */ -class BackgroundMaterialDefines extends MaterialDefines { - /** - * Constructor of the defines. - */ - constructor() { - super(); - /** - * True if the diffuse texture is in use. - */ - this.DIFFUSE = false; - /** - * The direct UV channel to use. - */ - this.DIFFUSEDIRECTUV = 0; - /** - * True if the diffuse texture is in gamma space. - */ - this.GAMMADIFFUSE = false; - /** - * True if the diffuse texture has opacity in the alpha channel. - */ - this.DIFFUSEHASALPHA = false; - /** - * True if you want the material to fade to transparent at grazing angle. - */ - this.OPACITYFRESNEL = false; - /** - * True if an extra blur needs to be added in the reflection. - */ - this.REFLECTIONBLUR = false; - /** - * True if you want the material to fade to reflection at grazing angle. - */ - this.REFLECTIONFRESNEL = false; - /** - * True if you want the material to falloff as far as you move away from the scene center. - */ - this.REFLECTIONFALLOFF = false; - /** - * False if the current Webgl implementation does not support the texture lod extension. - */ - this.TEXTURELODSUPPORT = false; - /** - * True to ensure the data are premultiplied. - */ - this.PREMULTIPLYALPHA = false; - /** - * True if the texture contains cooked RGB values and not gray scaled multipliers. - */ - this.USERGBCOLOR = false; - /** - * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color - * stays aligned with the desired configuration. - */ - this.USEHIGHLIGHTANDSHADOWCOLORS = false; - /** - * True if only shadows must be rendered - */ - this.BACKMAT_SHADOWONLY = false; - /** - * True to add noise in order to reduce the banding effect. - */ - this.NOISE = false; - /** - * is the reflection texture in BGR color scheme? - * Mainly used to solve a bug in ios10 video tag - */ - this.REFLECTIONBGR = false; - this.IMAGEPROCESSING = false; - this.VIGNETTE = false; - this.VIGNETTEBLENDMODEMULTIPLY = false; - this.VIGNETTEBLENDMODEOPAQUE = false; - this.TONEMAPPING = false; - this.TONEMAPPING_ACES = false; - this.CONTRAST = false; - this.COLORCURVES = false; - this.COLORGRADING = false; - this.COLORGRADING3D = false; - this.SAMPLER3DGREENDEPTH = false; - this.SAMPLER3DBGRMAP = false; - this.DITHER = false; - this.IMAGEPROCESSINGPOSTPROCESS = false; - this.SKIPFINALCOLORCLAMP = false; - this.EXPOSURE = false; - this.MULTIVIEW = false; - // Reflection. - this.REFLECTION = false; - this.REFLECTIONMAP_3D = false; - this.REFLECTIONMAP_SPHERICAL = false; - this.REFLECTIONMAP_PLANAR = false; - this.REFLECTIONMAP_CUBIC = false; - this.REFLECTIONMAP_PROJECTION = false; - this.REFLECTIONMAP_SKYBOX = false; - this.REFLECTIONMAP_EXPLICIT = false; - this.REFLECTIONMAP_EQUIRECTANGULAR = false; - this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; - this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; - this.INVERTCUBICMAP = false; - this.REFLECTIONMAP_OPPOSITEZ = false; - this.LODINREFLECTIONALPHA = false; - this.GAMMAREFLECTION = false; - this.RGBDREFLECTION = false; - this.EQUIRECTANGULAR_RELFECTION_FOV = false; - // Default BJS. - this.MAINUV1 = false; - this.MAINUV2 = false; - this.UV1 = false; - this.UV2 = false; - this.CLIPPLANE = false; - this.CLIPPLANE2 = false; - this.CLIPPLANE3 = false; - this.CLIPPLANE4 = false; - this.CLIPPLANE5 = false; - this.CLIPPLANE6 = false; - this.POINTSIZE = false; - this.FOG = false; - this.NORMAL = false; - this.NUM_BONE_INFLUENCERS = 0; - this.BonesPerMesh = 0; - this.INSTANCES = false; - this.SHADOWFLOAT = false; - this.LOGARITHMICDEPTH = false; - this.NONUNIFORMSCALING = false; - this.ALPHATEST = false; - this.rebuild(); - } -} -/** - * Background material used to create an efficient environment around your scene. - */ -class BackgroundMaterial extends PushMaterial { - /** - * Experimental Internal Use Only. - * - * Key light Color in "perceptual value" meaning the color you would like to see on screen. - * This acts as a helper to set the primary color to a more "human friendly" value. - * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the - * output color as close as possible from the chosen value. - * (This does not account for contrast color grading and color curves as they are considered post effect and not directly - * part of lighting setup.) - */ - get _perceptualColor() { - return this.__perceptualColor; - } - set _perceptualColor(value) { - this.__perceptualColor = value; - this._computePrimaryColorFromPerceptualColor(); - this._markAllSubMeshesAsLightsDirty(); - } - /** - * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors. - * The color opposite to the primary color is used at the level chosen to define what the black area would look. - */ - get primaryColorShadowLevel() { - return this._primaryColorShadowLevel; - } - set primaryColorShadowLevel(value) { - this._primaryColorShadowLevel = value; - this._computePrimaryColors(); - this._markAllSubMeshesAsLightsDirty(); - } - /** - * Defines the level of the highlights (highlight area of the reflection map) in order to help scaling the colors. - * The primary color is used at the level chosen to define what the white area would look. - */ - get primaryColorHighlightLevel() { - return this._primaryColorHighlightLevel; - } - set primaryColorHighlightLevel(value) { - this._primaryColorHighlightLevel = value; - this._computePrimaryColors(); - this._markAllSubMeshesAsLightsDirty(); - } - /** - * Sets the reflection reflectance fresnel values according to the default standard - * empirically know to work well :-) - */ - set reflectionStandardFresnelWeight(value) { - let reflectionWeight = value; - if (reflectionWeight < 0.5) { - reflectionWeight = reflectionWeight * 2.0; - this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight; - this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight; - } - else { - reflectionWeight = reflectionWeight * 2.0 - 1.0; - this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight; - this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight; - } - } - /** - * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". - * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov. - * Recommended to be keep at 1.0 except for special cases. - */ - get fovMultiplier() { - return this._fovMultiplier; - } - set fovMultiplier(value) { - if (isNaN(value)) { - value = 1.0; - } - this._fovMultiplier = Math.max(0.0, Math.min(2.0, value)); - } - /** - * Attaches a new image processing configuration to the PBR Material. - * @param configuration (if null the scene configuration will be use) - */ - _attachImageProcessingConfiguration(configuration) { - if (configuration === this._imageProcessingConfiguration) { - return; - } - // Detaches observer. - if (this._imageProcessingConfiguration && this._imageProcessingObserver) { - this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); - } - // Pick the scene configuration if needed. - if (!configuration) { - this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; - } - else { - this._imageProcessingConfiguration = configuration; - } - // Attaches observer. - if (this._imageProcessingConfiguration) { - this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { - this._computePrimaryColorFromPerceptualColor(); - this._markAllSubMeshesAsImageProcessingDirty(); - }); - } - } - /** - * Gets the image processing configuration used either in this material. - */ - get imageProcessingConfiguration() { - return this._imageProcessingConfiguration; - } - /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ - set imageProcessingConfiguration(value) { - this._attachImageProcessingConfiguration(value); - // Ensure the effect will be rebuilt. - this._markAllSubMeshesAsTexturesDirty(); - } - /** - * Gets whether the color curves effect is enabled. - */ - get cameraColorCurvesEnabled() { - return this.imageProcessingConfiguration.colorCurvesEnabled; - } - /** - * Sets whether the color curves effect is enabled. - */ - set cameraColorCurvesEnabled(value) { - this.imageProcessingConfiguration.colorCurvesEnabled = value; - } - /** - * Gets whether the color grading effect is enabled. - */ - get cameraColorGradingEnabled() { - return this.imageProcessingConfiguration.colorGradingEnabled; - } - /** - * Gets whether the color grading effect is enabled. - */ - set cameraColorGradingEnabled(value) { - this.imageProcessingConfiguration.colorGradingEnabled = value; - } - /** - * Gets whether tonemapping is enabled or not. - */ - get cameraToneMappingEnabled() { - return this._imageProcessingConfiguration.toneMappingEnabled; - } - /** - * Sets whether tonemapping is enabled or not - */ - set cameraToneMappingEnabled(value) { - this._imageProcessingConfiguration.toneMappingEnabled = value; - } - /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ - get cameraExposure() { - return this._imageProcessingConfiguration.exposure; - } - /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ - set cameraExposure(value) { - this._imageProcessingConfiguration.exposure = value; - } - /** - * Gets The camera contrast used on this material. - */ - get cameraContrast() { - return this._imageProcessingConfiguration.contrast; - } - /** - * Sets The camera contrast used on this material. - */ - set cameraContrast(value) { - this._imageProcessingConfiguration.contrast = value; - } - /** - * Gets the Color Grading 2D Lookup Texture. - */ - get cameraColorGradingTexture() { - return this._imageProcessingConfiguration.colorGradingTexture; - } - /** - * Sets the Color Grading 2D Lookup Texture. - */ - set cameraColorGradingTexture(value) { - this.imageProcessingConfiguration.colorGradingTexture = value; - } - /** - * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * 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; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ - get cameraColorCurves() { - return this.imageProcessingConfiguration.colorCurves; - } - /** - * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * 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; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ - set cameraColorCurves(value) { - this.imageProcessingConfiguration.colorCurves = value; - } - /** - * Instantiates a Background Material in the given scene - * @param name The friendly name of the material - * @param scene The scene to add the material to - */ - constructor(name, scene) { - super(name, scene); - /** - * Key light Color (multiply against the environment texture) - */ - this.primaryColor = math_color_Color3.White(); - this._primaryColorShadowLevel = 0; - this._primaryColorHighlightLevel = 0; - /** - * Reflection Texture used in the material. - * Should be author in a specific way for the best result (refer to the documentation). - */ - this.reflectionTexture = null; - /** - * Reflection Texture level of blur. - * - * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the - * texture twice. - */ - this.reflectionBlur = 0; - /** - * Diffuse Texture used in the material. - * Should be author in a specific way for the best result (refer to the documentation). - */ - this.diffuseTexture = null; - this._shadowLights = null; - /** - * Specify the list of lights casting shadow on the material. - * All scene shadow lights will be included if null. - */ - this.shadowLights = null; - /** - * Helps adjusting the shadow to a softer level if required. - * 0 means black shadows and 1 means no shadows. - */ - this.shadowLevel = 0; - /** - * In case of opacity Fresnel or reflection falloff, this is use as a scene center. - * It is usually zero but might be interesting to modify according to your setup. - */ - this.sceneCenter = math_vector_Vector3.Zero(); - /** - * This helps specifying that the material is falling off to the sky box at grazing angle. - * This helps ensuring a nice transition when the camera goes under the ground. - */ - this.opacityFresnel = true; - /** - * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle. - * This helps adding a mirror texture on the ground. - */ - this.reflectionFresnel = false; - /** - * This helps specifying the falloff radius off the reflection texture from the sceneCenter. - * This helps adding a nice falloff effect to the reflection if used as a mirror for instance. - */ - this.reflectionFalloffDistance = 0.0; - /** - * This specifies the weight of the reflection against the background in case of reflection Fresnel. - */ - this.reflectionAmount = 1.0; - /** - * This specifies the weight of the reflection at grazing angle. - */ - this.reflectionReflectance0 = 0.05; - /** - * This specifies the weight of the reflection at a perpendicular point of view. - */ - this.reflectionReflectance90 = 0.5; - /** - * Helps to directly use the maps channels instead of their level. - */ - this.useRGBColor = true; - /** - * This helps reducing the banding effect that could occur on the background. - */ - this.enableNoise = false; - this._fovMultiplier = 1.0; - /** - * Enable the FOV adjustment feature controlled by fovMultiplier. - */ - this.useEquirectangularFOV = false; - this._maxSimultaneousLights = 4; - /** - * Number of Simultaneous lights allowed on the material. - */ - this.maxSimultaneousLights = 4; - this._shadowOnly = false; - /** - * Make the material only render shadows - */ - this.shadowOnly = false; - /** - * Keep track of the image processing observer to allow dispose and replace. - */ - this._imageProcessingObserver = null; - /** - * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB. - * Setting this flag to true (not done automatically!) will convert it back to RGB. - */ - this.switchToBGR = false; - // Temp values kept as cache in the material. - this._renderTargets = new SmartArray(16); - this._reflectionControls = math_vector_Vector4.Zero(); - this._white = math_color_Color3.White(); - this._primaryShadowColor = math_color_Color3.Black(); - this._primaryHighlightColor = math_color_Color3.Black(); - // Setup the default processing configuration to the scene. - this._attachImageProcessingConfiguration(null); - this.getRenderTargetTextures = () => { - this._renderTargets.reset(); - if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) { - this._renderTargets.push(this._diffuseTexture); - } - if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { - this._renderTargets.push(this._reflectionTexture); - } - return this._renderTargets; - }; - } - /** - * Gets a boolean indicating that current material needs to register RTT - */ - get hasRenderTargetTextures() { - if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) { - return true; - } - if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { - return true; - } - return false; - } - /** - * The entire material has been created in order to prevent overdraw. - * @returns false - */ - needAlphaTesting() { - return true; - } - /** - * The entire material has been created in order to prevent overdraw. - * @returns true if blending is enable - */ - needAlphaBlending() { - return this.alpha < 1 || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._shadowOnly; - } - /** - * Checks whether the material is ready to be rendered for a given mesh. - * @param mesh The mesh to render - * @param subMesh The submesh to check against - * @param useInstances Specify wether or not the material is used with instances - * @returns true if all the dependencies are ready (Textures, Effects...) - */ - isReadyForSubMesh(mesh, subMesh, useInstances = false) { - if (subMesh.effect && this.isFrozen) { - if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) { - return true; - } - } - if (!subMesh.materialDefines) { - subMesh.materialDefines = new BackgroundMaterialDefines(); - } - const scene = this.getScene(); - const defines = subMesh.materialDefines; - if (this._isReadyForSubMesh(subMesh)) { - return true; - } - const engine = scene.getEngine(); - // Lights - MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights); - defines._needNormals = true; - // Multiview - MaterialHelper.PrepareDefinesForMultiview(scene, defines); - // Textures - if (defines._areTexturesDirty) { - defines._needUVs = false; - if (scene.texturesEnabled) { - if (scene.getEngine().getCaps().textureLOD) { - defines.TEXTURELODSUPPORT = true; - } - if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) { - if (!this._diffuseTexture.isReadyOrNotBlocking()) { - return false; - } - MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE"); - defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha; - defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace; - defines.OPACITYFRESNEL = this._opacityFresnel; - } - else { - defines.DIFFUSE = false; - defines.DIFFUSEDIRECTUV = 0; - defines.DIFFUSEHASALPHA = false; - defines.GAMMADIFFUSE = false; - defines.OPACITYFRESNEL = false; - } - const reflectionTexture = this._reflectionTexture; - if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { - if (!reflectionTexture.isReadyOrNotBlocking()) { - return false; - } - defines.REFLECTION = true; - defines.GAMMAREFLECTION = reflectionTexture.gammaSpace; - defines.RGBDREFLECTION = reflectionTexture.isRGBD; - defines.REFLECTIONBLUR = this._reflectionBlur > 0; - defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha; - defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV; - defines.REFLECTIONBGR = this.switchToBGR; - if (reflectionTexture.coordinatesMode === texture_Texture.INVCUBIC_MODE) { - defines.INVERTCUBICMAP = true; - } - defines.REFLECTIONMAP_3D = reflectionTexture.isCube; - defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ; - switch (reflectionTexture.coordinatesMode) { - case texture_Texture.EXPLICIT_MODE: - defines.REFLECTIONMAP_EXPLICIT = true; - break; - case texture_Texture.PLANAR_MODE: - defines.REFLECTIONMAP_PLANAR = true; - break; - case texture_Texture.PROJECTION_MODE: - defines.REFLECTIONMAP_PROJECTION = true; - break; - case texture_Texture.SKYBOX_MODE: - defines.REFLECTIONMAP_SKYBOX = true; - break; - case texture_Texture.SPHERICAL_MODE: - defines.REFLECTIONMAP_SPHERICAL = true; - break; - case texture_Texture.EQUIRECTANGULAR_MODE: - defines.REFLECTIONMAP_EQUIRECTANGULAR = true; - break; - case texture_Texture.FIXED_EQUIRECTANGULAR_MODE: - defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true; - break; - case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE: - defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true; - break; - case texture_Texture.CUBIC_MODE: - case texture_Texture.INVCUBIC_MODE: - default: - defines.REFLECTIONMAP_CUBIC = true; - break; - } - if (this.reflectionFresnel) { - defines.REFLECTIONFRESNEL = true; - defines.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; - } - else { - defines.REFLECTIONFRESNEL = false; - defines.REFLECTIONFALLOFF = false; - } - } - else { - defines.REFLECTION = false; - defines.REFLECTIONFRESNEL = false; - defines.REFLECTIONFALLOFF = false; - defines.REFLECTIONBLUR = false; - defines.REFLECTIONMAP_3D = false; - defines.REFLECTIONMAP_SPHERICAL = false; - defines.REFLECTIONMAP_PLANAR = false; - defines.REFLECTIONMAP_CUBIC = false; - defines.REFLECTIONMAP_PROJECTION = false; - defines.REFLECTIONMAP_SKYBOX = false; - defines.REFLECTIONMAP_EXPLICIT = false; - defines.REFLECTIONMAP_EQUIRECTANGULAR = false; - defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; - defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; - defines.INVERTCUBICMAP = false; - defines.REFLECTIONMAP_OPPOSITEZ = false; - defines.LODINREFLECTIONALPHA = false; - defines.GAMMAREFLECTION = false; - defines.RGBDREFLECTION = false; - } - } - defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8; - defines.USERGBCOLOR = this._useRGBColor; - defines.NOISE = this._enableNoise; - } - if (defines._areLightsDirty) { - defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0); - defines.BACKMAT_SHADOWONLY = this._shadowOnly; - } - if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { - if (!this._imageProcessingConfiguration.isReady()) { - return false; - } - this._imageProcessingConfiguration.prepareDefines(defines); - } - // Misc. - MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines); - // Values that need to be evaluated on every frame - MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances); - // Attribs - if (MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) { - if (mesh) { - if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)) { - mesh.createNormals(true); - logger_Logger.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name); - } - } - } - // Get correct effect - if (defines.isDirty) { - defines.markAsProcessed(); - scene.resetCachedMaterial(); - // Fallbacks - const fallbacks = new EffectFallbacks(); - if (defines.FOG) { - fallbacks.addFallback(0, "FOG"); - } - if (defines.POINTSIZE) { - fallbacks.addFallback(1, "POINTSIZE"); - } - if (defines.MULTIVIEW) { - fallbacks.addFallback(0, "MULTIVIEW"); - } - MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights); - //Attributes - const attribs = [buffer_VertexBuffer.PositionKind]; - if (defines.NORMAL) { - attribs.push(buffer_VertexBuffer.NormalKind); - } - if (defines.UV1) { - attribs.push(buffer_VertexBuffer.UVKind); - } - if (defines.UV2) { - attribs.push(buffer_VertexBuffer.UV2Kind); - } - MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks); - MaterialHelper.PrepareAttributesForInstances(attribs, defines); - const uniforms = [ - "world", - "view", - "viewProjection", - "vEyePosition", - "vLightsType", - "vFogInfos", - "vFogColor", - "pointSize", - "mBones", - "vPrimaryColor", - "vPrimaryColorShadow", - "vReflectionInfos", - "reflectionMatrix", - "vReflectionMicrosurfaceInfos", - "fFovMultiplier", - "shadowLevel", - "alpha", - "vBackgroundCenter", - "vReflectionControl", - "vDiffuseInfos", - "diffuseMatrix", - ]; - addClipPlaneUniforms(uniforms); - const samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"]; - const uniformBuffers = ["Material", "Scene"]; - if (ImageProcessingConfiguration) { - ImageProcessingConfiguration.PrepareUniforms(uniforms, defines); - ImageProcessingConfiguration.PrepareSamplers(samplers, defines); - } - MaterialHelper.PrepareUniformsAndSamplersList({ - uniformsNames: uniforms, - uniformBuffersNames: uniformBuffers, - samplers: samplers, - defines: defines, - maxSimultaneousLights: this._maxSimultaneousLights, - }); - const join = defines.toString(); - const effect = scene.getEngine().createEffect("background", { - attributes: attribs, - uniformsNames: uniforms, - uniformBuffersNames: uniformBuffers, - samplers: samplers, - defines: join, - fallbacks: fallbacks, - onCompiled: this.onCompiled, - onError: this.onError, - indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }, - }, engine); - subMesh.setEffect(effect, defines, this._materialContext); - this.buildUniformLayout(); - } - if (!subMesh.effect || !subMesh.effect.isReady()) { - return false; - } - defines._renderId = scene.getRenderId(); - subMesh.effect._wasPreviouslyReady = true; - subMesh.effect._wasPreviouslyUsingInstances = useInstances; - this._checkScenePerformancePriority(); - return true; - } - /** - * Compute the primary color according to the chosen perceptual color. - */ - _computePrimaryColorFromPerceptualColor() { - if (!this.__perceptualColor) { - return; - } - this._primaryColor.copyFrom(this.__perceptualColor); - // Revert gamma space. - this._primaryColor.toLinearSpaceToRef(this._primaryColor, this.getScene().getEngine().useExactSrgbConversions); - // Revert image processing configuration. - if (this._imageProcessingConfiguration) { - // Revert Exposure. - this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor); - } - this._computePrimaryColors(); - } - /** - * Compute the highlights and shadow colors according to their chosen levels. - */ - _computePrimaryColors() { - if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) { - return; - } - // Find the highlight color based on the configuration. - this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor); - this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor); - // Find the shadow color based on the configuration. - this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor); - this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor); - this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor); - } - /** - * Build the uniform buffer used in the material. - */ - buildUniformLayout() { - // Order is important ! - 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 the material. - */ - unbind() { - if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) { - this._uniformBuffer.setTexture("diffuseSampler", null); - } - if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { - this._uniformBuffer.setTexture("reflectionSampler", null); - } - super.unbind(); - } - /** - * Bind only the world matrix to the material. - * @param world The world matrix to bind. - */ - bindOnlyWorldMatrix(world) { - this._activeEffect.setMatrix("world", world); - } - /** - * Bind the material for a dedicated submeh (every used meshes will be considered opaque). - * @param world The world matrix to bind. - * @param mesh - * @param subMesh The submesh to bind for. - */ - bindForSubMesh(world, mesh, subMesh) { - const scene = this.getScene(); - const defines = subMesh.materialDefines; - if (!defines) { - return; - } - const effect = subMesh.effect; - if (!effect) { - return; - } - this._activeEffect = effect; - // Matrices - this.bindOnlyWorldMatrix(world); - // Bones - MaterialHelper.BindBonesParameters(mesh, this._activeEffect); - const mustRebind = this._mustRebind(scene, effect, mesh.visibility); - if (mustRebind) { - this._uniformBuffer.bindToEffect(effect, "Material"); - this.bindViewProjection(effect); - const reflectionTexture = this._reflectionTexture; - if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) { - // Texture uniforms - if (scene.texturesEnabled) { - if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) { - this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level); - MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse"); - } - if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { - this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix()); - this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur); - this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); - } - } - if (this.shadowLevel > 0) { - this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel); - } - this._uniformBuffer.updateFloat("alpha", this.alpha); - // Point size - if (this.pointsCloud) { - this._uniformBuffer.updateFloat("pointSize", this.pointSize); - } - if (defines.USEHIGHLIGHTANDSHADOWCOLORS) { - this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0); - this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0); - } - else { - this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0); - } - } - this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier); - // Textures - if (scene.texturesEnabled) { - if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) { - this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture); - } - if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { - if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) { - this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture); - } - else if (!defines.REFLECTIONBLUR) { - this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture); - } - else { - this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture); - this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture); - this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture); - } - if (defines.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); - } - } - } - // Clip plane - bindClipPlane(this._activeEffect, this, scene); - scene.bindEyePosition(effect); - } - else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) { - this._uniformBuffer.bindToEffect(effect, "Material"); - this._needToBindSceneUbo = true; - } - if (mustRebind || !this.isFrozen) { - if (scene.lightsEnabled) { - MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights); - } - // View - this.bindView(effect); - // Fog - MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true); - // image processing - if (this._imageProcessingConfiguration) { - this._imageProcessingConfiguration.bind(this._activeEffect); - } - } - this._afterBind(mesh, this._activeEffect); - this._uniformBuffer.update(); - } - /** - * Checks to see if a texture is used in the material. - * @param texture - Base texture to use. - * @returns - Boolean specifying if a texture is used in the material. - */ - hasTexture(texture) { - if (super.hasTexture(texture)) { - return true; - } - if (this._reflectionTexture === texture) { - return true; - } - if (this._diffuseTexture === texture) { - return true; - } - return false; - } - /** - * Dispose the material. - * @param forceDisposeEffect Force disposal of the associated effect. - * @param forceDisposeTextures Force disposal of the associated textures. - */ - dispose(forceDisposeEffect = false, forceDisposeTextures = false) { - if (forceDisposeTextures) { - if (this.diffuseTexture) { - this.diffuseTexture.dispose(); - } - if (this.reflectionTexture) { - this.reflectionTexture.dispose(); - } - } - this._renderTargets.dispose(); - if (this._imageProcessingConfiguration && this._imageProcessingObserver) { - this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); - } - super.dispose(forceDisposeEffect); - } - /** - * Clones the material. - * @param name The cloned name. - * @returns The cloned material. - */ - clone(name) { - return decorators_SerializationHelper.Clone(() => new BackgroundMaterial(name, this.getScene()), this); - } - /** - * Serializes the current material to its JSON representation. - * @returns The JSON representation. - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.customType = "BABYLON.BackgroundMaterial"; - return serializationObject; - } - /** - * Gets the class name of the material - * @returns "BackgroundMaterial" - */ - getClassName() { - return "BackgroundMaterial"; - } - /** - * Parse a JSON input to create back a background material. - * @param source The JSON data to parse - * @param scene The scene to create the parsed material in - * @param rootUrl The root url of the assets the material depends upon - * @returns the instantiated BackgroundMaterial. - */ - static Parse(source, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => new BackgroundMaterial(source.name, scene), source, scene, rootUrl); - } -} -/** - * Standard reflectance value at parallel view angle. - */ -BackgroundMaterial.StandardReflectance0 = 0.05; -/** - * Standard reflectance value at grazing angle. - */ -BackgroundMaterial.StandardReflectance90 = 0.5; -__decorate([ - serializeAsColor3() -], BackgroundMaterial.prototype, "_primaryColor", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsLightsDirty") -], BackgroundMaterial.prototype, "primaryColor", void 0); -__decorate([ - serializeAsColor3() -], BackgroundMaterial.prototype, "__perceptualColor", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsLightsDirty") -], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null); -__decorate([ - serializeAsTexture() -], BackgroundMaterial.prototype, "_reflectionTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "reflectionTexture", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_reflectionBlur", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "reflectionBlur", void 0); -__decorate([ - serializeAsTexture() -], BackgroundMaterial.prototype, "_diffuseTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "diffuseTexture", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "shadowLights", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_shadowLevel", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "shadowLevel", void 0); -__decorate([ - serializeAsVector3() -], BackgroundMaterial.prototype, "_sceneCenter", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "sceneCenter", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_opacityFresnel", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "opacityFresnel", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_reflectionFresnel", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "reflectionFresnel", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_reflectionAmount", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "reflectionAmount", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "reflectionReflectance0", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "reflectionReflectance90", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_useRGBColor", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "useRGBColor", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_enableNoise", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "enableNoise", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0); -__decorate([ - serialize() -], BackgroundMaterial.prototype, "_shadowOnly", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsLightsDirty") -], BackgroundMaterial.prototype, "shadowOnly", void 0); -__decorate([ - serializeAsImageProcessingConfiguration() -], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0); -RegisterClass("BABYLON.BackgroundMaterial", BackgroundMaterial); -//# sourceMappingURL=backgroundMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Helpers/environmentHelper.js - - - - - - - - - - - - - - -/** - * The EnvironmentHelper class can be used to add a fully featured non-expensive background to your scene. - * It includes by default a skybox and a ground relying on the BackgroundMaterial. - * It also helps with the default setup of your ImageProcessingConfiguration. - */ -class EnvironmentHelper { - /** - * Creates the default options for the helper. - * @param scene The scene the environment helper belongs to. - */ - static _GetDefaultOptions(scene) { - return { - createGround: true, - groundSize: 15, - groundTexture: this._GroundTextureCDNUrl, - groundColor: new math_color_Color3(0.2, 0.2, 0.3).toLinearSpace(scene.getEngine().useExactSrgbConversions).scale(3), - groundOpacity: 0.9, - enableGroundShadow: true, - groundShadowLevel: 0.5, - enableGroundMirror: false, - groundMirrorSizeRatio: 0.3, - groundMirrorBlurKernel: 64, - groundMirrorAmount: 1, - groundMirrorFresnelWeight: 1, - groundMirrorFallOffDistance: 0, - groundMirrorTextureType: 0, - groundYBias: 0.00001, - createSkybox: true, - skyboxSize: 20, - skyboxTexture: this._SkyboxTextureCDNUrl, - skyboxColor: new math_color_Color3(0.2, 0.2, 0.3).toLinearSpace(scene.getEngine().useExactSrgbConversions).scale(3), - backgroundYRotation: 0, - sizeAuto: true, - rootPosition: math_vector_Vector3.Zero(), - setupImageProcessing: true, - environmentTexture: this._EnvironmentTextureCDNUrl, - cameraExposure: 0.8, - cameraContrast: 1.2, - toneMappingEnabled: true, - }; - } - /** - * Gets the root mesh created by the helper. - */ - get rootMesh() { - return this._rootMesh; - } - /** - * Gets the skybox created by the helper. - */ - get skybox() { - return this._skybox; - } - /** - * Gets the skybox texture created by the helper. - */ - get skyboxTexture() { - return this._skyboxTexture; - } - /** - * Gets the skybox material created by the helper. - */ - get skyboxMaterial() { - return this._skyboxMaterial; - } - /** - * Gets the ground mesh created by the helper. - */ - get ground() { - return this._ground; - } - /** - * Gets the ground texture created by the helper. - */ - get groundTexture() { - return this._groundTexture; - } - /** - * Gets the ground mirror created by the helper. - */ - get groundMirror() { - return this._groundMirror; - } - /** - * Gets the ground mirror render list to helps pushing the meshes - * you wish in the ground reflection. - */ - get groundMirrorRenderList() { - if (this._groundMirror) { - return this._groundMirror.renderList; - } - return null; - } - /** - * Gets the ground material created by the helper. - */ - get groundMaterial() { - return this._groundMaterial; - } - /** - * constructor - * @param options Defines the options we want to customize the helper - * @param scene The scene to add the material to - */ - constructor(options, scene) { - this._errorHandler = (message, exception) => { - this.onErrorObservable.notifyObservers({ message: message, exception: exception }); - }; - this._options = Object.assign(Object.assign({}, EnvironmentHelper._GetDefaultOptions(scene)), options); - this._scene = scene; - this.onErrorObservable = new observable_Observable(); - this._setupBackground(); - this._setupImageProcessing(); - } - /** - * Updates the background according to the new options - * @param options - */ - updateOptions(options) { - const newOptions = Object.assign(Object.assign({}, this._options), options); - if (this._ground && !newOptions.createGround) { - this._ground.dispose(); - this._ground = null; - } - if (this._groundMaterial && !newOptions.createGround) { - this._groundMaterial.dispose(); - this._groundMaterial = null; - } - if (this._groundTexture) { - if (this._options.groundTexture != newOptions.groundTexture) { - this._groundTexture.dispose(); - this._groundTexture = null; - } - } - if (this._skybox && !newOptions.createSkybox) { - this._skybox.dispose(); - this._skybox = null; - } - if (this._skyboxMaterial && !newOptions.createSkybox) { - this._skyboxMaterial.dispose(); - this._skyboxMaterial = null; - } - if (this._skyboxTexture) { - if (this._options.skyboxTexture != newOptions.skyboxTexture) { - this._skyboxTexture.dispose(); - this._skyboxTexture = null; - } - } - if (this._groundMirror && !newOptions.enableGroundMirror) { - this._groundMirror.dispose(); - this._groundMirror = null; - } - if (this._scene.environmentTexture) { - if (this._options.environmentTexture != newOptions.environmentTexture) { - this._scene.environmentTexture.dispose(); - } - } - this._options = newOptions; - this._setupBackground(); - this._setupImageProcessing(); - } - /** - * Sets the primary color of all the available elements. - * @param color the main color to affect to the ground and the background - */ - setMainColor(color) { - if (this.groundMaterial) { - this.groundMaterial.primaryColor = color; - } - if (this.skyboxMaterial) { - this.skyboxMaterial.primaryColor = color; - } - if (this.groundMirror) { - this.groundMirror.clearColor = new math_color_Color4(color.r, color.g, color.b, 1.0); - } - } - /** - * Setup the image processing according to the specified options. - */ - _setupImageProcessing() { - if (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(); - } - } - /** - * Setup the environment texture according to the specified options. - */ - _setupEnvironmentTexture() { - if (this._scene.environmentTexture) { - return; - } - if (this._options.environmentTexture instanceof baseTexture_BaseTexture) { - this._scene.environmentTexture = this._options.environmentTexture; - return; - } - const environmentTexture = cubeTexture_CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene); - this._scene.environmentTexture = environmentTexture; - } - /** - * Setup the background according to the specified options. - */ - _setupBackground() { - if (!this._rootMesh) { - this._rootMesh = new mesh_Mesh("BackgroundHelper", this._scene); - } - this._rootMesh.rotation.y = this._options.backgroundYRotation; - const sceneSize = this._getSceneSize(); - if (this._options.createGround) { - this._setupGround(sceneSize); - this._setupGroundMaterial(); - this._setupGroundDiffuseTexture(); - if (this._options.enableGroundMirror) { - this._setupGroundMirrorTexture(sceneSize); - } - this._setupMirrorInGroundMaterial(); - } - if (this._options.createSkybox) { - this._setupSkybox(sceneSize); - this._setupSkyboxMaterial(); - this._setupSkyboxReflectionTexture(); - } - this._rootMesh.position.x = sceneSize.rootPosition.x; - this._rootMesh.position.z = sceneSize.rootPosition.z; - this._rootMesh.position.y = sceneSize.rootPosition.y; - } - /** - * Get the scene sizes according to the setup. - */ - _getSceneSize() { - let groundSize = this._options.groundSize; - let skyboxSize = this._options.skyboxSize; - let rootPosition = this._options.rootPosition; - if (!this._scene.meshes || this._scene.meshes.length === 1) { - // 1 only means the root of the helper. - return { groundSize, skyboxSize, rootPosition }; - } - const sceneExtends = this._scene.getWorldExtends((mesh) => { - return mesh !== this._ground && mesh !== this._rootMesh && mesh !== this._skybox; - }); - const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min); - if (this._options.sizeAuto) { - if (this._scene.activeCamera instanceof ArcRotateCamera && this._scene.activeCamera.upperRadiusLimit) { - groundSize = this._scene.activeCamera.upperRadiusLimit * 2; - skyboxSize = groundSize; - } - const sceneDiagonalLenght = sceneDiagonal.length(); - if (sceneDiagonalLenght > groundSize) { - groundSize = sceneDiagonalLenght * 2; - skyboxSize = groundSize; - } - // 10 % bigger. - groundSize *= 1.1; - skyboxSize *= 1.5; - rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5)); - rootPosition.y = sceneExtends.min.y - this._options.groundYBias; - } - return { groundSize, skyboxSize, rootPosition }; - } - /** - * Setup the ground according to the specified options. - * @param sceneSize - */ - _setupGround(sceneSize) { - if (!this._ground || this._ground.isDisposed()) { - this._ground = planeBuilder_CreatePlane("BackgroundPlane", { size: sceneSize.groundSize }, this._scene); - this._ground.rotation.x = Math.PI / 2; // Face up by default. - this._ground.parent = this._rootMesh; - this._ground.onDisposeObservable.add(() => { - this._ground = null; - }); - } - this._ground.receiveShadows = this._options.enableGroundShadow; - } - /** - * Setup the ground material according to the specified options. - */ - _setupGroundMaterial() { - if (!this._groundMaterial) { - this._groundMaterial = new BackgroundMaterial("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 = false; - this._groundMaterial.enableNoise = true; - if (this._ground) { - this._ground.material = this._groundMaterial; - } - } - /** - * Setup the ground diffuse texture according to the specified options. - */ - _setupGroundDiffuseTexture() { - if (!this._groundMaterial) { - return; - } - if (this._groundTexture) { - return; - } - if (this._options.groundTexture instanceof baseTexture_BaseTexture) { - this._groundMaterial.diffuseTexture = this._options.groundTexture; - return; - } - this._groundTexture = new texture_Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler); - this._groundTexture.gammaSpace = false; - this._groundTexture.hasAlpha = true; - this._groundMaterial.diffuseTexture = this._groundTexture; - } - /** - * Setup the ground mirror texture according to the specified options. - * @param sceneSize - */ - _setupGroundMirrorTexture(sceneSize) { - const wrapping = texture_Texture.CLAMP_ADDRESSMODE; - if (!this._groundMirror) { - this._groundMirror = new MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, texture_Texture.BILINEAR_SAMPLINGMODE, true); - this._groundMirror.mirrorPlane = new math_plane_Plane(0, -1, 0, sceneSize.rootPosition.y); - this._groundMirror.anisotropicFilteringLevel = 1; - this._groundMirror.wrapU = wrapping; - this._groundMirror.wrapV = wrapping; - if (this._groundMirror.renderList) { - for (let i = 0; i < this._scene.meshes.length; i++) { - const mesh = this._scene.meshes[i]; - if (mesh !== this._ground && mesh !== this._skybox && mesh !== this._rootMesh) { - this._groundMirror.renderList.push(mesh); - } - } - } - } - const gammaGround = this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions); - this._groundMirror.clearColor = new math_color_Color4(gammaGround.r, gammaGround.g, gammaGround.b, 1); - this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel; - } - /** - * Setup the ground to receive the mirror texture. - */ - _setupMirrorInGroundMaterial() { - if (this._groundMaterial) { - this._groundMaterial.reflectionTexture = this._groundMirror; - this._groundMaterial.reflectionFresnel = true; - this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount; - this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight; - this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance; - } - } - /** - * Setup the skybox according to the specified options. - * @param sceneSize - */ - _setupSkybox(sceneSize) { - if (!this._skybox || this._skybox.isDisposed()) { - this._skybox = boxBuilder_CreateBox("BackgroundSkybox", { size: sceneSize.skyboxSize, sideOrientation: mesh_Mesh.BACKSIDE }, this._scene); - this._skybox.onDisposeObservable.add(() => { - this._skybox = null; - }); - } - this._skybox.parent = this._rootMesh; - } - /** - * Setup the skybox material according to the specified options. - */ - _setupSkyboxMaterial() { - if (!this._skybox) { - return; - } - if (!this._skyboxMaterial) { - this._skyboxMaterial = new BackgroundMaterial("BackgroundSkyboxMaterial", this._scene); - } - this._skyboxMaterial.useRGBColor = false; - this._skyboxMaterial.primaryColor = this._options.skyboxColor; - this._skyboxMaterial.enableNoise = true; - this._skybox.material = this._skyboxMaterial; - } - /** - * Setup the skybox reflection texture according to the specified options. - */ - _setupSkyboxReflectionTexture() { - if (!this._skyboxMaterial) { - return; - } - if (this._skyboxTexture) { - return; - } - if (this._options.skyboxTexture instanceof baseTexture_BaseTexture) { - this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture; - return; - } - this._skyboxTexture = new cubeTexture_CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler); - this._skyboxTexture.coordinatesMode = texture_Texture.SKYBOX_MODE; - this._skyboxTexture.gammaSpace = false; - this._skyboxMaterial.reflectionTexture = this._skyboxTexture; - } - /** - * Dispose all the elements created by the Helper. - */ - dispose() { - if (this._groundMaterial) { - this._groundMaterial.dispose(true, true); - } - if (this._skyboxMaterial) { - this._skyboxMaterial.dispose(true, true); - } - this._rootMesh.dispose(false); - } -} -/** - * Default ground texture URL. - */ -EnvironmentHelper._GroundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png"; -/** - * Default skybox texture URL. - */ -EnvironmentHelper._SkyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds"; -/** - * Default environment texture URL. - */ -EnvironmentHelper._EnvironmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env"; -//# sourceMappingURL=environmentHelper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Helpers/textureDome.js - - - - - - - - -/** - * Display a 360/180 degree texture on an approximately spherical surface, useful for VR applications or skyboxes. - * As a subclass of TransformNode, this allow parenting to the camera or multiple textures with different locations in the scene. - * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere. - * Potential additions to this helper include zoom and and non-infinite distance rendering effects. - */ -class TextureDome extends transformNode_TransformNode { - /** - * Gets the texture being displayed on the sphere - */ - get texture() { - return this._texture; - } - /** - * Sets the texture being displayed on the sphere - */ - set texture(newTexture) { - if (this._texture === newTexture) { - return; - } - this._texture = newTexture; - if (this._useDirectMapping) { - this._texture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._texture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._material.diffuseTexture = this._texture; - } - else { - this._texture.coordinatesMode = texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation - this._texture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._material.reflectionTexture = this._texture; - } - this._changeTextureMode(this._textureMode); - } - /** - * Gets the mesh used for the dome. - */ - get mesh() { - return this._mesh; - } - /** - * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". - * Also see the options.resolution property. - */ - get fovMultiplier() { - return this._material.fovMultiplier; - } - set fovMultiplier(value) { - this._material.fovMultiplier = value; - } - /** - * Gets or set the current texture mode for the texture. It can be: - * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360. - * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360. - * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360. - */ - get textureMode() { - return this._textureMode; - } - /** - * Sets the current texture mode for the texture. It can be: - * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360. - * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360. - * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360. - */ - set textureMode(value) { - if (this._textureMode === value) { - return; - } - this._changeTextureMode(value); - } - /** - * Is it a 180 degrees dome (half dome) or 360 texture (full dome) - */ - get halfDome() { - return this._halfDome; - } - /** - * Set the halfDome mode. If set, only the front (180 degrees) will be displayed and the back will be blacked out. - */ - set halfDome(enabled) { - this._halfDome = enabled; - this._halfDomeMask.setEnabled(enabled); - this._changeTextureMode(this._textureMode); - } - /** - * Set the cross-eye mode. If set, images that can be seen when crossing eyes will render correctly - */ - set crossEye(enabled) { - this._crossEye = enabled; - this._changeTextureMode(this._textureMode); - } - /** - * Is it a cross-eye texture? - */ - get crossEye() { - return this._crossEye; - } - /** - * The background material of this dome. - */ - get material() { - return this._material; - } - /** - * Create an instance of this class and pass through the parameters to the relevant classes- Texture, StandardMaterial, and Mesh. - * @param name Element's name, child elements will append suffixes for their own names. - * @param textureUrlOrElement defines the url(s) or the (video) HTML element to use - * @param options An object containing optional or exposed sub element properties - * @param options.resolution - * @param options.clickToPlay - * @param options.autoPlay - * @param options.loop - * @param options.size - * @param options.poster - * @param options.faceForward - * @param options.useDirectMapping - * @param options.halfDomeMode - * @param options.crossEyeMode - * @param options.generateMipMaps - * @param options.mesh - * @param scene - * @param onError - */ - constructor(name, textureUrlOrElement, options, scene, - // eslint-disable-next-line @typescript-eslint/naming-convention - onError = null) { - super(name, scene); - this.onError = onError; - this._halfDome = false; - this._crossEye = false; - this._useDirectMapping = false; - this._textureMode = TextureDome.MODE_MONOSCOPIC; - /** - * Oberserver used in Stereoscopic VR Mode. - */ - this._onBeforeCameraRenderObserver = null; - /** - * Observable raised when an error occurred while loading the texture - */ - this.onLoadErrorObservable = new observable_Observable(); - /** - * Observable raised when the texture finished loading - */ - this.onLoadObservable = new observable_Observable(); - scene = this.getScene(); - // set defaults and manage values - name = name || "textureDome"; - options.resolution = Math.abs(options.resolution) | 0 || 32; - options.clickToPlay = Boolean(options.clickToPlay); - options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay); - options.loop = options.loop === undefined ? true : Boolean(options.loop); - options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000); - if (options.useDirectMapping === undefined) { - this._useDirectMapping = true; - } - else { - this._useDirectMapping = options.useDirectMapping; - } - if (options.faceForward === undefined) { - options.faceForward = true; - } - this._setReady(false); - if (!options.mesh) { - this._mesh = sphereBuilder_CreateSphere(name + "_mesh", { segments: options.resolution, diameter: options.size, updatable: false, sideOrientation: mesh_Mesh.BACKSIDE }, scene); - } - else { - this._mesh = options.mesh; - } - // configure material - const material = (this._material = new BackgroundMaterial(name + "_material", scene)); - material.useEquirectangularFOV = true; - material.fovMultiplier = 1.0; - material.opacityFresnel = false; - const texture = this._initTexture(textureUrlOrElement, scene, options); - this.texture = texture; - // configure mesh - this._mesh.material = material; - this._mesh.parent = this; - // create a (disabled until needed) mask to cover unneeded segments of 180 texture. - this._halfDomeMask = sphereBuilder_CreateSphere("", { slice: 0.5, diameter: options.size * 0.98, segments: options.resolution * 2, sideOrientation: mesh_Mesh.BACKSIDE }, scene); - this._halfDomeMask.rotate(math_axis_Axis.X, -Math.PI / 2); - // set the parent, so it will always be positioned correctly AND will be disposed when the main sphere is disposed - this._halfDomeMask.parent = this._mesh; - this._halfDome = !!options.halfDomeMode; - // enable or disable according to the settings - this._halfDomeMask.setEnabled(this._halfDome); - this._crossEye = !!options.crossEyeMode; - // create - this._texture.anisotropicFilteringLevel = 1; - this._texture.onLoadObservable.addOnce(() => { - this._setReady(true); - }); - // Initial rotation - if (options.faceForward && scene.activeCamera) { - const camera = scene.activeCamera; - const forward = math_vector_Vector3.Forward(); - const direction = math_vector_Vector3.TransformNormal(forward, camera.getViewMatrix()); - direction.normalize(); - this.rotation.y = Math.acos(math_vector_Vector3.Dot(forward, direction)); - } - this._changeTextureMode(this._textureMode); - } - _changeTextureMode(value) { - this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); - this._textureMode = value; - // Default Setup and Reset. - this._texture.uScale = 1; - this._texture.vScale = 1; - this._texture.uOffset = 0; - this._texture.vOffset = 0; - this._texture.vAng = 0; - switch (value) { - case TextureDome.MODE_MONOSCOPIC: - if (this._halfDome) { - this._texture.uScale = 2; - this._texture.uOffset = -1; - } - break; - case TextureDome.MODE_SIDEBYSIDE: { - // in half-dome mode the uScale should be double of 360 texture - // Use 0.99999 to boost perf by not switching program - this._texture.uScale = this._halfDome ? 0.99999 : 0.5; - const rightOffset = this._halfDome ? 0.0 : 0.5; - const leftOffset = this._halfDome ? -0.5 : 0.0; - this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add((camera) => { - let isRightCamera = camera.isRightCamera; - if (this._crossEye) { - isRightCamera = !isRightCamera; - } - if (isRightCamera) { - this._texture.uOffset = rightOffset; - } - else { - this._texture.uOffset = leftOffset; - } - }); - break; - } - case TextureDome.MODE_TOPBOTTOM: - // in half-dome mode the vScale should be double of 360 texture - // Use 0.99999 to boost perf by not switching program - this._texture.vScale = this._halfDome ? 0.99999 : 0.5; - this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add((camera) => { - let isRightCamera = camera.isRightCamera; - // allow "cross-eye" if left and right were switched in this mode - if (this._crossEye) { - isRightCamera = !isRightCamera; - } - this._texture.vOffset = isRightCamera ? 0.5 : 0.0; - }); - break; - } - } - /** - * Releases resources associated with this node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) - */ - dispose(doNotRecurse, disposeMaterialAndTextures = false) { - this._texture.dispose(); - this._mesh.dispose(); - this._material.dispose(); - this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); - this.onLoadErrorObservable.clear(); - this.onLoadObservable.clear(); - super.dispose(doNotRecurse, disposeMaterialAndTextures); - } -} -/** - * Define the source as a Monoscopic panoramic 360/180. - */ -TextureDome.MODE_MONOSCOPIC = 0; -/** - * Define the source as a Stereoscopic TopBottom/OverUnder panoramic 360/180. - */ -TextureDome.MODE_TOPBOTTOM = 1; -/** - * Define the source as a Stereoscopic Side by Side panoramic 360/180. - */ -TextureDome.MODE_SIDEBYSIDE = 2; -//# sourceMappingURL=textureDome.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Helpers/photoDome.js - - -/** - * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes. - * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene. - * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere. - * Potential additions to this helper include zoom and and non-infinite distance rendering effects. - */ -class PhotoDome extends TextureDome { - /** - * Gets or sets the texture being displayed on the sphere - */ - get photoTexture() { - return this.texture; - } - /** - * sets the texture being displayed on the sphere - */ - set photoTexture(value) { - this.texture = value; - } - /** - * Gets the current video mode for the video. It can be: - * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360. - * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360. - * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360. - */ - get imageMode() { - return this.textureMode; - } - /** - * Sets the current video mode for the video. It can be: - * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360. - * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360. - * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360. - */ - set imageMode(value) { - this.textureMode = value; - } - _initTexture(urlsOrElement, scene, options) { - return new texture_Texture(urlsOrElement, scene, !options.generateMipMaps, !this._useDirectMapping, undefined, () => { - this.onLoadObservable.notifyObservers(); - }, (message, exception) => { - this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured"); - if (this.onError) { - this.onError(message, exception); - } - }); - } -} -/** - * Define the image as a Monoscopic panoramic 360 image. - */ -PhotoDome.MODE_MONOSCOPIC = TextureDome.MODE_MONOSCOPIC; -/** - * Define the image as a Stereoscopic TopBottom/OverUnder panoramic 360 image. - */ -PhotoDome.MODE_TOPBOTTOM = TextureDome.MODE_TOPBOTTOM; -/** - * Define the image as a Stereoscopic Side by Side panoramic 360 image. - */ -PhotoDome.MODE_SIDEBYSIDE = TextureDome.MODE_SIDEBYSIDE; -//# sourceMappingURL=photoDome.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/brdfTextureTools.js - - - -// eslint-disable-next-line @typescript-eslint/naming-convention -const _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/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg=="; -let _instanceNumber = 0; -/** - * Gets a default environment BRDF for MS-BRDF Height Correlated BRDF - * @param scene defines the hosting scene - * @returns the environment BRDF texture - */ -const GetEnvironmentBRDFTexture = (scene) => { - if (!scene.environmentBRDFTexture) { - // Forces Delayed Texture Loading to prevent undefined error whilst setting RGBD values. - const useDelayedTextureLoading = scene.useDelayedTextureLoading; - scene.useDelayedTextureLoading = false; - const previousState = scene._blockEntityCollection; - scene._blockEntityCollection = false; - const texture = texture_Texture.CreateFromBase64String(_environmentBRDFBase64Texture, "EnvironmentBRDFTexture" + _instanceNumber++, scene, true, false, texture_Texture.BILINEAR_SAMPLINGMODE); - scene._blockEntityCollection = previousState; - // BRDF Texture should not be cached here due to pre processing and redundant scene caches. - const texturesCache = scene.getEngine().getLoadedTexturesCache(); - const index = texturesCache.indexOf(texture.getInternalTexture()); - if (index !== -1) { - texturesCache.splice(index, 1); - } - texture.isRGBD = true; - texture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - texture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - scene.environmentBRDFTexture = texture; - scene.useDelayedTextureLoading = useDelayedTextureLoading; - RGBDTextureTools.ExpandRGBDTexture(texture); - const observer = scene.getEngine().onContextRestoredObservable.add(() => { - texture.isRGBD = true; - const checkReady = () => { - if (texture.isReady()) { - RGBDTextureTools.ExpandRGBDTexture(texture); - } - else { - tools_Tools.SetImmediate(checkReady); - } - }; - checkReady(); - }); - scene.onDisposeObservable.add(() => { - scene.getEngine().onContextRestoredObservable.remove(observer); - }); - } - return scene.environmentBRDFTexture; -}; -/** - * Class used to host texture specific utilities - */ -const BRDFTextureTools = { - /** - * Gets a default environment BRDF for MS-BRDF Height Correlated BRDF - * @param scene defines the hosting scene - * @returns the environment BRDF texture - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - GetEnvironmentBRDFTexture, -}; -//# sourceMappingURL=brdfTextureTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrBRDFConfiguration.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - -/** - * @internal - */ -class MaterialBRDFDefines extends MaterialDefines { - constructor() { - super(...arguments); - this.BRDF_V_HEIGHT_CORRELATED = false; - this.MS_BRDF_ENERGY_CONSERVATION = false; - this.SPHERICAL_HARMONICS = false; - this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = false; - } -} -/** - * Plugin that implements the BRDF component of the PBR material - */ -class pbrBRDFConfiguration_PBRBRDFConfiguration extends MaterialPluginBase { - /** @internal */ - _markAllSubMeshesAsMiscDirty() { - this._internalMarkAllSubMeshesAsMiscDirty(); - } - constructor(material, addToPluginList = true) { - super(material, "PBRBRDF", 90, new MaterialBRDFDefines(), addToPluginList); - this._useEnergyConservation = pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION; - /** - * Defines if the material uses energy conservation. - */ - this.useEnergyConservation = pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION; - this._useSmithVisibilityHeightCorrelated = pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED; - /** - * LEGACY Mode set to false - * Defines if the material uses height smith correlated visibility term. - * If you intent to not use our default BRDF, you need to load a separate BRDF Texture for the PBR - * You can either load https://assets.babylonjs.com/environments/uncorrelatedBRDF.png - * or https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds to have more precision - * Not relying on height correlated will also disable energy conservation. - */ - this.useSmithVisibilityHeightCorrelated = pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED; - this._useSphericalHarmonics = pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS; - /** - * LEGACY Mode set to false - * Defines if the material uses spherical harmonics vs spherical polynomials for the - * diffuse part of the IBL. - * The harmonics despite a tiny bigger cost has been proven to provide closer results - * to the ground truth. - */ - this.useSphericalHarmonics = pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS; - this._useSpecularGlossinessInputEnergyConservation = pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION; - /** - * Defines if the material uses energy conservation, when the specular workflow is active. - * If activated, the albedo color is multiplied with (1. - maxChannel(specular color)). - * If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1. - * In the deactivated case, the material author has to ensure energy conservation, for a physically plausible rendering. - */ - this.useSpecularGlossinessInputEnergyConservation = pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION; - this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16]; - this._enable(true); - } - prepareDefines(defines) { - defines.BRDF_V_HEIGHT_CORRELATED = this._useSmithVisibilityHeightCorrelated; - defines.MS_BRDF_ENERGY_CONSERVATION = this._useEnergyConservation && this._useSmithVisibilityHeightCorrelated; - defines.SPHERICAL_HARMONICS = this._useSphericalHarmonics; - defines.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = this._useSpecularGlossinessInputEnergyConservation; - } - getClassName() { - return "PBRBRDFConfiguration"; - } -} -/** - * Default value used for the energy conservation. - * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture. - */ -pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION = true; -/** - * Default value used for the Smith Visibility Height Correlated mode. - * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture. - */ -pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = true; -/** - * Default value used for the IBL diffuse part. - * This can help switching back to the polynomials mode globally which is a tiny bit - * less GPU intensive at the drawback of a lower quality. - */ -pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS = true; -/** - * Default value used for activating energy conservation for the specular workflow. - * If activated, the albedo color is multiplied with (1. - maxChannel(specular color)). - * If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1. - */ -pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION = true; -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsMiscDirty") -], pbrBRDFConfiguration_PBRBRDFConfiguration.prototype, "useEnergyConservation", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsMiscDirty") -], pbrBRDFConfiguration_PBRBRDFConfiguration.prototype, "useSmithVisibilityHeightCorrelated", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsMiscDirty") -], pbrBRDFConfiguration_PBRBRDFConfiguration.prototype, "useSphericalHarmonics", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsMiscDirty") -], pbrBRDFConfiguration_PBRBRDFConfiguration.prototype, "useSpecularGlossinessInputEnergyConservation", void 0); -//# sourceMappingURL=pbrBRDFConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrFragmentDeclaration.js -// Do not edit. - - -const pbrFragmentDeclaration_name = "pbrFragmentDeclaration"; -const pbrFragmentDeclaration_shader = `uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; -#ifdef ALBEDO -uniform vec2 vAlbedoInfos; -#endif -#ifdef AMBIENT -uniform vec4 vAmbientInfos; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#ifdef OPACITY -uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos; -#endif -#ifdef REFLECTIVITY -uniform vec3 vReflectivityInfos; -#endif -#ifdef MICROSURFACEMAP -uniform vec2 vMicroSurfaceSamplerInfos; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) -uniform mat4 view; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos; -#ifdef REALTIME_FILTERING -uniform vec2 vReflectionFilteringInfo; -#endif -uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; -#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) -uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; -#endif -#ifdef CLEARCOAT -uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; -#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) -uniform vec4 vClearCoatInfos; -#endif -#ifdef CLEARCOAT_TEXTURE -uniform mat4 clearCoatMatrix; -#endif -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS -uniform mat4 clearCoatRoughnessMatrix; -#endif -#ifdef CLEARCOAT_BUMP -uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; -#endif -#ifdef CLEARCOAT_TINT -uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; -#ifdef CLEARCOAT_TINT_TEXTURE -uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; -#endif -#endif -#endif -#ifdef IRIDESCENCE -uniform vec4 vIridescenceParams; -#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) -uniform vec4 vIridescenceInfos; -#endif -#ifdef IRIDESCENCE_TEXTURE -uniform mat4 iridescenceMatrix; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -uniform mat4 iridescenceThicknessMatrix; -#endif -#endif -#ifdef ANISOTROPIC -uniform vec3 vAnisotropy; -#ifdef ANISOTROPIC_TEXTURE -uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; -#endif -#endif -#ifdef SHEEN -uniform vec4 vSheenColor; -#ifdef SHEEN_ROUGHNESS -uniform float vSheenRoughness; -#endif -#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) -uniform vec4 vSheenInfos; -#endif -#ifdef SHEEN_TEXTURE -uniform mat4 sheenMatrix; -#endif -#ifdef SHEEN_TEXTURE_ROUGHNESS -uniform mat4 sheenRoughnessMatrix; -#endif -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; -#ifdef REALTIME_FILTERING -uniform vec2 vRefractionFilteringInfo; -#endif -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; -#endif -uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity; -#endif -#ifdef PREPASS -#ifdef SS_SCATTERING -uniform float scatteringDiffusionProfile; -#endif -#endif -#if DEBUGMODE>0 -uniform vec2 vDebugMode; -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos; -#endif -#include<decalFragmentDeclaration> -#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; -#else -uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; -#endif -#endif -#define ADDITIONAL_FRAGMENT_DECLARATION -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrFragmentDeclaration_name] = pbrFragmentDeclaration_shader; -/** @internal */ -const pbrFragmentDeclaration = { name: pbrFragmentDeclaration_name, shader: pbrFragmentDeclaration_shader }; -//# sourceMappingURL=pbrFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrUboDeclaration.js -// Do not edit. - - - -const pbrUboDeclaration_name = "pbrUboDeclaration"; -const pbrUboDeclaration_shader = `layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; -#define ADDITIONAL_UBO_DECLARATION -}; -#include<sceneUboDeclaration> -#include<meshUboDeclaration> -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrUboDeclaration_name] = pbrUboDeclaration_shader; -/** @internal */ -const pbrUboDeclaration = { name: pbrUboDeclaration_name, shader: pbrUboDeclaration_shader }; -//# sourceMappingURL=pbrUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrFragmentExtraDeclaration.js -// Do not edit. - - -const pbrFragmentExtraDeclaration_name = "pbrFragmentExtraDeclaration"; -const pbrFragmentExtraDeclaration_shader = `varying vec3 vPositionW; -#if DEBUGMODE>0 -varying vec4 vClipSpacePosition; -#endif -#include<mainUVVaryingDeclaration>[1..7] -#ifdef NORMAL -varying vec3 vNormalW; -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -varying vec3 vEnvironmentIrradiance; -#endif -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrFragmentExtraDeclaration_name] = pbrFragmentExtraDeclaration_shader; -/** @internal */ -const pbrFragmentExtraDeclaration = { name: pbrFragmentExtraDeclaration_name, shader: pbrFragmentExtraDeclaration_shader }; -//# sourceMappingURL=pbrFragmentExtraDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerFragmentAlternateDeclaration.js -// Do not edit. - -const samplerFragmentAlternateDeclaration_name = "samplerFragmentAlternateDeclaration"; -const samplerFragmentAlternateDeclaration_shader = `#ifdef _DEFINENAME_ -#if _DEFINENAME_DIRECTUV==1 -#define v_VARYINGNAME_UV vMainUV1 -#elif _DEFINENAME_DIRECTUV==2 -#define v_VARYINGNAME_UV vMainUV2 -#elif _DEFINENAME_DIRECTUV==3 -#define v_VARYINGNAME_UV vMainUV3 -#elif _DEFINENAME_DIRECTUV==4 -#define v_VARYINGNAME_UV vMainUV4 -#elif _DEFINENAME_DIRECTUV==5 -#define v_VARYINGNAME_UV vMainUV5 -#elif _DEFINENAME_DIRECTUV==6 -#define v_VARYINGNAME_UV vMainUV6 -#else -varying vec2 v_VARYINGNAME_UV; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[samplerFragmentAlternateDeclaration_name] = samplerFragmentAlternateDeclaration_shader; -/** @internal */ -const samplerFragmentAlternateDeclaration = { name: samplerFragmentAlternateDeclaration_name, shader: samplerFragmentAlternateDeclaration_shader }; -//# sourceMappingURL=samplerFragmentAlternateDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrFragmentSamplersDeclaration.js -// Do not edit. - - - -const pbrFragmentSamplersDeclaration_name = "pbrFragmentSamplersDeclaration"; -const pbrFragmentSamplersDeclaration_shader = `#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) -#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) -#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) -#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) -#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) -#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) -#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) -#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) -#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) -#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) -#ifdef CLEARCOAT -#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) -#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) -uniform sampler2D clearCoatRoughnessSampler; -#endif -#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) -#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) -#endif -#ifdef IRIDESCENCE -#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) -#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) -#endif -#ifdef SHEEN -#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) -#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) -#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) -uniform sampler2D sheenRoughnessSampler; -#endif -#endif -#ifdef ANISOTROPIC -#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) -#endif -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -#define sampleReflection(s,c) textureCube(s,c) -uniform samplerCube reflectionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#ifdef USEIRRADIANCEMAP -uniform samplerCube irradianceSampler; -#endif -#else -#define sampleReflection(s,c) texture2D(s,c) -uniform sampler2D reflectionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; -#endif -#ifdef USEIRRADIANCEMAP -uniform sampler2D irradianceSampler; -#endif -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#endif -#ifdef ENVIRONMENTBRDF -uniform sampler2D environmentBrdfSampler; -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -#ifdef SS_REFRACTIONMAP_3D -#define sampleRefraction(s,c) textureCube(s,c) -uniform samplerCube refractionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; -#endif -#else -#define sampleRefraction(s,c) texture2D(s,c) -uniform sampler2D refractionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; -#endif -#endif -#endif -#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) -#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) -#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrFragmentSamplersDeclaration_name] = pbrFragmentSamplersDeclaration_shader; -/** @internal */ -const pbrFragmentSamplersDeclaration = { name: pbrFragmentSamplersDeclaration_name, shader: pbrFragmentSamplersDeclaration_shader }; -//# sourceMappingURL=pbrFragmentSamplersDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/subSurfaceScatteringFunctions.js -// Do not edit. - -const subSurfaceScatteringFunctions_name = "subSurfaceScatteringFunctions"; -const subSurfaceScatteringFunctions_shader = `bool testLightingForSSS(float diffusionProfile) -{return diffusionProfile<1.;}`; -// Sideeffect -ShaderStore.IncludesShadersStore[subSurfaceScatteringFunctions_name] = subSurfaceScatteringFunctions_shader; -/** @internal */ -const subSurfaceScatteringFunctions = { name: subSurfaceScatteringFunctions_name, shader: subSurfaceScatteringFunctions_shader }; -//# sourceMappingURL=subSurfaceScatteringFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/importanceSampling.js -// Do not edit. - -const importanceSampling_name = "importanceSampling"; -const importanceSampling_shader = `vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} -vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} -vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { -float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`; -// Sideeffect -ShaderStore.IncludesShadersStore[importanceSampling_name] = importanceSampling_shader; -/** @internal */ -const importanceSampling = { name: importanceSampling_name, shader: importanceSampling_shader }; -//# sourceMappingURL=importanceSampling.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrHelperFunctions.js -// Do not edit. - -const pbrHelperFunctions_name = "pbrHelperFunctions"; -const pbrHelperFunctions_shader = `#define RECIPROCAL_PI2 0.15915494 -#define RECIPROCAL_PI 0.31830988618 -#define MINIMUMVARIANCE 0.0005 -float convertRoughnessToAverageSlope(float roughness) -{return square(roughness)+MINIMUMVARIANCE;} -float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} -vec2 getAARoughnessFactors(vec3 normalVector) { -#ifdef SPECULARAA -vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); -#else -return vec2(0.); -#endif -} -#ifdef ANISOTROPIC -#ifdef ANISOTROPIC_LEGACY -vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} -vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} -#else -vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} -vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} -#endif -#endif -#if defined(CLEARCOAT) || defined(SS_REFRACTION) -vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} -vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} -vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} -vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), -cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), -clearCoatIntensity);return clearCoatAbsorption;} -#endif -#ifdef MICROSURFACEAUTOMATIC -float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) -{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrHelperFunctions_name] = pbrHelperFunctions_shader; -/** @internal */ -const pbrHelperFunctions = { name: pbrHelperFunctions_name, shader: pbrHelperFunctions_shader }; -//# sourceMappingURL=pbrHelperFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/harmonicsFunctions.js -// Do not edit. - -const harmonicsFunctions_name = "harmonicsFunctions"; -const harmonicsFunctions_shader = `#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 -+ vSphericalL1_1*(normal.y) -+ vSphericalL10*(normal.z) -+ vSphericalL11*(normal.x) -+ vSphericalL2_2*(normal.y*normal.x) -+ vSphericalL2_1*(normal.y*normal.z) -+ vSphericalL20*((3.0*normal.z*normal.z)-1.0) -+ vSphericalL21*(normal.z*normal.x) -+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} -#else -vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[harmonicsFunctions_name] = harmonicsFunctions_shader; -/** @internal */ -const harmonicsFunctions = { name: harmonicsFunctions_name, shader: harmonicsFunctions_shader }; -//# sourceMappingURL=harmonicsFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDirectLightingSetupFunctions.js -// Do not edit. - -const pbrDirectLightingSetupFunctions_name = "pbrDirectLightingSetupFunctions"; -const pbrDirectLightingSetupFunctions_shader = `struct preLightingInfo -{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; -#ifdef IRIDESCENCE -float iridescenceIntensity; -#endif -};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} -preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} -preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; -#ifdef SPECULARTERM -result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); -#endif -return result;}`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrDirectLightingSetupFunctions_name] = pbrDirectLightingSetupFunctions_shader; -/** @internal */ -const pbrDirectLightingSetupFunctions = { name: pbrDirectLightingSetupFunctions_name, shader: pbrDirectLightingSetupFunctions_shader }; -//# sourceMappingURL=pbrDirectLightingSetupFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDirectLightingFalloffFunctions.js -// Do not edit. - -const pbrDirectLightingFalloffFunctions_name = "pbrDirectLightingFalloffFunctions"; -const pbrDirectLightingFalloffFunctions_shader = `float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) -{return max(0.,1.0-length(lightOffset)/range);} -float computeDistanceLightFalloff_Physical(float lightDistanceSquared) -{return 1.0/maxEps(lightDistanceSquared);} -float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) -{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} -float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) -{ -#ifdef USEPHYSICALLIGHTFALLOFF -return computeDistanceLightFalloff_Physical(lightDistanceSquared); -#elif defined(USEGLTFLIGHTFALLOFF) -return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); -#else -return computeDistanceLightFalloff_Standard(lightOffset,range); -#endif -} -float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) -{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) -{falloff=max(0.,pow(cosAngle,exponent));} -return falloff;} -float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) -{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; -float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} -float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) -{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} -float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) -{ -#ifdef USEPHYSICALLIGHTFALLOFF -return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); -#elif defined(USEGLTFLIGHTFALLOFF) -return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); -#else -return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); -#endif -}`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrDirectLightingFalloffFunctions_name] = pbrDirectLightingFalloffFunctions_shader; -/** @internal */ -const pbrDirectLightingFalloffFunctions = { name: pbrDirectLightingFalloffFunctions_name, shader: pbrDirectLightingFalloffFunctions_shader }; -//# sourceMappingURL=pbrDirectLightingFalloffFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBRDFFunctions.js -// Do not edit. - -const pbrBRDFFunctions_name = "pbrBRDFFunctions"; -const pbrBRDFFunctions_shader = `#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 -#ifdef MS_BRDF_ENERGY_CONSERVATION -vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} -#endif -#ifdef ENVIRONMENTBRDF -vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); -#ifdef ENVIRONMENTBRDF_RGBD -brdfLookup.rgb=fromRGBD(brdfLookup.rgba); -#endif -return brdfLookup.rgb;} -vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { -#ifdef BRDF_V_HEIGHT_CORRELATED -vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; -#else -vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; -#endif -return reflectance;} -vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { -#ifdef BRDF_V_HEIGHT_CORRELATED -vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); -#else -vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; -#endif -return reflectance;} -#endif -/* NOT USED -#if defined(SHEEN) && defined(SHEEN_SOFTER) -float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) -{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} -#endif -*/ -#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) -vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) -{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) -/** -* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. -* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table -*/ -vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} -#endif -vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) -{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} -float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) -{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} -#ifdef CLEARCOAT -vec3 getR0RemappedForClearCoat(vec3 f0) { -#ifdef CLEARCOAT_DEFAULTIOR -#ifdef MOBILE -return saturate(f0*(f0*0.526868+0.529324)-0.0482256); -#else -return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); -#endif -#else -vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); -#endif -} -#endif -#ifdef IRIDESCENCE -const mat3 XYZ_TO_REC709=mat3( -3.2404542,-0.9692660, 0.0556434, --1.5371385, 1.8760108,-0.2040259, --0.4985314, 0.0415560, 1.0572252 -);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} -vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} -float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} -vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} -vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} -float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR<outsideIOR) phi12=PI;float phi21=PI-phi12;vec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999)); -vec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);vec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));vec3 phi23=vec3(0.0);if (baseIOR[0]<iridescenceIOR) phi23[0]=PI;if (baseIOR[1]<iridescenceIOR) phi23[1]=PI;if (baseIOR[2]<iridescenceIOR) phi23[2]=PI;float opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;vec3 phi=vec3(phi21)+phi23;vec3 R123=clamp(R12*R23,1e-5,0.9999);vec3 r123=sqrt(R123);vec3 Rs=square(T121)*R23/(vec3(1.0)-R123);vec3 C0=R12+Rs;I=C0;vec3 Cm=Rs-T121;for (int m=1; m<=2; ++m) -{Cm*=r123;vec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);I+=Cm*Sm;} -return max(I,vec3(0.0));} -#endif -float normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG) -{float a2=square(alphaG);float d=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);} -#ifdef SHEEN -float normalDistributionFunction_CharlieSheen(float NdotH,float alphaG) -{float invR=1./alphaG;float cos2h=NdotH*NdotH;float sin2h=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);} -#endif -#ifdef ANISOTROPIC -float normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {float a2=alphaTB.x*alphaTB.y;vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);float v2=dot(v,v);float w2=a2/v2;return a2*w2*w2*RECIPROCAL_PI;} -#endif -#ifdef BRDF_V_HEIGHT_CORRELATED -float smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) { -#ifdef MOBILE -float GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL); -#else -float a2=alphaG*alphaG;float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL); -#endif -} -#else -float smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG) -{ -#ifdef MOBILE -return 1.0/(dot+alphaG+(1.0-alphaG)*dot )); -#else -float alphaSquared=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot)); -#endif -} -float smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG) -{float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;} -#endif -#ifdef ANISOTROPIC -float smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));float v=0.5/(lambdaV+lambdaL);return v;} -#endif -#ifdef CLEARCOAT -float visibility_Kelemen(float VdotH) {return 0.25/(VdotH*VdotH); } -#endif -#ifdef SHEEN -float visibility_Ashikhmin(float NdotL,float NdotV) -{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));} -/* NOT USED -#ifdef SHEEN_SOFTER -float l(float x,float alphaG) -{float oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);float a=mix(21.5473,25.3245,oneMinusAlphaSq);float b=mix(3.82987,3.32435,oneMinusAlphaSq);float c=mix(0.19823,0.16801,oneMinusAlphaSq);float d=mix(-1.97760,-1.27393,oneMinusAlphaSq);float e=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;} -float lambdaSheen(float cosTheta,float alphaG) -{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));} -float visibility_CharlieSheen(float NdotL,float NdotV,float alphaG) -{float G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);} -#endif -*/ -#endif -float diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;float fresnel = -(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) * -(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;} -#ifdef SS_TRANSLUCENCY -vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);} -float computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBRDFFunctions_name] = pbrBRDFFunctions_shader; -/** @internal */ -const pbrBRDFFunctions = { name: pbrBRDFFunctions_name, shader: pbrBRDFFunctions_shader }; -//# sourceMappingURL=pbrBRDFFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/hdrFilteringFunctions.js -// Do not edit. - -const hdrFilteringFunctions_name = "hdrFilteringFunctions"; -const hdrFilteringFunctions_shader = `#ifdef NUM_SAMPLES -#if NUM_SAMPLES>0 -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -float radicalInverse_VdC(uint bits) -{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } -vec2 hammersley(uint i,uint N) -{return vec2(float(i)/float(N),radicalInverse_VdC(i));} -#else -float vanDerCorpus(int n,int base) -{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) -{if(n>0) -{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} -return result;} -vec2 hammersley(int i,int N) -{return vec2(float(i)/float(N),vanDerCorpus(i,2));} -#endif -float log4(float x) {return log2(x)/2.;} -const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; -#define inline -vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) -{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -for(uint i=0u; i<NUM_SAMPLES; ++i) -#else -for(int i=0; i<NUM_SAMPLES; ++i) -#endif -{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 Ls=hemisphereCosSample(Xi);Ls=normalize(Ls);vec3 Ns=vec3(0.,0.,1.);float NoL=dot(Ns,Ls);if (NoL>0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -result+=c;}} -result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} -#define inline -vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) -{vec3 n=normalize(inputN);if (alphaG==0.) {vec3 c=textureCube(inputTexture,n).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -for(uint i=0u; i<NUM_SAMPLES; ++i) -#else -for(int i=0; i<NUM_SAMPLES; ++i) -#endif -{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);float NoV=1.;float NoH=H.z;float NoH2=H.z*H.z;float NoL=2.*NoH2-1.;vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -result+=c*NoL;}} -result=result/weight;return result;}} -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[hdrFilteringFunctions_name] = hdrFilteringFunctions_shader; -/** @internal */ -const hdrFilteringFunctions = { name: hdrFilteringFunctions_name, shader: hdrFilteringFunctions_shader }; -//# sourceMappingURL=hdrFilteringFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDirectLightingFunctions.js -// Do not edit. - -const pbrDirectLightingFunctions_name = "pbrDirectLightingFunctions"; -const pbrDirectLightingFunctions_shader = `#define CLEARCOATREFLECTANCE90 1.0 -struct lightingInfo -{vec3 diffuse; -#ifdef SPECULARTERM -vec3 specular; -#endif -#ifdef CLEARCOAT -vec4 clearCoat; -#endif -#ifdef SHEEN -vec3 sheen; -#endif -};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { -#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) -float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; -#else -return roughness; -#endif -} -vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} -vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} -#define inline -vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} -#ifdef SS_TRANSLUCENCY -vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} -#endif -#ifdef SPECULARTERM -vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); -#ifdef IRIDESCENCE -fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); -#endif -float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); -#ifdef BRDF_V_HEIGHT_CORRELATED -float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); -#else -float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); -#endif -vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} -#endif -#ifdef ANISOTROPIC -vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); -#ifdef IRIDESCENCE -fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); -#endif -float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} -#endif -#ifdef CLEARCOAT -vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( -clearCoatTerm*info.attenuation*NccdotL*lightColor, -1.0-fresnel -);} -vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} -#endif -#ifdef SHEEN -vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER -float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); -#else */ -float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ -float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrDirectLightingFunctions_name] = pbrDirectLightingFunctions_shader; -/** @internal */ -const pbrDirectLightingFunctions = { name: pbrDirectLightingFunctions_name, shader: pbrDirectLightingFunctions_shader }; -//# sourceMappingURL=pbrDirectLightingFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrIBLFunctions.js -// Do not edit. - -const pbrIBLFunctions_name = "pbrIBLFunctions"; -const pbrIBLFunctions_shader = `#if defined(REFLECTION) || defined(SS_REFRACTION) -float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} -float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} -#endif -#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) -float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} -#endif -#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) -float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} -#endif -#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) -#define UNPACK_LOD(x) (1.0-x)*255.0 -float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrIBLFunctions_name] = pbrIBLFunctions_shader; -/** @internal */ -const pbrIBLFunctions = { name: pbrIBLFunctions_name, shader: pbrIBLFunctions_shader }; -//# sourceMappingURL=pbrIBLFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAlbedoOpacity.js -// Do not edit. - - -const pbrBlockAlbedoOpacity_name = "pbrBlockAlbedoOpacity"; -const pbrBlockAlbedoOpacity_shader = `struct albedoOpacityOutParams -{vec3 surfaceAlbedo;float alpha;}; -#define pbr_inline -void albedoOpacityBlock( -in vec4 vAlbedoColor, -#ifdef ALBEDO -in vec4 albedoTexture, -in vec2 albedoInfos, -#endif -#ifdef OPACITY -in vec4 opacityMap, -in vec2 vOpacityInfos, -#endif -#ifdef DETAIL -in vec4 detailColor, -in vec4 vDetailInfos, -#endif -#ifdef DECAL -in vec4 decalColor, -in vec4 vDecalInfos, -#endif -out albedoOpacityOutParams outParams -) -{vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; -#ifdef ALBEDO -#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) -alpha*=albedoTexture.a; -#endif -#ifdef GAMMAALBEDO -surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); -#else -surfaceAlbedo*=albedoTexture.rgb; -#endif -surfaceAlbedo*=albedoInfos.y; -#endif -#ifndef DECAL_AFTER_DETAIL -#include<decalFragment> -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -surfaceAlbedo*=vColor.rgb; -#endif -#ifdef DETAIL -float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; -#endif -#ifdef DECAL_AFTER_DETAIL -#include<decalFragment> -#endif -#define CUSTOM_FRAGMENT_UPDATE_ALBEDO -#ifdef OPACITY -#ifdef OPACITYRGB -alpha=getLuminance(opacityMap.rgb); -#else -alpha*=opacityMap.a; -#endif -alpha*=vOpacityInfos.y; -#endif -#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) -alpha*=vColor.a; -#endif -#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) -#ifdef ALPHATEST -#if DEBUGMODE != 88 -if (alpha<ALPHATESTVALUE) -discard; -#endif -#ifndef ALPHABLEND -alpha=1.0; -#endif -#endif -#endif -outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;} -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockAlbedoOpacity_name] = pbrBlockAlbedoOpacity_shader; -/** @internal */ -const pbrBlockAlbedoOpacity = { name: pbrBlockAlbedoOpacity_name, shader: pbrBlockAlbedoOpacity_shader }; -//# sourceMappingURL=pbrBlockAlbedoOpacity.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectivity.js -// Do not edit. - -const pbrBlockReflectivity_name = "pbrBlockReflectivity"; -const pbrBlockReflectivity_shader = `struct reflectivityOutParams -{float microSurface;float roughness;vec3 surfaceReflectivityColor; -#ifdef METALLICWORKFLOW -vec3 surfaceAlbedo; -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -vec3 ambientOcclusionColor; -#endif -#if DEBUGMODE>0 -#ifdef METALLICWORKFLOW -vec2 metallicRoughness; -#ifdef REFLECTIVITY -vec4 surfaceMetallicColorMap; -#endif -#ifndef FROSTBITE_REFLECTANCE -vec3 metallicF0; -#endif -#else -#ifdef REFLECTIVITY -vec4 surfaceReflectivityColorMap; -#endif -#endif -#endif -}; -#define pbr_inline -void reflectivityBlock( -in vec4 vReflectivityColor, -#ifdef METALLICWORKFLOW -in vec3 surfaceAlbedo, -in vec4 metallicReflectanceFactors, -#endif -#ifdef REFLECTIVITY -in vec3 reflectivityInfos, -in vec4 surfaceMetallicOrReflectivityColorMap, -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -in vec3 ambientOcclusionColorIn, -#endif -#ifdef MICROSURFACEMAP -in vec4 microSurfaceTexel, -#endif -#ifdef DETAIL -in vec4 detailColor, -in vec4 vDetailInfos, -#endif -out reflectivityOutParams outParams -) -{float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; -#ifdef METALLICWORKFLOW -vec2 metallicRoughness=surfaceReflectivityColor.rg; -#ifdef REFLECTIVITY -#if DEBUGMODE>0 -outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; -#endif -#ifdef AOSTOREINMETALMAPRED -vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); -#endif -#ifdef METALLNESSSTOREINMETALMAPBLUE -metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; -#else -metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; -#endif -#ifdef ROUGHNESSSTOREINMETALMAPALPHA -metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; -#else -#ifdef ROUGHNESSSTOREINMETALMAPGREEN -metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; -#endif -#endif -#endif -#ifdef DETAIL -float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); -#endif -#ifdef MICROSURFACEMAP -metallicRoughness.g*=microSurfaceTexel.r; -#endif -#if DEBUGMODE>0 -outParams.metallicRoughness=metallicRoughness; -#endif -#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS -microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; -#ifdef FROSTBITE_REFLECTANCE -outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); -#else -vec3 metallicF0=metallicReflectanceFactors.rgb; -#if DEBUGMODE>0 -outParams.metallicF0=metallicF0; -#endif -outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); -#endif -#else -#ifdef REFLECTIVITY -surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; -#if DEBUGMODE>0 -outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; -#endif -#ifdef MICROSURFACEFROMREFLECTIVITYMAP -microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; -#else -#ifdef MICROSURFACEAUTOMATIC -microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); -#endif -#ifdef MICROSURFACEMAP -microSurface*=microSurfaceTexel.r; -#endif -#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE -#endif -#endif -#endif -microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;} -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockReflectivity_name] = pbrBlockReflectivity_shader; -/** @internal */ -const pbrBlockReflectivity = { name: pbrBlockReflectivity_name, shader: pbrBlockReflectivity_shader }; -//# sourceMappingURL=pbrBlockReflectivity.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAmbientOcclusion.js -// Do not edit. - -const pbrBlockAmbientOcclusion_name = "pbrBlockAmbientOcclusion"; -const pbrBlockAmbientOcclusion_shader = `struct ambientOcclusionOutParams -{vec3 ambientOcclusionColor; -#if DEBUGMODE>0 && defined(AMBIENT) -vec3 ambientOcclusionColorMap; -#endif -}; -#define pbr_inline -void ambientOcclusionBlock( -#ifdef AMBIENT -in vec3 ambientOcclusionColorMap_, -in vec4 vAmbientInfos, -#endif -out ambientOcclusionOutParams outParams -) -{vec3 ambientOcclusionColor=vec3(1.,1.,1.); -#ifdef AMBIENT -vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; -#ifdef AMBIENTINGRAYSCALE -ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); -#endif -ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); -#if DEBUGMODE>0 -outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; -#endif -#endif -outParams.ambientOcclusionColor=ambientOcclusionColor;} -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockAmbientOcclusion_name] = pbrBlockAmbientOcclusion_shader; -/** @internal */ -const pbrBlockAmbientOcclusion = { name: pbrBlockAmbientOcclusion_name, shader: pbrBlockAmbientOcclusion_shader }; -//# sourceMappingURL=pbrBlockAmbientOcclusion.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAlphaFresnel.js -// Do not edit. - -const pbrBlockAlphaFresnel_name = "pbrBlockAlphaFresnel"; -const pbrBlockAlphaFresnel_shader = `#ifdef ALPHAFRESNEL -#if defined(ALPHATEST) || defined(ALPHABLEND) -struct alphaFresnelOutParams -{float alpha;}; -#define pbr_inline -void alphaFresnelBlock( -in vec3 normalW, -in vec3 viewDirectionW, -in float alpha, -in float microSurface, -out alphaFresnelOutParams outParams -) -{float opacityPerceptual=alpha; -#ifdef LINEARALPHAFRESNEL -float opacity0=opacityPerceptual; -#else -float opacity0=opacityPerceptual*opacityPerceptual; -#endif -float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; -#ifdef ALPHATEST -if (outParams.alpha<ALPHATESTVALUE) -discard; -#ifndef ALPHABLEND -outParams.alpha=1.0; -#endif -#endif -} -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockAlphaFresnel_name] = pbrBlockAlphaFresnel_shader; -/** @internal */ -const pbrBlockAlphaFresnel = { name: pbrBlockAlphaFresnel_name, shader: pbrBlockAlphaFresnel_shader }; -//# sourceMappingURL=pbrBlockAlphaFresnel.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAnisotropic.js -// Do not edit. - -const pbrBlockAnisotropic_name = "pbrBlockAnisotropic"; -const pbrBlockAnisotropic_shader = `#ifdef ANISOTROPIC -struct anisotropicOutParams -{float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal; -#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE) -vec3 anisotropyMapData; -#endif -}; -#define pbr_inline -void anisotropicBlock( -in vec3 vAnisotropy, -in float roughness, -#ifdef ANISOTROPIC_TEXTURE -in vec3 anisotropyMapData, -#endif -in mat3 TBN, -in vec3 normalW, -in vec3 viewDirectionW, -out anisotropicOutParams outParams -) -{float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); -#ifdef ANISOTROPIC_TEXTURE -anisotropy*=anisotropyMapData.b; -#if DEBUGMODE>0 -outParams.anisotropyMapData=anisotropyMapData; -#endif -anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; -#ifdef ANISOTROPIC_LEGACY -anisotropyDirection.rg*=anisotropyMapData.rg; -#else -anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); -#endif -#endif -mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockAnisotropic_name] = pbrBlockAnisotropic_shader; -/** @internal */ -const pbrBlockAnisotropic = { name: pbrBlockAnisotropic_name, shader: pbrBlockAnisotropic_shader }; -//# sourceMappingURL=pbrBlockAnisotropic.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflection.js -// Do not edit. - -const pbrBlockReflection_name = "pbrBlockReflection"; -const pbrBlockReflection_shader = `#ifdef REFLECTION -struct reflectionOutParams -{vec4 environmentRadiance;vec3 environmentIrradiance; -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords; -#else -vec2 reflectionCoords; -#endif -#ifdef SS_TRANSLUCENCY -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -vec3 irradianceVector; -#endif -#endif -#endif -}; -#define pbr_inline -void createReflectionCoords( -in vec3 vPositionW, -in vec3 normalW, -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#ifdef REFLECTIONMAP_3D -out vec3 reflectionCoords -#else -out vec2 reflectionCoords -#endif -) -{ -#ifdef ANISOTROPIC -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); -#else -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#endif -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -reflectionCoords=reflectionVector; -#else -reflectionCoords=reflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -reflectionCoords/=reflectionVector.z; -#endif -reflectionCoords.y=1.0-reflectionCoords.y; -#endif -} -#define pbr_inline -#define inline -void sampleReflectionTexture( -in float alphaG, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -in float NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -in float roughness, -#endif -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -const vec3 reflectionCoords, -#else -in sampler2D reflectionSampler, -const vec2 reflectionCoords, -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -out vec4 environmentRadiance -) -{ -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); -#elif defined(LINEARSPECULARREFLECTION) -float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); -#else -float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); -#endif -#ifdef LODBASEDMICROSFURACE -reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; -#ifdef LODINREFLECTIONALPHA -float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); -#else -float requestedReflectionLOD=reflectionLOD; -#endif -#ifdef REALTIME_FILTERING -environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); -#else -environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); -#endif -#else -float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( -sampleReflection(reflectionSamplerHigh,reflectionCoords), -environmentMid, -lodReflectionNormalizedDoubled -);} else {environmentRadiance=mix( -environmentMid, -sampleReflection(reflectionSamplerLow,reflectionCoords), -lodReflectionNormalizedDoubled-1.0 -);} -#endif -#ifdef RGBDREFLECTION -environmentRadiance.rgb=fromRGBD(environmentRadiance); -#endif -#ifdef GAMMAREFLECTION -environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); -#endif -environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} -#define pbr_inline -#define inline -void reflectionBlock( -in vec3 vPositionW, -in vec3 normalW, -in float alphaG, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -in float NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -in float roughness, -#endif -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -#else -in sampler2D reflectionSampler, -#endif -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -in vec3 vEnvironmentIrradiance, -#endif -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -in mat4 reflectionMatrix, -#endif -#endif -#ifdef USEIRRADIANCEMAP -#ifdef REFLECTIONMAP_3D -in samplerCube irradianceSampler, -#else -in sampler2D irradianceSampler, -#endif -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -out reflectionOutParams outParams -) -{vec4 environmentRadiance=vec4(0.,0.,0.,0.); -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords=vec3(0.); -#else -vec2 reflectionCoords=vec2(0.); -#endif -createReflectionCoords( -vPositionW, -normalW, -#ifdef ANISOTROPIC -anisotropicOut, -#endif -reflectionCoords -);sampleReflectionTexture( -alphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -roughness, -#endif -#ifdef REFLECTIONMAP_3D -reflectionSampler, -reflectionCoords, -#else -reflectionSampler, -reflectionCoords, -#endif -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentRadiance -);vec3 environmentIrradiance=vec3(0.,0.,0.); -#ifdef USESPHERICALFROMREFLECTIONMAP -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -environmentIrradiance=vEnvironmentIrradiance; -#else -#ifdef ANISOTROPIC -vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; -#else -vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; -#endif -#ifdef REFLECTIONMAP_OPPOSITEZ -irradianceVector.z*=-1.0; -#endif -#ifdef INVERTCUBICMAP -irradianceVector.y*=-1.0; -#endif -#if defined(REALTIME_FILTERING) -environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo); -#else -environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); -#endif -#ifdef SS_TRANSLUCENCY -outParams.irradianceVector=irradianceVector; -#endif -#endif -#elif defined(USEIRRADIANCEMAP) -vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; -#ifdef RGBDREFLECTION -environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); -#endif -#ifdef GAMMAREFLECTION -environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); -#endif -#endif -environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockReflection_name] = pbrBlockReflection_shader; -/** @internal */ -const pbrBlockReflection = { name: pbrBlockReflection_name, shader: pbrBlockReflection_shader }; -//# sourceMappingURL=pbrBlockReflection.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockSheen.js -// Do not edit. - -const pbrBlockSheen_name = "pbrBlockSheen"; -const pbrBlockSheen_shader = `#ifdef SHEEN -struct sheenOutParams -{float sheenIntensity;vec3 sheenColor;float sheenRoughness; -#ifdef SHEEN_LINKWITHALBEDO -vec3 surfaceAlbedo; -#endif -#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -float sheenAlbedoScaling; -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -vec3 finalSheenRadianceScaled; -#endif -#if DEBUGMODE>0 -#ifdef SHEEN_TEXTURE -vec4 sheenMapData; -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -vec3 sheenEnvironmentReflectance; -#endif -#endif -}; -#define pbr_inline -#define inline -void sheenBlock( -in vec4 vSheenColor, -#ifdef SHEEN_ROUGHNESS -in float vSheenRoughness, -#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -in vec4 sheenMapRoughnessData, -#endif -#endif -in float roughness, -#ifdef SHEEN_TEXTURE -in vec4 sheenMapData, -in float sheenMapLevel, -#endif -in float reflectance, -#ifdef SHEEN_LINKWITHALBEDO -in vec3 baseColor, -in vec3 surfaceAlbedo, -#endif -#ifdef ENVIRONMENTBRDF -in float NdotV, -in vec3 environmentBrdf, -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -in vec2 AARoughnessFactors, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -in vec4 vLightingIntensity, -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -in vec3 reflectionCoords, -#else -in sampler2D reflectionSampler, -in vec2 reflectionCoords, -#endif -in float NdotVUnclamped, -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -in float seo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -in float eho, -#endif -#endif -out sheenOutParams outParams -) -{float sheenIntensity=vSheenColor.a; -#ifdef SHEEN_TEXTURE -#if DEBUGMODE>0 -outParams.sheenMapData=sheenMapData; -#endif -#endif -#ifdef SHEEN_LINKWITHALBEDO -float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; -#ifdef SHEEN_TEXTURE -sheenIntensity*=sheenMapData.a; -#endif -#else -vec3 sheenColor=vSheenColor.rgb; -#ifdef SHEEN_TEXTURE -#ifdef SHEEN_GAMMATEXTURE -sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); -#else -sheenColor.rgb*=sheenMapData.rgb; -#endif -sheenColor.rgb*=sheenMapLevel; -#endif -#ifdef SHEEN_ROUGHNESS -float sheenRoughness=vSheenRoughness; -#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE -#if defined(SHEEN_TEXTURE) -sheenRoughness*=sheenMapData.a; -#endif -#elif defined(SHEEN_TEXTURE_ROUGHNESS) -#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL -sheenRoughness*=sheenMapData.a; -#else -sheenRoughness*=sheenMapRoughnessData.a; -#endif -#endif -#else -float sheenRoughness=roughness; -#ifdef SHEEN_TEXTURE -sheenIntensity*=sheenMapData.a; -#endif -#endif -#if !defined(SHEEN_ALBEDOSCALING) -sheenIntensity*=(1.-reflectance); -#endif -sheenColor*=sheenIntensity; -#endif -#ifdef ENVIRONMENTBRDF -/*#ifdef SHEEN_SOFTER -vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); -#else*/ -#ifdef SHEEN_ROUGHNESS -vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); -#else -vec3 environmentSheenBrdf=environmentBrdf; -#endif -/*#endif*/ -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); -#ifdef SPECULARAA -sheenAlphaG+=AARoughnessFactors.y; -#endif -vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( -sheenAlphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -sheenRoughness, -#endif -reflectionSampler, -reflectionCoords, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentSheenRadiance -);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -sheenEnvironmentReflectance*=seo; -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -sheenEnvironmentReflectance*=eho; -#endif -#if DEBUGMODE>0 -outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; -#endif -outParams.finalSheenRadianceScaled= -environmentSheenRadiance.rgb * -sheenEnvironmentReflectance * -vLightingIntensity.z; -#endif -#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; -#endif -outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockSheen_name] = pbrBlockSheen_shader; -/** @internal */ -const pbrBlockSheen = { name: pbrBlockSheen_name, shader: pbrBlockSheen_shader }; -//# sourceMappingURL=pbrBlockSheen.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockClearcoat.js -// Do not edit. - -const pbrBlockClearcoat_name = "pbrBlockClearcoat"; -const pbrBlockClearcoat_shader = `struct clearcoatOutParams -{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; -#ifdef REFLECTION -vec3 finalClearCoatRadianceScaled; -#endif -#ifdef CLEARCOAT_TINT -vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; -#endif -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -vec3 energyConservationFactorClearCoat; -#endif -#if DEBUGMODE>0 -#ifdef CLEARCOAT_BUMP -mat3 TBNClearCoat; -#endif -#ifdef CLEARCOAT_TEXTURE -vec2 clearCoatMapData; -#endif -#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -vec4 clearCoatTintMapData; -#endif -#ifdef REFLECTION -vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; -#endif -float clearCoatNdotV; -#endif -}; -#ifdef CLEARCOAT -#define pbr_inline -#define inline -void clearcoatBlock( -in vec3 vPositionW, -in vec3 geometricNormalW, -in vec3 viewDirectionW, -in vec2 vClearCoatParams, -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -in vec4 clearCoatMapRoughnessData, -#endif -in vec3 specularEnvironmentR0, -#ifdef CLEARCOAT_TEXTURE -in vec2 clearCoatMapData, -#endif -#ifdef CLEARCOAT_TINT -in vec4 vClearCoatTintParams, -in float clearCoatColorAtDistance, -in vec4 vClearCoatRefractionParams, -#ifdef CLEARCOAT_TINT_TEXTURE -in vec4 clearCoatTintMapData, -#endif -#endif -#ifdef CLEARCOAT_BUMP -in vec2 vClearCoatBumpInfos, -in vec4 clearCoatBumpMapData, -in vec2 vClearCoatBumpUV, -#if defined(TANGENT) && defined(NORMAL) -in mat3 vTBN, -#else -in vec2 vClearCoatTangentSpaceParams, -#endif -#ifdef OBJECTSPACE_NORMALMAP -in mat4 normalMatrix, -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -in vec3 faceNormal, -#endif -#ifdef REFLECTION -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -in vec4 vLightingIntensity, -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -#else -in sampler2D reflectionSampler, -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -in float ambientMonochrome, -#endif -#endif -#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) -in float frontFacingMultiplier, -#endif -out clearcoatOutParams outParams -) -{float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; -#ifdef CLEARCOAT_TEXTURE -clearCoatIntensity*=clearCoatMapData.x; -#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE -clearCoatRoughness*=clearCoatMapData.y; -#endif -#if DEBUGMODE>0 -outParams.clearCoatMapData=clearCoatMapData; -#endif -#endif -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL -clearCoatRoughness*=clearCoatMapData.y; -#else -clearCoatRoughness*=clearCoatMapRoughnessData.y; -#endif -#endif -outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; -#ifdef CLEARCOAT_TINT -vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; -#ifdef CLEARCOAT_TINT_TEXTURE -#ifdef CLEARCOAT_TINT_GAMMATEXTURE -clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); -#else -clearCoatColor*=clearCoatTintMapData.rgb; -#endif -clearCoatThickness*=clearCoatTintMapData.a; -#if DEBUGMODE>0 -outParams.clearCoatTintMapData=clearCoatTintMapData; -#endif -#endif -outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; -#endif -#ifdef CLEARCOAT_REMAP_F0 -vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); -#else -vec3 specularEnvironmentR0Updated=specularEnvironmentR0; -#endif -outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; -#ifdef CLEARCOAT_BUMP -#ifdef NORMALXYSCALE -float clearCoatNormalScale=1.0; -#else -float clearCoatNormalScale=vClearCoatBumpInfos.y; -#endif -#if defined(TANGENT) && defined(NORMAL) -mat3 TBNClearCoat=vTBN; -#else -vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); -#endif -#if DEBUGMODE>0 -outParams.TBNClearCoat=TBNClearCoat; -#endif -#ifdef OBJECTSPACE_NORMALMAP -clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); -#else -clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); -#endif -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; -#endif -outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); -#if DEBUGMODE>0 -outParams.clearCoatNdotV=clearCoatNdotV; -#endif -#ifdef CLEARCOAT_TINT -vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); -#endif -#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) -vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); -#endif -#if defined(REFLECTION) -float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); -#ifdef SPECULARAA -clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; -#endif -vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); -#ifdef REFLECTIONMAP_OPPOSITEZ -clearCoatReflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -vec3 clearCoatReflectionCoords=clearCoatReflectionVector; -#else -vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -clearCoatReflectionCoords/=clearCoatReflectionVector.z; -#endif -clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; -#endif -sampleReflectionTexture( -clearCoatAlphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -clearCoatNdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -clearCoatRoughness, -#endif -reflectionSampler, -clearCoatReflectionCoords, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentClearCoatRadiance -); -#if DEBUGMODE>0 -outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; -#endif -#endif -#endif -#else -vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); -#endif -clearCoatEnvironmentReflectance*=clearCoatIntensity; -#if DEBUGMODE>0 -outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; -#endif -outParams.finalClearCoatRadianceScaled= -environmentClearCoatRadiance.rgb * -clearCoatEnvironmentReflectance * -vLightingIntensity.z; -#endif -#if defined(CLEARCOAT_TINT) -outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); -#endif -float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); -#endif -} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockClearcoat_name] = pbrBlockClearcoat_shader; -/** @internal */ -const pbrBlockClearcoat = { name: pbrBlockClearcoat_name, shader: pbrBlockClearcoat_shader }; -//# sourceMappingURL=pbrBlockClearcoat.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockIridescence.js -// Do not edit. - -const pbrBlockIridescence_name = "pbrBlockIridescence"; -const pbrBlockIridescence_shader = `struct iridescenceOutParams -{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; -#ifdef IRIDESCENCE -#define pbr_inline -#define inline -void iridescenceBlock( -in vec4 vIridescenceParams, -in float viewAngle, -in vec3 specularEnvironmentR0, -#ifdef IRIDESCENCE_TEXTURE -in vec2 iridescenceMapData, -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -in vec2 iridescenceThicknessMapData, -#endif -#ifdef CLEARCOAT -in float NdotVUnclamped, -#ifdef CLEARCOAT_TEXTURE -in vec2 clearCoatMapData, -#endif -#endif -out iridescenceOutParams outParams -) -{float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; -#ifdef IRIDESCENCE_TEXTURE -iridescenceIntensity*=iridescenceMapData.x; -#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE -iridescenceThicknessWeight=iridescenceMapData.g; -#endif -#endif -#if defined(IRIDESCENCE_THICKNESS_TEXTURE) -iridescenceThicknessWeight=iridescenceThicknessMapData.g; -#endif -float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; -#ifdef CLEARCOAT -float clearCoatIntensity=vClearCoatParams.x; -#ifdef CLEARCOAT_TEXTURE -clearCoatIntensity*=clearCoatMapData.x; -#endif -topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); -#endif -vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockIridescence_name] = pbrBlockIridescence_shader; -/** @internal */ -const pbrBlockIridescence = { name: pbrBlockIridescence_name, shader: pbrBlockIridescence_shader }; -//# sourceMappingURL=pbrBlockIridescence.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockSubSurface.js -// Do not edit. - -const pbrBlockSubSurface_name = "pbrBlockSubSurface"; -const pbrBlockSubSurface_shader = `struct subSurfaceOutParams -{vec3 specularEnvironmentReflectance; -#ifdef SS_REFRACTION -vec3 finalRefraction;vec3 surfaceAlbedo; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -float alpha; -#endif -#ifdef REFLECTION -float refractionFactorForIrradiance; -#endif -#endif -#ifdef SS_TRANSLUCENCY -vec3 transmittance;float translucencyIntensity; -#ifdef REFLECTION -vec3 refractionIrradiance; -#endif -#endif -#if DEBUGMODE>0 -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec4 thicknessMap; -#endif -#ifdef SS_REFRACTION -vec4 environmentRefraction;vec3 refractionTransmittance; -#endif -#endif -}; -#ifdef SUBSURFACE -#define pbr_inline -#define inline -void subSurfaceBlock( -in vec3 vSubSurfaceIntensity, -in vec2 vThicknessParam, -in vec4 vTintColor, -in vec3 normalW, -in vec3 specularEnvironmentReflectance, -#ifdef SS_THICKNESSANDMASK_TEXTURE -in vec4 thicknessMap, -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -in vec4 refractionIntensityMap, -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -in vec4 translucencyIntensityMap, -#endif -#ifdef REFLECTION -#ifdef SS_TRANSLUCENCY -in mat4 reflectionMatrix, -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -in vec3 irradianceVector_, -#endif -#if defined(REALTIME_FILTERING) -in samplerCube reflectionSampler, -in vec2 vReflectionFilteringInfo, -#endif -#endif -#ifdef USEIRRADIANCEMAP -#ifdef REFLECTIONMAP_3D -in samplerCube irradianceSampler, -#else -in sampler2D irradianceSampler, -#endif -#endif -#endif -#endif -#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) -in vec3 surfaceAlbedo, -#endif -#ifdef SS_REFRACTION -in vec3 vPositionW, -in vec3 viewDirectionW, -in mat4 view, -in vec4 vRefractionInfos, -in mat4 refractionMatrix, -in vec4 vRefractionMicrosurfaceInfos, -in vec4 vLightingIntensity, -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -in float alpha, -#endif -#ifdef SS_LODINREFRACTIONALPHA -in float NdotVUnclamped, -#endif -#ifdef SS_LINEARSPECULARREFRACTION -in float roughness, -#endif -in float alphaG, -#ifdef SS_REFRACTIONMAP_3D -in samplerCube refractionSampler, -#ifndef LODBASEDMICROSFURACE -in samplerCube refractionSamplerLow, -in samplerCube refractionSamplerHigh, -#endif -#else -in sampler2D refractionSampler, -#ifndef LODBASEDMICROSFURACE -in sampler2D refractionSamplerLow, -in sampler2D refractionSamplerHigh, -#endif -#endif -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#ifdef REALTIME_FILTERING -in vec2 vRefractionFilteringInfo, -#endif -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -in vec3 refractionPosition, -in vec3 refractionSize, -#endif -#endif -#ifdef SS_TRANSLUCENCY -in vec3 vDiffusionDistance, -#endif -out subSurfaceOutParams outParams -) -{outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; -#ifdef SS_REFRACTION -float refractionIntensity=vSubSurfaceIntensity.x; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; -#endif -#endif -#ifdef SS_TRANSLUCENCY -float translucencyIntensity=vSubSurfaceIntensity.y; -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -#if defined(SS_USE_GLTF_TEXTURES) -float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; -#else -float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; -#endif -#if DEBUGMODE>0 -outParams.thicknessMap=thicknessMap; -#endif -#ifdef SS_MASK_FROM_THICKNESS_TEXTURE -#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE) -#if defined(SS_USE_GLTF_TEXTURES) -refractionIntensity*=thicknessMap.r; -#else -refractionIntensity*=thicknessMap.g; -#endif -#endif -#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE) -translucencyIntensity*=thicknessMap.b; -#endif -#endif -#else -float thickness=vThicknessParam.y; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -#ifdef SS_USE_GLTF_TEXTURES -refractionIntensity*=refractionIntensityMap.r; -#else -refractionIntensity*=refractionIntensityMap.g; -#endif -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -translucencyIntensity*=translucencyIntensityMap.b; -#endif -#ifdef SS_TRANSLUCENCY -thickness=maxEps(thickness);vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; -#endif -#ifdef SS_REFRACTION -vec4 environmentRefraction=vec4(0.,0.,0.,0.); -#ifdef ANISOTROPIC -vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y); -#else -vec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y); -#endif -#ifdef SS_REFRACTIONMAP_OPPOSITEZ -refractionVector.z*=-1.0; -#endif -#ifdef SS_REFRACTIONMAP_3D -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); -#endif -refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); -#else -#ifdef SS_USE_THICKNESS_AS_DEPTH -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); -#else -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); -#endif -vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; -#endif -#ifdef SS_HAS_THICKNESS -float ior=vRefractionInfos.y; -#else -float ior=vRefractionMicrosurfaceInfos.w; -#endif -#ifdef SS_LODINREFRACTIONALPHA -float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); -#elif defined(SS_LINEARSPECULARREFRACTION) -float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); -#else -float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); -#endif -#ifdef LODBASEDMICROSFURACE -refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; -#ifdef SS_LODINREFRACTIONALPHA -float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); -#else -float requestedRefractionLOD=refractionLOD; -#endif -#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) -environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); -#else -environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); -#endif -#else -float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( -sampleRefraction(refractionSamplerHigh,refractionCoords), -environmentRefractionMid, -lodRefractionNormalizedDoubled -);} else {environmentRefraction=mix( -environmentRefractionMid, -sampleRefraction(refractionSamplerLow,refractionCoords), -lodRefractionNormalizedDoubled-1.0 -);} -#endif -#ifdef SS_RGBDREFRACTION -environmentRefraction.rgb=fromRGBD(environmentRefraction); -#endif -#ifdef SS_GAMMAREFRACTION -environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); -#endif -environmentRefraction.rgb*=vRefractionInfos.x; -#endif -#ifdef SS_REFRACTION -vec3 refractionTransmittance=vec3(refractionIntensity); -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); -#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) -float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; -#else -vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); -#endif -#ifdef SS_ALBEDOFORREFRACTIONTINT -environmentRefraction.rgb*=surfaceAlbedo.rgb; -#endif -outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); -#ifdef REFLECTION -outParams.refractionFactorForIrradiance=(1.-refractionIntensity); -#endif -#ifdef UNUSED_MULTIPLEBOUNCES -vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); -#endif -refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; -#if DEBUGMODE>0 -outParams.refractionTransmittance=refractionTransmittance; -#endif -outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; -#if DEBUGMODE>0 -outParams.environmentRefraction=environmentRefraction; -#endif -#endif -#if defined(REFLECTION) && defined(SS_TRANSLUCENCY) -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) -vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; -#ifdef REFLECTIONMAP_OPPOSITEZ -irradianceVector.z*=-1.0; -#endif -#ifdef INVERTCUBICMAP -irradianceVector.y*=-1.0; -#endif -#else -vec3 irradianceVector=irradianceVector_; -#endif -#if defined(USESPHERICALFROMREFLECTIONMAP) -#if defined(REALTIME_FILTERING) -vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo); -#else -vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); -#endif -#elif defined(USEIRRADIANCEMAP) -#ifdef REFLECTIONMAP_3D -vec3 irradianceCoords=irradianceVector; -#else -vec2 irradianceCoords=irradianceVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -irradianceCoords/=irradianceVector.z; -#endif -irradianceCoords.y=1.0-irradianceCoords.y; -#endif -vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); -#ifdef RGBDREFLECTION -refractionIrradiance.rgb=fromRGBD(refractionIrradiance); -#endif -#ifdef GAMMAREFLECTION -refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); -#endif -#else -vec4 refractionIrradiance=vec4(0.); -#endif -refractionIrradiance.rgb*=transmittance; -#ifdef SS_ALBEDOFORTRANSLUCENCYTINT -refractionIrradiance.rgb*=surfaceAlbedo.rgb; -#endif -outParams.refractionIrradiance=refractionIrradiance.rgb; -#endif -} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockSubSurface_name] = pbrBlockSubSurface_shader; -/** @internal */ -const pbrBlockSubSurface = { name: pbrBlockSubSurface_name, shader: pbrBlockSubSurface_shader }; -//# sourceMappingURL=pbrBlockSubSurface.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockNormalGeometric.js -// Do not edit. - -const pbrBlockNormalGeometric_name = "pbrBlockNormalGeometric"; -const pbrBlockNormalGeometric_shader = `vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; -#endif -vec3 geometricNormalW=normalW; -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockNormalGeometric_name] = pbrBlockNormalGeometric_shader; -/** @internal */ -const pbrBlockNormalGeometric = { name: pbrBlockNormalGeometric_name, shader: pbrBlockNormalGeometric_shader }; -//# sourceMappingURL=pbrBlockNormalGeometric.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockNormalFinal.js -// Do not edit. - -const pbrBlockNormalFinal_name = "pbrBlockNormalFinal"; -const pbrBlockNormalFinal_shader = `#if defined(FORCENORMALFORWARD) && defined(NORMAL) -vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; -#if defined(TWOSIDEDLIGHTING) -faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; -#endif -normalW*=sign(dot(normalW,faceNormal)); -#endif -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -normalW=gl_FrontFacing ? normalW : -normalW; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockNormalFinal_name] = pbrBlockNormalFinal_shader; -/** @internal */ -const pbrBlockNormalFinal = { name: pbrBlockNormalFinal_name, shader: pbrBlockNormalFinal_shader }; -//# sourceMappingURL=pbrBlockNormalFinal.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockLightmapInit.js -// Do not edit. - -const pbrBlockLightmapInit_name = "pbrBlockLightmapInit"; -const pbrBlockLightmapInit_shader = `#ifdef LIGHTMAP -vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); -#ifdef RGBDLIGHTMAP -lightmapColor.rgb=fromRGBD(lightmapColor); -#endif -#ifdef GAMMALIGHTMAP -lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); -#endif -lightmapColor.rgb*=vLightmapInfos.y; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockLightmapInit_name] = pbrBlockLightmapInit_shader; -/** @internal */ -const pbrBlockLightmapInit = { name: pbrBlockLightmapInit_name, shader: pbrBlockLightmapInit_shader }; -//# sourceMappingURL=pbrBlockLightmapInit.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockGeometryInfo.js -// Do not edit. - -const pbrBlockGeometryInfo_name = "pbrBlockGeometryInfo"; -const pbrBlockGeometryInfo_shader = `float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); -#ifdef SPECULARAA -alphaG+=AARoughnessFactors.y; -#endif -#if defined(ENVIRONMENTBRDF) -vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -#ifdef AMBIENTINGRAYSCALE -float ambientMonochrome=aoOut.ambientOcclusionColor.r; -#else -float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); -#endif -float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); -#endif -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); -#endif -#endif -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockGeometryInfo_name] = pbrBlockGeometryInfo_shader; -/** @internal */ -const pbrBlockGeometryInfo = { name: pbrBlockGeometryInfo_name, shader: pbrBlockGeometryInfo_shader }; -//# sourceMappingURL=pbrBlockGeometryInfo.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectance0.js -// Do not edit. - -const pbrBlockReflectance0_name = "pbrBlockReflectance0"; -const pbrBlockReflectance0_shader = `float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; -#ifdef METALLICWORKFLOW -vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); -#else -vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); -#endif -#ifdef ALPHAFRESNEL -float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockReflectance0_name] = pbrBlockReflectance0_shader; -/** @internal */ -const pbrBlockReflectance0 = { name: pbrBlockReflectance0_name, shader: pbrBlockReflectance0_shader }; -//# sourceMappingURL=pbrBlockReflectance0.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectance.js -// Do not edit. - -const pbrBlockReflectance_name = "pbrBlockReflectance"; -const pbrBlockReflectance_shader = `#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); -#ifdef RADIANCEOCCLUSION -specularEnvironmentReflectance*=seo; -#endif -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -specularEnvironmentReflectance*=eho; -#endif -#endif -#endif -#else -vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); -#endif -#ifdef CLEARCOAT -specularEnvironmentReflectance*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -specularEnvironmentReflectance*=clearcoatOut.absorption; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockReflectance_name] = pbrBlockReflectance_shader; -/** @internal */ -const pbrBlockReflectance = { name: pbrBlockReflectance_name, shader: pbrBlockReflectance_shader }; -//# sourceMappingURL=pbrBlockReflectance.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockDirectLighting.js -// Do not edit. - -const pbrBlockDirectLighting_name = "pbrBlockDirectLighting"; -const pbrBlockDirectLighting_shader = `vec3 diffuseBase=vec3(0.,0.,0.); -#ifdef SPECULARTERM -vec3 specularBase=vec3(0.,0.,0.); -#endif -#ifdef CLEARCOAT -vec3 clearCoatBase=vec3(0.,0.,0.); -#endif -#ifdef SHEEN -vec3 sheenBase=vec3(0.,0.,0.); -#endif -preLightingInfo preInfo;lightingInfo info;float shadow=1.; -#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) -vec3 absorption=vec3(0.); -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockDirectLighting_name] = pbrBlockDirectLighting_shader; -/** @internal */ -const pbrBlockDirectLighting = { name: pbrBlockDirectLighting_name, shader: pbrBlockDirectLighting_shader }; -//# sourceMappingURL=pbrBlockDirectLighting.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalLitComponents.js -// Do not edit. - -const pbrBlockFinalLitComponents_name = "pbrBlockFinalLitComponents"; -const pbrBlockFinalLitComponents_shader = `#if defined(ENVIRONMENTBRDF) -#ifdef MS_BRDF_ENERGY_CONSERVATION -vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); -#endif -#endif -#ifndef METALLICWORKFLOW -#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION -surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; -#endif -#endif -#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) -surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; -#endif -#ifdef REFLECTION -vec3 finalIrradiance=reflectionOut.environmentIrradiance; -#if defined(CLEARCOAT) -finalIrradiance*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -finalIrradiance*=clearcoatOut.absorption; -#endif -#endif -#if defined(SS_REFRACTION) -finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; -#endif -#if defined(SS_TRANSLUCENCY) -finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; -#endif -finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; -#endif -#ifdef SPECULARTERM -vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalSpecularScaled*=energyConservationFactor; -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -finalSpecularScaled*=sheenOut.sheenAlbedoScaling; -#endif -#endif -#ifdef REFLECTION -vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalRadianceScaled*=energyConservationFactor; -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -finalRadianceScaled*=sheenOut.sheenAlbedoScaling; -#endif -#endif -#ifdef SHEEN -vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; -#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) -sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; -#endif -#endif -#endif -#ifdef CLEARCOAT -vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; -#endif -#ifdef SS_REFRACTION -subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; -#ifdef CLEARCOAT_TINT -subSurfaceOut.finalRefraction*=clearcoatOut.absorption; -#endif -#endif -#endif -#ifdef ALPHABLEND -float luminanceOverAlpha=0.0; -#if defined(REFLECTION) && defined(RADIANCEOVERALPHA) -luminanceOverAlpha+=getLuminance(finalRadianceScaled); -#if defined(CLEARCOAT) -luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); -#endif -#endif -#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) -luminanceOverAlpha+=getLuminance(finalSpecularScaled); -#endif -#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) -luminanceOverAlpha+=getLuminance(finalClearCoatScaled); -#endif -#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) -alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockFinalLitComponents_name] = pbrBlockFinalLitComponents_shader; -/** @internal */ -const pbrBlockFinalLitComponents = { name: pbrBlockFinalLitComponents_name, shader: pbrBlockFinalLitComponents_shader }; -//# sourceMappingURL=pbrBlockFinalLitComponents.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalUnlitComponents.js -// Do not edit. - -const pbrBlockFinalUnlitComponents_name = "pbrBlockFinalUnlitComponents"; -const pbrBlockFinalUnlitComponents_shader = `vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; -#ifdef EMISSIVE -vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; -#ifdef GAMMAEMISSIVE -finalEmissive*=toLinearSpace(emissiveColorTex.rgb); -#else -finalEmissive*=emissiveColorTex.rgb; -#endif -finalEmissive*= vEmissiveInfos.y; -#endif -finalEmissive*=vLightingIntensity.y; -#ifdef AMBIENT -vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); -#else -vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; -#endif -finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockFinalUnlitComponents_name] = pbrBlockFinalUnlitComponents_shader; -/** @internal */ -const pbrBlockFinalUnlitComponents = { name: pbrBlockFinalUnlitComponents_name, shader: pbrBlockFinalUnlitComponents_shader }; -//# sourceMappingURL=pbrBlockFinalUnlitComponents.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalColorComposition.js -// Do not edit. - -const pbrBlockFinalColorComposition_name = "pbrBlockFinalColorComposition"; -const pbrBlockFinalColorComposition_shader = `vec4 finalColor=vec4( -#ifndef UNLIT -#ifdef REFLECTION -finalIrradiance + -#endif -#ifdef SPECULARTERM -finalSpecularScaled + -#endif -#ifdef SHEEN -finalSheenScaled + -#endif -#ifdef CLEARCOAT -finalClearCoatScaled + -#endif -#ifdef REFLECTION -finalRadianceScaled + -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) -sheenOut.finalSheenRadianceScaled + -#endif -#ifdef CLEARCOAT -clearcoatOut.finalClearCoatRadianceScaled + -#endif -#endif -#ifdef SS_REFRACTION -subSurfaceOut.finalRefraction + -#endif -#endif -finalAmbient + -finalDiffuse, -alpha); -#ifdef LIGHTMAP -#ifndef LIGHTMAPEXCLUDED -#ifdef USELIGHTMAPASSHADOWMAP -finalColor.rgb*=lightmapColor.rgb; -#else -finalColor.rgb+=lightmapColor.rgb; -#endif -#endif -#endif -finalColor.rgb+=finalEmissive; -#define CUSTOM_FRAGMENT_BEFORE_FOG -finalColor=max(finalColor,0.0); -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockFinalColorComposition_name] = pbrBlockFinalColorComposition_shader; -/** @internal */ -const pbrBlockFinalColorComposition = { name: pbrBlockFinalColorComposition_name, shader: pbrBlockFinalColorComposition_shader }; -//# sourceMappingURL=pbrBlockFinalColorComposition.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockImageProcessing.js -// Do not edit. - -const pbrBlockImageProcessing_name = "pbrBlockImageProcessing"; -const pbrBlockImageProcessing_shader = `#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) -#if !defined(SKIPFINALCOLORCLAMP) -finalColor.rgb=clamp(finalColor.rgb,0.,30.0); -#endif -#else -finalColor=applyImageProcessing(finalColor); -#endif -finalColor.a*=visibility; -#ifdef PREMULTIPLYALPHA -finalColor.rgb*=finalColor.a; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrBlockImageProcessing_name] = pbrBlockImageProcessing_shader; -/** @internal */ -const pbrBlockImageProcessing = { name: pbrBlockImageProcessing_name, shader: pbrBlockImageProcessing_shader }; -//# sourceMappingURL=pbrBlockImageProcessing.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDebug.js -// Do not edit. - -const pbrDebug_name = "pbrDebug"; -const pbrDebug_shader = `#if DEBUGMODE>0 -if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { -#if DEBUGMODE==1 -gl_FragColor.rgb=vPositionW.rgb; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==2 && defined(NORMAL) -gl_FragColor.rgb=vNormalW.rgb; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) -gl_FragColor.rgb=TBN[0]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) -gl_FragColor.rgb=TBN[1]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==5 -gl_FragColor.rgb=normalW; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==6 && defined(MAINUV1) -gl_FragColor.rgb=vec3(vMainUV1,0.0); -#elif DEBUGMODE==7 && defined(MAINUV2) -gl_FragColor.rgb=vec3(vMainUV2,0.0); -#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) -gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) -gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==10 && defined(CLEARCOAT) -gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==11 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicNormal; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==12 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicTangent; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==13 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==20 && defined(ALBEDO) -gl_FragColor.rgb=albedoTexture.rgb; -#ifndef GAMMAALBEDO -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==21 && defined(AMBIENT) -gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; -#elif DEBUGMODE==22 && defined(OPACITY) -gl_FragColor.rgb=opacityMap.rgb; -#elif DEBUGMODE==23 && defined(EMISSIVE) -gl_FragColor.rgb=emissiveColorTex.rgb; -#ifndef GAMMAEMISSIVE -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==24 && defined(LIGHTMAP) -gl_FragColor.rgb=lightmapColor.rgb; -#ifndef GAMMALIGHTMAP -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; -#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); -#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; -#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) -gl_FragColor.rgb=sheenOut.sheenMapData.rgb; -#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) -gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; -#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) -gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; -#elif DEBUGMODE==32 && defined(BUMP) -gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; -#elif DEBUGMODE==40 && defined(SS_REFRACTION) -gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==41 && defined(REFLECTION) -gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; -#ifndef GAMMAREFLECTION -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) -gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==50 -gl_FragColor.rgb=diffuseBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==51 && defined(SPECULARTERM) -gl_FragColor.rgb=specularBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==52 && defined(CLEARCOAT) -gl_FragColor.rgb=clearCoatBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==53 && defined(SHEEN) -gl_FragColor.rgb=sheenBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==54 && defined(REFLECTION) -gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; -#ifndef GAMMAREFLECTION -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==60 -gl_FragColor.rgb=surfaceAlbedo.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==61 -gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==62 && defined(METALLICWORKFLOW) -gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); -#elif DEBUGMODE==71 && defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.metallicF0; -#elif DEBUGMODE==63 -gl_FragColor.rgb=vec3(roughness); -#elif DEBUGMODE==64 -gl_FragColor.rgb=vec3(alphaG); -#elif DEBUGMODE==65 -gl_FragColor.rgb=vec3(NdotV); -#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) -gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==67 && defined(CLEARCOAT) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); -#elif DEBUGMODE==68 && defined(CLEARCOAT) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); -#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) -gl_FragColor.rgb=subSurfaceOut.transmittance; -#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) -gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; -#elif DEBUGMODE==72 -gl_FragColor.rgb=vec3(microSurface); -#elif DEBUGMODE==73 -gl_FragColor.rgb=vAlbedoColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) -gl_FragColor.rgb=vReflectivityColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==75 -gl_FragColor.rgb=vEmissiveColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) -gl_FragColor.rgb=vec3(seo); -#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) -gl_FragColor.rgb=vec3(eho); -#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) -gl_FragColor.rgb=vec3(energyConservationFactor); -#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -gl_FragColor.rgb=specularEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) -gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==86 && defined(ALPHABLEND) -gl_FragColor.rgb=vec3(luminanceOverAlpha); -#elif DEBUGMODE==87 -gl_FragColor.rgb=vec3(alpha); -#elif DEBUGMODE==88 && defined(ALBEDO) -gl_FragColor.rgb=vec3(albedoTexture.a); -#else -float stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); -#endif -gl_FragColor.rgb*=vDebugMode.y; -#ifdef DEBUGMODE_NORMALIZE -gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; -#endif -#ifdef DEBUGMODE_GAMMA -gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); -#endif -gl_FragColor.a=1.0; -#ifdef PREPASS -gl_FragData[0]=toLinearSpace(gl_FragColor); -gl_FragData[1]=vec4(0.,0.,0.,0.); -#endif -} -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrDebug_name] = pbrDebug_shader; -/** @internal */ -const pbrDebug = { name: pbrDebug_name, shader: pbrDebug_shader }; -//# sourceMappingURL=pbrDebug.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/pbr.fragment.js -// Do not edit. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -const pbr_fragment_name = "pbrPixelShader"; -const pbr_fragment_shader = `#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#extension GL_OES_standard_derivatives : enable -#endif -#ifdef LODBASEDMICROSFURACE -#extension GL_EXT_shader_texture_lod : enable -#endif -#define CUSTOM_FRAGMENT_BEGIN -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -#include<prePassDeclaration>[SCENE_MRT_COUNT] -precision highp float; -#include<oitDeclaration> -#ifndef FROMLINEARSPACE -#define FROMLINEARSPACE -#endif -#include<__decl__pbrFragment> -#include<pbrFragmentExtraDeclaration> -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include<pbrFragmentSamplersDeclaration> -#include<imageProcessingDeclaration> -#include<clipPlaneFragmentDeclaration> -#include<logDepthDeclaration> -#include<fogFragmentDeclaration> -#include<helperFunctions> -#include<subSurfaceScatteringFunctions> -#include<importanceSampling> -#include<pbrHelperFunctions> -#include<imageProcessingFunctions> -#include<shadowsFragmentFunctions> -#include<harmonicsFunctions> -#include<pbrDirectLightingSetupFunctions> -#include<pbrDirectLightingFalloffFunctions> -#include<pbrBRDFFunctions> -#include<hdrFilteringFunctions> -#include<pbrDirectLightingFunctions> -#include<pbrIBLFunctions> -#include<bumpFragmentMainFunctions> -#include<bumpFragmentFunctions> -#ifdef REFLECTION -#include<reflectionFunction> -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -#include<pbrBlockAlbedoOpacity> -#include<pbrBlockReflectivity> -#include<pbrBlockAmbientOcclusion> -#include<pbrBlockAlphaFresnel> -#include<pbrBlockAnisotropic> -#include<pbrBlockReflection> -#include<pbrBlockSheen> -#include<pbrBlockClearcoat> -#include<pbrBlockIridescence> -#include<pbrBlockSubSurface> -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -#include<pbrBlockNormalGeometric> -#include<bumpFragment> -#include<pbrBlockNormalFinal> -albedoOpacityOutParams albedoOpacityOut; -#ifdef ALBEDO -vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); -#endif -#ifdef DECAL -vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); -#endif -albedoOpacityBlock( -vAlbedoColor, -#ifdef ALBEDO -albedoTexture, -vAlbedoInfos, -#endif -#ifdef OPACITY -opacityMap, -vOpacityInfos, -#endif -#ifdef DETAIL -detailColor, -vDetailInfos, -#endif -#ifdef DECAL -decalColor, -vDecalInfos, -#endif -albedoOpacityOut -);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; -#define CUSTOM_FRAGMENT_UPDATE_ALPHA -#include<depthPrePass> -#define CUSTOM_FRAGMENT_BEFORE_LIGHTS -ambientOcclusionOutParams aoOut; -#ifdef AMBIENT -vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; -#endif -ambientOcclusionBlock( -#ifdef AMBIENT -ambientOcclusionColorMap, -vAmbientInfos, -#endif -aoOut -); -#include<pbrBlockLightmapInit> -#ifdef UNLIT -vec3 diffuseBase=vec3(1.,1.,1.); -#else -vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; -#if defined(REFLECTIVITY) -vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; -#ifndef METALLICWORKFLOW -#ifdef REFLECTIVITY_GAMMA -surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); -#endif -surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; -#endif -#endif -#if defined(MICROSURFACEMAP) -vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; -#endif -#ifdef METALLICWORKFLOW -vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; -#ifdef REFLECTANCE -vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); -#ifdef REFLECTANCE_GAMMA -reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); -#endif -metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; -#endif -#ifdef METALLIC_REFLECTANCE -vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); -#ifdef METALLIC_REFLECTANCE_GAMMA -metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); -#endif -#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY -metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; -#endif -metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; -#endif -#endif -reflectivityBlock( -vReflectivityColor, -#ifdef METALLICWORKFLOW -surfaceAlbedo, -metallicReflectanceFactors, -#endif -#ifdef REFLECTIVITY -vReflectivityInfos, -surfaceMetallicOrReflectivityColorMap, -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -aoOut.ambientOcclusionColor, -#endif -#ifdef MICROSURFACEMAP -microSurfaceTexel, -#endif -#ifdef DETAIL -detailColor, -vDetailInfos, -#endif -reflectivityOut -);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; -#ifdef METALLICWORKFLOW -surfaceAlbedo=reflectivityOut.surfaceAlbedo; -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; -#endif -#ifdef ALPHAFRESNEL -#if defined(ALPHATEST) || defined(ALPHABLEND) -alphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock( -normalW, -viewDirectionW, -alpha, -microSurface, -alphaFresnelOut -);alpha=alphaFresnelOut.alpha; -#endif -#endif -#include<pbrBlockGeometryInfo> -#ifdef ANISOTROPIC -anisotropicOutParams anisotropicOut; -#ifdef ANISOTROPIC_TEXTURE -vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; -#endif -anisotropicBlock( -vAnisotropy, -roughness, -#ifdef ANISOTROPIC_TEXTURE -anisotropyMapData, -#endif -TBN, -normalW, -viewDirectionW, -anisotropicOut -); -#endif -#ifdef REFLECTION -reflectionOutParams reflectionOut; -#ifndef USE_CUSTOM_REFLECTION -reflectionBlock( -vPositionW, -normalW, -alphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#ifdef ANISOTROPIC -anisotropicOut, -#endif -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -roughness, -#endif -reflectionSampler, -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -vEnvironmentIrradiance, -#endif -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -reflectionMatrix, -#endif -#endif -#ifdef USEIRRADIANCEMAP -irradianceSampler, -#endif -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -reflectionOut -); -#else -#define CUSTOM_REFLECTION -#endif -#endif -#include<pbrBlockReflectance0> -#ifdef SHEEN -sheenOutParams sheenOut; -#ifdef SHEEN_TEXTURE -vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); -#endif -#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; -#endif -sheenBlock( -vSheenColor, -#ifdef SHEEN_ROUGHNESS -vSheenRoughness, -#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -sheenMapRoughnessData, -#endif -#endif -roughness, -#ifdef SHEEN_TEXTURE -sheenMapData, -vSheenInfos.y, -#endif -reflectance, -#ifdef SHEEN_LINKWITHALBEDO -baseColor, -surfaceAlbedo, -#endif -#ifdef ENVIRONMENTBRDF -NdotV, -environmentBrdf, -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -AARoughnessFactors, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -vLightingIntensity, -reflectionSampler, -reflectionOut.reflectionCoords, -NdotVUnclamped, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -seo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -eho, -#endif -#endif -sheenOut -); -#ifdef SHEEN_LINKWITHALBEDO -surfaceAlbedo=sheenOut.surfaceAlbedo; -#endif -#endif -#ifdef CLEARCOAT -#ifdef CLEARCOAT_TEXTURE -vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; -#endif -#endif -#ifdef IRIDESCENCE -iridescenceOutParams iridescenceOut; -#ifdef IRIDESCENCE_TEXTURE -vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; -#endif -iridescenceBlock( -vIridescenceParams, -NdotV, -specularEnvironmentR0, -#ifdef IRIDESCENCE_TEXTURE -iridescenceMapData, -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -iridescenceThicknessMapData, -#endif -#ifdef CLEARCOAT -NdotVUnclamped, -#ifdef CLEARCOAT_TEXTURE -clearCoatMapData, -#endif -#endif -iridescenceOut -);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; -#endif -clearcoatOutParams clearcoatOut; -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; -#endif -#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); -#endif -#ifdef CLEARCOAT_BUMP -vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); -#endif -clearcoatBlock( -vPositionW, -geometricNormalW, -viewDirectionW, -vClearCoatParams, -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -clearCoatMapRoughnessData, -#endif -specularEnvironmentR0, -#ifdef CLEARCOAT_TEXTURE -clearCoatMapData, -#endif -#ifdef CLEARCOAT_TINT -vClearCoatTintParams, -clearCoatColorAtDistance, -vClearCoatRefractionParams, -#ifdef CLEARCOAT_TINT_TEXTURE -clearCoatTintMapData, -#endif -#endif -#ifdef CLEARCOAT_BUMP -vClearCoatBumpInfos, -clearCoatBumpMapData, -vClearCoatBumpUV, -#if defined(TANGENT) && defined(NORMAL) -vTBN, -#else -vClearCoatTangentSpaceParams, -#endif -#ifdef OBJECTSPACE_NORMALMAP -normalMatrix, -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -faceNormal, -#endif -#ifdef REFLECTION -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -vLightingIntensity, -reflectionSampler, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -ambientMonochrome, -#endif -#endif -#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) -(gl_FrontFacing ? 1. : -1.), -#endif -clearcoatOut -); -#else -clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; -#endif -#include<pbrBlockReflectance> -subSurfaceOutParams subSurfaceOut; -#ifdef SUBSURFACE -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); -#endif -subSurfaceBlock( -vSubSurfaceIntensity, -vThicknessParam, -vTintColor, -normalW, -specularEnvironmentReflectance, -#ifdef SS_THICKNESSANDMASK_TEXTURE -thicknessMap, -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -refractionIntensityMap, -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -translucencyIntensityMap, -#endif -#ifdef REFLECTION -#ifdef SS_TRANSLUCENCY -reflectionMatrix, -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -reflectionOut.irradianceVector, -#endif -#if defined(REALTIME_FILTERING) -reflectionSampler, -vReflectionFilteringInfo, -#endif -#endif -#ifdef USEIRRADIANCEMAP -irradianceSampler, -#endif -#endif -#endif -#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) -surfaceAlbedo, -#endif -#ifdef SS_REFRACTION -vPositionW, -viewDirectionW, -view, -vRefractionInfos, -refractionMatrix, -vRefractionMicrosurfaceInfos, -vLightingIntensity, -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -alpha, -#endif -#ifdef SS_LODINREFRACTIONALPHA -NdotVUnclamped, -#endif -#ifdef SS_LINEARSPECULARREFRACTION -roughness, -#endif -alphaG, -refractionSampler, -#ifndef LODBASEDMICROSFURACE -refractionSamplerLow, -refractionSamplerHigh, -#endif -#ifdef ANISOTROPIC -anisotropicOut, -#endif -#ifdef REALTIME_FILTERING -vRefractionFilteringInfo, -#endif -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -vRefractionPosition, -vRefractionSize, -#endif -#endif -#ifdef SS_TRANSLUCENCY -vDiffusionDistance, -#endif -subSurfaceOut -); -#ifdef SS_REFRACTION -surfaceAlbedo=subSurfaceOut.surfaceAlbedo; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -alpha=subSurfaceOut.alpha; -#endif -#endif -#else -subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; -#endif -#include<pbrBlockDirectLighting> -#include<lightFragment>[0..maxSimultaneousLights] -#include<pbrBlockFinalLitComponents> -#endif -#include<pbrBlockFinalUnlitComponents> -#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION -#include<pbrBlockFinalColorComposition> -#include<logDepthFragment> -#include<fogFragment>(color,finalColor) -#include<pbrBlockImageProcessing> -#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR -#ifdef PREPASS -float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; -#ifdef PREPASS_POSITION -gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); -#endif -#ifdef PREPASS_VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_ALBEDO_SQRT -vec3 sqAlbedo=sqrt(surfaceAlbedo); -#endif -#ifdef PREPASS_IRRADIANCE -vec3 irradiance=finalDiffuse; -#ifndef UNLIT -#ifdef REFLECTION -irradiance+=finalIrradiance; -#endif -#endif -#ifdef SS_SCATTERING -gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); -irradiance/=sqAlbedo; -#else -gl_FragData[0]=finalColor; -float scatteringDiffusionProfile=255.; -#endif -gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); -#else -gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); -#endif -#ifdef PREPASS_DEPTH -gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_NORMAL -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); -#endif -#ifdef PREPASS_ALBEDO_SQRT -gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); -#endif -#ifdef PREPASS_REFLECTIVITY -#ifndef UNLIT -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; -#endif -#endif -#endif -#if !defined(PREPASS) || defined(WEBGL2) -gl_FragColor=finalColor; -#endif -#include<oitFragment> -#if ORDER_INDEPENDENT_TRANSPARENCY -if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} -#endif -#include<pbrDebug> -#define CUSTOM_FRAGMENT_MAIN_END -} -`; -// Sideeffect -ShaderStore.ShadersStore[pbr_fragment_name] = pbr_fragment_shader; -/** @internal */ -const pbrPixelShader = { name: pbr_fragment_name, shader: pbr_fragment_shader }; -//# sourceMappingURL=pbr.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrVertexDeclaration.js -// Do not edit. - - -const pbrVertexDeclaration_name = "pbrVertexDeclaration"; -const pbrVertexDeclaration_shader = `uniform mat4 view;uniform mat4 viewProjection; -#ifdef ALBEDO -uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; -#endif -#ifdef AMBIENT -uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; -#endif -#ifdef OPACITY -uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; -#endif -#ifdef REFLECTIVITY -uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; -#endif -#ifdef METALLIC_REFLECTANCE -uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; -#endif -#ifdef REFLECTANCE -uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; -#endif -#ifdef MICROSURFACEMAP -uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; -#endif -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) -uniform vec4 vClearCoatInfos; -#endif -#ifdef CLEARCOAT_TEXTURE -uniform mat4 clearCoatMatrix; -#endif -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS -uniform mat4 clearCoatRoughnessMatrix; -#endif -#ifdef CLEARCOAT_BUMP -uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; -#endif -#ifdef CLEARCOAT_TINT_TEXTURE -uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; -#endif -#endif -#ifdef IRIDESCENCE -#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) -uniform vec4 vIridescenceInfos; -#endif -#ifdef IRIDESCENCE_TEXTURE -uniform mat4 iridescenceMatrix; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -uniform mat4 iridescenceThicknessMatrix; -#endif -#endif -#ifdef ANISOTROPIC -#ifdef ANISOTROPIC_TEXTURE -uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; -#endif -#endif -#ifdef SHEEN -#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) -uniform vec4 vSheenInfos; -#endif -#ifdef SHEEN_TEXTURE -uniform mat4 sheenMatrix; -#endif -#ifdef SHEEN_TEXTURE_ROUGHNESS -uniform mat4 sheenRoughnessMatrix; -#endif -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; -#endif -#endif -#ifdef NORMAL -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; -#else -uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; -#endif -#endif -#endif -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos;uniform mat4 detailMatrix; -#endif -#include<decalVertexDeclaration> -#define ADDITIONAL_VERTEX_DECLARATION -`; -// Sideeffect -ShaderStore.IncludesShadersStore[pbrVertexDeclaration_name] = pbrVertexDeclaration_shader; -/** @internal */ -const pbrVertexDeclaration = { name: pbrVertexDeclaration_name, shader: pbrVertexDeclaration_shader }; -//# sourceMappingURL=pbrVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/pbr.vertex.js -// Do not edit. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -const pbr_vertex_name = "pbrVertexShader"; -const pbr_vertex_shader = `precision highp float; -#include<__decl__pbrVertex> -#define CUSTOM_VERTEX_BEGIN -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#ifdef TANGENT -attribute vec4 tangent; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#include<uvAttributeDeclaration>[2..7] -#include<mainUVVaryingDeclaration>[1..7] -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include<helperFunctions> -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<instancesDeclaration> -#include<prePassVertexDeclaration> -#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) -#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) -#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) -#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) -#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) -#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) -#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) -#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) -#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) -#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) -#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) -#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) -#ifdef CLEARCOAT -#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) -#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) -#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) -#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) -#endif -#ifdef IRIDESCENCE -#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) -#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) -#endif -#ifdef SHEEN -#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) -#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) -#endif -#ifdef ANISOTROPIC -#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) -#endif -#ifdef SUBSURFACE -#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) -#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) -#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) -#endif -varying vec3 vPositionW; -#if DEBUGMODE>0 -varying vec4 vClipSpacePosition; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -varying vec3 vEnvironmentIrradiance; -#include<harmonicsFunctions> -#endif -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include<bumpVertexDeclaration> -#include<clipPlaneVertexDeclaration> -#include<fogVertexDeclaration> -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#include<logDepthDeclaration> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#ifdef TANGENT -vec4 tangentUpdated=tangent; -#endif -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=positionUpdated; -#endif -#define CUSTOM_VERTEX_UPDATE_POSITION -#define CUSTOM_VERTEX_UPDATE_NORMAL -#include<instancesVertex> -#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); -#include<prePassVertex> -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normalUpdated); -#endif -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); -#endif -#endif -#define CUSTOM_VERTEX_UPDATE_WORLDPOS -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#if DEBUGMODE>0 -vClipSpacePosition=gl_Position; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); -#endif -#ifndef UV1 -vec2 uvUpdated=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uvUpdated; -#endif -#include<uvVariableDeclaration>[2..7] -#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) -#ifdef CLEARCOAT -#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) -#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) -#endif -#ifdef IRIDESCENCE -#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) -#endif -#ifdef SHEEN -#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z) -#endif -#ifdef ANISOTROPIC -#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) -#endif -#ifdef SUBSURFACE -#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) -#endif -#include<bumpVertex> -#include<clipPlaneVertex> -#include<fogVertex> -#include<shadowsVertex>[0..maxSimultaneousLights] -#include<vertexColorMixing> -#if defined(POINTSIZE) && !defined(WEBGPU) -gl_PointSize=pointSize; -#endif -#include<logDepthVertex> -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[pbr_vertex_name] = pbr_vertex_shader; -/** @internal */ -const pbrVertexShader = { name: pbr_vertex_name, shader: pbr_vertex_shader }; -//# sourceMappingURL=pbr.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrClearCoatConfiguration.js - - - - - - - - -/** - * @internal - */ -class MaterialClearCoatDefines extends MaterialDefines { - constructor() { - super(...arguments); - this.CLEARCOAT = false; - this.CLEARCOAT_DEFAULTIOR = false; - this.CLEARCOAT_TEXTURE = false; - this.CLEARCOAT_TEXTURE_ROUGHNESS = false; - this.CLEARCOAT_TEXTUREDIRECTUV = 0; - this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0; - this.CLEARCOAT_BUMP = false; - this.CLEARCOAT_BUMPDIRECTUV = 0; - this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false; - this.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = false; - this.CLEARCOAT_REMAP_F0 = false; - this.CLEARCOAT_TINT = false; - this.CLEARCOAT_TINT_TEXTURE = false; - this.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0; - this.CLEARCOAT_TINT_GAMMATEXTURE = false; - } -} -/** - * Plugin that implements the clear coat component of the PBR material - */ -class pbrClearCoatConfiguration_PBRClearCoatConfiguration extends MaterialPluginBase { - /** @internal */ - _markAllSubMeshesAsTexturesDirty() { - this._enable(this._isEnabled); - this._internalMarkAllSubMeshesAsTexturesDirty(); - } - constructor(material, addToPluginList = true) { - super(material, "PBRClearCoat", 100, new MaterialClearCoatDefines(), addToPluginList); - this._isEnabled = false; - /** - * Defines if the clear coat is enabled in the material. - */ - this.isEnabled = false; - /** - * Defines the clear coat layer strength (between 0 and 1) it defaults to 1. - */ - this.intensity = 1; - /** - * Defines the clear coat layer roughness. - */ - this.roughness = 0; - this._indexOfRefraction = pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction; - /** - * Defines the index of refraction of the clear coat. - * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence - * The default fits with a polyurethane material. - * Changing the default value is more performance intensive. - */ - this.indexOfRefraction = pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction; - this._texture = null; - /** - * Stores the clear coat values in a texture (red channel is intensity and green channel is roughness) - * If useRoughnessFromMainTexture is false, the green channel of texture is not used and the green channel of textureRoughness is used instead - * if textureRoughness is not empty, else no texture roughness is used - */ - this.texture = null; - this._useRoughnessFromMainTexture = true; - /** - * Indicates that the green channel of the texture property will be used for roughness (default: true) - * If false, the green channel from textureRoughness is used for roughness - */ - this.useRoughnessFromMainTexture = true; - this._textureRoughness = null; - /** - * Stores the clear coat roughness in a texture (green channel) - * Not used if useRoughnessFromMainTexture is true - */ - this.textureRoughness = null; - this._remapF0OnInterfaceChange = true; - /** - * Defines if the F0 value should be remapped to account for the interface change in the material. - */ - this.remapF0OnInterfaceChange = true; - this._bumpTexture = null; - /** - * Define the clear coat specific bump texture. - */ - this.bumpTexture = null; - this._isTintEnabled = false; - /** - * Defines if the clear coat tint is enabled in the material. - */ - this.isTintEnabled = false; - /** - * Defines the clear coat tint of the material. - * This is only use if tint is enabled - */ - this.tintColor = math_color_Color3.White(); - /** - * Defines the distance at which the tint color should be found in the - * clear coat media. - * This is only use if tint is enabled - */ - this.tintColorAtDistance = 1; - /** - * Defines the clear coat layer thickness. - * This is only use if tint is enabled - */ - this.tintThickness = 1; - this._tintTexture = null; - /** - * Stores the clear tint values in a texture. - * rgb is tint - * a is a thickness factor - */ - this.tintTexture = null; - this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; - } - isReadyForSubMesh(defines, scene, engine) { - if (!this._isEnabled) { - return true; - } - const disableBumpMap = this._material._disableBumpMap; - if (defines._areTexturesDirty) { - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.ClearCoatTextureEnabled) { - if (!this._texture.isReadyOrNotBlocking()) { - return false; - } - } - if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) { - if (!this._textureRoughness.isReadyOrNotBlocking()) { - return false; - } - } - if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) { - // Bump texture cannot be not blocking. - if (!this._bumpTexture.isReady()) { - return false; - } - } - if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) { - if (!this._tintTexture.isReadyOrNotBlocking()) { - return false; - } - } - } - } - return true; - } - prepareDefinesBeforeAttributes(defines, scene) { - var _a; - if (this._isEnabled) { - defines.CLEARCOAT = true; - defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture; - defines.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = - this._texture !== null && this._texture._texture === ((_a = this._textureRoughness) === null || _a === void 0 ? void 0 : _a._texture) && this._texture.checkTransformsAreIdentical(this._textureRoughness); - defines.CLEARCOAT_REMAP_F0 = this._remapF0OnInterfaceChange; - if (defines._areTexturesDirty) { - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.ClearCoatTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, "CLEARCOAT_TEXTURE"); - } - else { - defines.CLEARCOAT_TEXTURE = false; - } - if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness, defines, "CLEARCOAT_TEXTURE_ROUGHNESS"); - } - else { - defines.CLEARCOAT_TEXTURE_ROUGHNESS = false; - } - if (this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "CLEARCOAT_BUMP"); - } - else { - defines.CLEARCOAT_BUMP = false; - } - defines.CLEARCOAT_DEFAULTIOR = this._indexOfRefraction === pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction; - if (this._isTintEnabled) { - defines.CLEARCOAT_TINT = true; - if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._tintTexture, defines, "CLEARCOAT_TINT_TEXTURE"); - defines.CLEARCOAT_TINT_GAMMATEXTURE = this._tintTexture.gammaSpace; - } - else { - defines.CLEARCOAT_TINT_TEXTURE = false; - } - } - else { - defines.CLEARCOAT_TINT = false; - defines.CLEARCOAT_TINT_TEXTURE = false; - } - } - } - } - else { - defines.CLEARCOAT = false; - defines.CLEARCOAT_TEXTURE = false; - defines.CLEARCOAT_TEXTURE_ROUGHNESS = false; - defines.CLEARCOAT_BUMP = false; - defines.CLEARCOAT_TINT = false; - defines.CLEARCOAT_TINT_TEXTURE = false; - defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false; - defines.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = false; - defines.CLEARCOAT_DEFAULTIOR = false; - defines.CLEARCOAT_TEXTUREDIRECTUV = 0; - defines.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0; - defines.CLEARCOAT_BUMPDIRECTUV = 0; - defines.CLEARCOAT_REMAP_F0 = false; - defines.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0; - defines.CLEARCOAT_TINT_GAMMATEXTURE = false; - } - } - bindForSubMesh(uniformBuffer, scene, engine, subMesh) { - var _a, _b, _c, _d, _e, _f, _g, _h; - if (!this._isEnabled) { - return; - } - const defines = subMesh.materialDefines; - const isFrozen = this._material.isFrozen; - const disableBumpMap = this._material._disableBumpMap; - const invertNormalMapX = this._material._invertNormalMapX; - const invertNormalMapY = this._material._invertNormalMapY; - const identicalTextures = defines.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL; - if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { - if (identicalTextures && MaterialFlags.ClearCoatTextureEnabled) { - uniformBuffer.updateFloat4("vClearCoatInfos", this._texture.coordinatesIndex, this._texture.level, -1, -1); - MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, "clearCoat"); - } - else if ((this._texture || this._textureRoughness) && MaterialFlags.ClearCoatTextureEnabled) { - 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); - if (this._texture) { - MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, "clearCoat"); - } - if (this._textureRoughness && !identicalTextures && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) { - MaterialHelper.BindTextureMatrix(this._textureRoughness, uniformBuffer, "clearCoatRoughness"); - } - } - if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.ClearCoatTextureEnabled && !disableBumpMap) { - uniformBuffer.updateFloat2("vClearCoatBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level); - MaterialHelper.BindTextureMatrix(this._bumpTexture, uniformBuffer, "clearCoatBump"); - if (scene._mirroredCameraPosition) { - uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? 1.0 : -1.0, invertNormalMapY ? 1.0 : -1.0); - } - else { - uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? -1.0 : 1.0, invertNormalMapY ? -1.0 : 1.0); - } - } - if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) { - uniformBuffer.updateFloat2("vClearCoatTintInfos", this._tintTexture.coordinatesIndex, this._tintTexture.level); - MaterialHelper.BindTextureMatrix(this._tintTexture, uniformBuffer, "clearCoatTint"); - } - // Clear Coat General params - uniformBuffer.updateFloat2("vClearCoatParams", this.intensity, this.roughness); - // Clear Coat Refraction params - const a = 1 - this._indexOfRefraction; - const b = 1 + this._indexOfRefraction; - const f0 = Math.pow(-a / b, 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1. - const eta = 1 / this._indexOfRefraction; - uniformBuffer.updateFloat4("vClearCoatRefractionParams", f0, eta, a, b); - if (this._isTintEnabled) { - uniformBuffer.updateFloat4("vClearCoatTintParams", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintThickness)); - uniformBuffer.updateFloat("clearCoatColorAtDistance", Math.max(0.00001, this.tintColorAtDistance)); - } - } - // Textures - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.ClearCoatTextureEnabled) { - uniformBuffer.setTexture("clearCoatSampler", this._texture); - } - if (this._textureRoughness && !identicalTextures && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.ClearCoatTextureEnabled) { - uniformBuffer.setTexture("clearCoatRoughnessSampler", this._textureRoughness); - } - if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) { - uniformBuffer.setTexture("clearCoatBumpSampler", this._bumpTexture); - } - if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) { - uniformBuffer.setTexture("clearCoatTintSampler", this._tintTexture); - } - } - } - hasTexture(texture) { - if (this._texture === texture) { - return true; - } - if (this._textureRoughness === texture) { - return true; - } - if (this._bumpTexture === texture) { - return true; - } - if (this._tintTexture === texture) { - return true; - } - return false; - } - getActiveTextures(activeTextures) { - if (this._texture) { - activeTextures.push(this._texture); - } - if (this._textureRoughness) { - activeTextures.push(this._textureRoughness); - } - if (this._bumpTexture) { - activeTextures.push(this._bumpTexture); - } - if (this._tintTexture) { - activeTextures.push(this._tintTexture); - } - } - getAnimatables(animatables) { - if (this._texture && this._texture.animations && this._texture.animations.length > 0) { - animatables.push(this._texture); - } - if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) { - animatables.push(this._textureRoughness); - } - if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { - animatables.push(this._bumpTexture); - } - if (this._tintTexture && this._tintTexture.animations && this._tintTexture.animations.length > 0) { - animatables.push(this._tintTexture); - } - } - dispose(forceDisposeTextures) { - var _a, _b, _c, _d; - if (forceDisposeTextures) { - (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose(); - (_b = this._textureRoughness) === null || _b === void 0 ? void 0 : _b.dispose(); - (_c = this._bumpTexture) === null || _c === void 0 ? void 0 : _c.dispose(); - (_d = this._tintTexture) === null || _d === void 0 ? void 0 : _d.dispose(); - } - } - getClassName() { - return "PBRClearCoatConfiguration"; - } - addFallbacks(defines, fallbacks, currentRank) { - if (defines.CLEARCOAT_BUMP) { - fallbacks.addFallback(currentRank++, "CLEARCOAT_BUMP"); - } - if (defines.CLEARCOAT_TINT) { - fallbacks.addFallback(currentRank++, "CLEARCOAT_TINT"); - } - if (defines.CLEARCOAT) { - fallbacks.addFallback(currentRank++, "CLEARCOAT"); - } - return currentRank; - } - getSamplers(samplers) { - samplers.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" }, - ], - }; - } -} -/** - * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence - * The default fits with a polyurethane material. - * @internal - */ -pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction = 1.5; -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "isEnabled", void 0); -__decorate([ - serialize() -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "intensity", void 0); -__decorate([ - serialize() -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "roughness", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "indexOfRefraction", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "texture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "useRoughnessFromMainTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "textureRoughness", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "remapF0OnInterfaceChange", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "bumpTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "isTintEnabled", void 0); -__decorate([ - serializeAsColor3() -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "tintColor", void 0); -__decorate([ - serialize() -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "tintColorAtDistance", void 0); -__decorate([ - serialize() -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "tintThickness", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype, "tintTexture", void 0); -//# sourceMappingURL=pbrClearCoatConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrIridescenceConfiguration.js - - - - - - - -/** - * @internal - */ -class MaterialIridescenceDefines extends MaterialDefines { - constructor() { - super(...arguments); - this.IRIDESCENCE = false; - this.IRIDESCENCE_TEXTURE = false; - this.IRIDESCENCE_TEXTUREDIRECTUV = 0; - this.IRIDESCENCE_THICKNESS_TEXTURE = false; - this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0; - this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE = false; - } -} -/** - * Plugin that implements the iridescence (thin film) component of the PBR material - */ -class pbrIridescenceConfiguration_PBRIridescenceConfiguration extends MaterialPluginBase { - /** @internal */ - _markAllSubMeshesAsTexturesDirty() { - this._enable(this._isEnabled); - this._internalMarkAllSubMeshesAsTexturesDirty(); - } - constructor(material, addToPluginList = true) { - super(material, "PBRIridescence", 110, new MaterialIridescenceDefines(), addToPluginList); - this._isEnabled = false; - /** - * Defines if the iridescence is enabled in the material. - */ - this.isEnabled = false; - /** - * Defines the iridescence layer strength (between 0 and 1) it defaults to 1. - */ - this.intensity = 1; - /** - * Defines the minimum thickness of the thin-film layer given in nanometers (nm). - */ - this.minimumThickness = pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMinimumThickness; - /** - * 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. - */ - this.maximumThickness = pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness; - /** - * Defines the maximum thickness of the thin-film layer given in nanometers (nm). - */ - this.indexOfRefraction = pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction; - this._texture = null; - /** - * Stores the iridescence intensity in a texture (red channel) - */ - this.texture = null; - this._thicknessTexture = null; - /** - * Stores the iridescence thickness in a texture (green channel) - */ - this.thicknessTexture = null; - this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; - } - isReadyForSubMesh(defines, scene) { - if (!this._isEnabled) { - return true; - } - if (defines._areTexturesDirty) { - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.IridescenceTextureEnabled) { - if (!this._texture.isReadyOrNotBlocking()) { - return false; - } - } - if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) { - if (!this._thicknessTexture.isReadyOrNotBlocking()) { - return false; - } - } - } - } - return true; - } - prepareDefinesBeforeAttributes(defines, scene) { - var _a; - if (this._isEnabled) { - defines.IRIDESCENCE = true; - defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE = - this._texture !== null && this._texture._texture === ((_a = this._thicknessTexture) === null || _a === void 0 ? void 0 : _a._texture) && this._texture.checkTransformsAreIdentical(this._thicknessTexture); - if (defines._areTexturesDirty) { - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.IridescenceTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, "IRIDESCENCE_TEXTURE"); - } - else { - defines.IRIDESCENCE_TEXTURE = false; - } - if (!defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE && this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture, defines, "IRIDESCENCE_THICKNESS_TEXTURE"); - } - else { - defines.IRIDESCENCE_THICKNESS_TEXTURE = false; - } - } - } - } - else { - defines.IRIDESCENCE = false; - defines.IRIDESCENCE_TEXTURE = false; - defines.IRIDESCENCE_THICKNESS_TEXTURE = false; - defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE = false; - defines.IRIDESCENCE_TEXTUREDIRECTUV = 0; - defines.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0; - } - } - bindForSubMesh(uniformBuffer, scene, engine, subMesh) { - var _a, _b, _c, _d, _e, _f, _g, _h; - if (!this._isEnabled) { - return; - } - const defines = subMesh.materialDefines; - const isFrozen = this._material.isFrozen; - const identicalTextures = defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE; - if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { - if (identicalTextures && MaterialFlags.IridescenceTextureEnabled) { - uniformBuffer.updateFloat4("vIridescenceInfos", this._texture.coordinatesIndex, this._texture.level, -1, -1); - MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, "iridescence"); - } - else if ((this._texture || this._thicknessTexture) && MaterialFlags.IridescenceTextureEnabled) { - 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); - if (this._texture) { - MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, "iridescence"); - } - if (this._thicknessTexture && !identicalTextures && !defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE) { - MaterialHelper.BindTextureMatrix(this._thicknessTexture, uniformBuffer, "iridescenceThickness"); - } - } - // Clear Coat General params - uniformBuffer.updateFloat4("vIridescenceParams", this.intensity, this.indexOfRefraction, this.minimumThickness, this.maximumThickness); - } - // Textures - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.IridescenceTextureEnabled) { - uniformBuffer.setTexture("iridescenceSampler", this._texture); - } - if (this._thicknessTexture && !identicalTextures && !defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE && MaterialFlags.IridescenceTextureEnabled) { - uniformBuffer.setTexture("iridescenceThicknessSampler", this._thicknessTexture); - } - } - } - hasTexture(texture) { - if (this._texture === texture) { - return true; - } - if (this._thicknessTexture === texture) { - return true; - } - return false; - } - getActiveTextures(activeTextures) { - if (this._texture) { - activeTextures.push(this._texture); - } - if (this._thicknessTexture) { - activeTextures.push(this._thicknessTexture); - } - } - getAnimatables(animatables) { - if (this._texture && this._texture.animations && this._texture.animations.length > 0) { - animatables.push(this._texture); - } - if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) { - animatables.push(this._thicknessTexture); - } - } - dispose(forceDisposeTextures) { - var _a, _b; - if (forceDisposeTextures) { - (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose(); - (_b = this._thicknessTexture) === null || _b === void 0 ? void 0 : _b.dispose(); - } - } - getClassName() { - return "PBRIridescenceConfiguration"; - } - addFallbacks(defines, fallbacks, currentRank) { - if (defines.IRIDESCENCE) { - fallbacks.addFallback(currentRank++, "IRIDESCENCE"); - } - return currentRank; - } - getSamplers(samplers) { - samplers.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" }, - ], - }; - } -} -/** - * The default minimum thickness of the thin-film layer given in nanometers (nm). - * Defaults to 100 nm. - * @internal - */ -pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMinimumThickness = 100; -/** - * The default maximum thickness of the thin-film layer given in nanometers (nm). - * Defaults to 400 nm. - * @internal - */ -pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness = 400; -/** - * The default index of refraction of the thin-film layer. - * Defaults to 1.3 - * @internal - */ -pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction = 1.3; -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype, "isEnabled", void 0); -__decorate([ - serialize() -], pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype, "intensity", void 0); -__decorate([ - serialize() -], pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype, "minimumThickness", void 0); -__decorate([ - serialize() -], pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype, "maximumThickness", void 0); -__decorate([ - serialize() -], pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype, "indexOfRefraction", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype, "texture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype, "thicknessTexture", void 0); -//# sourceMappingURL=pbrIridescenceConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrAnisotropicConfiguration.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - -/** - * @internal - */ -class MaterialAnisotropicDefines extends MaterialDefines { - constructor() { - super(...arguments); - this.ANISOTROPIC = false; - this.ANISOTROPIC_TEXTURE = false; - this.ANISOTROPIC_TEXTUREDIRECTUV = 0; - this.ANISOTROPIC_LEGACY = false; - this.MAINUV1 = false; - } -} -/** - * Plugin that implements the anisotropic component of the PBR material - */ -class pbrAnisotropicConfiguration_PBRAnisotropicConfiguration extends MaterialPluginBase { - /** - * Sets the anisotropy direction as an angle. - */ - set angle(value) { - this.direction.x = Math.cos(value); - this.direction.y = Math.sin(value); - } - /** - * Gets the anisotropy angle value in radians. - * @returns the anisotropy angle value in radians. - */ - get angle() { - return Math.atan2(this.direction.y, this.direction.x); - } - /** @internal */ - _markAllSubMeshesAsTexturesDirty() { - this._enable(this._isEnabled); - this._internalMarkAllSubMeshesAsTexturesDirty(); - } - /** @internal */ - _markAllSubMeshesAsMiscDirty() { - this._enable(this._isEnabled); - this._internalMarkAllSubMeshesAsMiscDirty(); - } - constructor(material, addToPluginList = true) { - super(material, "PBRAnisotropic", 110, new MaterialAnisotropicDefines(), addToPluginList); - this._isEnabled = false; - /** - * Defines if the anisotropy is enabled in the material. - */ - this.isEnabled = false; - /** - * Defines the anisotropy strength (between 0 and 1) it defaults to 1. - */ - this.intensity = 1; - /** - * Defines if the effect is along the tangents, bitangents or in between. - * By default, the effect is "stretching" the highlights along the tangents. - */ - this.direction = new math_vector_Vector2(1, 0); - this._texture = null; - /** - * Stores the anisotropy values in a texture. - * rg is direction (like normal from -1 to 1) - * b is a intensity - */ - this.texture = null; - this._legacy = false; - /** - * Defines if the anisotropy is in legacy mode for backwards compatibility before 6.4.0. - */ - this.legacy = false; - this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; - this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16]; - } - isReadyForSubMesh(defines, scene) { - if (!this._isEnabled) { - return true; - } - if (defines._areTexturesDirty) { - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.AnisotropicTextureEnabled) { - if (!this._texture.isReadyOrNotBlocking()) { - return false; - } - } - } - } - return true; - } - prepareDefinesBeforeAttributes(defines, scene, mesh) { - if (this._isEnabled) { - defines.ANISOTROPIC = this._isEnabled; - if (this._isEnabled && !mesh.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)) { - defines._needUVs = true; - defines.MAINUV1 = true; - } - if (defines._areTexturesDirty) { - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.AnisotropicTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, "ANISOTROPIC_TEXTURE"); - } - else { - defines.ANISOTROPIC_TEXTURE = false; - } - } - } - if (defines._areMiscDirty) { - defines.ANISOTROPIC_LEGACY = this._legacy; - } - } - else { - defines.ANISOTROPIC = false; - defines.ANISOTROPIC_TEXTURE = false; - defines.ANISOTROPIC_TEXTUREDIRECTUV = 0; - defines.ANISOTROPIC_LEGACY = false; - } - } - bindForSubMesh(uniformBuffer, scene) { - if (!this._isEnabled) { - return; - } - const isFrozen = this._material.isFrozen; - if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { - if (this._texture && MaterialFlags.AnisotropicTextureEnabled) { - uniformBuffer.updateFloat2("vAnisotropyInfos", this._texture.coordinatesIndex, this._texture.level); - MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, "anisotropy"); - } - // Anisotropy - uniformBuffer.updateFloat3("vAnisotropy", this.direction.x, this.direction.y, this.intensity); - } - // Textures - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.AnisotropicTextureEnabled) { - uniformBuffer.setTexture("anisotropySampler", this._texture); - } - } - } - hasTexture(texture) { - if (this._texture === texture) { - return true; - } - return false; - } - getActiveTextures(activeTextures) { - if (this._texture) { - activeTextures.push(this._texture); - } - } - getAnimatables(animatables) { - if (this._texture && this._texture.animations && this._texture.animations.length > 0) { - animatables.push(this._texture); - } - } - dispose(forceDisposeTextures) { - if (forceDisposeTextures) { - if (this._texture) { - this._texture.dispose(); - } - } - } - getClassName() { - return "PBRAnisotropicConfiguration"; - } - addFallbacks(defines, fallbacks, currentRank) { - if (defines.ANISOTROPIC) { - fallbacks.addFallback(currentRank++, "ANISOTROPIC"); - } - return currentRank; - } - getSamplers(samplers) { - samplers.push("anisotropySampler"); - } - getUniforms() { - return { - ubo: [ - { name: "vAnisotropy", size: 3, type: "vec3" }, - { name: "vAnisotropyInfos", size: 2, type: "vec2" }, - { name: "anisotropyMatrix", size: 16, type: "mat4" }, - ], - }; - } - /** - * Parses a anisotropy Configuration from a serialized object. - * @param source - Serialized object. - * @param scene Defines the scene we are parsing for - * @param rootUrl Defines the rootUrl to load from - */ - parse(source, scene, rootUrl) { - super.parse(source, scene, rootUrl); - // Backward compatibility - if (source.legacy === undefined) { - this.legacy = true; - } - } -} -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype, "isEnabled", void 0); -__decorate([ - serialize() -], pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype, "intensity", void 0); -__decorate([ - serializeAsVector2() -], pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype, "direction", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype, "texture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsMiscDirty") -], pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype, "legacy", void 0); -//# sourceMappingURL=pbrAnisotropicConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrSheenConfiguration.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - -/** - * @internal - */ -class MaterialSheenDefines extends MaterialDefines { - constructor() { - super(...arguments); - this.SHEEN = false; - this.SHEEN_TEXTURE = false; - this.SHEEN_GAMMATEXTURE = false; - this.SHEEN_TEXTURE_ROUGHNESS = false; - this.SHEEN_TEXTUREDIRECTUV = 0; - this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0; - this.SHEEN_LINKWITHALBEDO = false; - this.SHEEN_ROUGHNESS = false; - this.SHEEN_ALBEDOSCALING = false; - this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false; - this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = false; - } -} -/** - * Plugin that implements the sheen component of the PBR material. - */ -class pbrSheenConfiguration_PBRSheenConfiguration extends MaterialPluginBase { - /** @internal */ - _markAllSubMeshesAsTexturesDirty() { - this._enable(this._isEnabled); - this._internalMarkAllSubMeshesAsTexturesDirty(); - } - constructor(material, addToPluginList = true) { - super(material, "Sheen", 120, new MaterialSheenDefines(), addToPluginList); - this._isEnabled = false; - /** - * Defines if the material uses sheen. - */ - this.isEnabled = false; - this._linkSheenWithAlbedo = false; - /** - * Defines if the sheen is linked to the sheen color. - */ - this.linkSheenWithAlbedo = false; - /** - * Defines the sheen intensity. - */ - this.intensity = 1; - /** - * Defines the sheen color. - */ - this.color = math_color_Color3.White(); - this._texture = null; - /** - * Stores the sheen tint values in a texture. - * rgb is tint - * 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) - * If the roughness property has been defined and useRoughnessFromTexture is false then the alpha channel is not used to modulate roughness - */ - this.texture = null; - this._useRoughnessFromMainTexture = true; - /** - * Indicates that the alpha channel of the texture property will be used for roughness. - * Has no effect if the roughness (and texture!) property is not defined - */ - this.useRoughnessFromMainTexture = true; - this._roughness = null; - /** - * Defines the sheen roughness. - * It is not taken into account if linkSheenWithAlbedo is true. - * To stay backward compatible, material roughness is used instead if sheen roughness = null - */ - this.roughness = null; - this._textureRoughness = null; - /** - * Stores the sheen roughness in a texture. - * alpha channel is the roughness. This texture won't be used if the texture property is not empty and useRoughnessFromTexture is true - */ - this.textureRoughness = null; - this._albedoScaling = false; - /** - * If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique. - * It allows the strength of the sheen effect to not depend on the base color of the material, - * making it easier to setup and tweak the effect - */ - this.albedoScaling = false; - this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; - } - isReadyForSubMesh(defines, scene) { - if (!this._isEnabled) { - return true; - } - if (defines._areTexturesDirty) { - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.SheenTextureEnabled) { - if (!this._texture.isReadyOrNotBlocking()) { - return false; - } - } - if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) { - if (!this._textureRoughness.isReadyOrNotBlocking()) { - return false; - } - } - } - } - return true; - } - prepareDefinesBeforeAttributes(defines, scene) { - var _a; - if (this._isEnabled) { - defines.SHEEN = true; - defines.SHEEN_LINKWITHALBEDO = this._linkSheenWithAlbedo; - defines.SHEEN_ROUGHNESS = this._roughness !== null; - defines.SHEEN_ALBEDOSCALING = this._albedoScaling; - defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture; - defines.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = - this._texture !== null && this._texture._texture === ((_a = this._textureRoughness) === null || _a === void 0 ? void 0 : _a._texture) && this._texture.checkTransformsAreIdentical(this._textureRoughness); - if (defines._areTexturesDirty) { - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.SheenTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, "SHEEN_TEXTURE"); - defines.SHEEN_GAMMATEXTURE = this._texture.gammaSpace; - } - else { - defines.SHEEN_TEXTURE = false; - } - if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness, defines, "SHEEN_TEXTURE_ROUGHNESS"); - } - else { - defines.SHEEN_TEXTURE_ROUGHNESS = false; - } - } - } - } - else { - defines.SHEEN = false; - defines.SHEEN_TEXTURE = false; - defines.SHEEN_TEXTURE_ROUGHNESS = false; - defines.SHEEN_LINKWITHALBEDO = false; - defines.SHEEN_ROUGHNESS = false; - defines.SHEEN_ALBEDOSCALING = false; - defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false; - defines.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = false; - defines.SHEEN_GAMMATEXTURE = false; - defines.SHEEN_TEXTUREDIRECTUV = 0; - defines.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0; - } - } - bindForSubMesh(uniformBuffer, scene, engine, subMesh) { - var _a, _b, _c, _d, _e, _f, _g, _h; - if (!this._isEnabled) { - return; - } - const defines = subMesh.materialDefines; - const isFrozen = this._material.isFrozen; - const identicalTextures = defines.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL; - if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { - if (identicalTextures && MaterialFlags.SheenTextureEnabled) { - uniformBuffer.updateFloat4("vSheenInfos", this._texture.coordinatesIndex, this._texture.level, -1, -1); - MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, "sheen"); - } - else if ((this._texture || this._textureRoughness) && MaterialFlags.SheenTextureEnabled) { - 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); - if (this._texture) { - MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, "sheen"); - } - if (this._textureRoughness && !identicalTextures && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) { - MaterialHelper.BindTextureMatrix(this._textureRoughness, uniformBuffer, "sheenRoughness"); - } - } - // Sheen - uniformBuffer.updateFloat4("vSheenColor", this.color.r, this.color.g, this.color.b, this.intensity); - if (this._roughness !== null) { - uniformBuffer.updateFloat("vSheenRoughness", this._roughness); - } - } - // Textures - if (scene.texturesEnabled) { - if (this._texture && MaterialFlags.SheenTextureEnabled) { - uniformBuffer.setTexture("sheenSampler", this._texture); - } - if (this._textureRoughness && !identicalTextures && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.SheenTextureEnabled) { - uniformBuffer.setTexture("sheenRoughnessSampler", this._textureRoughness); - } - } - } - hasTexture(texture) { - if (this._texture === texture) { - return true; - } - if (this._textureRoughness === texture) { - return true; - } - return false; - } - getActiveTextures(activeTextures) { - if (this._texture) { - activeTextures.push(this._texture); - } - if (this._textureRoughness) { - activeTextures.push(this._textureRoughness); - } - } - getAnimatables(animatables) { - if (this._texture && this._texture.animations && this._texture.animations.length > 0) { - animatables.push(this._texture); - } - if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) { - animatables.push(this._textureRoughness); - } - } - dispose(forceDisposeTextures) { - var _a, _b; - if (forceDisposeTextures) { - (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose(); - (_b = this._textureRoughness) === null || _b === void 0 ? void 0 : _b.dispose(); - } - } - getClassName() { - return "PBRSheenConfiguration"; - } - addFallbacks(defines, fallbacks, currentRank) { - if (defines.SHEEN) { - fallbacks.addFallback(currentRank++, "SHEEN"); - } - return currentRank; - } - getSamplers(samplers) { - samplers.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" }, - ], - }; - } -} -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSheenConfiguration_PBRSheenConfiguration.prototype, "isEnabled", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSheenConfiguration_PBRSheenConfiguration.prototype, "linkSheenWithAlbedo", void 0); -__decorate([ - serialize() -], pbrSheenConfiguration_PBRSheenConfiguration.prototype, "intensity", void 0); -__decorate([ - serializeAsColor3() -], pbrSheenConfiguration_PBRSheenConfiguration.prototype, "color", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSheenConfiguration_PBRSheenConfiguration.prototype, "texture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSheenConfiguration_PBRSheenConfiguration.prototype, "useRoughnessFromMainTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSheenConfiguration_PBRSheenConfiguration.prototype, "roughness", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSheenConfiguration_PBRSheenConfiguration.prototype, "textureRoughness", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSheenConfiguration_PBRSheenConfiguration.prototype, "albedoScaling", void 0); -//# sourceMappingURL=pbrSheenConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrSubSurfaceConfiguration.js - - - - - - - - - - -/** - * @internal - */ -class MaterialSubSurfaceDefines extends MaterialDefines { - constructor() { - super(...arguments); - this.SUBSURFACE = false; - this.SS_REFRACTION = false; - this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = false; - this.SS_TRANSLUCENCY = false; - this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = false; - this.SS_SCATTERING = false; - this.SS_THICKNESSANDMASK_TEXTURE = false; - this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0; - this.SS_HAS_THICKNESS = false; - this.SS_REFRACTIONINTENSITY_TEXTURE = false; - this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0; - this.SS_TRANSLUCENCYINTENSITY_TEXTURE = false; - this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0; - this.SS_REFRACTIONMAP_3D = false; - this.SS_REFRACTIONMAP_OPPOSITEZ = false; - this.SS_LODINREFRACTIONALPHA = false; - this.SS_GAMMAREFRACTION = false; - this.SS_RGBDREFRACTION = false; - this.SS_LINEARSPECULARREFRACTION = false; - this.SS_LINKREFRACTIONTOTRANSPARENCY = false; - this.SS_ALBEDOFORREFRACTIONTINT = false; - this.SS_ALBEDOFORTRANSLUCENCYTINT = false; - this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false; - this.SS_USE_THICKNESS_AS_DEPTH = false; - this.SS_MASK_FROM_THICKNESS_TEXTURE = false; - this.SS_USE_GLTF_TEXTURES = false; - } -} -/** - * Plugin that implements the sub surface component of the PBR material - */ -class pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration extends MaterialPluginBase { - /** - * Diffusion profile for subsurface scattering. - * Useful for better scattering in the skins or foliages. - */ - get scatteringDiffusionProfile() { - if (!this._scene.subSurfaceConfiguration) { - return null; - } - return this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]; - } - set scatteringDiffusionProfile(c) { - if (!this._scene.enableSubSurfaceForPrePass()) { - // Not supported - return; - } - // addDiffusionProfile automatically checks for doubles - if (c) { - this._scatteringDiffusionProfileIndex = this._scene.subSurfaceConfiguration.addDiffusionProfile(c); - } - } - /** - * Index of refraction of the material's volume. - * https://en.wikipedia.org/wiki/List_of_refractive_indices - * - * This ONLY impacts refraction. If not provided or given a non-valid value, - * the volume will use the same IOR as the surface. - */ - get volumeIndexOfRefraction() { - if (this._volumeIndexOfRefraction >= 1.0) { - return this._volumeIndexOfRefraction; - } - return this._indexOfRefraction; - } - set volumeIndexOfRefraction(value) { - if (value >= 1.0) { - this._volumeIndexOfRefraction = value; - } - else { - this._volumeIndexOfRefraction = -1.0; - } - } - /** @internal */ - _markAllSubMeshesAsTexturesDirty() { - this._enable(this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled); - this._internalMarkAllSubMeshesAsTexturesDirty(); - } - /** @internal */ - _markScenePrePassDirty() { - this._internalMarkAllSubMeshesAsTexturesDirty(); - this._internalMarkScenePrePassDirty(); - } - constructor(material, addToPluginList = true) { - super(material, "PBRSubSurface", 130, new MaterialSubSurfaceDefines(), addToPluginList); - this._isRefractionEnabled = false; - /** - * Defines if the refraction is enabled in the material. - */ - this.isRefractionEnabled = false; - this._isTranslucencyEnabled = false; - /** - * Defines if the translucency is enabled in the material. - */ - this.isTranslucencyEnabled = false; - this._isScatteringEnabled = false; - /** - * Defines if the sub surface scattering is enabled in the material. - */ - this.isScatteringEnabled = false; - this._scatteringDiffusionProfileIndex = 0; - /** - * Defines the refraction intensity of the material. - * The refraction when enabled replaces the Diffuse part of the material. - * The intensity helps transitioning between diffuse and refraction. - */ - this.refractionIntensity = 1; - /** - * Defines the translucency intensity of the material. - * When translucency has been enabled, this defines how much of the "translucency" - * is added to the diffuse part of the material. - */ - this.translucencyIntensity = 1; - /** - * When enabled, transparent surfaces will be tinted with the albedo colour (independent of thickness) - */ - this.useAlbedoToTintRefraction = false; - /** - * When enabled, translucent surfaces will be tinted with the albedo colour (independent of thickness) - */ - this.useAlbedoToTintTranslucency = false; - this._thicknessTexture = null; - /** - * Stores the average thickness of a mesh in a texture (The texture is holding the values linearly). - * The red (or green if useGltfStyleTextures=true) channel of the texture should contain the thickness remapped between 0 and 1. - * 0 would mean minimumThickness - * 1 would mean maximumThickness - * The other channels might be use as a mask to vary the different effects intensity. - */ - this.thicknessTexture = null; - this._refractionTexture = null; - /** - * Defines the texture to use for refraction. - */ - this.refractionTexture = null; - /** @internal */ - this._indexOfRefraction = 1.5; - /** - * Index of refraction of the material base layer. - * https://en.wikipedia.org/wiki/List_of_refractive_indices - * - * This does not only impact refraction but also the Base F0 of Dielectric Materials. - * - * From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI)) - */ - this.indexOfRefraction = 1.5; - this._volumeIndexOfRefraction = -1.0; - this._invertRefractionY = false; - /** - * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. - */ - this.invertRefractionY = false; - /** @internal */ - this._linkRefractionWithTransparency = false; - /** - * This parameters will make the material used its opacity to control how much it is refracting against not. - * Materials half opaque for instance using refraction could benefit from this control. - */ - this.linkRefractionWithTransparency = false; - /** - * Defines the minimum thickness stored in the thickness map. - * If no thickness map is defined, this value will be used to simulate thickness. - */ - this.minimumThickness = 0; - /** - * Defines the maximum thickness stored in the thickness map. - */ - this.maximumThickness = 1; - /** - * Defines that the thickness should be used as a measure of the depth volume. - */ - this.useThicknessAsDepth = false; - /** - * Defines the volume tint of the material. - * This is used for both translucency and scattering. - */ - this.tintColor = math_color_Color3.White(); - /** - * Defines the distance at which the tint color should be found in the media. - * This is used for refraction only. - */ - this.tintColorAtDistance = 1; - /** - * Defines how far each channel transmit through the media. - * It is defined as a color to simplify it selection. - */ - this.diffusionDistance = math_color_Color3.White(); - this._useMaskFromThicknessTexture = false; - /** - * Stores the intensity of the different subsurface effects in the thickness texture. - * Note that if refractionIntensityTexture and/or translucencyIntensityTexture is provided it takes precedence over thicknessTexture + useMaskFromThicknessTexture - * * the green (red if useGltfStyleTextures = true) channel is the refraction intensity. - * * the blue channel is the translucency intensity. - */ - this.useMaskFromThicknessTexture = false; - this._refractionIntensityTexture = null; - /** - * Stores the intensity of the refraction. If provided, it takes precedence over thicknessTexture + useMaskFromThicknessTexture - * * the green (red if useGltfStyleTextures = true) channel is the refraction intensity. - */ - this.refractionIntensityTexture = null; - this._translucencyIntensityTexture = null; - /** - * Stores the intensity of the translucency. If provided, it takes precedence over thicknessTexture + useMaskFromThicknessTexture - * * the blue channel is the translucency intensity. - */ - this.translucencyIntensityTexture = null; - this._useGltfStyleTextures = false; - /** - * Use channels layout used by glTF: - * * thicknessTexture: the green (instead of red) channel is the thickness - * * thicknessTexture/refractionIntensityTexture: the red (instead of green) channel is the refraction intensity - * * thicknessTexture/translucencyIntensityTexture: no change, use the blue channel for the translucency intensity - */ - this.useGltfStyleTextures = false; - this._scene = material.getScene(); - this.registerForExtraEvents = true; - this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; - this._internalMarkScenePrePassDirty = material._dirtyCallbacks[32]; - } - isReadyForSubMesh(defines, scene) { - if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) { - return true; - } - if (defines._areTexturesDirty) { - if (scene.texturesEnabled) { - if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) { - if (!this._thicknessTexture.isReadyOrNotBlocking()) { - return false; - } - } - const refractionTexture = this._getRefractionTexture(scene); - if (refractionTexture && MaterialFlags.RefractionTextureEnabled) { - if (!refractionTexture.isReadyOrNotBlocking()) { - return false; - } - } - } - } - return true; - } - prepareDefinesBeforeAttributes(defines, scene) { - if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) { - defines.SUBSURFACE = false; - defines.SS_TRANSLUCENCY = false; - defines.SS_SCATTERING = false; - defines.SS_REFRACTION = false; - defines.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = false; - defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = false; - defines.SS_THICKNESSANDMASK_TEXTURE = false; - defines.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0; - defines.SS_HAS_THICKNESS = false; - defines.SS_REFRACTIONINTENSITY_TEXTURE = false; - defines.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0; - defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false; - defines.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0; - defines.SS_REFRACTIONMAP_3D = false; - defines.SS_REFRACTIONMAP_OPPOSITEZ = false; - defines.SS_LODINREFRACTIONALPHA = false; - defines.SS_GAMMAREFRACTION = false; - defines.SS_RGBDREFRACTION = false; - defines.SS_LINEARSPECULARREFRACTION = false; - defines.SS_LINKREFRACTIONTOTRANSPARENCY = false; - defines.SS_ALBEDOFORREFRACTIONTINT = false; - defines.SS_ALBEDOFORTRANSLUCENCYTINT = false; - defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false; - defines.SS_USE_THICKNESS_AS_DEPTH = false; - defines.SS_MASK_FROM_THICKNESS_TEXTURE = false; - defines.SS_USE_GLTF_TEXTURES = false; - return; - } - if (defines._areTexturesDirty) { - defines.SUBSURFACE = true; - defines.SS_TRANSLUCENCY = this._isTranslucencyEnabled; - defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = false; - defines.SS_SCATTERING = this._isScatteringEnabled; - defines.SS_THICKNESSANDMASK_TEXTURE = false; - defines.SS_REFRACTIONINTENSITY_TEXTURE = false; - defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false; - defines.SS_HAS_THICKNESS = false; - defines.SS_MASK_FROM_THICKNESS_TEXTURE = false; - defines.SS_USE_GLTF_TEXTURES = false; - defines.SS_REFRACTION = false; - defines.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = false; - defines.SS_REFRACTIONMAP_3D = false; - defines.SS_GAMMAREFRACTION = false; - defines.SS_RGBDREFRACTION = false; - defines.SS_LINEARSPECULARREFRACTION = false; - defines.SS_REFRACTIONMAP_OPPOSITEZ = false; - defines.SS_LODINREFRACTIONALPHA = false; - defines.SS_LINKREFRACTIONTOTRANSPARENCY = false; - defines.SS_ALBEDOFORREFRACTIONTINT = false; - defines.SS_ALBEDOFORTRANSLUCENCYTINT = false; - defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false; - defines.SS_USE_THICKNESS_AS_DEPTH = false; - const refractionIntensityTextureIsThicknessTexture = !!this._thicknessTexture && - !!this._refractionIntensityTexture && - this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture) && - this._refractionIntensityTexture._texture === this._thicknessTexture._texture; - const translucencyIntensityTextureIsThicknessTexture = !!this._thicknessTexture && - !!this._translucencyIntensityTexture && - this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture) && - this._translucencyIntensityTexture._texture === this._thicknessTexture._texture; - // 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 - const useOnlyThicknessTexture = (refractionIntensityTextureIsThicknessTexture || !this._refractionIntensityTexture) && - (translucencyIntensityTextureIsThicknessTexture || !this._translucencyIntensityTexture); - if (defines._areTexturesDirty) { - if (scene.texturesEnabled) { - if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture, defines, "SS_THICKNESSANDMASK_TEXTURE"); - } - if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && !useOnlyThicknessTexture) { - MaterialHelper.PrepareDefinesForMergedUV(this._refractionIntensityTexture, defines, "SS_REFRACTIONINTENSITY_TEXTURE"); - } - if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && !useOnlyThicknessTexture) { - MaterialHelper.PrepareDefinesForMergedUV(this._translucencyIntensityTexture, defines, "SS_TRANSLUCENCYINTENSITY_TEXTURE"); - } - } - } - defines.SS_HAS_THICKNESS = this.maximumThickness - this.minimumThickness !== 0.0; - defines.SS_MASK_FROM_THICKNESS_TEXTURE = - (this._useMaskFromThicknessTexture || !!this._refractionIntensityTexture || !!this._translucencyIntensityTexture) && useOnlyThicknessTexture; - defines.SS_USE_GLTF_TEXTURES = this._useGltfStyleTextures; - defines.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = (this._useMaskFromThicknessTexture || !!this._refractionIntensityTexture) && useOnlyThicknessTexture; - defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = (this._useMaskFromThicknessTexture || !!this._translucencyIntensityTexture) && useOnlyThicknessTexture; - if (this._isRefractionEnabled) { - if (scene.texturesEnabled) { - const refractionTexture = this._getRefractionTexture(scene); - if (refractionTexture && MaterialFlags.RefractionTextureEnabled) { - defines.SS_REFRACTION = true; - defines.SS_REFRACTIONMAP_3D = refractionTexture.isCube; - defines.SS_GAMMAREFRACTION = refractionTexture.gammaSpace; - defines.SS_RGBDREFRACTION = refractionTexture.isRGBD; - defines.SS_LINEARSPECULARREFRACTION = refractionTexture.linearSpecularLOD; - defines.SS_REFRACTIONMAP_OPPOSITEZ = this._scene.useRightHandedSystem && refractionTexture.isCube ? !refractionTexture.invertZ : refractionTexture.invertZ; - defines.SS_LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha; - defines.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency; - defines.SS_ALBEDOFORREFRACTIONTINT = this.useAlbedoToTintRefraction; - defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = refractionTexture.isCube && refractionTexture.boundingBoxSize; - defines.SS_USE_THICKNESS_AS_DEPTH = this.useThicknessAsDepth; - } - } - } - if (this._isTranslucencyEnabled) { - defines.SS_ALBEDOFORTRANSLUCENCYTINT = this.useAlbedoToTintTranslucency; - } - } - } - /** - * Binds the material data (this function is called even if mustRebind() returns false) - * @param uniformBuffer defines the Uniform buffer to fill in. - * @param scene defines the scene the material belongs to. - * @param engine defines the engine the material belongs to. - * @param subMesh the submesh to bind data for - */ - hardBindForSubMesh(uniformBuffer, scene, engine, subMesh) { - if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) { - return; - } - subMesh.getRenderingMesh().getWorldMatrix().decompose(math_vector_TmpVectors.Vector3[0]); - const thicknessScale = Math.max(Math.abs(math_vector_TmpVectors.Vector3[0].x), Math.abs(math_vector_TmpVectors.Vector3[0].y), Math.abs(math_vector_TmpVectors.Vector3[0].z)); - uniformBuffer.updateFloat2("vThicknessParam", this.minimumThickness * thicknessScale, (this.maximumThickness - this.minimumThickness) * thicknessScale); - } - bindForSubMesh(uniformBuffer, scene, engine, subMesh) { - if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) { - return; - } - const defines = subMesh.materialDefines; - const isFrozen = this._material.isFrozen; - const realTimeFiltering = this._material.realTimeFiltering; - const lodBasedMicrosurface = defines.LODBASEDMICROSFURACE; - const refractionTexture = this._getRefractionTexture(scene); - if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { - if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) { - uniformBuffer.updateFloat2("vThicknessInfos", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level); - MaterialHelper.BindTextureMatrix(this._thicknessTexture, uniformBuffer, "thickness"); - } - if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) { - uniformBuffer.updateFloat2("vRefractionIntensityInfos", this._refractionIntensityTexture.coordinatesIndex, this._refractionIntensityTexture.level); - MaterialHelper.BindTextureMatrix(this._refractionIntensityTexture, uniformBuffer, "refractionIntensity"); - } - if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) { - uniformBuffer.updateFloat2("vTranslucencyIntensityInfos", this._translucencyIntensityTexture.coordinatesIndex, this._translucencyIntensityTexture.level); - MaterialHelper.BindTextureMatrix(this._translucencyIntensityTexture, uniformBuffer, "translucencyIntensity"); - } - if (refractionTexture && MaterialFlags.RefractionTextureEnabled) { - uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getRefractionTextureMatrix()); - let depth = 1.0; - if (!refractionTexture.isCube) { - if (refractionTexture.depth) { - depth = refractionTexture.depth; - } - } - const width = refractionTexture.getSize().width; - const refractionIor = this.volumeIndexOfRefraction; - uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, 1 / refractionIor, depth, this._invertRefractionY ? -1 : 1); - uniformBuffer.updateFloat4("vRefractionMicrosurfaceInfos", width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset, 1.0 / this.indexOfRefraction); - if (realTimeFiltering) { - uniformBuffer.updateFloat2("vRefractionFilteringInfo", width, math_scalar_Scalar.Log2(width)); - } - if (refractionTexture.boundingBoxSize) { - const cubeTexture = refractionTexture; - uniformBuffer.updateVector3("vRefractionPosition", cubeTexture.boundingBoxPosition); - uniformBuffer.updateVector3("vRefractionSize", cubeTexture.boundingBoxSize); - } - } - if (this._isScatteringEnabled) { - uniformBuffer.updateFloat("scatteringDiffusionProfile", this._scatteringDiffusionProfileIndex); - } - uniformBuffer.updateColor3("vDiffusionDistance", this.diffusionDistance); - uniformBuffer.updateFloat4("vTintColor", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintColorAtDistance)); - uniformBuffer.updateFloat3("vSubSurfaceIntensity", this.refractionIntensity, this.translucencyIntensity, 0); - } - // Textures - if (scene.texturesEnabled) { - if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) { - uniformBuffer.setTexture("thicknessSampler", this._thicknessTexture); - } - if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) { - uniformBuffer.setTexture("refractionIntensitySampler", this._refractionIntensityTexture); - } - if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) { - uniformBuffer.setTexture("translucencyIntensitySampler", this._translucencyIntensityTexture); - } - if (refractionTexture && MaterialFlags.RefractionTextureEnabled) { - if (lodBasedMicrosurface) { - uniformBuffer.setTexture("refractionSampler", refractionTexture); - } - else { - uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture); - uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture); - uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture); - } - } - } - } - /** - * Returns the texture used for refraction or null if none is used. - * @param scene defines the scene the material belongs to. - * @returns - Refraction texture if present. If no refraction texture and refraction - * is linked with transparency, returns environment texture. Otherwise, returns null. - */ - _getRefractionTexture(scene) { - if (this._refractionTexture) { - return this._refractionTexture; - } - if (this._isRefractionEnabled) { - return scene.environmentTexture; - } - return null; - } - /** - * Returns true if alpha blending should be disabled. - */ - get disableAlphaBlending() { - return this._isRefractionEnabled && this._linkRefractionWithTransparency; - } - /** - * Fills the list of render target textures. - * @param renderTargets the list of render targets to update - */ - fillRenderTargetTextures(renderTargets) { - if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { - renderTargets.push(this._refractionTexture); - } - } - hasTexture(texture) { - if (this._thicknessTexture === texture) { - return true; - } - if (this._refractionTexture === texture) { - return true; - } - return false; - } - hasRenderTargetTextures() { - if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { - return true; - } - return false; - } - getActiveTextures(activeTextures) { - if (this._thicknessTexture) { - activeTextures.push(this._thicknessTexture); - } - if (this._refractionTexture) { - activeTextures.push(this._refractionTexture); - } - } - getAnimatables(animatables) { - if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) { - animatables.push(this._thicknessTexture); - } - if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) { - animatables.push(this._refractionTexture); - } - } - dispose(forceDisposeTextures) { - if (forceDisposeTextures) { - if (this._thicknessTexture) { - this._thicknessTexture.dispose(); - } - if (this._refractionTexture) { - this._refractionTexture.dispose(); - } - } - } - getClassName() { - return "PBRSubSurfaceConfiguration"; - } - addFallbacks(defines, fallbacks, currentRank) { - if (defines.SS_SCATTERING) { - fallbacks.addFallback(currentRank++, "SS_SCATTERING"); - } - if (defines.SS_TRANSLUCENCY) { - fallbacks.addFallback(currentRank++, "SS_TRANSLUCENCY"); - } - return currentRank; - } - getSamplers(samplers) { - samplers.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" }, - ], - }; - } -} -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "isRefractionEnabled", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "isTranslucencyEnabled", void 0); -__decorate([ - serialize(), - expandToProperty("_markScenePrePassDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "isScatteringEnabled", void 0); -__decorate([ - serialize() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "_scatteringDiffusionProfileIndex", void 0); -__decorate([ - serialize() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "refractionIntensity", void 0); -__decorate([ - serialize() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "translucencyIntensity", void 0); -__decorate([ - serialize() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "useAlbedoToTintRefraction", void 0); -__decorate([ - serialize() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "useAlbedoToTintTranslucency", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "thicknessTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "refractionTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "indexOfRefraction", void 0); -__decorate([ - serialize() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "_volumeIndexOfRefraction", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "volumeIndexOfRefraction", null); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "invertRefractionY", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "linkRefractionWithTransparency", void 0); -__decorate([ - serialize() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "minimumThickness", void 0); -__decorate([ - serialize() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "maximumThickness", void 0); -__decorate([ - serialize() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "useThicknessAsDepth", void 0); -__decorate([ - serializeAsColor3() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "tintColor", void 0); -__decorate([ - serialize() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "tintColorAtDistance", void 0); -__decorate([ - serializeAsColor3() -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "diffusionDistance", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "useMaskFromThicknessTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "refractionIntensityTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "translucencyIntensityTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype, "useGltfStyleTextures", void 0); -//# sourceMappingURL=pbrSubSurfaceConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrBaseMaterial.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -const pbrBaseMaterial_onCreatedEffectParameters = { effect: null, subMesh: null }; -/** - * Manages the defines for the PBR Material. - * @internal - */ -class PBRMaterialDefines extends MaterialDefines { - /** - * Initializes the PBR Material defines. - * @param externalProperties The external properties - */ - constructor(externalProperties) { - super(externalProperties); - this.PBR = true; - this.NUM_SAMPLES = "0"; - this.REALTIME_FILTERING = false; - this.MAINUV1 = false; - this.MAINUV2 = false; - this.MAINUV3 = false; - this.MAINUV4 = false; - this.MAINUV5 = false; - this.MAINUV6 = false; - this.UV1 = false; - this.UV2 = false; - this.UV3 = false; - this.UV4 = false; - this.UV5 = false; - this.UV6 = false; - this.ALBEDO = false; - this.GAMMAALBEDO = false; - this.ALBEDODIRECTUV = 0; - this.VERTEXCOLOR = false; - this.BAKED_VERTEX_ANIMATION_TEXTURE = false; - this.AMBIENT = false; - this.AMBIENTDIRECTUV = 0; - this.AMBIENTINGRAYSCALE = false; - this.OPACITY = false; - this.VERTEXALPHA = false; - this.OPACITYDIRECTUV = 0; - this.OPACITYRGB = false; - this.ALPHATEST = false; - this.DEPTHPREPASS = false; - this.ALPHABLEND = false; - this.ALPHAFROMALBEDO = false; - this.ALPHATESTVALUE = "0.5"; - this.SPECULAROVERALPHA = false; - this.RADIANCEOVERALPHA = false; - this.ALPHAFRESNEL = false; - this.LINEARALPHAFRESNEL = false; - this.PREMULTIPLYALPHA = false; - this.EMISSIVE = false; - this.EMISSIVEDIRECTUV = 0; - this.GAMMAEMISSIVE = false; - this.REFLECTIVITY = false; - this.REFLECTIVITY_GAMMA = false; - this.REFLECTIVITYDIRECTUV = 0; - this.SPECULARTERM = false; - this.MICROSURFACEFROMREFLECTIVITYMAP = false; - this.MICROSURFACEAUTOMATIC = false; - this.LODBASEDMICROSFURACE = false; - this.MICROSURFACEMAP = false; - this.MICROSURFACEMAPDIRECTUV = 0; - this.METALLICWORKFLOW = false; - this.ROUGHNESSSTOREINMETALMAPALPHA = false; - this.ROUGHNESSSTOREINMETALMAPGREEN = false; - this.METALLNESSSTOREINMETALMAPBLUE = false; - this.AOSTOREINMETALMAPRED = false; - this.METALLIC_REFLECTANCE = false; - this.METALLIC_REFLECTANCE_GAMMA = false; - this.METALLIC_REFLECTANCEDIRECTUV = 0; - this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = false; - this.REFLECTANCE = false; - this.REFLECTANCE_GAMMA = false; - this.REFLECTANCEDIRECTUV = 0; - this.ENVIRONMENTBRDF = false; - this.ENVIRONMENTBRDF_RGBD = false; - this.NORMAL = false; - this.TANGENT = false; - this.BUMP = false; - this.BUMPDIRECTUV = 0; - this.OBJECTSPACE_NORMALMAP = false; - this.PARALLAX = false; - this.PARALLAXOCCLUSION = false; - this.NORMALXYSCALE = true; - this.LIGHTMAP = false; - this.LIGHTMAPDIRECTUV = 0; - this.USELIGHTMAPASSHADOWMAP = false; - this.GAMMALIGHTMAP = false; - this.RGBDLIGHTMAP = false; - this.REFLECTION = false; - this.REFLECTIONMAP_3D = false; - this.REFLECTIONMAP_SPHERICAL = false; - this.REFLECTIONMAP_PLANAR = false; - this.REFLECTIONMAP_CUBIC = false; - this.USE_LOCAL_REFLECTIONMAP_CUBIC = false; - this.REFLECTIONMAP_PROJECTION = false; - this.REFLECTIONMAP_SKYBOX = false; - this.REFLECTIONMAP_EXPLICIT = false; - this.REFLECTIONMAP_EQUIRECTANGULAR = false; - this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; - this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; - this.INVERTCUBICMAP = false; - this.USESPHERICALFROMREFLECTIONMAP = false; - this.USEIRRADIANCEMAP = false; - this.USESPHERICALINVERTEX = false; - this.REFLECTIONMAP_OPPOSITEZ = false; - this.LODINREFLECTIONALPHA = false; - this.GAMMAREFLECTION = false; - this.RGBDREFLECTION = false; - this.LINEARSPECULARREFLECTION = false; - this.RADIANCEOCCLUSION = false; - this.HORIZONOCCLUSION = false; - this.INSTANCES = false; - this.THIN_INSTANCES = false; - this.INSTANCESCOLOR = false; - this.PREPASS = false; - this.PREPASS_IRRADIANCE = false; - this.PREPASS_IRRADIANCE_INDEX = -1; - this.PREPASS_ALBEDO_SQRT = false; - this.PREPASS_ALBEDO_SQRT_INDEX = -1; - this.PREPASS_DEPTH = false; - this.PREPASS_DEPTH_INDEX = -1; - this.PREPASS_NORMAL = false; - this.PREPASS_NORMAL_INDEX = -1; - this.PREPASS_POSITION = false; - this.PREPASS_POSITION_INDEX = -1; - this.PREPASS_VELOCITY = false; - this.PREPASS_VELOCITY_INDEX = -1; - this.PREPASS_REFLECTIVITY = false; - this.PREPASS_REFLECTIVITY_INDEX = -1; - this.SCENE_MRT_COUNT = 0; - this.NUM_BONE_INFLUENCERS = 0; - this.BonesPerMesh = 0; - this.BONETEXTURE = false; - this.BONES_VELOCITY_ENABLED = false; - this.NONUNIFORMSCALING = false; - this.MORPHTARGETS = false; - this.MORPHTARGETS_NORMAL = false; - this.MORPHTARGETS_TANGENT = false; - this.MORPHTARGETS_UV = false; - this.NUM_MORPH_INFLUENCERS = 0; - this.MORPHTARGETS_TEXTURE = false; - this.IMAGEPROCESSING = false; - this.VIGNETTE = false; - this.VIGNETTEBLENDMODEMULTIPLY = false; - this.VIGNETTEBLENDMODEOPAQUE = false; - this.TONEMAPPING = false; - this.TONEMAPPING_ACES = false; - this.CONTRAST = false; - this.COLORCURVES = false; - this.COLORGRADING = false; - this.COLORGRADING3D = false; - this.SAMPLER3DGREENDEPTH = false; - this.SAMPLER3DBGRMAP = false; - this.DITHER = false; - this.IMAGEPROCESSINGPOSTPROCESS = false; - this.SKIPFINALCOLORCLAMP = false; - this.EXPOSURE = false; - this.MULTIVIEW = false; - this.ORDER_INDEPENDENT_TRANSPARENCY = false; - this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false; - this.USEPHYSICALLIGHTFALLOFF = false; - this.USEGLTFLIGHTFALLOFF = false; - this.TWOSIDEDLIGHTING = false; - this.SHADOWFLOAT = false; - this.CLIPPLANE = false; - this.CLIPPLANE2 = false; - this.CLIPPLANE3 = false; - this.CLIPPLANE4 = false; - this.CLIPPLANE5 = false; - this.CLIPPLANE6 = false; - this.POINTSIZE = false; - this.FOG = false; - this.LOGARITHMICDEPTH = false; - this.CAMERA_ORTHOGRAPHIC = false; - this.CAMERA_PERSPECTIVE = false; - this.FORCENORMALFORWARD = false; - this.SPECULARAA = false; - this.UNLIT = false; - this.DECAL_AFTER_DETAIL = false; - this.DEBUGMODE = 0; - this.rebuild(); - } - /** - * Resets the PBR Material defines. - */ - reset() { - super.reset(); - this.ALPHATESTVALUE = "0.5"; - this.PBR = true; - this.NORMALXYSCALE = true; - } -} -/** - * The Physically based material base class of BJS. - * - * This offers the main features of a standard PBR material. - * For more information, please refer to the documentation : - * https://doc.babylonjs.com/features/featuresDeepDive/materials/using/introToPBR - */ -class pbrBaseMaterial_PBRBaseMaterial extends PushMaterial { - /** - * Enables realtime filtering on the texture. - */ - get realTimeFiltering() { - return this._realTimeFiltering; - } - set realTimeFiltering(b) { - this._realTimeFiltering = b; - this.markAsDirty(1); - } - /** - * Quality switch for realtime filtering - */ - get realTimeFilteringQuality() { - return this._realTimeFilteringQuality; - } - set realTimeFilteringQuality(n) { - this._realTimeFilteringQuality = n; - this.markAsDirty(1); - } - /** - * Can this material render to several textures at once - */ - get canRenderToMRT() { - return true; - } - /** - * Attaches a new image processing configuration to the PBR Material. - * @param configuration - */ - _attachImageProcessingConfiguration(configuration) { - if (configuration === this._imageProcessingConfiguration) { - return; - } - // Detaches observer. - if (this._imageProcessingConfiguration && this._imageProcessingObserver) { - this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); - } - // Pick the scene configuration if needed. - if (!configuration) { - this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; - } - else { - this._imageProcessingConfiguration = configuration; - } - // Attaches observer. - if (this._imageProcessingConfiguration) { - this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { - this._markAllSubMeshesAsImageProcessingDirty(); - }); - } - } - /** - * Instantiates a new PBRMaterial instance. - * - * @param name The material name - * @param scene The scene the material will be use in. - */ - constructor(name, scene) { - super(name, scene); - /** - * Intensity of the direct lights e.g. the four lights available in your scene. - * This impacts both the direct diffuse and specular highlights. - * @internal - */ - this._directIntensity = 1.0; - /** - * Intensity of the emissive part of the material. - * This helps controlling the emissive effect without modifying the emissive color. - * @internal - */ - this._emissiveIntensity = 1.0; - /** - * Intensity of the environment e.g. how much the environment will light the object - * either through harmonics for rough material or through the reflection for shiny ones. - * @internal - */ - this._environmentIntensity = 1.0; - /** - * This is a special control allowing the reduction of the specular highlights coming from the - * four lights of the scene. Those highlights may not be needed in full environment lighting. - * @internal - */ - this._specularIntensity = 1.0; - /** - * This stores the direct, emissive, environment, and specular light intensities into a Vector4. - */ - this._lightingInfos = new math_vector_Vector4(this._directIntensity, this._emissiveIntensity, this._environmentIntensity, this._specularIntensity); - /** - * Debug Control allowing disabling the bump map on this material. - * @internal - */ - this._disableBumpMap = false; - /** - * AKA Diffuse Texture in standard nomenclature. - * @internal - */ - this._albedoTexture = null; - /** - * AKA Occlusion Texture in other nomenclature. - * @internal - */ - this._ambientTexture = null; - /** - * AKA Occlusion Texture Intensity in other nomenclature. - * @internal - */ - this._ambientTextureStrength = 1.0; - /** - * Defines how much the AO map is occluding the analytical lights (point spot...). - * 1 means it completely occludes it - * 0 mean it has no impact - * @internal - */ - this._ambientTextureImpactOnAnalyticalLights = pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS; - /** - * Stores the alpha values in a texture. - * @internal - */ - this._opacityTexture = null; - /** - * Stores the reflection values in a texture. - * @internal - */ - this._reflectionTexture = null; - /** - * Stores the emissive values in a texture. - * @internal - */ - this._emissiveTexture = null; - /** - * AKA Specular texture in other nomenclature. - * @internal - */ - this._reflectivityTexture = null; - /** - * Used to switch from specular/glossiness to metallic/roughness workflow. - * @internal - */ - this._metallicTexture = null; - /** - * Specifies the metallic scalar of the metallic/roughness workflow. - * Can also be used to scale the metalness values of the metallic texture. - * @internal - */ - this._metallic = null; - /** - * Specifies the roughness scalar of the metallic/roughness workflow. - * Can also be used to scale the roughness values of the metallic texture. - * @internal - */ - this._roughness = null; - /** - * In metallic workflow, specifies an F0 factor to help configuring the material F0. - * By default the indexOfrefraction is used to compute F0; - * - * This is used as a factor against the default reflectance at normal incidence to tweak it. - * - * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor; - * F90 = metallicReflectanceColor; - * @internal - */ - this._metallicF0Factor = 1; - /** - * In metallic workflow, specifies an F0 color. - * By default the F90 is always 1; - * - * Please note that this factor is also used as a factor against the default reflectance at normal incidence. - * - * F0 = defaultF0_from_IOR * metallicF0Factor * metallicReflectanceColor - * F90 = metallicF0Factor; - * @internal - */ - this._metallicReflectanceColor = math_color_Color3.White(); - /** - * Specifies that only the A channel from _metallicReflectanceTexture should be used. - * If false, both RGB and A channels will be used - * @internal - */ - this._useOnlyMetallicFromMetallicReflectanceTexture = false; - /** - * Defines to store metallicReflectanceColor in RGB and metallicF0Factor in A - * This is multiply against the scalar values defined in the material. - * @internal - */ - this._metallicReflectanceTexture = null; - /** - * Defines to store reflectanceColor in RGB - * This is multiplied against the scalar values defined in the material. - * If both _reflectanceTexture and _metallicReflectanceTexture textures are provided and _useOnlyMetallicFromMetallicReflectanceTexture - * is false, _metallicReflectanceTexture takes precedence and _reflectanceTexture is not used - * @internal - */ - this._reflectanceTexture = null; - /** - * Used to enable roughness/glossiness fetch from a separate channel depending on the current mode. - * Gray Scale represents roughness in metallic mode and glossiness in specular mode. - * @internal - */ - this._microSurfaceTexture = null; - /** - * Stores surface normal data used to displace a mesh in a texture. - * @internal - */ - this._bumpTexture = null; - /** - * Stores the pre-calculated light information of a mesh in a texture. - * @internal - */ - this._lightmapTexture = null; - /** - * The color of a material in ambient lighting. - * @internal - */ - this._ambientColor = new math_color_Color3(0, 0, 0); - /** - * AKA Diffuse Color in other nomenclature. - * @internal - */ - this._albedoColor = new math_color_Color3(1, 1, 1); - /** - * AKA Specular Color in other nomenclature. - * @internal - */ - this._reflectivityColor = new math_color_Color3(1, 1, 1); - /** - * The color applied when light is reflected from a material. - * @internal - */ - this._reflectionColor = new math_color_Color3(1, 1, 1); - /** - * The color applied when light is emitted from a material. - * @internal - */ - this._emissiveColor = new math_color_Color3(0, 0, 0); - /** - * AKA Glossiness in other nomenclature. - * @internal - */ - this._microSurface = 0.9; - /** - * Specifies that the material will use the light map as a show map. - * @internal - */ - this._useLightmapAsShadowmap = false; - /** - * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal - * makes the reflect vector face the model (under horizon). - * @internal - */ - this._useHorizonOcclusion = true; - /** - * This parameters will enable/disable radiance occlusion by preventing the radiance to lit - * too much the area relying on ambient texture to define their ambient occlusion. - * @internal - */ - this._useRadianceOcclusion = true; - /** - * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending. - * @internal - */ - this._useAlphaFromAlbedoTexture = false; - /** - * Specifies that the material will keeps the specular highlights over a transparent surface (only the most luminous ones). - * A car glass is a good example of that. When sun reflects on it you can not see what is behind. - * @internal - */ - this._useSpecularOverAlpha = true; - /** - * Specifies if the reflectivity texture contains the glossiness information in its alpha channel. - * @internal - */ - this._useMicroSurfaceFromReflectivityMapAlpha = false; - /** - * Specifies if the metallic texture contains the roughness information in its alpha channel. - * @internal - */ - this._useRoughnessFromMetallicTextureAlpha = true; - /** - * Specifies if the metallic texture contains the roughness information in its green channel. - * @internal - */ - this._useRoughnessFromMetallicTextureGreen = false; - /** - * Specifies if the metallic texture contains the metallness information in its blue channel. - * @internal - */ - this._useMetallnessFromMetallicTextureBlue = false; - /** - * Specifies if the metallic texture contains the ambient occlusion information in its red channel. - * @internal - */ - this._useAmbientOcclusionFromMetallicTextureRed = false; - /** - * Specifies if the ambient texture contains the ambient occlusion information in its red channel only. - * @internal - */ - this._useAmbientInGrayScale = false; - /** - * In case the reflectivity map does not contain the microsurface information in its alpha channel, - * The material will try to infer what glossiness each pixel should be. - * @internal - */ - this._useAutoMicroSurfaceFromReflectivityMap = false; - /** - * Defines the falloff type used in this material. - * It by default is Physical. - * @internal - */ - this._lightFalloff = pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL; - /** - * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones). - * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind. - * @internal - */ - this._useRadianceOverAlpha = true; - /** - * Allows using an object space normal map (instead of tangent space). - * @internal - */ - this._useObjectSpaceNormalMap = false; - /** - * Allows using the bump map in parallax mode. - * @internal - */ - this._useParallax = false; - /** - * Allows using the bump map in parallax occlusion mode. - * @internal - */ - this._useParallaxOcclusion = false; - /** - * Controls the scale bias of the parallax mode. - * @internal - */ - this._parallaxScaleBias = 0.05; - /** - * If sets to true, disables all the lights affecting the material. - * @internal - */ - this._disableLighting = false; - /** - * Number of Simultaneous lights allowed on the material. - * @internal - */ - this._maxSimultaneousLights = 4; - /** - * If sets to true, x component of normal map value will be inverted (x = 1.0 - x). - * @internal - */ - this._invertNormalMapX = false; - /** - * If sets to true, y component of normal map value will be inverted (y = 1.0 - y). - * @internal - */ - this._invertNormalMapY = false; - /** - * If sets to true and backfaceCulling is false, normals will be flipped on the backside. - * @internal - */ - this._twoSidedLighting = false; - /** - * Defines the alpha limits in alpha test mode. - * @internal - */ - this._alphaCutOff = 0.4; - /** - * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations. - * @internal - */ - this._forceAlphaTest = false; - /** - * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. - * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel) - * @internal - */ - this._useAlphaFresnel = false; - /** - * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. - * And/Or occlude the blended part. (alpha stays linear to compute the fresnel) - * @internal - */ - this._useLinearAlphaFresnel = false; - /** - * Specifies the environment BRDF texture used to compute the scale and offset roughness values - * from cos theta and roughness: - * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf - * @internal - */ - this._environmentBRDFTexture = null; - /** - * Force the shader to compute irradiance in the fragment shader in order to take bump in account. - * @internal - */ - this._forceIrradianceInFragment = false; - this._realTimeFiltering = false; - this._realTimeFilteringQuality = 8; - /** - * Force normal to face away from face. - * @internal - */ - this._forceNormalForward = false; - /** - * Enables specular anti aliasing in the PBR shader. - * It will both interacts on the Geometry for analytical and IBL lighting. - * It also prefilter the roughness map based on the bump values. - * @internal - */ - this._enableSpecularAntiAliasing = false; - /** - * Keep track of the image processing observer to allow dispose and replace. - */ - this._imageProcessingObserver = null; - /** - * Stores the available render targets. - */ - this._renderTargets = new SmartArray(16); - /** - * Sets the global ambient color for the material used in lighting calculations. - */ - this._globalAmbientColor = new math_color_Color3(0, 0, 0); - /** - * Enables the use of logarithmic depth buffers, which is good for wide depth buffers. - */ - this._useLogarithmicDepth = false; - /** - * If set to true, no lighting calculations will be applied. - */ - this._unlit = false; - /** - * If sets to true, the decal map will be applied after the detail map. Else, it is applied before (default: false) - */ - this._applyDecalMapAfterDetailMap = false; - this._debugMode = 0; - /** - * @internal - * This is reserved for the inspector. - * Defines the material debug mode. - * It helps seeing only some components of the material while troubleshooting. - */ - this.debugMode = 0; - /** - * @internal - * This is reserved for the inspector. - * Specify from where on screen the debug mode should start. - * The value goes from -1 (full screen) to 1 (not visible) - * It helps with side by side comparison against the final render - * This defaults to -1 - */ - this.debugLimit = -1; - /** - * @internal - * This is reserved for the inspector. - * As the default viewing range might not be enough (if the ambient is really small for instance) - * You can use the factor to better multiply the final value. - */ - this.debugFactor = 1; - this._cacheHasRenderTargetTextures = false; - this.brdf = new pbrBRDFConfiguration_PBRBRDFConfiguration(this); - this.clearCoat = new pbrClearCoatConfiguration_PBRClearCoatConfiguration(this); - this.iridescence = new pbrIridescenceConfiguration_PBRIridescenceConfiguration(this); - this.anisotropy = new pbrAnisotropicConfiguration_PBRAnisotropicConfiguration(this); - this.sheen = new pbrSheenConfiguration_PBRSheenConfiguration(this); - this.subSurface = new pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration(this); - this.detailMap = new material_detailMapConfiguration_DetailMapConfiguration(this); - // Setup the default processing configuration to the scene. - this._attachImageProcessingConfiguration(null); - this.getRenderTargetTextures = () => { - this._renderTargets.reset(); - if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { - this._renderTargets.push(this._reflectionTexture); - } - this._eventInfo.renderTargets = this._renderTargets; - this._callbackPluginEventFillRenderTargetTextures(this._eventInfo); - return this._renderTargets; - }; - this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene()); - this.prePassConfiguration = new PrePassConfiguration(); - } - /** - * Gets a boolean indicating that current material needs to register RTT - */ - get hasRenderTargetTextures() { - if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { - return true; - } - return this._cacheHasRenderTargetTextures; - } - /** - * Can this material render to prepass - */ - get isPrePassCapable() { - return !this.disableDepthWrite; - } - /** - * Gets the name of the material class. - */ - getClassName() { - return "PBRBaseMaterial"; - } - /** - * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. - */ - get useLogarithmicDepth() { - return this._useLogarithmicDepth; - } - /** - * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. - */ - set useLogarithmicDepth(value) { - this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported; - } - /** - * Returns true if alpha blending should be disabled. - */ - get _disableAlphaBlending() { - var _a; - return (this._transparencyMode === pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE || - this._transparencyMode === pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST || - ((_a = this.subSurface) === null || _a === void 0 ? void 0 : _a.disableAlphaBlending)); - } - /** - * Specifies whether or not this material should be rendered in alpha blend mode. - */ - needAlphaBlending() { - if (this._disableAlphaBlending) { - return false; - } - return this.alpha < 1.0 || this._opacityTexture != null || this._shouldUseAlphaFromAlbedoTexture(); - } - /** - * Specifies whether or not this material should be rendered in alpha test mode. - */ - needAlphaTesting() { - var _a; - if (this._forceAlphaTest) { - return true; - } - if ((_a = this.subSurface) === null || _a === void 0 ? void 0 : _a.disableAlphaBlending) { - return false; - } - return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST); - } - /** - * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending. - */ - _shouldUseAlphaFromAlbedoTexture() { - return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE; - } - /** - * Specifies whether or not there is a usable alpha channel for transparency. - */ - _hasAlphaChannel() { - return (this._albedoTexture != null && this._albedoTexture.hasAlpha) || this._opacityTexture != null; - } - /** - * Gets the texture used for the alpha test. - */ - getAlphaTestTexture() { - return this._albedoTexture; - } - /** - * Specifies that the submesh is ready to be used. - * @param mesh - BJS mesh. - * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready. - * @param useInstances - Specifies that instances should be used. - * @returns - boolean indicating that the submesh is ready or not. - */ - isReadyForSubMesh(mesh, subMesh, useInstances) { - var _a; - if (!this._uniformBufferLayoutBuilt) { - this.buildUniformLayout(); - } - if (subMesh.effect && this.isFrozen) { - if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) { - return true; - } - } - if (!subMesh.materialDefines) { - this._callbackPluginEventGeneric(materialPluginEvent_MaterialPluginEvent.GetDefineNames, this._eventInfo); - subMesh.materialDefines = new PBRMaterialDefines(this._eventInfo.defineNames); - } - const defines = subMesh.materialDefines; - if (this._isReadyForSubMesh(subMesh)) { - return true; - } - const scene = this.getScene(); - const engine = scene.getEngine(); - if (defines._areTexturesDirty) { - this._eventInfo.hasRenderTargetTextures = false; - this._callbackPluginEventHasRenderTargetTextures(this._eventInfo); - this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures; - if (scene.texturesEnabled) { - if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) { - if (!this._albedoTexture.isReadyOrNotBlocking()) { - return false; - } - } - if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) { - if (!this._ambientTexture.isReadyOrNotBlocking()) { - return false; - } - } - if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) { - if (!this._opacityTexture.isReadyOrNotBlocking()) { - return false; - } - } - const reflectionTexture = this._getReflectionTexture(); - if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { - if (!reflectionTexture.isReadyOrNotBlocking()) { - return false; - } - if (reflectionTexture.irradianceTexture) { - if (!reflectionTexture.irradianceTexture.isReadyOrNotBlocking()) { - return false; - } - } - else { - // Not ready until spherical are ready too. - if (!reflectionTexture.sphericalPolynomial && ((_a = reflectionTexture.getInternalTexture()) === null || _a === void 0 ? void 0 : _a._sphericalPolynomialPromise)) { - return false; - } - } - } - if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) { - if (!this._lightmapTexture.isReadyOrNotBlocking()) { - return false; - } - } - if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) { - if (!this._emissiveTexture.isReadyOrNotBlocking()) { - return false; - } - } - if (MaterialFlags.SpecularTextureEnabled) { - if (this._metallicTexture) { - if (!this._metallicTexture.isReadyOrNotBlocking()) { - return false; - } - } - else if (this._reflectivityTexture) { - if (!this._reflectivityTexture.isReadyOrNotBlocking()) { - return false; - } - } - if (this._metallicReflectanceTexture) { - if (!this._metallicReflectanceTexture.isReadyOrNotBlocking()) { - return false; - } - } - if (this._reflectanceTexture) { - if (!this._reflectanceTexture.isReadyOrNotBlocking()) { - return false; - } - } - if (this._microSurfaceTexture) { - if (!this._microSurfaceTexture.isReadyOrNotBlocking()) { - return false; - } - } - } - if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) { - // Bump texture cannot be not blocking. - if (!this._bumpTexture.isReady()) { - return false; - } - } - if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) { - // This is blocking. - if (!this._environmentBRDFTexture.isReady()) { - return false; - } - } - } - } - this._eventInfo.isReadyForSubMesh = true; - this._eventInfo.defines = defines; - this._eventInfo.subMesh = subMesh; - this._callbackPluginEventIsReadyForSubMesh(this._eventInfo); - if (!this._eventInfo.isReadyForSubMesh) { - return false; - } - if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { - if (!this._imageProcessingConfiguration.isReady()) { - return false; - } - } - if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)) { - mesh.createNormals(true); - logger_Logger.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name); - } - const previousEffect = subMesh.effect; - const lightDisposed = defines._areLightsDisposed; - let effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances, null, subMesh.getRenderingMesh().hasThinInstances); - let forceWasNotReadyPreviously = false; - if (effect) { - if (this._onEffectCreatedObservable) { - pbrBaseMaterial_onCreatedEffectParameters.effect = effect; - pbrBaseMaterial_onCreatedEffectParameters.subMesh = subMesh; - this._onEffectCreatedObservable.notifyObservers(pbrBaseMaterial_onCreatedEffectParameters); - } - // Use previous effect while new one is compiling - if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) { - effect = previousEffect; - defines.markAsUnprocessed(); - forceWasNotReadyPreviously = this.isFrozen; - if (lightDisposed) { - // re register in case it takes more than one frame. - defines._areLightsDisposed = true; - return false; - } - } - else { - scene.resetCachedMaterial(); - subMesh.setEffect(effect, defines, this._materialContext); - } - } - if (!subMesh.effect || !subMesh.effect.isReady()) { - return false; - } - defines._renderId = scene.getRenderId(); - subMesh.effect._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true; - subMesh.effect._wasPreviouslyUsingInstances = !!useInstances; - this._checkScenePerformancePriority(); - return true; - } - /** - * Specifies if the material uses metallic roughness workflow. - * @returns boolean specifying if the material uses metallic roughness workflow. - */ - isMetallicWorkflow() { - if (this._metallic != null || this._roughness != null || this._metallicTexture) { - return true; - } - return false; - } - _prepareEffect(mesh, defines, onCompiled = null, onError = null, useInstances = null, useClipPlane = null, useThinInstances) { - this._prepareDefines(mesh, defines, useInstances, useClipPlane, useThinInstances); - if (!defines.isDirty) { - return null; - } - defines.markAsProcessed(); - const scene = this.getScene(); - const engine = scene.getEngine(); - // Fallbacks - const fallbacks = new EffectFallbacks(); - let fallbackRank = 0; - if (defines.USESPHERICALINVERTEX) { - fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX"); - } - if (defines.FOG) { - fallbacks.addFallback(fallbackRank, "FOG"); - } - if (defines.SPECULARAA) { - fallbacks.addFallback(fallbackRank, "SPECULARAA"); - } - if (defines.POINTSIZE) { - fallbacks.addFallback(fallbackRank, "POINTSIZE"); - } - if (defines.LOGARITHMICDEPTH) { - fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH"); - } - if (defines.PARALLAX) { - fallbacks.addFallback(fallbackRank, "PARALLAX"); - } - if (defines.PARALLAXOCCLUSION) { - fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION"); - } - if (defines.ENVIRONMENTBRDF) { - fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF"); - } - if (defines.TANGENT) { - fallbacks.addFallback(fallbackRank++, "TANGENT"); - } - if (defines.BUMP) { - fallbacks.addFallback(fallbackRank++, "BUMP"); - } - fallbackRank = MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++); - if (defines.SPECULARTERM) { - fallbacks.addFallback(fallbackRank++, "SPECULARTERM"); - } - if (defines.USESPHERICALFROMREFLECTIONMAP) { - fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP"); - } - if (defines.USEIRRADIANCEMAP) { - fallbacks.addFallback(fallbackRank++, "USEIRRADIANCEMAP"); - } - if (defines.LIGHTMAP) { - fallbacks.addFallback(fallbackRank++, "LIGHTMAP"); - } - if (defines.NORMAL) { - fallbacks.addFallback(fallbackRank++, "NORMAL"); - } - if (defines.AMBIENT) { - fallbacks.addFallback(fallbackRank++, "AMBIENT"); - } - if (defines.EMISSIVE) { - fallbacks.addFallback(fallbackRank++, "EMISSIVE"); - } - if (defines.VERTEXCOLOR) { - fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR"); - } - if (defines.MORPHTARGETS) { - fallbacks.addFallback(fallbackRank++, "MORPHTARGETS"); - } - if (defines.MULTIVIEW) { - fallbacks.addFallback(0, "MULTIVIEW"); - } - //Attributes - const attribs = [buffer_VertexBuffer.PositionKind]; - if (defines.NORMAL) { - attribs.push(buffer_VertexBuffer.NormalKind); - } - if (defines.TANGENT) { - attribs.push(buffer_VertexBuffer.TangentKind); - } - for (let i = 1; i <= 6; ++i) { - if (defines["UV" + i]) { - attribs.push(`uv${i === 1 ? "" : i}`); - } - } - if (defines.VERTEXCOLOR) { - attribs.push(buffer_VertexBuffer.ColorKind); - } - if (defines.INSTANCESCOLOR) { - attribs.push(buffer_VertexBuffer.ColorInstanceKind); - } - MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks); - MaterialHelper.PrepareAttributesForInstances(attribs, defines); - MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines); - MaterialHelper.PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines); - let shaderName = "pbr"; - const uniforms = [ - "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", - ]; - const samplers = [ - "albedoSampler", - "reflectivitySampler", - "ambientSampler", - "emissiveSampler", - "bumpSampler", - "lightmapSampler", - "opacitySampler", - "reflectionSampler", - "reflectionSamplerLow", - "reflectionSamplerHigh", - "irradianceSampler", - "microSurfaceSampler", - "environmentBrdfSampler", - "boneSampler", - "metallicReflectanceSampler", - "reflectanceSampler", - "morphTargets", - "oitDepthSampler", - "oitFrontColorSampler", - ]; - const uniformBuffers = ["Material", "Scene", "Mesh"]; - const indexParameters = { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }; - this._eventInfo.fallbacks = fallbacks; - this._eventInfo.fallbackRank = fallbackRank; - this._eventInfo.defines = defines; - this._eventInfo.uniforms = uniforms; - this._eventInfo.attributes = attribs; - this._eventInfo.samplers = samplers; - this._eventInfo.uniformBuffersNames = uniformBuffers; - this._eventInfo.customCode = undefined; - this._eventInfo.mesh = mesh; - this._eventInfo.indexParameters = indexParameters; - this._callbackPluginEventGeneric(materialPluginEvent_MaterialPluginEvent.PrepareEffect, this._eventInfo); - PrePassConfiguration.AddUniforms(uniforms); - PrePassConfiguration.AddSamplers(samplers); - addClipPlaneUniforms(uniforms); - if (ImageProcessingConfiguration) { - ImageProcessingConfiguration.PrepareUniforms(uniforms, defines); - ImageProcessingConfiguration.PrepareSamplers(samplers, defines); - } - MaterialHelper.PrepareUniformsAndSamplersList({ - uniformsNames: uniforms, - uniformBuffersNames: uniformBuffers, - samplers: samplers, - defines: defines, - maxSimultaneousLights: this._maxSimultaneousLights, - }); - const csnrOptions = {}; - if (this.customShaderNameResolve) { - shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions); - } - const join = defines.toString(); - const effect = engine.createEffect(shaderName, { - attributes: attribs, - uniformsNames: uniforms, - uniformBuffersNames: uniformBuffers, - samplers: samplers, - defines: join, - fallbacks: fallbacks, - onCompiled: onCompiled, - onError: onError, - indexParameters, - processFinalCode: csnrOptions.processFinalCode, - processCodeAfterIncludes: this._eventInfo.customCode, - multiTarget: defines.PREPASS, - }, engine); - this._eventInfo.customCode = undefined; - return effect; - } - _prepareDefines(mesh, defines, useInstances = null, useClipPlane = null, useThinInstances = false) { - var _a; - const scene = this.getScene(); - const engine = scene.getEngine(); - // Lights - MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting); - defines._needNormals = true; - // Multiview - MaterialHelper.PrepareDefinesForMultiview(scene, defines); - // PrePass - const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency; - MaterialHelper.PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit); - // Order independant transparency - MaterialHelper.PrepareDefinesForOIT(scene, defines, oit); - // Textures - defines.METALLICWORKFLOW = this.isMetallicWorkflow(); - if (defines._areTexturesDirty) { - defines._needUVs = false; - for (let i = 1; i <= 6; ++i) { - defines["MAINUV" + i] = false; - } - if (scene.texturesEnabled) { - defines.ALBEDODIRECTUV = 0; - defines.AMBIENTDIRECTUV = 0; - defines.OPACITYDIRECTUV = 0; - defines.EMISSIVEDIRECTUV = 0; - defines.REFLECTIVITYDIRECTUV = 0; - defines.MICROSURFACEMAPDIRECTUV = 0; - defines.METALLIC_REFLECTANCEDIRECTUV = 0; - defines.REFLECTANCEDIRECTUV = 0; - defines.BUMPDIRECTUV = 0; - defines.LIGHTMAPDIRECTUV = 0; - if (engine.getCaps().textureLOD) { - defines.LODBASEDMICROSFURACE = true; - } - if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO"); - defines.GAMMAALBEDO = this._albedoTexture.gammaSpace; - } - else { - defines.ALBEDO = false; - } - if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT"); - defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale; - } - else { - defines.AMBIENT = false; - } - if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY"); - defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB; - } - else { - defines.OPACITY = false; - } - const reflectionTexture = this._getReflectionTexture(); - if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { - defines.REFLECTION = true; - defines.GAMMAREFLECTION = reflectionTexture.gammaSpace; - defines.RGBDREFLECTION = reflectionTexture.isRGBD; - defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha; - defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD; - if (this.realTimeFiltering && this.realTimeFilteringQuality > 0) { - defines.NUM_SAMPLES = "" + this.realTimeFilteringQuality; - if (engine._features.needTypeSuffixInShaderConstants) { - defines.NUM_SAMPLES = defines.NUM_SAMPLES + "u"; - } - defines.REALTIME_FILTERING = true; - } - else { - defines.REALTIME_FILTERING = false; - } - defines.INVERTCUBICMAP = reflectionTexture.coordinatesMode === texture_Texture.INVCUBIC_MODE; - defines.REFLECTIONMAP_3D = reflectionTexture.isCube; - defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ; - defines.REFLECTIONMAP_CUBIC = false; - defines.REFLECTIONMAP_EXPLICIT = false; - defines.REFLECTIONMAP_PLANAR = false; - defines.REFLECTIONMAP_PROJECTION = false; - defines.REFLECTIONMAP_SKYBOX = false; - defines.REFLECTIONMAP_SPHERICAL = false; - defines.REFLECTIONMAP_EQUIRECTANGULAR = false; - defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; - defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; - switch (reflectionTexture.coordinatesMode) { - case texture_Texture.EXPLICIT_MODE: - defines.REFLECTIONMAP_EXPLICIT = true; - break; - case texture_Texture.PLANAR_MODE: - defines.REFLECTIONMAP_PLANAR = true; - break; - case texture_Texture.PROJECTION_MODE: - defines.REFLECTIONMAP_PROJECTION = true; - break; - case texture_Texture.SKYBOX_MODE: - defines.REFLECTIONMAP_SKYBOX = true; - break; - case texture_Texture.SPHERICAL_MODE: - defines.REFLECTIONMAP_SPHERICAL = true; - break; - case texture_Texture.EQUIRECTANGULAR_MODE: - defines.REFLECTIONMAP_EQUIRECTANGULAR = true; - break; - case texture_Texture.FIXED_EQUIRECTANGULAR_MODE: - defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true; - break; - case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE: - defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true; - break; - case texture_Texture.CUBIC_MODE: - case texture_Texture.INVCUBIC_MODE: - default: - defines.REFLECTIONMAP_CUBIC = true; - defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false; - break; - } - if (reflectionTexture.coordinatesMode !== texture_Texture.SKYBOX_MODE) { - if (reflectionTexture.irradianceTexture) { - defines.USEIRRADIANCEMAP = true; - defines.USESPHERICALFROMREFLECTIONMAP = false; - } - // Assume using spherical polynomial if the reflection texture is a cube map - else if (reflectionTexture.isCube) { - defines.USESPHERICALFROMREFLECTIONMAP = true; - defines.USEIRRADIANCEMAP = false; - if (this._forceIrradianceInFragment || this.realTimeFiltering || engine.getCaps().maxVaryingVectors <= 8) { - defines.USESPHERICALINVERTEX = false; - } - else { - defines.USESPHERICALINVERTEX = true; - } - } - } - } - else { - defines.REFLECTION = false; - defines.REFLECTIONMAP_3D = false; - defines.REFLECTIONMAP_SPHERICAL = false; - defines.REFLECTIONMAP_PLANAR = false; - defines.REFLECTIONMAP_CUBIC = false; - defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false; - defines.REFLECTIONMAP_PROJECTION = false; - defines.REFLECTIONMAP_SKYBOX = false; - defines.REFLECTIONMAP_EXPLICIT = false; - defines.REFLECTIONMAP_EQUIRECTANGULAR = false; - defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; - defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; - defines.INVERTCUBICMAP = false; - defines.USESPHERICALFROMREFLECTIONMAP = false; - defines.USEIRRADIANCEMAP = false; - defines.USESPHERICALINVERTEX = false; - defines.REFLECTIONMAP_OPPOSITEZ = false; - defines.LODINREFLECTIONALPHA = false; - defines.GAMMAREFLECTION = false; - defines.RGBDREFLECTION = false; - defines.LINEARSPECULARREFLECTION = false; - } - if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP"); - defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap; - defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace; - defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD; - } - else { - defines.LIGHTMAP = false; - } - if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) { - MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE"); - defines.GAMMAEMISSIVE = this._emissiveTexture.gammaSpace; - } - else { - defines.EMISSIVE = false; - } - if (MaterialFlags.SpecularTextureEnabled) { - if (this._metallicTexture) { - MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY"); - defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha; - defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen; - defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue; - defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed; - defines.REFLECTIVITY_GAMMA = false; - } - else if (this._reflectivityTexture) { - MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY"); - defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha; - defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap; - defines.REFLECTIVITY_GAMMA = this._reflectivityTexture.gammaSpace; - } - else { - defines.REFLECTIVITY = false; - } - if (this._metallicReflectanceTexture || this._reflectanceTexture) { - const identicalTextures = this._metallicReflectanceTexture !== null && - this._metallicReflectanceTexture._texture === ((_a = this._reflectanceTexture) === null || _a === void 0 ? void 0 : _a._texture) && - this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture); - defines.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = this._useOnlyMetallicFromMetallicReflectanceTexture && !identicalTextures; - if (this._metallicReflectanceTexture) { - MaterialHelper.PrepareDefinesForMergedUV(this._metallicReflectanceTexture, defines, "METALLIC_REFLECTANCE"); - defines.METALLIC_REFLECTANCE_GAMMA = this._metallicReflectanceTexture.gammaSpace; - } - else { - defines.METALLIC_REFLECTANCE = false; - } - if (this._reflectanceTexture && - !identicalTextures && - (!this._metallicReflectanceTexture || (this._metallicReflectanceTexture && this._useOnlyMetallicFromMetallicReflectanceTexture))) { - MaterialHelper.PrepareDefinesForMergedUV(this._reflectanceTexture, defines, "REFLECTANCE"); - defines.REFLECTANCE_GAMMA = this._reflectanceTexture.gammaSpace; - } - else { - defines.REFLECTANCE = false; - } - } - else { - defines.METALLIC_REFLECTANCE = false; - defines.REFLECTANCE = false; - } - if (this._microSurfaceTexture) { - MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP"); - } - else { - defines.MICROSURFACEMAP = false; - } - } - else { - defines.REFLECTIVITY = false; - defines.MICROSURFACEMAP = false; - } - if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) { - MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP"); - if (this._useParallax && this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) { - defines.PARALLAX = true; - defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion; - } - else { - defines.PARALLAX = false; - } - defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap; - } - else { - defines.BUMP = false; - defines.PARALLAX = false; - defines.PARALLAXOCCLUSION = false; - defines.OBJECTSPACE_NORMALMAP = false; - } - if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) { - defines.ENVIRONMENTBRDF = true; - defines.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD; - } - else { - defines.ENVIRONMENTBRDF = false; - defines.ENVIRONMENTBRDF_RGBD = false; - } - if (this._shouldUseAlphaFromAlbedoTexture()) { - defines.ALPHAFROMALBEDO = true; - } - else { - defines.ALPHAFROMALBEDO = false; - } - } - defines.SPECULAROVERALPHA = this._useSpecularOverAlpha; - if (this._lightFalloff === pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD) { - defines.USEPHYSICALLIGHTFALLOFF = false; - defines.USEGLTFLIGHTFALLOFF = false; - } - else if (this._lightFalloff === pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF) { - defines.USEPHYSICALLIGHTFALLOFF = false; - defines.USEGLTFLIGHTFALLOFF = true; - } - else { - defines.USEPHYSICALLIGHTFALLOFF = true; - defines.USEGLTFLIGHTFALLOFF = false; - } - defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha; - if (!this.backFaceCulling && this._twoSidedLighting) { - defines.TWOSIDEDLIGHTING = true; - } - else { - defines.TWOSIDEDLIGHTING = false; - } - defines.SPECULARAA = engine.getCaps().standardDerivatives && this._enableSpecularAntiAliasing; - } - if (defines._areTexturesDirty || defines._areMiscDirty) { - defines.ALPHATESTVALUE = `${this._alphaCutOff}${this._alphaCutOff % 1 === 0 ? "." : ""}`; - defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8; - defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh); - defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel; - defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel; - } - if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { - this._imageProcessingConfiguration.prepareDefines(defines); - } - defines.FORCENORMALFORWARD = this._forceNormalForward; - defines.RADIANCEOCCLUSION = this._useRadianceOcclusion; - defines.HORIZONOCCLUSION = this._useHorizonOcclusion; - // Misc. - if (defines._areMiscDirty) { - MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines, this._applyDecalMapAfterDetailMap); - defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)); - defines.DEBUGMODE = this._debugMode; - } - // Values that need to be evaluated on every frame - MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances ? true : false, useClipPlane, useThinInstances); - // External config - this._eventInfo.defines = defines; - this._eventInfo.mesh = mesh; - this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo); - // Attribs - MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE); - // External config - this._callbackPluginEventPrepareDefines(this._eventInfo); - } - /** - * Force shader compilation - * @param mesh - * @param onCompiled - * @param options - */ - forceCompilation(mesh, onCompiled, options) { - const localOptions = Object.assign({ clipPlane: false, useInstances: false }, options); - if (!this._uniformBufferLayoutBuilt) { - this.buildUniformLayout(); - } - this._callbackPluginEventGeneric(materialPluginEvent_MaterialPluginEvent.GetDefineNames, this._eventInfo); - const defines = new PBRMaterialDefines(this._eventInfo.defineNames); - const effect = this._prepareEffect(mesh, defines, undefined, undefined, localOptions.useInstances, localOptions.clipPlane, mesh.hasThinInstances); - if (this._onEffectCreatedObservable) { - pbrBaseMaterial_onCreatedEffectParameters.effect = effect; - pbrBaseMaterial_onCreatedEffectParameters.subMesh = null; - this._onEffectCreatedObservable.notifyObservers(pbrBaseMaterial_onCreatedEffectParameters); - } - if (effect.isReady()) { - if (onCompiled) { - onCompiled(this); - } - } - else { - effect.onCompileObservable.add(() => { - if (onCompiled) { - onCompiled(this); - } - }); - } - } - /** - * Initializes the uniform buffer layout for the shader. - */ - buildUniformLayout() { - // Order is important ! - const ubo = this._uniformBuffer; - ubo.addUniform("vAlbedoInfos", 2); - ubo.addUniform("vAmbientInfos", 4); - ubo.addUniform("vOpacityInfos", 2); - ubo.addUniform("vEmissiveInfos", 2); - ubo.addUniform("vLightmapInfos", 2); - ubo.addUniform("vReflectivityInfos", 3); - ubo.addUniform("vMicroSurfaceSamplerInfos", 2); - ubo.addUniform("vReflectionInfos", 2); - ubo.addUniform("vReflectionFilteringInfo", 2); - ubo.addUniform("vReflectionPosition", 3); - ubo.addUniform("vReflectionSize", 3); - ubo.addUniform("vBumpInfos", 3); - ubo.addUniform("albedoMatrix", 16); - ubo.addUniform("ambientMatrix", 16); - ubo.addUniform("opacityMatrix", 16); - ubo.addUniform("emissiveMatrix", 16); - ubo.addUniform("lightmapMatrix", 16); - ubo.addUniform("reflectivityMatrix", 16); - ubo.addUniform("microSurfaceSamplerMatrix", 16); - ubo.addUniform("bumpMatrix", 16); - ubo.addUniform("vTangentSpaceParams", 2); - ubo.addUniform("reflectionMatrix", 16); - ubo.addUniform("vReflectionColor", 3); - ubo.addUniform("vAlbedoColor", 4); - ubo.addUniform("vLightingIntensity", 4); - ubo.addUniform("vReflectionMicrosurfaceInfos", 3); - ubo.addUniform("pointSize", 1); - ubo.addUniform("vReflectivityColor", 4); - ubo.addUniform("vEmissiveColor", 3); - ubo.addUniform("vAmbientColor", 3); - ubo.addUniform("vDebugMode", 2); - ubo.addUniform("vMetallicReflectanceFactors", 4); - ubo.addUniform("vMetallicReflectanceInfos", 2); - ubo.addUniform("metallicReflectanceMatrix", 16); - ubo.addUniform("vReflectanceInfos", 2); - ubo.addUniform("reflectanceMatrix", 16); - ubo.addUniform("vSphericalL00", 3); - ubo.addUniform("vSphericalL1_1", 3); - ubo.addUniform("vSphericalL10", 3); - ubo.addUniform("vSphericalL11", 3); - ubo.addUniform("vSphericalL2_2", 3); - ubo.addUniform("vSphericalL2_1", 3); - ubo.addUniform("vSphericalL20", 3); - ubo.addUniform("vSphericalL21", 3); - ubo.addUniform("vSphericalL22", 3); - ubo.addUniform("vSphericalX", 3); - ubo.addUniform("vSphericalY", 3); - ubo.addUniform("vSphericalZ", 3); - ubo.addUniform("vSphericalXX_ZZ", 3); - ubo.addUniform("vSphericalYY_ZZ", 3); - ubo.addUniform("vSphericalZZ", 3); - ubo.addUniform("vSphericalXY", 3); - ubo.addUniform("vSphericalYZ", 3); - ubo.addUniform("vSphericalZX", 3); - super.buildUniformLayout(); - } - /** - * Binds the submesh data. - * @param world - The world matrix. - * @param mesh - The BJS mesh. - * @param subMesh - A submesh of the BJS mesh. - */ - bindForSubMesh(world, mesh, subMesh) { - var _a, _b, _c, _d; - const scene = this.getScene(); - const defines = subMesh.materialDefines; - if (!defines) { - return; - } - const effect = subMesh.effect; - if (!effect) { - return; - } - this._activeEffect = effect; - // Matrices Mesh. - mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); - mesh.transferToEffect(world); - const engine = scene.getEngine(); - // Binding unconditionally - this._uniformBuffer.bindToEffect(effect, "Material"); - this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen); - this._eventInfo.subMesh = subMesh; - this._callbackPluginEventHardBindForSubMesh(this._eventInfo); - // Normal Matrix - if (defines.OBJECTSPACE_NORMALMAP) { - world.toNormalMatrix(this._normalMatrix); - this.bindOnlyNormalMatrix(this._normalMatrix); - } - const mustRebind = effect._forceRebindOnNextCall || this._mustRebind(scene, effect, mesh.visibility); - // Bones - MaterialHelper.BindBonesParameters(mesh, this._activeEffect, this.prePassConfiguration); - let reflectionTexture = null; - const ubo = this._uniformBuffer; - if (mustRebind) { - this.bindViewProjection(effect); - reflectionTexture = this._getReflectionTexture(); - if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || effect._forceRebindOnNextCall) { - // Texture uniforms - if (scene.texturesEnabled) { - if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) { - ubo.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level); - MaterialHelper.BindTextureMatrix(this._albedoTexture, ubo, "albedo"); - } - if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) { - ubo.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights); - MaterialHelper.BindTextureMatrix(this._ambientTexture, ubo, "ambient"); - } - if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) { - ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level); - MaterialHelper.BindTextureMatrix(this._opacityTexture, ubo, "opacity"); - } - if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { - ubo.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix()); - ubo.updateFloat2("vReflectionInfos", reflectionTexture.level, 0); - if (reflectionTexture.boundingBoxSize) { - const cubeTexture = reflectionTexture; - ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition); - ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize); - } - if (this.realTimeFiltering) { - const width = reflectionTexture.getSize().width; - ubo.updateFloat2("vReflectionFilteringInfo", width, math_scalar_Scalar.Log2(width)); - } - if (!defines.USEIRRADIANCEMAP) { - const polynomials = reflectionTexture.sphericalPolynomial; - if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) { - if (defines.SPHERICAL_HARMONICS) { - const preScaledHarmonics = polynomials.preScaledHarmonics; - ubo.updateVector3("vSphericalL00", preScaledHarmonics.l00); - ubo.updateVector3("vSphericalL1_1", preScaledHarmonics.l1_1); - ubo.updateVector3("vSphericalL10", preScaledHarmonics.l10); - ubo.updateVector3("vSphericalL11", preScaledHarmonics.l11); - ubo.updateVector3("vSphericalL2_2", preScaledHarmonics.l2_2); - ubo.updateVector3("vSphericalL2_1", preScaledHarmonics.l2_1); - ubo.updateVector3("vSphericalL20", preScaledHarmonics.l20); - ubo.updateVector3("vSphericalL21", preScaledHarmonics.l21); - ubo.updateVector3("vSphericalL22", preScaledHarmonics.l22); - } - else { - ubo.updateFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z); - ubo.updateFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z); - ubo.updateFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z); - ubo.updateFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z); - ubo.updateFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z); - ubo.updateFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z); - ubo.updateFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z); - ubo.updateFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z); - ubo.updateFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z); - } - } - } - ubo.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); - } - if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) { - ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level); - MaterialHelper.BindTextureMatrix(this._emissiveTexture, ubo, "emissive"); - } - if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) { - ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level); - MaterialHelper.BindTextureMatrix(this._lightmapTexture, ubo, "lightmap"); - } - if (MaterialFlags.SpecularTextureEnabled) { - if (this._metallicTexture) { - ubo.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength); - MaterialHelper.BindTextureMatrix(this._metallicTexture, ubo, "reflectivity"); - } - else if (this._reflectivityTexture) { - ubo.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0); - MaterialHelper.BindTextureMatrix(this._reflectivityTexture, ubo, "reflectivity"); - } - if (this._metallicReflectanceTexture) { - ubo.updateFloat2("vMetallicReflectanceInfos", this._metallicReflectanceTexture.coordinatesIndex, this._metallicReflectanceTexture.level); - MaterialHelper.BindTextureMatrix(this._metallicReflectanceTexture, ubo, "metallicReflectance"); - } - if (this._reflectanceTexture && defines.REFLECTANCE) { - ubo.updateFloat2("vReflectanceInfos", this._reflectanceTexture.coordinatesIndex, this._reflectanceTexture.level); - MaterialHelper.BindTextureMatrix(this._reflectanceTexture, ubo, "reflectance"); - } - if (this._microSurfaceTexture) { - ubo.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level); - MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, ubo, "microSurfaceSampler"); - } - } - if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) { - ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias); - MaterialHelper.BindTextureMatrix(this._bumpTexture, ubo, "bump"); - if (scene._mirroredCameraPosition) { - ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0); - } - else { - ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0); - } - } - } - // Point size - if (this.pointsCloud) { - ubo.updateFloat("pointSize", this.pointSize); - } - // Colors - if (defines.METALLICWORKFLOW) { - TmpColors.Color3[0].r = this._metallic === undefined || this._metallic === null ? 1 : this._metallic; - TmpColors.Color3[0].g = this._roughness === undefined || this._roughness === null ? 1 : this._roughness; - ubo.updateColor4("vReflectivityColor", TmpColors.Color3[0], 1); - const ior = (_b = (_a = this.subSurface) === null || _a === void 0 ? void 0 : _a._indexOfRefraction) !== null && _b !== void 0 ? _b : 1.5; - const outsideIOR = 1; // consider air as clear coat and other layers would remap in the shader. - // We are here deriving our default reflectance from a common value for none metallic surface. - // Based of the schlick fresnel approximation model - // for dielectrics. - const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2); - // Tweak the default F0 and F90 based on our given setup - this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]); - const metallicF90 = this._metallicF0Factor; - ubo.updateColor4("vMetallicReflectanceFactors", TmpColors.Color3[0], metallicF90); - } - else { - ubo.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface); - } - ubo.updateColor3("vEmissiveColor", MaterialFlags.EmissiveTextureEnabled ? this._emissiveColor : math_color_Color3.BlackReadOnly); - ubo.updateColor3("vReflectionColor", this._reflectionColor); - if (!defines.SS_REFRACTION && ((_c = this.subSurface) === null || _c === void 0 ? void 0 : _c._linkRefractionWithTransparency)) { - ubo.updateColor4("vAlbedoColor", this._albedoColor, 1); - } - else { - ubo.updateColor4("vAlbedoColor", this._albedoColor, this.alpha); - } - // Misc - this._lightingInfos.x = this._directIntensity; - this._lightingInfos.y = this._emissiveIntensity; - this._lightingInfos.z = this._environmentIntensity * scene.environmentIntensity; - this._lightingInfos.w = this._specularIntensity; - ubo.updateVector4("vLightingIntensity", this._lightingInfos); - // Colors - scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor); - ubo.updateColor3("vAmbientColor", this._globalAmbientColor); - ubo.updateFloat2("vDebugMode", this.debugLimit, this.debugFactor); - } - // Textures - if (scene.texturesEnabled) { - if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) { - ubo.setTexture("albedoSampler", this._albedoTexture); - } - if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) { - ubo.setTexture("ambientSampler", this._ambientTexture); - } - if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) { - ubo.setTexture("opacitySampler", this._opacityTexture); - } - if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { - if (defines.LODBASEDMICROSFURACE) { - ubo.setTexture("reflectionSampler", reflectionTexture); - } - else { - ubo.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture); - ubo.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture); - ubo.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture); - } - if (defines.USEIRRADIANCEMAP) { - ubo.setTexture("irradianceSampler", reflectionTexture.irradianceTexture); - } - } - if (defines.ENVIRONMENTBRDF) { - ubo.setTexture("environmentBrdfSampler", this._environmentBRDFTexture); - } - if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) { - ubo.setTexture("emissiveSampler", this._emissiveTexture); - } - if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) { - ubo.setTexture("lightmapSampler", this._lightmapTexture); - } - if (MaterialFlags.SpecularTextureEnabled) { - if (this._metallicTexture) { - ubo.setTexture("reflectivitySampler", this._metallicTexture); - } - else if (this._reflectivityTexture) { - ubo.setTexture("reflectivitySampler", this._reflectivityTexture); - } - if (this._metallicReflectanceTexture) { - ubo.setTexture("metallicReflectanceSampler", this._metallicReflectanceTexture); - } - if (this._reflectanceTexture && defines.REFLECTANCE) { - ubo.setTexture("reflectanceSampler", this._reflectanceTexture); - } - if (this._microSurfaceTexture) { - ubo.setTexture("microSurfaceSampler", this._microSurfaceTexture); - } - } - if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) { - ubo.setTexture("bumpSampler", this._bumpTexture); - } - } - // OIT with depth peeling - if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) { - this.getScene().depthPeelingRenderer.bind(effect); - } - this._eventInfo.subMesh = subMesh; - this._callbackPluginEventBindForSubMesh(this._eventInfo); - // Clip plane - bindClipPlane(this._activeEffect, this, scene); - this.bindEyePosition(effect); - } - else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) { - this._needToBindSceneUbo = true; - } - if (mustRebind || !this.isFrozen) { - // Lights - if (scene.lightsEnabled && !this._disableLighting) { - MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights); - } - // View - if ((scene.fogEnabled && mesh.applyFog && scene.fogMode !== scene_Scene.FOGMODE_NONE) || reflectionTexture || mesh.receiveShadows || defines.PREPASS) { - this.bindView(effect); - } - // Fog - MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true); - // Morph targets - if (defines.NUM_MORPH_INFLUENCERS) { - MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect); - } - if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) { - (_d = mesh.bakedVertexAnimationManager) === null || _d === void 0 ? void 0 : _d.bind(effect, defines.INSTANCES); - } - // image processing - this._imageProcessingConfiguration.bind(this._activeEffect); - // Log. depth - MaterialHelper.BindLogDepth(defines, this._activeEffect, scene); - } - this._afterBind(mesh, this._activeEffect); - ubo.update(); - } - /** - * Returns the animatable textures. - * If material have animatable metallic texture, then reflectivity texture will not be returned, even if it has animations. - * @returns - Array of animatable textures. - */ - getAnimatables() { - const results = super.getAnimatables(); - if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) { - results.push(this._albedoTexture); - } - if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) { - results.push(this._ambientTexture); - } - if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) { - results.push(this._opacityTexture); - } - if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) { - results.push(this._reflectionTexture); - } - if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) { - results.push(this._emissiveTexture); - } - if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) { - results.push(this._metallicTexture); - } - else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) { - results.push(this._reflectivityTexture); - } - if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { - results.push(this._bumpTexture); - } - if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) { - results.push(this._lightmapTexture); - } - if (this._metallicReflectanceTexture && this._metallicReflectanceTexture.animations && this._metallicReflectanceTexture.animations.length > 0) { - results.push(this._metallicReflectanceTexture); - } - if (this._reflectanceTexture && this._reflectanceTexture.animations && this._reflectanceTexture.animations.length > 0) { - results.push(this._reflectanceTexture); - } - if (this._microSurfaceTexture && this._microSurfaceTexture.animations && this._microSurfaceTexture.animations.length > 0) { - results.push(this._microSurfaceTexture); - } - return results; - } - /** - * Returns the texture used for reflections. - * @returns - Reflection texture if present. Otherwise, returns the environment texture. - */ - _getReflectionTexture() { - if (this._reflectionTexture) { - return this._reflectionTexture; - } - return this.getScene().environmentTexture; - } - /** - * Returns an array of the actively used textures. - * @returns - Array of BaseTextures - */ - getActiveTextures() { - const activeTextures = super.getActiveTextures(); - if (this._albedoTexture) { - activeTextures.push(this._albedoTexture); - } - if (this._ambientTexture) { - activeTextures.push(this._ambientTexture); - } - if (this._opacityTexture) { - activeTextures.push(this._opacityTexture); - } - if (this._reflectionTexture) { - activeTextures.push(this._reflectionTexture); - } - if (this._emissiveTexture) { - activeTextures.push(this._emissiveTexture); - } - if (this._reflectivityTexture) { - activeTextures.push(this._reflectivityTexture); - } - if (this._metallicTexture) { - activeTextures.push(this._metallicTexture); - } - if (this._metallicReflectanceTexture) { - activeTextures.push(this._metallicReflectanceTexture); - } - if (this._reflectanceTexture) { - activeTextures.push(this._reflectanceTexture); - } - if (this._microSurfaceTexture) { - activeTextures.push(this._microSurfaceTexture); - } - if (this._bumpTexture) { - activeTextures.push(this._bumpTexture); - } - if (this._lightmapTexture) { - activeTextures.push(this._lightmapTexture); - } - return activeTextures; - } - /** - * Checks to see if a texture is used in the material. - * @param texture - Base texture to use. - * @returns - Boolean specifying if a texture is used in the material. - */ - hasTexture(texture) { - if (super.hasTexture(texture)) { - return true; - } - if (this._albedoTexture === texture) { - return true; - } - if (this._ambientTexture === texture) { - return true; - } - if (this._opacityTexture === texture) { - return true; - } - if (this._reflectionTexture === texture) { - return true; - } - if (this._emissiveTexture === texture) { - return true; - } - if (this._reflectivityTexture === texture) { - return true; - } - if (this._metallicTexture === texture) { - return true; - } - if (this._metallicReflectanceTexture === texture) { - return true; - } - if (this._reflectanceTexture === texture) { - return true; - } - if (this._microSurfaceTexture === texture) { - return true; - } - if (this._bumpTexture === texture) { - return true; - } - if (this._lightmapTexture === texture) { - return true; - } - return false; - } - /** - * Sets the required values to the prepass renderer. - * It can't be sets when subsurface scattering of this material is disabled. - * When scene have ability to enable subsurface prepass effect, it will enable. - */ - setPrePassRenderer() { - var _a; - if (!((_a = this.subSurface) === null || _a === void 0 ? void 0 : _a.isScatteringEnabled)) { - return false; - } - const subSurfaceConfiguration = this.getScene().enableSubSurfaceForPrePass(); - if (subSurfaceConfiguration) { - subSurfaceConfiguration.enabled = true; - } - return true; - } - /** - * Disposes the resources of the material. - * @param forceDisposeEffect - Forces the disposal of effects. - * @param forceDisposeTextures - Forces the disposal of all textures. - */ - dispose(forceDisposeEffect, forceDisposeTextures) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; - if (forceDisposeTextures) { - if (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture) { - this._environmentBRDFTexture.dispose(); - } - (_a = this._albedoTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - (_b = this._ambientTexture) === null || _b === void 0 ? void 0 : _b.dispose(); - (_c = this._opacityTexture) === null || _c === void 0 ? void 0 : _c.dispose(); - (_d = this._reflectionTexture) === null || _d === void 0 ? void 0 : _d.dispose(); - (_e = this._emissiveTexture) === null || _e === void 0 ? void 0 : _e.dispose(); - (_f = this._metallicTexture) === null || _f === void 0 ? void 0 : _f.dispose(); - (_g = this._reflectivityTexture) === null || _g === void 0 ? void 0 : _g.dispose(); - (_h = this._bumpTexture) === null || _h === void 0 ? void 0 : _h.dispose(); - (_j = this._lightmapTexture) === null || _j === void 0 ? void 0 : _j.dispose(); - (_k = this._metallicReflectanceTexture) === null || _k === void 0 ? void 0 : _k.dispose(); - (_l = this._reflectanceTexture) === null || _l === void 0 ? void 0 : _l.dispose(); - (_m = this._microSurfaceTexture) === null || _m === void 0 ? void 0 : _m.dispose(); - } - this._renderTargets.dispose(); - if (this._imageProcessingConfiguration && this._imageProcessingObserver) { - this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); - } - super.dispose(forceDisposeEffect, forceDisposeTextures); - } -} -/** - * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use. - */ -pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE = material_Material.MATERIAL_OPAQUE; -/** - * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value. - */ -pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST = material_Material.MATERIAL_ALPHATEST; -/** - * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. - */ -pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHABLEND = material_Material.MATERIAL_ALPHABLEND; -/** - * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. - * They are also discarded below the alpha cutoff threshold to improve performances. - */ -pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND = material_Material.MATERIAL_ALPHATESTANDBLEND; -/** - * Defines the default value of how much AO map is occluding the analytical lights - * (point spot...). - */ -pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0; -/** - * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law. - */ -pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0; -/** - * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document - * to enhance interoperability with other engines. - */ -pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1; -/** - * PBRMaterialLightFalloff Standard: light is falling off like in the standard material - * to enhance interoperability with other materials. - */ -pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2; -__decorate([ - serializeAsImageProcessingConfiguration() -], pbrBaseMaterial_PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsMiscDirty") -], pbrBaseMaterial_PBRBaseMaterial.prototype, "debugMode", void 0); -__decorate([ - serialize() -], pbrBaseMaterial_PBRBaseMaterial.prototype, "useLogarithmicDepth", null); -//# sourceMappingURL=pbrBaseMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrMaterial.js - - - - - - - -/** - * The Physically based material of BJS. - * - * This offers the main features of a standard PBR material. - * For more information, please refer to the documentation : - * https://doc.babylonjs.com/features/featuresDeepDive/materials/using/introToPBR - */ -class pbrMaterial_PBRMaterial extends pbrBaseMaterial_PBRBaseMaterial { - /** - * Stores the refracted light information in a texture. - */ - get refractionTexture() { - return this.subSurface.refractionTexture; - } - set refractionTexture(value) { - this.subSurface.refractionTexture = value; - if (value) { - this.subSurface.isRefractionEnabled = true; - } - else if (!this.subSurface.linkRefractionWithTransparency) { - this.subSurface.isRefractionEnabled = false; - } - } - /** - * Index of refraction of the material base layer. - * https://en.wikipedia.org/wiki/List_of_refractive_indices - * - * This does not only impact refraction but also the Base F0 of Dielectric Materials. - * - * From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI)) - */ - get indexOfRefraction() { - return this.subSurface.indexOfRefraction; - } - set indexOfRefraction(value) { - this.subSurface.indexOfRefraction = value; - } - /** - * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. - */ - get invertRefractionY() { - return this.subSurface.invertRefractionY; - } - set invertRefractionY(value) { - this.subSurface.invertRefractionY = value; - } - /** - * This parameters will make the material used its opacity to control how much it is refracting against not. - * Materials half opaque for instance using refraction could benefit from this control. - */ - get linkRefractionWithTransparency() { - return this.subSurface.linkRefractionWithTransparency; - } - set linkRefractionWithTransparency(value) { - this.subSurface.linkRefractionWithTransparency = value; - if (value) { - this.subSurface.isRefractionEnabled = true; - } - } - /** - * BJS is using an hardcoded light falloff based on a manually sets up range. - * In PBR, one way to represents the falloff is to use the inverse squared root algorithm. - * This parameter can help you switch back to the BJS mode in order to create scenes using both materials. - */ - get usePhysicalLightFalloff() { - return this._lightFalloff === pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL; - } - /** - * BJS is using an hardcoded light falloff based on a manually sets up range. - * In PBR, one way to represents the falloff is to use the inverse squared root algorithm. - * This parameter can help you switch back to the BJS mode in order to create scenes using both materials. - */ - set usePhysicalLightFalloff(value) { - if (value !== this.usePhysicalLightFalloff) { - // Ensure the effect will be rebuilt. - this._markAllSubMeshesAsTexturesDirty(); - if (value) { - this._lightFalloff = pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL; - } - else { - this._lightFalloff = pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD; - } - } - } - /** - * In order to support the falloff compatibility with gltf, a special mode has been added - * to reproduce the gltf light falloff. - */ - get useGLTFLightFalloff() { - return this._lightFalloff === pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF; - } - /** - * In order to support the falloff compatibility with gltf, a special mode has been added - * to reproduce the gltf light falloff. - */ - set useGLTFLightFalloff(value) { - if (value !== this.useGLTFLightFalloff) { - // Ensure the effect will be rebuilt. - this._markAllSubMeshesAsTexturesDirty(); - if (value) { - this._lightFalloff = pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF; - } - else { - this._lightFalloff = pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD; - } - } - } - /** - * Gets the image processing configuration used either in this material. - */ - get imageProcessingConfiguration() { - return this._imageProcessingConfiguration; - } - /** - * Sets the Default image processing configuration used either in the this material. - * - * If sets to null, the scene one is in use. - */ - set imageProcessingConfiguration(value) { - this._attachImageProcessingConfiguration(value); - // Ensure the effect will be rebuilt. - this._markAllSubMeshesAsTexturesDirty(); - } - /** - * Gets whether the color curves effect is enabled. - */ - get cameraColorCurvesEnabled() { - return this.imageProcessingConfiguration.colorCurvesEnabled; - } - /** - * Sets whether the color curves effect is enabled. - */ - set cameraColorCurvesEnabled(value) { - this.imageProcessingConfiguration.colorCurvesEnabled = value; - } - /** - * Gets whether the color grading effect is enabled. - */ - get cameraColorGradingEnabled() { - return this.imageProcessingConfiguration.colorGradingEnabled; - } - /** - * Gets whether the color grading effect is enabled. - */ - set cameraColorGradingEnabled(value) { - this.imageProcessingConfiguration.colorGradingEnabled = value; - } - /** - * Gets whether tonemapping is enabled or not. - */ - get cameraToneMappingEnabled() { - return this._imageProcessingConfiguration.toneMappingEnabled; - } - /** - * Sets whether tonemapping is enabled or not - */ - set cameraToneMappingEnabled(value) { - this._imageProcessingConfiguration.toneMappingEnabled = value; - } - /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ - get cameraExposure() { - return this._imageProcessingConfiguration.exposure; - } - /** - * The camera exposure used on this material. - * This property is here and not in the camera to allow controlling exposure without full screen post process. - * This corresponds to a photographic exposure. - */ - set cameraExposure(value) { - this._imageProcessingConfiguration.exposure = value; - } - /** - * Gets The camera contrast used on this material. - */ - get cameraContrast() { - return this._imageProcessingConfiguration.contrast; - } - /** - * Sets The camera contrast used on this material. - */ - set cameraContrast(value) { - this._imageProcessingConfiguration.contrast = value; - } - /** - * Gets the Color Grading 2D Lookup Texture. - */ - get cameraColorGradingTexture() { - return this._imageProcessingConfiguration.colorGradingTexture; - } - /** - * Sets the Color Grading 2D Lookup Texture. - */ - set cameraColorGradingTexture(value) { - this._imageProcessingConfiguration.colorGradingTexture = value; - } - /** - * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * 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; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ - get cameraColorCurves() { - return this._imageProcessingConfiguration.colorCurves; - } - /** - * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT). - * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. - * 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; - * corresponding to low luminance, medium luminance, and high luminance areas respectively. - */ - set cameraColorCurves(value) { - this._imageProcessingConfiguration.colorCurves = value; - } - /** - * Instantiates a new PBRMaterial instance. - * - * @param name The material name - * @param scene The scene the material will be use in. - */ - constructor(name, scene) { - super(name, scene); - /** - * Intensity of the direct lights e.g. the four lights available in your scene. - * This impacts both the direct diffuse and specular highlights. - */ - this.directIntensity = 1.0; - /** - * Intensity of the emissive part of the material. - * This helps controlling the emissive effect without modifying the emissive color. - */ - this.emissiveIntensity = 1.0; - /** - * Intensity of the environment e.g. how much the environment will light the object - * either through harmonics for rough material or through the reflection for shiny ones. - */ - this.environmentIntensity = 1.0; - /** - * This is a special control allowing the reduction of the specular highlights coming from the - * four lights of the scene. Those highlights may not be needed in full environment lighting. - */ - this.specularIntensity = 1.0; - /** - * Debug Control allowing disabling the bump map on this material. - */ - this.disableBumpMap = false; - /** - * AKA Occlusion Texture Intensity in other nomenclature. - */ - this.ambientTextureStrength = 1.0; - /** - * Defines how much the AO map is occluding the analytical lights (point spot...). - * 1 means it completely occludes it - * 0 mean it has no impact - */ - this.ambientTextureImpactOnAnalyticalLights = pbrMaterial_PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS; - /** - * In metallic workflow, specifies an F0 factor to help configuring the material F0. - * By default the indexOfrefraction is used to compute F0; - * - * This is used as a factor against the default reflectance at normal incidence to tweak it. - * - * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor; - * F90 = metallicReflectanceColor; - */ - this.metallicF0Factor = 1; - /** - * In metallic workflow, specifies an F0 color. - * By default the F90 is always 1; - * - * Please note that this factor is also used as a factor against the default reflectance at normal incidence. - * - * F0 = defaultF0_from_IOR * metallicF0Factor * metallicReflectanceColor - * F90 = metallicF0Factor; - */ - this.metallicReflectanceColor = math_color_Color3.White(); - /** - * Specifies that only the A channel from metallicReflectanceTexture should be used. - * If false, both RGB and A channels will be used - */ - this.useOnlyMetallicFromMetallicReflectanceTexture = false; - /** - * The color of a material in ambient lighting. - */ - this.ambientColor = new math_color_Color3(0, 0, 0); - /** - * AKA Diffuse Color in other nomenclature. - */ - this.albedoColor = new math_color_Color3(1, 1, 1); - /** - * AKA Specular Color in other nomenclature. - */ - this.reflectivityColor = new math_color_Color3(1, 1, 1); - /** - * The color reflected from the material. - */ - this.reflectionColor = new math_color_Color3(1.0, 1.0, 1.0); - /** - * The color emitted from the material. - */ - this.emissiveColor = new math_color_Color3(0, 0, 0); - /** - * AKA Glossiness in other nomenclature. - */ - this.microSurface = 1.0; - /** - * If true, the light map contains occlusion information instead of lighting info. - */ - this.useLightmapAsShadowmap = false; - /** - * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending. - */ - this.useAlphaFromAlbedoTexture = false; - /** - * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations. - */ - this.forceAlphaTest = false; - /** - * Defines the alpha limits in alpha test mode. - */ - this.alphaCutOff = 0.4; - /** - * Specifies that the material will keep the specular highlights over a transparent surface (only the most luminous ones). - * A car glass is a good example of that. When sun reflects on it you can not see what is behind. - */ - this.useSpecularOverAlpha = true; - /** - * Specifies if the reflectivity texture contains the glossiness information in its alpha channel. - */ - this.useMicroSurfaceFromReflectivityMapAlpha = false; - /** - * Specifies if the metallic texture contains the roughness information in its alpha channel. - */ - this.useRoughnessFromMetallicTextureAlpha = true; - /** - * Specifies if the metallic texture contains the roughness information in its green channel. - */ - this.useRoughnessFromMetallicTextureGreen = false; - /** - * Specifies if the metallic texture contains the metallness information in its blue channel. - */ - this.useMetallnessFromMetallicTextureBlue = false; - /** - * Specifies if the metallic texture contains the ambient occlusion information in its red channel. - */ - this.useAmbientOcclusionFromMetallicTextureRed = false; - /** - * Specifies if the ambient texture contains the ambient occlusion information in its red channel only. - */ - this.useAmbientInGrayScale = false; - /** - * In case the reflectivity map does not contain the microsurface information in its alpha channel, - * The material will try to infer what glossiness each pixel should be. - */ - this.useAutoMicroSurfaceFromReflectivityMap = false; - /** - * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones). - * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind. - */ - this.useRadianceOverAlpha = true; - /** - * Allows using an object space normal map (instead of tangent space). - */ - this.useObjectSpaceNormalMap = false; - /** - * Allows using the bump map in parallax mode. - */ - this.useParallax = false; - /** - * Allows using the bump map in parallax occlusion mode. - */ - this.useParallaxOcclusion = false; - /** - * Controls the scale bias of the parallax mode. - */ - this.parallaxScaleBias = 0.05; - /** - * If sets to true, disables all the lights affecting the material. - */ - this.disableLighting = false; - /** - * Force the shader to compute irradiance in the fragment shader in order to take bump in account. - */ - this.forceIrradianceInFragment = false; - /** - * Number of Simultaneous lights allowed on the material. - */ - this.maxSimultaneousLights = 4; - /** - * If sets to true, x component of normal map value will invert (x = 1.0 - x). - */ - this.invertNormalMapX = false; - /** - * If sets to true, y component of normal map value will invert (y = 1.0 - y). - */ - this.invertNormalMapY = false; - /** - * If sets to true and backfaceCulling is false, normals will be flipped on the backside. - */ - this.twoSidedLighting = false; - /** - * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. - * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel) - */ - this.useAlphaFresnel = false; - /** - * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. - * And/Or occlude the blended part. (alpha stays linear to compute the fresnel) - */ - this.useLinearAlphaFresnel = false; - /** - * Let user defines the brdf lookup texture used for IBL. - * A default 8bit version is embedded but you could point at : - * * Default texture: https://assets.babylonjs.com/environments/correlatedMSBRDF_RGBD.png - * * Default 16bit pixel depth texture: https://assets.babylonjs.com/environments/correlatedMSBRDF.dds - * * LEGACY Default None correlated https://assets.babylonjs.com/environments/uncorrelatedBRDF_RGBD.png - * * LEGACY Default None correlated 16bit pixel depth https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds - */ - this.environmentBRDFTexture = null; - /** - * Force normal to face away from face. - */ - this.forceNormalForward = false; - /** - * Enables specular anti aliasing in the PBR shader. - * It will both interacts on the Geometry for analytical and IBL lighting. - * It also prefilter the roughness map based on the bump values. - */ - this.enableSpecularAntiAliasing = false; - /** - * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal - * makes the reflect vector face the model (under horizon). - */ - this.useHorizonOcclusion = true; - /** - * This parameters will enable/disable radiance occlusion by preventing the radiance to lit - * too much the area relying on ambient texture to define their ambient occlusion. - */ - this.useRadianceOcclusion = true; - /** - * If set to true, no lighting calculations will be applied. - */ - this.unlit = false; - /** - * If sets to true, the decal map will be applied after the detail map. Else, it is applied before (default: false) - */ - this.applyDecalMapAfterDetailMap = false; - this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene()); - } - /** - * Returns the name of this material class. - */ - getClassName() { - return "PBRMaterial"; - } - /** - * Makes a duplicate of the current material. - * @param name - name to use for the new material. - * @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. - * @param rootUrl defines the root URL to use to load textures - */ - clone(name, cloneTexturesOnlyOnce = true, rootUrl = "") { - const clone = decorators_SerializationHelper.Clone(() => new pbrMaterial_PBRMaterial(name, this.getScene()), this, { cloneTexturesOnlyOnce }); - clone.id = name; - clone.name = name; - this.stencil.copyTo(clone.stencil); - this._clonePlugins(clone, rootUrl); - return clone; - } - /** - * Serializes this PBR Material. - * @returns - An object with the serialized material. - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.customType = "BABYLON.PBRMaterial"; - return serializationObject; - } - // Statics - /** - * Parses a PBR Material from a serialized object. - * @param source - Serialized object. - * @param scene - BJS scene instance. - * @param rootUrl - url for the scene object - * @returns - PBRMaterial - */ - static Parse(source, scene, rootUrl) { - const material = decorators_SerializationHelper.Parse(() => new pbrMaterial_PBRMaterial(source.name, scene), source, scene, rootUrl); - if (source.stencil) { - material.stencil.parse(source.stencil, scene, rootUrl); - } - material_Material._parsePlugins(source, material, scene, rootUrl); - // The code block below ensures backward compatibility with serialized materials before plugins are automatically serialized. - if (source.clearCoat) { - material.clearCoat.parse(source.clearCoat, scene, rootUrl); - } - if (source.anisotropy) { - material.anisotropy.parse(source.anisotropy, scene, rootUrl); - } - if (source.brdf) { - material.brdf.parse(source.brdf, scene, rootUrl); - } - if (source.sheen) { - material.sheen.parse(source.sheen, scene, rootUrl); - } - if (source.subSurface) { - material.subSurface.parse(source.subSurface, scene, rootUrl); - } - if (source.iridescence) { - material.iridescence.parse(source.iridescence, scene, rootUrl); - } - return material; - } -} -/** - * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use. - */ -pbrMaterial_PBRMaterial.PBRMATERIAL_OPAQUE = pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE; -/** - * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value. - */ -pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHATEST = pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST; -/** - * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. - */ -pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHABLEND = pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHABLEND; -/** - * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. - * They are also discarded below the alpha cutoff threshold to improve performances. - */ -pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND; -/** - * Defines the default value of how much AO map is occluding the analytical lights - * (point spot...). - */ -pbrMaterial_PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS; -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "directIntensity", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "emissiveIntensity", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "environmentIntensity", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "specularIntensity", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "disableBumpMap", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "albedoTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "ambientTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "ambientTextureStrength", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") -], pbrMaterial_PBRMaterial.prototype, "opacityTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "reflectionTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "emissiveTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "reflectivityTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "metallicTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "metallic", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "roughness", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "metallicF0Factor", void 0); -__decorate([ - serializeAsColor3(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "metallicReflectanceColor", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useOnlyMetallicFromMetallicReflectanceTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "metallicReflectanceTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "reflectanceTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "microSurfaceTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "bumpTexture", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", null) -], pbrMaterial_PBRMaterial.prototype, "lightmapTexture", void 0); -__decorate([ - serializeAsColor3("ambient"), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "ambientColor", void 0); -__decorate([ - serializeAsColor3("albedo"), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "albedoColor", void 0); -__decorate([ - serializeAsColor3("reflectivity"), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "reflectivityColor", void 0); -__decorate([ - serializeAsColor3("reflection"), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "reflectionColor", void 0); -__decorate([ - serializeAsColor3("emissive"), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "emissiveColor", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "microSurface", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useLightmapAsShadowmap", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") -], pbrMaterial_PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") -], pbrMaterial_PBRMaterial.prototype, "forceAlphaTest", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") -], pbrMaterial_PBRMaterial.prototype, "alphaCutOff", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useSpecularOverAlpha", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useAmbientInGrayScale", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0); -__decorate([ - serialize() -], pbrMaterial_PBRMaterial.prototype, "usePhysicalLightFalloff", null); -__decorate([ - serialize() -], pbrMaterial_PBRMaterial.prototype, "useGLTFLightFalloff", null); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useRadianceOverAlpha", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useParallax", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useParallaxOcclusion", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "parallaxScaleBias", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsLightsDirty") -], pbrMaterial_PBRMaterial.prototype, "disableLighting", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "forceIrradianceInFragment", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsLightsDirty") -], pbrMaterial_PBRMaterial.prototype, "maxSimultaneousLights", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "invertNormalMapX", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "invertNormalMapY", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "twoSidedLighting", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useAlphaFresnel", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useLinearAlphaFresnel", void 0); -__decorate([ - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "environmentBRDFTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "forceNormalForward", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useHorizonOcclusion", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], pbrMaterial_PBRMaterial.prototype, "useRadianceOcclusion", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsMiscDirty") -], pbrMaterial_PBRMaterial.prototype, "unlit", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsMiscDirty") -], pbrMaterial_PBRMaterial.prototype, "applyDecalMapAfterDetailMap", void 0); -RegisterClass("BABYLON.PBRMaterial", pbrMaterial_PBRMaterial); -//# sourceMappingURL=pbrMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/dds.js -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - - - -// Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html -// All values and structures referenced from: -// http://msdn.microsoft.com/en-us/library/bb943991.aspx/ -const DDS_MAGIC = 0x20534444; -const //DDSD_CAPS = 0x1, -//DDSD_HEIGHT = 0x2, -//DDSD_WIDTH = 0x4, -//DDSD_PITCH = 0x8, -//DDSD_PIXELFORMAT = 0x1000, -DDSD_MIPMAPCOUNT = 0x20000; -//DDSD_LINEARSIZE = 0x80000, -//DDSD_DEPTH = 0x800000; -// var DDSCAPS_COMPLEX = 0x8, -// DDSCAPS_MIPMAP = 0x400000, -// DDSCAPS_TEXTURE = 0x1000; -const DDSCAPS2_CUBEMAP = 0x200; -// DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, -// DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, -// DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, -// DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, -// DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, -// DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, -// DDSCAPS2_VOLUME = 0x200000; -const //DDPF_ALPHAPIXELS = 0x1, -//DDPF_ALPHA = 0x2, -DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, -//DDPF_YUV = 0x200, -DDPF_LUMINANCE = 0x20000; -function FourCCToInt32(value) { - return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24); -} -function Int32ToFourCC(value) { - return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff); -} -const FOURCC_DXT1 = FourCCToInt32("DXT1"); -const FOURCC_DXT3 = FourCCToInt32("DXT3"); -const FOURCC_DXT5 = FourCCToInt32("DXT5"); -const FOURCC_DX10 = FourCCToInt32("DX10"); -const FOURCC_D3DFMT_R16G16B16A16F = 113; -const FOURCC_D3DFMT_R32G32B32A32F = 116; -const DXGI_FORMAT_R32G32B32A32_FLOAT = 2; -const DXGI_FORMAT_R16G16B16A16_FLOAT = 10; -const DXGI_FORMAT_B8G8R8X8_UNORM = 88; -const headerLengthInt = 31; // The header length in 32 bit ints -// Offsets into the header array -const off_magic = 0; -const off_size = 1; -const off_flags = 2; -const off_height = 3; -const off_width = 4; -const off_mipmapCount = 7; -const off_pfFlags = 20; -const off_pfFourCC = 21; -const off_RGBbpp = 22; -const off_RMask = 23; -const off_GMask = 24; -const off_BMask = 25; -const off_AMask = 26; -// var off_caps1 = 27; -const off_caps2 = 28; -// var off_caps3 = 29; -// var off_caps4 = 30; -const off_dxgiFormat = 32; -/** - * Class used to provide DDS decompression tools - */ -class DDSTools { - /** - * Gets DDS information from an array buffer - * @param data defines the array buffer view to read data from - * @returns the DDS information - */ - static GetDDSInfo(data) { - const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt); - const extendedHeader = new Int32Array(data.buffer, data.byteOffset, headerLengthInt + 4); - let mipmapCount = 1; - if (header[off_flags] & DDSD_MIPMAPCOUNT) { - mipmapCount = Math.max(1, header[off_mipmapCount]); - } - const fourCC = header[off_pfFourCC]; - const dxgiFormat = fourCC === FOURCC_DX10 ? extendedHeader[off_dxgiFormat] : 0; - let textureType = 0; - switch (fourCC) { - case FOURCC_D3DFMT_R16G16B16A16F: - textureType = 2; - break; - case FOURCC_D3DFMT_R32G32B32A32F: - textureType = 1; - break; - case FOURCC_DX10: - if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) { - textureType = 2; - break; - } - if (dxgiFormat === DXGI_FORMAT_R32G32B32A32_FLOAT) { - textureType = 1; - break; - } - } - return { - width: header[off_width], - height: header[off_height], - mipmapCount: mipmapCount, - isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC, - isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB, - isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE, - isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP, - isCompressed: fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5, - dxgiFormat: dxgiFormat, - textureType: textureType, - }; - } - static _GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { - const destArray = new Float32Array(dataLength); - const srcData = new Uint16Array(arrayBuffer, dataOffset); - let index = 0; - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - const srcPos = (x + y * width) * 4; - destArray[index] = FromHalfFloat(srcData[srcPos]); - destArray[index + 1] = FromHalfFloat(srcData[srcPos + 1]); - destArray[index + 2] = FromHalfFloat(srcData[srcPos + 2]); - if (DDSTools.StoreLODInAlphaChannel) { - destArray[index + 3] = lod; - } - else { - destArray[index + 3] = FromHalfFloat(srcData[srcPos + 3]); - } - index += 4; - } - } - return destArray; - } - static _GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { - if (DDSTools.StoreLODInAlphaChannel) { - const destArray = new Uint16Array(dataLength); - const srcData = new Uint16Array(arrayBuffer, dataOffset); - let index = 0; - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - const srcPos = (x + y * width) * 4; - destArray[index] = srcData[srcPos]; - destArray[index + 1] = srcData[srcPos + 1]; - destArray[index + 2] = srcData[srcPos + 2]; - destArray[index + 3] = ToHalfFloat(lod); - index += 4; - } - } - return destArray; - } - return new Uint16Array(arrayBuffer, dataOffset, dataLength); - } - static _GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { - if (DDSTools.StoreLODInAlphaChannel) { - const destArray = new Float32Array(dataLength); - const srcData = new Float32Array(arrayBuffer, dataOffset); - let index = 0; - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - const srcPos = (x + y * width) * 4; - destArray[index] = srcData[srcPos]; - destArray[index + 1] = srcData[srcPos + 1]; - destArray[index + 2] = srcData[srcPos + 2]; - destArray[index + 3] = lod; - index += 4; - } - } - return destArray; - } - return new Float32Array(arrayBuffer, dataOffset, dataLength); - } - static _GetFloatAsHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { - const destArray = new Uint16Array(dataLength); - const srcData = new Float32Array(arrayBuffer, dataOffset); - let index = 0; - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - destArray[index] = ToHalfFloat(srcData[index]); - destArray[index + 1] = ToHalfFloat(srcData[index + 1]); - destArray[index + 2] = ToHalfFloat(srcData[index + 2]); - if (DDSTools.StoreLODInAlphaChannel) { - destArray[index + 3] = ToHalfFloat(lod); - } - else { - destArray[index + 3] = ToHalfFloat(srcData[index + 3]); - } - index += 4; - } - } - return destArray; - } - static _GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { - const destArray = new Uint8Array(dataLength); - const srcData = new Float32Array(arrayBuffer, dataOffset); - let index = 0; - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - const srcPos = (x + y * width) * 4; - destArray[index] = math_scalar_Scalar.Clamp(srcData[srcPos]) * 255; - destArray[index + 1] = math_scalar_Scalar.Clamp(srcData[srcPos + 1]) * 255; - destArray[index + 2] = math_scalar_Scalar.Clamp(srcData[srcPos + 2]) * 255; - if (DDSTools.StoreLODInAlphaChannel) { - destArray[index + 3] = lod; - } - else { - destArray[index + 3] = math_scalar_Scalar.Clamp(srcData[srcPos + 3]) * 255; - } - index += 4; - } - } - return destArray; - } - static _GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { - const destArray = new Uint8Array(dataLength); - const srcData = new Uint16Array(arrayBuffer, dataOffset); - let index = 0; - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - const srcPos = (x + y * width) * 4; - destArray[index] = math_scalar_Scalar.Clamp(FromHalfFloat(srcData[srcPos])) * 255; - destArray[index + 1] = math_scalar_Scalar.Clamp(FromHalfFloat(srcData[srcPos + 1])) * 255; - destArray[index + 2] = math_scalar_Scalar.Clamp(FromHalfFloat(srcData[srcPos + 2])) * 255; - if (DDSTools.StoreLODInAlphaChannel) { - destArray[index + 3] = lod; - } - else { - destArray[index + 3] = math_scalar_Scalar.Clamp(FromHalfFloat(srcData[srcPos + 3])) * 255; - } - index += 4; - } - } - return destArray; - } - static _GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) { - const byteArray = new Uint8Array(dataLength); - const srcData = new Uint8Array(arrayBuffer, dataOffset); - let index = 0; - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - const srcPos = (x + y * width) * 4; - byteArray[index] = srcData[srcPos + rOffset]; - byteArray[index + 1] = srcData[srcPos + gOffset]; - byteArray[index + 2] = srcData[srcPos + bOffset]; - byteArray[index + 3] = srcData[srcPos + aOffset]; - index += 4; - } - } - return byteArray; - } - static _ExtractLongWordOrder(value) { - if (value === 0 || value === 255 || value === -16777216) { - return 0; - } - return 1 + DDSTools._ExtractLongWordOrder(value >> 8); - } - static _GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) { - const byteArray = new Uint8Array(dataLength); - const srcData = new Uint8Array(arrayBuffer, dataOffset); - let index = 0; - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - const srcPos = (x + y * width) * 3; - byteArray[index] = srcData[srcPos + rOffset]; - byteArray[index + 1] = srcData[srcPos + gOffset]; - byteArray[index + 2] = srcData[srcPos + bOffset]; - index += 3; - } - } - return byteArray; - } - static _GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer) { - const byteArray = new Uint8Array(dataLength); - const srcData = new Uint8Array(arrayBuffer, dataOffset); - let index = 0; - for (let y = 0; y < height; y++) { - for (let x = 0; x < width; x++) { - const srcPos = x + y * width; - byteArray[index] = srcData[srcPos]; - index++; - } - } - return byteArray; - } - /** - * Uploads DDS Levels to a Babylon Texture - * @internal - */ - static UploadDDSLevels(engine, texture, data, info, loadMipmaps, faces, lodIndex = -1, currentFace, destTypeMustBeFilterable = true) { - let sphericalPolynomialFaces = null; - if (info.sphericalPolynomial) { - sphericalPolynomialFaces = new Array(); - } - const ext = !!engine.getCaps().s3tc; - // TODO WEBGPU Once generateMipMaps is split into generateMipMaps + hasMipMaps in InternalTexture this line can be removed - texture.generateMipMaps = loadMipmaps; - const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt); - let fourCC, width, height, dataLength = 0, dataOffset; - let byteArray, mipmapCount, mip; - let internalCompressedFormat = 0; - let blockBytes = 1; - if (header[off_magic] !== DDS_MAGIC) { - logger_Logger.Error("Invalid magic number in DDS header"); - return; - } - if (!info.isFourCC && !info.isRGB && !info.isLuminance) { - logger_Logger.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code"); - return; - } - if (info.isCompressed && !ext) { - logger_Logger.Error("Compressed textures are not supported on this platform."); - return; - } - let bpp = header[off_RGBbpp]; - dataOffset = header[off_size] + 4; - let computeFormats = false; - if (info.isFourCC) { - fourCC = header[off_pfFourCC]; - switch (fourCC) { - case FOURCC_DXT1: - blockBytes = 8; - internalCompressedFormat = 33777; - break; - case FOURCC_DXT3: - blockBytes = 16; - internalCompressedFormat = 33778; - break; - case FOURCC_DXT5: - blockBytes = 16; - internalCompressedFormat = 33779; - break; - case FOURCC_D3DFMT_R16G16B16A16F: - computeFormats = true; - bpp = 64; - break; - case FOURCC_D3DFMT_R32G32B32A32F: - computeFormats = true; - bpp = 128; - break; - case FOURCC_DX10: { - // There is an additionnal header so dataOffset need to be changed - dataOffset += 5 * 4; // 5 uints - let supported = false; - switch (info.dxgiFormat) { - case DXGI_FORMAT_R16G16B16A16_FLOAT: - computeFormats = true; - bpp = 64; - supported = true; - break; - case DXGI_FORMAT_R32G32B32A32_FLOAT: - computeFormats = true; - bpp = 128; - supported = true; - break; - case DXGI_FORMAT_B8G8R8X8_UNORM: - info.isRGB = true; - info.isFourCC = false; - bpp = 32; - supported = true; - break; - } - if (supported) { - break; - } - } - // eslint-disable-next-line no-fallthrough - default: - console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC)); - return; - } - } - const rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]); - const gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]); - const bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]); - const aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]); - if (computeFormats) { - internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType); - } - mipmapCount = 1; - if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) { - mipmapCount = Math.max(1, header[off_mipmapCount]); - } - const startFace = currentFace || 0; - const caps = engine.getCaps(); - for (let face = startFace; face < faces; face++) { - width = header[off_width]; - height = header[off_height]; - for (mip = 0; mip < mipmapCount; ++mip) { - if (lodIndex === -1 || lodIndex === mip) { - // In case of fixed LOD, if the lod has just been uploaded, early exit. - const i = lodIndex === -1 ? mip : 0; - if (!info.isCompressed && info.isFourCC) { - texture.format = 5; - dataLength = width * height * 4; - let floatArray = null; - if (engine._badOS || engine._badDesktopOS || (!caps.textureHalfFloat && !caps.textureFloat)) { - // Required because iOS has many issues with float and half float generation - if (bpp === 128) { - floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i); - if (sphericalPolynomialFaces && i == 0) { - sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i)); - } - } - else if (bpp === 64) { - floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i); - if (sphericalPolynomialFaces && i == 0) { - sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i)); - } - } - texture.type = 0; - } - else { - const floatAvailable = caps.textureFloat && ((destTypeMustBeFilterable && caps.textureFloatLinearFiltering) || !destTypeMustBeFilterable); - const halfFloatAvailable = caps.textureHalfFloat && ((destTypeMustBeFilterable && caps.textureHalfFloatLinearFiltering) || !destTypeMustBeFilterable); - const destType = (bpp === 128 || (bpp === 64 && !halfFloatAvailable)) && floatAvailable - ? 1 - : (bpp === 64 || (bpp === 128 && !floatAvailable)) && halfFloatAvailable - ? 2 - : 0; - let dataGetter; - let dataGetterPolynomial = null; - switch (bpp) { - case 128: { - switch (destType) { - case 1: - dataGetter = DDSTools._GetFloatRGBAArrayBuffer; - dataGetterPolynomial = null; - break; - case 2: - dataGetter = DDSTools._GetFloatAsHalfFloatRGBAArrayBuffer; - dataGetterPolynomial = DDSTools._GetFloatRGBAArrayBuffer; - break; - case 0: - dataGetter = DDSTools._GetFloatAsUIntRGBAArrayBuffer; - dataGetterPolynomial = DDSTools._GetFloatRGBAArrayBuffer; - break; - } - break; - } - default: { - // 64 bpp - switch (destType) { - case 1: - dataGetter = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer; - dataGetterPolynomial = null; - break; - case 2: - dataGetter = DDSTools._GetHalfFloatRGBAArrayBuffer; - dataGetterPolynomial = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer; - break; - case 0: - dataGetter = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer; - dataGetterPolynomial = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer; - break; - } - break; - } - } - texture.type = destType; - floatArray = dataGetter(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i); - if (sphericalPolynomialFaces && i == 0) { - sphericalPolynomialFaces.push(dataGetterPolynomial ? dataGetterPolynomial(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i) : floatArray); - } - } - if (floatArray) { - engine._uploadDataToTextureDirectly(texture, floatArray, face, i); - } - } - else if (info.isRGB) { - texture.type = 0; - if (bpp === 24) { - texture.format = 4; - dataLength = width * height * 3; - byteArray = DDSTools._GetRGBArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset); - engine._uploadDataToTextureDirectly(texture, byteArray, face, i); - } - else { - // 32 - texture.format = 5; - dataLength = width * height * 4; - byteArray = DDSTools._GetRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset, aOffset); - engine._uploadDataToTextureDirectly(texture, byteArray, face, i); - } - } - else if (info.isLuminance) { - const unpackAlignment = engine._getUnpackAlignement(); - const unpaddedRowSize = width; - const paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment; - dataLength = paddedRowSize * (height - 1) + unpaddedRowSize; - byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer); - texture.format = 1; - texture.type = 0; - engine._uploadDataToTextureDirectly(texture, byteArray, face, i); - } - else { - dataLength = (((Math.max(4, width) / 4) * Math.max(4, height)) / 4) * blockBytes; - byteArray = new Uint8Array(data.buffer, data.byteOffset + dataOffset, dataLength); - texture.type = 0; - engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i); - } - } - dataOffset += bpp ? width * height * (bpp / 8) : dataLength; - width *= 0.5; - height *= 0.5; - width = Math.max(1.0, width); - height = Math.max(1.0, height); - } - if (currentFace !== undefined) { - // Loading a single face - break; - } - } - if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) { - info.sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({ - size: header[off_width], - right: sphericalPolynomialFaces[0], - left: sphericalPolynomialFaces[1], - up: sphericalPolynomialFaces[2], - down: sphericalPolynomialFaces[3], - front: sphericalPolynomialFaces[4], - back: sphericalPolynomialFaces[5], - format: 5, - type: 1, - gammaSpace: false, - }); - } - else { - info.sphericalPolynomial = undefined; - } - } -} -/** - * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default) - */ -DDSTools.StoreLODInAlphaChannel = false; -/** - * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection) - * @param rootUrl defines the url where the file to load is located - * @param scene defines the current scene - * @param lodScale defines scale to apply to the mip map selection - * @param lodOffset defines offset to apply to the mip map selection - * @param onLoad defines an optional callback raised when the texture is loaded - * @param onError defines an optional callback raised if there is an issue to load the texture - * @param format defines the format of the data - * @param forcedExtension defines the extension to use to pick the right loader - * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture - * @returns the cube texture as an InternalTexture - */ -ThinEngine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = true) { - const callback = (loadData) => { - if (!loadData) { - if (onLoad) { - onLoad(null); - } - return; - } - const texture = loadData.texture; - if (!createPolynomials) { - texture._sphericalPolynomial = new SphericalPolynomial(); - } - else if (loadData.info.sphericalPolynomial) { - texture._sphericalPolynomial = loadData.info.sphericalPolynomial; - } - texture._source = internalTexture_InternalTextureSource.CubePrefiltered; - if (this.getCaps().textureLOD) { - // Do not add extra process if texture lod is supported. - if (onLoad) { - onLoad(texture); - } - return; - } - const mipSlices = 3; - const gl = this._gl; - const width = loadData.width; - if (!width) { - return; - } - const textures = []; - for (let i = 0; i < mipSlices; i++) { - //compute LOD from even spacing in smoothness (matching shader calculation) - const smoothness = i / (mipSlices - 1); - const roughness = 1 - smoothness; - const minLODIndex = lodOffset; // roughness = 0 - const maxLODIndex = math_scalar_Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1 - const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness; - const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex)); - const glTextureFromLod = new internalTexture_InternalTexture(this, internalTexture_InternalTextureSource.Temp); - glTextureFromLod.type = texture.type; - glTextureFromLod.format = texture.format; - glTextureFromLod.width = Math.pow(2, Math.max(math_scalar_Scalar.Log2(width) - mipmapIndex, 0)); - glTextureFromLod.height = glTextureFromLod.width; - glTextureFromLod.isCube = true; - glTextureFromLod._cachedWrapU = 0; - glTextureFromLod._cachedWrapV = 0; - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true); - glTextureFromLod.samplingMode = 2; - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - if (loadData.isDDS) { - const info = loadData.info; - const data = loadData.data; - this._unpackFlipY(info.isCompressed); - DDSTools.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex); - } - else { - logger_Logger.Warn("DDS is the only prefiltered cube map supported so far."); - } - this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); - // Wrap in a base texture for easy binding. - const lodTexture = new baseTexture_BaseTexture(scene); - lodTexture._isCube = true; - lodTexture._texture = glTextureFromLod; - glTextureFromLod.isReady = true; - textures.push(lodTexture); - } - texture._lodTextureHigh = textures[2]; - texture._lodTextureMid = textures[1]; - texture._lodTextureLow = textures[0]; - if (onLoad) { - onLoad(texture); - } - }; - return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset); -}; -//# sourceMappingURL=dds.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader.js - - - -/** - * Implementation of the DDS Texture Loader. - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _DDSTextureLoader { - constructor() { - /** - * Defines whether the loader supports cascade loading the different faces. - */ - this.supportCascades = true; - } - /** - * This returns if the loader support the current file information. - * @param extension defines the file extension of the file being loaded - * @returns true if the loader can load the specified file - */ - canLoad(extension) { - return extension.endsWith(".dds"); - } - /** - * Uploads the cube texture data to the WebGL texture. It has already been bound. - * @param imgs contains the cube maps - * @param texture defines the BabylonJS internal texture - * @param createPolynomials will be true if polynomials have been requested - * @param onLoad defines the callback to trigger once the texture is ready - */ - loadCubeData(imgs, texture, createPolynomials, onLoad) { - const engine = texture.getEngine(); - let info; - let loadMipmap = false; - let maxLevel = 1000; - if (Array.isArray(imgs)) { - for (let index = 0; index < imgs.length; index++) { - const data = imgs[index]; - info = DDSTools.GetDDSInfo(data); - texture.width = info.width; - texture.height = info.height; - loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps; - engine._unpackFlipY(info.isCompressed); - DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6, -1, index); - if (!info.isFourCC && info.mipmapCount === 1) { - engine.generateMipMapsForCubemap(texture); - } - else { - maxLevel = info.mipmapCount - 1; - } - } - } - else { - const data = imgs; - info = DDSTools.GetDDSInfo(data); - texture.width = info.width; - texture.height = info.height; - if (createPolynomials) { - info.sphericalPolynomial = new SphericalPolynomial(); - } - loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps; - engine._unpackFlipY(info.isCompressed); - DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6); - if (!info.isFourCC && info.mipmapCount === 1) { - // Do not unbind as we still need to set the parameters. - engine.generateMipMapsForCubemap(texture, false); - } - else { - maxLevel = info.mipmapCount - 1; - } - } - engine._setCubeMapTextureParams(texture, loadMipmap, maxLevel); - texture.isReady = true; - texture.onLoadedObservable.notifyObservers(texture); - texture.onLoadedObservable.clear(); - if (onLoad) { - onLoad({ isDDS: true, width: texture.width, info, data: imgs, texture }); - } - } - /** - * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. - * @param data contains the texture data - * @param texture defines the BabylonJS internal texture - * @param callback defines the method to call once ready to upload - */ - loadData(data, texture, callback) { - const info = DDSTools.GetDDSInfo(data); - const loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && info.width >> (info.mipmapCount - 1) === 1; - callback(info.width, info.height, loadMipmap, info.isFourCC, () => { - DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1); - }); - } -} -// Register the loader. -engine_Engine._TextureLoaders.push(new _DDSTextureLoader()); -//# sourceMappingURL=ddsTextureLoader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Loaders/envTextureLoader.js - - -/** - * Implementation of the ENV Texture Loader. - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _ENVTextureLoader { - constructor() { - /** - * Defines whether the loader supports cascade loading the different faces. - */ - this.supportCascades = false; - } - /** - * This returns if the loader support the current file information. - * @param extension defines the file extension of the file being loaded - * @returns true if the loader can load the specified file - */ - canLoad(extension) { - return extension.endsWith(".env"); - } - /** - * Uploads the cube texture data to the WebGL texture. It has already been bound. - * @param data contains the texture data - * @param texture defines the BabylonJS internal texture - * @param createPolynomials will be true if polynomials have been requested - * @param onLoad defines the callback to trigger once the texture is ready - * @param onError defines the callback to trigger in case of error - */ - loadCubeData(data, texture, createPolynomials, onLoad, onError) { - if (Array.isArray(data)) { - return; - } - const info = GetEnvInfo(data); - if (info) { - texture.width = info.width; - texture.height = info.width; - try { - UploadEnvSpherical(texture, info); - UploadEnvLevelsAsync(texture, data, info).then(() => { - texture.isReady = true; - texture.onLoadedObservable.notifyObservers(texture); - texture.onLoadedObservable.clear(); - if (onLoad) { - onLoad(); - } - }, (reason) => { - onError === null || onError === void 0 ? void 0 : onError("Can not upload environment levels", reason); - }); - } - catch (e) { - onError === null || onError === void 0 ? void 0 : onError("Can not upload environment file", e); - } - } - else if (onError) { - onError("Can not parse the environment file", null); - } - } - /** - * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. - */ - loadData() { - throw ".env not supported in 2d."; - } -} -// Register the loader. -engine_Engine._TextureLoaders.push(new _ENVTextureLoader()); -//# sourceMappingURL=envTextureLoader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/khronosTextureContainer.js -/* eslint-disable @typescript-eslint/naming-convention */ - -/** - * for description see https://www.khronos.org/opengles/sdk/tools/KTX/ - * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ - */ -class KhronosTextureContainer { - /** - * Creates a new KhronosTextureContainer - * @param data contents of the KTX container file - * @param facesExpected should be either 1 or 6, based whether a cube texture or or - */ - constructor( - /** contents of the KTX container file */ - data, facesExpected) { - this.data = data; - /** - * If the container has been made invalid (eg. constructor failed to correctly load array buffer) - */ - this.isInvalid = false; - if (!KhronosTextureContainer.IsValid(data)) { - this.isInvalid = true; - logger_Logger.Error("texture missing KTX identifier"); - return; - } - // load the reset of the header in native 32 bit uint - const dataSize = Uint32Array.BYTES_PER_ELEMENT; - const headerDataView = new DataView(this.data.buffer, this.data.byteOffset + 12, 13 * dataSize); - const endianness = headerDataView.getUint32(0, true); - const littleEndian = endianness === 0x04030201; - this.glType = headerDataView.getUint32(1 * dataSize, littleEndian); // must be 0 for compressed textures - this.glTypeSize = headerDataView.getUint32(2 * dataSize, littleEndian); // must be 1 for compressed textures - this.glFormat = headerDataView.getUint32(3 * dataSize, littleEndian); // must be 0 for compressed textures - this.glInternalFormat = headerDataView.getUint32(4 * dataSize, littleEndian); // the value of arg passed to gl.compressedTexImage2D(,,x,,,,) - this.glBaseInternalFormat = headerDataView.getUint32(5 * dataSize, littleEndian); // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only) - this.pixelWidth = headerDataView.getUint32(6 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,) - this.pixelHeight = headerDataView.getUint32(7 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,) - this.pixelDepth = headerDataView.getUint32(8 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,) - this.numberOfArrayElements = headerDataView.getUint32(9 * dataSize, littleEndian); // used for texture arrays - this.numberOfFaces = headerDataView.getUint32(10 * dataSize, littleEndian); // used for cubemap textures, should either be 1 or 6 - this.numberOfMipmapLevels = headerDataView.getUint32(11 * dataSize, littleEndian); // number of levels; disregard possibility of 0 for compressed textures - this.bytesOfKeyValueData = headerDataView.getUint32(12 * dataSize, littleEndian); // the amount of space after the header for meta-data - // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing. - if (this.glType !== 0) { - logger_Logger.Error("only compressed formats currently supported"); - this.isInvalid = true; - return; - } - else { - // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard. - this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels); - } - if (this.pixelHeight === 0 || this.pixelDepth !== 0) { - logger_Logger.Error("only 2D textures currently supported"); - this.isInvalid = true; - return; - } - if (this.numberOfArrayElements !== 0) { - logger_Logger.Error("texture arrays not currently supported"); - this.isInvalid = true; - return; - } - if (this.numberOfFaces !== facesExpected) { - logger_Logger.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces); - this.isInvalid = true; - return; - } - // we now have a completely validated file, so could use existence of loadType as success - // would need to make this more elaborate & adjust checks above to support more than one load type - this.loadType = KhronosTextureContainer.COMPRESSED_2D; - } - /** - * Uploads KTX content to a Babylon Texture. - * It is assumed that the texture has already been created & is currently bound - * @internal - */ - uploadLevels(texture, loadMipmaps) { - switch (this.loadType) { - case KhronosTextureContainer.COMPRESSED_2D: - this._upload2DCompressedLevels(texture, loadMipmaps); - break; - case KhronosTextureContainer.TEX_2D: - case KhronosTextureContainer.COMPRESSED_3D: - case KhronosTextureContainer.TEX_3D: - } - } - _upload2DCompressedLevels(texture, loadMipmaps) { - // initialize width & height for level 1 - let dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData; - let width = this.pixelWidth; - let height = this.pixelHeight; - const mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1; - for (let level = 0; level < mipmapCount; level++) { - const imageSize = new Int32Array(this.data.buffer, this.data.byteOffset + dataOffset, 1)[0]; // size per face, since not supporting array cubemaps - dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above. - for (let face = 0; face < this.numberOfFaces; face++) { - const byteArray = new Uint8Array(this.data.buffer, this.data.byteOffset + dataOffset, imageSize); - const engine = texture.getEngine(); - engine._uploadCompressedDataToTextureDirectly(texture, texture.format, width, height, byteArray, face, level); - dataOffset += imageSize; // add size of the image for the next face/mipmap - dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image - } - width = Math.max(1.0, width * 0.5); - height = Math.max(1.0, height * 0.5); - } - } - /** - * Checks if the given data starts with a KTX file identifier. - * @param data the data to check - * @returns true if the data is a KTX file or false otherwise - */ - static IsValid(data) { - if (data.byteLength >= 12) { - // '«', 'K', 'T', 'X', ' ', '1', '1', '»', '\r', '\n', '\x1A', '\n' - const identifier = new Uint8Array(data.buffer, data.byteOffset, 12); - if (identifier[0] === 0xab && - identifier[1] === 0x4b && - identifier[2] === 0x54 && - identifier[3] === 0x58 && - identifier[4] === 0x20 && - identifier[5] === 0x31 && - identifier[6] === 0x31 && - identifier[7] === 0xbb && - identifier[8] === 0x0d && - identifier[9] === 0x0a && - identifier[10] === 0x1a && - identifier[11] === 0x0a) { - return true; - } - } - return false; - } -} -KhronosTextureContainer.HEADER_LEN = 12 + 13 * 4; // identifier + header elements (not including key value meta-data pairs) -// load types -KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D() -KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D() -KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D() -KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D() -//# sourceMappingURL=khronosTextureContainer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/workerPool.js -/** - * Helper class to push actions to a pool of workers. - */ -class WorkerPool { - /** - * Constructor - * @param workers Array of workers to use for actions - */ - constructor(workers) { - this._pendingActions = new Array(); - this._workerInfos = workers.map((worker) => ({ - workerPromise: Promise.resolve(worker), - idle: true, - })); - } - /** - * Terminates all workers and clears any pending actions. - */ - dispose() { - for (const workerInfo of this._workerInfos) { - workerInfo.workerPromise.then((worker) => { - worker.terminate(); - }); - } - this._workerInfos.length = 0; - this._pendingActions.length = 0; - } - /** - * Pushes an action to the worker pool. If all the workers are active, the action will be - * pended until a worker has completed its action. - * @param action The action to perform. Call onComplete when the action is complete. - */ - push(action) { - if (!this._executeOnIdleWorker(action)) { - this._pendingActions.push(action); - } - } - _executeOnIdleWorker(action) { - for (const workerInfo of this._workerInfos) { - if (workerInfo.idle) { - this._execute(workerInfo, action); - return true; - } - } - return false; - } - _execute(workerInfo, action) { - workerInfo.idle = false; - workerInfo.workerPromise.then((worker) => { - action(worker, () => { - const nextAction = this._pendingActions.shift(); - if (nextAction) { - this._execute(workerInfo, nextAction); - } - else { - workerInfo.idle = true; - } - }); - }); - } -} -/** - * Similar to the WorkerPool class except it creates and destroys workers automatically with a maximum of `maxWorkers` workers. - * Workers are terminated when it is idle for at least `idleTimeElapsedBeforeRelease` milliseconds. - */ -class AutoReleaseWorkerPool extends WorkerPool { - constructor(maxWorkers, createWorkerAsync, options = AutoReleaseWorkerPool.DefaultOptions) { - super([]); - this._maxWorkers = maxWorkers; - this._createWorkerAsync = createWorkerAsync; - this._options = options; - } - push(action) { - if (!this._executeOnIdleWorker(action)) { - if (this._workerInfos.length < this._maxWorkers) { - const workerInfo = { - workerPromise: this._createWorkerAsync(), - idle: false, - }; - this._workerInfos.push(workerInfo); - this._execute(workerInfo, action); - } - else { - this._pendingActions.push(action); - } - } - } - _execute(workerInfo, action) { - // Reset the idle timeout. - if (workerInfo.timeoutId) { - clearTimeout(workerInfo.timeoutId); - delete workerInfo.timeoutId; - } - super._execute(workerInfo, (worker, onComplete) => { - action(worker, () => { - onComplete(); - if (workerInfo.idle) { - // Schedule the worker to be terminated after the elapsed time. - workerInfo.timeoutId = setTimeout(() => { - workerInfo.workerPromise.then((worker) => { - worker.terminate(); - }); - const indexOf = this._workerInfos.indexOf(workerInfo); - if (indexOf !== -1) { - this._workerInfos.splice(indexOf, 1); - } - }, this._options.idleTimeElapsedBeforeRelease); - } - }); - }); - } -} -/** - * Default options for the constructor. - * Override to change the defaults. - */ -AutoReleaseWorkerPool.DefaultOptions = { - idleTimeElapsedBeforeRelease: 1000, -}; -//# sourceMappingURL=workerPool.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/ktx2decoderTypes.js -var SourceTextureFormat; -(function (SourceTextureFormat) { - SourceTextureFormat[SourceTextureFormat["ETC1S"] = 0] = "ETC1S"; - SourceTextureFormat[SourceTextureFormat["UASTC4x4"] = 1] = "UASTC4x4"; -})(SourceTextureFormat || (SourceTextureFormat = {})); -var TranscodeTarget; -(function (TranscodeTarget) { - TranscodeTarget[TranscodeTarget["ASTC_4X4_RGBA"] = 0] = "ASTC_4X4_RGBA"; - TranscodeTarget[TranscodeTarget["BC7_RGBA"] = 1] = "BC7_RGBA"; - TranscodeTarget[TranscodeTarget["BC3_RGBA"] = 2] = "BC3_RGBA"; - TranscodeTarget[TranscodeTarget["BC1_RGB"] = 3] = "BC1_RGB"; - TranscodeTarget[TranscodeTarget["PVRTC1_4_RGBA"] = 4] = "PVRTC1_4_RGBA"; - TranscodeTarget[TranscodeTarget["PVRTC1_4_RGB"] = 5] = "PVRTC1_4_RGB"; - TranscodeTarget[TranscodeTarget["ETC2_RGBA"] = 6] = "ETC2_RGBA"; - TranscodeTarget[TranscodeTarget["ETC1_RGB"] = 7] = "ETC1_RGB"; - TranscodeTarget[TranscodeTarget["RGBA32"] = 8] = "RGBA32"; - TranscodeTarget[TranscodeTarget["R8"] = 9] = "R8"; - TranscodeTarget[TranscodeTarget["RG8"] = 10] = "RG8"; -})(TranscodeTarget || (TranscodeTarget = {})); -var EngineFormat; -(function (EngineFormat) { - EngineFormat[EngineFormat["COMPRESSED_RGBA_BPTC_UNORM_EXT"] = 36492] = "COMPRESSED_RGBA_BPTC_UNORM_EXT"; - EngineFormat[EngineFormat["COMPRESSED_RGBA_ASTC_4X4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4X4_KHR"; - EngineFormat[EngineFormat["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT"; - EngineFormat[EngineFormat["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT"; - EngineFormat[EngineFormat["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; - EngineFormat[EngineFormat["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; - EngineFormat[EngineFormat["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC"; - EngineFormat[EngineFormat["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2"; - EngineFormat[EngineFormat["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL"; - EngineFormat[EngineFormat["RGBA8Format"] = 32856] = "RGBA8Format"; - EngineFormat[EngineFormat["R8Format"] = 33321] = "R8Format"; - EngineFormat[EngineFormat["RG8Format"] = 33323] = "RG8Format"; -})(EngineFormat || (EngineFormat = {})); -//# sourceMappingURL=ktx2decoderTypes.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/khronosTextureContainer2.js - - - - -function getAbsoluteUrlOrNull(url) { - return url ? tools_Tools.GetAbsoluteUrl(url) : null; -} -function applyConfig(urls) { - if (urls.wasmUASTCToASTC !== null) { - KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL = urls.wasmUASTCToASTC; - } - if (urls.wasmUASTCToBC7 !== null) { - KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL = urls.wasmUASTCToBC7; - } - if (urls.wasmUASTCToRGBA_UNORM !== null) { - KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = urls.wasmUASTCToRGBA_UNORM; - } - if (urls.wasmUASTCToRGBA_SRGB !== null) { - KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = urls.wasmUASTCToRGBA_SRGB; - } - if (urls.wasmUASTCToR8_UNORM !== null) { - KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL = urls.wasmUASTCToR8_UNORM; - } - if (urls.wasmUASTCToRG8_UNORM !== null) { - KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL = urls.wasmUASTCToRG8_UNORM; - } - if (urls.jsMSCTranscoder !== null) { - KTX2DECODER.MSCTranscoder.JSModuleURL = urls.jsMSCTranscoder; - } - if (urls.wasmMSCTranscoder !== null) { - KTX2DECODER.MSCTranscoder.WasmModuleURL = urls.wasmMSCTranscoder; - } - if (urls.wasmZSTDDecoder !== null) { - KTX2DECODER.ZSTDDecoder.WasmModuleURL = urls.wasmZSTDDecoder; - } -} -/** - * Class that defines the default KTX2 decoder options. - * - * This class is useful for providing options to the KTX2 decoder to control how the source data is transcoded. - */ -class DefaultKTX2DecoderOptions { - constructor() { - this._isDirty = true; - this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = true; - this._ktx2DecoderOptions = {}; - } - /** - * Gets the dirty flag - */ - get isDirty() { - return this._isDirty; - } - /** - * force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and ASTC + BC7 are not available as a compressed transcoded format - */ - get useRGBAIfASTCBC7NotAvailableWhenUASTC() { - return this._useRGBAIfASTCBC7NotAvailableWhenUASTC; - } - set useRGBAIfASTCBC7NotAvailableWhenUASTC(value) { - if (this._useRGBAIfASTCBC7NotAvailableWhenUASTC === value) { - return; - } - this._useRGBAIfASTCBC7NotAvailableWhenUASTC = value; - this._isDirty = true; - } - /** - * force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and only BC1 or BC3 are available as a compressed transcoded format. - * 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 - * to uncompressed and then recompresses the texture - */ - get useRGBAIfOnlyBC1BC3AvailableWhenUASTC() { - return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC; - } - set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(value) { - if (this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC === value) { - return; - } - this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = value; - this._isDirty = true; - } - /** - * force to always use (uncompressed) RGBA for transcoded format - */ - get forceRGBA() { - return this._forceRGBA; - } - set forceRGBA(value) { - if (this._forceRGBA === value) { - return; - } - this._forceRGBA = value; - this._isDirty = true; - } - /** - * force to always use (uncompressed) R8 for transcoded format - */ - get forceR8() { - return this._forceR8; - } - set forceR8(value) { - if (this._forceR8 === value) { - return; - } - this._forceR8 = value; - this._isDirty = true; - } - /** - * force to always use (uncompressed) RG8 for transcoded format - */ - get forceRG8() { - return this._forceRG8; - } - set forceRG8(value) { - if (this._forceRG8 === value) { - return; - } - this._forceRG8 = value; - this._isDirty = true; - } - /** - * list of transcoders to bypass when looking for a suitable transcoder. The available transcoders are: - * UniversalTranscoder_UASTC_ASTC - * UniversalTranscoder_UASTC_BC7 - * UniversalTranscoder_UASTC_RGBA_UNORM - * UniversalTranscoder_UASTC_RGBA_SRGB - * UniversalTranscoder_UASTC_R8_UNORM - * UniversalTranscoder_UASTC_RG8_UNORM - * MSCTranscoder - */ - get bypassTranscoders() { - return this._bypassTranscoders; - } - set bypassTranscoders(value) { - if (this._bypassTranscoders === value) { - return; - } - this._bypassTranscoders = value; - this._isDirty = true; - } - /** @internal */ - _getKTX2DecoderOptions() { - if (!this._isDirty) { - return this._ktx2DecoderOptions; - } - this._isDirty = false; - const options = { - useRGBAIfASTCBC7NotAvailableWhenUASTC: this._useRGBAIfASTCBC7NotAvailableWhenUASTC, - forceRGBA: this._forceRGBA, - forceR8: this._forceR8, - forceRG8: this._forceRG8, - bypassTranscoders: this._bypassTranscoders, - }; - if (this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC) { - options.transcodeFormatDecisionTree = { - UASTC: { - transcodeFormat: [TranscodeTarget.BC1_RGB, TranscodeTarget.BC3_RGBA], - yes: { - transcodeFormat: TranscodeTarget.RGBA32, - engineFormat: EngineFormat.RGBA8Format, - roundToMultiple4: false, - }, - }, - }; - } - this._ktx2DecoderOptions = options; - return options; - } -} -/** - * Class for loading KTX2 files - */ -class KhronosTextureContainer2 { - static GetDefaultNumWorkers() { - if (typeof navigator !== "object" || !navigator.hardwareConcurrency) { - return 1; - } - // Use 50% of the available logical processors but capped at 4. - return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4); - } - static _Initialize(numWorkers) { - if (KhronosTextureContainer2._WorkerPoolPromise || KhronosTextureContainer2._DecoderModulePromise) { - return; - } - const urls = { - jsDecoderModule: tools_Tools.GetAbsoluteUrl(this.URLConfig.jsDecoderModule), - wasmUASTCToASTC: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToASTC), - wasmUASTCToBC7: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToBC7), - wasmUASTCToRGBA_UNORM: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToRGBA_UNORM), - wasmUASTCToRGBA_SRGB: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToRGBA_SRGB), - wasmUASTCToR8_UNORM: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToR8_UNORM), - wasmUASTCToRG8_UNORM: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToRG8_UNORM), - jsMSCTranscoder: getAbsoluteUrlOrNull(this.URLConfig.jsMSCTranscoder), - wasmMSCTranscoder: getAbsoluteUrlOrNull(this.URLConfig.wasmMSCTranscoder), - wasmZSTDDecoder: getAbsoluteUrlOrNull(this.URLConfig.wasmZSTDDecoder), - }; - if (numWorkers && typeof Worker === "function" && typeof URL !== "undefined") { - KhronosTextureContainer2._WorkerPoolPromise = new Promise((resolve) => { - const workerContent = `${applyConfig}(${workerFunc})()`; - const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" })); - resolve(new AutoReleaseWorkerPool(numWorkers, () => new Promise((resolve, reject) => { - const worker = new Worker(workerBlobUrl); - const onError = (error) => { - worker.removeEventListener("error", onError); - worker.removeEventListener("message", onMessage); - reject(error); - }; - const onMessage = (message) => { - if (message.data.action === "init") { - worker.removeEventListener("error", onError); - worker.removeEventListener("message", onMessage); - resolve(worker); - } - }; - worker.addEventListener("error", onError); - worker.addEventListener("message", onMessage); - worker.postMessage({ - action: "init", - urls: urls, - }); - }))); - }); - } - else if (typeof KTX2DECODER === "undefined") { - KhronosTextureContainer2._DecoderModulePromise = tools_Tools.LoadScriptAsync(urls.jsDecoderModule).then(() => { - KTX2DECODER.MSCTranscoder.UseFromWorkerThread = false; - KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = true; - applyConfig(urls); - return new KTX2DECODER.KTX2Decoder(); - }); - } - else { - KTX2DECODER.MSCTranscoder.UseFromWorkerThread = false; - KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = true; - KhronosTextureContainer2._DecoderModulePromise = Promise.resolve(new KTX2DECODER.KTX2Decoder()); - } - } - /** - * Constructor - * @param engine The engine to use - * @param numWorkers The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context. - */ - constructor(engine, numWorkers = KhronosTextureContainer2.DefaultNumWorkers) { - this._engine = engine; - KhronosTextureContainer2._Initialize(numWorkers); - } - /** - * @internal - */ - uploadAsync(data, internalTexture, options) { - const caps = this._engine.getCaps(); - const compressedTexturesCaps = { - astc: !!caps.astc, - bptc: !!caps.bptc, - s3tc: !!caps.s3tc, - pvrtc: !!caps.pvrtc, - etc2: !!caps.etc2, - etc1: !!caps.etc1, - }; - if (KhronosTextureContainer2._WorkerPoolPromise) { - return KhronosTextureContainer2._WorkerPoolPromise.then((workerPool) => { - return new Promise((resolve, reject) => { - workerPool.push((worker, onComplete) => { - const onError = (error) => { - worker.removeEventListener("error", onError); - worker.removeEventListener("message", onMessage); - reject(error); - onComplete(); - }; - const onMessage = (message) => { - if (message.data.action === "decoded") { - worker.removeEventListener("error", onError); - worker.removeEventListener("message", onMessage); - if (!message.data.success) { - reject({ message: message.data.msg }); - } - else { - try { - this._createTexture(message.data.decodedData, internalTexture, options); - resolve(); - } - catch (err) { - reject({ message: err }); - } - } - onComplete(); - } - }; - worker.addEventListener("error", onError); - worker.addEventListener("message", onMessage); - worker.postMessage({ action: "setDefaultDecoderOptions", options: KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions() }); - const dataCopy = new Uint8Array(data.byteLength); - dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); - worker.postMessage({ action: "decode", data: dataCopy, caps: compressedTexturesCaps, options }, [dataCopy.buffer]); - }); - }); - }); - } - else if (KhronosTextureContainer2._DecoderModulePromise) { - return KhronosTextureContainer2._DecoderModulePromise.then((decoder) => { - if (KhronosTextureContainer2.DefaultDecoderOptions.isDirty) { - KTX2DECODER.KTX2Decoder.DefaultDecoderOptions = KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions(); - } - return new Promise((resolve, reject) => { - decoder - .decode(data, caps) - .then((data) => { - this._createTexture(data, internalTexture); - resolve(); - }) - .catch((reason) => { - reject({ message: reason }); - }); - }); - }); - } - throw new Error("KTX2 decoder module is not available"); - } - _createTexture(data, internalTexture, options) { - const oglTexture2D = 3553; // gl.TEXTURE_2D - this._engine._bindTextureDirectly(oglTexture2D, internalTexture); - if (options) { - // return back some information about the decoded data - options.transcodedFormat = data.transcodedFormat; - options.isInGammaSpace = data.isInGammaSpace; - options.hasAlpha = data.hasAlpha; - options.transcoderName = data.transcoderName; - } - let isUncompressedFormat = true; - switch (data.transcodedFormat) { - case 0x8058 /* RGBA8 */: - internalTexture.type = 0; - internalTexture.format = 5; - break; - case 0x8229 /* R8 */: - internalTexture.type = 0; - internalTexture.format = 6; - break; - case 0x822b /* RG8 */: - internalTexture.type = 0; - internalTexture.format = 7; - break; - default: - internalTexture.format = data.transcodedFormat; - isUncompressedFormat = false; - break; - } - internalTexture._gammaSpace = data.isInGammaSpace; - internalTexture.generateMipMaps = data.mipmaps.length > 1; - if (data.errors) { - throw new Error("KTX2 container - could not transcode the data. " + data.errors); - } - for (let t = 0; t < data.mipmaps.length; ++t) { - const mipmap = data.mipmaps[t]; - if (!mipmap || !mipmap.data) { - throw new Error("KTX2 container - could not transcode one of the image"); - } - if (isUncompressedFormat) { - // uncompressed RGBA / R8 / RG8 - internalTexture.width = mipmap.width; // need to set width/height so that the call to _uploadDataToTextureDirectly uses the right dimensions - internalTexture.height = mipmap.height; - this._engine._uploadDataToTextureDirectly(internalTexture, mipmap.data, 0, t, undefined, true); - } - else { - this._engine._uploadCompressedDataToTextureDirectly(internalTexture, data.transcodedFormat, mipmap.width, mipmap.height, mipmap.data, 0, t); - } - } - internalTexture._extension = ".ktx2"; - internalTexture.width = data.mipmaps[0].width; - internalTexture.height = data.mipmaps[0].height; - internalTexture.isReady = true; - this._engine._bindTextureDirectly(oglTexture2D, null); - } - /** - * Checks if the given data starts with a KTX2 file identifier. - * @param data the data to check - * @returns true if the data is a KTX2 file or false otherwise - */ - static IsValid(data) { - if (data.byteLength >= 12) { - // '«', 'K', 'T', 'X', ' ', '2', '0', '»', '\r', '\n', '\x1A', '\n' - const identifier = new Uint8Array(data.buffer, data.byteOffset, 12); - if (identifier[0] === 0xab && - identifier[1] === 0x4b && - identifier[2] === 0x54 && - identifier[3] === 0x58 && - identifier[4] === 0x20 && - identifier[5] === 0x32 && - identifier[6] === 0x30 && - identifier[7] === 0xbb && - identifier[8] === 0x0d && - identifier[9] === 0x0a && - identifier[10] === 0x1a && - identifier[11] === 0x0a) { - return true; - } - } - return false; - } -} -/** - * URLs to use when loading the KTX2 decoder module as well as its dependencies - * If a url is null, the default url is used (pointing to https://preview.babylonjs.com) - * Note that jsDecoderModule can't be null and that the other dependencies will only be loaded if necessary - * Urls you can change: - * URLConfig.jsDecoderModule - * URLConfig.wasmUASTCToASTC - * URLConfig.wasmUASTCToBC7 - * URLConfig.wasmUASTCToRGBA_UNORM - * URLConfig.wasmUASTCToRGBA_SRGB - * URLConfig.wasmUASTCToR8_UNORM - * URLConfig.wasmUASTCToRG8_UNORM - * URLConfig.jsMSCTranscoder - * URLConfig.wasmMSCTranscoder - * URLConfig.wasmZSTDDecoder - * You can see their default values in this PG: https://playground.babylonjs.com/#EIJH8L#29 - */ -KhronosTextureContainer2.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, -}; -/** - * Default number of workers used to handle data decoding - */ -KhronosTextureContainer2.DefaultNumWorkers = KhronosTextureContainer2.GetDefaultNumWorkers(); -/** - * Default configuration for the KTX2 decoder. - * The options defined in this way have priority over those passed when creating a KTX2 texture with new Texture(...). - */ -KhronosTextureContainer2.DefaultDecoderOptions = new DefaultKTX2DecoderOptions(); -function workerFunc() { - let ktx2Decoder; - onmessage = (event) => { - if (!event.data) { - return; - } - switch (event.data.action) { - case "init": { - const urls = event.data.urls; - importScripts(urls.jsDecoderModule); - applyConfig(urls); - ktx2Decoder = new KTX2DECODER.KTX2Decoder(); - postMessage({ action: "init" }); - break; - } - case "setDefaultDecoderOptions": { - KTX2DECODER.KTX2Decoder.DefaultDecoderOptions = event.data.options; - break; - } - case "decode": - ktx2Decoder - .decode(event.data.data, event.data.caps, event.data.options) - .then((data) => { - const buffers = []; - for (let mip = 0; mip < data.mipmaps.length; ++mip) { - const mipmap = data.mipmaps[mip]; - if (mipmap && mipmap.data) { - buffers.push(mipmap.data.buffer); - } - } - postMessage({ action: "decoded", success: true, decodedData: data }, buffers); - }) - .catch((reason) => { - postMessage({ action: "decoded", success: false, msg: reason }); - }); - break; - } - }; -} -//# sourceMappingURL=khronosTextureContainer2.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader.js - - - - - -function mapSRGBToLinear(format) { - switch (format) { - 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; -} -/** - * Implementation of the KTX Texture Loader. - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _KTXTextureLoader { - constructor() { - /** - * Defines whether the loader supports cascade loading the different faces. - */ - this.supportCascades = false; - } - /** - * This returns if the loader support the current file information. - * @param extension defines the file extension of the file being loaded - * @param mimeType defines the optional mime type of the file being loaded - * @returns true if the loader can load the specified file - */ - canLoad(extension, mimeType) { - // The ".ktx2" file extension is still up for debate: https://github.com/KhronosGroup/KTX-Specification/issues/18 - return extension.endsWith(".ktx") || extension.endsWith(".ktx2") || mimeType === "image/ktx" || mimeType === "image/ktx2"; - } - /** - * Uploads the cube texture data to the WebGL texture. It has already been bound. - * @param data contains the texture data - * @param texture defines the BabylonJS internal texture - * @param createPolynomials will be true if polynomials have been requested - * @param onLoad defines the callback to trigger once the texture is ready - */ - loadCubeData(data, texture, createPolynomials, onLoad) { - if (Array.isArray(data)) { - return; - } - // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture - texture._invertVScale = !texture.invertY; - const engine = texture.getEngine(); - const ktx = new KhronosTextureContainer(data, 6); - const loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps; - engine._unpackFlipY(true); - ktx.uploadLevels(texture, texture.generateMipMaps); - texture.width = ktx.pixelWidth; - texture.height = ktx.pixelHeight; - engine._setCubeMapTextureParams(texture, loadMipmap, ktx.numberOfMipmapLevels - 1); - texture.isReady = true; - texture.onLoadedObservable.notifyObservers(texture); - texture.onLoadedObservable.clear(); - if (onLoad) { - onLoad(); - } - } - /** - * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. - * @param data contains the texture data - * @param texture defines the BabylonJS internal texture - * @param callback defines the method to call once ready to upload - * @param options - */ - loadData(data, texture, callback, options) { - if (KhronosTextureContainer.IsValid(data)) { - // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture - texture._invertVScale = !texture.invertY; - const ktx = new KhronosTextureContainer(data, 1); - const mappedFormat = mapSRGBToLinear(ktx.glInternalFormat); - if (mappedFormat) { - texture.format = mappedFormat; - texture._useSRGBBuffer = texture.getEngine()._getUseSRGBBuffer(true, texture.generateMipMaps); - texture._gammaSpace = true; - } - else { - texture.format = ktx.glInternalFormat; - } - callback(ktx.pixelWidth, ktx.pixelHeight, texture.generateMipMaps, true, () => { - ktx.uploadLevels(texture, texture.generateMipMaps); - }, ktx.isInvalid); - } - else if (KhronosTextureContainer2.IsValid(data)) { - const ktx2 = new KhronosTextureContainer2(texture.getEngine()); - ktx2.uploadAsync(data, texture, options).then(() => { - callback(texture.width, texture.height, texture.generateMipMaps, true, () => { }, false); - }, (error) => { - logger_Logger.Warn(`Failed to load KTX2 texture data: ${error.message}`); - callback(0, 0, false, false, () => { }, true); - }); - } - else { - logger_Logger.Error("texture missing KTX identifier"); - callback(0, 0, false, false, () => { }, true); - } - } -} -// Register the loader. -engine_Engine._TextureLoaders.unshift(new _KTXTextureLoader()); -//# sourceMappingURL=ktxTextureLoader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRCamera.js - - - - - - - -/** - * WebXR Camera which holds the views for the xrSession - * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRCamera - */ -class WebXRCamera extends FreeCamera { - /** - * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager - * @param name the name of the camera - * @param scene the scene to add the camera to - * @param _xrSessionManager a constructed xr session manager - */ - constructor(name, scene, _xrSessionManager) { - super(name, math_vector_Vector3.Zero(), scene); - this._xrSessionManager = _xrSessionManager; - this._firstFrame = false; - this._referenceQuaternion = math_vector_Quaternion.Identity(); - this._referencedPosition = new math_vector_Vector3(); - this._trackingState = WebXRTrackingState.NOT_TRACKING; - /** - * Observable raised before camera teleportation - */ - this.onBeforeCameraTeleport = new observable_Observable(); - /** - * Observable raised after camera teleportation - */ - this.onAfterCameraTeleport = new observable_Observable(); - /** - * Notifies when the camera's tracking state has changed. - * Notice - will also be triggered when tracking has started (at the beginning of the session) - */ - this.onTrackingStateChanged = new observable_Observable(); - /** - * Should position compensation execute on first frame. - * This is used when copying the position from a native (non XR) camera - */ - this.compensateOnFirstFrame = true; - this._rotate180 = new math_vector_Quaternion(0, 1, 0, 0); - // Initial camera configuration - this.minZ = 0.1; - this.rotationQuaternion = new math_vector_Quaternion(); - this.cameraRigMode = camera_Camera.RIG_MODE_CUSTOM; - this.updateUpVectorFromRotation = true; - this._updateNumberOfRigCameras(1); - // freeze projection matrix, which will be copied later - this.freezeProjectionMatrix(); - this._deferOnly = true; - this._xrSessionManager.onXRSessionInit.add(() => { - this._referencedPosition.copyFromFloats(0, 0, 0); - this._referenceQuaternion.copyFromFloats(0, 0, 0, 1); - // first frame - camera's y position should be 0 for the correct offset - this._firstFrame = this.compensateOnFirstFrame; - }); - // Check transformation changes on each frame. Callback is added to be first so that the transformation will be - // applied to the rest of the elements using the referenceSpace object - this._xrSessionManager.onXRFrameObservable.add(() => { - if (this._firstFrame) { - this._updateFromXRSession(); - } - if (this._deferredUpdated) { - this.position.copyFrom(this._deferredPositionUpdate); - this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate); - } - this._updateReferenceSpace(); - this._updateFromXRSession(); - }, undefined, true); - } - /** - * Get the current XR tracking state of the camera - */ - get trackingState() { - return this._trackingState; - } - _setTrackingState(newState) { - if (this._trackingState !== newState) { - this._trackingState = newState; - this.onTrackingStateChanged.notifyObservers(newState); - } - } - /** - * Return the user's height, unrelated to the current ground. - * This will be the y position of this camera, when ground level is 0. - */ - get realWorldHeight() { - const basePose = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace); - if (basePose && basePose.transform) { - return basePose.transform.position.y; - } - else { - return 0; - } - } - /** @internal */ - _updateForDualEyeDebugging( /*pupilDistance = 0.01*/) { - // Create initial camera rigs - this._updateNumberOfRigCameras(2); - this.rigCameras[0].viewport = new math_viewport_Viewport(0, 0, 0.5, 1.0); - // this.rigCameras[0].position.x = -pupilDistance / 2; - this.rigCameras[0].outputRenderTarget = null; - this.rigCameras[1].viewport = new math_viewport_Viewport(0.5, 0, 0.5, 1.0); - // this.rigCameras[1].position.x = pupilDistance / 2; - this.rigCameras[1].outputRenderTarget = null; - } - /** - * Sets this camera's transformation based on a non-vr camera - * @param otherCamera the non-vr camera to copy the transformation from - * @param resetToBaseReferenceSpace should XR reset to the base reference space - */ - setTransformationFromNonVRCamera(otherCamera = this.getScene().activeCamera, resetToBaseReferenceSpace = true) { - if (!otherCamera || otherCamera === this) { - return; - } - const mat = otherCamera.computeWorldMatrix(); - mat.decompose(undefined, this.rotationQuaternion, this.position); - // set the ground level - this.position.y = 0; - math_vector_Quaternion.FromEulerAnglesToRef(0, this.rotationQuaternion.toEulerAngles().y, 0, this.rotationQuaternion); - this._firstFrame = true; - if (resetToBaseReferenceSpace) { - this._xrSessionManager.resetReferenceSpace(); - } - } - /** - * Gets the current instance class name ("WebXRCamera"). - * @returns the class name - */ - getClassName() { - return "WebXRCamera"; - } - /** - * Set the target for the camera to look at. - * Note that this only rotates around the Y axis, as opposed to the default behavior of other cameras - * @param target the target to set the camera to look at - */ - setTarget(target) { - // only rotate around the y axis! - const tmpVector = math_vector_TmpVectors.Vector3[1]; - target.subtractToRef(this.position, tmpVector); - tmpVector.y = 0; - tmpVector.normalize(); - const yRotation = Math.atan2(tmpVector.x, tmpVector.z); - this.rotationQuaternion.toEulerAnglesToRef(tmpVector); - math_vector_Quaternion.FromEulerAnglesToRef(tmpVector.x, yRotation, tmpVector.z, this.rotationQuaternion); - } - dispose() { - super.dispose(); - this._lastXRViewerPose = undefined; - } - _updateFromXRSession() { - const pose = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace); - this._lastXRViewerPose = pose || undefined; - if (!pose) { - this._setTrackingState(WebXRTrackingState.NOT_TRACKING); - return; - } - // Set the tracking state. if it didn't change it is a no-op - const trackingState = pose.emulatedPosition ? WebXRTrackingState.TRACKING_LOST : WebXRTrackingState.TRACKING; - this._setTrackingState(trackingState); - // check min/max Z and update if not the same as in cache - if (this.minZ !== this._cache.minZ || this.maxZ !== this._cache.maxZ) { - const xrRenderState = { - // if maxZ is 0 it should be "Infinity", but it doesn't work with the WebXR API. Setting to a large number. - depthFar: this.maxZ || 10000, - depthNear: this.minZ, - }; - this._xrSessionManager.updateRenderState(xrRenderState); - this._cache.minZ = this.minZ; - this._cache.maxZ = this.maxZ; - } - if (pose.transform) { - const orientation = pose.transform.orientation; - if (pose.transform.orientation.x === undefined) { - // Babylon native polyfill can return an undefined orientation value - // When not initialized - return; - } - const pos = pose.transform.position; - this._referencedPosition.set(pos.x, pos.y, pos.z); - this._referenceQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w); - if (!this._scene.useRightHandedSystem) { - this._referencedPosition.z *= -1; - this._referenceQuaternion.z *= -1; - this._referenceQuaternion.w *= -1; - } - if (this._firstFrame) { - this._firstFrame = false; - // we have the XR reference, now use this to find the offset to get the camera to be - // in the right position - // set the height to correlate to the current height - this.position.y += this._referencedPosition.y; - // avoid using the head rotation on the first frame. - this._referenceQuaternion.copyFromFloats(0, 0, 0, 1); - } - else { - // update position and rotation as reference - this.rotationQuaternion.copyFrom(this._referenceQuaternion); - this.position.copyFrom(this._referencedPosition); - } - } - // Update camera rigs - if (this.rigCameras.length !== pose.views.length) { - this._updateNumberOfRigCameras(pose.views.length); - } - pose.views.forEach((view, i) => { - var _a; - const currentRig = this.rigCameras[i]; - // update right and left, where applicable - if (!currentRig.isLeftCamera && !currentRig.isRightCamera) { - if (view.eye === "right") { - currentRig._isRightCamera = true; - } - else if (view.eye === "left") { - currentRig._isLeftCamera = true; - } - } - // Update view/projection matrix - const pos = view.transform.position; - const orientation = view.transform.orientation; - currentRig.parent = this.parent; - currentRig.position.set(pos.x, pos.y, pos.z); - currentRig.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w); - if (!this._scene.useRightHandedSystem) { - currentRig.position.z *= -1; - currentRig.rotationQuaternion.z *= -1; - currentRig.rotationQuaternion.w *= -1; - } - else { - currentRig.rotationQuaternion.multiplyInPlace(this._rotate180); - } - math_vector_Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, currentRig._projectionMatrix); - if (!this._scene.useRightHandedSystem) { - currentRig._projectionMatrix.toggleProjectionMatrixHandInPlace(); - } - // first camera? - if (i === 0) { - this._projectionMatrix.copyFrom(currentRig._projectionMatrix); - } - const renderTargetTexture = this._xrSessionManager.getRenderTargetTextureForView(view); - this._renderingMultiview = ((_a = renderTargetTexture === null || renderTargetTexture === void 0 ? void 0 : renderTargetTexture._texture) === null || _a === void 0 ? void 0 : _a.isMultiview) || false; - if (this._renderingMultiview) { - // For multiview, the render target texture is the same per-view (just the slice index is different), - // so we only need to set the output render target once for the rig parent. - if (i == 0) { - this._xrSessionManager.trySetViewportForView(this.viewport, view); - this.outputRenderTarget = renderTargetTexture; - } - } - else { - // Update viewport - this._xrSessionManager.trySetViewportForView(currentRig.viewport, view); - // Set cameras to render to the session's render target - currentRig.outputRenderTarget = renderTargetTexture || this._xrSessionManager.getRenderTargetTextureForView(view); - } - // Replicate parent rig camera behavior - currentRig.layerMask = this.layerMask; - }); - } - _updateNumberOfRigCameras(viewCount = 1) { - while (this.rigCameras.length < viewCount) { - const newCamera = new targetCamera_TargetCamera("XR-RigCamera: " + this.rigCameras.length, math_vector_Vector3.Zero(), this.getScene()); - newCamera.minZ = 0.1; - newCamera.rotationQuaternion = new math_vector_Quaternion(); - newCamera.updateUpVectorFromRotation = true; - newCamera.isRigCamera = true; - newCamera.rigParent = this; - // do not compute projection matrix, provided by XR - newCamera.freezeProjectionMatrix(); - this.rigCameras.push(newCamera); - } - while (this.rigCameras.length > viewCount) { - const removedCamera = this.rigCameras.pop(); - if (removedCamera) { - removedCamera.dispose(); - } - } - } - _updateReferenceSpace() { - // were position & rotation updated OUTSIDE of the xr update loop - if (!this.position.equals(this._referencedPosition) || !this.rotationQuaternion.equals(this._referenceQuaternion)) { - const referencedMat = math_vector_TmpVectors.Matrix[0]; - const poseMat = math_vector_TmpVectors.Matrix[1]; - const transformMat = math_vector_TmpVectors.Matrix[2]; - math_vector_Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly, this._referenceQuaternion, this._referencedPosition, referencedMat); - math_vector_Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly, this.rotationQuaternion, this.position, poseMat); - referencedMat.invert().multiplyToRef(poseMat, transformMat); - transformMat.invert(); - if (!this._scene.useRightHandedSystem) { - transformMat.toggleModelMatrixHandInPlace(); - } - transformMat.decompose(undefined, this._referenceQuaternion, this._referencedPosition); - const transform = 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(transform); - } - } -} -WebXRCamera._ScaleReadOnly = math_vector_Vector3.One(); -//# sourceMappingURL=webXRCamera.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRExperienceHelper.js - - - - - - - - -/** - * Base set of functionality needed to create an XR experience (WebXRSessionManager, Camera, StateManagement, etc.) - * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRExperienceHelpers - */ -class WebXRExperienceHelper { - /** - * Creates a WebXRExperienceHelper - * @param _scene The scene the helper should be created in - */ - constructor(_scene) { - this._scene = _scene; - this._nonVRCamera = null; - this._attachedToElement = false; - this._spectatorCamera = null; - this._originalSceneAutoClear = true; - this._supported = false; - this._spectatorMode = false; - this._lastTimestamp = 0; - /** - * Observers registered here will be triggered after the camera's initial transformation is set - * This can be used to set a different ground level or an extra rotation. - * - * Note that ground level is considered to be at 0. The height defined by the XR camera will be added - * to the position set after this observable is done executing. - */ - this.onInitialXRPoseSetObservable = new observable_Observable(); - /** - * Fires when the state of the experience helper has changed - */ - this.onStateChangedObservable = new observable_Observable(); - /** - * The current state of the XR experience (eg. transitioning, in XR or not in XR) - */ - this.state = WebXRState.NOT_IN_XR; - this.sessionManager = new WebXRSessionManager(_scene); - this.camera = new WebXRCamera("webxr", _scene, this.sessionManager); - this.featuresManager = new WebXRFeaturesManager(this.sessionManager); - _scene.onDisposeObservable.addOnce(() => { - this.dispose(); - }); - } - /** - * Creates the experience helper - * @param scene the scene to attach the experience helper to - * @returns a promise for the experience helper - */ - static CreateAsync(scene) { - const helper = new WebXRExperienceHelper(scene); - return helper.sessionManager - .initializeAsync() - .then(() => { - helper._supported = true; - return helper; - }) - .catch((e) => { - helper._setState(WebXRState.NOT_IN_XR); - helper.dispose(); - throw e; - }); - } - /** - * Disposes of the experience helper - */ - dispose() { - var _a; - this.exitXRAsync(); - this.camera.dispose(); - this.onStateChangedObservable.clear(); - this.onInitialXRPoseSetObservable.clear(); - this.sessionManager.dispose(); - (_a = this._spectatorCamera) === null || _a === void 0 ? void 0 : _a.dispose(); - if (this._nonVRCamera) { - this._scene.activeCamera = this._nonVRCamera; - } - } - /** - * Enters XR mode (This must be done within a user interaction in most browsers eg. button click) - * @param sessionMode options for the XR session - * @param referenceSpaceType frame of reference of the XR session - * @param renderTarget the output canvas that will be used to enter XR mode - * @param sessionCreationOptions optional XRSessionInit object to init the session with - * @returns promise that resolves after xr mode has entered - */ - async enterXRAsync(sessionMode, referenceSpaceType, renderTarget = this.sessionManager.getWebXRRenderTarget(), sessionCreationOptions = {}) { - var _a, _b, _c; - if (!this._supported) { - throw "WebXR not supported in this browser or environment"; - } - this._setState(WebXRState.ENTERING_XR); - if (referenceSpaceType !== "viewer" && referenceSpaceType !== "local") { - sessionCreationOptions.optionalFeatures = sessionCreationOptions.optionalFeatures || []; - sessionCreationOptions.optionalFeatures.push(referenceSpaceType); - } - sessionCreationOptions = await this.featuresManager._extendXRSessionInitObject(sessionCreationOptions); - // we currently recommend "unbounded" space in AR (#7959) - if (sessionMode === "immersive-ar" && referenceSpaceType !== "unbounded") { - logger_Logger.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode"); - } - // make sure that the session mode is supported - try { - await this.sessionManager.initializeSessionAsync(sessionMode, sessionCreationOptions); - await this.sessionManager.setReferenceSpaceTypeAsync(referenceSpaceType); - const baseLayer = await renderTarget.initializeXRLayerAsync(this.sessionManager.session); - const xrRenderState = { - // if maxZ is 0 it should be "Infinity", but it doesn't work with the WebXR API. Setting to a large number. - depthFar: this.camera.maxZ || 10000, - depthNear: this.camera.minZ, - }; - // The layers feature will have already initialized the xr session's layers on session init. - if (!this.featuresManager.getEnabledFeature(webXRFeaturesManager_WebXRFeatureName.LAYERS)) { - xrRenderState.baseLayer = baseLayer; - } - this.sessionManager.updateRenderState(xrRenderState); - // run the render loop - this.sessionManager.runXRRenderLoop(); - // Cache pre xr scene settings - this._originalSceneAutoClear = this._scene.autoClear; - this._nonVRCamera = this._scene.activeCamera; - this._attachedToElement = !!((_b = (_a = this._nonVRCamera) === null || _a === void 0 ? void 0 : _a.inputs) === null || _b === void 0 ? void 0 : _b.attachedToElement); - (_c = this._nonVRCamera) === null || _c === void 0 ? void 0 : _c.detachControl(); - this._scene.activeCamera = this.camera; - // do not compensate when AR session is used - if (sessionMode !== "immersive-ar") { - this._nonXRToXRCamera(); - } - else { - // Kept here, TODO - check if needed - this._scene.autoClear = false; - this.camera.compensateOnFirstFrame = false; - // reset the camera's position to the origin - this.camera.position.set(0, 0, 0); - this.camera.rotationQuaternion.set(0, 0, 0, 1); - this.onInitialXRPoseSetObservable.notifyObservers(this.camera); - } - this.sessionManager.onXRSessionEnded.addOnce(() => { - // when using the back button and not the exit button (default on mobile), the session is ending but the EXITING state was not set - if (this.state !== WebXRState.EXITING_XR) { - this._setState(WebXRState.EXITING_XR); - } - // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends - this.camera.rigCameras.forEach((c) => { - c.outputRenderTarget = null; - }); - // Restore scene settings - this._scene.autoClear = this._originalSceneAutoClear; - this._scene.activeCamera = this._nonVRCamera; - if (this._attachedToElement && this._nonVRCamera) { - this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault); - } - if (sessionMode !== "immersive-ar" && this.camera.compensateOnFirstFrame) { - if (this._nonVRCamera.setPosition) { - this._nonVRCamera.setPosition(this.camera.position); - } - else { - this._nonVRCamera.position.copyFrom(this.camera.position); - } - } - this._setState(WebXRState.NOT_IN_XR); - }); - // Wait until the first frame arrives before setting state to in xr - this.sessionManager.onXRFrameObservable.addOnce(() => { - this._setState(WebXRState.IN_XR); - }); - return this.sessionManager; - } - catch (e) { - console.log(e); - console.log(e.message); - this._setState(WebXRState.NOT_IN_XR); - throw e; - } - } - /** - * Exits XR mode and returns the scene to its original state - * @returns promise that resolves after xr mode has exited - */ - exitXRAsync() { - // only exit if state is IN_XR - if (this.state !== WebXRState.IN_XR) { - return Promise.resolve(); - } - this._setState(WebXRState.EXITING_XR); - return this.sessionManager.exitXRAsync(); - } - /** - * Enable spectator mode for desktop VR experiences. - * When spectator mode is enabled a camera will be attached to the desktop canvas and will - * display the first rig camera's view on the desktop canvas. - * Please note that this will degrade performance, as it requires another camera render. - * It is also not recommended to enable this in devices like the quest, as it brings no benefit there. - * @param options giving WebXRSpectatorModeOption for specutator camera to setup when the spectator mode is enabled. - */ - enableSpectatorMode(options) { - if (!this._spectatorMode) { - this._spectatorMode = true; - this._switchSpectatorMode(options); - } - } - /** - * Disable spectator mode for desktop VR experiences. - */ - disableSpecatatorMode() { - if (this._spectatorMode) { - this._spectatorMode = false; - this._switchSpectatorMode(); - } - } - _switchSpectatorMode(options) { - const fps = (options === null || options === void 0 ? void 0 : options.fps) ? options.fps : 1000.0; - const refreshRate = (1.0 / fps) * 1000.0; - const cameraIndex = (options === null || options === void 0 ? void 0 : options.preferredCameraIndex) ? options === null || options === void 0 ? void 0 : options.preferredCameraIndex : 0; - const updateSpectatorCamera = () => { - if (this._spectatorCamera) { - const delta = this.sessionManager.currentTimestamp - this._lastTimestamp; - if (delta >= refreshRate) { - this._lastTimestamp = this.sessionManager.currentTimestamp; - this._spectatorCamera.position.copyFrom(this.camera.rigCameras[cameraIndex].globalPosition); - this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[cameraIndex].absoluteRotation); - } - } - }; - if (this._spectatorMode) { - if (cameraIndex >= this.camera.rigCameras.length) { - throw new Error("the preferred camera index is beyond the length of rig camera array."); - } - const onStateChanged = () => { - if (this.state === WebXRState.IN_XR) { - this._spectatorCamera = new universalCamera_UniversalCamera("webxr-spectator", math_vector_Vector3.Zero(), this._scene); - this._spectatorCamera.rotationQuaternion = new math_vector_Quaternion(); - this._scene.activeCameras = [this.camera, this._spectatorCamera]; - this.sessionManager.onXRFrameObservable.add(updateSpectatorCamera); - this._scene.onAfterRenderCameraObservable.add((camera) => { - if (camera === this.camera) { - // reset the dimensions object for correct resizing - this._scene.getEngine().framebufferDimensionsObject = null; - } - }); - } - else if (this.state === WebXRState.EXITING_XR) { - this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera); - this._scene.activeCameras = null; - } - }; - this.onStateChangedObservable.add(onStateChanged); - onStateChanged(); - } - else { - this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera); - this._scene.activeCameras = [this.camera]; - } - } - _nonXRToXRCamera() { - this.camera.setTransformationFromNonVRCamera(this._nonVRCamera); - this.onInitialXRPoseSetObservable.notifyObservers(this.camera); - } - _setState(val) { - if (this.state === val) { - return; - } - this.state = val; - this.onStateChangedObservable.notifyObservers(this.state); - } -} -//# sourceMappingURL=webXRExperienceHelper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/motionController/webXRControllerComponent.js - -/** - * This class represents a single component (for example button or thumbstick) of a motion controller - */ -class WebXRControllerComponent { - /** - * Creates a new component for a motion controller. - * It is created by the motion controller itself - * - * @param id the id of this component - * @param type the type of the component - * @param _buttonIndex index in the buttons array of the gamepad - * @param _axesIndices indices of the values in the axes array of the gamepad - */ - constructor( - /** - * the id of this component - */ - id, - /** - * the type of the component - */ - type, _buttonIndex = -1, _axesIndices = []) { - this.id = id; - this.type = type; - this._buttonIndex = _buttonIndex; - this._axesIndices = _axesIndices; - this._axes = { - x: 0, - y: 0, - }; - this._changes = {}; - this._currentValue = 0; - this._hasChanges = false; - this._pressed = false; - this._touched = false; - /** - * If axes are available for this component (like a touchpad or thumbstick) the observers will be notified when - * the axes data changes - */ - this.onAxisValueChangedObservable = new observable_Observable(); - /** - * Observers registered here will be triggered when the state of a button changes - * State change is either pressed / touched / value - */ - this.onButtonStateChangedObservable = new observable_Observable(); - } - /** - * The current axes data. If this component has no axes it will still return an object { x: 0, y: 0 } - */ - get axes() { - return this._axes; - } - /** - * Get the changes. Elements will be populated only if they changed with their previous and current value - */ - get changes() { - return this._changes; - } - /** - * Return whether or not the component changed the last frame - */ - get hasChanges() { - return this._hasChanges; - } - /** - * is the button currently pressed - */ - get pressed() { - return this._pressed; - } - /** - * is the button currently touched - */ - get touched() { - return this._touched; - } - /** - * Get the current value of this component - */ - get value() { - return this._currentValue; - } - /** - * Dispose this component - */ - dispose() { - this.onAxisValueChangedObservable.clear(); - this.onButtonStateChangedObservable.clear(); - } - /** - * Are there axes correlating to this component - * @returns true is axes data is available - */ - isAxes() { - return this._axesIndices.length !== 0; - } - /** - * Is this component a button (hence - pressable) - * @returns true if can be pressed - */ - isButton() { - return this._buttonIndex !== -1; - } - /** - * update this component using the gamepad object it is in. Called on every frame - * @param nativeController the native gamepad controller object - */ - update(nativeController) { - let buttonUpdated = false; - let axesUpdate = false; - this._hasChanges = false; - this._changes = {}; - if (this.isButton()) { - const button = nativeController.buttons[this._buttonIndex]; - // defensive, in case a profile was forced - if (!button) { - return; - } - if (this._currentValue !== button.value) { - this.changes.value = { - current: button.value, - previous: this._currentValue, - }; - buttonUpdated = true; - this._currentValue = button.value; - } - if (this._touched !== button.touched) { - this.changes.touched = { - current: button.touched, - previous: this._touched, - }; - buttonUpdated = true; - this._touched = button.touched; - } - if (this._pressed !== button.pressed) { - this.changes.pressed = { - current: button.pressed, - previous: this._pressed, - }; - buttonUpdated = true; - this._pressed = button.pressed; - } - } - if (this.isAxes()) { - if (this._axes.x !== nativeController.axes[this._axesIndices[0]]) { - this.changes.axes = { - current: { - x: nativeController.axes[this._axesIndices[0]], - y: this._axes.y, - }, - previous: { - x: this._axes.x, - y: this._axes.y, - }, - }; - this._axes.x = nativeController.axes[this._axesIndices[0]]; - axesUpdate = true; - } - if (this._axes.y !== nativeController.axes[this._axesIndices[1]]) { - if (this.changes.axes) { - this.changes.axes.current.y = nativeController.axes[this._axesIndices[1]]; - } - else { - this.changes.axes = { - current: { - x: this._axes.x, - y: nativeController.axes[this._axesIndices[1]], - }, - previous: { - x: this._axes.x, - y: this._axes.y, - }, - }; - } - this._axes.y = nativeController.axes[this._axesIndices[1]]; - axesUpdate = true; - } - } - if (buttonUpdated) { - this._hasChanges = true; - this.onButtonStateChangedObservable.notifyObservers(this); - } - if (axesUpdate) { - this._hasChanges = true; - this.onAxisValueChangedObservable.notifyObservers(this._axes); - } - } -} -/** - * button component type - */ -WebXRControllerComponent.BUTTON_TYPE = "button"; -/** - * squeeze component type - */ -WebXRControllerComponent.SQUEEZE_TYPE = "squeeze"; -/** - * Thumbstick component type - */ -WebXRControllerComponent.THUMBSTICK_TYPE = "thumbstick"; -/** - * Touchpad component type - */ -WebXRControllerComponent.TOUCHPAD_TYPE = "touchpad"; -/** - * trigger component type - */ -WebXRControllerComponent.TRIGGER_TYPE = "trigger"; -//# sourceMappingURL=webXRControllerComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/motionController/webXRAbstractMotionController.js - - - - - - -/** - * An Abstract Motion controller - * This class receives an xrInput and a profile layout and uses those to initialize the components - * Each component has an observable to check for changes in value and state - */ -class WebXRAbstractMotionController { - /** - * constructs a new abstract motion controller - * @param scene the scene to which the model of the controller will be added - * @param layout The profile layout to load - * @param gamepadObject The gamepad object correlating to this controller - * @param handedness handedness (left/right/none) of this controller - * @param _doNotLoadControllerMesh set this flag to ignore the mesh loading - * @param _controllerCache a cache holding controller models already loaded in this session - */ - constructor( - // eslint-disable-next-line @typescript-eslint/naming-convention - scene, - // eslint-disable-next-line @typescript-eslint/naming-convention - layout, - /** - * The gamepad object correlating to this controller - */ - gamepadObject, - /** - * handedness (left/right/none) of this controller - */ - handedness, - /** - * @internal - */ - _doNotLoadControllerMesh = false, _controllerCache) { - this.scene = scene; - this.layout = layout; - this.gamepadObject = gamepadObject; - this.handedness = handedness; - this._doNotLoadControllerMesh = _doNotLoadControllerMesh; - this._controllerCache = _controllerCache; - this._initComponent = (id) => { - if (!id) { - return; - } - const componentDef = this.layout.components[id]; - const type = componentDef.type; - const buttonIndex = componentDef.gamepadIndices.button; - // search for axes - const axes = []; - if (componentDef.gamepadIndices.xAxis !== undefined && componentDef.gamepadIndices.yAxis !== undefined) { - axes.push(componentDef.gamepadIndices.xAxis, componentDef.gamepadIndices.yAxis); - } - this.components[id] = new WebXRControllerComponent(id, type, buttonIndex, axes); - }; - this._modelReady = false; - /** - * A map of components (WebXRControllerComponent) in this motion controller - * Components have a ComponentType and can also have both button and axis definitions - */ - this.components = {}; - /** - * Disable the model's animation. Can be set at any time. - */ - this.disableAnimation = false; - /** - * Observers registered here will be triggered when the model of this controller is done loading - */ - this.onModelLoadedObservable = new observable_Observable(); - // initialize the components - if (layout.components) { - Object.keys(layout.components).forEach(this._initComponent); - } - // Model is loaded in WebXRInput - } - /** - * Dispose this controller, the model mesh and all its components - */ - dispose() { - this.getComponentIds().forEach((id) => this.getComponent(id).dispose()); - if (this.rootMesh) { - this.rootMesh.getChildren(undefined, true).forEach((node) => { - node.setEnabled(false); - }); - this.rootMesh.dispose(!!this._controllerCache, !this._controllerCache); - } - } - /** - * Returns all components of specific type - * @param type the type to search for - * @returns an array of components with this type - */ - getAllComponentsOfType(type) { - return this.getComponentIds() - .map((id) => this.components[id]) - .filter((component) => component.type === type); - } - /** - * get a component based an its component id as defined in layout.components - * @param id the id of the component - * @returns the component correlates to the id or undefined if not found - */ - getComponent(id) { - return this.components[id]; - } - /** - * Get the list of components available in this motion controller - * @returns an array of strings correlating to available components - */ - getComponentIds() { - return Object.keys(this.components); - } - /** - * Get the first component of specific type - * @param type type of component to find - * @returns a controller component or null if not found - */ - getComponentOfType(type) { - return this.getAllComponentsOfType(type)[0] || null; - } - /** - * Get the main (Select) component of this controller as defined in the layout - * @returns the main component of this controller - */ - getMainComponent() { - return this.getComponent(this.layout.selectComponentId); - } - /** - * Loads the model correlating to this controller - * When the mesh is loaded, the onModelLoadedObservable will be triggered - * @returns A promise fulfilled with the result of the model loading - */ - async loadModel() { - const useGeneric = !this._getModelLoadingConstraints(); - let loadingParams = this._getGenericFilenameAndPath(); - // Checking if GLB loader is present - if (useGeneric) { - logger_Logger.Warn("Falling back to generic models"); - } - else { - loadingParams = this._getFilenameAndPath(); - } - return new Promise((resolve, reject) => { - const meshesLoaded = (meshes) => { - if (useGeneric) { - this._getGenericParentMesh(meshes); - } - else { - this._setRootMesh(meshes); - } - this._processLoadedModel(meshes); - this._modelReady = true; - this.onModelLoadedObservable.notifyObservers(this); - resolve(true); - }; - if (this._controllerCache) { - // look for it in the cache - const found = this._controllerCache.filter((c) => { - return c.filename === loadingParams.filename && c.path === loadingParams.path; - }); - if (found[0]) { - found[0].meshes.forEach((mesh) => mesh.setEnabled(true)); - meshesLoaded(found[0].meshes); - return; - // found, don't continue to load - } - } - sceneLoader_SceneLoader.ImportMesh("", loadingParams.path, loadingParams.filename, this.scene, (meshes) => { - if (this._controllerCache) { - this._controllerCache.push(Object.assign(Object.assign({}, loadingParams), { meshes })); - } - meshesLoaded(meshes); - }, null, (_scene, message) => { - logger_Logger.Log(message); - logger_Logger.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${loadingParams.path}${loadingParams.filename}`); - reject(message); - }); - }); - } - /** - * Update this model using the current XRFrame - * @param xrFrame the current xr frame to use and update the model - */ - updateFromXRFrame(xrFrame) { - this.getComponentIds().forEach((id) => this.getComponent(id).update(this.gamepadObject)); - this.updateModel(xrFrame); - } - /** - * Backwards compatibility due to a deeply-integrated typo - */ - get handness() { - return this.handedness; - } - /** - * Pulse (vibrate) this controller - * If the controller does not support pulses, this function will fail silently and return Promise<false> directly after called - * Consecutive calls to this function will cancel the last pulse call - * - * @param value the strength of the pulse in 0.0...1.0 range - * @param duration Duration of the pulse in milliseconds - * @param hapticActuatorIndex optional index of actuator (will usually be 0) - * @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 - */ - pulse(value, duration, hapticActuatorIndex = 0) { - if (this.gamepadObject.hapticActuators && this.gamepadObject.hapticActuators[hapticActuatorIndex]) { - return this.gamepadObject.hapticActuators[hapticActuatorIndex].pulse(value, duration); - } - else { - return Promise.resolve(false); - } - } - // Look through all children recursively. This will return null if no mesh exists with the given name. - _getChildByName(node, name) { - return node.getChildren((n) => n.name === name, false)[0]; - } - // Look through only immediate children. This will return null if no mesh exists with the given name. - _getImmediateChildByName(node, name) { - return node.getChildren((n) => n.name == name, true)[0]; - } - /** - * Moves the axis on the controller mesh based on its current state - * @param axisMap - * @param axisValue the value of the axis which determines the meshes new position - * @internal - */ - _lerpTransform(axisMap, axisValue, fixValueCoordinates) { - if (!axisMap.minMesh || !axisMap.maxMesh || !axisMap.valueMesh) { - return; - } - if (!axisMap.minMesh.rotationQuaternion || !axisMap.maxMesh.rotationQuaternion || !axisMap.valueMesh.rotationQuaternion) { - return; - } - // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1) - const lerpValue = fixValueCoordinates ? axisValue * 0.5 + 0.5 : axisValue; - math_vector_Quaternion.SlerpToRef(axisMap.minMesh.rotationQuaternion, axisMap.maxMesh.rotationQuaternion, lerpValue, axisMap.valueMesh.rotationQuaternion); - math_vector_Vector3.LerpToRef(axisMap.minMesh.position, axisMap.maxMesh.position, lerpValue, axisMap.valueMesh.position); - } - /** - * Update the model itself with the current frame data - * @param xrFrame the frame to use for updating the model mesh - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - updateModel(xrFrame) { - if (!this._modelReady) { - return; - } - this._updateModel(xrFrame); - } - _getGenericFilenameAndPath() { - return { - filename: "generic.babylon", - path: "https://controllers.babylonjs.com/generic/", - }; - } - _getGenericParentMesh(meshes) { - this.rootMesh = new mesh_Mesh(this.profileId + " " + this.handedness, this.scene); - meshes.forEach((mesh) => { - if (!mesh.parent) { - mesh.isPickable = false; - mesh.setParent(this.rootMesh); - } - }); - this.rootMesh.rotationQuaternion = math_vector_Quaternion.FromEulerAngles(0, Math.PI, 0); - } -} -//# sourceMappingURL=webXRAbstractMotionController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/motionController/webXRGenericMotionController.js - - - -/** - * A generic trigger-only motion controller for WebXR - */ -class WebXRGenericTriggerMotionController extends WebXRAbstractMotionController { - constructor(scene, gamepadObject, handedness) { - super(scene, GenericTriggerLayout[handedness], gamepadObject, handedness); - this.profileId = WebXRGenericTriggerMotionController.ProfileId; - } - _getFilenameAndPath() { - return { - filename: "generic.babylon", - path: "https://controllers.babylonjs.com/generic/", - }; - } - _getModelLoadingConstraints() { - return true; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _processLoadedModel(meshes) { - // nothing to do - } - _setRootMesh(meshes) { - this.rootMesh = new mesh_Mesh(this.profileId + " " + this.handedness, this.scene); - meshes.forEach((mesh) => { - mesh.isPickable = false; - if (!mesh.parent) { - mesh.setParent(this.rootMesh); - } - }); - this.rootMesh.rotationQuaternion = math_vector_Quaternion.FromEulerAngles(0, Math.PI, 0); - } - _updateModel() { - // no-op - } -} -/** - * Static version of the profile id of this controller - */ -WebXRGenericTriggerMotionController.ProfileId = "generic-trigger"; -// https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/generic/generic-trigger-touchpad-thumbstick.json -const GenericTriggerLayout = { - left: { - selectComponentId: "xr-standard-trigger", - components: { - // eslint-disable-next-line @typescript-eslint/naming-convention - "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: { - // eslint-disable-next-line @typescript-eslint/naming-convention - "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: { - // eslint-disable-next-line @typescript-eslint/naming-convention - "xr-standard-trigger": { - type: "trigger", - gamepadIndices: { - button: 0, - }, - rootNodeName: "xr_standard_trigger", - visualResponses: {}, - }, - }, - gamepadMapping: "xr-standard", - rootNodeName: "generic-trigger-none", - assetPath: "none.glb", - }, -}; -//# sourceMappingURL=webXRGenericMotionController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/motionController/webXRProfiledMotionController.js - - - - - - - - - -/** - * A profiled motion controller has its profile loaded from an online repository. - * The class is responsible of loading the model, mapping the keys and enabling model-animations - */ -class WebXRProfiledMotionController extends WebXRAbstractMotionController { - constructor(scene, xrInput, _profile, _repositoryUrl, - // eslint-disable-next-line @typescript-eslint/naming-convention - controllerCache) { - super(scene, _profile.layouts[xrInput.handedness || "none"], xrInput.gamepad, xrInput.handedness, undefined, controllerCache); - this._repositoryUrl = _repositoryUrl; - this.controllerCache = controllerCache; - this._buttonMeshMapping = {}; - this._touchDots = {}; - this.profileId = _profile.profileId; - } - dispose() { - super.dispose(); - if (!this.controllerCache) { - Object.keys(this._touchDots).forEach((visResKey) => { - this._touchDots[visResKey].dispose(); - }); - } - } - _getFilenameAndPath() { - return { - filename: this.layout.assetPath, - path: `${this._repositoryUrl}/profiles/${this.profileId}/`, - }; - } - _getModelLoadingConstraints() { - const glbLoaded = sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb"); - if (!glbLoaded) { - logger_Logger.Warn("glTF / glb loader was not registered, using generic controller instead"); - } - return glbLoaded; - } - _processLoadedModel(_meshes) { - this.getComponentIds().forEach((type) => { - const componentInLayout = this.layout.components[type]; - this._buttonMeshMapping[type] = { - mainMesh: this._getChildByName(this.rootMesh, componentInLayout.rootNodeName), - states: {}, - }; - Object.keys(componentInLayout.visualResponses).forEach((visualResponseKey) => { - const visResponse = componentInLayout.visualResponses[visualResponseKey]; - if (visResponse.valueNodeProperty === "transform") { - this._buttonMeshMapping[type].states[visualResponseKey] = { - valueMesh: this._getChildByName(this.rootMesh, visResponse.valueNodeName), - minMesh: this._getChildByName(this.rootMesh, visResponse.minNodeName), - maxMesh: this._getChildByName(this.rootMesh, visResponse.maxNodeName), - }; - } - else { - // visibility, usually for touchpads - const nameOfMesh = componentInLayout.type === WebXRControllerComponent.TOUCHPAD_TYPE && componentInLayout.touchPointNodeName - ? componentInLayout.touchPointNodeName - : visResponse.valueNodeName; - this._buttonMeshMapping[type].states[visualResponseKey] = { - valueMesh: this._getChildByName(this.rootMesh, nameOfMesh), - }; - if (componentInLayout.type === WebXRControllerComponent.TOUCHPAD_TYPE && !this._touchDots[visualResponseKey]) { - const dot = sphereBuilder_CreateSphere(visualResponseKey + "dot", { - diameter: 0.0015, - segments: 8, - }, this.scene); - dot.material = new standardMaterial_StandardMaterial(visualResponseKey + "mat", this.scene); - dot.material.diffuseColor = math_color_Color3.Red(); - dot.parent = this._buttonMeshMapping[type].states[visualResponseKey].valueMesh || null; - dot.isVisible = false; - this._touchDots[visualResponseKey] = dot; - } - } - }); - }); - } - _setRootMesh(meshes) { - this.rootMesh = new mesh_Mesh(this.profileId + "-" + this.handedness, this.scene); - this.rootMesh.isPickable = false; - let rootMesh; - // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh' - for (let i = 0; i < meshes.length; i++) { - const mesh = meshes[i]; - mesh.isPickable = false; - if (!mesh.parent) { - // Handle root node, attach to the new parentMesh - rootMesh = mesh; - } - } - if (rootMesh) { - rootMesh.setParent(this.rootMesh); - } - if (!this.scene.useRightHandedSystem) { - this.rootMesh.rotate(math_axis_Axis.Y, Math.PI, math_axis_Space.WORLD); - } - } - _updateModel(_xrFrame) { - if (this.disableAnimation) { - return; - } - this.getComponentIds().forEach((id) => { - const component = this.getComponent(id); - if (!component.hasChanges) { - return; - } - const meshes = this._buttonMeshMapping[id]; - const componentInLayout = this.layout.components[id]; - Object.keys(componentInLayout.visualResponses).forEach((visualResponseKey) => { - const visResponse = componentInLayout.visualResponses[visualResponseKey]; - let value = component.value; - if (visResponse.componentProperty === "xAxis") { - value = component.axes.x; - } - else if (visResponse.componentProperty === "yAxis") { - value = component.axes.y; - } - if (visResponse.valueNodeProperty === "transform") { - this._lerpTransform(meshes.states[visualResponseKey], value, visResponse.componentProperty !== "button"); - } - else { - // visibility - const valueMesh = meshes.states[visualResponseKey].valueMesh; - if (valueMesh) { - valueMesh.isVisible = component.touched || component.pressed; - } - if (this._touchDots[visualResponseKey]) { - this._touchDots[visualResponseKey].isVisible = component.touched || component.pressed; - } - } - }); - }); - } -} -//# sourceMappingURL=webXRProfiledMotionController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/motionController/webXRMotionControllerManager.js - - - -/** - * The MotionController Manager manages all registered motion controllers and loads the right one when needed. - * - * When this repository is complete: https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/assets - * it should be replaced with auto-loaded controllers. - * - * When using a model try to stay as generic as possible. Eventually there will be no need in any of the controller classes - */ -const controllerCache = []; -/** - * Motion controller manager is managing the different webxr profiles and makes sure the right - * controller is being loaded. - */ -class WebXRMotionControllerManager { - /** - * Clear the cache used for profile loading and reload when requested again - */ - static ClearProfilesCache() { - this._ProfilesList = null; - this._ProfileLoadingPromises = {}; - } - /** - * Register the default fallbacks. - * This function is called automatically when this file is imported. - */ - 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"]); - } - /** - * Find a fallback profile if the profile was not found. There are a few predefined generic profiles. - * @param profileId the profile to which a fallback needs to be found - * @returns an array with corresponding fallback profiles - */ - static FindFallbackWithProfileId(profileId) { - const returnArray = this._Fallbacks[profileId] || []; - returnArray.unshift(profileId); - return returnArray; - } - /** - * When acquiring a new xrInput object (usually by the WebXRInput class), match it with the correct profile. - * The order of search: - * - * 1) Iterate the profiles array of the xr input and try finding a corresponding motion controller - * 2) (If not found) search in the gamepad id and try using it (legacy versions only) - * 3) search for registered fallbacks (should be redundant, nonetheless it makes sense to check) - * 4) return the generic trigger controller if none were found - * - * @param xrInput the xrInput to which a new controller is initialized - * @param scene the scene to which the model will be added - * @param forceProfile force a certain profile for this controller - * @returns A promise that fulfils with the motion controller class for this profile id or the generic standard class if none was found - */ - static GetMotionControllerWithXRInput(xrInput, scene, forceProfile) { - const profileArray = []; - if (forceProfile) { - profileArray.push(forceProfile); - } - profileArray.push(...(xrInput.profiles || [])); - // emulator support - if (profileArray.length && !profileArray[0]) { - // remove the first "undefined" that the emulator is adding - profileArray.pop(); - } - // legacy support - try using the gamepad id - if (xrInput.gamepad && xrInput.gamepad.id) { - switch (xrInput.gamepad.id) { - case xrInput.gamepad.id.match(/oculus touch/gi) ? xrInput.gamepad.id : undefined: - // oculus in gamepad id - profileArray.push("oculus-touch-v2"); - break; - } - } - // make sure microsoft/windows mixed reality works correctly - const windowsMRIdx = profileArray.indexOf("windows-mixed-reality"); - if (windowsMRIdx !== -1) { - profileArray.splice(windowsMRIdx, 0, "microsoft-mixed-reality"); - } - if (!profileArray.length) { - profileArray.push("generic-trigger"); - } - if (this.UseOnlineRepository) { - const firstFunction = this.PrioritizeOnlineRepository ? this._LoadProfileFromRepository : this._LoadProfilesFromAvailableControllers; - const secondFunction = this.PrioritizeOnlineRepository ? this._LoadProfilesFromAvailableControllers : this._LoadProfileFromRepository; - return firstFunction.call(this, profileArray, xrInput, scene).catch(() => { - return secondFunction.call(this, profileArray, xrInput, scene); - }); - } - else { - // use only available functions - return this._LoadProfilesFromAvailableControllers(profileArray, xrInput, scene); - } - } - /** - * Register a new controller based on its profile. This function will be called by the controller classes themselves. - * - * If you are missing a profile, make sure it is imported in your source, otherwise it will not register. - * - * @param type the profile type to register - * @param constructFunction the function to be called when loading this profile - */ - static RegisterController(type, constructFunction) { - this._AvailableControllers[type] = constructFunction; - } - /** - * Register a fallback to a specific profile. - * @param profileId the profileId that will receive the fallbacks - * @param fallbacks A list of fallback profiles - */ - static RegisterFallbacksForProfileId(profileId, fallbacks) { - if (this._Fallbacks[profileId]) { - this._Fallbacks[profileId].push(...fallbacks); - } - else { - this._Fallbacks[profileId] = fallbacks; - } - } - /** - * Will update the list of profiles available in the repository - * @returns a promise that resolves to a map of profiles available online - */ - static UpdateProfilesList() { - this._ProfilesList = tools_Tools.LoadFileAsync(this.BaseRepositoryUrl + "/profiles/profilesList.json", false).then((data) => { - return JSON.parse(data.toString()); - }); - return this._ProfilesList; - } - /** - * Clear the controller's cache (usually happens at the end of a session) - */ - static ClearControllerCache() { - controllerCache.forEach((cacheItem) => { - cacheItem.meshes.forEach((mesh) => { - mesh.dispose(false, true); - }); - }); - controllerCache.length = 0; - } - static _LoadProfileFromRepository(profileArray, xrInput, scene) { - return Promise.resolve() - .then(() => { - if (!this._ProfilesList) { - return this.UpdateProfilesList(); - } - else { - return this._ProfilesList; - } - }) - .then((profilesList) => { - // load the right profile - for (let i = 0; i < profileArray.length; ++i) { - // defensive - if (!profileArray[i]) { - continue; - } - if (profilesList[profileArray[i]]) { - return profileArray[i]; - } - } - throw new Error(`neither controller ${profileArray[0]} nor all fallbacks were found in the repository,`); - }) - .then((profileToLoad) => { - // load the profile - if (!this._ProfileLoadingPromises[profileToLoad]) { - this._ProfileLoadingPromises[profileToLoad] = tools_Tools.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${profileToLoad}/profile.json`, false).then((data) => JSON.parse(data)); - } - return this._ProfileLoadingPromises[profileToLoad]; - }) - .then((profile) => { - return new WebXRProfiledMotionController(scene, xrInput, profile, this.BaseRepositoryUrl, this.DisableControllerCache ? undefined : controllerCache); - }); - } - static _LoadProfilesFromAvailableControllers(profileArray, xrInput, scene) { - // check fallbacks - for (let i = 0; i < profileArray.length; ++i) { - // defensive - if (!profileArray[i]) { - continue; - } - const fallbacks = this.FindFallbackWithProfileId(profileArray[i]); - for (let j = 0; j < fallbacks.length; ++j) { - const constructionFunction = this._AvailableControllers[fallbacks[j]]; - if (constructionFunction) { - return Promise.resolve(constructionFunction(xrInput, scene)); - } - } - } - throw new Error(`no controller requested was found in the available controllers list`); - } -} -WebXRMotionControllerManager._AvailableControllers = {}; -WebXRMotionControllerManager._Fallbacks = {}; -// cache for loading -WebXRMotionControllerManager._ProfileLoadingPromises = {}; -/** - * The base URL of the online controller repository. Can be changed at any time. - */ -WebXRMotionControllerManager.BaseRepositoryUrl = "https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist"; -/** - * Which repository gets priority - local or online - */ -WebXRMotionControllerManager.PrioritizeOnlineRepository = true; -/** - * Use the online repository, or use only locally-defined controllers - */ -WebXRMotionControllerManager.UseOnlineRepository = true; -/** - * Disable the controller cache and load the models each time a new WebXRProfileMotionController is loaded. - * Defaults to true. - */ -WebXRMotionControllerManager.DisableControllerCache = true; -// register the generic profile(s) here so we will at least have them -WebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId, (xrInput, scene) => { - return new WebXRGenericTriggerMotionController(scene, xrInput.gamepad, xrInput.handedness); -}); -// register fallbacks -WebXRMotionControllerManager.DefaultFallbacks(); -//# sourceMappingURL=webXRMotionControllerManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRInputSource.js - - - - - -let idCount = 0; -/** - * Represents an XR controller - */ -class WebXRInputSource { - /** - * Creates the input source object - * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRInputControllerSupport - * @param _scene the scene which the controller should be associated to - * @param inputSource the underlying input source for the controller - * @param _options options for this controller creation - */ - constructor(_scene, - /** The underlying input source for the controller */ - inputSource, _options = {}) { - this._scene = _scene; - this.inputSource = inputSource; - this._options = _options; - this._tmpVector = new math_vector_Vector3(); - this._disposed = false; - /** - * Event that fires when the controller is removed/disposed. - * The object provided as event data is this controller, after associated assets were disposed. - * uniqueId is still available. - */ - this.onDisposeObservable = new observable_Observable(); - /** - * Will be triggered when the mesh associated with the motion controller is done loading. - * It is also possible that this will never trigger (!) if no mesh was loaded, or if the developer decides to load a different mesh - * A shortened version of controller -> motion controller -> on mesh loaded. - */ - this.onMeshLoadedObservable = new observable_Observable(); - /** - * Observers registered here will trigger when a motion controller profile was assigned to this xr controller - */ - this.onMotionControllerInitObservable = new observable_Observable(); - this._uniqueId = `controller-${idCount++}-${inputSource.targetRayMode}-${inputSource.handedness}`; - this.pointer = new abstractMesh_AbstractMesh(`${this._uniqueId}-pointer`, _scene); - this.pointer.rotationQuaternion = new math_vector_Quaternion(); - if (this.inputSource.gripSpace) { - this.grip = new abstractMesh_AbstractMesh(`${this._uniqueId}-grip`, this._scene); - this.grip.rotationQuaternion = new math_vector_Quaternion(); - } - this._tmpVector.set(0, 0, this._scene.useRightHandedSystem ? -1.0 : 1.0); - // for now only load motion controllers if gamepad object available - if (this.inputSource.gamepad && this.inputSource.targetRayMode === "tracked-pointer") { - WebXRMotionControllerManager.GetMotionControllerWithXRInput(inputSource, _scene, this._options.forceControllerProfile).then((motionController) => { - this.motionController = motionController; - this.onMotionControllerInitObservable.notifyObservers(motionController); - // should the model be loaded? - if (!this._options.doNotLoadControllerMesh && !this.motionController._doNotLoadControllerMesh) { - this.motionController.loadModel().then((success) => { - var _a; - if (success && this.motionController && this.motionController.rootMesh) { - if (this._options.renderingGroupId) { - // anything other than 0? - this.motionController.rootMesh.renderingGroupId = this._options.renderingGroupId; - this.motionController.rootMesh.getChildMeshes(false).forEach((mesh) => (mesh.renderingGroupId = this._options.renderingGroupId)); - } - this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh); - this.motionController.rootMesh.parent = this.grip || this.pointer; - this.motionController.disableAnimation = !!this._options.disableMotionControllerAnimation; - } - // make sure to dispose is the controller is already disposed - if (this._disposed) { - (_a = this.motionController) === null || _a === void 0 ? void 0 : _a.dispose(); - } - }); - } - }, () => { - tools_Tools.Warn(`Could not find a matching motion controller for the registered input source`); - }); - } - } - /** - * Get this controllers unique id - */ - get uniqueId() { - return this._uniqueId; - } - /** - * Disposes of the object - */ - dispose() { - if (this.grip) { - this.grip.dispose(true); - } - if (this.motionController) { - this.motionController.dispose(); - } - this.pointer.dispose(true); - this.onMotionControllerInitObservable.clear(); - this.onMeshLoadedObservable.clear(); - this.onDisposeObservable.notifyObservers(this); - this.onDisposeObservable.clear(); - this._disposed = true; - } - /** - * Gets a world space ray coming from the pointer or grip - * @param result the resulting ray - * @param gripIfAvailable use the grip mesh instead of the pointer, if available - */ - getWorldPointerRayToRef(result, gripIfAvailable = false) { - const object = gripIfAvailable && this.grip ? this.grip : this.pointer; - math_vector_Vector3.TransformNormalToRef(this._tmpVector, object.getWorldMatrix(), result.direction); - result.direction.normalize(); - result.origin.copyFrom(object.absolutePosition); - result.length = 1000; - } - /** - * Updates the controller pose based on the given XRFrame - * @param xrFrame xr frame to update the pose with - * @param referenceSpace reference space to use - * @param xrCamera the xr camera, used for parenting - */ - updateFromXRFrame(xrFrame, referenceSpace, xrCamera) { - const pose = xrFrame.getPose(this.inputSource.targetRaySpace, referenceSpace); - this._lastXRPose = pose; - // Update the pointer mesh - if (pose) { - const pos = pose.transform.position; - this.pointer.position.set(pos.x, pos.y, pos.z); - const orientation = pose.transform.orientation; - this.pointer.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w); - if (!this._scene.useRightHandedSystem) { - this.pointer.position.z *= -1; - this.pointer.rotationQuaternion.z *= -1; - this.pointer.rotationQuaternion.w *= -1; - } - this.pointer.parent = xrCamera.parent; - } - // Update the grip mesh if it exists - if (this.inputSource.gripSpace && this.grip) { - const pose = xrFrame.getPose(this.inputSource.gripSpace, referenceSpace); - if (pose) { - const pos = pose.transform.position; - const orientation = pose.transform.orientation; - this.grip.position.set(pos.x, pos.y, pos.z); - this.grip.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w); - if (!this._scene.useRightHandedSystem) { - this.grip.position.z *= -1; - this.grip.rotationQuaternion.z *= -1; - this.grip.rotationQuaternion.w *= -1; - } - } - this.grip.parent = xrCamera.parent; - } - if (this.motionController) { - // either update buttons only or also position, if in gamepad mode - this.motionController.updateFromXRFrame(xrFrame); - } - } -} -//# sourceMappingURL=webXRInputSource.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRInput.js - - - -/** - * XR input used to track XR inputs such as controllers/rays - */ -class WebXRInput { - /** - * Initializes the WebXRInput - * @param xrSessionManager the xr session manager for this session - * @param xrCamera the WebXR camera for this session. Mainly used for teleportation - * @param _options = initialization options for this xr input - */ - constructor( - /** - * the xr session manager for this session - */ - xrSessionManager, - /** - * the WebXR camera for this session. Mainly used for teleportation - */ - xrCamera, _options = {}) { - this.xrSessionManager = xrSessionManager; - this.xrCamera = xrCamera; - this._options = _options; - /** - * XR controllers being tracked - */ - this.controllers = []; - /** - * Event when a controller has been connected/added - */ - this.onControllerAddedObservable = new observable_Observable(); - /** - * Event when a controller has been removed/disconnected - */ - this.onControllerRemovedObservable = new observable_Observable(); - this._onInputSourcesChange = (event) => { - this._addAndRemoveControllers(event.added, event.removed); - }; - // Remove controllers when exiting XR - this._sessionEndedObserver = this.xrSessionManager.onXRSessionEnded.add(() => { - this._addAndRemoveControllers([], this.controllers.map((c) => { - return c.inputSource; - })); - }); - this._sessionInitObserver = this.xrSessionManager.onXRSessionInit.add((session) => { - session.addEventListener("inputsourceschange", this._onInputSourcesChange); - }); - this._frameObserver = this.xrSessionManager.onXRFrameObservable.add((frame) => { - // Update controller pose info - this.controllers.forEach((controller) => { - controller.updateFromXRFrame(frame, this.xrSessionManager.referenceSpace, this.xrCamera); - }); - }); - if (this._options.customControllersRepositoryURL) { - WebXRMotionControllerManager.BaseRepositoryUrl = this._options.customControllersRepositoryURL; - } - WebXRMotionControllerManager.UseOnlineRepository = !this._options.disableOnlineControllerRepository; - if (WebXRMotionControllerManager.UseOnlineRepository) { - // pre-load the profiles list to load the controllers quicker afterwards - try { - WebXRMotionControllerManager.UpdateProfilesList().catch(() => { - WebXRMotionControllerManager.UseOnlineRepository = false; - }); - } - catch (e) { - WebXRMotionControllerManager.UseOnlineRepository = false; - } - } - } - _addAndRemoveControllers(addInputs, removeInputs) { - // Add controllers if they don't already exist - const sources = this.controllers.map((c) => { - return c.inputSource; - }); - for (const input of addInputs) { - if (sources.indexOf(input) === -1) { - 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 })); - this.controllers.push(controller); - this.onControllerAddedObservable.notifyObservers(controller); - } - } - // Remove and dispose of controllers to be disposed - const keepControllers = []; - const removedControllers = []; - this.controllers.forEach((c) => { - if (removeInputs.indexOf(c.inputSource) === -1) { - keepControllers.push(c); - } - else { - removedControllers.push(c); - } - }); - this.controllers = keepControllers; - removedControllers.forEach((c) => { - this.onControllerRemovedObservable.notifyObservers(c); - c.dispose(); - }); - } - /** - * Disposes of the object - */ - dispose() { - this.controllers.forEach((c) => { - c.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(); - // clear the controller cache - WebXRMotionControllerManager.ClearControllerCache(); - } -} -//# sourceMappingURL=webXRInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRControllerPointerSelection.js - - - - - - - - - - - - - -/** - * A module that will enable pointer selection for motion controllers of XR Input Sources - */ -class WebXRControllerPointerSelection extends WebXRAbstractFeature { - /** - * constructs a new background remover module - * @param _xrSessionManager the session manager for this module - * @param _options read-only options to be used in this module - */ - constructor(_xrSessionManager, _options) { - super(_xrSessionManager); - this._options = _options; - this._attachController = (xrController) => { - if (this._controllers[xrController.uniqueId]) { - // already attached - return; - } - const { laserPointer, selectionMesh } = this._generateNewMeshPair(xrController.pointer); - // get two new meshes - this._controllers[xrController.uniqueId] = { - xrController, - laserPointer, - selectionMesh, - meshUnderPointer: null, - pick: null, - tmpRay: new ray_Ray(new math_vector_Vector3(), new math_vector_Vector3()), - disabledByNearInteraction: false, - id: WebXRControllerPointerSelection._IdCounter++, - }; - if (this._attachedController) { - if (!this._options.enablePointerSelectionOnAllControllers && - this._options.preferredHandedness && - xrController.inputSource.handedness === this._options.preferredHandedness) { - this._attachedController = xrController.uniqueId; - } - } - else { - if (!this._options.enablePointerSelectionOnAllControllers) { - this._attachedController = xrController.uniqueId; - } - } - switch (xrController.inputSource.targetRayMode) { - case "tracked-pointer": - return this._attachTrackedPointerRayMode(xrController); - case "gaze": - return this._attachGazeMode(xrController); - case "screen": - return this._attachScreenRayMode(xrController); - } - }; - this._controllers = {}; - this._tmpVectorForPickCompare = new math_vector_Vector3(); - /** - * Disable lighting on the laser pointer (so it will always be visible) - */ - this.disablePointerLighting = true; - /** - * Disable lighting on the selection mesh (so it will always be visible) - */ - this.disableSelectionMeshLighting = true; - /** - * Should the laser pointer be displayed - */ - this.displayLaserPointer = true; - /** - * Should the selection mesh be displayed (The ring at the end of the laser pointer) - */ - this.displaySelectionMesh = true; - /** - * This color will be set to the laser pointer when selection is triggered - */ - this.laserPointerPickedColor = new math_color_Color3(0.9, 0.9, 0.9); - /** - * Default color of the laser pointer - */ - this.laserPointerDefaultColor = new math_color_Color3(0.7, 0.7, 0.7); - /** - * default color of the selection ring - */ - this.selectionMeshDefaultColor = new math_color_Color3(0.8, 0.8, 0.8); - /** - * This color will be applied to the selection ring when selection is triggered - */ - this.selectionMeshPickedColor = new math_color_Color3(0.3, 0.3, 1.0); - this._identityMatrix = math_vector_Matrix.Identity(); - this._screenCoordinatesRef = math_vector_Vector3.Zero(); - this._viewportRef = new math_viewport_Viewport(0, 0, 0, 0); - this._scene = this._xrSessionManager.scene; - } - /** - * attach this feature - * Will usually be called by the features manager - * - * @returns true if successful. - */ - attach() { - if (!super.attach()) { - return false; - } - this._options.xrInput.controllers.forEach(this._attachController); - this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController); - this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => { - // REMOVE the controller - this._detachController(controller.uniqueId); - }); - this._scene.constantlyUpdateMeshUnderPointer = true; - if (this._options.gazeCamera) { - const webXRCamera = this._options.gazeCamera; - const { laserPointer, selectionMesh } = this._generateNewMeshPair(webXRCamera); - this._controllers["camera"] = { - webXRCamera, - laserPointer, - selectionMesh, - meshUnderPointer: null, - pick: null, - tmpRay: new ray_Ray(new math_vector_Vector3(), new math_vector_Vector3()), - disabledByNearInteraction: false, - id: WebXRControllerPointerSelection._IdCounter++, - }; - this._attachGazeMode(); - } - return true; - } - /** - * detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - if (!super.detach()) { - return false; - } - Object.keys(this._controllers).forEach((controllerId) => { - this._detachController(controllerId); - }); - return true; - } - /** - * Will get the mesh under a specific pointer. - * `scene.meshUnderPointer` will only return one mesh - either left or right. - * @param controllerId the controllerId to check - * @returns The mesh under pointer or null if no mesh is under the pointer - */ - getMeshUnderPointer(controllerId) { - if (this._controllers[controllerId]) { - return this._controllers[controllerId].meshUnderPointer; - } - else { - return null; - } - } - /** - * Get the xr controller that correlates to the pointer id in the pointer event - * - * @param id the pointer id to search for - * @returns the controller that correlates to this id or null if not found - */ - getXRControllerByPointerId(id) { - const keys = Object.keys(this._controllers); - for (let i = 0; i < keys.length; ++i) { - if (this._controllers[keys[i]].id === id) { - return this._controllers[keys[i]].xrController || null; - } - } - return null; - } - /** - * @internal - */ - _getPointerSelectionDisabledByPointerId(id) { - const keys = Object.keys(this._controllers); - for (let i = 0; i < keys.length; ++i) { - if (this._controllers[keys[i]].id === id) { - return this._controllers[keys[i]].disabledByNearInteraction; - } - } - return true; - } - /** - * @internal - */ - _setPointerSelectionDisabledByPointerId(id, state) { - const keys = Object.keys(this._controllers); - for (let i = 0; i < keys.length; ++i) { - if (this._controllers[keys[i]].id === id) { - this._controllers[keys[i]].disabledByNearInteraction = state; - return; - } - } - } - _onXRFrame(_xrFrame) { - Object.keys(this._controllers).forEach((id) => { - // only do this for the selected pointer - const controllerData = this._controllers[id]; - if ((!this._options.enablePointerSelectionOnAllControllers && id !== this._attachedController) || controllerData.disabledByNearInteraction) { - controllerData.selectionMesh.isVisible = false; - controllerData.laserPointer.isVisible = false; - controllerData.pick = null; - return; - } - controllerData.laserPointer.isVisible = this.displayLaserPointer; - let controllerGlobalPosition; - // Every frame check collisions/input - if (controllerData.xrController) { - controllerGlobalPosition = controllerData.xrController.pointer.position; - controllerData.xrController.getWorldPointerRayToRef(controllerData.tmpRay); - } - else if (controllerData.webXRCamera) { - controllerGlobalPosition = controllerData.webXRCamera.position; - controllerData.webXRCamera.getForwardRayToRef(controllerData.tmpRay); - } - else { - return; - } - if (this._options.maxPointerDistance) { - controllerData.tmpRay.length = this._options.maxPointerDistance; - } - // update pointerX and pointerY of the scene. Only if the flag is set to true! - if (!this._options.disableScenePointerVectorUpdate && controllerGlobalPosition) { - const scene = this._xrSessionManager.scene; - const camera = this._options.xrInput.xrCamera; - if (camera) { - camera.viewport.toGlobalToRef(scene.getEngine().getRenderWidth(), scene.getEngine().getRenderHeight(), this._viewportRef); - math_vector_Vector3.ProjectToRef(controllerGlobalPosition, this._identityMatrix, scene.getTransformMatrix(), this._viewportRef, this._screenCoordinatesRef); - // stay safe - if (typeof this._screenCoordinatesRef.x === "number" && - typeof this._screenCoordinatesRef.y === "number" && - !isNaN(this._screenCoordinatesRef.x) && - !isNaN(this._screenCoordinatesRef.y)) { - scene.pointerX = this._screenCoordinatesRef.x; - scene.pointerY = this._screenCoordinatesRef.y; - controllerData.screenCoordinates = { - x: this._screenCoordinatesRef.x, - y: this._screenCoordinatesRef.y, - }; - } - } - } - let utilityScenePick = null; - if (this._utilityLayerScene) { - utilityScenePick = this._utilityLayerScene.pickWithRay(controllerData.tmpRay, this._utilityLayerScene.pointerMovePredicate || this.raySelectionPredicate); - } - const originalScenePick = this._scene.pickWithRay(controllerData.tmpRay, this._scene.pointerMovePredicate || this.raySelectionPredicate); - if (!utilityScenePick || !utilityScenePick.hit) { - // No hit in utility scene - controllerData.pick = originalScenePick; - } - else if (!originalScenePick || !originalScenePick.hit) { - // No hit in original scene - controllerData.pick = utilityScenePick; - } - else if (utilityScenePick.distance < originalScenePick.distance) { - // Hit is closer in utility scene - controllerData.pick = utilityScenePick; - } - else { - // Hit is closer in original scene - controllerData.pick = originalScenePick; - } - if (controllerData.pick && controllerData.xrController) { - controllerData.pick.aimTransform = controllerData.xrController.pointer; - controllerData.pick.gripTransform = controllerData.xrController.grip || null; - } - const pick = controllerData.pick; - if (pick && pick.pickedPoint && pick.hit) { - // Update laser state - this._updatePointerDistance(controllerData.laserPointer, pick.distance); - // Update cursor state - controllerData.selectionMesh.position.copyFrom(pick.pickedPoint); - controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance); - controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance); - controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance); - // To avoid z-fighting - const pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), controllerData.tmpRay); - const deltaFighting = 0.001; - controllerData.selectionMesh.position.copyFrom(pick.pickedPoint); - if (pickNormal) { - const axis1 = math_vector_Vector3.Cross(math_axis_Axis.Y, pickNormal); - const axis2 = math_vector_Vector3.Cross(pickNormal, axis1); - math_vector_Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation); - controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting)); - } - controllerData.selectionMesh.isVisible = true && this.displaySelectionMesh; - controllerData.meshUnderPointer = pick.pickedMesh; - } - else { - controllerData.selectionMesh.isVisible = false; - this._updatePointerDistance(controllerData.laserPointer, 1); - controllerData.meshUnderPointer = null; - } - }); - } - get _utilityLayerScene() { - return this._options.customUtilityLayerScene || utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene; - } - _attachGazeMode(xrController) { - const controllerData = this._controllers[(xrController && xrController.uniqueId) || "camera"]; - // attached when touched, detaches when raised - const timeToSelect = this._options.timeToSelect || 3000; - const sceneToRenderTo = this._options.useUtilityLayer ? this._utilityLayerScene : this._scene; - let oldPick = new PickingInfo(); - const discMesh = CreateTorus("selection", { - diameter: 0.0035 * 15, - thickness: 0.0025 * 6, - tessellation: 20, - }, sceneToRenderTo); - discMesh.isVisible = false; - discMesh.isPickable = false; - discMesh.parent = controllerData.selectionMesh; - let timer = 0; - let downTriggered = false; - const pointerEventInit = { - pointerId: controllerData.id, - pointerType: "xr", - }; - controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => { - if (!controllerData.pick) { - return; - } - this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); - controllerData.laserPointer.material.alpha = 0; - discMesh.isVisible = false; - if (controllerData.pick.hit) { - if (!this._pickingMoved(oldPick, controllerData.pick)) { - if (timer > timeToSelect / 10) { - discMesh.isVisible = true; - } - timer += this._scene.getEngine().getDeltaTime(); - if (timer >= timeToSelect) { - this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); - // this pointerdown event is not setting the controllerData.pointerDownTriggered to avoid a pointerUp event when this feature is detached - downTriggered = true; - // pointer up right after down, if disable on touch out - if (this._options.disablePointerUpOnTouchOut) { - this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); - } - discMesh.isVisible = false; - } - else { - const scaleFactor = 1 - timer / timeToSelect; - discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor); - } - } - else { - if (downTriggered) { - if (!this._options.disablePointerUpOnTouchOut) { - this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); - } - } - downTriggered = false; - timer = 0; - } - } - else { - downTriggered = false; - timer = 0; - } - this._scene.simulatePointerMove(controllerData.pick, pointerEventInit); - oldPick = controllerData.pick; - }); - if (this._options.renderingGroupId !== undefined) { - discMesh.renderingGroupId = this._options.renderingGroupId; - } - if (xrController) { - xrController.onDisposeObservable.addOnce(() => { - if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) { - this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); - controllerData.finalPointerUpTriggered = true; - } - discMesh.dispose(); - }); - } - } - _attachScreenRayMode(xrController) { - const controllerData = this._controllers[xrController.uniqueId]; - let downTriggered = false; - const pointerEventInit = { - pointerId: controllerData.id, - pointerType: "xr", - }; - controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => { - this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); - if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) { - return; - } - if (!downTriggered) { - this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); - controllerData.pointerDownTriggered = true; - downTriggered = true; - if (this._options.disablePointerUpOnTouchOut) { - this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); - } - } - else { - this._scene.simulatePointerMove(controllerData.pick, pointerEventInit); - } - }); - xrController.onDisposeObservable.addOnce(() => { - this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); - this._xrSessionManager.runInXRFrame(() => { - if (controllerData.pick && !controllerData.finalPointerUpTriggered && downTriggered && !this._options.disablePointerUpOnTouchOut) { - this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); - controllerData.finalPointerUpTriggered = true; - } - }); - }); - } - _attachTrackedPointerRayMode(xrController) { - const controllerData = this._controllers[xrController.uniqueId]; - if (this._options.forceGazeMode) { - return this._attachGazeMode(xrController); - } - const pointerEventInit = { - pointerId: controllerData.id, - pointerType: "xr", - }; - controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => { - controllerData.laserPointer.material.disableLighting = this.disablePointerLighting; - controllerData.selectionMesh.material.disableLighting = this.disableSelectionMeshLighting; - if (controllerData.pick) { - this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); - this._scene.simulatePointerMove(controllerData.pick, pointerEventInit); - } - }); - if (xrController.inputSource.gamepad) { - const init = (motionController) => { - if (this._options.overrideButtonId) { - controllerData.selectionComponent = motionController.getComponent(this._options.overrideButtonId); - } - if (!controllerData.selectionComponent) { - controllerData.selectionComponent = motionController.getMainComponent(); - } - controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => { - if (component.changes.pressed) { - const pressed = component.changes.pressed.current; - if (controllerData.pick) { - if (this._options.enablePointerSelectionOnAllControllers || xrController.uniqueId === this._attachedController) { - this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); - if (pressed) { - this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); - controllerData.pointerDownTriggered = true; - controllerData.selectionMesh.material.emissiveColor = this.selectionMeshPickedColor; - controllerData.laserPointer.material.emissiveColor = this.laserPointerPickedColor; - } - else { - this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); - controllerData.selectionMesh.material.emissiveColor = this.selectionMeshDefaultColor; - controllerData.laserPointer.material.emissiveColor = this.laserPointerDefaultColor; - } - } - } - else { - if (pressed && !this._options.enablePointerSelectionOnAllControllers && !this._options.disableSwitchOnClick) { - this._attachedController = xrController.uniqueId; - } - } - } - }); - }; - if (xrController.motionController) { - init(xrController.motionController); - } - else { - xrController.onMotionControllerInitObservable.add(init); - } - } - else { - // use the select and squeeze events - const selectStartListener = (event) => { - this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); - if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) { - this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); - controllerData.pointerDownTriggered = true; - controllerData.selectionMesh.material.emissiveColor = this.selectionMeshPickedColor; - controllerData.laserPointer.material.emissiveColor = this.laserPointerPickedColor; - } - }; - const selectEndListener = (event) => { - this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); - if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) { - this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); - controllerData.selectionMesh.material.emissiveColor = this.selectionMeshDefaultColor; - controllerData.laserPointer.material.emissiveColor = this.laserPointerDefaultColor; - } - }; - controllerData.eventListeners = { - selectend: selectEndListener, - selectstart: selectStartListener, - }; - this._xrSessionManager.session.addEventListener("selectstart", selectStartListener); - this._xrSessionManager.session.addEventListener("selectend", selectEndListener); - } - } - _convertNormalToDirectionOfRay(normal, ray) { - if (normal) { - const angle = Math.acos(math_vector_Vector3.Dot(normal, ray.direction)); - if (angle < Math.PI / 2) { - normal.scaleInPlace(-1); - } - } - return normal; - } - _detachController(xrControllerUniqueId) { - const controllerData = this._controllers[xrControllerUniqueId]; - if (!controllerData) { - return; - } - if (controllerData.selectionComponent) { - if (controllerData.onButtonChangedObserver) { - controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver); - } - } - if (controllerData.onFrameObserver) { - this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver); - } - if (controllerData.eventListeners) { - Object.keys(controllerData.eventListeners).forEach((eventName) => { - const func = controllerData.eventListeners && controllerData.eventListeners[eventName]; - if (func) { - // For future reference - this is an issue in the WebXR typings. - this._xrSessionManager.session.removeEventListener(eventName, func); - } - }); - } - if (!controllerData.finalPointerUpTriggered && controllerData.pointerDownTriggered) { - // Stay safe and fire a pointerup, in case it wasn't already triggered - const pointerEventInit = { - pointerId: controllerData.id, - pointerType: "xr", - }; - this._xrSessionManager.runInXRFrame(() => { - this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates); - this._scene.simulatePointerUp(controllerData.pick || new PickingInfo(), pointerEventInit); - controllerData.finalPointerUpTriggered = true; - }); - } - this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(() => { - try { - controllerData.selectionMesh.dispose(); - controllerData.laserPointer.dispose(); - // remove from the map - delete this._controllers[xrControllerUniqueId]; - if (this._attachedController === xrControllerUniqueId) { - // check for other controllers - const keys = Object.keys(this._controllers); - if (keys.length) { - this._attachedController = keys[0]; - } - else { - this._attachedController = ""; - } - } - } - catch (e) { - tools_Tools.Warn("controller already detached."); - } - }); - } - _generateNewMeshPair(meshParent) { - const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene; - const laserPointer = this._options.customLasterPointerMeshGenerator - ? this._options.customLasterPointerMeshGenerator() - : cylinderBuilder_CreateCylinder("laserPointer", { - height: 1, - diameterTop: 0.0002, - diameterBottom: 0.004, - tessellation: 20, - subdivisions: 1, - }, sceneToRenderTo); - laserPointer.parent = meshParent; - const laserPointerMaterial = new standardMaterial_StandardMaterial("laserPointerMat", sceneToRenderTo); - laserPointerMaterial.emissiveColor = this.laserPointerDefaultColor; - laserPointerMaterial.alpha = 0.7; - laserPointer.material = laserPointerMaterial; - laserPointer.rotation.x = Math.PI / 2; - this._updatePointerDistance(laserPointer, 1); - laserPointer.isPickable = false; - laserPointer.isVisible = false; - // Create a gaze tracker for the XR controller - const selectionMesh = this._options.customSelectionMeshGenerator - ? this._options.customSelectionMeshGenerator() - : CreateTorus("gazeTracker", { - diameter: 0.0035 * 3, - thickness: 0.0025 * 3, - tessellation: 20, - }, sceneToRenderTo); - selectionMesh.bakeCurrentTransformIntoVertices(); - selectionMesh.isPickable = false; - selectionMesh.isVisible = false; - const targetMat = new standardMaterial_StandardMaterial("targetMat", sceneToRenderTo); - targetMat.specularColor = math_color_Color3.Black(); - targetMat.emissiveColor = this.selectionMeshDefaultColor; - targetMat.backFaceCulling = false; - selectionMesh.material = targetMat; - if (this._options.renderingGroupId !== undefined) { - laserPointer.renderingGroupId = this._options.renderingGroupId; - selectionMesh.renderingGroupId = this._options.renderingGroupId; - } - return { - laserPointer, - selectionMesh, - }; - } - _pickingMoved(oldPick, newPick) { - var _a; - if (!oldPick.hit || !newPick.hit) { - return true; - } - if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) { - return true; - } - if (oldPick.pickedMesh !== newPick.pickedMesh) { - return true; - } - (_a = oldPick.pickedPoint) === null || _a === void 0 ? void 0 : _a.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare); - this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z)); - const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 * newPick.distance; - const length = this._tmpVectorForPickCompare.length(); - if (length > delta) { - return true; - } - return false; - } - _updatePointerDistance(_laserPointer, distance = 100) { - _laserPointer.scaling.y = distance; - // a bit of distance from the controller - if (this._scene.useRightHandedSystem) { - distance *= -1; - } - _laserPointer.position.z = distance / 2 + 0.05; - } - _augmentPointerInit(pointerEventInit, id, screenCoordinates) { - pointerEventInit.pointerId = id; - pointerEventInit.pointerType = "xr"; - if (screenCoordinates) { - pointerEventInit.screenX = screenCoordinates.x; - pointerEventInit.screenY = screenCoordinates.y; - } - } - /** @internal */ - get lasterPointerDefaultColor() { - // here due to a typo - return this.laserPointerDefaultColor; - } -} -WebXRControllerPointerSelection._IdCounter = 200; -/** - * The module's name - */ -WebXRControllerPointerSelection.Name = webXRFeaturesManager_WebXRFeatureName.POINTER_SELECTION; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRControllerPointerSelection.Version = 1; -//register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => { - return () => new WebXRControllerPointerSelection(xrSessionManager, options); -}, WebXRControllerPointerSelection.Version, true); -//# sourceMappingURL=WebXRControllerPointerSelection.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/subMesh.project.js - - - -/** - * @internal - */ -subMesh_SubMesh.prototype._projectOnTrianglesToRef = function (vector, positions, indices, step, checkStopper, ref) { - // Triangles test - const proj = math_vector_TmpVectors.Vector3[0]; - const tmp = math_vector_TmpVectors.Vector3[1]; - let distance = +Infinity; - for (let index = this.indexStart; index < this.indexStart + this.indexCount - (3 - step); index += step) { - const indexA = indices[index]; - const indexB = indices[index + 1]; - const indexC = indices[index + 2]; - if (checkStopper && indexC === 0xffffffff) { - index += 2; - continue; - } - const p0 = positions[indexA]; - const p1 = positions[indexB]; - const p2 = positions[indexC]; - // stay defensive and don't check against undefined positions. - if (!p0 || !p1 || !p2) { - continue; - } - const tmpDist = math_vector_Vector3.ProjectOnTriangleToRef(vector, p0, p1, p2, tmp); - if (tmpDist < distance) { - proj.copyFrom(tmp); - distance = tmpDist; - } - } - ref.copyFrom(proj); - return distance; -}; -/** - * @internal - */ -subMesh_SubMesh.prototype._projectOnUnIndexedTrianglesToRef = function (vector, positions, indices, ref) { - // Triangles test - const proj = math_vector_TmpVectors.Vector3[0]; - const tmp = math_vector_TmpVectors.Vector3[1]; - let distance = +Infinity; - for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) { - const p0 = positions[index]; - const p1 = positions[index + 1]; - const p2 = positions[index + 2]; - const tmpDist = math_vector_Vector3.ProjectOnTriangleToRef(vector, p0, p1, p2, tmp); - if (tmpDist < distance) { - proj.copyFrom(tmp); - distance = tmpDist; - } - } - ref.copyFrom(proj); - return distance; -}; -subMesh_SubMesh.prototype.projectToRef = function (vector, positions, indices, ref) { - const material = this.getMaterial(); - if (!material) { - return -1; - } - let step = 3; - let checkStopper = false; - switch (material.fillMode) { - case 3: - case 5: - case 6: - case 8: - return -1; - case 7: - step = 1; - checkStopper = true; - break; - default: - break; - } - // LineMesh first as it's also a Mesh... - if (material.fillMode === 4) { - return -1; - } - else { - // Check if mesh is unindexed - if (!indices.length && this._mesh._unIndexed) { - return this._projectOnUnIndexedTrianglesToRef(vector, positions, indices, ref); - } - return this._projectOnTrianglesToRef(vector, positions, indices, step, checkStopper, ref); - } -}; -//# sourceMappingURL=subMesh.project.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRNearInteraction.js - - - - - - - - - - - - - -// side effects - -// Tracks the interaction animation state when using a motion controller with a near interaction orb -var ControllerOrbAnimationState; -(function (ControllerOrbAnimationState) { - /** - * Orb is invisible - */ - ControllerOrbAnimationState[ControllerOrbAnimationState["DEHYDRATED"] = 0] = "DEHYDRATED"; - /** - * Orb is visible and inside the hover range - */ - ControllerOrbAnimationState[ControllerOrbAnimationState["HOVER"] = 1] = "HOVER"; - /** - * Orb is visible and touching a near interaction target - */ - ControllerOrbAnimationState[ControllerOrbAnimationState["TOUCH"] = 2] = "TOUCH"; -})(ControllerOrbAnimationState || (ControllerOrbAnimationState = {})); -/** - * Where should the near interaction mesh be attached to when using a motion controller for near interaction - */ -var WebXRNearControllerMode; -(function (WebXRNearControllerMode) { - /** - * Motion controllers will not support near interaction - */ - WebXRNearControllerMode[WebXRNearControllerMode["DISABLED"] = 0] = "DISABLED"; - /** - * The interaction point for motion controllers will be inside of them - */ - WebXRNearControllerMode[WebXRNearControllerMode["CENTERED_ON_CONTROLLER"] = 1] = "CENTERED_ON_CONTROLLER"; - /** - * The interaction point for motion controllers will be in front of the controller - */ - WebXRNearControllerMode[WebXRNearControllerMode["CENTERED_IN_FRONT"] = 2] = "CENTERED_IN_FRONT"; -})(WebXRNearControllerMode || (WebXRNearControllerMode = {})); -/** - * A module that will enable near interaction near interaction for hands and motion controllers of XR Input Sources - */ -class WebXRNearInteraction extends WebXRAbstractFeature { - /** - * constructs a new background remover module - * @param _xrSessionManager the session manager for this module - * @param _options read-only options to be used in this module - */ - constructor(_xrSessionManager, _options) { - super(_xrSessionManager); - this._options = _options; - this._tmpRay = new ray_Ray(new math_vector_Vector3(), new math_vector_Vector3()); - this._attachController = (xrController) => { - if (this._controllers[xrController.uniqueId]) { - // already attached - return; - } - // get two new meshes - const { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction } = this._generateNewTouchPointMesh(); - const selectionMesh = this._generateVisualCue(); - this._controllers[xrController.uniqueId] = { - xrController, - meshUnderPointer: null, - nearInteractionTargetMesh: null, - pick: null, - stalePick: null, - touchCollisionMesh, - touchCollisionMeshFunction: touchCollisionMeshFunction, - hydrateCollisionMeshFunction: hydrateCollisionMeshFunction, - currentAnimationState: ControllerOrbAnimationState.DEHYDRATED, - grabRay: new ray_Ray(new math_vector_Vector3(), new math_vector_Vector3()), - hoverInteraction: false, - nearInteraction: false, - grabInteraction: false, - id: WebXRNearInteraction._IdCounter++, - pickedPointVisualCue: selectionMesh, - }; - if (this._attachedController) { - if (!this._options.enableNearInteractionOnAllControllers && - this._options.preferredHandedness && - xrController.inputSource.handedness === this._options.preferredHandedness) { - this._attachedController = xrController.uniqueId; - } - } - else { - if (!this._options.enableNearInteractionOnAllControllers) { - this._attachedController = xrController.uniqueId; - } - } - switch (xrController.inputSource.targetRayMode) { - case "tracked-pointer": - return this._attachNearInteractionMode(xrController); - case "gaze": - return null; - case "screen": - return null; - } - }; - this._controllers = {}; - this._farInteractionFeature = null; - /** - * default color of the selection ring - */ - this.selectionMeshDefaultColor = new math_color_Color3(0.8, 0.8, 0.8); - /** - * This color will be applied to the selection ring when selection is triggered - */ - this.selectionMeshPickedColor = new math_color_Color3(0.3, 0.3, 1.0); - this._hoverRadius = 0.1; - this._pickRadius = 0.02; - 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 - this._nearGrabLengthScale = 5; - this._scene = this._xrSessionManager.scene; - if (this._options.nearInteractionControllerMode === undefined) { - this._options.nearInteractionControllerMode = WebXRNearControllerMode.CENTERED_IN_FRONT; - } - if (this._options.farInteractionFeature) { - this._farInteractionFeature = this._options.farInteractionFeature; - } - } - /** - * Attach this feature - * Will usually be called by the features manager - * - * @returns true if successful. - */ - attach() { - if (!super.attach()) { - return false; - } - this._options.xrInput.controllers.forEach(this._attachController); - this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController); - this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => { - // REMOVE the controller - this._detachController(controller.uniqueId); - }); - this._scene.constantlyUpdateMeshUnderPointer = true; - return true; - } - /** - * Detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - if (!super.detach()) { - return false; - } - Object.keys(this._controllers).forEach((controllerId) => { - this._detachController(controllerId); - }); - return true; - } - /** - * Will get the mesh under a specific pointer. - * `scene.meshUnderPointer` will only return one mesh - either left or right. - * @param controllerId the controllerId to check - * @returns The mesh under pointer or null if no mesh is under the pointer - */ - getMeshUnderPointer(controllerId) { - if (this._controllers[controllerId]) { - return this._controllers[controllerId].meshUnderPointer; - } - else { - return null; - } - } - /** - * Get the xr controller that correlates to the pointer id in the pointer event - * - * @param id the pointer id to search for - * @returns the controller that correlates to this id or null if not found - */ - getXRControllerByPointerId(id) { - const keys = Object.keys(this._controllers); - for (let i = 0; i < keys.length; ++i) { - if (this._controllers[keys[i]].id === id) { - return this._controllers[keys[i]].xrController || null; - } - } - return null; - } - /** - * This function sets webXRControllerPointerSelection feature that will be disabled when - * the hover range is reached for a mesh and will be reattached when not in hover range. - * This is used to remove the selection rays when moving. - * @param farInteractionFeature the feature to disable when finger is in hover range for a mesh - */ - setFarInteractionFeature(farInteractionFeature) { - this._farInteractionFeature = farInteractionFeature; - } - /** - * Filter used for near interaction pick and hover - * @param mesh - */ - _nearPickPredicate(mesh) { - return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearPickable; - } - /** - * Filter used for near interaction grab - * @param mesh - */ - _nearGrabPredicate(mesh) { - return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearGrabbable; - } - /** - * Filter used for any near interaction - * @param mesh - */ - _nearInteractionPredicate(mesh) { - return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && (mesh.isNearPickable || mesh.isNearGrabbable); - } - _controllerAvailablePredicate(mesh, controllerId) { - let parent = mesh; - while (parent) { - if (parent.reservedDataStore && parent.reservedDataStore.nearInteraction && parent.reservedDataStore.nearInteraction.excludedControllerId === controllerId) { - return false; - } - parent = parent.parent; - } - return true; - } - _handleTransitionAnimation(controllerData, newState) { - var _a; - if (controllerData.currentAnimationState === newState || - this._options.nearInteractionControllerMode !== WebXRNearControllerMode.CENTERED_IN_FRONT || - !!((_a = controllerData.xrController) === null || _a === void 0 ? void 0 : _a.inputSource.hand)) { - return; - } - // Don't always break to allow for animation fallthrough on rare cases of multi-transitions - if (newState > controllerData.currentAnimationState) { - switch (controllerData.currentAnimationState) { - case ControllerOrbAnimationState.DEHYDRATED: { - controllerData.hydrateCollisionMeshFunction(true); - if (newState === ControllerOrbAnimationState.HOVER) { - break; - } - } - // eslint-disable-next-line no-fallthrough - case ControllerOrbAnimationState.HOVER: { - controllerData.touchCollisionMeshFunction(true); - if (newState === ControllerOrbAnimationState.TOUCH) { - break; - } - } - } - } - else { - switch (controllerData.currentAnimationState) { - case ControllerOrbAnimationState.TOUCH: { - controllerData.touchCollisionMeshFunction(false); - if (newState === ControllerOrbAnimationState.HOVER) { - break; - } - } - // eslint-disable-next-line no-fallthrough - case ControllerOrbAnimationState.HOVER: { - controllerData.hydrateCollisionMeshFunction(false); - if (newState === ControllerOrbAnimationState.DEHYDRATED) { - break; - } - } - } - } - controllerData.currentAnimationState = newState; - } - _processTouchPoint(id, position, orientation) { - var _a; - const controllerData = this._controllers[id]; - // Position and orientation could be temporary values, se we take care of them before calling any functions that use temporary vectors/quaternions - controllerData.grabRay.origin.copyFrom(position); - orientation.toEulerAnglesToRef(math_vector_TmpVectors.Vector3[0]); - controllerData.grabRay.direction.copyFrom(math_vector_TmpVectors.Vector3[0]); - if (this._options.nearInteractionControllerMode === WebXRNearControllerMode.CENTERED_IN_FRONT && !((_a = controllerData.xrController) === null || _a === void 0 ? void 0 : _a.inputSource.hand)) { - // offset the touch point in the direction the transform is facing - controllerData.xrController.getWorldPointerRayToRef(this._tmpRay); - controllerData.grabRay.origin.addInPlace(this._tmpRay.direction.scale(0.05)); - } - controllerData.grabRay.length = this._nearGrabLengthScale * this._hoverRadius; - controllerData.touchCollisionMesh.position.copyFrom(controllerData.grabRay.origin); - } - _onXRFrame(_xrFrame) { - Object.keys(this._controllers).forEach((id) => { - var _a; - // only do this for the selected pointer - const controllerData = this._controllers[id]; - const handData = (_a = controllerData.xrController) === null || _a === void 0 ? void 0 : _a.inputSource.hand; - // If near interaction is not enabled/available for this controller, return early - if ((!this._options.enableNearInteractionOnAllControllers && id !== this._attachedController) || - !controllerData.xrController || - (!handData && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad))) { - controllerData.pick = null; - return; - } - controllerData.hoverInteraction = false; - controllerData.nearInteraction = false; - // Every frame check collisions/input - if (controllerData.xrController) { - if (handData) { - const xrIndexTip = handData.get("index-finger-tip"); - if (xrIndexTip) { - const indexTipPose = _xrFrame.getJointPose(xrIndexTip, this._xrSessionManager.referenceSpace); - if (indexTipPose && indexTipPose.transform) { - const axisRHSMultiplier = this._scene.useRightHandedSystem ? 1 : -1; - math_vector_TmpVectors.Vector3[0].set(indexTipPose.transform.position.x, indexTipPose.transform.position.y, indexTipPose.transform.position.z * axisRHSMultiplier); - math_vector_TmpVectors.Quaternion[0].set(indexTipPose.transform.orientation.x, indexTipPose.transform.orientation.y, indexTipPose.transform.orientation.z * axisRHSMultiplier, indexTipPose.transform.orientation.w * axisRHSMultiplier); - this._processTouchPoint(id, math_vector_TmpVectors.Vector3[0], math_vector_TmpVectors.Quaternion[0]); - } - } - } - else if (controllerData.xrController.inputSource.gamepad && this._options.nearInteractionControllerMode !== WebXRNearControllerMode.DISABLED) { - let controllerPose = controllerData.xrController.pointer; - if (controllerData.xrController.grip && this._options.nearInteractionControllerMode === WebXRNearControllerMode.CENTERED_ON_CONTROLLER) { - controllerPose = controllerData.xrController.grip; - } - this._processTouchPoint(id, controllerPose.position, controllerPose.rotationQuaternion); - } - } - else { - return; - } - const accuratePickInfo = (originalScenePick, utilityScenePick) => { - let pick = null; - if (!utilityScenePick || !utilityScenePick.hit) { - // No hit in utility scene - pick = originalScenePick; - } - else if (!originalScenePick || !originalScenePick.hit) { - // No hit in original scene - pick = utilityScenePick; - } - else if (utilityScenePick.distance < originalScenePick.distance) { - // Hit is closer in utility scene - pick = utilityScenePick; - } - else { - // Hit is closer in original scene - pick = originalScenePick; - } - return pick; - }; - const populateNearInteractionInfo = (nearInteractionInfo) => { - let result = new PickingInfo(); - let nearInteractionAtOrigin = false; - const nearInteraction = nearInteractionInfo && nearInteractionInfo.pickedPoint && nearInteractionInfo.hit; - if (nearInteractionInfo === null || nearInteractionInfo === void 0 ? void 0 : nearInteractionInfo.pickedPoint) { - nearInteractionAtOrigin = nearInteractionInfo.pickedPoint.x === 0 && nearInteractionInfo.pickedPoint.y === 0 && nearInteractionInfo.pickedPoint.z === 0; - } - if (nearInteraction && !nearInteractionAtOrigin) { - result = nearInteractionInfo; - } - return result; - }; - // Don't perform touch logic while grabbing, to prevent triggering touch interactions while in the middle of a grab interaction - // Dont update cursor logic either - the cursor should already be visible for the grab to be in range, - // and in order to maintain its position on the target mesh it is parented for the duration of the grab. - if (!controllerData.grabInteraction) { - let pick = null; - // near interaction hover - let utilitySceneHoverPick = null; - if (this._options.useUtilityLayer && this._utilityLayerScene) { - utilitySceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius, this._utilityLayerScene, (mesh) => this._nearInteractionPredicate(mesh)); - } - const originalSceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius, this._scene, (mesh) => this._nearInteractionPredicate(mesh)); - const hoverPickInfo = accuratePickInfo(originalSceneHoverPick, utilitySceneHoverPick); - if (hoverPickInfo && hoverPickInfo.hit) { - pick = populateNearInteractionInfo(hoverPickInfo); - if (pick.hit) { - controllerData.hoverInteraction = true; - } - } - // near interaction pick - if (controllerData.hoverInteraction) { - let utilitySceneNearPick = null; - const radius = handData ? this._pickRadius : this._controllerPickRadius; - if (this._options.useUtilityLayer && this._utilityLayerScene) { - utilitySceneNearPick = this._pickWithSphere(controllerData, radius, this._utilityLayerScene, (mesh) => this._nearPickPredicate(mesh)); - } - const originalSceneNearPick = this._pickWithSphere(controllerData, radius, this._scene, (mesh) => this._nearPickPredicate(mesh)); - const pickInfo = accuratePickInfo(originalSceneNearPick, utilitySceneNearPick); - const nearPick = populateNearInteractionInfo(pickInfo); - if (nearPick.hit) { - // Near pick takes precedence over hover interaction - pick = nearPick; - controllerData.nearInteraction = true; - } - } - controllerData.stalePick = controllerData.pick; - controllerData.pick = pick; - // Update mesh under pointer - if (controllerData.pick && controllerData.pick.pickedPoint && controllerData.pick.hit) { - controllerData.meshUnderPointer = controllerData.pick.pickedMesh; - controllerData.pickedPointVisualCue.position.copyFrom(controllerData.pick.pickedPoint); - controllerData.pickedPointVisualCue.isVisible = true; - if (this._farInteractionFeature && this._farInteractionFeature.attached) { - this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, true); - } - } - else { - controllerData.meshUnderPointer = null; - controllerData.pickedPointVisualCue.isVisible = false; - if (this._farInteractionFeature && this._farInteractionFeature.attached) { - this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, false); - } - } - } - // Update the interaction animation. Only updates if the visible touch mesh is active - let state = ControllerOrbAnimationState.DEHYDRATED; - if (controllerData.grabInteraction || controllerData.nearInteraction) { - state = ControllerOrbAnimationState.TOUCH; - } - else if (controllerData.hoverInteraction) { - state = ControllerOrbAnimationState.HOVER; - } - this._handleTransitionAnimation(controllerData, state); - }); - } - get _utilityLayerScene() { - return this._options.customUtilityLayerScene || utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene; - } - _generateVisualCue() { - const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene; - const selectionMesh = sphereBuilder_CreateSphere("nearInteraction", { - diameter: 0.0035 * 3, - }, sceneToRenderTo); - selectionMesh.bakeCurrentTransformIntoVertices(); - selectionMesh.isPickable = false; - selectionMesh.isVisible = false; - selectionMesh.rotationQuaternion = math_vector_Quaternion.Identity(); - const targetMat = new standardMaterial_StandardMaterial("targetMat", sceneToRenderTo); - targetMat.specularColor = math_color_Color3.Black(); - targetMat.emissiveColor = this.selectionMeshDefaultColor; - targetMat.backFaceCulling = false; - selectionMesh.material = targetMat; - return selectionMesh; - } - _isControllerReadyForNearInteraction(id) { - if (this._farInteractionFeature) { - return this._farInteractionFeature._getPointerSelectionDisabledByPointerId(id); - } - return true; - } - _attachNearInteractionMode(xrController) { - const controllerData = this._controllers[xrController.uniqueId]; - const pointerEventInit = { - pointerId: controllerData.id, - pointerType: "xr-near", - }; - controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => { - if ((!this._options.enableNearInteractionOnAllControllers && xrController.uniqueId !== this._attachedController) || - !controllerData.xrController || - (!controllerData.xrController.inputSource.hand && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad))) { - return; - } - if (controllerData.pick) { - controllerData.pick.ray = controllerData.grabRay; - } - if (controllerData.pick && this._isControllerReadyForNearInteraction(controllerData.id)) { - this._scene.simulatePointerMove(controllerData.pick, pointerEventInit); - } - // Near pick pointer event - if (controllerData.nearInteraction && controllerData.pick && controllerData.pick.hit) { - if (!controllerData.nearInteractionTargetMesh) { - this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); - controllerData.nearInteractionTargetMesh = controllerData.meshUnderPointer; - } - } - else if (controllerData.nearInteractionTargetMesh && controllerData.stalePick) { - this._scene.simulatePointerUp(controllerData.stalePick, pointerEventInit); - controllerData.nearInteractionTargetMesh = null; - } - }); - const grabCheck = (pressed) => { - if (this._options.enableNearInteractionOnAllControllers || - (xrController.uniqueId === this._attachedController && this._isControllerReadyForNearInteraction(controllerData.id))) { - if (controllerData.pick) { - controllerData.pick.ray = controllerData.grabRay; - } - if (pressed && controllerData.pick && controllerData.meshUnderPointer && this._nearGrabPredicate(controllerData.meshUnderPointer)) { - controllerData.grabInteraction = true; - controllerData.pickedPointVisualCue.isVisible = false; - this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); - } - else if (!pressed && controllerData.pick && controllerData.grabInteraction) { - this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); - controllerData.grabInteraction = false; - controllerData.pickedPointVisualCue.isVisible = true; - } - } - else { - if (pressed && !this._options.enableNearInteractionOnAllControllers && !this._options.disableSwitchOnClick) { - this._attachedController = xrController.uniqueId; - } - } - }; - if (xrController.inputSource.gamepad) { - const init = (motionController) => { - controllerData.squeezeComponent = motionController.getComponent("grasp"); - if (controllerData.squeezeComponent) { - controllerData.onSqueezeButtonChangedObserver = controllerData.squeezeComponent.onButtonStateChangedObservable.add((component) => { - if (component.changes.pressed) { - const pressed = component.changes.pressed.current; - grabCheck(pressed); - } - }); - } - else { - controllerData.selectionComponent = motionController.getMainComponent(); - controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => { - if (component.changes.pressed) { - const pressed = component.changes.pressed.current; - grabCheck(pressed); - } - }); - } - }; - if (xrController.motionController) { - init(xrController.motionController); - } - else { - xrController.onMotionControllerInitObservable.add(init); - } - } - else { - // use the select and squeeze events - const selectStartListener = (event) => { - if (controllerData.xrController && - event.inputSource === controllerData.xrController.inputSource && - controllerData.pick && - this._isControllerReadyForNearInteraction(controllerData.id) && - controllerData.meshUnderPointer && - this._nearGrabPredicate(controllerData.meshUnderPointer)) { - controllerData.grabInteraction = true; - controllerData.pickedPointVisualCue.isVisible = false; - this._scene.simulatePointerDown(controllerData.pick, pointerEventInit); - } - }; - const selectEndListener = (event) => { - if (controllerData.xrController && - event.inputSource === controllerData.xrController.inputSource && - controllerData.pick && - this._isControllerReadyForNearInteraction(controllerData.id)) { - this._scene.simulatePointerUp(controllerData.pick, pointerEventInit); - controllerData.grabInteraction = false; - controllerData.pickedPointVisualCue.isVisible = true; - } - }; - controllerData.eventListeners = { - selectend: selectEndListener, - selectstart: selectStartListener, - }; - this._xrSessionManager.session.addEventListener("selectstart", selectStartListener); - this._xrSessionManager.session.addEventListener("selectend", selectEndListener); - } - } - _detachController(xrControllerUniqueId) { - const controllerData = this._controllers[xrControllerUniqueId]; - if (!controllerData) { - return; - } - if (controllerData.squeezeComponent) { - if (controllerData.onSqueezeButtonChangedObserver) { - controllerData.squeezeComponent.onButtonStateChangedObservable.remove(controllerData.onSqueezeButtonChangedObserver); - } - } - if (controllerData.selectionComponent) { - if (controllerData.onButtonChangedObserver) { - controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver); - } - } - if (controllerData.onFrameObserver) { - this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver); - } - if (controllerData.eventListeners) { - Object.keys(controllerData.eventListeners).forEach((eventName) => { - const func = controllerData.eventListeners && controllerData.eventListeners[eventName]; - if (func) { - this._xrSessionManager.session.removeEventListener(eventName, func); - } - }); - } - controllerData.touchCollisionMesh.dispose(); - controllerData.pickedPointVisualCue.dispose(); - this._xrSessionManager.runInXRFrame(() => { - // Fire a pointerup - const pointerEventInit = { - pointerId: controllerData.id, - pointerType: "xr-near", - }; - this._scene.simulatePointerUp(new PickingInfo(), pointerEventInit); - }); - // remove from the map - delete this._controllers[xrControllerUniqueId]; - if (this._attachedController === xrControllerUniqueId) { - // check for other controllers - const keys = Object.keys(this._controllers); - if (keys.length) { - this._attachedController = keys[0]; - } - else { - this._attachedController = ""; - } - } - } - _generateNewTouchPointMesh() { - // populate information for near hover, pick and pinch - const meshCreationScene = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene; - const touchCollisionMesh = sphereBuilder_CreateSphere("PickSphere", { diameter: 1 }, meshCreationScene); - touchCollisionMesh.isVisible = false; - // Generate the material for the touch mesh visuals - if (this._options.motionControllerOrbMaterial) { - touchCollisionMesh.material = this._options.motionControllerOrbMaterial; - } - else { - NodeMaterial.ParseFromSnippetAsync("8RUNKL#3", meshCreationScene).then((nodeMaterial) => { - touchCollisionMesh.material = nodeMaterial; - }); - } - const easingFunction = new QuadraticEase(); - easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT); - // Adjust the visual size based off of the size of the touch collision orb. - // Having the size perfectly match for hover gives a more accurate tell for when the user will start interacting with the target - // Sizes for other states are somewhat arbitrary, as they are based on what feels nice during an interaction - const hoverSizeVec = new math_vector_Vector3(this._controllerPickRadius, this._controllerPickRadius, this._controllerPickRadius); - const touchSize = this._controllerPickRadius * (4 / 3); - const touchSizeVec = new math_vector_Vector3(touchSize, touchSize, touchSize); - const hydrateTransitionSize = this._controllerPickRadius * (7 / 6); - const hydrateTransitionSizeVec = new math_vector_Vector3(hydrateTransitionSize, hydrateTransitionSize, hydrateTransitionSize); - const touchHoverTransitionSize = this._controllerPickRadius * (4 / 5); - const touchHoverTransitionSizeVec = new math_vector_Vector3(touchHoverTransitionSize, touchHoverTransitionSize, touchHoverTransitionSize); - const hoverTouchTransitionSize = this._controllerPickRadius * (3 / 2); - const hoverTouchTransitionSizeVec = new math_vector_Vector3(hoverTouchTransitionSize, hoverTouchTransitionSize, hoverTouchTransitionSize); - const touchKeys = [ - { frame: 0, value: hoverSizeVec }, - { frame: 10, value: hoverTouchTransitionSizeVec }, - { frame: 18, value: touchSizeVec }, - ]; - const releaseKeys = [ - { frame: 0, value: touchSizeVec }, - { frame: 10, value: touchHoverTransitionSizeVec }, - { frame: 18, value: hoverSizeVec }, - ]; - const hydrateKeys = [ - { frame: 0, value: math_vector_Vector3.ZeroReadOnly }, - { frame: 12, value: hydrateTransitionSizeVec }, - { frame: 15, value: hoverSizeVec }, - ]; - const dehydrateKeys = [ - { frame: 0, value: hoverSizeVec }, - { frame: 10, value: math_vector_Vector3.ZeroReadOnly }, - { frame: 15, value: math_vector_Vector3.ZeroReadOnly }, - ]; - const touchAction = new animation_Animation("touch", "scaling", 60, animation_Animation.ANIMATIONTYPE_VECTOR3, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - const releaseAction = new animation_Animation("release", "scaling", 60, animation_Animation.ANIMATIONTYPE_VECTOR3, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - const hydrateAction = new animation_Animation("hydrate", "scaling", 60, animation_Animation.ANIMATIONTYPE_VECTOR3, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - const dehydrateAction = new animation_Animation("dehydrate", "scaling", 60, animation_Animation.ANIMATIONTYPE_VECTOR3, animation_Animation.ANIMATIONLOOPMODE_CONSTANT); - touchAction.setEasingFunction(easingFunction); - releaseAction.setEasingFunction(easingFunction); - hydrateAction.setEasingFunction(easingFunction); - dehydrateAction.setEasingFunction(easingFunction); - touchAction.setKeys(touchKeys); - releaseAction.setKeys(releaseKeys); - hydrateAction.setKeys(hydrateKeys); - dehydrateAction.setKeys(dehydrateKeys); - const touchCollisionMeshFunction = (isTouch) => { - const action = isTouch ? touchAction : releaseAction; - meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action], 0, 18, false, 1); - }; - const hydrateCollisionMeshFunction = (isHydration) => { - const action = isHydration ? hydrateAction : dehydrateAction; - if (isHydration) { - touchCollisionMesh.isVisible = true; - } - meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action], 0, 15, false, 1, () => { - if (!isHydration) { - touchCollisionMesh.isVisible = false; - } - }); - }; - return { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction }; - } - _pickWithSphere(controllerData, radius, sceneToUse, predicate) { - const pickingInfo = new PickingInfo(); - pickingInfo.distance = +Infinity; - if (controllerData.touchCollisionMesh && controllerData.xrController) { - const position = controllerData.touchCollisionMesh.position; - const sphere = boundingSphere_BoundingSphere.CreateFromCenterAndRadius(position, radius); - for (let meshIndex = 0; meshIndex < sceneToUse.meshes.length; meshIndex++) { - const mesh = sceneToUse.meshes[meshIndex]; - if (!predicate(mesh) || !this._controllerAvailablePredicate(mesh, controllerData.xrController.uniqueId)) { - continue; - } - const result = WebXRNearInteraction.PickMeshWithSphere(mesh, sphere); - if (result && result.hit && result.distance < pickingInfo.distance) { - pickingInfo.hit = result.hit; - pickingInfo.pickedMesh = mesh; - pickingInfo.pickedPoint = result.pickedPoint; - pickingInfo.aimTransform = controllerData.xrController.pointer; - pickingInfo.gripTransform = controllerData.xrController.grip || null; - pickingInfo.originMesh = controllerData.touchCollisionMesh; - pickingInfo.distance = result.distance; - } - } - } - return pickingInfo; - } - /** - * Picks a mesh with a sphere - * @param mesh the mesh to pick - * @param sphere picking sphere in world coordinates - * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check - * @returns the picking info - */ - static PickMeshWithSphere(mesh, sphere, skipBoundingInfo = false) { - const subMeshes = mesh.subMeshes; - const pi = new PickingInfo(); - const boundingInfo = mesh.getBoundingInfo(); - if (!mesh._generatePointsArray()) { - return pi; - } - if (!mesh.subMeshes || !boundingInfo) { - return pi; - } - if (!skipBoundingInfo && !boundingSphere_BoundingSphere.Intersects(boundingInfo.boundingSphere, sphere)) { - return pi; - } - const result = math_vector_TmpVectors.Vector3[0]; - const tmpVec = math_vector_TmpVectors.Vector3[1]; - let distance = +Infinity; - let tmp, tmpDistanceSphereToCenter, tmpDistanceSurfaceToCenter; - const center = math_vector_TmpVectors.Vector3[2]; - const worldToMesh = math_vector_TmpVectors.Matrix[0]; - worldToMesh.copyFrom(mesh.getWorldMatrix()); - worldToMesh.invert(); - math_vector_Vector3.TransformCoordinatesToRef(sphere.center, worldToMesh, center); - for (let index = 0; index < subMeshes.length; index++) { - const subMesh = subMeshes[index]; - subMesh.projectToRef(center, mesh._positions, mesh.getIndices(), tmpVec); - math_vector_Vector3.TransformCoordinatesToRef(tmpVec, mesh.getWorldMatrix(), tmpVec); - tmp = math_vector_Vector3.Distance(tmpVec, sphere.center); - // Check for finger inside of mesh - tmpDistanceSurfaceToCenter = math_vector_Vector3.Distance(tmpVec, mesh.getAbsolutePosition()); - tmpDistanceSphereToCenter = math_vector_Vector3.Distance(sphere.center, mesh.getAbsolutePosition()); - if (tmpDistanceSphereToCenter !== -1 && tmpDistanceSurfaceToCenter !== -1 && tmpDistanceSurfaceToCenter > tmpDistanceSphereToCenter) { - tmp = 0; - tmpVec.copyFrom(sphere.center); - } - if (tmp !== -1 && tmp < distance) { - distance = tmp; - result.copyFrom(tmpVec); - } - } - if (distance < sphere.radius) { - pi.hit = true; - pi.distance = distance; - pi.pickedMesh = mesh; - pi.pickedPoint = result.clone(); - } - return pi; - } -} -WebXRNearInteraction._IdCounter = 200; -/** - * The module's name - */ -WebXRNearInteraction.Name = webXRFeaturesManager_WebXRFeatureName.NEAR_INTERACTION; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRNearInteraction.Version = 1; -//Register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRNearInteraction.Name, (xrSessionManager, options) => { - return () => new WebXRNearInteraction(xrSessionManager, options); -}, WebXRNearInteraction.Version, true); -//# sourceMappingURL=WebXRNearInteraction.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXREnterExitUI.js - - - -/** - * Button which can be used to enter a different mode of XR - */ -class WebXREnterExitUIButton { - /** - * Creates a WebXREnterExitUIButton - * @param element button element - * @param sessionMode XR initialization session mode - * @param referenceSpaceType the type of reference space to be used - */ - constructor( - /** button element */ - element, - /** XR initialization options for the button */ - sessionMode, - /** Reference space type */ - referenceSpaceType) { - this.element = element; - this.sessionMode = sessionMode; - this.referenceSpaceType = referenceSpaceType; - } - /** - * Extendable function which can be used to update the button's visuals when the state changes - * @param activeButton the current active button in the UI - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - update(activeButton) { } -} -/** - * Options to create the webXR UI - */ -class WebXREnterExitUIOptions { -} -/** - * UI to allow the user to enter/exit XR mode - */ -class WebXREnterExitUI { - /** - * Construct a new EnterExit UI class - * - * @param _scene babylon scene object to use - * @param options (read-only) version of the options passed to this UI - */ - constructor(_scene, - /** version of the options passed to this UI */ - options) { - this._scene = _scene; - this.options = options; - this._activeButton = null; - this._buttons = []; - /** - * Fired every time the active button is changed. - * - * When xr is entered via a button that launches xr that button will be the callback parameter - * - * When exiting xr the callback parameter will be null) - */ - this.activeButtonChangedObservable = new observable_Observable(); - // eslint-disable-next-line @typescript-eslint/no-unused-vars - this._onSessionGranted = (evt) => { - // This section is for future reference. - // As per specs, evt.session.mode should have the supported session mode, but no browser supports it for now. - // // check if the session granted is the same as the one requested - // const grantedMode = (evt.session as any).mode; - // if (grantedMode) { - // this._buttons.some((btn, idx) => { - // if (btn.sessionMode === grantedMode) { - // this._enterXRWithButtonIndex(idx); - // return true; - // } - // return false; - // }); - // } else - if (this._helper) { - this._enterXRWithButtonIndex(0); - } - }; - this.overlay = document.createElement("div"); - this.overlay.classList.add("xr-button-overlay"); - // prepare for session granted event - if (!options.ignoreSessionGrantedEvent && navigator.xr) { - navigator.xr.addEventListener("sessiongranted", this._onSessionGranted); - } - // if served over HTTP, warn people. - // Hopefully the browsers will catch up - if (typeof window !== "undefined") { - if (window.location && window.location.protocol === "http:" && window.location.hostname !== "localhost") { - tools_Tools.Warn("WebXR can only be served over HTTPS"); - throw new Error("WebXR can only be served over HTTPS"); - } - } - if (options.customButtons) { - this._buttons = options.customButtons; - } - else { - this.overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;"; - const sessionMode = options.sessionMode || "immersive-vr"; - const referenceSpaceType = options.referenceSpaceType || "local-floor"; - const url = typeof SVGSVGElement === "undefined" - ? "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"; - 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(" + - url + - "); 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) }"; - css += '.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}'; - const style = document.createElement("style"); - style.appendChild(document.createTextNode(css)); - document.getElementsByTagName("head")[0].appendChild(style); - const hmdBtn = document.createElement("button"); - hmdBtn.className = "babylonVRicon"; - hmdBtn.title = `${sessionMode} - ${referenceSpaceType}`; - this._buttons.push(new WebXREnterExitUIButton(hmdBtn, sessionMode, referenceSpaceType)); - this._buttons[this._buttons.length - 1].update = function (activeButton) { - this.element.style.display = activeButton === null || activeButton === this ? "" : "none"; - hmdBtn.className = "babylonVRicon" + (activeButton === this ? " vrdisplaypresenting" : ""); - }; - this._updateButtons(null); - } - const renderCanvas = _scene.getEngine().getInputElement(); - if (renderCanvas && renderCanvas.parentNode) { - renderCanvas.parentNode.appendChild(this.overlay); - _scene.onDisposeObservable.addOnce(() => { - this.dispose(); - }); - } - } - /** - * Set the helper to be used with this UI component. - * 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. - * - * @param helper the experience helper to attach - * @param renderTarget an optional render target (in case it is created outside of the helper scope) - * @returns a promise that resolves when the ui is ready - */ - async setHelperAsync(helper, renderTarget) { - this._helper = helper; - this._renderTarget = renderTarget; - const supportedPromises = this._buttons.map((btn) => { - return helper.sessionManager.isSessionSupportedAsync(btn.sessionMode); - }); - helper.onStateChangedObservable.add((state) => { - if (state == WebXRState.NOT_IN_XR) { - this._updateButtons(null); - } - }); - const results = await Promise.all(supportedPromises); - results.forEach((supported, i) => { - if (supported) { - this.overlay.appendChild(this._buttons[i].element); - this._buttons[i].element.onclick = this._enterXRWithButtonIndex.bind(this, i); - } - else { - tools_Tools.Warn(`Session mode "${this._buttons[i].sessionMode}" not supported in browser`); - } - }); - } - /** - * Creates UI to allow the user to enter/exit XR mode - * @param scene the scene to add the ui to - * @param helper the xr experience helper to enter/exit xr with - * @param options options to configure the UI - * @returns the created ui - */ - static async CreateAsync(scene, helper, options) { - const ui = new WebXREnterExitUI(scene, options); - await ui.setHelperAsync(helper, options.renderTarget || undefined); - return ui; - } - async _enterXRWithButtonIndex(idx = 0) { - if (this._helper.state == WebXRState.IN_XR) { - await this._helper.exitXRAsync(); - this._updateButtons(null); - } - else if (this._helper.state == WebXRState.NOT_IN_XR) { - try { - await this._helper.enterXRAsync(this._buttons[idx].sessionMode, this._buttons[idx].referenceSpaceType, this._renderTarget, { - optionalFeatures: this.options.optionalFeatures, - requiredFeatures: this.options.requiredFeatures, - }); - this._updateButtons(this._buttons[idx]); - } - catch (e) { - // make sure button is visible - this._updateButtons(null); - const element = this._buttons[idx].element; - const prevTitle = element.title; - element.title = "Error entering XR session : " + prevTitle; - element.classList.add("xr-error"); - if (this.options.onError) { - this.options.onError(e); - } - } - } - } - /** - * Disposes of the XR UI component - */ - dispose() { - const renderCanvas = this._scene.getEngine().getInputElement(); - if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this.overlay)) { - renderCanvas.parentNode.removeChild(this.overlay); - } - this.activeButtonChangedObservable.clear(); - navigator.xr.removeEventListener("sessiongranted", this._onSessionGranted); - } - _updateButtons(activeButton) { - this._activeButton = activeButton; - this._buttons.forEach((b) => { - b.update(this._activeButton); - }); - this.activeButtonChangedObservable.notifyObservers(this._activeButton); - } -} -//# sourceMappingURL=webXREnterExitUI.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/timer.js - -/** - * The current state of the timer - */ -var TimerState; -(function (TimerState) { - /** - * Timer initialized, not yet started - */ - TimerState[TimerState["INIT"] = 0] = "INIT"; - /** - * Timer started and counting - */ - TimerState[TimerState["STARTED"] = 1] = "STARTED"; - /** - * Timer ended (whether aborted or time reached) - */ - TimerState[TimerState["ENDED"] = 2] = "ENDED"; -})(TimerState || (TimerState = {})); -/** - * A simple version of the timer. Will take options and start the timer immediately after calling it - * - * @param options options with which to initialize this timer - */ -function setAndStartTimer(options) { - var _a; - let timer = 0; - const startTime = Date.now(); - options.observableParameters = (_a = options.observableParameters) !== null && _a !== void 0 ? _a : {}; - const observer = options.contextObservable.add((payload) => { - const now = Date.now(); - timer = now - startTime; - const data = { - startTime, - currentTime: now, - deltaTime: timer, - completeRate: timer / options.timeout, - payload, - }; - options.onTick && options.onTick(data); - if (options.breakCondition && options.breakCondition()) { - options.contextObservable.remove(observer); - options.onAborted && options.onAborted(data); - } - if (timer >= options.timeout) { - options.contextObservable.remove(observer); - options.onEnded && options.onEnded(data); - } - }, options.observableParameters.mask, options.observableParameters.insertFirst, options.observableParameters.scope); - return observer; -} -/** - * An advanced implementation of a timer class - */ -class AdvancedTimer { - /** - * Will construct a new advanced timer based on the options provided. Timer will not start until start() is called. - * @param options construction options for this advanced timer - */ - constructor(options) { - var _a, _b; - /** - * Will notify each time the timer calculates the remaining time - */ - this.onEachCountObservable = new Observable(); - /** - * Will trigger when the timer was aborted due to the break condition - */ - this.onTimerAbortedObservable = new Observable(); - /** - * Will trigger when the timer ended successfully - */ - this.onTimerEndedObservable = new Observable(); - /** - * Will trigger when the timer state has changed - */ - this.onStateChangedObservable = new Observable(); - this._observer = null; - this._breakOnNextTick = false; - this._tick = (payload) => { - const now = Date.now(); - this._timer = now - this._startTime; - const data = { - startTime: this._startTime, - currentTime: now, - deltaTime: this._timer, - completeRate: this._timer / this._timeToEnd, - payload, - }; - const shouldBreak = this._breakOnNextTick || this._breakCondition(data); - if (shouldBreak || this._timer >= this._timeToEnd) { - this._stop(data, shouldBreak); - } - else { - this.onEachCountObservable.notifyObservers(data); - } - }; - this._setState(TimerState.INIT); - this._contextObservable = options.contextObservable; - this._observableParameters = (_a = options.observableParameters) !== null && _a !== void 0 ? _a : {}; - this._breakCondition = (_b = options.breakCondition) !== null && _b !== void 0 ? _b : (() => false); - this._timeToEnd = options.timeout; - if (options.onEnded) { - this.onTimerEndedObservable.add(options.onEnded); - } - if (options.onTick) { - this.onEachCountObservable.add(options.onTick); - } - if (options.onAborted) { - this.onTimerAbortedObservable.add(options.onAborted); - } - } - /** - * set a breaking condition for this timer. Default is to never break during count - * @param predicate the new break condition. Returns true to break, false otherwise - */ - set breakCondition(predicate) { - this._breakCondition = predicate; - } - /** - * Reset ALL associated observables in this advanced timer - */ - clearObservables() { - this.onEachCountObservable.clear(); - this.onTimerAbortedObservable.clear(); - this.onTimerEndedObservable.clear(); - this.onStateChangedObservable.clear(); - } - /** - * Will start a new iteration of this timer. Only one instance of this timer can run at a time. - * - * @param timeToEnd how much time to measure until timer ended - */ - start(timeToEnd = this._timeToEnd) { - if (this._state === TimerState.STARTED) { - throw new Error("Timer already started. Please stop it before starting again"); - } - this._timeToEnd = timeToEnd; - this._startTime = Date.now(); - this._timer = 0; - this._observer = this._contextObservable.add(this._tick, this._observableParameters.mask, this._observableParameters.insertFirst, this._observableParameters.scope); - this._setState(TimerState.STARTED); - } - /** - * Will force a stop on the next tick. - */ - stop() { - if (this._state !== TimerState.STARTED) { - return; - } - this._breakOnNextTick = true; - } - /** - * Dispose this timer, clearing all resources - */ - dispose() { - if (this._observer) { - this._contextObservable.remove(this._observer); - } - this.clearObservables(); - } - _setState(newState) { - this._state = newState; - this.onStateChangedObservable.notifyObservers(this._state); - } - _stop(data, aborted = false) { - this._contextObservable.remove(this._observer); - this._setState(TimerState.ENDED); - if (aborted) { - this.onTimerAbortedObservable.notifyObservers(data); - } - else { - this.onTimerEndedObservable.notifyObservers(data); - } - } -} -//# sourceMappingURL=timer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRControllerTeleportation.js - - - - - - - - - - - - - - - - - - - - -/** - * This is a teleportation feature to be used with WebXR-enabled motion controllers. - * When enabled and attached, the feature will allow a user to move around and rotate in the scene using - * the input of the attached controllers. - */ -class WebXRMotionControllerTeleportation extends WebXRAbstractFeature { - /** - * Is rotation enabled when moving forward? - * Disabling this feature will prevent the user from deciding the direction when teleporting - */ - get rotationEnabled() { - return this._rotationEnabled; - } - /** - * Sets whether rotation is enabled or not - * @param enabled is rotation enabled when teleportation is shown - */ - set rotationEnabled(enabled) { - this._rotationEnabled = enabled; - if (this._options.teleportationTargetMesh) { - const children = this._options.teleportationTargetMesh.getChildMeshes(false, (node) => node.name === "rotationCone"); - if (children[0]) { - children[0].setEnabled(enabled); - } - } - } - /** - * Exposes the currently set teleportation target mesh. - */ - get teleportationTargetMesh() { - return this._options.teleportationTargetMesh || null; - } - /** - * constructs a new teleportation system - * @param _xrSessionManager an instance of WebXRSessionManager - * @param _options configuration object for this feature - */ - constructor(_xrSessionManager, _options) { - super(_xrSessionManager); - this._options = _options; - this._controllers = {}; - this._snappedToPoint = false; - this._cachedColor4White = new math_color_Color4(1, 1, 1, 1); - this._tmpRay = new ray_Ray(new math_vector_Vector3(), new math_vector_Vector3()); - this._tmpVector = new math_vector_Vector3(); - this._tmpQuaternion = new math_vector_Quaternion(); - /** - * Skip the next teleportation. This can be controlled by the user to prevent the user from teleportation - * to sections that are not yet "unlocked", but should still show the teleportation mesh. - */ - this.skipNextTeleportation = false; - /** - * Is movement backwards enabled - */ - this.backwardsMovementEnabled = true; - /** - * Distance to travel when moving backwards - */ - this.backwardsTeleportationDistance = 0.7; - /** - * The distance from the user to the inspection point in the direction of the controller - * A higher number will allow the user to move further - * defaults to 5 (meters, in xr units) - */ - this.parabolicCheckRadius = 5; - /** - * Should the module support parabolic ray on top of direct ray - * If enabled, the user will be able to point "at the sky" and move according to predefined radius distance - * Very helpful when moving between floors / different heights - */ - this.parabolicRayEnabled = true; - /** - * The second type of ray - straight line. - * Should it be enabled or should the parabolic line be the only one. - */ - this.straightRayEnabled = true; - /** - * How much rotation should be applied when rotating right and left - */ - this.rotationAngle = Math.PI / 8; - /** - * This observable will notify when the target mesh position was updated. - * The picking info it provides contains the point to which the target mesh will move () - */ - this.onTargetMeshPositionUpdatedObservable = new observable_Observable(); - /** - * Is teleportation enabled. Can be used to allow rotation only. - */ - this.teleportationEnabled = true; - this._rotationEnabled = true; - this._attachController = (xrController) => { - if (this._controllers[xrController.uniqueId] || (this._options.forceHandedness && xrController.inputSource.handedness !== this._options.forceHandedness)) { - // already attached - return; - } - this._controllers[xrController.uniqueId] = { - xrController, - teleportationState: { - forward: false, - backwards: false, - rotating: false, - currentRotation: 0, - baseRotation: 0, - blocked: false, - }, - }; - const controllerData = this._controllers[xrController.uniqueId]; - // motion controller only available to gamepad-enabled input sources. - if (controllerData.xrController.inputSource.targetRayMode === "tracked-pointer" && controllerData.xrController.inputSource.gamepad) { - // motion controller support - const initMotionController = () => { - if (xrController.motionController) { - const movementController = xrController.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE) || - xrController.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE); - if (!movementController || this._options.useMainComponentOnly) { - // use trigger to move on long press - const mainComponent = xrController.motionController.getMainComponent(); - if (!mainComponent) { - return; - } - controllerData.teleportationComponent = mainComponent; - controllerData.onButtonChangedObserver = mainComponent.onButtonStateChangedObservable.add(() => { - if (!this.teleportationEnabled) { - return; - } - // did "pressed" changed? - if (mainComponent.changes.pressed) { - if (mainComponent.changes.pressed.current) { - // simulate "forward" thumbstick push - controllerData.teleportationState.forward = true; - this._currentTeleportationControllerId = controllerData.xrController.uniqueId; - controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y; - controllerData.teleportationState.currentRotation = 0; - const timeToSelect = this._options.timeToTeleport || 3000; - setAndStartTimer({ - timeout: timeToSelect, - contextObservable: this._xrSessionManager.onXRFrameObservable, - breakCondition: () => !mainComponent.pressed, - onEnded: () => { - if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId && controllerData.teleportationState.forward) { - this._teleportForward(xrController.uniqueId); - } - }, - }); - } - else { - controllerData.teleportationState.forward = false; - this._currentTeleportationControllerId = ""; - } - } - }); - } - else { - controllerData.teleportationComponent = movementController; - // use thumbstick (or touchpad if thumbstick not available) - controllerData.onAxisChangedObserver = movementController.onAxisValueChangedObservable.add((axesData) => { - if (axesData.y <= 0.7 && controllerData.teleportationState.backwards) { - controllerData.teleportationState.backwards = false; - } - if (axesData.y > 0.7 && !controllerData.teleportationState.forward && this.backwardsMovementEnabled && !this.snapPointsOnly) { - // teleport backwards - // General gist: Go Back N units, cast a ray towards the floor. If collided, move. - if (!controllerData.teleportationState.backwards) { - controllerData.teleportationState.backwards = true; - // teleport backwards ONCE - this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion); - this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector); - // get only the y rotation - this._tmpVector.x = 0; - this._tmpVector.z = 0; - // get the quaternion - math_vector_Quaternion.FromEulerVectorToRef(this._tmpVector, this._tmpQuaternion); - this._tmpVector.set(0, 0, this.backwardsTeleportationDistance * (this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1.0)); - this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion, this._tmpVector); - this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position); - this._tmpRay.origin.copyFrom(this._tmpVector); - // This will prevent the user from "falling" to a lower platform! - // TODO - should this be a flag? 'allow falling to lower platforms'? - this._tmpRay.length = this._options.xrInput.xrCamera.realWorldHeight + 0.1; - // Right handed system had here "1" instead of -1. This is unneeded. - this._tmpRay.direction.set(0, -1, 0); - const pick = this._xrSessionManager.scene.pickWithRay(this._tmpRay, (o) => { - return this._floorMeshes.indexOf(o) !== -1; - }); - // pick must exist, but stay safe - if (pick && pick.pickedPoint) { - // Teleport the users feet to where they targeted. Ignore the Y axis. - // If the "falling to lower platforms" feature is implemented the Y axis should be set here as well - this._options.xrInput.xrCamera.position.x = pick.pickedPoint.x; - this._options.xrInput.xrCamera.position.z = pick.pickedPoint.z; - } - } - } - if (axesData.y < -0.7 && !this._currentTeleportationControllerId && !controllerData.teleportationState.rotating && this.teleportationEnabled) { - controllerData.teleportationState.forward = true; - this._currentTeleportationControllerId = controllerData.xrController.uniqueId; - controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y; - } - if (axesData.x) { - if (!controllerData.teleportationState.forward) { - if (!controllerData.teleportationState.rotating && Math.abs(axesData.x) > 0.7) { - // rotate in the right direction positive is right - controllerData.teleportationState.rotating = true; - const rotation = this.rotationAngle * (axesData.x > 0 ? 1 : -1) * (this._xrSessionManager.scene.useRightHandedSystem ? -1 : 1); - math_vector_Quaternion.FromEulerAngles(0, rotation, 0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion, this._options.xrInput.xrCamera.rotationQuaternion); - } - } - else { - if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId) { - // set the rotation of the forward movement - if (this.rotationEnabled) { - setTimeout(() => { - controllerData.teleportationState.currentRotation = Math.atan2(axesData.x, axesData.y * (this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1)); - }); - } - else { - controllerData.teleportationState.currentRotation = 0; - } - } - } - } - else { - controllerData.teleportationState.rotating = false; - } - if (axesData.x === 0 && axesData.y === 0) { - if (controllerData.teleportationState.blocked) { - controllerData.teleportationState.blocked = false; - this._setTargetMeshVisibility(false); - } - if (controllerData.teleportationState.forward) { - this._teleportForward(xrController.uniqueId); - } - } - }); - } - } - }; - if (xrController.motionController) { - initMotionController(); - } - else { - xrController.onMotionControllerInitObservable.addOnce(() => { - initMotionController(); - }); - } - } - else { - this._xrSessionManager.scene.onPointerObservable.add((pointerInfo) => { - if (pointerInfo.type === pointerEvents_PointerEventTypes.POINTERDOWN) { - controllerData.teleportationState.forward = true; - this._currentTeleportationControllerId = controllerData.xrController.uniqueId; - controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y; - controllerData.teleportationState.currentRotation = 0; - const timeToSelect = this._options.timeToTeleport || 3000; - setAndStartTimer({ - timeout: timeToSelect, - contextObservable: this._xrSessionManager.onXRFrameObservable, - onEnded: () => { - if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId && controllerData.teleportationState.forward) { - this._teleportForward(xrController.uniqueId); - } - }, - }); - } - else if (pointerInfo.type === pointerEvents_PointerEventTypes.POINTERUP) { - controllerData.teleportationState.forward = false; - this._currentTeleportationControllerId = ""; - } - }); - } - }; - // create default mesh if not provided - if (!this._options.teleportationTargetMesh) { - this._createDefaultTargetMesh(); - } - this._floorMeshes = this._options.floorMeshes || []; - this._snapToPositions = this._options.snapPositions || []; - this._blockedRayColor = this._options.blockedRayColor || new math_color_Color4(1, 0, 0, 0.75); - this._setTargetMeshVisibility(false); - } - /** - * Get the snapPointsOnly flag - */ - get snapPointsOnly() { - return !!this._options.snapPointsOnly; - } - /** - * Sets the snapPointsOnly flag - * @param snapToPoints should teleportation be exclusively to snap points - */ - set snapPointsOnly(snapToPoints) { - this._options.snapPointsOnly = snapToPoints; - } - /** - * Add a new mesh to the floor meshes array - * @param mesh the mesh to use as floor mesh - */ - addFloorMesh(mesh) { - this._floorMeshes.push(mesh); - } - /** - * Add a mesh to the list of meshes blocking the teleportation ray - * @param mesh The mesh to add to the teleportation-blocking meshes - */ - addBlockerMesh(mesh) { - this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || []; - this._options.pickBlockerMeshes.push(mesh); - } - /** - * Add a new snap-to point to fix teleportation to this position - * @param newSnapPoint The new Snap-To point - */ - addSnapPoint(newSnapPoint) { - this._snapToPositions.push(newSnapPoint); - } - attach() { - if (!super.attach()) { - return false; - } - // Safety reset - this._currentTeleportationControllerId = ""; - this._options.xrInput.controllers.forEach(this._attachController); - this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController); - this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => { - // REMOVE the controller - this._detachController(controller.uniqueId); - }); - return true; - } - detach() { - if (!super.detach()) { - return false; - } - Object.keys(this._controllers).forEach((controllerId) => { - this._detachController(controllerId); - }); - this._setTargetMeshVisibility(false); - this._currentTeleportationControllerId = ""; - this._controllers = {}; - return true; - } - dispose() { - super.dispose(); - this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.dispose(false, true); - } - /** - * Remove a mesh from the floor meshes array - * @param mesh the mesh to remove - */ - removeFloorMesh(mesh) { - const index = this._floorMeshes.indexOf(mesh); - if (index !== -1) { - this._floorMeshes.splice(index, 1); - } - } - /** - * Remove a mesh from the blocker meshes array - * @param mesh the mesh to remove - */ - removeBlockerMesh(mesh) { - this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || []; - const index = this._options.pickBlockerMeshes.indexOf(mesh); - if (index !== -1) { - this._options.pickBlockerMeshes.splice(index, 1); - } - } - /** - * Remove a mesh from the floor meshes array using its name - * @param name the mesh name to remove - */ - removeFloorMeshByName(name) { - const mesh = this._xrSessionManager.scene.getMeshByName(name); - if (mesh) { - this.removeFloorMesh(mesh); - } - } - /** - * 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 - * @param snapPointToRemove the point (or a clone of it) to be removed from the array - * @returns was the point found and removed or not - */ - removeSnapPoint(snapPointToRemove) { - // check if the object is in the array - let index = this._snapToPositions.indexOf(snapPointToRemove); - // if not found as an object, compare to the points - if (index === -1) { - for (let i = 0; i < this._snapToPositions.length; ++i) { - // equals? index is i, break the loop - if (this._snapToPositions[i].equals(snapPointToRemove)) { - index = i; - break; - } - } - } - // index is not -1? remove the object - if (index !== -1) { - this._snapToPositions.splice(index, 1); - return true; - } - return false; - } - /** - * This function sets a selection feature that will be disabled when - * the forward ray is shown and will be reattached when hidden. - * This is used to remove the selection rays when moving. - * @param selectionFeature the feature to disable when forward movement is enabled - */ - setSelectionFeature(selectionFeature) { - this._selectionFeature = selectionFeature; - } - _onXRFrame(_xrFrame) { - const frame = this._xrSessionManager.currentFrame; - const scene = this._xrSessionManager.scene; - if (!this.attach || !frame) { - return; - } - // render target if needed - const targetMesh = this._options.teleportationTargetMesh; - if (this._currentTeleportationControllerId) { - if (!targetMesh) { - return; - } - targetMesh.rotationQuaternion = targetMesh.rotationQuaternion || new math_vector_Quaternion(); - const controllerData = this._controllers[this._currentTeleportationControllerId]; - if (controllerData && controllerData.teleportationState.forward) { - // set the rotation - math_vector_Quaternion.RotationYawPitchRollToRef(controllerData.teleportationState.currentRotation + controllerData.teleportationState.baseRotation, 0, 0, targetMesh.rotationQuaternion); - // set the ray and position - let hitPossible = false; - controllerData.xrController.getWorldPointerRayToRef(this._tmpRay); - if (this.straightRayEnabled) { - // first check if direct ray possible - // pick grounds that are LOWER only. upper will use parabolic path - const pick = scene.pickWithRay(this._tmpRay, (o) => { - // check for mesh-blockers - if (this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(o) !== -1) { - return true; - } - const index = this._floorMeshes.indexOf(o); - if (index === -1) { - return false; - } - return this._floorMeshes[index].absolutePosition.y < this._options.xrInput.xrCamera.globalPosition.y; - }); - if (pick && pick.pickedMesh && this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(pick.pickedMesh) !== -1) { - controllerData.teleportationState.blocked = true; - this._setTargetMeshVisibility(false); - this._showParabolicPath(pick); - return; - } - else if (pick && pick.pickedPoint) { - controllerData.teleportationState.blocked = false; - hitPossible = true; - this._setTargetMeshPosition(pick); - this._setTargetMeshVisibility(true); - this._showParabolicPath(pick); - } - } - // straight ray is still the main ray, but disabling the straight line will force parabolic line. - if (this.parabolicRayEnabled && !hitPossible) { - // radius compensation according to pointer rotation around X - const xRotation = controllerData.xrController.pointer.rotationQuaternion.toEulerAngles().x; - const compensation = 1 + (Math.PI / 2 - Math.abs(xRotation)); - // check parabolic ray - const radius = this.parabolicCheckRadius * compensation; - this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(radius * 2), this._tmpVector); - this._tmpVector.y = this._tmpRay.origin.y; - this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(radius)); - this._tmpVector.subtractToRef(this._tmpRay.origin, this._tmpRay.direction); - this._tmpRay.direction.normalize(); - const pick = scene.pickWithRay(this._tmpRay, (o) => { - // check for mesh-blockers - if (this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(o) !== -1) { - return true; - } - return this._floorMeshes.indexOf(o) !== -1; - }); - if (pick && pick.pickedMesh && this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(pick.pickedMesh) !== -1) { - controllerData.teleportationState.blocked = true; - this._setTargetMeshVisibility(false); - this._showParabolicPath(pick); - return; - } - else if (pick && pick.pickedPoint) { - controllerData.teleportationState.blocked = false; - hitPossible = true; - this._setTargetMeshPosition(pick); - this._setTargetMeshVisibility(true); - this._showParabolicPath(pick); - } - } - // if needed, set visible: - this._setTargetMeshVisibility(hitPossible); - } - else { - this._setTargetMeshVisibility(false); - } - } - else { - this._disposeBezierCurve(); - this._setTargetMeshVisibility(false); - } - } - _createDefaultTargetMesh() { - // set defaults - this._options.defaultTargetMeshOptions = this._options.defaultTargetMeshOptions || {}; - const sceneToRenderTo = this._options.useUtilityLayer - ? this._options.customUtilityLayerScene || utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene - : this._xrSessionManager.scene; - const teleportationTarget = CreateGround("teleportationTarget", { width: 2, height: 2, subdivisions: 2 }, sceneToRenderTo); - teleportationTarget.isPickable = false; - if (this._options.defaultTargetMeshOptions.teleportationCircleMaterial) { - teleportationTarget.material = this._options.defaultTargetMeshOptions.teleportationCircleMaterial; - } - else { - const length = 512; - const dynamicTexture = new dynamicTexture_DynamicTexture("teleportationPlaneDynamicTexture", length, sceneToRenderTo, true); - dynamicTexture.hasAlpha = true; - const context = dynamicTexture.getContext(); - const centerX = length / 2; - const centerY = length / 2; - const radius = 200; - context.beginPath(); - context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); - context.fillStyle = this._options.defaultTargetMeshOptions.teleportationFillColor || "#444444"; - context.fill(); - context.lineWidth = 10; - context.strokeStyle = this._options.defaultTargetMeshOptions.teleportationBorderColor || "#FFFFFF"; - context.stroke(); - context.closePath(); - dynamicTexture.update(); - const teleportationCircleMaterial = new standardMaterial_StandardMaterial("teleportationPlaneMaterial", sceneToRenderTo); - teleportationCircleMaterial.diffuseTexture = dynamicTexture; - teleportationTarget.material = teleportationCircleMaterial; - } - const torus = CreateTorus("torusTeleportation", { - diameter: 0.75, - thickness: 0.1, - tessellation: 20, - }, sceneToRenderTo); - torus.isPickable = false; - torus.parent = teleportationTarget; - if (!this._options.defaultTargetMeshOptions.disableAnimation) { - const animationInnerCircle = new animation_Animation("animationInnerCircle", "position.y", 30, animation_Animation.ANIMATIONTYPE_FLOAT, animation_Animation.ANIMATIONLOOPMODE_CYCLE); - const keys = []; - keys.push({ - frame: 0, - value: 0, - }); - keys.push({ - frame: 30, - value: 0.4, - }); - keys.push({ - frame: 60, - value: 0, - }); - animationInnerCircle.setKeys(keys); - const easingFunction = new SineEase(); - easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT); - animationInnerCircle.setEasingFunction(easingFunction); - torus.animations = []; - torus.animations.push(animationInnerCircle); - sceneToRenderTo.beginAnimation(torus, 0, 60, true); - } - const cone = cylinderBuilder_CreateCylinder("rotationCone", { diameterTop: 0, tessellation: 4 }, sceneToRenderTo); - cone.isPickable = false; - cone.scaling.set(0.5, 0.12, 0.2); - cone.rotate(math_axis_Axis.X, Math.PI / 2); - cone.position.z = 0.6; - cone.parent = torus; - if (this._options.defaultTargetMeshOptions.torusArrowMaterial) { - torus.material = this._options.defaultTargetMeshOptions.torusArrowMaterial; - cone.material = this._options.defaultTargetMeshOptions.torusArrowMaterial; - } - else { - const torusConeMaterial = new standardMaterial_StandardMaterial("torusConsMat", sceneToRenderTo); - torusConeMaterial.disableLighting = !!this._options.defaultTargetMeshOptions.disableLighting; - if (torusConeMaterial.disableLighting) { - torusConeMaterial.emissiveColor = new math_color_Color3(0.3, 0.3, 1.0); - } - else { - torusConeMaterial.diffuseColor = new math_color_Color3(0.3, 0.3, 1.0); - } - torusConeMaterial.alpha = 0.9; - torus.material = torusConeMaterial; - cone.material = torusConeMaterial; - this._teleportationRingMaterial = torusConeMaterial; - } - if (this._options.renderingGroupId !== undefined) { - teleportationTarget.renderingGroupId = this._options.renderingGroupId; - torus.renderingGroupId = this._options.renderingGroupId; - cone.renderingGroupId = this._options.renderingGroupId; - } - this._options.teleportationTargetMesh = teleportationTarget; - // hide the teleportation target mesh right after creating it. - this._setTargetMeshVisibility(false); - } - _detachController(xrControllerUniqueId) { - const controllerData = this._controllers[xrControllerUniqueId]; - if (!controllerData) { - return; - } - if (controllerData.teleportationComponent) { - if (controllerData.onAxisChangedObserver) { - controllerData.teleportationComponent.onAxisValueChangedObservable.remove(controllerData.onAxisChangedObserver); - } - if (controllerData.onButtonChangedObserver) { - controllerData.teleportationComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver); - } - } - // remove from the map - delete this._controllers[xrControllerUniqueId]; - } - _findClosestSnapPointWithRadius(realPosition, radius = this._options.snapToPositionRadius || 0.8) { - let closestPoint = null; - let closestDistance = Number.MAX_VALUE; - if (this._snapToPositions.length) { - const radiusSquared = radius * radius; - this._snapToPositions.forEach((position) => { - const dist = math_vector_Vector3.DistanceSquared(position, realPosition); - if (dist <= radiusSquared && dist < closestDistance) { - closestDistance = dist; - closestPoint = position; - } - }); - } - return closestPoint; - } - _setTargetMeshPosition(pickInfo) { - const newPosition = pickInfo.pickedPoint; - if (!this._options.teleportationTargetMesh || !newPosition) { - return; - } - const snapPosition = this._findClosestSnapPointWithRadius(newPosition); - this._snappedToPoint = !!snapPosition; - if (this.snapPointsOnly && !this._snappedToPoint && this._teleportationRingMaterial) { - this._teleportationRingMaterial.diffuseColor.set(1.0, 0.3, 0.3); - } - else if (this.snapPointsOnly && this._snappedToPoint && this._teleportationRingMaterial) { - this._teleportationRingMaterial.diffuseColor.set(0.3, 0.3, 1.0); - } - this._options.teleportationTargetMesh.position.copyFrom(snapPosition || newPosition); - this._options.teleportationTargetMesh.position.y += 0.01; - this.onTargetMeshPositionUpdatedObservable.notifyObservers(pickInfo); - } - _setTargetMeshVisibility(visible, force) { - if (!this._options.teleportationTargetMesh) { - return; - } - if (this._options.teleportationTargetMesh.isVisible === visible && !force) { - return; - } - this._options.teleportationTargetMesh.isVisible = visible; - this._options.teleportationTargetMesh.getChildren(undefined, false).forEach((m) => { - m.isVisible = visible; - }); - if (!visible) { - if (this._quadraticBezierCurve) { - this._quadraticBezierCurve.dispose(); - this._quadraticBezierCurve = null; - } - if (this._selectionFeature) { - this._selectionFeature.attach(); - } - } - else { - if (this._selectionFeature) { - this._selectionFeature.detach(); - } - } - } - _disposeBezierCurve() { - if (this._quadraticBezierCurve) { - this._quadraticBezierCurve.dispose(); - this._quadraticBezierCurve = null; - } - } - _showParabolicPath(pickInfo) { - if (!pickInfo.pickedPoint || !this._currentTeleportationControllerId) { - return; - } - const sceneToRenderTo = this._options.useUtilityLayer - ? this._options.customUtilityLayerScene || utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene - : this._xrSessionManager.scene; - const controllerData = this._controllers[this._currentTeleportationControllerId]; - const quadraticBezierVectors = Curve3.CreateQuadraticBezier(controllerData.xrController.pointer.absolutePosition, pickInfo.ray.origin, pickInfo.pickedPoint, 25); - const color = controllerData.teleportationState.blocked ? this._blockedRayColor : undefined; - const colorsArray = new Array(26).fill(color || this._cachedColor4White); - if (!this._options.generateRayPathMesh) { - this._quadraticBezierCurve = linesBuilder_CreateLines("teleportation path line", { points: quadraticBezierVectors.getPoints(), instance: this._quadraticBezierCurve, updatable: true, colors: colorsArray }, sceneToRenderTo); - } - else { - this._quadraticBezierCurve = this._options.generateRayPathMesh(quadraticBezierVectors.getPoints(), pickInfo); - } - this._quadraticBezierCurve.isPickable = false; - if (this._options.renderingGroupId !== undefined) { - this._quadraticBezierCurve.renderingGroupId = this._options.renderingGroupId; - } - } - _teleportForward(controllerId) { - const controllerData = this._controllers[controllerId]; - if (!controllerData || !controllerData.teleportationState.forward || !this.teleportationEnabled) { - return; - } - controllerData.teleportationState.forward = false; - this._currentTeleportationControllerId = ""; - if (this.snapPointsOnly && !this._snappedToPoint) { - return; - } - if (this.skipNextTeleportation) { - this.skipNextTeleportation = false; - return; - } - // do the movement forward here - if (this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.isVisible) { - const height = 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 += height; - math_vector_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); - this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position); - } - } -} -/** - * The module's name - */ -WebXRMotionControllerTeleportation.Name = webXRFeaturesManager_WebXRFeatureName.TELEPORTATION; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the webxr specs version - */ -WebXRMotionControllerTeleportation.Version = 1; -WebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name, (xrSessionManager, options) => { - return () => new WebXRMotionControllerTeleportation(xrSessionManager, options); -}, WebXRMotionControllerTeleportation.Version, true); -//# sourceMappingURL=WebXRControllerTeleportation.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/webXRDefaultExperience.js - - - - - - - -/** - * Options for the default xr helper - */ -class WebXRDefaultExperienceOptions { -} -/** - * Default experience which provides a similar setup to the previous webVRExperience - */ -class WebXRDefaultExperience { - constructor() { } - /** - * Creates the default xr experience - * @param scene scene - * @param options options for basic configuration - * @returns resulting WebXRDefaultExperience - */ - static CreateAsync(scene, options = {}) { - const result = new WebXRDefaultExperience(); - scene.onDisposeObservable.addOnce(() => { - result.dispose(); - }); - // init the UI right after construction - if (!options.disableDefaultUI) { - const uiOptions = Object.assign({ renderTarget: result.renderTarget }, (options.uiOptions || {})); - if (options.optionalFeatures) { - if (typeof options.optionalFeatures === "boolean") { - uiOptions.optionalFeatures = ["hit-test", "anchors", "plane-detection", "hand-tracking"]; - } - else { - uiOptions.optionalFeatures = options.optionalFeatures; - } - } - result.enterExitUI = new WebXREnterExitUI(scene, uiOptions); - } - // Create base experience - return WebXRExperienceHelper.CreateAsync(scene) - .then((xrHelper) => { - result.baseExperience = xrHelper; - if (options.ignoreNativeCameraTransformation) { - result.baseExperience.camera.compensateOnFirstFrame = false; - } - // Add controller support - result.input = new WebXRInput(xrHelper.sessionManager, xrHelper.camera, Object.assign({ controllerOptions: { - renderingGroupId: options.renderingGroupId, - } }, (options.inputOptions || {}))); - if (!options.disablePointerSelection) { - // Add default pointer selection - const pointerSelectionOptions = Object.assign(Object.assign({}, options.pointerSelectionOptions), { xrInput: result.input, renderingGroupId: options.renderingGroupId }); - result.pointerSelection = (result.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name, options.useStablePlugins ? "stable" : "latest", pointerSelectionOptions)); - if (!options.disableTeleportation) { - // Add default teleportation, including rotation - 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)); - result.teleportation.setSelectionFeature(result.pointerSelection); - } - } - if (!options.disableNearInteraction) { - // Add default pointer selection - 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)); - } - // Create the WebXR output target - result.renderTarget = result.baseExperience.sessionManager.getWebXRRenderTarget(options.outputCanvasOptions); - if (!options.disableDefaultUI) { - // Create ui for entering/exiting xr - return result.enterExitUI.setHelperAsync(result.baseExperience, result.renderTarget); - } - else { - return; - } - }) - .then(() => { - return result; - }) - .catch((error) => { - logger_Logger.Error("Error initializing XR"); - logger_Logger.Error(error); - return result; - }); - } - /** - * Disposes of the experience helper - */ - dispose() { - if (this.baseExperience) { - this.baseExperience.dispose(); - } - if (this.input) { - this.input.dispose(); - } - if (this.enterExitUI) { - this.enterExitUI.dispose(); - } - if (this.renderTarget) { - this.renderTarget.dispose(); - } - } -} -//# sourceMappingURL=webXRDefaultExperience.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Helpers/sceneHelpers.js - - - - - - - - - - - - - - - - -/** @internal */ -// eslint-disable-next-line no-var -var _forceSceneHelpersToBundle = true; -scene_Scene.prototype.createDefaultLight = function (replace = false) { - // Dispose existing light in replace mode. - if (replace) { - if (this.lights) { - for (let i = 0; i < this.lights.length; i++) { - this.lights[i].dispose(); - } - } - } - // Light - if (this.lights.length === 0) { - new HemisphericLight("default light", math_vector_Vector3.Up(), this); - } -}; -scene_Scene.prototype.createDefaultCamera = function (createArcRotateCamera = false, replace = false, attachCameraControls = false) { - // Dispose existing camera in replace mode. - if (replace) { - if (this.activeCamera) { - this.activeCamera.dispose(); - this.activeCamera = null; - } - } - // Camera - if (!this.activeCamera) { - const worldExtends = this.getWorldExtends((mesh) => mesh.isVisible && mesh.isEnabled()); - const worldSize = worldExtends.max.subtract(worldExtends.min); - const worldCenter = worldExtends.min.add(worldSize.scale(0.5)); - let camera; - let radius = worldSize.length() * 1.5; - // empty scene scenario! - if (!isFinite(radius)) { - radius = 1; - worldCenter.copyFromFloats(0, 0, 0); - } - if (createArcRotateCamera) { - const arcRotateCamera = new ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this); - arcRotateCamera.lowerRadiusLimit = radius * 0.01; - arcRotateCamera.wheelPrecision = 100 / radius; - camera = arcRotateCamera; - } - else { - const freeCamera = new FreeCamera("default camera", new math_vector_Vector3(worldCenter.x, worldCenter.y, -radius), this); - freeCamera.setTarget(worldCenter); - camera = freeCamera; - } - camera.minZ = radius * 0.01; - camera.maxZ = radius * 1000; - camera.speed = radius * 0.2; - this.activeCamera = camera; - if (attachCameraControls) { - camera.attachControl(); - } - } -}; -scene_Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera = false, replace = false, attachCameraControls = false) { - this.createDefaultLight(replace); - this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls); -}; -scene_Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr = false, scale = 1000, blur = 0, setGlobalEnvTexture = true) { - if (!environmentTexture) { - logger_Logger.Warn("Can not create default skybox without environment texture."); - return null; - } - if (setGlobalEnvTexture) { - if (environmentTexture) { - this.environmentTexture = environmentTexture; - } - } - // Skybox - const hdrSkybox = boxBuilder_CreateBox("hdrSkyBox", { size: scale }, this); - if (pbr) { - const hdrSkyboxMaterial = new pbrMaterial_PBRMaterial("skyBox", this); - hdrSkyboxMaterial.backFaceCulling = false; - hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone(); - if (hdrSkyboxMaterial.reflectionTexture) { - hdrSkyboxMaterial.reflectionTexture.coordinatesMode = texture_Texture.SKYBOX_MODE; - } - hdrSkyboxMaterial.microSurface = 1.0 - blur; - hdrSkyboxMaterial.disableLighting = true; - hdrSkyboxMaterial.twoSidedLighting = true; - hdrSkybox.material = hdrSkyboxMaterial; - } - else { - const skyboxMaterial = new standardMaterial_StandardMaterial("skyBox", this); - skyboxMaterial.backFaceCulling = false; - skyboxMaterial.reflectionTexture = environmentTexture.clone(); - if (skyboxMaterial.reflectionTexture) { - skyboxMaterial.reflectionTexture.coordinatesMode = texture_Texture.SKYBOX_MODE; - } - skyboxMaterial.disableLighting = true; - hdrSkybox.material = skyboxMaterial; - } - hdrSkybox.isPickable = false; - hdrSkybox.infiniteDistance = true; - hdrSkybox.ignoreCameraMaxZ = true; - return hdrSkybox; -}; -scene_Scene.prototype.createDefaultEnvironment = function (options) { - if (EnvironmentHelper) { - return new EnvironmentHelper(options, this); - } - return null; -}; -scene_Scene.prototype.createDefaultVRExperience = function (webVROptions = {}) { - return new VRExperienceHelper(this, webVROptions); -}; -scene_Scene.prototype.createDefaultXRExperienceAsync = function (options = {}) { - return WebXRDefaultExperience.CreateAsync(this, options).then((helper) => { - return helper; - }); -}; -//# sourceMappingURL=sceneHelpers.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/videoTexture.js - - - - - - - -function removeSource(video) { - // Remove any <source> elements, etc. - while (video.firstChild) { - video.removeChild(video.firstChild); - } - // detach srcObject - video.srcObject = null; - // Set a blank src (https://html.spec.whatwg.org/multipage/media.html#best-practices-for-authors-using-media-elements) - video.src = ""; - // Prevent non-important errors maybe (https://twitter.com/beraliv/status/1205214277956775936) - video.removeAttribute("src"); -} -/** - * If you want to display a video in your scene, this is the special texture for that. - * This special texture works similar to other textures, with the exception of a few parameters. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/videoTexture - */ -class VideoTexture extends texture_Texture { - /** - * Event triggered when a dom action is required by the user to play the video. - * This happens due to recent changes in browser policies preventing video to auto start. - */ - get onUserActionRequestedObservable() { - if (!this._onUserActionRequestedObservable) { - this._onUserActionRequestedObservable = new observable_Observable(); - } - return this._onUserActionRequestedObservable; - } - _processError(reason) { - this._errorFound = true; - if (this._onError) { - this._onError(reason === null || reason === void 0 ? void 0 : reason.message); - } - else { - logger_Logger.Error(reason === null || reason === void 0 ? void 0 : reason.message); - } - } - _handlePlay() { - this._errorFound = false; - this.video.play().catch((reason) => { - if ((reason === null || reason === void 0 ? void 0 : reason.name) === "NotAllowedError") { - if (this._onUserActionRequestedObservable && this._onUserActionRequestedObservable.hasObservers()) { - this._onUserActionRequestedObservable.notifyObservers(this); - return; - } - else if (!this.video.muted) { - logger_Logger.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"); - this.video.muted = true; - this._errorFound = false; - this.video.play().catch((otherReason) => { - this._processError(otherReason); - }); - return; - } - } - this._processError(reason); - }); - } - /** - * Creates a video texture. - * If you want to display a video in your scene, this is the special texture for that. - * This special texture works similar to other textures, with the exception of a few parameters. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/videoTexture - * @param name optional name, will detect from video source, if not defined - * @param src can be used to provide an url, array of urls or an already setup HTML video element. - * @param scene is obviously the current scene. - * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated). - * @param invertY is false by default but can be used to invert video on Y axis - * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default - * @param settings allows finer control over video usage - * @param onError defines a callback triggered when an error occurred during the loading session - * @param format defines the texture format to use (Engine.TEXTUREFORMAT_RGBA by default) - */ - constructor(name, src, scene, generateMipMaps = false, invertY = false, samplingMode = texture_Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) { - var _a, _b; - super(null, scene, !generateMipMaps, invertY); - this._onUserActionRequestedObservable = null; - this._stillImageCaptured = false; - this._displayingPosterTexture = false; - this._frameId = -1; - this._currentSrc = null; - this._errorFound = false; - this._resizeInternalTexture = () => { - var _a; - // Cleanup the old texture before replacing it - if (this._texture != null) { - this._texture.dispose(); - } - if (!this._getEngine().needPOTTextures || (tools_Tools.IsExponentOfTwo(this.video.videoWidth) && tools_Tools.IsExponentOfTwo(this.video.videoHeight))) { - this.wrapU = texture_Texture.WRAP_ADDRESSMODE; - this.wrapV = texture_Texture.WRAP_ADDRESSMODE; - } - else { - this.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._generateMipMaps = false; - } - this._texture = this._getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this.samplingMode); - this._texture.format = (_a = this._format) !== null && _a !== void 0 ? _a : 5; - // Reset the frame ID and update the new texture to ensure it pulls in the current video frame - this._frameId = -1; - this._updateInternalTexture(); - }; - this._createInternalTexture = () => { - if (this._texture != null) { - if (this._displayingPosterTexture) { - this._displayingPosterTexture = false; - } - else { - return; - } - } - this.video.addEventListener("resize", this._resizeInternalTexture); - this._resizeInternalTexture(); - if (!this.video.autoplay && !this._settings.poster && !this._settings.independentVideoSource) { - const oldHandler = this.video.onplaying; - const oldMuted = this.video.muted; - this.video.muted = true; - this.video.onplaying = () => { - this.video.muted = oldMuted; - this.video.onplaying = oldHandler; - this._updateInternalTexture(); - if (!this._errorFound) { - this.video.pause(); - } - if (this.onLoadObservable.hasObservers()) { - this.onLoadObservable.notifyObservers(this); - } - }; - this._handlePlay(); - } - else { - this._updateInternalTexture(); - if (this.onLoadObservable.hasObservers()) { - this.onLoadObservable.notifyObservers(this); - } - } - }; - this._reset = () => { - if (this._texture == null) { - return; - } - if (!this._displayingPosterTexture) { - this._texture.dispose(); - this._texture = null; - } - }; - this._updateInternalTexture = () => { - if (this._texture == null) { - return; - } - if (this.video.readyState < this.video.HAVE_CURRENT_DATA) { - return; - } - if (this._displayingPosterTexture) { - return; - } - const frameId = this.getScene().getFrameId(); - if (this._frameId === frameId) { - return; - } - this._frameId = frameId; - this._getEngine().updateVideoTexture(this._texture, this._externalTexture ? this._externalTexture : this.video, this._invertY); - }; - this._settings = Object.assign({ autoPlay: true, loop: true, autoUpdateTexture: true }, settings); - this._onError = onError; - this._generateMipMaps = generateMipMaps; - this._initialSamplingMode = samplingMode; - this.autoUpdateTexture = this._settings.autoUpdateTexture; - this._currentSrc = src; - this.name = name || this._getName(src); - this.video = this._getVideo(src); - this._externalTexture = (_b = (_a = this._engine) === null || _a === void 0 ? void 0 : _a.createExternalTexture(this.video)) !== null && _b !== void 0 ? _b : null; - if (!this._settings.independentVideoSource) { - if (this._settings.poster) { - this.video.poster = this._settings.poster; - } - if (this._settings.autoPlay !== undefined) { - this.video.autoplay = this._settings.autoPlay; - } - if (this._settings.loop !== undefined) { - this.video.loop = this._settings.loop; - } - if (this._settings.muted !== undefined) { - this.video.muted = this._settings.muted; - } - this.video.setAttribute("playsinline", ""); - this.video.addEventListener("paused", this._updateInternalTexture); - this.video.addEventListener("seeked", this._updateInternalTexture); - this.video.addEventListener("emptied", this._reset); - if (this._settings.autoPlay) { - this._handlePlay(); - } - } - this._createInternalTextureOnEvent = this._settings.poster && !this._settings.autoPlay ? "play" : "canplay"; - this.video.addEventListener(this._createInternalTextureOnEvent, this._createInternalTexture); - this._format = format; - const videoHasEnoughData = this.video.readyState >= this.video.HAVE_CURRENT_DATA; - if (this._settings.poster && (!this._settings.autoPlay || !videoHasEnoughData)) { - this._texture = this._getEngine().createTexture(this._settings.poster, false, !this.invertY, scene); - this._displayingPosterTexture = true; - } - else if (videoHasEnoughData) { - this._createInternalTexture(); - } - } - /** - * Get the current class name of the video texture useful for serialization or dynamic coding. - * @returns "VideoTexture" - */ - getClassName() { - return "VideoTexture"; - } - _getName(src) { - if (src instanceof HTMLVideoElement) { - return src.currentSrc; - } - if (typeof src === "object") { - return src.toString(); - } - return src; - } - _getVideo(src) { - if (src.isNative) { - return src; - } - if (src instanceof HTMLVideoElement) { - tools_Tools.SetCorsBehavior(src.currentSrc, src); - return src; - } - const video = document.createElement("video"); - if (typeof src === "string") { - tools_Tools.SetCorsBehavior(src, video); - video.src = src; - } - else { - tools_Tools.SetCorsBehavior(src[0], video); - src.forEach((url) => { - const source = document.createElement("source"); - source.src = url; - video.appendChild(source); - }); - } - this.onDisposeObservable.addOnce(() => { - removeSource(video); - }); - return video; - } - /** - * @internal Internal method to initiate `update`. - */ - _rebuild() { - this.update(); - } - /** - * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false. - */ - update() { - if (!this.autoUpdateTexture) { - // Expecting user to call `updateTexture` manually - return; - } - this.updateTexture(true); - } - /** - * Update Texture in `manual` mode. Does not do anything if not visible or paused. - * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or otherwise. - */ - updateTexture(isVisible) { - if (!isVisible) { - return; - } - if (this.video.paused && this._stillImageCaptured) { - return; - } - this._stillImageCaptured = true; - this._updateInternalTexture(); - } - /** - * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported. - * @param url New url. - */ - updateURL(url) { - this.video.src = url; - this._currentSrc = url; - } - /** - * Clones the texture. - * @returns the cloned texture - */ - clone() { - return new VideoTexture(this.name, this._currentSrc, this.getScene(), this._generateMipMaps, this.invertY, this.samplingMode, this._settings); - } - /** - * Dispose the texture and release its associated resources. - */ - dispose() { - var _a; - super.dispose(); - this._currentSrc = null; - if (this._onUserActionRequestedObservable) { - this._onUserActionRequestedObservable.clear(); - this._onUserActionRequestedObservable = null; - } - this.video.removeEventListener(this._createInternalTextureOnEvent, this._createInternalTexture); - if (!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(); - } - (_a = this._externalTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - } - /** - * Creates a video texture straight from a stream. - * @param scene Define the scene the texture should be created in - * @param stream Define the stream the texture should be created from - * @param constraints video constraints - * @param invertY Defines if the video should be stored with invert Y set to true (true by default) - * @returns The created video texture as a promise - */ - static CreateFromStreamAsync(scene, stream, constraints, invertY = true) { - const video = scene.getEngine().createVideoElement(constraints); - if (scene.getEngine()._badOS) { - // Yes... I know and I hope to remove it soon... - document.body.appendChild(video); - video.style.transform = "scale(0.0001, 0.0001)"; - video.style.opacity = "0"; - video.style.position = "fixed"; - video.style.bottom = "0px"; - video.style.right = "0px"; - } - video.setAttribute("autoplay", ""); - video.setAttribute("muted", "true"); - video.setAttribute("playsinline", ""); - video.muted = true; - if (video.isNative) { - // No additional configuration needed for native - } - else if (video.mozSrcObject !== undefined) { - // hack for Firefox < 19 - video.mozSrcObject = stream; - } - else { - if (typeof video.srcObject == "object") { - video.srcObject = stream; - } - else { - // older API. See https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL#using_object_urls_for_media_streams - video.src = window.URL && window.URL.createObjectURL(stream); - } - } - return new Promise((resolve) => { - const onPlaying = () => { - const videoTexture = new VideoTexture("video", video, scene, true, invertY, undefined, undefined, undefined, 4); - if (scene.getEngine()._badOS) { - videoTexture.onDisposeObservable.addOnce(() => { - video.remove(); - }); - } - videoTexture.onDisposeObservable.addOnce(() => { - removeSource(video); - }); - resolve(videoTexture); - video.removeEventListener("playing", onPlaying); - }; - video.addEventListener("playing", onPlaying); - video.play(); - }); - } - /** - * Creates a video texture straight from your WebCam video feed. - * @param scene Define the scene the texture should be created in - * @param constraints Define the constraints to use to create the web cam feed from WebRTC - * @param audioConstaints Define the audio constraints to use to create the web cam feed from WebRTC - * @param invertY Defines if the video should be stored with invert Y set to true (true by default) - * @returns The created video texture as a promise - */ - static async CreateFromWebCamAsync(scene, constraints, audioConstaints = false, invertY = true) { - if (navigator.mediaDevices) { - const stream = await navigator.mediaDevices.getUserMedia({ - video: constraints, - audio: audioConstaints, - }); - const videoTexture = await this.CreateFromStreamAsync(scene, stream, constraints, invertY); - videoTexture.onDisposeObservable.addOnce(() => { - stream.getTracks().forEach((track) => { - track.stop(); - }); - }); - return videoTexture; - } - return Promise.reject("No support for userMedia on this device"); - } - /** - * Creates a video texture straight from your WebCam video feed. - * @param scene Defines the scene the texture should be created in - * @param onReady Defines a callback to triggered once the texture will be ready - * @param constraints Defines the constraints to use to create the web cam feed from WebRTC - * @param audioConstaints Defines the audio constraints to use to create the web cam feed from WebRTC - * @param invertY Defines if the video should be stored with invert Y set to true (true by default) - */ - static CreateFromWebCam(scene, onReady, constraints, audioConstaints = false, invertY = true) { - this.CreateFromWebCamAsync(scene, constraints, audioConstaints, invertY) - .then(function (videoTexture) { - if (onReady) { - onReady(videoTexture); - } - }) - .catch(function (err) { - logger_Logger.Error(err.name); - }); - } -} -//# sourceMappingURL=videoTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Helpers/videoDome.js - - - - -/** - * Display a 360/180 degree video on an approximately spherical surface, useful for VR applications or skyboxes. - * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene. - * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere. - * Potential additions to this helper include zoom and and non-infinite distance rendering effects. - */ -class VideoDome extends TextureDome { - /** - * Get the video texture associated with this video dome - */ - get videoTexture() { - return this._texture; - } - /** - * Get the video mode of this dome - */ - get videoMode() { - return this.textureMode; - } - /** - * Set the video mode of this dome. - * @see textureMode - */ - set videoMode(value) { - this.textureMode = value; - } - _initTexture(urlsOrElement, scene, options) { - const tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster }; - const texture = new VideoTexture((this.name || "videoDome") + "_texture", urlsOrElement, scene, options.generateMipMaps, this._useDirectMapping, texture_Texture.TRILINEAR_SAMPLINGMODE, tempOptions); - // optional configuration - if (options.clickToPlay) { - this._pointerObserver = scene.onPointerObservable.add((data) => { - var _a; - ((_a = data.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) === this.mesh && this._texture.video.play(); - }, pointerEvents_PointerEventTypes.POINTERDOWN); - } - this._textureObserver = texture.onLoadObservable.add(() => { - this.onLoadObservable.notifyObservers(); - }); - return texture; - } - /** - * Releases resources associated with this node. - * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) - * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) - */ - dispose(doNotRecurse, disposeMaterialAndTextures = false) { - this._texture.onLoadObservable.remove(this._textureObserver); - this._scene.onPointerObservable.remove(this._pointerObserver); - super.dispose(doNotRecurse, disposeMaterialAndTextures); - } -} -/** - * Define the video source as a Monoscopic panoramic 360 video. - */ -VideoDome.MODE_MONOSCOPIC = TextureDome.MODE_MONOSCOPIC; -/** - * Define the video source as a Stereoscopic TopBottom/OverUnder panoramic 360 video. - */ -VideoDome.MODE_TOPBOTTOM = TextureDome.MODE_TOPBOTTOM; -/** - * Define the video source as a Stereoscopic Side by Side panoramic 360 video. - */ -VideoDome.MODE_SIDEBYSIDE = TextureDome.MODE_SIDEBYSIDE; -//# sourceMappingURL=videoDome.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Helpers/index.js - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Instrumentation/engineInstrumentation.js - -/** - * This class can be used to get instrumentation data from a Babylon engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation - */ -class engineInstrumentation_EngineInstrumentation { - // Properties - /** - * Gets the perf counter used for GPU frame time - */ - get gpuFrameTimeCounter() { - return this.engine.getGPUFrameTimeCounter(); - } - /** - * Gets the GPU frame time capture status - */ - get captureGPUFrameTime() { - return this._captureGPUFrameTime; - } - /** - * Enable or disable the GPU frame time capture - */ - set captureGPUFrameTime(value) { - if (value === this._captureGPUFrameTime) { - return; - } - this._captureGPUFrameTime = value; - this.engine.captureGPUFrameTime(value); - } - /** - * Gets the perf counter used for shader compilation time - */ - get shaderCompilationTimeCounter() { - return this._shaderCompilationTime; - } - /** - * Gets the shader compilation time capture status - */ - get captureShaderCompilationTime() { - return this._captureShaderCompilationTime; - } - /** - * Enable or disable the shader compilation time capture - */ - set captureShaderCompilationTime(value) { - if (value === this._captureShaderCompilationTime) { - return; - } - this._captureShaderCompilationTime = value; - if (value) { - this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(() => { - this._shaderCompilationTime.fetchNewFrame(); - this._shaderCompilationTime.beginMonitoring(); - }); - this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(() => { - this._shaderCompilationTime.endMonitoring(); - }); - } - else { - this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver); - this._onBeforeShaderCompilationObserver = null; - this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver); - this._onAfterShaderCompilationObserver = null; - } - } - /** - * Instantiates a new engine instrumentation. - * This class can be used to get instrumentation data from a Babylon engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation - * @param engine Defines the engine to instrument - */ - constructor( - /** - * Define the instrumented engine. - */ - engine) { - this.engine = engine; - this._captureGPUFrameTime = false; - this._captureShaderCompilationTime = false; - this._shaderCompilationTime = new PerfCounter(); - // Observers - this._onBeginFrameObserver = null; - this._onEndFrameObserver = null; - this._onBeforeShaderCompilationObserver = null; - this._onAfterShaderCompilationObserver = null; - } - /** - * Dispose and release associated resources. - */ - dispose() { - this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver); - this._onBeginFrameObserver = null; - this.engine.onEndFrameObservable.remove(this._onEndFrameObserver); - this._onEndFrameObserver = null; - this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver); - this._onBeforeShaderCompilationObserver = null; - this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver); - this._onAfterShaderCompilationObserver = null; - this.engine = null; - } -} -//# sourceMappingURL=engineInstrumentation.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Instrumentation/sceneInstrumentation.js - - -/** - * This class can be used to get instrumentation data from a Babylon engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#sceneinstrumentation - */ -class sceneInstrumentation_SceneInstrumentation { - // Properties - /** - * Gets the perf counter used for active meshes evaluation time - */ - get activeMeshesEvaluationTimeCounter() { - return this._activeMeshesEvaluationTime; - } - /** - * Gets the active meshes evaluation time capture status - */ - get captureActiveMeshesEvaluationTime() { - return this._captureActiveMeshesEvaluationTime; - } - /** - * Enable or disable the active meshes evaluation time capture - */ - set captureActiveMeshesEvaluationTime(value) { - if (value === this._captureActiveMeshesEvaluationTime) { - return; - } - this._captureActiveMeshesEvaluationTime = value; - if (value) { - this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(() => { - Tools.StartPerformanceCounter("Active meshes evaluation"); - this._activeMeshesEvaluationTime.beginMonitoring(); - }); - this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(() => { - Tools.EndPerformanceCounter("Active meshes evaluation"); - this._activeMeshesEvaluationTime.endMonitoring(false); - }); - } - else { - this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver); - this._onBeforeActiveMeshesEvaluationObserver = null; - this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver); - this._onAfterActiveMeshesEvaluationObserver = null; - } - } - /** - * Gets the perf counter used for render targets render time - */ - get renderTargetsRenderTimeCounter() { - return this._renderTargetsRenderTime; - } - /** - * Gets the render targets render time capture status - */ - get captureRenderTargetsRenderTime() { - return this._captureRenderTargetsRenderTime; - } - /** - * Enable or disable the render targets render time capture - */ - set captureRenderTargetsRenderTime(value) { - if (value === this._captureRenderTargetsRenderTime) { - return; - } - this._captureRenderTargetsRenderTime = value; - if (value) { - this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(() => { - Tools.StartPerformanceCounter("Render targets rendering"); - this._renderTargetsRenderTime.beginMonitoring(); - }); - this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(() => { - Tools.EndPerformanceCounter("Render targets rendering"); - this._renderTargetsRenderTime.endMonitoring(false); - }); - } - else { - this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver); - this._onBeforeRenderTargetsRenderObserver = null; - this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver); - this._onAfterRenderTargetsRenderObserver = null; - } - } - /** - * Gets the perf counter used for particles render time - */ - get particlesRenderTimeCounter() { - return this._particlesRenderTime; - } - /** - * Gets the particles render time capture status - */ - get captureParticlesRenderTime() { - return this._captureParticlesRenderTime; - } - /** - * Enable or disable the particles render time capture - */ - set captureParticlesRenderTime(value) { - if (value === this._captureParticlesRenderTime) { - return; - } - this._captureParticlesRenderTime = value; - if (value) { - this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(() => { - Tools.StartPerformanceCounter("Particles"); - this._particlesRenderTime.beginMonitoring(); - }); - this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(() => { - Tools.EndPerformanceCounter("Particles"); - this._particlesRenderTime.endMonitoring(false); - }); - } - else { - this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver); - this._onBeforeParticlesRenderingObserver = null; - this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver); - this._onAfterParticlesRenderingObserver = null; - } - } - /** - * Gets the perf counter used for sprites render time - */ - get spritesRenderTimeCounter() { - return this._spritesRenderTime; - } - /** - * Gets the sprites render time capture status - */ - get captureSpritesRenderTime() { - return this._captureSpritesRenderTime; - } - /** - * Enable or disable the sprites render time capture - */ - set captureSpritesRenderTime(value) { - if (value === this._captureSpritesRenderTime) { - return; - } - this._captureSpritesRenderTime = value; - if (!this.scene.spriteManagers) { - return; - } - if (value) { - this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(() => { - Tools.StartPerformanceCounter("Sprites"); - this._spritesRenderTime.beginMonitoring(); - }); - this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(() => { - Tools.EndPerformanceCounter("Sprites"); - this._spritesRenderTime.endMonitoring(false); - }); - } - else { - this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver); - this._onBeforeSpritesRenderingObserver = null; - this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver); - this._onAfterSpritesRenderingObserver = null; - } - } - /** - * Gets the perf counter used for physics time - */ - get physicsTimeCounter() { - return this._physicsTime; - } - /** - * Gets the physics time capture status - */ - get capturePhysicsTime() { - return this._capturePhysicsTime; - } - /** - * Enable or disable the physics time capture - */ - set capturePhysicsTime(value) { - if (value === this._capturePhysicsTime) { - return; - } - if (!this.scene.onBeforePhysicsObservable) { - return; - } - this._capturePhysicsTime = value; - if (value) { - this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(() => { - Tools.StartPerformanceCounter("Physics"); - this._physicsTime.beginMonitoring(); - }); - this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(() => { - Tools.EndPerformanceCounter("Physics"); - this._physicsTime.endMonitoring(); - }); - } - else { - this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver); - this._onBeforePhysicsObserver = null; - this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver); - this._onAfterPhysicsObserver = null; - } - } - /** - * Gets the perf counter used for animations time - */ - get animationsTimeCounter() { - return this._animationsTime; - } - /** - * Gets the animations time capture status - */ - get captureAnimationsTime() { - return this._captureAnimationsTime; - } - /** - * Enable or disable the animations time capture - */ - set captureAnimationsTime(value) { - if (value === this._captureAnimationsTime) { - return; - } - this._captureAnimationsTime = value; - if (value) { - this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(() => { - this._animationsTime.endMonitoring(); - }); - } - else { - this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver); - this._onAfterAnimationsObserver = null; - } - } - /** - * Gets the perf counter used for frame time capture - */ - get frameTimeCounter() { - return this._frameTime; - } - /** - * Gets the frame time capture status - */ - get captureFrameTime() { - return this._captureFrameTime; - } - /** - * Enable or disable the frame time capture - */ - set captureFrameTime(value) { - this._captureFrameTime = value; - } - /** - * Gets the perf counter used for inter-frames time capture - */ - get interFrameTimeCounter() { - return this._interFrameTime; - } - /** - * Gets the inter-frames time capture status - */ - get captureInterFrameTime() { - return this._captureInterFrameTime; - } - /** - * Enable or disable the inter-frames time capture - */ - set captureInterFrameTime(value) { - this._captureInterFrameTime = value; - } - /** - * Gets the perf counter used for render time capture - */ - get renderTimeCounter() { - return this._renderTime; - } - /** - * Gets the render time capture status - */ - get captureRenderTime() { - return this._captureRenderTime; - } - /** - * Enable or disable the render time capture - */ - set captureRenderTime(value) { - if (value === this._captureRenderTime) { - return; - } - this._captureRenderTime = value; - if (value) { - this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(() => { - this._renderTime.beginMonitoring(); - Tools.StartPerformanceCounter("Main render"); - }); - this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(() => { - this._renderTime.endMonitoring(false); - Tools.EndPerformanceCounter("Main render"); - }); - } - else { - this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver); - this._onBeforeDrawPhaseObserver = null; - this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver); - this._onAfterDrawPhaseObserver = null; - } - } - /** - * Gets the perf counter used for camera render time capture - */ - get cameraRenderTimeCounter() { - return this._cameraRenderTime; - } - /** - * Gets the camera render time capture status - */ - get captureCameraRenderTime() { - return this._captureCameraRenderTime; - } - /** - * Enable or disable the camera render time capture - */ - set captureCameraRenderTime(value) { - if (value === this._captureCameraRenderTime) { - return; - } - this._captureCameraRenderTime = value; - if (value) { - this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add((camera) => { - this._cameraRenderTime.beginMonitoring(); - Tools.StartPerformanceCounter(`Rendering camera ${camera.name}`); - }); - this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add((camera) => { - this._cameraRenderTime.endMonitoring(false); - Tools.EndPerformanceCounter(`Rendering camera ${camera.name}`); - }); - } - else { - this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); - this._onBeforeCameraRenderObserver = null; - this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver); - this._onAfterCameraRenderObserver = null; - } - } - /** - * Gets the perf counter used for draw calls - */ - get drawCallsCounter() { - return this.scene.getEngine()._drawCalls; - } - /** - * Instantiates a new scene instrumentation. - * This class can be used to get instrumentation data from a Babylon engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#sceneinstrumentation - * @param scene Defines the scene to instrument - */ - constructor( - /** - * Defines the scene to instrument - */ - scene) { - this.scene = scene; - this._captureActiveMeshesEvaluationTime = false; - this._activeMeshesEvaluationTime = new PerfCounter(); - this._captureRenderTargetsRenderTime = false; - this._renderTargetsRenderTime = new PerfCounter(); - this._captureFrameTime = false; - this._frameTime = new PerfCounter(); - this._captureRenderTime = false; - this._renderTime = new PerfCounter(); - this._captureInterFrameTime = false; - this._interFrameTime = new PerfCounter(); - this._captureParticlesRenderTime = false; - this._particlesRenderTime = new PerfCounter(); - this._captureSpritesRenderTime = false; - this._spritesRenderTime = new PerfCounter(); - this._capturePhysicsTime = false; - this._physicsTime = new PerfCounter(); - this._captureAnimationsTime = false; - this._animationsTime = new PerfCounter(); - this._captureCameraRenderTime = false; - this._cameraRenderTime = new PerfCounter(); - // Observers - this._onBeforeActiveMeshesEvaluationObserver = null; - this._onAfterActiveMeshesEvaluationObserver = null; - this._onBeforeRenderTargetsRenderObserver = null; - this._onAfterRenderTargetsRenderObserver = null; - this._onAfterRenderObserver = null; - this._onBeforeDrawPhaseObserver = null; - this._onAfterDrawPhaseObserver = null; - this._onBeforeAnimationsObserver = null; - this._onBeforeParticlesRenderingObserver = null; - this._onAfterParticlesRenderingObserver = null; - this._onBeforeSpritesRenderingObserver = null; - this._onAfterSpritesRenderingObserver = null; - this._onBeforePhysicsObserver = null; - this._onAfterPhysicsObserver = null; - this._onAfterAnimationsObserver = null; - this._onBeforeCameraRenderObserver = null; - this._onAfterCameraRenderObserver = null; - // Before render - this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => { - if (this._captureActiveMeshesEvaluationTime) { - this._activeMeshesEvaluationTime.fetchNewFrame(); - } - if (this._captureRenderTargetsRenderTime) { - this._renderTargetsRenderTime.fetchNewFrame(); - } - if (this._captureFrameTime) { - Tools.StartPerformanceCounter("Scene rendering"); - this._frameTime.beginMonitoring(); - } - if (this._captureInterFrameTime) { - this._interFrameTime.endMonitoring(); - } - if (this._captureParticlesRenderTime) { - this._particlesRenderTime.fetchNewFrame(); - } - if (this._captureSpritesRenderTime) { - this._spritesRenderTime.fetchNewFrame(); - } - if (this._captureAnimationsTime) { - this._animationsTime.beginMonitoring(); - } - if (this._captureRenderTime) { - this._renderTime.fetchNewFrame(); - } - if (this._captureCameraRenderTime) { - this._cameraRenderTime.fetchNewFrame(); - } - this.scene.getEngine()._drawCalls.fetchNewFrame(); - }); - // After render - this._onAfterRenderObserver = scene.onAfterRenderObservable.add(() => { - if (this._captureFrameTime) { - Tools.EndPerformanceCounter("Scene rendering"); - this._frameTime.endMonitoring(); - } - if (this._captureRenderTime) { - this._renderTime.endMonitoring(false); - } - if (this._captureInterFrameTime) { - this._interFrameTime.beginMonitoring(); - } - if (this._captureActiveMeshesEvaluationTime) { - this._activeMeshesEvaluationTime.endFrame(); - } - if (this._captureRenderTargetsRenderTime) { - this._renderTargetsRenderTime.endFrame(); - } - if (this._captureParticlesRenderTime) { - this._particlesRenderTime.endFrame(); - } - if (this._captureSpritesRenderTime) { - this._spritesRenderTime.endFrame(); - } - if (this._captureRenderTime) { - this._renderTime.endFrame(); - } - if (this._captureCameraRenderTime) { - this._cameraRenderTime.endFrame(); - } - }); - } - /** - * Dispose and release associated resources. - */ - dispose() { - this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver); - this._onAfterRenderObserver = null; - this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver); - this._onBeforeActiveMeshesEvaluationObserver = null; - this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver); - this._onAfterActiveMeshesEvaluationObserver = null; - this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver); - this._onBeforeRenderTargetsRenderObserver = null; - this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver); - this._onAfterRenderTargetsRenderObserver = null; - this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver); - this._onBeforeAnimationsObserver = null; - this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver); - this._onBeforeParticlesRenderingObserver = null; - this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver); - this._onAfterParticlesRenderingObserver = null; - if (this._onBeforeSpritesRenderingObserver) { - this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver); - this._onBeforeSpritesRenderingObserver = null; - } - if (this._onAfterSpritesRenderingObserver) { - this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver); - this._onAfterSpritesRenderingObserver = null; - } - this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver); - this._onBeforeDrawPhaseObserver = null; - this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver); - this._onAfterDrawPhaseObserver = null; - if (this._onBeforePhysicsObserver) { - this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver); - this._onBeforePhysicsObserver = null; - } - if (this._onAfterPhysicsObserver) { - this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver); - this._onAfterPhysicsObserver = null; - } - this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver); - this._onAfterAnimationsObserver = null; - this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); - this._onBeforeCameraRenderObserver = null; - this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver); - this._onAfterCameraRenderObserver = null; - this.scene = null; - } -} -//# sourceMappingURL=sceneInstrumentation.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Instrumentation/index.js - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/glowMapGeneration.fragment.js -// Do not edit. - - - - -const glowMapGeneration_fragment_name = "glowMapGenerationPixelShader"; -const glowMapGeneration_fragment_shader = `#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) -#include<helperFunctions> -#endif -#ifdef DIFFUSE -varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; -#endif -#ifdef OPACITY -varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; -#endif -#ifdef EMISSIVE -varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; -#endif -#ifdef VERTEXALPHA -varying vec4 vColor; -#endif -uniform vec4 glowColor;uniform float glowIntensity; -#include<clipPlaneFragmentDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include<clipPlaneFragment> -vec4 finalColor=glowColor; -#ifdef DIFFUSE -vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); -#ifdef DIFFUSE_ISLINEAR -albedoTexture=toGammaSpace(albedoTexture); -#endif -#ifdef GLOW -finalColor.a*=albedoTexture.a; -#endif -#ifdef HIGHLIGHT -finalColor.a=albedoTexture.a; -#endif -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); -#ifdef OPACITYRGB -finalColor.a*=getLuminance(opacityMap.rgb); -#else -finalColor.a*=opacityMap.a; -#endif -finalColor.a*=opacityIntensity; -#endif -#ifdef VERTEXALPHA -finalColor.a*=vColor.a; -#endif -#ifdef ALPHATEST -if (finalColor.a<ALPHATESTVALUE) -discard; -#endif -#ifdef EMISSIVE -vec4 emissive=texture2D(emissiveSampler,vUVEmissive); -#ifdef EMISSIVE_ISLINEAR -emissive=toGammaSpace(emissive); -#endif -gl_FragColor=emissive*finalColor*glowIntensity; -#else -gl_FragColor=finalColor*glowIntensity; -#endif -#ifdef HIGHLIGHT -gl_FragColor.a=glowColor.a; -#endif -}`; -// Sideeffect -ShaderStore.ShadersStore[glowMapGeneration_fragment_name] = glowMapGeneration_fragment_shader; -/** @internal */ -const glowMapGenerationPixelShader = { name: glowMapGeneration_fragment_name, shader: glowMapGeneration_fragment_shader }; -//# sourceMappingURL=glowMapGeneration.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/glowMapGeneration.vertex.js -// Do not edit. - - - - - - - - - - - - - -const glowMapGeneration_vertex_name = "glowMapGenerationVertexShader"; -const glowMapGeneration_vertex_shader = `attribute vec3 position; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<clipPlaneVertexDeclaration> -#include<instancesDeclaration> -uniform mat4 viewProjection;varying vec4 vPosition; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef DIFFUSE -varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; -#endif -#ifdef OPACITY -varying vec2 vUVOpacity;uniform mat4 opacityMatrix; -#endif -#ifdef EMISSIVE -varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; -#endif -#ifdef VERTEXALPHA -attribute vec4 color;varying vec4 vColor; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef CUBEMAP -vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); -#else -vPosition=viewProjection*worldPos;gl_Position=vPosition; -#endif -#ifdef DIFFUSE -#ifdef DIFFUSEUV1 -vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef DIFFUSEUV2 -vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef OPACITY -#ifdef OPACITYUV1 -vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef OPACITYUV2 -vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef EMISSIVE -#ifdef EMISSIVEUV1 -vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef EMISSIVEUV2 -vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef VERTEXALPHA -vColor=color; -#endif -#include<clipPlaneVertex> -}`; -// Sideeffect -ShaderStore.ShadersStore[glowMapGeneration_vertex_name] = glowMapGeneration_vertex_shader; -/** @internal */ -const glowMapGenerationVertexShader = { name: glowMapGeneration_vertex_name, shader: glowMapGeneration_vertex_shader }; -//# sourceMappingURL=glowMapGeneration.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Layers/effectLayer.js - - - - - - - - - - - - - - - - - - - -/** - * The effect layer Helps adding post process effect blended with the main pass. - * - * This can be for instance use to generate glow or highlight effects on the scene. - * - * The effect layer class can not be used directly and is intented to inherited from to be - * customized per effects. - */ -class EffectLayer { - /** - * Gets the camera attached to the layer. - */ - get camera() { - return this._effectLayerOptions.camera; - } - /** - * Gets the rendering group id the layer should render in. - */ - get renderingGroupId() { - return this._effectLayerOptions.renderingGroupId; - } - set renderingGroupId(renderingGroupId) { - this._effectLayerOptions.renderingGroupId = renderingGroupId; - } - /** - * Gets the main texture where the effect is rendered - */ - get mainTexture() { - return this._mainTexture; - } - /** - * Sets a specific material to be used to render a mesh/a list of meshes in the layer - * @param mesh mesh or array of meshes - * @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. - */ - setMaterialForRendering(mesh, material) { - this._mainTexture.setMaterialForRendering(mesh, material); - if (Array.isArray(mesh)) { - for (let i = 0; i < mesh.length; ++i) { - const currentMesh = mesh[i]; - if (!material) { - delete this._materialForRendering[currentMesh.uniqueId]; - } - else { - this._materialForRendering[currentMesh.uniqueId] = [currentMesh, material]; - } - } - } - else { - if (!material) { - delete this._materialForRendering[mesh.uniqueId]; - } - else { - this._materialForRendering[mesh.uniqueId] = [mesh, material]; - } - } - } - /** - * Gets the intensity of the effect for a specific mesh. - * @param mesh The mesh to get the effect intensity for - * @returns The intensity of the effect for the mesh - */ - getEffectIntensity(mesh) { - var _a; - return (_a = this._effectIntensity[mesh.uniqueId]) !== null && _a !== void 0 ? _a : 1; - } - /** - * Sets the intensity of the effect for a specific mesh. - * @param mesh The mesh to set the effect intensity for - * @param intensity The intensity of the effect for the mesh - */ - setEffectIntensity(mesh, intensity) { - this._effectIntensity[mesh.uniqueId] = intensity; - } - /** - * Instantiates a new effect Layer and references it in the scene. - * @param name The name of the layer - * @param scene The scene to use the layer in - */ - constructor( - /** The Friendly of the effect in the scene */ - name, scene) { - this._vertexBuffers = {}; - this._maxSize = 0; - this._mainTextureDesiredSize = { width: 0, height: 0 }; - this._shouldRender = true; - this._postProcesses = []; - this._textures = []; - this._emissiveTextureAndColor = { texture: null, color: new math_color_Color4() }; - this._effectIntensity = {}; - /** - * The clear color of the texture used to generate the glow map. - */ - this.neutralColor = new math_color_Color4(); - /** - * Specifies whether the highlight layer is enabled or not. - */ - this.isEnabled = true; - /** - * Specifies if the bounding boxes should be rendered normally or if they should undergo the effect of the layer - */ - this.disableBoundingBoxesFromEffectLayer = false; - /** - * An event triggered when the effect layer has been disposed. - */ - this.onDisposeObservable = new observable_Observable(); - /** - * An event triggered when the effect layer is about rendering the main texture with the glowy parts. - */ - this.onBeforeRenderMainTextureObservable = new observable_Observable(); - /** - * An event triggered when the generated texture is being merged in the scene. - */ - this.onBeforeComposeObservable = new observable_Observable(); - /** - * An event triggered when the mesh is rendered into the effect render target. - */ - this.onBeforeRenderMeshToEffect = new observable_Observable(); - /** - * An event triggered after the mesh has been rendered into the effect render target. - */ - this.onAfterRenderMeshToEffect = new observable_Observable(); - /** - * An event triggered when the generated texture has been merged in the scene. - */ - this.onAfterComposeObservable = new observable_Observable(); - /** - * An event triggered when the effect layer changes its size. - */ - this.onSizeChangedObservable = new observable_Observable(); - this._materialForRendering = {}; - this.name = name; - this._scene = scene || engineStore_EngineStore.LastCreatedScene; - EffectLayer._SceneComponentInitialization(this._scene); - this._engine = this._scene.getEngine(); - this._maxSize = this._engine.getCaps().maxTextureSize; - this._scene.effectLayers.push(this); - this._mergeDrawWrapper = []; - // Generate Buffers - this._generateIndexBuffer(); - this._generateVertexBuffer(); - } - /** - * 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 - * @returns Number of times a mesh must be rendered in the layer - */ - _numInternalDraws() { - return 1; - } - /** - * Initializes the effect layer with the required options. - * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information) - */ - _init(options) { - // Adapt options - this._effectLayerOptions = Object.assign({ mainTextureRatio: 0.5, alphaBlendingMode: 2, camera: null, renderingGroupId: -1, mainTextureType: 0, generateStencilBuffer: false }, options); - this._setMainTextureSize(); - this._createMainTexture(); - this._createTextureAndPostProcesses(); - } - /** - * Generates the index buffer of the full screen quad blending to the main canvas. - */ - _generateIndexBuffer() { - // Indices - const indices = []; - indices.push(0); - indices.push(1); - indices.push(2); - indices.push(0); - indices.push(2); - indices.push(3); - this._indexBuffer = this._engine.createIndexBuffer(indices); - } - /** - * Generates the vertex buffer of the full screen quad blending to the main canvas. - */ - _generateVertexBuffer() { - // VBO - const vertices = []; - vertices.push(1, 1); - vertices.push(-1, 1); - vertices.push(-1, -1); - vertices.push(1, -1); - const vertexBuffer = new buffer_VertexBuffer(this._engine, vertices, buffer_VertexBuffer.PositionKind, false, false, 2); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = vertexBuffer; - } - /** - * Sets the main texture desired size which is the closest power of two - * of the engine canvas size. - */ - _setMainTextureSize() { - if (this._effectLayerOptions.mainTextureFixedSize) { - this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize; - this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize; - } - else { - this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio; - this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio; - this._mainTextureDesiredSize.width = this._engine.needPOTTextures - ? engine_Engine.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) - : this._mainTextureDesiredSize.width; - this._mainTextureDesiredSize.height = this._engine.needPOTTextures - ? engine_Engine.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) - : this._mainTextureDesiredSize.height; - } - this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width); - this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height); - } - /** - * Creates the main texture for the effect layer. - */ - _createMainTexture() { - this._mainTexture = new renderTargetTexture_RenderTargetTexture("EffectLayerMainRTT", { - width: this._mainTextureDesiredSize.width, - height: this._mainTextureDesiredSize.height, - }, this._scene, false, true, this._effectLayerOptions.mainTextureType, false, texture_Texture.TRILINEAR_SAMPLINGMODE, true, this._effectLayerOptions.generateStencilBuffer); - this._mainTexture.activeCamera = this._effectLayerOptions.camera; - this._mainTexture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._mainTexture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._mainTexture.anisotropicFilteringLevel = 1; - this._mainTexture.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE); - this._mainTexture.renderParticles = false; - this._mainTexture.renderList = null; - this._mainTexture.ignoreCameraViewport = true; - for (const id in this._materialForRendering) { - const [mesh, material] = this._materialForRendering[id]; - this._mainTexture.setMaterialForRendering(mesh, material); - } - this._mainTexture.customIsReadyFunction = (mesh, refreshRate, preWarm) => { - if ((preWarm || refreshRate === 0) && mesh.subMeshes) { - for (let i = 0; i < mesh.subMeshes.length; ++i) { - const subMesh = mesh.subMeshes[i]; - const material = subMesh.getMaterial(); - const renderingMesh = subMesh.getRenderingMesh(); - if (!material) { - continue; - } - const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); - const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances; - this._setEmissiveTextureAndColor(renderingMesh, subMesh, material); - if (!this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) { - return false; - } - } - } - return true; - }; - // Custom render function - this._mainTexture.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { - this.onBeforeRenderMainTextureObservable.notifyObservers(this); - let index; - const engine = this._scene.getEngine(); - if (depthOnlySubMeshes.length) { - engine.setColorWrite(false); - for (index = 0; index < depthOnlySubMeshes.length; index++) { - this._renderSubMesh(depthOnlySubMeshes.data[index]); - } - engine.setColorWrite(true); - } - for (index = 0; index < opaqueSubMeshes.length; index++) { - this._renderSubMesh(opaqueSubMeshes.data[index]); - } - for (index = 0; index < alphaTestSubMeshes.length; index++) { - this._renderSubMesh(alphaTestSubMeshes.data[index]); - } - const previousAlphaMode = engine.getAlphaMode(); - for (index = 0; index < transparentSubMeshes.length; index++) { - this._renderSubMesh(transparentSubMeshes.data[index], true); - } - engine.setAlphaMode(previousAlphaMode); - }; - this._mainTexture.onClearObservable.add((engine) => { - engine.clear(this.neutralColor, true, true, true); - }); - // Prevent package size in es6 (getBoundingBoxRenderer might not be present) - if (this._scene.getBoundingBoxRenderer) { - const boundingBoxRendererEnabled = this._scene.getBoundingBoxRenderer().enabled; - this._mainTexture.onBeforeBindObservable.add(() => { - this._scene.getBoundingBoxRenderer().enabled = !this.disableBoundingBoxesFromEffectLayer && boundingBoxRendererEnabled; - }); - this._mainTexture.onAfterUnbindObservable.add(() => { - this._scene.getBoundingBoxRenderer().enabled = boundingBoxRendererEnabled; - }); - } - } - /** - * Adds specific effects defines. - * @param defines The defines to add specifics to. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _addCustomEffectDefines(defines) { - // Nothing to add by default. - } - /** - * Checks for the readiness of the element composing the layer. - * @param subMesh the mesh to check for - * @param useInstances specify whether or not to use instances to render the mesh - * @param emissiveTexture the associated emissive texture used to generate the glow - * @returns true if ready otherwise, false - */ - _isReady(subMesh, useInstances, emissiveTexture) { - var _a; - const engine = this._scene.getEngine(); - const mesh = subMesh.getMesh(); - const renderingMaterial = (_a = mesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[engine.currentRenderPassId]; - if (renderingMaterial) { - return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances); - } - const material = subMesh.getMaterial(); - if (!material) { - return false; - } - if (this._useMeshMaterial(subMesh.getRenderingMesh())) { - return material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances); - } - const defines = []; - const attribs = [buffer_VertexBuffer.PositionKind]; - let uv1 = false; - let uv2 = false; - // Diffuse - if (material) { - const needAlphaTest = material.needAlphaTesting(); - const diffuseTexture = material.getAlphaTestTexture(); - const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture); - if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) { - defines.push("#define DIFFUSE"); - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind) && diffuseTexture.coordinatesIndex === 1) { - defines.push("#define DIFFUSEUV2"); - uv2 = true; - } - else if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - defines.push("#define DIFFUSEUV1"); - uv1 = true; - } - if (needAlphaTest) { - defines.push("#define ALPHATEST"); - defines.push("#define ALPHATESTVALUE 0.4"); - } - if (!diffuseTexture.gammaSpace) { - defines.push("#define DIFFUSE_ISLINEAR"); - } - } - const opacityTexture = material.opacityTexture; - if (opacityTexture) { - defines.push("#define OPACITY"); - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind) && opacityTexture.coordinatesIndex === 1) { - defines.push("#define OPACITYUV2"); - uv2 = true; - } - else if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - defines.push("#define OPACITYUV1"); - uv1 = true; - } - } - } - // Emissive - if (emissiveTexture) { - defines.push("#define EMISSIVE"); - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind) && emissiveTexture.coordinatesIndex === 1) { - defines.push("#define EMISSIVEUV2"); - uv2 = true; - } - else if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - defines.push("#define EMISSIVEUV1"); - uv1 = true; - } - if (!emissiveTexture.gammaSpace) { - defines.push("#define EMISSIVE_ISLINEAR"); - } - } - // Vertex - if (mesh.useVertexColors && mesh.isVerticesDataPresent(buffer_VertexBuffer.ColorKind) && mesh.hasVertexAlpha && material.transparencyMode !== material_Material.MATERIAL_OPAQUE) { - attribs.push(buffer_VertexBuffer.ColorKind); - defines.push("#define VERTEXALPHA"); - } - if (uv1) { - attribs.push(buffer_VertexBuffer.UVKind); - defines.push("#define UV1"); - } - if (uv2) { - attribs.push(buffer_VertexBuffer.UV2Kind); - defines.push("#define UV2"); - } - // Bones - const fallbacks = new EffectFallbacks(); - if (mesh.useBones && mesh.computeBonesUsingShaders) { - attribs.push(buffer_VertexBuffer.MatricesIndicesKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsKind); - if (mesh.numBoneInfluencers > 4) { - attribs.push(buffer_VertexBuffer.MatricesIndicesExtraKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsExtraKind); - } - defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); - const skeleton = mesh.skeleton; - if (skeleton && skeleton.isUsingTextureForMatrices) { - defines.push("#define BONETEXTURE"); - } - else { - defines.push("#define BonesPerMesh " + (skeleton ? skeleton.bones.length + 1 : 0)); - } - if (mesh.numBoneInfluencers > 0) { - fallbacks.addCPUSkinningFallback(0, mesh); - } - } - else { - defines.push("#define NUM_BONE_INFLUENCERS 0"); - } - // Morph targets - const manager = mesh.morphTargetManager; - let morphInfluencers = 0; - if (manager) { - if (manager.numInfluencers > 0) { - defines.push("#define MORPHTARGETS"); - morphInfluencers = manager.numInfluencers; - defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers); - if (manager.isUsingTextureForTargets) { - defines.push("#define MORPHTARGETS_TEXTURE"); - } - MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers); - } - } - // Instances - if (useInstances) { - defines.push("#define INSTANCES"); - MaterialHelper.PushAttributesForInstances(attribs); - if (subMesh.getRenderingMesh().hasThinInstances) { - defines.push("#define THIN_INSTANCES"); - } - } - // ClipPlanes - prepareStringDefinesForClipPlanes(material, this._scene, defines); - this._addCustomEffectDefines(defines); - // Get correct effect - const drawWrapper = subMesh._getDrawWrapper(undefined, true); - const cachedDefines = drawWrapper.defines; - const join = defines.join("\n"); - if (cachedDefines !== join) { - const uniforms = [ - "world", - "mBones", - "viewProjection", - "glowColor", - "morphTargetInfluences", - "boneTextureWidth", - "diffuseMatrix", - "emissiveMatrix", - "opacityMatrix", - "opacityIntensity", - "morphTargetTextureInfo", - "morphTargetTextureIndices", - "glowIntensity", - ]; - addClipPlaneUniforms(uniforms); - drawWrapper.setEffect(this._engine.createEffect("glowMapGeneration", attribs, uniforms, ["diffuseSampler", "emissiveSampler", "opacitySampler", "boneSampler", "morphTargets"], join, fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers }), join); - } - return drawWrapper.effect.isReady(); - } - /** - * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene. - */ - render() { - for (let i = 0; i < this._postProcesses.length; i++) { - if (!this._postProcesses[i].isReady()) { - return; - } - } - const engine = this._scene.getEngine(); - const numDraws = this._numInternalDraws(); - // Check - let isReady = true; - for (let i = 0; i < numDraws; ++i) { - let currentEffect = this._mergeDrawWrapper[i]; - if (!currentEffect) { - currentEffect = this._mergeDrawWrapper[i] = new drawWrapper_DrawWrapper(this._engine); - currentEffect.setEffect(this._createMergeEffect()); - } - isReady = isReady && currentEffect.effect.isReady(); - } - if (!isReady) { - return; - } - this.onBeforeComposeObservable.notifyObservers(this); - const previousAlphaMode = engine.getAlphaMode(); - for (let i = 0; i < numDraws; ++i) { - const currentEffect = this._mergeDrawWrapper[i]; - // Render - engine.enableEffect(currentEffect); - engine.setState(false); - // VBOs - engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect.effect); - // Go Blend. - engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode); - // Blends the map on the main canvas. - this._internalRender(currentEffect.effect, i); - } - // Restore Alpha - engine.setAlphaMode(previousAlphaMode); - this.onAfterComposeObservable.notifyObservers(this); - // Handle size changes. - const size = this._mainTexture.getSize(); - this._setMainTextureSize(); - if ((size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) && - this._mainTextureDesiredSize.width !== 0 && - this._mainTextureDesiredSize.height !== 0) { - // Recreate RTT and post processes on size change. - this.onSizeChangedObservable.notifyObservers(this); - this._disposeTextureAndPostProcesses(); - this._createMainTexture(); - this._createTextureAndPostProcesses(); - } - } - /** - * Determine if a given mesh will be used in the current effect. - * @param mesh mesh to test - * @returns true if the mesh will be used - */ - hasMesh(mesh) { - if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) { - return true; - } - return false; - } - /** - * Returns true if the layer contains information to display, otherwise false. - * @returns true if the glow layer should be rendered - */ - shouldRender() { - return this.isEnabled && this._shouldRender; - } - /** - * Returns true if the mesh should render, otherwise false. - * @param mesh The mesh to render - * @returns true if it should render otherwise false - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _shouldRenderMesh(mesh) { - return true; - } - /** - * Returns true if the mesh can be rendered, otherwise false. - * @param mesh The mesh to render - * @param material The material used on the mesh - * @returns true if it can be rendered otherwise false - */ - _canRenderMesh(mesh, material) { - return !material.needAlphaBlendingForMesh(mesh); - } - /** - * Returns true if the mesh should render, otherwise false. - * @returns true if it should render otherwise false - */ - _shouldRenderEmissiveTextureForMesh() { - return true; - } - /** - * Renders the submesh passed in parameter to the generation map. - * @param subMesh - * @param enableAlphaMode - */ - _renderSubMesh(subMesh, enableAlphaMode = false) { - var _a, _b; - if (!this.shouldRender()) { - return; - } - const material = subMesh.getMaterial(); - const ownerMesh = subMesh.getMesh(); - const replacementMesh = subMesh.getReplacementMesh(); - const renderingMesh = subMesh.getRenderingMesh(); - const effectiveMesh = subMesh.getEffectiveMesh(); - const scene = this._scene; - const engine = scene.getEngine(); - effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; - if (!material) { - return; - } - // Do not block in blend mode. - if (!this._canRenderMesh(renderingMesh, material)) { - return; - } - // Culling - let sideOrientation = (_a = renderingMesh.overrideMaterialSideOrientation) !== null && _a !== void 0 ? _a : material.sideOrientation; - const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant(); - if (mainDeterminant < 0) { - sideOrientation = sideOrientation === material_Material.ClockWiseSideOrientation ? material_Material.CounterClockWiseSideOrientation : material_Material.ClockWiseSideOrientation; - } - const reverse = sideOrientation === material_Material.ClockWiseSideOrientation; - engine.setState(material.backFaceCulling, material.zOffset, undefined, reverse, material.cullBackFaces, undefined, material.zOffsetUnits); - // Managing instances - const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!replacementMesh); - if (batch.mustReturn) { - return; - } - // Early Exit per mesh - if (!this._shouldRenderMesh(renderingMesh)) { - return; - } - const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances; - this._setEmissiveTextureAndColor(renderingMesh, subMesh, material); - this.onBeforeRenderMeshToEffect.notifyObservers(ownerMesh); - if (this._useMeshMaterial(renderingMesh)) { - renderingMesh.render(subMesh, enableAlphaMode, replacementMesh || undefined); - } - else if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) { - const renderingMaterial = (_b = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _b === void 0 ? void 0 : _b[engine.currentRenderPassId]; - let drawWrapper = subMesh._getDrawWrapper(); - if (!drawWrapper && renderingMaterial) { - drawWrapper = renderingMaterial._getDrawWrapper(); - } - if (!drawWrapper) { - return; - } - const effect = drawWrapper.effect; - engine.enableEffect(drawWrapper); - if (!hardwareInstancedRendering) { - renderingMesh._bind(subMesh, effect, material.fillMode); - } - if (!renderingMaterial) { - effect.setMatrix("viewProjection", scene.getTransformMatrix()); - effect.setMatrix("world", effectiveMesh.getWorldMatrix()); - effect.setFloat4("glowColor", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a); - } - else { - renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh); - } - if (!renderingMaterial) { - const needAlphaTest = material.needAlphaTesting(); - const diffuseTexture = material.getAlphaTestTexture(); - const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture); - if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) { - effect.setTexture("diffuseSampler", diffuseTexture); - const textureMatrix = diffuseTexture.getTextureMatrix(); - if (textureMatrix) { - effect.setMatrix("diffuseMatrix", textureMatrix); - } - } - const opacityTexture = material.opacityTexture; - if (opacityTexture) { - effect.setTexture("opacitySampler", opacityTexture); - effect.setFloat("opacityIntensity", opacityTexture.level); - const textureMatrix = opacityTexture.getTextureMatrix(); - if (textureMatrix) { - effect.setMatrix("opacityMatrix", textureMatrix); - } - } - // Glow emissive only - if (this._emissiveTextureAndColor.texture) { - effect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture); - effect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix()); - } - // Bones - if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { - const skeleton = renderingMesh.skeleton; - if (skeleton.isUsingTextureForMatrices) { - const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh); - if (!boneTexture) { - return; - } - effect.setTexture("boneSampler", boneTexture); - effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); - } - else { - effect.setMatrices("mBones", skeleton.getTransformMatrices(renderingMesh)); - } - } - // Morph targets - MaterialHelper.BindMorphTargetParameters(renderingMesh, effect); - if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { - renderingMesh.morphTargetManager._bind(effect); - } - // Alpha mode - if (enableAlphaMode) { - engine.setAlphaMode(material.alphaMode); - } - // Intensity of effect - effect.setFloat("glowIntensity", this.getEffectIntensity(renderingMesh)); - // Clip planes - bindClipPlane(effect, material, scene); - } - // Draw - renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix("world", world)); - } - else { - // Need to reset refresh rate of the main map - this._mainTexture.resetRefreshCounter(); - } - this.onAfterRenderMeshToEffect.notifyObservers(ownerMesh); - } - /** - * Defines whether the current material of the mesh should be use to render the effect. - * @param mesh defines the current mesh to render - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _useMeshMaterial(mesh) { - return false; - } - /** - * Rebuild the required buffers. - * @internal Internal use only. - */ - _rebuild() { - const vb = this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - if (vb) { - vb._rebuild(); - } - this._generateIndexBuffer(); - } - /** - * Dispose only the render target textures and post process. - */ - _disposeTextureAndPostProcesses() { - this._mainTexture.dispose(); - for (let i = 0; i < this._postProcesses.length; i++) { - if (this._postProcesses[i]) { - this._postProcesses[i].dispose(); - } - } - this._postProcesses = []; - for (let i = 0; i < this._textures.length; i++) { - if (this._textures[i]) { - this._textures[i].dispose(); - } - } - this._textures = []; - } - /** - * Dispose the highlight layer and free resources. - */ - dispose() { - const vertexBuffer = this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - if (vertexBuffer) { - vertexBuffer.dispose(); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = null; - } - if (this._indexBuffer) { - this._scene.getEngine()._releaseBuffer(this._indexBuffer); - this._indexBuffer = null; - } - for (const drawWrapper of this._mergeDrawWrapper) { - drawWrapper.dispose(); - } - this._mergeDrawWrapper = []; - // Clean textures and post processes - this._disposeTextureAndPostProcesses(); - // Remove from scene - const index = this._scene.effectLayers.indexOf(this, 0); - if (index > -1) { - this._scene.effectLayers.splice(index, 1); - } - // Callback - 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(); - } - /** - * Gets the class name of the effect layer - * @returns the string with the class name of the effect layer - */ - getClassName() { - return "EffectLayer"; - } - /** - * Creates an effect layer from parsed effect layer data - * @param parsedEffectLayer defines effect layer data - * @param scene defines the current scene - * @param rootUrl defines the root URL containing the effect layer information - * @returns a parsed effect Layer - */ - static Parse(parsedEffectLayer, scene, rootUrl) { - const effectLayerType = tools_Tools.Instantiate(parsedEffectLayer.customType); - return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl); - } -} -/** - * @internal - */ -EffectLayer._SceneComponentInitialization = (_) => { - throw _WarnImport("EffectLayerSceneComponent"); -}; -__decorate([ - serialize() -], EffectLayer.prototype, "name", void 0); -__decorate([ - serializeAsColor4() -], EffectLayer.prototype, "neutralColor", void 0); -__decorate([ - serialize() -], EffectLayer.prototype, "isEnabled", void 0); -__decorate([ - serializeAsCameraReference() -], EffectLayer.prototype, "camera", null); -__decorate([ - serialize() -], EffectLayer.prototype, "renderingGroupId", null); -__decorate([ - serialize() -], EffectLayer.prototype, "disableBoundingBoxesFromEffectLayer", void 0); -//# sourceMappingURL=effectLayer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Layers/effectLayerSceneComponent.js - - - - - -// Adds the parser to the scene parsers. -AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_EFFECTLAYER, (parsedData, scene, container, rootUrl) => { - if (parsedData.effectLayers) { - if (!container.effectLayers) { - container.effectLayers = new Array(); - } - for (let index = 0; index < parsedData.effectLayers.length; index++) { - const effectLayer = EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl); - container.effectLayers.push(effectLayer); - } - } -}); -AbstractScene.prototype.removeEffectLayer = function (toRemove) { - const index = this.effectLayers.indexOf(toRemove); - if (index !== -1) { - this.effectLayers.splice(index, 1); - } - return index; -}; -AbstractScene.prototype.addEffectLayer = function (newEffectLayer) { - this.effectLayers.push(newEffectLayer); -}; -/** - * Defines the layer scene component responsible to manage any effect layers - * in a given scene. - */ -class EffectLayerSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_EFFECTLAYER; - this._renderEffects = false; - this._needStencil = false; - this._previousStencilState = false; - this.scene = scene || engineStore_EngineStore.LastCreatedScene; - if (!this.scene) { - return; - } - this._engine = this.scene.getEngine(); - this.scene.effectLayers = new Array(); - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._isReadyForMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh); - this.scene._cameraDrawRenderTargetStage.registerStep(sceneComponent_SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture); - this.scene._beforeCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil); - this.scene._afterRenderingGroupDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup); - this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack); - this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - const layers = this.scene.effectLayers; - for (const effectLayer of layers) { - effectLayer._rebuild(); - } - } - /** - * Serializes the component data to the specified json object - * @param serializationObject The object to serialize to - */ - serialize(serializationObject) { - // Effect layers - serializationObject.effectLayers = []; - const layers = this.scene.effectLayers; - for (const effectLayer of layers) { - if (effectLayer.serialize) { - serializationObject.effectLayers.push(effectLayer.serialize()); - } - } - } - /** - * Adds all the elements from the container to the scene - * @param container the container holding the elements - */ - addFromContainer(container) { - if (!container.effectLayers) { - return; - } - container.effectLayers.forEach((o) => { - this.scene.addEffectLayer(o); - }); - } - /** - * Removes all the elements in the container from the scene - * @param container contains the elements to remove - * @param dispose if the removed element should be disposed (default: false) - */ - removeFromContainer(container, dispose) { - if (!container.effectLayers) { - return; - } - container.effectLayers.forEach((o) => { - this.scene.removeEffectLayer(o); - if (dispose) { - o.dispose(); - } - }); - } - /** - * Disposes the component and the associated resources. - */ - dispose() { - const layers = this.scene.effectLayers; - while (layers.length) { - layers[0].dispose(); - } - } - _isReadyForMesh(mesh, hardwareInstancedRendering) { - const currentRenderPassId = this._engine.currentRenderPassId; - const layers = this.scene.effectLayers; - for (const layer of layers) { - if (!layer.hasMesh(mesh)) { - continue; - } - const renderTarget = layer._mainTexture; - this._engine.currentRenderPassId = renderTarget.renderPassId; - for (const subMesh of mesh.subMeshes) { - if (!layer.isReady(subMesh, hardwareInstancedRendering)) { - this._engine.currentRenderPassId = currentRenderPassId; - return false; - } - } - } - this._engine.currentRenderPassId = currentRenderPassId; - return true; - } - _renderMainTexture(camera) { - this._renderEffects = false; - this._needStencil = false; - let needRebind = false; - const layers = this.scene.effectLayers; - if (layers && layers.length > 0) { - this._previousStencilState = this._engine.getStencilBuffer(); - for (const effectLayer of layers) { - if (effectLayer.shouldRender() && - (!effectLayer.camera || - (effectLayer.camera.cameraRigMode === camera_Camera.RIG_MODE_NONE && camera === effectLayer.camera) || - (effectLayer.camera.cameraRigMode !== camera_Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) { - this._renderEffects = true; - this._needStencil = this._needStencil || effectLayer.needStencil(); - const renderTarget = effectLayer._mainTexture; - if (renderTarget._shouldRender()) { - this.scene.incrementRenderId(); - renderTarget.render(false, false); - needRebind = true; - } - } - } - this.scene.incrementRenderId(); - } - return needRebind; - } - _setStencil() { - // Activate effect Layer stencil - if (this._needStencil) { - this._engine.setStencilBuffer(true); - } - } - _setStencilBack() { - // Restore effect Layer stencil - if (this._needStencil) { - this._engine.setStencilBuffer(this._previousStencilState); - } - } - _draw(renderingGroupId) { - if (this._renderEffects) { - this._engine.setDepthBuffer(false); - const layers = this.scene.effectLayers; - for (let i = 0; i < layers.length; i++) { - const effectLayer = layers[i]; - if (effectLayer.renderingGroupId === renderingGroupId) { - if (effectLayer.shouldRender()) { - effectLayer.render(); - } - } - } - this._engine.setDepthBuffer(true); - } - } - _drawCamera() { - if (this._renderEffects) { - this._draw(-1); - } - } - _drawRenderingGroup(index) { - if (!this.scene._isInIntermediateRendering() && this._renderEffects) { - this._draw(index); - } - } -} -EffectLayer._SceneComponentInitialization = (scene) => { - let component = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_EFFECTLAYER); - if (!component) { - component = new EffectLayerSceneComponent(scene); - scene._addComponent(component); - } -}; -//# sourceMappingURL=effectLayerSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/glowMapMerge.fragment.js -// Do not edit. - -const glowMapMerge_fragment_name = "glowMapMergePixelShader"; -const glowMapMerge_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler; -#ifdef EMISSIVE -uniform sampler2D textureSampler2; -#endif -uniform float offset; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV); -#ifdef EMISSIVE -baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; -#else -baseColor.a=abs(offset-baseColor.a); -#ifdef STROKE -float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; -#endif -#endif -#if LDR -baseColor=clamp(baseColor,0.,1.0); -#endif -gl_FragColor=baseColor; -#define CUSTOM_FRAGMENT_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[glowMapMerge_fragment_name] = glowMapMerge_fragment_shader; -/** @internal */ -const glowMapMergePixelShader = { name: glowMapMerge_fragment_name, shader: glowMapMerge_fragment_shader }; -//# sourceMappingURL=glowMapMerge.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/glowMapMerge.vertex.js -// Do not edit. - -const glowMapMerge_vertex_name = "glowMapMergeVertexShader"; -const glowMapMerge_vertex_shader = `attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[glowMapMerge_vertex_name] = glowMapMerge_vertex_shader; -/** @internal */ -const glowMapMergeVertexShader = { name: glowMapMerge_vertex_name, shader: glowMapMerge_vertex_shader }; -//# sourceMappingURL=glowMapMerge.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Layers/glowLayer.js - -/* eslint-disable @typescript-eslint/no-unused-vars */ - - - - - - - - - - - - - - - - -AbstractScene.prototype.getGlowLayerByName = function (name) { - var _a; - for (let index = 0; index < ((_a = this.effectLayers) === null || _a === void 0 ? void 0 : _a.length); index++) { - if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) { - return this.effectLayers[index]; - } - } - return null; -}; -/** - * The glow layer Helps adding a glow effect around the emissive parts of a mesh. - * - * Once instantiated in a scene, by default, all the emissive meshes will glow. - * - * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/mesh/glowLayer - */ -class GlowLayer extends EffectLayer { - /** - * Sets the kernel size of the blur. - */ - set blurKernelSize(value) { - if (value === this._options.blurKernelSize) { - return; - } - this._options.blurKernelSize = value; - const effectiveKernel = this._getEffectiveBlurKernelSize(); - this._horizontalBlurPostprocess1.kernel = effectiveKernel; - this._verticalBlurPostprocess1.kernel = effectiveKernel; - this._horizontalBlurPostprocess2.kernel = effectiveKernel; - this._verticalBlurPostprocess2.kernel = effectiveKernel; - } - /** - * Gets the kernel size of the blur. - */ - get blurKernelSize() { - return this._options.blurKernelSize; - } - /** - * Sets the glow intensity. - */ - set intensity(value) { - this._intensity = value; - } - /** - * Gets the glow intensity. - */ - get intensity() { - return this._intensity; - } - /** - * Instantiates a new glow Layer and references it to the scene. - * @param name The name of the layer - * @param scene The scene to use the layer in - * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information) - */ - constructor(name, scene, options) { - super(name, scene); - this._intensity = 1.0; - this._includedOnlyMeshes = []; - this._excludedMeshes = []; - this._meshesUsingTheirOwnMaterials = []; - this.neutralColor = new math_color_Color4(0, 0, 0, 1); - // Adapt options - this._options = Object.assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1, ldrMerge: false, alphaBlendingMode: 1, mainTextureType: 0, generateStencilBuffer: false }, options); - // Initialize the layer - this._init({ - alphaBlendingMode: this._options.alphaBlendingMode, - camera: this._options.camera, - mainTextureFixedSize: this._options.mainTextureFixedSize, - mainTextureRatio: this._options.mainTextureRatio, - renderingGroupId: this._options.renderingGroupId, - mainTextureType: this._options.mainTextureType, - generateStencilBuffer: this._options.generateStencilBuffer, - }); - } - /** - * Get the effect name of the layer. - * @returns The effect name - */ - getEffectName() { - return GlowLayer.EffectName; - } - /** - * Create the merge effect. This is the shader use to blit the information back - * to the main canvas at the end of the scene rendering. - */ - _createMergeEffect() { - let defines = "#define EMISSIVE \n"; - if (this._options.ldrMerge) { - defines += "#define LDR \n"; - } - // Effect - return this._engine.createEffect("glowMapMerge", [buffer_VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], defines); - } - /** - * Creates the render target textures and post processes used in the glow layer. - */ - _createTextureAndPostProcesses() { - let blurTextureWidth = this._mainTextureDesiredSize.width; - let blurTextureHeight = this._mainTextureDesiredSize.height; - blurTextureWidth = this._engine.needPOTTextures ? engine_Engine.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth; - blurTextureHeight = this._engine.needPOTTextures ? engine_Engine.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight; - let textureType = 0; - if (this._engine.getCaps().textureHalfFloatRender) { - textureType = 2; - } - else { - textureType = 0; - } - this._blurTexture1 = new renderTargetTexture_RenderTargetTexture("GlowLayerBlurRTT", { - width: blurTextureWidth, - height: blurTextureHeight, - }, this._scene, false, true, textureType); - this._blurTexture1.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._blurTexture1.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._blurTexture1.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE); - this._blurTexture1.renderParticles = false; - this._blurTexture1.ignoreCameraViewport = true; - const blurTextureWidth2 = Math.floor(blurTextureWidth / 2); - const blurTextureHeight2 = Math.floor(blurTextureHeight / 2); - this._blurTexture2 = new renderTargetTexture_RenderTargetTexture("GlowLayerBlurRTT2", { - width: blurTextureWidth2, - height: blurTextureHeight2, - }, this._scene, false, true, textureType); - this._blurTexture2.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._blurTexture2.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._blurTexture2.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE); - this._blurTexture2.renderParticles = false; - this._blurTexture2.ignoreCameraViewport = true; - this._textures = [this._blurTexture1, this._blurTexture2]; - const effectiveKernel = this._getEffectiveBlurKernelSize(); - this._horizontalBlurPostprocess1 = new BlurPostProcess("GlowLayerHBP1", new math_vector_Vector2(1.0, 0), effectiveKernel, { - width: blurTextureWidth, - height: blurTextureHeight, - }, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); - this._horizontalBlurPostprocess1.width = blurTextureWidth; - this._horizontalBlurPostprocess1.height = blurTextureHeight; - this._horizontalBlurPostprocess1.externalTextureSamplerBinding = true; - this._horizontalBlurPostprocess1.onApplyObservable.add((effect) => { - effect.setTexture("textureSampler", this._mainTexture); - }); - this._verticalBlurPostprocess1 = new BlurPostProcess("GlowLayerVBP1", new math_vector_Vector2(0, 1.0), effectiveKernel, { - width: blurTextureWidth, - height: blurTextureHeight, - }, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); - this._horizontalBlurPostprocess2 = new BlurPostProcess("GlowLayerHBP2", new math_vector_Vector2(1.0, 0), effectiveKernel, { - width: blurTextureWidth2, - height: blurTextureHeight2, - }, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); - this._horizontalBlurPostprocess2.width = blurTextureWidth2; - this._horizontalBlurPostprocess2.height = blurTextureHeight2; - this._horizontalBlurPostprocess2.externalTextureSamplerBinding = true; - this._horizontalBlurPostprocess2.onApplyObservable.add((effect) => { - effect.setTexture("textureSampler", this._blurTexture1); - }); - this._verticalBlurPostprocess2 = new BlurPostProcess("GlowLayerVBP2", new math_vector_Vector2(0, 1.0), effectiveKernel, { - width: blurTextureWidth2, - height: blurTextureHeight2, - }, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); - 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 internalTexture = this._blurTexture1.renderTarget; - if (internalTexture) { - this._scene.postProcessManager.directRender(this._postProcesses1, internalTexture, true); - const internalTexture2 = this._blurTexture2.renderTarget; - if (internalTexture2) { - this._scene.postProcessManager.directRender(this._postProcesses2, internalTexture2, true); - } - this._engine.unBindFramebuffer(internalTexture2 !== null && internalTexture2 !== void 0 ? internalTexture2 : internalTexture, true); - } - }); - // Prevent autoClear. - this._postProcesses.map((pp) => { - pp.autoClear = false; - }); - } - /** - * @returns The blur kernel size used by the glow. - * Note: The value passed in the options is divided by 2 for back compatibility. - */ - _getEffectiveBlurKernelSize() { - return this._options.blurKernelSize / 2; - } - /** - * Checks for the readiness of the element composing the layer. - * @param subMesh the mesh to check for - * @param useInstances specify whether or not to use instances to render the mesh - * @returns true if ready otherwise, false - */ - isReady(subMesh, useInstances) { - const material = subMesh.getMaterial(); - const mesh = subMesh.getRenderingMesh(); - if (!material || !mesh) { - return false; - } - const emissiveTexture = material.emissiveTexture; - return super._isReady(subMesh, useInstances, emissiveTexture); - } - /** - * Returns whether or not the layer needs stencil enabled during the mesh rendering. - */ - needStencil() { - return false; - } - /** - * Returns true if the mesh can be rendered, otherwise false. - * @param mesh The mesh to render - * @param material The material used on the mesh - * @returns true if it can be rendered otherwise false - */ - _canRenderMesh(mesh, material) { - return true; - } - /** - * Implementation specific of rendering the generating effect on the main canvas. - * @param effect The effect used to render through - */ - _internalRender(effect) { - // Texture - effect.setTexture("textureSampler", this._blurTexture1); - effect.setTexture("textureSampler2", this._blurTexture2); - effect.setFloat("offset", this._intensity); - // Cache - const engine = this._engine; - const previousStencilBuffer = engine.getStencilBuffer(); - // Draw order - engine.setStencilBuffer(false); - engine.drawElementsType(material_Material.TriangleFillMode, 0, 6); - // Draw order - engine.setStencilBuffer(previousStencilBuffer); - } - /** - * Sets the required values for both the emissive texture and and the main color. - * @param mesh - * @param subMesh - * @param material - */ - _setEmissiveTextureAndColor(mesh, subMesh, material) { - var _a; - let textureLevel = 1.0; - if (this.customEmissiveTextureSelector) { - this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material); - } - else { - if (material) { - this._emissiveTextureAndColor.texture = material.emissiveTexture; - if (this._emissiveTextureAndColor.texture) { - textureLevel = this._emissiveTextureAndColor.texture.level; - } - } - else { - this._emissiveTextureAndColor.texture = null; - } - } - if (this.customEmissiveColorSelector) { - this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color); - } - else { - if (material.emissiveColor) { - const emissiveIntensity = (_a = material.emissiveIntensity) !== null && _a !== void 0 ? _a : 1; - textureLevel *= emissiveIntensity; - this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, material.alpha); - } - else { - this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a); - } - } - } - /** - * Returns true if the mesh should render, otherwise false. - * @param mesh The mesh to render - * @returns true if it should render otherwise false - */ - _shouldRenderMesh(mesh) { - return this.hasMesh(mesh); - } - /** - * Adds specific effects defines. - * @param defines The defines to add specifics to. - */ - _addCustomEffectDefines(defines) { - defines.push("#define GLOW"); - } - /** - * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer. - * @param mesh The mesh to exclude from the glow layer - */ - addExcludedMesh(mesh) { - if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) { - this._excludedMeshes.push(mesh.uniqueId); - } - } - /** - * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer. - * @param mesh The mesh to remove - */ - removeExcludedMesh(mesh) { - const index = this._excludedMeshes.indexOf(mesh.uniqueId); - if (index !== -1) { - this._excludedMeshes.splice(index, 1); - } - } - /** - * Add a mesh in the inclusion list to impact or being impacted by the glow layer. - * @param mesh The mesh to include in the glow layer - */ - addIncludedOnlyMesh(mesh) { - if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) { - this._includedOnlyMeshes.push(mesh.uniqueId); - } - } - /** - * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer. - * @param mesh The mesh to remove - */ - removeIncludedOnlyMesh(mesh) { - const index = this._includedOnlyMeshes.indexOf(mesh.uniqueId); - if (index !== -1) { - this._includedOnlyMeshes.splice(index, 1); - } - } - /** - * Determine if a given mesh will be used in the glow layer - * @param mesh The mesh to test - * @returns true if the mesh will be highlighted by the current glow layer - */ - hasMesh(mesh) { - if (!super.hasMesh(mesh)) { - return false; - } - // Included Mesh - if (this._includedOnlyMeshes.length) { - return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1; - } - // Excluded Mesh - if (this._excludedMeshes.length) { - return this._excludedMeshes.indexOf(mesh.uniqueId) === -1; - } - return true; - } - /** - * Defines whether the current material of the mesh should be use to render the effect. - * @param mesh defines the current mesh to render - */ - _useMeshMaterial(mesh) { - if (this._meshesUsingTheirOwnMaterials.length == 0) { - return false; - } - return this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId) > -1; - } - /** - * Add a mesh to be rendered through its own material and not with emissive only. - * @param mesh The mesh for which we need to use its material - */ - referenceMeshToUseItsOwnMaterial(mesh) { - mesh.resetDrawCache(this._mainTexture.renderPassId); - this._meshesUsingTheirOwnMaterials.push(mesh.uniqueId); - mesh.onDisposeObservable.add(() => { - this._disposeMesh(mesh); - }); - } - /** - * Remove a mesh from being rendered through its own material and not with emissive only. - * @param mesh The mesh for which we need to not use its material - */ - unReferenceMeshFromUsingItsOwnMaterial(mesh) { - let index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId); - while (index >= 0) { - this._meshesUsingTheirOwnMaterials.splice(index, 1); - index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId); - } - mesh.resetDrawCache(this._mainTexture.renderPassId); - } - /** - * Free any resources and references associated to a mesh. - * Internal use - * @param mesh The mesh to free. - * @internal - */ - _disposeMesh(mesh) { - this.removeIncludedOnlyMesh(mesh); - this.removeExcludedMesh(mesh); - } - /** - * Gets the class name of the effect layer - * @returns the string with the class name of the effect layer - */ - getClassName() { - return "GlowLayer"; - } - /** - * Serializes this glow layer - * @returns a serialized glow layer object - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.customType = "BABYLON.GlowLayer"; - let index; - // Included meshes - serializationObject.includedMeshes = []; - if (this._includedOnlyMeshes.length) { - for (index = 0; index < this._includedOnlyMeshes.length; index++) { - const mesh = this._scene.getMeshByUniqueId(this._includedOnlyMeshes[index]); - if (mesh) { - serializationObject.includedMeshes.push(mesh.id); - } - } - } - // Excluded meshes - serializationObject.excludedMeshes = []; - if (this._excludedMeshes.length) { - for (index = 0; index < this._excludedMeshes.length; index++) { - const mesh = this._scene.getMeshByUniqueId(this._excludedMeshes[index]); - if (mesh) { - serializationObject.excludedMeshes.push(mesh.id); - } - } - } - return serializationObject; - } - /** - * Creates a Glow Layer from parsed glow layer data - * @param parsedGlowLayer defines glow layer data - * @param scene defines the current scene - * @param rootUrl defines the root URL containing the glow layer information - * @returns a parsed Glow Layer - */ - static Parse(parsedGlowLayer, scene, rootUrl) { - const gl = decorators_SerializationHelper.Parse(() => new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options), parsedGlowLayer, scene, rootUrl); - let index; - // Excluded meshes - for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) { - const mesh = scene.getMeshById(parsedGlowLayer.excludedMeshes[index]); - if (mesh) { - gl.addExcludedMesh(mesh); - } - } - // Included meshes - for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) { - const mesh = scene.getMeshById(parsedGlowLayer.includedMeshes[index]); - if (mesh) { - gl.addIncludedOnlyMesh(mesh); - } - } - return gl; - } -} -/** - * Effect Name of the layer. - */ -GlowLayer.EffectName = "GlowLayer"; -/** - * The default blur kernel size used for the glow. - */ -GlowLayer.DefaultBlurKernelSize = 32; -/** - * The default texture size ratio used for the glow. - */ -GlowLayer.DefaultTextureRatio = 0.5; -__decorate([ - serialize() -], GlowLayer.prototype, "blurKernelSize", null); -__decorate([ - serialize() -], GlowLayer.prototype, "intensity", null); -__decorate([ - serialize("options") -], GlowLayer.prototype, "_options", void 0); -RegisterClass("BABYLON.GlowLayer", GlowLayer); -//# sourceMappingURL=glowLayer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/glowBlurPostProcess.fragment.js -// Do not edit. - -const glowBlurPostProcess_fragment_name = "glowBlurPostProcessPixelShader"; -const glowBlurPostProcess_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color) -{return dot(color,vec3(0.2126,0.7152,0.0722));} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++) -{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;} -gl_FragColor=baseColor;}`; -// Sideeffect -ShaderStore.ShadersStore[glowBlurPostProcess_fragment_name] = glowBlurPostProcess_fragment_shader; -/** @internal */ -const glowBlurPostProcessPixelShader = { name: glowBlurPostProcess_fragment_name, shader: glowBlurPostProcess_fragment_shader }; -//# sourceMappingURL=glowBlurPostProcess.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Layers/highlightLayer.js - -/* eslint-disable @typescript-eslint/no-unused-vars */ - - - - - - - - - - - - - - - - - - - - - -AbstractScene.prototype.getHighlightLayerByName = function (name) { - var _a; - for (let index = 0; index < ((_a = this.effectLayers) === null || _a === void 0 ? void 0 : _a.length); index++) { - if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) { - return this.effectLayers[index]; - } - } - return null; -}; -/** - * Special Glow Blur post process only blurring the alpha channel - * It enforces keeping the most luminous color in the color channel. - */ -class GlowBlurPostProcess extends postProcess_PostProcess { - constructor(name, direction, kernel, options, camera, samplingMode = texture_Texture.BILINEAR_SAMPLINGMODE, engine, reusable) { - super(name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable); - this.direction = direction; - this.kernel = kernel; - this.onApplyObservable.add((effect) => { - effect.setFloat2("screenSize", this.width, this.height); - effect.setVector2("direction", this.direction); - effect.setFloat("blurWidth", this.kernel); - }); - } -} -/** - * The highlight layer Helps adding a glow effect around a mesh. - * - * Once instantiated in a scene, simply use the addMesh or removeMesh method to add or remove - * glowy meshes to your scene. - * - * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!! - */ -class HighlightLayer extends EffectLayer { - /** - * Specifies the horizontal size of the blur. - */ - set blurHorizontalSize(value) { - this._horizontalBlurPostprocess.kernel = value; - this._options.blurHorizontalSize = value; - } - /** - * Specifies the vertical size of the blur. - */ - set blurVerticalSize(value) { - this._verticalBlurPostprocess.kernel = value; - this._options.blurVerticalSize = value; - } - /** - * Gets the horizontal size of the blur. - */ - get blurHorizontalSize() { - return this._horizontalBlurPostprocess.kernel; - } - /** - * Gets the vertical size of the blur. - */ - get blurVerticalSize() { - return this._verticalBlurPostprocess.kernel; - } - /** - * Instantiates a new highlight Layer and references it to the scene.. - * @param name The name of the layer - * @param scene The scene to use the layer in - * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information) - */ - constructor(name, scene, options) { - super(name, scene); - this.name = name; - /** - * Specifies whether or not the inner glow is ACTIVE in the layer. - */ - this.innerGlow = true; - /** - * Specifies whether or not the outer glow is ACTIVE in the layer. - */ - this.outerGlow = true; - /** - * An event triggered when the highlight layer is being blurred. - */ - this.onBeforeBlurObservable = new observable_Observable(); - /** - * An event triggered when the highlight layer has been blurred. - */ - this.onAfterBlurObservable = new observable_Observable(); - this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++; - this._meshes = {}; - this._excludedMeshes = {}; - this.neutralColor = HighlightLayer.NeutralColor; - // Warn on stencil - if (!this._engine.isStencilEnable) { - logger_Logger.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"); - } - // Adapt options - 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); - // Initialize the layer - 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, - }); - // Do not render as long as no meshes have been added - this._shouldRender = false; - } - /** - * Get the effect name of the layer. - * @returns The effect name - */ - getEffectName() { - return HighlightLayer.EffectName; - } - _numInternalDraws() { - return 2; // we need two rendering, one for the inner glow and the other for the outer glow - } - /** - * Create the merge effect. This is the shader use to blit the information back - * to the main canvas at the end of the scene rendering. - */ - _createMergeEffect() { - // Effect - return this._engine.createEffect("glowMapMerge", [buffer_VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined); - } - /** - * Creates the render target textures and post processes used in the highlight layer. - */ - _createTextureAndPostProcesses() { - let blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio; - let blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio; - blurTextureWidth = this._engine.needPOTTextures ? engine_Engine.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth; - blurTextureHeight = this._engine.needPOTTextures ? engine_Engine.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight; - let textureType = 0; - if (this._engine.getCaps().textureHalfFloatRender) { - textureType = 2; - } - else { - textureType = 0; - } - this._blurTexture = new renderTargetTexture_RenderTargetTexture("HighlightLayerBlurRTT", { - width: blurTextureWidth, - height: blurTextureHeight, - }, this._scene, false, true, textureType); - this._blurTexture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._blurTexture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._blurTexture.anisotropicFilteringLevel = 16; - this._blurTexture.updateSamplingMode(texture_Texture.TRILINEAR_SAMPLINGMODE); - this._blurTexture.renderParticles = false; - this._blurTexture.ignoreCameraViewport = true; - this._textures = [this._blurTexture]; - if (this._options.alphaBlendingMode === 2) { - this._downSamplePostprocess = new PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine()); - this._downSamplePostprocess.externalTextureSamplerBinding = true; - this._downSamplePostprocess.onApplyObservable.add((effect) => { - effect.setTexture("textureSampler", this._mainTexture); - }); - this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new math_vector_Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine()); - this._horizontalBlurPostprocess.onApplyObservable.add((effect) => { - effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); - }); - this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new math_vector_Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine()); - this._verticalBlurPostprocess.onApplyObservable.add((effect) => { - effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); - }); - this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess]; - } - else { - this._horizontalBlurPostprocess = new BlurPostProcess("HighlightLayerHBP", new math_vector_Vector2(1.0, 0), this._options.blurHorizontalSize / 2, { - width: blurTextureWidth, - height: blurTextureHeight, - }, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); - this._horizontalBlurPostprocess.width = blurTextureWidth; - this._horizontalBlurPostprocess.height = blurTextureHeight; - this._horizontalBlurPostprocess.externalTextureSamplerBinding = true; - this._horizontalBlurPostprocess.onApplyObservable.add((effect) => { - effect.setTexture("textureSampler", this._mainTexture); - }); - this._verticalBlurPostprocess = new BlurPostProcess("HighlightLayerVBP", new math_vector_Vector2(0, 1.0), this._options.blurVerticalSize / 2, { - width: blurTextureWidth, - height: blurTextureHeight, - }, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); - this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess]; - } - this._mainTexture.onAfterUnbindObservable.add(() => { - this.onBeforeBlurObservable.notifyObservers(this); - const internalTexture = this._blurTexture.renderTarget; - if (internalTexture) { - this._scene.postProcessManager.directRender(this._postProcesses, internalTexture, true); - this._engine.unBindFramebuffer(internalTexture, true); - } - this.onAfterBlurObservable.notifyObservers(this); - }); - // Prevent autoClear. - this._postProcesses.map((pp) => { - pp.autoClear = false; - }); - } - /** - * Returns whether or not the layer needs stencil enabled during the mesh rendering. - */ - needStencil() { - return true; - } - /** - * Checks for the readiness of the element composing the layer. - * @param subMesh the mesh to check for - * @param useInstances specify whether or not to use instances to render the mesh - * @returns true if ready otherwise, false - */ - isReady(subMesh, useInstances) { - const material = subMesh.getMaterial(); - const mesh = subMesh.getRenderingMesh(); - if (!material || !mesh || !this._meshes) { - return false; - } - let emissiveTexture = null; - const highlightLayerMesh = this._meshes[mesh.uniqueId]; - if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) { - emissiveTexture = material.emissiveTexture; - } - return super._isReady(subMesh, useInstances, emissiveTexture); - } - /** - * Implementation specific of rendering the generating effect on the main canvas. - * @param effect The effect used to render through - * @param renderIndex - */ - _internalRender(effect, renderIndex) { - // Texture - effect.setTexture("textureSampler", this._blurTexture); - // Cache - const engine = this._engine; - engine.cacheStencilState(); - // Stencil operations - engine.setStencilOperationPass(7681); - engine.setStencilOperationFail(7680); - engine.setStencilOperationDepthFail(7680); - // Draw order - engine.setStencilMask(0x00); - engine.setStencilBuffer(true); - engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference); - // 2 passes inner outer - if (this.outerGlow && renderIndex === 0) { - // the outer glow is rendered the first time _internalRender is called, so when renderIndex == 0 (and only if outerGlow is enabled) - effect.setFloat("offset", 0); - engine.setStencilFunction(517); - engine.drawElementsType(material_Material.TriangleFillMode, 0, 6); - } - if (this.innerGlow && renderIndex === 1) { - // the inner glow is rendered the second time _internalRender is called, so when renderIndex == 1 (and only if innerGlow is enabled) - effect.setFloat("offset", 1); - engine.setStencilFunction(514); - engine.drawElementsType(material_Material.TriangleFillMode, 0, 6); - } - // Restore Cache - engine.restoreStencilState(); - } - /** - * Returns true if the layer contains information to display, otherwise false. - */ - shouldRender() { - if (super.shouldRender()) { - return this._meshes ? true : false; - } - return false; - } - /** - * Returns true if the mesh should render, otherwise false. - * @param mesh The mesh to render - * @returns true if it should render otherwise false - */ - _shouldRenderMesh(mesh) { - // Excluded Mesh - if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) { - return false; - } - if (!super.hasMesh(mesh)) { - return false; - } - return true; - } - /** - * Returns true if the mesh can be rendered, otherwise false. - * @param mesh The mesh to render - * @param material The material used on the mesh - * @returns true if it can be rendered otherwise false - */ - _canRenderMesh(mesh, material) { - // all meshes can be rendered in the highlight layer, even transparent ones - return true; - } - /** - * Adds specific effects defines. - * @param defines The defines to add specifics to. - */ - _addCustomEffectDefines(defines) { - defines.push("#define HIGHLIGHT"); - } - /** - * Sets the required values for both the emissive texture and and the main color. - * @param mesh - * @param subMesh - * @param material - */ - _setEmissiveTextureAndColor(mesh, subMesh, material) { - const highlightLayerMesh = this._meshes[mesh.uniqueId]; - if (highlightLayerMesh) { - this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0); - } - else { - this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a); - } - if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) { - this._emissiveTextureAndColor.texture = material.emissiveTexture; - this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0); - } - else { - this._emissiveTextureAndColor.texture = null; - } - } - /** - * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer. - * @param mesh The mesh to exclude from the highlight layer - */ - addExcludedMesh(mesh) { - if (!this._excludedMeshes) { - return; - } - const meshExcluded = this._excludedMeshes[mesh.uniqueId]; - if (!meshExcluded) { - const obj = { - mesh: mesh, - beforeBind: null, - afterRender: null, - stencilState: false, - }; - obj.beforeBind = mesh.onBeforeBindObservable.add((mesh) => { - obj.stencilState = mesh.getEngine().getStencilBuffer(); - mesh.getEngine().setStencilBuffer(false); - }); - obj.afterRender = mesh.onAfterRenderObservable.add((mesh) => { - mesh.getEngine().setStencilBuffer(obj.stencilState); - }); - this._excludedMeshes[mesh.uniqueId] = obj; - } - } - /** - * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer. - * @param mesh The mesh to highlight - */ - removeExcludedMesh(mesh) { - if (!this._excludedMeshes) { - return; - } - const meshExcluded = this._excludedMeshes[mesh.uniqueId]; - if (meshExcluded) { - if (meshExcluded.beforeBind) { - mesh.onBeforeBindObservable.remove(meshExcluded.beforeBind); - } - if (meshExcluded.afterRender) { - mesh.onAfterRenderObservable.remove(meshExcluded.afterRender); - } - } - this._excludedMeshes[mesh.uniqueId] = null; - } - /** - * Determine if a given mesh will be highlighted by the current HighlightLayer - * @param mesh mesh to test - * @returns true if the mesh will be highlighted by the current HighlightLayer - */ - hasMesh(mesh) { - if (!this._meshes) { - return false; - } - if (!super.hasMesh(mesh)) { - return false; - } - return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null; - } - /** - * Add a mesh in the highlight layer in order to make it glow with the chosen color. - * @param mesh The mesh to highlight - * @param color The color of the highlight - * @param glowEmissiveOnly Extract the glow from the emissive texture - */ - addMesh(mesh, color, glowEmissiveOnly = false) { - if (!this._meshes) { - return; - } - const meshHighlight = this._meshes[mesh.uniqueId]; - if (meshHighlight) { - meshHighlight.color = color; - } - else { - this._meshes[mesh.uniqueId] = { - mesh: mesh, - color: color, - // Lambda required for capture due to Observable this context - observerHighlight: mesh.onBeforeBindObservable.add((mesh) => { - if (this.isEnabled) { - if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) { - this._defaultStencilReference(mesh); - } - else { - mesh.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference); - } - } - }), - observerDefault: mesh.onAfterRenderObservable.add((mesh) => { - if (this.isEnabled) { - this._defaultStencilReference(mesh); - } - }), - glowEmissiveOnly: glowEmissiveOnly, - }; - mesh.onDisposeObservable.add(() => { - this._disposeMesh(mesh); - }); - } - this._shouldRender = true; - } - /** - * Remove a mesh from the highlight layer in order to make it stop glowing. - * @param mesh The mesh to highlight - */ - removeMesh(mesh) { - if (!this._meshes) { - return; - } - const meshHighlight = this._meshes[mesh.uniqueId]; - if (meshHighlight) { - if (meshHighlight.observerHighlight) { - mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight); - } - if (meshHighlight.observerDefault) { - mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault); - } - delete this._meshes[mesh.uniqueId]; - } - this._shouldRender = false; - for (const meshHighlightToCheck in this._meshes) { - if (this._meshes[meshHighlightToCheck]) { - this._shouldRender = true; - break; - } - } - } - /** - * Remove all the meshes currently referenced in the highlight layer - */ - removeAllMeshes() { - if (!this._meshes) { - return; - } - for (const uniqueId in this._meshes) { - if (Object.prototype.hasOwnProperty.call(this._meshes, uniqueId)) { - const mesh = this._meshes[uniqueId]; - if (mesh) { - this.removeMesh(mesh.mesh); - } - } - } - } - /** - * Force the stencil to the normal expected value for none glowing parts - * @param mesh - */ - _defaultStencilReference(mesh) { - mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference); - } - /** - * Free any resources and references associated to a mesh. - * Internal use - * @param mesh The mesh to free. - * @internal - */ - _disposeMesh(mesh) { - this.removeMesh(mesh); - this.removeExcludedMesh(mesh); - } - /** - * Dispose the highlight layer and free resources. - */ - dispose() { - if (this._meshes) { - // Clean mesh references - for (const id in this._meshes) { - const meshHighlight = this._meshes[id]; - if (meshHighlight && meshHighlight.mesh) { - if (meshHighlight.observerHighlight) { - meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight); - } - if (meshHighlight.observerDefault) { - meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault); - } - } - } - this._meshes = null; - } - if (this._excludedMeshes) { - for (const id in this._excludedMeshes) { - const meshHighlight = this._excludedMeshes[id]; - if (meshHighlight) { - if (meshHighlight.beforeBind) { - meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.beforeBind); - } - if (meshHighlight.afterRender) { - meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender); - } - } - } - this._excludedMeshes = null; - } - super.dispose(); - } - /** - * Gets the class name of the effect layer - * @returns the string with the class name of the effect layer - */ - getClassName() { - return "HighlightLayer"; - } - /** - * Serializes this Highlight layer - * @returns a serialized Highlight layer object - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.customType = "BABYLON.HighlightLayer"; - // Highlighted meshes - serializationObject.meshes = []; - if (this._meshes) { - for (const m in this._meshes) { - const mesh = this._meshes[m]; - if (mesh) { - serializationObject.meshes.push({ - glowEmissiveOnly: mesh.glowEmissiveOnly, - color: mesh.color.asArray(), - meshId: mesh.mesh.id, - }); - } - } - } - // Excluded meshes - serializationObject.excludedMeshes = []; - if (this._excludedMeshes) { - for (const e in this._excludedMeshes) { - const excludedMesh = this._excludedMeshes[e]; - if (excludedMesh) { - serializationObject.excludedMeshes.push(excludedMesh.mesh.id); - } - } - } - return serializationObject; - } - /** - * Creates a Highlight layer from parsed Highlight layer data - * @param parsedHightlightLayer defines the Highlight layer data - * @param scene defines the current scene - * @param rootUrl defines the root URL containing the Highlight layer information - * @returns a parsed Highlight layer - */ - static Parse(parsedHightlightLayer, scene, rootUrl) { - const hl = decorators_SerializationHelper.Parse(() => new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options), parsedHightlightLayer, scene, rootUrl); - let index; - // Excluded meshes - for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) { - const mesh = scene.getMeshById(parsedHightlightLayer.excludedMeshes[index]); - if (mesh) { - hl.addExcludedMesh(mesh); - } - } - // Included meshes - for (index = 0; index < parsedHightlightLayer.meshes.length; index++) { - const highlightedMesh = parsedHightlightLayer.meshes[index]; - const mesh = scene.getMeshById(highlightedMesh.meshId); - if (mesh) { - hl.addMesh(mesh, math_color_Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly); - } - } - return hl; - } -} -/** - * Effect Name of the highlight layer. - */ -HighlightLayer.EffectName = "HighlightLayer"; -/** - * The neutral color used during the preparation of the glow effect. - * This is black by default as the blend operation is a blend operation. - */ -HighlightLayer.NeutralColor = new math_color_Color4(0, 0, 0, 0); -/** - * Stencil value used for glowing meshes. - */ -HighlightLayer.GlowingMeshStencilReference = 0x02; -/** - * Stencil value used for the other meshes in the scene. - */ -HighlightLayer.NormalMeshStencilReference = 0x01; -__decorate([ - serialize() -], HighlightLayer.prototype, "innerGlow", void 0); -__decorate([ - serialize() -], HighlightLayer.prototype, "outerGlow", void 0); -__decorate([ - serialize() -], HighlightLayer.prototype, "blurHorizontalSize", null); -__decorate([ - serialize() -], HighlightLayer.prototype, "blurVerticalSize", null); -__decorate([ - serialize("options") -], HighlightLayer.prototype, "_options", void 0); -RegisterClass("BABYLON.HighlightLayer", HighlightLayer); -//# sourceMappingURL=highlightLayer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Layers/layerSceneComponent.js - - -/** - * Defines the layer scene component responsible to manage any layers - * in a given scene. - */ -class layerSceneComponent_LayerSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = SceneComponentConstants.NAME_LAYER; - this.scene = scene || EngineStore.LastCreatedScene; - if (!this.scene) { - return; - } - this._engine = this.scene.getEngine(); - this.scene.layers = new Array(); - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground); - this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForegroundWithPostProcessing); - this.scene._afterCameraPostProcessStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER, this, this._drawCameraForegroundWithoutPostProcessing); - this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground); - this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForegroundWithPostProcessing); - this.scene._afterRenderTargetPostProcessStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER, this, this._drawRenderTargetForegroundWithoutPostProcessing); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - const layers = this.scene.layers; - for (const layer of layers) { - layer._rebuild(); - } - } - /** - * Disposes the component and the associated resources. - */ - dispose() { - const layers = this.scene.layers; - while (layers.length) { - layers[0].dispose(); - } - } - _draw(predicate) { - const layers = this.scene.layers; - if (layers.length) { - this._engine.setDepthBuffer(false); - for (const layer of layers) { - if (predicate(layer)) { - layer.render(); - } - } - this._engine.setDepthBuffer(true); - } - } - _drawCameraPredicate(layer, isBackground, applyPostProcess, cameraLayerMask) { - return (!layer.renderOnlyInRenderTargetTextures && - layer.isBackground === isBackground && - layer.applyPostProcess === applyPostProcess && - (layer.layerMask & cameraLayerMask) !== 0); - } - _drawCameraBackground(camera) { - this._draw((layer) => { - return this._drawCameraPredicate(layer, true, true, camera.layerMask); - }); - } - _drawCameraForegroundWithPostProcessing(camera) { - this._draw((layer) => { - return this._drawCameraPredicate(layer, false, true, camera.layerMask); - }); - } - _drawCameraForegroundWithoutPostProcessing(camera) { - this._draw((layer) => { - return this._drawCameraPredicate(layer, false, false, camera.layerMask); - }); - } - _drawRenderTargetPredicate(layer, isBackground, applyPostProcess, cameraLayerMask, renderTargetTexture) { - return (layer.renderTargetTextures.length > 0 && - layer.isBackground === isBackground && - layer.applyPostProcess === applyPostProcess && - layer.renderTargetTextures.indexOf(renderTargetTexture) > -1 && - (layer.layerMask & cameraLayerMask) !== 0); - } - _drawRenderTargetBackground(renderTarget) { - this._draw((layer) => { - return this._drawRenderTargetPredicate(layer, true, true, this.scene.activeCamera.layerMask, renderTarget); - }); - } - _drawRenderTargetForegroundWithPostProcessing(renderTarget) { - this._draw((layer) => { - return this._drawRenderTargetPredicate(layer, false, true, this.scene.activeCamera.layerMask, renderTarget); - }); - } - _drawRenderTargetForegroundWithoutPostProcessing(renderTarget) { - this._draw((layer) => { - return this._drawRenderTargetPredicate(layer, false, false, this.scene.activeCamera.layerMask, renderTarget); - }); - } - /** - * Adds all the elements from the container to the scene - * @param container the container holding the elements - */ - addFromContainer(container) { - if (!container.layers) { - return; - } - container.layers.forEach((layer) => { - this.scene.layers.push(layer); - }); - } - /** - * Removes all the elements in the container from the scene - * @param container contains the elements to remove - * @param dispose if the removed element should be disposed (default: false) - */ - removeFromContainer(container, dispose = false) { - if (!container.layers) { - return; - } - container.layers.forEach((layer) => { - const index = this.scene.layers.indexOf(layer); - if (index !== -1) { - this.scene.layers.splice(index, 1); - } - if (dispose) { - layer.dispose(); - } - }); - } -} -//# sourceMappingURL=layerSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/layer.fragment.js -// Do not edit. - - -const layer_fragment_name = "layerPixelShader"; -const layer_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; -#include<helperFunctions> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV); -#ifdef LINEAR -baseColor.rgb=toGammaSpace(baseColor.rgb); -#endif -#ifdef ALPHATEST -if (baseColor.a<0.4) -discard; -#endif -gl_FragColor=baseColor*color; -#define CUSTOM_FRAGMENT_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[layer_fragment_name] = layer_fragment_shader; -/** @internal */ -const layerPixelShader = { name: layer_fragment_name, shader: layer_fragment_shader }; -//# sourceMappingURL=layer.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/layer.vertex.js -// Do not edit. - -const layer_vertex_name = "layerVertexShader"; -const layer_vertex_shader = `attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[layer_vertex_name] = layer_vertex_shader; -/** @internal */ -const layerVertexShader = { name: layer_vertex_name, shader: layer_vertex_shader }; -//# sourceMappingURL=layer.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Layers/layer.js - - - - - - - - - - - - - -/** - * This represents a full screen 2d layer. - * This can be useful to display a picture in the background of your scene for instance. - * @see https://www.babylonjs-playground.com/#08A2BS#1 - */ -class Layer { - /** - * Determines if the layer is drawn before (true) or after (false) post-processing. - * If the layer is background, it is always before. - */ - set applyPostProcess(value) { - this._applyPostProcess = value; - } - get applyPostProcess() { - return this.isBackground || this._applyPostProcess; - } - /** - * Back compatibility with callback before the onDisposeObservable existed. - * The set callback will be triggered when the layer has been disposed. - */ - set onDispose(callback) { - if (this._onDisposeObserver) { - this.onDisposeObservable.remove(this._onDisposeObserver); - } - this._onDisposeObserver = this.onDisposeObservable.add(callback); - } - /** - * Back compatibility with callback before the onBeforeRenderObservable existed. - * The set callback will be triggered just before rendering the layer. - */ - set onBeforeRender(callback) { - if (this._onBeforeRenderObserver) { - this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); - } - this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); - } - /** - * Back compatibility with callback before the onAfterRenderObservable existed. - * The set callback will be triggered just after rendering the layer. - */ - set onAfterRender(callback) { - if (this._onAfterRenderObserver) { - this.onAfterRenderObservable.remove(this._onAfterRenderObserver); - } - this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); - } - /** - * Instantiates a new layer. - * This represents a full screen 2d layer. - * This can be useful to display a picture in the background of your scene for instance. - * @see https://www.babylonjs-playground.com/#08A2BS#1 - * @param name Define the name of the layer in the scene - * @param imgUrl Define the url of the texture to display in the layer - * @param scene Define the scene the layer belongs to - * @param isBackground Defines whether the layer is displayed in front or behind the scene - * @param color Defines a color for the layer - */ - constructor( - /** - * Define the name of the layer. - */ - name, imgUrl, scene, isBackground, color) { - this.name = name; - this._applyPostProcess = true; - /** - * Define the scale of the layer in order to zoom in out of the texture. - */ - this.scale = new Vector2(1, 1); - /** - * Define an offset for the layer in order to shift the texture. - */ - this.offset = new Vector2(0, 0); - /** - * Define the alpha blending mode used in the layer in case the texture or color has an alpha. - */ - this.alphaBlendingMode = 2; - /** - * Define a mask to restrict the layer to only some of the scene cameras. - */ - this.layerMask = 0x0fffffff; - /** - * Define the list of render target the layer is visible into. - */ - this.renderTargetTextures = []; - /** - * Define if the layer is only used in renderTarget or if it also - * renders in the main frame buffer of the canvas. - */ - this.renderOnlyInRenderTargetTextures = false; - /** - * Define if the layer is enabled (ie. should be displayed). Default: true - */ - this.isEnabled = true; - this._vertexBuffers = {}; - /** - * An event triggered when the layer is disposed. - */ - this.onDisposeObservable = new Observable(); - /** - * An event triggered before rendering the scene - */ - this.onBeforeRenderObservable = new Observable(); - /** - * An event triggered after rendering the scene - */ - this.onAfterRenderObservable = new Observable(); - this.texture = imgUrl ? new Texture(imgUrl, scene, true) : null; - this.isBackground = isBackground === undefined ? true : isBackground; - this.color = color === undefined ? new Color4(1, 1, 1, 1) : color; - this._scene = (scene || EngineStore.LastCreatedScene); - let layerComponent = this._scene._getComponent(SceneComponentConstants.NAME_LAYER); - if (!layerComponent) { - layerComponent = new LayerSceneComponent(this._scene); - this._scene._addComponent(layerComponent); - } - this._scene.layers.push(this); - const engine = this._scene.getEngine(); - this._drawWrapper = new DrawWrapper(engine); - // VBO - const vertices = []; - vertices.push(1, 1); - vertices.push(-1, 1); - vertices.push(-1, -1); - vertices.push(1, -1); - const vertexBuffer = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2); - this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer; - this._createIndexBuffer(); - } - _createIndexBuffer() { - const engine = this._scene.getEngine(); - // Indices - const indices = []; - indices.push(0); - indices.push(1); - indices.push(2); - indices.push(0); - indices.push(2); - indices.push(3); - this._indexBuffer = engine.createIndexBuffer(indices); - } - /** @internal */ - _rebuild() { - const vb = this._vertexBuffers[VertexBuffer.PositionKind]; - if (vb) { - vb._rebuild(); - } - this._createIndexBuffer(); - } - /** - * Checks if the layer is ready to be rendered - * @returns true if the layer is ready. False otherwise. - */ - isReady() { - var _a; - const engine = this._scene.getEngine(); - let defines = ""; - if (this.alphaTest) { - defines = "#define ALPHATEST"; - } - if (this.texture && !this.texture.gammaSpace) { - defines += "\n#define LINEAR"; - } - if (this._previousDefines !== defines) { - this._previousDefines = defines; - this._drawWrapper.effect = engine.createEffect("layer", [VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], defines); - } - const currentEffect = this._drawWrapper.effect; - return (currentEffect === null || currentEffect === void 0 ? void 0 : currentEffect.isReady()) && ((_a = this.texture) === null || _a === void 0 ? void 0 : _a.isReady()); - } - /** - * Renders the layer in the scene. - */ - render() { - if (!this.isEnabled) { - return; - } - const engine = this._scene.getEngine(); - // Check - if (!this.isReady()) { - return; - } - const currentEffect = this._drawWrapper.effect; - this.onBeforeRenderObservable.notifyObservers(this); - // Render - engine.enableEffect(this._drawWrapper); - engine.setState(false); - // Texture - currentEffect.setTexture("textureSampler", this.texture); - currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix()); - // Color - currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a); - // Scale / offset - currentEffect.setVector2("offset", this.offset); - currentEffect.setVector2("scale", this.scale); - // VBOs - engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect); - // Draw order - if (!this.alphaTest) { - engine.setAlphaMode(this.alphaBlendingMode); - engine.drawElementsType(Material.TriangleFillMode, 0, 6); - engine.setAlphaMode(0); - } - else { - engine.drawElementsType(Material.TriangleFillMode, 0, 6); - } - this.onAfterRenderObservable.notifyObservers(this); - } - /** - * Disposes and releases the associated resources. - */ - dispose() { - const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind]; - if (vertexBuffer) { - vertexBuffer.dispose(); - this._vertexBuffers[VertexBuffer.PositionKind] = null; - } - if (this._indexBuffer) { - this._scene.getEngine()._releaseBuffer(this._indexBuffer); - this._indexBuffer = null; - } - if (this.texture) { - this.texture.dispose(); - this.texture = null; - } - // Clean RTT list - this.renderTargetTextures = []; - // Remove from scene - const index = this._scene.layers.indexOf(this); - this._scene.layers.splice(index, 1); - // Callback - this.onDisposeObservable.notifyObservers(this); - this.onDisposeObservable.clear(); - this.onAfterRenderObservable.clear(); - this.onBeforeRenderObservable.clear(); - } -} -//# sourceMappingURL=layer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Layers/index.js - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/LensFlares/lensFlare.js - - - - - -/** - * This represents one of the lens effect in a `lensFlareSystem`. - * It controls one of the individual texture used in the effect. - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare - */ -class LensFlare { - /** - * Creates a new Lens Flare. - * This represents one of the lens effect in a `lensFlareSystem`. - * It controls one of the individual texture used in the effect. - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare - * @param size Define the size of the lens flare (a floating value between 0 and 1) - * @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. - * @param color Define the lens color - * @param imgUrl Define the lens texture url - * @param system Define the `lensFlareSystem` this flare is part of - * @returns The newly created Lens Flare - */ - static AddFlare(size, position, color, imgUrl, system) { - return new LensFlare(size, position, color, imgUrl, system); - } - /** - * Instantiates a new Lens Flare. - * This represents one of the lens effect in a `lensFlareSystem`. - * It controls one of the individual texture used in the effect. - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare - * @param size Define the size of the lens flare in the system (a floating value between 0 and 1) - * @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. - * @param color Define the lens color - * @param imgUrl Define the lens texture url - * @param system Define the `lensFlareSystem` this flare is part of - */ - constructor( - /** - * Define the size of the lens flare in the system (a floating value between 0 and 1) - */ - size, - /** - * 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. - */ - position, color, imgUrl, system) { - this.size = size; - this.position = position; - /** - * Define the alpha mode to render this particular lens. - */ - this.alphaMode = 6; - this.color = color || new math_color_Color3(1, 1, 1); - this.texture = imgUrl ? new texture_Texture(imgUrl, system.getScene(), true) : null; - this._system = system; - const engine = system.scene.getEngine(); - this._drawWrapper = new drawWrapper_DrawWrapper(engine); - this._drawWrapper.effect = engine.createEffect("lensFlare", [buffer_VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], ""); - system.lensFlares.push(this); - } - /** - * Dispose and release the lens flare with its associated resources. - */ - dispose() { - if (this.texture) { - this.texture.dispose(); - } - // Remove from scene - const index = this._system.lensFlares.indexOf(this); - this._system.lensFlares.splice(index, 1); - } -} -//# sourceMappingURL=lensFlare.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/lensFlare.fragment.js -// Do not edit. - -const lensFlare_fragment_name = "lensFlarePixelShader"; -const lensFlare_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; -#define CUSTOM_FRAGMENT_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[lensFlare_fragment_name] = lensFlare_fragment_shader; -/** @internal */ -const lensFlarePixelShader = { name: lensFlare_fragment_name, shader: lensFlare_fragment_shader }; -//# sourceMappingURL=lensFlare.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/lensFlare.vertex.js -// Do not edit. - -const lensFlare_vertex_name = "lensFlareVertexShader"; -const lensFlare_vertex_shader = `attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[lensFlare_vertex_name] = lensFlare_vertex_shader; -/** @internal */ -const lensFlareVertexShader = { name: lensFlare_vertex_name, shader: lensFlare_vertex_shader }; -//# sourceMappingURL=lensFlare.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/LensFlares/lensFlareSystem.js - - - - - - - - - - - - - -/** - * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses. - * It is usually composed of several `lensFlare`. - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare - */ -class LensFlareSystem { - /** Gets the scene */ - get scene() { - return this._scene; - } - /** - * Instantiates a lens flare system. - * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses. - * It is usually composed of several `lensFlare`. - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare - * @param name Define the name of the lens flare system in the scene - * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh). - * @param scene Define the scene the lens flare system belongs to - */ - constructor( - /** - * Define the name of the lens flare system - */ - name, emitter, scene) { - this.name = name; - /** - * List of lens flares used in this system. - */ - this.lensFlares = new Array(); - /** - * Define a limit from the border the lens flare can be visible. - */ - this.borderLimit = 300; - /** - * Define a viewport border we do not want to see the lens flare in. - */ - this.viewportBorder = 0; - /** - * Restricts the rendering of the effect to only the camera rendering this layer mask. - */ - this.layerMask = 0x0fffffff; - this._vertexBuffers = {}; - this._isEnabled = true; - this._scene = scene || engineStore_EngineStore.LastCreatedScene; - LensFlareSystem._SceneComponentInitialization(this._scene); - this._emitter = emitter; - this.id = name; - scene.lensFlareSystems.push(this); - this.meshesSelectionPredicate = (m) => (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && (m.layerMask & scene.activeCamera.layerMask) != 0); - const engine = scene.getEngine(); - // VBO - const vertices = []; - vertices.push(1, 1); - vertices.push(-1, 1); - vertices.push(-1, -1); - vertices.push(1, -1); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = new buffer_VertexBuffer(engine, vertices, buffer_VertexBuffer.PositionKind, false, false, 2); - // Indices - this._createIndexBuffer(); - } - _createIndexBuffer() { - const indices = []; - indices.push(0); - indices.push(1); - indices.push(2); - indices.push(0); - indices.push(2); - indices.push(3); - this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices); - } - /** - * Define if the lens flare system is enabled. - */ - get isEnabled() { - return this._isEnabled; - } - set isEnabled(value) { - this._isEnabled = value; - } - /** - * Get the scene the effects belongs to. - * @returns the scene holding the lens flare system - */ - getScene() { - return this._scene; - } - /** - * Get the emitter of the lens flare system. - * It defines the source of the lens flares (it can be a camera, a light or a mesh). - * @returns the emitter of the lens flare system - */ - getEmitter() { - return this._emitter; - } - /** - * Set the emitter of the lens flare system. - * It defines the source of the lens flares (it can be a camera, a light or a mesh). - * @param newEmitter Define the new emitter of the system - */ - setEmitter(newEmitter) { - this._emitter = newEmitter; - } - /** - * Get the lens flare system emitter position. - * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh). - * @returns the position - */ - getEmitterPosition() { - return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position; - } - /** - * @internal - */ - computeEffectivePosition(globalViewport) { - let position = this.getEmitterPosition(); - position = math_vector_Vector3.Project(position, math_vector_Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport); - this._positionX = position.x; - this._positionY = position.y; - position = math_vector_Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix()); - if (this.viewportBorder > 0) { - globalViewport.x -= this.viewportBorder; - globalViewport.y -= this.viewportBorder; - globalViewport.width += this.viewportBorder * 2; - globalViewport.height += this.viewportBorder * 2; - position.x += this.viewportBorder; - position.y += this.viewportBorder; - this._positionX += this.viewportBorder; - this._positionY += this.viewportBorder; - } - const rhs = this._scene.useRightHandedSystem; - const okZ = (position.z > 0 && !rhs) || (position.z < 0 && rhs); - if (okZ) { - if (this._positionX > globalViewport.x && this._positionX < globalViewport.x + globalViewport.width) { - if (this._positionY > globalViewport.y && this._positionY < globalViewport.y + globalViewport.height) { - return true; - } - } - return true; - } - return false; - } - /** @internal */ - _isVisible() { - if (!this._isEnabled || !this._scene.activeCamera) { - return false; - } - const emitterPosition = this.getEmitterPosition(); - const direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition); - const distance = direction.length(); - direction.normalize(); - const ray = new ray_Ray(this._scene.activeCamera.globalPosition, direction); - const pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true); - return !pickInfo || !pickInfo.hit || pickInfo.distance > distance; - } - /** - * @internal - */ - render() { - if (!this._scene.activeCamera) { - return false; - } - const engine = this._scene.getEngine(); - const viewport = this._scene.activeCamera.viewport; - const globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true)); - // Position - if (!this.computeEffectivePosition(globalViewport)) { - return false; - } - // Visibility - if (!this._isVisible()) { - return false; - } - // Intensity - let awayX; - let awayY; - if (this._positionX < this.borderLimit + globalViewport.x) { - awayX = this.borderLimit + globalViewport.x - this._positionX; - } - else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) { - awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit; - } - else { - awayX = 0; - } - if (this._positionY < this.borderLimit + globalViewport.y) { - awayY = this.borderLimit + globalViewport.y - this._positionY; - } - else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) { - awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit; - } - else { - awayY = 0; - } - let away = awayX > awayY ? awayX : awayY; - away -= this.viewportBorder; - if (away > this.borderLimit) { - away = this.borderLimit; - } - let intensity = 1.0 - math_scalar_Scalar.Clamp(away / this.borderLimit, 0, 1); - if (intensity < 0) { - return false; - } - if (intensity > 1.0) { - intensity = 1.0; - } - if (this.viewportBorder > 0) { - globalViewport.x += this.viewportBorder; - globalViewport.y += this.viewportBorder; - globalViewport.width -= this.viewportBorder * 2; - globalViewport.height -= this.viewportBorder * 2; - this._positionX -= this.viewportBorder; - this._positionY -= this.viewportBorder; - } - // Position - const centerX = globalViewport.x + globalViewport.width / 2; - const centerY = globalViewport.y + globalViewport.height / 2; - const distX = centerX - this._positionX; - const distY = centerY - this._positionY; - // Effects - engine.setState(false); - engine.setDepthBuffer(false); - // Flares - for (let index = 0; index < this.lensFlares.length; index++) { - const flare = this.lensFlares[index]; - if (!flare._drawWrapper.effect.isReady() || (flare.texture && !flare.texture.isReady())) { - continue; - } - engine.enableEffect(flare._drawWrapper); - engine.bindBuffers(this._vertexBuffers, this._indexBuffer, flare._drawWrapper.effect); - engine.setAlphaMode(flare.alphaMode); - const x = centerX - distX * flare.position; - const y = centerY - distY * flare.position; - const cw = flare.size; - const ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true); - const cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0; - const cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2)); - const viewportMatrix = math_vector_Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1); - flare._drawWrapper.effect.setMatrix("viewportMatrix", viewportMatrix); - // Texture - flare._drawWrapper.effect.setTexture("textureSampler", flare.texture); - // Color - flare._drawWrapper.effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0); - // Draw order - engine.drawElementsType(material_Material.TriangleFillMode, 0, 6); - } - engine.setDepthBuffer(true); - engine.setAlphaMode(0); - return true; - } - /** - * Rebuilds the lens flare system - */ - rebuild() { - var _a; - this._createIndexBuffer(); - for (const key in this._vertexBuffers) { - (_a = this._vertexBuffers[key]) === null || _a === void 0 ? void 0 : _a._rebuild(); - } - } - /** - * Dispose and release the lens flare with its associated resources. - */ - dispose() { - const vertexBuffer = this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - if (vertexBuffer) { - vertexBuffer.dispose(); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = null; - } - if (this._indexBuffer) { - this._scene.getEngine()._releaseBuffer(this._indexBuffer); - this._indexBuffer = null; - } - while (this.lensFlares.length) { - this.lensFlares[0].dispose(); - } - // Remove from scene - const index = this._scene.lensFlareSystems.indexOf(this); - this._scene.lensFlareSystems.splice(index, 1); - } - /** - * Parse a lens flare system from a JSON representation - * @param parsedLensFlareSystem Define the JSON to parse - * @param scene Define the scene the parsed system should be instantiated in - * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures - * @returns the parsed system - */ - static Parse(parsedLensFlareSystem, scene, rootUrl) { - const emitter = scene.getLastEntryById(parsedLensFlareSystem.emitterId); - const name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId; - const lensFlareSystem = new LensFlareSystem(name, emitter, scene); - lensFlareSystem.id = parsedLensFlareSystem.id || name; - lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit; - for (let index = 0; index < parsedLensFlareSystem.flares.length; index++) { - const parsedFlare = parsedLensFlareSystem.flares[index]; - LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, math_color_Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem); - } - return lensFlareSystem; - } - /** - * Serialize the current Lens Flare System into a JSON representation. - * @returns the serialized JSON - */ - serialize() { - const serializationObject = {}; - serializationObject.id = this.id; - serializationObject.name = this.name; - serializationObject.emitterId = this.getEmitter().id; - serializationObject.borderLimit = this.borderLimit; - serializationObject.flares = []; - for (let index = 0; index < this.lensFlares.length; index++) { - const flare = this.lensFlares[index]; - serializationObject.flares.push({ - size: flare.size, - position: flare.position, - color: flare.color.asArray(), - textureName: tools_Tools.GetFilename(flare.texture ? flare.texture.name : ""), - }); - } - return serializationObject; - } -} -/** - * @internal - */ -LensFlareSystem._SceneComponentInitialization = (_) => { - throw _WarnImport("LensFlareSystemSceneComponent"); -}; -//# sourceMappingURL=lensFlareSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/LensFlares/lensFlareSystemSceneComponent.js - - - - -// Adds the parser to the scene parsers. -AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_LENSFLARESYSTEM, (parsedData, scene, container, rootUrl) => { - // Lens flares - if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) { - if (!container.lensFlareSystems) { - container.lensFlareSystems = new Array(); - } - for (let index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) { - const parsedLensFlareSystem = parsedData.lensFlareSystems[index]; - const lf = LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl); - container.lensFlareSystems.push(lf); - } - } -}); -AbstractScene.prototype.getLensFlareSystemByName = function (name) { - for (let index = 0; index < this.lensFlareSystems.length; index++) { - if (this.lensFlareSystems[index].name === name) { - return this.lensFlareSystems[index]; - } - } - return null; -}; -AbstractScene.prototype.getLensFlareSystemById = function (id) { - for (let index = 0; index < this.lensFlareSystems.length; index++) { - if (this.lensFlareSystems[index].id === id) { - return this.lensFlareSystems[index]; - } - } - return null; -}; -AbstractScene.prototype.getLensFlareSystemByID = function (id) { - return this.getLensFlareSystemById(id); -}; -AbstractScene.prototype.removeLensFlareSystem = function (toRemove) { - const index = this.lensFlareSystems.indexOf(toRemove); - if (index !== -1) { - this.lensFlareSystems.splice(index, 1); - } - return index; -}; -AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) { - this.lensFlareSystems.push(newLensFlareSystem); -}; -/** - * Defines the lens flare scene component responsible to manage any lens flares - * in a given scene. - */ -class LensFlareSystemSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_LENSFLARESYSTEM; - this.scene = scene; - scene.lensFlareSystems = new Array(); - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - for (let index = 0; index < this.scene.lensFlareSystems.length; index++) { - this.scene.lensFlareSystems[index].rebuild(); - } - } - /** - * Adds all the elements from the container to the scene - * @param container the container holding the elements - */ - addFromContainer(container) { - if (!container.lensFlareSystems) { - return; - } - container.lensFlareSystems.forEach((o) => { - this.scene.addLensFlareSystem(o); - }); - } - /** - * Removes all the elements in the container from the scene - * @param container contains the elements to remove - * @param dispose if the removed element should be disposed (default: false) - */ - removeFromContainer(container, dispose) { - if (!container.lensFlareSystems) { - return; - } - container.lensFlareSystems.forEach((o) => { - this.scene.removeLensFlareSystem(o); - if (dispose) { - o.dispose(); - } - }); - } - /** - * Serializes the component data to the specified json object - * @param serializationObject The object to serialize to - */ - serialize(serializationObject) { - // Lens flares - serializationObject.lensFlareSystems = []; - const lensFlareSystems = this.scene.lensFlareSystems; - for (const lensFlareSystem of lensFlareSystems) { - serializationObject.lensFlareSystems.push(lensFlareSystem.serialize()); - } - } - /** - * Disposes the component and the associated resources. - */ - dispose() { - const lensFlareSystems = this.scene.lensFlareSystems; - while (lensFlareSystems.length) { - lensFlareSystems[0].dispose(); - } - } - _draw(camera) { - // Lens flares - if (this.scene.lensFlaresEnabled) { - const lensFlareSystems = this.scene.lensFlareSystems; - tools_Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0); - for (const lensFlareSystem of lensFlareSystems) { - if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) { - lensFlareSystem.render(); - } - } - tools_Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0); - } - } -} -LensFlareSystem._SceneComponentInitialization = (scene) => { - let component = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_LENSFLARESYSTEM); - if (!component) { - component = new LensFlareSystemSceneComponent(scene); - scene._addComponent(component); - } -}; -//# sourceMappingURL=lensFlareSystemSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/LensFlares/index.js - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/bayerDitherFunctions.js -// Do not edit. - -const bayerDitherFunctions_name = "bayerDitherFunctions"; -const bayerDitherFunctions_shader = `float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} -float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); -vec2 P2=floor(0.5*mod(_P,4.0)); -return 4.0*bayerDither2(P1)+bayerDither2(P2);} -float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); -vec2 P2=floor(0.5 *mod(_P,4.0)); -vec2 P4=floor(0.25*mod(_P,8.0)); -return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} -`; -// Sideeffect -ShaderStore.IncludesShadersStore[bayerDitherFunctions_name] = bayerDitherFunctions_shader; -/** @internal */ -const bayerDitherFunctions = { name: bayerDitherFunctions_name, shader: bayerDitherFunctions_shader }; -//# sourceMappingURL=bayerDitherFunctions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentExtraDeclaration.js -// Do not edit. - - - -const shadowMapFragmentExtraDeclaration_name = "shadowMapFragmentExtraDeclaration"; -const shadowMapFragmentExtraDeclaration_shader = `#if SM_FLOAT==0 -#include<packingFunctions> -#endif -#if SM_SOFTTRANSPARENTSHADOW==1 -#include<bayerDitherFunctions> -uniform float softTransparentShadowSM; -#endif -varying float vDepthMetricSM; -#if SM_USEDISTANCE==1 -uniform vec3 lightDataSM;varying vec3 vPositionWSM; -#endif -uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -varying float zSM; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[shadowMapFragmentExtraDeclaration_name] = shadowMapFragmentExtraDeclaration_shader; -/** @internal */ -const shadowMapFragmentExtraDeclaration = { name: shadowMapFragmentExtraDeclaration_name, shader: shadowMapFragmentExtraDeclaration_shader }; -//# sourceMappingURL=shadowMapFragmentExtraDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragment.js -// Do not edit. - -const shadowMapFragment_name = "shadowMapFragment"; -const shadowMapFragment_shader = `float depthSM=vDepthMetricSM; -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -#if SM_USEDISTANCE==1 -depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -#ifdef USE_REVERSE_DEPTHBUFFER -depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#endif -#ifdef USE_REVERSE_DEPTHBUFFER -gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); -#else -gl_FragDepth=clamp(depthSM,0.0,1.0); -#endif -#elif SM_USEDISTANCE==1 -depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#if SM_ESM==1 -depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); -#endif -#if SM_FLOAT==1 -gl_FragColor=vec4(depthSM,1.0,1.0,1.0); -#else -gl_FragColor=pack(depthSM); -#endif -return;`; -// Sideeffect -ShaderStore.IncludesShadersStore[shadowMapFragment_name] = shadowMapFragment_shader; -/** @internal */ -const shadowMapFragment = { name: shadowMapFragment_name, shader: shadowMapFragment_shader }; -//# sourceMappingURL=shadowMapFragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/shadowMap.fragment.js -// Do not edit. - - - - - -const shadowMap_fragment_name = "shadowMapPixelShader"; -const shadowMap_fragment_shader = `#include<shadowMapFragmentExtraDeclaration> -#ifdef ALPHATEXTURE -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include<clipPlaneFragmentDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include<clipPlaneFragment> -#ifdef ALPHATEXTURE -float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; -#ifdef ALPHATESTVALUE -if (alphaFromAlphaTexture<ALPHATESTVALUE) -discard; -#endif -#endif -#if SM_SOFTTRANSPARENTSHADOW==1 -#ifdef ALPHATEXTURE -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alphaFromAlphaTexture) discard; -#else -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard; -#endif -#endif -#include<shadowMapFragment> -}`; -// Sideeffect -ShaderStore.ShadersStore[shadowMap_fragment_name] = shadowMap_fragment_shader; -/** @internal */ -const shadowMapPixelShader = { name: shadowMap_fragment_name, shader: shadowMap_fragment_shader }; -//# sourceMappingURL=shadowMap.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneVertexDeclaration.js -// Do not edit. - -const sceneVertexDeclaration_name = "sceneVertexDeclaration"; -const sceneVertexDeclaration_shader = `uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; -`; -// Sideeffect -ShaderStore.IncludesShadersStore[sceneVertexDeclaration_name] = sceneVertexDeclaration_shader; -/** @internal */ -const sceneVertexDeclaration = { name: sceneVertexDeclaration_name, shader: sceneVertexDeclaration_shader }; -//# sourceMappingURL=sceneVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/meshVertexDeclaration.js -// Do not edit. - -const meshVertexDeclaration_name = "meshVertexDeclaration"; -const meshVertexDeclaration_shader = `uniform mat4 world;uniform float visibility; -`; -// Sideeffect -ShaderStore.IncludesShadersStore[meshVertexDeclaration_name] = meshVertexDeclaration_shader; -/** @internal */ -const meshVertexDeclaration = { name: meshVertexDeclaration_name, shader: meshVertexDeclaration_shader }; -//# sourceMappingURL=meshVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexDeclaration.js -// Do not edit. - - - -const shadowMapVertexDeclaration_name = "shadowMapVertexDeclaration"; -const shadowMapVertexDeclaration_shader = `#include<sceneVertexDeclaration> -#include<meshVertexDeclaration> -`; -// Sideeffect -ShaderStore.IncludesShadersStore[shadowMapVertexDeclaration_name] = shadowMapVertexDeclaration_shader; -/** @internal */ -const shadowMapVertexDeclaration = { name: shadowMapVertexDeclaration_name, shader: shadowMapVertexDeclaration_shader }; -//# sourceMappingURL=shadowMapVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapUboDeclaration.js -// Do not edit. - - - -const shadowMapUboDeclaration_name = "shadowMapUboDeclaration"; -const shadowMapUboDeclaration_shader = `layout(std140,column_major) uniform; -#include<sceneUboDeclaration> -#include<meshUboDeclaration> -`; -// Sideeffect -ShaderStore.IncludesShadersStore[shadowMapUboDeclaration_name] = shadowMapUboDeclaration_shader; -/** @internal */ -const shadowMapUboDeclaration = { name: shadowMapUboDeclaration_name, shader: shadowMapUboDeclaration_shader }; -//# sourceMappingURL=shadowMapUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexExtraDeclaration.js -// Do not edit. - -const shadowMapVertexExtraDeclaration_name = "shadowMapVertexExtraDeclaration"; -const shadowMapVertexExtraDeclaration_shader = `#if SM_NORMALBIAS==1 -uniform vec3 lightDataSM; -#endif -uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; -#if SM_USEDISTANCE==1 -varying vec3 vPositionWSM; -#endif -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -varying float zSM; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[shadowMapVertexExtraDeclaration_name] = shadowMapVertexExtraDeclaration_shader; -/** @internal */ -const shadowMapVertexExtraDeclaration = { name: shadowMapVertexExtraDeclaration_name, shader: shadowMapVertexExtraDeclaration_shader }; -//# sourceMappingURL=shadowMapVertexExtraDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexNormalBias.js -// Do not edit. - -const shadowMapVertexNormalBias_name = "shadowMapVertexNormalBias"; -const shadowMapVertexNormalBias_shader = `#if SM_NORMALBIAS==1 -#if SM_DIRECTIONINLIGHTDATA==1 -vec3 worldLightDirSM=normalize(-lightDataSM.xyz); -#else -vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); -#endif -float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[shadowMapVertexNormalBias_name] = shadowMapVertexNormalBias_shader; -/** @internal */ -const shadowMapVertexNormalBias = { name: shadowMapVertexNormalBias_name, shader: shadowMapVertexNormalBias_shader }; -//# sourceMappingURL=shadowMapVertexNormalBias.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexMetric.js -// Do not edit. - -const shadowMapVertexMetric_name = "shadowMapVertexMetric"; -const shadowMapVertexMetric_shader = `#if SM_USEDISTANCE==1 -vPositionWSM=worldPos.xyz; -#endif -#if SM_DEPTHTEXTURE==1 -#ifdef IS_NDC_HALF_ZRANGE -#define BIASFACTOR 0.5 -#else -#define BIASFACTOR 1.0 -#endif -#ifdef USE_REVERSE_DEPTHBUFFER -gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; -#else -gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; -#endif -#endif -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -zSM=gl_Position.z;gl_Position.z=0.0; -#elif SM_USEDISTANCE==0 -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[shadowMapVertexMetric_name] = shadowMapVertexMetric_shader; -/** @internal */ -const shadowMapVertexMetric = { name: shadowMapVertexMetric_name, shader: shadowMapVertexMetric_shader }; -//# sourceMappingURL=shadowMapVertexMetric.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/shadowMap.vertex.js -// Do not edit. - - - - - - - - - - - - - - - - - - -const shadowMap_vertex_name = "shadowMapVertexShader"; -const shadowMap_vertex_shader = `attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#ifdef INSTANCES -attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; -#endif -#include<helperFunctions> -#include<__decl__shadowMapVertex> -#ifdef ALPHATEXTURE -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#include<shadowMapVertexExtraDeclaration> -#include<clipPlaneVertexDeclaration> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef NORMAL -mat3 normWorldSM=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normWorldSM=transposeMat3(inverseMat3(normWorldSM)); -#endif -vec3 vNormalW=normalize(normWorldSM*normalUpdated); -#endif -#endif -#include<shadowMapVertexNormalBias> -gl_Position=viewProjection*worldPos; -#include<shadowMapVertexMetric> -#ifdef ALPHATEXTURE -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#include<clipPlaneVertex> -}`; -// Sideeffect -ShaderStore.ShadersStore[shadowMap_vertex_name] = shadowMap_vertex_shader; -/** @internal */ -const shadowMapVertexShader = { name: shadowMap_vertex_name, shader: shadowMap_vertex_shader }; -//# sourceMappingURL=shadowMap.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/depthBoxBlur.fragment.js -// Do not edit. - -const depthBoxBlur_fragment_name = "depthBoxBlurPixelShader"; -const depthBoxBlur_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) -for (int y=-OFFSET; y<=OFFSET; y++) -colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`; -// Sideeffect -ShaderStore.ShadersStore[depthBoxBlur_fragment_name] = depthBoxBlur_fragment_shader; -/** @internal */ -const depthBoxBlurPixelShader = { name: depthBoxBlur_fragment_name, shader: depthBoxBlur_fragment_shader }; -//# sourceMappingURL=depthBoxBlur.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js -// Do not edit. - -const shadowMapFragmentSoftTransparentShadow_name = "shadowMapFragmentSoftTransparentShadow"; -const shadowMapFragmentSoftTransparentShadow_shader = `#if SM_SOFTTRANSPARENTSHADOW==1 -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[shadowMapFragmentSoftTransparentShadow_name] = shadowMapFragmentSoftTransparentShadow_shader; -/** @internal */ -const shadowMapFragmentSoftTransparentShadow = { name: shadowMapFragmentSoftTransparentShadow_name, shader: shadowMapFragmentSoftTransparentShadow_shader }; -//# sourceMappingURL=shadowMapFragmentSoftTransparentShadow.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/Shadows/shadowGenerator.js - - - - - - - - - - - - - - - - - - - - -/** - * Default implementation IShadowGenerator. - * This is the main object responsible of generating shadows in the framework. - * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows - */ -class shadowGenerator_ShadowGenerator { - /** - * Gets the bias: offset applied on the depth preventing acnea (in light direction). - */ - get bias() { - return this._bias; - } - /** - * Sets the bias: offset applied on the depth preventing acnea (in light direction). - */ - set bias(bias) { - this._bias = bias; - } - /** - * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle). - */ - get normalBias() { - return this._normalBias; - } - /** - * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle). - */ - set normalBias(normalBias) { - this._normalBias = normalBias; - } - /** - * Gets the blur box offset: offset applied during the blur pass. - * Only useful if useKernelBlur = false - */ - get blurBoxOffset() { - return this._blurBoxOffset; - } - /** - * Sets the blur box offset: offset applied during the blur pass. - * Only useful if useKernelBlur = false - */ - set blurBoxOffset(value) { - if (this._blurBoxOffset === value) { - return; - } - this._blurBoxOffset = value; - this._disposeBlurPostProcesses(); - } - /** - * Gets the blur scale: scale of the blurred texture compared to the main shadow map. - * 2 means half of the size. - */ - get blurScale() { - return this._blurScale; - } - /** - * Sets the blur scale: scale of the blurred texture compared to the main shadow map. - * 2 means half of the size. - */ - set blurScale(value) { - if (this._blurScale === value) { - return; - } - this._blurScale = value; - this._disposeBlurPostProcesses(); - } - /** - * Gets the blur kernel: kernel size of the blur pass. - * Only useful if useKernelBlur = true - */ - get blurKernel() { - return this._blurKernel; - } - /** - * Sets the blur kernel: kernel size of the blur pass. - * Only useful if useKernelBlur = true - */ - set blurKernel(value) { - if (this._blurKernel === value) { - return; - } - this._blurKernel = value; - this._disposeBlurPostProcesses(); - } - /** - * Gets whether the blur pass is a kernel blur (if true) or box blur. - * Only useful in filtered mode (useBlurExponentialShadowMap...) - */ - get useKernelBlur() { - return this._useKernelBlur; - } - /** - * Sets whether the blur pass is a kernel blur (if true) or box blur. - * Only useful in filtered mode (useBlurExponentialShadowMap...) - */ - set useKernelBlur(value) { - if (this._useKernelBlur === value) { - return; - } - this._useKernelBlur = value; - this._disposeBlurPostProcesses(); - } - /** - * Gets the depth scale used in ESM mode. - */ - get depthScale() { - return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale(); - } - /** - * Sets the depth scale used in ESM mode. - * This can override the scale stored on the light. - */ - set depthScale(value) { - this._depthScale = value; - } - _validateFilter(filter) { - return filter; - } - /** - * Gets the current mode of the shadow generator (normal, PCF, ESM...). - * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE - */ - get filter() { - return this._filter; - } - /** - * Sets the current mode of the shadow generator (normal, PCF, ESM...). - * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE - */ - set filter(value) { - value = this._validateFilter(value); - // Blurring the cubemap is going to be too expensive. Reverting to unblurred version - if (this._light.needCube()) { - if (value === shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { - this.useExponentialShadowMap = true; - return; - } - else if (value === shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { - this.useCloseExponentialShadowMap = true; - return; - } - // PCF on cubemap would also be expensive - else if (value === shadowGenerator_ShadowGenerator.FILTER_PCF || value === shadowGenerator_ShadowGenerator.FILTER_PCSS) { - this.usePoissonSampling = true; - return; - } - } - // Weblg1 fallback for PCF. - if (value === shadowGenerator_ShadowGenerator.FILTER_PCF || value === shadowGenerator_ShadowGenerator.FILTER_PCSS) { - if (!this._scene.getEngine()._features.supportShadowSamplers) { - this.usePoissonSampling = true; - return; - } - } - if (this._filter === value) { - return; - } - this._filter = value; - this._disposeBlurPostProcesses(); - this._applyFilterValues(); - this._light._markMeshesAsLightDirty(); - } - /** - * Gets if the current filter is set to Poisson Sampling. - */ - get usePoissonSampling() { - return this.filter === shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING; - } - /** - * Sets the current filter to Poisson Sampling. - */ - set usePoissonSampling(value) { - const filter = this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING); - if (!value && this.filter !== shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING) { - return; - } - this.filter = value ? filter : shadowGenerator_ShadowGenerator.FILTER_NONE; - } - /** - * Gets if the current filter is set to ESM. - */ - get useExponentialShadowMap() { - return this.filter === shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP; - } - /** - * Sets the current filter is to ESM. - */ - set useExponentialShadowMap(value) { - const filter = this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP); - if (!value && this.filter !== shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) { - return; - } - this.filter = value ? filter : shadowGenerator_ShadowGenerator.FILTER_NONE; - } - /** - * Gets if the current filter is set to filtered ESM. - */ - get useBlurExponentialShadowMap() { - return this.filter === shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP; - } - /** - * Gets if the current filter is set to filtered ESM. - */ - set useBlurExponentialShadowMap(value) { - const filter = this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP); - if (!value && this.filter !== shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { - return; - } - this.filter = value ? filter : shadowGenerator_ShadowGenerator.FILTER_NONE; - } - /** - * Gets if the current filter is set to "close ESM" (using the inverse of the - * exponential to prevent steep falloff artifacts). - */ - get useCloseExponentialShadowMap() { - return this.filter === shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP; - } - /** - * Sets the current filter to "close ESM" (using the inverse of the - * exponential to prevent steep falloff artifacts). - */ - set useCloseExponentialShadowMap(value) { - const filter = this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP); - if (!value && this.filter !== shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) { - return; - } - this.filter = value ? filter : shadowGenerator_ShadowGenerator.FILTER_NONE; - } - /** - * Gets if the current filter is set to filtered "close ESM" (using the inverse of the - * exponential to prevent steep falloff artifacts). - */ - get useBlurCloseExponentialShadowMap() { - return this.filter === shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP; - } - /** - * Sets the current filter to filtered "close ESM" (using the inverse of the - * exponential to prevent steep falloff artifacts). - */ - set useBlurCloseExponentialShadowMap(value) { - const filter = this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP); - if (!value && this.filter !== shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { - return; - } - this.filter = value ? filter : shadowGenerator_ShadowGenerator.FILTER_NONE; - } - /** - * Gets if the current filter is set to "PCF" (percentage closer filtering). - */ - get usePercentageCloserFiltering() { - return this.filter === shadowGenerator_ShadowGenerator.FILTER_PCF; - } - /** - * Sets the current filter to "PCF" (percentage closer filtering). - */ - set usePercentageCloserFiltering(value) { - const filter = this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_PCF); - if (!value && this.filter !== shadowGenerator_ShadowGenerator.FILTER_PCF) { - return; - } - this.filter = value ? filter : shadowGenerator_ShadowGenerator.FILTER_NONE; - } - /** - * Gets the PCF or PCSS Quality. - * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. - */ - get filteringQuality() { - return this._filteringQuality; - } - /** - * Sets the PCF or PCSS Quality. - * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. - */ - set filteringQuality(filteringQuality) { - if (this._filteringQuality === filteringQuality) { - return; - } - this._filteringQuality = filteringQuality; - this._disposeBlurPostProcesses(); - this._applyFilterValues(); - this._light._markMeshesAsLightDirty(); - } - /** - * Gets if the current filter is set to "PCSS" (contact hardening). - */ - get useContactHardeningShadow() { - return this.filter === shadowGenerator_ShadowGenerator.FILTER_PCSS; - } - /** - * Sets the current filter to "PCSS" (contact hardening). - */ - set useContactHardeningShadow(value) { - const filter = this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_PCSS); - if (!value && this.filter !== shadowGenerator_ShadowGenerator.FILTER_PCSS) { - return; - } - this.filter = value ? filter : shadowGenerator_ShadowGenerator.FILTER_NONE; - } - /** - * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. - * Using a ratio helps keeping shape stability independently of the map size. - * - * It does not account for the light projection as it was having too much - * instability during the light setup or during light position changes. - * - * Only valid if useContactHardeningShadow is true. - */ - get contactHardeningLightSizeUVRatio() { - return this._contactHardeningLightSizeUVRatio; - } - /** - * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size. - * Using a ratio helps keeping shape stability independently of the map size. - * - * It does not account for the light projection as it was having too much - * instability during the light setup or during light position changes. - * - * Only valid if useContactHardeningShadow is true. - */ - set contactHardeningLightSizeUVRatio(contactHardeningLightSizeUVRatio) { - this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio; - } - /** Gets or sets the actual darkness of a shadow */ - get darkness() { - return this._darkness; - } - set darkness(value) { - this.setDarkness(value); - } - /** - * Returns the darkness value (float). This can only decrease the actual darkness of a shadow. - * 0 means strongest and 1 would means no shadow. - * @returns the darkness. - */ - getDarkness() { - return this._darkness; - } - /** - * Sets the darkness value (float). This can only decrease the actual darkness of a shadow. - * @param darkness The darkness value 0 means strongest and 1 would means no shadow. - * @returns the shadow generator allowing fluent coding. - */ - setDarkness(darkness) { - if (darkness >= 1.0) { - this._darkness = 1.0; - } - else if (darkness <= 0.0) { - this._darkness = 0.0; - } - else { - this._darkness = darkness; - } - return this; - } - /** Gets or sets the ability to have transparent shadow */ - get transparencyShadow() { - return this._transparencyShadow; - } - set transparencyShadow(value) { - this.setTransparencyShadow(value); - } - /** - * Sets the ability to have transparent shadow (boolean). - * @param transparent True if transparent else False - * @returns the shadow generator allowing fluent coding - */ - setTransparencyShadow(transparent) { - this._transparencyShadow = transparent; - return this; - } - /** - * Gets the main RTT containing the shadow map (usually storing depth from the light point of view). - * @returns The render target texture if present otherwise, null - */ - getShadowMap() { - return this._shadowMap; - } - /** - * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself). - * @returns The render target texture if the shadow map is present otherwise, null - */ - getShadowMapForRendering() { - if (this._shadowMap2) { - return this._shadowMap2; - } - return this._shadowMap; - } - /** - * Gets the class name of that object - * @returns "ShadowGenerator" - */ - getClassName() { - return shadowGenerator_ShadowGenerator.CLASSNAME; - } - /** - * Helper function to add a mesh and its descendants to the list of shadow casters. - * @param mesh Mesh to add - * @param includeDescendants boolean indicating if the descendants should be added. Default to true - * @returns the Shadow Generator itself - */ - addShadowCaster(mesh, includeDescendants = true) { - if (!this._shadowMap) { - return this; - } - if (!this._shadowMap.renderList) { - this._shadowMap.renderList = []; - } - if (this._shadowMap.renderList.indexOf(mesh) === -1) { - this._shadowMap.renderList.push(mesh); - } - if (includeDescendants) { - for (const childMesh of mesh.getChildMeshes()) { - if (this._shadowMap.renderList.indexOf(childMesh) === -1) { - this._shadowMap.renderList.push(childMesh); - } - } - } - return this; - } - /** - * Helper function to remove a mesh and its descendants from the list of shadow casters - * @param mesh Mesh to remove - * @param includeDescendants boolean indicating if the descendants should be removed. Default to true - * @returns the Shadow Generator itself - */ - removeShadowCaster(mesh, includeDescendants = true) { - if (!this._shadowMap || !this._shadowMap.renderList) { - return this; - } - const index = this._shadowMap.renderList.indexOf(mesh); - if (index !== -1) { - this._shadowMap.renderList.splice(index, 1); - } - if (includeDescendants) { - for (const child of mesh.getChildren()) { - this.removeShadowCaster(child); - } - } - return this; - } - /** - * Returns the associated light object. - * @returns the light generating the shadow - */ - getLight() { - return this._light; - } - _getCamera() { - var _a; - return (_a = this._camera) !== null && _a !== void 0 ? _a : this._scene.activeCamera; - } - /** - * Gets or sets the size of the texture what stores the shadows - */ - get mapSize() { - return this._mapSize; - } - set mapSize(size) { - this._mapSize = size; - this._light._markMeshesAsLightDirty(); - this.recreateShadowMap(); - } - /** - * Creates a ShadowGenerator object. - * A ShadowGenerator is the required tool to use the shadows. - * Each light casting shadows needs to use its own ShadowGenerator. - * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows - * @param mapSize The size of the texture what stores the shadows. Example : 1024. - * @param light The light object generating the shadows. - * @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. - * @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 - * @param useRedTextureType Forces the generator to use a Red instead of a RGBA type for the shadow map texture format (default: false) - */ - constructor(mapSize, light, usefullFloatFirst, camera, useRedTextureType) { - /** - * Observable triggered before the shadow is rendered. Can be used to update internal effect state - */ - this.onBeforeShadowMapRenderObservable = new observable_Observable(); - /** - * Observable triggered after the shadow is rendered. Can be used to restore internal effect state - */ - this.onAfterShadowMapRenderObservable = new observable_Observable(); - /** - * Observable triggered before a mesh is rendered in the shadow map. - * Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable) - */ - this.onBeforeShadowMapRenderMeshObservable = new observable_Observable(); - /** - * Observable triggered after a mesh is rendered in the shadow map. - * Can be used to update internal effect state (that you can get from the onAfterShadowMapRenderObservable) - */ - this.onAfterShadowMapRenderMeshObservable = new observable_Observable(); - this._bias = 0.00005; - this._normalBias = 0; - this._blurBoxOffset = 1; - this._blurScale = 2; - this._blurKernel = 1; - this._useKernelBlur = false; - this._filter = shadowGenerator_ShadowGenerator.FILTER_NONE; - this._filteringQuality = shadowGenerator_ShadowGenerator.QUALITY_HIGH; - this._contactHardeningLightSizeUVRatio = 0.1; - this._darkness = 0; - this._transparencyShadow = false; - /** - * Enables or disables shadows with varying strength based on the transparency - * When it is enabled, the strength of the shadow is taken equal to mesh.visibility - * If you enabled an alpha texture on your material, the alpha value red from the texture is also combined to compute the strength: - * mesh.visibility * alphaTexture.a - * The texture used is the diffuse by default, but it can be set to the opacity by setting useOpacityTextureForTransparentShadow - * Note that by definition transparencyShadow must be set to true for enableSoftTransparentShadow to work! - */ - this.enableSoftTransparentShadow = false; - /** - * If this is true, use the opacity texture's alpha channel for transparent shadows instead of the diffuse one - */ - this.useOpacityTextureForTransparentShadow = false; - /** - * Controls the extent to which the shadows fade out at the edge of the frustum - */ - this.frustumEdgeFalloff = 0; - /** - * If true the shadow map is generated by rendering the back face of the mesh instead of the front face. - * This can help with self-shadowing as the geometry making up the back of objects is slightly offset. - * It might on the other hand introduce peter panning. - */ - this.forceBackFacesOnly = false; - this._lightDirection = math_vector_Vector3.Zero(); - this._viewMatrix = math_vector_Matrix.Zero(); - this._projectionMatrix = math_vector_Matrix.Zero(); - this._transformMatrix = math_vector_Matrix.Zero(); - this._cachedPosition = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - this._cachedDirection = new math_vector_Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - this._currentFaceIndex = 0; - this._currentFaceIndexCache = 0; - this._defaultTextureMatrix = math_vector_Matrix.Identity(); - this._mapSize = mapSize; - this._light = light; - this._scene = light.getScene(); - this._camera = camera !== null && camera !== void 0 ? camera : null; - this._useRedTextureType = !!useRedTextureType; - let shadowGenerators = light._shadowGenerators; - if (!shadowGenerators) { - shadowGenerators = light._shadowGenerators = new Map(); - } - shadowGenerators.set(this._camera, this); - this.id = light.id; - this._useUBO = this._scene.getEngine().supportsUniformBuffers; - if (this._useUBO) { - this._sceneUBOs = []; - this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`)); - } - shadowGenerator_ShadowGenerator._SceneComponentInitialization(this._scene); - // Texture type fallback from float to int if not supported. - const caps = this._scene.getEngine().getCaps(); - if (!usefullFloatFirst) { - if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { - this._textureType = 2; - } - else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { - this._textureType = 1; - } - else { - this._textureType = 0; - } - } - else { - if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { - this._textureType = 1; - } - else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { - this._textureType = 2; - } - else { - this._textureType = 0; - } - } - this._initializeGenerator(); - this._applyFilterValues(); - } - _initializeGenerator() { - this._light._markMeshesAsLightDirty(); - this._initializeShadowMap(); - } - _createTargetRenderTexture() { - const engine = this._scene.getEngine(); - if (engine._features.supportDepthStencilTexture) { - this._shadowMap = new renderTargetTexture_RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false, undefined, this._useRedTextureType ? 6 : 5); - this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true); - } - else { - this._shadowMap = new renderTargetTexture_RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube()); - } - this._shadowMap.noPrePassRenderer = true; - } - _initializeShadowMap() { - this._createTargetRenderTexture(); - if (this._shadowMap === null) { - return; - } - this._shadowMap.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._shadowMap.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._shadowMap.anisotropicFilteringLevel = 1; - this._shadowMap.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE); - this._shadowMap.renderParticles = false; - this._shadowMap.ignoreCameraViewport = true; - if (this._storedUniqueId) { - this._shadowMap.uniqueId = this._storedUniqueId; - } - // Custom render function. - this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this); - // Force the mesh is ready function to true as we are double checking it - // in the custom render function. Also it prevents side effects and useless - // shader variations in DEPTHPREPASS mode. - this._shadowMap.customIsReadyFunction = () => { - return true; - }; - const engine = this._scene.getEngine(); - this._shadowMap.onBeforeBindObservable.add(() => { - var _a; - this._currentSceneUBO = this._scene.getSceneUniformBuffer(); - (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `shadow map generation for pass id ${engine.currentRenderPassId}`, 1); - }); - // Record Face Index before render. - this._shadowMap.onBeforeRenderObservable.add((faceIndex) => { - if (this._sceneUBOs) { - this._scene.setSceneUniformBuffer(this._sceneUBOs[0]); - } - this._currentFaceIndex = faceIndex; - if (this._filter === shadowGenerator_ShadowGenerator.FILTER_PCF) { - engine.setColorWrite(false); - } - this.getTransformMatrix(); // generate the view/projection matrix - this._scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix); - if (this._useUBO) { - this._scene.getSceneUniformBuffer().unbindEffect(); - this._scene.finalizeSceneUbo(); - } - }); - // Blur if required after render. - this._shadowMap.onAfterUnbindObservable.add(() => { - var _a, _b; - if (this._sceneUBOs) { - this._scene.setSceneUniformBuffer(this._currentSceneUBO); - } - this._scene.updateTransformMatrix(); // restore the view/projection matrices of the active camera - if (this._filter === shadowGenerator_ShadowGenerator.FILTER_PCF) { - engine.setColorWrite(true); - } - if (!this.useBlurExponentialShadowMap && !this.useBlurCloseExponentialShadowMap) { - (_a = engine._debugPopGroup) === null || _a === void 0 ? void 0 : _a.call(engine, 1); - return; - } - const shadowMap = this.getShadowMapForRendering(); - if (shadowMap) { - this._scene.postProcessManager.directRender(this._blurPostProcesses, shadowMap.renderTarget, true); - engine.unBindFramebuffer(shadowMap.renderTarget, true); - (_b = engine._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(engine, 1); - } - }); - // Clear according to the chosen filter. - const clearZero = new math_color_Color4(0, 0, 0, 0); - const clearOne = new math_color_Color4(1.0, 1.0, 1.0, 1.0); - this._shadowMap.onClearObservable.add((engine) => { - if (this._filter === shadowGenerator_ShadowGenerator.FILTER_PCF) { - engine.clear(clearOne, false, true, false); - } - else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { - engine.clear(clearZero, true, true, false); - } - else { - engine.clear(clearOne, true, true, false); - } - }); - // Recreate on resize. - this._shadowMap.onResizeObservable.add((rtt) => { - this._storedUniqueId = this._shadowMap.uniqueId; - this._mapSize = rtt.getRenderSize(); - this._light._markMeshesAsLightDirty(); - this.recreateShadowMap(); - }); - // Ensures rendering groupids do not erase the depth buffer - // or we would lose the shadows information. - for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) { - this._shadowMap.setRenderingAutoClearDepthStencil(i, false); - } - } - _initializeBlurRTTAndPostProcesses() { - const engine = this._scene.getEngine(); - const targetSize = this._mapSize / this.blurScale; - if (!this.useKernelBlur || this.blurScale !== 1.0) { - this._shadowMap2 = new renderTargetTexture_RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType, undefined, undefined, false); - this._shadowMap2.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._shadowMap2.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._shadowMap2.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE); - } - if (this.useKernelBlur) { - this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + "KernelBlurX", new math_vector_Vector2(1, 0), this.blurKernel, 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType); - this._kernelBlurXPostprocess.width = targetSize; - this._kernelBlurXPostprocess.height = targetSize; - this._kernelBlurXPostprocess.externalTextureSamplerBinding = true; - this._kernelBlurXPostprocess.onApplyObservable.add((effect) => { - effect.setTexture("textureSampler", this._shadowMap); - }); - this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + "KernelBlurY", new math_vector_Vector2(0, 1), this.blurKernel, 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType); - this._kernelBlurXPostprocess.autoClear = false; - this._kernelBlurYPostprocess.autoClear = false; - if (this._textureType === 0) { - this._kernelBlurXPostprocess.packedFloat = true; - this._kernelBlurYPostprocess.packedFloat = true; - } - this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess]; - } - else { - this._boxBlurPostprocess = new postProcess_PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType); - this._boxBlurPostprocess.externalTextureSamplerBinding = true; - this._boxBlurPostprocess.onApplyObservable.add((effect) => { - effect.setFloat2("screenSize", targetSize, targetSize); - effect.setTexture("textureSampler", this._shadowMap); - }); - this._boxBlurPostprocess.autoClear = false; - this._blurPostProcesses = [this._boxBlurPostprocess]; - } - } - _renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { - let index; - if (depthOnlySubMeshes.length) { - for (index = 0; index < depthOnlySubMeshes.length; index++) { - this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]); - } - } - for (index = 0; index < opaqueSubMeshes.length; index++) { - this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]); - } - for (index = 0; index < alphaTestSubMeshes.length; index++) { - this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]); - } - if (this._transparencyShadow) { - for (index = 0; index < transparentSubMeshes.length; index++) { - this._renderSubMeshForShadowMap(transparentSubMeshes.data[index], true); - } - } - else { - for (index = 0; index < transparentSubMeshes.length; index++) { - transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false; - } - } - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, mesh) { - effect.setMatrix("viewProjection", this.getTransformMatrix()); - } - _renderSubMeshForShadowMap(subMesh, isTransparent = false) { - var _a, _b; - const renderingMesh = subMesh.getRenderingMesh(); - const effectiveMesh = subMesh.getEffectiveMesh(); - const scene = this._scene; - const engine = scene.getEngine(); - const material = subMesh.getMaterial(); - effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; - if (!material || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) { - return; - } - // Culling - const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0; - let sideOrientation = (_a = renderingMesh.overrideMaterialSideOrientation) !== null && _a !== void 0 ? _a : material.sideOrientation; - if (detNeg) { - sideOrientation = - sideOrientation === 0 ? 1 : 0; - } - const reverseSideOrientation = sideOrientation === 0; - engine.setState(material.backFaceCulling, undefined, undefined, reverseSideOrientation, material.cullBackFaces); - // Managing instances - const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); - if (batch.mustReturn) { - return; - } - const hardwareInstancedRendering = engine.getCaps().instancedArrays && - ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances); - if (this.customAllowRendering && !this.customAllowRendering(subMesh)) { - return; - } - if (this.isReady(subMesh, hardwareInstancedRendering, isTransparent)) { - subMesh._renderId = scene.getRenderId(); - const shadowDepthWrapper = material.shadowDepthWrapper; - const drawWrapper = (_b = shadowDepthWrapper === null || shadowDepthWrapper === void 0 ? void 0 : shadowDepthWrapper.getEffect(subMesh, this, engine.currentRenderPassId)) !== null && _b !== void 0 ? _b : subMesh._getDrawWrapper(); - const effect = drawWrapper_DrawWrapper.GetEffect(drawWrapper); - engine.enableEffect(drawWrapper); - if (!hardwareInstancedRendering) { - renderingMesh._bind(subMesh, effect, material.fillMode); - } - this.getTransformMatrix(); // make sure _cachedDirection et _cachedPosition are up to date - effect.setFloat3("biasAndScaleSM", this.bias, this.normalBias, this.depthScale); - if (this.getLight().getTypeID() === light_Light.LIGHTTYPEID_DIRECTIONALLIGHT) { - effect.setVector3("lightDataSM", this._cachedDirection); - } - else { - effect.setVector3("lightDataSM", this._cachedPosition); - } - const camera = this._getCamera(); - if (camera) { - effect.setFloat2("depthValuesSM", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera)); - } - if (isTransparent && this.enableSoftTransparentShadow) { - effect.setFloat("softTransparentShadowSM", effectiveMesh.visibility * material.alpha); - } - if (shadowDepthWrapper) { - subMesh._setMainDrawWrapperOverride(drawWrapper); - if (shadowDepthWrapper.standalone) { - shadowDepthWrapper.baseMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh); - } - else { - material.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh); - } - subMesh._setMainDrawWrapperOverride(null); - } - else { - // Alpha test - if (this._opacityTexture) { - effect.setTexture("diffuseSampler", this._opacityTexture); - effect.setMatrix("diffuseMatrix", this._opacityTexture.getTextureMatrix() || this._defaultTextureMatrix); - } - // Bones - if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { - const skeleton = renderingMesh.skeleton; - if (skeleton.isUsingTextureForMatrices) { - const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh); - if (!boneTexture) { - return; - } - effect.setTexture("boneSampler", boneTexture); - effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); - } - else { - effect.setMatrices("mBones", skeleton.getTransformMatrices(renderingMesh)); - } - } - // Morph targets - MaterialHelper.BindMorphTargetParameters(renderingMesh, effect); - if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { - renderingMesh.morphTargetManager._bind(effect); - } - // Clip planes - bindClipPlane(effect, material, scene); - } - if (!this._useUBO && !shadowDepthWrapper) { - this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, effectiveMesh); - } - MaterialHelper.BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer()); - this._scene.getSceneUniformBuffer().bindUniformBuffer(); - const world = effectiveMesh.getWorldMatrix(); - // In the non hardware instanced mode, the Mesh ubo update is done by the callback passed to renderingMesh._processRendering (see below) - if (hardwareInstancedRendering) { - effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); - effectiveMesh.transferToEffect(world); - } - if (this.forceBackFacesOnly) { - engine.setState(true, 0, false, true, material.cullBackFaces); - } - // Observables - this.onBeforeShadowMapRenderMeshObservable.notifyObservers(renderingMesh); - this.onBeforeShadowMapRenderObservable.notifyObservers(effect); - // Draw - renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, worldOverride) => { - if (effectiveMesh !== renderingMesh && !isInstance) { - renderingMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); - renderingMesh.transferToEffect(worldOverride); - } - else { - effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); - effectiveMesh.transferToEffect(isInstance ? worldOverride : world); - } - }); - if (this.forceBackFacesOnly) { - engine.setState(true, 0, false, false, material.cullBackFaces); - } - // Observables - this.onAfterShadowMapRenderObservable.notifyObservers(effect); - this.onAfterShadowMapRenderMeshObservable.notifyObservers(renderingMesh); - } - else { - // Need to reset refresh rate of the shadowMap - if (this._shadowMap) { - this._shadowMap.resetRefreshCounter(); - } - } - } - _applyFilterValues() { - if (!this._shadowMap) { - return; - } - if (this.filter === shadowGenerator_ShadowGenerator.FILTER_NONE || this.filter === shadowGenerator_ShadowGenerator.FILTER_PCSS) { - this._shadowMap.updateSamplingMode(texture_Texture.NEAREST_SAMPLINGMODE); - } - else { - this._shadowMap.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE); - } - } - /** - * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects. - * @param onCompiled Callback triggered at the and of the effects compilation - * @param options Sets of optional options forcing the compilation with different modes - */ - forceCompilation(onCompiled, options) { - const localOptions = Object.assign({ useInstances: false }, options); - const shadowMap = this.getShadowMap(); - if (!shadowMap) { - if (onCompiled) { - onCompiled(this); - } - return; - } - const renderList = shadowMap.renderList; - if (!renderList) { - if (onCompiled) { - onCompiled(this); - } - return; - } - const subMeshes = new Array(); - for (const mesh of renderList) { - subMeshes.push(...mesh.subMeshes); - } - if (subMeshes.length === 0) { - if (onCompiled) { - onCompiled(this); - } - return; - } - let currentIndex = 0; - const checkReady = () => { - var _a, _b; - if (!this._scene || !this._scene.getEngine()) { - return; - } - 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)) { - currentIndex++; - if (currentIndex >= subMeshes.length) { - if (onCompiled) { - onCompiled(this); - } - return; - } - } - setTimeout(checkReady, 16); - }; - checkReady(); - } - /** - * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects. - * @param options Sets of optional options forcing the compilation with different modes - * @returns A promise that resolves when the compilation completes - */ - forceCompilationAsync(options) { - return new Promise((resolve) => { - this.forceCompilation(() => { - resolve(); - }, options); - }); - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _isReadyCustomDefines(defines, subMesh, useInstances) { } - _prepareShadowDefines(subMesh, useInstances, defines, isTransparent) { - defines.push("#define SM_LIGHTTYPE_" + this._light.getClassName().toUpperCase()); - defines.push("#define SM_FLOAT " + (this._textureType !== 0 ? "1" : "0")); - defines.push("#define SM_ESM " + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? "1" : "0")); - defines.push("#define SM_DEPTHTEXTURE " + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? "1" : "0")); - const mesh = subMesh.getMesh(); - // Normal bias. - defines.push("#define SM_NORMALBIAS " + (this.normalBias && mesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind) ? "1" : "0")); - defines.push("#define SM_DIRECTIONINLIGHTDATA " + (this.getLight().getTypeID() === light_Light.LIGHTTYPEID_DIRECTIONALLIGHT ? "1" : "0")); - // Point light - defines.push("#define SM_USEDISTANCE " + (this._light.needCube() ? "1" : "0")); - // Soft transparent shadows - defines.push("#define SM_SOFTTRANSPARENTSHADOW " + (this.enableSoftTransparentShadow && isTransparent ? "1" : "0")); - this._isReadyCustomDefines(defines, subMesh, useInstances); - return defines; - } - /** - * Determine whether the shadow generator is ready or not (mainly all effects and related post processes needs to be ready). - * @param subMesh The submesh we want to render in the shadow map - * @param useInstances Defines whether will draw in the map using instances - * @param isTransparent Indicates that isReady is called for a transparent subMesh - * @returns true if ready otherwise, false - */ - isReady(subMesh, useInstances, isTransparent) { - var _a; - const material = subMesh.getMaterial(), shadowDepthWrapper = material === null || material === void 0 ? void 0 : material.shadowDepthWrapper; - this._opacityTexture = null; - if (!material) { - return false; - } - const defines = []; - this._prepareShadowDefines(subMesh, useInstances, defines, isTransparent); - if (shadowDepthWrapper) { - if (!shadowDepthWrapper.isReadyForSubMesh(subMesh, defines, this, useInstances, this._scene.getEngine().currentRenderPassId)) { - return false; - } - } - else { - const subMeshEffect = subMesh._getDrawWrapper(undefined, true); - let effect = subMeshEffect.effect; - let cachedDefines = subMeshEffect.defines; - const attribs = [buffer_VertexBuffer.PositionKind]; - const mesh = subMesh.getMesh(); - // Normal bias. - if (this.normalBias && mesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)) { - attribs.push(buffer_VertexBuffer.NormalKind); - defines.push("#define NORMAL"); - if (mesh.nonUniformScaling) { - defines.push("#define NONUNIFORMSCALING"); - } - } - // Alpha test - const needAlphaTesting = material.needAlphaTesting(); - if (needAlphaTesting || material.needAlphaBlending()) { - if (this.useOpacityTextureForTransparentShadow) { - this._opacityTexture = material.opacityTexture; - } - else { - this._opacityTexture = material.getAlphaTestTexture(); - } - if (this._opacityTexture) { - if (!this._opacityTexture.isReady()) { - return false; - } - const alphaCutOff = (_a = material.alphaCutOff) !== null && _a !== void 0 ? _a : shadowGenerator_ShadowGenerator.DEFAULT_ALPHA_CUTOFF; - defines.push("#define ALPHATEXTURE"); - if (needAlphaTesting) { - defines.push(`#define ALPHATESTVALUE ${alphaCutOff}${alphaCutOff % 1 === 0 ? "." : ""}`); - } - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - attribs.push(buffer_VertexBuffer.UVKind); - defines.push("#define UV1"); - } - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)) { - if (this._opacityTexture.coordinatesIndex === 1) { - attribs.push(buffer_VertexBuffer.UV2Kind); - defines.push("#define UV2"); - } - } - } - } - // Bones - const fallbacks = new EffectFallbacks(); - if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { - attribs.push(buffer_VertexBuffer.MatricesIndicesKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsKind); - if (mesh.numBoneInfluencers > 4) { - attribs.push(buffer_VertexBuffer.MatricesIndicesExtraKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsExtraKind); - } - const skeleton = mesh.skeleton; - defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); - if (mesh.numBoneInfluencers > 0) { - fallbacks.addCPUSkinningFallback(0, mesh); - } - if (skeleton.isUsingTextureForMatrices) { - defines.push("#define BONETEXTURE"); - } - else { - defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); - } - } - else { - defines.push("#define NUM_BONE_INFLUENCERS 0"); - } - // Morph targets - const manager = mesh.morphTargetManager; - let morphInfluencers = 0; - if (manager) { - if (manager.numInfluencers > 0) { - defines.push("#define MORPHTARGETS"); - morphInfluencers = manager.numInfluencers; - defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers); - if (manager.isUsingTextureForTargets) { - defines.push("#define MORPHTARGETS_TEXTURE"); - } - MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers); - } - } - // ClipPlanes - prepareStringDefinesForClipPlanes(material, this._scene, defines); - // Instances - if (useInstances) { - defines.push("#define INSTANCES"); - MaterialHelper.PushAttributesForInstances(attribs); - if (subMesh.getRenderingMesh().hasThinInstances) { - defines.push("#define THIN_INSTANCES"); - } - } - if (this.customShaderOptions) { - if (this.customShaderOptions.defines) { - for (const define of this.customShaderOptions.defines) { - if (defines.indexOf(define) === -1) { - defines.push(define); - } - } - } - } - // Get correct effect - const join = defines.join("\n"); - if (cachedDefines !== join) { - cachedDefines = join; - let shaderName = "shadowMap"; - const uniforms = [ - "world", - "mBones", - "viewProjection", - "diffuseMatrix", - "lightDataSM", - "depthValuesSM", - "biasAndScaleSM", - "morphTargetInfluences", - "boneTextureWidth", - "softTransparentShadowSM", - "morphTargetTextureInfo", - "morphTargetTextureIndices", - ]; - const samplers = ["diffuseSampler", "boneSampler", "morphTargets"]; - const uniformBuffers = ["Scene", "Mesh"]; - addClipPlaneUniforms(uniforms); - // Custom shader? - if (this.customShaderOptions) { - shaderName = this.customShaderOptions.shaderName; - if (this.customShaderOptions.attributes) { - for (const attrib of this.customShaderOptions.attributes) { - if (attribs.indexOf(attrib) === -1) { - attribs.push(attrib); - } - } - } - if (this.customShaderOptions.uniforms) { - for (const uniform of this.customShaderOptions.uniforms) { - if (uniforms.indexOf(uniform) === -1) { - uniforms.push(uniform); - } - } - } - if (this.customShaderOptions.samplers) { - for (const sampler of this.customShaderOptions.samplers) { - if (samplers.indexOf(sampler) === -1) { - samplers.push(sampler); - } - } - } - } - const engine = this._scene.getEngine(); - effect = engine.createEffect(shaderName, { - attributes: attribs, - uniformsNames: uniforms, - uniformBuffersNames: uniformBuffers, - samplers: samplers, - defines: join, - fallbacks: fallbacks, - onCompiled: null, - onError: null, - indexParameters: { maxSimultaneousMorphTargets: morphInfluencers }, - }, engine); - subMeshEffect.setEffect(effect, cachedDefines); - } - if (!effect.isReady()) { - return false; - } - } - if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) { - if (!this._blurPostProcesses || !this._blurPostProcesses.length) { - this._initializeBlurRTTAndPostProcesses(); - } - } - if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) { - return false; - } - if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) { - return false; - } - if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) { - return false; - } - return true; - } - /** - * Prepare all the defines in a material relying on a shadow map at the specified light index. - * @param defines Defines of the material we want to update - * @param lightIndex Index of the light in the enabled light list of the material - */ - prepareDefines(defines, lightIndex) { - const scene = this._scene; - const light = this._light; - if (!scene.shadowsEnabled || !light.shadowEnabled) { - return; - } - defines["SHADOW" + lightIndex] = true; - if (this.useContactHardeningShadow) { - defines["SHADOWPCSS" + lightIndex] = true; - if (this._filteringQuality === shadowGenerator_ShadowGenerator.QUALITY_LOW) { - defines["SHADOWLOWQUALITY" + lightIndex] = true; - } - else if (this._filteringQuality === shadowGenerator_ShadowGenerator.QUALITY_MEDIUM) { - defines["SHADOWMEDIUMQUALITY" + lightIndex] = true; - } - // else default to high. - } - else if (this.usePercentageCloserFiltering) { - defines["SHADOWPCF" + lightIndex] = true; - if (this._filteringQuality === shadowGenerator_ShadowGenerator.QUALITY_LOW) { - defines["SHADOWLOWQUALITY" + lightIndex] = true; - } - else if (this._filteringQuality === shadowGenerator_ShadowGenerator.QUALITY_MEDIUM) { - defines["SHADOWMEDIUMQUALITY" + lightIndex] = true; - } - // else default to high. - } - else if (this.usePoissonSampling) { - defines["SHADOWPOISSON" + lightIndex] = true; - } - else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { - defines["SHADOWESM" + lightIndex] = true; - } - else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) { - defines["SHADOWCLOSEESM" + lightIndex] = true; - } - if (light.needCube()) { - defines["SHADOWCUBE" + lightIndex] = true; - } - } - /** - * Binds the shadow related information inside of an effect (information like near, far, darkness... - * defined in the generator but impacting the effect). - * @param lightIndex Index of the light in the enabled light list of the material owning the effect - * @param effect The effect we are binding the information for - */ - bindShadowLight(lightIndex, effect) { - const light = this._light; - const scene = this._scene; - if (!scene.shadowsEnabled || !light.shadowEnabled) { - return; - } - const camera = this._getCamera(); - if (!camera) { - return; - } - const shadowMap = this.getShadowMap(); - if (!shadowMap) { - return; - } - if (!light.needCube()) { - effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix()); - } - // Only PCF uses depth stencil texture. - if (this._filter === shadowGenerator_ShadowGenerator.FILTER_PCF) { - effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering()); - light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex); - } - else if (this._filter === shadowGenerator_ShadowGenerator.FILTER_PCSS) { - effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering()); - effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering()); - light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex); - } - else { - effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering()); - light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex); - } - light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex); - } - /** - * Gets the transformation matrix used to project the meshes into the map from the light point of view. - * (eq to shadow projection matrix * light transform matrix) - * @returns The transform matrix used to create the shadow map - */ - getTransformMatrix() { - const scene = this._scene; - if (this._currentRenderId === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) { - return this._transformMatrix; - } - this._currentRenderId = scene.getRenderId(); - this._currentFaceIndexCache = this._currentFaceIndex; - let lightPosition = this._light.position; - if (this._light.computeTransformedInformation()) { - lightPosition = this._light.transformedPosition; - } - math_vector_Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection); - if (Math.abs(math_vector_Vector3.Dot(this._lightDirection, math_vector_Vector3.Up())) === 1.0) { - this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light - } - if (this._light.needProjectionMatrixCompute() || - !this._cachedPosition || - !this._cachedDirection || - !lightPosition.equals(this._cachedPosition) || - !this._lightDirection.equals(this._cachedDirection)) { - this._cachedPosition.copyFrom(lightPosition); - this._cachedDirection.copyFrom(this._lightDirection); - math_vector_Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), math_vector_Vector3.Up(), this._viewMatrix); - const shadowMap = this.getShadowMap(); - if (shadowMap) { - const renderList = shadowMap.renderList; - if (renderList) { - this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList); - } - } - this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); - } - return this._transformMatrix; - } - /** - * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between - * Cube and 2D textures for instance. - */ - recreateShadowMap() { - const shadowMap = this._shadowMap; - if (!shadowMap) { - return; - } - // Track render list. - const renderList = shadowMap.renderList; - // Clean up existing data. - this._disposeRTTandPostProcesses(); - // Reinitializes. - this._initializeGenerator(); - // Reaffect the filter to ensure a correct fallback if necessary. - this.filter = this._filter; - // Reaffect the filter. - this._applyFilterValues(); - // Reaffect Render List. - if (renderList) { - // Note: don't do this._shadowMap!.renderList = renderList; - // The renderList hooked array is accessing the old RenderTargetTexture (see RenderTargetTexture._hookArray), which is disposed at this point (by the call to _disposeRTTandPostProcesses) - if (!this._shadowMap.renderList) { - this._shadowMap.renderList = []; - } - for (const mesh of renderList) { - this._shadowMap.renderList.push(mesh); - } - } - else { - this._shadowMap.renderList = null; - } - } - _disposeBlurPostProcesses() { - if (this._shadowMap2) { - this._shadowMap2.dispose(); - this._shadowMap2 = null; - } - if (this._boxBlurPostprocess) { - this._boxBlurPostprocess.dispose(); - this._boxBlurPostprocess = null; - } - if (this._kernelBlurXPostprocess) { - this._kernelBlurXPostprocess.dispose(); - this._kernelBlurXPostprocess = null; - } - if (this._kernelBlurYPostprocess) { - this._kernelBlurYPostprocess.dispose(); - this._kernelBlurYPostprocess = null; - } - this._blurPostProcesses = []; - } - _disposeRTTandPostProcesses() { - if (this._shadowMap) { - this._shadowMap.dispose(); - this._shadowMap = null; - } - this._disposeBlurPostProcesses(); - } - _disposeSceneUBOs() { - if (this._sceneUBOs) { - for (const ubo of this._sceneUBOs) { - ubo.dispose(); - } - this._sceneUBOs = []; - } - } - /** - * Disposes the ShadowGenerator. - * Returns nothing. - */ - dispose() { - this._disposeRTTandPostProcesses(); - this._disposeSceneUBOs(); - if (this._light) { - if (this._light._shadowGenerators) { - const iterator = this._light._shadowGenerators.entries(); - for (let entry = iterator.next(); entry.done !== true; entry = iterator.next()) { - const [camera, shadowGenerator] = entry.value; - if (shadowGenerator === this) { - this._light._shadowGenerators.delete(camera); - } - } - if (this._light._shadowGenerators.size === 0) { - this._light._shadowGenerators = null; - } - } - this._light._markMeshesAsLightDirty(); - } - this.onBeforeShadowMapRenderMeshObservable.clear(); - this.onBeforeShadowMapRenderObservable.clear(); - this.onAfterShadowMapRenderMeshObservable.clear(); - this.onAfterShadowMapRenderObservable.clear(); - } - /** - * Serializes the shadow generator setup to a json object. - * @returns The serialized JSON object - */ - serialize() { - var _a; - const serializationObject = {}; - const shadowMap = this.getShadowMap(); - if (!shadowMap) { - return serializationObject; - } - serializationObject.className = this.getClassName(); - serializationObject.lightId = this._light.id; - serializationObject.cameraId = (_a = this._camera) === null || _a === void 0 ? void 0 : _a.id; - serializationObject.id = this.id; - serializationObject.mapSize = shadowMap.getRenderSize(); - serializationObject.forceBackFacesOnly = this.forceBackFacesOnly; - serializationObject.darkness = this.getDarkness(); - serializationObject.transparencyShadow = this._transparencyShadow; - serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff; - serializationObject.bias = this.bias; - serializationObject.normalBias = this.normalBias; - serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering; - serializationObject.useContactHardeningShadow = this.useContactHardeningShadow; - serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio; - serializationObject.filteringQuality = this.filteringQuality; - serializationObject.useExponentialShadowMap = this.useExponentialShadowMap; - serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap; - serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap; - serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap; - serializationObject.usePoissonSampling = this.usePoissonSampling; - serializationObject.depthScale = this.depthScale; - serializationObject.blurBoxOffset = this.blurBoxOffset; - serializationObject.blurKernel = this.blurKernel; - serializationObject.blurScale = this.blurScale; - serializationObject.useKernelBlur = this.useKernelBlur; - serializationObject.renderList = []; - if (shadowMap.renderList) { - for (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) { - const mesh = shadowMap.renderList[meshIndex]; - serializationObject.renderList.push(mesh.id); - } - } - return serializationObject; - } - /** - * Parses a serialized ShadowGenerator and returns a new ShadowGenerator. - * @param parsedShadowGenerator The JSON object to parse - * @param scene The scene to create the shadow map for - * @param constr A function that builds a shadow generator or undefined to create an instance of the default shadow generator - * @returns The parsed shadow generator - */ - static Parse(parsedShadowGenerator, scene, constr) { - const light = scene.getLightById(parsedShadowGenerator.lightId); - const camera = parsedShadowGenerator.cameraId !== undefined ? scene.getCameraById(parsedShadowGenerator.cameraId) : null; - const shadowGenerator = constr ? constr(parsedShadowGenerator.mapSize, light, camera) : new shadowGenerator_ShadowGenerator(parsedShadowGenerator.mapSize, light, undefined, camera); - const shadowMap = shadowGenerator.getShadowMap(); - for (let meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) { - const meshes = scene.getMeshesById(parsedShadowGenerator.renderList[meshIndex]); - meshes.forEach(function (mesh) { - if (!shadowMap) { - return; - } - if (!shadowMap.renderList) { - shadowMap.renderList = []; - } - shadowMap.renderList.push(mesh); - }); - } - if (parsedShadowGenerator.id !== undefined) { - shadowGenerator.id = parsedShadowGenerator.id; - } - shadowGenerator.forceBackFacesOnly = !!parsedShadowGenerator.forceBackFacesOnly; - if (parsedShadowGenerator.darkness !== undefined) { - shadowGenerator.setDarkness(parsedShadowGenerator.darkness); - } - if (parsedShadowGenerator.transparencyShadow) { - shadowGenerator.setTransparencyShadow(true); - } - if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) { - shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff; - } - if (parsedShadowGenerator.bias !== undefined) { - shadowGenerator.bias = parsedShadowGenerator.bias; - } - if (parsedShadowGenerator.normalBias !== undefined) { - shadowGenerator.normalBias = parsedShadowGenerator.normalBias; - } - if (parsedShadowGenerator.usePercentageCloserFiltering) { - shadowGenerator.usePercentageCloserFiltering = true; - } - else if (parsedShadowGenerator.useContactHardeningShadow) { - shadowGenerator.useContactHardeningShadow = true; - } - else if (parsedShadowGenerator.usePoissonSampling) { - shadowGenerator.usePoissonSampling = true; - } - else if (parsedShadowGenerator.useExponentialShadowMap) { - shadowGenerator.useExponentialShadowMap = true; - } - else if (parsedShadowGenerator.useBlurExponentialShadowMap) { - shadowGenerator.useBlurExponentialShadowMap = true; - } - else if (parsedShadowGenerator.useCloseExponentialShadowMap) { - shadowGenerator.useCloseExponentialShadowMap = true; - } - else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) { - shadowGenerator.useBlurCloseExponentialShadowMap = true; - } - // Backward compat - else if (parsedShadowGenerator.useVarianceShadowMap) { - shadowGenerator.useExponentialShadowMap = true; - } - else if (parsedShadowGenerator.useBlurVarianceShadowMap) { - shadowGenerator.useBlurExponentialShadowMap = true; - } - if (parsedShadowGenerator.contactHardeningLightSizeUVRatio !== undefined) { - shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio; - } - if (parsedShadowGenerator.filteringQuality !== undefined) { - shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality; - } - if (parsedShadowGenerator.depthScale) { - shadowGenerator.depthScale = parsedShadowGenerator.depthScale; - } - if (parsedShadowGenerator.blurScale) { - shadowGenerator.blurScale = parsedShadowGenerator.blurScale; - } - if (parsedShadowGenerator.blurBoxOffset) { - shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset; - } - if (parsedShadowGenerator.useKernelBlur) { - shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur; - } - if (parsedShadowGenerator.blurKernel) { - shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel; - } - return shadowGenerator; - } -} -/** - * Name of the shadow generator class - */ -shadowGenerator_ShadowGenerator.CLASSNAME = "ShadowGenerator"; -/** - * Shadow generator mode None: no filtering applied. - */ -shadowGenerator_ShadowGenerator.FILTER_NONE = 0; -/** - * Shadow generator mode ESM: Exponential Shadow Mapping. - * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) - */ -shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1; -/** - * Shadow generator mode Poisson Sampling: Percentage Closer Filtering. - * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength) - */ -shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING = 2; -/** - * Shadow generator mode ESM: Blurred Exponential Shadow Mapping. - * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) - */ -shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3; -/** - * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing - * edge artifacts on steep falloff. - * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) - */ -shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4; -/** - * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing - * edge artifacts on steep falloff. - * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) - */ -shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5; -/** - * Shadow generator mode PCF: Percentage Closer Filtering - * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 - * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html) - */ -shadowGenerator_ShadowGenerator.FILTER_PCF = 6; -/** - * Shadow generator mode PCSS: Percentage Closering Soft Shadow. - * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 - * Contact Hardening - */ -shadowGenerator_ShadowGenerator.FILTER_PCSS = 7; -/** - * Reserved for PCF and PCSS - * Highest Quality. - * - * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts. - * - * Execute PCSS with 32 taps blocker search and 64 taps PCF. - */ -shadowGenerator_ShadowGenerator.QUALITY_HIGH = 0; -/** - * Reserved for PCF and PCSS - * Good tradeoff for quality/perf cross devices - * - * Execute PCF on a 3*3 kernel. - * - * Execute PCSS with 16 taps blocker search and 32 taps PCF. - */ -shadowGenerator_ShadowGenerator.QUALITY_MEDIUM = 1; -/** - * Reserved for PCF and PCSS - * The lowest quality but the fastest. - * - * Execute PCF on a 1*1 kernel. - * - * Execute PCSS with 16 taps blocker search and 16 taps PCF. - */ -shadowGenerator_ShadowGenerator.QUALITY_LOW = 2; -/** - * Defines the default alpha cutoff value used for transparent alpha tested materials. - */ -shadowGenerator_ShadowGenerator.DEFAULT_ALPHA_CUTOFF = 0.5; -/** - * @internal - */ -shadowGenerator_ShadowGenerator._SceneComponentInitialization = (_) => { - throw _WarnImport("ShadowGeneratorSceneComponent"); -}; -//# sourceMappingURL=shadowGenerator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/depth.fragment.js -// Do not edit. - - - - -const depth_fragment_name = "depthPixelShader"; -const depth_fragment_shader = `#ifdef ALPHATEST -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include<clipPlaneFragmentDeclaration> -varying float vDepthMetric; -#ifdef PACKED -#include<packingFunctions> -#endif -#ifdef STORE_CAMERASPACE_Z -varying vec4 vViewPos; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include<clipPlaneFragment> -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -#ifdef STORE_CAMERASPACE_Z -#ifdef PACKED -gl_FragColor=pack(vViewPos.z); -#else -gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); -#endif -#else -#ifdef NONLINEARDEPTH -#ifdef PACKED -gl_FragColor=pack(gl_FragCoord.z); -#else -gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); -#endif -#else -#ifdef PACKED -gl_FragColor=pack(vDepthMetric); -#else -gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); -#endif -#endif -#endif -}`; -// Sideeffect -ShaderStore.ShadersStore[depth_fragment_name] = depth_fragment_shader; -/** @internal */ -const depthPixelShader = { name: depth_fragment_name, shader: depth_fragment_shader }; -//# sourceMappingURL=depth.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/depth.vertex.js -// Do not edit. - - - - - - - - - - - - - -const depth_vertex_name = "depthVertexShader"; -const depth_vertex_shader = `attribute vec3 position; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<clipPlaneVertexDeclaration> -#include<instancesDeclaration> -uniform mat4 viewProjection;uniform vec2 depthValues; -#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#ifdef STORE_CAMERASPACE_Z -uniform mat4 view;varying vec4 vViewPos; -#endif -varying float vDepthMetric; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#include<clipPlaneVertex> -gl_Position=viewProjection*worldPos; -#ifdef STORE_CAMERASPACE_Z -vViewPos=view*worldPos; -#else -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); -#else -vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); -#endif -#endif -#if defined(ALPHATEST) || defined(BASIC_RENDER) -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[depth_vertex_name] = depth_vertex_shader; -/** @internal */ -const depthVertexShader = { name: depth_vertex_name, shader: depth_vertex_shader }; -//# sourceMappingURL=depth.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/depthRenderer.js - - - - - - - - - - - -/** - * This represents a depth renderer in Babylon. - * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing - */ -class DepthRenderer { - /** - * Sets a specific material to be used to render a mesh/a list of meshes by the depth renderer - * @param mesh mesh or array of meshes - * @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. - */ - setMaterialForRendering(mesh, material) { - this._depthMap.setMaterialForRendering(mesh, material); - } - /** - * Instantiates a depth renderer - * @param scene The scene the renderer belongs to - * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT) - * @param camera The camera to be used to render the depth map (default: scene's active camera) - * @param storeNonLinearDepth Defines whether the depth is stored linearly like in Babylon Shadows or directly like glFragCoord.z - * @param samplingMode The sampling mode to be used with the render target (Linear, Nearest...) (default: TRILINEAR_SAMPLINGMODE) - * @param storeCameraSpaceZ Defines whether the depth stored is the Z coordinate in camera space. If true, storeNonLinearDepth has no effect. (Default: false) - * @param name Name of the render target (default: DepthRenderer) - */ - constructor(scene, type = 1, camera = null, storeNonLinearDepth = false, samplingMode = texture_Texture.TRILINEAR_SAMPLINGMODE, storeCameraSpaceZ = false, name) { - /** Enable or disable the depth renderer. When disabled, the depth texture is not updated */ - this.enabled = true; - /** Force writing the transparent objects into the depth map */ - this.forceDepthWriteTransparentMeshes = false; - /** - * Specifies that the depth renderer will only be used within - * the camera it is created for. - * This can help forcing its rendering during the camera processing. - */ - this.useOnlyInActiveCamera = false; - /** If true, reverse the culling of materials before writing to the depth texture. - * So, basically, when "true", back facing instead of front facing faces are rasterized into the texture - */ - this.reverseCulling = false; - this._scene = scene; - this._storeNonLinearDepth = storeNonLinearDepth; - this._storeCameraSpaceZ = storeCameraSpaceZ; - this.isPacked = type === 0; - if (this.isPacked) { - this.clearColor = new math_color_Color4(1.0, 1.0, 1.0, 1.0); - } - else { - this.clearColor = new math_color_Color4(storeCameraSpaceZ ? 1e8 : 1.0, 0.0, 0.0, 1.0); - } - DepthRenderer._SceneComponentInitialization(this._scene); - const engine = scene.getEngine(); - this._camera = camera; - if (samplingMode !== texture_Texture.NEAREST_SAMPLINGMODE) { - if (type === 1 && !engine._caps.textureFloatLinearFiltering) { - samplingMode = texture_Texture.NEAREST_SAMPLINGMODE; - } - if (type === 2 && !engine._caps.textureHalfFloatLinearFiltering) { - samplingMode = texture_Texture.NEAREST_SAMPLINGMODE; - } - } - // Render target - const format = this.isPacked || !engine._features.supportExtendedTextureFormats ? 5 : 6; - this._depthMap = new renderTargetTexture_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); - this._depthMap.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._depthMap.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._depthMap.refreshRate = 1; - this._depthMap.renderParticles = false; - this._depthMap.renderList = null; - this._depthMap.noPrePassRenderer = true; - // Camera to get depth map from to support multiple concurrent cameras - this._depthMap.activeCamera = this._camera; - this._depthMap.ignoreCameraViewport = true; - this._depthMap.useCameraPostProcesses = false; - // set default depth value to 1.0 (far away) - this._depthMap.onClearObservable.add((engine) => { - engine.clear(this.clearColor, true, true, true); - }); - this._depthMap.onBeforeBindObservable.add(() => { - var _a; - (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, "depth renderer", 1); - }); - this._depthMap.onAfterUnbindObservable.add(() => { - var _a; - (_a = engine._debugPopGroup) === null || _a === void 0 ? void 0 : _a.call(engine, 1); - }); - this._depthMap.customIsReadyFunction = (mesh, refreshRate, preWarm) => { - if ((preWarm || refreshRate === 0) && mesh.subMeshes) { - for (let i = 0; i < mesh.subMeshes.length; ++i) { - const subMesh = mesh.subMeshes[i]; - const renderingMesh = subMesh.getRenderingMesh(); - const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); - const hardwareInstancedRendering = engine.getCaps().instancedArrays && - ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances); - if (!this.isReady(subMesh, hardwareInstancedRendering)) { - return false; - } - } - } - return true; - }; - // Custom render function - const renderSubMesh = (subMesh) => { - var _a, _b; - const renderingMesh = subMesh.getRenderingMesh(); - const effectiveMesh = subMesh.getEffectiveMesh(); - const scene = this._scene; - const engine = scene.getEngine(); - const material = subMesh.getMaterial(); - effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; - if (!material || effectiveMesh.infiniteDistance || material.disableDepthWrite || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) { - return; - } - // Culling - const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0; - let sideOrientation = (_a = renderingMesh.overrideMaterialSideOrientation) !== null && _a !== void 0 ? _a : material.sideOrientation; - if (detNeg) { - sideOrientation = - sideOrientation === 0 - ? 1 - : 0; - } - const reverseSideOrientation = sideOrientation === 0; - engine.setState(material.backFaceCulling, 0, false, reverseSideOrientation, this.reverseCulling ? !material.cullBackFaces : material.cullBackFaces); - // Managing instances - const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); - if (batch.mustReturn) { - return; - } - const hardwareInstancedRendering = engine.getCaps().instancedArrays && - ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances); - const camera = this._camera || scene.activeCamera; - if (this.isReady(subMesh, hardwareInstancedRendering) && camera) { - subMesh._renderId = scene.getRenderId(); - const renderingMaterial = (_b = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _b === void 0 ? void 0 : _b[engine.currentRenderPassId]; - let drawWrapper = subMesh._getDrawWrapper(); - if (!drawWrapper && renderingMaterial) { - drawWrapper = renderingMaterial._getDrawWrapper(); - } - const cameraIsOrtho = camera.mode === camera_Camera.ORTHOGRAPHIC_CAMERA; - if (!drawWrapper) { - return; - } - const effect = drawWrapper.effect; - engine.enableEffect(drawWrapper); - if (!hardwareInstancedRendering) { - renderingMesh._bind(subMesh, effect, material.fillMode); - } - if (!renderingMaterial) { - effect.setMatrix("viewProjection", scene.getTransformMatrix()); - effect.setMatrix("world", effectiveMesh.getWorldMatrix()); - if (this._storeCameraSpaceZ) { - effect.setMatrix("view", scene.getViewMatrix()); - } - } - else { - renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh); - } - let minZ, maxZ; - if (cameraIsOrtho) { - minZ = !engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1; - maxZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1; - } - else { - minZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? camera.minZ : engine.isNDCHalfZRange ? 0 : camera.minZ; - maxZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : camera.maxZ; - } - effect.setFloat2("depthValues", minZ, minZ + maxZ); - if (!renderingMaterial) { - // Alpha test - if (material.needAlphaTesting()) { - const alphaTexture = material.getAlphaTestTexture(); - if (alphaTexture) { - effect.setTexture("diffuseSampler", alphaTexture); - effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); - } - } - // Bones - if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { - const skeleton = renderingMesh.skeleton; - if (skeleton.isUsingTextureForMatrices) { - const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh); - if (!boneTexture) { - return; - } - effect.setTexture("boneSampler", boneTexture); - effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); - } - else { - effect.setMatrices("mBones", skeleton.getTransformMatrices(renderingMesh)); - } - } - // Clip planes - bindClipPlane(effect, material, scene); - // Morph targets - MaterialHelper.BindMorphTargetParameters(renderingMesh, effect); - if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { - renderingMesh.morphTargetManager._bind(effect); - } - } - // Draw - renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix("world", world)); - } - }; - this._depthMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { - let index; - if (depthOnlySubMeshes.length) { - for (index = 0; index < depthOnlySubMeshes.length; index++) { - renderSubMesh(depthOnlySubMeshes.data[index]); - } - } - for (index = 0; index < opaqueSubMeshes.length; index++) { - renderSubMesh(opaqueSubMeshes.data[index]); - } - for (index = 0; index < alphaTestSubMeshes.length; index++) { - renderSubMesh(alphaTestSubMeshes.data[index]); - } - if (this.forceDepthWriteTransparentMeshes) { - for (index = 0; index < transparentSubMeshes.length; index++) { - renderSubMesh(transparentSubMeshes.data[index]); - } - } - else { - for (index = 0; index < transparentSubMeshes.length; index++) { - transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false; - } - } - }; - } - /** - * Creates the depth rendering effect and checks if the effect is ready. - * @param subMesh The submesh to be used to render the depth map of - * @param useInstances If multiple world instances should be used - * @returns if the depth renderer is ready to render the depth map - */ - isReady(subMesh, useInstances) { - var _a; - const engine = this._scene.getEngine(); - const mesh = subMesh.getMesh(); - const scene = mesh.getScene(); - const renderingMaterial = (_a = mesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[engine.currentRenderPassId]; - if (renderingMaterial) { - return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances); - } - const material = subMesh.getMaterial(); - if (!material || material.disableDepthWrite) { - return false; - } - const defines = []; - const attribs = [buffer_VertexBuffer.PositionKind]; - // Alpha test - if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) { - defines.push("#define ALPHATEST"); - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - attribs.push(buffer_VertexBuffer.UVKind); - defines.push("#define UV1"); - } - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)) { - attribs.push(buffer_VertexBuffer.UV2Kind); - defines.push("#define UV2"); - } - } - // Bones - if (mesh.useBones && mesh.computeBonesUsingShaders) { - attribs.push(buffer_VertexBuffer.MatricesIndicesKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsKind); - if (mesh.numBoneInfluencers > 4) { - attribs.push(buffer_VertexBuffer.MatricesIndicesExtraKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsExtraKind); - } - defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); - defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0)); - const skeleton = subMesh.getRenderingMesh().skeleton; - if (skeleton === null || skeleton === void 0 ? void 0 : skeleton.isUsingTextureForMatrices) { - defines.push("#define BONETEXTURE"); - } - } - else { - defines.push("#define NUM_BONE_INFLUENCERS 0"); - } - // Morph targets - const morphTargetManager = mesh.morphTargetManager; - let numMorphInfluencers = 0; - if (morphTargetManager) { - if (morphTargetManager.numInfluencers > 0) { - numMorphInfluencers = morphTargetManager.numInfluencers; - defines.push("#define MORPHTARGETS"); - defines.push("#define NUM_MORPH_INFLUENCERS " + numMorphInfluencers); - if (morphTargetManager.isUsingTextureForTargets) { - defines.push("#define MORPHTARGETS_TEXTURE"); - } - MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers); - } - } - // Instances - if (useInstances) { - defines.push("#define INSTANCES"); - MaterialHelper.PushAttributesForInstances(attribs); - if (subMesh.getRenderingMesh().hasThinInstances) { - defines.push("#define THIN_INSTANCES"); - } - } - // None linear depth - if (this._storeNonLinearDepth) { - defines.push("#define NONLINEARDEPTH"); - } - // Store camera space Z coordinate instead of NDC Z - if (this._storeCameraSpaceZ) { - defines.push("#define STORE_CAMERASPACE_Z"); - } - // Float Mode - if (this.isPacked) { - defines.push("#define PACKED"); - } - // Clip planes - prepareStringDefinesForClipPlanes(material, scene, defines); - // Get correct effect - const drawWrapper = subMesh._getDrawWrapper(undefined, true); - const cachedDefines = drawWrapper.defines; - const join = defines.join("\n"); - if (cachedDefines !== join) { - const uniforms = [ - "world", - "mBones", - "boneTextureWidth", - "viewProjection", - "view", - "diffuseMatrix", - "depthValues", - "morphTargetInfluences", - "morphTargetTextureInfo", - "morphTargetTextureIndices", - ]; - addClipPlaneUniforms(uniforms); - drawWrapper.setEffect(engine.createEffect("depth", attribs, uniforms, ["diffuseSampler", "morphTargets", "boneSampler"], join, undefined, undefined, undefined, { - maxSimultaneousMorphTargets: numMorphInfluencers, - }), join); - } - return drawWrapper.effect.isReady(); - } - /** - * Gets the texture which the depth map will be written to. - * @returns The depth map texture - */ - getDepthMap() { - return this._depthMap; - } - /** - * Disposes of the depth renderer. - */ - dispose() { - const keysToDelete = []; - for (const key in this._scene._depthRenderer) { - const depthRenderer = this._scene._depthRenderer[key]; - if (depthRenderer === this) { - keysToDelete.push(key); - } - } - if (keysToDelete.length > 0) { - this._depthMap.dispose(); - for (const key of keysToDelete) { - delete this._scene._depthRenderer[key]; - } - } - } -} -/** - * @internal - */ -DepthRenderer._SceneComponentInitialization = (_) => { - throw _WarnImport("DepthRendererSceneComponent"); -}; -//# sourceMappingURL=depthRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/minmaxRedux.fragment.js -// Do not edit. - -const minmaxRedux_fragment_name = "minmaxReduxPixelShader"; -const minmaxRedux_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler; -#if defined(INITIAL) -uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); -#ifdef DEPTH_REDUX -float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); -#else -float maxz=max(max(max(f1,f2),f3),f4); -#endif -glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(MAIN) -uniform vec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(ONEBEFORELAST) -uniform ivec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(LAST) -void main(void) -{glFragColor=vec4(0.);if (true) { -discard;}} -#endif -`; -// Sideeffect -ShaderStore.ShadersStore[minmaxRedux_fragment_name] = minmaxRedux_fragment_shader; -/** @internal */ -const minmaxReduxPixelShader = { name: minmaxRedux_fragment_name, shader: minmaxRedux_fragment_shader }; -//# sourceMappingURL=minmaxRedux.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/minMaxReducer.js - - - - - -/** - * This class computes a min/max reduction from a texture: it means it computes the minimum - * and maximum values from all values of the texture. - * It is performed on the GPU for better performances, thanks to a succession of post processes. - * The source values are read from the red channel of the texture. - */ -class MinMaxReducer { - /** - * Creates a min/max reducer - * @param camera The camera to use for the post processes - */ - constructor(camera) { - /** - * Observable triggered when the computation has been performed - */ - this.onAfterReductionPerformed = new observable_Observable(); - this._forceFullscreenViewport = true; - this._activated = false; - this._camera = camera; - this._postProcessManager = new PostProcessManager(camera.getScene()); - this._onContextRestoredObserver = camera.getEngine().onContextRestoredObservable.add(() => { - this._postProcessManager._rebuild(); - }); - } - /** - * Gets the texture used to read the values from. - */ - get sourceTexture() { - return this._sourceTexture; - } - /** - * Sets the source texture to read the values from. - * One must indicate if the texture is a depth texture or not through the depthRedux parameter - * because in such textures '1' value must not be taken into account to compute the maximum - * as this value is used to clear the texture. - * Note that the computation is not activated by calling this function, you must call activate() for that! - * @param sourceTexture The texture to read the values from. The values should be in the red channel. - * @param depthRedux Indicates if the texture is a depth texture or not - * @param type The type of the textures created for the reduction (defaults to TEXTURETYPE_HALF_FLOAT) - * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true) - */ - setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) { - if (sourceTexture === this._sourceTexture) { - return; - } - this.dispose(false); - this._sourceTexture = sourceTexture; - this._reductionSteps = []; - this._forceFullscreenViewport = forceFullscreenViewport; - const scene = this._camera.getScene(); - // create the first step - const reductionInitial = new postProcess_PostProcess("Initial reduction phase", "minmaxRedux", // shader - ["texSize"], ["sourceTexture"], // textures - 1.0, // options - null, // camera - 1, // sampling - scene.getEngine(), // engine - false, // reusable - "#define INITIAL" + (depthRedux ? "\n#define DEPTH_REDUX" : ""), // defines - type, undefined, undefined, undefined, 7); - reductionInitial.autoClear = false; - reductionInitial.forceFullscreenViewport = forceFullscreenViewport; - let w = this._sourceTexture.getRenderWidth(), h = this._sourceTexture.getRenderHeight(); - reductionInitial.onApply = ((w, h) => { - return (effect) => { - effect.setTexture("sourceTexture", this._sourceTexture); - effect.setFloat2("texSize", w, h); - }; - })(w, h); - this._reductionSteps.push(reductionInitial); - let index = 1; - // create the additional steps - while (w > 1 || h > 1) { - w = Math.max(Math.round(w / 2), 1); - h = Math.max(Math.round(h / 2), 1); - const reduction = new postProcess_PostProcess("Reduction phase " + index, "minmaxRedux", // shader - ["texSize"], null, { width: w, height: h }, // options - null, // camera - 1, // sampling - scene.getEngine(), // engine - false, // reusable - "#define " + (w == 1 && h == 1 ? "LAST" : w == 1 || h == 1 ? "ONEBEFORELAST" : "MAIN"), // defines - type, undefined, undefined, undefined, 7); - reduction.autoClear = false; - reduction.forceFullscreenViewport = forceFullscreenViewport; - reduction.onApply = ((w, h) => { - return (effect) => { - if (w == 1 || h == 1) { - effect.setInt2("texSize", w, h); - } - else { - effect.setFloat2("texSize", w, h); - } - }; - })(w, h); - this._reductionSteps.push(reduction); - index++; - if (w == 1 && h == 1) { - const func = (w, h, reduction) => { - const buffer = new Float32Array(4 * w * h), minmax = { min: 0, max: 0 }; - return () => { - scene.getEngine()._readTexturePixels(reduction.inputTexture.texture, w, h, -1, 0, buffer, false); - minmax.min = buffer[0]; - minmax.max = buffer[1]; - this.onAfterReductionPerformed.notifyObservers(minmax); - }; - }; - reduction.onAfterRenderObservable.add(func(w, h, reduction)); - } - } - } - /** - * Defines the refresh rate of the computation. - * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on... - */ - get refreshRate() { - return this._sourceTexture ? this._sourceTexture.refreshRate : -1; - } - set refreshRate(value) { - if (this._sourceTexture) { - this._sourceTexture.refreshRate = value; - } - } - /** - * Gets the activation status of the reducer - */ - get activated() { - return this._activated; - } - /** - * Activates the reduction computation. - * When activated, the observers registered in onAfterReductionPerformed are - * called after the computation is performed - */ - activate() { - if (this._onAfterUnbindObserver || !this._sourceTexture) { - return; - } - this._onAfterUnbindObserver = this._sourceTexture.onAfterUnbindObservable.add(() => { - var _a, _b; - const engine = this._camera.getScene().getEngine(); - (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `min max reduction`, 1); - this._reductionSteps[0].activate(this._camera); - this._postProcessManager.directRender(this._reductionSteps, this._reductionSteps[0].inputTexture, this._forceFullscreenViewport); - engine.unBindFramebuffer(this._reductionSteps[0].inputTexture, false); - (_b = engine._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(engine, 1); - }); - this._activated = true; - } - /** - * Deactivates the reduction computation. - */ - deactivate() { - if (!this._onAfterUnbindObserver || !this._sourceTexture) { - return; - } - this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver); - this._onAfterUnbindObserver = null; - this._activated = false; - } - /** - * Disposes the min/max reducer - * @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. - */ - dispose(disposeAll = true) { - if (disposeAll) { - this.onAfterReductionPerformed.clear(); - if (this._onContextRestoredObserver) { - this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver); - this._onContextRestoredObserver = null; - } - } - this.deactivate(); - if (this._reductionSteps) { - for (let i = 0; i < this._reductionSteps.length; ++i) { - this._reductionSteps[i].dispose(); - } - this._reductionSteps = null; - } - if (this._postProcessManager && disposeAll) { - this._postProcessManager.dispose(); - } - this._sourceTexture = null; - } -} -//# sourceMappingURL=minMaxReducer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/depthReducer.js - - - -/** - * This class is a small wrapper around the MinMaxReducer class to compute the min/max values of a depth texture - */ -class DepthReducer extends MinMaxReducer { - /** - * Gets the depth renderer used for the computation. - * Note that the result is null if you provide your own renderer when calling setDepthRenderer. - */ - get depthRenderer() { - return this._depthRenderer; - } - /** - * Creates a depth reducer - * @param camera The camera used to render the depth texture - */ - constructor(camera) { - super(camera); - } - /** - * Sets the depth renderer to use to generate the depth map - * @param depthRenderer The depth renderer to use. If not provided, a new one will be created automatically - * @param type The texture type of the depth map (default: TEXTURETYPE_HALF_FLOAT) - * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true) - */ - setDepthRenderer(depthRenderer = null, type = 2, forceFullscreenViewport = true) { - const scene = this._camera.getScene(); - if (this._depthRenderer) { - delete scene._depthRenderer[this._depthRendererId]; - this._depthRenderer.dispose(); - this._depthRenderer = null; - } - if (depthRenderer === null) { - if (!scene._depthRenderer) { - scene._depthRenderer = {}; - } - depthRenderer = this._depthRenderer = new DepthRenderer(scene, type, this._camera, false, 1); - depthRenderer.enabled = false; - this._depthRendererId = "minmax" + this._camera.id; - scene._depthRenderer[this._depthRendererId] = depthRenderer; - } - super.setSourceTexture(depthRenderer.getDepthMap(), true, type, forceFullscreenViewport); - } - /** - * @internal - */ - setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) { - super.setSourceTexture(sourceTexture, depthRedux, type, forceFullscreenViewport); - } - /** - * Activates the reduction computation. - * When activated, the observers registered in onAfterReductionPerformed are - * called after the computation is performed - */ - activate() { - if (this._depthRenderer) { - this._depthRenderer.enabled = true; - } - super.activate(); - } - /** - * Deactivates the reduction computation. - */ - deactivate() { - super.deactivate(); - if (this._depthRenderer) { - this._depthRenderer.enabled = false; - } - } - /** - * Disposes the depth reducer - * @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. - */ - dispose(disposeAll = true) { - super.dispose(disposeAll); - if (this._depthRenderer && disposeAll) { - const scene = this._depthRenderer.getDepthMap().getScene(); - if (scene) { - delete scene._depthRenderer[this._depthRendererId]; - } - this._depthRenderer.dispose(); - this._depthRenderer = null; - } - } -} -//# sourceMappingURL=depthReducer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/Shadows/cascadedShadowGenerator.js - - - - - - - - - - - - -// eslint-disable-next-line @typescript-eslint/naming-convention -const UpDir = math_vector_Vector3.Up(); -// eslint-disable-next-line @typescript-eslint/naming-convention -const ZeroVec = math_vector_Vector3.Zero(); -const tmpv1 = new math_vector_Vector3(), tmpv2 = new math_vector_Vector3(), tmpMatrix = new math_vector_Matrix(); -/** - * A CSM implementation allowing casting shadows on large scenes. - * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows - * Based on: https://github.com/TheRealMJP/Shadows and https://johanmedestrom.wordpress.com/2016/03/18/opengl-cascaded-shadow-maps/ - */ -class CascadedShadowGenerator extends shadowGenerator_ShadowGenerator { - _validateFilter(filter) { - if (filter === shadowGenerator_ShadowGenerator.FILTER_NONE || filter === shadowGenerator_ShadowGenerator.FILTER_PCF || filter === shadowGenerator_ShadowGenerator.FILTER_PCSS) { - return filter; - } - console.error('Unsupported filter "' + filter + '"!'); - return shadowGenerator_ShadowGenerator.FILTER_NONE; - } - /** - * Gets or set the number of cascades used by the CSM. - */ - get numCascades() { - return this._numCascades; - } - set numCascades(value) { - value = Math.min(Math.max(value, CascadedShadowGenerator.MIN_CASCADES_COUNT), CascadedShadowGenerator.MAX_CASCADES_COUNT); - if (value === this._numCascades) { - return; - } - this._numCascades = value; - this.recreateShadowMap(); - this._recreateSceneUBOs(); - } - /** - * Enables or disables the shadow casters bounding info computation. - * If your shadow casters don't move, you can disable this feature. - * If it is enabled, the bounding box computation is done every frame. - */ - get freezeShadowCastersBoundingInfo() { - return this._freezeShadowCastersBoundingInfo; - } - set freezeShadowCastersBoundingInfo(freeze) { - if (this._freezeShadowCastersBoundingInfoObservable && freeze) { - this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable); - this._freezeShadowCastersBoundingInfoObservable = null; - } - if (!this._freezeShadowCastersBoundingInfoObservable && !freeze) { - this._freezeShadowCastersBoundingInfoObservable = this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this)); - } - this._freezeShadowCastersBoundingInfo = freeze; - if (freeze) { - this._computeShadowCastersBoundingInfo(); - } - } - _computeShadowCastersBoundingInfo() { - this._scbiMin.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - this._scbiMax.copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE); - if (this._shadowMap && this._shadowMap.renderList) { - const renderList = this._shadowMap.renderList; - for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) { - const mesh = renderList[meshIndex]; - if (!mesh) { - continue; - } - const boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox; - this._scbiMin.minimizeInPlace(boundingBox.minimumWorld); - this._scbiMax.maximizeInPlace(boundingBox.maximumWorld); - } - const meshes = this._scene.meshes; - for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) { - const mesh = meshes[meshIndex]; - if (!mesh || !mesh.isVisible || !mesh.isEnabled || !mesh.receiveShadows) { - continue; - } - const boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox; - this._scbiMin.minimizeInPlace(boundingBox.minimumWorld); - this._scbiMax.maximizeInPlace(boundingBox.maximumWorld); - } - } - this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax); - } - /** - * Gets or sets the shadow casters bounding info. - * If you provide your own shadow casters bounding info, first enable freezeShadowCastersBoundingInfo - * so that the system won't overwrite the bounds you provide - */ - get shadowCastersBoundingInfo() { - return this._shadowCastersBoundingInfo; - } - set shadowCastersBoundingInfo(boundingInfo) { - this._shadowCastersBoundingInfo = boundingInfo; - } - /** - * Sets the minimal and maximal distances to use when computing the cascade breaks. - * - * The values of min / max are typically the depth zmin and zmax values of your scene, for a given frame. - * If you don't know these values, simply leave them to their defaults and don't call this function. - * @param min minimal distance for the breaks (default to 0.) - * @param max maximal distance for the breaks (default to 1.) - */ - setMinMaxDistance(min, max) { - if (this._minDistance === min && this._maxDistance === max) { - return; - } - if (min > max) { - min = 0; - max = 1; - } - if (min < 0) { - min = 0; - } - if (max > 1) { - max = 1; - } - this._minDistance = min; - this._maxDistance = max; - this._breaksAreDirty = true; - } - /** Gets the minimal distance used in the cascade break computation */ - get minDistance() { - return this._minDistance; - } - /** Gets the maximal distance used in the cascade break computation */ - get maxDistance() { - return this._maxDistance; - } - /** - * Gets the class name of that object - * @returns "CascadedShadowGenerator" - */ - getClassName() { - return CascadedShadowGenerator.CLASSNAME; - } - /** - * Gets a cascade minimum extents - * @param cascadeIndex index of the cascade - * @returns the minimum cascade extents - */ - getCascadeMinExtents(cascadeIndex) { - return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMinExtents[cascadeIndex] : null; - } - /** - * Gets a cascade maximum extents - * @param cascadeIndex index of the cascade - * @returns the maximum cascade extents - */ - getCascadeMaxExtents(cascadeIndex) { - return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMaxExtents[cascadeIndex] : null; - } - /** - * Gets the shadow max z distance. It's the limit beyond which shadows are not displayed. - * It defaults to camera.maxZ - */ - get shadowMaxZ() { - if (!this._getCamera()) { - return 0; - } - return this._shadowMaxZ; - } - /** - * Sets the shadow max z distance. - */ - set shadowMaxZ(value) { - const camera = this._getCamera(); - if (!camera) { - this._shadowMaxZ = value; - return; - } - if (this._shadowMaxZ === value || value < camera.minZ || value > camera.maxZ) { - return; - } - this._shadowMaxZ = value; - this._light._markMeshesAsLightDirty(); - this._breaksAreDirty = true; - } - /** - * Gets or sets the debug flag. - * When enabled, the cascades are materialized by different colors on the screen. - */ - get debug() { - return this._debug; - } - set debug(dbg) { - this._debug = dbg; - this._light._markMeshesAsLightDirty(); - } - /** - * Gets or sets the depth clamping value. - * - * When enabled, it improves the shadow quality because the near z plane of the light frustum don't need to be adjusted - * to account for the shadow casters far away. - * - * Note that this property is incompatible with PCSS filtering, so it won't be used in that case. - */ - get depthClamp() { - return this._depthClamp; - } - set depthClamp(value) { - this._depthClamp = value; - } - /** - * Gets or sets the percentage of blending between two cascades (value between 0. and 1.). - * It defaults to 0.1 (10% blending). - */ - get cascadeBlendPercentage() { - return this._cascadeBlendPercentage; - } - set cascadeBlendPercentage(value) { - this._cascadeBlendPercentage = value; - this._light._markMeshesAsLightDirty(); - } - /** - * Gets or set the lambda parameter. - * This parameter is used to split the camera frustum and create the cascades. - * 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. - * For all values in-between, it's a linear combination of the uniform and logarithm split algorithm. - */ - get lambda() { - return this._lambda; - } - set lambda(value) { - const lambda = Math.min(Math.max(value, 0), 1); - if (this._lambda == lambda) { - return; - } - this._lambda = lambda; - this._breaksAreDirty = true; - } - /** - * Gets the view matrix corresponding to a given cascade - * @param cascadeNum cascade to retrieve the view matrix from - * @returns the cascade view matrix - */ - getCascadeViewMatrix(cascadeNum) { - return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._viewMatrices[cascadeNum] : null; - } - /** - * Gets the projection matrix corresponding to a given cascade - * @param cascadeNum cascade to retrieve the projection matrix from - * @returns the cascade projection matrix - */ - getCascadeProjectionMatrix(cascadeNum) { - return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._projectionMatrices[cascadeNum] : null; - } - /** - * Gets the transformation matrix corresponding to a given cascade - * @param cascadeNum cascade to retrieve the transformation matrix from - * @returns the cascade transformation matrix - */ - getCascadeTransformMatrix(cascadeNum) { - return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._transformMatrices[cascadeNum] : null; - } - /** - * Sets the depth renderer to use when autoCalcDepthBounds is enabled. - * - * Note that if no depth renderer is set, a new one will be automatically created internally when necessary. - * - * You should call this function if you already have a depth renderer enabled in your scene, to avoid - * doing multiple depth rendering each frame. If you provide your own depth renderer, make sure it stores linear depth! - * @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 - */ - setDepthRenderer(depthRenderer) { - this._depthRenderer = depthRenderer; - if (this._depthReducer) { - this._depthReducer.setDepthRenderer(this._depthRenderer); - } - } - /** - * Gets or sets the autoCalcDepthBounds property. - * - * When enabled, a depth rendering pass is first performed (with an internally created depth renderer or with the one - * you provide by calling setDepthRenderer). Then, a min/max reducing is applied on the depth map to compute the - * minimal and maximal depth of the map and those values are used as inputs for the setMinMaxDistance() function. - * It can greatly enhance the shadow quality, at the expense of more GPU works. - * When using this option, you should increase the value of the lambda parameter, and even set it to 1 for best results. - */ - get autoCalcDepthBounds() { - return this._autoCalcDepthBounds; - } - set autoCalcDepthBounds(value) { - const camera = this._getCamera(); - if (!camera) { - return; - } - this._autoCalcDepthBounds = value; - if (!value) { - if (this._depthReducer) { - this._depthReducer.deactivate(); - } - this.setMinMaxDistance(0, 1); - return; - } - if (!this._depthReducer) { - this._depthReducer = new DepthReducer(camera); - this._depthReducer.onAfterReductionPerformed.add((minmax) => { - let min = minmax.min, max = minmax.max; - if (min >= max) { - min = 0; - max = 1; - } - if (min != this._minDistance || max != this._maxDistance) { - this.setMinMaxDistance(min, max); - } - }); - this._depthReducer.setDepthRenderer(this._depthRenderer); - } - this._depthReducer.activate(); - } - /** - * Defines the refresh rate of the min/max computation used when autoCalcDepthBounds is set to true - * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on... - * Note that if you provided your own depth renderer through a call to setDepthRenderer, you are responsible - * for setting the refresh rate on the renderer yourself! - */ - get autoCalcDepthBoundsRefreshRate() { - var _a, _b, _c; - 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; - } - set autoCalcDepthBoundsRefreshRate(value) { - var _a; - if ((_a = this._depthReducer) === null || _a === void 0 ? void 0 : _a.depthRenderer) { - this._depthReducer.depthRenderer.getDepthMap().refreshRate = value; - } - } - /** - * Create the cascade breaks according to the lambda, shadowMaxZ and min/max distance properties, as well as the camera near and far planes. - * This function is automatically called when updating lambda, shadowMaxZ and min/max distances, however you should call it yourself if - * you change the camera near/far planes! - */ - splitFrustum() { - this._breaksAreDirty = true; - } - _splitFrustum() { - const camera = this._getCamera(); - if (!camera) { - return; - } - const near = camera.minZ, far = camera.maxZ || this._shadowMaxZ, // account for infinite far plane (ie. maxZ = 0) - cameraRange = far - near, minDistance = this._minDistance, maxDistance = this._shadowMaxZ < far && this._shadowMaxZ >= near ? Math.min((this._shadowMaxZ - near) / (far - near), this._maxDistance) : this._maxDistance; - const minZ = near + minDistance * cameraRange, maxZ = near + maxDistance * cameraRange; - const range = maxZ - minZ, ratio = maxZ / minZ; - for (let cascadeIndex = 0; cascadeIndex < this._cascades.length; ++cascadeIndex) { - const p = (cascadeIndex + 1) / this._numCascades, log = minZ * ratio ** p, uniform = minZ + range * p; - const d = this._lambda * (log - uniform) + uniform; - this._cascades[cascadeIndex].prevBreakDistance = cascadeIndex === 0 ? minDistance : this._cascades[cascadeIndex - 1].breakDistance; - this._cascades[cascadeIndex].breakDistance = (d - near) / cameraRange; - this._viewSpaceFrustumsZ[cascadeIndex] = d; - this._frustumLengths[cascadeIndex] = (this._cascades[cascadeIndex].breakDistance - this._cascades[cascadeIndex].prevBreakDistance) * cameraRange; - } - this._breaksAreDirty = false; - } - _computeMatrices() { - const scene = this._scene; - const camera = this._getCamera(); - if (!camera) { - return; - } - math_vector_Vector3.NormalizeToRef(this._light.getShadowDirection(0), this._lightDirection); - if (Math.abs(math_vector_Vector3.Dot(this._lightDirection, math_vector_Vector3.Up())) === 1.0) { - this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light - } - this._cachedDirection.copyFrom(this._lightDirection); - const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer; - for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) { - this._computeFrustumInWorldSpace(cascadeIndex); - this._computeCascadeFrustum(cascadeIndex); - this._cascadeMaxExtents[cascadeIndex].subtractToRef(this._cascadeMinExtents[cascadeIndex], tmpv1); // tmpv1 = cascadeExtents - // Get position of the shadow camera - this._frustumCenter[cascadeIndex].addToRef(this._lightDirection.scale(this._cascadeMinExtents[cascadeIndex].z), this._shadowCameraPos[cascadeIndex]); - // Come up with a new orthographic camera for the shadow caster - math_vector_Matrix.LookAtLHToRef(this._shadowCameraPos[cascadeIndex], this._frustumCenter[cascadeIndex], UpDir, this._viewMatrices[cascadeIndex]); - let minZ = 0, maxZ = tmpv1.z; - // Try to tighten minZ and maxZ based on the bounding box of the shadow casters - const boundingInfo = this._shadowCastersBoundingInfo; - boundingInfo.update(this._viewMatrices[cascadeIndex]); - maxZ = Math.min(maxZ, boundingInfo.boundingBox.maximumWorld.z); - if (!this._depthClamp || this.filter === shadowGenerator_ShadowGenerator.FILTER_PCSS) { - // If we don't use depth clamping, we must set minZ so that all shadow casters are in the light frustum - minZ = Math.min(minZ, boundingInfo.boundingBox.minimumWorld.z); - } - else { - // If using depth clamping, we can adjust minZ to reduce the [minZ, maxZ] range (and get some additional precision in the shadow map) - minZ = Math.max(minZ, boundingInfo.boundingBox.minimumWorld.z); - } - math_vector_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); - this._cascadeMinExtents[cascadeIndex].z = minZ; - this._cascadeMaxExtents[cascadeIndex].z = maxZ; - this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]); - // Create the rounding matrix, by projecting the world-space origin and determining - // the fractional offset in texel space - math_vector_Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[cascadeIndex], tmpv1); // tmpv1 = shadowOrigin - tmpv1.scaleInPlace(this._mapSize / 2); - tmpv2.copyFromFloats(Math.round(tmpv1.x), Math.round(tmpv1.y), Math.round(tmpv1.z)); // tmpv2 = roundedOrigin - tmpv2.subtractInPlace(tmpv1).scaleInPlace(2 / this._mapSize); // tmpv2 = roundOffset - math_vector_Matrix.TranslationToRef(tmpv2.x, tmpv2.y, 0.0, tmpMatrix); - this._projectionMatrices[cascadeIndex].multiplyToRef(tmpMatrix, this._projectionMatrices[cascadeIndex]); - this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]); - this._transformMatrices[cascadeIndex].copyToArray(this._transformMatricesAsArray, cascadeIndex * 16); - } - } - // Get the 8 points of the view frustum in world space - _computeFrustumInWorldSpace(cascadeIndex) { - const camera = this._getCamera(); - if (!camera) { - return; - } - const prevSplitDist = this._cascades[cascadeIndex].prevBreakDistance, splitDist = this._cascades[cascadeIndex].breakDistance; - const isNDCHalfZRange = this._scene.getEngine().isNDCHalfZRange; - camera.getViewMatrix(); // make sure the transformation matrix we get when calling 'getTransformationMatrix()' is calculated with an up to date view matrix - const cameraInfiniteFarPlane = camera.maxZ === 0; - const saveCameraMaxZ = camera.maxZ; - if (cameraInfiniteFarPlane) { - camera.maxZ = this._shadowMaxZ; - camera.getProjectionMatrix(true); - } - const invViewProj = math_vector_Matrix.Invert(camera.getTransformationMatrix()); - if (cameraInfiniteFarPlane) { - camera.maxZ = saveCameraMaxZ; - camera.getProjectionMatrix(true); - } - const cornerIndexOffset = this._scene.getEngine().useReverseDepthBuffer ? 4 : 0; - for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++cornerIndex) { - tmpv1.copyFrom(CascadedShadowGenerator._FrustumCornersNDCSpace[(cornerIndex + cornerIndexOffset) % CascadedShadowGenerator._FrustumCornersNDCSpace.length]); - if (isNDCHalfZRange && tmpv1.z === -1) { - tmpv1.z = 0; - } - math_vector_Vector3.TransformCoordinatesToRef(tmpv1, invViewProj, this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]); - } - // Get the corners of the current cascade slice of the view frustum - for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length / 2; ++cornerIndex) { - tmpv1.copyFrom(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4]).subtractInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]); - tmpv2.copyFrom(tmpv1).scaleInPlace(prevSplitDist); // near corner ray - tmpv1.scaleInPlace(splitDist); // far corner ray - tmpv1.addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]); - this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4].copyFrom(tmpv1); - this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].addInPlace(tmpv2); - } - } - _computeCascadeFrustum(cascadeIndex) { - this._cascadeMinExtents[cascadeIndex].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - this._cascadeMaxExtents[cascadeIndex].copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE); - this._frustumCenter[cascadeIndex].copyFromFloats(0, 0, 0); - const camera = this._getCamera(); - if (!camera) { - return; - } - // Calculate the centroid of the view frustum slice - for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) { - this._frustumCenter[cascadeIndex].addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]); - } - this._frustumCenter[cascadeIndex].scaleInPlace(1 / this._frustumCornersWorldSpace[cascadeIndex].length); - if (this.stabilizeCascades) { - // Calculate the radius of a bounding sphere surrounding the frustum corners - let sphereRadius = 0; - for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) { - const dist = this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].subtractToRef(this._frustumCenter[cascadeIndex], tmpv1).length(); - sphereRadius = Math.max(sphereRadius, dist); - } - sphereRadius = Math.ceil(sphereRadius * 16) / 16; - this._cascadeMaxExtents[cascadeIndex].copyFromFloats(sphereRadius, sphereRadius, sphereRadius); - this._cascadeMinExtents[cascadeIndex].copyFromFloats(-sphereRadius, -sphereRadius, -sphereRadius); - } - else { - // Create a temporary view matrix for the light - const lightCameraPos = this._frustumCenter[cascadeIndex]; - this._frustumCenter[cascadeIndex].addToRef(this._lightDirection, tmpv1); // tmpv1 = look at - math_vector_Matrix.LookAtLHToRef(lightCameraPos, tmpv1, UpDir, tmpMatrix); // matrix = lightView - // Calculate an AABB around the frustum corners - for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) { - math_vector_Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex], tmpMatrix, tmpv1); - this._cascadeMinExtents[cascadeIndex].minimizeInPlace(tmpv1); - this._cascadeMaxExtents[cascadeIndex].maximizeInPlace(tmpv1); - } - } - } - _recreateSceneUBOs() { - this._disposeSceneUBOs(); - if (this._sceneUBOs) { - for (let i = 0; i < this._numCascades; ++i) { - this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${i})`)); - } - } - } - /** - * Support test. - */ - static get IsSupported() { - const engine = engineStore_EngineStore.LastCreatedEngine; - if (!engine) { - return false; - } - return engine._features.supportCSM; - } - /** - * Creates a Cascaded Shadow Generator object. - * A ShadowGenerator is the required tool to use the shadows. - * Each directional light casting shadows needs to use its own ShadowGenerator. - * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows - * @param mapSize The size of the texture what stores the shadows. Example : 1024. - * @param light The directional light object generating the shadows. - * @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. - * @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 - * @param useRedTextureType Forces the generator to use a Red instead of a RGBA type for the shadow map texture format (default: true) - */ - constructor(mapSize, light, usefulFloatFirst, camera, useRedTextureType = true) { - if (!CascadedShadowGenerator.IsSupported) { - logger_Logger.Error("CascadedShadowMap is not supported by the current engine."); - return; - } - super(mapSize, light, usefulFloatFirst, camera, useRedTextureType); - this.usePercentageCloserFiltering = true; - } - _initializeGenerator() { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v; - this.penumbraDarkness = (_a = this.penumbraDarkness) !== null && _a !== void 0 ? _a : 1.0; - this._numCascades = (_b = this._numCascades) !== null && _b !== void 0 ? _b : CascadedShadowGenerator.DEFAULT_CASCADES_COUNT; - this.stabilizeCascades = (_c = this.stabilizeCascades) !== null && _c !== void 0 ? _c : false; - this._freezeShadowCastersBoundingInfoObservable = (_d = this._freezeShadowCastersBoundingInfoObservable) !== null && _d !== void 0 ? _d : null; - this.freezeShadowCastersBoundingInfo = (_e = this.freezeShadowCastersBoundingInfo) !== null && _e !== void 0 ? _e : false; - this._scbiMin = (_f = this._scbiMin) !== null && _f !== void 0 ? _f : new math_vector_Vector3(0, 0, 0); - this._scbiMax = (_g = this._scbiMax) !== null && _g !== void 0 ? _g : new math_vector_Vector3(0, 0, 0); - this._shadowCastersBoundingInfo = (_h = this._shadowCastersBoundingInfo) !== null && _h !== void 0 ? _h : new boundingInfo_BoundingInfo(new math_vector_Vector3(0, 0, 0), new math_vector_Vector3(0, 0, 0)); - this._breaksAreDirty = (_j = this._breaksAreDirty) !== null && _j !== void 0 ? _j : true; - this._minDistance = (_k = this._minDistance) !== null && _k !== void 0 ? _k : 0; - this._maxDistance = (_l = this._maxDistance) !== null && _l !== void 0 ? _l : 1; - this._currentLayer = (_m = this._currentLayer) !== null && _m !== void 0 ? _m : 0; - 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; - this._debug = (_r = this._debug) !== null && _r !== void 0 ? _r : false; - this._depthClamp = (_s = this._depthClamp) !== null && _s !== void 0 ? _s : true; - this._cascadeBlendPercentage = (_t = this._cascadeBlendPercentage) !== null && _t !== void 0 ? _t : 0.1; - this._lambda = (_u = this._lambda) !== null && _u !== void 0 ? _u : 0.5; - this._autoCalcDepthBounds = (_v = this._autoCalcDepthBounds) !== null && _v !== void 0 ? _v : false; - this._recreateSceneUBOs(); - super._initializeGenerator(); - } - _createTargetRenderTexture() { - const engine = this._scene.getEngine(); - const size = { width: this._mapSize, height: this._mapSize, layers: this.numCascades }; - this._shadowMap = new renderTargetTexture_RenderTargetTexture(this._light.name + "_CSMShadowMap", size, this._scene, false, true, this._textureType, false, undefined, false, false, undefined, this._useRedTextureType ? 6 : 5); - this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true); - this._shadowMap.noPrePassRenderer = true; - } - _initializeShadowMap() { - super._initializeShadowMap(); - if (this._shadowMap === null) { - return; - } - this._transformMatricesAsArray = new Float32Array(this._numCascades * 16); - this._viewSpaceFrustumsZ = new Array(this._numCascades); - this._frustumLengths = new Array(this._numCascades); - this._lightSizeUVCorrection = new Array(this._numCascades * 2); - this._depthCorrection = new Array(this._numCascades); - this._cascades = []; - this._viewMatrices = []; - this._projectionMatrices = []; - this._transformMatrices = []; - this._cascadeMinExtents = []; - this._cascadeMaxExtents = []; - this._frustumCenter = []; - this._shadowCameraPos = []; - this._frustumCornersWorldSpace = []; - for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) { - this._cascades[cascadeIndex] = { - prevBreakDistance: 0, - breakDistance: 0, - }; - this._viewMatrices[cascadeIndex] = math_vector_Matrix.Zero(); - this._projectionMatrices[cascadeIndex] = math_vector_Matrix.Zero(); - this._transformMatrices[cascadeIndex] = math_vector_Matrix.Zero(); - this._cascadeMinExtents[cascadeIndex] = new math_vector_Vector3(); - this._cascadeMaxExtents[cascadeIndex] = new math_vector_Vector3(); - this._frustumCenter[cascadeIndex] = new math_vector_Vector3(); - this._shadowCameraPos[cascadeIndex] = new math_vector_Vector3(); - this._frustumCornersWorldSpace[cascadeIndex] = new Array(CascadedShadowGenerator._FrustumCornersNDCSpace.length); - for (let i = 0; i < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++i) { - this._frustumCornersWorldSpace[cascadeIndex][i] = new math_vector_Vector3(); - } - } - const engine = this._scene.getEngine(); - this._shadowMap.onBeforeBindObservable.clear(); - this._shadowMap.onBeforeRenderObservable.clear(); - this._shadowMap.onBeforeRenderObservable.add((layer) => { - if (this._sceneUBOs) { - this._scene.setSceneUniformBuffer(this._sceneUBOs[layer]); - } - this._currentLayer = layer; - if (this._filter === shadowGenerator_ShadowGenerator.FILTER_PCF) { - engine.setColorWrite(false); - } - this._scene.setTransformMatrix(this.getCascadeViewMatrix(layer), this.getCascadeProjectionMatrix(layer)); - if (this._useUBO) { - this._scene.getSceneUniformBuffer().unbindEffect(); - this._scene.finalizeSceneUbo(); - } - }); - this._shadowMap.onBeforeBindObservable.add(() => { - var _a; - this._currentSceneUBO = this._scene.getSceneUniformBuffer(); - (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `cascaded shadow map generation for pass id ${engine.currentRenderPassId}`, 1); - if (this._breaksAreDirty) { - this._splitFrustum(); - } - this._computeMatrices(); - }); - this._splitFrustum(); - } - _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect) { - effect.setMatrix("viewProjection", this.getCascadeTransformMatrix(this._currentLayer)); - } - _isReadyCustomDefines(defines) { - defines.push("#define SM_DEPTHCLAMP " + (this._depthClamp && this._filter !== shadowGenerator_ShadowGenerator.FILTER_PCSS ? "1" : "0")); - } - /** - * Prepare all the defines in a material relying on a shadow map at the specified light index. - * @param defines Defines of the material we want to update - * @param lightIndex Index of the light in the enabled light list of the material - */ - prepareDefines(defines, lightIndex) { - super.prepareDefines(defines, lightIndex); - const scene = this._scene; - const light = this._light; - if (!scene.shadowsEnabled || !light.shadowEnabled) { - return; - } - defines["SHADOWCSM" + lightIndex] = true; - defines["SHADOWCSMDEBUG" + lightIndex] = this.debug; - defines["SHADOWCSMNUM_CASCADES" + lightIndex] = this.numCascades; - defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = scene.useRightHandedSystem; - const camera = this._getCamera(); - if (camera && this._shadowMaxZ <= (camera.maxZ || this._shadowMaxZ)) { - defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = true; - } - if (this.cascadeBlendPercentage === 0) { - defines["SHADOWCSMNOBLEND" + lightIndex] = true; - } - } - /** - * Binds the shadow related information inside of an effect (information like near, far, darkness... - * defined in the generator but impacting the effect). - * @param lightIndex Index of the light in the enabled light list of the material owning the effect - * @param effect The effect we are binfing the information for - */ - bindShadowLight(lightIndex, effect) { - const light = this._light; - const scene = this._scene; - if (!scene.shadowsEnabled || !light.shadowEnabled) { - return; - } - const camera = this._getCamera(); - if (!camera) { - return; - } - const shadowMap = this.getShadowMap(); - if (!shadowMap) { - return; - } - const width = shadowMap.getSize().width; - effect.setMatrices("lightMatrix" + lightIndex, this._transformMatricesAsArray); - effect.setArray("viewFrustumZ" + lightIndex, this._viewSpaceFrustumsZ); - effect.setFloat("cascadeBlendFactor" + lightIndex, this.cascadeBlendPercentage === 0 ? 10000 : 1 / this.cascadeBlendPercentage); - effect.setArray("frustumLengths" + lightIndex, this._frustumLengths); - // Only PCF uses depth stencil texture. - if (this._filter === shadowGenerator_ShadowGenerator.FILTER_PCF) { - effect.setDepthStencilTexture("shadowSampler" + lightIndex, shadowMap); - light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex); - } - else if (this._filter === shadowGenerator_ShadowGenerator.FILTER_PCSS) { - for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) { - this._lightSizeUVCorrection[cascadeIndex * 2 + 0] = - cascadeIndex === 0 - ? 1 - : (this._cascadeMaxExtents[0].x - this._cascadeMinExtents[0].x) / (this._cascadeMaxExtents[cascadeIndex].x - this._cascadeMinExtents[cascadeIndex].x); // x correction - this._lightSizeUVCorrection[cascadeIndex * 2 + 1] = - cascadeIndex === 0 - ? 1 - : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[cascadeIndex].y - this._cascadeMinExtents[cascadeIndex].y); // y correction - this._depthCorrection[cascadeIndex] = - cascadeIndex === 0 - ? 1 - : (this._cascadeMaxExtents[cascadeIndex].z - this._cascadeMinExtents[cascadeIndex].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z); - } - effect.setDepthStencilTexture("shadowSampler" + lightIndex, shadowMap); - effect.setTexture("depthSampler" + lightIndex, shadowMap); - effect.setArray2("lightSizeUVCorrection" + lightIndex, this._lightSizeUVCorrection); - effect.setArray("depthCorrection" + lightIndex, this._depthCorrection); - effect.setFloat("penumbraDarkness" + lightIndex, this.penumbraDarkness); - light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / width, this._contactHardeningLightSizeUVRatio * width, this.frustumEdgeFalloff, lightIndex); - } - else { - effect.setTexture("shadowSampler" + lightIndex, shadowMap); - light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex); - } - light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex); - } - /** - * Gets the transformation matrix of the first cascade used to project the meshes into the map from the light point of view. - * (eq to view projection * shadow projection matrices) - * @returns The transform matrix used to create the shadow map - */ - getTransformMatrix() { - return this.getCascadeTransformMatrix(0); - } - /** - * Disposes the ShadowGenerator. - * Returns nothing. - */ - dispose() { - super.dispose(); - if (this._freezeShadowCastersBoundingInfoObservable) { - this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable); - this._freezeShadowCastersBoundingInfoObservable = null; - } - if (this._depthReducer) { - this._depthReducer.dispose(); - this._depthReducer = null; - } - } - /** - * Serializes the shadow generator setup to a json object. - * @returns The serialized JSON object - */ - serialize() { - const serializationObject = super.serialize(); - const shadowMap = this.getShadowMap(); - if (!shadowMap) { - return serializationObject; - } - serializationObject.numCascades = this._numCascades; - serializationObject.debug = this._debug; - serializationObject.stabilizeCascades = this.stabilizeCascades; - serializationObject.lambda = this._lambda; - serializationObject.cascadeBlendPercentage = this.cascadeBlendPercentage; - serializationObject.depthClamp = this._depthClamp; - serializationObject.autoCalcDepthBounds = this.autoCalcDepthBounds; - serializationObject.shadowMaxZ = this._shadowMaxZ; - serializationObject.penumbraDarkness = this.penumbraDarkness; - serializationObject.freezeShadowCastersBoundingInfo = this._freezeShadowCastersBoundingInfo; - serializationObject.minDistance = this.minDistance; - serializationObject.maxDistance = this.maxDistance; - serializationObject.renderList = []; - if (shadowMap.renderList) { - for (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) { - const mesh = shadowMap.renderList[meshIndex]; - serializationObject.renderList.push(mesh.id); - } - } - return serializationObject; - } - /** - * Parses a serialized ShadowGenerator and returns a new ShadowGenerator. - * @param parsedShadowGenerator The JSON object to parse - * @param scene The scene to create the shadow map for - * @returns The parsed shadow generator - */ - static Parse(parsedShadowGenerator, scene) { - const shadowGenerator = shadowGenerator_ShadowGenerator.Parse(parsedShadowGenerator, scene, (mapSize, light, camera) => new CascadedShadowGenerator(mapSize, light, undefined, camera)); - if (parsedShadowGenerator.numCascades !== undefined) { - shadowGenerator.numCascades = parsedShadowGenerator.numCascades; - } - if (parsedShadowGenerator.debug !== undefined) { - shadowGenerator.debug = parsedShadowGenerator.debug; - } - if (parsedShadowGenerator.stabilizeCascades !== undefined) { - shadowGenerator.stabilizeCascades = parsedShadowGenerator.stabilizeCascades; - } - if (parsedShadowGenerator.lambda !== undefined) { - shadowGenerator.lambda = parsedShadowGenerator.lambda; - } - if (parsedShadowGenerator.cascadeBlendPercentage !== undefined) { - shadowGenerator.cascadeBlendPercentage = parsedShadowGenerator.cascadeBlendPercentage; - } - if (parsedShadowGenerator.depthClamp !== undefined) { - shadowGenerator.depthClamp = parsedShadowGenerator.depthClamp; - } - if (parsedShadowGenerator.autoCalcDepthBounds !== undefined) { - shadowGenerator.autoCalcDepthBounds = parsedShadowGenerator.autoCalcDepthBounds; - } - if (parsedShadowGenerator.shadowMaxZ !== undefined) { - shadowGenerator.shadowMaxZ = parsedShadowGenerator.shadowMaxZ; - } - if (parsedShadowGenerator.penumbraDarkness !== undefined) { - shadowGenerator.penumbraDarkness = parsedShadowGenerator.penumbraDarkness; - } - if (parsedShadowGenerator.freezeShadowCastersBoundingInfo !== undefined) { - shadowGenerator.freezeShadowCastersBoundingInfo = parsedShadowGenerator.freezeShadowCastersBoundingInfo; - } - if (parsedShadowGenerator.minDistance !== undefined && parsedShadowGenerator.maxDistance !== undefined) { - shadowGenerator.setMinMaxDistance(parsedShadowGenerator.minDistance, parsedShadowGenerator.maxDistance); - } - return shadowGenerator; - } -} -CascadedShadowGenerator._FrustumCornersNDCSpace = [ - new math_vector_Vector3(-1.0, +1.0, -1.0), - new math_vector_Vector3(+1.0, +1.0, -1.0), - new math_vector_Vector3(+1.0, -1.0, -1.0), - new math_vector_Vector3(-1.0, -1.0, -1.0), - new math_vector_Vector3(-1.0, +1.0, +1.0), - new math_vector_Vector3(+1.0, +1.0, +1.0), - new math_vector_Vector3(+1.0, -1.0, +1.0), - new math_vector_Vector3(-1.0, -1.0, +1.0), -]; -/** - * Name of the CSM class - */ -CascadedShadowGenerator.CLASSNAME = "CascadedShadowGenerator"; -/** - * Defines the default number of cascades used by the CSM. - */ -CascadedShadowGenerator.DEFAULT_CASCADES_COUNT = 4; -/** - * Defines the minimum number of cascades used by the CSM. - */ -CascadedShadowGenerator.MIN_CASCADES_COUNT = 2; -/** - * Defines the maximum number of cascades used by the CSM. - */ -CascadedShadowGenerator.MAX_CASCADES_COUNT = 4; -/** - * @internal - */ -CascadedShadowGenerator._SceneComponentInitialization = (_) => { - throw _WarnImport("ShadowGeneratorSceneComponent"); -}; -//# sourceMappingURL=cascadedShadowGenerator.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/Shadows/shadowGeneratorSceneComponent.js - - - - -// Adds the parser to the scene parsers. -AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_SHADOWGENERATOR, (parsedData, scene) => { - // Shadows - if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) { - for (let index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) { - const parsedShadowGenerator = parsedData.shadowGenerators[index]; - if (parsedShadowGenerator.className === CascadedShadowGenerator.CLASSNAME) { - CascadedShadowGenerator.Parse(parsedShadowGenerator, scene); - } - else { - shadowGenerator_ShadowGenerator.Parse(parsedShadowGenerator, scene); - } - // SG would be available on their associated lights - } - } -}); -/** - * Defines the shadow generator component responsible to manage any shadow generators - * in a given scene. - */ -class ShadowGeneratorSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_SHADOWGENERATOR; - this.scene = scene; - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._gatherRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing To Do Here. - } - /** - * Serializes the component data to the specified json object - * @param serializationObject The object to serialize to - */ - serialize(serializationObject) { - // Shadows - serializationObject.shadowGenerators = []; - const lights = this.scene.lights; - for (const light of lights) { - const shadowGenerators = light.getShadowGenerators(); - if (shadowGenerators) { - const iterator = shadowGenerators.values(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const shadowGenerator = key.value; - serializationObject.shadowGenerators.push(shadowGenerator.serialize()); - } - } - } - } - /** - * Adds all the elements from the container to the scene - * @param container the container holding the elements - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - addFromContainer(container) { - // Nothing To Do Here. (directly attached to a light) - } - /** - * Removes all the elements in the container from the scene - * @param container contains the elements to remove - * @param dispose if the removed element should be disposed (default: false) - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - removeFromContainer(container, dispose) { - // Nothing To Do Here. (directly attached to a light) - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - dispose() { - // Nothing To Do Here. - } - _gatherRenderTargets(renderTargets) { - // Shadows - const scene = this.scene; - if (this.scene.shadowsEnabled) { - for (let lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) { - const light = scene.lights[lightIndex]; - const shadowGenerators = light.getShadowGenerators(); - if (light.isEnabled() && light.shadowEnabled && shadowGenerators) { - const iterator = shadowGenerators.values(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const shadowGenerator = key.value; - const shadowMap = shadowGenerator.getShadowMap(); - if (scene.textures.indexOf(shadowMap) !== -1) { - renderTargets.push(shadowMap); - } - } - } - } - } - } -} -shadowGenerator_ShadowGenerator._SceneComponentInitialization = (scene) => { - let component = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_SHADOWGENERATOR); - if (!component) { - component = new ShadowGeneratorSceneComponent(scene); - scene._addComponent(component); - } -}; -//# sourceMappingURL=shadowGeneratorSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/Shadows/index.js - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/pointLight.js - - - - - - -node_Node.AddNodeConstructor("Light_Type_0", (name, scene) => { - return () => new PointLight(name, math_vector_Vector3.Zero(), scene); -}); -/** - * A point light is a light defined by an unique point in world space. - * The light is emitted in every direction from this point. - * A good example of a point light is a standard light bulb. - * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction - */ -class PointLight extends ShadowLight { - /** - * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback - * This specifies what angle the shadow will use to be created. - * - * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. - */ - get shadowAngle() { - return this._shadowAngle; - } - /** - * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback - * This specifies what angle the shadow will use to be created. - * - * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. - */ - set shadowAngle(value) { - this._shadowAngle = value; - this.forceProjectionMatrixCompute(); - } - /** - * Gets the direction if it has been set. - * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback - */ - get direction() { - return this._direction; - } - /** - * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback - */ - set direction(value) { - const previousNeedCube = this.needCube(); - this._direction = value; - if (this.needCube() !== previousNeedCube && this._shadowGenerators) { - const iterator = this._shadowGenerators.values(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const shadowGenerator = key.value; - shadowGenerator.recreateShadowMap(); - } - } - } - /** - * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene. - * A PointLight emits the light in every direction. - * It can cast shadows. - * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it : - * ```javascript - * var pointLight = new PointLight("pl", camera.position, scene); - * ``` - * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction - * @param name The light friendly name - * @param position The position of the point light in the scene - * @param scene The scene the lights belongs to - */ - constructor(name, position, scene) { - super(name, scene); - this._shadowAngle = Math.PI / 2; - this.position = position; - } - /** - * Returns the string "PointLight" - * @returns the class name - */ - getClassName() { - return "PointLight"; - } - /** - * Returns the integer 0. - * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x - */ - getTypeID() { - return light_Light.LIGHTTYPEID_POINTLIGHT; - } - /** - * Specifies whether or not the shadowmap should be a cube texture. - * @returns true if the shadowmap needs to be a cube texture. - */ - needCube() { - return !this.direction; - } - /** - * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer). - * @param faceIndex The index of the face we are computed the direction to generate shadow - * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true - */ - getShadowDirection(faceIndex) { - if (this.direction) { - return super.getShadowDirection(faceIndex); - } - else { - switch (faceIndex) { - case 0: - return new math_vector_Vector3(1.0, 0.0, 0.0); - case 1: - return new math_vector_Vector3(-1.0, 0.0, 0.0); - case 2: - return new math_vector_Vector3(0.0, -1.0, 0.0); - case 3: - return new math_vector_Vector3(0.0, 1.0, 0.0); - case 4: - return new math_vector_Vector3(0.0, 0.0, 1.0); - case 5: - return new math_vector_Vector3(0.0, 0.0, -1.0); - } - } - return math_vector_Vector3.Zero(); - } - /** - * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings : - * - fov = PI / 2 - * - aspect ratio : 1.0 - * - z-near and far equal to the active camera minZ and maxZ. - * Returns the PointLight. - * @param matrix - * @param viewMatrix - * @param renderList - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) { - const activeCamera = this.getScene().activeCamera; - if (!activeCamera) { - return; - } - const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ; - const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ; - const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer; - math_vector_Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer); - } - _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(); - } - /** - * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string). - * @param effect The effect to update - * @param lightIndex The index of the light in the effect to update - * @returns The point light - */ - transferToEffect(effect, lightIndex) { - if (this.computeTransformedInformation()) { - this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex); - } - else { - this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex); - } - this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex); - return this; - } - transferToNodeMaterialEffect(effect, lightDataUniformName) { - if (this.computeTransformedInformation()) { - effect.setFloat3(lightDataUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z); - } - else { - effect.setFloat3(lightDataUniformName, this.position.x, this.position.y, this.position.z); - } - return this; - } - /** - * Prepares the list of defines specific to the light type. - * @param defines the list of defines - * @param lightIndex defines the index of the light for the effect - */ - prepareLightSpecificDefines(defines, lightIndex) { - defines["POINTLIGHT" + lightIndex] = true; - } -} -__decorate([ - serialize() -], PointLight.prototype, "shadowAngle", null); -//# sourceMappingURL=pointLight.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Lights/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Loading/loadingScreen.js - -/** - * Class used for the default loading screen - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen - */ -class DefaultLoadingScreen { - /** - * Creates a new default loading screen - * @param _renderingCanvas defines the canvas used to render the scene - * @param _loadingText defines the default text to display - * @param _loadingDivBackgroundColor defines the default background color - */ - constructor(_renderingCanvas, _loadingText = "", _loadingDivBackgroundColor = "black") { - this._renderingCanvas = _renderingCanvas; - this._loadingText = _loadingText; - this._loadingDivBackgroundColor = _loadingDivBackgroundColor; - // Resize - this._resizeLoadingUI = () => { - const canvasRect = this._renderingCanvas.getBoundingClientRect(); - const canvasPositioning = window.getComputedStyle(this._renderingCanvas).position; - if (!this._loadingDiv) { - return; - } - this._loadingDiv.style.position = canvasPositioning === "fixed" ? "fixed" : "absolute"; - this._loadingDiv.style.left = canvasRect.left + "px"; - this._loadingDiv.style.top = canvasRect.top + "px"; - this._loadingDiv.style.width = canvasRect.width + "px"; - this._loadingDiv.style.height = canvasRect.height + "px"; - }; - } - /** - * Function called to display the loading screen - */ - displayLoadingUI() { - if (this._loadingDiv) { - // Do not add a loading screen if there is already one - 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"; - // Loading text - 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); - //set the predefined text - this._loadingTextDiv.innerHTML = this._loadingText; - // Generating keyframes - this._style = document.createElement("style"); - this._style.type = "text/css"; - const keyFrames = `@-webkit-keyframes spin1 {\ - 0% { -webkit-transform: rotate(0deg);} - 100% { -webkit-transform: rotate(360deg);} - }\ - @keyframes spin1 {\ - 0% { transform: rotate(0deg);} - 100% { transform: rotate(360deg);} - }`; - this._style.innerHTML = keyFrames; - document.getElementsByTagName("head")[0].appendChild(this._style); - const svgSupport = !!window.SVGSVGElement; - // Loading img - const imgBack = new Image(); - if (!DefaultLoadingScreen.DefaultLogoUrl) { - imgBack.src = !svgSupport - ? "https://cdn.babylonjs.com/Assets/babylonLogo.png" - : `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+`; - } - else { - imgBack.src = DefaultLoadingScreen.DefaultLogoUrl; - } - imgBack.style.width = "150px"; - imgBack.style.gridColumn = "1"; - imgBack.style.gridRow = "1"; - imgBack.style.top = "50%"; - imgBack.style.left = "50%"; - imgBack.style.transform = "translate(-50%, -50%)"; - imgBack.style.position = "absolute"; - const imageSpinnerContainer = document.createElement("div"); - imageSpinnerContainer.style.width = "300px"; - imageSpinnerContainer.style.gridColumn = "1"; - imageSpinnerContainer.style.gridRow = "1"; - imageSpinnerContainer.style.top = "50%"; - imageSpinnerContainer.style.left = "50%"; - imageSpinnerContainer.style.transform = "translate(-50%, -50%)"; - imageSpinnerContainer.style.position = "absolute"; - // Loading spinner - const imgSpinner = new Image(); - if (!DefaultLoadingScreen.DefaultSpinnerUrl) { - imgSpinner.src = !svgSupport - ? "https://cdn.babylonjs.com/Assets/loadingIcon.png" - : `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==`; - } - else { - imgSpinner.src = DefaultLoadingScreen.DefaultSpinnerUrl; - } - imgSpinner.style.animation = "spin1 0.75s infinite linear"; - imgSpinner.style.webkitAnimation = "spin1 0.75s infinite linear"; - imgSpinner.style.transformOrigin = "50% 50%"; - imgSpinner.style.webkitTransformOrigin = "50% 50%"; - if (!svgSupport) { - const logoSize = { w: 16, h: 18.5 }; - const loadingSize = { w: 30, h: 30 }; - // set styling correctly - imgBack.style.width = `${logoSize.w}vh`; - imgBack.style.height = `${logoSize.h}vh`; - imgBack.style.left = `calc(50% - ${logoSize.w / 2}vh)`; - imgBack.style.top = `calc(50% - ${logoSize.h / 2}vh)`; - imgSpinner.style.width = `${loadingSize.w}vh`; - imgSpinner.style.height = `${loadingSize.h}vh`; - imgSpinner.style.left = `calc(50% - ${loadingSize.w / 2}vh)`; - imgSpinner.style.top = `calc(50% - ${loadingSize.h / 2}vh)`; - } - imageSpinnerContainer.appendChild(imgSpinner); - this._loadingDiv.appendChild(imgBack); - this._loadingDiv.appendChild(imageSpinnerContainer); - this._resizeLoadingUI(); - window.addEventListener("resize", this._resizeLoadingUI); - this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor; - document.body.appendChild(this._loadingDiv); - this._loadingDiv.style.opacity = "1"; - } - /** - * Function called to hide the loading screen - */ - hideLoadingUI() { - if (!this._loadingDiv) { - return; - } - const onTransitionEnd = () => { - if (this._loadingTextDiv) { - this._loadingTextDiv.remove(); - this._loadingTextDiv = null; - } - if (this._loadingDiv) { - this._loadingDiv.remove(); - this._loadingDiv = null; - } - if (this._style) { - this._style.remove(); - this._style = null; - } - window.removeEventListener("resize", this._resizeLoadingUI); - }; - this._loadingDiv.style.opacity = "0"; - this._loadingDiv.addEventListener("transitionend", onTransitionEnd); - } - /** - * Gets or sets the text to display while loading - */ - set loadingUIText(text) { - this._loadingText = text; - if (this._loadingTextDiv) { - this._loadingTextDiv.innerHTML = this._loadingText; - } - } - get loadingUIText() { - return this._loadingText; - } - /** - * Gets or sets the color to use for the background - */ - get loadingUIBackgroundColor() { - return this._loadingDivBackgroundColor; - } - set loadingUIBackgroundColor(color) { - this._loadingDivBackgroundColor = color; - if (!this._loadingDiv) { - return; - } - this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor; - } -} -/** Gets or sets the logo url to use for the default loading screen */ -DefaultLoadingScreen.DefaultLogoUrl = ""; -/** Gets or sets the spinner url to use for the default loading screen */ -DefaultLoadingScreen.DefaultSpinnerUrl = ""; -engine_Engine.DefaultLoadingScreenFactory = (canvas) => { - return new DefaultLoadingScreen(canvas); -}; -//# sourceMappingURL=loadingScreen.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/HighDynamicRange/panoramaToCubemap.js - - -/** - * Helper class useful to convert panorama picture to their cubemap representation in 6 faces. - */ -class PanoramaToCubeMapTools { - /** - * Converts a panorama stored in RGB right to left up to down format into a cubemap (6 faces). - * - * @param float32Array The source data. - * @param inputWidth The width of the input panorama. - * @param inputHeight The height of the input panorama. - * @param size The willing size of the generated cubemap (each faces will be size * size pixels) - * @returns The cubemap data - */ - static ConvertPanoramaToCubemap(float32Array, inputWidth, inputHeight, size, supersample = false) { - if (!float32Array) { - throw "ConvertPanoramaToCubemap: input cannot be null"; - } - if (float32Array.length != inputWidth * inputHeight * 3) { - throw "ConvertPanoramaToCubemap: input size is wrong"; - } - const textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight, supersample); - const textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight, supersample); - const textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight, supersample); - const textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight, supersample); - const textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight, supersample); - const textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight, supersample); - return { - front: textureFront, - back: textureBack, - left: textureLeft, - right: textureRight, - up: textureUp, - down: textureDown, - size: size, - type: 1, - format: 4, - gammaSpace: false, - }; - } - static CreateCubemapTexture(texSize, faceData, float32Array, inputWidth, inputHeight, supersample = false) { - const buffer = new ArrayBuffer(texSize * texSize * 4 * 3); - const textureArray = new Float32Array(buffer); - // If supersampling, determine number of samples needed when source texture width is divided for 4 cube faces - const samples = supersample ? Math.max(1, Math.round(inputWidth / 4 / texSize)) : 1; - const sampleFactor = 1 / samples; - const sampleFactorSqr = sampleFactor * sampleFactor; - const rotDX1 = faceData[1].subtract(faceData[0]).scale(sampleFactor / texSize); - const rotDX2 = faceData[3].subtract(faceData[2]).scale(sampleFactor / texSize); - const dy = 1 / texSize; - let fy = 0; - for (let y = 0; y < texSize; y++) { - for (let sy = 0; sy < samples; sy++) { - let xv1 = faceData[0]; - let xv2 = faceData[2]; - for (let x = 0; x < texSize; x++) { - for (let sx = 0; sx < samples; sx++) { - const v = xv2.subtract(xv1).scale(fy).add(xv1); - v.normalize(); - const color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight); - // 3 channels per pixels - textureArray[y * texSize * 3 + x * 3 + 0] += color.r * sampleFactorSqr; - textureArray[y * texSize * 3 + x * 3 + 1] += color.g * sampleFactorSqr; - textureArray[y * texSize * 3 + x * 3 + 2] += color.b * sampleFactorSqr; - xv1 = xv1.add(rotDX1); - xv2 = xv2.add(rotDX2); - } - } - fy += dy * sampleFactor; - } - } - return textureArray; - } - static CalcProjectionSpherical(vDir, float32Array, inputWidth, inputHeight) { - let theta = Math.atan2(vDir.z, vDir.x); - const phi = Math.acos(vDir.y); - while (theta < -Math.PI) { - theta += 2 * Math.PI; - } - while (theta > Math.PI) { - theta -= 2 * Math.PI; - } - let dx = theta / Math.PI; - const dy = phi / Math.PI; - // recenter. - dx = dx * 0.5 + 0.5; - let px = Math.round(dx * inputWidth); - if (px < 0) { - px = 0; - } - else if (px >= inputWidth) { - px = inputWidth - 1; - } - let py = Math.round(dy * inputHeight); - if (py < 0) { - py = 0; - } - else if (py >= inputHeight) { - py = inputHeight - 1; - } - const inputY = inputHeight - py - 1; - const r = float32Array[inputY * inputWidth * 3 + px * 3 + 0]; - const g = float32Array[inputY * inputWidth * 3 + px * 3 + 1]; - const b = float32Array[inputY * inputWidth * 3 + px * 3 + 2]; - return { - r: r, - g: g, - b: b, - }; - } -} -PanoramaToCubeMapTools.FACE_LEFT = [new math_vector_Vector3(-1.0, -1.0, -1.0), new math_vector_Vector3(1.0, -1.0, -1.0), new math_vector_Vector3(-1.0, 1.0, -1.0), new math_vector_Vector3(1.0, 1.0, -1.0)]; -PanoramaToCubeMapTools.FACE_RIGHT = [new math_vector_Vector3(1.0, -1.0, 1.0), new math_vector_Vector3(-1.0, -1.0, 1.0), new math_vector_Vector3(1.0, 1.0, 1.0), new math_vector_Vector3(-1.0, 1.0, 1.0)]; -PanoramaToCubeMapTools.FACE_FRONT = [new math_vector_Vector3(1.0, -1.0, -1.0), new math_vector_Vector3(1.0, -1.0, 1.0), new math_vector_Vector3(1.0, 1.0, -1.0), new math_vector_Vector3(1.0, 1.0, 1.0)]; -PanoramaToCubeMapTools.FACE_BACK = [new math_vector_Vector3(-1.0, -1.0, 1.0), new math_vector_Vector3(-1.0, -1.0, -1.0), new math_vector_Vector3(-1.0, 1.0, 1.0), new math_vector_Vector3(-1.0, 1.0, -1.0)]; -PanoramaToCubeMapTools.FACE_DOWN = [new math_vector_Vector3(1.0, 1.0, -1.0), new math_vector_Vector3(1.0, 1.0, 1.0), new math_vector_Vector3(-1.0, 1.0, -1.0), new math_vector_Vector3(-1.0, 1.0, 1.0)]; -PanoramaToCubeMapTools.FACE_UP = [new math_vector_Vector3(-1.0, -1.0, -1.0), new math_vector_Vector3(-1.0, -1.0, 1.0), new math_vector_Vector3(1.0, -1.0, -1.0), new math_vector_Vector3(1.0, -1.0, 1.0)]; -//# sourceMappingURL=panoramaToCubemap.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/HighDynamicRange/hdr.js - -/** - * This groups tools to convert HDR texture to native colors array. - */ -class HDRTools { - static _Ldexp(mantissa, exponent) { - if (exponent > 1023) { - return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023); - } - if (exponent < -1074) { - return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074); - } - return mantissa * Math.pow(2, exponent); - } - static _Rgbe2float(float32array, red, green, blue, exponent, index) { - if (exponent > 0) { - /*nonzero pixel*/ - exponent = this._Ldexp(1.0, exponent - (128 + 8)); - float32array[index + 0] = red * exponent; - float32array[index + 1] = green * exponent; - float32array[index + 2] = blue * exponent; - } - else { - float32array[index + 0] = 0; - float32array[index + 1] = 0; - float32array[index + 2] = 0; - } - } - static _ReadStringLine(uint8array, startIndex) { - let line = ""; - let character = ""; - for (let i = startIndex; i < uint8array.length - startIndex; i++) { - character = String.fromCharCode(uint8array[i]); - if (character == "\n") { - break; - } - line += character; - } - return line; - } - /** - * Reads header information from an RGBE texture stored in a native array. - * More information on this format are available here: - * https://en.wikipedia.org/wiki/RGBE_image_format - * - * @param uint8array The binary file stored in native array. - * @returns The header information. - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static RGBE_ReadHeader(uint8array) { - let height = 0; - let width = 0; - let line = this._ReadStringLine(uint8array, 0); - if (line[0] != "#" || line[1] != "?") { - throw "Bad HDR Format."; - } - let endOfHeader = false; - let findFormat = false; - let lineIndex = 0; - do { - lineIndex += line.length + 1; - line = this._ReadStringLine(uint8array, lineIndex); - if (line == "FORMAT=32-bit_rle_rgbe") { - findFormat = true; - } - else if (line.length == 0) { - endOfHeader = true; - } - } while (!endOfHeader); - if (!findFormat) { - throw "HDR Bad header format, unsupported FORMAT"; - } - lineIndex += line.length + 1; - line = this._ReadStringLine(uint8array, lineIndex); - const sizeRegexp = /^-Y (.*) \+X (.*)$/g; - const match = sizeRegexp.exec(line); - // TODO. Support +Y and -X if needed. - if (!match || match.length < 3) { - throw "HDR Bad header format, no size"; - } - width = parseInt(match[2]); - height = parseInt(match[1]); - if (width < 8 || width > 0x7fff) { - throw "HDR Bad header format, unsupported size"; - } - lineIndex += line.length + 1; - return { - height: height, - width: width, - dataPosition: lineIndex, - }; - } - /** - * Returns the cubemap information (each faces texture data) extracted from an RGBE texture. - * This RGBE texture needs to store the information as a panorama. - * - * More information on this format are available here: - * https://en.wikipedia.org/wiki/RGBE_image_format - * - * @param buffer The binary file stored in an array buffer. - * @param size The expected size of the extracted cubemap. - * @returns The Cube Map information. - */ - static GetCubeMapTextureData(buffer, size, supersample = false) { - const uint8array = new Uint8Array(buffer); - const hdrInfo = this.RGBE_ReadHeader(uint8array); - const data = this.RGBE_ReadPixels(uint8array, hdrInfo); - const cubeMapData = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size, supersample); - return cubeMapData; - } - /** - * Returns the pixels data extracted from an RGBE texture. - * This pixels will be stored left to right up to down in the R G B order in one array. - * - * More information on this format are available here: - * https://en.wikipedia.org/wiki/RGBE_image_format - * - * @param uint8array The binary file stored in an array buffer. - * @param hdrInfo The header information of the file. - * @returns The pixels data in RGB right to left up to down order. - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static RGBE_ReadPixels(uint8array, hdrInfo) { - return this._RGBEReadPixelsRLE(uint8array, hdrInfo); - } - static _RGBEReadPixelsRLE(uint8array, hdrInfo) { - let num_scanlines = hdrInfo.height; - const scanline_width = hdrInfo.width; - let a, b, c, d, count; - let dataIndex = hdrInfo.dataPosition; - let index = 0, endIndex = 0, i = 0; - const scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E - const scanLineArray = new Uint8Array(scanLineArrayBuffer); - // 3 channels of 4 bytes per pixel in float. - const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3); - const resultArray = new Float32Array(resultBuffer); - // read in each successive scanline - while (num_scanlines > 0) { - a = uint8array[dataIndex++]; - b = uint8array[dataIndex++]; - c = uint8array[dataIndex++]; - d = uint8array[dataIndex++]; - if (a != 2 || b != 2 || c & 0x80 || hdrInfo.width < 8 || hdrInfo.width > 32767) { - return this._RGBEReadPixelsNOTRLE(uint8array, hdrInfo); - } - if (((c << 8) | d) != scanline_width) { - throw "HDR Bad header format, wrong scan line width"; - } - index = 0; - // read each of the four channels for the scanline into the buffer - for (i = 0; i < 4; i++) { - endIndex = (i + 1) * scanline_width; - while (index < endIndex) { - a = uint8array[dataIndex++]; - b = uint8array[dataIndex++]; - if (a > 128) { - // a run of the same value - count = a - 128; - if (count == 0 || count > endIndex - index) { - throw "HDR Bad Format, bad scanline data (run)"; - } - while (count-- > 0) { - scanLineArray[index++] = b; - } - } - else { - // a non-run - count = a; - if (count == 0 || count > endIndex - index) { - throw "HDR Bad Format, bad scanline data (non-run)"; - } - scanLineArray[index++] = b; - if (--count > 0) { - for (let j = 0; j < count; j++) { - scanLineArray[index++] = uint8array[dataIndex++]; - } - } - } - } - } - // now convert data from buffer into floats - for (i = 0; i < scanline_width; i++) { - a = scanLineArray[i]; - b = scanLineArray[i + scanline_width]; - c = scanLineArray[i + 2 * scanline_width]; - d = scanLineArray[i + 3 * scanline_width]; - this._Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3); - } - num_scanlines--; - } - return resultArray; - } - static _RGBEReadPixelsNOTRLE(uint8array, hdrInfo) { - // this file is not run length encoded - // read values sequentially - let num_scanlines = hdrInfo.height; - const scanline_width = hdrInfo.width; - let a, b, c, d, i; - let dataIndex = hdrInfo.dataPosition; - // 3 channels of 4 bytes per pixel in float. - const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3); - const resultArray = new Float32Array(resultBuffer); - // read in each successive scanline - while (num_scanlines > 0) { - for (i = 0; i < hdrInfo.width; i++) { - a = uint8array[dataIndex++]; - b = uint8array[dataIndex++]; - c = uint8array[dataIndex++]; - d = uint8array[dataIndex++]; - this._Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3); - } - num_scanlines--; - } - return resultArray; - } -} -//# sourceMappingURL=hdr.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/hdrFiltering.vertex.js -// Do not edit. - -const hdrFiltering_vertex_name = "hdrFilteringVertexShader"; -const hdrFiltering_vertex_shader = `attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -mat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[hdrFiltering_vertex_name] = hdrFiltering_vertex_shader; -/** @internal */ -const hdrFilteringVertexShader = { name: hdrFiltering_vertex_name, shader: hdrFiltering_vertex_shader }; -//# sourceMappingURL=hdrFiltering.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/hdrFiltering.fragment.js -// Do not edit. - - - - - -const hdrFiltering_fragment_name = "hdrFilteringPixelShader"; -const hdrFiltering_fragment_shader = `#include<helperFunctions> -#include<importanceSampling> -#include<pbrBRDFFunctions> -#include<hdrFilteringFunctions> -uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`; -// Sideeffect -ShaderStore.ShadersStore[hdrFiltering_fragment_name] = hdrFiltering_fragment_shader; -/** @internal */ -const hdrFilteringPixelShader = { name: hdrFiltering_fragment_name, shader: hdrFiltering_fragment_shader }; -//# sourceMappingURL=hdrFiltering.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Filtering/hdrFiltering.js - - - - - - - -/** - * Filters HDR maps to get correct renderings of PBR reflections - */ -class HDRFiltering { - /** - * Instantiates HDR filter for reflection maps - * - * @param engine Thin engine - * @param options Options - */ - constructor(engine, options = {}) { - this._lodGenerationOffset = 0; - this._lodGenerationScale = 0.8; - /** - * Quality switch for prefiltering. Should be set to `4096` unless - * you care about baking speed. - */ - this.quality = 4096; - /** - * Scales pixel intensity for the input HDR map. - */ - this.hdrScale = 1; - // pass - this._engine = engine; - this.hdrScale = options.hdrScale || this.hdrScale; - this.quality = options.quality || this.quality; - } - _createRenderTarget(size) { - let textureType = 0; - if (this._engine.getCaps().textureHalfFloatRender) { - textureType = 2; - } - else if (this._engine.getCaps().textureFloatRender) { - textureType = 1; - } - const rtWrapper = this._engine.createRenderTargetCubeTexture(size, { - format: 5, - type: textureType, - createMipMaps: true, - generateMipMaps: false, - generateDepthBuffer: false, - generateStencilBuffer: false, - samplingMode: 1, - }); - this._engine.updateTextureWrappingMode(rtWrapper.texture, 0, 0, 0); - this._engine.updateTextureSamplingMode(3, rtWrapper.texture, true); - return rtWrapper; - } - _prefilterInternal(texture) { - const width = texture.getSize().width; - const mipmapsCount = math_scalar_Scalar.ILog2(width) + 1; - const effect = this._effectWrapper.effect; - const outputTexture = this._createRenderTarget(width); - this._effectRenderer.saveStates(); - this._effectRenderer.setViewport(); - const intTexture = texture.getInternalTexture(); - if (intTexture) { - // Just in case generate fresh clean mips. - this._engine.updateTextureSamplingMode(3, intTexture, true); - } - this._effectRenderer.applyEffectWrapper(this._effectWrapper); - const directions = [ - [new math_vector_Vector3(0, 0, -1), new math_vector_Vector3(0, -1, 0), new math_vector_Vector3(1, 0, 0)], - [new math_vector_Vector3(0, 0, 1), new math_vector_Vector3(0, -1, 0), new math_vector_Vector3(-1, 0, 0)], - [new math_vector_Vector3(1, 0, 0), new math_vector_Vector3(0, 0, 1), new math_vector_Vector3(0, 1, 0)], - [new math_vector_Vector3(1, 0, 0), new math_vector_Vector3(0, 0, -1), new math_vector_Vector3(0, -1, 0)], - [new math_vector_Vector3(1, 0, 0), new math_vector_Vector3(0, -1, 0), new math_vector_Vector3(0, 0, 1)], - [new math_vector_Vector3(-1, 0, 0), new math_vector_Vector3(0, -1, 0), new math_vector_Vector3(0, 0, -1)], // NegativeZ - ]; - effect.setFloat("hdrScale", this.hdrScale); - effect.setFloat2("vFilteringInfo", texture.getSize().width, mipmapsCount); - effect.setTexture("inputTexture", texture); - for (let face = 0; face < 6; face++) { - effect.setVector3("up", directions[face][0]); - effect.setVector3("right", directions[face][1]); - effect.setVector3("front", directions[face][2]); - for (let lod = 0; lod < mipmapsCount; lod++) { - this._engine.bindFramebuffer(outputTexture, face, undefined, undefined, true, lod); - this._effectRenderer.applyEffectWrapper(this._effectWrapper); - let alpha = Math.pow(2, (lod - this._lodGenerationOffset) / this._lodGenerationScale) / width; - if (lod === 0) { - alpha = 0; - } - effect.setFloat("alphaG", alpha); - this._effectRenderer.draw(); - } - } - // Cleanup - this._effectRenderer.restoreStates(); - this._engine.restoreDefaultFramebuffer(); - this._engine._releaseTexture(texture._texture); - // Internal Swap - const type = outputTexture.texture.type; - const format = outputTexture.texture.format; - outputTexture._swapAndDie(texture._texture); - texture._texture.type = type; - texture._texture.format = format; - // New settings - texture.gammaSpace = false; - texture.lodGenerationOffset = this._lodGenerationOffset; - texture.lodGenerationScale = this._lodGenerationScale; - texture._prefiltered = true; - return texture; - } - _createEffect(texture, onCompiled) { - const defines = []; - if (texture.gammaSpace) { - defines.push("#define GAMMA_INPUT"); - } - defines.push("#define NUM_SAMPLES " + this.quality + "u"); // unsigned int - const effectWrapper = new EffectWrapper({ - engine: this._engine, - name: "hdrFiltering", - vertexShader: "hdrFiltering", - fragmentShader: "hdrFiltering", - samplerNames: ["inputTexture"], - uniformNames: ["vSampleDirections", "vWeights", "up", "right", "front", "vFilteringInfo", "hdrScale", "alphaG"], - useShaderStore: true, - defines, - onCompiled: onCompiled, - }); - return effectWrapper; - } - /** - * Get a value indicating if the filter is ready to be used - * @param texture Texture to filter - * @returns true if the filter is ready - */ - isReady(texture) { - return texture.isReady() && this._effectWrapper.effect.isReady(); - } - /** - * Prefilters a cube texture to have mipmap levels representing roughness values. - * Prefiltering will be invoked at the end of next rendering pass. - * This has to be done once the map is loaded, and has not been prefiltered by a third party software. - * See http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf for more information - * @param texture Texture to filter - * @param onFinished Callback when filtering is done - * @returns Promise called when prefiltering is done - */ - prefilter(texture, onFinished = null) { - if (!this._engine._features.allowTexturePrefiltering) { - logger_Logger.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."); - return Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."); - } - return new Promise((resolve) => { - this._effectRenderer = new EffectRenderer(this._engine); - this._effectWrapper = this._createEffect(texture); - this._effectWrapper.effect.executeWhenCompiled(() => { - this._prefilterInternal(texture); - this._effectRenderer.dispose(); - this._effectWrapper.dispose(); - resolve(); - if (onFinished) { - onFinished(); - } - }); - }); - } -} -//# sourceMappingURL=hdrFiltering.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/hdrCubeTexture.js - - - - - - - - - - - - - - -/** - * This represents a texture coming from an HDR input. - * - * The only supported format is currently panorama picture stored in RGBE format. - * Example of such files can be found on Poly Haven: https://polyhaven.com/hdris - */ -class hdrCubeTexture_HDRCubeTexture extends baseTexture_BaseTexture { - /** - * Sets whether or not the texture is blocking during loading. - */ - set isBlocking(value) { - this._isBlocking = value; - } - /** - * Gets whether or not the texture is blocking during loading. - */ - get isBlocking() { - return this._isBlocking; - } - /** - * Sets texture matrix rotation angle around Y axis in radians. - */ - set rotationY(value) { - this._rotationY = value; - this.setReflectionTextureMatrix(math_vector_Matrix.RotationY(this._rotationY)); - } - /** - * Gets texture matrix rotation angle around Y axis radians. - */ - get rotationY() { - return this._rotationY; - } - /** - * Gets or sets the size of the bounding box associated with the cube texture - * When defined, the cubemap will switch to local mode - * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity - * @example https://www.babylonjs-playground.com/#RNASML - */ - set boundingBoxSize(value) { - if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { - return; - } - this._boundingBoxSize = value; - const scene = this.getScene(); - if (scene) { - scene.markAllMaterialsAsDirty(1); - } - } - get boundingBoxSize() { - return this._boundingBoxSize; - } - /** - * Instantiates an HDRTexture from the following parameters. - * - * @param url The location of the HDR raw data (Panorama stored in RGBE format) - * @param sceneOrEngine The scene or engine the texture will be used in - * @param size The cubemap desired size (the more it increases the longer the generation will be) - * @param noMipmap Forces to not generate the mipmap if true - * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process - * @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) - * @param prefilterOnLoad Prefilters HDR texture to allow use of this texture as a PBR reflection texture. - * @param onLoad - * @param onError - */ - constructor(url, sceneOrEngine, size, noMipmap = false, generateHarmonics = true, gammaSpace = false, prefilterOnLoad = false, onLoad = null, onError = null, supersample = false) { - var _a; - super(sceneOrEngine); - this._generateHarmonics = true; - this._onError = null; - this._isBlocking = true; - this._rotationY = 0; - /** - * Gets or sets the center of the bounding box associated with the cube texture - * It must define where the camera used to render the texture was set - */ - this.boundingBoxPosition = math_vector_Vector3.Zero(); - /** - * Observable triggered once the texture has been loaded. - */ - this.onLoadObservable = new observable_Observable(); - if (!url) { - return; - } - this._coordinatesMode = texture_Texture.CUBIC_MODE; - this.name = url; - this.url = url; - this.hasAlpha = false; - this.isCube = true; - this._textureMatrix = math_vector_Matrix.Identity(); - this._prefilterOnLoad = prefilterOnLoad; - this._onLoad = () => { - this.onLoadObservable.notifyObservers(this); - if (onLoad) { - onLoad(); - } - }; - this._onError = onError; - this.gammaSpace = gammaSpace; - this._noMipmap = noMipmap; - this._size = size; - this._supersample = supersample; - this._generateHarmonics = generateHarmonics; - this._texture = this._getFromCache(url, this._noMipmap, undefined, undefined, undefined, this.isCube); - if (!this._texture) { - if (!((_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.useDelayedTextureLoading)) { - this._loadTexture(); - } - else { - this.delayLoadState = 4; - } - } - else { - if (this._texture.isReady) { - tools_Tools.SetImmediate(() => this._onLoad()); - } - else { - this._texture.onLoadedObservable.add(this._onLoad); - } - } - } - /** - * Get the current class name of the texture useful for serialization or dynamic coding. - * @returns "HDRCubeTexture" - */ - getClassName() { - return "HDRCubeTexture"; - } - /** - * Occurs when the file is raw .hdr file. - */ - _loadTexture() { - const engine = this._getEngine(); - const caps = engine.getCaps(); - let textureType = 0; - if (caps.textureFloat && caps.textureFloatLinearFiltering) { - textureType = 1; - } - else if (caps.textureHalfFloat && caps.textureHalfFloatLinearFiltering) { - textureType = 2; - } - const callback = (buffer) => { - this.lodGenerationOffset = 0.0; - this.lodGenerationScale = 0.8; - // Extract the raw linear data. - const data = HDRTools.GetCubeMapTextureData(buffer, this._size, this._supersample); - // Generate harmonics if needed. - if (this._generateHarmonics) { - const sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data); - this.sphericalPolynomial = sphericalPolynomial; - } - const results = []; - let byteArray = null; - let shortArray = null; - // Push each faces. - for (let j = 0; j < 6; j++) { - // Create fallback array - if (textureType === 2) { - shortArray = new Uint16Array(this._size * this._size * 3); - } - else if (textureType === 0) { - // 3 channels of 1 bytes per pixel in bytes. - byteArray = new Uint8Array(this._size * this._size * 3); - } - const dataFace = data[hdrCubeTexture_HDRCubeTexture._FacesMapping[j]]; - // If special cases. - if (this.gammaSpace || shortArray || byteArray) { - for (let i = 0; i < this._size * this._size; i++) { - // Put in gamma space if requested. - if (this.gammaSpace) { - dataFace[i * 3 + 0] = Math.pow(dataFace[i * 3 + 0], ToGammaSpace); - dataFace[i * 3 + 1] = Math.pow(dataFace[i * 3 + 1], ToGammaSpace); - dataFace[i * 3 + 2] = Math.pow(dataFace[i * 3 + 2], ToGammaSpace); - } - // Convert to half float texture for fallback. - if (shortArray) { - shortArray[i * 3 + 0] = ToHalfFloat(dataFace[i * 3 + 0]); - shortArray[i * 3 + 1] = ToHalfFloat(dataFace[i * 3 + 1]); - shortArray[i * 3 + 2] = ToHalfFloat(dataFace[i * 3 + 2]); - } - // Convert to int texture for fallback. - if (byteArray) { - let r = Math.max(dataFace[i * 3 + 0] * 255, 0); - let g = Math.max(dataFace[i * 3 + 1] * 255, 0); - let b = Math.max(dataFace[i * 3 + 2] * 255, 0); - // May use luminance instead if the result is not accurate. - const max = Math.max(Math.max(r, g), b); - if (max > 255) { - const scale = 255 / max; - r *= scale; - g *= scale; - b *= scale; - } - byteArray[i * 3 + 0] = r; - byteArray[i * 3 + 1] = g; - byteArray[i * 3 + 2] = b; - } - } - } - if (shortArray) { - results.push(shortArray); - } - else if (byteArray) { - results.push(byteArray); - } - else { - results.push(dataFace); - } - } - return results; - }; - if (engine._features.allowTexturePrefiltering && this._prefilterOnLoad) { - const previousOnLoad = this._onLoad; - const hdrFiltering = new HDRFiltering(engine); - this._onLoad = () => { - hdrFiltering.prefilter(this, previousOnLoad); - }; - } - this._texture = engine.createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, 4, textureType, this._noMipmap, callback, null, this._onLoad, this._onError); - } - clone() { - const newTexture = new hdrCubeTexture_HDRCubeTexture(this.url, this.getScene() || this._getEngine(), this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace); - // Base texture - newTexture.level = this.level; - newTexture.wrapU = this.wrapU; - newTexture.wrapV = this.wrapV; - newTexture.coordinatesIndex = this.coordinatesIndex; - newTexture.coordinatesMode = this.coordinatesMode; - return newTexture; - } - // Methods - delayLoad() { - if (this.delayLoadState !== 4) { - return; - } - this.delayLoadState = 1; - this._texture = this._getFromCache(this.url, this._noMipmap); - if (!this._texture) { - this._loadTexture(); - } - } - /** - * Get the texture reflection matrix used to rotate/transform the reflection. - * @returns the reflection matrix - */ - getReflectionTextureMatrix() { - return this._textureMatrix; - } - /** - * Set the texture reflection matrix used to rotate/transform the reflection. - * @param value Define the reflection matrix to set - */ - setReflectionTextureMatrix(value) { - var _a; - this._textureMatrix = value; - if (value.updateFlag === this._textureMatrix.updateFlag) { - return; - } - if (value.isIdentity() !== this._textureMatrix.isIdentity()) { - (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1); - } - } - /** - * Dispose the texture and release its associated resources. - */ - dispose() { - this.onLoadObservable.clear(); - super.dispose(); - } - /** - * Parses a JSON representation of an HDR Texture in order to create the texture - * @param parsedTexture Define the JSON representation - * @param scene Define the scene the texture should be created in - * @param rootUrl Define the root url in case we need to load relative dependencies - * @returns the newly created texture after parsing - */ - static Parse(parsedTexture, scene, rootUrl) { - let texture = null; - if (parsedTexture.name && !parsedTexture.isRenderTarget) { - texture = new hdrCubeTexture_HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace); - texture.name = parsedTexture.name; - texture.hasAlpha = parsedTexture.hasAlpha; - texture.level = parsedTexture.level; - texture.coordinatesMode = parsedTexture.coordinatesMode; - texture.isBlocking = parsedTexture.isBlocking; - } - if (texture) { - if (parsedTexture.boundingBoxPosition) { - texture.boundingBoxPosition = math_vector_Vector3.FromArray(parsedTexture.boundingBoxPosition); - } - if (parsedTexture.boundingBoxSize) { - texture.boundingBoxSize = math_vector_Vector3.FromArray(parsedTexture.boundingBoxSize); - } - if (parsedTexture.rotationY) { - texture.rotationY = parsedTexture.rotationY; - } - } - return texture; - } - serialize() { - if (!this.name) { - return null; - } - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.hasAlpha = this.hasAlpha; - serializationObject.isCube = true; - serializationObject.level = this.level; - serializationObject.size = this._size; - serializationObject.coordinatesMode = this.coordinatesMode; - serializationObject.useInGammaSpace = this.gammaSpace; - serializationObject.generateHarmonics = this._generateHarmonics; - serializationObject.customType = "BABYLON.HDRCubeTexture"; - serializationObject.noMipmap = this._noMipmap; - serializationObject.isBlocking = this._isBlocking; - serializationObject.rotationY = this._rotationY; - return serializationObject; - } -} -hdrCubeTexture_HDRCubeTexture._FacesMapping = ["right", "left", "up", "down", "front", "back"]; -RegisterClass("BABYLON.HDRCubeTexture", hdrCubeTexture_HDRCubeTexture); -//# sourceMappingURL=hdrCubeTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Morph/morphTarget.js - - - - - - -/** - * Defines a target to use with MorphTargetManager - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets - */ -class MorphTarget { - /** - * Gets or sets the influence of this target (ie. its weight in the overall morphing) - */ - get influence() { - return this._influence; - } - set influence(influence) { - if (this._influence === influence) { - return; - } - const previous = this._influence; - this._influence = influence; - if (this.onInfluenceChanged.hasObservers()) { - this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0); - } - } - /** - * Gets or sets the animation properties override - */ - get animationPropertiesOverride() { - if (!this._animationPropertiesOverride && this._scene) { - return this._scene.animationPropertiesOverride; - } - return this._animationPropertiesOverride; - } - set animationPropertiesOverride(value) { - this._animationPropertiesOverride = value; - } - /** - * Creates a new MorphTarget - * @param name defines the name of the target - * @param influence defines the influence to use - * @param scene defines the scene the morphtarget belongs to - */ - constructor( - /** defines the name of the target */ - name, influence = 0, scene = null) { - this.name = name; - /** - * Gets or sets the list of animations - */ - this.animations = new Array(); - this._positions = null; - this._normals = null; - this._tangents = null; - this._uvs = null; - this._uniqueId = 0; - /** - * Observable raised when the influence changes - */ - this.onInfluenceChanged = new observable_Observable(); - /** @internal */ - this._onDataLayoutChanged = new observable_Observable(); - this._animationPropertiesOverride = null; - this._scene = scene || engineStore_EngineStore.LastCreatedScene; - this.influence = influence; - if (this._scene) { - this._uniqueId = this._scene.getUniqueId(); - } - } - /** - * Gets the unique ID of this manager - */ - get uniqueId() { - return this._uniqueId; - } - /** - * Gets a boolean defining if the target contains position data - */ - get hasPositions() { - return !!this._positions; - } - /** - * Gets a boolean defining if the target contains normal data - */ - get hasNormals() { - return !!this._normals; - } - /** - * Gets a boolean defining if the target contains tangent data - */ - get hasTangents() { - return !!this._tangents; - } - /** - * Gets a boolean defining if the target contains texture coordinates data - */ - get hasUVs() { - return !!this._uvs; - } - /** - * Affects position data to this target - * @param data defines the position data to use - */ - setPositions(data) { - const hadPositions = this.hasPositions; - this._positions = data; - if (hadPositions !== this.hasPositions) { - this._onDataLayoutChanged.notifyObservers(undefined); - } - } - /** - * Gets the position data stored in this target - * @returns a FloatArray containing the position data (or null if not present) - */ - getPositions() { - return this._positions; - } - /** - * Affects normal data to this target - * @param data defines the normal data to use - */ - setNormals(data) { - const hadNormals = this.hasNormals; - this._normals = data; - if (hadNormals !== this.hasNormals) { - this._onDataLayoutChanged.notifyObservers(undefined); - } - } - /** - * Gets the normal data stored in this target - * @returns a FloatArray containing the normal data (or null if not present) - */ - getNormals() { - return this._normals; - } - /** - * Affects tangent data to this target - * @param data defines the tangent data to use - */ - setTangents(data) { - const hadTangents = this.hasTangents; - this._tangents = data; - if (hadTangents !== this.hasTangents) { - this._onDataLayoutChanged.notifyObservers(undefined); - } - } - /** - * Gets the tangent data stored in this target - * @returns a FloatArray containing the tangent data (or null if not present) - */ - getTangents() { - return this._tangents; - } - /** - * Affects texture coordinates data to this target - * @param data defines the texture coordinates data to use - */ - setUVs(data) { - const hadUVs = this.hasUVs; - this._uvs = data; - if (hadUVs !== this.hasUVs) { - this._onDataLayoutChanged.notifyObservers(undefined); - } - } - /** - * Gets the texture coordinates data stored in this target - * @returns a FloatArray containing the texture coordinates data (or null if not present) - */ - getUVs() { - return this._uvs; - } - /** - * Clone the current target - * @returns a new MorphTarget - */ - clone() { - const newOne = decorators_SerializationHelper.Clone(() => new MorphTarget(this.name, this.influence, this._scene), this); - newOne._positions = this._positions; - newOne._normals = this._normals; - newOne._tangents = this._tangents; - newOne._uvs = this._uvs; - return newOne; - } - /** - * Serializes the current target into a Serialization object - * @returns the serialized object - */ - serialize() { - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.influence = this.influence; - serializationObject.positions = Array.prototype.slice.call(this.getPositions()); - if (this.id != null) { - serializationObject.id = this.id; - } - if (this.hasNormals) { - serializationObject.normals = Array.prototype.slice.call(this.getNormals()); - } - if (this.hasTangents) { - serializationObject.tangents = Array.prototype.slice.call(this.getTangents()); - } - if (this.hasUVs) { - serializationObject.uvs = Array.prototype.slice.call(this.getUVs()); - } - // Animations - decorators_SerializationHelper.AppendSerializedAnimations(this, serializationObject); - return serializationObject; - } - /** - * Returns the string "MorphTarget" - * @returns "MorphTarget" - */ - getClassName() { - return "MorphTarget"; - } - // Statics - /** - * Creates a new target from serialized data - * @param serializationObject defines the serialized data to use - * @param scene defines the hosting scene - * @returns a new MorphTarget - */ - static Parse(serializationObject, scene) { - const result = new MorphTarget(serializationObject.name, serializationObject.influence); - result.setPositions(serializationObject.positions); - if (serializationObject.id != null) { - result.id = serializationObject.id; - } - if (serializationObject.normals) { - result.setNormals(serializationObject.normals); - } - if (serializationObject.tangents) { - result.setTangents(serializationObject.tangents); - } - if (serializationObject.uvs) { - result.setUVs(serializationObject.uvs); - } - // Animations - if (serializationObject.animations) { - for (let animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) { - const parsedAnimation = serializationObject.animations[animationIndex]; - const internalClass = GetClass("BABYLON.Animation"); - if (internalClass) { - result.animations.push(internalClass.Parse(parsedAnimation)); - } - } - if (serializationObject.autoAnimate && scene) { - scene.beginAnimation(result, serializationObject.autoAnimateFrom, serializationObject.autoAnimateTo, serializationObject.autoAnimateLoop, serializationObject.autoAnimateSpeed || 1.0); - } - } - return result; - } - /** - * Creates a MorphTarget from mesh data - * @param mesh defines the source mesh - * @param name defines the name to use for the new target - * @param influence defines the influence to attach to the target - * @returns a new MorphTarget - */ - static FromMesh(mesh, name, influence) { - if (!name) { - name = mesh.name; - } - const result = new MorphTarget(name, influence, mesh.getScene()); - result.setPositions(mesh.getVerticesData(buffer_VertexBuffer.PositionKind)); - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)) { - result.setNormals(mesh.getVerticesData(buffer_VertexBuffer.NormalKind)); - } - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)) { - result.setTangents(mesh.getVerticesData(buffer_VertexBuffer.TangentKind)); - } - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - result.setUVs(mesh.getVerticesData(buffer_VertexBuffer.UVKind)); - } - return result; - } -} -__decorate([ - serialize() -], MorphTarget.prototype, "id", void 0); -//# sourceMappingURL=morphTarget.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/rawTexture2DArray.js - - - -/** - * Class used to store 2D array textures containing user data - */ -class RawTexture2DArray extends texture_Texture { - /** - * Gets the number of layers of the texture - */ - get depth() { - return this._depth; - } - /** - * Create a new RawTexture2DArray - * @param data defines the data of the texture - * @param width defines the width of the texture - * @param height defines the height of the texture - * @param depth defines the number of layers of the texture - * @param format defines the texture format to use - * @param scene defines the hosting scene - * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default) - * @param invertY defines if texture must be stored with Y axis inverted - * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default) - * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...) - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - */ - constructor(data, width, height, depth, - /** Gets or sets the texture format to use */ - format, scene, generateMipMaps = true, invertY = false, samplingMode = texture_Texture.TRILINEAR_SAMPLINGMODE, textureType = 0, creationFlags) { - super(null, scene, !generateMipMaps, invertY); - this.format = format; - this._texture = scene.getEngine().createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, null, textureType, creationFlags); - this._depth = depth; - this.is2DArray = true; - } - /** - * Update the texture with new data - * @param data defines the data to store in the texture - */ - update(data) { - if (!this._texture) { - return; - } - this._getEngine().updateRawTexture2DArray(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type); - } - /** - * Creates a RGBA texture from some data. - * @param data Define the texture data - * @param width Define the width of the texture - * @param height Define the height of the texture - * @param depth defines the number of layers of the texture - * @param scene defines the scene the texture will belong to - * @param generateMipMaps Define whether or not to create mip maps for the texture - * @param invertY define if the data should be flipped on Y when uploaded to the GPU - * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) - * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) - * @returns the RGBA texture - */ - static CreateRGBATexture(data, width, height, depth, scene, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0) { - return new RawTexture2DArray(data, width, height, depth, 5, scene, generateMipMaps, invertY, samplingMode, type); - } -} -//# sourceMappingURL=rawTexture2DArray.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Morph/morphTargetManager.js - - - - - - -/** - * This class is used to deform meshes using morphing between different targets - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets - */ -class morphTargetManager_MorphTargetManager { - /** - * Sets a boolean indicating that adding new target or updating an existing target will not update the underlying data buffers - */ - set areUpdatesFrozen(block) { - if (block) { - this._blockCounter++; - } - else { - this._blockCounter--; - if (this._blockCounter <= 0) { - this._blockCounter = 0; - this._syncActiveTargets(true); - } - } - } - get areUpdatesFrozen() { - return this._blockCounter > 0; - } - /** - * Creates a new MorphTargetManager - * @param scene defines the current scene - */ - constructor(scene = null) { - this._targets = new Array(); - this._targetInfluenceChangedObservers = new Array(); - this._targetDataLayoutChangedObservers = new Array(); - this._activeTargets = new SmartArray(16); - this._supportsNormals = false; - this._supportsTangents = false; - this._supportsUVs = false; - this._vertexCount = 0; - this._textureVertexStride = 0; - this._textureWidth = 0; - this._textureHeight = 1; - this._uniqueId = 0; - this._tempInfluences = new Array(); - this._canUseTextureForTargets = false; - this._blockCounter = 0; - /** @internal */ - this._parentContainer = null; - /** - * Gets or sets a boolean indicating if influencers must be optimized (eg. recompiling the shader if less influencers are used) - */ - this.optimizeInfluencers = true; - /** - * Gets or sets a boolean indicating if normals must be morphed - */ - this.enableNormalMorphing = true; - /** - * Gets or sets a boolean indicating if tangents must be morphed - */ - this.enableTangentMorphing = true; - /** - * Gets or sets a boolean indicating if UV must be morphed - */ - this.enableUVMorphing = true; - this._useTextureToStoreTargets = true; - if (!scene) { - scene = engineStore_EngineStore.LastCreatedScene; - } - this._scene = scene; - if (this._scene) { - this._scene.addMorphTargetManager(this); - this._uniqueId = this._scene.getUniqueId(); - const engineCaps = this._scene.getEngine().getCaps(); - this._canUseTextureForTargets = - engineCaps.canUseGLVertexID && engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0 && engineCaps.texture2DArrayMaxLayerCount > 1; - } - } - /** - * Gets the unique ID of this manager - */ - get uniqueId() { - return this._uniqueId; - } - /** - * Gets the number of vertices handled by this manager - */ - get vertexCount() { - return this._vertexCount; - } - /** - * Gets a boolean indicating if this manager supports morphing of normals - */ - get supportsNormals() { - return this._supportsNormals && this.enableNormalMorphing; - } - /** - * Gets a boolean indicating if this manager supports morphing of tangents - */ - get supportsTangents() { - return this._supportsTangents && this.enableTangentMorphing; - } - /** - * Gets a boolean indicating if this manager supports morphing of texture coordinates - */ - get supportsUVs() { - return this._supportsUVs && this.enableUVMorphing; - } - /** - * Gets the number of targets stored in this manager - */ - get numTargets() { - return this._targets.length; - } - /** - * Gets the number of influencers (ie. the number of targets with influences > 0) - */ - get numInfluencers() { - return this._activeTargets.length; - } - /** - * Gets the list of influences (one per target) - */ - get influences() { - return this._influences; - } - /** - * Gets or sets a boolean indicating that targets should be stored as a texture instead of using vertex attributes (default is true). - * Please note that this option is not available if the hardware does not support it - */ - get useTextureToStoreTargets() { - return this._useTextureToStoreTargets; - } - set useTextureToStoreTargets(value) { - this._useTextureToStoreTargets = value; - } - /** - * Gets a boolean indicating that the targets are stored into a texture (instead of as attributes) - */ - get isUsingTextureForTargets() { - var _a; - return (morphTargetManager_MorphTargetManager.EnableTextureStorage && - this.useTextureToStoreTargets && - this._canUseTextureForTargets && - !((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getEngine().getCaps().disableMorphTargetTexture)); - } - /** - * Gets the active target at specified index. An active target is a target with an influence > 0 - * @param index defines the index to check - * @returns the requested target - */ - getActiveTarget(index) { - return this._activeTargets.data[index]; - } - /** - * Gets the target at specified index - * @param index defines the index to check - * @returns the requested target - */ - getTarget(index) { - return this._targets[index]; - } - /** - * Add a new target to this manager - * @param target defines the target to add - */ - addTarget(target) { - this._targets.push(target); - this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add((needUpdate) => { - this._syncActiveTargets(needUpdate); - })); - this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(() => { - this._syncActiveTargets(true); - })); - this._syncActiveTargets(true); - } - /** - * Removes a target from the manager - * @param target defines the target to remove - */ - removeTarget(target) { - const index = this._targets.indexOf(target); - if (index >= 0) { - this._targets.splice(index, 1); - target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]); - target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]); - this._syncActiveTargets(true); - } - if (this._scene) { - this._scene.stopAnimation(target); - } - } - /** - * @internal - */ - _bind(effect) { - effect.setFloat3("morphTargetTextureInfo", this._textureVertexStride, this._textureWidth, this._textureHeight); - effect.setFloatArray("morphTargetTextureIndices", this._morphTargetTextureIndices); - effect.setTexture("morphTargets", this._targetStoreTexture); - } - /** - * Clone the current manager - * @returns a new MorphTargetManager - */ - clone() { - const copy = new morphTargetManager_MorphTargetManager(this._scene); - for (const target of this._targets) { - copy.addTarget(target.clone()); - } - copy.enableNormalMorphing = this.enableNormalMorphing; - copy.enableTangentMorphing = this.enableTangentMorphing; - copy.enableUVMorphing = this.enableUVMorphing; - return copy; - } - /** - * Serializes the current manager into a Serialization object - * @returns the serialized object - */ - serialize() { - const serializationObject = {}; - serializationObject.id = this.uniqueId; - serializationObject.targets = []; - for (const target of this._targets) { - serializationObject.targets.push(target.serialize()); - } - return serializationObject; - } - _syncActiveTargets(needUpdate) { - if (this.areUpdatesFrozen) { - return; - } - let influenceCount = 0; - this._activeTargets.reset(); - this._supportsNormals = true; - this._supportsTangents = true; - this._supportsUVs = true; - this._vertexCount = 0; - if (this._scene && this._targets.length > this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount) { - this.useTextureToStoreTargets = false; - } - if (!this._morphTargetTextureIndices || this._morphTargetTextureIndices.length !== this._targets.length) { - this._morphTargetTextureIndices = new Float32Array(this._targets.length); - } - let targetIndex = -1; - for (const target of this._targets) { - targetIndex++; - if (target.influence === 0 && this.optimizeInfluencers) { - continue; - } - if (this._activeTargets.length >= morphTargetManager_MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode && !this.isUsingTextureForTargets) { - break; - } - this._activeTargets.push(target); - this._morphTargetTextureIndices[influenceCount] = targetIndex; - this._tempInfluences[influenceCount++] = target.influence; - this._supportsNormals = this._supportsNormals && target.hasNormals; - this._supportsTangents = this._supportsTangents && target.hasTangents; - this._supportsUVs = this._supportsUVs && target.hasUVs; - const positions = target.getPositions(); - if (positions) { - const vertexCount = positions.length / 3; - if (this._vertexCount === 0) { - this._vertexCount = vertexCount; - } - else if (this._vertexCount !== vertexCount) { - logger_Logger.Error("Incompatible target. Targets must all have the same vertices count."); - return; - } - } - } - if (this._morphTargetTextureIndices.length !== influenceCount) { - this._morphTargetTextureIndices = this._morphTargetTextureIndices.slice(0, influenceCount); - } - if (!this._influences || this._influences.length !== influenceCount) { - this._influences = new Float32Array(influenceCount); - } - for (let index = 0; index < influenceCount; index++) { - this._influences[index] = this._tempInfluences[index]; - } - if (needUpdate) { - this.synchronize(); - } - } - /** - * Synchronize the targets with all the meshes using this morph target manager - */ - synchronize() { - if (!this._scene || this.areUpdatesFrozen) { - return; - } - if (this.isUsingTextureForTargets && this._vertexCount) { - this._textureVertexStride = 1; - if (this._supportsNormals) { - this._textureVertexStride++; - } - if (this._supportsTangents) { - this._textureVertexStride++; - } - if (this._supportsUVs) { - this._textureVertexStride++; - } - this._textureWidth = this._vertexCount * this._textureVertexStride; - this._textureHeight = 1; - const maxTextureSize = this._scene.getEngine().getCaps().maxTextureSize; - if (this._textureWidth > maxTextureSize) { - this._textureHeight = Math.ceil(this._textureWidth / maxTextureSize); - this._textureWidth = maxTextureSize; - } - let mustUpdateTexture = true; - if (this._targetStoreTexture) { - const textureSize = this._targetStoreTexture.getSize(); - if (textureSize.width === this._textureWidth && textureSize.height === this._textureHeight && this._targetStoreTexture.depth === this._targets.length) { - mustUpdateTexture = false; - } - } - if (mustUpdateTexture) { - if (this._targetStoreTexture) { - this._targetStoreTexture.dispose(); - } - const targetCount = this._targets.length; - const data = new Float32Array(targetCount * this._textureWidth * this._textureHeight * 4); - let offset = 0; - for (let index = 0; index < targetCount; index++) { - const target = this._targets[index]; - const positions = target.getPositions(); - const normals = target.getNormals(); - const uvs = target.getUVs(); - const tangents = target.getTangents(); - if (!positions) { - if (index === 0) { - logger_Logger.Error("Invalid morph target. Target must have positions."); - } - return; - } - offset = index * this._textureWidth * this._textureHeight * 4; - for (let vertex = 0; vertex < this._vertexCount; vertex++) { - data[offset] = positions[vertex * 3]; - data[offset + 1] = positions[vertex * 3 + 1]; - data[offset + 2] = positions[vertex * 3 + 2]; - offset += 4; - if (this._supportsNormals && normals) { - data[offset] = normals[vertex * 3]; - data[offset + 1] = normals[vertex * 3 + 1]; - data[offset + 2] = normals[vertex * 3 + 2]; - offset += 4; - } - if (this._supportsUVs && uvs) { - data[offset] = uvs[vertex * 2]; - data[offset + 1] = uvs[vertex * 2 + 1]; - offset += 4; - } - if (this._supportsTangents && tangents) { - data[offset] = tangents[vertex * 3]; - data[offset + 1] = tangents[vertex * 3 + 1]; - data[offset + 2] = tangents[vertex * 3 + 2]; - offset += 4; - } - } - } - this._targetStoreTexture = RawTexture2DArray.CreateRGBATexture(data, this._textureWidth, this._textureHeight, targetCount, this._scene, false, false, 1, 1); - } - } - // Flag meshes as dirty to resync with the active targets - for (const mesh of this._scene.meshes) { - if (mesh.morphTargetManager === this) { - mesh._syncGeometryWithMorphTargetManager(); - } - } - } - /** - * Release all resources - */ - dispose() { - if (this._targetStoreTexture) { - this._targetStoreTexture.dispose(); - } - this._targetStoreTexture = null; - // Remove from scene - if (this._scene) { - this._scene.removeMorphTargetManager(this); - if (this._parentContainer) { - const index = this._parentContainer.morphTargetManagers.indexOf(this); - if (index > -1) { - this._parentContainer.morphTargetManagers.splice(index, 1); - } - this._parentContainer = null; - } - for (const morph of this._targets) { - this._scene.stopAnimation(morph); - } - } - } - // Statics - /** - * Creates a new MorphTargetManager from serialized data - * @param serializationObject defines the serialized data - * @param scene defines the hosting scene - * @returns the new MorphTargetManager - */ - static Parse(serializationObject, scene) { - const result = new morphTargetManager_MorphTargetManager(scene); - result._uniqueId = serializationObject.id; - for (const targetData of serializationObject.targets) { - result.addTarget(MorphTarget.Parse(targetData, scene)); - } - return result; - } -} -/** Enable storing morph target data into textures when set to true (true by default) */ -morphTargetManager_MorphTargetManager.EnableTextureStorage = true; -/** Maximum number of active morph targets supported in the "vertex attribute" mode (i.e., not the "texture" mode) */ -morphTargetManager_MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode = 8; -//# sourceMappingURL=morphTargetManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/physicsRaycastResult.js - -/** - * Holds the data for the raycast result - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -class PhysicsRaycastResult { - constructor() { - this._hasHit = false; - this._hitDistance = 0; - this._hitNormalWorld = math_vector_Vector3.Zero(); - this._hitPointWorld = math_vector_Vector3.Zero(); - this._rayFromWorld = math_vector_Vector3.Zero(); - this._rayToWorld = math_vector_Vector3.Zero(); - this._triangleIndex = -1; - } - /** - * Gets if there was a hit - */ - get hasHit() { - return this._hasHit; - } - /** - * Gets the distance from the hit - */ - get hitDistance() { - return this._hitDistance; - } - /** - * Gets the hit normal/direction in the world - */ - get hitNormalWorld() { - return this._hitNormalWorld; - } - /** - * Gets the hit point in the world - */ - get hitPointWorld() { - return this._hitPointWorld; - } - /** - * Gets the ray "start point" of the ray in the world - */ - get rayFromWorld() { - return this._rayFromWorld; - } - /** - * Gets the ray "end point" of the ray in the world - */ - get rayToWorld() { - return this._rayToWorld; - } - /* - * The index of the original triangle which was hit. Will be -1 if contact point is not on a mesh shape - */ - get triangleIndex() { - return this._triangleIndex; - } - /** - * Sets the hit data (normal & point in world space) - * @param hitNormalWorld defines the normal in world space - * @param hitPointWorld defines the point in world space - */ - setHitData(hitNormalWorld, hitPointWorld, triangleIndex) { - this._hasHit = true; - this._hitNormalWorld.set(hitNormalWorld.x, hitNormalWorld.y, hitNormalWorld.z); - this._hitPointWorld.set(hitPointWorld.x, hitPointWorld.y, hitPointWorld.z); - this._triangleIndex = triangleIndex !== null && triangleIndex !== void 0 ? triangleIndex : -1; - } - /** - * Sets the distance from the start point to the hit point - * @param distance - */ - setHitDistance(distance) { - this._hitDistance = distance; - } - /** - * Calculates the distance manually - */ - calculateHitDistance() { - this._hitDistance = math_vector_Vector3.Distance(this._rayFromWorld, this._hitPointWorld); - } - /** - * Resets all the values to default - * @param from The from point on world space - * @param to The to point on world space - */ - reset(from = math_vector_Vector3.Zero(), to = math_vector_Vector3.Zero()) { - this._rayFromWorld.copyFrom(from); - this._rayToWorld.copyFrom(to); - this._hasHit = false; - this._hitDistance = 0; - this._hitNormalWorld.setAll(0); - this._hitPointWorld.setAll(0); - this._triangleIndex = -1; - this.body = undefined; - this.bodyIndex = undefined; - } -} -//# sourceMappingURL=physicsRaycastResult.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v1/physicsEngine.js - - -/** - * Class used to control physics engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -class PhysicsEngine { - /** - * - * @returns version - */ - getPluginVersion() { - return this._physicsPlugin.getPluginVersion(); - } - /** - * Factory used to create the default physics plugin. - * @returns The default physics plugin - */ - static DefaultPluginFactory() { - throw _WarnImport("CannonJSPlugin"); - } - /** - * Creates a new Physics Engine - * @param gravity defines the gravity vector used by the simulation - * @param _physicsPlugin defines the plugin to use (CannonJS by default) - */ - constructor(gravity, _physicsPlugin = PhysicsEngine.DefaultPluginFactory()) { - this._physicsPlugin = _physicsPlugin; - /** - * Global value used to control the smallest number supported by the simulation - */ - this._impostors = []; - this._joints = []; - this._subTimeStep = 0; - this._uniqueIdCounter = 0; - if (!this._physicsPlugin.isSupported()) { - throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. " + "Please make sure it is included."); - } - gravity = gravity || new math_vector_Vector3(0, -9.807, 0); - this.setGravity(gravity); - this.setTimeStep(); - } - /** - * Sets the gravity vector used by the simulation - * @param gravity defines the gravity vector to use - */ - setGravity(gravity) { - this.gravity = gravity; - this._physicsPlugin.setGravity(this.gravity); - } - /** - * Set the time step of the physics engine. - * Default is 1/60. - * To slow it down, enter 1/600 for example. - * To speed it up, 1/30 - * @param newTimeStep defines the new timestep to apply to this world. - */ - setTimeStep(newTimeStep = 1 / 60) { - this._physicsPlugin.setTimeStep(newTimeStep); - } - /** - * Get the time step of the physics engine. - * @returns the current time step - */ - getTimeStep() { - return this._physicsPlugin.getTimeStep(); - } - /** - * Set the sub time step of the physics engine. - * Default is 0 meaning there is no sub steps - * To increase physics resolution precision, set a small value (like 1 ms) - * @param subTimeStep defines the new sub timestep used for physics resolution. - */ - setSubTimeStep(subTimeStep = 0) { - this._subTimeStep = subTimeStep; - } - /** - * Get the sub time step of the physics engine. - * @returns the current sub time step - */ - getSubTimeStep() { - return this._subTimeStep; - } - /** - * Release all resources - */ - dispose() { - this._impostors.forEach(function (impostor) { - impostor.dispose(); - }); - this._physicsPlugin.dispose(); - } - /** - * Gets the name of the current physics plugin - * @returns the name of the plugin - */ - getPhysicsPluginName() { - return this._physicsPlugin.name; - } - /** - * Adding a new impostor for the impostor tracking. - * This will be done by the impostor itself. - * @param impostor the impostor to add - */ - addImpostor(impostor) { - this._impostors.push(impostor); - impostor.uniqueId = this._uniqueIdCounter++; - //if no parent, generate the body - if (!impostor.parent) { - this._physicsPlugin.generatePhysicsBody(impostor); - } - } - /** - * Remove an impostor from the engine. - * This impostor and its mesh will not longer be updated by the physics engine. - * @param impostor the impostor to remove - */ - removeImpostor(impostor) { - const index = this._impostors.indexOf(impostor); - if (index > -1) { - const removed = this._impostors.splice(index, 1); - //Is it needed? - if (removed.length) { - this.getPhysicsPlugin().removePhysicsBody(impostor); - } - } - } - /** - * Add a joint to the physics engine - * @param mainImpostor defines the main impostor to which the joint is added. - * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint - * @param joint defines the joint that will connect both impostors. - */ - addJoint(mainImpostor, connectedImpostor, joint) { - const impostorJoint = { - mainImpostor: mainImpostor, - connectedImpostor: connectedImpostor, - joint: joint, - }; - joint.physicsPlugin = this._physicsPlugin; - this._joints.push(impostorJoint); - this._physicsPlugin.generateJoint(impostorJoint); - } - /** - * Removes a joint from the simulation - * @param mainImpostor defines the impostor used with the joint - * @param connectedImpostor defines the other impostor connected to the main one by the joint - * @param joint defines the joint to remove - */ - removeJoint(mainImpostor, connectedImpostor, joint) { - const matchingJoints = this._joints.filter(function (impostorJoint) { - return impostorJoint.connectedImpostor === connectedImpostor && impostorJoint.joint === joint && impostorJoint.mainImpostor === mainImpostor; - }); - if (matchingJoints.length) { - this._physicsPlugin.removeJoint(matchingJoints[0]); - //TODO remove it from the list as well - } - } - /** - * Called by the scene. No need to call it. - * @param delta defines the timespan between frames - */ - _step(delta) { - //check if any mesh has no body / requires an update - this._impostors.forEach((impostor) => { - if (impostor.isBodyInitRequired()) { - this._physicsPlugin.generatePhysicsBody(impostor); - } - }); - if (delta > 0.1) { - delta = 0.1; - } - else if (delta <= 0) { - delta = 1.0 / 60.0; - } - this._physicsPlugin.executeStep(delta, this._impostors); - } - /** - * Gets the current plugin used to run the simulation - * @returns current plugin - */ - getPhysicsPlugin() { - return this._physicsPlugin; - } - /** - * Gets the list of physic impostors - * @returns an array of PhysicsImpostor - */ - getImpostors() { - return this._impostors; - } - /** - * Gets the impostor for a physics enabled object - * @param object defines the object impersonated by the impostor - * @returns the PhysicsImpostor or null if not found - */ - getImpostorForPhysicsObject(object) { - for (let i = 0; i < this._impostors.length; ++i) { - if (this._impostors[i].object === object) { - return this._impostors[i]; - } - } - return null; - } - /** - * Gets the impostor for a physics body object - * @param body defines physics body used by the impostor - * @returns the PhysicsImpostor or null if not found - */ - getImpostorWithPhysicsBody(body) { - for (let i = 0; i < this._impostors.length; ++i) { - if (this._impostors[i].physicsBody === body) { - return this._impostors[i]; - } - } - return null; - } - /** - * Does a raycast in the physics world - * @param from when should the ray start? - * @param to when should the ray end? - * @returns PhysicsRaycastResult - */ - raycast(from, to) { - return this._physicsPlugin.raycast(from, to); - } - /** - * Does a raycast in the physics world - * @param from when should the ray start? - * @param to when should the ray end? - * @param result resulting PhysicsRaycastResult - */ - raycastToRef(from, to, result) { - return this._physicsPlugin.raycastToRef(from, to, result); - } -} -//# sourceMappingURL=physicsEngine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v1/Plugins/cannonJSPlugin.js - - - - - - - - -/** @internal */ -class CannonJSPlugin { - constructor(_useDeltaForWorldStep = true, iterations = 10, cannonInjection = CANNON) { - this._useDeltaForWorldStep = _useDeltaForWorldStep; - this.name = "CannonJSPlugin"; - this._physicsMaterials = new Array(); - this._fixedTimeStep = 1 / 60; - this._physicsBodiesToRemoveAfterStep = new Array(); - this._firstFrame = true; - this._tmpQuaternion = new math_vector_Quaternion(); - this._minus90X = new math_vector_Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475); - this._plus90X = new math_vector_Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475); - this._tmpPosition = math_vector_Vector3.Zero(); - this._tmpDeltaPosition = math_vector_Vector3.Zero(); - this._tmpUnityRotation = new math_vector_Quaternion(); - this.BJSCANNON = cannonInjection; - if (!this.isSupported()) { - logger_Logger.Error("CannonJS is not available. Please make sure you included the js file."); - return; - } - this._extendNamespace(); - this.world = new this.BJSCANNON.World(); - this.world.broadphase = new this.BJSCANNON.NaiveBroadphase(); - this.world.solver.iterations = iterations; - this._cannonRaycastResult = new this.BJSCANNON.RaycastResult(); - this._raycastResult = new PhysicsRaycastResult(); - } - /** - * - * @returns plugin version - */ - getPluginVersion() { - return 1; - } - setGravity(gravity) { - const vec = gravity; - this.world.gravity.set(vec.x, vec.y, vec.z); - } - setTimeStep(timeStep) { - this._fixedTimeStep = timeStep; - } - getTimeStep() { - return this._fixedTimeStep; - } - executeStep(delta, impostors) { - // due to cannon's architecture, the first frame's before-step is skipped. - if (this._firstFrame) { - this._firstFrame = false; - for (const impostor of impostors) { - if (!(impostor.type == physicsImpostor_PhysicsImpostor.HeightmapImpostor || impostor.type === physicsImpostor_PhysicsImpostor.PlaneImpostor)) { - impostor.beforeStep(); - } - } - } - this.world.step(this._useDeltaForWorldStep ? delta : this._fixedTimeStep); - this._removeMarkedPhysicsBodiesFromWorld(); - } - _removeMarkedPhysicsBodiesFromWorld() { - if (this._physicsBodiesToRemoveAfterStep.length > 0) { - this._physicsBodiesToRemoveAfterStep.forEach((physicsBody) => { - if (typeof this.world.removeBody === "function") { - this.world.removeBody(physicsBody); - } - else { - this.world.remove(physicsBody); - } - }); - this._physicsBodiesToRemoveAfterStep.length = 0; - } - } - applyImpulse(impostor, force, contactPoint) { - const worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z); - const impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z); - impostor.physicsBody.applyImpulse(impulse, worldPoint); - } - applyForce(impostor, force, contactPoint) { - const worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z); - const impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z); - impostor.physicsBody.applyForce(impulse, worldPoint); - } - generatePhysicsBody(impostor) { - // When calling forceUpdate generatePhysicsBody is called again, ensure that the updated body does not instantly collide with removed body - this._removeMarkedPhysicsBodiesFromWorld(); - //parent-child relationship. Does this impostor have a parent impostor? - if (impostor.parent) { - if (impostor.physicsBody) { - this.removePhysicsBody(impostor); - //TODO is that needed? - impostor.forceUpdate(); - } - return; - } - //should a new body be created for this impostor? - if (impostor.isBodyInitRequired()) { - const shape = this._createShape(impostor); - if (!shape) { - logger_Logger.Warn("It was not possible to create a physics body for this object."); - return; - } - //unregister events if body is being changed - const oldBody = impostor.physicsBody; - if (oldBody) { - this.removePhysicsBody(impostor); - } - //create the body and material - const material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution")); - const bodyCreationObject = { - mass: impostor.getParam("mass"), - material: material, - }; - // A simple extend, in case native options were used. - const nativeOptions = impostor.getParam("nativeOptions"); - for (const key in nativeOptions) { - if (Object.prototype.hasOwnProperty.call(nativeOptions, key)) { - bodyCreationObject[key] = nativeOptions[key]; - } - } - impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject); - impostor.physicsBody.addEventListener("collide", impostor.onCollide); - this.world.addEventListener("preStep", impostor.beforeStep); - this.world.addEventListener("postStep", impostor.afterStep); - impostor.physicsBody.addShape(shape); - if (typeof this.world.addBody === "function") { - this.world.addBody(impostor.physicsBody); - } - else { - this.world.add(impostor.physicsBody); - } - //try to keep the body moving in the right direction by taking old properties. - //Should be tested! - if (oldBody) { - ["force", "torque", "velocity", "angularVelocity"].forEach(function (param) { - const vec = oldBody[param]; - impostor.physicsBody[param].set(vec.x, vec.y, vec.z); - }); - } - this._processChildMeshes(impostor); - } - //now update the body's transformation - this._updatePhysicsBodyTransformation(impostor); - } - _processChildMeshes(mainImpostor) { - const meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : []; - const mainRotation = mainImpostor.object.rotationQuaternion; - if (mainRotation) { - mainRotation.conjugateToRef(this._tmpQuaternion); - } - else { - this._tmpQuaternion.set(0, 0, 0, 1); - } - if (meshChildren.length) { - const processMesh = (mesh) => { - if (!mesh.rotationQuaternion) { - return; - } - const childImpostor = mesh.getPhysicsImpostor(); - if (childImpostor) { - const parent = childImpostor.parent; - if (parent !== mainImpostor && mesh.parent) { - const pPosition = mesh.getAbsolutePosition().subtract(mesh.parent.getAbsolutePosition()); - const q = mesh.rotationQuaternion.multiply(this._tmpQuaternion); - if (childImpostor.physicsBody) { - this.removePhysicsBody(childImpostor); - childImpostor.physicsBody = null; - } - childImpostor.parent = mainImpostor; - childImpostor.resetUpdateFlags(); - 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)); - //Add the mass of the children. - mainImpostor.physicsBody.mass += childImpostor.getParam("mass"); - } - } - mesh.getChildMeshes(true) - .filter((m) => !!m.physicsImpostor) - .forEach(processMesh); - }; - meshChildren.filter((m) => !!m.physicsImpostor).forEach(processMesh); - } - } - removePhysicsBody(impostor) { - impostor.physicsBody.removeEventListener("collide", impostor.onCollide); - this.world.removeEventListener("preStep", impostor.beforeStep); - this.world.removeEventListener("postStep", impostor.afterStep); - // Only remove the physics body after the physics step to avoid disrupting cannon's internal state - if (this._physicsBodiesToRemoveAfterStep.indexOf(impostor.physicsBody) === -1) { - this._physicsBodiesToRemoveAfterStep.push(impostor.physicsBody); - } - } - generateJoint(impostorJoint) { - const mainBody = impostorJoint.mainImpostor.physicsBody; - const connectedBody = impostorJoint.connectedImpostor.physicsBody; - if (!mainBody || !connectedBody) { - return; - } - let constraint; - const jointData = impostorJoint.joint.jointData; - //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html - const constraintData = { - pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().set(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z) : null, - pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().set(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z) : null, - axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().set(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z) : null, - axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().set(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z) : null, - maxForce: jointData.nativeParams.maxForce, - collideConnected: !!jointData.collision, - }; - switch (impostorJoint.joint.type) { - case PhysicsJoint.HingeJoint: - case PhysicsJoint.Hinge2Joint: - constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData); - break; - case PhysicsJoint.DistanceJoint: - constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2); - break; - case PhysicsJoint.SpringJoint: { - const springData = jointData; - constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, { - restLength: springData.length, - stiffness: springData.stiffness, - damping: springData.damping, - localAnchorA: constraintData.pivotA, - localAnchorB: constraintData.pivotB, - }); - break; - } - case PhysicsJoint.LockJoint: - constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData); - break; - case PhysicsJoint.PointToPointJoint: - case PhysicsJoint.BallAndSocketJoint: - default: - constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotB, constraintData.maxForce); - break; - } - //set the collideConnected flag after the creation, since DistanceJoint ignores it. - constraint.collideConnected = !!jointData.collision; - impostorJoint.joint.physicsJoint = constraint; - //don't add spring as constraint, as it is not one. - if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) { - this.world.addConstraint(constraint); - } - else { - impostorJoint.joint.jointData.forceApplicationCallback = - impostorJoint.joint.jointData.forceApplicationCallback || - function () { - constraint.applyForce(); - }; - impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback); - } - } - removeJoint(impostorJoint) { - if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) { - this.world.removeConstraint(impostorJoint.joint.physicsJoint); - } - else { - impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback); - } - } - _addMaterial(name, friction, restitution) { - let index; - let mat; - for (index = 0; index < this._physicsMaterials.length; index++) { - mat = this._physicsMaterials[index]; - if (mat.friction === friction && mat.restitution === restitution) { - return mat; - } - } - const currentMat = new this.BJSCANNON.Material(name); - currentMat.friction = friction; - currentMat.restitution = restitution; - this._physicsMaterials.push(currentMat); - return currentMat; - } - _checkWithEpsilon(value) { - return value < math_constants_Epsilon ? math_constants_Epsilon : value; - } - _createShape(impostor) { - const object = impostor.object; - let returnValue; - const impostorExtents = impostor.getObjectExtents(); - switch (impostor.type) { - case physicsImpostor_PhysicsImpostor.SphereImpostor: { - const radiusX = impostorExtents.x; - const radiusY = impostorExtents.y; - const radiusZ = impostorExtents.z; - returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2); - break; - } - //TMP also for cylinder - TODO Cannon supports cylinder natively. - case physicsImpostor_PhysicsImpostor.CylinderImpostor: { - let nativeParams = impostor.getParam("nativeOptions"); - if (!nativeParams) { - nativeParams = {}; - } - const radiusTop = nativeParams.radiusTop !== undefined ? nativeParams.radiusTop : this._checkWithEpsilon(impostorExtents.x) / 2; - const radiusBottom = nativeParams.radiusBottom !== undefined ? nativeParams.radiusBottom : this._checkWithEpsilon(impostorExtents.x) / 2; - const height = nativeParams.height !== undefined ? nativeParams.height : this._checkWithEpsilon(impostorExtents.y); - const numSegments = nativeParams.numSegments !== undefined ? nativeParams.numSegments : 16; - returnValue = new this.BJSCANNON.Cylinder(radiusTop, radiusBottom, height, numSegments); - // Rotate 90 degrees as this shape is horizontal in cannon - const quat = new this.BJSCANNON.Quaternion(); - quat.setFromAxisAngle(new this.BJSCANNON.Vec3(1, 0, 0), -Math.PI / 2); - const translation = new this.BJSCANNON.Vec3(0, 0, 0); - returnValue.transformAllPoints(translation, quat); - break; - } - case physicsImpostor_PhysicsImpostor.BoxImpostor: { - const box = impostorExtents.scale(0.5); - returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z))); - break; - } - case physicsImpostor_PhysicsImpostor.PlaneImpostor: - logger_Logger.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"); - returnValue = new this.BJSCANNON.Plane(); - break; - case physicsImpostor_PhysicsImpostor.MeshImpostor: { - // should transform the vertex data to world coordinates!! - const rawVerts = object.getVerticesData ? object.getVerticesData(buffer_VertexBuffer.PositionKind) : []; - const rawFaces = object.getIndices ? object.getIndices() : []; - if (!rawVerts) { - logger_Logger.Warn("Tried to create a MeshImpostor for an object without vertices. This will fail."); - return; - } - // get only scale! so the object could transform correctly. - const oldPosition = object.position.clone(); - const oldRotation = object.rotation && object.rotation.clone(); - const oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone(); - object.position.copyFromFloats(0, 0, 0); - object.rotation && object.rotation.copyFromFloats(0, 0, 0); - object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation()); - object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace(); - const transform = object.computeWorldMatrix(true); - // convert rawVerts to object space - const transformedVertices = new Array(); - let index; - for (index = 0; index < rawVerts.length; index += 3) { - math_vector_Vector3.TransformCoordinates(math_vector_Vector3.FromArray(rawVerts, index), transform).toArray(transformedVertices, index); - } - logger_Logger.Warn("MeshImpostor only collides against spheres."); - returnValue = new this.BJSCANNON.Trimesh(transformedVertices, rawFaces); - //now set back the transformation! - object.position.copyFrom(oldPosition); - oldRotation && object.rotation && object.rotation.copyFrom(oldRotation); - oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion); - break; - } - case physicsImpostor_PhysicsImpostor.HeightmapImpostor: { - const oldPosition2 = object.position.clone(); - const oldRotation2 = object.rotation && object.rotation.clone(); - const oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone(); - object.position.copyFromFloats(0, 0, 0); - object.rotation && object.rotation.copyFromFloats(0, 0, 0); - object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation()); - object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace(); - object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X); - returnValue = this._createHeightmap(object); - object.position.copyFrom(oldPosition2); - oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2); - oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2); - object.computeWorldMatrix(true); - break; - } - case physicsImpostor_PhysicsImpostor.ParticleImpostor: - returnValue = new this.BJSCANNON.Particle(); - break; - case physicsImpostor_PhysicsImpostor.NoImpostor: - returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0, 0, 0)); - break; - } - return returnValue; - } - _createHeightmap(object, pointDepth) { - let pos = object.getVerticesData(buffer_VertexBuffer.PositionKind); - const transform = object.computeWorldMatrix(true); - // convert rawVerts to object space - const transformedVertices = new Array(); - let index; - for (index = 0; index < pos.length; index += 3) { - math_vector_Vector3.TransformCoordinates(math_vector_Vector3.FromArray(pos, index), transform).toArray(transformedVertices, index); - } - pos = transformedVertices; - const matrix = new Array(); - //For now pointDepth will not be used and will be automatically calculated. - //Future reference - try and find the best place to add a reference to the pointDepth variable. - const arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1); - const boundingInfo = object.getBoundingInfo(); - const dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y); - const minY = boundingInfo.boundingBox.extendSizeWorld.z; - const elementSize = (dim * 2) / arraySize; - for (let i = 0; i < pos.length; i = i + 3) { - const x = Math.round(pos[i + 0] / elementSize + arraySize / 2); - const z = Math.round((pos[i + 1] / elementSize - arraySize / 2) * -1); - const y = -pos[i + 2] + minY; - if (!matrix[x]) { - matrix[x] = []; - } - if (!matrix[x][z]) { - matrix[x][z] = y; - } - matrix[x][z] = Math.max(y, matrix[x][z]); - } - for (let x = 0; x <= arraySize; ++x) { - if (!matrix[x]) { - let loc = 1; - while (!matrix[(x + loc) % arraySize]) { - loc++; - } - matrix[x] = matrix[(x + loc) % arraySize].slice(); - //console.log("missing x", x); - } - for (let z = 0; z <= arraySize; ++z) { - if (!matrix[x][z]) { - let loc = 1; - let newValue; - while (newValue === undefined) { - newValue = matrix[x][(z + loc++) % arraySize]; - } - matrix[x][z] = newValue; - } - } - } - const shape = new this.BJSCANNON.Heightfield(matrix, { - elementSize: elementSize, - }); - //For future reference, needed for body transformation - shape.minY = minY; - return shape; - } - _updatePhysicsBodyTransformation(impostor) { - const object = impostor.object; - //make sure it is updated... - object.computeWorldMatrix && object.computeWorldMatrix(true); - if (!object.getBoundingInfo()) { - return; - } - const center = impostor.getObjectCenter(); - //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld) - // The delta between the mesh position and the mesh bounding box center - this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center)); - this._tmpDeltaPosition.divideInPlace(impostor.object.scaling); - this._tmpPosition.copyFrom(center); - let quaternion = object.rotationQuaternion; - if (!quaternion) { - return; - } - //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis. - //ideally these would be rotated at time of creation like cylinder but they dont extend ConvexPolyhedron - if (impostor.type === physicsImpostor_PhysicsImpostor.PlaneImpostor || impostor.type === physicsImpostor_PhysicsImpostor.HeightmapImpostor) { - //-90 DEG in X, precalculated - quaternion = quaternion.multiply(this._minus90X); - //Invert! (Precalculated, 90 deg in X) - //No need to clone. this will never change. - impostor.setDeltaRotation(this._plus90X); - } - //If it is a heightfield, if should be centered. - if (impostor.type === physicsImpostor_PhysicsImpostor.HeightmapImpostor) { - const mesh = object; - let boundingInfo = mesh.getBoundingInfo(); - //calculate the correct body position: - const rotationQuaternion = mesh.rotationQuaternion; - mesh.rotationQuaternion = this._tmpUnityRotation; - mesh.computeWorldMatrix(true); - //get original center with no rotation - const c = center.clone(); - let oldPivot = mesh.getPivotMatrix(); - if (oldPivot) { - // create a copy the pivot Matrix as it is modified in place - oldPivot = oldPivot.clone(); - } - else { - oldPivot = math_vector_Matrix.Identity(); - } - //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps) - const p = math_vector_Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z); - mesh.setPreTransformMatrix(p); - mesh.computeWorldMatrix(true); - // force bounding box recomputation - boundingInfo = mesh.getBoundingInfo(); - //calculate the translation - const translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate(); - this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z); - //add it inverted to the delta - this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c)); - this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y; - //rotation is back - mesh.rotationQuaternion = rotationQuaternion; - mesh.setPreTransformMatrix(oldPivot); - mesh.computeWorldMatrix(true); - } - else if (impostor.type === physicsImpostor_PhysicsImpostor.MeshImpostor) { - this._tmpDeltaPosition.copyFromFloats(0, 0, 0); - } - impostor.setDeltaPosition(this._tmpDeltaPosition); - //Now update the impostor object - impostor.physicsBody.position.set(this._tmpPosition.x, this._tmpPosition.y, this._tmpPosition.z); - impostor.physicsBody.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w); - } - setTransformationFromPhysicsBody(impostor) { - impostor.object.position.set(impostor.physicsBody.position.x, impostor.physicsBody.position.y, impostor.physicsBody.position.z); - if (impostor.object.rotationQuaternion) { - const q = impostor.physicsBody.quaternion; - impostor.object.rotationQuaternion.set(q.x, q.y, q.z, q.w); - } - } - setPhysicsBodyTransformation(impostor, newPosition, newRotation) { - impostor.physicsBody.position.set(newPosition.x, newPosition.y, newPosition.z); - impostor.physicsBody.quaternion.set(newRotation.x, newRotation.y, newRotation.z, newRotation.w); - } - isSupported() { - return this.BJSCANNON !== undefined; - } - setLinearVelocity(impostor, velocity) { - impostor.physicsBody.velocity.set(velocity.x, velocity.y, velocity.z); - } - setAngularVelocity(impostor, velocity) { - impostor.physicsBody.angularVelocity.set(velocity.x, velocity.y, velocity.z); - } - getLinearVelocity(impostor) { - const v = impostor.physicsBody.velocity; - if (!v) { - return null; - } - return new math_vector_Vector3(v.x, v.y, v.z); - } - getAngularVelocity(impostor) { - const v = impostor.physicsBody.angularVelocity; - if (!v) { - return null; - } - return new math_vector_Vector3(v.x, v.y, v.z); - } - setBodyMass(impostor, mass) { - impostor.physicsBody.mass = mass; - impostor.physicsBody.updateMassProperties(); - } - getBodyMass(impostor) { - return impostor.physicsBody.mass; - } - getBodyFriction(impostor) { - return impostor.physicsBody.material.friction; - } - setBodyFriction(impostor, friction) { - impostor.physicsBody.material.friction = friction; - } - getBodyRestitution(impostor) { - return impostor.physicsBody.material.restitution; - } - setBodyRestitution(impostor, restitution) { - impostor.physicsBody.material.restitution = restitution; - } - sleepBody(impostor) { - impostor.physicsBody.sleep(); - } - wakeUpBody(impostor) { - impostor.physicsBody.wakeUp(); - } - updateDistanceJoint(joint, maxDistance) { - joint.physicsJoint.distance = maxDistance; - } - setMotor(joint, speed, maxForce, motorIndex) { - if (!motorIndex) { - joint.physicsJoint.enableMotor(); - joint.physicsJoint.setMotorSpeed(speed); - if (maxForce) { - this.setLimit(joint, maxForce); - } - } - } - setLimit(joint, minForce, maxForce) { - joint.physicsJoint.motorEquation.maxForce = maxForce; - joint.physicsJoint.motorEquation.minForce = minForce === void 0 ? -minForce : minForce; - } - syncMeshWithImpostor(mesh, impostor) { - const body = impostor.physicsBody; - mesh.position.x = body.position.x; - mesh.position.y = body.position.y; - mesh.position.z = body.position.z; - if (mesh.rotationQuaternion) { - mesh.rotationQuaternion.x = body.quaternion.x; - mesh.rotationQuaternion.y = body.quaternion.y; - mesh.rotationQuaternion.z = body.quaternion.z; - mesh.rotationQuaternion.w = body.quaternion.w; - } - } - getRadius(impostor) { - const shape = impostor.physicsBody.shapes[0]; - return shape.boundingSphereRadius; - } - getBoxSizeToRef(impostor, result) { - const shape = impostor.physicsBody.shapes[0]; - result.x = shape.halfExtents.x * 2; - result.y = shape.halfExtents.y * 2; - result.z = shape.halfExtents.z * 2; - } - dispose() { } - _extendNamespace() { - //this will force cannon to execute at least one step when using interpolation - const step_tmp1 = new this.BJSCANNON.Vec3(); - const engine = this.BJSCANNON; - this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) { - maxSubSteps = maxSubSteps || 10; - timeSinceLastCalled = timeSinceLastCalled || 0; - if (timeSinceLastCalled === 0) { - this.internalStep(dt); - this.time += dt; - } - else { - let internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt); - internalSteps = Math.min(internalSteps, maxSubSteps) || 1; - const t0 = performance.now(); - for (let i = 0; i !== internalSteps; i++) { - this.internalStep(dt); - if (performance.now() - t0 > dt * 1000) { - break; - } - } - this.time += timeSinceLastCalled; - const h = this.time % dt; - const h_div_dt = h / dt; - const interpvelo = step_tmp1; - const bodies = this.bodies; - for (let j = 0; j !== bodies.length; j++) { - const b = bodies[j]; - if (b.type !== engine.Body.STATIC && b.sleepState !== engine.Body.SLEEPING) { - b.position.vsub(b.previousPosition, interpvelo); - interpvelo.scale(h_div_dt, interpvelo); - b.position.vadd(interpvelo, b.interpolatedPosition); - } - else { - b.interpolatedPosition.set(b.position.x, b.position.y, b.position.z); - b.interpolatedQuaternion.set(b.quaternion.x, b.quaternion.y, b.quaternion.z, b.quaternion.w); - } - } - } - }; - } - /** - * Does a raycast in the physics world - * @param from when should the ray start? - * @param to when should the ray end? - * @returns PhysicsRaycastResult - */ - raycast(from, to) { - this._raycastResult.reset(from, to); - this.raycastToRef(from, to, this._raycastResult); - return this._raycastResult; - } - /** - * Does a raycast in the physics world - * @param from when should the ray start? - * @param to when should the ray end? - * @param result resulting PhysicsRaycastResult - */ - raycastToRef(from, to, result) { - this._cannonRaycastResult.reset(); - this.world.raycastClosest(from, to, {}, this._cannonRaycastResult); - result.reset(from, to); - if (this._cannonRaycastResult.hasHit) { - // TODO: do we also want to get the body it hit? - result.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, - }); - result.setHitDistance(this._cannonRaycastResult.distance); - } - } -} -PhysicsEngine.DefaultPluginFactory = () => { - return new CannonJSPlugin(); -}; -//# sourceMappingURL=cannonJSPlugin.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v1/Plugins/oimoJSPlugin.js - - - - - - -/** @internal */ -class OimoJSPlugin { - constructor(_useDeltaForWorldStep = true, iterations, oimoInjection = OIMO) { - this._useDeltaForWorldStep = _useDeltaForWorldStep; - this.name = "OimoJSPlugin"; - this._fixedTimeStep = 1 / 60; - this._tmpImpostorsArray = []; - this._tmpPositionVector = math_vector_Vector3.Zero(); - this.BJSOIMO = oimoInjection; - this.world = new this.BJSOIMO.World({ - iterations: iterations, - }); - this.world.clear(); - this._raycastResult = new PhysicsRaycastResult(); - } - /** - * - * @returns plugin version - */ - getPluginVersion() { - return 1; - } - setGravity(gravity) { - this.world.gravity.set(gravity.x, gravity.y, gravity.z); - } - setTimeStep(timeStep) { - this.world.timeStep = timeStep; - } - getTimeStep() { - return this.world.timeStep; - } - executeStep(delta, impostors) { - impostors.forEach(function (impostor) { - impostor.beforeStep(); - }); - this.world.timeStep = this._useDeltaForWorldStep ? delta : this._fixedTimeStep; - this.world.step(); - impostors.forEach((impostor) => { - impostor.afterStep(); - //update the ordered impostors array - this._tmpImpostorsArray[impostor.uniqueId] = impostor; - }); - //check for collisions - let contact = this.world.contacts; - while (contact !== null) { - if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) { - contact = contact.next; - continue; - } - //is this body colliding with any other? get the impostor - const mainImpostor = this._tmpImpostorsArray[+contact.body1.name]; - const collidingImpostor = this._tmpImpostorsArray[+contact.body2.name]; - if (!mainImpostor || !collidingImpostor) { - contact = contact.next; - continue; - } - mainImpostor.onCollide({ body: collidingImpostor.physicsBody, point: null, distance: 0, impulse: 0, normal: null }); - collidingImpostor.onCollide({ body: mainImpostor.physicsBody, point: null, distance: 0, impulse: 0, normal: null }); - contact = contact.next; - } - } - applyImpulse(impostor, force, contactPoint) { - const mass = impostor.physicsBody.mass; - impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass)); - } - applyForce(impostor, force, contactPoint) { - logger_Logger.Warn("Oimo doesn't support applying force. Using impulse instead."); - this.applyImpulse(impostor, force, contactPoint); - } - generatePhysicsBody(impostor) { - //parent-child relationship. Does this impostor has a parent impostor? - if (impostor.parent) { - if (impostor.physicsBody) { - this.removePhysicsBody(impostor); - //TODO is that needed? - impostor.forceUpdate(); - } - return; - } - if (impostor.isBodyInitRequired()) { - const bodyConfig = { - name: impostor.uniqueId, - //Oimo must have mass, also for static objects. - config: [impostor.getParam("mass") || 0.001, impostor.getParam("friction"), impostor.getParam("restitution")], - size: [], - type: [], - pos: [], - posShape: [], - rot: [], - rotShape: [], - move: impostor.getParam("mass") !== 0, - density: impostor.getParam("mass"), - friction: impostor.getParam("friction"), - restitution: impostor.getParam("restitution"), - //Supporting older versions of Oimo - world: this.world, - }; - const impostors = [impostor]; - const addToArray = (parent) => { - if (!parent.getChildMeshes) { - return; - } - parent.getChildMeshes().forEach(function (m) { - if (m.physicsImpostor) { - impostors.push(m.physicsImpostor); - //m.physicsImpostor._init(); - } - }); - }; - addToArray(impostor.object); - const checkWithEpsilon = (value) => { - return Math.max(value, math_constants_Epsilon); - }; - const globalQuaternion = new math_vector_Quaternion(); - impostors.forEach((i) => { - if (!i.object.rotationQuaternion) { - return; - } - //get the correct bounding box - const oldQuaternion = i.object.rotationQuaternion; - globalQuaternion.copyFrom(oldQuaternion); - i.object.rotationQuaternion.set(0, 0, 0, 1); - i.object.computeWorldMatrix(true); - const rot = globalQuaternion.toEulerAngles(); - const impostorExtents = i.getObjectExtents(); - // eslint-disable-next-line no-loss-of-precision - const radToDeg = 57.295779513082320876; - if (i === impostor) { - const center = impostor.getObjectCenter(); - impostor.object.getAbsolutePivotPoint().subtractToRef(center, this._tmpPositionVector); - this._tmpPositionVector.divideInPlace(impostor.object.scaling); - //Can also use Array.prototype.push.apply - bodyConfig.pos.push(center.x); - bodyConfig.pos.push(center.y); - bodyConfig.pos.push(center.z); - bodyConfig.posShape.push(0, 0, 0); - bodyConfig.rotShape.push(0, 0, 0); - } - else { - const localPosition = i.object.position.clone(); - bodyConfig.posShape.push(localPosition.x); - bodyConfig.posShape.push(localPosition.y); - bodyConfig.posShape.push(localPosition.z); - // bodyConfig.pos.push(0, 0, 0); - bodyConfig.rotShape.push(rot.x * radToDeg, rot.y * radToDeg, rot.z * radToDeg); - } - i.object.rotationQuaternion.copyFrom(globalQuaternion); - // register mesh - switch (i.type) { - case physicsImpostor_PhysicsImpostor.ParticleImpostor: - logger_Logger.Warn("No Particle support in OIMO.js. using SphereImpostor instead"); - // eslint-disable-next-line no-fallthrough - case physicsImpostor_PhysicsImpostor.SphereImpostor: { - const radiusX = impostorExtents.x; - const radiusY = impostorExtents.y; - const radiusZ = impostorExtents.z; - const size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2; - bodyConfig.type.push("sphere"); - //due to the way oimo works with compounds, add 3 times - bodyConfig.size.push(size); - bodyConfig.size.push(size); - bodyConfig.size.push(size); - break; - } - case physicsImpostor_PhysicsImpostor.CylinderImpostor: { - const sizeX = checkWithEpsilon(impostorExtents.x) / 2; - const sizeY = checkWithEpsilon(impostorExtents.y); - bodyConfig.type.push("cylinder"); - bodyConfig.size.push(sizeX); - bodyConfig.size.push(sizeY); - //due to the way oimo works with compounds, add one more value. - bodyConfig.size.push(sizeY); - break; - } - case physicsImpostor_PhysicsImpostor.PlaneImpostor: - case physicsImpostor_PhysicsImpostor.BoxImpostor: - default: { - const sizeX = checkWithEpsilon(impostorExtents.x); - const sizeY = checkWithEpsilon(impostorExtents.y); - const sizeZ = checkWithEpsilon(impostorExtents.z); - bodyConfig.type.push("box"); - //if (i === impostor) { - bodyConfig.size.push(sizeX); - bodyConfig.size.push(sizeY); - bodyConfig.size.push(sizeZ); - //} else { - // bodyConfig.size.push(0,0,0); - //} - break; - } - } - //actually not needed, but hey... - i.object.rotationQuaternion = oldQuaternion; - }); - impostor.physicsBody = this.world.add(bodyConfig); - // set the quaternion, ignoring the previously defined (euler) rotation - impostor.physicsBody.resetQuaternion(globalQuaternion); - // update with delta 0, so the body will receive the new rotation. - impostor.physicsBody.updatePosition(0); - } - else { - this._tmpPositionVector.copyFromFloats(0, 0, 0); - } - impostor.setDeltaPosition(this._tmpPositionVector); - //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center); - //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion); - } - removePhysicsBody(impostor) { - //impostor.physicsBody.dispose(); - this.world.removeRigidBody(impostor.physicsBody); - } - generateJoint(impostorJoint) { - const mainBody = impostorJoint.mainImpostor.physicsBody; - const connectedBody = impostorJoint.connectedImpostor.physicsBody; - if (!mainBody || !connectedBody) { - return; - } - const jointData = impostorJoint.joint.jointData; - const options = jointData.nativeParams || {}; - let type; - const nativeJointData = { - body1: mainBody, - body2: connectedBody, - axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null), - axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null), - pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null), - pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null), - min: options.min, - max: options.max, - collision: options.collision || jointData.collision, - spring: options.spring, - //supporting older version of Oimo - world: this.world, - }; - switch (impostorJoint.joint.type) { - case PhysicsJoint.BallAndSocketJoint: - type = "jointBall"; - break; - case PhysicsJoint.SpringJoint: { - logger_Logger.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead"); - const springData = jointData; - nativeJointData.min = springData.length || nativeJointData.min; - //Max should also be set, just make sure it is at least min - nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max); - } - // eslint-disable-next-line no-fallthrough - case PhysicsJoint.DistanceJoint: - type = "jointDistance"; - nativeJointData.max = jointData.maxDistance; - break; - case PhysicsJoint.PrismaticJoint: - type = "jointPrisme"; - break; - case PhysicsJoint.SliderJoint: - type = "jointSlide"; - break; - case PhysicsJoint.WheelJoint: - type = "jointWheel"; - break; - case PhysicsJoint.HingeJoint: - default: - type = "jointHinge"; - break; - } - nativeJointData.type = type; - impostorJoint.joint.physicsJoint = this.world.add(nativeJointData); - } - removeJoint(impostorJoint) { - //Bug in Oimo prevents us from disposing a joint in the playground - //joint.joint.physicsJoint.dispose(); - //So we will bruteforce it! - try { - this.world.removeJoint(impostorJoint.joint.physicsJoint); - } - catch (e) { - logger_Logger.Warn(e); - } - } - isSupported() { - return this.BJSOIMO !== undefined; - } - setTransformationFromPhysicsBody(impostor) { - if (!impostor.physicsBody.sleeping) { - if (impostor.physicsBody.shapes.next) { - let parent = impostor.physicsBody.shapes; - while (parent.next) { - parent = parent.next; - } - impostor.object.position.set(parent.position.x, parent.position.y, parent.position.z); - } - else { - const pos = impostor.physicsBody.getPosition(); - impostor.object.position.set(pos.x, pos.y, pos.z); - } - if (impostor.object.rotationQuaternion) { - const quat = impostor.physicsBody.getQuaternion(); - impostor.object.rotationQuaternion.set(quat.x, quat.y, quat.z, quat.w); - } - } - } - setPhysicsBodyTransformation(impostor, newPosition, newRotation) { - const body = impostor.physicsBody; - // disable bidirectional for compound meshes - if (impostor.physicsBody.shapes.next) { - return; - } - body.position.set(newPosition.x, newPosition.y, newPosition.z); - body.orientation.set(newRotation.x, newRotation.y, newRotation.z, newRotation.w); - body.syncShapes(); - body.awake(); - } - /*private _getLastShape(body: any): any { - var lastShape = body.shapes; - while (lastShape.next) { - lastShape = lastShape.next; - } - return lastShape; - }*/ - setLinearVelocity(impostor, velocity) { - impostor.physicsBody.linearVelocity.set(velocity.x, velocity.y, velocity.z); - } - setAngularVelocity(impostor, velocity) { - impostor.physicsBody.angularVelocity.set(velocity.x, velocity.y, velocity.z); - } - getLinearVelocity(impostor) { - const v = impostor.physicsBody.linearVelocity; - if (!v) { - return null; - } - return new math_vector_Vector3(v.x, v.y, v.z); - } - getAngularVelocity(impostor) { - const v = impostor.physicsBody.angularVelocity; - if (!v) { - return null; - } - return new math_vector_Vector3(v.x, v.y, v.z); - } - setBodyMass(impostor, mass) { - const staticBody = mass === 0; - //this will actually set the body's density and not its mass. - //But this is how oimo treats the mass variable. - impostor.physicsBody.shapes.density = staticBody ? 1 : mass; - impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1); - } - getBodyMass(impostor) { - return impostor.physicsBody.shapes.density; - } - getBodyFriction(impostor) { - return impostor.physicsBody.shapes.friction; - } - setBodyFriction(impostor, friction) { - impostor.physicsBody.shapes.friction = friction; - } - getBodyRestitution(impostor) { - return impostor.physicsBody.shapes.restitution; - } - setBodyRestitution(impostor, restitution) { - impostor.physicsBody.shapes.restitution = restitution; - } - sleepBody(impostor) { - impostor.physicsBody.sleep(); - } - wakeUpBody(impostor) { - impostor.physicsBody.awake(); - } - updateDistanceJoint(joint, maxDistance, minDistance) { - joint.physicsJoint.limitMotor.upperLimit = maxDistance; - if (minDistance !== void 0) { - joint.physicsJoint.limitMotor.lowerLimit = minDistance; - } - } - setMotor(joint, speed, force, motorIndex) { - if (force !== undefined) { - logger_Logger.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"); - } - else { - force = 1e6; - } - speed *= -1; - //TODO separate rotational and transational motors. - const motor = motorIndex - ? joint.physicsJoint.rotationalLimitMotor2 - : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor; - if (motor) { - motor.setMotor(speed, force); - } - } - setLimit(joint, upperLimit, lowerLimit, motorIndex) { - //TODO separate rotational and transational motors. - const motor = motorIndex - ? joint.physicsJoint.rotationalLimitMotor2 - : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor; - if (motor) { - motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit); - } - } - syncMeshWithImpostor(mesh, impostor) { - const body = impostor.physicsBody; - mesh.position.x = body.position.x; - mesh.position.y = body.position.y; - mesh.position.z = body.position.z; - if (mesh.rotationQuaternion) { - mesh.rotationQuaternion.x = body.orientation.x; - mesh.rotationQuaternion.y = body.orientation.y; - mesh.rotationQuaternion.z = body.orientation.z; - mesh.rotationQuaternion.w = body.orientation.w; - } - } - getRadius(impostor) { - return impostor.physicsBody.shapes.radius; - } - getBoxSizeToRef(impostor, result) { - const shape = impostor.physicsBody.shapes; - result.x = shape.halfWidth * 2; - result.y = shape.halfHeight * 2; - result.z = shape.halfDepth * 2; - } - dispose() { - this.world.clear(); - } - /** - * Does a raycast in the physics world - * @param from when should the ray start? - * @param to when should the ray end? - * @returns PhysicsRaycastResult - */ - raycast(from, to) { - logger_Logger.Warn("raycast is not currently supported by the Oimo physics plugin"); - this._raycastResult.reset(from, to); - return this._raycastResult; - } - /** - * Does a raycast in the physics world - * @param from when should the ray start? - * @param to when should the ray end? - * @param result resulting PhysicsRaycastResult - */ - raycastToRef(from, to, result) { - logger_Logger.Warn("raycast is not currently supported by the Oimo physics plugin"); - result.reset(from, to); - } -} -//# sourceMappingURL=oimoJSPlugin.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v1/Plugins/ammoJSPlugin.js - - - - - - - - - - - -/** - * AmmoJS Physics plugin - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - * @see https://github.com/kripken/ammo.js/ - */ -class AmmoJSPlugin { - /** - * Initializes the ammoJS plugin - * @param _useDeltaForWorldStep if the time between frames should be used when calculating physics steps (Default: true) - * @param ammoInjection can be used to inject your own ammo reference - * @param overlappingPairCache can be used to specify your own overlapping pair cache - */ - constructor(_useDeltaForWorldStep = true, ammoInjection = Ammo, overlappingPairCache = null) { - this._useDeltaForWorldStep = _useDeltaForWorldStep; - /** - * Reference to the Ammo library - */ - this.bjsAMMO = {}; - /** - * Name of the plugin - */ - this.name = "AmmoJSPlugin"; - this._timeStep = 1 / 60; - this._fixedTimeStep = 1 / 60; - this._maxSteps = 5; - this._tmpQuaternion = new math_vector_Quaternion(); - this._tmpContactCallbackResult = false; - this._tmpContactPoint = new math_vector_Vector3(); - this._tmpContactNormal = new math_vector_Vector3(); - this._tmpVec3 = new math_vector_Vector3(); - this._tmpMatrix = new math_vector_Matrix(); - if (typeof ammoInjection === "function") { - logger_Logger.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin."); - return; - } - else { - this.bjsAMMO = ammoInjection; - } - if (!this.isSupported()) { - logger_Logger.Error("AmmoJS is not available. Please make sure you included the js file."); - return; - } - // Initialize the physics world - this._collisionConfiguration = new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration(); - this._dispatcher = new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration); - this._overlappingPairCache = overlappingPairCache || 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 = (contactPoint) => { - contactPoint = this.bjsAMMO.wrapPointer(contactPoint, this.bjsAMMO.btManifoldPoint); - const worldPoint = contactPoint.getPositionWorldOnA(); - const worldNormal = contactPoint.m_normalWorldOnB; - this._tmpContactPoint.x = worldPoint.x(); - this._tmpContactPoint.y = worldPoint.y(); - this._tmpContactPoint.z = worldPoint.z(); - this._tmpContactNormal.x = worldNormal.x(); - this._tmpContactNormal.y = worldNormal.y(); - this._tmpContactNormal.z = worldNormal.z(); - this._tmpContactImpulse = contactPoint.getAppliedImpulse(); - this._tmpContactDistance = contactPoint.getDistance(); - this._tmpContactCallbackResult = true; - }; - this._raycastResult = new PhysicsRaycastResult(); - // Create temp ammo variables - 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); - } - /** - * - * @returns plugin version - */ - getPluginVersion() { - return 1; - } - /** - * Sets the gravity of the physics world (m/(s^2)) - * @param gravity Gravity to set - */ - setGravity(gravity) { - this._tmpAmmoVectorA.setValue(gravity.x, gravity.y, gravity.z); - this.world.setGravity(this._tmpAmmoVectorA); - this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA); - } - /** - * Amount of time to step forward on each frame (only used if useDeltaForWorldStep is false in the constructor) - * @param timeStep timestep to use in seconds - */ - setTimeStep(timeStep) { - this._timeStep = timeStep; - } - /** - * 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) - * @param fixedTimeStep fixedTimeStep to use in seconds - */ - setFixedTimeStep(fixedTimeStep) { - this._fixedTimeStep = fixedTimeStep; - } - /** - * Sets the maximum number of steps by the physics engine per frame (Default: 5) - * @param maxSteps the maximum number of steps by the physics engine per frame - */ - setMaxSteps(maxSteps) { - this._maxSteps = maxSteps; - } - /** - * Gets the current timestep (only used if useDeltaForWorldStep is false in the constructor) - * @returns the current timestep in seconds - */ - getTimeStep() { - return this._timeStep; - } - // Ammo's contactTest and contactPairTest take a callback that runs synchronously, wrap them so that they are easier to consume - _isImpostorInContact(impostor) { - this._tmpContactCallbackResult = false; - this.world.contactTest(impostor.physicsBody, this._tmpAmmoConcreteContactResultCallback); - return this._tmpContactCallbackResult; - } - // Ammo's collision events have some weird quirks - // contactPairTest fires too many events as it fires events even when objects are close together but contactTest does not - // so only fire event if both contactTest and contactPairTest have a hit - _isImpostorPairInContact(impostorA, impostorB) { - this._tmpContactCallbackResult = false; - this.world.contactPairTest(impostorA.physicsBody, impostorB.physicsBody, this._tmpAmmoConcreteContactResultCallback); - return this._tmpContactCallbackResult; - } - // Ammo's behavior when maxSteps > 0 does not behave as described in docs - // @see http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World - // - // When maxSteps is 0 do the entire simulation in one step - // 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) - // Note: To get deterministic physics, timeStep would always need to be divisible by fixedTimeStep - _stepSimulation(timeStep = 1 / 60, maxSteps = 10, fixedTimeStep = 1 / 60) { - if (maxSteps == 0) { - this.world.stepSimulation(timeStep, 0); - } - else { - while (maxSteps > 0 && timeStep > 0) { - if (timeStep - fixedTimeStep < fixedTimeStep) { - this.world.stepSimulation(timeStep, 0); - timeStep = 0; - } - else { - timeStep -= fixedTimeStep; - this.world.stepSimulation(fixedTimeStep, 0); - } - maxSteps--; - } - } - } - /** - * Moves the physics simulation forward delta seconds and updates the given physics imposters - * Prior to the step the imposters physics location is set to the position of the babylon meshes - * After the step the babylon meshes are set to the position of the physics imposters - * @param delta amount of time to step forward - * @param impostors array of imposters to update before/after the step - */ - executeStep(delta, impostors) { - for (const impostor of impostors) { - // Update physics world objects to match babylon world - if (!impostor.soft) { - impostor.beforeStep(); - } - } - this._stepSimulation(this._useDeltaForWorldStep ? delta : this._timeStep, this._maxSteps, this._fixedTimeStep); - for (const mainImpostor of impostors) { - // After physics update make babylon world objects match physics world objects - if (mainImpostor.soft) { - this._afterSoftStep(mainImpostor); - } - else { - mainImpostor.afterStep(); - } - // Handle collision event - if (mainImpostor._onPhysicsCollideCallbacks.length > 0) { - if (this._isImpostorInContact(mainImpostor)) { - for (const collideCallback of mainImpostor._onPhysicsCollideCallbacks) { - for (const otherImpostor of collideCallback.otherImpostors) { - if (mainImpostor.physicsBody.isActive() || otherImpostor.physicsBody.isActive()) { - if (this._isImpostorPairInContact(mainImpostor, otherImpostor)) { - mainImpostor.onCollide({ - body: otherImpostor.physicsBody, - point: this._tmpContactPoint, - distance: this._tmpContactDistance, - impulse: this._tmpContactImpulse, - normal: this._tmpContactNormal, - }); - otherImpostor.onCollide({ - body: mainImpostor.physicsBody, - point: this._tmpContactPoint, - distance: this._tmpContactDistance, - impulse: this._tmpContactImpulse, - normal: this._tmpContactNormal, - }); - } - } - } - } - } - } - } - } - /** - * Update babylon mesh to match physics world object - * @param impostor imposter to match - */ - _afterSoftStep(impostor) { - if (impostor.type === physicsImpostor_PhysicsImpostor.RopeImpostor) { - this._ropeStep(impostor); - } - else { - this._softbodyOrClothStep(impostor); - } - } - /** - * Update babylon mesh vertices vertices to match physics world softbody or cloth - * @param impostor imposter to match - */ - _ropeStep(impostor) { - const bodyVertices = impostor.physicsBody.get_m_nodes(); - const nbVertices = bodyVertices.size(); - let node; - let nodePositions; - let x, y, z; - const path = new Array(); - for (let n = 0; n < nbVertices; n++) { - node = bodyVertices.at(n); - nodePositions = node.get_m_x(); - x = nodePositions.x(); - y = nodePositions.y(); - z = nodePositions.z(); - path.push(new math_vector_Vector3(x, y, z)); - } - const object = impostor.object; - const shape = impostor.getParam("shape"); - if (impostor._isFromLine) { - impostor.object = linesBuilder_CreateLines("lines", { points: path, instance: object }); - } - else { - impostor.object = ExtrudeShape("ext", { shape: shape, path: path, instance: object }); - } - } - /** - * Update babylon mesh vertices vertices to match physics world softbody or cloth - * @param impostor imposter to match - */ - _softbodyOrClothStep(impostor) { - const normalDirection = impostor.type === physicsImpostor_PhysicsImpostor.ClothImpostor ? 1 : -1; - const object = impostor.object; - let vertexPositions = object.getVerticesData(buffer_VertexBuffer.PositionKind); - if (!vertexPositions) { - vertexPositions = []; - } - let vertexNormals = object.getVerticesData(buffer_VertexBuffer.NormalKind); - if (!vertexNormals) { - vertexNormals = []; - } - const nbVertices = vertexPositions.length / 3; - const bodyVertices = impostor.physicsBody.get_m_nodes(); - let node; - let nodePositions; - let x, y, z; - let nx, ny, nz; - for (let n = 0; n < nbVertices; n++) { - node = bodyVertices.at(n); - nodePositions = node.get_m_x(); - x = nodePositions.x(); - y = nodePositions.y(); - z = nodePositions.z() * normalDirection; - const nodeNormals = node.get_m_n(); - nx = nodeNormals.x(); - ny = nodeNormals.y(); - nz = nodeNormals.z() * normalDirection; - vertexPositions[3 * n] = x; - vertexPositions[3 * n + 1] = y; - vertexPositions[3 * n + 2] = z; - vertexNormals[3 * n] = nx; - vertexNormals[3 * n + 1] = ny; - vertexNormals[3 * n + 2] = nz; - } - const vertex_data = new mesh_vertexData_VertexData(); - vertex_data.positions = vertexPositions; - vertex_data.normals = vertexNormals; - vertex_data.uvs = object.getVerticesData(buffer_VertexBuffer.UVKind); - vertex_data.colors = object.getVerticesData(buffer_VertexBuffer.ColorKind); - if (object && object.getIndices) { - vertex_data.indices = object.getIndices(); - } - vertex_data.applyToMesh(object); - } - /** - * Applies an impulse on the imposter - * @param impostor imposter to apply impulse to - * @param force amount of force to be applied to the imposter - * @param contactPoint the location to apply the impulse on the imposter - */ - applyImpulse(impostor, force, contactPoint) { - if (!impostor.soft) { - impostor.physicsBody.activate(); - const worldPoint = this._tmpAmmoVectorA; - const impulse = this._tmpAmmoVectorB; - // Convert contactPoint relative to center of mass - if (impostor.object && impostor.object.getWorldMatrix) { - contactPoint.subtractInPlace(impostor.object.getWorldMatrix().getTranslation()); - } - worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z); - impulse.setValue(force.x, force.y, force.z); - impostor.physicsBody.applyImpulse(impulse, worldPoint); - } - else { - logger_Logger.Warn("Cannot be applied to a soft body"); - } - } - /** - * Applies a force on the imposter - * @param impostor imposter to apply force - * @param force amount of force to be applied to the imposter - * @param contactPoint the location to apply the force on the imposter - */ - applyForce(impostor, force, contactPoint) { - if (!impostor.soft) { - impostor.physicsBody.activate(); - const worldPoint = this._tmpAmmoVectorA; - const impulse = this._tmpAmmoVectorB; - // Convert contactPoint relative to center of mass - if (impostor.object && impostor.object.getWorldMatrix) { - const localTranslation = impostor.object.getWorldMatrix().getTranslation(); - worldPoint.setValue(contactPoint.x - localTranslation.x, contactPoint.y - localTranslation.y, contactPoint.z - localTranslation.z); - } - else { - worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z); - } - impulse.setValue(force.x, force.y, force.z); - impostor.physicsBody.applyForce(impulse, worldPoint); - } - else { - logger_Logger.Warn("Cannot be applied to a soft body"); - } - } - /** - * Creates a physics body using the plugin - * @param impostor the imposter to create the physics body on - */ - generatePhysicsBody(impostor) { - // Note: this method will not be called on child imposotrs for compound impostors - impostor._pluginData.toDispose = []; - //parent-child relationship - if (impostor.parent) { - if (impostor.physicsBody) { - this.removePhysicsBody(impostor); - impostor.forceUpdate(); - } - return; - } - if (impostor.isBodyInitRequired()) { - const colShape = this._createShape(impostor); - const mass = impostor.getParam("mass"); - impostor._pluginData.mass = mass; - if (impostor.soft) { - colShape.get_m_cfg().set_collisions(0x11); - colShape.get_m_cfg().set_kDP(impostor.getParam("damping")); - this.bjsAMMO.castObject(colShape, this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(impostor.getParam("margin")); - colShape.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG); - this.world.addSoftBody(colShape, 1, -1); - impostor.physicsBody = colShape; - impostor._pluginData.toDispose.push(colShape); - this.setBodyPressure(impostor, 0); - if (impostor.type === physicsImpostor_PhysicsImpostor.SoftbodyImpostor) { - this.setBodyPressure(impostor, impostor.getParam("pressure")); - } - this.setBodyStiffness(impostor, impostor.getParam("stiffness")); - this.setBodyVelocityIterations(impostor, impostor.getParam("velocityIterations")); - this.setBodyPositionIterations(impostor, impostor.getParam("positionIterations")); - } - else { - const localInertia = new this.bjsAMMO.btVector3(0, 0, 0); - const startTransform = new this.bjsAMMO.btTransform(); - impostor.object.computeWorldMatrix(true); - startTransform.setIdentity(); - if (mass !== 0) { - colShape.calculateLocalInertia(mass, localInertia); - } - this._tmpAmmoVectorA.setValue(impostor.object.position.x, impostor.object.position.y, impostor.object.position.z); - this._tmpAmmoQuaternion.setValue(impostor.object.rotationQuaternion.x, impostor.object.rotationQuaternion.y, impostor.object.rotationQuaternion.z, impostor.object.rotationQuaternion.w); - startTransform.setOrigin(this._tmpAmmoVectorA); - startTransform.setRotation(this._tmpAmmoQuaternion); - const myMotionState = new this.bjsAMMO.btDefaultMotionState(startTransform); - const rbInfo = new this.bjsAMMO.btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia); - const body = new this.bjsAMMO.btRigidBody(rbInfo); - // Make objects kinematic if it's mass is 0 - if (mass === 0) { - body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin._KINEMATIC_FLAG); - body.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG); - } - // Disable collision if NoImpostor, but keep collision if shape is btCompoundShape - if (impostor.type == physicsImpostor_PhysicsImpostor.NoImpostor && !colShape.getChildShape) { - body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin._DISABLE_COLLISION_FLAG); - } - // compute delta position: compensate the difference between shape center and mesh origin - if (impostor.type !== physicsImpostor_PhysicsImpostor.MeshImpostor && impostor.type !== physicsImpostor_PhysicsImpostor.NoImpostor) { - const boundingInfo = impostor.object.getBoundingInfo(); - this._tmpVec3.copyFrom(impostor.object.getAbsolutePosition()); - this._tmpVec3.subtractInPlace(boundingInfo.boundingBox.centerWorld); - this._tmpVec3.x /= impostor.object.scaling.x; - this._tmpVec3.y /= impostor.object.scaling.y; - this._tmpVec3.z /= impostor.object.scaling.z; - impostor.setDeltaPosition(this._tmpVec3); - } - const group = impostor.getParam("group"); - const mask = impostor.getParam("mask"); - if (group && mask) { - this.world.addRigidBody(body, group, mask); - } - else { - this.world.addRigidBody(body); - } - impostor.physicsBody = body; - impostor._pluginData.toDispose = impostor._pluginData.toDispose.concat([body, rbInfo, myMotionState, startTransform, localInertia, colShape]); - } - this.setBodyRestitution(impostor, impostor.getParam("restitution")); - this.setBodyFriction(impostor, impostor.getParam("friction")); - } - } - /** - * Removes the physics body from the imposter and disposes of the body's memory - * @param impostor imposter to remove the physics body from - */ - removePhysicsBody(impostor) { - if (this.world) { - if (impostor.soft) { - this.world.removeSoftBody(impostor.physicsBody); - } - else { - this.world.removeRigidBody(impostor.physicsBody); - } - if (impostor._pluginData) { - impostor._pluginData.toDispose.forEach((d) => { - this.bjsAMMO.destroy(d); - }); - impostor._pluginData.toDispose = []; - } - } - } - /** - * Generates a joint - * @param impostorJoint the imposter joint to create the joint with - */ - generateJoint(impostorJoint) { - const mainBody = impostorJoint.mainImpostor.physicsBody; - const connectedBody = impostorJoint.connectedImpostor.physicsBody; - if (!mainBody || !connectedBody) { - return; - } - const jointData = impostorJoint.joint.jointData; - if (!jointData.mainPivot) { - jointData.mainPivot = new math_vector_Vector3(0, 0, 0); - } - if (!jointData.connectedPivot) { - jointData.connectedPivot = new math_vector_Vector3(0, 0, 0); - } - let joint; - switch (impostorJoint.joint.type) { - case PhysicsJoint.DistanceJoint: { - const distance = jointData.maxDistance; - if (distance) { - jointData.mainPivot = new math_vector_Vector3(0, -distance / 2, 0); - jointData.connectedPivot = new math_vector_Vector3(0, distance / 2, 0); - } - 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)); - break; - } - case PhysicsJoint.HingeJoint: { - if (!jointData.mainAxis) { - jointData.mainAxis = new math_vector_Vector3(0, 0, 0); - } - if (!jointData.connectedAxis) { - jointData.connectedAxis = new math_vector_Vector3(0, 0, 0); - } - const mainAxis = new this.bjsAMMO.btVector3(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z); - const connectedAxis = new this.bjsAMMO.btVector3(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z); - 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); - break; - } - case PhysicsJoint.BallAndSocketJoint: - 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)); - break; - default: - logger_Logger.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"); - 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)); - break; - } - this.world.addConstraint(joint, !impostorJoint.joint.jointData.collision); - impostorJoint.joint.physicsJoint = joint; - } - /** - * Removes a joint - * @param impostorJoint the imposter joint to remove the joint from - */ - removeJoint(impostorJoint) { - if (this.world) { - this.world.removeConstraint(impostorJoint.joint.physicsJoint); - } - } - // adds all verticies (including child verticies) to the triangle mesh - _addMeshVerts(btTriangleMesh, topLevelObject, object) { - let triangleCount = 0; - if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) { - let indices = object.getIndices(); - if (!indices) { - indices = []; - } - let vertexPositions = object.getVerticesData(buffer_VertexBuffer.PositionKind); - if (!vertexPositions) { - vertexPositions = []; - } - let localMatrix; - if (topLevelObject && topLevelObject !== object) { - // top level matrix used for shape transform doesn't take scale into account. - // Moreover, every children vertex position must be in that space. - // So, each vertex position here is transform by (mesh world matrix * toplevelMatrix -1) - let topLevelQuaternion; - if (topLevelObject.rotationQuaternion) { - topLevelQuaternion = topLevelObject.rotationQuaternion; - } - else if (topLevelObject.rotation) { - topLevelQuaternion = math_vector_Quaternion.FromEulerAngles(topLevelObject.rotation.x, topLevelObject.rotation.y, topLevelObject.rotation.z); - } - else { - topLevelQuaternion = math_vector_Quaternion.Identity(); - } - const topLevelMatrix = math_vector_Matrix.Compose(math_vector_Vector3.One(), topLevelQuaternion, topLevelObject.position); - topLevelMatrix.invertToRef(this._tmpMatrix); - const wm = object.computeWorldMatrix(false); - localMatrix = wm.multiply(this._tmpMatrix); - } - else { - // current top level is same as object level -> only use local scaling - math_vector_Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix); - localMatrix = this._tmpMatrix; - } - const faceCount = indices.length / 3; - for (let i = 0; i < faceCount; i++) { - const triPoints = []; - for (let point = 0; point < 3; point++) { - let v = new math_vector_Vector3(vertexPositions[indices[i * 3 + point] * 3 + 0], vertexPositions[indices[i * 3 + point] * 3 + 1], vertexPositions[indices[i * 3 + point] * 3 + 2]); - v = math_vector_Vector3.TransformCoordinates(v, localMatrix); - let vec; - if (point == 0) { - vec = this._tmpAmmoVectorA; - } - else if (point == 1) { - vec = this._tmpAmmoVectorB; - } - else { - vec = this._tmpAmmoVectorC; - } - vec.setValue(v.x, v.y, v.z); - triPoints.push(vec); - } - btTriangleMesh.addTriangle(triPoints[0], triPoints[1], triPoints[2]); - triangleCount++; - } - object.getChildMeshes().forEach((m) => { - triangleCount += this._addMeshVerts(btTriangleMesh, topLevelObject, m); - }); - } - return triangleCount; - } - /** - * Initialise the soft body vertices to match its object's (mesh) vertices - * Softbody vertices (nodes) are in world space and to match this - * The object's position and rotation is set to zero and so its vertices are also then set in world space - * @param impostor to create the softbody for - */ - _softVertexData(impostor) { - const object = impostor.object; - if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) { - let indices = object.getIndices(); - if (!indices) { - indices = []; - } - let vertexPositions = object.getVerticesData(buffer_VertexBuffer.PositionKind); - if (!vertexPositions) { - vertexPositions = []; - } - let vertexNormals = object.getVerticesData(buffer_VertexBuffer.NormalKind); - if (!vertexNormals) { - vertexNormals = []; - } - object.computeWorldMatrix(false); - const newPoints = []; - const newNorms = []; - for (let i = 0; i < vertexPositions.length; i += 3) { - let v = new math_vector_Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]); - let n = new math_vector_Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]); - v = math_vector_Vector3.TransformCoordinates(v, object.getWorldMatrix()); - n = math_vector_Vector3.TransformNormal(n, object.getWorldMatrix()); - newPoints.push(v.x, v.y, v.z); - newNorms.push(n.x, n.y, n.z); - } - const vertex_data = new mesh_vertexData_VertexData(); - vertex_data.positions = newPoints; - vertex_data.normals = newNorms; - vertex_data.uvs = object.getVerticesData(buffer_VertexBuffer.UVKind); - vertex_data.colors = object.getVerticesData(buffer_VertexBuffer.ColorKind); - if (object && object.getIndices) { - vertex_data.indices = object.getIndices(); - } - vertex_data.applyToMesh(object); - object.position = math_vector_Vector3.Zero(); - object.rotationQuaternion = null; - object.rotation = math_vector_Vector3.Zero(); - object.computeWorldMatrix(true); - return vertex_data; - } - return mesh_vertexData_VertexData.ExtractFromMesh(object); - } - /** - * Create an impostor's soft body - * @param impostor to create the softbody for - */ - _createSoftbody(impostor) { - const object = impostor.object; - if (object && object.getIndices) { - let indices = object.getIndices(); - if (!indices) { - indices = []; - } - const vertex_data = this._softVertexData(impostor); - const vertexPositions = vertex_data.positions; - const vertexNormals = vertex_data.normals; - if (vertexPositions === null || vertexNormals === null) { - return new this.bjsAMMO.btCompoundShape(); - } - else { - const triPoints = []; - const triNorms = []; - for (let i = 0; i < vertexPositions.length; i += 3) { - const v = new math_vector_Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]); - const n = new math_vector_Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]); - triPoints.push(v.x, v.y, -v.z); - triNorms.push(n.x, n.y, -n.z); - } - const softBody = new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(), triPoints, object.getIndices(), indices.length / 3, true); - const nbVertices = vertexPositions.length / 3; - const bodyVertices = softBody.get_m_nodes(); - let node; - let nodeNormals; - for (let i = 0; i < nbVertices; i++) { - node = bodyVertices.at(i); - nodeNormals = node.get_m_n(); - nodeNormals.setX(triNorms[3 * i]); - nodeNormals.setY(triNorms[3 * i + 1]); - nodeNormals.setZ(triNorms[3 * i + 2]); - } - return softBody; - } - } - } - /** - * Create cloth for an impostor - * @param impostor to create the softbody for - */ - _createCloth(impostor) { - const object = impostor.object; - if (object && object.getIndices) { - let indices = object.getIndices(); - if (!indices) { - indices = []; - } - const vertex_data = this._softVertexData(impostor); - const vertexPositions = vertex_data.positions; - const vertexNormals = vertex_data.normals; - if (vertexPositions === null || vertexNormals === null) { - return new this.bjsAMMO.btCompoundShape(); - } - else { - const len = vertexPositions.length; - const segments = Math.sqrt(len / 3); - impostor.segments = segments; - const segs = segments - 1; - this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]); - this._tmpAmmoVectorB.setValue(vertexPositions[3 * segs], vertexPositions[3 * segs + 1], vertexPositions[3 * segs + 2]); - this._tmpAmmoVectorD.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]); - this._tmpAmmoVectorC.setValue(vertexPositions[len - 3 - 3 * segs], vertexPositions[len - 2 - 3 * segs], vertexPositions[len - 1 - 3 * segs]); - const clothBody = new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, this._tmpAmmoVectorC, this._tmpAmmoVectorD, segments, segments, impostor.getParam("fixedPoints"), true); - return clothBody; - } - } - } - /** - * Create rope for an impostor - * @param impostor to create the softbody for - */ - _createRope(impostor) { - let len; - let segments; - const vertex_data = this._softVertexData(impostor); - const vertexPositions = vertex_data.positions; - const vertexNormals = vertex_data.normals; - if (vertexPositions === null || vertexNormals === null) { - return new this.bjsAMMO.btCompoundShape(); - } - //force the mesh to be updatable - vertex_data.applyToMesh(impostor.object, true); - impostor._isFromLine = true; - // If in lines mesh all normals will be zero - const vertexSquared = vertexNormals.map((x) => x * x); - const reducer = (accumulator, currentValue) => accumulator + currentValue; - const reduced = vertexSquared.reduce(reducer); - if (reduced === 0) { - // line mesh - len = vertexPositions.length; - segments = len / 3 - 1; - this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]); - this._tmpAmmoVectorB.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]); - } - else { - //extruded mesh - impostor._isFromLine = false; - const pathVectors = impostor.getParam("path"); - const shape = impostor.getParam("shape"); - if (shape === null) { - logger_Logger.Warn("No shape available for extruded mesh"); - return new this.bjsAMMO.btCompoundShape(); - } - len = pathVectors.length; - segments = len - 1; - this._tmpAmmoVectorA.setValue(pathVectors[0].x, pathVectors[0].y, pathVectors[0].z); - this._tmpAmmoVectorB.setValue(pathVectors[len - 1].x, pathVectors[len - 1].y, pathVectors[len - 1].z); - } - impostor.segments = segments; - let fixedPoints = impostor.getParam("fixedPoints"); - fixedPoints = fixedPoints > 3 ? 3 : fixedPoints; - const ropeBody = new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, segments - 1, fixedPoints); - ropeBody.get_m_cfg().set_collisions(0x11); - return ropeBody; - } - /** - * Create a custom physics impostor shape using the plugin's onCreateCustomShape handler - * @param impostor to create the custom physics shape for - */ - _createCustom(impostor) { - let returnValue = null; - if (this.onCreateCustomShape) { - returnValue = this.onCreateCustomShape(impostor); - } - if (returnValue == null) { - returnValue = new this.bjsAMMO.btCompoundShape(); - } - return returnValue; - } - // adds all verticies (including child verticies) to the convex hull shape - _addHullVerts(btConvexHullShape, topLevelObject, object) { - let triangleCount = 0; - if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) { - let indices = object.getIndices(); - if (!indices) { - indices = []; - } - let vertexPositions = object.getVerticesData(buffer_VertexBuffer.PositionKind); - if (!vertexPositions) { - vertexPositions = []; - } - object.computeWorldMatrix(false); - const faceCount = indices.length / 3; - for (let i = 0; i < faceCount; i++) { - const triPoints = []; - for (let point = 0; point < 3; point++) { - let v = new math_vector_Vector3(vertexPositions[indices[i * 3 + point] * 3 + 0], vertexPositions[indices[i * 3 + point] * 3 + 1], vertexPositions[indices[i * 3 + point] * 3 + 2]); - // Adjust for initial scaling - math_vector_Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix); - v = math_vector_Vector3.TransformCoordinates(v, this._tmpMatrix); - let vec; - if (point == 0) { - vec = this._tmpAmmoVectorA; - } - else if (point == 1) { - vec = this._tmpAmmoVectorB; - } - else { - vec = this._tmpAmmoVectorC; - } - vec.setValue(v.x, v.y, v.z); - triPoints.push(vec); - } - btConvexHullShape.addPoint(triPoints[0], true); - btConvexHullShape.addPoint(triPoints[1], true); - btConvexHullShape.addPoint(triPoints[2], true); - triangleCount++; - } - object.getChildMeshes().forEach((m) => { - triangleCount += this._addHullVerts(btConvexHullShape, topLevelObject, m); - }); - } - return triangleCount; - } - _createShape(impostor, ignoreChildren = false) { - const object = impostor.object; - let returnValue; - const impostorExtents = impostor.getObjectExtents(); - if (!ignoreChildren) { - const meshChildren = impostor.object.getChildMeshes ? impostor.object.getChildMeshes(true) : []; - returnValue = new this.bjsAMMO.btCompoundShape(); - // Add shape of all children to the compound shape - let childrenAdded = 0; - meshChildren.forEach((childMesh) => { - const childImpostor = childMesh.getPhysicsImpostor(); - if (childImpostor) { - if (childImpostor.type == physicsImpostor_PhysicsImpostor.MeshImpostor) { - throw "A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)"; - } - const shape = this._createShape(childImpostor); - // Position needs to be scaled based on parent's scaling - const parentMat = childMesh.parent.getWorldMatrix().clone(); - const s = new math_vector_Vector3(); - parentMat.decompose(s); - this._tmpAmmoTransform.getOrigin().setValue(childMesh.position.x * s.x, childMesh.position.y * s.y, childMesh.position.z * s.z); - this._tmpAmmoQuaternion.setValue(childMesh.rotationQuaternion.x, childMesh.rotationQuaternion.y, childMesh.rotationQuaternion.z, childMesh.rotationQuaternion.w); - this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion); - returnValue.addChildShape(this._tmpAmmoTransform, shape); - childImpostor.dispose(); - childrenAdded++; - } - }); - if (childrenAdded > 0) { - // Add parents shape as a child if present - if (impostor.type != physicsImpostor_PhysicsImpostor.NoImpostor) { - const shape = this._createShape(impostor, true); - if (shape) { - this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0); - this._tmpAmmoQuaternion.setValue(0, 0, 0, 1); - this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion); - returnValue.addChildShape(this._tmpAmmoTransform, shape); - } - } - return returnValue; - } - else { - // If no children with impostors create the actual shape below instead - this.bjsAMMO.destroy(returnValue); - returnValue = null; - } - } - switch (impostor.type) { - case physicsImpostor_PhysicsImpostor.SphereImpostor: - // Is there a better way to compare floats number? With an epsilon or with a Math function - if (math_scalar_Scalar.WithinEpsilon(impostorExtents.x, impostorExtents.y, 0.0001) && math_scalar_Scalar.WithinEpsilon(impostorExtents.x, impostorExtents.z, 0.0001)) { - returnValue = new this.bjsAMMO.btSphereShape(impostorExtents.x / 2); - } - else { - // create a btMultiSphereShape because it's not possible to set a local scaling on a btSphereShape - const positions = [new this.bjsAMMO.btVector3(0, 0, 0)]; - const radii = [1]; - returnValue = new this.bjsAMMO.btMultiSphereShape(positions, radii, 1); - returnValue.setLocalScaling(new this.bjsAMMO.btVector3(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2)); - } - break; - case physicsImpostor_PhysicsImpostor.CapsuleImpostor: - { - // https://pybullet.org/Bullet/BulletFull/classbtCapsuleShape.html#details - // Height is just the height between the center of each 'sphere' of the capsule caps - const capRadius = impostorExtents.x / 2; - returnValue = new this.bjsAMMO.btCapsuleShape(capRadius, impostorExtents.y - capRadius * 2); - } - break; - case physicsImpostor_PhysicsImpostor.CylinderImpostor: - this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2); - returnValue = new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA); - break; - case physicsImpostor_PhysicsImpostor.PlaneImpostor: - case physicsImpostor_PhysicsImpostor.BoxImpostor: - this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2); - returnValue = new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA); - break; - case physicsImpostor_PhysicsImpostor.MeshImpostor: { - if (impostor.getParam("mass") == 0) { - // Only create btBvhTriangleMeshShape if the impostor is static - // See https://pybullet.org/Bullet/phpBB3/viewtopic.php?t=7283 - if (this.onCreateCustomMeshImpostor) { - returnValue = this.onCreateCustomMeshImpostor(impostor); - } - else { - const triMesh = new this.bjsAMMO.btTriangleMesh(); - impostor._pluginData.toDispose.push(triMesh); - const triangleCount = this._addMeshVerts(triMesh, object, object); - if (triangleCount == 0) { - returnValue = new this.bjsAMMO.btCompoundShape(); - } - else { - returnValue = new this.bjsAMMO.btBvhTriangleMeshShape(triMesh); - } - } - break; - } - } - // Otherwise create convexHullImpostor - // eslint-disable-next-line no-fallthrough - case physicsImpostor_PhysicsImpostor.ConvexHullImpostor: { - if (this.onCreateCustomConvexHullImpostor) { - returnValue = this.onCreateCustomConvexHullImpostor(impostor); - } - else { - const convexHull = new this.bjsAMMO.btConvexHullShape(); - const triangleCount = this._addHullVerts(convexHull, object, object); - if (triangleCount == 0) { - // Cleanup Unused Convex Hull Shape - impostor._pluginData.toDispose.push(convexHull); - returnValue = new this.bjsAMMO.btCompoundShape(); - } - else { - returnValue = convexHull; - } - } - break; - } - case physicsImpostor_PhysicsImpostor.NoImpostor: - // Fill with sphere but collision is disabled on the rigid body in generatePhysicsBody, using an empty shape caused unexpected movement with joints - returnValue = new this.bjsAMMO.btSphereShape(impostorExtents.x / 2); - break; - case physicsImpostor_PhysicsImpostor.CustomImpostor: - // Only usable when the plugin's onCreateCustomShape is set - returnValue = this._createCustom(impostor); - break; - case physicsImpostor_PhysicsImpostor.SoftbodyImpostor: - // Only usable with a mesh that has sufficient and shared vertices - returnValue = this._createSoftbody(impostor); - break; - case physicsImpostor_PhysicsImpostor.ClothImpostor: - // Only usable with a ground mesh that has sufficient and shared vertices - returnValue = this._createCloth(impostor); - break; - case physicsImpostor_PhysicsImpostor.RopeImpostor: - // Only usable with a line mesh or an extruded mesh that is updatable - returnValue = this._createRope(impostor); - break; - default: - logger_Logger.Warn("The impostor type is not currently supported by the ammo plugin."); - break; - } - return returnValue; - } - /** - * Sets the mesh body position/rotation from the babylon impostor - * @param impostor imposter containing the physics body and babylon object - */ - setTransformationFromPhysicsBody(impostor) { - impostor.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform); - impostor.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z()); - if (!impostor.object.rotationQuaternion) { - if (impostor.object.rotation) { - this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w()); - this._tmpQuaternion.toEulerAnglesToRef(impostor.object.rotation); - } - } - else { - impostor.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w()); - } - } - /** - * Sets the babylon object's position/rotation from the physics body's position/rotation - * @param impostor imposter containing the physics body and babylon object - * @param newPosition new position - * @param newRotation new rotation - */ - setPhysicsBodyTransformation(impostor, newPosition, newRotation) { - const trans = impostor.physicsBody.getWorldTransform(); - // If rotation/position has changed update and activate rigged body - if (Math.abs(trans.getOrigin().x() - newPosition.x) > math_constants_Epsilon || - Math.abs(trans.getOrigin().y() - newPosition.y) > math_constants_Epsilon || - Math.abs(trans.getOrigin().z() - newPosition.z) > math_constants_Epsilon || - Math.abs(trans.getRotation().x() - newRotation.x) > math_constants_Epsilon || - Math.abs(trans.getRotation().y() - newRotation.y) > math_constants_Epsilon || - Math.abs(trans.getRotation().z() - newRotation.z) > math_constants_Epsilon || - Math.abs(trans.getRotation().w() - newRotation.w) > math_constants_Epsilon) { - this._tmpAmmoVectorA.setValue(newPosition.x, newPosition.y, newPosition.z); - trans.setOrigin(this._tmpAmmoVectorA); - this._tmpAmmoQuaternion.setValue(newRotation.x, newRotation.y, newRotation.z, newRotation.w); - trans.setRotation(this._tmpAmmoQuaternion); - impostor.physicsBody.setWorldTransform(trans); - if (impostor.mass == 0) { - // Kinematic objects must be updated using motion state - const motionState = impostor.physicsBody.getMotionState(); - if (motionState) { - motionState.setWorldTransform(trans); - } - } - else { - impostor.physicsBody.activate(); - } - } - } - /** - * If this plugin is supported - * @returns true if its supported - */ - isSupported() { - return this.bjsAMMO !== undefined; - } - /** - * Sets the linear velocity of the physics body - * @param impostor imposter to set the velocity on - * @param velocity velocity to set - */ - setLinearVelocity(impostor, velocity) { - this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z); - if (impostor.soft) { - impostor.physicsBody.linearVelocity(this._tmpAmmoVectorA); - } - else { - impostor.physicsBody.setLinearVelocity(this._tmpAmmoVectorA); - } - } - /** - * Sets the angular velocity of the physics body - * @param impostor imposter to set the velocity on - * @param velocity velocity to set - */ - setAngularVelocity(impostor, velocity) { - this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z); - if (impostor.soft) { - impostor.physicsBody.angularVelocity(this._tmpAmmoVectorA); - } - else { - impostor.physicsBody.setAngularVelocity(this._tmpAmmoVectorA); - } - } - /** - * gets the linear velocity - * @param impostor imposter to get linear velocity from - * @returns linear velocity - */ - getLinearVelocity(impostor) { - let v; - if (impostor.soft) { - v = impostor.physicsBody.linearVelocity(); - } - else { - v = impostor.physicsBody.getLinearVelocity(); - } - if (!v) { - return null; - } - const result = new math_vector_Vector3(v.x(), v.y(), v.z()); - this.bjsAMMO.destroy(v); - return result; - } - /** - * gets the angular velocity - * @param impostor imposter to get angular velocity from - * @returns angular velocity - */ - getAngularVelocity(impostor) { - let v; - if (impostor.soft) { - v = impostor.physicsBody.angularVelocity(); - } - else { - v = impostor.physicsBody.getAngularVelocity(); - } - if (!v) { - return null; - } - const result = new math_vector_Vector3(v.x(), v.y(), v.z()); - this.bjsAMMO.destroy(v); - return result; - } - /** - * Sets the mass of physics body - * @param impostor imposter to set the mass on - * @param mass mass to set - */ - setBodyMass(impostor, mass) { - if (impostor.soft) { - impostor.physicsBody.setTotalMass(mass, false); - } - else { - impostor.physicsBody.setMassProps(mass); - } - impostor._pluginData.mass = mass; - } - /** - * Gets the mass of the physics body - * @param impostor imposter to get the mass from - * @returns mass - */ - getBodyMass(impostor) { - return impostor._pluginData.mass || 0; - } - /** - * Gets friction of the impostor - * @param impostor impostor to get friction from - * @returns friction value - */ - getBodyFriction(impostor) { - return impostor._pluginData.friction || 0; - } - /** - * Sets friction of the impostor - * @param impostor impostor to set friction on - * @param friction friction value - */ - setBodyFriction(impostor, friction) { - if (impostor.soft) { - impostor.physicsBody.get_m_cfg().set_kDF(friction); - } - else { - impostor.physicsBody.setFriction(friction); - } - impostor._pluginData.friction = friction; - } - /** - * Gets restitution of the impostor - * @param impostor impostor to get restitution from - * @returns restitution value - */ - getBodyRestitution(impostor) { - return impostor._pluginData.restitution || 0; - } - /** - * Sets restitution of the impostor - * @param impostor impostor to set resitution on - * @param restitution resitution value - */ - setBodyRestitution(impostor, restitution) { - impostor.physicsBody.setRestitution(restitution); - impostor._pluginData.restitution = restitution; - } - /** - * Gets pressure inside the impostor - * @param impostor impostor to get pressure from - * @returns pressure value - */ - getBodyPressure(impostor) { - if (!impostor.soft) { - logger_Logger.Warn("Pressure is not a property of a rigid body"); - return 0; - } - return impostor._pluginData.pressure || 0; - } - /** - * Sets pressure inside a soft body impostor - * Cloth and rope must remain 0 pressure - * @param impostor impostor to set pressure on - * @param pressure pressure value - */ - setBodyPressure(impostor, pressure) { - if (impostor.soft) { - if (impostor.type === physicsImpostor_PhysicsImpostor.SoftbodyImpostor) { - impostor.physicsBody.get_m_cfg().set_kPR(pressure); - impostor._pluginData.pressure = pressure; - } - else { - impostor.physicsBody.get_m_cfg().set_kPR(0); - impostor._pluginData.pressure = 0; - } - } - else { - logger_Logger.Warn("Pressure can only be applied to a softbody"); - } - } - /** - * Gets stiffness of the impostor - * @param impostor impostor to get stiffness from - * @returns pressure value - */ - getBodyStiffness(impostor) { - if (!impostor.soft) { - logger_Logger.Warn("Stiffness is not a property of a rigid body"); - return 0; - } - return impostor._pluginData.stiffness || 0; - } - /** - * Sets stiffness of the impostor - * @param impostor impostor to set stiffness on - * @param stiffness stiffness value from 0 to 1 - */ - setBodyStiffness(impostor, stiffness) { - if (impostor.soft) { - stiffness = stiffness < 0 ? 0 : stiffness; - stiffness = stiffness > 1 ? 1 : stiffness; - impostor.physicsBody.get_m_materials().at(0).set_m_kLST(stiffness); - impostor._pluginData.stiffness = stiffness; - } - else { - logger_Logger.Warn("Stiffness cannot be applied to a rigid body"); - } - } - /** - * Gets velocityIterations of the impostor - * @param impostor impostor to get velocity iterations from - * @returns velocityIterations value - */ - getBodyVelocityIterations(impostor) { - if (!impostor.soft) { - logger_Logger.Warn("Velocity iterations is not a property of a rigid body"); - return 0; - } - return impostor._pluginData.velocityIterations || 0; - } - /** - * Sets velocityIterations of the impostor - * @param impostor impostor to set velocity iterations on - * @param velocityIterations velocityIterations value - */ - setBodyVelocityIterations(impostor, velocityIterations) { - if (impostor.soft) { - velocityIterations = velocityIterations < 0 ? 0 : velocityIterations; - impostor.physicsBody.get_m_cfg().set_viterations(velocityIterations); - impostor._pluginData.velocityIterations = velocityIterations; - } - else { - logger_Logger.Warn("Velocity iterations cannot be applied to a rigid body"); - } - } - /** - * Gets positionIterations of the impostor - * @param impostor impostor to get position iterations from - * @returns positionIterations value - */ - getBodyPositionIterations(impostor) { - if (!impostor.soft) { - logger_Logger.Warn("Position iterations is not a property of a rigid body"); - return 0; - } - return impostor._pluginData.positionIterations || 0; - } - /** - * Sets positionIterations of the impostor - * @param impostor impostor to set position on - * @param positionIterations positionIterations value - */ - setBodyPositionIterations(impostor, positionIterations) { - if (impostor.soft) { - positionIterations = positionIterations < 0 ? 0 : positionIterations; - impostor.physicsBody.get_m_cfg().set_piterations(positionIterations); - impostor._pluginData.positionIterations = positionIterations; - } - else { - logger_Logger.Warn("Position iterations cannot be applied to a rigid body"); - } - } - /** - * Append an anchor to a cloth object - * @param impostor is the cloth impostor to add anchor to - * @param otherImpostor is the rigid impostor to anchor to - * @param width ratio across width from 0 to 1 - * @param height ratio up height from 0 to 1 - * @param influence the elasticity between cloth impostor and anchor from 0, very stretchy to 1, little stretch - * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false - */ - appendAnchor(impostor, otherImpostor, width, height, influence = 1, noCollisionBetweenLinkedBodies = false) { - const segs = impostor.segments; - const nbAcross = Math.round((segs - 1) * width); - const nbUp = Math.round((segs - 1) * height); - const nbDown = segs - 1 - nbUp; - const node = nbAcross + segs * nbDown; - impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence); - } - /** - * Append an hook to a rope object - * @param impostor is the rope impostor to add hook to - * @param otherImpostor is the rigid impostor to hook to - * @param length ratio along the rope from 0 to 1 - * @param influence the elasticity between soft impostor and anchor from 0, very stretchy to 1, little stretch - * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false - */ - appendHook(impostor, otherImpostor, length, influence = 1, noCollisionBetweenLinkedBodies = false) { - const node = Math.round(impostor.segments * length); - impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence); - } - /** - * Sleeps the physics body and stops it from being active - * @param impostor impostor to sleep - */ - sleepBody(impostor) { - impostor.physicsBody.forceActivationState(0); - } - /** - * Activates the physics body - * @param impostor impostor to activate - */ - wakeUpBody(impostor) { - impostor.physicsBody.activate(); - } - /** - * Updates the distance parameters of the joint - */ - updateDistanceJoint() { - logger_Logger.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin"); - } - /** - * Sets a motor on the joint - * @param joint joint to set motor on - * @param speed speed of the motor - * @param maxForce maximum force of the motor - */ - setMotor(joint, speed, maxForce) { - joint.physicsJoint.enableAngularMotor(true, speed, maxForce); - } - /** - * Sets the motors limit - */ - setLimit() { - logger_Logger.Warn("setLimit is not currently supported by the Ammo physics plugin"); - } - /** - * Syncs the position and rotation of a mesh with the impostor - * @param mesh mesh to sync - * @param impostor impostor to update the mesh with - */ - syncMeshWithImpostor(mesh, impostor) { - const body = impostor.physicsBody; - body.getMotionState().getWorldTransform(this._tmpAmmoTransform); - mesh.position.x = this._tmpAmmoTransform.getOrigin().x(); - mesh.position.y = this._tmpAmmoTransform.getOrigin().y(); - mesh.position.z = this._tmpAmmoTransform.getOrigin().z(); - if (mesh.rotationQuaternion) { - mesh.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x(); - mesh.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y(); - mesh.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z(); - mesh.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w(); - } - } - /** - * Gets the radius of the impostor - * @param impostor impostor to get radius from - * @returns the radius - */ - getRadius(impostor) { - const extents = impostor.getObjectExtents(); - return extents.x / 2; - } - /** - * Gets the box size of the impostor - * @param impostor impostor to get box size from - * @param result the resulting box size - */ - getBoxSizeToRef(impostor, result) { - const extents = impostor.getObjectExtents(); - result.x = extents.x; - result.y = extents.y; - result.z = extents.z; - } - /** - * Disposes of the impostor - */ - dispose() { - // Dispose of world - 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); - // Dispose of temp variables - 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; - } - /** - * Does a raycast in the physics world - * @param from where should the ray start? - * @param to where should the ray end? - * @returns PhysicsRaycastResult - */ - raycast(from, to) { - this.raycastToRef(from, to, this._raycastResult); - return this._raycastResult; - } - /** - * Does a raycast in the physics world - * @param from when should the ray start? - * @param to when should the ray end? - * @param result resulting PhysicsRaycastResult - */ - raycastToRef(from, to, result) { - this._tmpAmmoVectorRCA = new this.bjsAMMO.btVector3(from.x, from.y, from.z); - this._tmpAmmoVectorRCB = new this.bjsAMMO.btVector3(to.x, to.y, to.z); - const rayCallback = new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB); - this.world.rayTest(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB, rayCallback); - result.reset(from, to); - if (rayCallback.hasHit()) { - // TODO: do we want/need the body? If so, set all the data - /* - var rigidBody = this.bjsAMMO.btRigidBody.prototype.upcast( - rayCallback.get_m_collisionObject() - ); - var body = {}; - */ - result.setHitData({ - x: rayCallback.get_m_hitNormalWorld().x(), - y: rayCallback.get_m_hitNormalWorld().y(), - z: rayCallback.get_m_hitNormalWorld().z(), - }, { - x: rayCallback.get_m_hitPointWorld().x(), - y: rayCallback.get_m_hitPointWorld().y(), - z: rayCallback.get_m_hitPointWorld().z(), - }); - result.calculateHitDistance(); - } - this.bjsAMMO.destroy(rayCallback); - this.bjsAMMO.destroy(this._tmpAmmoVectorRCA); - this.bjsAMMO.destroy(this._tmpAmmoVectorRCB); - } -} -AmmoJSPlugin._DISABLE_COLLISION_FLAG = 4; -AmmoJSPlugin._KINEMATIC_FLAG = 2; -AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG = 4; -//# sourceMappingURL=ammoJSPlugin.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Probes/reflectionProbe.js - - - - - - -AbstractScene.prototype.removeReflectionProbe = function (toRemove) { - if (!this.reflectionProbes) { - return -1; - } - const index = this.reflectionProbes.indexOf(toRemove); - if (index !== -1) { - this.reflectionProbes.splice(index, 1); - } - return index; -}; -AbstractScene.prototype.addReflectionProbe = function (newReflectionProbe) { - if (!this.reflectionProbes) { - this.reflectionProbes = []; - } - this.reflectionProbes.push(newReflectionProbe); -}; -/** - * Class used to generate realtime reflection / refraction cube textures - * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/reflectionProbes - */ -class ReflectionProbe { - /** - * Creates a new reflection probe - * @param name defines the name of the probe - * @param size defines the texture resolution (for each face) - * @param scene defines the hosting scene - * @param generateMipMaps defines if mip maps should be generated automatically (true by default) - * @param useFloat defines if HDR data (float data) should be used to store colors (false by default) - * @param linearSpace defines if the probe should be generated in linear space or not (false by default) - */ - constructor( - /** defines the name of the probe */ - name, size, scene, generateMipMaps = true, useFloat = false, linearSpace = false) { - this.name = name; - this._viewMatrix = math_vector_Matrix.Identity(); - this._target = math_vector_Vector3.Zero(); - this._add = math_vector_Vector3.Zero(); - this._invertYAxis = false; - /** Gets or sets probe position (center of the cube map) */ - this.position = math_vector_Vector3.Zero(); - /** - * Gets or sets an object used to store user defined information for the reflection probe. - */ - this.metadata = null; - /** @internal */ - this._parentContainer = null; - this._scene = scene; - if (scene.getEngine().supportsUniformBuffers) { - this._sceneUBOs = []; - for (let i = 0; i < 6; ++i) { - this._sceneUBOs.push(scene.createSceneUniformBuffer(`Scene for Reflection Probe (name "${name}") face #${i}`)); - } - } - // Create the scene field if not exist. - if (!this._scene.reflectionProbes) { - this._scene.reflectionProbes = new Array(); - } - this._scene.reflectionProbes.push(this); - let textureType = 0; - if (useFloat) { - const caps = this._scene.getEngine().getCaps(); - if (caps.textureHalfFloatRender) { - textureType = 2; - } - else if (caps.textureFloatRender) { - textureType = 1; - } - } - this._renderTargetTexture = new renderTargetTexture_RenderTargetTexture(name, size, scene, generateMipMaps, true, textureType, true); - this._renderTargetTexture.gammaSpace = !linearSpace; - this._renderTargetTexture.invertZ = scene.useRightHandedSystem; - const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer; - this._renderTargetTexture.onBeforeRenderObservable.add((faceIndex) => { - if (this._sceneUBOs) { - scene.setSceneUniformBuffer(this._sceneUBOs[faceIndex]); - scene.getSceneUniformBuffer().unbindEffect(); - } - switch (faceIndex) { - 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, scene.useRightHandedSystem ? -1 : 1); - break; - case 5: - this._add.copyFromFloats(0, 0, scene.useRightHandedSystem ? 1 : -1); - break; - } - if (this._attachedMesh) { - this.position.copyFrom(this._attachedMesh.getAbsolutePosition()); - } - this.position.addToRef(this._add, this._target); - const lookAtFunction = scene.useRightHandedSystem ? math_vector_Matrix.LookAtRHToRef : math_vector_Matrix.LookAtLHToRef; - const perspectiveFunction = scene.useRightHandedSystem ? math_vector_Matrix.PerspectiveFovRH : math_vector_Matrix.PerspectiveFovLH; - lookAtFunction(this.position, this._target, math_vector_Vector3.Up(), this._viewMatrix); - if (scene.activeCamera) { - 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); - scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix); - if (scene.activeCamera.isRigCamera && !this._renderTargetTexture.activeCamera) { - this._renderTargetTexture.activeCamera = scene.activeCamera.rigParent || null; - } - } - scene._forcedViewPosition = this.position; - }); - let currentApplyByPostProcess; - this._renderTargetTexture.onBeforeBindObservable.add(() => { - var _a, _b; - this._currentSceneUBO = scene.getSceneUniformBuffer(); - (_b = (_a = scene.getEngine())._debugPushGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `reflection probe generation for ${name}`, 1); - currentApplyByPostProcess = this._scene.imageProcessingConfiguration.applyByPostProcess; - if (linearSpace) { - scene.imageProcessingConfiguration.applyByPostProcess = true; - } - }); - this._renderTargetTexture.onAfterUnbindObservable.add(() => { - var _a, _b; - scene.imageProcessingConfiguration.applyByPostProcess = currentApplyByPostProcess; - scene._forcedViewPosition = null; - if (this._sceneUBOs) { - scene.setSceneUniformBuffer(this._currentSceneUBO); - } - scene.updateTransformMatrix(true); - (_b = (_a = scene.getEngine())._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(_a, 1); - }); - } - /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */ - get samples() { - return this._renderTargetTexture.samples; - } - set samples(value) { - this._renderTargetTexture.samples = value; - } - /** Gets or sets the refresh rate to use (on every frame by default) */ - get refreshRate() { - return this._renderTargetTexture.refreshRate; - } - set refreshRate(value) { - this._renderTargetTexture.refreshRate = value; - } - /** - * Gets the hosting scene - * @returns a Scene - */ - getScene() { - return this._scene; - } - /** Gets the internal CubeTexture used to render to */ - get cubeTexture() { - return this._renderTargetTexture; - } - /** Gets the list of meshes to render */ - get renderList() { - return this._renderTargetTexture.renderList; - } - /** - * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position) - * @param mesh defines the mesh to attach to - */ - attachToMesh(mesh) { - this._attachedMesh = mesh; - } - /** - * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups - * @param renderingGroupId The rendering group id corresponding to its index - * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. - */ - setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) { - this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); - } - /** - * Clean all associated resources - */ - dispose() { - const index = this._scene.reflectionProbes.indexOf(this); - if (index !== -1) { - // Remove from the scene if found - this._scene.reflectionProbes.splice(index, 1); - } - if (this._parentContainer) { - const index = this._parentContainer.reflectionProbes.indexOf(this); - if (index > -1) { - this._parentContainer.reflectionProbes.splice(index, 1); - } - this._parentContainer = null; - } - if (this._renderTargetTexture) { - this._renderTargetTexture.dispose(); - this._renderTargetTexture = null; - } - if (this._sceneUBOs) { - for (const ubo of this._sceneUBOs) { - ubo.dispose(); - } - this._sceneUBOs = []; - } - } - /** - * Converts the reflection probe information to a readable string for debug purpose. - * @param fullDetails Supports for multiple levels of logging within scene loading - * @returns the human readable reflection probe info - */ - toString(fullDetails) { - let ret = "Name: " + this.name; - if (fullDetails) { - ret += ", position: " + this.position.toString(); - if (this._attachedMesh) { - ret += ", attached mesh: " + this._attachedMesh.name; - } - } - return ret; - } - /** - * Get the class name of the refection probe. - * @returns "ReflectionProbe" - */ - getClassName() { - return "ReflectionProbe"; - } - /** - * Serialize the reflection probe to a JSON representation we can easily use in the respective Parse function. - * @returns The JSON representation of the texture - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this, this._renderTargetTexture.serialize()); - serializationObject.isReflectionProbe = true; - serializationObject.metadata = this.metadata; - return serializationObject; - } - /** - * Parse the JSON representation of a reflection probe in order to recreate the reflection probe in the given scene. - * @param parsedReflectionProbe Define the JSON representation of the reflection probe - * @param scene Define the scene the parsed reflection probe should be instantiated in - * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies - * @returns The parsed reflection probe if successful - */ - static Parse(parsedReflectionProbe, scene, rootUrl) { - let reflectionProbe = null; - if (scene.reflectionProbes) { - for (let index = 0; index < scene.reflectionProbes.length; index++) { - const rp = scene.reflectionProbes[index]; - if (rp.name === parsedReflectionProbe.name) { - reflectionProbe = rp; - break; - } - } - } - reflectionProbe = decorators_SerializationHelper.Parse(() => reflectionProbe || new ReflectionProbe(parsedReflectionProbe.name, parsedReflectionProbe.renderTargetSize, scene, parsedReflectionProbe._generateMipMaps), parsedReflectionProbe, scene, rootUrl); - reflectionProbe.cubeTexture._waitingRenderList = parsedReflectionProbe.renderList; - if (parsedReflectionProbe._attachedMesh) { - reflectionProbe.attachToMesh(scene.getMeshById(parsedReflectionProbe._attachedMesh)); - } - if (parsedReflectionProbe.metadata) { - reflectionProbe.metadata = parsedReflectionProbe.metadata; - } - return reflectionProbe; - } -} -__decorate([ - serializeAsMeshReference() -], ReflectionProbe.prototype, "_attachedMesh", void 0); -__decorate([ - serializeAsVector3() -], ReflectionProbe.prototype, "position", void 0); -//# sourceMappingURL=reflectionProbe.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Loading/Plugins/babylonFileLoader.js - - - - - - - - - - - - - - - - - - - - - - - - - - - -/** @internal */ -// eslint-disable-next-line @typescript-eslint/naming-convention, no-var -var _BabylonLoaderRegistered = true; -/** - * Helps setting up some configuration for the babylon file loader. - */ -class BabylonFileLoaderConfiguration { -} -/** - * The loader does not allow injecting custom physics engine into the plugins. - * Unfortunately in ES6, we need to manually inject them into the plugin. - * So you could set this variable to your engine import to make it work. - */ -BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine = undefined; -let tempIndexContainer = {}; -let tempMaterialIndexContainer = {}; -const parseMaterialByPredicate = (predicate, parsedData, scene, rootUrl) => { - if (!parsedData.materials) { - return null; - } - for (let index = 0, cache = parsedData.materials.length; index < cache; index++) { - const parsedMaterial = parsedData.materials[index]; - if (predicate(parsedMaterial)) { - return { parsedMaterial, material: material_Material.Parse(parsedMaterial, scene, rootUrl) }; - } - } - return null; -}; -const isDescendantOf = (mesh, names, hierarchyIds) => { - for (const i in names) { - if (mesh.name === names[i]) { - hierarchyIds.push(mesh.id); - return true; - } - } - if (mesh.parentId !== undefined && hierarchyIds.indexOf(mesh.parentId) !== -1) { - hierarchyIds.push(mesh.id); - return true; - } - return false; -}; -// eslint-disable-next-line @typescript-eslint/naming-convention -const logOperation = (operation, producer) => { - return (operation + - " of " + - (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown")); -}; -const loadDetailLevels = (scene, mesh) => { - const mastermesh = mesh; - // Every value specified in the ids array of the lod data points to another mesh which should be used as the lower LOD level. - // 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. - if (mesh._waitingData.lods) { - if (mesh._waitingData.lods.ids && mesh._waitingData.lods.ids.length > 0) { - const lodmeshes = mesh._waitingData.lods.ids; - const wasenabled = mastermesh.isEnabled(false); - if (mesh._waitingData.lods.distances) { - const distances = mesh._waitingData.lods.distances; - if (distances.length >= lodmeshes.length) { - const culling = distances.length > lodmeshes.length ? distances[distances.length - 1] : 0; - mastermesh.setEnabled(false); - for (let index = 0; index < lodmeshes.length; index++) { - const lodid = lodmeshes[index]; - const lodmesh = scene.getMeshById(lodid); - if (lodmesh != null) { - mastermesh.addLODLevel(distances[index], lodmesh); - } - } - if (culling > 0) { - mastermesh.addLODLevel(culling, null); - } - if (wasenabled === true) { - mastermesh.setEnabled(true); - } - } - else { - tools_Tools.Warn("Invalid level of detail distances for " + mesh.name); - } - } - } - mesh._waitingData.lods = null; - } -}; -const findParent = (parentId, parentInstanceIndex, scene) => { - if (typeof parentId !== "number") { - const parentEntry = scene.getLastEntryById(parentId); - if (parentEntry && parentInstanceIndex !== undefined && parentInstanceIndex !== null) { - const instance = parentEntry.instances[parseInt(parentInstanceIndex)]; - return instance; - } - return parentEntry; - } - const parent = tempIndexContainer[parentId]; - if (parent && parentInstanceIndex !== undefined && parentInstanceIndex !== null) { - const instance = parent.instances[parseInt(parentInstanceIndex)]; - return instance; - } - return parent; -}; -const findMaterial = (materialId, scene) => { - if (typeof materialId !== "number") { - return scene.getLastMaterialById(materialId, true); - } - return tempMaterialIndexContainer[materialId]; -}; -const loadAssetContainer = (scene, data, rootUrl, onError, addToScene = false) => { - const container = new AssetContainer(scene); - // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details - // when SceneLoader.debugLogging = true (default), or exception encountered. - // Everything stored in var log instead of writing separate lines to support only writing in exception, - // and avoid problems with multiple concurrent .babylon loads. - let log = "importScene has failed JSON parse"; - try { - // eslint-disable-next-line no-var - var parsedData = JSON.parse(data); - log = ""; - const fullDetails = sceneLoader_SceneLoader.loggingLevel === sceneLoader_SceneLoader.DETAILED_LOGGING; - let index; - let cache; - // Environment texture - if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) { - // PBR needed for both HDR texture (gamma space) & a sky box - const isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true; - if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") { - const hdrSize = parsedData.environmentTextureSize ? parsedData.environmentTextureSize : 128; - const hdrTexture = new hdrCubeTexture_HDRCubeTexture((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, hdrSize, true, !isPBR, undefined, parsedData.environmentTexturePrefilterOnLoad); - if (parsedData.environmentTextureRotationY) { - hdrTexture.rotationY = parsedData.environmentTextureRotationY; - } - scene.environmentTexture = hdrTexture; - } - else { - if (typeof parsedData.environmentTexture === "object") { - const environmentTexture = cubeTexture_CubeTexture.Parse(parsedData.environmentTexture, scene, rootUrl); - scene.environmentTexture = environmentTexture; - } - else if (parsedData.environmentTexture.endsWith(".env")) { - const compressedTexture = new cubeTexture_CubeTexture((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, parsedData.environmentTextureForcedExtension); - if (parsedData.environmentTextureRotationY) { - compressedTexture.rotationY = parsedData.environmentTextureRotationY; - } - scene.environmentTexture = compressedTexture; - } - else { - const cubeTexture = cubeTexture_CubeTexture.CreateFromPrefilteredData((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, parsedData.environmentTextureForcedExtension); - if (parsedData.environmentTextureRotationY) { - cubeTexture.rotationY = parsedData.environmentTextureRotationY; - } - scene.environmentTexture = cubeTexture; - } - } - if (parsedData.createDefaultSkybox === true) { - const skyboxScale = scene.activeCamera !== undefined && scene.activeCamera !== null ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000; - const skyboxBlurLevel = parsedData.skyboxBlurLevel || 0; - scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel); - } - container.environmentTexture = scene.environmentTexture; - } - // Environment Intensity - if (parsedData.environmentIntensity !== undefined && parsedData.environmentIntensity !== null) { - scene.environmentIntensity = parsedData.environmentIntensity; - } - // Lights - if (parsedData.lights !== undefined && parsedData.lights !== null) { - for (index = 0, cache = parsedData.lights.length; index < cache; index++) { - const parsedLight = parsedData.lights[index]; - const light = light_Light.Parse(parsedLight, scene); - if (light) { - tempIndexContainer[parsedLight.uniqueId] = light; - container.lights.push(light); - light._parentContainer = container; - log += index === 0 ? "\n\tLights:" : ""; - log += "\n\t\t" + light.toString(fullDetails); - } - } - } - // Reflection probes - if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) { - for (index = 0, cache = parsedData.reflectionProbes.length; index < cache; index++) { - const parsedReflectionProbe = parsedData.reflectionProbes[index]; - const reflectionProbe = ReflectionProbe.Parse(parsedReflectionProbe, scene, rootUrl); - if (reflectionProbe) { - container.reflectionProbes.push(reflectionProbe); - reflectionProbe._parentContainer = container; - log += index === 0 ? "\n\tReflection Probes:" : ""; - log += "\n\t\t" + reflectionProbe.toString(fullDetails); - } - } - } - // Animations - if (parsedData.animations !== undefined && parsedData.animations !== null) { - for (index = 0, cache = parsedData.animations.length; index < cache; index++) { - const parsedAnimation = parsedData.animations[index]; - const internalClass = GetClass("BABYLON.Animation"); - if (internalClass) { - const animation = internalClass.Parse(parsedAnimation); - scene.animations.push(animation); - container.animations.push(animation); - log += index === 0 ? "\n\tAnimations:" : ""; - log += "\n\t\t" + animation.toString(fullDetails); - } - } - } - // Materials - if (parsedData.materials !== undefined && parsedData.materials !== null) { - for (index = 0, cache = parsedData.materials.length; index < cache; index++) { - const parsedMaterial = parsedData.materials[index]; - const mat = material_Material.Parse(parsedMaterial, scene, rootUrl); - if (mat) { - tempMaterialIndexContainer[parsedMaterial.uniqueId || parsedMaterial.id] = mat; - container.materials.push(mat); - mat._parentContainer = container; - log += index === 0 ? "\n\tMaterials:" : ""; - log += "\n\t\t" + mat.toString(fullDetails); - // Textures - const textures = mat.getActiveTextures(); - textures.forEach((t) => { - if (container.textures.indexOf(t) == -1) { - container.textures.push(t); - t._parentContainer = container; - } - }); - } - } - } - if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) { - for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) { - const parsedMultiMaterial = parsedData.multiMaterials[index]; - const mmat = multiMaterial_MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene); - tempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat; - container.multiMaterials.push(mmat); - mmat._parentContainer = container; - log += index === 0 ? "\n\tMultiMaterials:" : ""; - log += "\n\t\t" + mmat.toString(fullDetails); - // Textures - const textures = mmat.getActiveTextures(); - textures.forEach((t) => { - if (container.textures.indexOf(t) == -1) { - container.textures.push(t); - t._parentContainer = container; - } - }); - } - } - // Morph targets - if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) { - for (const managerData of parsedData.morphTargetManagers) { - const manager = morphTargetManager_MorphTargetManager.Parse(managerData, scene); - container.morphTargetManagers.push(manager); - manager._parentContainer = container; - } - } - // Skeletons - if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) { - for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) { - const parsedSkeleton = parsedData.skeletons[index]; - const skeleton = skeleton_Skeleton.Parse(parsedSkeleton, scene); - container.skeletons.push(skeleton); - skeleton._parentContainer = container; - log += index === 0 ? "\n\tSkeletons:" : ""; - log += "\n\t\t" + skeleton.toString(fullDetails); - } - } - // Geometries - const geometries = parsedData.geometries; - if (geometries !== undefined && geometries !== null) { - const addedGeometry = new Array(); - // VertexData - const vertexData = geometries.vertexData; - if (vertexData !== undefined && vertexData !== null) { - for (index = 0, cache = vertexData.length; index < cache; index++) { - const parsedVertexData = vertexData[index]; - addedGeometry.push(Geometry.Parse(parsedVertexData, scene, rootUrl)); - } - } - addedGeometry.forEach((g) => { - if (g) { - container.geometries.push(g); - g._parentContainer = container; - } - }); - } - // Transform nodes - if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) { - for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) { - const parsedTransformNode = parsedData.transformNodes[index]; - const node = transformNode_TransformNode.Parse(parsedTransformNode, scene, rootUrl); - tempIndexContainer[parsedTransformNode.uniqueId] = node; - container.transformNodes.push(node); - node._parentContainer = container; - } - } - // Meshes - if (parsedData.meshes !== undefined && parsedData.meshes !== null) { - for (index = 0, cache = parsedData.meshes.length; index < cache; index++) { - const parsedMesh = parsedData.meshes[index]; - const mesh = mesh_Mesh.Parse(parsedMesh, scene, rootUrl); - tempIndexContainer[parsedMesh.uniqueId] = mesh; - container.meshes.push(mesh); - mesh._parentContainer = container; - if (mesh.hasInstances) { - for (const instance of mesh.instances) { - container.meshes.push(instance); - instance._parentContainer = container; - } - } - log += index === 0 ? "\n\tMeshes:" : ""; - log += "\n\t\t" + mesh.toString(fullDetails); - } - } - // Cameras - if (parsedData.cameras !== undefined && parsedData.cameras !== null) { - for (index = 0, cache = parsedData.cameras.length; index < cache; index++) { - const parsedCamera = parsedData.cameras[index]; - const camera = camera_Camera.Parse(parsedCamera, scene); - tempIndexContainer[parsedCamera.uniqueId] = camera; - container.cameras.push(camera); - camera._parentContainer = container; - log += index === 0 ? "\n\tCameras:" : ""; - log += "\n\t\t" + camera.toString(fullDetails); - } - } - // Postprocesses - if (parsedData.postProcesses !== undefined && parsedData.postProcesses !== null) { - for (index = 0, cache = parsedData.postProcesses.length; index < cache; index++) { - const parsedPostProcess = parsedData.postProcesses[index]; - const postProcess = postProcess_PostProcess.Parse(parsedPostProcess, scene, rootUrl); - if (postProcess) { - container.postProcesses.push(postProcess); - postProcess._parentContainer = container; - log += index === 0 ? "\nPostprocesses:" : ""; - log += "\n\t\t" + postProcess.toString(); - } - } - } - // Animation Groups - if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) { - for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) { - const parsedAnimationGroup = parsedData.animationGroups[index]; - const animationGroup = AnimationGroup.Parse(parsedAnimationGroup, scene); - container.animationGroups.push(animationGroup); - animationGroup._parentContainer = container; - log += index === 0 ? "\n\tAnimationGroups:" : ""; - log += "\n\t\t" + animationGroup.toString(fullDetails); - } - } - // Browsing all the graph to connect the dots - for (index = 0, cache = scene.cameras.length; index < cache; index++) { - const camera = scene.cameras[index]; - if (camera._waitingParentId !== null) { - camera.parent = findParent(camera._waitingParentId, camera._waitingParentInstanceIndex, scene); - camera._waitingParentId = null; - camera._waitingParentInstanceIndex = null; - } - } - for (index = 0, cache = scene.lights.length; index < cache; index++) { - const light = scene.lights[index]; - if (light && light._waitingParentId !== null) { - light.parent = findParent(light._waitingParentId, light._waitingParentInstanceIndex, scene); - light._waitingParentId = null; - light._waitingParentInstanceIndex = null; - } - } - // Connect parents & children and parse actions and lods - for (index = 0, cache = scene.transformNodes.length; index < cache; index++) { - const transformNode = scene.transformNodes[index]; - if (transformNode._waitingParentId !== null) { - transformNode.parent = findParent(transformNode._waitingParentId, transformNode._waitingParentInstanceIndex, scene); - transformNode._waitingParentId = null; - transformNode._waitingParentInstanceIndex = null; - } - } - for (index = 0, cache = scene.meshes.length; index < cache; index++) { - const mesh = scene.meshes[index]; - if (mesh._waitingParentId !== null) { - mesh.parent = findParent(mesh._waitingParentId, mesh._waitingParentInstanceIndex, scene); - mesh._waitingParentId = null; - mesh._waitingParentInstanceIndex = null; - } - if (mesh._waitingData.lods) { - loadDetailLevels(scene, mesh); - } - } - // link multimats with materials - scene.multiMaterials.forEach((multimat) => { - multimat._waitingSubMaterialsUniqueIds.forEach((subMaterial) => { - multimat.subMaterials.push(findMaterial(subMaterial, scene)); - }); - multimat._waitingSubMaterialsUniqueIds = []; - }); - // link meshes with materials - scene.meshes.forEach((mesh) => { - if (mesh._waitingMaterialId !== null) { - mesh.material = findMaterial(mesh._waitingMaterialId, scene); - mesh._waitingMaterialId = null; - } - }); - // link skeleton transform nodes - for (index = 0, cache = scene.skeletons.length; index < cache; index++) { - const skeleton = scene.skeletons[index]; - if (skeleton._hasWaitingData) { - if (skeleton.bones != null) { - skeleton.bones.forEach((bone) => { - if (bone._waitingTransformNodeId) { - const linkTransformNode = scene.getLastEntryById(bone._waitingTransformNodeId); - if (linkTransformNode) { - bone.linkTransformNode(linkTransformNode); - } - bone._waitingTransformNodeId = null; - } - }); - } - skeleton._hasWaitingData = null; - } - } - // freeze world matrix application - for (index = 0, cache = scene.meshes.length; index < cache; index++) { - const currentMesh = scene.meshes[index]; - if (currentMesh._waitingData.freezeWorldMatrix) { - currentMesh.freezeWorldMatrix(); - currentMesh._waitingData.freezeWorldMatrix = null; - } - else { - currentMesh.computeWorldMatrix(true); - } - } - // Lights exclusions / inclusions - for (index = 0, cache = scene.lights.length; index < cache; index++) { - const light = scene.lights[index]; - // Excluded check - if (light._excludedMeshesIds.length > 0) { - for (let excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) { - const excludedMesh = scene.getMeshById(light._excludedMeshesIds[excludedIndex]); - if (excludedMesh) { - light.excludedMeshes.push(excludedMesh); - } - } - light._excludedMeshesIds = []; - } - // Included check - if (light._includedOnlyMeshesIds.length > 0) { - for (let includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) { - const includedOnlyMesh = scene.getMeshById(light._includedOnlyMeshesIds[includedOnlyIndex]); - if (includedOnlyMesh) { - light.includedOnlyMeshes.push(includedOnlyMesh); - } - } - light._includedOnlyMeshesIds = []; - } - } - scene.geometries.forEach((g) => { - g._loadedUniqueId = ""; - }); - AbstractScene.Parse(parsedData, scene, container, rootUrl); - // Actions (scene) Done last as it can access other objects. - for (index = 0, cache = scene.meshes.length; index < cache; index++) { - const mesh = scene.meshes[index]; - if (mesh._waitingData.actions) { - ActionManager.Parse(mesh._waitingData.actions, mesh, scene); - mesh._waitingData.actions = null; - } - } - if (parsedData.actions !== undefined && parsedData.actions !== null) { - ActionManager.Parse(parsedData.actions, null, scene); - } - } - catch (err) { - const msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log; - if (onError) { - onError(msg, err); - } - else { - logger_Logger.Log(msg); - throw err; - } - } - finally { - tempIndexContainer = {}; - tempMaterialIndexContainer = {}; - if (!addToScene) { - container.removeAllFromScene(); - } - if (log !== null && sceneLoader_SceneLoader.loggingLevel !== sceneLoader_SceneLoader.NO_LOGGING) { - logger_Logger.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (sceneLoader_SceneLoader.loggingLevel !== sceneLoader_SceneLoader.MINIMAL_LOGGING ? log : "")); - } - } - return container; -}; -sceneLoader_SceneLoader.RegisterPlugin({ - name: "babylon.js", - extensions: ".babylon", - canDirectLoad: (data) => { - if (data.indexOf("babylon") !== -1) { - // We consider that the producer string is filled - return true; - } - return false; - }, - importMesh: (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) => { - var _a; - // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details - // when SceneLoader.debugLogging = true (default), or exception encountered. - // Everything stored in var log instead of writing separate lines to support only writing in exception, - // and avoid problems with multiple concurrent .babylon loads. - let log = "importMesh has failed JSON parse"; - try { - // eslint-disable-next-line no-var - var parsedData = JSON.parse(data); - log = ""; - const fullDetails = sceneLoader_SceneLoader.loggingLevel === sceneLoader_SceneLoader.DETAILED_LOGGING; - if (!meshesNames) { - meshesNames = null; - } - else if (!Array.isArray(meshesNames)) { - meshesNames = [meshesNames]; - } - const hierarchyIds = new Array(); - const parsedIdToNodeMap = new Map(); - // 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) - const loadedTransformNodes = []; - if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) { - for (let index = 0, cache = parsedData.transformNodes.length; index < cache; index++) { - const parsedJSONTransformNode = parsedData.transformNodes[index]; - const parsedTransformNode = transformNode_TransformNode.Parse(parsedJSONTransformNode, scene, rootUrl); - loadedTransformNodes.push(parsedTransformNode); - parsedIdToNodeMap.set(parsedTransformNode._waitingParsedUniqueId, parsedTransformNode); - parsedTransformNode._waitingParsedUniqueId = null; - } - } - if (parsedData.meshes !== undefined && parsedData.meshes !== null) { - const loadedSkeletonsIds = []; - const loadedMaterialsIds = []; - const loadedMaterialsUniqueIds = []; - const loadedMorphTargetsIds = []; - for (let index = 0, cache = parsedData.meshes.length; index < cache; index++) { - const parsedMesh = parsedData.meshes[index]; - if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) { - if (meshesNames !== null) { - // Remove found mesh name from list. - delete meshesNames[meshesNames.indexOf(parsedMesh.name)]; - } - //Geometry? - if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) { - //does the file contain geometries? - if (parsedData.geometries !== undefined && parsedData.geometries !== null) { - //find the correct geometry and add it to the scene - let found = false; - ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach((geometryType) => { - if (found === true || !parsedData.geometries[geometryType] || !Array.isArray(parsedData.geometries[geometryType])) { - return; - } - else { - parsedData.geometries[geometryType].forEach((parsedGeometryData) => { - if (parsedGeometryData.id === parsedMesh.geometryId) { - switch (geometryType) { - case "vertexData": - Geometry.Parse(parsedGeometryData, scene, rootUrl); - break; - } - found = true; - } - }); - } - }); - if (found === false) { - logger_Logger.Warn("Geometry not found for mesh " + parsedMesh.id); - } - } - } - // Material ? - if (parsedMesh.materialUniqueId || parsedMesh.materialId) { - // if we have a unique ID, look up and store in loadedMaterialsUniqueIds, else use loadedMaterialsIds - const materialArray = parsedMesh.materialUniqueId ? loadedMaterialsUniqueIds : loadedMaterialsIds; - let materialFound = materialArray.indexOf(parsedMesh.materialUniqueId || parsedMesh.materialId) !== -1; - if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) { - // Loads a submaterial of a multimaterial - const loadSubMaterial = (subMatId, predicate) => { - materialArray.push(subMatId); - const mat = parseMaterialByPredicate(predicate, parsedData, scene, rootUrl); - if (mat && mat.material) { - tempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material; - log += "\n\tMaterial " + mat.material.toString(fullDetails); - } - }; - for (let multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) { - const parsedMultiMaterial = parsedData.multiMaterials[multimatIndex]; - if ((parsedMesh.materialUniqueId && parsedMultiMaterial.uniqueId === parsedMesh.materialUniqueId) || - parsedMultiMaterial.id === parsedMesh.materialId) { - if (parsedMultiMaterial.materialsUniqueIds) { - // if the materials inside the multimat are stored by unique id - parsedMultiMaterial.materialsUniqueIds.forEach((subMatId) => loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.uniqueId === subMatId)); - } - else { - // if the mats are stored by id instead - parsedMultiMaterial.materials.forEach((subMatId) => loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.id === subMatId)); - } - materialArray.push(parsedMultiMaterial.uniqueId || parsedMultiMaterial.id); - const mmat = multiMaterial_MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene); - tempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat; - if (mmat) { - materialFound = true; - log += "\n\tMulti-Material " + mmat.toString(fullDetails); - } - break; - } - } - } - if (materialFound === false) { - materialArray.push(parsedMesh.materialUniqueId || parsedMesh.materialId); - const mat = parseMaterialByPredicate((parsedMaterial) => (parsedMesh.materialUniqueId && parsedMaterial.uniqueId === parsedMesh.materialUniqueId) || parsedMaterial.id === parsedMesh.materialId, parsedData, scene, rootUrl); - if (!mat || !mat.material) { - logger_Logger.Warn("Material not found for mesh " + parsedMesh.id); - } - else { - tempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material; - log += "\n\tMaterial " + mat.material.toString(fullDetails); - } - } - } - // Skeleton ? - if (parsedMesh.skeletonId !== null && - parsedMesh.skeletonId !== undefined && - parsedData.skeletonId !== -1 && - parsedData.skeletons !== undefined && - parsedData.skeletons !== null) { - const skeletonAlreadyLoaded = loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1; - if (!skeletonAlreadyLoaded) { - for (let skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) { - const parsedSkeleton = parsedData.skeletons[skeletonIndex]; - if (parsedSkeleton.id === parsedMesh.skeletonId) { - const skeleton = skeleton_Skeleton.Parse(parsedSkeleton, scene); - skeletons.push(skeleton); - loadedSkeletonsIds.push(parsedSkeleton.id); - log += "\n\tSkeleton " + skeleton.toString(fullDetails); - } - } - } - } - // Morph targets ? - if (parsedMesh.morphTargetManagerId > -1 && parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) { - const morphTargetAlreadyLoaded = loadedMorphTargetsIds.indexOf(parsedMesh.morphTargetManagerId) > -1; - if (!morphTargetAlreadyLoaded) { - for (let morphTargetIndex = 0, morphTargetCache = parsedData.morphTargetManagers.length; morphTargetIndex < morphTargetCache; morphTargetIndex++) { - const parsedMorphTarget = parsedData.morphTargetManagers[morphTargetIndex]; - if (parsedMorphTarget.id === parsedMesh.morphTargetManagerId) { - const morphTarget = morphTargetManager_MorphTargetManager.Parse(parsedMorphTarget, scene); - loadedMorphTargetsIds.push(morphTarget.uniqueId); - log += "\nMorph target " + morphTarget.toString(); - } - } - } - } - const mesh = mesh_Mesh.Parse(parsedMesh, scene, rootUrl); - meshes.push(mesh); - parsedIdToNodeMap.set(mesh._waitingParsedUniqueId, mesh); - mesh._waitingParsedUniqueId = null; - log += "\n\tMesh " + mesh.toString(fullDetails); - } - } - // link multimats with materials - scene.multiMaterials.forEach((multimat) => { - multimat._waitingSubMaterialsUniqueIds.forEach((subMaterial) => { - multimat.subMaterials.push(findMaterial(subMaterial, scene)); - }); - multimat._waitingSubMaterialsUniqueIds = []; - }); - // link meshes with materials - scene.meshes.forEach((mesh) => { - if (mesh._waitingMaterialId !== null) { - mesh.material = findMaterial(mesh._waitingMaterialId, scene); - mesh._waitingMaterialId = null; - } - }); - // Connecting parents and lods - for (let index = 0, cache = scene.transformNodes.length; index < cache; index++) { - const transformNode = scene.transformNodes[index]; - if (transformNode._waitingParentId !== null) { - let parent = parsedIdToNodeMap.get(parseInt(transformNode._waitingParentId)) || null; - if (parent === null) { - parent = scene.getLastEntryById(transformNode._waitingParentId); - } - let parentNode = parent; - if (transformNode._waitingParentInstanceIndex) { - parentNode = parent.instances[parseInt(transformNode._waitingParentInstanceIndex)]; - transformNode._waitingParentInstanceIndex = null; - } - transformNode.parent = parentNode; - transformNode._waitingParentId = null; - } - } - let currentMesh; - for (let index = 0, cache = scene.meshes.length; index < cache; index++) { - currentMesh = scene.meshes[index]; - if (currentMesh._waitingParentId) { - let parent = parsedIdToNodeMap.get(parseInt(currentMesh._waitingParentId)) || null; - if (parent === null) { - parent = scene.getLastEntryById(currentMesh._waitingParentId); - } - let parentNode = parent; - if (currentMesh._waitingParentInstanceIndex) { - parentNode = parent.instances[parseInt(currentMesh._waitingParentInstanceIndex)]; - currentMesh._waitingParentInstanceIndex = null; - } - currentMesh.parent = parentNode; - if (((_a = currentMesh.parent) === null || _a === void 0 ? void 0 : _a.getClassName()) === "TransformNode") { - const loadedTransformNodeIndex = loadedTransformNodes.indexOf(currentMesh.parent); - if (loadedTransformNodeIndex > -1) { - loadedTransformNodes.splice(loadedTransformNodeIndex, 1); - } - } - currentMesh._waitingParentId = null; - } - if (currentMesh._waitingData.lods) { - loadDetailLevels(scene, currentMesh); - } - } - // Remove unused transform nodes - for (const transformNode of loadedTransformNodes) { - transformNode.dispose(); - } - // link skeleton transform nodes - for (let index = 0, cache = scene.skeletons.length; index < cache; index++) { - const skeleton = scene.skeletons[index]; - if (skeleton._hasWaitingData) { - if (skeleton.bones != null) { - skeleton.bones.forEach((bone) => { - if (bone._waitingTransformNodeId) { - const linkTransformNode = scene.getLastEntryById(bone._waitingTransformNodeId); - if (linkTransformNode) { - bone.linkTransformNode(linkTransformNode); - } - bone._waitingTransformNodeId = null; - } - }); - } - skeleton._hasWaitingData = null; - } - } - // freeze and compute world matrix application - for (let index = 0, cache = scene.meshes.length; index < cache; index++) { - currentMesh = scene.meshes[index]; - if (currentMesh._waitingData.freezeWorldMatrix) { - currentMesh.freezeWorldMatrix(); - currentMesh._waitingData.freezeWorldMatrix = null; - } - else { - currentMesh.computeWorldMatrix(true); - } - } - } - // Particles - if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) { - const parser = AbstractScene.GetIndividualParser(sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM); - if (parser) { - for (let index = 0, cache = parsedData.particleSystems.length; index < cache; index++) { - const parsedParticleSystem = parsedData.particleSystems[index]; - if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) { - particleSystems.push(parser(parsedParticleSystem, scene, rootUrl)); - } - } - } - } - scene.geometries.forEach((g) => { - g._loadedUniqueId = ""; - }); - return true; - } - catch (err) { - const msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log; - if (onError) { - onError(msg, err); - } - else { - logger_Logger.Log(msg); - throw err; - } - } - finally { - if (log !== null && sceneLoader_SceneLoader.loggingLevel !== sceneLoader_SceneLoader.NO_LOGGING) { - logger_Logger.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (sceneLoader_SceneLoader.loggingLevel !== sceneLoader_SceneLoader.MINIMAL_LOGGING ? log : "")); - } - tempMaterialIndexContainer = {}; - } - return false; - }, - load: (scene, data, rootUrl, onError) => { - // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details - // when SceneLoader.debugLogging = true (default), or exception encountered. - // Everything stored in var log instead of writing separate lines to support only writing in exception, - // and avoid problems with multiple concurrent .babylon loads. - let log = "importScene has failed JSON parse"; - try { - // eslint-disable-next-line no-var - var parsedData = JSON.parse(data); - log = ""; - // Scene - if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) { - scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !sceneLoader_SceneLoader.ForceFullSceneLoadingForIncremental; - } - if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) { - scene.autoClear = parsedData.autoClear; - } - if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) { - scene.clearColor = math_color_Color4.FromArray(parsedData.clearColor); - } - if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) { - scene.ambientColor = math_color_Color3.FromArray(parsedData.ambientColor); - } - if (parsedData.gravity !== undefined && parsedData.gravity !== null) { - scene.gravity = math_vector_Vector3.FromArray(parsedData.gravity); - } - if (parsedData.useRightHandedSystem !== undefined) { - scene.useRightHandedSystem = !!parsedData.useRightHandedSystem; - } - // Fog - if (parsedData.fogMode && parsedData.fogMode !== 0) { - scene.fogMode = parsedData.fogMode; - scene.fogColor = math_color_Color3.FromArray(parsedData.fogColor); - scene.fogStart = parsedData.fogStart; - scene.fogEnd = parsedData.fogEnd; - scene.fogDensity = parsedData.fogDensity; - log += "\tFog mode for scene: "; - switch (scene.fogMode) { - // getters not compiling, so using hardcoded - case 1: - log += "exp\n"; - break; - case 2: - log += "exp2\n"; - break; - case 3: - log += "linear\n"; - break; - } - } - //Physics - if (parsedData.physicsEnabled) { - let physicsPlugin; - if (parsedData.physicsEngine === "cannon" || parsedData.physicsEngine === CannonJSPlugin.name) { - physicsPlugin = new CannonJSPlugin(undefined, undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine); - } - else if (parsedData.physicsEngine === "oimo" || parsedData.physicsEngine === OimoJSPlugin.name) { - physicsPlugin = new OimoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine); - } - else if (parsedData.physicsEngine === "ammo" || parsedData.physicsEngine === AmmoJSPlugin.name) { - physicsPlugin = new AmmoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine, undefined); - } - log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n"; - //else - default engine, which is currently oimo - const physicsGravity = parsedData.physicsGravity ? math_vector_Vector3.FromArray(parsedData.physicsGravity) : null; - scene.enablePhysics(physicsGravity, physicsPlugin); - } - // Metadata - if (parsedData.metadata !== undefined && parsedData.metadata !== null) { - scene.metadata = parsedData.metadata; - } - //collisions, if defined. otherwise, default is true - if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) { - scene.collisionsEnabled = parsedData.collisionsEnabled; - } - const container = loadAssetContainer(scene, data, rootUrl, onError, true); - if (!container) { - return false; - } - if (parsedData.autoAnimate) { - scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0); - } - if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) { - scene.setActiveCameraById(parsedData.activeCameraID); - } - // Finish - return true; - } - catch (err) { - const msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log; - if (onError) { - onError(msg, err); - } - else { - logger_Logger.Log(msg); - throw err; - } - } - finally { - if (log !== null && sceneLoader_SceneLoader.loggingLevel !== sceneLoader_SceneLoader.NO_LOGGING) { - logger_Logger.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (sceneLoader_SceneLoader.loggingLevel !== sceneLoader_SceneLoader.MINIMAL_LOGGING ? log : "")); - } - } - return false; - }, - loadAssetContainer: (scene, data, rootUrl, onError) => { - const container = loadAssetContainer(scene, data, rootUrl, onError); - return container; - }, -}); -//# sourceMappingURL=babylonFileLoader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Loading/Plugins/index.js - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Loading/index.js -/* eslint-disable import/no-internal-modules */ - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Background/index.js - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/iEffectFallbacks.js - -//# sourceMappingURL=iEffectFallbacks.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/fresnelParameters.js - - - - - -/** - * This represents all the required information to add a fresnel effect on a material: - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/fresnelParameters - */ -class FresnelParameters { - /** - * Define if the fresnel effect is enable or not. - */ - get isEnabled() { - return this._isEnabled; - } - set isEnabled(value) { - if (this._isEnabled === value) { - return; - } - this._isEnabled = value; - engine_Engine.MarkAllMaterialsAsDirty(4 | 16); - } - /** - * Creates a new FresnelParameters object. - * - * @param options provide your own settings to optionally to override defaults - */ - constructor(options = {}) { - this._isEnabled = true; - this.bias = options.bias === undefined ? 0 : options.bias; - this.power = options.power === undefined ? 1 : options.power; - this.leftColor = options.leftColor || math_color_Color3.White(); - this.rightColor = options.rightColor || math_color_Color3.Black(); - if (options.isEnabled === false) { - this.isEnabled = false; - } - } - /** - * Clones the current fresnel and its values - * @returns a clone fresnel configuration - */ - clone() { - const newFresnelParameters = new FresnelParameters(); - DeepCopier.DeepCopy(this, newFresnelParameters); - return newFresnelParameters; - } - /** - * Determines equality between FresnelParameters objects - * @param otherFresnelParameters defines the second operand - * @returns true if the power, bias, leftColor, rightColor and isEnabled values are equal to the given ones - */ - equals(otherFresnelParameters) { - return (otherFresnelParameters && - this.bias === otherFresnelParameters.bias && - this.power === otherFresnelParameters.power && - this.leftColor.equals(otherFresnelParameters.leftColor) && - this.rightColor.equals(otherFresnelParameters.rightColor) && - this.isEnabled === otherFresnelParameters.isEnabled); - } - /** - * Serializes the current fresnel parameters to a JSON representation. - * @returns the JSON serialization - */ - serialize() { - return { - isEnabled: this.isEnabled, - leftColor: this.leftColor.asArray(), - rightColor: this.rightColor.asArray(), - bias: this.bias, - power: this.power, - }; - } - /** - * Parse a JSON object and deserialize it to a new Fresnel parameter object. - * @param parsedFresnelParameters Define the JSON representation - * @returns the parsed parameters - */ - static Parse(parsedFresnelParameters) { - return new FresnelParameters({ - isEnabled: parsedFresnelParameters.isEnabled, - leftColor: math_color_Color3.FromArray(parsedFresnelParameters.leftColor), - rightColor: math_color_Color3.FromArray(parsedFresnelParameters.rightColor), - bias: parsedFresnelParameters.bias, - power: parsedFresnelParameters.power || 1.0, - }); - } -} -// References the dependencies. -decorators_SerializationHelper._FresnelParametersParser = FresnelParameters.Parse; -//# sourceMappingURL=fresnelParameters.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Occlusion/occlusionMaterial.js - - - - -/** - * A material to use for fast depth-only rendering. - * @since 5.0.0 - */ -class OcclusionMaterial extends (/* unused pure expression or super */ null && (ShaderMaterial)) { - constructor(name, scene) { - super(name, scene, "color", { - attributes: ["position"], - uniforms: ["world", "viewProjection", "color"], - }); - this.disableColorWrite = true; - this.forceDepthWrite = true; - this.setColor4("color", new Color4(0, 0, 0, 1)); - } -} -//# sourceMappingURL=occlusionMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Occlusion/index.js - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrBaseSimpleMaterial.js - - - - -/** - * The Physically based simple base material of BJS. - * - * This enables better naming and convention enforcements on top of the pbrMaterial. - * It is used as the base class for both the specGloss and metalRough conventions. - */ -class PBRBaseSimpleMaterial extends pbrBaseMaterial_PBRBaseMaterial { - /** - * Gets the current double sided mode. - */ - get doubleSided() { - return this._twoSidedLighting; - } - /** - * If sets to true and backfaceCulling is false, normals will be flipped on the backside. - */ - set doubleSided(value) { - if (this._twoSidedLighting === value) { - return; - } - this._twoSidedLighting = value; - this.backFaceCulling = !value; - this._markAllSubMeshesAsTexturesDirty(); - } - /** - * Instantiates a new PBRMaterial instance. - * - * @param name The material name - * @param scene The scene the material will be use in. - */ - constructor(name, scene) { - super(name, scene); - /** - * Number of Simultaneous lights allowed on the material. - */ - this.maxSimultaneousLights = 4; - /** - * If sets to true, disables all the lights affecting the material. - */ - this.disableLighting = false; - /** - * If sets to true, x component of normal map value will invert (x = 1.0 - x). - */ - this.invertNormalMapX = false; - /** - * If sets to true, y component of normal map value will invert (y = 1.0 - y). - */ - this.invertNormalMapY = false; - /** - * Emissivie color used to self-illuminate the model. - */ - this.emissiveColor = new math_color_Color3(0, 0, 0); - /** - * Occlusion Channel Strength. - */ - this.occlusionStrength = 1.0; - /** - * If true, the light map contains occlusion information instead of lighting info. - */ - this.useLightmapAsShadowmap = false; - this._useAlphaFromAlbedoTexture = true; - this._useAmbientInGrayScale = true; - } - getClassName() { - return "PBRBaseSimpleMaterial"; - } -} -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsLightsDirty") -], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsLightsDirty") -], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture") -], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture") -], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0); -__decorate([ - serializeAsColor3("emissive"), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength") -], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture") -], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff") -], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0); -__decorate([ - serialize() -], PBRBaseSimpleMaterial.prototype, "doubleSided", null); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", null) -], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0); -//# sourceMappingURL=pbrBaseSimpleMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrMetallicRoughnessMaterial.js - - - - -/** - * The PBR material of BJS following the metal roughness convention. - * - * This fits to the PBR convention in the GLTF definition: - * https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md - */ -class PBRMetallicRoughnessMaterial extends PBRBaseSimpleMaterial { - /** - * Instantiates a new PBRMetalRoughnessMaterial instance. - * - * @param name The material name - * @param scene The scene the material will be use in. - */ - constructor(name, scene) { - super(name, scene); - this._useRoughnessFromMetallicTextureAlpha = false; - this._useRoughnessFromMetallicTextureGreen = true; - this._useMetallnessFromMetallicTextureBlue = true; - this.metallic = 1.0; - this.roughness = 1.0; - } - /** - * Return the current class name of the material. - */ - getClassName() { - return "PBRMetallicRoughnessMaterial"; - } - /** - * Makes a duplicate of the current material. - * @param name - name to use for the new material. - */ - clone(name) { - const clone = decorators_SerializationHelper.Clone(() => new PBRMetallicRoughnessMaterial(name, this.getScene()), this); - clone.id = name; - clone.name = name; - this.clearCoat.copyTo(clone.clearCoat); - this.anisotropy.copyTo(clone.anisotropy); - this.brdf.copyTo(clone.brdf); - this.sheen.copyTo(clone.sheen); - this.subSurface.copyTo(clone.subSurface); - return clone; - } - /** - * Serialize the material to a parsable JSON object. - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial"; - serializationObject.clearCoat = this.clearCoat.serialize(); - serializationObject.anisotropy = this.anisotropy.serialize(); - serializationObject.brdf = this.brdf.serialize(); - serializationObject.sheen = this.sheen.serialize(); - serializationObject.subSurface = this.subSurface.serialize(); - serializationObject.iridescence = this.iridescence.serialize(); - return serializationObject; - } - /** - * Parses a JSON object corresponding to the serialize function. - * @param source - * @param scene - * @param rootUrl - */ - static Parse(source, scene, rootUrl) { - const material = decorators_SerializationHelper.Parse(() => new PBRMetallicRoughnessMaterial(source.name, scene), source, scene, rootUrl); - if (source.clearCoat) { - material.clearCoat.parse(source.clearCoat, scene, rootUrl); - } - if (source.anisotropy) { - material.anisotropy.parse(source.anisotropy, scene, rootUrl); - } - if (source.brdf) { - material.brdf.parse(source.brdf, scene, rootUrl); - } - if (source.sheen) { - material.sheen.parse(source.sheen, scene, rootUrl); - } - if (source.subSurface) { - material.subSurface.parse(source.subSurface, scene, rootUrl); - } - if (source.iridescence) { - material.iridescence.parse(source.iridescence, scene, rootUrl); - } - return material; - } -} -__decorate([ - serializeAsColor3(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor") -], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture") -], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture") -], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0); -RegisterClass("BABYLON.PBRMetallicRoughnessMaterial", PBRMetallicRoughnessMaterial); -//# sourceMappingURL=pbrMetallicRoughnessMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrSpecularGlossinessMaterial.js - - - - -/** - * The PBR material of BJS following the specular glossiness convention. - * - * This fits to the PBR convention in the GLTF definition: - * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness - */ -class PBRSpecularGlossinessMaterial extends PBRBaseSimpleMaterial { - /** - * Specifies if the reflectivity texture contains the glossiness information in its alpha channel. - */ - get useMicroSurfaceFromReflectivityMapAlpha() { - return this._useMicroSurfaceFromReflectivityMapAlpha; - } - /** - * Instantiates a new PBRSpecularGlossinessMaterial instance. - * - * @param name The material name - * @param scene The scene the material will be use in. - */ - constructor(name, scene) { - super(name, scene); - this._useMicroSurfaceFromReflectivityMapAlpha = true; - } - /** - * Return the current class name of the material. - */ - getClassName() { - return "PBRSpecularGlossinessMaterial"; - } - /** - * Makes a duplicate of the current material. - * @param name - name to use for the new material. - */ - clone(name) { - const clone = decorators_SerializationHelper.Clone(() => new PBRSpecularGlossinessMaterial(name, this.getScene()), this); - clone.id = name; - clone.name = name; - this.clearCoat.copyTo(clone.clearCoat); - this.anisotropy.copyTo(clone.anisotropy); - this.brdf.copyTo(clone.brdf); - this.sheen.copyTo(clone.sheen); - this.subSurface.copyTo(clone.subSurface); - return clone; - } - /** - * Serialize the material to a parsable JSON object. - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial"; - serializationObject.clearCoat = this.clearCoat.serialize(); - serializationObject.anisotropy = this.anisotropy.serialize(); - serializationObject.brdf = this.brdf.serialize(); - serializationObject.sheen = this.sheen.serialize(); - serializationObject.subSurface = this.subSurface.serialize(); - serializationObject.iridescence = this.iridescence.serialize(); - return serializationObject; - } - /** - * Parses a JSON object corresponding to the serialize function. - * @param source - * @param scene - * @param rootUrl - */ - static Parse(source, scene, rootUrl) { - const material = decorators_SerializationHelper.Parse(() => new PBRSpecularGlossinessMaterial(source.name, scene), source, scene, rootUrl); - if (source.clearCoat) { - material.clearCoat.parse(source.clearCoat, scene, rootUrl); - } - if (source.anisotropy) { - material.anisotropy.parse(source.anisotropy, scene, rootUrl); - } - if (source.brdf) { - material.brdf.parse(source.brdf, scene, rootUrl); - } - if (source.sheen) { - material.sheen.parse(source.sheen, scene, rootUrl); - } - if (source.subSurface) { - material.subSurface.parse(source.subSurface, scene, rootUrl); - } - if (source.iridescence) { - material.iridescence.parse(source.iridescence, scene, rootUrl); - } - return material; - } -} -__decorate([ - serializeAsColor3("diffuse"), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor") -], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture") -], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0); -__decorate([ - serializeAsColor3("specular"), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor") -], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface") -], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0); -__decorate([ - serializeAsTexture(), - expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture") -], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0); -RegisterClass("BABYLON.PBRSpecularGlossinessMaterial", PBRSpecularGlossinessMaterial); -//# sourceMappingURL=pbrSpecularGlossinessMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/index.js - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/colorGradingTexture.js - - - - -// Ensures Raw texture are included - -/** - * This represents a color grading texture. This acts as a lookup table LUT, useful during post process - * It can help converting any input color in a desired output one. This can then be used to create effects - * from sepia, black and white to sixties or futuristic rendering... - * - * The only supported format is currently 3dl. - * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table - */ -class ColorGradingTexture extends baseTexture_BaseTexture { - /** - * Instantiates a ColorGradingTexture from the following parameters. - * - * @param url The location of the color grading data (currently only supporting 3dl) - * @param sceneOrEngine The scene or engine the texture will be used in - * @param onLoad defines a callback triggered when the texture has been loaded - */ - constructor(url, sceneOrEngine, onLoad = null) { - super(sceneOrEngine); - if (!url) { - return; - } - this._textureMatrix = math_vector_Matrix.Identity(); - this.name = url; - this.url = url; - this._onLoad = onLoad; - this._texture = this._getFromCache(url, true); - if (!this._texture) { - const scene = this.getScene(); - if (scene) { - if (!scene.useDelayedTextureLoading) { - this._loadTexture(); - } - else { - this.delayLoadState = 4; - } - } - else { - this._loadTexture(); - } - } - else { - this._triggerOnLoad(); - } - } - /** - * Fires the onload event from the constructor if requested. - */ - _triggerOnLoad() { - if (this._onLoad) { - this._onLoad(); - } - } - /** - * Returns the texture matrix used in most of the material. - * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in). - */ - getTextureMatrix() { - return this._textureMatrix; - } - /** - * Occurs when the file being loaded is a .3dl LUT file. - */ - _load3dlTexture() { - const engine = this._getEngine(); - let texture; - if (!engine._features.support3DTextures) { - texture = engine.createRawTexture(null, 1, 1, 5, false, false, 2, null, 0); - } - else { - texture = engine.createRawTexture3D(null, 1, 1, 1, 5, false, false, 2, null, 0); - } - this._texture = texture; - this._texture.isReady = false; - this.isCube = false; - this.is3D = engine._features.support3DTextures; - this.wrapU = 0; - this.wrapV = 0; - this.wrapR = 0; - this.anisotropicFilteringLevel = 1; - const callback = (text) => { - if (typeof text !== "string") { - return; - } - let data = null; - let tempData = null; - let line; - const lines = text.split("\n"); - let size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0; - let maxColor = 0; - for (let i = 0; i < lines.length; i++) { - line = lines[i]; - if (!ColorGradingTexture._NoneEmptyLineRegex.test(line)) { - continue; - } - if (line.indexOf("#") === 0) { - continue; - } - const words = line.split(" "); - if (size === 0) { - // Number of space + one - size = words.length; - data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8 - tempData = new Float32Array(size * size * size * 4); - continue; - } - if (size != 0) { - const r = Math.max(parseInt(words[0]), 0); - const g = Math.max(parseInt(words[1]), 0); - const b = Math.max(parseInt(words[2]), 0); - maxColor = Math.max(r, maxColor); - maxColor = Math.max(g, maxColor); - maxColor = Math.max(b, maxColor); - const pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4; - if (tempData) { - tempData[pixelStorageIndex + 0] = r; - tempData[pixelStorageIndex + 1] = g; - tempData[pixelStorageIndex + 2] = b; - } - // Keep for reference in case of back compat problems. - // pixelIndexSlice++; - // if (pixelIndexSlice % size == 0) { - // pixelIndexH++; - // pixelIndexSlice = 0; - // if (pixelIndexH % size == 0) { - // pixelIndexW++; - // pixelIndexH = 0; - // } - // } - pixelIndexH++; - if (pixelIndexH % size == 0) { - pixelIndexSlice++; - pixelIndexH = 0; - if (pixelIndexSlice % size == 0) { - pixelIndexW++; - pixelIndexSlice = 0; - } - } - } - } - if (tempData && data) { - for (let i = 0; i < tempData.length; i++) { - if (i > 0 && (i + 1) % 4 === 0) { - data[i] = 255; - } - else { - const value = tempData[i]; - data[i] = (value / maxColor) * 255; - } - } - } - if (texture.is3D) { - texture.updateSize(size, size, size); - engine.updateRawTexture3D(texture, data, 5, false); - } - else { - texture.updateSize(size * size, size); - engine.updateRawTexture(texture, data, 5, false); - } - texture.isReady = true; - this._triggerOnLoad(); - }; - const scene = this.getScene(); - if (scene) { - scene._loadFile(this.url, callback); - } - else { - engine._loadFile(this.url, callback); - } - return this._texture; - } - /** - * Starts the loading process of the texture. - */ - _loadTexture() { - if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == this.url.length - 4) { - this._load3dlTexture(); - } - } - /** - * Clones the color grading texture. - */ - clone() { - const newTexture = new ColorGradingTexture(this.url, this.getScene() || this._getEngine()); - // Base texture - newTexture.level = this.level; - return newTexture; - } - /** - * Called during delayed load for textures. - */ - delayLoad() { - if (this.delayLoadState !== 4) { - return; - } - this.delayLoadState = 1; - this._texture = this._getFromCache(this.url, true); - if (!this._texture) { - this._loadTexture(); - } - } - /** - * Parses a color grading texture serialized by Babylon. - * @param parsedTexture The texture information being parsedTexture - * @param scene The scene to load the texture in - * @returns A color grading texture - */ - static Parse(parsedTexture, scene) { - let texture = null; - if (parsedTexture.name && !parsedTexture.isRenderTarget) { - texture = new ColorGradingTexture(parsedTexture.name, scene); - texture.name = parsedTexture.name; - texture.level = parsedTexture.level; - } - return texture; - } - /** - * Serializes the LUT texture to json format. - */ - serialize() { - if (!this.name) { - return null; - } - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.level = this.level; - serializationObject.customType = "BABYLON.ColorGradingTexture"; - return serializationObject; - } -} -/** - * Empty line regex stored for GC. - */ -ColorGradingTexture._NoneEmptyLineRegex = /\S+/; -RegisterClass("BABYLON.ColorGradingTexture", ColorGradingTexture); -//# sourceMappingURL=colorGradingTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/equiRectangularCubeTexture.js - - - - - - - -/** - * This represents a texture coming from an equirectangular image supported by the web browser canvas. - */ -class equiRectangularCubeTexture_EquiRectangularCubeTexture extends baseTexture_BaseTexture { - /** - * Instantiates an EquiRectangularCubeTexture from the following parameters. - * @param url The location of the image - * @param scene The scene the texture will be used in - * @param size The cubemap desired size (the more it increases the longer the generation will be) - * @param noMipmap Forces to not generate the mipmap if true - * @param gammaSpace Specifies if the texture will be used in gamma or linear space - * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space) - * @param onLoad — defines a callback called when texture is loaded - * @param onError — defines a callback called if there is an error - */ - constructor(url, scene, size, noMipmap = false, gammaSpace = true, onLoad = null, onError = null, supersample = false) { - super(scene); - this._onLoad = null; - this._onError = null; - if (!url) { - throw new Error("Image url is not set"); - } - this._coordinatesMode = texture_Texture.CUBIC_MODE; - this.name = url; - this.url = url; - this._size = size; - this._supersample = supersample; - this._noMipmap = noMipmap; - this.gammaSpace = gammaSpace; - this._onLoad = onLoad; - this._onError = onError; - this.hasAlpha = false; - this.isCube = true; - this._texture = this._getFromCache(url, this._noMipmap, undefined, undefined, undefined, this.isCube); - if (!this._texture) { - if (!scene.useDelayedTextureLoading) { - this._loadImage(this._loadTexture.bind(this), this._onError); - } - else { - this.delayLoadState = 4; - } - } - else if (onLoad) { - if (this._texture.isReady) { - tools_Tools.SetImmediate(() => onLoad()); - } - else { - this._texture.onLoadedObservable.add(onLoad); - } - } - } - /** - * Load the image data, by putting the image on a canvas and extracting its buffer. - * @param loadTextureCallback - * @param onError - */ - _loadImage(loadTextureCallback, onError) { - const canvas = document.createElement("canvas"); - LoadImage(this.url, (image) => { - this._width = image.width; - this._height = image.height; - canvas.width = this._width; - canvas.height = this._height; - const ctx = canvas.getContext("2d"); - ctx.drawImage(image, 0, 0); - const imageData = ctx.getImageData(0, 0, image.width, image.height); - this._buffer = imageData.data.buffer; - canvas.remove(); - loadTextureCallback(); - }, (_, e) => { - if (onError) { - onError(`${this.getClassName()} could not be loaded`, e); - } - }, null); - } - /** - * Convert the image buffer into a cubemap and create a CubeTexture. - */ - _loadTexture() { - const scene = this.getScene(); - const callback = () => { - const imageData = this._getFloat32ArrayFromArrayBuffer(this._buffer); - // Extract the raw linear data. - const data = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(imageData, this._width, this._height, this._size, this._supersample); - const results = []; - // Push each faces. - for (let i = 0; i < 6; i++) { - const dataFace = data[equiRectangularCubeTexture_EquiRectangularCubeTexture._FacesMapping[i]]; - results.push(dataFace); - } - return results; - }; - if (!scene) { - return; - } - this._texture = scene - .getEngine() - .createRawCubeTextureFromUrl(this.url, scene, this._size, 4, scene.getEngine().getCaps().textureFloat ? 1 : 7, this._noMipmap, callback, null, this._onLoad, this._onError); - } - /** - * Convert the ArrayBuffer into a Float32Array and drop the transparency channel. - * @param buffer The ArrayBuffer that should be converted. - * @returns The buffer as Float32Array. - */ - _getFloat32ArrayFromArrayBuffer(buffer) { - const dataView = new DataView(buffer); - const floatImageData = new Float32Array((buffer.byteLength * 3) / 4); - let k = 0; - for (let i = 0; i < buffer.byteLength; i++) { - // We drop the transparency channel, because we do not need/want it - if ((i + 1) % 4 !== 0) { - floatImageData[k++] = dataView.getUint8(i) / 255; - } - } - return floatImageData; - } - /** - * Get the current class name of the texture useful for serialization or dynamic coding. - * @returns "EquiRectangularCubeTexture" - */ - getClassName() { - return "EquiRectangularCubeTexture"; - } - /** - * Create a clone of the current EquiRectangularCubeTexture and return it. - * @returns A clone of the current EquiRectangularCubeTexture. - */ - clone() { - const scene = this.getScene(); - if (!scene) { - return this; - } - const newTexture = new equiRectangularCubeTexture_EquiRectangularCubeTexture(this.url, scene, this._size, this._noMipmap, this.gammaSpace); - // Base texture - newTexture.level = this.level; - newTexture.wrapU = this.wrapU; - newTexture.wrapV = this.wrapV; - newTexture.coordinatesIndex = this.coordinatesIndex; - newTexture.coordinatesMode = this.coordinatesMode; - return newTexture; - } -} -/** The six faces of the cube. */ -equiRectangularCubeTexture_EquiRectangularCubeTexture._FacesMapping = ["right", "left", "up", "down", "front", "back"]; -//# sourceMappingURL=equiRectangularCubeTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/htmlElementTexture.js - - - - - - - -/** - * This represents the smallest workload to use an already existing element (Canvas or Video) as a texture. - * To be as efficient as possible depending on your constraints nothing aside the first upload - * is automatically managed. - * It is a cheap VideoTexture or DynamicTexture if you prefer to keep full control of the elements - * in your application. - * - * As the update is not automatic, you need to call them manually. - */ -class HtmlElementTexture extends baseTexture_BaseTexture { - /** - * Instantiates a HtmlElementTexture from the following parameters. - * - * @param name Defines the name of the texture - * @param element Defines the video or canvas the texture is filled with - * @param options Defines the other none mandatory texture creation options - */ - constructor(name, element, options) { - var _a, _b; - super(options.scene || options.engine); - /** - * Observable triggered once the texture has been loaded. - */ - this.onLoadObservable = new observable_Observable(); - if (!element || (!options.engine && !options.scene)) { - return; - } - options = Object.assign(Object.assign({}, HtmlElementTexture._DefaultOptions), options); - this._generateMipMaps = options.generateMipMaps; - this._samplingMode = options.samplingMode; - this._textureMatrix = math_vector_Matrix.Identity(); - this._format = options.format; - this.name = name; - this.element = element; - this._isVideo = !!element.getVideoPlaybackQuality; - this._externalTexture = this._isVideo ? (_b = (_a = this._engine) === null || _a === void 0 ? void 0 : _a.createExternalTexture(element)) !== null && _b !== void 0 ? _b : null : null; - this.anisotropicFilteringLevel = 1; - this._createInternalTexture(); - } - _createInternalTexture() { - let width = 0; - let height = 0; - if (this._isVideo) { - width = this.element.videoWidth; - height = this.element.videoHeight; - } - else { - width = this.element.width; - height = this.element.height; - } - const engine = this._getEngine(); - if (engine) { - this._texture = engine.createDynamicTexture(width, height, this._generateMipMaps, this._samplingMode); - this._texture.format = this._format; - } - this.update(); - } - /** - * Returns the texture matrix used in most of the material. - */ - getTextureMatrix() { - return this._textureMatrix; - } - /** - * Updates the content of the texture. - * @param invertY Defines whether the texture should be inverted on Y (false by default on video and true on canvas) - */ - update(invertY = null) { - const engine = this._getEngine(); - if (this._texture == null || engine == null) { - return; - } - const wasReady = this.isReady(); - if (this._isVideo) { - const videoElement = this.element; - if (videoElement.readyState < videoElement.HAVE_CURRENT_DATA) { - return; - } - engine.updateVideoTexture(this._texture, this._externalTexture ? this._externalTexture : videoElement, invertY === null ? true : invertY); - } - else { - const canvasElement = this.element; - engine.updateDynamicTexture(this._texture, canvasElement, invertY === null ? true : invertY, false, this._format); - } - if (!wasReady && this.isReady()) { - this.onLoadObservable.notifyObservers(this); - } - } - /** - * Dispose the texture and release its associated resources. - */ - dispose() { - this.onLoadObservable.clear(); - super.dispose(); - } -} -HtmlElementTexture._DefaultOptions = { - generateMipMaps: false, - samplingMode: 2, - format: 5, - engine: null, - scene: null, -}; -//# sourceMappingURL=htmlElementTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/internalTextureLoader.js - -//# sourceMappingURL=internalTextureLoader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/tga.js - -//private static _TYPE_NO_DATA = 0; -const _TYPE_INDEXED = 1; -const _TYPE_RGB = 2; -const _TYPE_GREY = 3; -const _TYPE_RLE_INDEXED = 9; -const _TYPE_RLE_RGB = 10; -const _TYPE_RLE_GREY = 11; -const _ORIGIN_MASK = 0x30; -const _ORIGIN_SHIFT = 0x04; -const _ORIGIN_BL = 0x00; -const _ORIGIN_BR = 0x01; -const _ORIGIN_UL = 0x02; -const _ORIGIN_UR = 0x03; -/** - * Gets the header of a TGA file - * @param data defines the TGA data - * @returns the header - */ -function GetTGAHeader(data) { - let offset = 0; - const header = { - id_length: data[offset++], - colormap_type: data[offset++], - image_type: data[offset++], - colormap_index: data[offset++] | (data[offset++] << 8), - colormap_length: data[offset++] | (data[offset++] << 8), - colormap_size: data[offset++], - origin: [data[offset++] | (data[offset++] << 8), data[offset++] | (data[offset++] << 8)], - width: data[offset++] | (data[offset++] << 8), - height: data[offset++] | (data[offset++] << 8), - pixel_size: data[offset++], - flags: data[offset++], - }; - return header; -} -/** - * Uploads TGA content to a Babylon Texture - * @internal - */ -function UploadContent(texture, data) { - // Not enough data to contain header ? - if (data.length < 19) { - logger_Logger.Error("Unable to load TGA file - Not enough data to contain header"); - return; - } - // Read Header - let offset = 18; - const header = GetTGAHeader(data); - // Assume it's a valid Targa file. - if (header.id_length + offset > data.length) { - logger_Logger.Error("Unable to load TGA file - Not enough data"); - return; - } - // Skip not needed data - offset += header.id_length; - let use_rle = false; - let use_pal = false; - let use_grey = false; - // Get some informations. - switch (header.image_type) { - case _TYPE_RLE_INDEXED: - use_rle = true; - // eslint-disable-next-line no-fallthrough - case _TYPE_INDEXED: - use_pal = true; - break; - case _TYPE_RLE_RGB: - use_rle = true; - // eslint-disable-next-line no-fallthrough - case _TYPE_RGB: - // use_rgb = true; - break; - case _TYPE_RLE_GREY: - use_rle = true; - // eslint-disable-next-line no-fallthrough - case _TYPE_GREY: - use_grey = true; - break; - } - let pixel_data; - // var numAlphaBits = header.flags & 0xf; - const pixel_size = header.pixel_size >> 3; - const pixel_total = header.width * header.height * pixel_size; - // Read palettes - let palettes; - if (use_pal) { - palettes = data.subarray(offset, (offset += header.colormap_length * (header.colormap_size >> 3))); - } - // Read LRE - if (use_rle) { - pixel_data = new Uint8Array(pixel_total); - let c, count, i; - let localOffset = 0; - const pixels = new Uint8Array(pixel_size); - while (offset < pixel_total && localOffset < pixel_total) { - c = data[offset++]; - count = (c & 0x7f) + 1; - // RLE pixels - if (c & 0x80) { - // Bind pixel tmp array - for (i = 0; i < pixel_size; ++i) { - pixels[i] = data[offset++]; - } - // Copy pixel array - for (i = 0; i < count; ++i) { - pixel_data.set(pixels, localOffset + i * pixel_size); - } - localOffset += pixel_size * count; - } - // Raw pixels - else { - count *= pixel_size; - for (i = 0; i < count; ++i) { - pixel_data[localOffset + i] = data[offset++]; - } - localOffset += count; - } - } - } - // RAW Pixels - else { - pixel_data = data.subarray(offset, (offset += use_pal ? header.width * header.height : pixel_total)); - } - // Load to texture - let x_start, y_start, x_step, y_step, y_end, x_end; - switch ((header.flags & _ORIGIN_MASK) >> _ORIGIN_SHIFT) { - default: - case _ORIGIN_UL: - x_start = 0; - x_step = 1; - x_end = header.width; - y_start = 0; - y_step = 1; - y_end = header.height; - break; - case _ORIGIN_BL: - x_start = 0; - x_step = 1; - x_end = header.width; - y_start = header.height - 1; - y_step = -1; - y_end = -1; - break; - case _ORIGIN_UR: - x_start = header.width - 1; - x_step = -1; - x_end = -1; - y_start = 0; - y_step = 1; - y_end = header.height; - break; - case _ORIGIN_BR: - x_start = header.width - 1; - x_step = -1; - x_end = -1; - y_start = header.height - 1; - y_step = -1; - y_end = -1; - break; - } - // Load the specify method - const func = "_getImageData" + (use_grey ? "Grey" : "") + header.pixel_size + "bits"; - const imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end); - const engine = texture.getEngine(); - engine._uploadDataToTextureDirectly(texture, imageData); -} -/** - * @internal - */ -function _getImageData8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { - const image = pixel_data, colormap = palettes; - const width = header.width, height = header.height; - let color, i = 0, x, y; - const imageData = new Uint8Array(width * height * 4); - for (y = y_start; y !== y_end; y += y_step) { - for (x = x_start; x !== x_end; x += x_step, i++) { - color = image[i]; - imageData[(x + width * y) * 4 + 3] = 255; - imageData[(x + width * y) * 4 + 2] = colormap[color * 3 + 0]; - imageData[(x + width * y) * 4 + 1] = colormap[color * 3 + 1]; - imageData[(x + width * y) * 4 + 0] = colormap[color * 3 + 2]; - } - } - return imageData; -} -/** - * @internal - */ -function _getImageData16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { - const image = pixel_data; - const width = header.width, height = header.height; - let color, i = 0, x, y; - const imageData = new Uint8Array(width * height * 4); - for (y = y_start; y !== y_end; y += y_step) { - for (x = x_start; x !== x_end; x += x_step, i += 2) { - color = image[i + 0] + (image[i + 1] << 8); // Inversed ? - const r = ((((color & 0x7c00) >> 10) * 255) / 0x1f) | 0; - const g = ((((color & 0x03e0) >> 5) * 255) / 0x1f) | 0; - const b = (((color & 0x001f) * 255) / 0x1f) | 0; - imageData[(x + width * y) * 4 + 0] = r; - imageData[(x + width * y) * 4 + 1] = g; - imageData[(x + width * y) * 4 + 2] = b; - imageData[(x + width * y) * 4 + 3] = color & 0x8000 ? 0 : 255; - } - } - return imageData; -} -/** - * @internal - */ -function _getImageData24bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { - const image = pixel_data; - const width = header.width, height = header.height; - let i = 0, x, y; - const imageData = new Uint8Array(width * height * 4); - for (y = y_start; y !== y_end; y += y_step) { - for (x = x_start; x !== x_end; x += x_step, i += 3) { - imageData[(x + width * y) * 4 + 3] = 255; - imageData[(x + width * y) * 4 + 2] = image[i + 0]; - imageData[(x + width * y) * 4 + 1] = image[i + 1]; - imageData[(x + width * y) * 4 + 0] = image[i + 2]; - } - } - return imageData; -} -/** - * @internal - */ -function _getImageData32bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { - const image = pixel_data; - const width = header.width, height = header.height; - let i = 0, x, y; - const imageData = new Uint8Array(width * height * 4); - for (y = y_start; y !== y_end; y += y_step) { - for (x = x_start; x !== x_end; x += x_step, i += 4) { - imageData[(x + width * y) * 4 + 2] = image[i + 0]; - imageData[(x + width * y) * 4 + 1] = image[i + 1]; - imageData[(x + width * y) * 4 + 0] = image[i + 2]; - imageData[(x + width * y) * 4 + 3] = image[i + 3]; - } - } - return imageData; -} -/** - * @internal - */ -function _getImageDataGrey8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { - const image = pixel_data; - const width = header.width, height = header.height; - let color, i = 0, x, y; - const imageData = new Uint8Array(width * height * 4); - for (y = y_start; y !== y_end; y += y_step) { - for (x = x_start; x !== x_end; x += x_step, i++) { - color = image[i]; - imageData[(x + width * y) * 4 + 0] = color; - imageData[(x + width * y) * 4 + 1] = color; - imageData[(x + width * y) * 4 + 2] = color; - imageData[(x + width * y) * 4 + 3] = 255; - } - } - return imageData; -} -/** - * @internal - */ -function _getImageDataGrey16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { - const image = pixel_data; - const width = header.width, height = header.height; - let i = 0, x, y; - const imageData = new Uint8Array(width * height * 4); - for (y = y_start; y !== y_end; y += y_step) { - for (x = x_start; x !== x_end; x += x_step, i += 2) { - imageData[(x + width * y) * 4 + 0] = image[i + 0]; - imageData[(x + width * y) * 4 + 1] = image[i + 0]; - imageData[(x + width * y) * 4 + 2] = image[i + 0]; - imageData[(x + width * y) * 4 + 3] = image[i + 1]; - } - } - return imageData; -} -/** - * Based on jsTGALoader - Javascript loader for TGA file - * By Vincent Thibault - * @see http://blog.robrowser.com/javascript-tga-loader.html - */ -const TGATools = { - /** - * Gets the header of a TGA file - * @param data defines the TGA data - * @returns the header - */ - GetTGAHeader, - /** - * Uploads TGA content to a Babylon Texture - * @internal - */ - UploadContent, - /** @internal */ - _getImageData8bits, - /** @internal */ - _getImageData16bits, - /** @internal */ - _getImageData24bits, - /** @internal */ - _getImageData32bits, - /** @internal */ - _getImageDataGrey8bits, - /** @internal */ - _getImageDataGrey16bits, -}; -//# sourceMappingURL=tga.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Loaders/tgaTextureLoader.js - - -/** - * Implementation of the TGA Texture Loader. - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _TGATextureLoader { - constructor() { - /** - * Defines whether the loader supports cascade loading the different faces. - */ - this.supportCascades = false; - } - /** - * This returns if the loader support the current file information. - * @param extension defines the file extension of the file being loaded - * @returns true if the loader can load the specified file - */ - canLoad(extension) { - return extension.endsWith(".tga"); - } - /** - * Uploads the cube texture data to the WebGL texture. It has already been bound. - */ - loadCubeData() { - throw ".env not supported in Cube."; - } - /** - * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. - * @param data contains the texture data - * @param texture defines the BabylonJS internal texture - * @param callback defines the method to call once ready to upload - */ - loadData(data, texture, callback) { - const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); - const header = GetTGAHeader(bytes); - callback(header.width, header.height, texture.generateMipMaps, false, () => { - UploadContent(texture, bytes); - }); - } -} -// Register the loader. -engine_Engine._TextureLoaders.push(new _TGATextureLoader()); -//# sourceMappingURL=tgaTextureLoader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Loaders/hdrTextureLoader.js - - - -/** - * Implementation of the HDR Texture Loader. - * @internal - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _HDRTextureLoader { - constructor() { - /** - * Defines whether the loader supports cascade loading the different faces. - */ - this.supportCascades = false; - } - /** - * This returns if the loader support the current file information. - * @param extension defines the file extension of the file being loaded - * @returns true if the loader can load the specified file - */ - canLoad(extension) { - return extension.endsWith(".hdr"); - } - /** - * Uploads the cube texture data to the WebGL texture. It has already been bound. - */ - loadCubeData() { - throw ".env not supported in Cube."; - } - /** - * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. - * @param data contains the texture data - * @param texture defines the BabylonJS internal texture - * @param callback defines the method to call once ready to upload - */ - loadData(data, texture, callback) { - const uint8array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); - const hdrInfo = HDRTools.RGBE_ReadHeader(uint8array); - const pixelsDataRGB32 = HDRTools.RGBE_ReadPixels(uint8array, hdrInfo); - const pixels = hdrInfo.width * hdrInfo.height; - const pixelsDataRGBA32 = new Float32Array(pixels * 4); - for (let i = 0; i < pixels; i += 1) { - pixelsDataRGBA32[i * 4] = pixelsDataRGB32[i * 3]; - pixelsDataRGBA32[i * 4 + 1] = pixelsDataRGB32[i * 3 + 1]; - pixelsDataRGBA32[i * 4 + 2] = pixelsDataRGB32[i * 3 + 2]; - pixelsDataRGBA32[i * 4 + 3] = 1; - } - callback(hdrInfo.width, hdrInfo.height, texture.generateMipMaps, false, () => { - const engine = texture.getEngine(); - texture.type = 1; - texture.format = 5; - texture._gammaSpace = false; - engine._uploadDataToTextureDirectly(texture, pixelsDataRGBA32); - }); - } -} -// Register the loader. -engine_Engine._TextureLoaders.push(new _HDRTextureLoader()); -//# sourceMappingURL=hdrTextureLoader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/basis.js - - - - - -/** - * Info about the .basis files - */ -class BasisFileInfo { -} -/** - * Result of transcoding a basis file - */ -class TranscodeResult { -} -/** - * Configuration options for the Basis transcoder - */ -class BasisTranscodeConfiguration { -} -/** - * @internal - * Enum of basis transcoder formats - */ -var BASIS_FORMATS; -(function (BASIS_FORMATS) { - BASIS_FORMATS[BASIS_FORMATS["cTFETC1"] = 0] = "cTFETC1"; - BASIS_FORMATS[BASIS_FORMATS["cTFETC2"] = 1] = "cTFETC2"; - BASIS_FORMATS[BASIS_FORMATS["cTFBC1"] = 2] = "cTFBC1"; - BASIS_FORMATS[BASIS_FORMATS["cTFBC3"] = 3] = "cTFBC3"; - BASIS_FORMATS[BASIS_FORMATS["cTFBC4"] = 4] = "cTFBC4"; - BASIS_FORMATS[BASIS_FORMATS["cTFBC5"] = 5] = "cTFBC5"; - BASIS_FORMATS[BASIS_FORMATS["cTFBC7"] = 6] = "cTFBC7"; - BASIS_FORMATS[BASIS_FORMATS["cTFPVRTC1_4_RGB"] = 8] = "cTFPVRTC1_4_RGB"; - BASIS_FORMATS[BASIS_FORMATS["cTFPVRTC1_4_RGBA"] = 9] = "cTFPVRTC1_4_RGBA"; - BASIS_FORMATS[BASIS_FORMATS["cTFASTC_4x4"] = 10] = "cTFASTC_4x4"; - BASIS_FORMATS[BASIS_FORMATS["cTFATC_RGB"] = 11] = "cTFATC_RGB"; - BASIS_FORMATS[BASIS_FORMATS["cTFATC_RGBA_INTERPOLATED_ALPHA"] = 12] = "cTFATC_RGBA_INTERPOLATED_ALPHA"; - BASIS_FORMATS[BASIS_FORMATS["cTFRGBA32"] = 13] = "cTFRGBA32"; - BASIS_FORMATS[BASIS_FORMATS["cTFRGB565"] = 14] = "cTFRGB565"; - BASIS_FORMATS[BASIS_FORMATS["cTFBGR565"] = 15] = "cTFBGR565"; - BASIS_FORMATS[BASIS_FORMATS["cTFRGBA4444"] = 16] = "cTFRGBA4444"; - BASIS_FORMATS[BASIS_FORMATS["cTFFXT1_RGB"] = 17] = "cTFFXT1_RGB"; - BASIS_FORMATS[BASIS_FORMATS["cTFPVRTC2_4_RGB"] = 18] = "cTFPVRTC2_4_RGB"; - BASIS_FORMATS[BASIS_FORMATS["cTFPVRTC2_4_RGBA"] = 19] = "cTFPVRTC2_4_RGBA"; - BASIS_FORMATS[BASIS_FORMATS["cTFETC2_EAC_R11"] = 20] = "cTFETC2_EAC_R11"; - BASIS_FORMATS[BASIS_FORMATS["cTFETC2_EAC_RG11"] = 21] = "cTFETC2_EAC_RG11"; -})(BASIS_FORMATS || (BASIS_FORMATS = {})); -/** - * Used to load .Basis files - * See https://github.com/BinomialLLC/basis_universal/tree/master/webgl - */ -const BasisToolsOptions = { - /** - * URL to use when loading the basis transcoder - */ - JSModuleURL: "https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.js", - /** - * URL to use when loading the wasm module for the transcoder - */ - WasmModuleURL: "https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.wasm", -}; -/** - * Get the internal format to be passed to texImage2D corresponding to the .basis format value - * @param basisFormat format chosen from GetSupportedTranscodeFormat - * @param engine - * @returns internal format corresponding to the Basis format - */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -const GetInternalFormatFromBasisFormat = (basisFormat, engine) => { - let format; - switch (basisFormat) { - case BASIS_FORMATS.cTFETC1: - format = 36196; - break; - case BASIS_FORMATS.cTFBC1: - format = 33776; - break; - case BASIS_FORMATS.cTFBC4: - format = 33779; - break; - case BASIS_FORMATS.cTFASTC_4x4: - format = 37808; - break; - case BASIS_FORMATS.cTFETC2: - format = 37496; - break; - case BASIS_FORMATS.cTFBC7: - format = 36492; - break; - } - if (format === undefined) { - throw "The chosen Basis transcoder format is not currently supported"; - } - return format; -}; -let _WorkerPromise = null; -let _Worker = null; -let _actionId = 0; -const _IgnoreSupportedFormats = false; -const _CreateWorkerAsync = () => { - if (!_WorkerPromise) { - _WorkerPromise = new Promise((res, reject) => { - if (_Worker) { - res(_Worker); - } - else { - tools_Tools.LoadFileAsync(BasisToolsOptions.WasmModuleURL) - .then((wasmBinary) => { - if (typeof URL !== "function") { - return reject("Basis transcoder requires an environment with a URL constructor"); - } - const workerBlobUrl = URL.createObjectURL(new Blob([`(${basis_workerFunc})()`], { type: "application/javascript" })); - _Worker = new Worker(workerBlobUrl); - const initHandler = (msg) => { - if (msg.data.action === "init") { - _Worker.removeEventListener("message", initHandler); - res(_Worker); - } - else if (msg.data.action === "error") { - reject(msg.data.error || "error initializing worker"); - } - }; - _Worker.addEventListener("message", initHandler); - _Worker.postMessage({ action: "init", url: BasisToolsOptions.JSModuleURL, wasmBinary: wasmBinary }); - }) - .catch(reject); - } - }); - } - return _WorkerPromise; -}; -/** - * Transcodes a loaded image file to compressed pixel data - * @param data image data to transcode - * @param config configuration options for the transcoding - * @returns a promise resulting in the transcoded image - */ -const TranscodeAsync = (data, config) => { - const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data; - return new Promise((res, rej) => { - _CreateWorkerAsync().then(() => { - const actionId = _actionId++; - const messageHandler = (msg) => { - if (msg.data.action === "transcode" && msg.data.id === actionId) { - _Worker.removeEventListener("message", messageHandler); - if (!msg.data.success) { - rej("Transcode is not supported on this device"); - } - else { - res(msg.data); - } - } - }; - _Worker.addEventListener("message", messageHandler); - const dataViewCopy = new Uint8Array(dataView.byteLength); - dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength)); - _Worker.postMessage({ action: "transcode", id: actionId, imageData: dataViewCopy, config: config, ignoreSupportedFormats: _IgnoreSupportedFormats }, [ - dataViewCopy.buffer, - ]); - }, (error) => { - rej(error); - }); - }); -}; -/** - * Binds a texture according to its underlying target. - * @param texture texture to bind - * @param engine the engine to bind the texture in - */ -const BindTexture = (texture, engine) => { - var _a, _b; - let target = (_a = engine._gl) === null || _a === void 0 ? void 0 : _a.TEXTURE_2D; - if (texture.isCube) { - target = (_b = engine._gl) === null || _b === void 0 ? void 0 : _b.TEXTURE_CUBE_MAP; - } - engine._bindTextureDirectly(target, texture, true); -}; -/** - * Loads a texture from the transcode result - * @param texture texture load to - * @param transcodeResult the result of transcoding the basis file to load from - */ -const LoadTextureFromTranscodeResult = (texture, transcodeResult) => { - const engine = texture.getEngine(); - for (let i = 0; i < transcodeResult.fileInfo.images.length; i++) { - const rootImage = transcodeResult.fileInfo.images[i].levels[0]; - texture._invertVScale = texture.invertY; - if (transcodeResult.format === -1 || transcodeResult.format === BASIS_FORMATS.cTFRGB565) { - // No compatable compressed format found, fallback to RGB - texture.type = 10; - texture.format = 4; - if (engine._features.basisNeedsPOT && (math_scalar_Scalar.Log2(rootImage.width) % 1 !== 0 || math_scalar_Scalar.Log2(rootImage.height) % 1 !== 0)) { - // Create non power of two texture - const source = new internalTexture_InternalTexture(engine, internalTexture_InternalTextureSource.Temp); - texture._invertVScale = texture.invertY; - source.type = 10; - source.format = 4; - // Fallback requires aligned width/height - source.width = (rootImage.width + 3) & ~3; - source.height = (rootImage.height + 3) & ~3; - BindTexture(source, engine); - engine._uploadDataToTextureDirectly(source, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true); - // Resize to power of two - engine._rescaleTexture(source, texture, engine.scenes[0], engine._getInternalFormat(4), () => { - engine._releaseTexture(source); - BindTexture(texture, engine); - }); - } - else { - // Fallback is already inverted - texture._invertVScale = !texture.invertY; - // Upload directly - texture.width = (rootImage.width + 3) & ~3; - texture.height = (rootImage.height + 3) & ~3; - texture.samplingMode = 2; - BindTexture(texture, engine); - engine._uploadDataToTextureDirectly(texture, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true); - } - } - else { - texture.width = rootImage.width; - texture.height = rootImage.height; - texture.generateMipMaps = transcodeResult.fileInfo.images[i].levels.length > 1; - const format = BasisTools.GetInternalFormatFromBasisFormat(transcodeResult.format, engine); - texture.format = format; - BindTexture(texture, engine); - // Upload all mip levels in the file - transcodeResult.fileInfo.images[i].levels.forEach((level, index) => { - engine._uploadCompressedDataToTextureDirectly(texture, format, level.width, level.height, level.transcodedPixels, i, index); - }); - if (engine._features.basisNeedsPOT && (math_scalar_Scalar.Log2(texture.width) % 1 !== 0 || math_scalar_Scalar.Log2(texture.height) % 1 !== 0)) { - tools_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."); - texture._cachedWrapU = texture_Texture.CLAMP_ADDRESSMODE; - texture._cachedWrapV = texture_Texture.CLAMP_ADDRESSMODE; - } - } - } -}; -/** - * Used to load .Basis files - * See https://github.com/BinomialLLC/basis_universal/tree/master/webgl - */ -const BasisTools = { - /** - * URL to use when loading the basis transcoder - */ - JSModuleURL: BasisToolsOptions.JSModuleURL, - /** - * URL to use when loading the wasm module for the transcoder - */ - WasmModuleURL: BasisToolsOptions.WasmModuleURL, - /** - * Get the internal format to be passed to texImage2D corresponding to the .basis format value - * @param basisFormat format chosen from GetSupportedTranscodeFormat - * @returns internal format corresponding to the Basis format - */ - GetInternalFormatFromBasisFormat, - /** - * Transcodes a loaded image file to compressed pixel data - * @param data image data to transcode - * @param config configuration options for the transcoding - * @returns a promise resulting in the transcoded image - */ - TranscodeAsync, - /** - * Loads a texture from the transcode result - * @param texture texture load to - * @param transcodeResult the result of transcoding the basis file to load from - */ - LoadTextureFromTranscodeResult, -}; -function basis_workerFunc() { - const _BASIS_FORMAT = { - cTFETC1: 0, - cTFETC2: 1, - cTFBC1: 2, - cTFBC3: 3, - cTFBC4: 4, - cTFBC5: 5, - cTFBC7: 6, - cTFPVRTC1_4_RGB: 8, - cTFPVRTC1_4_RGBA: 9, - cTFASTC_4x4: 10, - cTFATC_RGB: 11, - cTFATC_RGBA_INTERPOLATED_ALPHA: 12, - cTFRGBA32: 13, - cTFRGB565: 14, - cTFBGR565: 15, - cTFRGBA4444: 16, - cTFFXT1_RGB: 17, - cTFPVRTC2_4_RGB: 18, - cTFPVRTC2_4_RGBA: 19, - cTFETC2_EAC_R11: 20, - cTFETC2_EAC_RG11: 21, - }; - let transcoderModulePromise = null; - onmessage = (event) => { - if (event.data.action === "init") { - // Load the transcoder if it hasn't been yet - if (!transcoderModulePromise) { - // make sure we loaded the script correctly - try { - importScripts(event.data.url); - } - catch (e) { - postMessage({ action: "error", error: e }); - } - transcoderModulePromise = BASIS({ - // Override wasm binary - wasmBinary: event.data.wasmBinary, - }); - } - if (transcoderModulePromise !== null) { - transcoderModulePromise.then((m) => { - BASIS = m; - m.initializeBasis(); - postMessage({ action: "init" }); - }); - } - } - else if (event.data.action === "transcode") { - // Transcode the basis image and return the resulting pixels - const config = event.data.config; - const imgData = event.data.imageData; - const loadedFile = new BASIS.BasisFile(imgData); - const fileInfo = GetFileInfo(loadedFile); - let format = event.data.ignoreSupportedFormats ? null : GetSupportedTranscodeFormat(event.data.config, fileInfo); - let needsConversion = false; - if (format === null) { - needsConversion = true; - format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1; - } - // Begin transcode - let success = true; - if (!loadedFile.startTranscoding()) { - success = false; - } - const buffers = []; - for (let imageIndex = 0; imageIndex < fileInfo.images.length; imageIndex++) { - if (!success) { - break; - } - const image = fileInfo.images[imageIndex]; - if (config.loadSingleImage === undefined || config.loadSingleImage === imageIndex) { - let mipCount = image.levels.length; - if (config.loadMipmapLevels === false) { - mipCount = 1; - } - for (let levelIndex = 0; levelIndex < mipCount; levelIndex++) { - const levelInfo = image.levels[levelIndex]; - const pixels = TranscodeLevel(loadedFile, imageIndex, levelIndex, format, needsConversion); - if (!pixels) { - success = false; - break; - } - levelInfo.transcodedPixels = pixels; - buffers.push(levelInfo.transcodedPixels.buffer); - } - } - } - // Close file - loadedFile.close(); - loadedFile.delete(); - if (needsConversion) { - format = -1; - } - if (!success) { - postMessage({ action: "transcode", success: success, id: event.data.id }); - } - else { - postMessage({ action: "transcode", success: success, id: event.data.id, fileInfo: fileInfo, format: format }, buffers); - } - } - }; - /** - * Detects the supported transcode format for the file - * @param config transcode config - * @param fileInfo info about the file - * @returns the chosed format or null if none are supported - */ - function GetSupportedTranscodeFormat(config, fileInfo) { - let format = null; - if (config.supportedCompressionFormats) { - if (config.supportedCompressionFormats.astc) { - format = _BASIS_FORMAT.cTFASTC_4x4; - } - else if (config.supportedCompressionFormats.bc7) { - format = _BASIS_FORMAT.cTFBC7; - } - else if (config.supportedCompressionFormats.s3tc) { - format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1; - } - else if (config.supportedCompressionFormats.pvrtc) { - format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFPVRTC1_4_RGBA : _BASIS_FORMAT.cTFPVRTC1_4_RGB; - } - else if (config.supportedCompressionFormats.etc2) { - format = _BASIS_FORMAT.cTFETC2; - } - else if (config.supportedCompressionFormats.etc1) { - format = _BASIS_FORMAT.cTFETC1; - } - else { - format = _BASIS_FORMAT.cTFRGB565; - } - } - return format; - } - /** - * Retrieves information about the basis file eg. dimensions - * @param basisFile the basis file to get the info from - * @returns information about the basis file - */ - function GetFileInfo(basisFile) { - const hasAlpha = basisFile.getHasAlpha(); - const imageCount = basisFile.getNumImages(); - const images = []; - for (let i = 0; i < imageCount; i++) { - const imageInfo = { - levels: [], - }; - const levelCount = basisFile.getNumLevels(i); - for (let level = 0; level < levelCount; level++) { - const levelInfo = { - width: basisFile.getImageWidth(i, level), - height: basisFile.getImageHeight(i, level), - }; - imageInfo.levels.push(levelInfo); - } - images.push(imageInfo); - } - const info = { hasAlpha, images }; - return info; - } - function TranscodeLevel(loadedFile, imageIndex, levelIndex, format, convertToRgb565) { - const dstSize = loadedFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, format); - let dst = new Uint8Array(dstSize); - if (!loadedFile.transcodeImage(dst, imageIndex, levelIndex, format, 1, 0)) { - return null; - } - // If no supported format is found, load as dxt and convert to rgb565 - if (convertToRgb565) { - const alignedWidth = (loadedFile.getImageWidth(imageIndex, levelIndex) + 3) & ~3; - const alignedHeight = (loadedFile.getImageHeight(imageIndex, levelIndex) + 3) & ~3; - dst = ConvertDxtToRgb565(dst, 0, alignedWidth, alignedHeight); - } - return dst; - } - /** - * From https://github.com/BinomialLLC/basis_universal/blob/master/webgl/texture/dxt-to-rgb565.js - * An unoptimized version of dxtToRgb565. Also, the floating - * point math used to compute the colors actually results in - * slightly different colors compared to hardware DXT decoders. - * @param src dxt src pixels - * @param srcByteOffset offset for the start of src - * @param width aligned width of the image - * @param height aligned height of the image - * @returns the converted pixels - */ - function ConvertDxtToRgb565(src, srcByteOffset, width, height) { - const c = new Uint16Array(4); - const dst = new Uint16Array(width * height); - const blockWidth = width / 4; - const blockHeight = height / 4; - for (let blockY = 0; blockY < blockHeight; blockY++) { - for (let blockX = 0; blockX < blockWidth; blockX++) { - const i = srcByteOffset + 8 * (blockY * blockWidth + blockX); - c[0] = src[i] | (src[i + 1] << 8); - c[1] = src[i + 2] | (src[i + 3] << 8); - c[2] = - ((2 * (c[0] & 0x1f) + 1 * (c[1] & 0x1f)) / 3) | - (((2 * (c[0] & 0x7e0) + 1 * (c[1] & 0x7e0)) / 3) & 0x7e0) | - (((2 * (c[0] & 0xf800) + 1 * (c[1] & 0xf800)) / 3) & 0xf800); - c[3] = - ((2 * (c[1] & 0x1f) + 1 * (c[0] & 0x1f)) / 3) | - (((2 * (c[1] & 0x7e0) + 1 * (c[0] & 0x7e0)) / 3) & 0x7e0) | - (((2 * (c[1] & 0xf800) + 1 * (c[0] & 0xf800)) / 3) & 0xf800); - for (let row = 0; row < 4; row++) { - const m = src[i + 4 + row]; - let dstI = (blockY * 4 + row) * width + blockX * 4; - dst[dstI++] = c[m & 0x3]; - dst[dstI++] = c[(m >> 2) & 0x3]; - dst[dstI++] = c[(m >> 4) & 0x3]; - dst[dstI++] = c[(m >> 6) & 0x3]; - } - } - } - return dst; - } -} -Object.defineProperty(BasisTools, "JSModuleURL", { - get: function () { - return BasisToolsOptions.JSModuleURL; - }, - set: function (value) { - BasisToolsOptions.JSModuleURL = value; - }, -}); -Object.defineProperty(BasisTools, "WasmModuleURL", { - get: function () { - return BasisToolsOptions.WasmModuleURL; - }, - set: function (value) { - BasisToolsOptions.WasmModuleURL = value; - }, -}); -//# sourceMappingURL=basis.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Loaders/basisTextureLoader.js - - - -/** - * Loader for .basis file format - */ -// eslint-disable-next-line @typescript-eslint/naming-convention -class _BasisTextureLoader { - constructor() { - /** - * Defines whether the loader supports cascade loading the different faces. - */ - this.supportCascades = false; - } - /** - * This returns if the loader support the current file information. - * @param extension defines the file extension of the file being loaded - * @returns true if the loader can load the specified file - */ - canLoad(extension) { - return extension.endsWith(".basis"); - } - /** - * Uploads the cube texture data to the WebGL texture. It has already been bound. - * @param data contains the texture data - * @param texture defines the BabylonJS internal texture - * @param createPolynomials will be true if polynomials have been requested - * @param onLoad defines the callback to trigger once the texture is ready - * @param onError defines the callback to trigger in case of error - */ - loadCubeData(data, texture, createPolynomials, onLoad, onError) { - if (Array.isArray(data)) { - return; - } - const caps = texture.getEngine().getCaps(); - const transcodeConfig = { - supportedCompressionFormats: { - etc1: caps.etc1 ? true : false, - s3tc: caps.s3tc ? true : false, - pvrtc: caps.pvrtc ? true : false, - etc2: caps.etc2 ? true : false, - astc: caps.astc ? true : false, - bc7: caps.bptc ? true : false, - }, - }; - TranscodeAsync(data, transcodeConfig) - .then((result) => { - const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps; - LoadTextureFromTranscodeResult(texture, result); - texture.getEngine()._setCubeMapTextureParams(texture, hasMipmap); - texture.isReady = true; - texture.onLoadedObservable.notifyObservers(texture); - texture.onLoadedObservable.clear(); - if (onLoad) { - onLoad(); - } - }) - .catch((err) => { - const errorMessage = "Failed to transcode Basis file, transcoding may not be supported on this device"; - tools_Tools.Warn(errorMessage); - texture.isReady = true; - if (onError) { - onError(err); - } - }); - } - /** - * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback. - * @param data contains the texture data - * @param texture defines the BabylonJS internal texture - * @param callback defines the method to call once ready to upload - */ - loadData(data, texture, callback) { - const caps = texture.getEngine().getCaps(); - const transcodeConfig = { - supportedCompressionFormats: { - etc1: caps.etc1 ? true : false, - s3tc: caps.s3tc ? true : false, - pvrtc: caps.pvrtc ? true : false, - etc2: caps.etc2 ? true : false, - astc: caps.astc ? true : false, - bc7: caps.bptc ? true : false, - }, - }; - TranscodeAsync(data, transcodeConfig) - .then((result) => { - const rootImage = result.fileInfo.images[0].levels[0]; - const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps; - callback(rootImage.width, rootImage.height, hasMipmap, result.format !== -1, () => { - LoadTextureFromTranscodeResult(texture, result); - }); - }) - .catch((err) => { - tools_Tools.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"); - tools_Tools.Warn(`Failed to transcode Basis file: ${err}`); - callback(0, 0, false, false, () => { }, true); - }); - } -} -// Register the loader. -engine_Engine._TextureLoaders.push(new _BasisTextureLoader()); -//# sourceMappingURL=basisTextureLoader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Loaders/index.js - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/multiRenderTarget.js - - - - -/** - * A multi render target, like a render target provides the ability to render to a texture. - * Unlike the render target, it can render to several draw buffers in one draw. - * This is specially interesting in deferred rendering or for any effects requiring more than - * just one color from a single pass. - */ -class MultiRenderTarget extends renderTargetTexture_RenderTargetTexture { - /** - * Get if draw buffers are currently supported by the used hardware and browser. - */ - get isSupported() { - var _a, _b; - return (_b = (_a = this._engine) === null || _a === void 0 ? void 0 : _a.getCaps().drawBuffersExtension) !== null && _b !== void 0 ? _b : false; - } - /** - * Get the list of textures generated by the multi render target. - */ - get textures() { - return this._textures; - } - /** - * Gets the number of textures in this MRT. This number can be different from `_textures.length` in case a depth texture is generated. - */ - get count() { - return this._count; - } - /** - * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set - */ - get depthTexture() { - return this._textures[this._textures.length - 1]; - } - /** - * Set the wrapping mode on U of all the textures we are rendering to. - * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE) - */ - set wrapU(wrap) { - if (this._textures) { - for (let i = 0; i < this._textures.length; i++) { - this._textures[i].wrapU = wrap; - } - } - } - /** - * Set the wrapping mode on V of all the textures we are rendering to. - * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE) - */ - set wrapV(wrap) { - if (this._textures) { - for (let i = 0; i < this._textures.length; i++) { - this._textures[i].wrapV = wrap; - } - } - } - /** - * Instantiate a new multi render target texture. - * A multi render target, like a render target provides the ability to render to a texture. - * Unlike the render target, it can render to several draw buffers in one draw. - * This is specially interesting in deferred rendering or for any effects requiring more than - * just one color from a single pass. - * @param name Define the name of the texture - * @param size Define the size of the buffers to render to - * @param count Define the number of target we are rendering into - * @param scene Define the scene the texture belongs to - * @param options Define the options used to create the multi render target - * @param textureNames Define the names to set to the textures (if count > 0 - optional) - */ - constructor(name, size, count, scene, options, textureNames) { - const generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false; - const generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false; - const depthTextureFormat = options && options.depthTextureFormat ? options.depthTextureFormat : 15; - const doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio; - const drawOnlyOnFirstAttachmentByDefault = options && options.drawOnlyOnFirstAttachmentByDefault ? options.drawOnlyOnFirstAttachmentByDefault : false; - super(name, size, scene, generateMipMaps, doNotChangeAspectRatio, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true); - if (!this.isSupported) { - this.dispose(); - return; - } - this._textureNames = textureNames; - const types = []; - const samplingModes = []; - const useSRGBBuffers = []; - const formats = []; - const targetTypes = []; - const faceIndex = []; - const layerIndex = []; - const layerCounts = []; - this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options); - const generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; - const generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer; - this._multiRenderTargetOptions = { - samplingModes: samplingModes, - generateMipMaps: generateMipMaps, - generateDepthBuffer: generateDepthBuffer, - generateStencilBuffer: generateStencilBuffer, - generateDepthTexture: generateDepthTexture, - depthTextureFormat: depthTextureFormat, - types: types, - textureCount: count, - useSRGBBuffers: useSRGBBuffers, - formats: formats, - targetTypes: targetTypes, - faceIndex: faceIndex, - layerIndex: layerIndex, - layerCounts: layerCounts, - }; - this._count = count; - this._drawOnlyOnFirstAttachmentByDefault = drawOnlyOnFirstAttachmentByDefault; - if (count > 0) { - this._createInternalTextures(); - this._createTextures(textureNames); - } - } - _initTypes(count, types, samplingModes, useSRGBBuffers, formats, targets, faceIndex, layerIndex, layerCounts, options) { - for (let i = 0; i < count; i++) { - if (options && options.types && options.types[i] !== undefined) { - types.push(options.types[i]); - } - else { - types.push(options && options.defaultType ? options.defaultType : 0); - } - if (options && options.samplingModes && options.samplingModes[i] !== undefined) { - samplingModes.push(options.samplingModes[i]); - } - else { - samplingModes.push(texture_Texture.BILINEAR_SAMPLINGMODE); - } - if (options && options.useSRGBBuffers && options.useSRGBBuffers[i] !== undefined) { - useSRGBBuffers.push(options.useSRGBBuffers[i]); - } - else { - useSRGBBuffers.push(false); - } - if (options && options.formats && options.formats[i] !== undefined) { - formats.push(options.formats[i]); - } - else { - formats.push(5); - } - if (options && options.targetTypes && options.targetTypes[i] !== undefined) { - targets.push(options.targetTypes[i]); - } - else { - targets.push(3553); - } - if (options && options.faceIndex && options.faceIndex[i] !== undefined) { - faceIndex.push(options.faceIndex[i]); - } - else { - faceIndex.push(0); - } - if (options && options.layerIndex && options.layerIndex[i] !== undefined) { - layerIndex.push(options.layerIndex[i]); - } - else { - layerIndex.push(0); - } - if (options && options.layerCounts && options.layerCounts[i] !== undefined) { - layerCounts.push(options.layerCounts[i]); - } - else { - layerCounts.push(1); - } - } - } - _createInternaTextureIndexMapping() { - const mapMainInternalTexture2Index = {}; - const mapInternalTexture2MainIndex = []; - if (!this._renderTarget) { - return mapInternalTexture2MainIndex; - } - const internalTextures = this._renderTarget.textures; - for (let i = 0; i < internalTextures.length; i++) { - const texture = internalTextures[i]; - if (!texture) { - continue; - } - const mainIndex = mapMainInternalTexture2Index[texture.uniqueId]; - if (mainIndex !== undefined) { - mapInternalTexture2MainIndex[i] = mainIndex; - } - else { - mapMainInternalTexture2Index[texture.uniqueId] = i; - } - } - return mapInternalTexture2MainIndex; - } - /** - * @internal - */ - _rebuild(forceFullRebuild = false, textureNames) { - if (this._count < 1) { - return; - } - const mapInternalTexture2MainIndex = this._createInternaTextureIndexMapping(); - this.releaseInternalTextures(); - this._createInternalTextures(); - if (forceFullRebuild) { - this._releaseTextures(); - this._createTextures(textureNames); - } - const internalTextures = this._renderTarget.textures; - for (let i = 0; i < internalTextures.length; i++) { - const texture = this._textures[i]; - if (mapInternalTexture2MainIndex[i] !== undefined) { - this._renderTarget.setTexture(internalTextures[mapInternalTexture2MainIndex[i]], i); - } - texture._texture = internalTextures[i]; - if (texture._texture) { - texture._noMipmap = !texture._texture.useMipMaps; - texture._useSRGBBuffer = texture._texture._useSRGBBuffer; - } - } - if (this.samples !== 1) { - this._renderTarget.setSamples(this.samples, !this._drawOnlyOnFirstAttachmentByDefault, true); - } - } - _createInternalTextures() { - this._renderTarget = this._getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions, !this._drawOnlyOnFirstAttachmentByDefault); - this._texture = this._renderTarget.texture; - } - _releaseTextures() { - if (this._textures) { - for (let i = 0; i < this._textures.length; i++) { - this._textures[i]._texture = null; // internal textures are released by a call to releaseInternalTextures() - this._textures[i].dispose(); - } - } - } - _createTextures(textureNames) { - const internalTextures = this._renderTarget.textures; - this._textures = []; - for (let i = 0; i < internalTextures.length; i++) { - const texture = new texture_Texture(null, this.getScene()); - if (textureNames === null || textureNames === void 0 ? void 0 : textureNames[i]) { - texture.name = textureNames[i]; - } - texture._texture = internalTextures[i]; - if (texture._texture) { - texture._noMipmap = !texture._texture.useMipMaps; - texture._useSRGBBuffer = texture._texture._useSRGBBuffer; - } - this._textures.push(texture); - } - } - /** - * Replaces an internal texture within the MRT. Useful to share textures between MultiRenderTarget. - * @param texture The new texture to set in the MRT - * @param index The index of the texture to replace - * @param disposePrevious Set to true if the previous internal texture should be disposed - */ - setInternalTexture(texture, index, disposePrevious = true) { - var _a, _b; - if (!this.renderTarget) { - return; - } - if (index === 0) { - this._texture = texture; - } - this.renderTarget.setTexture(texture, index, disposePrevious); - if (!this.textures[index]) { - this.textures[index] = new texture_Texture(null, this.getScene()); - 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; - } - this.textures[index]._texture = texture; - this.textures[index]._noMipmap = !texture.useMipMaps; - this.textures[index]._useSRGBBuffer = texture._useSRGBBuffer; - this._count = this.renderTarget.textures ? this.renderTarget.textures.length : 0; - if (this._multiRenderTargetOptions.types) { - this._multiRenderTargetOptions.types[index] = texture.type; - } - if (this._multiRenderTargetOptions.samplingModes) { - this._multiRenderTargetOptions.samplingModes[index] = texture.samplingMode; - } - if (this._multiRenderTargetOptions.useSRGBBuffers) { - this._multiRenderTargetOptions.useSRGBBuffers[index] = texture._useSRGBBuffer; - } - if (this._multiRenderTargetOptions.targetTypes && this._multiRenderTargetOptions.targetTypes[index] !== -1) { - let target = 0; - if (texture.is2DArray) { - target = 35866; - } - else if (texture.isCube) { - target = 34067; - } /*else if (texture.isCubeArray) { - target = 3735928559; - }*/ - else if (texture.is3D) { - target = 32879; - } - else { - target = 3553; - } - this._multiRenderTargetOptions.targetTypes[index] = target; - } - } - /** - * Changes an attached texture's face index or layer. - * @param index The index of the texture to modify the attachment of - * @param layerIndex The layer index of the texture to be attached to the framebuffer - * @param faceIndex The face index of the texture to be attached to the framebuffer - */ - setLayerAndFaceIndex(index, layerIndex = -1, faceIndex = -1) { - if (!this.textures[index] || !this.renderTarget) { - return; - } - if (this._multiRenderTargetOptions.layerIndex) { - this._multiRenderTargetOptions.layerIndex[index] = layerIndex; - } - if (this._multiRenderTargetOptions.faceIndex) { - this._multiRenderTargetOptions.faceIndex[index] = faceIndex; - } - this.renderTarget.setLayerAndFaceIndex(index, layerIndex, faceIndex); - } - /** - * Changes every attached texture's face index or layer. - * @param layerIndices The layer indices of the texture to be attached to the framebuffer - * @param faceIndices The face indices of the texture to be attached to the framebuffer - */ - setLayerAndFaceIndices(layerIndices, faceIndices) { - if (!this.renderTarget) { - return; - } - this._multiRenderTargetOptions.layerIndex = layerIndices; - this._multiRenderTargetOptions.faceIndex = faceIndices; - this.renderTarget.setLayerAndFaceIndices(layerIndices, faceIndices); - } - /** - * Define the number of samples used if MSAA is enabled. - */ - get samples() { - return this._samples; - } - set samples(value) { - if (this._renderTarget) { - this._samples = this._renderTarget.setSamples(value); - } - else { - // In case samples are set with 0 textures created, we must save the desired samples value - this._samples = value; - } - } - /** - * Resize all the textures in the multi render target. - * Be careful as it will recreate all the data in the new texture. - * @param size Define the new size - */ - resize(size) { - this._processSizeParameter(size, false); - this._rebuild(undefined, this._textureNames); - } - /** - * Changes the number of render targets in this MRT - * Be careful as it will recreate all the data in the new texture. - * @param count new texture count - * @param options Specifies texture types and sampling modes for new textures - * @param textureNames Specifies the names of the textures (optional) - */ - updateCount(count, options, textureNames) { - this._multiRenderTargetOptions.textureCount = count; - this._count = count; - const types = []; - const samplingModes = []; - const useSRGBBuffers = []; - const formats = []; - const targetTypes = []; - const faceIndex = []; - const layerIndex = []; - const layerCounts = []; - this._textureNames = textureNames; - this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options); - this._multiRenderTargetOptions.types = types; - this._multiRenderTargetOptions.samplingModes = samplingModes; - this._multiRenderTargetOptions.useSRGBBuffers = useSRGBBuffers; - this._multiRenderTargetOptions.formats = formats; - this._multiRenderTargetOptions.targetTypes = targetTypes; - this._multiRenderTargetOptions.faceIndex = faceIndex; - this._multiRenderTargetOptions.layerIndex = layerIndex; - this._multiRenderTargetOptions.layerCounts = layerCounts; - this._rebuild(true, textureNames); - } - _unbindFrameBuffer(engine, faceIndex) { - if (this._renderTarget) { - engine.unBindMultiColorAttachmentFramebuffer(this._renderTarget, this.isCube, () => { - this.onAfterRenderObservable.notifyObservers(faceIndex); - }); - } - } - /** - * Dispose the render targets and their associated resources - * @param doNotDisposeInternalTextures - */ - dispose(doNotDisposeInternalTextures = false) { - this._releaseTextures(); - if (!doNotDisposeInternalTextures) { - this.releaseInternalTextures(); - } - else { - // Prevent internal texture dispose in super.dispose - this._texture = null; - } - super.dispose(); - } - /** - * Release all the underlying texture used as draw buffers. - */ - releaseInternalTextures() { - var _a, _b; - const internalTextures = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.textures; - if (!internalTextures) { - return; - } - for (let i = internalTextures.length - 1; i >= 0; i--) { - this._textures[i]._texture = null; - } - (_b = this._renderTarget) === null || _b === void 0 ? void 0 : _b.dispose(); - this._renderTarget = null; - } -} -//# sourceMappingURL=multiRenderTarget.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Packer/frame.js -/** - * This is a support class for frame Data on texture packer sets. - */ -class TexturePackerFrame { - /** - * Initializes a texture package frame. - * @param id The numerical frame identifier - * @param scale Scalar Vector2 for UV frame - * @param offset Vector2 for the frame position in UV units. - * @returns TexturePackerFrame - */ - constructor(id, scale, offset) { - this.id = id; - this.scale = scale; - this.offset = offset; - } -} -//# sourceMappingURL=frame.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Packer/packer.js - - - - - - - - - -/** - * This is a support class that generates a series of packed texture sets. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction - */ -class TexturePacker { - /** - * Initializes a texture package series from an array of meshes or a single mesh. - * @param name The name of the package - * @param meshes The target meshes to compose the package from - * @param options The arguments that texture packer should follow while building. - * @param scene The scene which the textures are scoped to. - * @returns TexturePacker - */ - constructor(name, meshes, options, scene) { - var _b, _c, _d, _e, _g, _h, _j, _k, _l, _m, _o, _p, _q; - this.name = name; - this.meshes = meshes; - this.scene = scene; - /** - * Run through the options and set what ever defaults are needed that where not declared. - */ - this.options = options; - this.options.map = (_b = this.options.map) !== null && _b !== void 0 ? _b : [ - "ambientTexture", - "bumpTexture", - "diffuseTexture", - "emissiveTexture", - "lightmapTexture", - "opacityTexture", - "reflectionTexture", - "refractionTexture", - "specularTexture", - ]; - this.options.uvsIn = (_c = this.options.uvsIn) !== null && _c !== void 0 ? _c : buffer_VertexBuffer.UVKind; - this.options.uvsOut = (_d = this.options.uvsOut) !== null && _d !== void 0 ? _d : buffer_VertexBuffer.UVKind; - this.options.layout = (_e = this.options.layout) !== null && _e !== void 0 ? _e : TexturePacker.LAYOUT_STRIP; - if (this.options.layout === TexturePacker.LAYOUT_COLNUM) { - this.options.colnum = (_g = this.options.colnum) !== null && _g !== void 0 ? _g : 8; - } - this.options.updateInputMeshes = (_h = this.options.updateInputMeshes) !== null && _h !== void 0 ? _h : true; - this.options.disposeSources = (_j = this.options.disposeSources) !== null && _j !== void 0 ? _j : true; - this._expecting = 0; - this.options.fillBlanks = (_k = this.options.fillBlanks) !== null && _k !== void 0 ? _k : true; - if (this.options.fillBlanks === true) { - this.options.customFillColor = (_l = this.options.customFillColor) !== null && _l !== void 0 ? _l : "black"; - } - this.options.frameSize = (_m = this.options.frameSize) !== null && _m !== void 0 ? _m : 256; - this.options.paddingRatio = (_o = this.options.paddingRatio) !== null && _o !== void 0 ? _o : 0.0115; - this._paddingValue = Math.ceil(this.options.frameSize * this.options.paddingRatio); - //Make it an even padding Number. - if (this._paddingValue % 2 !== 0) { - this._paddingValue++; - } - this.options.paddingMode = (_p = this.options.paddingMode) !== null && _p !== void 0 ? _p : TexturePacker.SUBUV_WRAP; - if (this.options.paddingMode === TexturePacker.SUBUV_COLOR) { - this.options.paddingColor = (_q = this.options.paddingColor) !== null && _q !== void 0 ? _q : new math_color_Color4(0, 0, 0, 1.0); - } - this.sets = {}; - this.frames = []; - return this; - } - /** - * Starts the package process - * @param resolve The promises resolution function - * @returns TexturePacker - */ - _createFrames(resolve) { - const dtSize = this._calculateSize(); - const dtUnits = new math_vector_Vector2(1, 1).divide(dtSize); - let doneCount = 0; - const expecting = this._expecting; - const meshLength = this.meshes.length; - const sKeys = Object.keys(this.sets); - for (let i = 0; i < sKeys.length; i++) { - const setName = sKeys[i]; - const dt = new dynamicTexture_DynamicTexture(this.name + ".TexturePack." + setName + "Set", { width: dtSize.x, height: dtSize.y }, this.scene, true, //Generate Mips - texture_Texture.TRILINEAR_SAMPLINGMODE, engine_Engine.TEXTUREFORMAT_RGBA); - const dtx = dt.getContext(); - dtx.fillStyle = "rgba(0,0,0,0)"; - dtx.fillRect(0, 0, dtSize.x, dtSize.y); - dt.update(false); - this.sets[setName] = dt; - } - const baseSize = this.options.frameSize || 256; - const padding = this._paddingValue; - const tcs = baseSize + 2 * padding; - const done = () => { - this._calculateMeshUVFrames(baseSize, padding, dtSize, dtUnits, this.options.updateInputMeshes || false); - }; - //Update the Textures - for (let i = 0; i < meshLength; i++) { - const m = this.meshes[i]; - const mat = m.material; - //Check if the material has the texture - //Create a temporary canvas the same size as 1 frame - //Then apply the texture to the center and the 8 offsets - //Copy the Context and place in the correct frame on the DT - for (let j = 0; j < sKeys.length; j++) { - const tempTexture = new dynamicTexture_DynamicTexture("temp", tcs, this.scene, true); - const tcx = tempTexture.getContext(); - const offset = this._getFrameOffset(i); - const updateDt = () => { - doneCount++; - tempTexture.update(false); - const iDat = tcx.getImageData(0, 0, tcs, tcs); - //Update Set - const dt = this.sets[setName]; - const dtx = dt.getContext(); - dtx.putImageData(iDat, dtSize.x * offset.x, dtSize.y * offset.y); - tempTexture.dispose(); - dt.update(false); - if (doneCount == expecting) { - done(); - resolve(); - return; - } - }; - const setName = sKeys[j] || "_blank"; - if (!mat || mat[setName] === null) { - tcx.fillStyle = "rgba(0,0,0,0)"; - if (this.options.fillBlanks) { - tcx.fillStyle = this.options.customFillColor; - } - tcx.fillRect(0, 0, tcs, tcs); - updateDt(); - } - else { - const setTexture = mat[setName]; - const img = new Image(); - if (setTexture instanceof dynamicTexture_DynamicTexture) { - img.src = setTexture.getContext().canvas.toDataURL("image/png"); - } - else { - img.src = setTexture.url; - } - tools_Tools.SetCorsBehavior(img.src, img); - img.onload = () => { - tcx.fillStyle = "rgba(0,0,0,0)"; - tcx.fillRect(0, 0, tcs, tcs); - tempTexture.update(false); - tcx.setTransform(1, 0, 0, -1, 0, 0); - const cellOffsets = [0, 0, 1, 0, 1, 1, 0, 1, -1, 1, -1, 0, -1 - 1, 0, -1, 1, -1]; - switch (this.options.paddingMode) { - //Wrap Mode - case 0: - for (let i = 0; i < 9; i++) { - tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[i], padding + baseSize * cellOffsets[i + 1] - tcs, baseSize, baseSize); - } - break; - //Extend Mode - case 1: - for (let i = 0; i < padding; i++) { - tcx.drawImage(img, 0, 0, img.width, img.height, i + baseSize * cellOffsets[0], padding - tcs, baseSize, baseSize); - tcx.drawImage(img, 0, 0, img.width, img.height, padding * 2 - i, padding - tcs, baseSize, baseSize); - tcx.drawImage(img, 0, 0, img.width, img.height, padding, i - tcs, baseSize, baseSize); - tcx.drawImage(img, 0, 0, img.width, img.height, padding, padding * 2 - i - tcs, baseSize, baseSize); - } - tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[0], padding + baseSize * cellOffsets[1] - tcs, baseSize, baseSize); - break; - //Color Mode - case 2: - tcx.fillStyle = (this.options.paddingColor || math_color_Color3.Black()).toHexString(); - tcx.fillRect(0, 0, tcs, -tcs); - tcx.clearRect(padding, padding, baseSize, baseSize); - tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[0], padding + baseSize * cellOffsets[1] - tcs, baseSize, baseSize); - break; - } - tcx.setTransform(1, 0, 0, 1, 0, 0); - updateDt(); - }; - } - } - } - } - /** - * Calculates the Size of the Channel Sets - * @returns Vector2 - */ - _calculateSize() { - const meshLength = this.meshes.length || 0; - const baseSize = this.options.frameSize || 0; - const padding = this._paddingValue || 0; - switch (this.options.layout) { - case 0: { - //STRIP_LAYOUT - return new math_vector_Vector2(baseSize * meshLength + 2 * padding * meshLength, baseSize + 2 * padding); - } - case 1: { - //POWER2 - const sqrtCount = Math.max(2, Math.ceil(Math.sqrt(meshLength))); - const size = baseSize * sqrtCount + 2 * padding * sqrtCount; - return new math_vector_Vector2(size, size); - } - case 2: { - //COLNUM - const cols = this.options.colnum || 1; - const rowCnt = Math.max(1, Math.ceil(meshLength / cols)); - return new math_vector_Vector2(baseSize * cols + 2 * padding * cols, baseSize * rowCnt + 2 * padding * rowCnt); - } - } - return math_vector_Vector2.Zero(); - } - /** - * Calculates the UV data for the frames. - * @param baseSize the base frameSize - * @param padding the base frame padding - * @param dtSize size of the Dynamic Texture for that channel - * @param dtUnits is 1/dtSize - * @param update flag to update the input meshes - */ - _calculateMeshUVFrames(baseSize, padding, dtSize, dtUnits, update) { - const meshLength = this.meshes.length; - for (let i = 0; i < meshLength; i++) { - const m = this.meshes[i]; - const scale = new math_vector_Vector2(baseSize / dtSize.x, baseSize / dtSize.y); - const pOffset = dtUnits.clone().scale(padding); - const frameOffset = this._getFrameOffset(i); - const offset = frameOffset.add(pOffset); - const frame = new TexturePackerFrame(i, scale, offset); - this.frames.push(frame); - //Update Output UVs - if (update) { - this._updateMeshUV(m, i); - this._updateTextureReferences(m); - } - } - } - /** - * Calculates the frames Offset. - * @param index of the frame - * @returns Vector2 - */ - _getFrameOffset(index) { - const meshLength = this.meshes.length; - let uvStep, yStep, xStep; - switch (this.options.layout) { - case 0: { - //STRIP_LAYOUT - uvStep = 1 / meshLength; - return new math_vector_Vector2(index * uvStep, 0); - } - case 1: { - //POWER2 - const sqrtCount = Math.max(2, Math.ceil(Math.sqrt(meshLength))); - yStep = Math.floor(index / sqrtCount); - xStep = index - yStep * sqrtCount; - uvStep = 1 / sqrtCount; - return new math_vector_Vector2(xStep * uvStep, yStep * uvStep); - } - case 2: { - //COLNUM - const cols = this.options.colnum || 1; - const rowCnt = Math.max(1, Math.ceil(meshLength / cols)); - xStep = Math.floor(index / rowCnt); - yStep = index - xStep * rowCnt; - uvStep = new math_vector_Vector2(1 / cols, 1 / rowCnt); - return new math_vector_Vector2(xStep * uvStep.x, yStep * uvStep.y); - } - } - return math_vector_Vector2.Zero(); - } - /** - * Updates a Mesh to the frame data - * @param mesh that is the target - * @param frameID or the frame index - */ - _updateMeshUV(mesh, frameID) { - const frame = this.frames[frameID]; - const uvIn = mesh.getVerticesData(this.options.uvsIn || buffer_VertexBuffer.UVKind); - const uvOut = []; - let toCount = 0; - if (uvIn.length) { - toCount = uvIn.length || 0; - } - for (let i = 0; i < toCount; i += 2) { - uvOut.push(uvIn[i] * frame.scale.x + frame.offset.x, uvIn[i + 1] * frame.scale.y + frame.offset.y); - } - mesh.setVerticesData(this.options.uvsOut || buffer_VertexBuffer.UVKind, uvOut); - } - /** - * Updates a Meshes materials to use the texture packer channels - * @param m is the mesh to target - * @param force all channels on the packer to be set. - */ - _updateTextureReferences(m, force = false) { - const mat = m.material; - const sKeys = Object.keys(this.sets); - const _dispose = (_t) => { - if (_t.dispose) { - _t.dispose(); - } - }; - for (let i = 0; i < sKeys.length; i++) { - const setName = sKeys[i]; - if (!force) { - if (!mat) { - return; - } - if (mat[setName] !== null) { - _dispose(mat[setName]); - mat[setName] = this.sets[setName]; - } - } - else { - if (mat[setName] !== null) { - _dispose(mat[setName]); - } - mat[setName] = this.sets[setName]; - } - } - } - /** - * Public method to set a Mesh to a frame - * @param m that is the target - * @param frameID or the frame index - * @param updateMaterial trigger for if the Meshes attached Material be updated? - */ - setMeshToFrame(m, frameID, updateMaterial = false) { - this._updateMeshUV(m, frameID); - if (updateMaterial) { - this._updateTextureReferences(m, true); - } - } - /** - * Starts the async promise to compile the texture packer. - * @returns Promise<void> - */ - processAsync() { - return new Promise((resolve, reject) => { - try { - if (this.meshes.length === 0) { - //Must be a JSON load! - resolve(); - return; - } - let done = 0; - const doneCheck = (mat) => { - done++; - //Check Status of all Textures on all meshes, till they are ready. - if (this.options.map) { - for (let j = 0; j < this.options.map.length; j++) { - const index = this.options.map[j]; - const t = mat[index]; - if (t !== null) { - if (!this.sets[this.options.map[j]]) { - this.sets[this.options.map[j]] = true; - } - this._expecting++; - } - } - if (done === this.meshes.length) { - this._createFrames(resolve); - } - } - }; - for (let i = 0; i < this.meshes.length; i++) { - const mesh = this.meshes[i]; - const material = mesh.material; - if (!material) { - done++; - if (done === this.meshes.length) { - return this._createFrames(resolve); - } - continue; - } - material.forceCompilationAsync(mesh).then(() => { - doneCheck(material); - }); - } - } - catch (e) { - return reject(e); - } - }); - } - /** - * Disposes all textures associated with this packer - */ - dispose() { - const sKeys = Object.keys(this.sets); - for (let i = 0; i < sKeys.length; i++) { - const channel = sKeys[i]; - this.sets[channel].dispose(); - } - } - /** - * Starts the download process for all the channels converting them to base64 data and embedding it all in a JSON file. - * @param imageType is the image type to use. - * @param quality of the image if downloading as jpeg, Ranges from >0 to 1. - */ - download(imageType = "png", quality = 1) { - setTimeout(() => { - const pack = { - name: this.name, - sets: {}, - options: {}, - frames: [], - }; - const sKeys = Object.keys(this.sets); - const oKeys = Object.keys(this.options); - try { - for (let i = 0; i < sKeys.length; i++) { - const channel = sKeys[i]; - const dt = this.sets[channel]; - pack.sets[channel] = dt.getContext().canvas.toDataURL("image/" + imageType, quality); - } - for (let i = 0; i < oKeys.length; i++) { - const opt = oKeys[i]; - pack.options[opt] = this.options[opt]; - } - for (let i = 0; i < this.frames.length; i++) { - const _f = this.frames[i]; - pack.frames.push(_f.scale.x, _f.scale.y, _f.offset.x, _f.offset.y); - } - } - catch (err) { - logger_Logger.Warn("Unable to download: " + err); - return; - } - const data = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(pack, null, 4)); - const _a = document.createElement("a"); - _a.setAttribute("href", data); - _a.setAttribute("download", this.name + "_texurePackage.json"); - document.body.appendChild(_a); - _a.click(); - _a.remove(); - }, 0); - } - /** - * Public method to load a texturePacker JSON file. - * @param data of the JSON file in string format. - */ - updateFromJSON(data) { - try { - const parsedData = JSON.parse(data); - this.name = parsedData.name; - const _options = Object.keys(parsedData.options); - for (let i = 0; i < _options.length; i++) { - this.options[_options[i]] = parsedData.options[_options[i]]; - } - for (let i = 0; i < parsedData.frames.length; i += 4) { - const frame = new TexturePackerFrame(i / 4, new math_vector_Vector2(parsedData.frames[i], parsedData.frames[i + 1]), new math_vector_Vector2(parsedData.frames[i + 2], parsedData.frames[i + 3])); - this.frames.push(frame); - } - const channels = Object.keys(parsedData.sets); - for (let i = 0; i < channels.length; i++) { - const _t = new texture_Texture(parsedData.sets[channels[i]], this.scene, false, false); - this.sets[channels[i]] = _t; - } - } - catch (err) { - logger_Logger.Warn("Unable to update from JSON: " + err); - } - } -} -/** Packer Layout Constant 0 */ -TexturePacker.LAYOUT_STRIP = 0; -/** Packer Layout Constant 1 */ -TexturePacker.LAYOUT_POWER2 = 1; -/** Packer Layout Constant 2 */ -TexturePacker.LAYOUT_COLNUM = 2; -/** Packer Layout Constant 0 */ -TexturePacker.SUBUV_WRAP = 0; -/** Packer Layout Constant 1 */ -TexturePacker.SUBUV_EXTEND = 1; -/** Packer Layout Constant 2 */ -TexturePacker.SUBUV_COLOR = 2; -//# sourceMappingURL=packer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Packer/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Procedurals/customProceduralTexture.js - - - - - - -/** - * 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. - * Custom Procedural textures are the easiest way to create your own procedural in your application. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures#creating-custom-procedural-textures - */ -class CustomProceduralTexture extends (/* unused pure expression or super */ null && (ProceduralTexture)) { - /** - * Instantiates a new Custom Procedural Texture. - * 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. - * Custom Procedural textures are the easiest way to create your own procedural in your application. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures#creating-custom-procedural-textures - * @param name Define the name of the texture - * @param texturePath Define the folder path containing all the custom texture related files (config, shaders...) - * @param size Define the size of the texture to create - * @param scene Define the scene the texture belongs to - * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture - * @param generateMipMaps Define if the texture should creates mip maps or not - * @param skipJson Define a boolena indicating that there is no json config file to load - */ - constructor(name, texturePath, size, scene, fallbackTexture, generateMipMaps, skipJson) { - super(name, size, null, scene, fallbackTexture, generateMipMaps); - this._animate = true; - this._time = 0; - this._texturePath = texturePath; - if (!skipJson) { - //Try to load json - this._loadJson(texturePath); - } - else { - this.setFragment(this._texturePath); - } - this.refreshRate = 1; - } - _loadJson(jsonUrl) { - const noConfigFile = () => { - try { - this.setFragment(this._texturePath); - } - catch (ex) { - Logger.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture"); - } - }; - const configFileUrl = jsonUrl + "/config.json"; - const xhr = new WebRequest(); - xhr.open("GET", configFileUrl); - xhr.addEventListener("load", () => { - if (xhr.status === 200 || (xhr.responseText && xhr.responseText.length > 0)) { - try { - this._config = JSON.parse(xhr.response); - this.updateShaderUniforms(); - this.updateTextures(); - this.setFragment(this._texturePath + "/custom"); - this._animate = this._config.animate; - this.refreshRate = this._config.refreshrate; - } - catch (ex) { - noConfigFile(); - } - } - else { - noConfigFile(); - } - }, false); - xhr.addEventListener("error", () => { - noConfigFile(); - }, false); - try { - xhr.send(); - } - catch (ex) { - Logger.Error("CustomProceduralTexture: Error on XHR send request."); - } - } - /** - * Is the texture ready to be used ? (rendered at least once) - * @returns true if ready, otherwise, false. - */ - isReady() { - if (!super.isReady()) { - return false; - } - for (const name in this._textures) { - const texture = this._textures[name]; - if (!texture.isReady()) { - return false; - } - } - return true; - } - /** - * Render the texture to its associated render target. - * @param useCameraPostProcess Define if camera post process should be applied to the texture - */ - render(useCameraPostProcess) { - const scene = this.getScene(); - if (this._animate && scene) { - this._time += scene.getAnimationRatio() * 0.03; - this.updateShaderUniforms(); - } - super.render(useCameraPostProcess); - } - /** - * Update the list of dependant textures samplers in the shader. - */ - updateTextures() { - for (let i = 0; i < this._config.sampler2Ds.length; i++) { - this.setTexture(this._config.sampler2Ds[i].sample2Dname, new Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene())); - } - } - /** - * Update the uniform values of the procedural texture in the shader. - */ - updateShaderUniforms() { - if (this._config) { - for (let j = 0; j < this._config.uniforms.length; j++) { - const uniform = this._config.uniforms[j]; - switch (uniform.type) { - case "float": - this.setFloat(uniform.name, uniform.value); - break; - case "color3": - this.setColor3(uniform.name, new Color3(uniform.r, uniform.g, uniform.b)); - break; - case "color4": - this.setColor4(uniform.name, new Color4(uniform.r, uniform.g, uniform.b, uniform.a)); - break; - case "vector2": - this.setVector2(uniform.name, new Vector2(uniform.x, uniform.y)); - break; - case "vector3": - this.setVector3(uniform.name, new Vector3(uniform.x, uniform.y, uniform.z)); - break; - } - } - } - this.setFloat("time", this._time); - } - /** - * Define if the texture animates or not. - */ - get animate() { - return this._animate; - } - set animate(value) { - this._animate = value; - } -} -//# sourceMappingURL=customProceduralTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/noise.fragment.js -// Do not edit. - -const noise_fragment_name = "noisePixelShader"; -const noise_fragment_shader = `uniform float brightness;uniform float persistence;uniform float timeScale;varying vec2 vUV;vec2 hash22(vec2 p) -{p=p*mat2(127.1,311.7,269.5,183.3);p=-1.0+2.0*fract(sin(p)*43758.5453123);return sin(p*6.283+timeScale);} -float interpolationNoise(vec2 p) -{vec2 pi=floor(p);vec2 pf=p-pi;vec2 w=pf*pf*(3.-2.*pf);float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));float xm1=mix(f00,f10,w.x);float xm2=mix(f01,f11,w.x);float ym=mix(xm1,xm2,w.y); -return ym;} -float perlinNoise2D(float x,float y) -{float sum=0.0;float frequency=0.0;float amplitude=0.0;for(int i=0; i<OCTAVES; i++) -{frequency=pow(2.0,float(i));amplitude=pow(persistence,float(i));sum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;} -return sum;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float x=abs(vUV.x);float y=abs(vUV.y);float noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);gl_FragColor=vec4(noise,noise,noise,1.0);} -`; -// Sideeffect -ShaderStore.ShadersStore[noise_fragment_name] = noise_fragment_shader; -/** @internal */ -const noisePixelShader = { name: noise_fragment_name, shader: noise_fragment_shader }; -//# sourceMappingURL=noise.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Procedurals/noiseProceduralTexture.js - - - - -/** - * Class used to generate noise procedural textures - */ -class NoiseProceduralTexture extends proceduralTexture_ProceduralTexture { - /** - * Creates a new NoiseProceduralTexture - * @param name defines the name fo the texture - * @param size defines the size of the texture (default is 256) - * @param scene defines the hosting scene - * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created - * @param generateMipMaps defines if mipmaps must be generated (true by default) - */ - constructor(name, size = 256, scene = engineStore_EngineStore.LastCreatedScene, fallbackTexture, generateMipMaps) { - super(name, size, "noise", scene, fallbackTexture, generateMipMaps); - /** Gets or sets the start time (default is 0) */ - this.time = 0.0; - /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */ - this.brightness = 0.2; - /** Defines the number of octaves to process */ - this.octaves = 3; - /** Defines the level of persistence (0.8 by default) */ - this.persistence = 0.8; - /** Gets or sets animation speed factor (default is 1) */ - this.animationSpeedFactor = 1; - this.autoClear = false; - this._updateShaderUniforms(); - } - _updateShaderUniforms() { - const scene = this.getScene(); - if (!scene) { - return; - } - this.time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01; - this.setFloat("brightness", this.brightness); - this.setFloat("persistence", this.persistence); - this.setFloat("timeScale", this.time); - } - _getDefines() { - return "#define OCTAVES " + (this.octaves | 0); - } - /** - * Generate the current state of the procedural texture - * @param useCameraPostProcess - */ - render(useCameraPostProcess) { - this._updateShaderUniforms(); - super.render(useCameraPostProcess); - } - /** - * Serializes this noise procedural texture - * @returns a serialized noise procedural texture object - */ - serialize() { - const serializationObject = {}; - serializationObject.customType = "BABYLON.NoiseProceduralTexture"; - serializationObject.brightness = this.brightness; - serializationObject.octaves = this.octaves; - serializationObject.persistence = this.persistence; - serializationObject.animationSpeedFactor = this.animationSpeedFactor; - serializationObject.size = this.getSize().width; - serializationObject.generateMipMaps = this._generateMipMaps; - serializationObject.time = this.time; - return serializationObject; - } - /** - * Clone the texture. - * @returns the cloned texture - */ - clone() { - const textureSize = this.getSize(); - const newTexture = new NoiseProceduralTexture(this.name, textureSize.width, this.getScene(), this._fallbackTexture ? this._fallbackTexture : undefined, this._generateMipMaps); - // Base texture - newTexture.hasAlpha = this.hasAlpha; - newTexture.level = this.level; - // RenderTarget Texture - newTexture.coordinatesMode = this.coordinatesMode; - // Noise Specifics - newTexture.brightness = this.brightness; - newTexture.octaves = this.octaves; - newTexture.persistence = this.persistence; - newTexture.animationSpeedFactor = this.animationSpeedFactor; - newTexture.time = this.time; - return newTexture; - } - /** - * Creates a NoiseProceduralTexture from parsed noise procedural texture data - * @param parsedTexture defines parsed texture data - * @param scene defines the current scene - * @returns a parsed NoiseProceduralTexture - */ - static Parse(parsedTexture, scene) { - var _a; - const texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps); - texture.brightness = parsedTexture.brightness; - texture.octaves = parsedTexture.octaves; - texture.persistence = parsedTexture.persistence; - texture.animationSpeedFactor = parsedTexture.animationSpeedFactor; - texture.time = (_a = parsedTexture.time) !== null && _a !== void 0 ? _a : 0; - return texture; - } -} -RegisterClass("BABYLON.NoiseProceduralTexture", NoiseProceduralTexture); -//# sourceMappingURL=noiseProceduralTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/Procedurals/index.js - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/rawCubeTexture.js - - - - - - -/** - * Raw cube texture where the raw buffers are passed in - */ -class RawCubeTexture extends (/* unused pure expression or super */ null && (CubeTexture)) { - /** - * Creates a cube texture where the raw buffers are passed in. - * @param scene defines the scene the texture is attached to - * @param data defines the array of data to use to create each face - * @param size defines the size of the textures - * @param format defines the format of the data - * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT) - * @param generateMipMaps defines if the engine should generate the mip levels - * @param invertY defines if data must be stored with Y axis inverted - * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) - * @param compression defines the compression used (null by default) - */ - constructor(scene, data, size, format = 5, type = 0, generateMipMaps = false, invertY = false, samplingMode = 3, compression = null) { - super("", scene); - this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression); - } - /** - * Updates the raw cube texture. - * @param data defines the data to store - * @param format defines the data format - * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default) - * @param invertY defines if data must be stored with Y axis inverted - * @param compression defines the compression used (null by default) - */ - update(data, format, type, invertY, compression = null) { - this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression); - } - /** - * Updates a raw cube texture with RGBD encoded data. - * @param data defines the array of data [mipmap][face] to use to create each face - * @param sphericalPolynomial defines the spherical polynomial for irradiance - * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness - * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness - * @returns a promise that resolves when the operation is complete - */ - updateRGBDAsync(data, sphericalPolynomial = null, lodScale = 0.8, lodOffset = 0) { - return UpdateRGBDAsyncEnvTools(this._texture, data, sphericalPolynomial, lodScale, lodOffset).then(() => { }); - } - /** - * Clones the raw cube texture. - * @returns a new cube texture - */ - clone() { - return SerializationHelper.Clone(() => { - const scene = this.getScene(); - const internalTexture = this._texture; - const texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression); - if (internalTexture.source === InternalTextureSource.CubeRawRGBD) { - texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset); - } - return texture; - }, this); - } -} -//# sourceMappingURL=rawCubeTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/rawTexture3D.js - - - -/** - * Class used to store 3D textures containing user data - */ -class RawTexture3D extends (/* unused pure expression or super */ null && (Texture)) { - /** - * Create a new RawTexture3D - * @param data defines the data of the texture - * @param width defines the width of the texture - * @param height defines the height of the texture - * @param depth defines the depth of the texture - * @param format defines the texture format to use - * @param scene defines the hosting scene - * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default) - * @param invertY defines if texture must be stored with Y axis inverted - * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default) - * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...) - * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) - */ - constructor(data, width, height, depth, - /** Gets or sets the texture format to use */ - format, scene, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, textureType = 0, creationFlags) { - super(null, scene, !generateMipMaps, invertY); - this.format = format; - this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, null, textureType, creationFlags); - this.is3D = true; - } - /** - * Update the texture with new data - * @param data defines the data to store in the texture - */ - update(data) { - if (!this._texture) { - return; - } - this._getEngine().updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type); - } -} -//# sourceMappingURL=rawTexture3D.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/refractionTexture.js - - -/** - * Creates a refraction texture used by refraction channel of the standard material. - * It is like a mirror but to see through a material. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#refractiontexture - */ -class RefractionTexture extends (/* unused pure expression or super */ null && (RenderTargetTexture)) { - /** - * Creates a refraction texture used by refraction channel of the standard material. - * It is like a mirror but to see through a material. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#refraction - * @param name Define the texture name - * @param size Define the size of the underlying texture - * @param scene Define the scene the refraction belongs to - * @param generateMipMaps Define if we need to generate mips level for the refraction - */ - constructor(name, size, scene, generateMipMaps) { - super(name, size, scene, generateMipMaps, true); - /** - * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor. - * 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. - * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#refraction - */ - this.refractionPlane = new Plane(0, 1, 0, 1); - /** - * Define how deep under the surface we should see. - */ - this.depth = 2.0; - this.onBeforeRenderObservable.add(() => { - this.getScene().clipPlane = this.refractionPlane; - }); - this.onAfterRenderObservable.add(() => { - this.getScene().clipPlane = null; - }); - } - /** - * Clone the refraction texture. - * @returns the cloned texture - */ - clone() { - const scene = this.getScene(); - if (!scene) { - return this; - } - const textureSize = this.getSize(); - const newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps); - // Base texture - newTexture.hasAlpha = this.hasAlpha; - newTexture.level = this.level; - // Refraction Texture - newTexture.refractionPlane = this.refractionPlane.clone(); - if (this.renderList) { - newTexture.renderList = this.renderList.slice(0); - } - newTexture.depth = this.depth; - return newTexture; - } - /** - * Serialize the texture to a JSON representation you could use in Parse later on - * @returns the serialized JSON representation - */ - serialize() { - if (!this.name) { - return null; - } - const serializationObject = super.serialize(); - serializationObject.mirrorPlane = this.refractionPlane.asArray(); - serializationObject.depth = this.depth; - return serializationObject; - } -} -//# sourceMappingURL=refractionTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/thinRenderTargetTexture.js - -/** - * This is a tiny helper class to wrap a RenderTargetWrapper in a texture - * usable as the input of an effect. - */ -class ThinRenderTargetTexture extends (/* unused pure expression or super */ null && (ThinTexture)) { - /** - * Gets the render target wrapper associated with this render target - */ - get renderTarget() { - return this._renderTarget; - } - /** - * Instantiates a new ThinRenderTargetTexture. - * Tiny helper class to wrap a RenderTargetWrapper in a texture. - * This can be used as an internal texture wrapper in ThinEngine to benefit from the cache and to hold on the associated RTT - * @param engine Define the internalTexture to wrap - * @param size Define the size of the RTT to create - * @param options Define rendertarget options - */ - constructor(engine, size, options) { - super(null); - this._renderTarget = null; - this._engine = engine; - this._renderTargetOptions = options; - this.resize(size); - } - /** - * Resize the texture to a new desired size. - * Be careful as it will recreate all the data in the new texture. - * @param size Define the new size. It can be: - * - a number for squared texture, - * - an object containing { width: number, height: number } - */ - resize(size) { - var _a; - (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose(); - this._renderTarget = null; - this._texture = null; - this._size = size; - if (this._engine) { - this._renderTarget = this._engine.createRenderTargetTexture(this._size, this._renderTargetOptions); - } - this._texture = this.renderTarget.texture; - } - /** - * Get the underlying lower level texture from Babylon. - * @returns the internal texture - */ - getInternalTexture() { - return this._texture; - } - /** - * Get the class name of the texture. - * @returns "ThinRenderTargetTexture" - */ - getClassName() { - return "ThinRenderTargetTexture"; - } - /** - * Dispose the texture and release its associated resources. - * @param disposeOnlyFramebuffers - */ - dispose(disposeOnlyFramebuffers = false) { - var _a; - (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose(true); - this._renderTarget = null; - if (!disposeOnlyFramebuffers) { - super.dispose(); - } - } -} -//# sourceMappingURL=thinRenderTargetTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/index.js -/* eslint-disable import/no-internal-modules */ - -// eslint-disable-next-line import/export - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Enums/index.js - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/nodeMaterialConnectionPointCustomObject.js - -/** - * Defines a connection point to be used for points with a custom object type - */ -class NodeMaterialConnectionPointCustomObject extends NodeMaterialConnectionPoint { - /** - * Creates a new connection point - * @param name defines the connection point name - * @param ownerBlock defines the block hosting this connection point - * @param direction defines the direction of the connection point - * @param _blockType - * @param _blockName - */ - constructor(name, ownerBlock, direction, - // @internal - _blockType, _blockName) { - super(name, ownerBlock, direction); - this._blockType = _blockType; - this._blockName = _blockName; - this.needDualDirectionValidation = true; - } - /** - * Gets a number indicating if the current point can be connected to another point - * @param connectionPoint defines the other connection point - * @returns a number defining the compatibility state - */ - checkCompatibilityState(connectionPoint) { - return connectionPoint instanceof NodeMaterialConnectionPointCustomObject && connectionPoint._blockName === this._blockName - ? NodeMaterialConnectionPointCompatibilityStates.Compatible - : NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible; - } - /** - * Creates a block suitable to be used as an input for this input point. - * If null is returned, a block based on the point type will be created. - * @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 - */ - createCustomInputBlock() { - return [new this._blockType(this._blockName), this.name]; - } -} -//# sourceMappingURL=nodeMaterialConnectionPointCustomObject.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/bonesBlock.js - - - - - - - - - -/** - * Block used to add support for vertex skinning (bones) - */ -class BonesBlock extends NodeMaterialBlock { - /** - * Creates a new BonesBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Vertex); - this.registerInput("matricesIndices", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("matricesWeights", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("matricesIndicesExtra", NodeMaterialBlockConnectionPointTypes.Vector4, true); - this.registerInput("matricesWeightsExtra", NodeMaterialBlockConnectionPointTypes.Vector4, true); - this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("boneSampler"); - state._excludeVariableName("boneTextureWidth"); - state._excludeVariableName("mBones"); - state._excludeVariableName("BonesPerMesh"); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "BonesBlock"; - } - /** - * Gets the matrix indices input component - */ - get matricesIndices() { - return this._inputs[0]; - } - /** - * Gets the matrix weights input component - */ - get matricesWeights() { - return this._inputs[1]; - } - /** - * Gets the extra matrix indices input component - */ - get matricesIndicesExtra() { - return this._inputs[2]; - } - /** - * Gets the extra matrix weights input component - */ - get matricesWeightsExtra() { - return this._inputs[3]; - } - /** - * Gets the world input component - */ - get world() { - return this._inputs[4]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - autoConfigure(material) { - if (!this.matricesIndices.isConnected) { - let matricesIndicesInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "matricesIndices"); - if (!matricesIndicesInput) { - matricesIndicesInput = new InputBlock("matricesIndices"); - matricesIndicesInput.setAsAttribute("matricesIndices"); - } - matricesIndicesInput.output.connectTo(this.matricesIndices); - } - if (!this.matricesWeights.isConnected) { - let matricesWeightsInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "matricesWeights"); - if (!matricesWeightsInput) { - matricesWeightsInput = new InputBlock("matricesWeights"); - matricesWeightsInput.setAsAttribute("matricesWeights"); - } - matricesWeightsInput.output.connectTo(this.matricesWeights); - } - if (!this.world.isConnected) { - let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World); - if (!worldInput) { - worldInput = new InputBlock("world"); - worldInput.setAsSystemValue(NodeMaterialSystemValues.World); - } - worldInput.output.connectTo(this.world); - } - } - provideFallbacks(mesh, fallbacks) { - if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { - fallbacks.addCPUSkinningFallback(0, mesh); - } - } - bind(effect, nodeMaterial, mesh) { - MaterialHelper.BindBonesParameters(mesh, effect); - } - prepareDefines(mesh, nodeMaterial, defines) { - if (!defines._areAttributesDirty) { - return; - } - MaterialHelper.PrepareDefinesForBones(mesh, defines); - } - _buildBlock(state) { - super._buildBlock(state); - // Register for compilation fallbacks - state.sharedData.blocksWithFallbacks.push(this); - // Register for binding - state.sharedData.forcedBindableBlocks.push(this); - // Register for defines - state.sharedData.blocksWithDefines.push(this); - // Register internal uniforms and samplers - state.uniforms.push("boneTextureWidth"); - state.uniforms.push("mBones"); - state.samplers.push("boneSampler"); - // Emit code - const comments = `//${this.name}`; - state._emitFunctionFromInclude("bonesDeclaration", comments, { - removeAttributes: true, - removeUniforms: false, - removeVaryings: true, - removeIfDef: false, - }); - const influenceVariablename = state._getFreeVariableName("influence"); - state.compilationString += state._emitCodeFromInclude("bonesVertex", comments, { - replaceStrings: [ - { - search: /finalWorld=finalWorld\*influence;/, - replace: "", - }, - { - search: /influence/gm, - replace: influenceVariablename, - }, - ], - }); - const output = this._outputs[0]; - const worldInput = this.world; - state.compilationString += `#if NUM_BONE_INFLUENCERS>0\n`; - state.compilationString += this._declareOutput(output, state) + ` = ${worldInput.associatedVariableName} * ${influenceVariablename};\n`; - state.compilationString += `#else\n`; - state.compilationString += this._declareOutput(output, state) + ` = ${worldInput.associatedVariableName};\n`; - state.compilationString += `#endif\n`; - return this; - } -} -RegisterClass("BABYLON.BonesBlock", BonesBlock); -//# sourceMappingURL=bonesBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/instancesBlock.js - - - - - - -/** - * Block used to add support for instances - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances - */ -class InstancesBlock extends NodeMaterialBlock { - /** - * Creates a new InstancesBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Vertex); - this.registerInput("world0", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("world1", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("world2", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("world3", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, true); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix); - this.registerOutput("instanceID", NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "InstancesBlock"; - } - /** - * Gets the first world row input component - */ - get world0() { - return this._inputs[0]; - } - /** - * Gets the second world row input component - */ - get world1() { - return this._inputs[1]; - } - /** - * Gets the third world row input component - */ - get world2() { - return this._inputs[2]; - } - /** - * Gets the forth world row input component - */ - get world3() { - return this._inputs[3]; - } - /** - * Gets the world input component - */ - get world() { - return this._inputs[4]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets the instanceID component - */ - get instanceID() { - return this._outputs[1]; - } - autoConfigure(material) { - if (!this.world0.connectedPoint) { - let world0Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world0"); - if (!world0Input) { - world0Input = new InputBlock("world0"); - world0Input.setAsAttribute("world0"); - } - world0Input.output.connectTo(this.world0); - } - if (!this.world1.connectedPoint) { - let world1Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world1"); - if (!world1Input) { - world1Input = new InputBlock("world1"); - world1Input.setAsAttribute("world1"); - } - world1Input.output.connectTo(this.world1); - } - if (!this.world2.connectedPoint) { - let world2Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world2"); - if (!world2Input) { - world2Input = new InputBlock("world2"); - world2Input.setAsAttribute("world2"); - } - world2Input.output.connectTo(this.world2); - } - if (!this.world3.connectedPoint) { - let world3Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world3"); - if (!world3Input) { - world3Input = new InputBlock("world3"); - world3Input.setAsAttribute("world3"); - } - world3Input.output.connectTo(this.world3); - } - if (!this.world.connectedPoint) { - let worldInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "world"); - if (!worldInput) { - worldInput = new InputBlock("world"); - worldInput.setAsSystemValue(NodeMaterialSystemValues.World); - } - worldInput.output.connectTo(this.world); - } - this.world.define = "!INSTANCES || THIN_INSTANCES"; - } - prepareDefines(mesh, nodeMaterial, defines, useInstances = false, subMesh) { - let changed = false; - if (defines["INSTANCES"] !== useInstances) { - defines.setValue("INSTANCES", useInstances); - changed = true; - } - if (subMesh && defines["THIN_INSTANCES"] !== !!(subMesh === null || subMesh === void 0 ? void 0 : subMesh.getRenderingMesh().hasThinInstances)) { - defines.setValue("THIN_INSTANCES", !!(subMesh === null || subMesh === void 0 ? void 0 : subMesh.getRenderingMesh().hasThinInstances)); - changed = true; - } - if (changed) { - defines.markAsUnprocessed(); - } - } - _buildBlock(state) { - super._buildBlock(state); - const engine = state.sharedData.scene.getEngine(); - // Register for defines - state.sharedData.blocksWithDefines.push(this); - // Emit code - const output = this._outputs[0]; - const instanceID = this._outputs[1]; - const world0 = this.world0; - const world1 = this.world1; - const world2 = this.world2; - const world3 = this.world3; - state.compilationString += `#ifdef INSTANCES\n`; - state.compilationString += - this._declareOutput(output, state) + - ` = mat4(${world0.associatedVariableName}, ${world1.associatedVariableName}, ${world2.associatedVariableName}, ${world3.associatedVariableName});\n`; - state.compilationString += `#ifdef THIN_INSTANCES\n`; - state.compilationString += `${output.associatedVariableName} = ${this.world.associatedVariableName} * ${output.associatedVariableName};\n`; - state.compilationString += `#endif\n`; - if (engine._caps.canUseGLInstanceID) { - state.compilationString += this._declareOutput(instanceID, state) + ` = float(gl_InstanceID);\n`; - } - else { - state.compilationString += this._declareOutput(instanceID, state) + ` = 0.0;\n`; - } - state.compilationString += `#else\n`; - state.compilationString += this._declareOutput(output, state) + ` = ${this.world.associatedVariableName};\n`; - state.compilationString += this._declareOutput(instanceID, state) + ` = 0.0;\n`; - state.compilationString += `#endif\n`; - return this; - } -} -RegisterClass("BABYLON.InstancesBlock", InstancesBlock); -//# sourceMappingURL=instancesBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/morphTargetsBlock.js - - - - - - - - - -/** - * Block used to add morph targets support to vertex shader - */ -class MorphTargetsBlock extends NodeMaterialBlock { - /** - * Create a new MorphTargetsBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Vertex); - this.registerInput("position", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerInput("tangent", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.tangent.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerOutput("positionOutput", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerOutput("normalOutput", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerOutput("tangentOutput", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerOutput("uvOutput", NodeMaterialBlockConnectionPointTypes.Vector2); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MorphTargetsBlock"; - } - /** - * Gets the position input component - */ - get position() { - return this._inputs[0]; - } - /** - * Gets the normal input component - */ - get normal() { - return this._inputs[1]; - } - /** - * Gets the tangent input component - */ - get tangent() { - return this._inputs[2]; - } - /** - * Gets the tangent input component - */ - get uv() { - return this._inputs[3]; - } - /** - * Gets the position output component - */ - get positionOutput() { - return this._outputs[0]; - } - /** - * Gets the normal output component - */ - get normalOutput() { - return this._outputs[1]; - } - /** - * Gets the tangent output component - */ - get tangentOutput() { - return this._outputs[2]; - } - /** - * Gets the tangent output component - */ - get uvOutput() { - return this._outputs[3]; - } - initialize(state) { - state._excludeVariableName("morphTargetInfluences"); - } - autoConfigure(material) { - if (!this.position.isConnected) { - let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "position"); - if (!positionInput) { - positionInput = new InputBlock("position"); - positionInput.setAsAttribute(); - } - positionInput.output.connectTo(this.position); - } - if (!this.normal.isConnected) { - let normalInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "normal"); - if (!normalInput) { - normalInput = new InputBlock("normal"); - normalInput.setAsAttribute("normal"); - } - normalInput.output.connectTo(this.normal); - } - if (!this.tangent.isConnected) { - let tangentInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "tangent"); - if (!tangentInput) { - tangentInput = new InputBlock("tangent"); - tangentInput.setAsAttribute("tangent"); - } - tangentInput.output.connectTo(this.tangent); - } - if (!this.uv.isConnected) { - let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv"); - if (!uvInput) { - uvInput = new InputBlock("uv"); - uvInput.setAsAttribute("uv"); - } - uvInput.output.connectTo(this.uv); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - if (mesh.morphTargetManager) { - const morphTargetManager = mesh.morphTargetManager; - if ((morphTargetManager === null || morphTargetManager === void 0 ? void 0 : morphTargetManager.isUsingTextureForTargets) && morphTargetManager.numInfluencers !== defines["NUM_MORPH_INFLUENCERS"]) { - defines.markAsAttributesDirty(); - } - } - if (!defines._areAttributesDirty) { - return; - } - MaterialHelper.PrepareDefinesForMorphTargets(mesh, defines); - } - bind(effect, nodeMaterial, mesh) { - if (mesh && mesh.morphTargetManager && mesh.morphTargetManager.numInfluencers > 0) { - MaterialHelper.BindMorphTargetParameters(mesh, effect); - if (mesh.morphTargetManager.isUsingTextureForTargets) { - mesh.morphTargetManager._bind(effect); - } - } - } - replaceRepeatableContent(vertexShaderState, fragmentShaderState, mesh, defines) { - const position = this.position; - const normal = this.normal; - const tangent = this.tangent; - const uv = this.uv; - const positionOutput = this.positionOutput; - const normalOutput = this.normalOutput; - const tangentOutput = this.tangentOutput; - const uvOutput = this.uvOutput; - const state = vertexShaderState; - const repeatCount = defines.NUM_MORPH_INFLUENCERS; - const manager = mesh.morphTargetManager; - const hasNormals = manager && manager.supportsNormals && defines["NORMAL"]; - const hasTangents = manager && manager.supportsTangents && defines["TANGENT"]; - const hasUVs = manager && manager.supportsUVs && defines["UV1"]; - let injectionCode = ""; - if ((manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) && repeatCount > 0) { - injectionCode += `float vertexID;\n`; - } - for (let index = 0; index < repeatCount; index++) { - injectionCode += `#ifdef MORPHTARGETS\n`; - if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) { - injectionCode += `vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;\n`; - injectionCode += `${positionOutput.associatedVariableName} += (readVector3FromRawSampler(${index}, vertexID) - ${position.associatedVariableName}) * morphTargetInfluences[${index}];\n`; - injectionCode += `vertexID += 1.0;\n`; - } - else { - injectionCode += `${positionOutput.associatedVariableName} += (position${index} - ${position.associatedVariableName}) * morphTargetInfluences[${index}];\n`; - } - if (hasNormals) { - injectionCode += `#ifdef MORPHTARGETS_NORMAL\n`; - if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) { - injectionCode += `${normalOutput.associatedVariableName} += (readVector3FromRawSampler(${index}, vertexID) - ${normal.associatedVariableName}) * morphTargetInfluences[${index}];\n`; - injectionCode += `vertexID += 1.0;\n`; - } - else { - injectionCode += `${normalOutput.associatedVariableName} += (normal${index} - ${normal.associatedVariableName}) * morphTargetInfluences[${index}];\n`; - } - injectionCode += `#endif\n`; - } - if (hasUVs) { - injectionCode += `#ifdef MORPHTARGETS_UV\n`; - if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) { - injectionCode += `${uvOutput.associatedVariableName} += (readVector3FromRawSampler(${index}, vertexID).xy - ${uv.associatedVariableName}) * morphTargetInfluences[${index}];\n`; - injectionCode += `vertexID += 1.0;\n`; - } - else { - injectionCode += `${uvOutput.associatedVariableName}.xy += (uv_${index} - ${uv.associatedVariableName}.xy) * morphTargetInfluences[${index}];\n`; - } - injectionCode += `#endif\n`; - } - if (hasTangents) { - injectionCode += `#ifdef MORPHTARGETS_TANGENT\n`; - if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) { - injectionCode += `${tangentOutput.associatedVariableName}.xyz += (readVector3FromRawSampler(${index}, vertexID) - ${tangent.associatedVariableName}.xyz) * morphTargetInfluences[${index}];\n`; - } - else { - injectionCode += `${tangentOutput.associatedVariableName}.xyz += (tangent${index} - ${tangent.associatedVariableName}.xyz) * morphTargetInfluences[${index}];\n`; - } - if (tangent.type === NodeMaterialBlockConnectionPointTypes.Vector4) { - injectionCode += `${tangentOutput.associatedVariableName}.w = ${tangent.associatedVariableName}.w;\n`; - } - else { - injectionCode += `${tangentOutput.associatedVariableName}.w = 1.;\n`; - } - injectionCode += `#endif\n`; - } - injectionCode += `#endif\n`; - } - state.compilationString = state.compilationString.replace(this._repeatableContentAnchor, injectionCode); - if (repeatCount > 0) { - for (let index = 0; index < repeatCount; index++) { - state.attributes.push(buffer_VertexBuffer.PositionKind + index); - if (hasNormals) { - state.attributes.push(buffer_VertexBuffer.NormalKind + index); - } - if (hasTangents) { - state.attributes.push(buffer_VertexBuffer.TangentKind + index); - } - if (hasUVs) { - state.attributes.push(buffer_VertexBuffer.UVKind + "_" + index); - } - } - } - } - _buildBlock(state) { - super._buildBlock(state); - // Register for defines - state.sharedData.blocksWithDefines.push(this); - // Register for binding - state.sharedData.bindableBlocks.push(this); - // Register for repeatable content generation - state.sharedData.repeatableContentBlocks.push(this); - // Emit code - const position = this.position; - const normal = this.normal; - const tangent = this.tangent; - const uv = this.uv; - const positionOutput = this.positionOutput; - const normalOutput = this.normalOutput; - const tangentOutput = this.tangentOutput; - const uvOutput = this.uvOutput; - const comments = `//${this.name}`; - state.uniforms.push("morphTargetInfluences"); - state.uniforms.push("morphTargetTextureInfo"); - state.uniforms.push("morphTargetTextureIndices"); - state.samplers.push("morphTargets"); - state._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration", comments); - state._emitFunctionFromInclude("morphTargetsVertexDeclaration", comments, { - repeatKey: "maxSimultaneousMorphTargets", - }); - state.compilationString += `${this._declareOutput(positionOutput, state)} = ${position.associatedVariableName};\n`; - state.compilationString += `#ifdef NORMAL\n`; - state.compilationString += `${this._declareOutput(normalOutput, state)} = ${normal.associatedVariableName};\n`; - state.compilationString += `#else\n`; - state.compilationString += `${this._declareOutput(normalOutput, state)} = vec3(0., 0., 0.);\n`; - state.compilationString += `#endif\n`; - state.compilationString += `#ifdef TANGENT\n`; - state.compilationString += `${this._declareOutput(tangentOutput, state)} = ${tangent.associatedVariableName};\n`; - state.compilationString += `#else\n`; - state.compilationString += `${this._declareOutput(tangentOutput, state)} = vec4(0., 0., 0., 0.);\n`; - state.compilationString += `#endif\n`; - state.compilationString += `#ifdef UV1\n`; - state.compilationString += `${this._declareOutput(uvOutput, state)} = ${uv.associatedVariableName};\n`; - state.compilationString += `#else\n`; - state.compilationString += `${this._declareOutput(uvOutput, state)} = vec2(0., 0.);\n`; - state.compilationString += `#endif\n`; - // Repeatable content - this._repeatableContentAnchor = state._repeatableContentAnchor; - state.compilationString += this._repeatableContentAnchor; - return this; - } -} -RegisterClass("BABYLON.MorphTargetsBlock", MorphTargetsBlock); -//# sourceMappingURL=morphTargetsBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/lightInformationBlock.js - - - - - -/** - * Block used to get data information from a light - */ -class LightInformationBlock extends NodeMaterialBlock { - /** - * Creates a new LightInformationBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Vertex); - this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); - this.registerOutput("direction", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerOutput("color", NodeMaterialBlockConnectionPointTypes.Color3); - this.registerOutput("intensity", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("shadowBias", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("shadowNormalBias", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("shadowDepthScale", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("shadowDepthRange", NodeMaterialBlockConnectionPointTypes.Vector2); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "LightInformationBlock"; - } - /** - * Gets the world position input component - */ - get worldPosition() { - return this._inputs[0]; - } - /** - * Gets the direction output component - */ - get direction() { - return this._outputs[0]; - } - /** - * Gets the direction output component - */ - get color() { - return this._outputs[1]; - } - /** - * Gets the direction output component - */ - get intensity() { - return this._outputs[2]; - } - /** - * Gets the shadow bias output component - */ - get shadowBias() { - return this._outputs[3]; - } - /** - * Gets the shadow normal bias output component - */ - get shadowNormalBias() { - return this._outputs[4]; - } - /** - * Gets the shadow depth scale component - */ - get shadowDepthScale() { - return this._outputs[5]; - } - /** - * Gets the shadow depth range component - */ - get shadowDepthRange() { - return this._outputs[6]; - } - bind(effect, nodeMaterial, mesh) { - if (!mesh) { - return; - } - if (this.light && this.light.isDisposed()) { - this.light = null; - } - let light = this.light; - const scene = nodeMaterial.getScene(); - if (!light && scene.lights.length) { - light = this.light = scene.lights[0]; - this._forcePrepareDefines = true; - } - if (!light || !light.isEnabled) { - effect.setFloat3(this._lightDataUniformName, 0, 0, 0); - effect.setFloat4(this._lightColorUniformName, 0, 0, 0, 0); - return; - } - light.transferToNodeMaterialEffect(effect, this._lightDataUniformName); - effect.setColor4(this._lightColorUniformName, light.diffuse, light.intensity); - const generator = light.getShadowGenerator(); - if (this.shadowBias.hasEndpoints || this.shadowNormalBias.hasEndpoints || this.shadowDepthScale.hasEndpoints) { - if (generator) { - effect.setFloat3(this._lightShadowUniformName, generator.bias, generator.normalBias, generator.depthScale); - } - else { - effect.setFloat3(this._lightShadowUniformName, 0, 0, 0); - } - } - if (this.shadowDepthRange) { - if (generator && scene.activeCamera) { - const shadowLight = light; - effect.setFloat2(this._lightShadowExtraUniformName, shadowLight.getDepthMinZ(scene.activeCamera), shadowLight.getDepthMinZ(scene.activeCamera) + shadowLight.getDepthMaxZ(scene.activeCamera)); - } - else { - effect.setFloat2(this._lightShadowExtraUniformName, 0, 0); - } - } - } - prepareDefines(mesh, nodeMaterial, defines) { - if (!defines._areLightsDirty && !this._forcePrepareDefines) { - return; - } - this._forcePrepareDefines = false; - const light = this.light; - defines.setValue(this._lightTypeDefineName, light && light instanceof PointLight ? true : false, true); - } - _buildBlock(state) { - super._buildBlock(state); - state.sharedData.bindableBlocks.push(this); - state.sharedData.blocksWithDefines.push(this); - const direction = this.direction; - const color = this.color; - const intensity = this.intensity; - const shadowBias = this.shadowBias; - const shadowNormalBias = this.shadowNormalBias; - const shadowDepthScale = this.shadowDepthScale; - const shadowDepthRange = this.shadowDepthRange; - this._lightDataUniformName = state._getFreeVariableName("lightData"); - this._lightColorUniformName = state._getFreeVariableName("lightColor"); - this._lightShadowUniformName = state._getFreeVariableName("shadowData"); - this._lightShadowExtraUniformName = state._getFreeVariableName("shadowExtraData"); - this._lightTypeDefineName = state._getFreeDefineName("LIGHTPOINTTYPE"); - state._emitUniformFromString(this._lightDataUniformName, "vec3"); - state._emitUniformFromString(this._lightColorUniformName, "vec4"); - state.compilationString += `#ifdef ${this._lightTypeDefineName}\n`; - state.compilationString += this._declareOutput(direction, state) + ` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName});\n`; - state.compilationString += `#else\n`; - state.compilationString += this._declareOutput(direction, state) + ` = ${this._lightDataUniformName};\n`; - state.compilationString += `#endif\n`; - state.compilationString += this._declareOutput(color, state) + ` = ${this._lightColorUniformName}.rgb;\n`; - state.compilationString += this._declareOutput(intensity, state) + ` = ${this._lightColorUniformName}.a;\n`; - if (shadowBias.hasEndpoints || shadowNormalBias.hasEndpoints || shadowDepthScale.hasEndpoints) { - state._emitUniformFromString(this._lightShadowUniformName, "vec3"); - if (shadowBias.hasEndpoints) { - state.compilationString += this._declareOutput(shadowBias, state) + ` = ${this._lightShadowUniformName}.x;\n`; - } - if (shadowNormalBias.hasEndpoints) { - state.compilationString += this._declareOutput(shadowNormalBias, state) + ` = ${this._lightShadowUniformName}.y;\n`; - } - if (shadowDepthScale.hasEndpoints) { - state.compilationString += this._declareOutput(shadowDepthScale, state) + ` = ${this._lightShadowUniformName}.z;\n`; - } - } - if (shadowDepthRange.hasEndpoints) { - state._emitUniformFromString(this._lightShadowExtraUniformName, "vec2"); - state.compilationString += this._declareOutput(shadowDepthRange, state) + ` = ${this._lightShadowUniformName};\n`; - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - if (this.light) { - serializationObject.lightId = this.light.id; - } - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - if (serializationObject.lightId) { - this.light = scene.getLightById(serializationObject.lightId); - } - } -} -RegisterClass("BABYLON.LightInformationBlock", LightInformationBlock); -//# sourceMappingURL=lightInformationBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/index.js - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/imageProcessingBlock.js - - - - - - - - - -/** - * Block used to add image processing support to fragment shader - */ -class ImageProcessingBlock extends NodeMaterialBlock { - /** - * Create a new ImageProcessingBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - /** - * Defines if the input should be converted to linear space (default: true) - */ - this.convertInputToLinearSpace = true; - this.registerInput("color", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color4); - this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | - NodeMaterialBlockConnectionPointTypes.Color4 | - NodeMaterialBlockConnectionPointTypes.Vector3 | - NodeMaterialBlockConnectionPointTypes.Vector4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ImageProcessingBlock"; - } - /** - * Gets the color input component - */ - get color() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets the rgb component - */ - get rgb() { - return this._outputs[1]; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("exposureLinear"); - state._excludeVariableName("contrast"); - state._excludeVariableName("vInverseScreenSize"); - state._excludeVariableName("vignetteSettings1"); - state._excludeVariableName("vignetteSettings2"); - state._excludeVariableName("vCameraColorCurveNegative"); - state._excludeVariableName("vCameraColorCurveNeutral"); - state._excludeVariableName("vCameraColorCurvePositive"); - state._excludeVariableName("txColorTransform"); - state._excludeVariableName("colorTransformSettings"); - state._excludeVariableName("ditherIntensity"); - } - isReady(mesh, nodeMaterial, defines) { - if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) { - if (!nodeMaterial.imageProcessingConfiguration.isReady()) { - return false; - } - } - return true; - } - prepareDefines(mesh, nodeMaterial, defines) { - if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) { - nodeMaterial.imageProcessingConfiguration.prepareDefines(defines); - } - } - bind(effect, nodeMaterial, mesh) { - if (!mesh) { - return; - } - if (!nodeMaterial.imageProcessingConfiguration) { - return; - } - nodeMaterial.imageProcessingConfiguration.bind(effect); - } - _buildBlock(state) { - var _a; - super._buildBlock(state); - // Register for defines - state.sharedData.blocksWithDefines.push(this); - // Register for blocking - state.sharedData.blockingBlocks.push(this); - // Register for binding - state.sharedData.bindableBlocks.push(this); - // Uniforms - state.uniforms.push("exposureLinear"); - state.uniforms.push("contrast"); - state.uniforms.push("vInverseScreenSize"); - state.uniforms.push("vignetteSettings1"); - state.uniforms.push("vignetteSettings2"); - state.uniforms.push("vCameraColorCurveNegative"); - state.uniforms.push("vCameraColorCurveNeutral"); - state.uniforms.push("vCameraColorCurvePositive"); - state.uniforms.push("txColorTransform"); - state.uniforms.push("colorTransformSettings"); - state.uniforms.push("ditherIntensity"); - // Emit code - const color = this.color; - const output = this._outputs[0]; - const comments = `//${this.name}`; - state._emitFunctionFromInclude("helperFunctions", comments); - state._emitFunctionFromInclude("imageProcessingDeclaration", comments); - state._emitFunctionFromInclude("imageProcessingFunctions", comments); - if ((_a = color.connectedPoint) === null || _a === void 0 ? void 0 : _a.isConnected) { - if (color.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Color4 || color.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4) { - state.compilationString += `${this._declareOutput(output, state)} = ${color.associatedVariableName};\n`; - } - else { - state.compilationString += `${this._declareOutput(output, state)} = vec4(${color.associatedVariableName}, 1.0);\n`; - } - state.compilationString += `#ifdef IMAGEPROCESSINGPOSTPROCESS\n`; - if (this.convertInputToLinearSpace) { - state.compilationString += `${output.associatedVariableName}.rgb = toLinearSpace(${color.associatedVariableName}.rgb);\n`; - } - state.compilationString += `#else\n`; - state.compilationString += `#ifdef IMAGEPROCESSING\n`; - if (this.convertInputToLinearSpace) { - state.compilationString += `${output.associatedVariableName}.rgb = toLinearSpace(${color.associatedVariableName}.rgb);\n`; - } - state.compilationString += `${output.associatedVariableName} = applyImageProcessing(${output.associatedVariableName});\n`; - state.compilationString += `#endif\n`; - state.compilationString += `#endif\n`; - if (this.rgb.hasEndpoints) { - state.compilationString += this._declareOutput(this.rgb, state) + ` = ${this.output.associatedVariableName}.xyz;\n`; - } - } - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.convertInputToLinearSpace = this.convertInputToLinearSpace; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - var _a; - super._deserialize(serializationObject, scene, rootUrl); - this.convertInputToLinearSpace = (_a = serializationObject.convertInputToLinearSpace) !== null && _a !== void 0 ? _a : true; - } -} -__decorate([ - editableInPropertyPage("Convert input to linear space", PropertyTypeForEdition.Boolean, "ADVANCED") -], ImageProcessingBlock.prototype, "convertInputToLinearSpace", void 0); -RegisterClass("BABYLON.ImageProcessingBlock", ImageProcessingBlock); -//# sourceMappingURL=imageProcessingBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/TBNBlock.js - - - - - - - - -/** - * Block used to implement TBN matrix - */ -class TBNBlock extends NodeMaterialBlock { - /** - * Create a new TBNBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment, true); - this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect, false); - this.normal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerInput("tangent", NodeMaterialBlockConnectionPointTypes.Vector4, false); - this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false); - this.registerOutput("TBN", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("TBN", this, NodeMaterialConnectionPointDirection.Output, TBNBlock, "TBNBlock")); - this.registerOutput("row0", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("row1", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("row2", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "TBNBlock"; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("tbnNormal"); - state._excludeVariableName("tbnTangent"); - state._excludeVariableName("tbnBitangent"); - state._excludeVariableName("TBN"); - } - /** - * Gets the normal input component - */ - get normal() { - return this._inputs[0]; - } - /** - * Gets the tangent input component - */ - get tangent() { - return this._inputs[1]; - } - /** - * Gets the world matrix input component - */ - get world() { - return this._inputs[2]; - } - /** - * Gets the TBN output component - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - get TBN() { - return this._outputs[0]; - } - /** - * Gets the row0 of the output matrix - */ - get row0() { - return this._outputs[1]; - } - /** - * Gets the row1 of the output matrix - */ - get row1() { - return this._outputs[2]; - } - /** - * Gets the row2 of the output matrix - */ - get row2() { - return this._outputs[3]; - } - get target() { - return NodeMaterialBlockTargets.Fragment; - } - set target(value) { } - autoConfigure(material) { - if (!this.world.isConnected) { - let worldInput = material.getInputBlockByPredicate((b) => b.isSystemValue && b.systemValue === NodeMaterialSystemValues.World); - if (!worldInput) { - worldInput = new InputBlock("world"); - worldInput.setAsSystemValue(NodeMaterialSystemValues.World); - } - worldInput.output.connectTo(this.world); - } - if (!this.normal.isConnected) { - let normalInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "normal"); - if (!normalInput) { - normalInput = new InputBlock("normal"); - normalInput.setAsAttribute("normal"); - } - normalInput.output.connectTo(this.normal); - } - if (!this.tangent.isConnected) { - let tangentInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "tangent" && b.type === NodeMaterialBlockConnectionPointTypes.Vector4); - if (!tangentInput) { - tangentInput = new InputBlock("tangent"); - tangentInput.setAsAttribute("tangent"); - } - tangentInput.output.connectTo(this.tangent); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - var _a, _b, _c, _d; - const normal = this.normal; - const tangent = this.tangent; - let normalAvailable = normal.isConnected; - 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)) { - normalAvailable = false; - } - let tangentAvailable = tangent.isConnected; - 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)) { - tangentAvailable = false; - } - const useTBNBlock = normalAvailable && tangentAvailable; - defines.setValue("TBNBLOCK", useTBNBlock, true); - } - _buildBlock(state) { - super._buildBlock(state); - const normal = this.normal; - const tangent = this.tangent; - const world = this.world; - const TBN = this.TBN; - const row0 = this.row0; - const row1 = this.row1; - const row2 = this.row2; - // Fragment - if (state.target === NodeMaterialBlockTargets.Fragment) { - state.compilationString += ` - // ${this.name} - vec3 tbnNormal = normalize(${normal.associatedVariableName}).xyz; - vec3 tbnTangent = normalize(${tangent.associatedVariableName}.xyz); - vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${tangent.associatedVariableName}.w; - mat3 ${TBN.associatedVariableName} = mat3(${world.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); - `; - if (row0.hasEndpoints) { - state.compilationString += - this._declareOutput(row0, state) + ` = vec3(${TBN.associatedVariableName}[0][0], ${TBN.associatedVariableName}[0][1], ${TBN.associatedVariableName}[0][2]);\n`; - } - if (row1.hasEndpoints) { - state.compilationString += - this._declareOutput(row1, state) + ` = vec3(${TBN.associatedVariableName}[1[0], ${TBN.associatedVariableName}[1][1], ${TBN.associatedVariableName}[1][2]);\n`; - } - if (row2.hasEndpoints) { - state.compilationString += - this._declareOutput(row2, state) + ` = vec3(${TBN.associatedVariableName}[2][0], ${TBN.associatedVariableName}[2][1], ${TBN.associatedVariableName}[2][2]);\n`; - } - state.sharedData.blocksWithDefines.push(this); - } - return this; - } -} -RegisterClass("BABYLON.TBNBlock", TBNBlock); -//# sourceMappingURL=TBNBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/perturbNormalBlock.js - - - - - - - - - - - - - -/** - * Block used to perturb normals based on a normal map - */ -class PerturbNormalBlock extends NodeMaterialBlock { - /** - * Create a new PerturbNormalBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this._tangentSpaceParameterName = ""; - this._tangentCorrectionFactorName = ""; - this._worldMatrixName = ""; - /** Gets or sets a boolean indicating that normal should be inverted on X axis */ - this.invertX = false; - /** Gets or sets a boolean indicating that normal should be inverted on Y axis */ - this.invertY = false; - /** Gets or sets a boolean indicating that parallax occlusion should be enabled */ - this.useParallaxOcclusion = false; - /** Gets or sets a boolean indicating that sampling mode is in Object space */ - this.useObjectSpaceNormalMap = false; - this._isUnique = true; - // Vertex - this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false); - this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false); - this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, true); - this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, false); - this.registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes.Color3, false); - this.registerInput("strength", NodeMaterialBlockConnectionPointTypes.Float, false); - this.registerInput("viewDirection", NodeMaterialBlockConnectionPointTypes.Vector3, true); - this.registerInput("parallaxScale", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("parallaxHeight", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("TBN", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("TBN", this, NodeMaterialConnectionPointDirection.Input, TBNBlock, "TBNBlock")); - this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, true); - // Fragment - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerOutput("uvOffset", NodeMaterialBlockConnectionPointTypes.Vector2); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "PerturbNormalBlock"; - } - /** - * Gets the world position input component - */ - get worldPosition() { - return this._inputs[0]; - } - /** - * Gets the world normal input component - */ - get worldNormal() { - return this._inputs[1]; - } - /** - * Gets the world tangent input component - */ - get worldTangent() { - return this._inputs[2]; - } - /** - * Gets the uv input component - */ - get uv() { - return this._inputs[3]; - } - /** - * Gets the normal map color input component - */ - get normalMapColor() { - return this._inputs[4]; - } - /** - * Gets the strength input component - */ - get strength() { - return this._inputs[5]; - } - /** - * Gets the view direction input component - */ - get viewDirection() { - return this._inputs[6]; - } - /** - * Gets the parallax scale input component - */ - get parallaxScale() { - return this._inputs[7]; - } - /** - * Gets the parallax height input component - */ - get parallaxHeight() { - return this._inputs[8]; - } - /** - * Gets the TBN input component - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - get TBN() { - return this._inputs[9]; - } - /** - * Gets the World input component - */ - get world() { - return this._inputs[10]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets the uv offset output component - */ - get uvOffset() { - return this._outputs[1]; - } - prepareDefines(mesh, nodeMaterial, defines) { - const normalSamplerName = this.normalMapColor.connectedPoint._ownerBlock.samplerName; - const useParallax = this.viewDirection.isConnected && ((this.useParallaxOcclusion && normalSamplerName) || (!this.useParallaxOcclusion && this.parallaxHeight.isConnected)); - defines.setValue("BUMP", true); - defines.setValue("PARALLAX", useParallax, true); - defines.setValue("PARALLAXOCCLUSION", this.useParallaxOcclusion, true); - defines.setValue("OBJECTSPACE_NORMALMAP", this.useObjectSpaceNormalMap, true); - } - bind(effect, nodeMaterial, mesh) { - if (nodeMaterial.getScene()._mirroredCameraPosition) { - effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? 1.0 : -1.0, this.invertY ? 1.0 : -1.0); - } - else { - effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? -1.0 : 1.0, this.invertY ? -1.0 : 1.0); - } - if (mesh) { - effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1); - if (this.useObjectSpaceNormalMap && !this.world.isConnected) { - // World default to the mesh world matrix - effect.setMatrix(this._worldMatrixName, mesh.getWorldMatrix()); - } - } - } - autoConfigure(material) { - if (!this.uv.isConnected) { - let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "uv"); - if (!uvInput) { - uvInput = new InputBlock("uv"); - uvInput.setAsAttribute(); - } - uvInput.output.connectTo(this.uv); - } - if (!this.strength.isConnected) { - const strengthInput = new InputBlock("strength"); - strengthInput.value = 1.0; - strengthInput.output.connectTo(this.strength); - } - } - _buildBlock(state) { - super._buildBlock(state); - const comments = `//${this.name}`; - const uv = this.uv; - const worldPosition = this.worldPosition; - const worldNormal = this.worldNormal; - const worldTangent = this.worldTangent; - state.sharedData.blocksWithDefines.push(this); - state.sharedData.bindableBlocks.push(this); - this._tangentSpaceParameterName = state._getFreeDefineName("tangentSpaceParameter"); - state._emitUniformFromString(this._tangentSpaceParameterName, "vec2"); - this._tangentCorrectionFactorName = state._getFreeDefineName("tangentCorrectionFactor"); - state._emitUniformFromString(this._tangentCorrectionFactorName, "float"); - this._worldMatrixName = state._getFreeDefineName("perturbNormalWorldMatrix"); - state._emitUniformFromString(this._worldMatrixName, "mat4"); - let normalSamplerName = null; - if (this.normalMapColor.connectedPoint) { - normalSamplerName = this.normalMapColor.connectedPoint._ownerBlock.samplerName; - } - const useParallax = this.viewDirection.isConnected && ((this.useParallaxOcclusion && normalSamplerName) || (!this.useParallaxOcclusion && this.parallaxHeight.isConnected)); - const replaceForParallaxInfos = !this.parallaxScale.isConnectedToInputBlock - ? "0.05" - : this.parallaxScale.connectInputBlock.isConstant - ? state._emitFloat(this.parallaxScale.connectInputBlock.value) - : this.parallaxScale.associatedVariableName; - const replaceForBumpInfos = this.strength.isConnectedToInputBlock && this.strength.connectInputBlock.isConstant - ? `\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${state._emitFloat(this.strength.connectInputBlock.value)}` - : `\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${this.strength.associatedVariableName}`; - state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); - const tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" }; - const tbnVarying = { search: /varying mat3 vTBN;/g, replace: "" }; - const normalMatrixReplaceString = { search: /uniform mat4 normalMatrix;/g, replace: "" }; - const TBN = this.TBN; - if (TBN.isConnected) { - state.compilationString += ` - #ifdef TBNBLOCK - mat3 vTBN = ${TBN.associatedVariableName}; - #endif - `; - } - else if (worldTangent.isConnected) { - state.compilationString += `vec3 tbnNormal = normalize(${worldNormal.associatedVariableName}.xyz);\n`; - state.compilationString += `vec3 tbnTangent = normalize(${worldTangent.associatedVariableName}.xyz);\n`; - state.compilationString += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`; - state.compilationString += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\n`; - } - state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, { - replaceStrings: [tangentReplaceString, tbnVarying, normalMatrixReplaceString], - }); - state._emitFunctionFromInclude("bumpFragmentFunctions", comments, { - replaceStrings: [ - { search: /#include<samplerFragmentDeclaration>\(_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\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 uvForPerturbNormal = !useParallax || !normalSamplerName ? this.normalMapColor.associatedVariableName : `texture2D(${normalSamplerName}, ${uv.associatedVariableName} + uvOffset).xyz`; - state.compilationString += this._declareOutput(this.output, state) + " = vec4(0.);\n"; - state.compilationString += state._emitCodeFromInclude("bumpFragment", comments, { - replaceStrings: [ - { search: /texture2D\(bumpSampler,vBumpUV\)/g, replace: `${uvForPerturbNormal}` }, - { - 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, ${uvForPerturbNormal}, vBumpInfos.y)` }, - { - search: /parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g, - replace: `parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${useParallax && this.useParallaxOcclusion ? normalSamplerName : "bumpSampler"})`, - }, - { - search: /parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g, - replace: `parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${useParallax ? this.parallaxHeight.associatedVariableName : "0."})`, - }, - { search: /vTangentSpaceParams/g, replace: this._tangentSpaceParameterName }, - { search: /vBumpInfos.y/g, replace: replaceForBumpInfos }, - { search: /vBumpInfos.z/g, replace: replaceForParallaxInfos }, - { search: /vBumpUV/g, replace: uv.associatedVariableName }, - { search: /vPositionW/g, replace: worldPosition.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: worldNormal.associatedVariableName + ".xyz" }, - { search: /viewDirectionW/g, replace: useParallax ? this.viewDirection.associatedVariableName : "vec3(0.)" }, - tangentReplaceString, - ], - }); - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.invertX = ${this.invertX};\n`; - codeString += `${this._codeVariableName}.invertY = ${this.invertY};\n`; - codeString += `${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\n`; - codeString += `${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.invertX = this.invertX; - serializationObject.invertY = this.invertY; - serializationObject.useParallaxOcclusion = this.useParallaxOcclusion; - serializationObject.useObjectSpaceNormalMap = this.useObjectSpaceNormalMap; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.invertX = serializationObject.invertX; - this.invertY = serializationObject.invertY; - this.useParallaxOcclusion = !!serializationObject.useParallaxOcclusion; - this.useObjectSpaceNormalMap = !!serializationObject.useObjectSpaceNormalMap; - } -} -__decorate([ - editableInPropertyPage("Invert X axis", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: false } }) -], PerturbNormalBlock.prototype, "invertX", void 0); -__decorate([ - editableInPropertyPage("Invert Y axis", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: false } }) -], PerturbNormalBlock.prototype, "invertY", void 0); -__decorate([ - editableInPropertyPage("Use parallax occlusion", PropertyTypeForEdition.Boolean) -], PerturbNormalBlock.prototype, "useParallaxOcclusion", void 0); -__decorate([ - editableInPropertyPage("Object Space Mode", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: false } }) -], PerturbNormalBlock.prototype, "useObjectSpaceNormalMap", void 0); -RegisterClass("BABYLON.PerturbNormalBlock", PerturbNormalBlock); -//# sourceMappingURL=perturbNormalBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/discardBlock.js - - - - -/** - * Block used to discard a pixel if a value is smaller than a cutoff - */ -class DiscardBlock extends NodeMaterialBlock { - /** - * Create a new DiscardBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment, true); - this.registerInput("value", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("cutoff", NodeMaterialBlockConnectionPointTypes.Float, true); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "DiscardBlock"; - } - /** - * Gets the color input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the cutoff input component - */ - get cutoff() { - return this._inputs[1]; - } - _buildBlock(state) { - super._buildBlock(state); - state.sharedData.hints.needAlphaTesting = true; - if (!this.cutoff.isConnected || !this.value.isConnected) { - return; - } - state.compilationString += `if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard;\n`; - return this; - } -} -RegisterClass("BABYLON.DiscardBlock", DiscardBlock); -//# sourceMappingURL=discardBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/frontFacingBlock.js - - - - -/** - * Block used to test if the fragment shader is front facing - */ -class FrontFacingBlock extends NodeMaterialBlock { - /** - * Creates a new FrontFacingBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "FrontFacingBlock"; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - if (state.target === NodeMaterialBlockTargets.Vertex) { - throw "FrontFacingBlock must only be used in a fragment shader"; - } - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = gl_FrontFacing ? 1.0 : 0.0;\n`; - return this; - } -} -RegisterClass("BABYLON.FrontFacingBlock", FrontFacingBlock); -//# sourceMappingURL=frontFacingBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/derivativeBlock.js - - - - -/** - * Block used to get the derivative value on x and y of a given input - */ -class DerivativeBlock extends NodeMaterialBlock { - /** - * Create a new DerivativeBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect, false); - this.registerOutput("dx", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this.registerOutput("dy", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._outputs[1]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "DerivativeBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the derivative output on x - */ - get dx() { - return this._outputs[0]; - } - /** - * Gets the derivative output on y - */ - get dy() { - return this._outputs[1]; - } - _buildBlock(state) { - super._buildBlock(state); - const dx = this._outputs[0]; - const dy = this._outputs[1]; - state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); - if (dx.hasEndpoints) { - state.compilationString += this._declareOutput(dx, state) + ` = dFdx(${this.input.associatedVariableName});\n`; - } - if (dy.hasEndpoints) { - state.compilationString += this._declareOutput(dy, state) + ` = dFdy(${this.input.associatedVariableName});\n`; - } - return this; - } -} -RegisterClass("BABYLON.DerivativeBlock", DerivativeBlock); -//# sourceMappingURL=derivativeBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragCoordBlock.js - - - - -/** - * Block used to make gl_FragCoord available - */ -class FragCoordBlock extends NodeMaterialBlock { - /** - * Creates a new FragCoordBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment); - this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockTargets.Fragment); - this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - this.registerOutput("z", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - this.registerOutput("w", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "FragCoordBlock"; - } - /** - * Gets the xy component - */ - get xy() { - return this._outputs[0]; - } - /** - * Gets the xyz component - */ - get xyz() { - return this._outputs[1]; - } - /** - * Gets the xyzw component - */ - get xyzw() { - return this._outputs[2]; - } - /** - * Gets the x component - */ - get x() { - return this._outputs[3]; - } - /** - * Gets the y component - */ - get y() { - return this._outputs[4]; - } - /** - * Gets the z component - */ - get z() { - return this._outputs[5]; - } - /** - * Gets the w component - */ - get output() { - return this._outputs[6]; - } - // eslint-disable-next-line @typescript-eslint/naming-convention - writeOutputs(state) { - let code = ""; - for (const output of this._outputs) { - if (output.hasEndpoints) { - code += `${this._declareOutput(output, state)} = gl_FragCoord.${output.name};\n`; - } - } - return code; - } - _buildBlock(state) { - super._buildBlock(state); - if (state.target === NodeMaterialBlockTargets.Vertex) { - throw "FragCoordBlock must only be used in a fragment shader"; - } - state.compilationString += this.writeOutputs(state); - return this; - } -} -RegisterClass("BABYLON.FragCoordBlock", FragCoordBlock); -//# sourceMappingURL=fragCoordBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/screenSizeBlock.js - - - - -/** - * Block used to get the screen sizes - */ -class ScreenSizeBlock extends NodeMaterialBlock { - /** - * Creates a new ScreenSizeBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment); - this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ScreenSizeBlock"; - } - /** - * Gets the xy component - */ - get xy() { - return this._outputs[0]; - } - /** - * Gets the x component - */ - get x() { - return this._outputs[1]; - } - /** - * Gets the y component - */ - get y() { - return this._outputs[2]; - } - bind(effect) { - const engine = this._scene.getEngine(); - effect.setFloat2(this._varName, engine.getRenderWidth(), engine.getRenderHeight()); - } - // eslint-disable-next-line @typescript-eslint/naming-convention - writeOutputs(state, varName) { - let code = ""; - for (const output of this._outputs) { - if (output.hasEndpoints) { - code += `${this._declareOutput(output, state)} = ${varName}.${output.name};\n`; - } - } - return code; - } - _buildBlock(state) { - super._buildBlock(state); - this._scene = state.sharedData.scene; - if (state.target === NodeMaterialBlockTargets.Vertex) { - throw "ScreenSizeBlock must only be used in a fragment shader"; - } - state.sharedData.bindableBlocks.push(this); - this._varName = state._getFreeVariableName("screenSize"); - state._emitUniformFromString(this._varName, "vec2"); - state.compilationString += this.writeOutputs(state, this._varName); - return this; - } -} -RegisterClass("BABYLON.ScreenSizeBlock", ScreenSizeBlock); -//# sourceMappingURL=screenSizeBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/screenSpaceBlock.js - - - - - - -/** - * Block used to transform a vector3 or a vector4 into screen space - */ -class ScreenSpaceBlock extends NodeMaterialBlock { - /** - * Creates a new ScreenSpaceBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this.registerInput("vector", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("worldViewProjection", NodeMaterialBlockConnectionPointTypes.Matrix); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float); - this.inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ScreenSpaceBlock"; - } - /** - * Gets the vector input - */ - get vector() { - return this._inputs[0]; - } - /** - * Gets the worldViewProjection transform input - */ - get worldViewProjection() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets the x output component - */ - get x() { - return this._outputs[1]; - } - /** - * Gets the y output component - */ - get y() { - return this._outputs[2]; - } - autoConfigure(material) { - if (!this.worldViewProjection.isConnected) { - let worldViewProjectionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.WorldViewProjection); - if (!worldViewProjectionInput) { - worldViewProjectionInput = new InputBlock("worldViewProjection"); - worldViewProjectionInput.setAsSystemValue(NodeMaterialSystemValues.WorldViewProjection); - } - worldViewProjectionInput.output.connectTo(this.worldViewProjection); - } - } - _buildBlock(state) { - super._buildBlock(state); - const vector = this.vector; - const worldViewProjection = this.worldViewProjection; - if (!vector.connectedPoint) { - return; - } - const worldViewProjectionName = worldViewProjection.associatedVariableName; - const tempVariableName = state._getFreeVariableName("screenSpaceTemp"); - switch (vector.connectedPoint.type) { - case NodeMaterialBlockConnectionPointTypes.Vector3: - state.compilationString += `vec4 ${tempVariableName} = ${worldViewProjectionName} * vec4(${vector.associatedVariableName}, 1.0);\n`; - break; - case NodeMaterialBlockConnectionPointTypes.Vector4: - state.compilationString += `vec4 ${tempVariableName} = ${worldViewProjectionName} * ${vector.associatedVariableName};\n`; - break; - } - state.compilationString += `${tempVariableName}.xy /= ${tempVariableName}.w;`; - state.compilationString += `${tempVariableName}.xy = ${tempVariableName}.xy * 0.5 + vec2(0.5, 0.5);`; - if (this.output.hasEndpoints) { - state.compilationString += this._declareOutput(this.output, state) + ` = ${tempVariableName}.xy;\n`; - } - if (this.x.hasEndpoints) { - state.compilationString += this._declareOutput(this.x, state) + ` = ${tempVariableName}.x;\n`; - } - if (this.y.hasEndpoints) { - state.compilationString += this._declareOutput(this.y, state) + ` = ${tempVariableName}.y;\n`; - } - return this; - } -} -RegisterClass("BABYLON.ScreenSpaceBlock", ScreenSpaceBlock); -//# sourceMappingURL=screenSpaceBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/twirlBlock.js - - - - - - -/** - * Block used to generate a twirl - */ -class TwirlBlock extends NodeMaterialBlock { - /** - * Creates a new TwirlBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerInput("strength", NodeMaterialBlockConnectionPointTypes.Float); - this.registerInput("center", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerInput("offset", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "TwirlBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the strength component - */ - get strength() { - return this._inputs[1]; - } - /** - * Gets the center component - */ - get center() { - return this._inputs[2]; - } - /** - * Gets the offset component - */ - get offset() { - return this._inputs[3]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets the x output component - */ - get x() { - return this._outputs[1]; - } - /** - * Gets the y output component - */ - get y() { - return this._outputs[2]; - } - autoConfigure() { - if (!this.center.isConnected) { - const centerInput = new InputBlock("center"); - centerInput.value = new math_vector_Vector2(0.5, 0.5); - centerInput.output.connectTo(this.center); - } - if (!this.strength.isConnected) { - const strengthInput = new InputBlock("strength"); - strengthInput.value = 1.0; - strengthInput.output.connectTo(this.strength); - } - if (!this.offset.isConnected) { - const offsetInput = new InputBlock("offset"); - offsetInput.value = new math_vector_Vector2(0, 0); - offsetInput.output.connectTo(this.offset); - } - } - _buildBlock(state) { - super._buildBlock(state); - const tempDelta = state._getFreeVariableName("delta"); - const tempAngle = state._getFreeVariableName("angle"); - const tempX = state._getFreeVariableName("x"); - const tempY = state._getFreeVariableName("y"); - const tempResult = state._getFreeVariableName("result"); - state.compilationString += ` - vec2 ${tempDelta} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; - float ${tempAngle} = ${this.strength.associatedVariableName} * length(${tempDelta}); - float ${tempX} = cos(${tempAngle}) * ${tempDelta}.x - sin(${tempAngle}) * ${tempDelta}.y; - float ${tempY} = sin(${tempAngle}) * ${tempDelta}.x + cos(${tempAngle}) * ${tempDelta}.y; - vec2 ${tempResult} = vec2(${tempX} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${tempY} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); - `; - if (this.output.hasEndpoints) { - state.compilationString += this._declareOutput(this.output, state) + ` = ${tempResult};\n`; - } - if (this.x.hasEndpoints) { - state.compilationString += this._declareOutput(this.x, state) + ` = ${tempResult}.x;\n`; - } - if (this.y.hasEndpoints) { - state.compilationString += this._declareOutput(this.y, state) + ` = ${tempResult}.y;\n`; - } - return this; - } -} -RegisterClass("BABYLON.TwirlBlock", TwirlBlock); -//# sourceMappingURL=twirlBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/heightToNormalBlock.js - - - - - - -/** - * Block used to convert a height vector to a normal - */ -class HeightToNormalBlock extends NodeMaterialBlock { - /** - * Creates a new HeightToNormalBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - /** - * Defines if the output should be generated in world or tangent space. - * 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 - */ - this.generateInWorldSpace = false; - /** - * Defines that the worldNormal input will be normalized by the HeightToNormal block before being used - */ - this.automaticNormalizationNormal = true; - /** - * Defines that the worldTangent input will be normalized by the HeightToNormal block before being used - */ - this.automaticNormalizationTangent = true; - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Float); - this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3); - this._inputs[3].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "HeightToNormalBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the position component - */ - get worldPosition() { - return this._inputs[1]; - } - /** - * Gets the normal component - */ - get worldNormal() { - return this._inputs[2]; - } - /** - * Gets the tangent component - */ - get worldTangent() { - return this._inputs[3]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets the xyz component - */ - get xyz() { - return this._outputs[1]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - if (!this.generateInWorldSpace && !this.worldTangent.isConnected) { - console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`); - } - const startCode = this.generateInWorldSpace - ? "" - : ` - vec3 biTangent = cross(normal, tangent); - mat3 TBN = mat3(tangent, biTangent, normal); - `; - const endCode = this.generateInWorldSpace - ? "" - : ` - result = TBN * result; - result = result * vec3(0.5) + vec3(0.5); - `; - const heightToNormal = ` - vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { - ${startCode} - ${this.automaticNormalizationTangent ? "tangent = normalize(tangent);" : ""} - ${this.automaticNormalizationNormal ? "normal = normalize(normal);" : ""} - vec3 worlddX = dFdx(position); - vec3 worlddY = dFdy(position); - vec3 crossX = cross(normal, worlddX); - vec3 crossY = cross(normal, worlddY); - float d = abs(dot(crossY, worlddX)); - vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); - inToNormal.y *= -1.0; - vec3 result = normalize((d * normal) - inToNormal); - ${endCode} - return vec4(result, 0.); - }`; - state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); - state._emitFunction("heightToNormal", heightToNormal, "// heightToNormal"); - state.compilationString += - this._declareOutput(output, state) + - ` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected ? this.worldTangent.associatedVariableName : "vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName});\n`; - if (this.xyz.hasEndpoints) { - state.compilationString += this._declareOutput(this.xyz, state) + ` = ${this.output.associatedVariableName}.xyz;\n`; - } - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\n`; - codeString += `${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\n`; - codeString += `${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.generateInWorldSpace = this.generateInWorldSpace; - serializationObject.automaticNormalizationNormal = this.automaticNormalizationNormal; - serializationObject.automaticNormalizationTangent = this.automaticNormalizationTangent; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.generateInWorldSpace = serializationObject.generateInWorldSpace; - this.automaticNormalizationNormal = serializationObject.automaticNormalizationNormal; - this.automaticNormalizationTangent = serializationObject.automaticNormalizationTangent; - } -} -__decorate([ - editableInPropertyPage("Generate in world space instead of tangent space", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: true } }) -], HeightToNormalBlock.prototype, "generateInWorldSpace", void 0); -__decorate([ - editableInPropertyPage("Force normalization for the worldNormal input", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: true } }) -], HeightToNormalBlock.prototype, "automaticNormalizationNormal", void 0); -__decorate([ - editableInPropertyPage("Force normalization for the worldTangent input", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: true } }) -], HeightToNormalBlock.prototype, "automaticNormalizationTangent", void 0); -RegisterClass("BABYLON.HeightToNormalBlock", HeightToNormalBlock); -//# sourceMappingURL=heightToNormalBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragDepthBlock.js - - - - -/** - * Block used to write the fragment depth - */ -class FragDepthBlock extends NodeMaterialBlock { - /** - * Create a new FragDepthBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment, true); - this.registerInput("depth", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("worldPos", NodeMaterialBlockConnectionPointTypes.Vector4, true); - this.registerInput("viewProjection", NodeMaterialBlockConnectionPointTypes.Matrix, true); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "FragDepthBlock"; - } - /** - * Gets the depth input component - */ - get depth() { - return this._inputs[0]; - } - /** - * Gets the worldPos input component - */ - get worldPos() { - return this._inputs[1]; - } - /** - * Gets the viewProjection input component - */ - get viewProjection() { - return this._inputs[2]; - } - _buildBlock(state) { - super._buildBlock(state); - if (this.depth.isConnected) { - state.compilationString += `gl_FragDepth = ${this.depth.associatedVariableName};\n`; - } - else if (this.worldPos.isConnected && this.viewProjection.isConnected) { - state.compilationString += ` - vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; - float v = p.z / p.w; - #ifndef IS_NDC_HALF_ZRANGE - v = v * 0.5 + 0.5; - #endif - gl_FragDepth = v; - - `; - } - else { - console.warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"); - } - return this; - } -} -RegisterClass("BABYLON.FragDepthBlock", FragDepthBlock); -//# sourceMappingURL=fragDepthBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/shadowMapBlock.js - - - - -/** - * Block used to output the depth to a shadow map - */ -class ShadowMapBlock extends NodeMaterialBlock { - /** - * Create a new ShadowMapBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false); - this.registerInput("viewProjection", NodeMaterialBlockConnectionPointTypes.Matrix, false); - this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); - this.registerOutput("depth", NodeMaterialBlockConnectionPointTypes.Vector3); - this.worldNormal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ShadowMapBlock"; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("vPositionWSM"); - state._excludeVariableName("lightDataSM"); - state._excludeVariableName("biasAndScaleSM"); - state._excludeVariableName("depthValuesSM"); - state._excludeVariableName("clipPos"); - state._excludeVariableName("worldPos"); - state._excludeVariableName("zSM"); - } - /** - * Gets the world position input component - */ - get worldPosition() { - return this._inputs[0]; - } - /** - * Gets the view x projection input component - */ - get viewProjection() { - return this._inputs[1]; - } - /** - * Gets the world normal input component - */ - get worldNormal() { - return this._inputs[2]; - } - /** - * Gets the depth output component - */ - get depth() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const comments = `//${this.name}`; - state._emitUniformFromString("biasAndScaleSM", "vec3"); - state._emitUniformFromString("lightDataSM", "vec3"); - state._emitUniformFromString("depthValuesSM", "vec2"); - state._emitFunctionFromInclude("packingFunctions", comments); - state.compilationString += `vec4 worldPos = ${this.worldPosition.associatedVariableName};\n`; - state.compilationString += `vec3 vPositionWSM;\n`; - state.compilationString += `float vDepthMetricSM = 0.0;\n`; - state.compilationString += `float zSM;\n`; - if (this.worldNormal.isConnected) { - state.compilationString += `vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\n`; - state.compilationString += state._emitCodeFromInclude("shadowMapVertexNormalBias", comments); - } - state.compilationString += `vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\n`; - state.compilationString += state._emitCodeFromInclude("shadowMapVertexMetric", comments, { - replaceStrings: [ - { - search: /gl_Position/g, - replace: "clipPos", - }, - ], - }); - state.compilationString += state._emitCodeFromInclude("shadowMapFragment", comments, { - replaceStrings: [ - { - search: /return;/g, - replace: "", - }, - ], - }); - state.compilationString += ` - #if SM_DEPTHTEXTURE == 1 - #ifdef IS_NDC_HALF_ZRANGE - gl_FragDepth = (clipPos.z / clipPos.w); - #else - gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5; - #endif - #endif - `; - state.compilationString += `${this._declareOutput(this.depth, state)} = vec3(depthSM, 1., 1.);\n`; - return this; - } -} -RegisterClass("BABYLON.ShadowMapBlock", ShadowMapBlock); -//# sourceMappingURL=shadowMapBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/index.js - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/fogBlock.js - - - - - - - - -/** - * Block used to add support for scene fog - */ -class FogBlock extends NodeMaterialBlock { - /** - * Create a new FogBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.VertexAndFragment, false); - // Vertex - this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); - this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex); - // Fragment - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("fogColor", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Fragment); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.input.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Color4); - this.fogColor.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Color4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "FogBlock"; - } - /** - * Gets the world position input component - */ - get worldPosition() { - return this._inputs[0]; - } - /** - * Gets the view input component - */ - get view() { - return this._inputs[1]; - } - /** - * Gets the color input component - */ - get input() { - return this._inputs[2]; - } - /** - * Gets the fog color input component - */ - get fogColor() { - return this._inputs[3]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - autoConfigure(material) { - if (!this.view.isConnected) { - let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View); - if (!viewInput) { - viewInput = new InputBlock("view"); - viewInput.setAsSystemValue(NodeMaterialSystemValues.View); - } - viewInput.output.connectTo(this.view); - } - if (!this.fogColor.isConnected) { - let fogColorInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.FogColor); - if (!fogColorInput) { - fogColorInput = new InputBlock("fogColor", undefined, NodeMaterialBlockConnectionPointTypes.Color3); - fogColorInput.setAsSystemValue(NodeMaterialSystemValues.FogColor); - } - fogColorInput.output.connectTo(this.fogColor); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - const scene = mesh.getScene(); - defines.setValue("FOG", nodeMaterial.fogEnabled && MaterialHelper.GetFogState(mesh, scene)); - } - bind(effect, nodeMaterial, mesh) { - if (!mesh) { - return; - } - const scene = mesh.getScene(); - effect.setFloat4(this._fogParameters, scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); - } - _buildBlock(state) { - super._buildBlock(state); - if (state.target === NodeMaterialBlockTargets.Fragment) { - state.sharedData.blocksWithDefines.push(this); - state.sharedData.bindableBlocks.push(this); - state._emitFunctionFromInclude("fogFragmentDeclaration", `//${this.name}`, { - removeUniforms: true, - removeVaryings: true, - removeIfDef: false, - replaceStrings: [{ search: /float CalcFogFactor\(\)/, replace: "float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)" }], - }); - const tempFogVariablename = state._getFreeVariableName("fog"); - const color = this.input; - const fogColor = this.fogColor; - this._fogParameters = state._getFreeVariableName("fogParameters"); - const output = this._outputs[0]; - state._emitUniformFromString(this._fogParameters, "vec4"); - state.compilationString += `#ifdef FOG\n`; - state.compilationString += `float ${tempFogVariablename} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters});\n`; - state.compilationString += - this._declareOutput(output, state) + - ` = ${tempFogVariablename} * ${color.associatedVariableName}.rgb + (1.0 - ${tempFogVariablename}) * ${fogColor.associatedVariableName}.rgb;\n`; - state.compilationString += `#else\n${this._declareOutput(output, state)} = ${color.associatedVariableName}.rgb;\n`; - state.compilationString += `#endif\n`; - } - else { - const worldPos = this.worldPosition; - const view = this.view; - this._fogDistanceName = state._getFreeVariableName("vFogDistance"); - state._emitVaryingFromString(this._fogDistanceName, "vec3"); - state.compilationString += `${this._fogDistanceName} = (${view.associatedVariableName} * ${worldPos.associatedVariableName}).xyz;\n`; - } - return this; - } -} -RegisterClass("BABYLON.FogBlock", FogBlock); -//# sourceMappingURL=fogBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/lightBlock.js - - - - - - - - - - - - - - - - - - -/** - * Block used to add light in the fragment shader - */ -class LightBlock extends NodeMaterialBlock { - static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) { - const that = block; - if (that.worldPosition.isConnected) { - that.generateOnlyFragmentCode = !that.generateOnlyFragmentCode; - console.error("The worldPosition input must not be connected to be able to switch!"); - return false; - } - that._setTarget(); - return true; - } - _setTarget() { - this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment); - this.getInputByName("worldPosition").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; - } - /** - * Create a new LightBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.VertexAndFragment); - this._lightId = 0; - /** 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) */ - this.generateOnlyFragmentCode = false; - this._isUnique = true; - this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); - this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("glossiness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("glossPower", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("diffuseColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("specularColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, true); - this.registerOutput("diffuseOutput", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("specularOutput", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("shadow", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "LightBlock"; - } - /** - * Gets the world position input component - */ - get worldPosition() { - return this._inputs[0]; - } - /** - * Gets the world normal input component - */ - get worldNormal() { - return this._inputs[1]; - } - /** - * Gets the camera (or eye) position component - */ - get cameraPosition() { - return this._inputs[2]; - } - /** - * Gets the glossiness component - */ - get glossiness() { - return this._inputs[3]; - } - /** - * Gets the glossiness power component - */ - get glossPower() { - return this._inputs[4]; - } - /** - * Gets the diffuse color component - */ - get diffuseColor() { - return this._inputs[5]; - } - /** - * Gets the specular color component - */ - get specularColor() { - return this._inputs[6]; - } - /** - * Gets the view matrix component - */ - get view() { - return this._inputs[7]; - } - /** - * Gets the diffuse output component - */ - get diffuseOutput() { - return this._outputs[0]; - } - /** - * Gets the specular output component - */ - get specularOutput() { - return this._outputs[1]; - } - /** - * Gets the shadow output component - */ - get shadow() { - return this._outputs[2]; - } - autoConfigure(material) { - if (!this.cameraPosition.isConnected) { - let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition); - if (!cameraPositionInput) { - cameraPositionInput = new InputBlock("cameraPosition"); - cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition); - } - cameraPositionInput.output.connectTo(this.cameraPosition); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - if (!defines._areLightsDirty) { - return; - } - const scene = mesh.getScene(); - if (!this.light) { - MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights); - } - else { - const state = { - needNormals: false, - needRebuild: false, - lightmapMode: false, - shadowEnabled: false, - specularEnabled: false, - }; - MaterialHelper.PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state); - if (state.needRebuild) { - defines.rebuild(); - } - } - } - updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) { - for (let lightIndex = 0; lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) { - if (!defines["LIGHT" + lightIndex]) { - break; - } - const onlyUpdateBuffersList = state.uniforms.indexOf("vLightData" + lightIndex) >= 0; - MaterialHelper.PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffers, onlyUpdateBuffersList); - } - } - bind(effect, nodeMaterial, mesh) { - if (!mesh) { - return; - } - const scene = mesh.getScene(); - if (!this.light) { - MaterialHelper.BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights); - } - else { - MaterialHelper.BindLight(this.light, this._lightId, scene, effect, true); - } - } - _injectVertexCode(state) { - const worldPos = this.worldPosition; - const comments = `//${this.name}`; - // Declaration - if (!this.light) { - // Emit for all lights - state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, { - repeatKey: "maxSimultaneousLights", - }); - this._lightId = 0; - state.sharedData.dynamicUniformBlocks.push(this); - } - else { - this._lightId = (state.counters["lightCounter"] !== undefined ? state.counters["lightCounter"] : -1) + 1; - state.counters["lightCounter"] = this._lightId; - state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, { - replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }], - }, this._lightId.toString()); - } - // Inject code in vertex - const worldPosVaryingName = "v_" + worldPos.associatedVariableName; - if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) { - state.compilationString += `${worldPosVaryingName} = ${worldPos.associatedVariableName};\n`; - } - if (this.light) { - state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { - replaceStrings: [ - { search: /{X}/g, replace: this._lightId.toString() }, - { search: /worldPos/g, replace: worldPos.associatedVariableName }, - ], - }); - } - else { - state.compilationString += `vec4 worldPos = ${worldPos.associatedVariableName};\n`; - if (this.view.isConnected) { - state.compilationString += `mat4 view = ${this.view.associatedVariableName};\n`; - } - state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { - repeatKey: "maxSimultaneousLights", - }); - } - } - _buildBlock(state) { - super._buildBlock(state); - if (state.target !== NodeMaterialBlockTargets.Fragment) { - // Vertex - this._injectVertexCode(state); - return; - } - if (this.generateOnlyFragmentCode) { - state.sharedData.dynamicUniformBlocks.push(this); - } - // Fragment - state.sharedData.forcedBindableBlocks.push(this); - state.sharedData.blocksWithDefines.push(this); - const comments = `//${this.name}`; - const worldPos = this.worldPosition; - let worldPosVariableName = worldPos.associatedVariableName; - if (this.generateOnlyFragmentCode) { - worldPosVariableName = state._getFreeVariableName("globalWorldPos"); - state._emitFunction("light_globalworldpos", `vec3 ${worldPosVariableName};\n`, comments); - state.compilationString += `${worldPosVariableName} = ${worldPos.associatedVariableName}.xyz;\n`; - state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { - repeatKey: "maxSimultaneousLights", - substitutionVars: this.generateOnlyFragmentCode ? `worldPos,${worldPos.associatedVariableName}` : undefined, - }); - } - else { - worldPosVariableName = "v_" + worldPosVariableName + ".xyz"; - } - state._emitFunctionFromInclude("helperFunctions", comments); - state._emitFunctionFromInclude("lightsFragmentFunctions", comments, { - replaceStrings: [{ search: /vPositionW/g, replace: worldPosVariableName }], - }); - state._emitFunctionFromInclude("shadowsFragmentFunctions", comments, { - replaceStrings: [{ search: /vPositionW/g, replace: worldPosVariableName }], - }); - if (!this.light) { - // Emit for all lights - state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, { - repeatKey: "maxSimultaneousLights", - substitutionVars: this.generateOnlyFragmentCode ? "varying," : undefined, - }); - } - else { - state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, { - replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }], - }, this._lightId.toString()); - } - // Code - if (this._lightId === 0) { - if (state._registerTempVariable("viewDirectionW")) { - state.compilationString += `vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${worldPosVariableName});\n`; - } - state.compilationString += `lightingInfo info;\n`; - state.compilationString += `float shadow = 1.;\n`; - state.compilationString += `float glossiness = ${this.glossiness.isConnected ? this.glossiness.associatedVariableName : "1.0"} * ${this.glossPower.isConnected ? this.glossPower.associatedVariableName : "1024.0"};\n`; - state.compilationString += `vec3 diffuseBase = vec3(0., 0., 0.);\n`; - state.compilationString += `vec3 specularBase = vec3(0., 0., 0.);\n`; - state.compilationString += `vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz;\n`; - } - if (this.light) { - state.compilationString += state._emitCodeFromInclude("lightFragment", comments, { - replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }], - }); - } - else { - state.compilationString += state._emitCodeFromInclude("lightFragment", comments, { - repeatKey: "maxSimultaneousLights", - }); - } - const diffuseOutput = this.diffuseOutput; - const specularOutput = this.specularOutput; - state.compilationString += - this._declareOutput(diffuseOutput, state) + ` = diffuseBase${this.diffuseColor.isConnected ? " * " + this.diffuseColor.associatedVariableName : ""};\n`; - if (specularOutput.hasEndpoints) { - state.compilationString += - this._declareOutput(specularOutput, state) + ` = specularBase${this.specularColor.isConnected ? " * " + this.specularColor.associatedVariableName : ""};\n`; - } - if (this.shadow.hasEndpoints) { - state.compilationString += this._declareOutput(this.shadow, state) + ` = shadow;\n`; - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode; - if (this.light) { - serializationObject.lightId = this.light.id; - } - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - if (serializationObject.lightId) { - this.light = scene.getLightById(serializationObject.lightId); - } - this.generateOnlyFragmentCode = serializationObject.generateOnlyFragmentCode; - this._setTarget(); - } -} -__decorate([ - editableInPropertyPage("Generate only fragment code", PropertyTypeForEdition.Boolean, "ADVANCED", { - notifiers: { rebuild: true, update: true, onValidation: LightBlock._OnGenerateOnlyFragmentCodeChanged }, - }) -], LightBlock.prototype, "generateOnlyFragmentCode", void 0); -RegisterClass("BABYLON.LightBlock", LightBlock); -//# sourceMappingURL=lightBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/imageSourceBlock.js - - - - - - - - - - -/** - * Block used to provide an image for a TextureBlock - */ -class ImageSourceBlock extends NodeMaterialBlock { - /** - * Gets or sets the texture associated with the node - */ - get texture() { - return this._texture; - } - set texture(texture) { - var _a; - if (this._texture === texture) { - return; - } - const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : engineStore_EngineStore.LastCreatedScene; - if (!texture && scene) { - scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this._texture); - }); - } - this._texture = texture; - if (texture && scene) { - scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(texture); - }); - } - } - /** - * Gets the sampler name associated with this image source - */ - get samplerName() { - return this._samplerName; - } - /** - * Creates a new ImageSourceBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.VertexAndFragment); - this.registerOutput("source", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source", this, NodeMaterialConnectionPointDirection.Output, ImageSourceBlock, "ImageSourceBlock")); - } - bind(effect) { - if (!this.texture) { - return; - } - effect.setTexture(this._samplerName, this.texture); - } - isReady() { - if (this.texture && !this.texture.isReadyOrNotBlocking()) { - return false; - } - return true; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ImageSourceBlock"; - } - /** - * Gets the output component - */ - get source() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - if (state.target === NodeMaterialBlockTargets.Vertex) { - this._samplerName = state._getFreeVariableName(this.name + "Sampler"); - // Declarations - state.sharedData.blockingBlocks.push(this); - state.sharedData.textureBlocks.push(this); - state.sharedData.bindableBlocks.push(this); - } - state._emit2DSampler(this._samplerName); - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - if (!this.texture) { - return codeString; - } - codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`; - codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`; - codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`; - codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`; - codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`; - codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`; - codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`; - codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`; - codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`; - codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`; - codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - if (this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture") { - serializationObject.texture = this.texture.serialize(); - } - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) { - rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; - this.texture = texture_Texture.Parse(serializationObject.texture, scene, rootUrl); - } - } -} -RegisterClass("BABYLON.ImageSourceBlock", ImageSourceBlock); -//# sourceMappingURL=imageSourceBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/textureBlock.js - - - - - - - - - - - - - - -/** - * Block used to read a texture from a sampler - */ -class TextureBlock extends NodeMaterialBlock { - /** - * Gets or sets the texture associated with the node - */ - get texture() { - var _a; - if (this.source.isConnected) { - return ((_a = this.source.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock).texture; - } - return this._texture; - } - set texture(texture) { - var _a; - if (this._texture === texture) { - return; - } - const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : engineStore_EngineStore.LastCreatedScene; - if (!texture && scene) { - scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this._texture); - }); - } - this._texture = texture; - if (texture && scene) { - scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(texture); - }); - } - } - /** - * Gets the sampler name associated with this texture - */ - get samplerName() { - if (this._imageSource) { - return this._imageSource.samplerName; - } - return this._samplerName; - } - /** - * Gets a boolean indicating that this block is linked to an ImageSourceBlock - */ - get hasImageSource() { - return this.source.isConnected; - } - /** - * Gets or sets a boolean indicating if content needs to be converted to gamma space - */ - set convertToGammaSpace(value) { - var _a; - if (value === this._convertToGammaSpace) { - return; - } - this._convertToGammaSpace = value; - if (this.texture) { - const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : engineStore_EngineStore.LastCreatedScene; - scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this.texture); - }); - } - } - get convertToGammaSpace() { - return this._convertToGammaSpace; - } - /** - * Gets or sets a boolean indicating if content needs to be converted to linear space - */ - set convertToLinearSpace(value) { - var _a; - if (value === this._convertToLinearSpace) { - return; - } - this._convertToLinearSpace = value; - if (this.texture) { - const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : engineStore_EngineStore.LastCreatedScene; - scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this.texture); - }); - } - } - get convertToLinearSpace() { - return this._convertToLinearSpace; - } - /** - * Create a new TextureBlock - * @param name defines the block name - * @param fragmentOnly - */ - constructor(name, fragmentOnly = false) { - super(name, fragmentOnly ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment); - this._convertToGammaSpace = false; - this._convertToLinearSpace = false; - /** - * Gets or sets a boolean indicating if multiplication of texture with level should be disabled - */ - this.disableLevelMultiplication = false; - this._fragmentOnly = fragmentOnly; - this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment); - this.registerInput("source", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, "ImageSourceBlock")); - this.registerInput("layer", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("lod", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral); - this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral); - this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("level", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - this._inputs[0]._prioritizeVertex = !fragmentOnly; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "TextureBlock"; - } - /** - * Gets the uv input component - */ - get uv() { - return this._inputs[0]; - } - /** - * Gets the source input component - */ - get source() { - return this._inputs[1]; - } - /** - * Gets the layer input component - */ - get layer() { - return this._inputs[2]; - } - /** - * Gets the LOD input component - */ - get lod() { - return this._inputs[3]; - } - /** - * Gets the rgba output component - */ - get rgba() { - return this._outputs[0]; - } - /** - * Gets the rgb output component - */ - get rgb() { - return this._outputs[1]; - } - /** - * Gets the r output component - */ - get r() { - return this._outputs[2]; - } - /** - * Gets the g output component - */ - get g() { - return this._outputs[3]; - } - /** - * Gets the b output component - */ - get b() { - return this._outputs[4]; - } - /** - * Gets the a output component - */ - get a() { - return this._outputs[5]; - } - /** - * Gets the level output component - */ - get level() { - return this._outputs[6]; - } - get target() { - if (this._fragmentOnly) { - return NodeMaterialBlockTargets.Fragment; - } - // TextureBlock has a special optimizations for uvs that come from the vertex shaders as they can be packed into a single varyings. - // But we need to detect uvs coming from fragment then - if (!this.uv.isConnected) { - return NodeMaterialBlockTargets.VertexAndFragment; - } - if (this.uv.sourceBlock.isInput) { - return NodeMaterialBlockTargets.VertexAndFragment; - } - let parent = this.uv.connectedPoint; - while (parent) { - if (parent.target === NodeMaterialBlockTargets.Fragment) { - return NodeMaterialBlockTargets.Fragment; - } - if (parent.target === NodeMaterialBlockTargets.Vertex) { - return NodeMaterialBlockTargets.VertexAndFragment; - } - if (parent.target === NodeMaterialBlockTargets.Neutral || parent.target === NodeMaterialBlockTargets.VertexAndFragment) { - const parentBlock = parent.ownerBlock; - if (parentBlock.target === NodeMaterialBlockTargets.Fragment) { - return NodeMaterialBlockTargets.Fragment; - } - parent = null; - for (const input of parentBlock.inputs) { - if (input.connectedPoint) { - parent = input.connectedPoint; - break; - } - } - } - } - return NodeMaterialBlockTargets.VertexAndFragment; - } - set target(value) { } - autoConfigure(material) { - if (!this.uv.isConnected) { - if (material.mode === NodeMaterialModes.PostProcess) { - const uvInput = material.getBlockByPredicate((b) => b.name === "uv"); - if (uvInput) { - uvInput.connectTo(this); - } - } - else { - const attributeName = material.mode === NodeMaterialModes.Particle ? "particle_uv" : "uv"; - let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === attributeName); - if (!uvInput) { - uvInput = new InputBlock("uv"); - uvInput.setAsAttribute(attributeName); - } - uvInput.output.connectTo(this.uv); - } - } - } - initializeDefines(mesh, nodeMaterial, defines) { - if (!defines._areTexturesDirty) { - return; - } - if (this._mainUVDefineName !== undefined) { - defines.setValue(this._mainUVDefineName, false, true); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - if (!defines._areTexturesDirty) { - return; - } - if (!this.texture || !this.texture.getTextureMatrix) { - if (this._isMixed) { - defines.setValue(this._defineName, false, true); - defines.setValue(this._mainUVDefineName, true, true); - } - return; - } - const toGamma = this.convertToGammaSpace && this.texture && !this.texture.gammaSpace; - const toLinear = this.convertToLinearSpace && this.texture && this.texture.gammaSpace; - // Not a bug... Name defines the texture space not the required conversion - defines.setValue(this._linearDefineName, toGamma, true); - defines.setValue(this._gammaDefineName, toLinear, true); - if (this._isMixed) { - if (!this.texture.getTextureMatrix().isIdentityAs3x2()) { - defines.setValue(this._defineName, true); - if (defines[this._mainUVDefineName] == undefined) { - defines.setValue(this._mainUVDefineName, false, true); - } - } - else { - defines.setValue(this._defineName, false, true); - defines.setValue(this._mainUVDefineName, true, true); - } - } - } - isReady() { - if (this.texture && !this.texture.isReadyOrNotBlocking()) { - return false; - } - return true; - } - bind(effect) { - if (!this.texture) { - return; - } - if (this._isMixed) { - effect.setFloat(this._textureInfoName, this.texture.level); - effect.setMatrix(this._textureTransformName, this.texture.getTextureMatrix()); - } - if (!this._imageSource) { - effect.setTexture(this._samplerName, this.texture); - } - } - get _isMixed() { - return this.target !== NodeMaterialBlockTargets.Fragment; - } - _injectVertexCode(state) { - const uvInput = this.uv; - // Inject code in vertex - this._defineName = state._getFreeDefineName("UVTRANSFORM"); - this._mainUVDefineName = "VMAIN" + uvInput.associatedVariableName.toUpperCase(); - this._mainUVName = "vMain" + uvInput.associatedVariableName; - this._transformedUVName = state._getFreeVariableName("transformedUV"); - this._textureTransformName = state._getFreeVariableName("textureTransform"); - this._textureInfoName = state._getFreeVariableName("textureInfoName"); - this.level.associatedVariableName = this._textureInfoName; - state._emitVaryingFromString(this._transformedUVName, "vec2", this._defineName); - state._emitVaryingFromString(this._mainUVName, "vec2", this._mainUVDefineName); - state._emitUniformFromString(this._textureTransformName, "mat4", this._defineName); - state.compilationString += `#ifdef ${this._defineName}\n`; - state.compilationString += `${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${uvInput.associatedVariableName}.xy, 1.0, 0.0));\n`; - state.compilationString += `#elif defined(${this._mainUVDefineName})\n`; - state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\n`; - state.compilationString += `#endif\n`; - if (!this._outputs.some((o) => o.isConnectedInVertexShader)) { - return; - } - this._writeTextureRead(state, true); - for (const output of this._outputs) { - if (output.hasEndpoints && output.name !== "level") { - this._writeOutput(state, output, output.name, true); - } - } - } - _getUVW(uvName) { - var _a, _b, _c; - let coords = uvName; - 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; - if (is2DArrayTexture) { - const layerValue = this.layer.isConnected ? this.layer.associatedVariableName : "0"; - coords = `vec3(${uvName}, ${layerValue})`; - } - return coords; - } - get _samplerFunc() { - return this.lod.isConnected ? "texture2DLodEXT" : "texture2D"; - } - get _samplerLodSuffix() { - return this.lod.isConnected ? `, ${this.lod.associatedVariableName}` : ""; - } - _generateTextureLookup(state) { - const samplerName = this.samplerName; - state.compilationString += `#ifdef ${this._defineName}\n`; - state.compilationString += `vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${samplerName}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix});\n`; - state.compilationString += `#elif defined(${this._mainUVDefineName})\n`; - state.compilationString += `vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${samplerName}, ${this._getUVW(this._mainUVName ? this._mainUVName : this.uv.associatedVariableName)}${this._samplerLodSuffix});\n`; - state.compilationString += `#endif\n`; - } - _writeTextureRead(state, vertexMode = false) { - const uvInput = this.uv; - if (vertexMode) { - if (state.target === NodeMaterialBlockTargets.Fragment) { - return; - } - this._generateTextureLookup(state); - return; - } - if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { - state.compilationString += `vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(uvInput.associatedVariableName)}${this._samplerLodSuffix});\n`; - return; - } - this._generateTextureLookup(state); - } - _generateConversionCode(state, output, swizzle) { - if (swizzle !== "a") { - // no conversion if the output is "a" (alpha) - if (!this.texture || !this.texture.gammaSpace) { - state.compilationString += `#ifdef ${this._linearDefineName} - ${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName}); - #endif - `; - } - state.compilationString += `#ifdef ${this._gammaDefineName} - ${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName}); - #endif - `; - } - } - _writeOutput(state, output, swizzle, vertexMode = false) { - if (vertexMode) { - if (state.target === NodeMaterialBlockTargets.Fragment) { - return; - } - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\n`; - this._generateConversionCode(state, output, swizzle); - return; - } - if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\n`; - this._generateConversionCode(state, output, swizzle); - return; - } - let complement = ""; - if (!this.disableLevelMultiplication) { - complement = ` * ${this._textureInfoName}`; - } - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle}${complement};\n`; - this._generateConversionCode(state, output, swizzle); - } - _buildBlock(state) { - var _a, _b, _c, _d; - super._buildBlock(state); - if (this.source.isConnected) { - this._imageSource = this.source.connectedPoint.ownerBlock; - } - else { - this._imageSource = null; - } - if (state.target === NodeMaterialBlockTargets.Vertex || this._fragmentOnly || state.target === NodeMaterialBlockTargets.Fragment) { - this._tempTextureRead = state._getFreeVariableName("tempTextureRead"); - this._linearDefineName = state._getFreeDefineName("ISLINEAR"); - this._gammaDefineName = state._getFreeDefineName("ISGAMMA"); - } - if ((!this._isMixed && state.target === NodeMaterialBlockTargets.Fragment) || (this._isMixed && state.target === NodeMaterialBlockTargets.Vertex)) { - if (!this._imageSource) { - this._samplerName = state._getFreeVariableName(this.name + "Sampler"); - if ((_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a._texture) === null || _b === void 0 ? void 0 : _b.is2DArray) { - state._emit2DArraySampler(this._samplerName); - } - else { - state._emit2DSampler(this._samplerName); - } - } - // Declarations - state.sharedData.blockingBlocks.push(this); - state.sharedData.textureBlocks.push(this); - state.sharedData.blocksWithDefines.push(this); - state.sharedData.bindableBlocks.push(this); - } - if (state.target !== NodeMaterialBlockTargets.Fragment) { - // Vertex - this._injectVertexCode(state); - return; - } - // Fragment - if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) { - return; - } - if (this._isMixed && !this._imageSource) { - // Reexport the sampler - if ((_d = (_c = this._texture) === null || _c === void 0 ? void 0 : _c._texture) === null || _d === void 0 ? void 0 : _d.is2DArray) { - state._emit2DArraySampler(this._samplerName); - } - else { - state._emit2DSampler(this._samplerName); - } - } - const comments = `//${this.name}`; - state._emitFunctionFromInclude("helperFunctions", comments); - if (this._isMixed) { - state._emitUniformFromString(this._textureInfoName, "float"); - } - this._writeTextureRead(state); - for (const output of this._outputs) { - if (output.hasEndpoints && output.name !== "level") { - this._writeOutput(state, output, output.name); - } - } - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`; - codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`; - codeString += `${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`; - if (!this.texture) { - return codeString; - } - codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`; - codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`; - codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`; - codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`; - codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`; - codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`; - codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`; - codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`; - codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`; - codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`; - codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.convertToGammaSpace = this.convertToGammaSpace; - serializationObject.convertToLinearSpace = this.convertToLinearSpace; - serializationObject.fragmentOnly = this._fragmentOnly; - serializationObject.disableLevelMultiplication = this.disableLevelMultiplication; - if (!this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture") { - serializationObject.texture = this.texture.serialize(); - } - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.convertToGammaSpace = serializationObject.convertToGammaSpace; - this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; - this._fragmentOnly = !!serializationObject.fragmentOnly; - this.disableLevelMultiplication = !!serializationObject.disableLevelMultiplication; - if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) { - rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; - this.texture = texture_Texture.Parse(serializationObject.texture, scene, rootUrl); - } - } -} -RegisterClass("BABYLON.TextureBlock", TextureBlock); -//# sourceMappingURL=textureBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/reflectionTextureBaseBlock.js - - - - - - - - - - - - - -/** - * Base block used to read a reflection texture from a sampler - */ -class ReflectionTextureBaseBlock extends NodeMaterialBlock { - /** - * Gets or sets the texture associated with the node - */ - get texture() { - return this._texture; - } - set texture(texture) { - var _a; - if (this._texture === texture) { - return; - } - const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : engineStore_EngineStore.LastCreatedScene; - if (!texture && scene) { - scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this._texture); - }); - } - this._texture = texture; - if (texture && scene) { - scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(texture); - }); - } - } - static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) { - const that = block; - return that._onGenerateOnlyFragmentCodeChanged(); - } - _onGenerateOnlyFragmentCodeChanged() { - this._setTarget(); - return true; - } - _setTarget() { - this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment); - } - /** - * Create a new ReflectionTextureBaseBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.VertexAndFragment); - /** 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) */ - this.generateOnlyFragmentCode = false; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ReflectionTextureBaseBlock"; - } - _getTexture() { - return this.texture; - } - autoConfigure(material) { - if (!this.position.isConnected) { - let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === "position"); - if (!positionInput) { - positionInput = new InputBlock("position"); - positionInput.setAsAttribute(); - } - positionInput.output.connectTo(this.position); - } - if (!this.world.isConnected) { - let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World); - if (!worldInput) { - worldInput = new InputBlock("world"); - worldInput.setAsSystemValue(NodeMaterialSystemValues.World); - } - worldInput.output.connectTo(this.world); - } - if (this.view && !this.view.isConnected) { - let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View); - if (!viewInput) { - viewInput = new InputBlock("view"); - viewInput.setAsSystemValue(NodeMaterialSystemValues.View); - } - viewInput.output.connectTo(this.view); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - if (!defines._areTexturesDirty) { - return; - } - const texture = this._getTexture(); - if (!texture || !texture.getTextureMatrix) { - return; - } - defines.setValue(this._define3DName, texture.isCube, true); - defines.setValue(this._defineLocalCubicName, texture.boundingBoxSize ? true : false, true); - defines.setValue(this._defineExplicitName, texture.coordinatesMode === 0, true); - defines.setValue(this._defineSkyboxName, texture.coordinatesMode === 5, true); - defines.setValue(this._defineCubicName, texture.coordinatesMode === 3 || texture.coordinatesMode === 6, true); - defines.setValue("INVERTCUBICMAP", texture.coordinatesMode === 6, true); - defines.setValue(this._defineSphericalName, texture.coordinatesMode === 1, true); - defines.setValue(this._definePlanarName, texture.coordinatesMode === 2, true); - defines.setValue(this._defineProjectionName, texture.coordinatesMode === 4, true); - defines.setValue(this._defineEquirectangularName, texture.coordinatesMode === 7, true); - defines.setValue(this._defineEquirectangularFixedName, texture.coordinatesMode === 8, true); - defines.setValue(this._defineMirroredEquirectangularFixedName, texture.coordinatesMode === 9, true); - } - isReady() { - const texture = this._getTexture(); - if (texture && !texture.isReadyOrNotBlocking()) { - return false; - } - return true; - } - bind(effect, nodeMaterial, mesh) { - const texture = this._getTexture(); - if (!mesh || !texture) { - return; - } - effect.setMatrix(this._reflectionMatrixName, texture.getReflectionTextureMatrix()); - if (texture.isCube) { - effect.setTexture(this._cubeSamplerName, texture); - } - else { - effect.setTexture(this._2DSamplerName, texture); - } - if (texture.boundingBoxSize) { - const cubeTexture = texture; - effect.setVector3(this._reflectionPositionName, cubeTexture.boundingBoxPosition); - effect.setVector3(this._reflectionSizeName, cubeTexture.boundingBoxSize); - } - } - /** - * Gets the code to inject in the vertex shader - * @param state current state of the node material building - * @returns the shader code - */ - handleVertexSide(state) { - if (this.generateOnlyFragmentCode && state.target === NodeMaterialBlockTargets.Vertex) { - return ""; - } - this._define3DName = state._getFreeDefineName("REFLECTIONMAP_3D"); - this._defineCubicName = state._getFreeDefineName("REFLECTIONMAP_CUBIC"); - this._defineSphericalName = state._getFreeDefineName("REFLECTIONMAP_SPHERICAL"); - this._definePlanarName = state._getFreeDefineName("REFLECTIONMAP_PLANAR"); - this._defineProjectionName = state._getFreeDefineName("REFLECTIONMAP_PROJECTION"); - this._defineExplicitName = state._getFreeDefineName("REFLECTIONMAP_EXPLICIT"); - this._defineEquirectangularName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"); - this._defineLocalCubicName = state._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"); - this._defineMirroredEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"); - this._defineEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"); - this._defineSkyboxName = state._getFreeDefineName("REFLECTIONMAP_SKYBOX"); - this._defineOppositeZ = state._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"); - this._reflectionMatrixName = state._getFreeVariableName("reflectionMatrix"); - state._emitUniformFromString(this._reflectionMatrixName, "mat4"); - let code = ""; - this._worldPositionNameInFragmentOnlyMode = state._getFreeVariableName("worldPosition"); - const worldPosVaryingName = this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : "v_" + this.worldPosition.associatedVariableName; - if (this.generateOnlyFragmentCode || state._emitVaryingFromString(worldPosVaryingName, "vec4")) { - code += `${this.generateOnlyFragmentCode ? "vec4 " : ""}${worldPosVaryingName} = ${this.worldPosition.associatedVariableName};\n`; - } - this._positionUVWName = state._getFreeVariableName("positionUVW"); - this._directionWName = state._getFreeVariableName("directionW"); - if (this.generateOnlyFragmentCode || state._emitVaryingFromString(this._positionUVWName, "vec3", this._defineSkyboxName)) { - code += `#ifdef ${this._defineSkyboxName}\n`; - code += `${this.generateOnlyFragmentCode ? "vec3 " : ""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\n`; - code += `#endif\n`; - } - if (this.generateOnlyFragmentCode || - state._emitVaryingFromString(this._directionWName, "vec3", `defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`)) { - code += `#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\n`; - code += `${this.generateOnlyFragmentCode ? "vec3 " : ""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\n`; - code += `#endif\n`; - } - return code; - } - /** - * Handles the inits for the fragment code path - * @param state node material build state - */ - handleFragmentSideInits(state) { - state.sharedData.blockingBlocks.push(this); - state.sharedData.textureBlocks.push(this); - // Samplers - this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler"); - state.samplers.push(this._cubeSamplerName); - this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler"); - state.samplers.push(this._2DSamplerName); - state._samplerDeclaration += `#ifdef ${this._define3DName}\n`; - state._samplerDeclaration += `uniform samplerCube ${this._cubeSamplerName};\n`; - state._samplerDeclaration += `#else\n`; - state._samplerDeclaration += `uniform sampler2D ${this._2DSamplerName};\n`; - state._samplerDeclaration += `#endif\n`; - // Fragment - state.sharedData.blocksWithDefines.push(this); - state.sharedData.bindableBlocks.push(this); - const comments = `//${this.name}`; - state._emitFunction("ReciprocalPI", "#define RECIPROCAL_PI2 0.15915494", ""); - state._emitFunctionFromInclude("helperFunctions", comments); - state._emitFunctionFromInclude("reflectionFunction", comments, { - replaceStrings: [{ search: /vec3 computeReflectionCoords/g, replace: "void DUMMYFUNC" }], - }); - this._reflectionColorName = state._getFreeVariableName("reflectionColor"); - this._reflectionVectorName = state._getFreeVariableName("reflectionUVW"); - this._reflectionCoordsName = state._getFreeVariableName("reflectionCoords"); - this._reflectionPositionName = state._getFreeVariableName("vReflectionPosition"); - state._emitUniformFromString(this._reflectionPositionName, "vec3"); - this._reflectionSizeName = state._getFreeVariableName("vReflectionPosition"); - state._emitUniformFromString(this._reflectionSizeName, "vec3"); - } - /** - * Generates the reflection coords code for the fragment code path - * @param worldNormalVarName name of the world normal variable - * @param worldPos name of the world position variable. If not provided, will use the world position connected to this block - * @param onlyReflectionVector if true, generates code only for the reflection vector computation, not for the reflection coordinates - * @param doNotEmitInvertZ if true, does not emit the invertZ code - * @returns the shader code - */ - handleFragmentSideCodeReflectionCoords(worldNormalVarName, worldPos, onlyReflectionVector = false, doNotEmitInvertZ = false) { - if (!worldPos) { - worldPos = this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : `v_${this.worldPosition.associatedVariableName}`; - } - const reflectionMatrix = this._reflectionMatrixName; - const direction = `normalize(${this._directionWName})`; - const positionUVW = `${this._positionUVWName}`; - const vEyePosition = `${this.cameraPosition.associatedVariableName}`; - const view = `${this.view.associatedVariableName}`; - worldNormalVarName += ".xyz"; - let code = ` - #ifdef ${this._defineMirroredEquirectangularFixedName} - vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction}); - #endif - - #ifdef ${this._defineEquirectangularFixedName} - vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction}); - #endif - - #ifdef ${this._defineEquirectangularName} - vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}); - #endif - - #ifdef ${this._defineSphericalName} - vec3 ${this._reflectionVectorName} = computeSphericalCoords(${worldPos}, ${worldNormalVarName}, ${view}, ${reflectionMatrix}); - #endif - - #ifdef ${this._definePlanarName} - vec3 ${this._reflectionVectorName} = computePlanarCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}); - #endif - - #ifdef ${this._defineCubicName} - #ifdef ${this._defineLocalCubicName} - vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); - #else - vec3 ${this._reflectionVectorName} = computeCubicCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}); - #endif - #endif - - #ifdef ${this._defineProjectionName} - vec3 ${this._reflectionVectorName} = computeProjectionCoords(${worldPos}, ${view}, ${reflectionMatrix}); - #endif - - #ifdef ${this._defineSkyboxName} - vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${positionUVW}, ${reflectionMatrix}); - #endif - - #ifdef ${this._defineExplicitName} - vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); - #endif\n`; - if (!doNotEmitInvertZ) { - code += `#ifdef ${this._defineOppositeZ} - ${this._reflectionVectorName}.z *= -1.0; - #endif\n`; - } - if (!onlyReflectionVector) { - code += ` - #ifdef ${this._define3DName} - vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName}; - #else - vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy; - #ifdef ${this._defineProjectionName} - ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; - #endif - ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; - #endif\n`; - } - return code; - } - /** - * Generates the reflection color code for the fragment code path - * @param lodVarName name of the lod variable - * @param swizzleLookupTexture swizzle to use for the final color variable - * @returns the shader code - */ - handleFragmentSideCodeReflectionColor(lodVarName, swizzleLookupTexture = ".rgb") { - const colorType = "vec" + (swizzleLookupTexture.length === 0 ? "4" : swizzleLookupTexture.length - 1); - let code = `${colorType} ${this._reflectionColorName}; - #ifdef ${this._define3DName}\n`; - if (lodVarName) { - code += `${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${lodVarName})${swizzleLookupTexture};\n`; - } - else { - code += `${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${swizzleLookupTexture};\n`; - } - code += ` - #else\n`; - if (lodVarName) { - code += `${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${lodVarName})${swizzleLookupTexture};\n`; - } - else { - code += `${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${swizzleLookupTexture};\n`; - } - code += `#endif\n`; - return code; - } - /** - * Generates the code corresponding to the connected output points - * @param state node material build state - * @param varName name of the variable to output - * @returns the shader code - */ - writeOutputs(state, varName) { - let code = ""; - if (state.target === NodeMaterialBlockTargets.Fragment) { - for (const output of this._outputs) { - if (output.hasEndpoints) { - code += `${this._declareOutput(output, state)} = ${varName}.${output.name};\n`; - } - } - } - return code; - } - _buildBlock(state) { - super._buildBlock(state); - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - if (!this.texture) { - return codeString; - } - if (this.texture.isCube) { - const forcedExtension = this.texture.forcedExtension; - 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"});\n`; - } - else { - codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\n`; - } - codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - if (this.texture && !this.texture.isRenderTarget) { - serializationObject.texture = this.texture.serialize(); - } - serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime) { - rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; - if (serializationObject.texture.isCube) { - this.texture = cubeTexture_CubeTexture.Parse(serializationObject.texture, scene, rootUrl); - } - else { - this.texture = texture_Texture.Parse(serializationObject.texture, scene, rootUrl); - } - } - this.generateOnlyFragmentCode = serializationObject.generateOnlyFragmentCode; - this._setTarget(); - } -} -__decorate([ - editableInPropertyPage("Generate only fragment code", PropertyTypeForEdition.Boolean, "ADVANCED", { - notifiers: { rebuild: true, update: true, onValidation: ReflectionTextureBaseBlock._OnGenerateOnlyFragmentCodeChanged }, - }) -], ReflectionTextureBaseBlock.prototype, "generateOnlyFragmentCode", void 0); -RegisterClass("BABYLON.ReflectionTextureBaseBlock", ReflectionTextureBaseBlock); -//# sourceMappingURL=reflectionTextureBaseBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/reflectionTextureBlock.js - - - - - - -/** - * Block used to read a reflection texture from a sampler - */ -class ReflectionTextureBlock extends ReflectionTextureBaseBlock { - _onGenerateOnlyFragmentCodeChanged() { - if (this.position.isConnected) { - this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode; - console.error("The position input must not be connected to be able to switch!"); - return false; - } - if (this.worldPosition.isConnected) { - this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode; - console.error("The worldPosition input must not be connected to be able to switch!"); - return false; - } - this._setTarget(); - return true; - } - _setTarget() { - super._setTarget(); - this.getInputByName("position").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; - this.getInputByName("worldPosition").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; - } - /** - * Create a new ReflectionTextureBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("position", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Vertex); - this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); - this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment); // Flagging as fragment as the normal can be changed by fragment code - this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex); - this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Fragment); - this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment); - this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ReflectionTextureBlock"; - } - /** - * Gets the world position input component - */ - get position() { - return this._inputs[0]; - } - /** - * Gets the world position input component - */ - get worldPosition() { - return this._inputs[1]; - } - /** - * Gets the world normal input component - */ - get worldNormal() { - return this._inputs[2]; - } - /** - * Gets the world input component - */ - get world() { - return this._inputs[3]; - } - /** - * Gets the camera (or eye) position component - */ - get cameraPosition() { - return this._inputs[4]; - } - /** - * Gets the view input component - */ - get view() { - return this._inputs[5]; - } - /** - * Gets the rgb output component - */ - get rgb() { - return this._outputs[0]; - } - /** - * Gets the rgba output component - */ - get rgba() { - return this._outputs[1]; - } - /** - * Gets the r output component - */ - get r() { - return this._outputs[2]; - } - /** - * Gets the g output component - */ - get g() { - return this._outputs[3]; - } - /** - * Gets the b output component - */ - get b() { - return this._outputs[4]; - } - /** - * Gets the a output component - */ - get a() { - return this._outputs[5]; - } - autoConfigure(material) { - super.autoConfigure(material); - if (!this.cameraPosition.isConnected) { - let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition); - if (!cameraPositionInput) { - cameraPositionInput = new InputBlock("cameraPosition"); - cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition); - } - cameraPositionInput.output.connectTo(this.cameraPosition); - } - } - _buildBlock(state) { - super._buildBlock(state); - if (!this.texture) { - state.compilationString += this.writeOutputs(state, "vec4(0.)"); - return this; - } - if (state.target !== NodeMaterialBlockTargets.Fragment) { - state.compilationString += this.handleVertexSide(state); - return this; - } - if (this.generateOnlyFragmentCode) { - state.compilationString += this.handleVertexSide(state); - } - this.handleFragmentSideInits(state); - const normalWUnit = state._getFreeVariableName("normalWUnit"); - state.compilationString += `vec4 ${normalWUnit} = normalize(${this.worldNormal.associatedVariableName});\n`; - state.compilationString += this.handleFragmentSideCodeReflectionCoords(normalWUnit); - state.compilationString += this.handleFragmentSideCodeReflectionColor(undefined, ""); - state.compilationString += this.writeOutputs(state, this._reflectionColorName); - return this; - } -} -RegisterClass("BABYLON.ReflectionTextureBlock", ReflectionTextureBlock); -//# sourceMappingURL=reflectionTextureBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/sceneDepthBlock.js - - - - - - -/** - * Block used to retrieve the depth (zbuffer) of the scene - * @since 5.0.0 - */ -class SceneDepthBlock extends NodeMaterialBlock { - /** - * Create a new SceneDepthBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.VertexAndFragment); - /** - * Defines if the depth renderer should be setup in non linear mode - */ - this.useNonLinearDepth = false; - /** - * Defines if the depth renderer should be setup in camera space Z mode (if set, useNonLinearDepth has no effect) - */ - this.storeCameraSpaceZ = false; - /** - * Defines if the depth renderer should be setup in full 32 bits float mode - */ - this.force32itsFloat = false; - this._isUnique = true; - this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment); - this.registerOutput("depth", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - this._inputs[0]._prioritizeVertex = false; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SceneDepthBlock"; - } - /** - * Gets the uv input component - */ - get uv() { - return this._inputs[0]; - } - /** - * Gets the depth output component - */ - get depth() { - return this._outputs[0]; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("textureSampler"); - } - get target() { - if (!this.uv.isConnected) { - return NodeMaterialBlockTargets.VertexAndFragment; - } - if (this.uv.sourceBlock.isInput) { - return NodeMaterialBlockTargets.VertexAndFragment; - } - return NodeMaterialBlockTargets.Fragment; - } - _getTexture(scene) { - const depthRenderer = scene.enableDepthRenderer(undefined, this.useNonLinearDepth, this.force32itsFloat, undefined, this.storeCameraSpaceZ); - return depthRenderer.getDepthMap(); - } - bind(effect, nodeMaterial) { - const texture = this._getTexture(nodeMaterial.getScene()); - effect.setTexture(this._samplerName, texture); - } - _injectVertexCode(state) { - const uvInput = this.uv; - if (uvInput.connectedPoint.ownerBlock.isInput) { - const uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock; - if (!uvInputOwnerBlock.isAttribute) { - state._emitUniformFromString(uvInput.associatedVariableName, "vec" + (uvInput.type === NodeMaterialBlockConnectionPointTypes.Vector3 ? "3" : uvInput.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? "4" : "2")); - } - } - this._mainUVName = "vMain" + uvInput.associatedVariableName; - state._emitVaryingFromString(this._mainUVName, "vec2"); - state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\n`; - if (!this._outputs.some((o) => o.isConnectedInVertexShader)) { - return; - } - this._writeTextureRead(state, true); - for (const output of this._outputs) { - if (output.hasEndpoints) { - this._writeOutput(state, output, "r", true); - } - } - } - _writeTextureRead(state, vertexMode = false) { - const uvInput = this.uv; - if (vertexMode) { - if (state.target === NodeMaterialBlockTargets.Fragment) { - return; - } - state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName}.xy);\n`; - return; - } - if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { - state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName}.xy);\n`; - return; - } - state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`; - } - _writeOutput(state, output, swizzle, vertexMode = false) { - if (vertexMode) { - if (state.target === NodeMaterialBlockTargets.Fragment) { - return; - } - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\n`; - return; - } - if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) { - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\n`; - return; - } - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\n`; - } - _buildBlock(state) { - super._buildBlock(state); - this._samplerName = state._getFreeVariableName(this.name + "Sampler"); - this._tempTextureRead = state._getFreeVariableName("tempTextureRead"); - if (state.sharedData.bindableBlocks.indexOf(this) < 0) { - state.sharedData.bindableBlocks.push(this); - } - if (state.target !== NodeMaterialBlockTargets.Fragment) { - // Vertex - state._emit2DSampler(this._samplerName); - this._injectVertexCode(state); - return; - } - // Fragment - if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) { - return; - } - state._emit2DSampler(this._samplerName); - this._writeTextureRead(state); - for (const output of this._outputs) { - if (output.hasEndpoints) { - this._writeOutput(state, output, "r"); - } - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.useNonLinearDepth = this.useNonLinearDepth; - serializationObject.storeCameraSpaceZ = this.storeCameraSpaceZ; - serializationObject.force32itsFloat = this.force32itsFloat; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.useNonLinearDepth = serializationObject.useNonLinearDepth; - this.storeCameraSpaceZ = !!serializationObject.storeCameraSpaceZ; - this.force32itsFloat = serializationObject.force32itsFloat; - } -} -__decorate([ - editableInPropertyPage("Use non linear depth", PropertyTypeForEdition.Boolean, "ADVANCED", { - notifiers: { - activatePreviewCommand: true, - callback: (scene, block) => { - const sceneDepthBlock = block; - let retVal = false; - if (sceneDepthBlock.useNonLinearDepth) { - sceneDepthBlock.storeCameraSpaceZ = false; - retVal = true; - } - if (scene) { - scene.disableDepthRenderer(); - } - return retVal; - }, - }, - }) -], SceneDepthBlock.prototype, "useNonLinearDepth", void 0); -__decorate([ - editableInPropertyPage("Store Camera space Z", PropertyTypeForEdition.Boolean, "ADVANCED", { - notifiers: { - activatePreviewCommand: true, - callback: (scene, block) => { - const sceneDepthBlock = block; - let retVal = false; - if (sceneDepthBlock.storeCameraSpaceZ) { - sceneDepthBlock.useNonLinearDepth = false; - retVal = true; - } - if (scene) { - scene.disableDepthRenderer(); - } - return retVal; - }, - }, - }) -], SceneDepthBlock.prototype, "storeCameraSpaceZ", void 0); -__decorate([ - editableInPropertyPage("Force 32 bits float", PropertyTypeForEdition.Boolean, "ADVANCED", { - notifiers: { activatePreviewCommand: true, callback: (scene) => scene === null || scene === void 0 ? void 0 : scene.disableDepthRenderer() }, - }) -], SceneDepthBlock.prototype, "force32itsFloat", void 0); -RegisterClass("BABYLON.SceneDepthBlock", SceneDepthBlock); -//# sourceMappingURL=sceneDepthBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/clipPlanesBlock.js - - - - - -/** - * Block used to implement clip planes - */ -class ClipPlanesBlock extends NodeMaterialBlock { - /** - * Create a new ClipPlanesBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.VertexAndFragment, true); - this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ClipPlanesBlock"; - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("vClipPlane"); - state._excludeVariableName("fClipDistance"); - state._excludeVariableName("vClipPlane2"); - state._excludeVariableName("fClipDistance2"); - state._excludeVariableName("vClipPlane3"); - state._excludeVariableName("fClipDistance3"); - state._excludeVariableName("vClipPlane4"); - state._excludeVariableName("fClipDistance4"); - state._excludeVariableName("vClipPlane5"); - state._excludeVariableName("fClipDistance5"); - state._excludeVariableName("vClipPlane6"); - state._excludeVariableName("fClipDistance6"); - } - /** - * Gets the worldPosition input component - */ - get worldPosition() { - return this._inputs[0]; - } - get target() { - return NodeMaterialBlockTargets.VertexAndFragment; - } - set target(value) { } - prepareDefines(mesh, nodeMaterial, defines) { - var _a, _b, _c, _d, _e, _f; - const scene = mesh.getScene(); - const useClipPlane1 = ((_a = nodeMaterial.clipPlane) !== null && _a !== void 0 ? _a : scene.clipPlane) ? true : false; - const useClipPlane2 = ((_b = nodeMaterial.clipPlane2) !== null && _b !== void 0 ? _b : scene.clipPlane2) ? true : false; - const useClipPlane3 = ((_c = nodeMaterial.clipPlane3) !== null && _c !== void 0 ? _c : scene.clipPlane3) ? true : false; - const useClipPlane4 = ((_d = nodeMaterial.clipPlane4) !== null && _d !== void 0 ? _d : scene.clipPlane4) ? true : false; - const useClipPlane5 = ((_e = nodeMaterial.clipPlane5) !== null && _e !== void 0 ? _e : scene.clipPlane5) ? true : false; - const useClipPlane6 = ((_f = nodeMaterial.clipPlane6) !== null && _f !== void 0 ? _f : scene.clipPlane6) ? true : false; - defines.setValue("CLIPPLANE", useClipPlane1, true); - defines.setValue("CLIPPLANE2", useClipPlane2, true); - defines.setValue("CLIPPLANE3", useClipPlane3, true); - defines.setValue("CLIPPLANE4", useClipPlane4, true); - defines.setValue("CLIPPLANE5", useClipPlane5, true); - defines.setValue("CLIPPLANE6", useClipPlane6, true); - } - bind(effect, nodeMaterial, mesh) { - if (!mesh) { - return; - } - const scene = mesh.getScene(); - bindClipPlane(effect, nodeMaterial, scene); - } - _buildBlock(state) { - super._buildBlock(state); - const comments = `//${this.name}`; - if (state.target !== NodeMaterialBlockTargets.Fragment) { - // Vertex - const worldPos = this.worldPosition; - state._emitFunctionFromInclude("clipPlaneVertexDeclaration", comments, { - replaceStrings: [{ search: /uniform vec4 vClipPlane\d*;/g, replace: "" }], - }); - state.compilationString += state._emitCodeFromInclude("clipPlaneVertex", comments, { - replaceStrings: [{ search: /worldPos/g, replace: worldPos.associatedVariableName }], - }); - state._emitUniformFromString("vClipPlane", "vec4"); - state._emitUniformFromString("vClipPlane2", "vec4"); - state._emitUniformFromString("vClipPlane3", "vec4"); - state._emitUniformFromString("vClipPlane4", "vec4"); - state._emitUniformFromString("vClipPlane5", "vec4"); - state._emitUniformFromString("vClipPlane6", "vec4"); - return; - } - // Fragment - state.sharedData.bindableBlocks.push(this); - state.sharedData.blocksWithDefines.push(this); - state._emitFunctionFromInclude("clipPlaneFragmentDeclaration", comments); - state.compilationString += state._emitCodeFromInclude("clipPlaneFragment", comments); - return this; - } -} -RegisterClass("BABYLON.ClipPlanesBlock", ClipPlanesBlock); -//# sourceMappingURL=clipPlanesBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/index.js - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Input/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Teleport/teleportInBlock.js - - - - -/** - * Defines a block used to teleport a value to an endpoint - */ -class NodeMaterialTeleportInBlock extends NodeMaterialBlock { - /** Gets the list of attached endpoints */ - get endpoints() { - return this._endpoints; - } - /** - * Create a new NodeMaterialTeleportInBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this._endpoints = []; - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "NodeMaterialTeleportInBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** Gets a boolean indicating that this connection will be used in the fragment shader */ - isConnectedInFragmentShader() { - return this.endpoints.some((e) => e.output.isConnectedInFragmentShader); - } - _dumpCode(uniqueNames, alreadyDumped) { - let codeString = super._dumpCode(uniqueNames, alreadyDumped); - for (const endpoint of this.endpoints) { - if (alreadyDumped.indexOf(endpoint) === -1) { - codeString += endpoint._dumpCode(uniqueNames, alreadyDumped); - } - } - return codeString; - } - /** - * Add an enpoint to this block - * @param endpoint define the endpoint to attach to - */ - attachToEndpoint(endpoint) { - endpoint.detach(); - this._endpoints.push(endpoint); - endpoint._entryPoint = this; - endpoint._outputs[0]._typeConnectionSource = this._inputs[0]; - endpoint._tempEntryPointUniqueId = null; - endpoint.name = "> " + this.name; - } - /** - * Remove enpoint from this block - * @param endpoint define the endpoint to remove - */ - detachFromEndpoint(endpoint) { - const index = this._endpoints.indexOf(endpoint); - if (index !== -1) { - this._endpoints.splice(index, 1); - endpoint._outputs[0]._typeConnectionSource = null; - endpoint._entryPoint = null; - } - } - /** - * Release resources - */ - dispose() { - super.dispose(); - for (const endpoint of this._endpoints) { - this.detachFromEndpoint(endpoint); - } - this._endpoints = []; - } -} -RegisterClass("BABYLON.NodeMaterialTeleportInBlock", NodeMaterialTeleportInBlock); -//# sourceMappingURL=teleportInBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Teleport/teleportOutBlock.js - - - - -/** - * Defines a block used to receive a value from a teleport entry point - */ -class NodeMaterialTeleportOutBlock extends NodeMaterialBlock { - /** - * Create a new TeleportOutBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** @internal */ - this._entryPoint = null; - /** @internal */ - this._tempEntryPointUniqueId = null; - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - } - /** - * Gets the entry point - */ - get entryPoint() { - return this._entryPoint; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "NodeMaterialTeleportOutBlock"; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets or sets the target of the block - */ - get target() { - return this._entryPoint ? this._entryPoint.target : this._target; - } - set target(value) { - if ((this._target & value) !== 0) { - return; - } - this._target = value; - } - /** Detach from entry point */ - detach() { - if (!this._entryPoint) { - return; - } - this._entryPoint.detachFromEndpoint(this); - } - _buildBlock(state) { - super._buildBlock(state); - if (this.entryPoint) { - state.compilationString += this._declareOutput(this.output, state) + ` = ${this.entryPoint.input.associatedVariableName};\n`; - } - } - /** - * Clone the current block to a new identical block - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a copy of the current block - */ - clone(scene, rootUrl = "") { - const clone = super.clone(scene, rootUrl); - if (this.entryPoint) { - this.entryPoint.attachToEndpoint(clone); - } - return clone; - } - _customBuildStep(state, activeBlocks) { - if (this.entryPoint) { - this.entryPoint.build(state, activeBlocks); - } - } - _dumpCode(uniqueNames, alreadyDumped) { - let codeString = ""; - if (this.entryPoint) { - if (alreadyDumped.indexOf(this.entryPoint) === -1) { - codeString += this.entryPoint._dumpCode(uniqueNames, alreadyDumped); - } - } - return codeString + super._dumpCode(uniqueNames, alreadyDumped); - } - _dumpCodeForOutputConnections(alreadyDumped) { - let codeString = super._dumpCodeForOutputConnections(alreadyDumped); - if (this.entryPoint) { - codeString += this.entryPoint._dumpCodeForOutputConnections(alreadyDumped); - } - return codeString; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - if (this.entryPoint) { - codeString += `${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`; - } - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - var _a, _b; - const serializationObject = super.serialize(); - serializationObject.entryPoint = (_b = (_a = this.entryPoint) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : ""; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this._tempEntryPointUniqueId = serializationObject.entryPoint; - } -} -RegisterClass("BABYLON.NodeMaterialTeleportOutBlock", NodeMaterialTeleportOutBlock); -//# sourceMappingURL=teleportOutBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Teleport/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/addBlock.js - - - - -/** - * Block used to add 2 vectors - */ -class AddBlock extends NodeMaterialBlock { - /** - * Creates a new AddBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "AddBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\n`; - return this; - } -} -RegisterClass("BABYLON.AddBlock", AddBlock); -//# sourceMappingURL=addBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/scaleBlock.js - - - - -/** - * Block used to scale a vector by a float - */ -class ScaleBlock extends NodeMaterialBlock { - /** - * Creates a new ScaleBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("factor", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ScaleBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the factor input component - */ - get factor() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};\n`; - return this; - } -} -RegisterClass("BABYLON.ScaleBlock", ScaleBlock); -//# sourceMappingURL=scaleBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/clampBlock.js - - - - - - -/** - * Block used to clamp a float - */ -class ClampBlock extends NodeMaterialBlock { - /** - * Creates a new ClampBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** Gets or sets the minimum range */ - this.minimum = 0.0; - /** Gets or sets the maximum range */ - this.maximum = 1.0; - this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ClampBlock"; - } - /** - * Gets the value input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += - this._declareOutput(output, state) + ` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)});\n`; - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.minimum = ${this.minimum};\n`; - codeString += `${this._codeVariableName}.maximum = ${this.maximum};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.minimum = this.minimum; - serializationObject.maximum = this.maximum; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.minimum = serializationObject.minimum; - this.maximum = serializationObject.maximum; - } -} -__decorate([ - editableInPropertyPage("Minimum", PropertyTypeForEdition.Float) -], ClampBlock.prototype, "minimum", void 0); -__decorate([ - editableInPropertyPage("Maximum", PropertyTypeForEdition.Float) -], ClampBlock.prototype, "maximum", void 0); -RegisterClass("BABYLON.ClampBlock", ClampBlock); -//# sourceMappingURL=clampBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/crossBlock.js - - - - -/** - * Block used to apply a cross product between 2 vectors - */ -class CrossBlock extends NodeMaterialBlock { - /** - * Creates a new CrossBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3); - this._linkConnectionTypes(0, 1); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2); - this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "CrossBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\n`; - return this; - } -} -RegisterClass("BABYLON.CrossBlock", CrossBlock); -//# sourceMappingURL=crossBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/customBlock.js - - - - - - - -/** - * Custom block created from user-defined json - */ -class CustomBlock extends NodeMaterialBlock { - /** - * Gets or sets the options for this custom block - */ - get options() { - return this._options; - } - set options(options) { - this._deserializeOptions(options); - } - /** - * Creates a new CustomBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "CustomBlock"; - } - _buildBlock(state) { - super._buildBlock(state); - let code = this._code; - let functionName = this._options.functionName; - // Replace the TYPE_XXX placeholders (if any) - this._inputs.forEach((input) => { - const rexp = new RegExp("\\{TYPE_" + input.name + "\\}", "gm"); - const type = state._getGLType(input.type); - code = code.replace(rexp, type); - functionName = functionName.replace(rexp, type); - }); - this._outputs.forEach((output) => { - const rexp = new RegExp("\\{TYPE_" + output.name + "\\}", "gm"); - const type = state._getGLType(output.type); - code = code.replace(rexp, type); - functionName = functionName.replace(rexp, type); - }); - state._emitFunction(functionName, code, ""); - // Declare the output variables - this._outputs.forEach((output) => { - state.compilationString += this._declareOutput(output, state) + ";\n"; - }); - // Generate the function call - state.compilationString += functionName + "("; - let hasInput = false; - this._inputs.forEach((input, index) => { - var _a, _b, _c; - if (index > 0) { - state.compilationString += ", "; - } - if (this._inputSamplers && this._inputSamplers.indexOf(input.name) !== -1) { - 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; - } - else { - state.compilationString += input.associatedVariableName; - } - hasInput = true; - }); - this._outputs.forEach((output, index) => { - if (index > 0 || hasInput) { - state.compilationString += ", "; - } - state.compilationString += output.associatedVariableName; - }); - state.compilationString += ");\n"; - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.options = ${JSON.stringify(this._options)};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.options = this._options; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - this._deserializeOptions(serializationObject.options); - super._deserialize(serializationObject, scene, rootUrl); - } - _deserializeOptions(options) { - var _a, _b, _c; - this._options = options; - this._code = options.code.join("\n") + "\n"; - this.name = this.name || options.name; - this.target = NodeMaterialBlockTargets[options.target]; - (_a = options.inParameters) === null || _a === void 0 ? void 0 : _a.forEach((input, index) => { - const type = NodeMaterialBlockConnectionPointTypes[input.type]; - if (input.type === "sampler2D" || input.type === "samplerCube") { - this._inputSamplers = this._inputSamplers || []; - this._inputSamplers.push(input.name); - this.registerInput(input.name, NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(input.name, this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, "ImageSourceBlock")); - } - else { - this.registerInput(input.name, type); - } - Object.defineProperty(this, input.name, { - get: function () { - return this._inputs[index]; - }, - enumerable: true, - configurable: true, - }); - }); - (_b = options.outParameters) === null || _b === void 0 ? void 0 : _b.forEach((output, index) => { - this.registerOutput(output.name, NodeMaterialBlockConnectionPointTypes[output.type]); - Object.defineProperty(this, output.name, { - get: function () { - return this._outputs[index]; - }, - enumerable: true, - configurable: true, - }); - if (output.type === "BasedOnInput") { - this._outputs[index]._typeConnectionSource = this._findInputByName(output.typeFromInput)[0]; - } - }); - (_c = options.inLinkedConnectionTypes) === null || _c === void 0 ? void 0 : _c.forEach((connection) => { - this._linkConnectionTypes(this._findInputByName(connection.input1)[1], this._findInputByName(connection.input2)[1]); - }); - } - _findInputByName(name) { - if (!name) { - return null; - } - for (let i = 0; i < this._inputs.length; i++) { - if (this._inputs[i].name === name) { - return [this._inputs[i], i]; - } - } - return null; - } -} -RegisterClass("BABYLON.CustomBlock", CustomBlock); -//# sourceMappingURL=customBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/dotBlock.js - - - - -/** - * Block used to apply a dot product between 2 vectors - */ -class DotBlock extends NodeMaterialBlock { - /** - * Creates a new DotBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); - this._linkConnectionTypes(0, 1); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "DotBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = dot(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.DotBlock", DotBlock); -//# sourceMappingURL=dotBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/normalizeBlock.js - - - - -/** - * Block used to normalize a vector - */ -class NormalizeBlock extends NodeMaterialBlock { - /** - * Creates a new NormalizeBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "NormalizeBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - const input = this._inputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = normalize(${input.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.NormalizeBlock", NormalizeBlock); -//# sourceMappingURL=normalizeBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/colorMergerBlock.js - - - - -/** - * Block used to create a Color3/4 out of individual inputs (one for each component) - */ -class ColorMergerBlock extends NodeMaterialBlock { - /** - * Create a new ColorMergerBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Gets or sets the swizzle for r (meaning which component to affect to the output.r) - */ - this.rSwizzle = "r"; - /** - * Gets or sets the swizzle for g (meaning which component to affect to the output.g) - */ - this.gSwizzle = "g"; - /** - * Gets or sets the swizzle for b (meaning which component to affect to the output.b) - */ - this.bSwizzle = "b"; - /** - * Gets or sets the swizzle for a (meaning which component to affect to the output.a) - */ - this.aSwizzle = "a"; - this.registerInput("rgb ", NodeMaterialBlockConnectionPointTypes.Color3, true); - this.registerInput("r", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("g", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("b", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4); - this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ColorMergerBlock"; - } - /** - * Gets the rgb component (input) - */ - get rgbIn() { - return this._inputs[0]; - } - /** - * Gets the r component (input) - */ - get r() { - return this._inputs[1]; - } - /** - * Gets the g component (input) - */ - get g() { - return this._inputs[2]; - } - /** - * Gets the b component (input) - */ - get b() { - return this._inputs[3]; - } - /** - * Gets the a component (input) - */ - get a() { - return this._inputs[4]; - } - /** - * Gets the rgba component (output) - */ - get rgba() { - return this._outputs[0]; - } - /** - * Gets the rgb component (output) - */ - get rgbOut() { - return this._outputs[1]; - } - /** - * Gets the rgb component (output) - * @deprecated Please use rgbOut instead. - */ - get rgb() { - return this.rgbOut; - } - _inputRename(name) { - if (name === "rgb ") { - return "rgbIn"; - } - return name; - } - _buildSwizzle(len) { - const swizzle = this.rSwizzle + this.gSwizzle + this.bSwizzle + this.aSwizzle; - return "." + swizzle.substr(0, len); - } - _buildBlock(state) { - super._buildBlock(state); - const rInput = this.r; - const gInput = this.g; - const bInput = this.b; - const aInput = this.a; - const rgbInput = this.rgbIn; - const color4Output = this._outputs[0]; - const color3Output = this._outputs[1]; - if (rgbInput.isConnected) { - if (color4Output.hasEndpoints) { - state.compilationString += - this._declareOutput(color4Output, state) + - ` = vec4(${rgbInput.associatedVariableName}, ${aInput.isConnected ? this._writeVariable(aInput) : "0.0"})${this._buildSwizzle(4)};\n`; - } - if (color3Output.hasEndpoints) { - state.compilationString += this._declareOutput(color3Output, state) + ` = ${rgbInput.associatedVariableName}${this._buildSwizzle(3)};\n`; - } - } - else { - if (color4Output.hasEndpoints) { - state.compilationString += - this._declareOutput(color4Output, state) + - ` = 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)};\n`; - } - if (color3Output.hasEndpoints) { - state.compilationString += - this._declareOutput(color3Output, state) + - ` = 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)};\n`; - } - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.rSwizzle = this.rSwizzle; - serializationObject.gSwizzle = this.gSwizzle; - serializationObject.bSwizzle = this.bSwizzle; - serializationObject.aSwizzle = this.aSwizzle; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - var _a, _b, _c, _d; - super._deserialize(serializationObject, scene, rootUrl); - this.rSwizzle = (_a = serializationObject.rSwizzle) !== null && _a !== void 0 ? _a : "r"; - this.gSwizzle = (_b = serializationObject.gSwizzle) !== null && _b !== void 0 ? _b : "g"; - this.bSwizzle = (_c = serializationObject.bSwizzle) !== null && _c !== void 0 ? _c : "b"; - this.aSwizzle = (_d = serializationObject.aSwizzle) !== null && _d !== void 0 ? _d : "a"; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.rSwizzle = "${this.rSwizzle}";\n`; - codeString += `${this._codeVariableName}.gSwizzle = "${this.gSwizzle}";\n`; - codeString += `${this._codeVariableName}.bSwizzle = "${this.bSwizzle}";\n`; - codeString += `${this._codeVariableName}.aSwizzle = "${this.aSwizzle}";\n`; - return codeString; - } -} -RegisterClass("BABYLON.ColorMergerBlock", ColorMergerBlock); -//# sourceMappingURL=colorMergerBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/vectorSplitterBlock.js - - - - -/** - * Block used to expand a Vector3/4 into 4 outputs (one for each component) - */ -class VectorSplitterBlock extends NodeMaterialBlock { - /** - * Create a new VectorSplitterBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("xyzw", NodeMaterialBlockConnectionPointTypes.Vector4, true); - this.registerInput("xyz ", NodeMaterialBlockConnectionPointTypes.Vector3, true); - this.registerInput("xy ", NodeMaterialBlockConnectionPointTypes.Vector2, true); - this.registerOutput("xyz", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerOutput("xy", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerOutput("zw", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("z", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("w", NodeMaterialBlockConnectionPointTypes.Float); - this.inputsAreExclusive = true; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "VectorSplitterBlock"; - } - /** - * Gets the xyzw component (input) - */ - get xyzw() { - return this._inputs[0]; - } - /** - * Gets the xyz component (input) - */ - get xyzIn() { - return this._inputs[1]; - } - /** - * Gets the xy component (input) - */ - get xyIn() { - return this._inputs[2]; - } - /** - * Gets the xyz component (output) - */ - get xyzOut() { - return this._outputs[0]; - } - /** - * Gets the xy component (output) - */ - get xyOut() { - return this._outputs[1]; - } - /** - * Gets the zw component (output) - */ - get zw() { - return this._outputs[2]; - } - /** - * Gets the x component (output) - */ - get x() { - return this._outputs[3]; - } - /** - * Gets the y component (output) - */ - get y() { - return this._outputs[4]; - } - /** - * Gets the z component (output) - */ - get z() { - return this._outputs[5]; - } - /** - * Gets the w component (output) - */ - get w() { - return this._outputs[6]; - } - _inputRename(name) { - switch (name) { - case "xy ": - return "xyIn"; - case "xyz ": - return "xyzIn"; - default: - return name; - } - } - _outputRename(name) { - switch (name) { - case "xy": - return "xyOut"; - case "xyz": - return "xyzOut"; - default: - return name; - } - } - _buildBlock(state) { - super._buildBlock(state); - const input = this.xyzw.isConnected ? this.xyzw : this.xyzIn.isConnected ? this.xyzIn : this.xyIn; - const xyzOutput = this._outputs[0]; - const xyOutput = this._outputs[1]; - const zwOutput = this._outputs[2]; - const xOutput = this._outputs[3]; - const yOutput = this._outputs[4]; - const zOutput = this._outputs[5]; - const wOutput = this._outputs[6]; - if (xyzOutput.hasEndpoints) { - if (input === this.xyIn) { - state.compilationString += this._declareOutput(xyzOutput, state) + ` = vec3(${input.associatedVariableName}, 0.0);\n`; - } - else { - state.compilationString += this._declareOutput(xyzOutput, state) + ` = ${input.associatedVariableName}.xyz;\n`; - } - } - if (zwOutput.hasEndpoints && this.xyzw.isConnected) { - state.compilationString += this._declareOutput(zwOutput, state) + ` = ${this.xyzw.associatedVariableName}.zw;\n`; - } - if (xyOutput.hasEndpoints) { - state.compilationString += this._declareOutput(xyOutput, state) + ` = ${input.associatedVariableName}.xy;\n`; - } - if (xOutput.hasEndpoints) { - state.compilationString += this._declareOutput(xOutput, state) + ` = ${input.associatedVariableName}.x;\n`; - } - if (yOutput.hasEndpoints) { - state.compilationString += this._declareOutput(yOutput, state) + ` = ${input.associatedVariableName}.y;\n`; - } - if (zOutput.hasEndpoints) { - state.compilationString += this._declareOutput(zOutput, state) + ` = ${input.associatedVariableName}.z;\n`; - } - if (wOutput.hasEndpoints) { - state.compilationString += this._declareOutput(wOutput, state) + ` = ${input.associatedVariableName}.w;\n`; - } - return this; - } -} -RegisterClass("BABYLON.VectorSplitterBlock", VectorSplitterBlock); -//# sourceMappingURL=vectorSplitterBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/lerpBlock.js - - - - -/** - * Block used to lerp between 2 values - */ -class LerpBlock extends NodeMaterialBlock { - /** - * Creates a new LerpBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - this._linkConnectionTypes(1, 2, true); - this._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "LerpBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the gradient operand input component - */ - get gradient() { - return this._inputs[2]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += - this._declareOutput(output, state) + ` = mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.LerpBlock", LerpBlock); -//# sourceMappingURL=lerpBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/divideBlock.js - - - - -/** - * Block used to divide 2 vectors - */ -class DivideBlock extends NodeMaterialBlock { - /** - * Creates a new DivideBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "DivideBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} / ${this.right.associatedVariableName};\n`; - return this; - } -} -RegisterClass("BABYLON.DivideBlock", DivideBlock); -//# sourceMappingURL=divideBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/subtractBlock.js - - - - -/** - * Block used to subtract 2 vectors - */ -class SubtractBlock extends NodeMaterialBlock { - /** - * Creates a new SubtractBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SubtractBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} - ${this.right.associatedVariableName};\n`; - return this; - } -} -RegisterClass("BABYLON.SubtractBlock", SubtractBlock); -//# sourceMappingURL=subtractBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/stepBlock.js - - - - -/** - * Block used to step a value - */ -class StepBlock extends NodeMaterialBlock { - /** - * Creates a new StepBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("value", NodeMaterialBlockConnectionPointTypes.Float); - this.registerInput("edge", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "StepBlock"; - } - /** - * Gets the value operand input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the edge operand input component - */ - get edge() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = step(${this.edge.associatedVariableName}, ${this.value.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.StepBlock", StepBlock); -//# sourceMappingURL=stepBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/oneMinusBlock.js - - - - -/** - * Block used to get the opposite (1 - x) of a value - */ -class OneMinusBlock extends NodeMaterialBlock { - /** - * Creates a new OneMinusBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "OneMinusBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = 1. - ${this.input.associatedVariableName};\n`; - return this; - } -} -RegisterClass("BABYLON.OneMinusBlock", OneMinusBlock); -RegisterClass("BABYLON.OppositeBlock", OneMinusBlock); // Backward compatibility -//# sourceMappingURL=oneMinusBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/viewDirectionBlock.js - - - - - - -/** - * Block used to get the view direction - */ -class ViewDirectionBlock extends NodeMaterialBlock { - /** - * Creates a new ViewDirectionBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ViewDirectionBlock"; - } - /** - * Gets the world position component - */ - get worldPosition() { - return this._inputs[0]; - } - /** - * Gets the camera position component - */ - get cameraPosition() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - autoConfigure(material) { - if (!this.cameraPosition.isConnected) { - let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition); - if (!cameraPositionInput) { - cameraPositionInput = new InputBlock("cameraPosition"); - cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition); - } - cameraPositionInput.output.connectTo(this.cameraPosition); - } - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += - this._declareOutput(output, state) + ` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\n`; - return this; - } -} -RegisterClass("BABYLON.ViewDirectionBlock", ViewDirectionBlock); -//# sourceMappingURL=viewDirectionBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/fresnelBlock.js - - - - - - - -/** - * Block used to compute fresnel value - */ -class FresnelBlock extends NodeMaterialBlock { - /** - * Create a new FresnelBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("viewDirection", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerInput("bias", NodeMaterialBlockConnectionPointTypes.Float); - this.registerInput("power", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("fresnel", NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "FresnelBlock"; - } - /** - * Gets the world normal input component - */ - get worldNormal() { - return this._inputs[0]; - } - /** - * Gets the view direction input component - */ - get viewDirection() { - return this._inputs[1]; - } - /** - * Gets the bias input component - */ - get bias() { - return this._inputs[2]; - } - /** - * Gets the camera (or eye) position component - */ - get power() { - return this._inputs[3]; - } - /** - * Gets the fresnel output component - */ - get fresnel() { - return this._outputs[0]; - } - autoConfigure(material) { - if (!this.viewDirection.isConnected) { - const viewDirectionInput = new ViewDirectionBlock("View direction"); - viewDirectionInput.output.connectTo(this.viewDirection); - viewDirectionInput.autoConfigure(material); - } - if (!this.bias.isConnected) { - const biasInput = new InputBlock("bias"); - biasInput.value = 0; - biasInput.output.connectTo(this.bias); - } - if (!this.power.isConnected) { - const powerInput = new InputBlock("power"); - powerInput.value = 1; - powerInput.output.connectTo(this.power); - } - } - _buildBlock(state) { - super._buildBlock(state); - const comments = `//${this.name}`; - state._emitFunctionFromInclude("fresnelFunction", comments, { removeIfDef: true }); - state.compilationString += - this._declareOutput(this.fresnel, state) + - ` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.FresnelBlock", FresnelBlock); -//# sourceMappingURL=fresnelBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/maxBlock.js - - - - -/** - * Block used to get the max of 2 values - */ -class MaxBlock extends NodeMaterialBlock { - /** - * Creates a new MaxBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MaxBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.MaxBlock", MaxBlock); -//# sourceMappingURL=maxBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/minBlock.js - - - - -/** - * Block used to get the min of 2 values - */ -class MinBlock extends NodeMaterialBlock { - /** - * Creates a new MinBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MinBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.MinBlock", MinBlock); -//# sourceMappingURL=minBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/distanceBlock.js - - - - -/** - * Block used to get the distance between 2 values - */ -class DistanceBlock extends NodeMaterialBlock { - /** - * Creates a new DistanceBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); - this._linkConnectionTypes(0, 1); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "DistanceBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.DistanceBlock", DistanceBlock); -//# sourceMappingURL=distanceBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/lengthBlock.js - - - - -/** - * Block used to get the length of a vector - */ -class LengthBlock extends NodeMaterialBlock { - /** - * Creates a new LengthBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "LengthBlock"; - } - /** - * Gets the value input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = length(${this.value.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.LengthBlock", LengthBlock); -//# sourceMappingURL=lengthBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/negateBlock.js - - - - -/** - * Block used to get negative version of a value (i.e. x * -1) - */ -class NegateBlock extends NodeMaterialBlock { - /** - * Creates a new NegateBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "NegateBlock"; - } - /** - * Gets the value input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = -1.0 * ${this.value.associatedVariableName};\n`; - return this; - } -} -RegisterClass("BABYLON.NegateBlock", NegateBlock); -//# sourceMappingURL=negateBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/powBlock.js - - - - -/** - * Block used to get the value of the first parameter raised to the power of the second - */ -class PowBlock extends NodeMaterialBlock { - /** - * Creates a new PowBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("power", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "PowBlock"; - } - /** - * Gets the value operand input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the power operand input component - */ - get power() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.PowBlock", PowBlock); -//# sourceMappingURL=powBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/randomNumberBlock.js - - - - - -/** - * Block used to get a random number - */ -class RandomNumberBlock extends NodeMaterialBlock { - /** - * Creates a new RandomNumberBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | - NodeMaterialBlockConnectionPointTypes.Vector3 | - NodeMaterialBlockConnectionPointTypes.Vector4 | - NodeMaterialBlockConnectionPointTypes.Color3 | - NodeMaterialBlockConnectionPointTypes.Color4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "RandomNumberBlock"; - } - /** - * Gets the seed input component - */ - get seed() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - const comments = `//${this.name}`; - state._emitFunctionFromInclude("helperFunctions", comments); - state.compilationString += this._declareOutput(output, state) + ` = getRand(${this.seed.associatedVariableName}.xy);\n`; - return this; - } -} -RegisterClass("BABYLON.RandomNumberBlock", RandomNumberBlock); -//# sourceMappingURL=randomNumberBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/arcTan2Block.js - - - - -/** - * Block used to compute arc tangent of 2 values - */ -class ArcTan2Block extends NodeMaterialBlock { - /** - * Creates a new ArcTan2Block - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("x", NodeMaterialBlockConnectionPointTypes.Float); - this.registerInput("y", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ArcTan2Block"; - } - /** - * Gets the x operand input component - */ - get x() { - return this._inputs[0]; - } - /** - * Gets the y operand input component - */ - get y() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.ArcTan2Block", ArcTan2Block); -//# sourceMappingURL=arcTan2Block.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/smoothStepBlock.js - - - - -/** - * Block used to smooth step a value - */ -class SmoothStepBlock extends NodeMaterialBlock { - /** - * Creates a new SmoothStepBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("edge0", NodeMaterialBlockConnectionPointTypes.Float); - this.registerInput("edge1", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SmoothStepBlock"; - } - /** - * Gets the value operand input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the first edge operand input component - */ - get edge0() { - return this._inputs[1]; - } - /** - * Gets the second edge operand input component - */ - get edge1() { - return this._inputs[2]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += - this._declareOutput(output, state) + - ` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.SmoothStepBlock", SmoothStepBlock); -//# sourceMappingURL=smoothStepBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/reciprocalBlock.js - - - - -/** - * Block used to get the reciprocal (1 / x) of a value - */ -class ReciprocalBlock extends NodeMaterialBlock { - /** - * Creates a new ReciprocalBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ReciprocalBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - if (this.input.type === NodeMaterialBlockConnectionPointTypes.Matrix) { - state.compilationString += this._declareOutput(output, state) + ` = inverse(${this.input.associatedVariableName});\n`; - } - else { - state.compilationString += this._declareOutput(output, state) + ` = 1. / ${this.input.associatedVariableName};\n`; - } - return this; - } -} -RegisterClass("BABYLON.ReciprocalBlock", ReciprocalBlock); -//# sourceMappingURL=reciprocalBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/replaceColorBlock.js - - - - -/** - * Block used to replace a color by another one - */ -class ReplaceColorBlock extends NodeMaterialBlock { - /** - * Creates a new ReplaceColorBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("reference", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("distance", NodeMaterialBlockConnectionPointTypes.Float); - this.registerInput("replacement", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - this._linkConnectionTypes(0, 3); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - this._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ReplaceColorBlock"; - } - /** - * Gets the value input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the reference input component - */ - get reference() { - return this._inputs[1]; - } - /** - * Gets the distance input component - */ - get distance() { - return this._inputs[2]; - } - /** - * Gets the replacement input component - */ - get replacement() { - return this._inputs[3]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + `;\n`; - state.compilationString += `if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\n`; - state.compilationString += `${output.associatedVariableName} = ${this.replacement.associatedVariableName};\n`; - state.compilationString += `} else {\n`; - state.compilationString += `${output.associatedVariableName} = ${this.value.associatedVariableName};\n`; - state.compilationString += `}\n`; - return this; - } -} -RegisterClass("BABYLON.ReplaceColorBlock", ReplaceColorBlock); -//# sourceMappingURL=replaceColorBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/posterizeBlock.js - - - - -/** - * Block used to posterize a value - * @see https://en.wikipedia.org/wiki/Posterization - */ -class PosterizeBlock extends NodeMaterialBlock { - /** - * Creates a new PosterizeBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("value", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("steps", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "PosterizeBlock"; - } - /** - * Gets the value input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the steps input component - */ - get steps() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += - this._declareOutput(output, state) + - ` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.PosterizeBlock", PosterizeBlock); -//# sourceMappingURL=posterizeBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/waveBlock.js - - - - -/** - * Operations supported by the Wave block - */ -var WaveBlockKind; -(function (WaveBlockKind) { - /** SawTooth */ - WaveBlockKind[WaveBlockKind["SawTooth"] = 0] = "SawTooth"; - /** Square */ - WaveBlockKind[WaveBlockKind["Square"] = 1] = "Square"; - /** Triangle */ - WaveBlockKind[WaveBlockKind["Triangle"] = 2] = "Triangle"; -})(WaveBlockKind || (WaveBlockKind = {})); -/** - * Block used to apply wave operation to floats - */ -class WaveBlock extends NodeMaterialBlock { - /** - * Creates a new WaveBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Gets or sets the kibnd of wave to be applied by the block - */ - this.kind = WaveBlockKind.SawTooth; - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "WaveBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - switch (this.kind) { - case WaveBlockKind.SawTooth: { - state.compilationString += this._declareOutput(output, state) + ` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\n`; - break; - } - case WaveBlockKind.Square: { - state.compilationString += this._declareOutput(output, state) + ` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\n`; - break; - } - case WaveBlockKind.Triangle: { - state.compilationString += - this._declareOutput(output, state) + ` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\n`; - break; - } - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.kind = this.kind; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.kind = serializationObject.kind; - } -} -RegisterClass("BABYLON.WaveBlock", WaveBlock); -//# sourceMappingURL=waveBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/gradientBlock.js - - - - - - -/** - * Class used to store a color step for the GradientBlock - */ -class GradientBlockColorStep { - /** - * Gets value indicating which step this color is associated with (between 0 and 1) - */ - get step() { - return this._step; - } - /** - * Sets a value indicating which step this color is associated with (between 0 and 1) - */ - set step(val) { - this._step = val; - } - /** - * Gets the color associated with this step - */ - get color() { - return this._color; - } - /** - * Sets the color associated with this step - */ - set color(val) { - this._color = val; - } - /** - * Creates a new GradientBlockColorStep - * @param step defines a value indicating which step this color is associated with (between 0 and 1) - * @param color defines the color associated with this step - */ - constructor(step, color) { - this.step = step; - this.color = color; - } -} -/** - * Block used to return a color from a gradient based on an input value between 0 and 1 - */ -class GradientBlock extends NodeMaterialBlock { - /** calls observable when the value is changed*/ - colorStepsUpdated() { - this.onValueChangedObservable.notifyObservers(this); - } - /** - * Creates a new GradientBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Gets or sets the list of color steps - */ - this.colorSteps = [new GradientBlockColorStep(0, math_color_Color3.Black()), new GradientBlockColorStep(1.0, math_color_Color3.White())]; - /** Gets an observable raised when the value is changed */ - this.onValueChangedObservable = new observable_Observable(); - this.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Float | - NodeMaterialBlockConnectionPointTypes.Vector2 | - NodeMaterialBlockConnectionPointTypes.Vector3 | - NodeMaterialBlockConnectionPointTypes.Vector4 | - NodeMaterialBlockConnectionPointTypes.Color3 | - NodeMaterialBlockConnectionPointTypes.Color4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "GradientBlock"; - } - /** - * Gets the gradient input component - */ - get gradient() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _writeColorConstant(index) { - const step = this.colorSteps[index]; - return `vec3(${step.color.r}, ${step.color.g}, ${step.color.b})`; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - if (!this.colorSteps.length || !this.gradient.connectedPoint) { - state.compilationString += this._declareOutput(output, state) + ` = vec3(0., 0., 0.);\n`; - return; - } - const tempColor = state._getFreeVariableName("gradientTempColor"); - const tempPosition = state._getFreeVariableName("gradientTempPosition"); - state.compilationString += `vec3 ${tempColor} = ${this._writeColorConstant(0)};\n`; - state.compilationString += `float ${tempPosition};\n`; - let gradientSource = this.gradient.associatedVariableName; - if (this.gradient.connectedPoint.type !== NodeMaterialBlockConnectionPointTypes.Float) { - gradientSource += ".x"; - } - for (let index = 1; index < this.colorSteps.length; index++) { - const step = this.colorSteps[index]; - const previousStep = this.colorSteps[index - 1]; - 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)});\n`; - state.compilationString += `${tempColor} = mix(${tempColor}, ${this._writeColorConstant(index)}, ${tempPosition});\n`; - } - state.compilationString += this._declareOutput(output, state) + ` = ${tempColor};\n`; - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.colorSteps = []; - for (const step of this.colorSteps) { - serializationObject.colorSteps.push({ - step: step.step, - color: { - r: step.color.r, - g: step.color.g, - b: step.color.b, - }, - }); - } - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.colorSteps.length = 0; - for (const step of serializationObject.colorSteps) { - this.colorSteps.push(new GradientBlockColorStep(step.step, new math_color_Color3(step.color.r, step.color.g, step.color.b))); - } - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.colorSteps = [];\n`; - for (const colorStep of this.colorSteps) { - codeString += `${this._codeVariableName}.colorSteps.push(new BABYLON.GradientBlockColorStep(${colorStep.step}, new BABYLON.Color3(${colorStep.color.r}, ${colorStep.color.g}, ${colorStep.color.b})));\n`; - } - return codeString; - } -} -RegisterClass("BABYLON.GradientBlock", GradientBlock); -//# sourceMappingURL=gradientBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/nLerpBlock.js - - - - -/** - * Block used to normalize lerp between 2 values - */ -class NLerpBlock extends NodeMaterialBlock { - /** - * Creates a new NLerpBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("gradient", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - this._linkConnectionTypes(1, 2, true); - this._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "NLerpBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the gradient operand input component - */ - get gradient() { - return this._inputs[2]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += - this._declareOutput(output, state) + - ` = normalize(mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName}));\n`; - return this; - } -} -RegisterClass("BABYLON.NLerpBlock", NLerpBlock); -//# sourceMappingURL=nLerpBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/worleyNoise3DBlock.js - - - - - - -/** - * block used to Generate a Worley Noise 3D Noise Pattern - */ -// Source: https://github.com/Erkaman/glsl-worley -// Converted to BJS by Pryme8 -// -// Worley Noise 3D -// Return vec2 value range of -1.0->1.0, F1-F2 respectivly -class WorleyNoise3DBlock extends NodeMaterialBlock { - /** - * Creates a new WorleyNoise3DBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** Gets or sets a boolean indicating that normal should be inverted on X axis */ - this.manhattanDistance = false; - this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerInput("jitter", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerOutput("x", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("y", NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "WorleyNoise3DBlock"; - } - /** - * Gets the seed input component - */ - get seed() { - return this._inputs[0]; - } - /** - * Gets the jitter input component - */ - get jitter() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets the x component - */ - get x() { - return this._outputs[1]; - } - /** - * Gets the y component - */ - get y() { - return this._outputs[2]; - } - _buildBlock(state) { - super._buildBlock(state); - if (!this.seed.isConnected) { - return; - } - if (!this.output.hasEndpoints && !this.x.hasEndpoints && !this.y.hasEndpoints) { - return; - } - let functionString = `vec3 permute(vec3 x){\n`; - functionString += ` return mod((34.0 * x + 1.0) * x, 289.0);\n`; - functionString += `}\n\n`; - functionString += `vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\n`; - functionString += ` return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z);\n`; - functionString += `}\n\n`; - functionString += `vec2 worley(vec3 P, float jitter, bool manhattanDistance){\n`; - functionString += ` float K = 0.142857142857; // 1/7\n`; - functionString += ` float Ko = 0.428571428571; // 1/2-K/2\n`; - functionString += ` float K2 = 0.020408163265306; // 1/(7*7)\n`; - functionString += ` float Kz = 0.166666666667; // 1/6\n`; - functionString += ` float Kzo = 0.416666666667; // 1/2-1/6*2\n`; - functionString += `\n`; - functionString += ` vec3 Pi = mod(floor(P), 289.0);\n`; - functionString += ` vec3 Pf = fract(P) - 0.5;\n`; - functionString += `\n`; - functionString += ` vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\n`; - functionString += ` vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\n`; - functionString += ` vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\n`; - functionString += `\n`; - functionString += ` vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\n`; - functionString += ` vec3 p1 = permute(p + Pi.y - 1.0);\n`; - functionString += ` vec3 p2 = permute(p + Pi.y);\n`; - functionString += ` vec3 p3 = permute(p + Pi.y + 1.0);\n`; - functionString += `\n`; - functionString += ` vec3 p11 = permute(p1 + Pi.z - 1.0);\n`; - functionString += ` vec3 p12 = permute(p1 + Pi.z);\n`; - functionString += ` vec3 p13 = permute(p1 + Pi.z + 1.0);\n`; - functionString += `\n`; - functionString += ` vec3 p21 = permute(p2 + Pi.z - 1.0);\n`; - functionString += ` vec3 p22 = permute(p2 + Pi.z);\n`; - functionString += ` vec3 p23 = permute(p2 + Pi.z + 1.0);\n`; - functionString += `\n`; - functionString += ` vec3 p31 = permute(p3 + Pi.z - 1.0);\n`; - functionString += ` vec3 p32 = permute(p3 + Pi.z);\n`; - functionString += ` vec3 p33 = permute(p3 + Pi.z + 1.0);\n`; - functionString += `\n`; - functionString += ` vec3 ox11 = fract(p11*K) - Ko;\n`; - functionString += ` vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\n`; - functionString += ` vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\n`; - functionString += `\n`; - functionString += ` vec3 ox12 = fract(p12*K) - Ko;\n`; - functionString += ` vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\n`; - functionString += ` vec3 oz12 = floor(p12*K2)*Kz - Kzo;\n`; - functionString += `\n`; - functionString += ` vec3 ox13 = fract(p13*K) - Ko;\n`; - functionString += ` vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\n`; - functionString += ` vec3 oz13 = floor(p13*K2)*Kz - Kzo;\n`; - functionString += `\n`; - functionString += ` vec3 ox21 = fract(p21*K) - Ko;\n`; - functionString += ` vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\n`; - functionString += ` vec3 oz21 = floor(p21*K2)*Kz - Kzo;\n`; - functionString += `\n`; - functionString += ` vec3 ox22 = fract(p22*K) - Ko;\n`; - functionString += ` vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\n`; - functionString += ` vec3 oz22 = floor(p22*K2)*Kz - Kzo;\n`; - functionString += `\n`; - functionString += ` vec3 ox23 = fract(p23*K) - Ko;\n`; - functionString += ` vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\n`; - functionString += ` vec3 oz23 = floor(p23*K2)*Kz - Kzo;\n`; - functionString += `\n`; - functionString += ` vec3 ox31 = fract(p31*K) - Ko;\n`; - functionString += ` vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\n`; - functionString += ` vec3 oz31 = floor(p31*K2)*Kz - Kzo;\n`; - functionString += `\n`; - functionString += ` vec3 ox32 = fract(p32*K) - Ko;\n`; - functionString += ` vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\n`; - functionString += ` vec3 oz32 = floor(p32*K2)*Kz - Kzo;\n`; - functionString += `\n`; - functionString += ` vec3 ox33 = fract(p33*K) - Ko;\n`; - functionString += ` vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\n`; - functionString += ` vec3 oz33 = floor(p33*K2)*Kz - Kzo;\n`; - functionString += `\n`; - functionString += ` vec3 dx11 = Pfx + jitter*ox11;\n`; - functionString += ` vec3 dy11 = Pfy.x + jitter*oy11;\n`; - functionString += ` vec3 dz11 = Pfz.x + jitter*oz11;\n`; - functionString += `\n`; - functionString += ` vec3 dx12 = Pfx + jitter*ox12;\n`; - functionString += ` vec3 dy12 = Pfy.x + jitter*oy12;\n`; - functionString += ` vec3 dz12 = Pfz.y + jitter*oz12;\n`; - functionString += `\n`; - functionString += ` vec3 dx13 = Pfx + jitter*ox13;\n`; - functionString += ` vec3 dy13 = Pfy.x + jitter*oy13;\n`; - functionString += ` vec3 dz13 = Pfz.z + jitter*oz13;\n`; - functionString += `\n`; - functionString += ` vec3 dx21 = Pfx + jitter*ox21;\n`; - functionString += ` vec3 dy21 = Pfy.y + jitter*oy21;\n`; - functionString += ` vec3 dz21 = Pfz.x + jitter*oz21;\n`; - functionString += `\n`; - functionString += ` vec3 dx22 = Pfx + jitter*ox22;\n`; - functionString += ` vec3 dy22 = Pfy.y + jitter*oy22;\n`; - functionString += ` vec3 dz22 = Pfz.y + jitter*oz22;\n`; - functionString += `\n`; - functionString += ` vec3 dx23 = Pfx + jitter*ox23;\n`; - functionString += ` vec3 dy23 = Pfy.y + jitter*oy23;\n`; - functionString += ` vec3 dz23 = Pfz.z + jitter*oz23;\n`; - functionString += `\n`; - functionString += ` vec3 dx31 = Pfx + jitter*ox31;\n`; - functionString += ` vec3 dy31 = Pfy.z + jitter*oy31;\n`; - functionString += ` vec3 dz31 = Pfz.x + jitter*oz31;\n`; - functionString += `\n`; - functionString += ` vec3 dx32 = Pfx + jitter*ox32;\n`; - functionString += ` vec3 dy32 = Pfy.z + jitter*oy32;\n`; - functionString += ` vec3 dz32 = Pfz.y + jitter*oz32;\n`; - functionString += `\n`; - functionString += ` vec3 dx33 = Pfx + jitter*ox33;\n`; - functionString += ` vec3 dy33 = Pfy.z + jitter*oy33;\n`; - functionString += ` vec3 dz33 = Pfz.z + jitter*oz33;\n`; - functionString += `\n`; - functionString += ` vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\n`; - functionString += ` vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\n`; - functionString += ` vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\n`; - functionString += ` vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\n`; - functionString += ` vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\n`; - functionString += ` vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\n`; - functionString += ` vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\n`; - functionString += ` vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\n`; - functionString += ` vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\n`; - functionString += `\n`; - functionString += ` vec3 d1a = min(d11, d12);\n`; - functionString += ` d12 = max(d11, d12);\n`; - functionString += ` d11 = min(d1a, d13); // Smallest now not in d12 or d13\n`; - functionString += ` d13 = max(d1a, d13);\n`; - functionString += ` d12 = min(d12, d13); // 2nd smallest now not in d13\n`; - functionString += ` vec3 d2a = min(d21, d22);\n`; - functionString += ` d22 = max(d21, d22);\n`; - functionString += ` d21 = min(d2a, d23); // Smallest now not in d22 or d23\n`; - functionString += ` d23 = max(d2a, d23);\n`; - functionString += ` d22 = min(d22, d23); // 2nd smallest now not in d23\n`; - functionString += ` vec3 d3a = min(d31, d32);\n`; - functionString += ` d32 = max(d31, d32);\n`; - functionString += ` d31 = min(d3a, d33); // Smallest now not in d32 or d33\n`; - functionString += ` d33 = max(d3a, d33);\n`; - functionString += ` d32 = min(d32, d33); // 2nd smallest now not in d33\n`; - functionString += ` vec3 da = min(d11, d21);\n`; - functionString += ` d21 = max(d11, d21);\n`; - functionString += ` d11 = min(da, d31); // Smallest now in d11\n`; - functionString += ` d31 = max(da, d31); // 2nd smallest now not in d31\n`; - functionString += ` d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\n`; - functionString += ` d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\n`; - functionString += ` d12 = min(d12, d21); // 2nd smallest now not in d21\n`; - functionString += ` d12 = min(d12, d22); // nor in d22\n`; - functionString += ` d12 = min(d12, d31); // nor in d31\n`; - functionString += ` d12 = min(d12, d32); // nor in d32\n`; - functionString += ` d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\n`; - functionString += ` d11.y = min(d11.y,d12.z); // Only two more to go\n`; - functionString += ` d11.y = min(d11.y,d11.z); // Done! (Phew!)\n`; - functionString += ` return sqrt(d11.xy); // F1, F2\n`; - functionString += `}\n\n`; - state._emitFunction("worley3D", functionString, "// Worley3D"); - const tempVariable = state._getFreeVariableName("worleyTemp"); - state.compilationString += `vec2 ${tempVariable} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance});\n`; - if (this.output.hasEndpoints) { - state.compilationString += this._declareOutput(this.output, state) + ` = ${tempVariable};\n`; - } - if (this.x.hasEndpoints) { - state.compilationString += this._declareOutput(this.x, state) + ` = ${tempVariable}.x;\n`; - } - if (this.y.hasEndpoints) { - state.compilationString += this._declareOutput(this.y, state) + ` = ${tempVariable}.y;\n`; - } - return this; - } - /** - * Exposes the properties to the UI? - */ - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance};\n`; - return codeString; - } - /** - * Exposes the properties to the Serialize? - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.manhattanDistance = this.manhattanDistance; - return serializationObject; - } - /** - * Exposes the properties to the deserialize? - * @param serializationObject - * @param scene - * @param rootUrl - */ - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.manhattanDistance = serializationObject.manhattanDistance; - } -} -__decorate([ - editableInPropertyPage("Use Manhattan Distance", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: false } }) -], WorleyNoise3DBlock.prototype, "manhattanDistance", void 0); -RegisterClass("BABYLON.WorleyNoise3DBlock", WorleyNoise3DBlock); -//# sourceMappingURL=worleyNoise3DBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/simplexPerlin3DBlock.js - - - - -/** - * block used to Generate a Simplex Perlin 3d Noise Pattern - */ -// -// Wombat -// An efficient texture-free GLSL procedural noise library -// Source: https://github.com/BrianSharpe/Wombat -// Derived from: https://github.com/BrianSharpe/GPU-Noise-Lib -// -// I'm not one for copyrights. Use the code however you wish. -// All I ask is that credit be given back to the blog or myself when appropriate. -// And also to let me know if you come up with any changes, improvements, thoughts or interesting uses for this stuff. :) -// Thanks! -// -// Brian Sharpe -// brisharpe CIRCLE_A yahoo DOT com -// http://briansharpe.wordpress.com -// https://github.com/BrianSharpe -// -// -// This is a modified version of Stefan Gustavson's and Ian McEwan's work at http://github.com/ashima/webgl-noise -// Modifications are... -// - faster random number generation -// - analytical final normalization -// - space scaled can have an approx feature size of 1.0 -// - filter kernel changed to fix discontinuities at tetrahedron boundaries -// -// Converted to BJS by Pryme8 -// -// Simplex Perlin Noise 3D -// Return value range of -1.0->1.0 -// -class SimplexPerlin3DBlock extends NodeMaterialBlock { - /** - * Creates a new SimplexPerlin3DBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SimplexPerlin3DBlock"; - } - /** - * Gets the seed operand input component - */ - get seed() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - if (!this.seed.isConnected) { - return; - } - if (!this._outputs[0].hasEndpoints) { - return; - } - let functionString = `const float SKEWFACTOR = 1.0/3.0;\n`; - functionString += `const float UNSKEWFACTOR = 1.0/6.0;\n`; - functionString += `const float SIMPLEX_CORNER_POS = 0.5;\n`; - functionString += `const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\n`; - functionString += `float SimplexPerlin3D( vec3 P ){\n`; - functionString += ` P.x = P == vec3(0., 0., 0.) ? 0.00001 : P.x;\n`; - functionString += ` P *= SIMPLEX_TETRAHADRON_HEIGHT;\n`; - functionString += ` vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );`; - functionString += ` vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\n`; - functionString += ` vec3 g = step(x0.yzx, x0.xyz);\n`; - functionString += ` vec3 l = 1.0 - g;\n`; - functionString += ` vec3 Pi_1 = min( g.xyz, l.zxy );\n`; - functionString += ` vec3 Pi_2 = max( g.xyz, l.zxy );\n`; - functionString += ` vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\n`; - functionString += ` vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\n`; - functionString += ` vec3 x3 = x0 - SIMPLEX_CORNER_POS;\n`; - functionString += ` vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\n`; - functionString += ` vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\n`; - functionString += ` vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\n`; - functionString += ` Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\n`; - functionString += ` vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\n`; - functionString += ` vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\n`; - functionString += ` Pt *= Pt;\n`; - functionString += ` vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\n`; - functionString += ` Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\n`; - functionString += ` const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\n`; - functionString += ` const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\n`; - functionString += ` vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\n`; - functionString += ` vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\n`; - functionString += ` Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\n`; - functionString += ` Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\n`; - functionString += ` vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\n`; - functionString += ` vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\n`; - functionString += ` vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\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 );\n`; - functionString += ` const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\n`; - functionString += ` vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\n`; - functionString += ` kernel_weights = max(0.5 - kernel_weights, 0.0);\n`; - functionString += ` kernel_weights = kernel_weights*kernel_weights*kernel_weights;\n`; - functionString += ` return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\n`; - functionString += `}\n`; - state._emitFunction("SimplexPerlin3D", functionString, "// SimplexPerlin3D"); - state.compilationString += this._declareOutput(this._outputs[0], state) + ` = SimplexPerlin3D(${this.seed.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.SimplexPerlin3DBlock", SimplexPerlin3DBlock); -//# sourceMappingURL=simplexPerlin3DBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/normalBlendBlock.js - - - - -/** - * Block used to blend normals - */ -class NormalBlendBlock extends NodeMaterialBlock { - /** - * Creates a new NormalBlendBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("normalMap0", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("normalMap1", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | - NodeMaterialBlockConnectionPointTypes.Color4 | - NodeMaterialBlockConnectionPointTypes.Vector3 | - NodeMaterialBlockConnectionPointTypes.Vector4); - this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | - NodeMaterialBlockConnectionPointTypes.Color4 | - NodeMaterialBlockConnectionPointTypes.Vector3 | - NodeMaterialBlockConnectionPointTypes.Vector4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "NormalBlendBlock"; - } - /** - * Gets the first input component - */ - get normalMap0() { - return this._inputs[0]; - } - /** - * Gets the second input component - */ - get normalMap1() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - const input0 = this._inputs[0]; - const input1 = this._inputs[1]; - const stepR = state._getFreeVariableName("stepR"); - const stepG = state._getFreeVariableName("stepG"); - state.compilationString += `float ${stepR} = step(0.5, ${input0.associatedVariableName}.r);\n`; - state.compilationString += `float ${stepG} = step(0.5, ${input0.associatedVariableName}.g);\n`; - state.compilationString += this._declareOutput(output, state) + `;\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);\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);\n`; - state.compilationString += `${output.associatedVariableName}.b = ${input0.associatedVariableName}.b * ${input1.associatedVariableName}.b;\n`; - return this; - } -} -RegisterClass("BABYLON.NormalBlendBlock", NormalBlendBlock); -//# sourceMappingURL=normalBlendBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/rotate2dBlock.js - - - - - -/** - * Block used to rotate a 2d vector by a given angle - */ -class Rotate2dBlock extends NodeMaterialBlock { - /** - * Creates a new Rotate2dBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerInput("angle", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector2); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "Rotate2dBlock"; - } - /** - * Gets the input vector - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the input angle - */ - get angle() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.angle.isConnected) { - const angleInput = new InputBlock("angle"); - angleInput.value = 0; - angleInput.output.connectTo(this.angle); - } - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - const angle = this.angle; - const input = this.input; - state.compilationString += - this._declareOutput(output, state) + - ` = 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);\n`; - return this; - } -} -RegisterClass("BABYLON.Rotate2dBlock", Rotate2dBlock); -//# sourceMappingURL=rotate2dBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/reflectBlock.js - - - - -/** - * Block used to get the reflected vector from a direction and a normal - */ -class ReflectBlock extends NodeMaterialBlock { - /** - * Creates a new ReflectBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("incident", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | - NodeMaterialBlockConnectionPointTypes.Vector4 | - NodeMaterialBlockConnectionPointTypes.Color3 | - NodeMaterialBlockConnectionPointTypes.Color4); - this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | - NodeMaterialBlockConnectionPointTypes.Vector4 | - NodeMaterialBlockConnectionPointTypes.Color3 | - NodeMaterialBlockConnectionPointTypes.Color4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ReflectBlock"; - } - /** - * Gets the incident component - */ - get incident() { - return this._inputs[0]; - } - /** - * Gets the normal component - */ - get normal() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz);\n`; - return this; - } -} -RegisterClass("BABYLON.ReflectBlock", ReflectBlock); -//# sourceMappingURL=reflectBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/refractBlock.js - - - - -/** - * Block used to get the refracted vector from a direction and a normal - */ -class RefractBlock extends NodeMaterialBlock { - /** - * Creates a new RefractBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("incident", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("ior", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Vector3); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | - NodeMaterialBlockConnectionPointTypes.Vector4 | - NodeMaterialBlockConnectionPointTypes.Color3 | - NodeMaterialBlockConnectionPointTypes.Color4); - this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 | - NodeMaterialBlockConnectionPointTypes.Vector4 | - NodeMaterialBlockConnectionPointTypes.Color3 | - NodeMaterialBlockConnectionPointTypes.Color4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "RefractBlock"; - } - /** - * Gets the incident component - */ - get incident() { - return this._inputs[0]; - } - /** - * Gets the normal component - */ - get normal() { - return this._inputs[1]; - } - /** - * Gets the index of refraction component - */ - get ior() { - return this._inputs[2]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += - this._declareOutput(output, state) + - ` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.RefractBlock", RefractBlock); -//# sourceMappingURL=refractBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/desaturateBlock.js - - - - -/** - * Block used to desaturate a color - */ -class DesaturateBlock extends NodeMaterialBlock { - /** - * Creates a new DesaturateBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3); - this.registerInput("level", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Color3); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "DesaturateBlock"; - } - /** - * Gets the color operand input component - */ - get color() { - return this._inputs[0]; - } - /** - * Gets the level operand input component - */ - get level() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - const color = this.color; - const colorName = color.associatedVariableName; - const tempMin = state._getFreeVariableName("colorMin"); - const tempMax = state._getFreeVariableName("colorMax"); - const tempMerge = state._getFreeVariableName("colorMerge"); - state.compilationString += `float ${tempMin} = min(min(${colorName}.x, ${colorName}.y), ${colorName}.z);\n`; - state.compilationString += `float ${tempMax} = max(max(${colorName}.x, ${colorName}.y), ${colorName}.z);\n`; - state.compilationString += `float ${tempMerge} = 0.5 * (${tempMin} + ${tempMax});\n`; - state.compilationString += - this._declareOutput(output, state) + ` = mix(${colorName}, vec3(${tempMerge}, ${tempMerge}, ${tempMerge}), ${this.level.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.DesaturateBlock", DesaturateBlock); -//# sourceMappingURL=desaturateBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/sheenBlock.js - - - - - - - - -/** - * Block used to implement the sheen module of the PBR material - */ -class SheenBlock extends NodeMaterialBlock { - /** - * Create a new SheenBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - /** - * If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique. - * It allows the strength of the sheen effect to not depend on the base color of the material, - * making it easier to setup and tweak the effect - */ - this.albedoScaling = false; - /** - * Defines if the sheen is linked to the sheen color. - */ - this.linkSheenWithAlbedo = false; - this._isUnique = true; - this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerOutput("sheen", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("sheen", this, NodeMaterialConnectionPointDirection.Output, SheenBlock, "SheenBlock")); - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("sheenOut"); - state._excludeVariableName("sheenMapData"); - state._excludeVariableName("vSheenColor"); - state._excludeVariableName("vSheenRoughness"); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SheenBlock"; - } - /** - * Gets the intensity input component - */ - get intensity() { - return this._inputs[0]; - } - /** - * Gets the color input component - */ - get color() { - return this._inputs[1]; - } - /** - * Gets the roughness input component - */ - get roughness() { - return this._inputs[2]; - } - /** - * Gets the sheen object output component - */ - get sheen() { - return this._outputs[0]; - } - prepareDefines(mesh, nodeMaterial, defines) { - super.prepareDefines(mesh, nodeMaterial, defines); - defines.setValue("SHEEN", true); - defines.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE", true, true); - defines.setValue("SHEEN_LINKWITHALBEDO", this.linkSheenWithAlbedo, true); - defines.setValue("SHEEN_ROUGHNESS", this.roughness.isConnected, true); - defines.setValue("SHEEN_ALBEDOSCALING", this.albedoScaling, true); - } - /** - * Gets the main code of the block (fragment side) - * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module - * @returns the shader code - */ - getCode(reflectionBlock) { - let code = ""; - const color = this.color.isConnected ? this.color.associatedVariableName : "vec3(1.)"; - const intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : "1."; - const roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : "0."; - const texture = "vec4(0.)"; - code = `#ifdef SHEEN - sheenOutParams sheenOut; - - vec4 vSheenColor = vec4(${color}, ${intensity}); - - sheenBlock( - vSheenColor, - #ifdef SHEEN_ROUGHNESS - ${roughness}, - #endif - roughness, - #ifdef SHEEN_TEXTURE - ${texture}, - 1.0, - #endif - reflectance, - #ifdef SHEEN_LINKWITHALBEDO - baseColor, - surfaceAlbedo, - #endif - #ifdef ENVIRONMENTBRDF - NdotV, - environmentBrdf, - #endif - #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) - AARoughnessFactors, - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionMicrosurfaceInfosName}, - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionInfosName}, - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.reflectionColor}, - vLightingIntensity, - #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName} - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName}, - #else - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName}, - #endif - reflectionOut.reflectionCoords, - NdotVUnclamped, - #ifndef LODBASEDMICROSFURACE - #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName} - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName}, - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName}, - #else - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName}, - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName}, - #endif - #endif - #if !defined(${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName}) && defined(RADIANCEOCCLUSION) - seo, - #endif - #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}) - eho, - #endif - #endif - sheenOut - ); - - #ifdef SHEEN_LINKWITHALBEDO - surfaceAlbedo = sheenOut.surfaceAlbedo; - #endif - #endif\n`; - return code; - } - _buildBlock(state) { - if (state.target === NodeMaterialBlockTargets.Fragment) { - state.sharedData.blocksWithDefines.push(this); - } - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.albedoScaling = ${this.albedoScaling};\n`; - codeString += `${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.albedoScaling = this.albedoScaling; - serializationObject.linkSheenWithAlbedo = this.linkSheenWithAlbedo; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.albedoScaling = serializationObject.albedoScaling; - this.linkSheenWithAlbedo = serializationObject.linkSheenWithAlbedo; - } -} -__decorate([ - editableInPropertyPage("Albedo scaling", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: true } }) -], SheenBlock.prototype, "albedoScaling", void 0); -__decorate([ - editableInPropertyPage("Link sheen with albedo", PropertyTypeForEdition.Boolean, "PROPERTIES", { notifiers: { update: true } }) -], SheenBlock.prototype, "linkSheenWithAlbedo", void 0); -RegisterClass("BABYLON.SheenBlock", SheenBlock); -//# sourceMappingURL=sheenBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/anisotropyBlock.js - - - - - - - -/** - * Block used to implement the anisotropy module of the PBR material - */ -class AnisotropyBlock extends NodeMaterialBlock { - /** - * Create a new AnisotropyBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this._tangentCorrectionFactorName = ""; - this._isUnique = true; - this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("direction", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Fragment); - 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 - this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, true); - this.registerInput("TBN", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("TBN", this, NodeMaterialConnectionPointDirection.Input, TBNBlock, "TBNBlock")); - this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerOutput("anisotropy", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("anisotropy", this, NodeMaterialConnectionPointDirection.Output, AnisotropyBlock, "AnisotropyBlock")); - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("anisotropicOut"); - state._excludeVariableName("TBN"); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "AnisotropyBlock"; - } - /** - * Gets the intensity input component - */ - get intensity() { - return this._inputs[0]; - } - /** - * Gets the direction input component - */ - get direction() { - return this._inputs[1]; - } - /** - * Gets the uv input component - */ - get uv() { - return this._inputs[2]; - } - /** - * Gets the worldTangent input component - */ - get worldTangent() { - return this._inputs[3]; - } - /** - * Gets the TBN input component - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - get TBN() { - return this._inputs[4]; - } - /** - * Gets the roughness input component - */ - get roughness() { - return this._inputs[5]; - } - /** - * Gets the anisotropy object output component - */ - get anisotropy() { - return this._outputs[0]; - } - _generateTBNSpace(state) { - let code = ""; - const comments = `//${this.name}`; - const uv = this.uv; - const worldPosition = this.worldPositionConnectionPoint; - const worldNormal = this.worldNormalConnectionPoint; - const worldTangent = this.worldTangent; - if (!uv.isConnected) { - // 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) - // 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 - // it will stop the building of the node material and will lead to errors in the editor! - console.error("You must connect the 'uv' input of the Anisotropy block!"); - } - state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); - const tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" }; - const TBN = this.TBN; - if (TBN.isConnected) { - state.compilationString += ` - #ifdef TBNBLOCK - mat3 vTBN = ${TBN.associatedVariableName}; - #endif - `; - } - else if (worldTangent.isConnected) { - code += `vec3 tbnNormal = normalize(${worldNormal.associatedVariableName}.xyz);\n`; - code += `vec3 tbnTangent = normalize(${worldTangent.associatedVariableName}.xyz);\n`; - code += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`; - code += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\n`; - } - code += ` - #if defined(${worldTangent.isConnected ? "TANGENT" : "IGNORE"}) && defined(NORMAL) - mat3 TBN = vTBN; - #else - mat3 TBN = cotangent_frame(${worldNormal.associatedVariableName + ".xyz"}, ${"v_" + worldPosition.associatedVariableName + ".xyz"}, ${uv.isConnected ? uv.associatedVariableName : "vec2(0.)"}, vec2(1., 1.)); - #endif\n`; - state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, { - replaceStrings: [tangentReplaceString], - }); - return code; - } - /** - * Gets the main code of the block (fragment side) - * @param state current state of the node material building - * @param generateTBNSpace if true, the code needed to create the TBN coordinate space is generated - * @returns the shader code - */ - getCode(state, generateTBNSpace = false) { - let code = ""; - if (generateTBNSpace) { - code += this._generateTBNSpace(state); - } - const intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : "1.0"; - const direction = this.direction.isConnected ? this.direction.associatedVariableName : "vec2(1., 0.)"; - const roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : "0."; - code += `anisotropicOutParams anisotropicOut; - anisotropicBlock( - vec3(${direction}, ${intensity}), - ${roughness}, - #ifdef ANISOTROPIC_TEXTURE - vec3(0.), - #endif - TBN, - normalW, - viewDirectionW, - anisotropicOut - );\n`; - return code; - } - prepareDefines(mesh, nodeMaterial, defines) { - super.prepareDefines(mesh, nodeMaterial, defines); - defines.setValue("ANISOTROPIC", true); - defines.setValue("ANISOTROPIC_TEXTURE", false, true); - defines.setValue("ANISOTROPIC_LEGACY", !this.roughness.isConnected); - } - bind(effect, nodeMaterial, mesh) { - super.bind(effect, nodeMaterial, mesh); - if (mesh) { - effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1); - } - } - _buildBlock(state) { - if (state.target === NodeMaterialBlockTargets.Fragment) { - state.sharedData.blocksWithDefines.push(this); - state.sharedData.bindableBlocks.push(this); - this._tangentCorrectionFactorName = state._getFreeDefineName("tangentCorrectionFactor"); - state._emitUniformFromString(this._tangentCorrectionFactorName, "float"); - } - return this; - } -} -RegisterClass("BABYLON.AnisotropyBlock", AnisotropyBlock); -//# sourceMappingURL=anisotropyBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/reflectionBlock.js - - - - - - - - - - -/** - * Block used to implement the reflection module of the PBR material - */ -class ReflectionBlock extends ReflectionTextureBaseBlock { - _onGenerateOnlyFragmentCodeChanged() { - if (this.position.isConnected) { - this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode; - console.error("The position input must not be connected to be able to switch!"); - return false; - } - this._setTarget(); - return true; - } - _setTarget() { - super._setTarget(); - this.getInputByName("position").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; - if (this.generateOnlyFragmentCode) { - this.forceIrradianceInFragment = true; - } - } - /** - * Create a new ReflectionBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Defines if the material uses spherical harmonics vs spherical polynomials for the - * diffuse part of the IBL. - */ - this.useSphericalHarmonics = true; - /** - * Force the shader to compute irradiance in the fragment shader in order to take bump in account. - */ - this.forceIrradianceInFragment = false; - this._isUnique = true; - this.registerInput("position", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Vertex); - this.registerInput("world", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex); - this.registerInput("color", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); - this.registerOutput("reflection", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("reflection", this, NodeMaterialConnectionPointDirection.Output, ReflectionBlock, "ReflectionBlock")); - this.position.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ReflectionBlock"; - } - /** - * Gets the position input component - */ - get position() { - return this._inputs[0]; - } - /** - * Gets the world position input component - */ - get worldPosition() { - return this.worldPositionConnectionPoint; - } - /** - * Gets the world normal input component - */ - get worldNormal() { - return this.worldNormalConnectionPoint; - } - /** - * Gets the world input component - */ - get world() { - return this._inputs[1]; - } - /** - * Gets the camera (or eye) position component - */ - get cameraPosition() { - return this.cameraPositionConnectionPoint; - } - /** - * Gets the view input component - */ - get view() { - return this.viewConnectionPoint; - } - /** - * Gets the color input component - */ - get color() { - return this._inputs[2]; - } - /** - * Gets the reflection object output component - */ - get reflection() { - return this._outputs[0]; - } - /** - * Returns true if the block has a texture (either its own texture or the environment texture from the scene, if set) - */ - get hasTexture() { - return !!this._getTexture(); - } - /** - * Gets the reflection color (either the name of the variable if the color input is connected, else a default value) - */ - get reflectionColor() { - return this.color.isConnected ? this.color.associatedVariableName : "vec3(1., 1., 1.)"; - } - _getTexture() { - if (this.texture) { - return this.texture; - } - return this._scene.environmentTexture; - } - prepareDefines(mesh, nodeMaterial, defines) { - super.prepareDefines(mesh, nodeMaterial, defines); - const reflectionTexture = this._getTexture(); - const reflection = reflectionTexture && reflectionTexture.getTextureMatrix; - defines.setValue("REFLECTION", reflection, true); - if (!reflection) { - return; - } - defines.setValue(this._defineLODReflectionAlpha, reflectionTexture.lodLevelInAlpha, true); - defines.setValue(this._defineLinearSpecularReflection, reflectionTexture.linearSpecularLOD, true); - defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ, true); - defines.setValue("SPHERICAL_HARMONICS", this.useSphericalHarmonics, true); - defines.setValue("GAMMAREFLECTION", reflectionTexture.gammaSpace, true); - defines.setValue("RGBDREFLECTION", reflectionTexture.isRGBD, true); - if (reflectionTexture && reflectionTexture.coordinatesMode !== texture_Texture.SKYBOX_MODE) { - if (reflectionTexture.isCube) { - defines.setValue("USESPHERICALFROMREFLECTIONMAP", true); - defines.setValue("USEIRRADIANCEMAP", false); - if (this.forceIrradianceInFragment || this._scene.getEngine().getCaps().maxVaryingVectors <= 8) { - defines.setValue("USESPHERICALINVERTEX", false); - } - else { - defines.setValue("USESPHERICALINVERTEX", true); - } - } - } - } - bind(effect, nodeMaterial, mesh, subMesh) { - super.bind(effect, nodeMaterial, mesh); - const reflectionTexture = this._getTexture(); - if (!reflectionTexture || !subMesh) { - return; - } - if (reflectionTexture.isCube) { - effect.setTexture(this._cubeSamplerName, reflectionTexture); - } - else { - effect.setTexture(this._2DSamplerName, reflectionTexture); - } - const width = reflectionTexture.getSize().width; - effect.setFloat3(this._vReflectionMicrosurfaceInfosName, width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); - effect.setFloat2(this._vReflectionFilteringInfoName, width, math_scalar_Scalar.Log2(width)); - const defines = subMesh.materialDefines; - const polynomials = reflectionTexture.sphericalPolynomial; - if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) { - if (defines.SPHERICAL_HARMONICS) { - const preScaledHarmonics = polynomials.preScaledHarmonics; - effect.setVector3("vSphericalL00", preScaledHarmonics.l00); - effect.setVector3("vSphericalL1_1", preScaledHarmonics.l1_1); - effect.setVector3("vSphericalL10", preScaledHarmonics.l10); - effect.setVector3("vSphericalL11", preScaledHarmonics.l11); - effect.setVector3("vSphericalL2_2", preScaledHarmonics.l2_2); - effect.setVector3("vSphericalL2_1", preScaledHarmonics.l2_1); - effect.setVector3("vSphericalL20", preScaledHarmonics.l20); - effect.setVector3("vSphericalL21", preScaledHarmonics.l21); - effect.setVector3("vSphericalL22", preScaledHarmonics.l22); - } - else { - effect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z); - effect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z); - effect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z); - effect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z); - effect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z); - effect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z); - effect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z); - effect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z); - effect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z); - } - } - } - /** - * Gets the code to inject in the vertex shader - * @param state current state of the node material building - * @returns the shader code - */ - handleVertexSide(state) { - let code = super.handleVertexSide(state); - state._emitFunctionFromInclude("harmonicsFunctions", `//${this.name}`, { - replaceStrings: [ - { search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g, replace: "" }, - { search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g, replace: "" }, - ], - }); - const reflectionVectorName = state._getFreeVariableName("reflectionVector"); - this._vEnvironmentIrradianceName = state._getFreeVariableName("vEnvironmentIrradiance"); - state._emitVaryingFromString(this._vEnvironmentIrradianceName, "vec3", "defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"); - state._emitUniformFromString("vSphericalL00", "vec3", "SPHERICAL_HARMONICS"); - state._emitUniformFromString("vSphericalL1_1", "vec3", "SPHERICAL_HARMONICS"); - state._emitUniformFromString("vSphericalL10", "vec3", "SPHERICAL_HARMONICS"); - state._emitUniformFromString("vSphericalL11", "vec3", "SPHERICAL_HARMONICS"); - state._emitUniformFromString("vSphericalL2_2", "vec3", "SPHERICAL_HARMONICS"); - state._emitUniformFromString("vSphericalL2_1", "vec3", "SPHERICAL_HARMONICS"); - state._emitUniformFromString("vSphericalL20", "vec3", "SPHERICAL_HARMONICS"); - state._emitUniformFromString("vSphericalL21", "vec3", "SPHERICAL_HARMONICS"); - state._emitUniformFromString("vSphericalL22", "vec3", "SPHERICAL_HARMONICS"); - state._emitUniformFromString("vSphericalX", "vec3", "SPHERICAL_HARMONICS", true); - state._emitUniformFromString("vSphericalY", "vec3", "SPHERICAL_HARMONICS", true); - state._emitUniformFromString("vSphericalZ", "vec3", "SPHERICAL_HARMONICS", true); - state._emitUniformFromString("vSphericalXX_ZZ", "vec3", "SPHERICAL_HARMONICS", true); - state._emitUniformFromString("vSphericalYY_ZZ", "vec3", "SPHERICAL_HARMONICS", true); - state._emitUniformFromString("vSphericalZZ", "vec3", "SPHERICAL_HARMONICS", true); - state._emitUniformFromString("vSphericalXY", "vec3", "SPHERICAL_HARMONICS", true); - state._emitUniformFromString("vSphericalYZ", "vec3", "SPHERICAL_HARMONICS", true); - state._emitUniformFromString("vSphericalZX", "vec3", "SPHERICAL_HARMONICS", true); - code += `#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) - vec3 ${reflectionVectorName} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; - #ifdef ${this._defineOppositeZ} - ${reflectionVectorName}.z *= -1.0; - #endif - ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${reflectionVectorName}); - #endif\n`; - return code; - } - /** - * Gets the main code of the block (fragment side) - * @param state current state of the node material building - * @param normalVarName name of the existing variable corresponding to the normal - * @returns the shader code - */ - getCode(state, normalVarName) { - let code = ""; - this.handleFragmentSideInits(state); - state._emitFunctionFromInclude("harmonicsFunctions", `//${this.name}`, { - replaceStrings: [ - { search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g, replace: "" }, - { search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g, replace: "" }, - ], - }); - state._emitFunction("sampleReflection", ` - #ifdef ${this._define3DName} - #define sampleReflection(s, c) textureCube(s, c) - #else - #define sampleReflection(s, c) texture2D(s, c) - #endif\n`, `//${this.name}`); - state._emitFunction("sampleReflectionLod", ` - #ifdef ${this._define3DName} - #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l) - #else - #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l) - #endif\n`, `//${this.name}`); - const computeReflectionCoordsFunc = ` - vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) { - ${this.handleFragmentSideCodeReflectionCoords("worldNormal", "worldPos", true, true)} - return ${this._reflectionVectorName}; - }\n`; - state._emitFunction("computeReflectionCoordsPBR", computeReflectionCoordsFunc, `//${this.name}`); - this._vReflectionMicrosurfaceInfosName = state._getFreeVariableName("vReflectionMicrosurfaceInfos"); - state._emitUniformFromString(this._vReflectionMicrosurfaceInfosName, "vec3"); - this._vReflectionInfosName = state._getFreeVariableName("vReflectionInfos"); - this._vReflectionFilteringInfoName = state._getFreeVariableName("vReflectionFilteringInfo"); - state._emitUniformFromString(this._vReflectionFilteringInfoName, "vec2"); - code += `#ifdef REFLECTION - vec2 ${this._vReflectionInfosName} = vec2(1., 0.); - - reflectionOutParams reflectionOut; - - reflectionBlock( - ${this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : "v_" + this.worldPosition.associatedVariableName}.xyz, - ${normalVarName}, - alphaG, - ${this._vReflectionMicrosurfaceInfosName}, - ${this._vReflectionInfosName}, - ${this.reflectionColor}, - #ifdef ANISOTROPIC - anisotropicOut, - #endif - #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName}) - NdotVUnclamped, - #endif - #ifdef ${this._defineLinearSpecularReflection} - roughness, - #endif - #ifdef ${this._define3DName} - ${this._cubeSamplerName}, - #else - ${this._2DSamplerName}, - #endif - #if defined(NORMAL) && defined(USESPHERICALINVERTEX) - ${this._vEnvironmentIrradianceName}, - #endif - #ifdef USESPHERICALFROMREFLECTIONMAP - #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) - ${this._reflectionMatrixName}, - #endif - #endif - #ifdef USEIRRADIANCEMAP - irradianceSampler, // ** not handled ** - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${this._define3DName} - ${this._cubeSamplerName}, - ${this._cubeSamplerName}, - #else - ${this._2DSamplerName}, - ${this._2DSamplerName}, - #endif - #endif - #ifdef REALTIME_FILTERING - ${this._vReflectionFilteringInfoName}, - #endif - reflectionOut - ); - #endif\n`; - return code; - } - _buildBlock(state) { - this._scene = state.sharedData.scene; - if (state.target !== NodeMaterialBlockTargets.Fragment) { - this._defineLODReflectionAlpha = state._getFreeDefineName("LODINREFLECTIONALPHA"); - this._defineLinearSpecularReflection = state._getFreeDefineName("LINEARSPECULARREFLECTION"); - } - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - if (this.texture) { - codeString += `${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};\n`; - } - codeString += `${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics};\n`; - codeString += `${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment};\n`; - return codeString; - } - serialize() { - var _a, _b; - const serializationObject = super.serialize(); - serializationObject.useSphericalHarmonics = this.useSphericalHarmonics; - serializationObject.forceIrradianceInFragment = this.forceIrradianceInFragment; - serializationObject.gammaSpace = (_b = (_a = this.texture) === null || _a === void 0 ? void 0 : _a.gammaSpace) !== null && _b !== void 0 ? _b : true; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.useSphericalHarmonics = serializationObject.useSphericalHarmonics; - this.forceIrradianceInFragment = serializationObject.forceIrradianceInFragment; - if (this.texture) { - this.texture.gammaSpace = serializationObject.gammaSpace; - } - } -} -__decorate([ - editableInPropertyPage("Spherical Harmonics", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], ReflectionBlock.prototype, "useSphericalHarmonics", void 0); -__decorate([ - editableInPropertyPage("Force irradiance in fragment", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], ReflectionBlock.prototype, "forceIrradianceInFragment", void 0); -RegisterClass("BABYLON.ReflectionBlock", ReflectionBlock); -//# sourceMappingURL=reflectionBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/clearCoatBlock.js - - - - - - - - - - - -/** - * Block used to implement the clear coat module of the PBR material - */ -class ClearCoatBlock extends NodeMaterialBlock { - /** - * Create a new ClearCoatBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this._tangentCorrectionFactorName = ""; - /** - * Defines if the F0 value should be remapped to account for the interface change in the material. - */ - this.remapF0OnInterfaceChange = true; - this._isUnique = true; - this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("normalMapColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("uv", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("tintColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("tintThickness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("worldTangent", NodeMaterialBlockConnectionPointTypes.Vector4, true); - this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); - this.worldNormal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3); - this.registerInput("TBN", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("TBN", this, NodeMaterialConnectionPointDirection.Input, TBNBlock, "TBNBlock")); - this.registerOutput("clearcoat", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("clearcoat", this, NodeMaterialConnectionPointDirection.Output, ClearCoatBlock, "ClearCoatBlock")); - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("clearcoatOut"); - state._excludeVariableName("vClearCoatParams"); - state._excludeVariableName("vClearCoatTintParams"); - state._excludeVariableName("vClearCoatRefractionParams"); - state._excludeVariableName("vClearCoatTangentSpaceParams"); - state._excludeVariableName("vGeometricNormaClearCoatW"); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ClearCoatBlock"; - } - /** - * Gets the intensity input component - */ - get intensity() { - return this._inputs[0]; - } - /** - * Gets the roughness input component - */ - get roughness() { - return this._inputs[1]; - } - /** - * Gets the ior input component - */ - get indexOfRefraction() { - return this._inputs[2]; - } - /** - * Gets the bump texture input component - */ - get normalMapColor() { - return this._inputs[3]; - } - /** - * Gets the uv input component - */ - get uv() { - return this._inputs[4]; - } - /** - * Gets the tint color input component - */ - get tintColor() { - return this._inputs[5]; - } - /** - * Gets the tint "at distance" input component - */ - get tintAtDistance() { - return this._inputs[6]; - } - /** - * Gets the tint thickness input component - */ - get tintThickness() { - return this._inputs[7]; - } - /** - * Gets the world tangent input component - */ - get worldTangent() { - return this._inputs[8]; - } - /** - * Gets the world normal input component - */ - get worldNormal() { - return this._inputs[9]; - } - /** - * Gets the TBN input component - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - get TBN() { - return this._inputs[10]; - } - /** - * Gets the clear coat object output component - */ - get clearcoat() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.intensity.isConnected) { - const intensityInput = new InputBlock("ClearCoat intensity", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); - intensityInput.value = 1; - intensityInput.output.connectTo(this.intensity); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - super.prepareDefines(mesh, nodeMaterial, defines); - defines.setValue("CLEARCOAT", true); - defines.setValue("CLEARCOAT_TEXTURE", false, true); - defines.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE", true, true); - defines.setValue("CLEARCOAT_TINT", this.tintColor.isConnected || this.tintThickness.isConnected || this.tintAtDistance.isConnected, true); - defines.setValue("CLEARCOAT_BUMP", this.normalMapColor.isConnected, true); - defines.setValue("CLEARCOAT_DEFAULTIOR", this.indexOfRefraction.isConnected ? this.indexOfRefraction.connectInputBlock.value === pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction : true, true); - defines.setValue("CLEARCOAT_REMAP_F0", this.remapF0OnInterfaceChange, true); - } - bind(effect, nodeMaterial, mesh) { - var _a, _b; - super.bind(effect, nodeMaterial, mesh); - // Clear Coat Refraction params - const indexOfRefraction = (_b = (_a = this.indexOfRefraction.connectInputBlock) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction; - const a = 1 - indexOfRefraction; - const b = 1 + indexOfRefraction; - const f0 = Math.pow(-a / b, 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1. - const eta = 1 / indexOfRefraction; - effect.setFloat4("vClearCoatRefractionParams", f0, eta, a, b); - // Clear Coat tangent space params - const mainPBRBlock = this.clearcoat.hasEndpoints ? this.clearcoat.endpoints[0].ownerBlock : null; - const perturbedNormalBlock = (mainPBRBlock === null || mainPBRBlock === void 0 ? void 0 : mainPBRBlock.perturbedNormal.isConnected) ? mainPBRBlock.perturbedNormal.connectedPoint.ownerBlock : null; - if (this._scene._mirroredCameraPosition) { - 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); - } - else { - 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); - } - if (mesh) { - effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1); - } - } - _generateTBNSpace(state, worldPositionVarName, worldNormalVarName) { - let code = ""; - const comments = `//${this.name}`; - const worldTangent = this.worldTangent; - state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); - const tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" }; - const TBN = this.TBN; - if (TBN.isConnected) { - state.compilationString += ` - #ifdef TBNBLOCK - mat3 vTBN = ${TBN.associatedVariableName}; - #endif - `; - } - else if (worldTangent.isConnected) { - code += `vec3 tbnNormal = normalize(${worldNormalVarName}.xyz);\n`; - code += `vec3 tbnTangent = normalize(${worldTangent.associatedVariableName}.xyz);\n`; - code += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`; - code += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\n`; - } - state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, { - replaceStrings: [tangentReplaceString], - }); - return code; - } - /** - * Gets the main code of the block (fragment side) - * @param state current state of the node material building - * @param ccBlock instance of a ClearCoatBlock or null if the code must be generated without an active clear coat module - * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module - * @param worldPosVarName name of the variable holding the world position - * @param generateTBNSpace if true, the code needed to create the TBN coordinate space is generated - * @param vTBNAvailable indicate that the vTBN variable is already existing because it has already been generated by another block (PerturbNormal or Anisotropy) - * @param worldNormalVarName name of the variable holding the world normal - * @returns the shader code - */ - static GetCode(state, ccBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, worldNormalVarName) { - let code = ""; - const intensity = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.intensity.isConnected) ? ccBlock.intensity.associatedVariableName : "1."; - const roughness = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.roughness.isConnected) ? ccBlock.roughness.associatedVariableName : "0."; - const normalMapColor = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.normalMapColor.isConnected) ? ccBlock.normalMapColor.associatedVariableName : "vec3(0.)"; - const uv = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.uv.isConnected) ? ccBlock.uv.associatedVariableName : "vec2(0.)"; - const tintColor = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintColor.isConnected) ? ccBlock.tintColor.associatedVariableName : "vec3(1.)"; - const tintThickness = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintThickness.isConnected) ? ccBlock.tintThickness.associatedVariableName : "1."; - const tintAtDistance = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintAtDistance.isConnected) ? ccBlock.tintAtDistance.associatedVariableName : "1."; - const tintTexture = "vec4(0.)"; - if (ccBlock) { - state._emitUniformFromString("vClearCoatRefractionParams", "vec4"); - state._emitUniformFromString("vClearCoatTangentSpaceParams", "vec2"); - const normalShading = ccBlock.worldNormal; - code += `vec3 vGeometricNormaClearCoatW = ${normalShading.isConnected ? "normalize(" + normalShading.associatedVariableName + ".xyz)" : "geometricNormalW"};\n`; - } - else { - code += `vec3 vGeometricNormaClearCoatW = geometricNormalW;\n`; - } - if (generateTBNSpace && ccBlock) { - code += ccBlock._generateTBNSpace(state, worldPosVarName, worldNormalVarName); - vTBNAvailable = ccBlock.worldTangent.isConnected; - } - code += `clearcoatOutParams clearcoatOut; - - #ifdef CLEARCOAT - vec2 vClearCoatParams = vec2(${intensity}, ${roughness}); - vec4 vClearCoatTintParams = vec4(${tintColor}, ${tintThickness}); - - clearcoatBlock( - ${worldPosVarName}.xyz, - vGeometricNormaClearCoatW, - viewDirectionW, - vClearCoatParams, - specularEnvironmentR0, - #ifdef CLEARCOAT_TEXTURE - vec2(0.), - #endif - #ifdef CLEARCOAT_TINT - vClearCoatTintParams, - ${tintAtDistance}, - vClearCoatRefractionParams, - #ifdef CLEARCOAT_TINT_TEXTURE - ${tintTexture}, - #endif - #endif - #ifdef CLEARCOAT_BUMP - vec2(0., 1.), - vec4(${normalMapColor}, 0.), - ${uv}, - #if defined(${vTBNAvailable ? "TANGENT" : "IGNORE"}) && defined(NORMAL) - vTBN, - #else - vClearCoatTangentSpaceParams, - #endif - #ifdef OBJECTSPACE_NORMALMAP - normalMatrix, - #endif - #endif - #if defined(FORCENORMALFORWARD) && defined(NORMAL) - faceNormal, - #endif - #ifdef REFLECTION - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionMicrosurfaceInfosName}, - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionInfosName}, - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.reflectionColor}, - vLightingIntensity, - #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName} - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName}, - #else - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName}, - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName} - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName}, - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName}, - #else - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName}, - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName}, - #endif - #endif - #endif - #if defined(ENVIRONMENTBRDF) && !defined(${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName}) - #ifdef RADIANCEOCCLUSION - ambientMonochrome, - #endif - #endif - #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) - (gl_FrontFacing ? 1. : -1.), - #endif - clearcoatOut - ); - #else - clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0; - #endif\n`; - return code; - } - _buildBlock(state) { - this._scene = state.sharedData.scene; - if (state.target === NodeMaterialBlockTargets.Fragment) { - state.sharedData.bindableBlocks.push(this); - state.sharedData.blocksWithDefines.push(this); - this._tangentCorrectionFactorName = state._getFreeDefineName("tangentCorrectionFactor"); - state._emitUniformFromString(this._tangentCorrectionFactorName, "float"); - } - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.remapF0OnInterfaceChange = this.remapF0OnInterfaceChange; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - var _a; - super._deserialize(serializationObject, scene, rootUrl); - this.remapF0OnInterfaceChange = (_a = serializationObject.remapF0OnInterfaceChange) !== null && _a !== void 0 ? _a : true; - } -} -__decorate([ - editableInPropertyPage("Remap F0 on interface change", PropertyTypeForEdition.Boolean, "ADVANCED") -], ClearCoatBlock.prototype, "remapF0OnInterfaceChange", void 0); -RegisterClass("BABYLON.ClearCoatBlock", ClearCoatBlock); -//# sourceMappingURL=clearCoatBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/iridescenceBlock.js - - - - - - - - -/** - * Block used to implement the iridescence module of the PBR material - */ -class IridescenceBlock extends NodeMaterialBlock { - /** - * Create a new IridescenceBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this._isUnique = true; - this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("thickness", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerOutput("iridescence", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("iridescence", this, NodeMaterialConnectionPointDirection.Output, IridescenceBlock, "IridescenceBlock")); - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("iridescenceOut"); - state._excludeVariableName("vIridescenceParams"); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "IridescenceBlock"; - } - /** - * Gets the intensity input component - */ - get intensity() { - return this._inputs[0]; - } - /** - * Gets the indexOfRefraction input component - */ - get indexOfRefraction() { - return this._inputs[1]; - } - /** - * Gets the thickness input component - */ - get thickness() { - return this._inputs[2]; - } - /** - * Gets the iridescence object output component - */ - get iridescence() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.intensity.isConnected) { - const intensityInput = new InputBlock("Iridescence intensity", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); - intensityInput.value = 1; - intensityInput.output.connectTo(this.intensity); - const indexOfRefractionInput = new InputBlock("Iridescence ior", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); - indexOfRefractionInput.value = 1.3; - indexOfRefractionInput.output.connectTo(this.indexOfRefraction); - const thicknessInput = new InputBlock("Iridescence thickness", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); - thicknessInput.value = 400; - thicknessInput.output.connectTo(this.thickness); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - super.prepareDefines(mesh, nodeMaterial, defines); - defines.setValue("IRIDESCENCE", true, true); - defines.setValue("IRIDESCENCE_TEXTURE", false, true); - defines.setValue("IRIDESCENCE_THICKNESS_TEXTURE", false, true); - } - /** - * Gets the main code of the block (fragment side) - * @param iridescenceBlock instance of a IridescenceBlock or null if the code must be generated without an active iridescence module - * @returns the shader code - */ - static GetCode(iridescenceBlock) { - let code = ""; - const intensityName = (iridescenceBlock === null || iridescenceBlock === void 0 ? void 0 : iridescenceBlock.intensity.isConnected) ? iridescenceBlock.intensity.associatedVariableName : "1."; - const indexOfRefraction = (iridescenceBlock === null || iridescenceBlock === void 0 ? void 0 : iridescenceBlock.indexOfRefraction.isConnected) - ? iridescenceBlock.indexOfRefraction.associatedVariableName - : pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction; - const thickness = (iridescenceBlock === null || iridescenceBlock === void 0 ? void 0 : iridescenceBlock.thickness.isConnected) ? iridescenceBlock.thickness.associatedVariableName : pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness; - code += `iridescenceOutParams iridescenceOut; - - #ifdef IRIDESCENCE - iridescenceBlock( - vec4(${intensityName}, ${indexOfRefraction}, 1., ${thickness}), - NdotV, - specularEnvironmentR0, - #ifdef CLEARCOAT - NdotVUnclamped, - #endif - iridescenceOut - ); - - float iridescenceIntensity = iridescenceOut.iridescenceIntensity; - specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; - #endif\n`; - return code; - } - _buildBlock(state) { - if (state.target === NodeMaterialBlockTargets.Fragment) { - state.sharedData.bindableBlocks.push(this); - state.sharedData.blocksWithDefines.push(this); - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - } -} -RegisterClass("BABYLON.IridescenceBlock", IridescenceBlock); -//# sourceMappingURL=iridescenceBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/refractionBlock.js - - - - - - - - - - - - - -/** - * Block used to implement the refraction part of the sub surface module of the PBR material - */ -class RefractionBlock extends NodeMaterialBlock { - /** - * Create a new RefractionBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - /** - * This parameters will make the material used its opacity to control how much it is refracting against not. - * Materials half opaque for instance using refraction could benefit from this control. - */ - this.linkRefractionWithTransparency = false; - /** - * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. - */ - this.invertRefractionY = false; - /** - * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. - */ - this.useThicknessAsDepth = false; - this._isUnique = true; - this.registerInput("intensity", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("tintAtDistance", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("volumeIndexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerOutput("refraction", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("refraction", this, NodeMaterialConnectionPointDirection.Output, RefractionBlock, "RefractionBlock")); - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("vRefractionPosition"); - state._excludeVariableName("vRefractionSize"); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "RefractionBlock"; - } - /** - * Gets the intensity input component - */ - get intensity() { - return this._inputs[0]; - } - /** - * Gets the tint at distance input component - */ - get tintAtDistance() { - return this._inputs[1]; - } - /** - * Gets the volume index of refraction input component - */ - get volumeIndexOfRefraction() { - return this._inputs[2]; - } - /** - * Gets the view input component - */ - get view() { - return this.viewConnectionPoint; - } - /** - * Gets the refraction object output component - */ - get refraction() { - return this._outputs[0]; - } - /** - * Returns true if the block has a texture - */ - get hasTexture() { - return !!this._getTexture(); - } - _getTexture() { - if (this.texture) { - return this.texture; - } - return this._scene.environmentTexture; - } - autoConfigure(material) { - if (!this.intensity.isConnected) { - const intensityInput = new InputBlock("Refraction intensity", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); - intensityInput.value = 1; - intensityInput.output.connectTo(this.intensity); - } - if (this.view && !this.view.isConnected) { - let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View); - if (!viewInput) { - viewInput = new InputBlock("view"); - viewInput.setAsSystemValue(NodeMaterialSystemValues.View); - } - viewInput.output.connectTo(this.view); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - super.prepareDefines(mesh, nodeMaterial, defines); - const refractionTexture = this._getTexture(); - const refraction = refractionTexture && refractionTexture.getTextureMatrix; - defines.setValue("SS_REFRACTION", refraction, true); - if (!refraction) { - return; - } - defines.setValue(this._define3DName, refractionTexture.isCube, true); - defines.setValue(this._defineLODRefractionAlpha, refractionTexture.lodLevelInAlpha, true); - defines.setValue(this._defineLinearSpecularRefraction, refractionTexture.linearSpecularLOD, true); - defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem && refractionTexture.isCube ? !refractionTexture.invertZ : refractionTexture.invertZ, true); - defines.setValue("SS_LINKREFRACTIONTOTRANSPARENCY", this.linkRefractionWithTransparency, true); - defines.setValue("SS_GAMMAREFRACTION", refractionTexture.gammaSpace, true); - defines.setValue("SS_RGBDREFRACTION", refractionTexture.isRGBD, true); - defines.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC", refractionTexture.boundingBoxSize ? true : false, true); - defines.setValue("SS_USE_THICKNESS_AS_DEPTH", this.useThicknessAsDepth, true); - } - isReady() { - const texture = this._getTexture(); - if (texture && !texture.isReadyOrNotBlocking()) { - return false; - } - return true; - } - bind(effect, nodeMaterial, mesh) { - var _a, _b, _c, _d; - super.bind(effect, nodeMaterial, mesh); - const refractionTexture = this._getTexture(); - if (!refractionTexture) { - return; - } - if (refractionTexture.isCube) { - effect.setTexture(this._cubeSamplerName, refractionTexture); - } - else { - effect.setTexture(this._2DSamplerName, refractionTexture); - } - effect.setMatrix(this._refractionMatrixName, refractionTexture.getRefractionTextureMatrix()); - let depth = 1.0; - if (!refractionTexture.isCube) { - if (refractionTexture.depth) { - depth = refractionTexture.depth; - } - } - 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; - effect.setFloat4(this._vRefractionInfosName, refractionTexture.level, 1 / indexOfRefraction, depth, this.invertRefractionY ? -1 : 1); - effect.setFloat4(this._vRefractionMicrosurfaceInfosName, refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset, 1 / indexOfRefraction); - const width = refractionTexture.getSize().width; - effect.setFloat2(this._vRefractionFilteringInfoName, width, math_scalar_Scalar.Log2(width)); - if (refractionTexture.boundingBoxSize) { - const cubeTexture = refractionTexture; - effect.setVector3("vRefractionPosition", cubeTexture.boundingBoxPosition); - effect.setVector3("vRefractionSize", cubeTexture.boundingBoxSize); - } - } - /** - * Gets the main code of the block (fragment side) - * @param state current state of the node material building - * @returns the shader code - */ - getCode(state) { - const code = ""; - state.sharedData.blockingBlocks.push(this); - state.sharedData.textureBlocks.push(this); - // Samplers - this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler"); - state.samplers.push(this._cubeSamplerName); - this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler"); - state.samplers.push(this._2DSamplerName); - this._define3DName = state._getFreeDefineName("SS_REFRACTIONMAP_3D"); - state._samplerDeclaration += `#ifdef ${this._define3DName}\n`; - state._samplerDeclaration += `uniform samplerCube ${this._cubeSamplerName};\n`; - state._samplerDeclaration += `#else\n`; - state._samplerDeclaration += `uniform sampler2D ${this._2DSamplerName};\n`; - state._samplerDeclaration += `#endif\n`; - // Fragment - state.sharedData.blocksWithDefines.push(this); - state.sharedData.bindableBlocks.push(this); - this._defineLODRefractionAlpha = state._getFreeDefineName("SS_LODINREFRACTIONALPHA"); - this._defineLinearSpecularRefraction = state._getFreeDefineName("SS_LINEARSPECULARREFRACTION"); - this._defineOppositeZ = state._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"); - this._refractionMatrixName = state._getFreeVariableName("refractionMatrix"); - state._emitUniformFromString(this._refractionMatrixName, "mat4"); - state._emitFunction("sampleRefraction", ` - #ifdef ${this._define3DName} - #define sampleRefraction(s, c) textureCube(s, c) - #else - #define sampleRefraction(s, c) texture2D(s, c) - #endif\n`, `//${this.name}`); - state._emitFunction("sampleRefractionLod", ` - #ifdef ${this._define3DName} - #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) - #else - #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) - #endif\n`, `//${this.name}`); - this._vRefractionMicrosurfaceInfosName = state._getFreeVariableName("vRefractionMicrosurfaceInfos"); - state._emitUniformFromString(this._vRefractionMicrosurfaceInfosName, "vec4"); - this._vRefractionInfosName = state._getFreeVariableName("vRefractionInfos"); - state._emitUniformFromString(this._vRefractionInfosName, "vec4"); - this._vRefractionFilteringInfoName = state._getFreeVariableName("vRefractionFilteringInfo"); - state._emitUniformFromString(this._vRefractionFilteringInfoName, "vec2"); - state._emitUniformFromString("vRefractionPosition", "vec3"); - state._emitUniformFromString("vRefractionSize", "vec3"); - return code; - } - _buildBlock(state) { - this._scene = state.sharedData.scene; - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - if (this.texture) { - if (this.texture.isCube) { - codeString = `${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\n`; - } - else { - codeString = `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\n`; - } - codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`; - } - codeString += `${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\n`; - codeString += `${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\n`; - codeString += `${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - if (this.texture && !this.texture.isRenderTarget) { - serializationObject.texture = this.texture.serialize(); - } - serializationObject.linkRefractionWithTransparency = this.linkRefractionWithTransparency; - serializationObject.invertRefractionY = this.invertRefractionY; - serializationObject.useThicknessAsDepth = this.useThicknessAsDepth; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - if (serializationObject.texture) { - rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; - if (serializationObject.texture.isCube) { - this.texture = cubeTexture_CubeTexture.Parse(serializationObject.texture, scene, rootUrl); - } - else { - this.texture = texture_Texture.Parse(serializationObject.texture, scene, rootUrl); - } - } - this.linkRefractionWithTransparency = serializationObject.linkRefractionWithTransparency; - this.invertRefractionY = serializationObject.invertRefractionY; - this.useThicknessAsDepth = !!serializationObject.useThicknessAsDepth; - } -} -__decorate([ - editableInPropertyPage("Link refraction to transparency", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], RefractionBlock.prototype, "linkRefractionWithTransparency", void 0); -__decorate([ - editableInPropertyPage("Invert refraction Y", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], RefractionBlock.prototype, "invertRefractionY", void 0); -__decorate([ - editableInPropertyPage("Use thickness as depth", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], RefractionBlock.prototype, "useThicknessAsDepth", void 0); -RegisterClass("BABYLON.RefractionBlock", RefractionBlock); -//# sourceMappingURL=refractionBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/subSurfaceBlock.js - - - - - - - - -/** - * Block used to implement the sub surface module of the PBR material - */ -class SubSurfaceBlock extends NodeMaterialBlock { - /** - * Create a new SubSurfaceBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Fragment); - this._isUnique = true; - this.registerInput("thickness", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("tintColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("translucencyIntensity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("translucencyDiffusionDist", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("refraction", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("refraction", this, NodeMaterialConnectionPointDirection.Input, RefractionBlock, "RefractionBlock")); - this.registerOutput("subsurface", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("subsurface", this, NodeMaterialConnectionPointDirection.Output, SubSurfaceBlock, "SubSurfaceBlock")); - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("subSurfaceOut"); - state._excludeVariableName("vThicknessParam"); - state._excludeVariableName("vTintColor"); - state._excludeVariableName("vSubSurfaceIntensity"); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SubSurfaceBlock"; - } - /** - * Gets the thickness component - */ - get thickness() { - return this._inputs[0]; - } - /** - * Gets the tint color input component - */ - get tintColor() { - return this._inputs[1]; - } - /** - * Gets the translucency intensity input component - */ - get translucencyIntensity() { - return this._inputs[2]; - } - /** - * Gets the translucency diffusion distance input component - */ - get translucencyDiffusionDist() { - return this._inputs[3]; - } - /** - * Gets the refraction object parameters - */ - get refraction() { - return this._inputs[4]; - } - /** - * Gets the sub surface object output component - */ - get subsurface() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.thickness.isConnected) { - const thicknessInput = new InputBlock("SubSurface thickness", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float); - thicknessInput.value = 0; - thicknessInput.output.connectTo(this.thickness); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - super.prepareDefines(mesh, nodeMaterial, defines); - const translucencyEnabled = this.translucencyDiffusionDist.isConnected || this.translucencyIntensity.isConnected; - defines.setValue("SUBSURFACE", translucencyEnabled || this.refraction.isConnected, true); - defines.setValue("SS_TRANSLUCENCY", translucencyEnabled, true); - defines.setValue("SS_THICKNESSANDMASK_TEXTURE", false, true); - defines.setValue("SS_REFRACTIONINTENSITY_TEXTURE", false, true); - defines.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE", false, true); - defines.setValue("SS_MASK_FROM_THICKNESS_TEXTURE", false, true); - defines.setValue("SS_USE_GLTF_TEXTURES", false, true); - } - /** - * Gets the main code of the block (fragment side) - * @param state current state of the node material building - * @param ssBlock instance of a SubSurfaceBlock or null if the code must be generated without an active sub surface module - * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module - * @param worldPosVarName name of the variable holding the world position - * @returns the shader code - */ - static GetCode(state, ssBlock, reflectionBlock, worldPosVarName) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r; - let code = ""; - const thickness = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.thickness.isConnected) ? ssBlock.thickness.associatedVariableName : "0."; - const tintColor = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.tintColor.isConnected) ? ssBlock.tintColor.associatedVariableName : "vec3(1.)"; - const translucencyIntensity = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyIntensity.isConnected) ? ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyIntensity.associatedVariableName : "1."; - const translucencyDiffusionDistance = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyDiffusionDist.isConnected) ? ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyDiffusionDist.associatedVariableName : "vec3(1.)"; - 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); - const refractionTintAtDistance = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.tintAtDistance.isConnected) ? refractionBlock.tintAtDistance.associatedVariableName : "1."; - const refractionIntensity = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.intensity.isConnected) ? refractionBlock.intensity.associatedVariableName : "1."; - const refractionView = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.view.isConnected) ? refractionBlock.view.associatedVariableName : ""; - code += (_b = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.getCode(state)) !== null && _b !== void 0 ? _b : ""; - code += `subSurfaceOutParams subSurfaceOut; - - #ifdef SUBSURFACE - vec2 vThicknessParam = vec2(0., ${thickness}); - vec4 vTintColor = vec4(${tintColor}, ${refractionTintAtDistance}); - vec3 vSubSurfaceIntensity = vec3(${refractionIntensity}, ${translucencyIntensity}, 0.); - - subSurfaceBlock( - vSubSurfaceIntensity, - vThicknessParam, - vTintColor, - normalW, - specularEnvironmentReflectance, - #ifdef SS_THICKNESSANDMASK_TEXTURE - vec4(0.), - #endif - #ifdef REFLECTION - #ifdef SS_TRANSLUCENCY - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._reflectionMatrixName}, - #ifdef USESPHERICALFROMREFLECTIONMAP - #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) - reflectionOut.irradianceVector, - #endif - #if defined(REALTIME_FILTERING) - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName}, - ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionFilteringInfoName}, - #endif - #endif - #ifdef USEIRRADIANCEMAP - irradianceSampler, - #endif - #endif - #endif - #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) - surfaceAlbedo, - #endif - #ifdef SS_REFRACTION - ${worldPosVarName}.xyz, - viewDirectionW, - ${refractionView}, - ${(_c = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionInfosName) !== null && _c !== void 0 ? _c : ""}, - ${(_d = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._refractionMatrixName) !== null && _d !== void 0 ? _d : ""}, - ${(_e = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionMicrosurfaceInfosName) !== null && _e !== void 0 ? _e : ""}, - vLightingIntensity, - #ifdef SS_LINKREFRACTIONTOTRANSPARENCY - alpha, - #endif - #ifdef ${(_f = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLODRefractionAlpha) !== null && _f !== void 0 ? _f : "IGNORE"} - NdotVUnclamped, - #endif - #ifdef ${(_g = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLinearSpecularRefraction) !== null && _g !== void 0 ? _g : "IGNORE"} - roughness, - #endif - alphaG, - #ifdef ${(_h = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _h !== void 0 ? _h : "IGNORE"} - ${(_j = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _j !== void 0 ? _j : ""}, - #else - ${(_k = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _k !== void 0 ? _k : ""}, - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${(_l = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _l !== void 0 ? _l : "IGNORE"} - ${(_m = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _m !== void 0 ? _m : ""}, - ${(_o = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _o !== void 0 ? _o : ""}, - #else - ${(_p = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _p !== void 0 ? _p : ""}, - ${(_q = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _q !== void 0 ? _q : ""}, - #endif - #endif - #ifdef ANISOTROPIC - anisotropicOut, - #endif - #ifdef REALTIME_FILTERING - ${(_r = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionFilteringInfoName) !== null && _r !== void 0 ? _r : ""}, - #endif - #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC - vRefractionPosition, - vRefractionSize, - #endif - #endif - #ifdef SS_TRANSLUCENCY - ${translucencyDiffusionDistance}, - #endif - subSurfaceOut - ); - - #ifdef SS_REFRACTION - surfaceAlbedo = subSurfaceOut.surfaceAlbedo; - #ifdef SS_LINKREFRACTIONTOTRANSPARENCY - alpha = subSurfaceOut.alpha; - #endif - #endif - #else - subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; - #endif\n`; - return code; - } - _buildBlock(state) { - if (state.target === NodeMaterialBlockTargets.Fragment) { - state.sharedData.blocksWithDefines.push(this); - } - return this; - } -} -RegisterClass("BABYLON.SubSurfaceBlock", SubSurfaceBlock); -//# sourceMappingURL=subSurfaceBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/pbrMetallicRoughnessBlock.js - - - - - - - - - - - - - - - - - - - - - - -const mapOutputToVariable = { - 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", ""], -}; -/** - * Block used to implement the PBR metallic/roughness model - */ -class PBRMetallicRoughnessBlock extends NodeMaterialBlock { - static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) { - const that = block; - if (that.worldPosition.isConnected) { - that.generateOnlyFragmentCode = !that.generateOnlyFragmentCode; - console.error("The worldPosition input must not be connected to be able to switch!"); - return false; - } - that._setTarget(); - return true; - } - _setTarget() { - this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment); - this.getInputByName("worldPosition").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex; - } - /** - * Create a new ReflectionBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.VertexAndFragment); - this._environmentBRDFTexture = null; - this._metallicReflectanceColor = math_color_Color3.White(); - this._metallicF0Factor = 1; - /** - * Intensity of the direct lights e.g. the four lights available in your scene. - * This impacts both the direct diffuse and specular highlights. - */ - this.directIntensity = 1.0; - /** - * Intensity of the environment e.g. how much the environment will light the object - * either through harmonics for rough material or through the reflection for shiny ones. - */ - this.environmentIntensity = 1.0; - /** - * This is a special control allowing the reduction of the specular highlights coming from the - * four lights of the scene. Those highlights may not be needed in full environment lighting. - */ - this.specularIntensity = 1.0; - /** - * Defines the falloff type used in this material. - * It by default is Physical. - */ - this.lightFalloff = 0; - /** - * Specifies that alpha test should be used - */ - this.useAlphaTest = false; - /** - * Defines the alpha limits in alpha test mode. - */ - this.alphaTestCutoff = 0.5; - /** - * Specifies that alpha blending should be used - */ - this.useAlphaBlending = false; - /** - * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones). - * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind. - */ - this.useRadianceOverAlpha = true; - /** - * Specifies that the material will keeps the specular highlights over a transparent surface (only the most luminous ones). - * A car glass is a good example of that. When sun reflects on it you can not see what is behind. - */ - this.useSpecularOverAlpha = true; - /** - * Enables specular anti aliasing in the PBR shader. - * It will both interacts on the Geometry for analytical and IBL lighting. - * It also prefilter the roughness map based on the bump values. - */ - this.enableSpecularAntiAliasing = false; - /** - * Enables realtime filtering on the texture. - */ - this.realTimeFiltering = false; - /** - * Quality switch for realtime filtering - */ - this.realTimeFilteringQuality = 8; - /** - * Defines if the material uses energy conservation. - */ - this.useEnergyConservation = true; - /** - * This parameters will enable/disable radiance occlusion by preventing the radiance to lit - * too much the area relying on ambient texture to define their ambient occlusion. - */ - this.useRadianceOcclusion = true; - /** - * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal - * makes the reflect vector face the model (under horizon). - */ - this.useHorizonOcclusion = true; - /** - * If set to true, no lighting calculations will be applied. - */ - this.unlit = false; - /** - * Force normal to face away from face. - */ - this.forceNormalForward = false; - /** 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) */ - this.generateOnlyFragmentCode = false; - /** - * Defines the material debug mode. - * It helps seeing only some components of the material while troubleshooting. - */ - this.debugMode = 0; - /** - * Specify from where on screen the debug mode should start. - * The value goes from -1 (full screen) to 1 (not visible) - * It helps with side by side comparison against the final render - * This defaults to 0 - */ - this.debugLimit = 0; - /** - * As the default viewing range might not be enough (if the ambient is really small for instance) - * You can use the factor to better multiply the final value. - */ - this.debugFactor = 1; - this._isUnique = true; - this.registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex); - this.registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("view", NodeMaterialBlockConnectionPointTypes.Matrix, false); - this.registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("perturbedNormal", NodeMaterialBlockConnectionPointTypes.Vector4, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("baseColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("metallic", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("roughness", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment); - this.registerInput("ambientOcc", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("opacity", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("indexOfRefraction", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("ambientColor", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment); - this.registerInput("reflection", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("reflection", this, NodeMaterialConnectionPointDirection.Input, ReflectionBlock, "ReflectionBlock")); - this.registerInput("clearcoat", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("clearcoat", this, NodeMaterialConnectionPointDirection.Input, ClearCoatBlock, "ClearCoatBlock")); - this.registerInput("sheen", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("sheen", this, NodeMaterialConnectionPointDirection.Input, SheenBlock, "SheenBlock")); - this.registerInput("subsurface", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("subsurface", this, NodeMaterialConnectionPointDirection.Input, SubSurfaceBlock, "SubSurfaceBlock")); - this.registerInput("anisotropy", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("anisotropy", this, NodeMaterialConnectionPointDirection.Input, AnisotropyBlock, "AnisotropyBlock")); - this.registerInput("iridescence", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject("iridescence", this, NodeMaterialConnectionPointDirection.Input, IridescenceBlock, "IridescenceBlock")); - this.registerOutput("ambientClr", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("diffuseDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("specularDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("clearcoatDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("sheenDir", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("diffuseInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("specularInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("clearcoatInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("sheenInd", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("refraction", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("lighting", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment); - this.registerOutput("shadow", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - this.registerOutput("alpha", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment); - } - /** - * Initialize the block and prepare the context for build - * @param state defines the state that will be used for the build - */ - initialize(state) { - state._excludeVariableName("vLightingIntensity"); - state._excludeVariableName("geometricNormalW"); - state._excludeVariableName("normalW"); - state._excludeVariableName("faceNormal"); - state._excludeVariableName("albedoOpacityOut"); - state._excludeVariableName("surfaceAlbedo"); - state._excludeVariableName("alpha"); - state._excludeVariableName("aoOut"); - state._excludeVariableName("baseColor"); - state._excludeVariableName("reflectivityOut"); - state._excludeVariableName("microSurface"); - state._excludeVariableName("roughness"); - state._excludeVariableName("NdotVUnclamped"); - state._excludeVariableName("NdotV"); - state._excludeVariableName("alphaG"); - state._excludeVariableName("AARoughnessFactors"); - state._excludeVariableName("environmentBrdf"); - state._excludeVariableName("ambientMonochrome"); - state._excludeVariableName("seo"); - state._excludeVariableName("eho"); - state._excludeVariableName("environmentRadiance"); - state._excludeVariableName("irradianceVector"); - state._excludeVariableName("environmentIrradiance"); - state._excludeVariableName("diffuseBase"); - state._excludeVariableName("specularBase"); - state._excludeVariableName("preInfo"); - state._excludeVariableName("info"); - state._excludeVariableName("shadow"); - state._excludeVariableName("finalDiffuse"); - state._excludeVariableName("finalAmbient"); - state._excludeVariableName("ambientOcclusionForDirectDiffuse"); - state._excludeVariableName("finalColor"); - state._excludeVariableName("vClipSpacePosition"); - state._excludeVariableName("vDebugMode"); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "PBRMetallicRoughnessBlock"; - } - /** - * Gets the world position input component - */ - get worldPosition() { - return this._inputs[0]; - } - /** - * Gets the world normal input component - */ - get worldNormal() { - return this._inputs[1]; - } - /** - * Gets the view matrix parameter - */ - get view() { - return this._inputs[2]; - } - /** - * Gets the camera position input component - */ - get cameraPosition() { - return this._inputs[3]; - } - /** - * Gets the perturbed normal input component - */ - get perturbedNormal() { - return this._inputs[4]; - } - /** - * Gets the base color input component - */ - get baseColor() { - return this._inputs[5]; - } - /** - * Gets the metallic input component - */ - get metallic() { - return this._inputs[6]; - } - /** - * Gets the roughness input component - */ - get roughness() { - return this._inputs[7]; - } - /** - * Gets the ambient occlusion input component - */ - get ambientOcc() { - return this._inputs[8]; - } - /** - * Gets the opacity input component - */ - get opacity() { - return this._inputs[9]; - } - /** - * Gets the index of refraction input component - */ - get indexOfRefraction() { - return this._inputs[10]; - } - /** - * Gets the ambient color input component - */ - get ambientColor() { - return this._inputs[11]; - } - /** - * Gets the reflection object parameters - */ - get reflection() { - return this._inputs[12]; - } - /** - * Gets the clear coat object parameters - */ - get clearcoat() { - return this._inputs[13]; - } - /** - * Gets the sheen object parameters - */ - get sheen() { - return this._inputs[14]; - } - /** - * Gets the sub surface object parameters - */ - get subsurface() { - return this._inputs[15]; - } - /** - * Gets the anisotropy object parameters - */ - get anisotropy() { - return this._inputs[16]; - } - /** - * Gets the iridescence object parameters - */ - get iridescence() { - return this._inputs[17]; - } - /** - * Gets the ambient output component - */ - get ambientClr() { - return this._outputs[0]; - } - /** - * Gets the diffuse output component - */ - get diffuseDir() { - return this._outputs[1]; - } - /** - * Gets the specular output component - */ - get specularDir() { - return this._outputs[2]; - } - /** - * Gets the clear coat output component - */ - get clearcoatDir() { - return this._outputs[3]; - } - /** - * Gets the sheen output component - */ - get sheenDir() { - return this._outputs[4]; - } - /** - * Gets the indirect diffuse output component - */ - get diffuseInd() { - return this._outputs[5]; - } - /** - * Gets the indirect specular output component - */ - get specularInd() { - return this._outputs[6]; - } - /** - * Gets the indirect clear coat output component - */ - get clearcoatInd() { - return this._outputs[7]; - } - /** - * Gets the indirect sheen output component - */ - get sheenInd() { - return this._outputs[8]; - } - /** - * Gets the refraction output component - */ - get refraction() { - return this._outputs[9]; - } - /** - * Gets the global lighting output component - */ - get lighting() { - return this._outputs[10]; - } - /** - * Gets the shadow output component - */ - get shadow() { - return this._outputs[11]; - } - /** - * Gets the alpha output component - */ - get alpha() { - return this._outputs[12]; - } - autoConfigure(material) { - if (!this.cameraPosition.isConnected) { - let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition); - if (!cameraPositionInput) { - cameraPositionInput = new InputBlock("cameraPosition"); - cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition); - } - cameraPositionInput.output.connectTo(this.cameraPosition); - } - if (!this.view.isConnected) { - let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View); - if (!viewInput) { - viewInput = new InputBlock("view"); - viewInput.setAsSystemValue(NodeMaterialSystemValues.View); - } - viewInput.output.connectTo(this.view); - } - } - prepareDefines(mesh, nodeMaterial, defines) { - // General - defines.setValue("PBR", true); - defines.setValue("METALLICWORKFLOW", true); - defines.setValue("DEBUGMODE", this.debugMode, true); - defines.setValue("NORMALXYSCALE", true); - defines.setValue("BUMP", this.perturbedNormal.isConnected, true); - defines.setValue("LODBASEDMICROSFURACE", this._scene.getEngine().getCaps().textureLOD); - // Albedo & Opacity - defines.setValue("ALBEDO", false, true); - defines.setValue("OPACITY", this.opacity.isConnected, true); - // Ambient occlusion - defines.setValue("AMBIENT", true, true); - defines.setValue("AMBIENTINGRAYSCALE", false, true); - // Reflectivity - defines.setValue("REFLECTIVITY", false, true); - defines.setValue("AOSTOREINMETALMAPRED", false, true); - defines.setValue("METALLNESSSTOREINMETALMAPBLUE", false, true); - defines.setValue("ROUGHNESSSTOREINMETALMAPALPHA", false, true); - defines.setValue("ROUGHNESSSTOREINMETALMAPGREEN", false, true); - // Lighting & colors - if (this.lightFalloff === pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD) { - defines.setValue("USEPHYSICALLIGHTFALLOFF", false); - defines.setValue("USEGLTFLIGHTFALLOFF", false); - } - else if (this.lightFalloff === pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF) { - defines.setValue("USEPHYSICALLIGHTFALLOFF", false); - defines.setValue("USEGLTFLIGHTFALLOFF", true); - } - else { - defines.setValue("USEPHYSICALLIGHTFALLOFF", true); - defines.setValue("USEGLTFLIGHTFALLOFF", false); - } - // Transparency - const alphaTestCutOffString = this.alphaTestCutoff.toString(); - defines.setValue("ALPHABLEND", this.useAlphaBlending, true); - defines.setValue("ALPHAFROMALBEDO", false, true); - defines.setValue("ALPHATEST", this.useAlphaTest, true); - defines.setValue("ALPHATESTVALUE", alphaTestCutOffString.indexOf(".") < 0 ? alphaTestCutOffString + "." : alphaTestCutOffString, true); - defines.setValue("OPACITYRGB", false, true); - // Rendering - defines.setValue("RADIANCEOVERALPHA", this.useRadianceOverAlpha, true); - defines.setValue("SPECULAROVERALPHA", this.useSpecularOverAlpha, true); - defines.setValue("SPECULARAA", this._scene.getEngine().getCaps().standardDerivatives && this.enableSpecularAntiAliasing, true); - defines.setValue("REALTIME_FILTERING", this.realTimeFiltering, true); - const scene = mesh.getScene(); - const engine = scene.getEngine(); - if (engine._features.needTypeSuffixInShaderConstants) { - defines.setValue("NUM_SAMPLES", this.realTimeFilteringQuality + "u", true); - } - else { - defines.setValue("NUM_SAMPLES", "" + this.realTimeFilteringQuality, true); - } - // Advanced - defines.setValue("BRDF_V_HEIGHT_CORRELATED", true); - defines.setValue("MS_BRDF_ENERGY_CONSERVATION", this.useEnergyConservation, true); - defines.setValue("RADIANCEOCCLUSION", this.useRadianceOcclusion, true); - defines.setValue("HORIZONOCCLUSION", this.useHorizonOcclusion, true); - defines.setValue("UNLIT", this.unlit, true); - defines.setValue("FORCENORMALFORWARD", this.forceNormalForward, true); - if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) { - defines.setValue("ENVIRONMENTBRDF", true); - defines.setValue("ENVIRONMENTBRDF_RGBD", this._environmentBRDFTexture.isRGBD, true); - } - else { - defines.setValue("ENVIRONMENTBRDF", false); - defines.setValue("ENVIRONMENTBRDF_RGBD", false); - } - if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) { - nodeMaterial.imageProcessingConfiguration.prepareDefines(defines); - } - if (!defines._areLightsDirty) { - return; - } - if (!this.light) { - // Lights - MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights); - defines._needNormals = true; - // Multiview - MaterialHelper.PrepareDefinesForMultiview(scene, defines); - } - else { - const state = { - needNormals: false, - needRebuild: false, - lightmapMode: false, - shadowEnabled: false, - specularEnabled: false, - }; - MaterialHelper.PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state); - if (state.needRebuild) { - defines.rebuild(); - } - } - } - updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) { - for (let lightIndex = 0; lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) { - if (!defines["LIGHT" + lightIndex]) { - break; - } - const onlyUpdateBuffersList = state.uniforms.indexOf("vLightData" + lightIndex) >= 0; - MaterialHelper.PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffers, onlyUpdateBuffersList); - } - } - isReady(mesh, nodeMaterial, defines) { - if (this._environmentBRDFTexture && !this._environmentBRDFTexture.isReady()) { - return false; - } - if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) { - if (!nodeMaterial.imageProcessingConfiguration.isReady()) { - return false; - } - } - return true; - } - bind(effect, nodeMaterial, mesh) { - var _a, _b; - if (!mesh) { - return; - } - const scene = mesh.getScene(); - if (!this.light) { - MaterialHelper.BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights); - } - else { - MaterialHelper.BindLight(this.light, this._lightId, scene, effect, true); - } - effect.setTexture(this._environmentBrdfSamplerName, this._environmentBRDFTexture); - effect.setFloat2("vDebugMode", this.debugLimit, this.debugFactor); - const ambientScene = this._scene.ambientColor; - if (ambientScene) { - effect.setColor3("ambientFromScene", ambientScene); - } - const invertNormal = scene.useRightHandedSystem === (scene._mirroredCameraPosition != null); - effect.setFloat(this._invertNormalName, invertNormal ? -1 : 1); - effect.setFloat4("vLightingIntensity", this.directIntensity, 1, this.environmentIntensity * this._scene.environmentIntensity, this.specularIntensity); - // reflectivity bindings - const outsideIOR = 1; // consider air as clear coat and other layers would remap in the shader. - const ior = (_b = (_a = this.indexOfRefraction.connectInputBlock) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : 1.5; - // We are here deriving our default reflectance from a common value for none metallic surface. - // Based of the schlick fresnel approximation model - // for dielectrics. - const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2); - // Tweak the default F0 and F90 based on our given setup - this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]); - const metallicF90 = this._metallicF0Factor; - effect.setColor4(this._vMetallicReflectanceFactorsName, TmpColors.Color3[0], metallicF90); - if (nodeMaterial.imageProcessingConfiguration) { - nodeMaterial.imageProcessingConfiguration.bind(effect); - } - } - _injectVertexCode(state) { - var _a, _b; - const worldPos = this.worldPosition; - const comments = `//${this.name}`; - // Declaration - if (!this.light) { - // Emit for all lights - state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, { - repeatKey: "maxSimultaneousLights", - }); - this._lightId = 0; - state.sharedData.dynamicUniformBlocks.push(this); - } - else { - this._lightId = (state.counters["lightCounter"] !== undefined ? state.counters["lightCounter"] : -1) + 1; - state.counters["lightCounter"] = this._lightId; - state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightVxUboDeclaration" : "lightVxFragmentDeclaration", comments, { - replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }], - }, this._lightId.toString()); - } - // Inject code in vertex - const worldPosVaryingName = "v_" + worldPos.associatedVariableName; - if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) { - state.compilationString += `${worldPosVaryingName} = ${worldPos.associatedVariableName};\n`; - } - const reflectionBlock = this.reflection.isConnected ? (_a = this.reflection.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null; - if (reflectionBlock) { - reflectionBlock.viewConnectionPoint = this.view; - } - state.compilationString += (_b = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.handleVertexSide(state)) !== null && _b !== void 0 ? _b : ""; - if (state._emitVaryingFromString("vClipSpacePosition", "vec4", "defined(IGNORE) || DEBUGMODE > 0")) { - state._injectAtEnd += `#if DEBUGMODE > 0\n`; - state._injectAtEnd += `vClipSpacePosition = gl_Position;\n`; - state._injectAtEnd += `#endif\n`; - } - if (this.light) { - state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { - replaceStrings: [ - { search: /{X}/g, replace: this._lightId.toString() }, - { search: /worldPos/g, replace: worldPos.associatedVariableName }, - ], - }); - } - else { - state.compilationString += `vec4 worldPos = ${worldPos.associatedVariableName};\n`; - if (this.view.isConnected) { - state.compilationString += `mat4 view = ${this.view.associatedVariableName};\n`; - } - state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { - repeatKey: "maxSimultaneousLights", - }); - } - } - _getAlbedoOpacityCode() { - let code = `albedoOpacityOutParams albedoOpacityOut;\n`; - const albedoColor = this.baseColor.isConnected ? this.baseColor.associatedVariableName : "vec3(1.)"; - const opacity = this.opacity.isConnected ? this.opacity.associatedVariableName : "1."; - code += `albedoOpacityBlock( - vec4(${albedoColor}, 1.), - #ifdef ALBEDO - vec4(1.), - vec2(1., 1.), - #endif - #ifdef OPACITY - vec4(${opacity}), - vec2(1., 1.), - #endif - albedoOpacityOut - ); - - vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; - float alpha = albedoOpacityOut.alpha;\n`; - return code; - } - _getAmbientOcclusionCode() { - let code = `ambientOcclusionOutParams aoOut;\n`; - const ao = this.ambientOcc.isConnected ? this.ambientOcc.associatedVariableName : "1."; - code += `ambientOcclusionBlock( - #ifdef AMBIENT - vec3(${ao}), - vec4(0., 1.0, 1.0, 0.), - #endif - aoOut - );\n`; - return code; - } - _getReflectivityCode(state) { - let code = `reflectivityOutParams reflectivityOut;\n`; - const aoIntensity = "1."; - this._vMetallicReflectanceFactorsName = state._getFreeVariableName("vMetallicReflectanceFactors"); - state._emitUniformFromString(this._vMetallicReflectanceFactorsName, "vec4"); - code += `vec3 baseColor = surfaceAlbedo; - - reflectivityBlock( - vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.), - #ifdef METALLICWORKFLOW - surfaceAlbedo, - ${this._vMetallicReflectanceFactorsName}, - #endif - #ifdef REFLECTIVITY - vec3(0., 0., ${aoIntensity}), - vec4(1.), - #endif - #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) - aoOut.ambientOcclusionColor, - #endif - #ifdef MICROSURFACEMAP - microSurfaceTexel, <== not handled! - #endif - reflectivityOut - ); - - float microSurface = reflectivityOut.microSurface; - float roughness = reflectivityOut.roughness; - - #ifdef METALLICWORKFLOW - surfaceAlbedo = reflectivityOut.surfaceAlbedo; - #endif - #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) - aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; - #endif\n`; - return code; - } - _buildBlock(state) { - 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; - super._buildBlock(state); - this._scene = state.sharedData.scene; - if (!this._environmentBRDFTexture) { - this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this._scene); - } - const reflectionBlock = this.reflection.isConnected ? (_a = this.reflection.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null; - if (reflectionBlock) { - // Need those variables to be setup when calling _injectVertexCode - reflectionBlock.worldPositionConnectionPoint = this.worldPosition; - reflectionBlock.cameraPositionConnectionPoint = this.cameraPosition; - reflectionBlock.worldNormalConnectionPoint = this.worldNormal; - reflectionBlock.viewConnectionPoint = this.view; - } - if (state.target !== NodeMaterialBlockTargets.Fragment) { - // Vertex - this._injectVertexCode(state); - return this; - } - // Fragment - state.sharedData.forcedBindableBlocks.push(this); - state.sharedData.blocksWithDefines.push(this); - state.sharedData.blockingBlocks.push(this); - if (this.generateOnlyFragmentCode) { - state.sharedData.dynamicUniformBlocks.push(this); - } - const comments = `//${this.name}`; - const normalShading = this.perturbedNormal; - let worldPosVarName = this.worldPosition.associatedVariableName; - if (this.generateOnlyFragmentCode) { - worldPosVarName = state._getFreeVariableName("globalWorldPos"); - state._emitFunction("pbr_globalworldpos", `vec3 ${worldPosVarName};\n`, comments); - state.compilationString += `${worldPosVarName} = ${this.worldPosition.associatedVariableName}.xyz;\n`; - state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, { - repeatKey: "maxSimultaneousLights", - substitutionVars: this.generateOnlyFragmentCode ? `worldPos,${this.worldPosition.associatedVariableName}` : undefined, - }); - state.compilationString += `#if DEBUGMODE > 0\n`; - state.compilationString += `vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n`; - state.compilationString += `#endif\n`; - } - else { - worldPosVarName = "v_" + worldPosVarName; - } - this._environmentBrdfSamplerName = state._getFreeVariableName("environmentBrdfSampler"); - state._emit2DSampler(this._environmentBrdfSamplerName); - state.sharedData.hints.needAlphaBlending = state.sharedData.hints.needAlphaBlending || this.useAlphaBlending; - state.sharedData.hints.needAlphaTesting = state.sharedData.hints.needAlphaTesting || this.useAlphaTest; - state._emitExtension("lod", "#extension GL_EXT_shader_texture_lod : enable", "defined(LODBASEDMICROSFURACE)"); - state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable"); - state._emitUniformFromString("vDebugMode", "vec2", "defined(IGNORE) || DEBUGMODE > 0"); - state._emitUniformFromString("ambientFromScene", "vec3"); - // Image processing uniforms - state.uniforms.push("exposureLinear"); - state.uniforms.push("contrast"); - state.uniforms.push("vInverseScreenSize"); - state.uniforms.push("vignetteSettings1"); - state.uniforms.push("vignetteSettings2"); - state.uniforms.push("vCameraColorCurveNegative"); - state.uniforms.push("vCameraColorCurveNeutral"); - state.uniforms.push("vCameraColorCurvePositive"); - state.uniforms.push("txColorTransform"); - state.uniforms.push("colorTransformSettings"); - state.uniforms.push("ditherIntensity"); - // - // Includes - // - if (!this.light) { - // Emit for all lights - state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, { - repeatKey: "maxSimultaneousLights", - substitutionVars: this.generateOnlyFragmentCode ? "varying," : undefined, - }); - } - else { - state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, { - replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }], - }, this._lightId.toString()); - } - state._emitFunctionFromInclude("helperFunctions", comments); - state._emitFunctionFromInclude("importanceSampling", comments); - state._emitFunctionFromInclude("pbrHelperFunctions", comments); - state._emitFunctionFromInclude("imageProcessingDeclaration", comments); - state._emitFunctionFromInclude("imageProcessingFunctions", comments); - state._emitFunctionFromInclude("shadowsFragmentFunctions", comments, { - replaceStrings: [{ search: /vPositionW/g, replace: worldPosVarName + ".xyz" }], - }); - state._emitFunctionFromInclude("pbrDirectLightingSetupFunctions", comments, { - replaceStrings: [{ search: /vPositionW/g, replace: worldPosVarName + ".xyz" }], - }); - state._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions", comments); - state._emitFunctionFromInclude("pbrBRDFFunctions", comments, { - replaceStrings: [{ search: /REFLECTIONMAP_SKYBOX/g, replace: (_b = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _b !== void 0 ? _b : "REFLECTIONMAP_SKYBOX" }], - }); - state._emitFunctionFromInclude("hdrFilteringFunctions", comments); - state._emitFunctionFromInclude("pbrDirectLightingFunctions", comments, { - replaceStrings: [{ search: /vPositionW/g, replace: worldPosVarName + ".xyz" }], - }); - state._emitFunctionFromInclude("pbrIBLFunctions", comments); - state._emitFunctionFromInclude("pbrBlockAlbedoOpacity", comments); - state._emitFunctionFromInclude("pbrBlockReflectivity", comments); - state._emitFunctionFromInclude("pbrBlockAmbientOcclusion", comments); - state._emitFunctionFromInclude("pbrBlockAlphaFresnel", comments); - state._emitFunctionFromInclude("pbrBlockAnisotropic", comments); - // - // code - // - state._emitUniformFromString("vLightingIntensity", "vec4"); - if (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.generateOnlyFragmentCode) { - state.compilationString += reflectionBlock.handleVertexSide(state); - } - // _____________________________ Geometry Information ____________________________ - this._vNormalWName = state._getFreeVariableName("vNormalW"); - state.compilationString += `vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\n`; - if (state._registerTempVariable("viewDirectionW")) { - state.compilationString += `vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${worldPosVarName}.xyz);\n`; - } - state.compilationString += `vec3 geometricNormalW = ${this._vNormalWName}.xyz;\n`; - state.compilationString += `vec3 normalW = ${normalShading.isConnected ? "normalize(" + normalShading.associatedVariableName + ".xyz)" : "geometricNormalW"};\n`; - this._invertNormalName = state._getFreeVariableName("invertNormal"); - state._emitUniformFromString(this._invertNormalName, "float"); - state.compilationString += state._emitCodeFromInclude("pbrBlockNormalFinal", comments, { - replaceStrings: [ - { search: /vPositionW/g, replace: worldPosVarName + ".xyz" }, - { search: /vEyePosition.w/g, replace: this._invertNormalName }, - ], - }); - // _____________________________ Albedo & Opacity ______________________________ - state.compilationString += this._getAlbedoOpacityCode(); - state.compilationString += state._emitCodeFromInclude("depthPrePass", comments); - // _____________________________ AO _______________________________ - state.compilationString += this._getAmbientOcclusionCode(); - state.compilationString += state._emitCodeFromInclude("pbrBlockLightmapInit", comments); - // _____________________________ UNLIT _______________________________ - state.compilationString += `#ifdef UNLIT - vec3 diffuseBase = vec3(1., 1., 1.); - #else\n`; - // _____________________________ Reflectivity _______________________________ - state.compilationString += this._getReflectivityCode(state); - // _____________________________ Geometry info _________________________________ - state.compilationString += state._emitCodeFromInclude("pbrBlockGeometryInfo", comments, { - replaceStrings: [ - { search: /REFLECTIONMAP_SKYBOX/g, replace: (_c = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _c !== void 0 ? _c : "REFLECTIONMAP_SKYBOX" }, - { search: /REFLECTIONMAP_3D/g, replace: (_d = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _d !== void 0 ? _d : "REFLECTIONMAP_3D" }, - ], - }); - // _____________________________ Anisotropy _______________________________________ - const anisotropyBlock = this.anisotropy.isConnected ? (_e = this.anisotropy.connectedPoint) === null || _e === void 0 ? void 0 : _e.ownerBlock : null; - if (anisotropyBlock) { - anisotropyBlock.worldPositionConnectionPoint = this.worldPosition; - anisotropyBlock.worldNormalConnectionPoint = this.worldNormal; - state.compilationString += anisotropyBlock.getCode(state, !this.perturbedNormal.isConnected); - } - // _____________________________ Reflection _______________________________________ - if (reflectionBlock && reflectionBlock.hasTexture) { - state.compilationString += reflectionBlock.getCode(state, anisotropyBlock ? "anisotropicOut.anisotropicNormal" : "normalW"); - } - state._emitFunctionFromInclude("pbrBlockReflection", comments, { - replaceStrings: [ - { search: /computeReflectionCoords/g, replace: "computeReflectionCoordsPBR" }, - { search: /REFLECTIONMAP_3D/g, replace: (_f = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _f !== void 0 ? _f : "REFLECTIONMAP_3D" }, - { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_g = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _g !== void 0 ? _g : "REFLECTIONMAP_OPPOSITEZ" }, - { search: /REFLECTIONMAP_PROJECTION/g, replace: (_h = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _h !== void 0 ? _h : "REFLECTIONMAP_PROJECTION" }, - { search: /REFLECTIONMAP_SKYBOX/g, replace: (_j = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _j !== void 0 ? _j : "REFLECTIONMAP_SKYBOX" }, - { search: /LODINREFLECTIONALPHA/g, replace: (_k = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _k !== void 0 ? _k : "LODINREFLECTIONALPHA" }, - { search: /LINEARSPECULARREFLECTION/g, replace: (_l = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _l !== void 0 ? _l : "LINEARSPECULARREFLECTION" }, - { search: /vReflectionFilteringInfo/g, replace: (_m = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionFilteringInfoName) !== null && _m !== void 0 ? _m : "vReflectionFilteringInfo" }, - ], - }); - // ___________________ Compute Reflectance aka R0 F0 info _________________________ - state.compilationString += state._emitCodeFromInclude("pbrBlockReflectance0", comments, { - replaceStrings: [{ search: /metallicReflectanceFactors/g, replace: this._vMetallicReflectanceFactorsName }], - }); - // ________________________________ Sheen ______________________________ - const sheenBlock = this.sheen.isConnected ? (_o = this.sheen.connectedPoint) === null || _o === void 0 ? void 0 : _o.ownerBlock : null; - if (sheenBlock) { - state.compilationString += sheenBlock.getCode(reflectionBlock); - } - state._emitFunctionFromInclude("pbrBlockSheen", comments, { - replaceStrings: [ - { search: /REFLECTIONMAP_3D/g, replace: (_p = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _p !== void 0 ? _p : "REFLECTIONMAP_3D" }, - { search: /REFLECTIONMAP_SKYBOX/g, replace: (_q = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _q !== void 0 ? _q : "REFLECTIONMAP_SKYBOX" }, - { search: /LODINREFLECTIONALPHA/g, replace: (_r = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _r !== void 0 ? _r : "LODINREFLECTIONALPHA" }, - { search: /LINEARSPECULARREFLECTION/g, replace: (_s = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _s !== void 0 ? _s : "LINEARSPECULARREFLECTION" }, - ], - }); - // _____________________________ Iridescence _______________________________ - const iridescenceBlock = this.iridescence.isConnected ? (_t = this.iridescence.connectedPoint) === null || _t === void 0 ? void 0 : _t.ownerBlock : null; - state.compilationString += IridescenceBlock.GetCode(iridescenceBlock); - state._emitFunctionFromInclude("pbrBlockIridescence", comments, { - replaceStrings: [], - }); - // _____________________________ Clear Coat ____________________________ - const clearcoatBlock = this.clearcoat.isConnected ? (_u = this.clearcoat.connectedPoint) === null || _u === void 0 ? void 0 : _u.ownerBlock : null; - const generateTBNSpace = !this.perturbedNormal.isConnected && !this.anisotropy.isConnected; - 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); - const isTangentConnectedToAnisotropy = this.anisotropy.isConnected && ((_x = this.anisotropy.connectedPoint) === null || _x === void 0 ? void 0 : _x.ownerBlock).worldTangent.isConnected; - let vTBNAvailable = isTangentConnectedToPerturbNormal || (!this.perturbedNormal.isConnected && isTangentConnectedToAnisotropy); - state.compilationString += ClearCoatBlock.GetCode(state, clearcoatBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, this.worldNormal.associatedVariableName); - if (generateTBNSpace) { - vTBNAvailable = (_y = clearcoatBlock === null || clearcoatBlock === void 0 ? void 0 : clearcoatBlock.worldTangent.isConnected) !== null && _y !== void 0 ? _y : false; - } - state._emitFunctionFromInclude("pbrBlockClearcoat", comments, { - replaceStrings: [ - { search: /computeReflectionCoords/g, replace: "computeReflectionCoordsPBR" }, - { search: /REFLECTIONMAP_3D/g, replace: (_z = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _z !== void 0 ? _z : "REFLECTIONMAP_3D" }, - { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_0 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _0 !== void 0 ? _0 : "REFLECTIONMAP_OPPOSITEZ" }, - { search: /REFLECTIONMAP_PROJECTION/g, replace: (_1 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _1 !== void 0 ? _1 : "REFLECTIONMAP_PROJECTION" }, - { search: /REFLECTIONMAP_SKYBOX/g, replace: (_2 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _2 !== void 0 ? _2 : "REFLECTIONMAP_SKYBOX" }, - { search: /LODINREFLECTIONALPHA/g, replace: (_3 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _3 !== void 0 ? _3 : "LODINREFLECTIONALPHA" }, - { search: /LINEARSPECULARREFLECTION/g, replace: (_4 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _4 !== void 0 ? _4 : "LINEARSPECULARREFLECTION" }, - { search: /defined\(TANGENT\)/g, replace: vTBNAvailable ? "defined(TANGENT)" : "defined(IGNORE)" }, - ], - }); - // _________________________ Specular Environment Reflectance __________________________ - state.compilationString += state._emitCodeFromInclude("pbrBlockReflectance", comments, { - replaceStrings: [ - { search: /REFLECTIONMAP_SKYBOX/g, replace: (_5 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _5 !== void 0 ? _5 : "REFLECTIONMAP_SKYBOX" }, - { search: /REFLECTIONMAP_3D/g, replace: (_6 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _6 !== void 0 ? _6 : "REFLECTIONMAP_3D" }, - ], - }); - // ___________________________________ SubSurface ______________________________________ - const subsurfaceBlock = this.subsurface.isConnected ? (_7 = this.subsurface.connectedPoint) === null || _7 === void 0 ? void 0 : _7.ownerBlock : null; - const refractionBlock = this.subsurface.isConnected - ? (_9 = ((_8 = this.subsurface.connectedPoint) === null || _8 === void 0 ? void 0 : _8.ownerBlock).refraction.connectedPoint) === null || _9 === void 0 ? void 0 : _9.ownerBlock - : null; - if (refractionBlock) { - refractionBlock.viewConnectionPoint = this.view; - refractionBlock.indexOfRefractionConnectionPoint = this.indexOfRefraction; - } - state.compilationString += SubSurfaceBlock.GetCode(state, subsurfaceBlock, reflectionBlock, worldPosVarName); - state._emitFunctionFromInclude("pbrBlockSubSurface", comments, { - replaceStrings: [ - { search: /REFLECTIONMAP_3D/g, replace: (_10 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _10 !== void 0 ? _10 : "REFLECTIONMAP_3D" }, - { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_11 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _11 !== void 0 ? _11 : "REFLECTIONMAP_OPPOSITEZ" }, - { search: /REFLECTIONMAP_PROJECTION/g, replace: (_12 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _12 !== void 0 ? _12 : "REFLECTIONMAP_PROJECTION" }, - { search: /SS_REFRACTIONMAP_3D/g, replace: (_13 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _13 !== void 0 ? _13 : "SS_REFRACTIONMAP_3D" }, - { search: /SS_LODINREFRACTIONALPHA/g, replace: (_14 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLODRefractionAlpha) !== null && _14 !== void 0 ? _14 : "SS_LODINREFRACTIONALPHA" }, - { search: /SS_LINEARSPECULARREFRACTION/g, replace: (_15 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLinearSpecularRefraction) !== null && _15 !== void 0 ? _15 : "SS_LINEARSPECULARREFRACTION" }, - { search: /SS_REFRACTIONMAP_OPPOSITEZ/g, replace: (_16 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineOppositeZ) !== null && _16 !== void 0 ? _16 : "SS_REFRACTIONMAP_OPPOSITEZ" }, - ], - }); - // _____________________________ Direct Lighting Info __________________________________ - state.compilationString += state._emitCodeFromInclude("pbrBlockDirectLighting", comments); - if (this.light) { - state.compilationString += state._emitCodeFromInclude("lightFragment", comments, { - replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }], - }); - } - else { - state.compilationString += state._emitCodeFromInclude("lightFragment", comments, { - repeatKey: "maxSimultaneousLights", - }); - } - // _____________________________ Compute Final Lit Components ________________________ - state.compilationString += state._emitCodeFromInclude("pbrBlockFinalLitComponents", comments); - // _____________________________ UNLIT (2) ________________________ - state.compilationString += `#endif\n`; // UNLIT - // _____________________________ Compute Final Unlit Components ________________________ - const aoColor = this.ambientColor.isConnected ? this.ambientColor.associatedVariableName : "vec3(0., 0., 0.)"; - let aoDirectLightIntensity = pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString(); - if (aoDirectLightIntensity.indexOf(".") === -1) { - aoDirectLightIntensity += "."; - } - state.compilationString += state._emitCodeFromInclude("pbrBlockFinalUnlitComponents", comments, { - replaceStrings: [ - { search: /vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g, replace: "" }, - { search: /vAmbientColor/g, replace: aoColor + " * ambientFromScene" }, - { search: /vAmbientInfos\.w/g, replace: aoDirectLightIntensity }, - ], - }); - // _____________________________ Output Final Color Composition ________________________ - state.compilationString += state._emitCodeFromInclude("pbrBlockFinalColorComposition", comments, { - replaceStrings: [{ search: /finalEmissive/g, replace: "vec3(0.)" }], - }); - // _____________________________ Apply image processing ________________________ - state.compilationString += state._emitCodeFromInclude("pbrBlockImageProcessing", comments, { - replaceStrings: [{ search: /visibility/g, replace: "1." }], - }); - // _____________________________ Generate debug code ________________________ - state.compilationString += state._emitCodeFromInclude("pbrDebug", comments, { - replaceStrings: [ - { search: /vNormalW/g, replace: this._vNormalWName }, - { search: /vPositionW/g, replace: worldPosVarName }, - { search: /albedoTexture\.rgb;/g, replace: "vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n" }, - ], - }); - // _____________________________ Generate end points ________________________ - for (const output of this._outputs) { - if (output.hasEndpoints) { - const remap = mapOutputToVariable[output.name]; - if (remap) { - const [varName, conditions] = remap; - if (conditions) { - state.compilationString += `#if ${conditions}\n`; - } - state.compilationString += `${this._declareOutput(output, state)} = ${varName};\n`; - if (conditions) { - state.compilationString += `#else\n`; - state.compilationString += `${this._declareOutput(output, state)} = vec3(0.);\n`; - state.compilationString += `#endif\n`; - } - } - else { - console.error(`There's no remapping for the ${output.name} end point! No code generated`); - } - } - } - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\n`; - codeString += `${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\n`; - codeString += `${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\n`; - codeString += `${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\n`; - codeString += `${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\n`; - codeString += `${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\n`; - codeString += `${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\n`; - codeString += `${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\n`; - codeString += `${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\n`; - codeString += `${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\n`; - codeString += `${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\n`; - codeString += `${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\n`; - codeString += `${this._codeVariableName}.unlit = ${this.unlit};\n`; - codeString += `${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\n`; - codeString += `${this._codeVariableName}.debugMode = ${this.debugMode};\n`; - codeString += `${this._codeVariableName}.debugLimit = ${this.debugLimit};\n`; - codeString += `${this._codeVariableName}.debugFactor = ${this.debugFactor};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - if (this.light) { - serializationObject.lightId = this.light.id; - } - serializationObject.lightFalloff = this.lightFalloff; - serializationObject.useAlphaTest = this.useAlphaTest; - serializationObject.alphaTestCutoff = this.alphaTestCutoff; - serializationObject.useAlphaBlending = this.useAlphaBlending; - serializationObject.useRadianceOverAlpha = this.useRadianceOverAlpha; - serializationObject.useSpecularOverAlpha = this.useSpecularOverAlpha; - serializationObject.enableSpecularAntiAliasing = this.enableSpecularAntiAliasing; - serializationObject.realTimeFiltering = this.realTimeFiltering; - serializationObject.realTimeFilteringQuality = this.realTimeFilteringQuality; - serializationObject.useEnergyConservation = this.useEnergyConservation; - serializationObject.useRadianceOcclusion = this.useRadianceOcclusion; - serializationObject.useHorizonOcclusion = this.useHorizonOcclusion; - serializationObject.unlit = this.unlit; - serializationObject.forceNormalForward = this.forceNormalForward; - serializationObject.debugMode = this.debugMode; - serializationObject.debugLimit = this.debugLimit; - serializationObject.debugFactor = this.debugFactor; - serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - var _a, _b; - super._deserialize(serializationObject, scene, rootUrl); - if (serializationObject.lightId) { - this.light = scene.getLightById(serializationObject.lightId); - } - this.lightFalloff = (_a = serializationObject.lightFalloff) !== null && _a !== void 0 ? _a : 0; - this.useAlphaTest = serializationObject.useAlphaTest; - this.alphaTestCutoff = serializationObject.alphaTestCutoff; - this.useAlphaBlending = serializationObject.useAlphaBlending; - this.useRadianceOverAlpha = serializationObject.useRadianceOverAlpha; - this.useSpecularOverAlpha = serializationObject.useSpecularOverAlpha; - this.enableSpecularAntiAliasing = serializationObject.enableSpecularAntiAliasing; - this.realTimeFiltering = !!serializationObject.realTimeFiltering; - this.realTimeFilteringQuality = (_b = serializationObject.realTimeFilteringQuality) !== null && _b !== void 0 ? _b : 8; - this.useEnergyConservation = serializationObject.useEnergyConservation; - this.useRadianceOcclusion = serializationObject.useRadianceOcclusion; - this.useHorizonOcclusion = serializationObject.useHorizonOcclusion; - this.unlit = serializationObject.unlit; - this.forceNormalForward = !!serializationObject.forceNormalForward; - this.debugMode = serializationObject.debugMode; - this.debugLimit = serializationObject.debugLimit; - this.debugFactor = serializationObject.debugFactor; - this.generateOnlyFragmentCode = !!serializationObject.generateOnlyFragmentCode; - this._setTarget(); - } -} -__decorate([ - editableInPropertyPage("Direct lights", PropertyTypeForEdition.Float, "INTENSITY", { min: 0, max: 1, notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "directIntensity", void 0); -__decorate([ - editableInPropertyPage("Environment lights", PropertyTypeForEdition.Float, "INTENSITY", { min: 0, max: 1, notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "environmentIntensity", void 0); -__decorate([ - editableInPropertyPage("Specular highlights", PropertyTypeForEdition.Float, "INTENSITY", { min: 0, max: 1, notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "specularIntensity", void 0); -__decorate([ - editableInPropertyPage("Light falloff", PropertyTypeForEdition.List, "LIGHTING & COLORS", { - notifiers: { update: true }, - options: [ - { label: "Physical", value: pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL }, - { label: "GLTF", value: pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF }, - { label: "Standard", value: pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD }, - ], - }) -], PBRMetallicRoughnessBlock.prototype, "lightFalloff", void 0); -__decorate([ - editableInPropertyPage("Alpha Testing", PropertyTypeForEdition.Boolean, "OPACITY") -], PBRMetallicRoughnessBlock.prototype, "useAlphaTest", void 0); -__decorate([ - editableInPropertyPage("Alpha CutOff", PropertyTypeForEdition.Float, "OPACITY", { min: 0, max: 1, notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "alphaTestCutoff", void 0); -__decorate([ - editableInPropertyPage("Alpha blending", PropertyTypeForEdition.Boolean, "OPACITY") -], PBRMetallicRoughnessBlock.prototype, "useAlphaBlending", void 0); -__decorate([ - editableInPropertyPage("Radiance over alpha", PropertyTypeForEdition.Boolean, "RENDERING", { notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "useRadianceOverAlpha", void 0); -__decorate([ - editableInPropertyPage("Specular over alpha", PropertyTypeForEdition.Boolean, "RENDERING", { notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "useSpecularOverAlpha", void 0); -__decorate([ - editableInPropertyPage("Specular anti-aliasing", PropertyTypeForEdition.Boolean, "RENDERING", { notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "enableSpecularAntiAliasing", void 0); -__decorate([ - editableInPropertyPage("Realtime filtering", PropertyTypeForEdition.Boolean, "RENDERING", { notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "realTimeFiltering", void 0); -__decorate([ - editableInPropertyPage("Realtime filtering quality", PropertyTypeForEdition.List, "RENDERING", { - notifiers: { update: true }, - options: [ - { label: "Low", value: 8 }, - { label: "Medium", value: 16 }, - { label: "High", value: 64 }, - ], - }) -], PBRMetallicRoughnessBlock.prototype, "realTimeFilteringQuality", void 0); -__decorate([ - editableInPropertyPage("Energy Conservation", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "useEnergyConservation", void 0); -__decorate([ - editableInPropertyPage("Radiance occlusion", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "useRadianceOcclusion", void 0); -__decorate([ - editableInPropertyPage("Horizon occlusion", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "useHorizonOcclusion", void 0); -__decorate([ - editableInPropertyPage("Unlit", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "unlit", void 0); -__decorate([ - editableInPropertyPage("Force normal forward", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "forceNormalForward", void 0); -__decorate([ - editableInPropertyPage("Generate only fragment code", PropertyTypeForEdition.Boolean, "ADVANCED", { - notifiers: { rebuild: true, update: true, onValidation: PBRMetallicRoughnessBlock._OnGenerateOnlyFragmentCodeChanged }, - }) -], PBRMetallicRoughnessBlock.prototype, "generateOnlyFragmentCode", void 0); -__decorate([ - editableInPropertyPage("Debug mode", PropertyTypeForEdition.List, "DEBUG", { - notifiers: { update: true }, - options: [ - { label: "None", value: 0 }, - // Geometry - { label: "Normalized position", value: 1 }, - { label: "Normals", value: 2 }, - { label: "Tangents", value: 3 }, - { label: "Bitangents", value: 4 }, - { label: "Bump Normals", value: 5 }, - //{ label: "UV1", value: 6 }, - //{ label: "UV2", value: 7 }, - { 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 }, - // Maps - //{ label: "Emissive Map", value: 23 }, - //{ label: "Light Map", value: 24 }, - // Env - { label: "Env Refraction", value: 40 }, - { label: "Env Reflection", value: 41 }, - { label: "Env Clear Coat", value: 42 }, - // Lighting - { 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 }, - // Lighting Params - { 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 }, - // Misc - { 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 }, - ], - }) -], PBRMetallicRoughnessBlock.prototype, "debugMode", void 0); -__decorate([ - editableInPropertyPage("Split position", PropertyTypeForEdition.Float, "DEBUG", { min: -1, max: 1, notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "debugLimit", void 0); -__decorate([ - editableInPropertyPage("Output factor", PropertyTypeForEdition.Float, "DEBUG", { min: 0, max: 5, notifiers: { update: true } }) -], PBRMetallicRoughnessBlock.prototype, "debugFactor", void 0); -RegisterClass("BABYLON.PBRMetallicRoughnessBlock", PBRMetallicRoughnessBlock); -//# sourceMappingURL=pbrMetallicRoughnessBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/index.js - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/index.js - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/modBlock.js - - - - -/** - * Block used to compute value of one parameter modulo another - */ -class ModBlock extends NodeMaterialBlock { - /** - * Creates a new ModBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("left", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ModBlock"; - } - /** - * Gets the left operand input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right operand input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.ModBlock", ModBlock); -//# sourceMappingURL=modBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/matrixBuilderBlock.js - - - - - - -/** - * Block used to build a matrix from 4 Vector4 - */ -class MatrixBuilderBlock extends NodeMaterialBlock { - /** - * Creates a new MatrixBuilder - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("row0", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("row1", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("row2", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerInput("row3", NodeMaterialBlockConnectionPointTypes.Vector4); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MatrixBuilder"; - } - /** - * Gets the row0 vector - */ - get row0() { - return this._inputs[0]; - } - /** - * Gets the row1 vector - */ - get row1() { - return this._inputs[1]; - } - /** - * Gets the row2 vector - */ - get row2() { - return this._inputs[2]; - } - /** - * Gets the row3 vector - */ - get row3() { - return this._inputs[3]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.row0.isConnected) { - const row0Input = new InputBlock("row0"); - row0Input.value = new math_vector_Vector4(1, 0, 0, 0); - row0Input.output.connectTo(this.row0); - } - if (!this.row1.isConnected) { - const row1Input = new InputBlock("row1"); - row1Input.value = new math_vector_Vector4(0, 1, 0, 0); - row1Input.output.connectTo(this.row1); - } - if (!this.row2.isConnected) { - const row2Input = new InputBlock("row2"); - row2Input.value = new math_vector_Vector4(0, 0, 1, 0); - row2Input.output.connectTo(this.row2); - } - if (!this.row3.isConnected) { - const row3Input = new InputBlock("row3"); - row3Input.value = new math_vector_Vector4(0, 0, 0, 1); - row3Input.output.connectTo(this.row3); - } - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - const row0 = this.row0; - const row1 = this.row1; - const row2 = this.row2; - const row3 = this.row3; - state.compilationString += - this._declareOutput(output, state) + - ` = mat4(${row0.associatedVariableName}, ${row1.associatedVariableName}, ${row2.associatedVariableName}, ${row3.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.MatrixBuilder", MatrixBuilderBlock); -//# sourceMappingURL=matrixBuilderBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/conditionalBlock.js - - - - -/** - * Operations supported by the ConditionalBlock block - */ -var ConditionalBlockConditions; -(function (ConditionalBlockConditions) { - /** Equal */ - ConditionalBlockConditions[ConditionalBlockConditions["Equal"] = 0] = "Equal"; - /** NotEqual */ - ConditionalBlockConditions[ConditionalBlockConditions["NotEqual"] = 1] = "NotEqual"; - /** LessThan */ - ConditionalBlockConditions[ConditionalBlockConditions["LessThan"] = 2] = "LessThan"; - /** GreaterThan */ - ConditionalBlockConditions[ConditionalBlockConditions["GreaterThan"] = 3] = "GreaterThan"; - /** LessOrEqual */ - ConditionalBlockConditions[ConditionalBlockConditions["LessOrEqual"] = 4] = "LessOrEqual"; - /** GreaterOrEqual */ - ConditionalBlockConditions[ConditionalBlockConditions["GreaterOrEqual"] = 5] = "GreaterOrEqual"; - /** Logical Exclusive OR */ - ConditionalBlockConditions[ConditionalBlockConditions["Xor"] = 6] = "Xor"; - /** Logical Or */ - ConditionalBlockConditions[ConditionalBlockConditions["Or"] = 7] = "Or"; - /** Logical And */ - ConditionalBlockConditions[ConditionalBlockConditions["And"] = 8] = "And"; -})(ConditionalBlockConditions || (ConditionalBlockConditions = {})); -/** - * Block used to apply conditional operation between floats - * @since 5.0.0 - */ -class ConditionalBlock extends NodeMaterialBlock { - /** - * Creates a new ConditionalBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Gets or sets the condition applied by the block - */ - this.condition = ConditionalBlockConditions.LessThan; - this.registerInput("a", NodeMaterialBlockConnectionPointTypes.Float); - this.registerInput("b", NodeMaterialBlockConnectionPointTypes.Float); - this.registerInput("true", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); - this.registerInput("false", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._linkConnectionTypes(2, 3); - this._outputs[0]._typeConnectionSource = this._inputs[2]; - this._outputs[0]._defaultConnectionPointType = NodeMaterialBlockConnectionPointTypes.Float; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ConditionalBlock"; - } - /** - * Gets the first operand component - */ - get a() { - return this._inputs[0]; - } - /** - * Gets the second operand component - */ - get b() { - return this._inputs[1]; - } - /** - * Gets the value to return if condition is true - */ - get true() { - return this._inputs[2]; - } - /** - * Gets the value to return if condition is false - */ - get false() { - return this._inputs[3]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - const trueStatement = this.true.isConnected ? this.true.associatedVariableName : "1.0"; - const falseStatement = this.false.isConnected ? this.false.associatedVariableName : "0.0"; - switch (this.condition) { - case ConditionalBlockConditions.Equal: { - state.compilationString += - this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\n`; - break; - } - case ConditionalBlockConditions.NotEqual: { - state.compilationString += - this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\n`; - break; - } - case ConditionalBlockConditions.LessThan: { - state.compilationString += - this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\n`; - break; - } - case ConditionalBlockConditions.LessOrEqual: { - state.compilationString += - this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\n`; - break; - } - case ConditionalBlockConditions.GreaterThan: { - state.compilationString += - this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\n`; - break; - } - case ConditionalBlockConditions.GreaterOrEqual: { - state.compilationString += - this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\n`; - break; - } - case ConditionalBlockConditions.Xor: { - state.compilationString += - this._declareOutput(output, state) + - ` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${trueStatement} : ${falseStatement};\n`; - break; - } - case ConditionalBlockConditions.Or: { - state.compilationString += - this._declareOutput(output, state) + - ` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${trueStatement} : ${falseStatement};\n`; - break; - } - case ConditionalBlockConditions.And: { - state.compilationString += - this._declareOutput(output, state) + - ` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${trueStatement} : ${falseStatement};\n`; - break; - } - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.condition = this.condition; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.condition = serializationObject.condition; - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${ConditionalBlockConditions[this.condition]};\n`; - return codeString; - } -} -RegisterClass("BABYLON.ConditionalBlock", ConditionalBlock); -//# sourceMappingURL=conditionalBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/cloudBlock.js - - - - - - -/** - * block used to Generate Fractal Brownian Motion Clouds - */ -class CloudBlock extends NodeMaterialBlock { - /** - * Creates a new CloudBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** Gets or sets the number of octaves */ - this.octaves = 6.0; - this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("chaos", NodeMaterialBlockConnectionPointTypes.AutoDetect, true); - this.registerInput("offsetX", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("offsetY", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("offsetZ", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); - this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2); - this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3); - this._linkConnectionTypes(0, 1); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "CloudBlock"; - } - /** - * Gets the seed input component - */ - get seed() { - return this._inputs[0]; - } - /** - * Gets the chaos input component - */ - get chaos() { - return this._inputs[1]; - } - /** - * Gets the offset X input component - */ - get offsetX() { - return this._inputs[2]; - } - /** - * Gets the offset Y input component - */ - get offsetY() { - return this._inputs[3]; - } - /** - * Gets the offset Z input component - */ - get offsetZ() { - return this._inputs[4]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - var _a, _b; - super._buildBlock(state); - if (!this.seed.isConnected) { - return; - } - if (!this._outputs[0].hasEndpoints) { - return; - } - const functionString = ` - - float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } - - // Based on Morgan McGuire @morgan3d - // https://www.shadertoy.com/view/4dS3Wd - float cloudNoise(in vec2 x, in vec2 chaos) { - vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); - - vec2 i = floor(x); - vec2 f = fract(x); - - float n = dot(i, step); - - vec2 u = f * f * (3.0 - 2.0 * f); - return mix( - mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), - mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), - u.y - ); - } - - float cloudNoise(in vec3 x, in vec3 chaos) { - vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); - - vec3 i = floor(x); - vec3 f = fract(x); - - float n = dot(i, step); - - vec3 u = f * f * (3.0 - 2.0 * f); - return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), - mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), - mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), - mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); - }`; - const fractalBrownianString = ` - float fbm(in vec2 st, in vec2 chaos) { - // Initial values - float value = 0.0; - float amplitude = .5; - float frequency = 0.; - - // Loop of octaves - for (int i = 0; i < OCTAVES; i++) { - value += amplitude * cloudNoise(st, chaos); - st *= 2.0; - amplitude *= 0.5; - } - return value; - } - - float fbm(in vec3 x, in vec3 chaos) { - // Initial values - float value = 0.0; - float amplitude = 0.5; - for (int i = 0; i < OCTAVES; ++i) { - value += amplitude * cloudNoise(x, chaos); - x = x * 2.0; - amplitude *= 0.5; - } - return value; - }`; - const fbmNewName = `fbm${this.octaves}`; - state._emitFunction("CloudBlockCode", functionString, "// CloudBlockCode"); - state._emitFunction("CloudBlockCodeFBM" + this.octaves, fractalBrownianString.replace(/fbm/gi, fbmNewName).replace(/OCTAVES/gi, (this.octaves | 0).toString()), "// CloudBlockCode FBM"); - const localVariable = state._getFreeVariableName("st"); - const seedType = ((_a = this.seed.connectedPoint) === null || _a === void 0 ? void 0 : _a.type) === NodeMaterialBlockConnectionPointTypes.Vector2 ? "vec2" : "vec3"; - state.compilationString += `${seedType} ${localVariable} = ${this.seed.associatedVariableName};\n`; - if (this.offsetX.isConnected) { - state.compilationString += `${localVariable}.x += 0.1 * ${this.offsetX.associatedVariableName};\n`; - } - if (this.offsetY.isConnected) { - state.compilationString += `${localVariable}.y += 0.1 * ${this.offsetY.associatedVariableName};\n`; - } - if (this.offsetZ.isConnected && seedType === "vec3") { - state.compilationString += `${localVariable}.z += 0.1 * ${this.offsetZ.associatedVariableName};\n`; - } - let chaosValue = ""; - if (this.chaos.isConnected) { - chaosValue = this.chaos.associatedVariableName; - } - else { - chaosValue = ((_b = this.seed.connectedPoint) === null || _b === void 0 ? void 0 : _b.type) === NodeMaterialBlockConnectionPointTypes.Vector2 ? "vec2(0., 0.)" : "vec3(0., 0., 0.)"; - } - state.compilationString += this._declareOutput(this._outputs[0], state) + ` = ${fbmNewName}(${localVariable}, ${chaosValue});\n`; - return this; - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.octaves = ${this.octaves};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.octaves = this.octaves; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.octaves = serializationObject.octaves; - } -} -__decorate([ - editableInPropertyPage("Octaves", PropertyTypeForEdition.Int) -], CloudBlock.prototype, "octaves", void 0); -RegisterClass("BABYLON.CloudBlock", CloudBlock); -//# sourceMappingURL=cloudBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/voronoiNoiseBlock.js - - - - -/** - * block used to Generate a Voronoi Noise Pattern - */ -class VoronoiNoiseBlock extends NodeMaterialBlock { - /** - * Creates a new VoronoiNoiseBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("seed", NodeMaterialBlockConnectionPointTypes.Vector2); - this.registerInput("offset", NodeMaterialBlockConnectionPointTypes.Float); - this.registerInput("density", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); - this.registerOutput("cells", NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "VoronoiNoiseBlock"; - } - /** - * Gets the seed input component - */ - get seed() { - return this._inputs[0]; - } - /** - * Gets the offset input component - */ - get offset() { - return this._inputs[1]; - } - /** - * Gets the density input component - */ - get density() { - return this._inputs[2]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets the output component - */ - get cells() { - return this._outputs[1]; - } - _buildBlock(state) { - super._buildBlock(state); - if (!this.seed.isConnected) { - return; - } - let functionString = `vec2 voronoiRandom(vec2 seed, float offset){ - mat2 m = mat2(15.27, 47.63, 99.41, 89.98); - vec2 uv = fract(sin(m * seed) * 46839.32); - return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5); - } - `; - state._emitFunction("voronoiRandom", functionString, "// Voronoi random generator"); - functionString = `void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ - vec2 g = floor(seed * density); - vec2 f = fract(seed * density); - float t = 8.0; - vec3 res = vec3(8.0, 0.0, 0.0); - - for(int y=-1; y<=1; y++) - { - for(int x=-1; x<=1; x++) - { - vec2 lattice = vec2(x,y); - vec2 randomOffset = voronoiRandom(lattice + g, offset); - float d = distance(lattice + randomOffset, f); - if(d < res.x) - { - res = vec3(d, randomOffset.x, randomOffset.y); - outValue = res.x; - cells = res.y; - } - } - } - } - `; - state._emitFunction("voronoi", functionString, "// Voronoi"); - const tempOutput = state._getFreeVariableName("tempOutput"); - const tempCells = state._getFreeVariableName("tempCells"); - state.compilationString += `float ${tempOutput} = 0.0;\n`; - state.compilationString += `float ${tempCells} = 0.0;\n`; - state.compilationString += `voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${tempOutput}, ${tempCells});\n`; - if (this.output.hasEndpoints) { - state.compilationString += this._declareOutput(this.output, state) + ` = ${tempOutput};\n`; - } - if (this.cells.hasEndpoints) { - state.compilationString += this._declareOutput(this.cells, state) + ` = ${tempCells};\n`; - } - return this; - } -} -RegisterClass("BABYLON.VoronoiNoiseBlock", VoronoiNoiseBlock); -//# sourceMappingURL=voronoiNoiseBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/elbowBlock.js - - - - -/** - * Block used as a pass through - */ -class ElbowBlock extends NodeMaterialBlock { - /** - * Creates a new ElbowBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ElbowBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets or sets the target of the block - */ - get target() { - const input = this._inputs[0]; - if (input.isConnected) { - const block = input.connectedPoint.ownerBlock; - if (block.target !== NodeMaterialBlockTargets.VertexAndFragment) { - return block.target; - } - if (input.connectedPoint.target !== NodeMaterialBlockTargets.VertexAndFragment) { - return input.connectedPoint.target; - } - } - return this._target; - } - set target(value) { - if ((this._target & value) !== 0) { - return; - } - this._target = value; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - const input = this._inputs[0]; - state.compilationString += this._declareOutput(output, state) + ` = ${input.associatedVariableName};\n`; - return this; - } -} -RegisterClass("BABYLON.ElbowBlock", ElbowBlock); -//# sourceMappingURL=elbowBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/triPlanarBlock.js - - - - - - - - - - - - - - -/** - * Block used to read a texture with triplanar mapping (see "boxmap" in https://iquilezles.org/articles/biplanar/) - */ -class TriPlanarBlock extends NodeMaterialBlock { - /** - * Gets or sets the texture associated with the node - */ - get texture() { - var _a; - if (this.source.isConnected) { - return ((_a = this.source.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock).texture; - } - return this._texture; - } - set texture(texture) { - var _a; - if (this._texture === texture) { - return; - } - const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : engineStore_EngineStore.LastCreatedScene; - if (!texture && scene) { - scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this._texture); - }); - } - this._texture = texture; - if (texture && scene) { - scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(texture); - }); - } - } - /** - * Gets the textureY associated with the node - */ - get textureY() { - var _a; - if (this.sourceY.isConnected) { - return ((_a = this.sourceY.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock).texture; - } - return null; - } - /** - * Gets the textureZ associated with the node - */ - get textureZ() { - var _a, _b; - if ((_a = this.sourceZ) === null || _a === void 0 ? void 0 : _a.isConnected) { - return ((_b = this.sourceY.connectedPoint) === null || _b === void 0 ? void 0 : _b.ownerBlock).texture; - } - return null; - } - _getImageSourceBlock(connectionPoint) { - return (connectionPoint === null || connectionPoint === void 0 ? void 0 : connectionPoint.isConnected) ? connectionPoint.connectedPoint.ownerBlock : null; - } - /** - * Gets the sampler name associated with this texture - */ - get samplerName() { - const imageSourceBlock = this._getImageSourceBlock(this.source); - if (imageSourceBlock) { - return imageSourceBlock.samplerName; - } - return this._samplerName; - } - /** - * Gets the samplerY name associated with this texture - */ - get samplerYName() { - var _a, _b; - return (_b = (_a = this._getImageSourceBlock(this.sourceY)) === null || _a === void 0 ? void 0 : _a.samplerName) !== null && _b !== void 0 ? _b : null; - } - /** - * Gets the samplerZ name associated with this texture - */ - get samplerZName() { - var _a, _b; - return (_b = (_a = this._getImageSourceBlock(this.sourceZ)) === null || _a === void 0 ? void 0 : _a.samplerName) !== null && _b !== void 0 ? _b : null; - } - /** - * Gets a boolean indicating that this block is linked to an ImageSourceBlock - */ - get hasImageSource() { - return this.source.isConnected; - } - /** - * Gets or sets a boolean indicating if content needs to be converted to gamma space - */ - set convertToGammaSpace(value) { - var _a; - if (value === this._convertToGammaSpace) { - return; - } - this._convertToGammaSpace = value; - if (this.texture) { - const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : engineStore_EngineStore.LastCreatedScene; - scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this.texture); - }); - } - } - get convertToGammaSpace() { - return this._convertToGammaSpace; - } - /** - * Gets or sets a boolean indicating if content needs to be converted to linear space - */ - set convertToLinearSpace(value) { - var _a; - if (value === this._convertToLinearSpace) { - return; - } - this._convertToLinearSpace = value; - if (this.texture) { - const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : engineStore_EngineStore.LastCreatedScene; - scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => { - return mat.hasTexture(this.texture); - }); - } - } - get convertToLinearSpace() { - return this._convertToLinearSpace; - } - /** - * Create a new TriPlanarBlock - * @param name defines the block name - */ - constructor(name, hideSourceZ = false) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Project the texture(s) for a better fit to a cube - */ - this.projectAsCube = false; - this._convertToGammaSpace = false; - this._convertToLinearSpace = false; - /** - * Gets or sets a boolean indicating if multiplication of texture with level should be disabled - */ - this.disableLevelMultiplication = false; - this.registerInput("position", NodeMaterialBlockConnectionPointTypes.AutoDetect, false); - this.registerInput("normal", NodeMaterialBlockConnectionPointTypes.AutoDetect, false); - this.registerInput("sharpness", NodeMaterialBlockConnectionPointTypes.Float, true); - this.registerInput("source", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("source", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, "ImageSourceBlock")); - this.registerInput("sourceY", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("sourceY", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, "ImageSourceBlock")); - if (!hideSourceZ) { - this.registerInput("sourceZ", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject("sourceZ", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, "ImageSourceBlock")); - } - this.registerOutput("rgba", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral); - this.registerOutput("rgb", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral); - this.registerOutput("r", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("g", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("b", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("a", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this.registerOutput("level", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral); - this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "TriPlanarBlock"; - } - /** - * Gets the position input component - */ - get position() { - return this._inputs[0]; - } - /** - * Gets the normal input component - */ - get normal() { - return this._inputs[1]; - } - /** - * Gets the sharpness input component - */ - get sharpness() { - return this._inputs[2]; - } - /** - * Gets the source input component - */ - get source() { - return this._inputs[3]; - } - /** - * Gets the sourceY input component - */ - get sourceY() { - return this._inputs[4]; - } - /** - * Gets the sourceZ input component - */ - get sourceZ() { - return this._inputs[5]; - } - /** - * Gets the rgba output component - */ - get rgba() { - return this._outputs[0]; - } - /** - * Gets the rgb output component - */ - get rgb() { - return this._outputs[1]; - } - /** - * Gets the r output component - */ - get r() { - return this._outputs[2]; - } - /** - * Gets the g output component - */ - get g() { - return this._outputs[3]; - } - /** - * Gets the b output component - */ - get b() { - return this._outputs[4]; - } - /** - * Gets the a output component - */ - get a() { - return this._outputs[5]; - } - /** - * Gets the level output component - */ - get level() { - return this._outputs[6]; - } - prepareDefines(mesh, nodeMaterial, defines) { - if (!defines._areTexturesDirty) { - return; - } - const toGamma = this.convertToGammaSpace && this.texture && !this.texture.gammaSpace; - const toLinear = this.convertToLinearSpace && this.texture && this.texture.gammaSpace; - // Not a bug... Name defines the texture space not the required conversion - defines.setValue(this._linearDefineName, toGamma, true); - defines.setValue(this._gammaDefineName, toLinear, true); - } - isReady() { - if (this.texture && !this.texture.isReadyOrNotBlocking()) { - return false; - } - return true; - } - bind(effect) { - if (!this.texture) { - return; - } - effect.setFloat(this._textureInfoName, this.texture.level); - if (!this._imageSource) { - effect.setTexture(this._samplerName, this.texture); - } - } - _generateTextureLookup(state) { - var _a, _b; - const samplerName = this.samplerName; - const samplerYName = (_a = this.samplerYName) !== null && _a !== void 0 ? _a : samplerName; - const samplerZName = (_b = this.samplerZName) !== null && _b !== void 0 ? _b : samplerName; - const sharpness = this.sharpness.isConnected ? this.sharpness.associatedVariableName : "1.0"; - const x = state._getFreeVariableName("x"); - const y = state._getFreeVariableName("y"); - const z = state._getFreeVariableName("z"); - const w = state._getFreeVariableName("w"); - const n = state._getFreeVariableName("n"); - const uvx = state._getFreeVariableName("uvx"); - const uvy = state._getFreeVariableName("uvy"); - const uvz = state._getFreeVariableName("uvz"); - state.compilationString += ` - vec3 ${n} = ${this.normal.associatedVariableName}.xyz; - - vec2 ${uvx} = ${this.position.associatedVariableName}.yz; - vec2 ${uvy} = ${this.position.associatedVariableName}.zx; - vec2 ${uvz} = ${this.position.associatedVariableName}.xy; - `; - if (this.projectAsCube) { - state.compilationString += ` - ${uvx}.xy = ${uvx}.yx; - - if (${n}.x >= 0.0) { - ${uvx}.x = -${uvx}.x; - } - if (${n}.y < 0.0) { - ${uvy}.y = -${uvy}.y; - } - if (${n}.z < 0.0) { - ${uvz}.x = -${uvz}.x; - } - `; - } - state.compilationString += ` - vec4 ${x} = texture2D(${samplerName}, ${uvx}); - vec4 ${y} = texture2D(${samplerYName}, ${uvy}); - vec4 ${z} = texture2D(${samplerZName}, ${uvz}); - - // blend weights - vec3 ${w} = pow(abs(${n}), vec3(${sharpness})); - - // blend and return - vec4 ${this._tempTextureRead} = (${x}*${w}.x + ${y}*${w}.y + ${z}*${w}.z) / (${w}.x + ${w}.y + ${w}.z); - `; - } - _generateConversionCode(state, output, swizzle) { - if (swizzle !== "a") { - // no conversion if the output is "a" (alpha) - if (!this.texture || !this.texture.gammaSpace) { - state.compilationString += `#ifdef ${this._linearDefineName} - ${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName}); - #endif - `; - } - state.compilationString += `#ifdef ${this._gammaDefineName} - ${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName}); - #endif - `; - } - } - _writeOutput(state, output, swizzle) { - let complement = ""; - if (!this.disableLevelMultiplication) { - complement = ` * ${this._textureInfoName}`; - } - state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle}${complement};\n`; - this._generateConversionCode(state, output, swizzle); - } - _buildBlock(state) { - super._buildBlock(state); - if (this.source.isConnected) { - this._imageSource = this.source.connectedPoint.ownerBlock; - } - else { - this._imageSource = null; - } - this._textureInfoName = state._getFreeVariableName("textureInfoName"); - this.level.associatedVariableName = this._textureInfoName; - this._tempTextureRead = state._getFreeVariableName("tempTextureRead"); - this._linearDefineName = state._getFreeDefineName("ISLINEAR"); - this._gammaDefineName = state._getFreeDefineName("ISGAMMA"); - if (!this._imageSource) { - this._samplerName = state._getFreeVariableName(this.name + "Sampler"); - state._emit2DSampler(this._samplerName); - } - // Declarations - state.sharedData.blockingBlocks.push(this); - state.sharedData.textureBlocks.push(this); - state.sharedData.blocksWithDefines.push(this); - state.sharedData.bindableBlocks.push(this); - const comments = `//${this.name}`; - state._emitFunctionFromInclude("helperFunctions", comments); - state._emitUniformFromString(this._textureInfoName, "float"); - this._generateTextureLookup(state); - for (const output of this._outputs) { - if (output.hasEndpoints && output.name !== "level") { - this._writeOutput(state, output, output.name); - } - } - return this; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`; - codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`; - codeString += `${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`; - codeString += `${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\n`; - if (!this.texture) { - return codeString; - } - codeString += `${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`; - codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`; - codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`; - codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`; - codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`; - codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`; - codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`; - codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`; - codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`; - codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`; - codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`; - return codeString; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.convertToGammaSpace = this.convertToGammaSpace; - serializationObject.convertToLinearSpace = this.convertToLinearSpace; - serializationObject.disableLevelMultiplication = this.disableLevelMultiplication; - serializationObject.projectAsCube = this.projectAsCube; - if (!this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== "VideoTexture") { - serializationObject.texture = this.texture.serialize(); - } - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.convertToGammaSpace = serializationObject.convertToGammaSpace; - this.convertToLinearSpace = !!serializationObject.convertToLinearSpace; - this.disableLevelMultiplication = !!serializationObject.disableLevelMultiplication; - this.projectAsCube = !!serializationObject.projectAsCube; - if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) { - rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl; - this.texture = texture_Texture.Parse(serializationObject.texture, scene, rootUrl); - } - } -} -__decorate([ - editableInPropertyPage("Project as cube", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], TriPlanarBlock.prototype, "projectAsCube", void 0); -RegisterClass("BABYLON.TriPlanarBlock", TriPlanarBlock); -//# sourceMappingURL=triPlanarBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/biPlanarBlock.js - - -/** - * Block used to read a texture with triplanar mapping (see https://iquilezles.org/articles/biplanar/) - */ -class BiPlanarBlock extends TriPlanarBlock { - /** - * Create a new BiPlanarBlock - * @param name defines the block name - */ - constructor(name) { - super(name, true); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "BiPlanarBlock"; - } - _generateTextureLookup(state) { - var _a; - const samplerName = this.samplerName; - const samplerYName = (_a = this.samplerYName) !== null && _a !== void 0 ? _a : this.samplerName; - const sharpness = this.sharpness.isConnected ? this.sharpness.associatedVariableName : "1.0"; - const dpdx = state._getFreeVariableName("dpdx"); - const dpdy = state._getFreeVariableName("dpdy"); - const n = state._getFreeVariableName("n"); - const ma = state._getFreeVariableName("ma"); - const mi = state._getFreeVariableName("mi"); - const me = state._getFreeVariableName("me"); - const x = state._getFreeVariableName("x"); - const y = state._getFreeVariableName("y"); - const w = state._getFreeVariableName("y"); - state.compilationString += ` - // grab coord derivatives for texturing - vec3 ${dpdx} = dFdx(${this.position.associatedVariableName}.xyz); - vec3 ${dpdy} = dFdy(${this.position.associatedVariableName}.xyz); - vec3 ${n} = abs(${this.normal.associatedVariableName}.xyz); - - // determine major axis (in x; yz are following axis) - ivec3 ${ma} = (${n}.x>${n}.y && ${n}.x>${n}.z) ? ivec3(0,1,2) : - (${n}.y>${n}.z) ? ivec3(1,2,0) : - ivec3(2,0,1) ; - // determine minor axis (in x; yz are following axis) - ivec3 ${mi} = (${n}.x<${n}.y && ${n}.x<${n}.z) ? ivec3(0,1,2) : - (${n}.y<${n}.z) ? ivec3(1,2,0) : - ivec3(2,0,1) ; - // determine median axis (in x; yz are following axis) - ivec3 ${me} = ivec3(3) - ${mi} - ${ma}; - - // project+fetch - vec4 ${x} = textureGrad( ${samplerName}, vec2( ${this.position.associatedVariableName}[${ma}.y], ${this.position.associatedVariableName}[${ma}.z]), - vec2(${dpdx}[${ma}.y],${dpdx}[${ma}.z]), - vec2(${dpdy}[${ma}.y],${dpdy}[${ma}.z]) ); - vec4 ${y} = textureGrad( ${samplerYName}, vec2( ${this.position.associatedVariableName}[${me}.y], ${this.position.associatedVariableName}[${me}.z]), - vec2(${dpdx}[${me}.y],${dpdx}[${me}.z]), - vec2(${dpdy}[${me}.y],${dpdy}[${me}.z]) ); - - // blend factors - vec2 ${w} = vec2(${n}[${ma}.x],${n}[${me}.x]); - // make local support - ${w} = clamp( (${w}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); - // shape transition - ${w} = pow( ${w}, vec2(${sharpness}/8.0) ); - // blend and return - vec4 ${this._tempTextureRead} = (${x}*${w}.x + ${y}*${w}.y) / (${w}.x + ${w}.y); - `; - } -} -RegisterClass("BABYLON.BiPlanarBlock", BiPlanarBlock); -//# sourceMappingURL=biPlanarBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/matrixDeterminantBlock.js - - - - -/** - * Block used to compute the determinant of a matrix - */ -class MatrixDeterminantBlock extends NodeMaterialBlock { - /** - * Creates a new MatrixDeterminantBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Matrix); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MatrixDeterminantBlock"; - } - /** - * Gets the input matrix - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this.output; - const input = this.input; - state.compilationString += this._declareOutput(output, state) + `${output.associatedVariableName} = determinant(${input.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.MatrixDeterminantBlock", MatrixDeterminantBlock); -//# sourceMappingURL=matrixDeterminantBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/matrixTransposeBlock.js - - - - -/** - * Block used to transpose a matrix - */ -class MatrixTransposeBlock extends NodeMaterialBlock { - /** - * Creates a new MatrixTransposeBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.Matrix); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MatrixTransposeBlock"; - } - /** - * Gets the input matrix - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this.output; - const input = this.input; - state.compilationString += this._declareOutput(output, state) + `${output.associatedVariableName} = transpose(${input.associatedVariableName});\n`; - return this; - } -} -RegisterClass("BABYLON.MatrixTransposeBlock", MatrixTransposeBlock); -//# sourceMappingURL=matrixTransposeBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/meshAttributeExistsBlock.js - - - - - - - - -var MeshAttributeExistsBlockTypes; -(function (MeshAttributeExistsBlockTypes) { - MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["None"] = 0] = "None"; - MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["Normal"] = 1] = "Normal"; - MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["Tangent"] = 2] = "Tangent"; - MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["VertexColor"] = 3] = "VertexColor"; - MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV1"] = 4] = "UV1"; - MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV2"] = 5] = "UV2"; - MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV3"] = 6] = "UV3"; - MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV4"] = 7] = "UV4"; - MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV5"] = 8] = "UV5"; - MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes["UV6"] = 9] = "UV6"; -})(MeshAttributeExistsBlockTypes || (MeshAttributeExistsBlockTypes = {})); -/** - * Block used to check if Mesh attribute of specified type exists - * and provide an alternative fallback input for to use in such case - */ -class MeshAttributeExistsBlock extends NodeMaterialBlock { - /** - * Creates a new MeshAttributeExistsBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Defines which mesh attribute to use - */ - this.attributeType = MeshAttributeExistsBlockTypes.None; - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerInput("fallback", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - // Try to auto determine attributeType - this._inputs[0].onConnectionObservable.add((other) => { - var _a; - if (this.attributeType) { - // But only if not already specified - return; - } - const sourceBlock = other.ownerBlock; - if (sourceBlock instanceof InputBlock && sourceBlock.isAttribute) { - switch (sourceBlock.name) { - case "color": - this.attributeType = MeshAttributeExistsBlockTypes.VertexColor; - break; - case "normal": - this.attributeType = MeshAttributeExistsBlockTypes.Normal; - break; - case "tangent": - this.attributeType = MeshAttributeExistsBlockTypes.Tangent; - break; - case "uv": - this.attributeType = MeshAttributeExistsBlockTypes.UV1; - break; - case "uv2": - this.attributeType = MeshAttributeExistsBlockTypes.UV2; - break; - case "uv3": - this.attributeType = MeshAttributeExistsBlockTypes.UV3; - break; - case "uv4": - this.attributeType = MeshAttributeExistsBlockTypes.UV4; - break; - case "uv5": - this.attributeType = MeshAttributeExistsBlockTypes.UV5; - break; - case "uv6": - this.attributeType = MeshAttributeExistsBlockTypes.UV6; - break; - } - } - else if (sourceBlock instanceof MorphTargetsBlock) { - switch ((_a = this.input.connectedPoint) === null || _a === void 0 ? void 0 : _a.name) { - case "normalOutput": - this.attributeType = MeshAttributeExistsBlockTypes.Normal; - break; - case "tangentOutput": - this.attributeType = MeshAttributeExistsBlockTypes.Tangent; - break; - case "uvOutput": - this.attributeType = MeshAttributeExistsBlockTypes.UV1; - break; - } - } - }); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MeshAttributeExistsBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the fallback component when speciefied attribute doesn't exist - */ - get fallback() { - return this._inputs[1]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - let attributeDefine = null; - switch (this.attributeType) { - case MeshAttributeExistsBlockTypes.VertexColor: - attributeDefine = "VERTEXCOLOR_NME"; - break; - case MeshAttributeExistsBlockTypes.Normal: - attributeDefine = "NORMAL"; - break; - case MeshAttributeExistsBlockTypes.Tangent: - attributeDefine = "TANGENT"; - break; - case MeshAttributeExistsBlockTypes.UV1: - attributeDefine = "UV1"; - break; - case MeshAttributeExistsBlockTypes.UV2: - attributeDefine = "UV2"; - break; - case MeshAttributeExistsBlockTypes.UV3: - attributeDefine = "UV3"; - break; - case MeshAttributeExistsBlockTypes.UV4: - attributeDefine = "UV4"; - break; - case MeshAttributeExistsBlockTypes.UV5: - attributeDefine = "UV5"; - break; - case MeshAttributeExistsBlockTypes.UV6: - attributeDefine = "UV6"; - break; - } - const output = this._declareOutput(this.output, state); - if (attributeDefine) { - state.compilationString += `#ifdef ${attributeDefine}\n`; - } - state.compilationString += `${output} = ${this.input.associatedVariableName};\n`; - if (attributeDefine) { - state.compilationString += `#else\n`; - state.compilationString += `${output} = ${this.fallback.associatedVariableName};\n`; - state.compilationString += `#endif\n`; - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.attributeType = this.attributeType; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - var _a; - super._deserialize(serializationObject, scene, rootUrl); - this.attributeType = (_a = serializationObject.attributeType) !== null && _a !== void 0 ? _a : MeshAttributeExistsBlockTypes.None; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - codeString += `${this._codeVariableName}.attributeType = ${this.attributeType};\n`; - return codeString; - } -} -__decorate([ - editableInPropertyPage("Attribute lookup", PropertyTypeForEdition.List, undefined, { - notifiers: { update: true }, - options: [ - { label: "(None)", value: MeshAttributeExistsBlockTypes.None }, - { label: "Normal", value: MeshAttributeExistsBlockTypes.Normal }, - { label: "Tangent", value: MeshAttributeExistsBlockTypes.Tangent }, - { label: "Vertex Color", value: MeshAttributeExistsBlockTypes.VertexColor }, - { label: "UV1", value: MeshAttributeExistsBlockTypes.UV1 }, - { label: "UV2", value: MeshAttributeExistsBlockTypes.UV2 }, - { label: "UV3", value: MeshAttributeExistsBlockTypes.UV3 }, - { label: "UV4", value: MeshAttributeExistsBlockTypes.UV4 }, - { label: "UV5", value: MeshAttributeExistsBlockTypes.UV5 }, - { label: "UV6", value: MeshAttributeExistsBlockTypes.UV6 }, - ], - }) -], MeshAttributeExistsBlock.prototype, "attributeType", void 0); -RegisterClass("BABYLON.MeshAttributeExistsBlock", MeshAttributeExistsBlock); -//# sourceMappingURL=meshAttributeExistsBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/curveBlock.js - - - - -/** - * Types of curves supported by the Curve block - */ -var CurveBlockTypes; -(function (CurveBlockTypes) { - /** EaseInSine */ - CurveBlockTypes[CurveBlockTypes["EaseInSine"] = 0] = "EaseInSine"; - /** EaseOutSine */ - CurveBlockTypes[CurveBlockTypes["EaseOutSine"] = 1] = "EaseOutSine"; - /** EaseInOutSine */ - CurveBlockTypes[CurveBlockTypes["EaseInOutSine"] = 2] = "EaseInOutSine"; - /** EaseInQuad */ - CurveBlockTypes[CurveBlockTypes["EaseInQuad"] = 3] = "EaseInQuad"; - /** EaseOutQuad */ - CurveBlockTypes[CurveBlockTypes["EaseOutQuad"] = 4] = "EaseOutQuad"; - /** EaseInOutQuad */ - CurveBlockTypes[CurveBlockTypes["EaseInOutQuad"] = 5] = "EaseInOutQuad"; - /** EaseInCubic */ - CurveBlockTypes[CurveBlockTypes["EaseInCubic"] = 6] = "EaseInCubic"; - /** EaseOutCubic */ - CurveBlockTypes[CurveBlockTypes["EaseOutCubic"] = 7] = "EaseOutCubic"; - /** EaseInOutCubic */ - CurveBlockTypes[CurveBlockTypes["EaseInOutCubic"] = 8] = "EaseInOutCubic"; - /** EaseInQuart */ - CurveBlockTypes[CurveBlockTypes["EaseInQuart"] = 9] = "EaseInQuart"; - /** EaseOutQuart */ - CurveBlockTypes[CurveBlockTypes["EaseOutQuart"] = 10] = "EaseOutQuart"; - /** EaseInOutQuart */ - CurveBlockTypes[CurveBlockTypes["EaseInOutQuart"] = 11] = "EaseInOutQuart"; - /** EaseInQuint */ - CurveBlockTypes[CurveBlockTypes["EaseInQuint"] = 12] = "EaseInQuint"; - /** EaseOutQuint */ - CurveBlockTypes[CurveBlockTypes["EaseOutQuint"] = 13] = "EaseOutQuint"; - /** EaseInOutQuint */ - CurveBlockTypes[CurveBlockTypes["EaseInOutQuint"] = 14] = "EaseInOutQuint"; - /** EaseInExpo */ - CurveBlockTypes[CurveBlockTypes["EaseInExpo"] = 15] = "EaseInExpo"; - /** EaseOutExpo */ - CurveBlockTypes[CurveBlockTypes["EaseOutExpo"] = 16] = "EaseOutExpo"; - /** EaseInOutExpo */ - CurveBlockTypes[CurveBlockTypes["EaseInOutExpo"] = 17] = "EaseInOutExpo"; - /** EaseInCirc */ - CurveBlockTypes[CurveBlockTypes["EaseInCirc"] = 18] = "EaseInCirc"; - /** EaseOutCirc */ - CurveBlockTypes[CurveBlockTypes["EaseOutCirc"] = 19] = "EaseOutCirc"; - /** EaseInOutCirc */ - CurveBlockTypes[CurveBlockTypes["EaseInOutCirc"] = 20] = "EaseInOutCirc"; - /** EaseInBack */ - CurveBlockTypes[CurveBlockTypes["EaseInBack"] = 21] = "EaseInBack"; - /** EaseOutBack */ - CurveBlockTypes[CurveBlockTypes["EaseOutBack"] = 22] = "EaseOutBack"; - /** EaseInOutBack */ - CurveBlockTypes[CurveBlockTypes["EaseInOutBack"] = 23] = "EaseInOutBack"; - /** EaseInElastic */ - CurveBlockTypes[CurveBlockTypes["EaseInElastic"] = 24] = "EaseInElastic"; - /** EaseOutElastic */ - CurveBlockTypes[CurveBlockTypes["EaseOutElastic"] = 25] = "EaseOutElastic"; - /** EaseInOutElastic */ - CurveBlockTypes[CurveBlockTypes["EaseInOutElastic"] = 26] = "EaseInOutElastic"; -})(CurveBlockTypes || (CurveBlockTypes = {})); -/** - * Block used to apply curve operation - */ -class CurveBlock extends NodeMaterialBlock { - /** - * Creates a new CurveBlock - * @param name defines the block name - */ - constructor(name) { - super(name, NodeMaterialBlockTargets.Neutral); - /** - * Gets or sets the type of the curve applied by the block - */ - this.type = CurveBlockTypes.EaseInOutSine; - this.registerInput("input", NodeMaterialBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeMaterialBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Object); - this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Int); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "CurveBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _duplicateEntry(entry, component) { - return `ret.${component} = ${entry.replace(/VAL/g, "v." + component)}`; - } - _duplicateEntryDirect(entry) { - return `return ${entry.replace(/VAL/g, "v")}`; - } - _duplicateVector(entry, inputType) { - if (inputType === "float") { - return this._duplicateEntryDirect(entry); - } - const size = parseInt(inputType.replace("vec", "")); - let code = ` - vec${size} ret = vec${size}(0.0); - `; - for (let i = 1; i <= size; i++) { - code += this._duplicateEntry(entry, i === 1 ? "x" : i === 2 ? "y" : i === 3 ? "z" : "w") + ";\n"; - } - code += "return ret;\n"; - return code; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - let registeredFunction = ""; - let registeredFunctionName = ""; - let inputType = ""; - switch (this.input.type) { - case NodeMaterialBlockConnectionPointTypes.Float: - inputType = "float"; - break; - case NodeMaterialBlockConnectionPointTypes.Vector2: - inputType = "vec2"; - break; - case NodeMaterialBlockConnectionPointTypes.Vector3: - case NodeMaterialBlockConnectionPointTypes.Color3: - inputType = "vec3"; - break; - case NodeMaterialBlockConnectionPointTypes.Vector4: - case NodeMaterialBlockConnectionPointTypes.Color4: - inputType = "vec4"; - break; - } - registeredFunctionName = CurveBlockTypes[this.type] + "_" + inputType; - switch (this.type) { - case CurveBlockTypes.EaseInSine: - registeredFunction = `return 1.0 - cos((v * 3.1415) / 2.0)`; - break; - case CurveBlockTypes.EaseOutSine: - registeredFunction = `return sin((v * 3.1415) / 2.0)`; - break; - case CurveBlockTypes.EaseInOutSine: - registeredFunction = `return -(cos(v * 3.1415) - 1.0) / 2.0`; - break; - case CurveBlockTypes.EaseInQuad: - registeredFunction = `return v * v`; - break; - case CurveBlockTypes.EaseOutQuad: - registeredFunction = `return (1.0 - v) * (1.0 - v)`; - break; - case CurveBlockTypes.EaseInOutQuad: { - const entry = "VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInCubic: - registeredFunction = `return v * v * v`; - break; - case CurveBlockTypes.EaseOutCubic: { - const entry = "1.0 - pow(1.0 - VAL, 3.0)"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInOutCubic: { - const entry = "VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInQuart: - registeredFunction = `return v * v * v * v`; - break; - case CurveBlockTypes.EaseOutQuart: { - const entry = "1.0 - pow(1.0 - VAL, 4.0)"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInOutQuart: { - const entry = "VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInQuint: - registeredFunction = `return v * v * v * v * v`; - break; - case CurveBlockTypes.EaseOutQuint: { - const entry = "1.0 - pow(1.0 - VAL, 5.0)"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInOutQuint: { - const entry = "VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInExpo: { - const entry = "VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseOutExpo: { - const entry = "VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInOutExpo: { - 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"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInCirc: { - const entry = "1.0 - sqrt(1.0 - pow(VAL, 2.0))"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseOutCirc: { - const entry = "sqrt(1.0 - pow(VAL - 1.0, 2.0))"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInOutCirc: { - 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"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInBack: { - registeredFunction = "return 2.70158 * v * v * v - 1.70158 * v * v"; - break; - } - case CurveBlockTypes.EaseOutBack: { - const entry = "2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInOutBack: { - 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"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInElastic: { - 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))"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseOutElastic: { - 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"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - case CurveBlockTypes.EaseInOutElastic: { - 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"; - registeredFunction = this._duplicateVector(entry, inputType); - break; - } - } - state._emitFunction(registeredFunctionName, `${inputType} ${registeredFunctionName}(${inputType} v) {${registeredFunction};}\n`, ""); - state.compilationString += this._declareOutput(output, state) + ` = ${registeredFunctionName}(${this.input.associatedVariableName});\n`; - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.curveType = this.type; - return serializationObject; - } - _deserialize(serializationObject, scene, rootUrl) { - super._deserialize(serializationObject, scene, rootUrl); - this.type = serializationObject.curveType; - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${CurveBlockTypes[this.type]};\n`; - return codeString; - } -} -RegisterClass("BABYLON.CurveBlock", CurveBlock); -//# sourceMappingURL=curveBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Blocks/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Optimizers/nodeMaterialOptimizer.js -/** - * Root class for all node material optimizers - */ -class NodeMaterialOptimizer { - /** - * Function used to optimize a NodeMaterial graph - * @param _vertexOutputNodes defines the list of output nodes for the vertex shader - * @param _fragmentOutputNodes defines the list of output nodes for the fragment shader - */ - optimize(_vertexOutputNodes, _fragmentOutputNodes) { - // Do nothing by default - } -} -//# sourceMappingURL=nodeMaterialOptimizer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/Optimizers/index.js - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Node/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/shadowDepthWrapper.js - - - - -class MapMap { - constructor() { - this.mm = new Map(); - } - get(a, b) { - const m = this.mm.get(a); - if (m !== undefined) { - return m.get(b); - } - return undefined; - } - set(a, b, v) { - let m = this.mm.get(a); - if (m === undefined) { - this.mm.set(a, (m = new Map())); - } - m.set(b, v); - } -} -/** - * Class that can be used to wrap a base material to generate accurate shadows when using custom vertex/fragment code in the base material - */ -class ShadowDepthWrapper { - /** Gets the standalone status of the wrapper */ - get standalone() { - var _a, _b; - return (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.standalone) !== null && _b !== void 0 ? _b : false; - } - /** Gets the base material the wrapper is built upon */ - get baseMaterial() { - return this._baseMaterial; - } - /** Gets the doNotInjectCode status of the wrapper */ - get doNotInjectCode() { - var _a, _b; - return (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.doNotInjectCode) !== null && _b !== void 0 ? _b : false; - } - /** - * Instantiate a new shadow depth wrapper. - * It works by injecting some specific code in the vertex/fragment shaders of the base material and is used by a shadow generator to - * generate the shadow depth map. For more information, please refer to the documentation: - * https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows - * @param baseMaterial Material to wrap - * @param scene Define the scene the material belongs to - * @param options Options used to create the wrapper - */ - constructor(baseMaterial, scene, options) { - this._baseMaterial = baseMaterial; - this._scene = scene !== null && scene !== void 0 ? scene : EngineStore.LastCreatedScene; - this._options = options; - this._subMeshToEffect = new Map(); - this._subMeshToDepthWrapper = new MapMap(); - this._meshes = new Map(); - // Register for onEffectCreated to store the effect of the base material when it is (re)generated. This effect will be used - // to create the depth effect later on - this._onEffectCreatedObserver = this._baseMaterial.onEffectCreatedObservable.add((params) => { - var _a; - const mesh = (_a = params.subMesh) === null || _a === void 0 ? void 0 : _a.getMesh(); - if (mesh && !this._meshes.has(mesh)) { - // Register for mesh onDispose to clean up our internal maps when a mesh is disposed - this._meshes.set(mesh, mesh.onDisposeObservable.add((mesh) => { - const iterator = this._subMeshToEffect.keys(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const subMesh = key.value; - if ((subMesh === null || subMesh === void 0 ? void 0 : subMesh.getMesh()) === mesh) { - this._subMeshToEffect.delete(subMesh); - this._subMeshToDepthWrapper.mm.delete(subMesh); - } - } - })); - } - this._subMeshToEffect.set(params.subMesh, [params.effect, this._scene.getEngine().currentRenderPassId]); - this._subMeshToDepthWrapper.mm.delete(params.subMesh); // trigger a depth effect recreation - }); - } - /** - * Gets the effect to use to generate the depth map - * @param subMesh subMesh to get the effect for - * @param shadowGenerator shadow generator to get the effect for - * @param passIdForDrawWrapper Id of the pass for which the effect from the draw wrapper must be retrieved from - * @returns the effect to use to generate the depth map for the subMesh + shadow generator specified - */ - getEffect(subMesh, shadowGenerator, passIdForDrawWrapper) { - var _a; - const entry = (_a = this._subMeshToDepthWrapper.mm.get(subMesh)) === null || _a === void 0 ? void 0 : _a.get(shadowGenerator); - if (!entry) { - return null; - } - let drawWrapper = entry.drawWrapper[passIdForDrawWrapper]; - if (!drawWrapper) { - drawWrapper = entry.drawWrapper[passIdForDrawWrapper] = new DrawWrapper(this._scene.getEngine()); - drawWrapper.setEffect(entry.mainDrawWrapper.effect, entry.mainDrawWrapper.defines); - } - return drawWrapper; - } - /** - * Specifies that the submesh is ready to be used for depth rendering - * @param subMesh submesh to check - * @param defines the list of defines to take into account when checking the effect - * @param shadowGenerator combined with subMesh, it defines the effect to check - * @param useInstances specifies that instances should be used - * @param passIdForDrawWrapper Id of the pass for which the draw wrapper should be created - * @returns a boolean indicating that the submesh is ready or not - */ - isReadyForSubMesh(subMesh, defines, shadowGenerator, useInstances, passIdForDrawWrapper) { - var _a, _b; - if (this.standalone) { - // will ensure the effect is (re)created for the base material - if (!this._baseMaterial.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) { - return false; - } - } - return (_b = (_a = this._makeEffect(subMesh, defines, shadowGenerator, passIdForDrawWrapper)) === null || _a === void 0 ? void 0 : _a.isReady()) !== null && _b !== void 0 ? _b : false; - } - /** - * Disposes the resources - */ - dispose() { - this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver); - this._onEffectCreatedObserver = null; - const iterator = this._meshes.entries(); - for (let entry = iterator.next(); entry.done !== true; entry = iterator.next()) { - const [mesh, observer] = entry.value; - mesh.onDisposeObservable.remove(observer); - } - } - _makeEffect(subMesh, defines, shadowGenerator, passIdForDrawWrapper) { - var _a, _b, _c; - const engine = this._scene.getEngine(); - const origEffectAndRenderPassId = this._subMeshToEffect.get(subMesh); - if (!origEffectAndRenderPassId) { - return null; - } - const [origEffect, origRenderPassId] = origEffectAndRenderPassId; - let params = this._subMeshToDepthWrapper.get(subMesh, shadowGenerator); - if (!params) { - const mainDrawWrapper = new DrawWrapper(engine); - mainDrawWrapper.defines = (_b = (_a = subMesh._getDrawWrapper(origRenderPassId)) === null || _a === void 0 ? void 0 : _a.defines) !== null && _b !== void 0 ? _b : null; - params = { - drawWrapper: [], - mainDrawWrapper, - depthDefines: "", - token: RandomGUID(), - }; - params.drawWrapper[passIdForDrawWrapper] = mainDrawWrapper; - this._subMeshToDepthWrapper.set(subMesh, shadowGenerator, params); - } - const join = defines.join("\n"); - if (params.mainDrawWrapper.effect) { - if (join === params.depthDefines) { - // we already created the depth effect and it is still up to date for this submesh + shadow generator - return params.mainDrawWrapper.effect; - } - } - params.depthDefines = join; - const uniforms = origEffect.getUniformNames().slice(); - // the depth effect is either out of date or has not been created yet - let vertexCode = origEffect.vertexSourceCodeBeforeMigration, fragmentCode = origEffect.fragmentSourceCodeBeforeMigration; - if (!this.doNotInjectCode) { - // vertex code - const vertexNormalBiasCode = this._options && this._options.remappedVariables - ? `#include<shadowMapVertexNormalBias>(${this._options.remappedVariables.join(",")})` - : Effect.IncludesShadersStore["shadowMapVertexNormalBias"], vertexMetricCode = this._options && this._options.remappedVariables - ? `#include<shadowMapVertexMetric>(${this._options.remappedVariables.join(",")})` - : Effect.IncludesShadersStore["shadowMapVertexMetric"], fragmentSoftTransparentShadow = this._options && this._options.remappedVariables - ? `#include<shadowMapFragmentSoftTransparentShadow>(${this._options.remappedVariables.join(",")})` - : Effect.IncludesShadersStore["shadowMapFragmentSoftTransparentShadow"], fragmentBlockCode = Effect.IncludesShadersStore["shadowMapFragment"]; - vertexCode = vertexCode.replace(/void\s+?main/g, Effect.IncludesShadersStore["shadowMapVertexExtraDeclaration"] + "\nvoid main"); - vertexCode = vertexCode.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g, vertexNormalBiasCode); - if (vertexCode.indexOf("#define SHADOWDEPTH_METRIC") !== -1) { - vertexCode = vertexCode.replace(/#define SHADOWDEPTH_METRIC/g, vertexMetricCode); - } - else { - vertexCode = vertexCode.replace(/}\s*$/g, vertexMetricCode + "\n}"); - } - vertexCode = vertexCode.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g, ""); - // fragment code - const hasLocationForSoftTransparentShadow = fragmentCode.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW") >= 0 || fragmentCode.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG") >= 0; - const hasLocationForFragment = fragmentCode.indexOf("#define SHADOWDEPTH_FRAGMENT") !== -1; - let fragmentCodeToInjectAtEnd = ""; - if (!hasLocationForSoftTransparentShadow) { - fragmentCodeToInjectAtEnd = fragmentSoftTransparentShadow + "\n"; - } - else { - fragmentCode = fragmentCode.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g, fragmentSoftTransparentShadow); - } - fragmentCode = fragmentCode.replace(/void\s+?main/g, Effect.IncludesShadersStore["shadowMapFragmentExtraDeclaration"] + "\nvoid main"); - if (hasLocationForFragment) { - fragmentCode = fragmentCode.replace(/#define SHADOWDEPTH_FRAGMENT/g, fragmentBlockCode); - } - else { - fragmentCodeToInjectAtEnd += fragmentBlockCode + "\n"; - } - if (fragmentCodeToInjectAtEnd) { - fragmentCode = fragmentCode.replace(/}\s*$/g, fragmentCodeToInjectAtEnd + "}"); - } - uniforms.push("biasAndScaleSM", "depthValuesSM", "lightDataSM", "softTransparentShadowSM"); - } - params.mainDrawWrapper.effect = engine.createEffect({ - vertexSource: vertexCode, - fragmentSource: fragmentCode, - vertexToken: params.token, - fragmentToken: params.token, - }, { - attributes: origEffect.getAttributesNames(), - uniformsNames: uniforms, - uniformBuffersNames: origEffect.getUniformBuffersNames(), - samplers: origEffect.getSamplers(), - defines: join + "\n" + origEffect.defines.replace("#define SHADOWS", "").replace(/#define SHADOW\d/g, ""), - indexParameters: origEffect.getIndexParameters(), - }, engine); - for (let id = 0; id < params.drawWrapper.length; ++id) { - if (id !== passIdForDrawWrapper) { - (_c = params.drawWrapper[id]) === null || _c === void 0 ? void 0 : _c.setEffect(params.mainDrawWrapper.effect, params.mainDrawWrapper.defines); - } - } - return params.mainDrawWrapper.effect; - } -} -//# sourceMappingURL=shadowDepthWrapper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/material.decalMapConfiguration.js - - - - - - - - -/** - * @internal - */ -class DecalMapDefines extends MaterialDefines { - constructor() { - super(...arguments); - this.DECAL = false; - this.DECALDIRECTUV = 0; - this.DECAL_SMOOTHALPHA = false; - this.GAMMADECAL = false; - } -} -/** - * Plugin that implements the decal map component of a material - * @since 5.49.1 - */ -class DecalMapConfiguration extends MaterialPluginBase { - /** @internal */ - _markAllSubMeshesAsTexturesDirty() { - this._enable(this._isEnabled); - this._internalMarkAllSubMeshesAsTexturesDirty(); - } - /** - * Creates a new DecalMapConfiguration - * @param material The material to attach the decal map plugin to - * @param addToPluginList If the plugin should be added to the material plugin list - */ - constructor(material, addToPluginList = true) { - super(material, "DecalMap", 150, new DecalMapDefines(), addToPluginList); - this._isEnabled = false; - /** - * Enables or disables the decal map on this material - */ - this.isEnabled = false; - this._smoothAlpha = false; - /** - * Enables or disables the smooth alpha mode on this material. Default: false. - * When enabled, the alpha value used to blend the decal map will be the squared value and will produce a smoother result. - */ - this.smoothAlpha = false; - this.registerForExtraEvents = true; // because we override the hardBindForSubMesh method - this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; - } - isReadyForSubMesh(defines, scene, engine, subMesh) { - const decalMap = subMesh.getMesh().decalMap; - if (!this._isEnabled || !(decalMap === null || decalMap === void 0 ? void 0 : decalMap.texture) || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) { - return true; - } - return decalMap.isReady(); - } - prepareDefines(defines, scene, mesh) { - const decalMap = mesh.decalMap; - if (!this._isEnabled || !(decalMap === null || decalMap === void 0 ? void 0 : decalMap.texture) || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) { - const isDirty = defines.DECAL; - if (isDirty) { - defines.markAsTexturesDirty(); - } - defines.DECAL = false; - } - else { - const isDirty = !defines.DECAL || defines.GAMMADECAL !== decalMap.texture.gammaSpace; - if (isDirty) { - defines.markAsTexturesDirty(); - } - defines.DECAL = true; - defines.GAMMADECAL = decalMap.texture.gammaSpace; - defines.DECAL_SMOOTHALPHA = this._smoothAlpha; - MaterialHelper.PrepareDefinesForMergedUV(decalMap.texture, defines, "DECAL"); - } - } - /** - * Note that we override hardBindForSubMesh and not bindForSubMesh because the material can be shared by multiple meshes, - * in which case mustRebind could return false even though the decal map is different for each mesh: that's because the decal map - * is not part of the material but hosted by the decalMap of the mesh instead. - */ - hardBindForSubMesh(uniformBuffer, scene, _engine, subMesh) { - const decalMap = subMesh.getMesh().decalMap; - if (!this._isEnabled || !(decalMap === null || decalMap === void 0 ? void 0 : decalMap.texture) || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) { - return; - } - const isFrozen = this._material.isFrozen; - const texture = decalMap.texture; - if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { - uniformBuffer.updateFloat4("vDecalInfos", texture.coordinatesIndex, 0, 0, 0); - MaterialHelper.BindTextureMatrix(texture, uniformBuffer, "decal"); - } - uniformBuffer.setTexture("decalSampler", texture); - } - getClassName() { - return "DecalMapConfiguration"; - } - getSamplers(samplers) { - samplers.push("decalSampler"); - } - getUniforms() { - return { - ubo: [ - { name: "vDecalInfos", size: 4, type: "vec4" }, - { name: "decalMatrix", size: 16, type: "mat4" }, - ], - }; - } -} -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], DecalMapConfiguration.prototype, "isEnabled", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllSubMeshesAsTexturesDirty") -], DecalMapConfiguration.prototype, "smoothAlpha", void 0); -RegisterClass("BABYLON.DecalMapConfiguration", DecalMapConfiguration); -//# sourceMappingURL=material.decalMapConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/materialPluginFactoryExport.js - - - - - - - - - -/** - * Creates an instance of the anisotropic plugin - * @param material parent material the plugin will be created for - * @returns the plugin instance or null if the plugin is incompatible with material - */ -function createPBRAnisotropicPlugin(material) { - if (material instanceof PBRBaseMaterial) { - return new PBRAnisotropicConfiguration(material); - } - return null; -} -/** - * Creates an instance of the brdf plugin - * @param material parent material the plugin will be created for - * @returns the plugin instance or null if the plugin is incompatible with material - */ -function createPBRBRDFPlugin(material) { - if (material instanceof PBRBaseMaterial) { - return new PBRBRDFConfiguration(material); - } - return null; -} -/** - * Creates an instance of the clear coat plugin - * @param material parent material the plugin will be created for - * @returns the plugin instance or null if the plugin is incompatible with material - */ -function createPBRClearCoatPlugin(material) { - if (material instanceof PBRBaseMaterial) { - return new PBRClearCoatConfiguration(material); - } - return null; -} -/** - * Creates an instance of the iridescence plugin - * @param material parent material the plugin will be created for - * @returns the plugin instance or null if the plugin is incompatible with material - */ -function createPBRIridescencePlugin(material) { - if (material instanceof PBRBaseMaterial) { - return new PBRIridescenceConfiguration(material); - } - return null; -} -/** - * Creates an instance of the sheen plugin - * @param material parent material the plugin will be created for - * @returns the plugin instance or null if the plugin is incompatible with material - */ -function createPBRSheenPlugin(material) { - if (material instanceof PBRBaseMaterial) { - return new PBRSheenConfiguration(material); - } - return null; -} -/** - * Creates an instance of the sub surface plugin - * @param material parent material the plugin will be created for - * @returns the plugin instance or null if the plugin is incompatible with material - */ -function createPBRSubSurfacePlugin(material) { - if (material instanceof PBRBaseMaterial) { - return new PBRSubSurfaceConfiguration(material); - } - return null; -} -/** - * Creates an instance of the detail map plugin - * @param material parent material the plugin will be created for - * @returns the plugin instance or null if the plugin is incompatible with material - */ -function createDetailMapPlugin(material) { - if (material instanceof PBRBaseMaterial || material instanceof StandardMaterial) { - return new DetailMapConfiguration(material); - } - return null; -} -//# sourceMappingURL=materialPluginFactoryExport.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/greasedLinePluginMaterial.js - - - - - - - -/** - * Material types for GreasedLine - * {@link https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/greased_line#materialtype} - */ -var greasedLinePluginMaterial_GreasedLineMeshMaterialType; -(function (GreasedLineMeshMaterialType) { - /** - * StandardMaterial - */ - GreasedLineMeshMaterialType[GreasedLineMeshMaterialType["MATERIAL_TYPE_STANDARD"] = 0] = "MATERIAL_TYPE_STANDARD"; - /** - * PBR Material - */ - GreasedLineMeshMaterialType[GreasedLineMeshMaterialType["MATERIAL_TYPE_PBR"] = 1] = "MATERIAL_TYPE_PBR"; - /** - * Simple and fast shader material not supporting lightning nor textures - */ - GreasedLineMeshMaterialType[GreasedLineMeshMaterialType["MATERIAL_TYPE_SIMPLE"] = 2] = "MATERIAL_TYPE_SIMPLE"; -})(greasedLinePluginMaterial_GreasedLineMeshMaterialType || (greasedLinePluginMaterial_GreasedLineMeshMaterialType = {})); -/** - * Color blending mode of the @see GreasedLineMaterial and the base material - * {@link https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/greased_line#colormode} - */ -var GreasedLineMeshColorMode; -(function (GreasedLineMeshColorMode) { - /** - * Color blending mode SET - */ - GreasedLineMeshColorMode[GreasedLineMeshColorMode["COLOR_MODE_SET"] = 0] = "COLOR_MODE_SET"; - /** - * Color blending mode ADD - */ - GreasedLineMeshColorMode[GreasedLineMeshColorMode["COLOR_MODE_ADD"] = 1] = "COLOR_MODE_ADD"; - /** - * Color blending mode ADD - */ - GreasedLineMeshColorMode[GreasedLineMeshColorMode["COLOR_MODE_MULTIPLY"] = 2] = "COLOR_MODE_MULTIPLY"; -})(GreasedLineMeshColorMode || (GreasedLineMeshColorMode = {})); -/** - * Color distribution type of the @see colors. - * {@link https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/greased_line#colordistributiontype} - * - */ -var GreasedLineMeshColorDistributionType; -(function (GreasedLineMeshColorDistributionType) { - /** - * Colors distributed between segments of the line - */ - GreasedLineMeshColorDistributionType[GreasedLineMeshColorDistributionType["COLOR_DISTRIBUTION_TYPE_SEGMENT"] = 0] = "COLOR_DISTRIBUTION_TYPE_SEGMENT"; - /** - * Colors distributed along the line ingoring the segments - */ - GreasedLineMeshColorDistributionType[GreasedLineMeshColorDistributionType["COLOR_DISTRIBUTION_TYPE_LINE"] = 1] = "COLOR_DISTRIBUTION_TYPE_LINE"; -})(GreasedLineMeshColorDistributionType || (GreasedLineMeshColorDistributionType = {})); -/** - * @internal - */ -class MaterialGreasedLineDefines extends MaterialDefines { - constructor() { - super(...arguments); - /** - * The material has a color option specified - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - this.GREASED_LINE_HAS_COLOR = false; - /** - * The material's size attenuation optiom - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - this.GREASED_LINE_SIZE_ATTENUATION = false; - /** - * The type of color distribution is set to line this value equals to true. - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = false; - /** - * True if scene is in right handed coordinate system. - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - this.GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM = false; - } -} -/** - * GreasedLinePluginMaterial for GreasedLineMesh - */ -class greasedLinePluginMaterial_GreasedLinePluginMaterial extends MaterialPluginBase { - constructor(material, scene, options) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; - options = options || { - color: greasedLinePluginMaterial_GreasedLinePluginMaterial.DEFAULT_COLOR, - }; - const defines = new MaterialGreasedLineDefines(); - defines.GREASED_LINE_HAS_COLOR = !!options.color; - defines.GREASED_LINE_SIZE_ATTENUATION = (_a = options.sizeAttenuation) !== null && _a !== void 0 ? _a : false; - defines.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = options.colorDistributionType === GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_LINE; - defines.GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM = (scene !== null && scene !== void 0 ? scene : material.getScene()).useRightHandedSystem; - super(material, greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME, 200, defines); - this._scene = scene !== null && scene !== void 0 ? scene : material.getScene(); - this._engine = this._scene.getEngine(); - this.visibility = (_b = options.visibility) !== null && _b !== void 0 ? _b : 1; - this.useDash = (_c = options.useDash) !== null && _c !== void 0 ? _c : false; - this.dashRatio = (_d = options.dashRatio) !== null && _d !== void 0 ? _d : 0.5; - this.dashOffset = (_e = options.dashOffset) !== null && _e !== void 0 ? _e : 0; - this.width = options.width ? options.width : options.sizeAttenuation ? greasedLinePluginMaterial_GreasedLinePluginMaterial.DEFAULT_WIDTH_ATTENUATED : greasedLinePluginMaterial_GreasedLinePluginMaterial.DEFAULT_WIDTH; - this._sizeAttenuation = (_f = options.sizeAttenuation) !== null && _f !== void 0 ? _f : false; - this.colorMode = (_g = options.colorMode) !== null && _g !== void 0 ? _g : GreasedLineMeshColorMode.COLOR_MODE_SET; - this._color = (_h = options.color) !== null && _h !== void 0 ? _h : null; - this.useColors = (_j = options.useColors) !== null && _j !== void 0 ? _j : false; - this._colorsDistributionType = (_k = options.colorDistributionType) !== null && _k !== void 0 ? _k : GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_SEGMENT; - this.colorsSampling = (_l = options.colorsSampling) !== null && _l !== void 0 ? _l : rawTexture_RawTexture.NEAREST_NEAREST; - this._colors = (_m = options.colors) !== null && _m !== void 0 ? _m : null; - this.dashCount = (_o = options.dashCount) !== null && _o !== void 0 ? _o : 1; // calculate the _dashArray value, call the setter - this.resolution = (_p = options.resolution) !== null && _p !== void 0 ? _p : new math_vector_Vector2(this._engine.getRenderWidth(), this._engine.getRenderHeight()); // calculate aspect call the setter - if (this._colors) { - this._createColorsTexture(`${material.name}-colors-texture`, this._colors); - } - else { - this._color = (_q = this._color) !== null && _q !== void 0 ? _q : greasedLinePluginMaterial_GreasedLinePluginMaterial.DEFAULT_COLOR; - greasedLinePluginMaterial_GreasedLinePluginMaterial._PrepareEmptyColorsTexture(this._scene); - } - this._engine.onDisposeObservable.add(() => { - var _a; - (_a = greasedLinePluginMaterial_GreasedLinePluginMaterial._EmptyColorsTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - greasedLinePluginMaterial_GreasedLinePluginMaterial._EmptyColorsTexture = null; - }); - this._enable(true); // always enabled - } - /** - * Get the shader attributes - * @param attributes array which will be filled with the attributes - */ - getAttributes(attributes) { - attributes.push("grl_offsets"); - attributes.push("grl_previousAndSide"); - attributes.push("grl_nextAndCounters"); - attributes.push("grl_widths"); - attributes.push("grl_colorPointers"); - } - /** - * Get the shader samplers - * @param samplers - */ - getSamplers(samplers) { - samplers.push("grl_colors"); - } - /** - * Get the shader textures - * @param activeTextures - */ - getActiveTextures(activeTextures) { - if (this._colorsTexture) { - activeTextures.push(this._colorsTexture); - } - } - /** - * Get the shader uniforms - * @returns uniforms - */ - getUniforms() { - const ubo = [ - { name: "grl_projection", size: 16, type: "mat4" }, - { name: "grl_singleColor", size: 3, type: "vec3" }, - { name: "grl_aspect_resolution_lineWidth", size: 4, type: "vec4" }, - { name: "grl_dashOptions", size: 4, type: "vec4" }, - { name: "grl_colorMode_visibility_colorsWidth_useColors", size: 4, type: "vec4" }, - ]; - return { - ubo, - vertex: ` - uniform vec4 grl_aspect_resolution_lineWidth; - uniform mat4 grl_projection; - `, - fragment: ` - uniform vec4 grl_dashOptions; - uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; - uniform vec3 grl_singleColor; - `, - }; - } - // only getter, it doesn't make sense to use this plugin on a mesh other than GreasedLineMesh - // and it doesn't make sense to disable it on the mesh - get isEnabled() { - return true; - } - /** - * Bind the uniform buffer - * @param uniformBuffer - */ - bindForSubMesh(uniformBuffer) { - var _a; - const activeCamera = this._scene.activeCamera; - if (activeCamera) { - const projection = activeCamera.getProjectionMatrix(); - uniformBuffer.updateMatrix("grl_projection", projection); - } - else { - throw Error("GreasedLinePluginMaterial requires an active camera."); - } - const resolutionLineWidth = math_vector_TmpVectors.Vector4[0]; - resolutionLineWidth.x = this._aspect; - resolutionLineWidth.y = this._resolution.x; - resolutionLineWidth.z = this._resolution.y; - resolutionLineWidth.w = this.width; - uniformBuffer.updateVector4("grl_aspect_resolution_lineWidth", resolutionLineWidth); - const dashOptions = math_vector_TmpVectors.Vector4[0]; - dashOptions.x = greasedLinePluginMaterial_GreasedLinePluginMaterial._BooleanToNumber(this.useDash); - dashOptions.y = this._dashArray; - dashOptions.z = this.dashOffset; - dashOptions.w = this.dashRatio; - uniformBuffer.updateVector4("grl_dashOptions", dashOptions); - const colorModeVisibilityColorsWidthUseColors = math_vector_TmpVectors.Vector4[1]; - colorModeVisibilityColorsWidthUseColors.x = this.colorMode; - colorModeVisibilityColorsWidthUseColors.y = this.visibility; - colorModeVisibilityColorsWidthUseColors.z = this._colorsTexture ? this._colorsTexture.getSize().width : 0; - colorModeVisibilityColorsWidthUseColors.w = greasedLinePluginMaterial_GreasedLinePluginMaterial._BooleanToNumber(this.useColors); - uniformBuffer.updateVector4("grl_colorMode_visibility_colorsWidth_useColors", colorModeVisibilityColorsWidthUseColors); - if (this._color) { - uniformBuffer.updateColor3("grl_singleColor", this._color); - } - uniformBuffer.setTexture("grl_colors", (_a = this._colorsTexture) !== null && _a !== void 0 ? _a : greasedLinePluginMaterial_GreasedLinePluginMaterial._EmptyColorsTexture); - } - /** - * Prepare the defines - * @param defines - * @param _scene - * @param _mesh - */ - prepareDefines(defines, _scene, _mesh) { - var _a; - defines.GREASED_LINE_HAS_COLOR = !!this._color; - defines.GREASED_LINE_SIZE_ATTENUATION = (_a = this._sizeAttenuation) !== null && _a !== void 0 ? _a : false; - defines.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = this._colorsDistributionType === GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_LINE; - defines.GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM = _scene.useRightHandedSystem; - } - /** - * Get the class name - * @returns class name - */ - getClassName() { - return greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME; - } - /** - * Get shader code - * @param shaderType vertex/fragment - * @returns shader code - */ - getCustomCode(shaderType) { - if (shaderType === "vertex") { - return { - // eslint-disable-next-line @typescript-eslint/naming-convention - CUSTOM_VERTEX_DEFINITIONS: ` - attribute vec4 grl_previousAndSide; - attribute vec4 grl_nextAndCounters; - attribute float grl_widths; - attribute vec3 grl_offsets; - attribute float grl_colorPointers; - - varying float grlCounters; - varying float grlColorPointer; - - vec2 grlFix( vec4 i, float aspect ) { - vec2 res = i.xy / i.w; - res.x *= aspect; - return res; - } - `, - // eslint-disable-next-line @typescript-eslint/naming-convention - CUSTOM_VERTEX_UPDATE_POSITION: ` - vec3 grlPositionOffset = grl_offsets; - positionUpdated += grlPositionOffset; - `, - // eslint-disable-next-line @typescript-eslint/naming-convention - CUSTOM_VERTEX_MAIN_END: ` - - float grlAspect = grl_aspect_resolution_lineWidth.x; - float grlBaseWidth = grl_aspect_resolution_lineWidth.w; - - grlColorPointer = grl_colorPointers; - - vec3 grlPrevious = grl_previousAndSide.xyz; - float grlSide = grl_previousAndSide.w; - - vec3 grlNext = grl_nextAndCounters.xyz; - grlCounters = grl_nextAndCounters.w; - - - mat4 grlMatrix = viewProjection * world; - vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 ); - vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 ); - vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 ); - - vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect ); - vec2 grlPrevP = grlFix( grlPrevPos, grlAspect ); - vec2 grlNextP = grlFix( grlNextPos, grlAspect ); - - float grlWidth = grlBaseWidth * grl_widths; - - vec2 grlDir; - if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP ); - else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP ); - else { - vec2 grlDir1 = normalize( grlCurrentP - grlPrevP ); - vec2 grlDir2 = normalize( grlNextP - grlCurrentP ); - grlDir = normalize( grlDir1 + grlDir2 ); - } - vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. ); - #ifdef GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM - grlNormal.xy *= -.5 * grlWidth; - #else - grlNormal.xy *= .5 * grlWidth; - #endif - grlNormal *= grl_projection; - #ifdef GREASED_LINE_SIZE_ATTENUATION - grlNormal.xy *= grlFinalPosition.w; - grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy; - #endif - grlFinalPosition.xy += grlNormal.xy * grlSide; - gl_Position = grlFinalPosition; - - vPositionW = vec3(grlFinalPosition); - - `, - // eslint-disable-next-line @typescript-eslint/naming-convention - "!gl_Position\\=viewProjection\\*worldPos;": "//", // remove - }; - } - if (shaderType === "fragment") { - return { - // eslint-disable-next-line @typescript-eslint/naming-convention - CUSTOM_FRAGMENT_DEFINITIONS: ` - varying float grlCounters; - varying float grlColorPointer; - uniform sampler2D grl_colors; - `, - // eslint-disable-next-line @typescript-eslint/naming-convention - CUSTOM_FRAGMENT_MAIN_END: ` - float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; - float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; - float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; - float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; - - float grlUseDash = grl_dashOptions.x; - float grlDashArray = grl_dashOptions.y; - float grlDashOffset = grl_dashOptions.z; - float grlDashRatio = grl_dashOptions.w; - - gl_FragColor.a *= step(grlCounters, grlVisibility); - if( gl_FragColor.a == 0. ) discard; - - if(grlUseDash == 1.){ - gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); - if (gl_FragColor.a == 0.) discard; - } - - #ifdef GREASED_LINE_HAS_COLOR - if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_SET}.) { - gl_FragColor.rgb = grl_singleColor; - } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_ADD}.) { - gl_FragColor.rgb += grl_singleColor; - } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY}.) { - gl_FragColor.rgb *= grl_singleColor; - } - #else - if (grlUseColors == 1.) { - #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE - vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); - #else - vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.); - #endif - if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_SET}.) { - gl_FragColor = grlColor; - } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_ADD}.) { - gl_FragColor += grlColor; - } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY}.) { - gl_FragColor *= grlColor; - } - } - #endif - `, - }; - } - return null; - } - /** - * Converts boolean to number. - * @param bool - * @returns 1 if true, 0 if false. - */ - static _BooleanToNumber(bool) { - return bool ? 1 : 0; - } - /** - * Converts an array of Color3 to Uint8Array - * @param colors Arrray of Color3 - * @returns Uin8Array of colors [r, g, b, a, r, g, b, a, ...] - */ - static _Color3toRGBAUint8(colors) { - const colorTable = new Uint8Array(colors.length * 4); - for (let i = 0, j = 0; i < colors.length; i++) { - colorTable[j++] = colors[i].r * 255; - colorTable[j++] = colors[i].g * 255; - colorTable[j++] = colors[i].b * 255; - colorTable[j++] = 255; - } - return colorTable; - } - /** - * Creates a RawTexture from an RGBA color array and sets it on the plugin material instance. - * @param name name of the texture - * @param colors Uint8Array of colors - */ - _createColorsTexture(name, colors) { - const colorsArray = greasedLinePluginMaterial_GreasedLinePluginMaterial._Color3toRGBAUint8(colors); - this._colorsTexture = new rawTexture_RawTexture(colorsArray, colors.length, 1, engine_Engine.TEXTUREFORMAT_RGBA, this._scene, false, true, this.colorsSampling); - this._colorsTexture.name = name; - } - /** - * Disposes the plugin material. - */ - dispose() { - var _a; - (_a = this._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - super.dispose(); - } - /** - * Returns the colors used to colorize the line - */ - get colors() { - return this._colors; - } - /** - * Sets the colors used to colorize the line - */ - set colors(value) { - this.setColors(value); - } - /** - * Creates or updates the colors texture - * @param colors color table RGBA - * @param lazy if lazy, the colors are not updated - * @param forceNewTexture force creation of a new texture - * @returns - */ - setColors(colors, lazy = false, forceNewTexture = false) { - var _a, _b, _c, _d; - const origColorsCount = (_b = (_a = this._colors) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0; - this._colors = colors; - if (colors === null || colors.length === 0) { - (_c = this._colorsTexture) === null || _c === void 0 ? void 0 : _c.dispose(); - return; - } - if (lazy && !forceNewTexture) { - return; - } - if (this._colorsTexture && origColorsCount === colors.length && !forceNewTexture) { - const colorArray = greasedLinePluginMaterial_GreasedLinePluginMaterial._Color3toRGBAUint8(colors); - this._colorsTexture.update(colorArray); - } - else { - (_d = this._colorsTexture) === null || _d === void 0 ? void 0 : _d.dispose(); - this._createColorsTexture(`${this._material.name}-colors-texture`, colors); - } - } - /** - * Updates the material. Use when material created in lazy mode. - */ - updateLazy() { - if (this._colors) { - this.setColors(this._colors, false, true); - } - } - /** - * Gets the number of dashes in the line - */ - get dashCount() { - return this._dashCount; - } - /** - * Sets the number of dashes in the line - * @param value dash - */ - set dashCount(value) { - this._dashCount = value; - this._dashArray = 1 / 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 - */ - get sizeAttenuation() { - return this._sizeAttenuation; - } - /** - * Turn on/off attenuation of the width option and widths array. - * @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 - */ - set sizeAttenuation(value) { - this._sizeAttenuation = value; - this.markAllDefinesAsDirty(); - } - /** - * Gets the color of the line - */ - get color() { - return this._color; - } - /** - * Sets the color of the line - * @param value Color3 or null to clear the color. You need to clear the color if you use colors and useColors = true - */ - set color(value) { - this.setColor(value); - } - /** - * Sets the color of the line. If set the whole line will be mixed with this color according to the colorMode option. - * @param value color - */ - setColor(value, doNotMarkDirty = false) { - if ((this._color === null && value !== null) || (this._color !== null && value === null)) { - this._color = value; - !doNotMarkDirty && this.markAllDefinesAsDirty(); - } - else { - this._color = value; - } - } - /** - * Gets the color distributiopn type - */ - get colorsDistributionType() { - return this._colorsDistributionType; - } - /** - * Sets the color distribution type - * @see GreasedLineMeshColorDistributionType - * @param value color distribution type - */ - set colorsDistributionType(value) { - this._colorsDistributionType = value; - this.markAllDefinesAsDirty(); - } - /** - * Gets the resolution - */ - get resolution() { - return this._resolution; - } - /** - * Sets the resolution - * @param value resolution of the screen for GreasedLine - */ - set resolution(value) { - this._aspect = value.x / value.y; - this._resolution = value; - } - /** - * Serializes this plugin material - * @returns serializationObjec - */ - serialize() { - const serializationObject = super.serialize(); - const greasedLineMaterialOptions = { - colorDistributionType: this._colorsDistributionType, - colorsSampling: this.colorsSampling, - colorMode: this.colorMode, - dashCount: this._dashCount, - dashOffset: this.dashOffset, - dashRatio: this.dashRatio, - resolution: this._resolution, - sizeAttenuation: this._sizeAttenuation, - useColors: this.useColors, - useDash: this.useDash, - visibility: this.visibility, - width: this.width, - }; - this._colors && (greasedLineMaterialOptions.colors = this._colors); - this._color && (greasedLineMaterialOptions.color = this._color); - serializationObject.greasedLineMaterialOptions = greasedLineMaterialOptions; - return serializationObject; - } - /** - * Parses a serialized objects - * @param source serialized object - * @param scene scene - * @param rootUrl root url for textures - */ - parse(source, scene, rootUrl) { - var _a; - super.parse(source, scene, rootUrl); - const greasedLineMaterialOptions = source.greasedLineMaterialOptions; - (_a = this._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - if (greasedLineMaterialOptions.colors) { - this._createColorsTexture(`${this._material.name}-colors-texture`, greasedLineMaterialOptions.colors); - } - else { - greasedLinePluginMaterial_GreasedLinePluginMaterial._PrepareEmptyColorsTexture(scene); - } - greasedLineMaterialOptions.color && this.setColor(greasedLineMaterialOptions.color, true); - greasedLineMaterialOptions.colorDistributionType && (this.colorsDistributionType = greasedLineMaterialOptions.colorDistributionType); - greasedLineMaterialOptions.colorsSampling && (this.colorsSampling = greasedLineMaterialOptions.colorsSampling); - greasedLineMaterialOptions.colorMode && (this.colorMode = greasedLineMaterialOptions.colorMode); - greasedLineMaterialOptions.useColors && (this.useColors = greasedLineMaterialOptions.useColors); - greasedLineMaterialOptions.visibility && (this.visibility = greasedLineMaterialOptions.visibility); - greasedLineMaterialOptions.useDash && (this.useDash = greasedLineMaterialOptions.useDash); - greasedLineMaterialOptions.dashCount && (this.dashCount = greasedLineMaterialOptions.dashCount); - greasedLineMaterialOptions.dashRatio && (this.dashRatio = greasedLineMaterialOptions.dashRatio); - greasedLineMaterialOptions.dashOffset && (this.dashOffset = greasedLineMaterialOptions.dashOffset); - greasedLineMaterialOptions.width && (this.width = greasedLineMaterialOptions.width); - greasedLineMaterialOptions.sizeAttenuation && (this.sizeAttenuation = greasedLineMaterialOptions.sizeAttenuation); - greasedLineMaterialOptions.resolution && (this.resolution = greasedLineMaterialOptions.resolution); - this.markAllDefinesAsDirty(); - } - /** - * Makes a duplicate of the current configuration into another one. - * @param plugin define the config where to copy the info - */ - copyTo(plugin) { - var _a; - const dest = plugin; - (_a = dest._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - if (this._colors) { - dest._createColorsTexture(`${dest._material.name}-colors-texture`, this._colors); - } - dest.setColor(this.color, true); - dest.colorsDistributionType = this.colorsDistributionType; - dest.colorsSampling = this.colorsSampling; - dest.colorMode = this.colorMode; - dest.useColors = this.useColors; - dest.visibility = this.visibility; - dest.useDash = this.useDash; - dest.dashCount = this.dashCount; - dest.dashRatio = this.dashRatio; - dest.dashOffset = this.dashOffset; - dest.width = this.width; - dest.sizeAttenuation = this.sizeAttenuation; - dest.resolution = this.resolution; - dest.markAllDefinesAsDirty(); - } - /** - * A minimum size texture for the colors sampler2D when there is no colors texture defined yet. - * For fast switching using the useColors property without the need to use defines. - * @param scene Scene - */ - static _PrepareEmptyColorsTexture(scene) { - if (!this._EmptyColorsTexture) { - const colorsArray = new Uint8Array(4); - greasedLinePluginMaterial_GreasedLinePluginMaterial._EmptyColorsTexture = new rawTexture_RawTexture(colorsArray, 1, 1, engine_Engine.TEXTUREFORMAT_RGBA, scene, false, false, rawTexture_RawTexture.NEAREST_NEAREST); - greasedLinePluginMaterial_GreasedLinePluginMaterial._EmptyColorsTexture.name = "grlEmptyColorsTexture"; - } - } -} -/** - * Plugin name - */ -greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME = "GreasedLinePluginMaterial"; -/** - * Default line color for newly created lines - */ -greasedLinePluginMaterial_GreasedLinePluginMaterial.DEFAULT_COLOR = math_color_Color3.White(); -/** - * Default line width when sizeAttenuation is true - */ -greasedLinePluginMaterial_GreasedLinePluginMaterial.DEFAULT_WIDTH_ATTENUATED = 1; -/** - * Defaule line width - */ -greasedLinePluginMaterial_GreasedLinePluginMaterial.DEFAULT_WIDTH = 0.1; -RegisterClass(`BABYLON.${greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}`, greasedLinePluginMaterial_GreasedLinePluginMaterial); -//# sourceMappingURL=greasedLinePluginMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/meshDebugPluginMaterial.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - -const vertexDefinitions = `#if defined(DBG_ENABLED) -attribute float dbg_initialPass; -varying vec3 dbg_vBarycentric; -flat varying vec3 dbg_vVertexWorldPos; -flat varying float dbg_vPass; -#endif`; -const vertexMainEnd = `#if defined(DBG_ENABLED) -float dbg_vertexIndex = mod(float(gl_VertexID), 3.); -if (dbg_vertexIndex == 0.0) { - dbg_vBarycentric = vec3(1.,0.,0.); -} -else if (dbg_vertexIndex == 1.0) { - dbg_vBarycentric = vec3(0.,1.,0.); -} -else { - dbg_vBarycentric = vec3(0.,0.,1.); -} - -dbg_vVertexWorldPos = vPositionW; -dbg_vPass = dbg_initialPass; -#endif`; -const fragmentUniforms = `#if defined(DBG_ENABLED) -uniform vec3 dbg_shadedDiffuseColor; -uniform vec4 dbg_shadedSpecularColorPower; -uniform vec3 dbg_thicknessRadiusScale; - -#if DBG_MODE == 2 || DBG_MODE == 3 - uniform vec3 dbg_vertexColor; -#endif - -#if DBG_MODE == 1 - uniform vec3 dbg_wireframeTrianglesColor; -#elif DBG_MODE == 3 - uniform vec3 dbg_wireframeVerticesColor; -#elif DBG_MODE == 4 || DBG_MODE == 5 - uniform vec3 dbg_uvPrimaryColor; - uniform vec3 dbg_uvSecondaryColor; -#elif DBG_MODE == 7 - uniform vec3 dbg_materialColor; -#endif -#endif`; -const fragmentDefinitions = `#if defined(DBG_ENABLED) -varying vec3 dbg_vBarycentric; -flat varying vec3 dbg_vVertexWorldPos; -flat varying float dbg_vPass; - -#if !defined(DBG_MULTIPLY) - vec3 dbg_applyShading(vec3 color) { - vec3 N = vNormalW.xyz; - vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); - vec3 H = normalize(L + L); - float LdotN = clamp(dot(L,N), 0., 1.); - float HdotN = clamp(dot(H,N), 0., 1.); - float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); - color *= (LdotN / PI); - color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); - return color; - } -#endif - -#if DBG_MODE == 1 || DBG_MODE == 3 - float dbg_edgeFactor() { - vec3 d = fwidth(dbg_vBarycentric); - vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); - return min(min(a3.x, a3.y), a3.z); - } -#endif - -#if DBG_MODE == 2 || DBG_MODE == 3 - float dbg_cornerFactor() { - vec3 worldPos = vPositionW; - float dist = length(worldPos - dbg_vVertexWorldPos); - float camDist = length(worldPos - vEyePosition.xyz); - float d = sqrt(camDist) * .001; - return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); - } -#endif - -#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) - float dbg_checkerboardFactor(vec2 uv) { - vec2 f = fract(uv * dbg_thicknessRadiusScale.z); - f -= .5; - return (f.x * f.y) > 0. ? 1. : 0.; - } -#endif -#endif`; -const fragmentMainEnd = `#if defined(DBG_ENABLED) -vec3 dbg_color = vec3(1.); -#if DBG_MODE == 1 - dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); -#elif DBG_MODE == 2 || DBG_MODE == 3 - float dbg_cornerFactor = dbg_cornerFactor(); - if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; - dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); - #if DBG_MODE == 3 - dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); - #endif -#elif DBG_MODE == 4 && defined(UV1) - dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); -#elif DBG_MODE == 5 && defined(UV2) - dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); -#elif DBG_MODE == 6 && defined(VERTEXCOLOR) - dbg_color = vColor.rgb; -#elif DBG_MODE == 7 - dbg_color = dbg_materialColor; -#endif - -#if defined(DBG_MULTIPLY) - gl_FragColor *= vec4(dbg_color, 1.); -#else - #if DBG_MODE != 6 - gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); - #else - gl_FragColor = vec4(dbg_color, 1.); - #endif -#endif -#endif`; -const defaultMaterialColors = [ - new math_color_Color3(0.98, 0.26, 0.38), - new math_color_Color3(0.47, 0.75, 0.3), - new math_color_Color3(0, 0.26, 0.77), - new math_color_Color3(0.97, 0.6, 0.76), - new math_color_Color3(0.19, 0.63, 0.78), - new math_color_Color3(0.98, 0.8, 0.6), - new math_color_Color3(0.65, 0.43, 0.15), - new math_color_Color3(0.15, 0.47, 0.22), - new math_color_Color3(0.67, 0.71, 0.86), - new math_color_Color3(0.09, 0.46, 0.56), - new math_color_Color3(0.8, 0.98, 0.02), - new math_color_Color3(0.39, 0.29, 0.13), - new math_color_Color3(0.53, 0.63, 0.06), - new math_color_Color3(0.95, 0.96, 0.41), - new math_color_Color3(1, 0.72, 0.94), - new math_color_Color3(0.63, 0.08, 0.31), - new math_color_Color3(0.66, 0.96, 0.95), - new math_color_Color3(0.22, 0.14, 0.19), - new math_color_Color3(0.14, 0.65, 0.59), - new math_color_Color3(0.93, 1, 0.68), - new math_color_Color3(0.93, 0.14, 0.44), - new math_color_Color3(0.47, 0.86, 0.67), - new math_color_Color3(0.85, 0.07, 0.78), - new math_color_Color3(0.53, 0.64, 0.98), - new math_color_Color3(0.43, 0.37, 0.56), - new math_color_Color3(0.71, 0.65, 0.25), - new math_color_Color3(0.66, 0.19, 0.01), - new math_color_Color3(0.94, 0.53, 0.12), - new math_color_Color3(0.41, 0.44, 0.44), - new math_color_Color3(0.24, 0.71, 0.96), - new math_color_Color3(0.57, 0.28, 0.56), - new math_color_Color3(0.44, 0.98, 0.42), -]; -/** - * Supported visualizations of MeshDebugPluginMaterial - */ -var MeshDebugMode; -(function (MeshDebugMode) { - /** - * Material without any mesh debug visualization - */ - MeshDebugMode[MeshDebugMode["NONE"] = 0] = "NONE"; - /** - * A wireframe of the mesh - * NOTE: For this mode to work correctly, convertToUnIndexedMesh() or MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() must first be called on mesh. - */ - MeshDebugMode[MeshDebugMode["TRIANGLES"] = 1] = "TRIANGLES"; - /** - * Points drawn over vertices of mesh - * NOTE: For this mode to work correctly, MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() must first be called on mesh. - */ - MeshDebugMode[MeshDebugMode["VERTICES"] = 2] = "VERTICES"; - /** - * A wireframe of the mesh, with points drawn over vertices - * NOTE: For this mode to work correctly, MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() must first be called on mesh. - */ - MeshDebugMode[MeshDebugMode["TRIANGLES_VERTICES"] = 3] = "TRIANGLES_VERTICES"; - /** - * A checkerboard grid of the mesh's UV set 0 - */ - MeshDebugMode[MeshDebugMode["UV0"] = 4] = "UV0"; - /** - * A checkerboard grid of the mesh's UV set 1 - */ - MeshDebugMode[MeshDebugMode["UV1"] = 5] = "UV1"; - /** - * The mesh's vertex colors displayed as the primary texture - */ - MeshDebugMode[MeshDebugMode["VERTEXCOLORS"] = 6] = "VERTEXCOLORS"; - /** - * An arbitrary, distinguishable color to identify the material - */ - MeshDebugMode[MeshDebugMode["MATERIALIDS"] = 7] = "MATERIALIDS"; -})(MeshDebugMode || (MeshDebugMode = {})); -/** @internal */ -class MeshDebugDefines extends MaterialDefines { - constructor() { - super(...arguments); - /** - * Current mesh debug visualization. - * Defaults to NONE. - */ - this.DBG_MODE = MeshDebugMode.NONE; - /** - * Whether the mesh debug visualization multiplies with colors underneath. - * Defaults to true. - */ - this.DBG_MULTIPLY = true; - /** - * Whether the mesh debug plugin is enabled in the material. - * Defaults to true. - */ - this.DBG_ENABLED = true; - } -} -/** - * Plugin that implements various mesh debug visualizations, - * List of available visualizations can be found in MeshDebugMode enum. - */ -class MeshDebugPluginMaterial extends MaterialPluginBase { - /** @internal */ - _markAllDefinesAsDirty() { - this._enable(this._isEnabled); - this.markAllDefinesAsDirty(); - } - /** - * Creates a new MeshDebugPluginMaterial - * @param material Material to attach the mesh debug plugin to - * @param options Options for the mesh debug plugin - */ - constructor(material, options = {}) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o; - const defines = new MeshDebugDefines(); - defines.DBG_MODE = (_a = options.mode) !== null && _a !== void 0 ? _a : defines.DBG_MODE; - defines.DBG_MULTIPLY = (_b = options.multiply) !== null && _b !== void 0 ? _b : defines.DBG_MULTIPLY; - super(material, "MeshDebug", 200, defines, true, true); - this._mode = defines.DBG_MODE; - this._multiply = defines.DBG_MULTIPLY; - this.shadedDiffuseColor = (_c = options.shadedDiffuseColor) !== null && _c !== void 0 ? _c : new math_color_Color3(1, 1, 1); - this.shadedSpecularColor = (_d = options.shadedSpecularColor) !== null && _d !== void 0 ? _d : new math_color_Color3(0.8, 0.8, 0.8); - this.shadedSpecularPower = (_e = options.shadedSpecularPower) !== null && _e !== void 0 ? _e : 10; - this.wireframeThickness = (_f = options.wireframeThickness) !== null && _f !== void 0 ? _f : 0.7; - this.wireframeTrianglesColor = (_g = options.wireframeTrianglesColor) !== null && _g !== void 0 ? _g : new math_color_Color3(0, 0, 0); - this.wireframeVerticesColor = (_h = options.wireframeVerticesColor) !== null && _h !== void 0 ? _h : new math_color_Color3(0.8, 0.8, 0.8); - this.vertexColor = (_j = options.vertexColor) !== null && _j !== void 0 ? _j : new math_color_Color3(0, 0, 0); - this.vertexRadius = (_k = options.vertexRadius) !== null && _k !== void 0 ? _k : 1.2; - this.uvScale = (_l = options.uvScale) !== null && _l !== void 0 ? _l : 20; - this.uvPrimaryColor = (_m = options.uvPrimaryColor) !== null && _m !== void 0 ? _m : new math_color_Color3(1, 1, 1); - this.uvSecondaryColor = (_o = options.uvSecondaryColor) !== null && _o !== void 0 ? _o : new math_color_Color3(0.5, 0.5, 0.5); - this._materialColor = MeshDebugPluginMaterial.MaterialColors[MeshDebugPluginMaterial._PluginCount++ % MeshDebugPluginMaterial.MaterialColors.length]; - this.isEnabled = true; - } - /** - * Get the class name - * @returns Class name - */ - getClassName() { - return "MeshDebugPluginMaterial"; - } - /** - * Gets whether the mesh debug plugin is enabled in the material. - */ - get isEnabled() { - return this._isEnabled; - } - /** - * Sets whether the mesh debug plugin is enabled in the material. - * @param value enabled - */ - set isEnabled(value) { - if (this._isEnabled === value) { - return; - } - if (this._material.getScene().getEngine().webGLVersion == 1) { - logger_Logger.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."); - this._isEnabled = false; - return; - } - this._isEnabled = value; - this._markAllDefinesAsDirty(); - } - /** - * Prepare the defines - * @param defines Mesh debug defines - * @param scene Scene - * @param mesh Mesh associated with material - */ - prepareDefines(defines, scene, mesh) { - if ((this._mode == MeshDebugMode.VERTICES || this._mode == MeshDebugMode.TRIANGLES || this._mode == MeshDebugMode.TRIANGLES_VERTICES) && - !mesh.isVerticesDataPresent("dbg_initialPass")) { - logger_Logger.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.", 1); - } - defines.DBG_MODE = this._mode; - defines.DBG_MULTIPLY = this._multiply; - defines.DBG_ENABLED = this._isEnabled; - } - /** - * Get the shader attributes - * @param attributes Array of attributes - */ - getAttributes(attributes) { - attributes.push("dbg_initialPass"); - } - /** - * Get the shader uniforms - * @returns Uniforms - */ - getUniforms() { - return { - ubo: [ - { name: "dbg_shadedDiffuseColor", size: 3, type: "vec3" }, - { name: "dbg_shadedSpecularColorPower", size: 4, type: "vec4" }, - { name: "dbg_thicknessRadiusScale", size: 3, type: "vec3" }, - { name: "dbg_wireframeTrianglesColor", size: 3, type: "vec3" }, - { name: "dbg_wireframeVerticesColor", size: 3, type: "vec3" }, - { name: "dbg_vertexColor", size: 3, type: "vec3" }, - { name: "dbg_uvPrimaryColor", size: 3, type: "vec3" }, - { name: "dbg_uvSecondaryColor", size: 3, type: "vec3" }, - { name: "dbg_materialColor", size: 3, type: "vec3" }, - ], - fragment: fragmentUniforms, - }; - } - /** - * Bind the uniform buffer - * @param uniformBuffer Uniform buffer - */ - bindForSubMesh(uniformBuffer) { - if (!this._isEnabled) { - return; - } - uniformBuffer.updateFloat3("dbg_shadedDiffuseColor", this.shadedDiffuseColor.r, this.shadedDiffuseColor.g, this.shadedDiffuseColor.b); - uniformBuffer.updateFloat4("dbg_shadedSpecularColorPower", this.shadedSpecularColor.r, this.shadedSpecularColor.g, this.shadedSpecularColor.b, this.shadedSpecularPower); - uniformBuffer.updateFloat3("dbg_thicknessRadiusScale", this.wireframeThickness, this.vertexRadius, this.uvScale); - uniformBuffer.updateColor3("dbg_wireframeTrianglesColor", this.wireframeTrianglesColor); - uniformBuffer.updateColor3("dbg_wireframeVerticesColor", this.wireframeVerticesColor); - uniformBuffer.updateColor3("dbg_vertexColor", this.vertexColor); - uniformBuffer.updateColor3("dbg_uvPrimaryColor", this.uvPrimaryColor); - uniformBuffer.updateColor3("dbg_uvSecondaryColor", this.uvSecondaryColor); - uniformBuffer.updateColor3("dbg_materialColor", this._materialColor); - } - /** - * Get shader code - * @param shaderType "vertex" or "fragment" - * @returns Shader code - */ - getCustomCode(shaderType) { - return shaderType === "vertex" - ? { - CUSTOM_VERTEX_DEFINITIONS: vertexDefinitions, - CUSTOM_VERTEX_MAIN_END: vertexMainEnd, - } - : { - CUSTOM_FRAGMENT_DEFINITIONS: fragmentDefinitions, - CUSTOM_FRAGMENT_MAIN_END: fragmentMainEnd, - }; - } - /** - * Resets static variables of the plugin to their original state - */ - static Reset() { - this._PluginCount = 0; - this.MaterialColors = defaultMaterialColors; - } - /** - * Renders triangles in a mesh 3 times by tripling the indices in the index buffer. - * Used to prepare a mesh to be rendered in `TRIANGLES`, `VERTICES`, or `TRIANGLES_VERTICES` modes. - * NOTE: This is a destructive operation. The mesh's index buffer and vertex buffers are modified, and a new vertex buffer is allocated. - * If you'd like the ability to revert these changes, toggle the optional `returnRollback` flag. - * @param mesh the mesh to target - * @param returnRollback whether or not to return a function that reverts mesh to its initial state. Default: false. - * @returns a rollback function if `returnRollback` is true, otherwise an empty function. - */ - static PrepareMeshForTrianglesAndVerticesMode(mesh, returnRollback = false) { - let rollback = () => { }; - if (mesh.getTotalIndices() == 0) - return rollback; - if (returnRollback) { - const kinds = mesh.getVerticesDataKinds(); - const indices = mesh.getIndices(); - const data = {}; - for (const kind of kinds) { - data[kind] = mesh.getVerticesData(kind); - } - rollback = function () { - mesh.setIndices(indices); - for (const kind of kinds) { - const stride = mesh.getVertexBuffer(kind).getStrideSize(); - mesh.setVerticesData(kind, data[kind], undefined, stride); - } - mesh.removeVerticesData("dbg_initialPass"); - }; - } - let indices = Array.from(mesh.getIndices()); - const newIndices1 = []; - for (let i = 0; i < indices.length; i += 3) { - newIndices1.push(indices[i + 1], indices[i + 2], indices[i + 0]); - } - mesh.setIndices(indices.concat(newIndices1)); - mesh.convertToUnIndexedMesh(); - mesh.isUnIndexed = false; - indices = Array.from(mesh.getIndices()); - const newIndices2 = []; - for (let i = indices.length / 2; i < indices.length; i += 3) { - newIndices2.push(indices[i + 1], indices[i + 2], indices[i + 0]); - } - mesh.setIndices(indices.concat(newIndices2)); - const num = mesh.getTotalVertices(); - const mid = num / 2; - const pass = new Array(num).fill(1, 0, mid).fill(0, mid, num); - mesh.setVerticesData("dbg_initialPass", pass, false, 1); - return rollback; - } -} -/** - * Total number of instances of the plugin. - * Starts at 0. - */ -MeshDebugPluginMaterial._PluginCount = 0; -/** - * Color palette used for MATERIALIDS mode. - * Defaults to `defaultMaterialColors` - */ -MeshDebugPluginMaterial.MaterialColors = defaultMaterialColors; -__decorate([ - serializeAsColor3() -], MeshDebugPluginMaterial.prototype, "_materialColor", void 0); -__decorate([ - serialize() -], MeshDebugPluginMaterial.prototype, "_isEnabled", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllDefinesAsDirty") -], MeshDebugPluginMaterial.prototype, "mode", void 0); -__decorate([ - serialize(), - expandToProperty("_markAllDefinesAsDirty") -], MeshDebugPluginMaterial.prototype, "multiply", void 0); -__decorate([ - serializeAsColor3() -], MeshDebugPluginMaterial.prototype, "shadedDiffuseColor", void 0); -__decorate([ - serializeAsColor3() -], MeshDebugPluginMaterial.prototype, "shadedSpecularColor", void 0); -__decorate([ - serialize() -], MeshDebugPluginMaterial.prototype, "shadedSpecularPower", void 0); -__decorate([ - serialize() -], MeshDebugPluginMaterial.prototype, "wireframeThickness", void 0); -__decorate([ - serializeAsColor3() -], MeshDebugPluginMaterial.prototype, "wireframeTrianglesColor", void 0); -__decorate([ - serializeAsColor3() -], MeshDebugPluginMaterial.prototype, "wireframeVerticesColor", void 0); -__decorate([ - serializeAsColor3() -], MeshDebugPluginMaterial.prototype, "vertexColor", void 0); -__decorate([ - serialize() -], MeshDebugPluginMaterial.prototype, "vertexRadius", void 0); -__decorate([ - serialize() -], MeshDebugPluginMaterial.prototype, "uvScale", void 0); -__decorate([ - serializeAsColor3() -], MeshDebugPluginMaterial.prototype, "uvPrimaryColor", void 0); -__decorate([ - serializeAsColor3() -], MeshDebugPluginMaterial.prototype, "uvSecondaryColor", void 0); -RegisterClass("BABYLON.MeshDebugPluginMaterial", MeshDebugPluginMaterial); -//# sourceMappingURL=meshDebugPluginMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/standardMaterial.decalMap.js - - -Object.defineProperty(standardMaterial_StandardMaterial.prototype, "decalMap", { - get: function () { - if (!this._decalMap) { - if (this._uniformBufferLayoutBuilt) { - // Material already used to display a mesh, so it's invalid to add the decal map plugin at that point - // Returns null instead of having new DecalMapConfiguration throws an exception - return null; - } - this._decalMap = new DecalMapConfiguration(this); - } - return this._decalMap; - }, - enumerable: true, - configurable: true, -}); -//# sourceMappingURL=standardMaterial.decalMap.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/PBR/pbrMaterial.decalMap.js - - -Object.defineProperty(pbrBaseMaterial_PBRBaseMaterial.prototype, "decalMap", { - get: function () { - if (!this._decalMap) { - if (this._uniformBufferLayoutBuilt) { - // Material already used to display a mesh, so it's invalid to add the decal map plugin at that point - // Returns null instead of having new DecalMapConfiguration throws an exception - return null; - } - this._decalMap = new DecalMapConfiguration(this); - } - return this._decalMap; - }, - enumerable: true, - configurable: true, -}); -//# sourceMappingURL=pbrMaterial.decalMap.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/abstractMesh.decalMap.js - -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "decalMap", { - get: function () { - return this._decalMap; - }, - set: function (decalMap) { - this._decalMap = decalMap; - }, - enumerable: true, - configurable: true, -}); -//# sourceMappingURL=abstractMesh.decalMap.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/material.decalMap.js - - - -//# sourceMappingURL=material.decalMap.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/math.polar.js - -/** - * Class used to store (r, theta) vector representation - */ -class Polar { - /** - * Creates a new Polar object - * @param radius the radius of the vector - * @param theta the angle of the vector - */ - constructor(radius, theta) { - this.radius = radius; - this.theta = theta; - } - /** - * Gets the class name - * @returns the string "Polar" - */ - getClassName() { - return "Polar"; - } - /** - * Converts the current polar to a string - * @returns the current polar as a string - */ - toString() { - return JSON.stringify(this); - } - /** - * Converts the current polar to an array - * @reutrns the current polar as an array - */ - asArray() { - return [this.radius, this.theta]; - } - /** - * Adds the current Polar and the given Polar and stores the result - * @param polar the polar to add - * @param ref the polar to store the result in - * @returns the updated ref - */ - addToRef(polar, ref) { - ref.radius = this.radius + polar.radius; - ref.theta = this.theta + polar.theta; - return ref; - } - /** - * Adds the current Polar and the given Polar - * @param polar the polar to add - * @returns the sum polar - */ - add(polar) { - const ref = new Polar(0, 0); - this.addToRef(polar, ref); - return ref; - } - /** - * Adds the given polar to the current polar - * @param polar the polar to add - * @returns the current polar - */ - addInPlace(polar) { - this.addToRef(polar, this); - return this; - } - /** - * Adds the provided values to the current polar - * @param radius the amount to add to the radius - * @param theta the amount to add to the theta - * @returns the current polar - */ - addInPlaceFromFloats(radius, theta) { - this.radius += radius; - this.theta += theta; - return this; - } - /** - * Subtracts the given Polar from the current Polar and stores the result - * @param polar the polar to subtract - * @param ref the polar to store the result in - * @returns the updated ref - */ - subtractToRef(polar, ref) { - ref.radius = this.radius - polar.radius; - ref.theta = this.theta - polar.theta; - return ref; - } - /** - * Subtracts the given Polar from the current Polar - * @param polar the polar to subtract - * @returns the difference polar - */ - subtract(polar) { - const ref = new Polar(0, 0); - this.subtractToRef(polar, ref); - return ref; - } - /** - * Subtracts the given Polar from the current Polar - * @param polar the polar to subtract - * @returns the current polar - */ - subtractInPlace(polar) { - this.subtractToRef(polar, this); - return this; - } - /** - * Subtracts the given floats from the current polar - * @param radius the amount to subtract from the radius - * @param theta the amount to subtract from the theta - * @param ref the polar to store the result in - * @returns the updated ref - */ - subtractFromFloatsToRef(radius, theta, ref) { - ref.radius = this.radius - radius; - ref.theta = this.theta - theta; - return ref; - } - /** - * Subtracts the given floats from the current polar - * @param radius the amount to subtract from the radius - * @param theta the amount to subtract from the theta - * @returns the difference polar - */ - subtractFromFloats(radius, theta) { - const ref = new Polar(0, 0); - this.subtractFromFloatsToRef(radius, theta, ref); - return ref; - } - /** - * Multiplies the given Polar with the current Polar and stores the result - * @param polar the polar to multiply - * @param ref the polar to store the result in - * @returns the updated ref - */ - multiplyToRef(polar, ref) { - ref.radius = this.radius * polar.radius; - ref.theta = this.theta * polar.theta; - return ref; - } - /** - * Multiplies the given Polar with the current Polar - * @param polar the polar to multiply - * @returns the product polar - */ - multiply(polar) { - const ref = new Polar(0, 0); - this.multiplyToRef(polar, ref); - return ref; - } - /** - * Multiplies the given Polar with the current Polar - * @param polar the polar to multiply - * @returns the current polar - */ - multiplyInPlace(polar) { - this.multiplyToRef(polar, this); - return this; - } - /** - * Divides the current Polar by the given Polar and stores the result - * @param polar the polar to divide - * @param ref the polar to store the result in - * @returns the updated ref - */ - divideToRef(polar, ref) { - ref.radius = this.radius / polar.radius; - ref.theta = this.theta / polar.theta; - return ref; - } - /** - * Divides the current Polar by the given Polar - * @param polar the polar to divide - * @returns the quotient polar - */ - divide(polar) { - const ref = new Polar(0, 0); - this.divideToRef(polar, ref); - return ref; - } - /** - * Divides the current Polar by the given Polar - * @param polar the polar to divide - * @returns the current polar - */ - divideInPlace(polar) { - this.divideToRef(polar, this); - return this; - } - /** - * Clones the current polar - * @returns a clone of the current polar - */ - clone() { - return new Polar(this.radius, this.theta); - } - /** - * Copies the source polar into the current polar - * @param source the polar to copy from - * @returns the current polar - */ - copyFrom(source) { - this.radius = source.radius; - this.theta = source.theta; - return this; - } - /** - * Copies the given values into the current polar - * @param radius the radius to use - * @param theta the theta to use - * @returns the current polar - */ - copyFromFloats(radius, theta) { - this.radius = radius; - this.theta = theta; - return this; - } - /** - * Scales the current polar and stores the result - * @param scale defines the multiplication factor - * @param ref where to store the result - * @returns the updated ref - */ - scaleToRef(scale, ref) { - ref.radius = this.radius * scale; - ref.theta = this.theta * scale; - return ref; - } - /** - * Scales the current polar and returns a new polar with the scaled coordinates - * @param scale defines the multiplication factor - * @returns the scaled polar - */ - scale(scale) { - const ref = new Polar(0, 0); - this.scaleToRef(scale, ref); - return ref; - } - /** - * Scales the current polar - * @param scale defines the multiplication factor - * @returns the current polar - */ - scaleInPlace(scale) { - this.scaleToRef(scale, this); - return this; - } - /** - * Sets the values of the current polar - * @param radius the new radius - * @param theta the new theta - * @returns the current polar - */ - set(radius, theta) { - this.radius = radius; - this.theta = theta; - return this; - } - /** - * Sets the values of the current polar - * @param value the new values - * @returns the current polar - */ - setAll(value) { - this.set(value, value); - return this; - } - /** - * Gets the rectangular coordinates of the current Polar - * @param ref the reference to assign the result - * @returns the updated reference - */ - toVector2ToRef(ref) { - const x = this.radius * Math.cos(this.theta); - const y = this.radius * Math.sin(this.theta); - ref.set(x, y); - return ref; - } - /** - * Gets the rectangular coordinates of the current Polar - * @returns the rectangular coordinates - */ - toVector2() { - const ref = new Vector2(0, 0); - return this.toVector2ToRef(ref); - } - /** - * Converts a given Vector2 to its polar coordinates - * @param v the Vector2 to convert - * @param ref the reference to assign the result - * @returns the updated reference - */ - static FromVector2ToRef(v, ref) { - const theta = Math.sign(v.y) * Math.acos(v.x / v.length()); - ref.radius = v.length(); - ref.theta = theta; - return ref; - } - /** - * Converts a given Vector2 to its polar coordinates - * @param v the Vector2 to convert - * @returns a Polar - */ - static FromVector2(v) { - const polar = new Polar(0, 0); - Polar.FromVector2ToRef(v, polar); - return polar; - } - /** - * Converts an array of floats to a polar - * @param array the array to convert - * @returns the converted polar - */ - static FromArray(array) { - return new Polar(array[0], array[1]); - } -} -/** - * Class used for (radius, theta, phi) vector representation. - */ -class Spherical { - /** - * @param radius spherical radius - * @param theta angle from positive y axis to radial line from 0 to PI (vertical) - * @param phi angle from positive x axis measured anticlockwise from -PI to PI (horizontal) - */ - constructor(radius, theta, phi) { - this.radius = radius; - this.theta = theta; - this.phi = phi; - } - /** - * Gets the class name - * @returns the string "Spherical" - */ - getClassName() { - return "Spherical"; - } - /** - * Converts the current spherical to a string - * @returns the current spherical as a string - */ - toString() { - return JSON.stringify(this); - } - /** - * Converts the current spherical to an array - * @reutrns the current spherical as an array - */ - asArray() { - return [this.radius, this.theta, this.phi]; - } - /** - * Adds the current Spherical and the given Spherical and stores the result - * @param spherical the spherical to add - * @param ref the spherical to store the result in - * @returns the updated ref - */ - addToRef(spherical, ref) { - ref.radius = this.radius + spherical.radius; - ref.theta = this.theta + spherical.theta; - ref.phi = this.phi + spherical.phi; - return ref; - } - /** - * Adds the current Spherical and the given Spherical - * @param spherical the spherical to add - * @returns the sum spherical - */ - add(spherical) { - const ref = new Spherical(0, 0, 0); - this.addToRef(spherical, ref); - return ref; - } - /** - * Adds the given spherical to the current spherical - * @param spherical the spherical to add - * @returns the current spherical - */ - addInPlace(spherical) { - this.addToRef(spherical, this); - return this; - } - /** - * Adds the provided values to the current spherical - * @param radius the amount to add to the radius - * @param theta the amount to add to the theta - * @param phi the amount to add to the phi - * @returns the current spherical - */ - addInPlaceFromFloats(radius, theta, phi) { - this.radius += radius; - this.theta += theta; - this.phi += phi; - return this; - } - /** - * Subtracts the given Spherical from the current Spherical and stores the result - * @param spherical the spherical to subtract - * @param ref the spherical to store the result in - * @returns the updated ref - */ - subtractToRef(spherical, ref) { - ref.radius = this.radius - spherical.radius; - ref.theta = this.theta - spherical.theta; - ref.phi = this.phi - spherical.phi; - return ref; - } - /** - * Subtracts the given Spherical from the current Spherical - * @param spherical the spherical to subtract - * @returns the difference spherical - */ - subtract(spherical) { - const ref = new Spherical(0, 0, 0); - this.subtractToRef(spherical, ref); - return ref; - } - /** - * Subtracts the given Spherical from the current Spherical - * @param spherical the spherical to subtract - * @returns the current spherical - */ - subtractInPlace(spherical) { - this.subtractToRef(spherical, this); - return this; - } - /** - * Subtracts the given floats from the current spherical - * @param radius the amount to subtract from the radius - * @param theta the amount to subtract from the theta - * @param phi the amount to subtract from the phi - * @param ref the spherical to store the result in - * @returns the updated ref - */ - subtractFromFloatsToRef(radius, theta, phi, ref) { - ref.radius = this.radius - radius; - ref.theta = this.theta - theta; - ref.phi = this.phi - phi; - return ref; - } - /** - * Subtracts the given floats from the current spherical - * @param radius the amount to subtract from the radius - * @param theta the amount to subtract from the theta - * @param phi the amount to subtract from the phi - * @returns the difference spherical - */ - subtractFromFloats(radius, theta, phi) { - const ref = new Spherical(0, 0, 0); - this.subtractFromFloatsToRef(radius, theta, phi, ref); - return ref; - } - /** - * Multiplies the given Spherical with the current Spherical and stores the result - * @param spherical the spherical to multiply - * @param ref the spherical to store the result in - * @returns the updated ref - */ - multiplyToRef(spherical, ref) { - ref.radius = this.radius * spherical.radius; - ref.theta = this.theta * spherical.theta; - ref.phi = this.phi * spherical.phi; - return ref; - } - /** - * Multiplies the given Spherical with the current Spherical - * @param spherical the spherical to multiply - * @returns the product spherical - */ - multiply(spherical) { - const ref = new Spherical(0, 0, 0); - this.multiplyToRef(spherical, ref); - return ref; - } - /** - * Multiplies the given Spherical with the current Spherical - * @param spherical the spherical to multiply - * @returns the current spherical - */ - multiplyInPlace(spherical) { - this.multiplyToRef(spherical, this); - return this; - } - /** - * Divides the current Spherical by the given Spherical and stores the result - * @param spherical the spherical to divide - * @param ref the spherical to store the result in - * @returns the updated ref - */ - divideToRef(spherical, ref) { - ref.radius = this.radius / spherical.radius; - ref.theta = this.theta / spherical.theta; - ref.phi = this.phi / spherical.phi; - return ref; - } - /** - * Divides the current Spherical by the given Spherical - * @param spherical the spherical to divide - * @returns the quotient spherical - */ - divide(spherical) { - const ref = new Spherical(0, 0, 0); - this.divideToRef(spherical, ref); - return ref; - } - /** - * Divides the current Spherical by the given Spherical - * @param spherical the spherical to divide - * @returns the current spherical - */ - divideInPlace(spherical) { - this.divideToRef(spherical, this); - return this; - } - /** - * Clones the current spherical - * @returns a clone of the current spherical - */ - clone() { - return new Spherical(this.radius, this.theta, this.phi); - } - /** - * Copies the source spherical into the current spherical - * @param source the spherical to copy from - * @returns the current spherical - */ - copyFrom(source) { - this.radius = source.radius; - this.theta = source.theta; - this.phi = source.phi; - return this; - } - /** - * Copies the given values into the current spherical - * @param radius the radius to use - * @param theta the theta to use - * @param phi the phi to use - * @returns the current spherical - */ - copyFromFloats(radius, theta, phi) { - this.radius = radius; - this.theta = theta; - this.phi = phi; - return this; - } - /** - * Scales the current spherical and stores the result - * @param scale defines the multiplication factor - * @param ref where to store the result - * @returns the updated ref - */ - scaleToRef(scale, ref) { - ref.radius = this.radius * scale; - ref.theta = this.theta * scale; - ref.phi = this.phi * scale; - return ref; - } - /** - * Scales the current spherical and returns a new spherical with the scaled coordinates - * @param scale defines the multiplication factor - * @returns the scaled spherical - */ - scale(scale) { - const ref = new Spherical(0, 0, 0); - this.scaleToRef(scale, ref); - return ref; - } - /** - * Scales the current spherical - * @param scale defines the multiplication factor - * @returns the current spherical - */ - scaleInPlace(scale) { - this.scaleToRef(scale, this); - return this; - } - /** - * Sets the values of the current spherical - * @param radius the new radius - * @param theta the new theta - * @param phi the new phi - * @returns the current spherical - */ - set(radius, theta, phi) { - this.radius = radius; - this.theta = theta; - this.phi = phi; - return this; - } - /** - * Sets the values of the current spherical - * @param value the new values - * @returns the current spherical - */ - setAll(value) { - this.set(value, value, value); - return this; - } - /** - * Assigns the rectangular coordinates of the current Spherical to a Vector3 - * @param ref the Vector3 to update - * @returns the updated Vector3 - */ - toVector3ToRef(ref) { - const x = this.radius * Math.sin(this.theta) * Math.cos(this.phi); - const y = this.radius * Math.cos(this.theta); - const z = this.radius * Math.sin(this.theta) * Math.sin(this.phi); - ref.set(x, y, z); - return ref; - } - /** - * Gets a Vector3 from the current spherical coordinates - * @returns the (x, y,z) form of the current Spherical - */ - toVector3() { - const ref = new Vector3(0, 0, 0); - return this.toVector3ToRef(ref); - } - /** - * Assigns the spherical coordinates from a Vector3 - * @param vector the vector to convert - * @param ref the Spherical to update - * @returns the updated ref - */ - static FromVector3ToRef(vector, ref) { - ref.radius = vector.length(); - ref.theta = Math.acos(vector.y / ref.radius); - ref.phi = Math.atan2(vector.z, vector.x); - return ref; - } - /** - * Gets a Spherical from a Vector3 - * @param vector defines the vector in (x, y, z) coordinate space - * @returns a new Spherical - */ - static FromVector3(vector) { - const spherical = new Spherical(0, 0, 0); - Spherical.FromVector3ToRef(vector, spherical); - return spherical; - } - /** - * Converts an array of floats to a spherical - * @param array the array to convert - * @returns the converted spherical - */ - static FromArray(array) { - return new Spherical(array[0], array[1], array[2]); - } -} -//# sourceMappingURL=math.polar.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Maths/index.js - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Compression/dracoCompression.js -/* eslint-disable @typescript-eslint/naming-convention */ - - - -function createDecoderAsync(wasmBinary) { - return new Promise((resolve) => { - DracoDecoderModule({ wasmBinary: wasmBinary }).then((module) => { - resolve({ module: module }); - }); - }); -} -function decodeMesh(decoderModule, dataView, attributes, onIndicesData, onAttributeData, dividers) { - const buffer = new decoderModule.DecoderBuffer(); - buffer.Init(dataView, dataView.byteLength); - const decoder = new decoderModule.Decoder(); - let geometry; - let status; - try { - const type = decoder.GetEncodedGeometryType(buffer); - switch (type) { - case decoderModule.TRIANGULAR_MESH: - geometry = new decoderModule.Mesh(); - status = decoder.DecodeBufferToMesh(buffer, geometry); - break; - case decoderModule.POINT_CLOUD: - geometry = new decoderModule.PointCloud(); - status = decoder.DecodeBufferToPointCloud(buffer, geometry); - break; - default: - throw new Error(`Invalid geometry type ${type}`); - } - if (!status.ok() || !geometry.ptr) { - throw new Error(status.error_msg()); - } - if (type === decoderModule.TRIANGULAR_MESH) { - const numFaces = geometry.num_faces(); - const numIndices = numFaces * 3; - const byteLength = numIndices * 4; - const ptr = decoderModule._malloc(byteLength); - try { - decoder.GetTrianglesUInt32Array(geometry, byteLength, ptr); - const indices = new Uint32Array(numIndices); - indices.set(new Uint32Array(decoderModule.HEAPF32.buffer, ptr, numIndices)); - onIndicesData(indices); - } - finally { - decoderModule._free(ptr); - } - } - const processAttribute = (kind, attribute, divider = 1) => { - const numComponents = attribute.num_components(); - const numPoints = geometry.num_points(); - const numValues = numPoints * numComponents; - const byteLength = numValues * Float32Array.BYTES_PER_ELEMENT; - const ptr = decoderModule._malloc(byteLength); - try { - decoder.GetAttributeDataArrayForAllPoints(geometry, attribute, decoderModule.DT_FLOAT32, byteLength, ptr); - const values = new Float32Array(decoderModule.HEAPF32.buffer, ptr, numValues); - if (kind === "color" && numComponents === 3) { - const babylonData = new Float32Array(numPoints * 4); - for (let i = 0, j = 0; i < babylonData.length; i += 4, j += numComponents) { - babylonData[i + 0] = values[j + 0]; - babylonData[i + 1] = values[j + 1]; - babylonData[i + 2] = values[j + 2]; - babylonData[i + 3] = 1; - } - onAttributeData(kind, babylonData); - } - else { - const babylonData = new Float32Array(numValues); - babylonData.set(new Float32Array(decoderModule.HEAPF32.buffer, ptr, numValues)); - if (divider !== 1) { - for (let i = 0; i < babylonData.length; i++) { - babylonData[i] = babylonData[i] / divider; - } - } - onAttributeData(kind, babylonData); - } - } - finally { - decoderModule._free(ptr); - } - }; - if (attributes) { - for (const kind in attributes) { - const id = attributes[kind]; - const attribute = decoder.GetAttributeByUniqueId(geometry, id); - const divider = (dividers && dividers[kind]) || 1; - processAttribute(kind, attribute, divider); - } - } - else { - const nativeAttributeTypes = { - position: "POSITION", - normal: "NORMAL", - color: "COLOR", - uv: "TEX_COORD", - }; - for (const kind in nativeAttributeTypes) { - const id = decoder.GetAttributeId(geometry, decoderModule[nativeAttributeTypes[kind]]); - if (id !== -1) { - const attribute = decoder.GetAttribute(geometry, id); - processAttribute(kind, attribute); - } - } - } - } - finally { - if (geometry) { - decoderModule.destroy(geometry); - } - decoderModule.destroy(decoder); - decoderModule.destroy(buffer); - } -} -/** - * The worker function that gets converted to a blob url to pass into a worker. - */ -function worker() { - let decoderPromise; - onmessage = (event) => { - const data = event.data; - switch (data.id) { - case "init": { - const decoder = data.decoder; - if (decoder.url) { - importScripts(decoder.url); - decoderPromise = DracoDecoderModule({ wasmBinary: decoder.wasmBinary }); - } - postMessage("done"); - break; - } - case "decodeMesh": { - if (!decoderPromise) { - throw new Error("Draco decoder module is not available"); - } - decoderPromise.then((decoder) => { - decodeMesh(decoder, data.dataView, data.attributes, (indices) => { - postMessage({ id: "indices", value: indices }, [indices.buffer]); - }, (kind, data) => { - postMessage({ id: kind, value: data }, [data.buffer]); - }); - postMessage("done"); - }); - break; - } - } - }; -} -/** - * Draco compression (https://google.github.io/draco/) - * - * This class wraps the Draco module. - * - * **Encoder** - * - * The encoder is not currently implemented. - * - * **Decoder** - * - * 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. - * - * To update the configuration, use the following code: - * ```javascript - * DracoCompression.Configuration = { - * decoder: { - * wasmUrl: "<url to the WebAssembly library>", - * wasmBinaryUrl: "<url to the WebAssembly binary>", - * fallbackUrl: "<url to the fallback JavaScript library>", - * } - * }; - * ``` - * - * 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. - * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser. - * Use `DracoCompression.DecoderAvailable` to determine if the decoder configuration is available for the current context. - * - * To decode Draco compressed data, get the default DracoCompression object and call decodeMeshAsync: - * ```javascript - * var vertexData = await DracoCompression.Default.decodeMeshAsync(data); - * ``` - * - * @see https://playground.babylonjs.com/#DMZIBD#0 - */ -class DracoCompression { - /** - * Returns true if the decoder configuration is available. - */ - static get DecoderAvailable() { - const decoder = DracoCompression.Configuration.decoder; - return !!((decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") || decoder.fallbackUrl); - } - static GetDefaultNumWorkers() { - if (typeof navigator !== "object" || !navigator.hardwareConcurrency) { - return 1; - } - // Use 50% of the available logical processors but capped at 4. - return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4); - } - /** - * Default instance for the draco compression object. - */ - static get Default() { - if (!DracoCompression._Default) { - DracoCompression._Default = new DracoCompression(); - } - return DracoCompression._Default; - } - /** - * Constructor - * @param numWorkers The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context. - */ - constructor(numWorkers = DracoCompression.DefaultNumWorkers) { - const decoder = DracoCompression.Configuration.decoder; - const decoderInfo = decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object" - ? { - url: tools_Tools.GetAbsoluteUrl(decoder.wasmUrl), - wasmBinaryPromise: tools_Tools.LoadFileAsync(tools_Tools.GetAbsoluteUrl(decoder.wasmBinaryUrl)), - } - : { - url: tools_Tools.GetAbsoluteUrl(decoder.fallbackUrl), - wasmBinaryPromise: Promise.resolve(undefined), - }; - if (numWorkers && typeof Worker === "function" && typeof URL === "function") { - this._workerPoolPromise = decoderInfo.wasmBinaryPromise.then((decoderWasmBinary) => { - const workerContent = `${decodeMesh}(${worker})()`; - const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" })); - return new AutoReleaseWorkerPool(numWorkers, () => { - return new Promise((resolve, reject) => { - const worker = new Worker(workerBlobUrl); - const onError = (error) => { - worker.removeEventListener("error", onError); - worker.removeEventListener("message", onMessage); - reject(error); - }; - const onMessage = (message) => { - if (message.data === "done") { - worker.removeEventListener("error", onError); - worker.removeEventListener("message", onMessage); - resolve(worker); - } - }; - worker.addEventListener("error", onError); - worker.addEventListener("message", onMessage); - worker.postMessage({ - id: "init", - decoder: { - url: decoderInfo.url, - wasmBinary: decoderWasmBinary, - }, - }); - }); - }); - }); - } - else { - this._decoderModulePromise = decoderInfo.wasmBinaryPromise.then((decoderWasmBinary) => { - if (!decoderInfo.url) { - throw new Error("Draco decoder module is not available"); - } - return tools_Tools.LoadScriptAsync(decoderInfo.url).then(() => { - return createDecoderAsync(decoderWasmBinary); - }); - }); - } - } - /** - * Stop all async operations and release resources. - */ - dispose() { - if (this._workerPoolPromise) { - this._workerPoolPromise.then((workerPool) => { - workerPool.dispose(); - }); - } - delete this._workerPoolPromise; - delete this._decoderModulePromise; - } - /** - * Returns a promise that resolves when ready. Call this manually to ensure draco compression is ready before use. - * @returns a promise that resolves when ready - */ - whenReadyAsync() { - if (this._workerPoolPromise) { - return this._workerPoolPromise.then(() => { }); - } - if (this._decoderModulePromise) { - return this._decoderModulePromise.then(() => { }); - } - return Promise.resolve(); - } - /** - * Decode Draco compressed mesh data to vertex data. - * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data - * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids - * @param dividers a list of optional dividers for normalization - * @returns A promise that resolves with the decoded vertex data - */ - decodeMeshAsync(data, attributes, dividers) { - const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data; - if (this._workerPoolPromise) { - return this._workerPoolPromise.then((workerPool) => { - return new Promise((resolve, reject) => { - workerPool.push((worker, onComplete) => { - const vertexData = new mesh_vertexData_VertexData(); - const onError = (error) => { - worker.removeEventListener("error", onError); - worker.removeEventListener("message", onMessage); - reject(error); - onComplete(); - }; - const onMessage = (message) => { - if (message.data === "done") { - worker.removeEventListener("error", onError); - worker.removeEventListener("message", onMessage); - resolve(vertexData); - onComplete(); - } - else if (message.data.id === "indices") { - vertexData.indices = message.data.value; - } - else { - // check normalization - const divider = dividers && dividers[message.data.id] ? dividers[message.data.id] : 1; - if (divider !== 1) { - // normalize - for (let i = 0; i < message.data.value.length; i++) { - message.data.value[i] = message.data.value[i] / divider; - } - } - vertexData.set(message.data.value, message.data.id); - } - }; - worker.addEventListener("error", onError); - worker.addEventListener("message", onMessage); - const dataViewCopy = new Uint8Array(dataView.byteLength); - dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength)); - worker.postMessage({ id: "decodeMesh", dataView: dataViewCopy, attributes: attributes }, [dataViewCopy.buffer]); - }); - }); - }); - } - if (this._decoderModulePromise) { - return this._decoderModulePromise.then((decoder) => { - const vertexData = new mesh_vertexData_VertexData(); - decodeMesh(decoder.module, dataView, attributes, (indices) => { - vertexData.indices = indices; - }, (kind, data) => { - vertexData.set(data, kind); - }, dividers); - return vertexData; - }); - } - throw new Error("Draco decoder module is not available"); - } -} -/** - * The configuration. Defaults to the following urls: - * - 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" - */ -DracoCompression.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", - }, -}; -/** - * Default number of workers to create when creating the draco compression object. - */ -DracoCompression.DefaultNumWorkers = DracoCompression.GetDefaultNumWorkers(); -DracoCompression._Default = null; -//# sourceMappingURL=dracoCompression.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Compression/meshoptCompression.js - -/** - * Meshopt compression (https://github.com/zeux/meshoptimizer) - * - * This class wraps the meshopt library from https://github.com/zeux/meshoptimizer/tree/master/js. - * - * **Encoder** - * - * The encoder is not currently implemented. - * - * **Decoder** - * - * 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). - * - * To update the configuration, use the following code: - * ```javascript - * MeshoptCompression.Configuration = { - * decoder: { - * url: "<url to the meshopt decoder library>" - * } - * }; - * ``` - */ -class MeshoptCompression { - /** - * Default instance for the meshoptimizer object. - */ - static get Default() { - if (!MeshoptCompression._Default) { - MeshoptCompression._Default = new MeshoptCompression(); - } - return MeshoptCompression._Default; - } - /** - * Constructor - */ - constructor() { - const decoder = MeshoptCompression.Configuration.decoder; - this._decoderModulePromise = tools_Tools.LoadScriptAsync(tools_Tools.GetAbsoluteUrl(decoder.url)).then(() => { - // Wait for WebAssembly compilation before resolving promise - return MeshoptDecoder.ready; - }); - } - /** - * Stop all async operations and release resources. - */ - dispose() { - delete this._decoderModulePromise; - } - /** - * Decode meshopt data. - * @see https://github.com/zeux/meshoptimizer/tree/master/js#decoder - * @param source The input data. - * @param count The number of elements. - * @param stride The stride in bytes. - * @param mode The compression mode. - * @param filter The compression filter. - * @returns a Promise<Uint8Array> that resolves to the decoded data - */ - decodeGltfBufferAsync(source, count, stride, mode, filter) { - return this._decoderModulePromise.then(() => { - const result = new Uint8Array(count * stride); - MeshoptDecoder.decodeGltfBuffer(result, count, stride, source, mode, filter); - return result; - }); - } -} -/** - * The configuration. Defaults to the following: - * ```javascript - * decoder: { - * url: "https://preview.babylonjs.com/meshopt_decoder.js" - * } - * ``` - */ -MeshoptCompression.Configuration = { - decoder: { - url: "https://preview.babylonjs.com/meshopt_decoder.js", - }, -}; -MeshoptCompression._Default = null; -//# sourceMappingURL=meshoptCompression.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Compression/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/csg.js - - - - - - -/** - * Unique ID when we import meshes from Babylon to CSG - */ -let currentCSGMeshId = 0; -/** - * Represents a vertex of a polygon. Use your own vertex class instead of this - * one to provide additional features like texture coordinates and vertex - * colors. Custom vertex classes need to provide a `pos` property and `clone()`, - * `flip()`, and `interpolate()` methods that behave analogous to the ones - * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience - * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal` - * is not used anywhere else. - * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes - */ -class Vertex { - /** - * Initializes the vertex - * @param pos The position of the vertex - * @param normal The normal of the vertex - * @param uv The texture coordinate of the vertex - * @param vertColor The RGBA color of the vertex - */ - constructor( - /** - * The position of the vertex - */ - pos, - /** - * The normal of the vertex - */ - normal, - /** - * The texture coordinate of the vertex - */ - uv, - /** - * The texture coordinate of the vertex - */ - vertColor) { - this.pos = pos; - this.normal = normal; - this.uv = uv; - this.vertColor = vertColor; - } - /** - * Make a clone, or deep copy, of the vertex - * @returns A new Vertex - */ - clone() { - var _a, _b; - 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()); - } - /** - * Invert all orientation-specific data (e.g. vertex normal). Called when the - * orientation of a polygon is flipped. - */ - flip() { - this.normal = this.normal.scale(-1); - } - /** - * Create a new vertex between this vertex and `other` by linearly - * interpolating all properties using a parameter of `t`. Subclasses should - * override this to interpolate additional properties. - * @param other the vertex to interpolate against - * @param t The factor used to linearly interpolate between the vertices - */ - interpolate(other, t) { - 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); - } -} -/** - * Represents a plane in 3D space. - */ -class csg_Plane { - /** - * Initializes the plane - * @param normal The normal for the plane - * @param w - */ - constructor(normal, w) { - this.normal = normal; - this.w = w; - } - /** - * Construct a plane from three points - * @param a Point a - * @param b Point b - * @param c Point c - */ - static FromPoints(a, b, c) { - const v0 = c.subtract(a); - const v1 = b.subtract(a); - if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) { - return null; - } - const n = math_vector_Vector3.Normalize(math_vector_Vector3.Cross(v0, v1)); - return new csg_Plane(n, math_vector_Vector3.Dot(n, a)); - } - /** - * Clone, or make a deep copy of the plane - * @returns a new Plane - */ - clone() { - return new csg_Plane(this.normal.clone(), this.w); - } - /** - * Flip the face of the plane - */ - flip() { - this.normal.scaleInPlace(-1); - this.w = -this.w; - } - /** - * Split `polygon` by this plane if needed, then put the polygon or polygon - * fragments in the appropriate lists. Coplanar polygons go into either - `* coplanarFront` or `coplanarBack` depending on their orientation with - * respect to this plane. Polygons in front or in back of this plane go into - * either `front` or `back` - * @param polygon The polygon to be split - * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane - * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane - * @param front Will contain the polygons in front of the plane - * @param back Will contain the polygons begind the plane - */ - splitPolygon(polygon, coplanarFront, coplanarBack, front, back) { - const COPLANAR = 0; - const FRONT = 1; - const BACK = 2; - const SPANNING = 3; - // Classify each point as well as the entire polygon into one of the above - // four classes. - let polygonType = 0; - const types = []; - let i; - let t; - for (i = 0; i < polygon.vertices.length; i++) { - t = math_vector_Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w; - const type = t < -csg_Plane.EPSILON ? BACK : t > csg_Plane.EPSILON ? FRONT : COPLANAR; - polygonType |= type; - types.push(type); - } - // Put the polygon in the correct list, splitting it when necessary - switch (polygonType) { - case COPLANAR: - (math_vector_Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon); - break; - case FRONT: - front.push(polygon); - break; - case BACK: - back.push(polygon); - break; - case SPANNING: { - const f = [], b = []; - for (i = 0; i < polygon.vertices.length; i++) { - const j = (i + 1) % polygon.vertices.length; - const ti = types[i], tj = types[j]; - const vi = polygon.vertices[i], vj = polygon.vertices[j]; - if (ti !== BACK) { - f.push(vi); - } - if (ti !== FRONT) { - b.push(ti !== BACK ? vi.clone() : vi); - } - if ((ti | tj) === SPANNING) { - t = (this.w - math_vector_Vector3.Dot(this.normal, vi.pos)) / math_vector_Vector3.Dot(this.normal, vj.pos.subtract(vi.pos)); - const v = vi.interpolate(vj, t); - f.push(v); - b.push(v.clone()); - } - } - let poly; - if (f.length >= 3) { - poly = new csg_Polygon(f, polygon.shared); - if (poly.plane) { - front.push(poly); - } - } - if (b.length >= 3) { - poly = new csg_Polygon(b, polygon.shared); - if (poly.plane) { - back.push(poly); - } - } - break; - } - } - } -} -/** - * `CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a - * point is on the plane - */ -csg_Plane.EPSILON = 1e-5; -/** - * Represents a convex polygon. The vertices used to initialize a polygon must - * be coplanar and form a convex loop. - * - * Each convex polygon has a `shared` property, which is shared between all - * polygons that are clones of each other or were split from the same polygon. - * This can be used to define per-polygon properties (such as surface color) - */ -class csg_Polygon { - /** - * Initializes the polygon - * @param vertices The vertices of the polygon - * @param shared The properties shared across all polygons - */ - constructor(vertices, shared) { - this.vertices = vertices; - this.shared = shared; - this.plane = csg_Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos); - } - /** - * Clones, or makes a deep copy, or the polygon - */ - clone() { - const vertices = this.vertices.map((v) => v.clone()); - return new csg_Polygon(vertices, this.shared); - } - /** - * Flips the faces of the polygon - */ - flip() { - this.vertices.reverse().map((v) => { - v.flip(); - }); - this.plane.flip(); - } -} -/** - * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons - * by picking a polygon to split along. That polygon (and all other coplanar - * polygons) are added directly to that node and the other polygons are added to - * the front and/or back subtrees. This is not a leafy BSP tree since there is - * no distinction between internal and leaf nodes - */ -class csg_Node { - /** - * Initializes the node - * @param polygons A collection of polygons held in the node - */ - constructor(polygons) { - this._plane = null; - this._front = null; - this._back = null; - this._polygons = new Array(); - if (polygons) { - this.build(polygons); - } - } - /** - * Clones, or makes a deep copy, of the node - * @returns The cloned node - */ - clone() { - const node = new csg_Node(); - node._plane = this._plane && this._plane.clone(); - node._front = this._front && this._front.clone(); - node._back = this._back && this._back.clone(); - node._polygons = this._polygons.map((p) => p.clone()); - return node; - } - /** - * Convert solid space to empty space and empty space to solid space - */ - invert() { - for (let i = 0; i < this._polygons.length; i++) { - this._polygons[i].flip(); - } - if (this._plane) { - this._plane.flip(); - } - if (this._front) { - this._front.invert(); - } - if (this._back) { - this._back.invert(); - } - const temp = this._front; - this._front = this._back; - this._back = temp; - } - /** - * Recursively remove all polygons in `polygons` that are inside this BSP - * tree. - * @param polygons Polygons to remove from the BSP - * @returns Polygons clipped from the BSP - */ - clipPolygons(polygons) { - if (!this._plane) { - return polygons.slice(); - } - let front = new Array(), back = new Array(); - for (let i = 0; i < polygons.length; i++) { - this._plane.splitPolygon(polygons[i], front, back, front, back); - } - if (this._front) { - front = this._front.clipPolygons(front); - } - if (this._back) { - back = this._back.clipPolygons(back); - } - else { - back = []; - } - return front.concat(back); - } - /** - * Remove all polygons in this BSP tree that are inside the other BSP tree - * `bsp`. - * @param bsp BSP containing polygons to remove from this BSP - */ - clipTo(bsp) { - this._polygons = bsp.clipPolygons(this._polygons); - if (this._front) { - this._front.clipTo(bsp); - } - if (this._back) { - this._back.clipTo(bsp); - } - } - /** - * Return a list of all polygons in this BSP tree - * @returns List of all polygons in this BSP tree - */ - allPolygons() { - let polygons = this._polygons.slice(); - if (this._front) { - polygons = polygons.concat(this._front.allPolygons()); - } - if (this._back) { - polygons = polygons.concat(this._back.allPolygons()); - } - return polygons; - } - /** - * Build a BSP tree out of `polygons`. When called on an existing tree, the - * new polygons are filtered down to the bottom of the tree and become new - * nodes there. Each set of polygons is partitioned using the first polygon - * (no heuristic is used to pick a good split) - * @param polygons Polygons used to construct the BSP tree - */ - build(polygons) { - if (!polygons.length) { - return; - } - if (!this._plane) { - this._plane = polygons[0].plane.clone(); - } - const front = new Array(), back = new Array(); - for (let i = 0; i < polygons.length; i++) { - this._plane.splitPolygon(polygons[i], this._polygons, this._polygons, front, back); - } - if (front.length) { - if (!this._front) { - this._front = new csg_Node(); - } - this._front.build(front); - } - if (back.length) { - if (!this._back) { - this._back = new csg_Node(); - } - this._back.build(back); - } - } -} -/** - * Class for building Constructive Solid Geometry - */ -class CSG { - constructor() { - this._polygons = new Array(); - } - /** - * Convert the Mesh to CSG - * @param mesh The Mesh to convert to CSG - * @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) - * @returns A new CSG from the Mesh - */ - static FromMesh(mesh, absolute = false) { - let vertex, normal, uv = undefined, position, vertColor = undefined, polygon, vertices; - const polygons = new Array(); - let matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling; - let invertWinding = false; - if (mesh instanceof Mesh) { - mesh.computeWorldMatrix(true); - matrix = mesh.getWorldMatrix(); - meshPosition = mesh.position.clone(); - meshRotation = mesh.rotation.clone(); - if (mesh.rotationQuaternion) { - meshRotationQuaternion = mesh.rotationQuaternion.clone(); - } - meshScaling = mesh.scaling.clone(); - if (mesh.material && absolute) { - invertWinding = mesh.material.sideOrientation === 0; - } - } - else { - throw "BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh"; - } - const indices = mesh.getIndices(), positions = mesh.getVerticesData(VertexBuffer.PositionKind), normals = mesh.getVerticesData(VertexBuffer.NormalKind), uvs = mesh.getVerticesData(VertexBuffer.UVKind), vertColors = mesh.getVerticesData(VertexBuffer.ColorKind); - const subMeshes = mesh.subMeshes; - for (let sm = 0, sml = subMeshes.length; sm < sml; sm++) { - for (let i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) { - vertices = []; - for (let j = 0; j < 3; j++) { - const indexIndices = j === 0 ? i + j : invertWinding ? i + 3 - j : i + j; - const sourceNormal = new Vector3(normals[indices[indexIndices] * 3], normals[indices[indexIndices] * 3 + 1], normals[indices[indexIndices] * 3 + 2]); - if (uvs) { - uv = new Vector2(uvs[indices[indexIndices] * 2], uvs[indices[indexIndices] * 2 + 1]); - } - if (vertColors) { - vertColor = new Color4(vertColors[indices[indexIndices] * 4], vertColors[indices[indexIndices] * 4 + 1], vertColors[indices[indexIndices] * 4 + 2], vertColors[indices[indexIndices] * 4 + 3]); - } - const sourcePosition = new Vector3(positions[indices[indexIndices] * 3], positions[indices[indexIndices] * 3 + 1], positions[indices[indexIndices] * 3 + 2]); - position = Vector3.TransformCoordinates(sourcePosition, matrix); - normal = Vector3.TransformNormal(sourceNormal, matrix); - vertex = new Vertex(position, normal, uv, vertColor); - vertices.push(vertex); - } - polygon = new csg_Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex }); - // To handle the case of degenerated triangle - // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated - if (polygon.plane) { - polygons.push(polygon); - } - } - } - const csg = CSG._FromPolygons(polygons); - csg.matrix = absolute ? Matrix.Identity() : matrix; - csg.position = absolute ? Vector3.Zero() : meshPosition; - csg.rotation = absolute ? Vector3.Zero() : meshRotation; - csg.scaling = absolute ? Vector3.One() : meshScaling; - csg.rotationQuaternion = absolute && meshRotationQuaternion ? Quaternion.Identity() : meshRotationQuaternion; - currentCSGMeshId++; - return csg; - } - /** - * Construct a CSG solid from a list of `CSG.Polygon` instances. - * @param polygons Polygons used to construct a CSG solid - */ - static _FromPolygons(polygons) { - const csg = new CSG(); - csg._polygons = polygons; - return csg; - } - /** - * Clones, or makes a deep copy, of the CSG - * @returns A new CSG - */ - clone() { - const csg = new CSG(); - csg._polygons = this._polygons.map((p) => p.clone()); - csg.copyTransformAttributes(this); - return csg; - } - /** - * Unions this CSG with another CSG - * @param csg The CSG to union against this CSG - * @returns The unioned CSG - */ - union(csg) { - const a = new csg_Node(this.clone()._polygons); - const b = new csg_Node(csg.clone()._polygons); - a.clipTo(b); - b.clipTo(a); - b.invert(); - b.clipTo(a); - b.invert(); - a.build(b.allPolygons()); - return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this); - } - /** - * Unions this CSG with another CSG in place - * @param csg The CSG to union against this CSG - */ - unionInPlace(csg) { - const a = new csg_Node(this._polygons); - const b = new csg_Node(csg._polygons); - a.clipTo(b); - b.clipTo(a); - b.invert(); - b.clipTo(a); - b.invert(); - a.build(b.allPolygons()); - this._polygons = a.allPolygons(); - } - /** - * Subtracts this CSG with another CSG - * @param csg The CSG to subtract against this CSG - * @returns A new CSG - */ - subtract(csg) { - const a = new csg_Node(this.clone()._polygons); - const b = new csg_Node(csg.clone()._polygons); - a.invert(); - a.clipTo(b); - b.clipTo(a); - b.invert(); - b.clipTo(a); - b.invert(); - a.build(b.allPolygons()); - a.invert(); - return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this); - } - /** - * Subtracts this CSG with another CSG in place - * @param csg The CSG to subtract against this CSG - */ - subtractInPlace(csg) { - const a = new csg_Node(this._polygons); - const b = new csg_Node(csg._polygons); - a.invert(); - a.clipTo(b); - b.clipTo(a); - b.invert(); - b.clipTo(a); - b.invert(); - a.build(b.allPolygons()); - a.invert(); - this._polygons = a.allPolygons(); - } - /** - * Intersect this CSG with another CSG - * @param csg The CSG to intersect against this CSG - * @returns A new CSG - */ - intersect(csg) { - const a = new csg_Node(this.clone()._polygons); - const b = new csg_Node(csg.clone()._polygons); - a.invert(); - b.clipTo(a); - b.invert(); - a.clipTo(b); - b.clipTo(a); - a.build(b.allPolygons()); - a.invert(); - return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this); - } - /** - * Intersects this CSG with another CSG in place - * @param csg The CSG to intersect against this CSG - */ - intersectInPlace(csg) { - const a = new csg_Node(this._polygons); - const b = new csg_Node(csg._polygons); - a.invert(); - b.clipTo(a); - b.invert(); - a.clipTo(b); - b.clipTo(a); - a.build(b.allPolygons()); - a.invert(); - this._polygons = a.allPolygons(); - } - /** - * Return a new CSG solid with solid and empty space switched. This solid is - * not modified. - * @returns A new CSG solid with solid and empty space switched - */ - inverse() { - const csg = this.clone(); - csg.inverseInPlace(); - return csg; - } - /** - * Inverses the CSG in place - */ - inverseInPlace() { - this._polygons.map((p) => { - p.flip(); - }); - } - /** - * This is used to keep meshes transformations so they can be restored - * when we build back a Babylon Mesh - * NB : All CSG operations are performed in world coordinates - * @param csg The CSG to copy the transform attributes from - * @returns This CSG - */ - copyTransformAttributes(csg) { - this.matrix = csg.matrix; - this.position = csg.position; - this.rotation = csg.rotation; - this.scaling = csg.scaling; - this.rotationQuaternion = csg.rotationQuaternion; - return this; - } - /** - * Build Raw mesh from CSG - * Coordinates here are in world space - * @param name The name of the mesh geometry - * @param scene The Scene - * @param keepSubMeshes Specifies if the submeshes should be kept - * @returns A new Mesh - */ - buildMeshGeometry(name, scene, keepSubMeshes) { - const matrix = this.matrix.clone(); - matrix.invert(); - const mesh = new Mesh(name, scene); - const vertices = []; - const indices = []; - const normals = []; - let uvs = null; - let vertColors = null; - const vertex = Vector3.Zero(); - const normal = Vector3.Zero(); - const uv = Vector2.Zero(); - const vertColor = new Color4(0, 0, 0, 0); - const polygons = this._polygons; - const polygonIndices = [0, 0, 0]; - let polygon; - const vertice_dict = {}; - let vertex_idx; - let currentIndex = 0; - const subMeshDict = {}; - let subMeshObj; - if (keepSubMeshes) { - // Sort Polygons, since subMeshes are indices range - polygons.sort((a, b) => { - if (a.shared.meshId === b.shared.meshId) { - return a.shared.subMeshId - b.shared.subMeshId; - } - else { - return a.shared.meshId - b.shared.meshId; - } - }); - } - for (let i = 0, il = polygons.length; i < il; i++) { - polygon = polygons[i]; - // Building SubMeshes - if (!subMeshDict[polygon.shared.meshId]) { - subMeshDict[polygon.shared.meshId] = {}; - } - if (!subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId]) { - subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId] = { - indexStart: +Infinity, - indexEnd: -Infinity, - materialIndex: polygon.shared.materialIndex, - }; - } - subMeshObj = subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId]; - for (let j = 2, jl = polygon.vertices.length; j < jl; j++) { - polygonIndices[0] = 0; - polygonIndices[1] = j - 1; - polygonIndices[2] = j; - for (let k = 0; k < 3; k++) { - vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos); - normal.copyFrom(polygon.vertices[polygonIndices[k]].normal); - if (polygon.vertices[polygonIndices[k]].uv) { - if (!uvs) { - uvs = []; - } - uv.copyFrom(polygon.vertices[polygonIndices[k]].uv); - } - if (polygon.vertices[polygonIndices[k]].vertColor) { - if (!vertColors) { - vertColors = []; - } - vertColor.copyFrom(polygon.vertices[polygonIndices[k]].vertColor); - } - const localVertex = Vector3.TransformCoordinates(vertex, matrix); - const localNormal = Vector3.TransformNormal(normal, matrix); - vertex_idx = vertice_dict[localVertex.x + "," + localVertex.y + "," + localVertex.z]; - let areUvsDifferent = false; - if (uvs && !(uvs[vertex_idx * 2] === uv.x || uvs[vertex_idx * 2 + 1] === uv.y)) { - areUvsDifferent = true; - } - let areColorsDifferent = false; - if (vertColors && - !(vertColors[vertex_idx * 4] === vertColor.r || - vertColors[vertex_idx * 4 + 1] === vertColor.g || - vertColors[vertex_idx * 4 + 2] === vertColor.b || - vertColors[vertex_idx * 4 + 3] === vertColor.a)) { - areColorsDifferent = true; - } - // Check if 2 points can be merged - if (!(typeof vertex_idx !== "undefined" && - normals[vertex_idx * 3] === localNormal.x && - normals[vertex_idx * 3 + 1] === localNormal.y && - normals[vertex_idx * 3 + 2] === localNormal.z) || - areUvsDifferent || - areColorsDifferent) { - vertices.push(localVertex.x, localVertex.y, localVertex.z); - if (uvs) { - uvs.push(uv.x, uv.y); - } - normals.push(normal.x, normal.y, normal.z); - if (vertColors) { - vertColors.push(vertColor.r, vertColor.g, vertColor.b, vertColor.a); - } - vertex_idx = vertice_dict[localVertex.x + "," + localVertex.y + "," + localVertex.z] = vertices.length / 3 - 1; - } - indices.push(vertex_idx); - subMeshObj.indexStart = Math.min(currentIndex, subMeshObj.indexStart); - subMeshObj.indexEnd = Math.max(currentIndex, subMeshObj.indexEnd); - currentIndex++; - } - } - } - mesh.setVerticesData(VertexBuffer.PositionKind, vertices); - mesh.setVerticesData(VertexBuffer.NormalKind, normals); - if (uvs) { - mesh.setVerticesData(VertexBuffer.UVKind, uvs); - } - if (vertColors) { - mesh.setVerticesData(VertexBuffer.ColorKind, vertColors); - } - mesh.setIndices(indices, null); - if (keepSubMeshes) { - // We offset the materialIndex by the previous number of materials in the CSG mixed meshes - let materialIndexOffset = 0, materialMaxIndex; - mesh.subMeshes = new Array(); - for (const m in subMeshDict) { - materialMaxIndex = -1; - for (const sm in subMeshDict[m]) { - subMeshObj = subMeshDict[m][sm]; - SubMesh.CreateFromIndices(subMeshObj.materialIndex + materialIndexOffset, subMeshObj.indexStart, subMeshObj.indexEnd - subMeshObj.indexStart + 1, mesh); - materialMaxIndex = Math.max(subMeshObj.materialIndex, materialMaxIndex); - } - materialIndexOffset += ++materialMaxIndex; - } - } - return mesh; - } - /** - * Build Mesh from CSG taking material and transforms into account - * @param name The name of the Mesh - * @param material The material of the Mesh - * @param scene The Scene - * @param keepSubMeshes Specifies if submeshes should be kept - * @returns The new Mesh - */ - toMesh(name, material = null, scene, keepSubMeshes) { - const mesh = this.buildMeshGeometry(name, scene, keepSubMeshes); - mesh.material = material; - mesh.position.copyFrom(this.position); - mesh.rotation.copyFrom(this.rotation); - if (this.rotationQuaternion) { - mesh.rotationQuaternion = this.rotationQuaternion.clone(); - } - mesh.scaling.copyFrom(this.scaling); - mesh.computeWorldMatrix(true); - return mesh; - } -} -//# sourceMappingURL=csg.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/meshUVSpaceRenderer.vertex.js -// Do not edit. - - - - - - - - - - - -const meshUVSpaceRenderer_vertex_name = "meshUVSpaceRendererVertexShader"; -const meshUVSpaceRenderer_vertex_shader = `precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<instancesDeclaration> -void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normWorldSM=transposeMat3(inverseMat3(normWorldSM)); -#endif -vNormalW=normalize(normWorldSM*normalUpdated); -#endif -vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);} -`; -// Sideeffect -ShaderStore.ShadersStore[meshUVSpaceRenderer_vertex_name] = meshUVSpaceRenderer_vertex_shader; -/** @internal */ -const meshUVSpaceRendererVertexShader = { name: meshUVSpaceRenderer_vertex_name, shader: meshUVSpaceRenderer_vertex_shader }; -//# sourceMappingURL=meshUVSpaceRenderer.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/meshUVSpaceRenderer.fragment.js -// Do not edit. - -const meshUVSpaceRenderer_fragment_name = "meshUVSpaceRendererPixelShader"; -const meshUVSpaceRenderer_fragment_shader = `precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} -gl_FragColor=texture2D(textureSampler,vDecalTC);} -`; -// Sideeffect -ShaderStore.ShadersStore[meshUVSpaceRenderer_fragment_name] = meshUVSpaceRenderer_fragment_shader; -/** @internal */ -const meshUVSpaceRendererPixelShader = { name: meshUVSpaceRenderer_fragment_name, shader: meshUVSpaceRenderer_fragment_shader }; -//# sourceMappingURL=meshUVSpaceRenderer.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/meshUVSpaceRenderer.js - - - - - - - -/** - * Class used to render in the mesh UV space - * @since 5.49.1 - */ -class MeshUVSpaceRenderer { - static _GetShader(scene) { - if (!scene._meshUVSpaceRendererShader) { - const shader = new ShaderMaterial("meshUVSpaceRendererShader", scene, { - vertex: "meshUVSpaceRenderer", - fragment: "meshUVSpaceRenderer", - }, { - attributes: ["position", "normal", "uv"], - uniforms: ["world", "projMatrix"], - samplers: ["textureSampler"], - needAlphaBlending: true, - }); - shader.backFaceCulling = false; - shader.alphaMode = 2; - scene.onDisposeObservable.add(() => { - var _a; - (_a = scene._meshUVSpaceRendererShader) === null || _a === void 0 ? void 0 : _a.dispose(); - scene._meshUVSpaceRendererShader = null; - }); - scene._meshUVSpaceRendererShader = shader; - } - return scene._meshUVSpaceRendererShader; - } - static _IsRenderTargetTexture(texture) { - return texture.renderList !== undefined; - } - /** - * Creates a new MeshUVSpaceRenderer - * @param mesh The mesh used for the source UV space - * @param scene The scene the mesh belongs to - * @param options The options to use when creating the texture - */ - constructor(mesh, scene, options) { - this._textureCreatedInternally = false; - /** - * Clear color of the texture - */ - this.clearColor = new Color4(0, 0, 0, 0); - this._mesh = mesh; - this._scene = scene; - this._options = Object.assign({ width: 1024, height: 1024, textureType: 0, generateMipMaps: true, optimizeUVAllocation: true }, options); - } - /** - * Checks if the texture is ready to be used - * @returns true if the texture is ready to be used - */ - isReady() { - if (!this.texture) { - this._createDiffuseRTT(); - } - return MeshUVSpaceRenderer._IsRenderTargetTexture(this.texture) ? this.texture.isReadyForRendering() : this.texture.isReady(); - } - /** - * Projects and renders a texture in the mesh UV space - * @param texture The texture - * @param position The position of the center of projection (world space coordinates) - * @param normal The direction of the projection (world space coordinates) - * @param size The size of the projection - * @param angle The rotation angle around the direction of the projection - */ - renderTexture(texture, position, normal, size, angle = 0) { - if (!this.texture) { - this._createDiffuseRTT(); - } - if (MeshUVSpaceRenderer._IsRenderTargetTexture(this.texture)) { - const matrix = this._createProjectionMatrix(position, normal, size, angle); - const shader = MeshUVSpaceRenderer._GetShader(this._scene); - shader.setTexture("textureSampler", texture); - shader.setMatrix("projMatrix", matrix); - this.texture.render(); - } - } - /** - * Clears the texture map - */ - clear() { - if (MeshUVSpaceRenderer._IsRenderTargetTexture(this.texture) && this.texture.renderTarget) { - const engine = this._scene.getEngine(); - engine.bindFramebuffer(this.texture.renderTarget); - engine.clear(this.clearColor, true, true, true); - engine.unBindFramebuffer(this.texture.renderTarget); - } - } - /** - * Disposes of the ressources - */ - dispose() { - if (this._textureCreatedInternally) { - this.texture.dispose(); - this._textureCreatedInternally = false; - } - } - _createDiffuseRTT() { - this._textureCreatedInternally = true; - const texture = this._createRenderTargetTexture(this._options.width, this._options.height); - texture.setMaterialForRendering(this._mesh, MeshUVSpaceRenderer._GetShader(this._scene)); - this.texture = texture; - } - _createRenderTargetTexture(width, height) { - 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); - rtt.renderParticles = false; - rtt.optimizeUVAllocation = !!this._options.optimizeUVAllocation; - rtt.onClearObservable.addOnce(() => { - this._scene.getEngine().clear(this.clearColor, true, true, true); - rtt.onClearObservable.add(() => { }); // this disables clearing the texture for the next frames - }); - rtt.renderList = [this._mesh]; - return rtt; - } - _createProjectionMatrix(position, normal, size, angle = 0) { - const yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2; - const len = Math.sqrt(normal.x * normal.x + normal.z * normal.z); - const pitch = Math.atan2(normal.y, len); - const p = position.add(normal.scale(size.z * 0.5)); - const projWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(p.x, p.y, p.z)); - const inverseProjWorldMatrix = Matrix.Invert(projWorldMatrix); - 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]); - 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]); - return inverseProjWorldMatrix.multiply(projMatrix).multiply(screenMatrix); - } -} -//# sourceMappingURL=meshUVSpaceRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/trailMesh.js - - - - - -mesh_Mesh._TrailMeshParser = (parsedMesh, scene) => { - return TrailMesh.Parse(parsedMesh, scene); -}; -/** - * Class used to create a trail following a mesh - */ -class TrailMesh extends mesh_Mesh { - /** - * Creates a new TrailMesh. - * @param name The value used by scene.getMeshByName() to do a lookup. - * @param generator The mesh or transform node to generate a trail. - * @param scene The scene to add this mesh to. - * @param diameter Diameter of trailing mesh. Default is 1. - * @param length Length of trailing mesh. Default is 60. - * @param autoStart Automatically start trailing mesh. Default true. - */ - constructor(name, generator, scene, diameter = 1, length = 60, autoStart = true) { - super(name, scene); - this._sectionPolygonPointsCount = 4; - this._running = false; - this._autoStart = autoStart; - this._generator = generator; - this.diameter = diameter; - this._length = length; - this._sectionVectors = []; - this._sectionNormalVectors = []; - for (let i = 0; i < this._sectionPolygonPointsCount; i++) { - this._sectionVectors[i] = math_vector_Vector3.Zero(); - this._sectionNormalVectors[i] = math_vector_Vector3.Zero(); - } - this._createMesh(); - } - /** - * "TrailMesh" - * @returns "TrailMesh" - */ - getClassName() { - return "TrailMesh"; - } - _createMesh() { - const data = new mesh_vertexData_VertexData(); - const positions = []; - const normals = []; - const indices = []; - let meshCenter = math_vector_Vector3.Zero(); - if (this._generator instanceof abstractMesh_AbstractMesh && this._generator.hasBoundingInfo) { - meshCenter = this._generator.getBoundingInfo().boundingBox.centerWorld; - } - else { - meshCenter = this._generator.position; - } - const alpha = (2 * Math.PI) / this._sectionPolygonPointsCount; - for (let i = 0; i < this._sectionPolygonPointsCount; i++) { - positions.push(meshCenter.x + Math.cos(i * alpha) * this.diameter, meshCenter.y + Math.sin(i * alpha) * this.diameter, meshCenter.z); - } - for (let i = 1; i <= this._length; i++) { - for (let j = 0; j < this._sectionPolygonPointsCount; j++) { - positions.push(meshCenter.x + Math.cos(j * alpha) * this.diameter, meshCenter.y + Math.sin(j * alpha) * this.diameter, meshCenter.z); - } - const l = positions.length / 3 - 2 * this._sectionPolygonPointsCount; - for (let j = 0; j < this._sectionPolygonPointsCount - 1; j++) { - indices.push(l + j, l + j + this._sectionPolygonPointsCount, l + j + this._sectionPolygonPointsCount + 1); - indices.push(l + j, l + j + this._sectionPolygonPointsCount + 1, l + j + 1); - } - indices.push(l + this._sectionPolygonPointsCount - 1, l + this._sectionPolygonPointsCount - 1 + this._sectionPolygonPointsCount, l + this._sectionPolygonPointsCount); - indices.push(l + this._sectionPolygonPointsCount - 1, l + this._sectionPolygonPointsCount, l); - } - mesh_vertexData_VertexData.ComputeNormals(positions, indices, normals); - data.positions = positions; - data.normals = normals; - data.indices = indices; - data.applyToMesh(this, true); - if (this._autoStart) { - this.start(); - } - } - /** - * Start trailing mesh. - */ - start() { - if (!this._running) { - this._running = true; - this._beforeRenderObserver = this.getScene().onBeforeRenderObservable.add(() => { - this.update(); - }); - } - } - /** - * Stop trailing mesh. - */ - stop() { - if (this._beforeRenderObserver && this._running) { - this._running = false; - this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver); - } - } - /** - * Update trailing mesh geometry. - */ - update() { - const positions = this.getVerticesData(buffer_VertexBuffer.PositionKind); - const normals = this.getVerticesData(buffer_VertexBuffer.NormalKind); - const wm = this._generator.getWorldMatrix(); - if (positions && normals) { - for (let i = 3 * this._sectionPolygonPointsCount; i < positions.length; i++) { - positions[i - 3 * this._sectionPolygonPointsCount] = positions[i] - (normals[i] / this._length) * this.diameter; - } - for (let i = 3 * this._sectionPolygonPointsCount; i < normals.length; i++) { - normals[i - 3 * this._sectionPolygonPointsCount] = normals[i]; - } - const l = positions.length - 3 * this._sectionPolygonPointsCount; - const alpha = (2 * Math.PI) / this._sectionPolygonPointsCount; - for (let i = 0; i < this._sectionPolygonPointsCount; i++) { - this._sectionVectors[i].copyFromFloats(Math.cos(i * alpha) * this.diameter, Math.sin(i * alpha) * this.diameter, 0); - this._sectionNormalVectors[i].copyFromFloats(Math.cos(i * alpha), Math.sin(i * alpha), 0); - math_vector_Vector3.TransformCoordinatesToRef(this._sectionVectors[i], wm, this._sectionVectors[i]); - math_vector_Vector3.TransformNormalToRef(this._sectionNormalVectors[i], wm, this._sectionNormalVectors[i]); - } - for (let i = 0; i < this._sectionPolygonPointsCount; i++) { - positions[l + 3 * i] = this._sectionVectors[i].x; - positions[l + 3 * i + 1] = this._sectionVectors[i].y; - positions[l + 3 * i + 2] = this._sectionVectors[i].z; - normals[l + 3 * i] = this._sectionNormalVectors[i].x; - normals[l + 3 * i + 1] = this._sectionNormalVectors[i].y; - normals[l + 3 * i + 2] = this._sectionNormalVectors[i].z; - } - this.updateVerticesData(buffer_VertexBuffer.PositionKind, positions, true, false); - this.updateVerticesData(buffer_VertexBuffer.NormalKind, normals, true, false); - } - } - /** - * Returns a new TrailMesh object. - * @param name is a string, the name given to the new mesh - * @param newGenerator use new generator object for cloned trail mesh - * @returns a new mesh - */ - clone(name = "", newGenerator) { - return new TrailMesh(name, newGenerator === undefined ? this._generator : newGenerator, this.getScene(), this.diameter, this._length, this._autoStart); - } - /** - * Serializes this trail mesh - * @param serializationObject object to write serialization to - */ - serialize(serializationObject) { - super.serialize(serializationObject); - serializationObject.generatorId = this._generator.id; - } - /** - * Parses a serialized trail mesh - * @param parsedMesh the serialized mesh - * @param scene the scene to create the trail mesh in - * @returns the created trail mesh - */ - static Parse(parsedMesh, scene) { - var _a, _b; - const generator = (_a = scene.getLastMeshById(parsedMesh.generatorId)) !== null && _a !== void 0 ? _a : scene.getLastTransformNodeById(parsedMesh.generatorId); - if (!generator) { - throw new Error("TrailMesh: generator not found with ID " + parsedMesh.generatorId); - } - return new TrailMesh(parsedMesh.name, generator, scene, (_b = parsedMesh.diameter) !== null && _b !== void 0 ? _b : parsedMesh._diameter, parsedMesh._length, parsedMesh._autoStart); - } -} -//# sourceMappingURL=trailMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/meshSimplification.js - - - - - - -/** - * Class used to specify simplification options - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes - */ -class SimplificationSettings { - /** - * Creates a SimplificationSettings - * @param quality expected quality - * @param distance distance when this optimized version should be used - * @param optimizeMesh already optimized mesh - */ - constructor( - /** expected quality */ - quality, - /** distance when this optimized version should be used */ - distance, - /** already optimized mesh */ - optimizeMesh) { - this.quality = quality; - this.distance = distance; - this.optimizeMesh = optimizeMesh; - } -} -/** - * Queue used to order the simplification tasks - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes - */ -class SimplificationQueue { - /** - * Creates a new queue - */ - constructor() { - this.running = false; - this._simplificationArray = []; - } - /** - * Adds a new simplification task - * @param task defines a task to add - */ - addTask(task) { - this._simplificationArray.push(task); - } - /** - * Execute next task - */ - executeNext() { - const task = this._simplificationArray.pop(); - if (task) { - this.running = true; - this.runSimplification(task); - } - else { - this.running = false; - } - } - /** - * Execute a simplification task - * @param task defines the task to run - */ - runSimplification(task) { - if (task.parallelProcessing) { - //parallel simplifier - task.settings.forEach((setting) => { - const simplifier = this._getSimplifier(task); - simplifier.simplify(setting, (newMesh) => { - if (setting.distance !== undefined) { - task.mesh.addLODLevel(setting.distance, newMesh); - } - newMesh.isVisible = true; - //check if it is the last - if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) { - //all done, run the success callback. - task.successCallback(); - } - this.executeNext(); - }); - }); - } - else { - //single simplifier. - const simplifier = this._getSimplifier(task); - const runDecimation = (setting, callback) => { - simplifier.simplify(setting, (newMesh) => { - if (setting.distance !== undefined) { - task.mesh.addLODLevel(setting.distance, newMesh); - } - newMesh.isVisible = true; - //run the next quality level - callback(); - }); - }; - AsyncLoop.Run(task.settings.length, (loop) => { - runDecimation(task.settings[loop.index], () => { - loop.executeNext(); - }); - }, () => { - //execution ended, run the success callback. - if (task.successCallback) { - task.successCallback(); - } - this.executeNext(); - }); - } - } - _getSimplifier(task) { - switch (task.simplificationType) { - case SimplificationType.QUADRATIC: - default: - return new QuadraticErrorSimplification(task.mesh); - } - } -} -/** - * The implemented types of simplification - * At the moment only Quadratic Error Decimation is implemented - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes - */ -var SimplificationType; -(function (SimplificationType) { - /** Quadratic error decimation */ - SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC"; -})(SimplificationType || (SimplificationType = {})); -class DecimationTriangle { - constructor(_vertices) { - this._vertices = _vertices; - this.error = new Array(4); - this.deleted = false; - this.isDirty = false; - this.deletePending = false; - this.borderFactor = 0; - } -} -class DecimationVertex { - constructor(position, id) { - this.position = position; - this.id = id; - this.isBorder = true; - this.q = new QuadraticMatrix(); - this.triangleCount = 0; - this.triangleStart = 0; - this.originalOffsets = []; - } - updatePosition(newPosition) { - this.position.copyFrom(newPosition); - } -} -class QuadraticMatrix { - constructor(data) { - this.data = new Array(10); - for (let i = 0; i < 10; ++i) { - if (data && data[i]) { - this.data[i] = data[i]; - } - else { - this.data[i] = 0; - } - } - } - det(a11, a12, a13, a21, a22, a23, a31, a32, a33) { - const det = this.data[a11] * this.data[a22] * this.data[a33] + - this.data[a13] * this.data[a21] * this.data[a32] + - this.data[a12] * this.data[a23] * this.data[a31] - - this.data[a13] * this.data[a22] * this.data[a31] - - this.data[a11] * this.data[a23] * this.data[a32] - - this.data[a12] * this.data[a21] * this.data[a33]; - return det; - } - addInPlace(matrix) { - for (let i = 0; i < 10; ++i) { - this.data[i] += matrix.data[i]; - } - } - addArrayInPlace(data) { - for (let i = 0; i < 10; ++i) { - this.data[i] += data[i]; - } - } - add(matrix) { - const m = new QuadraticMatrix(); - for (let i = 0; i < 10; ++i) { - m.data[i] = this.data[i] + matrix.data[i]; - } - return m; - } - static FromData(a, b, c, d) { - return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d)); - } - //returning an array to avoid garbage collection - static DataFromNumbers(a, b, c, d) { - return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d]; - } -} -class Reference { - constructor(vertexId, triangleId) { - this.vertexId = vertexId; - this.triangleId = triangleId; - } -} -/** - * An implementation of the Quadratic Error simplification algorithm. - * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf - * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS - * @author RaananW - * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes - */ -class QuadraticErrorSimplification { - /** - * Creates a new QuadraticErrorSimplification - * @param _mesh defines the target mesh - */ - constructor(_mesh) { - this._mesh = _mesh; - /** Gets or sets the number pf sync iterations */ - this.syncIterations = 5000; - this.aggressiveness = 7; - this.decimationIterations = 100; - this.boundingBoxEpsilon = math_constants_Epsilon; - } - /** - * Simplification of a given mesh according to the given settings. - * Since this requires computation, it is assumed that the function runs async. - * @param settings The settings of the simplification, including quality and distance - * @param successCallback A callback that will be called after the mesh was simplified. - */ - simplify(settings, successCallback) { - this._initDecimatedMesh(); - //iterating through the submeshes array, one after the other. - AsyncLoop.Run(this._mesh.subMeshes.length, (loop) => { - this._initWithMesh(loop.index, () => { - this._runDecimation(settings, loop.index, () => { - loop.executeNext(); - }); - }, settings.optimizeMesh); - }, () => { - setTimeout(() => { - successCallback(this._reconstructedMesh); - }, 0); - }); - } - _runDecimation(settings, submeshIndex, successCallback) { - const targetCount = ~~(this._triangles.length * settings.quality); - let deletedTriangles = 0; - const triangleCount = this._triangles.length; - const iterationFunction = (iteration, callback) => { - setTimeout(() => { - if (iteration % 5 === 0) { - this._updateMesh(iteration === 0); - } - for (let i = 0; i < this._triangles.length; ++i) { - this._triangles[i].isDirty = false; - } - const threshold = 0.000000001 * Math.pow(iteration + 3, this.aggressiveness); - const trianglesIterator = (i) => { - const tIdx = ~~((this._triangles.length / 2 + i) % this._triangles.length); - const t = this._triangles[tIdx]; - if (!t) { - return; - } - if (t.error[3] > threshold || t.deleted || t.isDirty) { - return; - } - for (let j = 0; j < 3; ++j) { - if (t.error[j] < threshold) { - const deleted0 = []; - const deleted1 = []; - const v0 = t._vertices[j]; - const v1 = t._vertices[(j + 1) % 3]; - if (v0.isBorder || v1.isBorder) { - continue; - } - const p = math_vector_Vector3.Zero(); - // var n = Vector3.Zero(); - // var uv = Vector2.Zero(); - // var color = new Color4(0, 0, 0, 1); - this._calculateError(v0, v1, p); - const delTr = new Array(); - if (this._isFlipped(v0, v1, p, deleted0, delTr)) { - continue; - } - if (this._isFlipped(v1, v0, p, deleted1, delTr)) { - continue; - } - if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) { - continue; - } - const uniqueArray = new Array(); - delTr.forEach((deletedT) => { - if (uniqueArray.indexOf(deletedT) === -1) { - deletedT.deletePending = true; - uniqueArray.push(deletedT); - } - }); - if (uniqueArray.length % 2 !== 0) { - continue; - } - v0.q = v1.q.add(v0.q); - v0.updatePosition(p); - const tStart = this._references.length; - deletedTriangles = this._updateTriangles(v0, v0, deleted0, deletedTriangles); - deletedTriangles = this._updateTriangles(v0, v1, deleted1, deletedTriangles); - const tCount = this._references.length - tStart; - if (tCount <= v0.triangleCount) { - if (tCount) { - for (let c = 0; c < tCount; c++) { - this._references[v0.triangleStart + c] = this._references[tStart + c]; - } - } - } - else { - v0.triangleStart = tStart; - } - v0.triangleCount = tCount; - break; - } - } - }; - AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, trianglesIterator, callback, () => { - return triangleCount - deletedTriangles <= targetCount; - }); - }, 0); - }; - AsyncLoop.Run(this.decimationIterations, (loop) => { - if (triangleCount - deletedTriangles <= targetCount) { - loop.breakLoop(); - } - else { - iterationFunction(loop.index, () => { - loop.executeNext(); - }); - } - }, () => { - setTimeout(() => { - //reconstruct this part of the mesh - this._reconstructMesh(submeshIndex); - successCallback(); - }, 0); - }); - } - _initWithMesh(submeshIndex, callback, optimizeMesh) { - this._vertices = []; - this._triangles = []; - const positionData = this._mesh.getVerticesData(buffer_VertexBuffer.PositionKind); - const indices = this._mesh.getIndices(); - const submesh = this._mesh.subMeshes[submeshIndex]; - const findInVertices = (positionToSearch) => { - if (optimizeMesh) { - for (let ii = 0; ii < this._vertices.length; ++ii) { - if (this._vertices[ii].position.equalsWithEpsilon(positionToSearch, 0.0001)) { - return this._vertices[ii]; - } - } - } - return null; - }; - const vertexReferences = []; - const vertexInit = (i) => { - if (!positionData) { - return; - } - const offset = i + submesh.verticesStart; - const position = math_vector_Vector3.FromArray(positionData, offset * 3); - const vertex = findInVertices(position) || new DecimationVertex(position, this._vertices.length); - vertex.originalOffsets.push(offset); - if (vertex.id === this._vertices.length) { - this._vertices.push(vertex); - } - vertexReferences.push(vertex.id); - }; - //var totalVertices = mesh.getTotalVertices(); - const totalVertices = submesh.verticesCount; - AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, () => { - const indicesInit = (i) => { - if (!indices) { - return; - } - const offset = submesh.indexStart / 3 + i; - const pos = offset * 3; - const i0 = indices[pos + 0]; - const i1 = indices[pos + 1]; - const i2 = indices[pos + 2]; - const v0 = this._vertices[vertexReferences[i0 - submesh.verticesStart]]; - const v1 = this._vertices[vertexReferences[i1 - submesh.verticesStart]]; - const v2 = this._vertices[vertexReferences[i2 - submesh.verticesStart]]; - const triangle = new DecimationTriangle([v0, v1, v2]); - triangle.originalOffset = pos; - this._triangles.push(triangle); - }; - AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, this.syncIterations, indicesInit, () => { - this._init(callback); - }); - }); - } - _init(callback) { - const triangleInit1 = (i) => { - const t = this._triangles[i]; - t.normal = math_vector_Vector3.Cross(t._vertices[1].position.subtract(t._vertices[0].position), t._vertices[2].position.subtract(t._vertices[0].position)).normalize(); - for (let j = 0; j < 3; j++) { - t._vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -math_vector_Vector3.Dot(t.normal, t._vertices[0].position))); - } - }; - AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, triangleInit1, () => { - const triangleInit2 = (i) => { - const t = this._triangles[i]; - for (let j = 0; j < 3; ++j) { - t.error[j] = this._calculateError(t._vertices[j], t._vertices[(j + 1) % 3]); - } - t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]); - }; - AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, triangleInit2, () => { - callback(); - }); - }); - } - _reconstructMesh(submeshIndex) { - const newTriangles = []; - let i; - for (i = 0; i < this._vertices.length; ++i) { - this._vertices[i].triangleCount = 0; - } - let t; - let j; - for (i = 0; i < this._triangles.length; ++i) { - if (!this._triangles[i].deleted) { - t = this._triangles[i]; - for (j = 0; j < 3; ++j) { - t._vertices[j].triangleCount = 1; - } - newTriangles.push(t); - } - } - const newPositionData = (this._reconstructedMesh.getVerticesData(buffer_VertexBuffer.PositionKind) || []); - const newNormalData = (this._reconstructedMesh.getVerticesData(buffer_VertexBuffer.NormalKind) || []); - const newUVsData = (this._reconstructedMesh.getVerticesData(buffer_VertexBuffer.UVKind) || []); - const newColorsData = (this._reconstructedMesh.getVerticesData(buffer_VertexBuffer.ColorKind) || []); - const normalData = this._mesh.getVerticesData(buffer_VertexBuffer.NormalKind); - const uvs = this._mesh.getVerticesData(buffer_VertexBuffer.UVKind); - const colorsData = this._mesh.getVerticesData(buffer_VertexBuffer.ColorKind); - let vertexCount = 0; - for (i = 0; i < this._vertices.length; ++i) { - const vertex = this._vertices[i]; - vertex.id = vertexCount; - if (vertex.triangleCount) { - vertex.originalOffsets.forEach((originalOffset) => { - newPositionData.push(vertex.position.x); - newPositionData.push(vertex.position.y); - newPositionData.push(vertex.position.z); - if (normalData && normalData.length) { - newNormalData.push(normalData[originalOffset * 3]); - newNormalData.push(normalData[originalOffset * 3 + 1]); - newNormalData.push(normalData[originalOffset * 3 + 2]); - } - if (uvs && uvs.length) { - newUVsData.push(uvs[originalOffset * 2]); - newUVsData.push(uvs[originalOffset * 2 + 1]); - } - if (colorsData && colorsData.length) { - newColorsData.push(colorsData[originalOffset * 4]); - newColorsData.push(colorsData[originalOffset * 4 + 1]); - newColorsData.push(colorsData[originalOffset * 4 + 2]); - newColorsData.push(colorsData[originalOffset * 4 + 3]); - } - ++vertexCount; - }); - } - } - const startingIndex = this._reconstructedMesh.getTotalIndices(); - const startingVertex = this._reconstructedMesh.getTotalVertices(); - const submeshesArray = this._reconstructedMesh.subMeshes; - this._reconstructedMesh.subMeshes = []; - const newIndicesArray = this._reconstructedMesh.getIndices(); //[]; - const originalIndices = this._mesh.getIndices(); - for (i = 0; i < newTriangles.length; ++i) { - t = newTriangles[i]; //now get the new referencing point for each vertex - [0, 1, 2].forEach((idx) => { - const id = originalIndices[t.originalOffset + idx]; - let offset = t._vertices[idx].originalOffsets.indexOf(id); - if (offset < 0) { - offset = 0; - } - newIndicesArray.push(t._vertices[idx].id + offset + startingVertex); - }); - } - //overwriting the old vertex buffers and indices. - this._reconstructedMesh.setIndices(newIndicesArray); - this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.PositionKind, newPositionData); - if (newNormalData.length > 0) { - this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.NormalKind, newNormalData); - } - if (newUVsData.length > 0) { - this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.UVKind, newUVsData); - } - if (newColorsData.length > 0) { - this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.ColorKind, newColorsData); - } - //create submesh - const originalSubmesh = this._mesh.subMeshes[submeshIndex]; - if (submeshIndex > 0) { - this._reconstructedMesh.subMeshes = []; - submeshesArray.forEach((submesh) => { - subMesh_SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, - /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh()); - }); - subMesh_SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, - /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh); - } - } - _initDecimatedMesh() { - this._reconstructedMesh = new mesh_Mesh(this._mesh.name + "Decimated", this._mesh.getScene()); - this._reconstructedMesh.material = this._mesh.material; - this._reconstructedMesh.parent = this._mesh.parent; - this._reconstructedMesh.isVisible = false; - this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId; - } - _isFlipped(vertex1, vertex2, point, deletedArray, delTr) { - for (let i = 0; i < vertex1.triangleCount; ++i) { - const t = this._triangles[this._references[vertex1.triangleStart + i].triangleId]; - if (t.deleted) { - continue; - } - const s = this._references[vertex1.triangleStart + i].vertexId; - const v1 = t._vertices[(s + 1) % 3]; - const v2 = t._vertices[(s + 2) % 3]; - if (v1 === vertex2 || v2 === vertex2) { - deletedArray[i] = true; - delTr.push(t); - continue; - } - let d1 = v1.position.subtract(point); - d1 = d1.normalize(); - let d2 = v2.position.subtract(point); - d2 = d2.normalize(); - if (Math.abs(math_vector_Vector3.Dot(d1, d2)) > 0.999) { - return true; - } - const normal = math_vector_Vector3.Cross(d1, d2).normalize(); - deletedArray[i] = false; - if (math_vector_Vector3.Dot(normal, t.normal) < 0.2) { - return true; - } - } - return false; - } - _updateTriangles(origVertex, vertex, deletedArray, deletedTriangles) { - let newDeleted = deletedTriangles; - for (let i = 0; i < vertex.triangleCount; ++i) { - const ref = this._references[vertex.triangleStart + i]; - const t = this._triangles[ref.triangleId]; - if (t.deleted) { - continue; - } - if (deletedArray[i] && t.deletePending) { - t.deleted = true; - newDeleted++; - continue; - } - t._vertices[ref.vertexId] = origVertex; - t.isDirty = true; - t.error[0] = this._calculateError(t._vertices[0], t._vertices[1]) + t.borderFactor / 2; - t.error[1] = this._calculateError(t._vertices[1], t._vertices[2]) + t.borderFactor / 2; - t.error[2] = this._calculateError(t._vertices[2], t._vertices[0]) + t.borderFactor / 2; - t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]); - this._references.push(ref); - } - return newDeleted; - } - _identifyBorder() { - for (let i = 0; i < this._vertices.length; ++i) { - const vCount = []; - const vId = []; - const v = this._vertices[i]; - let j; - for (j = 0; j < v.triangleCount; ++j) { - const triangle = this._triangles[this._references[v.triangleStart + j].triangleId]; - for (let ii = 0; ii < 3; ii++) { - let ofs = 0; - const vv = triangle._vertices[ii]; - while (ofs < vCount.length) { - if (vId[ofs] === vv.id) { - break; - } - ++ofs; - } - if (ofs === vCount.length) { - vCount.push(1); - vId.push(vv.id); - } - else { - vCount[ofs]++; - } - } - } - for (j = 0; j < vCount.length; ++j) { - if (vCount[j] === 1) { - this._vertices[vId[j]].isBorder = true; - } - else { - this._vertices[vId[j]].isBorder = false; - } - } - } - } - _updateMesh(identifyBorders = false) { - let i; - if (!identifyBorders) { - const newTrianglesVector = []; - for (i = 0; i < this._triangles.length; ++i) { - if (!this._triangles[i].deleted) { - newTrianglesVector.push(this._triangles[i]); - } - } - this._triangles = newTrianglesVector; - } - for (i = 0; i < this._vertices.length; ++i) { - this._vertices[i].triangleCount = 0; - this._vertices[i].triangleStart = 0; - } - let t; - let j; - let v; - for (i = 0; i < this._triangles.length; ++i) { - t = this._triangles[i]; - for (j = 0; j < 3; ++j) { - v = t._vertices[j]; - v.triangleCount++; - } - } - let tStart = 0; - for (i = 0; i < this._vertices.length; ++i) { - this._vertices[i].triangleStart = tStart; - tStart += this._vertices[i].triangleCount; - this._vertices[i].triangleCount = 0; - } - const newReferences = new Array(this._triangles.length * 3); - for (i = 0; i < this._triangles.length; ++i) { - t = this._triangles[i]; - for (j = 0; j < 3; ++j) { - v = t._vertices[j]; - newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i); - v.triangleCount++; - } - } - this._references = newReferences; - if (identifyBorders) { - this._identifyBorder(); - } - } - _vertexError(q, point) { - const x = point.x; - const y = point.y; - const z = point.z; - return (q.data[0] * x * x + - 2 * q.data[1] * x * y + - 2 * q.data[2] * x * z + - 2 * q.data[3] * x + - q.data[4] * y * y + - 2 * q.data[5] * y * z + - 2 * q.data[6] * y + - q.data[7] * z * z + - 2 * q.data[8] * z + - q.data[9]); - } - _calculateError(vertex1, vertex2, pointResult) { - const q = vertex1.q.add(vertex2.q); - const border = vertex1.isBorder && vertex2.isBorder; - let error = 0; - const qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7); - if (qDet !== 0 && !border) { - if (!pointResult) { - pointResult = math_vector_Vector3.Zero(); - } - pointResult.x = (-1 / qDet) * q.det(1, 2, 3, 4, 5, 6, 5, 7, 8); - pointResult.y = (1 / qDet) * q.det(0, 2, 3, 1, 5, 6, 2, 7, 8); - pointResult.z = (-1 / qDet) * q.det(0, 1, 3, 1, 4, 6, 2, 5, 8); - error = this._vertexError(q, pointResult); - } - else { - const p3 = vertex1.position.add(vertex2.position).divide(new math_vector_Vector3(2, 2, 2)); - //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize(); - const error1 = this._vertexError(q, vertex1.position); - const error2 = this._vertexError(q, vertex2.position); - const error3 = this._vertexError(q, p3); - error = Math.min(error1, error2, error3); - if (error === error1) { - if (pointResult) { - pointResult.copyFrom(vertex1.position); - } - } - else if (error === error2) { - if (pointResult) { - pointResult.copyFrom(vertex2.position); - } - } - else { - if (pointResult) { - pointResult.copyFrom(p3); - } - } - } - return error; - } -} -//# sourceMappingURL=meshSimplification.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/meshSimplificationSceneComponent.js - - - - -Object.defineProperty(scene_Scene.prototype, "simplificationQueue", { - get: function () { - if (!this._simplificationQueue) { - this._simplificationQueue = new SimplificationQueue(); - let component = this._getComponent(sceneComponent_SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE); - if (!component) { - component = new SimplicationQueueSceneComponent(this); - this._addComponent(component); - } - } - return this._simplificationQueue; - }, - set: function (value) { - this._simplificationQueue = value; - }, - enumerable: true, - configurable: true, -}); -mesh_Mesh.prototype.simplify = function (settings, parallelProcessing = true, simplificationType = SimplificationType.QUADRATIC, successCallback) { - this.getScene().simplificationQueue.addTask({ - settings: settings, - parallelProcessing: parallelProcessing, - mesh: this, - simplificationType: simplificationType, - successCallback: successCallback, - }); - return this; -}; -/** - * Defines the simplification queue scene component responsible to help scheduling the various simplification task - * created in a scene - */ -class SimplicationQueueSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpfull to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE; - this.scene = scene; - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._beforeCameraUpdateStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing to do for this component - } - /** - * Disposes the component and the associated resources - */ - dispose() { - // Nothing to do for this component - } - _beforeCameraUpdate() { - if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) { - this.scene._simplificationQueue.executeNext(); - } - } -} -//# sourceMappingURL=meshSimplificationSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/greasedLineTools.js - - - - -/** - * Tool functions for GreasedLine - */ -class GreasedLineTools { - /** - * Omit zero length lines predicate for the MeshesToLines function - * @param p1 point1 position of the face - * @param p2 point2 position of the face - * @param p3 point3 position of the face - * @returns - */ - static OmitZeroLengthPredicate(p1, p2, p3) { - return p1.lengthSquared() === 0 && p2.lengthSquared() === 0 && p3.lengthSquared() === 0; - } - /** - * Gets mesh triangles as line positions - * @param meshes array of meshes - * @param predicate predicate function which decides whether to include the mesh triangle/face in the ouput - * @returns array of arrays of points - */ - static MeshesToLines(meshes, predicate) { - const points = []; - meshes.forEach((m, meshIndex) => { - const vertices = m.getVerticesData(buffer_VertexBuffer.PositionKind); - const indices = m.getIndices(); - if (vertices && indices) { - for (let i = 0, ii = 0; i < indices.length; i++) { - const vi1 = indices[ii++] * 3; - const vi2 = indices[ii++] * 3; - const vi3 = indices[ii++] * 3; - const p1 = new math_vector_Vector3(vertices[vi1], vertices[vi1 + 1], vertices[vi1 + 2]); - const p2 = new math_vector_Vector3(vertices[vi2], vertices[vi2 + 1], vertices[vi2 + 2]); - const p3 = new math_vector_Vector3(vertices[vi3], vertices[vi3 + 1], vertices[vi3 + 2]); - if (predicate) { - const pointsFromPredicate = predicate(p1, p2, p3, i, vi1, m, meshIndex, vertices, indices); - pointsFromPredicate && points.push(pointsFromPredicate); - } - else { - points.push([p1, p2, p3, p1]); - } - } - } - }); - return points; - } - /** - * Converts number coordinates to Vector3s - * @param points number array of x, y, z, x, y z, ... coordinates - * @returns Vector3 array - */ - static ToVector3Array(points) { - const array = []; - for (let i = 0; i < points.length; i += 3) { - array.push(new math_vector_Vector3(points[i], points[i + 1], points[i + 2])); - } - return array; - } - /** - * Gets a number array from a Vector3 array. - * You can you for example to convert your Vector3[] offsets to the required number[] for the offsets option. - * @param points Vector3 array - * @returns an array of x, y, z coordinates as numbers [x, y, z, x, y, z, x, y, z, ....] - */ - static ToNumberArray(points) { - return points.flatMap((v) => [v.x, v.y, v.z]); - } - /** - * Calculates the sum of points of every line and the number of points in each line. - * This function is useful when you are drawing multiple lines in one mesh and you want - * to know the counts. For example for creating an offsets table. - * @param points point array - * @returns points count info - */ - static GetPointsCountInfo(points) { - const counts = new Array(points.length); - let total = 0; - for (let n = points.length; n--;) { - counts[n] = points[n].length / 3; - total += counts[n]; - } - return { total, counts }; - } - /** - * Gets the length of the line counting all it's segments length - * @param data array of line points - * @returns length of the line - */ - static GetLineLength(data) { - if (data.length === 0) { - return 0; - } - let points; - if (typeof data[0] === "number") { - points = GreasedLineTools.ToVector3Array(data); - } - else { - points = data; - } - const tmp = math_vector_TmpVectors.Vector3[0]; - let length = 0; - for (let index = 0; index < points.length - 1; index++) { - const point1 = points[index]; - const point2 = points[index + 1]; - length += point2.subtractToRef(point1, tmp).length(); - } - return length; - } - /** - * Divides a segment into smaller segments. - * A segment is a part of the line between it's two points. - * @param point1 first point of the line - * @param point2 second point of the line - * @param segmentCount number of segments we want to have in the divided line - * @returns - */ - static SegmentizeSegmentByCount(point1, point2, segmentCount) { - const dividedLinePoints = []; - const diff = point2.subtract(point1); - const divisor = math_vector_TmpVectors.Vector3[0]; - divisor.setAll(segmentCount); - const segmentVector = math_vector_TmpVectors.Vector3[1]; - diff.divideToRef(divisor, segmentVector); - let nextPoint = point1.clone(); - dividedLinePoints.push(nextPoint); - for (let index = 0; index < segmentCount; index++) { - nextPoint = nextPoint.clone(); - dividedLinePoints.push(nextPoint.addInPlace(segmentVector)); - } - return dividedLinePoints; - } - /** - * Divides a line into segments. - * A segment is a part of the line between it's two points. - * @param what line points - * @param segmentLength length of each segment of the resulting line (distance between two line points) - * @returns line point - */ - static SegmentizeLineBySegmentLength(what, segmentLength) { - const subLines = what[0] instanceof math_vector_Vector3 ? GreasedLineTools.GetLineSegments(what) : what; - const points = []; - subLines.forEach((s) => { - if (s.length > segmentLength) { - const segments = GreasedLineTools.SegmentizeSegmentByCount(s.point1, s.point2, Math.ceil(s.length / segmentLength)); - segments.forEach((seg) => { - points.push(seg); - }); - } - else { - points.push(s.point1); - points.push(s.point2); - } - }); - return points; - } - /** - * Divides a line into segments. - * A segment is a part of the line between it's two points. - * @param what line points - * @param segmentCount number of segments - * @returns line point - */ - static SegmentizeLineBySegmentCount(what, segmentCount) { - const segmentLength = GreasedLineTools.GetLineLength(what) / segmentCount; - return GreasedLineTools.SegmentizeLineBySegmentLength(what, segmentLength); - } - /** - * Gets line segments. - * A segment is a part of the line between it's two points. - * @param points line points - * @returns segments information of the line segment including starting point, ending point and the distance between them - */ - static GetLineSegments(points) { - const segments = []; - for (let index = 0; index < points.length - 1; index++) { - const point1 = points[index]; - const point2 = points[index + 1]; - const length = point2.subtract(point1).length(); - segments.push({ point1, point2, length }); - } - return segments; - } - /** - * Gets the minimum and the maximum length of a line segment in the line. - * A segment is a part of the line between it's two points. - * @param points line points - * @returns - */ - static GetMinMaxSegmentLength(points) { - const subLines = GreasedLineTools.GetLineSegments(points); - const sorted = subLines.sort((s) => s.length); - return { - min: sorted[0].length, - max: sorted[sorted.length - 1].length, - }; - } - /** - * Finds the last visible position in world space of the line according to the visibility parameter - * @param lineSegments segments of the line - * @param lineLength total length of the line - * @param visbility normalized value of visibility - * @returns world space coordinate of the last visible piece of the line - */ - static GetPositionOnLineByVisibility(lineSegments, lineLength, visbility, localSpace = false) { - const lengthVisibilityRatio = lineLength * visbility; - let sumSegmentLengths = 0; - let segmentIndex = 0; - const lineSegmentsLength = lineSegments.length; - for (let i = 0; i < lineSegmentsLength; i++) { - if (lengthVisibilityRatio <= sumSegmentLengths + lineSegments[i].length) { - segmentIndex = i; - break; - } - sumSegmentLengths += lineSegments[i].length; - } - const s = (lengthVisibilityRatio - sumSegmentLengths) / lineSegments[segmentIndex].length; - lineSegments[segmentIndex].point2.subtractToRef(lineSegments[segmentIndex].point1, math_vector_TmpVectors.Vector3[0]); - math_vector_TmpVectors.Vector3[1] = math_vector_TmpVectors.Vector3[0].multiplyByFloats(s, s, s); - if (!localSpace) { - math_vector_TmpVectors.Vector3[1].addInPlace(lineSegments[segmentIndex].point1); - } - return math_vector_TmpVectors.Vector3[1].clone(); - } - /** - * Creates lines in a shape of circle/arc. - * A segment is a part of the line between it's two points. - * @param radiusX radiusX of the circle - * @param segments number of segments in the circle - * @param z z coordinate of the points. Defaults to 0. - * @param radiusY radiusY of the circle - you can draw an oval if using different values - * @param segmentAngle angle offset of the segments. Defaults to Math.PI * 2 / segments. Change this value to draw a part of the circle. - * @returns line points - */ - static GetCircleLinePoints(radiusX, segments, z = 0, radiusY = radiusX, segmentAngle = (Math.PI * 2) / segments) { - const points = []; - for (let i = 0; i <= segments; i++) { - points.push(new math_vector_Vector3(Math.cos(i * segmentAngle) * radiusX, Math.sin(i * segmentAngle) * radiusY, z)); - } - return points; - } - /** - * Gets line points in a shape of a bezier curve - * @param p0 bezier point0 - * @param p1 bezier point1 - * @param p2 bezier point2 - * @param segments number of segments in the curve - * @returns - */ - static GetBezierLinePoints(p0, p1, p2, segments) { - return Curve3.CreateQuadraticBezier(p0, p1, p2, segments) - .getPoints() - .flatMap((v) => [v.x, v.y, v.z]); - } - /** - * - * @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) - * @param direction direction which the arrow points to - * @param length length (size) of the arrow cap itself - * @param widthUp the arrow width above the line - * @param widthDown the arrow width belove the line - * @param widthStartUp the arrow width at the start of the arrow above the line. In most scenarios this is 0. - * @param widthStartDown the arrow width at the start of the arrow below the line. In most scenarios this is 0. - * @returns - */ - static GetArrowCap(position, direction, length, widthUp, widthDown, widthStartUp = 0, widthStartDown = 0) { - const points = [position.clone(), position.add(direction.multiplyByFloats(length, length, length))]; - const widths = [widthUp, widthDown, widthStartUp, widthStartDown]; - return { - points, - widths, - }; - } - /** - * Gets 3D positions of points from a text and font - * @param text Text - * @param size Size of the font - * @param resolution Resolution of the font - * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/) - * @param z z coordinate - * @param includeInner include the inner parts of the font in the result. Default true. If false, only the outlines will be returned. - * @returns number[][] of 3D positions - */ - static GetPointsFromText(text, size, resolution, fontData, z = 0, includeInner = true) { - const allPoints = []; - const shapePaths = CreateTextShapePaths(text, size, resolution, fontData); - for (const sp of shapePaths) { - for (const p of sp.paths) { - const points = []; - const points2d = p.getPoints(); - for (const p2d of points2d) { - points.push(p2d.x, p2d.y, z); - } - allPoints.push(points); - } - if (includeInner) { - for (const h of sp.holes) { - const holes = []; - const points2d = h.getPoints(); - for (const p2d of points2d) { - holes.push(p2d.x, p2d.y, z); - } - allPoints.push(holes); - } - } - } - return allPoints; - } -} -//# sourceMappingURL=greasedLineTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/greasedLine.fragment.js -// Do not edit. - -const greasedLine_fragment_name = "greasedLinePixelShader"; -const greasedLine_fragment_shader = `precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} -if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==1.) { -textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} -if (grlColorMode==0.) { -gl_FragColor=textureColor;} else if (grlColorMode==1.) { -gl_FragColor+=textureColor;} else if (grlColorMode==2.) { -gl_FragColor*=textureColor;}}} -`; -// Sideeffect -ShaderStore.ShadersStore[greasedLine_fragment_name] = greasedLine_fragment_shader; -/** @internal */ -const greasedLinePixelShader = { name: greasedLine_fragment_name, shader: greasedLine_fragment_shader }; -//# sourceMappingURL=greasedLine.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/greasedLine.vertex.js -// Do not edit. - -const greasedLine_vertex_name = "greasedLineVertexShader"; -const greasedLine_vertex_shader = `precision highp float;attribute vec4 grl_previousAndSide;attribute vec4 grl_nextAndCounters;attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;uniform mat4 worldViewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} -void main() {grlColorPointer=grl_colorPointers;float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=worldViewProjection;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );} -vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); -#ifdef GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM -grlNormal.xy*=-.5*grlWidth; -#else -grlNormal.xy*=.5*grlWidth; -#endif -grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} -grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;} -`; -// Sideeffect -ShaderStore.ShadersStore[greasedLine_vertex_name] = greasedLine_vertex_shader; -/** @internal */ -const greasedLineVertexShader = { name: greasedLine_vertex_name, shader: greasedLine_vertex_shader }; -//# sourceMappingURL=greasedLine.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/greasedLineSimpleMaterial.js - - - - - - - - -/** - * GreasedLineSimpleMaterial - */ -class greasedLineSimpleMaterial_GreasedLineSimpleMaterial extends shaderMaterial_ShaderMaterial { - /** - * GreasedLineSimple material constructor - * @param name material name - * @param scene the scene - * @param options material options - */ - constructor(name, scene, options) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o; - super(name, scene, { - vertex: "greasedLine", - fragment: "greasedLine", - }, { - attributes: ["position", "normal", "grl_previousAndSide", "grl_nextAndCounters", "grl_widths", "grl_offsets", "grl_colorPointers"], - uniforms: [ - "worldViewProjection", - "projection", - "grlColorsWidth", - "grlUseColors", - "grlWidth", - "grlColor", - "grl_colorModeAndColorDistributionType", - "grlResolution", - "grlAspect", - "grlAizeAttenuation", - "grlDashArray", - "grlDashOffset", - "grlDashRatio", - "grlUseDash", - "grlVisibility", - ], - samplers: ["grlColors"], - defines: scene.useRightHandedSystem ? ["GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM"] : [], - }); - this._color = math_color_Color3.White(); - this._colorsDistributionType = GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_SEGMENT; - options = options || { - color: greasedLineSimpleMaterial_GreasedLineSimpleMaterial.DEFAULT_COLOR, - }; - this._engine = scene.getEngine(); - this.visibility = (_a = options.visibility) !== null && _a !== void 0 ? _a : 1; - this.useDash = (_b = options.useDash) !== null && _b !== void 0 ? _b : false; - this.dashRatio = (_c = options.dashRatio) !== null && _c !== void 0 ? _c : 0.5; - this.dashOffset = (_d = options.dashOffset) !== null && _d !== void 0 ? _d : 0; - this.dashCount = (_e = options.dashCount) !== null && _e !== void 0 ? _e : 1; // calculate the _dashArray value, call the setter - this.width = options.width ? options.width : options.sizeAttenuation ? greasedLineSimpleMaterial_GreasedLineSimpleMaterial.DEFAULT_WIDTH_ATTENUATED : greasedLineSimpleMaterial_GreasedLineSimpleMaterial.DEFAULT_WIDTH; - this.sizeAttenuation = (_f = options.sizeAttenuation) !== null && _f !== void 0 ? _f : false; - this.color = (_g = options.color) !== null && _g !== void 0 ? _g : math_color_Color3.White(); - this.useColors = (_h = options.useColors) !== null && _h !== void 0 ? _h : false; - this.colorsDistributionType = (_j = options.colorDistributionType) !== null && _j !== void 0 ? _j : GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_SEGMENT; - this.colorsSampling = (_k = options.colorsSampling) !== null && _k !== void 0 ? _k : rawTexture_RawTexture.NEAREST_NEAREST; - this.colorMode = (_l = options.colorMode) !== null && _l !== void 0 ? _l : GreasedLineMeshColorMode.COLOR_MODE_SET; - this._colors = (_m = options.colors) !== null && _m !== void 0 ? _m : null; - this.resolution = (_o = options.resolution) !== null && _o !== void 0 ? _o : new math_vector_Vector2(this._engine.getRenderWidth(), this._engine.getRenderHeight()); // calculate aspect call the setter - if (this._colors) { - this.setColors(this._colors); - } - this._engine.onDisposeObservable.add(() => { - var _a; - (_a = greasedLineSimpleMaterial_GreasedLineSimpleMaterial._EmptyColorsTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - }); - } - /** - * Converts boolean to number. - * @param bool - * @returns 1 if true, 0 if false. - */ - static _BooleanToNumber(bool) { - return bool ? 1 : 0; - } - /** - * Converts an array of Color3 to Uint8Array - * @param colors Arrray of Color3 - * @returns Uin8Array of colors [r, g, b, a, r, g, b, a, ...] - */ - static _Color3toRGBAUint8(colors) { - const colorTable = new Uint8Array(colors.length * 4); - for (let i = 0, j = 0; i < colors.length; i++) { - colorTable[j++] = colors[i].r * 255; - colorTable[j++] = colors[i].g * 255; - colorTable[j++] = colors[i].b * 255; - colorTable[j++] = 255; - } - return colorTable; - } - /** - * Creates a RawTexture from an RGBA color array and sets it on the plugin material instance. - * @param name name of the texture - * @param colors Uint8Array of colors - */ - _createColorsTexture(name, colors) { - const colorsArray = greasedLineSimpleMaterial_GreasedLineSimpleMaterial._Color3toRGBAUint8(colors); - this._colorsTexture = new rawTexture_RawTexture(colorsArray, colors.length, 1, engine_Engine.TEXTUREFORMAT_RGBA, this.getScene(), false, true, this._colorsSampling); - this._colorsTexture.name = name; - } - /** - * Disposes the plugin material. - */ - dispose() { - var _a; - (_a = this._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - super.dispose(); - } - _setColorModeAndColorDistributionType() { - this.setVector2("grl_colorModeAndColorDistributionType", new math_vector_Vector2(this._colorMode, this._colorsDistributionType)); - } - /** - * Updates the material. Use when material created in lazy mode. - */ - updateLazy() { - if (this._colors) { - this.setColors(this._colors, false, true); - } - } - /** - * Returns the colors used to colorize the line - */ - get colors() { - return this._colors; - } - /** - * Sets the colors used to colorize the line - */ - set colors(value) { - this.setColors(value); - } - /** - * Creates or updates the colors texture - * @param colors color table RGBA - * @param lazy if lazy, the colors are not updated - * @param forceNewTexture force creation of a new texture - * @returns - */ - setColors(colors, lazy = false, forceNewTexture = false) { - var _a, _b, _c, _d; - const origColorsCount = (_b = (_a = this._colors) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0; - this._colors = colors; - if (colors === null || colors.length === 0) { - (_c = this._colorsTexture) === null || _c === void 0 ? void 0 : _c.dispose(); - return; - } - if (lazy && !forceNewTexture) { - return; - } - if (this._colorsTexture && origColorsCount === colors.length && !forceNewTexture) { - const colorArray = greasedLineSimpleMaterial_GreasedLineSimpleMaterial._Color3toRGBAUint8(colors); - this._colorsTexture.update(colorArray); - } - else { - (_d = this._colorsTexture) === null || _d === void 0 ? void 0 : _d.dispose(); - this._createColorsTexture(`${this.name}-colors-texture`, colors); - } - if (this._colorsTexture) { - this.setFloat("grlColorsWidth", this._colorsTexture.getSize().width); - this.setTexture("grlColors", this._colorsTexture); - } - } - /** - * Line base width. At each point the line width is calculated by widths[pointIndex] * width - */ - get width() { - return this._width; - } - /** - * Line base width. At each point the line width is calculated by widths[pointIndex] * width - */ - set width(value) { - this._width = value; - this.setFloat("grlWidth", value); - } - /** - * Whether to use the colors option to colorize the line - */ - get useColors() { - return this._useColors; - } - set useColors(value) { - this._useColors = value; - this.setFloat("grlUseColors", greasedLineSimpleMaterial_GreasedLineSimpleMaterial._BooleanToNumber(value)); - } - /** - * The type of sampling of the colors texture. The values are the same when using with textures. - */ - get colorsSampling() { - return this._colorsSampling; - } - /** - * The type of sampling of the colors texture. The values are the same when using with textures. - */ - set colorsSampling(value) { - this._colorsSampling = value; - } - /** - * Normalized value of how much of the line will be visible - * 0 - 0% of the line will be visible - * 1 - 100% of the line will be visible - */ - get visibility() { - return this._visibility; - } - set visibility(value) { - this._visibility = value; - this.setFloat("grlVisibility", value); - } - /** - * Turns on/off dash mode - */ - get useDash() { - return this._useDash; - } - /** - * Turns on/off dash mode - */ - set useDash(value) { - this._useDash = value; - this.setFloat("grlUseDash", greasedLineSimpleMaterial_GreasedLineSimpleMaterial._BooleanToNumber(value)); - } - /** - * Gets the dash offset - */ - get dashOffset() { - return this._dashOffset; - } - /** - * Sets the dash offset - */ - set dashOffset(value) { - this._dashOffset = value; - this.setFloat("grlDashOffset", value); - } - /** - * Length of the dash. 0 to 1. 0.5 means half empty, half drawn. - */ - get dashRatio() { - return this._dashRatio; - } - /** - * Length of the dash. 0 to 1. 0.5 means half empty, half drawn. - */ - set dashRatio(value) { - this._dashRatio = value; - this.setFloat("grlDashRatio", value); - } - /** - * Gets the number of dashes in the line - */ - get dashCount() { - return this._dashCount; - } - /** - * Sets the number of dashes in the line - * @param value dash - */ - set dashCount(value) { - this._dashCount = value; - this._dashArray = 1 / value; - this.setFloat("grlDashArray", this._dashArray); - } - /** - * 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 - */ - get sizeAttenuation() { - return this._sizeAttenuation; - } - /** - * Turn on/off attenuation of the width option and widths array. - * @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 - */ - set sizeAttenuation(value) { - this._sizeAttenuation = value; - this.setFloat("grlSizeAttenuation", greasedLineSimpleMaterial_GreasedLineSimpleMaterial._BooleanToNumber(value)); - } - /** - * Gets the color of the line - */ - get color() { - return this.color; - } - /** - * Sets the color of the line - * @param value Color3 - */ - set color(value) { - this.setColor(value); - } - /** - * Sets the color of the line. If set the whole line will be mixed with this color according to the colorMode option. - * The simple material always needs a color to be set. If you set it to null it will set the color to the default color (GreasedLineSimpleMaterial.DEFAULT_COLOR). - * @param value color - */ - setColor(value) { - value = value !== null && value !== void 0 ? value : greasedLineSimpleMaterial_GreasedLineSimpleMaterial.DEFAULT_COLOR; - this._color = value; - this.setColor3("grlColor", value); - } - /** - * Gets the color distributiopn type - */ - get colorsDistributionType() { - return this._colorsDistributionType; - } - /** - * Sets the color distribution type - * @see GreasedLineMeshColorDistributionType - * @param value color distribution type - */ - set colorsDistributionType(value) { - this._colorsDistributionType = value; - this._setColorModeAndColorDistributionType(); - } - /** - * Gets the mixing mode of the color and colors paramaters. Default value is GreasedLineMeshColorMode.SET. - * MATERIAL_TYPE_SIMPLE mixes the color and colors of the greased line material. - * @see GreasedLineMeshColorMode - */ - get colorMode() { - return this._colorMode; - } - /** - * Sets the mixing mode of the color and colors paramaters. Default value is GreasedLineMeshColorMode.SET. - * MATERIAL_TYPE_SIMPLE mixes the color and colors of the greased line material. - * @see GreasedLineMeshColorMode - */ - set colorMode(value) { - this._colorMode = value; - this._setColorModeAndColorDistributionType(); - } - /** - * Gets the resolution - */ - get resolution() { - return this._resolution; - } - /** - * Sets the resolution - * @param value resolution of the screen for GreasedLine - */ - set resolution(value) { - this._resolution = value; - this.setVector2("grlResolution", value); - this.setFloat("grlAspect", value.x / value.y); - } - /** - * Serializes this plugin material - * @returns serializationObjec - */ - serialize() { - const serializationObject = super.serialize(); - const greasedLineMaterialOptions = { - colorDistributionType: this._colorsDistributionType, - colorsSampling: this._colorsSampling, - colorMode: this._colorMode, - color: this._color, - dashCount: this._dashCount, - dashOffset: this._dashOffset, - dashRatio: this._dashRatio, - resolution: this._resolution, - sizeAttenuation: this._sizeAttenuation, - useColors: this._useColors, - useDash: this._useDash, - visibility: this._visibility, - width: this._width, - }; - this._colors && (greasedLineMaterialOptions.colors = this._colors); - serializationObject.greasedLineMaterialOptions = greasedLineMaterialOptions; - return serializationObject; - } - /** - * Parses a serialized objects - * @param source serialized object - * @param scene scene - * @param _rootUrl root url for textures - */ - parse(source, scene, _rootUrl) { - var _a; - // TODO: super.parse? - const greasedLineMaterialOptions = source.greasedLineMaterialOptions; - (_a = this._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - if (greasedLineMaterialOptions.colors) { - this._createColorsTexture(`${this.name}-colors-texture`, greasedLineMaterialOptions.colors); - } - else { - greasedLineSimpleMaterial_GreasedLineSimpleMaterial._PrepareEmptyColorsTexture(scene); - } - greasedLineMaterialOptions.color && (this.color = greasedLineMaterialOptions.color); - greasedLineMaterialOptions.colorDistributionType && (this.colorsDistributionType = greasedLineMaterialOptions.colorDistributionType); - greasedLineMaterialOptions.colorsSampling && (this.colorsSampling = greasedLineMaterialOptions.colorsSampling); - greasedLineMaterialOptions.colorMode && (this.colorMode = greasedLineMaterialOptions.colorMode); - greasedLineMaterialOptions.useColors && (this.useColors = greasedLineMaterialOptions.useColors); - greasedLineMaterialOptions.visibility && (this.visibility = greasedLineMaterialOptions.visibility); - greasedLineMaterialOptions.useDash && (this.useDash = greasedLineMaterialOptions.useDash); - greasedLineMaterialOptions.dashCount && (this.dashCount = greasedLineMaterialOptions.dashCount); - greasedLineMaterialOptions.dashRatio && (this.dashRatio = greasedLineMaterialOptions.dashRatio); - greasedLineMaterialOptions.dashOffset && (this.dashOffset = greasedLineMaterialOptions.dashOffset); - greasedLineMaterialOptions.width && (this.width = greasedLineMaterialOptions.width); - greasedLineMaterialOptions.sizeAttenuation && (this.sizeAttenuation = greasedLineMaterialOptions.sizeAttenuation); - greasedLineMaterialOptions.resolution && (this.resolution = greasedLineMaterialOptions.resolution); - } - /** - * A minimum size texture for the colors sampler2D when there is no colors texture defined yet. - * For fast switching using the useColors property without the need to use defines. - * @param scene Scene - */ - static _PrepareEmptyColorsTexture(scene) { - if (!this._EmptyColorsTexture) { - const colorsArray = new Uint8Array(4); - greasedLineSimpleMaterial_GreasedLineSimpleMaterial._EmptyColorsTexture = new rawTexture_RawTexture(colorsArray, 1, 1, engine_Engine.TEXTUREFORMAT_RGBA, scene, false, false, rawTexture_RawTexture.NEAREST_NEAREST); - greasedLineSimpleMaterial_GreasedLineSimpleMaterial._EmptyColorsTexture.name = "grlEmptyColorsTexture"; - } - } -} -/** - * Default line color for newly created lines - */ -greasedLineSimpleMaterial_GreasedLineSimpleMaterial.DEFAULT_COLOR = math_color_Color3.White(); -/** - * Default line width when sizeAttenuation is true - */ -greasedLineSimpleMaterial_GreasedLineSimpleMaterial.DEFAULT_WIDTH_ATTENUATED = 1; -/** - * Defaule line width - */ -greasedLineSimpleMaterial_GreasedLineSimpleMaterial.DEFAULT_WIDTH = 0.1; -//# sourceMappingURL=greasedLineSimpleMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/greasedLineMesh.js - - - - - - - - - -mesh_Mesh._GreasedLineMeshParser = (parsedMesh, scene) => { - return greasedLineMesh_GreasedLineMesh.Parse(parsedMesh, scene); -}; -/** - * GreasedLine - */ -class greasedLineMesh_GreasedLineMesh extends mesh_Mesh { - constructor(name, scene, _options) { - var _a, _b, _c, _d; - super(name, scene, null, null, false, false); - this.name = name; - this._options = _options; - this._lazy = false; - this._updatable = false; - /** - * Treshold used to pick the mesh - */ - this.intersectionThreshold = 0.1; - this._lazy = (_a = _options.lazy) !== null && _a !== void 0 ? _a : false; - this._updatable = (_b = _options.updatable) !== null && _b !== void 0 ? _b : false; - this._vertexPositions = []; - this._indices = []; - this._uvs = []; - this._points = []; - this._colorPointers = (_c = _options.colorPointers) !== null && _c !== void 0 ? _c : []; - this._widths = (_d = _options.widths) !== null && _d !== void 0 ? _d : new Array(_options.points.length).fill(1); - this._previousAndSide = []; - this._nextAndCounters = []; - if (_options.points) { - this.addPoints(greasedLineMesh_GreasedLineMesh.ConvertPoints(_options.points)); - } - } - /** - * "GreasedLineMesh" - * @returns "GreasedLineMesh" - */ - getClassName() { - return "GreasedLineMesh"; - } - /** - * Converts GreasedLinePoints to number[][] - * @param points GreasedLinePoints - * @returns number[][] with x, y, z coordinates of the points, like [[x, y, z, x, y, z, ...], [x, y, z, ...]] - */ - static ConvertPoints(points) { - if (points.length && Array.isArray(points) && typeof points[0] === "number") { - return [points]; - } - else if (points.length && Array.isArray(points[0]) && typeof points[0][0] === "number") { - return points; - } - else if (points.length && !Array.isArray(points[0]) && points[0] instanceof math_vector_Vector3) { - const positions = []; - for (let j = 0; j < points.length; j++) { - const p = points[j]; - positions.push(p.x, p.y, p.z); - } - return [positions]; - } - else if (points.length > 0 && Array.isArray(points[0]) && points[0].length > 0 && points[0][0] instanceof math_vector_Vector3) { - const positions = []; - const vectorPoints = points; - vectorPoints.forEach((p) => { - positions.push(p.flatMap((p2) => [p2.x, p2.y, p2.z])); - }); - return positions; - } - else if (points instanceof Float32Array) { - return [Array.from(points)]; - } - else if (points.length && points[0] instanceof Float32Array) { - const positions = []; - points.forEach((p) => { - positions.push(Array.from(p)); - }); - return positions; - } - return []; - } - /** - * Updated a lazy line. Rerenders the line and updates boundinfo as well. - */ - updateLazy() { - var _a; - this._setPoints(this._points); - if (!this._options.colorPointers) { - this._updateColorPointers(); - } - this._createVertexBuffers(); - this.refreshBoundingInfo(); - (_a = this.greasedLineMaterial) === null || _a === void 0 ? void 0 : _a.updateLazy(); - } - /** - * Dispose the line and it's resources - */ - dispose() { - super.dispose(); - } - /** - * - * @returns true if the mesh was created in lazy mode - */ - isLazy() { - return this._lazy; - } - /** - * Return the the points offsets - */ - get offsets() { - return this._offsets; - } - /** - * Sets point offests - * @param offsets offset table [x,y,z, x,y,z, ....] - */ - set offsets(offsets) { - this._offsets = offsets; - if (!this._offsetsBuffer) { - this._createOffsetsBuffer(offsets); - } - else { - this._offsetsBuffer && this._offsetsBuffer.update(offsets); - } - } - /** - * Gets widths at each line point like [widthLower, widthUpper, widthLower, widthUpper, ...] - */ - get widths() { - return this._widths; - } - /** - * Sets widths at each line point - * @param widths width table [widthLower, widthUpper, widthLower, widthUpper ...] - */ - set widths(widths) { - this._widths = widths; - if (!this._lazy) { - this._widthsBuffer && this._widthsBuffer.update(widths); - } - } - /** - * Gets the color pointer. Each vertex need a color pointer. These color pointers points to the colors in the color table @see colors - */ - get colorPointers() { - return this._colorPointers; - } - /** - * Sets the color pointer - * @param colorPointers array of color pointer in the colors array. One pointer for every vertex is needed. - */ - set colorPointers(colorPointers) { - this._colorPointers = colorPointers; - if (!this._lazy) { - this._colorPointersBuffer && this._colorPointersBuffer.update(colorPointers); - } - } - /** - * Gets the pluginMaterial associated with line - */ - get greasedLineMaterial() { - var _a, _b; - if (this.material && this.material instanceof greasedLineSimpleMaterial_GreasedLineSimpleMaterial) { - return this.material; - } - const materialPlugin = (_b = (_a = this.material) === null || _a === void 0 ? void 0 : _a.pluginManager) === null || _b === void 0 ? void 0 : _b.getPlugin(greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME); - if (materialPlugin) { - return materialPlugin; - } - return; - } - /** - * Return copy the points. - */ - get points() { - const pointsCopy = []; - DeepCopier.DeepCopy(this._points, pointsCopy); - return pointsCopy; - } - /** - * Adds new points to the line. It doesn't rerenders the line if in lazy mode. - * @param points points table - */ - addPoints(points) { - for (const p of points) { - this._points.push(p); - } - if (!this._lazy) { - this.setPoints(this._points); - } - } - _updateColorPointers() { - let colorPointer = 0; - this._colorPointers = []; - this._points.forEach((p) => { - for (let jj = 0; jj < p.length; jj += 3) { - this._colorPointers.push(colorPointer); - this._colorPointers.push(colorPointer++); - } - }); - } - _updateWidths() { - let pointCount = 0; - for (const points of this._points) { - pointCount += points.length; - } - const countDiff = (pointCount / 3) * 2 - this._widths.length; - for (let i = 0; i < countDiff; i++) { - this._widths.push(1); - } - } - /** - * Sets line points and rerenders the line. - * @param points points table - */ - setPoints(points) { - this._points = points; - this._updateWidths(); - this._updateColorPointers(); - this._setPoints(points); - } - _setPoints(points) { - this._points = points; - this._options.points = points; - this._initGreasedLine(); - let indiceOffset = 0; - points.forEach((p) => { - var _a; - const counters = []; - const positions = []; - const indices = []; - const totalLength = GreasedLineTools.GetLineLength(p); - for (let j = 0, jj = 0; jj < p.length; j++, jj += 3) { - const partialLine = p.slice(0, jj + 3); - const partialLineLength = GreasedLineTools.GetLineLength(partialLine); - const c = partialLineLength / totalLength; - positions.push(p[jj], p[jj + 1], p[jj + 2]); - positions.push(p[jj], p[jj + 1], p[jj + 2]); - counters.push(c); - counters.push(c); - if (jj < p.length - 3) { - const n = j * 2 + indiceOffset; - indices.push(n, n + 1, n + 2); - indices.push(n + 2, n + 1, n + 3); - } - } - indiceOffset += (p.length / 3) * 2; - const previous = []; - const next = []; - const side = []; - let uvs = []; - this._preprocess(positions, previous, next, side, uvs); - for (const vp of positions) { - this._vertexPositions.push(vp); - } - for (const i of indices) { - this._indices.push(i); - } - for (let i = 0; i < side.length; i++) { - this._previousAndSide.push(previous[i * 3], previous[i * 3 + 1], previous[i * 3 + 2], side[i]); - this._nextAndCounters.push(next[i * 3], next[i * 3 + 1], next[i * 3 + 2], counters[i]); - } - uvs = (_a = this._options.uvs) !== null && _a !== void 0 ? _a : uvs; - for (const uv of uvs) { - this._uvs.push(uv); - } - }); - if (!this._lazy) { - if (!this._options.colorPointers) { - this._updateColorPointers(); - } - this._createVertexBuffers(); - this.refreshBoundingInfo(); - } - } - _createLineOptions() { - const lineOptions = { - points: this._points, - colorPointers: this._colorPointers, - lazy: this._lazy, - updatable: this._updatable, - uvs: this._uvs, - widths: this._widths, - }; - return lineOptions; - } - /** - * Clones the GreasedLineMesh. - * @param name new line name - * @param newParent new parent node - * @returns cloned line - */ - clone(name = `${this.name}-cloned`, newParent) { - const lineOptions = this._createLineOptions(); - const deepCopiedLineOptions = {}; - DeepCopier.DeepCopy(lineOptions, deepCopiedLineOptions, ["instance"]); - const cloned = new greasedLineMesh_GreasedLineMesh(name, this._scene, deepCopiedLineOptions); - if (newParent) { - cloned.parent = newParent; - } - cloned.material = this.material; - return cloned; - } - /** - * Serializes this GreasedLineMesh - * @param serializationObject object to write serialization to - */ - serialize(serializationObject) { - super.serialize(serializationObject); - serializationObject.type = this.getClassName(); - serializationObject.lineOptions = this._createLineOptions(); - } - /** - * Parses a serialized GreasedLineMesh - * @param parsedMesh the serialized GreasedLineMesh - * @param scene the scene to create the GreasedLineMesh in - * @returns the created GreasedLineMesh - */ - static Parse(parsedMesh, scene) { - const lineOptions = parsedMesh.lineOptions; - const name = parsedMesh.name; - const result = new greasedLineMesh_GreasedLineMesh(name, scene, lineOptions); - return result; - } - /** - * Checks whether a ray is intersecting this GreasedLineMesh - * @param ray ray to check the intersection of this mesh with - * @param fastCheck not supported - * @param trianglePredicate not supported - * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default) - * @param worldToUse not supported - * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check - * @returns the picking info - */ - intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) { - const pickingInfo = new PickingInfo(); - const intersections = this.findAllIntersections(ray, fastCheck, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo, true); - if ((intersections === null || intersections === void 0 ? void 0 : intersections.length) === 1) { - const intersection = intersections[0]; - pickingInfo.hit = true; - pickingInfo.distance = intersection.distance; - pickingInfo.ray = ray; - pickingInfo.pickedMesh = this; - pickingInfo.pickedPoint = intersection.point; - } - return pickingInfo; - } - /** - * Gets all intersections of a ray and the line - * @param ray Ray to check the intersection of this mesh with - * @param _fastCheck not supported - * @param _trianglePredicate not supported - * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default) - * @param _worldToUse not supported - * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check - * @param firstOnly If true, the first and only intersection is immediatelly returned if found - * @returns intersection(s) - */ - findAllIntersections(ray, _fastCheck, _trianglePredicate, onlyBoundingInfo = false, _worldToUse, skipBoundingInfo = false, firstOnly = false) { - var _a, _b; - if (onlyBoundingInfo && !skipBoundingInfo && ray.intersectsSphere(this._boundingSphere, this.intersectionThreshold) === false) { - return; - } - const indices = this.getIndices(); - const positions = this.getVerticesData(buffer_VertexBuffer.PositionKind); - const widths = this._widths; - const lineWidth = (_b = (_a = this.greasedLineMaterial) === null || _a === void 0 ? void 0 : _a.width) !== null && _b !== void 0 ? _b : 1; - const intersects = []; - if (indices && positions && widths) { - let i = 0, l = 0; - for (i = 0, l = indices.length - 1; i < l; i += 3) { - const a = indices[i]; - const b = indices[i + 1]; - greasedLineMesh_GreasedLineMesh._V_START.fromArray(positions, a * 3); - greasedLineMesh_GreasedLineMesh._V_END.fromArray(positions, b * 3); - if (this._offsets) { - greasedLineMesh_GreasedLineMesh._V_OFFSET_START.fromArray(this._offsets, a * 3); - greasedLineMesh_GreasedLineMesh._V_OFFSET_END.fromArray(this._offsets, b * 3); - greasedLineMesh_GreasedLineMesh._V_START.addInPlace(greasedLineMesh_GreasedLineMesh._V_OFFSET_START); - greasedLineMesh_GreasedLineMesh._V_END.addInPlace(greasedLineMesh_GreasedLineMesh._V_OFFSET_END); - } - const iFloored = Math.floor(i / 3); - const width = widths[iFloored] !== undefined ? widths[iFloored] : 1; - const precision = (this.intersectionThreshold * (lineWidth * width)) / 2; - const distance = ray.intersectionSegment(greasedLineMesh_GreasedLineMesh._V_START, greasedLineMesh_GreasedLineMesh._V_END, precision); - if (distance !== -1) { - intersects.push({ - distance: distance, - point: ray.direction.normalize().multiplyByFloats(distance, distance, distance).add(ray.origin), - }); - if (firstOnly) { - return intersects; - } - } - } - i = l; - } - return intersects; - } - _initGreasedLine() { - this._vertexPositions = []; - this._previousAndSide = []; - this._nextAndCounters = []; - this._indices = []; - this._uvs = []; - } - get _boundingSphere() { - return this.getBoundingInfo().boundingSphere; - } - static _CompareV3(positionIdx1, positionIdx2, positions) { - const arrayIdx1 = positionIdx1 * 6; - const arrayIdx2 = positionIdx2 * 6; - return positions[arrayIdx1] === positions[arrayIdx2] && positions[arrayIdx1 + 1] === positions[arrayIdx2 + 1] && positions[arrayIdx1 + 2] === positions[arrayIdx2 + 2]; - } - static _CopyV3(positionIdx, positions) { - const arrayIdx = positionIdx * 6; - return [positions[arrayIdx], positions[arrayIdx + 1], positions[arrayIdx + 2]]; - } - _preprocess(positions, previous, next, side, uvs) { - const l = positions.length / 6; - let v = []; - if (greasedLineMesh_GreasedLineMesh._CompareV3(0, l - 1, positions)) { - v = greasedLineMesh_GreasedLineMesh._CopyV3(l - 2, positions); - } - else { - v = greasedLineMesh_GreasedLineMesh._CopyV3(0, positions); - } - previous.push(v[0], v[1], v[2]); - previous.push(v[0], v[1], v[2]); - for (let j = 0; j < l; j++) { - side.push(1); - side.push(-1); - // uvs - if (!this._options.uvs) { - uvs.push(j / (l - 1), 0); - uvs.push(j / (l - 1), 1); - } - if (j < l - 1) { - v = greasedLineMesh_GreasedLineMesh._CopyV3(j, positions); - previous.push(v[0], v[1], v[2]); - previous.push(v[0], v[1], v[2]); - } - if (j > 0) { - v = greasedLineMesh_GreasedLineMesh._CopyV3(j, positions); - next.push(v[0], v[1], v[2]); - next.push(v[0], v[1], v[2]); - } - } - if (greasedLineMesh_GreasedLineMesh._CompareV3(l - 1, 0, positions)) { - v = greasedLineMesh_GreasedLineMesh._CopyV3(1, positions); - } - else { - v = greasedLineMesh_GreasedLineMesh._CopyV3(l - 1, positions); - } - next.push(v[0], v[1], v[2]); - next.push(v[0], v[1], v[2]); - return { - previous, - next, - uvs, - side, - }; - } - _createVertexBuffers() { - const vertexData = new mesh_vertexData_VertexData(); - vertexData.positions = this._vertexPositions; - vertexData.indices = this._indices; - vertexData.uvs = this._uvs; - vertexData.applyToMesh(this, this._options.updatable); - const engine = this._scene.getEngine(); - const previousAndSideBuffer = new Buffer(engine, this._previousAndSide, false, 4); - this.setVerticesBuffer(previousAndSideBuffer.createVertexBuffer("grl_previousAndSide", 0, 4)); - const nextAndCountersBuffer = new Buffer(engine, this._nextAndCounters, false, 4); - this.setVerticesBuffer(nextAndCountersBuffer.createVertexBuffer("grl_nextAndCounters", 0, 4)); - const widthBuffer = new Buffer(engine, this._widths, this._updatable, 1); - this.setVerticesBuffer(widthBuffer.createVertexBuffer("grl_widths", 0, 1)); - this._widthsBuffer = widthBuffer; - const colorPointersBuffer = new Buffer(engine, this._colorPointers, this._updatable, 1); - this.setVerticesBuffer(colorPointersBuffer.createVertexBuffer("grl_colorPointers", 0, 1)); - this._colorPointersBuffer = colorPointersBuffer; - } - _createOffsetsBuffer(offsets) { - const engine = this._scene.getEngine(); - const offsetBuffer = new Buffer(engine, offsets, this._updatable, 3); - this.setVerticesBuffer(offsetBuffer.createVertexBuffer("grl_offsets", 0, 3)); - this._offsetsBuffer = offsetBuffer; - } -} -greasedLineMesh_GreasedLineMesh._V_START = new math_vector_Vector3(); -greasedLineMesh_GreasedLineMesh._V_END = new math_vector_Vector3(); -greasedLineMesh_GreasedLineMesh._V_OFFSET_START = new math_vector_Vector3(); -greasedLineMesh_GreasedLineMesh._V_OFFSET_END = new math_vector_Vector3(); -//# sourceMappingURL=greasedLineMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/greasedLineBuilder.js - - - - - - -/** - * How are the colors distributed along the color table - * {@link https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/greased_line#colors-and-colordistribution} - */ -var GreasedLineMeshColorDistribution; -(function (GreasedLineMeshColorDistribution) { - /** - * Do no modify the color table - */ - GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_NONE"] = 0] = "COLOR_DISTRIBUTION_NONE"; - /** - * Repeat the colors until the color table is full - */ - GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_REPEAT"] = 1] = "COLOR_DISTRIBUTION_REPEAT"; - /** - * Distribute the colors evenly through the color table - */ - GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_EVEN"] = 2] = "COLOR_DISTRIBUTION_EVEN"; - /** - * Put the colors to start of the color table a fill the rest with the default color - */ - GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_START"] = 3] = "COLOR_DISTRIBUTION_START"; - /** - * Put the colors to the end of the color table and fill the rest with the default color - */ - GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_END"] = 4] = "COLOR_DISTRIBUTION_END"; - /** - * Put the colors to start and to the end of the color table and fill the gap between with the default color - */ - GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution["COLOR_DISTRIBUTION_START_END"] = 5] = "COLOR_DISTRIBUTION_START_END"; -})(GreasedLineMeshColorDistribution || (GreasedLineMeshColorDistribution = {})); -/** - * How are the widths distributed along the width table - * {@link https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/greased_line#widths-and-widthdistribution} - */ -var GreasedLineMeshWidthDistribution; -(function (GreasedLineMeshWidthDistribution) { - /** - * Do no modify the width table - */ - GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_NONE"] = 0] = "WIDTH_DISTRIBUTION_NONE"; - /** - * Repeat the widths until the width table is full - */ - GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_REPEAT"] = 1] = "WIDTH_DISTRIBUTION_REPEAT"; - /** - * Distribute the widths evenly through the width table - */ - GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_EVEN"] = 2] = "WIDTH_DISTRIBUTION_EVEN"; - /** - * Put the widths to start of the width table a fill the rest with the default width - */ - GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_START"] = 3] = "WIDTH_DISTRIBUTION_START"; - /** - * Put the widths to the end of the width table and fill the rest with the default width - */ - GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_END"] = 4] = "WIDTH_DISTRIBUTION_END"; - /** - * Put the widths to start and to the end of the width table and fill the gap between with the default width - */ - GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution["WIDTH_DISTRIBUTION_START_END"] = 5] = "WIDTH_DISTRIBUTION_START_END"; -})(GreasedLineMeshWidthDistribution || (GreasedLineMeshWidthDistribution = {})); -/** - * Builder class for create GreasedLineMeshes - */ -/** - * Creates a new @see GreasedLinePluginMaterial - * @param name name of the material - * @param options material options @see GreasedLineMaterialOptions - * @param scene scene or null to use the last scene - * @returns StandardMaterial or PBRMaterial with the @see GreasedLinePluginMaterial attached to it - */ -function CreateGreasedLineMaterial(name, options, scene) { - scene = (scene !== null && scene !== void 0 ? scene : EngineStore.LastCreatedScene); - let material; - switch (options.materialType) { - case GreasedLineMeshMaterialType.MATERIAL_TYPE_PBR: - material = new PBRMaterial(name, scene); - new GreasedLinePluginMaterial(material, scene, options); - break; - case GreasedLineMeshMaterialType.MATERIAL_TYPE_SIMPLE: - material = new GreasedLineSimpleMaterial(name, scene, options); - break; - default: - material = new StandardMaterial(name, scene); - new GreasedLinePluginMaterial(material, scene, options); - break; - } - return material; -} -/** - * Creates a GreasedLine mesh - * @param name name of the mesh - * @param options options for the mesh - * @param materialOptions material options for the mesh - * @param scene scene where the mesh will be created - * @returns instance of GreasedLineMesh - */ -function CreateGreasedLine(name, options, materialOptions, scene) { - var _a, _b, _c, _d, _e, _f; - scene = (scene !== null && scene !== void 0 ? scene : EngineStore.LastCreatedScene); - let instance; - const allPoints = GreasedLineMesh.ConvertPoints(options.points); - let length = 0; - if (Array.isArray(allPoints[0])) { - allPoints.forEach((points) => { - length += points.length / 3; - }); - } - options.widthDistribution = (_a = options.widthDistribution) !== null && _a !== void 0 ? _a : GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_START; - materialOptions = materialOptions !== null && materialOptions !== void 0 ? materialOptions : { - color: GreasedLinePluginMaterial.DEFAULT_COLOR, - }; - materialOptions.createAndAssignMaterial = (_b = materialOptions.createAndAssignMaterial) !== null && _b !== void 0 ? _b : true; - materialOptions.colorDistribution = (_c = materialOptions === null || materialOptions === void 0 ? void 0 : materialOptions.colorDistribution) !== null && _c !== void 0 ? _c : GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_START; - materialOptions.materialType = (_d = materialOptions.materialType) !== null && _d !== void 0 ? _d : GreasedLineMeshMaterialType.MATERIAL_TYPE_STANDARD; - const widths = CompleteGreasedLineWidthTable(length, (_e = options.widths) !== null && _e !== void 0 ? _e : [], options.widthDistribution); - const colors = (materialOptions === null || materialOptions === void 0 ? void 0 : materialOptions.colors) - ? CompleteGreasedLineColorTable(length, materialOptions.colors, materialOptions.colorDistribution, (_f = materialOptions.color) !== null && _f !== void 0 ? _f : GreasedLinePluginMaterial.DEFAULT_COLOR) - : undefined; - // create new mesh if instance is not defined - if (!options.instance) { - const initialGreasedLineOptions = { - points: allPoints, - updatable: options.updatable, - widths, - lazy: options.lazy, - }; - instance = new GreasedLineMesh(name, scene, initialGreasedLineOptions); - if (materialOptions) { - const initialMaterialOptions = { - materialType: materialOptions.materialType, - dashCount: materialOptions.dashCount, - dashOffset: materialOptions.dashOffset, - dashRatio: materialOptions.dashRatio, - resolution: materialOptions.resolution, - sizeAttenuation: materialOptions.sizeAttenuation, - useColors: materialOptions.useColors, - useDash: materialOptions.useDash, - visibility: materialOptions.visibility, - width: materialOptions.width, - color: materialOptions.color, - colorMode: materialOptions.colorMode, - colorsSampling: materialOptions.colorsSampling, - colorDistributionType: materialOptions.colorDistributionType, - colors, - }; - if (materialOptions.createAndAssignMaterial) { - const material = CreateGreasedLineMaterial(name, initialMaterialOptions, scene); - instance.material = material; - } - } - } - else { - // update the data on the mesh instance - instance = options.instance; - const currentWidths = instance.widths; - if (currentWidths) { - const newWidths = currentWidths.slice(); - for (const w of widths) { - newWidths.push(w); - } - instance.widths = newWidths; - } - else { - instance.widths = widths; - } - instance.addPoints(allPoints); - } - // add colors - // it will merge if any colors already on the instance - if (colors && options.instance) { - if (options.instance.greasedLineMaterial) { - const currentColors = options.instance.greasedLineMaterial.colors; - if (currentColors) { - const newColors = currentColors.concat(colors); - options.instance.greasedLineMaterial.setColors(newColors, instance.isLazy()); - } - } - } - return instance; -} -/** - * Completes the width table/fills the missing entries. It means it creates a width entry for every point of the line mesh. - * You can provide more points the widths when creating the mesh. This function will fill the empty entries. - * The algorithm used to fill the empty entries can be - * GreasedLineMeshWidthDistribution.REPEAT - the width table will be repeatedly copied to the empty values [wL, wU] = [wL, wU, wL, wU, wL, wU, wL, wU, ...] - * GreasedLineMeshWidthDistribution.EVEN - the width table will be evenly copied to the empty values [wL, wU] = [wL, wL, wL, wL, wU, wU, wU, wU] - * GreasedLineMeshWidthDistribution.START - the width table will be copied at the start of the empty values - * 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] - * GreasedLineMeshWidthDistribution.END - the width table will be copied at the end of the empty values - * and rest will be filled width the default values [wL, wU] = [wL, wU, dwL, dwU, dwL, dwU, wL, wU] - * @param pointCount number of points of the line mesh - * @param widths array of widths [widhtLower, widthUpper, widthLower, widthUpper ...]. Two widths (lower/upper) per point. - * @param widthsDistribution how to distribute widths if the widths array has fewer entries than pointCount - * @param defaultWidthUpper the default value which will be used to fill empty width entries - upper width - * @param defaultWidthLower the default value which will be used to fill empty width entries - lower width - * @returns completed width table. - */ -function CompleteGreasedLineWidthTable(pointCount, widths, widthsDistribution, defaultWidthUpper = 1, defaultWidthLower = 1) { - const missingCount = pointCount - widths.length / 2; - const widthsData = []; - if (missingCount < 0) { - return widths.slice(0, pointCount * 2); - } - // is the width table shorter than the point table? - if (missingCount > 0) { - // it is, fill in the missing elements - if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_START_END) { - const halfCount = Math.floor(widths.length / 2); - // start sector - for (let i = 0, j = 0; i < halfCount - 1; i++) { - widthsData.push(widths[j++]); - widthsData.push(widths[j++]); - } - // middle sector - const widthL = widths[halfCount / 2]; - const widthU = widths[halfCount / 2 + 1]; - for (let i = 0; i < missingCount; i++) { - widthsData.push(widthU); - widthsData.push(widthL); - } - // end sector - for (let i = halfCount; i < widths.length; i += 2) { - widthsData.push(widths[i]); - widthsData.push(widths[i + 1]); - } - } - else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_START) { - // start sector - for (let i = 0; i < widths.length; i += 2) { - widthsData.push(widths[i]); - widthsData.push(widths[i + 1]); - } - // end sector - for (let i = 0; i < missingCount; i++) { - widthsData.push(defaultWidthUpper); - widthsData.push(defaultWidthLower); - } - } - else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_END) { - // start sector - for (let i = 0; i < missingCount; i++) { - widthsData.push(defaultWidthUpper); - widthsData.push(defaultWidthLower); - } - // end sector - for (let i = 0; i < widths.length; i += 2) { - widthsData.push(widths[i]); - widthsData.push(widths[i + 1]); - } - } - else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_REPEAT) { - let i = 0; - for (let x = 0; x < pointCount; x++) { - widthsData.push(widths[i++]); - widthsData.push(widths[i++]); - if (i === widths.length) { - i = 0; - } - } - } - else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_EVEN) { - let j = 0; - const widthsectorLength = widths.length / ((pointCount - 1) * 2); - for (let x = 0; x < pointCount; x++) { - const i = Math.floor(j); - widthsData.push(widths[i]); - widthsData.push(widths[i + 1]); - j += widthsectorLength; - } - } - } - else { - for (let i = 0; i < widths.length; i++) { - widthsData.push(widths[i]); - } - } - return widthsData; -} -/** - * Completes the color table/fill the missing color entries. It means it creates a color entry for every point of the line mesh. - * You can provide more points the colors when creating the mesh. This function will fill the empty entries. - * The algorithm used to fill the empty entries can be - * GreasedLineMesColorhDistribution.REPEAT - the color table will be repeatedly copied to the empty values [c1, c2] = [c1, c2, c1, c2, c1, c2, c1, c2] - * GreasedLineMesColorhDistribution.EVEN - the color table will be evenly copied to the empty values [c1, c2] = [c1, c1, c1, c1, c2, c2, c2, c2] - * GreasedLineMesColorhDistribution.START - the color table will be copied at the start of the empty values - * and rest will be filled color the default color value [c1, c2] = [c1, c2, dc, dc, dc, dc, dc, dc] - * GreasedLineMesColorhDistribution.START_END - the color table will be copied at the start and the end of the empty values - * and rest will be filled color the default color value [c1, c2] = [c1, c2, dc, dc, dc, dc, c1, c2] - * @param pointCount number of points of the line mesh - * @param colors array of Color3 for the color table - * @param colorDistribution how to distribute colors if the colors array has fewer entries than pointCount - * @param defaultColor default color to be used to fill empty entries in the color table - * @returns completed array of Color3s - */ -function CompleteGreasedLineColorTable(pointCount, colors, colorDistribution, defaultColor) { - pointCount = Math.max(colors.length, pointCount); - const missingCount = pointCount - colors.length; - if (missingCount < 0) { - return colors.slice(0, pointCount); - } - const colorsData = []; - // is the color table shorter than the point table? - if (missingCount > 0) { - // it is, fill in the missing elements - if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_START_END) { - const halfCount = Math.floor(colors.length / 2); - // start sector - for (let i = 0; i < halfCount; i++) { - colorsData.push(colors[i]); - } - // middle sector - for (let i = 0; i < missingCount - 1; i++) { - colorsData.push(defaultColor); - } - // end sector - for (let i = halfCount; i < colors.length; i++) { - colorsData.push(colors[i]); - } - } - else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_START) { - // start sector - for (let i = 0; i < colors.length; i++) { - colorsData.push(colors[i]); - } - // end sector - for (let i = 0; i < missingCount; i++) { - colorsData.push(defaultColor); - } - } - else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_END) { - // start sector - for (let i = 0; i < missingCount - 1; i++) { - colorsData.push(defaultColor); - } - // end sector - for (let i = 0; i < colors.length; i++) { - colorsData.push(colors[i]); - } - } - else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_REPEAT) { - let i = 0; - for (let x = 0; x < pointCount; x++) { - colorsData.push(colors[i]); - i++; - if (i === colors.length) { - i = 0; - } - } - } - else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_EVEN) { - let j = 0; - const colorSectorLength = colors.length / (pointCount - 1); - for (let x = 0; x < pointCount - 1; x++) { - const i = Math.floor(j); - colorsData.push(colors[i]); - j += colorSectorLength; - } - } - else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_NONE) { - for (let i = 0; i < colors.length; i++) { - colorsData.push(colors[i]); - } - } - } - else { - for (let i = 0; i < pointCount; i++) { - colorsData.push(colors[i]); - } - } - return colorsData; -} -//# sourceMappingURL=greasedLineBuilder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Builders/index.js - - - - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/thinInstanceMesh.js - - - - - -mesh_Mesh.prototype.thinInstanceAdd = function (matrix, refresh = true) { - if (!this.getScene().getEngine().getCaps().instancedArrays) { - logger_Logger.Error("Thin Instances are not supported on this device as Instanced Array extension not supported"); - return -1; - } - this._thinInstanceUpdateBufferSize("matrix", Array.isArray(matrix) ? matrix.length : 1); - const index = this._thinInstanceDataStorage.instancesCount; - if (Array.isArray(matrix)) { - for (let i = 0; i < matrix.length; ++i) { - this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++, matrix[i], i === matrix.length - 1 && refresh); - } - } - else { - this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++, matrix, refresh); - } - return index; -}; -mesh_Mesh.prototype.thinInstanceAddSelf = function (refresh = true) { - return this.thinInstanceAdd(math_vector_Matrix.IdentityReadOnly, refresh); -}; -mesh_Mesh.prototype.thinInstanceRegisterAttribute = function (kind, stride) { - // preserve backward compatibility - if (kind === buffer_VertexBuffer.ColorKind) { - kind = buffer_VertexBuffer.ColorInstanceKind; - } - this.removeVerticesData(kind); - this._thinInstanceInitializeUserStorage(); - this._userThinInstanceBuffersStorage.strides[kind] = stride; - this._userThinInstanceBuffersStorage.sizes[kind] = stride * Math.max(32, this._thinInstanceDataStorage.instancesCount); // Initial size - this._userThinInstanceBuffersStorage.data[kind] = new Float32Array(this._userThinInstanceBuffersStorage.sizes[kind]); - this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new buffer_VertexBuffer(this.getEngine(), this._userThinInstanceBuffersStorage.data[kind], kind, true, false, stride, true); - this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]); -}; -mesh_Mesh.prototype.thinInstanceSetMatrixAt = function (index, matrix, refresh = true) { - if (!this._thinInstanceDataStorage.matrixData || index >= this._thinInstanceDataStorage.instancesCount) { - return false; - } - const matrixData = this._thinInstanceDataStorage.matrixData; - matrix.copyToArray(matrixData, index * 16); - if (this._thinInstanceDataStorage.worldMatrices) { - this._thinInstanceDataStorage.worldMatrices[index] = matrix; - } - if (refresh) { - this.thinInstanceBufferUpdated("matrix"); - if (!this.doNotSyncBoundingInfo) { - this.thinInstanceRefreshBoundingInfo(false); - } - } - return true; -}; -mesh_Mesh.prototype.thinInstanceSetAttributeAt = function (kind, index, value, refresh = true) { - // preserve backward compatibility - if (kind === buffer_VertexBuffer.ColorKind) { - kind = buffer_VertexBuffer.ColorInstanceKind; - } - if (!this._userThinInstanceBuffersStorage || !this._userThinInstanceBuffersStorage.data[kind] || index >= this._thinInstanceDataStorage.instancesCount) { - return false; - } - this._thinInstanceUpdateBufferSize(kind, 0); // make sur the buffer for the kind attribute is big enough - this._userThinInstanceBuffersStorage.data[kind].set(value, index * this._userThinInstanceBuffersStorage.strides[kind]); - if (refresh) { - this.thinInstanceBufferUpdated(kind); - } - return true; -}; -Object.defineProperty(mesh_Mesh.prototype, "thinInstanceCount", { - get: function () { - return this._thinInstanceDataStorage.instancesCount; - }, - set: function (value) { - var _a, _b; - const matrixData = (_a = this._thinInstanceDataStorage.matrixData) !== null && _a !== void 0 ? _a : (_b = this.source) === null || _b === void 0 ? void 0 : _b._thinInstanceDataStorage.matrixData; - const numMaxInstances = matrixData ? matrixData.length / 16 : 0; - if (value <= numMaxInstances) { - this._thinInstanceDataStorage.instancesCount = value; - } - }, - enumerable: true, - configurable: true, -}); -mesh_Mesh.prototype._thinInstanceCreateMatrixBuffer = function (kind, buffer, staticBuffer = false) { - // preserve backward compatibility - if (kind === buffer_VertexBuffer.ColorKind) { - kind = buffer_VertexBuffer.ColorInstanceKind; - } - const matrixBuffer = new Buffer(this.getEngine(), buffer, !staticBuffer, 16, false, true); - for (let i = 0; i < 4; i++) { - this.setVerticesBuffer(matrixBuffer.createVertexBuffer(kind + i, i * 4, 4)); - } - return matrixBuffer; -}; -mesh_Mesh.prototype.thinInstanceSetBuffer = function (kind, buffer, stride = 0, staticBuffer = false) { - var _a, _b, _c; - stride = stride || 16; - if (kind === "matrix") { - (_a = this._thinInstanceDataStorage.matrixBuffer) === null || _a === void 0 ? void 0 : _a.dispose(); - this._thinInstanceDataStorage.matrixBuffer = null; - this._thinInstanceDataStorage.matrixBufferSize = buffer ? buffer.length : 32 * stride; - this._thinInstanceDataStorage.matrixData = buffer; - this._thinInstanceDataStorage.worldMatrices = null; - if (buffer !== null) { - this._thinInstanceDataStorage.instancesCount = buffer.length / stride; - this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer("world", buffer, staticBuffer); - if (!this.doNotSyncBoundingInfo) { - this.thinInstanceRefreshBoundingInfo(false); - } - } - else { - this._thinInstanceDataStorage.instancesCount = 0; - if (!this.doNotSyncBoundingInfo) { - // mesh has no more thin instances, so need to recompute the bounding box because it's the regular mesh that will now be displayed - this.refreshBoundingInfo(); - } - } - } - else if (kind === "previousMatrix") { - (_b = this._thinInstanceDataStorage.previousMatrixBuffer) === null || _b === void 0 ? void 0 : _b.dispose(); - this._thinInstanceDataStorage.previousMatrixBuffer = null; - this._thinInstanceDataStorage.previousMatrixData = buffer; - if (buffer !== null) { - this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", buffer, staticBuffer); - } - } - else { - // color for instanced mesh is ColorInstanceKind and not ColorKind because of native that needs to do the differenciation - // hot switching kind here to preserve backward compatibility - if (kind === buffer_VertexBuffer.ColorKind) { - kind = buffer_VertexBuffer.ColorInstanceKind; - } - if (buffer === null) { - if ((_c = this._userThinInstanceBuffersStorage) === null || _c === void 0 ? void 0 : _c.data[kind]) { - this.removeVerticesData(kind); - delete this._userThinInstanceBuffersStorage.data[kind]; - delete this._userThinInstanceBuffersStorage.strides[kind]; - delete this._userThinInstanceBuffersStorage.sizes[kind]; - delete this._userThinInstanceBuffersStorage.vertexBuffers[kind]; - } - } - else { - this._thinInstanceInitializeUserStorage(); - this._userThinInstanceBuffersStorage.data[kind] = buffer; - this._userThinInstanceBuffersStorage.strides[kind] = stride; - this._userThinInstanceBuffersStorage.sizes[kind] = buffer.length; - this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new buffer_VertexBuffer(this.getEngine(), buffer, kind, !staticBuffer, false, stride, true); - this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]); - } - } -}; -mesh_Mesh.prototype.thinInstanceBufferUpdated = function (kind) { - var _a, _b, _c; - if (kind === "matrix") { - (_a = this._thinInstanceDataStorage.matrixBuffer) === null || _a === void 0 ? void 0 : _a.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, this._thinInstanceDataStorage.instancesCount); - } - else if (kind === "previousMatrix") { - (_b = this._thinInstanceDataStorage.previousMatrixBuffer) === null || _b === void 0 ? void 0 : _b.updateDirectly(this._thinInstanceDataStorage.previousMatrixData, 0, this._thinInstanceDataStorage.instancesCount); - } - else { - // preserve backward compatibility - if (kind === buffer_VertexBuffer.ColorKind) { - kind = buffer_VertexBuffer.ColorInstanceKind; - } - if ((_c = this._userThinInstanceBuffersStorage) === null || _c === void 0 ? void 0 : _c.vertexBuffers[kind]) { - this._userThinInstanceBuffersStorage.vertexBuffers[kind].updateDirectly(this._userThinInstanceBuffersStorage.data[kind], 0); - } - } -}; -mesh_Mesh.prototype.thinInstancePartialBufferUpdate = function (kind, data, offset) { - var _a; - if (kind === "matrix") { - if (this._thinInstanceDataStorage.matrixBuffer) { - this._thinInstanceDataStorage.matrixBuffer.updateDirectly(data, offset); - } - } - else { - // preserve backward compatibility - if (kind === buffer_VertexBuffer.ColorKind) { - kind = buffer_VertexBuffer.ColorInstanceKind; - } - if ((_a = this._userThinInstanceBuffersStorage) === null || _a === void 0 ? void 0 : _a.vertexBuffers[kind]) { - this._userThinInstanceBuffersStorage.vertexBuffers[kind].updateDirectly(data, offset); - } - } -}; -mesh_Mesh.prototype.thinInstanceGetWorldMatrices = function () { - if (!this._thinInstanceDataStorage.matrixData || !this._thinInstanceDataStorage.matrixBuffer) { - return []; - } - const matrixData = this._thinInstanceDataStorage.matrixData; - if (!this._thinInstanceDataStorage.worldMatrices) { - this._thinInstanceDataStorage.worldMatrices = new Array(); - for (let i = 0; i < this._thinInstanceDataStorage.instancesCount; ++i) { - this._thinInstanceDataStorage.worldMatrices[i] = math_vector_Matrix.FromArray(matrixData, i * 16); - } - } - return this._thinInstanceDataStorage.worldMatrices; -}; -mesh_Mesh.prototype.thinInstanceRefreshBoundingInfo = function (forceRefreshParentInfo = false, applySkeleton = false, applyMorph = false) { - if (!this._thinInstanceDataStorage.matrixData || !this._thinInstanceDataStorage.matrixBuffer) { - return; - } - const vectors = this._thinInstanceDataStorage.boundingVectors; - if (forceRefreshParentInfo || !this.rawBoundingInfo) { - vectors.length = 0; - this.refreshBoundingInfo(applySkeleton, applyMorph); - const boundingInfo = this.getBoundingInfo(); - this.rawBoundingInfo = new boundingInfo_BoundingInfo(boundingInfo.minimum, boundingInfo.maximum); - } - const boundingInfo = this.getBoundingInfo(); - const matrixData = this._thinInstanceDataStorage.matrixData; - if (vectors.length === 0) { - for (let v = 0; v < boundingInfo.boundingBox.vectors.length; ++v) { - vectors.push(boundingInfo.boundingBox.vectors[v].clone()); - } - } - math_vector_TmpVectors.Vector3[0].setAll(Number.POSITIVE_INFINITY); // min - math_vector_TmpVectors.Vector3[1].setAll(Number.NEGATIVE_INFINITY); // max - for (let i = 0; i < this._thinInstanceDataStorage.instancesCount; ++i) { - math_vector_Matrix.FromArrayToRef(matrixData, i * 16, math_vector_TmpVectors.Matrix[0]); - for (let v = 0; v < vectors.length; ++v) { - math_vector_Vector3.TransformCoordinatesToRef(vectors[v], math_vector_TmpVectors.Matrix[0], math_vector_TmpVectors.Vector3[2]); - math_vector_TmpVectors.Vector3[0].minimizeInPlace(math_vector_TmpVectors.Vector3[2]); - math_vector_TmpVectors.Vector3[1].maximizeInPlace(math_vector_TmpVectors.Vector3[2]); - } - } - boundingInfo.reConstruct(math_vector_TmpVectors.Vector3[0], math_vector_TmpVectors.Vector3[1]); - this._updateBoundingInfo(); -}; -mesh_Mesh.prototype._thinInstanceUpdateBufferSize = function (kind, numInstances = 1) { - var _a, _b, _c; - // preserve backward compatibility - if (kind === buffer_VertexBuffer.ColorKind) { - kind = buffer_VertexBuffer.ColorInstanceKind; - } - const kindIsMatrix = kind === "matrix"; - if (!kindIsMatrix && (!this._userThinInstanceBuffersStorage || !this._userThinInstanceBuffersStorage.strides[kind])) { - return; - } - const stride = kindIsMatrix ? 16 : this._userThinInstanceBuffersStorage.strides[kind]; - const currentSize = kindIsMatrix ? this._thinInstanceDataStorage.matrixBufferSize : this._userThinInstanceBuffersStorage.sizes[kind]; - let data = kindIsMatrix ? this._thinInstanceDataStorage.matrixData : this._userThinInstanceBuffersStorage.data[kind]; - const bufferSize = (this._thinInstanceDataStorage.instancesCount + numInstances) * stride; - let newSize = currentSize; - while (newSize < bufferSize) { - newSize *= 2; - } - if (!data || currentSize != newSize) { - if (!data) { - data = new Float32Array(newSize); - } - else { - const newData = new Float32Array(newSize); - newData.set(data, 0); - data = newData; - } - if (kindIsMatrix) { - (_a = this._thinInstanceDataStorage.matrixBuffer) === null || _a === void 0 ? void 0 : _a.dispose(); - this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer("world", data, false); - this._thinInstanceDataStorage.matrixData = data; - this._thinInstanceDataStorage.matrixBufferSize = newSize; - if (this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData) { - (_b = this._thinInstanceDataStorage.previousMatrixBuffer) === null || _b === void 0 ? void 0 : _b.dispose(); - this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", data, false); - } - } - else { - (_c = this._userThinInstanceBuffersStorage.vertexBuffers[kind]) === null || _c === void 0 ? void 0 : _c.dispose(); - this._userThinInstanceBuffersStorage.data[kind] = data; - this._userThinInstanceBuffersStorage.sizes[kind] = newSize; - this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new buffer_VertexBuffer(this.getEngine(), data, kind, true, false, stride, true); - this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]); - } - } -}; -mesh_Mesh.prototype._thinInstanceInitializeUserStorage = function () { - if (!this._userThinInstanceBuffersStorage) { - this._userThinInstanceBuffersStorage = { - data: {}, - sizes: {}, - vertexBuffers: {}, - strides: {}, - }; - } -}; -mesh_Mesh.prototype._disposeThinInstanceSpecificData = function () { - var _a; - if ((_a = this._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.matrixBuffer) { - this._thinInstanceDataStorage.matrixBuffer.dispose(); - this._thinInstanceDataStorage.matrixBuffer = null; - } -}; -//# sourceMappingURL=thinInstanceMesh.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Enums/nodeGeometryConnectionPointTypes.js -/** - * Defines the kind of connection point for node geometry - */ -var NodeGeometryBlockConnectionPointTypes; -(function (NodeGeometryBlockConnectionPointTypes) { - /** Int */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Int"] = 1] = "Int"; - /** Float */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Float"] = 2] = "Float"; - /** Vector2 */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Vector2"] = 4] = "Vector2"; - /** Vector3 */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Vector3"] = 8] = "Vector3"; - /** Vector4 */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Vector4"] = 16] = "Vector4"; - /** Matrix */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Matrix"] = 32] = "Matrix"; - /** Geometry */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Geometry"] = 64] = "Geometry"; - /** Detect type based on connection */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["AutoDetect"] = 1024] = "AutoDetect"; - /** Output type that will be defined by input type */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["BasedOnInput"] = 2048] = "BasedOnInput"; - /** Undefined */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["Undefined"] = 4096] = "Undefined"; - /** Bitmask of all types */ - NodeGeometryBlockConnectionPointTypes[NodeGeometryBlockConnectionPointTypes["All"] = 4095] = "All"; -})(NodeGeometryBlockConnectionPointTypes || (NodeGeometryBlockConnectionPointTypes = {})); -//# sourceMappingURL=nodeGeometryConnectionPointTypes.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/nodeGeometryBlockConnectionPoint.js - - -/** - * Enum used to define the compatibility state between two connection points - */ -var NodeGeometryConnectionPointCompatibilityStates; -(function (NodeGeometryConnectionPointCompatibilityStates) { - /** Points are compatibles */ - NodeGeometryConnectionPointCompatibilityStates[NodeGeometryConnectionPointCompatibilityStates["Compatible"] = 0] = "Compatible"; - /** Points are incompatible because of their types */ - NodeGeometryConnectionPointCompatibilityStates[NodeGeometryConnectionPointCompatibilityStates["TypeIncompatible"] = 1] = "TypeIncompatible"; - /** Points are incompatible because they are in the same hierarchy **/ - NodeGeometryConnectionPointCompatibilityStates[NodeGeometryConnectionPointCompatibilityStates["HierarchyIssue"] = 2] = "HierarchyIssue"; -})(NodeGeometryConnectionPointCompatibilityStates || (NodeGeometryConnectionPointCompatibilityStates = {})); -/** - * Defines the direction of a connection point - */ -var NodeGeometryConnectionPointDirection; -(function (NodeGeometryConnectionPointDirection) { - /** Input */ - NodeGeometryConnectionPointDirection[NodeGeometryConnectionPointDirection["Input"] = 0] = "Input"; - /** Output */ - NodeGeometryConnectionPointDirection[NodeGeometryConnectionPointDirection["Output"] = 1] = "Output"; -})(NodeGeometryConnectionPointDirection || (NodeGeometryConnectionPointDirection = {})); -/** - * Defines a connection point for a block - */ -class NodeGeometryConnectionPoint { - /** Gets the direction of the point */ - get direction() { - return this._direction; - } - /** - * Gets or sets the connection point type (default is float) - */ - get type() { - if (this._type === NodeGeometryBlockConnectionPointTypes.AutoDetect) { - if (this._ownerBlock.isInput) { - return this._ownerBlock.type; - } - if (this._connectedPoint) { - return this._connectedPoint.type; - } - if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected) { - return this._linkedConnectionSource.type; - } - } - if (this._type === NodeGeometryBlockConnectionPointTypes.BasedOnInput) { - if (this._typeConnectionSource) { - if (!this._typeConnectionSource.isConnected && this._defaultConnectionPointType) { - return this._defaultConnectionPointType; - } - return this._typeConnectionSource.type; - } - else if (this._defaultConnectionPointType) { - return this._defaultConnectionPointType; - } - } - return this._type; - } - set type(value) { - this._type = value; - } - /** - * Gets a boolean indicating that the current point is connected to another NodeMaterialBlock - */ - get isConnected() { - return this.connectedPoint !== null || this.hasEndpoints; - } - /** Get the other side of the connection (if any) */ - get connectedPoint() { - return this._connectedPoint; - } - /** Get the block that owns this connection point */ - get ownerBlock() { - return this._ownerBlock; - } - /** Get the block connected on the other side of this connection (if any) */ - get sourceBlock() { - if (!this._connectedPoint) { - return null; - } - return this._connectedPoint.ownerBlock; - } - /** Get the block connected on the endpoints of this connection (if any) */ - get connectedBlocks() { - if (this._endpoints.length === 0) { - return []; - } - return this._endpoints.map((e) => e.ownerBlock); - } - /** Gets the list of connected endpoints */ - get endpoints() { - return this._endpoints; - } - /** Gets a boolean indicating if that output point is connected to at least one input */ - get hasEndpoints() { - return this._endpoints && this._endpoints.length > 0; - } - /** Get the inner type (ie AutoDetect for instance instead of the inferred one) */ - get innerType() { - if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected) { - return this.type; - } - return this._type; - } - /** - * Gets the value represented by this connection point - * @param state current evaluation state - * @returns the connected value or the value if nothing is connected - */ - getConnectedValue(state) { - var _a, _b, _c; - if (this.isConnected) { - if ((_a = this._connectedPoint) === null || _a === void 0 ? void 0 : _a._storedFunction) { - return (_b = this._connectedPoint) === null || _b === void 0 ? void 0 : _b._storedFunction(state); - } - return (_c = this._connectedPoint) === null || _c === void 0 ? void 0 : _c._storedValue; - } - return this.value; - } - /** - * Creates a new connection point - * @param name defines the connection point name - * @param ownerBlock defines the block hosting this connection point - * @param direction defines the direction of the connection point - */ - constructor(name, ownerBlock, direction) { - /** @internal */ - this._connectedPoint = null; - /** @internal */ - this._storedValue = null; - /** @internal */ - this._storedFunction = null; - /** @internal */ - this._acceptedConnectionPointType = null; - this._endpoints = new Array(); - this._type = NodeGeometryBlockConnectionPointTypes.Geometry; - /** @internal */ - this._linkedConnectionSource = null; - /** @internal */ - this._typeConnectionSource = null; - /** @internal */ - this._defaultConnectionPointType = null; - /** - * Gets or sets the additional types supported by this connection point - */ - this.acceptedConnectionPointTypes = new Array(); - /** - * Gets or sets the additional types excluded by this connection point - */ - this.excludedConnectionPointTypes = new Array(); - /** - * Observable triggered when this point is connected - */ - this.onConnectionObservable = new observable_Observable(); - /** - * Gets or sets a boolean indicating that this connection point is exposed on a frame - */ - this.isExposedOnFrame = false; - /** - * Gets or sets number indicating the position that the port is exposed to on a frame - */ - this.exposedPortPosition = -1; - /** - * Gets or sets the default value used for this point if nothing is connected - */ - this.value = null; - /** - * Gets or sets the min value accepted for this point if nothing is connected - */ - this.valueMin = null; - /** - * Gets or sets the max value accepted for this point if nothing is connected - */ - this.valueMax = null; - this._ownerBlock = ownerBlock; - this.name = name; - this._direction = direction; - } - /** - * Gets the current class name e.g. "NodeMaterialConnectionPoint" - * @returns the class name - */ - getClassName() { - return "NodeGeometryConnectionPoint"; - } - /** - * Gets a boolean indicating if the current point can be connected to another point - * @param connectionPoint defines the other connection point - * @returns a boolean - */ - canConnectTo(connectionPoint) { - return this.checkCompatibilityState(connectionPoint) === NodeGeometryConnectionPointCompatibilityStates.Compatible; - } - /** - * Gets a number indicating if the current point can be connected to another point - * @param connectionPoint defines the other connection point - * @returns a number defining the compatibility state - */ - checkCompatibilityState(connectionPoint) { - const ownerBlock = this._ownerBlock; - const otherBlock = connectionPoint.ownerBlock; - if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeGeometryBlockConnectionPointTypes.AutoDetect) { - // Accepted types - if (connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) { - return NodeGeometryConnectionPointCompatibilityStates.Compatible; - } - else { - return NodeGeometryConnectionPointCompatibilityStates.TypeIncompatible; - } - } - // Excluded - if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) { - return NodeGeometryConnectionPointCompatibilityStates.TypeIncompatible; - } - // Check hierarchy - let targetBlock = otherBlock; - let sourceBlock = ownerBlock; - if (this.direction === NodeGeometryConnectionPointDirection.Input) { - targetBlock = ownerBlock; - sourceBlock = otherBlock; - } - if (targetBlock.isAnAncestorOf(sourceBlock)) { - return NodeGeometryConnectionPointCompatibilityStates.HierarchyIssue; - } - return NodeGeometryConnectionPointCompatibilityStates.Compatible; - } - /** - * Connect this point to another connection point - * @param connectionPoint defines the other connection point - * @param ignoreConstraints defines if the system will ignore connection type constraints (default is false) - * @returns the current connection point - */ - connectTo(connectionPoint, ignoreConstraints = false) { - if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) { - throw "Cannot connect these two connectors."; - } - this._endpoints.push(connectionPoint); - connectionPoint._connectedPoint = this; - this.onConnectionObservable.notifyObservers(connectionPoint); - connectionPoint.onConnectionObservable.notifyObservers(this); - return this; - } - /** - * Disconnect this point from one of his endpoint - * @param endpoint defines the other connection point - * @returns the current connection point - */ - disconnectFrom(endpoint) { - const index = this._endpoints.indexOf(endpoint); - if (index === -1) { - return this; - } - this._endpoints.splice(index, 1); - endpoint._connectedPoint = null; - return this; - } - /** - * Fill the list of excluded connection point types with all types other than those passed in the parameter - * @param mask Types (ORed values of NodeMaterialBlockConnectionPointTypes) that are allowed, and thus will not be pushed to the excluded list - */ - addExcludedConnectionPointFromAllowedTypes(mask) { - let bitmask = 1; - while (bitmask < NodeGeometryBlockConnectionPointTypes.All) { - if (!(mask & bitmask)) { - this.excludedConnectionPointTypes.push(bitmask); - } - bitmask = bitmask << 1; - } - } - /** - * Serializes this point in a JSON representation - * @param isInput defines if the connection point is an input (default is true) - * @returns the serialized point object - */ - serialize(isInput = true) { - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.displayName = this.displayName; - if (this.value !== undefined && this.value !== null) { - if (this.value.asArray) { - serializationObject.valueType = "BABYLON." + this.value.getClassName(); - serializationObject.value = this.value.asArray(); - } - else { - serializationObject.valueType = "number"; - serializationObject.value = this.value; - } - } - if (isInput && this.connectedPoint) { - serializationObject.inputName = this.name; - serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId; - serializationObject.targetConnectionName = this.connectedPoint.name; - } - return serializationObject; - } - /** - * Release resources - */ - dispose() { - this.onConnectionObservable.clear(); - } -} -//# sourceMappingURL=nodeGeometryBlockConnectionPoint.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/nodeGeometryBlock.js - - - - - - - -/** - * Defines a block that can be used inside a node based geometry - */ -class NodeGeometryBlock { - /** - * Gets the time spent to build this block (in ms) - */ - get buildExecutionTime() { - return this._buildExecutionTime; - } - /** - * Gets the list of input points - */ - get inputs() { - return this._inputs; - } - /** Gets the list of output points */ - get outputs() { - return this._outputs; - } - /** - * Gets or set the name of the block - */ - get name() { - return this._name; - } - set name(value) { - this._name = value; - } - /** - * Gets a boolean indicating if this block is an input - */ - get isInput() { - return this._isInput; - } - /** - * Gets a boolean indicating if this block is a teleport out - */ - get isTeleportOut() { - return this._isTeleportOut; - } - /** - * Gets a boolean indicating if this block is a teleport in - */ - get isTeleportIn() { - return this._isTeleportIn; - } - /** - * Gets a boolean indicating that this block can only be used once per NodeGeometry - */ - get isUnique() { - return this._isUnique; - } - /** - * Gets the current class name e.g. "NodeGeometryBlock" - * @returns the class name - */ - getClassName() { - return "NodeGeometryBlock"; - } - _inputRename(name) { - return name; - } - _outputRename(name) { - return name; - } - /** - * Checks if the current block is an ancestor of a given block - * @param block defines the potential descendant block to check - * @returns true if block is a descendant - */ - isAnAncestorOf(block) { - for (const output of this._outputs) { - if (!output.hasEndpoints) { - continue; - } - for (const endpoint of output.endpoints) { - if (endpoint.ownerBlock === block) { - return true; - } - if (endpoint.ownerBlock.isAnAncestorOf(block)) { - return true; - } - } - } - return false; - } - /** - * Checks if the current block is an ancestor of a given type - * @param type defines the potential type to check - * @returns true if block is a descendant - */ - isAnAncestorOfType(type) { - if (this.getClassName() === type) { - return true; - } - for (const output of this._outputs) { - if (!output.hasEndpoints) { - continue; - } - for (const endpoint of output.endpoints) { - if (endpoint.ownerBlock.isAnAncestorOfType(type)) { - return true; - } - } - } - return false; - } - /** - * Get the first descendant using a predicate - * @param predicate defines the predicate to check - * @returns descendant or null if none found - */ - getDescendantOfPredicate(predicate) { - if (predicate(this)) { - return this; - } - for (const output of this._outputs) { - if (!output.hasEndpoints) { - continue; - } - for (const endpoint of output.endpoints) { - const descendant = endpoint.ownerBlock.getDescendantOfPredicate(predicate); - if (descendant) { - return descendant; - } - } - } - return null; - } - /** - * Creates a new NodeGeometryBlock - * @param name defines the block name - */ - constructor(name) { - this._name = ""; - this._isInput = false; - this._isTeleportOut = false; - this._isTeleportIn = false; - this._isUnique = false; - this._buildExecutionTime = 0; - /** - * Gets an observable raised when the block is built - */ - this.onBuildObservable = new observable_Observable(); - /** @internal */ - this._inputs = new Array(); - /** @internal */ - this._outputs = new Array(); - /** @internal */ - this._codeVariableName = ""; - /** Gets or sets a boolean indicating that this input can be edited from a collapsed frame */ - this.visibleOnFrame = false; - this._name = name; - this._isInput = this.getClassName() === "GeometryInputBlock"; - this._isTeleportOut = this.getClassName() === "TeleportOutBlock"; - this._isTeleportIn = this.getClassName() === "TeleportInBlock"; - this.uniqueId = UniqueIdGenerator.UniqueId; - } - /** - * Register a new input. Must be called inside a block constructor - * @param name defines the connection point name - * @param type defines the connection point type - * @param isOptional defines a boolean indicating that this input can be omitted - * @param value value to return if there is no connection - * @param valueMin min value accepted for value - * @param valueMax max value accepted for value - * @returns the current block - */ - registerInput(name, type, isOptional = false, value, valueMin, valueMax) { - const point = new NodeGeometryConnectionPoint(name, this, NodeGeometryConnectionPointDirection.Input); - point.type = type; - point.isOptional = isOptional; - point.value = value; - point.valueMin = valueMin; - point.valueMax = valueMax; - this._inputs.push(point); - return this; - } - /** - * Register a new output. Must be called inside a block constructor - * @param name defines the connection point name - * @param type defines the connection point type - * @param point an already created connection point. If not provided, create a new one - * @returns the current block - */ - registerOutput(name, type, point) { - point = point !== null && point !== void 0 ? point : new NodeGeometryConnectionPoint(name, this, NodeGeometryConnectionPointDirection.Output); - point.type = type; - this._outputs.push(point); - return this; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _buildBlock(state) { - // Empty. Must be defined by child nodes - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _customBuildStep(state) { - // Must be implemented by children - } - /** - * Build the current node and generate the vertex data - * @param state defines the current generation state - * @returns true if already built - */ - build(state) { - if (this._buildId === state.buildId) { - return true; - } - if (this._outputs.length > 0) { - if (!this._outputs.some((o) => o.hasEndpoints)) { - return false; - } - } - this._buildId = state.buildId; - // Check if "parent" blocks are compiled - for (const input of this._inputs) { - if (!input.connectedPoint) { - if (!input.isOptional) { - // Emit a warning - state.notConnectedNonOptionalInputs.push(input); - } - continue; - } - const block = input.connectedPoint.ownerBlock; - if (block && block !== this) { - block.build(state); - } - } - this._customBuildStep(state); - // Logs - if (state.verbose) { - console.log(`Building ${this.name} [${this.getClassName()}]`); - } - const now = precisionDate_PrecisionDate.Now; - this._buildBlock(state); - this._buildExecutionTime = precisionDate_PrecisionDate.Now - now; - // Compile connected blocks - for (const output of this._outputs) { - for (const endpoint of output.endpoints) { - const block = endpoint.ownerBlock; - if (block) { - block.build(state); - } - } - } - this.onBuildObservable.notifyObservers(this); - return false; - } - _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) { - if (looseCoupling) { - this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0]; - } - else { - this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1]; - } - this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0]; - } - /** - * Initialize the block and prepare the context for build - */ - initialize() { - // Do nothing - } - /** - * Lets the block try to connect some inputs automatically - */ - autoConfigure() { - // Do nothing - } - /** - * Find an input by its name - * @param name defines the name of the input to look for - * @returns the input or null if not found - */ - getInputByName(name) { - const filter = this._inputs.filter((e) => e.name === name); - if (filter.length) { - return filter[0]; - } - return null; - } - /** - * Find an output by its name - * @param name defines the name of the output to look for - * @returns the output or null if not found - */ - getOutputByName(name) { - const filter = this._outputs.filter((e) => e.name === name); - if (filter.length) { - return filter[0]; - } - return null; - } - /** - * Serializes this block in a JSON representation - * @param _saveMeshData defines a boolean indicating that mesh data must be saved as well - * @returns the serialized block object - */ - serialize(_saveMeshData) { - const serializationObject = {}; - serializationObject.customType = "BABYLON." + this.getClassName(); - serializationObject.id = this.uniqueId; - serializationObject.name = this.name; - serializationObject.inputs = []; - serializationObject.outputs = []; - for (const input of this.inputs) { - serializationObject.inputs.push(input.serialize()); - } - for (const output of this.outputs) { - serializationObject.outputs.push(output.serialize(false)); - } - return serializationObject; - } - /** - * @internal - */ - _deserialize(serializationObject) { - this._name = serializationObject.name; - this.comments = serializationObject.comments; - this.visibleOnFrame = !!serializationObject.visibleOnFrame; - this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject); - } - _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) { - const serializedInputs = serializationObject.inputs; - const serializedOutputs = serializationObject.outputs; - if (serializedInputs) { - serializedInputs.forEach((port, i) => { - if (port.displayName) { - this.inputs[i].displayName = port.displayName; - } - if (port.isExposedOnFrame) { - this.inputs[i].isExposedOnFrame = port.isExposedOnFrame; - this.inputs[i].exposedPortPosition = port.exposedPortPosition; - } - if (port.value !== undefined && port.value !== null) { - if (port.valueType === "number") { - this.inputs[i].value = port.value; - } - else { - const valueType = GetClass(port.valueType); - if (valueType) { - this.inputs[i].value = valueType.FromArray(port.value); - } - } - } - }); - } - if (serializedOutputs) { - serializedOutputs.forEach((port, i) => { - if (port.displayName) { - this.outputs[i].displayName = port.displayName; - } - if (port.isExposedOnFrame) { - this.outputs[i].isExposedOnFrame = port.isExposedOnFrame; - this.outputs[i].exposedPortPosition = port.exposedPortPosition; - } - }); - } - } - _dumpPropertiesCode() { - const variableName = this._codeVariableName; - return `${variableName}.visibleOnFrame = ${this.visibleOnFrame};\n`; - } - /** - * @internal - */ - _dumpCodeForOutputConnections(alreadyDumped) { - let codeString = ""; - if (alreadyDumped.indexOf(this) !== -1) { - return codeString; - } - alreadyDumped.push(this); - for (const input of this.inputs) { - if (!input.isConnected) { - continue; - } - const connectedOutput = input.connectedPoint; - const connectedBlock = connectedOutput.ownerBlock; - codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped); - codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});\n`; - } - return codeString; - } - /** - * @internal - */ - _dumpCode(uniqueNames, alreadyDumped) { - alreadyDumped.push(this); - // Get unique name - const nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, ""); - this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`; - if (uniqueNames.indexOf(this._codeVariableName) !== -1) { - let index = 0; - do { - index++; - this._codeVariableName = nameAsVariableName + index; - } while (uniqueNames.indexOf(this._codeVariableName) !== -1); - } - uniqueNames.push(this._codeVariableName); - // Declaration - let codeString = `\n// ${this.getClassName()}\n`; - if (this.comments) { - codeString += `// ${this.comments}\n`; - } - codeString += `var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`; - // Properties - codeString += this._dumpPropertiesCode(); - // Inputs - for (const input of this.inputs) { - if (!input.isConnected) { - continue; - } - const connectedOutput = input.connectedPoint; - const connectedBlock = connectedOutput.ownerBlock; - if (alreadyDumped.indexOf(connectedBlock) === -1) { - codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped); - } - } - // Outputs - for (const output of this.outputs) { - if (!output.hasEndpoints) { - continue; - } - for (const endpoint of output.endpoints) { - const connectedBlock = endpoint.ownerBlock; - if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) { - codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped); - } - } - } - return codeString; - } - /** - * Clone the current block to a new identical block - * @returns a copy of the current block - */ - clone() { - const serializationObject = this.serialize(); - const blockType = GetClass(serializationObject.customType); - if (blockType) { - const block = new blockType(); - block._deserialize(serializationObject); - return block; - } - return null; - } - /** - * Release resources - */ - dispose() { - for (const input of this.inputs) { - input.dispose(); - } - for (const output of this.outputs) { - output.dispose(); - } - this.onBuildObservable.clear(); - } -} -__decorate([ - serialize("comment") -], NodeGeometryBlock.prototype, "comments", void 0); -//# sourceMappingURL=nodeGeometryBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryOutputBlock.js - - - -/** - * Block used to generate the final geometry - */ -class GeometryOutputBlock extends NodeGeometryBlock { - /** - * Gets the current vertex data if the graph was successfully built - */ - get currentVertexData() { - return this._vertexData; - } - /** - * Create a new GeometryOutputBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this._vertexData = null; - this._isUnique = true; - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "GeometryOutputBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - _buildBlock(state) { - state.vertexData = this.geometry.getConnectedValue(state); - this._vertexData = state.vertexData; - } -} -RegisterClass("BABYLON.GeometryOutputBlock", GeometryOutputBlock); -//# sourceMappingURL=geometryOutputBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Enums/nodeGeometryContextualSources.js -/** - * Defines the kind of contextual sources for node geometry - */ -var NodeGeometryContextualSources; -(function (NodeGeometryContextualSources) { - /** None */ - NodeGeometryContextualSources[NodeGeometryContextualSources["None"] = 0] = "None"; - /** Positions */ - NodeGeometryContextualSources[NodeGeometryContextualSources["Positions"] = 1] = "Positions"; - /** Normals */ - NodeGeometryContextualSources[NodeGeometryContextualSources["Normals"] = 2] = "Normals"; - /** Tangents */ - NodeGeometryContextualSources[NodeGeometryContextualSources["Tangents"] = 3] = "Tangents"; - /** UV */ - NodeGeometryContextualSources[NodeGeometryContextualSources["UV"] = 4] = "UV"; - /** UV2 */ - NodeGeometryContextualSources[NodeGeometryContextualSources["UV2"] = 5] = "UV2"; - /** UV3 */ - NodeGeometryContextualSources[NodeGeometryContextualSources["UV3"] = 6] = "UV3"; - /** UV4 */ - NodeGeometryContextualSources[NodeGeometryContextualSources["UV4"] = 7] = "UV4"; - /** UV5 */ - NodeGeometryContextualSources[NodeGeometryContextualSources["UV5"] = 8] = "UV5"; - /** UV6 */ - NodeGeometryContextualSources[NodeGeometryContextualSources["UV6"] = 9] = "UV6"; - /** Colors */ - NodeGeometryContextualSources[NodeGeometryContextualSources["Colors"] = 10] = "Colors"; - /** VertexID */ - NodeGeometryContextualSources[NodeGeometryContextualSources["VertexID"] = 11] = "VertexID"; - /** FaceID */ - NodeGeometryContextualSources[NodeGeometryContextualSources["FaceID"] = 12] = "FaceID"; - /** GeometryID */ - NodeGeometryContextualSources[NodeGeometryContextualSources["GeometryID"] = 13] = "GeometryID"; - /** CollectionID */ - NodeGeometryContextualSources[NodeGeometryContextualSources["CollectionID"] = 14] = "CollectionID"; - /** LoopID */ - NodeGeometryContextualSources[NodeGeometryContextualSources["LoopID"] = 15] = "LoopID"; -})(NodeGeometryContextualSources || (NodeGeometryContextualSources = {})); -//# sourceMappingURL=nodeGeometryContextualSources.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/nodeGeometryBuildState.js - - - -/** - * Class used to store node based geometry build state - */ -class NodeGeometryBuildState { - constructor() { - this._rotationMatrix = new math_vector_Matrix(); - this._scalingMatrix = new math_vector_Matrix(); - this._positionMatrix = new math_vector_Matrix(); - this._scalingRotationMatrix = new math_vector_Matrix(); - this._transformMatrix = new math_vector_Matrix(); - this._tempVector3 = new math_vector_Vector3(); - /** Gets or sets the list of non connected mandatory inputs */ - this.notConnectedNonOptionalInputs = []; - /** Gets or sets the vertex data */ - this.vertexData = null; - /** Gets or sets the geometry context */ - this.geometryContext = null; - /** Gets or sets the execution context */ - this.executionContext = null; - } - /** - * Gets the value associated with a contextual source - * @param source Source of the contextual value - * @returns the value associated with the source - */ - getContextualValue(source) { - if (!this.executionContext) { - return null; - } - const index = this.executionContext.getExecutionIndex(); - switch (source) { - case NodeGeometryContextualSources.Positions: - if (this.executionContext.getOverridePositionsContextualValue) { - return this.executionContext.getOverridePositionsContextualValue(); - } - if (!this.geometryContext || !this.geometryContext.positions) { - return math_vector_Vector3.Zero(); - } - return math_vector_Vector3.FromArray(this.geometryContext.positions, index * 3); - case NodeGeometryContextualSources.Normals: - if (this.executionContext.getOverrideNormalsContextualValue) { - return this.executionContext.getOverrideNormalsContextualValue(); - } - if (!this.geometryContext || !this.geometryContext.normals) { - return math_vector_Vector3.Zero(); - } - return math_vector_Vector3.FromArray(this.geometryContext.normals, index * 3); - case NodeGeometryContextualSources.Colors: - if (!this.geometryContext || !this.geometryContext.colors) { - return math_vector_Vector4.Zero(); - } - return math_vector_Vector4.FromArray(this.geometryContext.colors, index * 4); - case NodeGeometryContextualSources.Tangents: - if (!this.geometryContext || !this.geometryContext.tangents) { - return math_vector_Vector4.Zero(); - } - return math_vector_Vector4.FromArray(this.geometryContext.tangents, index * 4); - case NodeGeometryContextualSources.UV: - if (!this.geometryContext || !this.geometryContext.uvs) { - return math_vector_Vector2.Zero(); - } - return math_vector_Vector2.FromArray(this.geometryContext.uvs, index * 2); - case NodeGeometryContextualSources.UV2: - if (!this.geometryContext || !this.geometryContext.uvs2) { - return math_vector_Vector2.Zero(); - } - return math_vector_Vector2.FromArray(this.geometryContext.uvs2, index * 2); - case NodeGeometryContextualSources.UV3: - if (!this.geometryContext || !this.geometryContext.uvs3) { - return math_vector_Vector2.Zero(); - } - return math_vector_Vector2.FromArray(this.geometryContext.uvs3, index * 2); - case NodeGeometryContextualSources.UV4: - if (!this.geometryContext || !this.geometryContext.uvs4) { - return math_vector_Vector2.Zero(); - } - return math_vector_Vector2.FromArray(this.geometryContext.uvs4, index * 2); - case NodeGeometryContextualSources.UV5: - if (!this.geometryContext || !this.geometryContext.uvs5) { - return math_vector_Vector2.Zero(); - } - return math_vector_Vector2.FromArray(this.geometryContext.uvs5, index * 2); - case NodeGeometryContextualSources.UV6: - if (!this.geometryContext || !this.geometryContext.uvs6) { - return math_vector_Vector2.Zero(); - } - return math_vector_Vector2.FromArray(this.geometryContext.uvs6, index * 2); - case NodeGeometryContextualSources.VertexID: - return index; - case NodeGeometryContextualSources.FaceID: - return this.executionContext.getExecutionFaceIndex(); - case NodeGeometryContextualSources.LoopID: - return this.executionContext.getExecutionLoopIndex(); - case NodeGeometryContextualSources.GeometryID: - return !this.geometryContext ? 0 : this.geometryContext.uniqueId; - case NodeGeometryContextualSources.CollectionID: { - if (!this.geometryContext || !this.geometryContext.metadata) { - return 0; - } - return this.geometryContext.metadata.collectionId || 0; - } - } - return null; - } - /** - * Adapt a value to a target type - * @param source defines the value to adapt - * @param targetType defines the target type - * @returns the adapted value - */ - adapt(source, targetType) { - const value = source.getConnectedValue(this); - if (source.type === targetType) { - return value; - } - switch (targetType) { - case NodeGeometryBlockConnectionPointTypes.Vector2: - return new math_vector_Vector2(value, value); - case NodeGeometryBlockConnectionPointTypes.Vector3: - return new math_vector_Vector3(value, value, value); - case NodeGeometryBlockConnectionPointTypes.Vector4: - return new math_vector_Vector4(value, value, value, value); - } - return null; - } - /** - * Adapt an input value to a target type - * @param source defines the value to adapt - * @param targetType defines the target type - * @param defaultValue defines the default value to use if not connected - * @returns the adapted value - */ - adaptInput(source, targetType, defaultValue) { - var _a; - if (!source.isConnected) { - return source.value || defaultValue; - } - const value = source.getConnectedValue(this); - if (((_a = source._connectedPoint) === null || _a === void 0 ? void 0 : _a.type) === targetType) { - return value; - } - switch (targetType) { - case NodeGeometryBlockConnectionPointTypes.Vector2: - return new math_vector_Vector2(value, value); - case NodeGeometryBlockConnectionPointTypes.Vector3: - return new math_vector_Vector3(value, value, value); - case NodeGeometryBlockConnectionPointTypes.Vector4: - return new math_vector_Vector4(value, value, value, value); - } - return null; - } - /** - * Emits console errors and exceptions if there is a failing check - */ - emitErrors() { - let errorMessage = ""; - for (const notConnectedInput of this.notConnectedNonOptionalInputs) { - errorMessage += `input ${notConnectedInput.name} from block ${notConnectedInput.ownerBlock.name}[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional.\n`; - } - if (errorMessage) { - throw "Build of NodeGeometry failed:\n" + errorMessage; - } - } - /** @internal */ - _instantiate(clone, currentPosition, rotation, scaling, additionalVertexData) { - // Transform - math_vector_Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, this._scalingMatrix); - math_vector_Matrix.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, this._rotationMatrix); - math_vector_Matrix.TranslationToRef(currentPosition.x, currentPosition.y, currentPosition.z, this._positionMatrix); - this._scalingMatrix.multiplyToRef(this._rotationMatrix, this._scalingRotationMatrix); - this._scalingRotationMatrix.multiplyToRef(this._positionMatrix, this._transformMatrix); - for (let clonePositionIndex = 0; clonePositionIndex < clone.positions.length; clonePositionIndex += 3) { - this._tempVector3.fromArray(clone.positions, clonePositionIndex); - math_vector_Vector3.TransformCoordinatesToRef(this._tempVector3, this._transformMatrix, this._tempVector3); - this._tempVector3.toArray(clone.positions, clonePositionIndex); - if (clone.normals) { - this._tempVector3.fromArray(clone.normals, clonePositionIndex); - math_vector_Vector3.TransformNormalToRef(this._tempVector3, this._scalingRotationMatrix, this._tempVector3); - this._tempVector3.toArray(clone.normals, clonePositionIndex); - } - } - additionalVertexData.push(clone); - } - /** @internal */ - _instantiateWithMatrix(clone, transform, additionalVertexData) { - for (let clonePositionIndex = 0; clonePositionIndex < clone.positions.length; clonePositionIndex += 3) { - this._tempVector3.fromArray(clone.positions, clonePositionIndex); - math_vector_Vector3.TransformCoordinatesToRef(this._tempVector3, transform, this._tempVector3); - this._tempVector3.toArray(clone.positions, clonePositionIndex); - if (clone.normals) { - this._tempVector3.fromArray(clone.normals, clonePositionIndex); - math_vector_Vector3.TransformNormalToRef(this._tempVector3, transform, this._tempVector3); - this._tempVector3.toArray(clone.normals, clonePositionIndex); - } - } - additionalVertexData.push(clone); - } -} -//# sourceMappingURL=nodeGeometryBuildState.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryInputBlock.js - - - - - - -/** - * Block used to expose an input value - */ -class GeometryInputBlock extends NodeGeometryBlock { - /** - * Gets or sets the connection point type (default is float) - */ - get type() { - if (this._type === NodeGeometryBlockConnectionPointTypes.AutoDetect) { - if (this.value != null) { - if (!isNaN(this.value)) { - this._type = NodeGeometryBlockConnectionPointTypes.Float; - return this._type; - } - switch (this.value.getClassName()) { - case "Vector2": - this._type = NodeGeometryBlockConnectionPointTypes.Vector2; - return this._type; - case "Vector3": - this._type = NodeGeometryBlockConnectionPointTypes.Vector3; - return this._type; - case "Vector4": - this._type = NodeGeometryBlockConnectionPointTypes.Vector4; - return this._type; - case "Matrix": - this._type = NodeGeometryBlockConnectionPointTypes.Matrix; - return this._type; - } - } - } - return this._type; - } - /** - * Gets a boolean indicating that the current connection point is a contextual value - */ - get isContextual() { - return this._contextualSource !== NodeGeometryContextualSources.None; - } - /** - * Gets or sets the current contextual value - */ - get contextualValue() { - return this._contextualSource; - } - set contextualValue(value) { - this._contextualSource = value; - switch (value) { - case NodeGeometryContextualSources.Positions: - case NodeGeometryContextualSources.Normals: - this._type = NodeGeometryBlockConnectionPointTypes.Vector3; - break; - case NodeGeometryContextualSources.Colors: - case NodeGeometryContextualSources.Tangents: - this._type = NodeGeometryBlockConnectionPointTypes.Vector4; - break; - case NodeGeometryContextualSources.UV: - case NodeGeometryContextualSources.UV2: - case NodeGeometryContextualSources.UV3: - case NodeGeometryContextualSources.UV4: - case NodeGeometryContextualSources.UV5: - case NodeGeometryContextualSources.UV6: - this._type = NodeGeometryBlockConnectionPointTypes.Vector2; - break; - case NodeGeometryContextualSources.VertexID: - case NodeGeometryContextualSources.GeometryID: - case NodeGeometryContextualSources.CollectionID: - case NodeGeometryContextualSources.FaceID: - case NodeGeometryContextualSources.LoopID: - this._type = NodeGeometryBlockConnectionPointTypes.Int; - break; - } - } - /** - * Creates a new InputBlock - * @param name defines the block name - * @param type defines the type of the input (can be set to NodeGeometryBlockConnectionPointTypes.AutoDetect) - */ - constructor(name, type = NodeGeometryBlockConnectionPointTypes.AutoDetect) { - super(name); - this._type = NodeGeometryBlockConnectionPointTypes.Undefined; - this._contextualSource = NodeGeometryContextualSources.None; - /** Gets or set a value used to limit the range of float values */ - this.min = 0; - /** Gets or set a value used to limit the range of float values */ - this.max = 0; - /** Gets or sets the group to use to display this block in the Inspector */ - this.groupInInspector = ""; - /** Gets an observable raised when the value is changed */ - this.onValueChangedObservable = new observable_Observable(); - this._type = type; - this.setDefaultValue(); - this.registerOutput("output", type); - } - /** - * Gets or sets the value of that point. - * Please note that this value will be ignored if valueCallback is defined - */ - get value() { - return this._storedValue; - } - set value(value) { - if (this.type === NodeGeometryBlockConnectionPointTypes.Float) { - if (this.min !== this.max) { - value = Math.max(this.min, value); - value = Math.min(this.max, value); - } - } - this._storedValue = value; - this.onValueChangedObservable.notifyObservers(this); - } - /** - * Gets or sets a callback used to get the value of that point. - * Please note that setting this value will force the connection point to ignore the value property - */ - get valueCallback() { - return this._valueCallback; - } - set valueCallback(value) { - this._valueCallback = value; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "GeometryInputBlock"; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - /** - * Set the input block to its default value (based on its type) - */ - setDefaultValue() { - this.contextualValue = NodeGeometryContextualSources.None; - switch (this.type) { - case NodeGeometryBlockConnectionPointTypes.Int: - case NodeGeometryBlockConnectionPointTypes.Float: - this.value = 0; - break; - case NodeGeometryBlockConnectionPointTypes.Vector2: - this.value = math_vector_Vector2.Zero(); - break; - case NodeGeometryBlockConnectionPointTypes.Vector3: - this.value = math_vector_Vector3.Zero(); - break; - case NodeGeometryBlockConnectionPointTypes.Vector4: - this.value = math_vector_Vector4.Zero(); - break; - case NodeGeometryBlockConnectionPointTypes.Matrix: - this.value = math_vector_Matrix.Identity(); - break; - } - } - _buildBlock(state) { - super._buildBlock(state); - if (this.isContextual) { - this.output._storedValue = null; - this.output._storedFunction = (state) => { - return state.getContextualValue(this._contextualSource); - }; - } - else { - this.output._storedFunction = null; - this.output._storedValue = this.value; - } - } - dispose() { - this.onValueChangedObservable.clear(); - super.dispose(); - } - _dumpPropertiesCode() { - const variableName = this._codeVariableName; - if (this.isContextual) { - return (super._dumpPropertiesCode() + `${variableName}.contextualValue = BABYLON.NodeGeometryContextualSources.${NodeGeometryContextualSources[this._contextualSource]};\n`); - } - const codes = []; - let valueString = ""; - switch (this.type) { - case NodeGeometryBlockConnectionPointTypes.Float: - case NodeGeometryBlockConnectionPointTypes.Int: - valueString = `${this.value}`; - break; - case NodeGeometryBlockConnectionPointTypes.Vector2: - valueString = `new BABYLON.Vector2(${this.value.x}, ${this.value.y})`; - break; - case NodeGeometryBlockConnectionPointTypes.Vector3: - valueString = `new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`; - break; - case NodeGeometryBlockConnectionPointTypes.Vector4: - valueString = `new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`; - break; - } - // Common Property "Value" - codes.push(`${variableName}.value = ${valueString}`); - // Float-Value-Specific Properties - if (this.type === NodeGeometryBlockConnectionPointTypes.Float || this.type === NodeGeometryBlockConnectionPointTypes.Int) { - codes.push(`${variableName}.min = ${this.min}`, `${variableName}.max = ${this.max}`); - } - codes.push(""); - return super._dumpPropertiesCode() + codes.join(";\n"); - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.type = this.type; - serializationObject.contextualValue = this.contextualValue; - serializationObject.min = this.min; - serializationObject.max = this.max; - serializationObject.groupInInspector = this.groupInInspector; - if (this._storedValue !== null && !this.isContextual) { - if (this._storedValue.asArray) { - serializationObject.valueType = "BABYLON." + this._storedValue.getClassName(); - serializationObject.value = this._storedValue.asArray(); - } - else { - serializationObject.valueType = "number"; - serializationObject.value = this._storedValue; - } - } - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this._type = serializationObject.type; - this.contextualValue = serializationObject.contextualValue; - this.min = serializationObject.min || 0; - this.max = serializationObject.max || 0; - this.groupInInspector = serializationObject.groupInInspector || ""; - if (!serializationObject.valueType) { - return; - } - if (serializationObject.valueType === "number") { - this._storedValue = serializationObject.value; - } - else { - const valueType = GetClass(serializationObject.valueType); - if (valueType) { - this._storedValue = valueType.FromArray(serializationObject.value); - } - } - } -} -RegisterClass("BABYLON.GeometryInputBlock", GeometryInputBlock); -//# sourceMappingURL=geometryInputBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/boxBlock.js - - - - - - - -/** - * Defines a block used to generate box geometry data - */ -class BoxBlock extends NodeGeometryBlock { - /** - * Create a new BoxBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - this.registerInput("size", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("width", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("depth", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1); - this.registerInput("subdivisionsX", NodeGeometryBlockConnectionPointTypes.Int, true, 0); - this.registerInput("subdivisionsY", NodeGeometryBlockConnectionPointTypes.Int, true, 0); - this.registerInput("subdivisionsZ", NodeGeometryBlockConnectionPointTypes.Int, true, 0); - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "BoxBlock"; - } - /** - * Gets the size input component - */ - get size() { - return this._inputs[0]; - } - /** - * Gets the width input component - */ - get width() { - return this._inputs[1]; - } - /** - * Gets the height input component - */ - get height() { - return this._inputs[2]; - } - /** - * Gets the depth input component - */ - get depth() { - return this._inputs[3]; - } - /** - * Gets the subdivisions input component - */ - get subdivisions() { - return this._inputs[4]; - } - /** - * Gets the subdivisionsX input component - */ - get subdivisionsX() { - return this._inputs[5]; - } - /** - * Gets the subdivisionsY input component - */ - get subdivisionsY() { - return this._inputs[6]; - } - /** - * Gets the subdivisionsZ input component - */ - get subdivisionsZ() { - return this._inputs[7]; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - autoConfigure() { - if (this.size.isConnected) { - return; - } - if (!this.width.isConnected && !this.height.isConnected && !this.depth.isConnected) { - const sizeInput = new GeometryInputBlock("Size"); - sizeInput.value = 1; - sizeInput.output.connectTo(this.size); - return; - } - if (!this.width.isConnected) { - const widthInput = new GeometryInputBlock("Width"); - widthInput.value = 1; - widthInput.output.connectTo(this.width); - } - if (!this.height.isConnected) { - const heightInput = new GeometryInputBlock("Height"); - heightInput.value = 1; - heightInput.output.connectTo(this.height); - } - if (!this.depth.isConnected) { - const depthInput = new GeometryInputBlock("Depth"); - depthInput.value = 1; - depthInput.output.connectTo(this.depth); - } - } - _buildBlock(state) { - const options = {}; - const func = (state) => { - options.size = this.size.getConnectedValue(state); - options.width = this.width.getConnectedValue(state); - options.height = this.height.getConnectedValue(state); - options.depth = this.depth.getConnectedValue(state); - const subdivisions = this.subdivisions.getConnectedValue(state); - const subdivisionsX = this.subdivisionsX.getConnectedValue(state); - const subdivisionsY = this.subdivisionsY.getConnectedValue(state); - const subdivisionsZ = this.subdivisionsZ.getConnectedValue(state); - if (subdivisions) { - options.segments = subdivisions; - } - if (subdivisionsX) { - options.widthSegments = subdivisionsX; - } - if (subdivisionsY) { - options.heightSegments = subdivisionsY; - } - if (subdivisionsZ) { - options.depthSegments = subdivisionsZ; - } - // Append vertex data from the plane builder - return CreateSegmentedBoxVertexData(options); - }; - if (this.evaluateContext) { - this.geometry._storedFunction = func; - } - else { - this.geometry._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], BoxBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.BoxBlock", BoxBlock); -//# sourceMappingURL=boxBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/nodeGeometry.js - - - - - - - - - - - - - -/** - * Defines a node based geometry - * @see demo at https://playground.babylonjs.com#PYY6XE#69 - */ -class NodeGeometry { - /** Get the inspector from bundle or global */ - _getGlobalNodeGeometryEditor() { - // UMD Global name detection from Webpack Bundle UMD Name. - if (typeof NODEGEOMETRYEDITOR !== "undefined") { - return NODEGEOMETRYEDITOR; - } - // In case of module let's check the global emitted from the editor entry point. - if (typeof BABYLON !== "undefined" && typeof BABYLON.NodeGeometryEditor !== "undefined") { - return BABYLON; - } - return undefined; - } - /** - * Gets the time spent to build this block (in ms) - */ - get buildExecutionTime() { - return this._buildExecutionTime; - } - /** - * Creates a new geometry - * @param name defines the name of the geometry - */ - constructor(name) { - this._buildId = NodeGeometry._BuildIdGenerator++; - this._buildWasSuccessful = false; - this._vertexData = null; - this._buildExecutionTime = 0; - // eslint-disable-next-line @typescript-eslint/naming-convention - this.BJSNODEGEOMETRYEDITOR = this._getGlobalNodeGeometryEditor(); - /** - * Gets or sets data used by visual editor - * @see https://nge.babylonjs.com - */ - this.editorData = null; - /** - * Gets an array of blocks that needs to be serialized even if they are not yet connected - */ - this.attachedBlocks = new Array(); - /** - * Observable raised when the geometry is built - */ - this.onBuildObservable = new observable_Observable(); - /** Gets or sets the GeometryOutputBlock used to gather the final geometry data */ - this.outputBlock = null; - this.name = name; - } - /** - * Gets the current class name of the geometry e.g. "NodeGeometry" - * @returns the class name - */ - getClassName() { - return "NodeGeometry"; - } - /** - * Get a block by its name - * @param name defines the name of the block to retrieve - * @returns the required block or null if not found - */ - getBlockByName(name) { - let result = null; - for (const block of this.attachedBlocks) { - if (block.name === name) { - if (!result) { - result = block; - } - else { - tools_Tools.Warn("More than one block was found with the name `" + name + "`"); - return result; - } - } - } - return result; - } - /** - * Get a block using a predicate - * @param predicate defines the predicate used to find the good candidate - * @returns the required block or null if not found - */ - getBlockByPredicate(predicate) { - for (const block of this.attachedBlocks) { - if (predicate(block)) { - return block; - } - } - return null; - } - /** - * Gets the list of input blocks attached to this material - * @returns an array of InputBlocks - */ - getInputBlocks() { - const blocks = []; - for (const block of this.attachedBlocks) { - if (block.isInput) { - blocks.push(block); - } - } - return blocks; - } - /** - * Launch the node geometry editor - * @param config Define the configuration of the editor - * @returns a promise fulfilled when the node editor is visible - */ - edit(config) { - return new Promise((resolve) => { - this.BJSNODEGEOMETRYEDITOR = this.BJSNODEGEOMETRYEDITOR || this._getGlobalNodeGeometryEditor(); - if (typeof this.BJSNODEGEOMETRYEDITOR == "undefined") { - const editorUrl = config && config.editorURL ? config.editorURL : NodeGeometry.EditorURL; - // Load editor and add it to the DOM - tools_Tools.LoadScript(editorUrl, () => { - this.BJSNODEGEOMETRYEDITOR = this.BJSNODEGEOMETRYEDITOR || this._getGlobalNodeGeometryEditor(); - this._createNodeEditor(config === null || config === void 0 ? void 0 : config.nodeGeometryEditorConfig); - resolve(); - }); - } - else { - // Otherwise creates the editor - this._createNodeEditor(config === null || config === void 0 ? void 0 : config.nodeGeometryEditorConfig); - resolve(); - } - }); - } - /** Creates the node editor window. */ - _createNodeEditor(additionalConfig) { - const nodeEditorConfig = Object.assign({ nodeGeometry: this }, additionalConfig); - this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(nodeEditorConfig); - } - /** - * Build the final geometry - * @param verbose defines if the build should log activity - * @param updateBuildId defines if the internal build Id should be updated (default is true) - * @param autoConfigure defines if the autoConfigure method should be called when initializing blocks (default is false) - */ - build(verbose = false, updateBuildId = true, autoConfigure = false) { - this._buildWasSuccessful = false; - if (!this.outputBlock) { - throw "You must define the outputBlock property before building the geometry"; - } - const now = precisionDate_PrecisionDate.Now; - // Initialize blocks - this._initializeBlock(this.outputBlock, autoConfigure); - // Build - const state = new NodeGeometryBuildState(); - state.buildId = this._buildId; - state.verbose = verbose; - this.outputBlock.build(state); - if (updateBuildId) { - this._buildId = NodeGeometry._BuildIdGenerator++; - } - this._buildExecutionTime = precisionDate_PrecisionDate.Now - now; - // Errors - state.emitErrors(); - this._buildWasSuccessful = true; - this._vertexData = state.vertexData; - this.onBuildObservable.notifyObservers(this); - } - /** - * Creates a mesh from the geometry blocks - * @param name defines the name of the mesh - * @param scene The scene the mesh is scoped to - * @returns The new mesh - */ - createMesh(name, scene = null) { - if (!this._buildWasSuccessful) { - this.build(); - } - if (!this._vertexData) { - return null; - } - const mesh = new mesh_Mesh(name, scene); - this._vertexData.applyToMesh(mesh); - mesh._internalMetadata = mesh._internalMetadata || {}; - mesh._internalMetadata.nodeGeometry = this; - return mesh; - } - /** - * Creates a mesh from the geometry blocks - * @param mesh the mesh to update - * @returns True if successfully updated - */ - updateMesh(mesh) { - if (!this._buildWasSuccessful) { - this.build(); - } - if (!this._vertexData) { - return false; - } - this._vertexData.applyToMesh(mesh); - mesh._internalMetadata = mesh._internalMetadata || {}; - mesh._internalMetadata.nodeGeometry = this; - return mesh; - } - _initializeBlock(node, autoConfigure = true) { - node.initialize(); - if (autoConfigure) { - node.autoConfigure(); - } - node._preparationId = this._buildId; - if (this.attachedBlocks.indexOf(node) === -1) { - this.attachedBlocks.push(node); - } - for (const input of node.inputs) { - const connectedPoint = input.connectedPoint; - if (connectedPoint) { - const block = connectedPoint.ownerBlock; - if (block !== node) { - this._initializeBlock(block, autoConfigure); - } - } - } - } - /** - * Clear the current geometry - */ - clear() { - this.outputBlock = null; - this.attachedBlocks.length = 0; - } - /** - * Remove a block from the current geometry - * @param block defines the block to remove - */ - removeBlock(block) { - const attachedBlockIndex = this.attachedBlocks.indexOf(block); - if (attachedBlockIndex > -1) { - this.attachedBlocks.splice(attachedBlockIndex, 1); - } - if (block === this.outputBlock) { - this.outputBlock = null; - } - } - /** - * Clear the current graph and load a new one from a serialization object - * @param source defines the JSON representation of the geometry - * @param merge defines whether or not the source must be merged or replace the current content - */ - parseSerializedObject(source, merge = false) { - if (!merge) { - this.clear(); - } - const map = {}; - // Create blocks - for (const parsedBlock of source.blocks) { - const blockType = GetClass(parsedBlock.customType); - if (blockType) { - const block = new blockType(); - block._deserialize(parsedBlock); - map[parsedBlock.id] = block; - this.attachedBlocks.push(block); - } - } - // Reconnect teleportation - for (const block of this.attachedBlocks) { - if (block.isTeleportOut) { - const teleportOut = block; - const id = teleportOut._tempEntryPointUniqueId; - if (id) { - const source = map[id]; - source.attachToEndpoint(teleportOut); - } - } - } - // Connections - Starts with input blocks only (except if in "merge" mode where we scan all blocks) - for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) { - const parsedBlock = source.blocks[blockIndex]; - const block = map[parsedBlock.id]; - if (!block) { - continue; - } - if (block.inputs.length && parsedBlock.inputs.some((i) => i.targetConnectionName) && !merge) { - continue; - } - this._restoreConnections(block, source, map); - } - // Outputs - if (source.outputNodeId) { - this.outputBlock = map[source.outputNodeId]; - } - // UI related info - if (source.locations || (source.editorData && source.editorData.locations)) { - const locations = source.locations || source.editorData.locations; - for (const location of locations) { - if (map[location.blockId]) { - location.blockId = map[location.blockId].uniqueId; - } - } - if (merge && this.editorData && this.editorData.locations) { - locations.concat(this.editorData.locations); - } - if (source.locations) { - this.editorData = { - locations: locations, - }; - } - else { - this.editorData = source.editorData; - this.editorData.locations = locations; - } - const blockMap = []; - for (const key in map) { - blockMap[key] = map[key].uniqueId; - } - this.editorData.map = blockMap; - } - this.comment = source.comment; - } - _restoreConnections(block, source, map) { - for (const outputPoint of block.outputs) { - for (const candidate of source.blocks) { - const target = map[candidate.id]; - if (!target) { - continue; - } - for (const input of candidate.inputs) { - if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) { - const inputPoint = target.getInputByName(input.inputName); - if (!inputPoint || inputPoint.isConnected) { - continue; - } - outputPoint.connectTo(inputPoint, true); - this._restoreConnections(target, source, map); - continue; - } - } - } - } - } - /** - * Generate a string containing the code declaration required to create an equivalent of this geometry - * @returns a string - */ - generateCode() { - let alreadyDumped = []; - const blocks = []; - const uniqueNames = ["const", "var", "let"]; - // Gets active blocks - if (this.outputBlock) { - this._gatherBlocks(this.outputBlock, blocks); - } - // Generate - let codeString = `let nodeGeometry = new BABYLON.NodeGeometry("${this.name || "node geometry"}");\n`; - for (const node of blocks) { - if (node.isInput && alreadyDumped.indexOf(node) === -1) { - codeString += node._dumpCode(uniqueNames, alreadyDumped); - } - } - if (this.outputBlock) { - // Connections - alreadyDumped = []; - codeString += "\n`;// Connections\n`;"; - codeString += this.outputBlock._dumpCodeForOutputConnections(alreadyDumped); - // Output nodes - codeString += "\n`;// Output nodes\n`;"; - codeString += `nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`; - codeString += `nodeGeometry.build();\n`; - } - return codeString; - } - _gatherBlocks(rootNode, list) { - if (list.indexOf(rootNode) !== -1) { - return; - } - list.push(rootNode); - for (const input of rootNode.inputs) { - const connectedPoint = input.connectedPoint; - if (connectedPoint) { - const block = connectedPoint.ownerBlock; - if (block !== rootNode) { - this._gatherBlocks(block, list); - } - } - } - // Teleportation - if (rootNode.isTeleportOut) { - const block = rootNode; - if (block.entryPoint) { - this._gatherBlocks(block.entryPoint, list); - } - } - } - /** - * Clear the current geometry and set it to a default state - */ - setToDefault() { - this.clear(); - this.editorData = null; - // Source - const dataBlock = new BoxBlock("Box"); - dataBlock.autoConfigure(); - // Final output - const output = new GeometryOutputBlock("Geometry Output"); - dataBlock.geometry.connectTo(output.geometry); - this.outputBlock = output; - } - /** - * Makes a duplicate of the current geometry. - * @param name defines the name to use for the new geometry - */ - clone(name) { - const serializationObject = this.serialize(); - const clone = decorators_SerializationHelper.Clone(() => new NodeGeometry(name), this); - clone.name = name; - clone.parseSerializedObject(serializationObject); - clone._buildId = this._buildId; - clone.build(false); - return clone; - } - /** - * Serializes this geometry in a JSON representation - * @param saveMeshData defines a boolean indicating that mesh data must be saved as well - * @param selectedBlocks defines the list of blocks to save (if null the whole geometry will be saved) - * @returns the serialized geometry object - */ - serialize(saveMeshData, selectedBlocks) { - const serializationObject = selectedBlocks ? {} : decorators_SerializationHelper.Serialize(this); - serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy - let blocks = []; - if (selectedBlocks) { - blocks = selectedBlocks; - } - else { - serializationObject.customType = "BABYLON.NodeGeometry"; - if (this.outputBlock) { - serializationObject.outputNodeId = this.outputBlock.uniqueId; - } - } - // Blocks - serializationObject.blocks = []; - for (const block of blocks) { - serializationObject.blocks.push(block.serialize(saveMeshData)); - } - if (!selectedBlocks) { - for (const block of this.attachedBlocks) { - if (blocks.indexOf(block) !== -1) { - continue; - } - serializationObject.blocks.push(block.serialize(saveMeshData)); - } - } - return serializationObject; - } - /** - * Disposes the ressources - */ - dispose() { - for (const block of this.attachedBlocks) { - block.dispose(); - } - this.attachedBlocks.length = 0; - this.onBuildObservable.clear(); - } - /** - * Creates a new node geometry set to default basic configuration - * @param name defines the name of the geometry - * @returns a new NodeGeometry - */ - static CreateDefault(name) { - const nodeGeometry = new NodeGeometry(name); - nodeGeometry.setToDefault(); - nodeGeometry.build(); - return nodeGeometry; - } - /** - * Creates a node geometry from parsed geometry data - * @param source defines the JSON representation of the geometry - * @returns a new node geometry - */ - static Parse(source) { - const nodeGeometry = decorators_SerializationHelper.Parse(() => new NodeGeometry(source.name), source, null); - nodeGeometry.parseSerializedObject(source); - nodeGeometry.build(); - return nodeGeometry; - } - /** - * Creates a node geometry from a snippet saved by the node geometry editor - * @param snippetId defines the snippet to load - * @param nodeGeometry defines a node geometry to update (instead of creating a new one) - * @param skipBuild defines whether to build the node geometry - * @returns a promise that will resolve to the new node geometry - */ - static ParseFromSnippetAsync(snippetId, nodeGeometry, skipBuild = false) { - if (snippetId === "_BLANK") { - return Promise.resolve(NodeGeometry.CreateDefault("blank")); - } - return new Promise((resolve, reject) => { - const request = new webRequest_WebRequest(); - request.addEventListener("readystatechange", () => { - if (request.readyState == 4) { - if (request.status == 200) { - const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); - const serializationObject = JSON.parse(snippet.nodeGeometry); - if (!nodeGeometry) { - nodeGeometry = decorators_SerializationHelper.Parse(() => new NodeGeometry(snippetId), serializationObject, null); - } - nodeGeometry.parseSerializedObject(serializationObject); - nodeGeometry.snippetId = snippetId; - try { - if (!skipBuild) { - nodeGeometry.build(); - } - resolve(nodeGeometry); - } - catch (err) { - reject(err); - } - } - else { - reject("Unable to load the snippet " + snippetId); - } - } - }); - request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); - request.send(); - }); - } -} -NodeGeometry._BuildIdGenerator = 0; -/** Define the Url to load node editor script */ -NodeGeometry.EditorURL = `https://unpkg.com/babylonjs-node-geometry-editor@${engine_Engine.Version}/babylon.nodeGeometryEditor.js`; -/** Define the Url to load snippets */ -NodeGeometry.SnippetUrl = `https://snippet.babylonjs.com`; -__decorate([ - serialize() -], NodeGeometry.prototype, "name", void 0); -__decorate([ - serialize("comment") -], NodeGeometry.prototype, "comment", void 0); -//# sourceMappingURL=nodeGeometry.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Interfaces/nodeGeometryExecutionContext.js - -//# sourceMappingURL=nodeGeometryExecutionContext.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryOptimizeBlock.js - - - - - - - - -/** - * Block used to extract unique positions from a geometry - */ -class GeometryOptimizeBlock extends NodeGeometryBlock { - /** - * Creates a new GeometryOptimizeBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - /** - * Define the epsilon used to compare similar positions - */ - this.epsilon = math_constants_Epsilon; - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "GeometryOptimizeBlock"; - } - /** - * Gets the geometry component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - const func = (state) => { - if (!this.geometry.isConnected) { - return null; - } - const vertexData = this.geometry.getConnectedValue(state); - const newPositions = []; - const newIndicesMap = {}; - for (let index = 0; index < vertexData.positions.length; index += 3) { - const x = vertexData.positions[index]; - const y = vertexData.positions[index + 1]; - const z = vertexData.positions[index + 2]; - // check if we already have it - let found = false; - for (let checkIndex = 0; checkIndex < newPositions.length; checkIndex += 3) { - if (math_scalar_Scalar.WithinEpsilon(x, newPositions[checkIndex], this.epsilon) && - math_scalar_Scalar.WithinEpsilon(y, newPositions[checkIndex + 1], this.epsilon) && - math_scalar_Scalar.WithinEpsilon(z, newPositions[checkIndex + 2], this.epsilon)) { - newIndicesMap[index / 3] = checkIndex / 3; - found = true; - continue; - } - } - if (!found) { - newIndicesMap[index / 3] = newPositions.length / 3; - newPositions.push(x, y, z); - } - } - const newVertexData = new mesh_vertexData_VertexData(); - newVertexData.positions = newPositions; - newVertexData.indices = vertexData.indices.map((index) => newIndicesMap[index]); - return newVertexData; - }; - if (this.evaluateContext) { - this.output._storedFunction = func; - } - else { - this.output._storedValue = func(state); - } - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - codeString += `${this._codeVariableName}.epsilon = ${this.epsilon};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - serializationObject.epsilon = this.epsilon; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - this.epsilon = serializationObject.epsilon; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], GeometryOptimizeBlock.prototype, "evaluateContext", void 0); -__decorate([ - editableInPropertyPage("Epsilon", PropertyTypeForEdition.Float, "ADVANCED", { notifiers: { rebuild: true } }) -], GeometryOptimizeBlock.prototype, "epsilon", void 0); -RegisterClass("BABYLON.GeometryOptimizeBlock", GeometryOptimizeBlock); -//# sourceMappingURL=geometryOptimizeBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/planeBlock.js - - - - - - - -/** - * Defines a block used to generate plane geometry data - */ -class PlaneBlock extends NodeGeometryBlock { - /** - * Create a new PlaneBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - this.registerInput("size", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("width", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "PlaneBlock"; - } - /** - * Gets the size input component - */ - get size() { - return this._inputs[0]; - } - /** - * Gets the width input component - */ - get width() { - return this._inputs[1]; - } - /** - * Gets the height input component - */ - get height() { - return this._inputs[2]; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - autoConfigure() { - if (this.size.isConnected) { - return; - } - if (!this.width.isConnected && !this.height.isConnected) { - const sizeInput = new GeometryInputBlock("Size"); - sizeInput.value = 1; - sizeInput.output.connectTo(this.size); - return; - } - if (!this.width.isConnected) { - const widthInput = new GeometryInputBlock("Width"); - widthInput.value = 1; - widthInput.output.connectTo(this.width); - } - if (!this.height.isConnected) { - const heightInput = new GeometryInputBlock("Height"); - heightInput.value = 1; - heightInput.output.connectTo(this.height); - } - } - _buildBlock(state) { - const options = {}; - const func = (state) => { - options.size = this.size.getConnectedValue(state); - options.width = this.width.getConnectedValue(state); - options.height = this.height.getConnectedValue(state); - // Append vertex data from the plane builder - return CreatePlaneVertexData(options); - }; - if (this.evaluateContext) { - this.geometry._storedFunction = func; - } - else { - this.geometry._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], PlaneBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.PlaneBlock", PlaneBlock); -//# sourceMappingURL=planeBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/meshBlock.js - - - - -/** - * Defines a block used to generate a user defined mesh geometry data - */ -class MeshBlock extends NodeGeometryBlock { - /** - * Gets or sets the mesh to use to get vertex data - */ - get mesh() { - return this._mesh; - } - set mesh(value) { - this._mesh = value; - } - /** - * Create a new MeshBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this._cachedVertexData = null; - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MeshBlock"; - } - /** - * Gets a boolean indicating if the block is using cached data - */ - get isUsingCachedData() { - return !this.mesh && !!this._cachedVertexData; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - _buildBlock() { - if (!this._mesh) { - if (this._cachedVertexData) { - this.geometry._storedValue = this._cachedVertexData.clone(); - } - else { - this.geometry._storedValue = null; - } - return; - } - this.geometry._storedValue = mesh_vertexData_VertexData.ExtractFromMesh(this._mesh, false, true); - this._cachedVertexData = null; - } - /** - * Serializes this block in a JSON representation - * @param saveMeshData defines a boolean indicating that mesh data must be saved as well - * @returns the serialized block object - */ - serialize(saveMeshData) { - const serializationObject = super.serialize(); - if (saveMeshData) { - if (this._mesh) { - serializationObject.cachedVertexData = mesh_vertexData_VertexData.ExtractFromMesh(this._mesh, false, true).serialize(); - } - else if (this._cachedVertexData) { - serializationObject.cachedVertexData = this._cachedVertexData.serialize(); - } - } - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - if (serializationObject.cachedVertexData) { - this._cachedVertexData = mesh_vertexData_VertexData.Parse(serializationObject.cachedVertexData); - } - } -} -RegisterClass("BABYLON.MeshBlock", MeshBlock); -//# sourceMappingURL=meshBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/icoSphereBlock.js - - - - - - - -/** - * Defines a block used to generate icosphere geometry data - */ -class IcoSphereBlock extends NodeGeometryBlock { - /** - * Create a new IcoSphereBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("radiusX", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("radiusY", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("radiusZ", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 4); - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "IcoSphereBlock"; - } - /** - * Gets the radius input component - */ - get radius() { - return this._inputs[0]; - } - /** - * Gets the radiusX input component - */ - get radiusX() { - return this._inputs[1]; - } - /** - * Gets the radiusY input component - */ - get radiusY() { - return this._inputs[2]; - } - /** - * Gets the radiusZ input component - */ - get radiusZ() { - return this._inputs[3]; - } - /** - * Gets the subdivisions input component - */ - get subdivisions() { - return this._inputs[4]; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.radius.isConnected) { - const radiusInput = new GeometryInputBlock("Radius"); - radiusInput.value = 0.2; - radiusInput.output.connectTo(this.radius); - } - } - _buildBlock(state) { - const options = {}; - const func = (state) => { - options.radius = this.radius.getConnectedValue(state); - options.subdivisions = this.subdivisions.getConnectedValue(state); - options.radiusX = this.radiusX.getConnectedValue(state); - options.radiusY = this.radiusY.getConnectedValue(state); - options.radiusZ = this.radiusZ.getConnectedValue(state); - // Append vertex data from the plane builder - return CreateIcoSphereVertexData(options); - }; - if (this.evaluateContext) { - this.geometry._storedFunction = func; - } - else { - this.geometry._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], IcoSphereBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.IcoSphereBlock", IcoSphereBlock); -//# sourceMappingURL=icoSphereBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/sphereBlock.js - - - - - - - -/** - * Defines a block used to generate sphere geometry data - */ -class SphereBlock extends NodeGeometryBlock { - /** - * Create a new SphereBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - this.registerInput("segments", NodeGeometryBlockConnectionPointTypes.Int, true, 32); - this.registerInput("diameter", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("diameterX", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("diameterY", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("diameterZ", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("arc", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("slice", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SphereBlock"; - } - /** - * Gets the segments input component - */ - get segments() { - return this._inputs[0]; - } - /** - * Gets the diameter input component - */ - get diameter() { - return this._inputs[1]; - } - /** - * Gets the diameterX input component - */ - get diameterX() { - return this._inputs[2]; - } - /** - * Gets the diameterY input component - */ - get diameterY() { - return this._inputs[3]; - } - /** - * Gets the diameterZ input component - */ - get diameterZ() { - return this._inputs[4]; - } - /** - * Gets the arc input component - */ - get arc() { - return this._inputs[5]; - } - /** - * Gets the slice input component - */ - get slice() { - return this._inputs[6]; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.diameter.isConnected) { - const diameterInput = new GeometryInputBlock("Diameter"); - diameterInput.value = 1; - diameterInput.output.connectTo(this.diameter); - } - } - _buildBlock(state) { - const options = {}; - const func = (state) => { - options.segments = this.segments.getConnectedValue(state); - options.diameter = this.diameter.getConnectedValue(state); - options.diameterX = this.diameterX.getConnectedValue(state); - options.diameterY = this.diameterY.getConnectedValue(state); - options.diameterZ = this.diameterZ.getConnectedValue(state); - options.arc = this.arc.getConnectedValue(state); - options.slice = this.slice.getConnectedValue(state); - // Append vertex data from the plane builder - return CreateSphereVertexData(options); - }; - if (this.evaluateContext) { - this.geometry._storedFunction = func; - } - else { - this.geometry._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], SphereBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.SphereBlock", SphereBlock); -//# sourceMappingURL=sphereBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/gridBlock.js - - - - - - - -/** - * Defines a block used to generate grid geometry data - */ -class GridBlock extends NodeGeometryBlock { - /** - * Create a new GridBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - this.registerInput("width", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1); - this.registerInput("subdivisionsX", NodeGeometryBlockConnectionPointTypes.Int, true, 0); - this.registerInput("subdivisionsY", NodeGeometryBlockConnectionPointTypes.Int, true, 0); - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "GridBlock"; - } - /** - * Gets the width input component - */ - get width() { - return this._inputs[0]; - } - /** - * Gets the height input component - */ - get height() { - return this._inputs[1]; - } - /** - * Gets the subdivisions input component - */ - get subdivisions() { - return this._inputs[2]; - } - /** - * Gets the subdivisionsX input component - */ - get subdivisionsX() { - return this._inputs[3]; - } - /** - * Gets the subdivisionsY input component - */ - get subdivisionsY() { - return this._inputs[4]; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.width.isConnected) { - const widthInput = new GeometryInputBlock("Width"); - widthInput.value = 1; - widthInput.output.connectTo(this.width); - } - if (!this.height.isConnected) { - const heightInput = new GeometryInputBlock("Height"); - heightInput.value = 1; - heightInput.output.connectTo(this.height); - } - } - _buildBlock(state) { - const options = {}; - const func = (state) => { - options.width = this.width.getConnectedValue(state); - options.height = this.height.getConnectedValue(state); - options.subdivisions = this.subdivisions.getConnectedValue(state); - options.subdivisionsX = this.subdivisionsX.getConnectedValue(state); - options.subdivisionsY = this.subdivisionsY.getConnectedValue(state); - // Append vertex data from the plane builder - return CreateGroundVertexData(options); - }; - if (this.evaluateContext) { - this.geometry._storedFunction = func; - } - else { - this.geometry._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], GridBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.GridBlock", GridBlock); -//# sourceMappingURL=gridBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/torusBlock.js - - - - - - - -/** - * Defines a block used to generate torus geometry data - */ -class TorusBlock extends NodeGeometryBlock { - /** - * Create a new TorusBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - this.registerInput("diameter", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("thickness", NodeGeometryBlockConnectionPointTypes.Float, true, 0.5); - this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 16); - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "TorusBlock"; - } - /** - * Gets the diameter input component - */ - get diameter() { - return this._inputs[0]; - } - /** - * Gets the thickness input component - */ - get thickness() { - return this._inputs[1]; - } - /** - * Gets the tessellation input component - */ - get tessellation() { - return this._inputs[2]; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.diameter.isConnected) { - const diameterInput = new GeometryInputBlock("Diameter"); - diameterInput.value = 1; - diameterInput.output.connectTo(this.diameter); - } - } - _buildBlock(state) { - const options = {}; - const func = (state) => { - options.thickness = this.thickness.getConnectedValue(state); - options.diameter = this.diameter.getConnectedValue(state); - options.tessellation = this.tessellation.getConnectedValue(state); - // Append vertex data from the plane builder - return CreateTorusVertexData(options); - }; - if (this.evaluateContext) { - this.geometry._storedFunction = func; - } - else { - this.geometry._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], TorusBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.TorusBlock", TorusBlock); -//# sourceMappingURL=torusBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/cylinderBlock.js - - - - - - - -/** - * Defines a block used to generate cylinder geometry data - */ -class CylinderBlock extends NodeGeometryBlock { - /** - * Create a new SphereBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 25); - this.registerInput("diameter", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("diameterTop", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("diameterBottom", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 1); - this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 24); - this.registerInput("arc", NodeGeometryBlockConnectionPointTypes.Float, true, 1.0); - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "CylinderBlock"; - } - /** - * Gets the height input component - */ - get height() { - return this._inputs[0]; - } - /** - * Gets the diameter input component - */ - get diameter() { - return this._inputs[1]; - } - /** - * Gets the diameterTop input component - */ - get diameterTop() { - return this._inputs[2]; - } - /** - * Gets the diameterBottom input component - */ - get diameterBottom() { - return this._inputs[3]; - } - /** - * Gets the subdivisions input component - */ - get subdivisions() { - return this._inputs[4]; - } - /** - * Gets the tessellation input component - */ - get tessellation() { - return this._inputs[5]; - } - /** - * Gets the arc input component - */ - get arc() { - return this._inputs[6]; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.diameter.isConnected) { - const diameterInput = new GeometryInputBlock("Diameter"); - diameterInput.value = 1; - diameterInput.output.connectTo(this.diameter); - } - if (!this.height.isConnected) { - const heightInput = new GeometryInputBlock("Height"); - heightInput.value = 1; - heightInput.output.connectTo(this.height); - } - } - _buildBlock(state) { - const options = {}; - const func = (state) => { - options.height = this.height.getConnectedValue(state); - options.diameter = this.diameter.getConnectedValue(state); - if (!options.diameter) { - options.diameterTop = this.diameterTop.getConnectedValue(state); - options.diameterBottom = this.diameterBottom.getConnectedValue(state); - } - options.tessellation = this.tessellation.getConnectedValue(state); - options.subdivisions = this.subdivisions.getConnectedValue(state); - options.arc = this.arc.getConnectedValue(state); - // Append vertex data from the plane builder - return CreateCylinderVertexData(options); - }; - if (this.evaluateContext) { - this.geometry._storedFunction = func; - } - else { - this.geometry._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], CylinderBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.CylinderBlock", CylinderBlock); -//# sourceMappingURL=cylinderBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/capsuleBlock.js - - - - - - - -/** - * Defines a block used to generate capsule geometry data - */ -class CapsuleBlock extends NodeGeometryBlock { - /** - * Create a new CapsuleBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - this.registerInput("height", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Float, true, 0.25); - this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 16); - this.registerInput("subdivisions", NodeGeometryBlockConnectionPointTypes.Int, true, 2); - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "CapsuleBlock"; - } - /** - * Gets the height input component - */ - get height() { - return this._inputs[0]; - } - /** - * Gets the radius input component - */ - get radius() { - return this._inputs[1]; - } - /** - * Gets the tessellation input component - */ - get tessellation() { - return this._inputs[2]; - } - /** - * Gets the subdivisions input component - */ - get subdivisions() { - return this._inputs[3]; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.height.isConnected) { - const heightInput = new GeometryInputBlock("Height"); - heightInput.value = 1; - heightInput.output.connectTo(this.height); - } - if (!this.radius.isConnected) { - const radiusInput = new GeometryInputBlock("Radius"); - radiusInput.value = 0.2; - radiusInput.output.connectTo(this.radius); - } - } - _buildBlock(state) { - const options = {}; - const func = (state) => { - options.height = this.height.getConnectedValue(state); - options.radius = this.radius.getConnectedValue(state); - options.tessellation = this.tessellation.getConnectedValue(state); - options.subdivisions = this.subdivisions.getConnectedValue(state); - // Append vertex data from the plane builder - return CreateCapsuleVertexData(options); - }; - if (this.evaluateContext) { - this.geometry._storedFunction = func; - } - else { - this.geometry._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], CapsuleBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.CapsuleBlock", CapsuleBlock); -//# sourceMappingURL=capsuleBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/discBlock.js - - - - - - - -/** - * Defines a block used to generate disc geometry data - */ -class DiscBlock extends NodeGeometryBlock { - /** - * Create a new DiscBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - this.registerInput("radius", NodeGeometryBlockConnectionPointTypes.Float, true, 0.5); - this.registerInput("tessellation", NodeGeometryBlockConnectionPointTypes.Int, true, 64); - this.registerInput("arc", NodeGeometryBlockConnectionPointTypes.Float, true, 1.0); - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "DiscBlock"; - } - /** - * Gets the radius input component - */ - get radius() { - return this._inputs[0]; - } - /** - * Gets the tessellation input component - */ - get tessellation() { - return this._inputs[1]; - } - /** - * Gets the arc input component - */ - get arc() { - return this._inputs[2]; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.radius.isConnected) { - const radiusInput = new GeometryInputBlock("Radius"); - radiusInput.value = 0.2; - radiusInput.output.connectTo(this.radius); - } - } - _buildBlock(state) { - const options = {}; - const func = (state) => { - options.radius = this.radius.getConnectedValue(state); - options.tessellation = this.tessellation.getConnectedValue(state); - options.arc = this.arc.getConnectedValue(state); - // Append vertex data from the plane builder - return CreateDiscVertexData(options); - }; - if (this.evaluateContext) { - this.geometry._storedFunction = func; - } - else { - this.geometry._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], DiscBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.DiscBlock", DiscBlock); -//# sourceMappingURL=discBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Sources/nullBlock.js - - - -/** - * Defines a block used to generate a null geometry data - */ -class NullBlock extends NodeGeometryBlock { - /** - * Create a new NullBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerOutput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "NullBlock"; - } - /** - * Gets the geometry output component - */ - get geometry() { - return this._outputs[0]; - } - _buildBlock() { - this.geometry._storedValue = null; - } -} -RegisterClass("BABYLON.NullBlock", NullBlock); -//# sourceMappingURL=nullBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setPositionsBlock.js - - - -/** - * Block used to set positions for a geometry - */ -class SetPositionsBlock extends NodeGeometryBlock { - /** - * Create a new SetPositionsBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerInput("positions", NodeGeometryBlockConnectionPointTypes.Vector3); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current index in the current flow - * @returns the current index - */ - getExecutionIndex() { - return this._currentIndex; - } - /** - * Gets the current loop index in the current flow - * @returns the current loop index - */ - getExecutionLoopIndex() { - return this._currentIndex; - } - /** - * Gets the current face index in the current flow - * @returns the current face index - */ - getExecutionFaceIndex() { - return 0; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SetPositionsBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the positions input component - */ - get positions() { - return this._inputs[1]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - state.executionContext = this; - this._vertexData = this.geometry.getConnectedValue(state); - state.geometryContext = this._vertexData; - if (!this._vertexData || !this._vertexData.positions || !this.positions.isConnected) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = null; - return; - } - // Processing - const vertexCount = this._vertexData.positions.length / 3; - for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { - const tempVector3 = this.positions.getConnectedValue(state); - if (tempVector3) { - tempVector3.toArray(this._vertexData.positions, this._currentIndex * 3); - } - } - // Storage - this.output._storedValue = this._vertexData; - state.executionContext = null; - state.geometryContext = null; - } -} -RegisterClass("BABYLON.SetPositionsBlock", SetPositionsBlock); -//# sourceMappingURL=setPositionsBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setNormalsBlock.js - - - -/** - * Block used to set normals for a geometry - */ -class SetNormalsBlock extends NodeGeometryBlock { - /** - * Create a new SetNormalsBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerInput("normals", NodeGeometryBlockConnectionPointTypes.Vector3); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current index in the current flow - * @returns the current index - */ - getExecutionIndex() { - return this._currentIndex; - } - /** - * Gets the current loop index in the current flow - * @returns the current loop index - */ - getExecutionLoopIndex() { - return this._currentIndex; - } - /** - * Gets the current face index in the current flow - * @returns the current face index - */ - getExecutionFaceIndex() { - return 0; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SetNormalsBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the normals input component - */ - get normals() { - return this._inputs[1]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - state.executionContext = this; - this._vertexData = this.geometry.getConnectedValue(state); - state.geometryContext = this._vertexData; - if (!this._vertexData || !this._vertexData.positions) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = null; - return; - } - if (!this.normals.isConnected) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = this._vertexData; - return; - } - if (!this._vertexData.normals) { - this._vertexData.normals = []; - } - // Processing - const vertexCount = this._vertexData.positions.length / 3; - for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { - const tempVector3 = this.normals.getConnectedValue(state); - if (tempVector3) { - tempVector3.toArray(this._vertexData.normals, this._currentIndex * 3); - } - } - // Storage - this.output._storedValue = this._vertexData; - state.executionContext = null; - state.geometryContext = null; - } -} -RegisterClass("BABYLON.SetNormalsBlock", SetNormalsBlock); -//# sourceMappingURL=setNormalsBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setUVsBlock.js - - - - - -/** - * Block used to set texture coordinates for a geometry - */ -class SetUVsBlock extends NodeGeometryBlock { - /** - * Create a new SetUVsBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a value indicating which UV to set - */ - this.textureCoordinateIndex = 0; - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerInput("uvs", NodeGeometryBlockConnectionPointTypes.Vector2); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current index in the current flow - * @returns the current index - */ - getExecutionIndex() { - return this._currentIndex; - } - /** - * Gets the current loop index in the current flow - * @returns the current loop index - */ - getExecutionLoopIndex() { - return this._currentIndex; - } - /** - * Gets the current face index in the current flow - * @returns the current face index - */ - getExecutionFaceIndex() { - return 0; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SetUVsBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the uvs input component - */ - get uvs() { - return this._inputs[1]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - state.executionContext = this; - this._vertexData = this.geometry.getConnectedValue(state); - state.geometryContext = this._vertexData; - if (!this._vertexData || !this._vertexData.positions) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = null; - return; - } - if (!this.uvs.isConnected) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = this._vertexData; - return; - } - const uvs = []; - // Processing - const vertexCount = this._vertexData.positions.length / 3; - for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { - const tempVector2 = this.uvs.getConnectedValue(state); - if (tempVector2) { - tempVector2.toArray(uvs, this._currentIndex * 2); - } - } - switch (this.textureCoordinateIndex) { - case 0: - this._vertexData.uvs = uvs; - break; - case 1: - this._vertexData.uvs2 = uvs; - break; - case 2: - this._vertexData.uvs3 = uvs; - break; - case 3: - this._vertexData.uvs4 = uvs; - break; - case 4: - this._vertexData.uvs5 = uvs; - break; - case 5: - this._vertexData.uvs6 = uvs; - break; - } - // Storage - this.output._storedValue = this._vertexData; - state.executionContext = null; - state.geometryContext = null; - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.textureCoordinateIndex};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.textureCoordinateIndex = this.textureCoordinateIndex; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.textureCoordinateIndex = serializationObject.textureCoordinateIndex; - } -} -__decorate([ - editableInPropertyPage("Texture coordinates index", PropertyTypeForEdition.List, "ADVANCED", { - notifiers: { update: true }, - options: [ - { label: "UV1", value: 0 }, - { label: "UV2", value: 1 }, - { label: "UV3", value: 2 }, - { label: "UV4", value: 3 }, - { label: "UV5", value: 4 }, - { label: "UV6", value: 5 }, - ], - }) -], SetUVsBlock.prototype, "textureCoordinateIndex", void 0); -RegisterClass("BABYLON.SetUVsBlock", SetUVsBlock); -//# sourceMappingURL=setUVsBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setColorsBlock.js - - - -/** - * Block used to set colors for a geometry - */ -class SetColorsBlock extends NodeGeometryBlock { - /** - * Create a new SetColorsBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerInput("colors", NodeGeometryBlockConnectionPointTypes.Vector4); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current index in the current flow - * @returns the current index - */ - getExecutionIndex() { - return this._currentIndex; - } - /** - * Gets the current loop index in the current flow - * @returns the current loop index - */ - getExecutionLoopIndex() { - return this._currentIndex; - } - /** - * Gets the current face index in the current flow - * @returns the current face index - */ - getExecutionFaceIndex() { - return 0; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SetColorsBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the colors input component - */ - get colors() { - return this._inputs[1]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - state.executionContext = this; - this._vertexData = this.geometry.getConnectedValue(state); - state.geometryContext = this._vertexData; - if (!this._vertexData || !this._vertexData.positions) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = null; - return; - } - if (!this.colors.isConnected) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = this._vertexData; - return; - } - if (!this._vertexData.colors) { - this._vertexData.colors = []; - } - // Processing - const vertexCount = this._vertexData.positions.length / 3; - for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { - const tempVector4 = this.colors.getConnectedValue(state); - if (tempVector4) { - tempVector4.toArray(this._vertexData.colors, this._currentIndex * 4); - } - } - // Storage - this.output._storedValue = this._vertexData; - state.executionContext = null; - state.geometryContext = null; - } -} -RegisterClass("BABYLON.SetColorsBlock", SetColorsBlock); -//# sourceMappingURL=setColorsBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setTangentsBlock.js - - - -/** - * Block used to set tangents for a geometry - */ -class SetTangentsBlock extends NodeGeometryBlock { - /** - * Create a new SetTangentsBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerInput("tangents", NodeGeometryBlockConnectionPointTypes.Vector4); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current index in the current flow - * @returns the current index - */ - getExecutionIndex() { - return this._currentIndex; - } - /** - * Gets the current loop index in the current flow - * @returns the current loop index - */ - getExecutionLoopIndex() { - return this._currentIndex; - } - /** - * Gets the current face index in the current flow - * @returns the current face index - */ - getExecutionFaceIndex() { - return 0; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SetTangentsBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the tangents input component - */ - get tangents() { - return this._inputs[1]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - state.executionContext = this; - this._vertexData = this.geometry.getConnectedValue(state); - state.geometryContext = this._vertexData; - if (!this._vertexData || !this._vertexData.positions) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = null; - return; - } - if (!this.tangents.isConnected) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = this._vertexData; - return; - } - if (!this._vertexData.tangents) { - this._vertexData.tangents = []; - } - // Processing - const vertexCount = this._vertexData.positions.length / 3; - for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { - const tempVector4 = this.tangents.getConnectedValue(state); - if (tempVector4) { - tempVector4.toArray(this._vertexData.tangents, this._currentIndex * 4); - } - } - // Storage - this.output._storedValue = this._vertexData; - state.executionContext = null; - state.geometryContext = null; - } -} -RegisterClass("BABYLON.SetTangentsBlock", SetTangentsBlock); -//# sourceMappingURL=setTangentsBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/mathBlock.js - - - - - - -/** - * Operations supported by the Math block - */ -var MathBlockOperations; -(function (MathBlockOperations) { - /** Add */ - MathBlockOperations[MathBlockOperations["Add"] = 0] = "Add"; - /** Subtract */ - MathBlockOperations[MathBlockOperations["Subtract"] = 1] = "Subtract"; - /** Multiply */ - MathBlockOperations[MathBlockOperations["Multiply"] = 2] = "Multiply"; - /** Divide */ - MathBlockOperations[MathBlockOperations["Divide"] = 3] = "Divide"; - /** Max */ - MathBlockOperations[MathBlockOperations["Max"] = 4] = "Max"; - /** Min */ - MathBlockOperations[MathBlockOperations["Min"] = 5] = "Min"; -})(MathBlockOperations || (MathBlockOperations = {})); -/** - * Block used to apply math functions - */ -class MathBlock extends NodeGeometryBlock { - /** - * Create a new MathBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets the operation applied by the block - */ - this.operation = MathBlockOperations.Add; - this.registerInput("left", NodeGeometryBlockConnectionPointTypes.AutoDetect); - this.registerInput("right", NodeGeometryBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); - this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); - this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); - this._linkConnectionTypes(0, 1); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MathBlock"; - } - /** - * Gets the left input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock() { - let func; - const left = this.left; - const right = this.right; - if (!left.isConnected || !right.isConnected) { - this.output._storedFunction = null; - this.output._storedValue = null; - return; - } - const isFloat = left.type === NodeGeometryBlockConnectionPointTypes.Float || left.type === NodeGeometryBlockConnectionPointTypes.Int; - switch (this.operation) { - case MathBlockOperations.Add: { - if (isFloat) { - func = (state) => { - return left.getConnectedValue(state) + right.getConnectedValue(state); - }; - } - else { - func = (state) => { - return left.getConnectedValue(state).add(state.adapt(right, left.type)); - }; - } - break; - } - case MathBlockOperations.Subtract: { - if (isFloat) { - func = (state) => { - return left.getConnectedValue(state) - right.getConnectedValue(state); - }; - } - else { - func = (state) => { - return left.getConnectedValue(state).subtract(state.adapt(right, left.type)); - }; - } - break; - } - case MathBlockOperations.Multiply: { - if (isFloat) { - func = (state) => { - return left.getConnectedValue(state) * right.getConnectedValue(state); - }; - } - else { - func = (state) => { - return left.getConnectedValue(state).multiply(state.adapt(right, left.type)); - }; - } - break; - } - case MathBlockOperations.Divide: { - if (isFloat) { - func = (state) => { - return left.getConnectedValue(state) / right.getConnectedValue(state); - }; - } - else { - func = (state) => { - return left.getConnectedValue(state).divide(state.adapt(right, left.type)); - }; - } - break; - } - case MathBlockOperations.Min: { - if (isFloat) { - func = (state) => { - return Math.min(left.getConnectedValue(state), right.getConnectedValue(state)); - }; - } - else { - switch (left.type) { - case NodeGeometryBlockConnectionPointTypes.Vector2: { - func = (state) => { - return math_vector_Vector2.Minimize(left.getConnectedValue(state), state.adapt(right, left.type)); - }; - break; - } - case NodeGeometryBlockConnectionPointTypes.Vector3: { - func = (state) => { - return math_vector_Vector3.Minimize(left.getConnectedValue(state), state.adapt(right, left.type)); - }; - break; - } - case NodeGeometryBlockConnectionPointTypes.Vector4: { - func = (state) => { - return math_vector_Vector4.Minimize(left.getConnectedValue(state), state.adapt(right, left.type)); - }; - break; - } - } - } - break; - } - case MathBlockOperations.Max: { - if (isFloat) { - func = (state) => { - return Math.max(left.getConnectedValue(state), right.getConnectedValue(state)); - }; - } - else { - switch (left.type) { - case NodeGeometryBlockConnectionPointTypes.Vector2: { - func = (state) => { - return math_vector_Vector2.Maximize(left.getConnectedValue(state), state.adapt(right, left.type)); - }; - break; - } - case NodeGeometryBlockConnectionPointTypes.Vector3: { - func = (state) => { - return math_vector_Vector3.Maximize(left.getConnectedValue(state), state.adapt(right, left.type)); - }; - break; - } - case NodeGeometryBlockConnectionPointTypes.Vector4: { - func = (state) => { - return math_vector_Vector4.Maximize(left.getConnectedValue(state), state.adapt(right, left.type)); - }; - break; - } - } - break; - } - } - } - this.output._storedFunction = (state) => { - if (left.type === NodeGeometryBlockConnectionPointTypes.Int) { - return func(state) | 0; - } - return func(state); - }; - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${MathBlockOperations[this.operation]};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.operation = this.operation; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.operation = serializationObject.operation; - } -} -__decorate([ - editableInPropertyPage("Operation", PropertyTypeForEdition.List, "ADVANCED", { - notifiers: { rebuild: true }, - options: [ - { label: "Add", value: MathBlockOperations.Add }, - { label: "Subtract", value: MathBlockOperations.Subtract }, - { label: "Multiply", value: MathBlockOperations.Multiply }, - { label: "Divide", value: MathBlockOperations.Divide }, - { label: "Max", value: MathBlockOperations.Max }, - { label: "Min", value: MathBlockOperations.Min }, - ], - }) -], MathBlock.prototype, "operation", void 0); -RegisterClass("BABYLON.MathBlock", MathBlock); -//# sourceMappingURL=mathBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/mapRangeBlock.js - - - -/** - * Defines a block used to move a value from a range to another - */ -class MapRangeBlock extends NodeGeometryBlock { - /** - * Create a new MapRangeBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); - this.registerInput("fromMin", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("fromMax", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("toMin", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("toMax", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MapRangeBlock"; - } - /** - * Gets the value input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the fromMin input component - */ - get fromMin() { - return this._inputs[1]; - } - /** - * Gets the fromMax input component - */ - get fromMax() { - return this._inputs[2]; - } - /** - * Gets the toMin input component - */ - get toMin() { - return this._inputs[3]; - } - /** - * Gets the toMax input component - */ - get toMax() { - return this._inputs[4]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock() { - if (!this.value.isConnected) { - this.output._storedFunction = null; - this.output._storedValue = null; - return; - } - this.output._storedFunction = (state) => { - const value = this.value.getConnectedValue(state); - const fromMin = this.fromMin.getConnectedValue(state); - const fromMax = this.fromMax.getConnectedValue(state); - const toMin = this.toMin.getConnectedValue(state); - const toMax = this.toMax.getConnectedValue(state); - return ((value - fromMin) / (fromMax - fromMin)) * (toMax - toMin) + toMin; - }; - } -} -RegisterClass("BABYLON.MapRangeBlock", MapRangeBlock); -//# sourceMappingURL=mapRangeBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/conditionBlock.js - - - - - - - -/** - * Conditions supported by the condition block - */ -var ConditionBlockTests; -(function (ConditionBlockTests) { - /** Equal */ - ConditionBlockTests[ConditionBlockTests["Equal"] = 0] = "Equal"; - /** NotEqual */ - ConditionBlockTests[ConditionBlockTests["NotEqual"] = 1] = "NotEqual"; - /** LessThan */ - ConditionBlockTests[ConditionBlockTests["LessThan"] = 2] = "LessThan"; - /** GreaterThan */ - ConditionBlockTests[ConditionBlockTests["GreaterThan"] = 3] = "GreaterThan"; - /** LessOrEqual */ - ConditionBlockTests[ConditionBlockTests["LessOrEqual"] = 4] = "LessOrEqual"; - /** GreaterOrEqual */ - ConditionBlockTests[ConditionBlockTests["GreaterOrEqual"] = 5] = "GreaterOrEqual"; - /** Logical Exclusive OR */ - ConditionBlockTests[ConditionBlockTests["Xor"] = 6] = "Xor"; - /** Logical Or */ - ConditionBlockTests[ConditionBlockTests["Or"] = 7] = "Or"; - /** Logical And */ - ConditionBlockTests[ConditionBlockTests["And"] = 8] = "And"; -})(ConditionBlockTests || (ConditionBlockTests = {})); -/** - * Block used to evaluate a condition and return a true or false value - */ -class ConditionBlock extends NodeGeometryBlock { - /** - * Create a new ConditionBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets the test used by the block - */ - this.test = ConditionBlockTests.Equal; - this.registerInput("left", NodeGeometryBlockConnectionPointTypes.Float); - this.registerInput("right", NodeGeometryBlockConnectionPointTypes.Float, true, 0); - this.registerInput("ifTrue", NodeGeometryBlockConnectionPointTypes.AutoDetect, true, 1); - this.registerInput("ifFalse", NodeGeometryBlockConnectionPointTypes.AutoDetect, true, 0); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[2]; - this._outputs[0]._defaultConnectionPointType = NodeGeometryBlockConnectionPointTypes.Float; - this._inputs[0].acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); - this._inputs[1].acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Int); - this._linkConnectionTypes(2, 3); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ConditionBlock"; - } - /** - * Gets the left input component - */ - get left() { - return this._inputs[0]; - } - /** - * Gets the right input component - */ - get right() { - return this._inputs[1]; - } - /** - * Gets the ifTrue input component - */ - get ifTrue() { - return this._inputs[2]; - } - /** - * Gets the ifFalse input component - */ - get ifFalse() { - return this._inputs[3]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock() { - if (!this.left.isConnected) { - this.output._storedFunction = null; - this.output._storedValue = null; - return; - } - const func = (state) => { - const left = this.left.getConnectedValue(state); - const right = this.right.getConnectedValue(state); - let condition = false; - switch (this.test) { - case ConditionBlockTests.Equal: - condition = math_scalar_Scalar.WithinEpsilon(left, right, math_constants_Epsilon); - break; - case ConditionBlockTests.NotEqual: - condition = left !== right; - break; - case ConditionBlockTests.LessThan: - condition = left < right; - break; - case ConditionBlockTests.GreaterThan: - condition = left > right; - break; - case ConditionBlockTests.LessOrEqual: - condition = left <= right; - break; - case ConditionBlockTests.GreaterOrEqual: - condition = left >= right; - break; - case ConditionBlockTests.Xor: - condition = (!!left && !right) || (!left && !!right); - break; - case ConditionBlockTests.Or: - condition = !!left || !!right; - break; - case ConditionBlockTests.And: - condition = !!left && !!right; - break; - } - return condition; - }; - this.output._storedFunction = (state) => { - if (func(state)) { - return this.ifTrue.getConnectedValue(state); - } - return this.ifFalse.getConnectedValue(state); - }; - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${ConditionBlockTests[this.test]};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.test = this.test; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.test = serializationObject.test; - } -} -__decorate([ - editableInPropertyPage("Test", PropertyTypeForEdition.List, "ADVANCED", { - notifiers: { rebuild: true }, - options: [ - { label: "Equal", value: ConditionBlockTests.Equal }, - { label: "NotEqual", value: ConditionBlockTests.NotEqual }, - { label: "LessThan", value: ConditionBlockTests.LessThan }, - { label: "GreaterThan", value: ConditionBlockTests.GreaterThan }, - { label: "LessOrEqual", value: ConditionBlockTests.LessOrEqual }, - { label: "GreaterOrEqual", value: ConditionBlockTests.GreaterOrEqual }, - { label: "Xor", value: ConditionBlockTests.Xor }, - { label: "Or", value: ConditionBlockTests.Or }, - { label: "And", value: ConditionBlockTests.And }, - ], - }) -], ConditionBlock.prototype, "test", void 0); -RegisterClass("BABYLON.ConditionBlock", ConditionBlock); -//# sourceMappingURL=conditionBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/randomBlock.js - - - - - -/** - * Block used to get a random number - */ -class RandomBlock extends NodeGeometryBlock { - /** - * Create a new RandomBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("min", NodeGeometryBlockConnectionPointTypes.AutoDetect); - this.registerInput("max", NodeGeometryBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); - this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); - this._inputs[1].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "RandomBlock"; - } - /** - * Gets the min input component - */ - get min() { - return this._inputs[0]; - } - /** - * Gets the max input component - */ - get max() { - return this._inputs[1]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.min.isConnected) { - const minInput = new GeometryInputBlock("Min"); - minInput.value = 0; - minInput.output.connectTo(this.min); - } - if (!this.max.isConnected) { - const maxInput = new GeometryInputBlock("Max"); - maxInput.value = 1; - maxInput.output.connectTo(this.max); - } - } - _buildBlock() { - let func = null; - switch (this.min.type) { - case NodeGeometryBlockConnectionPointTypes.Int: - case NodeGeometryBlockConnectionPointTypes.Float: { - func = (state) => { - const min = this.min.getConnectedValue(state) || 0; - const max = this.max.getConnectedValue(state) || 0; - return min + Math.random() * (max - min); - }; - break; - } - case NodeGeometryBlockConnectionPointTypes.Vector2: { - func = (state) => { - const min = this.min.getConnectedValue(state) || math_vector_Vector2.Zero(); - const max = this.max.getConnectedValue(state) || math_vector_Vector2.Zero(); - return new math_vector_Vector2(min.x + Math.random() * (max.x - min.x), min.y + Math.random() * (max.y - min.y)); - }; - break; - } - case NodeGeometryBlockConnectionPointTypes.Vector3: { - func = (state) => { - const min = this.min.getConnectedValue(state) || math_vector_Vector3.Zero(); - const max = this.max.getConnectedValue(state) || math_vector_Vector3.Zero(); - return new math_vector_Vector3(min.x + Math.random() * (max.x - min.x), min.y + Math.random() * (max.y - min.y), min.z + Math.random() * (max.z - min.z)); - }; - break; - } - case NodeGeometryBlockConnectionPointTypes.Vector4: { - func = (state) => { - const min = this.min.getConnectedValue(state) || math_vector_Vector4.Zero(); - const max = this.max.getConnectedValue(state) || math_vector_Vector4.Zero(); - return new math_vector_Vector4(min.x + Math.random() * (max.x - min.x), min.y + Math.random() * (max.y - min.y), min.z + Math.random() * (max.z - min.z), min.w + Math.random() * (max.w - min.w)); - }; - break; - } - } - this.output._storedFunction = func; - } -} -RegisterClass("BABYLON.RandomBlock", RandomBlock); -//# sourceMappingURL=randomBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/noiseBlock.js - - - - - - -/** - * Block used to get a noise value - */ -class NoiseBlock extends NodeGeometryBlock { - /** - * Create a new NoiseBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("offset", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.Zero()); - this.registerInput("scale", NodeGeometryBlockConnectionPointTypes.Float, true, 1); - this.registerInput("octaves", NodeGeometryBlockConnectionPointTypes.Float, true, 2, 0, 16); - this.registerInput("roughness", NodeGeometryBlockConnectionPointTypes.Float, true, 0.5, 0, 1); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "NoiseBlock"; - } - /** - * Gets the offset input component - */ - get offset() { - return this._inputs[0]; - } - /** - * Gets the scale input component - */ - get scale() { - return this._inputs[1]; - } - /** - * Gets the octaves input component - */ - get octaves() { - return this._inputs[2]; - } - /** - * Gets the roughtness input component - */ - get roughness() { - return this._inputs[3]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _negateIf(value, condition) { - return condition !== 0 ? -value : value; - } - _noiseGrad(hash, x, y, z) { - const h = hash & 15; - const u = h < 8 ? x : y; - const vt = h === 12 || h == 14 ? x : z; - const v = h < 4 ? y : vt; - return this._negateIf(u, h & u) + this._negateIf(v, h & 2); - } - _fade(t) { - return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); - } - _hashBitRotate(x, k) { - return (x << k) | (x >> (32 - k)); - } - _hash(kx, ky, kz) { - let a, b, c; - a = b = c = 0xdeadbeef + (3 << 2) + 13; - c += kz; - b += ky; - a += kx; - c ^= b; - c -= this._hashBitRotate(b, 14); - a ^= c; - a -= this._hashBitRotate(c, 11); - b ^= a; - b -= this._hashBitRotate(a, 25); - c ^= b; - c -= this._hashBitRotate(b, 16); - a ^= c; - a -= this._hashBitRotate(c, 4); - b ^= a; - b -= this._hashBitRotate(a, 14); - c ^= b; - c -= this._hashBitRotate(b, 24); - return c; - } - _mix(v0, v1, v2, v3, v4, v5, v6, v7, x, y, z) { - const x1 = 1.0 - x; - const y1 = 1.0 - y; - const z1 = 1.0 - z; - return z1 * (y1 * (v0 * x1 + v1 * x) + y * (v2 * x1 + v3 * x)) + z * (y1 * (v4 * x1 + v5 * x) + y * (v6 * x1 + v7 * x)); - } - _perlinNoise(position) { - const X = (position.x | 0) - (position.x < 0 ? 1 : 0); - const Y = (position.y | 0) - (position.y < 0 ? 1 : 0); - const Z = (position.z | 0) - (position.z < 0 ? 1 : 0); - const fx = position.x - X; - const fy = position.y - Y; - const fz = position.z - Z; - const u = this._fade(fx); - const v = this._fade(fy); - const w = this._fade(fz); - return this._mix(this._noiseGrad(this._hash(X, Y, Z), fx, fy, fz), this._noiseGrad(this._hash(X + 1, Y, Z), fx - 1, fy, fz), this._noiseGrad(this._hash(X, Y + 1, Z), fx, fy - 1, fz), this._noiseGrad(this._hash(X + 1, Y + 1, Z), fx - 1, fy - 1, fz), this._noiseGrad(this._hash(X, Y, Z + 1), fx, fy, fz - 1), this._noiseGrad(this._hash(X + 1, Y, Z + 1), fx - 1, fy, fz - 1), this._noiseGrad(this._hash(X, Y + 1, Z + 1), fx, fy - 1, fz - 1), this._noiseGrad(this._hash(X + 1, Y + 1, Z + 1), fx - 1, fy - 1, fz - 1), u, v, w); - } - _perlinSigned(position) { - return this._perlinNoise(position) * 0.982; - } - _perlin(position) { - return this._perlinSigned(position) / 2.0 + 0.5; - } - /** - * Gets a perlin noise value - * @param octaves - * @param roughness - * @param position - * @returns a value between 0 and 1 - * @see Based on https://github.com/blender/blender/blob/main/source/blender/blenlib/intern/noise.cc#L533 - */ - noise(octaves, roughness, _position, offset, scale) { - const position = new math_vector_Vector3(_position.x + offset.x * scale, _position.y + offset.y * scale, _position.z + offset.z * scale); - let fscale = 1.0; - let amp = 1.0; - let maxamp = 0.0; - let sum = 0.0; - octaves = math_scalar_Scalar.Clamp(octaves, 0, 15.0); - const step = octaves | 0; - for (let i = 0; i <= step; i++) { - const t = this._perlin(position.scale(fscale)); - sum += t * amp; - maxamp += amp; - amp *= math_scalar_Scalar.Clamp(roughness, 0.0, 1.0); - fscale *= 2.0; - } - const rmd = octaves - Math.floor(octaves); - if (rmd == 0.0) { - return sum / maxamp; - } - const t = this._perlin(position.scale(fscale)); - let sum2 = sum + t * amp; - sum /= maxamp; - sum2 /= maxamp + amp; - return (1.0 - rmd) * sum + rmd * sum2; - } - _buildBlock() { - this.output._storedFunction = (state) => { - const position = state.getContextualValue(NodeGeometryContextualSources.Positions); - const octaves = this.octaves.getConnectedValue(state); - const roughness = this.roughness.getConnectedValue(state); - const offset = this.offset.getConnectedValue(state); - const scale = this.scale.getConnectedValue(state); - return this.noise(octaves, roughness, position, offset, scale); - }; - } -} -RegisterClass("BABYLON.NoiseBlock", NoiseBlock); -//# sourceMappingURL=noiseBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/mergeGeometryBlock.js - - - - - -/** - * Block used to merge several geometries - */ -class MergeGeometryBlock extends NodeGeometryBlock { - /** - * Create a new MergeGeometryBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = false; - this.registerInput("geometry0", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerInput("geometry1", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry2", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry3", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry4", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "MergeGeometryBlock"; - } - /** - * Gets the geometry0 input component - */ - get geometry0() { - return this._inputs[0]; - } - /** - * Gets the geometry1 input component - */ - get geometry1() { - return this._inputs[1]; - } - /** - * Gets the geometry2 input component - */ - get geometry2() { - return this._inputs[2]; - } - /** - * Gets the geometry3 input component - */ - get geometry3() { - return this._inputs[3]; - } - /** - * Gets the geometry4 input component - */ - get geometry4() { - return this._inputs[4]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - const func = (state) => { - let vertexData = this.geometry0.getConnectedValue(state); - const additionalVertexData = []; - if (this.geometry1.isConnected) { - additionalVertexData.push(this.geometry1.getConnectedValue(state)); - } - if (this.geometry2.isConnected) { - additionalVertexData.push(this.geometry2.getConnectedValue(state)); - } - if (this.geometry3.isConnected) { - additionalVertexData.push(this.geometry3.getConnectedValue(state)); - } - if (this.geometry4.isConnected) { - additionalVertexData.push(this.geometry4.getConnectedValue(state)); - } - if (additionalVertexData.length && vertexData) { - vertexData = vertexData.merge(additionalVertexData, true, false, true, true); - } - return vertexData; - }; - if (this.evaluateContext) { - this.output._storedFunction = func; - } - else { - this.output._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], MergeGeometryBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.MergeGeometryBlock", MergeGeometryBlock); -//# sourceMappingURL=mergeGeometryBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryCollectionBlock.js - - - - - -/** - * Block used to randomly pick a geometry from a collection - */ -class GeometryCollectionBlock extends NodeGeometryBlock { - /** - * Create a new GeometryCollectionBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = true; - this.registerInput("geometry0", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry1", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry2", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry3", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry4", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry5", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry6", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry7", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry8", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("geometry9", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._linkConnectionTypes(0, 1); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "GeometryCollectionBlock"; - } - /** - * Gets the geometry0 input component - */ - get geometry0() { - return this._inputs[0]; - } - /** - * Gets the geometry1 input component - */ - get geometry1() { - return this._inputs[1]; - } - /** - * Gets the geometry2 input component - */ - get geometry2() { - return this._inputs[2]; - } - /** - * Gets the geometry3 input component - */ - get geometry3() { - return this._inputs[3]; - } - /** - * Gets the geometry4 input component - */ - get geometry4() { - return this._inputs[4]; - } - /** - * Gets the geometry5 input component - */ - get geometry5() { - return this._inputs[5]; - } - /** - * Gets the geometry6 input component - */ - get geometry6() { - return this._inputs[6]; - } - /** - * Gets the geometry7 input component - */ - get geometry7() { - return this._inputs[7]; - } - /** - * Gets the geometry8 input component - */ - get geometry8() { - return this._inputs[8]; - } - /** - * Gets the geometry9 input component - */ - get geometry9() { - return this._inputs[9]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _storeGeometry(input, state, index, availables) { - if (input.isConnected) { - const vertexData = input.getConnectedValue(state); - vertexData.metadata = vertexData.metadata || {}; - vertexData.metadata.collectionId = index; - availables.push(vertexData); - } - } - _buildBlock(state) { - const func = (state) => { - const availables = []; - this._storeGeometry(this.geometry0, state, 0, availables); - this._storeGeometry(this.geometry1, state, 1, availables); - this._storeGeometry(this.geometry2, state, 2, availables); - this._storeGeometry(this.geometry3, state, 3, availables); - this._storeGeometry(this.geometry4, state, 4, availables); - this._storeGeometry(this.geometry5, state, 5, availables); - this._storeGeometry(this.geometry6, state, 6, availables); - this._storeGeometry(this.geometry7, state, 7, availables); - this._storeGeometry(this.geometry8, state, 8, availables); - this._storeGeometry(this.geometry9, state, 9, availables); - if (!availables.length) { - return null; - } - return availables[Math.round(Math.random() * (availables.length - 1))]; - }; - if (this.evaluateContext) { - this.output._storedFunction = func; - } - else { - this.output._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], GeometryCollectionBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.GeometryCollectionBlock", GeometryCollectionBlock); -//# sourceMappingURL=geometryCollectionBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryElbowBlock.js - - - -/** - * Block used as a pass through - */ -class GeometryElbowBlock extends NodeGeometryBlock { - /** - * Creates a new GeometryElbowBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the time spent to build this block (in ms) - */ - get buildExecutionTime() { - return 0; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "GeometryElbowBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - const output = this._outputs[0]; - const input = this._inputs[0]; - output._storedFunction = (state) => { - return input.getConnectedValue(state); - }; - } -} -RegisterClass("BABYLON.GeometryElbowBlock", GeometryElbowBlock); -//# sourceMappingURL=geometryElbowBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/computeNormalsBlock.js - - - - -/** - * Block used to recompute normals for a geometry - */ -class ComputeNormalsBlock extends NodeGeometryBlock { - /** - * Creates a new ComputeNormalsBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ComputeNormalsBlock"; - } - /** - * Gets the geometry component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock() { - this.output._storedFunction = (state) => { - if (!this.geometry.isConnected) { - return null; - } - const vertexData = this.geometry.getConnectedValue(state); - if (!vertexData.normals) { - vertexData.normals = []; - } - mesh_vertexData_VertexData.ComputeNormals(vertexData.positions, vertexData.indices, vertexData.normals); - return vertexData; - }; - } -} -RegisterClass("BABYLON.ComputeNormalsBlock", ComputeNormalsBlock); -//# sourceMappingURL=computeNormalsBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/vectorConverterBlock.js - - - - -/** - * Block used to create a Vector2/3/4 out of individual or partial inputs - */ -class VectorConverterBlock extends NodeGeometryBlock { - /** - * Create a new VectorConverterBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("xyzw ", NodeGeometryBlockConnectionPointTypes.Vector4, true); - this.registerInput("xyz ", NodeGeometryBlockConnectionPointTypes.Vector3, true); - this.registerInput("xy ", NodeGeometryBlockConnectionPointTypes.Vector2, true); - this.registerInput("zw ", NodeGeometryBlockConnectionPointTypes.Vector2, true); - this.registerInput("x ", NodeGeometryBlockConnectionPointTypes.Float, true); - this.registerInput("y ", NodeGeometryBlockConnectionPointTypes.Float, true); - this.registerInput("z ", NodeGeometryBlockConnectionPointTypes.Float, true); - this.registerInput("w ", NodeGeometryBlockConnectionPointTypes.Float, true); - this.registerOutput("xyzw", NodeGeometryBlockConnectionPointTypes.Vector4); - this.registerOutput("xyz", NodeGeometryBlockConnectionPointTypes.Vector3); - this.registerOutput("xy", NodeGeometryBlockConnectionPointTypes.Vector2); - this.registerOutput("zw", NodeGeometryBlockConnectionPointTypes.Vector2); - this.registerOutput("x", NodeGeometryBlockConnectionPointTypes.Float); - this.registerOutput("y", NodeGeometryBlockConnectionPointTypes.Float); - this.registerOutput("z", NodeGeometryBlockConnectionPointTypes.Float); - this.registerOutput("w", NodeGeometryBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "VectorConverterBlock"; - } - /** - * Gets the xyzw component (input) - */ - get xyzwIn() { - return this._inputs[0]; - } - /** - * Gets the xyz component (input) - */ - get xyzIn() { - return this._inputs[1]; - } - /** - * Gets the xy component (input) - */ - get xyIn() { - return this._inputs[2]; - } - /** - * Gets the zw component (input) - */ - get zwIn() { - return this._inputs[3]; - } - /** - * Gets the x component (input) - */ - get xIn() { - return this._inputs[4]; - } - /** - * Gets the y component (input) - */ - get yIn() { - return this._inputs[5]; - } - /** - * Gets the z component (input) - */ - get zIn() { - return this._inputs[6]; - } - /** - * Gets the w component (input) - */ - get wIn() { - return this._inputs[7]; - } - /** - * Gets the xyzw component (output) - */ - get xyzwOut() { - return this._outputs[0]; - } - /** - * Gets the xyz component (output) - */ - get xyzOut() { - return this._outputs[1]; - } - /** - * Gets the xy component (output) - */ - get xyOut() { - return this._outputs[2]; - } - /** - * Gets the zw component (output) - */ - get zwOut() { - return this._outputs[3]; - } - /** - * Gets the x component (output) - */ - get xOut() { - return this._outputs[4]; - } - /** - * Gets the y component (output) - */ - get yOut() { - return this._outputs[5]; - } - /** - * Gets the z component (output) - */ - get zOut() { - return this._outputs[6]; - } - /** - * Gets the w component (output) - */ - get wOut() { - return this._outputs[7]; - } - _inputRename(name) { - if (name === "xyzw ") { - return "xyzwIn"; - } - if (name === "xyz ") { - return "xyzIn"; - } - if (name === "xy ") { - return "xyIn"; - } - if (name === "zw ") { - return "zwIn"; - } - if (name === "x ") { - return "xIn"; - } - if (name === "y ") { - return "yIn"; - } - if (name === "z ") { - return "zIn"; - } - if (name === "w ") { - return "wIn"; - } - return name; - } - _outputRename(name) { - switch (name) { - case "x": - return "xOut"; - case "y": - return "yOut"; - case "z": - return "zOut"; - case "w": - return "wOut"; - case "xy": - return "xyOut"; - case "zw": - return "zwOut"; - case "xyz": - return "xyzOut"; - case "xyzw": - return "xyzwOut"; - default: - return name; - } - } - _buildBlock(state) { - super._buildBlock(state); - const xInput = this.xIn; - const yInput = this.yIn; - const zInput = this.zIn; - const wInput = this.wIn; - const xyInput = this.xyIn; - const zwInput = this.zwIn; - const xyzInput = this.xyzIn; - const xyzwInput = this.xyzwIn; - const xyzwOutput = this.xyzwOut; - const xyzOutput = this.xyzOut; - const xyOutput = this.xyOut; - const zwOutput = this.zwOut; - const xOutput = this.xOut; - const yOutput = this.yOut; - const zOutput = this.zOut; - const wOutput = this.wOut; - const getData = (state) => { - if (xyzwInput.isConnected) { - return xyzwInput.getConnectedValue(state); - } - let x = 0; - let y = 0; - let z = 0; - let w = 0; - if (xInput.isConnected) { - x = xInput.getConnectedValue(state); - } - if (yInput.isConnected) { - y = yInput.getConnectedValue(state); - } - if (zInput.isConnected) { - z = zInput.getConnectedValue(state); - } - if (wInput.isConnected) { - w = wInput.getConnectedValue(state); - } - if (xyInput.isConnected) { - const temp = xyInput.getConnectedValue(state); - if (temp) { - x = temp.x; - y = temp.y; - } - } - if (zwInput.isConnected) { - const temp = zwInput.getConnectedValue(state); - if (temp) { - z = temp.x; - w = temp.y; - } - } - if (xyzInput.isConnected) { - const temp = xyzInput.getConnectedValue(state); - if (temp) { - x = temp.x; - y = temp.y; - z = temp.z; - } - } - return new math_vector_Vector4(x, y, z, w); - }; - xyzwOutput._storedFunction = (state) => getData(state); - xyzOutput._storedFunction = (state) => { - const data = getData(state); - return new math_vector_Vector3(data.x, data.y, data.z); - }; - xyOutput._storedFunction = (state) => { - const data = getData(state); - return new math_vector_Vector2(data.x, data.y); - }; - zwOutput._storedFunction = (state) => { - const data = getData(state); - return new math_vector_Vector2(data.z, data.w); - }; - xOutput._storedFunction = (state) => getData(state).x; - yOutput._storedFunction = (state) => getData(state).y; - zOutput._storedFunction = (state) => getData(state).z; - wOutput._storedFunction = (state) => getData(state).w; - } -} -RegisterClass("BABYLON.VectorConverterBlock", VectorConverterBlock); -//# sourceMappingURL=vectorConverterBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/normalizeVectorBlock.js - - - -/** - * Block used to normalize vectors - */ -class NormalizeVectorBlock extends NodeGeometryBlock { - /** - * Creates a new NormalizeVectorBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "NormalizeVectorBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - this.output._storedFunction = null; - if (!this.input.isConnected) { - this.output._storedValue = null; - return; - } - this.output._storedFunction = (state) => this.input.getConnectedValue(state).normalize(); - } -} -RegisterClass("BABYLON.NormalizeVectorBlock", NormalizeVectorBlock); -//# sourceMappingURL=normalizeVectorBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Set/setMaterialIDBlock.js - - - - - - -/** - * Block used to affect a material ID to a geometry - */ -class SetMaterialIDBlock extends NodeGeometryBlock { - /** - * Create a new SetMaterialIDBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = true; - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerInput("id", NodeGeometryBlockConnectionPointTypes.Int, true, 0); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - this.id.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "SetMaterialIDBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the id input component - */ - get id() { - return this._inputs[1]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - if (!this.geometry.isConnected) { - this.output._storedFunction = null; - this.output._storedValue = null; - return; - } - const func = (state) => { - const vertexData = this.geometry.getConnectedValue(state); - if (!vertexData || !vertexData.indices || !vertexData.positions) { - return vertexData; - } - const materialInfo = new VertexDataMaterialInfo(); - materialInfo.materialIndex = this.id.getConnectedValue(state) | 0; - materialInfo.indexStart = 0; - materialInfo.indexCount = vertexData.indices.length; - materialInfo.verticesStart = 0; - materialInfo.verticesCount = vertexData.positions.length / 3; - vertexData.materialInfos = [materialInfo]; - return vertexData; - }; - if (this.evaluateContext) { - this.output._storedFunction = func; - } - else { - this.output._storedValue = func(state); - } - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], SetMaterialIDBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.SetMaterialIDBlock", SetMaterialIDBlock); -//# sourceMappingURL=setMaterialIDBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryTrigonometryBlock.js - - - - - - -/** - * Operations supported by the Trigonometry block - */ -var GeometryTrigonometryBlockOperations; -(function (GeometryTrigonometryBlockOperations) { - /** Cos */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Cos"] = 0] = "Cos"; - /** Sin */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Sin"] = 1] = "Sin"; - /** Abs */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Abs"] = 2] = "Abs"; - /** Exp */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Exp"] = 3] = "Exp"; - /** Round */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Round"] = 4] = "Round"; - /** Floor */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Floor"] = 5] = "Floor"; - /** Ceiling */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Ceiling"] = 6] = "Ceiling"; - /** Square root */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Sqrt"] = 7] = "Sqrt"; - /** Log */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Log"] = 8] = "Log"; - /** Tangent */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Tan"] = 9] = "Tan"; - /** Arc tangent */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["ArcTan"] = 10] = "ArcTan"; - /** Arc cosinus */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["ArcCos"] = 11] = "ArcCos"; - /** Arc sinus */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["ArcSin"] = 12] = "ArcSin"; - /** Sign */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Sign"] = 13] = "Sign"; - /** Negate */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Negate"] = 14] = "Negate"; - /** OneMinus */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["OneMinus"] = 15] = "OneMinus"; - /** Reciprocal */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["Reciprocal"] = 16] = "Reciprocal"; - /** ToDegrees */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["ToDegrees"] = 17] = "ToDegrees"; - /** ToRadians */ - GeometryTrigonometryBlockOperations[GeometryTrigonometryBlockOperations["ToRadians"] = 18] = "ToRadians"; -})(GeometryTrigonometryBlockOperations || (GeometryTrigonometryBlockOperations = {})); -/** - * Block used to apply trigonometry operation to floats - */ -class GeometryTrigonometryBlock extends NodeGeometryBlock { - /** - * Creates a new GeometryTrigonometryBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets the operation applied by the block - */ - this.operation = GeometryTrigonometryBlockOperations.Cos; - this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "GeometryTrigonometryBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - let func = null; - switch (this.operation) { - case GeometryTrigonometryBlockOperations.Cos: { - func = (value) => Math.cos(value); - break; - } - case GeometryTrigonometryBlockOperations.Sin: { - func = (value) => Math.sin(value); - break; - } - case GeometryTrigonometryBlockOperations.Abs: { - func = (value) => Math.abs(value); - break; - } - case GeometryTrigonometryBlockOperations.Exp: { - func = (value) => Math.exp(value); - break; - } - case GeometryTrigonometryBlockOperations.Round: { - func = (value) => Math.round(value); - break; - } - case GeometryTrigonometryBlockOperations.Floor: { - func = (value) => Math.floor(value); - break; - } - case GeometryTrigonometryBlockOperations.Ceiling: { - func = (value) => Math.ceil(value); - break; - } - case GeometryTrigonometryBlockOperations.Sqrt: { - func = (value) => Math.sqrt(value); - break; - } - case GeometryTrigonometryBlockOperations.Log: { - func = (value) => Math.log(value); - break; - } - case GeometryTrigonometryBlockOperations.Tan: { - func = (value) => Math.tan(value); - break; - } - case GeometryTrigonometryBlockOperations.ArcTan: { - func = (value) => Math.atan(value); - break; - } - case GeometryTrigonometryBlockOperations.ArcCos: { - func = (value) => Math.acos(value); - break; - } - case GeometryTrigonometryBlockOperations.ArcSin: { - func = (value) => Math.asin(value); - break; - } - case GeometryTrigonometryBlockOperations.Sign: { - func = (value) => Math.sign(value); - break; - } - case GeometryTrigonometryBlockOperations.Negate: { - func = (value) => -value; - break; - } - case GeometryTrigonometryBlockOperations.OneMinus: { - func = (value) => 1 - value; - break; - } - case GeometryTrigonometryBlockOperations.Reciprocal: { - func = (value) => 1 / value; - break; - } - case GeometryTrigonometryBlockOperations.ToRadians: { - func = (value) => (value * Math.PI) / 180; - break; - } - case GeometryTrigonometryBlockOperations.ToDegrees: { - func = (value) => (value * 180) / Math.PI; - break; - } - } - if (!func) { - this.input._storedFunction = null; - this.input._storedValue = null; - return; - } - switch (this.input.type) { - case NodeGeometryBlockConnectionPointTypes.Int: - case NodeGeometryBlockConnectionPointTypes.Float: { - this.output._storedFunction = (state) => { - const source = this.input.getConnectedValue(state); - return func(source); - }; - break; - } - case NodeGeometryBlockConnectionPointTypes.Vector2: { - this.output._storedFunction = (state) => { - const source = this.input.getConnectedValue(state); - return new math_vector_Vector2(func(source.x), func(source.y)); - }; - break; - } - case NodeGeometryBlockConnectionPointTypes.Vector3: { - this.output._storedFunction = (state) => { - const source = this.input.getConnectedValue(state); - return new math_vector_Vector3(func(source.x), func(source.y), func(source.z)); - }; - break; - } - case NodeGeometryBlockConnectionPointTypes.Vector4: { - this.output._storedFunction = (state) => { - const source = this.input.getConnectedValue(state); - return new math_vector_Vector4(func(source.x), func(source.y), func(source.z), func(source.w)); - }; - break; - } - } - return this; - } - serialize() { - const serializationObject = super.serialize(); - serializationObject.operation = this.operation; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.operation = serializationObject.operation; - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + - `${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${GeometryTrigonometryBlockOperations[this.operation]};\n`; - return codeString; - } -} -__decorate([ - editableInPropertyPage("Operation", PropertyTypeForEdition.List, "ADVANCED", { - notifiers: { rebuild: true }, - options: [ - { label: "Cos", value: GeometryTrigonometryBlockOperations.Cos }, - { label: "Sin", value: GeometryTrigonometryBlockOperations.Sin }, - { label: "Abs", value: GeometryTrigonometryBlockOperations.Abs }, - { label: "Exp", value: GeometryTrigonometryBlockOperations.Exp }, - { label: "Round", value: GeometryTrigonometryBlockOperations.Round }, - { label: "Floor", value: GeometryTrigonometryBlockOperations.Floor }, - { label: "Ceiling", value: GeometryTrigonometryBlockOperations.Ceiling }, - { label: "Sqrt", value: GeometryTrigonometryBlockOperations.Sqrt }, - { label: "Log", value: GeometryTrigonometryBlockOperations.Log }, - { label: "Tan", value: GeometryTrigonometryBlockOperations.Tan }, - { label: "ArcTan", value: GeometryTrigonometryBlockOperations.ArcTan }, - { label: "ArcCos", value: GeometryTrigonometryBlockOperations.ArcCos }, - { label: "ArcSin", value: GeometryTrigonometryBlockOperations.ArcSin }, - { label: "Sign", value: GeometryTrigonometryBlockOperations.Sign }, - { label: "Negate", value: GeometryTrigonometryBlockOperations.Negate }, - { label: "OneMinus", value: GeometryTrigonometryBlockOperations.OneMinus }, - { label: "Reciprocal", value: GeometryTrigonometryBlockOperations.Reciprocal }, - { label: "ToDegrees", value: GeometryTrigonometryBlockOperations.ToDegrees }, - { label: "ToRadians", value: GeometryTrigonometryBlockOperations.ToRadians }, - ], - }) -], GeometryTrigonometryBlock.prototype, "operation", void 0); -RegisterClass("BABYLON.GeometryTrigonometryBlock", GeometryTrigonometryBlock); -//# sourceMappingURL=geometryTrigonometryBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryTransformBlock.js - - - - - - -/** - * Block used to apply a transform to a vector / geometry - */ -class GeometryTransformBlock extends NodeGeometryBlock { - /** - * Create a new GeometryTransformBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this._rotationMatrix = new math_vector_Matrix(); - this._scalingMatrix = new math_vector_Matrix(); - this._translationMatrix = new math_vector_Matrix(); - this._scalingRotationMatrix = new math_vector_Matrix(); - this._transformMatrix = new math_vector_Matrix(); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = true; - this.registerInput("value", NodeGeometryBlockConnectionPointTypes.AutoDetect); - this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true); - this.registerInput("translation", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.Zero()); - this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.Zero()); - this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.One()); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "GeometryTransformBlock"; - } - /** - * Gets the value input component - */ - get value() { - return this._inputs[0]; - } - /** - * Gets the matrix input component - */ - get matrix() { - return this._inputs[1]; - } - /** - * Gets the translation input component - */ - get translation() { - return this._inputs[2]; - } - /** - * Gets the rotation input component - */ - get rotation() { - return this._inputs[3]; - } - /** - * Gets the scaling input component - */ - get scaling() { - return this._inputs[4]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - if (!this.value.isConnected) { - this.output._storedFunction = null; - this.output._storedValue = null; - return; - } - const func = (state) => { - const value = this.value.getConnectedValue(state); - if (!value) { - return null; - } - let matrix; - if (this.matrix.isConnected) { - matrix = this.matrix.getConnectedValue(state); - } - else { - const scaling = this.scaling.getConnectedValue(state); - const rotation = this.rotation.getConnectedValue(state); - const translation = this.translation.getConnectedValue(state); - // Transform - math_vector_Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, this._scalingMatrix); - math_vector_Matrix.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, this._rotationMatrix); - math_vector_Matrix.TranslationToRef(translation.x, translation.y, translation.z, this._translationMatrix); - this._scalingMatrix.multiplyToRef(this._rotationMatrix, this._scalingRotationMatrix); - this._scalingRotationMatrix.multiplyToRef(this._translationMatrix, this._transformMatrix); - matrix = this._transformMatrix; - } - switch (this.value.type) { - case NodeGeometryBlockConnectionPointTypes.Geometry: { - const geometry = value.clone(); - geometry.transform(matrix); - return geometry; - } - case NodeGeometryBlockConnectionPointTypes.Vector2: - return math_vector_Vector2.Transform(value, matrix); - case NodeGeometryBlockConnectionPointTypes.Vector3: - return math_vector_Vector3.TransformCoordinates(value, matrix); - case NodeGeometryBlockConnectionPointTypes.Vector4: - return math_vector_Vector4.TransformCoordinates(value, matrix); - } - return null; - }; - if (this.evaluateContext) { - this.output._storedFunction = func; - } - else { - this.output._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - if (serializationObject.evaluateContext !== undefined) { - this.evaluateContext = serializationObject.evaluateContext; - } - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], GeometryTransformBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.GeometryTransformBlock", GeometryTransformBlock); -//# sourceMappingURL=geometryTransformBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/rotationXBlock.js - - - - - -/** - * Block used to get a rotation matrix on X Axis - */ -class RotationXBlock extends NodeGeometryBlock { - /** - * Create a new RotationXBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, false, 0); - this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "RotationXBlock"; - } - /** - * Gets the angle input component - */ - get angle() { - return this._inputs[0]; - } - /** - * Gets the matrix output component - */ - get matrix() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.angle.isConnected) { - const angleInput = new GeometryInputBlock("Angle"); - angleInput.value = 0; - angleInput.output.connectTo(this.angle); - } - } - _buildBlock(state) { - super._buildBlock(state); - this.matrix._storedFunction = (state) => { - return math_vector_Matrix.RotationX(this.angle.getConnectedValue(state)); - }; - } -} -RegisterClass("BABYLON.RotationXBlock", RotationXBlock); -//# sourceMappingURL=rotationXBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/rotationYBlock.js - - - - - -/** - * Block used to get a rotation matrix on Y Axis - */ -class RotationYBlock extends NodeGeometryBlock { - /** - * Create a new RotationYBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, false, 0); - this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "RotationYBlock"; - } - /** - * Gets the angle input component - */ - get angle() { - return this._inputs[0]; - } - /** - * Gets the matrix output component - */ - get matrix() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.angle.isConnected) { - const angleInput = new GeometryInputBlock("Angle"); - angleInput.value = 0; - angleInput.output.connectTo(this.angle); - } - } - _buildBlock(state) { - super._buildBlock(state); - this.matrix._storedFunction = (state) => { - return math_vector_Matrix.RotationY(this.angle.getConnectedValue(state)); - }; - } -} -RegisterClass("BABYLON.RotationYBlock", RotationYBlock); -//# sourceMappingURL=rotationYBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/rotationZBlock.js - - - - - -/** - * Block used to get a rotation matrix on Z Axis - */ -class RotationZBlock extends NodeGeometryBlock { - /** - * Create a new RotationZBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("angle", NodeGeometryBlockConnectionPointTypes.Float, false, 0); - this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "RotationZBlock"; - } - /** - * Gets the angle input component - */ - get angle() { - return this._inputs[0]; - } - /** - * Gets the matrix output component - */ - get matrix() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.angle.isConnected) { - const angleInput = new GeometryInputBlock("Angle"); - angleInput.value = 0; - angleInput.output.connectTo(this.angle); - } - } - _buildBlock(state) { - super._buildBlock(state); - this.matrix._storedFunction = (state) => { - return math_vector_Matrix.RotationZ(this.angle.getConnectedValue(state)); - }; - } -} -RegisterClass("BABYLON.RotationZBlock", RotationZBlock); -//# sourceMappingURL=rotationZBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/scalingBlock.js - - - - - -/** - * Block used to get a scaling matrix - */ -class ScalingBlock extends NodeGeometryBlock { - /** - * Create a new ScalingBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("scale", NodeGeometryBlockConnectionPointTypes.Vector3, false, math_vector_Vector3.One()); - this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "ScalingBlock"; - } - /** - * Gets the scale input component - */ - get scale() { - return this._inputs[0]; - } - /** - * Gets the matrix output component - */ - get matrix() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.scale.isConnected) { - const scaleInput = new GeometryInputBlock("Scale"); - scaleInput.value = new math_vector_Vector3(1, 1, 1); - scaleInput.output.connectTo(this.scale); - } - } - _buildBlock(state) { - super._buildBlock(state); - this.matrix._storedFunction = (state) => { - const value = this.scale.getConnectedValue(state); - return math_vector_Matrix.Scaling(value.x, value.y, value.z); - }; - } -} -RegisterClass("BABYLON.ScalingBlock", ScalingBlock); -//# sourceMappingURL=scalingBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/alignBlock.js - - - - -/** - * Block used to get a align matrix - */ -class AlignBlock extends NodeGeometryBlock { - /** - * Create a new AlignBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("source", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.Up()); - this.registerInput("target", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.Left()); - this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "AlignBlock"; - } - /** - * Gets the source input component - */ - get source() { - return this._inputs[0]; - } - /** - * Gets the target input component - */ - get target() { - return this._inputs[1]; - } - /** - * Gets the matrix output component - */ - get matrix() { - return this._outputs[0]; - } - _buildBlock(state) { - super._buildBlock(state); - this.matrix._storedFunction = (state) => { - const source = this.source.getConnectedValue(state).clone(); - const target = this.target.getConnectedValue(state).clone(); - const result = new math_vector_Matrix(); - source.normalize(); - target.normalize(); - math_vector_Matrix.RotationAlignToRef(source, target, result); - return result; - }; - } -} -RegisterClass("BABYLON.AlignBlock", AlignBlock); -//# sourceMappingURL=alignBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Matrices/translationBlock.js - - - - - -/** - * Block used to get a translation matrix - */ -class TranslationBlock extends NodeGeometryBlock { - /** - * Create a new TranslationBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("translation", NodeGeometryBlockConnectionPointTypes.Vector3, false, math_vector_Vector3.Zero()); - this.registerOutput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "TranslationBlock"; - } - /** - * Gets the translation input component - */ - get translation() { - return this._inputs[0]; - } - /** - * Gets the matrix output component - */ - get matrix() { - return this._outputs[0]; - } - autoConfigure() { - if (!this.translation.isConnected) { - const translationInput = new GeometryInputBlock("Translation"); - translationInput.value = new math_vector_Vector3(0, 0, 0); - translationInput.output.connectTo(this.translation); - } - } - _buildBlock(state) { - super._buildBlock(state); - this.matrix._storedFunction = (state) => { - const value = this.translation.getConnectedValue(state); - return math_vector_Matrix.Translation(value.x, value.y, value.z); - }; - } -} -RegisterClass("BABYLON.TranslationBlock", TranslationBlock); -//# sourceMappingURL=translationBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateOnVerticesBlock.js - - - - - - - -/** - * Block used to instance geometry on every vertex of a geometry - */ -class InstantiateOnVerticesBlock extends NodeGeometryBlock { - /** - * Create a new InstantiateOnVerticesBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this._indexTranslation = null; - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = true; - /** - * Gets or sets a boolean indicating if the block should remove duplicated positions - */ - this.removeDuplicatedPositions = true; - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.Zero()); - this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.One()); - this.registerInput("density", NodeGeometryBlockConnectionPointTypes.Float, true, 1, 0, 1); - this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current index in the current flow - * @returns the current index - */ - getExecutionIndex() { - return this._indexTranslation ? this._indexTranslation[this._currentIndex] : this._currentIndex; - } - /** - * Gets the current loop index in the current flow - * @returns the current loop index - */ - getExecutionLoopIndex() { - return this._currentLoopIndex; - } - /** - * Gets the current face index in the current flow - * @returns the current face index - */ - getExecutionFaceIndex() { - return 0; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "InstantiateOnVerticesBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the instance input component - */ - get instance() { - return this._inputs[1]; - } - /** - * Gets the rotation input component - */ - get rotation() { - return this._inputs[2]; - } - /** - * Gets the scaling input component - */ - get scaling() { - return this._inputs[3]; - } - /** - * Gets the density input component - */ - get density() { - return this._inputs[4]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - const func = (state) => { - state.executionContext = this; - this._vertexData = this.geometry.getConnectedValue(state); - state.geometryContext = this._vertexData; - if (!this._vertexData || !this._vertexData.positions || !this.instance.isConnected) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = null; - return; - } - // Processing - let vertexCount = this._vertexData.positions.length / 3; - const additionalVertexData = []; - const currentPosition = new math_vector_Vector3(); - const alreadyDone = new Array(); - let vertices = this._vertexData.positions; - this._currentLoopIndex = 0; - if (this.removeDuplicatedPositions) { - this._indexTranslation = {}; - for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { - const x = vertices[this._currentIndex * 3]; - const y = vertices[this._currentIndex * 3 + 1]; - const z = vertices[this._currentIndex * 3 + 2]; - let found = false; - for (let index = 0; index < alreadyDone.length; index += 3) { - if (Math.abs(alreadyDone[index] - x) < math_constants_Epsilon && Math.abs(alreadyDone[index + 1] - y) < math_constants_Epsilon && Math.abs(alreadyDone[index + 2] - z) < math_constants_Epsilon) { - found = true; - break; - } - } - if (found) { - continue; - } - this._indexTranslation[alreadyDone.length / 3] = this._currentIndex; - alreadyDone.push(x, y, z); - } - vertices = alreadyDone; - vertexCount = vertices.length / 3; - } - else { - this._indexTranslation = null; - } - for (this._currentIndex = 0; this._currentIndex < vertexCount; this._currentIndex++) { - const instanceGeometry = this.instance.getConnectedValue(state); - if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) { - continue; - } - const density = this.density.getConnectedValue(state); - if (density < 1) { - if (Math.random() > density) { - continue; - } - } - currentPosition.fromArray(vertices, this._currentIndex * 3); - // Clone the instance - const clone = instanceGeometry.clone(); - // Transform - const scaling = state.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, math_vector_Vector3.OneReadOnly); - const rotation = this.rotation.getConnectedValue(state) || math_vector_Vector3.ZeroReadOnly; - state._instantiate(clone, currentPosition, rotation, scaling, additionalVertexData); - this._currentLoopIndex++; - } - // Merge - if (additionalVertexData.length) { - if (additionalVertexData.length === 1) { - this._vertexData = additionalVertexData[0]; - } - else { - // We do not merge the main one as user can use a merge node if wanted - const main = additionalVertexData.splice(0, 1)[0]; - this._vertexData = main.merge(additionalVertexData, true, false, true, true); - } - } - return this._vertexData; - }; - // Storage - if (this.evaluateContext) { - this.output._storedFunction = func; - } - else { - this.output._storedValue = func(state); - } - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions ? "true" : "false"};\n`; - codeString += `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.removeDuplicatedPositions = this.removeDuplicatedPositions; - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.removeDuplicatedPositions = serializationObject.removeDuplicatedPositions; - if (serializationObject.evaluateContext !== undefined) { - this.evaluateContext = serializationObject.evaluateContext; - } - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], InstantiateOnVerticesBlock.prototype, "evaluateContext", void 0); -__decorate([ - editableInPropertyPage("Remove duplicated positions", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { update: true } }) -], InstantiateOnVerticesBlock.prototype, "removeDuplicatedPositions", void 0); -RegisterClass("BABYLON.InstantiateOnVerticesBlock", InstantiateOnVerticesBlock); -//# sourceMappingURL=instantiateOnVerticesBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateOnFacesBlock.js - - - - - - -/** - * Block used to instance geometry on every face of a geometry - */ -class InstantiateOnFacesBlock extends NodeGeometryBlock { - /** - * Create a new InstantiateOnFacesBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this._currentPosition = new math_vector_Vector3(); - this._vertex0 = new math_vector_Vector3(); - this._vertex1 = new math_vector_Vector3(); - this._vertex2 = new math_vector_Vector3(); - this._tempVector0 = new math_vector_Vector3(); - this._tempVector1 = new math_vector_Vector3(); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = true; - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.Zero()); - this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.One()); - this.registerInput("count", NodeGeometryBlockConnectionPointTypes.Int, true, 256); - this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current index in the current flow - * @returns the current index - */ - getExecutionIndex() { - return 0; - } - /** - * Gets the current face index in the current flow - * @returns the current face index - */ - getExecutionFaceIndex() { - return this._currentFaceIndex; - } - /** - * Gets the current loop index in the current flow - * @returns the current loop index - */ - getExecutionLoopIndex() { - return this._currentLoopIndex; - } - /** - * Gets the value associated with a contextual positions - * @returns the value associated with the source - */ - getOverridePositionsContextualValue() { - return this._currentPosition; - } - /** - * Gets the value associated with a contextual normals - * @returns the value associated with the source - */ - getOverrideNormalsContextualValue() { - this._vertex1.subtractToRef(this._vertex0, this._tempVector0); - this._vertex2.subtractToRef(this._vertex1, this._tempVector1); - this._tempVector0.normalize(); - this._tempVector1.normalize(); - return math_vector_Vector3.Cross(this._tempVector1, this._tempVector0); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "InstantiateOnFacesBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the instance input component - */ - get instance() { - return this._inputs[1]; - } - /** - * Gets the rotation input component - */ - get rotation() { - return this._inputs[2]; - } - /** - * Gets the scaling input component - */ - get scaling() { - return this._inputs[3]; - } - /** - * Gets the count input component - */ - get count() { - return this._inputs[4]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - const func = (state) => { - state.executionContext = this; - this._vertexData = this.geometry.getConnectedValue(state); - state.geometryContext = this._vertexData; - if (!this._vertexData || !this._vertexData.positions || !this._vertexData.indices || !this.instance.isConnected) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = null; - return; - } - // Processing - let instanceGeometry = null; - const instanceCount = this.count.getConnectedValue(state); - const faceCount = this._vertexData.indices.length / 3; - const instancePerFace = instanceCount / faceCount; - let accumulatedCount = 0; - const additionalVertexData = []; - let totalDone = 0; - this._currentLoopIndex = 0; - for (this._currentFaceIndex = 0; this._currentFaceIndex < faceCount; this._currentFaceIndex++) { - // Extract face vertices - this._vertex0.fromArray(this._vertexData.positions, this._vertexData.indices[this._currentFaceIndex * 3] * 3); - this._vertex1.fromArray(this._vertexData.positions, this._vertexData.indices[this._currentFaceIndex * 3 + 1] * 3); - this._vertex2.fromArray(this._vertexData.positions, this._vertexData.indices[this._currentFaceIndex * 3 + 2] * 3); - accumulatedCount += instancePerFace; - const countPerFace = (accumulatedCount | 0) - totalDone; - if (countPerFace < 1) { - continue; - } - for (let faceDispatchCount = 0; faceDispatchCount < countPerFace; faceDispatchCount++) { - if (totalDone >= instanceCount) { - break; - } - // Get random point on face - let x = Math.random(); - let y = Math.random(); - if (x > y) { - const temp = x; - x = y; - y = temp; - } - const s = x; - const t = y - x; - const u = 1 - s - t; - this._currentPosition.set(s * this._vertex0.x + t * this._vertex1.x + u * this._vertex2.x, s * this._vertex0.y + t * this._vertex1.y + u * this._vertex2.y, s * this._vertex0.z + t * this._vertex1.z + u * this._vertex2.z); - // Clone the instance - instanceGeometry = this.instance.getConnectedValue(state); - if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) { - continue; - } - const clone = instanceGeometry.clone(); - const scaling = state.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, math_vector_Vector3.OneReadOnly); - const rotation = this.rotation.getConnectedValue(state) || math_vector_Vector3.ZeroReadOnly; - state._instantiate(clone, this._currentPosition, rotation, scaling, additionalVertexData); - totalDone++; - this._currentLoopIndex++; - } - } - // Merge - if (additionalVertexData.length) { - if (additionalVertexData.length === 1) { - this._vertexData = additionalVertexData[0]; - } - else { - // We do not merge the main one as user can use a merge node if wanted - const main = additionalVertexData.splice(0, 1)[0]; - this._vertexData = main.merge(additionalVertexData, true, false, true, true); - } - } - return this._vertexData; - }; - // Storage - if (this.evaluateContext) { - this.output._storedFunction = func; - } - else { - this.output._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - if (serializationObject.evaluateContext !== undefined) { - this.evaluateContext = serializationObject.evaluateContext; - } - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], InstantiateOnFacesBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.InstantiateOnFacesBlock", InstantiateOnFacesBlock); -//# sourceMappingURL=instantiateOnFacesBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateOnVolumeBlock.js - - - - - - - - -/** - * Block used to instance geometry inside a geometry - */ -class InstantiateOnVolumeBlock extends NodeGeometryBlock { - /** - * Create a new InstantiateOnVolumeBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this._currentPosition = new math_vector_Vector3(); - this._vertex0 = new math_vector_Vector3(); - this._vertex1 = new math_vector_Vector3(); - this._vertex2 = new math_vector_Vector3(); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = true; - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.Zero()); - this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.One()); - this.registerInput("count", NodeGeometryBlockConnectionPointTypes.Int, true, 256); - this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current index in the current flow - * @returns the current index - */ - getExecutionIndex() { - return 0; - } - /** - * Gets the current face index in the current flow - * @returns the current face index - */ - getExecutionFaceIndex() { - return 0; - } - /** - * Gets the current loop index in the current flow - * @returns the current loop index - */ - getExecutionLoopIndex() { - return this._currentLoopIndex; - } - /** - * Gets the value associated with a contextual positions - * @returns the value associated with the source - */ - getOverridePositionsContextualValue() { - return this._currentPosition; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "InstantiateOnVolumeBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the instance input component - */ - get instance() { - return this._inputs[1]; - } - /** - * Gets the rotation input component - */ - get rotation() { - return this._inputs[2]; - } - /** - * Gets the scaling input component - */ - get scaling() { - return this._inputs[3]; - } - /** - * Gets the count input component - */ - get count() { - return this._inputs[4]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - const func = (state) => { - state.executionContext = this; - this._vertexData = this.geometry.getConnectedValue(state); - state.geometryContext = this._vertexData; - if (!this._vertexData || !this._vertexData.positions || !this._vertexData.indices || !this.instance.isConnected) { - state.executionContext = null; - state.geometryContext = null; - this.output._storedValue = null; - return; - } - // Processing - let instanceGeometry = null; - const instanceCount = this.count.getConnectedValue(state); - const additionalVertexData = []; - const boundingInfo = extractMinAndMax(this._vertexData.positions, 0, this._vertexData.positions.length / 3); - const min = boundingInfo.minimum; - const max = boundingInfo.maximum; - const direction = new math_vector_Vector3(1, 0, 0); - const faceCount = this._vertexData.indices.length / 3; - this._currentLoopIndex = 0; - for (let index = 0; index < instanceCount; index++) { - this._currentPosition.set(Math.random() * (max.x - min.x) + min.x, Math.random() * (max.y - min.y) + min.y, Math.random() * (max.z - min.z) + min.z); - // Cast a ray from the random point in an arbitrary direction - const ray = new ray_Ray(this._currentPosition, direction); - let intersectionCount = 0; - for (let currentFaceIndex = 0; currentFaceIndex < faceCount; currentFaceIndex++) { - // Extract face vertices - this._vertex0.fromArray(this._vertexData.positions, this._vertexData.indices[currentFaceIndex * 3] * 3); - this._vertex1.fromArray(this._vertexData.positions, this._vertexData.indices[currentFaceIndex * 3 + 1] * 3); - this._vertex2.fromArray(this._vertexData.positions, this._vertexData.indices[currentFaceIndex * 3 + 2] * 3); - const currentIntersectInfo = ray.intersectsTriangle(this._vertex0, this._vertex1, this._vertex2); - if (currentIntersectInfo && currentIntersectInfo.distance > 0) { - intersectionCount++; - } - } - if (intersectionCount % 2 === 0) { - // We are outside, try again - index--; - continue; - } - // Clone the instance - instanceGeometry = this.instance.getConnectedValue(state); - if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) { - continue; - } - const clone = instanceGeometry.clone(); - const scaling = state.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, math_vector_Vector3.OneReadOnly); - const rotation = this.rotation.getConnectedValue(state) || math_vector_Vector3.ZeroReadOnly; - state._instantiate(clone, this._currentPosition, rotation, scaling, additionalVertexData); - this._currentLoopIndex++; - } - // Merge - if (additionalVertexData.length) { - if (additionalVertexData.length === 1) { - this._vertexData = additionalVertexData[0]; - } - else { - // We do not merge the main one as user can use a merge node if wanted - const main = additionalVertexData.splice(0, 1)[0]; - this._vertexData = main.merge(additionalVertexData, true, false, true, true); - } - } - return this._vertexData; - }; - // Storage - if (this.evaluateContext) { - this.output._storedFunction = func; - } - else { - this.output._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - if (serializationObject.evaluateContext !== undefined) { - this.evaluateContext = serializationObject.evaluateContext; - } - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], InstantiateOnVolumeBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.InstantiateOnVolumeBlock", InstantiateOnVolumeBlock); -//# sourceMappingURL=instantiateOnVolumeBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Instances/instantiateBlock.js - - - - - - -/** - * Block used to instantiate a geometry inside a loop - */ -class InstantiateBlock extends NodeGeometryBlock { - /** - * Create a new InstantiateBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets or sets a boolean indicating that this block can evaluate context - * Build performance is improved when this value is set to false as the system will cache values instead of reevaluating everything per context change - */ - this.evaluateContext = true; - this.registerInput("instance", NodeGeometryBlockConnectionPointTypes.Geometry, true); - this.registerInput("count", NodeGeometryBlockConnectionPointTypes.Int, true, 1); - this.registerInput("position", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.Zero()); - this.registerInput("rotation", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.Zero()); - this.registerInput("scaling", NodeGeometryBlockConnectionPointTypes.Vector3, true, math_vector_Vector3.One()); - this.registerInput("matrix", NodeGeometryBlockConnectionPointTypes.Matrix, true); - this.scaling.acceptedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Float); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the current index in the current flow - * @returns the current index - */ - getExecutionIndex() { - return this._currentIndex; - } - /** - * Gets the current loop index in the current flow - * @returns the current loop index - */ - getExecutionLoopIndex() { - return this._currentIndex; - } - /** - * Gets the current face index in the current flow - * @returns the current face index - */ - getExecutionFaceIndex() { - return 0; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "InstantiateBlock"; - } - /** - * Gets the instance input component - */ - get instance() { - return this._inputs[0]; - } - /** - * Gets the instance input component - */ - get count() { - return this._inputs[1]; - } - /** - * Gets the position input component - */ - get position() { - return this._inputs[2]; - } - /** - * Gets the rotation input component - */ - get rotation() { - return this._inputs[3]; - } - /** - * Gets the scaling input component - */ - get scaling() { - return this._inputs[4]; - } - /** - * Gets the matrix input component - */ - get matrix() { - return this._inputs[5]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock(state) { - const func = (state) => { - state.executionContext = this; - // Processing - const iterationCount = this.count.getConnectedValue(state); - const additionalVertexData = []; - for (this._currentIndex = 0; this._currentIndex < iterationCount; this._currentIndex++) { - const instanceGeometry = this.instance.getConnectedValue(state); - if (!instanceGeometry || !instanceGeometry.positions || instanceGeometry.positions.length === 0) { - continue; - } - // Clone the instance - const clone = instanceGeometry.clone(); - // Transform - if (this.matrix.isConnected) { - const transform = this.matrix.getConnectedValue(state); - state._instantiateWithMatrix(clone, transform, additionalVertexData); - } - else { - const position = this.position.getConnectedValue(state) || math_vector_Vector3.ZeroReadOnly; - const scaling = state.adaptInput(this.scaling, NodeGeometryBlockConnectionPointTypes.Vector3, math_vector_Vector3.OneReadOnly); - const rotation = this.rotation.getConnectedValue(state) || math_vector_Vector3.ZeroReadOnly; - state._instantiate(clone, position, rotation, scaling, additionalVertexData); - } - } - // Merge - if (additionalVertexData.length) { - if (additionalVertexData.length === 1) { - this._vertexData = additionalVertexData[0]; - } - else { - // We do not merge the main one as user can use a merge node if wanted - const main = additionalVertexData.splice(0, 1)[0]; - this._vertexData = main.merge(additionalVertexData, true, false, true, true); - } - } - return this._vertexData; - }; - // Storage - if (this.evaluateContext) { - this.output._storedFunction = func; - } - else { - this.output._storedValue = func(state); - } - } - _dumpPropertiesCode() { - const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.evaluateContext = ${this.evaluateContext ? "true" : "false"};\n`; - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - const serializationObject = super.serialize(); - serializationObject.evaluateContext = this.evaluateContext; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this.evaluateContext = serializationObject.evaluateContext; - } -} -__decorate([ - editableInPropertyPage("Evaluate context", PropertyTypeForEdition.Boolean, "ADVANCED", { notifiers: { rebuild: true } }) -], InstantiateBlock.prototype, "evaluateContext", void 0); -RegisterClass("BABYLON.InstantiateBlock", InstantiateBlock); -//# sourceMappingURL=instantiateBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/intFloatConverterBlock.js - - - -/** - * Defines a block used to convert from int to float - */ -class IntFloatConverterBlock extends NodeGeometryBlock { - /** - * Create a new IntFloatConverterBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("float ", NodeGeometryBlockConnectionPointTypes.Float, true); - this.registerInput("int ", NodeGeometryBlockConnectionPointTypes.Int, true); - this.registerOutput("float", NodeGeometryBlockConnectionPointTypes.Float); - this.registerOutput("int", NodeGeometryBlockConnectionPointTypes.Int); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "IntFloatConverterBlock"; - } - /** - * Gets the float input component - */ - get floatIn() { - return this._inputs[0]; - } - /** - * Gets the int input component - */ - get intIn() { - return this._inputs[1]; - } - /** - * Gets the float output component - */ - get floatOut() { - return this._outputs[0]; - } - /** - * Gets the int output component - */ - get intOut() { - return this._outputs[1]; - } - _inputRename(name) { - if (name === "float ") { - return "floatIn"; - } - if (name === "int ") { - return "intIn"; - } - return name; - } - _buildBlock() { - this.floatOut._storedFunction = (state) => { - if (this.floatIn.isConnected) { - return this.floatIn.getConnectedValue(state); - } - if (this.intIn.isConnected) { - return this.intIn.getConnectedValue(state); - } - return 0; - }; - this.intOut._storedFunction = (state) => { - if (this.floatIn.isConnected) { - return this.floatIn.getConnectedValue(state) | 0; - } - if (this.intIn.isConnected) { - return this.intIn.getConnectedValue(state) | 0; - } - return 0; - }; - } -} -RegisterClass("BABYLON.IntFloatConverterBlock", IntFloatConverterBlock); -//# sourceMappingURL=intFloatConverterBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/debugBlock.js - - - -/** - * Defines a block used to debug values going through it - */ -class DebugBlock extends NodeGeometryBlock { - /** - * Create a new DebugBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** - * Gets the log entries - */ - this.log = []; - this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); - this._outputs[0]._typeConnectionSource = this._inputs[0]; - this._inputs[0].excludedConnectionPointTypes.push(NodeGeometryBlockConnectionPointTypes.Geometry); - } - /** - * Gets the time spent to build this block (in ms) - */ - get buildExecutionTime() { - return 0; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "DebugBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - _buildBlock() { - if (!this.input.isConnected) { - this.output._storedFunction = null; - this.output._storedValue = null; - return; - } - this.log = []; - this.output._storedFunction = (state) => { - const input = this.input.getConnectedValue(state); - this.log.push(input !== undefined && input !== null ? input.toString() : "null"); - return input; - }; - } -} -RegisterClass("BABYLON.DebugBlock", DebugBlock); -//# sourceMappingURL=debugBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/geometryInfoBlock.js - - - -/** - * Block used to get information about a geometry - */ -class GeometryInfoBlock extends NodeGeometryBlock { - /** - * Create a new GeometryInfoBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this.registerInput("geometry", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.Geometry); - this.registerOutput("id", NodeGeometryBlockConnectionPointTypes.Int); - this.registerOutput("collectionId", NodeGeometryBlockConnectionPointTypes.Int); - this.registerOutput("verticesCount", NodeGeometryBlockConnectionPointTypes.Int); - this.registerOutput("facesCount", NodeGeometryBlockConnectionPointTypes.Int); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "GeometryInfoBlock"; - } - /** - * Gets the geometry input component - */ - get geometry() { - return this._inputs[0]; - } - /** - * Gets the geometry output component - */ - get output() { - return this._outputs[0]; - } - /** - * Gets the id output component - */ - get id() { - return this._outputs[1]; - } - /** - * Gets the collectionId output component - */ - get collectionId() { - return this._outputs[2]; - } - /** - * Gets the verticesCount output component - */ - get verticesCount() { - return this._outputs[3]; - } - /** - * Gets the facesCount output component - */ - get facesCount() { - return this._outputs[4]; - } - _buildBlock() { - if (!this.geometry.isConnected) { - this.id._storedValue = 0; - this.collectionId._storedValue = 0; - this.verticesCount._storedValue = 0; - this.facesCount._storedValue = 0; - this.output._storedValue = 0; - this.id._storedFunction = null; - this.collectionId._storedFunction = null; - this.verticesCount._storedFunction = null; - this.facesCount._storedFunction = null; - this.output._storedFunction = null; - return; - } - this.output._storedFunction = (state) => { - return this._currentVertexData || this.geometry.getConnectedValue(state); - }; - this.id._storedFunction = (state) => { - this._currentVertexData = this.geometry.getConnectedValue(state); - return this._currentVertexData.uniqueId; - }; - this.collectionId._storedFunction = (state) => { - this._currentVertexData = this.geometry.getConnectedValue(state); - return this._currentVertexData.metadata ? this._currentVertexData.metadata.collectionId : 0; - }; - this.verticesCount._storedFunction = (state) => { - this._currentVertexData = this.geometry.getConnectedValue(state); - return this._currentVertexData.positions ? this._currentVertexData.positions.length / 3 : 0; - }; - this.facesCount._storedFunction = (state) => { - this._currentVertexData = this.geometry.getConnectedValue(state); - return this._currentVertexData.indices ? this._currentVertexData.indices.length / 3 : 0; - }; - } -} -RegisterClass("BABYLON.GeometryInfoBlock", GeometryInfoBlock); -//# sourceMappingURL=geometryInfoBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Teleport/teleportInBlock.js - - - -/** - * Defines a block used to teleport a value to an endpoint - */ -class TeleportInBlock extends NodeGeometryBlock { - /** Gets the list of attached endpoints */ - get endpoints() { - return this._endpoints; - } - /** - * Create a new TeleportInBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - this._endpoints = []; - this.registerInput("input", NodeGeometryBlockConnectionPointTypes.AutoDetect); - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "TeleportInBlock"; - } - /** - * Gets the input component - */ - get input() { - return this._inputs[0]; - } - _dumpCode(uniqueNames, alreadyDumped) { - let codeString = super._dumpCode(uniqueNames, alreadyDumped); - for (const endpoint of this.endpoints) { - if (alreadyDumped.indexOf(endpoint) === -1) { - codeString += endpoint._dumpCode(uniqueNames, alreadyDumped); - } - } - return codeString; - } - /** - * Add an enpoint to this block - * @param endpoint define the endpoint to attach to - */ - attachToEndpoint(endpoint) { - endpoint.detach(); - this._endpoints.push(endpoint); - endpoint._entryPoint = this; - endpoint._outputs[0]._typeConnectionSource = this._inputs[0]; - endpoint._tempEntryPointUniqueId = null; - endpoint.name = "> " + this.name; - } - /** - * Remove enpoint from this block - * @param endpoint define the endpoint to remove - */ - detachFromEndpoint(endpoint) { - const index = this._endpoints.indexOf(endpoint); - if (index !== -1) { - this._endpoints.splice(index, 1); - endpoint._outputs[0]._typeConnectionSource = null; - endpoint._entryPoint = null; - } - } - _buildBlock() { - for (const endpoint of this._endpoints) { - endpoint.output._storedFunction = (state) => { - return this.input.getConnectedValue(state); - }; - } - } -} -RegisterClass("BABYLON.TeleportInBlock", TeleportInBlock); -//# sourceMappingURL=teleportInBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/Blocks/Teleport/teleportOutBlock.js - - - -/** - * Defines a block used to receive a value from a teleport entry point - */ -class TeleportOutBlock extends NodeGeometryBlock { - /** - * Create a new TeleportOutBlock - * @param name defines the block name - */ - constructor(name) { - super(name); - /** @internal */ - this._entryPoint = null; - /** @internal */ - this._tempEntryPointUniqueId = null; - this.registerOutput("output", NodeGeometryBlockConnectionPointTypes.BasedOnInput); - } - /** - * Gets the entry point - */ - get entryPoint() { - return this._entryPoint; - } - /** - * Gets the current class name - * @returns the class name - */ - getClassName() { - return "TeleportOutBlock"; - } - /** - * Gets the output component - */ - get output() { - return this._outputs[0]; - } - /** Detach from entry point */ - detach() { - if (!this._entryPoint) { - return; - } - this._entryPoint.detachFromEndpoint(this); - } - _buildBlock() { - // Do nothing - // All work done by the emitter - } - _customBuildStep(state) { - if (this.entryPoint) { - this.entryPoint.build(state); - } - } - _dumpCode(uniqueNames, alreadyDumped) { - let codeString = ""; - if (this.entryPoint) { - if (alreadyDumped.indexOf(this.entryPoint) === -1) { - codeString += this.entryPoint._dumpCode(uniqueNames, alreadyDumped); - } - } - return codeString + super._dumpCode(uniqueNames, alreadyDumped); - } - _dumpCodeForOutputConnections(alreadyDumped) { - let codeString = super._dumpCodeForOutputConnections(alreadyDumped); - if (this.entryPoint) { - codeString += this.entryPoint._dumpCodeForOutputConnections(alreadyDumped); - } - return codeString; - } - /** - * Clone the current block to a new identical block - * @returns a copy of the current block - */ - clone() { - const clone = super.clone(); - if (this.entryPoint) { - this.entryPoint.attachToEndpoint(clone); - } - return clone; - } - _dumpPropertiesCode() { - let codeString = super._dumpPropertiesCode(); - if (this.entryPoint) { - codeString += `${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`; - } - return codeString; - } - /** - * Serializes this block in a JSON representation - * @returns the serialized block object - */ - serialize() { - var _a, _b; - const serializationObject = super.serialize(); - serializationObject.entryPoint = (_b = (_a = this.entryPoint) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : ""; - return serializationObject; - } - _deserialize(serializationObject) { - super._deserialize(serializationObject); - this._tempEntryPointUniqueId = serializationObject.entryPoint; - } -} -RegisterClass("BABYLON.TeleportOutBlock", TeleportOutBlock); -//# sourceMappingURL=teleportOutBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/Node/index.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Meshes/index.js -/* eslint-disable import/export */ -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - - - - - - - - - - - - - - - - - - -// eslint-disable-next-line no-duplicate-imports - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Morph/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Navigation/INavigationEngine.js - -//# sourceMappingURL=INavigationEngine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Navigation/Plugins/recastJSPlugin.js - - - - - - -/** - * RecastJS navigation plugin - */ -class RecastJSPlugin { - /** - * Initializes the recastJS plugin - * @param recastInjection can be used to inject your own recast reference - */ - constructor(recastInjection = Recast) { - /** - * Reference to the Recast library - */ - this.bjsRECAST = {}; - /** - * plugin name - */ - this.name = "RecastJSPlugin"; - this._maximumSubStepCount = 10; - this._timeStep = 1 / 60; - this._timeFactor = 1; - this._worker = null; - if (typeof recastInjection === "function") { - Logger.Error("RecastJS is not ready. Please make sure you await Recast() before using the plugin."); - } - else { - this.bjsRECAST = recastInjection; - } - if (!this.isSupported()) { - Logger.Error("RecastJS is not available. Please make sure you included the js file."); - return; - } - this.setTimeStep(); - this._tempVec1 = new this.bjsRECAST.Vec3(); - this._tempVec2 = new this.bjsRECAST.Vec3(); - } - /** - * Set worker URL to be used when generating a new navmesh - * @param workerURL url string - * @returns boolean indicating if worker is created - */ - setWorkerURL(workerURL) { - if (window && window.Worker) { - this._worker = new Worker(workerURL); - return true; - } - return false; - } - /** - * Set the time step of the navigation tick update. - * Default is 1/60. - * A value of 0 will disable fixed time update - * @param newTimeStep the new timestep to apply to this world. - */ - setTimeStep(newTimeStep = 1 / 60) { - this._timeStep = newTimeStep; - } - /** - * Get the time step of the navigation tick update. - * @returns the current time step - */ - getTimeStep() { - return this._timeStep; - } - /** - * If delta time in navigation tick update is greater than the time step - * a number of sub iterations are done. If more iterations are need to reach deltatime - * they will be discarded. - * A value of 0 will set to no maximum and update will use as many substeps as needed - * @param newStepCount the maximum number of iterations - */ - setMaximumSubStepCount(newStepCount = 10) { - this._maximumSubStepCount = newStepCount; - } - /** - * Get the maximum number of iterations per navigation tick update - * @returns the maximum number of iterations - */ - getMaximumSubStepCount() { - return this._maximumSubStepCount; - } - /** - * Time factor applied when updating crowd agents (default 1). A value of 0 will pause crowd updates. - * @param value the time factor applied at update - */ - set timeFactor(value) { - this._timeFactor = Math.max(value, 0); - } - /** - * Get the time factor used for crowd agent update - * @returns the time factor - */ - get timeFactor() { - return this._timeFactor; - } - /** - * Creates a navigation mesh - * @param meshes array of all the geometry used to compute the navigation mesh - * @param parameters bunch of parameters used to filter geometry - * @param completion callback when data is available from the worker. Not used without a worker - */ - createNavMesh(meshes, parameters, completion) { - if (this._worker && !completion) { - console.warn("A worker is avaible but no completion callback. Defaulting to blocking navmesh creation"); - } - else if (!this._worker && completion) { - console.warn("A completion callback is avaible but no worker. Defaulting to blocking navmesh creation"); - } - this.navMesh = new this.bjsRECAST.NavMesh(); - let index; - let tri; - let pt; - const indices = []; - const positions = []; - let offset = 0; - for (index = 0; index < meshes.length; index++) { - if (meshes[index]) { - const mesh = meshes[index]; - const meshIndices = mesh.getIndices(); - if (!meshIndices) { - continue; - } - const meshPositions = mesh.getVerticesData(VertexBuffer.PositionKind, false, false); - if (!meshPositions) { - continue; - } - const worldMatrices = []; - const worldMatrix = mesh.computeWorldMatrix(true); - if (mesh.hasThinInstances) { - const thinMatrices = mesh.thinInstanceGetWorldMatrices(); - for (let instanceIndex = 0; instanceIndex < thinMatrices.length; instanceIndex++) { - const tmpMatrix = new Matrix(); - const thinMatrix = thinMatrices[instanceIndex]; - thinMatrix.multiplyToRef(worldMatrix, tmpMatrix); - worldMatrices.push(tmpMatrix); - } - } - else { - worldMatrices.push(worldMatrix); - } - for (let matrixIndex = 0; matrixIndex < worldMatrices.length; matrixIndex++) { - const wm = worldMatrices[matrixIndex]; - for (tri = 0; tri < meshIndices.length; tri++) { - indices.push(meshIndices[tri] + offset); - } - const transformed = Vector3.Zero(); - const position = Vector3.Zero(); - for (pt = 0; pt < meshPositions.length; pt += 3) { - Vector3.FromArrayToRef(meshPositions, pt, position); - Vector3.TransformCoordinatesToRef(position, wm, transformed); - positions.push(transformed.x, transformed.y, transformed.z); - } - offset += meshPositions.length / 3; - } - } - } - if (this._worker && completion) { - // spawn worker and send message - this._worker.postMessage([positions, offset, indices, indices.length, parameters]); - this._worker.onmessage = function (e) { - completion(e.data); - }; - } - else { - // blocking calls - const rc = new this.bjsRECAST.rcConfig(); - rc.cs = parameters.cs; - rc.ch = parameters.ch; - rc.borderSize = parameters.borderSize ? parameters.borderSize : 0; - rc.tileSize = parameters.tileSize ? parameters.tileSize : 0; - rc.walkableSlopeAngle = parameters.walkableSlopeAngle; - rc.walkableHeight = parameters.walkableHeight; - rc.walkableClimb = parameters.walkableClimb; - rc.walkableRadius = parameters.walkableRadius; - rc.maxEdgeLen = parameters.maxEdgeLen; - rc.maxSimplificationError = parameters.maxSimplificationError; - rc.minRegionArea = parameters.minRegionArea; - rc.mergeRegionArea = parameters.mergeRegionArea; - rc.maxVertsPerPoly = parameters.maxVertsPerPoly; - rc.detailSampleDist = parameters.detailSampleDist; - rc.detailSampleMaxError = parameters.detailSampleMaxError; - this.navMesh.build(positions, offset, indices, indices.length, rc); - } - } - /** - * Create a navigation mesh debug mesh - * @param scene is where the mesh will be added - * @returns debug display mesh - */ - createDebugNavMesh(scene) { - let tri; - let pt; - const debugNavMesh = this.navMesh.getDebugNavMesh(); - const triangleCount = debugNavMesh.getTriangleCount(); - const indices = []; - const positions = []; - for (tri = 0; tri < triangleCount * 3; tri++) { - indices.push(tri); - } - for (tri = 0; tri < triangleCount; tri++) { - for (pt = 0; pt < 3; pt++) { - const point = debugNavMesh.getTriangle(tri).getPoint(pt); - positions.push(point.x, point.y, point.z); - } - } - const mesh = new Mesh("NavMeshDebug", scene); - const vertexData = new VertexData(); - vertexData.indices = indices; - vertexData.positions = positions; - vertexData.applyToMesh(mesh, false); - return mesh; - } - /** - * Get a navigation mesh constrained position, closest to the parameter position - * @param position world position - * @returns the closest point to position constrained by the navigation mesh - */ - getClosestPoint(position) { - this._tempVec1.x = position.x; - this._tempVec1.y = position.y; - this._tempVec1.z = position.z; - const ret = this.navMesh.getClosestPoint(this._tempVec1); - const pr = new Vector3(ret.x, ret.y, ret.z); - return pr; - } - /** - * Get a navigation mesh constrained position, closest to the parameter position - * @param position world position - * @param result output the closest point to position constrained by the navigation mesh - */ - getClosestPointToRef(position, result) { - this._tempVec1.x = position.x; - this._tempVec1.y = position.y; - this._tempVec1.z = position.z; - const ret = this.navMesh.getClosestPoint(this._tempVec1); - result.set(ret.x, ret.y, ret.z); - } - /** - * Get a navigation mesh constrained position, within a particular radius - * @param position world position - * @param maxRadius the maximum distance to the constrained world position - * @returns the closest point to position constrained by the navigation mesh - */ - getRandomPointAround(position, maxRadius) { - this._tempVec1.x = position.x; - this._tempVec1.y = position.y; - this._tempVec1.z = position.z; - const ret = this.navMesh.getRandomPointAround(this._tempVec1, maxRadius); - const pr = new Vector3(ret.x, ret.y, ret.z); - return pr; - } - /** - * Get a navigation mesh constrained position, within a particular radius - * @param position world position - * @param maxRadius the maximum distance to the constrained world position - * @param result output the closest point to position constrained by the navigation mesh - */ - getRandomPointAroundToRef(position, maxRadius, result) { - this._tempVec1.x = position.x; - this._tempVec1.y = position.y; - this._tempVec1.z = position.z; - const ret = this.navMesh.getRandomPointAround(this._tempVec1, maxRadius); - result.set(ret.x, ret.y, ret.z); - } - /** - * Compute the final position from a segment made of destination-position - * @param position world position - * @param destination world position - * @returns the resulting point along the navmesh - */ - moveAlong(position, destination) { - this._tempVec1.x = position.x; - this._tempVec1.y = position.y; - this._tempVec1.z = position.z; - this._tempVec2.x = destination.x; - this._tempVec2.y = destination.y; - this._tempVec2.z = destination.z; - const ret = this.navMesh.moveAlong(this._tempVec1, this._tempVec2); - const pr = new Vector3(ret.x, ret.y, ret.z); - return pr; - } - /** - * Compute the final position from a segment made of destination-position - * @param position world position - * @param destination world position - * @param result output the resulting point along the navmesh - */ - moveAlongToRef(position, destination, result) { - this._tempVec1.x = position.x; - this._tempVec1.y = position.y; - this._tempVec1.z = position.z; - this._tempVec2.x = destination.x; - this._tempVec2.y = destination.y; - this._tempVec2.z = destination.z; - const ret = this.navMesh.moveAlong(this._tempVec1, this._tempVec2); - result.set(ret.x, ret.y, ret.z); - } - /** - * Compute a navigation path from start to end. Returns an empty array if no path can be computed - * @param start world position - * @param end world position - * @returns array containing world position composing the path - */ - computePath(start, end) { - let pt; - this._tempVec1.x = start.x; - this._tempVec1.y = start.y; - this._tempVec1.z = start.z; - this._tempVec2.x = end.x; - this._tempVec2.y = end.y; - this._tempVec2.z = end.z; - const navPath = this.navMesh.computePath(this._tempVec1, this._tempVec2); - const pointCount = navPath.getPointCount(); - const positions = []; - for (pt = 0; pt < pointCount; pt++) { - const p = navPath.getPoint(pt); - positions.push(new Vector3(p.x, p.y, p.z)); - } - return positions; - } - /** - * Create a new Crowd so you can add agents - * @param maxAgents the maximum agent count in the crowd - * @param maxAgentRadius the maximum radius an agent can have - * @param scene to attach the crowd to - * @returns the crowd you can add agents to - */ - createCrowd(maxAgents, maxAgentRadius, scene) { - const crowd = new RecastJSCrowd(this, maxAgents, maxAgentRadius, scene); - return crowd; - } - /** - * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...) - * The queries will try to find a solution within those bounds - * default is (1,1,1) - * @param extent x,y,z value that define the extent around the queries point of reference - */ - setDefaultQueryExtent(extent) { - this._tempVec1.x = extent.x; - this._tempVec1.y = extent.y; - this._tempVec1.z = extent.z; - this.navMesh.setDefaultQueryExtent(this._tempVec1); - } - /** - * Get the Bounding box extent specified by setDefaultQueryExtent - * @returns the box extent values - */ - getDefaultQueryExtent() { - const p = this.navMesh.getDefaultQueryExtent(); - return new Vector3(p.x, p.y, p.z); - } - /** - * build the navmesh from a previously saved state using getNavmeshData - * @param data the Uint8Array returned by getNavmeshData - */ - buildFromNavmeshData(data) { - const nDataBytes = data.length * data.BYTES_PER_ELEMENT; - const dataPtr = this.bjsRECAST._malloc(nDataBytes); - const dataHeap = new Uint8Array(this.bjsRECAST.HEAPU8.buffer, dataPtr, nDataBytes); - dataHeap.set(data); - const buf = new this.bjsRECAST.NavmeshData(); - buf.dataPointer = dataHeap.byteOffset; - buf.size = data.length; - this.navMesh = new this.bjsRECAST.NavMesh(); - this.navMesh.buildFromNavmeshData(buf); - // Free memory - this.bjsRECAST._free(dataHeap.byteOffset); - } - /** - * returns the navmesh data that can be used later. The navmesh must be built before retrieving the data - * @returns data the Uint8Array that can be saved and reused - */ - getNavmeshData() { - const navmeshData = this.navMesh.getNavmeshData(); - const arrView = new Uint8Array(this.bjsRECAST.HEAPU8.buffer, navmeshData.dataPointer, navmeshData.size); - const ret = new Uint8Array(navmeshData.size); - ret.set(arrView); - this.navMesh.freeNavmeshData(navmeshData); - return ret; - } - /** - * Get the Bounding box extent result specified by setDefaultQueryExtent - * @param result output the box extent values - */ - getDefaultQueryExtentToRef(result) { - const p = this.navMesh.getDefaultQueryExtent(); - result.set(p.x, p.y, p.z); - } - /** - * Disposes - */ - dispose() { } - /** - * Creates a cylinder obstacle and add it to the navigation - * @param position world position - * @param radius cylinder radius - * @param height cylinder height - * @returns the obstacle freshly created - */ - addCylinderObstacle(position, radius, height) { - this._tempVec1.x = position.x; - this._tempVec1.y = position.y; - this._tempVec1.z = position.z; - return this.navMesh.addCylinderObstacle(this._tempVec1, radius, height); - } - /** - * Creates an oriented box obstacle and add it to the navigation - * @param position world position - * @param extent box size - * @param angle angle in radians of the box orientation on Y axis - * @returns the obstacle freshly created - */ - addBoxObstacle(position, extent, angle) { - this._tempVec1.x = position.x; - this._tempVec1.y = position.y; - this._tempVec1.z = position.z; - this._tempVec2.x = extent.x; - this._tempVec2.y = extent.y; - this._tempVec2.z = extent.z; - return this.navMesh.addBoxObstacle(this._tempVec1, this._tempVec2, angle); - } - /** - * Removes an obstacle created by addCylinderObstacle or addBoxObstacle - * @param obstacle obstacle to remove from the navigation - */ - removeObstacle(obstacle) { - this.navMesh.removeObstacle(obstacle); - } - /** - * If this plugin is supported - * @returns true if plugin is supported - */ - isSupported() { - return this.bjsRECAST !== undefined; - } -} -/** - * Recast detour crowd implementation - */ -class RecastJSCrowd { - /** - * Constructor - * @param plugin recastJS plugin - * @param maxAgents the maximum agent count in the crowd - * @param maxAgentRadius the maximum radius an agent can have - * @param scene to attach the crowd to - * @returns the crowd you can add agents to - */ - constructor(plugin, maxAgents, maxAgentRadius, scene) { - /** - * Link to the detour crowd - */ - this.recastCrowd = {}; - /** - * One transform per agent - */ - this.transforms = new Array(); - /** - * All agents created - */ - this.agents = new Array(); - /** - * agents reach radius - */ - this.reachRadii = new Array(); - /** - * true when a destination is active for an agent and notifier hasn't been notified of reach - */ - this._agentDestinationArmed = new Array(); - /** - * agent current target - */ - this._agentDestination = new Array(); - /** - * Observer for crowd updates - */ - this._onBeforeAnimationsObserver = null; - /** - * Fires each time an agent is in reach radius of its destination - */ - this.onReachTargetObservable = new Observable(); - this.bjsRECASTPlugin = plugin; - this.recastCrowd = new this.bjsRECASTPlugin.bjsRECAST.Crowd(maxAgents, maxAgentRadius, this.bjsRECASTPlugin.navMesh.getNavMesh()); - this._scene = scene; - this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => { - this.update(scene.getEngine().getDeltaTime() * 0.001 * plugin.timeFactor); - }); - } - /** - * Add a new agent to the crowd with the specified parameter a corresponding transformNode. - * You can attach anything to that node. The node position is updated in the scene update tick. - * @param pos world position that will be constrained by the navigation mesh - * @param parameters agent parameters - * @param transform hooked to the agent that will be update by the scene - * @returns agent index - */ - addAgent(pos, parameters, transform) { - const agentParams = new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams(); - agentParams.radius = parameters.radius; - agentParams.height = parameters.height; - agentParams.maxAcceleration = parameters.maxAcceleration; - agentParams.maxSpeed = parameters.maxSpeed; - agentParams.collisionQueryRange = parameters.collisionQueryRange; - agentParams.pathOptimizationRange = parameters.pathOptimizationRange; - agentParams.separationWeight = parameters.separationWeight; - agentParams.updateFlags = 7; - agentParams.obstacleAvoidanceType = 0; - agentParams.queryFilterType = 0; - agentParams.userData = 0; - const agentIndex = this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(pos.x, pos.y, pos.z), agentParams); - this.transforms.push(transform); - this.agents.push(agentIndex); - this.reachRadii.push(parameters.reachRadius ? parameters.reachRadius : parameters.radius); - this._agentDestinationArmed.push(false); - this._agentDestination.push(new Vector3(0, 0, 0)); - return agentIndex; - } - /** - * Returns the agent position in world space - * @param index agent index returned by addAgent - * @returns world space position - */ - getAgentPosition(index) { - const agentPos = this.recastCrowd.getAgentPosition(index); - return new Vector3(agentPos.x, agentPos.y, agentPos.z); - } - /** - * Returns the agent position result in world space - * @param index agent index returned by addAgent - * @param result output world space position - */ - getAgentPositionToRef(index, result) { - const agentPos = this.recastCrowd.getAgentPosition(index); - result.set(agentPos.x, agentPos.y, agentPos.z); - } - /** - * Returns the agent velocity in world space - * @param index agent index returned by addAgent - * @returns world space velocity - */ - getAgentVelocity(index) { - const agentVel = this.recastCrowd.getAgentVelocity(index); - return new Vector3(agentVel.x, agentVel.y, agentVel.z); - } - /** - * Returns the agent velocity result in world space - * @param index agent index returned by addAgent - * @param result output world space velocity - */ - getAgentVelocityToRef(index, result) { - const agentVel = this.recastCrowd.getAgentVelocity(index); - result.set(agentVel.x, agentVel.y, agentVel.z); - } - /** - * Returns the agent next target point on the path - * @param index agent index returned by addAgent - * @returns world space position - */ - getAgentNextTargetPath(index) { - const pathTargetPos = this.recastCrowd.getAgentNextTargetPath(index); - return new Vector3(pathTargetPos.x, pathTargetPos.y, pathTargetPos.z); - } - /** - * Returns the agent next target point on the path - * @param index agent index returned by addAgent - * @param result output world space position - */ - getAgentNextTargetPathToRef(index, result) { - const pathTargetPos = this.recastCrowd.getAgentNextTargetPath(index); - result.set(pathTargetPos.x, pathTargetPos.y, pathTargetPos.z); - } - /** - * Gets the agent state - * @param index agent index returned by addAgent - * @returns agent state - */ - getAgentState(index) { - return this.recastCrowd.getAgentState(index); - } - /** - * returns true if the agent in over an off mesh link connection - * @param index agent index returned by addAgent - * @returns true if over an off mesh link connection - */ - overOffmeshConnection(index) { - return this.recastCrowd.overOffmeshConnection(index); - } - /** - * Asks a particular agent to go to a destination. That destination is constrained by the navigation mesh - * @param index agent index returned by addAgent - * @param destination targeted world position - */ - agentGoto(index, destination) { - this.recastCrowd.agentGoto(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z)); - // arm observer - const item = this.agents.indexOf(index); - if (item > -1) { - this._agentDestinationArmed[item] = true; - this._agentDestination[item].set(destination.x, destination.y, destination.z); - } - } - /** - * Teleport the agent to a new position - * @param index agent index returned by addAgent - * @param destination targeted world position - */ - agentTeleport(index, destination) { - this.recastCrowd.agentTeleport(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z)); - } - /** - * Update agent parameters - * @param index agent index returned by addAgent - * @param parameters agent parameters - */ - updateAgentParameters(index, parameters) { - const agentParams = this.recastCrowd.getAgentParameters(index); - if (parameters.radius !== undefined) { - agentParams.radius = parameters.radius; - } - if (parameters.height !== undefined) { - agentParams.height = parameters.height; - } - if (parameters.maxAcceleration !== undefined) { - agentParams.maxAcceleration = parameters.maxAcceleration; - } - if (parameters.maxSpeed !== undefined) { - agentParams.maxSpeed = parameters.maxSpeed; - } - if (parameters.collisionQueryRange !== undefined) { - agentParams.collisionQueryRange = parameters.collisionQueryRange; - } - if (parameters.pathOptimizationRange !== undefined) { - agentParams.pathOptimizationRange = parameters.pathOptimizationRange; - } - if (parameters.separationWeight !== undefined) { - agentParams.separationWeight = parameters.separationWeight; - } - this.recastCrowd.setAgentParameters(index, agentParams); - } - /** - * remove a particular agent previously created - * @param index agent index returned by addAgent - */ - removeAgent(index) { - this.recastCrowd.removeAgent(index); - const item = this.agents.indexOf(index); - if (item > -1) { - this.agents.splice(item, 1); - this.transforms.splice(item, 1); - this.reachRadii.splice(item, 1); - this._agentDestinationArmed.splice(item, 1); - this._agentDestination.splice(item, 1); - } - } - /** - * get the list of all agents attached to this crowd - * @returns list of agent indices - */ - getAgents() { - return this.agents; - } - /** - * Tick update done by the Scene. Agent position/velocity/acceleration is updated by this function - * @param deltaTime in seconds - */ - update(deltaTime) { - // update obstacles - this.bjsRECASTPlugin.navMesh.update(); - if (deltaTime <= Epsilon) { - return; - } - // update crowd - const timeStep = this.bjsRECASTPlugin.getTimeStep(); - const maxStepCount = this.bjsRECASTPlugin.getMaximumSubStepCount(); - if (timeStep <= Epsilon) { - this.recastCrowd.update(deltaTime); - } - else { - let iterationCount = Math.floor(deltaTime / timeStep); - if (maxStepCount && iterationCount > maxStepCount) { - iterationCount = maxStepCount; - } - if (iterationCount < 1) { - iterationCount = 1; - } - const step = deltaTime / iterationCount; - for (let i = 0; i < iterationCount; i++) { - this.recastCrowd.update(step); - } - } - // update transforms - for (let index = 0; index < this.agents.length; index++) { - // update transform position - const agentIndex = this.agents[index]; - const agentPosition = this.getAgentPosition(agentIndex); - this.transforms[index].position = agentPosition; - // check agent reach destination - if (this._agentDestinationArmed[index]) { - const dx = agentPosition.x - this._agentDestination[index].x; - const dz = agentPosition.z - this._agentDestination[index].z; - const radius = this.reachRadii[index]; - const groundY = this._agentDestination[index].y - this.reachRadii[index]; - const ceilingY = this._agentDestination[index].y + this.reachRadii[index]; - const distanceXZSquared = dx * dx + dz * dz; - if (agentPosition.y > groundY && agentPosition.y < ceilingY && distanceXZSquared < radius * radius) { - this.onReachTargetObservable.notifyObservers({ agentIndex: agentIndex, destination: this._agentDestination[index] }); - this._agentDestinationArmed[index] = false; - } - } - } - } - /** - * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...) - * The queries will try to find a solution within those bounds - * default is (1,1,1) - * @param extent x,y,z value that define the extent around the queries point of reference - */ - setDefaultQueryExtent(extent) { - const ext = new this.bjsRECASTPlugin.bjsRECAST.Vec3(extent.x, extent.y, extent.z); - this.recastCrowd.setDefaultQueryExtent(ext); - } - /** - * Get the Bounding box extent specified by setDefaultQueryExtent - * @returns the box extent values - */ - getDefaultQueryExtent() { - const p = this.recastCrowd.getDefaultQueryExtent(); - return new Vector3(p.x, p.y, p.z); - } - /** - * Get the Bounding box extent result specified by setDefaultQueryExtent - * @param result output the box extent values - */ - getDefaultQueryExtentToRef(result) { - const p = this.recastCrowd.getDefaultQueryExtent(); - result.set(p.x, p.y, p.z); - } - /** - * Get the next corner points composing the path (max 4 points) - * @param index agent index returned by addAgent - * @returns array containing world position composing the path - */ - getCorners(index) { - let pt; - const navPath = this.recastCrowd.getCorners(index); - const pointCount = navPath.getPointCount(); - const positions = []; - for (pt = 0; pt < pointCount; pt++) { - const p = navPath.getPoint(pt); - positions.push(new Vector3(p.x, p.y, p.z)); - } - return positions; - } - /** - * Release all resources - */ - dispose() { - this.recastCrowd.destroy(); - this._scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver); - this._onBeforeAnimationsObserver = null; - this.onReachTargetObservable.clear(); - } -} -//# sourceMappingURL=recastJSPlugin.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Navigation/Plugins/index.js - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Navigation/index.js -/* eslint-disable import/no-internal-modules */ - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Offline/database.js - - - - - -// Sets the default offline provider to Babylon.js -engine_Engine.OfflineProviderFactory = (urlToScene, callbackManifestChecked, disableManifestCheck = false) => { - return new Database(urlToScene, callbackManifestChecked, disableManifestCheck); -}; -/** - * Class used to enable access to IndexedDB - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeCached - */ -class Database { - /** - * Gets a boolean indicating if scene must be saved in the database - */ - get enableSceneOffline() { - return this._enableSceneOffline; - } - /** - * Gets a boolean indicating if textures must be saved in the database - */ - get enableTexturesOffline() { - return this._enableTexturesOffline; - } - /** - * Creates a new Database - * @param urlToScene defines the url to load the scene - * @param callbackManifestChecked defines the callback to use when manifest is checked - * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date) - */ - constructor(urlToScene, callbackManifestChecked, disableManifestCheck = false) { - // Handling various flavors of prefixed version of IndexedDB - this._idbFactory = (typeof indexedDB !== "undefined" ? indexedDB : undefined); - this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene); - this._db = null; - this._enableSceneOffline = false; - this._enableTexturesOffline = false; - this._manifestVersionFound = 0; - this._mustUpdateRessources = false; - this._hasReachedQuota = false; - if (!Database.IDBStorageEnabled) { - callbackManifestChecked(true); - } - else { - if (disableManifestCheck) { - this._enableSceneOffline = true; - this._enableTexturesOffline = true; - this._manifestVersionFound = 1; - tools_Tools.SetImmediate(() => { - callbackManifestChecked(true); - }); - } - else { - this._checkManifestFile(callbackManifestChecked); - } - } - } - _checkManifestFile(callbackManifestChecked) { - const noManifestFile = () => { - this._enableSceneOffline = false; - this._enableTexturesOffline = false; - callbackManifestChecked(false); - }; - const createManifestURL = () => { - try { - // make sure we have a valid URL. - if (typeof URL === "function" && this._currentSceneUrl.indexOf("http") === 0) { - // we don't have the base url, so the URL string must have a protocol - const url = new URL(this._currentSceneUrl); - url.pathname += ".manifest"; - return url.toString(); - } - } - catch (e) { - // defensive - if this fails for any reason, fall back to the older method - } - return `${this._currentSceneUrl}.manifest`; - }; - let timeStampUsed = false; - let manifestURL = createManifestURL(); - const xhr = new webRequest_WebRequest(); - if (navigator.onLine) { - // Adding a timestamp to by-pass browsers' cache - timeStampUsed = true; - manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now(); - } - xhr.open("GET", manifestURL); - xhr.addEventListener("load", () => { - if (xhr.status === 200 || Database._ValidateXHRData(xhr, 1)) { - try { - const manifestFile = JSON.parse(xhr.response); - this._enableSceneOffline = manifestFile.enableSceneOffline; - this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database._IsUASupportingBlobStorage; - if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) { - this._manifestVersionFound = manifestFile.version; - } - callbackManifestChecked(true); - } - catch (ex) { - noManifestFile(); - } - } - else { - noManifestFile(); - } - }, false); - xhr.addEventListener("error", () => { - if (timeStampUsed) { - timeStampUsed = false; - // Let's retry without the timeStamp - // It could fail when coupled with HTML5 Offline API - const retryManifestURL = createManifestURL(); - xhr.open("GET", retryManifestURL); - xhr.send(); - } - else { - noManifestFile(); - } - }, false); - try { - xhr.send(); - } - catch (ex) { - logger_Logger.Error("Error on XHR send request."); - callbackManifestChecked(false); - } - } - /** - * Open the database and make it available - * @param successCallback defines the callback to call on success - * @param errorCallback defines the callback to call on error - */ - open(successCallback, errorCallback) { - const handleError = () => { - this._isSupported = false; - if (errorCallback) { - errorCallback(); - } - }; - if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) { - // Your browser doesn't support IndexedDB - this._isSupported = false; - if (errorCallback) { - errorCallback(); - } - } - else { - // If the DB hasn't been opened or created yet - if (!this._db) { - this._hasReachedQuota = false; - this._isSupported = true; - const request = this._idbFactory.open("babylonjs", 1); - // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB - request.onerror = () => { - handleError(); - }; - // executes when a version change transaction cannot complete due to other active transactions - request.onblocked = () => { - logger_Logger.Error("IDB request blocked. Please reload the page."); - handleError(); - }; - // DB has been opened successfully - request.onsuccess = () => { - this._db = request.result; - successCallback(); - }; - // Initialization of the DB. Creating Scenes & Textures stores - request.onupgradeneeded = (event) => { - this._db = event.target.result; - if (this._db) { - try { - this._db.createObjectStore("scenes", { keyPath: "sceneUrl" }); - this._db.createObjectStore("versions", { keyPath: "sceneUrl" }); - this._db.createObjectStore("textures", { keyPath: "textureUrl" }); - } - catch (ex) { - logger_Logger.Error("Error while creating object stores. Exception: " + ex.message); - handleError(); - } - } - }; - } - // DB has already been created and opened - else { - if (successCallback) { - successCallback(); - } - } - } - } - /** - * Loads an image from the database - * @param url defines the url to load from - * @param image defines the target DOM image - */ - loadImage(url, image) { - const completeURL = Database._ReturnFullUrlLocation(url); - const saveAndLoadImage = () => { - if (!this._hasReachedQuota && this._db !== null) { - // the texture is not yet in the DB, let's try to save it - this._saveImageIntoDBAsync(completeURL, image); - } - // If the texture is not in the DB and we've reached the DB quota limit - // let's load it directly from the web - else { - image.src = url; - } - }; - if (!this._mustUpdateRessources) { - this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage); - } - // First time we're download the images or update requested in the manifest file by a version change - else { - saveAndLoadImage(); - } - } - _loadImageFromDBAsync(url, image, notInDBCallback) { - if (this._isSupported && this._db !== null) { - let texture; - const transaction = this._db.transaction(["textures"]); - transaction.onabort = () => { - image.src = url; - }; - transaction.oncomplete = () => { - let blobTextureURL; - if (texture && typeof URL === "function") { - blobTextureURL = URL.createObjectURL(texture.data); - image.onerror = () => { - logger_Logger.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url); - image.src = url; - }; - image.src = blobTextureURL; - } - else { - notInDBCallback(); - } - }; - const getRequest = transaction.objectStore("textures").get(url); - getRequest.onsuccess = (event) => { - texture = event.target.result; - }; - getRequest.onerror = () => { - logger_Logger.Error("Error loading texture " + url + " from DB."); - image.src = url; - }; - } - else { - logger_Logger.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."); - image.src = url; - } - } - _saveImageIntoDBAsync(url, image) { - let blob; - if (this._isSupported) { - // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on - const generateBlobUrl = () => { - let blobTextureURL; - if (blob && typeof URL === "function") { - try { - blobTextureURL = URL.createObjectURL(blob); - } - catch (ex) { - // Chrome is raising a type error if we're setting the oneTimeOnly parameter - blobTextureURL = URL.createObjectURL(blob); - } - } - if (blobTextureURL) { - image.src = blobTextureURL; - } - }; - if (Database._IsUASupportingBlobStorage) { - // Create XHR - const xhr = new webRequest_WebRequest(); - xhr.open("GET", url); - xhr.responseType = "blob"; - xhr.addEventListener("load", () => { - if (xhr.status === 200 && this._db) { - // Blob as response - blob = xhr.response; - const transaction = this._db.transaction(["textures"], "readwrite"); - // the transaction could abort because of a QuotaExceededError error - transaction.onabort = (event) => { - try { - //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3 - const srcElement = event.target; - const error = srcElement.error; - if (error && error.name === "QuotaExceededError") { - this._hasReachedQuota = true; - } - } - catch (ex) { } - generateBlobUrl(); - }; - transaction.oncomplete = () => { - generateBlobUrl(); - }; - const newTexture = { textureUrl: url, data: blob }; - try { - // Put the blob into the dabase - const addRequest = transaction.objectStore("textures").put(newTexture); - addRequest.onsuccess = () => { }; - addRequest.onerror = () => { - generateBlobUrl(); - }; - } - catch (ex) { - // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB - if (ex.code === 25) { - Database._IsUASupportingBlobStorage = false; - this._enableTexturesOffline = false; - } - image.src = url; - } - } - else { - image.src = url; - } - }, false); - xhr.addEventListener("error", () => { - logger_Logger.Error("Error in XHR request in BABYLON.Database."); - image.src = url; - }, false); - xhr.send(); - } - else { - image.src = url; - } - } - else { - logger_Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."); - image.src = url; - } - } - _checkVersionFromDB(url, versionLoaded) { - const updateVersion = () => { - // the version is not yet in the DB or we need to update it - this._saveVersionIntoDBAsync(url, versionLoaded); - }; - this._loadVersionFromDBAsync(url, versionLoaded, updateVersion); - } - _loadVersionFromDBAsync(url, callback, updateInDBCallback) { - if (this._isSupported && this._db) { - let version; - try { - const transaction = this._db.transaction(["versions"]); - transaction.oncomplete = () => { - if (version) { - // If the version in the JSON file is different from the version in DB - if (this._manifestVersionFound !== version.data) { - this._mustUpdateRessources = true; - updateInDBCallback(); - } - else { - callback(version.data); - } - } - // version was not found in DB - else { - this._mustUpdateRessources = true; - updateInDBCallback(); - } - }; - transaction.onabort = () => { - callback(-1); - }; - const getRequest = transaction.objectStore("versions").get(url); - getRequest.onsuccess = (event) => { - version = event.target.result; - }; - getRequest.onerror = () => { - logger_Logger.Error("Error loading version for scene " + url + " from DB."); - callback(-1); - }; - } - catch (ex) { - logger_Logger.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message); - callback(-1); - } - } - else { - logger_Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."); - callback(-1); - } - } - _saveVersionIntoDBAsync(url, callback) { - if (this._isSupported && !this._hasReachedQuota && this._db) { - try { - // Open a transaction to the database - const transaction = this._db.transaction(["versions"], "readwrite"); - // the transaction could abort because of a QuotaExceededError error - transaction.onabort = (event) => { - try { - //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3 - const error = event.target["error"]; - if (error && error.name === "QuotaExceededError") { - this._hasReachedQuota = true; - } - } - catch (ex) { } - callback(-1); - }; - transaction.oncomplete = () => { - callback(this._manifestVersionFound); - }; - const newVersion = { sceneUrl: url, data: this._manifestVersionFound }; - // Put the scene into the database - const addRequest = transaction.objectStore("versions").put(newVersion); - addRequest.onsuccess = () => { }; - addRequest.onerror = () => { - logger_Logger.Error("Error in DB add version request in BABYLON.Database."); - }; - } - catch (ex) { - logger_Logger.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message); - callback(-1); - } - } - else { - callback(-1); - } - } - /** - * Loads a file from database - * @param url defines the URL to load from - * @param sceneLoaded defines a callback to call on success - * @param progressCallBack defines a callback to call when progress changed - * @param errorCallback defines a callback to call on error - * @param useArrayBuffer defines a boolean to use array buffer instead of text string - */ - loadFile(url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) { - const completeUrl = Database._ReturnFullUrlLocation(url); - const saveAndLoadFile = () => { - // the scene is not yet in the DB, let's try to save it - this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback); - }; - this._checkVersionFromDB(completeUrl, (version) => { - if (version !== -1) { - if (!this._mustUpdateRessources) { - this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile); - } - else { - this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback); - } - } - else { - if (errorCallback) { - errorCallback(); - } - } - }); - } - _loadFileAsync(url, callback, notInDBCallback) { - if (this._isSupported && this._db) { - let targetStore; - if (url.indexOf(".babylon") !== -1) { - targetStore = "scenes"; - } - else { - targetStore = "textures"; - } - let file; - const transaction = this._db.transaction([targetStore]); - transaction.oncomplete = () => { - if (file) { - callback(file.data); - } - // file was not found in DB - else { - notInDBCallback(); - } - }; - transaction.onabort = () => { - notInDBCallback(); - }; - const getRequest = transaction.objectStore(targetStore).get(url); - getRequest.onsuccess = (event) => { - file = event.target.result; - }; - getRequest.onerror = () => { - logger_Logger.Error("Error loading file " + url + " from DB."); - notInDBCallback(); - }; - } - else { - logger_Logger.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."); - callback(); - } - } - _saveFileAsync(url, callback, progressCallback, useArrayBuffer, errorCallback) { - if (this._isSupported) { - let targetStore; - if (url.indexOf(".babylon") !== -1) { - targetStore = "scenes"; - } - else { - targetStore = "textures"; - } - // Create XHR - const xhr = new webRequest_WebRequest(); - let fileData; - xhr.open("GET", url + (url.match(/\?/) == null ? "?" : "&") + Date.now()); - if (useArrayBuffer) { - xhr.responseType = "arraybuffer"; - } - if (progressCallback) { - xhr.onprogress = progressCallback; - } - xhr.addEventListener("load", () => { - if (xhr.status === 200 || (xhr.status < 400 && Database._ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) { - // Blob as response - fileData = !useArrayBuffer ? xhr.responseText : xhr.response; - if (!this._hasReachedQuota && this._db) { - // Open a transaction to the database - const transaction = this._db.transaction([targetStore], "readwrite"); - // the transaction could abort because of a QuotaExceededError error - transaction.onabort = (event) => { - try { - //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3 - const error = event.target["error"]; - if (error && error.name === "QuotaExceededError") { - this._hasReachedQuota = true; - } - } - catch (ex) { } - callback(fileData); - }; - transaction.oncomplete = () => { - callback(fileData); - }; - let newFile; - if (targetStore === "scenes") { - newFile = { sceneUrl: url, data: fileData, version: this._manifestVersionFound }; - } - else { - newFile = { textureUrl: url, data: fileData }; - } - try { - // Put the scene into the database - const addRequest = transaction.objectStore(targetStore).put(newFile); - addRequest.onsuccess = () => { }; - addRequest.onerror = () => { - logger_Logger.Error("Error in DB add file request in BABYLON.Database."); - }; - } - catch (ex) { - callback(fileData); - } - } - else { - callback(fileData); - } - } - else { - if (xhr.status >= 400 && errorCallback) { - errorCallback(xhr); - } - else { - callback(); - } - } - }, false); - xhr.addEventListener("error", () => { - logger_Logger.Error("error on XHR request."); - errorCallback && errorCallback(); - }, false); - xhr.send(); - } - else { - logger_Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."); - errorCallback && errorCallback(); - } - } - /** - * Validates if xhr data is correct - * @param xhr defines the request to validate - * @param dataType defines the expected data type - * @returns true if data is correct - */ - static _ValidateXHRData(xhr, dataType = 7) { - // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all - try { - if (dataType & 1) { - if (xhr.responseText && xhr.responseText.length > 0) { - return true; - } - else if (dataType === 1) { - return false; - } - } - if (dataType & 2) { - // Check header width and height since there is no "TGA" magic number - const tgaHeader = GetTGAHeader(xhr.response); - if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) { - return true; - } - else if (dataType === 2) { - return false; - } - } - if (dataType & 4) { - // Check for the "DDS" magic number - const ddsHeader = new Uint8Array(xhr.response, 0, 3); - if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) { - return true; - } - else { - return false; - } - } - } - catch (e) { - // Global protection - } - return false; - } -} -/** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */ -Database._IsUASupportingBlobStorage = true; -/** - * Gets a boolean indicating if Database storage is enabled (off by default) - */ -Database.IDBStorageEnabled = false; -Database._ParseURL = (url) => { - const a = document.createElement("a"); - a.href = url; - const urlWithoutHash = url.substring(0, url.lastIndexOf("#")); - const fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length); - const absLocation = url.substring(0, url.indexOf(fileName, 0)); - return absLocation; -}; -Database._ReturnFullUrlLocation = (url) => { - if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1 && typeof window !== "undefined") { - return Database._ParseURL(window.location.href) + url; - } - else { - return url; - } -}; -//# sourceMappingURL=database.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Offline/IOfflineProvider.js - -//# sourceMappingURL=IOfflineProvider.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Offline/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/uniformBufferEffectCommonAccessor.js -/** @internal */ -class UniformBufferEffectCommonAccessor { - _isUbo(uboOrEffect) { - return uboOrEffect.addUniform !== undefined; - } - constructor(uboOrEffect) { - if (this._isUbo(uboOrEffect)) { - this.setMatrix3x3 = uboOrEffect.updateMatrix3x3.bind(uboOrEffect); - this.setMatrix2x2 = uboOrEffect.updateMatrix2x2.bind(uboOrEffect); - this.setFloat = uboOrEffect.updateFloat.bind(uboOrEffect); - this.setFloat2 = uboOrEffect.updateFloat2.bind(uboOrEffect); - this.setFloat3 = uboOrEffect.updateFloat3.bind(uboOrEffect); - this.setFloat4 = uboOrEffect.updateFloat4.bind(uboOrEffect); - this.setFloatArray = uboOrEffect.updateFloatArray.bind(uboOrEffect); - this.setArray = uboOrEffect.updateArray.bind(uboOrEffect); - this.setIntArray = uboOrEffect.updateIntArray.bind(uboOrEffect); - this.setMatrix = uboOrEffect.updateMatrix.bind(uboOrEffect); - this.setMatrices = uboOrEffect.updateMatrices.bind(uboOrEffect); - this.setVector3 = uboOrEffect.updateVector3.bind(uboOrEffect); - this.setVector4 = uboOrEffect.updateVector4.bind(uboOrEffect); - this.setColor3 = uboOrEffect.updateColor3.bind(uboOrEffect); - this.setColor4 = uboOrEffect.updateColor4.bind(uboOrEffect); - this.setDirectColor4 = uboOrEffect.updateDirectColor4.bind(uboOrEffect); - this.setInt = uboOrEffect.updateInt.bind(uboOrEffect); - this.setInt2 = uboOrEffect.updateInt2.bind(uboOrEffect); - this.setInt3 = uboOrEffect.updateInt3.bind(uboOrEffect); - this.setInt4 = uboOrEffect.updateInt4.bind(uboOrEffect); - } - else { - this.setMatrix3x3 = uboOrEffect.setMatrix3x3.bind(uboOrEffect); - this.setMatrix2x2 = uboOrEffect.setMatrix2x2.bind(uboOrEffect); - this.setFloat = uboOrEffect.setFloat.bind(uboOrEffect); - this.setFloat2 = uboOrEffect.setFloat2.bind(uboOrEffect); - this.setFloat3 = uboOrEffect.setFloat3.bind(uboOrEffect); - this.setFloat4 = uboOrEffect.setFloat4.bind(uboOrEffect); - this.setFloatArray = uboOrEffect.setFloatArray.bind(uboOrEffect); - this.setArray = uboOrEffect.setArray.bind(uboOrEffect); - this.setIntArray = uboOrEffect.setIntArray.bind(uboOrEffect); - this.setMatrix = uboOrEffect.setMatrix.bind(uboOrEffect); - this.setMatrices = uboOrEffect.setMatrices.bind(uboOrEffect); - this.setVector3 = uboOrEffect.setVector3.bind(uboOrEffect); - this.setVector4 = uboOrEffect.setVector4.bind(uboOrEffect); - this.setColor3 = uboOrEffect.setColor3.bind(uboOrEffect); - this.setColor4 = uboOrEffect.setColor4.bind(uboOrEffect); - this.setDirectColor4 = uboOrEffect.setDirectColor4.bind(uboOrEffect); - this.setInt = uboOrEffect.setInt.bind(uboOrEffect); - this.setInt2 = uboOrEffect.setInt2.bind(uboOrEffect); - this.setInt3 = uboOrEffect.setInt3.bind(uboOrEffect); - this.setInt4 = uboOrEffect.setInt4.bind(uboOrEffect); - } - } -} -//# sourceMappingURL=uniformBufferEffectCommonAccessor.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/gpuUpdateParticles.fragment.js -// Do not edit. - -const gpuUpdateParticles_fragment_name = "gpuUpdateParticlesPixelShader"; -const gpuUpdateParticles_fragment_shader = `#version 300 es -void main() {discard;} -`; -// Sideeffect -ShaderStore.ShadersStore[gpuUpdateParticles_fragment_name] = gpuUpdateParticles_fragment_shader; -/** @internal */ -const gpuUpdateParticlesPixelShader = { name: gpuUpdateParticles_fragment_name, shader: gpuUpdateParticles_fragment_shader }; -//# sourceMappingURL=gpuUpdateParticles.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/gpuUpdateParticles.vertex.js -// Do not edit. - -const gpuUpdateParticles_vertex_name = "gpuUpdateParticlesVertexShader"; -const gpuUpdateParticles_vertex_shader = `#version 300 es -#define PI 3.14159 -uniform float currentCount;uniform float timeDelta;uniform float stopFactor; -#ifndef LOCAL -uniform mat4 emitterWM; -#endif -uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; -#ifndef COLORGRADIENTS -uniform vec4 color1;uniform vec4 color2; -#endif -uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; -#ifdef BOXEMITTER -uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; -#endif -#ifdef POINTEMITTER -uniform vec3 direction1;uniform vec3 direction2; -#endif -#ifdef HEMISPHERICEMITTER -uniform float radius;uniform float radiusRange;uniform float directionRandomizer; -#endif -#ifdef SPHEREEMITTER -uniform float radius;uniform float radiusRange; -#ifdef DIRECTEDSPHEREEMITTER -uniform vec3 direction1;uniform vec3 direction2; -#else -uniform float directionRandomizer; -#endif -#endif -#ifdef CYLINDEREMITTER -uniform float radius;uniform float height;uniform float radiusRange; -#ifdef DIRECTEDCYLINDEREMITTER -uniform vec3 direction1;uniform vec3 direction2; -#else -uniform float directionRandomizer; -#endif -#endif -#ifdef CONEEMITTER -uniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer; -#endif -in vec3 position; -#ifdef CUSTOMEMITTER -in vec3 initialPosition; -#endif -in float age;in float life;in vec4 seed;in vec3 size; -#ifndef COLORGRADIENTS -in vec4 color; -#endif -in vec3 direction; -#ifndef BILLBOARD -in vec3 initialDirection; -#endif -#ifdef ANGULARSPEEDGRADIENTS -in float angle; -#else -in vec2 angle; -#endif -#ifdef ANIMATESHEET -in float cellIndex; -#ifdef ANIMATESHEETRANDOMSTART -in float cellStartOffset; -#endif -#endif -#ifdef NOISE -in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; -#endif -out vec3 outPosition; -#ifdef CUSTOMEMITTER -out vec3 outInitialPosition; -#endif -out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; -#ifndef COLORGRADIENTS -out vec4 outColor; -#endif -out vec3 outDirection; -#ifndef BILLBOARD -out vec3 outInitialDirection; -#endif -#ifdef ANGULARSPEEDGRADIENTS -out float outAngle; -#else -out vec2 outAngle; -#endif -#ifdef ANIMATESHEET -out float outCellIndex; -#ifdef ANIMATESHEETRANDOMSTART -out float outCellStartOffset; -#endif -#endif -#ifdef NOISE -out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; -#endif -#ifdef SIZEGRADIENTS -uniform sampler2D sizeGradientSampler; -#endif -#ifdef ANGULARSPEEDGRADIENTS -uniform sampler2D angularSpeedGradientSampler; -#endif -#ifdef VELOCITYGRADIENTS -uniform sampler2D velocityGradientSampler; -#endif -#ifdef LIMITVELOCITYGRADIENTS -uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; -#endif -#ifdef DRAGGRADIENTS -uniform sampler2D dragGradientSampler; -#endif -#ifdef NOISE -uniform vec3 noiseStrength;uniform sampler2D noiseSampler; -#endif -#ifdef ANIMATESHEET -uniform vec4 cellInfos; -#endif -vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} -vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} -void main() {float newAge=age+timeDelta; -if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; -#ifdef SIZEGRADIENTS -outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; -#else -outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; -#endif -outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; -#ifndef COLORGRADIENTS -outColor=color1+(color2-color1)*randoms.b; -#endif -#ifndef ANGULARSPEEDGRADIENTS -outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; -#else -outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; -#endif -#ifdef POINTEMITTER -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; -#elif defined(BOXEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; -#elif defined(HEMISPHERICEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; -#elif defined(SPHEREEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); -#ifdef DIRECTEDSPHEREEMITTER -newDirection=normalize(direction1+(direction2-direction1)*randoms3); -#else -newDirection=normalize(newPosition+directionRandomizer*randoms3); -#endif -#elif defined(CYLINDEREMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); -#ifdef DIRECTEDCYLINDEREMITTER -newDirection=direction1+(direction2-direction1)*randoms3; -#else -angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); -#endif -#elif defined(CONEEMITTER) -vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; -#ifdef CONEEMITTERSPAWNPOINT -float h=0.0001; -#else -float h=randoms2.y*height.y;h=1.-h*h; -#endif -float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); -if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); } -#elif defined(CUSTOMEMITTER) -newPosition=initialPosition;outInitialPosition=initialPosition; -#else -newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); -#endif -float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; -#ifdef LOCAL -outPosition=newPosition; -#else -outPosition=(emitterWM*vec4(newPosition,1.)).xyz; -#endif -#ifdef CUSTOMEMITTER -outDirection=direction; -#ifndef BILLBOARD -outInitialDirection=direction; -#endif -#else -#ifdef LOCAL -vec3 initial=newDirection; -#else -vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; -#endif -outDirection=initial*power; -#ifndef BILLBOARD -outInitialDirection=initial; -#endif -#endif -#ifdef ANIMATESHEET -outCellIndex=cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -outCellStartOffset=randoms.a*outLife; -#endif -#endif -#ifdef NOISE -outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; -#endif -} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; -#ifdef VELOCITYGRADIENTS -directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; -#endif -#ifdef DRAGGRADIENTS -directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; -#endif -#if defined(CUSTOMEMITTER) -outPosition=position+(direction-position)*ageGradient; -outInitialPosition=initialPosition; -#else -outPosition=position+direction*directionScale; -#endif -outLife=life;outSeed=seed; -#ifndef COLORGRADIENTS -outColor=color; -#endif -#ifdef SIZEGRADIENTS -outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; -#else -outSize=size; -#endif -#ifndef BILLBOARD -outInitialDirection=initialDirection; -#endif -#ifdef CUSTOMEMITTER -outDirection=direction; -#else -vec3 updatedDirection=direction+gravity*timeDelta; -#ifdef LIMITVELOCITYGRADIENTS -float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} -#endif -outDirection=updatedDirection; -#ifdef NOISE -float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; -#endif -#endif -#ifdef ANGULARSPEEDGRADIENTS -float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; -#else -outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); -#endif -#ifdef ANIMATESHEET -float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; -#else -float cellStartOffset=0.; -#endif -float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} -else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} -outCellIndex=float(int(cellInfos.x+ratio*dist)); -#endif -}}`; -// Sideeffect -ShaderStore.ShadersStore[gpuUpdateParticles_vertex_name] = gpuUpdateParticles_vertex_shader; -/** @internal */ -const gpuUpdateParticlesVertexShader = { name: gpuUpdateParticles_vertex_name, shader: gpuUpdateParticles_vertex_shader }; -//# sourceMappingURL=gpuUpdateParticles.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/webgl2ParticleSystem.js - - - - - - - -/** @internal */ -class WebGL2ParticleSystem { - constructor(parent, engine) { - this._renderVAO = []; - this._updateVAO = []; - this.alignDataInBuffer = false; - this._parent = parent; - this._engine = engine; - this._updateEffectOptions = { - attributes: [ - "position", - "initialPosition", - "age", - "life", - "seed", - "size", - "color", - "direction", - "initialDirection", - "angle", - "cellIndex", - "cellStartOffset", - "noiseCoordinates1", - "noiseCoordinates2", - ], - uniformsNames: [ - "currentCount", - "timeDelta", - "emitterWM", - "lifeTime", - "color1", - "color2", - "sizeRange", - "scaleRange", - "gravity", - "emitPower", - "direction1", - "direction2", - "minEmitBox", - "maxEmitBox", - "radius", - "directionRandomizer", - "height", - "coneAngle", - "stopFactor", - "angleRange", - "radiusRange", - "cellInfos", - "noiseStrength", - "limitVelocityDamping", - ], - uniformBuffersNames: [], - samplers: [ - "randomSampler", - "randomSampler2", - "sizeGradientSampler", - "angularSpeedGradientSampler", - "velocityGradientSampler", - "limitVelocityGradientSampler", - "noiseSampler", - "dragGradientSampler", - ], - defines: "", - fallbacks: null, - onCompiled: null, - onError: null, - indexParameters: null, - maxSimultaneousLights: 0, - transformFeedbackVaryings: [], - }; - } - contextLost() { - this._updateEffect = undefined; - this._renderVAO.length = 0; - this._updateVAO.length = 0; - } - isUpdateBufferCreated() { - return !!this._updateEffect; - } - isUpdateBufferReady() { - var _a, _b; - return (_b = (_a = this._updateEffect) === null || _a === void 0 ? void 0 : _a.isReady()) !== null && _b !== void 0 ? _b : false; - } - createUpdateBuffer(defines) { - 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"); - if (this._parent.particleEmitterType instanceof CustomParticleEmitter) { - this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"); - } - if (!this._parent._colorGradientsTexture) { - this._updateEffectOptions.transformFeedbackVaryings.push("outColor"); - } - if (!this._parent._isBillboardBased) { - this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"); - } - if (this._parent.noiseTexture) { - this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"); - this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2"); - } - this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"); - if (this._parent.isAnimationSheetEnabled) { - this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"); - if (this._parent.spriteRandomStartCell) { - this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset"); - } - } - this._updateEffectOptions.defines = defines; - this._updateEffect = new effect_Effect("gpuUpdateParticles", this._updateEffectOptions, this._engine); - return new UniformBufferEffectCommonAccessor(this._updateEffect); - } - createVertexBuffers(updateBuffer, renderVertexBuffers) { - this._updateVAO.push(this._createUpdateVAO(updateBuffer)); - this._renderVAO.push(this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._parent._getWrapper(this._parent.blendMode).effect)); - this._engine.bindArrayBuffer(null); - this._renderVertexBuffers = renderVertexBuffers; - } - createParticleBuffer(data) { - return data; - } - bindDrawBuffers(index, effect, indexBuffer) { - if (indexBuffer) { - this._engine.bindBuffers(this._renderVertexBuffers, indexBuffer, effect); - } - else { - this._engine.bindVertexArrayObject(this._renderVAO[index], null); - } - } - preUpdateParticleBuffer() { - const engine = this._engine; - this._engine.enableEffect(this._updateEffect); - if (!engine.setState) { - throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported"); - } - } - updateParticleBuffer(index, targetBuffer, currentActiveCount) { - this._updateEffect.setTexture("randomSampler", this._parent._randomTexture); - this._updateEffect.setTexture("randomSampler2", this._parent._randomTexture2); - if (this._parent._sizeGradientsTexture) { - this._updateEffect.setTexture("sizeGradientSampler", this._parent._sizeGradientsTexture); - } - if (this._parent._angularSpeedGradientsTexture) { - this._updateEffect.setTexture("angularSpeedGradientSampler", this._parent._angularSpeedGradientsTexture); - } - if (this._parent._velocityGradientsTexture) { - this._updateEffect.setTexture("velocityGradientSampler", this._parent._velocityGradientsTexture); - } - if (this._parent._limitVelocityGradientsTexture) { - this._updateEffect.setTexture("limitVelocityGradientSampler", this._parent._limitVelocityGradientsTexture); - } - if (this._parent._dragGradientsTexture) { - this._updateEffect.setTexture("dragGradientSampler", this._parent._dragGradientsTexture); - } - if (this._parent.noiseTexture) { - this._updateEffect.setTexture("noiseSampler", this._parent.noiseTexture); - } - // Bind source VAO - this._engine.bindVertexArrayObject(this._updateVAO[index], null); - // Update - const engine = this._engine; - engine.bindTransformFeedbackBuffer(targetBuffer.getBuffer()); - engine.setRasterizerState(false); - engine.beginTransformFeedback(true); - engine.drawArraysType(3, 0, currentActiveCount); - engine.endTransformFeedback(); - engine.setRasterizerState(true); - engine.bindTransformFeedbackBuffer(null); - } - releaseBuffers() { } - releaseVertexBuffers() { - for (let index = 0; index < this._updateVAO.length; index++) { - this._engine.releaseVertexArrayObject(this._updateVAO[index]); - } - this._updateVAO.length = 0; - for (let index = 0; index < this._renderVAO.length; index++) { - this._engine.releaseVertexArrayObject(this._renderVAO[index]); - } - this._renderVAO.length = 0; - } - _createUpdateVAO(source) { - const updateVertexBuffers = {}; - updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3); - let offset = 3; - updateVertexBuffers["age"] = source.createVertexBuffer("age", offset, 1); - offset += 1; - updateVertexBuffers["size"] = source.createVertexBuffer("size", offset, 3); - offset += 3; - updateVertexBuffers["life"] = source.createVertexBuffer("life", offset, 1); - offset += 1; - updateVertexBuffers["seed"] = source.createVertexBuffer("seed", offset, 4); - offset += 4; - updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3); - offset += 3; - if (this._parent.particleEmitterType instanceof CustomParticleEmitter) { - updateVertexBuffers["initialPosition"] = source.createVertexBuffer("initialPosition", offset, 3); - offset += 3; - } - if (!this._parent._colorGradientsTexture) { - updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4); - offset += 4; - } - if (!this._parent._isBillboardBased) { - updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3); - offset += 3; - } - if (this._parent.noiseTexture) { - updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3); - offset += 3; - updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3); - offset += 3; - } - if (this._parent._angularSpeedGradientsTexture) { - updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1); - offset += 1; - } - else { - updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2); - offset += 2; - } - if (this._parent._isAnimationSheetEnabled) { - updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1); - offset += 1; - if (this._parent.spriteRandomStartCell) { - updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1); - offset += 1; - } - } - const vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect); - this._engine.bindArrayBuffer(null); - return vao; - } -} -RegisterClass("BABYLON.WebGL2ParticleSystem", WebGL2ParticleSystem); -//# sourceMappingURL=webgl2ParticleSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/ShadersWGSL/gpuUpdateParticles.compute.js -// Do not edit. - -const gpuUpdateParticles_compute_name = "gpuUpdateParticlesComputeShader"; -const gpuUpdateParticles_compute_shader = `struct Particle {position : vec3<f32>, -age : f32, -size : vec3<f32>, -life : f32, -seed : vec4<f32>, -direction : vec3<f32>, -dummy0: f32, -#ifdef CUSTOMEMITTER -initialPosition : vec3<f32>, -dummy1: f32, -#endif -#ifndef COLORGRADIENTS -color : vec4<f32>, -#endif -#ifndef BILLBOARD -initialDirection : vec3<f32>, -dummy2: f32, -#endif -#ifdef NOISE -noiseCoordinates1 : vec3<f32>, -dummy3: f32, -noiseCoordinates2 : vec3<f32>, -dummy4: f32, -#endif -#ifdef ANGULARSPEEDGRADIENTS -angle : f32, -#else -angle : vec2<f32>, -#endif -#ifdef ANIMATESHEET -cellIndex : f32, -#ifdef ANIMATESHEETRANDOMSTART -cellStartOffset : f32, -#endif -#endif -};struct Particles {particles : array<Particle>,};struct SimParams {currentCount : f32, -timeDelta : f32, -stopFactor : f32, -randomTextureSize: i32, -lifeTime : vec2<f32>, -emitPower : vec2<f32>, -#ifndef COLORGRADIENTS -color1 : vec4<f32>, -color2 : vec4<f32>, -#endif -sizeRange : vec2<f32>, -scaleRange : vec4<f32>, -angleRange : vec4<f32>, -gravity : vec3<f32>, -#ifdef LIMITVELOCITYGRADIENTS -limitVelocityDamping : f32, -#endif -#ifdef ANIMATESHEET -cellInfos : vec4<f32>, -#endif -#ifdef NOISE -noiseStrength : vec3<f32>, -#endif -#ifndef LOCAL -emitterWM : mat4x4<f32>, -#endif -#ifdef BOXEMITTER -direction1 : vec3<f32>, -direction2 : vec3<f32>, -minEmitBox : vec3<f32>, -maxEmitBox : vec3<f32>, -#endif -#ifdef CONEEMITTER -radius : vec2<f32>, -coneAngle : f32, -height : vec2<f32>, -directionRandomizer : f32, -#endif -#ifdef CYLINDEREMITTER -radius : f32, -height : f32, -radiusRange : f32, -#ifdef DIRECTEDCYLINDEREMITTER -direction1 : vec3<f32>, -direction2 : vec3<f32>, -#else -directionRandomizer : f32, -#endif -#endif -#ifdef HEMISPHERICEMITTER -radius : f32, -radiusRange : f32, -directionRandomizer : f32, -#endif -#ifdef POINTEMITTER -direction1 : vec3<f32>, -direction2 : vec3<f32>, -#endif -#ifdef SPHEREEMITTER -radius : f32, -radiusRange : f32, -#ifdef DIRECTEDSPHEREEMITTER -direction1 : vec3<f32>, -direction2 : vec3<f32>, -#else -directionRandomizer : f32, -#endif -#endif -};@binding(0) @group(0) var<uniform> params : SimParams;@binding(1) @group(0) var<storage,read> particlesIn : Particles;@binding(2) @group(0) var<storage,read_write> particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d<f32>;@binding(4) @group(0) var randomTexture2 : texture_2d<f32>; -#ifdef SIZEGRADIENTS -@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d<f32>; -#endif -#ifdef ANGULARSPEEDGRADIENTS -@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d<f32>; -#endif -#ifdef VELOCITYGRADIENTS -@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d<f32>; -#endif -#ifdef LIMITVELOCITYGRADIENTS -@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d<f32>; -#endif -#ifdef DRAGGRADIENTS -@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d<f32>; -#endif -#ifdef NOISE -@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d<f32>; -#endif -fn getRandomVec3(offset : f32,vertexID : f32)->vec3<f32> {return textureLoad(randomTexture2,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} -fn getRandomVec4(offset : f32,vertexID : f32)->vec4<f32> {return textureLoad(randomTexture,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} -@compute @workgroup_size(64) -fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3<u32>) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} -let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4<f32>=particlesIn.particles[index].seed;let direction : vec3<f32>=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3<f32>;var newDirection : vec3<f32>;let randoms : vec4<f32>=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; -#ifdef SIZEGRADIENTS -sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(0.,0.),0.).r; -#else -sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; -#endif -particlesOut.particles[index].size=vec3<f32>( -sizex, -params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, -params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); -#ifndef COLORGRADIENTS -particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; -#endif -#ifndef ANGULARSPEEDGRADIENTS -particlesOut.particles[index].angle=vec2<f32>( -params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, -params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); -#else -particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; -#endif -#if defined(POINTEMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=vec3<f32>(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#elif defined(BOXEMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#elif defined(HEMISPHERICEMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); -#elif defined(SPHEREEMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,randY,randZ); -#ifdef DIRECTEDSPHEREEMITTER -newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); -#else -newDirection=normalize(newPosition+params.directionRandomizer*randoms3); -#endif -#elif defined(CYLINDEREMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3<f32>(xPos,yPos,zPos); -#ifdef DIRECTEDCYLINDEREMITTER -newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#else -angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3<f32>(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); -#endif -#elif defined(CONEEMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; -#ifdef CONEEMITTERSPAWNPOINT -let h : f32=0.0001; -#else -var h : f32=randoms2.y*params.height.y;h=1.-h*h; -#endif -var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3<f32>(randX,randY,randZ); -if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3<f32>(0.,1.0,0.);} else {let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } -#elif defined(CUSTOMEMITTER) -newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; -#else -newPosition=vec3<f32>(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3<f32>(0.5,0.5,0.5)); -#endif -let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; -#ifdef LOCAL -particlesOut.particles[index].position=newPosition; -#else -particlesOut.particles[index].position=(params.emitterWM*vec4<f32>(newPosition,1.)).xyz; -#endif -#ifdef CUSTOMEMITTER -particlesOut.particles[index].direction=direction; -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=direction; -#endif -#else -#ifdef LOCAL -let initial : vec3<f32>=newDirection; -#else -let initial : vec3<f32>=(params.emitterWM*vec4<f32>(newDirection,0.)).xyz; -#endif -particlesOut.particles[index].direction=initial*power; -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=initial; -#endif -#endif -#ifdef ANIMATESHEET -particlesOut.particles[index].cellIndex=params.cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -particlesOut.particles[index].cellStartOffset=randoms.a*outLife; -#endif -#endif -#ifdef NOISE -particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; -#endif -} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; -#ifdef VELOCITYGRADIENTS -directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r; -#endif -#ifdef DRAGGRADIENTS -directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2<f32>(ageGradient,0.),0.).r); -#endif -let position : vec3<f32>=particlesIn.particles[index].position; -#if defined(CUSTOMEMITTER) -particlesOut.particles[index].position=position+(direction-position)*ageGradient; -particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; -#else -particlesOut.particles[index].position=position+direction*directionScale; -#endif -particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; -#ifndef COLORGRADIENTS -particlesOut.particles[index].color=particlesIn.particles[index].color; -#endif -#ifdef SIZEGRADIENTS -particlesOut.particles[index].size=vec3<f32>( -textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(ageGradient,0.),0.).r, -particlesIn.particles[index].size.yz); -#else -particlesOut.particles[index].size=particlesIn.particles[index].size; -#endif -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; -#endif -#ifdef CUSTOMEMITTER -particlesOut.particles[index].direction=direction; -#else -var updatedDirection : vec3<f32>=direction+params.gravity*timeDelta; -#ifdef LIMITVELOCITYGRADIENTS -let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} -#endif -particlesOut.particles[index].direction=updatedDirection; -#ifdef NOISE -let noiseCoordinates1 : vec3<f32>=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3<f32>=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.x,noiseCoordinates1.y)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.z,noiseCoordinates2.x)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates2.y,noiseCoordinates2.z)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let force : vec3<f32>=vec3<f32>(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; -#endif -#endif -#ifdef ANGULARSPEEDGRADIENTS -let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2<f32>(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; -#else -let angle : vec2<f32>=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2<f32>(angle.x+angle.y*timeDelta,angle.y); -#endif -#ifdef ANIMATESHEET -var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; -#else -let cellStartOffset : f32=0.; -#endif -var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} -else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} -particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); -#endif -}} -`; -// Sideeffect -ShaderStore.ShadersStoreWGSL[gpuUpdateParticles_compute_name] = gpuUpdateParticles_compute_shader; -/** @internal */ -const gpuUpdateParticlesComputeShader = { name: gpuUpdateParticles_compute_name, shader: gpuUpdateParticles_compute_shader }; -//# sourceMappingURL=gpuUpdateParticles.compute.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/computeShaderParticleSystem.js - - - - - - - -/** @internal */ -class ComputeShaderParticleSystem { - constructor(parent, engine) { - this._bufferComputeShader = []; - this._renderVertexBuffers = []; - this.alignDataInBuffer = true; - this._parent = parent; - this._engine = engine; - } - contextLost() { - this._updateComputeShader = undefined; - this._bufferComputeShader.length = 0; - this._renderVertexBuffers.length = 0; - } - isUpdateBufferCreated() { - return !!this._updateComputeShader; - } - isUpdateBufferReady() { - var _a, _b; - return (_b = (_a = this._updateComputeShader) === null || _a === void 0 ? void 0 : _a.isReady()) !== null && _b !== void 0 ? _b : false; - } - createUpdateBuffer(defines) { - var _a; - const bindingsMapping = { - params: { group: 0, binding: 0 }, - particlesIn: { group: 0, binding: 1 }, - particlesOut: { group: 0, binding: 2 }, - randomTexture: { group: 0, binding: 3 }, - randomTexture2: { group: 0, binding: 4 }, - }; - if (this._parent._sizeGradientsTexture) { - bindingsMapping["sizeGradientTexture"] = { group: 1, binding: 1 }; - } - if (this._parent._angularSpeedGradientsTexture) { - bindingsMapping["angularSpeedGradientTexture"] = { group: 1, binding: 3 }; - } - if (this._parent._velocityGradientsTexture) { - bindingsMapping["velocityGradientTexture"] = { group: 1, binding: 5 }; - } - if (this._parent._limitVelocityGradientsTexture) { - bindingsMapping["limitVelocityGradientTexture"] = { group: 1, binding: 7 }; - } - if (this._parent._dragGradientsTexture) { - bindingsMapping["dragGradientTexture"] = { group: 1, binding: 9 }; - } - if (this._parent.noiseTexture) { - bindingsMapping["noiseTexture"] = { group: 1, binding: 11 }; - } - this._updateComputeShader = new ComputeShader("updateParticles", this._engine, "gpuUpdateParticles", { bindingsMapping, defines: defines.split("\n") }); - (_a = this._simParamsComputeShader) === null || _a === void 0 ? void 0 : _a.dispose(); - this._simParamsComputeShader = new UniformBuffer(this._engine); - this._simParamsComputeShader.addUniform("currentCount", 1); - this._simParamsComputeShader.addUniform("timeDelta", 1); - this._simParamsComputeShader.addUniform("stopFactor", 1); - this._simParamsComputeShader.addUniform("randomTextureSize", 1); - this._simParamsComputeShader.addUniform("lifeTime", 2); - this._simParamsComputeShader.addUniform("emitPower", 2); - if (!this._parent._colorGradientsTexture) { - this._simParamsComputeShader.addUniform("color1", 4); - this._simParamsComputeShader.addUniform("color2", 4); - } - this._simParamsComputeShader.addUniform("sizeRange", 2); - this._simParamsComputeShader.addUniform("scaleRange", 4); - this._simParamsComputeShader.addUniform("angleRange", 4); - this._simParamsComputeShader.addUniform("gravity", 3); - if (this._parent._limitVelocityGradientsTexture) { - this._simParamsComputeShader.addUniform("limitVelocityDamping", 1); - } - if (this._parent.isAnimationSheetEnabled) { - this._simParamsComputeShader.addUniform("cellInfos", 4); - } - if (this._parent.noiseTexture) { - this._simParamsComputeShader.addUniform("noiseStrength", 3); - } - if (!this._parent.isLocal) { - this._simParamsComputeShader.addUniform("emitterWM", 16); - } - if (this._parent.particleEmitterType) { - this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader); - } - this._updateComputeShader.setUniformBuffer("params", this._simParamsComputeShader); - return new UniformBufferEffectCommonAccessor(this._simParamsComputeShader); - } - createVertexBuffers(updateBuffer, renderVertexBuffers) { - this._renderVertexBuffers.push(renderVertexBuffers); - } - createParticleBuffer(data) { - const buffer = new StorageBuffer(this._engine, data.length * 4, 3 | 8); - buffer.update(data); - this._bufferComputeShader.push(buffer); - return buffer.getBuffer(); - } - bindDrawBuffers(index, effect, indexBuffer) { - this._engine.bindBuffers(this._renderVertexBuffers[index], indexBuffer, effect); - } - preUpdateParticleBuffer() { } - updateParticleBuffer(index, targetBuffer, currentActiveCount) { - this._simParamsComputeShader.update(); - this._updateComputeShader.setTexture("randomTexture", this._parent._randomTexture, false); - this._updateComputeShader.setTexture("randomTexture2", this._parent._randomTexture2, false); - if (this._parent._sizeGradientsTexture) { - this._updateComputeShader.setTexture("sizeGradientTexture", this._parent._sizeGradientsTexture); - } - if (this._parent._angularSpeedGradientsTexture) { - this._updateComputeShader.setTexture("angularSpeedGradientTexture", this._parent._angularSpeedGradientsTexture); - } - if (this._parent._velocityGradientsTexture) { - this._updateComputeShader.setTexture("velocityGradientTexture", this._parent._velocityGradientsTexture); - } - if (this._parent._limitVelocityGradientsTexture) { - this._updateComputeShader.setTexture("limitVelocityGradientTexture", this._parent._limitVelocityGradientsTexture); - } - if (this._parent._dragGradientsTexture) { - this._updateComputeShader.setTexture("dragGradientTexture", this._parent._dragGradientsTexture); - } - if (this._parent.noiseTexture) { - this._updateComputeShader.setTexture("noiseTexture", this._parent.noiseTexture); - } - this._updateComputeShader.setStorageBuffer("particlesIn", this._bufferComputeShader[index]); - this._updateComputeShader.setStorageBuffer("particlesOut", this._bufferComputeShader[index ^ 1]); - this._updateComputeShader.dispatch(Math.ceil(currentActiveCount / 64)); - } - releaseBuffers() { - var _a; - for (let i = 0; i < this._bufferComputeShader.length; ++i) { - this._bufferComputeShader[i].dispose(); - } - this._bufferComputeShader.length = 0; - (_a = this._simParamsComputeShader) === null || _a === void 0 ? void 0 : _a.dispose(); - this._simParamsComputeShader = null; - this._updateComputeShader = null; - } - releaseVertexBuffers() { - this._renderVertexBuffers.length = 0; - } -} -RegisterClass("BABYLON.ComputeShaderParticleSystem", ComputeShaderParticleSystem); -//# sourceMappingURL=computeShaderParticleSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/gradients.js - -/** Class used to store color4 gradient */ -class ColorGradient { - /** - * Creates a new color4 gradient - * @param gradient gets or sets the gradient value (between 0 and 1) - * @param color1 gets or sets first associated color - * @param color2 gets or sets first second color - */ - constructor( - /** - * Gets or sets the gradient value (between 0 and 1) - */ - gradient, - /** - * Gets or sets first associated color - */ - color1, - /** - * Gets or sets second associated color - */ - color2) { - this.gradient = gradient; - this.color1 = color1; - this.color2 = color2; - } - /** - * Will get a color picked randomly between color1 and color2. - * If color2 is undefined then color1 will be used - * @param result defines the target Color4 to store the result in - */ - getColorToRef(result) { - if (!this.color2) { - result.copyFrom(this.color1); - return; - } - math_color_Color4.LerpToRef(this.color1, this.color2, Math.random(), result); - } -} -/** Class used to store color 3 gradient */ -class Color3Gradient { - /** - * Creates a new color3 gradient - * @param gradient gets or sets the gradient value (between 0 and 1) - * @param color gets or sets associated color - */ - constructor( - /** - * Gets or sets the gradient value (between 0 and 1) - */ - gradient, - /** - * Gets or sets the associated color - */ - color) { - this.gradient = gradient; - this.color = color; - } -} -/** Class used to store factor gradient */ -class FactorGradient { - /** - * Creates a new factor gradient - * @param gradient gets or sets the gradient value (between 0 and 1) - * @param factor1 gets or sets first associated factor - * @param factor2 gets or sets second associated factor - */ - constructor( - /** - * Gets or sets the gradient value (between 0 and 1) - */ - gradient, - /** - * Gets or sets first associated factor - */ - factor1, - /** - * Gets or sets second associated factor - */ - factor2) { - this.gradient = gradient; - this.factor1 = factor1; - this.factor2 = factor2; - } - /** - * Will get a number picked randomly between factor1 and factor2. - * If factor2 is undefined then factor1 will be used - * @returns the picked number - */ - getFactor() { - if (this.factor2 === undefined || this.factor2 === this.factor1) { - return this.factor1; - } - return this.factor1 + (this.factor2 - this.factor1) * Math.random(); - } -} -/** - * Helper used to simplify some generic gradient tasks - */ -class GradientHelper { - /** - * Gets the current gradient from an array of IValueGradient - * @param ratio defines the current ratio to get - * @param gradients defines the array of IValueGradient - * @param updateFunc defines the callback function used to get the final value from the selected gradients - */ - static GetCurrentGradient(ratio, gradients, updateFunc) { - // Use last index if over - if (gradients[0].gradient > ratio) { - updateFunc(gradients[0], gradients[0], 1.0); - return; - } - for (let gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) { - const currentGradient = gradients[gradientIndex]; - const nextGradient = gradients[gradientIndex + 1]; - if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) { - const scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient); - updateFunc(currentGradient, nextGradient, scale); - return; - } - } - // Use last index if over - const lastIndex = gradients.length - 1; - updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0); - } -} -//# sourceMappingURL=gradients.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/particle.js - - - -/** - * A particle represents one of the element emitted by a particle system. - * This is mainly define by its coordinates, direction, velocity and age. - */ -class Particle { - /** - * Creates a new instance Particle - * @param particleSystem the particle system the particle belongs to - */ - constructor( - /** - * The particle system the particle belongs to. - */ - particleSystem) { - this.particleSystem = particleSystem; - /** - * The world position of the particle in the scene. - */ - this.position = math_vector_Vector3.Zero(); - /** - * The world direction of the particle in the scene. - */ - this.direction = math_vector_Vector3.Zero(); - /** - * The color of the particle. - */ - this.color = new math_color_Color4(0, 0, 0, 0); - /** - * The color change of the particle per step. - */ - this.colorStep = new math_color_Color4(0, 0, 0, 0); - /** - * Defines how long will the life of the particle be. - */ - this.lifeTime = 1.0; - /** - * The current age of the particle. - */ - this.age = 0; - /** - * The current size of the particle. - */ - this.size = 0; - /** - * The current scale of the particle. - */ - this.scale = new math_vector_Vector2(1, 1); - /** - * The current angle of the particle. - */ - this.angle = 0; - /** - * Defines how fast is the angle changing. - */ - this.angularSpeed = 0; - /** - * Defines the cell index used by the particle to be rendered from a sprite. - */ - this.cellIndex = 0; - /** @internal */ - this._attachedSubEmitters = null; - /** @internal */ - this._currentColor1 = new math_color_Color4(0, 0, 0, 0); - /** @internal */ - this._currentColor2 = new math_color_Color4(0, 0, 0, 0); - /** @internal */ - this._currentSize1 = 0; - /** @internal */ - this._currentSize2 = 0; - /** @internal */ - this._currentAngularSpeed1 = 0; - /** @internal */ - this._currentAngularSpeed2 = 0; - /** @internal */ - this._currentVelocity1 = 0; - /** @internal */ - this._currentVelocity2 = 0; - /** @internal */ - this._currentLimitVelocity1 = 0; - /** @internal */ - this._currentLimitVelocity2 = 0; - /** @internal */ - this._currentDrag1 = 0; - /** @internal */ - this._currentDrag2 = 0; - this.id = Particle._Count++; - if (!this.particleSystem.isAnimationSheetEnabled) { - return; - } - this._updateCellInfoFromSystem(); - } - _updateCellInfoFromSystem() { - this.cellIndex = this.particleSystem.startSpriteCellID; - } - /** - * Defines how the sprite cell index is updated for the particle - */ - updateCellIndex() { - let offsetAge = this.age; - let changeSpeed = this.particleSystem.spriteCellChangeSpeed; - if (this.particleSystem.spriteRandomStartCell) { - if (this._randomCellOffset === undefined) { - this._randomCellOffset = Math.random() * this.lifeTime; - } - if (changeSpeed === 0) { - // Special case when speed = 0 meaning we want to stay on initial cell - changeSpeed = 1; - offsetAge = this._randomCellOffset; - } - else { - offsetAge += this._randomCellOffset; - } - } - const dist = this._initialEndSpriteCellID - this._initialStartSpriteCellID; - let ratio; - if (this._initialSpriteCellLoop) { - ratio = math_scalar_Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime); - } - else { - ratio = math_scalar_Scalar.Clamp((offsetAge * changeSpeed) / this.lifeTime); - } - this.cellIndex = (this._initialStartSpriteCellID + ratio * dist) | 0; - } - /** - * @internal - */ - _inheritParticleInfoToSubEmitter(subEmitter) { - if (subEmitter.particleSystem.emitter.position) { - const emitterMesh = subEmitter.particleSystem.emitter; - emitterMesh.position.copyFrom(this.position); - if (subEmitter.inheritDirection) { - const temp = math_vector_TmpVectors.Vector3[0]; - this.direction.normalizeToRef(temp); - emitterMesh.setDirection(temp, 0, Math.PI / 2); - } - } - else { - const emitterPosition = subEmitter.particleSystem.emitter; - emitterPosition.copyFrom(this.position); - } - // Set inheritedVelocityOffset to be used when new particles are created - this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, math_vector_TmpVectors.Vector3[0]); - subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(math_vector_TmpVectors.Vector3[0]); - } - /** @internal */ - _inheritParticleInfoToSubEmitters() { - if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) { - this._attachedSubEmitters.forEach((subEmitter) => { - this._inheritParticleInfoToSubEmitter(subEmitter); - }); - } - } - /** @internal */ - _reset() { - this.age = 0; - this.id = Particle._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 = undefined; - } - /** - * Copy the properties of particle to another one. - * @param other the particle to copy the information to. - */ - copyTo(other) { - other.position.copyFrom(this.position); - if (this._initialDirection) { - if (other._initialDirection) { - other._initialDirection.copyFrom(this._initialDirection); - } - else { - other._initialDirection = this._initialDirection.clone(); - } - } - else { - other._initialDirection = null; - } - other.direction.copyFrom(this.direction); - if (this._localPosition) { - if (other._localPosition) { - other._localPosition.copyFrom(this._localPosition); - } - else { - other._localPosition = this._localPosition.clone(); - } - } - other.color.copyFrom(this.color); - other.colorStep.copyFrom(this.colorStep); - other.lifeTime = this.lifeTime; - other.age = this.age; - other._randomCellOffset = this._randomCellOffset; - other.size = this.size; - other.scale.copyFrom(this.scale); - other.angle = this.angle; - other.angularSpeed = this.angularSpeed; - other.particleSystem = this.particleSystem; - other.cellIndex = this.cellIndex; - other.id = this.id; - other._attachedSubEmitters = this._attachedSubEmitters; - if (this._currentColorGradient) { - other._currentColorGradient = this._currentColorGradient; - other._currentColor1.copyFrom(this._currentColor1); - other._currentColor2.copyFrom(this._currentColor2); - } - if (this._currentSizeGradient) { - other._currentSizeGradient = this._currentSizeGradient; - other._currentSize1 = this._currentSize1; - other._currentSize2 = this._currentSize2; - } - if (this._currentAngularSpeedGradient) { - other._currentAngularSpeedGradient = this._currentAngularSpeedGradient; - other._currentAngularSpeed1 = this._currentAngularSpeed1; - other._currentAngularSpeed2 = this._currentAngularSpeed2; - } - if (this._currentVelocityGradient) { - other._currentVelocityGradient = this._currentVelocityGradient; - other._currentVelocity1 = this._currentVelocity1; - other._currentVelocity2 = this._currentVelocity2; - } - if (this._currentLimitVelocityGradient) { - other._currentLimitVelocityGradient = this._currentLimitVelocityGradient; - other._currentLimitVelocity1 = this._currentLimitVelocity1; - other._currentLimitVelocity2 = this._currentLimitVelocity2; - } - if (this._currentDragGradient) { - other._currentDragGradient = this._currentDragGradient; - other._currentDrag1 = this._currentDrag1; - other._currentDrag2 = this._currentDrag2; - } - if (this.particleSystem.isAnimationSheetEnabled) { - other._initialStartSpriteCellID = this._initialStartSpriteCellID; - other._initialEndSpriteCellID = this._initialEndSpriteCellID; - other._initialSpriteCellLoop = this._initialSpriteCellLoop; - } - if (this.particleSystem.useRampGradients) { - if (other.remapData && this.remapData) { - other.remapData.copyFrom(this.remapData); - } - else { - other.remapData = new math_vector_Vector4(0, 0, 0, 0); - } - } - if (this._randomNoiseCoordinates1) { - if (other._randomNoiseCoordinates1) { - other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1); - other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2); - } - else { - other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone(); - other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone(); - } - } - } -} -Particle._Count = 0; -//# sourceMappingURL=particle.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/subEmitter.js - - - -/** - * Type of sub emitter - */ -var SubEmitterType; -(function (SubEmitterType) { - /** - * Attached to the particle over it's lifetime - */ - SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED"; - /** - * Created when the particle dies - */ - SubEmitterType[SubEmitterType["END"] = 1] = "END"; -})(SubEmitterType || (SubEmitterType = {})); -/** - * Sub emitter class used to emit particles from an existing particle - */ -class SubEmitter { - /** - * Creates a sub emitter - * @param particleSystem the particle system to be used by the sub emitter - */ - constructor( - /** - * the particle system to be used by the sub emitter - */ - particleSystem) { - this.particleSystem = particleSystem; - /** - * Type of the submitter (Default: END) - */ - this.type = SubEmitterType.END; - /** - * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false) - * Note: This only is supported when using an emitter of type Mesh - */ - this.inheritDirection = false; - /** - * How much of the attached particles speed should be added to the sub emitted particle (default: 0) - */ - this.inheritedVelocityAmount = 0; - // Create mesh as emitter to support rotation - if (!particleSystem.emitter || !particleSystem.emitter.dispose) { - const internalClass = GetClass("BABYLON.AbstractMesh"); - particleSystem.emitter = new internalClass("SubemitterSystemEmitter", particleSystem.getScene()); - particleSystem._disposeEmitterOnDispose = true; - } - } - /** - * Clones the sub emitter - * @returns the cloned sub emitter - */ - clone() { - // Clone particle system - let emitter = this.particleSystem.emitter; - if (!emitter) { - emitter = new math_vector_Vector3(); - } - else if (emitter instanceof math_vector_Vector3) { - emitter = emitter.clone(); - } - else if (emitter.getClassName().indexOf("Mesh") !== -1) { - const internalClass = GetClass("BABYLON.Mesh"); - emitter = new internalClass("", emitter.getScene()); - emitter.isVisible = false; - } - const clone = new SubEmitter(this.particleSystem.clone(this.particleSystem.name, emitter)); - // Clone properties - clone.particleSystem.name += "Clone"; - clone.type = this.type; - clone.inheritDirection = this.inheritDirection; - clone.inheritedVelocityAmount = this.inheritedVelocityAmount; - clone.particleSystem._disposeEmitterOnDispose = true; - clone.particleSystem.disposeOnStop = true; - return clone; - } - /** - * Serialize current object to a JSON object - * @param serializeTexture defines if the texture must be serialized as well - * @returns the serialized object - */ - serialize(serializeTexture = false) { - const serializationObject = {}; - serializationObject.type = this.type; - serializationObject.inheritDirection = this.inheritDirection; - serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount; - serializationObject.particleSystem = this.particleSystem.serialize(serializeTexture); - return serializationObject; - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static _ParseParticleSystem(system, sceneOrEngine, rootUrl, doNotStart = false) { - throw _WarnImport("ParseParticle"); - } - /** - * Creates a new SubEmitter from a serialized JSON version - * @param serializationObject defines the JSON object to read from - * @param sceneOrEngine defines the hosting scene or the hosting engine - * @param rootUrl defines the rootUrl for data loading - * @returns a new SubEmitter - */ - static Parse(serializationObject, sceneOrEngine, rootUrl) { - const system = serializationObject.particleSystem; - const subEmitter = new SubEmitter(SubEmitter._ParseParticleSystem(system, sceneOrEngine, rootUrl, true)); - subEmitter.type = serializationObject.type; - subEmitter.inheritDirection = serializationObject.inheritDirection; - subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount; - subEmitter.particleSystem._isSubEmitter = true; - return subEmitter; - } - /** Release associated resources */ - dispose() { - this.particleSystem.dispose(); - } -} -//# sourceMappingURL=subEmitter.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/particles.fragment.js -// Do not edit. - - - - - - - - -const particles_fragment_name = "particlesPixelShader"; -const particles_fragment_shader = `#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; -#include<clipPlaneFragmentDeclaration> -#include<imageProcessingDeclaration> -#include<logDepthDeclaration> -#include<helperFunctions> -#include<imageProcessingFunctions> -#ifdef RAMPGRADIENT -varying vec4 remapRanges;uniform sampler2D rampSampler; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; -#ifdef RAMPGRADIENT -float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); -#endif -#ifdef BLENDMULTIPLYMODE -float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); -#endif -#include<logDepthFragment> -#ifdef IMAGEPROCESSINGPOSTPROCESS -baseColor.rgb=toLinearSpace(baseColor.rgb); -#else -#ifdef IMAGEPROCESSING -baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); -#endif -#endif -gl_FragColor=baseColor; -#define CUSTOM_FRAGMENT_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[particles_fragment_name] = particles_fragment_shader; -/** @internal */ -const particlesPixelShader = { name: particles_fragment_name, shader: particles_fragment_shader }; -//# sourceMappingURL=particles.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/particles.vertex.js -// Do not edit. - - - - - -const particles_vertex_name = "particlesVertexShader"; -const particles_vertex_shader = `attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; -#ifdef ANIMATESHEET -attribute float cellIndex; -#endif -#ifndef BILLBOARD -attribute vec3 direction; -#endif -#ifdef BILLBOARDSTRETCHED -attribute vec3 direction; -#endif -#ifdef RAMPGRADIENT -attribute vec4 remapData; -#endif -attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; -#ifdef ANIMATESHEET -uniform vec3 particlesInfos; -#endif -varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; -#ifdef RAMPGRADIENT -varying vec4 remapRanges; -#endif -#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) -uniform mat4 invView; -#endif -#include<clipPlaneVertexDeclaration> -#include<logDepthDeclaration> -#ifdef BILLBOARD -uniform vec3 eyePosition; -#endif -vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} -#ifdef BILLBOARDSTRETCHED -vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); -#ifdef BILLBOARDSTRETCHED_LOCAL -vec3 row1=direction; -#else -vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); -#endif -mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; -#ifdef BILLBOARD -vec3 rotatedCorner; -#ifdef BILLBOARDY -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; -#elif defined(BILLBOARDSTRETCHED) -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; -#else -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; -#endif -#ifdef RAMPGRADIENT -remapRanges=remapData; -#endif -gl_Position=projection*vec4(viewPos,1.0); -#else -vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); -#endif -vColor=color; -#ifdef ANIMATESHEET -float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; -#else -vUV=offset; -#endif -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=vec4(vPositionW,1.0); -#endif -#include<clipPlaneVertex> -#include<logDepthVertex> -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[particles_vertex_name] = particles_vertex_shader; -/** @internal */ -const particlesVertexShader = { name: particles_vertex_name, shader: particles_vertex_shader }; -//# sourceMappingURL=particles.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/particleSystem.js - - - - - - - - - - - - - - - - - - - - - - - -/** - * This represents a particle system in Babylon. - * 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. - * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function. - * @example https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro - */ -class particleSystem_ParticleSystem extends BaseParticleSystem { - /** - * Sets a callback that will be triggered when the system is disposed - */ - set onDispose(callback) { - if (this._onDisposeObserver) { - this.onDisposeObservable.remove(this._onDisposeObserver); - } - this._onDisposeObserver = this.onDisposeObservable.add(callback); - } - /** Gets or sets a boolean indicating that ramp gradients must be used - * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients - */ - get useRampGradients() { - return this._useRampGradients; - } - set useRampGradients(value) { - if (this._useRampGradients === value) { - return; - } - this._useRampGradients = value; - this._resetEffect(); - } - //end of Sub-emitter - /** - * Gets the current list of active particles - */ - get particles() { - return this._particles; - } - /** - * Gets the number of particles active at the same time. - * @returns The number of active particles. - */ - getActiveCount() { - return this._particles.length; - } - /** - * Returns the string "ParticleSystem" - * @returns a string containing the class name - */ - getClassName() { - return "ParticleSystem"; - } - /** - * Gets a boolean indicating that the system is stopping - * @returns true if the system is currently stopping - */ - isStopping() { - return this._stopped && this.isAlive(); - } - /** - * Gets the custom effect used to render the particles - * @param blendMode Blend mode for which the effect should be retrieved - * @returns The effect - */ - getCustomEffect(blendMode = 0) { - var _a, _b; - return (_b = (_a = this._customWrappers[blendMode]) === null || _a === void 0 ? void 0 : _a.effect) !== null && _b !== void 0 ? _b : this._customWrappers[0].effect; - } - _getCustomDrawWrapper(blendMode = 0) { - var _a; - return (_a = this._customWrappers[blendMode]) !== null && _a !== void 0 ? _a : this._customWrappers[0]; - } - /** - * Sets the custom effect used to render the particles - * @param effect The effect to set - * @param blendMode Blend mode for which the effect should be set - */ - setCustomEffect(effect, blendMode = 0) { - this._customWrappers[blendMode] = new drawWrapper_DrawWrapper(this._engine); - this._customWrappers[blendMode].effect = effect; - if (this._customWrappers[blendMode].drawContext) { - this._customWrappers[blendMode].drawContext.useInstancing = this._useInstancing; - } - } - /** - * Observable that will be called just before the particles are drawn - */ - get onBeforeDrawParticlesObservable() { - if (!this._onBeforeDrawParticlesObservable) { - this._onBeforeDrawParticlesObservable = new observable_Observable(); - } - return this._onBeforeDrawParticlesObservable; - } - /** - * Gets the name of the particle vertex shader - */ - get vertexShaderName() { - return "particles"; - } - /** - * Gets the vertex buffers used by the particle system - */ - get vertexBuffers() { - return this._vertexBuffers; - } - /** - * Gets the index buffer used by the particle system (or null if no index buffer is used (if _useInstancing=true)) - */ - get indexBuffer() { - return this._indexBuffer; - } - /** - * Instantiates a particle system. - * 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. - * @param name The name of the particle system - * @param capacity The max number of particles alive at the same time - * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene - * @param customEffect a custom effect used to change the way particles are rendered by default - * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture - * @param epsilon Offset used to render the particles - */ - constructor(name, capacity, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false, epsilon = 0.01) { - super(name); - this._emitterInverseWorldMatrix = math_vector_Matrix.Identity(); - /** - * @internal - */ - this._inheritedVelocityOffset = new math_vector_Vector3(); - /** - * An event triggered when the system is disposed - */ - this.onDisposeObservable = new observable_Observable(); - /** - * An event triggered when the system is stopped - */ - this.onStoppedObservable = new observable_Observable(); - this._particles = new Array(); - this._stockParticles = new Array(); - this._newPartsExcess = 0; - this._vertexBuffers = {}; - this._scaledColorStep = new math_color_Color4(0, 0, 0, 0); - this._colorDiff = new math_color_Color4(0, 0, 0, 0); - this._scaledDirection = math_vector_Vector3.Zero(); - this._scaledGravity = math_vector_Vector3.Zero(); - this._currentRenderId = -1; - this._useInstancing = false; - this._started = false; - this._stopped = false; - this._actualFrame = 0; - /** @internal */ - this._currentEmitRate1 = 0; - /** @internal */ - this._currentEmitRate2 = 0; - /** @internal */ - this._currentStartSize1 = 0; - /** @internal */ - this._currentStartSize2 = 0; - /** Indicates that the update of particles is done in the animate function */ - this.updateInAnimate = true; - this._rawTextureWidth = 256; - this._useRampGradients = false; - /** - * @internal - * If the particle systems emitter should be disposed when the particle system is disposed - */ - this._disposeEmitterOnDispose = false; - /** - * Specifies if the particles are updated in emitter local space or world space - */ - this.isLocal = false; - /** Indicates that the particle system is CPU based */ - this.isGPU = false; - /** @internal */ - this._onBeforeDrawParticlesObservable = null; - // start of sub system methods - /** - * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list. - * Its lifetime will start back at 0. - * @param particle - */ - this.recycleParticle = (particle) => { - // move particle from activeParticle list to stock particles - const lastParticle = this._particles.pop(); - if (lastParticle !== particle) { - lastParticle.copyTo(particle); - } - this._stockParticles.push(lastParticle); - }; - this._createParticle = () => { - let particle; - if (this._stockParticles.length !== 0) { - particle = this._stockParticles.pop(); - particle._reset(); - } - else { - particle = new Particle(this); - } - // Attach emitters - if (this._subEmitters && this._subEmitters.length > 0) { - const subEmitters = this._subEmitters[Math.floor(Math.random() * this._subEmitters.length)]; - particle._attachedSubEmitters = []; - subEmitters.forEach((subEmitter) => { - if (subEmitter.type === SubEmitterType.ATTACHED) { - const newEmitter = subEmitter.clone(); - particle._attachedSubEmitters.push(newEmitter); - newEmitter.particleSystem.start(); - } - }); - } - return particle; - }; - this._emitFromParticle = (particle) => { - if (!this._subEmitters || this._subEmitters.length === 0) { - return; - } - const templateIndex = Math.floor(Math.random() * this._subEmitters.length); - this._subEmitters[templateIndex].forEach((subEmitter) => { - if (subEmitter.type === SubEmitterType.END) { - const subSystem = subEmitter.clone(); - particle._inheritParticleInfoToSubEmitter(subSystem); - subSystem.particleSystem._rootParticleSystem = this; - this.activeSubSystems.push(subSystem.particleSystem); - subSystem.particleSystem.start(); - } - }); - }; - this._capacity = capacity; - this._epsilon = epsilon; - this._isAnimationSheetEnabled = isAnimationSheetEnabled; - if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") { - this._scene = sceneOrEngine || engineStore_EngineStore.LastCreatedScene; - this._engine = this._scene.getEngine(); - this.uniqueId = this._scene.getUniqueId(); - this._scene.particleSystems.push(this); - } - else { - this._engine = sceneOrEngine; - this.defaultProjectionMatrix = math_vector_Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange); - } - if (this._engine.getCaps().vertexArrayObject) { - this._vertexArrayObject = null; - } - // Setup the default processing configuration to the scene. - this._attachImageProcessingConfiguration(null); - // eslint-disable-next-line @typescript-eslint/naming-convention - this._customWrappers = { 0: new drawWrapper_DrawWrapper(this._engine) }; - this._customWrappers[0].effect = customEffect; - this._drawWrappers = []; - this._useInstancing = this._engine.getCaps().instancedArrays; - this._createIndexBuffer(); - this._createVertexBuffers(); - // Default emitter type - this.particleEmitterType = new BoxParticleEmitter(); - let noiseTextureData = null; - // Update - this.updateFunction = (particles) => { - var _a; - let noiseTextureSize = null; - if (this.noiseTexture) { - // We need to get texture data back to CPU - noiseTextureSize = this.noiseTexture.getSize(); - (_a = this.noiseTexture.getContent()) === null || _a === void 0 ? void 0 : _a.then((data) => { - noiseTextureData = data; - }); - } - const sameParticleArray = particles === this._particles; - for (let index = 0; index < particles.length; index++) { - const particle = particles[index]; - let scaledUpdateSpeed = this._scaledUpdateSpeed; - const previousAge = particle.age; - particle.age += scaledUpdateSpeed; - // Evaluate step to death - if (particle.age > particle.lifeTime) { - const diff = particle.age - previousAge; - const oldDiff = particle.lifeTime - previousAge; - scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff; - particle.age = particle.lifeTime; - } - const ratio = particle.age / particle.lifeTime; - // Color - if (this._colorGradients && this._colorGradients.length > 0) { - GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => { - if (currentGradient !== particle._currentColorGradient) { - particle._currentColor1.copyFrom(particle._currentColor2); - nextGradient.getColorToRef(particle._currentColor2); - particle._currentColorGradient = currentGradient; - } - math_color_Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color); - }); - } - else { - particle.colorStep.scaleToRef(scaledUpdateSpeed, this._scaledColorStep); - particle.color.addInPlace(this._scaledColorStep); - if (particle.color.a < 0) { - particle.color.a = 0; - } - } - // Angular speed - if (this._angularSpeedGradients && this._angularSpeedGradients.length > 0) { - GradientHelper.GetCurrentGradient(ratio, this._angularSpeedGradients, (currentGradient, nextGradient, scale) => { - if (currentGradient !== particle._currentAngularSpeedGradient) { - particle._currentAngularSpeed1 = particle._currentAngularSpeed2; - particle._currentAngularSpeed2 = nextGradient.getFactor(); - particle._currentAngularSpeedGradient = currentGradient; - } - particle.angularSpeed = math_scalar_Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale); - }); - } - particle.angle += particle.angularSpeed * scaledUpdateSpeed; - // Direction - let directionScale = scaledUpdateSpeed; - /// Velocity - if (this._velocityGradients && this._velocityGradients.length > 0) { - GradientHelper.GetCurrentGradient(ratio, this._velocityGradients, (currentGradient, nextGradient, scale) => { - if (currentGradient !== particle._currentVelocityGradient) { - particle._currentVelocity1 = particle._currentVelocity2; - particle._currentVelocity2 = nextGradient.getFactor(); - particle._currentVelocityGradient = currentGradient; - } - directionScale *= math_scalar_Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale); - }); - } - particle.direction.scaleToRef(directionScale, this._scaledDirection); - /// Limit velocity - if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) { - GradientHelper.GetCurrentGradient(ratio, this._limitVelocityGradients, (currentGradient, nextGradient, scale) => { - if (currentGradient !== particle._currentLimitVelocityGradient) { - particle._currentLimitVelocity1 = particle._currentLimitVelocity2; - particle._currentLimitVelocity2 = nextGradient.getFactor(); - particle._currentLimitVelocityGradient = currentGradient; - } - const limitVelocity = math_scalar_Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale); - const currentVelocity = particle.direction.length(); - if (currentVelocity > limitVelocity) { - particle.direction.scaleInPlace(this.limitVelocityDamping); - } - }); - } - /// Drag - if (this._dragGradients && this._dragGradients.length > 0) { - GradientHelper.GetCurrentGradient(ratio, this._dragGradients, (currentGradient, nextGradient, scale) => { - if (currentGradient !== particle._currentDragGradient) { - particle._currentDrag1 = particle._currentDrag2; - particle._currentDrag2 = nextGradient.getFactor(); - particle._currentDragGradient = currentGradient; - } - const drag = math_scalar_Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale); - this._scaledDirection.scaleInPlace(1.0 - drag); - }); - } - if (this.isLocal && particle._localPosition) { - particle._localPosition.addInPlace(this._scaledDirection); - math_vector_Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position); - } - else { - particle.position.addInPlace(this._scaledDirection); - } - // Noise - if (noiseTextureData && noiseTextureSize && particle._randomNoiseCoordinates1) { - const fetchedColorR = this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData); - const fetchedColorG = this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData); - const fetchedColorB = this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData); - const force = math_vector_TmpVectors.Vector3[0]; - const scaledForce = math_vector_TmpVectors.Vector3[1]; - force.copyFromFloats((2 * fetchedColorR - 1) * this.noiseStrength.x, (2 * fetchedColorG - 1) * this.noiseStrength.y, (2 * fetchedColorB - 1) * this.noiseStrength.z); - force.scaleToRef(scaledUpdateSpeed, scaledForce); - particle.direction.addInPlace(scaledForce); - } - // Gravity - this.gravity.scaleToRef(scaledUpdateSpeed, this._scaledGravity); - particle.direction.addInPlace(this._scaledGravity); - // Size - if (this._sizeGradients && this._sizeGradients.length > 0) { - GradientHelper.GetCurrentGradient(ratio, this._sizeGradients, (currentGradient, nextGradient, scale) => { - if (currentGradient !== particle._currentSizeGradient) { - particle._currentSize1 = particle._currentSize2; - particle._currentSize2 = nextGradient.getFactor(); - particle._currentSizeGradient = currentGradient; - } - particle.size = math_scalar_Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale); - }); - } - // Remap data - if (this._useRampGradients) { - if (this._colorRemapGradients && this._colorRemapGradients.length > 0) { - GradientHelper.GetCurrentGradient(ratio, this._colorRemapGradients, (currentGradient, nextGradient, scale) => { - const min = math_scalar_Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale); - const max = math_scalar_Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale); - particle.remapData.x = min; - particle.remapData.y = max - min; - }); - } - if (this._alphaRemapGradients && this._alphaRemapGradients.length > 0) { - GradientHelper.GetCurrentGradient(ratio, this._alphaRemapGradients, (currentGradient, nextGradient, scale) => { - const min = math_scalar_Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale); - const max = math_scalar_Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale); - particle.remapData.z = min; - particle.remapData.w = max - min; - }); - } - } - if (this._isAnimationSheetEnabled) { - particle.updateCellIndex(); - } - // Update the position of the attached sub-emitters to match their attached particle - particle._inheritParticleInfoToSubEmitters(); - if (particle.age >= particle.lifeTime) { - // Recycle by swapping with last particle - this._emitFromParticle(particle); - if (particle._attachedSubEmitters) { - particle._attachedSubEmitters.forEach((subEmitter) => { - subEmitter.particleSystem.disposeOnStop = true; - subEmitter.particleSystem.stop(); - }); - particle._attachedSubEmitters = null; - } - this.recycleParticle(particle); - if (sameParticleArray) { - index--; - } - continue; - } - } - }; - } - _addFactorGradient(factorGradients, gradient, factor, factor2) { - const newGradient = new FactorGradient(gradient, factor, factor2); - factorGradients.push(newGradient); - factorGradients.sort((a, b) => { - if (a.gradient < b.gradient) { - return -1; - } - else if (a.gradient > b.gradient) { - return 1; - } - return 0; - }); - } - _removeFactorGradient(factorGradients, gradient) { - if (!factorGradients) { - return; - } - let index = 0; - for (const factorGradient of factorGradients) { - if (factorGradient.gradient === gradient) { - factorGradients.splice(index, 1); - break; - } - index++; - } - } - /** - * Adds a new life time gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the life time factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system - */ - addLifeTimeGradient(gradient, factor, factor2) { - if (!this._lifeTimeGradients) { - this._lifeTimeGradients = []; - } - this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2); - return this; - } - /** - * Remove a specific life time gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeLifeTimeGradient(gradient) { - this._removeFactorGradient(this._lifeTimeGradients, gradient); - return this; - } - /** - * Adds a new size gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system - */ - addSizeGradient(gradient, factor, factor2) { - if (!this._sizeGradients) { - this._sizeGradients = []; - } - this._addFactorGradient(this._sizeGradients, gradient, factor, factor2); - return this; - } - /** - * Remove a specific size gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeSizeGradient(gradient) { - this._removeFactorGradient(this._sizeGradients, gradient); - return this; - } - /** - * Adds a new color remap gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param min defines the color remap minimal range - * @param max defines the color remap maximal range - * @returns the current particle system - */ - addColorRemapGradient(gradient, min, max) { - if (!this._colorRemapGradients) { - this._colorRemapGradients = []; - } - this._addFactorGradient(this._colorRemapGradients, gradient, min, max); - return this; - } - /** - * Remove a specific color remap gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeColorRemapGradient(gradient) { - this._removeFactorGradient(this._colorRemapGradients, gradient); - return this; - } - /** - * Adds a new alpha remap gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param min defines the alpha remap minimal range - * @param max defines the alpha remap maximal range - * @returns the current particle system - */ - addAlphaRemapGradient(gradient, min, max) { - if (!this._alphaRemapGradients) { - this._alphaRemapGradients = []; - } - this._addFactorGradient(this._alphaRemapGradients, gradient, min, max); - return this; - } - /** - * Remove a specific alpha remap gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeAlphaRemapGradient(gradient) { - this._removeFactorGradient(this._alphaRemapGradients, gradient); - return this; - } - /** - * Adds a new angular speed gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the angular speed to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system - */ - addAngularSpeedGradient(gradient, factor, factor2) { - if (!this._angularSpeedGradients) { - this._angularSpeedGradients = []; - } - this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2); - return this; - } - /** - * Remove a specific angular speed gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeAngularSpeedGradient(gradient) { - this._removeFactorGradient(this._angularSpeedGradients, gradient); - return this; - } - /** - * Adds a new velocity gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the velocity to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system - */ - addVelocityGradient(gradient, factor, factor2) { - if (!this._velocityGradients) { - this._velocityGradients = []; - } - this._addFactorGradient(this._velocityGradients, gradient, factor, factor2); - return this; - } - /** - * Remove a specific velocity gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeVelocityGradient(gradient) { - this._removeFactorGradient(this._velocityGradients, gradient); - return this; - } - /** - * Adds a new limit velocity gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the limit velocity value to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system - */ - addLimitVelocityGradient(gradient, factor, factor2) { - if (!this._limitVelocityGradients) { - this._limitVelocityGradients = []; - } - this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2); - return this; - } - /** - * Remove a specific limit velocity gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeLimitVelocityGradient(gradient) { - this._removeFactorGradient(this._limitVelocityGradients, gradient); - return this; - } - /** - * Adds a new drag gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the drag value to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system - */ - addDragGradient(gradient, factor, factor2) { - if (!this._dragGradients) { - this._dragGradients = []; - } - this._addFactorGradient(this._dragGradients, gradient, factor, factor2); - return this; - } - /** - * Remove a specific drag gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeDragGradient(gradient) { - this._removeFactorGradient(this._dragGradients, gradient); - return this; - } - /** - * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property) - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the emit rate value to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system - */ - addEmitRateGradient(gradient, factor, factor2) { - if (!this._emitRateGradients) { - this._emitRateGradients = []; - } - this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2); - return this; - } - /** - * Remove a specific emit rate gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeEmitRateGradient(gradient) { - this._removeFactorGradient(this._emitRateGradients, gradient); - return this; - } - /** - * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property) - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the start size value to affect to the specified gradient - * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from - * @returns the current particle system - */ - addStartSizeGradient(gradient, factor, factor2) { - if (!this._startSizeGradients) { - this._startSizeGradients = []; - } - this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2); - return this; - } - /** - * Remove a specific start size gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeStartSizeGradient(gradient) { - this._removeFactorGradient(this._startSizeGradients, gradient); - return this; - } - _createRampGradientTexture() { - if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture || !this._scene) { - return; - } - const data = new Uint8Array(this._rawTextureWidth * 4); - const tmpColor = TmpColors.Color3[0]; - for (let x = 0; x < this._rawTextureWidth; x++) { - const ratio = x / this._rawTextureWidth; - GradientHelper.GetCurrentGradient(ratio, this._rampGradients, (currentGradient, nextGradient, scale) => { - math_color_Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor); - data[x * 4] = tmpColor.r * 255; - data[x * 4 + 1] = tmpColor.g * 255; - data[x * 4 + 2] = tmpColor.b * 255; - data[x * 4 + 3] = 255; - }); - } - this._rampGradientsTexture = rawTexture_RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1); - } - /** - * Gets the current list of ramp gradients. - * You must use addRampGradient and removeRampGradient to update this list - * @returns the list of ramp gradients - */ - getRampGradients() { - return this._rampGradients; - } - /** Force the system to rebuild all gradients that need to be resync */ - forceRefreshGradients() { - this._syncRampGradientTexture(); - } - _syncRampGradientTexture() { - if (!this._rampGradients) { - return; - } - this._rampGradients.sort((a, b) => { - if (a.gradient < b.gradient) { - return -1; - } - else if (a.gradient > b.gradient) { - return 1; - } - return 0; - }); - if (this._rampGradientsTexture) { - this._rampGradientsTexture.dispose(); - this._rampGradientsTexture = null; - } - this._createRampGradientTexture(); - } - /** - * Adds a new ramp gradient used to remap particle colors - * @param gradient defines the gradient to use (between 0 and 1) - * @param color defines the color to affect to the specified gradient - * @returns the current particle system - */ - addRampGradient(gradient, color) { - if (!this._rampGradients) { - this._rampGradients = []; - } - const rampGradient = new Color3Gradient(gradient, color); - this._rampGradients.push(rampGradient); - this._syncRampGradientTexture(); - return this; - } - /** - * Remove a specific ramp gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeRampGradient(gradient) { - this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture); - this._rampGradientsTexture = null; - if (this._rampGradients && this._rampGradients.length > 0) { - this._createRampGradientTexture(); - } - return this; - } - /** - * Adds a new color gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param color1 defines the color to affect to the specified gradient - * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from - * @returns this particle system - */ - addColorGradient(gradient, color1, color2) { - if (!this._colorGradients) { - this._colorGradients = []; - } - const colorGradient = new ColorGradient(gradient, color1, color2); - this._colorGradients.push(colorGradient); - this._colorGradients.sort((a, b) => { - if (a.gradient < b.gradient) { - return -1; - } - else if (a.gradient > b.gradient) { - return 1; - } - return 0; - }); - return this; - } - /** - * Remove a specific color gradient - * @param gradient defines the gradient to remove - * @returns this particle system - */ - removeColorGradient(gradient) { - if (!this._colorGradients) { - return this; - } - let index = 0; - for (const colorGradient of this._colorGradients) { - if (colorGradient.gradient === gradient) { - this._colorGradients.splice(index, 1); - break; - } - index++; - } - return this; - } - /** - * Resets the draw wrappers cache - */ - resetDrawCache() { - for (const drawWrappers of this._drawWrappers) { - if (drawWrappers) { - for (const drawWrapper of drawWrappers) { - drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.dispose(); - } - } - } - this._drawWrappers = []; - } - _fetchR(u, v, width, height, pixels) { - u = Math.abs(u) * 0.5 + 0.5; - v = Math.abs(v) * 0.5 + 0.5; - const wrappedU = (u * width) % width | 0; - const wrappedV = (v * height) % height | 0; - const position = (wrappedU + wrappedV * width) * 4; - return pixels[position] / 255; - } - _reset() { - this._resetEffect(); - } - _resetEffect() { - if (this._vertexBuffer) { - this._vertexBuffer.dispose(); - this._vertexBuffer = null; - } - if (this._spriteBuffer) { - this._spriteBuffer.dispose(); - this._spriteBuffer = null; - } - if (this._vertexArrayObject) { - this._engine.releaseVertexArrayObject(this._vertexArrayObject); - this._vertexArrayObject = null; - } - this._createVertexBuffers(); - } - _createVertexBuffers() { - this._vertexBufferSize = this._useInstancing ? 10 : 12; - if (this._isAnimationSheetEnabled) { - this._vertexBufferSize += 1; - } - if (!this._isBillboardBased || this.billboardMode === particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED || this.billboardMode === particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) { - this._vertexBufferSize += 3; - } - if (this._useRampGradients) { - this._vertexBufferSize += 4; - } - const engine = this._engine; - const vertexSize = this._vertexBufferSize * (this._useInstancing ? 1 : 4); - this._vertexData = new Float32Array(this._capacity * vertexSize); - this._vertexBuffer = new Buffer(engine, this._vertexData, true, vertexSize); - let dataOffset = 0; - const positions = this._vertexBuffer.createVertexBuffer(buffer_VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = positions; - dataOffset += 3; - const colors = this._vertexBuffer.createVertexBuffer(buffer_VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing); - this._vertexBuffers[buffer_VertexBuffer.ColorKind] = colors; - dataOffset += 4; - const options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing); - this._vertexBuffers["angle"] = options; - dataOffset += 1; - const size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing); - this._vertexBuffers["size"] = size; - dataOffset += 2; - if (this._isAnimationSheetEnabled) { - const cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing); - this._vertexBuffers["cellIndex"] = cellIndexBuffer; - dataOffset += 1; - } - if (!this._isBillboardBased || this.billboardMode === particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED || this.billboardMode === particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) { - const directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing); - this._vertexBuffers["direction"] = directionBuffer; - dataOffset += 3; - } - if (this._useRampGradients) { - const rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing); - this._vertexBuffers["remapData"] = rampDataBuffer; - dataOffset += 4; - } - let offsets; - if (this._useInstancing) { - const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]); - this._spriteBuffer = new Buffer(engine, spriteData, false, 2); - offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2); - } - else { - offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing); - dataOffset += 2; - } - this._vertexBuffers["offset"] = offsets; - this.resetDrawCache(); - } - _createIndexBuffer() { - if (this._useInstancing) { - this._linesIndexBufferUseInstancing = this._engine.createIndexBuffer(new Uint32Array([0, 1, 1, 3, 3, 2, 2, 0, 0, 3])); - return; - } - const indices = []; - const indicesWireframe = []; - let index = 0; - for (let count = 0; count < this._capacity; count++) { - indices.push(index); - indices.push(index + 1); - indices.push(index + 2); - indices.push(index); - indices.push(index + 2); - indices.push(index + 3); - indicesWireframe.push(index, index + 1, index + 1, index + 2, index + 2, index + 3, index + 3, index, index, index + 3); - index += 4; - } - this._indexBuffer = this._engine.createIndexBuffer(indices); - this._linesIndexBuffer = this._engine.createIndexBuffer(indicesWireframe); - } - /** - * Gets the maximum number of particles active at the same time. - * @returns The max number of active particles. - */ - getCapacity() { - return this._capacity; - } - /** - * Gets whether there are still active particles in the system. - * @returns True if it is alive, otherwise false. - */ - isAlive() { - return this._alive; - } - /** - * Gets if the system has been started. (Note: this will still be true after stop is called) - * @returns True if it has been started, otherwise false. - */ - isStarted() { - return this._started; - } - _prepareSubEmitterInternalArray() { - this._subEmitters = new Array(); - if (this.subEmitters) { - this.subEmitters.forEach((subEmitter) => { - if (subEmitter instanceof particleSystem_ParticleSystem) { - this._subEmitters.push([new SubEmitter(subEmitter)]); - } - else if (subEmitter instanceof SubEmitter) { - this._subEmitters.push([subEmitter]); - } - else if (subEmitter instanceof Array) { - this._subEmitters.push(subEmitter); - } - }); - } - } - /** - * Starts the particle system and begins to emit - * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default) - */ - start(delay = this.startDelay) { - var _a; - if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) { - throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set"; - } - if (delay) { - setTimeout(() => { - this.start(0); - }, delay); - return; - } - // Convert the subEmitters field to the constant type field _subEmitters - this._prepareSubEmitterInternalArray(); - this._started = true; - this._stopped = false; - this._actualFrame = 0; - if (this._subEmitters && this._subEmitters.length != 0) { - this.activeSubSystems = new Array(); - } - // Reset emit gradient so it acts the same on every start - if (this._emitRateGradients) { - if (this._emitRateGradients.length > 0) { - this._currentEmitRateGradient = this._emitRateGradients[0]; - this._currentEmitRate1 = this._currentEmitRateGradient.getFactor(); - this._currentEmitRate2 = this._currentEmitRate1; - } - if (this._emitRateGradients.length > 1) { - this._currentEmitRate2 = this._emitRateGradients[1].getFactor(); - } - } - // Reset start size gradient so it acts the same on every start - if (this._startSizeGradients) { - if (this._startSizeGradients.length > 0) { - this._currentStartSizeGradient = this._startSizeGradients[0]; - this._currentStartSize1 = this._currentStartSizeGradient.getFactor(); - this._currentStartSize2 = this._currentStartSize1; - } - if (this._startSizeGradients.length > 1) { - this._currentStartSize2 = this._startSizeGradients[1].getFactor(); - } - } - if (this.preWarmCycles) { - if (((_a = this.emitter) === null || _a === void 0 ? void 0 : _a.getClassName().indexOf("Mesh")) !== -1) { - this.emitter.computeWorldMatrix(true); - } - const noiseTextureAsProcedural = this.noiseTexture; - if (noiseTextureAsProcedural && noiseTextureAsProcedural.onGeneratedObservable) { - noiseTextureAsProcedural.onGeneratedObservable.addOnce(() => { - setTimeout(() => { - for (let index = 0; index < this.preWarmCycles; index++) { - this.animate(true); - noiseTextureAsProcedural.render(); - } - }); - }); - } - else { - for (let index = 0; index < this.preWarmCycles; index++) { - this.animate(true); - } - } - } - // Animations - if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) { - this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop); - } - } - /** - * Stops the particle system. - * @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. - */ - stop(stopSubEmitters = true) { - if (this._stopped) { - return; - } - this.onStoppedObservable.notifyObservers(this); - this._stopped = true; - if (stopSubEmitters) { - this._stopSubEmitters(); - } - } - // animation sheet - /** - * Remove all active particles - */ - reset() { - this._stockParticles.length = 0; - this._particles.length = 0; - } - /** - * @internal (for internal use only) - */ - _appendParticleVertex(index, particle, offsetX, offsetY) { - let offset = index * this._vertexBufferSize; - this._vertexData[offset++] = particle.position.x + this.worldOffset.x; - this._vertexData[offset++] = particle.position.y + this.worldOffset.y; - this._vertexData[offset++] = particle.position.z + this.worldOffset.z; - this._vertexData[offset++] = particle.color.r; - this._vertexData[offset++] = particle.color.g; - this._vertexData[offset++] = particle.color.b; - this._vertexData[offset++] = particle.color.a; - this._vertexData[offset++] = particle.angle; - this._vertexData[offset++] = particle.scale.x * particle.size; - this._vertexData[offset++] = particle.scale.y * particle.size; - if (this._isAnimationSheetEnabled) { - this._vertexData[offset++] = particle.cellIndex; - } - if (!this._isBillboardBased) { - if (particle._initialDirection) { - let initialDirection = particle._initialDirection; - if (this.isLocal) { - math_vector_Vector3.TransformNormalToRef(initialDirection, this._emitterWorldMatrix, math_vector_TmpVectors.Vector3[0]); - initialDirection = math_vector_TmpVectors.Vector3[0]; - } - if (initialDirection.x === 0 && initialDirection.z === 0) { - initialDirection.x = 0.001; - } - this._vertexData[offset++] = initialDirection.x; - this._vertexData[offset++] = initialDirection.y; - this._vertexData[offset++] = initialDirection.z; - } - else { - let direction = particle.direction; - if (this.isLocal) { - math_vector_Vector3.TransformNormalToRef(direction, this._emitterWorldMatrix, math_vector_TmpVectors.Vector3[0]); - direction = math_vector_TmpVectors.Vector3[0]; - } - if (direction.x === 0 && direction.z === 0) { - direction.x = 0.001; - } - this._vertexData[offset++] = direction.x; - this._vertexData[offset++] = direction.y; - this._vertexData[offset++] = direction.z; - } - } - else if (this.billboardMode === particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED || this.billboardMode === particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) { - this._vertexData[offset++] = particle.direction.x; - this._vertexData[offset++] = particle.direction.y; - this._vertexData[offset++] = particle.direction.z; - } - if (this._useRampGradients && particle.remapData) { - this._vertexData[offset++] = particle.remapData.x; - this._vertexData[offset++] = particle.remapData.y; - this._vertexData[offset++] = particle.remapData.z; - this._vertexData[offset++] = particle.remapData.w; - } - if (!this._useInstancing) { - if (this._isAnimationSheetEnabled) { - if (offsetX === 0) { - offsetX = this._epsilon; - } - else if (offsetX === 1) { - offsetX = 1 - this._epsilon; - } - if (offsetY === 0) { - offsetY = this._epsilon; - } - else if (offsetY === 1) { - offsetY = 1 - this._epsilon; - } - } - this._vertexData[offset++] = offsetX; - this._vertexData[offset++] = offsetY; - } - } - _stopSubEmitters() { - if (!this.activeSubSystems) { - return; - } - this.activeSubSystems.forEach((subSystem) => { - subSystem.stop(true); - }); - this.activeSubSystems = new Array(); - } - _removeFromRoot() { - if (!this._rootParticleSystem) { - return; - } - const index = this._rootParticleSystem.activeSubSystems.indexOf(this); - if (index !== -1) { - this._rootParticleSystem.activeSubSystems.splice(index, 1); - } - this._rootParticleSystem = null; - } - // End of sub system methods - _update(newParticles) { - // Update current - this._alive = this._particles.length > 0; - if (this.emitter.position) { - const emitterMesh = this.emitter; - this._emitterWorldMatrix = emitterMesh.getWorldMatrix(); - } - else { - const emitterPosition = this.emitter; - this._emitterWorldMatrix = math_vector_Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z); - } - this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix); - this.updateFunction(this._particles); - // Add new ones - let particle; - for (let index = 0; index < newParticles; index++) { - if (this._particles.length === this._capacity) { - break; - } - particle = this._createParticle(); - this._particles.push(particle); - // Life time - if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) { - const ratio = math_scalar_Scalar.Clamp(this._actualFrame / this.targetStopDuration); - GradientHelper.GetCurrentGradient(ratio, this._lifeTimeGradients, (currentGradient, nextGradient) => { - const factorGradient1 = currentGradient; - const factorGradient2 = nextGradient; - const lifeTime1 = factorGradient1.getFactor(); - const lifeTime2 = factorGradient2.getFactor(); - const gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient); - particle.lifeTime = math_scalar_Scalar.Lerp(lifeTime1, lifeTime2, gradient); - }); - } - else { - particle.lifeTime = math_scalar_Scalar.RandomRange(this.minLifeTime, this.maxLifeTime); - } - // Emitter - const emitPower = math_scalar_Scalar.RandomRange(this.minEmitPower, this.maxEmitPower); - if (this.startPositionFunction) { - this.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal); - } - else { - this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal); - } - if (this.isLocal) { - if (!particle._localPosition) { - particle._localPosition = particle.position.clone(); - } - else { - particle._localPosition.copyFrom(particle.position); - } - math_vector_Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position); - } - if (this.startDirectionFunction) { - this.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal); - } - else { - this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal, this._emitterInverseWorldMatrix); - } - if (emitPower === 0) { - if (!particle._initialDirection) { - particle._initialDirection = particle.direction.clone(); - } - else { - particle._initialDirection.copyFrom(particle.direction); - } - } - else { - particle._initialDirection = null; - } - particle.direction.scaleInPlace(emitPower); - // Size - if (!this._sizeGradients || this._sizeGradients.length === 0) { - particle.size = math_scalar_Scalar.RandomRange(this.minSize, this.maxSize); - } - else { - particle._currentSizeGradient = this._sizeGradients[0]; - particle._currentSize1 = particle._currentSizeGradient.getFactor(); - particle.size = particle._currentSize1; - if (this._sizeGradients.length > 1) { - particle._currentSize2 = this._sizeGradients[1].getFactor(); - } - else { - particle._currentSize2 = particle._currentSize1; - } - } - // Size and scale - particle.scale.copyFromFloats(math_scalar_Scalar.RandomRange(this.minScaleX, this.maxScaleX), math_scalar_Scalar.RandomRange(this.minScaleY, this.maxScaleY)); - // Adjust scale by start size - if (this._startSizeGradients && this._startSizeGradients[0] && this.targetStopDuration) { - const ratio = this._actualFrame / this.targetStopDuration; - GradientHelper.GetCurrentGradient(ratio, this._startSizeGradients, (currentGradient, nextGradient, scale) => { - if (currentGradient !== this._currentStartSizeGradient) { - this._currentStartSize1 = this._currentStartSize2; - this._currentStartSize2 = nextGradient.getFactor(); - this._currentStartSizeGradient = currentGradient; - } - const value = math_scalar_Scalar.Lerp(this._currentStartSize1, this._currentStartSize2, scale); - particle.scale.scaleInPlace(value); - }); - } - // Angle - if (!this._angularSpeedGradients || this._angularSpeedGradients.length === 0) { - particle.angularSpeed = math_scalar_Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed); - } - else { - particle._currentAngularSpeedGradient = this._angularSpeedGradients[0]; - particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor(); - particle._currentAngularSpeed1 = particle.angularSpeed; - if (this._angularSpeedGradients.length > 1) { - particle._currentAngularSpeed2 = this._angularSpeedGradients[1].getFactor(); - } - else { - particle._currentAngularSpeed2 = particle._currentAngularSpeed1; - } - } - particle.angle = math_scalar_Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation); - // Velocity - if (this._velocityGradients && this._velocityGradients.length > 0) { - particle._currentVelocityGradient = this._velocityGradients[0]; - particle._currentVelocity1 = particle._currentVelocityGradient.getFactor(); - if (this._velocityGradients.length > 1) { - particle._currentVelocity2 = this._velocityGradients[1].getFactor(); - } - else { - particle._currentVelocity2 = particle._currentVelocity1; - } - } - // Limit velocity - if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) { - particle._currentLimitVelocityGradient = this._limitVelocityGradients[0]; - particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor(); - if (this._limitVelocityGradients.length > 1) { - particle._currentLimitVelocity2 = this._limitVelocityGradients[1].getFactor(); - } - else { - particle._currentLimitVelocity2 = particle._currentLimitVelocity1; - } - } - // Drag - if (this._dragGradients && this._dragGradients.length > 0) { - particle._currentDragGradient = this._dragGradients[0]; - particle._currentDrag1 = particle._currentDragGradient.getFactor(); - if (this._dragGradients.length > 1) { - particle._currentDrag2 = this._dragGradients[1].getFactor(); - } - else { - particle._currentDrag2 = particle._currentDrag1; - } - } - // Color - if (!this._colorGradients || this._colorGradients.length === 0) { - const step = math_scalar_Scalar.RandomRange(0, 1.0); - math_color_Color4.LerpToRef(this.color1, this.color2, step, particle.color); - this.colorDead.subtractToRef(particle.color, this._colorDiff); - this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep); - } - else { - particle._currentColorGradient = this._colorGradients[0]; - particle._currentColorGradient.getColorToRef(particle.color); - particle._currentColor1.copyFrom(particle.color); - if (this._colorGradients.length > 1) { - this._colorGradients[1].getColorToRef(particle._currentColor2); - } - else { - particle._currentColor2.copyFrom(particle.color); - } - } - // Sheet - if (this._isAnimationSheetEnabled) { - particle._initialStartSpriteCellID = this.startSpriteCellID; - particle._initialEndSpriteCellID = this.endSpriteCellID; - particle._initialSpriteCellLoop = this.spriteCellLoop; - } - // Inherited Velocity - particle.direction.addInPlace(this._inheritedVelocityOffset); - // Ramp - if (this._useRampGradients) { - particle.remapData = new math_vector_Vector4(0, 1, 0, 1); - } - // Noise texture coordinates - if (this.noiseTexture) { - if (particle._randomNoiseCoordinates1) { - particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random()); - particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random()); - } - else { - particle._randomNoiseCoordinates1 = new math_vector_Vector3(Math.random(), Math.random(), Math.random()); - particle._randomNoiseCoordinates2 = new math_vector_Vector3(Math.random(), Math.random(), Math.random()); - } - } - // Update the position of the attached sub-emitters to match their attached particle - particle._inheritParticleInfoToSubEmitters(); - } - } - /** - * @internal - */ - static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false, useRampGradients = false) { - const attributeNamesOrOptions = [buffer_VertexBuffer.PositionKind, buffer_VertexBuffer.ColorKind, "angle", "offset", "size"]; - if (isAnimationSheetEnabled) { - attributeNamesOrOptions.push("cellIndex"); - } - if (!isBillboardBased) { - attributeNamesOrOptions.push("direction"); - } - if (useRampGradients) { - attributeNamesOrOptions.push("remapData"); - } - return attributeNamesOrOptions; - } - /** - * @internal - */ - static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false) { - const effectCreationOption = ["invView", "view", "projection", "textureMask", "translationPivot", "eyePosition"]; - addClipPlaneUniforms(effectCreationOption); - if (isAnimationSheetEnabled) { - effectCreationOption.push("particlesInfos"); - } - if (useLogarithmicDepth) { - effectCreationOption.push("logarithmicDepthConstant"); - } - return effectCreationOption; - } - /** - * Fill the defines array according to the current settings of the particle system - * @param defines Array to be updated - * @param blendMode blend mode to take into account when updating the array - */ - fillDefines(defines, blendMode) { - if (this._scene) { - prepareStringDefinesForClipPlanes(this, this._scene, defines); - } - if (this._isAnimationSheetEnabled) { - defines.push("#define ANIMATESHEET"); - } - if (this.useLogarithmicDepth) { - defines.push("#define LOGARITHMICDEPTH"); - } - if (blendMode === particleSystem_ParticleSystem.BLENDMODE_MULTIPLY) { - defines.push("#define BLENDMULTIPLYMODE"); - } - if (this._useRampGradients) { - defines.push("#define RAMPGRADIENT"); - } - if (this._isBillboardBased) { - defines.push("#define BILLBOARD"); - switch (this.billboardMode) { - case particleSystem_ParticleSystem.BILLBOARDMODE_Y: - defines.push("#define BILLBOARDY"); - break; - case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED: - case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL: - defines.push("#define BILLBOARDSTRETCHED"); - if (this.billboardMode === particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) { - defines.push("#define BILLBOARDSTRETCHED_LOCAL"); - } - break; - case particleSystem_ParticleSystem.BILLBOARDMODE_ALL: - defines.push("#define BILLBOARDMODE_ALL"); - break; - default: - break; - } - } - if (this._imageProcessingConfiguration) { - this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines); - defines.push(this._imageProcessingConfigurationDefines.toString()); - } - } - /** - * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system - * @param uniforms Uniforms array to fill - * @param attributes Attributes array to fill - * @param samplers Samplers array to fill - */ - fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) { - attributes.push(...particleSystem_ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED && this.billboardMode !== particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL, this._useRampGradients)); - uniforms.push(...particleSystem_ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth)); - samplers.push("diffuseSampler", "rampSampler"); - if (this._imageProcessingConfiguration) { - ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines); - ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines); - } - } - /** - * @internal - */ - _getWrapper(blendMode) { - const customWrapper = this._getCustomDrawWrapper(blendMode); - if (customWrapper === null || customWrapper === void 0 ? void 0 : customWrapper.effect) { - return customWrapper; - } - const defines = []; - this.fillDefines(defines, blendMode); - // Effect - const currentRenderPassId = this._engine._features.supportRenderPasses ? this._engine.currentRenderPassId : 0; - let drawWrappers = this._drawWrappers[currentRenderPassId]; - if (!drawWrappers) { - drawWrappers = this._drawWrappers[currentRenderPassId] = []; - } - let drawWrapper = drawWrappers[blendMode]; - if (!drawWrapper) { - drawWrapper = new drawWrapper_DrawWrapper(this._engine); - if (drawWrapper.drawContext) { - drawWrapper.drawContext.useInstancing = this._useInstancing; - } - drawWrappers[blendMode] = drawWrapper; - } - const join = defines.join("\n"); - if (drawWrapper.defines !== join) { - const attributesNamesOrOptions = []; - const effectCreationOption = []; - const samplers = []; - this.fillUniformsAttributesAndSamplerNames(effectCreationOption, attributesNamesOrOptions, samplers); - drawWrapper.setEffect(this._engine.createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join), join); - } - return drawWrapper; - } - /** - * Animates the particle system for the current frame by emitting new particles and or animating the living ones. - * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false) - */ - animate(preWarmOnly = false) { - var _a; - if (!this._started) { - return; - } - if (!preWarmOnly && this._scene) { - // Check - if (!this.isReady()) { - return; - } - if (this._currentRenderId === this._scene.getFrameId()) { - return; - } - this._currentRenderId = this._scene.getFrameId(); - } - this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : ((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getAnimationRatio()) || 1); - // Determine the number of particles we need to create - let newParticles; - if (this.manualEmitCount > -1) { - newParticles = this.manualEmitCount; - this._newPartsExcess = 0; - this.manualEmitCount = 0; - } - else { - let rate = this.emitRate; - if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) { - const ratio = this._actualFrame / this.targetStopDuration; - GradientHelper.GetCurrentGradient(ratio, this._emitRateGradients, (currentGradient, nextGradient, scale) => { - if (currentGradient !== this._currentEmitRateGradient) { - this._currentEmitRate1 = this._currentEmitRate2; - this._currentEmitRate2 = nextGradient.getFactor(); - this._currentEmitRateGradient = currentGradient; - } - rate = math_scalar_Scalar.Lerp(this._currentEmitRate1, this._currentEmitRate2, scale); - }); - } - newParticles = (rate * this._scaledUpdateSpeed) >> 0; - this._newPartsExcess += rate * this._scaledUpdateSpeed - newParticles; - } - if (this._newPartsExcess > 1.0) { - newParticles += this._newPartsExcess >> 0; - this._newPartsExcess -= this._newPartsExcess >> 0; - } - this._alive = false; - if (!this._stopped) { - this._actualFrame += this._scaledUpdateSpeed; - if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) { - this.stop(); - } - } - else { - newParticles = 0; - } - this._update(newParticles); - // Stopped? - if (this._stopped) { - if (!this._alive) { - this._started = false; - if (this.onAnimationEnd) { - this.onAnimationEnd(); - } - if (this.disposeOnStop && this._scene) { - this._scene._toBeDisposed.push(this); - } - } - } - if (!preWarmOnly) { - // Update VBO - let offset = 0; - for (let index = 0; index < this._particles.length; index++) { - const particle = this._particles[index]; - this._appendParticleVertices(offset, particle); - offset += this._useInstancing ? 1 : 4; - } - if (this._vertexBuffer) { - this._vertexBuffer.updateDirectly(this._vertexData, 0, this._particles.length); - } - } - if (this.manualEmitCount === 0 && this.disposeOnStop) { - this.stop(); - } - } - _appendParticleVertices(offset, particle) { - this._appendParticleVertex(offset++, particle, 0, 0); - if (!this._useInstancing) { - this._appendParticleVertex(offset++, particle, 1, 0); - this._appendParticleVertex(offset++, particle, 1, 1); - this._appendParticleVertex(offset++, particle, 0, 1); - } - } - /** - * Rebuilds the particle system. - */ - rebuild() { - var _a, _b; - if (this._engine.getCaps().vertexArrayObject) { - this._vertexArrayObject = null; - } - this._createIndexBuffer(); - (_a = this._spriteBuffer) === null || _a === void 0 ? void 0 : _a._rebuild(); - (_b = this._vertexBuffer) === null || _b === void 0 ? void 0 : _b._rebuild(); - for (const key in this._vertexBuffers) { - this._vertexBuffers[key]._rebuild(); - } - this.resetDrawCache(); - } - /** - * Is this system ready to be used/rendered - * @returns true if the system is ready - */ - isReady() { - if (!this.emitter || (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady()) || !this.particleTexture || !this.particleTexture.isReady()) { - return false; - } - if (this.blendMode !== particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD) { - if (!this._getWrapper(this.blendMode).effect.isReady()) { - return false; - } - } - else { - if (!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) { - return false; - } - if (!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_ADD).effect.isReady()) { - return false; - } - } - return true; - } - _render(blendMode) { - var _a, _b, _c, _d, _e, _f, _g, _h; - const drawWrapper = this._getWrapper(blendMode); - const effect = drawWrapper.effect; - const engine = this._engine; - // Render - engine.enableEffect(drawWrapper); - const viewMatrix = (_a = this.defaultViewMatrix) !== null && _a !== void 0 ? _a : this._scene.getViewMatrix(); - effect.setTexture("diffuseSampler", this.particleTexture); - effect.setMatrix("view", viewMatrix); - effect.setMatrix("projection", (_b = this.defaultProjectionMatrix) !== null && _b !== void 0 ? _b : this._scene.getProjectionMatrix()); - if (this._isAnimationSheetEnabled && this.particleTexture) { - const baseSize = this.particleTexture.getBaseSize(); - effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, this.spriteCellWidth / baseSize.width); - } - effect.setVector2("translationPivot", this.translationPivot); - effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a); - if (this._isBillboardBased && this._scene) { - const camera = this._scene.activeCamera; - effect.setVector3("eyePosition", camera.globalPosition); - } - if (this._rampGradientsTexture) { - if (!this._rampGradients || !this._rampGradients.length) { - this._rampGradientsTexture.dispose(); - this._rampGradientsTexture = null; - } - effect.setTexture("rampSampler", this._rampGradientsTexture); - } - const defines = effect.defines; - if (this._scene) { - bindClipPlane(effect, this, this._scene); - } - if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) { - viewMatrix.invertToRef(math_vector_TmpVectors.Matrix[0]); - effect.setMatrix("invView", math_vector_TmpVectors.Matrix[0]); - } - if (this._vertexArrayObject !== undefined) { - if ((_c = this._scene) === null || _c === void 0 ? void 0 : _c.forceWireframe) { - engine.bindBuffers(this._vertexBuffers, this._linesIndexBufferUseInstancing, effect); - } - else { - if (!this._vertexArrayObject) { - this._vertexArrayObject = this._engine.recordVertexArrayObject(this._vertexBuffers, null, effect); - } - this._engine.bindVertexArrayObject(this._vertexArrayObject, ((_d = this._scene) === null || _d === void 0 ? void 0 : _d.forceWireframe) ? this._linesIndexBufferUseInstancing : this._indexBuffer); - } - } - else { - if (!this._indexBuffer) { - // Use instancing mode - engine.bindBuffers(this._vertexBuffers, ((_e = this._scene) === null || _e === void 0 ? void 0 : _e.forceWireframe) ? this._linesIndexBufferUseInstancing : null, effect); - } - else { - engine.bindBuffers(this._vertexBuffers, ((_f = this._scene) === null || _f === void 0 ? void 0 : _f.forceWireframe) ? this._linesIndexBuffer : this._indexBuffer, effect); - } - } - // Log. depth - if (this.useLogarithmicDepth && this._scene) { - MaterialHelper.BindLogDepth(defines, effect, this._scene); - } - // image processing - if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) { - this._imageProcessingConfiguration.bind(effect); - } - // Draw order - switch (blendMode) { - case particleSystem_ParticleSystem.BLENDMODE_ADD: - engine.setAlphaMode(1); - break; - case particleSystem_ParticleSystem.BLENDMODE_ONEONE: - engine.setAlphaMode(6); - break; - case particleSystem_ParticleSystem.BLENDMODE_STANDARD: - engine.setAlphaMode(2); - break; - case particleSystem_ParticleSystem.BLENDMODE_MULTIPLY: - engine.setAlphaMode(4); - break; - } - if (this._onBeforeDrawParticlesObservable) { - this._onBeforeDrawParticlesObservable.notifyObservers(effect); - } - if (this._useInstancing) { - if ((_g = this._scene) === null || _g === void 0 ? void 0 : _g.forceWireframe) { - engine.drawElementsType(6, 0, 10, this._particles.length); - } - else { - engine.drawArraysType(7, 0, 4, this._particles.length); - } - } - else { - if ((_h = this._scene) === null || _h === void 0 ? void 0 : _h.forceWireframe) { - engine.drawElementsType(1, 0, this._particles.length * 10); - } - else { - engine.drawElementsType(0, 0, this._particles.length * 6); - } - } - return this._particles.length; - } - /** - * Renders the particle system in its current state. - * @returns the current number of particles - */ - render() { - // Check - if (!this.isReady() || !this._particles.length) { - return 0; - } - const engine = this._engine; - if (engine.setState) { - engine.setState(false); - if (this.forceDepthWrite) { - engine.setDepthWrite(true); - } - } - let outparticles = 0; - if (this.blendMode === particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD) { - outparticles = this._render(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY) + this._render(particleSystem_ParticleSystem.BLENDMODE_ADD); - } - else { - outparticles = this._render(this.blendMode); - } - this._engine.unbindInstanceAttributes(); - this._engine.setAlphaMode(0); - return outparticles; - } - /** - * Disposes the particle system and free the associated resources - * @param disposeTexture defines if the particle texture must be disposed as well (true by default) - */ - dispose(disposeTexture = true) { - this.resetDrawCache(); - if (this._vertexBuffer) { - this._vertexBuffer.dispose(); - this._vertexBuffer = null; - } - if (this._spriteBuffer) { - this._spriteBuffer.dispose(); - this._spriteBuffer = null; - } - if (this._indexBuffer) { - this._engine._releaseBuffer(this._indexBuffer); - this._indexBuffer = null; - } - if (this._linesIndexBuffer) { - this._engine._releaseBuffer(this._linesIndexBuffer); - this._linesIndexBuffer = null; - } - if (this._linesIndexBufferUseInstancing) { - this._engine._releaseBuffer(this._linesIndexBufferUseInstancing); - this._linesIndexBufferUseInstancing = null; - } - if (this._vertexArrayObject) { - this._engine.releaseVertexArrayObject(this._vertexArrayObject); - this._vertexArrayObject = null; - } - if (disposeTexture && this.particleTexture) { - this.particleTexture.dispose(); - this.particleTexture = null; - } - if (disposeTexture && this.noiseTexture) { - this.noiseTexture.dispose(); - this.noiseTexture = null; - } - if (this._rampGradientsTexture) { - this._rampGradientsTexture.dispose(); - this._rampGradientsTexture = null; - } - this._removeFromRoot(); - if (this.subEmitters && !this._subEmitters) { - this._prepareSubEmitterInternalArray(); - } - if (this._subEmitters && this._subEmitters.length) { - for (let index = 0; index < this._subEmitters.length; index++) { - for (const subEmitter of this._subEmitters[index]) { - subEmitter.dispose(); - } - } - this._subEmitters = []; - this.subEmitters = []; - } - if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) { - this.emitter.dispose(true); - } - if (this._onBeforeDrawParticlesObservable) { - this._onBeforeDrawParticlesObservable.clear(); - } - // Remove from scene - if (this._scene) { - const index = this._scene.particleSystems.indexOf(this); - if (index > -1) { - this._scene.particleSystems.splice(index, 1); - } - this._scene._activeParticleSystems.dispose(); - } - // Callback - this.onDisposeObservable.notifyObservers(this); - this.onDisposeObservable.clear(); - this.onStoppedObservable.clear(); - this.reset(); - } - // Clone - /** - * Clones the particle system. - * @param name The name of the cloned object - * @param newEmitter The new emitter to use - * @param cloneTexture Also clone the textures if true - * @returns the cloned particle system - */ - clone(name, newEmitter, cloneTexture = false) { - const custom = Object.assign({}, this._customWrappers); - let program = null; - const engine = this._engine; - if (engine.createEffectForParticles) { - if (this.customShader != null) { - program = this.customShader; - const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; - const effect = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines); - if (!custom[0]) { - this.setCustomEffect(effect, 0); - } - else { - custom[0].effect = effect; - } - } - } - const serialization = this.serialize(cloneTexture); - const result = particleSystem_ParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl); - result.name = name; - result.customShader = program; - result._customWrappers = custom; - if (newEmitter === undefined) { - newEmitter = this.emitter; - } - if (this.noiseTexture) { - result.noiseTexture = this.noiseTexture.clone(); - } - result.emitter = newEmitter; - if (!this.preventAutoStart) { - result.start(); - } - return result; - } - /** - * Serializes the particle system to a JSON object - * @param serializeTexture defines if the texture must be serialized as well - * @returns the JSON object - */ - serialize(serializeTexture = false) { - const serializationObject = {}; - particleSystem_ParticleSystem._Serialize(serializationObject, this, serializeTexture); - serializationObject.textureMask = this.textureMask.asArray(); - serializationObject.customShader = this.customShader; - serializationObject.preventAutoStart = this.preventAutoStart; - // SubEmitters - if (this.subEmitters) { - serializationObject.subEmitters = []; - if (!this._subEmitters) { - this._prepareSubEmitterInternalArray(); - } - for (const subs of this._subEmitters) { - const cell = []; - for (const sub of subs) { - cell.push(sub.serialize(serializeTexture)); - } - serializationObject.subEmitters.push(cell); - } - } - return serializationObject; - } - /** - * @internal - */ - static _Serialize(serializationObject, particleSystem, serializeTexture) { - serializationObject.name = particleSystem.name; - serializationObject.id = particleSystem.id; - serializationObject.capacity = particleSystem.getCapacity(); - serializationObject.disposeOnStop = particleSystem.disposeOnStop; - serializationObject.manualEmitCount = particleSystem.manualEmitCount; - // Emitter - if (particleSystem.emitter.position) { - const emitterMesh = particleSystem.emitter; - serializationObject.emitterId = emitterMesh.id; - } - else { - const emitterPosition = particleSystem.emitter; - serializationObject.emitter = emitterPosition.asArray(); - } - // Emitter - if (particleSystem.particleEmitterType) { - serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize(); - } - if (particleSystem.particleTexture) { - if (serializeTexture) { - serializationObject.texture = particleSystem.particleTexture.serialize(); - } - else { - serializationObject.textureName = particleSystem.particleTexture.name; - serializationObject.invertY = !!particleSystem.particleTexture._invertY; - } - } - serializationObject.isLocal = particleSystem.isLocal; - // Animations - decorators_SerializationHelper.AppendSerializedAnimations(particleSystem, serializationObject); - serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart; - serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom; - serializationObject.beginAnimationTo = particleSystem.beginAnimationTo; - serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop; - // Particle system - serializationObject.startDelay = particleSystem.startDelay; - serializationObject.renderingGroupId = particleSystem.renderingGroupId; - serializationObject.isBillboardBased = particleSystem.isBillboardBased; - serializationObject.billboardMode = particleSystem.billboardMode; - serializationObject.minAngularSpeed = particleSystem.minAngularSpeed; - serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed; - serializationObject.minSize = particleSystem.minSize; - serializationObject.maxSize = particleSystem.maxSize; - serializationObject.minScaleX = particleSystem.minScaleX; - serializationObject.maxScaleX = particleSystem.maxScaleX; - serializationObject.minScaleY = particleSystem.minScaleY; - serializationObject.maxScaleY = particleSystem.maxScaleY; - serializationObject.minEmitPower = particleSystem.minEmitPower; - serializationObject.maxEmitPower = particleSystem.maxEmitPower; - serializationObject.minLifeTime = particleSystem.minLifeTime; - serializationObject.maxLifeTime = particleSystem.maxLifeTime; - serializationObject.emitRate = particleSystem.emitRate; - serializationObject.gravity = particleSystem.gravity.asArray(); - serializationObject.noiseStrength = particleSystem.noiseStrength.asArray(); - serializationObject.color1 = particleSystem.color1.asArray(); - serializationObject.color2 = particleSystem.color2.asArray(); - serializationObject.colorDead = particleSystem.colorDead.asArray(); - serializationObject.updateSpeed = particleSystem.updateSpeed; - serializationObject.targetStopDuration = particleSystem.targetStopDuration; - serializationObject.blendMode = particleSystem.blendMode; - serializationObject.preWarmCycles = particleSystem.preWarmCycles; - serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset; - serializationObject.minInitialRotation = particleSystem.minInitialRotation; - serializationObject.maxInitialRotation = particleSystem.maxInitialRotation; - serializationObject.startSpriteCellID = particleSystem.startSpriteCellID; - serializationObject.spriteCellLoop = particleSystem.spriteCellLoop; - serializationObject.endSpriteCellID = particleSystem.endSpriteCellID; - serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed; - serializationObject.spriteCellWidth = particleSystem.spriteCellWidth; - serializationObject.spriteCellHeight = particleSystem.spriteCellHeight; - serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell; - serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled; - serializationObject.useLogarithmicDepth = particleSystem.useLogarithmicDepth; - const colorGradients = particleSystem.getColorGradients(); - if (colorGradients) { - serializationObject.colorGradients = []; - for (const colorGradient of colorGradients) { - const serializedGradient = { - gradient: colorGradient.gradient, - color1: colorGradient.color1.asArray(), - }; - if (colorGradient.color2) { - serializedGradient.color2 = colorGradient.color2.asArray(); - } - else { - serializedGradient.color2 = colorGradient.color1.asArray(); - } - serializationObject.colorGradients.push(serializedGradient); - } - } - const rampGradients = particleSystem.getRampGradients(); - if (rampGradients) { - serializationObject.rampGradients = []; - for (const rampGradient of rampGradients) { - const serializedGradient = { - gradient: rampGradient.gradient, - color: rampGradient.color.asArray(), - }; - serializationObject.rampGradients.push(serializedGradient); - } - serializationObject.useRampGradients = particleSystem.useRampGradients; - } - const colorRemapGradients = particleSystem.getColorRemapGradients(); - if (colorRemapGradients) { - serializationObject.colorRemapGradients = []; - for (const colorRemapGradient of colorRemapGradients) { - const serializedGradient = { - gradient: colorRemapGradient.gradient, - factor1: colorRemapGradient.factor1, - }; - if (colorRemapGradient.factor2 !== undefined) { - serializedGradient.factor2 = colorRemapGradient.factor2; - } - else { - serializedGradient.factor2 = colorRemapGradient.factor1; - } - serializationObject.colorRemapGradients.push(serializedGradient); - } - } - const alphaRemapGradients = particleSystem.getAlphaRemapGradients(); - if (alphaRemapGradients) { - serializationObject.alphaRemapGradients = []; - for (const alphaRemapGradient of alphaRemapGradients) { - const serializedGradient = { - gradient: alphaRemapGradient.gradient, - factor1: alphaRemapGradient.factor1, - }; - if (alphaRemapGradient.factor2 !== undefined) { - serializedGradient.factor2 = alphaRemapGradient.factor2; - } - else { - serializedGradient.factor2 = alphaRemapGradient.factor1; - } - serializationObject.alphaRemapGradients.push(serializedGradient); - } - } - const sizeGradients = particleSystem.getSizeGradients(); - if (sizeGradients) { - serializationObject.sizeGradients = []; - for (const sizeGradient of sizeGradients) { - const serializedGradient = { - gradient: sizeGradient.gradient, - factor1: sizeGradient.factor1, - }; - if (sizeGradient.factor2 !== undefined) { - serializedGradient.factor2 = sizeGradient.factor2; - } - else { - serializedGradient.factor2 = sizeGradient.factor1; - } - serializationObject.sizeGradients.push(serializedGradient); - } - } - const angularSpeedGradients = particleSystem.getAngularSpeedGradients(); - if (angularSpeedGradients) { - serializationObject.angularSpeedGradients = []; - for (const angularSpeedGradient of angularSpeedGradients) { - const serializedGradient = { - gradient: angularSpeedGradient.gradient, - factor1: angularSpeedGradient.factor1, - }; - if (angularSpeedGradient.factor2 !== undefined) { - serializedGradient.factor2 = angularSpeedGradient.factor2; - } - else { - serializedGradient.factor2 = angularSpeedGradient.factor1; - } - serializationObject.angularSpeedGradients.push(serializedGradient); - } - } - const velocityGradients = particleSystem.getVelocityGradients(); - if (velocityGradients) { - serializationObject.velocityGradients = []; - for (const velocityGradient of velocityGradients) { - const serializedGradient = { - gradient: velocityGradient.gradient, - factor1: velocityGradient.factor1, - }; - if (velocityGradient.factor2 !== undefined) { - serializedGradient.factor2 = velocityGradient.factor2; - } - else { - serializedGradient.factor2 = velocityGradient.factor1; - } - serializationObject.velocityGradients.push(serializedGradient); - } - } - const dragGradients = particleSystem.getDragGradients(); - if (dragGradients) { - serializationObject.dragGradients = []; - for (const dragGradient of dragGradients) { - const serializedGradient = { - gradient: dragGradient.gradient, - factor1: dragGradient.factor1, - }; - if (dragGradient.factor2 !== undefined) { - serializedGradient.factor2 = dragGradient.factor2; - } - else { - serializedGradient.factor2 = dragGradient.factor1; - } - serializationObject.dragGradients.push(serializedGradient); - } - } - const emitRateGradients = particleSystem.getEmitRateGradients(); - if (emitRateGradients) { - serializationObject.emitRateGradients = []; - for (const emitRateGradient of emitRateGradients) { - const serializedGradient = { - gradient: emitRateGradient.gradient, - factor1: emitRateGradient.factor1, - }; - if (emitRateGradient.factor2 !== undefined) { - serializedGradient.factor2 = emitRateGradient.factor2; - } - else { - serializedGradient.factor2 = emitRateGradient.factor1; - } - serializationObject.emitRateGradients.push(serializedGradient); - } - } - const startSizeGradients = particleSystem.getStartSizeGradients(); - if (startSizeGradients) { - serializationObject.startSizeGradients = []; - for (const startSizeGradient of startSizeGradients) { - const serializedGradient = { - gradient: startSizeGradient.gradient, - factor1: startSizeGradient.factor1, - }; - if (startSizeGradient.factor2 !== undefined) { - serializedGradient.factor2 = startSizeGradient.factor2; - } - else { - serializedGradient.factor2 = startSizeGradient.factor1; - } - serializationObject.startSizeGradients.push(serializedGradient); - } - } - const lifeTimeGradients = particleSystem.getLifeTimeGradients(); - if (lifeTimeGradients) { - serializationObject.lifeTimeGradients = []; - for (const lifeTimeGradient of lifeTimeGradients) { - const serializedGradient = { - gradient: lifeTimeGradient.gradient, - factor1: lifeTimeGradient.factor1, - }; - if (lifeTimeGradient.factor2 !== undefined) { - serializedGradient.factor2 = lifeTimeGradient.factor2; - } - else { - serializedGradient.factor2 = lifeTimeGradient.factor1; - } - serializationObject.lifeTimeGradients.push(serializedGradient); - } - } - const limitVelocityGradients = particleSystem.getLimitVelocityGradients(); - if (limitVelocityGradients) { - serializationObject.limitVelocityGradients = []; - for (const limitVelocityGradient of limitVelocityGradients) { - const serializedGradient = { - gradient: limitVelocityGradient.gradient, - factor1: limitVelocityGradient.factor1, - }; - if (limitVelocityGradient.factor2 !== undefined) { - serializedGradient.factor2 = limitVelocityGradient.factor2; - } - else { - serializedGradient.factor2 = limitVelocityGradient.factor1; - } - serializationObject.limitVelocityGradients.push(serializedGradient); - } - serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping; - } - if (particleSystem.noiseTexture) { - serializationObject.noiseTexture = particleSystem.noiseTexture.serialize(); - } - } - /** - * @internal - */ - static _Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl) { - var _a, _b, _c; - let scene; - if (sceneOrEngine instanceof ThinEngine) { - scene = null; - } - else { - scene = sceneOrEngine; - } - const internalClass = GetClass("BABYLON.Texture"); - if (internalClass && scene) { - // Texture - if (parsedParticleSystem.texture) { - particleSystem.particleTexture = internalClass.Parse(parsedParticleSystem.texture, scene, rootUrl); - } - else if (parsedParticleSystem.textureName) { - particleSystem.particleTexture = new internalClass(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true); - particleSystem.particleTexture.name = parsedParticleSystem.textureName; - } - } - // Emitter - if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) { - particleSystem.emitter = math_vector_Vector3.Zero(); - } - else if (parsedParticleSystem.emitterId && scene) { - particleSystem.emitter = scene.getLastMeshById(parsedParticleSystem.emitterId); - } - else { - particleSystem.emitter = math_vector_Vector3.FromArray(parsedParticleSystem.emitter); - } - particleSystem.isLocal = !!parsedParticleSystem.isLocal; - // Misc. - if (parsedParticleSystem.renderingGroupId !== undefined) { - particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId; - } - if (parsedParticleSystem.isBillboardBased !== undefined) { - particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased; - } - if (parsedParticleSystem.billboardMode !== undefined) { - particleSystem.billboardMode = parsedParticleSystem.billboardMode; - } - if (parsedParticleSystem.useLogarithmicDepth !== undefined) { - particleSystem.useLogarithmicDepth = parsedParticleSystem.useLogarithmicDepth; - } - // Animations - if (parsedParticleSystem.animations) { - for (let animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) { - const parsedAnimation = parsedParticleSystem.animations[animationIndex]; - const internalClass = GetClass("BABYLON.Animation"); - if (internalClass) { - particleSystem.animations.push(internalClass.Parse(parsedAnimation)); - } - } - particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart; - particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom; - particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo; - particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop; - } - if (parsedParticleSystem.autoAnimate && scene) { - scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0); - } - // Particle system - particleSystem.startDelay = parsedParticleSystem.startDelay | 0; - particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed; - particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed; - particleSystem.minSize = parsedParticleSystem.minSize; - particleSystem.maxSize = parsedParticleSystem.maxSize; - if (parsedParticleSystem.minScaleX) { - particleSystem.minScaleX = parsedParticleSystem.minScaleX; - particleSystem.maxScaleX = parsedParticleSystem.maxScaleX; - particleSystem.minScaleY = parsedParticleSystem.minScaleY; - particleSystem.maxScaleY = parsedParticleSystem.maxScaleY; - } - if (parsedParticleSystem.preWarmCycles !== undefined) { - particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles; - particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset; - } - if (parsedParticleSystem.minInitialRotation !== undefined) { - particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation; - particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation; - } - particleSystem.minLifeTime = parsedParticleSystem.minLifeTime; - particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime; - particleSystem.minEmitPower = parsedParticleSystem.minEmitPower; - particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower; - particleSystem.emitRate = parsedParticleSystem.emitRate; - particleSystem.gravity = math_vector_Vector3.FromArray(parsedParticleSystem.gravity); - if (parsedParticleSystem.noiseStrength) { - particleSystem.noiseStrength = math_vector_Vector3.FromArray(parsedParticleSystem.noiseStrength); - } - particleSystem.color1 = math_color_Color4.FromArray(parsedParticleSystem.color1); - particleSystem.color2 = math_color_Color4.FromArray(parsedParticleSystem.color2); - particleSystem.colorDead = math_color_Color4.FromArray(parsedParticleSystem.colorDead); - particleSystem.updateSpeed = parsedParticleSystem.updateSpeed; - particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration; - particleSystem.blendMode = parsedParticleSystem.blendMode; - if (parsedParticleSystem.colorGradients) { - for (const colorGradient of parsedParticleSystem.colorGradients) { - particleSystem.addColorGradient(colorGradient.gradient, math_color_Color4.FromArray(colorGradient.color1), colorGradient.color2 ? math_color_Color4.FromArray(colorGradient.color2) : undefined); - } - } - if (parsedParticleSystem.rampGradients) { - for (const rampGradient of parsedParticleSystem.rampGradients) { - particleSystem.addRampGradient(rampGradient.gradient, math_color_Color3.FromArray(rampGradient.color)); - } - particleSystem.useRampGradients = parsedParticleSystem.useRampGradients; - } - if (parsedParticleSystem.colorRemapGradients) { - for (const colorRemapGradient of parsedParticleSystem.colorRemapGradients) { - particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2); - } - } - if (parsedParticleSystem.alphaRemapGradients) { - for (const alphaRemapGradient of parsedParticleSystem.alphaRemapGradients) { - particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2); - } - } - if (parsedParticleSystem.sizeGradients) { - for (const sizeGradient of parsedParticleSystem.sizeGradients) { - particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2); - } - } - if (parsedParticleSystem.angularSpeedGradients) { - for (const angularSpeedGradient of parsedParticleSystem.angularSpeedGradients) { - particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2); - } - } - if (parsedParticleSystem.velocityGradients) { - for (const velocityGradient of parsedParticleSystem.velocityGradients) { - particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2); - } - } - if (parsedParticleSystem.dragGradients) { - for (const dragGradient of parsedParticleSystem.dragGradients) { - particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2); - } - } - if (parsedParticleSystem.emitRateGradients) { - for (const emitRateGradient of parsedParticleSystem.emitRateGradients) { - particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2); - } - } - if (parsedParticleSystem.startSizeGradients) { - for (const startSizeGradient of parsedParticleSystem.startSizeGradients) { - particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2); - } - } - if (parsedParticleSystem.lifeTimeGradients) { - for (const lifeTimeGradient of parsedParticleSystem.lifeTimeGradients) { - particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2); - } - } - if (parsedParticleSystem.limitVelocityGradients) { - for (const limitVelocityGradient of parsedParticleSystem.limitVelocityGradients) { - particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2); - } - particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping; - } - if (parsedParticleSystem.noiseTexture && scene) { - const internalClass = GetClass("BABYLON.ProceduralTexture"); - particleSystem.noiseTexture = internalClass.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl); - } - // Emitter - let emitterType; - if (parsedParticleSystem.particleEmitterType) { - switch (parsedParticleSystem.particleEmitterType.type) { - case "SphereParticleEmitter": - emitterType = new SphereParticleEmitter(); - break; - case "SphereDirectedParticleEmitter": - emitterType = new SphereDirectedParticleEmitter(); - break; - case "ConeEmitter": - case "ConeParticleEmitter": - emitterType = new ConeParticleEmitter(); - break; - case "CylinderParticleEmitter": - emitterType = new CylinderParticleEmitter(); - break; - case "CylinderDirectedParticleEmitter": - emitterType = new CylinderDirectedParticleEmitter(); - break; - case "HemisphericParticleEmitter": - emitterType = new HemisphericParticleEmitter(); - break; - case "PointParticleEmitter": - emitterType = new PointParticleEmitter(); - break; - case "MeshParticleEmitter": - emitterType = new MeshParticleEmitter(); - break; - case "BoxEmitter": - case "BoxParticleEmitter": - default: - emitterType = new BoxParticleEmitter(); - break; - } - emitterType.parse(parsedParticleSystem.particleEmitterType, scene); - } - else { - emitterType = new BoxParticleEmitter(); - emitterType.parse(parsedParticleSystem, scene); - } - particleSystem.particleEmitterType = emitterType; - // Animation sheet - particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID; - particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID; - particleSystem.spriteCellLoop = (_a = parsedParticleSystem.spriteCellLoop) !== null && _a !== void 0 ? _a : true; - particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth; - particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight; - particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed; - particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell; - particleSystem.disposeOnStop = (_b = parsedParticleSystem.disposeOnStop) !== null && _b !== void 0 ? _b : false; - particleSystem.manualEmitCount = (_c = parsedParticleSystem.manualEmitCount) !== null && _c !== void 0 ? _c : -1; - } - /** - * Parses a JSON object to create a particle system. - * @param parsedParticleSystem The JSON object to parse - * @param sceneOrEngine The scene or the engine to create the particle system in - * @param rootUrl The root url to use to load external dependencies like texture - * @param doNotStart Ignore the preventAutoStart attribute and does not start - * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) - * @returns the Parsed particle system - */ - static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) { - const name = parsedParticleSystem.name; - let custom = null; - let program = null; - let engine; - let scene; - if (sceneOrEngine instanceof ThinEngine) { - engine = sceneOrEngine; - } - else { - scene = sceneOrEngine; - engine = scene.getEngine(); - } - if (parsedParticleSystem.customShader && engine.createEffectForParticles) { - program = parsedParticleSystem.customShader; - const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; - custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines); - } - const particleSystem = new particleSystem_ParticleSystem(name, capacity || parsedParticleSystem.capacity, sceneOrEngine, custom, parsedParticleSystem.isAnimationSheetEnabled); - particleSystem.customShader = program; - particleSystem._rootUrl = rootUrl; - if (parsedParticleSystem.id) { - particleSystem.id = parsedParticleSystem.id; - } - // SubEmitters - if (parsedParticleSystem.subEmitters) { - particleSystem.subEmitters = []; - for (const cell of parsedParticleSystem.subEmitters) { - const cellArray = []; - for (const sub of cell) { - cellArray.push(SubEmitter.Parse(sub, sceneOrEngine, rootUrl)); - } - particleSystem.subEmitters.push(cellArray); - } - } - particleSystem_ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl); - if (parsedParticleSystem.textureMask) { - particleSystem.textureMask = math_color_Color4.FromArray(parsedParticleSystem.textureMask); - } - // Auto start - if (parsedParticleSystem.preventAutoStart) { - particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart; - } - if (!doNotStart && !particleSystem.preventAutoStart) { - particleSystem.start(); - } - return particleSystem; - } -} -/** - * Billboard mode will only apply to Y axis - */ -particleSystem_ParticleSystem.BILLBOARDMODE_Y = 2; -/** - * Billboard mode will apply to all axes - */ -particleSystem_ParticleSystem.BILLBOARDMODE_ALL = 7; -/** - * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction - */ -particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED = 8; -/** - * Special billboard mode where the particle will be billboard to the camera but only around the axis of the direction of particle emission - */ -particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL = 9; -SubEmitter._ParseParticleSystem = particleSystem_ParticleSystem.Parse; -//# sourceMappingURL=particleSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragmentDeclaration2.js -// Do not edit. - -const clipPlaneFragmentDeclaration2_name = "clipPlaneFragmentDeclaration2"; -const clipPlaneFragmentDeclaration2_shader = `#ifdef CLIPPLANE -in float fClipDistance; -#endif -#ifdef CLIPPLANE2 -in float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -in float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -in float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -in float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -in float fClipDistance6; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[clipPlaneFragmentDeclaration2_name] = clipPlaneFragmentDeclaration2_shader; -/** @internal */ -const clipPlaneFragmentDeclaration2 = { name: clipPlaneFragmentDeclaration2_name, shader: clipPlaneFragmentDeclaration2_shader }; -//# sourceMappingURL=clipPlaneFragmentDeclaration2.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/gpuRenderParticles.fragment.js -// Do not edit. - - - - - - - - -const gpuRenderParticles_fragment_name = "gpuRenderParticlesPixelShader"; -const gpuRenderParticles_fragment_shader = `precision highp float; -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; -#include<clipPlaneFragmentDeclaration2> -#include<imageProcessingDeclaration> -#include<logDepthDeclaration> -#include<helperFunctions> -#include<imageProcessingFunctions> -void main() { -#include<clipPlaneFragment> -vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; -#ifdef BLENDMULTIPLYMODE -float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); -#endif -#include<logDepthFragment> -#ifdef IMAGEPROCESSINGPOSTPROCESS -gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); -#else -#ifdef IMAGEPROCESSING -gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); -#endif -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[gpuRenderParticles_fragment_name] = gpuRenderParticles_fragment_shader; -/** @internal */ -const gpuRenderParticlesPixelShader = { name: gpuRenderParticles_fragment_name, shader: gpuRenderParticles_fragment_shader }; -//# sourceMappingURL=gpuRenderParticles.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertexDeclaration2.js -// Do not edit. - -const clipPlaneVertexDeclaration2_name = "clipPlaneVertexDeclaration2"; -const clipPlaneVertexDeclaration2_shader = `#ifdef CLIPPLANE -uniform vec4 vClipPlane;out float fClipDistance; -#endif -#ifdef CLIPPLANE2 -uniform vec4 vClipPlane2;out float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -uniform vec4 vClipPlane3;out float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -uniform vec4 vClipPlane4;out float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -uniform vec4 vClipPlane5;out float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -uniform vec4 vClipPlane6;out float fClipDistance6; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[clipPlaneVertexDeclaration2_name] = clipPlaneVertexDeclaration2_shader; -/** @internal */ -const clipPlaneVertexDeclaration2 = { name: clipPlaneVertexDeclaration2_name, shader: clipPlaneVertexDeclaration2_shader }; -//# sourceMappingURL=clipPlaneVertexDeclaration2.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/gpuRenderParticles.vertex.js -// Do not edit. - - - - - -const gpuRenderParticles_vertex_name = "gpuRenderParticlesVertexShader"; -const gpuRenderParticles_vertex_shader = `precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; -#ifdef LOCAL -uniform mat4 emitterWM; -#endif -attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; -#ifndef BILLBOARD -attribute vec3 initialDirection; -#endif -#ifdef BILLBOARDSTRETCHED -attribute vec3 direction; -#endif -attribute float angle; -#ifdef ANIMATESHEET -attribute float cellIndex; -#endif -attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; -#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) -uniform mat4 invView; -#endif -#include<clipPlaneVertexDeclaration2> -#include<logDepthDeclaration> -#ifdef COLORGRADIENTS -uniform sampler2D colorGradientSampler; -#else -uniform vec4 colorDead;attribute vec4 color; -#endif -#ifdef ANIMATESHEET -uniform vec3 sheetInfos; -#endif -#ifdef BILLBOARD -uniform vec3 eyePosition; -#endif -vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; -#ifdef LOCAL -return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; -#else -return (position+worldOffset)+alignedCorner; -#endif -} -#ifdef BILLBOARDSTRETCHED -vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; -#ifdef LOCAL -return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; -#else -return (position+worldOffset)+alignedCorner; -#endif -} -#endif -void main() { -#ifdef ANIMATESHEET -float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; -#else -vUV=uv; -#endif -float ratio=age/life; -#ifdef COLORGRADIENTS -vColor=texture2D(colorGradientSampler,vec2(ratio,0)); -#else -vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); -#endif -vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; -#ifdef BILLBOARD -vec4 rotatedCorner;rotatedCorner.w=0.; -#ifdef BILLBOARDY -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); -#elif defined(BILLBOARDSTRETCHED) -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); -#else -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; -#ifdef LOCAL -vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; -#else -vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; -#endif -vPositionW=(invView*viewPosition).xyz; -#endif -#else -vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); -#endif -gl_Position=projection*viewPosition; -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=vec4(vPositionW,1.0); -#endif -#include<clipPlaneVertex> -#include<logDepthVertex> -}`; -// Sideeffect -ShaderStore.ShadersStore[gpuRenderParticles_vertex_name] = gpuRenderParticles_vertex_shader; -/** @internal */ -const gpuRenderParticlesVertexShader = { name: gpuRenderParticles_vertex_name, shader: gpuRenderParticles_vertex_shader }; -//# sourceMappingURL=gpuRenderParticles.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/gpuParticleSystem.js - - - - - - - - - - - - - - - - - - - - - - -/** - * This represents a GPU particle system in Babylon - * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data - * @see https://www.babylonjs-playground.com/#PU4WYI#4 - */ -class GPUParticleSystem extends BaseParticleSystem { - /** - * Gets a boolean indicating if the GPU particles can be rendered on current browser - */ - static get IsSupported() { - if (!engineStore_EngineStore.LastCreatedEngine) { - return false; - } - const caps = engineStore_EngineStore.LastCreatedEngine.getCaps(); - return caps.supportTransformFeedbacks || caps.supportComputeShaders; - } - _createIndexBuffer() { - this._linesIndexBufferUseInstancing = this._engine.createIndexBuffer(new Uint32Array([0, 1, 1, 3, 3, 2, 2, 0, 0, 3])); - } - /** - * Gets the maximum number of particles active at the same time. - * @returns The max number of active particles. - */ - getCapacity() { - return this._capacity; - } - /** - * Gets or set the number of active particles - * The value cannot be greater than "capacity" (if it is, it will be limited to "capacity"). - */ - get maxActiveParticleCount() { - return this._maxActiveParticleCount; - } - set maxActiveParticleCount(value) { - this._maxActiveParticleCount = Math.min(value, this._capacity); - } - /** - * Gets or set the number of active particles - * @deprecated Please use maxActiveParticleCount instead. - */ - get activeParticleCount() { - return this.maxActiveParticleCount; - } - set activeParticleCount(value) { - this.maxActiveParticleCount = value; - } - /** - * Is this system ready to be used/rendered - * @returns true if the system is ready - */ - isReady() { - if (!this.emitter || (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady()) || !this.particleTexture || !this.particleTexture.isReady()) { - return false; - } - if (this.blendMode !== particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD) { - if (!this._getWrapper(this.blendMode).effect.isReady()) { - return false; - } - } - else { - if (!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) { - return false; - } - if (!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_ADD).effect.isReady()) { - return false; - } - } - if (!this._platform.isUpdateBufferCreated()) { - this._recreateUpdateEffect(); - return false; - } - return this._platform.isUpdateBufferReady(); - } - /** - * Gets if the system has been started. (Note: this will still be true after stop is called) - * @returns True if it has been started, otherwise false. - */ - isStarted() { - return this._started; - } - /** - * Gets if the system has been stopped. (Note: rendering is still happening but the system is frozen) - * @returns True if it has been stopped, otherwise false. - */ - isStopped() { - return this._stopped; - } - /** - * Gets a boolean indicating that the system is stopping - * @returns true if the system is currently stopping - */ - isStopping() { - return false; // Stop is immediate on GPU - } - /** - * Gets the number of particles active at the same time. - * @returns The number of active particles. - */ - getActiveCount() { - return this._currentActiveCount; - } - /** - * Starts the particle system and begins to emit - * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default) - */ - start(delay = this.startDelay) { - if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) { - throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set"; - } - if (delay) { - setTimeout(() => { - this.start(0); - }, delay); - return; - } - this._started = true; - this._stopped = false; - this._preWarmDone = false; - // Animations - if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) { - this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop); - } - } - /** - * Stops the particle system. - */ - stop() { - if (this._stopped) { - return; - } - this._stopped = true; - } - /** - * Remove all active particles - */ - reset() { - this._releaseBuffers(); - this._platform.releaseVertexBuffers(); - this._currentActiveCount = 0; - this._targetIndex = 0; - } - /** - * Returns the string "GPUParticleSystem" - * @returns a string containing the class name - */ - getClassName() { - return "GPUParticleSystem"; - } - /** - * Gets the custom effect used to render the particles - * @param blendMode Blend mode for which the effect should be retrieved - * @returns The effect - */ - getCustomEffect(blendMode = 0) { - var _a, _b; - return (_b = (_a = this._customWrappers[blendMode]) === null || _a === void 0 ? void 0 : _a.effect) !== null && _b !== void 0 ? _b : this._customWrappers[0].effect; - } - _getCustomDrawWrapper(blendMode = 0) { - var _a; - return (_a = this._customWrappers[blendMode]) !== null && _a !== void 0 ? _a : this._customWrappers[0]; - } - /** - * Sets the custom effect used to render the particles - * @param effect The effect to set - * @param blendMode Blend mode for which the effect should be set - */ - setCustomEffect(effect, blendMode = 0) { - this._customWrappers[blendMode] = new drawWrapper_DrawWrapper(this._engine); - this._customWrappers[blendMode].effect = effect; - } - /** - * Observable that will be called just before the particles are drawn - */ - get onBeforeDrawParticlesObservable() { - if (!this._onBeforeDrawParticlesObservable) { - this._onBeforeDrawParticlesObservable = new observable_Observable(); - } - return this._onBeforeDrawParticlesObservable; - } - /** - * Gets the name of the particle vertex shader - */ - get vertexShaderName() { - return "gpuRenderParticles"; - } - /** - * Gets the vertex buffers used by the particle system - * Should be called after render() has been called for the current frame so that the buffers returned are the ones that have been updated - * 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) - */ - get vertexBuffers() { - // We return the other buffers than those corresponding to this._targetIndex because it is assumed vertexBuffers will be called in the current frame - // after render() has been called, meaning that the buffers have already been swapped and this._targetIndex points to the buffers that will be updated - // 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 - // (and that will be the source buffers in the next frame) - return this._renderVertexBuffers[this._targetIndex ^ 1]; - } - /** - * Gets the index buffer used by the particle system (null for GPU particle systems) - */ - get indexBuffer() { - return null; - } - _removeGradientAndTexture(gradient, gradients, texture) { - super._removeGradientAndTexture(gradient, gradients, texture); - this._releaseBuffers(); - return this; - } - /** - * Adds a new color gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param color1 defines the color to affect to the specified gradient - * @returns the current particle system - */ - addColorGradient(gradient, color1) { - if (!this._colorGradients) { - this._colorGradients = []; - } - const colorGradient = new ColorGradient(gradient, color1); - this._colorGradients.push(colorGradient); - this._refreshColorGradient(true); - this._releaseBuffers(); - return this; - } - _refreshColorGradient(reorder = false) { - if (this._colorGradients) { - if (reorder) { - this._colorGradients.sort((a, b) => { - if (a.gradient < b.gradient) { - return -1; - } - else if (a.gradient > b.gradient) { - return 1; - } - return 0; - }); - } - if (this._colorGradientsTexture) { - this._colorGradientsTexture.dispose(); - this._colorGradientsTexture = null; - } - } - } - /** Force the system to rebuild all gradients that need to be resync */ - 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(); - } - /** - * Remove a specific color gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeColorGradient(gradient) { - this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture); - this._colorGradientsTexture = null; - return this; - } - /** - * Resets the draw wrappers cache - */ - resetDrawCache() { - var _a; - for (const blendMode in this._drawWrappers) { - const drawWrapper = this._drawWrappers[blendMode]; - (_a = drawWrapper.drawContext) === null || _a === void 0 ? void 0 : _a.reset(); - } - } - _addFactorGradient(factorGradients, gradient, factor) { - const valueGradient = new FactorGradient(gradient, factor); - factorGradients.push(valueGradient); - this._releaseBuffers(); - } - /** - * Adds a new size gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the size factor to affect to the specified gradient - * @returns the current particle system - */ - addSizeGradient(gradient, factor) { - if (!this._sizeGradients) { - this._sizeGradients = []; - } - this._addFactorGradient(this._sizeGradients, gradient, factor); - this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture", true); - this._releaseBuffers(); - return this; - } - /** - * Remove a specific size gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeSizeGradient(gradient) { - this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture); - this._sizeGradientsTexture = null; - return this; - } - _refreshFactorGradient(factorGradients, textureName, reorder = false) { - if (!factorGradients) { - return; - } - if (reorder) { - factorGradients.sort((a, b) => { - if (a.gradient < b.gradient) { - return -1; - } - else if (a.gradient > b.gradient) { - return 1; - } - return 0; - }); - } - const that = this; - if (that[textureName]) { - that[textureName].dispose(); - that[textureName] = null; - } - } - /** - * Adds a new angular speed gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the angular speed to affect to the specified gradient - * @returns the current particle system - */ - addAngularSpeedGradient(gradient, factor) { - if (!this._angularSpeedGradients) { - this._angularSpeedGradients = []; - } - this._addFactorGradient(this._angularSpeedGradients, gradient, factor); - this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture", true); - this._releaseBuffers(); - return this; - } - /** - * Remove a specific angular speed gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeAngularSpeedGradient(gradient) { - this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture); - this._angularSpeedGradientsTexture = null; - return this; - } - /** - * Adds a new velocity gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the velocity to affect to the specified gradient - * @returns the current particle system - */ - addVelocityGradient(gradient, factor) { - if (!this._velocityGradients) { - this._velocityGradients = []; - } - this._addFactorGradient(this._velocityGradients, gradient, factor); - this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture", true); - this._releaseBuffers(); - return this; - } - /** - * Remove a specific velocity gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeVelocityGradient(gradient) { - this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture); - this._velocityGradientsTexture = null; - return this; - } - /** - * Adds a new limit velocity gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the limit velocity value to affect to the specified gradient - * @returns the current particle system - */ - addLimitVelocityGradient(gradient, factor) { - if (!this._limitVelocityGradients) { - this._limitVelocityGradients = []; - } - this._addFactorGradient(this._limitVelocityGradients, gradient, factor); - this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture", true); - this._releaseBuffers(); - return this; - } - /** - * Remove a specific limit velocity gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeLimitVelocityGradient(gradient) { - this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture); - this._limitVelocityGradientsTexture = null; - return this; - } - /** - * Adds a new drag gradient - * @param gradient defines the gradient to use (between 0 and 1) - * @param factor defines the drag value to affect to the specified gradient - * @returns the current particle system - */ - addDragGradient(gradient, factor) { - if (!this._dragGradients) { - this._dragGradients = []; - } - this._addFactorGradient(this._dragGradients, gradient, factor); - this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture", true); - this._releaseBuffers(); - return this; - } - /** - * Remove a specific drag gradient - * @param gradient defines the gradient to remove - * @returns the current particle system - */ - removeDragGradient(gradient) { - this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture); - this._dragGradientsTexture = null; - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - addEmitRateGradient() { - // Do nothing as emit rate is not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - removeEmitRateGradient() { - // Do nothing as emit rate is not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - addStartSizeGradient() { - // Do nothing as start size is not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - removeStartSizeGradient() { - // Do nothing as start size is not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - addColorRemapGradient() { - // Do nothing as start size is not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - removeColorRemapGradient() { - // Do nothing as start size is not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - addAlphaRemapGradient() { - // Do nothing as start size is not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - removeAlphaRemapGradient() { - // Do nothing as start size is not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - addRampGradient() { - //Not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - removeRampGradient() { - //Not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the list of ramp gradients - */ - getRampGradients() { - return null; - } - /** - * Not supported by GPUParticleSystem - * Gets or sets a boolean indicating that ramp gradients must be used - * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients - */ - get useRampGradients() { - //Not supported by GPUParticleSystem - return false; - } - set useRampGradients(value) { - //Not supported by GPUParticleSystem - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - addLifeTimeGradient() { - //Not supported by GPUParticleSystem - return this; - } - /** - * Not supported by GPUParticleSystem - * @returns the current particle system - */ - removeLifeTimeGradient() { - //Not supported by GPUParticleSystem - return this; - } - /** - * Instantiates a GPU particle system. - * 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. - * @param name The name of the particle system - * @param options The options used to create the system - * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene - * @param customEffect a custom effect used to change the way particles are rendered by default - * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture - */ - constructor(name, options, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false) { - super(name); - /** - * The layer mask we are rendering the particles through. - */ - this.layerMask = 0x0fffffff; - this._accumulatedCount = 0; - this._renderVertexBuffers = []; - this._targetIndex = 0; - this._currentRenderId = -1; - this._currentRenderingCameraUniqueId = -1; - this._started = false; - this._stopped = false; - this._timeDelta = 0; - /** Indicates that the update of particles is done in the animate function (and not in render). Default: false */ - this.updateInAnimate = false; - this._actualFrame = 0; - this._rawTextureWidth = 256; - /** - * An event triggered when the system is disposed. - */ - this.onDisposeObservable = new observable_Observable(); - /** - * An event triggered when the system is stopped - */ - this.onStoppedObservable = new observable_Observable(); - /** - * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls - * to override the particles. - */ - this.forceDepthWrite = false; - this._preWarmDone = false; - /** - * Specifies if the particles are updated in emitter local space or world space. - */ - this.isLocal = false; - /** Indicates that the particle system is GPU based */ - this.isGPU = true; - /** @internal */ - this._onBeforeDrawParticlesObservable = null; - if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") { - this._scene = sceneOrEngine || engineStore_EngineStore.LastCreatedScene; - this._engine = this._scene.getEngine(); - this.uniqueId = this._scene.getUniqueId(); - this._scene.particleSystems.push(this); - } - else { - this._engine = sceneOrEngine; - this.defaultProjectionMatrix = math_vector_Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange); - } - if (this._engine.getCaps().supportComputeShaders) { - if (!GetClass("BABYLON.ComputeShaderParticleSystem")) { - throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it."); - } - this._platform = new (GetClass("BABYLON.ComputeShaderParticleSystem"))(this, this._engine); - } - else { - if (!GetClass("BABYLON.WebGL2ParticleSystem")) { - throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it."); - } - this._platform = new (GetClass("BABYLON.WebGL2ParticleSystem"))(this, this._engine); - } - this._customWrappers = { 0: new drawWrapper_DrawWrapper(this._engine) }; - this._customWrappers[0].effect = customEffect; - this._drawWrappers = { 0: new drawWrapper_DrawWrapper(this._engine) }; - if (this._drawWrappers[0].drawContext) { - this._drawWrappers[0].drawContext.useInstancing = true; - } - this._createIndexBuffer(); - // Setup the default processing configuration to the scene. - this._attachImageProcessingConfiguration(null); - options = options !== null && options !== void 0 ? options : {}; - if (!options.randomTextureSize) { - delete options.randomTextureSize; - } - const fullOptions = Object.assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options); - const optionsAsNumber = options; - if (isFinite(optionsAsNumber)) { - fullOptions.capacity = optionsAsNumber; - } - this._capacity = fullOptions.capacity; - this._maxActiveParticleCount = fullOptions.capacity; - this._currentActiveCount = 0; - this._isAnimationSheetEnabled = isAnimationSheetEnabled; - this.particleEmitterType = new BoxParticleEmitter(); - // Random data - const maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize); - let d = []; - for (let i = 0; i < maxTextureSize; ++i) { - d.push(Math.random()); - d.push(Math.random()); - d.push(Math.random()); - d.push(Math.random()); - } - this._randomTexture = new rawTexture_RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1); - this._randomTexture.name = "GPUParticleSystem_random1"; - this._randomTexture.wrapU = 1; - this._randomTexture.wrapV = 1; - d = []; - for (let i = 0; i < maxTextureSize; ++i) { - d.push(Math.random()); - d.push(Math.random()); - d.push(Math.random()); - d.push(Math.random()); - } - this._randomTexture2 = new rawTexture_RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1); - this._randomTexture2.name = "GPUParticleSystem_random2"; - this._randomTexture2.wrapU = 1; - this._randomTexture2.wrapV = 1; - this._randomTextureSize = maxTextureSize; - } - _reset() { - this._releaseBuffers(); - } - _createVertexBuffers(updateBuffer, renderBuffer, spriteSource) { - const renderVertexBuffers = {}; - renderVertexBuffers["position"] = renderBuffer.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true); - let offset = 3; - renderVertexBuffers["age"] = renderBuffer.createVertexBuffer("age", offset, 1, this._attributesStrideSize, true); - offset += 1; - renderVertexBuffers["size"] = renderBuffer.createVertexBuffer("size", offset, 3, this._attributesStrideSize, true); - offset += 3; - renderVertexBuffers["life"] = renderBuffer.createVertexBuffer("life", offset, 1, this._attributesStrideSize, true); - offset += 1; - offset += 4; // seed - if (this.billboardMode === particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED) { - renderVertexBuffers["direction"] = renderBuffer.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true); - } - offset += 3; // direction - if (this._platform.alignDataInBuffer) { - offset += 1; - } - if (this.particleEmitterType instanceof CustomParticleEmitter) { - offset += 3; - if (this._platform.alignDataInBuffer) { - offset += 1; - } - } - if (!this._colorGradientsTexture) { - renderVertexBuffers["color"] = renderBuffer.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true); - offset += 4; - } - if (!this._isBillboardBased) { - renderVertexBuffers["initialDirection"] = renderBuffer.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true); - offset += 3; - if (this._platform.alignDataInBuffer) { - offset += 1; - } - } - if (this.noiseTexture) { - renderVertexBuffers["noiseCoordinates1"] = renderBuffer.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true); - offset += 3; - if (this._platform.alignDataInBuffer) { - offset += 1; - } - renderVertexBuffers["noiseCoordinates2"] = renderBuffer.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true); - offset += 3; - if (this._platform.alignDataInBuffer) { - offset += 1; - } - } - renderVertexBuffers["angle"] = renderBuffer.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true); - if (this._angularSpeedGradientsTexture) { - offset++; - } - else { - offset += 2; - } - if (this._isAnimationSheetEnabled) { - renderVertexBuffers["cellIndex"] = renderBuffer.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true); - offset += 1; - if (this.spriteRandomStartCell) { - renderVertexBuffers["cellStartOffset"] = renderBuffer.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true); - offset += 1; - } - } - renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2); - renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2); - this._renderVertexBuffers.push(renderVertexBuffers); - this._platform.createVertexBuffers(updateBuffer, renderVertexBuffers); - this.resetDrawCache(); - } - _initialize(force = false) { - if (this._buffer0 && !force) { - return; - } - const engine = this._engine; - const data = new Array(); - this._attributesStrideSize = 21; - this._targetIndex = 0; - if (this._platform.alignDataInBuffer) { - this._attributesStrideSize += 1; - } - if (this.particleEmitterType instanceof CustomParticleEmitter) { - this._attributesStrideSize += 3; - if (this._platform.alignDataInBuffer) { - this._attributesStrideSize += 1; - } - } - if (!this.isBillboardBased) { - this._attributesStrideSize += 3; - if (this._platform.alignDataInBuffer) { - this._attributesStrideSize += 1; - } - } - if (this._colorGradientsTexture) { - this._attributesStrideSize -= 4; - } - if (this._angularSpeedGradientsTexture) { - this._attributesStrideSize -= 1; - } - if (this._isAnimationSheetEnabled) { - this._attributesStrideSize += 1; - if (this.spriteRandomStartCell) { - this._attributesStrideSize += 1; - } - } - if (this.noiseTexture) { - this._attributesStrideSize += 6; - if (this._platform.alignDataInBuffer) { - this._attributesStrideSize += 2; - } - } - if (this._platform.alignDataInBuffer) { - this._attributesStrideSize += 3 - ((this._attributesStrideSize + 3) & 3); // round to multiple of 4 - } - const usingCustomEmitter = this.particleEmitterType instanceof CustomParticleEmitter; - const tmpVector = math_vector_TmpVectors.Vector3[0]; - let offset = 0; - for (let particleIndex = 0; particleIndex < this._capacity; particleIndex++) { - // position - data.push(0.0); - data.push(0.0); - data.push(0.0); - // Age - data.push(0.0); // create the particle as a dead one to create a new one at start - // Size - data.push(0.0); - data.push(0.0); - data.push(0.0); - // life - data.push(0.0); - // Seed - data.push(Math.random()); - data.push(Math.random()); - data.push(Math.random()); - data.push(Math.random()); - // direction - if (usingCustomEmitter) { - this.particleEmitterType.particleDestinationGenerator(particleIndex, null, tmpVector); - data.push(tmpVector.x); - data.push(tmpVector.y); - data.push(tmpVector.z); - } - else { - data.push(0.0); - data.push(0.0); - data.push(0.0); - } - if (this._platform.alignDataInBuffer) { - data.push(0.0); // dummy0 - } - offset += 16; // position, age, size, life, seed, direction, dummy0 - if (usingCustomEmitter) { - this.particleEmitterType.particlePositionGenerator(particleIndex, null, tmpVector); - data.push(tmpVector.x); - data.push(tmpVector.y); - data.push(tmpVector.z); - if (this._platform.alignDataInBuffer) { - data.push(0.0); // dummy1 - } - offset += 4; - } - if (!this._colorGradientsTexture) { - // color - data.push(0.0); - data.push(0.0); - data.push(0.0); - data.push(0.0); - offset += 4; - } - if (!this.isBillboardBased) { - // initialDirection - data.push(0.0); - data.push(0.0); - data.push(0.0); - if (this._platform.alignDataInBuffer) { - data.push(0.0); // dummy2 - } - offset += 4; - } - if (this.noiseTexture) { - // Random coordinates for reading into noise texture - data.push(Math.random()); - data.push(Math.random()); - data.push(Math.random()); - if (this._platform.alignDataInBuffer) { - data.push(0.0); // dummy3 - } - data.push(Math.random()); - data.push(Math.random()); - data.push(Math.random()); - if (this._platform.alignDataInBuffer) { - data.push(0.0); // dummy4 - } - offset += 8; - } - // angle - data.push(0.0); - offset += 1; - if (!this._angularSpeedGradientsTexture) { - data.push(0.0); - offset += 1; - } - if (this._isAnimationSheetEnabled) { - data.push(0.0); - offset += 1; - if (this.spriteRandomStartCell) { - data.push(0.0); - offset += 1; - } - } - if (this._platform.alignDataInBuffer) { - let numDummies = 3 - ((offset + 3) & 3); - offset += numDummies; - while (numDummies-- > 0) { - data.push(0.0); - } - } - } - // Sprite data - 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]); - const bufferData1 = this._platform.createParticleBuffer(data); - const bufferData2 = this._platform.createParticleBuffer(data); - // Buffers - this._buffer0 = new Buffer(engine, bufferData1, false, this._attributesStrideSize); - this._buffer1 = new Buffer(engine, bufferData2, false, this._attributesStrideSize); - this._spriteBuffer = new Buffer(engine, spriteData, false, 4); - // Update & Render vertex buffers - this._renderVertexBuffers = []; - this._createVertexBuffers(this._buffer0, this._buffer1, this._spriteBuffer); - this._createVertexBuffers(this._buffer1, this._buffer0, this._spriteBuffer); - // Links - this._sourceBuffer = this._buffer0; - this._targetBuffer = this._buffer1; - } - /** @internal */ - _recreateUpdateEffect() { - this._createColorGradientTexture(); - this._createSizeGradientTexture(); - this._createAngularSpeedGradientTexture(); - this._createVelocityGradientTexture(); - this._createLimitVelocityGradientTexture(); - this._createDragGradientTexture(); - let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : ""; - if (this._isBillboardBased) { - defines += "\n#define BILLBOARD"; - } - if (this._colorGradientsTexture) { - defines += "\n#define COLORGRADIENTS"; - } - if (this._sizeGradientsTexture) { - defines += "\n#define SIZEGRADIENTS"; - } - if (this._angularSpeedGradientsTexture) { - defines += "\n#define ANGULARSPEEDGRADIENTS"; - } - if (this._velocityGradientsTexture) { - defines += "\n#define VELOCITYGRADIENTS"; - } - if (this._limitVelocityGradientsTexture) { - defines += "\n#define LIMITVELOCITYGRADIENTS"; - } - if (this._dragGradientsTexture) { - defines += "\n#define DRAGGRADIENTS"; - } - if (this.isAnimationSheetEnabled) { - defines += "\n#define ANIMATESHEET"; - if (this.spriteRandomStartCell) { - defines += "\n#define ANIMATESHEETRANDOMSTART"; - } - } - if (this.noiseTexture) { - defines += "\n#define NOISE"; - } - if (this.isLocal) { - defines += "\n#define LOCAL"; - } - if (this._platform.isUpdateBufferCreated() && this._cachedUpdateDefines === defines) { - return true; - } - this._cachedUpdateDefines = defines; - this._updateBuffer = this._platform.createUpdateBuffer(defines); - return this._platform.isUpdateBufferReady(); - } - /** - * @internal - */ - _getWrapper(blendMode) { - const customWrapper = this._getCustomDrawWrapper(blendMode); - if (customWrapper === null || customWrapper === void 0 ? void 0 : customWrapper.effect) { - return customWrapper; - } - const defines = []; - this.fillDefines(defines, blendMode); - // Effect - let drawWrapper = this._drawWrappers[blendMode]; - if (!drawWrapper) { - drawWrapper = new drawWrapper_DrawWrapper(this._engine); - if (drawWrapper.drawContext) { - drawWrapper.drawContext.useInstancing = true; - } - this._drawWrappers[blendMode] = drawWrapper; - } - const join = defines.join("\n"); - if (drawWrapper.defines !== join) { - const attributes = []; - const uniforms = []; - const samplers = []; - this.fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers); - drawWrapper.setEffect(this._engine.createEffect("gpuRenderParticles", attributes, uniforms, samplers, join), join); - } - return drawWrapper; - } - /** - * @internal - */ - static _GetAttributeNamesOrOptions(hasColorGradients = false, isAnimationSheetEnabled = false, isBillboardBased = false, isBillboardStretched = false) { - const attributeNamesOrOptions = [buffer_VertexBuffer.PositionKind, "age", "life", "size", "angle"]; - if (!hasColorGradients) { - attributeNamesOrOptions.push(buffer_VertexBuffer.ColorKind); - } - if (isAnimationSheetEnabled) { - attributeNamesOrOptions.push("cellIndex"); - } - if (!isBillboardBased) { - attributeNamesOrOptions.push("initialDirection"); - } - if (isBillboardStretched) { - attributeNamesOrOptions.push("direction"); - } - attributeNamesOrOptions.push("offset", buffer_VertexBuffer.UVKind); - return attributeNamesOrOptions; - } - /** - * @internal - */ - static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false) { - const effectCreationOption = ["emitterWM", "worldOffset", "view", "projection", "colorDead", "invView", "translationPivot", "eyePosition"]; - addClipPlaneUniforms(effectCreationOption); - if (isAnimationSheetEnabled) { - effectCreationOption.push("sheetInfos"); - } - if (useLogarithmicDepth) { - effectCreationOption.push("logarithmicDepthConstant"); - } - return effectCreationOption; - } - /** - * Fill the defines array according to the current settings of the particle system - * @param defines Array to be updated - * @param blendMode blend mode to take into account when updating the array - */ - fillDefines(defines, blendMode = 0) { - if (this._scene) { - prepareStringDefinesForClipPlanes(this, this._scene, defines); - } - if (blendMode === particleSystem_ParticleSystem.BLENDMODE_MULTIPLY) { - defines.push("#define BLENDMULTIPLYMODE"); - } - if (this.isLocal) { - defines.push("#define LOCAL"); - } - if (this.useLogarithmicDepth) { - defines.push("#define LOGARITHMICDEPTH"); - } - if (this._isBillboardBased) { - defines.push("#define BILLBOARD"); - switch (this.billboardMode) { - case particleSystem_ParticleSystem.BILLBOARDMODE_Y: - defines.push("#define BILLBOARDY"); - break; - case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED: - defines.push("#define BILLBOARDSTRETCHED"); - break; - case particleSystem_ParticleSystem.BILLBOARDMODE_ALL: - defines.push("#define BILLBOARDMODE_ALL"); - break; - default: - break; - } - } - if (this._colorGradientsTexture) { - defines.push("#define COLORGRADIENTS"); - } - if (this.isAnimationSheetEnabled) { - defines.push("#define ANIMATESHEET"); - } - if (this._imageProcessingConfiguration) { - this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines); - defines.push("" + this._imageProcessingConfigurationDefines.toString()); - } - } - /** - * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system - * @param uniforms Uniforms array to fill - * @param attributes Attributes array to fill - * @param samplers Samplers array to fill - */ - fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) { - attributes.push(...GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture, this._isAnimationSheetEnabled, this._isBillboardBased, this._isBillboardBased && this.billboardMode === particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED)); - uniforms.push(...GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth)); - samplers.push("diffuseSampler", "colorGradientSampler"); - if (this._imageProcessingConfiguration) { - ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines); - ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines); - } - } - /** - * Animates the particle system for the current frame by emitting new particles and or animating the living ones. - * @param preWarm defines if we are in the pre-warmimg phase - */ - animate(preWarm = false) { - var _a; - this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : ((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getAnimationRatio()) || 1); - this._actualFrame += this._timeDelta; - if (!this._stopped) { - if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) { - this.stop(); - } - } - if (this.updateInAnimate) { - this._update(); - } - } - _createFactorGradientTexture(factorGradients, textureName) { - const texture = this[textureName]; - if (!factorGradients || !factorGradients.length || texture) { - return; - } - const data = new Float32Array(this._rawTextureWidth); - for (let x = 0; x < this._rawTextureWidth; x++) { - const ratio = x / this._rawTextureWidth; - GradientHelper.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => { - data[x] = math_scalar_Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale); - }); - } - this[textureName] = rawTexture_RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene || this._engine, false, false, 1); - this[textureName].name = textureName.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 data = new Uint8Array(this._rawTextureWidth * 4); - const tmpColor = TmpColors.Color4[0]; - for (let x = 0; x < this._rawTextureWidth; x++) { - const ratio = x / this._rawTextureWidth; - GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => { - math_color_Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor); - data[x * 4] = tmpColor.r * 255; - data[x * 4 + 1] = tmpColor.g * 255; - data[x * 4 + 2] = tmpColor.b * 255; - data[x * 4 + 3] = tmpColor.a * 255; - }); - } - this._colorGradientsTexture = rawTexture_RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1); - this._colorGradientsTexture.name = "colorGradients"; - } - _render(blendMode, emitterWM) { - var _a, _b, _c, _d, _e; - // Enable render effect - const drawWrapper = this._getWrapper(blendMode); - const effect = drawWrapper.effect; - this._engine.enableEffect(drawWrapper); - const viewMatrix = ((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getViewMatrix()) || math_vector_Matrix.IdentityReadOnly; - effect.setMatrix("view", viewMatrix); - effect.setMatrix("projection", (_b = this.defaultProjectionMatrix) !== null && _b !== void 0 ? _b : this._scene.getProjectionMatrix()); - effect.setTexture("diffuseSampler", this.particleTexture); - effect.setVector2("translationPivot", this.translationPivot); - effect.setVector3("worldOffset", this.worldOffset); - if (this.isLocal) { - effect.setMatrix("emitterWM", emitterWM); - } - if (this._colorGradientsTexture) { - effect.setTexture("colorGradientSampler", this._colorGradientsTexture); - } - else { - effect.setDirectColor4("colorDead", this.colorDead); - } - if (this._isAnimationSheetEnabled && this.particleTexture) { - const baseSize = this.particleTexture.getBaseSize(); - effect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth); - } - if (this._isBillboardBased && this._scene) { - const camera = this._scene.activeCamera; - effect.setVector3("eyePosition", camera.globalPosition); - } - const defines = effect.defines; - if (this._scene) { - bindClipPlane(effect, this, this._scene); - } - if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) { - const invView = viewMatrix.clone(); - invView.invert(); - effect.setMatrix("invView", invView); - } - // Log. depth - if (this.useLogarithmicDepth && this._scene) { - MaterialHelper.BindLogDepth(defines, effect, this._scene); - } - // image processing - if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) { - this._imageProcessingConfiguration.bind(effect); - } - // Draw order - switch (blendMode) { - case particleSystem_ParticleSystem.BLENDMODE_ADD: - this._engine.setAlphaMode(1); - break; - case particleSystem_ParticleSystem.BLENDMODE_ONEONE: - this._engine.setAlphaMode(6); - break; - case particleSystem_ParticleSystem.BLENDMODE_STANDARD: - this._engine.setAlphaMode(2); - break; - case particleSystem_ParticleSystem.BLENDMODE_MULTIPLY: - this._engine.setAlphaMode(4); - break; - } - // Bind source VAO - this._platform.bindDrawBuffers(this._targetIndex, effect, ((_c = this._scene) === null || _c === void 0 ? void 0 : _c.forceWireframe) ? this._linesIndexBufferUseInstancing : null); - if (this._onBeforeDrawParticlesObservable) { - this._onBeforeDrawParticlesObservable.notifyObservers(effect); - } - // Render - if ((_d = this._scene) === null || _d === void 0 ? void 0 : _d.forceWireframe) { - this._engine.drawElementsType(6, 0, 10, this._currentActiveCount); - } - else { - this._engine.drawArraysType(7, 0, 4, this._currentActiveCount); - } - this._engine.setAlphaMode(0); - if ((_e = this._scene) === null || _e === void 0 ? void 0 : _e.forceWireframe) { - this._engine.unbindInstanceAttributes(); - } - return this._currentActiveCount; - } - /** @internal */ - _update(emitterWM) { - if (!this.emitter || !this._targetBuffer) { - return; - } - if (!this._recreateUpdateEffect()) { - return; - } - if (!emitterWM) { - if (this.emitter.position) { - const emitterMesh = this.emitter; - emitterWM = emitterMesh.getWorldMatrix(); - } - else { - const emitterPosition = this.emitter; - emitterWM = math_vector_TmpVectors.Matrix[0]; - math_vector_Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM); - } - } - 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); - if (!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); - if (this._limitVelocityGradientsTexture) { - this._updateBuffer.setFloat("limitVelocityDamping", this.limitVelocityDamping); - } - if (this.particleEmitterType) { - this.particleEmitterType.applyToShader(this._updateBuffer); - } - if (this._isAnimationSheetEnabled) { - this._updateBuffer.setFloat4("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed, this.spriteCellLoop ? 1 : 0); - } - if (this.noiseTexture) { - this._updateBuffer.setVector3("noiseStrength", this.noiseStrength); - } - if (!this.isLocal) { - this._updateBuffer.setMatrix("emitterWM", emitterWM); - } - this._platform.updateParticleBuffer(this._targetIndex, this._targetBuffer, this._currentActiveCount); - // Switch VAOs - this._targetIndex++; - if (this._targetIndex === 2) { - this._targetIndex = 0; - } - // Switch buffers - const tmpBuffer = this._sourceBuffer; - this._sourceBuffer = this._targetBuffer; - this._targetBuffer = tmpBuffer; - } - /** - * Renders the particle system in its current state - * @param preWarm defines if the system should only update the particles but not render them - * @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) - * @returns the current number of particles - */ - render(preWarm = false, forceUpdateOnly = false) { - if (!this._started) { - return 0; - } - if (!this.isReady()) { - return 0; - } - if (!preWarm && this._scene) { - if (!this._preWarmDone && this.preWarmCycles) { - for (let index = 0; index < this.preWarmCycles; index++) { - this.animate(true); - this.render(true, true); - } - this._preWarmDone = true; - } - if (this._currentRenderId === this._scene.getRenderId() && - (!this._scene.activeCamera || (this._scene.activeCamera && this._currentRenderingCameraUniqueId === this._scene.activeCamera.uniqueId))) { - return 0; - } - this._currentRenderId = this._scene.getRenderId(); - if (this._scene.activeCamera) { - this._currentRenderingCameraUniqueId = this._scene.activeCamera.uniqueId; - } - } - // Get everything ready to render - this._initialize(); - this._accumulatedCount += this.emitRate * this._timeDelta; - if (this._accumulatedCount > 1) { - const intPart = this._accumulatedCount | 0; - this._accumulatedCount -= intPart; - this._currentActiveCount += intPart; - } - this._currentActiveCount = Math.min(this._maxActiveParticleCount, this._currentActiveCount); - if (!this._currentActiveCount) { - return 0; - } - // Enable update effect - let emitterWM; - if (this.emitter.position) { - const emitterMesh = this.emitter; - emitterWM = emitterMesh.getWorldMatrix(); - } - else { - const emitterPosition = this.emitter; - emitterWM = math_vector_TmpVectors.Matrix[0]; - math_vector_Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM); - } - const engine = this._engine; - if (!this.updateInAnimate) { - this._update(emitterWM); - } - let outparticles = 0; - if (!preWarm && !forceUpdateOnly) { - engine.setState(false); - if (this.forceDepthWrite) { - engine.setDepthWrite(true); - } - if (this.blendMode === particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD) { - outparticles = this._render(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY, emitterWM) + this._render(particleSystem_ParticleSystem.BLENDMODE_ADD, emitterWM); - } - else { - outparticles = this._render(this.blendMode, emitterWM); - } - this._engine.setAlphaMode(0); - } - return outparticles; - } - /** - * Rebuilds the particle system - */ - rebuild() { - const checkUpdateEffect = () => { - if (!this._recreateUpdateEffect() || !this._platform.isUpdateBufferReady()) { - setTimeout(checkUpdateEffect, 10); - } - else { - this._initialize(true); - } - }; - this._createIndexBuffer(); - this._cachedUpdateDefines = ""; - this._platform.contextLost(); - checkUpdateEffect(); - } - _releaseBuffers() { - if (this._buffer0) { - this._buffer0.dispose(); - this._buffer0 = null; - } - if (this._buffer1) { - this._buffer1.dispose(); - this._buffer1 = null; - } - if (this._spriteBuffer) { - this._spriteBuffer.dispose(); - this._spriteBuffer = null; - } - this._platform.releaseBuffers(); - } - /** - * Disposes the particle system and free the associated resources - * @param disposeTexture defines if the particule texture must be disposed as well (true by default) - */ - dispose(disposeTexture = true) { - for (const blendMode in this._drawWrappers) { - const drawWrapper = this._drawWrappers[blendMode]; - drawWrapper.dispose(); - } - this._drawWrappers = {}; - if (this._scene) { - const index = this._scene.particleSystems.indexOf(this); - if (index > -1) { - this._scene.particleSystems.splice(index, 1); - } - } - this._releaseBuffers(); - this._platform.releaseVertexBuffers(); - for (let i = 0; i < this._renderVertexBuffers.length; ++i) { - const rvb = this._renderVertexBuffers[i]; - for (const key in rvb) { - rvb[key].dispose(); - } - } - this._renderVertexBuffers = []; - if (this._colorGradientsTexture) { - this._colorGradientsTexture.dispose(); - this._colorGradientsTexture = null; - } - if (this._sizeGradientsTexture) { - this._sizeGradientsTexture.dispose(); - this._sizeGradientsTexture = null; - } - if (this._angularSpeedGradientsTexture) { - this._angularSpeedGradientsTexture.dispose(); - this._angularSpeedGradientsTexture = null; - } - if (this._velocityGradientsTexture) { - this._velocityGradientsTexture.dispose(); - this._velocityGradientsTexture = null; - } - if (this._limitVelocityGradientsTexture) { - this._limitVelocityGradientsTexture.dispose(); - this._limitVelocityGradientsTexture = null; - } - if (this._dragGradientsTexture) { - this._dragGradientsTexture.dispose(); - this._dragGradientsTexture = null; - } - if (this._randomTexture) { - this._randomTexture.dispose(); - this._randomTexture = null; - } - if (this._randomTexture2) { - this._randomTexture2.dispose(); - this._randomTexture2 = null; - } - if (disposeTexture && this.particleTexture) { - this.particleTexture.dispose(); - this.particleTexture = null; - } - if (disposeTexture && this.noiseTexture) { - this.noiseTexture.dispose(); - this.noiseTexture = null; - } - // Callback - this.onStoppedObservable.clear(); - this.onDisposeObservable.notifyObservers(this); - this.onDisposeObservable.clear(); - } - /** - * Clones the particle system. - * @param name The name of the cloned object - * @param newEmitter The new emitter to use - * @param cloneTexture Also clone the textures if true - * @returns the cloned particle system - */ - clone(name, newEmitter, cloneTexture = false) { - const custom = Object.assign({}, this._customWrappers); - let program = null; - const engine = this._engine; - if (engine.createEffectForParticles) { - if (this.customShader != null) { - program = this.customShader; - const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; - custom[0] = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, this); - } - } - const serialization = this.serialize(cloneTexture); - const result = GPUParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl); - result.name = name; - result.customShader = program; - result._customWrappers = custom; - if (newEmitter === undefined) { - newEmitter = this.emitter; - } - if (this.noiseTexture) { - result.noiseTexture = this.noiseTexture.clone(); - } - result.emitter = newEmitter; - return result; - } - /** - * Serializes the particle system to a JSON object - * @param serializeTexture defines if the texture must be serialized as well - * @returns the JSON object - */ - serialize(serializeTexture = false) { - const serializationObject = {}; - particleSystem_ParticleSystem._Serialize(serializationObject, this, serializeTexture); - serializationObject.activeParticleCount = this.activeParticleCount; - serializationObject.randomTextureSize = this._randomTextureSize; - serializationObject.customShader = this.customShader; - return serializationObject; - } - /** - * Parses a JSON object to create a GPU particle system. - * @param parsedParticleSystem The JSON object to parse - * @param sceneOrEngine The scene or the engine to create the particle system in - * @param rootUrl The root url to use to load external dependencies like texture - * @param doNotStart Ignore the preventAutoStart attribute and does not start - * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) - * @returns the parsed GPU particle system - */ - static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) { - const name = parsedParticleSystem.name; - let engine; - let scene; - if (sceneOrEngine instanceof ThinEngine) { - engine = sceneOrEngine; - } - else { - scene = sceneOrEngine; - engine = scene.getEngine(); - } - const particleSystem = new GPUParticleSystem(name, { capacity: capacity || parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, sceneOrEngine, null, parsedParticleSystem.isAnimationSheetEnabled); - particleSystem._rootUrl = rootUrl; - if (parsedParticleSystem.customShader && engine.createEffectForParticles) { - const program = parsedParticleSystem.customShader; - const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; - const custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, particleSystem); - particleSystem.setCustomEffect(custom, 0); - particleSystem.customShader = program; - } - if (parsedParticleSystem.id) { - particleSystem.id = parsedParticleSystem.id; - } - if (parsedParticleSystem.activeParticleCount) { - particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount; - } - particleSystem_ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl); - // Auto start - if (parsedParticleSystem.preventAutoStart) { - particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart; - } - if (!doNotStart && !particleSystem.preventAutoStart) { - particleSystem.start(); - } - return particleSystem; - } -} -//# sourceMappingURL=gpuParticleSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/IParticleSystem.js - -//# sourceMappingURL=IParticleSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/particleSystemSet.js - - - - - - -/** Internal class used to store shapes for emitters */ -class ParticleSystemSetEmitterCreationOptions { -} -/** - * Represents a set of particle systems working together to create a specific effect - */ -class ParticleSystemSet { - constructor() { - this._emitterNodeIsOwned = true; - /** - * Gets the particle system list - */ - this.systems = new Array(); - } - /** - * Gets or sets the emitter node used with this set - */ - get emitterNode() { - return this._emitterNode; - } - set emitterNode(value) { - if (this._emitterNodeIsOwned && this._emitterNode) { - if (this._emitterNode.dispose) { - this._emitterNode.dispose(); - } - this._emitterNodeIsOwned = false; - } - for (const system of this.systems) { - system.emitter = value; - } - this._emitterNode = value; - } - /** - * Creates a new emitter mesh as a sphere - * @param options defines the options used to create the sphere - * @param options.diameter - * @param options.segments - * @param options.color - * @param renderingGroupId defines the renderingGroupId to use for the sphere - * @param scene defines the hosting scene - */ - setEmitterAsSphere(options, renderingGroupId, scene) { - if (this._emitterNodeIsOwned && this._emitterNode) { - if (this._emitterNode.dispose) { - this._emitterNode.dispose(); - } - } - this._emitterNodeIsOwned = true; - this._emitterCreationOptions = { - kind: "Sphere", - options: options, - renderingGroupId: renderingGroupId, - }; - const emitterMesh = sphereBuilder_CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene); - emitterMesh.renderingGroupId = renderingGroupId; - const material = new standardMaterial_StandardMaterial("emitterSphereMaterial", scene); - material.emissiveColor = options.color; - emitterMesh.material = material; - for (const system of this.systems) { - system.emitter = emitterMesh; - } - this._emitterNode = emitterMesh; - } - /** - * Starts all particle systems of the set - * @param emitter defines an optional mesh to use as emitter for the particle systems - */ - start(emitter) { - for (const system of this.systems) { - if (emitter) { - system.emitter = emitter; - } - system.start(); - } - } - /** - * Release all associated resources - */ - dispose() { - for (const system of this.systems) { - system.dispose(); - } - this.systems.length = 0; - if (this._emitterNode) { - if (this._emitterNode.dispose) { - this._emitterNode.dispose(); - } - this._emitterNode = null; - } - } - /** - * Serialize the set into a JSON compatible object - * @param serializeTexture defines if the texture must be serialized as well - * @returns a JSON compatible representation of the set - */ - serialize(serializeTexture = false) { - const result = {}; - result.systems = []; - for (const system of this.systems) { - result.systems.push(system.serialize(serializeTexture)); - } - if (this._emitterNode) { - result.emitter = this._emitterCreationOptions; - } - return result; - } - /** - * Parse a new ParticleSystemSet from a serialized source - * @param data defines a JSON compatible representation of the set - * @param scene defines the hosting scene - * @param gpu defines if we want GPU particles or CPU particles - * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) - * @returns a new ParticleSystemSet - */ - static Parse(data, scene, gpu = false, capacity) { - const result = new ParticleSystemSet(); - const rootUrl = this.BaseAssetsUrl + "/textures/"; - scene = scene || engineStore_EngineStore.LastCreatedScene; - for (const system of data.systems) { - result.systems.push(gpu ? GPUParticleSystem.Parse(system, scene, rootUrl, true, capacity) : particleSystem_ParticleSystem.Parse(system, scene, rootUrl, true, capacity)); - } - if (data.emitter) { - const options = data.emitter.options; - switch (data.emitter.kind) { - case "Sphere": - result.setEmitterAsSphere({ - diameter: options.diameter, - segments: options.segments, - color: math_color_Color3.FromArray(options.color), - }, data.emitter.renderingGroupId, scene); - break; - } - } - return result; - } -} -/** - * Gets or sets base Assets URL - */ -ParticleSystemSet.BaseAssetsUrl = "https://assets.babylonjs.com/particles"; -//# sourceMappingURL=particleSystemSet.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/particleHelper.js - - - - - - - - - -/** - * This class is made for on one-liner static method to help creating particle system set. - */ -class ParticleHelper { - /** - * Create a default particle system that you can tweak - * @param emitter defines the emitter to use - * @param capacity defines the system capacity (default is 500 particles) - * @param scene defines the hosting scene - * @param useGPU defines if a GPUParticleSystem must be created (default is false) - * @returns the new Particle system - */ - static CreateDefault(emitter, capacity = 500, scene, useGPU = false) { - let system; - if (useGPU) { - system = new GPUParticleSystem("default system", { capacity: capacity }, scene); - } - else { - system = new particleSystem_ParticleSystem("default system", capacity, scene); - } - system.emitter = emitter; - system.particleTexture = new texture_Texture("https://assets.babylonjs.com/textures/flare.png", system.getScene()); - system.createConeEmitter(0.1, Math.PI / 4); - // Particle color - system.color1 = new math_color_Color4(1.0, 1.0, 1.0, 1.0); - system.color2 = new math_color_Color4(1.0, 1.0, 1.0, 1.0); - system.colorDead = new math_color_Color4(1.0, 1.0, 1.0, 0.0); - // Particle Size - system.minSize = 0.1; - system.maxSize = 0.1; - // Emission speed - system.minEmitPower = 2; - system.maxEmitPower = 2; - // Update speed - system.updateSpeed = 1 / 60; - system.emitRate = 30; - return system; - } - /** - * This is the main static method (one-liner) of this helper to create different particle systems - * @param type This string represents the type to the particle system to create - * @param scene The scene where the particle system should live - * @param gpu If the system will use gpu - * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) - * @returns the ParticleSystemSet created - */ - static CreateAsync(type, scene, gpu = false, capacity) { - if (!scene) { - scene = engineStore_EngineStore.LastCreatedScene; - } - const token = {}; - scene.addPendingData(token); - return new Promise((resolve, reject) => { - if (gpu && !GPUParticleSystem.IsSupported) { - scene.removePendingData(token); - return reject("Particle system with GPU is not supported."); - } - tools_Tools.LoadFile(`${ParticleHelper.BaseAssetsUrl}/systems/${type}.json`, (data) => { - scene.removePendingData(token); - const newData = JSON.parse(data.toString()); - return resolve(ParticleSystemSet.Parse(newData, scene, gpu, capacity)); - }, undefined, undefined, undefined, () => { - scene.removePendingData(token); - return reject(`An error occurred with the creation of your particle system. Check if your type '${type}' exists.`); - }); - }); - } - /** - * Static function used to export a particle system to a ParticleSystemSet variable. - * Please note that the emitter shape is not exported - * @param systems defines the particle systems to export - * @returns the created particle system set - */ - static ExportSet(systems) { - const set = new ParticleSystemSet(); - for (const system of systems) { - set.systems.push(system); - } - return set; - } - /** - * Creates a particle system from a snippet saved in a remote file - * @param name defines the name of the particle system to create (can be null or empty to use the one from the json data) - * @param url defines the url to load from - * @param scene defines the hosting scene - * @param gpu If the system will use gpu - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) - * @returns a promise that will resolve to the new particle system - */ - static ParseFromFileAsync(name, url, scene, gpu = false, rootUrl = "", capacity) { - return new Promise((resolve, reject) => { - const request = new webRequest_WebRequest(); - request.addEventListener("readystatechange", () => { - if (request.readyState == 4) { - if (request.status == 200) { - const serializationObject = JSON.parse(request.responseText); - let output; - if (gpu) { - output = GPUParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity); - } - else { - output = particleSystem_ParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity); - } - if (name) { - output.name = name; - } - resolve(output); - } - else { - reject("Unable to load the particle system"); - } - } - }); - request.open("GET", url); - request.send(); - }); - } - /** - * Creates a particle system from a snippet saved by the particle system editor - * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one) - * @param scene defines the hosting scene - * @param gpu If the system will use gpu - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) - * @returns a promise that will resolve to the new particle system - */ - static ParseFromSnippetAsync(snippetId, scene, gpu = false, rootUrl = "", capacity) { - if (snippetId === "_BLANK") { - const system = this.CreateDefault(null); - system.start(); - return Promise.resolve(system); - } - return new Promise((resolve, reject) => { - const request = new webRequest_WebRequest(); - request.addEventListener("readystatechange", () => { - if (request.readyState == 4) { - if (request.status == 200) { - const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); - const serializationObject = JSON.parse(snippet.particleSystem); - let output; - if (gpu) { - output = GPUParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity); - } - else { - output = particleSystem_ParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity); - } - output.snippetId = snippetId; - resolve(output); - } - else { - reject("Unable to load the snippet " + snippetId); - } - } - }); - request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); - request.send(); - }); - } -} -/** - * Gets or sets base Assets URL - */ -ParticleHelper.BaseAssetsUrl = ParticleSystemSet.BaseAssetsUrl; -/** Define the Url to load snippets */ -ParticleHelper.SnippetUrl = `https://snippet.babylonjs.com`; -/** - * Creates a particle system from a snippet saved by the particle system editor - * @deprecated Please use ParseFromSnippetAsync instead - * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one) - * @param scene defines the hosting scene - * @param gpu If the system will use gpu - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) - * @returns a promise that will resolve to the new particle system - */ -ParticleHelper.CreateFromSnippetAsync = ParticleHelper.ParseFromSnippetAsync; -//# sourceMappingURL=particleHelper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/particleSystemComponent.js - - - - - - - -// Adds the parsers to the scene parsers. -AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM, (parsedData, scene, container, rootUrl) => { - const individualParser = AbstractScene.GetIndividualParser(sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM); - if (!individualParser) { - return; - } - // Particles Systems - if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) { - for (let index = 0, cache = parsedData.particleSystems.length; index < cache; index++) { - const parsedParticleSystem = parsedData.particleSystems[index]; - container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl)); - } - } -}); -AbstractScene.AddIndividualParser(sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM, (parsedParticleSystem, scene, rootUrl) => { - if (parsedParticleSystem.activeParticleCount) { - const ps = GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl); - return ps; - } - else { - const ps = particleSystem_ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl); - return ps; - } -}); -engine_Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames = [], samplers = [], defines = "", fallbacks, onCompiled, onError, particleSystem) { - var _a; - let attributesNamesOrOptions = []; - let effectCreationOption = []; - const allSamplers = []; - if (particleSystem) { - particleSystem.fillUniformsAttributesAndSamplerNames(effectCreationOption, attributesNamesOrOptions, allSamplers); - } - else { - attributesNamesOrOptions = particleSystem_ParticleSystem._GetAttributeNamesOrOptions(); - effectCreationOption = particleSystem_ParticleSystem._GetEffectCreationOptions(); - } - if (defines.indexOf(" BILLBOARD") === -1) { - defines += "\n#define BILLBOARD\n"; - } - if (particleSystem === null || particleSystem === void 0 ? void 0 : particleSystem.isAnimationSheetEnabled) { - if (defines.indexOf(" ANIMATESHEET") === -1) { - defines += "\n#define ANIMATESHEET\n"; - } - } - if (samplers.indexOf("diffuseSampler") === -1) { - samplers.push("diffuseSampler"); - } - return this.createEffect({ - vertex: (_a = particleSystem === null || particleSystem === void 0 ? void 0 : particleSystem.vertexShaderName) !== null && _a !== void 0 ? _a : "particles", - fragmentElement: fragmentName, - }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), allSamplers.concat(samplers), defines, fallbacks, onCompiled, onError); -}; -mesh_Mesh.prototype.getEmittedParticleSystems = function () { - const results = new Array(); - for (let index = 0; index < this.getScene().particleSystems.length; index++) { - const particleSystem = this.getScene().particleSystems[index]; - if (particleSystem.emitter === this) { - results.push(particleSystem); - } - } - return results; -}; -mesh_Mesh.prototype.getHierarchyEmittedParticleSystems = function () { - const results = new Array(); - const descendants = this.getDescendants(); - descendants.push(this); - for (let index = 0; index < this.getScene().particleSystems.length; index++) { - const particleSystem = this.getScene().particleSystems[index]; - const emitter = particleSystem.emitter; - if (emitter.position && descendants.indexOf(emitter) !== -1) { - results.push(particleSystem); - } - } - return results; -}; -//# sourceMappingURL=particleSystemComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/solidParticle.js - - - - - -/** - * Represents one particle of a solid particle system. - */ -class solidParticle_SolidParticle { - /** - * Particle BoundingInfo object - * @returns a BoundingInfo - */ - getBoundingInfo() { - return this._boundingInfo; - } - /** - * Returns true if there is already a bounding info - */ - get hasBoundingInfo() { - return this._boundingInfo !== null; - } - /** - * Creates a Solid Particle object. - * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle() - * @param particleIndex (integer) is the particle index in the Solid Particle System pool. - * @param particleId (integer) is the particle identifier. Unless some particles are removed from the SPS, it's the same value than the particle idx. - * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array. - * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array. - * @param model (ModelShape) is a reference to the model shape on what the particle is designed. - * @param shapeId (integer) is the model shape identifier in the SPS. - * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30)) - * @param sps defines the sps it is associated to - * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations. - * @param materialIndex is the particle material identifier (integer) when the MultiMaterials are enabled in the SPS. - */ - constructor(particleIndex, particleId, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo = null, materialIndex = null) { - /** - * particle global index - */ - this.idx = 0; - /** - * particle identifier - */ - this.id = 0; - /** - * The color of the particle - */ - this.color = new Color4(1.0, 1.0, 1.0, 1.0); - /** - * The world space position of the particle. - */ - this.position = Vector3.Zero(); - /** - * The world space rotation of the particle. (Not use if rotationQuaternion is set) - */ - this.rotation = Vector3.Zero(); - /** - * The scaling of the particle. - */ - this.scaling = Vector3.One(); - /** - * The uvs of the particle. - */ - this.uvs = new Vector4(0.0, 0.0, 1.0, 1.0); - /** - * The current speed of the particle. - */ - this.velocity = Vector3.Zero(); - /** - * The pivot point in the particle local space. - */ - this.pivot = Vector3.Zero(); - /** - * Must the particle be translated from its pivot point in its local space ? - * In this case, the pivot point is set at the origin of the particle local space and the particle is translated. - * Default : false - */ - this.translateFromPivot = false; - /** - * Is the particle active or not ? - */ - this.alive = true; - /** - * Is the particle visible or not ? - */ - this.isVisible = true; - /** - * Index of this particle in the global "positions" array (Internal use) - * @internal - */ - this._pos = 0; - /** - * @internal Index of this particle in the global "indices" array (Internal use) - */ - this._ind = 0; - /** - * ModelShape id of this particle - */ - this.shapeId = 0; - /** - * Index of the particle in its shape id - */ - this.idxInShape = 0; - /** - * @internal Still set as invisible in order to skip useless computations (Internal use) - */ - this._stillInvisible = false; - /** - * @internal Last computed particle rotation matrix - */ - this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]; - /** - * Parent particle Id, if any. - * Default null. - */ - this.parentId = null; - /** - * The particle material identifier (integer) when MultiMaterials are enabled in the SPS. - */ - this.materialIndex = null; - /** - * Custom object or properties. - */ - this.props = null; - /** - * The culling strategy to use to check whether the solid particle must be culled or not when using isInFrustum(). - * The possible values are : - * - AbstractMesh.CULLINGSTRATEGY_STANDARD - * - AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY - * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION - * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY - * The default value for solid particles is AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY - * Please read each static variable documentation in the class AbstractMesh to get details about the culling process. - * */ - this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY; - /** - * @internal Internal global position in the SPS. - */ - this._globalPosition = Vector3.Zero(); - this.idx = particleIndex; - this.id = particleId; - this._pos = positionIndex; - this._ind = indiceIndex; - this._model = model; - this.shapeId = shapeId; - this.idxInShape = idxInShape; - this._sps = sps; - if (modelBoundingInfo) { - this._modelBoundingInfo = modelBoundingInfo; - this._boundingInfo = new BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum); - } - if (materialIndex !== null) { - this.materialIndex = materialIndex; - } - } - /** - * Copies the particle property values into the existing target : position, rotation, scaling, uvs, colors, pivot, parent, visibility, alive - * @param target the particle target - * @returns the current particle - */ - copyToRef(target) { - target.position.copyFrom(this.position); - target.rotation.copyFrom(this.rotation); - if (this.rotationQuaternion) { - if (target.rotationQuaternion) { - target.rotationQuaternion.copyFrom(this.rotationQuaternion); - } - else { - target.rotationQuaternion = this.rotationQuaternion.clone(); - } - } - target.scaling.copyFrom(this.scaling); - if (this.color) { - if (target.color) { - target.color.copyFrom(this.color); - } - else { - target.color = this.color.clone(); - } - } - target.uvs.copyFrom(this.uvs); - target.velocity.copyFrom(this.velocity); - target.pivot.copyFrom(this.pivot); - target.translateFromPivot = this.translateFromPivot; - target.alive = this.alive; - target.isVisible = this.isVisible; - target.parentId = this.parentId; - target.cullingStrategy = this.cullingStrategy; - if (this.materialIndex !== null) { - target.materialIndex = this.materialIndex; - } - return this; - } - /** - * Legacy support, changed scale to scaling - */ - get scale() { - return this.scaling; - } - /** - * Legacy support, changed scale to scaling - */ - set scale(scale) { - this.scaling = scale; - } - /** - * Legacy support, changed quaternion to rotationQuaternion - */ - get quaternion() { - return this.rotationQuaternion; - } - /** - * Legacy support, changed quaternion to rotationQuaternion - */ - set quaternion(q) { - this.rotationQuaternion = q; - } - /** - * Returns a boolean. True if the particle intersects another particle or another mesh, else false. - * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB) - * @param target is the object (solid particle or mesh) what the intersection is computed against. - * @returns true if it intersects - */ - intersectsMesh(target) { - if (!this._boundingInfo || !target.hasBoundingInfo) { - return false; - } - if (this._sps._bSphereOnly) { - return BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target.getBoundingInfo().boundingSphere); - } - return this._boundingInfo.intersects(target.getBoundingInfo(), false); - } - /** - * Returns `true` if the solid particle is within the frustum defined by the passed array of planes. - * A particle is in the frustum if its bounding box intersects the frustum - * @param frustumPlanes defines the frustum to test - * @returns true if the particle is in the frustum planes - */ - isInFrustum(frustumPlanes) { - return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy); - } - /** - * get the rotation matrix of the particle - * @internal - */ - getRotationMatrix(m) { - let quaternion; - if (this.rotationQuaternion) { - quaternion = this.rotationQuaternion; - } - else { - quaternion = TmpVectors.Quaternion[0]; - const rotation = this.rotation; - Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion); - } - quaternion.toRotationMatrix(m); - } -} -/** - * Represents the shape of the model used by one particle of a solid particle system. - * SPS internal tool, don't use it manually. - */ -class solidParticle_ModelShape { - /** - * Get or set the shapeId - * @deprecated Please use shapeId instead - */ - get shapeID() { - return this.shapeId; - } - set shapeID(shapeID) { - this.shapeId = shapeID; - } - /** - * 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. - * SPS internal tool, don't use it manually. - * @internal - */ - constructor(id, shape, indices, normals, colors, shapeUV, posFunction, vtxFunction, material) { - /** - * length of the shape in the model indices array (internal use) - * @internal - */ - this._indicesLength = 0; - this.shapeId = id; - this._shape = shape; - this._indices = indices; - this._indicesLength = indices.length; - this._shapeUV = shapeUV; - this._shapeColors = colors; - this._normals = normals; - this._positionFunction = posFunction; - this._vertexFunction = vtxFunction; - this._material = material; - } -} -/** - * Represents a Depth Sorted Particle in the solid particle system. - * @internal - */ -class solidParticle_DepthSortedParticle { - /** - * Creates a new sorted particle - * @param idx - * @param ind - * @param indLength - * @param materialIndex - */ - constructor(idx, ind, indLength, materialIndex) { - /** - * Particle index - */ - this.idx = 0; - /** - * Index of the particle in the "indices" array - */ - this.ind = 0; - /** - * Length of the particle shape in the "indices" array - */ - this.indicesLength = 0; - /** - * Squared distance from the particle to the camera - */ - this.sqDistance = 0.0; - /** - * Material index when used with MultiMaterials - */ - this.materialIndex = 0; - this.idx = idx; - this.ind = ind; - this.indicesLength = indLength; - this.materialIndex = materialIndex; - } -} -/** - * Represents a solid particle vertex - */ -class solidParticle_SolidParticleVertex { - /** - * Creates a new solid particle vertex - */ - constructor() { - this.position = Vector3.Zero(); - this.color = new Color4(1.0, 1.0, 1.0, 1.0); - this.uv = Vector2.Zero(); - } - // Getters and Setters for back-compatibility - /** Vertex x coordinate */ - get x() { - return this.position.x; - } - set x(val) { - this.position.x = val; - } - /** Vertex y coordinate */ - get y() { - return this.position.y; - } - set y(val) { - this.position.y = val; - } - /** Vertex z coordinate */ - get z() { - return this.position.z; - } - set z(val) { - this.position.z = val; - } -} -//# sourceMappingURL=solidParticle.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/solidParticleSystem.js - - - - - - - - - - - - - -/** - * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces of this big mesh. - *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. - - * The SPS is also a particle system. It provides some methods to manage the particles. - * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior. - * - * Full documentation here : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_intro - */ -class SolidParticleSystem { - /** - * Creates a SPS (Solid Particle System) object. - * @param name (String) is the SPS name, this will be the underlying mesh name. - * @param scene (Scene) is the scene in which the SPS is added. - * @param options defines the options of the sps e.g. - * * updatable (optional boolean, default true) : if the SPS must be updatable or immutable. - * * isPickable (optional boolean, default false) : if the solid particles must be pickable. - * * enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera. - * * 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. - * * enableMultiMaterial (optional boolean, default false) : if the solid particles can be given different materials. - * * expandable (optional boolean, default false) : if particles can still be added after the initial SPS mesh creation. - * * particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed. - * * boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). - * * bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the bounding sphere radius by in order to reduce it for instance. - * * 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. - * * autoFixFaceOrientation (optional boolean, default false): if the particle face orientations will be flipped for transformations that change orientation (scale (-1, 1, 1), for example) - * @param options.updatable - * @param options.isPickable - * @param options.enableDepthSort - * @param options.particleIntersection - * @param options.boundingSphereOnly - * @param options.bSphereRadiusFactor - * @param options.expandable - * @param options.useModelMaterial - * @param options.enableMultiMaterial - * @param options.computeBoundingBox - * @param options.autoFixFaceOrientation - * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh. - */ - constructor(name, scene, options) { - /** - * The SPS array of Solid Particle objects. Just access each particle as with any classic array. - * Example : var p = SPS.particles[i]; - */ - this.particles = new Array(); - /** - * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value. - */ - this.nbParticles = 0; - /** - * If the particles must ever face the camera (default false). Useful for planar particles. - */ - this.billboard = false; - /** - * Recompute normals when adding a shape - */ - this.recomputeNormals = false; - /** - * This a counter ofr your own usage. It's not set by any SPS functions. - */ - this.counter = 0; - /** - * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity. - * Please read : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/optimize_sps#limit-garbage-collection - */ - this.vars = {}; - /** - * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only) - * @internal - */ - this._bSphereOnly = false; - /** - * A number to multiply the bounding sphere radius by in order to reduce it for instance. (Internal use only) - * @internal - */ - this._bSphereRadiusFactor = 1.0; - this._positions = new Array(); - this._indices = new Array(); - this._normals = new Array(); - this._colors = new Array(); - this._uvs = new Array(); - this._index = 0; // indices index - this._updatable = true; - this._pickable = false; - this._isVisibilityBoxLocked = false; - this._alwaysVisible = false; - this._depthSort = false; - this._expandable = false; - this._shapeCounter = 0; - this._copy = new SolidParticle(0, 0, 0, 0, null, 0, 0, this); - this._color = new Color4(0, 0, 0, 0); - this._computeParticleColor = true; - this._computeParticleTexture = true; - this._computeParticleRotation = true; - this._computeParticleVertex = false; - this._computeBoundingBox = false; - this._autoFixFaceOrientation = false; - this._depthSortParticles = true; - this._mustUnrotateFixedNormals = false; - this._particlesIntersect = false; - this._needs32Bits = false; - this._isNotBuilt = true; - this._lastParticleId = 0; - this._idxOfId = []; // array : key = particle.id / value = particle.idx - this._multimaterialEnabled = false; - this._useModelMaterial = false; - this._depthSortFunction = (p1, p2) => p2.sqDistance - p1.sqDistance; - this._materialSortFunction = (p1, p2) => p1.materialIndex - p2.materialIndex; - this._autoUpdateSubMeshes = false; - this._recomputeInvisibles = false; - this.name = name; - this._scene = scene || EngineStore.LastCreatedScene; - this._camera = scene.activeCamera; - this._pickable = options ? options.isPickable : false; - this._depthSort = options ? options.enableDepthSort : false; - this._multimaterialEnabled = options ? options.enableMultiMaterial : false; - this._useModelMaterial = options ? options.useModelMaterial : false; - this._multimaterialEnabled = this._useModelMaterial ? true : this._multimaterialEnabled; - this._expandable = options ? options.expandable : false; - this._particlesIntersect = options ? options.particleIntersection : false; - this._bSphereOnly = options ? options.boundingSphereOnly : false; - this._bSphereRadiusFactor = options && options.bSphereRadiusFactor ? options.bSphereRadiusFactor : 1.0; - this._computeBoundingBox = (options === null || options === void 0 ? void 0 : options.computeBoundingBox) ? options.computeBoundingBox : false; - this._autoFixFaceOrientation = (options === null || options === void 0 ? void 0 : options.autoFixFaceOrientation) ? options.autoFixFaceOrientation : false; - if (options && options.updatable !== undefined) { - this._updatable = options.updatable; - } - else { - this._updatable = true; - } - if (this._pickable) { - this.pickedBySubMesh = [[]]; - this.pickedParticles = this.pickedBySubMesh[0]; - } - if (this._depthSort || this._multimaterialEnabled) { - this.depthSortedParticles = []; - } - if (this._multimaterialEnabled) { - this._multimaterial = new MultiMaterial(this.name + "MultiMaterial", this._scene); - this._materials = []; - this._materialIndexesById = {}; - } - this._tmpVertex = new SolidParticleVertex(); - } - /** - * Builds the SPS underlying mesh. Returns a standard Mesh. - * If no model shape was added to the SPS, the returned mesh is just a single triangular plane. - * @returns the created mesh - */ - buildMesh() { - if (!this._isNotBuilt && this.mesh) { - return this.mesh; - } - if (this.nbParticles === 0 && !this.mesh) { - const triangle = CreateDisc("", { radius: 1, tessellation: 3 }, this._scene); - this.addShape(triangle, 1); - triangle.dispose(); - } - this._indices32 = this._needs32Bits ? new Uint32Array(this._indices) : new Uint16Array(this._indices); - this._positions32 = new Float32Array(this._positions); - this._uvs32 = new Float32Array(this._uvs); - this._colors32 = new Float32Array(this._colors); - if (!this.mesh) { - // in case it's already expanded - const mesh = new Mesh(this.name, this._scene); - this.mesh = mesh; - } - if (!this._updatable && this._multimaterialEnabled) { - this._sortParticlesByMaterial(); // this may reorder the indices32 - } - if (this.recomputeNormals) { - VertexData.ComputeNormals(this._positions32, this._indices32, this._normals); - } - this._normals32 = new Float32Array(this._normals); - this._fixedNormal32 = new Float32Array(this._normals); - if (this._mustUnrotateFixedNormals) { - // the particles could be created already rotated in the mesh with a positionFunction - this._unrotateFixedNormals(); - } - const vertexData = new VertexData(); - vertexData.indices = this._depthSort ? this._indices : this._indices32; - vertexData.set(this._positions32, VertexBuffer.PositionKind); - vertexData.set(this._normals32, VertexBuffer.NormalKind); - if (this._uvs32.length > 0) { - vertexData.set(this._uvs32, VertexBuffer.UVKind); - } - if (this._colors32.length > 0) { - vertexData.set(this._colors32, VertexBuffer.ColorKind); - } - vertexData.applyToMesh(this.mesh, this._updatable); - this.mesh.isPickable = this._pickable; - if (this._pickable) { - let faceId = 0; - for (let p = 0; p < this.nbParticles; p++) { - const part = this.particles[p]; - const lind = part._model._indicesLength; - for (let i = 0; i < lind; i++) { - const f = i % 3; - if (f == 0) { - const pickedData = { idx: part.idx, faceId: faceId }; - this.pickedParticles[faceId] = pickedData; - faceId++; - } - } - } - } - if (this._multimaterialEnabled) { - this.setMultiMaterial(this._materials); - } - if (!this._expandable) { - // free memory - if (!this._depthSort && !this._multimaterialEnabled && !this._autoFixFaceOrientation) { - this._indices = null; - } - this._positions = null; - this._normals = null; - this._uvs = null; - this._colors = null; - if (!this._updatable) { - this.particles.length = 0; - } - } - this._isNotBuilt = false; - this.recomputeNormals = false; - this._recomputeInvisibles = true; - return this.mesh; - } - /** - * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS. - * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places. - * Thus the particles generated from `digest()` have their property `position` set yet. - * @param mesh ( Mesh ) is the mesh to be digested - * @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 - * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets - * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets - * {storage} (optional existing array) is an array where the particles will be stored for a further use instead of being inserted in the SPS. - * @param options.facetNb - * @param options.number - * @param options.delta - * @param options.storage - * @returns the current SPS - */ - digest(mesh, options) { - let size = (options && options.facetNb) || 1; - let number = (options && options.number) || 0; - let delta = (options && options.delta) || 0; - const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind); - const meshInd = mesh.getIndices(); - const meshUV = mesh.getVerticesData(VertexBuffer.UVKind); - const meshCol = mesh.getVerticesData(VertexBuffer.ColorKind); - const meshNor = mesh.getVerticesData(VertexBuffer.NormalKind); - const storage = options && options.storage ? options.storage : null; - let f = 0; // facet counter - const totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices - // compute size from number - if (number) { - number = number > totalFacets ? totalFacets : number; - size = Math.round(totalFacets / number); - delta = 0; - } - else { - size = size > totalFacets ? totalFacets : size; - } - const facetPos = []; // submesh positions - const facetNor = []; - const facetInd = []; // submesh indices - const facetUV = []; // submesh UV - const facetCol = []; // submesh colors - const barycenter = Vector3.Zero(); - const sizeO = size; - while (f < totalFacets) { - size = sizeO + Math.floor((1 + delta) * Math.random()); - if (f > totalFacets - size) { - size = totalFacets - f; - } - // reset temp arrays - facetPos.length = 0; - facetNor.length = 0; - facetInd.length = 0; - facetUV.length = 0; - facetCol.length = 0; - // iterate over "size" facets - let fi = 0; - for (let j = f * 3; j < (f + size) * 3; j++) { - facetInd.push(fi); - const i = meshInd[j]; - const i3 = i * 3; - facetPos.push(meshPos[i3], meshPos[i3 + 1], meshPos[i3 + 2]); - facetNor.push(meshNor[i3], meshNor[i3 + 1], meshNor[i3 + 2]); - if (meshUV) { - const i2 = i * 2; - facetUV.push(meshUV[i2], meshUV[i2 + 1]); - } - if (meshCol) { - const i4 = i * 4; - facetCol.push(meshCol[i4], meshCol[i4 + 1], meshCol[i4 + 2], meshCol[i4 + 3]); - } - fi++; - } - // create a model shape for each single particle - let idx = this.nbParticles; - const shape = this._posToShape(facetPos); - const shapeUV = this._uvsToShapeUV(facetUV); - const shapeInd = facetInd.slice(); - const shapeCol = facetCol.slice(); - const shapeNor = facetNor.slice(); - // compute the barycenter of the shape - barycenter.copyFromFloats(0, 0, 0); - let v; - for (v = 0; v < shape.length; v++) { - barycenter.addInPlace(shape[v]); - } - barycenter.scaleInPlace(1 / shape.length); - // shift the shape from its barycenter to the origin - // and compute the BBox required for intersection. - const minimum = new Vector3(Infinity, Infinity, Infinity); - const maximum = new Vector3(-Infinity, -Infinity, -Infinity); - for (v = 0; v < shape.length; v++) { - shape[v].subtractInPlace(barycenter); - minimum.minimizeInPlaceFromFloats(shape[v].x, shape[v].y, shape[v].z); - maximum.maximizeInPlaceFromFloats(shape[v].x, shape[v].y, shape[v].z); - } - let bInfo; - if (this._particlesIntersect) { - bInfo = new BoundingInfo(minimum, maximum); - } - let material = null; - if (this._useModelMaterial) { - material = mesh.material ? mesh.material : this._setDefaultMaterial(); - } - const modelShape = new ModelShape(this._shapeCounter, shape, shapeInd, shapeNor, shapeCol, shapeUV, null, null, material); - // add the particle in the SPS - const currentPos = this._positions.length; - const currentInd = this._indices.length; - this._meshBuilder(this._index, currentInd, shape, this._positions, shapeInd, this._indices, facetUV, this._uvs, shapeCol, this._colors, shapeNor, this._normals, idx, 0, null, modelShape); - this._addParticle(idx, this._lastParticleId, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo, storage); - // initialize the particle position - this.particles[this.nbParticles].position.addInPlace(barycenter); - if (!storage) { - this._index += shape.length; - idx++; - this.nbParticles++; - this._lastParticleId++; - } - this._shapeCounter++; - f += size; - } - this._isNotBuilt = true; // buildMesh() is now expected for setParticles() to work - return this; - } - /** - * Unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape() - * @internal - */ - _unrotateFixedNormals() { - let index = 0; - let idx = 0; - const tmpNormal = TmpVectors.Vector3[0]; - const quaternion = TmpVectors.Quaternion[0]; - const invertedRotMatrix = TmpVectors.Matrix[0]; - for (let p = 0; p < this.particles.length; p++) { - const particle = this.particles[p]; - const shape = particle._model._shape; - // computing the inverse of the rotation matrix from the quaternion - // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion - if (particle.rotationQuaternion) { - particle.rotationQuaternion.conjugateToRef(quaternion); - } - else { - const rotation = particle.rotation; - Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion); - quaternion.conjugateInPlace(); - } - quaternion.toRotationMatrix(invertedRotMatrix); - for (let pt = 0; pt < shape.length; pt++) { - idx = index + pt * 3; - Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal); - tmpNormal.toArray(this._fixedNormal32, idx); - } - index = idx + 3; - } - } - /** - * Resets the temporary working copy particle - * @internal - */ - _resetCopy() { - const copy = this._copy; - copy.position.setAll(0); - copy.rotation.setAll(0); - copy.rotationQuaternion = null; - copy.scaling.setAll(1); - copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0); - copy.color = null; - copy.translateFromPivot = false; - copy.shapeId = 0; - copy.materialIndex = null; - } - /** - * Inserts the shape model geometry in the global SPS mesh by updating the positions, indices, normals, colors, uvs arrays - * @param p the current index in the positions array to be updated - * @param ind the current index in the indices array - * @param shape a Vector3 array, the shape geometry - * @param positions the positions array to be updated - * @param meshInd the shape indices array - * @param indices the indices array to be updated - * @param meshUV the shape uv array - * @param uvs the uv array to be updated - * @param meshCol the shape color array - * @param colors the color array to be updated - * @param meshNor the shape normals array - * @param normals the normals array to be updated - * @param idx the particle index - * @param idxInShape the particle index in its shape - * @param options the addShape() method passed options - * @param model - * @model the particle model - * @internal - */ - _meshBuilder(p, ind, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options, model) { - let i; - let u = 0; - let c = 0; - let n = 0; - this._resetCopy(); - const copy = this._copy; - const storeApart = options && options.storage ? true : false; - copy.idx = idx; - copy.idxInShape = idxInShape; - copy.shapeId = model.shapeId; - if (this._useModelMaterial) { - const materialId = model._material.uniqueId; - const materialIndexesById = this._materialIndexesById; - if (!Object.prototype.hasOwnProperty.call(materialIndexesById, materialId)) { - materialIndexesById[materialId] = this._materials.length; - this._materials.push(model._material); - } - const matIdx = materialIndexesById[materialId]; - copy.materialIndex = matIdx; - } - if (options && options.positionFunction) { - // call to custom positionFunction - options.positionFunction(copy, idx, idxInShape); - this._mustUnrotateFixedNormals = true; - } - // in case the particle geometry must NOT be inserted in the SPS mesh geometry - if (storeApart) { - return copy; - } - const rotMatrix = TmpVectors.Matrix[0]; - const tmpVertex = this._tmpVertex; - const tmpVector = tmpVertex.position; - const tmpColor = tmpVertex.color; - const tmpUV = tmpVertex.uv; - const tmpRotated = TmpVectors.Vector3[1]; - const pivotBackTranslation = TmpVectors.Vector3[2]; - const scaledPivot = TmpVectors.Vector3[3]; - Matrix.IdentityToRef(rotMatrix); - copy.getRotationMatrix(rotMatrix); - copy.pivot.multiplyToRef(copy.scaling, scaledPivot); - if (copy.translateFromPivot) { - pivotBackTranslation.setAll(0.0); - } - else { - pivotBackTranslation.copyFrom(scaledPivot); - } - const someVertexFunction = options && options.vertexFunction; - for (i = 0; i < shape.length; i++) { - tmpVector.copyFrom(shape[i]); - if (copy.color) { - tmpColor.copyFrom(copy.color); - } - if (meshUV) { - tmpUV.copyFromFloats(meshUV[u], meshUV[u + 1]); - } - if (someVertexFunction) { - options.vertexFunction(copy, tmpVertex, i); - } - tmpVector.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot); - Vector3.TransformCoordinatesToRef(tmpVector, rotMatrix, tmpRotated); - tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position); - positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z); - if (meshUV) { - const copyUvs = copy.uvs; - uvs.push((copyUvs.z - copyUvs.x) * tmpUV.x + copyUvs.x, (copyUvs.w - copyUvs.y) * tmpUV.y + copyUvs.y); - u += 2; - } - if (copy.color) { - this._color.copyFrom(tmpColor); - } - else { - const color = this._color; - if (meshCol && meshCol[c] !== undefined) { - color.r = meshCol[c]; - color.g = meshCol[c + 1]; - color.b = meshCol[c + 2]; - color.a = meshCol[c + 3]; - } - else { - color.r = 1.0; - color.g = 1.0; - color.b = 1.0; - color.a = 1.0; - } - } - colors.push(this._color.r, this._color.g, this._color.b, this._color.a); - c += 4; - if (!this.recomputeNormals && meshNor) { - Vector3.TransformNormalFromFloatsToRef(meshNor[n], meshNor[n + 1], meshNor[n + 2], rotMatrix, tmpVector); - normals.push(tmpVector.x, tmpVector.y, tmpVector.z); - n += 3; - } - } - for (i = 0; i < meshInd.length; i++) { - const current_ind = p + meshInd[i]; - indices.push(current_ind); - if (current_ind > 65535) { - this._needs32Bits = true; - } - } - if (this._depthSort || this._multimaterialEnabled) { - const matIndex = copy.materialIndex !== null ? copy.materialIndex : 0; - this.depthSortedParticles.push(new DepthSortedParticle(idx, ind, meshInd.length, matIndex)); - } - return copy; - } - /** - * Returns a shape Vector3 array from positions float array - * @param positions float array - * @returns a vector3 array - * @internal - */ - _posToShape(positions) { - const shape = []; - for (let i = 0; i < positions.length; i += 3) { - shape.push(Vector3.FromArray(positions, i)); - } - return shape; - } - /** - * Returns a shapeUV array from a float uvs (array deep copy) - * @param uvs as a float array - * @returns a shapeUV array - * @internal - */ - _uvsToShapeUV(uvs) { - const shapeUV = []; - if (uvs) { - for (let i = 0; i < uvs.length; i++) { - shapeUV.push(uvs[i]); - } - } - return shapeUV; - } - /** - * Adds a new particle object in the particles array - * @param idx particle index in particles array - * @param id particle id - * @param idxpos positionIndex : the starting index of the particle vertices in the SPS "positions" array - * @param idxind indiceIndex : he starting index of the particle indices in the SPS "indices" array - * @param model particle ModelShape object - * @param shapeId model shape identifier - * @param idxInShape index of the particle in the current model - * @param bInfo model bounding info object - * @param storage target storage array, if any - * @internal - */ - _addParticle(idx, id, idxpos, idxind, model, shapeId, idxInShape, bInfo = null, storage = null) { - const sp = new SolidParticle(idx, id, idxpos, idxind, model, shapeId, idxInShape, this, bInfo); - const target = storage ? storage : this.particles; - target.push(sp); - return sp; - } - /** - * Adds some particles to the SPS from the model shape. Returns the shape id. - * Please read the doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/immutable_sps - * @param mesh is any Mesh object that will be used as a model for the solid particles. - * @param nb (positive integer) the number of particles to be created from this model - * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation. - * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation - * {storage} (optional existing array) is an array where the particles will be stored for a further use instead of being inserted in the SPS. - * @param options.positionFunction - * @param options.vertexFunction - * @param options.storage - * @returns the number of shapes in the system - */ - addShape(mesh, nb, options) { - const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind); - const meshInd = mesh.getIndices(); - const meshUV = mesh.getVerticesData(VertexBuffer.UVKind); - const meshCol = mesh.getVerticesData(VertexBuffer.ColorKind); - const meshNor = mesh.getVerticesData(VertexBuffer.NormalKind); - this.recomputeNormals = meshNor ? false : true; - const indices = Array.from(meshInd); - const shapeNormals = Array.from(meshNor); - const shapeColors = meshCol ? Array.from(meshCol) : []; - const storage = options && options.storage ? options.storage : null; - let bbInfo = null; - if (this._particlesIntersect) { - bbInfo = mesh.getBoundingInfo(); - } - const shape = this._posToShape(meshPos); - const shapeUV = this._uvsToShapeUV(meshUV); - const posfunc = options ? options.positionFunction : null; - const vtxfunc = options ? options.vertexFunction : null; - let material = null; - if (this._useModelMaterial) { - material = mesh.material ? mesh.material : this._setDefaultMaterial(); - } - const modelShape = new ModelShape(this._shapeCounter, shape, indices, shapeNormals, shapeColors, shapeUV, posfunc, vtxfunc, material); - // particles - for (let i = 0; i < nb; i++) { - this._insertNewParticle(this.nbParticles, i, modelShape, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, storage, options); - } - this._shapeCounter++; - this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work - return this._shapeCounter - 1; - } - /** - * Rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices - * @internal - */ - _rebuildParticle(particle, reset = false) { - this._resetCopy(); - const copy = this._copy; - if (particle._model._positionFunction) { - // recall to stored custom positionFunction - particle._model._positionFunction(copy, particle.idx, particle.idxInShape); - } - const rotMatrix = TmpVectors.Matrix[0]; - const tmpVertex = TmpVectors.Vector3[0]; - const tmpRotated = TmpVectors.Vector3[1]; - const pivotBackTranslation = TmpVectors.Vector3[2]; - const scaledPivot = TmpVectors.Vector3[3]; - copy.getRotationMatrix(rotMatrix); - particle.pivot.multiplyToRef(particle.scaling, scaledPivot); - if (copy.translateFromPivot) { - pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0); - } - else { - pivotBackTranslation.copyFrom(scaledPivot); - } - const shape = particle._model._shape; - for (let pt = 0; pt < shape.length; pt++) { - tmpVertex.copyFrom(shape[pt]); - if (particle._model._vertexFunction) { - particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction - } - tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot); - Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated); - tmpRotated - .addInPlace(pivotBackTranslation) - .addInPlace(copy.position) - .toArray(this._positions32, particle._pos + pt * 3); - } - if (reset) { - particle.position.setAll(0.0); - particle.rotation.setAll(0.0); - particle.rotationQuaternion = null; - particle.scaling.setAll(1.0); - particle.uvs.setAll(0.0); - particle.pivot.setAll(0.0); - particle.translateFromPivot = false; - particle.parentId = null; - } - } - /** - * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed. - * @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. - * @returns the SPS. - */ - rebuildMesh(reset = false) { - for (let p = 0; p < this.particles.length; p++) { - this._rebuildParticle(this.particles[p], reset); - } - this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false); - return this; - } - /** Removes the particles from the start-th to the end-th included from an expandable SPS (required). - * Returns an array with the removed particles. - * 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. - * The SPS can't be empty so at least one particle needs to remain in place. - * Under the hood, the VertexData array, so the VBO buffer, is recreated each call. - * @param start index of the first particle to remove - * @param end index of the last particle to remove (included) - * @returns an array populated with the removed particles - */ - removeParticles(start, end) { - const nb = end - start + 1; - if (!this._expandable || nb <= 0 || nb >= this.nbParticles || !this._updatable) { - return []; - } - const particles = this.particles; - const currentNb = this.nbParticles; - if (end < currentNb - 1) { - // update the particle indexes in the positions array in case they're remaining particles after the last removed - const firstRemaining = end + 1; - const shiftPos = particles[firstRemaining]._pos - particles[start]._pos; - const shifInd = particles[firstRemaining]._ind - particles[start]._ind; - for (let i = firstRemaining; i < currentNb; i++) { - const part = particles[i]; - part._pos -= shiftPos; - part._ind -= shifInd; - } - } - const removed = particles.splice(start, nb); - this._positions.length = 0; - this._indices.length = 0; - this._colors.length = 0; - this._uvs.length = 0; - this._normals.length = 0; - this._index = 0; - this._idxOfId.length = 0; - if (this._depthSort || this._multimaterialEnabled) { - this.depthSortedParticles = []; - } - let ind = 0; - const particlesLength = particles.length; - for (let p = 0; p < particlesLength; p++) { - const particle = particles[p]; - const model = particle._model; - const shape = model._shape; - const modelIndices = model._indices; - const modelNormals = model._normals; - const modelColors = model._shapeColors; - const modelUVs = model._shapeUV; - particle.idx = p; - this._idxOfId[particle.id] = p; - 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); - this._index += shape.length; - ind += modelIndices.length; - } - this.nbParticles -= nb; - this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work - return removed; - } - /** - * Inserts some pre-created particles in the solid particle system so that they can be managed by setParticles(). - * @param solidParticleArray an array populated with Solid Particles objects - * @returns the SPS - */ - insertParticlesFromArray(solidParticleArray) { - if (!this._expandable) { - return this; - } - let idxInShape = 0; - let currentShapeId = solidParticleArray[0].shapeId; - const nb = solidParticleArray.length; - for (let i = 0; i < nb; i++) { - const sp = solidParticleArray[i]; - const model = sp._model; - const shape = model._shape; - const meshInd = model._indices; - const meshUV = model._shapeUV; - const meshCol = model._shapeColors; - const meshNor = model._normals; - const noNor = meshNor ? false : true; - this.recomputeNormals = noNor || this.recomputeNormals; - const bbInfo = sp.getBoundingInfo(); - const newPart = this._insertNewParticle(this.nbParticles, idxInShape, model, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, null, null); - sp.copyToRef(newPart); - idxInShape++; - if (currentShapeId != sp.shapeId) { - currentShapeId = sp.shapeId; - idxInShape = 0; - } - } - this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work - return this; - } - /** - * Creates a new particle and modifies the SPS mesh geometry : - * - calls _meshBuilder() to increase the SPS mesh geometry step by step - * - calls _addParticle() to populate the particle array - * factorized code from addShape() and insertParticlesFromArray() - * @param idx particle index in the particles array - * @param i particle index in its shape - * @param modelShape particle ModelShape object - * @param shape shape vertex array - * @param meshInd shape indices array - * @param meshUV shape uv array - * @param meshCol shape color array - * @param meshNor shape normals array - * @param bbInfo shape bounding info - * @param storage target particle storage - * @param options - * @options addShape() passed options - * @internal - */ - _insertNewParticle(idx, i, modelShape, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, storage, options) { - const currentPos = this._positions.length; - const currentInd = this._indices.length; - 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); - let sp = null; - if (this._updatable) { - sp = this._addParticle(this.nbParticles, this._lastParticleId, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo, storage); - sp.position.copyFrom(currentCopy.position); - sp.rotation.copyFrom(currentCopy.rotation); - if (currentCopy.rotationQuaternion) { - if (sp.rotationQuaternion) { - sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion); - } - else { - sp.rotationQuaternion = currentCopy.rotationQuaternion.clone(); - } - } - if (currentCopy.color) { - if (sp.color) { - sp.color.copyFrom(currentCopy.color); - } - else { - sp.color = currentCopy.color.clone(); - } - } - sp.scaling.copyFrom(currentCopy.scaling); - sp.uvs.copyFrom(currentCopy.uvs); - if (currentCopy.materialIndex !== null) { - sp.materialIndex = currentCopy.materialIndex; - } - if (this.expandable) { - this._idxOfId[sp.id] = sp.idx; - } - } - if (!storage) { - this._index += shape.length; - this.nbParticles++; - this._lastParticleId++; - } - return sp; - } - /** - * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc. - * This method calls `updateParticle()` for each particle of the SPS. - * For an animated SPS, it is usually called within the render loop. - * 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. - * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_ - * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_ - * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_ - * @returns the SPS. - */ - setParticles(start = 0, end = this.nbParticles - 1, update = true) { - if (!this._updatable || this._isNotBuilt) { - return this; - } - // custom beforeUpdate - this.beforeUpdateParticles(start, end, update); - const rotMatrix = TmpVectors.Matrix[0]; - const invertedMatrix = TmpVectors.Matrix[1]; - const mesh = this.mesh; - const colors32 = this._colors32; - const positions32 = this._positions32; - const normals32 = this._normals32; - const uvs32 = this._uvs32; - const indices32 = this._indices32; - const indices = this._indices; - const fixedNormal32 = this._fixedNormal32; - const depthSortParticles = this._depthSort && this._depthSortParticles; - const tempVectors = TmpVectors.Vector3; - const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0); - const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0); - const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0); - const minimum = tempVectors[8].setAll(Number.MAX_VALUE); - const maximum = tempVectors[9].setAll(-Number.MAX_VALUE); - const camInvertedPosition = tempVectors[10].setAll(0); - const tmpVertex = this._tmpVertex; - const tmpVector = tmpVertex.position; - const tmpColor = tmpVertex.color; - const tmpUV = tmpVertex.uv; - // cases when the World Matrix is to be computed first - if (this.billboard || this._depthSort) { - this.mesh.computeWorldMatrix(true); - this.mesh._worldMatrix.invertToRef(invertedMatrix); - } - // if the particles will always face the camera - if (this.billboard) { - // compute the camera position and un-rotate it by the current mesh rotation - const tmpVector0 = tempVectors[0]; - this._camera.getDirectionToRef(Axis.Z, tmpVector0); - Vector3.TransformNormalToRef(tmpVector0, invertedMatrix, camAxisZ); - camAxisZ.normalize(); - // same for camera up vector extracted from the cam view matrix - const view = this._camera.getViewMatrix(true); - Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY); - Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX); - camAxisY.normalize(); - camAxisX.normalize(); - } - // if depthSort, compute the camera global position in the mesh local system - if (this._depthSort) { - Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera - } - Matrix.IdentityToRef(rotMatrix); - let idx = 0; // current position index in the global array positions32 - let index = 0; // position start index in the global array positions32 of the current particle - let colidx = 0; // current color index in the global array colors32 - let colorIndex = 0; // color start index in the global array colors32 of the current particle - let uvidx = 0; // current uv index in the global array uvs32 - let uvIndex = 0; // uv start index in the global array uvs32 of the current particle - let pt = 0; // current index in the particle model shape - if (this.mesh.isFacetDataEnabled) { - this._computeBoundingBox = true; - } - end = end >= this.nbParticles ? this.nbParticles - 1 : end; - if (this._computeBoundingBox) { - if (start != 0 || end != this.nbParticles - 1) { - // only some particles are updated, then use the current existing BBox basis. Note : it can only increase. - const boundingInfo = this.mesh.getBoundingInfo(); - if (boundingInfo) { - minimum.copyFrom(boundingInfo.minimum); - maximum.copyFrom(boundingInfo.maximum); - } - } - } - // particle loop - index = this.particles[start]._pos; - const vpos = (index / 3) | 0; - colorIndex = vpos * 4; - uvIndex = vpos * 2; - for (let p = start; p <= end; p++) { - const particle = this.particles[p]; - // call to custom user function to update the particle properties - this.updateParticle(particle); - const shape = particle._model._shape; - const shapeUV = particle._model._shapeUV; - const particleRotationMatrix = particle._rotationMatrix; - const particlePosition = particle.position; - const particleRotation = particle.rotation; - const particleScaling = particle.scaling; - const particleGlobalPosition = particle._globalPosition; - // camera-particle distance for depth sorting - if (depthSortParticles) { - const dsp = this.depthSortedParticles[p]; - dsp.idx = particle.idx; - dsp.ind = particle._ind; - dsp.indicesLength = particle._model._indicesLength; - dsp.sqDistance = Vector3.DistanceSquared(particle.position, camInvertedPosition); - } - // skip the computations for inactive or already invisible particles - if (!particle.alive || (particle._stillInvisible && !particle.isVisible && !this._recomputeInvisibles)) { - // increment indexes for the next particle - pt = shape.length; - index += pt * 3; - colorIndex += pt * 4; - uvIndex += pt * 2; - continue; - } - if (particle.isVisible) { - particle._stillInvisible = false; // un-mark permanent invisibility - const scaledPivot = tempVectors[12]; - particle.pivot.multiplyToRef(particleScaling, scaledPivot); - // particle rotation matrix - if (this.billboard) { - particleRotation.x = 0.0; - particleRotation.y = 0.0; - } - if (this._computeParticleRotation || this.billboard) { - particle.getRotationMatrix(rotMatrix); - } - const particleHasParent = particle.parentId !== null; - if (particleHasParent) { - const parent = this.getParticleById(particle.parentId); - if (parent) { - const parentRotationMatrix = parent._rotationMatrix; - const parentGlobalPosition = parent._globalPosition; - const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7]; - const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6]; - const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8]; - particleGlobalPosition.x = parentGlobalPosition.x + rotatedX; - particleGlobalPosition.y = parentGlobalPosition.y + rotatedY; - particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ; - if (this._computeParticleRotation || this.billboard) { - const rotMatrixValues = rotMatrix.m; - particleRotationMatrix[0] = - rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6]; - particleRotationMatrix[1] = - rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7]; - particleRotationMatrix[2] = - rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8]; - particleRotationMatrix[3] = - rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6]; - particleRotationMatrix[4] = - rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7]; - particleRotationMatrix[5] = - rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8]; - particleRotationMatrix[6] = - rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6]; - particleRotationMatrix[7] = - rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7]; - particleRotationMatrix[8] = - rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8]; - } - } - else { - // in case the parent were removed at some moment - particle.parentId = null; - } - } - else { - particleGlobalPosition.x = particlePosition.x; - particleGlobalPosition.y = particlePosition.y; - particleGlobalPosition.z = particlePosition.z; - if (this._computeParticleRotation || this.billboard) { - const rotMatrixValues = rotMatrix.m; - particleRotationMatrix[0] = rotMatrixValues[0]; - particleRotationMatrix[1] = rotMatrixValues[1]; - particleRotationMatrix[2] = rotMatrixValues[2]; - particleRotationMatrix[3] = rotMatrixValues[4]; - particleRotationMatrix[4] = rotMatrixValues[5]; - particleRotationMatrix[5] = rotMatrixValues[6]; - particleRotationMatrix[6] = rotMatrixValues[8]; - particleRotationMatrix[7] = rotMatrixValues[9]; - particleRotationMatrix[8] = rotMatrixValues[10]; - } - } - const pivotBackTranslation = tempVectors[11]; - if (particle.translateFromPivot) { - pivotBackTranslation.setAll(0.0); - } - else { - pivotBackTranslation.copyFrom(scaledPivot); - } - // particle vertex loop - for (pt = 0; pt < shape.length; pt++) { - idx = index + pt * 3; - colidx = colorIndex + pt * 4; - uvidx = uvIndex + pt * 2; - const iu = 2 * pt; - const iv = iu + 1; - tmpVector.copyFrom(shape[pt]); - if (this._computeParticleColor && particle.color) { - tmpColor.copyFrom(particle.color); - } - if (this._computeParticleTexture) { - tmpUV.copyFromFloats(shapeUV[iu], shapeUV[iv]); - } - if (this._computeParticleVertex) { - this.updateParticleVertex(particle, tmpVertex, pt); - } - // positions - const vertexX = tmpVector.x * particleScaling.x - scaledPivot.x; - const vertexY = tmpVector.y * particleScaling.y - scaledPivot.y; - const vertexZ = tmpVector.z * particleScaling.z - scaledPivot.z; - let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6]; - let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7]; - let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8]; - rotatedX += pivotBackTranslation.x; - rotatedY += pivotBackTranslation.y; - rotatedZ += pivotBackTranslation.z; - const px = (positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ); - const py = (positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ); - const pz = (positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ); - if (this._computeBoundingBox) { - minimum.minimizeInPlaceFromFloats(px, py, pz); - maximum.maximizeInPlaceFromFloats(px, py, pz); - } - // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals() - if (!this._computeParticleVertex) { - const normalx = fixedNormal32[idx]; - const normaly = fixedNormal32[idx + 1]; - const normalz = fixedNormal32[idx + 2]; - const rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6]; - const rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7]; - const rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8]; - normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz; - normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz; - normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz; - } - if (this._computeParticleColor && particle.color) { - const colors32 = this._colors32; - colors32[colidx] = tmpColor.r; - colors32[colidx + 1] = tmpColor.g; - colors32[colidx + 2] = tmpColor.b; - colors32[colidx + 3] = tmpColor.a; - } - if (this._computeParticleTexture) { - const uvs = particle.uvs; - uvs32[uvidx] = tmpUV.x * (uvs.z - uvs.x) + uvs.x; - uvs32[uvidx + 1] = tmpUV.y * (uvs.w - uvs.y) + uvs.y; - } - } - } - // particle just set invisible : scaled to zero and positioned at the origin - else { - particle._stillInvisible = true; // mark the particle as invisible - for (pt = 0; pt < shape.length; pt++) { - idx = index + pt * 3; - colidx = colorIndex + pt * 4; - uvidx = uvIndex + pt * 2; - positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0; - normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0; - if (this._computeParticleColor && particle.color) { - const color = particle.color; - colors32[colidx] = color.r; - colors32[colidx + 1] = color.g; - colors32[colidx + 2] = color.b; - colors32[colidx + 3] = color.a; - } - if (this._computeParticleTexture) { - const uvs = particle.uvs; - uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x; - uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y; - } - } - } - // if the particle intersections must be computed : update the bbInfo - if (this._particlesIntersect) { - const bInfo = particle.getBoundingInfo(); - const bBox = bInfo.boundingBox; - const bSphere = bInfo.boundingSphere; - const modelBoundingInfo = particle._modelBoundingInfo; - if (!this._bSphereOnly) { - // place, scale and rotate the particle bbox within the SPS local system, then update it - const modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors; - const tempMin = tempVectors[1]; - const tempMax = tempVectors[2]; - tempMin.setAll(Number.MAX_VALUE); - tempMax.setAll(-Number.MAX_VALUE); - for (let b = 0; b < 8; b++) { - const scaledX = modelBoundingInfoVectors[b].x * particleScaling.x; - const scaledY = modelBoundingInfoVectors[b].y * particleScaling.y; - const scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z; - const rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6]; - const rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7]; - const rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8]; - const x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ; - const y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ; - const z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ; - tempMin.minimizeInPlaceFromFloats(x, y, z); - tempMax.maximizeInPlaceFromFloats(x, y, z); - } - bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix); - } - // place and scale the particle bouding sphere in the SPS local system, then update it - const minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]); - const maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]); - const bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5).addInPlace(particleGlobalPosition); - const halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor); - const bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]); - const bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]); - bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix); - } - // increment indexes for the next particle - index = idx + 3; - colorIndex = colidx + 4; - uvIndex = uvidx + 2; - } - // if the VBO must be updated - if (update) { - if (this._computeParticleColor) { - const vb = mesh.getVertexBuffer(VertexBuffer.ColorKind); - if (vb && !mesh.isPickable) { - vb.updateDirectly(colors32, 0); - } - else { - mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false); - } - } - if (this._computeParticleTexture) { - const vb = mesh.getVertexBuffer(VertexBuffer.UVKind); - if (vb && !mesh.isPickable) { - vb.updateDirectly(uvs32, 0); - } - else { - mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false); - } - } - const vbp = mesh.getVertexBuffer(VertexBuffer.PositionKind); - if (vbp && !mesh.isPickable) { - vbp.updateDirectly(positions32, 0); - } - else { - mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false); - } - if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) { - if (this._computeParticleVertex || mesh.isFacetDataEnabled) { - // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[] - const params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null; - VertexData.ComputeNormals(positions32, indices32, normals32, params); - for (let i = 0; i < normals32.length; i++) { - fixedNormal32[i] = normals32[i]; - } - } - if (!mesh.areNormalsFrozen) { - const vb = mesh.getVertexBuffer(VertexBuffer.NormalKind); - if (vb && !mesh.isPickable) { - vb.updateDirectly(normals32, 0); - } - else { - mesh.updateVerticesData(VertexBuffer.NormalKind, normals32, false, false); - } - } - } - if (depthSortParticles) { - const depthSortedParticles = this.depthSortedParticles; - depthSortedParticles.sort(this._depthSortFunction); - const dspl = depthSortedParticles.length; - let sid = 0; - let faceId = 0; - for (let sorted = 0; sorted < dspl; sorted++) { - const sortedParticle = depthSortedParticles[sorted]; - const lind = sortedParticle.indicesLength; - const sind = sortedParticle.ind; - for (let i = 0; i < lind; i++) { - indices32[sid] = indices[sind + i]; - sid++; - if (this._pickable) { - const f = i % 3; - if (f == 0) { - const pickedData = this.pickedParticles[faceId]; - pickedData.idx = sortedParticle.idx; - pickedData.faceId = faceId; - faceId++; - } - } - } - } - } - if (this._autoFixFaceOrientation) { - let particleInd = 0; - for (let particleIdx = 0; particleIdx < this.particles.length; particleIdx++) { - const particle = depthSortParticles ? this.particles[this.depthSortedParticles[particleIdx].idx] : this.particles[particleIdx]; - const flipFaces = particle.scale.x * particle.scale.y * particle.scale.z < 0; - if (flipFaces) { - for (let faceInd = 0; faceInd < particle._model._indicesLength; faceInd += 3) { - const tmp = indices[particle._ind + faceInd]; - indices32[particleInd + faceInd] = indices[particle._ind + faceInd + 1]; - indices32[particleInd + faceInd + 1] = tmp; - } - } - particleInd += particle._model._indicesLength; - } - } - if (depthSortParticles || this._autoFixFaceOrientation) { - mesh.updateIndices(indices32); - } - } - if (this._computeBoundingBox) { - if (mesh.hasBoundingInfo) { - mesh.getBoundingInfo().reConstruct(minimum, maximum, mesh._worldMatrix); - } - else { - mesh.buildBoundingInfo(minimum, maximum, mesh._worldMatrix); - } - } - if (this._autoUpdateSubMeshes) { - this.computeSubMeshes(); - } - this._recomputeInvisibles = false; - this.afterUpdateParticles(start, end, update); - return this; - } - /** - * Disposes the SPS. - */ - dispose() { - this.mesh.dispose(); - this.vars = null; - // drop references to internal big arrays for the GC - this._positions = null; - this._indices = null; - this._normals = null; - this._uvs = null; - this._colors = null; - this._indices32 = null; - this._positions32 = null; - this._normals32 = null; - this._fixedNormal32 = null; - this._uvs32 = null; - this._colors32 = null; - this.pickedParticles = null; - this.pickedBySubMesh = null; - this._materials = null; - this._materialIndexes = null; - this._indicesByMaterial = null; - this._idxOfId = null; - } - /** Returns an object {idx: number faceId: number} for the picked particle from the passed pickingInfo object. - * idx is the particle index in the SPS - * faceId is the picked face index counted within this particle. - * Returns null if the pickInfo can't identify a picked particle. - * @param pickingInfo (PickingInfo object) - * @returns {idx: number, faceId: number} or null - */ - pickedParticle(pickingInfo) { - if (pickingInfo.hit) { - const subMesh = pickingInfo.subMeshId; - const faceId = pickingInfo.faceId - this.mesh.subMeshes[subMesh].indexStart / 3; - const picked = this.pickedBySubMesh; - if (picked[subMesh] && picked[subMesh][faceId]) { - return picked[subMesh][faceId]; - } - } - return null; - } - /** - * Returns a SolidParticle object from its identifier : particle.id - * @param id (integer) the particle Id - * @returns the searched particle or null if not found in the SPS. - */ - getParticleById(id) { - const p = this.particles[id]; - if (p && p.id == id) { - return p; - } - const particles = this.particles; - const idx = this._idxOfId[id]; - if (idx !== undefined) { - return particles[idx]; - } - let i = 0; - const nb = this.nbParticles; - while (i < nb) { - const particle = particles[i]; - if (particle.id == id) { - return particle; - } - i++; - } - return null; - } - /** - * Returns a new array populated with the particles having the passed shapeId. - * @param shapeId (integer) the shape identifier - * @returns a new solid particle array - */ - getParticlesByShapeId(shapeId) { - const ref = []; - this.getParticlesByShapeIdToRef(shapeId, ref); - return ref; - } - /** - * Populates the passed array "ref" with the particles having the passed shapeId. - * @param shapeId the shape identifier - * @returns the SPS - * @param ref - */ - getParticlesByShapeIdToRef(shapeId, ref) { - ref.length = 0; - for (let i = 0; i < this.nbParticles; i++) { - const p = this.particles[i]; - if (p.shapeId == shapeId) { - ref.push(p); - } - } - return this; - } - /** - * Computes the required SubMeshes according the materials assigned to the particles. - * @returns the solid particle system. - * Does nothing if called before the SPS mesh is built. - */ - computeSubMeshes() { - if (!this.mesh || !this._multimaterialEnabled) { - return this; - } - const depthSortedParticles = this.depthSortedParticles; - if (this.particles.length > 0) { - for (let p = 0; p < this.particles.length; p++) { - const part = this.particles[p]; - if (!part.materialIndex) { - part.materialIndex = 0; - } - const sortedPart = depthSortedParticles[p]; - sortedPart.materialIndex = part.materialIndex; - sortedPart.ind = part._ind; - sortedPart.indicesLength = part._model._indicesLength; - sortedPart.idx = part.idx; - } - } - this._sortParticlesByMaterial(); - const indicesByMaterial = this._indicesByMaterial; - const materialIndexes = this._materialIndexes; - const mesh = this.mesh; - mesh.subMeshes = []; - const vcount = mesh.getTotalVertices(); - for (let m = 0; m < materialIndexes.length; m++) { - const start = indicesByMaterial[m]; - const count = indicesByMaterial[m + 1] - start; - const matIndex = materialIndexes[m]; - new SubMesh(matIndex, 0, vcount, start, count, mesh); - } - return this; - } - /** - * Sorts the solid particles by material when MultiMaterial is enabled. - * Updates the indices32 array. - * Updates the indicesByMaterial array. - * Updates the mesh indices array. - * @returns the SPS - * @internal - */ - _sortParticlesByMaterial() { - const indicesByMaterial = [0]; - this._indicesByMaterial = indicesByMaterial; - const materialIndexes = []; - this._materialIndexes = materialIndexes; - const depthSortedParticles = this.depthSortedParticles; - depthSortedParticles.sort(this._materialSortFunction); - const length = depthSortedParticles.length; - const indices32 = this._indices32; - const indices = this._indices; - let subMeshIndex = 0; - let subMeshFaceId = 0; - let sid = 0; - let lastMatIndex = depthSortedParticles[0].materialIndex; - materialIndexes.push(lastMatIndex); - if (this._pickable) { - this.pickedBySubMesh = [[]]; - this.pickedParticles = this.pickedBySubMesh[0]; - } - for (let sorted = 0; sorted < length; sorted++) { - const sortedPart = depthSortedParticles[sorted]; - const lind = sortedPart.indicesLength; - const sind = sortedPart.ind; - if (sortedPart.materialIndex !== lastMatIndex) { - lastMatIndex = sortedPart.materialIndex; - indicesByMaterial.push(sid); - materialIndexes.push(lastMatIndex); - if (this._pickable) { - subMeshIndex++; - this.pickedBySubMesh[subMeshIndex] = []; - subMeshFaceId = 0; - } - } - let faceId = 0; - for (let i = 0; i < lind; i++) { - indices32[sid] = indices[sind + i]; - if (this._pickable) { - const f = i % 3; - if (f == 0) { - const pickedData = this.pickedBySubMesh[subMeshIndex][subMeshFaceId]; - if (pickedData) { - pickedData.idx = sortedPart.idx; - pickedData.faceId = faceId; - } - else { - this.pickedBySubMesh[subMeshIndex][subMeshFaceId] = { idx: sortedPart.idx, faceId: faceId }; - } - subMeshFaceId++; - faceId++; - } - } - sid++; - } - } - indicesByMaterial.push(indices32.length); // add the last number to ease the indices start/count values for subMeshes creation - if (this._updatable) { - this.mesh.updateIndices(indices32); - } - return this; - } - /** - * Sets the material indexes by id materialIndexesById[id] = materialIndex - * @internal - */ - _setMaterialIndexesById() { - this._materialIndexesById = {}; - for (let i = 0; i < this._materials.length; i++) { - const id = this._materials[i].uniqueId; - this._materialIndexesById[id] = i; - } - } - /** - * Returns an array with unique values of Materials from the passed array - * @param array the material array to be checked and filtered - * @internal - */ - _filterUniqueMaterialId(array) { - const filtered = array.filter(function (value, index, self) { - return self.indexOf(value) === index; - }); - return filtered; - } - /** - * Sets a new Standard Material as _defaultMaterial if not already set. - * @internal - */ - _setDefaultMaterial() { - if (!this._defaultMaterial) { - this._defaultMaterial = new StandardMaterial(this.name + "DefaultMaterial", this._scene); - } - return this._defaultMaterial; - } - /** - * Visibility helper : Recomputes the visible size according to the mesh bounding box - * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility - * @returns the SPS. - */ - refreshVisibleSize() { - if (!this._isVisibilityBoxLocked) { - this.mesh.refreshBoundingInfo(); - } - return this; - } - /** - * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box. - * @param size the size (float) of the visibility box - * note : this doesn't lock the SPS mesh bounding box. - * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility - */ - setVisibilityBox(size) { - const vis = size / 2; - this.mesh.buildBoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis)); - } - /** - * Gets whether the SPS as always visible or not - * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility - */ - get isAlwaysVisible() { - return this._alwaysVisible; - } - /** - * Sets the SPS as always visible or not - * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility - */ - set isAlwaysVisible(val) { - this._alwaysVisible = val; - this.mesh.alwaysSelectAsActiveMesh = val; - } - /** - * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. - * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility - */ - set isVisibilityBoxLocked(val) { - this._isVisibilityBoxLocked = val; - const boundingInfo = this.mesh.getBoundingInfo(); - boundingInfo.isLocked = val; - } - /** - * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates. - * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility - */ - get isVisibilityBoxLocked() { - return this._isVisibilityBoxLocked; - } - /** - * Tells to `setParticles()` to compute the particle rotations or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. - */ - set computeParticleRotation(val) { - this._computeParticleRotation = val; - } - /** - * Tells to `setParticles()` to compute the particle colors or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. - */ - set computeParticleColor(val) { - this._computeParticleColor = val; - } - set computeParticleTexture(val) { - this._computeParticleTexture = val; - } - /** - * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not. - * Default value : false. The SPS is faster when it's set to false. - * Note : the particle custom vertex positions aren't stored values. - */ - set computeParticleVertex(val) { - this._computeParticleVertex = val; - } - /** - * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions. - */ - set computeBoundingBox(val) { - this._computeBoundingBox = val; - } - /** - * Tells to `setParticles()` to sort or not the distance between each particle and the camera. - * Skipped when `enableDepthSort` is set to `false` (default) at construction time. - * Default : `true` - */ - set depthSortParticles(val) { - this._depthSortParticles = val; - } - /** - * Gets if `setParticles()` computes the particle rotations or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate. - */ - get computeParticleRotation() { - return this._computeParticleRotation; - } - /** - * Gets if `setParticles()` computes the particle colors or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. - */ - get computeParticleColor() { - return this._computeParticleColor; - } - /** - * Gets if `setParticles()` computes the particle textures or not. - * Default value : true. The SPS is faster when it's set to false. - * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set. - */ - get computeParticleTexture() { - return this._computeParticleTexture; - } - /** - * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not. - * Default value : false. The SPS is faster when it's set to false. - * Note : the particle custom vertex positions aren't stored values. - */ - get computeParticleVertex() { - return this._computeParticleVertex; - } - /** - * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions. - */ - get computeBoundingBox() { - return this._computeBoundingBox; - } - /** - * Gets if `setParticles()` sorts or not the distance between each particle and the camera. - * Skipped when `enableDepthSort` is set to `false` (default) at construction time. - * Default : `true` - */ - get depthSortParticles() { - return this._depthSortParticles; - } - /** - * Gets if the SPS is created as expandable at construction time. - * Default : `false` - */ - get expandable() { - return this._expandable; - } - /** - * Gets if the SPS supports the Multi Materials - */ - get multimaterialEnabled() { - return this._multimaterialEnabled; - } - /** - * Gets if the SPS uses the model materials for its own multimaterial. - */ - get useModelMaterial() { - return this._useModelMaterial; - } - /** - * The SPS used material array. - */ - get materials() { - return this._materials; - } - /** - * Sets the SPS MultiMaterial from the passed materials. - * Note : the passed array is internally copied and not used then by reference. - * @param materials an array of material objects. This array indexes are the materialIndex values of the particles. - */ - setMultiMaterial(materials) { - this._materials = this._filterUniqueMaterialId(materials); - this._setMaterialIndexesById(); - if (this._multimaterial) { - this._multimaterial.dispose(); - } - this._multimaterial = new MultiMaterial(this.name + "MultiMaterial", this._scene); - for (let m = 0; m < this._materials.length; m++) { - this._multimaterial.subMaterials.push(this._materials[m]); - } - this.computeSubMeshes(); - this.mesh.material = this._multimaterial; - } - /** - * The SPS computed multimaterial object - */ - get multimaterial() { - return this._multimaterial; - } - set multimaterial(mm) { - this._multimaterial = mm; - } - /** - * If the subMeshes must be updated on the next call to setParticles() - */ - get autoUpdateSubMeshes() { - return this._autoUpdateSubMeshes; - } - set autoUpdateSubMeshes(val) { - this._autoUpdateSubMeshes = val; - } - // ======================================================================= - // Particle behavior logic - // these following methods may be overwritten by the user to fit his needs - /** - * This function does nothing. It may be overwritten to set all the particle first values. - * The SPS doesn't call this function, you may have to call it by your own. - * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/manage_sps_particles - */ - initParticles() { } - /** - * This function does nothing. It may be overwritten to recycle a particle. - * The SPS doesn't call this function, you may have to call it by your own. - * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/manage_sps_particles - * @param particle The particle to recycle - * @returns the recycled particle - */ - recycleParticle(particle) { - return particle; - } - /** - * Updates a particle : this function should be overwritten by the user. - * It is called on each particle by `setParticles()`. This is the place to code each particle behavior. - * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/manage_sps_particles - * @example : just set a particle position or velocity and recycle conditions - * @param particle The particle to update - * @returns the updated particle - */ - updateParticle(particle) { - return particle; - } - /** - * Updates a vertex of a particle : it can be overwritten by the user. - * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only. - * @param particle the current particle - * @param vertex the current vertex of the current particle : a SolidParticleVertex object - * @param pt the index of the current vertex in the particle shape - * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_vertices - * @example : just set a vertex particle position or color - * @returns the sps - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - updateParticleVertex(particle, vertex, pt) { - return this; - } - /** - * This will be called before any other treatment by `setParticles()` and will be passed three parameters. - * This does nothing and may be overwritten by the user. - * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param update the boolean update value actually passed to setParticles() - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - beforeUpdateParticles(start, stop, update) { } - /** - * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update. - * This will be passed three parameters. - * This does nothing and may be overwritten by the user. - * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param update the boolean update value actually passed to setParticles() - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - afterUpdateParticles(start, stop, update) { } -} -//# sourceMappingURL=solidParticleSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/cloudPoint.js - -/** - * Represents one particle of a points cloud system. - */ -class cloudPoint_CloudPoint { - /** - * Creates a Point Cloud object. - * Don't create particles manually, use instead the PCS internal tools like _addParticle() - * @param particleIndex (integer) is the particle index in the PCS pool. It's also the particle identifier. - * @param group (PointsGroup) is the group the particle belongs to - * @param groupId (integer) is the group identifier in the PCS. - * @param idxInGroup (integer) is the index of the particle in the current point group (ex: the 10th point of addPoints(30)) - * @param pcs defines the PCS it is associated to - */ - constructor(particleIndex, group, groupId, idxInGroup, pcs) { - /** - * particle global index - */ - this.idx = 0; - /** - * The color of the particle - */ - this.color = new Color4(1.0, 1.0, 1.0, 1.0); - /** - * The world space position of the particle. - */ - this.position = Vector3.Zero(); - /** - * The world space rotation of the particle. (Not use if rotationQuaternion is set) - */ - this.rotation = Vector3.Zero(); - /** - * The uv of the particle. - */ - this.uv = new Vector2(0.0, 0.0); - /** - * The current speed of the particle. - */ - this.velocity = Vector3.Zero(); - /** - * The pivot point in the particle local space. - */ - this.pivot = Vector3.Zero(); - /** - * Must the particle be translated from its pivot point in its local space ? - * In this case, the pivot point is set at the origin of the particle local space and the particle is translated. - * Default : false - */ - this.translateFromPivot = false; - /** - * Index of this particle in the global "positions" array (Internal use) - * @internal - */ - this._pos = 0; - /** - * @internal Index of this particle in the global "indices" array (Internal use) - */ - this._ind = 0; - /** - * Group id of this particle - */ - this.groupId = 0; - /** - * Index of the particle in its group id (Internal use) - */ - this.idxInGroup = 0; - /** - * @internal Still set as invisible in order to skip useless computations (Internal use) - */ - this._stillInvisible = false; - /** - * @internal Last computed particle rotation matrix - */ - this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]; - /** - * Parent particle Id, if any. - * Default null. - */ - this.parentId = null; - /** - * @internal Internal global position in the PCS. - */ - this._globalPosition = Vector3.Zero(); - this.idx = particleIndex; - this._group = group; - this.groupId = groupId; - this.idxInGroup = idxInGroup; - this._pcs = pcs; - } - /** - * get point size - */ - get size() { - return this.size; - } - /** - * Set point size - */ - set size(scale) { - this.size = scale; - } - /** - * Legacy support, changed quaternion to rotationQuaternion - */ - get quaternion() { - return this.rotationQuaternion; - } - /** - * Legacy support, changed quaternion to rotationQuaternion - */ - set quaternion(q) { - this.rotationQuaternion = q; - } - /** - * Returns a boolean. True if the particle intersects a mesh, else false - * The intersection is computed on the particle position and Axis Aligned Bounding Box (AABB) or Sphere - * @param target is the object (point or mesh) what the intersection is computed against - * @param isSphere is boolean flag when false (default) bounding box of mesh is used, when true the bounding sphere is used - * @returns true if it intersects - */ - intersectsMesh(target, isSphere) { - if (!target.hasBoundingInfo) { - return false; - } - if (!this._pcs.mesh) { - throw new Error("Point Cloud System doesnt contain the Mesh"); - } - if (isSphere) { - return target.getBoundingInfo().boundingSphere.intersectsPoint(this.position.add(this._pcs.mesh.position)); - } - const bbox = target.getBoundingInfo().boundingBox; - const maxX = bbox.maximumWorld.x; - const minX = bbox.minimumWorld.x; - const maxY = bbox.maximumWorld.y; - const minY = bbox.minimumWorld.y; - const maxZ = bbox.maximumWorld.z; - const minZ = bbox.minimumWorld.z; - const x = this.position.x + this._pcs.mesh.position.x; - const y = this.position.y + this._pcs.mesh.position.y; - const z = this.position.z + this._pcs.mesh.position.z; - return minX <= x && x <= maxX && minY <= y && y <= maxY && minZ <= z && z <= maxZ; - } - /** - * get the rotation matrix of the particle - * @internal - */ - getRotationMatrix(m) { - let quaternion; - if (this.rotationQuaternion) { - quaternion = this.rotationQuaternion; - } - else { - quaternion = TmpVectors.Quaternion[0]; - const rotation = this.rotation; - Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion); - } - quaternion.toRotationMatrix(m); - } -} -/** - * Represents a group of points in a points cloud system - * * PCS internal tool, don't use it manually. - */ -class cloudPoint_PointsGroup { - /** - * Get or set the groupId - * @deprecated Please use groupId instead - */ - get groupID() { - return this.groupId; - } - set groupID(groupID) { - this.groupId = groupID; - } - /** - * Creates a points group object. This is an internal reference to produce particles for the PCS. - * PCS internal tool, don't use it manually. - * @internal - */ - constructor(id, posFunction) { - this.groupId = id; - this._positionFunction = posFunction; - } -} -//# sourceMappingURL=cloudPoint.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/pointsCloudSystem.js - - - - - - - - - - - - -/** Defines the 4 color options */ -var PointColor; -(function (PointColor) { - /** color value */ - PointColor[PointColor["Color"] = 2] = "Color"; - /** uv value */ - PointColor[PointColor["UV"] = 1] = "UV"; - /** random value */ - PointColor[PointColor["Random"] = 0] = "Random"; - /** stated value */ - PointColor[PointColor["Stated"] = 3] = "Stated"; -})(PointColor || (PointColor = {})); -/** - * The PointCloudSystem (PCS) is a single updatable mesh. The points corresponding to the vertices of this big mesh. - * 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. - - * The PointCloudSystem is also a particle system, with each point being a particle. It provides some methods to manage the particles. - * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior. - * - * Full documentation here : TO BE ENTERED - */ -class PointsCloudSystem { - /** - * Gets the particle positions computed by the Point Cloud System - */ - get positions() { - return this._positions32; - } - /** - * Gets the particle colors computed by the Point Cloud System - */ - get colors() { - return this._colors32; - } - /** - * Gets the particle uvs computed by the Point Cloud System - */ - get uvs() { - return this._uvs32; - } - /** - * Creates a PCS (Points Cloud System) object - * @param name (String) is the PCS name, this will be the underlying mesh name - * @param pointSize (number) is the size for each point. Has no effect on a WebGPU engine. - * @param scene (Scene) is the scene in which the PCS is added - * @param options defines the options of the PCS e.g. - * * updatable (optional boolean, default true) : if the PCS must be updatable or immutable - * @param options.updatable - */ - constructor(name, pointSize, scene, options) { - /** - * The PCS array of cloud point objects. Just access each particle as with any classic array. - * Example : var p = SPS.particles[i]; - */ - this.particles = new Array(); - /** - * The PCS total number of particles. Read only. Use PCS.counter instead if you need to set your own value. - */ - this.nbParticles = 0; - /** - * This a counter for your own usage. It's not set by any SPS functions. - */ - this.counter = 0; - /** - * This empty object is intended to store some PCS specific or temporary values in order to lower the Garbage Collector activity. - * Please read : - */ - this.vars = {}; - this._promises = []; - this._positions = new Array(); - this._indices = new Array(); - this._normals = new Array(); - this._colors = new Array(); - this._uvs = new Array(); - this._updatable = true; - this._isVisibilityBoxLocked = false; - this._alwaysVisible = false; - this._groups = new Array(); //start indices for each group of particles - this._groupCounter = 0; - this._computeParticleColor = true; - this._computeParticleTexture = true; - this._computeParticleRotation = true; - this._computeBoundingBox = false; - this._isReady = false; - this.name = name; - this._size = pointSize; - this._scene = scene || EngineStore.LastCreatedScene; - if (options && options.updatable !== undefined) { - this._updatable = options.updatable; - } - else { - this._updatable = true; - } - } - /** - * Builds the PCS underlying mesh. Returns a standard Mesh. - * If no points were added to the PCS, the returned mesh is just a single point. - * @param material The material to use to render the mesh. If not provided, will create a default one - * @returns a promise for the created mesh - */ - buildMeshAsync(material) { - return Promise.all(this._promises).then(() => { - this._isReady = true; - return this._buildMesh(material); - }); - } - /** - * @internal - */ - _buildMesh(material) { - if (this.nbParticles === 0) { - this.addPoints(1); - } - this._positions32 = new Float32Array(this._positions); - this._uvs32 = new Float32Array(this._uvs); - this._colors32 = new Float32Array(this._colors); - const vertexData = new VertexData(); - vertexData.set(this._positions32, VertexBuffer.PositionKind); - if (this._uvs32.length > 0) { - vertexData.set(this._uvs32, VertexBuffer.UVKind); - } - let ec = 0; //emissive color value 0 for UVs, 1 for color - if (this._colors32.length > 0) { - ec = 1; - vertexData.set(this._colors32, VertexBuffer.ColorKind); - } - const mesh = new Mesh(this.name, this._scene); - vertexData.applyToMesh(mesh, this._updatable); - this.mesh = mesh; - // free memory - this._positions = null; - this._uvs = null; - this._colors = null; - if (!this._updatable) { - this.particles.length = 0; - } - let mat = material; - if (!mat) { - mat = new StandardMaterial("point cloud material", this._scene); - mat.emissiveColor = new Color3(ec, ec, ec); - mat.disableLighting = true; - mat.pointsCloud = true; - mat.pointSize = this._size; - } - mesh.material = mat; - return new Promise((resolve) => resolve(mesh)); - } - // adds a new particle object in the particles array - _addParticle(idx, group, groupId, idxInGroup) { - const cp = new CloudPoint(idx, group, groupId, idxInGroup, this); - this.particles.push(cp); - return cp; - } - _randomUnitVector(particle) { - particle.position = new Vector3(Math.random(), Math.random(), Math.random()); - particle.color = new Color4(1, 1, 1, 1); - } - _getColorIndicesForCoord(pointsGroup, x, y, width) { - const imageData = pointsGroup._groupImageData; - const color = y * (width * 4) + x * 4; - const colorIndices = [color, color + 1, color + 2, color + 3]; - const redIndex = colorIndices[0]; - const greenIndex = colorIndices[1]; - const blueIndex = colorIndices[2]; - const alphaIndex = colorIndices[3]; - const redForCoord = imageData[redIndex]; - const greenForCoord = imageData[greenIndex]; - const blueForCoord = imageData[blueIndex]; - const alphaForCoord = imageData[alphaIndex]; - return new Color4(redForCoord / 255, greenForCoord / 255, blueForCoord / 255, alphaForCoord); - } - _setPointsColorOrUV(mesh, pointsGroup, isVolume, colorFromTexture, hasTexture, color, range) { - if (isVolume) { - mesh.updateFacetData(); - } - const boundInfo = mesh.getBoundingInfo(); - const diameter = 2 * boundInfo.boundingSphere.radius; - let meshPos = mesh.getVerticesData(VertexBuffer.PositionKind); - const meshInd = mesh.getIndices(); - const meshUV = mesh.getVerticesData(VertexBuffer.UVKind); - const meshCol = mesh.getVerticesData(VertexBuffer.ColorKind); - const place = Vector3.Zero(); - mesh.computeWorldMatrix(); - const meshMatrix = mesh.getWorldMatrix(); - if (!meshMatrix.isIdentity()) { - meshPos = meshPos.slice(0); - for (let p = 0; p < meshPos.length / 3; p++) { - Vector3.TransformCoordinatesFromFloatsToRef(meshPos[3 * p], meshPos[3 * p + 1], meshPos[3 * p + 2], meshMatrix, place); - meshPos[3 * p] = place.x; - meshPos[3 * p + 1] = place.y; - meshPos[3 * p + 2] = place.z; - } - } - let idxPoints = 0; - let id0 = 0; - let id1 = 0; - let id2 = 0; - let v0X = 0; - let v0Y = 0; - let v0Z = 0; - let v1X = 0; - let v1Y = 0; - let v1Z = 0; - let v2X = 0; - let v2Y = 0; - let v2Z = 0; - const vertex0 = Vector3.Zero(); - const vertex1 = Vector3.Zero(); - const vertex2 = Vector3.Zero(); - const vec0 = Vector3.Zero(); - const vec1 = Vector3.Zero(); - let uv0X = 0; - let uv0Y = 0; - let uv1X = 0; - let uv1Y = 0; - let uv2X = 0; - let uv2Y = 0; - const uv0 = Vector2.Zero(); - const uv1 = Vector2.Zero(); - const uv2 = Vector2.Zero(); - const uvec0 = Vector2.Zero(); - const uvec1 = Vector2.Zero(); - let col0X = 0; - let col0Y = 0; - let col0Z = 0; - let col0A = 0; - let col1X = 0; - let col1Y = 0; - let col1Z = 0; - let col1A = 0; - let col2X = 0; - let col2Y = 0; - let col2Z = 0; - let col2A = 0; - const col0 = Vector4.Zero(); - const col1 = Vector4.Zero(); - const col2 = Vector4.Zero(); - const colvec0 = Vector4.Zero(); - const colvec1 = Vector4.Zero(); - let lamda = 0; - let mu = 0; - range = range ? range : 0; - let facetPoint; - let uvPoint; - let colPoint = new Vector4(0, 0, 0, 0); - let norm = Vector3.Zero(); - let tang = Vector3.Zero(); - let biNorm = Vector3.Zero(); - let angle = 0; - let facetPlaneVec = Vector3.Zero(); - let gap = 0; - let distance = 0; - const ray = new Ray(Vector3.Zero(), new Vector3(1, 0, 0)); - let pickInfo; - let direction = Vector3.Zero(); - for (let index = 0; index < meshInd.length / 3; index++) { - id0 = meshInd[3 * index]; - id1 = meshInd[3 * index + 1]; - id2 = meshInd[3 * index + 2]; - v0X = meshPos[3 * id0]; - v0Y = meshPos[3 * id0 + 1]; - v0Z = meshPos[3 * id0 + 2]; - v1X = meshPos[3 * id1]; - v1Y = meshPos[3 * id1 + 1]; - v1Z = meshPos[3 * id1 + 2]; - v2X = meshPos[3 * id2]; - v2Y = meshPos[3 * id2 + 1]; - v2Z = meshPos[3 * id2 + 2]; - vertex0.set(v0X, v0Y, v0Z); - vertex1.set(v1X, v1Y, v1Z); - vertex2.set(v2X, v2Y, v2Z); - vertex1.subtractToRef(vertex0, vec0); - vertex2.subtractToRef(vertex1, vec1); - if (meshUV) { - uv0X = meshUV[2 * id0]; - uv0Y = meshUV[2 * id0 + 1]; - uv1X = meshUV[2 * id1]; - uv1Y = meshUV[2 * id1 + 1]; - uv2X = meshUV[2 * id2]; - uv2Y = meshUV[2 * id2 + 1]; - uv0.set(uv0X, uv0Y); - uv1.set(uv1X, uv1Y); - uv2.set(uv2X, uv2Y); - uv1.subtractToRef(uv0, uvec0); - uv2.subtractToRef(uv1, uvec1); - } - if (meshCol && colorFromTexture) { - col0X = meshCol[4 * id0]; - col0Y = meshCol[4 * id0 + 1]; - col0Z = meshCol[4 * id0 + 2]; - col0A = meshCol[4 * id0 + 3]; - col1X = meshCol[4 * id1]; - col1Y = meshCol[4 * id1 + 1]; - col1Z = meshCol[4 * id1 + 2]; - col1A = meshCol[4 * id1 + 3]; - col2X = meshCol[4 * id2]; - col2Y = meshCol[4 * id2 + 1]; - col2Z = meshCol[4 * id2 + 2]; - col2A = meshCol[4 * id2 + 3]; - col0.set(col0X, col0Y, col0Z, col0A); - col1.set(col1X, col1Y, col1Z, col1A); - col2.set(col2X, col2Y, col2Z, col2A); - col1.subtractToRef(col0, colvec0); - col2.subtractToRef(col1, colvec1); - } - let width; - let height; - let deltaS; - let deltaV; - let h; - let s; - let v; - let hsvCol; - const statedColor = new Color3(0, 0, 0); - const colPoint3 = new Color3(0, 0, 0); - let pointColors; - let particle; - for (let i = 0; i < pointsGroup._groupDensity[index]; i++) { - idxPoints = this.particles.length; - this._addParticle(idxPoints, pointsGroup, this._groupCounter, index + i); - particle = this.particles[idxPoints]; - //form a point inside the facet v0, v1, v2; - lamda = Scalar.RandomRange(0, 1); - mu = Scalar.RandomRange(0, 1); - facetPoint = vertex0.add(vec0.scale(lamda)).add(vec1.scale(lamda * mu)); - if (isVolume) { - norm = mesh.getFacetNormal(index).normalize().scale(-1); - tang = vec0.clone().normalize(); - biNorm = Vector3.Cross(norm, tang); - angle = Scalar.RandomRange(0, 2 * Math.PI); - facetPlaneVec = tang.scale(Math.cos(angle)).add(biNorm.scale(Math.sin(angle))); - angle = Scalar.RandomRange(0.1, Math.PI / 2); - direction = facetPlaneVec.scale(Math.cos(angle)).add(norm.scale(Math.sin(angle))); - ray.origin = facetPoint.add(direction.scale(0.00001)); - ray.direction = direction; - ray.length = diameter; - pickInfo = ray.intersectsMesh(mesh); - if (pickInfo.hit) { - distance = pickInfo.pickedPoint.subtract(facetPoint).length(); - gap = Scalar.RandomRange(0, 1) * distance; - facetPoint.addInPlace(direction.scale(gap)); - } - } - particle.position = facetPoint.clone(); - this._positions.push(particle.position.x, particle.position.y, particle.position.z); - if (colorFromTexture !== undefined) { - if (meshUV) { - uvPoint = uv0.add(uvec0.scale(lamda)).add(uvec1.scale(lamda * mu)); - if (colorFromTexture) { - //Set particle color to texture color - if (hasTexture && pointsGroup._groupImageData !== null) { - width = pointsGroup._groupImgWidth; - height = pointsGroup._groupImgHeight; - pointColors = this._getColorIndicesForCoord(pointsGroup, Math.round(uvPoint.x * width), Math.round(uvPoint.y * height), width); - particle.color = pointColors; - this._colors.push(pointColors.r, pointColors.g, pointColors.b, pointColors.a); - } - else { - if (meshCol) { - //failure in texture and colors available - colPoint = col0.add(colvec0.scale(lamda)).add(colvec1.scale(lamda * mu)); - particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w); - this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w); - } - else { - colPoint = col0.set(Math.random(), Math.random(), Math.random(), 1); - particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w); - this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w); - } - } - } - else { - //Set particle uv based on a mesh uv - particle.uv = uvPoint.clone(); - this._uvs.push(particle.uv.x, particle.uv.y); - } - } - } - else { - if (color) { - statedColor.set(color.r, color.g, color.b); - deltaS = Scalar.RandomRange(-range, range); - deltaV = Scalar.RandomRange(-range, range); - hsvCol = statedColor.toHSV(); - h = hsvCol.r; - s = hsvCol.g + deltaS; - v = hsvCol.b + deltaV; - if (s < 0) { - s = 0; - } - if (s > 1) { - s = 1; - } - if (v < 0) { - v = 0; - } - if (v > 1) { - v = 1; - } - Color3.HSVtoRGBToRef(h, s, v, colPoint3); - colPoint.set(colPoint3.r, colPoint3.g, colPoint3.b, 1); - } - else { - colPoint = col0.set(Math.random(), Math.random(), Math.random(), 1); - } - particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w); - this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w); - } - } - } - } - // stores mesh texture in dynamic texture for color pixel retrieval - // when pointColor type is color for surface points - _colorFromTexture(mesh, pointsGroup, isVolume) { - if (mesh.material === null) { - Logger.Warn(mesh.name + "has no material."); - pointsGroup._groupImageData = null; - this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false); - return; - } - const mat = mesh.material; - const textureList = mat.getActiveTextures(); - if (textureList.length === 0) { - Logger.Warn(mesh.name + "has no usable texture."); - pointsGroup._groupImageData = null; - this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false); - return; - } - const clone = mesh.clone(); - clone.setEnabled(false); - this._promises.push(new Promise((resolve) => { - BaseTexture.WhenAllReady(textureList, () => { - let n = pointsGroup._textureNb; - if (n < 0) { - n = 0; - } - if (n > textureList.length - 1) { - n = textureList.length - 1; - } - const finalize = () => { - pointsGroup._groupImgWidth = textureList[n].getSize().width; - pointsGroup._groupImgHeight = textureList[n].getSize().height; - this._setPointsColorOrUV(clone, pointsGroup, isVolume, true, true); - clone.dispose(); - resolve(); - }; - pointsGroup._groupImageData = null; - const dataPromise = textureList[n].readPixels(); - if (!dataPromise) { - finalize(); - } - else { - dataPromise.then((data) => { - pointsGroup._groupImageData = data; - finalize(); - }); - } - }); - })); - } - // calculates the point density per facet of a mesh for surface points - _calculateDensity(nbPoints, positions, indices) { - let density = new Array(); - let id0; - let id1; - let id2; - let v0X; - let v0Y; - let v0Z; - let v1X; - let v1Y; - let v1Z; - let v2X; - let v2Y; - let v2Z; - const vertex0 = Vector3.Zero(); - const vertex1 = Vector3.Zero(); - const vertex2 = Vector3.Zero(); - const vec0 = Vector3.Zero(); - const vec1 = Vector3.Zero(); - const vec2 = Vector3.Zero(); - let a; //length of side of triangle - let b; //length of side of triangle - let c; //length of side of triangle - let p; //perimeter of triangle - let area; - const areas = new Array(); - let surfaceArea = 0; - const nbFacets = indices.length / 3; - //surface area - for (let index = 0; index < nbFacets; index++) { - id0 = indices[3 * index]; - id1 = indices[3 * index + 1]; - id2 = indices[3 * index + 2]; - v0X = positions[3 * id0]; - v0Y = positions[3 * id0 + 1]; - v0Z = positions[3 * id0 + 2]; - v1X = positions[3 * id1]; - v1Y = positions[3 * id1 + 1]; - v1Z = positions[3 * id1 + 2]; - v2X = positions[3 * id2]; - v2Y = positions[3 * id2 + 1]; - v2Z = positions[3 * id2 + 2]; - vertex0.set(v0X, v0Y, v0Z); - vertex1.set(v1X, v1Y, v1Z); - vertex2.set(v2X, v2Y, v2Z); - vertex1.subtractToRef(vertex0, vec0); - vertex2.subtractToRef(vertex1, vec1); - vertex2.subtractToRef(vertex0, vec2); - a = vec0.length(); - b = vec1.length(); - c = vec2.length(); - p = (a + b + c) / 2; - area = Math.sqrt(p * (p - a) * (p - b) * (p - c)); - surfaceArea += area; - areas[index] = area; - } - let pointCount = 0; - for (let index = 0; index < nbFacets; index++) { - density[index] = Math.floor((nbPoints * areas[index]) / surfaceArea); - pointCount += density[index]; - } - const diff = nbPoints - pointCount; - const pointsPerFacet = Math.floor(diff / nbFacets); - const extraPoints = diff % nbFacets; - if (pointsPerFacet > 0) { - density = density.map((x) => x + pointsPerFacet); - } - for (let index = 0; index < extraPoints; index++) { - density[index] += 1; - } - return density; - } - /** - * Adds points to the PCS in random positions within a unit sphere - * @param nb (positive integer) the number of particles to be created from this model - * @param pointFunction is an optional javascript function to be called for each particle on PCS creation - * @returns the number of groups in the system - */ - addPoints(nb, pointFunction = this._randomUnitVector) { - const pointsGroup = new PointsGroup(this._groupCounter, pointFunction); - let cp; - // particles - let idx = this.nbParticles; - for (let i = 0; i < nb; i++) { - cp = this._addParticle(idx, pointsGroup, this._groupCounter, i); - if (pointsGroup && pointsGroup._positionFunction) { - pointsGroup._positionFunction(cp, idx, i); - } - this._positions.push(cp.position.x, cp.position.y, cp.position.z); - if (cp.color) { - this._colors.push(cp.color.r, cp.color.g, cp.color.b, cp.color.a); - } - if (cp.uv) { - this._uvs.push(cp.uv.x, cp.uv.y); - } - idx++; - } - this.nbParticles += nb; - this._groupCounter++; - return this._groupCounter; - } - /** - * Adds points to the PCS from the surface of the model shape - * @param mesh is any Mesh object that will be used as a surface model for the points - * @param nb (positive integer) the number of particles to be created from this model - * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible) - * @param color (color4) to be used when colorWith is stated or color (number) when used to specify texture position - * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color - * @returns the number of groups in the system - */ - addSurfacePoints(mesh, nb, colorWith, color, range) { - let colored = colorWith ? colorWith : PointColor.Random; - if (isNaN(colored) || colored < 0 || colored > 3) { - colored = PointColor.Random; - } - const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind); - const meshInd = mesh.getIndices(); - this._groups.push(this._groupCounter); - const pointsGroup = new PointsGroup(this._groupCounter, null); - pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd); - if (colored === PointColor.Color) { - pointsGroup._textureNb = color ? color : 0; - } - else { - color = color ? color : new Color4(1, 1, 1, 1); - } - switch (colored) { - case PointColor.Color: - this._colorFromTexture(mesh, pointsGroup, false); - break; - case PointColor.UV: - this._setPointsColorOrUV(mesh, pointsGroup, false, false, false); - break; - case PointColor.Random: - this._setPointsColorOrUV(mesh, pointsGroup, false); - break; - case PointColor.Stated: - this._setPointsColorOrUV(mesh, pointsGroup, false, undefined, undefined, color, range); - break; - } - this.nbParticles += nb; - this._groupCounter++; - return this._groupCounter - 1; - } - /** - * Adds points to the PCS inside the model shape - * @param mesh is any Mesh object that will be used as a surface model for the points - * @param nb (positive integer) the number of particles to be created from this model - * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible) - * @param color (color4) to be used when colorWith is stated or color (number) when used to specify texture position - * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color - * @returns the number of groups in the system - */ - addVolumePoints(mesh, nb, colorWith, color, range) { - let colored = colorWith ? colorWith : PointColor.Random; - if (isNaN(colored) || colored < 0 || colored > 3) { - colored = PointColor.Random; - } - const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind); - const meshInd = mesh.getIndices(); - this._groups.push(this._groupCounter); - const pointsGroup = new PointsGroup(this._groupCounter, null); - pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd); - if (colored === PointColor.Color) { - pointsGroup._textureNb = color ? color : 0; - } - else { - color = color ? color : new Color4(1, 1, 1, 1); - } - switch (colored) { - case PointColor.Color: - this._colorFromTexture(mesh, pointsGroup, true); - break; - case PointColor.UV: - this._setPointsColorOrUV(mesh, pointsGroup, true, false, false); - break; - case PointColor.Random: - this._setPointsColorOrUV(mesh, pointsGroup, true); - break; - case PointColor.Stated: - this._setPointsColorOrUV(mesh, pointsGroup, true, undefined, undefined, color, range); - break; - } - this.nbParticles += nb; - this._groupCounter++; - return this._groupCounter - 1; - } - /** - * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc. - * This method calls `updateParticle()` for each particle of the SPS. - * For an animated SPS, it is usually called within the render loop. - * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_ - * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_ - * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_ - * @returns the PCS. - */ - setParticles(start = 0, end = this.nbParticles - 1, update = true) { - var _a, _b; - if (!this._updatable || !this._isReady) { - return this; - } - // custom beforeUpdate - this.beforeUpdateParticles(start, end, update); - const rotMatrix = TmpVectors.Matrix[0]; - const mesh = this.mesh; - const colors32 = this._colors32; - const positions32 = this._positions32; - const uvs32 = this._uvs32; - const tempVectors = TmpVectors.Vector3; - const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0); - const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0); - const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0); - const minimum = tempVectors[8].setAll(Number.MAX_VALUE); - const maximum = tempVectors[9].setAll(-Number.MAX_VALUE); - Matrix.IdentityToRef(rotMatrix); - let idx = 0; // current index of the particle - if ((_a = this.mesh) === null || _a === void 0 ? void 0 : _a.isFacetDataEnabled) { - this._computeBoundingBox = true; - } - end = end >= this.nbParticles ? this.nbParticles - 1 : end; - if (this._computeBoundingBox) { - if (start != 0 || end != this.nbParticles - 1) { - // only some particles are updated, then use the current existing BBox basis. Note : it can only increase. - const boundingInfo = (_b = this.mesh) === null || _b === void 0 ? void 0 : _b.getBoundingInfo(); - if (boundingInfo) { - minimum.copyFrom(boundingInfo.minimum); - maximum.copyFrom(boundingInfo.maximum); - } - } - } - idx = 0; // particle index - let pindex = 0; //index in positions array - let cindex = 0; //index in color array - let uindex = 0; //index in uv array - // particle loop - for (let p = start; p <= end; p++) { - const particle = this.particles[p]; - idx = particle.idx; - pindex = 3 * idx; - cindex = 4 * idx; - uindex = 2 * idx; - // call to custom user function to update the particle properties - this.updateParticle(particle); - const particleRotationMatrix = particle._rotationMatrix; - const particlePosition = particle.position; - const particleGlobalPosition = particle._globalPosition; - if (this._computeParticleRotation) { - particle.getRotationMatrix(rotMatrix); - } - const particleHasParent = particle.parentId !== null; - if (particleHasParent) { - const parent = this.particles[particle.parentId]; - const parentRotationMatrix = parent._rotationMatrix; - const parentGlobalPosition = parent._globalPosition; - const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7]; - const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6]; - const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8]; - particleGlobalPosition.x = parentGlobalPosition.x + rotatedX; - particleGlobalPosition.y = parentGlobalPosition.y + rotatedY; - particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ; - if (this._computeParticleRotation) { - const rotMatrixValues = rotMatrix.m; - particleRotationMatrix[0] = - rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6]; - particleRotationMatrix[1] = - rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7]; - particleRotationMatrix[2] = - rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8]; - particleRotationMatrix[3] = - rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6]; - particleRotationMatrix[4] = - rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7]; - particleRotationMatrix[5] = - rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8]; - particleRotationMatrix[6] = - rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6]; - particleRotationMatrix[7] = - rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7]; - particleRotationMatrix[8] = - rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8]; - } - } - else { - particleGlobalPosition.x = 0; - particleGlobalPosition.y = 0; - particleGlobalPosition.z = 0; - if (this._computeParticleRotation) { - const rotMatrixValues = rotMatrix.m; - particleRotationMatrix[0] = rotMatrixValues[0]; - particleRotationMatrix[1] = rotMatrixValues[1]; - particleRotationMatrix[2] = rotMatrixValues[2]; - particleRotationMatrix[3] = rotMatrixValues[4]; - particleRotationMatrix[4] = rotMatrixValues[5]; - particleRotationMatrix[5] = rotMatrixValues[6]; - particleRotationMatrix[6] = rotMatrixValues[8]; - particleRotationMatrix[7] = rotMatrixValues[9]; - particleRotationMatrix[8] = rotMatrixValues[10]; - } - } - const pivotBackTranslation = tempVectors[11]; - if (particle.translateFromPivot) { - pivotBackTranslation.setAll(0.0); - } - else { - pivotBackTranslation.copyFrom(particle.pivot); - } - // positions - const tmpVertex = tempVectors[0]; - tmpVertex.copyFrom(particle.position); - const vertexX = tmpVertex.x - particle.pivot.x; - const vertexY = tmpVertex.y - particle.pivot.y; - const vertexZ = tmpVertex.z - particle.pivot.z; - let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6]; - let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7]; - let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8]; - rotatedX += pivotBackTranslation.x; - rotatedY += pivotBackTranslation.y; - rotatedZ += pivotBackTranslation.z; - const px = (positions32[pindex] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ); - const py = (positions32[pindex + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ); - const pz = (positions32[pindex + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ); - if (this._computeBoundingBox) { - minimum.minimizeInPlaceFromFloats(px, py, pz); - maximum.maximizeInPlaceFromFloats(px, py, pz); - } - if (this._computeParticleColor && particle.color) { - const color = particle.color; - const colors32 = this._colors32; - colors32[cindex] = color.r; - colors32[cindex + 1] = color.g; - colors32[cindex + 2] = color.b; - colors32[cindex + 3] = color.a; - } - if (this._computeParticleTexture && particle.uv) { - const uv = particle.uv; - const uvs32 = this._uvs32; - uvs32[uindex] = uv.x; - uvs32[uindex + 1] = uv.y; - } - } - // if the VBO must be updated - if (mesh) { - if (update) { - if (this._computeParticleColor) { - mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false); - } - if (this._computeParticleTexture) { - mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false); - } - mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false); - } - if (this._computeBoundingBox) { - if (mesh.hasBoundingInfo) { - mesh.getBoundingInfo().reConstruct(minimum, maximum, mesh._worldMatrix); - } - else { - mesh.buildBoundingInfo(minimum, maximum, mesh._worldMatrix); - } - } - } - this.afterUpdateParticles(start, end, update); - return this; - } - /** - * Disposes the PCS. - */ - dispose() { - var _a; - (_a = this.mesh) === null || _a === void 0 ? void 0 : _a.dispose(); - this.vars = null; - // drop references to internal big arrays for the GC - this._positions = null; - this._indices = null; - this._normals = null; - this._uvs = null; - this._colors = null; - this._indices32 = null; - this._positions32 = null; - this._uvs32 = null; - this._colors32 = null; - } - /** - * Visibility helper : Recomputes the visible size according to the mesh bounding box - * doc : - * @returns the PCS. - */ - refreshVisibleSize() { - var _a; - if (!this._isVisibilityBoxLocked) { - (_a = this.mesh) === null || _a === void 0 ? void 0 : _a.refreshBoundingInfo(); - } - return this; - } - /** - * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box. - * @param size the size (float) of the visibility box - * note : this doesn't lock the PCS mesh bounding box. - * doc : - */ - setVisibilityBox(size) { - if (!this.mesh) { - return; - } - const vis = size / 2; - this.mesh.buildBoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis)); - } - /** - * Gets whether the PCS is always visible or not - * doc : - */ - get isAlwaysVisible() { - return this._alwaysVisible; - } - /** - * Sets the PCS as always visible or not - * doc : - */ - set isAlwaysVisible(val) { - if (!this.mesh) { - return; - } - this._alwaysVisible = val; - this.mesh.alwaysSelectAsActiveMesh = val; - } - /** - * Tells to `setParticles()` to compute the particle rotations or not - * Default value : false. The PCS is faster when it's set to false - * Note : particle rotations are only applied to parent particles - * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate - */ - set computeParticleRotation(val) { - this._computeParticleRotation = val; - } - /** - * Tells to `setParticles()` to compute the particle colors or not. - * Default value : true. The PCS is faster when it's set to false. - * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. - */ - set computeParticleColor(val) { - this._computeParticleColor = val; - } - set computeParticleTexture(val) { - this._computeParticleTexture = val; - } - /** - * Gets if `setParticles()` computes the particle colors or not. - * Default value : false. The PCS is faster when it's set to false. - * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set. - */ - get computeParticleColor() { - return this._computeParticleColor; - } - /** - * Gets if `setParticles()` computes the particle textures or not. - * Default value : false. The PCS is faster when it's set to false. - * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set. - */ - get computeParticleTexture() { - return this._computeParticleTexture; - } - /** - * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions. - */ - set computeBoundingBox(val) { - this._computeBoundingBox = val; - } - /** - * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions. - */ - get computeBoundingBox() { - return this._computeBoundingBox; - } - // ======================================================================= - // Particle behavior logic - // these following methods may be overwritten by users to fit their needs - /** - * This function does nothing. It may be overwritten to set all the particle first values. - * The PCS doesn't call this function, you may have to call it by your own. - * doc : - */ - initParticles() { } - /** - * This function does nothing. It may be overwritten to recycle a particle - * The PCS doesn't call this function, you can to call it - * doc : - * @param particle The particle to recycle - * @returns the recycled particle - */ - recycleParticle(particle) { - return particle; - } - /** - * Updates a particle : this function should be overwritten by the user. - * It is called on each particle by `setParticles()`. This is the place to code each particle behavior. - * doc : - * @example : just set a particle position or velocity and recycle conditions - * @param particle The particle to update - * @returns the updated particle - */ - updateParticle(particle) { - return particle; - } - /** - * This will be called before any other treatment by `setParticles()` and will be passed three parameters. - * This does nothing and may be overwritten by the user. - * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle() - * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param update the boolean update value actually passed to setParticles() - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - beforeUpdateParticles(start, stop, update) { } - /** - * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update. - * This will be passed three parameters. - * This does nothing and may be overwritten by the user. - * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle() - * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle() - * @param update the boolean update value actually passed to setParticles() - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - afterUpdateParticles(start, stop, update) { } -} -//# sourceMappingURL=pointsCloudSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Particles/index.js -/* eslint-disable import/export */ -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - -// eslint-disable-next-line no-duplicate-imports - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v1/IPhysicsEnginePlugin.js - -//# sourceMappingURL=IPhysicsEnginePlugin.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v1/physicsEngineComponent.js - - -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "physicsImpostor", { - get: function () { - return this._physicsImpostor; - }, - set: function (value) { - if (this._physicsImpostor === value) { - return; - } - if (this._disposePhysicsObserver) { - this.onDisposeObservable.remove(this._disposePhysicsObserver); - } - this._physicsImpostor = value; - if (value) { - this._disposePhysicsObserver = this.onDisposeObservable.add(() => { - // Physics - if (this.physicsImpostor) { - this.physicsImpostor.dispose( /*!doNotRecurse*/); - this.physicsImpostor = null; - } - }); - } - }, - enumerable: true, - configurable: true, -}); -/** - * Gets the current physics impostor - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics - * @returns a physics impostor or null - */ -abstractMesh_AbstractMesh.prototype.getPhysicsImpostor = function () { - return this.physicsImpostor; -}; -/** - * Apply a physic impulse to the mesh - * @param force defines the force to apply - * @param contactPoint defines where to apply the force - * @returns the current mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -abstractMesh_AbstractMesh.prototype.applyImpulse = function (force, contactPoint) { - if (!this.physicsImpostor) { - return this; - } - this.physicsImpostor.applyImpulse(force, contactPoint); - return this; -}; -/** - * Creates a physic joint between two meshes - * @param otherMesh defines the other mesh to use - * @param pivot1 defines the pivot to use on this mesh - * @param pivot2 defines the pivot to use on the other mesh - * @param options defines additional options (can be plugin dependent) - * @returns the current mesh - * @see https://www.babylonjs-playground.com/#0BS5U0#0 - */ -abstractMesh_AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) { - if (!this.physicsImpostor || !otherMesh.physicsImpostor) { - return this; - } - this.physicsImpostor.createJoint(otherMesh.physicsImpostor, PhysicsJoint.HingeJoint, { - mainPivot: pivot1, - connectedPivot: pivot2, - nativeParams: options, - }); - return this; -}; -//# sourceMappingURL=physicsEngineComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v1/Plugins/index.js - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v1/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/physicsEngine.js - - - -/** - * Class used to control physics engine - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -class physicsEngine_PhysicsEngine { - /** - * - * @returns physics plugin version - */ - getPluginVersion() { - return this._physicsPlugin.getPluginVersion(); - } - /** - * Factory used to create the default physics plugin. - * @returns The default physics plugin - */ - static DefaultPluginFactory() { - throw _WarnImport(""); - } - /** - * Creates a new Physics Engine - * @param gravity defines the gravity vector used by the simulation - * @param _physicsPlugin defines the plugin to use (CannonJS by default) - */ - constructor(gravity, _physicsPlugin = physicsEngine_PhysicsEngine.DefaultPluginFactory()) { - this._physicsPlugin = _physicsPlugin; - /** @internal */ - this._physicsBodies = []; - this._subTimeStep = 0; - gravity = gravity || new math_vector_Vector3(0, -9.807, 0); - this.setGravity(gravity); - this.setTimeStep(); - } - /** - * Sets the gravity vector used by the simulation - * @param gravity defines the gravity vector to use - */ - setGravity(gravity) { - this.gravity = gravity; - this._physicsPlugin.setGravity(this.gravity); - } - /** - * Set the time step of the physics engine. - * Default is 1/60. - * To slow it down, enter 1/600 for example. - * To speed it up, 1/30 - * @param newTimeStep defines the new timestep to apply to this world. - */ - setTimeStep(newTimeStep = 1 / 60) { - this._physicsPlugin.setTimeStep(newTimeStep); - } - /** - * Get the time step of the physics engine. - * @returns the current time step - */ - getTimeStep() { - return this._physicsPlugin.getTimeStep(); - } - /** - * Set the sub time step of the physics engine. - * Default is 0 meaning there is no sub steps - * To increase physics resolution precision, set a small value (like 1 ms) - * @param subTimeStep defines the new sub timestep used for physics resolution. - */ - setSubTimeStep(subTimeStep = 0) { - this._subTimeStep = subTimeStep; - } - /** - * Get the sub time step of the physics engine. - * @returns the current sub time step - */ - getSubTimeStep() { - return this._subTimeStep; - } - /** - * Release all resources - */ - dispose() { - this._physicsPlugin.dispose(); - } - /** - * Gets the name of the current physics plugin - * @returns the name of the plugin - */ - getPhysicsPluginName() { - return this._physicsPlugin.name; - } - /** - * Adding a new impostor for the impostor tracking. - * This will be done by the impostor itself. - * @param impostor the impostor to add - */ - /** - * Called by the scene. No need to call it. - * @param delta defines the timespan between frames - */ - _step(delta) { - if (delta > 0.1) { - delta = 0.1; - } - else if (delta <= 0) { - delta = 1.0 / 60.0; - } - this._physicsPlugin.executeStep(delta, this._physicsBodies); - } - /** - * Add a body as an active component of this engine - * @param body - */ - addBody(physicsBody) { - this._physicsBodies.push(physicsBody); - } - /** - * Removes a particular body from this engine - */ - removeBody(physicsBody) { - const index = this._physicsBodies.indexOf(physicsBody); - if (index > -1) { - /*const removed =*/ this._physicsBodies.splice(index, 1); - } - } - /** - * Returns an array of bodies added to this engine - - */ - getBodies() { - return this._physicsBodies; - } - /** - * Gets the current plugin used to run the simulation - * @returns current plugin - */ - getPhysicsPlugin() { - return this._physicsPlugin; - } - /** - * Does a raycast in the physics world - * @param from when should the ray start? - * @param to when should the ray end? - * @param result resulting PhysicsRaycastResult - */ - raycastToRef(from, to, result, query) { - this._physicsPlugin.raycast(from, to, result, query); - } - /** - * Does a raycast in the physics world - * @param from when should the ray start? - * @param to when should the ray end? - * @returns PhysicsRaycastResult - */ - raycast(from, to, query) { - const result = new PhysicsRaycastResult(); - this._physicsPlugin.raycast(from, to, result, query); - return result; - } -} -//# sourceMappingURL=physicsEngine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/physicsBody.js - - -/** - * PhysicsBody is useful for creating a physics body that can be used in a physics engine. It allows - * the user to set the mass and velocity of the body, which can then be used to calculate the - * motion of the body in the physics engine. - */ -class physicsBody_PhysicsBody { - /** - * Constructs a new physics body for the given node. - * @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. - * @param motionType - The motion type of the physics body. The options are: - * - PhysicsMotionType.STATIC - Static bodies are not moving and unaffected by forces or collisions. They are good for level boundaries or terrain. - * - PhysicsMotionType.DYNAMIC - Dynamic bodies are fully simulated. They can move and collide with other objects. - * - 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. - * @param startsAsleep - Whether the physics body should start in a sleeping state (not a guarantee). Defaults to false. - * @param scene - The scene containing the physics engine. - * - * This code is useful for creating a physics body for a given Transform Node in a scene. - * It checks the version of the physics engine and the physics plugin, and initializes the body accordingly. - * It also sets the node's rotation quaternion if it is not already set. Finally, it adds the body to the physics engine. - */ - constructor(transformNode, motionType, startsAsleep, scene) { - /** - * V2 Physics plugin private data for single Transform - */ - this._pluginData = undefined; - /** - * V2 Physics plugin private data for instances - */ - this._pluginDataInstances = []; - /** - * If the collision callback is enabled - */ - this._collisionCBEnabled = false; - /** - * Disable pre-step that consists in updating Physics Body from Transform Node Translation/Orientation. - * True by default for maximum performance. - */ - this.disablePreStep = true; - if (!scene) { - return; - } - const physicsEngine = scene.getPhysicsEngine(); - if (!physicsEngine) { - throw new Error("No Physics Engine available."); - } - this._physicsEngine = physicsEngine; - if (physicsEngine.getPluginVersion() != 2) { - throw new Error("Plugin version is incorrect. Expected version 2."); - } - const physicsPlugin = physicsEngine.getPhysicsPlugin(); - if (!physicsPlugin) { - throw new Error("No Physics Plugin available."); - } - this._physicsPlugin = physicsPlugin; - if (!transformNode.rotationQuaternion) { - transformNode.rotationQuaternion = Quaternion.FromEulerAngles(transformNode.rotation.x, transformNode.rotation.y, transformNode.rotation.z); - } - this.startAsleep = startsAsleep; - // instances? - const m = transformNode; - if (m.hasThinInstances) { - this._physicsPlugin.initBodyInstances(this, motionType, m); - } - else { - // single instance - if (transformNode.parent) { - // Force computation of world matrix so that the parent transforms are correctly reflected in absolutePosition/absoluteRotationQuaternion. - transformNode.computeWorldMatrix(true); - } - this._physicsPlugin.initBody(this, motionType, transformNode.absolutePosition, transformNode.absoluteRotationQuaternion); - } - this.transformNode = transformNode; - transformNode.physicsBody = this; - physicsEngine.addBody(this); - this._nodeDisposeObserver = transformNode.onDisposeObservable.add(() => { - this.dispose(); - }); - } - /** - * Returns the string "PhysicsBody". - * @returns "PhysicsBody" - */ - getClassName() { - return "PhysicsBody"; - } - /** - * Clone the PhysicsBody to a new body and assign it to the transformNode parameter - * @param transformNode transformNode that will be used for the cloned PhysicsBody - * @returns the newly cloned PhysicsBody - */ - clone(transformNode) { - const clonedBody = new physicsBody_PhysicsBody(transformNode, this.getMotionType(), this.startAsleep, this.transformNode.getScene()); - clonedBody.shape = this.shape; - clonedBody.setMassProperties(this.getMassProperties()); - clonedBody.setLinearDamping(this.getLinearDamping()); - clonedBody.setAngularDamping(this.getAngularDamping()); - return clonedBody; - } - /** - * If a physics body is connected to an instanced node, update the number physic instances to match the number of node instances. - */ - updateBodyInstances() { - const m = this.transformNode; - if (m.hasThinInstances) { - this._physicsPlugin.updateBodyInstances(this, m); - } - } - /** - * This returns the number of internal instances of the physics body - */ - get numInstances() { - return this._pluginDataInstances.length; - } - /** - * Sets the shape of the physics body. - * @param shape - The shape of the physics body. - * - * 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. - * The shape is used to calculate the body's mass, inertia, and other properties. - */ - set shape(shape) { - this._physicsPlugin.setShape(this, shape); - } - /** - * Retrieves the physics shape associated with this object. - * - * @returns The physics shape associated with this object, or `undefined` if no - * shape is associated. - * - * This method is useful for retrieving the physics shape associated with this object, - * which can be used to apply physical forces to the object or to detect collisions. - */ - get shape() { - return this._physicsPlugin.getShape(this); - } - /** - * Sets the event mask for the physics engine. - * - * @param eventMask - A bitmask that determines which events will be sent to the physics engine. - * - * This method is useful for setting the event mask for the physics engine, which determines which events - * will be sent to the physics engine. This allows the user to control which events the physics engine will respond to. - */ - setEventMask(eventMask, instanceIndex) { - this._physicsPlugin.setEventMask(this, eventMask, instanceIndex); - } - /** - * Gets the event mask of the physics engine. - * - * @returns The event mask of the physics engine. - * - * This method is useful for getting the event mask of the physics engine, - * which is used to determine which events the engine will respond to. - * This is important for ensuring that the engine is responding to the correct events and not - * wasting resources on unnecessary events. - */ - getEventMask(instanceIndex) { - return this._physicsPlugin.getEventMask(this, instanceIndex); - } - /** - * Sets the motion type of the physics body. Can be STATIC, DYNAMIC, or ANIMATED. - */ - setMotionType(motionType, instanceIndex) { - this._physicsPlugin.setMotionType(this, motionType, instanceIndex); - } - /** - * Gets the motion type of the physics body. Can be STATIC, DYNAMIC, or ANIMATED. - */ - getMotionType(instanceIndex) { - return this._physicsPlugin.getMotionType(this, instanceIndex); - } - /** - * Computes the mass properties of the physics object, based on the set of physics shapes this body uses. - * This method is useful for computing the initial mass properties of a physics object, such as its mass, - * inertia, and center of mass; these values are important for accurately simulating the physics of the - * object in the physics engine, and computing values based on the shape will provide you with reasonable - * intial values, which you can then customize. - */ - computeMassProperties(instanceIndex) { - return this._physicsPlugin.computeMassProperties(this, instanceIndex); - } - /** - * Sets the mass properties of the physics object. - * - * @param massProps - The mass properties to set. - * @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. - * - * This method is useful for setting the mass properties of a physics object, such as its mass, - * inertia, and center of mass. This is important for accurately simulating the physics of the object in the physics engine. - */ - setMassProperties(massProps, instanceIndex) { - this._physicsPlugin.setMassProperties(this, massProps, instanceIndex); - } - /** - * Retrieves the mass properties of the object. - * - * @returns The mass properties of the object. - * - * This method is useful for physics simulations, as it allows the user to - * retrieve the mass properties of the object, such as its mass, center of mass, - * and moment of inertia. This information is necessary for accurate physics - * simulations. - */ - getMassProperties(instanceIndex) { - return this._physicsPlugin.getMassProperties(this, instanceIndex); - } - /** - * Sets the linear damping of the physics body. - * - * @param damping - The linear damping value. - * - * This method is useful for controlling the linear damping of the physics body, - * which is the rate at which the body's velocity decreases over time. This is useful for simulating - * the effects of air resistance or other forms of friction. - */ - setLinearDamping(damping, instanceIndex) { - this._physicsPlugin.setLinearDamping(this, damping, instanceIndex); - } - /** - * Gets the linear damping of the physics body. - * @returns The linear damping of the physics body. - * - * This method is useful for retrieving the linear damping of the physics body, which is the amount of - * resistance the body has to linear motion. This is useful for simulating realistic physics behavior - * in a game. - */ - getLinearDamping(instanceIndex) { - return this._physicsPlugin.getLinearDamping(this, instanceIndex); - } - /** - * Sets the angular damping of the physics body. - * @param damping The angular damping of the body. - * - * This method is useful for controlling the angular velocity of a physics body. - * By setting the damping, the body's angular velocity will be reduced over time, simulating the effect of friction. - * This can be used to create realistic physical behavior in a physics engine. - */ - setAngularDamping(damping, instanceIndex) { - this._physicsPlugin.setAngularDamping(this, damping, instanceIndex); - } - /** - * Gets the angular damping of the physics body. - * - * @returns The angular damping of the physics body. - * - * This method is useful for getting the angular damping of the physics body, - * which is the rate of reduction of the angular velocity over time. - * This is important for simulating realistic physics behavior in a game. - */ - getAngularDamping(instanceIndex) { - return this._physicsPlugin.getAngularDamping(this, instanceIndex); - } - /** - * Sets the linear velocity of the physics object. - * @param linVel - The linear velocity to set. - * - * This method is useful for setting the linear velocity of a physics object, - * which is necessary for simulating realistic physics in a game engine. - * By setting the linear velocity, the physics object will move in the direction and speed specified by the vector. - * This allows for realistic physics simulations, such as simulating the motion of a ball rolling down a hill. - */ - setLinearVelocity(linVel, instanceIndex) { - this._physicsPlugin.setLinearVelocity(this, linVel, instanceIndex); - } - /** - * Gets the linear velocity of the physics body and stores it in the given vector3. - * @param linVel - The vector3 to store the linear velocity in. - * - * This method is useful for getting the linear velocity of a physics body in a physics engine. - * This can be used to determine the speed and direction of the body, which can be used to calculate the motion of the body. - */ - getLinearVelocityToRef(linVel, instanceIndex) { - return this._physicsPlugin.getLinearVelocityToRef(this, linVel, instanceIndex); - } - /** - * Gets the linear velocity of the physics body as a new vector3. - * @returns The linear velocity of the physics body. - * - * This method is useful for getting the linear velocity of a physics body in a physics engine. - * This can be used to determine the speed and direction of the body, which can be used to calculate the motion of the body. - */ - getLinearVelocity(instanceIndex) { - const ref = new Vector3(); - this.getLinearVelocityToRef(ref, instanceIndex); - return ref; - } - /** - * Sets the angular velocity of the physics object. - * @param angVel - The angular velocity to set. - * - * This method is useful for setting the angular velocity of a physics object, which is necessary for - * simulating realistic physics behavior. The angular velocity is used to determine the rate of rotation of the object, - * which is important for simulating realistic motion. - */ - setAngularVelocity(angVel, instanceIndex) { - this._physicsPlugin.setAngularVelocity(this, angVel, instanceIndex); - } - /** - * Gets the angular velocity of the physics body and stores it in the given vector3. - * @param angVel - The vector3 to store the angular velocity in. - * - * This method is useful for getting the angular velocity of a physics body, which can be used to determine the body's - * rotational speed. This information can be used to create realistic physics simulations. - */ - getAngularVelocityToRef(angVel, instanceIndex) { - return this._physicsPlugin.getAngularVelocityToRef(this, angVel, instanceIndex); - } - /** - * Gets the angular velocity of the physics body as a new vector3. - * @returns The angular velocity of the physics body. - * - * This method is useful for getting the angular velocity of a physics body, which can be used to determine the body's - * rotational speed. This information can be used to create realistic physics simulations. - */ - getAngularVelocity(instanceIndex) { - const ref = new Vector3(); - this.getAngularVelocityToRef(ref, instanceIndex); - return ref; - } - /** - * Applies an impulse to the physics object. - * - * @param impulse The impulse vector. - * @param location The location of the impulse. - * @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. - * - * This method is useful for applying an impulse to a physics object, which can be used to simulate physical forces such as gravity, - * collisions, and explosions. This can be used to create realistic physics simulations in a game or other application. - */ - applyImpulse(impulse, location, instanceIndex) { - this._physicsPlugin.applyImpulse(this, impulse, location, instanceIndex); - } - /** - * Applies a force to the physics object. - * - * @param force The force vector. - * @param location The location of the force. - * @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. - * - * This method is useful for applying a force to a physics object, which can be used to simulate physical forces such as gravity, - * collisions, and explosions. This can be used to create realistic physics simulations in a game or other application. - */ - applyForce(force, location, instanceIndex) { - this._physicsPlugin.applyForce(this, force, location, instanceIndex); - } - /** - * Retrieves the geometry of the body from the physics plugin. - * - * @returns The geometry of the body. - * - * This method is useful for retrieving the geometry of the body from the physics plugin, which can be used for various physics calculations. - */ - getGeometry() { - return this._physicsPlugin.getBodyGeometry(this); - } - /** - * Returns an observable that will be notified for all collisions happening for event-enabled bodies - * @returns Observable - */ - getCollisionObservable() { - return this._physicsPlugin.getCollisionObservable(this); - } - /** - * Enable or disable collision callback for this PhysicsBody. - * @param enabled true if PhysicsBody's collision will rise a collision event and notifies the observable - */ - setCollisionCallbackEnabled(enabled) { - this._collisionCBEnabled = enabled; - this._physicsPlugin.setCollisionCallbackEnabled(this, enabled); - } - /* - * Get the center of the object in world space. - * @param instanceIndex - If this body is instanced, the index of the instance to get the center for. - * @returns geometric center of the associated mesh - */ - getObjectCenterWorld(instanceIndex) { - const ref = new Vector3(); - return this.getObjectCenterWorldToRef(ref, instanceIndex); - } - /* - * Get the center of the object in world space. - * @param ref - The vector3 to store the result in. - * @param instanceIndex - If this body is instanced, the index of the instance to get the center for. - * @returns geometric center of the associated mesh - */ - getObjectCenterWorldToRef(ref, instanceIndex) { - var _a; - if (((_a = this._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0) { - const index = instanceIndex || 0; - const matrixData = this.transformNode._thinInstanceDataStorage.matrixData; - if (matrixData) { - ref.set(matrixData[index * 16 + 12], matrixData[index * 16 + 13], matrixData[index * 16 + 14]); - } - } - else { - ref.copyFrom(this.transformNode.position); - } - return ref; - } - /** - * Adds a constraint to the physics engine. - * - * @param childBody - The body to which the constraint will be applied. - * @param constraint - The constraint to be applied. - * @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. - * @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. - * - */ - addConstraint(childBody, constraint, instanceIndex, childInstanceIndex) { - this._physicsPlugin.addConstraint(this, childBody, constraint, instanceIndex, childInstanceIndex); - } - /** - * Sync with a bone - * @param bone The bone that the impostor will be synced to. - * @param boneMesh The mesh that the bone is influencing. - * @param jointPivot The pivot of the joint / bone in local space. - * @param distToJoint Optional distance from the impostor to the joint. - * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. - * @param boneAxis Optional vector3 axis the bone is aligned with - */ - syncWithBone(bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) { - const mesh = this.transformNode; - if (mesh.rotationQuaternion) { - if (adjustRotation) { - const tempQuat = TmpVectors.Quaternion[0]; - bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, tempQuat); - tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion); - } - else { - bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, mesh.rotationQuaternion); - } - } - const pos = TmpVectors.Vector3[0]; - const boneDir = TmpVectors.Vector3[1]; - if (!boneAxis) { - boneAxis = TmpVectors.Vector3[2]; - boneAxis.x = 0; - boneAxis.y = 1; - boneAxis.z = 0; - } - bone.getDirectionToRef(boneAxis, boneMesh, boneDir); - bone.getAbsolutePositionToRef(boneMesh, pos); - if ((distToJoint === undefined || distToJoint === null) && jointPivot) { - distToJoint = jointPivot.length(); - } - if (distToJoint !== undefined && distToJoint !== null) { - pos.x += boneDir.x * distToJoint; - pos.y += boneDir.y * distToJoint; - pos.z += boneDir.z * distToJoint; - } - mesh.setAbsolutePosition(pos); - } - /** - * Executes a callback on the body or all of the instances of a body - * @param callback the callback to execute - */ - iterateOverAllInstances(callback) { - var _a; - if (((_a = this._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0) { - for (let i = 0; i < this._pluginDataInstances.length; i++) { - callback(this, i); - } - } - else { - callback(this, undefined); - } - } - /** - * Sets the gravity factor of the physics body - * @param factor the gravity factor to set - * @param instanceIndex the instance of the body to set, if undefined all instances will be set - */ - setGravityFactor(factor, instanceIndex) { - this._physicsPlugin.setGravityFactor(this, factor, instanceIndex); - } - /** - * Gets the gravity factor of the physics body - * @param instanceIndex the instance of the body to get, if undefined the value of first instance will be returned - * @returns the gravity factor - */ - getGravityFactor(instanceIndex) { - return this._physicsPlugin.getGravityFactor(this, instanceIndex); - } - /** - * Set the target transformation (position and rotation) of the body, such that the body will set its velocity to reach that target - * @param position The target position - * @param rotation The target rotation - * @param instanceIndex The index of the instance in an instanced body - */ - setTargetTransform(position, rotation, instanceIndex) { - this._physicsPlugin.setTargetTransform(this, position, rotation, instanceIndex); - } - /** - * Disposes the body from the physics engine. - * - * 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. - */ - dispose() { - // Disable collisions CB so it doesn't fire when the body is disposed - if (this._collisionCBEnabled) { - this.setCollisionCallbackEnabled(false); - } - if (this._nodeDisposeObserver) { - this.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver); - this._nodeDisposeObserver = null; - } - this._physicsEngine.removeBody(this); - this._physicsPlugin.removeBody(this); - this._physicsPlugin.disposeBody(this); - this.transformNode.physicsBody = null; - this._pluginData = null; - this._pluginDataInstances.length = 0; - } -} -//# sourceMappingURL=physicsBody.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/IPhysicsEnginePlugin.js -/** How a specific axis can be constrained */ -var IPhysicsEnginePlugin_PhysicsConstraintAxisLimitMode; -(function (PhysicsConstraintAxisLimitMode) { - /* - * The axis is not restricted at all - */ - PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode["FREE"] = 0] = "FREE"; - /* - * The axis has a minimum/maximum limit - */ - PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode["LIMITED"] = 1] = "LIMITED"; - /* - * The axis allows no relative movement of the pivots - */ - PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode["LOCKED"] = 2] = "LOCKED"; -})(IPhysicsEnginePlugin_PhysicsConstraintAxisLimitMode || (IPhysicsEnginePlugin_PhysicsConstraintAxisLimitMode = {})); -/** The constraint specific axis to use when setting Friction, `ConstraintAxisLimitMode`, max force, ... */ -var IPhysicsEnginePlugin_PhysicsConstraintAxis; -(function (PhysicsConstraintAxis) { - /* - * Translation along the primary axis of the constraint (i.e. the - * direction specified by PhysicsConstraintParameters.axisA/axisB) - */ - PhysicsConstraintAxis[PhysicsConstraintAxis["LINEAR_X"] = 0] = "LINEAR_X"; - /* - * Translation along the second axis of the constraint (i.e. the - * direction specified by PhysicsConstraintParameters.perpAxisA/perpAxisB) - */ - PhysicsConstraintAxis[PhysicsConstraintAxis["LINEAR_Y"] = 1] = "LINEAR_Y"; - /* - * Translation along the third axis of the constraint. This axis is - * computed from the cross product of axisA/axisB and perpAxisA/perpAxisB) - */ - PhysicsConstraintAxis[PhysicsConstraintAxis["LINEAR_Z"] = 2] = "LINEAR_Z"; - /* - * Rotation around the primary axis of the constraint (i.e. the - * axis specified by PhysicsConstraintParameters.axisA/axisB) - */ - PhysicsConstraintAxis[PhysicsConstraintAxis["ANGULAR_X"] = 3] = "ANGULAR_X"; - /* - * Rotation around the second axis of the constraint (i.e. the - * axis specified by PhysicsConstraintParameters.perpAxisA/perpAxisB) - */ - PhysicsConstraintAxis[PhysicsConstraintAxis["ANGULAR_Y"] = 4] = "ANGULAR_Y"; - /* - * Rotation around the third axis of the constraint. This axis is - * computed from the cross product of axisA/axisB and perpAxisA/perpAxisB) - */ - PhysicsConstraintAxis[PhysicsConstraintAxis["ANGULAR_Z"] = 5] = "ANGULAR_Z"; - /* - * A 3D distance limit; similar to specifying the LINEAR_X/Y/Z axes - * individually, but the distance calculation uses all three axes - * simultaneously, instead of individually. - */ - PhysicsConstraintAxis[PhysicsConstraintAxis["LINEAR_DISTANCE"] = 6] = "LINEAR_DISTANCE"; -})(IPhysicsEnginePlugin_PhysicsConstraintAxis || (IPhysicsEnginePlugin_PhysicsConstraintAxis = {})); -/** Type of Constraint */ -var IPhysicsEnginePlugin_PhysicsConstraintType; -(function (PhysicsConstraintType) { - /** - * A ball and socket constraint will attempt to line up the pivot - * positions in each body, and have no restrictions on rotation - */ - PhysicsConstraintType[PhysicsConstraintType["BALL_AND_SOCKET"] = 1] = "BALL_AND_SOCKET"; - /** - * A distance constraint will attempt to keep the pivot locations - * within a specified distance. - */ - PhysicsConstraintType[PhysicsConstraintType["DISTANCE"] = 2] = "DISTANCE"; - /** - * A hinge constraint will keep the pivot positions aligned as well - * as two angular axes. The remaining angular axis will be free to rotate. - */ - PhysicsConstraintType[PhysicsConstraintType["HINGE"] = 3] = "HINGE"; - /** - * A slider constraint allows bodies to translate along one axis and - * rotate about the same axis. The remaining two axes are locked in - * place - */ - PhysicsConstraintType[PhysicsConstraintType["SLIDER"] = 4] = "SLIDER"; - /** - * A lock constraint will attempt to keep the pivots completely lined - * up between both bodies, allowing no relative movement. - */ - PhysicsConstraintType[PhysicsConstraintType["LOCK"] = 5] = "LOCK"; - /* - * A prismatic will lock the rotations of the bodies, and allow translation - * only along one axis - */ - PhysicsConstraintType[PhysicsConstraintType["PRISMATIC"] = 6] = "PRISMATIC"; - /* - * A generic constraint; this starts with no limits on how the bodies can - * move relative to each other, but limits can be added via the PhysicsConstraint - * interfaces. This can be used to specify a large variety of constraints - */ - PhysicsConstraintType[PhysicsConstraintType["SIX_DOF"] = 7] = "SIX_DOF"; -})(IPhysicsEnginePlugin_PhysicsConstraintType || (IPhysicsEnginePlugin_PhysicsConstraintType = {})); -/** Type of Shape */ -var IPhysicsEnginePlugin_PhysicsShapeType; -(function (PhysicsShapeType) { - PhysicsShapeType[PhysicsShapeType["SPHERE"] = 0] = "SPHERE"; - PhysicsShapeType[PhysicsShapeType["CAPSULE"] = 1] = "CAPSULE"; - PhysicsShapeType[PhysicsShapeType["CYLINDER"] = 2] = "CYLINDER"; - PhysicsShapeType[PhysicsShapeType["BOX"] = 3] = "BOX"; - PhysicsShapeType[PhysicsShapeType["CONVEX_HULL"] = 4] = "CONVEX_HULL"; - PhysicsShapeType[PhysicsShapeType["CONTAINER"] = 5] = "CONTAINER"; - PhysicsShapeType[PhysicsShapeType["MESH"] = 6] = "MESH"; - PhysicsShapeType[PhysicsShapeType["HEIGHTFIELD"] = 7] = "HEIGHTFIELD"; -})(IPhysicsEnginePlugin_PhysicsShapeType || (IPhysicsEnginePlugin_PhysicsShapeType = {})); -/** Optional motor which attempts to move a body at a specific velocity, or at a specific position */ -var IPhysicsEnginePlugin_PhysicsConstraintMotorType; -(function (PhysicsConstraintMotorType) { - PhysicsConstraintMotorType[PhysicsConstraintMotorType["NONE"] = 0] = "NONE"; - PhysicsConstraintMotorType[PhysicsConstraintMotorType["VELOCITY"] = 1] = "VELOCITY"; - PhysicsConstraintMotorType[PhysicsConstraintMotorType["POSITION"] = 2] = "POSITION"; -})(IPhysicsEnginePlugin_PhysicsConstraintMotorType || (IPhysicsEnginePlugin_PhysicsConstraintMotorType = {})); -var IPhysicsEnginePlugin_PhysicsEventType; -(function (PhysicsEventType) { - PhysicsEventType["COLLISION_STARTED"] = "COLLISION_STARTED"; - PhysicsEventType["COLLISION_CONTINUED"] = "COLLISION_CONTINUED"; - PhysicsEventType["COLLISION_FINISHED"] = "COLLISION_FINISHED"; - PhysicsEventType["TRIGGER_ENTERED"] = "TRIGGER_ENTERED"; - PhysicsEventType["TRIGGER_EXITED"] = "TRIGGER_EXITED"; -})(IPhysicsEnginePlugin_PhysicsEventType || (IPhysicsEnginePlugin_PhysicsEventType = {})); -/** - * Indicates how the body will behave. - */ -var IPhysicsEnginePlugin_PhysicsMotionType; -(function (PhysicsMotionType) { - PhysicsMotionType[PhysicsMotionType["STATIC"] = 0] = "STATIC"; - PhysicsMotionType[PhysicsMotionType["ANIMATED"] = 1] = "ANIMATED"; - PhysicsMotionType[PhysicsMotionType["DYNAMIC"] = 2] = "DYNAMIC"; -})(IPhysicsEnginePlugin_PhysicsMotionType || (IPhysicsEnginePlugin_PhysicsMotionType = {})); -//# sourceMappingURL=IPhysicsEnginePlugin.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/physicsShape.js - - -/** - * PhysicsShape class. - * This class is useful for creating a physics shape that can be used in a physics engine. - * A Physic Shape determine how collision are computed. It must be attached to a body. - */ -class physicsShape_PhysicsShape { - /** - * Constructs a new physics shape. - * @param options The options for the physics shape. These are: - * * type: The type of the shape. This can be one of the following: SPHERE, BOX, CAPSULE, CYLINDER, CONVEX_HULL, MESH, HEIGHTFIELD, CONTAINER - * * parameters: The parameters of the shape. - * * pluginData: The plugin data of the shape. This is used if you already have a reference to the object on the plugin side. - * You need to specify either type or pluginData. - * @param scene The scene the shape belongs to. - * - * This code is useful for creating a new physics shape with the given type, options, and scene. - * It also checks that the physics engine and plugin version are correct. - * If not, it throws an error. This ensures that the shape is created with the correct parameters and is compatible with the physics engine. - */ - constructor(options, scene) { - var _a; - /** - * V2 Physics plugin private data for single shape - */ - this._pluginData = undefined; - this._isTrigger = false; - if (!scene) { - return; - } - const physicsEngine = scene.getPhysicsEngine(); - if (!physicsEngine) { - throw new Error("No Physics Engine available."); - } - if (physicsEngine.getPluginVersion() != 2) { - throw new Error("Plugin version is incorrect. Expected version 2."); - } - const physicsPlugin = physicsEngine.getPhysicsPlugin(); - if (!physicsPlugin) { - throw new Error("No Physics Plugin available."); - } - this._physicsPlugin = physicsPlugin; - if (options.pluginData !== undefined && options.pluginData !== null) { - this._pluginData = options.pluginData; - this._type = this._physicsPlugin.getShapeType(this); - } - else if (options.type !== undefined && options.type !== null) { - this._type = options.type; - const parameters = (_a = options.parameters) !== null && _a !== void 0 ? _a : {}; - this._physicsPlugin.initShape(this, options.type, parameters); - } - } - /** - * Returns the string "PhysicsShape". - * @returns "PhysicsShape" - */ - getClassName() { - return "PhysicsShape"; - } - /** - * Returns the type of the physics shape. - * @returns The type of the physics shape. - */ - get type() { - return this._type; - } - /** - * Set the membership mask of a shape. This is a bitfield of arbitrary - * "categories" to which the shape is a member. This is used in combination - * with the collide mask to determine if this shape should collide with - * another. - * - * @param membershipMask Bitfield of categories of this shape. - */ - set filterMembershipMask(membershipMask) { - this._physicsPlugin.setShapeFilterMembershipMask(this, membershipMask); - } - /** - * Get the membership mask of a shape. - * @returns Bitmask of categories which this shape is a member of. - */ - get filterMembershipMask() { - return this._physicsPlugin.getShapeFilterMembershipMask(this); - } - /** - * Sets the collide mask of a shape. This is a bitfield of arbitrary - * "categories" to which this shape collides with. Given two shapes, - * the engine will check if the collide mask and membership overlap: - * shapeA.filterMembershipMask & shapeB.filterCollideMask - * - * If this value is zero (i.e. shapeB only collides with categories - * which shapeA is _not_ a member of) then the shapes will not collide. - * - * Note, the engine will also perform the same test with shapeA and - * shapeB swapped; the shapes will not collide if either shape has - * a collideMask which prevents collision with the other shape. - * - * @param collideMask Bitmask of categories this shape should collide with - */ - set filterCollideMask(collideMask) { - this._physicsPlugin.setShapeFilterCollideMask(this, collideMask); - } - /** - * - * @returns Bitmask of categories that this shape should collide with - */ - get filterCollideMask() { - return this._physicsPlugin.getShapeFilterCollideMask(this); - } - /** - * - * @param material - */ - set material(material) { - this._physicsPlugin.setMaterial(this, material); - this._material = material; - } - /** - * Returns the material of the physics shape. - * @returns The material of the physics shape. - */ - get material() { - return this._material; - } - /** - * Sets the density of the physics shape. - * @param density The density of the physics shape. - */ - set density(density) { - this._physicsPlugin.setDensity(this, density); - } - /** - * Returns the density of the physics shape. - * @returns The density of the physics shape. - */ - get density() { - return this._physicsPlugin.getDensity(this); - } - /** - * Utility to add a child shape to this container, - * automatically computing the relative transform between - * the container shape and the child instance. - * - * @param parentTransform The transform node associated with this shape - * @param newChild The new PhysicsShape to add - * @param childTransform The transform node associated with the child shape - */ - addChildFromParent(parentTransform, newChild, childTransform) { - const childToWorld = childTransform.computeWorldMatrix(true); - const parentToWorld = parentTransform.computeWorldMatrix(true); - const childToParent = TmpVectors.Matrix[0]; - childToWorld.multiplyToRef(Matrix.Invert(parentToWorld), childToParent); - const translation = TmpVectors.Vector3[0]; - const rotation = TmpVectors.Quaternion[0]; - const scale = TmpVectors.Vector3[1]; - childToParent.decompose(scale, rotation, translation); - this._physicsPlugin.addChild(this, newChild, translation, rotation, scale); - } - /** - * Adds a child shape to a container with an optional transform - * @param newChild The new PhysicsShape to add - * @param translation Optional position of the child shape relative to this shape - * @param rotation Optional rotation of the child shape relative to this shape - * @param scale Optional scale of the child shape relative to this shape - */ - addChild(newChild, translation, rotation, scale) { - this._physicsPlugin.addChild(this, newChild, translation, rotation, scale); - } - /** - * Removes a child shape from this shape. - * @param childIndex The index of the child shape to remove - */ - removeChild(childIndex) { - this._physicsPlugin.removeChild(this, childIndex); - } - /** - * Returns the number of children of a physics shape. - * @returns The number of children of a physics shape. - */ - getNumChildren() { - return this._physicsPlugin.getNumChildren(this); - } - /** - * Returns the bounding box of the physics shape. - * @returns The bounding box of the physics shape. - */ - getBoundingBox() { - return this._physicsPlugin.getBoundingBox(this); - } - set isTrigger(isTrigger) { - if (this._isTrigger === isTrigger) { - return; - } - this._isTrigger = isTrigger; - this._physicsPlugin.setTrigger(this, isTrigger); - } - get isTrigger() { - return this._isTrigger; - } - /** - * Dispose the shape and release its associated resources. - */ - dispose() { - this._physicsPlugin.disposeShape(this); - } -} -/** - * Helper object to create a sphere shape - */ -class PhysicsShapeSphere extends (/* unused pure expression or super */ null && (physicsShape_PhysicsShape)) { - /** - * Constructor for the Sphere Shape - * @param center local center of the sphere - * @param radius radius - * @param scene scene to attach to - */ - constructor(center, radius, scene) { - super({ type: PhysicsShapeType.SPHERE, parameters: { center: center, radius: radius } }, scene); - } - /** - * Derive an approximate sphere from the mesh. - * @param mesh node from which to derive the sphere shape - * @returns PhysicsShapeSphere - */ - static FromMesh(mesh) { - const bounds = mesh.getBoundingInfo(); - const centerLocal = bounds.boundingSphere.center; - const he = bounds.boundingBox.extendSize; - const radius = Math.max(he.x, he.y, he.z); - return new PhysicsShapeSphere(centerLocal, radius, mesh.getScene()); - } -} -/** - * Helper object to create a capsule shape - */ -class PhysicsShapeCapsule extends (/* unused pure expression or super */ null && (physicsShape_PhysicsShape)) { - /** - * - * @param pointA Starting point that defines the capsule segment - * @param pointB ending point of that same segment - * @param radius radius - * @param scene scene to attach to - */ - constructor(pointA, pointB, radius, scene) { - super({ type: PhysicsShapeType.CAPSULE, parameters: { pointA: pointA, pointB: pointB, radius: radius } }, scene); - } - /** - * Derive an approximate capsule from the mesh. Note, this is - * not the optimal bounding capsule. - * @param mesh Node from which to derive a cylinder shape - */ - static FromMesh(mesh) { - const boundsLocal = mesh.getBoundingInfo(); - const radius = boundsLocal.boundingBox.extendSize.x; - const pointFromCenter = new Vector3(0, boundsLocal.boundingBox.extendSize.y - radius, 0); - const pointA = boundsLocal.boundingBox.center.add(pointFromCenter); - const pointB = boundsLocal.boundingBox.center.subtract(pointFromCenter); - return new PhysicsShapeCapsule(pointA, pointB, radius, mesh.getScene()); - } -} -/** - * Helper object to create a cylinder shape - */ -class PhysicsShapeCylinder extends (/* unused pure expression or super */ null && (physicsShape_PhysicsShape)) { - /** - * - * @param pointA Starting point that defines the cylinder segment - * @param pointB ending point of that same segment - * @param radius radius - * @param scene scene to attach to - */ - constructor(pointA, pointB, radius, scene) { - super({ type: PhysicsShapeType.CYLINDER, parameters: { pointA: pointA, pointB: pointB, radius: radius } }, scene); - } - /** - * Derive an approximate cylinder from the mesh. Note, this is - * not the optimal bounding cylinder. - * @param mesh Node from which to derive a cylinder shape - */ - static FromMesh(mesh) { - const boundsLocal = mesh.getBoundingInfo(); - const radius = boundsLocal.boundingBox.extendSize.x; - const pointFromCenter = new Vector3(0, boundsLocal.boundingBox.extendSize.y, 0); - const pointA = boundsLocal.boundingBox.center.add(pointFromCenter); - const pointB = boundsLocal.boundingBox.center.subtract(pointFromCenter); - return new PhysicsShapeCylinder(pointA, pointB, radius, mesh.getScene()); - } -} -/** - * Helper object to create a box shape - */ -class PhysicsShapeBox extends (/* unused pure expression or super */ null && (physicsShape_PhysicsShape)) { - /** - * - * @param center local center of the box - * @param rotation local orientation - * @param extents size of the box in each direction - * @param scene scene to attach to - */ - constructor(center, rotation, extents, scene) { - super({ type: PhysicsShapeType.BOX, parameters: { center: center, rotation: rotation, extents: extents } }, scene); - } - /** - * - * @param mesh - * @returns PhysicsShapeBox - */ - static FromMesh(mesh) { - const bounds = mesh.getBoundingInfo(); - const centerLocal = bounds.boundingBox.center; - const extents = bounds.boundingBox.extendSize.scale(2.0); //<todo.eoin extendSize seems to really be half-extents? - return new PhysicsShapeBox(centerLocal, Quaternion.Identity(), extents, mesh.getScene()); - } -} -/** - * Helper object to create a convex hull shape - */ -class PhysicsShapeConvexHull extends (/* unused pure expression or super */ null && (physicsShape_PhysicsShape)) { - /** - * - * @param mesh the mesh to be used as topology infos for the convex hull - * @param scene scene to attach to - */ - constructor(mesh, scene) { - super({ type: PhysicsShapeType.CONVEX_HULL, parameters: { mesh: mesh } }, scene); - } -} -/** - * Helper object to create a mesh shape - */ -class PhysicsShapeMesh extends (/* unused pure expression or super */ null && (physicsShape_PhysicsShape)) { - /** - * - * @param mesh the mesh topology that will be used to create the shape - * @param scene scene to attach to - */ - constructor(mesh, scene) { - super({ type: PhysicsShapeType.MESH, parameters: { mesh: mesh } }, scene); - } -} -/** - * A shape container holds a variable number of shapes. Use AddChild to append to newly created parent container. - */ -class PhysicsShapeContainer extends (/* unused pure expression or super */ null && (physicsShape_PhysicsShape)) { - /** - * Constructor of the Shape container - * @param scene scene to attach to - */ - constructor(scene) { - super({ type: PhysicsShapeType.CONTAINER, parameters: {} }, scene); - } -} -//# sourceMappingURL=physicsShape.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/physicsConstraint.js - -/** - * This is a holder class for the physics constraint created by the physics plugin - * It holds a set of functions to control the underlying constraint - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -class PhysicsConstraint { - /** - * Constructs a new constraint for the physics constraint. - * @param type The type of constraint to create. - * @param options The options for the constraint. - * @param scene The scene the constraint belongs to. - * - * This code is useful for creating a new constraint for the physics engine. It checks if the scene has a physics engine, and if the plugin version is correct. - * If all checks pass, it initializes the constraint with the given type and options. - */ - constructor(type, options, scene) { - /** - * V2 Physics plugin private data for a physics material - */ - this._pluginData = undefined; - if (!scene) { - throw new Error("Missing scene parameter for constraint constructor."); - } - const physicsEngine = scene.getPhysicsEngine(); - if (!physicsEngine) { - throw new Error("No Physics Engine available."); - } - if (physicsEngine.getPluginVersion() != 2) { - throw new Error("Plugin version is incorrect. Expected version 2."); - } - const physicsPlugin = physicsEngine.getPhysicsPlugin(); - if (!physicsPlugin) { - throw new Error("No Physics Plugin available."); - } - this._physicsPlugin = physicsPlugin; - this._options = options; - this._type = type; - } - /** - * Gets the type of the constraint. - * - * @returns The type of the constraint. - * - */ - get type() { - return this._type; - } - /** - * Retrieves the options of the physics constraint. - * - * @returns The physics constraint parameters. - * - */ - get options() { - return this._options; - } - /** - * Enable/disable the constraint - * @param isEnabled value for the constraint - */ - set isEnabled(isEnabled) { - this._physicsPlugin.setEnabled(this, isEnabled); - } - /** - * - * @returns true if constraint is enabled - */ - get isEnabled() { - return this._physicsPlugin.getEnabled(this); - } - /** - * Enables or disables collisions for the physics engine. - * - * @param isEnabled - A boolean value indicating whether collisions should be enabled or disabled. - * - */ - set isCollisionsEnabled(isEnabled) { - this._physicsPlugin.setCollisionsEnabled(this, isEnabled); - } - /** - * Gets whether collisions are enabled for this physics object. - * - * @returns `true` if collisions are enabled, `false` otherwise. - * - */ - get isCollisionsEnabled() { - return this._physicsPlugin.getCollisionsEnabled(this); - } - /** - * Disposes the constraint from the physics engine. - * - * 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. - */ - dispose() { - this._physicsPlugin.disposeConstraint(this); - } -} -/** - * This describes a single limit used by Physics6DoFConstraint - */ -class Physics6DoFLimit { -} -/** - * A generic constraint, which can be used to build more complex constraints than those specified - * in PhysicsConstraintType. The axis and pivot options in PhysicsConstraintParameters define the space - * the constraint operates in. This constraint contains a set of limits, which restrict the - * relative movement of the bodies in that coordinate system - */ -class Physics6DoFConstraint extends (/* unused pure expression or super */ null && (PhysicsConstraint)) { - constructor(constraintParams, limits, scene) { - super(PhysicsConstraintType.SIX_DOF, constraintParams, scene); - this.limits = limits; - } - /** - * Sets the friction of the given axis of the physics engine. - * @param axis - The axis of the physics engine to set the friction for. - * @param friction - The friction to set for the given axis. - * - */ - setAxisFriction(axis, friction) { - this._physicsPlugin.setAxisFriction(this, axis, friction); - } - /** - * Gets the friction of the given axis of the physics engine. - * @param axis - The axis of the physics engine. - * @returns The friction of the given axis. - * - */ - getAxisFriction(axis) { - return this._physicsPlugin.getAxisFriction(this, axis); - } - /** - * Sets the limit mode for the given axis of the constraint. - * @param axis The axis to set the limit mode for. - * @param limitMode The limit mode to set. - * - * This method is useful for setting the limit mode for a given axis of the constraint. This is important for - * controlling the behavior of the physics engine when the constraint is reached. By setting the limit mode, - * the engine can be configured to either stop the motion of the objects, or to allow them to continue - * moving beyond the constraint. - */ - setAxisMode(axis, limitMode) { - this._physicsPlugin.setAxisMode(this, axis, limitMode); - } - /** - * Gets the limit mode of the given axis of the constraint. - * - * @param axis - The axis of the constraint. - * @returns The limit mode of the given axis. - * - */ - getAxisMode(axis) { - return this._physicsPlugin.getAxisMode(this, axis); - } - /** - * Sets the minimum limit of a given axis of a constraint. - * @param axis - The axis of the constraint. - * @param minLimit - The minimum limit of the axis. - * - */ - setAxisMinLimit(axis, minLimit) { - this._physicsPlugin.setAxisMinLimit(this, axis, minLimit); - } - /** - * Gets the minimum limit of the given axis of the physics engine. - * @param axis - The axis of the physics engine. - * @returns The minimum limit of the given axis. - * - */ - getAxisMinLimit(axis) { - return this._physicsPlugin.getAxisMinLimit(this, axis); - } - /** - * Sets the maximum limit of the given axis for the physics engine. - * @param axis - The axis to set the limit for. - * @param limit - The maximum limit of the axis. - * - * This method is useful for setting the maximum limit of the given axis for the physics engine, - * which can be used to control the movement of the physics object. This helps to ensure that the - * physics object does not move beyond the given limit. - */ - setAxisMaxLimit(axis, limit) { - this._physicsPlugin.setAxisMaxLimit(this, axis, limit); - } - /** - * Gets the maximum limit of the given axis of the physics engine. - * @param axis - The axis of the physics engine. - * @returns The maximum limit of the given axis. - * - */ - getAxisMaxLimit(axis) { - return this._physicsPlugin.getAxisMaxLimit(this, axis); - } - /** - * Sets the motor type of the given axis of the constraint. - * @param axis - The axis of the constraint. - * @param motorType - The type of motor to use. - * @returns void - * - */ - setAxisMotorType(axis, motorType) { - this._physicsPlugin.setAxisMotorType(this, axis, motorType); - } - /** - * Gets the motor type of the specified axis of the constraint. - * - * @param axis - The axis of the constraint. - * @returns The motor type of the specified axis. - * - */ - getAxisMotorType(axis) { - return this._physicsPlugin.getAxisMotorType(this, axis); - } - /** - * Sets the target velocity of the motor associated with the given axis of the constraint. - * @param axis - The axis of the constraint. - * @param target - The target velocity of the motor. - * - * This method is useful for setting the target velocity of the motor associated with the given axis of the constraint. - */ - setAxisMotorTarget(axis, target) { - this._physicsPlugin.setAxisMotorTarget(this, axis, target); - } - /** - * Gets the target velocity of the motor associated to the given constraint axis. - * @param axis - The constraint axis associated to the motor. - * @returns The target velocity of the motor. - * - */ - getAxisMotorTarget(axis) { - return this._physicsPlugin.getAxisMotorTarget(this, axis); - } - /** - * Sets the maximum force of the motor of the given axis of the constraint. - * @param axis - The axis of the constraint. - * @param maxForce - The maximum force of the motor. - * - */ - setAxisMotorMaxForce(axis, maxForce) { - this._physicsPlugin.setAxisMotorMaxForce(this, axis, maxForce); - } - /** - * Gets the maximum force of the motor of the given axis of the constraint. - * @param axis - The axis of the constraint. - * @returns The maximum force of the motor. - * - */ - getAxisMotorMaxForce(axis) { - return this._physicsPlugin.getAxisMotorMaxForce(this, axis); - } -} -/** - * Represents a Ball and Socket Constraint, used to simulate a joint - * - * @param pivotA - The first pivot, defined locally in the first body frame - * @param pivotB - The second pivot, defined locally in the second body frame - * @param axisA - The axis of the first body - * @param axisB - The axis of the second body - * @param scene - The scene the constraint is applied to - * @returns The Ball and Socket Constraint - * - * This class is useful for simulating a joint between two bodies in a physics engine. - * It allows for the two bodies to move relative to each other in a way that mimics a ball and socket joint, such as a shoulder or hip joint. - */ -class BallAndSocketConstraint extends (/* unused pure expression or super */ null && (PhysicsConstraint)) { - constructor(pivotA, pivotB, axisA, axisB, scene) { - super(PhysicsConstraintType.BALL_AND_SOCKET, { pivotA: pivotA, pivotB: pivotB, axisA: axisA, axisB: axisB }, scene); - } -} -/** - * Creates a distance constraint. - * @param maxDistance distance between bodies - * @param scene The scene the constraint belongs to - * @returns DistanceConstraint - * - * This code is useful for creating a distance constraint in a physics engine. - * A distance constraint is a type of constraint that keeps two objects at a certain distance from each other. - * The scene is used to add the constraint to the physics engine. - */ -class DistanceConstraint extends (/* unused pure expression or super */ null && (PhysicsConstraint)) { - constructor(maxDistance, scene) { - super(PhysicsConstraintType.DISTANCE, { maxDistance: maxDistance }, scene); - } -} -/** - * Creates a HingeConstraint, which is a type of PhysicsConstraint. - * - * @param pivotA - The first pivot point, in world space. - * @param pivotB - The second pivot point, in world space. - * @param scene - The scene the constraint is used in. - * @returns The new HingeConstraint. - * - * This code is useful for creating a HingeConstraint, which is a type of PhysicsConstraint. - * This constraint is used to simulate a hinge joint between two rigid bodies, allowing them to rotate around a single axis. - */ -class HingeConstraint extends (/* unused pure expression or super */ null && (PhysicsConstraint)) { - constructor(pivotA, pivotB, axisA, axisB, scene) { - super(PhysicsConstraintType.HINGE, { pivotA: pivotA, pivotB: pivotB, axisA: axisA, axisB: axisB }, scene); - } -} -/** - * Creates a SliderConstraint, which is a type of PhysicsConstraint. - * - * @param pivotA - The first pivot of the constraint, in world space. - * @param pivotB - The second pivot of the constraint, in world space. - * @param axisA - The first axis of the constraint, in world space. - * @param axisB - The second axis of the constraint, in world space. - * @param scene - The scene the constraint belongs to. - * @returns The created SliderConstraint. - * - * This code is useful for creating a SliderConstraint, which is a type of PhysicsConstraint. - * It allows the user to specify the two pivots and two axes of the constraint in world space, as well as the scene the constraint belongs to. - * This is useful for creating a constraint between two rigid bodies that allows them to move along a certain axis. - */ -class SliderConstraint extends (/* unused pure expression or super */ null && (PhysicsConstraint)) { - constructor(pivotA, pivotB, axisA, axisB, scene) { - super(PhysicsConstraintType.SLIDER, { pivotA: pivotA, pivotB: pivotB, axisA: axisA, axisB: axisB }, scene); - } -} -/** - * Creates a LockConstraint, which is a type of PhysicsConstraint. - * - * @param pivotA - The first pivot of the constraint in local space. - * @param pivotB - The second pivot of the constraint in local space. - * @param axisA - The first axis of the constraint in local space. - * @param axisB - The second axis of the constraint in local space. - * @param scene - The scene the constraint belongs to. - * @returns The created LockConstraint. - * - * This code is useful for creating a LockConstraint, which is a type of PhysicsConstraint. - * It takes in two pivots and two axes in local space, as well as the scene the constraint belongs to, and creates a LockConstraint. - */ -class LockConstraint extends (/* unused pure expression or super */ null && (PhysicsConstraint)) { - constructor(pivotA, pivotB, axisA, axisB, scene) { - super(PhysicsConstraintType.LOCK, { pivotA: pivotA, pivotB: pivotB, axisA: axisA, axisB: axisB }, scene); - } -} -/** - * Creates a PrismaticConstraint, which is a type of PhysicsConstraint. - * - * @param pivotA - The first pivot of the constraint in local space. - * @param pivotB - The second pivot of the constraint in local space. - * @param axisA - The first axis of the constraint in local space. - * @param axisB - The second axis of the constraint in local space. - * @param scene - The scene the constraint belongs to. - * @returns The created LockConstraint. - * - * This code is useful for creating a PrismaticConstraint, which is a type of PhysicsConstraint. - * It takes in two pivots and two axes in local space, as well as the scene the constraint belongs to, and creates a PrismaticConstraint. - */ -class PrismaticConstraint extends (/* unused pure expression or super */ null && (PhysicsConstraint)) { - constructor(pivotA, pivotB, axisA, axisB, scene) { - super(PhysicsConstraintType.PRISMATIC, { pivotA: pivotA, pivotB: pivotB, axisA: axisA, axisB: axisB }, scene); - } -} -/** - * Creates a SpringConstraint, which is a type of Physics6DoFConstraint. This constraint applies a force at the ends which is proportional - * to the distance between ends, and a stiffness and damping factor. The force is calculated as (stiffness * positionError) - (damping * velocity) - * - * @param pivotA - The first pivot of the constraint in local space. - * @param pivotB - The second pivot of the constraint in local space. - * @param axisA - The first axis of the constraint in local space. - * @param axisB - The second axis of the constraint in local space. - * @param minDistance - The minimum distance between the two pivots. - * @param maxDistance - The maximum distance between the two pivots. - * @param stiffness - The stiffness of the spring. - * @param damping - The damping of the spring. - * @param scene - The scene the constraint belongs to. - * @returns The created SpringConstraint. - */ -class SpringConstraint extends (/* unused pure expression or super */ null && (Physics6DoFConstraint)) { - constructor(pivotA, pivotB, axisA, axisB, minDistance, maxDistance, stiffness, damping, scene) { - super({ pivotA, pivotB, axisA, axisB }, [{ axis: PhysicsConstraintAxis.LINEAR_DISTANCE, minLimit: minDistance, maxLimit: maxDistance, stiffness, damping }], scene); - } -} -//# sourceMappingURL=physicsConstraint.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/physicsMaterial.js -/** - * Determines how values from the PhysicsMaterial are combined when - * two objects are in contact. When each PhysicsMaterial specifies - * a different combine mode for some property, the combine mode which - * is used will be selected based on their order in this enum - i.e. - * a value later in this list will be preferentially used. - */ -var physicsMaterial_PhysicsMaterialCombineMode; -(function (PhysicsMaterialCombineMode) { - /** - * The final value will be the geometric mean of the two values: - * sqrt( valueA * valueB ) - */ - PhysicsMaterialCombineMode[PhysicsMaterialCombineMode["GEOMETRIC_MEAN"] = 0] = "GEOMETRIC_MEAN"; - /** - * The final value will be the smaller of the two: - * min( valueA , valueB ) - */ - PhysicsMaterialCombineMode[PhysicsMaterialCombineMode["MINIMUM"] = 1] = "MINIMUM"; - /* The final value will be the larger of the two: - * max( valueA , valueB ) - */ - PhysicsMaterialCombineMode[PhysicsMaterialCombineMode["MAXIMUM"] = 2] = "MAXIMUM"; - /* The final value will be the arithmetic mean of the two values: - * (valueA + valueB) / 2 - */ - PhysicsMaterialCombineMode[PhysicsMaterialCombineMode["ARITHMETIC_MEAN"] = 3] = "ARITHMETIC_MEAN"; - /** - * The final value will be the product of the two values: - * valueA * valueB - */ - PhysicsMaterialCombineMode[PhysicsMaterialCombineMode["MULTIPLY"] = 4] = "MULTIPLY"; -})(physicsMaterial_PhysicsMaterialCombineMode || (physicsMaterial_PhysicsMaterialCombineMode = {})); -//# sourceMappingURL=physicsMaterial.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/physicsAggregate.js - - - - - - - -/** - * Helper class to create and interact with a PhysicsAggregate. - * This is a transition object that works like Physics Plugin V1 Impostors. - * This helper instanciate all mandatory physics objects to get a body/shape and material. - * It's less efficient that handling body and shapes independently but for prototyping or - * a small numbers of physics objects, it's good enough. - */ -class PhysicsAggregate { - constructor( - /** - * The physics-enabled object used as the physics aggregate - */ - transformNode, - /** - * The type of the physics aggregate - */ - type, _options = { mass: 0 }, _scene) { - var _a; - this.transformNode = transformNode; - this.type = type; - this._options = _options; - this._scene = _scene; - this._disposeShapeWhenDisposed = true; - //sanity check! - if (!this.transformNode) { - Logger.Error("No object was provided. A physics object is obligatory"); - return; - } - const m = transformNode; - if (this.transformNode.parent && this._options.mass !== 0 && m.hasThinInstances) { - Logger.Warn("A physics body has been created for an object which has a parent and thin instances. Babylon physics currently works in local space so unexpected issues may occur."); - } - // Legacy support for old syntax. - if (!this._scene && transformNode.getScene) { - this._scene = transformNode.getScene(); - } - if (!this._scene) { - return; - } - //default options params - this._options.mass = _options.mass === void 0 ? 0 : _options.mass; - this._options.friction = _options.friction === void 0 ? 0.2 : _options.friction; - this._options.restitution = _options.restitution === void 0 ? 0.2 : _options.restitution; - const motionType = this._options.mass === 0 ? PhysicsMotionType.STATIC : PhysicsMotionType.DYNAMIC; - const startAsleep = (_a = this._options.startAsleep) !== null && _a !== void 0 ? _a : false; - this.body = new PhysicsBody(transformNode, motionType, startAsleep, this._scene); - this._addSizeOptions(); - if (type.getClassName && type.getClassName() === "PhysicsShape") { - this.shape = type; - this._disposeShapeWhenDisposed = false; - } - else { - this.shape = new PhysicsShape({ type: type, parameters: this._options }, this._scene); - } - if (this._options.isTriggerShape) { - this.shape.isTrigger = true; - } - this.material = { friction: this._options.friction, restitution: this._options.restitution }; - this.body.shape = this.shape; - this.shape.material = this.material; - this.body.setMassProperties({ mass: this._options.mass }); - this._nodeDisposeObserver = this.transformNode.onDisposeObservable.add(() => { - this.dispose(); - }); - } - _getObjectBoundingBox() { - if (this.transformNode.getRawBoundingInfo) { - return this.transformNode.getRawBoundingInfo().boundingBox; - } - else { - return new BoundingBox(new Vector3(-0.5, -0.5, -0.5), new Vector3(0.5, 0.5, 0.5)); - } - } - _hasVertices(node) { - return (node === null || node === void 0 ? void 0 : node.getTotalVertices()) > 0; - } - _addSizeOptions() { - var _a, _b, _c, _d, _e, _f, _g, _h; - this.transformNode.computeWorldMatrix(true); - const bb = this._getObjectBoundingBox(); - const extents = TmpVectors.Vector3[0]; - extents.copyFrom(bb.extendSize); - extents.scaleInPlace(2); - extents.multiplyInPlace(this.transformNode.scaling); - const min = TmpVectors.Vector3[1]; - min.copyFrom(bb.minimum); - min.multiplyInPlace(this.transformNode.scaling); - if (!this._options.center) { - const center = new Vector3(); - center.copyFrom(bb.center); - center.multiplyInPlace(this.transformNode.scaling); - this._options.center = center; - } - switch (this.type) { - case PhysicsShapeType.SPHERE: - if (!this._options.radius && Scalar.WithinEpsilon(extents.x, extents.y, 0.0001) && Scalar.WithinEpsilon(extents.x, extents.z, 0.0001)) { - this._options.radius = extents.x / 2; - } - else if (!this._options.radius) { - Logger.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."); - this._options.radius = Math.max(extents.x, extents.y, extents.z) / 2; - } - break; - case PhysicsShapeType.CAPSULE: - { - const capRadius = extents.x / 2; - this._options.radius = (_a = this._options.radius) !== null && _a !== void 0 ? _a : capRadius; - this._options.pointA = (_b = this._options.pointA) !== null && _b !== void 0 ? _b : new Vector3(0, min.y + capRadius, 0); - this._options.pointB = (_c = this._options.pointB) !== null && _c !== void 0 ? _c : new Vector3(0, min.y + extents.y - capRadius, 0); - } - break; - case PhysicsShapeType.CYLINDER: - { - const capRadius = extents.x / 2; - this._options.radius = (_d = this._options.radius) !== null && _d !== void 0 ? _d : capRadius; - this._options.pointA = (_e = this._options.pointA) !== null && _e !== void 0 ? _e : new Vector3(0, min.y, 0); - this._options.pointB = (_f = this._options.pointB) !== null && _f !== void 0 ? _f : new Vector3(0, min.y + extents.y, 0); - } - break; - case PhysicsShapeType.MESH: - case PhysicsShapeType.CONVEX_HULL: - if (!this._options.mesh && this._hasVertices(this.transformNode)) { - this._options.mesh = this.transformNode; - } - else if (!this._options.mesh || !this._hasVertices(this._options.mesh)) { - throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0)."); - } - break; - case PhysicsShapeType.BOX: - this._options.extents = (_g = this._options.extents) !== null && _g !== void 0 ? _g : new Vector3(extents.x, extents.y, extents.z); - this._options.rotation = (_h = this._options.rotation) !== null && _h !== void 0 ? _h : Quaternion.Identity(); - break; - } - } - /** - * Releases the body, shape and material - */ - dispose() { - if (this._nodeDisposeObserver) { - this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver); - this._nodeDisposeObserver = null; - } - this.body.dispose(); - if (this._disposeShapeWhenDisposed) { - this.shape.dispose(); - } - } -} -//# sourceMappingURL=physicsAggregate.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/Plugins/havokPlugin.js - - - - - - - - - - -class MeshAccumulator { - /** - * Constructor of the mesh accumulator - * @param mesh - The mesh used to compute the world matrix. - * @param collectIndices - use mesh indices - * @param scene - The scene used to determine the right handed system. - * - * Merge mesh and its children so whole hierarchy can be used as a mesh shape or convex hull - */ - constructor(mesh, collectIndices, scene) { - this._vertices = []; /// Vertices in body space - this._indices = []; - this._isRightHanded = scene.useRightHandedSystem; - this._collectIndices = collectIndices; - } - /** - * Adds a mesh to the physics engine. - * @param mesh The mesh to add. - * @param includeChildren Whether to include the children of the mesh. - * - * This method adds a mesh to the physics engine by computing the world matrix, - * multiplying it with the body from world matrix, and then transforming the - * coordinates of the mesh's vertices. It also adds the indices of the mesh - * to the physics engine. If includeChildren is true, it will also add the - * children of the mesh to the physics engine, ignoring any children which - * have a physics impostor. This is useful for creating a physics engine - * that accurately reflects the mesh and its children. - */ - addNodeMeshes(mesh, includeChildren) { - // Force absoluteScaling to be computed; we're going to use that to bake - // the scale of any parent nodes into this shape, as physics engines - // usually use rigid transforms, so can't handle arbitrary scale. - mesh.computeWorldMatrix(true); - const rootScaled = TmpVectors.Matrix[0]; - Matrix.ScalingToRef(mesh.absoluteScaling.x, mesh.absoluteScaling.y, mesh.absoluteScaling.z, rootScaled); - if (mesh instanceof Mesh) { - this._addMesh(mesh, rootScaled); - } - else if (mesh instanceof InstancedMesh) { - this._addMesh(mesh.sourceMesh, rootScaled); - } - if (includeChildren) { - const worldToRoot = TmpVectors.Matrix[1]; - mesh.computeWorldMatrix().invertToRef(worldToRoot); - const worldToRootScaled = TmpVectors.Matrix[2]; - worldToRoot.multiplyToRef(rootScaled, worldToRootScaled); - const children = mesh.getChildMeshes(false); - // Ignore any children which have a physics body. - // Other plugin implementations do not have this check, which appears to be - // a bug, as otherwise, the mesh will have a duplicate collider - children - .filter((m) => !m.physicsBody) - .forEach((m) => { - const childToWorld = m.computeWorldMatrix(); - const childToRootScaled = TmpVectors.Matrix[3]; - childToWorld.multiplyToRef(worldToRootScaled, childToRootScaled); - if (m instanceof Mesh) { - this._addMesh(m, childToRootScaled); - } - else if (m instanceof InstancedMesh) { - this._addMesh(m.sourceMesh, childToRootScaled); - } - }); - } - } - _addMesh(mesh, meshToRoot) { - const vertexData = mesh.getVerticesData(VertexBuffer.PositionKind) || []; - const numVerts = vertexData.length / 3; - const indexOffset = this._vertices.length; - for (let v = 0; v < numVerts; v++) { - const pos = new Vector3(vertexData[v * 3 + 0], vertexData[v * 3 + 1], vertexData[v * 3 + 2]); - this._vertices.push(Vector3.TransformCoordinates(pos, meshToRoot)); - } - if (this._collectIndices) { - const meshIndices = mesh.getIndices(); - if (meshIndices) { - for (let i = 0; i < meshIndices.length; i += 3) { - // Havok wants the correct triangle winding to enable the interior triangle optimization - if (this._isRightHanded) { - this._indices.push(meshIndices[i + 0] + indexOffset); - this._indices.push(meshIndices[i + 1] + indexOffset); - this._indices.push(meshIndices[i + 2] + indexOffset); - } - else { - this._indices.push(meshIndices[i + 2] + indexOffset); - this._indices.push(meshIndices[i + 1] + indexOffset); - this._indices.push(meshIndices[i + 0] + indexOffset); - } - } - } - } - } - /** - * Allocate and populate the vertex positions inside the physics plugin. - * - * @returns An array of floats, whose backing memory is inside the plugin. The array contains the - * positions of the mesh vertices, where a position is defined by three floats. You must call - * freeBuffer() on the returned array once you have finished with it, in order to free the - * memory inside the plugin.. - */ - getVertices(plugin) { - const nFloats = this._vertices.length * 3; - const bytesPerFloat = 4; - const nBytes = nFloats * bytesPerFloat; - const bufferBegin = plugin._malloc(nBytes); - const ret = new Float32Array(plugin.HEAPU8.buffer, bufferBegin, nFloats); - for (let i = 0; i < this._vertices.length; i++) { - ret[i * 3 + 0] = this._vertices[i].x; - ret[i * 3 + 1] = this._vertices[i].y; - ret[i * 3 + 2] = this._vertices[i].z; - } - return { offset: bufferBegin, numObjects: nFloats }; - } - freeBuffer(plugin, arr) { - plugin._free(arr.offset); - } - /** - * Allocate and populate the triangle indices inside the physics plugin - * - * @returns A new Int32Array, whose backing memory is inside the plugin. The array contains the indices - * of the triangle positions, where a single triangle is defined by three indices. You must call - * freeBuffer() on this array once you have finished with it, to free the memory inside the plugin.. - */ - getTriangles(plugin) { - const bytesPerInt = 4; - const nBytes = this._indices.length * bytesPerInt; - const bufferBegin = plugin._malloc(nBytes); - const ret = new Int32Array(plugin.HEAPU8.buffer, bufferBegin, this._indices.length); - for (let i = 0; i < this._indices.length; i++) { - ret[i] = this._indices[i]; - } - return { offset: bufferBegin, numObjects: this._indices.length }; - } -} -class BodyPluginData { - constructor(bodyId) { - this.hpBodyId = bodyId; - this.userMassProps = { centerOfMass: undefined, mass: undefined, inertia: undefined, inertiaOrientation: undefined }; - } -} -/* -class ShapePath -{ - public colliderId: number; - public pathData: number; -} -*/ -class ContactPoint { - constructor() { - this.bodyId = BigInt(0); //0,2 - //public colliderId: number = 0; //2,4 - //public shapePath: ShapePath = new ShapePath(); //4,8 - this.position = new Vector3(); //8,11 - this.normal = new Vector3(); //11,14 - //public triIdx: number = 0; //14,15 - } -} -class CollisionEvent { - constructor() { - this.contactOnA = new ContactPoint(); //1 - this.contactOnB = new ContactPoint(); - this.impulseApplied = 0; - this.type = 0; - } - static readToRef(buffer, offset, eventOut) { - const intBuf = new Int32Array(buffer, offset); - const floatBuf = new Float32Array(buffer, offset); - const offA = 2; - eventOut.contactOnA.bodyId = BigInt(intBuf[offA]); //<todo Need to get the high+low words! - eventOut.contactOnA.position.set(floatBuf[offA + 8], floatBuf[offA + 9], floatBuf[offA + 10]); - eventOut.contactOnA.normal.set(floatBuf[offA + 11], floatBuf[offA + 12], floatBuf[offA + 13]); - const offB = 18; - eventOut.contactOnB.bodyId = BigInt(intBuf[offB]); - eventOut.contactOnB.position.set(floatBuf[offB + 8], floatBuf[offB + 9], floatBuf[offB + 10]); - eventOut.contactOnB.normal.set(floatBuf[offB + 11], floatBuf[offB + 12], floatBuf[offB + 13]); - eventOut.impulseApplied = floatBuf[offB + 13 + 3]; - eventOut.type = intBuf[0]; - } -} -class TriggerEvent { - constructor() { - this.bodyIdA = BigInt(0); - this.bodyIdB = BigInt(0); - this.type = 0; - } - static readToRef(buffer, offset, eventOut) { - const intBuf = new Int32Array(buffer, offset); - eventOut.type = intBuf[0]; - eventOut.bodyIdA = BigInt(intBuf[2]); - eventOut.bodyIdB = BigInt(intBuf[6]); - } -} -/** - * The Havok Physics plugin - */ -class HavokPlugin { - constructor(_useDeltaForWorldStep = true, hpInjection = HK) { - this._useDeltaForWorldStep = _useDeltaForWorldStep; - /** - * Reference to the WASM library - */ - this._hknp = {}; - /** - * Name of the plugin - */ - this.name = "HavokPlugin"; - this._fixedTimeStep = 1 / 60; - this._timeStep = 1 / 60; - this._tmpVec3 = ArrayTools.BuildArray(3, Vector3.Zero); - this._bodies = new Map(); - this._bodyCollisionObservable = new Map(); - /** - * Observable for collision started and collision continued events - */ - this.onCollisionObservable = new Observable(); - /** - * Observable for collision ended events - */ - this.onCollisionEndedObservable = new Observable(); - /** - * Observable for trigger entered and trigger exited events - */ - this.onTriggerCollisionObservable = new Observable(); - if (typeof hpInjection === "function") { - Logger.Error("Havok is not ready. Please make sure you await HK() before using the plugin."); - return; - } - else { - this._hknp = hpInjection; - } - if (!this.isSupported()) { - Logger.Error("Havok is not available. Please make sure you included the js file."); - return; - } - this.world = this._hknp.HP_World_Create()[1]; - this._queryCollector = this._hknp.HP_QueryCollector_Create(1)[1]; - } - /** - * If this plugin is supported - * @returns true if its supported - */ - isSupported() { - return this._hknp !== undefined; - } - /** - * Sets the gravity of the physics world. - * - * @param gravity - The gravity vector to set. - * - */ - setGravity(gravity) { - this._hknp.HP_World_SetGravity(this.world, this._bVecToV3(gravity)); - } - /** - * Sets the fixed time step for the physics engine. - * - * @param timeStep - The fixed time step to use for the physics engine. - * - */ - setTimeStep(timeStep) { - this._fixedTimeStep = timeStep; - } - /** - * Gets the fixed time step used by the physics engine. - * - * @returns The fixed time step used by the physics engine. - * - */ - getTimeStep() { - return this._fixedTimeStep; - } - /** - * Executes a single step of the physics engine. - * - * @param delta The time delta in seconds since the last step. - * @param physicsBodies An array of physics bodies to be simulated. - * @returns void - * - * This method is useful for simulating the physics engine. It sets the physics body transformation, - * steps the world, syncs the physics body, and notifies collisions. This allows for the physics engine - * to accurately simulate the physics bodies in the world. - */ - executeStep(delta, physicsBodies) { - for (const physicsBody of physicsBodies) { - if (physicsBody.disablePreStep) { - continue; - } - this.setPhysicsBodyTransformation(physicsBody, physicsBody.transformNode); - } - this._hknp.HP_World_Step(this.world, this._useDeltaForWorldStep ? delta : this._timeStep); - this._bodyBuffer = this._hknp.HP_World_GetBodyBuffer(this.world)[1]; - for (const physicsBody of physicsBodies) { - this.sync(physicsBody); - } - this._notifyCollisions(); - this._notifyTriggers(); - } - /** - * Returns the version of the physics engine plugin. - * - * @returns The version of the physics engine plugin. - * - * This method is useful for determining the version of the physics engine plugin that is currently running. - */ - getPluginVersion() { - return 2; - } - /** - * Initializes a physics body with the given position and orientation. - * - * @param body - The physics body to initialize. - * @param motionType - The motion type of the body. - * @param position - The position of the body. - * @param orientation - The orientation of the body. - * This code is useful for initializing a physics body with the given position and orientation. - * It creates a plugin data for the body and adds it to the world. It then converts the position - * and orientation to a transform and sets the body's transform to the given values. - */ - initBody(body, motionType, position, orientation) { - body._pluginData = new BodyPluginData(this._hknp.HP_Body_Create()[1]); - this._internalSetMotionType(body._pluginData, motionType); - const transform = [this._bVecToV3(position), this._bQuatToV4(orientation)]; //<todo temp transform? - this._hknp.HP_Body_SetQTransform(body._pluginData.hpBodyId, transform); - this._hknp.HP_World_AddBody(this.world, body._pluginData.hpBodyId, body.startAsleep); - this._bodies.set(body._pluginData.hpBodyId[0], { body: body, index: 0 }); - } - /** - * Removes a body from the world. To dispose of a body, it is necessary to remove it from the world first. - * - * @param body - The body to remove. - */ - removeBody(body) { - if (body._pluginDataInstances && body._pluginDataInstances.length > 0) { - for (const instance of body._pluginDataInstances) { - this._bodyCollisionObservable.delete(instance.hpBodyId[0]); - this._hknp.HP_World_RemoveBody(this.world, instance.hpBodyId); - } - } - if (body._pluginData) { - this._bodyCollisionObservable.delete(body._pluginData.hpBodyId[0]); - this._hknp.HP_World_RemoveBody(this.world, body._pluginData.hpBodyId); - } - } - /** - * Initializes the body instances for a given physics body and mesh. - * - * @param body - The physics body to initialize. - * @param motionType - How the body will be handled by the engine - * @param mesh - The mesh to initialize. - * - * This code is useful for creating a physics body from a mesh. It creates a - * body instance for each instance of the mesh and adds it to the world. It also - * sets the position of the body instance to the position of the mesh instance. - * This allows for the physics engine to accurately simulate the mesh in the - * world. - */ - initBodyInstances(body, motionType, mesh) { - var _a, _b; - const instancesCount = (_b = (_a = mesh._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.instancesCount) !== null && _b !== void 0 ? _b : 0; - const matrixData = mesh._thinInstanceDataStorage.matrixData; - if (!matrixData) { - return; // TODO: error handling - } - this._createOrUpdateBodyInstances(body, motionType, matrixData, 0, instancesCount, false); - body._pluginDataInstances.forEach((bodyId, index) => { - this._bodies.set(bodyId.hpBodyId[0], { body: body, index: index }); - }); - } - _createOrUpdateBodyInstances(body, motionType, matrixData, startIndex, endIndex, update) { - const rotation = TmpVectors.Quaternion[0]; - const rotationMatrix = Matrix.Identity(); - for (let i = startIndex; i < endIndex; i++) { - const position = [matrixData[i * 16 + 12], matrixData[i * 16 + 13], matrixData[i * 16 + 14]]; - let hkbody; - if (!update) { - hkbody = this._hknp.HP_Body_Create()[1]; - } - else { - hkbody = body._pluginDataInstances[i].hpBodyId; - } - rotationMatrix.setRowFromFloats(0, matrixData[i * 16 + 0], matrixData[i * 16 + 1], matrixData[i * 16 + 2], 0); - rotationMatrix.setRowFromFloats(1, matrixData[i * 16 + 4], matrixData[i * 16 + 5], matrixData[i * 16 + 6], 0); - rotationMatrix.setRowFromFloats(2, matrixData[i * 16 + 8], matrixData[i * 16 + 9], matrixData[i * 16 + 10], 0); - Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation); - const transform = [position, [rotation.x, rotation.y, rotation.z, rotation.w]]; - this._hknp.HP_Body_SetQTransform(hkbody, transform); - if (!update) { - const pluginData = new BodyPluginData(hkbody); - if (body._pluginDataInstances.length) { - // If an instance already exists, copy any user-provided mass properties - pluginData.userMassProps = body._pluginDataInstances[0].userMassProps; - } - this._internalSetMotionType(pluginData, motionType); - this._internalUpdateMassProperties(pluginData); - body._pluginDataInstances.push(pluginData); - this._hknp.HP_World_AddBody(this.world, hkbody, body.startAsleep); - pluginData.worldTransformOffset = this._hknp.HP_Body_GetWorldTransformOffset(hkbody)[1]; - } - } - } - /** - * Update the internal body instances for a given physics body to match the instances in a mesh. - * @param body the body that will be updated - * @param mesh the mesh with reference instances - */ - updateBodyInstances(body, mesh) { - var _a, _b; - const instancesCount = (_b = (_a = mesh._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.instancesCount) !== null && _b !== void 0 ? _b : 0; - const matrixData = mesh._thinInstanceDataStorage.matrixData; - if (!matrixData) { - return; // TODO: error handling - } - const pluginInstancesCount = body._pluginDataInstances.length; - const motionType = this.getMotionType(body); - if (instancesCount > pluginInstancesCount) { - this._createOrUpdateBodyInstances(body, motionType, matrixData, pluginInstancesCount, instancesCount, false); - const firstBodyShape = this._hknp.HP_Body_GetShape(body._pluginDataInstances[0].hpBodyId)[1]; - for (let i = pluginInstancesCount; i < instancesCount; i++) { - this._hknp.HP_Body_SetShape(body._pluginDataInstances[i].hpBodyId, firstBodyShape); - this._internalUpdateMassProperties(body._pluginDataInstances[i]); - this._bodies.set(body._pluginDataInstances[i].hpBodyId[0], { body: body, index: i }); - } - } - else if (instancesCount < pluginInstancesCount) { - const instancesToRemove = pluginInstancesCount - instancesCount; - for (let i = 0; i < instancesToRemove; i++) { - const hkbody = body._pluginDataInstances.pop(); - this._bodies.delete(hkbody.hpBodyId[0]); - this._hknp.HP_World_RemoveBody(this.world, hkbody.hpBodyId); - this._hknp.HP_Body_Release(hkbody.hpBodyId); - } - this._createOrUpdateBodyInstances(body, motionType, matrixData, 0, instancesCount, true); - } - } - /** - * Synchronizes the transform of a physics body with its transform node. - * @param body - The physics body to synchronize. - * - * This function is useful for keeping the physics body's transform in sync with its transform node. - * This is important for ensuring that the physics body is accurately represented in the physics engine. - */ - sync(body) { - this.syncTransform(body, body.transformNode); - } - /** - * Synchronizes the transform of a physics body with the transform of its - * corresponding transform node. - * - * @param body - The physics body to synchronize. - * @param transformNode - The destination Transform Node. - * - * This code is useful for synchronizing the position and orientation of a - * physics body with the position and orientation of its corresponding - * transform node. This is important for ensuring that the physics body and - * the transform node are in the same position and orientation in the scene. - * This is necessary for the physics engine to accurately simulate the - * physical behavior of the body. - */ - syncTransform(body, transformNode) { - var _a; - if (body._pluginDataInstances.length) { - // instances - const m = transformNode; - const matrixData = m._thinInstanceDataStorage.matrixData; - if (!matrixData) { - return; // TODO: error handling - } - const instancesCount = body._pluginDataInstances.length; - for (let i = 0; i < instancesCount; i++) { - const bufOffset = body._pluginDataInstances[i].worldTransformOffset; - const transformBuffer = new Float32Array(this._hknp.HEAPU8.buffer, this._bodyBuffer + bufOffset, 16); - const index = i * 16; - for (let mi = 0; mi < 15; mi++) { - if ((mi & 3) != 3) { - matrixData[index + mi] = transformBuffer[mi]; - } - } - matrixData[index + 15] = 1; - } - m.thinInstanceBufferUpdated("matrix"); - } - else { - try { - // regular - const bodyTransform = this._hknp.HP_Body_GetQTransform(body._pluginData.hpBodyId)[1]; - const bodyTranslation = bodyTransform[0]; - const bodyOrientation = bodyTransform[1]; - const quat = TmpVectors.Quaternion[0]; - quat.set(bodyOrientation[0], bodyOrientation[1], bodyOrientation[2], bodyOrientation[3]); - const parent = transformNode.parent; - // transform position/orientation in parent space - if (parent && !parent.getWorldMatrix().isIdentity()) { - parent.computeWorldMatrix(true); - quat.normalize(); - const finalTransform = TmpVectors.Matrix[0]; - const finalTranslation = TmpVectors.Vector3[0]; - finalTranslation.copyFromFloats(bodyTranslation[0], bodyTranslation[1], bodyTranslation[2]); - Matrix.ComposeToRef(transformNode.absoluteScaling, quat, finalTranslation, finalTransform); - const parentInverseTransform = TmpVectors.Matrix[1]; - parent.getWorldMatrix().invertToRef(parentInverseTransform); - const localTransform = TmpVectors.Matrix[2]; - finalTransform.multiplyToRef(parentInverseTransform, localTransform); - localTransform.decomposeToTransformNode(transformNode); - (_a = transformNode.rotationQuaternion) === null || _a === void 0 ? void 0 : _a.normalize(); - } - else { - transformNode.position.set(bodyTranslation[0], bodyTranslation[1], bodyTranslation[2]); - if (transformNode.rotationQuaternion) { - transformNode.rotationQuaternion.copyFrom(quat); - } - else { - quat.toEulerAnglesToRef(transformNode.rotation); - } - } - } - catch (e) { - console.log(`Syncing transform failed for node ${transformNode.name}: ${e.message}...`); - } - } - } - /** - * Sets the shape of a physics body. - * @param body - The physics body to set the shape for. - * @param shape - The physics shape to set. - * - * This function is used to set the shape of a physics body. It is useful for - * creating a physics body with a specific shape, such as a box or a sphere, - * which can then be used to simulate physical interactions in a physics engine. - * This function is especially useful for meshes with multiple instances, as it - * will set the shape for each instance of the mesh. - */ - setShape(body, shape) { - var _a, _b, _c; - const shapeHandle = shape && shape._pluginData ? shape._pluginData : BigInt(0); - if (!(body.transformNode instanceof Mesh) || !((_a = body.transformNode._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.matrixData)) { - this._hknp.HP_Body_SetShape(body._pluginData.hpBodyId, shapeHandle); - this._internalUpdateMassProperties(body._pluginData); - return; - } - const m = body.transformNode; - const instancesCount = (_c = (_b = m._thinInstanceDataStorage) === null || _b === void 0 ? void 0 : _b.instancesCount) !== null && _c !== void 0 ? _c : 0; - for (let i = 0; i < instancesCount; i++) { - this._hknp.HP_Body_SetShape(body._pluginDataInstances[i].hpBodyId, shapeHandle); - this._internalUpdateMassProperties(body._pluginDataInstances[i]); - } - } - /** - * Returns a reference to the first instance of the plugin data for a physics body. - * @param body - * @param instanceIndex - * @returns a reference to the first instance - */ - _getPluginReference(body, instanceIndex) { - var _a; - return ((_a = body._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) ? body._pluginDataInstances[instanceIndex !== null && instanceIndex !== void 0 ? instanceIndex : 0] : body._pluginData; - } - /** - * Gets the shape of a physics body. This will create a new shape object - * - * @param body - The physics body. - * @returns The shape of the physics body. - * - */ - getShape(body) { - const pluginRef = this._getPluginReference(body); - const shapePluginData = this._hknp.HP_Body_GetShape(pluginRef.hpBodyId)[1]; - if (shapePluginData != 0) { - const scene = body.transformNode.getScene(); - return new PhysicsShape({ pluginData: shapePluginData }, scene); - } - return null; - } - /** - * Gets the type of a physics shape. - * @param shape - The physics shape to get the type for. - * @returns The type of the physics shape. - * - */ - getShapeType(shape) { - if (shape.type) { - return shape.type; - } - else { - //<todo This returns a native type! - return this._hknp.HP_Shape_GetType(shape._pluginData); - } - } - /** - * Sets the event mask of a physics body. - * @param body - The physics body to set the event mask for. - * @param eventMask - The event mask to set. - * - * This function is useful for setting the event mask of a physics body, which is used to determine which events the body will respond to. This is important for ensuring that the physics engine is able to accurately simulate the behavior of the body in the game world. - */ - setEventMask(body, eventMask, instanceIndex) { - this._applyToBodyOrInstances(body, (bodyPluginData) => { - this._hknp.HP_Body_SetEventMask(bodyPluginData.hpBodyId, eventMask); - }, instanceIndex); - } - /** - * Retrieves the event mask of a physics body. - * - * @param body - The physics body to retrieve the event mask from. - * @returns The event mask of the physics body. - * - */ - getEventMask(body, instanceIndex) { - const pluginRef = this._getPluginReference(body, instanceIndex); - return this._hknp.HP_Body_GetEventMask(pluginRef.hpBodyId)[1]; - } - _fromMassPropertiesTuple(massPropsTuple) { - return { - centerOfMass: Vector3.FromArray(massPropsTuple[0]), - mass: massPropsTuple[1], - inertia: Vector3.FromArray(massPropsTuple[2]), - inertiaOrientation: Quaternion.FromArray(massPropsTuple[3]), - }; - } - _internalUpdateMassProperties(pluginData) { - // Recompute the mass based on the shape - const newProps = this._internalComputeMassProperties(pluginData); - const massProps = pluginData.userMassProps; - // Override the computed values with any the user has set - if (massProps.centerOfMass) { - newProps[0] = massProps.centerOfMass.asArray(); - } - if (massProps.mass != undefined) { - newProps[1] = massProps.mass; - } - if (massProps.inertia) { - newProps[2] = massProps.inertia.asArray(); - } - if (massProps.inertiaOrientation) { - newProps[3] = massProps.inertiaOrientation.asArray(); - } - this._hknp.HP_Body_SetMassProperties(pluginData.hpBodyId, newProps); - } - _internalSetMotionType(pluginData, motionType) { - switch (motionType) { - case PhysicsMotionType.STATIC: - this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.STATIC); - break; - case PhysicsMotionType.ANIMATED: - this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.KINEMATIC); - break; - case PhysicsMotionType.DYNAMIC: - this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.DYNAMIC); - break; - } - } - setMotionType(body, motionType, instanceIndex) { - this._applyToBodyOrInstances(body, (pluginData) => { - this._internalSetMotionType(pluginData, motionType); - }, instanceIndex); - } - getMotionType(body, instanceIndex) { - const pluginRef = this._getPluginReference(body, instanceIndex); - const type = this._hknp.HP_Body_GetMotionType(pluginRef.hpBodyId)[1]; - switch (type) { - case this._hknp.MotionType.STATIC: - return PhysicsMotionType.STATIC; - case this._hknp.MotionType.KINEMATIC: - return PhysicsMotionType.ANIMATED; - case this._hknp.MotionType.DYNAMIC: - return PhysicsMotionType.DYNAMIC; - } - throw new Error("Unknown motion type: " + type); - } - _internalComputeMassProperties(pluginData) { - const shapeRes = this._hknp.HP_Body_GetShape(pluginData.hpBodyId); - if (shapeRes[0] == this._hknp.Result.RESULT_OK) { - const shapeMass = this._hknp.HP_Shape_BuildMassProperties(shapeRes[1]); - if (shapeMass[0] == this._hknp.Result.RESULT_OK) { - return shapeMass[1]; - } - } - // Failed; return a unit inertia - return [[0, 0, 0], 1, [1, 1, 1], [0, 0, 0, 1]]; - } - /** - * Computes the mass properties of a physics body, from it's shape - * - * @param body - The physics body to copmute the mass properties of - */ - computeMassProperties(body, instanceIndex) { - const pluginRef = this._getPluginReference(body, instanceIndex); - const computed = this._internalComputeMassProperties(pluginRef); - return this._fromMassPropertiesTuple(computed); - } - /** - * Sets the mass properties of a physics body. - * - * @param body - The physics body to set the mass properties of. - * @param massProps - The mass properties to set. - * @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. - * This function is useful for setting the mass properties of a physics body, - * such as its mass, inertia, and center of mass. This is important for - * accurately simulating the physics of the body in the physics engine. - * - */ - setMassProperties(body, massProps, instanceIndex) { - this._applyToBodyOrInstances(body, (pluginData) => { - pluginData.userMassProps = massProps; - this._internalUpdateMassProperties(pluginData); - }, instanceIndex); - } - /** - * - */ - getMassProperties(body, instanceIndex) { - const pluginRef = this._getPluginReference(body, instanceIndex); - const massPropsTuple = this._hknp.HP_Body_GetMassProperties(pluginRef.hpBodyId)[1]; - return this._fromMassPropertiesTuple(massPropsTuple); - } - /** - * Sets the linear damping of the given body. - * @param body - The body to set the linear damping for. - * @param damping - The linear damping to set. - * - * This method is useful for controlling the linear damping of a body in a physics engine. - * Linear damping is a force that opposes the motion of the body, and is proportional to the velocity of the body. - * This method allows the user to set the linear damping of a body, which can be used to control the motion of the body. - */ - setLinearDamping(body, damping, instanceIndex) { - this._applyToBodyOrInstances(body, (pluginData) => { - this._hknp.HP_Body_SetLinearDamping(pluginData.hpBodyId, damping); - }, instanceIndex); - } - /** - * Gets the linear damping of the given body. - * @param body - The body to get the linear damping from. - * @returns The linear damping of the given body. - * - * This method is useful for getting the linear damping of a body in a physics engine. - * Linear damping is a force that opposes the motion of the body and is proportional to the velocity of the body. - * It is used to simulate the effects of air resistance and other forms of friction. - */ - getLinearDamping(body, instanceIndex) { - const pluginRef = this._getPluginReference(body, instanceIndex); - return this._hknp.HP_Body_GetLinearDamping(pluginRef.hpBodyId)[1]; - } - /** - * Sets the angular damping of a physics body. - * @param body - The physics body to set the angular damping for. - * @param damping - The angular damping value to set. - * - * This function is useful for controlling the angular velocity of a physics body. - * By setting the angular damping, the body's angular velocity will be reduced over time, allowing for more realistic physics simulations. - */ - setAngularDamping(body, damping, instanceIndex) { - this._applyToBodyOrInstances(body, (pluginData) => { - this._hknp.HP_Body_SetAngularDamping(pluginData.hpBodyId, damping); - }, instanceIndex); - } - /** - * Gets the angular damping of a physics body. - * @param body - The physics body to get the angular damping from. - * @returns The angular damping of the body. - * - * This function is useful for retrieving the angular damping of a physics body, - * 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. - */ - getAngularDamping(body, instanceIndex) { - const pluginRef = this._getPluginReference(body, instanceIndex); - return this._hknp.HP_Body_GetAngularDamping(pluginRef.hpBodyId)[1]; - } - /** - * Sets the linear velocity of a physics body. - * @param body - The physics body to set the linear velocity of. - * @param linVel - The linear velocity to set. - * - * This function is useful for setting the linear velocity of a physics body, which is necessary for simulating - * motion in a physics engine. The linear velocity is the speed and direction of the body's movement. - */ - setLinearVelocity(body, linVel, instanceIndex) { - this._applyToBodyOrInstances(body, (pluginData) => { - this._hknp.HP_Body_SetLinearVelocity(pluginData.hpBodyId, this._bVecToV3(linVel)); - }, instanceIndex); - } - /** - * Gets the linear velocity of a physics body and stores it in a given vector. - * @param body - The physics body to get the linear velocity from. - * @param linVel - The vector to store the linear velocity in. - * - * This function is useful for retrieving the linear velocity of a physics body, - * which can be used to determine the speed and direction of the body. This - * information can be used to simulate realistic physics behavior in a game. - */ - getLinearVelocityToRef(body, linVel, instanceIndex) { - const pluginRef = this._getPluginReference(body, instanceIndex); - const lv = this._hknp.HP_Body_GetLinearVelocity(pluginRef.hpBodyId)[1]; - this._v3ToBvecRef(lv, linVel); - } - /* - * Apply an operation either to all instances of a body, if instanceIndex is not specified, or to a specific instance. - */ - _applyToBodyOrInstances(body, fnToApply, instanceIndex) { - var _a; - if (((_a = body._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0 && instanceIndex === undefined) { - for (let i = 0; i < body._pluginDataInstances.length; i++) { - fnToApply(body._pluginDataInstances[i]); - } - } - else { - fnToApply(this._getPluginReference(body, instanceIndex)); - } - } - /** - * Applies an impulse to a physics body at a given location. - * @param body - The physics body to apply the impulse to. - * @param impulse - The impulse vector to apply. - * @param location - The location in world space to apply the impulse. - * @param instanceIndex - The index of the instance to apply the impulse to. If not specified, the impulse will be applied to all instances. - * - * This method is useful for applying an impulse to a physics body at a given location. - * This can be used to simulate physical forces such as explosions, collisions, and gravity. - */ - applyImpulse(body, impulse, location, instanceIndex) { - this._applyToBodyOrInstances(body, (pluginRef) => { - this._hknp.HP_Body_ApplyImpulse(pluginRef.hpBodyId, this._bVecToV3(location), this._bVecToV3(impulse)); - }, instanceIndex); - } - /** - * Applies a force to a physics body at a given location. - * @param body - The physics body to apply the impulse to. - * @param force - The force vector to apply. - * @param location - The location in world space to apply the impulse. - * @param instanceIndex - The index of the instance to apply the force to. If not specified, the force will be applied to all instances. - * - * This method is useful for applying a force to a physics body at a given location. - * This can be used to simulate physical forces such as explosions, collisions, and gravity. - */ - applyForce(body, force, location, instanceIndex) { - force.scaleToRef(this.getTimeStep(), this._tmpVec3[0]); - this.applyImpulse(body, this._tmpVec3[0], location, instanceIndex); - } - /** - * Sets the angular velocity of a physics body. - * - * @param body - The physics body to set the angular velocity of. - * @param angVel - The angular velocity to set. - * - * This function is useful for setting the angular velocity of a physics body in a physics engine. - * This allows for more realistic simulations of physical objects, as they can be given a rotational velocity. - */ - setAngularVelocity(body, angVel, instanceIndex) { - this._applyToBodyOrInstances(body, (pluginRef) => { - this._hknp.HP_Body_SetAngularVelocity(pluginRef.hpBodyId, this._bVecToV3(angVel)); - }, instanceIndex); - } - /** - * Gets the angular velocity of a body. - * @param body - The body to get the angular velocity from. - * @param angVel - The vector3 to store the angular velocity. - * - * This method is useful for getting the angular velocity of a body in a physics engine. It - * takes the body and a vector3 as parameters and stores the angular velocity of the body - * in the vector3. This is useful for getting the angular velocity of a body in order to - * calculate the motion of the body in the physics engine. - */ - getAngularVelocityToRef(body, angVel, instanceIndex) { - const pluginRef = this._getPluginReference(body, instanceIndex); - const av = this._hknp.HP_Body_GetAngularVelocity(pluginRef.hpBodyId)[1]; - this._v3ToBvecRef(av, angVel); - } - /** - * Sets the transformation of the given physics body to the given transform node. - * @param body The physics body to set the transformation for. - * @param node The transform node to set the transformation from. - * Sets the transformation of the given physics body to the given transform node. - * - * This function is useful for setting the transformation of a physics body to a - * transform node, which is necessary for the physics engine to accurately simulate - * the motion of the body. It also takes into account instances of the transform - * node, which is necessary for accurate simulation of multiple bodies with the - * same transformation. - */ - setPhysicsBodyTransformation(body, node) { - const transformNode = body.transformNode; - if (body.numInstances > 0) { - // instances - const m = transformNode; - const matrixData = m._thinInstanceDataStorage.matrixData; - if (!matrixData) { - return; // TODO: error handling - } - const instancesCount = body.numInstances; - this._createOrUpdateBodyInstances(body, body.getMotionType(), matrixData, 0, instancesCount, true); - } - else { - // regular - this._hknp.HP_Body_SetQTransform(body._pluginData.hpBodyId, this._getTransformInfos(node)); - } - } - /** - * Set the target transformation (position and rotation) of the body, such that the body will set its velocity to reach that target - * @param body The physics body to set the target transformation for. - * @param position The target position - * @param rotation The target rotation - * @param instanceIndex The index of the instance in an instanced body - */ - setTargetTransform(body, position, rotation, instanceIndex) { - this._applyToBodyOrInstances(body, (pluginRef) => { - this._hknp.HP_Body_SetTargetQTransform(pluginRef.hpBodyId, [this._bVecToV3(position), this._bQuatToV4(rotation)]); - }, instanceIndex); - } - /** - * Sets the gravity factor of a body - * @param body the physics body to set the gravity factor for - * @param factor the gravity factor - * @param instanceIndex the index of the instance in an instanced body - */ - setGravityFactor(body, factor, instanceIndex) { - this._applyToBodyOrInstances(body, (pluginRef) => { - this._hknp.HP_Body_SetGravityFactor(pluginRef.hpBodyId, factor); - }, instanceIndex); - } - /** - * Get the gravity factor of a body - * @param body the physics body to get the gravity factor from - * @param instanceIndex the index of the instance in an instanced body. If not specified, the gravity factor of the first instance will be returned. - * @returns the gravity factor - */ - getGravityFactor(body, instanceIndex) { - const pluginRef = this._getPluginReference(body, instanceIndex); - return this._hknp.HP_Body_GetGravityFactor(pluginRef.hpBodyId)[1]; - } - /** - * Disposes a physics body. - * - * @param body - The physics body to dispose. - * - * This method is useful for releasing the resources associated with a physics body when it is no longer needed. - * This is important for avoiding memory leaks in the physics engine. - */ - disposeBody(body) { - if (body._pluginDataInstances && body._pluginDataInstances.length > 0) { - for (const instance of body._pluginDataInstances) { - this._hknp.HP_Body_Release(instance.hpBodyId); - instance.hpBodyId = undefined; - } - } - if (body._pluginData) { - this._hknp.HP_Body_Release(body._pluginData.hpBodyId); - body._pluginData.hpBodyId = undefined; - } - } - /** - * Initializes a physics shape with the given type and parameters. - * @param shape - The physics shape to initialize. - * @param type - The type of shape to initialize. - * @param options - The parameters for the shape. - * - * This code is useful for initializing a physics shape with the given type and parameters. - * It allows for the creation of a sphere, box, capsule, container, cylinder, mesh, and heightfield. - * Depending on the type of shape, different parameters are required. - * For example, a sphere requires a radius, while a box requires extents and a rotation. - */ - initShape(shape, type, options) { - switch (type) { - case PhysicsShapeType.SPHERE: - { - const radius = options.radius || 1; - const center = options.center ? this._bVecToV3(options.center) : [0, 0, 0]; - shape._pluginData = this._hknp.HP_Shape_CreateSphere(center, radius)[1]; - } - break; - case PhysicsShapeType.BOX: - { - const rotation = options.rotation ? this._bQuatToV4(options.rotation) : [0, 0, 0, 1]; - const extent = options.extents ? this._bVecToV3(options.extents) : [1, 1, 1]; - const center = options.center ? this._bVecToV3(options.center) : [0, 0, 0]; - shape._pluginData = this._hknp.HP_Shape_CreateBox(center, rotation, extent)[1]; - } - break; - case PhysicsShapeType.CAPSULE: - { - const pointA = options.pointA ? this._bVecToV3(options.pointA) : [0, 0, 0]; - const pointB = options.pointB ? this._bVecToV3(options.pointB) : [0, 1, 0]; - const radius = options.radius || 0; - shape._pluginData = this._hknp.HP_Shape_CreateCapsule(pointA, pointB, radius)[1]; - } - break; - case PhysicsShapeType.CONTAINER: - { - shape._pluginData = this._hknp.HP_Shape_CreateContainer()[1]; - } - break; - case PhysicsShapeType.CYLINDER: - { - const pointA = options.pointA ? this._bVecToV3(options.pointA) : [0, 0, 0]; - const pointB = options.pointB ? this._bVecToV3(options.pointB) : [0, 1, 0]; - const radius = options.radius || 0; - shape._pluginData = this._hknp.HP_Shape_CreateCylinder(pointA, pointB, radius)[1]; - } - break; - case PhysicsShapeType.CONVEX_HULL: - case PhysicsShapeType.MESH: - { - const mesh = options.mesh; - if (mesh) { - const includeChildMeshes = !!options.includeChildMeshes; - const needIndices = type != PhysicsShapeType.CONVEX_HULL; - const accum = new MeshAccumulator(mesh, needIndices, mesh === null || mesh === void 0 ? void 0 : mesh.getScene()); - accum.addNodeMeshes(mesh, includeChildMeshes); - const positions = accum.getVertices(this._hknp); - const numVec3s = positions.numObjects / 3; - if (type == PhysicsShapeType.CONVEX_HULL) { - shape._pluginData = this._hknp.HP_Shape_CreateConvexHull(positions.offset, numVec3s)[1]; - } - else { - const triangles = accum.getTriangles(this._hknp); - const numTriangles = triangles.numObjects / 3; - shape._pluginData = this._hknp.HP_Shape_CreateMesh(positions.offset, numVec3s, triangles.offset, numTriangles)[1]; - accum.freeBuffer(this._hknp, triangles); - } - accum.freeBuffer(this._hknp, positions); - } - else { - throw new Error("No mesh provided to create physics shape."); - } - } - break; - default: - throw new Error("Unsupported Shape Type."); - break; - } - } - setShapeFilterMembershipMask(shape, membershipMask) { - const collideWith = this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][1]; - this._hknp.HP_Shape_SetFilterInfo(shape._pluginData, [membershipMask, collideWith]); - } - getShapeFilterMembershipMask(shape) { - return this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][0]; - } - setShapeFilterCollideMask(shape, collideMask) { - const membership = this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][0]; - this._hknp.HP_Shape_SetFilterInfo(shape._pluginData, [membership, collideMask]); - } - getShapeFilterCollideMask(shape) { - return this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][1]; - } - /** - * Sets the material of a physics shape. - * @param shape - The physics shape to set the material of. - * @param material - The material to set. - * - */ - setMaterial(shape, material) { - var _a, _b, _c, _d, _e; - const dynamicFriction = (_a = material.friction) !== null && _a !== void 0 ? _a : 0.5; - const staticFriction = (_b = material.staticFriction) !== null && _b !== void 0 ? _b : dynamicFriction; - const restitution = (_c = material.restitution) !== null && _c !== void 0 ? _c : 0.0; - const frictionCombine = (_d = material.frictionCombine) !== null && _d !== void 0 ? _d : PhysicsMaterialCombineMode.MINIMUM; - const restitutionCombine = (_e = material.restitutionCombine) !== null && _e !== void 0 ? _e : PhysicsMaterialCombineMode.MAXIMUM; - const hpMaterial = [staticFriction, dynamicFriction, restitution, this._materialCombineToNative(frictionCombine), this._materialCombineToNative(restitutionCombine)]; - this._hknp.HP_Shape_SetMaterial(shape._pluginData, hpMaterial); - } - /** - * Sets the density of a physics shape. - * @param shape - The physics shape to set the density of. - * @param density - The density to set. - * - */ - setDensity(shape, density) { - this._hknp.HP_Shape_SetDensity(shape._pluginData, density); - } - /** - * Calculates the density of a given physics shape. - * - * @param shape - The physics shape to calculate the density of. - * @returns The density of the given physics shape. - * - */ - getDensity(shape) { - return this._hknp.HP_Shape_GetDensity(shape._pluginData)[1]; - } - /** - * Gets the transform infos of a given transform node. - * @param node - The transform node. - * @returns An array containing the position and orientation of the node. - * This code is useful for getting the position and orientation of a given transform node. - * It first checks if the node has a rotation quaternion, and if not, it creates one from the node's rotation. - * It then creates an array containing the position and orientation of the node and returns it. - */ - _getTransformInfos(node) { - if (node.parent) { - node.computeWorldMatrix(true); - return [this._bVecToV3(node.absolutePosition), this._bQuatToV4(node.absoluteRotationQuaternion)]; - } - let orientation = TmpVectors.Quaternion[0]; - if (node.rotationQuaternion) { - orientation = node.rotationQuaternion; - } - else { - const r = node.rotation; - Quaternion.FromEulerAnglesToRef(r.x, r.y, r.z, orientation); - } - const transform = [this._bVecToV3(node.position), this._bQuatToV4(orientation)]; - return transform; - } - /** - * Adds a child shape to the given shape. - * @param shape - The parent shape. - * @param newChild - The child shape to add. - * @param translation - The relative translation of the child from the parent shape - * @param rotation - The relative rotation of the child from the parent shape - * @param scale - The relative scale scale of the child from the parent shaep - * - */ - addChild(shape, newChild, translation, rotation, scale) { - const transformNative = [ - translation ? this._bVecToV3(translation) : [0, 0, 0], - rotation ? this._bQuatToV4(rotation) : [0, 0, 0, 1], - scale ? this._bVecToV3(scale) : [1, 1, 1], - ]; - this._hknp.HP_Shape_AddChild(shape._pluginData, newChild._pluginData, transformNative); - } - /** - * Removes a child shape from a parent shape. - * @param shape - The parent shape. - * @param childIndex - The index of the child shape to remove. - * - */ - removeChild(shape, childIndex) { - this._hknp.HP_Shape_RemoveChild(shape._pluginData, childIndex); - } - /** - * Returns the number of children of the given shape. - * - * @param shape - The shape to get the number of children from. - * @returns The number of children of the given shape. - * - */ - getNumChildren(shape) { - return this._hknp.HP_Shape_GetNumChildren(shape._pluginData)[1]; - } - /** - * Marks the shape as a trigger - * @param shape the shape to mark as a trigger - * @param isTrigger if the shape is a trigger - */ - setTrigger(shape, isTrigger) { - this._hknp.HP_Shape_SetTrigger(shape._pluginData, isTrigger); - } - /** - * Calculates the bounding box of a given physics shape. - * - * @param _shape - The physics shape to calculate the bounding box for. - * @returns The calculated bounding box. - * - * This method is useful for physics engines as it allows to calculate the - * boundaries of a given shape. Knowing the boundaries of a shape is important - * for collision detection and other physics calculations. - */ - getBoundingBox(_shape) { - return {}; - } - /** - * Gets the geometry of a physics body. - * - * @param body - The physics body. - * @returns An object containing the positions and indices of the body's geometry. - * - */ - getBodyGeometry(body) { - var _a; - const dataInfo = ((_a = body._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0 ? body._pluginDataInstances[0] : body._pluginData; - const shape = this._hknp.HP_Body_GetShape(dataInfo.hpBodyId)[1]; - const geometryRes = this._hknp.HP_Shape_CreateDebugDisplayGeometry(shape); - if (geometryRes[0] != this._hknp.Result.RESULT_OK) { - return { positions: [], indices: [] }; - } - const geometryInfo = this._hknp.HP_DebugGeometry_GetInfo(geometryRes[1])[1]; - const positionsInPlugin = new Float32Array(this._hknp.HEAPU8.buffer, geometryInfo[0], geometryInfo[1] * 3); // 3 floats per position - const indicesInPlugin = new Uint32Array(this._hknp.HEAPU8.buffer, geometryInfo[2], geometryInfo[3] * 3); // 3 indices per triangle - // HP_DebugGeometry_Release will free the buffer in the plugin. To avoid a - // use-after-free, we need to make a copy of the data here. - const positions = positionsInPlugin.slice(0); - const indices = indicesInPlugin.slice(0); - this._hknp.HP_DebugGeometry_Release(geometryRes[1]); - return { positions: positions, indices: indices }; - } - /** - * Releases a physics shape from the physics engine. - * - * @param shape - The physics shape to be released. - * @returns void - * - * This method is useful for releasing a physics shape from the physics engine, freeing up resources and preventing memory leaks. - */ - disposeShape(shape) { - this._hknp.HP_Shape_Release(shape._pluginData); - shape._pluginData = undefined; - } - // constraint - /** - * Initializes a physics constraint with the given parameters. - * - * @param constraint - The physics constraint to be initialized. - * @param body - The main body - * @param childBody - The child body. - * @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. - * @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. - * - * This function is useful for setting up a physics constraint in a physics engine. - */ - initConstraint(constraint, body, childBody, instanceIndex, childInstanceIndex) { - var _a, _b, _c, _d; - const type = constraint.type; - const options = constraint.options; - if (!type || !options) { - Logger.Warn("No constraint type or options. Constraint is invalid."); - return; - } - if ((body._pluginDataInstances.length > 0 && instanceIndex === undefined) || (childBody._pluginDataInstances.length > 0 && childInstanceIndex === undefined)) { - Logger.Warn("Body is instanced but no instance index was specified. Constraint will not be applied."); - return; - } - const jointId = this._hknp.HP_Constraint_Create()[1]; - constraint._pluginData = jointId; - // body parenting - const bodyA = this._getPluginReference(body, instanceIndex).hpBodyId; - const bodyB = this._getPluginReference(childBody, childInstanceIndex).hpBodyId; - this._hknp.HP_Constraint_SetParentBody(jointId, bodyA); - this._hknp.HP_Constraint_SetChildBody(jointId, bodyB); - // anchors - const pivotA = options.pivotA ? this._bVecToV3(options.pivotA) : this._bVecToV3(Vector3.Zero()); - const axisA = (_a = options.axisA) !== null && _a !== void 0 ? _a : new Vector3(1, 0, 0); - const perpAxisA = this._tmpVec3[0]; - if (options.perpAxisA) { - perpAxisA.copyFrom(options.perpAxisA); - } - else { - axisA.getNormalToRef(perpAxisA); - } - this._hknp.HP_Constraint_SetAnchorInParent(jointId, pivotA, this._bVecToV3(axisA), this._bVecToV3(perpAxisA)); - const pivotB = options.pivotB ? this._bVecToV3(options.pivotB) : this._bVecToV3(Vector3.Zero()); - const axisB = (_b = options.axisB) !== null && _b !== void 0 ? _b : new Vector3(1, 0, 0); - const perpAxisB = this._tmpVec3[0]; - if (options.perpAxisB) { - perpAxisB.copyFrom(options.perpAxisB); - } - else { - axisB.getNormalToRef(perpAxisB); - } - this._hknp.HP_Constraint_SetAnchorInChild(jointId, pivotB, this._bVecToV3(axisB), this._bVecToV3(perpAxisB)); - if (type == PhysicsConstraintType.LOCK) { - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED); - } - else if (type == PhysicsConstraintType.DISTANCE) { - const distance = options.maxDistance || 0; - const dist3d = this._hknp.ConstraintAxis.LINEAR_DISTANCE; - this._hknp.HP_Constraint_SetAxisMode(jointId, dist3d, this._hknp.ConstraintAxisLimitMode.LIMITED); - this._hknp.HP_Constraint_SetAxisMinLimit(jointId, dist3d, distance); - this._hknp.HP_Constraint_SetAxisMaxLimit(jointId, dist3d, distance); - } - else if (type == PhysicsConstraintType.HINGE) { - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED); - } - else if (type == PhysicsConstraintType.PRISMATIC) { - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED); - } - else if (type == PhysicsConstraintType.SLIDER) { - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED); - } - else if (type == PhysicsConstraintType.BALL_AND_SOCKET) { - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED); - this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED); - } - else if (type == PhysicsConstraintType.SIX_DOF) { - const sixdofData = constraint; - for (const l of sixdofData.limits) { - const axId = this._constraintAxisToNative(l.axis); - if (((_c = l.minLimit) !== null && _c !== void 0 ? _c : -1) == 0 && ((_d = l.maxLimit) !== null && _d !== void 0 ? _d : -1) == 0) { - this._hknp.HP_Constraint_SetAxisMode(jointId, axId, this._hknp.ConstraintAxisLimitMode.LOCKED); - } - else { - if (l.minLimit != undefined) { - this._hknp.HP_Constraint_SetAxisMode(jointId, axId, this._hknp.ConstraintAxisLimitMode.LIMITED); - this._hknp.HP_Constraint_SetAxisMinLimit(jointId, axId, l.minLimit); - } - if (l.maxLimit != undefined) { - this._hknp.HP_Constraint_SetAxisMode(jointId, axId, this._hknp.ConstraintAxisLimitMode.LIMITED); - this._hknp.HP_Constraint_SetAxisMaxLimit(jointId, axId, l.maxLimit); - } - } - if (l.stiffness) { - this._hknp.HP_Constraint_SetAxisStiffness(jointId, axId, l.stiffness); - } - if (l.damping) { - this._hknp.HP_Constraint_SetAxisDamping(jointId, axId, l.damping); - } - } - } - else { - throw new Error("Unsupported Constraint Type."); - } - const collisionEnabled = !!options.collision; - this._hknp.HP_Constraint_SetCollisionsEnabled(jointId, collisionEnabled); - this._hknp.HP_Constraint_SetEnabled(jointId, true); - } - /** - * Adds a constraint to the physics engine. - * - * @param body - The main body to which the constraint is applied. - * @param childBody - The body to which the constraint is applied. - * @param constraint - The constraint to be applied. - * @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. - * @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. - */ - addConstraint(body, childBody, constraint, instanceIndex, childInstanceIndex) { - //<todo It's real weird that initConstraint() is called only after adding to a body! - this.initConstraint(constraint, body, childBody, instanceIndex, childInstanceIndex); - } - /** - * Enables or disables a constraint in the physics engine. - * @param constraint - The constraint to enable or disable. - * @param isEnabled - Whether the constraint should be enabled or disabled. - * - */ - setEnabled(constraint, isEnabled) { - this._hknp.HP_Constraint_SetEnabled(constraint._pluginData, isEnabled); - } - /** - * Gets the enabled state of the given constraint. - * @param constraint - The constraint to get the enabled state from. - * @returns The enabled state of the given constraint. - * - */ - getEnabled(constraint) { - return this._hknp.HP_Constraint_GetEnabled(constraint._pluginData)[1]; - } - /** - * Enables or disables collisions for the given constraint. - * @param constraint - The constraint to enable or disable collisions for. - * @param isEnabled - Whether collisions should be enabled or disabled. - * - */ - setCollisionsEnabled(constraint, isEnabled) { - this._hknp.HP_Constraint_SetCollisionsEnabled(constraint._pluginData, isEnabled); - } - /** - * Gets whether collisions are enabled for the given constraint. - * @param constraint - The constraint to get collisions enabled for. - * @returns Whether collisions are enabled for the given constraint. - * - */ - getCollisionsEnabled(constraint) { - return this._hknp.HP_Constraint_GetCollisionsEnabled(constraint._pluginData)[1]; - } - /** - * Sets the friction of the given axis of the given constraint. - * - * @param constraint - The constraint to set the friction of. - * @param axis - The axis of the constraint to set the friction of. - * @param friction - The friction to set. - * @returns void - * - */ - setAxisFriction(constraint, axis, friction) { - this._hknp.HP_Constraint_SetAxisFriction(constraint._pluginData, this._constraintAxisToNative(axis), friction); - } - /** - * Gets the friction value of the specified axis of the given constraint. - * - * @param constraint - The constraint to get the axis friction from. - * @param axis - The axis to get the friction from. - * @returns The friction value of the specified axis. - * - */ - getAxisFriction(constraint, axis) { - return this._hknp.HP_Constraint_GetAxisFriction(constraint._pluginData, this._constraintAxisToNative(axis))[1]; - } - /** - * Sets the limit mode of the specified axis of the given constraint. - * @param constraint - The constraint to set the axis mode of. - * @param axis - The axis to set the limit mode of. - * @param limitMode - The limit mode to set. - */ - setAxisMode(constraint, axis, limitMode) { - this._hknp.HP_Constraint_SetAxisMode(constraint._pluginData, this._constraintAxisToNative(axis), this._limitModeToNative(limitMode)); - } - /** - * Gets the axis limit mode of the given constraint. - * - * @param constraint - The constraint to get the axis limit mode from. - * @param axis - The axis to get the limit mode from. - * @returns The axis limit mode of the given constraint. - * - */ - getAxisMode(constraint, axis) { - const mode = this._hknp.HP_Constraint_GetAxisMode(constraint._pluginData, this._constraintAxisToNative(axis))[1]; - return this._nativeToLimitMode(mode); - } - /** - * Sets the minimum limit of the given axis of the given constraint. - * @param constraint - The constraint to set the minimum limit of. - * @param axis - The axis to set the minimum limit of. - * @param limit - The minimum limit to set. - * - */ - setAxisMinLimit(constraint, axis, limit) { - this._hknp.HP_Constraint_SetAxisMinLimit(constraint._pluginData, this._constraintAxisToNative(axis), limit); - } - /** - * Gets the minimum limit of the specified axis of the given constraint. - * @param constraint - The constraint to get the minimum limit from. - * @param axis - The axis to get the minimum limit from. - * @returns The minimum limit of the specified axis of the given constraint. - * - */ - getAxisMinLimit(constraint, axis) { - return this._hknp.HP_Constraint_GetAxisMinLimit(constraint._pluginData, this._constraintAxisToNative(axis))[1]; - } - /** - * Sets the maximum limit of the given axis of the given constraint. - * @param constraint - The constraint to set the maximum limit of the given axis. - * @param axis - The axis to set the maximum limit of. - * @param limit - The maximum limit to set. - * - */ - setAxisMaxLimit(constraint, axis, limit) { - this._hknp.HP_Constraint_SetAxisMaxLimit(constraint._pluginData, this._constraintAxisToNative(axis), limit); - } - /** - * Gets the maximum limit of the given axis of the given constraint. - * - * @param constraint - The constraint to get the maximum limit from. - * @param axis - The axis to get the maximum limit from. - * @returns The maximum limit of the given axis of the given constraint. - * - */ - getAxisMaxLimit(constraint, axis) { - return this._hknp.HP_Constraint_GetAxisMaxLimit(constraint._pluginData, this._constraintAxisToNative(axis))[1]; - } - /** - * Sets the motor type of the given axis of the given constraint. - * @param constraint - The constraint to set the motor type of. - * @param axis - The axis of the constraint to set the motor type of. - * @param motorType - The motor type to set. - * @returns void - * - */ - setAxisMotorType(constraint, axis, motorType) { - this._hknp.HP_Constraint_SetAxisMotorType(constraint._pluginData, this._constraintAxisToNative(axis), this._constraintMotorTypeToNative(motorType)); - } - /** - * Gets the motor type of the specified axis of the given constraint. - * @param constraint - The constraint to get the motor type from. - * @param axis - The axis of the constraint to get the motor type from. - * @returns The motor type of the specified axis of the given constraint. - * - */ - getAxisMotorType(constraint, axis) { - return this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(constraint._pluginData, this._constraintAxisToNative(axis))[1]); - } - /** - * Sets the target of an axis motor of a constraint. - * - * @param constraint - The constraint to set the axis motor target of. - * @param axis - The axis of the constraint to set the motor target of. - * @param target - The target of the axis motor. - * - */ - setAxisMotorTarget(constraint, axis, target) { - this._hknp.HP_Constraint_SetAxisMotorTarget(constraint._pluginData, this._constraintAxisToNative(axis), target); - } - /** - * Gets the target of the motor of the given axis of the given constraint. - * - * @param constraint - The constraint to get the motor target from. - * @param axis - The axis of the constraint to get the motor target from. - * @returns The target of the motor of the given axis of the given constraint. - * - */ - getAxisMotorTarget(constraint, axis) { - return this._hknp.HP_Constraint_GetAxisMotorTarget(constraint._pluginData, this._constraintAxisToNative(axis))[1]; - } - /** - * Sets the maximum force that can be applied by the motor of the given constraint axis. - * @param constraint - The constraint to set the motor max force for. - * @param axis - The axis of the constraint to set the motor max force for. - * @param maxForce - The maximum force that can be applied by the motor. - * - */ - setAxisMotorMaxForce(constraint, axis, maxForce) { - this._hknp.HP_Constraint_SetAxisMotorMaxForce(constraint._pluginData, this._constraintAxisToNative(axis), maxForce); - } - /** - * Gets the maximum force of the motor of the given constraint axis. - * - * @param constraint - The constraint to get the motor maximum force from. - * @param axis - The axis of the constraint to get the motor maximum force from. - * @returns The maximum force of the motor of the given constraint axis. - * - */ - getAxisMotorMaxForce(constraint, axis) { - return this._hknp.HP_Constraint_GetAxisMotorMaxForce(constraint._pluginData, this._constraintAxisToNative(axis))[1]; - } - /** - * Disposes a physics constraint. - * - * @param constraint - The physics constraint to dispose. - * - * This method is useful for releasing the resources associated with a physics constraint, such as - * the Havok constraint, when it is no longer needed. This is important for avoiding memory leaks. - */ - disposeConstraint(constraint) { - const jointId = constraint._pluginData; - this._hknp.HP_Constraint_SetEnabled(jointId, false); - this._hknp.HP_Constraint_Release(jointId); - constraint._pluginData = undefined; - } - /** - * Performs a raycast from a given start point to a given end point and stores the result in a given PhysicsRaycastResult object. - * - * @param from - The start point of the raycast. - * @param to - The end point of the raycast. - * @param result - The PhysicsRaycastResult object to store the result of the raycast. - * @param query - The raycast query options. See [[IRaycastQuery]] for more information. - * - * Performs a raycast. It takes in two points, from and to, and a PhysicsRaycastResult object to store the result of the raycast. - * It then performs the raycast and stores the hit data in the PhysicsRaycastResult object. - */ - raycast(from, to, result, query) { - var _a, _b; - const queryMembership = (_a = query === null || query === void 0 ? void 0 : query.membership) !== null && _a !== void 0 ? _a : ~0; - const queryCollideWith = (_b = query === null || query === void 0 ? void 0 : query.collideWith) !== null && _b !== void 0 ? _b : ~0; - result.reset(from, to); - const hkQuery = [this._bVecToV3(from), this._bVecToV3(to), [queryMembership, queryCollideWith]]; - this._hknp.HP_World_CastRayWithCollector(this.world, this._queryCollector, hkQuery); - if (this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1] > 0) { - const hitData = this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector, 0)[1]; - const hitPos = hitData[1][3]; - const hitNormal = hitData[1][4]; - const hitTriangle = hitData[1][5]; - result.setHitData({ x: hitNormal[0], y: hitNormal[1], z: hitNormal[2] }, { x: hitPos[0], y: hitPos[1], z: hitPos[2] }, hitTriangle); - result.calculateHitDistance(); - const hitBody = this._bodies.get(hitData[1][0][0]); - result.body = hitBody === null || hitBody === void 0 ? void 0 : hitBody.body; - result.bodyIndex = hitBody === null || hitBody === void 0 ? void 0 : hitBody.index; - } - } - /** - * Return the collision observable for a particular physics body. - * @param body the physics body - */ - getCollisionObservable(body) { - const bodyId = body._pluginData.hpBodyId[0]; - let observable = this._bodyCollisionObservable.get(bodyId); - if (!observable) { - observable = new Observable(); - this._bodyCollisionObservable.set(bodyId, observable); - } - return observable; - } - /** - * Enable collision to be reported for a body when a callback is settup on the world - * @param body the physics body - * @param enabled - */ - setCollisionCallbackEnabled(body, enabled) { - // Register for collide events by default - const collideEvents = this._hknp.EventType.COLLISION_STARTED.value | this._hknp.EventType.COLLISION_CONTINUED.value | this._hknp.EventType.COLLISION_FINISHED.value; - if (body._pluginDataInstances && body._pluginDataInstances.length) { - body._pluginDataInstances.forEach((bodyId) => { - this._hknp.HP_Body_SetEventMask(bodyId.hpBodyId, enabled ? collideEvents : 0); - }); - } - else if (body._pluginData) { - this._hknp.HP_Body_SetEventMask(body._pluginData.hpBodyId, enabled ? collideEvents : 0); - } - } - _notifyTriggers() { - let eventAddress = this._hknp.HP_World_GetTriggerEvents(this.world)[1]; - const event = new TriggerEvent(); - while (eventAddress) { - TriggerEvent.readToRef(this._hknp.HEAPU8.buffer, eventAddress, event); - const bodyInfoA = this._bodies.get(event.bodyIdA); - const bodyInfoB = this._bodies.get(event.bodyIdB); - const triggerCollisionInfo = { - collider: bodyInfoA.body, - colliderIndex: bodyInfoA.index, - collidedAgainst: bodyInfoB.body, - collidedAgainstIndex: bodyInfoB.index, - type: this._nativeTriggerCollisionValueToCollisionType(event.type), - }; - this.onTriggerCollisionObservable.notifyObservers(triggerCollisionInfo); - eventAddress = this._hknp.HP_World_GetNextTriggerEvent(this.world, eventAddress); - } - } - /** - * Runs thru all detected collisions and filter by body - */ - _notifyCollisions() { - let eventAddress = this._hknp.HP_World_GetCollisionEvents(this.world)[1]; - const event = new CollisionEvent(); - const worldAddr = Number(this.world); - while (eventAddress) { - CollisionEvent.readToRef(this._hknp.HEAPU8.buffer, eventAddress, event); - const bodyInfoA = this._bodies.get(event.contactOnA.bodyId); - const bodyInfoB = this._bodies.get(event.contactOnB.bodyId); - const collisionInfo = { - collider: bodyInfoA.body, - colliderIndex: bodyInfoA.index, - collidedAgainst: bodyInfoB.body, - collidedAgainstIndex: bodyInfoB.index, - type: this._nativeCollisionValueToCollisionType(event.type), - }; - if (collisionInfo.type === PhysicsEventType.COLLISION_FINISHED) { - this.onCollisionEndedObservable.notifyObservers(collisionInfo); - } - else { - event.contactOnB.position.subtractToRef(event.contactOnA.position, this._tmpVec3[0]); - const distance = Vector3.Dot(this._tmpVec3[0], event.contactOnA.normal); - collisionInfo.point = event.contactOnA.position; - collisionInfo.distance = distance; - collisionInfo.impulse = event.impulseApplied; - collisionInfo.normal = event.contactOnA.normal; - this.onCollisionObservable.notifyObservers(collisionInfo); - } - if (this._bodyCollisionObservable.size && collisionInfo.type !== PhysicsEventType.COLLISION_FINISHED) { - const observableA = this._bodyCollisionObservable.get(event.contactOnA.bodyId); - const observableB = this._bodyCollisionObservable.get(event.contactOnB.bodyId); - if (observableA) { - observableA.notifyObservers(collisionInfo); - } - else if (observableB) { - //<todo This seems like it would give unexpected results when both bodies have observers? - // Flip collision info: - collisionInfo.collider = bodyInfoB.body; - collisionInfo.colliderIndex = bodyInfoB.index; - collisionInfo.collidedAgainst = bodyInfoA.body; - collisionInfo.collidedAgainstIndex = bodyInfoA.index; - collisionInfo.normal = event.contactOnB.normal; - observableB.notifyObservers(collisionInfo); - } - } - eventAddress = this._hknp.HP_World_GetNextCollisionEvent(worldAddr, eventAddress); - } - } - /** - * Gets the number of bodies in the world - */ - get numBodies() { - return this._hknp.HP_World_GetNumBodies(this.world)[1]; - } - /** - * Dispose the world and free resources - */ - dispose() { - this._hknp.HP_QueryCollector_Release(this._queryCollector); - this._queryCollector = BigInt(0); - this._hknp.HP_World_Release(this.world); - this.world = undefined; - } - _v3ToBvecRef(v, vec3) { - vec3.set(v[0], v[1], v[2]); - } - _bVecToV3(v) { - return [v._x, v._y, v._z]; - } - _bQuatToV4(q) { - return [q._x, q._y, q._z, q._w]; - } - _constraintMotorTypeToNative(motorType) { - switch (motorType) { - case PhysicsConstraintMotorType.POSITION: - return this._hknp.ConstraintMotorType.POSITION; - case PhysicsConstraintMotorType.VELOCITY: - return this._hknp.ConstraintMotorType.VELOCITY; - } - return this._hknp.ConstraintMotorType.NONE; - } - _nativeToMotorType(motorType) { - switch (motorType) { - case this._hknp.ConstraintMotorType.POSITION: - return PhysicsConstraintMotorType.POSITION; - case this._hknp.ConstraintMotorType.VELOCITY: - return PhysicsConstraintMotorType.VELOCITY; - } - return PhysicsConstraintMotorType.NONE; - } - _materialCombineToNative(mat) { - switch (mat) { - case PhysicsMaterialCombineMode.GEOMETRIC_MEAN: - return this._hknp.MaterialCombine.GEOMETRIC_MEAN; - case PhysicsMaterialCombineMode.MINIMUM: - return this._hknp.MaterialCombine.MINIMUM; - case PhysicsMaterialCombineMode.MAXIMUM: - return this._hknp.MaterialCombine.MAXIMUM; - case PhysicsMaterialCombineMode.ARITHMETIC_MEAN: - return this._hknp.MaterialCombine.ARITHMETIC_MEAN; - case PhysicsMaterialCombineMode.MULTIPLY: - return this._hknp.MaterialCombine.MULTIPLY; - } - } - _constraintAxisToNative(axId) { - switch (axId) { - case PhysicsConstraintAxis.LINEAR_X: - return this._hknp.ConstraintAxis.LINEAR_X; - case PhysicsConstraintAxis.LINEAR_Y: - return this._hknp.ConstraintAxis.LINEAR_Y; - case PhysicsConstraintAxis.LINEAR_Z: - return this._hknp.ConstraintAxis.LINEAR_Z; - case PhysicsConstraintAxis.ANGULAR_X: - return this._hknp.ConstraintAxis.ANGULAR_X; - case PhysicsConstraintAxis.ANGULAR_Y: - return this._hknp.ConstraintAxis.ANGULAR_Y; - case PhysicsConstraintAxis.ANGULAR_Z: - return this._hknp.ConstraintAxis.ANGULAR_Z; - case PhysicsConstraintAxis.LINEAR_DISTANCE: - return this._hknp.ConstraintAxis.LINEAR_DISTANCE; - } - } - _nativeToLimitMode(mode) { - switch (mode) { - case this._hknp.ConstraintAxisLimitMode.FREE: - return PhysicsConstraintAxisLimitMode.FREE; - case this._hknp.ConstraintAxisLimitMode.LIMITED: - return PhysicsConstraintAxisLimitMode.LIMITED; - case this._hknp.ConstraintAxisLimitMode.LOCKED: - return PhysicsConstraintAxisLimitMode.LOCKED; - } - return PhysicsConstraintAxisLimitMode.FREE; - } - _limitModeToNative(mode) { - switch (mode) { - case PhysicsConstraintAxisLimitMode.FREE: - return this._hknp.ConstraintAxisLimitMode.FREE; - case PhysicsConstraintAxisLimitMode.LIMITED: - return this._hknp.ConstraintAxisLimitMode.LIMITED; - case PhysicsConstraintAxisLimitMode.LOCKED: - return this._hknp.ConstraintAxisLimitMode.LOCKED; - } - } - _nativeCollisionValueToCollisionType(type) { - switch (type) { - case this._hknp.EventType.COLLISION_STARTED.value: - return PhysicsEventType.COLLISION_STARTED; - case this._hknp.EventType.COLLISION_FINISHED.value: - return PhysicsEventType.COLLISION_FINISHED; - case this._hknp.EventType.COLLISION_CONTINUED.value: - return PhysicsEventType.COLLISION_CONTINUED; - } - return PhysicsEventType.COLLISION_STARTED; - } - _nativeTriggerCollisionValueToCollisionType(type) { - switch (type) { - case 8: - return PhysicsEventType.TRIGGER_ENTERED; - case 16: - return PhysicsEventType.TRIGGER_EXITED; - } - return PhysicsEventType.TRIGGER_ENTERED; - } -} -//# sourceMappingURL=havokPlugin.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/Plugins/index.js - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - -/* eslint-disable import/no-internal-modules */ - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/joinedPhysicsEngineComponent.js - - - - - - -/** - * Gets the current physics engine - * @returns a IPhysicsEngine or null if none attached - */ -scene_Scene.prototype.getPhysicsEngine = function () { - return this._physicsEngine; -}; -/** - * Enables physics to the current scene - * @param gravity defines the scene's gravity for the physics engine - * @param plugin defines the physics engine to be used. defaults to CannonJS. - * @returns a boolean indicating if the physics engine was initialized - */ -scene_Scene.prototype.enablePhysics = function (gravity = null, plugin) { - if (this._physicsEngine) { - return true; - } - // Register the component to the scene - let component = this._getComponent(sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE); - if (!component) { - component = new PhysicsEngineSceneComponent(this); - this._addComponent(component); - } - try { - if (!plugin || (plugin === null || plugin === void 0 ? void 0 : plugin.getPluginVersion()) === 1) { - this._physicsEngine = new PhysicsEngine(gravity, plugin); - } - else if ((plugin === null || plugin === void 0 ? void 0 : plugin.getPluginVersion()) === 2) { - this._physicsEngine = new physicsEngine_PhysicsEngine(gravity, plugin); - } - else { - throw new Error("Unsupported Physics plugin version."); - } - this._physicsTimeAccumulator = 0; - return true; - } - catch (e) { - logger_Logger.Error(e.message); - return false; - } -}; -/** - * Disables and disposes the physics engine associated with the scene - */ -scene_Scene.prototype.disablePhysicsEngine = function () { - if (!this._physicsEngine) { - return; - } - this._physicsEngine.dispose(); - this._physicsEngine = null; -}; -/** - * Gets a boolean indicating if there is an active physics engine - * @returns a boolean indicating if there is an active physics engine - */ -scene_Scene.prototype.isPhysicsEnabled = function () { - return this._physicsEngine !== undefined; -}; -/** - * Deletes a physics compound impostor - * @param compound defines the compound to delete - */ -scene_Scene.prototype.deleteCompoundImpostor = function (compound) { - const mesh = compound.parts[0].mesh; - if (mesh.physicsImpostor) { - mesh.physicsImpostor.dispose( /*true*/); - mesh.physicsImpostor = null; - } -}; -/** - * @internal - */ -scene_Scene.prototype._advancePhysicsEngineStep = function (step) { - if (this._physicsEngine) { - const subTime = this._physicsEngine.getSubTimeStep(); - if (subTime > 0) { - this._physicsTimeAccumulator += step; - while (this._physicsTimeAccumulator > subTime) { - this.onBeforePhysicsObservable.notifyObservers(this); - this._physicsEngine._step(subTime / 1000); - this.onAfterPhysicsObservable.notifyObservers(this); - this._physicsTimeAccumulator -= subTime; - } - } - else { - this.onBeforePhysicsObservable.notifyObservers(this); - this._physicsEngine._step(step / 1000); - this.onAfterPhysicsObservable.notifyObservers(this); - } - } -}; -/** - * Defines the physics engine scene component responsible to manage a physics engine - */ -class PhysicsEngineSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE; - this.scene = scene; - this.scene.onBeforePhysicsObservable = new observable_Observable(); - this.scene.onAfterPhysicsObservable = new observable_Observable(); - // Replace the function used to get the deterministic frame time - this.scene.getDeterministicFrameTime = () => { - if (this.scene._physicsEngine) { - return this.scene._physicsEngine.getTimeStep() * 1000; - } - return 1000.0 / 60.0; - }; - } - /** - * Registers the component in a given scene - */ - register() { } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing to do for this component - } - /** - * Disposes the component and the associated resources - */ - dispose() { - this.scene.onBeforePhysicsObservable.clear(); - this.scene.onAfterPhysicsObservable.clear(); - if (this.scene._physicsEngine) { - this.scene.disablePhysicsEngine(); - } - } -} -//# sourceMappingURL=joinedPhysicsEngineComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/v2/physicsEngineComponent.js - - -Object.defineProperty(transformNode_TransformNode.prototype, "physicsBody", { - get: function () { - return this._physicsBody; - }, - set: function (value) { - if (this._physicsBody === value) { - return; - } - if (this._disposePhysicsObserver) { - this.onDisposeObservable.remove(this._disposePhysicsObserver); - } - this._physicsBody = value; - if (value) { - this._disposePhysicsObserver = this.onDisposeObservable.add(() => { - // Physics - if (this.physicsBody) { - this.physicsBody.dispose( /*!doNotRecurse*/); - this.physicsBody = null; - } - }); - } - }, - enumerable: true, - configurable: true, -}); -/** - * Gets the current physics body - * @returns a physics body or null - */ -transformNode_TransformNode.prototype.getPhysicsBody = function () { - return this.physicsBody; -}; -/** - * Apply a physic impulse to the mesh - * @param force defines the force to apply - * @param contactPoint defines where to apply the force - * @returns the current mesh - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine - */ -transformNode_TransformNode.prototype.applyImpulse = function (force, contactPoint) { - if (!this.physicsBody) { - throw new Error("No Physics Body for TransformNode"); - } - this.physicsBody.applyImpulse(force, contactPoint); - return this; -}; -//# sourceMappingURL=physicsEngineComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/physicsEngineComponent.js -// back compat - - - -//# sourceMappingURL=physicsEngineComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/physicsHelper.js - - - - - - -class HelperTools { - /* - * Gets the hit contact point between a mesh and a ray. The method varies between - * the different plugin versions; V1 uses a mesh intersection, V2 uses the physics body instance/object center (to avoid a raycast and improve perf). - */ - static GetContactPointToRef(mesh, origin, direction, result, instanceIndex) { - const engine = mesh.getScene().getPhysicsEngine(); - const pluginVersion = engine === null || engine === void 0 ? void 0 : engine.getPluginVersion(); - if (pluginVersion === 1) { - const ray = new ray_Ray(origin, direction); - const hit = ray.intersectsMesh(mesh); - if (hit.hit && hit.pickedPoint) { - result.copyFrom(hit.pickedPoint); - return true; - } - } - else if (pluginVersion === 2) { - mesh.physicsBody.getObjectCenterWorldToRef(result, instanceIndex); - return true; - } - return false; - } - /** - * Checks if a body will be affected by forces - * @param body the body to check - * @param instanceIndex for instanced bodies, the index of the instance to check - * @returns - */ - static HasAppliedForces(body, instanceIndex) { - var _a, _b, _c; - return (body.getMotionType(instanceIndex) === IPhysicsEnginePlugin_PhysicsMotionType.STATIC || - ((_b = (_a = body.getMassProperties(instanceIndex)) === null || _a === void 0 ? void 0 : _a.mass) !== null && _b !== void 0 ? _b : 0) === 0 || - ((_c = body.transformNode) === null || _c === void 0 ? void 0 : _c.getTotalVertices()) === 0); - } - /** - * Checks if a point is inside a cylinder - * @param point point to check - * @param origin cylinder origin on the bottom - * @param radius cylinder radius - * @param height cylinder height - * @returns - */ - static IsInsideCylinder(point, origin, radius, height) { - const distance = math_vector_TmpVectors.Vector3[0]; - point.subtractToRef(origin, distance); - return Math.abs(distance.x) <= radius && Math.abs(distance.z) <= radius && distance.y >= 0 && distance.y <= height; - } -} -/** - * A helper for physics simulations - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine#further-functionality-of-the-impostor-class - */ -class PhysicsHelper { - /** - * Initializes the Physics helper - * @param scene Babylon.js scene - */ - constructor(scene) { - this._hitData = { force: new Vector3(), contactPoint: new Vector3(), distanceFromOrigin: 0 }; - this._scene = scene; - this._physicsEngine = this._scene.getPhysicsEngine(); - if (!this._physicsEngine) { - Logger.Warn("Physics engine not enabled. Please enable the physics before you can use the methods."); - return; - } - } - /** - * Applies a radial explosion impulse - * @param origin the origin of the explosion - * @param radiusOrEventOptions the radius or the options of radial explosion - * @param strength the explosion strength - * @param falloff possible options: Constant & Linear. Defaults to Constant - * @returns A physics radial explosion event, or null - */ - applyRadialExplosionImpulse(origin, radiusOrEventOptions, strength, falloff) { - if (!this._physicsEngine) { - Logger.Warn("Physics engine not enabled. Please enable the physics before you call this method."); - return null; - } - if (this._physicsEngine.getPluginVersion() === 1 && this._physicsEngine.getImpostors().length === 0) { - return null; - } - if (this._physicsEngine.getPluginVersion() === 2 && this._physicsEngine.getBodies().length === 0) { - return null; - } - let useCallback = false; - if (typeof radiusOrEventOptions === "number") { - const r = radiusOrEventOptions; - radiusOrEventOptions = new PhysicsRadialExplosionEventOptions(); - radiusOrEventOptions.radius = r; - radiusOrEventOptions.strength = strength !== null && strength !== void 0 ? strength : radiusOrEventOptions.strength; - radiusOrEventOptions.falloff = falloff !== null && falloff !== void 0 ? falloff : radiusOrEventOptions.falloff; - } - else { - useCallback = !!(radiusOrEventOptions.affectedImpostorsCallback || radiusOrEventOptions.affectedBodiesCallback); - } - const event = new PhysicsRadialExplosionEvent(this._scene, radiusOrEventOptions); - const hitData = this._hitData; - if (this._physicsEngine.getPluginVersion() === 1) { - const affectedImpostorsWithData = Array(); - const impostors = this._physicsEngine.getImpostors(); - impostors.forEach((impostor) => { - if (!event.getImpostorHitData(impostor, origin, hitData)) { - return; - } - impostor.applyImpulse(hitData.force, hitData.contactPoint); - if (useCallback) { - affectedImpostorsWithData.push({ - impostor: impostor, - hitData: this._copyPhysicsHitData(hitData), - }); - } - }); - event.triggerAffectedImpostorsCallback(affectedImpostorsWithData); - } - else { - this._applicationForBodies(event, origin, hitData, useCallback, (body, hitData) => { - body.applyImpulse(hitData.force, hitData.contactPoint, hitData.instanceIndex); - }); - } - event.dispose(false); - return event; - } - /** - * Applies a radial explosion force - * @param origin the origin of the explosion - * @param radiusOrEventOptions the radius or the options of radial explosion - * @param strength the explosion strength - * @param falloff possible options: Constant & Linear. Defaults to Constant - * @returns A physics radial explosion event, or null - */ - applyRadialExplosionForce(origin, radiusOrEventOptions, strength, falloff) { - if (!this._physicsEngine) { - Logger.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."); - return null; - } - if (this._physicsEngine.getPluginVersion() === 1 && this._physicsEngine.getImpostors().length === 0) { - return null; - } - if (this._physicsEngine.getPluginVersion() === 2 && this._physicsEngine.getBodies().length === 0) { - return null; - } - let useCallback = false; - if (typeof radiusOrEventOptions === "number") { - const r = radiusOrEventOptions; - radiusOrEventOptions = new PhysicsRadialExplosionEventOptions(); - radiusOrEventOptions.radius = r; - radiusOrEventOptions.strength = strength !== null && strength !== void 0 ? strength : radiusOrEventOptions.strength; - radiusOrEventOptions.falloff = falloff !== null && falloff !== void 0 ? falloff : radiusOrEventOptions.falloff; - } - else { - useCallback = !!(radiusOrEventOptions.affectedImpostorsCallback || radiusOrEventOptions.affectedBodiesCallback); - } - const event = new PhysicsRadialExplosionEvent(this._scene, radiusOrEventOptions); - const hitData = this._hitData; - if (this._physicsEngine.getPluginVersion() === 1) { - const affectedImpostorsWithData = Array(); - const impostors = this._physicsEngine.getImpostors(); - impostors.forEach((impostor) => { - if (!event.getImpostorHitData(impostor, origin, hitData)) { - return; - } - impostor.applyForce(hitData.force, hitData.contactPoint); - if (useCallback) { - affectedImpostorsWithData.push({ - impostor: impostor, - hitData: this._copyPhysicsHitData(hitData), - }); - } - }); - event.triggerAffectedImpostorsCallback(affectedImpostorsWithData); - } - else { - this._applicationForBodies(event, origin, hitData, useCallback, (body, hitData) => { - body.applyForce(hitData.force, hitData.contactPoint, hitData.instanceIndex); - }); - } - event.dispose(false); - return event; - } - _applicationForBodies(event, origin, hitData, useCallback, fnApplication) { - const affectedBodiesWithData = Array(); - const bodies = this._physicsEngine.getBodies(); - for (const body of bodies) { - body.iterateOverAllInstances((body, instanceIndex) => { - if (!event.getBodyHitData(body, origin, hitData, instanceIndex)) { - return; - } - fnApplication(body, hitData); - if (useCallback) { - affectedBodiesWithData.push({ - body: body, - hitData: this._copyPhysicsHitData(hitData), - }); - } - }); - } - event.triggerAffectedBodiesCallback(affectedBodiesWithData); - } - /** - * Creates a gravitational field - * @param origin the origin of the gravitational field - * @param radiusOrEventOptions the radius or the options of radial gravitational field - * @param strength the gravitational field strength - * @param falloff possible options: Constant & Linear. Defaults to Constant - * @returns A physics gravitational field event, or null - */ - gravitationalField(origin, radiusOrEventOptions, strength, falloff) { - if (!this._physicsEngine) { - Logger.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."); - return null; - } - if (this._physicsEngine.getPluginVersion() === 1 && this._physicsEngine.getImpostors().length === 0) { - return null; - } - if (this._physicsEngine.getPluginVersion() === 2 && this._physicsEngine.getBodies().length === 0) { - return null; - } - if (typeof radiusOrEventOptions === "number") { - const r = radiusOrEventOptions; - radiusOrEventOptions = new PhysicsRadialExplosionEventOptions(); - radiusOrEventOptions.radius = r; - radiusOrEventOptions.strength = strength !== null && strength !== void 0 ? strength : radiusOrEventOptions.strength; - radiusOrEventOptions.falloff = falloff !== null && falloff !== void 0 ? falloff : radiusOrEventOptions.falloff; - } - const event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radiusOrEventOptions); - event.dispose(false); - return event; - } - /** - * Creates a physics updraft event - * @param origin the origin of the updraft - * @param radiusOrEventOptions the radius or the options of the updraft - * @param strength the strength of the updraft - * @param height the height of the updraft - * @param updraftMode possible options: Center & Perpendicular. Defaults to Center - * @returns A physics updraft event, or null - */ - updraft(origin, radiusOrEventOptions, strength, height, updraftMode) { - if (!this._physicsEngine) { - Logger.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."); - return null; - } - if (this._physicsEngine.getPluginVersion() === 1 && this._physicsEngine.getImpostors().length === 0) { - return null; - } - if (this._physicsEngine.getPluginVersion() === 2 && this._physicsEngine.getBodies().length === 0) { - return null; - } - if (typeof radiusOrEventOptions === "number") { - const r = radiusOrEventOptions; - radiusOrEventOptions = new PhysicsUpdraftEventOptions(); - radiusOrEventOptions.radius = r; - radiusOrEventOptions.strength = strength !== null && strength !== void 0 ? strength : radiusOrEventOptions.strength; - radiusOrEventOptions.height = height !== null && height !== void 0 ? height : radiusOrEventOptions.height; - radiusOrEventOptions.updraftMode = updraftMode !== null && updraftMode !== void 0 ? updraftMode : radiusOrEventOptions.updraftMode; - } - const event = new PhysicsUpdraftEvent(this._scene, origin, radiusOrEventOptions); - event.dispose(false); - return event; - } - /** - * Creates a physics vortex event - * @param origin the of the vortex - * @param radiusOrEventOptions the radius or the options of the vortex - * @param strength the strength of the vortex - * @param height the height of the vortex - * @returns a Physics vortex event, or null - * A physics vortex event or null - */ - vortex(origin, radiusOrEventOptions, strength, height) { - if (!this._physicsEngine) { - Logger.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."); - return null; - } - if (this._physicsEngine.getPluginVersion() === 1 && this._physicsEngine.getImpostors().length === 0) { - return null; - } - if (this._physicsEngine.getPluginVersion() === 2 && this._physicsEngine.getBodies().length === 0) { - return null; - } - if (typeof radiusOrEventOptions === "number") { - const r = radiusOrEventOptions; - radiusOrEventOptions = new PhysicsVortexEventOptions(); - radiusOrEventOptions.radius = r; - radiusOrEventOptions.strength = strength !== null && strength !== void 0 ? strength : radiusOrEventOptions.strength; - radiusOrEventOptions.height = height !== null && height !== void 0 ? height : radiusOrEventOptions.height; - } - const event = new PhysicsVortexEvent(this._scene, origin, radiusOrEventOptions); - event.dispose(false); - return event; - } - _copyPhysicsHitData(data) { - return { force: data.force.clone(), contactPoint: data.contactPoint.clone(), distanceFromOrigin: data.distanceFromOrigin, instanceIndex: data.instanceIndex }; - } -} -/** - * Represents a physics radial explosion event - */ -class PhysicsRadialExplosionEvent { - /** - * Initializes a radial explosion event - * @param _scene BabylonJS scene - * @param _options The options for the vortex event - */ - constructor(_scene, _options) { - this._scene = _scene; - this._options = _options; - this._dataFetched = false; // check if the data has been fetched. If not, do cleanup - this._options = Object.assign(Object.assign({}, new PhysicsRadialExplosionEventOptions()), this._options); - } - /** - * Returns the data related to the radial explosion event (sphere). - * @returns The radial explosion event data - */ - getData() { - this._dataFetched = true; - return { - sphere: this._sphere, - }; - } - _getHitData(mesh, center, origin, data) { - const direction = TmpVectors.Vector3[0]; - direction.copyFrom(center).subtractInPlace(origin); - const contactPoint = TmpVectors.Vector3[1]; - const hasContactPoint = HelperTools.GetContactPointToRef(mesh, origin, direction, contactPoint, data.instanceIndex); - if (!hasContactPoint) { - return false; - } - const distanceFromOrigin = Vector3.Distance(origin, contactPoint); - if (distanceFromOrigin > this._options.radius) { - return false; - } - const multiplier = this._options.falloff === PhysicsRadialImpulseFalloff.Constant ? this._options.strength : this._options.strength * (1 - distanceFromOrigin / this._options.radius); - // Direction x multiplier equals force - direction.scaleInPlace(multiplier); - data.force.copyFrom(direction); - data.contactPoint.copyFrom(contactPoint); - data.distanceFromOrigin = distanceFromOrigin; - return true; - } - /** - * Returns the force and contact point of the body or false, if the body is not affected by the force/impulse. - * @param body A physics body where the transform node is an AbstractMesh - * @param origin the origin of the explosion - * @param data the data of the hit - * @param instanceIndex the instance index of the body - * @returns if there was a hit - */ - getBodyHitData(body, origin, data, instanceIndex) { - // No force will be applied in these cases, so we skip calculation - if (HelperTools.HasAppliedForces(body, instanceIndex)) { - return false; - } - const mesh = body.transformNode; - const bodyObjectCenter = body.getObjectCenterWorld(instanceIndex); - data.instanceIndex = instanceIndex; - return this._getHitData(mesh, bodyObjectCenter, origin, data); - } - /** - * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse. - * @param impostor A physics imposter - * @param origin the origin of the explosion - * @returns A physics force and contact point, or null - */ - getImpostorHitData(impostor, origin, data) { - if (impostor.mass === 0) { - return false; - } - if (impostor.object.getClassName() !== "Mesh" && impostor.object.getClassName() !== "InstancedMesh") { - return false; - } - const mesh = impostor.object; - if (!this._intersectsWithSphere(mesh, origin, this._options.radius)) { - return false; - } - const impostorObjectCenter = impostor.getObjectCenter(); - this._getHitData(mesh, impostorObjectCenter, origin, data); - return true; - } - /** - * Triggers affected impostors callbacks - * @param affectedImpostorsWithData defines the list of affected impostors (including associated data) - */ - triggerAffectedImpostorsCallback(affectedImpostorsWithData) { - if (this._options.affectedImpostorsCallback) { - this._options.affectedImpostorsCallback(affectedImpostorsWithData); - } - } - /** - * Triggers affected bodies callbacks - * @param affectedBodiesWithData defines the list of affected bodies (including associated data) - */ - triggerAffectedBodiesCallback(affectedBodiesWithData) { - if (this._options.affectedBodiesCallback) { - this._options.affectedBodiesCallback(affectedBodiesWithData); - } - } - /** - * Disposes the sphere. - * @param force Specifies if the sphere should be disposed by force - */ - dispose(force = true) { - if (this._sphere) { - if (force) { - this._sphere.dispose(); - } - else { - setTimeout(() => { - if (!this._dataFetched) { - this._sphere.dispose(); - } - }, 0); - } - } - } - /*** Helpers ***/ - _prepareSphere() { - if (!this._sphere) { - this._sphere = CreateSphere("radialExplosionEventSphere", this._options.sphere, this._scene); - this._sphere.isVisible = false; - } - } - _intersectsWithSphere(mesh, origin, radius) { - this._prepareSphere(); - this._sphere.position = origin; - this._sphere.scaling.setAll(radius * 2); - this._sphere._updateBoundingInfo(); - this._sphere.computeWorldMatrix(true); - return this._sphere.intersectsMesh(mesh, true); - } -} -/** - * Represents a gravitational field event - */ -class PhysicsGravitationalFieldEvent { - /** - * Initializes the physics gravitational field event - * @param _physicsHelper A physics helper - * @param _scene BabylonJS scene - * @param _origin The origin position of the gravitational field event - * @param _options The options for the vortex event - */ - constructor(_physicsHelper, _scene, _origin, _options) { - this._physicsHelper = _physicsHelper; - this._scene = _scene; - this._origin = _origin; - this._options = _options; - this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup - this._options = Object.assign(Object.assign({}, new PhysicsRadialExplosionEventOptions()), this._options); - this._tickCallback = this._tick.bind(this); - this._options.strength = this._options.strength * -1; - } - /** - * Returns the data related to the gravitational field event (sphere). - * @returns A gravitational field event - */ - getData() { - this._dataFetched = true; - return { - sphere: this._sphere, - }; - } - /** - * Enables the gravitational field. - */ - enable() { - this._tickCallback.call(this); - this._scene.registerBeforeRender(this._tickCallback); - } - /** - * Disables the gravitational field. - */ - disable() { - this._scene.unregisterBeforeRender(this._tickCallback); - } - /** - * Disposes the sphere. - * @param force The force to dispose from the gravitational field event - */ - dispose(force = true) { - if (!this._sphere) { - return; - } - if (force) { - this._sphere.dispose(); - } - else { - setTimeout(() => { - if (!this._dataFetched) { - this._sphere.dispose(); - } - }, 0); - } - } - _tick() { - var _a; - // Since the params won't change, we fetch the event only once - if (this._sphere) { - this._physicsHelper.applyRadialExplosionForce(this._origin, this._options); - } - else { - const radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._options); - if (radialExplosionEvent) { - this._sphere = (_a = radialExplosionEvent.getData().sphere) === null || _a === void 0 ? void 0 : _a.clone("radialExplosionEventSphereClone"); - } - } - } -} -/** - * Represents a physics updraft event - */ -class PhysicsUpdraftEvent { - /** - * Initializes the physics updraft event - * @param _scene BabylonJS scene - * @param _origin The origin position of the updraft - * @param _options The options for the updraft event - */ - constructor(_scene, _origin, _options) { - this._scene = _scene; - this._origin = _origin; - this._options = _options; - this._originTop = math_vector_Vector3.Zero(); // the most upper part of the cylinder - this._originDirection = math_vector_Vector3.Zero(); // used if the updraftMode is perpendicular - this._cylinderPosition = math_vector_Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom - this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup - this._physicsEngine = this._scene.getPhysicsEngine(); - this._options = Object.assign(Object.assign({}, new PhysicsUpdraftEventOptions()), this._options); - this._origin.addToRef(new math_vector_Vector3(0, this._options.height / 2, 0), this._cylinderPosition); - this._origin.addToRef(new math_vector_Vector3(0, this._options.height, 0), this._originTop); - if (this._options.updraftMode === PhysicsUpdraftMode.Perpendicular) { - this._originDirection = this._origin.subtract(this._originTop).normalize(); - } - this._tickCallback = this._tick.bind(this); - if (this._physicsEngine.getPluginVersion() === 1) { - this._prepareCylinder(); - } - } - /** - * Returns the data related to the updraft event (cylinder). - * @returns A physics updraft event - */ - getData() { - this._dataFetched = true; - return { - cylinder: this._cylinder, - }; - } - /** - * Enables the updraft. - */ - enable() { - this._tickCallback.call(this); - this._scene.registerBeforeRender(this._tickCallback); - } - /** - * Disables the updraft. - */ - disable() { - this._scene.unregisterBeforeRender(this._tickCallback); - } - /** - * Disposes the cylinder. - * @param force Specifies if the updraft should be disposed by force - */ - dispose(force = true) { - if (!this._cylinder) { - return; - } - if (force) { - this._cylinder.dispose(); - this._cylinder = undefined; - } - else { - setTimeout(() => { - if (!this._dataFetched && this._cylinder) { - this._cylinder.dispose(); - this._cylinder = undefined; - } - }, 0); - } - } - _getHitData(center, data) { - let direction; - if (this._options.updraftMode === PhysicsUpdraftMode.Perpendicular) { - direction = this._originDirection; - } - else { - direction = center.subtract(this._originTop); - } - const distanceFromOrigin = math_vector_Vector3.Distance(this._origin, center); - const multiplier = this._options.strength * -1; - const force = direction.multiplyByFloats(multiplier, multiplier, multiplier); - data.force.copyFrom(force); - data.contactPoint.copyFrom(center); - data.distanceFromOrigin = distanceFromOrigin; - } - _getBodyHitData(body, data, instanceIndex) { - if (HelperTools.HasAppliedForces(body)) { - return false; - } - const center = body.getObjectCenterWorld(instanceIndex); - if (!HelperTools.IsInsideCylinder(center, this._origin, this._options.radius, this._options.height)) { - return false; - } - data.instanceIndex = instanceIndex; - this._getHitData(center, data); - return true; - } - _getImpostorHitData(impostor, data) { - if (impostor.mass === 0) { - return false; - } - const impostorObject = impostor.object; - if (!this._intersectsWithCylinder(impostorObject)) { - return false; - } - const center = impostor.getObjectCenter(); - this._getHitData(center, data); - return true; - } - _tick() { - const hitData = PhysicsUpdraftEvent._HitData; - if (this._physicsEngine.getPluginVersion() === 1) { - this._physicsEngine.getImpostors().forEach((impostor) => { - if (!this._getImpostorHitData(impostor, hitData)) { - return; - } - impostor.applyForce(hitData.force, hitData.contactPoint); - }); - } - else { - // V2 - this._physicsEngine.getBodies().forEach((body) => { - body.iterateOverAllInstances((body, instanceIndex) => { - if (!this._getBodyHitData(body, hitData, instanceIndex)) { - return; - } - body.applyForce(hitData.force, hitData.contactPoint, hitData.instanceIndex); - }); - }); - } - } - /*** Helpers ***/ - _prepareCylinder() { - if (!this._cylinder) { - this._cylinder = cylinderBuilder_CreateCylinder("updraftEventCylinder", { - height: this._options.height, - diameter: this._options.radius * 2, - }, this._scene); - this._cylinder.isVisible = false; - } - } - _intersectsWithCylinder(mesh) { - if (!this._cylinder) { - return false; - } - this._cylinder.position = this._cylinderPosition; - return this._cylinder.intersectsMesh(mesh, true); - } -} -PhysicsUpdraftEvent._HitData = { force: new math_vector_Vector3(), contactPoint: new math_vector_Vector3(), distanceFromOrigin: 0 }; -/** - * Represents a physics vortex event - */ -class PhysicsVortexEvent { - /** - * Initializes the physics vortex event - * @param _scene The BabylonJS scene - * @param _origin The origin position of the vortex - * @param _options The options for the vortex event - */ - constructor(_scene, _origin, _options) { - this._scene = _scene; - this._origin = _origin; - this._options = _options; - this._originTop = math_vector_Vector3.Zero(); // the most upper part of the cylinder - this._cylinderPosition = math_vector_Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom - this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup - this._physicsEngine = this._scene.getPhysicsEngine(); - this._options = Object.assign(Object.assign({}, new PhysicsVortexEventOptions()), this._options); - this._origin.addToRef(new math_vector_Vector3(0, this._options.height / 2, 0), this._cylinderPosition); - this._origin.addToRef(new math_vector_Vector3(0, this._options.height, 0), this._originTop); - this._tickCallback = this._tick.bind(this); - if (this._physicsEngine.getPluginVersion() === 1) { - this._prepareCylinder(); - } - } - /** - * Returns the data related to the vortex event (cylinder). - * @returns The physics vortex event data - */ - getData() { - this._dataFetched = true; - return { - cylinder: this._cylinder, - }; - } - /** - * Enables the vortex. - */ - enable() { - this._tickCallback.call(this); - this._scene.registerBeforeRender(this._tickCallback); - } - /** - * Disables the cortex. - */ - disable() { - this._scene.unregisterBeforeRender(this._tickCallback); - } - /** - * Disposes the sphere. - * @param force - */ - dispose(force = true) { - if (!this._cylinder) { - return; - } - if (force) { - this._cylinder.dispose(); - } - else { - setTimeout(() => { - if (!this._dataFetched) { - this._cylinder.dispose(); - } - }, 0); - } - } - _getHitData(mesh, center, data) { - const originOnPlane = PhysicsVortexEvent.originOnPlane; - originOnPlane.set(this._origin.x, center.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis) - const originToImpostorDirection = math_vector_TmpVectors.Vector3[0]; - center.subtractToRef(originOnPlane, originToImpostorDirection); - const contactPoint = math_vector_TmpVectors.Vector3[1]; - const hasContactPoint = HelperTools.GetContactPointToRef(mesh, originOnPlane, originToImpostorDirection, contactPoint, data.instanceIndex); - if (!hasContactPoint) { - return false; - } - const distance = math_vector_Vector3.Distance(contactPoint, originOnPlane); - const absoluteDistanceFromOrigin = distance / this._options.radius; - const directionToOrigin = math_vector_TmpVectors.Vector3[2]; - contactPoint.normalizeToRef(directionToOrigin); - if (absoluteDistanceFromOrigin > this._options.centripetalForceThreshold) { - directionToOrigin.negateInPlace(); - } - let forceX; - let forceY; - let forceZ; - if (absoluteDistanceFromOrigin > this._options.centripetalForceThreshold) { - forceX = directionToOrigin.x * this._options.centripetalForceMultiplier; - forceY = directionToOrigin.y * this._options.updraftForceMultiplier; - forceZ = directionToOrigin.z * this._options.centripetalForceMultiplier; - } - else { - const perpendicularDirection = math_vector_Vector3.Cross(originOnPlane, center).normalize(); - forceX = (perpendicularDirection.x + directionToOrigin.x) * this._options.centrifugalForceMultiplier; - forceY = this._originTop.y * this._options.updraftForceMultiplier; - forceZ = (perpendicularDirection.z + directionToOrigin.z) * this._options.centrifugalForceMultiplier; - } - const force = math_vector_TmpVectors.Vector3[3]; - force.set(forceX, forceY, forceZ); - force.scaleInPlace(this._options.strength); - data.force.copyFrom(force); - data.contactPoint.copyFrom(center); - data.distanceFromOrigin = absoluteDistanceFromOrigin; - return true; - } - _getBodyHitData(body, data, instanceIndex) { - if (HelperTools.HasAppliedForces(body, instanceIndex)) { - return false; - } - const bodyObject = body.transformNode; - const bodyCenter = body.getObjectCenterWorld(instanceIndex); - if (!HelperTools.IsInsideCylinder(bodyCenter, this._origin, this._options.radius, this._options.height)) { - return false; - } - data.instanceIndex = instanceIndex; - return this._getHitData(bodyObject, bodyCenter, data); - } - _getImpostorHitData(impostor, data) { - if (impostor.mass === 0) { - return false; - } - if (impostor.object.getClassName() !== "Mesh" && impostor.object.getClassName() !== "InstancedMesh") { - return false; - } - const impostorObject = impostor.object; - if (!this._intersectsWithCylinder(impostorObject)) { - return false; - } - const impostorObjectCenter = impostor.getObjectCenter(); - this._getHitData(impostorObject, impostorObjectCenter, data); - return true; - } - _tick() { - const hitData = PhysicsVortexEvent.hitData; - if (this._physicsEngine.getPluginVersion() === 1) { - this._physicsEngine.getImpostors().forEach((impostor) => { - if (!this._getImpostorHitData(impostor, hitData)) { - return; - } - impostor.applyForce(hitData.force, hitData.contactPoint); - }); - } - else { - this._physicsEngine.getBodies().forEach((body) => { - body.iterateOverAllInstances((body, instanceIndex) => { - if (!this._getBodyHitData(body, hitData, instanceIndex)) { - return; - } - body.applyForce(hitData.force, hitData.contactPoint, hitData.instanceIndex); - }); - }); - } - } - /*** Helpers ***/ - _prepareCylinder() { - if (!this._cylinder) { - this._cylinder = cylinderBuilder_CreateCylinder("vortexEventCylinder", { - height: this._options.height, - diameter: this._options.radius * 2, - }, this._scene); - this._cylinder.isVisible = false; - } - } - _intersectsWithCylinder(mesh) { - this._cylinder.position = this._cylinderPosition; - return this._cylinder.intersectsMesh(mesh, true); - } -} -PhysicsVortexEvent.originOnPlane = math_vector_Vector3.Zero(); -PhysicsVortexEvent.hitData = { force: new math_vector_Vector3(), contactPoint: new math_vector_Vector3(), distanceFromOrigin: 0 }; -/** - * Options fot the radial explosion event - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine#further-functionality-of-the-impostor-class - */ -class PhysicsRadialExplosionEventOptions { - constructor() { - /** - * The radius of the sphere for the radial explosion. - */ - this.radius = 5; - /** - * The strength of the explosion. - */ - this.strength = 10; - /** - * The strength of the force in correspondence to the distance of the affected object - */ - this.falloff = PhysicsRadialImpulseFalloff.Constant; - /** - * Sphere options for the radial explosion. - */ - this.sphere = { segments: 32, diameter: 1 }; - } -} -/** - * Options fot the updraft event - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine#further-functionality-of-the-impostor-class - */ -class PhysicsUpdraftEventOptions { - constructor() { - /** - * The radius of the cylinder for the vortex - */ - this.radius = 5; - /** - * The strength of the updraft. - */ - this.strength = 10; - /** - * The height of the cylinder for the updraft. - */ - this.height = 10; - /** - * The mode for the the updraft. - */ - this.updraftMode = PhysicsUpdraftMode.Center; - } -} -/** - * Options fot the vortex event - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine#further-functionality-of-the-impostor-class - */ -class PhysicsVortexEventOptions { - constructor() { - /** - * The radius of the cylinder for the vortex - */ - this.radius = 5; - /** - * The strength of the vortex. - */ - this.strength = 10; - /** - * The height of the cylinder for the vortex. - */ - this.height = 10; - /** - * At which distance, relative to the radius the centripetal forces should kick in? Range: 0-1 - */ - this.centripetalForceThreshold = 0.7; - /** - * This multiplier determines with how much force the objects will be pushed sideways/around the vortex, when below the threshold. - */ - this.centripetalForceMultiplier = 5; - /** - * This multiplier determines with how much force the objects will be pushed sideways/around the vortex, when above the threshold. - */ - this.centrifugalForceMultiplier = 0.5; - /** - * This multiplier determines with how much force the objects will be pushed upwards, when in the vortex. - */ - this.updraftForceMultiplier = 0.02; - } -} -/** - * The strength of the force in correspondence to the distance of the affected object - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine#further-functionality-of-the-impostor-class - */ -var PhysicsRadialImpulseFalloff; -(function (PhysicsRadialImpulseFalloff) { - /** Defines that impulse is constant in strength across it's whole radius */ - PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant"; - /** Defines that impulse gets weaker if it's further from the origin */ - PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; -})(PhysicsRadialImpulseFalloff || (PhysicsRadialImpulseFalloff = {})); -/** - * The strength of the force in correspondence to the distance of the affected object - * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine#further-functionality-of-the-impostor-class - */ -var PhysicsUpdraftMode; -(function (PhysicsUpdraftMode) { - /** Defines that the upstream forces will pull towards the top center of the cylinder */ - PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center"; - /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */ - PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; -})(PhysicsUpdraftMode || (PhysicsUpdraftMode = {})); -//# sourceMappingURL=physicsHelper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Physics/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/blackAndWhite.fragment.js -// Do not edit. - -const blackAndWhite_fragment_name = "blackAndWhitePixelShader"; -const blackAndWhite_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); -vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`; -// Sideeffect -ShaderStore.ShadersStore[blackAndWhite_fragment_name] = blackAndWhite_fragment_shader; -/** @internal */ -const blackAndWhitePixelShader = { name: blackAndWhite_fragment_name, shader: blackAndWhite_fragment_shader }; -//# sourceMappingURL=blackAndWhite.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/blackAndWhitePostProcess.js - - - - - -/** - * Post process used to render in black and white - */ -class BlackAndWhitePostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "BlackAndWhitePostProcess" string - */ - getClassName() { - return "BlackAndWhitePostProcess"; - } - /** - * Creates a black and white post process - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#black-and-white - * @param name The name of the effect. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - */ - constructor(name, options, camera, samplingMode, engine, reusable) { - super(name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable); - /** - * Linear about to convert he result to black and white (default: 1) - */ - this.degree = 1; - this.onApplyObservable.add((effect) => { - effect.setFloat("degree", this.degree); - }); - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new BlackAndWhitePostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serialize() -], BlackAndWhitePostProcess.prototype, "degree", void 0); -RegisterClass("BABYLON.BlackAndWhitePostProcess", BlackAndWhitePostProcess); -//# sourceMappingURL=blackAndWhitePostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderEffect.js - -/** - * This represents a set of one or more post processes in Babylon. - * A post process can be used to apply a shader to a texture after it is rendered. - * @example https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/postProcessRenderPipeline - */ -class postProcessRenderEffect_PostProcessRenderEffect { - /** - * Instantiates a post process render effect. - * A post process can be used to apply a shader to a texture after it is rendered. - * @param engine The engine the effect is tied to - * @param name The name of the effect - * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run. - * @param singleInstance False if this post process can be run on multiple cameras. (default: true) - */ - constructor(engine, name, getPostProcesses, singleInstance) { - this._name = name; - this._singleInstance = singleInstance || true; - this._getPostProcesses = getPostProcesses; - this._cameras = {}; - this._indicesForCamera = {}; - this._postProcesses = {}; - } - /** - * Checks if all the post processes in the effect are supported. - */ - get isSupported() { - for (const index in this._postProcesses) { - if (Object.prototype.hasOwnProperty.call(this._postProcesses, index)) { - const pps = this._postProcesses[index]; - for (let ppIndex = 0; ppIndex < pps.length; ppIndex++) { - if (!pps[ppIndex].isSupported) { - return false; - } - } - } - } - return true; - } - /** - * Updates the current state of the effect - * @internal - */ - _update() { } - /** - * Attaches the effect on cameras - * @param cameras The camera to attach to. - * @internal - */ - _attachCameras(cameras) { - let cameraKey; - const cams = tools_Tools.MakeArray(cameras || this._cameras); - if (!cams) { - return; - } - for (let i = 0; i < cams.length; i++) { - const camera = cams[i]; - if (!camera) { - continue; - } - const cameraName = camera.name; - if (this._singleInstance) { - cameraKey = 0; - } - else { - cameraKey = cameraName; - } - if (!this._postProcesses[cameraKey]) { - const postProcess = this._getPostProcesses(); - if (postProcess) { - this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess]; - } - } - if (!this._indicesForCamera[cameraName]) { - this._indicesForCamera[cameraName] = []; - } - this._postProcesses[cameraKey].forEach((postProcess) => { - const index = camera.attachPostProcess(postProcess); - this._indicesForCamera[cameraName].push(index); - }); - if (!this._cameras[cameraName]) { - this._cameras[cameraName] = camera; - } - } - } - /** - * Detaches the effect on cameras - * @param cameras The camera to detach from. - * @internal - */ - _detachCameras(cameras) { - const cams = tools_Tools.MakeArray(cameras || this._cameras); - if (!cams) { - return; - } - for (let i = 0; i < cams.length; i++) { - const camera = cams[i]; - const cameraName = camera.name; - const postProcesses = this._postProcesses[this._singleInstance ? 0 : cameraName]; - if (postProcesses) { - postProcesses.forEach((postProcess) => { - camera.detachPostProcess(postProcess); - }); - } - if (this._cameras[cameraName]) { - this._cameras[cameraName] = null; - } - delete this._indicesForCamera[cameraName]; - } - } - /** - * Enables the effect on given cameras - * @param cameras The camera to enable. - * @internal - */ - _enable(cameras) { - const cams = tools_Tools.MakeArray(cameras || this._cameras); - if (!cams) { - return; - } - for (let i = 0; i < cams.length; i++) { - const camera = cams[i]; - const cameraName = camera.name; - const cameraKey = this._singleInstance ? 0 : cameraName; - for (let j = 0; j < this._indicesForCamera[cameraName].length; j++) { - const index = this._indicesForCamera[cameraName][j]; - const postProcess = camera._postProcesses[index]; - if (postProcess === undefined || postProcess === null) { - cams[i].attachPostProcess(this._postProcesses[cameraKey][j], index); - } - } - } - } - /** - * Disables the effect on the given cameras - * @param cameras The camera to disable. - * @internal - */ - _disable(cameras) { - const cams = tools_Tools.MakeArray(cameras || this._cameras); - if (!cams) { - return; - } - for (let i = 0; i < cams.length; i++) { - const camera = cams[i]; - const cameraName = camera.name; - this._postProcesses[this._singleInstance ? 0 : cameraName].forEach((postProcess) => { - camera.detachPostProcess(postProcess); - }); - } - } - /** - * Gets a list of the post processes contained in the effect. - * @param camera The camera to get the post processes on. - * @returns The list of the post processes in the effect. - */ - getPostProcesses(camera) { - if (this._singleInstance) { - return this._postProcesses[0]; - } - else { - if (!camera) { - return null; - } - return this._postProcesses[camera.name]; - } - } -} -//# sourceMappingURL=postProcessRenderEffect.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/extractHighlights.fragment.js -// Do not edit. - - -const extractHighlights_fragment_name = "extractHighlightsPixelShader"; -const extractHighlights_fragment_shader = `#include<helperFunctions> -varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`; -// Sideeffect -ShaderStore.ShadersStore[extractHighlights_fragment_name] = extractHighlights_fragment_shader; -/** @internal */ -const extractHighlightsPixelShader = { name: extractHighlights_fragment_name, shader: extractHighlights_fragment_shader }; -//# sourceMappingURL=extractHighlights.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/extractHighlightsPostProcess.js - - - - - - - -/** - * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect. - */ -class ExtractHighlightsPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "ExtractHighlightsPostProcess" string - */ - getClassName() { - return "ExtractHighlightsPostProcess"; - } - constructor(name, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { - super(name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation); - /** - * The luminance threshold, pixels below this value will be set to black. - */ - this.threshold = 0.9; - /** @internal */ - this._exposure = 1; - /** - * Post process which has the input texture to be used when performing highlight extraction - * @internal - */ - this._inputPostProcess = null; - this.onApplyObservable.add((effect) => { - this.externalTextureSamplerBinding = !!this._inputPostProcess; - if (this._inputPostProcess) { - effect.setTextureFromPostProcess("textureSampler", this._inputPostProcess); - } - effect.setFloat("threshold", Math.pow(this.threshold, ToGammaSpace)); - effect.setFloat("exposure", this._exposure); - }); - } -} -__decorate([ - serialize() -], ExtractHighlightsPostProcess.prototype, "threshold", void 0); -RegisterClass("BABYLON.ExtractHighlightsPostProcess", ExtractHighlightsPostProcess); -//# sourceMappingURL=extractHighlightsPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/bloomMerge.fragment.js -// Do not edit. - -const bloomMerge_fragment_name = "bloomMergePixelShader"; -const bloomMerge_fragment_shader = `uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } -`; -// Sideeffect -ShaderStore.ShadersStore[bloomMerge_fragment_name] = bloomMerge_fragment_shader; -/** @internal */ -const bloomMergePixelShader = { name: bloomMerge_fragment_name, shader: bloomMerge_fragment_shader }; -//# sourceMappingURL=bloomMerge.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/bloomMergePostProcess.js - - - - - - -/** - * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion. - */ -class BloomMergePostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "BloomMergePostProcess" string - */ - getClassName() { - return "BloomMergePostProcess"; - } - /** - * Creates a new instance of @see BloomMergePostProcess - * @param name The name of the effect. - * @param originalFromInput Post process which's input will be used for the merge. - * @param blurred Blurred highlights post process which's output will be used. - * @param weight Weight of the bloom to be added to the original input. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @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) - */ - constructor(name, originalFromInput, blurred, - /** Weight of the bloom to be added to the original input. */ - weight, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { - super(name, "bloomMerge", ["bloomWeight"], ["bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true); - /** Weight of the bloom to be added to the original input. */ - this.weight = 1; - this.weight = weight; - this.externalTextureSamplerBinding = true; - this.onApplyObservable.add((effect) => { - effect.setTextureFromPostProcess("textureSampler", originalFromInput); - effect.setTextureFromPostProcessOutput("bloomBlur", blurred); - effect.setFloat("bloomWeight", this.weight); - }); - if (!blockCompilation) { - this.updateEffect(); - } - } -} -__decorate([ - serialize() -], BloomMergePostProcess.prototype, "weight", void 0); -RegisterClass("BABYLON.BloomMergePostProcess", BloomMergePostProcess); -//# sourceMappingURL=bloomMergePostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/bloomEffect.js - - - - - - -/** - * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras - */ -class BloomEffect extends postProcessRenderEffect_PostProcessRenderEffect { - /** - * The luminance threshold to find bright areas of the image to bloom. - */ - get threshold() { - return this._downscale.threshold; - } - set threshold(value) { - this._downscale.threshold = value; - } - /** - * The strength of the bloom. - */ - get weight() { - return this._merge.weight; - } - set weight(value) { - this._merge.weight = value; - } - /** - * Specifies the size of the bloom blur kernel, relative to the final output size - */ - get kernel() { - return this._blurX.kernel / this._bloomScale; - } - set kernel(value) { - this._blurX.kernel = value * this._bloomScale; - this._blurY.kernel = value * this._bloomScale; - } - /** - * Creates a new instance of @see BloomEffect - * @param scene The scene the effect belongs to. - * @param _bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom. - * @param bloomWeight The the strength of bloom. - * @param bloomKernel The size of the kernel to be used when applying the blur. - * @param pipelineTextureType The type of texture to be used when performing the post processing. - * @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) - */ - constructor(scene, _bloomScale, bloomWeight, bloomKernel, pipelineTextureType = 0, blockCompilation = false) { - super(scene.getEngine(), "bloom", () => { - return this._effects; - }, true); - this._bloomScale = _bloomScale; - /** - * @internal Internal - */ - this._effects = []; - this._downscale = new ExtractHighlightsPostProcess("highlights", 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation); - this._blurX = new BlurPostProcess("horizontal blur", new math_vector_Vector2(1.0, 0), 10.0, _bloomScale, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation); - this._blurX.alwaysForcePOT = true; - this._blurX.autoClear = false; - this._blurY = new BlurPostProcess("vertical blur", new math_vector_Vector2(0, 1.0), 10.0, _bloomScale, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation); - this._blurY.alwaysForcePOT = true; - this._blurY.autoClear = false; - this.kernel = bloomKernel; - this._effects = [this._downscale, this._blurX, this._blurY]; - this._merge = new BloomMergePostProcess("bloomMerge", this._downscale, this._blurY, bloomWeight, _bloomScale, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation); - this._merge.autoClear = false; - this._effects.push(this._merge); - } - /** - * Disposes each of the internal effects for a given camera. - * @param camera The camera to dispose the effect on. - */ - disposeEffects(camera) { - for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { - this._effects[effectIndex].dispose(camera); - } - } - /** - * @internal Internal - */ - _updateEffects() { - for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { - this._effects[effectIndex].updateEffect(); - } - } - /** - * Internal - * @returns if all the contained post processes are ready. - * @internal - */ - _isReady() { - for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { - if (!this._effects[effectIndex].isReady()) { - return false; - } - } - return true; - } -} -//# sourceMappingURL=bloomEffect.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/chromaticAberration.fragment.js -// Do not edit. - -const chromaticAberration_fragment_name = "chromaticAberrationPixelShader"; -const chromaticAberration_fragment_shader = `uniform sampler2D textureSampler; -uniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);} -float radius2=centered_screen_pos.x*centered_screen_pos.x -+ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec4 original=texture2D(textureSampler,vUV);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);original.r=texture2D(textureSampler,ref_coords_r).r;original.g=texture2D(textureSampler,ref_coords_g).g;original.b=texture2D(textureSampler,ref_coords_b).b;original.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);gl_FragColor=original;}`; -// Sideeffect -ShaderStore.ShadersStore[chromaticAberration_fragment_name] = chromaticAberration_fragment_shader; -/** @internal */ -const chromaticAberrationPixelShader = { name: chromaticAberration_fragment_name, shader: chromaticAberration_fragment_shader }; -//# sourceMappingURL=chromaticAberration.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/chromaticAberrationPostProcess.js - - - - - - - -/** - * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen - */ -class ChromaticAberrationPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "ChromaticAberrationPostProcess" string - */ - getClassName() { - return "ChromaticAberrationPostProcess"; - } - /** - * Creates a new instance ChromaticAberrationPostProcess - * @param name The name of the effect. - * @param screenWidth The width of the screen to apply the effect on. - * @param screenHeight The height of the screen to apply the effect on. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @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) - */ - constructor(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { - super(name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation); - /** - * The amount of separation of rgb channels (default: 30) - */ - this.aberrationAmount = 30; - /** - * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0) - */ - this.radialIntensity = 0; - /** - * The normalized direction in which the rgb channels should be separated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707)) - */ - this.direction = new math_vector_Vector2(0.707, 0.707); - /** - * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corner] (default: Vector2(0.5 ,0.5)) - */ - this.centerPosition = new math_vector_Vector2(0.5, 0.5); - this.screenWidth = screenWidth; - this.screenHeight = screenHeight; - this.onApplyObservable.add((effect) => { - effect.setFloat("chromatic_aberration", this.aberrationAmount); - effect.setFloat("screen_width", screenWidth); - effect.setFloat("screen_height", screenHeight); - effect.setFloat("radialIntensity", this.radialIntensity); - effect.setFloat2("direction", this.direction.x, this.direction.y); - effect.setFloat2("centerPosition", this.centerPosition.x, this.centerPosition.y); - }); - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new ChromaticAberrationPostProcess(parsedPostProcess.name, parsedPostProcess.screenWidth, parsedPostProcess.screenHeight, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, false); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serialize() -], ChromaticAberrationPostProcess.prototype, "aberrationAmount", void 0); -__decorate([ - serialize() -], ChromaticAberrationPostProcess.prototype, "radialIntensity", void 0); -__decorate([ - serialize() -], ChromaticAberrationPostProcess.prototype, "direction", void 0); -__decorate([ - serialize() -], ChromaticAberrationPostProcess.prototype, "centerPosition", void 0); -__decorate([ - serialize() -], ChromaticAberrationPostProcess.prototype, "screenWidth", void 0); -__decorate([ - serialize() -], ChromaticAberrationPostProcess.prototype, "screenHeight", void 0); -RegisterClass("BABYLON.ChromaticAberrationPostProcess", ChromaticAberrationPostProcess); -//# sourceMappingURL=chromaticAberrationPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/circleOfConfusion.fragment.js -// Do not edit. - -const circleOfConfusion_fragment_name = "circleOfConfusionPixelShader"; -const circleOfConfusion_fragment_shader = `uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float depth=texture2D(depthSampler,vUV).r; -#define CUSTOM_COC_DEPTH -float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; -#define CUSTOM_COC_PIXELDISTANCE -float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} -`; -// Sideeffect -ShaderStore.ShadersStore[circleOfConfusion_fragment_name] = circleOfConfusion_fragment_shader; -/** @internal */ -const circleOfConfusionPixelShader = { name: circleOfConfusion_fragment_name, shader: circleOfConfusion_fragment_shader }; -//# sourceMappingURL=circleOfConfusion.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/circleOfConfusionPostProcess.js - - - - - - - -/** - * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion - */ -class CircleOfConfusionPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "CircleOfConfusionPostProcess" string - */ - getClassName() { - return "CircleOfConfusionPostProcess"; - } - /** - * Creates a new instance CircleOfConfusionPostProcess - * @param name The name of the effect. - * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @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) - */ - constructor(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { - super(name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation); - /** - * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diameter of the resulting aperture can be computed by lensSize/fStop. - */ - this.lensSize = 50; - /** - * F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop. (default: 1.4) - */ - this.fStop = 1.4; - /** - * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000) - */ - this.focusDistance = 2000; - /** - * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50) - */ - this.focalLength = 50; - this._depthTexture = null; - this._depthTexture = depthTexture; - this.onApplyObservable.add((effect) => { - if (!this._depthTexture) { - logger_Logger.Warn("No depth texture set on CircleOfConfusionPostProcess"); - return; - } - effect.setTexture("depthSampler", this._depthTexture); - // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html - const aperture = this.lensSize / this.fStop; - const cocPrecalculation = (aperture * this.focalLength) / (this.focusDistance - this.focalLength); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader] - effect.setFloat("focusDistance", this.focusDistance); - effect.setFloat("cocPrecalculation", cocPrecalculation); - const activeCamera = this._depthTexture.activeCamera; - effect.setFloat2("cameraMinMaxZ", activeCamera.minZ, activeCamera.maxZ - activeCamera.minZ); - }); - } - /** - * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function. - */ - set depthTexture(value) { - this._depthTexture = value; - } -} -__decorate([ - serialize() -], CircleOfConfusionPostProcess.prototype, "lensSize", void 0); -__decorate([ - serialize() -], CircleOfConfusionPostProcess.prototype, "fStop", void 0); -__decorate([ - serialize() -], CircleOfConfusionPostProcess.prototype, "focusDistance", void 0); -__decorate([ - serialize() -], CircleOfConfusionPostProcess.prototype, "focalLength", void 0); -RegisterClass("BABYLON.CircleOfConfusionPostProcess", CircleOfConfusionPostProcess); -//# sourceMappingURL=circleOfConfusionPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/colorCorrection.fragment.js -// Do not edit. - -const colorCorrection_fragment_name = "colorCorrectionPixelShader"; -const colorCorrection_fragment_shader = `uniform sampler2D textureSampler; -uniform sampler2D colorTable; -varying vec2 vUV;const float SLICE_COUNT=16.0; -vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; -float slicePixelSize=sliceSize/width; -float sliceInnerSize=slicePixelSize*(width-1.0); -float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`; -// Sideeffect -ShaderStore.ShadersStore[colorCorrection_fragment_name] = colorCorrection_fragment_shader; -/** @internal */ -const colorCorrectionPixelShader = { name: colorCorrection_fragment_name, shader: colorCorrection_fragment_shader }; -//# sourceMappingURL=colorCorrection.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/colorCorrectionPostProcess.js - - - - - - -/** - * - * This post-process allows the modification of rendered colors by using - * a 'look-up table' (LUT). This effect is also called Color Grading. - * - * The object needs to be provided an url to a texture containing the color - * look-up table: the texture must be 256 pixels wide and 16 pixels high. - * Use an image editing software to tweak the LUT to match your needs. - * - * For an example of a color LUT, see here: - * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png - * For explanations on color grading, see here: - * @see http://udn.epicgames.com/Three/ColorGrading.html - * - */ -class ColorCorrectionPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "ColorCorrectionPostProcess" string - */ - getClassName() { - return "ColorCorrectionPostProcess"; - } - constructor(name, colorTableUrl, options, camera, samplingMode, engine, reusable) { - super(name, "colorCorrection", null, ["colorTable"], options, camera, samplingMode, engine, reusable); - const scene = (camera === null || camera === void 0 ? void 0 : camera.getScene()) || null; - this._colorTableTexture = new texture_Texture(colorTableUrl, scene, true, false, texture_Texture.TRILINEAR_SAMPLINGMODE); - this._colorTableTexture.anisotropicFilteringLevel = 1; - this._colorTableTexture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._colorTableTexture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this.colorTableUrl = colorTableUrl; - this.onApply = (effect) => { - effect.setTexture("colorTable", this._colorTableTexture); - }; - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new ColorCorrectionPostProcess(parsedPostProcess.name, parsedPostProcess.colorTableUrl, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serialize() -], ColorCorrectionPostProcess.prototype, "colorTableUrl", void 0); -RegisterClass("BABYLON.ColorCorrectionPostProcess", ColorCorrectionPostProcess); -//# sourceMappingURL=colorCorrectionPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/convolution.fragment.js -// Do not edit. - -const convolution_fragment_name = "convolutionPixelShader"; -const convolution_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = -texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + -texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + -texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + -texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + -texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + -texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + -texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + -texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + -texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = -kernel[0] + -kernel[1] + -kernel[2] + -kernel[3] + -kernel[4] + -kernel[5] + -kernel[6] + -kernel[7] + -kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} -gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`; -// Sideeffect -ShaderStore.ShadersStore[convolution_fragment_name] = convolution_fragment_shader; -/** @internal */ -const convolutionPixelShader = { name: convolution_fragment_name, shader: convolution_fragment_shader }; -//# sourceMappingURL=convolution.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/convolutionPostProcess.js - - - - - - -/** - * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the - * input texture to perform effects such as edge detection or sharpening - * See http://en.wikipedia.org/wiki/Kernel_(image_processing) - */ -class ConvolutionPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "ConvolutionPostProcess" string - */ - getClassName() { - return "ConvolutionPostProcess"; - } - /** - * Creates a new instance ConvolutionPostProcess - * @param name The name of the effect. - * @param kernel Array of 9 values corresponding to the 3x3 kernel to be applied - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - */ - constructor(name, kernel, options, camera, samplingMode, engine, reusable, textureType = 0) { - super(name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType); - this.kernel = kernel; - this.onApply = (effect) => { - effect.setFloat2("screenSize", this.width, this.height); - effect.setArray("kernel", this.kernel); - }; - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new ConvolutionPostProcess(parsedPostProcess.name, parsedPostProcess.kernel, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType); - }, parsedPostProcess, scene, rootUrl); - } -} -// Statics -/** - * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing) - */ -ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1]; -/** - * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing) - */ -ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0]; -/** - * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing) - */ -ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1]; -/** - * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing) - */ -ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0]; -/** - * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing) - */ -ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2]; -/** - * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing) - */ -ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0]; -__decorate([ - serialize() -], ConvolutionPostProcess.prototype, "kernel", void 0); -RegisterClass("BABYLON.ConvolutionPostProcess", ConvolutionPostProcess); -//# sourceMappingURL=convolutionPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/depthOfFieldBlurPostProcess.js - - - - - - -/** - * The DepthOfFieldBlurPostProcess applied a blur in a give direction. - * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels - * based on samples that have a large difference in distance than the center pixel. - * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf - */ -class DepthOfFieldBlurPostProcess extends BlurPostProcess { - /** - * Gets a string identifying the name of the class - * @returns "DepthOfFieldBlurPostProcess" string - */ - getClassName() { - return "DepthOfFieldBlurPostProcess"; - } - /** - * Creates a new instance DepthOfFieldBlurPostProcess - * @param name The name of the effect. - * @param scene The scene the effect belongs to. - * @param direction The direction the blur should be applied. - * @param kernel The size of the kernel used to blur. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring across edges - * @param imageToBlur The image to apply the blur to (default: Current rendered frame) - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @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) - * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA) - */ - constructor(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur = null, samplingMode = texture_Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = 0, blockCompilation = false, textureFormat = 5) { - super(name, direction, kernel, options, camera, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (samplingMode = 2), engine, reusable, textureType, `#define DOF 1\n`, blockCompilation, textureFormat); - this.direction = direction; - this.externalTextureSamplerBinding = !!imageToBlur; - this.onApplyObservable.add((effect) => { - if (imageToBlur != null) { - effect.setTextureFromPostProcess("textureSampler", imageToBlur); - } - effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion); - }); - } -} -__decorate([ - serialize() -], DepthOfFieldBlurPostProcess.prototype, "direction", void 0); -RegisterClass("BABYLON.DepthOfFieldBlurPostProcess", DepthOfFieldBlurPostProcess); -//# sourceMappingURL=depthOfFieldBlurPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/depthOfFieldMerge.fragment.js -// Do not edit. - -const depthOfFieldMerge_fragment_name = "depthOfFieldMergePixelShader"; -const depthOfFieldMerge_fragment_shader = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; -#if BLUR_LEVEL>0 -uniform sampler2D blurStep1; -#endif -#if BLUR_LEVEL>1 -uniform sampler2D blurStep2; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; -#if BLUR_LEVEL==0 -vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); -#endif -#if BLUR_LEVEL==1 -if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} -#endif -#if BLUR_LEVEL==2 -if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[depthOfFieldMerge_fragment_name] = depthOfFieldMerge_fragment_shader; -/** @internal */ -const depthOfFieldMergePixelShader = { name: depthOfFieldMerge_fragment_name, shader: depthOfFieldMerge_fragment_shader }; -//# sourceMappingURL=depthOfFieldMerge.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/depthOfFieldMergePostProcess.js - - - -/** - * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion. - */ -class DepthOfFieldMergePostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "DepthOfFieldMergePostProcess" string - */ - getClassName() { - return "DepthOfFieldMergePostProcess"; - } - /** - * Creates a new instance of DepthOfFieldMergePostProcess - * @param name The name of the effect. - * @param originalFromInput Post process which's input will be used for the merge. - * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel. - * @param _blurSteps Blur post processes from low to high which will be mixed with the original image. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @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) - */ - constructor(name, originalFromInput, circleOfConfusion, _blurSteps, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { - super(name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true); - this._blurSteps = _blurSteps; - this.externalTextureSamplerBinding = true; - this.onApplyObservable.add((effect) => { - effect.setTextureFromPostProcess("textureSampler", originalFromInput); - effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion); - _blurSteps.forEach((step, index) => { - effect.setTextureFromPostProcessOutput("blurStep" + (_blurSteps.length - index - 1), step); - }); - }); - if (!blockCompilation) { - this.updateEffect(); - } - } - /** - * Updates the effect with the current post process compile time values and recompiles the shader. - * @param defines Define statements that should be added at the beginning of the shader. (default: null) - * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) - * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) - * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx - * @param onCompiled Called when the shader has been compiled. - * @param onError Called if there is an error when compiling a shader. - */ - updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError) { - if (!defines) { - defines = ""; - defines += "#define BLUR_LEVEL " + (this._blurSteps.length - 1) + "\n"; - } - super.updateEffect(defines, uniforms, samplers, indexParameters, onCompiled, onError); - } -} -//# sourceMappingURL=depthOfFieldMergePostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/depthOfFieldEffect.js - - - - - - - -/** - * Specifies the level of max blur that should be applied when using the depth of field effect - */ -var DepthOfFieldEffectBlurLevel; -(function (DepthOfFieldEffectBlurLevel) { - /** - * Subtle blur - */ - DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low"; - /** - * Medium blur - */ - DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium"; - /** - * Large blur - */ - DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High"; -})(DepthOfFieldEffectBlurLevel || (DepthOfFieldEffectBlurLevel = {})); -/** - * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing. - */ -class DepthOfFieldEffect extends postProcessRenderEffect_PostProcessRenderEffect { - /** - * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter) - */ - set focalLength(value) { - this._circleOfConfusion.focalLength = value; - } - get focalLength() { - return this._circleOfConfusion.focalLength; - } - /** - * F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop. (default: 1.4) - */ - set fStop(value) { - this._circleOfConfusion.fStop = value; - } - get fStop() { - return this._circleOfConfusion.fStop; - } - /** - * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000) - */ - set focusDistance(value) { - this._circleOfConfusion.focusDistance = value; - } - get focusDistance() { - return this._circleOfConfusion.focusDistance; - } - /** - * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diameter of the resulting aperture can be computed by lensSize/fStop. - */ - set lensSize(value) { - this._circleOfConfusion.lensSize = value; - } - get lensSize() { - return this._circleOfConfusion.lensSize; - } - /** - * Creates a new instance DepthOfFieldEffect - * @param scene The scene the effect belongs to. - * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed. - * @param blurLevel - * @param pipelineTextureType The type of texture to be used when performing the post processing. - * @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) - */ - constructor(scene, depthTexture, blurLevel = DepthOfFieldEffectBlurLevel.Low, pipelineTextureType = 0, blockCompilation = false) { - super(scene.getEngine(), "depth of field", () => { - return this._effects; - }, true); - /** - * @internal Internal post processes in depth of field effect - */ - this._effects = []; - // Use R-only formats if supported to store the circle of confusion values. - // This should be more space and bandwidth efficient than using RGBA. - const engine = scene.getEngine(); - const circleOfConfusionTextureFormat = engine.isWebGPU || engine.webGLVersion > 1 ? 6 : 5; - // Circle of confusion value for each pixel is used to determine how much to blur that pixel - this._circleOfConfusion = new CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, pipelineTextureType, blockCompilation); - // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur) - // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts - // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf - this._depthOfFieldBlurY = []; - this._depthOfFieldBlurX = []; - let blurCount = 1; - let kernelSize = 15; - switch (blurLevel) { - case DepthOfFieldEffectBlurLevel.High: { - blurCount = 3; - kernelSize = 51; - break; - } - case DepthOfFieldEffectBlurLevel.Medium: { - blurCount = 2; - kernelSize = 31; - break; - } - default: { - kernelSize = 15; - blurCount = 1; - break; - } - } - const adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1); - let ratio = 1.0; - for (let i = 0; i < blurCount; i++) { - const blurY = new DepthOfFieldBlurPostProcess("vertical blur", scene, new math_vector_Vector2(0, 1.0), adjustedKernelSize, ratio, null, this._circleOfConfusion, i == 0 ? this._circleOfConfusion : null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, pipelineTextureType, blockCompilation, i == 0 ? circleOfConfusionTextureFormat : 5); - blurY.autoClear = false; - ratio = 0.75 / Math.pow(2, i); - const blurX = new DepthOfFieldBlurPostProcess("horizontal blur", scene, new math_vector_Vector2(1.0, 0), adjustedKernelSize, ratio, null, this._circleOfConfusion, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, pipelineTextureType, blockCompilation); - blurX.autoClear = false; - this._depthOfFieldBlurY.push(blurY); - this._depthOfFieldBlurX.push(blurX); - } - // Set all post processes on the effect. - this._effects = [this._circleOfConfusion]; - for (let i = 0; i < this._depthOfFieldBlurX.length; i++) { - this._effects.push(this._depthOfFieldBlurY[i]); - this._effects.push(this._depthOfFieldBlurX[i]); - } - // Merge blurred images with original image based on circleOfConfusion - this._dofMerge = new DepthOfFieldMergePostProcess("dofMerge", this._circleOfConfusion, this._circleOfConfusion, this._depthOfFieldBlurX, ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, pipelineTextureType, blockCompilation); - this._dofMerge.autoClear = false; - this._effects.push(this._dofMerge); - } - /** - * Get the current class name of the current effect - * @returns "DepthOfFieldEffect" - */ - getClassName() { - return "DepthOfFieldEffect"; - } - /** - * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function. - */ - set depthTexture(value) { - this._circleOfConfusion.depthTexture = value; - } - /** - * Disposes each of the internal effects for a given camera. - * @param camera The camera to dispose the effect on. - */ - disposeEffects(camera) { - for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { - this._effects[effectIndex].dispose(camera); - } - } - /** - * @internal Internal - */ - _updateEffects() { - for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { - this._effects[effectIndex].updateEffect(); - } - } - /** - * Internal - * @returns if all the contained post processes are ready. - * @internal - */ - _isReady() { - for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { - if (!this._effects[effectIndex].isReady()) { - return false; - } - } - return true; - } -} -//# sourceMappingURL=depthOfFieldEffect.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/displayPass.fragment.js -// Do not edit. - -const displayPass_fragment_name = "displayPassPixelShader"; -const displayPass_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(passSampler,vUV);}`; -// Sideeffect -ShaderStore.ShadersStore[displayPass_fragment_name] = displayPass_fragment_shader; -/** @internal */ -const displayPassPixelShader = { name: displayPass_fragment_name, shader: displayPass_fragment_shader }; -//# sourceMappingURL=displayPass.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/displayPassPostProcess.js - - - - -/** - * DisplayPassPostProcess which produces an output the same as it's input - */ -class DisplayPassPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "DisplayPassPostProcess" string - */ - getClassName() { - return "DisplayPassPostProcess"; - } - /** - * Creates the DisplayPassPostProcess - * @param name The name of the effect. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - */ - constructor(name, options, camera, samplingMode, engine, reusable) { - super(name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable); - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new DisplayPassPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -RegisterClass("BABYLON.DisplayPassPostProcess", DisplayPassPostProcess); -//# sourceMappingURL=displayPassPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/filter.fragment.js -// Do not edit. - -const filter_fragment_name = "filterPixelShader"; -const filter_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`; -// Sideeffect -ShaderStore.ShadersStore[filter_fragment_name] = filter_fragment_shader; -/** @internal */ -const filterPixelShader = { name: filter_fragment_name, shader: filter_fragment_shader }; -//# sourceMappingURL=filter.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/filterPostProcess.js - - - - - -/** - * Applies a kernel filter to the image - */ -class FilterPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "FilterPostProcess" string - */ - getClassName() { - return "FilterPostProcess"; - } - /** - * - * @param name The name of the effect. - * @param kernelMatrix The matrix to be applied to the image - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - */ - constructor(name, kernelMatrix, options, camera, samplingMode, engine, reusable) { - super(name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable); - this.kernelMatrix = kernelMatrix; - this.onApply = (effect) => { - effect.setMatrix("kernelMatrix", this.kernelMatrix); - }; - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new FilterPostProcess(parsedPostProcess.name, parsedPostProcess.kernelMatrix, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serializeAsMatrix() -], FilterPostProcess.prototype, "kernelMatrix", void 0); -RegisterClass("BABYLON.FilterPostProcess", FilterPostProcess); -//# sourceMappingURL=filterPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fxaa.fragment.js -// Do not edit. - -const fxaa_fragment_name = "fxaaPixelShader"; -const fxaa_fragment_shader = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); -#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) -void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); -#ifndef MALI -if(range<rangeMaxClamped) -{gl_FragColor=rgbyM;return;} -#endif -float lumaNW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNW,0.0));float lumaSE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSE,0.0));float lumaNE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNE,0.0));float lumaSW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSW,0.0));float lumaNS=lumaN+lumaS;float lumaWE=lumaW+lumaE;float subpixRcpRange=1.0/range;float subpixNSWE=lumaNS+lumaWE;float edgeHorz1=(-2.0*lumaM)+lumaNS;float edgeVert1=(-2.0*lumaM)+lumaWE;float lumaNESE=lumaNE+lumaSE;float lumaNWNE=lumaNW+lumaNE;float edgeHorz2=(-2.0*lumaE)+lumaNESE;float edgeVert2=(-2.0*lumaN)+lumaNWNE;float lumaNWSW=lumaNW+lumaSW;float lumaSWSE=lumaSW+lumaSE;float edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);float edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);float edgeHorz3=(-2.0*lumaW)+lumaNWSW;float edgeVert3=(-2.0*lumaS)+lumaSWSE;float edgeHorz=abs(edgeHorz3)+edgeHorz4;float edgeVert=abs(edgeVert3)+edgeVert4;float subpixNWSWNESE=lumaNWSW+lumaNESE;float lengthSign=texelSize.x;bool horzSpan=edgeHorz>=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) -{lumaN=lumaW;} -if (!horzSpan) -{lumaS=lumaE;} -if (horzSpan) -{lengthSign=texelSize.y;} -float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) -{lengthSign=-lengthSign;} -float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) -{posB.x+=lengthSign*0.5;} -if (horzSpan) -{posB.y+=lengthSign*0.5;} -vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) -{lumaNN=lumaSS;} -float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) -{posN.x-=offNP.x*3.0;} -if (!doneN) -{posN.y-=offNP.y*3.0;} -bool doneNP=(!doneN) || (!doneP);if (!doneP) -{posP.x+=offNP.x*3.0;} -if (!doneP) -{posP.y+=offNP.y*3.0;} -if (doneNP) -{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} -float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) -{dstN=posM.y-posN.y;} -if (!horzSpan) -{dstP=posP.y-posM.y;} -bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN<dstP;float dst=min(dstN,dstP);bool goodSpan=directionN ? goodSpanN : goodSpanP;float subpixG=subpixF*subpixF;float pixelOffset=(dst*(-spanLengthRcp))+0.5;float subpixH=subpixG*fxaaQualitySubpix;float pixelOffsetGood=goodSpan ? pixelOffset : 0.0;float pixelOffsetSubpix=max(pixelOffsetGood,subpixH);if (!horzSpan) -{posM.x+=pixelOffsetSubpix*lengthSign;} -if (horzSpan) -{posM.y+=pixelOffsetSubpix*lengthSign;} -#ifdef MALI -if(range<rangeMaxClamped) -{gl_FragColor=rgbyM;} -else -{gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);} -#else -gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0); -#endif -}`; -// Sideeffect -ShaderStore.ShadersStore[fxaa_fragment_name] = fxaa_fragment_shader; -/** @internal */ -const fxaaPixelShader = { name: fxaa_fragment_name, shader: fxaa_fragment_shader }; -//# sourceMappingURL=fxaa.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fxaa.vertex.js -// Do not edit. - -const fxaa_vertex_name = "fxaaVertexShader"; -const fxaa_vertex_shader = `attribute vec2 position;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[fxaa_vertex_name] = fxaa_vertex_shader; -/** @internal */ -const fxaaVertexShader = { name: fxaa_vertex_name, shader: fxaa_vertex_shader }; -//# sourceMappingURL=fxaa.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/fxaaPostProcess.js - - - - - - - -/** - * Fxaa post process - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#fxaa - */ -class FxaaPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "FxaaPostProcess" string - */ - getClassName() { - return "FxaaPostProcess"; - } - constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0) { - super(name, "fxaa", ["texelSize"], null, options, camera, samplingMode || texture_Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true); - const defines = this._getDefines(); - this.updateEffect(defines); - this.onApplyObservable.add((effect) => { - const texelSize = this.texelSize; - effect.setFloat2("texelSize", texelSize.x, texelSize.y); - }); - } - _getDefines() { - const engine = this.getEngine(); - if (!engine) { - return null; - } - const glInfo = engine.getGlInfo(); - if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) { - return "#define MALI 1\n"; - } - return null; - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new FxaaPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -RegisterClass("BABYLON.FxaaPostProcess", FxaaPostProcess); -//# sourceMappingURL=fxaaPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/grain.fragment.js -// Do not edit. - - -const grain_fragment_name = "grainPixelShader"; -const grain_fragment_shader = `#include<helperFunctions> -uniform sampler2D textureSampler; -uniform float intensity;uniform float animatedSeed;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`; -// Sideeffect -ShaderStore.ShadersStore[grain_fragment_name] = grain_fragment_shader; -/** @internal */ -const grainPixelShader = { name: grain_fragment_name, shader: grain_fragment_shader }; -//# sourceMappingURL=grain.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/grainPostProcess.js - - - - - - -/** - * The GrainPostProcess adds noise to the image at mid luminance levels - */ -class GrainPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "GrainPostProcess" string - */ - getClassName() { - return "GrainPostProcess"; - } - /** - * Creates a new instance of @see GrainPostProcess - * @param name The name of the effect. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @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) - */ - constructor(name, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { - super(name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation); - /** - * The intensity of the grain added (default: 30) - */ - this.intensity = 30; - /** - * If the grain should be randomized on every frame - */ - this.animated = false; - this.onApplyObservable.add((effect) => { - effect.setFloat("intensity", this.intensity); - effect.setFloat("animatedSeed", this.animated ? Math.random() + 1 : 1); - }); - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new GrainPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serialize() -], GrainPostProcess.prototype, "intensity", void 0); -__decorate([ - serialize() -], GrainPostProcess.prototype, "animated", void 0); -RegisterClass("BABYLON.GrainPostProcess", GrainPostProcess); -//# sourceMappingURL=grainPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/highlights.fragment.js -// Do not edit. - -const highlights_fragment_name = "highlightsPixelShader"; -const highlights_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`; -// Sideeffect -ShaderStore.ShadersStore[highlights_fragment_name] = highlights_fragment_shader; -/** @internal */ -const highlightsPixelShader = { name: highlights_fragment_name, shader: highlights_fragment_shader }; -//# sourceMappingURL=highlights.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/highlightsPostProcess.js - - - -/** - * Extracts highlights from the image - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses - */ -class HighlightsPostProcess extends (/* unused pure expression or super */ null && (PostProcess)) { - /** - * Gets a string identifying the name of the class - * @returns "HighlightsPostProcess" string - */ - getClassName() { - return "HighlightsPostProcess"; - } - /** - * Extracts highlights from the image - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses - * @param name The name of the effect. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT) - */ - constructor(name, options, camera, samplingMode, engine, reusable, textureType = 0) { - super(name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType); - } -} -//# sourceMappingURL=highlightsPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/mrtFragmentDeclaration.js -// Do not edit. - -const mrtFragmentDeclaration_name = "mrtFragmentDeclaration"; -const mrtFragmentDeclaration_shader = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -layout(location=0) out vec4 glFragData[{X}]; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[mrtFragmentDeclaration_name] = mrtFragmentDeclaration_shader; -/** @internal */ -const mrtFragmentDeclaration = { name: mrtFragmentDeclaration_name, shader: mrtFragmentDeclaration_shader }; -//# sourceMappingURL=mrtFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/geometry.fragment.js -// Do not edit. - - - - - - - - -const geometry_fragment_name = "geometryPixelShader"; -const geometry_fragment_shader = `#extension GL_EXT_draw_buffers : require -#if defined(BUMP) || !defined(NORMAL) -#extension GL_OES_standard_derivatives : enable -#endif -precision highp float; -#ifdef BUMP -varying mat4 vWorldView;varying vec3 vNormalW; -#else -varying vec3 vNormalV; -#endif -varying vec4 vViewPos; -#if defined(POSITION) || defined(BUMP) -varying vec3 vPositionW; -#endif -#ifdef VELOCITY -varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#ifdef NEED_UV -varying vec2 vUV; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#if defined(REFLECTIVITY) -#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) -uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; -#endif -#ifdef ALBEDOTEXTURE -varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; -#endif -#ifdef REFLECTIVITYCOLOR -uniform vec3 reflectivityColor; -#endif -#ifdef ALBEDOCOLOR -uniform vec3 albedoColor; -#endif -#ifdef METALLIC -uniform float metallic; -#endif -#if defined(ROUGHNESS) || defined(GLOSSINESS) -uniform float glossiness; -#endif -#endif -#if defined(ALPHATEST) && defined(NEED_UV) -uniform sampler2D diffuseSampler; -#endif -#include<clipPlaneFragmentDeclaration> -#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT] -#include<bumpFragmentMainFunctions> -#include<bumpFragmentFunctions> -#include<helperFunctions> -void main() { -#include<clipPlaneFragment> -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -vec3 normalOutput; -#ifdef BUMP -vec3 normalW=normalize(vNormalW); -#include<bumpFragment> -normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); -#else -normalOutput=normalize(vNormalV); -#endif -#ifdef PREPASS -#ifdef PREPASS_DEPTH -gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); -#endif -#ifdef PREPASS_NORMAL -gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); -#endif -#else -gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); -#endif -#ifdef POSITION -gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); -#endif -#ifdef VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); -#endif -#ifdef REFLECTIVITY -vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); -#ifdef METALLICWORKFLOW -float metal=1.0;float roughness=1.0; -#ifdef ORMTEXTURE -metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; -#endif -#ifdef METALLIC -metal*=metallic; -#endif -#ifdef ROUGHNESS -roughness*=(1.0-glossiness); -#endif -reflectivity.a-=roughness;vec3 color=vec3(1.0); -#ifdef ALBEDOTEXTURE -color=texture2D(albedoSampler,vAlbedoUV).rgb; -#ifdef GAMMAALBEDO -color=toLinearSpace(color); -#endif -#endif -#ifdef ALBEDOCOLOR -color*=albedoColor.xyz; -#endif -reflectivity.rgb=mix(vec3(0.04),color,metal); -#else -#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) -reflectivity=texture2D(reflectivitySampler,vReflectivityUV); -#ifdef GAMMAREFLECTIVITYTEXTURE -reflectivity.rgb=toLinearSpace(reflectivity.rgb); -#endif -#else -#ifdef REFLECTIVITYCOLOR -reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; -#endif -#endif -#ifdef GLOSSINESSS -reflectivity.a*=glossiness; -#endif -#endif -gl_FragData[REFLECTIVITY_INDEX]=reflectivity; -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[geometry_fragment_name] = geometry_fragment_shader; -/** @internal */ -const geometryPixelShader = { name: geometry_fragment_name, shader: geometry_fragment_shader }; -//# sourceMappingURL=geometry.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/geometryVertexDeclaration.js -// Do not edit. - -const geometryVertexDeclaration_name = "geometryVertexDeclaration"; -const geometryVertexDeclaration_shader = `uniform mat4 viewProjection;uniform mat4 view;`; -// Sideeffect -ShaderStore.IncludesShadersStore[geometryVertexDeclaration_name] = geometryVertexDeclaration_shader; -/** @internal */ -const geometryVertexDeclaration = { name: geometryVertexDeclaration_name, shader: geometryVertexDeclaration_shader }; -//# sourceMappingURL=geometryVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/geometryUboDeclaration.js -// Do not edit. - - -const geometryUboDeclaration_name = "geometryUboDeclaration"; -const geometryUboDeclaration_shader = `#include<sceneUboDeclaration> -`; -// Sideeffect -ShaderStore.IncludesShadersStore[geometryUboDeclaration_name] = geometryUboDeclaration_shader; -/** @internal */ -const geometryUboDeclaration = { name: geometryUboDeclaration_name, shader: geometryUboDeclaration_shader }; -//# sourceMappingURL=geometryUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/geometry.vertex.js -// Do not edit. - - - - - - - - - - - - - - - - -const geometry_vertex_name = "geometryVertexShader"; -const geometry_vertex_shader = `precision highp float; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<instancesDeclaration> -#include<__decl__geometryVertex> -#include<clipPlaneVertexDeclaration> -attribute vec3 position;attribute vec3 normal; -#ifdef NEED_UV -varying vec2 vUV; -#ifdef ALPHATEST -uniform mat4 diffuseMatrix; -#endif -#ifdef BUMP -uniform mat4 bumpMatrix;varying vec2 vBumpUV; -#endif -#ifdef REFLECTIVITY -uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#ifdef BUMP -varying mat4 vWorldView; -#endif -#ifdef BUMP -varying vec3 vNormalW; -#else -varying vec3 vNormalV; -#endif -varying vec4 vViewPos; -#if defined(POSITION) || defined(BUMP) -varying vec3 vPositionW; -#endif -#ifdef VELOCITY -uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position;vec3 normalUpdated=normal; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); -#ifdef BUMP -vWorldView=view*finalWorld;vNormalW=normalUpdated; -#else -vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); -#endif -vViewPos=view*worldPos; -#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#if NUM_BONE_INFLUENCERS>0 -mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); -#else -vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#endif -#if defined(POSITION) || defined(BUMP) -vPositionW=worldPos.xyz/worldPos.w; -#endif -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#include<clipPlaneVertex> -#ifdef NEED_UV -#ifdef UV1 -#if defined(ALPHATEST) && defined(ALPHATEST_UV1) -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#else -vUV=uv; -#endif -#ifdef BUMP_UV1 -vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef REFLECTIVITY_UV1 -vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef ALBEDO_UV1 -vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#endif -#ifdef UV2 -#if defined(ALPHATEST) && defined(ALPHATEST_UV2) -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#else -vUV=uv2; -#endif -#ifdef BUMP_UV2 -vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); -#endif -#ifdef REFLECTIVITY_UV2 -vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); -#endif -#ifdef ALBEDO_UV2 -vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#endif -#include<bumpVertex> -} -`; -// Sideeffect -ShaderStore.ShadersStore[geometry_vertex_name] = geometry_vertex_shader; -/** @internal */ -const geometryVertexShader = { name: geometry_vertex_name, shader: geometry_vertex_shader }; -//# sourceMappingURL=geometry.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/geometryBufferRenderer.js - - - - - - - - - - - - - -/** list the uniforms used by the geometry renderer */ -const uniforms = [ - "world", - "mBones", - "viewProjection", - "diffuseMatrix", - "view", - "previousWorld", - "previousViewProjection", - "mPreviousBones", - "bumpMatrix", - "reflectivityMatrix", - "albedoMatrix", - "reflectivityColor", - "albedoColor", - "metallic", - "glossiness", - "vTangentSpaceParams", - "vBumpInfos", - "morphTargetInfluences", - "morphTargetTextureInfo", - "morphTargetTextureIndices", -]; -addClipPlaneUniforms(uniforms); -/** - * This renderer is helpful to fill one of the render target with a geometry buffer. - */ -class GeometryBufferRenderer { - /** - * @internal - * Sets up internal structures to share outputs with PrePassRenderer - * This method should only be called by the PrePassRenderer itself - */ - _linkPrePassRenderer(prePassRenderer) { - this._linkedWithPrePass = true; - this._prePassRenderer = prePassRenderer; - if (this._multiRenderTarget) { - // prevents clearing of the RT since it's done by prepass - this._multiRenderTarget.onClearObservable.clear(); - this._multiRenderTarget.onClearObservable.add(() => { - // pass - }); - } - } - /** - * @internal - * Separates internal structures from PrePassRenderer so the geometry buffer can now operate by itself. - * This method should only be called by the PrePassRenderer itself - */ - _unlinkPrePassRenderer() { - this._linkedWithPrePass = false; - this._createRenderTargets(); - } - /** - * @internal - * Resets the geometry buffer layout - */ - _resetLayout() { - this._enablePosition = false; - this._enableReflectivity = false; - this._enableVelocity = false; - this._attachmentsFromPrePass = []; - } - /** - * @internal - * Replaces a texture in the geometry buffer renderer - * Useful when linking textures of the prepass renderer - */ - _forceTextureType(geometryBufferType, index) { - if (geometryBufferType === GeometryBufferRenderer.POSITION_TEXTURE_TYPE) { - this._positionIndex = index; - this._enablePosition = true; - } - else if (geometryBufferType === GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE) { - this._velocityIndex = index; - this._enableVelocity = true; - } - else if (geometryBufferType === GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE) { - this._reflectivityIndex = index; - this._enableReflectivity = true; - } - else if (geometryBufferType === GeometryBufferRenderer.DEPTH_TEXTURE_TYPE) { - this._depthIndex = index; - } - else if (geometryBufferType === GeometryBufferRenderer.NORMAL_TEXTURE_TYPE) { - this._normalIndex = index; - } - } - /** - * @internal - * Sets texture attachments - * Useful when linking textures of the prepass renderer - */ - _setAttachments(attachments) { - this._attachmentsFromPrePass = attachments; - } - /** - * @internal - * Replaces the first texture which is hard coded as a depth texture in the geometry buffer - * Useful when linking textures of the prepass renderer - */ - _linkInternalTexture(internalTexture) { - this._multiRenderTarget.setInternalTexture(internalTexture, 0, false); - } - /** - * Gets the render list (meshes to be rendered) used in the G buffer. - */ - get renderList() { - return this._multiRenderTarget.renderList; - } - /** - * Set the render list (meshes to be rendered) used in the G buffer. - */ - set renderList(meshes) { - this._multiRenderTarget.renderList = meshes; - } - /** - * Gets whether or not G buffer are supported by the running hardware. - * This requires draw buffer supports - */ - get isSupported() { - return this._multiRenderTarget.isSupported; - } - /** - * Returns the index of the given texture type in the G-Buffer textures array - * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX - * @returns the index of the given texture type in the G-Buffer textures array - */ - getTextureIndex(textureType) { - switch (textureType) { - case GeometryBufferRenderer.POSITION_TEXTURE_TYPE: - return this._positionIndex; - case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: - return this._velocityIndex; - case GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE: - return this._reflectivityIndex; - default: - return -1; - } - } - /** - * Gets a boolean indicating if objects positions are enabled for the G buffer. - */ - get enablePosition() { - return this._enablePosition; - } - /** - * Sets whether or not objects positions are enabled for the G buffer. - */ - set enablePosition(enable) { - this._enablePosition = enable; - // PrePass handles index and texture links - if (!this._linkedWithPrePass) { - this.dispose(); - this._createRenderTargets(); - } - } - /** - * Gets a boolean indicating if objects velocities are enabled for the G buffer. - */ - get enableVelocity() { - return this._enableVelocity; - } - /** - * Sets whether or not objects velocities are enabled for the G buffer. - */ - set enableVelocity(enable) { - this._enableVelocity = enable; - if (!enable) { - this._previousTransformationMatrices = {}; - } - if (!this._linkedWithPrePass) { - this.dispose(); - this._createRenderTargets(); - } - this._scene.needsPreviousWorldMatrices = enable; - } - /** - * Gets a boolean indicating if objects reflectivity are enabled in the G buffer. - */ - get enableReflectivity() { - return this._enableReflectivity; - } - /** - * Sets whether or not objects reflectivity are enabled for the G buffer. - * For Metallic-Roughness workflow with ORM texture, we assume that ORM texture is defined according to the default layout: - * pbr.useRoughnessFromMetallicTextureAlpha = false; - * pbr.useRoughnessFromMetallicTextureGreen = true; - * pbr.useMetallnessFromMetallicTextureBlue = true; - */ - set enableReflectivity(enable) { - this._enableReflectivity = enable; - if (!this._linkedWithPrePass) { - this.dispose(); - this._createRenderTargets(); - } - } - /** - * Gets the scene associated with the buffer. - */ - get scene() { - return this._scene; - } - /** - * Gets the ratio used by the buffer during its creation. - * How big is the buffer related to the main canvas. - */ - get ratio() { - return this._ratio; - } - /** - * Creates a new G Buffer for the scene - * @param scene The scene the buffer belongs to - * @param ratio How big is the buffer related to the main canvas (default: 1) - * @param depthFormat Format of the depth texture (default: 15) - */ - constructor(scene, ratio = 1, depthFormat = 15) { - /** - * Dictionary used to store the previous transformation matrices of each rendered mesh - * in order to compute objects velocities when enableVelocity is set to "true" - * @internal - */ - this._previousTransformationMatrices = {}; - /** - * Dictionary used to store the previous bones transformation matrices of each rendered mesh - * in order to compute objects velocities when enableVelocity is set to "true" - * @internal - */ - this._previousBonesTransformationMatrices = {}; - /** - * Array used to store the ignored skinned meshes while computing velocity map (typically used by the motion blur post-process). - * Avoids computing bones velocities and computes only mesh's velocity itself (position, rotation, scaling). - */ - this.excludedSkinnedMeshesFromVelocity = []; - /** Gets or sets a boolean indicating if transparent meshes should be rendered */ - this.renderTransparentMeshes = true; - this._resizeObserver = null; - this._enablePosition = false; - this._enableVelocity = false; - this._enableReflectivity = false; - this._clearColor = new math_color_Color4(0, 0, 0, 0); - this._clearDepthColor = new math_color_Color4(1e8, 0, 0, 1); // "infinity" value - depth in the depth texture is view.z, not a 0..1 value! - this._positionIndex = -1; - this._velocityIndex = -1; - this._reflectivityIndex = -1; - this._depthIndex = -1; - this._normalIndex = -1; - this._linkedWithPrePass = false; - /** - * 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) - * If set to false, the depth texture is always cleared with 0. - */ - this.useSpecificClearForDepthTexture = false; - this._scene = scene; - this._ratio = ratio; - this._useUbo = scene.getEngine().supportsUniformBuffers; - this._depthFormat = depthFormat; - GeometryBufferRenderer._SceneComponentInitialization(this._scene); - // Render target - this._createRenderTargets(); - } - /** - * Checks whether everything is ready to render a submesh to the G buffer. - * @param subMesh the submesh to check readiness for - * @param useInstances is the mesh drawn using instance or not - * @returns true if ready otherwise false - */ - isReady(subMesh, useInstances) { - const material = subMesh.getMaterial(); - if (material && material.disableDepthWrite) { - return false; - } - const defines = []; - const attribs = [buffer_VertexBuffer.PositionKind, buffer_VertexBuffer.NormalKind]; - const mesh = subMesh.getMesh(); - // Alpha test - if (material) { - let needUv = false; - if (material.needAlphaTesting() && material.getAlphaTestTexture()) { - defines.push("#define ALPHATEST"); - defines.push(`#define ALPHATEST_UV${material.getAlphaTestTexture().coordinatesIndex + 1}`); - needUv = true; - } - if (material.bumpTexture && MaterialFlags.BumpTextureEnabled) { - defines.push("#define BUMP"); - defines.push(`#define BUMP_UV${material.bumpTexture.coordinatesIndex + 1}`); - needUv = true; - } - if (this._enableReflectivity) { - let metallicWorkflow = false; - // for PBR materials: cf. https://doc.babylonjs.com/features/featuresDeepDive/materials/using/masterPBR - if (material.getClassName() === "PBRMetallicRoughnessMaterial") { - // if it is a PBR material in MetallicRoughness Mode: - if (material.metallicRoughnessTexture !== null) { - defines.push("#define ORMTEXTURE"); - defines.push(`#define REFLECTIVITY_UV${material.metallicRoughnessTexture.coordinatesIndex + 1}`); - defines.push("#define METALLICWORKFLOW"); - needUv = true; - metallicWorkflow = true; - } - if (material.metallic !== null) { - defines.push("#define METALLIC"); - defines.push("#define METALLICWORKFLOW"); - metallicWorkflow = true; - } - if (material.roughness !== null) { - defines.push("#define ROUGHNESS"); - defines.push("#define METALLICWORKFLOW"); - metallicWorkflow = true; - } - if (metallicWorkflow) { - if (material.baseTexture !== null) { - defines.push("#define ALBEDOTEXTURE"); - defines.push(`#define ALBEDO_UV${material.baseTexture.coordinatesIndex + 1}`); - if (material.baseTexture.gammaSpace) { - defines.push("#define GAMMAALBEDO"); - } - needUv = true; - } - if (material.baseColor !== null) { - defines.push("#define ALBEDOCOLOR"); - } - } - } - else if (material.getClassName() === "PBRSpecularGlossinessMaterial") { - // if it is a PBR material in Specular/Glossiness Mode: - if (material.specularGlossinessTexture !== null) { - defines.push("#define SPECULARGLOSSINESSTEXTURE"); - defines.push(`#define REFLECTIVITY_UV${material.specularGlossinessTexture.coordinatesIndex + 1}`); - needUv = true; - if (material.specularGlossinessTexture.gammaSpace) { - defines.push("#define GAMMAREFLECTIVITYTEXTURE"); - } - } - else { - if (material.specularColor !== null) { - defines.push("#define REFLECTIVITYCOLOR"); - } - } - if (material.glossiness !== null) { - defines.push("#define GLOSSINESS"); - } - } - else if (material.getClassName() === "PBRMaterial") { - // if it is the bigger PBRMaterial - if (material.metallicTexture !== null) { - defines.push("#define ORMTEXTURE"); - defines.push(`#define REFLECTIVITY_UV${material.metallicTexture.coordinatesIndex + 1}`); - defines.push("#define METALLICWORKFLOW"); - needUv = true; - metallicWorkflow = true; - } - if (material.metallic !== null) { - defines.push("#define METALLIC"); - defines.push("#define METALLICWORKFLOW"); - metallicWorkflow = true; - } - if (material.roughness !== null) { - defines.push("#define ROUGHNESS"); - defines.push("#define METALLICWORKFLOW"); - metallicWorkflow = true; - } - if (metallicWorkflow) { - if (material.albedoTexture !== null) { - defines.push("#define ALBEDOTEXTURE"); - defines.push(`#define ALBEDO_UV${material.albedoTexture.coordinatesIndex + 1}`); - if (material.albedoTexture.gammaSpace) { - defines.push("#define GAMMAALBEDO"); - } - needUv = true; - } - if (material.albedoColor !== null) { - defines.push("#define ALBEDOCOLOR"); - } - } - else { - // SpecularGlossiness Model - if (material.reflectivityTexture !== null) { - defines.push("#define SPECULARGLOSSINESSTEXTURE"); - defines.push(`#define REFLECTIVITY_UV${material.reflectivityTexture.coordinatesIndex + 1}`); - if (material.reflectivityTexture.gammaSpace) { - defines.push("#define GAMMAREFLECTIVITYTEXTURE"); - } - needUv = true; - } - else if (material.reflectivityColor !== null) { - defines.push("#define REFLECTIVITYCOLOR"); - } - if (material.microSurface !== null) { - defines.push("#define GLOSSINESS"); - } - } - } - else if (material.getClassName() === "StandardMaterial") { - // if StandardMaterial: - if (material.specularTexture !== null) { - defines.push("#define REFLECTIVITYTEXTURE"); - defines.push(`#define REFLECTIVITY_UV${material.specularTexture.coordinatesIndex + 1}`); - if (material.specularTexture.gammaSpace) { - defines.push("#define GAMMAREFLECTIVITYTEXTURE"); - } - needUv = true; - } - if (material.specularColor !== null) { - defines.push("#define REFLECTIVITYCOLOR"); - } - } - } - if (needUv) { - defines.push("#define NEED_UV"); - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - attribs.push(buffer_VertexBuffer.UVKind); - defines.push("#define UV1"); - } - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)) { - attribs.push(buffer_VertexBuffer.UV2Kind); - defines.push("#define UV2"); - } - } - } - // PrePass - if (this._linkedWithPrePass) { - defines.push("#define PREPASS"); - if (this._depthIndex !== -1) { - defines.push("#define DEPTH_INDEX " + this._depthIndex); - defines.push("#define PREPASS_DEPTH"); - } - if (this._normalIndex !== -1) { - defines.push("#define NORMAL_INDEX " + this._normalIndex); - defines.push("#define PREPASS_NORMAL"); - } - } - // Buffers - if (this._enablePosition) { - defines.push("#define POSITION"); - defines.push("#define POSITION_INDEX " + this._positionIndex); - } - if (this._enableVelocity) { - defines.push("#define VELOCITY"); - defines.push("#define VELOCITY_INDEX " + this._velocityIndex); - if (this.excludedSkinnedMeshesFromVelocity.indexOf(mesh) === -1) { - defines.push("#define BONES_VELOCITY_ENABLED"); - } - } - if (this._enableReflectivity) { - defines.push("#define REFLECTIVITY"); - defines.push("#define REFLECTIVITY_INDEX " + this._reflectivityIndex); - } - // Bones - if (mesh.useBones && mesh.computeBonesUsingShaders) { - attribs.push(buffer_VertexBuffer.MatricesIndicesKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsKind); - if (mesh.numBoneInfluencers > 4) { - attribs.push(buffer_VertexBuffer.MatricesIndicesExtraKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsExtraKind); - } - defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); - defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0)); - } - else { - defines.push("#define NUM_BONE_INFLUENCERS 0"); - } - // Morph targets - const morphTargetManager = mesh.morphTargetManager; - let numMorphInfluencers = 0; - if (morphTargetManager) { - if (morphTargetManager.numInfluencers > 0) { - numMorphInfluencers = morphTargetManager.numInfluencers; - defines.push("#define MORPHTARGETS"); - defines.push("#define NUM_MORPH_INFLUENCERS " + numMorphInfluencers); - if (morphTargetManager.isUsingTextureForTargets) { - defines.push("#define MORPHTARGETS_TEXTURE"); - } - MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers); - } - } - // Instances - if (useInstances) { - defines.push("#define INSTANCES"); - MaterialHelper.PushAttributesForInstances(attribs, this._enableVelocity); - if (subMesh.getRenderingMesh().hasThinInstances) { - defines.push("#define THIN_INSTANCES"); - } - } - // Setup textures count - if (this._linkedWithPrePass) { - defines.push("#define RENDER_TARGET_COUNT " + this._attachmentsFromPrePass.length); - } - else { - defines.push("#define RENDER_TARGET_COUNT " + this._multiRenderTarget.textures.length); - } - prepareStringDefinesForClipPlanes(material, this._scene, defines); - // Get correct effect - const engine = this._scene.getEngine(); - const drawWrapper = subMesh._getDrawWrapper(undefined, true); - const cachedDefines = drawWrapper.defines; - const join = defines.join("\n"); - if (cachedDefines !== join) { - drawWrapper.setEffect(engine.createEffect("geometry", { - attributes: attribs, - uniformsNames: uniforms, - samplers: ["diffuseSampler", "bumpSampler", "reflectivitySampler", "albedoSampler", "morphTargets"], - defines: join, - onCompiled: null, - fallbacks: null, - onError: null, - uniformBuffersNames: ["Scene"], - indexParameters: { buffersCount: this._multiRenderTarget.textures.length - 1, maxSimultaneousMorphTargets: numMorphInfluencers }, - }, engine), join); - } - return drawWrapper.effect.isReady(); - } - /** - * Gets the current underlying G Buffer. - * @returns the buffer - */ - getGBuffer() { - return this._multiRenderTarget; - } - /** - * Gets the number of samples used to render the buffer (anti aliasing). - */ - get samples() { - return this._multiRenderTarget.samples; - } - /** - * Sets the number of samples used to render the buffer (anti aliasing). - */ - set samples(value) { - this._multiRenderTarget.samples = value; - } - /** - * Disposes the renderer and frees up associated resources. - */ - dispose() { - if (this._resizeObserver) { - const engine = this._scene.getEngine(); - engine.onResizeObservable.remove(this._resizeObserver); - this._resizeObserver = null; - } - this.getGBuffer().dispose(); - } - _assignRenderTargetIndices() { - const textureNames = []; - let count = 2; - textureNames.push("gBuffer_Depth", "gBuffer_Normal"); - if (this._enablePosition) { - this._positionIndex = count; - count++; - textureNames.push("gBuffer_Position"); - } - if (this._enableVelocity) { - this._velocityIndex = count; - count++; - textureNames.push("gBuffer_Velocity"); - } - if (this._enableReflectivity) { - this._reflectivityIndex = count; - count++; - textureNames.push("gBuffer_Reflectivity"); - } - return [count, textureNames]; - } - _createRenderTargets() { - const engine = this._scene.getEngine(); - const [count, textureNames] = this._assignRenderTargetIndices(); - let type = 0; - if (engine._caps.textureFloat && engine._caps.textureFloatLinearFiltering) { - type = 1; - } - else if (engine._caps.textureHalfFloat && engine._caps.textureHalfFloatLinearFiltering) { - type = 2; - } - 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")); - if (!this.isSupported) { - return; - } - this._multiRenderTarget.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._multiRenderTarget.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._multiRenderTarget.refreshRate = 1; - this._multiRenderTarget.renderParticles = false; - this._multiRenderTarget.renderList = null; - // Depth is always the first texture in the geometry buffer renderer! - const layoutAttachmentsAll = [true]; - const layoutAttachmentsAllButDepth = [false]; - const layoutAttachmentsDepthOnly = [true]; - for (let i = 1; i < count; ++i) { - layoutAttachmentsAll.push(true); - layoutAttachmentsDepthOnly.push(false); - layoutAttachmentsAllButDepth.push(true); - } - const attachmentsAll = engine.buildTextureLayout(layoutAttachmentsAll); - const attachmentsAllButDepth = engine.buildTextureLayout(layoutAttachmentsAllButDepth); - const attachmentsDepthOnly = engine.buildTextureLayout(layoutAttachmentsDepthOnly); - this._multiRenderTarget.onClearObservable.add((engine) => { - engine.bindAttachments(this.useSpecificClearForDepthTexture ? attachmentsAllButDepth : attachmentsAll); - engine.clear(this._clearColor, true, true, true); - if (this.useSpecificClearForDepthTexture) { - engine.bindAttachments(attachmentsDepthOnly); - engine.clear(this._clearDepthColor, true, true, true); - } - engine.bindAttachments(attachmentsAll); - }); - this._resizeObserver = engine.onResizeObservable.add(() => { - if (this._multiRenderTarget) { - this._multiRenderTarget.resize({ width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }); - } - }); - // Custom render function - const renderSubMesh = (subMesh) => { - const renderingMesh = subMesh.getRenderingMesh(); - const effectiveMesh = subMesh.getEffectiveMesh(); - const scene = this._scene; - const engine = scene.getEngine(); - const material = subMesh.getMaterial(); - if (!material) { - return; - } - effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; - // Velocity - if (this._enableVelocity && !this._previousTransformationMatrices[effectiveMesh.uniqueId]) { - this._previousTransformationMatrices[effectiveMesh.uniqueId] = { - world: math_vector_Matrix.Identity(), - viewProjection: scene.getTransformMatrix(), - }; - if (renderingMesh.skeleton) { - const bonesTransformations = renderingMesh.skeleton.getTransformMatrices(renderingMesh); - this._previousBonesTransformationMatrices[renderingMesh.uniqueId] = this._copyBonesTransformationMatrices(bonesTransformations, new Float32Array(bonesTransformations.length)); - } - } - // Managing instances - const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); - if (batch.mustReturn) { - return; - } - const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); - const world = effectiveMesh.getWorldMatrix(); - if (this.isReady(subMesh, hardwareInstancedRendering)) { - const drawWrapper = subMesh._getDrawWrapper(); - if (!drawWrapper) { - return; - } - const effect = drawWrapper.effect; - engine.enableEffect(drawWrapper); - if (!hardwareInstancedRendering) { - renderingMesh._bind(subMesh, effect, material.fillMode); - } - if (!this._useUbo) { - effect.setMatrix("viewProjection", scene.getTransformMatrix()); - effect.setMatrix("view", scene.getViewMatrix()); - } - else { - MaterialHelper.BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer()); - this._scene.finalizeSceneUbo(); - } - let sideOrientation; - const instanceDataStorage = renderingMesh._instanceDataStorage; - if (!instanceDataStorage.isFrozen && (material.backFaceCulling || renderingMesh.overrideMaterialSideOrientation !== null)) { - const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant(); - sideOrientation = renderingMesh.overrideMaterialSideOrientation; - if (sideOrientation === null) { - sideOrientation = material.sideOrientation; - } - if (mainDeterminant < 0) { - sideOrientation = sideOrientation === material_Material.ClockWiseSideOrientation ? material_Material.CounterClockWiseSideOrientation : material_Material.ClockWiseSideOrientation; - } - } - else { - sideOrientation = instanceDataStorage.sideOrientation; - } - material._preBind(drawWrapper, sideOrientation); - // Alpha test - if (material.needAlphaTesting()) { - const alphaTexture = material.getAlphaTestTexture(); - if (alphaTexture) { - effect.setTexture("diffuseSampler", alphaTexture); - effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); - } - } - // Bump - if (material.bumpTexture && scene.getEngine().getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled) { - effect.setFloat3("vBumpInfos", material.bumpTexture.coordinatesIndex, 1.0 / material.bumpTexture.level, material.parallaxScaleBias); - effect.setMatrix("bumpMatrix", material.bumpTexture.getTextureMatrix()); - effect.setTexture("bumpSampler", material.bumpTexture); - effect.setFloat2("vTangentSpaceParams", material.invertNormalMapX ? -1.0 : 1.0, material.invertNormalMapY ? -1.0 : 1.0); - } - // Reflectivity - if (this._enableReflectivity) { - // for PBR materials: cf. https://doc.babylonjs.com/features/featuresDeepDive/materials/using/masterPBR - if (material.getClassName() === "PBRMetallicRoughnessMaterial") { - // if it is a PBR material in MetallicRoughness Mode: - if (material.metallicRoughnessTexture !== null) { - effect.setTexture("reflectivitySampler", material.metallicRoughnessTexture); - effect.setMatrix("reflectivityMatrix", material.metallicRoughnessTexture.getTextureMatrix()); - } - if (material.metallic !== null) { - effect.setFloat("metallic", material.metallic); - } - if (material.roughness !== null) { - effect.setFloat("glossiness", 1.0 - material.roughness); - } - if (material.baseTexture !== null) { - effect.setTexture("albedoSampler", material.baseTexture); - effect.setMatrix("albedoMatrix", material.baseTexture.getTextureMatrix()); - } - if (material.baseColor !== null) { - effect.setColor3("albedoColor", material.baseColor); - } - } - else if (material.getClassName() === "PBRSpecularGlossinessMaterial") { - // if it is a PBR material in Specular/Glossiness Mode: - if (material.specularGlossinessTexture !== null) { - effect.setTexture("reflectivitySampler", material.specularGlossinessTexture); - effect.setMatrix("reflectivityMatrix", material.specularGlossinessTexture.getTextureMatrix()); - } - else { - if (material.specularColor !== null) { - effect.setColor3("reflectivityColor", material.specularColor); - } - } - if (material.glossiness !== null) { - effect.setFloat("glossiness", material.glossiness); - } - } - else if (material.getClassName() === "PBRMaterial") { - // if it is the bigger PBRMaterial - if (material.metallicTexture !== null) { - effect.setTexture("reflectivitySampler", material.metallicTexture); - effect.setMatrix("reflectivityMatrix", material.metallicTexture.getTextureMatrix()); - } - if (material.metallic !== null) { - effect.setFloat("metallic", material.metallic); - } - if (material.roughness !== null) { - effect.setFloat("glossiness", 1.0 - material.roughness); - } - if (material.roughness !== null || material.metallic !== null || material.metallicTexture !== null) { - // MetallicRoughness Model - if (material.albedoTexture !== null) { - effect.setTexture("albedoSampler", material.albedoTexture); - effect.setMatrix("albedoMatrix", material.albedoTexture.getTextureMatrix()); - } - if (material.albedoColor !== null) { - effect.setColor3("albedoColor", material.albedoColor); - } - } - else { - // SpecularGlossiness Model - if (material.reflectivityTexture !== null) { - effect.setTexture("reflectivitySampler", material.reflectivityTexture); - effect.setMatrix("reflectivityMatrix", material.reflectivityTexture.getTextureMatrix()); - } - else if (material.reflectivityColor !== null) { - effect.setColor3("reflectivityColor", material.reflectivityColor); - } - if (material.microSurface !== null) { - effect.setFloat("glossiness", material.microSurface); - } - } - } - else if (material.getClassName() === "StandardMaterial") { - // if StandardMaterial: - if (material.specularTexture !== null) { - effect.setTexture("reflectivitySampler", material.specularTexture); - effect.setMatrix("reflectivityMatrix", material.specularTexture.getTextureMatrix()); - } - if (material.specularColor !== null) { - effect.setColor3("reflectivityColor", material.specularColor); - } - } - } - // Clip plane - bindClipPlane(effect, material, this._scene); - // Bones - if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { - effect.setMatrices("mBones", renderingMesh.skeleton.getTransformMatrices(renderingMesh)); - if (this._enableVelocity) { - effect.setMatrices("mPreviousBones", this._previousBonesTransformationMatrices[renderingMesh.uniqueId]); - } - } - // Morph targets - MaterialHelper.BindMorphTargetParameters(renderingMesh, effect); - if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { - renderingMesh.morphTargetManager._bind(effect); - } - // Velocity - if (this._enableVelocity) { - effect.setMatrix("previousWorld", this._previousTransformationMatrices[effectiveMesh.uniqueId].world); - effect.setMatrix("previousViewProjection", this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection); - } - if (hardwareInstancedRendering && renderingMesh.hasThinInstances) { - effect.setMatrix("world", world); - } - // Draw - renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, w) => { - if (!isInstance) { - effect.setMatrix("world", w); - } - }); - } - // Velocity - if (this._enableVelocity) { - this._previousTransformationMatrices[effectiveMesh.uniqueId].world = world.clone(); - this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection = this._scene.getTransformMatrix().clone(); - if (renderingMesh.skeleton) { - this._copyBonesTransformationMatrices(renderingMesh.skeleton.getTransformMatrices(renderingMesh), this._previousBonesTransformationMatrices[effectiveMesh.uniqueId]); - } - } - }; - this._multiRenderTarget.customIsReadyFunction = (mesh, refreshRate, preWarm) => { - if ((preWarm || refreshRate === 0) && mesh.subMeshes) { - for (let i = 0; i < mesh.subMeshes.length; ++i) { - const subMesh = mesh.subMeshes[i]; - const material = subMesh.getMaterial(); - const renderingMesh = subMesh.getRenderingMesh(); - if (!material) { - continue; - } - const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); - const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); - if (!this.isReady(subMesh, hardwareInstancedRendering)) { - return false; - } - } - } - return true; - }; - this._multiRenderTarget.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { - let index; - if (this._linkedWithPrePass) { - if (!this._prePassRenderer.enabled) { - return; - } - this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass); - } - if (depthOnlySubMeshes.length) { - engine.setColorWrite(false); - for (index = 0; index < depthOnlySubMeshes.length; index++) { - renderSubMesh(depthOnlySubMeshes.data[index]); - } - engine.setColorWrite(true); - } - for (index = 0; index < opaqueSubMeshes.length; index++) { - renderSubMesh(opaqueSubMeshes.data[index]); - } - engine.setDepthWrite(false); - for (index = 0; index < alphaTestSubMeshes.length; index++) { - renderSubMesh(alphaTestSubMeshes.data[index]); - } - if (this.renderTransparentMeshes) { - for (index = 0; index < transparentSubMeshes.length; index++) { - renderSubMesh(transparentSubMeshes.data[index]); - } - } - engine.setDepthWrite(true); - }; - } - // Copies the bones transformation matrices into the target array and returns the target's reference - _copyBonesTransformationMatrices(source, target) { - for (let i = 0; i < source.length; i++) { - target[i] = source[i]; - } - return target; - } -} -/** - * Constant used to retrieve the depth texture index in the G-Buffer textures array - * using getIndex(GeometryBufferRenderer.DEPTH_TEXTURE_INDEX) - */ -GeometryBufferRenderer.DEPTH_TEXTURE_TYPE = 0; -/** - * Constant used to retrieve the normal texture index in the G-Buffer textures array - * using getIndex(GeometryBufferRenderer.NORMAL_TEXTURE_INDEX) - */ -GeometryBufferRenderer.NORMAL_TEXTURE_TYPE = 1; -/** - * Constant used to retrieve the position texture index in the G-Buffer textures array - * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX) - */ -GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 2; -/** - * Constant used to retrieve the velocity texture index in the G-Buffer textures array - * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX) - */ -GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 3; -/** - * Constant used to retrieve the reflectivity texture index in the G-Buffer textures array - * using the getIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE) - */ -GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE = 4; -/** - * @internal - */ -GeometryBufferRenderer._SceneComponentInitialization = (_) => { - throw _WarnImport("GeometryBufferRendererSceneComponent"); -}; -//# sourceMappingURL=geometryBufferRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/motionBlurConfiguration.js - -/** - * Contains all parameters needed for the prepass to perform - * motion blur - */ -class MotionBlurConfiguration { - constructor() { - /** - * Is motion blur enabled - */ - this.enabled = false; - /** - * Name of the configuration - */ - this.name = "motionBlur"; - /** - * Textures that should be present in the MRT for this effect to work - */ - this.texturesRequired = [2]; - } -} -//# sourceMappingURL=motionBlurConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/geometryBufferRendererSceneComponent.js - - - - -Object.defineProperty(scene_Scene.prototype, "geometryBufferRenderer", { - get: function () { - return this._geometryBufferRenderer; - }, - set: function (value) { - if (value && value.isSupported) { - this._geometryBufferRenderer = value; - } - }, - enumerable: true, - configurable: true, -}); -scene_Scene.prototype.enableGeometryBufferRenderer = function (ratio = 1, depthFormat = 15) { - if (this._geometryBufferRenderer) { - return this._geometryBufferRenderer; - } - this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio, depthFormat); - if (!this._geometryBufferRenderer.isSupported) { - this._geometryBufferRenderer = null; - } - return this._geometryBufferRenderer; -}; -scene_Scene.prototype.disableGeometryBufferRenderer = function () { - if (!this._geometryBufferRenderer) { - return; - } - this._geometryBufferRenderer.dispose(); - this._geometryBufferRenderer = null; -}; -/** - * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful - * in several rendering techniques. - */ -class GeometryBufferRendererSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER; - this.scene = scene; - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._gatherRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing to do for this component - } - /** - * Disposes the component and the associated resources - */ - dispose() { - // Nothing to do for this component - } - _gatherRenderTargets(renderTargets) { - if (this.scene._geometryBufferRenderer) { - renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer()); - } - } -} -GeometryBufferRenderer._SceneComponentInitialization = (scene) => { - // Register the G Buffer component to the scene. - let component = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER); - if (!component) { - component = new GeometryBufferRendererSceneComponent(scene); - scene._addComponent(component); - } -}; -//# sourceMappingURL=geometryBufferRendererSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/motionBlur.fragment.js -// Do not edit. - -const motionBlur_fragment_name = "motionBlurPixelShader"; -const motionBlur_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; -#ifdef OBJECT_BASED -uniform sampler2D velocitySampler; -#else -uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#ifdef GEOMETRY_SUPPORTED -#ifdef OBJECT_BASED -vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) -{if (i>=samplesCount) -break;vec2 offset=vUV+velocity*(hlim+float(i)); -#if defined(WEBGPU) -result+=texture2DLodEXT(textureSampler,offset,0.0); -#else -result+=texture2D(textureSampler,offset); -#endif -} -gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; -#else -vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; -vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) {if (i>=nSamples) -break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); -#if defined(WEBGPU) -result+=texture2DLodEXT(textureSampler,offset1,0.0); -#else -result+=texture2D(textureSampler,offset1); -#endif -} -gl_FragColor=result/float(nSamples); -#endif -#else -gl_FragColor=texture2D(textureSampler,vUV); -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[motionBlur_fragment_name] = motionBlur_fragment_shader; -/** @internal */ -const motionBlurPixelShader = { name: motionBlur_fragment_name, shader: motionBlur_fragment_shader }; -//# sourceMappingURL=motionBlur.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/motionBlurPostProcess.js - - - - - - - - - - - - -/** - * The Motion Blur Post Process which blurs an image based on the objects velocity in scene. - * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed. - * As an example, all you have to do is to create the post-process: - * var mb = new BABYLON.MotionBlurPostProcess( - * 'mb', // The name of the effect. - * scene, // The scene containing the objects to blur according to their velocity. - * 1.0, // The required width/height ratio to downsize to before computing the render pass. - * camera // The camera to apply the render pass to. - * ); - * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed. - */ -class MotionBlurPostProcess extends postProcess_PostProcess { - /** - * Gets the number of iterations are used for motion blur quality. Default value is equal to 32 - */ - get motionBlurSamples() { - return this._motionBlurSamples; - } - /** - * Sets the number of iterations to be used for motion blur quality - */ - set motionBlurSamples(samples) { - this._motionBlurSamples = samples; - this._updateEffect(); - } - /** - * Gets whether or not the motion blur post-process is in object based mode. - */ - get isObjectBased() { - return this._isObjectBased; - } - /** - * Sets whether or not the motion blur post-process is in object based mode. - */ - set isObjectBased(value) { - if (this._isObjectBased === value) { - return; - } - this._isObjectBased = value; - this._applyMode(); - } - get _geometryBufferRenderer() { - if (!this._forceGeometryBuffer) { - return null; - } - return this._scene.geometryBufferRenderer; - } - get _prePassRenderer() { - if (this._forceGeometryBuffer) { - return null; - } - return this._scene.prePassRenderer; - } - /** - * Gets a string identifying the name of the class - * @returns "MotionBlurPostProcess" string - */ - getClassName() { - return "MotionBlurPostProcess"; - } - /** - * Creates a new instance MotionBlurPostProcess - * @param name The name of the effect. - * @param scene The scene containing the objects to blur according to their velocity. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @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) - * @param forceGeometryBuffer If this post process should use geometry buffer instead of prepass (default: false) - */ - constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false, forceGeometryBuffer = false) { - 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); - /** - * Defines how much the image is blurred by the movement. Default value is equal to 1 - */ - this.motionStrength = 1; - this._motionBlurSamples = 32; - this._isObjectBased = true; - this._forceGeometryBuffer = false; - this._invViewProjection = null; - this._previousViewProjection = null; - this._forceGeometryBuffer = forceGeometryBuffer; - // Set up assets - if (this._forceGeometryBuffer) { - scene.enableGeometryBufferRenderer(); - if (this._geometryBufferRenderer) { - this._geometryBufferRenderer.enableVelocity = true; - } - } - else { - scene.enablePrePassRenderer(); - if (this._prePassRenderer) { - this._prePassRenderer.markAsDirty(); - this._prePassEffectConfiguration = new MotionBlurConfiguration(); - } - } - this._applyMode(); - } - /** - * Excludes the given skinned mesh from computing bones velocities. - * 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. - * @param skinnedMesh The mesh containing the skeleton to ignore when computing the velocity map. - */ - excludeSkinnedMesh(skinnedMesh) { - if (skinnedMesh.skeleton) { - let list; - if (this._geometryBufferRenderer) { - list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity; - } - else if (this._prePassRenderer) { - list = this._prePassRenderer.excludedSkinnedMesh; - } - else { - return; - } - list.push(skinnedMesh); - } - } - /** - * Removes the given skinned mesh from the excluded meshes to integrate bones velocities while rendering the velocity map. - * @param skinnedMesh The mesh containing the skeleton that has been ignored previously. - * @see excludeSkinnedMesh to exclude a skinned mesh from bones velocity computation. - */ - removeExcludedSkinnedMesh(skinnedMesh) { - if (skinnedMesh.skeleton) { - let list; - if (this._geometryBufferRenderer) { - list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity; - } - else if (this._prePassRenderer) { - list = this._prePassRenderer.excludedSkinnedMesh; - } - else { - return; - } - const index = list.indexOf(skinnedMesh); - if (index !== -1) { - list.splice(index, 1); - } - } - } - /** - * Disposes the post process. - * @param camera The camera to dispose the post process on. - */ - dispose(camera) { - if (this._geometryBufferRenderer) { - // Clear previous transformation matrices dictionary used to compute objects velocities - this._geometryBufferRenderer._previousTransformationMatrices = {}; - this._geometryBufferRenderer._previousBonesTransformationMatrices = {}; - this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity = []; - } - super.dispose(camera); - } - /** - * Called on the mode changed (object based or screen based). - */ - _applyMode() { - if (!this._geometryBufferRenderer && !this._prePassRenderer) { - // We can't get a velocity or depth texture. So, work as a passthrough. - logger_Logger.Warn("Multiple Render Target support needed to compute object based motion blur"); - return this.updateEffect(); - } - this._updateEffect(); - this._invViewProjection = null; - this._previousViewProjection = null; - if (this.isObjectBased) { - if (this._prePassRenderer && this._prePassEffectConfiguration) { - this._prePassEffectConfiguration.texturesRequired[0] = 2; - } - this.onApply = (effect) => this._onApplyObjectBased(effect); - } - else { - this._invViewProjection = math_vector_Matrix.Identity(); - this._previousViewProjection = this._scene.getTransformMatrix().clone(); - if (this._prePassRenderer && this._prePassEffectConfiguration) { - this._prePassEffectConfiguration.texturesRequired[0] = 5; - } - this.onApply = (effect) => this._onApplyScreenBased(effect); - } - } - /** - * Called on the effect is applied when the motion blur post-process is in object based mode. - * @param effect - */ - _onApplyObjectBased(effect) { - effect.setVector2("screenSize", new math_vector_Vector2(this.width, this.height)); - effect.setFloat("motionScale", this._scene.getAnimationRatio()); - effect.setFloat("motionStrength", this.motionStrength); - if (this._geometryBufferRenderer) { - const velocityIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE); - effect.setTexture("velocitySampler", this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]); - } - else if (this._prePassRenderer) { - const velocityIndex = this._prePassRenderer.getIndex(2); - effect.setTexture("velocitySampler", this._prePassRenderer.getRenderTarget().textures[velocityIndex]); - } - } - /** - * Called on the effect is applied when the motion blur post-process is in screen based mode. - * @param effect - */ - _onApplyScreenBased(effect) { - const viewProjection = math_vector_TmpVectors.Matrix[0]; - viewProjection.copyFrom(this._scene.getTransformMatrix()); - viewProjection.invertToRef(this._invViewProjection); - effect.setMatrix("inverseViewProjection", this._invViewProjection); - effect.setMatrix("prevViewProjection", this._previousViewProjection); - this._previousViewProjection.copyFrom(viewProjection); - effect.setMatrix("projection", this._scene.getProjectionMatrix()); - effect.setVector2("screenSize", new math_vector_Vector2(this.width, this.height)); - effect.setFloat("motionScale", this._scene.getAnimationRatio()); - effect.setFloat("motionStrength", this.motionStrength); - if (this._geometryBufferRenderer) { - const depthIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE); - effect.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[depthIndex]); - } - else if (this._prePassRenderer) { - const depthIndex = this._prePassRenderer.getIndex(5); - effect.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[depthIndex]); - } - } - /** - * Called on the effect must be updated (changed mode, samples count, etc.). - */ - _updateEffect() { - if (this._geometryBufferRenderer || this._prePassRenderer) { - const defines = [ - "#define GEOMETRY_SUPPORTED", - "#define SAMPLES " + this._motionBlurSamples.toFixed(1), - this._isObjectBased ? "#define OBJECT_BASED" : "#define SCREEN_BASED", - ]; - this.updateEffect(defines.join("\n")); - } - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new MotionBlurPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, false); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serialize() -], MotionBlurPostProcess.prototype, "motionStrength", void 0); -__decorate([ - serialize() -], MotionBlurPostProcess.prototype, "motionBlurSamples", null); -__decorate([ - serialize() -], MotionBlurPostProcess.prototype, "isObjectBased", null); -RegisterClass("BABYLON.MotionBlurPostProcess", MotionBlurPostProcess); -//# sourceMappingURL=motionBlurPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/refraction.fragment.js -// Do not edit. - -const refraction_fragment_name = "refractionPixelShader"; -const refraction_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}`; -// Sideeffect -ShaderStore.ShadersStore[refraction_fragment_name] = refraction_fragment_shader; -/** @internal */ -const refractionPixelShader = { name: refraction_fragment_name, shader: refraction_fragment_shader }; -//# sourceMappingURL=refraction.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/refractionPostProcess.js - - - - - - -/** - * Post process which applies a refraction texture - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#refraction - */ -class RefractionPostProcess extends postProcess_PostProcess { - /** - * Gets or sets the refraction texture - * Please note that you are responsible for disposing the texture if you set it manually - */ - get refractionTexture() { - return this._refTexture; - } - set refractionTexture(value) { - if (this._refTexture && this._ownRefractionTexture) { - this._refTexture.dispose(); - } - this._refTexture = value; - this._ownRefractionTexture = false; - } - /** - * Gets a string identifying the name of the class - * @returns "RefractionPostProcess" string - */ - getClassName() { - return "RefractionPostProcess"; - } - /** - * Initializes the RefractionPostProcess - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#refraction - * @param name The name of the effect. - * @param refractionTextureUrl Url of the refraction texture to use - * @param color the base color of the refraction (used to taint the rendering) - * @param depth simulated refraction depth - * @param colorLevel the coefficient of the base color (0 to remove base color tainting) - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - */ - constructor(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) { - super(name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable); - this._ownRefractionTexture = true; - this.color = color; - this.depth = depth; - this.colorLevel = colorLevel; - this.refractionTextureUrl = refractionTextureUrl; - this.onActivateObservable.add((cam) => { - this._refTexture = this._refTexture || new texture_Texture(refractionTextureUrl, cam.getScene()); - }); - this.onApplyObservable.add((effect) => { - effect.setColor3("baseColor", this.color); - effect.setFloat("depth", this.depth); - effect.setFloat("colorLevel", this.colorLevel); - effect.setTexture("refractionSampler", this._refTexture); - }); - } - // Methods - /** - * Disposes of the post process - * @param camera Camera to dispose post process on - */ - dispose(camera) { - if (this._refTexture && this._ownRefractionTexture) { - this._refTexture.dispose(); - this._refTexture = null; - } - super.dispose(camera); - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new RefractionPostProcess(parsedPostProcess.name, parsedPostProcess.refractionTextureUrl, parsedPostProcess.color, parsedPostProcess.depth, parsedPostProcess.colorLevel, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serialize() -], RefractionPostProcess.prototype, "color", void 0); -__decorate([ - serialize() -], RefractionPostProcess.prototype, "depth", void 0); -__decorate([ - serialize() -], RefractionPostProcess.prototype, "colorLevel", void 0); -__decorate([ - serialize() -], RefractionPostProcess.prototype, "refractionTextureUrl", void 0); -RegisterClass("BABYLON.RefractionPostProcess", RefractionPostProcess); -//# sourceMappingURL=refractionPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/sharpen.fragment.js -// Do not edit. - -const sharpen_fragment_name = "sharpenPixelShader"; -const sharpen_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + -texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + -texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + -texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - -color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`; -// Sideeffect -ShaderStore.ShadersStore[sharpen_fragment_name] = sharpen_fragment_shader; -/** @internal */ -const sharpenPixelShader = { name: sharpen_fragment_name, shader: sharpen_fragment_shader }; -//# sourceMappingURL=sharpen.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/sharpenPostProcess.js - - - - - - -/** - * The SharpenPostProcess applies a sharpen kernel to every pixel - * See http://en.wikipedia.org/wiki/Kernel_(image_processing) - */ -class SharpenPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "SharpenPostProcess" string - */ - getClassName() { - return "SharpenPostProcess"; - } - /** - * Creates a new instance ConvolutionPostProcess - * @param name The name of the effect. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @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) - */ - constructor(name, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { - super(name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation); - /** - * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1) - */ - this.colorAmount = 1.0; - /** - * How much sharpness should be applied (default: 0.3) - */ - this.edgeAmount = 0.3; - this.onApply = (effect) => { - effect.setFloat2("screenSize", this.width, this.height); - effect.setFloat2("sharpnessAmounts", this.edgeAmount, this.colorAmount); - }; - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new SharpenPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serialize() -], SharpenPostProcess.prototype, "colorAmount", void 0); -__decorate([ - serialize() -], SharpenPostProcess.prototype, "edgeAmount", void 0); -RegisterClass("BABYLON.SharpenPostProcess", SharpenPostProcess); -//# sourceMappingURL=sharpenPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipeline.js - - - -/** - * PostProcessRenderPipeline - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/postProcessRenderPipeline - */ -class postProcessRenderPipeline_PostProcessRenderPipeline { - /** - * Gets pipeline name - */ - get name() { - return this._name; - } - /** Gets the list of attached cameras */ - get cameras() { - return this._cameras; - } - /** - * Initializes a PostProcessRenderPipeline - * @param _engine engine to add the pipeline to - * @param name name of the pipeline - */ - constructor(_engine, name) { - this._engine = _engine; - this._name = name; - this._renderEffects = {}; - this._renderEffectsForIsolatedPass = new Array(); - this._cameras = []; - } - /** - * Gets the class name - * @returns "PostProcessRenderPipeline" - */ - getClassName() { - return "PostProcessRenderPipeline"; - } - /** - * If all the render effects in the pipeline are supported - */ - get isSupported() { - for (const renderEffectName in this._renderEffects) { - if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { - if (!this._renderEffects[renderEffectName].isSupported) { - return false; - } - } - } - return true; - } - /** - * Adds an effect to the pipeline - * @param renderEffect the effect to add - */ - addEffect(renderEffect) { - this._renderEffects[renderEffect._name] = renderEffect; - } - // private - /** @internal */ - _rebuild() { } - /** - * @internal - */ - _enableEffect(renderEffectName, cameras) { - const renderEffects = this._renderEffects[renderEffectName]; - if (!renderEffects) { - return; - } - renderEffects._enable(tools_Tools.MakeArray(cameras || this._cameras)); - } - /** - * @internal - */ - _disableEffect(renderEffectName, cameras) { - const renderEffects = this._renderEffects[renderEffectName]; - if (!renderEffects) { - return; - } - renderEffects._disable(tools_Tools.MakeArray(cameras || this._cameras)); - } - /** - * @internal - */ - _attachCameras(cameras, unique) { - const cams = tools_Tools.MakeArray(cameras || this._cameras); - if (!cams) { - return; - } - const indicesToDelete = []; - let i; - for (i = 0; i < cams.length; i++) { - const camera = cams[i]; - if (!camera) { - continue; - } - if (this._cameras.indexOf(camera) === -1) { - this._cameras.push(camera); - } - else if (unique) { - indicesToDelete.push(i); - } - } - for (i = 0; i < indicesToDelete.length; i++) { - cams.splice(indicesToDelete[i], 1); - } - for (const renderEffectName in this._renderEffects) { - if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { - this._renderEffects[renderEffectName]._attachCameras(cams); - } - } - } - /** - * @internal - */ - _detachCameras(cameras) { - const cams = tools_Tools.MakeArray(cameras || this._cameras); - if (!cams) { - return; - } - for (const renderEffectName in this._renderEffects) { - if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { - this._renderEffects[renderEffectName]._detachCameras(cams); - } - } - for (let i = 0; i < cams.length; i++) { - this._cameras.splice(this._cameras.indexOf(cams[i]), 1); - } - } - /** @internal */ - _update() { - for (const renderEffectName in this._renderEffects) { - if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { - this._renderEffects[renderEffectName]._update(); - } - } - for (let i = 0; i < this._cameras.length; i++) { - if (!this._cameras[i]) { - continue; - } - const cameraName = this._cameras[i].name; - if (this._renderEffectsForIsolatedPass[cameraName]) { - this._renderEffectsForIsolatedPass[cameraName]._update(); - } - } - } - /** @internal */ - _reset() { - this._renderEffects = {}; - this._renderEffectsForIsolatedPass = new Array(); - } - _enableMSAAOnFirstPostProcess(sampleCount) { - if (!this._engine._features.supportMSAA) { - return false; - } - // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754) - const effectKeys = Object.keys(this._renderEffects); - if (effectKeys.length > 0) { - const postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses(); - if (postProcesses) { - postProcesses[0].samples = sampleCount; - } - } - return true; - } - /** - * Sets the required values to the prepass renderer. - * @param prePassRenderer defines the prepass renderer to setup. - * @returns true if the pre pass is needed. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - setPrePassRenderer(prePassRenderer) { - // Do Nothing by default - return false; - } - /** - * Disposes of the pipeline - */ - dispose() { - // Must be implemented by children - } -} -__decorate([ - serialize() -], postProcessRenderPipeline_PostProcessRenderPipeline.prototype, "_name", void 0); -//# sourceMappingURL=postProcessRenderPipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipelineManager.js -/** - * PostProcessRenderPipelineManager class - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/postProcessRenderPipeline - */ -class PostProcessRenderPipelineManager { - /** - * Initializes a PostProcessRenderPipelineManager - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/postProcessRenderPipeline - */ - constructor() { - this._renderPipelines = {}; - } - /** - * Gets the list of supported render pipelines - */ - get supportedPipelines() { - const result = []; - for (const renderPipelineName in this._renderPipelines) { - if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { - const pipeline = this._renderPipelines[renderPipelineName]; - if (pipeline.isSupported) { - result.push(pipeline); - } - } - } - return result; - } - /** - * Adds a pipeline to the manager - * @param renderPipeline The pipeline to add - */ - addPipeline(renderPipeline) { - this._renderPipelines[renderPipeline._name] = renderPipeline; - } - /** - * Remove the pipeline from the manager - * @param renderPipelineName the name of the pipeline to remove - */ - removePipeline(renderPipelineName) { - delete this._renderPipelines[renderPipelineName]; - } - /** - * Attaches a camera to the pipeline - * @param renderPipelineName The name of the pipeline to attach to - * @param cameras the camera to attach - * @param unique if the camera can be attached multiple times to the pipeline - */ - attachCamerasToRenderPipeline(renderPipelineName, cameras, unique = false) { - const renderPipeline = this._renderPipelines[renderPipelineName]; - if (!renderPipeline) { - return; - } - renderPipeline._attachCameras(cameras, unique); - } - /** - * Detaches a camera from the pipeline - * @param renderPipelineName The name of the pipeline to detach from - * @param cameras the camera to detach - */ - detachCamerasFromRenderPipeline(renderPipelineName, cameras) { - const renderPipeline = this._renderPipelines[renderPipelineName]; - if (!renderPipeline) { - return; - } - renderPipeline._detachCameras(cameras); - } - /** - * Enables an effect by name on a pipeline - * @param renderPipelineName the name of the pipeline to enable the effect in - * @param renderEffectName the name of the effect to enable - * @param cameras the cameras that the effect should be enabled on - */ - enableEffectInPipeline(renderPipelineName, renderEffectName, cameras) { - const renderPipeline = this._renderPipelines[renderPipelineName]; - if (!renderPipeline) { - return; - } - renderPipeline._enableEffect(renderEffectName, cameras); - } - /** - * Disables an effect by name on a pipeline - * @param renderPipelineName the name of the pipeline to disable the effect in - * @param renderEffectName the name of the effect to disable - * @param cameras the cameras that the effect should be disabled on - */ - disableEffectInPipeline(renderPipelineName, renderEffectName, cameras) { - const renderPipeline = this._renderPipelines[renderPipelineName]; - if (!renderPipeline) { - return; - } - renderPipeline._disableEffect(renderEffectName, cameras); - } - /** - * Updates the state of all contained render pipelines and disposes of any non supported pipelines - */ - update() { - for (const renderPipelineName in this._renderPipelines) { - if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { - const pipeline = this._renderPipelines[renderPipelineName]; - if (!pipeline.isSupported) { - pipeline.dispose(); - delete this._renderPipelines[renderPipelineName]; - } - else { - pipeline._update(); - } - } - } - } - /** @internal */ - _rebuild() { - for (const renderPipelineName in this._renderPipelines) { - if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { - const pipeline = this._renderPipelines[renderPipelineName]; - pipeline._rebuild(); - } - } - } - /** - * Disposes of the manager and pipelines - */ - dispose() { - for (const renderPipelineName in this._renderPipelines) { - if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { - const pipeline = this._renderPipelines[renderPipelineName]; - pipeline.dispose(); - } - } - } -} -//# sourceMappingURL=postProcessRenderPipelineManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipelineManagerSceneComponent.js - - - -Object.defineProperty(scene_Scene.prototype, "postProcessRenderPipelineManager", { - get: function () { - if (!this._postProcessRenderPipelineManager) { - // Register the G Buffer component to the scene. - let component = this._getComponent(sceneComponent_SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER); - if (!component) { - component = new PostProcessRenderPipelineManagerSceneComponent(this); - this._addComponent(component); - } - this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager(); - } - return this._postProcessRenderPipelineManager; - }, - enumerable: true, - configurable: true, -}); -/** - * Defines the Render Pipeline scene component responsible to rendering pipelines - */ -class PostProcessRenderPipelineManagerSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER; - this.scene = scene; - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._gatherRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - if (this.scene._postProcessRenderPipelineManager) { - this.scene._postProcessRenderPipelineManager._rebuild(); - } - } - /** - * Disposes the component and the associated resources - */ - dispose() { - if (this.scene._postProcessRenderPipelineManager) { - this.scene._postProcessRenderPipelineManager.dispose(); - } - } - _gatherRenderTargets() { - if (this.scene._postProcessRenderPipelineManager) { - this.scene._postProcessRenderPipelineManager.update(); - } - } -} -//# sourceMappingURL=postProcessRenderPipelineManagerSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/defaultRenderingPipeline.js - - - - - - - - - - - - - - - - - - - - -/** - * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field. - * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/defaultRenderingPipeline - */ -class DefaultRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline { - /** - * Enable or disable automatic building of the pipeline when effects are enabled and disabled. - * If false, you will have to manually call prepare() to update the pipeline. - */ - get automaticBuild() { - return this._buildAllowed; - } - set automaticBuild(value) { - this._buildAllowed = value; - } - /** - * Gets active scene - */ - get scene() { - return this._scene; - } - /** - * Enable or disable the sharpen process from the pipeline - */ - set sharpenEnabled(enabled) { - if (this._sharpenEnabled === enabled) { - return; - } - this._sharpenEnabled = enabled; - this._buildPipeline(); - } - get sharpenEnabled() { - return this._sharpenEnabled; - } - /** - * Specifies the size of the bloom blur kernel, relative to the final output size - */ - get bloomKernel() { - return this._bloomKernel; - } - set bloomKernel(value) { - this._bloomKernel = value; - this.bloom.kernel = value / this._hardwareScaleLevel; - } - /** - * The strength of the bloom. - */ - set bloomWeight(value) { - if (this._bloomWeight === value) { - return; - } - this.bloom.weight = value; - this._bloomWeight = value; - } - get bloomWeight() { - return this._bloomWeight; - } - /** - * The luminance threshold to find bright areas of the image to bloom. - */ - set bloomThreshold(value) { - if (this._bloomThreshold === value) { - return; - } - this.bloom.threshold = value; - this._bloomThreshold = value; - } - get bloomThreshold() { - return this._bloomThreshold; - } - /** - * The scale of the bloom, lower value will provide better performance. - */ - set bloomScale(value) { - if (this._bloomScale === value) { - return; - } - this._bloomScale = value; - // recreate bloom and dispose old as this setting is not dynamic - this._rebuildBloom(); - this._buildPipeline(); - } - get bloomScale() { - return this._bloomScale; - } - /** - * Enable or disable the bloom from the pipeline - */ - set bloomEnabled(enabled) { - if (this._bloomEnabled === enabled) { - return; - } - this._bloomEnabled = enabled; - this._buildPipeline(); - } - get bloomEnabled() { - return this._bloomEnabled; - } - _rebuildBloom() { - // recreate bloom and dispose old as this setting is not dynamic - const oldBloom = this.bloom; - this.bloom = new BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel / this._hardwareScaleLevel, this._defaultPipelineTextureType, false); - this.bloom.threshold = oldBloom.threshold; - for (let i = 0; i < this._cameras.length; i++) { - oldBloom.disposeEffects(this._cameras[i]); - } - } - /** - * If the depth of field is enabled. - */ - get depthOfFieldEnabled() { - return this._depthOfFieldEnabled; - } - set depthOfFieldEnabled(enabled) { - if (this._depthOfFieldEnabled === enabled) { - return; - } - this._depthOfFieldEnabled = enabled; - this._buildPipeline(); - } - /** - * Blur level of the depth of field effect. (Higher blur will effect performance) - */ - get depthOfFieldBlurLevel() { - return this._depthOfFieldBlurLevel; - } - set depthOfFieldBlurLevel(value) { - if (this._depthOfFieldBlurLevel === value) { - return; - } - this._depthOfFieldBlurLevel = value; - // recreate dof and dispose old as this setting is not dynamic - const oldDof = this.depthOfField; - this.depthOfField = new DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false); - this.depthOfField.focalLength = oldDof.focalLength; - this.depthOfField.focusDistance = oldDof.focusDistance; - this.depthOfField.fStop = oldDof.fStop; - this.depthOfField.lensSize = oldDof.lensSize; - for (let i = 0; i < this._cameras.length; i++) { - oldDof.disposeEffects(this._cameras[i]); - } - this._buildPipeline(); - } - /** - * If the anti aliasing is enabled. - */ - set fxaaEnabled(enabled) { - if (this._fxaaEnabled === enabled) { - return; - } - this._fxaaEnabled = enabled; - this._buildPipeline(); - } - get fxaaEnabled() { - return this._fxaaEnabled; - } - /** - * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1) - */ - set samples(sampleCount) { - if (this._samples === sampleCount) { - return; - } - this._samples = sampleCount; - this._buildPipeline(); - } - get samples() { - return this._samples; - } - /** - * If image processing is enabled. - */ - set imageProcessingEnabled(enabled) { - if (this._imageProcessingEnabled === enabled) { - return; - } - this._scene.imageProcessingConfiguration.isEnabled = enabled; - } - get imageProcessingEnabled() { - return this._imageProcessingEnabled; - } - /** - * If glow layer is enabled. (Adds a glow effect to emmissive materials) - */ - set glowLayerEnabled(enabled) { - if (enabled && !this._glowLayer) { - this._glowLayer = new GlowLayer("", this._scene); - } - else if (!enabled && this._glowLayer) { - this._glowLayer.dispose(); - this._glowLayer = null; - } - } - get glowLayerEnabled() { - return this._glowLayer != null; - } - /** - * Gets the glow layer (or null if not defined) - */ - get glowLayer() { - return this._glowLayer; - } - /** - * Enable or disable the chromaticAberration process from the pipeline - */ - set chromaticAberrationEnabled(enabled) { - if (this._chromaticAberrationEnabled === enabled) { - return; - } - this._chromaticAberrationEnabled = enabled; - this._buildPipeline(); - } - get chromaticAberrationEnabled() { - return this._chromaticAberrationEnabled; - } - /** - * Enable or disable the grain process from the pipeline - */ - set grainEnabled(enabled) { - if (this._grainEnabled === enabled) { - return; - } - this._grainEnabled = enabled; - this._buildPipeline(); - } - get grainEnabled() { - return this._grainEnabled; - } - /** - * Instantiates a DefaultRenderingPipeline. - * @param name The rendering pipeline name (default: "") - * @param hdr If high dynamic range textures should be used (default: true) - * @param scene The scene linked to this pipeline (default: the last created scene) - * @param cameras The array of cameras that the rendering pipeline will be attached to (default: scene.cameras) - * @param automaticBuild If false, you will have to manually call prepare() to update the pipeline (default: true) - */ - constructor(name = "", hdr = true, scene = engineStore_EngineStore.LastCreatedScene, cameras, automaticBuild = true) { - super(scene.getEngine(), name); - this._camerasToBeAttached = []; - /** - * ID of the sharpen post process, - */ - this.SharpenPostProcessId = "SharpenPostProcessEffect"; - /** - * @ignore - * ID of the image processing post process; - */ - this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect"; - /** - * @ignore - * ID of the Fast Approximate Anti-Aliasing post process; - */ - this.FxaaPostProcessId = "FxaaPostProcessEffect"; - /** - * ID of the chromatic aberration post process, - */ - this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect"; - /** - * ID of the grain post process - */ - this.GrainPostProcessId = "GrainPostProcessEffect"; - /** - * Glow post process which adds a glow to emissive areas of the image - */ - this._glowLayer = null; - /** - * Animations which can be used to tweak settings over a period of time - */ - this.animations = []; - this._imageProcessingConfigurationObserver = null; - // Values - this._sharpenEnabled = false; - this._bloomEnabled = false; - this._depthOfFieldEnabled = false; - this._depthOfFieldBlurLevel = DepthOfFieldEffectBlurLevel.Low; - this._fxaaEnabled = false; - this._imageProcessingEnabled = true; - this._bloomScale = 0.5; - this._chromaticAberrationEnabled = false; - this._grainEnabled = false; - this._buildAllowed = true; - /** - * This is triggered each time the pipeline has been built. - */ - this.onBuildObservable = new observable_Observable(); - this._resizeObserver = null; - this._hardwareScaleLevel = 1.0; - this._bloomKernel = 64; - /** - * Specifies the weight of the bloom in the final rendering - */ - this._bloomWeight = 0.15; - /** - * Specifies the luma threshold for the area that will be blurred by the bloom - */ - this._bloomThreshold = 0.9; - this._samples = 1; - this._hasCleared = false; - this._prevPostProcess = null; - this._prevPrevPostProcess = null; - this._depthOfFieldSceneObserver = null; - this._activeCameraChangedObserver = null; - this._activeCamerasChangedObserver = null; - this._cameras = cameras || scene.cameras; - this._cameras = this._cameras.slice(); - this._camerasToBeAttached = this._cameras.slice(); - this._buildAllowed = automaticBuild; - // Initialize - this._scene = scene; - const caps = this._scene.getEngine().getCaps(); - this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender); - // Misc - if (this._hdr) { - if (caps.textureHalfFloatRender) { - this._defaultPipelineTextureType = 2; - } - else if (caps.textureFloatRender) { - this._defaultPipelineTextureType = 1; - } - } - else { - this._defaultPipelineTextureType = 0; - } - // Attach - scene.postProcessRenderPipelineManager.addPipeline(this); - const engine = this._scene.getEngine(); - // Create post processes before hand so they can be modified before enabled. - // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline. - this.sharpen = new SharpenPostProcess("sharpen", 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, true); - this._sharpenEffect = new postProcessRenderEffect_PostProcessRenderEffect(engine, this.SharpenPostProcessId, () => { - return this.sharpen; - }, true); - this.depthOfField = new DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, true); - // To keep the bloom sizes consistent across different display densities, factor in the hardware scaling level. - this._hardwareScaleLevel = engine.getHardwareScalingLevel(); - this._resizeObserver = engine.onResizeObservable.add(() => { - this._hardwareScaleLevel = engine.getHardwareScalingLevel(); - this.bloomKernel = this._bloomKernel; - }); - this.bloom = new BloomEffect(this._scene, this._bloomScale, this._bloomWeight, this.bloomKernel / this._hardwareScaleLevel, this._defaultPipelineTextureType, true); - this.chromaticAberration = new ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, true); - this._chromaticAberrationEffect = new postProcessRenderEffect_PostProcessRenderEffect(engine, this.ChromaticAberrationPostProcessId, () => { - return this.chromaticAberration; - }, true); - this.grain = new GrainPostProcess("Grain", 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, true); - this._grainEffect = new postProcessRenderEffect_PostProcessRenderEffect(engine, this.GrainPostProcessId, () => { - return this.grain; - }, true); - this._imageProcessingConfigurationObserver = this._scene.imageProcessingConfiguration.onUpdateParameters.add(() => { - this.bloom._downscale._exposure = this._scene.imageProcessingConfiguration.exposure; - if (this.imageProcessingEnabled !== this._scene.imageProcessingConfiguration.isEnabled) { - this._imageProcessingEnabled = this._scene.imageProcessingConfiguration.isEnabled; - // Avoid re-entrant problems by deferring the call to _buildPipeline because the call to _buildPipeline - // at the end of the constructor could end up triggering imageProcessingConfiguration.onUpdateParameters! - // Note that the pipeline could have been disposed before the deferred call was executed, but in that case - // _buildAllowed will have been set to false, preventing _buildPipeline from being executed. - tools_Tools.SetImmediate(() => { - this._buildPipeline(); - }); - } - }); - this._buildPipeline(); - } - /** - * Get the class name - * @returns "DefaultRenderingPipeline" - */ - getClassName() { - return "DefaultRenderingPipeline"; - } - /** - * Force the compilation of the entire pipeline. - */ - prepare() { - const previousState = this._buildAllowed; - this._buildAllowed = true; - this._buildPipeline(); - this._buildAllowed = previousState; - } - _setAutoClearAndTextureSharing(postProcess, skipTextureSharing = false) { - if (this._hasCleared) { - postProcess.autoClear = false; - } - else { - postProcess.autoClear = true; - this._scene.autoClear = false; - this._hasCleared = true; - } - if (!skipTextureSharing) { - if (this._prevPrevPostProcess) { - postProcess.shareOutputWith(this._prevPrevPostProcess); - } - else { - postProcess.useOwnOutput(); - } - if (this._prevPostProcess) { - this._prevPrevPostProcess = this._prevPostProcess; - } - this._prevPostProcess = postProcess; - } - } - _buildPipeline() { - if (!this._buildAllowed) { - return; - } - this._scene.autoClear = true; - const engine = this._scene.getEngine(); - this._disposePostProcesses(); - if (this._cameras !== null) { - this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); - // get back cameras to be used to reattach pipeline - this._cameras = this._camerasToBeAttached.slice(); - } - this._reset(); - this._prevPostProcess = null; - this._prevPrevPostProcess = null; - this._hasCleared = false; - if (this.depthOfFieldEnabled) { - // Multi camera suport - if (this._cameras.length > 1) { - for (const camera of this._cameras) { - const depthRenderer = this._scene.enableDepthRenderer(camera); - depthRenderer.useOnlyInActiveCamera = true; - } - this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add((scene) => { - if (this._cameras.indexOf(scene.activeCamera) > -1) { - this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap(); - } - }); - } - else { - this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver); - const depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]); - this.depthOfField.depthTexture = depthRenderer.getDepthMap(); - } - if (!this.depthOfField._isReady()) { - this.depthOfField._updateEffects(); - } - this.addEffect(this.depthOfField); - this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true); - } - else { - this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver); - } - if (this.bloomEnabled) { - if (!this.bloom._isReady()) { - this.bloom._updateEffects(); - } - this.addEffect(this.bloom); - this._setAutoClearAndTextureSharing(this.bloom._effects[0], true); - } - if (this._imageProcessingEnabled) { - this.imageProcessing = new ImageProcessingPostProcess("imageProcessing", 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, this.scene.imageProcessingConfiguration); - if (this._hdr) { - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, () => { - return this.imageProcessing; - }, true)); - this._setAutoClearAndTextureSharing(this.imageProcessing); - } - else { - this._scene.imageProcessingConfiguration.applyByPostProcess = false; - } - if (!this._cameras || this._cameras.length === 0) { - this._scene.imageProcessingConfiguration.applyByPostProcess = false; - } - if (!this.imageProcessing.getEffect()) { - this.imageProcessing._updateParameters(); - } - } - if (this.sharpenEnabled) { - if (!this.sharpen.isReady()) { - this.sharpen.updateEffect(); - } - this.addEffect(this._sharpenEffect); - this._setAutoClearAndTextureSharing(this.sharpen); - } - if (this.grainEnabled) { - if (!this.grain.isReady()) { - this.grain.updateEffect(); - } - this.addEffect(this._grainEffect); - this._setAutoClearAndTextureSharing(this.grain); - } - if (this.chromaticAberrationEnabled) { - if (!this.chromaticAberration.isReady()) { - this.chromaticAberration.updateEffect(); - } - this.addEffect(this._chromaticAberrationEffect); - this._setAutoClearAndTextureSharing(this.chromaticAberration); - } - if (this.fxaaEnabled) { - this.fxaa = new FxaaPostProcess("fxaa", 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(engine, this.FxaaPostProcessId, () => { - return this.fxaa; - }, true)); - this._setAutoClearAndTextureSharing(this.fxaa, true); - } - if (this._cameras !== null) { - this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); - } - // In multicamera mode, the scene needs to autoclear in between cameras. - if ((this._scene.activeCameras && this._scene.activeCameras.length > 1) || (this._scene.activeCamera && this._cameras.indexOf(this._scene.activeCamera) === -1)) { - this._scene.autoClear = true; - } - // The active camera on the scene can be changed anytime - if (!this._activeCameraChangedObserver) { - this._activeCameraChangedObserver = this._scene.onActiveCameraChanged.add(() => { - if (this._scene.activeCamera && this._cameras.indexOf(this._scene.activeCamera) === -1) { - this._scene.autoClear = true; - } - }); - } - if (!this._activeCamerasChangedObserver) { - this._activeCamerasChangedObserver = this._scene.onActiveCamerasChanged.add(() => { - if (this._scene.activeCameras && this._scene.activeCameras.length > 1) { - this._scene.autoClear = true; - } - }); - } - if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) { - logger_Logger.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"); - } - this.onBuildObservable.notifyObservers(this); - } - _disposePostProcesses(disposeNonRecreated = false) { - for (let i = 0; i < this._cameras.length; i++) { - const camera = this._cameras[i]; - if (this.imageProcessing) { - this.imageProcessing.dispose(camera); - } - if (this.fxaa) { - this.fxaa.dispose(camera); - } - // These are created in the constructor and should not be disposed on every pipeline change - if (disposeNonRecreated) { - if (this.sharpen) { - this.sharpen.dispose(camera); - } - if (this.depthOfField) { - this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver); - this.depthOfField.disposeEffects(camera); - } - if (this.bloom) { - this.bloom.disposeEffects(camera); - } - if (this.chromaticAberration) { - this.chromaticAberration.dispose(camera); - } - if (this.grain) { - this.grain.dispose(camera); - } - if (this._glowLayer) { - this._glowLayer.dispose(); - } - } - } - this.imageProcessing = null; - this.fxaa = null; - if (disposeNonRecreated) { - this.sharpen = null; - this._sharpenEffect = null; - this.depthOfField = null; - this.bloom = null; - this.chromaticAberration = null; - this._chromaticAberrationEffect = null; - this.grain = null; - this._grainEffect = null; - this._glowLayer = null; - } - } - /** - * Adds a camera to the pipeline - * @param camera the camera to be added - */ - addCamera(camera) { - this._camerasToBeAttached.push(camera); - this._buildPipeline(); - } - /** - * Removes a camera from the pipeline - * @param camera the camera to remove - */ - removeCamera(camera) { - const index = this._camerasToBeAttached.indexOf(camera); - this._camerasToBeAttached.splice(index, 1); - this._buildPipeline(); - } - /** - * Dispose of the pipeline and stop all post processes - */ - dispose() { - this._buildAllowed = false; - this.onBuildObservable.clear(); - this._disposePostProcesses(true); - this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); - this._scene._postProcessRenderPipelineManager.removePipeline(this.name); - this._scene.autoClear = true; - if (this._resizeObserver) { - this._scene.getEngine().onResizeObservable.remove(this._resizeObserver); - this._resizeObserver = null; - } - this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver); - this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver); - this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver); - super.dispose(); - } - /** - * Serialize the rendering pipeline (Used when exporting) - * @returns the serialized object - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.customType = "DefaultRenderingPipeline"; - return serializationObject; - } - /** - * Parse the serialized pipeline - * @param source Source pipeline. - * @param scene The scene to load the pipeline to. - * @param rootUrl The URL of the serialized pipeline. - * @returns An instantiated pipeline from the serialized object. - */ - static Parse(source, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => new DefaultRenderingPipeline(source._name, source._name._hdr, scene), source, scene, rootUrl); - } -} -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "sharpenEnabled", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "bloomKernel", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "_hdr", void 0); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "bloomWeight", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "bloomThreshold", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "bloomScale", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "bloomEnabled", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "fxaaEnabled", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "samples", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null); -__decorate([ - serialize() -], DefaultRenderingPipeline.prototype, "grainEnabled", null); -RegisterClass("BABYLON.DefaultRenderingPipeline", DefaultRenderingPipeline); -//# sourceMappingURL=defaultRenderingPipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/lensHighlights.fragment.js -// Do not edit. - -const lensHighlights_fragment_name = "lensHighlightsPixelShader"; -const lensHighlights_fragment_shader = `uniform sampler2D textureSampler; -uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } -else { lum_threshold=0.5+0.44*threshold; } -luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} -float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); -#ifdef PENTAGON -blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); -#else -blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); -#endif -blurred/=39.0;gl_FragColor=blurred;}`; -// Sideeffect -ShaderStore.ShadersStore[lensHighlights_fragment_name] = lensHighlights_fragment_shader; -/** @internal */ -const lensHighlightsPixelShader = { name: lensHighlights_fragment_name, shader: lensHighlights_fragment_shader }; -//# sourceMappingURL=lensHighlights.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/depthOfField.fragment.js -// Do not edit. - -const depthOfField_fragment_name = "depthOfFieldPixelShader"; -const depthOfField_fragment_shader = `uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; -uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; -#define PI 3.14159265 -#define TWOPI 6.28318530 -#define inverse_focal_length 0.1 -vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) -{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} -vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } -vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} -float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} -float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} -vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} -if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} -col/=total_weight; -if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} -return col;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); -vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); -float depth=texture2D(depthSampler,distorted_coords).r; -float distance=near+(far-near)*depth; -vec4 color=texture2D(textureSampler,vUV); -float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } -float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} -float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} -else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} -if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} -if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} -`; -// Sideeffect -ShaderStore.ShadersStore[depthOfField_fragment_name] = depthOfField_fragment_shader; -/** @internal */ -const depthOfFieldPixelShader = { name: depthOfField_fragment_name, shader: depthOfField_fragment_shader }; -//# sourceMappingURL=depthOfField.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/lensRenderingPipeline.js - - - - - - - - - -/** - * BABYLON.JS Chromatic Aberration GLSL Shader - * Author: Olivier Guyot - * Separates very slightly R, G and B colors on the edges of the screen - * Inspired by Francois Tarlier & Martins Upitis - */ -class LensRenderingPipeline extends (/* unused pure expression or super */ null && (PostProcessRenderPipeline)) { - /** - * @constructor - * - * Effect parameters are as follow: - * { - * chromatic_aberration: number; // from 0 to x (1 for realism) - * edge_blur: number; // from 0 to x (1 for realism) - * distortion: number; // from 0 to x (1 for realism), note that this will effect the pointer position precision - * grain_amount: number; // from 0 to 1 - * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise - * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default) - * dof_aperture: number; // depth-of-field: focus blur bias (default: 1) - * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default) - * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect - * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default) - * dof_threshold: number; // depth-of-field: highlights threshold (default: 1) - * blur_noise: boolean; // add a little bit of noise to the blur (default: true) - * } - * Note: if an effect parameter is unset, effect is disabled - * - * @param name The rendering pipeline name - * @param parameters - An object containing all parameters (see above) - * @param scene The scene linked to this pipeline - * @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) - * @param cameras The array of cameras that the rendering pipeline will be attached to - */ - constructor(name, parameters, scene, ratio = 1.0, cameras) { - super(scene.getEngine(), name); - // Lens effects can be of the following: - // - chromatic aberration (slight shift of RGB colors) - // - blur on the edge of the lens - // - lens distortion - // - depth-of-field blur & highlights enhancing - // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas) - // - grain effect (noise or custom texture) - // Two additional texture samplers are needed: - // - depth map (for depth-of-field) - // - grain texture - /** - * @ignore - * The chromatic aberration PostProcess id in the pipeline - */ - this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect"; - /** - * @ignore - * The highlights enhancing PostProcess id in the pipeline - */ - this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect"; - /** - * @ignore - * The depth-of-field PostProcess id in the pipeline - */ - this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect"; - this._pentagonBokehIsEnabled = false; - this._scene = scene; - // Fetch texture samplers - this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on" - if (parameters.grain_texture) { - this._grainTexture = parameters.grain_texture; - } - else { - this._createGrainTexture(); - } - // save parameters - this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0; - this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0; - this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0; - this._distortion = parameters.distortion ? parameters.distortion : 0; - this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1; - this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1; - this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1; - this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1; - this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0; - this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true; - this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true; - // Create effects - this._createChromaticAberrationPostProcess(ratio); - this._createHighlightsPostProcess(ratio); - this._createDepthOfFieldPostProcess(ratio / 4); - // Set up pipeline - this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, () => { - return this._chromaticAberrationPostProcess; - }, true)); - this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, () => { - return this._highlightsPostProcess; - }, true)); - this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, () => { - return this._depthOfFieldPostProcess; - }, true)); - if (this._highlightsGain === -1) { - this._disableEffect(this.HighlightsEnhancingEffect, null); - } - // Finish - scene.postProcessRenderPipelineManager.addPipeline(this); - if (cameras) { - scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras); - } - } - /** - * Get the class name - * @returns "LensRenderingPipeline" - */ - getClassName() { - return "LensRenderingPipeline"; - } - // Properties - /** - * Gets associated scene - */ - get scene() { - return this._scene; - } - /** - * Gets or sets the edge blur - */ - get edgeBlur() { - return this._edgeBlur; - } - set edgeBlur(value) { - this.setEdgeBlur(value); - } - /** - * Gets or sets the grain amount - */ - get grainAmount() { - return this._grainAmount; - } - set grainAmount(value) { - this.setGrainAmount(value); - } - /** - * Gets or sets the chromatic aberration amount - */ - get chromaticAberration() { - return this._chromaticAberration; - } - set chromaticAberration(value) { - this.setChromaticAberration(value); - } - /** - * Gets or sets the depth of field aperture - */ - get dofAperture() { - return this._dofAperture; - } - set dofAperture(value) { - this.setAperture(value); - } - /** - * Gets or sets the edge distortion - */ - get edgeDistortion() { - return this._distortion; - } - set edgeDistortion(value) { - this.setEdgeDistortion(value); - } - /** - * Gets or sets the depth of field distortion - */ - get dofDistortion() { - return this._dofDistance; - } - set dofDistortion(value) { - this.setFocusDistance(value); - } - /** - * Gets or sets the darken out of focus amount - */ - get darkenOutOfFocus() { - return this._dofDarken; - } - set darkenOutOfFocus(value) { - this.setDarkenOutOfFocus(value); - } - /** - * Gets or sets a boolean indicating if blur noise is enabled - */ - get blurNoise() { - return this._blurNoise; - } - set blurNoise(value) { - this._blurNoise = value; - } - /** - * Gets or sets a boolean indicating if pentagon bokeh is enabled - */ - get pentagonBokeh() { - return this._pentagonBokehIsEnabled; - } - set pentagonBokeh(value) { - if (value) { - this.enablePentagonBokeh(); - } - else { - this.disablePentagonBokeh(); - } - } - /** - * Gets or sets the highlight grain amount - */ - get highlightsGain() { - return this._highlightsGain; - } - set highlightsGain(value) { - this.setHighlightsGain(value); - } - /** - * Gets or sets the highlight threshold - */ - get highlightsThreshold() { - return this._highlightsThreshold; - } - set highlightsThreshold(value) { - this.setHighlightsThreshold(value); - } - // public methods (self explanatory) - /** - * Sets the amount of blur at the edges - * @param amount blur amount - */ - setEdgeBlur(amount) { - this._edgeBlur = amount; - } - /** - * Sets edge blur to 0 - */ - disableEdgeBlur() { - this._edgeBlur = 0; - } - /** - * Sets the amount of grain - * @param amount Amount of grain - */ - setGrainAmount(amount) { - this._grainAmount = amount; - } - /** - * Set grain amount to 0 - */ - disableGrain() { - this._grainAmount = 0; - } - /** - * Sets the chromatic aberration amount - * @param amount amount of chromatic aberration - */ - setChromaticAberration(amount) { - this._chromaticAberration = amount; - } - /** - * Sets chromatic aberration amount to 0 - */ - disableChromaticAberration() { - this._chromaticAberration = 0; - } - /** - * Sets the EdgeDistortion amount - * @param amount amount of EdgeDistortion - */ - setEdgeDistortion(amount) { - this._distortion = amount; - } - /** - * Sets edge distortion to 0 - */ - disableEdgeDistortion() { - this._distortion = 0; - } - /** - * Sets the FocusDistance amount - * @param amount amount of FocusDistance - */ - setFocusDistance(amount) { - this._dofDistance = amount; - } - /** - * Disables depth of field - */ - disableDepthOfField() { - this._dofDistance = -1; - } - /** - * Sets the Aperture amount - * @param amount amount of Aperture - */ - setAperture(amount) { - this._dofAperture = amount; - } - /** - * Sets the DarkenOutOfFocus amount - * @param amount amount of DarkenOutOfFocus - */ - setDarkenOutOfFocus(amount) { - this._dofDarken = amount; - } - /** - * Creates a pentagon bokeh effect - */ - enablePentagonBokeh() { - this._highlightsPostProcess.updateEffect("#define PENTAGON\n"); - this._pentagonBokehIsEnabled = true; - } - /** - * Disables the pentagon bokeh effect - */ - disablePentagonBokeh() { - this._pentagonBokehIsEnabled = false; - this._highlightsPostProcess.updateEffect(); - } - /** - * Enables noise blur - */ - enableNoiseBlur() { - this._blurNoise = true; - } - /** - * Disables noise blur - */ - disableNoiseBlur() { - this._blurNoise = false; - } - /** - * Sets the HighlightsGain amount - * @param amount amount of HighlightsGain - */ - setHighlightsGain(amount) { - this._highlightsGain = amount; - } - /** - * Sets the HighlightsThreshold amount - * @param amount amount of HighlightsThreshold - */ - setHighlightsThreshold(amount) { - if (this._highlightsGain === -1) { - this._highlightsGain = 1.0; - } - this._highlightsThreshold = amount; - } - /** - * Disables highlights - */ - disableHighlights() { - this._highlightsGain = -1; - } - /** - * Removes the internal pipeline assets and detaches the pipeline from the scene cameras - * @param disableDepthRender If the scene's depth rendering should be disabled (default: false) - */ - dispose(disableDepthRender = false) { - this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras); - this._chromaticAberrationPostProcess = null; - this._highlightsPostProcess = null; - this._depthOfFieldPostProcess = null; - this._grainTexture.dispose(); - if (disableDepthRender) { - this._scene.disableDepthRenderer(); - } - } - // colors shifting and distortion - _createChromaticAberrationPostProcess(ratio) { - this._chromaticAberrationPostProcess = new PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms - [], // samplers - ratio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false); - this._chromaticAberrationPostProcess.onApply = (effect) => { - effect.setFloat("chromatic_aberration", this._chromaticAberration); - effect.setFloat("screen_width", this._scene.getEngine().getRenderWidth()); - effect.setFloat("screen_height", this._scene.getEngine().getRenderHeight()); - effect.setFloat("radialIntensity", 1); - effect.setFloat2("direction", 17, 17); - effect.setFloat2("centerPosition", 0.5, 0.5); - }; - } - // highlights enhancing - _createHighlightsPostProcess(ratio) { - this._highlightsPostProcess = new PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms - [], // samplers - ratio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : ""); - this._highlightsPostProcess.externalTextureSamplerBinding = true; - this._highlightsPostProcess.onApply = (effect) => { - effect.setFloat("gain", this._highlightsGain); - effect.setFloat("threshold", this._highlightsThreshold); - effect.setTextureFromPostProcess("textureSampler", this._chromaticAberrationPostProcess); - effect.setFloat("screen_width", this._scene.getEngine().getRenderWidth()); - effect.setFloat("screen_height", this._scene.getEngine().getRenderHeight()); - }; - } - // colors shifting and distortion - _createDepthOfFieldPostProcess(ratio) { - this._depthOfFieldPostProcess = new PostProcess("LensDepthOfField", "depthOfField", [ - "grain_amount", - "blur_noise", - "screen_width", - "screen_height", - "distortion", - "dof_enabled", - "screen_distance", - "aperture", - "darken", - "edge_blur", - "highlights", - "near", - "far", - ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false); - this._depthOfFieldPostProcess.externalTextureSamplerBinding = true; - this._depthOfFieldPostProcess.onApply = (effect) => { - effect.setTexture("depthSampler", this._depthTexture); - effect.setTexture("grainSampler", this._grainTexture); - effect.setTextureFromPostProcess("textureSampler", this._highlightsPostProcess); - effect.setTextureFromPostProcess("highlightsSampler", this._depthOfFieldPostProcess); - effect.setFloat("grain_amount", this._grainAmount); - effect.setBool("blur_noise", this._blurNoise); - effect.setFloat("screen_width", this._scene.getEngine().getRenderWidth()); - effect.setFloat("screen_height", this._scene.getEngine().getRenderHeight()); - effect.setFloat("distortion", this._distortion); - effect.setBool("dof_enabled", this._dofDistance !== -1); - effect.setFloat("screen_distance", 1.0 / (0.1 - 1.0 / this._dofDistance)); - effect.setFloat("aperture", this._dofAperture); - effect.setFloat("darken", this._dofDarken); - effect.setFloat("edge_blur", this._edgeBlur); - effect.setBool("highlights", this._highlightsGain !== -1); - if (this._scene.activeCamera) { - effect.setFloat("near", this._scene.activeCamera.minZ); - effect.setFloat("far", this._scene.activeCamera.maxZ); - } - }; - } - // creates a black and white random noise texture, 512x512 - _createGrainTexture() { - const size = 512; - this._grainTexture = new DynamicTexture("LensNoiseTexture", size, this._scene, false, Texture.BILINEAR_SAMPLINGMODE); - this._grainTexture.wrapU = Texture.WRAP_ADDRESSMODE; - this._grainTexture.wrapV = Texture.WRAP_ADDRESSMODE; - const context = this._grainTexture.getContext(); - const rand = (min, max) => { - return Math.random() * (max - min) + min; - }; - let value; - for (let x = 0; x < size; x++) { - for (let y = 0; y < size; y++) { - value = Math.floor(rand(0.42, 0.58) * 255); - context.fillStyle = "rgb(" + value + ", " + value + ", " + value + ")"; - context.fillRect(x, y, 1, 1); - } - } - this._grainTexture.update(false); - } -} -//# sourceMappingURL=lensRenderingPipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/ssao2Configuration.js - -/** - * Contains all parameters needed for the prepass to perform - * screen space subsurface scattering - */ -class SSAO2Configuration { - constructor() { - /** - * Is subsurface enabled - */ - this.enabled = false; - /** - * Name of the configuration - */ - this.name = "ssao2"; - /** - * Textures that should be present in the MRT for this effect to work - */ - this.texturesRequired = [6, 5]; - } -} -//# sourceMappingURL=ssao2Configuration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ssao2.fragment.js -// Do not edit. - -const ssao2_fragment_name = "ssao2PixelShader"; -const ssao2_fragment_shader = `precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSAO -float scales[16]=float[16]( -0.1, -0.11406250000000001, -0.131640625, -0.15625, -0.187890625, -0.2265625, -0.272265625, -0.325, -0.384765625, -0.4515625, -0.525390625, -0.60625, -0.694140625, -0.7890625, -0.891015625, -1.0 -);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() -{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=depth/abs(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i<SAMPLES; ++i) {vec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];samplePosition=samplePosition*correctedRadius+origin;vec4 offset=vec4(samplePosition,1.0);offset=projection*offset;offset.xyz/=offset.w;offset.xy=offset.xy*0.5+0.5;if (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {continue;} -float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} -occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} -#endif -#ifdef BLUR -uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; -#ifndef BLUR_BYPASS -uniform sampler2D depthSampler; -#ifdef BLUR_LEGACY -#define inline -float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} -#endif -#endif -void main() -{float result=0.0; -#ifdef BLUR_BYPASS -result=textureLod(textureSampler,vUV,0.0).r; -#else -#ifdef BLUR_H -vec2 step=vec2(1.0/outSize,0.0); -#else -vec2 step=vec2(0.0,1.0/outSize); -#endif -#ifdef BLUR_LEGACY -result=blur13Bilateral(textureSampler,vUV,step); -#else -float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i<samples; i+=2) -{vec2 samplePos=vUV+step*(float(i)+0.5);float sampleDepth=abs(textureLod(depthSampler,samplePos,0.0).r);float falloff=smoothstep(0.0, -float(samples), -float(samples)-abs(float(i))*soften);float minDivider=tolerance*0.5+0.003;float weight=falloff/( minDivider+abs(compareDepth-sampleDepth));result+=textureLod(textureSampler,samplePos,0.0).r*weight;weightSum+=weight;} -result/=weightSum; -#endif -#endif -gl_FragColor.rgb=vec3(result);gl_FragColor.a=1.0;} -#endif -`; -// Sideeffect -ShaderStore.ShadersStore[ssao2_fragment_name] = ssao2_fragment_shader; -/** @internal */ -const ssao2PixelShader = { name: ssao2_fragment_name, shader: ssao2_fragment_shader }; -//# sourceMappingURL=ssao2.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ssaoCombine.fragment.js -// Do not edit. - -const ssaoCombine_fragment_name = "ssaoCombinePixelShader"; -const ssaoCombine_fragment_shader = `uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);vec4 sceneColor=texture2D(originalColor,vUV);gl_FragColor=sceneColor*ssaoColor; -#define CUSTOM_FRAGMENT_MAIN_END -} -`; -// Sideeffect -ShaderStore.ShadersStore[ssaoCombine_fragment_name] = ssaoCombine_fragment_shader; -/** @internal */ -const ssaoCombinePixelShader = { name: ssaoCombine_fragment_name, shader: ssaoCombine_fragment_shader }; -//# sourceMappingURL=ssaoCombine.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssao2RenderingPipeline.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - - - - - - - - - - -/** - * Render pipeline to produce ssao effect - */ -class SSAO2RenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline { - /** - * Used in SSAO calculations to compensate for accuracy issues with depth values. Default 0.02. - * - * Normally you do not need to change this value, but you can experiment with it if you get a lot of in false self-occlusion on flat surfaces when using fewer than 16 samples. Useful range is normally [0..0.1] but higher values is allowed. - */ - set epsilon(n) { - this._epsilon = n; - this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO()); - } - get epsilon() { - return this._epsilon; - } - /** - * Number of samples used for the SSAO calculations. Default value is 8. - */ - set samples(n) { - this._samples = n; - this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO()); - this._sampleSphere = this._generateHemisphere(); - } - get samples() { - return this._samples; - } - /** - * Number of samples to use for antialiasing. - */ - set textureSamples(n) { - this._textureSamples = n; - if (this._prePassRenderer) { - this._prePassRenderer.samples = n; - } - else { - this._originalColorPostProcess.samples = n; - } - } - get textureSamples() { - return this._textureSamples; - } - get _geometryBufferRenderer() { - if (!this._forceGeometryBuffer) { - return null; - } - return this._scene.geometryBufferRenderer; - } - get _prePassRenderer() { - if (this._forceGeometryBuffer) { - return null; - } - return this._scene.prePassRenderer; - } - /** - * Skips the denoising (blur) stage of the SSAO calculations. - * - * Useful to temporarily set while experimenting with the other SSAO2 settings. - */ - set bypassBlur(b) { - const defines = this._getDefinesForBlur(this.expensiveBlur, b); - const samplers = this._getSamplersForBlur(b); - this._blurHPostProcess.updateEffect(defines.h, null, samplers); - this._blurVPostProcess.updateEffect(defines.v, null, samplers); - this._bypassBlur = b; - } - get bypassBlur() { - return this._bypassBlur; - } - /** - * Enables the configurable bilateral denoising (blurring) filter. Default is true. - * Set to false to instead use a legacy bilateral filter that can't be configured. - * - * The denoising filter runs after the SSAO calculations and is a very important step. Both options results in a so called bilateral being used, but the "expensive" one can be - * configured in several ways to fit your scene. - */ - set expensiveBlur(b) { - const defines = this._getDefinesForBlur(b, this._bypassBlur); - this._blurHPostProcess.updateEffect(defines.h); - this._blurVPostProcess.updateEffect(defines.v); - this._expensiveBlur = b; - } - get expensiveBlur() { - return this._expensiveBlur; - } - /** - * Support test. - */ - static get IsSupported() { - const engine = engineStore_EngineStore.LastCreatedEngine; - if (!engine) { - return false; - } - return engine._features.supportSSAO2; - } - /** - * Gets active scene - */ - get scene() { - return this._scene; - } - /** - * @constructor - * @param name The rendering pipeline name - * @param scene The scene linked to this pipeline - * @param ratio The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 } - * @param cameras The array of cameras that the rendering pipeline will be attached to - * @param forceGeometryBuffer Set to true if you want to use the legacy geometry buffer renderer - * @param textureType The texture type used by the different post processes created by SSAO (default: 0) - */ - constructor(name, scene, ratio, cameras, forceGeometryBuffer = false, textureType = 0) { - super(scene.getEngine(), name); - // Members - /** - * @ignore - * The PassPostProcess id in the pipeline that contains the original scene color - */ - this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect"; - /** - * @ignore - * The SSAO PostProcess id in the pipeline - */ - this.SSAORenderEffect = "SSAORenderEffect"; - /** - * @ignore - * The horizontal blur PostProcess id in the pipeline - */ - this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect"; - /** - * @ignore - * The vertical blur PostProcess id in the pipeline - */ - this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect"; - /** - * @ignore - * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect) - */ - this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect"; - /** - * The output strength of the SSAO post-process. Default value is 1.0. - */ - this.totalStrength = 1.0; - /** - * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change. - */ - this.maxZ = 100.0; - /** - * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much. - */ - this.minZAspect = 0.2; - this._epsilon = 0.02; - this._samples = 8; - this._textureSamples = 1; - /** - * Force rendering the geometry through geometry buffer. - */ - this._forceGeometryBuffer = false; - /** - * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0 - */ - this.radius = 2.0; - /** - * The base color of the SSAO post-process - * The final result is "base + ssao" between [0, 1] - */ - this.base = 0; - this._bypassBlur = false; - this._expensiveBlur = true; - /** - * The number of samples the bilateral filter uses in both dimensions when denoising the SSAO calculations. Default value is 16. - * - * A higher value should result in smoother shadows but will use more processing time in the shaders. - * - * A high value can cause the shadows to get to blurry or create visible artifacts (bands) near sharp details in the geometry. The artifacts can sometimes be mitigated by increasing the bilateralSoften setting. - */ - this.bilateralSamples = 16; - /** - * Controls the shape of the denoising kernel used by the bilateral filter. Default value is 0. - * - * By default the bilateral filter acts like a box-filter, treating all samples on the same depth with equal weights. This is effective to maximize the denoising effect given a limited set of samples. However, it also often results in visible ghosting around sharp shadow regions and can spread out lines over large areas so they are no longer visible. - * - * Increasing this setting will make the filter pay less attention to samples further away from the center sample, reducing many artifacts but at the same time increasing noise. - * - * Useful value range is [0..1]. - */ - this.bilateralSoften = 0; - /** - * How forgiving the bilateral denoiser should be when rejecting samples. Default value is 0. - * - * A higher value results in the bilateral filter being more forgiving and thus doing a better job at denoising slanted and curved surfaces, but can lead to shadows spreading out around corners or between objects that are close to each other depth wise. - * - * Useful value range is normally [0..1], but higher values are allowed. - */ - this.bilateralTolerance = 0; - this._bits = new Uint32Array(1); - this._scene = scene; - this._ratio = ratio; - this._textureType = textureType; - this._forceGeometryBuffer = forceGeometryBuffer; - if (!this.isSupported) { - logger_Logger.Error("The current engine does not support SSAO 2."); - return; - } - const ssaoRatio = this._ratio.ssaoRatio || ratio; - const blurRatio = this._ratio.blurRatio || ratio; - // Set up assets - if (this._forceGeometryBuffer) { - scene.enableGeometryBufferRenderer(); - } - else { - scene.enablePrePassRenderer(); - } - this._createRandomTexture(); - this._originalColorPostProcess = new PassPostProcess("SSAOOriginalSceneColor", 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), undefined, this._textureType); - this._originalColorPostProcess.samples = this.textureSamples; - this._createSSAOPostProcess(1.0, textureType); - this._createBlurPostProcess(ssaoRatio, blurRatio, this._textureType); - this._createSSAOCombinePostProcess(blurRatio, this._textureType); - // Set up pipeline - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, () => { - return this._originalColorPostProcess; - }, true)); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => { - return this._ssaoPostProcess; - }, true)); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => { - return this._blurHPostProcess; - }, true)); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => { - return this._blurVPostProcess; - }, true)); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => { - return this._ssaoCombinePostProcess; - }, true)); - // Finish - scene.postProcessRenderPipelineManager.addPipeline(this); - if (cameras) { - scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras); - } - } - // Public Methods - /** - * Get the class name - * @returns "SSAO2RenderingPipeline" - */ - getClassName() { - return "SSAO2RenderingPipeline"; - } - /** - * Removes the internal pipeline assets and detaches the pipeline from the scene cameras - * @param disableGeometryBufferRenderer - */ - dispose(disableGeometryBufferRenderer = false) { - for (let i = 0; i < this._scene.cameras.length; i++) { - const camera = this._scene.cameras[i]; - this._originalColorPostProcess.dispose(camera); - this._ssaoPostProcess.dispose(camera); - this._blurHPostProcess.dispose(camera); - this._blurVPostProcess.dispose(camera); - this._ssaoCombinePostProcess.dispose(camera); - } - this._randomTexture.dispose(); - if (disableGeometryBufferRenderer) { - this._scene.disableGeometryBufferRenderer(); - } - this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras); - super.dispose(); - } - // Private Methods - /** @internal */ - _rebuild() { - super._rebuild(); - } - _getSamplersForBlur(disabled) { - return disabled ? ["textureSampler"] : ["textureSampler", "depthSampler"]; - } - _getDefinesForBlur(bilateral, disabled) { - let define = "#define BLUR\n"; - if (disabled) { - define += "#define BLUR_BYPASS\n"; - } - if (!bilateral) { - define += "#define BLUR_LEGACY\n"; - } - return { h: define + "#define BLUR_H\n", v: define }; - } - _createBlurPostProcess(ssaoRatio, blurRatio, textureType) { - const defines = this._getDefinesForBlur(this.expensiveBlur, this.bypassBlur); - const samplers = this._getSamplersForBlur(this.bypassBlur); - this._blurHPostProcess = this._createBlurFilter("BlurH", samplers, ssaoRatio, defines.h, textureType, true); - this._blurVPostProcess = this._createBlurFilter("BlurV", samplers, blurRatio, defines.v, textureType, false); - } - _createBlurFilter(name, samplers, ratio, defines, textureType, horizontal) { - const blurFilter = new postProcess_PostProcess(name, "ssao2", ["outSize", "samples", "soften", "tolerance"], samplers, ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, defines, textureType); - blurFilter.onApply = (effect) => { - if (!this._scene.activeCamera) { - return; - } - const ssaoCombineSize = horizontal ? this._ssaoCombinePostProcess.width : this._ssaoCombinePostProcess.height; - const originalColorSize = horizontal ? this._originalColorPostProcess.width : this._originalColorPostProcess.height; - effect.setFloat("outSize", ssaoCombineSize > 0 ? ssaoCombineSize : originalColorSize); - effect.setInt("samples", this.bilateralSamples); - effect.setFloat("soften", this.bilateralSoften); - effect.setFloat("tolerance", this.bilateralTolerance); - if (this._geometryBufferRenderer) { - effect.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[0]); - } - else if (this._prePassRenderer) { - effect.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]); - } - }; - blurFilter.samples = this.textureSamples; - return blurFilter; - } - //Van der Corput radical inverse - _radicalInverse_VdC(i) { - this._bits[0] = i; - this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0; - this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | (((this._bits[0] & 0xaaaaaaaa) >>> 1) >>> 0); - this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | (((this._bits[0] & 0xcccccccc) >>> 2) >>> 0); - this._bits[0] = ((this._bits[0] & 0x0f0f0f0f) << 4) | (((this._bits[0] & 0xf0f0f0f0) >>> 4) >>> 0); - this._bits[0] = ((this._bits[0] & 0x00ff00ff) << 8) | (((this._bits[0] & 0xff00ff00) >>> 8) >>> 0); - return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296 - } - _hammersley(i, n) { - return [i / n, this._radicalInverse_VdC(i)]; - } - _hemisphereSample_uniform(u, v) { - const phi = v * 2.0 * Math.PI; - // rejecting samples that are close to tangent plane to avoid z-fighting artifacts - const cosTheta = 1.0 - u * 0.85; - const sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta); - return new math_vector_Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta); - } - _generateHemisphere() { - const numSamples = this.samples; - const result = []; - let vector; - let i = 0; - while (i < numSamples) { - if (numSamples < 16) { - vector = this._hemisphereSample_uniform(Math.random(), Math.random()); - } - else { - const rand = this._hammersley(i, numSamples); - vector = this._hemisphereSample_uniform(rand[0], rand[1]); - } - result.push(vector.x, vector.y, vector.z); - i++; - } - return result; - } - _getDefinesForSSAO() { - const defines = `#define SSAO\n#define SAMPLES ${this.samples}\n#define EPSILON ${this.epsilon.toFixed(4)}`; - return defines; - } - _createSSAOPostProcess(ratio, textureType) { - this._sampleSphere = this._generateHemisphere(); - const defines = this._getDefinesForSSAO(); - const samplers = ["randomSampler", "depthSampler", "normalSampler"]; - this._ssaoPostProcess = new postProcess_PostProcess("ssao2", "ssao2", [ - "sampleSphere", - "samplesFactor", - "randTextureTiles", - "totalStrength", - "radius", - "base", - "range", - "projection", - "near", - "texelSize", - "xViewport", - "yViewport", - "maxZ", - "minZAspect", - "depthProjection", - ], samplers, ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, defines, textureType); - this._ssaoPostProcess.onApply = (effect) => { - var _a, _b, _c, _d; - if (!this._scene.activeCamera) { - return; - } - effect.setArray3("sampleSphere", this._sampleSphere); - effect.setFloat("randTextureTiles", 32.0); - effect.setFloat("samplesFactor", 1 / this.samples); - effect.setFloat("totalStrength", this.totalStrength); - effect.setFloat2("texelSize", 1 / this._ssaoPostProcess.width, 1 / this._ssaoPostProcess.height); - effect.setFloat("radius", this.radius); - effect.setFloat("maxZ", this.maxZ); - effect.setFloat("minZAspect", this.minZAspect); - effect.setFloat("base", this.base); - effect.setFloat("near", this._scene.activeCamera.minZ); - if (this._scene.activeCamera.mode === camera_Camera.PERSPECTIVE_CAMERA) { - effect.setMatrix3x3("depthProjection", SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION); - effect.setFloat("xViewport", Math.tan(this._scene.activeCamera.fov / 2) * this._scene.getEngine().getAspectRatio(this._scene.activeCamera, true)); - effect.setFloat("yViewport", Math.tan(this._scene.activeCamera.fov / 2)); - } - else { - const halfWidth = this._scene.getEngine().getRenderWidth() / 2.0; - const halfHeight = this._scene.getEngine().getRenderHeight() / 2.0; - const orthoLeft = (_a = this._scene.activeCamera.orthoLeft) !== null && _a !== void 0 ? _a : -halfWidth; - const orthoRight = (_b = this._scene.activeCamera.orthoRight) !== null && _b !== void 0 ? _b : halfWidth; - const orthoBottom = (_c = this._scene.activeCamera.orthoBottom) !== null && _c !== void 0 ? _c : -halfHeight; - const orthoTop = (_d = this._scene.activeCamera.orthoTop) !== null && _d !== void 0 ? _d : halfHeight; - effect.setMatrix3x3("depthProjection", SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION); - effect.setFloat("xViewport", (orthoRight - orthoLeft) * 0.5); - effect.setFloat("yViewport", (orthoTop - orthoBottom) * 0.5); - } - effect.setMatrix("projection", this._scene.getProjectionMatrix()); - if (this._geometryBufferRenderer) { - effect.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[0]); - effect.setTexture("normalSampler", this._geometryBufferRenderer.getGBuffer().textures[1]); - } - else if (this._prePassRenderer) { - effect.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]); - effect.setTexture("normalSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)]); - } - effect.setTexture("randomSampler", this._randomTexture); - }; - this._ssaoPostProcess.samples = this.textureSamples; - if (!this._forceGeometryBuffer) { - this._ssaoPostProcess._prePassEffectConfiguration = new SSAO2Configuration(); - } - } - _createSSAOCombinePostProcess(ratio, textureType) { - this._ssaoCombinePostProcess = new postProcess_PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, undefined, textureType); - this._ssaoCombinePostProcess.onApply = (effect) => { - const viewport = this._scene.activeCamera.viewport; - effect.setVector4("viewport", math_vector_TmpVectors.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height)); - effect.setTextureFromPostProcessOutput("originalColor", this._originalColorPostProcess); - }; - this._ssaoCombinePostProcess.samples = this.textureSamples; - } - _createRandomTexture() { - const size = 128; - this._randomTexture = new dynamicTexture_DynamicTexture("SSAORandomTexture", size, this._scene, false, texture_Texture.BILINEAR_SAMPLINGMODE); - this._randomTexture.wrapU = texture_Texture.WRAP_ADDRESSMODE; - this._randomTexture.wrapV = texture_Texture.WRAP_ADDRESSMODE; - const context = this._randomTexture.getContext(); - const rand = (min, max) => { - return Math.random() * (max - min) + min; - }; - const randVector = math_vector_Vector3.Zero(); - for (let x = 0; x < size; x++) { - for (let y = 0; y < size; y++) { - randVector.x = rand(0.0, 1.0); - randVector.y = rand(0.0, 1.0); - randVector.z = 0.0; - randVector.normalize(); - randVector.scaleInPlace(255); - randVector.x = Math.floor(randVector.x); - randVector.y = Math.floor(randVector.y); - context.fillStyle = "rgb(" + randVector.x + ", " + randVector.y + ", " + randVector.z + ")"; - context.fillRect(x, y, 1, 1); - } - } - this._randomTexture.update(false); - } - /** - * Serialize the rendering pipeline (Used when exporting) - * @returns the serialized object - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.customType = "SSAO2RenderingPipeline"; - return serializationObject; - } - /** - * Parse the serialized pipeline - * @param source Source pipeline. - * @param scene The scene to load the pipeline to. - * @param rootUrl The URL of the serialized pipeline. - * @returns An instantiated pipeline from the serialized object. - */ - static Parse(source, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => new SSAO2RenderingPipeline(source._name, scene, source._ratio, undefined, source._forceGeometryBuffer, source._textureType), source, scene, rootUrl); - } -} -SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION = [1, 0, 0, 0, 1, 0, 0, 0, 1]; -SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION = [0, 0, 0, 0, 0, 0, 1, 1, 1]; -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "totalStrength", void 0); -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "maxZ", void 0); -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "minZAspect", void 0); -__decorate([ - serialize("epsilon") -], SSAO2RenderingPipeline.prototype, "_epsilon", void 0); -__decorate([ - serialize("samples") -], SSAO2RenderingPipeline.prototype, "_samples", void 0); -__decorate([ - serialize("textureSamples") -], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0); -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "_forceGeometryBuffer", void 0); -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "_ratio", void 0); -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "_textureType", void 0); -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "radius", void 0); -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "base", void 0); -__decorate([ - serialize("bypassBlur") -], SSAO2RenderingPipeline.prototype, "_bypassBlur", void 0); -__decorate([ - serialize("expensiveBlur") -], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0); -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "bilateralSamples", void 0); -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "bilateralSoften", void 0); -__decorate([ - serialize() -], SSAO2RenderingPipeline.prototype, "bilateralTolerance", void 0); -RegisterClass("BABYLON.SSAO2RenderingPipeline", SSAO2RenderingPipeline); -//# sourceMappingURL=ssao2RenderingPipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ssao.fragment.js -// Do not edit. - -const ssao_fragment_name = "ssaoPixelShader"; -const ssao_fragment_shader = `uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSAO -uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) -{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} -void main() -{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; i<SAMPLES; i++) -{ray=radiusDepth*reflect(sampleSphere[i],random);hemiRay=position+sign(dot(ray,normal))*ray;occlusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;difference=depth-occlusionDepth;occlusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));} -float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor.r=result;gl_FragColor.g=result;gl_FragColor.b=result;gl_FragColor.a=1.0;} -#endif -`; -// Sideeffect -ShaderStore.ShadersStore[ssao_fragment_name] = ssao_fragment_shader; -/** @internal */ -const ssaoPixelShader = { name: ssao_fragment_name, shader: ssao_fragment_shader }; -//# sourceMappingURL=ssao.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssaoRenderingPipeline.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - - - - - - -/** - * Render pipeline to produce ssao effect - */ -class SSAORenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline { - /** - * Gets active scene - */ - get scene() { - return this._scene; - } - /** - * @constructor - * @param name - The rendering pipeline name - * @param scene - The scene linked to this pipeline - * @param ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 } - * @param cameras - The array of cameras that the rendering pipeline will be attached to - */ - constructor(name, scene, ratio, cameras) { - super(scene.getEngine(), name); - // Members - /** - * @ignore - * The PassPostProcess id in the pipeline that contains the original scene color - */ - this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect"; - /** - * @ignore - * The SSAO PostProcess id in the pipeline - */ - this.SSAORenderEffect = "SSAORenderEffect"; - /** - * @ignore - * The horizontal blur PostProcess id in the pipeline - */ - this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect"; - /** - * @ignore - * The vertical blur PostProcess id in the pipeline - */ - this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect"; - /** - * @ignore - * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect) - */ - this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect"; - /** - * The output strength of the SSAO post-process. Default value is 1.0. - */ - this.totalStrength = 1.0; - /** - * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006 - */ - this.radius = 0.0001; - /** - * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel - * Must not be equal to fallOff and superior to fallOff. - * Default value is 0.0075 - */ - this.area = 0.0075; - /** - * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel - * Must not be equal to area and inferior to area. - * Default value is 0.000001 - */ - this.fallOff = 0.000001; - /** - * The base color of the SSAO post-process - * The final result is "base + ssao" between [0, 1] - */ - this.base = 0.5; - this._firstUpdate = true; - this._scene = scene; - // Set up assets - this._createRandomTexture(); - const ssaoRatio = ratio.ssaoRatio || ratio; - const combineRatio = ratio.combineRatio || ratio; - this._originalColorPostProcess = new PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false); - this._createSSAOPostProcess(ssaoRatio); - this._createBlurPostProcess(ssaoRatio); - this._createSSAOCombinePostProcess(combineRatio); - // Set up pipeline - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, () => { - return this._originalColorPostProcess; - }, true)); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => { - return this._ssaoPostProcess; - }, true)); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => { - return this._blurHPostProcess; - }, true)); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => { - return this._blurVPostProcess; - }, true)); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => { - return this._ssaoCombinePostProcess; - }, true)); - // Finish - scene.postProcessRenderPipelineManager.addPipeline(this); - if (cameras) { - scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras); - } - } - /** - * @internal - */ - _attachCameras(cameras, unique) { - super._attachCameras(cameras, unique); - for (const camera of this._cameras) { - this._scene.enableDepthRenderer(camera).getDepthMap(); // Force depth renderer "on" - } - } - // Public Methods - /** - * Get the class name - * @returns "SSAORenderingPipeline" - */ - getClassName() { - return "SSAORenderingPipeline"; - } - /** - * Removes the internal pipeline assets and detaches the pipeline from the scene cameras - * @param disableDepthRender - */ - dispose(disableDepthRender = false) { - for (let i = 0; i < this._scene.cameras.length; i++) { - const camera = this._scene.cameras[i]; - this._originalColorPostProcess.dispose(camera); - this._ssaoPostProcess.dispose(camera); - this._blurHPostProcess.dispose(camera); - this._blurVPostProcess.dispose(camera); - this._ssaoCombinePostProcess.dispose(camera); - } - this._randomTexture.dispose(); - if (disableDepthRender) { - this._scene.disableDepthRenderer(); - } - this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras); - super.dispose(); - } - // Private Methods - _createBlurPostProcess(ratio) { - const size = 16; - this._blurHPostProcess = new BlurPostProcess("BlurH", new math_vector_Vector2(1, 0), size, ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, 0); - this._blurVPostProcess = new BlurPostProcess("BlurV", new math_vector_Vector2(0, 1), size, ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, 0); - this._blurHPostProcess.onActivateObservable.add(() => { - const dw = this._blurHPostProcess.width / this._scene.getEngine().getRenderWidth(); - this._blurHPostProcess.kernel = size * dw; - }); - this._blurVPostProcess.onActivateObservable.add(() => { - const dw = this._blurVPostProcess.height / this._scene.getEngine().getRenderHeight(); - this._blurVPostProcess.kernel = size * dw; - }); - } - /** @internal */ - _rebuild() { - this._firstUpdate = true; - super._rebuild(); - } - _createSSAOPostProcess(ratio) { - const numSamples = 16; - const sampleSphere = [ - 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, - 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, - 0.0596, -0.5411, 0.0352, -0.0631, 0.546, -0.4776, 0.2847, -0.0271, - ]; - const samplesFactor = 1.0 / numSamples; - this._ssaoPostProcess = new postProcess_PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff", "base", "range", "viewport"], ["randomSampler"], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO"); - this._ssaoPostProcess.externalTextureSamplerBinding = true; - this._ssaoPostProcess.onApply = (effect) => { - if (this._firstUpdate) { - effect.setArray3("sampleSphere", sampleSphere); - effect.setFloat("samplesFactor", samplesFactor); - effect.setFloat("randTextureTiles", 4.0); - } - effect.setFloat("totalStrength", this.totalStrength); - effect.setFloat("radius", this.radius); - effect.setFloat("area", this.area); - effect.setFloat("fallOff", this.fallOff); - effect.setFloat("base", this.base); - effect.setTexture("textureSampler", this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()); - effect.setTexture("randomSampler", this._randomTexture); - }; - } - _createSSAOCombinePostProcess(ratio) { - this._ssaoCombinePostProcess = new postProcess_PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false); - this._ssaoCombinePostProcess.onApply = (effect) => { - effect.setVector4("viewport", math_vector_TmpVectors.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0)); - effect.setTextureFromPostProcess("originalColor", this._originalColorPostProcess); - }; - } - _createRandomTexture() { - const size = 512; - this._randomTexture = new dynamicTexture_DynamicTexture("SSAORandomTexture", size, this._scene, false, texture_Texture.TRILINEAR_SAMPLINGMODE); - this._randomTexture.wrapU = texture_Texture.WRAP_ADDRESSMODE; - this._randomTexture.wrapV = texture_Texture.WRAP_ADDRESSMODE; - const context = this._randomTexture.getContext(); - const rand = (min, max) => { - return Math.random() * (max - min) + min; - }; - const randVector = math_vector_Vector3.Zero(); - for (let x = 0; x < size; x++) { - for (let y = 0; y < size; y++) { - randVector.x = Math.floor(Math.max(0.0, rand(-1.0, 1.0)) * 255); - randVector.y = Math.floor(Math.max(0.0, rand(-1.0, 1.0)) * 255); - randVector.z = Math.floor(Math.max(0.0, rand(-1.0, 1.0)) * 255); - context.fillStyle = "rgb(" + randVector.x + ", " + randVector.y + ", " + randVector.z + ")"; - context.fillRect(x, y, 1, 1); - } - } - this._randomTexture.update(false); - } -} -__decorate([ - serialize() -], SSAORenderingPipeline.prototype, "totalStrength", void 0); -__decorate([ - serialize() -], SSAORenderingPipeline.prototype, "radius", void 0); -__decorate([ - serialize() -], SSAORenderingPipeline.prototype, "area", void 0); -__decorate([ - serialize() -], SSAORenderingPipeline.prototype, "fallOff", void 0); -__decorate([ - serialize() -], SSAORenderingPipeline.prototype, "base", void 0); -//# sourceMappingURL=ssaoRenderingPipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/screenSpaceReflectionsConfiguration.js - -/** - * Contains all parameters needed for the prepass to perform - * screen space reflections - */ -class ScreenSpaceReflectionsConfiguration { - constructor() { - /** - * Is ssr enabled - */ - this.enabled = false; - /** - * Name of the configuration - */ - this.name = "screenSpaceReflections"; - /** - * Textures that should be present in the MRT for this effect to work - */ - this.texturesRequired = [6, 3, 1]; - } -} -//# sourceMappingURL=screenSpaceReflectionsConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/screenSpaceReflection.fragment.js -// Do not edit. - -const screenSpaceReflection_fragment_name = "screenSpaceReflectionPixelShader"; -const screenSpaceReflection_fragment_shader = `uniform sampler2D textureSampler; -#ifdef SSR_SUPPORTED -uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler; -#endif -uniform mat4 view;uniform mat4 projection;uniform float stepSize;uniform float strength;uniform float threshold;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;varying vec2 vUV; -#ifdef SSR_SUPPORTED -struct ReflectionInfo {vec3 color;vec4 coords;};/** -* According to specular,see https: -*/ -vec3 fresnelSchlick(float cosTheta,vec3 F0) -{return F0+(1.0-F0)*pow(1.0-cosTheta,5.0);} -/** -* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit -* by sampling multiple reflection pixels. -*/ -ReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord) -{ReflectionInfo info;info.color=vec3(0.0);vec4 projectedCoord;float sampledDepth;for(int i=0; i<SMOOTH_STEPS; i++) -{projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z;dir*=0.5;if(depth>0.0) -hitCoord-=dir;else -hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} -projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} -/** -* Tests the given world position (hitCoord) according to the given reflection vector (dir) -* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). -*/ -ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) -{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i<REFLECTION_SAMPLES; i++) -{hitCoord+=dir;projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z; -#ifdef RIGHT_HANDED_SCENE -depth*=-1.0; -#endif -if(((depth-dir.z)<threshold) && depth<=0.0) -{ -#ifdef ENABLE_SMOOTH_REFLECTIONS -return smoothReflectionInfo(dir,hitCoord); -#else -info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info; -#endif -}} -info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info;} -vec3 hash(vec3 a) -{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} -#endif -void main() -{ -#ifdef SSR_SUPPORTED -vec4 albedoFull=texture2D(textureSampler,vUV);vec3 albedo=albedoFull.rgb;float spec=texture2D(reflectivitySampler,vUV).r;if (spec==0.0) {gl_FragColor=albedoFull;return;} -vec3 normal=(texture2D(normalSampler,vUV)).xyz;vec3 position=(view*texture2D(positionSampler,vUV)).xyz;vec3 reflected=normalize(reflect(normalize(position),normalize(normal)));float roughness=1.0-texture2D(reflectivitySampler,vUV).a;vec3 jitt=mix(vec3(0.0),hash(position),roughness)*roughnessFactor;ReflectionInfo info=getReflectionInfo(jitt+reflected,position);vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-info.coords.xy));float screenEdgefactor=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);vec3 F0=vec3(0.04);F0 =mix(F0,albedo,spec);vec3 fresnel=fresnelSchlick(max(dot(normalize(normal),normalize(position)),0.0),F0); -#ifdef RIGHT_HANDED_SCENE -reflected.z*=-1.0; -#endif -float reflectionMultiplier=clamp(pow(spec*strength,reflectionSpecularFalloffExponent)*screenEdgefactor*reflected.z,0.0,0.9);float albedoMultiplier=1.0-reflectionMultiplier;vec3 SSR=info.color*fresnel;gl_FragColor=vec4((albedo*albedoMultiplier)+(SSR*reflectionMultiplier),albedoFull.a); -#else -gl_FragColor=texture2D(textureSampler,vUV); -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[screenSpaceReflection_fragment_name] = screenSpaceReflection_fragment_shader; -/** @internal */ -const screenSpaceReflectionPixelShader = { name: screenSpaceReflection_fragment_name, shader: screenSpaceReflection_fragment_shader }; -//# sourceMappingURL=screenSpaceReflection.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/screenSpaceReflectionPostProcess.js - - - - - - - - -/** - * The ScreenSpaceReflectionPostProcess performs realtime reflections using only and only the available informations on the screen (positions and normals). - * Basically, the screen space reflection post-process will compute reflections according the material's reflectivity. - * @deprecated Use the new SSRRenderingPipeline instead. - */ -class ScreenSpaceReflectionPostProcess extends postProcess_PostProcess { - get _geometryBufferRenderer() { - if (!this._forceGeometryBuffer) { - return null; - } - return this._scene.geometryBufferRenderer; - } - get _prePassRenderer() { - if (this._forceGeometryBuffer) { - return null; - } - return this._scene.prePassRenderer; - } - /** - * Gets a string identifying the name of the class - * @returns "ScreenSpaceReflectionPostProcess" string - */ - getClassName() { - return "ScreenSpaceReflectionPostProcess"; - } - /** - * Creates a new instance of ScreenSpaceReflectionPostProcess. - * @param name The name of the effect. - * @param scene The scene containing the objects to calculate reflections. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @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) - * @param forceGeometryBuffer If this post process should use geometry buffer instead of prepass (default: false) - */ - constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false, forceGeometryBuffer = false) { - 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); - /** - * Gets or sets a reflection threshold mainly used to adjust the reflection's height. - */ - this.threshold = 1.2; - /** - * Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results. - */ - this.strength = 1; - /** - * Gets or sets the falloff exponent used while computing fresnel. More the exponent is high, more the reflections will be discrete. - */ - this.reflectionSpecularFalloffExponent = 3; - /** - * 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] - */ - this.step = 1.0; - /** - * Gets or sets the factor applied when computing roughness. Default value is 0.2. - */ - this.roughnessFactor = 0.2; - this._forceGeometryBuffer = false; - this._enableSmoothReflections = false; - this._reflectionSamples = 64; - this._smoothSteps = 5; - this._forceGeometryBuffer = forceGeometryBuffer; - if (this._forceGeometryBuffer) { - // Get geometry buffer renderer and update effect - const geometryBufferRenderer = scene.enableGeometryBufferRenderer(); - if (geometryBufferRenderer) { - if (geometryBufferRenderer.isSupported) { - geometryBufferRenderer.enablePosition = true; - geometryBufferRenderer.enableReflectivity = true; - } - } - } - else { - const prePassRenderer = scene.enablePrePassRenderer(); - prePassRenderer === null || prePassRenderer === void 0 ? void 0 : prePassRenderer.markAsDirty(); - this._prePassEffectConfiguration = new ScreenSpaceReflectionsConfiguration(); - } - this._updateEffectDefines(); - // On apply, send uniforms - this.onApply = (effect) => { - const geometryBufferRenderer = this._geometryBufferRenderer; - const prePassRenderer = this._prePassRenderer; - if (!prePassRenderer && !geometryBufferRenderer) { - return; - } - if (geometryBufferRenderer) { - // Samplers - const positionIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.POSITION_TEXTURE_TYPE); - const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE); - effect.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[1]); - effect.setTexture("positionSampler", geometryBufferRenderer.getGBuffer().textures[positionIndex]); - effect.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]); - } - else if (prePassRenderer) { - // Samplers - const positionIndex = prePassRenderer.getIndex(1); - const roughnessIndex = prePassRenderer.getIndex(3); - const normalIndex = prePassRenderer.getIndex(6); - effect.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]); - effect.setTexture("positionSampler", prePassRenderer.getRenderTarget().textures[positionIndex]); - effect.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]); - } - // Uniforms - const camera = scene.activeCamera; - if (!camera) { - return; - } - const viewMatrix = camera.getViewMatrix(true); - const projectionMatrix = camera.getProjectionMatrix(true); - effect.setMatrix("projection", projectionMatrix); - effect.setMatrix("view", viewMatrix); - effect.setFloat("threshold", this.threshold); - effect.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent); - effect.setFloat("strength", this.strength); - effect.setFloat("stepSize", this.step); - effect.setFloat("roughnessFactor", this.roughnessFactor); - }; - this._isSceneRightHanded = scene.useRightHandedSystem; - } - /** - * Gets whether or not smoothing reflections is enabled. - * Enabling smoothing will require more GPU power and can generate a drop in FPS. - */ - get enableSmoothReflections() { - return this._enableSmoothReflections; - } - /** - * Sets whether or not smoothing reflections is enabled. - * Enabling smoothing will require more GPU power and can generate a drop in FPS. - */ - set enableSmoothReflections(enabled) { - if (enabled === this._enableSmoothReflections) { - return; - } - this._enableSmoothReflections = enabled; - this._updateEffectDefines(); - } - /** - * Gets the number of samples taken while computing reflections. More samples count is high, - * more the post-process wil require GPU power and can generate a drop in FPS. Basically in interval [25, 100]. - */ - get reflectionSamples() { - return this._reflectionSamples; - } - /** - * Sets the number of samples taken while computing reflections. More samples count is high, - * more the post-process wil require GPU power and can generate a drop in FPS. Basically in interval [25, 100]. - */ - set reflectionSamples(samples) { - if (samples === this._reflectionSamples) { - return; - } - this._reflectionSamples = samples; - this._updateEffectDefines(); - } - /** - * Gets the number of samples taken while smoothing reflections. More samples count is high, - * more the post-process will require GPU power and can generate a drop in FPS. - * Default value (5.0) work pretty well in all cases but can be adjusted. - */ - get smoothSteps() { - return this._smoothSteps; - } - /* - * Sets the number of samples taken while smoothing reflections. More samples count is high, - * more the post-process will require GPU power and can generate a drop in FPS. - * Default value (5.0) work pretty well in all cases but can be adjusted. - */ - set smoothSteps(steps) { - if (steps === this._smoothSteps) { - return; - } - this._smoothSteps = steps; - this._updateEffectDefines(); - } - _updateEffectDefines() { - const defines = []; - if (this._geometryBufferRenderer || this._prePassRenderer) { - defines.push("#define SSR_SUPPORTED"); - } - if (this._enableSmoothReflections) { - defines.push("#define ENABLE_SMOOTH_REFLECTIONS"); - } - if (this._isSceneRightHanded) { - defines.push("#define RIGHT_HANDED_SCENE"); - } - defines.push("#define REFLECTION_SAMPLES " + (this._reflectionSamples >> 0)); - defines.push("#define SMOOTH_STEPS " + (this._smoothSteps >> 0)); - this.updateEffect(defines.join("\n")); - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new ScreenSpaceReflectionPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serialize() -], ScreenSpaceReflectionPostProcess.prototype, "threshold", void 0); -__decorate([ - serialize() -], ScreenSpaceReflectionPostProcess.prototype, "strength", void 0); -__decorate([ - serialize() -], ScreenSpaceReflectionPostProcess.prototype, "reflectionSpecularFalloffExponent", void 0); -__decorate([ - serialize() -], ScreenSpaceReflectionPostProcess.prototype, "step", void 0); -__decorate([ - serialize() -], ScreenSpaceReflectionPostProcess.prototype, "roughnessFactor", void 0); -__decorate([ - serialize() -], ScreenSpaceReflectionPostProcess.prototype, "enableSmoothReflections", null); -__decorate([ - serialize() -], ScreenSpaceReflectionPostProcess.prototype, "reflectionSamples", null); -__decorate([ - serialize() -], ScreenSpaceReflectionPostProcess.prototype, "smoothSteps", null); -RegisterClass("BABYLON.ScreenSpaceReflectionPostProcess", ScreenSpaceReflectionPostProcess); -//# sourceMappingURL=screenSpaceReflectionPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/standard.fragment.js -// Do not edit. - - -const standard_fragment_name = "standardPixelShader"; -const standard_fragment_shader = `uniform sampler2D textureSampler;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -#if defined(PASS_POST_PROCESS) -void main(void) -{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} -#endif -#if defined(DOWN_SAMPLE_X4) -uniform vec2 dsOffsets[16];void main(void) -{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} -#endif -#if defined(BRIGHT_PASS) -uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) -{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminance<brightThreshold) {average=vec4(0.0,0.0,0.0,1.0);} -gl_FragColor=average;} -#endif -#if defined(TEXTURE_ADDER) -uniform sampler2D otherSampler;uniform sampler2D lensSampler;uniform float exposure;void main(void) -{vec3 colour=texture2D(textureSampler,vUV).rgb;colour*=exposure;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;colour+=colour*texture2D(lensSampler,vUV).rgb;vec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);gl_FragColor=finalColor;} -#endif -#if defined(VLS) -#define PI 3.1415926535897932384626433832795 -uniform mat4 shadowViewProjection;uniform mat4 lightWorld;uniform vec3 cameraPosition;uniform vec3 sunDirection;uniform vec3 sunColor;uniform vec2 depthValues;uniform float scatteringCoefficient;uniform float scatteringPower;uniform sampler2D shadowMapSampler;uniform sampler2D positionSampler;float computeScattering(float lightDotView) -{float result=1.0-scatteringCoefficient*scatteringCoefficient;result/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));return result;} -void main(void) -{vec3 worldPos=texture2D(positionSampler,vUV).rgb;vec3 startPosition=cameraPosition;vec3 rayVector=worldPos-startPosition;float rayLength=length(rayVector);vec3 rayDirection=rayVector/rayLength;float stepLength=rayLength/NB_STEPS;vec3 stepL=rayDirection*stepLength;vec3 currentPosition=startPosition;vec3 accumFog=vec3(0.0);for (int i=0; i<int(NB_STEPS); i++) -{vec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);float depthMetric= (worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depthMetric,0.0,1.0);worldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;worldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);float shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;if (shadowMapValue>shadowPixelDepth) -accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} -accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} -#endif -#if defined(VLSMERGE) -uniform sampler2D originalSampler;void main(void) -{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} -#endif -#if defined(LUMINANCE) -uniform vec2 lumOffsets[4];void main() -{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) -{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); -#ifdef WEIGHTED_AVERAGE -float GreyValue=dot(color.rgb,weight); -#endif -#ifdef BRIGHTNESS -float GreyValue=max(color.r,max(color.g,color.b)); -#endif -#ifdef HSL_COMPONENT -float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); -#endif -#ifdef MAGNITUDE -float GreyValue=length(color.rgb); -#endif -maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} -average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} -#endif -#if defined(LUMINANCE_DOWN_SAMPLE) -uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; -#ifdef FINAL_DOWN_SAMPLER -#include<packingFunctions> -#endif -void main() -{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) -{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} -average/=9.0; -#ifdef FINAL_DOWN_SAMPLER -gl_FragColor=pack(average); -#else -gl_FragColor=vec4(average,average,0.0,1.0); -#endif -} -#endif -#if defined(HDR) -uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() -{vec4 color=texture2D(textureAdderSampler,vUV); -#ifndef AUTO_EXPOSURE -vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; -#endif -gl_FragColor=color;} -#endif -#if defined(LENS_FLARE) -#define GHOSTS 3 -uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) -{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} -float noise(in vec2 p) -{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), -hash(i+vec2(1.0,0.0)),u.x), -mix(hash(i+vec2(0.0,1.0)), -hash(i+vec2(1.0,1.0)),u.x),u.y);} -float fbm(vec2 p) -{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} -vec3 pattern(vec2 uv) -{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} -float luminance(vec3 color) -{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} -vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) -{return vec4( -texture2D(tex,texcoord+direction*distortion.r).r, -texture2D(tex,texcoord+direction*distortion.g).g, -texture2D(tex,texcoord+direction*distortion.b).b, -1.0 -);} -void main(void) -{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i<GHOSTS; ++i) -{vec2 offset=fract(uv+ghostDir*ghostIndice);float weight=length(vec2(0.5)-offset)/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;ghostIndice+=1.0;} -vec2 haloVec=normalize(ghostDir)*haloWidth;float weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;result*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));gl_FragColor=result;} -#endif -#if defined(LENS_FLARE_COMPOSE) -uniform sampler2D otherSampler;uniform sampler2D lensDirtSampler;uniform sampler2D lensStarSampler;uniform mat4 lensStarMatrix;void main(void) -{vec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;vec4 lensMod=texture2D(lensDirtSampler,vUV);lensMod+=texture2D(lensStarSampler,vUV/*lensFlareCoords*/);vec4 result=texture2D(textureSampler,vUV)*lensMod;gl_FragColor=texture2D(otherSampler,vUV)+result;} -#endif -#if defined(DEPTH_OF_FIELD) -uniform sampler2D otherSampler;uniform sampler2D depthSampler;uniform float distance;void main(void) -{vec4 sharp=texture2D(otherSampler,vUV);vec4 blur=texture2D(textureSampler,vUV);float dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);float factor=0.0;if (dist<0.05) -factor=1.0;else if (dist<0.1) -factor=20.0*(0.1-dist);else if (dist<0.5) -factor=0.0;else -factor=2.0*(dist-0.5);factor=clamp(factor,0.0,0.90);gl_FragColor=mix(sharp,blur,factor);} -#endif -#if defined(MOTION_BLUR) -uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform vec2 screenSize;uniform float motionScale;uniform float motionStrength;uniform sampler2D depthSampler;void main(void) -{vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=cpos*inverseViewProjection;vec4 ppos=cpos*prevViewProjection;ppos.xyz/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {if (i>=nSamples) -break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} -gl_FragColor=result/float(nSamples);} -#endif -`; -// Sideeffect -ShaderStore.ShadersStore[standard_fragment_name] = standard_fragment_shader; -/** @internal */ -const standardPixelShader = { name: standard_fragment_name, shader: standard_fragment_shader }; -//# sourceMappingURL=standard.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/standardRenderingPipeline.js - - - - - - - - - - - - - - - - - -/** - * Standard rendering pipeline - * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility. - * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/standardRenderingPipeline - */ -class StandardRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline { - /** - * Gets the overall exposure used by the pipeline - */ - get exposure() { - return this._fixedExposure; - } - /** - * Sets the overall exposure used by the pipeline - */ - set exposure(value) { - this._fixedExposure = value; - this._currentExposure = value; - } - /** - * Gets whether or not the exposure of the overall pipeline should be automatically adjusted by the HDR post-process - */ - get hdrAutoExposure() { - return this._hdrAutoExposure; - } - /** - * Sets whether or not the exposure of the overall pipeline should be automatically adjusted by the HDR post-process - */ - set hdrAutoExposure(value) { - this._hdrAutoExposure = value; - if (this.hdrPostProcess) { - const defines = ["#define HDR"]; - if (value) { - defines.push("#define AUTO_EXPOSURE"); - } - this.hdrPostProcess.updateEffect(defines.join("\n")); - } - } - /** - * Gets how much the image is blurred by the movement while using the motion blur post-process - */ - get motionStrength() { - return this._motionStrength; - } - /** - * Sets how much the image is blurred by the movement while using the motion blur post-process - */ - set motionStrength(strength) { - this._motionStrength = strength; - if (this._isObjectBasedMotionBlur && this.motionBlurPostProcess) { - this.motionBlurPostProcess.motionStrength = strength; - } - } - /** - * Gets whether or not the motion blur post-process is object based or screen based. - */ - get objectBasedMotionBlur() { - return this._isObjectBasedMotionBlur; - } - /** - * Sets whether or not the motion blur post-process should be object based or screen based - */ - set objectBasedMotionBlur(value) { - const shouldRebuild = this._isObjectBasedMotionBlur !== value; - this._isObjectBasedMotionBlur = value; - if (shouldRebuild) { - this._buildPipeline(); - } - } - /** - * @ignore - * Specifies if the bloom pipeline is enabled - */ - get BloomEnabled() { - return this._bloomEnabled; - } - set BloomEnabled(enabled) { - if (this._bloomEnabled === enabled) { - return; - } - this._bloomEnabled = enabled; - this._buildPipeline(); - } - /** - * @ignore - * Specifies if the depth of field pipeline is enabled - */ - get DepthOfFieldEnabled() { - return this._depthOfFieldEnabled; - } - set DepthOfFieldEnabled(enabled) { - if (this._depthOfFieldEnabled === enabled) { - return; - } - this._depthOfFieldEnabled = enabled; - this._buildPipeline(); - } - /** - * @ignore - * Specifies if the lens flare pipeline is enabled - */ - get LensFlareEnabled() { - return this._lensFlareEnabled; - } - set LensFlareEnabled(enabled) { - if (this._lensFlareEnabled === enabled) { - return; - } - this._lensFlareEnabled = enabled; - this._buildPipeline(); - } - /** - * @ignore - * Specifies if the HDR pipeline is enabled - */ - get HDREnabled() { - return this._hdrEnabled; - } - set HDREnabled(enabled) { - if (this._hdrEnabled === enabled) { - return; - } - this._hdrEnabled = enabled; - this._buildPipeline(); - } - /** - * @ignore - * Specifies if the volumetric lights scattering effect is enabled - */ - get VLSEnabled() { - return this._vlsEnabled; - } - // eslint-disable-next-line @typescript-eslint/naming-convention - set VLSEnabled(enabled) { - if (this._vlsEnabled === enabled) { - return; - } - if (enabled) { - const geometry = this._scene.enableGeometryBufferRenderer(); - if (!geometry) { - logger_Logger.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline"); - return; - } - } - this._vlsEnabled = enabled; - this._buildPipeline(); - } - /** - * @ignore - * Specifies if the motion blur effect is enabled - */ - get MotionBlurEnabled() { - return this._motionBlurEnabled; - } - set MotionBlurEnabled(enabled) { - if (this._motionBlurEnabled === enabled) { - return; - } - this._motionBlurEnabled = enabled; - this._buildPipeline(); - } - /** - * Specifies if anti-aliasing is enabled - */ - get fxaaEnabled() { - return this._fxaaEnabled; - } - set fxaaEnabled(enabled) { - if (this._fxaaEnabled === enabled) { - return; - } - this._fxaaEnabled = enabled; - this._buildPipeline(); - } - /** - * Specifies if screen space reflections are enabled. - */ - get screenSpaceReflectionsEnabled() { - return this._screenSpaceReflectionsEnabled; - } - set screenSpaceReflectionsEnabled(enabled) { - if (this._screenSpaceReflectionsEnabled === enabled) { - return; - } - this._screenSpaceReflectionsEnabled = enabled; - this._buildPipeline(); - } - /** - * Specifies the number of steps used to calculate the volumetric lights - * Typically in interval [50, 200] - */ - get volumetricLightStepsCount() { - return this._volumetricLightStepsCount; - } - set volumetricLightStepsCount(count) { - if (this.volumetricLightPostProcess) { - this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1)); - } - this._volumetricLightStepsCount = count; - } - /** - * Specifies the number of samples used for the motion blur effect - * Typically in interval [16, 64] - */ - get motionBlurSamples() { - return this._motionBlurSamples; - } - set motionBlurSamples(samples) { - if (this.motionBlurPostProcess) { - if (this._isObjectBasedMotionBlur) { - this.motionBlurPostProcess.motionBlurSamples = samples; - } - else { - this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1)); - } - } - this._motionBlurSamples = samples; - } - /** - * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1) - */ - get samples() { - return this._samples; - } - set samples(sampleCount) { - if (this._samples === sampleCount) { - return; - } - this._samples = sampleCount; - this._buildPipeline(); - } - /** - * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility. - * @constructor - * @param name The rendering pipeline name - * @param scene The scene linked to this pipeline - * @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) - * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null. - * @param cameras The array of cameras that the rendering pipeline will be attached to - */ - constructor(name, scene, ratio, originalPostProcess = null, cameras) { - super(scene.getEngine(), name); - /** - * Post-process used to down scale an image x4 - */ - this.downSampleX4PostProcess = null; - /** - * Post-process used to calculate the illuminated surfaces controlled by a threshold - */ - this.brightPassPostProcess = null; - /** - * Post-process array storing all the horizontal blur post-processes used by the pipeline - */ - this.blurHPostProcesses = []; - /** - * Post-process array storing all the vertical blur post-processes used by the pipeline - */ - this.blurVPostProcesses = []; - /** - * Post-process used to add colors of 2 textures (typically brightness + real scene color) - */ - this.textureAdderPostProcess = null; - /** - * Post-process used to create volumetric lighting effect - */ - this.volumetricLightPostProcess = null; - /** - * Post-process used to smooth the previous volumetric light post-process on the X axis - */ - this.volumetricLightSmoothXPostProcess = null; - /** - * Post-process used to smooth the previous volumetric light post-process on the Y axis - */ - this.volumetricLightSmoothYPostProcess = null; - /** - * Post-process used to merge the volumetric light effect and the real scene color - */ - this.volumetricLightMergePostProces = null; - /** - * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose) - */ - this.volumetricLightFinalPostProcess = null; - /** - * Base post-process used to calculate the average luminance of the final image for HDR - */ - this.luminancePostProcess = null; - /** - * Post-processes used to create down sample post-processes in order to get - * the average luminance of the final image for HDR - * Array of length "StandardRenderingPipeline.LuminanceSteps" - */ - this.luminanceDownSamplePostProcesses = []; - /** - * Post-process used to create a HDR effect (light adaptation) - */ - this.hdrPostProcess = null; - /** - * Post-process used to store the final texture adder post-process (attach/detach for debug purpose) - */ - this.textureAdderFinalPostProcess = null; - /** - * Post-process used to store the final lens flare post-process (attach/detach for debug purpose) - */ - this.lensFlareFinalPostProcess = null; - /** - * Post-process used to merge the final HDR post-process and the real scene color - */ - this.hdrFinalPostProcess = null; - /** - * Post-process used to create a lens flare effect - */ - this.lensFlarePostProcess = null; - /** - * Post-process that merges the result of the lens flare post-process and the real scene color - */ - this.lensFlareComposePostProcess = null; - /** - * Post-process used to create a motion blur effect - */ - this.motionBlurPostProcess = null; - /** - * Post-process used to create a depth of field effect - */ - this.depthOfFieldPostProcess = null; - /** - * The Fast Approximate Anti-Aliasing post process which attempts to remove aliasing from an image. - */ - this.fxaaPostProcess = null; - /** - * Post-process used to simulate realtime reflections using the screen space and geometry renderer. - */ - this.screenSpaceReflectionPostProcess = null; - // Values - /** - * Represents the brightness threshold in order to configure the illuminated surfaces - */ - this.brightThreshold = 1.0; - /** - * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo) - */ - this.blurWidth = 512.0; - /** - * Sets if the blur for highlighted surfaces must be only horizontal - */ - this.horizontalBlur = false; - /** - * Texture used typically to simulate "dirty" on camera lens - */ - this.lensTexture = null; - /** - * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2] - */ - this.volumetricLightCoefficient = 0.2; - /** - * The overall power of volumetric lights, typically in interval [0, 10] maximum - */ - this.volumetricLightPower = 4.0; - /** - * Used the set the blur intensity to smooth the volumetric lights - */ - this.volumetricLightBlurScale = 64.0; - /** - * Light (spot or directional) used to generate the volumetric lights rays - * The source light must have a shadow generate so the pipeline can get its - * depth map - */ - this.sourceLight = null; - /** - * For eye adaptation, represents the minimum luminance the eye can see - */ - this.hdrMinimumLuminance = 1.0; - /** - * For eye adaptation, represents the decrease luminance speed - */ - this.hdrDecreaseRate = 0.5; - /** - * For eye adaptation, represents the increase luminance speed - */ - this.hdrIncreaseRate = 0.5; - /** - * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled - */ - this.lensColorTexture = null; - /** - * The overall strength for the lens flare effect - */ - this.lensFlareStrength = 20.0; - /** - * Dispersion coefficient for lens flare ghosts - */ - this.lensFlareGhostDispersal = 1.4; - /** - * Main lens flare halo width - */ - this.lensFlareHaloWidth = 0.7; - /** - * Based on the lens distortion effect, defines how much the lens flare result - * is distorted - */ - this.lensFlareDistortionStrength = 16.0; - /** - * Configures the blur intensity used for for lens flare (halo) - */ - this.lensFlareBlurWidth = 512.0; - /** - * Lens star texture must be used to simulate rays on the flares and is available - * in the documentation - */ - this.lensStarTexture = null; - /** - * As the "lensTexture" (can be the same texture or different), it is used to apply the lens - * flare effect by taking account of the dirt texture - */ - this.lensFlareDirtTexture = null; - /** - * Represents the focal length for the depth of field effect - */ - this.depthOfFieldDistance = 10.0; - /** - * Represents the blur intensity for the blurred part of the depth of field effect - */ - this.depthOfFieldBlurWidth = 64.0; - /** - * List of animations for the pipeline (IAnimatable implementation) - */ - this.animations = []; - this._currentDepthOfFieldSource = null; - this._fixedExposure = 1.0; - this._currentExposure = 1.0; - this._hdrAutoExposure = false; - this._hdrCurrentLuminance = 1.0; - this._motionStrength = 1.0; - this._isObjectBasedMotionBlur = false; - this._camerasToBeAttached = []; - // Getters and setters - this._bloomEnabled = false; - this._depthOfFieldEnabled = false; - this._vlsEnabled = false; - this._lensFlareEnabled = false; - this._hdrEnabled = false; - this._motionBlurEnabled = false; - this._fxaaEnabled = false; - this._screenSpaceReflectionsEnabled = false; - this._motionBlurSamples = 64.0; - this._volumetricLightStepsCount = 50.0; - this._samples = 1; - this._cameras = cameras || scene.cameras; - this._cameras = this._cameras.slice(); - this._camerasToBeAttached = this._cameras.slice(); - // Initialize - this._scene = scene; - this._basePostProcess = originalPostProcess; - this._ratio = ratio; - // Misc - this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? 1 : 2; - // Finish - scene.postProcessRenderPipelineManager.addPipeline(this); - this._buildPipeline(); - } - _buildPipeline() { - const ratio = this._ratio; - const scene = this._scene; - this._disposePostProcesses(); - if (this._cameras !== null) { - this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); - // get back cameras to be used to reattach pipeline - this._cameras = this._camerasToBeAttached.slice(); - } - this._reset(); - // Create pass post-process - if (this._screenSpaceReflectionsEnabled) { - this.screenSpaceReflectionPostProcess = new ScreenSpaceReflectionPostProcess("HDRPass", scene, ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType); - this.screenSpaceReflectionPostProcess.onApplyObservable.add(() => { - this._currentDepthOfFieldSource = this.screenSpaceReflectionPostProcess; - }); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRScreenSpaceReflections", () => this.screenSpaceReflectionPostProcess, true)); - } - if (!this._basePostProcess) { - this.originalPostProcess = new postProcess_PostProcess("HDRPass", "standard", [], [], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType); - } - else { - this.originalPostProcess = this._basePostProcess; - } - this.originalPostProcess.autoClear = !this.screenSpaceReflectionPostProcess; - this.originalPostProcess.onApplyObservable.add(() => { - this._currentDepthOfFieldSource = this.originalPostProcess; - }); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", () => this.originalPostProcess, true)); - if (this._bloomEnabled) { - // Create down sample X4 post-process - this._createDownSampleX4PostProcess(scene, ratio / 4); - // Create bright pass post-process - this._createBrightPassPostProcess(scene, ratio / 4); - // Create gaussian blur post-processes (down sampling blurs) - this._createBlurPostProcesses(scene, ratio / 4, 1); - // Create texture adder post-process - this._createTextureAdderPostProcess(scene, ratio); - // Create depth-of-field source post-process - this.textureAdderFinalPostProcess = new postProcess_PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", () => { - return this.textureAdderFinalPostProcess; - }, true)); - } - if (this._vlsEnabled) { - // Create volumetric light - this._createVolumetricLightPostProcess(scene, ratio); - // Create volumetric light final post-process - this.volumetricLightFinalPostProcess = new postProcess_PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", () => { - return this.volumetricLightFinalPostProcess; - }, true)); - } - if (this._lensFlareEnabled) { - // Create lens flare post-process - this._createLensFlarePostProcess(scene, ratio); - // Create depth-of-field source post-process post lens-flare and disable it now - this.lensFlareFinalPostProcess = new postProcess_PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", () => { - return this.lensFlareFinalPostProcess; - }, true)); - } - if (this._hdrEnabled) { - // Create luminance - this._createLuminancePostProcesses(scene, this._floatTextureType); - // Create HDR - this._createHdrPostProcess(scene, ratio); - // Create depth-of-field source post-process post hdr and disable it now - this.hdrFinalPostProcess = new postProcess_PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", 0); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", () => { - return this.hdrFinalPostProcess; - }, true)); - } - if (this._depthOfFieldEnabled) { - // Create gaussian blur used by depth-of-field - this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth"); - // Create depth-of-field post-process - this._createDepthOfFieldPostProcess(scene, ratio); - } - if (this._motionBlurEnabled) { - // Create motion blur post-process - this._createMotionBlurPostProcess(scene, ratio); - } - if (this._fxaaEnabled) { - // Create fxaa post-process - this.fxaaPostProcess = new FxaaPostProcess("fxaa", 1.0, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, 0); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", () => { - return this.fxaaPostProcess; - }, true)); - } - if (this._cameras !== null) { - this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); - } - if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) { - logger_Logger.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"); - } - } - // Down Sample X4 Post-Process - _createDownSampleX4PostProcess(scene, ratio) { - const downSampleX4Offsets = new Array(32); - this.downSampleX4PostProcess = new postProcess_PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", this._floatTextureType); - this.downSampleX4PostProcess.onApply = (effect) => { - let id = 0; - const width = this.downSampleX4PostProcess.width; - const height = this.downSampleX4PostProcess.height; - for (let i = -2; i < 2; i++) { - for (let j = -2; j < 2; j++) { - downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width); - downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height); - id += 2; - } - } - effect.setArray2("dsOffsets", downSampleX4Offsets); - }; - // Add to pipeline - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", () => { - return this.downSampleX4PostProcess; - }, true)); - } - // Brightpass Post-Process - _createBrightPassPostProcess(scene, ratio) { - const brightOffsets = new Array(8); - this.brightPassPostProcess = new postProcess_PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", this._floatTextureType); - this.brightPassPostProcess.onApply = (effect) => { - const sU = 1.0 / this.brightPassPostProcess.width; - const sV = 1.0 / this.brightPassPostProcess.height; - brightOffsets[0] = -0.5 * sU; - brightOffsets[1] = 0.5 * sV; - brightOffsets[2] = 0.5 * sU; - brightOffsets[3] = 0.5 * sV; - brightOffsets[4] = -0.5 * sU; - brightOffsets[5] = -0.5 * sV; - brightOffsets[6] = 0.5 * sU; - brightOffsets[7] = -0.5 * sV; - effect.setArray2("dsOffsets", brightOffsets); - effect.setFloat("brightThreshold", this.brightThreshold); - }; - // Add to pipeline - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", () => { - return this.brightPassPostProcess; - }, true)); - } - // Create blur H&V post-processes - _createBlurPostProcesses(scene, ratio, indice, blurWidthKey = "blurWidth") { - const engine = scene.getEngine(); - const blurX = new BlurPostProcess("HDRBlurH" + "_" + indice, new math_vector_Vector2(1, 0), this[blurWidthKey], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType); - const blurY = new BlurPostProcess("HDRBlurV" + "_" + indice, new math_vector_Vector2(0, 1), this[blurWidthKey], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType); - blurX.onActivateObservable.add(() => { - const dw = blurX.width / engine.getRenderWidth(); - blurX.kernel = this[blurWidthKey] * dw; - }); - blurY.onActivateObservable.add(() => { - const dw = blurY.height / engine.getRenderHeight(); - blurY.kernel = this.horizontalBlur ? 64 * dw : this[blurWidthKey] * dw; - }); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, () => { - return blurX; - }, true)); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, () => { - return blurY; - }, true)); - this.blurHPostProcesses.push(blurX); - this.blurVPostProcesses.push(blurY); - } - // Create texture adder post-process - _createTextureAdderPostProcess(scene, ratio) { - this.textureAdderPostProcess = new postProcess_PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", this._floatTextureType); - this.textureAdderPostProcess.onApply = (effect) => { - effect.setTextureFromPostProcess("otherSampler", this._vlsEnabled ? this._currentDepthOfFieldSource : this.originalPostProcess); - effect.setTexture("lensSampler", this.lensTexture); - effect.setFloat("exposure", this._currentExposure); - this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess; - }; - // Add to pipeline - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", () => { - return this.textureAdderPostProcess; - }, true)); - } - _createVolumetricLightPostProcess(scene, ratio) { - const geometryRenderer = scene.enableGeometryBufferRenderer(); - geometryRenderer.enablePosition = true; - const geometry = geometryRenderer.getGBuffer(); - // Base post-process - this.volumetricLightPostProcess = new postProcess_PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1)); - const depthValues = math_vector_Vector2.Zero(); - this.volumetricLightPostProcess.onApply = (effect) => { - if (this.sourceLight && this.sourceLight.getShadowGenerator() && this._scene.activeCamera) { - const generator = this.sourceLight.getShadowGenerator(); - effect.setTexture("shadowMapSampler", generator.getShadowMap()); - effect.setTexture("positionSampler", geometry.textures[2]); - effect.setColor3("sunColor", this.sourceLight.diffuse); - effect.setVector3("sunDirection", this.sourceLight.getShadowDirection()); - effect.setVector3("cameraPosition", this._scene.activeCamera.globalPosition); - effect.setMatrix("shadowViewProjection", generator.getTransformMatrix()); - effect.setFloat("scatteringCoefficient", this.volumetricLightCoefficient); - effect.setFloat("scatteringPower", this.volumetricLightPower); - depthValues.x = this.sourceLight.getDepthMinZ(this._scene.activeCamera); - depthValues.y = this.sourceLight.getDepthMaxZ(this._scene.activeCamera); - effect.setVector2("depthValues", depthValues); - } - }; - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRVLS", () => { - return this.volumetricLightPostProcess; - }, true)); - // Smooth - this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale"); - // Merge - this.volumetricLightMergePostProces = new postProcess_PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE"); - this.volumetricLightMergePostProces.onApply = (effect) => { - effect.setTextureFromPostProcess("originalSampler", this._bloomEnabled ? this.textureAdderFinalPostProcess : this.originalPostProcess); - this._currentDepthOfFieldSource = this.volumetricLightFinalPostProcess; - }; - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", () => { - return this.volumetricLightMergePostProces; - }, true)); - } - // Create luminance - _createLuminancePostProcesses(scene, textureType) { - // Create luminance - let size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps); - this.luminancePostProcess = new postProcess_PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType); - const offsets = []; - this.luminancePostProcess.onApply = (effect) => { - const sU = 1.0 / this.luminancePostProcess.width; - const sV = 1.0 / this.luminancePostProcess.height; - offsets[0] = -0.5 * sU; - offsets[1] = 0.5 * sV; - offsets[2] = 0.5 * sU; - offsets[3] = 0.5 * sV; - offsets[4] = -0.5 * sU; - offsets[5] = -0.5 * sV; - offsets[6] = 0.5 * sU; - offsets[7] = -0.5 * sV; - effect.setArray2("lumOffsets", offsets); - }; - // Add to pipeline - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", () => { - return this.luminancePostProcess; - }, true)); - // Create down sample luminance - for (let i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) { - size = Math.pow(3, i); - let defines = "#define LUMINANCE_DOWN_SAMPLE\n"; - if (i === 0) { - defines += "#define FINAL_DOWN_SAMPLER"; - } - const postProcess = new postProcess_PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType); - this.luminanceDownSamplePostProcesses.push(postProcess); - } - // Create callbacks and add effects - let lastLuminance = this.luminancePostProcess; - this.luminanceDownSamplePostProcesses.forEach((pp, index) => { - const downSampleOffsets = new Array(18); - pp.onApply = (effect) => { - if (!lastLuminance) { - return; - } - let id = 0; - for (let x = -1; x < 2; x++) { - for (let y = -1; y < 2; y++) { - downSampleOffsets[id] = x / lastLuminance.width; - downSampleOffsets[id + 1] = y / lastLuminance.height; - id += 2; - } - } - effect.setArray2("dsOffsets", downSampleOffsets); - effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width); - if (index === this.luminanceDownSamplePostProcesses.length - 1) { - lastLuminance = this.luminancePostProcess; - } - else { - lastLuminance = pp; - } - }; - if (index === this.luminanceDownSamplePostProcesses.length - 1) { - pp.onAfterRender = () => { - const pixel = scene.getEngine().readPixels(0, 0, 1, 1); - const bit_shift = new math_vector_Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0); - pixel.then((pixel) => { - const data = new Uint8Array(pixel.buffer); - this._hdrCurrentLuminance = (data[0] * bit_shift.x + data[1] * bit_shift.y + data[2] * bit_shift.z + data[3] * bit_shift.w) / 100.0; - }); - }; - } - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, () => { - return pp; - }, true)); - }); - } - // Create HDR post-process - _createHdrPostProcess(scene, ratio) { - const defines = ["#define HDR"]; - if (this._hdrAutoExposure) { - defines.push("#define AUTO_EXPOSURE"); - } - this.hdrPostProcess = new postProcess_PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines.join("\n"), 0); - let outputLiminance = 1; - let time = 0; - let lastTime = 0; - this.hdrPostProcess.onApply = (effect) => { - effect.setTextureFromPostProcess("textureAdderSampler", this._currentDepthOfFieldSource); - time += scene.getEngine().getDeltaTime(); - if (outputLiminance < 0) { - outputLiminance = this._hdrCurrentLuminance; - } - else { - const dt = (lastTime - time) / 1000.0; - if (this._hdrCurrentLuminance < outputLiminance + this.hdrDecreaseRate * dt) { - outputLiminance += this.hdrDecreaseRate * dt; - } - else if (this._hdrCurrentLuminance > outputLiminance - this.hdrIncreaseRate * dt) { - outputLiminance -= this.hdrIncreaseRate * dt; - } - else { - outputLiminance = this._hdrCurrentLuminance; - } - } - if (this.hdrAutoExposure) { - this._currentExposure = this._fixedExposure / outputLiminance; - } - else { - outputLiminance = math_scalar_Scalar.Clamp(outputLiminance, this.hdrMinimumLuminance, 1e20); - effect.setFloat("averageLuminance", outputLiminance); - } - lastTime = time; - this._currentDepthOfFieldSource = this.hdrFinalPostProcess; - }; - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDR", () => { - return this.hdrPostProcess; - }, true)); - } - // Create lens flare post-process - _createLensFlarePostProcess(scene, ratio) { - this.lensFlarePostProcess = new postProcess_PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", 0); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", () => { - return this.lensFlarePostProcess; - }, true)); - this._createBlurPostProcesses(scene, ratio / 4, 2, "lensFlareBlurWidth"); - this.lensFlareComposePostProcess = new postProcess_PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", 0); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", () => { - return this.lensFlareComposePostProcess; - }, true)); - const resolution = new math_vector_Vector2(0, 0); - // Lens flare - this.lensFlarePostProcess.externalTextureSamplerBinding = true; - this.lensFlarePostProcess.onApply = (effect) => { - effect.setTextureFromPostProcess("textureSampler", this._bloomEnabled ? this.blurHPostProcesses[0] : this.originalPostProcess); - effect.setTexture("lensColorSampler", this.lensColorTexture); - effect.setFloat("strength", this.lensFlareStrength); - effect.setFloat("ghostDispersal", this.lensFlareGhostDispersal); - effect.setFloat("haloWidth", this.lensFlareHaloWidth); - // Shift - resolution.x = this.lensFlarePostProcess.width; - resolution.y = this.lensFlarePostProcess.height; - effect.setVector2("resolution", resolution); - effect.setFloat("distortionStrength", this.lensFlareDistortionStrength); - }; - // Compose - const scaleBias1 = math_vector_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); - const scaleBias2 = math_vector_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); - this.lensFlareComposePostProcess.onApply = (effect) => { - if (!this._scene.activeCamera) { - return; - } - effect.setTextureFromPostProcess("otherSampler", this.lensFlarePostProcess); - effect.setTexture("lensDirtSampler", this.lensFlareDirtTexture); - effect.setTexture("lensStarSampler", this.lensStarTexture); - // Lens start rotation matrix - const camerax = this._scene.activeCamera.getViewMatrix().getRow(0); - const cameraz = this._scene.activeCamera.getViewMatrix().getRow(2); - let camRot = math_vector_Vector3.Dot(camerax.toVector3(), new math_vector_Vector3(1.0, 0.0, 0.0)) + math_vector_Vector3.Dot(cameraz.toVector3(), new math_vector_Vector3(0.0, 0.0, 1.0)); - camRot *= 4.0; - const starRotation = math_vector_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); - const lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1); - effect.setMatrix("lensStarMatrix", lensStarMatrix); - this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess; - }; - } - // Create depth-of-field post-process - _createDepthOfFieldPostProcess(scene, ratio) { - this.depthOfFieldPostProcess = new postProcess_PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", 0); - this.depthOfFieldPostProcess.onApply = (effect) => { - effect.setTextureFromPostProcess("otherSampler", this._currentDepthOfFieldSource); - effect.setTexture("depthSampler", this._getDepthTexture()); - effect.setFloat("distance", this.depthOfFieldDistance); - }; - // Add to pipeline - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", () => { - return this.depthOfFieldPostProcess; - }, true)); - } - // Create motion blur post-process - _createMotionBlurPostProcess(scene, ratio) { - if (this._isObjectBasedMotionBlur) { - const mb = new MotionBlurPostProcess("HDRMotionBlur", scene, ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, 0); - mb.motionStrength = this.motionStrength; - mb.motionBlurSamples = this.motionBlurSamples; - this.motionBlurPostProcess = mb; - } - else { - this.motionBlurPostProcess = new postProcess_PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, texture_Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), 0); - let motionScale = 0; - let prevViewProjection = math_vector_Matrix.Identity(); - const invViewProjection = math_vector_Matrix.Identity(); - let viewProjection = math_vector_Matrix.Identity(); - const screenSize = math_vector_Vector2.Zero(); - this.motionBlurPostProcess.onApply = (effect) => { - viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix()); - viewProjection.invertToRef(invViewProjection); - effect.setMatrix("inverseViewProjection", invViewProjection); - effect.setMatrix("prevViewProjection", prevViewProjection); - prevViewProjection = viewProjection; - screenSize.x = this.motionBlurPostProcess.width; - screenSize.y = this.motionBlurPostProcess.height; - effect.setVector2("screenSize", screenSize); - motionScale = scene.getEngine().getFps() / 60.0; - effect.setFloat("motionScale", motionScale); - effect.setFloat("motionStrength", this.motionStrength); - effect.setTexture("depthSampler", this._getDepthTexture()); - }; - } - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", () => { - return this.motionBlurPostProcess; - }, true)); - } - _getDepthTexture() { - if (this._scene.getEngine().getCaps().drawBuffersExtension) { - const renderer = this._scene.enableGeometryBufferRenderer(); - return renderer.getGBuffer().textures[0]; - } - return this._scene.enableDepthRenderer().getDepthMap(); - } - _disposePostProcesses() { - for (let i = 0; i < this._cameras.length; i++) { - const camera = this._cameras[i]; - if (this.originalPostProcess) { - this.originalPostProcess.dispose(camera); - } - if (this.screenSpaceReflectionPostProcess) { - this.screenSpaceReflectionPostProcess.dispose(camera); - } - if (this.downSampleX4PostProcess) { - this.downSampleX4PostProcess.dispose(camera); - } - if (this.brightPassPostProcess) { - this.brightPassPostProcess.dispose(camera); - } - if (this.textureAdderPostProcess) { - this.textureAdderPostProcess.dispose(camera); - } - if (this.volumetricLightPostProcess) { - this.volumetricLightPostProcess.dispose(camera); - } - if (this.volumetricLightSmoothXPostProcess) { - this.volumetricLightSmoothXPostProcess.dispose(camera); - } - if (this.volumetricLightSmoothYPostProcess) { - this.volumetricLightSmoothYPostProcess.dispose(camera); - } - if (this.volumetricLightMergePostProces) { - this.volumetricLightMergePostProces.dispose(camera); - } - if (this.volumetricLightFinalPostProcess) { - this.volumetricLightFinalPostProcess.dispose(camera); - } - if (this.lensFlarePostProcess) { - this.lensFlarePostProcess.dispose(camera); - } - if (this.lensFlareComposePostProcess) { - this.lensFlareComposePostProcess.dispose(camera); - } - for (let j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) { - this.luminanceDownSamplePostProcesses[j].dispose(camera); - } - if (this.luminancePostProcess) { - this.luminancePostProcess.dispose(camera); - } - if (this.hdrPostProcess) { - this.hdrPostProcess.dispose(camera); - } - if (this.hdrFinalPostProcess) { - this.hdrFinalPostProcess.dispose(camera); - } - if (this.depthOfFieldPostProcess) { - this.depthOfFieldPostProcess.dispose(camera); - } - if (this.motionBlurPostProcess) { - this.motionBlurPostProcess.dispose(camera); - } - if (this.fxaaPostProcess) { - this.fxaaPostProcess.dispose(camera); - } - for (let j = 0; j < this.blurHPostProcesses.length; j++) { - this.blurHPostProcesses[j].dispose(camera); - } - for (let j = 0; j < this.blurVPostProcesses.length; j++) { - this.blurVPostProcesses[j].dispose(camera); - } - } - this.originalPostProcess = null; - this.downSampleX4PostProcess = null; - this.brightPassPostProcess = null; - this.textureAdderPostProcess = null; - this.textureAdderFinalPostProcess = null; - this.volumetricLightPostProcess = null; - this.volumetricLightSmoothXPostProcess = null; - this.volumetricLightSmoothYPostProcess = null; - this.volumetricLightMergePostProces = null; - this.volumetricLightFinalPostProcess = null; - this.lensFlarePostProcess = null; - this.lensFlareComposePostProcess = null; - this.luminancePostProcess = null; - this.hdrPostProcess = null; - this.hdrFinalPostProcess = null; - this.depthOfFieldPostProcess = null; - this.motionBlurPostProcess = null; - this.fxaaPostProcess = null; - this.screenSpaceReflectionPostProcess = null; - this.luminanceDownSamplePostProcesses.length = 0; - this.blurHPostProcesses.length = 0; - this.blurVPostProcesses.length = 0; - } - /** - * Dispose of the pipeline and stop all post processes - */ - dispose() { - this._disposePostProcesses(); - this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); - super.dispose(); - } - /** - * Serialize the rendering pipeline (Used when exporting) - * @returns the serialized object - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - if (this.sourceLight) { - serializationObject.sourceLightId = this.sourceLight.id; - } - if (this.screenSpaceReflectionPostProcess) { - serializationObject.screenSpaceReflectionPostProcess = decorators_SerializationHelper.Serialize(this.screenSpaceReflectionPostProcess); - } - serializationObject.customType = "StandardRenderingPipeline"; - return serializationObject; - } - /** - * Parse the serialized pipeline - * @param source Source pipeline. - * @param scene The scene to load the pipeline to. - * @param rootUrl The URL of the serialized pipeline. - * @returns An instantiated pipeline from the serialized object. - */ - static Parse(source, scene, rootUrl) { - const p = decorators_SerializationHelper.Parse(() => new StandardRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl); - if (source.sourceLightId) { - p.sourceLight = scene.getLightById(source.sourceLightId); - } - if (source.screenSpaceReflectionPostProcess) { - decorators_SerializationHelper.Parse(() => p.screenSpaceReflectionPostProcess, source.screenSpaceReflectionPostProcess, scene, rootUrl); - } - return p; - } -} -/** - * Luminance steps - */ -StandardRenderingPipeline.LuminanceSteps = 6; -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "brightThreshold", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "blurWidth", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "horizontalBlur", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "exposure", null); -__decorate([ - serializeAsTexture("lensTexture") -], StandardRenderingPipeline.prototype, "lensTexture", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "hdrAutoExposure", null); -__decorate([ - serializeAsTexture("lensColorTexture") -], StandardRenderingPipeline.prototype, "lensColorTexture", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "lensFlareBlurWidth", void 0); -__decorate([ - serializeAsTexture("lensStarTexture") -], StandardRenderingPipeline.prototype, "lensStarTexture", void 0); -__decorate([ - serializeAsTexture("lensFlareDirtTexture") -], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "motionStrength", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "objectBasedMotionBlur", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "_ratio", void 0); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "BloomEnabled", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "LensFlareEnabled", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "HDREnabled", null); -__decorate([ - serialize() - // eslint-disable-next-line @typescript-eslint/naming-convention -], StandardRenderingPipeline.prototype, "VLSEnabled", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "fxaaEnabled", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "screenSpaceReflectionsEnabled", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "motionBlurSamples", null); -__decorate([ - serialize() -], StandardRenderingPipeline.prototype, "samples", null); -RegisterClass("BABYLON.StandardRenderingPipeline", StandardRenderingPipeline); -//# sourceMappingURL=standardRenderingPipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/screenSpaceReflections2Configuration.js - -/** - * Contains all parameters needed for the prepass to perform - * screen space reflections - */ -class ScreenSpaceReflections2Configuration { - constructor() { - /** - * Is ssr enabled - */ - this.enabled = false; - /** - * Name of the configuration - */ - this.name = "screenSpaceReflections2"; - /** - * Textures that should be present in the MRT for this effect to work - */ - this.texturesRequired = [6, 3, 5]; - } -} -//# sourceMappingURL=screenSpaceReflections2Configuration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/screenSpaceRayTrace.js -// Do not edit. - -const screenSpaceRayTrace_name = "screenSpaceRayTrace"; -const screenSpaceRayTrace_shader = `float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } -/** -\param csOrigin Camera-space ray origin,which must be -within the view volume and must have z>0.01 and project within the valid screen rectangle -\param csDirection Unit length camera-space ray direction -\param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates -(**not** [-1,+1] normalized device coordinates). -\param csZBuffer The camera-space Z buffer -\param csZBufferSize Dimensions of csZBuffer -\param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer -\param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value -for clipping rays headed towards the camera -\param stride Step in horizontal or vertical pixels between samples. This is a float -because integer math is slow on GPUs,but should be set to an integer>=1 -\param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units -to conceal banding artifacts,plus the stride ray offset. -\param maxSteps Maximum number of iterations. Higher gives better images but may be slow -\param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss -\param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. -1 is a reasonable value,depending on the scene you may need to set this value to 2 -\param hitPixel Pixel coordinates of the first intersection with the scene -\param numIterations number of iterations performed -\param csHitPoint Camera space location of the ray hit -*/ -#define inline -bool traceScreenSpaceRay1( -vec3 csOrigin, -vec3 csDirection, -mat4 projectToPixelMatrix, -sampler2D csZBuffer, -vec2 csZBufferSize, -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -sampler2D csZBackBuffer, -float csZBackSizeFactor, -#endif -float csZThickness, -float nearPlaneZ, -float stride, -float jitterFraction, -float maxSteps, -float maxRayTraceDistance, -float selfCollisionNumSkip, -out vec2 startPixel, -out vec2 hitPixel, -out vec3 csHitPoint, -out float numIterations -#ifdef SSRAYTRACE_DEBUG -,out vec3 debugColor -#endif -) -{ -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; -#else -float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)<nearPlaneZ ? (nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; -#endif -vec3 csEndPoint=csOrigin+csDirection*rayLength;hitPixel=vec2(-1.0,-1.0);vec4 H0=projectToPixelMatrix*vec4(csOrigin,1.0);vec4 H1=projectToPixelMatrix*vec4(csEndPoint,1.0);float k0=1.0/H0.w;float k1=1.0/H1.w;vec3 Q0=csOrigin*k0;vec3 Q1=csEndPoint*k1;vec2 P0=H0.xy*k0;vec2 P1=H1.xy*k1; -#ifdef SSRAYTRACE_CLIP_TO_FRUSTUM -float xMax=csZBufferSize.x-0.5,xMin=0.5,yMax=csZBufferSize.y-0.5,yMin=0.5;float alpha=0.0;if ((P1.y>yMax) || (P1.y<yMin)) {alpha=(P1.y-((P1.y>yMax) ? yMax : yMin))/(P1.y-P0.y);} -if ((P1.x>xMax) || (P1.x<xMin)) {alpha=max(alpha,(P1.x-((P1.x>xMax) ? xMax : xMin))/(P1.x-P0.x));} -P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); -#endif -P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)<abs(delta.y)) { -permute=true;delta=delta.yx;P0=P0.yx;P1=P1.yx; } -float stepDirection=sign(delta.x);float invdx=stepDirection/delta.x;vec2 dP=vec2(stepDirection,delta.y*invdx);vec3 dQ=(Q1-Q0)*invdx;float dk=(k1-k0)*invdx;float zMin=min(csEndPoint.z,csOrigin.z);float zMax=max(csEndPoint.z,csOrigin.z);dP*=stride; dQ*=stride; dk*=stride;P0+=dP*jitterFraction; Q0+=dQ*jitterFraction; k0+=dk*jitterFraction;vec4 pqk=vec4(P0,Q0.z,k0);vec4 dPQK=vec4(dP,dQ.z,dk);startPixel=permute ? P0.yx : P0.xy;float prevZMaxEstimate=csOrigin.z;float rayZMin=prevZMaxEstimate,rayZMax=prevZMaxEstimate;float sceneZMax=rayZMax+1e4;float end=P1.x*stepDirection;bool hit=false;float stepCount;for (stepCount=0.0;stepCount<=selfCollisionNumSkip || -(pqk.x*stepDirection)<=end && -stepCount<maxSteps && -!hit && -sceneZMax != 0.0; -pqk+=dPQK,++stepCount) -{hitPixel=permute ? pqk.yx : pqk.xy;rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;if (rayZMin>rayZMax) { -float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} -sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); -#else -hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); -#endif -#else -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); -#else -hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); -#endif -#endif -} -pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} -#ifdef SSRAYTRACE_ENABLE_REFINEMENT -if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || -(refinementStepCount<=stride*1.4) && -(rayZMax<sceneZMax) && (sceneZMax != 0.0);pqk+=dPQK,refinementStepCount+=1.0) -{rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;rayZMax=max(rayZMax,rayZMin);hitPixel=permute ? pqk.yx : pqk.xy;sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;} -pqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;} -#endif -Q0.xy+=dQ.xy*stepCount;Q0.z=pqk.z;csHitPoint=Q0/pqk.w;numIterations=stepCount+1.0; -#ifdef SSRAYTRACE_DEBUG -if (((pqk.x+dPQK.x)*stepDirection)>end) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} -#endif -return hit;} -/** -texCoord: in the [0,1] range -depth: depth in view space (range [znear,zfar]]) -*/ -vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -ndc.z=-projection[2].z-projection[3].z/depth; -#else -ndc.z=projection[2].z+projection[3].z/depth; -#endif -ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} -`; -// Sideeffect -ShaderStore.IncludesShadersStore[screenSpaceRayTrace_name] = screenSpaceRayTrace_shader; -/** @internal */ -const screenSpaceRayTrace = { name: screenSpaceRayTrace_name, shader: screenSpaceRayTrace_shader }; -//# sourceMappingURL=screenSpaceRayTrace.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/screenSpaceReflection2.fragment.js -// Do not edit. - - - - -const screenSpaceReflection2_fragment_name = "screenSpaceReflection2PixelShader"; -const screenSpaceReflection2_fragment_shader = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSR_SUPPORTED -uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -uniform sampler2D backDepthSampler;uniform float backSizeFactor; -#endif -#ifdef SSR_USE_ENVIRONMENT_CUBE -uniform samplerCube envCubeSampler; -#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; -#include<helperFunctions> -#include<pbrBRDFFunctions> -#include<screenSpaceRayTrace> -vec3 hash(vec3 a) -{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} -float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; -#ifdef SSR_ATTENUATE_SCREEN_BORDERS -vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); -#endif -#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE -attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); -#endif -#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS -attenuation*=1.0-(numIterations/maxSteps); -#endif -#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION -vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; -#endif -return attenuation;} -#endif -void main() -{ -#ifdef SSR_SUPPORTED -vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0); -#ifndef SSR_DISABLE_REFLECTIVITY_TEST -if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { -#ifdef SSR_USE_BLUR -gl_FragColor=vec4(0.); -#else -gl_FragColor=colorFull; -#endif -return;} -#endif -#ifdef SSR_INPUT_IS_GAMMA_SPACE -color=toLinearSpace(color); -#endif -vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; -float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal); -#ifdef SSR_USE_ENVIRONMENT_CUBE -vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); -#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC -vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); -#endif -#ifdef SSR_INVERTCUBICMAP -wReflectedVector.y*=-1.0; -#endif -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -wReflectedVector.z*=-1.0; -#endif -vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; -#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE -envColor=toLinearSpace(envColor); -#endif -#else -vec3 envColor=color; -#endif -float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; -#ifdef SSRAYTRACE_DEBUG -vec3 debugColor; -#endif -#ifdef SSR_ATTENUATE_FACING_CAMERA -reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); -#endif -if (reflectionAttenuation>0.0) { -#ifdef SSR_USE_BLUR -vec3 jitt=vec3(0.); -#else -float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; -#endif -vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); -rayHasHit=traceScreenSpaceRay1( -csPosition, -normalize(csReflectedVector+jitt), -projectionPixel, -depthSampler, -texSize, -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -backDepthSampler, -backSizeFactor, -#endif -thickness, -nearPlaneZ, -stepSize, -jitter, -maxSteps, -maxDistance, -selfCollisionNumSkip, -startPixel, -hitPixel, -hitPoint, -numIterations -#ifdef SSRAYTRACE_DEBUG -,debugColor -#endif -);} -#ifdef SSRAYTRACE_DEBUG -gl_FragColor=vec4(debugColor,1.);return; -#endif -vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; -#ifdef SSR_INPUT_IS_GAMMA_SPACE -reflectedColor=toLinearSpace(reflectedColor); -#endif -reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} -#ifndef SSR_BLEND_WITH_FRESNEL -SSR*=fresnel; -#endif -#ifdef SSR_USE_BLUR -float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; -float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} -gl_FragColor=vec4(SSR,blur_radius/255.0); -#else -#ifdef SSR_BLEND_WITH_FRESNEL -vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#else -vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#endif -vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); -#ifdef SSR_OUTPUT_IS_GAMMA_SPACE -finalColor=toGammaSpace(finalColor); -#endif -gl_FragColor=vec4(finalColor,colorFull.a); -#endif -#else -gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[screenSpaceReflection2_fragment_name] = screenSpaceReflection2_fragment_shader; -/** @internal */ -const screenSpaceReflection2PixelShader = { name: screenSpaceReflection2_fragment_name, shader: screenSpaceReflection2_fragment_shader }; -//# sourceMappingURL=screenSpaceReflection2.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/screenSpaceReflection2Blur.fragment.js -// Do not edit. - -const screenSpaceReflection2Blur_fragment_name = "screenSpaceReflection2BlurPixelShader"; -const screenSpaceReflection2Blur_fragment_shader = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) -{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} -void main() -{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} -float blurRadius=colorFull.a*255.0; -vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} -`; -// Sideeffect -ShaderStore.ShadersStore[screenSpaceReflection2Blur_fragment_name] = screenSpaceReflection2Blur_fragment_shader; -/** @internal */ -const screenSpaceReflection2BlurPixelShader = { name: screenSpaceReflection2Blur_fragment_name, shader: screenSpaceReflection2Blur_fragment_shader }; -//# sourceMappingURL=screenSpaceReflection2Blur.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/screenSpaceReflection2BlurCombiner.fragment.js -// Do not edit. - - - - -const screenSpaceReflection2BlurCombiner_fragment_name = "screenSpaceReflection2BlurCombinerPixelShader"; -const screenSpaceReflection2BlurCombiner_fragment_shader = `uniform sampler2D textureSampler; -uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; -#include<helperFunctions> -#ifdef SSR_BLEND_WITH_FRESNEL -#include<pbrBRDFFunctions> -#include<screenSpaceRayTrace> -uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler; -#endif -void main() -{ -#ifdef SSRAYTRACE_DEBUG -gl_FragColor=texture2D(textureSampler,vUV); -#else -vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); -#ifndef SSR_DISABLE_REFLECTIVITY_TEST -if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} -#endif -#ifdef SSR_INPUT_IS_GAMMA_SPACE -color=toLinearSpace(color); -#endif -#ifdef SSR_BLEND_WITH_FRESNEL -vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#else -vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#endif -vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); -#ifdef SSR_OUTPUT_IS_GAMMA_SPACE -finalColor=toGammaSpace(finalColor); -#endif -gl_FragColor=vec4(finalColor,color.a); -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[screenSpaceReflection2BlurCombiner_fragment_name] = screenSpaceReflection2BlurCombiner_fragment_shader; -/** @internal */ -const screenSpaceReflection2BlurCombinerPixelShader = { name: screenSpaceReflection2BlurCombiner_fragment_name, shader: screenSpaceReflection2BlurCombiner_fragment_shader }; -//# sourceMappingURL=screenSpaceReflection2BlurCombiner.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssrRenderingPipeline.js - -/* eslint-disable @typescript-eslint/naming-convention */ - - - - - - - - - - - - - - -const trs = math_vector_Matrix.Compose(new math_vector_Vector3(0.5, 0.5, 0.5), math_vector_Quaternion.Identity(), new math_vector_Vector3(0.5, 0.5, 0.5)); -const trsWebGPU = math_vector_Matrix.Compose(new math_vector_Vector3(0.5, 0.5, 1), math_vector_Quaternion.Identity(), new math_vector_Vector3(0.5, 0.5, 0)); -/** - * Render pipeline to produce Screen Space Reflections (SSR) effect - * - * References: - * Screen Space Ray Tracing: - * - http://casual-effects.blogspot.com/2014/08/screen-space-ray-tracing.html - * - https://sourceforge.net/p/g3d/code/HEAD/tree/G3D10/data-files/shader/screenSpaceRayTrace.glsl - * - https://github.com/kode80/kode80SSR - * SSR: - * - general tips: https://sakibsaikia.github.io/graphics/2016/12/26/Screen-Space-Reflection-in-Killing-Floor-2.html - * - 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 - * - blur and usage of back depth buffer: https://github.com/kode80/kode80SSR - */ -class SSRRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline { - /** - * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1) - */ - set samples(sampleCount) { - if (this._samples === sampleCount) { - return; - } - this._samples = sampleCount; - this._buildPipeline(); - } - get samples() { - return this._samples; - } - /** - * Gets or sets the minimum value for one of the reflectivity component of the material to consider it for SSR (default: 0.04). - * 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. - */ - get reflectivityThreshold() { - return this._reflectivityThreshold; - } - set reflectivityThreshold(threshold) { - if (threshold === this._reflectivityThreshold) { - return; - } - if ((threshold === 0 && this._reflectivityThreshold !== 0) || (threshold !== 0 && this._reflectivityThreshold === 0)) { - this._reflectivityThreshold = threshold; - this._buildPipeline(); - } - else { - this._reflectivityThreshold = threshold; - } - } - /** - * Gets or sets the downsample factor used to reduce the size of the texture used to compute the SSR contribution (default: 0). - * Use 0 to render the SSR contribution at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc. - * 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. - */ - get ssrDownsample() { - return this._ssrDownsample; - } - set ssrDownsample(downsample) { - if (downsample === this._ssrDownsample) { - return; - } - this._ssrDownsample = downsample; - this._buildPipeline(); - } - /** - * Gets or sets the blur dispersion strength. Set this value to 0 to disable blurring (default: 0.05) - * 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. - * blurDispersionStrength allows to increase or decrease this effect. - */ - get blurDispersionStrength() { - return this._blurDispersionStrength; - } - set blurDispersionStrength(strength) { - if (strength === this._blurDispersionStrength) { - return; - } - const rebuild = (strength === 0 && this._blurDispersionStrength !== 0) || (strength !== 0 && this._blurDispersionStrength === 0); - this._blurDispersionStrength = strength; - if (rebuild) { - this._buildPipeline(); - } - } - _useBlur() { - return this._blurDispersionStrength > 0; - } - /** - * Gets or sets the downsample factor used to reduce the size of the textures used to blur the reflection effect (default: 0). - * Use 0 to blur at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc. - */ - get blurDownsample() { - return this._blurDownsample; - } - set blurDownsample(downsample) { - if (downsample === this._blurDownsample) { - return; - } - this._blurDownsample = downsample; - this._buildPipeline(); - } - /** - * Gets or sets whether or not smoothing reflections is enabled (default: false) - * Enabling smoothing will require more GPU power. - * Note that this setting has no effect if step = 1: it's only used if step \> 1. - */ - get enableSmoothReflections() { - return this._enableSmoothReflections; - } - set enableSmoothReflections(enabled) { - if (enabled === this._enableSmoothReflections) { - return; - } - this._enableSmoothReflections = enabled; - this._updateEffectDefines(); - } - /** - * 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. - */ - get environmentTexture() { - return this._environmentTexture; - } - set environmentTexture(texture) { - this._environmentTexture = texture; - this._updateEffectDefines(); - } - /** - * Gets or sets the boolean defining if the environment texture is a standard cubemap (false) or a probe (true). Default value is false. - * Note: a probe cube texture is treated differently than an ordinary cube texture because the Y axis is reversed. - */ - get environmentTextureIsProbe() { - return this._environmentTextureIsProbe; - } - set environmentTextureIsProbe(isProbe) { - this._environmentTextureIsProbe = isProbe; - this._updateEffectDefines(); - } - /** - * Gets or sets a boolean indicating if the reflections should be attenuated at the screen borders (default: true). - */ - get attenuateScreenBorders() { - return this._attenuateScreenBorders; - } - set attenuateScreenBorders(attenuate) { - if (this._attenuateScreenBorders === attenuate) { - return; - } - this._attenuateScreenBorders = attenuate; - this._updateEffectDefines(); - } - /** - * Gets or sets a boolean indicating if the reflections should be attenuated according to the distance of the intersection (default: true). - */ - get attenuateIntersectionDistance() { - return this._attenuateIntersectionDistance; - } - set attenuateIntersectionDistance(attenuate) { - if (this._attenuateIntersectionDistance === attenuate) { - return; - } - this._attenuateIntersectionDistance = attenuate; - this._updateEffectDefines(); - } - /** - * 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). - */ - get attenuateIntersectionIterations() { - return this._attenuateIntersectionIterations; - } - set attenuateIntersectionIterations(attenuate) { - if (this._attenuateIntersectionIterations === attenuate) { - return; - } - this._attenuateIntersectionIterations = attenuate; - this._updateEffectDefines(); - } - /** - * 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). - */ - get attenuateFacingCamera() { - return this._attenuateFacingCamera; - } - set attenuateFacingCamera(attenuate) { - if (this._attenuateFacingCamera === attenuate) { - return; - } - this._attenuateFacingCamera = attenuate; - this._updateEffectDefines(); - } - /** - * Gets or sets a boolean indicating if the backface reflections should be attenuated (default: false). - */ - get attenuateBackfaceReflection() { - return this._attenuateBackfaceReflection; - } - set attenuateBackfaceReflection(attenuate) { - if (this._attenuateBackfaceReflection === attenuate) { - return; - } - this._attenuateBackfaceReflection = attenuate; - this._updateEffectDefines(); - } - /** - * Gets or sets a boolean indicating if the ray should be clipped to the frustum (default: true). - * 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 - */ - get clipToFrustum() { - return this._clipToFrustum; - } - set clipToFrustum(clip) { - if (this._clipToFrustum === clip) { - return; - } - this._clipToFrustum = clip; - this._updateEffectDefines(); - } - /** - * 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). - * 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). - */ - get useFresnel() { - return this._useFresnel; - } - set useFresnel(fresnel) { - if (this._useFresnel === fresnel) { - return; - } - this._useFresnel = fresnel; - this._buildPipeline(); - } - /** - * Gets or sets a boolean defining if geometry thickness should be computed automatically (default: false). - * 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). - * 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 - * value than when enableAutomaticThicknessComputation is false (it's even possible to use a value of 0 when using low values for "step") - * Note that for performance reasons, this option will only apply to the first camera to which the the rendering pipeline is attached! - */ - get enableAutomaticThicknessComputation() { - return this._enableAutomaticThicknessComputation; - } - set enableAutomaticThicknessComputation(automatic) { - if (this._enableAutomaticThicknessComputation === automatic) { - return; - } - this._enableAutomaticThicknessComputation = automatic; - this._buildPipeline(); - } - /** - * Gets the depth renderer used to render the back faces of the scene to a depth texture. - */ - get backfaceDepthRenderer() { - return this._depthRenderer; - } - /** - * Gets or sets the downsample factor (default: 0) used to create the backface depth texture - used only if enableAutomaticThicknessComputation = true. - * Use 0 to render the depth at full resolution, 1 to render at half resolution, 2 to render at 1/4 resolution, etc. - * Note that you will get rendering artefacts when using a value different from 0: it's a tradeoff between image quality and performances. - */ - get backfaceDepthTextureDownsample() { - return this._backfaceDepthTextureDownsample; - } - set backfaceDepthTextureDownsample(factor) { - if (this._backfaceDepthTextureDownsample === factor) { - return; - } - this._backfaceDepthTextureDownsample = factor; - this._resizeDepthRenderer(); - } - /** - * 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). - */ - get backfaceForceDepthWriteTransparentMeshes() { - return this._backfaceForceDepthWriteTransparentMeshes; - } - set backfaceForceDepthWriteTransparentMeshes(force) { - if (this._backfaceForceDepthWriteTransparentMeshes === force) { - return; - } - this._backfaceForceDepthWriteTransparentMeshes = force; - if (this._depthRenderer) { - this._depthRenderer.forceDepthWriteTransparentMeshes = force; - } - } - /** - * Gets or sets a boolean indicating if the effect is enabled (default: true). - */ - get isEnabled() { - return this._isEnabled; - } - set isEnabled(value) { - if (this._isEnabled === value) { - return; - } - this._isEnabled = value; - if (!value) { - if (this._cameras !== null) { - this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); - this._cameras = this._camerasToBeAttached.slice(); - } - } - else if (value) { - if (!this._isDirty) { - if (this._cameras !== null) { - this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); - } - } - else { - this._buildPipeline(); - } - } - } - /** - * Gets or sets a boolean defining if the input color texture is in gamma space (default: true) - * 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 - */ - get inputTextureColorIsInGammaSpace() { - return this._inputTextureColorIsInGammaSpace; - } - set inputTextureColorIsInGammaSpace(gammaSpace) { - if (this._inputTextureColorIsInGammaSpace === gammaSpace) { - return; - } - this._inputTextureColorIsInGammaSpace = gammaSpace; - this._buildPipeline(); - } - /** - * Gets or sets a boolean defining if the output color texture generated by the SSR pipeline should be in gamma space (default: true) - * 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 - */ - get generateOutputInGammaSpace() { - return this._generateOutputInGammaSpace; - } - set generateOutputInGammaSpace(gammaSpace) { - if (this._generateOutputInGammaSpace === gammaSpace) { - return; - } - this._generateOutputInGammaSpace = gammaSpace; - this._buildPipeline(); - } - /** - * Gets or sets a boolean indicating if the effect should be rendered in debug mode (default: false). - * In this mode, colors have this meaning: - * - blue: the ray hit the max distance (we reached maxDistance) - * - red: the ray ran out of steps (we reached maxSteps) - * - yellow: the ray went off screen - * - 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. - * 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 - * 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. - */ - get debug() { - return this._debug; - } - set debug(value) { - if (this._debug === value) { - return; - } - this._debug = value; - this._buildPipeline(); - } - /** - * Gets the scene the effect belongs to. - * @returns the scene the effect belongs to. - */ - getScene() { - return this._scene; - } - get _geometryBufferRenderer() { - if (!this._forceGeometryBuffer) { - return null; - } - return this._scene.geometryBufferRenderer; - } - get _prePassRenderer() { - if (this._forceGeometryBuffer) { - return null; - } - return this._scene.prePassRenderer; - } - /** - * Gets active scene - */ - get scene() { - return this._scene; - } - /** - * Returns true if SSR is supported by the running hardware - */ - get isSupported() { - const caps = this._scene.getEngine().getCaps(); - return caps.drawBuffersExtension && caps.texelFetch; - } - /** - * Constructor of the SSR rendering pipeline - * @param name The rendering pipeline name - * @param scene The scene linked to this pipeline - * @param cameras The array of cameras that the rendering pipeline will be attached to (default: scene.cameras) - * @param forceGeometryBuffer Set to true if you want to use the legacy geometry buffer renderer (default: false) - * @param textureType The texture type used by the different post processes created by SSR (default: 0) - */ - constructor(name, scene, cameras, forceGeometryBuffer = false, textureType = 0) { - super(scene.getEngine(), name); - /** - * The SSR PostProcess effect id in the pipeline - */ - this.SSRRenderEffect = "SSRRenderEffect"; - /** - * The blur PostProcess effect id in the pipeline - */ - this.SSRBlurRenderEffect = "SSRBlurRenderEffect"; - /** - * The PostProcess effect id in the pipeline that combines the SSR-Blur output with the original scene color - */ - this.SSRCombineRenderEffect = "SSRCombineRenderEffect"; - this._samples = 1; - /** - * Gets or sets the maxDistance used to define how far we look for reflection during the ray-marching on the reflected ray (default: 1000). - * Note that this value is a view (camera) space distance (not pixels!). - */ - this.maxDistance = 1000.0; - /** - * 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). - * Use higher values to improve performances (but at the expense of quality). - */ - this.step = 1.0; - /** - * Gets or sets the thickness value used as tolerance when computing the intersection between the reflected ray and the scene (default: 0.5). - * If setting "enableAutomaticThicknessComputation" to true, you can use lower values for "thickness" (even 0), as the geometry thickness - * is automatically computed thank to the regular depth buffer + the backface depth buffer - */ - this.thickness = 0.5; - /** - * Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results (default: 1). - */ - this.strength = 1; - /** - * Gets or sets the falloff exponent used to compute the reflection strength. Higher values lead to fainter reflections (default: 1). - */ - this.reflectionSpecularFalloffExponent = 1; - /** - * Maximum number of steps during the ray marching process after which we consider an intersection could not be found (default: 1000). - * Should be an integer value. - */ - this.maxSteps = 1000.0; - /** - * Gets or sets the factor applied when computing roughness. Default value is 0.2. - * When blurring based on roughness is enabled (meaning blurDispersionStrength \> 0), roughnessFactor is used as a global roughness factor applied on all objects. - * If you want to disable this global roughness set it to 0. - */ - this.roughnessFactor = 0.2; - /** - * Number of steps to skip at start when marching the ray to avoid self collisions (default: 1) - * 1 should normally be a good value, depending on the scene you may need to use a higher value (2 or 3) - */ - this.selfCollisionNumSkip = 1; - this._reflectivityThreshold = 0.04; - this._ssrDownsample = 0; - this._blurDispersionStrength = 0.03; - this._blurDownsample = 0; - this._enableSmoothReflections = false; - this._environmentTextureIsProbe = false; - this._attenuateScreenBorders = true; - this._attenuateIntersectionDistance = true; - this._attenuateIntersectionIterations = true; - this._attenuateFacingCamera = false; - this._attenuateBackfaceReflection = false; - this._clipToFrustum = true; - this._useFresnel = false; - this._enableAutomaticThicknessComputation = false; - this._backfaceDepthTextureDownsample = 0; - this._backfaceForceDepthWriteTransparentMeshes = true; - this._isEnabled = true; - this._inputTextureColorIsInGammaSpace = true; - this._generateOutputInGammaSpace = true; - this._debug = false; - this._forceGeometryBuffer = false; - this._isDirty = false; - this._camerasToBeAttached = []; - this._cameras = cameras || scene.cameras; - this._cameras = this._cameras.slice(); - this._camerasToBeAttached = this._cameras.slice(); - this._scene = scene; - this._textureType = textureType; - this._forceGeometryBuffer = forceGeometryBuffer; - if (this.isSupported) { - scene.postProcessRenderPipelineManager.addPipeline(this); - if (this._forceGeometryBuffer) { - const geometryBufferRenderer = scene.enableGeometryBufferRenderer(); - if (geometryBufferRenderer) { - geometryBufferRenderer.enableReflectivity = true; - geometryBufferRenderer.useSpecificClearForDepthTexture = true; - } - } - else { - const prePassRenderer = scene.enablePrePassRenderer(); - if (prePassRenderer) { - prePassRenderer.useSpecificClearForDepthTexture = true; - prePassRenderer.markAsDirty(); - } - } - this._buildPipeline(); - } - } - /** - * Get the class name - * @returns "SSRRenderingPipeline" - */ - getClassName() { - return "SSRRenderingPipeline"; - } - /** - * Adds a camera to the pipeline - * @param camera the camera to be added - */ - addCamera(camera) { - this._camerasToBeAttached.push(camera); - this._buildPipeline(); - } - /** - * Removes a camera from the pipeline - * @param camera the camera to remove - */ - removeCamera(camera) { - const index = this._camerasToBeAttached.indexOf(camera); - this._camerasToBeAttached.splice(index, 1); - this._buildPipeline(); - } - /** - * Removes the internal pipeline assets and detaches the pipeline from the scene cameras - * @param disableGeometryBufferRenderer - */ - dispose(disableGeometryBufferRenderer = false) { - this._disposeDepthRenderer(); - this._disposePostProcesses(); - if (disableGeometryBufferRenderer) { - this._scene.disableGeometryBufferRenderer(); - } - this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); - super.dispose(); - } - _getTextureSize() { - var _a, _b; - const engine = this._scene.getEngine(); - const prePassRenderer = this._prePassRenderer; - let textureSize = { width: engine.getRenderWidth(), height: engine.getRenderHeight() }; - if (prePassRenderer && ((_a = this._scene.activeCamera) === null || _a === void 0 ? void 0 : _a._getFirstPostProcess()) === this._ssrPostProcess) { - const renderTarget = prePassRenderer.getRenderTarget(); - if (renderTarget && renderTarget.textures) { - textureSize = renderTarget.textures[prePassRenderer.getIndex(4)].getSize(); - } - } - else if ((_b = this._ssrPostProcess) === null || _b === void 0 ? void 0 : _b.inputTexture) { - textureSize.width = this._ssrPostProcess.inputTexture.width; - textureSize.height = this._ssrPostProcess.inputTexture.height; - } - return textureSize; - } - _updateEffectDefines() { - var _a; - const defines = []; - if (this._geometryBufferRenderer || this._prePassRenderer) { - defines.push("#define SSR_SUPPORTED"); - } - if (this._enableSmoothReflections) { - defines.push("#define SSRAYTRACE_ENABLE_REFINEMENT"); - } - if (this._scene.useRightHandedSystem) { - defines.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"); - } - if (this._environmentTexture) { - defines.push("#define SSR_USE_ENVIRONMENT_CUBE"); - if (this._environmentTexture.boundingBoxSize) { - defines.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"); - } - if (this._environmentTexture.gammaSpace) { - defines.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE"); - } - } - if (this._environmentTextureIsProbe) { - defines.push("#define SSR_INVERTCUBICMAP"); - } - if (this._enableAutomaticThicknessComputation) { - defines.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"); - } - if (this._attenuateScreenBorders) { - defines.push("#define SSR_ATTENUATE_SCREEN_BORDERS"); - } - if (this._attenuateIntersectionDistance) { - defines.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"); - } - if (this._attenuateIntersectionIterations) { - defines.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"); - } - if (this._attenuateFacingCamera) { - defines.push("#define SSR_ATTENUATE_FACING_CAMERA"); - } - if (this._attenuateBackfaceReflection) { - defines.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"); - } - if (this._clipToFrustum) { - defines.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"); - } - if (this._useBlur()) { - defines.push("#define SSR_USE_BLUR"); - } - if (this._debug) { - defines.push("#define SSRAYTRACE_DEBUG"); - } - if (this._inputTextureColorIsInGammaSpace) { - defines.push("#define SSR_INPUT_IS_GAMMA_SPACE"); - } - if (this._generateOutputInGammaSpace) { - defines.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"); - } - if (this._useFresnel) { - defines.push("#define SSR_BLEND_WITH_FRESNEL"); - } - if (this._reflectivityThreshold === 0) { - defines.push("#define SSR_DISABLE_REFLECTIVITY_TEST"); - } - (_a = this._ssrPostProcess) === null || _a === void 0 ? void 0 : _a.updateEffect(defines.join("\n")); - } - _buildPipeline() { - var _a; - if (!this.isSupported) { - return; - } - if (!this._isEnabled) { - this._isDirty = true; - return; - } - this._isDirty = false; - const engine = this._scene.getEngine(); - this._disposeDepthRenderer(); - this._disposePostProcesses(); - if (this._cameras !== null) { - this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); - // get back cameras to be used to reattach pipeline - this._cameras = this._camerasToBeAttached.slice(); - } - this._reset(); - if (this._enableAutomaticThicknessComputation) { - const camera = (_a = this._cameras) === null || _a === void 0 ? void 0 : _a[0]; - if (camera) { - this._depthRendererCamera = camera; - this._depthRenderer = new DepthRenderer(this._scene, undefined, undefined, undefined, 1, true, "SSRBackDepth"); - this._depthRenderer.clearColor.r = 1e8; // "infinity": put a big value because we use the storeCameraSpaceZ mode - this._depthRenderer.reverseCulling = true; // we generate depth for the back faces - this._depthRenderer.forceDepthWriteTransparentMeshes = this._backfaceForceDepthWriteTransparentMeshes; - this._resizeDepthRenderer(); - camera.customRenderTargets.push(this._depthRenderer.getDepthMap()); - } - } - this._createSSRPostProcess(); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(engine, this.SSRRenderEffect, () => { - return this._ssrPostProcess; - }, true)); - if (this._useBlur()) { - this._createBlurAndCombinerPostProcesses(); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(engine, this.SSRBlurRenderEffect, () => { - return [this._blurPostProcessX, this._blurPostProcessY]; - }, true)); - this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(engine, this.SSRCombineRenderEffect, () => { - return this._blurCombinerPostProcess; - }, true)); - } - if (this._cameras !== null) { - this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); - } - } - _resizeDepthRenderer() { - if (!this._depthRenderer) { - return; - } - const textureSize = this._getTextureSize(); - const depthRendererSize = this._depthRenderer.getDepthMap().getSize(); - const width = Math.floor(textureSize.width / (this._backfaceDepthTextureDownsample + 1)); - const height = Math.floor(textureSize.height / (this._backfaceDepthTextureDownsample + 1)); - if (depthRendererSize.width !== width || depthRendererSize.height !== height) { - this._depthRenderer.getDepthMap().resize({ width, height }); - } - } - _disposeDepthRenderer() { - var _a; - if (this._depthRenderer) { - if (this._depthRendererCamera) { - const idx = (_a = this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())) !== null && _a !== void 0 ? _a : -1; - if (idx !== -1) { - this._depthRendererCamera.customRenderTargets.splice(idx, 1); - } - } - this._depthRendererCamera = null; - this._depthRenderer.getDepthMap().dispose(); - } - this._depthRenderer = null; - } - _disposePostProcesses() { - var _a, _b, _c, _d; - for (let i = 0; i < this._cameras.length; i++) { - const camera = this._cameras[i]; - (_a = this._ssrPostProcess) === null || _a === void 0 ? void 0 : _a.dispose(camera); - (_b = this._blurPostProcessX) === null || _b === void 0 ? void 0 : _b.dispose(camera); - (_c = this._blurPostProcessY) === null || _c === void 0 ? void 0 : _c.dispose(camera); - (_d = this._blurCombinerPostProcess) === null || _d === void 0 ? void 0 : _d.dispose(camera); - } - this._ssrPostProcess = null; - this._blurPostProcessX = null; - this._blurPostProcessY = null; - this._blurCombinerPostProcess = null; - } - _createSSRPostProcess() { - this._ssrPostProcess = new postProcess_PostProcess("ssr", "screenSpaceReflection2", [ - "projection", - "invProjectionMatrix", - "view", - "invView", - "thickness", - "reflectionSpecularFalloffExponent", - "strength", - "stepSize", - "maxSteps", - "roughnessFactor", - "projectionPixel", - "nearPlaneZ", - "maxDistance", - "selfCollisionNumSkip", - "vReflectionPosition", - "vReflectionSize", - "backSizeFactor", - "reflectivityThreshold", - ], ["textureSampler", "normalSampler", "reflectivitySampler", "depthSampler", "envCubeSampler", "backDepthSampler"], 1.0, null, this._textureType, this._scene.getEngine(), false, "", this._textureType); - this._updateEffectDefines(); - this._ssrPostProcess.onApply = (effect) => { - this._resizeDepthRenderer(); - const geometryBufferRenderer = this._geometryBufferRenderer; - const prePassRenderer = this._prePassRenderer; - if (!prePassRenderer && !geometryBufferRenderer) { - return; - } - if (geometryBufferRenderer) { - const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE); - effect.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[1]); - effect.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]); - effect.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[0]); - } - else if (prePassRenderer) { - const depthIndex = prePassRenderer.getIndex(5); - const roughnessIndex = prePassRenderer.getIndex(3); - const normalIndex = prePassRenderer.getIndex(6); - effect.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]); - effect.setTexture("depthSampler", prePassRenderer.getRenderTarget().textures[depthIndex]); - effect.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]); - } - if (this._enableAutomaticThicknessComputation && this._depthRenderer) { - effect.setTexture("backDepthSampler", this._depthRenderer.getDepthMap()); - effect.setFloat("backSizeFactor", this._backfaceDepthTextureDownsample + 1); - } - const camera = this._scene.activeCamera; - if (!camera) { - return; - } - const viewMatrix = camera.getViewMatrix(true); - const projectionMatrix = camera.getProjectionMatrix(true); - projectionMatrix.invertToRef(math_vector_TmpVectors.Matrix[0]); - viewMatrix.invertToRef(math_vector_TmpVectors.Matrix[1]); - effect.setMatrix("projection", projectionMatrix); - effect.setMatrix("view", viewMatrix); - effect.setMatrix("invView", math_vector_TmpVectors.Matrix[1]); - effect.setMatrix("invProjectionMatrix", math_vector_TmpVectors.Matrix[0]); - effect.setFloat("thickness", this.thickness); - effect.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent); - effect.setFloat("strength", this.strength); - effect.setFloat("stepSize", this.step); - effect.setFloat("maxSteps", this.maxSteps); - effect.setFloat("roughnessFactor", this.roughnessFactor); - effect.setFloat("nearPlaneZ", camera.minZ); - effect.setFloat("maxDistance", this.maxDistance); - effect.setFloat("selfCollisionNumSkip", this.selfCollisionNumSkip); - effect.setFloat("reflectivityThreshold", this._reflectivityThreshold); - const textureSize = this._getTextureSize(); - math_vector_Matrix.ScalingToRef(textureSize.width, textureSize.height, 1, math_vector_TmpVectors.Matrix[2]); - projectionMatrix.multiplyToRef(this._scene.getEngine().isWebGPU ? trsWebGPU : trs, math_vector_TmpVectors.Matrix[3]); - math_vector_TmpVectors.Matrix[3].multiplyToRef(math_vector_TmpVectors.Matrix[2], math_vector_TmpVectors.Matrix[4]); - effect.setMatrix("projectionPixel", math_vector_TmpVectors.Matrix[4]); - if (this._environmentTexture) { - effect.setTexture("envCubeSampler", this._environmentTexture); - if (this._environmentTexture.boundingBoxSize) { - effect.setVector3("vReflectionPosition", this._environmentTexture.boundingBoxPosition); - effect.setVector3("vReflectionSize", this._environmentTexture.boundingBoxSize); - } - } - }; - this._ssrPostProcess.samples = this.samples; - if (!this._forceGeometryBuffer) { - this._ssrPostProcess._prePassEffectConfiguration = new ScreenSpaceReflections2Configuration(); - } - } - _createBlurAndCombinerPostProcesses() { - const engine = this._scene.getEngine(); - this._blurPostProcessX = new postProcess_PostProcess("SSRblurX", "screenSpaceReflection2Blur", ["texelOffsetScale"], ["textureSampler"], this._useBlur() ? 1 / (this._ssrDownsample + 1) : 1, null, 2, engine, false, "", this._textureType); - this._blurPostProcessX.autoClear = false; - this._blurPostProcessX.onApplyObservable.add((effect) => { - var _a, _b; - const width = (_b = (_a = this._blurPostProcessX) === null || _a === void 0 ? void 0 : _a.inputTexture.width) !== null && _b !== void 0 ? _b : this._scene.getEngine().getRenderWidth(); - effect.setFloat2("texelOffsetScale", this._blurDispersionStrength / width, 0); - }); - this._blurPostProcessY = new postProcess_PostProcess("SSRblurY", "screenSpaceReflection2Blur", ["texelOffsetScale"], ["textureSampler"], this._useBlur() ? 1 / (this._blurDownsample + 1) : 1, null, 2, engine, false, "", this._textureType); - this._blurPostProcessY.autoClear = false; - this._blurPostProcessY.onApplyObservable.add((effect) => { - var _a, _b; - const height = (_b = (_a = this._blurPostProcessY) === null || _a === void 0 ? void 0 : _a.inputTexture.height) !== null && _b !== void 0 ? _b : this._scene.getEngine().getRenderHeight(); - effect.setFloat2("texelOffsetScale", 0, this._blurDispersionStrength / height); - }); - const uniformNames = ["strength", "reflectionSpecularFalloffExponent", "reflectivityThreshold"]; - const samplerNames = ["textureSampler", "mainSampler", "reflectivitySampler"]; - let defines = ""; - if (this._debug) { - defines += "#define SSRAYTRACE_DEBUG\n"; - } - if (this._inputTextureColorIsInGammaSpace) { - defines += "#define SSR_INPUT_IS_GAMMA_SPACE\n"; - } - if (this._generateOutputInGammaSpace) { - defines += "#define SSR_OUTPUT_IS_GAMMA_SPACE\n"; - } - if (this.useFresnel) { - defines += "#define SSR_BLEND_WITH_FRESNEL\n"; - uniformNames.push("projection", "invProjectionMatrix"); - samplerNames.push("depthSampler", "normalSampler"); - } - if (this._reflectivityThreshold === 0) { - defines += "#define SSR_DISABLE_REFLECTIVITY_TEST"; - } - this._blurCombinerPostProcess = new postProcess_PostProcess("SSRblurCombiner", "screenSpaceReflection2BlurCombiner", uniformNames, samplerNames, this._useBlur() ? 1 / (this._blurDownsample + 1) : 1, null, 1, engine, false, defines, this._textureType); - this._blurCombinerPostProcess.autoClear = false; - this._blurCombinerPostProcess.onApplyObservable.add((effect) => { - var _a; - const geometryBufferRenderer = this._geometryBufferRenderer; - const prePassRenderer = this._prePassRenderer; - if (!prePassRenderer && !geometryBufferRenderer) { - return; - } - if (prePassRenderer && ((_a = this._scene.activeCamera) === null || _a === void 0 ? void 0 : _a._getFirstPostProcess()) === this._ssrPostProcess) { - const renderTarget = prePassRenderer.getRenderTarget(); - if (renderTarget && renderTarget.textures) { - effect.setTexture("mainSampler", renderTarget.textures[prePassRenderer.getIndex(4)]); - } - } - else { - effect.setTextureFromPostProcess("mainSampler", this._ssrPostProcess); - } - if (geometryBufferRenderer) { - const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE); - effect.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]); - if (this.useFresnel) { - effect.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[1]); - effect.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[0]); - } - } - else if (prePassRenderer) { - const roughnessIndex = prePassRenderer.getIndex(3); - effect.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]); - if (this.useFresnel) { - const depthIndex = prePassRenderer.getIndex(5); - const normalIndex = prePassRenderer.getIndex(6); - effect.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]); - effect.setTexture("depthSampler", prePassRenderer.getRenderTarget().textures[depthIndex]); - } - } - effect.setFloat("strength", this.strength); - effect.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent); - effect.setFloat("reflectivityThreshold", this._reflectivityThreshold); - if (this.useFresnel) { - const camera = this._scene.activeCamera; - if (camera) { - const projectionMatrix = camera.getProjectionMatrix(); - projectionMatrix.invertToRef(math_vector_TmpVectors.Matrix[0]); - effect.setMatrix("projection", projectionMatrix); - effect.setMatrix("invProjectionMatrix", math_vector_TmpVectors.Matrix[0]); - } - } - }); - } - /** - * Serializes the rendering pipeline (Used when exporting) - * @returns the serialized object - */ - serialize() { - const serializationObject = decorators_SerializationHelper.Serialize(this); - serializationObject.customType = "SSRRenderingPipeline"; - return serializationObject; - } - /** - * Parse the serialized pipeline - * @param source Source pipeline. - * @param scene The scene to load the pipeline to. - * @param rootUrl The URL of the serialized pipeline. - * @returns An instantiated pipeline from the serialized object. - */ - static Parse(source, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => new SSRRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl); - } -} -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "samples", null); -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "maxDistance", void 0); -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "step", void 0); -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "thickness", void 0); -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "strength", void 0); -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "reflectionSpecularFalloffExponent", void 0); -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "maxSteps", void 0); -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "roughnessFactor", void 0); -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "selfCollisionNumSkip", void 0); -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "_reflectivityThreshold", void 0); -__decorate([ - serialize("_ssrDownsample") -], SSRRenderingPipeline.prototype, "_ssrDownsample", void 0); -__decorate([ - serialize() -], SSRRenderingPipeline.prototype, "ssrDownsample", null); -__decorate([ - serialize("blurDispersionStrength") -], SSRRenderingPipeline.prototype, "_blurDispersionStrength", void 0); -__decorate([ - serialize("blurDownsample") -], SSRRenderingPipeline.prototype, "_blurDownsample", void 0); -__decorate([ - serialize("enableSmoothReflections") -], SSRRenderingPipeline.prototype, "_enableSmoothReflections", void 0); -__decorate([ - serialize("environmentTexture") -], SSRRenderingPipeline.prototype, "_environmentTexture", void 0); -__decorate([ - serialize("environmentTextureIsProbe") -], SSRRenderingPipeline.prototype, "_environmentTextureIsProbe", void 0); -__decorate([ - serialize("attenuateScreenBorders") -], SSRRenderingPipeline.prototype, "_attenuateScreenBorders", void 0); -__decorate([ - serialize("attenuateIntersectionDistance") -], SSRRenderingPipeline.prototype, "_attenuateIntersectionDistance", void 0); -__decorate([ - serialize("attenuateIntersectionIterations") -], SSRRenderingPipeline.prototype, "_attenuateIntersectionIterations", void 0); -__decorate([ - serialize("attenuateFacingCamera") -], SSRRenderingPipeline.prototype, "_attenuateFacingCamera", void 0); -__decorate([ - serialize("attenuateBackfaceReflection") -], SSRRenderingPipeline.prototype, "_attenuateBackfaceReflection", void 0); -__decorate([ - serialize("clipToFrustum") -], SSRRenderingPipeline.prototype, "_clipToFrustum", void 0); -__decorate([ - serialize("useFresnel") -], SSRRenderingPipeline.prototype, "_useFresnel", void 0); -__decorate([ - serialize("enableAutomaticThicknessComputation") -], SSRRenderingPipeline.prototype, "_enableAutomaticThicknessComputation", void 0); -__decorate([ - serialize("backfaceDepthTextureDownsample") -], SSRRenderingPipeline.prototype, "_backfaceDepthTextureDownsample", void 0); -__decorate([ - serialize("backfaceForceDepthWriteTransparentMeshes") -], SSRRenderingPipeline.prototype, "_backfaceForceDepthWriteTransparentMeshes", void 0); -__decorate([ - serialize("isEnabled") -], SSRRenderingPipeline.prototype, "_isEnabled", void 0); -__decorate([ - serialize("inputTextureColorIsInGammaSpace") -], SSRRenderingPipeline.prototype, "_inputTextureColorIsInGammaSpace", void 0); -__decorate([ - serialize("generateOutputInGammaSpace") -], SSRRenderingPipeline.prototype, "_generateOutputInGammaSpace", void 0); -__decorate([ - serialize("debug") -], SSRRenderingPipeline.prototype, "_debug", void 0); -RegisterClass("BABYLON.SSRRenderingPipeline", SSRRenderingPipeline); -//# sourceMappingURL=ssrRenderingPipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/index.js - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/index.js -/* eslint-disable import/no-internal-modules */ - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/tonemap.fragment.js -// Do not edit. - -const tonemap_fragment_name = "tonemapPixelShader"; -const tonemap_fragment_shader = `varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; -#if defined(HABLE_TONEMAPPING) -const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2; -#endif -float Luminance(vec3 c) -{return dot(c,vec3(0.22,0.707,0.071));} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 colour=texture2D(textureSampler,vUV).rgb; -#if defined(REINHARD_TONEMAPPING) -float lum=Luminance(colour.rgb); -float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); -colour*=scale/lum; -#elif defined(HABLE_TONEMAPPING) -colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; -#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) -colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; -#elif defined(PHOTOGRAPHIC_TONEMAPPING) -colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); -#endif -gl_FragColor=vec4(colour.rgb,1.0);}`; -// Sideeffect -ShaderStore.ShadersStore[tonemap_fragment_name] = tonemap_fragment_shader; -/** @internal */ -const tonemapPixelShader = { name: tonemap_fragment_name, shader: tonemap_fragment_shader }; -//# sourceMappingURL=tonemap.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/tonemapPostProcess.js - - - -/** Defines operator used for tonemapping */ -var TonemappingOperator; -(function (TonemappingOperator) { - /** Hable */ - TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable"; - /** Reinhard */ - TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard"; - /** HejiDawson */ - TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson"; - /** Photographic */ - TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic"; -})(TonemappingOperator || (TonemappingOperator = {})); -/** - * Defines a post process to apply tone mapping - */ -class TonemapPostProcess extends (/* unused pure expression or super */ null && (PostProcess)) { - /** - * Gets a string identifying the name of the class - * @returns "TonemapPostProcess" string - */ - getClassName() { - return "TonemapPostProcess"; - } - /** - * Creates a new TonemapPostProcess - * @param name defines the name of the postprocess - * @param _operator defines the operator to use - * @param exposureAdjustment defines the required exposure adjustment - * @param camera defines the camera to use (can be null) - * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default) - * @param engine defines the hosting engine (can be ignore if camera is set) - * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default) - * @param reusable If the post process can be reused on the same frame. (default: false) - */ - constructor(name, _operator, - /** Defines the required exposure adjustment */ - exposureAdjustment, camera, samplingMode = 2, engine, textureFormat = 0, reusable) { - super(name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, reusable, null, textureFormat); - this._operator = _operator; - this.exposureAdjustment = exposureAdjustment; - let defines = "#define "; - if (this._operator === TonemappingOperator.Hable) { - defines += "HABLE_TONEMAPPING"; - } - else if (this._operator === TonemappingOperator.Reinhard) { - defines += "REINHARD_TONEMAPPING"; - } - else if (this._operator === TonemappingOperator.HejiDawson) { - defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING"; - } - else if (this._operator === TonemappingOperator.Photographic) { - defines += "PHOTOGRAPHIC_TONEMAPPING"; - } - //sadly a second call to create the effect. - this.updateEffect(defines); - this.onApply = (effect) => { - effect.setFloat("_ExposureAdjustment", this.exposureAdjustment); - }; - } -} -//# sourceMappingURL=tonemapPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/volumetricLightScattering.fragment.js -// Do not edit. - -const volumetricLightScattering_fragment_name = "volumetricLightScatteringPixelShader"; -const volumetricLightScattering_fragment_shader = `uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i<NUM_SAMPLES; i++) {tc-=deltaTexCoord;vec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;dataSample*=illuminationDecay*weight;color+=dataSample;illuminationDecay*=decay;} -vec4 realColor=texture2D(textureSampler,vUV);gl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4))); -#define CUSTOM_FRAGMENT_MAIN_END -} -`; -// Sideeffect -ShaderStore.ShadersStore[volumetricLightScattering_fragment_name] = volumetricLightScattering_fragment_shader; -/** @internal */ -const volumetricLightScatteringPixelShader = { name: volumetricLightScattering_fragment_name, shader: volumetricLightScattering_fragment_shader }; -//# sourceMappingURL=volumetricLightScattering.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/volumetricLightScatteringPass.vertex.js -// Do not edit. - - - - - - - - - - - -const volumetricLightScatteringPass_vertex_name = "volumetricLightScatteringPassVertexShader"; -const volumetricLightScatteringPass_vertex_shader = `attribute vec3 position; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<instancesDeclaration> -uniform mat4 viewProjection;uniform vec2 depthValues; -#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#if defined(ALPHATEST) || defined(BASIC_RENDER) -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[volumetricLightScatteringPass_vertex_name] = volumetricLightScatteringPass_vertex_shader; -/** @internal */ -const volumetricLightScatteringPassVertexShader = { name: volumetricLightScatteringPass_vertex_name, shader: volumetricLightScatteringPass_vertex_shader }; -//# sourceMappingURL=volumetricLightScatteringPass.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/volumetricLightScatteringPass.fragment.js -// Do not edit. - -const volumetricLightScatteringPass_fragment_name = "volumetricLightScatteringPassPixelShader"; -const volumetricLightScatteringPass_fragment_shader = `#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV; -#endif -#if defined(ALPHATEST) -uniform sampler2D diffuseSampler; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#if defined(ALPHATEST) -vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) -discard; -#endif -gl_FragColor=vec4(0.0,0.0,0.0,1.0);} -`; -// Sideeffect -ShaderStore.ShadersStore[volumetricLightScatteringPass_fragment_name] = volumetricLightScatteringPass_fragment_shader; -/** @internal */ -const volumetricLightScatteringPassPixelShader = { name: volumetricLightScatteringPass_fragment_name, shader: volumetricLightScatteringPass_fragment_shader }; -//# sourceMappingURL=volumetricLightScatteringPass.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/volumetricLightScatteringPostProcess.js - - - - - - - - - - - - - - - - - - - - - -/** - * Inspired by https://developer.nvidia.com/gpugems/gpugems3/part-ii-light-and-shadows/chapter-13-volumetric-light-scattering-post-process - */ -class VolumetricLightScatteringPostProcess extends postProcess_PostProcess { - /** - * @internal - * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead - */ - get useDiffuseColor() { - logger_Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"); - return false; - } - set useDiffuseColor(useDiffuseColor) { - logger_Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"); - } - /** - * @constructor - * @param name The post-process name - * @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) - * @param camera The camera that the post-process will be attached to - * @param mesh The mesh used to create the light scattering - * @param samples The post-process quality, default 100 - * @param samplingMode The post-process filtering mode - * @param engine The babylon engine - * @param reusable If the post-process is reusable - * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided - */ - constructor(name, ratio, camera, mesh, samples = 100, samplingMode = texture_Texture.BILINEAR_SAMPLINGMODE, engine, reusable, scene) { - var _a, _b; - super(name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples); - this._screenCoordinates = math_vector_Vector2.Zero(); - /** - * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true" - */ - this.customMeshPosition = math_vector_Vector3.Zero(); - /** - * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false) - */ - this.useCustomMeshPosition = false; - /** - * If the post-process should inverse the light scattering direction - */ - this.invert = true; - /** - * Array containing the excluded meshes not rendered in the internal pass - */ - this.excludedMeshes = new Array(); - /** - * Array containing the only meshes rendered in the internal pass. - * If this array is not empty, only the meshes from this array are rendered in the internal pass - */ - this.includedMeshes = new Array(); - /** - * Controls the overall intensity of the post-process - */ - this.exposure = 0.3; - /** - * Dissipates each sample's contribution in range [0, 1] - */ - this.decay = 0.96815; - /** - * Controls the overall intensity of each sample - */ - this.weight = 0.58767; - /** - * Controls the density of each sample - */ - this.density = 0.926; - 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. - engine = scene.getEngine(); - this._viewPort = new math_viewport_Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); - // Configure mesh - this.mesh = mesh !== null && mesh !== void 0 ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene); - // Configure - this._createPass(scene, ratio.passRatio || ratio); - this.onActivate = (camera) => { - if (!this.isSupported) { - this.dispose(camera); - } - this.onActivate = null; - }; - this.onApplyObservable.add((effect) => { - this._updateMeshScreenCoordinates(scene); - effect.setTexture("lightScatteringSampler", this._volumetricLightScatteringRTT); - effect.setFloat("exposure", this.exposure); - effect.setFloat("decay", this.decay); - effect.setFloat("weight", this.weight); - effect.setFloat("density", this.density); - effect.setVector2("meshPositionOnScreen", this._screenCoordinates); - }); - } - /** - * Returns the string "VolumetricLightScatteringPostProcess" - * @returns "VolumetricLightScatteringPostProcess" - */ - getClassName() { - return "VolumetricLightScatteringPostProcess"; - } - _isReady(subMesh, useInstances) { - var _a; - const mesh = subMesh.getMesh(); - // Render this.mesh as default - if (mesh === this.mesh && mesh.material) { - return mesh.material.isReady(mesh); - } - const renderingMaterial = (_a = mesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[this._scene.getEngine().currentRenderPassId]; - if (renderingMaterial) { - return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances); - } - const defines = []; - const attribs = [buffer_VertexBuffer.PositionKind]; - const material = subMesh.getMaterial(); - // Alpha test - if (material) { - if (material.needAlphaTesting()) { - defines.push("#define ALPHATEST"); - } - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - attribs.push(buffer_VertexBuffer.UVKind); - defines.push("#define UV1"); - } - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)) { - attribs.push(buffer_VertexBuffer.UV2Kind); - defines.push("#define UV2"); - } - } - // Bones - if (mesh.useBones && mesh.computeBonesUsingShaders) { - attribs.push(buffer_VertexBuffer.MatricesIndicesKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsKind); - defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); - defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0)); - } - else { - defines.push("#define NUM_BONE_INFLUENCERS 0"); - } - // Instances - if (useInstances) { - defines.push("#define INSTANCES"); - MaterialHelper.PushAttributesForInstances(attribs); - if (subMesh.getRenderingMesh().hasThinInstances) { - defines.push("#define THIN_INSTANCES"); - } - } - // Get correct effect - const drawWrapper = subMesh._getDrawWrapper(undefined, true); - const cachedDefines = drawWrapper.defines; - const join = defines.join("\n"); - if (cachedDefines !== join) { - drawWrapper.setEffect(mesh - .getScene() - .getEngine() - .createEffect("volumetricLightScatteringPass", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: mesh.numBoneInfluencers }), join); - } - return drawWrapper.effect.isReady(); - } - /** - * Sets the new light position for light scattering effect - * @param position The new custom light position - */ - setCustomMeshPosition(position) { - this.customMeshPosition = position; - } - /** - * Returns the light position for light scattering effect - * @returns Vector3 The custom light position - */ - getCustomMeshPosition() { - return this.customMeshPosition; - } - /** - * Disposes the internal assets and detaches the post-process from the camera - * @param camera - */ - dispose(camera) { - const rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT); - if (rttIndex !== -1) { - camera.getScene().customRenderTargets.splice(rttIndex, 1); - } - this._volumetricLightScatteringRTT.dispose(); - super.dispose(camera); - } - /** - * Returns the render target texture used by the post-process - * @returns the render target texture used by the post-process - */ - getPass() { - return this._volumetricLightScatteringRTT; - } - // Private methods - _meshExcluded(mesh) { - if ((this.includedMeshes.length > 0 && this.includedMeshes.indexOf(mesh) === -1) || (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1)) { - return true; - } - return false; - } - _createPass(scene, ratio) { - const engine = scene.getEngine(); - this._volumetricLightScatteringRTT = new renderTargetTexture_RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, 0); - this._volumetricLightScatteringRTT.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._volumetricLightScatteringRTT.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._volumetricLightScatteringRTT.renderList = null; - this._volumetricLightScatteringRTT.renderParticles = false; - this._volumetricLightScatteringRTT.ignoreCameraViewport = true; - const camera = this.getCamera(); - if (camera) { - camera.customRenderTargets.push(this._volumetricLightScatteringRTT); - } - else { - scene.customRenderTargets.push(this._volumetricLightScatteringRTT); - } - // Custom render function for submeshes - const renderSubMesh = (subMesh) => { - var _a; - const renderingMesh = subMesh.getRenderingMesh(); - const effectiveMesh = subMesh.getEffectiveMesh(); - if (this._meshExcluded(renderingMesh)) { - return; - } - effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; - const material = subMesh.getMaterial(); - if (!material) { - return; - } - const scene = renderingMesh.getScene(); - const engine = scene.getEngine(); - // Culling - engine.setState(material.backFaceCulling, undefined, undefined, undefined, material.cullBackFaces); - // Managing instances - const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); - if (batch.mustReturn) { - return; - } - const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); - if (this._isReady(subMesh, hardwareInstancedRendering)) { - const renderingMaterial = (_a = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[engine.currentRenderPassId]; - let drawWrapper = subMesh._getDrawWrapper(); - if (renderingMesh === this.mesh && !drawWrapper) { - drawWrapper = material._getDrawWrapper(); - } - if (!drawWrapper) { - return; - } - const effect = drawWrapper.effect; - engine.enableEffect(drawWrapper); - if (!hardwareInstancedRendering) { - renderingMesh._bind(subMesh, effect, material.fillMode); - } - if (renderingMesh === this.mesh) { - material.bind(effectiveMesh.getWorldMatrix(), renderingMesh); - } - else if (renderingMaterial) { - renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh); - } - else { - effect.setMatrix("viewProjection", scene.getTransformMatrix()); - // Alpha test - if (material && material.needAlphaTesting()) { - const alphaTexture = material.getAlphaTestTexture(); - effect.setTexture("diffuseSampler", alphaTexture); - if (alphaTexture) { - effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); - } - } - // Bones - if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { - effect.setMatrices("mBones", renderingMesh.skeleton.getTransformMatrices(renderingMesh)); - } - } - if (hardwareInstancedRendering && renderingMesh.hasThinInstances) { - effect.setMatrix("world", effectiveMesh.getWorldMatrix()); - } - // Draw - renderingMesh._processRendering(effectiveMesh, subMesh, effect, material_Material.TriangleFillMode, batch, hardwareInstancedRendering, (isInstance, world) => { - if (!isInstance) { - effect.setMatrix("world", world); - } - }); - } - }; - // Render target texture callbacks - let savedSceneClearColor; - const sceneClearColor = new math_color_Color4(0.0, 0.0, 0.0, 1.0); - this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(() => { - savedSceneClearColor = scene.clearColor; - scene.clearColor = sceneClearColor; - }); - this._volumetricLightScatteringRTT.onAfterRenderObservable.add(() => { - scene.clearColor = savedSceneClearColor; - }); - this._volumetricLightScatteringRTT.customIsReadyFunction = (mesh, refreshRate, preWarm) => { - if ((preWarm || refreshRate === 0) && mesh.subMeshes) { - for (let i = 0; i < mesh.subMeshes.length; ++i) { - const subMesh = mesh.subMeshes[i]; - const material = subMesh.getMaterial(); - const renderingMesh = subMesh.getRenderingMesh(); - if (!material) { - continue; - } - const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); - const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); - if (!this._isReady(subMesh, hardwareInstancedRendering)) { - return false; - } - } - } - return true; - }; - this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { - const engine = scene.getEngine(); - let index; - if (depthOnlySubMeshes.length) { - engine.setColorWrite(false); - for (index = 0; index < depthOnlySubMeshes.length; index++) { - renderSubMesh(depthOnlySubMeshes.data[index]); - } - engine.setColorWrite(true); - } - for (index = 0; index < opaqueSubMeshes.length; index++) { - renderSubMesh(opaqueSubMeshes.data[index]); - } - for (index = 0; index < alphaTestSubMeshes.length; index++) { - renderSubMesh(alphaTestSubMeshes.data[index]); - } - if (transparentSubMeshes.length) { - // Sort sub meshes - for (index = 0; index < transparentSubMeshes.length; index++) { - const submesh = transparentSubMeshes.data[index]; - const boundingInfo = submesh.getBoundingInfo(); - if (boundingInfo && scene.activeCamera) { - submesh._alphaIndex = submesh.getMesh().alphaIndex; - submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length(); - } - } - const sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length); - sortedArray.sort((a, b) => { - // Alpha index first - if (a._alphaIndex > b._alphaIndex) { - return 1; - } - if (a._alphaIndex < b._alphaIndex) { - return -1; - } - // Then distance to camera - if (a._distanceToCamera < b._distanceToCamera) { - return 1; - } - if (a._distanceToCamera > b._distanceToCamera) { - return -1; - } - return 0; - }); - // Render sub meshes - engine.setAlphaMode(2); - for (index = 0; index < sortedArray.length; index++) { - renderSubMesh(sortedArray[index]); - } - engine.setAlphaMode(0); - } - }; - } - _updateMeshScreenCoordinates(scene) { - const transform = scene.getTransformMatrix(); - let meshPosition; - if (this.useCustomMeshPosition) { - meshPosition = this.customMeshPosition; - } - else if (this.attachedNode) { - meshPosition = this.attachedNode.position; - } - else { - meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position; - } - const pos = math_vector_Vector3.Project(meshPosition, math_vector_Matrix.Identity(), transform, this._viewPort); - this._screenCoordinates.x = pos.x / this._viewPort.width; - this._screenCoordinates.y = pos.y / this._viewPort.height; - if (this.invert) { - this._screenCoordinates.y = 1.0 - this._screenCoordinates.y; - } - } - // Static methods - /** - * Creates a default mesh for the Volumeric Light Scattering post-process - * @param name The mesh name - * @param scene The scene where to create the mesh - * @returns the default mesh - */ - static CreateDefaultMesh(name, scene) { - const mesh = planeBuilder_CreatePlane(name, { size: 1 }, scene); - mesh.billboardMode = abstractMesh_AbstractMesh.BILLBOARDMODE_ALL; - const material = new standardMaterial_StandardMaterial(name + "Material", scene); - material.emissiveColor = new math_color_Color3(1, 1, 1); - mesh.material = material; - return mesh; - } -} -__decorate([ - serializeAsVector3() -], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0); -__decorate([ - serialize() -], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0); -__decorate([ - serialize() -], VolumetricLightScatteringPostProcess.prototype, "invert", void 0); -__decorate([ - serializeAsMeshReference() -], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0); -__decorate([ - serialize() -], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0); -__decorate([ - serialize() -], VolumetricLightScatteringPostProcess.prototype, "includedMeshes", void 0); -__decorate([ - serialize() -], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0); -__decorate([ - serialize() -], VolumetricLightScatteringPostProcess.prototype, "decay", void 0); -__decorate([ - serialize() -], VolumetricLightScatteringPostProcess.prototype, "weight", void 0); -__decorate([ - serialize() -], VolumetricLightScatteringPostProcess.prototype, "density", void 0); -RegisterClass("BABYLON.VolumetricLightScatteringPostProcess", VolumetricLightScatteringPostProcess); -//# sourceMappingURL=volumetricLightScatteringPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/screenSpaceCurvature.fragment.js -// Do not edit. - -const screenSpaceCurvature_fragment_name = "screenSpaceCurvaturePixelShader"; -const screenSpaceCurvature_fragment_shader = `precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform float curvature_ridge;uniform float curvature_valley; -#ifndef CURVATURE_OFFSET -#define CURVATURE_OFFSET 1 -#endif -float curvature_soft_clamp(float curvature,float control) -{if (curvature<0.5/control) -return curvature*(1.0-curvature*control);return 0.25/control;} -float calculate_curvature(ivec2 texel,float ridge,float valley) -{vec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;vec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;vec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;vec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;float normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));if (normal_diff<0.0) -return -2.0*curvature_soft_clamp(-normal_diff,valley);return 2.0*curvature_soft_clamp(normal_diff,ridge);} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ivec2 texel=ivec2(gl_FragCoord.xy);vec4 baseColor=texture2D(textureSampler,vUV);float curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);baseColor.rgb*=curvature+1.0;gl_FragColor=baseColor;}`; -// Sideeffect -ShaderStore.ShadersStore[screenSpaceCurvature_fragment_name] = screenSpaceCurvature_fragment_shader; -/** @internal */ -const screenSpaceCurvaturePixelShader = { name: screenSpaceCurvature_fragment_name, shader: screenSpaceCurvature_fragment_shader }; -//# sourceMappingURL=screenSpaceCurvature.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/screenSpaceCurvaturePostProcess.js - - - - - - - - - -/** - * The Screen Space curvature effect can help highlighting ridge and valley of a model. - */ -class ScreenSpaceCurvaturePostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "ScreenSpaceCurvaturePostProcess" string - */ - getClassName() { - return "ScreenSpaceCurvaturePostProcess"; - } - /** - * Creates a new instance ScreenSpaceCurvaturePostProcess - * @param name The name of the effect. - * @param scene The scene containing the objects to blur according to their velocity. - * @param options The required width/height ratio to downsize to before computing the render pass. - * @param camera The camera to apply the render pass to. - * @param samplingMode The sampling mode to be used when computing the pass. (default: 0) - * @param engine The engine which the post process will be applied. (default: current engine) - * @param reusable If the post process can be reused on the same frame. (default: false) - * @param textureType Type of textures used when performing the post process. (default: 0) - * @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) - */ - constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { - super(name, "screenSpaceCurvature", ["curvature_ridge", "curvature_valley"], ["textureSampler", "normalSampler"], options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation); - /** - * Defines how much ridge the curvature effect displays. - */ - this.ridge = 1; - /** - * Defines how much valley the curvature effect displays. - */ - this.valley = 1; - this._geometryBufferRenderer = scene.enableGeometryBufferRenderer(); - if (!this._geometryBufferRenderer) { - // Geometry buffer renderer is not supported. So, work as a passthrough. - logger_Logger.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first."); - } - else { - // Geometry buffer renderer is supported. - this.onApply = (effect) => { - effect.setFloat("curvature_ridge", 0.5 / Math.max(this.ridge * this.ridge, 1e-4)); - effect.setFloat("curvature_valley", 0.7 / Math.max(this.valley * this.valley, 1e-4)); - const normalTexture = this._geometryBufferRenderer.getGBuffer().textures[1]; - effect.setTexture("normalSampler", normalTexture); - }; - } - } - /** - * Support test. - */ - static get IsSupported() { - const engine = engineStore_EngineStore.LastCreatedEngine; - if (!engine) { - return false; - } - return engine.getCaps().drawBuffersExtension; - } - /** - * @internal - */ - static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { - return decorators_SerializationHelper.Parse(() => { - return new ScreenSpaceCurvaturePostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable); - }, parsedPostProcess, scene, rootUrl); - } -} -__decorate([ - serialize() -], ScreenSpaceCurvaturePostProcess.prototype, "ridge", void 0); -__decorate([ - serialize() -], ScreenSpaceCurvaturePostProcess.prototype, "valley", void 0); -RegisterClass("BABYLON.ScreenSpaceCurvaturePostProcess", ScreenSpaceCurvaturePostProcess); -//# sourceMappingURL=screenSpaceCurvaturePostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Probes/index.js - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/boundingBoxRendererFragmentDeclaration.js -// Do not edit. - -const boundingBoxRendererFragmentDeclaration_name = "boundingBoxRendererFragmentDeclaration"; -const boundingBoxRendererFragmentDeclaration_shader = `uniform vec4 color; -`; -// Sideeffect -ShaderStore.IncludesShadersStore[boundingBoxRendererFragmentDeclaration_name] = boundingBoxRendererFragmentDeclaration_shader; -/** @internal */ -const boundingBoxRendererFragmentDeclaration = { name: boundingBoxRendererFragmentDeclaration_name, shader: boundingBoxRendererFragmentDeclaration_shader }; -//# sourceMappingURL=boundingBoxRendererFragmentDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/boundingBoxRendererUboDeclaration.js -// Do not edit. - -const boundingBoxRendererUboDeclaration_name = "boundingBoxRendererUboDeclaration"; -const boundingBoxRendererUboDeclaration_shader = `#ifdef WEBGL2 -uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -#else -layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[boundingBoxRendererUboDeclaration_name] = boundingBoxRendererUboDeclaration_shader; -/** @internal */ -const boundingBoxRendererUboDeclaration = { name: boundingBoxRendererUboDeclaration_name, shader: boundingBoxRendererUboDeclaration_shader }; -//# sourceMappingURL=boundingBoxRendererUboDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/boundingBoxRenderer.fragment.js -// Do not edit. - - - -const boundingBoxRenderer_fragment_name = "boundingBoxRendererPixelShader"; -const boundingBoxRenderer_fragment_shader = `#include<__decl__boundingBoxRendererFragment> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[boundingBoxRenderer_fragment_name] = boundingBoxRenderer_fragment_shader; -/** @internal */ -const boundingBoxRendererPixelShader = { name: boundingBoxRenderer_fragment_name, shader: boundingBoxRenderer_fragment_shader }; -//# sourceMappingURL=boundingBoxRenderer.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/boundingBoxRendererVertexDeclaration.js -// Do not edit. - -const boundingBoxRendererVertexDeclaration_name = "boundingBoxRendererVertexDeclaration"; -const boundingBoxRendererVertexDeclaration_shader = `uniform mat4 world;uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[boundingBoxRendererVertexDeclaration_name] = boundingBoxRendererVertexDeclaration_shader; -/** @internal */ -const boundingBoxRendererVertexDeclaration = { name: boundingBoxRendererVertexDeclaration_name, shader: boundingBoxRendererVertexDeclaration_shader }; -//# sourceMappingURL=boundingBoxRendererVertexDeclaration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/boundingBoxRenderer.vertex.js -// Do not edit. - - - -const boundingBoxRenderer_vertex_name = "boundingBoxRendererVertexShader"; -const boundingBoxRenderer_vertex_shader = `attribute vec3 position; -#include<__decl__boundingBoxRendererVertex> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec4 worldPos=world*vec4(position,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -} -`; -// Sideeffect -ShaderStore.ShadersStore[boundingBoxRenderer_vertex_name] = boundingBoxRenderer_vertex_shader; -/** @internal */ -const boundingBoxRendererVertexShader = { name: boundingBoxRenderer_vertex_name, shader: boundingBoxRenderer_vertex_shader }; -//# sourceMappingURL=boundingBoxRenderer.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/boundingBoxRenderer.js - - - - - - - - - - - - - - - -Object.defineProperty(scene_Scene.prototype, "forceShowBoundingBoxes", { - get: function () { - return this._forceShowBoundingBoxes || false; - }, - set: function (value) { - this._forceShowBoundingBoxes = value; - // Lazyly creates a BB renderer if needed. - if (value) { - this.getBoundingBoxRenderer(); - } - }, - enumerable: true, - configurable: true, -}); -scene_Scene.prototype.getBoundingBoxRenderer = function () { - if (!this._boundingBoxRenderer) { - this._boundingBoxRenderer = new BoundingBoxRenderer(this); - } - return this._boundingBoxRenderer; -}; -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "showBoundingBox", { - get: function () { - return this._showBoundingBox || false; - }, - set: function (value) { - this._showBoundingBox = value; - // Lazyly creates a BB renderer if needed. - if (value) { - this.getScene().getBoundingBoxRenderer(); - } - }, - enumerable: true, - configurable: true, -}); -/** - * Component responsible of rendering the bounding box of the meshes in a scene. - * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties - */ -class BoundingBoxRenderer { - /** - * Instantiates a new bounding box renderer in a scene. - * @param scene the scene the renderer renders in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_BOUNDINGBOXRENDERER; - /** - * Color of the bounding box lines placed in front of an object - */ - this.frontColor = new math_color_Color3(1, 1, 1); - /** - * Color of the bounding box lines placed behind an object - */ - this.backColor = new math_color_Color3(0.1, 0.1, 0.1); - /** - * Defines if the renderer should show the back lines or not - */ - this.showBackLines = true; - /** - * Observable raised before rendering a bounding box - */ - this.onBeforeBoxRenderingObservable = new observable_Observable(); - /** - * Observable raised after rendering a bounding box - */ - this.onAfterBoxRenderingObservable = new observable_Observable(); - /** - * Observable raised after resources are created - */ - this.onResourcesReadyObservable = new observable_Observable(); - /** - * When false, no bounding boxes will be rendered - */ - this.enabled = true; - /** - * @internal - */ - this.renderList = new SmartArray(32); - this._vertexBuffers = {}; - this._fillIndexBuffer = null; - this._fillIndexData = null; - this.scene = scene; - scene._addComponent(this); - this._uniformBufferFront = new UniformBuffer(this.scene.getEngine(), undefined, undefined, "BoundingBoxRendererFront", !this.scene.getEngine().isWebGPU); - this._buildUniformLayout(this._uniformBufferFront); - this._uniformBufferBack = new UniformBuffer(this.scene.getEngine(), undefined, undefined, "BoundingBoxRendererBack", !this.scene.getEngine().isWebGPU); - this._buildUniformLayout(this._uniformBufferBack); - } - _buildUniformLayout(ubo) { - ubo.addUniform("color", 4); - ubo.addUniform("world", 16); - ubo.addUniform("viewProjection", 16); - ubo.addUniform("viewProjectionR", 16); - ubo.create(); - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._beforeEvaluateActiveMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset); - this.scene._preActiveMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER, this, this._preActiveMesh); - this.scene._evaluateSubMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh); - this.scene._afterRenderingGroupDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render); - } - _evaluateSubMesh(mesh, subMesh) { - if (mesh.showSubMeshesBoundingBox) { - const boundingInfo = subMesh.getBoundingInfo(); - if (boundingInfo !== null && boundingInfo !== undefined) { - boundingInfo.boundingBox._tag = mesh.renderingGroupId; - this.renderList.push(boundingInfo.boundingBox); - } - } - } - _preActiveMesh(mesh) { - if (mesh.showBoundingBox || this.scene.forceShowBoundingBoxes) { - const boundingInfo = mesh.getBoundingInfo(); - boundingInfo.boundingBox._tag = mesh.renderingGroupId; - this.renderList.push(boundingInfo.boundingBox); - } - } - _prepareResources() { - if (this._colorShader) { - return; - } - this._colorShader = new shaderMaterial_ShaderMaterial("colorShader", this.scene, "boundingBoxRenderer", { - attributes: [buffer_VertexBuffer.PositionKind], - uniforms: ["world", "viewProjection", "viewProjectionR", "color"], - uniformBuffers: ["BoundingBoxRenderer"], - }, false); - this._colorShader.doNotSerialize = true; - this._colorShader.reservedDataStore = { - hidden: true, - }; - this._colorShaderForOcclusionQuery = new shaderMaterial_ShaderMaterial("colorShaderOccQuery", this.scene, "boundingBoxRenderer", { - attributes: [buffer_VertexBuffer.PositionKind], - uniforms: ["world", "viewProjection", "viewProjectionR", "color"], - uniformBuffers: ["BoundingBoxRenderer"], - }, true); - this._colorShaderForOcclusionQuery.doNotSerialize = true; - this._colorShaderForOcclusionQuery.reservedDataStore = { - hidden: true, - }; - const engine = this.scene.getEngine(); - const boxdata = CreateBoxVertexData({ size: 1.0 }); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = new buffer_VertexBuffer(engine, boxdata.positions, buffer_VertexBuffer.PositionKind, false); - this._createIndexBuffer(); - this._fillIndexData = boxdata.indices; - this.onResourcesReadyObservable.notifyObservers(this); - } - _createIndexBuffer() { - const engine = this.scene.getEngine(); - 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]); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - const vb = this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - if (vb) { - vb._rebuild(); - } - this._createIndexBuffer(); - } - /** - * @internal - */ - reset() { - this.renderList.reset(); - } - /** - * Render the bounding boxes of a specific rendering group - * @param renderingGroupId defines the rendering group to render - */ - render(renderingGroupId) { - var _a, _b; - if (this.renderList.length === 0 || !this.enabled) { - return; - } - this._prepareResources(); - if (!this._colorShader.isReady()) { - return; - } - const engine = this.scene.getEngine(); - engine.setDepthWrite(false); - const transformMatrix = this.scene.getTransformMatrix(); - for (let boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) { - const boundingBox = this.renderList.data[boundingBoxIndex]; - if (boundingBox._tag !== renderingGroupId) { - continue; - } - this._createWrappersForBoundingBox(boundingBox); - this.onBeforeBoxRenderingObservable.notifyObservers(boundingBox); - const min = boundingBox.minimum; - const max = boundingBox.maximum; - const diff = max.subtract(min); - const median = min.add(diff.scale(0.5)); - const worldMatrix = math_vector_Matrix.Scaling(diff.x, diff.y, diff.z).multiply(math_vector_Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix()); - const useReverseDepthBuffer = engine.useReverseDepthBuffer; - if (this.showBackLines) { - const drawWrapperBack = (_a = boundingBox._drawWrapperBack) !== null && _a !== void 0 ? _a : this._colorShader._getDrawWrapper(); - this._colorShader._preBind(drawWrapperBack); - engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect()); - // Back - if (useReverseDepthBuffer) { - engine.setDepthFunctionToLessOrEqual(); - } - else { - engine.setDepthFunctionToGreaterOrEqual(); - } - this._uniformBufferBack.bindToEffect(drawWrapperBack.effect, "BoundingBoxRenderer"); - this._uniformBufferBack.updateColor4("color", this.backColor, 1); - this._uniformBufferBack.updateMatrix("world", worldMatrix); - this._uniformBufferBack.updateMatrix("viewProjection", transformMatrix); - this._uniformBufferBack.update(); - // Draw order - engine.drawElementsType(material_Material.LineListDrawMode, 0, 24); - } - const drawWrapperFront = (_b = boundingBox._drawWrapperFront) !== null && _b !== void 0 ? _b : this._colorShader._getDrawWrapper(); - this._colorShader._preBind(drawWrapperFront); - engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect()); - // Front - if (useReverseDepthBuffer) { - engine.setDepthFunctionToGreater(); - } - else { - engine.setDepthFunctionToLess(); - } - this._uniformBufferFront.bindToEffect(drawWrapperFront.effect, "BoundingBoxRenderer"); - this._uniformBufferFront.updateColor4("color", this.frontColor, 1); - this._uniformBufferFront.updateMatrix("world", worldMatrix); - this._uniformBufferFront.updateMatrix("viewProjection", transformMatrix); - this._uniformBufferFront.update(); - // Draw order - engine.drawElementsType(material_Material.LineListDrawMode, 0, 24); - this.onAfterBoxRenderingObservable.notifyObservers(boundingBox); - } - this._colorShader.unbind(); - engine.setDepthFunctionToLessOrEqual(); - engine.setDepthWrite(true); - } - _createWrappersForBoundingBox(boundingBox) { - if (!boundingBox._drawWrapperFront) { - const engine = this.scene.getEngine(); - boundingBox._drawWrapperFront = new drawWrapper_DrawWrapper(engine); - boundingBox._drawWrapperBack = new drawWrapper_DrawWrapper(engine); - boundingBox._drawWrapperFront.setEffect(this._colorShader.getEffect()); - boundingBox._drawWrapperBack.setEffect(this._colorShader.getEffect()); - } - } - /** - * In case of occlusion queries, we can render the occlusion bounding box through this method - * @param mesh Define the mesh to render the occlusion bounding box for - */ - renderOcclusionBoundingBox(mesh) { - const engine = this.scene.getEngine(); - if (this._renderPassIdForOcclusionQuery === undefined) { - this._renderPassIdForOcclusionQuery = engine.createRenderPassId(`Render pass for occlusion query`); - } - const currentRenderPassId = engine.currentRenderPassId; - engine.currentRenderPassId = this._renderPassIdForOcclusionQuery; - this._prepareResources(); - const subMesh = mesh.subMeshes[0]; - if (!this._colorShaderForOcclusionQuery.isReady(mesh, undefined, subMesh) || !mesh.hasBoundingInfo) { - engine.currentRenderPassId = currentRenderPassId; - return; - } - if (!this._fillIndexBuffer) { - this._fillIndexBuffer = engine.createIndexBuffer(this._fillIndexData); - } - const useReverseDepthBuffer = engine.useReverseDepthBuffer; - engine.setDepthWrite(false); - engine.setColorWrite(false); - const boundingBox = mesh.getBoundingInfo().boundingBox; - const min = boundingBox.minimum; - const max = boundingBox.maximum; - const diff = max.subtract(min); - const median = min.add(diff.scale(0.5)); - const worldMatrix = math_vector_Matrix.Scaling(diff.x, diff.y, diff.z).multiply(math_vector_Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix()); - const drawWrapper = subMesh._drawWrapper; - this._colorShaderForOcclusionQuery._preBind(drawWrapper); - engine.bindBuffers(this._vertexBuffers, this._fillIndexBuffer, drawWrapper.effect); - if (useReverseDepthBuffer) { - engine.setDepthFunctionToGreater(); - } - else { - engine.setDepthFunctionToLess(); - } - this.scene.resetCachedMaterial(); - this._uniformBufferFront.bindToEffect(drawWrapper.effect, "BoundingBoxRenderer"); - this._uniformBufferFront.updateMatrix("world", worldMatrix); - this._uniformBufferFront.updateMatrix("viewProjection", this.scene.getTransformMatrix()); - this._uniformBufferFront.update(); - engine.drawElementsType(material_Material.TriangleFillMode, 0, 36); - this._colorShaderForOcclusionQuery.unbind(); - engine.setDepthFunctionToLessOrEqual(); - engine.setDepthWrite(true); - engine.setColorWrite(true); - engine.currentRenderPassId = currentRenderPassId; - } - /** - * Dispose and release the resources attached to this renderer. - */ - dispose() { - if (this._renderPassIdForOcclusionQuery !== undefined) { - this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery); - this._renderPassIdForOcclusionQuery = undefined; - } - if (!this._colorShader) { - return; - } - this.onBeforeBoxRenderingObservable.clear(); - this.onAfterBoxRenderingObservable.clear(); - this.onResourcesReadyObservable.clear(); - this.renderList.dispose(); - this._colorShader.dispose(); - this._colorShaderForOcclusionQuery.dispose(); - this._uniformBufferFront.dispose(); - this._uniformBufferBack.dispose(); - const buffer = this._vertexBuffers[buffer_VertexBuffer.PositionKind]; - if (buffer) { - buffer.dispose(); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = null; - } - this.scene.getEngine()._releaseBuffer(this._indexBuffer); - if (this._fillIndexBuffer) { - this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer); - this._fillIndexBuffer = null; - } - } -} -//# sourceMappingURL=boundingBoxRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/depthRendererSceneComponent.js - - - - -scene_Scene.prototype.enableDepthRenderer = function (camera, storeNonLinearDepth = false, force32bitsFloat = false, samplingMode = 3, storeCameraSpaceZ = false) { - camera = camera || this.activeCamera; - if (!camera) { - throw "No camera available to enable depth renderer"; - } - if (!this._depthRenderer) { - this._depthRenderer = {}; - } - if (!this._depthRenderer[camera.id]) { - const supportFullfloat = !!this.getEngine().getCaps().textureFloatRender; - let textureType = 0; - if (this.getEngine().getCaps().textureHalfFloatRender && (!force32bitsFloat || !supportFullfloat)) { - textureType = 2; - } - else if (supportFullfloat) { - textureType = 1; - } - else { - textureType = 0; - } - this._depthRenderer[camera.id] = new DepthRenderer(this, textureType, camera, storeNonLinearDepth, samplingMode, storeCameraSpaceZ); - } - return this._depthRenderer[camera.id]; -}; -scene_Scene.prototype.disableDepthRenderer = function (camera) { - camera = camera || this.activeCamera; - if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) { - return; - } - this._depthRenderer[camera.id].dispose(); -}; -/** - * Defines the Depth Renderer scene component responsible to manage a depth buffer useful - * in several rendering techniques. - */ -class DepthRendererSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_DEPTHRENDERER; - this.scene = scene; - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._gatherRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets); - this.scene._gatherActiveCameraRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing to do for this component - } - /** - * Disposes the component and the associated resources - */ - dispose() { - for (const key in this.scene._depthRenderer) { - this.scene._depthRenderer[key].dispose(); - } - } - _gatherRenderTargets(renderTargets) { - if (this.scene._depthRenderer) { - for (const key in this.scene._depthRenderer) { - const depthRenderer = this.scene._depthRenderer[key]; - if (depthRenderer.enabled && !depthRenderer.useOnlyInActiveCamera) { - renderTargets.push(depthRenderer.getDepthMap()); - } - } - } - } - _gatherActiveCameraRenderTargets(renderTargets) { - if (this.scene._depthRenderer) { - for (const key in this.scene._depthRenderer) { - const depthRenderer = this.scene._depthRenderer[key]; - if (depthRenderer.enabled && depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) { - renderTargets.push(depthRenderer.getDepthMap()); - } - } - } - } -} -DepthRenderer._SceneComponentInitialization = (scene) => { - // Register the G Buffer component to the scene. - let component = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_DEPTHRENDERER); - if (!component) { - component = new DepthRendererSceneComponent(scene); - scene._addComponent(component); - } -}; -//# sourceMappingURL=depthRendererSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/oitFinal.fragment.js -// Do not edit. - -const oitFinal_fragment_name = "oitFinalPixelShader"; -const oitFinal_fragment_shader = `precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( -frontColor.rgb+alphaMultiplier*backColor.rgb, -frontColor.a+backColor.a -);}`; -// Sideeffect -ShaderStore.ShadersStore[oitFinal_fragment_name] = oitFinal_fragment_shader; -/** @internal */ -const oitFinalPixelShader = { name: oitFinal_fragment_name, shader: oitFinal_fragment_shader }; -//# sourceMappingURL=oitFinal.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/oitBackBlend.fragment.js -// Do not edit. - -const oitBackBlend_fragment_name = "oitBackBlendPixelShader"; -const oitBackBlend_fragment_shader = `precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { -discard;}}`; -// Sideeffect -ShaderStore.ShadersStore[oitBackBlend_fragment_name] = oitBackBlend_fragment_shader; -/** @internal */ -const oitBackBlendPixelShader = { name: oitBackBlend_fragment_name, shader: oitBackBlend_fragment_shader }; -//# sourceMappingURL=oitBackBlend.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/depthPeelingRenderer.js -/** - * Implementation based on https://medium.com/@shrekshao_71662/dual-depth-peeling-implementation-in-webgl-11baa061ba4b - */ - - - - - - - - - - - - -class DepthPeelingEffectConfiguration { - constructor() { - /** - * Is this effect enabled - */ - this.enabled = true; - /** - * Name of the configuration - */ - this.name = "depthPeeling"; - /** - * Textures that should be present in the MRT for this effect to work - */ - this.texturesRequired = [4]; - } -} -/** - * The depth peeling renderer that performs - * Order independant transparency (OIT). - * This should not be instanciated directly, as it is part of a scene component - */ -class DepthPeelingRenderer { - /** - * Number of depth peeling passes. As we are using dual depth peeling, each pass two levels of transparency are processed. - */ - get passCount() { - return this._passCount; - } - set passCount(count) { - if (this._passCount === count) { - return; - } - this._passCount = count; - this._createRenderPassIds(); - } - /** - * 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. - */ - get useRenderPasses() { - return this._useRenderPasses; - } - set useRenderPasses(usePasses) { - if (this._useRenderPasses === usePasses) { - return; - } - this._useRenderPasses = usePasses; - this._createRenderPassIds(); - } - /** - * Add a mesh in the exclusion list to prevent it to be handled by the depth peeling renderer - * @param mesh The mesh to exclude from the depth peeling renderer - */ - addExcludedMesh(mesh) { - if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) { - this._excludedMeshes.push(mesh.uniqueId); - } - } - /** - * Remove a mesh from the exclusion list of the depth peeling renderer - * @param mesh The mesh to remove - */ - removeExcludedMesh(mesh) { - const index = this._excludedMeshes.indexOf(mesh.uniqueId); - if (index !== -1) { - this._excludedMeshes.splice(index, 1); - } - } - /** - * Instanciates the depth peeling renderer - * @param scene Scene to attach to - * @param passCount Number of depth layers to peel - * @returns The depth peeling renderer - */ - constructor(scene, passCount = 5) { - this._thinTextures = []; - this._currentPingPongState = 0; - this._layoutCacheFormat = [[true], [true, true], [true, true, true]]; - this._layoutCache = []; - this._candidateSubMeshes = new SmartArray(10); - this._excludedSubMeshes = new SmartArray(10); - this._excludedMeshes = []; - this._colorCache = [ - new math_color_Color4(DepthPeelingRenderer._DEPTH_CLEAR_VALUE, DepthPeelingRenderer._DEPTH_CLEAR_VALUE, 0, 0), - new math_color_Color4(-DepthPeelingRenderer._MIN_DEPTH, DepthPeelingRenderer._MAX_DEPTH, 0, 0), - new math_color_Color4(0, 0, 0, 0), - ]; - this._scene = scene; - this._engine = scene.getEngine(); - this._passCount = passCount; - // We need a depth texture for opaque - if (!scene.enablePrePassRenderer()) { - logger_Logger.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting."); - return; - } - for (let i = 0; i < this._layoutCacheFormat.length; ++i) { - this._layoutCache[i] = this._engine.buildTextureLayout(this._layoutCacheFormat[i]); - } - this._renderPassIds = []; - this.useRenderPasses = false; - this._prePassEffectConfiguration = new DepthPeelingEffectConfiguration(); - this._createTextures(); - this._createEffects(); - } - _createRenderPassIds() { - this._releaseRenderPassIds(); - if (this._useRenderPasses) { - for (let i = 0; i < this._passCount + 1; ++i) { - if (!this._renderPassIds[i]) { - this._renderPassIds[i] = this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${i}`); - } - } - } - } - _releaseRenderPassIds() { - for (let i = 0; i < this._renderPassIds.length; ++i) { - this._engine.releaseRenderPassId(this._renderPassIds[i]); - } - this._renderPassIds = []; - } - _createTextures() { - const size = { - width: this._engine.getRenderWidth(), - height: this._engine.getRenderHeight(), - }; - // 2 for ping pong - this._depthMrts = [new MultiRenderTarget("depthPeelingDepth0", size, 3, this._scene), new MultiRenderTarget("depthPeelingDepth1", size, 3, this._scene)]; - this._colorMrts = [ - new MultiRenderTarget("depthPeelingColor0", size, 2, this._scene, { generateDepthBuffer: false }), - new MultiRenderTarget("depthPeelingColor1", size, 2, this._scene, { generateDepthBuffer: false }), - ]; - this._blendBackMrt = new MultiRenderTarget("depthPeelingBack", size, 1, this._scene, { generateDepthBuffer: false }); - this._outputRT = new renderTargetTexture_RenderTargetTexture("depthPeelingOutput", size, this._scene, false); - // 0 is a depth texture - // 1 is a color texture - const optionsArray = [ - { - format: 7, - samplingMode: 1, - type: this._engine.getCaps().textureFloatLinearFiltering ? 1 : 2, - label: "DepthPeelingRenderer-DepthTexture", - }, - { - format: 5, - samplingMode: 1, - type: 2, - label: "DepthPeelingRenderer-ColorTexture", - }, - ]; - for (let i = 0; i < 2; i++) { - const depthTexture = this._engine._createInternalTexture(size, optionsArray[0], false); - const frontColorTexture = this._engine._createInternalTexture(size, optionsArray[1], false); - const backColorTexture = this._engine._createInternalTexture(size, optionsArray[1], false); - this._depthMrts[i].setInternalTexture(depthTexture, 0); - this._depthMrts[i].setInternalTexture(frontColorTexture, 1); - this._depthMrts[i].setInternalTexture(backColorTexture, 2); - this._colorMrts[i].setInternalTexture(frontColorTexture, 0); - this._colorMrts[i].setInternalTexture(backColorTexture, 1); - this._thinTextures.push(new thinTexture_ThinTexture(depthTexture), new thinTexture_ThinTexture(frontColorTexture), new thinTexture_ThinTexture(backColorTexture)); - } - } - // TODO : explore again MSAA with depth peeling when - // we are able to fetch individual samples in a multisampled renderbuffer - // public set samples(value: number) { - // for (let i = 0; i < 2; i++) { - // this._depthMrts[i].samples = value; - // this._colorMrts[i].samples = value; - // } - // this._scene.prePassRenderer!.samples = value; - // } - _disposeTextures() { - for (let i = 0; i < this._thinTextures.length; i++) { - if (i === 6) { - // Do not dispose the shared texture with the prepass - continue; - } - this._thinTextures[i].dispose(); - } - for (let i = 0; i < 2; i++) { - this._depthMrts[i].dispose(true); - this._colorMrts[i].dispose(true); - this._blendBackMrt.dispose(true); - } - this._outputRT.dispose(); - this._thinTextures = []; - this._colorMrts = []; - this._depthMrts = []; - } - _updateTextures() { - if (this._depthMrts[0].getSize().width !== this._engine.getRenderWidth() || this._depthMrts[0].getSize().height !== this._engine.getRenderHeight()) { - this._disposeTextures(); - this._createTextures(); - } - return this._updateTextureReferences(); - } - _updateTextureReferences() { - var _a; - const prePassRenderer = this._scene.prePassRenderer; - if (!prePassRenderer) { - return false; - } - // Retrieve opaque color texture - const textureIndex = prePassRenderer.getIndex(4); - const prePassTexture = ((_a = prePassRenderer.defaultRT.textures) === null || _a === void 0 ? void 0 : _a.length) ? prePassRenderer.defaultRT.textures[textureIndex].getInternalTexture() : null; - if (!prePassTexture) { - return false; - } - if (this._blendBackTexture !== prePassTexture) { - this._blendBackTexture = prePassTexture; - this._blendBackMrt.setInternalTexture(this._blendBackTexture, 0); - if (this._thinTextures[6]) { - this._thinTextures[6].dispose(); - } - this._thinTextures[6] = new thinTexture_ThinTexture(this._blendBackTexture); - prePassRenderer.defaultRT.renderTarget._shareDepth(this._depthMrts[0].renderTarget); - } - return true; - } - _createEffects() { - this._blendBackEffectWrapper = new EffectWrapper({ - fragmentShader: "oitBackBlend", - useShaderStore: true, - engine: this._engine, - samplerNames: ["uBackColor"], - uniformNames: [], - }); - this._blendBackEffectWrapperPingPong = new EffectWrapper({ - fragmentShader: "oitBackBlend", - useShaderStore: true, - engine: this._engine, - samplerNames: ["uBackColor"], - uniformNames: [], - }); - this._finalEffectWrapper = new EffectWrapper({ - fragmentShader: "oitFinal", - useShaderStore: true, - engine: this._engine, - samplerNames: ["uFrontColor", "uBackColor"], - uniformNames: [], - }); - this._effectRenderer = new EffectRenderer(this._engine); - } - /** - * Links to the prepass renderer - * @param prePassRenderer The scene PrePassRenderer - */ - setPrePassRenderer(prePassRenderer) { - prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration); - } - /** - * Binds depth peeling textures on an effect - * @param effect The effect to bind textures on - */ - bind(effect) { - effect.setTexture("oitDepthSampler", this._thinTextures[this._currentPingPongState * 3]); - effect.setTexture("oitFrontColorSampler", this._thinTextures[this._currentPingPongState * 3 + 1]); - } - _renderSubMeshes(transparentSubMeshes) { - let mapMaterialContext; - if (this._useRenderPasses) { - mapMaterialContext = {}; - } - for (let j = 0; j < transparentSubMeshes.length; j++) { - const material = transparentSubMeshes.data[j].getMaterial(); - let previousShaderHotSwapping = true; - let previousBFC = false; - const subMesh = transparentSubMeshes.data[j]; - let drawWrapper; - let firstDraw = false; - if (this._useRenderPasses) { - drawWrapper = subMesh._getDrawWrapper(); - firstDraw = !drawWrapper; - } - if (material) { - previousShaderHotSwapping = material.allowShaderHotSwapping; - previousBFC = material.backFaceCulling; - material.allowShaderHotSwapping = false; - material.backFaceCulling = false; - } - subMesh.render(false); - if (firstDraw) { - // first time we draw this submesh: we replace the material context - drawWrapper = subMesh._getDrawWrapper(); // we are sure it is now non empty as we just rendered the submesh - if (drawWrapper.materialContext) { - let newMaterialContext = mapMaterialContext[drawWrapper.materialContext.uniqueId]; - if (!newMaterialContext) { - newMaterialContext = mapMaterialContext[drawWrapper.materialContext.uniqueId] = this._engine.createMaterialContext(); - } - subMesh._getDrawWrapper().materialContext = newMaterialContext; - } - } - if (material) { - material.allowShaderHotSwapping = previousShaderHotSwapping; - material.backFaceCulling = previousBFC; - } - } - } - _finalCompose(writeId) { - var _a; - const output = (_a = this._scene.prePassRenderer) === null || _a === void 0 ? void 0 : _a.setCustomOutput(this._outputRT); - if (output) { - this._engine.bindFramebuffer(this._outputRT.renderTarget); - } - else { - this._engine.restoreDefaultFramebuffer(); - } - this._engine.setAlphaMode(0); - this._engine.applyStates(); - this._engine.enableEffect(this._finalEffectWrapper._drawWrapper); - this._finalEffectWrapper.effect.setTexture("uFrontColor", this._thinTextures[writeId * 3 + 1]); - this._finalEffectWrapper.effect.setTexture("uBackColor", this._thinTextures[6]); - this._effectRenderer.render(this._finalEffectWrapper); - } - /** - * Renders transparent submeshes with depth peeling - * @param transparentSubMeshes List of transparent meshes to render - * @returns The array of submeshes that could not be handled by this renderer - */ - render(transparentSubMeshes) { - this._candidateSubMeshes.length = 0; - this._excludedSubMeshes.length = 0; - if (!this._blendBackEffectWrapper.effect.isReady() || - !this._blendBackEffectWrapperPingPong.effect.isReady() || - !this._finalEffectWrapper.effect.isReady() || - !this._updateTextures()) { - return this._excludedSubMeshes; - } - for (let i = 0; i < transparentSubMeshes.length; i++) { - const subMesh = transparentSubMeshes.data[i]; - const material = subMesh.getMaterial(); - const fillMode = material && subMesh.getRenderingMesh()._getRenderingFillMode(material.fillMode); - if (material && - (fillMode === material_Material.TriangleFanDrawMode || fillMode === material_Material.TriangleFillMode || fillMode === material_Material.TriangleStripDrawMode) && - this._excludedMeshes.indexOf(subMesh.getMesh().uniqueId) === -1) { - this._candidateSubMeshes.push(subMesh); - } - else { - this._excludedSubMeshes.push(subMesh); - } - } - if (!this._candidateSubMeshes.length) { - this._engine.bindFramebuffer(this._colorMrts[1].renderTarget); - this._engine.bindAttachments(this._layoutCache[1]); - this._engine.clear(this._colorCache[2], true, false, false); - this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget); - this._finalCompose(1); - return this._excludedSubMeshes; - } - const currentRenderPassId = this._engine.currentRenderPassId; - this._scene.prePassRenderer._enabled = false; - if (this._useRenderPasses) { - this._engine.currentRenderPassId = this._renderPassIds[0]; - } - // Clears - this._engine.bindFramebuffer(this._depthMrts[0].renderTarget); - this._engine.bindAttachments(this._layoutCache[0]); - this._engine.clear(this._colorCache[0], true, false, false); - this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget); - this._engine.bindFramebuffer(this._depthMrts[1].renderTarget); - this._engine.bindAttachments(this._layoutCache[0]); - this._engine.clear(this._colorCache[1], true, false, false); - this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget); - this._engine.bindFramebuffer(this._colorMrts[0].renderTarget); - this._engine.bindAttachments(this._layoutCache[1]); - this._engine.clear(this._colorCache[2], true, false, false); - this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget); - this._engine.bindFramebuffer(this._colorMrts[1].renderTarget); - this._engine.bindAttachments(this._layoutCache[1]); - this._engine.clear(this._colorCache[2], true, false, false); - this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget); - // Draw depth for first pass - this._engine.bindFramebuffer(this._depthMrts[0].renderTarget); - this._engine.bindAttachments(this._layoutCache[0]); - 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 - this._engine.setAlphaEquation(3); - this._engine.depthCullingState.depthMask = false; - this._engine.depthCullingState.depthTest = true; - this._engine.applyStates(); - this._currentPingPongState = 1; - // Render - this._renderSubMeshes(this._candidateSubMeshes); - this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget); - this._scene.resetCachedMaterial(); - // depth peeling ping-pong - let readId = 0; - let writeId = 0; - for (let i = 0; i < this._passCount; i++) { - readId = i % 2; - writeId = 1 - readId; - this._currentPingPongState = readId; - if (this._useRenderPasses) { - this._engine.currentRenderPassId = this._renderPassIds[i + 1]; - } - // Clears - this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget); - this._engine.bindAttachments(this._layoutCache[0]); - this._engine.clear(this._colorCache[0], true, false, false); - this._engine.unBindFramebuffer(this._depthMrts[writeId].renderTarget); - this._engine.bindFramebuffer(this._colorMrts[writeId].renderTarget); - this._engine.bindAttachments(this._layoutCache[1]); - this._engine.clear(this._colorCache[2], true, false, false); - this._engine.unBindFramebuffer(this._colorMrts[writeId].renderTarget); - this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget); - this._engine.bindAttachments(this._layoutCache[2]); - 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 - this._engine.setAlphaEquation(3); - this._engine.depthCullingState.depthTest = false; - this._engine.applyStates(); - // Render - this._renderSubMeshes(this._candidateSubMeshes); - this._engine.unBindFramebuffer(this._depthMrts[writeId].renderTarget); - this._scene.resetCachedMaterial(); - // Back color - this._engine.bindFramebuffer(this._blendBackMrt.renderTarget); - this._engine.bindAttachments(this._layoutCache[0]); - this._engine.setAlphaEquation(0); - this._engine.setAlphaMode(17); - this._engine.applyStates(); - const blendBackEffectWrapper = writeId === 0 || !this._useRenderPasses ? this._blendBackEffectWrapper : this._blendBackEffectWrapperPingPong; - this._engine.enableEffect(blendBackEffectWrapper._drawWrapper); - blendBackEffectWrapper.effect.setTexture("uBackColor", this._thinTextures[writeId * 3 + 2]); - this._effectRenderer.render(blendBackEffectWrapper); - this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget); - } - this._engine.currentRenderPassId = currentRenderPassId; - // Final composition on default FB - this._finalCompose(writeId); - this._scene.prePassRenderer._enabled = true; - this._engine.depthCullingState.depthMask = true; - this._engine.depthCullingState.depthTest = true; - return this._excludedSubMeshes; - } - /** - * Disposes the depth peeling renderer and associated ressources - */ - dispose() { - this._disposeTextures(); - this._blendBackEffectWrapper.dispose(); - this._finalEffectWrapper.dispose(); - this._effectRenderer.dispose(); - this._releaseRenderPassIds(); - } -} -DepthPeelingRenderer._DEPTH_CLEAR_VALUE = -99999.0; -DepthPeelingRenderer._MIN_DEPTH = 0; -DepthPeelingRenderer._MAX_DEPTH = 1; -//# sourceMappingURL=depthPeelingRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/depthPeelingSceneComponent.js - - - - -Object.defineProperty(scene_Scene.prototype, "depthPeelingRenderer", { - get: function () { - if (!this._depthPeelingRenderer) { - let component = this._getComponent(sceneComponent_SceneComponentConstants.NAME_DEPTHPEELINGRENDERER); - if (!component) { - component = new DepthPeelingSceneComponent(this); - this._addComponent(component); - } - } - return this._depthPeelingRenderer; - }, - set: function (value) { - this._depthPeelingRenderer = value; - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(scene_Scene.prototype, "useOrderIndependentTransparency", { - get: function () { - return this._useOrderIndependentTransparency; - }, - set: function (value) { - var _a; - if (this._useOrderIndependentTransparency === value) { - return; - } - this._useOrderIndependentTransparency = value; - this.markAllMaterialsAsDirty(63); - (_a = this.prePassRenderer) === null || _a === void 0 ? void 0 : _a.markAsDirty(); - }, - enumerable: true, - configurable: true, -}); -/** - * Scene component to render order independent transparency with depth peeling - */ -class DepthPeelingSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_DEPTHPEELINGRENDERER; - this.scene = scene; - scene.depthPeelingRenderer = new DepthPeelingRenderer(scene); - } - /** - * Registers the component in a given scene - */ - register() { } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { } - /** - * Disposes the component and the associated resources. - */ - dispose() { - var _a; - (_a = this.scene.depthPeelingRenderer) === null || _a === void 0 ? void 0 : _a.dispose(); - this.scene.depthPeelingRenderer = null; - } -} -//# sourceMappingURL=depthPeelingSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/line.fragment.js -// Do not edit. - - - -const line_fragment_name = "linePixelShader"; -const line_fragment_shader = `#include<clipPlaneFragmentDeclaration> -uniform vec4 color; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[line_fragment_name] = line_fragment_shader; -/** @internal */ -const linePixelShader = { name: line_fragment_name, shader: line_fragment_shader }; -//# sourceMappingURL=line.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/line.vertex.js -// Do not edit. - - - - - -const line_vertex_name = "lineVertexShader"; -const line_vertex_shader = `#include<instancesDeclaration> -#include<clipPlaneVertexDeclaration> -attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#include<instancesVertex> -mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=finalWorld*vec4(position,1.0); -#include<clipPlaneVertex> -#endif -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[line_vertex_name] = line_vertex_shader; -/** @internal */ -const lineVertexShader = { name: line_vertex_name, shader: line_vertex_shader }; -//# sourceMappingURL=line.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/edgesRenderer.js - - - - - - - - - - - - -abstractMesh_AbstractMesh.prototype.disableEdgesRendering = function () { - if (this._edgesRenderer) { - this._edgesRenderer.dispose(); - this._edgesRenderer = null; - } - return this; -}; -abstractMesh_AbstractMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false, options) { - this.disableEdgesRendering(); - this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices, true, options); - return this; -}; -Object.defineProperty(abstractMesh_AbstractMesh.prototype, "edgesRenderer", { - get: function () { - return this._edgesRenderer; - }, - enumerable: true, - configurable: true, -}); -LinesMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false) { - this.disableEdgesRendering(); - this._edgesRenderer = new LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices); - return this; -}; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -InstancedLinesMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false) { - LinesMesh.prototype.enableEdgesRendering.apply(this, arguments); - return this; -}; -/** - * FaceAdjacencies Helper class to generate edges - */ -class FaceAdjacencies { - constructor() { - this.edges = new Array(); - this.edgesConnectedCount = 0; - } -} -/** - * This class is used to generate edges of the mesh that could then easily be rendered in a scene. - */ -class EdgesRenderer { - /** Gets the vertices generated by the edge renderer */ - get linesPositions() { - return this._linesPositions; - } - /** Gets the normals generated by the edge renderer */ - get linesNormals() { - return this._linesNormals; - } - /** Gets the indices generated by the edge renderer */ - get linesIndices() { - return this._linesIndices; - } - /** - * Gets or sets the shader used to draw the lines - */ - get lineShader() { - return this._lineShader; - } - set lineShader(shader) { - this._lineShader = shader; - } - static _GetShader(scene) { - if (!scene._edgeRenderLineShader) { - const shader = new shaderMaterial_ShaderMaterial("lineShader", scene, "line", { - attributes: ["position", "normal"], - uniforms: ["world", "viewProjection", "color", "width", "aspectRatio"], - }, false); - shader.disableDepthWrite = true; - shader.backFaceCulling = false; - shader.checkReadyOnEveryCall = scene.getEngine().isWebGPU; - scene._edgeRenderLineShader = shader; - } - return scene._edgeRenderLineShader; - } - /** - * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh. - * Beware when you use this class with complex objects as the adjacencies computation can be really long - * @param source Mesh used to create edges - * @param epsilon sum of angles in adjacency to check for edge - * @param checkVerticesInsteadOfIndices bases the edges detection on vertices vs indices. Note that this parameter is not used if options.useAlternateEdgeFinder = true - * @param generateEdgesLines - should generate Lines or only prepare resources. - * @param options The options to apply when generating the edges - */ - constructor(source, epsilon = 0.95, checkVerticesInsteadOfIndices = false, generateEdgesLines = true, options) { - var _a; - /** - * Define the size of the edges with an orthographic camera - */ - this.edgesWidthScalerForOrthographic = 1000.0; - /** - * Define the size of the edges with a perspective camera - */ - this.edgesWidthScalerForPerspective = 50.0; - this._linesPositions = new Array(); - this._linesNormals = new Array(); - this._linesIndices = new Array(); - this._buffers = {}; - this._buffersForInstances = {}; - this._checkVerticesInsteadOfIndices = false; - /** Gets or sets a boolean indicating if the edgesRenderer is active */ - this.isEnabled = true; - /** - * List of instances to render in case the source mesh has instances - */ - this.customInstances = new SmartArray(32); - this._source = source; - this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices; - this._options = options !== null && options !== void 0 ? options : null; - this._epsilon = epsilon; - if (this._source.getScene().getEngine().isWebGPU) { - this._drawWrapper = new drawWrapper_DrawWrapper(source.getEngine()); - } - this._prepareRessources(); - if (generateEdgesLines) { - if ((_a = options === null || options === void 0 ? void 0 : options.useAlternateEdgeFinder) !== null && _a !== void 0 ? _a : true) { - this._generateEdgesLinesAlternate(); - } - else { - this._generateEdgesLines(); - } - } - this._meshRebuildObserver = this._source.onRebuildObservable.add(() => { - this._rebuild(); - }); - this._meshDisposeObserver = this._source.onDisposeObservable.add(() => { - this.dispose(); - }); - } - _prepareRessources() { - if (this._lineShader) { - return; - } - this._lineShader = EdgesRenderer._GetShader(this._source.getScene()); - } - /** @internal */ - _rebuild() { - let buffer = this._buffers[buffer_VertexBuffer.PositionKind]; - if (buffer) { - buffer._rebuild(); - } - buffer = this._buffers[buffer_VertexBuffer.NormalKind]; - if (buffer) { - buffer._rebuild(); - } - const scene = this._source.getScene(); - const engine = scene.getEngine(); - this._ib = engine.createIndexBuffer(this._linesIndices); - } - /** - * Releases the required resources for the edges renderer - */ - dispose() { - var _a; - this._source.onRebuildObservable.remove(this._meshRebuildObserver); - this._source.onDisposeObservable.remove(this._meshDisposeObserver); - let buffer = this._buffers[buffer_VertexBuffer.PositionKind]; - if (buffer) { - buffer.dispose(); - this._buffers[buffer_VertexBuffer.PositionKind] = null; - } - buffer = this._buffers[buffer_VertexBuffer.NormalKind]; - if (buffer) { - buffer.dispose(); - this._buffers[buffer_VertexBuffer.NormalKind] = null; - } - if (this._ib) { - this._source.getScene().getEngine()._releaseBuffer(this._ib); - } - this._lineShader.dispose(); - (_a = this._drawWrapper) === null || _a === void 0 ? void 0 : _a.dispose(); - } - _processEdgeForAdjacencies(pa, pb, p0, p1, p2) { - if ((pa === p0 && pb === p1) || (pa === p1 && pb === p0)) { - return 0; - } - if ((pa === p1 && pb === p2) || (pa === p2 && pb === p1)) { - return 1; - } - if ((pa === p2 && pb === p0) || (pa === p0 && pb === p2)) { - return 2; - } - return -1; - } - _processEdgeForAdjacenciesWithVertices(pa, pb, p0, p1, p2) { - const eps = 1e-10; - if ((pa.equalsWithEpsilon(p0, eps) && pb.equalsWithEpsilon(p1, eps)) || (pa.equalsWithEpsilon(p1, eps) && pb.equalsWithEpsilon(p0, eps))) { - return 0; - } - if ((pa.equalsWithEpsilon(p1, eps) && pb.equalsWithEpsilon(p2, eps)) || (pa.equalsWithEpsilon(p2, eps) && pb.equalsWithEpsilon(p1, eps))) { - return 1; - } - if ((pa.equalsWithEpsilon(p2, eps) && pb.equalsWithEpsilon(p0, eps)) || (pa.equalsWithEpsilon(p0, eps) && pb.equalsWithEpsilon(p2, eps))) { - return 2; - } - return -1; - } - /** - * Checks if the pair of p0 and p1 is en edge - * @param faceIndex - * @param edge - * @param faceNormals - * @param p0 - * @param p1 - * @private - */ - _checkEdge(faceIndex, edge, faceNormals, p0, p1) { - let needToCreateLine; - if (edge === undefined) { - needToCreateLine = true; - } - else { - const dotProduct = math_vector_Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]); - needToCreateLine = dotProduct < this._epsilon; - } - if (needToCreateLine) { - this.createLine(p0, p1, this._linesPositions.length / 3); - } - } - /** - * push line into the position, normal and index buffer - * @param p0 - * @param p1 - * @param offset - * @protected - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - createLine(p0, p1, offset) { - // Positions - 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); - // Normals - 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); - // Indices - this._linesIndices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3); - } - /** - * See https://playground.babylonjs.com/#R3JR6V#1 for a visual display of the algorithm - * @param edgePoints - * @param indexTriangle - * @param indices - * @param remapVertexIndices - */ - _tessellateTriangle(edgePoints, indexTriangle, indices, remapVertexIndices) { - const makePointList = (edgePoints, pointIndices, firstIndex) => { - if (firstIndex >= 0) { - pointIndices.push(firstIndex); - } - for (let i = 0; i < edgePoints.length; ++i) { - pointIndices.push(edgePoints[i][0]); - } - }; - let startEdge = 0; - if (edgePoints[1].length >= edgePoints[0].length && edgePoints[1].length >= edgePoints[2].length) { - startEdge = 1; - } - else if (edgePoints[2].length >= edgePoints[0].length && edgePoints[2].length >= edgePoints[1].length) { - startEdge = 2; - } - for (let e = 0; e < 3; ++e) { - if (e === startEdge) { - edgePoints[e].sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)); - } - else { - edgePoints[e].sort((a, b) => (a[1] > b[1] ? -1 : a[1] < b[1] ? 1 : 0)); - } - } - const mainPointIndices = [], otherPointIndices = []; - makePointList(edgePoints[startEdge], mainPointIndices, -1); - const numMainPoints = mainPointIndices.length; - for (let i = startEdge + 2; i >= startEdge + 1; --i) { - makePointList(edgePoints[i % 3], otherPointIndices, i !== startEdge + 2 ? remapVertexIndices[indices[indexTriangle + ((i + 1) % 3)]] : -1); - } - const numOtherPoints = otherPointIndices.length; - const idxMain = 0; - const idxOther = 0; - indices.push(remapVertexIndices[indices[indexTriangle + startEdge]], mainPointIndices[0], otherPointIndices[0]); - indices.push(remapVertexIndices[indices[indexTriangle + ((startEdge + 1) % 3)]], otherPointIndices[numOtherPoints - 1], mainPointIndices[numMainPoints - 1]); - const bucketIsMain = numMainPoints <= numOtherPoints; - const bucketStep = bucketIsMain ? numMainPoints : numOtherPoints; - const bucketLimit = bucketIsMain ? numOtherPoints : numMainPoints; - const bucketIdxLimit = bucketIsMain ? numMainPoints - 1 : numOtherPoints - 1; - const winding = bucketIsMain ? 0 : 1; - let numTris = numMainPoints + numOtherPoints - 2; - let bucketIdx = bucketIsMain ? idxMain : idxOther; - let nbucketIdx = bucketIsMain ? idxOther : idxMain; - const bucketPoints = bucketIsMain ? mainPointIndices : otherPointIndices; - const nbucketPoints = bucketIsMain ? otherPointIndices : mainPointIndices; - let bucket = 0; - while (numTris-- > 0) { - if (winding) { - indices.push(bucketPoints[bucketIdx], nbucketPoints[nbucketIdx]); - } - else { - indices.push(nbucketPoints[nbucketIdx], bucketPoints[bucketIdx]); - } - bucket += bucketStep; - let lastIdx; - if (bucket >= bucketLimit && bucketIdx < bucketIdxLimit) { - lastIdx = bucketPoints[++bucketIdx]; - bucket -= bucketLimit; - } - else { - lastIdx = nbucketPoints[++nbucketIdx]; - } - indices.push(lastIdx); - } - indices[indexTriangle + 0] = indices[indices.length - 3]; - indices[indexTriangle + 1] = indices[indices.length - 2]; - indices[indexTriangle + 2] = indices[indices.length - 1]; - indices.length = indices.length - 3; - } - _generateEdgesLinesAlternate() { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; - const positions = this._source.getVerticesData(buffer_VertexBuffer.PositionKind); - let indices = this._source.getIndices(); - if (!indices || !positions) { - return; - } - if (!Array.isArray(indices)) { - indices = Array.from(indices); - } - /** - * Find all vertices that are at the same location (with an epsilon) and remapp them on the same vertex - */ - const useFastVertexMerger = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.useFastVertexMerger) !== null && _b !== void 0 ? _b : true; - 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; - const remapVertexIndices = []; - const uniquePositions = []; // list of unique index of vertices - needed for tessellation - if (useFastVertexMerger) { - const mapVertices = {}; - for (let v1 = 0; v1 < positions.length; v1 += 3) { - const x1 = positions[v1 + 0], y1 = positions[v1 + 1], z1 = positions[v1 + 2]; - const key = x1.toFixed(epsVertexMerge) + "|" + y1.toFixed(epsVertexMerge) + "|" + z1.toFixed(epsVertexMerge); - if (mapVertices[key] !== undefined) { - remapVertexIndices.push(mapVertices[key]); - } - else { - const idx = v1 / 3; - mapVertices[key] = idx; - remapVertexIndices.push(idx); - uniquePositions.push(idx); - } - } - } - else { - for (let v1 = 0; v1 < positions.length; v1 += 3) { - const x1 = positions[v1 + 0], y1 = positions[v1 + 1], z1 = positions[v1 + 2]; - let found = false; - for (let v2 = 0; v2 < v1 && !found; v2 += 3) { - const x2 = positions[v2 + 0], y2 = positions[v2 + 1], z2 = positions[v2 + 2]; - if (Math.abs(x1 - x2) < epsVertexMerge && Math.abs(y1 - y2) < epsVertexMerge && Math.abs(z1 - z2) < epsVertexMerge) { - remapVertexIndices.push(v2 / 3); - found = true; - break; - } - } - if (!found) { - remapVertexIndices.push(v1 / 3); - uniquePositions.push(v1 / 3); - } - } - } - if ((_g = this._options) === null || _g === void 0 ? void 0 : _g.applyTessellation) { - /** - * Tessellate triangles if necessary: - * - * A - * + - * |\ - * | \ - * | \ - * E + \ - * /| \ - * / | \ - * / | \ - * +---+-------+ B - * D C - * - * 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. - * - * 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 - */ - // First step: collect the triangles to tessellate - const epsVertexAligned = (_j = (_h = this._options) === null || _h === void 0 ? void 0 : _h.epsilonVertexAligned) !== null && _j !== void 0 ? _j : 1e-6; - const mustTesselate = []; // liste of triangles that must be tessellated - for (let index = 0; index < indices.length; index += 3) { - // loop over all triangles - let triangleToTessellate; - for (let i = 0; i < 3; ++i) { - // loop over the 3 edges of the triangle - const p0Index = remapVertexIndices[indices[index + i]]; - const p1Index = remapVertexIndices[indices[index + ((i + 1) % 3)]]; - const p2Index = remapVertexIndices[indices[index + ((i + 2) % 3)]]; - if (p0Index === p1Index) { - continue; - } // degenerated triangle - don't process - const p0x = positions[p0Index * 3 + 0], p0y = positions[p0Index * 3 + 1], p0z = positions[p0Index * 3 + 2]; - const p1x = positions[p1Index * 3 + 0], p1y = positions[p1Index * 3 + 1], p1z = positions[p1Index * 3 + 2]; - const p0p1 = Math.sqrt((p1x - p0x) * (p1x - p0x) + (p1y - p0y) * (p1y - p0y) + (p1z - p0z) * (p1z - p0z)); - for (let v = 0; v < uniquePositions.length - 1; v++) { - // loop over all (unique) vertices and look for the ones that would be in-between p0 and p1 - const vIndex = uniquePositions[v]; - if (vIndex === p0Index || vIndex === p1Index || vIndex === p2Index) { - continue; - } // don't handle the vertex if it is a vertex of the current triangle - const x = positions[vIndex * 3 + 0], y = positions[vIndex * 3 + 1], z = positions[vIndex * 3 + 2]; - const p0p = Math.sqrt((x - p0x) * (x - p0x) + (y - p0y) * (y - p0y) + (z - p0z) * (z - p0z)); - const pp1 = Math.sqrt((x - p1x) * (x - p1x) + (y - p1y) * (y - p1y) + (z - p1z) * (z - p1z)); - if (Math.abs(p0p + pp1 - p0p1) < epsVertexAligned) { - // vertices are aligned and p in-between p0 and p1 if distance(p0, p) + distance (p, p1) ~ distance(p0, p1) - if (!triangleToTessellate) { - triangleToTessellate = { - index: index, - edgesPoints: [[], [], []], - }; - mustTesselate.push(triangleToTessellate); - } - triangleToTessellate.edgesPoints[i].push([vIndex, p0p]); - } - } - } - } - // Second step: tesselate the triangles - for (let t = 0; t < mustTesselate.length; ++t) { - const triangle = mustTesselate[t]; - this._tessellateTriangle(triangle.edgesPoints, triangle.index, indices, remapVertexIndices); - } - mustTesselate.length = 0; - } - /** - * Collect the edges to render - */ - const edges = {}; - for (let index = 0; index < indices.length; index += 3) { - let faceNormal; - for (let i = 0; i < 3; ++i) { - let p0Index = remapVertexIndices[indices[index + i]]; - let p1Index = remapVertexIndices[indices[index + ((i + 1) % 3)]]; - const p2Index = remapVertexIndices[indices[index + ((i + 2) % 3)]]; - if (p0Index === p1Index || ((p0Index === p2Index || p1Index === p2Index) && ((_k = this._options) === null || _k === void 0 ? void 0 : _k.removeDegeneratedTriangles))) { - continue; - } - math_vector_TmpVectors.Vector3[0].copyFromFloats(positions[p0Index * 3 + 0], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]); - math_vector_TmpVectors.Vector3[1].copyFromFloats(positions[p1Index * 3 + 0], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]); - math_vector_TmpVectors.Vector3[2].copyFromFloats(positions[p2Index * 3 + 0], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]); - if (!faceNormal) { - math_vector_TmpVectors.Vector3[1].subtractToRef(math_vector_TmpVectors.Vector3[0], math_vector_TmpVectors.Vector3[3]); - math_vector_TmpVectors.Vector3[2].subtractToRef(math_vector_TmpVectors.Vector3[1], math_vector_TmpVectors.Vector3[4]); - faceNormal = math_vector_Vector3.Cross(math_vector_TmpVectors.Vector3[3], math_vector_TmpVectors.Vector3[4]); - faceNormal.normalize(); - } - if (p0Index > p1Index) { - const tmp = p0Index; - p0Index = p1Index; - p1Index = tmp; - } - const key = p0Index + "_" + p1Index; - const ei = edges[key]; - if (ei) { - if (!ei.done) { - const dotProduct = math_vector_Vector3.Dot(faceNormal, ei.normal); - if (dotProduct < this._epsilon) { - this.createLine(math_vector_TmpVectors.Vector3[0], math_vector_TmpVectors.Vector3[1], this._linesPositions.length / 3); - } - ei.done = true; - } - } - else { - edges[key] = { normal: faceNormal, done: false, index: index, i: i }; - } - } - } - for (const key in edges) { - const ei = edges[key]; - if (!ei.done) { - // Orphaned edge - we must display it - const p0Index = remapVertexIndices[indices[ei.index + ei.i]]; - const p1Index = remapVertexIndices[indices[ei.index + ((ei.i + 1) % 3)]]; - math_vector_TmpVectors.Vector3[0].copyFromFloats(positions[p0Index * 3 + 0], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]); - math_vector_TmpVectors.Vector3[1].copyFromFloats(positions[p1Index * 3 + 0], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]); - this.createLine(math_vector_TmpVectors.Vector3[0], math_vector_TmpVectors.Vector3[1], this._linesPositions.length / 3); - } - } - /** - * Merge into a single mesh - */ - const engine = this._source.getScene().getEngine(); - this._buffers[buffer_VertexBuffer.PositionKind] = new buffer_VertexBuffer(engine, this._linesPositions, buffer_VertexBuffer.PositionKind, false); - this._buffers[buffer_VertexBuffer.NormalKind] = new buffer_VertexBuffer(engine, this._linesNormals, buffer_VertexBuffer.NormalKind, false, false, 4); - this._buffersForInstances[buffer_VertexBuffer.PositionKind] = this._buffers[buffer_VertexBuffer.PositionKind]; - this._buffersForInstances[buffer_VertexBuffer.NormalKind] = this._buffers[buffer_VertexBuffer.NormalKind]; - this._ib = engine.createIndexBuffer(this._linesIndices); - this._indicesCount = this._linesIndices.length; - } - /** - * Generates lines edges from adjacencjes - * @private - */ - _generateEdgesLines() { - const positions = this._source.getVerticesData(buffer_VertexBuffer.PositionKind); - const indices = this._source.getIndices(); - if (!indices || !positions) { - return; - } - // First let's find adjacencies - const adjacencies = new Array(); - const faceNormals = new Array(); - let index; - let faceAdjacencies; - // Prepare faces - for (index = 0; index < indices.length; index += 3) { - faceAdjacencies = new FaceAdjacencies(); - const p0Index = indices[index]; - const p1Index = indices[index + 1]; - const p2Index = indices[index + 2]; - faceAdjacencies.p0 = new math_vector_Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]); - faceAdjacencies.p1 = new math_vector_Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]); - faceAdjacencies.p2 = new math_vector_Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]); - const faceNormal = math_vector_Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1)); - faceNormal.normalize(); - faceNormals.push(faceNormal); - adjacencies.push(faceAdjacencies); - } - // Scan - for (index = 0; index < adjacencies.length; index++) { - faceAdjacencies = adjacencies[index]; - for (let otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) { - const otherFaceAdjacencies = adjacencies[otherIndex]; - if (faceAdjacencies.edgesConnectedCount === 3) { - // Full - break; - } - if (otherFaceAdjacencies.edgesConnectedCount === 3) { - // Full - continue; - } - const otherP0 = indices[otherIndex * 3]; - const otherP1 = indices[otherIndex * 3 + 1]; - const otherP2 = indices[otherIndex * 3 + 2]; - for (let edgeIndex = 0; edgeIndex < 3; edgeIndex++) { - let otherEdgeIndex = 0; - if (faceAdjacencies.edges[edgeIndex] !== undefined) { - continue; - } - switch (edgeIndex) { - case 0: - if (this._checkVerticesInsteadOfIndices) { - otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2); - } - else { - otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2); - } - break; - case 1: - if (this._checkVerticesInsteadOfIndices) { - otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2); - } - else { - otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2); - } - break; - case 2: - if (this._checkVerticesInsteadOfIndices) { - otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2); - } - else { - otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2); - } - break; - } - if (otherEdgeIndex === -1) { - continue; - } - faceAdjacencies.edges[edgeIndex] = otherIndex; - otherFaceAdjacencies.edges[otherEdgeIndex] = index; - faceAdjacencies.edgesConnectedCount++; - otherFaceAdjacencies.edgesConnectedCount++; - if (faceAdjacencies.edgesConnectedCount === 3) { - break; - } - } - } - } - // Create lines - for (index = 0; index < adjacencies.length; index++) { - // 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 - const current = adjacencies[index]; - this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1); - this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2); - this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0); - } - // Merge into a single mesh - const engine = this._source.getScene().getEngine(); - this._buffers[buffer_VertexBuffer.PositionKind] = new buffer_VertexBuffer(engine, this._linesPositions, buffer_VertexBuffer.PositionKind, false); - this._buffers[buffer_VertexBuffer.NormalKind] = new buffer_VertexBuffer(engine, this._linesNormals, buffer_VertexBuffer.NormalKind, false, false, 4); - this._buffersForInstances[buffer_VertexBuffer.PositionKind] = this._buffers[buffer_VertexBuffer.PositionKind]; - this._buffersForInstances[buffer_VertexBuffer.NormalKind] = this._buffers[buffer_VertexBuffer.NormalKind]; - this._ib = engine.createIndexBuffer(this._linesIndices); - this._indicesCount = this._linesIndices.length; - } - /** - * Checks whether or not the edges renderer is ready to render. - * @returns true if ready, otherwise false. - */ - isReady() { - return this._lineShader.isReady(this._source, (this._source.hasInstances && this.customInstances.length > 0) || this._source.hasThinInstances); - } - /** - * Renders the edges of the attached mesh, - */ - render() { - const scene = this._source.getScene(); - const currentDrawWrapper = this._lineShader._getDrawWrapper(); - if (this._drawWrapper) { - this._lineShader._setDrawWrapper(this._drawWrapper); - } - if (!this.isReady() || !scene.activeCamera) { - this._lineShader._setDrawWrapper(currentDrawWrapper); - return; - } - const hasInstances = this._source.hasInstances && this.customInstances.length > 0; - const useBuffersWithInstances = hasInstances || this._source.hasThinInstances; - let instanceCount = 0; - if (useBuffersWithInstances) { - 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"); - if (hasInstances) { - const instanceStorage = this._source._instanceDataStorage; - instanceCount = this.customInstances.length; - if (!instanceStorage.instancesData) { - if (!this._source.getScene()._activeMeshesFrozen) { - this.customInstances.reset(); - } - return; - } - if (!instanceStorage.isFrozen) { - let offset = 0; - for (let i = 0; i < instanceCount; ++i) { - this.customInstances.data[i].copyToArray(instanceStorage.instancesData, offset); - offset += 16; - } - instanceStorage.instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instanceCount); - } - } - else { - instanceCount = this._source.thinInstanceCount; - } - } - const engine = scene.getEngine(); - this._lineShader._preBind(); - if (this._source.edgesColor.a !== 1) { - engine.setAlphaMode(2); - } - else { - engine.setAlphaMode(0); - } - // VBOs - engine.bindBuffers(useBuffersWithInstances ? this._buffersForInstances : this._buffers, this._ib, this._lineShader.getEffect()); - scene.resetCachedMaterial(); - this._lineShader.setColor4("color", this._source.edgesColor); - if (scene.activeCamera.mode === camera_Camera.ORTHOGRAPHIC_CAMERA) { - this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic); - } - else { - this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective); - } - this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera)); - this._lineShader.bind(this._source.getWorldMatrix()); - // Draw order - engine.drawElementsType(material_Material.TriangleFillMode, 0, this._indicesCount, instanceCount); - this._lineShader.unbind(); - if (useBuffersWithInstances) { - engine.unbindInstanceAttributes(); - } - if (!this._source.getScene()._activeMeshesFrozen) { - this.customInstances.reset(); - } - this._lineShader._setDrawWrapper(currentDrawWrapper); - } -} -/** - * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation - */ -class LineEdgesRenderer extends EdgesRenderer { - /** - * This constructor turns off auto generating edges line in Edges Renderer to make it here. - * @param source LineMesh used to generate edges - * @param epsilon not important (specified angle for edge detection) - * @param checkVerticesInsteadOfIndices not important for LineMesh - */ - constructor(source, epsilon = 0.95, checkVerticesInsteadOfIndices = false) { - super(source, epsilon, checkVerticesInsteadOfIndices, false); - this._generateEdgesLines(); - } - /** - * Generate edges for each line in LinesMesh. Every Line should be rendered as edge. - */ - _generateEdgesLines() { - const positions = this._source.getVerticesData(buffer_VertexBuffer.PositionKind); - const indices = this._source.getIndices(); - if (!indices || !positions) { - return; - } - const p0 = math_vector_TmpVectors.Vector3[0]; - const p1 = math_vector_TmpVectors.Vector3[1]; - const len = indices.length - 1; - for (let i = 0, offset = 0; i < len; i += 2, offset += 4) { - math_vector_Vector3.FromArrayToRef(positions, 3 * indices[i], p0); - math_vector_Vector3.FromArrayToRef(positions, 3 * indices[i + 1], p1); - this.createLine(p0, p1, offset); - } - // Merge into a single mesh - const engine = this._source.getScene().getEngine(); - this._buffers[buffer_VertexBuffer.PositionKind] = new buffer_VertexBuffer(engine, this._linesPositions, buffer_VertexBuffer.PositionKind, false); - this._buffers[buffer_VertexBuffer.NormalKind] = new buffer_VertexBuffer(engine, this._linesNormals, buffer_VertexBuffer.NormalKind, false, false, 4); - this._ib = engine.createIndexBuffer(this._linesIndices); - this._indicesCount = this._linesIndices.length; - } -} -//# sourceMappingURL=edgesRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Materials/Textures/prePassRenderTarget.js - - -/** - * A multi render target designed to render the prepass. - * Prepass is a scene component used to render information in multiple textures - * alongside with the scene materials rendering. - * Note : This is an internal class, and you should NOT need to instanciate this. - * Only the `PrePassRenderer` should instanciate this class. - * It is more likely that you need a regular `MultiRenderTarget` - * @internal - */ -class PrePassRenderTarget extends MultiRenderTarget { - constructor(name, renderTargetTexture, size, count, scene, options) { - super(name, size, count, scene, options); - /** - * @internal - */ - this._beforeCompositionPostProcesses = []; - /** - * @internal - */ - this._internalTextureDirty = false; - /** - * Is this render target enabled for prepass rendering - */ - this.enabled = false; - /** - * Render target associated with this prePassRenderTarget - * If this is `null`, it means this prePassRenderTarget is associated with the scene - */ - this.renderTargetTexture = null; - this.renderTargetTexture = renderTargetTexture; - } - /** - * Creates a composition effect for this RT - * @internal - */ - _createCompositionEffect() { - this.imageProcessingPostProcess = new ImageProcessingPostProcess("prePassComposition", 1, null, undefined, this._engine); - this.imageProcessingPostProcess._updateParameters(); - } - /** - * Checks that the size of this RT is still adapted to the desired render size. - * @internal - */ - _checkSize() { - const requiredWidth = this._engine.getRenderWidth(true); - const requiredHeight = this._engine.getRenderHeight(true); - const width = this.getRenderWidth(); - const height = this.getRenderHeight(); - if (width !== requiredWidth || height !== requiredHeight) { - this.resize({ width: requiredWidth, height: requiredHeight }); - this._internalTextureDirty = true; - } - } - /** - * Changes the number of render targets in this MRT - * Be careful as it will recreate all the data in the new texture. - * @param count new texture count - * @param options Specifies texture types and sampling modes for new textures - * @param textureNames Specifies the names of the textures (optional) - */ - updateCount(count, options, textureNames) { - super.updateCount(count, options, textureNames); - this._internalTextureDirty = true; - } - /** - * Resets the post processes chains applied to this RT. - * @internal - */ - _resetPostProcessChain() { - this._beforeCompositionPostProcesses.length = 0; - } - /** - * Diposes this render target - */ - dispose() { - const scene = this._scene; - super.dispose(); - if (scene && scene.prePassRenderer) { - const index = scene.prePassRenderer.renderTargets.indexOf(this); - if (index !== -1) { - scene.prePassRenderer.renderTargets.splice(index, 1); - } - } - if (this.imageProcessingPostProcess) { - this.imageProcessingPostProcess.dispose(); - } - if (this.renderTargetTexture) { - this.renderTargetTexture._prePassRenderTarget = null; - } - if (this._outputPostProcess) { - this._outputPostProcess.autoClear = true; - this._outputPostProcess.restoreDefaultInputTexture(); - } - } -} -//# sourceMappingURL=prePassRenderTarget.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/prePassRenderer.js - - - - - - -/** - * Renders a pre pass of the scene - * This means every mesh in the scene will be rendered to a render target texture - * And then this texture will be composited to the rendering canvas with post processes - * It is necessary for effects like subsurface scattering or deferred shading - */ -class PrePassRenderer { - /** - * Returns the index of a texture in the multi render target texture array. - * @param type Texture type - * @returns The index - */ - getIndex(type) { - return this._textureIndices[type]; - } - /** - * How many samples are used for MSAA of the scene render target - */ - get samples() { - return this.defaultRT.samples; - } - set samples(n) { - this.defaultRT.samples = 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) - * If set to false, the depth texture is always cleared with 0. - */ - get useSpecificClearForDepthTexture() { - return this._useSpecificClearForDepthTexture; - } - set useSpecificClearForDepthTexture(value) { - if (this._useSpecificClearForDepthTexture === value) { - return; - } - this._useSpecificClearForDepthTexture = value; - this._isDirty = true; - } - /** - * @returns the prepass render target for the rendering pass. - * If we are currently rendering a render target, it returns the PrePassRenderTarget - * associated with that render target. Otherwise, it returns the scene default PrePassRenderTarget - */ - getRenderTarget() { - return this._currentTarget; - } - /** - * @internal - * Managed by the scene component - * @param prePassRenderTarget - */ - _setRenderTarget(prePassRenderTarget) { - var _a, _b; - if (prePassRenderTarget) { - this._currentTarget = prePassRenderTarget; - } - else { - this._currentTarget = this.defaultRT; - this._engine.currentRenderPassId = (_b = (_a = this._scene.activeCamera) === null || _a === void 0 ? void 0 : _a.renderPassId) !== null && _b !== void 0 ? _b : this._currentTarget.renderPassId; - } - } - /** - * Returns true if the currently rendered prePassRenderTarget is the one - * associated with the scene. - */ - get currentRTisSceneRT() { - return this._currentTarget === this.defaultRT; - } - _refreshGeometryBufferRendererLink() { - if (!this.doNotUseGeometryRendererFallback) { - this._geometryBuffer = this._scene.enableGeometryBufferRenderer(); - if (!this._geometryBuffer) { - // Not supported - this.doNotUseGeometryRendererFallback = true; - return; - } - this._geometryBuffer._linkPrePassRenderer(this); - } - else { - if (this._geometryBuffer) { - this._geometryBuffer._unlinkPrePassRenderer(); - } - this._geometryBuffer = null; - this._scene.disableGeometryBufferRenderer(); - } - } - /** - * Indicates if the prepass is enabled - */ - get enabled() { - return this._enabled; - } - /** - * Instantiates a prepass renderer - * @param scene The scene - */ - constructor(scene) { - /** - * To save performance, we can excluded skinned meshes from the prepass - */ - this.excludedSkinnedMesh = []; - /** - * Force material to be excluded from the prepass - * Can be useful when `useGeometryBufferFallback` is set to `true` - * and you don't want a material to show in the effect. - */ - this.excludedMaterials = []; - /** - * Number of textures in the multi render target texture where the scene is directly rendered - */ - this.mrtCount = 0; - this._mrtTypes = []; - this._mrtFormats = []; - this._mrtLayout = []; - this._mrtNames = []; - this._textureIndices = []; - this._useSpecificClearForDepthTexture = false; - this._isDirty = true; - /** - * Configuration for prepass effects - */ - this._effectConfigurations = []; - /** - * Prevents the PrePassRenderer from using the GeometryBufferRenderer as a fallback - */ - this.doNotUseGeometryRendererFallback = true; - /** - * All the render targets generated by prepass - */ - this.renderTargets = []; - this._clearColor = new math_color_Color4(0, 0, 0, 0); - this._clearDepthColor = new math_color_Color4(1e8, 0, 0, 1); // "infinity" value - depth in the depth texture is view.z, not a 0..1 value! - this._enabled = false; - this._needsCompositionForThisPass = false; - /** - * Set to true to disable gamma transform in PrePass. - * Can be useful in case you already proceed to gamma transform on a material level - * and your post processes don't need to be in linear color space. - */ - this.disableGammaTransform = false; - this._scene = scene; - this._engine = scene.getEngine(); - let type = 0; - if (this._engine._caps.textureFloat && this._engine._caps.textureFloatLinearFiltering) { - type = 1; - } - else if (this._engine._caps.textureHalfFloat && this._engine._caps.textureHalfFloatLinearFiltering) { - type = 2; - } - if (type !== 1) { - for (let i = 0; i < PrePassRenderer.TextureFormats.length; ++i) { - if (PrePassRenderer.TextureFormats[i].type === 1) { - PrePassRenderer.TextureFormats[5].type = type; - } - } - } - PrePassRenderer._SceneComponentInitialization(this._scene); - this.defaultRT = this._createRenderTarget("sceneprePassRT", null); - this._currentTarget = this.defaultRT; - } - /** - * Creates a new PrePassRenderTarget - * This should be the only way to instantiate a `PrePassRenderTarget` - * @param name Name of the `PrePassRenderTarget` - * @param renderTargetTexture RenderTarget the `PrePassRenderTarget` will be attached to. - * Can be `null` if the created `PrePassRenderTarget` is attached to the scene (default framebuffer). - * @internal - */ - _createRenderTarget(name, renderTargetTexture) { - const rt = new PrePassRenderTarget(name, renderTargetTexture, { width: this._engine.getRenderWidth(), height: this._engine.getRenderHeight() }, 0, this._scene, { - generateMipMaps: false, - generateStencilBuffer: this._engine.isStencilEnable, - defaultType: 0, - types: [], - drawOnlyOnFirstAttachmentByDefault: true, - }); - this.renderTargets.push(rt); - if (this._enabled) { - // The pre-pass renderer is already enabled, so make sure we create the render target with the correct number of textures - this._update(); - } - return rt; - } - /** - * Indicates if rendering a prepass is supported - */ - get isSupported() { - return this._scene.getEngine().getCaps().drawBuffersExtension; - } - /** - * Sets the proper output textures to draw in the engine. - * @param effect The effect that is drawn. It can be or not be compatible with drawing to several output textures. - * @param subMesh Submesh on which the effect is applied - */ - bindAttachmentsForEffect(effect, subMesh) { - const material = subMesh.getMaterial(); - const isPrePassCapable = material && material.isPrePassCapable; - const excluded = material && this.excludedMaterials.indexOf(material) !== -1; - if (this.enabled && this._currentTarget.enabled) { - if (effect._multiTarget && isPrePassCapable && !excluded) { - this._engine.bindAttachments(this._multiRenderAttachments); - } - else { - if (this._engine._currentRenderTarget) { - this._engine.bindAttachments(this._defaultAttachments); - } - else { - this._engine.restoreSingleAttachment(); - } - if (this._geometryBuffer && this.currentRTisSceneRT && !excluded) { - this._geometryBuffer.renderList.push(subMesh.getRenderingMesh()); - } - } - } - } - _reinitializeAttachments() { - const multiRenderLayout = []; - const clearLayout = [false]; - const clearDepthLayout = [false]; - const defaultLayout = [true]; - for (let i = 0; i < this.mrtCount; i++) { - multiRenderLayout.push(true); - if (i > 0) { - if (this._useSpecificClearForDepthTexture && this._mrtLayout[i] === 5) { - clearLayout.push(false); - clearDepthLayout.push(true); - } - else { - clearLayout.push(true); - clearDepthLayout.push(false); - } - defaultLayout.push(false); - } - } - this._multiRenderAttachments = this._engine.buildTextureLayout(multiRenderLayout); - this._clearAttachments = this._engine.buildTextureLayout(clearLayout); - this._clearDepthAttachments = this._engine.buildTextureLayout(clearDepthLayout); - this._defaultAttachments = this._engine.buildTextureLayout(defaultLayout); - } - _resetLayout() { - for (let i = 0; i < PrePassRenderer.TextureFormats.length; i++) { - this._textureIndices[PrePassRenderer.TextureFormats[i].purpose] = -1; - } - this._textureIndices[4] = 0; - this._mrtLayout = [4]; - this._mrtTypes = [PrePassRenderer.TextureFormats[4].type]; - this._mrtFormats = [PrePassRenderer.TextureFormats[4].format]; - this._mrtNames = [PrePassRenderer.TextureFormats[4].name]; - this.mrtCount = 1; - } - _updateGeometryBufferLayout() { - this._refreshGeometryBufferRendererLink(); - if (this._geometryBuffer) { - this._geometryBuffer._resetLayout(); - const texturesActivated = []; - for (let i = 0; i < this._mrtLayout.length; i++) { - texturesActivated.push(false); - } - this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture()); - const matches = [ - { - prePassConstant: 5, - geometryBufferConstant: GeometryBufferRenderer.DEPTH_TEXTURE_TYPE, - }, - { - prePassConstant: 6, - geometryBufferConstant: GeometryBufferRenderer.NORMAL_TEXTURE_TYPE, - }, - { - prePassConstant: 1, - geometryBufferConstant: GeometryBufferRenderer.POSITION_TEXTURE_TYPE, - }, - { - prePassConstant: 3, - geometryBufferConstant: GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE, - }, - { - prePassConstant: 2, - geometryBufferConstant: GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE, - }, - ]; - // replace textures in the geometryBuffer RT - for (let i = 0; i < matches.length; i++) { - const index = this._mrtLayout.indexOf(matches[i].prePassConstant); - if (index !== -1) { - this._geometryBuffer._forceTextureType(matches[i].geometryBufferConstant, index); - texturesActivated[index] = true; - } - } - this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(texturesActivated)); - } - } - /** - * Restores attachments for single texture draw. - */ - restoreAttachments() { - if (this.enabled && this._currentTarget.enabled && this._defaultAttachments) { - if (this._engine._currentRenderTarget) { - this._engine.bindAttachments(this._defaultAttachments); - } - else { - this._engine.restoreSingleAttachment(); - } - } - } - /** - * @internal - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _beforeDraw(camera, faceIndex, layer) { - // const previousEnabled = this._enabled && this._currentTarget.enabled; - if (this._isDirty) { - this._update(); - } - if (!this._enabled || !this._currentTarget.enabled) { - return; - } - if (this._geometryBuffer) { - this._geometryBuffer.renderList = []; - } - this._setupOutputForThisPass(this._currentTarget, camera); - } - _prepareFrame(prePassRenderTarget, faceIndex, layer) { - if (prePassRenderTarget.renderTargetTexture) { - prePassRenderTarget.renderTargetTexture._prepareFrame(this._scene, faceIndex, layer, prePassRenderTarget.renderTargetTexture.useCameraPostProcesses); - } - else if (this._postProcessesSourceForThisPass.length) { - this._scene.postProcessManager._prepareFrame(); - } - else { - this._engine.restoreDefaultFramebuffer(); - } - } - /** - * Sets an intermediary texture between prepass and postprocesses. This texture - * will be used as input for post processes - * @param rt - * @returns true if there are postprocesses that will use this texture, - * false if there is no postprocesses - and the function has no effect - */ - setCustomOutput(rt) { - const firstPP = this._postProcessesSourceForThisPass[0]; - if (!firstPP) { - return false; - } - firstPP.inputTexture = rt.renderTarget; - return true; - } - _renderPostProcesses(prePassRenderTarget, faceIndex) { - var _a; - const firstPP = this._postProcessesSourceForThisPass[0]; - const outputTexture = firstPP ? firstPP.inputTexture : prePassRenderTarget.renderTargetTexture ? prePassRenderTarget.renderTargetTexture.renderTarget : null; - // Build post process chain for this prepass post draw - let postProcessChain = this._currentTarget._beforeCompositionPostProcesses; - if (this._needsCompositionForThisPass) { - postProcessChain = postProcessChain.concat([this._currentTarget.imageProcessingPostProcess]); - } - // Activates and renders the chain - if (postProcessChain.length) { - this._scene.postProcessManager._prepareFrame((_a = this._currentTarget.renderTarget) === null || _a === void 0 ? void 0 : _a.texture, postProcessChain); - this._scene.postProcessManager.directRender(postProcessChain, outputTexture, false, faceIndex); - } - } - /** - * @internal - */ - _afterDraw(faceIndex, layer) { - if (this._enabled && this._currentTarget.enabled) { - this._prepareFrame(this._currentTarget, faceIndex, layer); - this._renderPostProcesses(this._currentTarget, faceIndex); - } - } - /** - * Clears the current prepass render target (in the sense of settings pixels to the scene clear color value) - * @internal - */ - _clear() { - if (this._enabled && this._currentTarget.enabled) { - this._bindFrameBuffer(this._currentTarget); - // Clearing other attachment with 0 on all other attachments - this._engine.bindAttachments(this._clearAttachments); - this._engine.clear(this._clearColor, true, false, false); - if (this._useSpecificClearForDepthTexture) { - this._engine.bindAttachments(this._clearDepthAttachments); - this._engine.clear(this._clearDepthColor, true, false, false); - } - // Regular clear color with the scene clear color of the 1st attachment - this._engine.bindAttachments(this._defaultAttachments); - } - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _bindFrameBuffer(prePassRenderTarget) { - if (this._enabled && this._currentTarget.enabled) { - this._currentTarget._checkSize(); - const internalTexture = this._currentTarget.renderTarget; - if (internalTexture) { - this._engine.bindFramebuffer(internalTexture); - } - } - } - _setEnabled(enabled) { - this._enabled = enabled; - } - _setRenderTargetEnabled(prePassRenderTarget, enabled) { - prePassRenderTarget.enabled = enabled; - if (!enabled) { - this._unlinkInternalTexture(prePassRenderTarget); - } - } - /** - * Adds an effect configuration to the prepass render target. - * If an effect has already been added, it won't add it twice and will return the configuration - * already present. - * @param cfg the effect configuration - * @returns the effect configuration now used by the prepass - */ - addEffectConfiguration(cfg) { - // Do not add twice - for (let i = 0; i < this._effectConfigurations.length; i++) { - if (this._effectConfigurations[i].name === cfg.name) { - return this._effectConfigurations[i]; - } - } - this._effectConfigurations.push(cfg); - return cfg; - } - _enable() { - const previousMrtCount = this.mrtCount; - for (let i = 0; i < this._effectConfigurations.length; i++) { - if (this._effectConfigurations[i].enabled) { - this._enableTextures(this._effectConfigurations[i].texturesRequired); - } - } - for (let i = 0; i < this.renderTargets.length; i++) { - if (this.mrtCount !== previousMrtCount || this.renderTargets[i].count !== this.mrtCount) { - this.renderTargets[i].updateCount(this.mrtCount, { types: this._mrtTypes, formats: this._mrtFormats }, this._mrtNames.concat("prePass_DepthBuffer")); - } - this.renderTargets[i]._resetPostProcessChain(); - for (let j = 0; j < this._effectConfigurations.length; j++) { - if (this._effectConfigurations[j].enabled) { - // TODO : subsurface scattering has 1 scene-wide effect configuration - // solution : do not stock postProcess on effectConfiguration, but in the prepassRenderTarget (hashmap configuration => postProcess) - // And call createPostProcess whenever the post process does not exist in the RT - if (!this._effectConfigurations[j].postProcess && this._effectConfigurations[j].createPostProcess) { - this._effectConfigurations[j].createPostProcess(); - } - if (this._effectConfigurations[j].postProcess) { - this.renderTargets[i]._beforeCompositionPostProcesses.push(this._effectConfigurations[j].postProcess); - } - } - } - } - this._reinitializeAttachments(); - this._setEnabled(true); - this._updateGeometryBufferLayout(); - } - _disable() { - this._setEnabled(false); - for (let i = 0; i < this.renderTargets.length; i++) { - this._setRenderTargetEnabled(this.renderTargets[i], false); - } - this._resetLayout(); - for (let i = 0; i < this._effectConfigurations.length; i++) { - this._effectConfigurations[i].enabled = false; - } - } - _getPostProcessesSource(prePassRenderTarget, camera) { - if (camera) { - return camera._postProcesses; - } - else if (prePassRenderTarget.renderTargetTexture) { - if (prePassRenderTarget.renderTargetTexture.useCameraPostProcesses) { - const camera = prePassRenderTarget.renderTargetTexture.activeCamera ? prePassRenderTarget.renderTargetTexture.activeCamera : this._scene.activeCamera; - return camera ? camera._postProcesses : []; - } - else if (prePassRenderTarget.renderTargetTexture.postProcesses) { - return prePassRenderTarget.renderTargetTexture.postProcesses; - } - else { - return []; - } - } - else { - return this._scene.activeCamera ? this._scene.activeCamera._postProcesses : []; - } - } - _setupOutputForThisPass(prePassRenderTarget, camera) { - // Order is : draw ===> prePassRenderTarget._postProcesses ==> ipp ==> camera._postProcesses - const secondaryCamera = camera && this._scene.activeCameras && !!this._scene.activeCameras.length && this._scene.activeCameras.indexOf(camera) !== 0; - this._postProcessesSourceForThisPass = this._getPostProcessesSource(prePassRenderTarget, camera); - this._postProcessesSourceForThisPass = this._postProcessesSourceForThisPass.filter((pp) => { - return pp != null; - }); - this._scene.autoClear = true; - const cameraHasImageProcessing = this._hasImageProcessing(this._postProcessesSourceForThisPass); - this._needsCompositionForThisPass = !cameraHasImageProcessing && !this.disableGammaTransform && this._needsImageProcessing() && !secondaryCamera; - const firstCameraPP = this._getFirstPostProcess(this._postProcessesSourceForThisPass); - const firstPrePassPP = prePassRenderTarget._beforeCompositionPostProcesses && prePassRenderTarget._beforeCompositionPostProcesses[0]; - let firstPP = null; - // Setting the scene-wide post process configuration - this._scene.imageProcessingConfiguration.applyByPostProcess = this._needsCompositionForThisPass || cameraHasImageProcessing; - // Create composition effect if needed - if (this._needsCompositionForThisPass && !prePassRenderTarget.imageProcessingPostProcess) { - prePassRenderTarget._createCompositionEffect(); - } - // Setting the prePassRenderTarget as input texture of the first PP - if (firstPrePassPP) { - firstPP = firstPrePassPP; - } - else if (this._needsCompositionForThisPass) { - firstPP = prePassRenderTarget.imageProcessingPostProcess; - } - else if (firstCameraPP) { - firstPP = firstCameraPP; - } - this._bindFrameBuffer(prePassRenderTarget); - this._linkInternalTexture(prePassRenderTarget, firstPP); - } - _linkInternalTexture(prePassRenderTarget, postProcess) { - if (postProcess) { - postProcess.autoClear = false; - postProcess.inputTexture = prePassRenderTarget.renderTarget; - } - if (prePassRenderTarget._outputPostProcess !== postProcess) { - if (prePassRenderTarget._outputPostProcess) { - this._unlinkInternalTexture(prePassRenderTarget); - } - prePassRenderTarget._outputPostProcess = postProcess; - } - if (prePassRenderTarget._internalTextureDirty) { - this._updateGeometryBufferLayout(); - prePassRenderTarget._internalTextureDirty = false; - } - } - /** - * @internal - */ - _unlinkInternalTexture(prePassRenderTarget) { - if (prePassRenderTarget._outputPostProcess) { - prePassRenderTarget._outputPostProcess.autoClear = true; - prePassRenderTarget._outputPostProcess.restoreDefaultInputTexture(); - prePassRenderTarget._outputPostProcess = null; - } - } - _needsImageProcessing() { - for (let i = 0; i < this._effectConfigurations.length; i++) { - if (this._effectConfigurations[i].enabled && this._effectConfigurations[i].needsImageProcessing) { - return true; - } - } - return false; - } - _hasImageProcessing(postProcesses) { - var _a; - let isIPPAlreadyPresent = false; - if (postProcesses) { - for (let i = 0; i < postProcesses.length; i++) { - if (((_a = postProcesses[i]) === null || _a === void 0 ? void 0 : _a.getClassName()) === "ImageProcessingPostProcess") { - isIPPAlreadyPresent = true; - break; - } - } - } - return isIPPAlreadyPresent; - } - /** - * Internal, gets the first post proces. - * @param postProcesses - * @returns the first post process to be run on this camera. - */ - _getFirstPostProcess(postProcesses) { - for (let ppIndex = 0; ppIndex < postProcesses.length; ppIndex++) { - if (postProcesses[ppIndex] !== null) { - return postProcesses[ppIndex]; - } - } - return null; - } - /** - * Marks the prepass renderer as dirty, triggering a check if the prepass is necessary for the next rendering. - */ - markAsDirty() { - this._isDirty = true; - } - /** - * Enables a texture on the MultiRenderTarget for prepass - * @param types - */ - _enableTextures(types) { - // For velocity : enable storage of previous matrices for instances - this._scene.needsPreviousWorldMatrices = false; - for (let i = 0; i < types.length; i++) { - const type = types[i]; - if (this._textureIndices[type] === -1) { - this._textureIndices[type] = this._mrtLayout.length; - this._mrtLayout.push(type); - this._mrtTypes.push(PrePassRenderer.TextureFormats[type].type); - this._mrtFormats.push(PrePassRenderer.TextureFormats[type].format); - this._mrtNames.push(PrePassRenderer.TextureFormats[type].name); - this.mrtCount++; - } - if (type === 2) { - this._scene.needsPreviousWorldMatrices = true; - } - } - } - /** - * Makes sure that the prepass renderer is up to date if it has been dirtified. - */ - update() { - if (this._isDirty) { - this._update(); - } - } - _update() { - this._disable(); - let enablePrePass = false; - this._scene.imageProcessingConfiguration.applyByPostProcess = false; - if (this._scene._depthPeelingRenderer && this._scene.useOrderIndependentTransparency) { - this._scene._depthPeelingRenderer.setPrePassRenderer(this); - enablePrePass = true; - } - for (let i = 0; i < this._scene.materials.length; i++) { - if (this._scene.materials[i].setPrePassRenderer(this)) { - enablePrePass = true; - } - } - if (enablePrePass) { - this._setRenderTargetEnabled(this.defaultRT, true); - } - let postProcesses; - for (let i = 0; i < this.renderTargets.length; i++) { - if (this.renderTargets[i].renderTargetTexture) { - postProcesses = this._getPostProcessesSource(this.renderTargets[i]); - } - else { - const camera = this._scene.activeCamera; - if (!camera) { - continue; - } - postProcesses = camera._postProcesses; - } - if (!postProcesses) { - continue; - } - postProcesses = postProcesses.filter((pp) => { - return pp != null; - }); - if (postProcesses) { - for (let j = 0; j < postProcesses.length; j++) { - if (postProcesses[j].setPrePassRenderer(this)) { - this._setRenderTargetEnabled(this.renderTargets[i], true); - enablePrePass = true; - } - } - if (this._hasImageProcessing(postProcesses)) { - this._scene.imageProcessingConfiguration.applyByPostProcess = true; - } - } - } - this._markAllMaterialsAsPrePassDirty(); - this._isDirty = false; - if (enablePrePass) { - this._enable(); - } - } - _markAllMaterialsAsPrePassDirty() { - const materials = this._scene.materials; - for (let i = 0; i < materials.length; i++) { - materials[i].markAsDirty(material_Material.PrePassDirtyFlag); - } - } - /** - * Disposes the prepass renderer. - */ - dispose() { - for (let i = this.renderTargets.length - 1; i >= 0; i--) { - this.renderTargets[i].dispose(); - } - for (let i = 0; i < this._effectConfigurations.length; i++) { - if (this._effectConfigurations[i].dispose) { - this._effectConfigurations[i].dispose(); - } - } - } -} -/** - * @internal - */ -PrePassRenderer._SceneComponentInitialization = (_) => { - throw _WarnImport("PrePassRendererSceneComponent"); -}; -/** - * Describes the types and formats of the textures used by the pre-pass renderer - */ -PrePassRenderer.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", - }, -]; -//# sourceMappingURL=prePassRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/prePassRendererSceneComponent.js - - - - -Object.defineProperty(scene_Scene.prototype, "prePassRenderer", { - get: function () { - return this._prePassRenderer; - }, - set: function (value) { - if (value && value.isSupported) { - this._prePassRenderer = value; - } - }, - enumerable: true, - configurable: true, -}); -scene_Scene.prototype.enablePrePassRenderer = function () { - if (this._prePassRenderer) { - return this._prePassRenderer; - } - this._prePassRenderer = new PrePassRenderer(this); - if (!this._prePassRenderer.isSupported) { - this._prePassRenderer = null; - logger_Logger.Error("PrePassRenderer needs WebGL 2 support.\n" + "Maybe you tried to use the following features that need the PrePassRenderer :\n" + " + Subsurface Scattering"); - } - return this._prePassRenderer; -}; -scene_Scene.prototype.disablePrePassRenderer = function () { - if (!this._prePassRenderer) { - return; - } - this._prePassRenderer.dispose(); - this._prePassRenderer = null; -}; -/** - * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful - * in several rendering techniques. - */ -class PrePassRendererSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_PREPASSRENDERER; - this.scene = scene; - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._beforeCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS, this, this._beforeCameraDraw); - this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS, this, this._afterCameraDraw); - this.scene._beforeRenderTargetDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS, this, this._beforeRenderTargetDraw); - this.scene._afterRenderTargetDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS, this, this._afterRenderTargetDraw); - this.scene._beforeClearStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECLEAR_PREPASS, this, this._beforeClearStage); - this.scene._beforeRenderTargetClearStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS, this, this._beforeRenderTargetClearStage); - this.scene._beforeRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS, this, this._beforeRenderingMeshStage); - this.scene._afterRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS, this, this._afterRenderingMeshStage); - } - _beforeRenderTargetDraw(renderTarget, faceIndex, layer) { - if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) { - this.scene.prePassRenderer._setRenderTarget(renderTarget._prePassRenderTarget); - this.scene.prePassRenderer._beforeDraw(undefined, faceIndex, layer); - } - } - _afterRenderTargetDraw(renderTarget, faceIndex, layer) { - if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) { - this.scene.prePassRenderer._afterDraw(faceIndex, layer); - } - } - _beforeRenderTargetClearStage(renderTarget) { - if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) { - if (!renderTarget._prePassRenderTarget) { - renderTarget._prePassRenderTarget = this.scene.prePassRenderer._createRenderTarget(renderTarget.name + "_prePassRTT", renderTarget); - } - this.scene.prePassRenderer._setRenderTarget(renderTarget._prePassRenderTarget); - this.scene.prePassRenderer._clear(); - } - } - _beforeCameraDraw(camera) { - if (this.scene.prePassRenderer) { - this.scene.prePassRenderer._setRenderTarget(null); - this.scene.prePassRenderer._beforeDraw(camera); - } - } - _afterCameraDraw() { - if (this.scene.prePassRenderer) { - this.scene.prePassRenderer._afterDraw(); - } - } - _beforeClearStage() { - if (this.scene.prePassRenderer) { - this.scene.prePassRenderer._setRenderTarget(null); - this.scene.prePassRenderer._clear(); - } - } - _beforeRenderingMeshStage(mesh, subMesh, batch, effect) { - if (!effect) { - return; - } - // Render to MRT - const scene = mesh.getScene(); - if (scene.prePassRenderer) { - scene.prePassRenderer.bindAttachmentsForEffect(effect, subMesh); - } - } - _afterRenderingMeshStage(mesh) { - const scene = mesh.getScene(); - if (scene.prePassRenderer) { - scene.prePassRenderer.restoreAttachments(); - } - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Release textures first - this.scene.disablePrePassRenderer(); - // Re-enable - this.scene.enablePrePassRenderer(); - } - /** - * Disposes the component and the associated resources - */ - dispose() { - this.scene.disablePrePassRenderer(); - } -} -PrePassRenderer._SceneComponentInitialization = (scene) => { - // Register the G Buffer component to the scene. - let component = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_PREPASSRENDERER); - if (!component) { - component = new PrePassRendererSceneComponent(scene); - scene._addComponent(component); - } -}; -//# sourceMappingURL=prePassRendererSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/fibonacci.js -// Do not edit. - -const fibonacci_name = "fibonacci"; -const fibonacci_shader = `#define rcp(x) 1./x -#define GOLDEN_RATIO 1.618033988749895 -#define TWO_PI 6.2831855 -vec2 Golden2dSeq(int i,float n) -{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} -vec2 SampleDiskGolden(int i,int sampleCount) -{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`; -// Sideeffect -ShaderStore.IncludesShadersStore[fibonacci_name] = fibonacci_shader; -/** @internal */ -const fibonacci = { name: fibonacci_name, shader: fibonacci_shader }; -//# sourceMappingURL=fibonacci.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/diffusionProfile.js -// Do not edit. - -const diffusionProfile_name = "diffusionProfile"; -const diffusionProfile_shader = `uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];`; -// Sideeffect -ShaderStore.IncludesShadersStore[diffusionProfile_name] = diffusionProfile_shader; -/** @internal */ -const diffusionProfile = { name: diffusionProfile_name, shader: diffusionProfile_shader }; -//# sourceMappingURL=diffusionProfile.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/subSurfaceScattering.fragment.js -// Do not edit. - - - - - -const subSurfaceScattering_fragment_name = "subSurfaceScatteringPixelShader"; -const subSurfaceScattering_fragment_shader = `#include<fibonacci> -#include<helperFunctions> -#include<subSurfaceScatteringFunctions> -#include<diffusionProfile> -varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; -#define rcp(x) 1./x -#define Sq(x) x*x -#define SSS_BILATERAL_FILTER true -vec3 EvalBurleyDiffusionProfile(float r,vec3 S) -{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); -vec3 expSum=exp_13*(1.+exp_13*exp_13); -return (S*rcp(8.*PI))*expSum; } -vec2 SampleBurleyDiffusionProfile(float u,float rcpS) -{u=1.-u; -float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); -float p=(g*n)*n; -float c=1.+p+n; -float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); -float x=(3./LOG2_E)*log2(c)-d; -float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; -return vec2(r,rcpPdf);} -vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) -{ -#ifndef SSS_BILATERAL_FILTER -z=0.; -#endif -float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; -#if SSS_CLAMP_ARTIFACT -return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); -#else -return EvalBurleyDiffusionProfile(r,S)*area; -#endif -} -void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, -float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) -{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; -float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; -vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; -float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) -{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} -else -{}} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) -{centerDepth=texture2D(depthSampler,vUV).r;} -if (!passedStencilTest) { -gl_FragColor=inputColor;return;} -float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; -vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; -float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) -{ -#ifdef DEBUG_SSS_SAMPLES -vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; -#endif -gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} -#ifdef DEBUG_SSS_SAMPLES -vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; -#endif -float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); -vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i<n; i++) -{EvaluateSample(i,n,S,d,centerPosVS,mmPerUnit,pixelsPerMm, -phase,totalIrradiance,totalWeight);} -totalWeight=max(totalWeight,HALF_MIN);gl_FragColor=vec4(inputColor.rgb+albedo*max(totalIrradiance/totalWeight,vec3(0.0)),1.);}`; -// Sideeffect -ShaderStore.ShadersStore[subSurfaceScattering_fragment_name] = subSurfaceScattering_fragment_shader; -/** @internal */ -const subSurfaceScatteringPixelShader = { name: subSurfaceScattering_fragment_name, shader: subSurfaceScattering_fragment_shader }; -//# sourceMappingURL=subSurfaceScattering.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/PostProcesses/subSurfaceScatteringPostProcess.js - - - - - - - -/** - * Sub surface scattering post process - */ -class SubSurfaceScatteringPostProcess extends postProcess_PostProcess { - /** - * Gets a string identifying the name of the class - * @returns "SubSurfaceScatteringPostProcess" string - */ - getClassName() { - return "SubSurfaceScatteringPostProcess"; - } - constructor(name, scene, options, camera = null, samplingMode, engine, reusable, textureType = 0) { - super(name, "subSurfaceScattering", ["texelSize", "viewportSize", "metersPerUnit"], ["diffusionS", "diffusionD", "filterRadii", "irradianceSampler", "depthSampler", "albedoSampler"], options, camera, samplingMode || texture_Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "postprocess", undefined, true); - this._scene = scene; - this.updateEffect(); - this.onApplyObservable.add((effect) => { - if (!scene.prePassRenderer || !scene.subSurfaceConfiguration) { - logger_Logger.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering."); - return; - } - const texelSize = this.texelSize; - effect.setFloat("metersPerUnit", scene.subSurfaceConfiguration.metersPerUnit); - effect.setFloat2("texelSize", texelSize.x, texelSize.y); - effect.setTexture("irradianceSampler", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(0)]); - effect.setTexture("depthSampler", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(5)]); - effect.setTexture("albedoSampler", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(7)]); - effect.setFloat2("viewportSize", Math.tan(scene.activeCamera.fov / 2) * scene.getEngine().getAspectRatio(scene.activeCamera, true), Math.tan(scene.activeCamera.fov / 2)); - effect.setArray3("diffusionS", scene.subSurfaceConfiguration.ssDiffusionS); - effect.setArray("diffusionD", scene.subSurfaceConfiguration.ssDiffusionD); - effect.setArray("filterRadii", scene.subSurfaceConfiguration.ssFilterRadii); - }); - } -} -//# sourceMappingURL=subSurfaceScatteringPostProcess.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/subSurfaceConfiguration.js - - - - - - -/** - * Contains all parameters needed for the prepass to perform - * screen space subsurface scattering - */ -class SubSurfaceConfiguration { - /** - * Diffusion profile color for subsurface scattering - */ - get ssDiffusionS() { - return this._ssDiffusionS; - } - /** - * Diffusion profile max color channel value for subsurface scattering - */ - get ssDiffusionD() { - return this._ssDiffusionD; - } - /** - * Diffusion profile filter radius for subsurface scattering - */ - get ssFilterRadii() { - return this._ssFilterRadii; - } - /** - * Builds a subsurface configuration object - * @param scene The scene - */ - constructor(scene) { - this._ssDiffusionS = []; - this._ssFilterRadii = []; - this._ssDiffusionD = []; - /** - * Is subsurface enabled - */ - this.enabled = false; - /** - * Does the output of this prepass need to go through imageprocessing - */ - this.needsImageProcessing = true; - /** - * Name of the configuration - */ - this.name = sceneComponent_SceneComponentConstants.NAME_SUBSURFACE; - /** - * Diffusion profile colors for subsurface scattering - * You can add one diffusion color using `addDiffusionProfile` on `scene.prePassRenderer` - * See ... - * Note that you can only store up to 5 of them - */ - this.ssDiffusionProfileColors = []; - /** - * Defines the ratio real world => scene units. - * Used for subsurface scattering - */ - this.metersPerUnit = 1; - /** - * Textures that should be present in the MRT for this effect to work - */ - this.texturesRequired = [ - 5, - 7, - 4, - 0, - ]; - // Adding default diffusion profile - this.addDiffusionProfile(new math_color_Color3(1, 1, 1)); - this._scene = scene; - SubSurfaceConfiguration._SceneComponentInitialization(this._scene); - } - /** - * Adds a new diffusion profile. - * Useful for more realistic subsurface scattering on diverse materials. - * @param color The color of the diffusion profile. Should be the average color of the material. - * @returns The index of the diffusion profile for the material subsurface configuration - */ - addDiffusionProfile(color) { - if (this.ssDiffusionD.length >= 5) { - // We only suppport 5 diffusion profiles - logger_Logger.Error("You already reached the maximum number of diffusion profiles."); - return 0; // default profile - } - // Do not add doubles - for (let i = 0; i < this._ssDiffusionS.length / 3; i++) { - if (this._ssDiffusionS[i * 3] === color.r && this._ssDiffusionS[i * 3 + 1] === color.g && this._ssDiffusionS[i * 3 + 2] === color.b) { - return i; - } - } - this._ssDiffusionS.push(color.r, color.b, color.g); - this._ssDiffusionD.push(Math.max(Math.max(color.r, color.b), color.g)); - this._ssFilterRadii.push(this.getDiffusionProfileParameters(color)); - this.ssDiffusionProfileColors.push(color); - return this._ssDiffusionD.length - 1; - } - /** - * Creates the sss post process - * @returns The created post process - */ - createPostProcess() { - this.postProcess = new SubSurfaceScatteringPostProcess("subSurfaceScattering", this._scene, 1, null, undefined, this._scene.getEngine()); - this.postProcess.autoClear = false; - return this.postProcess; - } - /** - * Deletes all diffusion profiles. - * Note that in order to render subsurface scattering, you should have at least 1 diffusion profile. - */ - clearAllDiffusionProfiles() { - this._ssDiffusionD = []; - this._ssDiffusionS = []; - this._ssFilterRadii = []; - this.ssDiffusionProfileColors = []; - } - /** - * Disposes this object - */ - dispose() { - this.clearAllDiffusionProfiles(); - if (this.postProcess) { - this.postProcess.dispose(); - } - } - /** - * @internal - * https://zero-radiance.github.io/post/sampling-diffusion/ - * - * Importance sample the normalized diffuse reflectance profile for the computed value of 's'. - * ------------------------------------------------------------------------------------ - * R[r, phi, s] = s * (Exp[-r * s] + Exp[-r * s / 3]) / (8 * Pi * r) - * PDF[r, phi, s] = r * R[r, phi, s] - * CDF[r, s] = 1 - 1/4 * Exp[-r * s] - 3/4 * Exp[-r * s / 3] - * ------------------------------------------------------------------------------------ - * We importance sample the color channel with the widest scattering distance. - */ - getDiffusionProfileParameters(color) { - const cdf = 0.997; - const maxScatteringDistance = Math.max(color.r, color.g, color.b); - return this._sampleBurleyDiffusionProfile(cdf, maxScatteringDistance); - } - /** - * Performs sampling of a Normalized Burley diffusion profile in polar coordinates. - * 'u' is the random number (the value of the CDF): [0, 1). - * rcp(s) = 1 / ShapeParam = ScatteringDistance. - * Returns the sampled radial distance, s.t. (u = 0 -> r = 0) and (u = 1 -> r = Inf). - * @param u - * @param rcpS - */ - _sampleBurleyDiffusionProfile(u, rcpS) { - u = 1 - u; // Convert CDF to CCDF - const g = 1 + 4 * u * (2 * u + Math.sqrt(1 + 4 * u * u)); - const n = Math.pow(g, -1.0 / 3.0); // g^(-1/3) - const p = g * n * n; // g^(+1/3) - const c = 1 + p + n; // 1 + g^(+1/3) + g^(-1/3) - const x = 3 * Math.log(c / (4 * u)); - return x * rcpS; - } -} -/** - * @internal - */ -SubSurfaceConfiguration._SceneComponentInitialization = (_) => { - throw _WarnImport("SubSurfaceSceneComponent"); -}; -//# sourceMappingURL=subSurfaceConfiguration.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/subSurfaceSceneComponent.js - - - - - -// Adds the parser to the scene parsers. -AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_SUBSURFACE, (parsedData, scene) => { - // Diffusion profiles - if (parsedData.ssDiffusionProfileColors !== undefined && parsedData.ssDiffusionProfileColors !== null) { - scene.enableSubSurfaceForPrePass(); - if (scene.subSurfaceConfiguration) { - for (let index = 0, cache = parsedData.ssDiffusionProfileColors.length; index < cache; index++) { - const color = parsedData.ssDiffusionProfileColors[index]; - scene.subSurfaceConfiguration.addDiffusionProfile(new math_color_Color3(color.r, color.g, color.b)); - } - } - } -}); -Object.defineProperty(scene_Scene.prototype, "subSurfaceConfiguration", { - get: function () { - return this._subSurfaceConfiguration; - }, - set: function (value) { - if (value) { - if (this.enablePrePassRenderer()) { - this._subSurfaceConfiguration = value; - } - } - }, - enumerable: true, - configurable: true, -}); -scene_Scene.prototype.enableSubSurfaceForPrePass = function () { - if (this._subSurfaceConfiguration) { - return this._subSurfaceConfiguration; - } - const prePassRenderer = this.enablePrePassRenderer(); - if (prePassRenderer) { - this._subSurfaceConfiguration = new SubSurfaceConfiguration(this); - prePassRenderer.addEffectConfiguration(this._subSurfaceConfiguration); - return this._subSurfaceConfiguration; - } - return null; -}; -scene_Scene.prototype.disableSubSurfaceForPrePass = function () { - if (!this._subSurfaceConfiguration) { - return; - } - this._subSurfaceConfiguration.dispose(); - this._subSurfaceConfiguration = null; -}; -/** - * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful - * in several rendering techniques. - */ -class SubSurfaceSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_PREPASSRENDERER; - this.scene = scene; - } - /** - * Registers the component in a given scene - */ - register() { } - /** - * Serializes the component data to the specified json object - * @param serializationObject The object to serialize to - */ - serialize(serializationObject) { - if (!this.scene.subSurfaceConfiguration) { - return; - } - const ssDiffusionProfileColors = this.scene.subSurfaceConfiguration.ssDiffusionProfileColors; - serializationObject.ssDiffusionProfileColors = []; - for (let i = 0; i < ssDiffusionProfileColors.length; i++) { - serializationObject.ssDiffusionProfileColors.push({ - r: ssDiffusionProfileColors[i].r, - g: ssDiffusionProfileColors[i].g, - b: ssDiffusionProfileColors[i].b, - }); - } - } - /** - * Adds all the elements from the container to the scene - */ - addFromContainer() { - // Nothing to do - } - /** - * Removes all the elements in the container from the scene - */ - removeFromContainer() { - // Make sure nothing will be serialized - if (!this.scene.prePassRenderer) { - return; - } - if (this.scene.subSurfaceConfiguration) { - this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles(); - } - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing to do for this component - } - /** - * Disposes the component and the associated resources - */ - dispose() { - // Nothing to do for this component - } -} -SubSurfaceConfiguration._SceneComponentInitialization = (scene) => { - // Register the G Buffer component to the scene. - let component = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_SUBSURFACE); - if (!component) { - component = new SubSurfaceSceneComponent(scene); - scene._addComponent(component); - } -}; -//# sourceMappingURL=subSurfaceSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/outline.fragment.js -// Do not edit. - - - - - -const outline_fragment_name = "outlinePixelShader"; -const outline_fragment_shader = `#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -uniform vec4 color; -#ifdef ALPHATEST -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include<clipPlaneFragmentDeclaration> -#include<logDepthDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -#include<logDepthFragment> -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[outline_fragment_name] = outline_fragment_shader; -/** @internal */ -const outlinePixelShader = { name: outline_fragment_name, shader: outline_fragment_shader }; -//# sourceMappingURL=outline.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/outline.vertex.js -// Do not edit. - - - - - - - - - - - - - - - -const outline_vertex_name = "outlineVertexShader"; -const outline_vertex_shader = `attribute vec3 position;attribute vec3 normal; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<clipPlaneVertexDeclaration> -uniform float offset; -#include<instancesDeclaration> -uniform mat4 viewProjection; -#ifdef ALPHATEST -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#include<logDepthDeclaration> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position;vec3 normalUpdated=normal; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -vec3 offsetPosition=positionUpdated+(normalUpdated*offset); -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; -#ifdef ALPHATEST -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#include<clipPlaneVertex> -#include<logDepthVertex> -} -`; -// Sideeffect -ShaderStore.ShadersStore[outline_vertex_name] = outline_vertex_shader; -/** @internal */ -const outlineVertexShader = { name: outline_vertex_name, shader: outline_vertex_shader }; -//# sourceMappingURL=outline.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/outlineRenderer.js - - - - - - - - - - -/** - * Gets the outline renderer associated with the scene - * @returns a OutlineRenderer - */ -scene_Scene.prototype.getOutlineRenderer = function () { - if (!this._outlineRenderer) { - this._outlineRenderer = new OutlineRenderer(this); - } - return this._outlineRenderer; -}; -Object.defineProperty(mesh_Mesh.prototype, "renderOutline", { - get: function () { - return this._renderOutline; - }, - set: function (value) { - if (value) { - // Lazy Load the component. - this.getScene().getOutlineRenderer(); - } - this._renderOutline = value; - }, - enumerable: true, - configurable: true, -}); -Object.defineProperty(mesh_Mesh.prototype, "renderOverlay", { - get: function () { - return this._renderOverlay; - }, - set: function (value) { - if (value) { - // Lazy Load the component. - this.getScene().getOutlineRenderer(); - } - this._renderOverlay = value; - }, - enumerable: true, - configurable: true, -}); -/** - * This class is responsible to draw the outline/overlay of meshes. - * It should not be used directly but through the available method on mesh. - */ -class OutlineRenderer { - /** - * Instantiates a new outline renderer. (There could be only one per scene). - * @param scene Defines the scene it belongs to - */ - constructor(scene) { - /** - * The name of the component. Each component must have a unique name. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_OUTLINERENDERER; - /** - * Defines a zOffset default Factor to prevent zFighting between the overlay and the mesh. - */ - this.zOffset = 1; - /** - * Defines a zOffset default Unit to prevent zFighting between the overlay and the mesh. - */ - this.zOffsetUnits = 4; // 4 to account for projection a bit by default - this.scene = scene; - this._engine = scene.getEngine(); - this.scene._addComponent(this); - this._passIdForDrawWrapper = []; - for (let i = 0; i < 4; ++i) { - this._passIdForDrawWrapper[i] = this._engine.createRenderPassId(`Outline Renderer (${i})`); - } - } - /** - * Register the component to one instance of a scene. - */ - register() { - this.scene._beforeRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh); - this.scene._afterRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - // Nothing to do here. - } - /** - * Disposes the component and the associated resources. - */ - dispose() { - for (let i = 0; i < this._passIdForDrawWrapper.length; ++i) { - this._engine.releaseRenderPassId(this._passIdForDrawWrapper[i]); - } - } - /** - * Renders the outline in the canvas. - * @param subMesh Defines the sumesh to render - * @param batch Defines the batch of meshes in case of instances - * @param useOverlay Defines if the rendering is for the overlay or the outline - * @param renderPassId Render pass id to use to render the mesh - */ - render(subMesh, batch, useOverlay = false, renderPassId) { - renderPassId = renderPassId !== null && renderPassId !== void 0 ? renderPassId : this._passIdForDrawWrapper[0]; - const scene = this.scene; - const engine = scene.getEngine(); - const hardwareInstancedRendering = engine.getCaps().instancedArrays && - ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || subMesh.getRenderingMesh().hasThinInstances); - if (!this.isReady(subMesh, hardwareInstancedRendering, renderPassId)) { - return; - } - const ownerMesh = subMesh.getMesh(); - const replacementMesh = ownerMesh._internalAbstractMeshDataInfo._actAsRegularMesh ? ownerMesh : null; - const renderingMesh = subMesh.getRenderingMesh(); - const effectiveMesh = replacementMesh ? replacementMesh : renderingMesh; - const material = subMesh.getMaterial(); - if (!material || !scene.activeCamera) { - return; - } - const drawWrapper = subMesh._getDrawWrapper(renderPassId); - const effect = drawWrapper_DrawWrapper.GetEffect(drawWrapper); - engine.enableEffect(drawWrapper); - // Logarithmic depth - if (material.useLogarithmicDepth) { - effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2)); - } - effect.setFloat("offset", useOverlay ? 0 : renderingMesh.outlineWidth); - effect.setColor4("color", useOverlay ? renderingMesh.overlayColor : renderingMesh.outlineColor, useOverlay ? renderingMesh.overlayAlpha : material.alpha); - effect.setMatrix("viewProjection", scene.getTransformMatrix()); - effect.setMatrix("world", effectiveMesh.getWorldMatrix()); - // Bones - if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { - effect.setMatrices("mBones", renderingMesh.skeleton.getTransformMatrices(renderingMesh)); - } - if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { - renderingMesh.morphTargetManager._bind(effect); - } - // Morph targets - MaterialHelper.BindMorphTargetParameters(renderingMesh, effect); - if (!hardwareInstancedRendering) { - renderingMesh._bind(subMesh, effect, material.fillMode); - } - // Alpha test - if (material && material.needAlphaTesting()) { - const alphaTexture = material.getAlphaTestTexture(); - if (alphaTexture) { - effect.setTexture("diffuseSampler", alphaTexture); - effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); - } - } - // Clip plane - bindClipPlane(effect, material, scene); - engine.setZOffset(-this.zOffset); - engine.setZOffsetUnits(-this.zOffsetUnits); - renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => { - effect.setMatrix("world", world); - }); - engine.setZOffset(0); - engine.setZOffsetUnits(0); - } - /** - * Returns whether or not the outline renderer is ready for a given submesh. - * All the dependencies e.g. submeshes, texture, effect... mus be ready - * @param subMesh Defines the submesh to check readiness for - * @param useInstances Defines whether wee are trying to render instances or not - * @param renderPassId Render pass id to use to render the mesh - * @returns true if ready otherwise false - */ - isReady(subMesh, useInstances, renderPassId) { - renderPassId = renderPassId !== null && renderPassId !== void 0 ? renderPassId : this._passIdForDrawWrapper[0]; - const defines = []; - const attribs = [buffer_VertexBuffer.PositionKind, buffer_VertexBuffer.NormalKind]; - const mesh = subMesh.getMesh(); - const material = subMesh.getMaterial(); - if (!material) { - return false; - } - const scene = mesh.getScene(); - // Alpha test - if (material.needAlphaTesting()) { - defines.push("#define ALPHATEST"); - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UVKind)) { - attribs.push(buffer_VertexBuffer.UVKind); - defines.push("#define UV1"); - } - if (mesh.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)) { - attribs.push(buffer_VertexBuffer.UV2Kind); - defines.push("#define UV2"); - } - } - //Logarithmic depth - if (material.useLogarithmicDepth) { - defines.push("#define LOGARITHMICDEPTH"); - } - // Clip planes - prepareStringDefinesForClipPlanes(material, scene, defines); - // Bones - if (mesh.useBones && mesh.computeBonesUsingShaders) { - attribs.push(buffer_VertexBuffer.MatricesIndicesKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsKind); - if (mesh.numBoneInfluencers > 4) { - attribs.push(buffer_VertexBuffer.MatricesIndicesExtraKind); - attribs.push(buffer_VertexBuffer.MatricesWeightsExtraKind); - } - defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); - defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0)); - } - else { - defines.push("#define NUM_BONE_INFLUENCERS 0"); - } - // Morph targets - const morphTargetManager = mesh.morphTargetManager; - let numMorphInfluencers = 0; - if (morphTargetManager) { - if (morphTargetManager.numInfluencers > 0) { - numMorphInfluencers = morphTargetManager.numInfluencers; - defines.push("#define MORPHTARGETS"); - defines.push("#define NUM_MORPH_INFLUENCERS " + numMorphInfluencers); - if (morphTargetManager.isUsingTextureForTargets) { - defines.push("#define MORPHTARGETS_TEXTURE"); - } - MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers); - } - } - // Instances - if (useInstances) { - defines.push("#define INSTANCES"); - MaterialHelper.PushAttributesForInstances(attribs); - if (subMesh.getRenderingMesh().hasThinInstances) { - defines.push("#define THIN_INSTANCES"); - } - } - // Get correct effect - const drawWrapper = subMesh._getDrawWrapper(renderPassId, true); - const cachedDefines = drawWrapper.defines; - const join = defines.join("\n"); - if (cachedDefines !== join) { - const uniforms = [ - "world", - "mBones", - "viewProjection", - "diffuseMatrix", - "offset", - "color", - "logarithmicDepthConstant", - "morphTargetInfluences", - "morphTargetTextureInfo", - "morphTargetTextureIndices", - ]; - addClipPlaneUniforms(uniforms); - drawWrapper.setEffect(this.scene.getEngine().createEffect("outline", attribs, uniforms, ["diffuseSampler", "morphTargets"], join, undefined, undefined, undefined, { - maxSimultaneousMorphTargets: numMorphInfluencers, - }), join); - } - return drawWrapper.effect.isReady(); - } - _beforeRenderingMesh(mesh, subMesh, batch) { - // Outline - step 1 - this._savedDepthWrite = this._engine.getDepthWrite(); - if (mesh.renderOutline) { - const material = subMesh.getMaterial(); - if (material && material.needAlphaBlendingForMesh(mesh)) { - this._engine.cacheStencilState(); - // Draw only to stencil buffer for the original mesh - // The resulting stencil buffer will be used so the outline is not visible inside the mesh when the mesh is transparent - this._engine.setDepthWrite(false); - this._engine.setColorWrite(false); - this._engine.setStencilBuffer(true); - this._engine.setStencilOperationPass(7681); - this._engine.setStencilFunction(519); - this._engine.setStencilMask(OutlineRenderer._StencilReference); - this._engine.setStencilFunctionReference(OutlineRenderer._StencilReference); - this._engine.stencilStateComposer.useStencilGlobalOnly = true; - this.render(subMesh, batch, /* This sets offset to 0 */ true, this._passIdForDrawWrapper[1]); - this._engine.setColorWrite(true); - this._engine.setStencilFunction(517); - } - // Draw the outline using the above stencil if needed to avoid drawing within the mesh - this._engine.setDepthWrite(false); - this.render(subMesh, batch, false, this._passIdForDrawWrapper[0]); - this._engine.setDepthWrite(this._savedDepthWrite); - if (material && material.needAlphaBlendingForMesh(mesh)) { - this._engine.stencilStateComposer.useStencilGlobalOnly = false; - this._engine.restoreStencilState(); - } - } - } - _afterRenderingMesh(mesh, subMesh, batch) { - // Overlay - if (mesh.renderOverlay) { - const currentMode = this._engine.getAlphaMode(); - const alphaBlendState = this._engine.alphaState.alphaBlend; - this._engine.setAlphaMode(2); - this.render(subMesh, batch, true, this._passIdForDrawWrapper[3]); - this._engine.setAlphaMode(currentMode); - this._engine.setDepthWrite(this._savedDepthWrite); - this._engine.alphaState.alphaBlend = alphaBlendState; - } - // Outline - step 2 - if (mesh.renderOutline && this._savedDepthWrite) { - this._engine.setDepthWrite(true); - this._engine.setColorWrite(false); - this.render(subMesh, batch, false, this._passIdForDrawWrapper[2]); - this._engine.setColorWrite(true); - } - } -} -/** - * Stencil value used to avoid outline being seen within the mesh when the mesh is transparent - */ -OutlineRenderer._StencilReference = 0x04; -//# sourceMappingURL=outlineRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingObject.js - - - -/** - * Defines the base object used for fluid rendering. - * It is based on a list of vertices (particles) - */ -class FluidRenderingObject { - /** Gets or sets the size of the particle */ - get particleSize() { - return this._particleSize; - } - set particleSize(size) { - if (size === this._particleSize) { - return; - } - this._particleSize = size; - this.onParticleSizeChanged.notifyObservers(this); - } - /** Indicates if the object uses instancing or not */ - get useInstancing() { - return !this.indexBuffer; - } - /** 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! */ - get useVelocity() { - return this._useVelocity; - } - set useVelocity(use) { - if (this._useVelocity === use || !this._hasVelocity()) { - return; - } - this._useVelocity = use; - this._effectsAreDirty = true; - } - _hasVelocity() { - var _a; - return !!((_a = this.vertexBuffers) === null || _a === void 0 ? void 0 : _a.velocity); - } - /** - * Gets the index buffer (or null if the object is using instancing) - */ - get indexBuffer() { - return null; - } - /** - * Gets the name of the class - */ - getClassName() { - return "FluidRenderingObject"; - } - /** - * Instantiates a fluid rendering object - * @param scene The scene the object is part of - */ - constructor(scene) { - /** Defines the priority of the object. Objects will be rendered in ascending order of priority */ - this.priority = 0; - this._particleSize = 0.1; - /** Observable triggered when the size of the particle is changed */ - this.onParticleSizeChanged = new observable_Observable(); - /** Defines the alpha value of a particle */ - this.particleThicknessAlpha = 0.05; - this._useVelocity = false; - this._scene = scene; - this._engine = scene.getEngine(); - this._effectsAreDirty = true; - this._depthEffectWrapper = null; - this._thicknessEffectWrapper = null; - } - _createEffects() { - const uniformNames = ["view", "projection", "particleRadius", "size"]; - const attributeNames = ["position", "offset"]; - const defines = []; - this._effectsAreDirty = false; - if (this.useVelocity) { - attributeNames.push("velocity"); - defines.push("#define FLUIDRENDERING_VELOCITY"); - } - if (this._scene.useRightHandedSystem) { - defines.push("#define FLUIDRENDERING_RHS"); - } - this._depthEffectWrapper = new EffectWrapper({ - engine: this._engine, - useShaderStore: true, - vertexShader: "fluidRenderingParticleDepth", - fragmentShader: "fluidRenderingParticleDepth", - attributeNames, - uniformNames, - samplerNames: [], - defines, - }); - uniformNames.push("particleAlpha"); - this._thicknessEffectWrapper = new EffectWrapper({ - engine: this._engine, - useShaderStore: true, - vertexShader: "fluidRenderingParticleThickness", - fragmentShader: "fluidRenderingParticleThickness", - attributeNames: ["position", "offset"], - uniformNames, - samplerNames: [], - }); - } - /** - * Indicates if the object is ready to be rendered - * @returns True if everything is ready for the object to be rendered, otherwise false - */ - isReady() { - if (this._effectsAreDirty) { - this._createEffects(); - } - if (!this._depthEffectWrapper || !this._thicknessEffectWrapper) { - return false; - } - const depthEffect = this._depthEffectWrapper._drawWrapper.effect; - const thicknessEffect = this._thicknessEffectWrapper._drawWrapper.effect; - return depthEffect.isReady() && thicknessEffect.isReady(); - } - /** - * Render the depth texture for this object - */ - renderDepthTexture() { - const numParticles = this.numParticles; - if (!this._depthEffectWrapper || numParticles === 0) { - return; - } - const depthDrawWrapper = this._depthEffectWrapper._drawWrapper; - const depthEffect = depthDrawWrapper.effect; - this._engine.enableEffect(depthDrawWrapper); - this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, depthEffect); - depthEffect.setMatrix("view", this._scene.getViewMatrix()); - depthEffect.setMatrix("projection", this._scene.getProjectionMatrix()); - depthEffect.setFloat2("size", this._particleSize, this._particleSize); - depthEffect.setFloat("particleRadius", this._particleSize / 2); - if (this.useInstancing) { - this._engine.drawArraysType(7, 0, 4, numParticles); - } - else { - this._engine.drawElementsType(0, 0, numParticles); - } - } - /** - * Render the thickness texture for this object - */ - renderThicknessTexture() { - const numParticles = this.numParticles; - if (!this._thicknessEffectWrapper || numParticles === 0) { - return; - } - const thicknessDrawWrapper = this._thicknessEffectWrapper._drawWrapper; - const thicknessEffect = thicknessDrawWrapper.effect; - this._engine.setAlphaMode(6); - this._engine.setDepthWrite(false); - this._engine.enableEffect(thicknessDrawWrapper); - this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, thicknessEffect); - thicknessEffect.setMatrix("view", this._scene.getViewMatrix()); - thicknessEffect.setMatrix("projection", this._scene.getProjectionMatrix()); - thicknessEffect.setFloat("particleAlpha", this.particleThicknessAlpha); - thicknessEffect.setFloat2("size", this._particleSize, this._particleSize); - if (this.useInstancing) { - this._engine.drawArraysType(7, 0, 4, numParticles); - } - else { - this._engine.drawElementsType(0, 0, numParticles); - } - this._engine.setDepthWrite(true); - this._engine.setAlphaMode(0); - } - /** - * Render the diffuse texture for this object - */ - renderDiffuseTexture() { - // do nothing by default - } - /** - * Releases the ressources used by the class - */ - dispose() { - var _a, _b; - (_a = this._depthEffectWrapper) === null || _a === void 0 ? void 0 : _a.dispose(); - (_b = this._thicknessEffectWrapper) === null || _b === void 0 ? void 0 : _b.dispose(); - } -} -//# sourceMappingURL=fluidRenderingObject.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingObjectParticleSystem.js - - -/** - * Defines a rendering object based on a particle system - */ -class FluidRenderingObjectParticleSystem extends FluidRenderingObject { - /** Gets the particle system */ - get particleSystem() { - return this._particleSystem; - } - /** - * Gets the name of the class - */ - getClassName() { - return "FluidRenderingObjectParticleSystem"; - } - /** - * Gets or sets a boolean indicating that the diffuse texture should be generated based on the regular rendering of the particle system (default: true). - * Sometimes, generating the diffuse texture this way may be sub-optimal. In that case, you can disable this property, in which case the particle system will be - * rendered using a ALPHA_COMBINE mode instead of the one used by the particle system. - */ - get useTrueRenderingForDiffuseTexture() { - return this._useTrueRenderingForDiffuseTexture; - } - set useTrueRenderingForDiffuseTexture(use) { - if (this._useTrueRenderingForDiffuseTexture === use) { - return; - } - this._useTrueRenderingForDiffuseTexture = use; - if (use) { - this._particleSystem.blendMode = this._blendMode; - this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver); - this._onBeforeDrawParticleObserver = null; - } - else { - this._particleSystem.blendMode = -1; - this._onBeforeDrawParticleObserver = this._particleSystem.onBeforeDrawParticlesObservable.add(() => { - this._engine.setAlphaMode(2); - }); - } - } - /** - * Gets the vertex buffers - */ - get vertexBuffers() { - return this._particleSystem.vertexBuffers; - } - /** - * Gets the index buffer (or null if the object is using instancing) - */ - get indexBuffer() { - return this._particleSystem.indexBuffer; - } - /** - * Creates a new instance of the class - * @param scene The scene the particle system is part of - * @param ps The particle system - */ - constructor(scene, ps) { - super(scene); - this._useTrueRenderingForDiffuseTexture = true; - this._particleSystem = ps; - this._originalRender = ps.render.bind(ps); - this._blendMode = ps.blendMode; - this._onBeforeDrawParticleObserver = null; - this._updateInAnimate = this._particleSystem.updateInAnimate; - this._particleSystem.updateInAnimate = true; - this._particleSystem.render = () => 0; - this.particleSize = (ps.minSize + ps.maxSize) / 2; - this.useTrueRenderingForDiffuseTexture = false; - } - /** - * Indicates if the object is ready to be rendered - * @returns True if everything is ready for the object to be rendered, otherwise false - */ - isReady() { - return super.isReady() && this._particleSystem.isReady(); - } - /** - * Gets the number of particles in this particle system - * @returns The number of particles - */ - get numParticles() { - return this._particleSystem.getActiveCount(); - } - /** - * Render the diffuse texture for this object - */ - renderDiffuseTexture() { - this._originalRender(); - } - /** - * Releases the ressources used by the class - */ - 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; - } -} -//# sourceMappingURL=fluidRenderingObjectParticleSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingTextures.js - - - - - -/** @internal */ -class FluidRenderingTextures { - get blurNumIterations() { - return this._blurNumIterations; - } - set blurNumIterations(numIterations) { - if (this._blurNumIterations === numIterations) { - return; - } - this._blurNumIterations = numIterations; - if (this._blurPostProcesses !== null) { - const blurX = this._blurPostProcesses[0]; - const blurY = this._blurPostProcesses[1]; - this._blurPostProcesses = []; - for (let i = 0; i < this._blurNumIterations * 2; ++i) { - this._blurPostProcesses[i] = i & 1 ? blurY : blurX; - } - } - } - get renderTarget() { - return this._rt; - } - get renderTargetBlur() { - return this._rtBlur; - } - get texture() { - return this._texture; - } - get textureBlur() { - return this._textureBlurred; - } - constructor(name, scene, width, height, blurTextureSizeX, blurTextureSizeY, textureType = 1, textureFormat = 6, blurTextureType = 1, blurTextureFormat = 6, useStandardBlur = false, camera = null, generateDepthBuffer = true, samples = 1) { - this.enableBlur = true; - this.blurSizeDivisor = 1; - this.blurFilterSize = 7; - this._blurNumIterations = 3; - this.blurMaxFilterSize = 100; - this.blurDepthScale = 10; - this.particleSize = 0.02; - this.onDisposeObservable = new observable_Observable(); - this._name = name; - this._scene = scene; - this._camera = camera; - this._engine = scene.getEngine(); - this._width = width; - this._height = height; - this._blurTextureSizeX = blurTextureSizeX; - this._blurTextureSizeY = blurTextureSizeY; - this._textureType = textureType; - this._textureFormat = textureFormat; - this._blurTextureType = blurTextureType; - this._blurTextureFormat = blurTextureFormat; - this._useStandardBlur = useStandardBlur; - this._generateDepthBuffer = generateDepthBuffer; - this._samples = samples; - this._postProcessRunningIndex = 0; - this.enableBlur = blurTextureSizeX !== 0 && blurTextureSizeY !== 0; - this._rt = null; - this._texture = null; - this._rtBlur = null; - this._textureBlurred = null; - this._blurPostProcesses = null; - } - initialize() { - this.dispose(); - this._createRenderTarget(); - if (this.enableBlur && this._texture) { - const [rtBlur, textureBlurred, blurPostProcesses] = this._createBlurPostProcesses(this._texture, this._blurTextureType, this._blurTextureFormat, this.blurSizeDivisor, this._name, this._useStandardBlur); - this._rtBlur = rtBlur; - this._textureBlurred = textureBlurred; - this._blurPostProcesses = blurPostProcesses; - } - } - applyBlurPostProcesses() { - if (this.enableBlur && this._blurPostProcesses) { - this._postProcessRunningIndex = 0; - this._scene.postProcessManager.directRender(this._blurPostProcesses, this._rtBlur, true); - this._engine.unBindFramebuffer(this._rtBlur); - } - } - _createRenderTarget() { - this._rt = this._engine.createRenderTargetTexture({ width: this._width, height: this._height }, { - generateMipMaps: false, - type: this._textureType, - format: this._textureFormat, - samplingMode: 1, - generateDepthBuffer: this._generateDepthBuffer, - generateStencilBuffer: false, - samples: this._samples, - label: `FluidRenderingRTT-${this._name}`, - }); - const renderTexture = this._rt.texture; - renderTexture.incrementReferences(); - this._texture = new texture_Texture(null, this._scene); - this._texture.name = "rtt" + this._name; - this._texture._texture = renderTexture; - this._texture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - this._texture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._texture.anisotropicFilteringLevel = 1; - } - _createBlurPostProcesses(textureBlurSource, textureType, textureFormat, blurSizeDivisor, debugName, useStandardBlur = false) { - const engine = this._scene.getEngine(); - const targetSize = new math_vector_Vector2(Math.floor(this._blurTextureSizeX / blurSizeDivisor), Math.floor(this._blurTextureSizeY / blurSizeDivisor)); - const useBilinearFiltering = (textureType === 1 && engine.getCaps().textureFloatLinearFiltering) || - (textureType === 2 && engine.getCaps().textureHalfFloatLinearFiltering); - const rtBlur = this._engine.createRenderTargetTexture({ width: targetSize.x, height: targetSize.y }, { - generateMipMaps: false, - type: textureType, - format: textureFormat, - samplingMode: useBilinearFiltering ? 2 : 1, - generateDepthBuffer: false, - generateStencilBuffer: false, - samples: this._samples, - label: `FluidRenderingRTTBlur-${debugName}`, - }); - const renderTexture = rtBlur.texture; - renderTexture.incrementReferences(); - const texture = new texture_Texture(null, this._scene); - texture.name = "rttBlurred" + debugName; - texture._texture = renderTexture; - texture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - texture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - texture.anisotropicFilteringLevel = 1; - if (useStandardBlur) { - const kernelBlurXPostprocess = new postProcess_PostProcess("BilateralBlurX", "fluidRenderingStandardBlur", ["filterSize", "blurDir"], null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat); - kernelBlurXPostprocess.samples = this._samples; - kernelBlurXPostprocess.externalTextureSamplerBinding = true; - kernelBlurXPostprocess.onApplyObservable.add((effect) => { - if (this._postProcessRunningIndex === 0) { - effect.setTexture("textureSampler", textureBlurSource); - } - else { - effect._bindTexture("textureSampler", kernelBlurXPostprocess.inputTexture.texture); - } - effect.setInt("filterSize", this.blurFilterSize); - effect.setFloat2("blurDir", 1 / this._blurTextureSizeX, 0); - this._postProcessRunningIndex++; - }); - kernelBlurXPostprocess.onSizeChangedObservable.add(() => { - kernelBlurXPostprocess._textures.forEach((rt) => { - rt.texture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - rt.texture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - }); - }); - this._fixReusablePostProcess(kernelBlurXPostprocess); - const kernelBlurYPostprocess = new postProcess_PostProcess("BilateralBlurY", "fluidRenderingStandardBlur", ["filterSize", "blurDir"], null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat); - kernelBlurYPostprocess.samples = this._samples; - kernelBlurYPostprocess.onApplyObservable.add((effect) => { - effect.setInt("filterSize", this.blurFilterSize); - effect.setFloat2("blurDir", 0, 1 / this._blurTextureSizeY); - this._postProcessRunningIndex++; - }); - kernelBlurYPostprocess.onSizeChangedObservable.add(() => { - kernelBlurYPostprocess._textures.forEach((rt) => { - rt.texture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - rt.texture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - }); - }); - this._fixReusablePostProcess(kernelBlurYPostprocess); - kernelBlurXPostprocess.autoClear = false; - kernelBlurYPostprocess.autoClear = false; - const blurList = []; - for (let i = 0; i < this._blurNumIterations * 2; ++i) { - blurList[i] = i & 1 ? kernelBlurYPostprocess : kernelBlurXPostprocess; - } - return [rtBlur, texture, blurList]; - } - else { - const uniforms = ["maxFilterSize", "blurDir", "projectedParticleConstant", "depthThreshold"]; - const kernelBlurXPostprocess = new postProcess_PostProcess("BilateralBlurX", "fluidRenderingBilateralBlur", uniforms, null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat); - kernelBlurXPostprocess.samples = this._samples; - kernelBlurXPostprocess.externalTextureSamplerBinding = true; - kernelBlurXPostprocess.onApplyObservable.add((effect) => { - if (this._postProcessRunningIndex === 0) { - effect.setTexture("textureSampler", textureBlurSource); - } - else { - effect._bindTexture("textureSampler", kernelBlurXPostprocess.inputTexture.texture); - } - effect.setInt("maxFilterSize", this.blurMaxFilterSize); - effect.setFloat2("blurDir", 1 / this._blurTextureSizeX, 0); - effect.setFloat("projectedParticleConstant", this._getProjectedParticleConstant()); - effect.setFloat("depthThreshold", this._getDepthThreshold()); - this._postProcessRunningIndex++; - }); - kernelBlurXPostprocess.onSizeChangedObservable.add(() => { - kernelBlurXPostprocess._textures.forEach((rt) => { - rt.texture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - rt.texture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - }); - }); - this._fixReusablePostProcess(kernelBlurXPostprocess); - const kernelBlurYPostprocess = new postProcess_PostProcess("BilateralBlurY", "fluidRenderingBilateralBlur", uniforms, null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat); - kernelBlurYPostprocess.samples = this._samples; - kernelBlurYPostprocess.onApplyObservable.add((effect) => { - effect.setInt("maxFilterSize", this.blurMaxFilterSize); - effect.setFloat2("blurDir", 0, 1 / this._blurTextureSizeY); - effect.setFloat("projectedParticleConstant", this._getProjectedParticleConstant()); - effect.setFloat("depthThreshold", this._getDepthThreshold()); - this._postProcessRunningIndex++; - }); - kernelBlurYPostprocess.onSizeChangedObservable.add(() => { - kernelBlurYPostprocess._textures.forEach((rt) => { - rt.texture.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - rt.texture.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - }); - }); - this._fixReusablePostProcess(kernelBlurYPostprocess); - kernelBlurXPostprocess.autoClear = false; - kernelBlurYPostprocess.autoClear = false; - const blurList = []; - for (let i = 0; i < this._blurNumIterations * 2; ++i) { - blurList[i] = i & 1 ? kernelBlurYPostprocess : kernelBlurXPostprocess; - } - return [rtBlur, texture, blurList]; - } - } - _fixReusablePostProcess(pp) { - if (!pp.isReusable()) { - return; - } - pp.onActivateObservable.add(() => { - // undo what calling activate() does which will make sure we will retrieve the right texture when getting the input for the post process - pp._currentRenderTextureInd = (pp._currentRenderTextureInd + 1) % 2; - }); - pp.onApplyObservable.add(() => { - // now we can advance to the next texture - pp._currentRenderTextureInd = (pp._currentRenderTextureInd + 1) % 2; - }); - } - _getProjectedParticleConstant() { - var _a, _b; - 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); - } - _getDepthThreshold() { - return (this.particleSize / 2) * this.blurDepthScale; - } - dispose() { - var _a, _b, _c, _d; - if (this.onDisposeObservable.hasObservers()) { - this.onDisposeObservable.notifyObservers(this); - } - (_a = this._rt) === null || _a === void 0 ? void 0 : _a.dispose(); - this._rt = null; - (_b = this._texture) === null || _b === void 0 ? void 0 : _b.dispose(); - this._texture = null; - (_c = this._rtBlur) === null || _c === void 0 ? void 0 : _c.dispose(); - this._rtBlur = null; - (_d = this._textureBlurred) === null || _d === void 0 ? void 0 : _d.dispose(); - this._textureBlurred = null; - if (this._blurPostProcesses) { - this._blurPostProcesses[0].dispose(); - this._blurPostProcesses[1].dispose(); - } - this._blurPostProcesses = null; - } -} -//# sourceMappingURL=fluidRenderingTextures.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingTargetRenderer.js - - - - - - -/** - * Textures that can be displayed as a debugging tool - */ -var FluidRenderingDebug; -(function (FluidRenderingDebug) { - FluidRenderingDebug[FluidRenderingDebug["DepthTexture"] = 0] = "DepthTexture"; - FluidRenderingDebug[FluidRenderingDebug["DepthBlurredTexture"] = 1] = "DepthBlurredTexture"; - FluidRenderingDebug[FluidRenderingDebug["ThicknessTexture"] = 2] = "ThicknessTexture"; - FluidRenderingDebug[FluidRenderingDebug["ThicknessBlurredTexture"] = 3] = "ThicknessBlurredTexture"; - FluidRenderingDebug[FluidRenderingDebug["DiffuseTexture"] = 4] = "DiffuseTexture"; - FluidRenderingDebug[FluidRenderingDebug["Normals"] = 5] = "Normals"; - FluidRenderingDebug[FluidRenderingDebug["DiffuseRendering"] = 6] = "DiffuseRendering"; -})(FluidRenderingDebug || (FluidRenderingDebug = {})); -/** - * Class used to render an object as a fluid thanks to different render target textures (depth, thickness, diffuse) - */ -class FluidRenderingTargetRenderer { - /** - * Returns true if the class needs to be reinitialized (because of changes in parameterization) - */ - get needInitialization() { - return this._needInitialization; - } - /** - * Gets or sets a boolean indicating that the diffuse texture should be generated and used for the rendering - */ - get generateDiffuseTexture() { - return this._generateDiffuseTexture; - } - set generateDiffuseTexture(generate) { - if (this._generateDiffuseTexture === generate) { - return; - } - this._generateDiffuseTexture = generate; - this._needInitialization = true; - } - /** - * Gets or sets the feature (texture) to be debugged. Not used if debug is false - */ - get debugFeature() { - return this._debugFeature; - } - set debugFeature(feature) { - if (this._debugFeature === feature) { - return; - } - this._needInitialization = true; - this._debugFeature = feature; - } - /** - * Gets or sets a boolean indicating if we should display a specific texture (given by debugFeature) for debugging purpose - */ - get debug() { - return this._debug; - } - set debug(debug) { - if (this._debug === debug) { - return; - } - this._debug = debug; - this._needInitialization = true; - } - /** - * Gets or sets the environment map used for the reflection part of the shading - * If null, no map will be used. If undefined, the scene.environmentMap will be used (if defined) - */ - get environmentMap() { - return this._environmentMap; - } - set environmentMap(map) { - if (this._environmentMap === map) { - return; - } - this._needInitialization = true; - this._environmentMap = map; - } - /** - * Gets or sets a boolean indicating that the depth texture should be blurred - */ - get enableBlurDepth() { - return this._enableBlurDepth; - } - set enableBlurDepth(enable) { - if (this._enableBlurDepth === enable) { - return; - } - this._enableBlurDepth = enable; - this._needInitialization = true; - } - /** - * 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 - * For eg. if blurDepthSizeDivisor=2, the texture used to blur the depth will be half the size of the depth texture - */ - get blurDepthSizeDivisor() { - return this._blurDepthSizeDivisor; - } - set blurDepthSizeDivisor(scale) { - if (this._blurDepthSizeDivisor === scale) { - return; - } - this._blurDepthSizeDivisor = scale; - this._needInitialization = true; - } - /** - * 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) - */ - get blurDepthFilterSize() { - return this._blurDepthFilterSize; - } - set blurDepthFilterSize(filterSize) { - if (this._blurDepthFilterSize === filterSize) { - return; - } - this._blurDepthFilterSize = filterSize; - this._setBlurParameters(); - } - /** - * 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) - */ - get blurDepthNumIterations() { - return this._blurDepthNumIterations; - } - set blurDepthNumIterations(numIterations) { - if (this._blurDepthNumIterations === numIterations) { - return; - } - this._blurDepthNumIterations = numIterations; - this._setBlurParameters(); - } - /** - * 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) - */ - get blurDepthMaxFilterSize() { - return this._blurDepthMaxFilterSize; - } - set blurDepthMaxFilterSize(maxFilterSize) { - if (this._blurDepthMaxFilterSize === maxFilterSize) { - return; - } - this._blurDepthMaxFilterSize = maxFilterSize; - this._setBlurParameters(); - } - /** - * Depth weight in the calculation when applying the bilateral blur to generate the depth blur texture (positive number, generally between 0 and 100) - */ - get blurDepthDepthScale() { - return this._blurDepthDepthScale; - } - set blurDepthDepthScale(scale) { - if (this._blurDepthDepthScale === scale) { - return; - } - this._blurDepthDepthScale = scale; - this._setBlurParameters(); - } - /** - * Gets or sets a boolean indicating that the thickness texture should be blurred - */ - get enableBlurThickness() { - return this._enableBlurThickness; - } - set enableBlurThickness(enable) { - if (this._enableBlurThickness === enable) { - return; - } - this._enableBlurThickness = enable; - this._needInitialization = true; - } - /** - * 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 - * For eg. if blurThicknessSizeDivisor=2, the texture used to blur the thickness will be half the size of the thickness texture - */ - get blurThicknessSizeDivisor() { - return this._blurThicknessSizeDivisor; - } - set blurThicknessSizeDivisor(scale) { - if (this._blurThicknessSizeDivisor === scale) { - return; - } - this._blurThicknessSizeDivisor = scale; - this._needInitialization = true; - } - /** - * 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) - */ - get blurThicknessFilterSize() { - return this._blurThicknessFilterSize; - } - set blurThicknessFilterSize(filterSize) { - if (this._blurThicknessFilterSize === filterSize) { - return; - } - this._blurThicknessFilterSize = filterSize; - this._setBlurParameters(); - } - /** - * 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) - */ - get blurThicknessNumIterations() { - return this._blurThicknessNumIterations; - } - set blurThicknessNumIterations(numIterations) { - if (this._blurThicknessNumIterations === numIterations) { - return; - } - this._blurThicknessNumIterations = numIterations; - this._setBlurParameters(); - } - /** - * Gets or sets a boolean indicating that a fixed thickness should be used instead of generating a thickness texture - */ - get useFixedThickness() { - return this._useFixedThickness; - } - set useFixedThickness(use) { - if (this._useFixedThickness === use) { - return; - } - this._useFixedThickness = use; - this._needInitialization = true; - } - /** - * Gets or sets a boolean indicating that the velocity should be used when rendering the particles as a fluid. - * Note: the vertex buffers must contain a "velocity" buffer for this to work! - */ - get useVelocity() { - return this._useVelocity; - } - set useVelocity(use) { - if (this._useVelocity === use) { - return; - } - this._useVelocity = use; - this._needInitialization = true; - this._onUseVelocityChanged.notifyObservers(this); - } - /** - * Defines the size of the depth texture. - * If null, the texture will have the size of the screen - */ - get depthMapSize() { - return this._depthMapSize; - } - set depthMapSize(size) { - if (this._depthMapSize === size) { - return; - } - this._depthMapSize = size; - this._needInitialization = true; - } - /** - * Defines the size of the thickness texture. - * If null, the texture will have the size of the screen - */ - get thicknessMapSize() { - return this._thicknessMapSize; - } - set thicknessMapSize(size) { - if (this._thicknessMapSize === size) { - return; - } - this._thicknessMapSize = size; - this._needInitialization = true; - } - /** - * Defines the size of the diffuse texture. - * If null, the texture will have the size of the screen - */ - get diffuseMapSize() { - return this._diffuseMapSize; - } - set diffuseMapSize(size) { - if (this._diffuseMapSize === size) { - return; - } - this._diffuseMapSize = size; - this._needInitialization = true; - } - /** - * Gets or sets the number of samples used by MSAA - * 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) - */ - get samples() { - return this._samples; - } - set samples(samples) { - if (this._samples === samples) { - return; - } - this._samples = samples; - this._needInitialization = true; - } - /** - * Gets the camera used for the rendering - */ - get camera() { - return this._camera; - } - /** - * Creates an instance of the class - * @param scene Scene used to render the fluid object into - * @param camera Camera used to render the fluid object. If not provided, use the active camera of the scene instead - */ - constructor(scene, camera) { - this._generateDiffuseTexture = false; - /** - * Fluid color. Not used if generateDiffuseTexture is true - */ - this.fluidColor = new math_color_Color3(0.085, 0.6375, 0.765); - /** - * Density of the fluid (positive number). The higher the value, the more opaque the fluid. - */ - this.density = 2; - /** - * Strength of the refraction (positive number, but generally between 0 and 0.3). - */ - this.refractionStrength = 0.1; - /** - * Strength of the fresnel effect (value between 0 and 1). Lower the value if you want to soften the specular effect - */ - this.fresnelClamp = 1.0; - /** - * Strength of the specular power (positive number). Increase the value to make the specular effect more concentrated - */ - this.specularPower = 250; - /** - * Minimum thickness of the particles (positive number). If useFixedThickness is true, minimumThickness is the thickness used - */ - this.minimumThickness = 0; - /** - * Direction of the light. The fluid is assumed to be lit by a directional light - */ - this.dirLight = new math_vector_Vector3(-2, -1, 1).normalize(); - this._debugFeature = FluidRenderingDebug.DepthBlurredTexture; - this._debug = false; - this._enableBlurDepth = true; - this._blurDepthSizeDivisor = 1; - this._blurDepthFilterSize = 7; - this._blurDepthNumIterations = 3; - this._blurDepthMaxFilterSize = 100; - this._blurDepthDepthScale = 10; - this._enableBlurThickness = true; - this._blurThicknessSizeDivisor = 1; - this._blurThicknessFilterSize = 5; - this._blurThicknessNumIterations = 1; - this._useFixedThickness = false; - /** @internal */ - this._onUseVelocityChanged = new observable_Observable(); - this._useVelocity = false; - this._depthMapSize = null; - this._thicknessMapSize = null; - this._diffuseMapSize = null; - this._samples = 1; - this._scene = scene; - this._engine = scene.getEngine(); - this._camera = camera !== null && camera !== void 0 ? camera : scene.activeCamera; - this._needInitialization = true; - this._bgDepthTexture = null; - this._invProjectionMatrix = new math_vector_Matrix(); - this._depthClearColor = new math_color_Color4(1e6, 1e6, 1e6, 1); - this._thicknessClearColor = new math_color_Color4(0, 0, 0, 1); - this._depthRenderTarget = null; - this._diffuseRenderTarget = null; - this._thicknessRenderTarget = null; - this._renderPostProcess = null; - } - /** @internal */ - _initialize() { - var _a, _b, _c; - this.dispose(); - this._needInitialization = false; - const depthWidth = (_a = this._depthMapSize) !== null && _a !== void 0 ? _a : this._engine.getRenderWidth(); - const depthHeight = this._depthMapSize !== null ? Math.round((this._depthMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth()) : this._engine.getRenderHeight(); - this._depthRenderTarget = new FluidRenderingTextures("Depth", this._scene, depthWidth, depthHeight, depthWidth, depthHeight, 1, 7, 1, 7, false, this._camera, true, this._samples); - this._initializeRenderTarget(this._depthRenderTarget); - if (this.generateDiffuseTexture) { - const diffuseWidth = (_b = this._diffuseMapSize) !== null && _b !== void 0 ? _b : this._engine.getRenderWidth(); - const diffuseHeight = this._diffuseMapSize !== null - ? Math.round((this._diffuseMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth()) - : this._engine.getRenderHeight(); - this._diffuseRenderTarget = new FluidRenderingTextures("Diffuse", this._scene, diffuseWidth, diffuseHeight, 0, 0, 0, 5, 0, 5, true, this._camera, true, this._samples); - this._initializeRenderTarget(this._diffuseRenderTarget); - } - const thicknessWidth = (_c = this._thicknessMapSize) !== null && _c !== void 0 ? _c : this._engine.getRenderWidth(); - const thicknessHeight = this._thicknessMapSize !== null - ? Math.round((this._thicknessMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth()) - : this._engine.getRenderHeight(); - if (!this._useFixedThickness) { - this._thicknessRenderTarget = new FluidRenderingTextures("Thickness", this._scene, thicknessWidth, thicknessHeight, thicknessWidth, thicknessHeight, 2, 6, 2, 6, true, this._camera, false, this._samples); - this._initializeRenderTarget(this._thicknessRenderTarget); - } - this._createLiquidRenderingPostProcess(); - } - _setBlurParameters(renderTarget = null) { - if (renderTarget === null || renderTarget === this._depthRenderTarget) { - this._setBlurDepthParameters(); - } - if (renderTarget === null || renderTarget === this._thicknessRenderTarget) { - this._setBlurThicknessParameters(); - } - } - _setBlurDepthParameters() { - if (!this._depthRenderTarget) { - return; - } - this._depthRenderTarget.blurFilterSize = this.blurDepthFilterSize; - this._depthRenderTarget.blurMaxFilterSize = this.blurDepthMaxFilterSize; - this._depthRenderTarget.blurNumIterations = this.blurDepthNumIterations; - this._depthRenderTarget.blurDepthScale = this.blurDepthDepthScale; - } - _setBlurThicknessParameters() { - if (!this._thicknessRenderTarget) { - return; - } - this._thicknessRenderTarget.blurFilterSize = this.blurThicknessFilterSize; - this._thicknessRenderTarget.blurNumIterations = this.blurThicknessNumIterations; - } - _initializeRenderTarget(renderTarget) { - if (renderTarget !== this._diffuseRenderTarget) { - renderTarget.enableBlur = renderTarget === this._depthRenderTarget ? this.enableBlurDepth : this.enableBlurThickness; - renderTarget.blurSizeDivisor = renderTarget === this._depthRenderTarget ? this.blurDepthSizeDivisor : this.blurThicknessSizeDivisor; - } - this._setBlurParameters(renderTarget); - renderTarget.initialize(); - } - _createLiquidRenderingPostProcess() { - var _a; - const engine = this._scene.getEngine(); - const uniformNames = [ - "viewMatrix", - "projectionMatrix", - "invProjectionMatrix", - "texelSize", - "dirLight", - "cameraFar", - "density", - "refractionStrength", - "fresnelClamp", - "specularPower", - ]; - const samplerNames = ["depthSampler"]; - const defines = []; - this.dispose(true); - if (!this._camera) { - return; - } - const texture = this._depthRenderTarget.enableBlur ? this._depthRenderTarget.textureBlur : this._depthRenderTarget.texture; - const texelSize = new math_vector_Vector2(1 / texture.getSize().width, 1 / texture.getSize().height); - if (this._scene.useRightHandedSystem) { - defines.push("#define FLUIDRENDERING_RHS"); - } - if (this._environmentMap !== null) { - const envMap = (_a = this._environmentMap) !== null && _a !== void 0 ? _a : this._scene.environmentTexture; - if (envMap) { - samplerNames.push("reflectionSampler"); - defines.push("#define FLUIDRENDERING_ENVIRONMENT"); - } - } - if (this._diffuseRenderTarget) { - samplerNames.push("diffuseSampler"); - defines.push("#define FLUIDRENDERING_DIFFUSETEXTURE"); - } - else { - uniformNames.push("diffuseColor"); - } - if (this._useVelocity) { - samplerNames.push("velocitySampler"); - defines.push("#define FLUIDRENDERING_VELOCITY"); - } - if (this._useFixedThickness) { - uniformNames.push("thickness"); - samplerNames.push("bgDepthSampler"); - defines.push("#define FLUIDRENDERING_FIXED_THICKNESS"); - } - else { - uniformNames.push("minimumThickness"); - samplerNames.push("thicknessSampler"); - } - if (this._debug) { - defines.push("#define FLUIDRENDERING_DEBUG"); - if (this._debugFeature === FluidRenderingDebug.Normals) { - defines.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"); - } - else if (this._debugFeature === FluidRenderingDebug.DiffuseRendering) { - defines.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"); - } - else { - defines.push("#define FLUIDRENDERING_DEBUG_TEXTURE"); - samplerNames.push("debugSampler"); - if (this._debugFeature === FluidRenderingDebug.DepthTexture || this._debugFeature === FluidRenderingDebug.DepthBlurredTexture) { - defines.push("#define FLUIDRENDERING_DEBUG_DEPTH"); - } - } - } - this._renderPostProcess = new postProcess_PostProcess("FluidRendering", "fluidRenderingRender", uniformNames, samplerNames, 1, null, 2, engine, false, null, 0, undefined, undefined, true, undefined); - this._renderPostProcess.updateEffect(defines.join("\n")); - this._renderPostProcess.samples = this._samples; - this._renderPostProcess.onApplyObservable.add((effect) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y; - this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()); - this._invProjectionMatrix.invert(); - if (engine.isWebGPU) { - effect.setTextureSampler("textureSamplerSampler", this._renderPostProcess.inputTexture.texture); - } - if (!this._depthRenderTarget.enableBlur) { - effect.setTexture("depthSampler", this._depthRenderTarget.texture); - if (engine.isWebGPU) { - effect.setTextureSampler("depthSamplerSampler", (_b = (_a = this._depthRenderTarget.texture) === null || _a === void 0 ? void 0 : _a.getInternalTexture()) !== null && _b !== void 0 ? _b : null); - } - } - else { - effect.setTexture("depthSampler", this._depthRenderTarget.textureBlur); - if (engine.isWebGPU) { - effect.setTextureSampler("depthSamplerSampler", (_d = (_c = this._depthRenderTarget.textureBlur) === null || _c === void 0 ? void 0 : _c.getInternalTexture()) !== null && _d !== void 0 ? _d : null); - } - } - if (this._diffuseRenderTarget) { - if (!this._diffuseRenderTarget.enableBlur) { - effect.setTexture("diffuseSampler", this._diffuseRenderTarget.texture); - if (engine.isWebGPU) { - effect.setTextureSampler("diffuseSamplerSampler", (_f = (_e = this._diffuseRenderTarget.texture) === null || _e === void 0 ? void 0 : _e.getInternalTexture()) !== null && _f !== void 0 ? _f : null); - } - } - else { - effect.setTexture("diffuseSampler", this._diffuseRenderTarget.textureBlur); - if (engine.isWebGPU) { - effect.setTextureSampler("diffuseSamplerSampler", (_h = (_g = this._diffuseRenderTarget.textureBlur) === null || _g === void 0 ? void 0 : _g.getInternalTexture()) !== null && _h !== void 0 ? _h : null); - } - } - } - else { - effect.setColor3("diffuseColor", this.fluidColor); - } - if (this._useFixedThickness) { - effect.setFloat("thickness", this.minimumThickness); - effect._bindTexture("bgDepthSampler", this._bgDepthTexture); - if (engine.isWebGPU) { - effect.setTextureSampler("bgDepthSamplerSampler", (_j = this._bgDepthTexture) !== null && _j !== void 0 ? _j : null); - } - } - else { - if (!this._thicknessRenderTarget.enableBlur) { - effect.setTexture("thicknessSampler", this._thicknessRenderTarget.texture); - if (engine.isWebGPU) { - effect.setTextureSampler("thicknessSamplerSampler", (_l = (_k = this._thicknessRenderTarget.texture) === null || _k === void 0 ? void 0 : _k.getInternalTexture()) !== null && _l !== void 0 ? _l : null); - } - } - else { - effect.setTexture("thicknessSampler", this._thicknessRenderTarget.textureBlur); - if (engine.isWebGPU) { - effect.setTextureSampler("thicknessSamplerSampler", (_o = (_m = this._thicknessRenderTarget.textureBlur) === null || _m === void 0 ? void 0 : _m.getInternalTexture()) !== null && _o !== void 0 ? _o : null); - } - } - effect.setFloat("minimumThickness", this.minimumThickness); - } - if (this._environmentMap !== null) { - const envMap = (_p = this._environmentMap) !== null && _p !== void 0 ? _p : this._scene.environmentTexture; - if (envMap) { - effect.setTexture("reflectionSampler", envMap); - if (engine.isWebGPU) { - effect.setTextureSampler("reflectionSamplerSampler", (_q = envMap === null || envMap === void 0 ? void 0 : envMap.getInternalTexture()) !== null && _q !== void 0 ? _q : null); - } - } - } - effect.setMatrix("viewMatrix", this._scene.getViewMatrix()); - effect.setMatrix("invProjectionMatrix", this._invProjectionMatrix); - effect.setMatrix("projectionMatrix", this._scene.getProjectionMatrix()); - effect.setVector2("texelSize", texelSize); - effect.setFloat("density", this.density); - effect.setFloat("refractionStrength", this.refractionStrength); - effect.setFloat("fresnelClamp", this.fresnelClamp); - effect.setFloat("specularPower", this.specularPower); - effect.setVector3("dirLight", this.dirLight); - effect.setFloat("cameraFar", this._camera.maxZ); - if (this._debug) { - let texture = null; - switch (this._debugFeature) { - case FluidRenderingDebug.DepthTexture: - texture = this._depthRenderTarget.texture; - break; - case FluidRenderingDebug.DepthBlurredTexture: - texture = this._depthRenderTarget.enableBlur ? this._depthRenderTarget.textureBlur : this._depthRenderTarget.texture; - break; - case FluidRenderingDebug.ThicknessTexture: - texture = (_s = (_r = this._thicknessRenderTarget) === null || _r === void 0 ? void 0 : _r.texture) !== null && _s !== void 0 ? _s : null; - break; - case FluidRenderingDebug.ThicknessBlurredTexture: - 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; - break; - case FluidRenderingDebug.DiffuseTexture: - if (this._diffuseRenderTarget) { - texture = this._diffuseRenderTarget.texture; - } - break; - } - if (this._debugFeature !== FluidRenderingDebug.Normals) { - effect.setTexture("debugSampler", texture); - if (engine.isWebGPU) { - effect.setTextureSampler("debugSamplerSampler", (_y = texture === null || texture === void 0 ? void 0 : texture.getInternalTexture()) !== null && _y !== void 0 ? _y : null); - } - } - } - }); - } - /** @internal */ - _clearTargets() { - var _a, _b, _c; - if ((_a = this._depthRenderTarget) === null || _a === void 0 ? void 0 : _a.renderTarget) { - this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget); - this._engine.clear(this._depthClearColor, true, true, false); - this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget); - } - if ((_b = this._diffuseRenderTarget) === null || _b === void 0 ? void 0 : _b.renderTarget) { - this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget); - this._engine.clear(this._thicknessClearColor, true, true, false); - this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget); - } - if ((_c = this._thicknessRenderTarget) === null || _c === void 0 ? void 0 : _c.renderTarget) { - this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget); - // 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 - this._engine.clear(this._thicknessClearColor, true, false, false); - this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget); - } - } - /** @internal */ - _render(fluidObject) { - var _a, _b, _c, _d, _e, _f; - if (this._needInitialization || !fluidObject.isReady()) { - return; - } - const currentRenderTarget = this._engine._currentRenderTarget; - this._engine.setState(false, undefined, undefined, undefined, true); - this._engine.setDepthBuffer(true); - this._engine.setDepthWrite(true); - this._engine.setAlphaMode(0); - // Render the particles in the depth texture - if ((_a = this._depthRenderTarget) === null || _a === void 0 ? void 0 : _a.renderTarget) { - this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget); - fluidObject.renderDepthTexture(); - this._engine.unbindInstanceAttributes(); - this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget); - } - // Render the particles in the diffuse texture - if ((_b = this._diffuseRenderTarget) === null || _b === void 0 ? void 0 : _b.renderTarget) { - this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget); - fluidObject.renderDiffuseTexture(); - this._engine.unbindInstanceAttributes(); - this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget); - } - // Render the particles in the thickness texture - if ((_c = this._thicknessRenderTarget) === null || _c === void 0 ? void 0 : _c.renderTarget) { - this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget); - fluidObject.renderThicknessTexture(); - this._engine.unbindInstanceAttributes(); - this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget); - } - // Run the blur post processes - (_d = this._depthRenderTarget) === null || _d === void 0 ? void 0 : _d.applyBlurPostProcesses(); - (_e = this._diffuseRenderTarget) === null || _e === void 0 ? void 0 : _e.applyBlurPostProcesses(); - (_f = this._thicknessRenderTarget) === null || _f === void 0 ? void 0 : _f.applyBlurPostProcesses(); - if (currentRenderTarget) { - this._engine.bindFramebuffer(currentRenderTarget); - } - } - /** - * Releases all the ressources used by the class - * @param onlyPostProcesses If true, releases only the ressources used by the render post processes - */ - dispose(onlyPostProcesses = false) { - var _a, _b, _c, _d; - if (!onlyPostProcesses) { - (_a = this._depthRenderTarget) === null || _a === void 0 ? void 0 : _a.dispose(); - this._depthRenderTarget = null; - (_b = this._diffuseRenderTarget) === null || _b === void 0 ? void 0 : _b.dispose(); - this._diffuseRenderTarget = null; - (_c = this._thicknessRenderTarget) === null || _c === void 0 ? void 0 : _c.dispose(); - this._thicknessRenderTarget = null; - } - if (this._renderPostProcess && this._camera) { - this._camera.detachPostProcess(this._renderPostProcess); - } - (_d = this._renderPostProcess) === null || _d === void 0 ? void 0 : _d.dispose(); - this._renderPostProcess = null; - this._needInitialization = false; - } -} -//# sourceMappingURL=fluidRenderingTargetRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingObjectCustomParticles.js - - - - -/** - * Defines a rendering object based on a list of custom buffers - * The list must contain at least a "position" buffer! - */ -class FluidRenderingObjectCustomParticles extends FluidRenderingObject { - /** - * Gets the name of the class - */ - getClassName() { - return "FluidRenderingObjectCustomParticles"; - } - /** - * Gets the vertex buffers - */ - get vertexBuffers() { - return this._vertexBuffers; - } - /** - * Creates a new instance of the class - * @param scene The scene the particles should be rendered into - * @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. - * @param numParticles Number of vertices to take into account from the buffers - */ - constructor(scene, buffers, numParticles) { - super(scene); - this._numParticles = numParticles; - this._diffuseEffectWrapper = null; - this._vertexBuffers = {}; - this.addBuffers(buffers); - } - /** - * Add some new buffers - * @param buffers List of buffers - */ - addBuffers(buffers) { - for (const name in buffers) { - let stride; - let instanced = true; - switch (name) { - case "velocity": - stride = 3; - break; - case "offset": - instanced = false; - break; - } - this._vertexBuffers[name] = new buffer_VertexBuffer(this._engine, buffers[name], name, true, false, stride, instanced); - } - } - _createEffects() { - super._createEffects(); - const uniformNames = ["view", "projection", "size"]; - const attributeNames = ["position", "offset", "color"]; - this._diffuseEffectWrapper = new EffectWrapper({ - engine: this._engine, - useShaderStore: true, - vertexShader: "fluidRenderingParticleDiffuse", - fragmentShader: "fluidRenderingParticleDiffuse", - attributeNames, - uniformNames, - samplerNames: [], - }); - } - /** - * Indicates if the object is ready to be rendered - * @returns True if everything is ready for the object to be rendered, otherwise false - */ - isReady() { - var _a, _b; - if (!this._vertexBuffers["offset"]) { - this._vertexBuffers["offset"] = new buffer_VertexBuffer(this._engine, [0, 0, 1, 0, 0, 1, 1, 1], "offset", false, false, 2); - } - return super.isReady() && ((_b = (_a = this._diffuseEffectWrapper) === null || _a === void 0 ? void 0 : _a.effect.isReady()) !== null && _b !== void 0 ? _b : false); - } - /** - * Gets the number of particles in this object - * @returns The number of particles - */ - get numParticles() { - return this._numParticles; - } - /** - * Sets the number of particles in this object - * @param num The number of particles to take into account - */ - setNumParticles(num) { - this._numParticles = num; - } - /** - * Render the diffuse texture for this object - */ - renderDiffuseTexture() { - const numParticles = this.numParticles; - if (!this._diffuseEffectWrapper || numParticles === 0) { - return; - } - const diffuseDrawWrapper = this._diffuseEffectWrapper._drawWrapper; - const diffuseEffect = diffuseDrawWrapper.effect; - this._engine.enableEffect(diffuseDrawWrapper); - this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, diffuseEffect); - diffuseEffect.setMatrix("view", this._scene.getViewMatrix()); - diffuseEffect.setMatrix("projection", this._scene.getProjectionMatrix()); - if (this._particleSize !== null) { - diffuseEffect.setFloat2("size", this._particleSize, this._particleSize); - } - if (this.useInstancing) { - this._engine.drawArraysType(7, 0, 4, numParticles); - } - else { - this._engine.drawElementsType(0, 0, numParticles); - } - } - /** - * Releases the ressources used by the class - */ - dispose() { - var _a; - super.dispose(); - (_a = this._diffuseEffectWrapper) === null || _a === void 0 ? void 0 : _a.dispose(); - for (const name in this._vertexBuffers) { - this._vertexBuffers[name].dispose(); - } - this._vertexBuffers = {}; - } -} -//# sourceMappingURL=fluidRenderingObjectCustomParticles.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/copyTextureToTexture.fragment.js -// Do not edit. - - -const copyTextureToTexture_fragment_name = "copyTextureToTexturePixelShader"; -const copyTextureToTexture_fragment_shader = `uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; -#include<helperFunctions> -void main(void) -{vec4 color=texture2D(textureSampler,vUV); -#ifdef DEPTH_TEXTURE -gl_FragDepth=color.r; -#else -if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} -gl_FragColor=color; -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[copyTextureToTexture_fragment_name] = copyTextureToTexture_fragment_shader; -/** @internal */ -const copyTextureToTexturePixelShader = { name: copyTextureToTexture_fragment_name, shader: copyTextureToTexture_fragment_shader }; -//# sourceMappingURL=copyTextureToTexture.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/copyTextureToTexture.js - - - -/** - * Conversion modes available when copying a texture into another one - */ -var ConversionMode; -(function (ConversionMode) { - ConversionMode[ConversionMode["None"] = 0] = "None"; - ConversionMode[ConversionMode["ToLinearSpace"] = 1] = "ToLinearSpace"; - ConversionMode[ConversionMode["ToGammaSpace"] = 2] = "ToGammaSpace"; -})(ConversionMode || (ConversionMode = {})); -/** - * Class used for fast copy from one texture to another - */ -class CopyTextureToTexture { - _textureIsInternal(texture) { - return texture.getInternalTexture === undefined; - } - /** - * Constructs a new instance of the class - * @param engine The engine to use for the copy - * @param isDepthTexture True means that we should write (using gl_FragDepth) into the depth texture attached to the destination (default: false) - */ - constructor(engine, isDepthTexture = false) { - this._engine = engine; - this._isDepthTexture = isDepthTexture; - this._renderer = new EffectRenderer(engine); - this._effectWrapper = new EffectWrapper({ - engine: engine, - name: "CopyTextureToTexture", - fragmentShader: "copyTextureToTexture", - useShaderStore: true, - uniformNames: ["conversion"], - samplerNames: ["textureSampler"], - defines: isDepthTexture ? ["#define DEPTH_TEXTURE"] : [], - }); - this._effectWrapper.onApplyObservable.add(() => { - if (isDepthTexture) { - engine.setState(false); - engine.setDepthBuffer(true); - engine.depthCullingState.depthMask = true; - engine.depthCullingState.depthFunc = 519; - } - if (this._textureIsInternal(this._source)) { - this._effectWrapper.effect._bindTexture("textureSampler", this._source); - } - else { - this._effectWrapper.effect.setTexture("textureSampler", this._source); - } - this._effectWrapper.effect.setFloat("conversion", this._conversion); - }); - } - /** - * Indicates if the effect is ready to be used for the copy - * @returns true if "copy" can be called without delay, else false - */ - isReady() { - return this._effectWrapper.effect.isReady(); - } - /** - * Copy one texture into another - * @param source The source texture - * @param destination The destination texture - * @param conversion The conversion mode that should be applied when copying - * @returns - */ - copy(source, destination, conversion = ConversionMode.None) { - if (!this.isReady()) { - return false; - } - this._source = source; - this._conversion = conversion; - const engineDepthFunc = this._engine.depthCullingState.depthFunc; - this._renderer.render(this._effectWrapper, destination); - if (this._isDepthTexture && engineDepthFunc) { - this._engine.depthCullingState.depthFunc = engineDepthFunc; - } - return true; - } - /** - * Releases all the resources used by the class - */ - dispose() { - this._effectWrapper.dispose(); - this._renderer.dispose(); - } -} -//# sourceMappingURL=copyTextureToTexture.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingDepthTextureCopy.js - - -/** @internal */ -class FluidRenderingDepthTextureCopy { - get depthRTWrapper() { - return this._depthRTWrapper; - } - constructor(engine, width, height, samples = 1) { - this._engine = engine; - this._copyTextureToTexture = new CopyTextureToTexture(engine, true); - this._depthRTWrapper = this._engine.createRenderTargetTexture({ width, height }, { - generateMipMaps: false, - type: 0, - format: 6, - samplingMode: 1, - generateDepthBuffer: true, - generateStencilBuffer: false, - samples, - noColorAttachment: true, - label: "FluidRenderingDepthTextureCopyRTT", - }); - this._depthRTWrapper.createDepthStencilTexture(0, false, false, 1, undefined, "FluidRenderingDepthTextureCopyRTTDepthStencil"); - } - copy(source) { - return this._copyTextureToTexture.copy(source, this._depthRTWrapper); - } - dispose() { - this._depthRTWrapper.dispose(); - this._copyTextureToTexture.dispose(); - } -} -//# sourceMappingURL=fluidRenderingDepthTextureCopy.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDepth.vertex.js -// Do not edit. - -const fluidRenderingParticleDepth_vertex_name = "fluidRenderingParticleDepthVertexShader"; -const fluidRenderingParticleDepth_vertex_shader = `attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; -#ifdef FLUIDRENDERING_VELOCITY -attribute vec3 velocity;varying float velocityNorm; -#endif -void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; -#ifdef FLUIDRENDERING_VELOCITY -velocityNorm=length(velocity); -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[fluidRenderingParticleDepth_vertex_name] = fluidRenderingParticleDepth_vertex_shader; -/** @internal */ -const fluidRenderingParticleDepthVertexShader = { name: fluidRenderingParticleDepth_vertex_name, shader: fluidRenderingParticleDepth_vertex_shader }; -//# sourceMappingURL=fluidRenderingParticleDepth.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDepth.fragment.js -// Do not edit. - -const fluidRenderingParticleDepth_fragment_name = "fluidRenderingParticleDepthPixelShader"; -const fluidRenderingParticleDepth_fragment_shader = `uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; -#ifdef FLUIDRENDERING_VELOCITY -varying float velocityNorm; -#endif -void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); -#ifndef FLUIDRENDERING_RHS -normal.z=-normal.z; -#endif -vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; -#ifdef WEBGPU -gl_FragDepth=clipSpacePos.z/clipSpacePos.w; -#else -gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; -#endif -#ifdef FLUIDRENDERING_RHS -realViewPos.z=-realViewPos.z; -#endif -#ifdef FLUIDRENDERING_VELOCITY -glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); -#else -glFragColor=vec4(realViewPos.z,0.,0.,1.); -#endif -} -`; -// Sideeffect -ShaderStore.ShadersStore[fluidRenderingParticleDepth_fragment_name] = fluidRenderingParticleDepth_fragment_shader; -/** @internal */ -const fluidRenderingParticleDepthPixelShader = { name: fluidRenderingParticleDepth_fragment_name, shader: fluidRenderingParticleDepth_fragment_shader }; -//# sourceMappingURL=fluidRenderingParticleDepth.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleThickness.vertex.js -// Do not edit. - -const fluidRenderingParticleThickness_vertex_name = "fluidRenderingParticleThicknessVertexShader"; -const fluidRenderingParticleThickness_vertex_shader = `attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} -`; -// Sideeffect -ShaderStore.ShadersStore[fluidRenderingParticleThickness_vertex_name] = fluidRenderingParticleThickness_vertex_shader; -/** @internal */ -const fluidRenderingParticleThicknessVertexShader = { name: fluidRenderingParticleThickness_vertex_name, shader: fluidRenderingParticleThickness_vertex_shader }; -//# sourceMappingURL=fluidRenderingParticleThickness.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleThickness.fragment.js -// Do not edit. - -const fluidRenderingParticleThickness_fragment_name = "fluidRenderingParticleThicknessPixelShader"; -const fluidRenderingParticleThickness_fragment_shader = `uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} -`; -// Sideeffect -ShaderStore.ShadersStore[fluidRenderingParticleThickness_fragment_name] = fluidRenderingParticleThickness_fragment_shader; -/** @internal */ -const fluidRenderingParticleThicknessPixelShader = { name: fluidRenderingParticleThickness_fragment_name, shader: fluidRenderingParticleThickness_fragment_shader }; -//# sourceMappingURL=fluidRenderingParticleThickness.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDiffuse.vertex.js -// Do not edit. - -const fluidRenderingParticleDiffuse_vertex_name = "fluidRenderingParticleDiffuseVertexShader"; -const fluidRenderingParticleDiffuse_vertex_shader = `attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} -`; -// Sideeffect -ShaderStore.ShadersStore[fluidRenderingParticleDiffuse_vertex_name] = fluidRenderingParticleDiffuse_vertex_shader; -/** @internal */ -const fluidRenderingParticleDiffuseVertexShader = { name: fluidRenderingParticleDiffuse_vertex_name, shader: fluidRenderingParticleDiffuse_vertex_shader }; -//# sourceMappingURL=fluidRenderingParticleDiffuse.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDiffuse.fragment.js -// Do not edit. - -const fluidRenderingParticleDiffuse_fragment_name = "fluidRenderingParticleDiffusePixelShader"; -const fluidRenderingParticleDiffuse_fragment_shader = `uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} -`; -// Sideeffect -ShaderStore.ShadersStore[fluidRenderingParticleDiffuse_fragment_name] = fluidRenderingParticleDiffuse_fragment_shader; -/** @internal */ -const fluidRenderingParticleDiffusePixelShader = { name: fluidRenderingParticleDiffuse_fragment_name, shader: fluidRenderingParticleDiffuse_fragment_shader }; -//# sourceMappingURL=fluidRenderingParticleDiffuse.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fluidRenderingBilateralBlur.fragment.js -// Do not edit. - -const fluidRenderingBilateralBlur_fragment_name = "fluidRenderingBilateralBlurPixelShader"; -const fluidRenderingBilateralBlur_fragment_shader = `uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} -int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} -glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} -`; -// Sideeffect -ShaderStore.ShadersStore[fluidRenderingBilateralBlur_fragment_name] = fluidRenderingBilateralBlur_fragment_shader; -/** @internal */ -const fluidRenderingBilateralBlurPixelShader = { name: fluidRenderingBilateralBlur_fragment_name, shader: fluidRenderingBilateralBlur_fragment_shader }; -//# sourceMappingURL=fluidRenderingBilateralBlur.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fluidRenderingStandardBlur.fragment.js -// Do not edit. - -const fluidRenderingStandardBlur_fragment_name = "fluidRenderingStandardBlurPixelShader"; -const fluidRenderingStandardBlur_fragment_shader = `uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} -float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} -sum/=wsum;glFragColor=vec4(sum.rgb,1.);} -`; -// Sideeffect -ShaderStore.ShadersStore[fluidRenderingStandardBlur_fragment_name] = fluidRenderingStandardBlur_fragment_shader; -/** @internal */ -const fluidRenderingStandardBlurPixelShader = { name: fluidRenderingStandardBlur_fragment_name, shader: fluidRenderingStandardBlur_fragment_shader }; -//# sourceMappingURL=fluidRenderingStandardBlur.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/fluidRenderingRender.fragment.js -// Do not edit. - -const fluidRenderingRender_fragment_name = "fluidRenderingRenderPixelShader"; -const fluidRenderingRender_fragment_shader = `/* disable_uniformity_analysis */ -#define IOR 1.333 -#define ETA 1.0/IOR -#define F0 0.02 -uniform sampler2D textureSampler;uniform sampler2D depthSampler; -#ifdef FLUIDRENDERING_DIFFUSETEXTURE -uniform sampler2D diffuseSampler; -#else -uniform vec3 diffuseColor; -#endif -#ifdef FLUIDRENDERING_FIXED_THICKNESS -uniform float thickness;uniform sampler2D bgDepthSampler; -#else -uniform float minimumThickness;uniform sampler2D thicknessSampler; -#endif -#ifdef FLUIDRENDERING_ENVIRONMENT -uniform samplerCube reflectionSampler; -#endif -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) -uniform sampler2D debugSampler; -#endif -uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; -#ifdef FLUIDRENDERING_RHS -ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; -#else -ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; -#endif -ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} -vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} -void main(void) {vec2 texCoord=vUV; -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) -vec4 color=texture2D(debugSampler,texCoord); -#ifdef FLUIDRENDERING_DEBUG_DEPTH -glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} -#else -glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} -#endif -return; -#endif -vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; -#ifndef FLUIDRENDERING_FIXED_THICKNESS -float thickness=texture2D(thicknessSampler,texCoord).x; -#else -float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; -#endif -vec4 backColor=texture2D(textureSampler,texCoord); -#ifndef FLUIDRENDERING_FIXED_THICKNESS -if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { -#else -if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { -#endif -glFragColor=backColor;return;} -vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} -vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} -vec3 normal=normalize(cross(ddy,ddx)); -#ifdef FLUIDRENDERING_RHS -normal=-normal; -#endif -#ifndef WEBGPU -if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} -#endif -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) -glFragColor=vec4(normal*0.5+0.5,1.0);return; -#endif -vec3 rayDir=normalize(viewPos); -#ifdef FLUIDRENDERING_DIFFUSETEXTURE -vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; -#endif -vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); -#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING -float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; -#endif -vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); -vec3 refractionColor=transmitted.rgb*transmittance; -#ifdef FLUIDRENDERING_ENVIRONMENT -vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; -#else -vec3 finalColor=refractionColor+specular; -#endif -#ifdef FLUIDRENDERING_VELOCITY -float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); -#endif -glFragColor=vec4(finalColor,transmitted.a);} -`; -// Sideeffect -ShaderStore.ShadersStore[fluidRenderingRender_fragment_name] = fluidRenderingRender_fragment_shader; -/** @internal */ -const fluidRenderingRenderPixelShader = { name: fluidRenderingRender_fragment_name, shader: fluidRenderingRender_fragment_shader }; -//# sourceMappingURL=fluidRenderingRender.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderer.js - - - - - - - - - - - - - - - - -Object.defineProperty(scene_Scene.prototype, "fluidRenderer", { - get: function () { - return this._fluidRenderer; - }, - set: function (value) { - this._fluidRenderer = value; - }, - enumerable: true, - configurable: true, -}); -scene_Scene.prototype.enableFluidRenderer = function () { - if (this._fluidRenderer) { - return this._fluidRenderer; - } - this._fluidRenderer = new FluidRenderer(this); - return this._fluidRenderer; -}; -scene_Scene.prototype.disableFluidRenderer = function () { - var _a; - (_a = this._fluidRenderer) === null || _a === void 0 ? void 0 : _a.dispose(); - this._fluidRenderer = null; -}; -function IsParticleSystemObject(obj) { - return !!obj.particleSystem; -} -/** - * Defines the fluid renderer scene component responsible to render objects as fluids - */ -class FluidRendererSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpful to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_FLUIDRENDERER; - this.scene = scene; - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._gatherActiveCameraRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER, this, this._gatherActiveCameraRenderTargets); - this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER, this, this._afterCameraDraw); - } - _gatherActiveCameraRenderTargets(_renderTargets) { - var _a; - (_a = this.scene.fluidRenderer) === null || _a === void 0 ? void 0 : _a._prepareRendering(); - } - _afterCameraDraw(camera) { - var _a; - (_a = this.scene.fluidRenderer) === null || _a === void 0 ? void 0 : _a._render(camera); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - if (this.scene._fluidRenderer) { - // Release resources first - this.scene.disableFluidRenderer(); - // Re-enable - this.scene.enableFluidRenderer(); - } - } - /** - * Disposes the component and the associated resources - */ - dispose() { - this.scene.disableFluidRenderer(); - } -} -/** - * Class responsible for fluid rendering. - * It is implementing the method described in https://developer.download.nvidia.com/presentations/2010/gdc/Direct3D_Effects.pdf - */ -class FluidRenderer { - /** @internal */ - static _SceneComponentInitialization(scene) { - let component = scene._getComponent(sceneComponent_SceneComponentConstants.NAME_FLUIDRENDERER); - if (!component) { - component = new FluidRendererSceneComponent(scene); - scene._addComponent(component); - } - } - /** - * Initializes the class - * @param scene Scene in which the objects are part of - */ - constructor(scene) { - this._scene = scene; - this._engine = scene.getEngine(); - this._onEngineResizeObserver = null; - this.renderObjects = []; - this.targetRenderers = []; - this._cameras = new Map(); - FluidRenderer._SceneComponentInitialization(this._scene); - this._onEngineResizeObserver = this._engine.onResizeObservable.add(() => { - this._initialize(); - }); - } - /** - * Reinitializes the class - * Can be used if you change the object priority (FluidRenderingObject.priority), to make sure the objects are rendered in the right order - */ - recreate() { - this._sortRenderingObjects(); - this._initialize(); - } - /** - * Gets the render object corresponding to a particle system (null if the particle system is not rendered as a fluid) - * @param ps The particle system - * @returns the render object corresponding to this particle system if any, otherwise null - */ - getRenderObjectFromParticleSystem(ps) { - const index = this._getParticleSystemIndex(ps); - return index !== -1 ? this.renderObjects[index] : null; - } - /** - * Adds a particle system to the fluid renderer. - * @param ps particle system - * @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) - * @param targetRenderer The target renderer used to display the particle system as a fluid. If not provided, the method will create a new one - * @param camera The camera used by the target renderer (if the target renderer is created by the method) - * @returns the render object corresponding to the particle system - */ - addParticleSystem(ps, generateDiffuseTexture, targetRenderer, camera) { - const object = new FluidRenderingObjectParticleSystem(this._scene, ps); - object.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)); - if (!targetRenderer) { - targetRenderer = new FluidRenderingTargetRenderer(this._scene, camera); - this.targetRenderers.push(targetRenderer); - } - if (!targetRenderer._onUseVelocityChanged.hasObservers()) { - targetRenderer._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)); - } - if (generateDiffuseTexture !== undefined) { - targetRenderer.generateDiffuseTexture = generateDiffuseTexture; - } - const renderObject = { object, targetRenderer }; - this.renderObjects.push(renderObject); - this._sortRenderingObjects(); - this._setParticleSizeForRenderTargets(); - return renderObject; - } - /** - * Adds a custom particle set to the fluid renderer. - * @param buffers The list of buffers (should contain at least a "position" buffer!) - * @param numParticles Number of particles in each buffer - * @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! - * @param targetRenderer The target renderer used to display the particle system as a fluid. If not provided, the method will create a new one - * @param camera The camera used by the target renderer (if the target renderer is created by the method) - * @returns the render object corresponding to the custom particle set - */ - addCustomParticles(buffers, numParticles, generateDiffuseTexture, targetRenderer, camera) { - const object = new FluidRenderingObjectCustomParticles(this._scene, buffers, numParticles); - object.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)); - if (!targetRenderer) { - targetRenderer = new FluidRenderingTargetRenderer(this._scene, camera); - this.targetRenderers.push(targetRenderer); - } - if (!targetRenderer._onUseVelocityChanged.hasObservers()) { - targetRenderer._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)); - } - if (generateDiffuseTexture !== undefined) { - targetRenderer.generateDiffuseTexture = generateDiffuseTexture; - } - const renderObject = { object, targetRenderer }; - this.renderObjects.push(renderObject); - this._sortRenderingObjects(); - this._setParticleSizeForRenderTargets(); - return renderObject; - } - /** - * Removes a render object from the fluid renderer - * @param renderObject the render object to remove - * @param removeUnusedTargetRenderer True to remove/dispose of the target renderer if it's not used anymore (default: true) - * @returns True if the render object has been found and released, else false - */ - removeRenderObject(renderObject, removeUnusedTargetRenderer = true) { - const index = this.renderObjects.indexOf(renderObject); - if (index === -1) { - return false; - } - renderObject.object.dispose(); - this.renderObjects.splice(index, 1); - if (removeUnusedTargetRenderer && this._removeUnusedTargetRenderers()) { - this._initialize(); - } - else { - this._setParticleSizeForRenderTargets(); - } - return true; - } - _sortRenderingObjects() { - this.renderObjects.sort((a, b) => { - return a.object.priority < b.object.priority ? -1 : a.object.priority > b.object.priority ? 1 : 0; - }); - } - _removeUnusedTargetRenderers() { - const indexes = {}; - for (let i = 0; i < this.renderObjects.length; ++i) { - const targetRenderer = this.renderObjects[i].targetRenderer; - indexes[this.targetRenderers.indexOf(targetRenderer)] = true; - } - let removed = false; - const newList = []; - for (let i = 0; i < this.targetRenderers.length; ++i) { - if (!indexes[i]) { - this.targetRenderers[i].dispose(); - removed = true; - } - else { - newList.push(this.targetRenderers[i]); - } - } - if (removed) { - this.targetRenderers.length = 0; - this.targetRenderers.push(...newList); - } - return removed; - } - _getParticleSystemIndex(ps) { - for (let i = 0; i < this.renderObjects.length; ++i) { - const obj = this.renderObjects[i].object; - if (IsParticleSystemObject(obj) && obj.particleSystem === ps) { - return i; - } - } - return -1; - } - _initialize() { - for (let i = 0; i < this.targetRenderers.length; ++i) { - this.targetRenderers[i].dispose(); - } - const cameras = new Map(); - for (let i = 0; i < this.targetRenderers.length; ++i) { - const targetRenderer = this.targetRenderers[i]; - targetRenderer._initialize(); - if (targetRenderer.camera && targetRenderer._renderPostProcess) { - let list = cameras.get(targetRenderer.camera); - if (!list) { - list = [[], {}]; - cameras.set(targetRenderer.camera, list); - } - list[0].push(targetRenderer); - targetRenderer.camera.attachPostProcess(targetRenderer._renderPostProcess, i); - } - } - let iterator = cameras.keys(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const camera = key.value; - const list = cameras.get(camera); - const firstPostProcess = camera._getFirstPostProcess(); - if (!firstPostProcess) { - continue; - } - const [targetRenderers, copyDepthTextures] = list; - firstPostProcess.onSizeChangedObservable.add(() => { - var _a; - if (!firstPostProcess.inputTexture.depthStencilTexture) { - firstPostProcess.inputTexture.createDepthStencilTexture(0, true, this._engine.isStencilEnable, targetRenderers[0].samples, this._engine.isStencilEnable ? 13 : 14, `PostProcessRTTDepthStencil-${firstPostProcess.name}`); - } - for (const targetRenderer of targetRenderers) { - const thicknessRT = (_a = targetRenderer._thicknessRenderTarget) === null || _a === void 0 ? void 0 : _a.renderTarget; - const thicknessTexture = thicknessRT === null || thicknessRT === void 0 ? void 0 : thicknessRT.texture; - if (thicknessRT && thicknessTexture) { - const key = thicknessTexture.width + "_" + thicknessTexture.height; - let copyDepthTexture = copyDepthTextures[key]; - if (!copyDepthTexture) { - copyDepthTexture = copyDepthTextures[key] = new FluidRenderingDepthTextureCopy(this._engine, thicknessTexture.width, thicknessTexture.height); - } - copyDepthTexture.depthRTWrapper._shareDepth(thicknessRT); - } - } - }); - } - // Dispose the CopyDepthTexture instances that we don't need anymore - iterator = this._cameras.keys(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const camera = key.value; - const list = this._cameras.get(camera); - const copyDepthTextures = list[1]; - const list2 = cameras.get(camera); - if (!list2) { - for (const key in copyDepthTextures) { - copyDepthTextures[key].dispose(); - } - } - else { - for (const key in copyDepthTextures) { - if (!list2[1][key]) { - copyDepthTextures[key].dispose(); - } - } - } - } - this._cameras.clear(); - this._cameras = cameras; - this._setParticleSizeForRenderTargets(); - } - _setParticleSizeForRenderTargets() { - const particleSizes = new Map(); - for (let i = 0; i < this.renderObjects.length; ++i) { - const renderingObject = this.renderObjects[i]; - let curSize = particleSizes.get(renderingObject.targetRenderer); - if (curSize === undefined) { - curSize = 0; - } - particleSizes.set(renderingObject.targetRenderer, Math.max(curSize, renderingObject.object.particleSize)); - } - particleSizes.forEach((particleSize, targetRenderer) => { - if (targetRenderer._depthRenderTarget) { - targetRenderer._depthRenderTarget.particleSize = particleSize; - } - }); - } - _setUseVelocityForRenderObject() { - for (const renderingObject of this.renderObjects) { - renderingObject.object.useVelocity = renderingObject.targetRenderer.useVelocity; - } - } - /** @internal */ - _prepareRendering() { - for (const renderer of this.targetRenderers) { - if (renderer.needInitialization) { - this._initialize(); - return; - } - } - } - /** @internal */ - _render(forCamera) { - var _a; - for (let i = 0; i < this.targetRenderers.length; ++i) { - if (!forCamera || this.targetRenderers[i].camera === forCamera) { - this.targetRenderers[i]._clearTargets(); - } - } - const iterator = this._cameras.keys(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const camera = key.value; - const list = this._cameras.get(camera); - if (forCamera && camera !== forCamera) { - continue; - } - const firstPostProcess = camera._getFirstPostProcess(); - if (!firstPostProcess) { - continue; - } - const sourceCopyDepth = (_a = firstPostProcess.inputTexture) === null || _a === void 0 ? void 0 : _a.depthStencilTexture; - if (sourceCopyDepth) { - const [targetRenderers, copyDepthTextures] = list; - for (const targetRenderer of targetRenderers) { - targetRenderer._bgDepthTexture = sourceCopyDepth; - } - for (const key in copyDepthTextures) { - copyDepthTextures[key].copy(sourceCopyDepth); - } - } - } - for (let i = 0; i < this.renderObjects.length; ++i) { - const renderingObject = this.renderObjects[i]; - if (!forCamera || renderingObject.targetRenderer.camera === forCamera) { - renderingObject.targetRenderer._render(renderingObject.object); - } - } - } - /** - * Disposes of all the ressources used by the class - */ - dispose() { - this._engine.onResizeObservable.remove(this._onEngineResizeObserver); - this._onEngineResizeObserver = null; - for (let i = 0; i < this.renderObjects.length; ++i) { - this.renderObjects[i].object.dispose(); - } - for (let i = 0; i < this.targetRenderers.length; ++i) { - this.targetRenderers[i].dispose(); - } - this._cameras.forEach((list) => { - const copyDepthTextures = list[1]; - for (const key in copyDepthTextures) { - copyDepthTextures[key].dispose(); - } - }); - this.renderObjects = []; - this.targetRenderers = []; - this._cameras.clear(); - } -} -//# sourceMappingURL=fluidRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/fluidRenderer/index.js - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Rendering/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Sprites/thinSprite.js -/** - * ThinSprite Class used to represent a thin sprite - * This is the base class for sprites but can also directly be used with ThinEngine - * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites - */ -class ThinSprite { - /** - * Returns a boolean indicating if the animation is started - */ - get animationStarted() { - return this._animationStarted; - } - /** Gets the initial key for the animation (setting it will restart the animation) */ - get fromIndex() { - return this._fromIndex; - } - /** Gets or sets the end key for the animation (setting it will restart the animation) */ - get toIndex() { - return this._toIndex; - } - /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation) */ - get loopAnimation() { - return this._loopAnimation; - } - /** Gets or sets the delay between cell changes (setting it will restart the animation) */ - get delay() { - return Math.max(this._delay, 1); - } - /** - * Creates a new Thin Sprite - */ - constructor() { - /** Gets or sets the width */ - this.width = 1.0; - /** Gets or sets the height */ - this.height = 1.0; - /** Gets or sets rotation angle */ - this.angle = 0; - /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */ - this.invertU = false; - /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */ - this.invertV = false; - /** Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true */ - this.isVisible = true; - this._animationStarted = false; - this._loopAnimation = false; - this._fromIndex = 0; - this._toIndex = 0; - this._delay = 0; - this._direction = 1; - this._time = 0; - this._onBaseAnimationEnd = null; - this.position = { x: 1.0, y: 1.0, z: 1.0 }; - this.color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; - } - /** - * Starts an animation - * @param from defines the initial key - * @param to defines the end key - * @param loop defines if the animation must loop - * @param delay defines the start delay (in ms) - * @param onAnimationEnd defines a callback for when the animation ends - */ - playAnimation(from, to, loop, delay, onAnimationEnd) { - this._fromIndex = from; - this._toIndex = to; - this._loopAnimation = loop; - this._delay = delay || 1; - this._animationStarted = true; - this._onBaseAnimationEnd = onAnimationEnd; - if (from < to) { - this._direction = 1; - } - else { - this._direction = -1; - this._toIndex = from; - this._fromIndex = to; - } - this.cellIndex = from; - this._time = 0; - } - /** Stops current animation (if any) */ - stopAnimation() { - this._animationStarted = false; - } - /** - * @internal - */ - _animate(deltaTime) { - if (!this._animationStarted) { - return; - } - this._time += deltaTime; - if (this._time > this._delay) { - this._time = this._time % this._delay; - this.cellIndex += this._direction; - if ((this._direction > 0 && this.cellIndex > this._toIndex) || (this._direction < 0 && this.cellIndex < this._fromIndex)) { - if (this._loopAnimation) { - this.cellIndex = this._direction > 0 ? this._fromIndex : this._toIndex; - } - else { - this.cellIndex = this._toIndex; - this._animationStarted = false; - if (this._onBaseAnimationEnd) { - this._onBaseAnimationEnd(); - } - } - } - } - } -} -//# sourceMappingURL=thinSprite.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Sprites/sprite.js - - - - -/** - * Class used to represent a sprite - * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites - */ -class Sprite extends ThinSprite { - /** - * Gets or sets the sprite size - */ - get size() { - return this.width; - } - set size(value) { - this.width = value; - this.height = value; - } - /** - * Gets the manager of this sprite - */ - get manager() { - return this._manager; - } - /** - * Creates a new Sprite - * @param name defines the name - * @param manager defines the manager - */ - constructor( - /** defines the name */ - name, manager) { - super(); - this.name = name; - /** Gets the list of attached animations */ - this.animations = new Array(); - /** Gets or sets a boolean indicating if the sprite can be picked */ - this.isPickable = false; - /** Gets or sets a boolean indicating that sprite texture alpha will be used for precise picking (false by default) */ - this.useAlphaForPicking = false; - /** - * An event triggered when the control has been disposed - */ - this.onDisposeObservable = new observable_Observable(); - this._onAnimationEnd = null; - this._endAnimation = () => { - if (this._onAnimationEnd) { - this._onAnimationEnd(); - } - if (this.disposeWhenFinishedAnimating) { - this.dispose(); - } - }; - this.color = new math_color_Color4(1.0, 1.0, 1.0, 1.0); - this.position = math_vector_Vector3.Zero(); - this._manager = manager; - this._manager.sprites.push(this); - this.uniqueId = this._manager.scene.getUniqueId(); - } - /** - * Returns the string "Sprite" - * @returns "Sprite" - */ - getClassName() { - return "Sprite"; - } - /** Gets or sets the initial key for the animation (setting it will restart the animation) */ - get fromIndex() { - return this._fromIndex; - } - set fromIndex(value) { - this.playAnimation(value, this._toIndex, this._loopAnimation, this._delay, this._onAnimationEnd); - } - /** Gets or sets the end key for the animation (setting it will restart the animation) */ - get toIndex() { - return this._toIndex; - } - set toIndex(value) { - this.playAnimation(this._fromIndex, value, this._loopAnimation, this._delay, this._onAnimationEnd); - } - /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation) */ - get loopAnimation() { - return this._loopAnimation; - } - set loopAnimation(value) { - this.playAnimation(this._fromIndex, this._toIndex, value, this._delay, this._onAnimationEnd); - } - /** Gets or sets the delay between cell changes (setting it will restart the animation) */ - get delay() { - return Math.max(this._delay, 1); - } - set delay(value) { - this.playAnimation(this._fromIndex, this._toIndex, this._loopAnimation, value, this._onAnimationEnd); - } - /** - * Starts an animation - * @param from defines the initial key - * @param to defines the end key - * @param loop defines if the animation must loop - * @param delay defines the start delay (in ms) - * @param onAnimationEnd defines a callback to call when animation ends - */ - playAnimation(from, to, loop, delay, onAnimationEnd = null) { - this._onAnimationEnd = onAnimationEnd; - super.playAnimation(from, to, loop, delay, this._endAnimation); - } - /** Release associated resources */ - dispose() { - for (let i = 0; i < this._manager.sprites.length; i++) { - if (this._manager.sprites[i] == this) { - this._manager.sprites.splice(i, 1); - } - } - // Callback - this.onDisposeObservable.notifyObservers(this); - this.onDisposeObservable.clear(); - } - /** - * Serializes the sprite to a JSON object - * @returns the JSON object - */ - serialize() { - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.position = this.position.asArray(); - serializationObject.color = this.color.asArray(); - serializationObject.width = this.width; - serializationObject.height = this.height; - serializationObject.angle = this.angle; - serializationObject.cellIndex = this.cellIndex; - serializationObject.cellRef = this.cellRef; - serializationObject.invertU = this.invertU; - serializationObject.invertV = this.invertV; - serializationObject.disposeWhenFinishedAnimating = this.disposeWhenFinishedAnimating; - serializationObject.isPickable = this.isPickable; - serializationObject.isVisible = this.isVisible; - serializationObject.useAlphaForPicking = this.useAlphaForPicking; - serializationObject.animationStarted = this.animationStarted; - serializationObject.fromIndex = this.fromIndex; - serializationObject.toIndex = this.toIndex; - serializationObject.loopAnimation = this.loopAnimation; - serializationObject.delay = this.delay; - return serializationObject; - } - /** - * Parses a JSON object to create a new sprite - * @param parsedSprite The JSON object to parse - * @param manager defines the hosting manager - * @returns the new sprite - */ - static Parse(parsedSprite, manager) { - const sprite = new Sprite(parsedSprite.name, manager); - sprite.position = math_vector_Vector3.FromArray(parsedSprite.position); - sprite.color = math_color_Color4.FromArray(parsedSprite.color); - sprite.width = parsedSprite.width; - sprite.height = parsedSprite.height; - sprite.angle = parsedSprite.angle; - sprite.cellIndex = parsedSprite.cellIndex; - sprite.cellRef = parsedSprite.cellRef; - sprite.invertU = parsedSprite.invertU; - sprite.invertV = parsedSprite.invertV; - sprite.disposeWhenFinishedAnimating = parsedSprite.disposeWhenFinishedAnimating; - sprite.isPickable = parsedSprite.isPickable; - sprite.isVisible = parsedSprite.isVisible; - sprite.useAlphaForPicking = parsedSprite.useAlphaForPicking; - sprite._fromIndex = parsedSprite.fromIndex; - sprite._toIndex = parsedSprite.toIndex; - sprite._loopAnimation = parsedSprite.loopAnimation; - sprite._delay = parsedSprite.delay; - if (parsedSprite.animationStarted) { - sprite.playAnimation(sprite.fromIndex, sprite.toIndex, sprite.loopAnimation, sprite.delay); - } - return sprite; - } -} -//# sourceMappingURL=sprite.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Sprites/ISprites.js - -//# sourceMappingURL=ISprites.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Sprites/spriteSceneComponent.js - - - - - - - -scene_Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) { - if (!PickingInfo) { - return null; - } - let pickingInfo = null; - if (!camera) { - if (!this.activeCamera) { - return null; - } - camera = this.activeCamera; - } - if (this.spriteManagers && this.spriteManagers.length > 0) { - for (let spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) { - const spriteManager = this.spriteManagers[spriteIndex]; - if (!spriteManager.isPickable) { - continue; - } - const result = spriteManager.intersects(ray, camera, predicate, fastCheck); - if (!result || !result.hit) { - continue; - } - if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) { - continue; - } - pickingInfo = result; - if (fastCheck) { - break; - } - } - } - return pickingInfo || new PickingInfo(); -}; -scene_Scene.prototype._internalMultiPickSprites = function (ray, predicate, camera) { - if (!PickingInfo) { - return null; - } - let pickingInfos = new Array(); - if (!camera) { - if (!this.activeCamera) { - return null; - } - camera = this.activeCamera; - } - if (this.spriteManagers && this.spriteManagers.length > 0) { - for (let spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) { - const spriteManager = this.spriteManagers[spriteIndex]; - if (!spriteManager.isPickable) { - continue; - } - const results = spriteManager.multiIntersects(ray, camera, predicate); - if (results !== null) { - pickingInfos = pickingInfos.concat(results); - } - } - } - return pickingInfos; -}; -scene_Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) { - if (!this._tempSpritePickingRay) { - return null; - } - this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera); - const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera); - if (result) { - result.ray = this.createPickingRayInCameraSpace(x, y, camera); - } - return result; -}; -scene_Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) { - if (!this._tempSpritePickingRay) { - return null; - } - if (!camera) { - if (!this.activeCamera) { - return null; - } - camera = this.activeCamera; - } - ray_Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay); - const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera); - if (result) { - result.ray = ray; - } - return result; -}; -scene_Scene.prototype.multiPickSprite = function (x, y, predicate, camera) { - this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera); - return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera); -}; -scene_Scene.prototype.multiPickSpriteWithRay = function (ray, predicate, camera) { - if (!this._tempSpritePickingRay) { - return null; - } - if (!camera) { - if (!this.activeCamera) { - return null; - } - camera = this.activeCamera; - } - ray_Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay); - return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera); -}; -scene_Scene.prototype.setPointerOverSprite = function (sprite) { - if (this._pointerOverSprite === sprite) { - return; - } - if (this._pointerOverSprite && this._pointerOverSprite.actionManager) { - this._pointerOverSprite.actionManager.processTrigger(10, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)); - } - this._pointerOverSprite = sprite; - if (this._pointerOverSprite && this._pointerOverSprite.actionManager) { - this._pointerOverSprite.actionManager.processTrigger(9, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)); - } -}; -scene_Scene.prototype.getPointerOverSprite = function () { - return this._pointerOverSprite; -}; -/** - * Defines the sprite scene component responsible to manage sprites - * in a given scene. - */ -class SpriteSceneComponent { - /** - * Creates a new instance of the component for the given scene - * @param scene Defines the scene to register the component in - */ - constructor(scene) { - /** - * The component name helpfull to identify the component in the list of scene components. - */ - this.name = sceneComponent_SceneComponentConstants.NAME_SPRITE; - this.scene = scene; - this.scene.spriteManagers = new Array(); - this.scene._tempSpritePickingRay = ray_Ray ? ray_Ray.Zero() : null; - this.scene.onBeforeSpritesRenderingObservable = new observable_Observable(); - this.scene.onAfterSpritesRenderingObservable = new observable_Observable(); - this._spritePredicate = (sprite) => { - if (!sprite.actionManager) { - return false; - } - return sprite.isPickable && sprite.actionManager.hasPointerTriggers; - }; - } - /** - * Registers the component in a given scene - */ - register() { - this.scene._pointerMoveStage.registerStep(sceneComponent_SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove); - this.scene._pointerDownStage.registerStep(sceneComponent_SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown); - this.scene._pointerUpStage.registerStep(sceneComponent_SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp); - } - /** - * Rebuilds the elements related to this component in case of - * context lost for instance. - */ - rebuild() { - /** Nothing to do for sprites */ - } - /** - * Disposes the component and the associated resources. - */ - dispose() { - this.scene.onBeforeSpritesRenderingObservable.clear(); - this.scene.onAfterSpritesRenderingObservable.clear(); - const spriteManagers = this.scene.spriteManagers; - if (!spriteManagers) { - return; - } - while (spriteManagers.length) { - spriteManagers[0].dispose(); - } - } - _pickSpriteButKeepRay(originalPointerInfo, x, y, fastCheck, camera) { - const result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera); - if (result) { - result.ray = originalPointerInfo ? originalPointerInfo.ray : null; - } - return result; - } - _pointerMove(unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, element) { - const scene = this.scene; - if (isMeshPicked) { - scene.setPointerOverSprite(null); - } - else { - pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined); - if (pickResult && pickResult.hit && pickResult.pickedSprite) { - scene.setPointerOverSprite(pickResult.pickedSprite); - if (!scene.doNotHandleCursors && element) { - if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) { - element.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor; - } - else { - element.style.cursor = scene.hoverCursor; - } - } - } - else { - scene.setPointerOverSprite(null); - } - } - return pickResult; - } - _pointerDown(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) { - const scene = this.scene; - scene._pickedDownSprite = null; - if (scene.spriteManagers && scene.spriteManagers.length > 0) { - pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined); - if (pickResult && pickResult.hit && pickResult.pickedSprite) { - if (pickResult.pickedSprite.actionManager) { - scene._pickedDownSprite = pickResult.pickedSprite; - switch (evt.button) { - case 0: - pickResult.pickedSprite.actionManager.processTrigger(2, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); - break; - case 1: - pickResult.pickedSprite.actionManager.processTrigger(4, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); - break; - case 2: - pickResult.pickedSprite.actionManager.processTrigger(3, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); - break; - } - if (pickResult.pickedSprite.actionManager) { - pickResult.pickedSprite.actionManager.processTrigger(5, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); - } - } - } - } - return pickResult; - } - _pointerUp(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt, doubleClick) { - const scene = this.scene; - if (scene.spriteManagers && scene.spriteManagers.length > 0) { - const spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined); - if (spritePickResult) { - if (spritePickResult.hit && spritePickResult.pickedSprite) { - if (spritePickResult.pickedSprite.actionManager) { - spritePickResult.pickedSprite.actionManager.processTrigger(7, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt)); - if (spritePickResult.pickedSprite.actionManager) { - if (!this.scene._inputManager._isPointerSwiping()) { - spritePickResult.pickedSprite.actionManager.processTrigger(1, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt)); - } - if (doubleClick) { - spritePickResult.pickedSprite.actionManager.processTrigger(6, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt)); - } - } - } - } - if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) { - scene._pickedDownSprite.actionManager.processTrigger(16, ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt)); - } - } - } - return pickResult; - } -} -//# sourceMappingURL=spriteSceneComponent.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingCompatibility.js -// Do not edit. - -const imageProcessingCompatibility_name = "imageProcessingCompatibility"; -const imageProcessingCompatibility_shader = `#ifdef IMAGEPROCESSINGPOSTPROCESS -gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); -#endif -`; -// Sideeffect -ShaderStore.IncludesShadersStore[imageProcessingCompatibility_name] = imageProcessingCompatibility_shader; -/** @internal */ -const imageProcessingCompatibility = { name: imageProcessingCompatibility_name, shader: imageProcessingCompatibility_shader }; -//# sourceMappingURL=imageProcessingCompatibility.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/sprites.fragment.js -// Do not edit. - - - - -const sprites_fragment_name = "spritesPixelShader"; -const sprites_fragment_shader = `uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; -#include<fogFragmentDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -#ifdef PIXEL_PERFECT -vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} -#endif -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#ifdef PIXEL_PERFECT -vec2 uv=uvPixelPerfect(vUV); -#else -vec2 uv=vUV; -#endif -vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) -{if (color.a<0.95) -discard;} -color*=vColor; -#include<fogFragment> -gl_FragColor=color; -#include<imageProcessingCompatibility> -#define CUSTOM_FRAGMENT_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[sprites_fragment_name] = sprites_fragment_shader; -/** @internal */ -const spritesPixelShader = { name: sprites_fragment_name, shader: sprites_fragment_shader }; -//# sourceMappingURL=sprites.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/sprites.vertex.js -// Do not edit. - - -const sprites_vertex_name = "spritesVertexShader"; -const sprites_vertex_shader = `attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; -#include<fogVertexDeclaration> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; -vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); -vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; -#ifdef FOG -vFogDistance=viewPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[sprites_vertex_name] = sprites_vertex_shader; -/** @internal */ -const spritesVertexShader = { name: sprites_vertex_name, shader: sprites_vertex_shader }; -//# sourceMappingURL=sprites.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Sprites/spriteRenderer.js - - - - - - - -/** - * Class used to render sprites. - * - * It can be used either to render Sprites or ThinSprites with ThinEngine only. - */ -class SpriteRenderer { - /** - * Gets the capacity of the manager - */ - get capacity() { - return this._capacity; - } - /** - * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering - * Note that pixel perfect mode is not supported in WebGL 1 - */ - get pixelPerfect() { - return this._pixelPerfect; - } - set pixelPerfect(value) { - if (this._pixelPerfect === value) { - return; - } - this._pixelPerfect = value; - this._createEffects(); - } - /** - * Creates a new sprite Renderer - * @param engine defines the engine the renderer works with - * @param capacity defines the maximum allowed number of sprites - * @param epsilon defines the epsilon value to align texture (0.01 by default) - * @param scene defines the hosting scene - */ - constructor(engine, capacity, epsilon = 0.01, scene = null) { - /** - * Blend mode use to render the particle, it can be any of - * the static undefined properties provided in this class. - * Default value is 2 - */ - this.blendMode = 2; - /** - * Gets or sets a boolean indicating if alpha mode is automatically - * reset. - */ - this.autoResetAlpha = true; - /** - * Disables writing to the depth buffer when rendering the sprites. - * It can be handy to disable depth writing when using textures without alpha channel - * and setting some specific blend modes. - */ - this.disableDepthWrite = false; - /** - * Gets or sets a boolean indicating if the manager must consider scene fog when rendering - */ - this.fogEnabled = true; - this._pixelPerfect = false; - this._useVAO = false; - this._useInstancing = false; - this._vertexBuffers = {}; - this._capacity = capacity; - this._epsilon = epsilon; - this._engine = engine; - this._useInstancing = engine.getCaps().instancedArrays && engine._features.supportSpriteInstancing; - this._useVAO = engine.getCaps().vertexArrayObject && !engine.disableVertexArrayObjects; - this._scene = scene; - if (!this._useInstancing) { - this._buildIndexBuffer(); - } - // VBO - // 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) - // 16 when using instances - this._vertexBufferSize = this._useInstancing ? 16 : 18; - this._vertexData = new Float32Array(capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4)); - this._buffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize); - const positions = this._buffer.createVertexBuffer(buffer_VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing); - const options = this._buffer.createVertexBuffer("options", 4, 2, this._vertexBufferSize, this._useInstancing); - let offset = 6; - let offsets; - if (this._useInstancing) { - const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]); - this._spriteBuffer = new Buffer(engine, spriteData, false, 2); - offsets = this._spriteBuffer.createVertexBuffer("offsets", 0, 2); - } - else { - offsets = this._buffer.createVertexBuffer("offsets", offset, 2, this._vertexBufferSize, this._useInstancing); - offset += 2; - } - const inverts = this._buffer.createVertexBuffer("inverts", offset, 2, this._vertexBufferSize, this._useInstancing); - const cellInfo = this._buffer.createVertexBuffer("cellInfo", offset + 2, 4, this._vertexBufferSize, this._useInstancing); - const colors = this._buffer.createVertexBuffer(buffer_VertexBuffer.ColorKind, offset + 6, 4, this._vertexBufferSize, this._useInstancing); - this._vertexBuffers[buffer_VertexBuffer.PositionKind] = positions; - this._vertexBuffers["options"] = options; - this._vertexBuffers["offsets"] = offsets; - this._vertexBuffers["inverts"] = inverts; - this._vertexBuffers["cellInfo"] = cellInfo; - this._vertexBuffers[buffer_VertexBuffer.ColorKind] = colors; - this._createEffects(); - } - _createEffects() { - var _a, _b, _c, _d; - (_a = this._drawWrapperBase) === null || _a === void 0 ? void 0 : _a.dispose(); - (_b = this._drawWrapperFog) === null || _b === void 0 ? void 0 : _b.dispose(); - (_c = this._drawWrapperDepth) === null || _c === void 0 ? void 0 : _c.dispose(); - (_d = this._drawWrapperFogDepth) === null || _d === void 0 ? void 0 : _d.dispose(); - this._drawWrapperBase = new drawWrapper_DrawWrapper(this._engine); - this._drawWrapperFog = new drawWrapper_DrawWrapper(this._engine); - this._drawWrapperDepth = new drawWrapper_DrawWrapper(this._engine, false); - this._drawWrapperFogDepth = new drawWrapper_DrawWrapper(this._engine, false); - if (this._drawWrapperBase.drawContext) { - this._drawWrapperBase.drawContext.useInstancing = this._useInstancing; - } - if (this._drawWrapperFog.drawContext) { - this._drawWrapperFog.drawContext.useInstancing = this._useInstancing; - } - if (this._drawWrapperDepth.drawContext) { - this._drawWrapperDepth.drawContext.useInstancing = this._useInstancing; - } - if (this._drawWrapperFogDepth.drawContext) { - this._drawWrapperFogDepth.drawContext.useInstancing = this._useInstancing; - } - const defines = this._pixelPerfect ? "#define PIXEL_PERFECT\n" : ""; - this._drawWrapperBase.effect = this._engine.createEffect("sprites", [buffer_VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", buffer_VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], defines); - this._drawWrapperDepth.effect = this._drawWrapperBase.effect; - this._drawWrapperDepth.materialContext = this._drawWrapperBase.materialContext; - if (this._scene) { - this._drawWrapperFog.effect = this._scene - .getEngine() - .createEffect("sprites", [buffer_VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", buffer_VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], defines + "#define FOG"); - this._drawWrapperFogDepth.effect = this._drawWrapperFog.effect; - this._drawWrapperFogDepth.materialContext = this._drawWrapperFog.materialContext; - } - } - /** - * Render all child sprites - * @param sprites defines the list of sprites to render - * @param deltaTime defines the time since last frame - * @param viewMatrix defines the viewMatrix to use to render the sprites - * @param projectionMatrix defines the projectionMatrix to use to render the sprites - * @param customSpriteUpdate defines a custom function to update the sprites data before they render - */ - render(sprites, deltaTime, viewMatrix, projectionMatrix, customSpriteUpdate = null) { - if (!this.texture || !this.texture.isReady() || !sprites.length) { - return; - } - let drawWrapper = this._drawWrapperBase; - let drawWrapperDepth = this._drawWrapperDepth; - let shouldRenderFog = false; - if (this.fogEnabled && this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0) { - drawWrapper = this._drawWrapperFog; - drawWrapperDepth = this._drawWrapperFogDepth; - shouldRenderFog = true; - } - const effect = drawWrapper.effect; - // Check - if (!effect.isReady()) { - return; - } - const engine = this._engine; - const useRightHandedSystem = !!(this._scene && this._scene.useRightHandedSystem); - const baseSize = this.texture.getBaseSize(); - // Sprites - const max = Math.min(this._capacity, sprites.length); - let offset = 0; - let noSprite = true; - for (let index = 0; index < max; index++) { - const sprite = sprites[index]; - if (!sprite || !sprite.isVisible) { - continue; - } - noSprite = false; - sprite._animate(deltaTime); - this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize, useRightHandedSystem, customSpriteUpdate); - if (!this._useInstancing) { - this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize, useRightHandedSystem, customSpriteUpdate); - this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize, useRightHandedSystem, customSpriteUpdate); - this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize, useRightHandedSystem, customSpriteUpdate); - } - } - if (noSprite) { - return; - } - this._buffer.update(this._vertexData); - const culling = !!engine.depthCullingState.cull; - const zOffset = engine.depthCullingState.zOffset; - const zOffsetUnits = engine.depthCullingState.zOffsetUnits; - engine.setState(culling, zOffset, false, false, undefined, undefined, zOffsetUnits); - // Render - engine.enableEffect(drawWrapper); - effect.setTexture("diffuseSampler", this.texture); - effect.setMatrix("view", viewMatrix); - effect.setMatrix("projection", projectionMatrix); - // Scene Info - if (shouldRenderFog) { - const scene = this._scene; - // Fog - effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); - effect.setColor3("vFogColor", scene.fogColor); - } - if (this._useVAO) { - if (!this._vertexArrayObject) { - this._vertexArrayObject = engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect); - } - engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer); - } - else { - // VBOs - engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); - } - // Draw order - engine.depthCullingState.depthFunc = engine.useReverseDepthBuffer ? 518 : 515; - if (!this.disableDepthWrite) { - effect.setBool("alphaTest", true); - engine.setColorWrite(false); - engine.enableEffect(drawWrapperDepth); - if (this._useInstancing) { - engine.drawArraysType(7, 0, 4, offset); - } - else { - engine.drawElementsType(0, 0, (offset / 4) * 6); - } - engine.enableEffect(drawWrapper); - engine.setColorWrite(true); - effect.setBool("alphaTest", false); - } - engine.setAlphaMode(this.blendMode); - if (this._useInstancing) { - engine.drawArraysType(7, 0, 4, offset); - } - else { - engine.drawElementsType(0, 0, (offset / 4) * 6); - } - if (this.autoResetAlpha) { - engine.setAlphaMode(0); - } - // Restore Right Handed - if (useRightHandedSystem) { - this._scene.getEngine().setState(culling, zOffset, false, true, undefined, undefined, zOffsetUnits); - } - engine.unbindInstanceAttributes(); - } - _appendSpriteVertex(index, sprite, offsetX, offsetY, baseSize, useRightHandedSystem, customSpriteUpdate) { - let arrayOffset = index * this._vertexBufferSize; - if (offsetX === 0) { - offsetX = this._epsilon; - } - else if (offsetX === 1) { - offsetX = 1 - this._epsilon; - } - if (offsetY === 0) { - offsetY = this._epsilon; - } - else if (offsetY === 1) { - offsetY = 1 - this._epsilon; - } - if (customSpriteUpdate) { - customSpriteUpdate(sprite, baseSize); - } - else { - if (!sprite.cellIndex) { - sprite.cellIndex = 0; - } - const rowSize = baseSize.width / this.cellWidth; - const offset = (sprite.cellIndex / rowSize) >> 0; - sprite._xOffset = ((sprite.cellIndex - offset * rowSize) * this.cellWidth) / baseSize.width; - sprite._yOffset = (offset * this.cellHeight) / baseSize.height; - sprite._xSize = this.cellWidth; - sprite._ySize = this.cellHeight; - } - // Positions - this._vertexData[arrayOffset] = sprite.position.x; - this._vertexData[arrayOffset + 1] = sprite.position.y; - this._vertexData[arrayOffset + 2] = sprite.position.z; - this._vertexData[arrayOffset + 3] = sprite.angle; - // Options - this._vertexData[arrayOffset + 4] = sprite.width; - this._vertexData[arrayOffset + 5] = sprite.height; - if (!this._useInstancing) { - this._vertexData[arrayOffset + 6] = offsetX; - this._vertexData[arrayOffset + 7] = offsetY; - } - else { - arrayOffset -= 2; - } - // Inverts according to Right Handed - if (useRightHandedSystem) { - this._vertexData[arrayOffset + 8] = sprite.invertU ? 0 : 1; - } - else { - this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0; - } - this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0; - this._vertexData[arrayOffset + 10] = sprite._xOffset; - this._vertexData[arrayOffset + 11] = sprite._yOffset; - this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width; - this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height; - // Color - this._vertexData[arrayOffset + 14] = sprite.color.r; - this._vertexData[arrayOffset + 15] = sprite.color.g; - this._vertexData[arrayOffset + 16] = sprite.color.b; - this._vertexData[arrayOffset + 17] = sprite.color.a; - } - _buildIndexBuffer() { - const indices = []; - let index = 0; - for (let count = 0; count < this._capacity; count++) { - indices.push(index); - indices.push(index + 1); - indices.push(index + 2); - indices.push(index); - indices.push(index + 2); - indices.push(index + 3); - index += 4; - } - this._indexBuffer = this._engine.createIndexBuffer(indices); - } - /** - * Rebuilds the renderer (after a context lost, for eg) - */ - rebuild() { - var _a; - if (this._indexBuffer) { - this._buildIndexBuffer(); - } - if (this._useVAO) { - this._vertexArrayObject = undefined; - } - this._buffer._rebuild(); - for (const key in this._vertexBuffers) { - const vertexBuffer = this._vertexBuffers[key]; - vertexBuffer._rebuild(); - } - (_a = this._spriteBuffer) === null || _a === void 0 ? void 0 : _a._rebuild(); - } - /** - * Release associated resources - */ - dispose() { - if (this._buffer) { - this._buffer.dispose(); - this._buffer = null; - } - if (this._spriteBuffer) { - this._spriteBuffer.dispose(); - this._spriteBuffer = null; - } - if (this._indexBuffer) { - this._engine._releaseBuffer(this._indexBuffer); - this._indexBuffer = null; - } - if (this._vertexArrayObject) { - this._engine.releaseVertexArrayObject(this._vertexArrayObject); - this._vertexArrayObject = null; - } - if (this.texture) { - this.texture.dispose(); - this.texture = null; - } - this._drawWrapperBase.dispose(); - this._drawWrapperFog.dispose(); - this._drawWrapperDepth.dispose(); - this._drawWrapperFogDepth.dispose(); - } -} -//# sourceMappingURL=spriteRenderer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Sprites/spriteManager.js - - - - - - - - - - - - - -/** - * Class used to manage multiple sprites on the same spritesheet - * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites - */ -class spriteManager_SpriteManager { - /** - * Callback called when the manager is disposed - */ - set onDispose(callback) { - if (this._onDisposeObserver) { - this.onDisposeObservable.remove(this._onDisposeObserver); - } - this._onDisposeObserver = this.onDisposeObservable.add(callback); - } - /** - * Gets the array of sprites - */ - get children() { - return this.sprites; - } - /** - * Gets the hosting scene - */ - get scene() { - return this._scene; - } - /** - * Gets the capacity of the manager - */ - get capacity() { - return this._spriteRenderer.capacity; - } - /** - * Gets or sets the spritesheet texture - */ - get texture() { - return this._spriteRenderer.texture; - } - set texture(value) { - value.wrapU = texture_Texture.CLAMP_ADDRESSMODE; - value.wrapV = texture_Texture.CLAMP_ADDRESSMODE; - this._spriteRenderer.texture = value; - this._textureContent = null; - } - /** Defines the default width of a cell in the spritesheet */ - get cellWidth() { - return this._spriteRenderer.cellWidth; - } - set cellWidth(value) { - this._spriteRenderer.cellWidth = value; - } - /** Defines the default height of a cell in the spritesheet */ - get cellHeight() { - return this._spriteRenderer.cellHeight; - } - set cellHeight(value) { - this._spriteRenderer.cellHeight = value; - } - /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */ - get fogEnabled() { - return this._spriteRenderer.fogEnabled; - } - set fogEnabled(value) { - this._spriteRenderer.fogEnabled = value; - } - /** - * Blend mode use to render the particle, it can be any of - * the static undefined properties provided in this class. - * Default value is 2 - */ - get blendMode() { - return this._spriteRenderer.blendMode; - } - set blendMode(blendMode) { - this._spriteRenderer.blendMode = blendMode; - } - /** Disables writing to the depth buffer when rendering the sprites. - * It can be handy to disable depth writing when using textures without alpha channel - * and setting some specific blend modes. - */ - get disableDepthWrite() { - return this._disableDepthWrite; - } - set disableDepthWrite(value) { - this._disableDepthWrite = value; - this._spriteRenderer.disableDepthWrite = value; - } - /** - * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering - * 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. - * Note that for this mode to work as expected, the sprite texture must use the BILINEAR sampling mode, not NEAREST! - */ - get pixelPerfect() { - return this._spriteRenderer.pixelPerfect; - } - set pixelPerfect(value) { - this._spriteRenderer.pixelPerfect = value; - if (value && this.texture.samplingMode !== 3) { - this.texture.updateSamplingMode(3); - } - } - /** - * Creates a new sprite manager - * @param name defines the manager's name - * @param imgUrl defines the sprite sheet url - * @param capacity defines the maximum allowed number of sprites - * @param cellSize defines the size of a sprite cell - * @param scene defines the hosting scene - * @param epsilon defines the epsilon value to align texture (0.01 by default) - * @param samplingMode defines the sampling mode to use with spritesheet - * @param fromPacked set to false; do not alter - * @param spriteJSON null otherwise a JSON object defining sprite sheet data; do not alter - */ - constructor( - /** defines the manager's name */ - name, imgUrl, capacity, cellSize, scene, epsilon = 0.01, samplingMode = texture_Texture.TRILINEAR_SAMPLINGMODE, fromPacked = false, spriteJSON = null) { - this.name = name; - /** Gets the list of sprites */ - this.sprites = new Array(); - /** Gets or sets the rendering group id (0 by default) */ - this.renderingGroupId = 0; - /** Gets or sets camera layer mask */ - this.layerMask = 0x0fffffff; - /** Gets or sets a boolean indicating if the sprites are pickable */ - this.isPickable = false; - /** - * Gets or sets an object used to store user defined information for the sprite manager - */ - this.metadata = null; - /** @internal */ - this._wasDispatched = false; - /** - * An event triggered when the manager is disposed. - */ - this.onDisposeObservable = new observable_Observable(); - this._disableDepthWrite = false; - /** True when packed cell data from JSON file is ready*/ - this._packedAndReady = false; - this._customUpdate = (sprite, baseSize) => { - if (!sprite.cellRef) { - sprite.cellIndex = 0; - } - const num = sprite.cellIndex; - if (typeof num === "number" && isFinite(num) && Math.floor(num) === num) { - sprite.cellRef = this._spriteMap[sprite.cellIndex]; - } - sprite._xOffset = this._cellData[sprite.cellRef].frame.x / baseSize.width; - sprite._yOffset = this._cellData[sprite.cellRef].frame.y / baseSize.height; - sprite._xSize = this._cellData[sprite.cellRef].frame.w; - sprite._ySize = this._cellData[sprite.cellRef].frame.h; - }; - if (!scene) { - scene = engineStore_EngineStore.LastCreatedScene; - } - if (!scene._getComponent(sceneComponent_SceneComponentConstants.NAME_SPRITE)) { - scene._addComponent(new SpriteSceneComponent(scene)); - } - this._fromPacked = fromPacked; - this._scene = scene; - const engine = this._scene.getEngine(); - this._spriteRenderer = new SpriteRenderer(engine, capacity, epsilon, scene); - if (cellSize.width && cellSize.height) { - this.cellWidth = cellSize.width; - this.cellHeight = cellSize.height; - } - else if (cellSize !== undefined) { - this.cellWidth = cellSize; - this.cellHeight = cellSize; - } - else { - this._spriteRenderer = null; - return; - } - this._scene.spriteManagers && this._scene.spriteManagers.push(this); - this.uniqueId = this.scene.getUniqueId(); - if (imgUrl) { - this.texture = new texture_Texture(imgUrl, scene, true, false, samplingMode); - } - if (this._fromPacked) { - this._makePacked(imgUrl, spriteJSON); - } - } - /** - * Returns the string "SpriteManager" - * @returns "SpriteManager" - */ - getClassName() { - return "SpriteManager"; - } - _makePacked(imgUrl, spriteJSON) { - if (spriteJSON !== null) { - try { - //Get the JSON and Check its structure. If its an array parse it if its a JSON string etc... - let celldata; - if (typeof spriteJSON === "string") { - celldata = JSON.parse(spriteJSON); - } - else { - celldata = spriteJSON; - } - if (celldata.frames.length) { - const frametemp = {}; - for (let i = 0; i < celldata.frames.length; i++) { - const _f = celldata.frames[i]; - if (typeof Object.keys(_f)[0] !== "string") { - throw new Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter."); - } - const name = _f[Object.keys(_f)[0]]; - frametemp[name] = _f; - } - celldata.frames = frametemp; - } - const spritemap = Reflect.ownKeys(celldata.frames); - this._spriteMap = spritemap; - this._packedAndReady = true; - this._cellData = celldata.frames; - } - catch (e) { - this._fromPacked = false; - this._packedAndReady = false; - throw new Error("Invalid JSON from string. Spritesheet managed with constant cell size."); - } - } - else { - const re = /\./g; - let li; - do { - li = re.lastIndex; - re.test(imgUrl); - } while (re.lastIndex > 0); - const jsonUrl = imgUrl.substring(0, li - 1) + ".json"; - const onerror = () => { - logger_Logger.Error("JSON ERROR: Unable to load JSON file."); - this._fromPacked = false; - this._packedAndReady = false; - }; - const onload = (data) => { - try { - const celldata = JSON.parse(data); - const spritemap = Reflect.ownKeys(celldata.frames); - this._spriteMap = spritemap; - this._packedAndReady = true; - this._cellData = celldata.frames; - } - catch (e) { - this._fromPacked = false; - this._packedAndReady = false; - throw new Error("Invalid JSON format. Please check documentation for format specifications."); - } - }; - tools_Tools.LoadFile(jsonUrl, onload, undefined, undefined, false, onerror); - } - } - _checkTextureAlpha(sprite, ray, distance, min, max) { - if (!sprite.useAlphaForPicking || !this.texture) { - return true; - } - const textureSize = this.texture.getSize(); - if (!this._textureContent) { - this._textureContent = new Uint8Array(textureSize.width * textureSize.height * 4); - this.texture.readPixels(0, 0, this._textureContent); - } - const contactPoint = math_vector_TmpVectors.Vector3[0]; - contactPoint.copyFrom(ray.direction); - contactPoint.normalize(); - contactPoint.scaleInPlace(distance); - contactPoint.addInPlace(ray.origin); - const contactPointU = (contactPoint.x - min.x) / (max.x - min.x); - const contactPointV = 1.0 - (contactPoint.y - min.y) / (max.y - min.y); - const u = (sprite._xOffset * textureSize.width + contactPointU * sprite._xSize) | 0; - const v = (sprite._yOffset * textureSize.height + contactPointV * sprite._ySize) | 0; - const alpha = this._textureContent[(u + v * textureSize.width) * 4 + 3]; - return alpha > 0.5; - } - /** - * Intersects the sprites with a ray - * @param ray defines the ray to intersect with - * @param camera defines the current active camera - * @param predicate defines a predicate used to select candidate sprites - * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer) - * @returns null if no hit or a PickingInfo - */ - intersects(ray, camera, predicate, fastCheck) { - const count = Math.min(this.capacity, this.sprites.length); - const min = math_vector_Vector3.Zero(); - const max = math_vector_Vector3.Zero(); - let distance = Number.MAX_VALUE; - let currentSprite = null; - const pickedPoint = math_vector_TmpVectors.Vector3[0]; - const cameraSpacePosition = math_vector_TmpVectors.Vector3[1]; - const cameraView = camera.getViewMatrix(); - let activeRay = ray; - let pickedRay = ray; - for (let index = 0; index < count; index++) { - const sprite = this.sprites[index]; - if (!sprite) { - continue; - } - if (predicate) { - if (!predicate(sprite)) { - continue; - } - } - else if (!sprite.isPickable) { - continue; - } - math_vector_Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition); - if (sprite.angle) { - // Create a rotation matrix to rotate the ray to the sprite's rotation - math_vector_Matrix.TranslationToRef(-cameraSpacePosition.x, -cameraSpacePosition.y, 0, math_vector_TmpVectors.Matrix[1]); - math_vector_Matrix.TranslationToRef(cameraSpacePosition.x, cameraSpacePosition.y, 0, math_vector_TmpVectors.Matrix[2]); - math_vector_Matrix.RotationZToRef(-sprite.angle, math_vector_TmpVectors.Matrix[3]); - // inv translation x rotation x translation - math_vector_TmpVectors.Matrix[1].multiplyToRef(math_vector_TmpVectors.Matrix[3], math_vector_TmpVectors.Matrix[4]); - math_vector_TmpVectors.Matrix[4].multiplyToRef(math_vector_TmpVectors.Matrix[2], math_vector_TmpVectors.Matrix[0]); - activeRay = ray.clone(); - math_vector_Vector3.TransformCoordinatesToRef(ray.origin, math_vector_TmpVectors.Matrix[0], activeRay.origin); - math_vector_Vector3.TransformNormalToRef(ray.direction, math_vector_TmpVectors.Matrix[0], activeRay.direction); - } - else { - activeRay = ray; - } - min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z); - max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z); - if (activeRay.intersectsBoxMinMax(min, max)) { - const currentDistance = math_vector_Vector3.Distance(cameraSpacePosition, activeRay.origin); - if (distance > currentDistance) { - if (!this._checkTextureAlpha(sprite, activeRay, currentDistance, min, max)) { - continue; - } - pickedRay = activeRay; - distance = currentDistance; - currentSprite = sprite; - if (fastCheck) { - break; - } - } - } - } - if (currentSprite) { - const result = new PickingInfo(); - cameraView.invertToRef(math_vector_TmpVectors.Matrix[0]); - result.hit = true; - result.pickedSprite = currentSprite; - result.distance = distance; - // Get picked point - const direction = math_vector_TmpVectors.Vector3[2]; - direction.copyFrom(pickedRay.direction); - direction.normalize(); - direction.scaleInPlace(distance); - pickedRay.origin.addToRef(direction, pickedPoint); - result.pickedPoint = math_vector_Vector3.TransformCoordinates(pickedPoint, math_vector_TmpVectors.Matrix[0]); - return result; - } - return null; - } - /** - * Intersects the sprites with a ray - * @param ray defines the ray to intersect with - * @param camera defines the current active camera - * @param predicate defines a predicate used to select candidate sprites - * @returns null if no hit or a PickingInfo array - */ - multiIntersects(ray, camera, predicate) { - const count = Math.min(this.capacity, this.sprites.length); - const min = math_vector_Vector3.Zero(); - const max = math_vector_Vector3.Zero(); - let distance; - const results = []; - const pickedPoint = math_vector_TmpVectors.Vector3[0].copyFromFloats(0, 0, 0); - const cameraSpacePosition = math_vector_TmpVectors.Vector3[1].copyFromFloats(0, 0, 0); - const cameraView = camera.getViewMatrix(); - for (let index = 0; index < count; index++) { - const sprite = this.sprites[index]; - if (!sprite) { - continue; - } - if (predicate) { - if (!predicate(sprite)) { - continue; - } - } - else if (!sprite.isPickable) { - continue; - } - math_vector_Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition); - min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z); - max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z); - if (ray.intersectsBoxMinMax(min, max)) { - distance = math_vector_Vector3.Distance(cameraSpacePosition, ray.origin); - if (!this._checkTextureAlpha(sprite, ray, distance, min, max)) { - continue; - } - const result = new PickingInfo(); - results.push(result); - cameraView.invertToRef(math_vector_TmpVectors.Matrix[0]); - result.hit = true; - result.pickedSprite = sprite; - result.distance = distance; - // Get picked point - const direction = math_vector_TmpVectors.Vector3[2]; - direction.copyFrom(ray.direction); - direction.normalize(); - direction.scaleInPlace(distance); - ray.origin.addToRef(direction, pickedPoint); - result.pickedPoint = math_vector_Vector3.TransformCoordinates(pickedPoint, math_vector_TmpVectors.Matrix[0]); - } - } - return results; - } - /** - * Render all child sprites - */ - render() { - // Check - if (this._fromPacked && (!this._packedAndReady || !this._spriteMap || !this._cellData)) { - return; - } - const engine = this._scene.getEngine(); - const deltaTime = engine.getDeltaTime(); - if (this._packedAndReady) { - this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix(), this._customUpdate); - } - else { - this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix()); - } - } - /** - * Rebuilds the manager (after a context lost, for eg) - */ - rebuild() { - var _a; - (_a = this._spriteRenderer) === null || _a === void 0 ? void 0 : _a.rebuild(); - } - /** - * Release associated resources - */ - dispose() { - if (this._spriteRenderer) { - this._spriteRenderer.dispose(); - this._spriteRenderer = null; - } - this._textureContent = null; - // Remove from scene - if (this._scene.spriteManagers) { - const index = this._scene.spriteManagers.indexOf(this); - this._scene.spriteManagers.splice(index, 1); - } - // Callback - this.onDisposeObservable.notifyObservers(this); - this.onDisposeObservable.clear(); - this.metadata = null; - } - /** - * Serializes the sprite manager to a JSON object - * @param serializeTexture defines if the texture must be serialized as well - * @returns the JSON object - */ - serialize(serializeTexture = false) { - const serializationObject = {}; - serializationObject.name = this.name; - serializationObject.capacity = this.capacity; - serializationObject.cellWidth = this.cellWidth; - serializationObject.cellHeight = this.cellHeight; - serializationObject.fogEnabled = this.fogEnabled; - serializationObject.blendMode = this.blendMode; - serializationObject.disableDepthWrite = this.disableDepthWrite; - serializationObject.pixelPerfect = this.pixelPerfect; - if (this.texture) { - if (serializeTexture) { - serializationObject.texture = this.texture.serialize(); - } - else { - serializationObject.textureUrl = this.texture.name; - serializationObject.invertY = this.texture._invertY; - } - } - serializationObject.sprites = []; - for (const sprite of this.sprites) { - serializationObject.sprites.push(sprite.serialize()); - } - serializationObject.metadata = this.metadata; - return serializationObject; - } - /** - * Parses a JSON object to create a new sprite manager. - * @param parsedManager The JSON object to parse - * @param scene The scene to create the sprite manager - * @param rootUrl The root url to use to load external dependencies like texture - * @returns the new sprite manager - */ - static Parse(parsedManager, scene, rootUrl) { - const manager = new spriteManager_SpriteManager(parsedManager.name, "", parsedManager.capacity, { - width: parsedManager.cellWidth, - height: parsedManager.cellHeight, - }, scene); - if (parsedManager.fogEnabled !== undefined) { - manager.fogEnabled = parsedManager.fogEnabled; - } - if (parsedManager.blendMode !== undefined) { - manager.blendMode = parsedManager.blendMode; - } - if (parsedManager.disableDepthWrite !== undefined) { - manager.disableDepthWrite = parsedManager.disableDepthWrite; - } - if (parsedManager.pixelPerfect !== undefined) { - manager.pixelPerfect = parsedManager.pixelPerfect; - } - if (parsedManager.metadata !== undefined) { - manager.metadata = parsedManager.metadata; - } - if (parsedManager.texture) { - manager.texture = texture_Texture.Parse(parsedManager.texture, scene, rootUrl); - } - else if (parsedManager.textureName) { - manager.texture = new texture_Texture(rootUrl + parsedManager.textureUrl, scene, false, parsedManager.invertY !== undefined ? parsedManager.invertY : true); - } - for (const parsedSprite of parsedManager.sprites) { - Sprite.Parse(parsedSprite, manager); - } - return manager; - } - /** - * Creates a sprite manager from a snippet saved in a remote file - * @param name defines the name of the sprite manager to create (can be null or empty to use the one from the json data) - * @param url defines the url to load from - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a promise that will resolve to the new sprite manager - */ - static ParseFromFileAsync(name, url, scene, rootUrl = "") { - return new Promise((resolve, reject) => { - const request = new webRequest_WebRequest(); - request.addEventListener("readystatechange", () => { - if (request.readyState == 4) { - if (request.status == 200) { - const serializationObject = JSON.parse(request.responseText); - const output = spriteManager_SpriteManager.Parse(serializationObject, scene || engineStore_EngineStore.LastCreatedScene, rootUrl); - if (name) { - output.name = name; - } - resolve(output); - } - else { - reject("Unable to load the sprite manager"); - } - } - }); - request.open("GET", url); - request.send(); - }); - } - /** - * Creates a sprite manager from a snippet saved by the sprite editor - * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one) - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a promise that will resolve to the new sprite manager - */ - static ParseFromSnippetAsync(snippetId, scene, rootUrl = "") { - if (snippetId === "_BLANK") { - return Promise.resolve(new spriteManager_SpriteManager("Default sprite manager", "//playground.babylonjs.com/textures/player.png", 500, 64, scene)); - } - return new Promise((resolve, reject) => { - const request = new webRequest_WebRequest(); - request.addEventListener("readystatechange", () => { - if (request.readyState == 4) { - if (request.status == 200) { - const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); - const serializationObject = JSON.parse(snippet.spriteManager); - const output = spriteManager_SpriteManager.Parse(serializationObject, scene || engineStore_EngineStore.LastCreatedScene, rootUrl); - output.snippetId = snippetId; - resolve(output); - } - else { - reject("Unable to load the snippet " + snippetId); - } - } - }); - request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); - request.send(); - }); - } -} -/** Define the Url to load snippets */ -spriteManager_SpriteManager.SnippetUrl = `https://snippet.babylonjs.com`; -/** - * Creates a sprite manager from a snippet saved by the sprite editor - * @deprecated Please use ParseFromSnippetAsync instead - * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one) - * @param scene defines the hosting scene - * @param rootUrl defines the root URL to use to load textures and relative dependencies - * @returns a promise that will resolve to the new sprite manager - */ -spriteManager_SpriteManager.CreateFromSnippetAsync = spriteManager_SpriteManager.ParseFromSnippetAsync; -//# sourceMappingURL=spriteManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/spriteMap.fragment.js -// Do not edit. - -const spriteMap_fragment_name = "spriteMapPixelShader"; -const spriteMap_fragment_shader = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4( -texture2D(frameMap,vec2(fX,0.),0.), -texture2D(frameMap,vec2(fX,fdStep*1.),0.), -texture2D(frameMap,vec2(fX,fdStep*2.),0.), -vec4(0.) -);} -void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV); -#ifdef FLIPU -tileUV.y=1.0-tileUV.y; -#endif -vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i<LAYERS; i++) {float frameID; -#define LAYER_ID_SWITCH -vec4 animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,0.),0.);if(animationData.y>0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; f<MAX_ANIMATION_FRAMES; f++){if(animationData.y>mt){frameID=animationData.x;break;} -animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}} -mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;} -vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} -color.xyz*=colorMul;gl_FragColor=color;}`; -// Sideeffect -ShaderStore.ShadersStore[spriteMap_fragment_name] = spriteMap_fragment_shader; -/** @internal */ -const spriteMapPixelShader = { name: spriteMap_fragment_name, shader: spriteMap_fragment_shader }; -//# sourceMappingURL=spriteMap.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/spriteMap.vertex.js -// Do not edit. - -const spriteMap_vertex_name = "spriteMapVertexShader"; -const spriteMap_vertex_shader = `precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; -gl_Position=worldViewProjection*p;}`; -// Sideeffect -ShaderStore.ShadersStore[spriteMap_vertex_name] = spriteMap_vertex_shader; -/** @internal */ -const spriteMapVertexShader = { name: spriteMap_vertex_name, shader: spriteMap_vertex_shader }; -//# sourceMappingURL=spriteMap.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Sprites/spriteMap.js - - - - - - - - - -/** - * Class used to manage a grid restricted sprite deployment on an Output plane. - */ -class SpriteMap { - /** Returns the Number of Sprites in the System */ - get spriteCount() { - return this.sprites.length; - } - /** Returns the Position of Output Plane*/ - get position() { - return this._output.position; - } - /** Returns the Position of Output Plane*/ - set position(v) { - this._output.position = v; - } - /** Returns the Rotation of Output Plane*/ - get rotation() { - return this._output.rotation; - } - /** Returns the Rotation of Output Plane*/ - set rotation(v) { - this._output.rotation = v; - } - /** Sets the AnimationMap*/ - get animationMap() { - return this._animationMap; - } - /** Sets the AnimationMap*/ - set animationMap(v) { - const buffer = v._texture._bufferView; - const am = this._createTileAnimationBuffer(buffer); - this._animationMap.dispose(); - this._animationMap = am; - this._material.setTexture("animationMap", this._animationMap); - } - /** - * Creates a new SpriteMap - * @param name defines the SpriteMaps Name - * @param atlasJSON is the JSON file that controls the Sprites Frames and Meta - * @param spriteSheet is the Texture that the Sprites are on. - * @param options a basic deployment configuration - * @param scene The Scene that the map is deployed on - */ - constructor(name, atlasJSON, spriteSheet, options, scene) { - this.name = name; - this.sprites = []; - this.atlasJSON = atlasJSON; - this.sprites = this.atlasJSON["frames"]; - this.spriteSheet = spriteSheet; - /** - * Run through the options and set what ever defaults are needed that where not declared. - */ - this.options = options; - options.stageSize = options.stageSize || new Vector2(1, 1); - options.outputSize = options.outputSize || options.stageSize; - options.outputPosition = options.outputPosition || Vector3.Zero(); - options.outputRotation = options.outputRotation || Vector3.Zero(); - options.layerCount = options.layerCount || 1; - options.maxAnimationFrames = options.maxAnimationFrames || 0; - options.baseTile = options.baseTile || 0; - options.flipU = options.flipU || false; - options.colorMultiply = options.colorMultiply || new Vector3(1, 1, 1); - this._scene = scene; - this._frameMap = this._createFrameBuffer(); - this._tileMaps = new Array(); - for (let i = 0; i < options.layerCount; i++) { - this._tileMaps.push(this._createTileBuffer(null, i)); - } - this._animationMap = this._createTileAnimationBuffer(null); - const defines = []; - defines.push("#define LAYERS " + options.layerCount); - if (options.flipU) { - defines.push("#define FLIPU"); - } - defines.push(`#define MAX_ANIMATION_FRAMES ${options.maxAnimationFrames}.0`); - const shaderString = Effect.ShadersStore["spriteMapPixelShader"]; - let layerSampleString; - if (!scene.getEngine()._features.supportSwitchCaseInShader) { - layerSampleString = ""; - for (let i = 0; i < options.layerCount; i++) { - layerSampleString += `if (${i} == i) { frameID = texture2D(tileMaps[${i}], (tileID + 0.5) / stageSize, 0.).x; }`; - } - } - else { - layerSampleString = "switch(i) {"; - for (let i = 0; i < options.layerCount; i++) { - layerSampleString += "case " + i + " : frameID = texture(tileMaps[" + i + "], (tileID + 0.5) / stageSize, 0.).x;"; - layerSampleString += "break;"; - } - layerSampleString += "}"; - } - Effect.ShadersStore["spriteMap" + this.name + "PixelShader"] = shaderString.replace("#define LAYER_ID_SWITCH", layerSampleString); - this._material = new ShaderMaterial("spriteMap:" + this.name, this._scene, { - vertex: "spriteMap", - fragment: "spriteMap" + this.name, - }, { - defines, - attributes: ["position", "normal", "uv"], - uniforms: ["worldViewProjection", "time", "stageSize", "outputSize", "spriteMapSize", "spriteCount", "time", "colorMul", "mousePosition", "curTile", "flipU"], - samplers: ["spriteSheet", "frameMap", "tileMaps", "animationMap"], - needAlphaBlending: true, - }); - this._time = 0; - this._material.setFloat("spriteCount", this.spriteCount); - this._material.setVector2("stageSize", options.stageSize); - this._material.setVector2("outputSize", options.outputSize); - this._material.setTexture("spriteSheet", this.spriteSheet); - this._material.setVector2("spriteMapSize", new Vector2(1, 1)); - this._material.setVector3("colorMul", options.colorMultiply); - let tickSave = 0; - const bindSpriteTexture = () => { - if (this.spriteSheet && this.spriteSheet.isReady()) { - if (this.spriteSheet._texture) { - this._material.setVector2("spriteMapSize", new Vector2(this.spriteSheet._texture.baseWidth || 1, this.spriteSheet._texture.baseHeight || 1)); - return; - } - } - if (tickSave < 100) { - setTimeout(() => { - tickSave++; - bindSpriteTexture(); - }, 100); - } - }; - bindSpriteTexture(); - this._material.setVector3("colorMul", options.colorMultiply); - this._material.setTexture("frameMap", this._frameMap); - this._material.setTextureArray("tileMaps", this._tileMaps); - this._material.setTexture("animationMap", this._animationMap); - this._material.setFloat("time", this._time); - this._output = CreatePlane(name + ":output", { size: 1, updatable: true }, scene); - this._output.scaling.x = options.outputSize.x; - this._output.scaling.y = options.outputSize.y; - this.position = options.outputPosition; - this.rotation = options.outputRotation; - const obfunction = () => { - this._time += this._scene.getEngine().getDeltaTime(); - this._material.setFloat("time", this._time); - }; - this._scene.onBeforeRenderObservable.add(obfunction); - this._output.material = this._material; - } - /** - * Returns tileID location - * @returns Vector2 the cell position ID - */ - getTileID() { - const p = this.getMousePosition(); - p.multiplyInPlace(this.options.stageSize || Vector2.Zero()); - p.x = Math.floor(p.x); - p.y = Math.floor(p.y); - return p; - } - /** - * Gets the UV location of the mouse over the SpriteMap. - * @returns Vector2 the UV position of the mouse interaction - */ - getMousePosition() { - const out = this._output; - const pickinfo = this._scene.pick(this._scene.pointerX, this._scene.pointerY, (mesh) => { - if (mesh !== out) { - return false; - } - return true; - }); - if (!pickinfo || !pickinfo.hit || !pickinfo.getTextureCoordinates) { - return new Vector2(-1, -1); - } - const coords = pickinfo.getTextureCoordinates(); - if (coords) { - return coords; - } - return new Vector2(-1, -1); - } - /** - * Creates the "frame" texture Buffer - * ------------------------------------- - * Structure of frames - * "filename": "Falling-Water-2.png", - * "frame": {"x":69,"y":103,"w":24,"h":32}, - * "rotated": true, - * "trimmed": true, - * "spriteSourceSize": {"x":4,"y":0,"w":24,"h":32}, - * "sourceSize": {"w":32,"h":32} - * @returns RawTexture of the frameMap - */ - _createFrameBuffer() { - const data = new Array(); - //Do two Passes - for (let i = 0; i < this.spriteCount; i++) { - data.push(0, 0, 0, 0); //frame - data.push(0, 0, 0, 0); //spriteSourceSize - data.push(0, 0, 0, 0); //sourceSize, rotated, trimmed - 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. - } - //Second Pass - for (let i = 0; i < this.spriteCount; i++) { - const f = this.sprites[i]["frame"]; - const sss = this.sprites[i]["spriteSourceSize"]; - const ss = this.sprites[i]["sourceSize"]; - const r = this.sprites[i]["rotated"] ? 1 : 0; - const t = this.sprites[i]["trimmed"] ? 1 : 0; - //frame - data[i * 4] = f.x; - data[i * 4 + 1] = f.y; - data[i * 4 + 2] = f.w; - data[i * 4 + 3] = f.h; - //spriteSourceSize - data[i * 4 + this.spriteCount * 4] = sss.x; - data[i * 4 + 1 + this.spriteCount * 4] = sss.y; - data[i * 4 + 3 + this.spriteCount * 4] = sss.h; - //sourceSize, rotated, trimmed - data[i * 4 + this.spriteCount * 8] = ss.w; - data[i * 4 + 1 + this.spriteCount * 8] = ss.h; - data[i * 4 + 2 + this.spriteCount * 8] = r; - data[i * 4 + 3 + this.spriteCount * 8] = t; - } - const floatArray = new Float32Array(data); - const t = RawTexture.CreateRGBATexture(floatArray, this.spriteCount, 4, this._scene, false, false, Texture.NEAREST_NEAREST, Engine.TEXTURETYPE_FLOAT); - return t; - } - /** - * Creates the tileMap texture Buffer - * @param buffer normally and array of numbers, or a false to generate from scratch - * @param _layer indicates what layer for a logic trigger dealing with the baseTile. The system uses this - * @returns RawTexture of the tileMap - */ - _createTileBuffer(buffer, _layer = 0) { - let data = new Array(); - const _ty = this.options.stageSize.y || 0; - const _tx = this.options.stageSize.x || 0; - if (!buffer) { - let bt = this.options.baseTile; - if (_layer != 0) { - bt = 0; - } - for (let y = 0; y < _ty; y++) { - for (let x = 0; x < _tx * 4; x += 4) { - data.push(bt, 0, 0, 0); - } - } - } - else { - data = buffer; - } - const floatArray = new Float32Array(data); - const t = RawTexture.CreateRGBATexture(floatArray, _tx, _ty, this._scene, false, false, Texture.NEAREST_NEAREST, Engine.TEXTURETYPE_FLOAT); - return t; - } - /** - * Modifies the data of the tileMaps - * @param _layer is the ID of the layer you want to edit on the SpriteMap - * @param pos is the iVector2 Coordinates of the Tile - * @param tile The SpriteIndex of the new Tile - */ - changeTiles(_layer = 0, pos, tile = 0) { - const buffer = this._tileMaps[_layer]._texture._bufferView; - if (buffer === null) { - return; - } - let p = new Array(); - if (pos instanceof Vector2) { - p.push(pos); - } - else { - p = pos; - } - const _tx = this.options.stageSize.x || 0; - for (let i = 0; i < p.length; i++) { - const _p = p[i]; - _p.x = Math.floor(_p.x); - _p.y = Math.floor(_p.y); - const id = _p.x * 4 + _p.y * (_tx * 4); - buffer[id] = tile; - } - const t = this._createTileBuffer(buffer); - this._tileMaps[_layer].dispose(); - this._tileMaps[_layer] = t; - this._material.setTextureArray("tileMap", this._tileMaps); - } - /** - * Creates the animationMap texture Buffer - * @param buffer normally and array of numbers, or a false to generate from scratch - * @returns RawTexture of the animationMap - */ - _createTileAnimationBuffer(buffer) { - const data = new Array(); - let floatArray; - if (!buffer) { - for (let i = 0; i < this.spriteCount; i++) { - data.push(0, 0, 0, 0); - let count = 1; - while (count < (this.options.maxAnimationFrames || 4)) { - data.push(0, 0, 0, 0); - count++; - } - } - floatArray = new Float32Array(data); - } - else { - floatArray = buffer; - } - const t = RawTexture.CreateRGBATexture(floatArray, this.spriteCount, this.options.maxAnimationFrames || 4, this._scene, false, false, Texture.NEAREST_NEAREST, Engine.TEXTURETYPE_FLOAT); - return t; - } - /** - * Modifies the data of the animationMap - * @param cellID is the Index of the Sprite - * @param _frame is the target Animation frame - * @param toCell is the Target Index of the next frame of the animation - * @param time is a value between 0-1 that is the trigger for when the frame should change tiles - * @param speed is a global scalar of the time variable on the map. - */ - addAnimationToTile(cellID = 0, _frame = 0, toCell = 0, time = 0, speed = 1) { - const buffer = this._animationMap._texture._bufferView; - const id = cellID * 4 + this.spriteCount * 4 * _frame; - if (!buffer) { - return; - } - buffer[id] = toCell; - buffer[id + 1] = time; - buffer[id + 2] = speed; - const t = this._createTileAnimationBuffer(buffer); - this._animationMap.dispose(); - this._animationMap = t; - this._material.setTexture("animationMap", this._animationMap); - } - /** - * Exports the .tilemaps file - */ - saveTileMaps() { - let maps = ""; - for (let i = 0; i < this._tileMaps.length; i++) { - if (i > 0) { - maps += "\n\r"; - } - maps += this._tileMaps[i]._texture._bufferView.toString(); - } - const hiddenElement = document.createElement("a"); - hiddenElement.href = "data:octet/stream;charset=utf-8," + encodeURI(maps); - hiddenElement.target = "_blank"; - hiddenElement.download = this.name + ".tilemaps"; - hiddenElement.click(); - hiddenElement.remove(); - } - /** - * Imports the .tilemaps file - * @param url of the .tilemaps file - */ - loadTileMaps(url) { - const xhr = new XMLHttpRequest(); - xhr.open("GET", url); - const _lc = this.options.layerCount || 0; - xhr.onload = () => { - const data = xhr.response.split("\n\r"); - for (let i = 0; i < _lc; i++) { - const d = data[i].split(",").map(Number); - const t = this._createTileBuffer(d); - this._tileMaps[i].dispose(); - this._tileMaps[i] = t; - } - this._material.setTextureArray("tileMap", this._tileMaps); - }; - xhr.send(); - } - /** - * Release associated resources - */ - dispose() { - this._output.dispose(); - this._material.dispose(); - this._animationMap.dispose(); - this._tileMaps.forEach((tm) => { - tm.dispose(); - }); - this._frameMap.dispose(); - } -} -//# sourceMappingURL=spriteMap.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Sprites/spritePackedManager.js - - -/** - * Class used to manage multiple sprites of different sizes on the same spritesheet - * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites - */ -class SpritePackedManager extends (/* unused pure expression or super */ null && (SpriteManager)) { - /** - * Creates a new sprite manager from a packed sprite sheet - * @param name defines the manager's name - * @param imgUrl defines the sprite sheet url - * @param capacity defines the maximum allowed number of sprites - * @param scene defines the hosting scene - * @param spriteJSON null otherwise a JSON object defining sprite sheet data - * @param epsilon defines the epsilon value to align texture (0.01 by default) - * @param samplingMode defines the sampling mode to use with spritesheet - * @param fromPacked set to true; do not alter - */ - constructor( - /** defines the packed manager's name */ - name, imgUrl, capacity, scene, spriteJSON = null, epsilon = 0.01, samplingMode = Texture.TRILINEAR_SAMPLINGMODE) { - //the cellSize parameter is not used when built from JSON which provides individual cell data, defaults to 64 if JSON load fails - super(name, imgUrl, capacity, 64, scene, epsilon, samplingMode, true, spriteJSON); - this.name = name; - } -} -//# sourceMappingURL=spritePackedManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Sprites/index.js - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/States/index.js - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/assetsManager.js - - - - - - - - - -/** - * Defines the list of states available for a task inside a AssetsManager - */ -var AssetTaskState; -(function (AssetTaskState) { - /** - * Initialization - */ - AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT"; - /** - * Running - */ - AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING"; - /** - * Done - */ - AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE"; - /** - * Error - */ - AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR"; -})(AssetTaskState || (AssetTaskState = {})); -/** - * Define an abstract asset task used with a AssetsManager class to load assets into a scene - */ -class AbstractAssetTask { - /** - * Creates a new AssetsManager - * @param name defines the name of the task - */ - constructor( - /** - * Task name - */ name) { - this.name = name; - this._isCompleted = false; - this._taskState = AssetTaskState.INIT; - } - /** - * Get if the task is completed - */ - get isCompleted() { - return this._isCompleted; - } - /** - * Gets the current state of the task - */ - get taskState() { - return this._taskState; - } - /** - * Gets the current error object (if task is in error) - */ - get errorObject() { - return this._errorObject; - } - /** - * Internal only - * @internal - */ - _setErrorObject(message, exception) { - if (this._errorObject) { - return; - } - this._errorObject = { - message: message, - exception: exception, - }; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - run(scene, onSuccess, onError) { - this._taskState = AssetTaskState.RUNNING; - this.runTask(scene, () => { - this._onDoneCallback(onSuccess, onError); - }, (msg, exception) => { - this._onErrorCallback(onError, msg, exception); - }); - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - runTask(scene, onSuccess, onError) { - throw new Error("runTask is not implemented"); - } - /** - * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again. - * This can be used with failed tasks that have the reason for failure fixed. - */ - reset() { - this._taskState = AssetTaskState.INIT; - } - _onErrorCallback(onError, message, exception) { - this._taskState = AssetTaskState.ERROR; - this._errorObject = { - message: message, - exception: exception, - }; - if (this.onError) { - this.onError(this, message, exception); - } - onError(); - } - _onDoneCallback(onSuccess, onError) { - try { - this._taskState = AssetTaskState.DONE; - this._isCompleted = true; - if (this.onSuccess) { - this.onSuccess(this); - } - onSuccess(); - } - catch (e) { - this._onErrorCallback(onError, "Task is done, error executing success callback(s)", e); - } - } -} -/** - * Class used to share progress information about assets loading - */ -class AssetsProgressEvent { - /** - * Creates a AssetsProgressEvent - * @param remainingCount defines the number of remaining tasks to process - * @param totalCount defines the total number of tasks - * @param task defines the task that was just processed - */ - constructor(remainingCount, totalCount, task) { - this.remainingCount = remainingCount; - this.totalCount = totalCount; - this.task = task; - } -} -/** - * Define a task used by AssetsManager to load assets into a container - */ -class ContainerAssetTask extends (/* unused pure expression or super */ null && (AbstractAssetTask)) { - /** - * Creates a new ContainerAssetTask - * @param name defines the name of the task - * @param meshesNames defines the list of mesh's names you want to load - * @param rootUrl defines the root url to use as a base to load your meshes and associated resources - * @param sceneFilename defines the filename or File of the scene to load from - */ - constructor( - /** - * Defines the name of the task - */ - name, - /** - * Defines the list of mesh's names you want to load - */ - meshesNames, - /** - * Defines the root url to use as a base to load your meshes and associated resources - */ - rootUrl, - /** - * Defines the filename or File of the scene to load from - */ - sceneFilename, - /** - * Defines the extension to use to load the scene (if not defined, ".babylon" will be used) - */ - extension) { - super(name); - this.name = name; - this.meshesNames = meshesNames; - this.rootUrl = rootUrl; - this.sceneFilename = sceneFilename; - this.extension = extension; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - runTask(scene, onSuccess, onError) { - SceneLoader.LoadAssetContainer(this.rootUrl, this.sceneFilename, scene, (container) => { - this.loadedContainer = container; - this.loadedMeshes = container.meshes; - this.loadedTransformNodes = container.transformNodes; - this.loadedParticleSystems = container.particleSystems; - this.loadedSkeletons = container.skeletons; - this.loadedAnimationGroups = container.animationGroups; - onSuccess(); - }, null, (scene, message, exception) => { - onError(message, exception); - }, this.extension); - } -} -/** - * Define a task used by AssetsManager to load meshes - */ -class MeshAssetTask extends (/* unused pure expression or super */ null && (AbstractAssetTask)) { - /** - * Creates a new MeshAssetTask - * @param name defines the name of the task - * @param meshesNames defines the list of mesh's names you want to load - * @param rootUrl defines the root url to use as a base to load your meshes and associated resources - * @param sceneFilename defines the filename or File of the scene to load from - */ - constructor( - /** - * Defines the name of the task - */ - name, - /** - * Defines the list of mesh's names you want to load - */ - meshesNames, - /** - * Defines the root url to use as a base to load your meshes and associated resources - */ - rootUrl, - /** - * Defines the filename or File of the scene to load from - */ - sceneFilename, - /** - * Defines the extension to use to load the scene (if not defined, ".babylon" will be used) - */ - extension) { - super(name); - this.name = name; - this.meshesNames = meshesNames; - this.rootUrl = rootUrl; - this.sceneFilename = sceneFilename; - this.extension = extension; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - runTask(scene, onSuccess, onError) { - SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups, transformNodes) => { - this.loadedMeshes = meshes; - this.loadedTransformNodes = transformNodes; - this.loadedParticleSystems = particleSystems; - this.loadedSkeletons = skeletons; - this.loadedAnimationGroups = animationGroups; - onSuccess(); - }, null, (scene, message, exception) => { - onError(message, exception); - }, this.extension); - } -} -/** - * Define a task used by AssetsManager to load animations - */ -class AnimationAssetTask extends (/* unused pure expression or super */ null && (AbstractAssetTask)) { - /** - * Creates a new AnimationAssetTask - * @param name defines the name of the task - * @param rootUrl defines the root url to use as a base to load your meshes and associated resources - * @param filename defines the filename or File of the scene to load from - * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name) - */ - constructor( - /** - * Defines the name of the task - */ - name, - /** - * Defines the root url to use as a base to load your meshes and associated resources - */ - rootUrl, - /** - * Defines the filename to load from - */ - filename, - /** - * Defines a function used to convert animation targets from loaded scene to current scene (default: search node by name) - */ - targetConverter, - /** - * Defines the extension to use to load the scene (if not defined, ".babylon" will be used) - */ - extension) { - super(name); - this.name = name; - this.rootUrl = rootUrl; - this.filename = filename; - this.targetConverter = targetConverter; - this.extension = extension; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - runTask(scene, onSuccess, onError) { - const startingIndexForNewAnimatables = scene.animatables.length; - const startingIndexForNewAnimationGroups = scene.animationGroups.length; - this.loadedAnimatables = []; - this.loadedAnimationGroups = []; - SceneLoader.ImportAnimations(this.rootUrl, this.filename, scene, false, SceneLoaderAnimationGroupLoadingMode.NoSync, this.targetConverter, () => { - this.loadedAnimatables = scene.animatables.slice(startingIndexForNewAnimatables); - this.loadedAnimationGroups = scene.animationGroups.slice(startingIndexForNewAnimationGroups); - onSuccess(); - }, null, (scene, message, exception) => { - onError(message, exception); - }, this.extension); - } -} -/** - * Define a task used by AssetsManager to load text content - */ -class TextFileAssetTask extends (/* unused pure expression or super */ null && (AbstractAssetTask)) { - /** - * Creates a new TextFileAssetTask object - * @param name defines the name of the task - * @param url defines the location of the file to load - */ - constructor( - /** - * Defines the name of the task - */ - name, - /** - * Defines the location of the file to load - */ - url) { - super(name); - this.name = name; - this.url = url; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - runTask(scene, onSuccess, onError) { - scene._loadFile(this.url, (data) => { - this.text = data; - onSuccess(); - }, undefined, false, false, (request, exception) => { - if (request) { - onError(request.status + " " + request.statusText, exception); - } - }); - } -} -/** - * Define a task used by AssetsManager to load binary data - */ -class BinaryFileAssetTask extends (/* unused pure expression or super */ null && (AbstractAssetTask)) { - /** - * Creates a new BinaryFileAssetTask object - * @param name defines the name of the new task - * @param url defines the location of the file to load - */ - constructor( - /** - * Defines the name of the task - */ - name, - /** - * Defines the location of the file to load - */ - url) { - super(name); - this.name = name; - this.url = url; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - runTask(scene, onSuccess, onError) { - scene._loadFile(this.url, (data) => { - this.data = data; - onSuccess(); - }, undefined, true, true, (request, exception) => { - if (request) { - onError(request.status + " " + request.statusText, exception); - } - }); - } -} -/** - * Define a task used by AssetsManager to load images - */ -class ImageAssetTask extends (/* unused pure expression or super */ null && (AbstractAssetTask)) { - /** - * Creates a new ImageAssetTask - * @param name defines the name of the task - * @param url defines the location of the image to load - */ - constructor( - /** - * Defines the name of the task - */ - name, - /** - * Defines the location of the image to load - */ - url) { - super(name); - this.name = name; - this.url = url; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - runTask(scene, onSuccess, onError) { - const img = new Image(); - Tools.SetCorsBehavior(this.url, img); - img.onload = () => { - this.image = img; - onSuccess(); - }; - img.onerror = (err) => { - onError("Error loading image", err); - }; - img.src = this.url; - } -} -/** - * Define a task used by AssetsManager to load 2D textures - */ -class TextureAssetTask extends (/* unused pure expression or super */ null && (AbstractAssetTask)) { - /** - * Creates a new TextureAssetTask object - * @param name defines the name of the task - * @param url defines the location of the file to load - * @param noMipmap defines if mipmap should not be generated (default is false) - * @param invertY defines if texture must be inverted on Y axis (default is true) - * @param samplingMode defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE) - */ - constructor( - /** - * Defines the name of the task - */ - name, - /** - * Defines the location of the file to load - */ - url, - /** - * Defines if mipmap should not be generated (default is false) - */ - noMipmap, - /** - * Defines if texture must be inverted on Y axis (default is true) - */ - invertY = true, - /** - * Defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE) - */ - samplingMode = Texture.TRILINEAR_SAMPLINGMODE) { - super(name); - this.name = name; - this.url = url; - this.noMipmap = noMipmap; - this.invertY = invertY; - this.samplingMode = samplingMode; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - runTask(scene, onSuccess, onError) { - const onload = () => { - onSuccess(); - }; - const onerror = (message, exception) => { - onError(message, exception); - }; - this.texture = new Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror); - } -} -/** - * Define a task used by AssetsManager to load cube textures - */ -class CubeTextureAssetTask extends (/* unused pure expression or super */ null && (AbstractAssetTask)) { - /** - * Creates a new CubeTextureAssetTask - * @param name defines the name of the task - * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension) - * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default) - * @param noMipmap defines if mipmaps should not be generated (default is false) - * @param files defines the explicit list of files (undefined by default) - * @param prefiltered - */ - constructor( - /** - * Defines the name of the task - */ - name, - /** - * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension) - */ - url, - /** - * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default) - */ - extensions, - /** - * Defines if mipmaps should not be generated (default is false) - */ - noMipmap, - /** - * Defines the explicit list of files (undefined by default) - */ - files, - /** - * Defines the prefiltered texture option (default is false) - */ - prefiltered) { - super(name); - this.name = name; - this.url = url; - this.extensions = extensions; - this.noMipmap = noMipmap; - this.files = files; - this.prefiltered = prefiltered; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - runTask(scene, onSuccess, onError) { - const onload = () => { - onSuccess(); - }; - const onerror = (message, exception) => { - onError(message, exception); - }; - this.texture = new CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror, undefined, this.prefiltered); - } -} -/** - * Define a task used by AssetsManager to load HDR cube textures - */ -class HDRCubeTextureAssetTask extends (/* unused pure expression or super */ null && (AbstractAssetTask)) { - /** - * Creates a new HDRCubeTextureAssetTask object - * @param name defines the name of the task - * @param url defines the location of the file to load - * @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. - * @param noMipmap defines if mipmaps should not be generated (default is false) - * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true) - * @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) - * @param reserved Internal use only - */ - constructor( - /** - * Defines the name of the task - */ - name, - /** - * Defines the location of the file to load - */ - url, - /** - * Defines the desired size (the more it increases the longer the generation will be) - */ - size, - /** - * Defines if mipmaps should not be generated (default is false) - */ - noMipmap = false, - /** - * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true) - */ - generateHarmonics = true, - /** - * 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) - */ - gammaSpace = false, - /** - * Internal Use Only - */ - reserved = false) { - super(name); - this.name = name; - this.url = url; - this.size = size; - this.noMipmap = noMipmap; - this.generateHarmonics = generateHarmonics; - this.gammaSpace = gammaSpace; - this.reserved = reserved; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - runTask(scene, onSuccess, onError) { - const onload = () => { - onSuccess(); - }; - const onerror = (message, exception) => { - onError(message, exception); - }; - this.texture = new HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror); - } -} -/** - * Define a task used by AssetsManager to load Equirectangular cube textures - */ -class EquiRectangularCubeTextureAssetTask extends (/* unused pure expression or super */ null && (AbstractAssetTask)) { - /** - * Creates a new EquiRectangularCubeTextureAssetTask object - * @param name defines the name of the task - * @param url defines the location of the file to load - * @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. - * @param noMipmap defines if mipmaps should not be generated (default is false) - * @param gammaSpace specifies if the texture will be used 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 true) - */ - constructor( - /** - * Defines the name of the task - */ - name, - /** - * Defines the location of the file to load - */ - url, - /** - * Defines the desired size (the more it increases the longer the generation will be) - */ - size, - /** - * Defines if mipmaps should not be generated (default is false) - */ - noMipmap = false, - /** - * 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 true) - */ - gammaSpace = true) { - super(name); - this.name = name; - this.url = url; - this.size = size; - this.noMipmap = noMipmap; - this.gammaSpace = gammaSpace; - } - /** - * Execute the current task - * @param scene defines the scene where you want your assets to be loaded - * @param onSuccess is a callback called when the task is successfully executed - * @param onError is a callback called if an error occurs - */ - runTask(scene, onSuccess, onError) { - const onload = () => { - onSuccess(); - }; - const onerror = (message, exception) => { - onError(message, exception); - }; - this.texture = new EquiRectangularCubeTexture(this.url, scene, this.size, this.noMipmap, this.gammaSpace, onload, onerror); - } -} -/** - * This class can be used to easily import assets into a scene - * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/assetManager - */ -class AssetsManager { - /** - * Creates a new AssetsManager - * @param scene defines the scene to work on - */ - constructor(scene) { - this._isLoading = false; - this._tasks = new Array(); - this._waitingTasksCount = 0; - this._totalTasksCount = 0; - /** - * Observable called when all tasks are processed - */ - this.onTaskSuccessObservable = new Observable(); - /** - * Observable called when a task had an error - */ - this.onTaskErrorObservable = new Observable(); - /** - * Observable called when all tasks were executed - */ - this.onTasksDoneObservable = new Observable(); - /** - * Observable called when a task is done (whatever the result is) - */ - this.onProgressObservable = new Observable(); - /** - * Gets or sets a boolean defining if the AssetsManager should use the default loading screen - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen - */ - this.useDefaultLoadingScreen = true; - /** - * Gets or sets a boolean defining if the AssetsManager should automatically hide the loading screen - * when all assets have been downloaded. - * If set to false, you need to manually call in hideLoadingUI() once your scene is ready. - */ - this.autoHideLoadingUI = true; - this._scene = scene || EngineStore.LastCreatedScene; - } - /** - * Add a ContainerAssetTask to the list of active tasks - * @param taskName defines the name of the new task - * @param meshesNames defines the name of meshes to load - * @param rootUrl defines the root url to use to locate files - * @param sceneFilename defines the filename of the scene file or the File itself - * @param extension defines the extension to use to load the file - * @returns a new ContainerAssetTask object - */ - addContainerTask(taskName, meshesNames, rootUrl, sceneFilename, extension) { - const task = new ContainerAssetTask(taskName, meshesNames, rootUrl, sceneFilename, extension); - this._tasks.push(task); - return task; - } - /** - * Add a MeshAssetTask to the list of active tasks - * @param taskName defines the name of the new task - * @param meshesNames defines the name of meshes to load - * @param rootUrl defines the root url to use to locate files - * @param sceneFilename defines the filename of the scene file or the File itself - * @param extension defines the extension to use to load the file - * @returns a new MeshAssetTask object - */ - addMeshTask(taskName, meshesNames, rootUrl, sceneFilename, extension) { - const task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename, extension); - this._tasks.push(task); - return task; - } - /** - * Add a TextFileAssetTask to the list of active tasks - * @param taskName defines the name of the new task - * @param url defines the url of the file to load - * @returns a new TextFileAssetTask object - */ - addTextFileTask(taskName, url) { - const task = new TextFileAssetTask(taskName, url); - this._tasks.push(task); - return task; - } - /** - * Add a BinaryFileAssetTask to the list of active tasks - * @param taskName defines the name of the new task - * @param url defines the url of the file to load - * @returns a new BinaryFileAssetTask object - */ - addBinaryFileTask(taskName, url) { - const task = new BinaryFileAssetTask(taskName, url); - this._tasks.push(task); - return task; - } - /** - * Add a ImageAssetTask to the list of active tasks - * @param taskName defines the name of the new task - * @param url defines the url of the file to load - * @returns a new ImageAssetTask object - */ - addImageTask(taskName, url) { - const task = new ImageAssetTask(taskName, url); - this._tasks.push(task); - return task; - } - /** - * Add a TextureAssetTask to the list of active tasks - * @param taskName defines the name of the new task - * @param url defines the url of the file to load - * @param noMipmap defines if the texture must not receive mipmaps (false by default) - * @param invertY defines if you want to invert Y axis of the loaded texture (true by default) - * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default) - * @returns a new TextureAssetTask object - */ - addTextureTask(taskName, url, noMipmap, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE) { - const task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode); - this._tasks.push(task); - return task; - } - /** - * Add a CubeTextureAssetTask to the list of active tasks - * @param taskName defines the name of the new task - * @param url defines the url of the file to load - * @param extensions defines the extension to use to load the cube map (can be null) - * @param noMipmap defines if the texture must not receive mipmaps (false by default) - * @param files defines the list of files to load (can be null) - * @param prefiltered defines the prefiltered texture option (default is false) - * @returns a new CubeTextureAssetTask object - */ - addCubeTextureTask(taskName, url, extensions, noMipmap, files, prefiltered) { - const task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files, prefiltered); - this._tasks.push(task); - return task; - } - /** - * - * Add a HDRCubeTextureAssetTask to the list of active tasks - * @param taskName defines the name of the new task - * @param url defines the url of the file to load - * @param size defines the size you want for the cubemap (can be null) - * @param noMipmap defines if the texture must not receive mipmaps (false by default) - * @param generateHarmonics defines if you want to automatically generate (true by default) - * @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) - * @param reserved Internal use only - * @returns a new HDRCubeTextureAssetTask object - */ - addHDRCubeTextureTask(taskName, url, size, noMipmap = false, generateHarmonics = true, gammaSpace = false, reserved = false) { - const task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved); - this._tasks.push(task); - return task; - } - /** - * - * Add a EquiRectangularCubeTextureAssetTask to the list of active tasks - * @param taskName defines the name of the new task - * @param url defines the url of the file to load - * @param size defines the size you want for the cubemap (can be null) - * @param noMipmap defines if the texture must not receive mipmaps (false by default) - * @param gammaSpace Specifies if the texture will be used in gamma or linear space - * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space) - * @returns a new EquiRectangularCubeTextureAssetTask object - */ - addEquiRectangularCubeTextureAssetTask(taskName, url, size, noMipmap = false, gammaSpace = true) { - const task = new EquiRectangularCubeTextureAssetTask(taskName, url, size, noMipmap, gammaSpace); - this._tasks.push(task); - return task; - } - /** - * Remove a task from the assets manager. - * @param task the task to remove - */ - removeTask(task) { - const index = this._tasks.indexOf(task); - if (index > -1) { - this._tasks.splice(index, 1); - } - } - _decreaseWaitingTasksCount(task) { - this._waitingTasksCount--; - try { - if (this.onProgress) { - this.onProgress(this._waitingTasksCount, this._totalTasksCount, task); - } - this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task)); - } - catch (e) { - Logger.Error("Error running progress callbacks."); - console.log(e); - } - if (this._waitingTasksCount === 0) { - try { - const currentTasks = this._tasks.slice(); - if (this.onFinish) { - // Calling onFinish with immutable array of tasks - this.onFinish(currentTasks); - } - // Let's remove successful tasks - for (const task of currentTasks) { - if (task.taskState === AssetTaskState.DONE) { - const index = this._tasks.indexOf(task); - if (index > -1) { - this._tasks.splice(index, 1); - } - } - } - this.onTasksDoneObservable.notifyObservers(this._tasks); - } - catch (e) { - Logger.Error("Error running tasks-done callbacks."); - console.log(e); - } - this._isLoading = false; - if (this.autoHideLoadingUI) { - this._scene.getEngine().hideLoadingUI(); - } - } - } - _runTask(task) { - const done = () => { - try { - if (this.onTaskSuccess) { - this.onTaskSuccess(task); - } - this.onTaskSuccessObservable.notifyObservers(task); - this._decreaseWaitingTasksCount(task); - } - catch (e) { - error("Error executing task success callbacks", e); - } - }; - const error = (message, exception) => { - task._setErrorObject(message, exception); - if (this.onTaskError) { - this.onTaskError(task); - } - else if (!task.onError) { - Logger.Error(this._formatTaskErrorMessage(task)); - } - this.onTaskErrorObservable.notifyObservers(task); - this._decreaseWaitingTasksCount(task); - }; - task.run(this._scene, done, error); - } - _formatTaskErrorMessage(task) { - let errorMessage = "Unable to complete task " + task.name; - if (task.errorObject.message) { - errorMessage += `: ${task.errorObject.message}`; - } - if (task.errorObject.exception) { - errorMessage += `: ${task.errorObject.exception}`; - } - return errorMessage; - } - /** - * Reset the AssetsManager and remove all tasks - * @returns the current instance of the AssetsManager - */ - reset() { - this._isLoading = false; - this._tasks = new Array(); - return this; - } - /** - * Start the loading process - * @returns the current instance of the AssetsManager - */ - load() { - if (this._isLoading) { - return this; - } - this._isLoading = true; - this._waitingTasksCount = this._tasks.length; - this._totalTasksCount = this._tasks.length; - if (this._waitingTasksCount === 0) { - this._isLoading = false; - if (this.onFinish) { - this.onFinish(this._tasks); - } - this.onTasksDoneObservable.notifyObservers(this._tasks); - return this; - } - if (this.useDefaultLoadingScreen) { - this._scene.getEngine().displayLoadingUI(); - } - for (let index = 0; index < this._tasks.length; index++) { - const task = this._tasks[index]; - if (task.taskState === AssetTaskState.INIT) { - this._runTask(task); - } - } - return this; - } - /** - * Start the loading process as an async operation - * @returns a promise returning the list of failed tasks - */ - loadAsync() { - return new Promise((resolve, reject) => { - if (this._isLoading) { - resolve(); - return; - } - this.onTasksDoneObservable.addOnce((remainingTasks) => { - if (remainingTasks && remainingTasks.length) { - reject(remainingTasks); - } - else { - resolve(); - } - }); - this.load(); - }); - } -} -//# sourceMappingURL=assetsManager.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/deferred.js -/** - * Wrapper class for promise with external resolve and reject. - */ -class Deferred { - /** - * The resolve method of the promise associated with this deferred object. - */ - get resolve() { - return this._resolve; - } - /** - * The reject method of the promise associated with this deferred object. - */ - get reject() { - return this._reject; - } - /** - * Constructor for this deferred object. - */ - constructor() { - this.promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - }); - } -} -//# sourceMappingURL=deferred.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/meshExploder.js - -/** - * Class used to explode meshes (ie. to have a center and move them away from that center to better see the overall organization) - */ -class MeshExploder { - /** - * Explodes meshes from a center mesh. - * @param meshes The meshes to explode. - * @param centerMesh The mesh to be center of explosion. - */ - constructor(meshes, centerMesh) { - this._meshesOrigins = []; - this._toCenterVectors = []; - this._scaledDirection = new Vector3(1, 1, 1); - this._newPosition = Vector3.Zero(); - this._centerPosition = Vector3.Zero(); - this._meshes = meshes.slice(); - if (centerMesh) { - this._centerMesh = centerMesh; - } - else { - this._setCenterMesh(); - } - this._centerMesh.computeWorldMatrix(true); - const centerMeshIndex = this._meshes.indexOf(this._centerMesh); - if (centerMeshIndex >= 0) { - this._meshes.splice(centerMeshIndex, 1); - } - this._centerPosition = this._centerMesh.getAbsolutePosition().clone(); - for (let index = 0; index < this._meshes.length; index++) { - if (this._meshes[index]) { - const mesh = this._meshes[index]; - this._meshesOrigins[index] = mesh.getAbsolutePosition().clone(); - this._toCenterVectors[index] = Vector3.Zero(); - if (mesh.hasBoundingInfo && this._centerMesh.hasBoundingInfo) { - mesh.computeWorldMatrix(true); - mesh.getBoundingInfo().boundingBox.centerWorld.subtractToRef(this._centerMesh.getBoundingInfo().boundingBox.centerWorld, this._toCenterVectors[index]); - } - } - } - } - _setCenterMesh() { - let averageCenter = Vector3.Zero(); - const totalCenters = Vector3.Zero(); - let shortestToCenter = Number.MAX_VALUE; - for (let index = 0; index < this._meshes.length; index++) { - if (this._meshes[index]) { - const mesh = this._meshes[index]; - const boundingInfo = mesh.getBoundingInfo(); - if (boundingInfo) { - totalCenters.addInPlace(boundingInfo.boundingBox.centerWorld); - } - } - } - averageCenter = totalCenters.scale(1 / this._meshes.length); - for (let index = 0; index < this._meshes.length; index++) { - if (this._meshes[index]) { - const mesh = this._meshes[index]; - const boundingInfo = mesh.getBoundingInfo(); - if (boundingInfo) { - const distanceToCenter = boundingInfo.boundingBox.centerWorld.subtract(averageCenter).lengthSquared(); - if (distanceToCenter < shortestToCenter) { - this._centerMesh = mesh; - shortestToCenter = distanceToCenter; - } - } - } - } - } - /** - * Get class name - * @returns "MeshExploder" - */ - getClassName() { - return "MeshExploder"; - } - /** - * "Exploded meshes" - * @returns Array of meshes with the centerMesh at index 0. - */ - getMeshes() { - const meshArray = this._meshes.slice(); - meshArray.unshift(this._centerMesh); - return meshArray; - } - /** - * Explodes meshes giving a specific direction - * @param direction Number to multiply distance of each mesh's origin from center. Use a negative number to implode, or zero to reset. - */ - explode(direction = 1.0) { - for (let index = 0; index < this._meshes.length; index++) { - if (this._meshes[index] && this._meshesOrigins[index] && this._toCenterVectors[index]) { - this._toCenterVectors[index].scaleToRef(direction, this._scaledDirection); - this._meshesOrigins[index].addToRef(this._scaledDirection, this._newPosition); - this._meshes[index].setAbsolutePosition(this._newPosition); - } - } - this._centerMesh.setAbsolutePosition(this._centerPosition); - } -} -//# sourceMappingURL=meshExploder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/filesInput.js - - - -/** - * Class used to help managing file picking and drag-n-drop - */ -class FilesInput { - /** - * List of files ready to be loaded - */ - static get FilesToLoad() { - return FilesInputStore.FilesToLoad; - } - /** - * Creates a new FilesInput - * @param engine defines the rendering engine - * @param scene defines the hosting scene - * @param sceneLoadedCallback callback called when scene (files provided) is loaded - * @param progressCallback callback called to track progress - * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop - * @param textureLoadingCallback callback called when a texture is loading - * @param startingProcessingFilesCallback callback called when the system is about to process all files - * @param onReloadCallback callback called when a reload is requested - * @param errorCallback callback call if an error occurs - * @param useAppend defines if the file loaded must be appended (true) or have the scene replaced (false, default behavior) - */ - constructor(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback, useAppend = false) { - this.useAppend = useAppend; - /** - * Callback called when a file is processed - */ - this.onProcessFileCallback = () => { - return true; - }; - this.displayLoadingUI = true; - /** - * Function used when loading the scene file - * @param sceneFile - * @param onProgress - */ - this.loadAsync = (sceneFile, onProgress) => this.useAppend ? SceneLoader.AppendAsync("file:", sceneFile, this._currentScene, onProgress) : SceneLoader.LoadAsync("file:", sceneFile, this._engine, onProgress); - this._engine = engine; - this._currentScene = scene; - this._sceneLoadedCallback = sceneLoadedCallback; - this._progressCallback = progressCallback; - this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback; - this._textureLoadingCallback = textureLoadingCallback; - this._startingProcessingFilesCallback = startingProcessingFilesCallback; - this._onReloadCallback = onReloadCallback; - this._errorCallback = errorCallback; - } - /** - * Calls this function to listen to drag'n'drop events on a specific DOM element - * @param elementToMonitor defines the DOM element to track - */ - monitorElementForDragNDrop(elementToMonitor) { - if (elementToMonitor) { - this._elementToMonitor = elementToMonitor; - this._dragEnterHandler = (e) => { - this._drag(e); - }; - this._dragOverHandler = (e) => { - this._drag(e); - }; - this._dropHandler = (e) => { - this._drop(e); - }; - this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false); - this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false); - this._elementToMonitor.addEventListener("drop", this._dropHandler, false); - } - } - /** Gets the current list of files to load */ - get filesToLoad() { - return this._filesToLoad; - } - /** - * Release all associated resources - */ - dispose() { - if (!this._elementToMonitor) { - return; - } - this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler); - this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler); - this._elementToMonitor.removeEventListener("drop", this._dropHandler); - } - _renderFunction() { - if (this._additionalRenderLoopLogicCallback) { - this._additionalRenderLoopLogicCallback(); - } - if (this._currentScene) { - if (this._textureLoadingCallback) { - const remaining = this._currentScene.getWaitingItemsCount(); - if (remaining > 0) { - this._textureLoadingCallback(remaining); - } - } - this._currentScene.render(); - } - } - _drag(e) { - e.stopPropagation(); - e.preventDefault(); - } - _drop(eventDrop) { - eventDrop.stopPropagation(); - eventDrop.preventDefault(); - this.loadFiles(eventDrop); - } - _traverseFolder(folder, files, remaining, callback) { - const reader = folder.createReader(); - const relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/"); - reader.readEntries((entries) => { - remaining.count += entries.length; - for (const entry of entries) { - if (entry.isFile) { - entry.file((file) => { - file.correctName = relativePath + file.name; - files.push(file); - if (--remaining.count === 0) { - callback(); - } - }); - } - else if (entry.isDirectory) { - this._traverseFolder(entry, files, remaining, callback); - } - } - if (--remaining.count === 0) { - callback(); - } - }); - } - _processFiles(files) { - for (let i = 0; i < files.length; i++) { - const name = files[i].correctName.toLowerCase(); - const extension = name.split(".").pop(); - if (!this.onProcessFileCallback(files[i], name, extension, (sceneFile) => (this._sceneFileToLoad = sceneFile))) { - continue; - } - if (SceneLoader.IsPluginForExtensionAvailable("." + extension)) { - this._sceneFileToLoad = files[i]; - } - FilesInput.FilesToLoad[name] = files[i]; - } - } - /** - * Load files from a drop event - * @param event defines the drop event to use as source - */ - loadFiles(event) { - // Handling data transfer via drag'n'drop - if (event && event.dataTransfer && event.dataTransfer.files) { - this._filesToLoad = event.dataTransfer.files; - } - // Handling files from input files - if (event && event.target && event.target.files) { - this._filesToLoad = event.target.files; - } - if (!this._filesToLoad || this._filesToLoad.length === 0) { - return; - } - if (this._startingProcessingFilesCallback) { - this._startingProcessingFilesCallback(this._filesToLoad); - } - if (this._filesToLoad && this._filesToLoad.length > 0) { - const files = new Array(); - const folders = []; - const items = event.dataTransfer ? event.dataTransfer.items : null; - for (let i = 0; i < this._filesToLoad.length; i++) { - const fileToLoad = this._filesToLoad[i]; - const name = fileToLoad.name.toLowerCase(); - let entry; - fileToLoad.correctName = name; - if (items) { - const item = items[i]; - if (item.getAsEntry) { - entry = item.getAsEntry(); - } - else if (item.webkitGetAsEntry) { - entry = item.webkitGetAsEntry(); - } - } - if (!entry) { - files.push(fileToLoad); - } - else { - if (entry.isDirectory) { - folders.push(entry); - } - else { - files.push(fileToLoad); - } - } - } - if (folders.length === 0) { - this._processFiles(files); - this._processReload(); - } - else { - const remaining = { count: folders.length }; - for (const folder of folders) { - this._traverseFolder(folder, files, remaining, () => { - this._processFiles(files); - if (remaining.count === 0) { - this._processReload(); - } - }); - } - } - } - } - _processReload() { - if (this._onReloadCallback) { - this._onReloadCallback(this._sceneFileToLoad); - } - else { - this.reload(); - } - } - /** - * Reload the current scene from the loaded files - */ - reload() { - // If a scene file has been provided - if (this._sceneFileToLoad) { - if (!this.useAppend) { - if (this._currentScene) { - if (Logger.errorsCount > 0) { - Logger.ClearLogCache(); - } - this._engine.stopRenderLoop(); - } - } - SceneLoader.ShowLoadingScreen = false; - if (this.displayLoadingUI) { - this._engine.displayLoadingUI(); - } - this.loadAsync(this._sceneFileToLoad, this._progressCallback) - .then((scene) => { - // if appending do nothing - if (!this.useAppend) { - if (this._currentScene) { - this._currentScene.dispose(); - } - this._currentScene = scene; - // Wait for textures and shaders to be ready - this._currentScene.executeWhenReady(() => { - if (this.displayLoadingUI) { - this._engine.hideLoadingUI(); - } - this._engine.runRenderLoop(() => { - this._renderFunction(); - }); - }); - } - else { - if (this.displayLoadingUI) { - this._engine.hideLoadingUI(); - } - } - if (this._sceneLoadedCallback && this._currentScene) { - this._sceneLoadedCallback(this._sceneFileToLoad, this._currentScene); - } - }) - .catch((error) => { - if (this.displayLoadingUI) { - this._engine.hideLoadingUI(); - } - if (this._errorCallback) { - this._errorCallback(this._sceneFileToLoad, this._currentScene, error.message); - } - }); - } - else { - Logger.Error("Please provide a valid .babylon file."); - } - } -} -//# sourceMappingURL=filesInput.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/HighDynamicRange/index.js - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/observable.extensions.js - -/** - * Represent a list of observers registered to multiple Observables object. - */ -class MultiObserver { - /** - * Release associated resources - */ - dispose() { - if (this._observers && this._observables) { - for (let index = 0; index < this._observers.length; index++) { - this._observables[index].remove(this._observers[index]); - } - } - this._observers = null; - this._observables = null; - } - /** - * Raise a callback when one of the observable will notify - * @param observables defines a list of observables to watch - * @param callback defines the callback to call on notification - * @param mask defines the mask used to filter notifications - * @param scope defines the current scope used to restore the JS context - * @returns the new MultiObserver - */ - static Watch(observables, callback, mask = -1, scope = null) { - const result = new MultiObserver(); - result._observers = new Array(); - result._observables = observables; - for (const observable of observables) { - const observer = observable.add(callback, mask, false, scope); - if (observer) { - result._observers.push(observer); - } - } - return result; - } -} -observable_Observable.prototype.notifyObserversWithPromise = async function (eventData, mask = -1, target, currentTarget, userInfo) { - // create an empty promise - let p = Promise.resolve(eventData); - // no observers? return this promise. - if (!this.observers.length) { - return p; - } - const state = this._eventState; - state.mask = mask; - state.target = target; - state.currentTarget = currentTarget; - state.skipNextObservers = false; - state.userInfo = userInfo; - // execute one callback after another (not using Promise.all, the order is important) - this.observers.forEach((obs) => { - if (state.skipNextObservers) { - return; - } - if (obs._willBeUnregistered) { - return; - } - if (obs.mask & mask) { - if (obs.scope) { - p = p.then((lastReturnedValue) => { - state.lastReturnValue = lastReturnedValue; - return obs.callback.apply(obs.scope, [eventData, state]); - }); - } - else { - p = p.then((lastReturnedValue) => { - state.lastReturnValue = lastReturnedValue; - return obs.callback(eventData, state); - }); - } - if (obs.unregisterOnNextCall) { - this._deferUnregister(obs); - } - } - }); - // return the eventData - await p; - return eventData; -}; -//# sourceMappingURL=observable.extensions.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/sceneOptimizer.js - - - -/** - * Defines the root class used to create scene optimization to use with SceneOptimizer - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class SceneOptimization { - /** - * Gets a string describing the action executed by the current optimization - * @returns description string - */ - getDescription() { - return ""; - } - /** - * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization - * @param scene defines the current scene where to apply this optimization - * @param optimizer defines the current optimizer - * @returns true if everything that can be done was applied - */ - apply(scene, optimizer) { - return true; - } - /** - * Creates the SceneOptimization object - * @param priority defines the priority of this optimization (0 by default which means first in the list) - */ - constructor( - /** - * Defines the priority of this optimization (0 by default which means first in the list) - */ - priority = 0) { - this.priority = priority; - } -} -/** - * Defines an optimization used to reduce the size of render target textures - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class TextureOptimization extends (/* unused pure expression or super */ null && (SceneOptimization)) { - /** - * Gets a string describing the action executed by the current optimization - * @returns description string - */ - getDescription() { - return "Reducing render target texture size to " + this.maximumSize; - } - /** - * Creates the TextureOptimization object - * @param priority defines the priority of this optimization (0 by default which means first in the list) - * @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 - * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed. - */ - constructor( - /** - * Defines the priority of this optimization (0 by default which means first in the list) - */ - priority = 0, - /** - * 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 - */ - maximumSize = 1024, - /** - * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed. - */ - step = 0.5) { - super(priority); - this.priority = priority; - this.maximumSize = maximumSize; - this.step = step; - } - /** - * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization - * @param scene defines the current scene where to apply this optimization - * @param optimizer defines the current optimizer - * @returns true if everything that can be done was applied - */ - apply(scene, optimizer) { - let allDone = true; - for (let index = 0; index < scene.textures.length; index++) { - const texture = scene.textures[index]; - if (!texture.canRescale || texture.getContext) { - continue; - } - const currentSize = texture.getSize(); - const maxDimension = Math.max(currentSize.width, currentSize.height); - if (maxDimension > this.maximumSize) { - texture.scale(this.step); - allDone = false; - } - } - return allDone; - } -} -/** - * Defines an optimization used to increase or decrease the rendering resolution - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class HardwareScalingOptimization extends (/* unused pure expression or super */ null && (SceneOptimization)) { - /** - * Gets a string describing the action executed by the current optimization - * @returns description string - */ - getDescription() { - return "Setting hardware scaling level to " + this._currentScale; - } - /** - * Creates the HardwareScalingOptimization object - * @param priority defines the priority of this optimization (0 by default which means first in the list) - * @param maximumScale defines the maximum scale to use (2 by default) - * @param step defines the step to use between two passes (0.5 by default) - */ - constructor( - /** - * Defines the priority of this optimization (0 by default which means first in the list) - */ - priority = 0, - /** - * Defines the maximum scale to use (2 by default) - */ - maximumScale = 2, - /** - * Defines the step to use between two passes (0.5 by default) - */ - step = 0.25) { - super(priority); - this.priority = priority; - this.maximumScale = maximumScale; - this.step = step; - this._currentScale = -1; - this._directionOffset = 1; - } - /** - * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization - * @param scene defines the current scene where to apply this optimization - * @param optimizer defines the current optimizer - * @returns true if everything that can be done was applied - */ - apply(scene, optimizer) { - if (this._currentScale === -1) { - this._currentScale = scene.getEngine().getHardwareScalingLevel(); - if (this._currentScale > this.maximumScale) { - this._directionOffset = -1; - } - } - this._currentScale += this._directionOffset * this.step; - scene.getEngine().setHardwareScalingLevel(this._currentScale); - return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale; - } -} -/** - * Defines an optimization used to remove shadows - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class ShadowsOptimization extends (/* unused pure expression or super */ null && (SceneOptimization)) { - /** - * Gets a string describing the action executed by the current optimization - * @returns description string - */ - getDescription() { - return "Turning shadows on/off"; - } - /** - * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization - * @param scene defines the current scene where to apply this optimization - * @param optimizer defines the current optimizer - * @returns true if everything that can be done was applied - */ - apply(scene, optimizer) { - scene.shadowsEnabled = optimizer.isInImprovementMode; - return true; - } -} -/** - * Defines an optimization used to turn post-processes off - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class PostProcessesOptimization extends (/* unused pure expression or super */ null && (SceneOptimization)) { - /** - * Gets a string describing the action executed by the current optimization - * @returns description string - */ - getDescription() { - return "Turning post-processes on/off"; - } - /** - * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization - * @param scene defines the current scene where to apply this optimization - * @param optimizer defines the current optimizer - * @returns true if everything that can be done was applied - */ - apply(scene, optimizer) { - scene.postProcessesEnabled = optimizer.isInImprovementMode; - return true; - } -} -/** - * Defines an optimization used to turn lens flares off - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class LensFlaresOptimization extends (/* unused pure expression or super */ null && (SceneOptimization)) { - /** - * Gets a string describing the action executed by the current optimization - * @returns description string - */ - getDescription() { - return "Turning lens flares on/off"; - } - /** - * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization - * @param scene defines the current scene where to apply this optimization - * @param optimizer defines the current optimizer - * @returns true if everything that can be done was applied - */ - apply(scene, optimizer) { - scene.lensFlaresEnabled = optimizer.isInImprovementMode; - return true; - } -} -/** - * Defines an optimization based on user defined callback. - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class CustomOptimization extends (/* unused pure expression or super */ null && (SceneOptimization)) { - /** - * Gets a string describing the action executed by the current optimization - * @returns description string - */ - getDescription() { - if (this.onGetDescription) { - return this.onGetDescription(); - } - return "Running user defined callback"; - } - /** - * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization - * @param scene defines the current scene where to apply this optimization - * @param optimizer defines the current optimizer - * @returns true if everything that can be done was applied - */ - apply(scene, optimizer) { - if (this.onApply) { - return this.onApply(scene, optimizer); - } - return true; - } -} -/** - * Defines an optimization used to turn particles off - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class ParticlesOptimization extends (/* unused pure expression or super */ null && (SceneOptimization)) { - /** - * Gets a string describing the action executed by the current optimization - * @returns description string - */ - getDescription() { - return "Turning particles on/off"; - } - /** - * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization - * @param scene defines the current scene where to apply this optimization - * @param optimizer defines the current optimizer - * @returns true if everything that can be done was applied - */ - apply(scene, optimizer) { - scene.particlesEnabled = optimizer.isInImprovementMode; - return true; - } -} -/** - * Defines an optimization used to turn render targets off - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class RenderTargetsOptimization extends (/* unused pure expression or super */ null && (SceneOptimization)) { - /** - * Gets a string describing the action executed by the current optimization - * @returns description string - */ - getDescription() { - return "Turning render targets off"; - } - /** - * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization - * @param scene defines the current scene where to apply this optimization - * @param optimizer defines the current optimizer - * @returns true if everything that can be done was applied - */ - apply(scene, optimizer) { - scene.renderTargetsEnabled = optimizer.isInImprovementMode; - return true; - } -} -/** - * Defines an optimization used to merge meshes with compatible materials - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class MergeMeshesOptimization extends SceneOptimization { - constructor() { - super(...arguments); - this._canBeMerged = (abstractMesh) => { - if (!(abstractMesh instanceof mesh_Mesh)) { - return false; - } - const mesh = abstractMesh; - if (mesh.isDisposed()) { - return false; - } - if (!mesh.isVisible || !mesh.isEnabled()) { - return false; - } - if (mesh.instances.length > 0) { - return false; - } - if (mesh.skeleton || mesh.hasLODLevels) { - return false; - } - if (mesh.getTotalVertices() === 0) { - return false; - } - return true; - }; - } - /** - * Gets or sets a boolean which defines if optimization octree has to be updated - */ - static get UpdateSelectionTree() { - return MergeMeshesOptimization._UpdateSelectionTree; - } - /** - * Gets or sets a boolean which defines if optimization octree has to be updated - */ - static set UpdateSelectionTree(value) { - MergeMeshesOptimization._UpdateSelectionTree = value; - } - /** - * Gets a string describing the action executed by the current optimization - * @returns description string - */ - getDescription() { - return "Merging similar meshes together"; - } - /** - * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization - * @param scene defines the current scene where to apply this optimization - * @param optimizer defines the current optimizer - * @param updateSelectionTree defines that the selection octree has to be updated (false by default) - * @returns true if everything that can be done was applied - */ - apply(scene, optimizer, updateSelectionTree) { - const globalPool = scene.meshes.slice(0); - let globalLength = globalPool.length; - for (let index = 0; index < globalLength; index++) { - const currentPool = new Array(); - const current = globalPool[index]; - // Checks - if (!this._canBeMerged(current)) { - continue; - } - currentPool.push(current); - // Find compatible meshes - for (let subIndex = index + 1; subIndex < globalLength; subIndex++) { - const otherMesh = globalPool[subIndex]; - if (!this._canBeMerged(otherMesh)) { - continue; - } - if (otherMesh.material !== current.material) { - continue; - } - if (otherMesh.checkCollisions !== current.checkCollisions) { - continue; - } - currentPool.push(otherMesh); - globalLength--; - globalPool.splice(subIndex, 1); - subIndex--; - } - if (currentPool.length < 2) { - continue; - } - // Merge meshes - mesh_Mesh.MergeMeshes(currentPool, undefined, true); - } - // Call the octree system optimization if it is defined. - const sceneAsAny = scene; - if (sceneAsAny.createOrUpdateSelectionOctree) { - if (updateSelectionTree != undefined) { - if (updateSelectionTree) { - sceneAsAny.createOrUpdateSelectionOctree(); - } - } - else if (MergeMeshesOptimization.UpdateSelectionTree) { - sceneAsAny.createOrUpdateSelectionOctree(); - } - } - return true; - } -} -MergeMeshesOptimization._UpdateSelectionTree = false; -/** - * Defines a list of options used by SceneOptimizer - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class SceneOptimizerOptions { - /** - * Creates a new list of options used by SceneOptimizer - * @param targetFrameRate defines the target frame rate to reach (60 by default) - * @param trackerDuration defines the interval between two checks (2000ms by default) - */ - constructor( - /** - * Defines the target frame rate to reach (60 by default) - */ - targetFrameRate = 60, - /** - * Defines the interval between two checks (2000ms by default) - */ - trackerDuration = 2000) { - this.targetFrameRate = targetFrameRate; - this.trackerDuration = trackerDuration; - /** - * Gets the list of optimizations to apply - */ - this.optimizations = new Array(); - } - /** - * Add a new optimization - * @param optimization defines the SceneOptimization to add to the list of active optimizations - * @returns the current SceneOptimizerOptions - */ - addOptimization(optimization) { - this.optimizations.push(optimization); - return this; - } - /** - * Add a new custom optimization - * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied) - * @param onGetDescription defines the callback called to get the description attached with the optimization. - * @param priority defines the priority of this optimization (0 by default which means first in the list) - * @returns the current SceneOptimizerOptions - */ - addCustomOptimization(onApply, onGetDescription, priority = 0) { - const optimization = new CustomOptimization(priority); - optimization.onApply = onApply; - optimization.onGetDescription = onGetDescription; - this.optimizations.push(optimization); - return this; - } - /** - * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene - * @param targetFrameRate defines the target frame rate (60 by default) - * @returns a SceneOptimizerOptions object - */ - static LowDegradationAllowed(targetFrameRate) { - const result = new SceneOptimizerOptions(targetFrameRate); - let priority = 0; - result.addOptimization(new MergeMeshesOptimization(priority)); - result.addOptimization(new ShadowsOptimization(priority)); - result.addOptimization(new LensFlaresOptimization(priority)); - // Next priority - priority++; - result.addOptimization(new PostProcessesOptimization(priority)); - result.addOptimization(new ParticlesOptimization(priority)); - // Next priority - priority++; - result.addOptimization(new TextureOptimization(priority, 1024)); - return result; - } - /** - * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual - * @param targetFrameRate defines the target frame rate (60 by default) - * @returns a SceneOptimizerOptions object - */ - static ModerateDegradationAllowed(targetFrameRate) { - const result = new SceneOptimizerOptions(targetFrameRate); - let priority = 0; - result.addOptimization(new MergeMeshesOptimization(priority)); - result.addOptimization(new ShadowsOptimization(priority)); - result.addOptimization(new LensFlaresOptimization(priority)); - // Next priority - priority++; - result.addOptimization(new PostProcessesOptimization(priority)); - result.addOptimization(new ParticlesOptimization(priority)); - // Next priority - priority++; - result.addOptimization(new TextureOptimization(priority, 512)); - // Next priority - priority++; - result.addOptimization(new RenderTargetsOptimization(priority)); - // Next priority - priority++; - result.addOptimization(new HardwareScalingOptimization(priority, 2)); - return result; - } - /** - * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual - * @param targetFrameRate defines the target frame rate (60 by default) - * @returns a SceneOptimizerOptions object - */ - static HighDegradationAllowed(targetFrameRate) { - const result = new SceneOptimizerOptions(targetFrameRate); - let priority = 0; - result.addOptimization(new MergeMeshesOptimization(priority)); - result.addOptimization(new ShadowsOptimization(priority)); - result.addOptimization(new LensFlaresOptimization(priority)); - // Next priority - priority++; - result.addOptimization(new PostProcessesOptimization(priority)); - result.addOptimization(new ParticlesOptimization(priority)); - // Next priority - priority++; - result.addOptimization(new TextureOptimization(priority, 256)); - // Next priority - priority++; - result.addOptimization(new RenderTargetsOptimization(priority)); - // Next priority - priority++; - result.addOptimization(new HardwareScalingOptimization(priority, 4)); - return result; - } -} -/** - * Class used to run optimizations in order to reach a target frame rate - * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer - */ -class SceneOptimizer { - /** - * Gets or sets a boolean indicating if the optimizer is in improvement mode - */ - get isInImprovementMode() { - return this._improvementMode; - } - set isInImprovementMode(value) { - this._improvementMode = value; - } - /** - * Gets the current priority level (0 at start) - */ - get currentPriorityLevel() { - return this._currentPriorityLevel; - } - /** - * Gets the current frame rate checked by the SceneOptimizer - */ - get currentFrameRate() { - return this._currentFrameRate; - } - /** - * Gets or sets the current target frame rate (60 by default) - */ - get targetFrameRate() { - return this._targetFrameRate; - } - /** - * Gets or sets the current target frame rate (60 by default) - */ - set targetFrameRate(value) { - this._targetFrameRate = value; - } - /** - * Gets or sets the current interval between two checks (every 2000ms by default) - */ - get trackerDuration() { - return this._trackerDuration; - } - /** - * Gets or sets the current interval between two checks (every 2000ms by default) - */ - set trackerDuration(value) { - this._trackerDuration = value; - } - /** - * Gets the list of active optimizations - */ - get optimizations() { - return this._options.optimizations; - } - /** - * Creates a new SceneOptimizer - * @param scene defines the scene to work on - * @param options defines the options to use with the SceneOptimizer - * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default) - * @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) - */ - constructor(scene, options, autoGeneratePriorities = true, improvementMode = false) { - this._isRunning = false; - this._currentPriorityLevel = 0; - this._targetFrameRate = 60; - this._trackerDuration = 2000; - this._currentFrameRate = 0; - this._improvementMode = false; - /** - * Defines an observable called when the optimizer reaches the target frame rate - */ - this.onSuccessObservable = new Observable(); - /** - * Defines an observable called when the optimizer enables an optimization - */ - this.onNewOptimizationAppliedObservable = new Observable(); - /** - * Defines an observable called when the optimizer is not able to reach the target frame rate - */ - this.onFailureObservable = new Observable(); - if (!options) { - this._options = new SceneOptimizerOptions(); - } - else { - this._options = options; - } - if (this._options.targetFrameRate) { - this._targetFrameRate = this._options.targetFrameRate; - } - if (this._options.trackerDuration) { - this._trackerDuration = this._options.trackerDuration; - } - if (autoGeneratePriorities) { - let priority = 0; - for (const optim of this._options.optimizations) { - optim.priority = priority++; - } - } - this._improvementMode = improvementMode; - this._scene = scene || EngineStore.LastCreatedScene; - this._sceneDisposeObserver = this._scene.onDisposeObservable.add(() => { - this._sceneDisposeObserver = null; - this.dispose(); - }); - } - /** - * Stops the current optimizer - */ - stop() { - this._isRunning = false; - } - /** - * Reset the optimizer to initial step (current priority level = 0) - */ - reset() { - this._currentPriorityLevel = 0; - } - /** - * Start the optimizer. By default it will try to reach a specific framerate - * but if the optimizer is set with improvementMode === true then it will run all optimization while frame rate is above the target frame rate - */ - start() { - if (this._isRunning) { - return; - } - this._isRunning = true; - // Let's wait for the scene to be ready before running our check - this._scene.executeWhenReady(() => { - setTimeout(() => { - this._checkCurrentState(); - }, this._trackerDuration); - }); - } - _checkCurrentState() { - if (!this._isRunning) { - return; - } - const scene = this._scene; - const options = this._options; - this._currentFrameRate = Math.round(scene.getEngine().getFps()); - if ((this._improvementMode && this._currentFrameRate <= this._targetFrameRate) || (!this._improvementMode && this._currentFrameRate >= this._targetFrameRate)) { - this._isRunning = false; - this.onSuccessObservable.notifyObservers(this); - return; - } - // Apply current level of optimizations - let allDone = true; - let noOptimizationApplied = true; - for (let index = 0; index < options.optimizations.length; index++) { - const optimization = options.optimizations[index]; - if (optimization.priority === this._currentPriorityLevel) { - noOptimizationApplied = false; - allDone = allDone && optimization.apply(scene, this); - this.onNewOptimizationAppliedObservable.notifyObservers(optimization); - } - } - // If no optimization was applied, this is a failure :( - if (noOptimizationApplied) { - this._isRunning = false; - this.onFailureObservable.notifyObservers(this); - return; - } - // If all optimizations were done, move to next level - if (allDone) { - this._currentPriorityLevel++; - } - // Let's the system running for a specific amount of time before checking FPS - scene.executeWhenReady(() => { - setTimeout(() => { - this._checkCurrentState(); - }, this._trackerDuration); - }); - } - /** - * Release all resources - */ - dispose() { - this.stop(); - this.onSuccessObservable.clear(); - this.onFailureObservable.clear(); - this.onNewOptimizationAppliedObservable.clear(); - if (this._sceneDisposeObserver) { - this._scene.onDisposeObservable.remove(this._sceneDisposeObserver); - } - } - /** - * Helper function to create a SceneOptimizer with one single line of code - * @param scene defines the scene to work on - * @param options defines the options to use with the SceneOptimizer - * @param onSuccess defines a callback to call on success - * @param onFailure defines a callback to call on failure - * @returns the new SceneOptimizer object - */ - static OptimizeAsync(scene, options, onSuccess, onFailure) { - const optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false); - if (onSuccess) { - optimizer.onSuccessObservable.add(() => { - onSuccess(); - }); - } - if (onFailure) { - optimizer.onFailureObservable.add(() => { - onFailure(); - }); - } - optimizer.start(); - return optimizer; - } -} -//# sourceMappingURL=sceneOptimizer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/sceneSerializer.js - - - - - -let serializedGeometries = []; -const SerializeGeometry = (geometry, serializationGeometries) => { - if (geometry.doNotSerialize) { - return; - } - serializationGeometries.vertexData.push(geometry.serializeVerticeData()); - serializedGeometries[geometry.id] = true; -}; -const SerializeMesh = (mesh, serializationScene) => { - const serializationObject = {}; - // Geometry - const geometry = mesh._geometry; - if (geometry) { - if (!mesh.getScene().getGeometryById(geometry.id)) { - // 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 - SerializeGeometry(geometry, serializationScene.geometries); - } - } - // Custom - if (mesh.serialize) { - mesh.serialize(serializationObject); - } - return serializationObject; -}; -const FinalizeSingleNode = (node, serializationObject) => { - if (node._isMesh) { - const mesh = node; - //only works if the mesh is already loaded - if (mesh.delayLoadState === 1 || mesh.delayLoadState === 0) { - const serializeMaterial = (material) => { - serializationObject.materials = serializationObject.materials || []; - if (mesh.material && !serializationObject.materials.some((mat) => mat.id === mesh.material.id)) { - serializationObject.materials.push(material.serialize()); - } - }; - //serialize material - if (mesh.material && !mesh.material.doNotSerialize) { - if (mesh.material instanceof multiMaterial_MultiMaterial) { - serializationObject.multiMaterials = serializationObject.multiMaterials || []; - if (!serializationObject.multiMaterials.some((mat) => mat.id === mesh.material.id)) { - serializationObject.multiMaterials.push(mesh.material.serialize()); - for (const submaterial of mesh.material.subMaterials) { - if (submaterial) { - serializeMaterial(submaterial); - } - } - } - } - else { - serializeMaterial(mesh.material); - } - } - else if (!mesh.material) { - serializeMaterial(mesh.getScene().defaultMaterial); - } - //serialize geometry - const geometry = mesh._geometry; - if (geometry) { - if (!serializationObject.geometries) { - serializationObject.geometries = {}; - serializationObject.geometries.boxes = []; - serializationObject.geometries.spheres = []; - serializationObject.geometries.cylinders = []; - serializationObject.geometries.toruses = []; - serializationObject.geometries.grounds = []; - serializationObject.geometries.planes = []; - serializationObject.geometries.torusKnots = []; - serializationObject.geometries.vertexData = []; - } - SerializeGeometry(geometry, serializationObject.geometries); - } - // Skeletons - if (mesh.skeleton && !mesh.skeleton.doNotSerialize) { - serializationObject.skeletons = serializationObject.skeletons || []; - serializationObject.skeletons.push(mesh.skeleton.serialize()); - } - //serialize the actual mesh - serializationObject.meshes = serializationObject.meshes || []; - serializationObject.meshes.push(SerializeMesh(mesh, serializationObject)); - } - } - else if (node.getClassName() === "TransformNode") { - const transformNode = node; - serializationObject.transformNodes.push(transformNode.serialize()); - } - else if (node.getClassName().indexOf("Camera") !== -1) { - const camera = node; - serializationObject.cameras.push(camera.serialize()); - } - else if (node.getClassName().indexOf("Light") !== -1) { - const light = node; - serializationObject.lights.push(light.serialize()); - } -}; -/** - * Class used to serialize a scene into a string - */ -class sceneSerializer_SceneSerializer { - /** - * Clear cache used by a previous serialization - */ - static ClearCache() { - serializedGeometries = []; - } - /** - * Serialize a scene into a JSON compatible object - * Note that if the current engine does not support synchronous texture reading (like WebGPU), you should use SerializeAsync instead - * as else you may not retrieve the proper base64 encoded texture data (when using the Texture.ForceSerializeBuffers flag) - * @param scene defines the scene to serialize - * @returns a JSON compatible object - */ - static Serialize(scene) { - return sceneSerializer_SceneSerializer._Serialize(scene); - } - static _Serialize(scene, checkSyncReadSupported = true) { - const serializationObject = {}; - if (checkSyncReadSupported && !scene.getEngine()._features.supportSyncTextureRead && texture_Texture.ForceSerializeBuffers) { - console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."); - } - sceneSerializer_SceneSerializer.ClearCache(); - // Scene - serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading; - serializationObject.autoClear = scene.autoClear; - serializationObject.clearColor = scene.clearColor.asArray(); - serializationObject.ambientColor = scene.ambientColor.asArray(); - serializationObject.gravity = scene.gravity.asArray(); - serializationObject.collisionsEnabled = scene.collisionsEnabled; - serializationObject.useRightHandedSystem = scene.useRightHandedSystem; - // Fog - if (scene.fogMode && scene.fogMode !== 0) { - serializationObject.fogMode = scene.fogMode; - serializationObject.fogColor = scene.fogColor.asArray(); - serializationObject.fogStart = scene.fogStart; - serializationObject.fogEnd = scene.fogEnd; - serializationObject.fogDensity = scene.fogDensity; - } - //Physics - if (scene.isPhysicsEnabled && scene.isPhysicsEnabled()) { - const physicEngine = scene.getPhysicsEngine(); - if (physicEngine) { - serializationObject.physicsEnabled = true; - serializationObject.physicsGravity = physicEngine.gravity.asArray(); - serializationObject.physicsEngine = physicEngine.getPhysicsPluginName(); - } - } - // Metadata - if (scene.metadata) { - serializationObject.metadata = scene.metadata; - } - // Morph targets - serializationObject.morphTargetManagers = []; - for (const abstractMesh of scene.meshes) { - const manager = abstractMesh.morphTargetManager; - if (manager) { - serializationObject.morphTargetManagers.push(manager.serialize()); - } - } - // Lights - serializationObject.lights = []; - let index; - let light; - for (index = 0; index < scene.lights.length; index++) { - light = scene.lights[index]; - if (!light.doNotSerialize) { - serializationObject.lights.push(light.serialize()); - } - } - // Cameras - serializationObject.cameras = []; - for (index = 0; index < scene.cameras.length; index++) { - const camera = scene.cameras[index]; - if (!camera.doNotSerialize) { - serializationObject.cameras.push(camera.serialize()); - } - } - if (scene.activeCamera) { - serializationObject.activeCameraID = scene.activeCamera.id; - } - // Animations - decorators_SerializationHelper.AppendSerializedAnimations(scene, serializationObject); - // Animation Groups - if (scene.animationGroups && scene.animationGroups.length > 0) { - serializationObject.animationGroups = []; - for (let animationGroupIndex = 0; animationGroupIndex < scene.animationGroups.length; animationGroupIndex++) { - const animationGroup = scene.animationGroups[animationGroupIndex]; - serializationObject.animationGroups.push(animationGroup.serialize()); - } - } - // Reflection probes - if (scene.reflectionProbes && scene.reflectionProbes.length > 0) { - serializationObject.reflectionProbes = []; - for (index = 0; index < scene.reflectionProbes.length; index++) { - const reflectionProbe = scene.reflectionProbes[index]; - serializationObject.reflectionProbes.push(reflectionProbe.serialize()); - } - } - // Materials - serializationObject.materials = []; - serializationObject.multiMaterials = []; - let material; - for (index = 0; index < scene.materials.length; index++) { - material = scene.materials[index]; - if (!material.doNotSerialize) { - serializationObject.materials.push(material.serialize()); - } - } - // MultiMaterials - serializationObject.multiMaterials = []; - for (index = 0; index < scene.multiMaterials.length; index++) { - const multiMaterial = scene.multiMaterials[index]; - serializationObject.multiMaterials.push(multiMaterial.serialize()); - } - // Environment texture - if (scene.environmentTexture) { - if (scene.environmentTexture._files) { - serializationObject.environmentTexture = scene.environmentTexture.serialize(); - } - else { - serializationObject.environmentTexture = scene.environmentTexture.name; - serializationObject.environmentTextureRotationY = scene.environmentTexture.rotationY; - } - } - // Environment Intensity - serializationObject.environmentIntensity = scene.environmentIntensity; - // Skeletons - serializationObject.skeletons = []; - for (index = 0; index < scene.skeletons.length; index++) { - const skeleton = scene.skeletons[index]; - if (!skeleton.doNotSerialize) { - serializationObject.skeletons.push(skeleton.serialize()); - } - } - // Transform nodes - serializationObject.transformNodes = []; - for (index = 0; index < scene.transformNodes.length; index++) { - if (!scene.transformNodes[index].doNotSerialize) { - serializationObject.transformNodes.push(scene.transformNodes[index].serialize()); - } - } - // Geometries - serializationObject.geometries = {}; - serializationObject.geometries.boxes = []; - serializationObject.geometries.spheres = []; - serializationObject.geometries.cylinders = []; - serializationObject.geometries.toruses = []; - serializationObject.geometries.grounds = []; - serializationObject.geometries.planes = []; - serializationObject.geometries.torusKnots = []; - serializationObject.geometries.vertexData = []; - serializedGeometries = []; - const geometries = scene.getGeometries(); - for (index = 0; index < geometries.length; index++) { - const geometry = geometries[index]; - if (geometry.isReady()) { - SerializeGeometry(geometry, serializationObject.geometries); - } - } - // Meshes - serializationObject.meshes = []; - for (index = 0; index < scene.meshes.length; index++) { - const abstractMesh = scene.meshes[index]; - if (abstractMesh instanceof mesh_Mesh) { - const mesh = abstractMesh; - if (!mesh.doNotSerialize) { - if (mesh.delayLoadState === 1 || mesh.delayLoadState === 0) { - serializationObject.meshes.push(SerializeMesh(mesh, serializationObject)); - } - } - } - } - // Particles Systems - serializationObject.particleSystems = []; - for (index = 0; index < scene.particleSystems.length; index++) { - serializationObject.particleSystems.push(scene.particleSystems[index].serialize(false)); - } - // Post processes - serializationObject.postProcesses = []; - for (index = 0; index < scene.postProcesses.length; index++) { - serializationObject.postProcesses.push(scene.postProcesses[index].serialize()); - } - // Action Manager - if (scene.actionManager) { - serializationObject.actions = scene.actionManager.serialize("scene"); - } - // Components - for (const component of scene._serializableComponents) { - component.serialize(serializationObject); - } - return serializationObject; - } - /** - * Serialize a scene into a JSON compatible object - * @param scene defines the scene to serialize - * @returns a JSON promise compatible object - */ - static SerializeAsync(scene) { - const serializationObject = sceneSerializer_SceneSerializer._Serialize(scene, false); - const promises = []; - this._CollectPromises(serializationObject, promises); - return Promise.all(promises).then(() => serializationObject); - } - static _CollectPromises(obj, promises) { - if (Array.isArray(obj)) { - for (let i = 0; i < obj.length; ++i) { - const o = obj[i]; - if (o instanceof Promise) { - promises.push(o.then((res) => (obj[i] = res))); - } - else if (o instanceof Object || Array.isArray(o)) { - this._CollectPromises(o, promises); - } - } - } - else if (obj instanceof Object) { - for (const name in obj) { - if (Object.prototype.hasOwnProperty.call(obj, name)) { - const o = obj[name]; - if (o instanceof Promise) { - promises.push(o.then((res) => (obj[name] = res))); - } - else if (o instanceof Object || Array.isArray(o)) { - this._CollectPromises(o, promises); - } - } - } - } - } - /** - * Serialize a mesh into a JSON compatible object - * @param toSerialize defines the mesh to serialize - * @param withParents defines if parents must be serialized as well - * @param withChildren defines if children must be serialized as well - * @returns a JSON compatible object - */ - static SerializeMesh(toSerialize /* Mesh || Mesh[] */, withParents = false, withChildren = false) { - const serializationObject = {}; - serializationObject.meshes = []; - serializationObject.transformNodes = []; - serializationObject.cameras = []; - serializationObject.lights = []; - sceneSerializer_SceneSerializer.ClearCache(); - toSerialize = toSerialize instanceof Array ? toSerialize : [toSerialize]; - if (withParents || withChildren) { - //deliberate for loop! not for each, appended should be processed as well. - for (let i = 0; i < toSerialize.length; ++i) { - if (withChildren) { - toSerialize[i].getDescendants().forEach((node) => { - if (toSerialize.indexOf(node) < 0 && !node.doNotSerialize) { - toSerialize.push(node); - } - }); - } - //make sure the array doesn't contain the object already - if (withParents && toSerialize[i].parent && toSerialize.indexOf(toSerialize[i].parent) < 0 && !toSerialize[i].parent.doNotSerialize) { - toSerialize.push(toSerialize[i].parent); - } - } - } - toSerialize.forEach((mesh) => { - FinalizeSingleNode(mesh, serializationObject); - }); - return serializationObject; - } -} -//# sourceMappingURL=sceneSerializer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/videoRecorder.js - -/** - * This can help with recording videos from BabylonJS. - * This is based on the available WebRTC functionalities of the browser. - * - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToVideo - */ -class VideoRecorder { - /** - * Returns whether or not the VideoRecorder is available in your browser. - * @param engine Defines the Babylon Engine. - * @returns true if supported otherwise false. - */ - static IsSupported(engine) { - const canvas = engine.getRenderingCanvas(); - return !!canvas && typeof canvas.captureStream === "function"; - } - /** - * True when a recording is already in progress. - */ - get isRecording() { - return !!this._canvas && this._canvas.isRecording; - } - /** - * Create a new VideoCapture object which can help converting what you see in Babylon to a video file. - * @param engine Defines the BabylonJS Engine you wish to record. - * @param options Defines options that can be used to customize the capture. - */ - constructor(engine, options = {}) { - if (!VideoRecorder.IsSupported(engine)) { - throw "Your browser does not support recording so far."; - } - const canvas = engine.getRenderingCanvas(); - if (!canvas) { - throw "The babylon engine must have a canvas to be recorded"; - } - this._canvas = canvas; - this._canvas.isRecording = false; - this._options = Object.assign(Object.assign({}, VideoRecorder._DefaultOptions), options); - const stream = this._canvas.captureStream(this._options.fps); - if (this._options.audioTracks) { - for (const track of this._options.audioTracks) { - stream.addTrack(track); - } - } - this._mediaRecorder = new MediaRecorder(stream, { 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); - } - /** - * Stops the current recording before the default capture timeout passed in the startRecording function. - */ - stopRecording() { - if (!this._canvas || !this._mediaRecorder) { - return; - } - if (!this.isRecording) { - return; - } - this._canvas.isRecording = false; - this._mediaRecorder.stop(); - } - /** - * Starts recording the canvas for a max duration specified in parameters. - * @param fileName Defines the name of the file to be downloaded when the recording stop. - * If null no automatic download will start and you can rely on the promise to get the data back. - * @param maxDuration Defines the maximum recording time in seconds. - * It defaults to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually. - * @returns A promise callback at the end of the recording with the video data in Blob. - */ - startRecording(fileName = "babylonjs.webm", maxDuration = 7) { - if (!this._canvas || !this._mediaRecorder) { - throw "Recorder has already been disposed"; - } - if (this.isRecording) { - throw "Recording already in progress"; - } - if (maxDuration > 0) { - setTimeout(() => { - this.stopRecording(); - }, maxDuration * 1000); - } - this._fileName = fileName; - this._recordedChunks = []; - this._resolve = null; - this._reject = null; - this._canvas.isRecording = true; - this._mediaRecorder.start(this._options.recordChunckSize); - return new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - }); - } - /** - * Releases internal resources used during the recording. - */ - dispose() { - this._canvas = null; - this._mediaRecorder = null; - this._recordedChunks = []; - this._fileName = null; - this._resolve = null; - this._reject = null; - } - _handleDataAvailable(event) { - if (event.data.size > 0) { - this._recordedChunks.push(event.data); - } - } - _handleError(event) { - this.stopRecording(); - if (this._reject) { - this._reject(event.error); - } - else { - throw new event.error(); - } - } - _handleStop() { - this.stopRecording(); - const superBuffer = new Blob(this._recordedChunks); - if (this._resolve) { - this._resolve(superBuffer); - } - window.URL.createObjectURL(superBuffer); - if (this._fileName) { - tools_Tools.Download(superBuffer, this._fileName); - } - } -} -VideoRecorder._DefaultOptions = { - mimeType: "video/webm", - fps: 25, - recordChunckSize: 3000, -}; -//# sourceMappingURL=videoRecorder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/screenshotTools.js - - - - - - - - -let screenshotCanvas = null; -/** - * Captures a screenshot of the current rendering - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine defines the rendering engine - * @param camera defines the source camera - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param successCallback defines the callback receives a single parameter which contains the - * screenshot as a string of base64-encoded characters. This string can be assigned to the - * src parameter of an <img> to display it - * @param mimeType defines the MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @param forceDownload force the system to download the image even if a successCallback is provided - * @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. - */ -function CreateScreenshot(engine, camera, size, successCallback, mimeType = "image/png", forceDownload = false, quality) { - const { height, width } = _GetScreenshotSize(engine, camera, size); - if (!(height && width)) { - logger_Logger.Error("Invalid 'size' parameter !"); - return; - } - if (!screenshotCanvas) { - screenshotCanvas = document.createElement("canvas"); - } - screenshotCanvas.width = width; - screenshotCanvas.height = height; - const renderContext = screenshotCanvas.getContext("2d"); - const ratio = engine.getRenderWidth() / engine.getRenderHeight(); - let newWidth = width; - let newHeight = newWidth / ratio; - if (newHeight > height) { - newHeight = height; - newWidth = newHeight * ratio; - } - const offsetX = Math.max(0, width - newWidth) / 2; - const offsetY = Math.max(0, height - newHeight) / 2; - const scene = camera.getScene(); - if (scene.activeCamera !== camera) { - CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => { - if (forceDownload) { - const blob = new Blob([data]); - tools_Tools.DownloadBlob(blob); - if (successCallback) { - successCallback(""); - } - } - else if (successCallback) { - successCallback(data); - } - }, mimeType, 1.0, engine.getCreationOptions().antialias, undefined, undefined, undefined, undefined, quality); - } - else { - engine.onEndFrameObservable.addOnce(() => { - const renderingCanvas = engine.getRenderingCanvas(); - if (renderContext && renderingCanvas) { - renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight); - } - if (screenshotCanvas) { - if (forceDownload) { - tools_Tools.EncodeScreenshotCanvasData(screenshotCanvas, undefined, mimeType, undefined, quality); - if (successCallback) { - successCallback(""); - } - } - else { - tools_Tools.EncodeScreenshotCanvasData(screenshotCanvas, successCallback, mimeType, undefined, quality); - } - } - }); - } -} -/** - * Captures a screenshot of the current rendering - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine defines the rendering engine - * @param camera defines the source camera - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param mimeType defines the MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @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. - * @returns screenshot as a string of base64-encoded characters. This string can be assigned - * to the src parameter of an <img> to display it - */ -function CreateScreenshotAsync(engine, camera, size, mimeType = "image/png", quality) { - return new Promise((resolve, reject) => { - CreateScreenshot(engine, camera, size, (data) => { - if (typeof data !== "undefined") { - resolve(data); - } - else { - reject(new Error("Data is undefined")); - } - }, mimeType, undefined, quality); - }); -} -/** - * 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) - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine defines the rendering engine - * @param camera defines the source camera - * @param width defines the expected width - * @param height defines the expected height - * @param mimeType defines the MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @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. - * @returns screenshot as a string of base64-encoded characters. This string can be assigned - * to the src parameter of an <img> to display it - */ -function CreateScreenshotWithResizeAsync(engine, camera, width, height, mimeType = "image/png", quality) { - return new Promise((resolve) => { - CreateScreenshot(engine, camera, { width: width, height: height }, () => { - resolve(); - }, mimeType, true, quality); - }); -} -/** - * Generates an image screenshot from the specified camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine The engine to use for rendering - * @param camera The camera to use for rendering - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height, finalWidth, finalHeight. If a single number is passed, - * it will be used for both width and height, as well as finalWidth, finalHeight. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param successCallback The callback receives a single parameter which contains the - * screenshot as a string of base64-encoded characters. This string can be assigned to the - * src parameter of an <img> to display it - * @param mimeType The MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @param samples Texture samples (default: 1) - * @param antialiasing Whether antialiasing should be turned on or not (default: false) - * @param fileName A name for for the downloaded file. - * @param renderSprites Whether the sprites should be rendered or not (default: false) - * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) - * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true) - * @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. - */ -function CreateScreenshotUsingRenderTarget(engine, camera, size, successCallback, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) { - const { height, width, finalWidth, finalHeight } = _GetScreenshotSize(engine, camera, size); - const targetTextureSize = { width, height }; - if (!(height && width)) { - logger_Logger.Error("Invalid 'size' parameter !"); - return; - } - const originalSize = { width: engine.getRenderWidth(), height: engine.getRenderHeight() }; - 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 - const scene = camera.getScene(); - // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method) - const texture = new renderTargetTexture_RenderTargetTexture("screenShot", targetTextureSize, scene, false, false, 0, false, texture_Texture.BILINEAR_SAMPLINGMODE, undefined, enableStencilBuffer, undefined, undefined, undefined, samples); - texture.renderList = scene.meshes.slice(); - texture.samples = samples; - texture.renderSprites = renderSprites; - texture.activeCamera = camera; - texture.forceLayerMaskCheck = useLayerMask; - const renderToTexture = () => { - engine.onEndFrameObservable.addOnce(() => { - if (finalWidth === width && finalHeight === height) { - texture.readPixels(undefined, undefined, undefined, false).then((data) => { - DumpTools.DumpData(width, height, data, successCallback, mimeType, fileName, true, undefined, quality); - texture.dispose(); - }); - } - else { - ApplyPostProcess("pass", texture.getInternalTexture(), scene, undefined, undefined, undefined, finalWidth, finalHeight).then((texture) => { - engine._readTexturePixels(texture, finalWidth, finalHeight, -1, 0, null, true, false, 0, 0).then((data) => { - DumpTools.DumpData(finalWidth, finalHeight, data, successCallback, mimeType, fileName, true, undefined, quality); - texture.dispose(); - }); - }); - } - }); - // render the RTT - scene.incrementRenderId(); - scene.resetCachedMaterial(); - texture.render(true); - // re-render the scene after the camera has been reset to the original camera to avoid a flicker that could occur - // 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) - scene.incrementRenderId(); - scene.resetCachedMaterial(); - engine.setSize(originalSize.width, originalSize.height); - camera.getProjectionMatrix(true); // Force cache refresh; - scene.render(); - }; - if (antialiasing) { - const fxaaPostProcess = new FxaaPostProcess("antialiasing", 1.0, scene.activeCamera); - texture.addPostProcess(fxaaPostProcess); - // Async Shader Compilation can lead to none ready effects in synchronous code - if (!fxaaPostProcess.getEffect().isReady()) { - fxaaPostProcess.getEffect().onCompiled = () => { - renderToTexture(); - }; - } - // The effect is ready we can render - else { - renderToTexture(); - } - } - else { - // No need to wait for extra resources to be ready - renderToTexture(); - } -} -/** - * Generates an image screenshot from the specified camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine The engine to use for rendering - * @param camera The camera to use for rendering - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param mimeType The MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @param samples Texture samples (default: 1) - * @param antialiasing Whether antialiasing should be turned on or not (default: false) - * @param fileName A name for for the downloaded file. - * @param renderSprites Whether the sprites should be rendered or not (default: false) - * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) - * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true) - * @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. - * @returns screenshot as a string of base64-encoded characters. This string can be assigned - * to the src parameter of an <img> to display it - */ -function CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) { - return new Promise((resolve, reject) => { - CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => { - if (typeof data !== "undefined") { - resolve(data); - } - else { - reject(new Error("Data is undefined")); - } - }, mimeType, samples, antialiasing, fileName, renderSprites, enableStencilBuffer, useLayerMask, quality); - }); -} -/** - * Gets height and width for screenshot size - * @param engine - * @param camera - * @param size - * @private - */ -function _GetScreenshotSize(engine, camera, size) { - let height = 0; - let width = 0; - let finalWidth = 0; - let finalHeight = 0; - //If a size value defined as object - if (typeof size === "object") { - const precision = size.precision - ? Math.abs(size.precision) // prevent GL_INVALID_VALUE : glViewport: negative width/height - : 1; - //If a width and height values is specified - if (size.width && size.height) { - height = size.height * precision; - width = size.width * precision; - } - //If passing only width, computing height to keep display canvas ratio. - else if (size.width && !size.height) { - width = size.width * precision; - height = Math.round(width / engine.getAspectRatio(camera)); - } - //If passing only height, computing width to keep display canvas ratio. - else if (size.height && !size.width) { - height = size.height * precision; - width = Math.round(height * engine.getAspectRatio(camera)); - } - else { - width = Math.round(engine.getRenderWidth() * precision); - height = Math.round(width / engine.getAspectRatio(camera)); - } - //If a finalWidth and finalHeight values is specified - if (size.finalWidth && size.finalHeight) { - finalHeight = size.finalHeight; - finalWidth = size.finalWidth; - } - //If passing only finalWidth, computing finalHeight to keep display canvas ratio. - else if (size.finalWidth && !size.finalHeight) { - finalWidth = size.finalWidth; - finalHeight = Math.round(finalWidth / engine.getAspectRatio(camera)); - } - //If passing only finalHeight, computing finalWidth to keep display canvas ratio. - else if (size.finalHeight && !size.finalWidth) { - finalHeight = size.finalHeight; - finalWidth = Math.round(finalHeight * engine.getAspectRatio(camera)); - } - else { - finalWidth = width; - finalHeight = height; - } - } - //Assuming here that "size" parameter is a number - else if (!isNaN(size)) { - height = size; - width = size; - finalWidth = size; - finalHeight = size; - } - // When creating the image data from the CanvasRenderingContext2D, the width and height is clamped to the size of the _gl context - // 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 - // 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 - // to resolve this, we truncate the floats here to ensure the same size - if (width) { - width = Math.floor(width); - } - if (height) { - height = Math.floor(height); - } - if (finalWidth) { - finalWidth = Math.floor(finalWidth); - } - if (finalHeight) { - finalHeight = Math.floor(finalHeight); - } - return { height: height | 0, width: width | 0, finalWidth: finalWidth | 0, finalHeight: finalHeight | 0 }; -} -/** - * Class containing a set of static utilities functions for screenshots - */ -const ScreenshotTools = { - /** - * Captures a screenshot of the current rendering - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine defines the rendering engine - * @param camera defines the source camera - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param successCallback defines the callback receives a single parameter which contains the - * screenshot as a string of base64-encoded characters. This string can be assigned to the - * src parameter of an <img> to display it - * @param mimeType defines the MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @param forceDownload force the system to download the image even if a successCallback is provided - * @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. - */ - CreateScreenshot, - /** - * Captures a screenshot of the current rendering - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine defines the rendering engine - * @param camera defines the source camera - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param mimeType defines the MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @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. - * @returns screenshot as a string of base64-encoded characters. This string can be assigned - * to the src parameter of an <img> to display it - */ - CreateScreenshotAsync, - /** - * 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) - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine defines the rendering engine - * @param camera defines the source camera - * @param width defines the expected width - * @param height defines the expected height - * @param mimeType defines the MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @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. - * @returns screenshot as a string of base64-encoded characters. This string can be assigned - * to the src parameter of an <img> to display it - */ - CreateScreenshotWithResizeAsync, - /** - * Generates an image screenshot from the specified camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine The engine to use for rendering - * @param camera The camera to use for rendering - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param successCallback The callback receives a single parameter which contains the - * screenshot as a string of base64-encoded characters. This string can be assigned to the - * src parameter of an <img> to display it - * @param mimeType The MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @param samples Texture samples (default: 1) - * @param antialiasing Whether antialiasing should be turned on or not (default: false) - * @param fileName A name for for the downloaded file. - * @param renderSprites Whether the sprites should be rendered or not (default: false) - * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) - * @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. - */ - CreateScreenshotUsingRenderTarget, - /** - * Generates an image screenshot from the specified camera. - * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG - * @param engine The engine to use for rendering - * @param camera The camera to use for rendering - * @param size This parameter can be set to a single number or to an object with the - * following (optional) properties: precision, width, height. If a single number is passed, - * it will be used for both width and height. If an object is passed, the screenshot size - * will be derived from the parameters. The precision property is a multiplier allowing - * rendering at a higher or lower resolution - * @param mimeType The MIME type of the screenshot image (default: image/png). - * Check your browser for supported MIME types - * @param samples Texture samples (default: 1) - * @param antialiasing Whether antialiasing should be turned on or not (default: false) - * @param fileName A name for for the downloaded file. - * @param renderSprites Whether the sprites should be rendered or not (default: false) - * @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. - * @returns screenshot as a string of base64-encoded characters. This string can be assigned - * to the src parameter of an <img> to display it - */ - CreateScreenshotUsingRenderTargetAsync, -}; -/** - * This will be executed automatically for UMD and es5. - * If esm dev wants the side effects to execute they will have to run it manually - * Once we build native modules those need to be exported. - * @internal - */ -const screenshotTools_initSideEffects = () => { - // References the dependencies. - tools_Tools.CreateScreenshot = CreateScreenshot; - tools_Tools.CreateScreenshotAsync = CreateScreenshotAsync; - tools_Tools.CreateScreenshotUsingRenderTarget = CreateScreenshotUsingRenderTarget; - tools_Tools.CreateScreenshotUsingRenderTargetAsync = CreateScreenshotUsingRenderTargetAsync; -}; -screenshotTools_initSideEffects(); -//# sourceMappingURL=screenshotTools.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/iInspectable.js -/** - * Enum that determines the text-wrapping mode to use. - */ -var InspectableType; -(function (InspectableType) { - /** - * Checkbox for booleans - */ - InspectableType[InspectableType["Checkbox"] = 0] = "Checkbox"; - /** - * Sliders for numbers - */ - InspectableType[InspectableType["Slider"] = 1] = "Slider"; - /** - * Vector3 - */ - InspectableType[InspectableType["Vector3"] = 2] = "Vector3"; - /** - * Quaternions - */ - InspectableType[InspectableType["Quaternion"] = 3] = "Quaternion"; - /** - * Color3 - */ - InspectableType[InspectableType["Color3"] = 4] = "Color3"; - /** - * String - */ - InspectableType[InspectableType["String"] = 5] = "String"; - /** - * Button - */ - InspectableType[InspectableType["Button"] = 6] = "Button"; - /** - * Options - */ - InspectableType[InspectableType["Options"] = 7] = "Options"; - /** - * Tab - */ - InspectableType[InspectableType["Tab"] = 8] = "Tab"; - /** - * File button - */ - InspectableType[InspectableType["FileButton"] = 9] = "FileButton"; - /** - * Vector2 - */ - InspectableType[InspectableType["Vector2"] = 10] = "Vector2"; -})(InspectableType || (InspectableType = {})); -//# sourceMappingURL=iInspectable.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/fileRequest.js - -//# sourceMappingURL=fileRequest.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/customAnimationFrameRequester.js - -//# sourceMappingURL=customAnimationFrameRequester.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/interfaces/screenshotSize.js - -//# sourceMappingURL=screenshotSize.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/interfaces/iPerfViewer.js - -//# sourceMappingURL=iPerfViewer.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/dataReader.js - -/** - * Utility class for reading from a data buffer - */ -class DataReader { - /** - * Constructor - * @param buffer The buffer to read - */ - constructor(buffer) { - /** - * The current byte offset from the beginning of the data buffer. - */ - this.byteOffset = 0; - this.buffer = buffer; - } - /** - * Loads the given byte length. - * @param byteLength The byte length to load - * @returns A promise that resolves when the load is complete - */ - loadAsync(byteLength) { - return this.buffer.readAsync(this.byteOffset, byteLength).then((data) => { - this._dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); - this._dataByteOffset = 0; - }); - } - /** - * Read a unsigned 32-bit integer from the currently loaded data range. - * @returns The 32-bit integer read - */ - readUint32() { - const value = this._dataView.getUint32(this._dataByteOffset, true); - this._dataByteOffset += 4; - this.byteOffset += 4; - return value; - } - /** - * Read a byte array from the currently loaded data range. - * @param byteLength The byte length to read - * @returns The byte array read - */ - readUint8Array(byteLength) { - const value = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._dataByteOffset, byteLength); - this._dataByteOffset += byteLength; - this.byteOffset += byteLength; - return value; - } - /** - * Read a string from the currently loaded data range. - * @param byteLength The byte length to read - * @returns The string read - */ - readString(byteLength) { - return Decode(this.readUint8Array(byteLength)); - } - /** - * Skips the given byte length the currently loaded data range. - * @param byteLength The byte length to skip - */ - skipBytes(byteLength) { - this._dataByteOffset += byteLength; - this.byteOffset += byteLength; - } -} -//# sourceMappingURL=dataReader.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/dataStorage.js -/** - * Class for storing data to local storage if available or in-memory storage otherwise - */ -class DataStorage { - static _GetStorage() { - try { - localStorage.setItem("test", ""); - localStorage.removeItem("test"); - return localStorage; - } - catch (_a) { - const inMemoryStorage = {}; - return { - getItem: (key) => { - const value = inMemoryStorage[key]; - return value === undefined ? null : value; - }, - setItem: (key, value) => { - inMemoryStorage[key] = value; - }, - }; - } - } - /** - * Reads a string from the data storage - * @param key The key to read - * @param defaultValue The value if the key doesn't exist - * @returns The string value - */ - static ReadString(key, defaultValue) { - const value = this._Storage.getItem(key); - return value !== null ? value : defaultValue; - } - /** - * Writes a string to the data storage - * @param key The key to write - * @param value The value to write - */ - static WriteString(key, value) { - this._Storage.setItem(key, value); - } - /** - * Reads a boolean from the data storage - * @param key The key to read - * @param defaultValue The value if the key doesn't exist - * @returns The boolean value - */ - static ReadBoolean(key, defaultValue) { - const value = this._Storage.getItem(key); - return value !== null ? value === "true" : defaultValue; - } - /** - * Writes a boolean to the data storage - * @param key The key to write - * @param value The value to write - */ - static WriteBoolean(key, value) { - this._Storage.setItem(key, value ? "true" : "false"); - } - /** - * Reads a number from the data storage - * @param key The key to read - * @param defaultValue The value if the key doesn't exist - * @returns The number value - */ - static ReadNumber(key, defaultValue) { - const value = this._Storage.getItem(key); - return value !== null ? parseFloat(value) : defaultValue; - } - /** - * Writes a number to the data storage - * @param key The key to write - * @param value The value to write - */ - static WriteNumber(key, value) { - this._Storage.setItem(key, value.toString()); - } -} -DataStorage._Storage = DataStorage._GetStorage(); -//# sourceMappingURL=dataStorage.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/sceneRecorder.js - - - - - - - - - - - - - - -/** - * Class used to record delta files between 2 scene states - */ -class SceneRecorder { - constructor() { - this._trackedScene = null; - } - /** - * Track a given scene. This means the current scene state will be considered the original state - * @param scene defines the scene to track - */ - track(scene) { - this._trackedScene = scene; - SerializationHelper.AllowLoadingUniqueId = true; - this._savedJSON = SceneSerializer.Serialize(scene); - SerializationHelper.AllowLoadingUniqueId = false; - } - /** - * Get the delta between current state and original state - * @returns a any containing the delta - */ - getDelta() { - if (!this._trackedScene) { - return null; - } - const currentForceSerializeBuffers = Texture.ForceSerializeBuffers; - Texture.ForceSerializeBuffers = false; - SerializationHelper.AllowLoadingUniqueId = true; - const newJSON = SceneSerializer.Serialize(this._trackedScene); - SerializationHelper.AllowLoadingUniqueId = false; - const deltaJSON = {}; - for (const node in newJSON) { - this._compareCollections(node, this._savedJSON[node], newJSON[node], deltaJSON); - } - Texture.ForceSerializeBuffers = currentForceSerializeBuffers; - return deltaJSON; - } - _compareArray(key, original, current, deltaJSON) { - if (original.length === 0 && current.length === 0) { - return true; - } - // Numbers? - if ((original.length && !isNaN(original[0])) || (current.length && !isNaN(current[0]))) { - if (original.length !== current.length) { - return false; - } - if (original.length === 0) { - return true; - } - for (let index = 0; index < original.length; index++) { - if (original[index] !== current[index]) { - deltaJSON[key] = current; - return false; - } - } - return true; - } - // let's use uniqueId to find similar objects - const originalUniqueIds = []; - for (let index = 0; index < original.length; index++) { - const originalObject = original[index]; - const originalUniqueId = originalObject.uniqueId; - originalUniqueIds.push(originalUniqueId); - // Look for that object in current state - const currentObjects = current.filter((c) => c.uniqueId === originalUniqueId); - if (currentObjects.length) { - // We have a candidate - const currentObject = currentObjects[0]; - const newObject = {}; - if (!this._compareObjects(originalObject, currentObject, newObject)) { - if (!deltaJSON[key]) { - deltaJSON[key] = []; - } - newObject.__state = { - id: currentObject.id || currentObject.name, - }; - deltaJSON[key].push(newObject); - } - } - else { - // We need to delete - const newObject = { - __state: { - deleteId: originalObject.id || originalObject.name, - }, - }; - if (!deltaJSON[key]) { - deltaJSON[key] = []; - } - deltaJSON[key].push(newObject); - } - } - // Checking for new objects - for (let index = 0; index < current.length; index++) { - const currentObject = current[index]; - const currentUniqueId = currentObject.uniqueId; - // Object was added - if (originalUniqueIds.indexOf(currentUniqueId) === -1) { - if (!deltaJSON[key]) { - deltaJSON[key] = []; - } - deltaJSON[key].push(currentObject); - } - } - return true; - } - _compareObjects(originalObjet, currentObject, deltaJSON) { - let aDifferenceWasFound = false; - for (const prop in originalObjet) { - if (!Object.prototype.hasOwnProperty.call(originalObjet, prop)) { - continue; - } - const originalValue = originalObjet[prop]; - const currentValue = currentObject[prop]; - let diffFound = false; - if (Array.isArray(originalValue)) { - diffFound = JSON.stringify(originalValue) !== JSON.stringify(currentValue); - } - else if (!isNaN(originalValue) || Object.prototype.toString.call(originalValue) == "[object String]") { - diffFound = originalValue !== currentValue; - } - else if (typeof originalValue === "object" && typeof currentValue === "object") { - const newObject = {}; - if (!this._compareObjects(originalValue, currentValue, newObject)) { - deltaJSON[prop] = newObject; - aDifferenceWasFound = true; - } - } - if (diffFound) { - aDifferenceWasFound = true; - deltaJSON[prop] = currentValue; - } - } - return !aDifferenceWasFound; - } - _compareCollections(key, original, current, deltaJSON) { - // Same ? - if (original === current) { - return; - } - if (original && current) { - // Array? - if (Array.isArray(original) && Array.isArray(current)) { - if (this._compareArray(key, original, current, deltaJSON)) { - return; - } - } - else if (typeof original === "object" && typeof current === "object") { - // Object - const newObject = {}; - if (!this._compareObjects(original, current, newObject)) { - deltaJSON[key] = newObject; - } - return; - } - } - } - static GetShadowGeneratorById(scene, id) { - const allGenerators = scene.lights.map((l) => l.getShadowGenerators()); - for (const generators of allGenerators) { - if (generators) { - const iterator = generators.values(); - for (let key = iterator.next(); key.done !== true; key = iterator.next()) { - const generator = key.value; - if (generator && generator.id === id) { - return generator; - } - } - } - } - return null; - } - /** - * Apply a given delta to a given scene - * @param deltaJSON defines the JSON containing the delta - * @param scene defines the scene to apply the delta to - */ - static ApplyDelta(deltaJSON, scene) { - if (typeof deltaJSON === "string") { - deltaJSON = JSON.parse(deltaJSON); - } - // Scene - const anyScene = scene; - for (const prop in deltaJSON) { - const source = deltaJSON[prop]; - const property = anyScene[prop]; - if (Array.isArray(property) || prop === "shadowGenerators") { - // Restore array - switch (prop) { - case "cameras": - this._ApplyDeltaForEntity(source, scene, scene.getCameraById.bind(scene), (data) => Camera.Parse(data, scene)); - break; - case "lights": - this._ApplyDeltaForEntity(source, scene, scene.getLightById.bind(scene), (data) => Light.Parse(data, scene)); - break; - case "shadowGenerators": - this._ApplyDeltaForEntity(source, scene, (id) => this.GetShadowGeneratorById(scene, id), (data) => ShadowGenerator.Parse(data, scene)); - break; - case "meshes": - this._ApplyDeltaForEntity(source, scene, scene.getMeshById.bind(scene), (data) => Mesh.Parse(data, scene, "")); - break; - case "skeletons": - this._ApplyDeltaForEntity(source, scene, scene.getSkeletonById.bind(scene), (data) => Skeleton.Parse(data, scene)); - break; - case "materials": - this._ApplyDeltaForEntity(source, scene, scene.getMaterialById.bind(scene), (data) => Material.Parse(data, scene, "")); - break; - case "multiMaterials": - this._ApplyDeltaForEntity(source, scene, scene.getMaterialById.bind(scene), (data) => MultiMaterial.Parse(data, scene, "")); - break; - case "transformNodes": - this._ApplyDeltaForEntity(source, scene, scene.getTransformNodeById.bind(scene), (data) => TransformNode.Parse(data, scene, "")); - break; - case "particleSystems": - this._ApplyDeltaForEntity(source, scene, scene.getParticleSystemById.bind(scene), (data) => ParticleSystem.Parse(data, scene, "")); - break; - case "morphTargetManagers": - this._ApplyDeltaForEntity(source, scene, scene.getMorphTargetById.bind(scene), (data) => MorphTargetManager.Parse(data, scene)); - break; - case "postProcesses": - this._ApplyDeltaForEntity(source, scene, scene.getPostProcessByName.bind(scene), (data) => PostProcess.Parse(data, scene, "")); - break; - } - } - else if (!isNaN(property)) { - anyScene[prop] = source; - } - else if (property.fromArray) { - property.fromArray(source); - } - } - } - static _ApplyPropertiesToEntity(deltaJSON, entity) { - for (const prop in deltaJSON) { - const source = deltaJSON[prop]; - const property = entity[prop]; - if (property === undefined) { - continue; - } - if (!isNaN(property) || Array.isArray(property)) { - entity[prop] = source; - } - else if (property.fromArray) { - property.fromArray(source); - } - else if (typeof property === "object" && property !== null) { - this._ApplyPropertiesToEntity(source, property); - } - } - } - static _ApplyDeltaForEntity(sources, scene, finder, addNew) { - for (const source of sources) { - // Update - if (source.__state && source.__state.id !== undefined) { - const targetEntity = finder(source.__state.id); - if (targetEntity) { - // This first pass applies properties that aren't on the serialization list - this._ApplyPropertiesToEntity(source, targetEntity); - // The second pass applies the serializable properties - SerializationHelper.ParseProperties(source, targetEntity, scene, null); - } - } - else if (source.__state && source.__state.deleteId !== undefined) { - const target = finder(source.__state.deleteId); - target === null || target === void 0 ? void 0 : target.dispose(); - } - else { - // New - addNew(source); - } - } - } -} -//# sourceMappingURL=sceneRecorder.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/trajectoryClassifier.js - -// This implementation was based on the original MIT-licensed TRACE repository -// from https://github.com/septagon/TRACE. -/** - * Generic implementation of Levenshtein distance. - */ -var Levenshtein; -(function (Levenshtein) { - /** - * Alphabet from which to construct sequences to be compared using Levenshtein - * distance. - */ - class Alphabet { - /** - * Serialize the Alphabet to JSON string. - * @returns JSON serialization - */ - serialize() { - const jsonObject = {}; - const characters = new Array(this._characterToIdx.size); - this._characterToIdx.forEach((v, k) => { - characters[v] = k; - }); - jsonObject["characters"] = characters; - jsonObject["insertionCosts"] = this._insertionCosts; - jsonObject["deletionCosts"] = this._deletionCosts; - jsonObject["substitutionCosts"] = this._substitutionCosts; - return JSON.stringify(jsonObject); - } - /** - * Parse an Alphabet from a JSON serialization. - * @param json JSON string to deserialize - * @returns deserialized Alphabet - */ - static Deserialize(json) { - const jsonObject = JSON.parse(json); - const alphabet = new Alphabet(jsonObject["characters"]); - alphabet._insertionCosts = jsonObject["insertionCosts"]; - alphabet._deletionCosts = jsonObject["deletionCosts"]; - alphabet._substitutionCosts = jsonObject["substitutionCosts"]; - return alphabet; - } - /** - * Create a new Alphabet. - * @param characters characters of the alphabet - * @param charToInsertionCost function mapping characters to insertion costs - * @param charToDeletionCost function mapping characters to deletion costs - * @param charsToSubstitutionCost function mapping character pairs to substitution costs - */ - constructor(characters, charToInsertionCost = null, charToDeletionCost = null, charsToSubstitutionCost = null) { - charToInsertionCost = charToInsertionCost !== null && charToInsertionCost !== void 0 ? charToInsertionCost : (() => 1); - charToDeletionCost = charToDeletionCost !== null && charToDeletionCost !== void 0 ? charToDeletionCost : (() => 1); - charsToSubstitutionCost = charsToSubstitutionCost !== null && charsToSubstitutionCost !== void 0 ? charsToSubstitutionCost : ((a, b) => (a === b ? 0 : 1)); - this._characterToIdx = new Map(); - this._insertionCosts = new Array(characters.length); - this._deletionCosts = new Array(characters.length); - this._substitutionCosts = new Array(characters.length); - let c; - for (let outerIdx = 0; outerIdx < characters.length; ++outerIdx) { - c = characters[outerIdx]; - this._characterToIdx.set(c, outerIdx); - this._insertionCosts[outerIdx] = charToInsertionCost(c); - this._deletionCosts[outerIdx] = charToDeletionCost(c); - this._substitutionCosts[outerIdx] = new Array(characters.length); - for (let innerIdx = outerIdx; innerIdx < characters.length; ++innerIdx) { - this._substitutionCosts[outerIdx][innerIdx] = charsToSubstitutionCost(c, characters[innerIdx]); - } - } - } - /** - * Get the index (internally-assigned number) for a character. - * @param char character - * @returns index - */ - getCharacterIdx(char) { - return this._characterToIdx.get(char); - } - /** - * Get the insertion cost of a character from its index. - * @param idx character index - * @returns insertion cost - */ - getInsertionCost(idx) { - return this._insertionCosts[idx]; - } - /** - * Get the deletion cost of a character from its index. - * @param idx character index - * @returns deletion cost - */ - getDeletionCost(idx) { - return this._deletionCosts[idx]; - } - /** - * Gets the cost to substitute two characters. NOTE: this cost is - * required to be bi-directional, meaning it cannot matter which of - * the provided characters is being removed and which is being inserted. - * @param idx1 the first character index - * @param idx2 the second character index - * @returns substitution cost - */ - getSubstitutionCost(idx1, idx2) { - const min = Math.min(idx1, idx2); - const max = Math.max(idx1, idx2); - return this._substitutionCosts[min][max]; - } - } - Levenshtein.Alphabet = Alphabet; - /** - * Character sequence intended to be compared against other Sequences created - * with the same Alphabet in order to compute Levenshtein distance. - */ - class Sequence { - /** - * Serialize to JSON string. JSON representation does NOT include the Alphabet - * from which this Sequence was created; Alphabet must be independently - * serialized. - * @returns JSON string - */ - serialize() { - return JSON.stringify(this._characters); - } - /** - * Deserialize from JSON string and Alphabet. This should be the same Alphabet - * from which the Sequence was originally created, which must be serialized and - * deserialized independently so that it can be passed in here. - * @param json JSON string representation of Sequence - * @param alphabet Alphabet from which Sequence was originally created - * @returns Sequence - */ - static Deserialize(json, alphabet) { - const sequence = new Sequence([], alphabet); - sequence._characters = JSON.parse(json); - return sequence; - } - /** - * Create a new Sequence. - * @param characters characters in the new Sequence - * @param alphabet Alphabet, which must include all used characters - */ - constructor(characters, alphabet) { - if (characters.length > Sequence._MAX_SEQUENCE_LENGTH) { - throw new Error("Sequences longer than " + Sequence._MAX_SEQUENCE_LENGTH + " not supported."); - } - this._alphabet = alphabet; - this._characters = characters.map((c) => this._alphabet.getCharacterIdx(c)); - } - /** - * Get the distance between this Sequence and another. - * @param other sequence to compare to - * @returns Levenshtein distance - */ - distance(other) { - return Sequence._Distance(this, other); - } - /** - * Compute the Levenshtein distance between two Sequences. - * @param a first Sequence - * @param b second Sequence - * @returns Levenshtein distance - */ - static _Distance(a, b) { - const alphabet = a._alphabet; - if (alphabet !== b._alphabet) { - throw new Error("Cannot Levenshtein compare Sequences built from different alphabets."); - } - const aChars = a._characters; - const bChars = b._characters; - const aLength = aChars.length; - const bLength = bChars.length; - const costMatrix = Sequence._CostMatrix; - costMatrix[0][0] = 0; - for (let idx = 0; idx < aLength; ++idx) { - costMatrix[idx + 1][0] = costMatrix[idx][0] + alphabet.getInsertionCost(aChars[idx]); - } - for (let idx = 0; idx < bLength; ++idx) { - costMatrix[0][idx + 1] = costMatrix[0][idx] + alphabet.getInsertionCost(bChars[idx]); - } - for (let aIdx = 0; aIdx < aLength; ++aIdx) { - for (let bIdx = 0; bIdx < bLength; ++bIdx) { - Sequence._InsertionCost = costMatrix[aIdx + 1][bIdx] + alphabet.getInsertionCost(bChars[bIdx]); - Sequence._DeletionCost = costMatrix[aIdx][bIdx + 1] + alphabet.getDeletionCost(aChars[aIdx]); - Sequence._SubstitutionCost = costMatrix[aIdx][bIdx] + alphabet.getSubstitutionCost(aChars[aIdx], bChars[bIdx]); - costMatrix[aIdx + 1][bIdx + 1] = Math.min(Sequence._InsertionCost, Sequence._DeletionCost, Sequence._SubstitutionCost); - } - } - return costMatrix[aLength][bLength]; - } - } - // Scratch values - Sequence._MAX_SEQUENCE_LENGTH = 256; - Sequence._CostMatrix = [...Array(Sequence._MAX_SEQUENCE_LENGTH + 1)].map(() => new Array(Sequence._MAX_SEQUENCE_LENGTH + 1)); - Levenshtein.Sequence = Sequence; -})(Levenshtein || (Levenshtein = {})); -/** - * A 3D trajectory consisting of an order list of vectors describing a - * path of motion through 3D space. - */ -class Trajectory { - /** - * Serialize to JSON. - * @returns serialized JSON string - */ - serialize() { - return JSON.stringify(this); - } - /** - * Deserialize from JSON. - * @param json serialized JSON string - * @returns deserialized Trajectory - */ - static Deserialize(json) { - const jsonObject = JSON.parse(json); - const trajectory = new Trajectory(jsonObject["_segmentLength"]); - trajectory._points = jsonObject["_points"].map((pt) => { - return new math_vector_Vector3(pt["_x"], pt["_y"], pt["_z"]); - }); - return trajectory; - } - /** - * Create a new empty Trajectory. - * @param segmentLength radius of discretization for Trajectory points - */ - constructor(segmentLength = 0.01) { - this._points = []; - this._segmentLength = segmentLength; - } - /** - * Get the length of the Trajectory. - * @returns length of the Trajectory - */ - getLength() { - return this._points.length * this._segmentLength; - } - /** - * Append a new point to the Trajectory. - * NOTE: This implementation has many allocations. - * @param point point to append to the Trajectory - */ - add(point) { - let numPoints = this._points.length; - if (numPoints === 0) { - this._points.push(point.clone()); - } - else { - const getT = () => this._segmentLength / math_vector_Vector3.Distance(this._points[numPoints - 1], point); - for (let t = getT(); t <= 1.0; t = getT()) { - const newPoint = this._points[numPoints - 1].scale(1.0 - t); - point.scaleAndAddToRef(t, newPoint); - this._points.push(newPoint); - ++numPoints; - } - } - } - /** - * Create a new Trajectory with a segment length chosen to make it - * probable that the new Trajectory will have a specified number of - * segments. This operation is imprecise. - * @param targetResolution number of segments desired - * @returns new Trajectory with approximately the requested number of segments - */ - resampleAtTargetResolution(targetResolution) { - const resampled = new Trajectory(this.getLength() / targetResolution); - this._points.forEach((pt) => { - resampled.add(pt); - }); - return resampled; - } - /** - * Convert Trajectory segments into tokenized representation. This - * representation is an array of numbers where each nth number is the - * index of the token which is most similar to the nth segment of the - * Trajectory. - * @param tokens list of vectors which serve as discrete tokens - * @returns list of indices of most similar token per segment - */ - tokenize(tokens) { - const tokenization = []; - const segmentDir = new math_vector_Vector3(); - for (let idx = 2; idx < this._points.length; ++idx) { - if (Trajectory._TransformSegmentDirToRef(this._points[idx - 2], this._points[idx - 1], this._points[idx], segmentDir)) { - tokenization.push(Trajectory._TokenizeSegment(segmentDir, tokens)); - } - } - return tokenization; - } - /** - * Transform the rotation (i.e., direction) of a segment to isolate - * the relative transformation represented by the segment. This operation - * may or may not succeed due to singularities in the equations that define - * motion relativity in this context. - * @param priorVec the origin of the prior segment - * @param fromVec the origin of the current segment - * @param toVec the destination of the current segment - * @param result reference to output variable - * @returns whether or not transformation was successful - */ - static _TransformSegmentDirToRef(priorVec, fromVec, toVec, result) { - const DOT_PRODUCT_SAMPLE_REJECTION_THRESHOLD = 0.98; - fromVec.subtractToRef(priorVec, Trajectory._ForwardDir); - Trajectory._ForwardDir.normalize(); - fromVec.scaleToRef(-1, Trajectory._InverseFromVec); - Trajectory._InverseFromVec.normalize(); - if (Math.abs(math_vector_Vector3.Dot(Trajectory._ForwardDir, Trajectory._InverseFromVec)) > DOT_PRODUCT_SAMPLE_REJECTION_THRESHOLD) { - return false; - } - math_vector_Vector3.CrossToRef(Trajectory._ForwardDir, Trajectory._InverseFromVec, Trajectory._UpDir); - Trajectory._UpDir.normalize(); - math_vector_Matrix.LookAtLHToRef(priorVec, fromVec, Trajectory._UpDir, Trajectory._LookMatrix); - toVec.subtractToRef(fromVec, Trajectory._FromToVec); - Trajectory._FromToVec.normalize(); - math_vector_Vector3.TransformNormalToRef(Trajectory._FromToVec, Trajectory._LookMatrix, result); - return true; - } - /** - * Determine which token vector is most similar to the - * segment vector. - * @param segment segment vector - * @param tokens token vector list - * @returns index of the most similar token to the segment - */ - static _TokenizeSegment(segment, tokens) { - Trajectory._BestMatch = 0; - Trajectory._Score = math_vector_Vector3.Dot(segment, tokens[0]); - Trajectory._BestScore = Trajectory._Score; - for (let idx = 1; idx < tokens.length; ++idx) { - Trajectory._Score = math_vector_Vector3.Dot(segment, tokens[idx]); - if (Trajectory._Score > Trajectory._BestScore) { - Trajectory._BestMatch = idx; - Trajectory._BestScore = Trajectory._Score; - } - } - return Trajectory._BestMatch; - } -} -Trajectory._ForwardDir = new math_vector_Vector3(); -Trajectory._InverseFromVec = new math_vector_Vector3(); -Trajectory._UpDir = new math_vector_Vector3(); -Trajectory._FromToVec = new math_vector_Vector3(); -Trajectory._LookMatrix = new math_vector_Matrix(); -/** - * Collection of vectors intended to be used as the basis of Trajectory - * tokenization for Levenshtein distance comparison. Canonically, a - * Vector3Alphabet will resemble a "spikeball" of vectors distributed - * roughly evenly over the surface of the unit sphere. - */ -class Vector3Alphabet { - /** - * Helper method to create new "spikeball" Vector3Alphabets. Uses a naive - * optimize-from-random strategy to space points around the unit sphere - * surface as a simple alternative to really doing the math to tile the - * sphere. - * @param alphabetSize size of the desired alphabet - * @param iterations number of iterations over which to optimize the "spikeball" - * @param startingStepSize distance factor to move points in early optimization iterations - * @param endingStepSize distance factor to move points in late optimization iterations - * @param fixedValues alphabet "characters" that are required and cannot be moved by optimization - * @returns a new randomly generated and optimized Vector3Alphabet of the specified size - */ - static Generate(alphabetSize = 64, iterations = 256, startingStepSize = 0.1, endingStepSize = 0.001, fixedValues = []) { - const EPSILON = 0.001; - const EPSILON_SQUARED = EPSILON * EPSILON; - const alphabet = new Vector3Alphabet(alphabetSize); - for (let idx = 0; idx < alphabetSize; ++idx) { - alphabet.chars[idx] = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5); - alphabet.chars[idx].normalize(); - } - for (let idx = 0; idx < fixedValues.length; ++idx) { - alphabet.chars[idx].copyFrom(fixedValues[idx]); - } - let stepSize; - let distSq; - const force = new Vector3(); - const scratch = new Vector3(); - const lerp = (l, r, t) => (1.0 - t) * l + t * r; - for (let iteration = 0; iteration < iterations; ++iteration) { - stepSize = lerp(startingStepSize, endingStepSize, iteration / (iterations - 1)); - for (let idx = fixedValues.length; idx < alphabet.chars.length; ++idx) { - force.copyFromFloats(0, 0, 0); - alphabet.chars.forEach((pt) => { - alphabet.chars[idx].subtractToRef(pt, scratch); - distSq = scratch.lengthSquared(); - if (distSq > EPSILON_SQUARED) { - scratch.scaleAndAddToRef(1 / (scratch.lengthSquared() * distSq), force); - } - }); - force.scaleInPlace(stepSize); - alphabet.chars[idx].addInPlace(force); - alphabet.chars[idx].normalize(); - } - } - return alphabet; - } - /** - * Serialize to JSON. - * @returns JSON serialization - */ - serialize() { - return JSON.stringify(this.chars); - } - /** - * Deserialize from JSON. - * @param json JSON serialization - * @returns deserialized Vector3Alphabet - */ - static Deserialize(json) { - const jsonObject = JSON.parse(json); - const alphabet = new Vector3Alphabet(jsonObject.length); - for (let idx = 0; idx < jsonObject.length; ++idx) { - alphabet.chars[idx] = new Vector3(jsonObject[idx]["_x"], jsonObject[idx]["_y"], jsonObject[idx]["_z"]); - } - return alphabet; - } - constructor(size) { - this.chars = new Array(size); - } -} -/** - * Class which formalizes the manner in which a Vector3Alphabet is used to tokenize and - * describe a Trajectory. This class houses the functionality which determines what - * attributes of Trajectories are and are not considered important, such as scale. - */ -class TrajectoryDescriptor { - /** - * Serialize to JSON. - * @returns JSON serialization - */ - serialize() { - return JSON.stringify(this._sequences.map((sequence) => sequence.serialize())); - } - /** - * Deserialize from JSON string and Alphabet. This should be the same Alphabet - * from which the descriptor was originally created, which must be serialized and - * deserialized independently so that it can be passed in here. - * @param json JSON serialization - * @param alphabet Alphabet from which descriptor was originally created - * @returns deserialized TrajectoryDescriptor - */ - static Deserialize(json, alphabet) { - const descriptor = new TrajectoryDescriptor(); - descriptor._sequences = JSON.parse(json).map((s) => Levenshtein.Sequence.Deserialize(s, alphabet)); - return descriptor; - } - /** - * Create a new TrajectoryDescriptor to describe a provided Trajectory according - * to the provided alphabets. - * @param trajectory Trajectory to be described - * @param vector3Alphabet Vector3Alphabet to be used to tokenize the Trajectory - * @param levenshteinAlphabet Levenshtein.Alphabet to be used as basis for comparison with other descriptors - * @returns TrajectoryDescriptor describing provided Trajectory - */ - static CreateFromTrajectory(trajectory, vector3Alphabet, levenshteinAlphabet) { - return TrajectoryDescriptor.CreateFromTokenizationPyramid(TrajectoryDescriptor._GetTokenizationPyramid(trajectory, vector3Alphabet), levenshteinAlphabet); - } - /** - * Create a new TrajectoryDescriptor from a pre-existing pyramid of tokens. - * NOTE: This function exists to support an outdated serialization mechanism and should - * be deleted if it is no longer useful. - * @param pyramid tokenization pyramid - * @param levenshteinAlphabet Levenshtein.Alphabet to be uses as basis for comparison with other descriptors - * @returns TrajectoryDescriptor describing the Trajectory from which the pyramid was built - */ - static CreateFromTokenizationPyramid(pyramid, levenshteinAlphabet) { - const descriptor = new TrajectoryDescriptor(); - descriptor._sequences = pyramid.map((tokens) => new Levenshtein.Sequence(tokens, levenshteinAlphabet)); - return descriptor; - } - constructor() { - this._sequences = []; - } - /** - * Create the tokenization pyramid for the provided Trajectory according to the given - * Vector3Alphabet. - * @param trajectory Trajectory to be tokenized - * @param alphabet Vector3Alphabet containing tokens - * @param targetResolution finest resolution of descriptor - * @returns tokenization pyramid for Trajectory - */ - static _GetTokenizationPyramid(trajectory, alphabet, targetResolution = TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION) { - const pyramid = []; - for (let res = targetResolution; res > 4; res = Math.floor(res / 2)) { - pyramid.push(trajectory.resampleAtTargetResolution(res).tokenize(alphabet.chars)); - } - return pyramid; - } - /** - * Calculate a distance metric between this TrajectoryDescriptor and another. This is - * essentially a similarity score and does not directly represent Euclidean distance, - * edit distance, or any other formal distance metric. - * @param other TrajectoryDescriptor from which to determine distance - * @returns distance, a nonnegative similarity score where larger values indicate dissimilarity - */ - distance(other) { - let totalDistance = 0; - let weight; - for (let idx = 0; idx < this._sequences.length; ++idx) { - weight = Math.pow(2, idx); - totalDistance += weight * this._sequences[idx].distance(other._sequences[idx]); - } - return totalDistance; - } -} -TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION = 32; -/** - * A set of TrajectoryDescriptors defined to be "the same." This is essentially a helper - * class to facilitate methods of Trajectory clustering. - */ -class TrajectoryClass { - /** - * Serialize to JSON. - * @returns JSON serialization - */ - serialize() { - const jsonObject = {}; - jsonObject.descriptors = this._descriptors.map((desc) => desc.serialize()); - jsonObject.centroidIdx = this._centroidIdx; - jsonObject.averageDistance = this._averageDistance; - return JSON.stringify(jsonObject); - } - /** - * Deserialize from JSON string and Alphabet. This should be the same Alphabet - * from which the descriptors were originally created, which must be serialized and - * deserialized independently so that it can be passed in here. - * @param json JSON string representation - * @param alphabet Alphabet from which TrajectoryDescriptors were originally created - * @returns deserialized TrajectoryDescriptor - */ - static Deserialize(json, alphabet) { - const jsonObject = JSON.parse(json); - const described = new TrajectoryClass(); - described._descriptors = jsonObject.descriptors.map((s) => TrajectoryDescriptor.Deserialize(s, alphabet)); - described._centroidIdx = jsonObject.centroidIdx; - described._averageDistance = jsonObject.averageDistance; - return described; - } - /** - * Create a new DescribedTrajectory. - * @param descriptors currently-known TrajectoryDescriptors, if any - */ - constructor(descriptors = []) { - this._descriptors = descriptors; - this._centroidIdx = -1; - this._averageDistance = 0; - this._refreshDescription(); - } - /** - * Add a new TrajectoryDescriptor to the list of descriptors known to describe - * this same DescribedTrajectory. - * @param descriptor descriptor to be added - */ - add(descriptor) { - this._descriptors.push(descriptor); - this._refreshDescription(); - } - /** - * Compute the cost, which is inversely related to the likelihood that the provided - * TrajectoryDescriptor describes a Trajectory that is considered to be the same as - * the class represented by this DescribedTrajectory. - * @param descriptor the descriptor to be costed - * @returns cost of the match, which is a nonnegative similarity metric where larger values indicate dissimilarity - */ - getMatchCost(descriptor) { - return descriptor.distance(this._descriptors[this._centroidIdx]) / this._averageDistance; - } - /** - * Compute the minimum distance between the queried TrajectoryDescriptor and a - * descriptor which is a member of this collection. This is an alternative way of - * conceptualizing match cost from getMatchCost(), and it serves a different function. - * @param descriptor the descriptor to find the minimum distance to - * @returns minimum descriptor distance to a member descriptor of this DescribedTrajectory - */ - getMatchMinimumDistance(descriptor) { - return Math.min(...this._descriptors.map((desc) => desc.distance(descriptor))); - } - /** - * Refreshes the internal representation of this DescribedTrajectory. - */ - _refreshDescription() { - this._centroidIdx = -1; - let sum; - const distances = this._descriptors.map((a) => { - sum = 0; - this._descriptors.forEach((b) => { - sum += a.distance(b); - }); - return sum; - }); - for (let idx = 0; idx < distances.length; ++idx) { - if (this._centroidIdx < 0 || distances[idx] < distances[this._centroidIdx]) { - this._centroidIdx = idx; - } - } - this._averageDistance = 0; - this._descriptors.forEach((desc) => { - this._averageDistance += desc.distance(this._descriptors[this._centroidIdx]); - }); - if (this._descriptors.length > 0) { - this._averageDistance = Math.max(this._averageDistance / this._descriptors.length, TrajectoryClass._MIN_AVERAGE_DISTANCE); - } - } -} -TrajectoryClass._MIN_AVERAGE_DISTANCE = 1; -/** - * Class representing a set of known, named trajectories to which Trajectories can be - * added and using which Trajectories can be recognized. - */ -class TrajectoryClassifier { - /** - * Serialize to JSON. - * @returns JSON serialization - */ - serialize() { - const jsonObject = {}; - jsonObject.maximumAllowableMatchCost = this._maximumAllowableMatchCost; - jsonObject.vector3Alphabet = this._vector3Alphabet.serialize(); - jsonObject.levenshteinAlphabet = this._levenshteinAlphabet.serialize(); - jsonObject.nameToDescribedTrajectory = []; - this._nameToDescribedTrajectory.forEach((described, name) => { - jsonObject.nameToDescribedTrajectory.push(name); - jsonObject.nameToDescribedTrajectory.push(described.serialize()); - }); - return JSON.stringify(jsonObject); - } - /** - * Deserialize from JSON. - * @param json JSON serialization - * @returns deserialized TrajectorySet - */ - static Deserialize(json) { - const jsonObject = JSON.parse(json); - const classifier = new TrajectoryClassifier(); - classifier._maximumAllowableMatchCost = jsonObject.maximumAllowableMatchCost; - classifier._vector3Alphabet = Vector3Alphabet.Deserialize(jsonObject.vector3Alphabet); - classifier._levenshteinAlphabet = Levenshtein.Alphabet.Deserialize(jsonObject.levenshteinAlphabet); - for (let idx = 0; idx < jsonObject.nameToDescribedTrajectory.length; idx += 2) { - classifier._nameToDescribedTrajectory.set(jsonObject.nameToDescribedTrajectory[idx], TrajectoryClass.Deserialize(jsonObject.nameToDescribedTrajectory[idx + 1], classifier._levenshteinAlphabet)); - } - return classifier; - } - /** - * Initialize a new empty TrajectorySet with auto-generated Alphabets. - * VERY naive, need to be generating these things from known - * sets. Better version later, probably eliminating this one. - * @returns auto-generated TrajectorySet - */ - static Generate() { - const vecs = Vector3Alphabet.Generate(64, 256, 0.1, 0.001, [Vector3.Forward()]); - const charIdxs = new Array(vecs.chars.length); - for (let idx = 0; idx < charIdxs.length; ++idx) { - charIdxs[idx] = idx; - } - 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)); - const trajectorySet = new TrajectoryClassifier(); - trajectorySet._vector3Alphabet = vecs; - trajectorySet._levenshteinAlphabet = alphabet; - return trajectorySet; - } - constructor() { - this._maximumAllowableMatchCost = 4; - this._nameToDescribedTrajectory = new Map(); - } - /** - * Add a new Trajectory to the set with a given name. - * @param trajectory new Trajectory to be added - * @param classification name to which to add the Trajectory - */ - addTrajectoryToClassification(trajectory, classification) { - if (!this._nameToDescribedTrajectory.has(classification)) { - this._nameToDescribedTrajectory.set(classification, new TrajectoryClass()); - } - this._nameToDescribedTrajectory.get(classification).add(TrajectoryDescriptor.CreateFromTrajectory(trajectory, this._vector3Alphabet, this._levenshteinAlphabet)); - } - /** - * Remove a known named trajectory and all Trajectories associated with it. - * @param classification name to remove - * @returns whether anything was removed - */ - deleteClassification(classification) { - return this._nameToDescribedTrajectory.delete(classification); - } - /** - * Attempt to recognize a Trajectory from among all the classifications - * already known to the classifier. - * @param trajectory Trajectory to be recognized - * @returns classification of Trajectory if recognized, null otherwise - */ - classifyTrajectory(trajectory) { - const descriptor = TrajectoryDescriptor.CreateFromTrajectory(trajectory, this._vector3Alphabet, this._levenshteinAlphabet); - const allowableMatches = []; - this._nameToDescribedTrajectory.forEach((trajectoryClass, classification) => { - if (trajectoryClass.getMatchCost(descriptor) < this._maximumAllowableMatchCost) { - allowableMatches.push(classification); - } - }); - if (allowableMatches.length === 0) { - return null; - } - let bestIdx = 0; - let bestMatch = this._nameToDescribedTrajectory.get(allowableMatches[bestIdx]).getMatchMinimumDistance(descriptor); - let match; - for (let idx = 0; idx < allowableMatches.length; ++idx) { - match = this._nameToDescribedTrajectory.get(allowableMatches[idx]).getMatchMinimumDistance(descriptor); - if (match < bestMatch) { - bestMatch = match; - bestIdx = idx; - } - } - return allowableMatches[bestIdx]; - } -} -//# sourceMappingURL=trajectoryClassifier.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/reflector.js - - -/** - * Class used to connect with the reflector zone of the sandbox via the reflector bridge - * @since 5.0.0 - */ -class Reflector { - /** - * Constructs a reflector object. - * @param scene The scene to use - * @param hostname The hostname of the reflector bridge - * @param port The port of the reflector bridge - */ - constructor(scene, hostname, port) { - this._scene = scene; - logger_Logger.Log(`[Reflector] Connecting to ws://${hostname}:${port}`); - this._webSocket = new WebSocket(`ws://${hostname}:${port}`); - this._webSocket.onmessage = (event) => { - const message = event.data; - if (message.startsWith(Reflector._SERVER_PREFIX)) { - const serverMessage = message.substr(Reflector._SERVER_PREFIX.length); - logger_Logger.Log(`[Reflector] Received server message: ${serverMessage.substr(0, 64)}`); - this._handleServerMessage(serverMessage); - return; - } - else { - logger_Logger.Log(`[Reflector] Received client message: ${message.substr(0, 64)}`); - this._handleClientMessage(); - } - }; - this._webSocket.onclose = (event) => { - logger_Logger.Log(`[Reflector] Disconnected ${event.code} ${event.reason}`); - }; - } - /** - * Closes the reflector connection - */ - close() { - this._webSocket.close(); - } - _handleServerMessage(message) { - switch (message) { - case "connected": { - sceneSerializer_SceneSerializer.SerializeAsync(this._scene).then((serialized) => { - this._webSocket.send(`load|${JSON.stringify(serialized)}`); - }); - break; - } - } - } - _handleClientMessage() { - // do nothing - } -} -Reflector._SERVER_PREFIX = "$$"; -//# sourceMappingURL=reflector.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/pressureObserverWrapper.js - -/** - * A wrapper for the experimental pressure api which allows a callback to be called whenever certain thresholds are met. - */ -class pressureObserverWrapper_PressureObserverWrapper { - /** - * A pressure observer will call this callback, whenever these thresholds are met. - * @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). - */ - constructor(options) { - this._observer = null; - this._currentState = []; - /** - * An event triggered when the cpu usage/speed meets certain thresholds. - * Note: pressure is an experimental API. - */ - this.onPressureChanged = new Observable(); - if (pressureObserverWrapper_PressureObserverWrapper.IsAvailable) { - this._observer = new PressureObserver((update) => { - this._currentState = update; - this.onPressureChanged.notifyObservers(update); - }, options); - } - } - /** - * Returns true if PressureObserver is available for use, false otherwise. - */ - static get IsAvailable() { - return typeof PressureObserver !== "undefined" && PressureObserver.supportedSources.includes("cpu"); - } - /** - * Method that must be called to begin observing changes, and triggering callbacks. - * @param source defines the source to observe - */ - observe(source) { - var _a; - try { - (_a = this._observer) === null || _a === void 0 ? void 0 : _a.observe(source); - this.onPressureChanged.notifyObservers(this._currentState); - } - catch (_b) { - // Ignore error - } - } - /** - * Method that must be called to stop observing changes and triggering callbacks (cleanup function). - * @param source defines the source to unobserve - */ - unobserve(source) { - var _a; - try { - (_a = this._observer) === null || _a === void 0 ? void 0 : _a.unobserve(source); - } - catch (_b) { - // Ignore error - } - } - /** - * Release the associated resources. - */ - dispose() { - var _a; - (_a = this._observer) === null || _a === void 0 ? void 0 : _a.disconnect(); - this._observer = null; - this.onPressureChanged.clear(); - } -} -//# sourceMappingURL=pressureObserverWrapper.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/PerformanceViewer/dynamicFloat32Array.js -const growthFactor = 1.5; -/** - * A class acting as a dynamic float32array used in the performance viewer - */ -class DynamicFloat32Array { - /** - * Creates a new DynamicFloat32Array with the desired item capacity. - * @param itemCapacity The initial item capacity you would like to set for the array. - */ - constructor(itemCapacity) { - this._view = new Float32Array(itemCapacity); - this._itemLength = 0; - } - /** - * The number of items currently in the array. - */ - get itemLength() { - return this._itemLength; - } - /** - * Gets value at index, NaN if no such index exists. - * @param index the index to get the value at. - * @returns the value at the index provided. - */ - at(index) { - if (index < 0 || index >= this._itemLength) { - return NaN; - } - return this._view[index]; - } - /** - * Gets a view of the original array from start to end (exclusive of end). - * @param start starting index. - * @param end ending index. - * @returns a subarray of the original array. - */ - subarray(start, end) { - if (start >= end || start < 0) { - return new Float32Array(0); - } - if (end > this._itemLength) { - end = this._itemLength; - } - return this._view.subarray(start, end); - } - /** - * Pushes items to the end of the array. - * @param item The item to push into the array. - */ - push(item) { - this._view[this._itemLength] = item; - this._itemLength++; - if (this._itemLength >= this._view.length) { - this._growArray(); - } - } - /** - * Grows the array by the growth factor when necessary. - */ - _growArray() { - const newCapacity = Math.floor(this._view.length * growthFactor); - const view = new Float32Array(newCapacity); - view.set(this._view); - this._view = view; - } -} -//# sourceMappingURL=dynamicFloat32Array.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerCollector.js - - - - -// the initial size of our array, should be a multiple of two! -const InitialArraySize = 1800; -// three octets in a hexcode. #[AA][BB][CC], i.e. 24 bits of data. -const NumberOfBitsInHexcode = 24; -// Allows single numeral hex numbers to be appended by a 0. -const HexPadding = "0"; -// header for the timestamp column -const TimestampColHeader = "timestamp"; -// header for the numPoints column -const NumPointsColHeader = "numPoints"; -// regex to capture all carriage returns in the string. -const CarriageReturnRegex = /\r/g; -// string to use as separator when exporting extra information along with the dataset id -const ExportedDataSeparator = "@"; -/** - * The collector class handles the collection and storage of data into the appropriate array. - * The collector also handles notifying any observers of any updates. - */ -class PerformanceViewerCollector { - /** - * The offset for when actual data values start appearing inside a slice. - */ - static get SliceDataOffset() { - return 2; - } - /** - * The offset for the value of the number of points inside a slice. - */ - static get NumberOfPointsOffset() { - return 1; - } - /** - * Handles the creation of a performance viewer collector. - * @param _scene the scene to collect on. - * @param _enabledStrategyCallbacks the list of data to collect with callbacks for initialization purposes. - */ - constructor(_scene, _enabledStrategyCallbacks) { - this._scene = _scene; - /** - * Collects data for every dataset by using the appropriate strategy. This is called every frame. - * This method will then notify all observers with the latest slice. - */ - this._collectDataAtFrame = () => { - const timestamp = precisionDate_PrecisionDate.Now - this._startingTimestamp; - const numPoints = this.datasets.ids.length; - // add the starting index for the slice - const numberOfIndices = this.datasets.startingIndices.itemLength; - let startingIndex = 0; - if (numberOfIndices > 0) { - const previousStartingIndex = this.datasets.startingIndices.at(numberOfIndices - 1); - startingIndex = - previousStartingIndex + this.datasets.data.at(previousStartingIndex + PerformanceViewerCollector.NumberOfPointsOffset) + PerformanceViewerCollector.SliceDataOffset; - } - this.datasets.startingIndices.push(startingIndex); - // add the first 2 items in our slice. - this.datasets.data.push(timestamp); - this.datasets.data.push(numPoints); - // add the values inside the slice. - this.datasets.ids.forEach((id) => { - const strategy = this._strategies.get(id); - if (!strategy) { - return; - } - this.datasets.data.push(strategy.getData()); - }); - if (this.datasetObservable.hasObservers()) { - const slice = [timestamp, numPoints]; - for (let i = 0; i < numPoints; i++) { - slice.push(this.datasets.data.at(startingIndex + PerformanceViewerCollector.SliceDataOffset + i)); - } - this.datasetObservable.notifyObservers(slice); - } - }; - this.datasets = { - ids: [], - data: new DynamicFloat32Array(InitialArraySize), - startingIndices: new DynamicFloat32Array(InitialArraySize), - }; - this._strategies = new Map(); - this._datasetMeta = new Map(); - this._eventRestoreSet = new Set(); - this._customEventObservable = new observable_Observable(); - this.datasetObservable = new observable_Observable(); - this.metadataObservable = new observable_Observable((observer) => observer.callback(this._datasetMeta, new EventState(0))); - if (_enabledStrategyCallbacks) { - this.addCollectionStrategies(..._enabledStrategyCallbacks); - } - } - /** - * 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. - * 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, - * 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. - * @param name The name of the event to register - * @param forceUpdate if the code should force add an event, and replace the last one. - * @param category the category for that event - * @returns The event registered, used in sendEvent - */ - registerEvent(name, forceUpdate, category) { - var _a; - if (this._strategies.has(name) && !forceUpdate) { - return; - } - if (this._strategies.has(name) && forceUpdate) { - (_a = this._strategies.get(name)) === null || _a === void 0 ? void 0 : _a.dispose(); - this._strategies.delete(name); - } - const strategy = (scene) => { - let counter = 0; - let value = 0; - const afterRenderObserver = scene.onAfterRenderObservable.add(() => { - value = counter; - counter = 0; - }); - const stringObserver = this._customEventObservable.add((eventVal) => { - if (name !== eventVal.name) { - return; - } - if (eventVal.value !== undefined) { - counter = eventVal.value; - } - else { - counter++; - } - }); - return { - id: name, - getData: () => value, - dispose: () => { - scene.onAfterRenderObservable.remove(afterRenderObserver); - this._customEventObservable.remove(stringObserver); - }, - }; - }; - const event = { - name, - }; - this._eventRestoreSet.add(name); - this.addCollectionStrategies({ strategyCallback: strategy, category }); - return event; - } - /** - * Lets the perf collector handle an event, occurences or event value depending on if the event.value params is set. - * @param event the event to handle an occurence for - */ - sendEvent(event) { - this._customEventObservable.notifyObservers(event); - } - /** - * This event restores all custom string events if necessary. - */ - _restoreStringEvents() { - if (this._eventRestoreSet.size !== this._customEventObservable.observers.length) { - this._eventRestoreSet.forEach((event) => { - this.registerEvent(event, true); - }); - } - } - /** - * This method adds additional collection strategies for data collection purposes. - * @param strategyCallbacks the list of data to collect with callbacks. - */ - addCollectionStrategies(...strategyCallbacks) { - // eslint-disable-next-line prefer-const - for (let { strategyCallback, category, hidden } of strategyCallbacks) { - const strategy = strategyCallback(this._scene); - if (this._strategies.has(strategy.id)) { - strategy.dispose(); - continue; - } - this.datasets.ids.push(strategy.id); - if (category) { - category = category.replace(new RegExp(ExportedDataSeparator, "g"), ""); - } - this._datasetMeta.set(strategy.id, { - color: this._getHexColorFromId(strategy.id), - category, - hidden, - }); - this._strategies.set(strategy.id, strategy); - } - this.metadataObservable.notifyObservers(this._datasetMeta); - } - /** - * Gets a 6 character hexcode representing the colour from a passed in string. - * @param id the string to get a hex code for. - * @returns a hexcode hashed from the id. - */ - _getHexColorFromId(id) { - // this first bit is just a known way of hashing a string. - let hash = 0; - for (let i = 0; i < id.length; i++) { - // (hash << 5) - hash is the same as hash * 31 - hash = id.charCodeAt(i) + ((hash << 5) - hash); - } - // then we build the string octet by octet. - let hex = "#"; - for (let i = 0; i < NumberOfBitsInHexcode; i += 8) { - const octet = (hash >> i) & 0xff; - hex += (HexPadding + octet.toString(16)).substr(-2); - } - return hex; - } - /** - * Collects and then sends the latest slice to any observers by using the appropriate strategy when the user wants. - * The slice will be of the form [timestamp, numberOfPoints, value1, value2...] - * This method does not add onto the collected data accessible via the datasets variable. - */ - getCurrentSlice() { - const timestamp = precisionDate_PrecisionDate.Now - this._startingTimestamp; - const numPoints = this.datasets.ids.length; - const slice = [timestamp, numPoints]; - // add the values inside the slice. - this.datasets.ids.forEach((id) => { - const strategy = this._strategies.get(id); - if (!strategy) { - return; - } - if (this.datasetObservable.hasObservers()) { - slice.push(strategy.getData()); - } - }); - if (this.datasetObservable.hasObservers()) { - this.datasetObservable.notifyObservers(slice); - } - } - /** - * Updates a property for a dataset's metadata with the value provided. - * @param id the id of the dataset which needs its metadata updated. - * @param prop the property to update. - * @param value the value to update the property with. - */ - updateMetadata(id, prop, value) { - const meta = this._datasetMeta.get(id); - if (!meta) { - return; - } - meta[prop] = value; - this.metadataObservable.notifyObservers(this._datasetMeta); - } - /** - * Completely clear, data, ids, and strategies saved to this performance collector. - * @param preserveStringEventsRestore if it should preserve the string events, by default will clear string events registered when called. - */ - clear(preserveStringEventsRestore) { - this.datasets.data = new DynamicFloat32Array(InitialArraySize); - this.datasets.ids.length = 0; - this.datasets.startingIndices = new DynamicFloat32Array(InitialArraySize); - this._datasetMeta.clear(); - this._strategies.forEach((strategy) => strategy.dispose()); - this._strategies.clear(); - if (!preserveStringEventsRestore) { - this._eventRestoreSet.clear(); - } - this._hasLoadedData = false; - } - /** - * Accessor which lets the caller know if the performance collector has data loaded from a file or not! - * Call clear() to reset this value. - * @returns true if the data is loaded from a file, false otherwise. - */ - get hasLoadedData() { - return this._hasLoadedData; - } - /** - * Given a string containing file data, this function parses the file data into the datasets object. - * It returns a boolean to indicate if this object was successfully loaded with the data. - * @param data string content representing the file data. - * @param keepDatasetMeta if it should use reuse the existing dataset metadata - * @returns true if the data was successfully loaded, false otherwise. - */ - loadFromFileData(data, keepDatasetMeta) { - const lines = data - .replace(CarriageReturnRegex, "") - .split("\n") - .map((line) => line.split(",").filter((s) => s.length > 0)) - .filter((line) => line.length > 0); - const timestampIndex = 0; - const numPointsIndex = PerformanceViewerCollector.NumberOfPointsOffset; - if (lines.length < 2) { - return false; - } - const parsedDatasets = { - ids: [], - data: new DynamicFloat32Array(InitialArraySize), - startingIndices: new DynamicFloat32Array(InitialArraySize), - }; - // parse first line separately to populate ids! - const [firstLine, ...dataLines] = lines; - // make sure we have the correct beginning headers - if (firstLine.length < 2 || firstLine[timestampIndex] !== TimestampColHeader || firstLine[numPointsIndex] !== NumPointsColHeader) { - return false; - } - const idCategoryMap = new Map(); - // populate the ids. - for (let i = PerformanceViewerCollector.SliceDataOffset; i < firstLine.length; i++) { - const [id, category] = firstLine[i].split(ExportedDataSeparator); - parsedDatasets.ids.push(id); - idCategoryMap.set(id, category); - } - let startingIndex = 0; - for (const line of dataLines) { - if (line.length < 2) { - return false; - } - const timestamp = parseFloat(line[timestampIndex]); - const numPoints = parseInt(line[numPointsIndex]); - if (isNaN(numPoints) || isNaN(timestamp)) { - return false; - } - parsedDatasets.data.push(timestamp); - parsedDatasets.data.push(numPoints); - if (numPoints + PerformanceViewerCollector.SliceDataOffset !== line.length) { - return false; - } - for (let i = PerformanceViewerCollector.SliceDataOffset; i < line.length; i++) { - const val = parseFloat(line[i]); - if (isNaN(val)) { - return false; - } - parsedDatasets.data.push(val); - } - parsedDatasets.startingIndices.push(startingIndex); - startingIndex += line.length; - } - this.datasets.ids = parsedDatasets.ids; - this.datasets.data = parsedDatasets.data; - this.datasets.startingIndices = parsedDatasets.startingIndices; - if (!keepDatasetMeta) { - this._datasetMeta.clear(); - } - this._strategies.forEach((strategy) => strategy.dispose()); - this._strategies.clear(); - // populate metadata. - if (!keepDatasetMeta) { - for (const id of this.datasets.ids) { - const category = idCategoryMap.get(id); - this._datasetMeta.set(id, { category, color: this._getHexColorFromId(id) }); - } - } - this.metadataObservable.notifyObservers(this._datasetMeta); - this._hasLoadedData = true; - return true; - } - /** - * Exports the datasets inside of the collector to a csv. - */ - exportDataToCsv() { - let csvContent = ""; - // create the header line. - csvContent += `${TimestampColHeader},${NumPointsColHeader}`; - for (let i = 0; i < this.datasets.ids.length; i++) { - csvContent += `,${this.datasets.ids[i]}`; - if (this._datasetMeta) { - const meta = this._datasetMeta.get(this.datasets.ids[i]); - if (meta === null || meta === void 0 ? void 0 : meta.category) { - csvContent += `${ExportedDataSeparator}${meta.category}`; - } - } - } - csvContent += "\n"; - // create the data lines - for (let i = 0; i < this.datasets.startingIndices.itemLength; i++) { - const startingIndex = this.datasets.startingIndices.at(i); - const timestamp = this.datasets.data.at(startingIndex); - const numPoints = this.datasets.data.at(startingIndex + PerformanceViewerCollector.NumberOfPointsOffset); - csvContent += `${timestamp},${numPoints}`; - for (let offset = 0; offset < numPoints; offset++) { - csvContent += `,${this.datasets.data.at(startingIndex + PerformanceViewerCollector.SliceDataOffset + offset)}`; - } - // add extra commas. - for (let diff = 0; diff < this.datasets.ids.length - numPoints; diff++) { - csvContent += ","; - } - csvContent += "\n"; - } - const fileName = `${new Date().toISOString()}-perfdata.csv`; - tools_Tools.Download(new Blob([csvContent], { type: "text/csv" }), fileName); - } - /** - * Starts the realtime collection of data. - * @param shouldPreserve optional boolean param, if set will preserve the dataset between calls of start. - */ - start(shouldPreserve) { - if (!shouldPreserve) { - this.datasets.data = new DynamicFloat32Array(InitialArraySize); - this.datasets.startingIndices = new DynamicFloat32Array(InitialArraySize); - this._startingTimestamp = precisionDate_PrecisionDate.Now; - } - else if (this._startingTimestamp === undefined) { - this._startingTimestamp = precisionDate_PrecisionDate.Now; - } - this._scene.onAfterRenderObservable.add(this._collectDataAtFrame); - this._restoreStringEvents(); - this._isStarted = true; - } - /** - * Stops the collection of data. - */ - stop() { - this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame); - this._isStarted = false; - } - /** - * Returns if the perf collector has been started or not. - */ - get isStarted() { - return this._isStarted; - } - /** - * Disposes of the object - */ - dispose() { - this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame); - this._datasetMeta.clear(); - this._strategies.forEach((strategy) => { - strategy.dispose(); - }); - this.datasetObservable.clear(); - this.metadataObservable.clear(); - this._isStarted = false; - this.datasets = null; - } -} -//# sourceMappingURL=performanceViewerCollector.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerCollectionStrategies.js - - - - -// Dispose which does nothing. -const defaultDisposeImpl = () => { }; -/** - * Defines the predefined strategies used in the performance viewer. - */ -class PerfCollectionStrategy { - /** - * Gets the initializer for the strategy used for collection of fps metrics - * @returns the initializer for the fps strategy - */ - static FpsStrategy() { - return (scene) => { - const engine = scene.getEngine(); - return { - id: "FPS", - getData: () => engine.getFps(), - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of thermal utilization metrics. - * Needs the experimental pressure API. - * @returns the initializer for the thermal utilization strategy - */ - static ThermalStrategy() { - return this._PressureStrategy("Thermal utilization", "thermal"); - } - /** - * Gets the initializer for the strategy used for collection of power supply utilization metrics. - * Needs the experimental pressure API. - * @returns the initializer for the power supply utilization strategy - */ - static PowerSupplyStrategy() { - return this._PressureStrategy("Power supply utilization", "power-supply"); - } - /** - * Gets the initializer for the strategy used for collection of pressure metrics. - * Needs the experimental pressure API. - * @returns the initializer for the pressure strategy - */ - static PressureStrategy() { - return this._PressureStrategy("Pressure"); - } - static _PressureStrategy(name, factor = null) { - return () => { - let value = 0; - const wrapper = new PressureObserverWrapper(); - wrapper.observe("cpu"); - wrapper.onPressureChanged.add((update) => { - for (const record of update) { - if ((factor && record.factors.includes(factor)) || (!factor && record.factors.length === 0)) { - // Let s consider each step being 25% of the total pressure. - switch (record.state) { - case "nominal": - value = 0; - break; - case "fair": - value = 0.25; - break; - case "serious": - value = 0.5; - break; - case "critical": - value = 1; - break; - } - } - } - }); - return { - id: name, - getData: () => value, - dispose: () => wrapper.dispose(), - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of total meshes metrics. - * @returns the initializer for the total meshes strategy - */ - static TotalMeshesStrategy() { - return (scene) => { - return { - id: "Total meshes", - getData: () => scene.meshes.length, - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of active meshes metrics. - * @returns the initializer for the active meshes strategy - */ - static ActiveMeshesStrategy() { - return (scene) => { - return { - id: "Active meshes", - getData: () => scene.getActiveMeshes().length, - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of active indices metrics. - * @returns the initializer for the active indices strategy - */ - static ActiveIndicesStrategy() { - return (scene) => { - return { - id: "Active indices", - getData: () => scene.getActiveIndices(), - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of active faces metrics. - * @returns the initializer for the active faces strategy - */ - static ActiveFacesStrategy() { - return (scene) => { - return { - id: "Active faces", - getData: () => scene.getActiveIndices() / 3, - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of active bones metrics. - * @returns the initializer for the active bones strategy - */ - static ActiveBonesStrategy() { - return (scene) => { - return { - id: "Active bones", - getData: () => scene.getActiveBones(), - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of active particles metrics. - * @returns the initializer for the active particles strategy - */ - static ActiveParticlesStrategy() { - return (scene) => { - return { - id: "Active particles", - getData: () => scene.getActiveParticles(), - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of draw calls metrics. - * @returns the initializer for the draw calls strategy - */ - static DrawCallsStrategy() { - return (scene) => { - let drawCalls = 0; - const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => { - scene.getEngine()._drawCalls.fetchNewFrame(); - }); - const onAfterRenderObserver = scene.onAfterRenderObservable.add(() => { - drawCalls = scene.getEngine()._drawCalls.current; - }); - return { - id: "Draw calls", - getData: () => drawCalls, - dispose: () => { - scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver); - scene.onAfterRenderObservable.remove(onAfterRenderObserver); - }, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of total lights metrics. - * @returns the initializer for the total lights strategy - */ - static TotalLightsStrategy() { - return (scene) => { - return { - id: "Total lights", - getData: () => scene.lights.length, - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of total vertices metrics. - * @returns the initializer for the total vertices strategy - */ - static TotalVerticesStrategy() { - return (scene) => { - return { - id: "Total vertices", - getData: () => scene.getTotalVertices(), - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of total materials metrics. - * @returns the initializer for the total materials strategy - */ - static TotalMaterialsStrategy() { - return (scene) => { - return { - id: "Total materials", - getData: () => scene.materials.length, - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of total textures metrics. - * @returns the initializer for the total textures strategy - */ - static TotalTexturesStrategy() { - return (scene) => { - return { - id: "Total textures", - getData: () => scene.textures.length, - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of absolute fps metrics. - * @returns the initializer for the absolute fps strategy - */ - static AbsoluteFpsStrategy() { - return (scene) => { - const sceneInstrumentation = new SceneInstrumentation(scene); - sceneInstrumentation.captureFrameTime = true; - return { - id: "Absolute FPS", - getData: () => { - return 1000.0 / sceneInstrumentation.frameTimeCounter.lastSecAverage; - }, - dispose: defaultDisposeImpl, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of meshes selection time metrics. - * @returns the initializer for the meshes selection time strategy - */ - static MeshesSelectionStrategy() { - return (scene) => { - let startTime = PrecisionDate.Now; - let timeTaken = 0; - const onBeforeActiveMeshesObserver = scene.onBeforeActiveMeshesEvaluationObservable.add(() => { - startTime = PrecisionDate.Now; - }); - const onAfterActiveMeshesObserver = scene.onAfterActiveMeshesEvaluationObservable.add(() => { - timeTaken = PrecisionDate.Now - startTime; - }); - return { - id: "Meshes Selection", - getData: () => timeTaken, - dispose: () => { - scene.onBeforeActiveMeshesEvaluationObservable.remove(onBeforeActiveMeshesObserver); - scene.onAfterActiveMeshesEvaluationObservable.remove(onAfterActiveMeshesObserver); - }, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of render targets time metrics. - * @returns the initializer for the render targets time strategy - */ - static RenderTargetsStrategy() { - return (scene) => { - let startTime = PrecisionDate.Now; - let timeTaken = 0; - const onBeforeRenderTargetsObserver = scene.onBeforeRenderTargetsRenderObservable.add(() => { - startTime = PrecisionDate.Now; - }); - const onAfterRenderTargetsObserver = scene.onAfterRenderTargetsRenderObservable.add(() => { - timeTaken = PrecisionDate.Now - startTime; - }); - return { - id: "Render Targets", - getData: () => timeTaken, - dispose: () => { - scene.onBeforeRenderTargetsRenderObservable.remove(onBeforeRenderTargetsObserver); - scene.onAfterRenderTargetsRenderObservable.remove(onAfterRenderTargetsObserver); - }, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of particles time metrics. - * @returns the initializer for the particles time strategy - */ - static ParticlesStrategy() { - return (scene) => { - let startTime = PrecisionDate.Now; - let timeTaken = 0; - const onBeforeParticlesObserver = scene.onBeforeParticlesRenderingObservable.add(() => { - startTime = PrecisionDate.Now; - }); - const onAfterParticlesObserver = scene.onAfterParticlesRenderingObservable.add(() => { - timeTaken = PrecisionDate.Now - startTime; - }); - return { - id: "Particles", - getData: () => timeTaken, - dispose: () => { - scene.onBeforeParticlesRenderingObservable.remove(onBeforeParticlesObserver); - scene.onAfterParticlesRenderingObservable.remove(onAfterParticlesObserver); - }, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of sprites time metrics. - * @returns the initializer for the sprites time strategy - */ - static SpritesStrategy() { - return (scene) => { - var _a, _b; - let startTime = PrecisionDate.Now; - let timeTaken = 0; - const onBeforeSpritesObserver = (_a = scene.onBeforeSpritesRenderingObservable) === null || _a === void 0 ? void 0 : _a.add(() => { - startTime = PrecisionDate.Now; - }); - const onAfterSpritesObserver = (_b = scene.onAfterSpritesRenderingObservable) === null || _b === void 0 ? void 0 : _b.add(() => { - timeTaken = PrecisionDate.Now - startTime; - }); - return { - id: "Sprites", - getData: () => timeTaken, - dispose: () => { - var _a, _b; - (_a = scene.onBeforeSpritesRenderingObservable) === null || _a === void 0 ? void 0 : _a.remove(onBeforeSpritesObserver); - (_b = scene.onAfterSpritesRenderingObservable) === null || _b === void 0 ? void 0 : _b.remove(onAfterSpritesObserver); - }, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of animations time metrics. - * @returns the initializer for the animations time strategy - */ - static AnimationsStrategy() { - return (scene) => { - let startTime = PrecisionDate.Now; - let timeTaken = 0; - const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => { - startTime = PrecisionDate.Now; - }); - const onAfterAnimationsObserver = scene.onAfterAnimationsObservable.add(() => { - timeTaken = PrecisionDate.Now - startTime; - }); - return { - id: "Animations", - getData: () => timeTaken, - dispose: () => { - scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver); - scene.onAfterAnimationsObservable.remove(onAfterAnimationsObserver); - }, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of physics time metrics. - * @returns the initializer for the physics time strategy - */ - static PhysicsStrategy() { - return (scene) => { - var _a, _b; - let startTime = PrecisionDate.Now; - let timeTaken = 0; - const onBeforePhysicsObserver = (_a = scene.onBeforePhysicsObservable) === null || _a === void 0 ? void 0 : _a.add(() => { - startTime = PrecisionDate.Now; - }); - const onAfterPhysicsObserver = (_b = scene.onAfterPhysicsObservable) === null || _b === void 0 ? void 0 : _b.add(() => { - timeTaken = PrecisionDate.Now - startTime; - }); - return { - id: "Physics", - getData: () => timeTaken, - dispose: () => { - var _a, _b; - (_a = scene.onBeforePhysicsObservable) === null || _a === void 0 ? void 0 : _a.remove(onBeforePhysicsObserver); - (_b = scene.onAfterPhysicsObservable) === null || _b === void 0 ? void 0 : _b.remove(onAfterPhysicsObserver); - }, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of render time metrics. - * @returns the initializer for the render time strategy - */ - static RenderStrategy() { - return (scene) => { - let startTime = PrecisionDate.Now; - let timeTaken = 0; - const onBeforeDrawPhaseObserver = scene.onBeforeDrawPhaseObservable.add(() => { - startTime = PrecisionDate.Now; - }); - const onAfterDrawPhaseObserver = scene.onAfterDrawPhaseObservable.add(() => { - timeTaken = PrecisionDate.Now - startTime; - }); - return { - id: "Render", - getData: () => timeTaken, - dispose: () => { - scene.onBeforeDrawPhaseObservable.remove(onBeforeDrawPhaseObserver); - scene.onAfterDrawPhaseObservable.remove(onAfterDrawPhaseObserver); - }, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of total frame time metrics. - * @returns the initializer for the total frame time strategy - */ - static FrameTotalStrategy() { - return (scene) => { - let startTime = PrecisionDate.Now; - let timeTaken = 0; - const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => { - startTime = PrecisionDate.Now; - }); - const onAfterRenderObserver = scene.onAfterRenderObservable.add(() => { - timeTaken = PrecisionDate.Now - startTime; - }); - return { - id: "Frame Total", - getData: () => timeTaken, - dispose: () => { - scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver); - scene.onAfterRenderObservable.remove(onAfterRenderObserver); - }, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of inter-frame time metrics. - * @returns the initializer for the inter-frame time strategy - */ - static InterFrameStrategy() { - return (scene) => { - let startTime = PrecisionDate.Now; - let timeTaken = 0; - const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => { - timeTaken = PrecisionDate.Now - startTime; - }); - const onAfterRenderObserver = scene.onAfterRenderObservable.add(() => { - startTime = PrecisionDate.Now; - }); - return { - id: "Inter-frame", - getData: () => timeTaken, - dispose: () => { - scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver); - scene.onAfterRenderObservable.remove(onAfterRenderObserver); - }, - }; - }; - } - /** - * Gets the initializer for the strategy used for collection of gpu frame time metrics. - * @returns the initializer for the gpu frame time strategy - */ - static GpuFrameTimeStrategy() { - return (scene) => { - const engineInstrumentation = new EngineInstrumentation(scene.getEngine()); - engineInstrumentation.captureGPUFrameTime = true; - return { - id: "GPU frame time", - getData: () => Math.max(engineInstrumentation.gpuFrameTimeCounter.current * 0.000001, 0), - dispose: () => { - engineInstrumentation.dispose(); - }, - }; - }; - } -} -//# sourceMappingURL=performanceViewerCollectionStrategies.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerSceneExtension.js - - -scene_Scene.prototype.getPerfCollector = function () { - if (!this._perfCollector) { - this._perfCollector = new PerformanceViewerCollector(this); - } - return this._perfCollector; -}; -//# sourceMappingURL=performanceViewerSceneExtension.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/PerformanceViewer/index.js -/* eslint-disable import/export */ - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/observableCoroutine.js - - -function CreateObservableScheduler(observable) { - const coroutines = new Array(); - const onSteps = new Array(); - const onErrors = new Array(); - const observer = observable.add(() => { - const count = coroutines.length; - for (let i = 0; i < count; i++) { - inlineScheduler(coroutines.shift(), onSteps.shift(), onErrors.shift()); - } - }); - const scheduler = (coroutine, onStep, onError) => { - coroutines.push(coroutine); - onSteps.push(onStep); - onErrors.push(onError); - }; - return { - scheduler: scheduler, - dispose: () => { - observable.remove(observer); - }, - }; -} -observable_Observable.prototype.runCoroutineAsync = function (coroutine) { - if (!this._coroutineScheduler) { - const schedulerAndDispose = CreateObservableScheduler(this); - this._coroutineScheduler = schedulerAndDispose.scheduler; - this._coroutineSchedulerDispose = schedulerAndDispose.dispose; - } - return runCoroutineAsync(coroutine, this._coroutineScheduler); -}; -observable_Observable.prototype.cancelAllCoroutines = function () { - if (this._coroutineSchedulerDispose) { - this._coroutineSchedulerDispose(); - } - this._coroutineScheduler = undefined; - this._coroutineSchedulerDispose = undefined; -}; -//# sourceMappingURL=observableCoroutine.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Misc/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -// eslint-disable-next-line import/export - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRHitTestLegacy.js - - - - - -/** - * The currently-working hit-test module. - * Hit test (or Ray-casting) is used to interact with the real world. - * For further information read here - https://github.com/immersive-web/hit-test - */ -class WebXRHitTestLegacy extends WebXRAbstractFeature { - /** - * Creates a new instance of the (legacy version) hit test feature - * @param _xrSessionManager an instance of WebXRSessionManager - * @param options options to use when constructing this feature - */ - constructor(_xrSessionManager, - /** - * options to use when constructing this feature - */ - options = {}) { - super(_xrSessionManager); - this.options = options; - // in XR space z-forward is negative - this._direction = new math_vector_Vector3(0, 0, -1); - this._mat = new math_vector_Matrix(); - this._onSelectEnabled = false; - this._origin = new math_vector_Vector3(0, 0, 0); - /** - * Populated with the last native XR Hit Results - */ - this.lastNativeXRHitResults = []; - /** - * Triggered when new babylon (transformed) hit test results are available - */ - this.onHitTestResultObservable = new observable_Observable(); - this._onHitTestResults = (xrResults) => { - const mats = xrResults.map((result) => { - const mat = math_vector_Matrix.FromArray(result.hitMatrix); - if (!this._xrSessionManager.scene.useRightHandedSystem) { - mat.toggleModelMatrixHandInPlace(); - } - // if (this.options.coordinatesSpace === Space.WORLD) { - if (this.options.worldParentNode) { - mat.multiplyToRef(this.options.worldParentNode.getWorldMatrix(), mat); - } - return { - xrHitResult: result, - transformationMatrix: mat, - }; - }); - this.lastNativeXRHitResults = xrResults; - this.onHitTestResultObservable.notifyObservers(mats); - }; - // can be done using pointerdown event, and xrSessionManager.currentFrame - this._onSelect = (event) => { - if (!this._onSelectEnabled) { - return; - } - WebXRHitTestLegacy.XRHitTestWithSelectEvent(event, this._xrSessionManager.referenceSpace); - }; - this.xrNativeFeatureName = "hit-test"; - tools_Tools.Warn("A newer version of this plugin is available"); - } - /** - * execute a hit test with an XR Ray - * - * @param xrSession a native xrSession that will execute this hit test - * @param xrRay the ray (position and direction) to use for ray-casting - * @param referenceSpace native XR reference space to use for the hit-test - * @param filter filter function that will filter the results - * @returns a promise that resolves with an array of native XR hit result in xr coordinates system - */ - static XRHitTestWithRay(xrSession, xrRay, referenceSpace, filter) { - return xrSession.requestHitTest(xrRay, referenceSpace).then((results) => { - const filterFunction = filter || ((result) => !!result.hitMatrix); - return results.filter(filterFunction); - }); - } - /** - * Execute a hit test on the current running session using a select event returned from a transient input (such as touch) - * @param event the (select) event to use to select with - * @param referenceSpace the reference space to use for this hit test - * @returns a promise that resolves with an array of native XR hit result in xr coordinates system - */ - static XRHitTestWithSelectEvent(event, referenceSpace) { - const targetRayPose = event.frame.getPose(event.inputSource.targetRaySpace, referenceSpace); - if (!targetRayPose) { - return Promise.resolve([]); - } - const targetRay = new XRRay(targetRayPose.transform); - return this.XRHitTestWithRay(event.frame.session, targetRay, referenceSpace); - } - /** - * attach this feature - * Will usually be called by the features manager - * - * @returns true if successful. - */ - attach() { - if (!super.attach()) { - return false; - } - if (this.options.testOnPointerDownOnly) { - this._xrSessionManager.session.addEventListener("select", this._onSelect, false); - } - return true; - } - /** - * detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - if (!super.detach()) { - return false; - } - // disable select - this._onSelectEnabled = false; - this._xrSessionManager.session.removeEventListener("select", this._onSelect); - return true; - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - super.dispose(); - this.onHitTestResultObservable.clear(); - } - _onXRFrame(frame) { - // make sure we do nothing if (async) not attached - if (!this.attached || this.options.testOnPointerDownOnly) { - return; - } - const pose = frame.getViewerPose(this._xrSessionManager.referenceSpace); - if (!pose) { - return; - } - math_vector_Matrix.FromArrayToRef(pose.transform.matrix, 0, this._mat); - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, this._mat, this._origin); - math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0, 0, -1, this._mat, this._direction); - this._direction.subtractInPlace(this._origin); - this._direction.normalize(); - 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 }); - WebXRHitTestLegacy.XRHitTestWithRay(this._xrSessionManager.session, ray, this._xrSessionManager.referenceSpace).then(this._onHitTestResults); - } -} -/** - * The module's name - */ -WebXRHitTestLegacy.Name = webXRFeaturesManager_WebXRFeatureName.HIT_TEST; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRHitTestLegacy.Version = 1; -//register the plugin versions -WebXRFeaturesManager.AddWebXRFeature(WebXRHitTestLegacy.Name, (xrSessionManager, options) => { - return () => new WebXRHitTestLegacy(xrSessionManager, options); -}, WebXRHitTestLegacy.Version, false); -//# sourceMappingURL=WebXRHitTestLegacy.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRAnchorSystem.js - - - - - -let anchorIdProvider = 0; -/** - * An implementation of the anchor system for WebXR. - * For further information see https://github.com/immersive-web/anchors/ - */ -class WebXRAnchorSystem extends WebXRAbstractFeature { - /** - * Set the reference space to use for anchor creation, when not using a hit test. - * Will default to the session's reference space if not defined - */ - set referenceSpaceForFrameAnchors(referenceSpace) { - this._referenceSpaceForFrameAnchors = referenceSpace; - } - /** - * constructs a new anchor system - * @param _xrSessionManager an instance of WebXRSessionManager - * @param _options configuration object for this feature - */ - constructor(_xrSessionManager, _options = {}) { - super(_xrSessionManager); - this._options = _options; - this._lastFrameDetected = new Set(); - this._trackedAnchors = []; - this._futureAnchors = []; - /** - * Observers registered here will be executed when a new anchor was added to the session - */ - this.onAnchorAddedObservable = new observable_Observable(); - /** - * Observers registered here will be executed when an anchor was removed from the session - */ - this.onAnchorRemovedObservable = new observable_Observable(); - /** - * Observers registered here will be executed when an existing anchor updates - * This can execute N times every frame - */ - this.onAnchorUpdatedObservable = new observable_Observable(); - this._tmpVector = new math_vector_Vector3(); - this._tmpQuaternion = new math_vector_Quaternion(); - this.xrNativeFeatureName = "anchors"; - } - _populateTmpTransformation(position, rotationQuaternion) { - this._tmpVector.copyFrom(position); - this._tmpQuaternion.copyFrom(rotationQuaternion); - if (!this._xrSessionManager.scene.useRightHandedSystem) { - this._tmpVector.z *= -1; - this._tmpQuaternion.z *= -1; - this._tmpQuaternion.w *= -1; - } - return { - position: this._tmpVector, - rotationQuaternion: this._tmpQuaternion, - }; - } - /** - * Create a new anchor point using a hit test result at a specific point in the scene - * An anchor is tracked only after it is added to the trackerAnchors in xrFrame. The promise returned here does not yet guaranty that. - * Use onAnchorAddedObservable to get newly added anchors if you require tracking guaranty. - * - * @param hitTestResult The hit test result to use for this anchor creation - * @param position an optional position offset for this anchor - * @param rotationQuaternion an optional rotation offset for this anchor - * @returns A promise that fulfills when babylon has created the corresponding WebXRAnchor object and tracking has begun - */ - async addAnchorPointUsingHitTestResultAsync(hitTestResult, position = new math_vector_Vector3(), rotationQuaternion = new math_vector_Quaternion()) { - // convert to XR space (right handed) if needed - this._populateTmpTransformation(position, rotationQuaternion); - // the matrix that we'll use - 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 }); - if (!hitTestResult.xrHitResult.createAnchor) { - this.detach(); - throw new Error("Anchors not enabled in this environment/browser"); - } - else { - try { - const nativeAnchor = await hitTestResult.xrHitResult.createAnchor(m); - return new Promise((resolve, reject) => { - this._futureAnchors.push({ - nativeAnchor, - resolved: false, - submitted: true, - xrTransformation: m, - resolve, - reject, - }); - }); - } - catch (error) { - throw new Error(error); - } - } - } - /** - * Add a new anchor at a specific position and rotation - * This function will add a new anchor per default in the next available frame. Unless forced, the createAnchor function - * will be called in the next xrFrame loop to make sure that the anchor can be created correctly. - * An anchor is tracked only after it is added to the trackerAnchors in xrFrame. The promise returned here does not yet guaranty that. - * Use onAnchorAddedObservable to get newly added anchors if you require tracking guaranty. - * - * @param position the position in which to add an anchor - * @param rotationQuaternion an optional rotation for the anchor transformation - * @param forceCreateInCurrentFrame force the creation of this anchor in the current frame. Must be called inside xrFrame loop! - * @returns A promise that fulfills when babylon has created the corresponding WebXRAnchor object and tracking has begun - */ - async addAnchorAtPositionAndRotationAsync(position, rotationQuaternion = new math_vector_Quaternion(), forceCreateInCurrentFrame = false) { - // convert to XR space (right handed) if needed - this._populateTmpTransformation(position, rotationQuaternion); - // the matrix that we'll use - 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 }); - const xrAnchor = forceCreateInCurrentFrame && this.attached && this._xrSessionManager.currentFrame - ? await this._createAnchorAtTransformation(xrTransformation, this._xrSessionManager.currentFrame) - : undefined; - // add the transformation to the future anchors list - return new Promise((resolve, reject) => { - this._futureAnchors.push({ - nativeAnchor: xrAnchor, - resolved: false, - submitted: false, - xrTransformation, - resolve, - reject, - }); - }); - } - /** - * Get the list of anchors currently being tracked by the system - */ - get anchors() { - return this._trackedAnchors; - } - /** - * detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - if (!super.detach()) { - return false; - } - if (!this._options.doNotRemoveAnchorsOnSessionEnded) { - while (this._trackedAnchors.length) { - const toRemove = this._trackedAnchors.pop(); - if (toRemove) { - try { - // try to natively remove it as well - toRemove.remove(); - } - catch (e) { - // no-op - } - // as the xr frame loop is removed, we need to notify manually - this.onAnchorRemovedObservable.notifyObservers(toRemove); - } - } - } - return true; - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - this._futureAnchors.length = 0; - super.dispose(); - this.onAnchorAddedObservable.clear(); - this.onAnchorRemovedObservable.clear(); - this.onAnchorUpdatedObservable.clear(); - } - _onXRFrame(frame) { - if (!this.attached || !frame) { - return; - } - const trackedAnchors = frame.trackedAnchors; - if (trackedAnchors) { - const toRemove = this._trackedAnchors - .filter((anchor) => !trackedAnchors.has(anchor.xrAnchor)) - .map((anchor) => { - const index = this._trackedAnchors.indexOf(anchor); - return index; - }); - let idxTracker = 0; - toRemove.forEach((index) => { - const anchor = this._trackedAnchors.splice(index - idxTracker, 1)[0]; - this.onAnchorRemovedObservable.notifyObservers(anchor); - idxTracker++; - }); - // now check for new ones - trackedAnchors.forEach((xrAnchor) => { - if (!this._lastFrameDetected.has(xrAnchor)) { - const newAnchor = { - id: anchorIdProvider++, - xrAnchor: xrAnchor, - remove: () => xrAnchor.delete(), - }; - const anchor = this._updateAnchorWithXRFrame(xrAnchor, newAnchor, frame); - this._trackedAnchors.push(anchor); - this.onAnchorAddedObservable.notifyObservers(anchor); - // search for the future anchor promise that matches this - const results = this._futureAnchors.filter((futureAnchor) => futureAnchor.nativeAnchor === xrAnchor); - const result = results[0]; - if (result) { - result.resolve(anchor); - result.resolved = true; - } - } - else { - const index = this._findIndexInAnchorArray(xrAnchor); - const anchor = this._trackedAnchors[index]; - try { - // anchors update every frame - this._updateAnchorWithXRFrame(xrAnchor, anchor, frame); - if (anchor.attachedNode) { - anchor.attachedNode.rotationQuaternion = anchor.attachedNode.rotationQuaternion || new math_vector_Quaternion(); - anchor.transformationMatrix.decompose(anchor.attachedNode.scaling, anchor.attachedNode.rotationQuaternion, anchor.attachedNode.position); - } - this.onAnchorUpdatedObservable.notifyObservers(anchor); - } - catch (e) { - tools_Tools.Warn(`Anchor could not be updated`); - } - } - }); - this._lastFrameDetected = trackedAnchors; - } - // process future anchors - this._futureAnchors.forEach((futureAnchor) => { - if (!futureAnchor.resolved && !futureAnchor.submitted) { - this._createAnchorAtTransformation(futureAnchor.xrTransformation, frame).then((nativeAnchor) => { - futureAnchor.nativeAnchor = nativeAnchor; - }, (error) => { - futureAnchor.resolved = true; - futureAnchor.reject(error); - }); - futureAnchor.submitted = true; - } - }); - } - /** - * avoiding using Array.find for global support. - * @param xrAnchor the plane to find in the array - */ - _findIndexInAnchorArray(xrAnchor) { - for (let i = 0; i < this._trackedAnchors.length; ++i) { - if (this._trackedAnchors[i].xrAnchor === xrAnchor) { - return i; - } - } - return -1; - } - _updateAnchorWithXRFrame(xrAnchor, anchor, xrFrame) { - // matrix - const pose = xrFrame.getPose(xrAnchor.anchorSpace, this._xrSessionManager.referenceSpace); - if (pose) { - const mat = anchor.transformationMatrix || new math_vector_Matrix(); - math_vector_Matrix.FromArrayToRef(pose.transform.matrix, 0, mat); - if (!this._xrSessionManager.scene.useRightHandedSystem) { - mat.toggleModelMatrixHandInPlace(); - } - anchor.transformationMatrix = mat; - if (!this._options.worldParentNode) { - // Logger.Warn("Please provide a world parent node to apply world transformation"); - } - else { - mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat); - } - } - return anchor; - } - async _createAnchorAtTransformation(xrTransformation, xrFrame) { - var _a; - if (xrFrame.createAnchor) { - try { - return xrFrame.createAnchor(xrTransformation, (_a = this._referenceSpaceForFrameAnchors) !== null && _a !== void 0 ? _a : this._xrSessionManager.referenceSpace); - } - catch (error) { - throw new Error(error); - } - } - else { - this.detach(); - throw new Error("Anchors are not enabled in your browser"); - } - } -} -/** - * The module's name - */ -WebXRAnchorSystem.Name = webXRFeaturesManager_WebXRFeatureName.ANCHOR_SYSTEM; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRAnchorSystem.Version = 1; -// register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRAnchorSystem.Name, (xrSessionManager, options) => { - return () => new WebXRAnchorSystem(xrSessionManager, options); -}, WebXRAnchorSystem.Version); -//# sourceMappingURL=WebXRAnchorSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRPlaneDetector.js - - - - -let planeIdProvider = 0; -/** - * The plane detector is used to detect planes in the real world when in AR - * For more information see https://github.com/immersive-web/real-world-geometry/ - */ -class WebXRPlaneDetector extends WebXRAbstractFeature { - /** - * construct a new Plane Detector - * @param _xrSessionManager an instance of xr Session manager - * @param _options configuration to use when constructing this feature - */ - constructor(_xrSessionManager, _options = {}) { - super(_xrSessionManager); - this._options = _options; - this._detectedPlanes = []; - this._enabled = false; - this._lastFrameDetected = new Set(); - /** - * Observers registered here will be executed when a new plane was added to the session - */ - this.onPlaneAddedObservable = new observable_Observable(); - /** - * Observers registered here will be executed when a plane is no longer detected in the session - */ - this.onPlaneRemovedObservable = new observable_Observable(); - /** - * Observers registered here will be executed when an existing plane updates (for example - expanded) - * This can execute N times every frame - */ - this.onPlaneUpdatedObservable = new observable_Observable(); - this.xrNativeFeatureName = "plane-detection"; - if (this._xrSessionManager.session) { - this._init(); - } - else { - this._xrSessionManager.onXRSessionInit.addOnce(() => { - this._init(); - }); - } - } - /** - * detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - if (!super.detach()) { - return false; - } - if (!this._options.doNotRemovePlanesOnSessionEnded) { - while (this._detectedPlanes.length) { - const toRemove = this._detectedPlanes.pop(); - if (toRemove) { - this.onPlaneRemovedObservable.notifyObservers(toRemove); - } - } - } - return true; - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - super.dispose(); - this.onPlaneAddedObservable.clear(); - this.onPlaneRemovedObservable.clear(); - this.onPlaneUpdatedObservable.clear(); - } - /** - * Check if the needed objects are defined. - * This does not mean that the feature is enabled, but that the objects needed are well defined. - */ - isCompatible() { - return typeof XRPlane !== "undefined"; - } - _onXRFrame(frame) { - var _a; - if (!this.attached || !this._enabled || !frame) { - return; - } - const detectedPlanes = frame.detectedPlanes || ((_a = frame.worldInformation) === null || _a === void 0 ? void 0 : _a.detectedPlanes); - if (detectedPlanes) { - // remove all planes that are not currently detected in the frame - for (let planeIdx = 0; planeIdx < this._detectedPlanes.length; planeIdx++) { - const plane = this._detectedPlanes[planeIdx]; - if (!detectedPlanes.has(plane.xrPlane)) { - this._detectedPlanes.splice(planeIdx--, 1); - this.onPlaneRemovedObservable.notifyObservers(plane); - } - } - // now check for new ones - detectedPlanes.forEach((xrPlane) => { - if (!this._lastFrameDetected.has(xrPlane)) { - const newPlane = { - id: planeIdProvider++, - xrPlane: xrPlane, - polygonDefinition: [], - }; - const plane = this._updatePlaneWithXRPlane(xrPlane, newPlane, frame); - this._detectedPlanes.push(plane); - this.onPlaneAddedObservable.notifyObservers(plane); - } - else { - // updated? - if (xrPlane.lastChangedTime === this._xrSessionManager.currentTimestamp) { - const index = this._findIndexInPlaneArray(xrPlane); - const plane = this._detectedPlanes[index]; - this._updatePlaneWithXRPlane(xrPlane, plane, frame); - this.onPlaneUpdatedObservable.notifyObservers(plane); - } - } - }); - this._lastFrameDetected = detectedPlanes; - } - } - _init() { - const internalInit = () => { - this._enabled = true; - if (this._detectedPlanes.length) { - this._detectedPlanes.length = 0; - } - }; - // Only supported by BabylonNative - if (!!this._xrSessionManager.isNative && !!this._options.preferredDetectorOptions && !!this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions) { - this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions); - } - if (!this._xrSessionManager.session.updateWorldTrackingState) { - internalInit(); - return; - } - this._xrSessionManager.session.updateWorldTrackingState({ planeDetectionState: { enabled: true } }); - internalInit(); - } - _updatePlaneWithXRPlane(xrPlane, plane, xrFrame) { - plane.polygonDefinition = xrPlane.polygon.map((xrPoint) => { - const rightHandedSystem = this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1; - return new math_vector_Vector3(xrPoint.x, xrPoint.y, xrPoint.z * rightHandedSystem); - }); - // matrix - const pose = xrFrame.getPose(xrPlane.planeSpace, this._xrSessionManager.referenceSpace); - if (pose) { - const mat = plane.transformationMatrix || new math_vector_Matrix(); - math_vector_Matrix.FromArrayToRef(pose.transform.matrix, 0, mat); - if (!this._xrSessionManager.scene.useRightHandedSystem) { - mat.toggleModelMatrixHandInPlace(); - } - plane.transformationMatrix = mat; - if (this._options.worldParentNode) { - mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat); - } - } - return plane; - } - /** - * avoiding using Array.find for global support. - * @param xrPlane the plane to find in the array - */ - _findIndexInPlaneArray(xrPlane) { - for (let i = 0; i < this._detectedPlanes.length; ++i) { - if (this._detectedPlanes[i].xrPlane === xrPlane) { - return i; - } - } - return -1; - } -} -/** - * The module's name - */ -WebXRPlaneDetector.Name = webXRFeaturesManager_WebXRFeatureName.PLANE_DETECTION; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRPlaneDetector.Version = 1; -//register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRPlaneDetector.Name, (xrSessionManager, options) => { - return () => new WebXRPlaneDetector(xrSessionManager, options); -}, WebXRPlaneDetector.Version); -//# sourceMappingURL=WebXRPlaneDetector.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRBackgroundRemover.js - - - -/** - * A module that will automatically disable background meshes when entering AR and will enable them when leaving AR. - */ -class WebXRBackgroundRemover extends WebXRAbstractFeature { - /** - * constructs a new background remover module - * @param _xrSessionManager the session manager for this module - * @param options read-only options to be used in this module - */ - constructor(_xrSessionManager, - /** - * read-only options to be used in this module - */ - options = {}) { - super(_xrSessionManager); - this.options = options; - /** - * registered observers will be triggered when the background state changes - */ - this.onBackgroundStateChangedObservable = new observable_Observable(); - } - /** - * attach this feature - * Will usually be called by the features manager - * - * @returns true if successful. - */ - attach() { - this._setBackgroundState(false); - return super.attach(); - } - /** - * detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - this._setBackgroundState(true); - return super.detach(); - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - super.dispose(); - this.onBackgroundStateChangedObservable.clear(); - } - _onXRFrame(_xrFrame) { - // no-op - } - _setBackgroundState(newState) { - const scene = this._xrSessionManager.scene; - if (!this.options.ignoreEnvironmentHelper) { - if (this.options.environmentHelperRemovalFlags) { - if (this.options.environmentHelperRemovalFlags.skyBox) { - const backgroundSkybox = scene.getMeshByName("BackgroundSkybox"); - if (backgroundSkybox) { - backgroundSkybox.setEnabled(newState); - } - } - if (this.options.environmentHelperRemovalFlags.ground) { - const backgroundPlane = scene.getMeshByName("BackgroundPlane"); - if (backgroundPlane) { - backgroundPlane.setEnabled(newState); - } - } - } - else { - const backgroundHelper = scene.getMeshByName("BackgroundHelper"); - if (backgroundHelper) { - backgroundHelper.setEnabled(newState); - } - } - } - if (this.options.backgroundMeshes) { - this.options.backgroundMeshes.forEach((mesh) => mesh.setEnabled(newState)); - } - this.onBackgroundStateChangedObservable.notifyObservers(newState); - } -} -/** - * The module's name - */ -WebXRBackgroundRemover.Name = webXRFeaturesManager_WebXRFeatureName.BACKGROUND_REMOVER; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRBackgroundRemover.Version = 1; -//register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRBackgroundRemover.Name, (xrSessionManager, options) => { - return () => new WebXRBackgroundRemover(xrSessionManager, options); -}, WebXRBackgroundRemover.Version, true); -//# sourceMappingURL=WebXRBackgroundRemover.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRControllerPhysics.js - - - - - - -/** - * Options for the controller physics feature - */ -class IWebXRControllerPhysicsOptions { -} -/** - * Add physics impostor to your webxr controllers, - * including naive calculation of their linear and angular velocity - */ -class WebXRControllerPhysics extends WebXRAbstractFeature { - _createPhysicsImpostor(xrController) { - const impostorType = this._options.physicsProperties.impostorType || physicsImpostor_PhysicsImpostor.SphereImpostor; - const impostorSize = this._options.physicsProperties.impostorSize || 0.1; - const impostorMesh = sphereBuilder_CreateSphere("impostor-mesh-" + xrController.uniqueId, { - diameterX: typeof impostorSize === "number" ? impostorSize : impostorSize.width, - diameterY: typeof impostorSize === "number" ? impostorSize : impostorSize.height, - diameterZ: typeof impostorSize === "number" ? impostorSize : impostorSize.depth, - }); - impostorMesh.isVisible = this._debugMode; - impostorMesh.isPickable = false; - impostorMesh.rotationQuaternion = new math_vector_Quaternion(); - const controllerMesh = xrController.grip || xrController.pointer; - impostorMesh.position.copyFrom(controllerMesh.position); - impostorMesh.rotationQuaternion.copyFrom(controllerMesh.rotationQuaternion); - const impostor = new physicsImpostor_PhysicsImpostor(impostorMesh, impostorType, Object.assign({ mass: 0 }, this._options.physicsProperties)); - this._controllers[xrController.uniqueId] = { - xrController, - impostor, - impostorMesh, - }; - } - /** - * Construct a new Controller Physics Feature - * @param _xrSessionManager the corresponding xr session manager - * @param _options options to create this feature with - */ - constructor(_xrSessionManager, _options) { - super(_xrSessionManager); - this._options = _options; - this._attachController = (xrController) => { - if (this._controllers[xrController.uniqueId]) { - // already attached - return; - } - if (!this._xrSessionManager.scene.isPhysicsEnabled()) { - logger_Logger.Warn("physics engine not enabled, skipped. Please add this controller manually."); - } - // if no motion controller available, create impostors! - if (this._options.physicsProperties.useControllerMesh && xrController.inputSource.gamepad) { - xrController.onMotionControllerInitObservable.addOnce((motionController) => { - if (!motionController._doNotLoadControllerMesh) { - motionController.onModelLoadedObservable.addOnce(() => { - const impostor = new physicsImpostor_PhysicsImpostor(motionController.rootMesh, physicsImpostor_PhysicsImpostor.MeshImpostor, Object.assign({ mass: 0 }, this._options.physicsProperties)); - const controllerMesh = xrController.grip || xrController.pointer; - this._controllers[xrController.uniqueId] = { - xrController, - impostor, - oldPos: controllerMesh.position.clone(), - oldRotation: controllerMesh.rotationQuaternion.clone(), - }; - }); - } - else { - // This controller isn't using a model, create impostors instead - this._createPhysicsImpostor(xrController); - } - }); - } - else { - this._createPhysicsImpostor(xrController); - } - }; - this._controllers = {}; - this._debugMode = false; - this._delta = 0; - this._lastTimestamp = 0; - this._tmpQuaternion = new math_vector_Quaternion(); - this._tmpVector = new math_vector_Vector3(); - if (!this._options.physicsProperties) { - this._options.physicsProperties = {}; - } - } - /** - * @internal - * enable debugging - will show console outputs and the impostor mesh - */ - _enablePhysicsDebug() { - this._debugMode = true; - Object.keys(this._controllers).forEach((controllerId) => { - const controllerData = this._controllers[controllerId]; - if (controllerData.impostorMesh) { - controllerData.impostorMesh.isVisible = true; - } - }); - } - /** - * Manually add a controller (if no xrInput was provided or physics engine was not enabled) - * @param xrController the controller to add - */ - addController(xrController) { - this._attachController(xrController); - } - /** - * attach this feature - * Will usually be called by the features manager - * - * @returns true if successful. - */ - attach() { - if (!super.attach()) { - return false; - } - if (!this._options.xrInput) { - return true; - } - this._options.xrInput.controllers.forEach(this._attachController); - this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController); - this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => { - // REMOVE the controller - this._detachController(controller.uniqueId); - }); - if (this._options.enableHeadsetImpostor) { - const params = this._options.headsetImpostorParams || { - impostorType: physicsImpostor_PhysicsImpostor.SphereImpostor, - restitution: 0.8, - impostorSize: 0.3, - }; - const impostorSize = params.impostorSize || 0.3; - this._headsetMesh = sphereBuilder_CreateSphere("headset-mesh", { - diameterX: typeof impostorSize === "number" ? impostorSize : impostorSize.width, - diameterY: typeof impostorSize === "number" ? impostorSize : impostorSize.height, - diameterZ: typeof impostorSize === "number" ? impostorSize : impostorSize.depth, - }); - this._headsetMesh.rotationQuaternion = new math_vector_Quaternion(); - this._headsetMesh.isVisible = false; - this._headsetImpostor = new physicsImpostor_PhysicsImpostor(this._headsetMesh, params.impostorType, Object.assign({ mass: 0 }, params)); - } - return true; - } - /** - * detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - if (!super.detach()) { - return false; - } - Object.keys(this._controllers).forEach((controllerId) => { - this._detachController(controllerId); - }); - if (this._headsetMesh) { - this._headsetMesh.dispose(); - } - return true; - } - /** - * Get the headset impostor, if enabled - * @returns the impostor - */ - getHeadsetImpostor() { - return this._headsetImpostor; - } - /** - * Get the physics impostor of a specific controller. - * The impostor is not attached to a mesh because a mesh for each controller is not obligatory - * @param controller the controller or the controller id of which to get the impostor - * @returns the impostor or null - */ - getImpostorForController(controller) { - const id = typeof controller === "string" ? controller : controller.uniqueId; - if (this._controllers[id]) { - return this._controllers[id].impostor; - } - else { - return null; - } - } - /** - * Update the physics properties provided in the constructor - * @param newProperties the new properties object - * @param newProperties.impostorType - * @param newProperties.impostorSize - * @param newProperties.friction - * @param newProperties.restitution - */ - setPhysicsProperties(newProperties) { - this._options.physicsProperties = Object.assign(Object.assign({}, this._options.physicsProperties), newProperties); - } - _onXRFrame(_xrFrame) { - var _a, _b; - this._delta = this._xrSessionManager.currentTimestamp - this._lastTimestamp; - this._lastTimestamp = this._xrSessionManager.currentTimestamp; - if (this._headsetMesh && this._headsetImpostor) { - this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition); - this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation); - if ((_a = this._options.xrInput.xrCamera._lastXRViewerPose) === null || _a === void 0 ? void 0 : _a.linearVelocity) { - const lv = this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity; - this._tmpVector.set(lv.x, lv.y, lv.z); - this._headsetImpostor.setLinearVelocity(this._tmpVector); - } - if ((_b = this._options.xrInput.xrCamera._lastXRViewerPose) === null || _b === void 0 ? void 0 : _b.angularVelocity) { - const av = this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity; - this._tmpVector.set(av.x, av.y, av.z); - this._headsetImpostor.setAngularVelocity(this._tmpVector); - } - } - Object.keys(this._controllers).forEach((controllerId) => { - var _a, _b; - const controllerData = this._controllers[controllerId]; - const controllerMesh = controllerData.xrController.grip || controllerData.xrController.pointer; - const comparedPosition = controllerData.oldPos || controllerData.impostorMesh.position; - if ((_a = controllerData.xrController._lastXRPose) === null || _a === void 0 ? void 0 : _a.linearVelocity) { - const lv = controllerData.xrController._lastXRPose.linearVelocity; - this._tmpVector.set(lv.x, lv.y, lv.z); - controllerData.impostor.setLinearVelocity(this._tmpVector); - } - else { - controllerMesh.position.subtractToRef(comparedPosition, this._tmpVector); - this._tmpVector.scaleInPlace(1000 / this._delta); - controllerData.impostor.setLinearVelocity(this._tmpVector); - } - comparedPosition.copyFrom(controllerMesh.position); - if (this._debugMode) { - console.log(this._tmpVector, "linear"); - } - const comparedQuaternion = controllerData.oldRotation || controllerData.impostorMesh.rotationQuaternion; - if ((_b = controllerData.xrController._lastXRPose) === null || _b === void 0 ? void 0 : _b.angularVelocity) { - const av = controllerData.xrController._lastXRPose.angularVelocity; - this._tmpVector.set(av.x, av.y, av.z); - controllerData.impostor.setAngularVelocity(this._tmpVector); - } - else { - if (!comparedQuaternion.equalsWithEpsilon(controllerMesh.rotationQuaternion)) { - // roughly based on this - https://www.gamedev.net/forums/topic/347752-quaternion-and-angular-velocity/ - comparedQuaternion.conjugateInPlace().multiplyToRef(controllerMesh.rotationQuaternion, this._tmpQuaternion); - const len = Math.sqrt(this._tmpQuaternion.x * this._tmpQuaternion.x + this._tmpQuaternion.y * this._tmpQuaternion.y + this._tmpQuaternion.z * this._tmpQuaternion.z); - this._tmpVector.set(this._tmpQuaternion.x, this._tmpQuaternion.y, this._tmpQuaternion.z); - // define a better epsilon - if (len < 0.001) { - this._tmpVector.scaleInPlace(2); - } - else { - const angle = 2 * Math.atan2(len, this._tmpQuaternion.w); - this._tmpVector.scaleInPlace(angle / (len * (this._delta / 1000))); - } - controllerData.impostor.setAngularVelocity(this._tmpVector); - } - } - comparedQuaternion.copyFrom(controllerMesh.rotationQuaternion); - if (this._debugMode) { - console.log(this._tmpVector, this._tmpQuaternion, "angular"); - } - }); - } - _detachController(xrControllerUniqueId) { - const controllerData = this._controllers[xrControllerUniqueId]; - if (!controllerData) { - return; - } - if (controllerData.impostorMesh) { - controllerData.impostorMesh.dispose(); - } - // remove from the map - delete this._controllers[xrControllerUniqueId]; - } -} -/** - * The module's name - */ -WebXRControllerPhysics.Name = webXRFeaturesManager_WebXRFeatureName.PHYSICS_CONTROLLERS; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the webxr specs version - */ -WebXRControllerPhysics.Version = 1; -//register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPhysics.Name, (xrSessionManager, options) => { - return () => new WebXRControllerPhysics(xrSessionManager, options); -}, WebXRControllerPhysics.Version, true); -//# sourceMappingURL=WebXRControllerPhysics.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRHitTest.js - - - - - -/** - * The currently-working hit-test module. - * Hit test (or Ray-casting) is used to interact with the real world. - * For further information read here - https://github.com/immersive-web/hit-test - * - * Tested on chrome (mobile) 80. - */ -class WebXRHitTest extends WebXRAbstractFeature { - /** - * Creates a new instance of the hit test feature - * @param _xrSessionManager an instance of WebXRSessionManager - * @param options options to use when constructing this feature - */ - constructor(_xrSessionManager, - /** - * options to use when constructing this feature - */ - options = {}) { - super(_xrSessionManager); - this.options = options; - this._tmpMat = new math_vector_Matrix(); - this._tmpPos = new math_vector_Vector3(); - this._tmpQuat = new math_vector_Quaternion(); - this._initHitTestSource = (referenceSpace) => { - if (!referenceSpace) { - return; - } - const offsetRay = new XRRay(this.options.offsetRay || {}); - const hitTestOptions = { - space: this.options.useReferenceSpace ? referenceSpace : this._xrSessionManager.viewerReferenceSpace, - offsetRay: offsetRay, - }; - if (this.options.entityTypes) { - hitTestOptions.entityTypes = this.options.entityTypes; - } - if (!hitTestOptions.space) { - tools_Tools.Warn("waiting for viewer reference space to initialize"); - return; - } - this._xrSessionManager.session.requestHitTestSource(hitTestOptions).then((hitTestSource) => { - if (this._xrHitTestSource) { - this._xrHitTestSource.cancel(); - } - this._xrHitTestSource = hitTestSource; - }); - }; - /** - * When set to true, each hit test will have its own position/rotation objects - * When set to false, position and rotation objects will be reused for each hit test. It is expected that - * the developers will clone them or copy them as they see fit. - */ - this.autoCloneTransformation = false; - /** - * Triggered when new babylon (transformed) hit test results are available - * Note - this will be called when results come back from the device. It can be an empty array!! - */ - this.onHitTestResultObservable = new observable_Observable(); - /** - * Use this to temporarily pause hit test checks. - */ - this.paused = false; - this.xrNativeFeatureName = "hit-test"; - tools_Tools.Warn("Hit test is an experimental and unstable feature."); - } - /** - * attach this feature - * Will usually be called by the features manager - * - * @returns true if successful. - */ - attach() { - if (!super.attach()) { - return false; - } - // Feature enabled, but not available - if (!this._xrSessionManager.session.requestHitTestSource) { - return false; - } - if (!this.options.disablePermanentHitTest) { - if (this._xrSessionManager.referenceSpace) { - this._initHitTestSource(this._xrSessionManager.referenceSpace); - } - this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource); - } - if (this.options.enableTransientHitTest) { - const offsetRay = new XRRay(this.options.transientOffsetRay || {}); - this._xrSessionManager.session.requestHitTestSourceForTransientInput({ - profile: this.options.transientHitTestProfile || "generic-touchscreen", - offsetRay, - entityTypes: this.options.entityTypes, - }).then((hitSource) => { - this._transientXrHitTestSource = hitSource; - }); - } - return true; - } - /** - * detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - if (!super.detach()) { - return false; - } - if (this._xrHitTestSource) { - this._xrHitTestSource.cancel(); - this._xrHitTestSource = null; - } - this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource); - if (this._transientXrHitTestSource) { - this._transientXrHitTestSource.cancel(); - this._transientXrHitTestSource = null; - } - return true; - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - super.dispose(); - this.onHitTestResultObservable.clear(); - } - _onXRFrame(frame) { - // make sure we do nothing if (async) not attached - if (!this.attached || this.paused) { - return; - } - if (this._xrHitTestSource) { - const results = frame.getHitTestResults(this._xrHitTestSource); - this._processWebXRHitTestResult(results); - } - if (this._transientXrHitTestSource) { - const hitTestResultsPerInputSource = frame.getHitTestResultsForTransientInput(this._transientXrHitTestSource); - hitTestResultsPerInputSource.forEach((resultsPerInputSource) => { - this._processWebXRHitTestResult(resultsPerInputSource.results, resultsPerInputSource.inputSource); - }); - } - } - _processWebXRHitTestResult(hitTestResults, inputSource) { - const results = []; - hitTestResults.forEach((hitTestResult) => { - const pose = hitTestResult.getPose(this._xrSessionManager.referenceSpace); - if (!pose) { - return; - } - const pos = pose.transform.position; - const quat = pose.transform.orientation; - this._tmpPos.set(pos.x, pos.y, pos.z); - this._tmpQuat.set(quat.x, quat.y, quat.z, quat.w); - math_vector_Matrix.FromFloat32ArrayToRefScaled(pose.transform.matrix, 0, 1, this._tmpMat); - if (!this._xrSessionManager.scene.useRightHandedSystem) { - this._tmpPos.z *= -1; - this._tmpQuat.z *= -1; - this._tmpQuat.w *= -1; - this._tmpMat.toggleModelMatrixHandInPlace(); - } - const result = { - 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: inputSource, - isTransient: !!inputSource, - xrHitResult: hitTestResult, - }; - results.push(result); - }); - this.onHitTestResultObservable.notifyObservers(results); - } -} -/** - * The module's name - */ -WebXRHitTest.Name = webXRFeaturesManager_WebXRFeatureName.HIT_TEST; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRHitTest.Version = 2; -//register the plugin versions -WebXRFeaturesManager.AddWebXRFeature(WebXRHitTest.Name, (xrSessionManager, options) => { - return () => new WebXRHitTest(xrSessionManager, options); -}, WebXRHitTest.Version, false); -//# sourceMappingURL=WebXRHitTest.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRFeaturePointSystem.js - - - - -/** - * The feature point system is used to detect feature points from real world geometry. - * This feature is currently experimental and only supported on BabylonNative, and should not be used in the browser. - * The newly introduced API can be seen in webxr.nativeextensions.d.ts and described in FeaturePoints.md. - */ -class WebXRFeaturePointSystem extends WebXRAbstractFeature { - /** - * The current feature point cloud maintained across frames. - */ - get featurePointCloud() { - return this._featurePointCloud; - } - /** - * construct the feature point system - * @param _xrSessionManager an instance of xr Session manager - */ - constructor(_xrSessionManager) { - super(_xrSessionManager); - this._enabled = false; - this._featurePointCloud = []; - /** - * Observers registered here will be executed whenever new feature points are added (on XRFrame while the session is tracking). - * Will notify the observers about which feature points have been added. - */ - this.onFeaturePointsAddedObservable = new observable_Observable(); - /** - * Observers registered here will be executed whenever a feature point has been updated (on XRFrame while the session is tracking). - * Will notify the observers about which feature points have been updated. - */ - this.onFeaturePointsUpdatedObservable = new observable_Observable(); - this.xrNativeFeatureName = "bjsfeature-points"; - if (this._xrSessionManager.session) { - this._init(); - } - else { - this._xrSessionManager.onXRSessionInit.addOnce(() => { - this._init(); - }); - } - } - /** - * Detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - if (!super.detach()) { - return false; - } - this.featurePointCloud.length = 0; - return true; - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - super.dispose(); - this._featurePointCloud.length = 0; - this.onFeaturePointsUpdatedObservable.clear(); - this.onFeaturePointsAddedObservable.clear(); - } - /** - * On receiving a new XR frame if this feature is attached notify observers new feature point data is available. - * @param frame - */ - _onXRFrame(frame) { - if (!this.attached || !this._enabled || !frame) { - return; - } - const featurePointRawData = frame.featurePointCloud; - if (!featurePointRawData || featurePointRawData.length === 0) { - return; - } - else { - if (featurePointRawData.length % 5 !== 0) { - throw new Error("Received malformed feature point cloud of length: " + featurePointRawData.length); - } - const numberOfFeaturePoints = featurePointRawData.length / 5; - const updatedFeaturePoints = new Array(); - const addedFeaturePoints = new Array(); - for (let i = 0; i < numberOfFeaturePoints; i++) { - const rawIndex = i * 5; - const id = featurePointRawData[rawIndex + 4]; - // IDs should be durable across frames and strictly increasing from 0 up, so use them as indexing into the feature point array. - if (!this._featurePointCloud[id]) { - this._featurePointCloud[id] = { position: new math_vector_Vector3(), confidenceValue: 0 }; - addedFeaturePoints.push(id); - } - else { - updatedFeaturePoints.push(id); - } - // Set the feature point values. - this._featurePointCloud[id].position.x = featurePointRawData[rawIndex]; - this._featurePointCloud[id].position.y = featurePointRawData[rawIndex + 1]; - this._featurePointCloud[id].position.z = featurePointRawData[rawIndex + 2]; - this._featurePointCloud[id].confidenceValue = featurePointRawData[rawIndex + 3]; - } - // Signal observers that feature points have been added if necessary. - if (addedFeaturePoints.length > 0) { - this.onFeaturePointsAddedObservable.notifyObservers(addedFeaturePoints); - } - // Signal observers that feature points have been updated if necessary. - if (updatedFeaturePoints.length > 0) { - this.onFeaturePointsUpdatedObservable.notifyObservers(updatedFeaturePoints); - } - } - } - /** - * Initializes the feature. If the feature point feature is not available for this environment do not mark the feature as enabled. - */ - _init() { - if (!this._xrSessionManager.session.trySetFeaturePointCloudEnabled || !this._xrSessionManager.session.trySetFeaturePointCloudEnabled(true)) { - // fail silently - return; - } - this._enabled = true; - } -} -/** - * The module's name - */ -WebXRFeaturePointSystem.Name = webXRFeaturesManager_WebXRFeatureName.FEATURE_POINTS; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRFeaturePointSystem.Version = 1; -// register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRFeaturePointSystem.Name, (xrSessionManager) => { - return () => new WebXRFeaturePointSystem(xrSessionManager); -}, WebXRFeaturePointSystem.Version); -//# sourceMappingURL=WebXRFeaturePointSystem.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRMeshDetector.js - - - - -let meshIdProvider = 0; -/** - * The mesh detector is used to detect meshes in the real world when in AR - */ -class WebXRMeshDetector extends WebXRAbstractFeature { - constructor(_xrSessionManager, _options = {}) { - super(_xrSessionManager); - this._options = _options; - this._detectedMeshes = new Map(); - /** - * Observers registered here will be executed when a new mesh was added to the session - */ - this.onMeshAddedObservable = new observable_Observable(); - /** - * Observers registered here will be executed when a mesh is no longer detected in the session - */ - this.onMeshRemovedObservable = new observable_Observable(); - /** - * Observers registered here will be executed when an existing mesh updates - */ - this.onMeshUpdatedObservable = new observable_Observable(); - this.xrNativeFeatureName = "mesh-detection"; - if (this._xrSessionManager.session) { - this._init(); - } - else { - this._xrSessionManager.onXRSessionInit.addOnce(() => { - this._init(); - }); - } - } - detach() { - if (!super.detach()) { - return false; - } - // Only supported by BabylonNative - if (!!this._xrSessionManager.isNative && !!this._xrSessionManager.session.trySetMeshDetectorEnabled) { - this._xrSessionManager.session.trySetMeshDetectorEnabled(false); - } - if (!this._options.doNotRemoveMeshesOnSessionEnded) { - this._detectedMeshes.forEach((mesh) => { - this.onMeshRemovedObservable.notifyObservers(mesh); - }); - this._detectedMeshes.clear(); - } - return true; - } - dispose() { - super.dispose(); - this.onMeshAddedObservable.clear(); - this.onMeshRemovedObservable.clear(); - this.onMeshUpdatedObservable.clear(); - } - _onXRFrame(frame) { - var _a; - // TODO remove try catch - try { - if (!this.attached || !frame) { - return; - } - const detectedMeshes = (_a = frame.worldInformation) === null || _a === void 0 ? void 0 : _a.detectedMeshes; - if (detectedMeshes) { - const toRemove = new Set(); - this._detectedMeshes.forEach((vertexData, xrMesh) => { - if (!detectedMeshes.has(xrMesh)) { - toRemove.add(xrMesh); - } - }); - toRemove.forEach((xrMesh) => { - const vertexData = this._detectedMeshes.get(xrMesh); - if (vertexData) { - this.onMeshRemovedObservable.notifyObservers(vertexData); - this._detectedMeshes.delete(xrMesh); - } - }); - // now check for new ones - detectedMeshes.forEach((xrMesh) => { - if (!this._detectedMeshes.has(xrMesh)) { - const partialVertexData = { - id: meshIdProvider++, - xrMesh: xrMesh, - }; - const vertexData = this._updateVertexDataWithXRMesh(xrMesh, partialVertexData, frame); - this._detectedMeshes.set(xrMesh, vertexData); - this.onMeshAddedObservable.notifyObservers(vertexData); - } - else { - // updated? - if (xrMesh.lastChangedTime === this._xrSessionManager.currentTimestamp) { - const vertexData = this._detectedMeshes.get(xrMesh); - if (vertexData) { - this._updateVertexDataWithXRMesh(xrMesh, vertexData, frame); - this.onMeshUpdatedObservable.notifyObservers(vertexData); - } - } - } - }); - } - } - catch (error) { - console.log(error.stack); - } - } - _init() { - // Only supported by BabylonNative - if (this._xrSessionManager.isNative) { - if (this._xrSessionManager.session.trySetMeshDetectorEnabled) { - this._xrSessionManager.session.trySetMeshDetectorEnabled(true); - } - if (!!this._options.preferredDetectorOptions && !!this._xrSessionManager.session.trySetPreferredMeshDetectorOptions) { - this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions); - } - } - } - _updateVertexDataWithXRMesh(xrMesh, mesh, xrFrame) { - mesh.xrMesh = xrMesh; - mesh.worldParentNode = this._options.worldParentNode; - if (this._options.convertCoordinateSystems) { - if (!this._xrSessionManager.scene.useRightHandedSystem) { - mesh.positions = new Float32Array(xrMesh.positions.length); - for (let i = 0; i < xrMesh.positions.length; i += 3) { - mesh.positions[i] = xrMesh.positions[i]; - mesh.positions[i + 1] = xrMesh.positions[i + 1]; - mesh.positions[i + 2] = -1 * xrMesh.positions[i + 2]; - } - if (xrMesh.normals) { - mesh.normals = new Float32Array(xrMesh.normals.length); - for (let i = 0; i < xrMesh.normals.length; i += 3) { - mesh.normals[i] = xrMesh.normals[i]; - mesh.normals[i + 1] = xrMesh.normals[i + 1]; - mesh.normals[i + 2] = -1 * xrMesh.normals[i + 2]; - } - } - } - else { - mesh.positions = xrMesh.positions; - mesh.normals = xrMesh.normals; - } - // WebXR should provide indices in a counterclockwise winding order regardless of coordinate system handedness - mesh.indices = xrMesh.indices; - // matrix - const pose = xrFrame.getPose(xrMesh.meshSpace, this._xrSessionManager.referenceSpace); - if (pose) { - const mat = mesh.transformationMatrix || new math_vector_Matrix(); - math_vector_Matrix.FromArrayToRef(pose.transform.matrix, 0, mat); - if (!this._xrSessionManager.scene.useRightHandedSystem) { - mat.toggleModelMatrixHandInPlace(); - } - mesh.transformationMatrix = mat; - if (this._options.worldParentNode) { - mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat); - } - } - } - return mesh; - } -} -/** - * The module's name - */ -WebXRMeshDetector.Name = webXRFeaturesManager_WebXRFeatureName.MESH_DETECTION; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRMeshDetector.Version = 1; -WebXRFeaturesManager.AddWebXRFeature(WebXRMeshDetector.Name, (xrSessionManager, options) => { - return () => new WebXRMeshDetector(xrSessionManager, options); -}, WebXRMeshDetector.Version, false); -//# sourceMappingURL=WebXRMeshDetector.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRImageTracking.js - - - - - -/** - * Enum that describes the state of the image trackability score status for this session. - */ -var ImageTrackingScoreStatus; -(function (ImageTrackingScoreStatus) { - // AR Session has not yet assessed image trackability scores. - ImageTrackingScoreStatus[ImageTrackingScoreStatus["NotReceived"] = 0] = "NotReceived"; - // A request to retrieve trackability scores has been sent, but no response has been received. - ImageTrackingScoreStatus[ImageTrackingScoreStatus["Waiting"] = 1] = "Waiting"; - // Image trackability scores have been received for this session - ImageTrackingScoreStatus[ImageTrackingScoreStatus["Received"] = 2] = "Received"; -})(ImageTrackingScoreStatus || (ImageTrackingScoreStatus = {})); -/** - * Image tracking for immersive AR sessions. - * Providing a list of images and their estimated widths will enable tracking those images in the real world. - */ -class WebXRImageTracking extends WebXRAbstractFeature { - /** - * constructs the image tracking feature - * @param _xrSessionManager the session manager for this module - * @param options read-only options to be used in this module - */ - constructor(_xrSessionManager, - /** - * read-only options to be used in this module - */ - options) { - super(_xrSessionManager); - this.options = options; - /** - * This will be triggered if the underlying system deems an image untrackable. - * The index is the index of the image from the array used to initialize the feature. - */ - this.onUntrackableImageFoundObservable = new observable_Observable(); - /** - * An image was deemed trackable, and the system will start tracking it. - */ - this.onTrackableImageFoundObservable = new observable_Observable(); - /** - * The image was found and its state was updated. - */ - this.onTrackedImageUpdatedObservable = new observable_Observable(); - this._trackableScoreStatus = ImageTrackingScoreStatus.NotReceived; - this._trackedImages = []; - this.xrNativeFeatureName = "image-tracking"; - } - /** - * attach this feature - * Will usually be called by the features manager - * - * @returns true if successful. - */ - attach() { - return super.attach(); - } - /** - * detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - return super.detach(); - } - /** - * Get a tracked image by its ID. - * - * @param id the id of the image to load (position in the init array) - * @returns a trackable image, if exists in this location - */ - getTrackedImageById(id) { - return this._trackedImages[id] || null; - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - super.dispose(); - this._trackedImages.forEach((trackedImage) => { - trackedImage.originalBitmap.close(); - }); - this._trackedImages.length = 0; - this.onTrackableImageFoundObservable.clear(); - this.onUntrackableImageFoundObservable.clear(); - this.onTrackedImageUpdatedObservable.clear(); - } - /** - * Extends the session init object if needed - * @returns augmentation object fo the xr session init object. - */ - async getXRSessionInitExtension() { - if (!this.options.images || !this.options.images.length) { - return {}; - } - const promises = this.options.images.map((image) => { - if (typeof image.src === "string") { - return this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(image.src); - } - else { - return Promise.resolve(image.src); // resolve is probably unneeded - } - }); - try { - const images = await Promise.all(promises); - this._originalTrackingRequest = images.map((image, idx) => { - return { - image, - widthInMeters: this.options.images[idx].estimatedRealWorldWidth, - }; - }); - return { - trackedImages: this._originalTrackingRequest, - }; - } - catch (ex) { - tools_Tools.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."); - return {}; - } - } - _onXRFrame(_xrFrame) { - if (!_xrFrame.getImageTrackingResults || this._trackableScoreStatus === ImageTrackingScoreStatus.Waiting) { - return; - } - // Image tracking scores may be generated a few frames after the XR Session initializes. - // If we haven't received scores yet, then kick off the task to check scores and return immediately. - if (this._trackableScoreStatus === ImageTrackingScoreStatus.NotReceived) { - this._checkScoresAsync(); - return; - } - const imageTrackedResults = _xrFrame.getImageTrackingResults(); - for (const result of imageTrackedResults) { - let changed = false; - const imageIndex = result.index; - const imageObject = this._trackedImages[imageIndex]; - if (!imageObject) { - // something went wrong! - continue; - } - imageObject.xrTrackingResult = result; - if (imageObject.realWorldWidth !== result.measuredWidthInMeters) { - imageObject.realWorldWidth = result.measuredWidthInMeters; - changed = true; - } - // Get the pose of the image relative to a reference space. - const pose = _xrFrame.getPose(result.imageSpace, this._xrSessionManager.referenceSpace); - if (pose) { - const mat = imageObject.transformationMatrix; - math_vector_Matrix.FromArrayToRef(pose.transform.matrix, 0, mat); - if (!this._xrSessionManager.scene.useRightHandedSystem) { - mat.toggleModelMatrixHandInPlace(); - } - changed = true; - } - const state = result.trackingState; - const emulated = state === "emulated"; - if (imageObject.emulated !== emulated) { - imageObject.emulated = emulated; - changed = true; - } - if (changed) { - this.onTrackedImageUpdatedObservable.notifyObservers(imageObject); - } - } - } - async _checkScoresAsync() { - if (!this._xrSessionManager.session.getTrackedImageScores || this._trackableScoreStatus !== ImageTrackingScoreStatus.NotReceived) { - return; - } - this._trackableScoreStatus = ImageTrackingScoreStatus.Waiting; - const imageScores = await this._xrSessionManager.session.getTrackedImageScores(); - if (!imageScores || imageScores.length === 0) { - this._trackableScoreStatus = ImageTrackingScoreStatus.NotReceived; - return; - } - // check the scores for all - for (let idx = 0; idx < imageScores.length; ++idx) { - if (imageScores[idx] == "untrackable") { - this.onUntrackableImageFoundObservable.notifyObservers(idx); - } - else { - const originalBitmap = this._originalTrackingRequest[idx].image; - const imageObject = { - id: idx, - originalBitmap, - transformationMatrix: new math_vector_Matrix(), - ratio: originalBitmap.width / originalBitmap.height, - }; - this._trackedImages[idx] = imageObject; - this.onTrackableImageFoundObservable.notifyObservers(imageObject); - } - } - this._trackableScoreStatus = imageScores.length > 0 ? ImageTrackingScoreStatus.Received : ImageTrackingScoreStatus.NotReceived; - } -} -/** - * The module's name - */ -WebXRImageTracking.Name = webXRFeaturesManager_WebXRFeatureName.IMAGE_TRACKING; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRImageTracking.Version = 1; -//register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRImageTracking.Name, (xrSessionManager, options) => { - return () => new WebXRImageTracking(xrSessionManager, options); -}, WebXRImageTracking.Version, false); -//# sourceMappingURL=WebXRImageTracking.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRDOMOverlay.js - - - -/** - * DOM Overlay Feature - * - * @since 5.0.0 - */ -class WebXRDomOverlay extends WebXRAbstractFeature { - /** - * Creates a new instance of the dom-overlay feature - * @param _xrSessionManager an instance of WebXRSessionManager - * @param options options to use when constructing this feature - */ - constructor(_xrSessionManager, - /** - * options to use when constructing this feature - */ - options) { - super(_xrSessionManager); - this.options = options; - /** - * Type of overlay - non-null when available - */ - this._domOverlayType = null; - /** - * Event Listener to supress "beforexrselect" events. - */ - this._beforeXRSelectListener = null; - /** - * Element used for overlay - */ - this._element = null; - this.xrNativeFeatureName = "dom-overlay"; - // https://immersive-web.github.io/dom-overlays/ - tools_Tools.Warn("dom-overlay is an experimental and unstable feature."); - } - /** - * attach this feature - * Will usually be called by the features manager - * - * @returns true if successful. - */ - attach() { - if (!super.attach()) { - return false; - } - // Feature not available - if (!this._xrSessionManager.session.domOverlayState || this._xrSessionManager.session.domOverlayState.type === null) { - return false; - } - this._domOverlayType = this._xrSessionManager.session.domOverlayState.type; - if (this._element !== null && this.options.supressXRSelectEvents === true) { - this._beforeXRSelectListener = (ev) => { - ev.preventDefault(); - }; - this._element.addEventListener("beforexrselect", this._beforeXRSelectListener); - } - return true; - } - /** - * The type of DOM overlay (null when not supported). Provided by UA and remains unchanged for duration of session. - */ - get domOverlayType() { - return this._domOverlayType; - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - super.dispose(); - if (this._element !== null && this._beforeXRSelectListener) { - this._element.removeEventListener("beforexrselect", this._beforeXRSelectListener); - } - } - _onXRFrame(_xrFrame) { - /* empty */ - } - /** - * Extends the session init object if needed - * @returns augmentation object for the xr session init object. - */ - async getXRSessionInitExtension() { - if (this.options.element === undefined) { - tools_Tools.Warn('"element" option must be provided to attach xr-dom-overlay feature.'); - return {}; - } - else if (typeof this.options.element === "string") { - const selectedElement = document.querySelector(this.options.element); - if (selectedElement === null) { - tools_Tools.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`); - return {}; - } - this._element = selectedElement; - } - else { - this._element = this.options.element; - } - return { - domOverlay: { - root: this._element, - }, - }; - } -} -/** - * The module's name - */ -WebXRDomOverlay.Name = webXRFeaturesManager_WebXRFeatureName.DOM_OVERLAY; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRDomOverlay.Version = 1; -//register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRDomOverlay.Name, (xrSessionManager, options) => { - return () => new WebXRDomOverlay(xrSessionManager, options); -}, WebXRDomOverlay.Version, false); -//# sourceMappingURL=WebXRDOMOverlay.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRControllerMovement.js - - - - - -/** - * This is a movement feature to be used with WebXR-enabled motion controllers. - * When enabled and attached, the feature will allow a user to move around and rotate in the scene using - * the input of the attached controllers. - */ -class WebXRControllerMovement extends WebXRAbstractFeature { - /** - * Current movement direction. Will be null before XR Frames have been processed. - */ - get movementDirection() { - return this._movementDirection; - } - /** - * Is movement enabled - */ - get movementEnabled() { - return this._featureContext.movementEnabled; - } - /** - * Sets whether movement is enabled or not - * @param enabled is movement enabled - */ - set movementEnabled(enabled) { - this._featureContext.movementEnabled = enabled; - } - /** - * If movement follows viewer pose - */ - get movementOrientationFollowsViewerPose() { - return this._featureContext.movementOrientationFollowsViewerPose; - } - /** - * Sets whether movement follows viewer pose - * @param followsPose is movement should follow viewer pose - */ - set movementOrientationFollowsViewerPose(followsPose) { - this._featureContext.movementOrientationFollowsViewerPose = followsPose; - } - /** - * Gets movement speed - */ - get movementSpeed() { - return this._featureContext.movementSpeed; - } - /** - * Sets movement speed - * @param movementSpeed movement speed - */ - set movementSpeed(movementSpeed) { - this._featureContext.movementSpeed = movementSpeed; - } - /** - * Gets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for movement (avoids jitter/unintentional movement) - */ - get movementThreshold() { - return this._featureContext.movementThreshold; - } - /** - * Sets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for movement (avoids jitter/unintentional movement) - * @param movementThreshold new threshold - */ - set movementThreshold(movementThreshold) { - this._featureContext.movementThreshold = movementThreshold; - } - /** - * Is rotation enabled - */ - get rotationEnabled() { - return this._featureContext.rotationEnabled; - } - /** - * Sets whether rotation is enabled or not - * @param enabled is rotation enabled - */ - set rotationEnabled(enabled) { - this._featureContext.rotationEnabled = enabled; - } - /** - * Gets rotation speed factor - */ - get rotationSpeed() { - return this._featureContext.rotationSpeed; - } - /** - * Sets rotation speed factor (1.0 is default) - * @param rotationSpeed new rotation speed factor - */ - set rotationSpeed(rotationSpeed) { - this._featureContext.rotationSpeed = rotationSpeed; - } - /** - * Gets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for rotation (avoids jitter/unintentional rotation) - */ - get rotationThreshold() { - return this._featureContext.rotationThreshold; - } - /** - * Sets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for rotation (avoids jitter/unintentional rotation) - * @param threshold new threshold - */ - set rotationThreshold(threshold) { - this._featureContext.rotationThreshold = threshold; - } - /** - * constructs a new movement controller system - * @param _xrSessionManager an instance of WebXRSessionManager - * @param options configuration object for this feature - */ - constructor(_xrSessionManager, options) { - var _a, _b, _c, _d, _e, _f; - super(_xrSessionManager); - this._controllers = {}; - this._currentRegistrationConfigurations = []; - // forward direction for movement, which may differ from viewer pose. - this._movementDirection = new math_vector_Quaternion(); - // unused - this._tmpRotationMatrix = math_vector_Matrix.Identity(); - this._tmpTranslationDirection = new math_vector_Vector3(); - this._tmpMovementTranslation = new math_vector_Vector3(); - this._tempCacheQuaternion = new math_vector_Quaternion(); - this._attachController = (xrController) => { - if (this._controllers[xrController.uniqueId]) { - // already attached - return; - } - this._controllers[xrController.uniqueId] = { - xrController, - registeredComponents: [], - }; - const controllerData = this._controllers[xrController.uniqueId]; - // movement controller only available to gamepad-enabled input sources. - if (controllerData.xrController.inputSource.targetRayMode === "tracked-pointer" && controllerData.xrController.inputSource.gamepad) { - // motion controller support - const initController = () => { - if (xrController.motionController) { - for (const registration of this._currentRegistrationConfigurations) { - let component = null; - if (registration.allowedComponentTypes) { - for (const componentType of registration.allowedComponentTypes) { - const componentOfType = xrController.motionController.getComponentOfType(componentType); - if (componentOfType !== null) { - component = componentOfType; - break; - } - } - } - if (registration.mainComponentOnly) { - const mainComponent = xrController.motionController.getMainComponent(); - if (mainComponent === null) { - continue; - } - component = mainComponent; - } - if (typeof registration.componentSelectionPredicate === "function") { - // if does not match we do want to ignore a previously found component - component = registration.componentSelectionPredicate(xrController); - } - if (component && registration.forceHandedness) { - if (xrController.inputSource.handedness !== registration.forceHandedness) { - continue; // do not register - } - } - if (component === null) { - continue; // do not register - } - const registeredComponent = { - registrationConfiguration: registration, - component, - }; - controllerData.registeredComponents.push(registeredComponent); - if ("axisChangedHandler" in registration) { - registeredComponent.onAxisChangedObserver = component.onAxisValueChangedObservable.add((axesData) => { - registration.axisChangedHandler(axesData, this._movementState, this._featureContext, this._xrInput); - }); - } - if ("buttonChangedhandler" in registration) { - registeredComponent.onButtonChangedObserver = component.onButtonStateChangedObservable.add(() => { - if (component.changes.pressed) { - registration.buttonChangedhandler(component.changes.pressed, this._movementState, this._featureContext, this._xrInput); - } - }); - } - } - } - }; - if (xrController.motionController) { - initController(); - } - else { - xrController.onMotionControllerInitObservable.addOnce(() => { - initController(); - }); - } - } - }; - if (!options || options.xrInput === undefined) { - tools_Tools.Error('WebXRControllerMovement feature requires "xrInput" option.'); - return; - } - if (Array.isArray(options.customRegistrationConfigurations)) { - this._currentRegistrationConfigurations = options.customRegistrationConfigurations; - } - else { - this._currentRegistrationConfigurations = WebXRControllerMovement.REGISTRATIONS.default; - } - // synchronized from feature setter properties - this._featureContext = { - movementEnabled: options.movementEnabled || true, - movementOrientationFollowsViewerPose: (_a = options.movementOrientationFollowsViewerPose) !== null && _a !== void 0 ? _a : true, - movementSpeed: (_b = options.movementSpeed) !== null && _b !== void 0 ? _b : 1, - movementThreshold: (_c = options.movementThreshold) !== null && _c !== void 0 ? _c : 0.25, - rotationEnabled: (_d = options.rotationEnabled) !== null && _d !== void 0 ? _d : true, - rotationSpeed: (_e = options.rotationSpeed) !== null && _e !== void 0 ? _e : 1.0, - rotationThreshold: (_f = options.rotationThreshold) !== null && _f !== void 0 ? _f : 0.25, - }; - this._movementState = { - moveX: 0, - moveY: 0, - rotateX: 0, - rotateY: 0, - }; - this._xrInput = options.xrInput; - } - attach() { - if (!super.attach()) { - return false; - } - this._xrInput.controllers.forEach(this._attachController); - this._addNewAttachObserver(this._xrInput.onControllerAddedObservable, this._attachController); - this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable, (controller) => { - // REMOVE the controller - this._detachController(controller.uniqueId); - }); - return true; - } - detach() { - if (!super.detach()) { - return false; - } - Object.keys(this._controllers).forEach((controllerId) => { - this._detachController(controllerId); - }); - this._controllers = {}; - return true; - } - /** - * Occurs on every XR frame. - * @param _xrFrame - */ - _onXRFrame(_xrFrame) { - if (!this.attached) { - return; - } - if (this._movementState.rotateX !== 0 && this._featureContext.rotationEnabled) { - // smooth rotation - const deltaMillis = this._xrSessionManager.scene.getEngine().getDeltaTime(); - const rotationY = deltaMillis * 0.001 * this._featureContext.rotationSpeed * this._movementState.rotateX * (this._xrSessionManager.scene.useRightHandedSystem ? -1 : 1); - if (this._featureContext.movementOrientationFollowsViewerPose) { - this._xrInput.xrCamera.cameraRotation.y += rotationY; - math_vector_Quaternion.RotationYawPitchRollToRef(rotationY, 0, 0, this._tempCacheQuaternion); - this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion, this._movementDirection); - } - else { - // movement orientation direction does not affect camera. We use rotation speed multiplier - // otherwise need to implement inertia and constraints for same feel as TargetCamera. - math_vector_Quaternion.RotationYawPitchRollToRef(rotationY * 3.0, 0, 0, this._tempCacheQuaternion); - this._movementDirection.multiplyInPlace(this._tempCacheQuaternion); - } - } - else if (this._featureContext.movementOrientationFollowsViewerPose) { - this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion); - } - if ((this._movementState.moveX || this._movementState.moveY) && this._featureContext.movementEnabled) { - math_vector_Matrix.FromQuaternionToRef(this._movementDirection, this._tmpRotationMatrix); - this._tmpTranslationDirection.set(this._movementState.moveX, 0, this._movementState.moveY * (this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1.0)); - // move according to forward direction based on camera speed - math_vector_Vector3.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(xrControllerUniqueId) { - const controllerData = this._controllers[xrControllerUniqueId]; - if (!controllerData) { - return; - } - for (const registeredComponent of controllerData.registeredComponents) { - if (registeredComponent.onAxisChangedObserver) { - registeredComponent.component.onAxisValueChangedObservable.remove(registeredComponent.onAxisChangedObserver); - } - if (registeredComponent.onButtonChangedObserver) { - registeredComponent.component.onButtonStateChangedObservable.remove(registeredComponent.onButtonChangedObserver); - } - } - // remove from the map - delete this._controllers[xrControllerUniqueId]; - } -} -/** - * The module's name - */ -WebXRControllerMovement.Name = webXRFeaturesManager_WebXRFeatureName.MOVEMENT; -/** - * Standard controller configurations. - */ -WebXRControllerMovement.REGISTRATIONS = { - default: [ - { - allowedComponentTypes: [WebXRControllerComponent.THUMBSTICK_TYPE, WebXRControllerComponent.TOUCHPAD_TYPE], - forceHandedness: "left", - axisChangedHandler: (axes, movementState, featureContext) => { - movementState.rotateX = Math.abs(axes.x) > featureContext.rotationThreshold ? axes.x : 0; - movementState.rotateY = Math.abs(axes.y) > featureContext.rotationThreshold ? axes.y : 0; - }, - }, - { - allowedComponentTypes: [WebXRControllerComponent.THUMBSTICK_TYPE, WebXRControllerComponent.TOUCHPAD_TYPE], - forceHandedness: "right", - axisChangedHandler: (axes, movementState, featureContext) => { - movementState.moveX = Math.abs(axes.x) > featureContext.movementThreshold ? axes.x : 0; - movementState.moveY = Math.abs(axes.y) > featureContext.movementThreshold ? axes.y : 0; - }, - }, - ], -}; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the webxr specs version - */ -WebXRControllerMovement.Version = 1; -WebXRFeaturesManager.AddWebXRFeature(WebXRControllerMovement.Name, (xrSessionManager, options) => { - return () => new WebXRControllerMovement(xrSessionManager, options); -}, WebXRControllerMovement.Version, true); -//# sourceMappingURL=WebXRControllerMovement.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRLightEstimation.js - - - - - - - - - - - - - -/** - * Light Estimation Feature - * - * @since 5.0.0 - */ -class WebXRLightEstimation extends WebXRAbstractFeature { - /** - * Creates a new instance of the light estimation feature - * @param _xrSessionManager an instance of WebXRSessionManager - * @param options options to use when constructing this feature - */ - constructor(_xrSessionManager, - /** - * options to use when constructing this feature - */ - options) { - super(_xrSessionManager); - this.options = options; - this._canvasContext = null; - this._reflectionCubeMap = null; - this._xrLightEstimate = null; - this._xrLightProbe = null; - this._xrWebGLBinding = null; - this._lightDirection = math_vector_Vector3.Up().negateInPlace(); - this._lightColor = math_color_Color3.White(); - this._intensity = 1; - this._sphericalHarmonics = new SphericalHarmonics(); - this._cubeMapPollTime = Date.now(); - this._lightEstimationPollTime = Date.now(); - /** - * ARCore's reflection cube map size is 16x16. - * Once other systems support this feature we will need to change this to be dynamic. - * see https://github.com/immersive-web/lighting-estimation/blob/main/lighting-estimation-explainer.md#cube-map-open-questions - */ - this._reflectionCubeMapTextureSize = 16; - /** - * If createDirectionalLightSource is set to true this light source will be created automatically. - * Otherwise this can be set with an external directional light source. - * This light will be updated whenever the light estimation values change. - */ - this.directionalLight = null; - /** - * This observable will notify when the reflection cube map is updated. - */ - this.onReflectionCubeMapUpdatedObservable = new observable_Observable(); - /** - * Event Listener for "reflectionchange" events. - */ - this._updateReflectionCubeMap = () => { - var _a; - if (!this._xrLightProbe) { - return; - } - // check poll time, do not update if it has not been long enough - if (this.options.cubeMapPollInterval) { - const now = Date.now(); - if (now - this._cubeMapPollTime < this.options.cubeMapPollInterval) { - return; - } - this._cubeMapPollTime = now; - } - const lp = this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe); - if (lp && this._reflectionCubeMap) { - if (!this._reflectionCubeMap._texture) { - const internalTexture = new internalTexture_InternalTexture(this._xrSessionManager.scene.getEngine(), internalTexture_InternalTextureSource.Unknown); - internalTexture.isCube = true; - internalTexture.invertY = false; - internalTexture._useSRGBBuffer = this.options.reflectionFormat === "srgba8"; - internalTexture.format = 5; - internalTexture.generateMipMaps = true; - internalTexture.type = this.options.reflectionFormat !== "srgba8" ? 2 : 0; - internalTexture.samplingMode = 3; - internalTexture.width = this._reflectionCubeMapTextureSize; - internalTexture.height = this._reflectionCubeMapTextureSize; - internalTexture._cachedWrapU = 1; - internalTexture._cachedWrapV = 1; - internalTexture._hardwareTexture = new WebGLHardwareTexture(lp, this._getCanvasContext()); - this._reflectionCubeMap._texture = internalTexture; - } - else { - (_a = this._reflectionCubeMap._texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.set(lp); - this._reflectionCubeMap._texture.getEngine().resetTextureCache(); - } - this._reflectionCubeMap._texture.isReady = true; - this._xrSessionManager.scene.markAllMaterialsAsDirty(1); - this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap); - } - }; - this.xrNativeFeatureName = "light-estimation"; - if (this.options.createDirectionalLightSource) { - this.directionalLight = new DirectionalLight("light estimation directional", this._lightDirection, this._xrSessionManager.scene); - this.directionalLight.position = new math_vector_Vector3(0, 8, 0); - // intensity will be set later - this.directionalLight.intensity = 0; - this.directionalLight.falloffType = LightConstants.FALLOFF_GLTF; - } - // https://immersive-web.github.io/lighting-estimation/ - tools_Tools.Warn("light-estimation is an experimental and unstable feature."); - } - /** - * 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. - * Since creating and processing the cube map is potentially expensive, especially if mip maps are needed, you can listen to the onReflectionCubeMapUpdatedObservable to determine - * when it has been updated. - */ - get reflectionCubeMapTexture() { - return this._reflectionCubeMap; - } - /** - * The most recent light estimate. Available starting on the first frame where the device provides a light probe. - */ - get xrLightingEstimate() { - if (this._xrLightEstimate) { - return { - lightColor: this._lightColor, - lightDirection: this._lightDirection, - lightIntensity: this._intensity, - sphericalHarmonics: this._sphericalHarmonics, - }; - } - return this._xrLightEstimate; - } - _getCanvasContext() { - if (this._canvasContext === null) { - this._canvasContext = this._xrSessionManager.scene.getEngine()._gl; - } - return this._canvasContext; - } - _getXRGLBinding() { - if (this._xrWebGLBinding === null) { - const context = this._getCanvasContext(); - this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, context); - } - return this._xrWebGLBinding; - } - /** - * attach this feature - * Will usually be called by the features manager - * - * @returns true if successful. - */ - attach() { - var _a; - if (!super.attach()) { - return false; - } - const reflectionFormat = (_a = this.options.reflectionFormat) !== null && _a !== void 0 ? _a : (this._xrSessionManager.session.preferredReflectionFormat || "srgba8"); - this.options.reflectionFormat = reflectionFormat; - this._xrSessionManager.session - .requestLightProbe({ - reflectionFormat, - }) - .then((xrLightProbe) => { - this._xrLightProbe = xrLightProbe; - if (!this.options.disableCubeMapReflection) { - if (!this._reflectionCubeMap) { - this._reflectionCubeMap = new baseTexture_BaseTexture(this._xrSessionManager.scene); - this._reflectionCubeMap._isCube = true; - this._reflectionCubeMap.coordinatesMode = 3; - if (this.options.setSceneEnvironmentTexture) { - this._xrSessionManager.scene.environmentTexture = this._reflectionCubeMap; - } - } - this._xrLightProbe.addEventListener("reflectionchange", this._updateReflectionCubeMap); - } - }); - return true; - } - /** - * detach this feature. - * Will usually be called by the features manager - * - * @returns true if successful. - */ - detach() { - const detached = super.detach(); - if (this._xrLightProbe !== null && !this.options.disableCubeMapReflection) { - this._xrLightProbe.removeEventListener("reflectionchange", this._updateReflectionCubeMap); - this._xrLightProbe = null; - } - this._canvasContext = null; - this._xrLightEstimate = null; - // When the session ends (on detach) we must clear our XRWebGLBinging instance, which references the ended session. - this._xrWebGLBinding = null; - return detached; - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - super.dispose(); - this.onReflectionCubeMapUpdatedObservable.clear(); - if (this.directionalLight) { - this.directionalLight.dispose(); - this.directionalLight = null; - } - if (this._reflectionCubeMap !== null) { - if (this._reflectionCubeMap._texture) { - this._reflectionCubeMap._texture.dispose(); - } - this._reflectionCubeMap.dispose(); - this._reflectionCubeMap = null; - } - } - _onXRFrame(_xrFrame) { - var _a; - if (this._xrLightProbe !== null) { - if (this.options.lightEstimationPollInterval) { - const now = Date.now(); - if (now - this._lightEstimationPollTime < this.options.lightEstimationPollInterval) { - return; - } - this._lightEstimationPollTime = now; - } - this._xrLightEstimate = _xrFrame.getLightEstimate(this._xrLightProbe); - if (this._xrLightEstimate) { - this._intensity = Math.max(1.0, this._xrLightEstimate.primaryLightIntensity.x, this._xrLightEstimate.primaryLightIntensity.y, this._xrLightEstimate.primaryLightIntensity.z); - const rhsFactor = this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1.0; - // recreate the vector caches, so that the last one provided to the user will persist - if (this.options.disableVectorReuse) { - this._lightDirection = new math_vector_Vector3(); - this._lightColor = new math_color_Color3(); - if (this.directionalLight) { - this.directionalLight.direction = this._lightDirection; - this.directionalLight.diffuse = this._lightColor; - } - } - this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x, this._xrLightEstimate.primaryLightDirection.y, this._xrLightEstimate.primaryLightDirection.z * rhsFactor); - this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x / this._intensity, this._xrLightEstimate.primaryLightIntensity.y / this._intensity, this._xrLightEstimate.primaryLightIntensity.z / this._intensity); - this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients); - if (this._reflectionCubeMap && !this.options.disableSphericalPolynomial) { - this._reflectionCubeMap.sphericalPolynomial = this._reflectionCubeMap.sphericalPolynomial || new SphericalPolynomial(); - (_a = this._reflectionCubeMap.sphericalPolynomial) === null || _a === void 0 ? void 0 : _a.updateFromHarmonics(this._sphericalHarmonics); - } - // direction from instead of direction to - this._lightDirection.negateInPlace(); - // set the values after calculating them - if (this.directionalLight) { - this.directionalLight.direction.copyFrom(this._lightDirection); - this.directionalLight.intensity = Math.min(this._intensity, 1.0); - this.directionalLight.diffuse.copyFrom(this._lightColor); - } - } - } - } -} -/** - * The module's name - */ -WebXRLightEstimation.Name = webXRFeaturesManager_WebXRFeatureName.LIGHT_ESTIMATION; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRLightEstimation.Version = 1; -// register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRLightEstimation.Name, (xrSessionManager, options) => { - return () => new WebXRLightEstimation(xrSessionManager, options); -}, WebXRLightEstimation.Version, false); -//# sourceMappingURL=WebXRLightEstimation.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXREyeTracking.js - - - - - -/** - * The WebXR Eye Tracking feature grabs eye data from the device and provides it in an easy-access format. - * Currently only enabled for BabylonNative applications. - */ -class WebXREyeTracking extends WebXRAbstractFeature { - /** - * Creates a new instance of the XR eye tracking feature. - * @param _xrSessionManager An instance of WebXRSessionManager. - */ - constructor(_xrSessionManager) { - super(_xrSessionManager); - /** - * This observable will notify registered observers when eye tracking starts - */ - this.onEyeTrackingStartedObservable = new observable_Observable(); - /** - * This observable will notify registered observers when eye tracking ends - */ - this.onEyeTrackingEndedObservable = new observable_Observable(); - /** - * This observable will notify registered observers on each frame that has valid tracking - */ - this.onEyeTrackingFrameUpdateObservable = new observable_Observable(); - this._eyeTrackingStartListener = (event) => { - this._latestEyeSpace = event.gazeSpace; - this._gazeRay = new ray_Ray(math_vector_Vector3.Zero(), math_vector_Vector3.Forward()); - this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay); - }; - this._eyeTrackingEndListener = () => { - this._latestEyeSpace = null; - this._gazeRay = null; - this.onEyeTrackingEndedObservable.notifyObservers(); - }; - this.xrNativeFeatureName = "eye-tracking"; - if (this._xrSessionManager.session) { - this._init(); - } - else { - this._xrSessionManager.onXRSessionInit.addOnce(() => { - this._init(); - }); - } - } - /** - * Dispose this feature and all of the resources attached. - */ - 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(); - } - /** - * Returns whether the gaze data is valid or not - * @returns true if the data is valid - */ - get isEyeGazeValid() { - return !!this._gazeRay; - } - /** - * Get a reference to the gaze ray. This data is valid while eye tracking persists, and will be set to null when gaze data is no longer available - * @returns a reference to the gaze ray if it exists and is valid, returns null otherwise. - */ - getEyeGaze() { - return this._gazeRay; - } - _onXRFrame(frame) { - if (!this.attached || !frame) { - return; - } - if (this._latestEyeSpace && this._gazeRay) { - const pose = frame.getPose(this._latestEyeSpace, this._xrSessionManager.referenceSpace); - if (pose) { - this._gazeRay.origin.set(pose.transform.position.x, pose.transform.position.y, pose.transform.position.z); - const quat = pose.transform.orientation; - math_vector_TmpVectors.Quaternion[0].set(quat.x, quat.y, quat.z, quat.w); - if (!this._xrSessionManager.scene.useRightHandedSystem) { - this._gazeRay.origin.z *= -1; - math_vector_TmpVectors.Quaternion[0].z *= -1; - math_vector_TmpVectors.Quaternion[0].w *= -1; - math_vector_Vector3.LeftHandedForwardReadOnly.rotateByQuaternionToRef(math_vector_TmpVectors.Quaternion[0], this._gazeRay.direction); - } - else { - math_vector_Vector3.RightHandedForwardReadOnly.rotateByQuaternionToRef(math_vector_TmpVectors.Quaternion[0], this._gazeRay.direction); - } - this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay); - } - } - } - _init() { - // Only supported by BabylonNative - if (this._xrSessionManager.isNative) { - this._xrSessionManager.session.addEventListener("eyetrackingstart", this._eyeTrackingStartListener); - this._xrSessionManager.session.addEventListener("eyetrackingend", this._eyeTrackingEndListener); - } - } -} -/** - * The module's name - */ -WebXREyeTracking.Name = webXRFeaturesManager_WebXRFeatureName.EYE_TRACKING; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXREyeTracking.Version = 1; -WebXRFeaturesManager.AddWebXRFeature(WebXREyeTracking.Name, (xrSessionManager) => { - return () => new WebXREyeTracking(xrSessionManager); -}, WebXREyeTracking.Version, false); -//# sourceMappingURL=WebXREyeTracking.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRWalkingLocomotion.js - - - - - -class CircleBuffer { - constructor(numSamples, initializer) { - this._samples = []; - this._idx = 0; - for (let idx = 0; idx < numSamples; ++idx) { - this._samples.push(initializer ? initializer() : math_vector_Vector2.Zero()); - } - } - get length() { - return this._samples.length; - } - push(x, y) { - this._idx = (this._idx + this._samples.length - 1) % this._samples.length; - this.at(0).copyFromFloats(x, y); - } - at(idx) { - if (idx >= this._samples.length) { - throw new Error("Index out of bounds"); - } - return this._samples[(this._idx + idx) % this._samples.length]; - } -} -class FirstStepDetector { - constructor() { - this._samples = new CircleBuffer(20); - this._entropy = 0; - this.onFirstStepDetected = new observable_Observable(); - } - update(posX, posY, forwardX, forwardY) { - this._samples.push(posX, posY); - const origin = this._samples.at(0); - this._entropy *= this._entropyDecayFactor; - this._entropy += math_vector_Vector2.Distance(origin, this._samples.at(1)); - if (this._entropy > this._entropyThreshold) { - return; - } - let samePointIdx; - for (samePointIdx = this._samePointCheckStartIdx; samePointIdx < this._samples.length; ++samePointIdx) { - if (math_vector_Vector2.DistanceSquared(origin, this._samples.at(samePointIdx)) < this._samePointSquaredDistanceThreshold) { - break; - } - } - if (samePointIdx === this._samples.length) { - return; - } - let apexDistSquared = -1; - let apexIdx = 0; - for (let distSquared, idx = 1; idx < samePointIdx; ++idx) { - distSquared = math_vector_Vector2.DistanceSquared(origin, this._samples.at(idx)); - if (distSquared > apexDistSquared) { - apexIdx = idx; - apexDistSquared = distSquared; - } - } - if (apexDistSquared < this._apexSquaredDistanceThreshold) { - return; - } - const apex = this._samples.at(apexIdx); - const axis = apex.subtract(origin); - axis.normalize(); - const vec = math_vector_TmpVectors.Vector2[0]; - let dot; - let sample; - let sumSquaredProjectionDistances = 0; - for (let idx = 1; idx < samePointIdx; ++idx) { - sample = this._samples.at(idx); - sample.subtractToRef(origin, vec); - dot = math_vector_Vector2.Dot(axis, vec); - sumSquaredProjectionDistances += vec.lengthSquared() - dot * dot; - } - if (sumSquaredProjectionDistances > samePointIdx * this._squaredProjectionDistanceThreshold) { - return; - } - const forwardVec = math_vector_TmpVectors.Vector3[0]; - forwardVec.set(forwardX, forwardY, 0); - const axisVec = math_vector_TmpVectors.Vector3[1]; - axisVec.set(axis.x, axis.y, 0); - const isApexLeft = math_vector_Vector3.Cross(forwardVec, axisVec).z > 0; - const leftApex = origin.clone(); - const rightApex = origin.clone(); - apex.subtractToRef(origin, axis); - if (isApexLeft) { - axis.scaleAndAddToRef(this._axisToApexShrinkFactor, leftApex); - axis.scaleAndAddToRef(this._axisToApexExtendFactor, rightApex); - } - else { - axis.scaleAndAddToRef(this._axisToApexExtendFactor, leftApex); - axis.scaleAndAddToRef(this._axisToApexShrinkFactor, rightApex); - } - this.onFirstStepDetected.notifyObservers({ - leftApex: leftApex, - rightApex: rightApex, - currentPosition: origin, - currentStepDirection: isApexLeft ? "right" : "left", - }); - } - reset() { - for (let idx = 0; idx < this._samples.length; ++idx) { - this._samples.at(idx).copyFromFloats(0, 0); - } - } - get _samePointCheckStartIdx() { - return Math.floor(this._samples.length / 3); - } - get _samePointSquaredDistanceThreshold() { - return 0.03 * 0.03; - } - get _apexSquaredDistanceThreshold() { - return 0.09 * 0.09; - } - get _squaredProjectionDistanceThreshold() { - return 0.03 * 0.03; - } - get _axisToApexShrinkFactor() { - return 0.8; - } - get _axisToApexExtendFactor() { - return -1.6; - } - get _entropyDecayFactor() { - return 0.93; - } - get _entropyThreshold() { - return 0.4; - } -} -class WalkingTracker { - constructor(leftApex, rightApex, currentPosition, currentStepDirection) { - this._leftApex = new math_vector_Vector2(); - this._rightApex = new math_vector_Vector2(); - this._currentPosition = new math_vector_Vector2(); - this._axis = new math_vector_Vector2(); - this._axisLength = -1; - this._forward = new math_vector_Vector2(); - this._steppingLeft = false; - this._t = -1; - this._maxT = -1; - this._maxTPosition = new math_vector_Vector2(); - this._vitality = 0; - this.onMovement = new observable_Observable(); - this.onFootfall = new observable_Observable(); - this._reset(leftApex, rightApex, currentPosition, currentStepDirection === "left"); - } - _reset(leftApex, rightApex, currentPosition, steppingLeft) { - this._leftApex.copyFrom(leftApex); - this._rightApex.copyFrom(rightApex); - this._steppingLeft = steppingLeft; - if (this._steppingLeft) { - this._leftApex.subtractToRef(this._rightApex, this._axis); - this._forward.copyFromFloats(-this._axis.y, this._axis.x); - } - else { - this._rightApex.subtractToRef(this._leftApex, this._axis); - this._forward.copyFromFloats(this._axis.y, -this._axis.x); - } - this._axisLength = this._axis.length(); - this._forward.scaleInPlace(1 / this._axisLength); - this._updateTAndVitality(currentPosition.x, currentPosition.y); - this._maxT = this._t; - this._maxTPosition.copyFrom(currentPosition); - this._vitality = 1; - } - _updateTAndVitality(x, y) { - this._currentPosition.copyFromFloats(x, y); - if (this._steppingLeft) { - this._currentPosition.subtractInPlace(this._rightApex); - } - else { - this._currentPosition.subtractInPlace(this._leftApex); - } - const priorT = this._t; - const dot = math_vector_Vector2.Dot(this._currentPosition, this._axis); - this._t = dot / (this._axisLength * this._axisLength); - const projDistSquared = this._currentPosition.lengthSquared() - (dot / this._axisLength) * (dot / this._axisLength); - // TODO: Extricate the magic. - this._vitality *= 0.92 - 100 * Math.max(projDistSquared - 0.0016, 0) + Math.max(this._t - priorT, 0); - } - update(x, y) { - if (this._vitality < this._vitalityThreshold) { - return false; - } - const priorT = this._t; - this._updateTAndVitality(x, y); - if (this._t > this._maxT) { - this._maxT = this._t; - this._maxTPosition.copyFromFloats(x, y); - } - if (this._vitality < this._vitalityThreshold) { - return false; - } - if (this._t > priorT) { - this.onMovement.notifyObservers({ deltaT: this._t - priorT }); - if (priorT < 0.5 && this._t >= 0.5) { - this.onFootfall.notifyObservers({ foot: this._steppingLeft ? "left" : "right" }); - } - } - if (this._t < 0.95 * this._maxT) { - this._currentPosition.copyFromFloats(x, y); - if (this._steppingLeft) { - this._leftApex.copyFrom(this._maxTPosition); - } - else { - this._rightApex.copyFrom(this._maxTPosition); - } - this._reset(this._leftApex, this._rightApex, this._currentPosition, !this._steppingLeft); - } - if (this._axisLength < 0.03) { - return false; - } - return true; - } - get _vitalityThreshold() { - return 0.1; - } - get forward() { - return this._forward; - } -} -class Walker { - static get _MillisecondsPerUpdate() { - // 15 FPS - return 1000 / 15; - } - constructor(engine) { - this._detector = new FirstStepDetector(); - this._walker = null; - this._movement = new math_vector_Vector2(); - this._millisecondsSinceLastUpdate = Walker._MillisecondsPerUpdate; - this.movementThisFrame = math_vector_Vector3.Zero(); - this._engine = engine; - this._detector.onFirstStepDetected.add((event) => { - if (!this._walker) { - this._walker = new WalkingTracker(event.leftApex, event.rightApex, event.currentPosition, event.currentStepDirection); - this._walker.onFootfall.add(() => { - console.log("Footfall!"); - }); - this._walker.onMovement.add((event) => { - this._walker.forward.scaleAndAddToRef(0.024 * event.deltaT, this._movement); - }); - } - }); - } - update(position, forward) { - forward.y = 0; - forward.normalize(); - // Enforce reduced framerate - this._millisecondsSinceLastUpdate += this._engine.getDeltaTime(); - if (this._millisecondsSinceLastUpdate >= Walker._MillisecondsPerUpdate) { - this._millisecondsSinceLastUpdate -= Walker._MillisecondsPerUpdate; - this._detector.update(position.x, position.z, forward.x, forward.z); - if (this._walker) { - const updated = this._walker.update(position.x, position.z); - if (!updated) { - this._walker = null; - } - } - this._movement.scaleInPlace(0.85); - } - this.movementThisFrame.set(this._movement.x, 0, this._movement.y); - } -} -/** - * A module that will enable VR locomotion by detecting when the user walks in place. - */ -class WebXRWalkingLocomotion extends WebXRAbstractFeature { - /** - * The module's name. - */ - static get Name() { - return webXRFeaturesManager_WebXRFeatureName.WALKING_LOCOMOTION; - } - /** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number has no external basis. - */ - static get Version() { - return 1; - } - /** - * The target to be articulated by walking locomotion. - * When the walking locomotion feature detects walking in place, this element's - * X and Z coordinates will be modified to reflect locomotion. This target should - * be either the XR space's origin (i.e., the parent node of the WebXRCamera) or - * the WebXRCamera itself. Note that the WebXRCamera path will modify the position - * of the WebXRCamera directly and is thus discouraged. - */ - get locomotionTarget() { - return this._locomotionTarget; - } - /** - * The target to be articulated by walking locomotion. - * When the walking locomotion feature detects walking in place, this element's - * X and Z coordinates will be modified to reflect locomotion. This target should - * be either the XR space's origin (i.e., the parent node of the WebXRCamera) or - * the WebXRCamera itself. Note that the WebXRCamera path will modify the position - * of the WebXRCamera directly and is thus discouraged. - */ - set locomotionTarget(locomotionTarget) { - this._locomotionTarget = locomotionTarget; - this._isLocomotionTargetWebXRCamera = this._locomotionTarget.getClassName() === "WebXRCamera"; - } - /** - * Construct a new Walking Locomotion feature. - * @param sessionManager manager for the current XR session - * @param options creation options, prominently including the vector target for locomotion - */ - constructor(sessionManager, options) { - super(sessionManager); - this._up = new math_vector_Vector3(); - this._forward = new math_vector_Vector3(); - this._position = new math_vector_Vector3(); - this._movement = new math_vector_Vector3(); - this._sessionManager = sessionManager; - this.locomotionTarget = options.locomotionTarget; - if (this._isLocomotionTargetWebXRCamera) { - logger_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"); - } - } - /** - * Checks whether this feature is compatible with the current WebXR session. - * Walking locomotion is only compatible with "immersive-vr" sessions. - * @returns true if compatible, false otherwise - */ - isCompatible() { - return this._sessionManager.sessionMode === undefined || this._sessionManager.sessionMode === "immersive-vr"; - } - /** - * Attaches the feature. - * Typically called automatically by the features manager. - * @returns true if attach succeeded, false otherwise - */ - attach() { - if (!this.isCompatible || !super.attach()) { - return false; - } - this._walker = new Walker(this._sessionManager.scene.getEngine()); - return true; - } - /** - * Detaches the feature. - * Typically called automatically by the features manager. - * @returns true if detach succeeded, false otherwise - */ - detach() { - if (!super.detach()) { - return false; - } - this._walker = null; - return true; - } - _onXRFrame(frame) { - const pose = frame.getViewerPose(this._sessionManager.baseReferenceSpace); - if (!pose) { - return; - } - const handednessScalar = this.locomotionTarget.getScene().useRightHandedSystem ? 1 : -1; - const m = pose.transform.matrix; - this._up.copyFromFloats(m[4], m[5], handednessScalar * m[6]); - this._forward.copyFromFloats(m[8], m[9], handednessScalar * m[10]); - this._position.copyFromFloats(m[12], m[13], handednessScalar * m[14]); - // Compute the nape position - this._forward.scaleAndAddToRef(0.05, this._position); - this._up.scaleAndAddToRef(-0.05, this._position); - this._walker.update(this._position, this._forward); - this._movement.copyFrom(this._walker.movementThisFrame); - if (!this._isLocomotionTargetWebXRCamera) { - math_vector_Vector3.TransformNormalToRef(this._movement, this.locomotionTarget.getWorldMatrix(), this._movement); - } - this.locomotionTarget.position.addInPlace(this._movement); - } -} -//register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRWalkingLocomotion.Name, (xrSessionManager, options) => { - return () => new WebXRWalkingLocomotion(xrSessionManager, options); -}, WebXRWalkingLocomotion.Version, false); -//# sourceMappingURL=WebXRWalkingLocomotion.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRLayers.js - - - - - -/** - * Wraps xr composition layers. - * @internal - */ -class WebXRCompositionLayerWrapper extends WebXRLayerWrapper { - constructor(getWidth, getHeight, layer, layerType, isMultiview, createRTTProvider) { - super(getWidth, getHeight, layer, layerType, createRTTProvider); - this.getWidth = getWidth; - this.getHeight = getHeight; - this.layer = layer; - this.layerType = layerType; - this.isMultiview = isMultiview; - this.createRTTProvider = createRTTProvider; - } -} -/** - * Provides render target textures and other important rendering information for a given XRCompositionLayer. - * @internal - */ -class WebXRCompositionLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider { - constructor(_xrSessionManager, _xrWebGLBinding, layerWrapper) { - super(_xrSessionManager.scene, layerWrapper); - this._xrSessionManager = _xrSessionManager; - this._xrWebGLBinding = _xrWebGLBinding; - this.layerWrapper = layerWrapper; - this._lastSubImages = new Map(); - this._compositionLayer = layerWrapper.layer; - } - _getRenderTargetForSubImage(subImage, eye) { - var _a, _b, _c, _d; - const lastSubImage = this._lastSubImages.get(eye); - const eyeIndex = eye == "left" ? 0 : 1; - const colorTextureWidth = (_a = subImage.colorTextureWidth) !== null && _a !== void 0 ? _a : subImage.textureWidth; - const colorTextureHeight = (_b = subImage.colorTextureHeight) !== null && _b !== void 0 ? _b : subImage.textureHeight; - if (!this._renderTargetTextures[eyeIndex] || (lastSubImage === null || lastSubImage === void 0 ? void 0 : lastSubImage.textureWidth) !== colorTextureWidth || (lastSubImage === null || lastSubImage === void 0 ? void 0 : lastSubImage.textureHeight) !== colorTextureHeight) { - let depthStencilTexture; - const depthStencilTextureWidth = (_c = subImage.depthStencilTextureWidth) !== null && _c !== void 0 ? _c : colorTextureWidth; - const depthStencilTextureHeight = (_d = subImage.depthStencilTextureHeight) !== null && _d !== void 0 ? _d : colorTextureHeight; - if (colorTextureWidth === depthStencilTextureWidth || colorTextureHeight === depthStencilTextureHeight) { - depthStencilTexture = subImage.depthStencilTexture; - } - this._renderTargetTextures[eyeIndex] = this._createRenderTargetTexture(colorTextureWidth, colorTextureHeight, null, subImage.colorTexture, depthStencilTexture, this.layerWrapper.isMultiview); - this._framebufferDimensions = { - framebufferWidth: colorTextureWidth, - framebufferHeight: colorTextureHeight, - }; - } - this._lastSubImages.set(eye, subImage); - return this._renderTargetTextures[eyeIndex]; - } - _getSubImageForEye(eye) { - const currentFrame = this._xrSessionManager.currentFrame; - if (currentFrame) { - return this._xrWebGLBinding.getSubImage(this._compositionLayer, currentFrame, eye); - } - return null; - } - getRenderTargetTextureForEye(eye) { - const subImage = this._getSubImageForEye(eye); - if (subImage) { - return this._getRenderTargetForSubImage(subImage, eye); - } - return null; - } - getRenderTargetTextureForView(view) { - return this.getRenderTargetTextureForEye(view.eye); - } - _setViewportForSubImage(viewport, subImage) { - var _a, _b; - const textureWidth = (_a = subImage.colorTextureWidth) !== null && _a !== void 0 ? _a : subImage.textureWidth; - const textureHeight = (_b = subImage.colorTextureWidth) !== null && _b !== void 0 ? _b : subImage.textureHeight; - const xrViewport = subImage.viewport; - viewport.x = xrViewport.x / textureWidth; - viewport.y = xrViewport.y / textureHeight; - viewport.width = xrViewport.width / textureWidth; - viewport.height = xrViewport.height / textureHeight; - } - trySetViewportForView(viewport, view) { - const subImage = this._lastSubImages.get(view.eye) || this._getSubImageForEye(view.eye); - if (subImage) { - this._setViewportForSubImage(viewport, subImage); - return true; - } - return false; - } -} -/** - * Wraps xr projection layers. - * @internal - */ -class WebXRProjectionLayerWrapper extends WebXRCompositionLayerWrapper { - constructor(layer, isMultiview, xrGLBinding) { - super(() => layer.textureWidth, () => layer.textureHeight, layer, "XRProjectionLayer", isMultiview, (sessionManager) => new WebXRProjectionLayerRenderTargetTextureProvider(sessionManager, xrGLBinding, this)); - this.layer = layer; - } -} -/** - * Provides render target textures and other important rendering information for a given XRProjectionLayer. - * @internal - */ -class WebXRProjectionLayerRenderTargetTextureProvider extends WebXRCompositionLayerRenderTargetTextureProvider { - constructor(_xrSessionManager, _xrWebGLBinding, layerWrapper) { - super(_xrSessionManager, _xrWebGLBinding, layerWrapper); - this.layerWrapper = layerWrapper; - this._projectionLayer = layerWrapper.layer; - } - _getSubImageForView(view) { - return this._xrWebGLBinding.getViewSubImage(this._projectionLayer, view); - } - getRenderTargetTextureForView(view) { - return this._getRenderTargetForSubImage(this._getSubImageForView(view), view.eye); - } - getRenderTargetTextureForEye(eye) { - const lastSubImage = this._lastSubImages.get(eye); - if (lastSubImage) { - return this._getRenderTargetForSubImage(lastSubImage, eye); - } - return null; - } - trySetViewportForView(viewport, view) { - const subImage = this._lastSubImages.get(view.eye) || this._getSubImageForView(view); - if (subImage) { - this._setViewportForSubImage(viewport, subImage); - return true; - } - return false; - } -} -const defaultXRWebGLLayerInit = {}; -const defaultXRProjectionLayerInit = { - textureType: "texture", - colorFormat: 0x1908 /* WebGLRenderingContext.RGBA */, - depthFormat: 0x88f0 /* WebGLRenderingContext.DEPTH24_STENCIL8 */, - scaleFactor: 1.0, -}; -/** - * Exposes the WebXR Layers API. - */ -class WebXRLayers extends WebXRAbstractFeature { - constructor(_xrSessionManager, _options = {}) { - super(_xrSessionManager); - this._options = _options; - /** - * Already-created layers - */ - this._existingLayers = []; - this.xrNativeFeatureName = "layers"; - } - /** - * Attach this feature. - * Will usually be called by the features manager. - * - * @returns true if successful. - */ - attach() { - if (!super.attach()) { - return false; - } - const engine = this._xrSessionManager.scene.getEngine(); - this._glContext = engine._gl; - this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, this._glContext); - this._existingLayers.length = 0; - const projectionLayerInit = Object.assign({}, defaultXRProjectionLayerInit); - const projectionLayerMultiview = this._options.preferMultiviewOnInit && engine.getCaps().multiview; - if (projectionLayerMultiview) { - projectionLayerInit.textureType = "texture-array"; - } - this.addXRSessionLayer(this.createProjectionLayer(projectionLayerInit, projectionLayerMultiview)); - return true; - } - detach() { - if (!super.detach()) { - return false; - } - this._existingLayers.length = 0; - return true; - } - /** - * Creates a new XRWebGLLayer. - * @param params an object providing configuration options for the new XRWebGLLayer - * @returns the XRWebGLLayer - */ - createXRWebGLLayer(params = defaultXRWebGLLayerInit) { - const layer = new XRWebGLLayer(this._xrSessionManager.session, this._glContext, params); - return new WebXRWebGLLayerWrapper(layer); - } - /** - * Creates a new XRProjectionLayer. - * @param params an object providing configuration options for the new XRProjectionLayer. - * @param multiview whether the projection layer should render with multiview. - * @returns the projection layer - */ - createProjectionLayer(params = defaultXRProjectionLayerInit, multiview = false) { - if (multiview && params.textureType !== "texture-array") { - throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'."); - } - // TODO (rgerd): Support RTT's that are bound to sub-images in the texture array. - if (!multiview && params.textureType === "texture-array") { - throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'."); - } - const projLayer = this._xrWebGLBinding.createProjectionLayer(params); - return new WebXRProjectionLayerWrapper(projLayer, multiview, this._xrWebGLBinding); - } - /** - * Add a new layer to the already-existing list of layers - * @param wrappedLayer the new layer to add to the existing ones - */ - addXRSessionLayer(wrappedLayer) { - this.setXRSessionLayers([...this._existingLayers, wrappedLayer]); - } - /** - * Sets the layers to be used by the XR session. - * Note that you must call this function with any layers you wish to render to - * since it adds them to the XR session's render state - * (replacing any layers that were added in a previous call to setXRSessionLayers or updateRenderState). - * This method also sets up the session manager's render target texture provider - * as the first layer in the array, which feeds the WebXR camera(s) attached to the session. - * @param wrappedLayers An array of WebXRLayerWrapper, usually returned from the WebXRLayers createLayer functions. - */ - setXRSessionLayers(wrappedLayers) { - this._existingLayers = wrappedLayers; - const renderStateInit = Object.assign({}, this._xrSessionManager.session.renderState); - // Clear out the layer-related fields. - renderStateInit.baseLayer = undefined; - renderStateInit.layers = wrappedLayers.map((wrappedLayer) => wrappedLayer.layer); - this._xrSessionManager.updateRenderState(renderStateInit); - this._xrSessionManager._setBaseLayerWrapper(wrappedLayers.length > 0 ? wrappedLayers[0] : null); - } - isCompatible() { - // TODO (rgerd): Add native support. - return !this._xrSessionManager.isNative && typeof XRWebGLBinding !== "undefined" && !!XRWebGLBinding.prototype.createProjectionLayer; - } - /** - * Dispose this feature and all of the resources attached. - */ - dispose() { - super.dispose(); - } - _onXRFrame(_xrFrame) { - /* empty */ - } -} -/** - * The module's name - */ -WebXRLayers.Name = webXRFeaturesManager_WebXRFeatureName.LAYERS; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRLayers.Version = 1; -//register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRLayers.Name, (xrSessionManager, options) => { - return () => new WebXRLayers(xrSessionManager, options); -}, WebXRLayers.Version, false); -//# sourceMappingURL=WebXRLayers.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRDepthSensing.js - - - - - - - - - - -/** - * WebXR Feature for WebXR Depth Sensing Module - * @since 5.49.1 - */ -class WebXRDepthSensing extends WebXRAbstractFeature { - /** - * Width of depth data. If depth data is not exist, returns null. - */ - get width() { - return this._width; - } - /** - * Height of depth data. If depth data is not exist, returns null. - */ - get height() { - return this._height; - } - /** - * Scale factor by which the raw depth values must be multiplied in order to get the depths in meters. - */ - get rawValueToMeters() { - return this._rawValueToMeters; - } - /** - * An XRRigidTransform that needs to be applied when indexing into the depth buffer. - */ - get normDepthBufferFromNormView() { - return this._normDepthBufferFromNormView; - } - /** - * Describes which depth-sensing usage ("cpu" or "gpu") is used. - */ - get depthUsage() { - switch (this._xrSessionManager.session.depthUsage) { - case "cpu-optimized": - return "cpu"; - case "gpu-optimized": - return "gpu"; - } - } - /** - * Describes which depth sensing data format ("ushort" or "float") is used. - */ - get depthDataFormat() { - switch (this._xrSessionManager.session.depthDataFormat) { - case "luminance-alpha": - return "ushort"; - case "float32": - return "float"; - } - } - /** - * Latest cached InternalTexture which containing depth buffer information. - * This can be used when the depth usage is "gpu". - */ - get latestInternalTexture() { - var _a, _b; - if (!this._cachedWebGLTexture) { - return null; - } - const engine = this._xrSessionManager.scene.getEngine(); - const internalTexture = new internalTexture_InternalTexture(engine, internalTexture_InternalTextureSource.Unknown); - internalTexture.isCube = false; - internalTexture.invertY = false; - internalTexture._useSRGBBuffer = false; - internalTexture.format = this.depthDataFormat === "ushort" ? 2 : 5; - internalTexture.generateMipMaps = false; - internalTexture.type = this.depthDataFormat === "ushort" ? 5 : 1; - internalTexture.samplingMode = 7; - internalTexture.width = (_a = this.width) !== null && _a !== void 0 ? _a : 0; - internalTexture.height = (_b = this.height) !== null && _b !== void 0 ? _b : 0; - internalTexture._cachedWrapU = 1; - internalTexture._cachedWrapV = 1; - internalTexture._hardwareTexture = new WebGLHardwareTexture(this._cachedWebGLTexture, engine._gl); - return internalTexture; - } - /** - * cached depth buffer - */ - get latestDepthBuffer() { - if (!this._cachedDepthBuffer) { - return null; - } - return this.depthDataFormat === "ushort" ? new Uint16Array(this._cachedDepthBuffer) : new Float32Array(this._cachedDepthBuffer); - } - /** - * Latest cached Texture of depth image which is made from the depth buffer data. - */ - get latestDepthImageTexture() { - return this._cachedDepthImageTexture; - } - /** - * Creates a new instance of the depth sensing feature - * @param _xrSessionManager the WebXRSessionManager - * @param options options for WebXR Depth Sensing Feature - */ - constructor(_xrSessionManager, options) { - super(_xrSessionManager); - this.options = options; - this._width = null; - this._height = null; - this._rawValueToMeters = null; - this._normDepthBufferFromNormView = null; - this._cachedDepthBuffer = null; - this._cachedWebGLTexture = null; - this._cachedDepthImageTexture = null; - /** - * Event that notify when `DepthInformation.getDepthInMeters` is available. - * `getDepthInMeters` method needs active XRFrame (not available for cached XRFrame) - */ - this.onGetDepthInMetersAvailable = new observable_Observable(); - this.xrNativeFeatureName = "depth-sensing"; - // https://immersive-web.github.io/depth-sensing/ - tools_Tools.Warn("depth-sensing is an experimental and unstable feature."); - } - /** - * attach this feature - * Will usually be called by the features manager - * - * @returns true if successful. - */ - attach(force) { - if (!super.attach(force)) { - return false; - } - const isBothDepthUsageAndFormatNull = this._xrSessionManager.session.depthDataFormat == null || this._xrSessionManager.session.depthUsage == null; - if (isBothDepthUsageAndFormatNull) { - return false; - } - this._glBinding = new XRWebGLBinding(this._xrSessionManager.session, this._xrSessionManager.scene.getEngine()._gl); - return true; - } - /** - * Dispose this feature and all of the resources attached - */ - dispose() { - var _a; - (_a = this._cachedDepthImageTexture) === null || _a === void 0 ? void 0 : _a.dispose(); - } - _onXRFrame(_xrFrame) { - const referenceSPace = this._xrSessionManager.referenceSpace; - const pose = _xrFrame.getViewerPose(referenceSPace); - if (pose == null) { - return; - } - for (const view of pose.views) { - switch (this.depthUsage) { - case "cpu": - this._updateDepthInformationAndTextureCPUDepthUsage(_xrFrame, view, this.depthDataFormat); - break; - case "gpu": - if (!this._glBinding) { - break; - } - this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding, view, this.depthDataFormat); - break; - default: - tools_Tools.Error("Unknown depth usage"); - this.detach(); - break; - } - } - } - _updateDepthInformationAndTextureCPUDepthUsage(frame, view, dataFormat) { - const depthInfo = frame.getDepthInformation(view); - if (depthInfo === null) { - return; - } - const { data, width, height, rawValueToMeters, getDepthInMeters } = depthInfo; - this._width = width; - this._height = height; - this._rawValueToMeters = rawValueToMeters; - this._cachedDepthBuffer = data; - // to avoid Illegal Invocation error, bind `this` - this.onGetDepthInMetersAvailable.notifyObservers(getDepthInMeters.bind(depthInfo)); - if (!this._cachedDepthImageTexture) { - this._cachedDepthImageTexture = rawTexture_RawTexture.CreateRTexture(null, width, height, this._xrSessionManager.scene, false, true, texture_Texture.NEAREST_SAMPLINGMODE, engine_Engine.TEXTURETYPE_FLOAT); - } - switch (dataFormat) { - case "ushort": - this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(data)).map((value) => value * rawValueToMeters)); - break; - case "float": - this._cachedDepthImageTexture.update(new Float32Array(data).map((value) => value * rawValueToMeters)); - break; - default: - break; - } - } - _updateDepthInformationAndTextureWebGLDepthUsage(webglBinding, view, dataFormat) { - const depthInfo = webglBinding.getDepthInformation(view); - if (depthInfo === null) { - return; - } - const { texture, width, height } = depthInfo; - this._width = width; - this._height = height; - this._cachedWebGLTexture = texture; - const scene = this._xrSessionManager.scene; - const engine = scene.getEngine(); - const internalTexture = engine.wrapWebGLTexture(texture); - if (!this._cachedDepthImageTexture) { - this._cachedDepthImageTexture = rawTexture_RawTexture.CreateRTexture(null, width, height, scene, false, true, texture_Texture.NEAREST_SAMPLINGMODE, dataFormat === "ushort" ? engine_Engine.TEXTURETYPE_UNSIGNED_BYTE : engine_Engine.TEXTURETYPE_FLOAT); - } - this._cachedDepthImageTexture._texture = internalTexture; - } - /** - * Extends the session init object if needed - * @returns augmentation object for the xr session init object. - */ - getXRSessionInitExtension() { - const isDepthUsageDeclared = this.options.usagePreference != null && this.options.usagePreference.length !== 0; - const isDataFormatDeclared = this.options.dataFormatPreference != null && this.options.dataFormatPreference.length !== 0; - return new Promise((resolve) => { - if (isDepthUsageDeclared && isDataFormatDeclared) { - const usages = this.options.usagePreference.map((usage) => { - switch (usage) { - case "cpu": - return "cpu-optimized"; - case "gpu": - return "gpu-optimized"; - } - }); - const dataFormats = this.options.dataFormatPreference.map((format) => { - switch (format) { - case "ushort": - return "luminance-alpha"; - case "float": - return "float32"; - } - }); - resolve({ - depthSensing: { - usagePreference: usages, - dataFormatPreference: dataFormats, - }, - }); - } - else { - resolve({}); - } - }); - } -} -/** - * The module's name - */ -WebXRDepthSensing.Name = webXRFeaturesManager_WebXRFeatureName.DEPTH_SENSING; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRDepthSensing.Version = 1; -WebXRFeaturesManager.AddWebXRFeature(WebXRDepthSensing.Name, (xrSessionManager, options) => { - return () => new WebXRDepthSensing(xrSessionManager, options); -}, WebXRDepthSensing.Version, false); -//# sourceMappingURL=WebXRDepthSensing.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/velocity.fragment.js -// Do not edit. - -const velocity_fragment_name = "velocityPixelShader"; -const velocity_fragment_shader = `precision highp float; -#define CUSTOM_FRAGMENT_BEGIN -varying vec4 clipPos;varying vec4 previousClipPos; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; -#define CUSTOM_FRAGMENT_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[velocity_fragment_name] = velocity_fragment_shader; -/** @internal */ -const velocityPixelShader = { name: velocity_fragment_name, shader: velocity_fragment_shader }; -//# sourceMappingURL=velocity.fragment.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Shaders/velocity.vertex.js -// Do not edit. - - - -const velocity_vertex_name = "velocityVertexShader"; -const velocity_vertex_shader = `#define CUSTOM_VERTEX_BEGIN -#define VELOCITY -attribute vec3 position; -#include<instancesDeclaration> -uniform mat4 viewProjection;uniform mat4 previousViewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; -#endif -varying vec4 clipPos;varying vec4 previousClipPos; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#include<instancesVertex> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} -#elif -clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -}`; -// Sideeffect -ShaderStore.ShadersStore[velocity_vertex_name] = velocity_vertex_shader; -/** @internal */ -const velocityVertexShader = { name: velocity_vertex_name, shader: velocity_vertex_shader }; -//# sourceMappingURL=velocity.vertex.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/WebXRSpaceWarp.js - - - - - - - - -/** - * Used for Space Warp render process - */ -class XRSpaceWarpRenderTarget extends renderTargetTexture_RenderTargetTexture { - /** - * Creates a Space Warp render target - * @param motionVectorTexture WebGLTexture provided by WebGLSubImage - * @param depthStencilTexture WebGLTexture provided by WebGLSubImage - * @param scene scene used with the render target - * @param size the size of the render target (used for each view) - */ - constructor(motionVectorTexture, depthStencilTexture, scene, size = 512) { - super("spacewarp rtt", size, scene, false, true, 2, false, undefined, false, false, true, undefined, true); - this._originalPairing = []; - this._previousWorldMatrices = []; - this._previousTransforms = [math_vector_Matrix.Identity(), math_vector_Matrix.Identity()]; - this._renderTarget = this.getScene() - .getEngine() - .createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight(), motionVectorTexture, depthStencilTexture); - this._renderTarget._disposeOnlyFramebuffers = true; - this._texture = this._renderTarget.texture; - this._texture.isMultiview = true; - this._texture.format = 5; - if (scene) { - this._velocityMaterial = new shaderMaterial_ShaderMaterial("velocity shader material", scene, { - vertex: "velocity", - fragment: "velocity", - }, { - uniforms: ["world", "previousWorld", "viewProjection", "viewProjectionR", "previousViewProjection", "previousViewProjectionR"], - }); - this._velocityMaterial._materialHelperNeedsPreviousMatrices = true; - this._velocityMaterial.onBindObservable.add((mesh) => { - // mesh. getWorldMatrix can be incorrect under rare conditions (e.g. when using a effective mesh in the render function). - // 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 - this._previousWorldMatrices[mesh.uniqueId] = this._previousWorldMatrices[mesh.uniqueId] || mesh.getWorldMatrix(); - this._velocityMaterial.getEffect().setMatrix("previousWorld", this._previousWorldMatrices[mesh.uniqueId]); - this._previousWorldMatrices[mesh.uniqueId] = mesh.getWorldMatrix(); - // now set the scene's previous matrix - this._velocityMaterial.getEffect().setMatrix("previousViewProjection", this._previousTransforms[0]); - // multiview for sure - this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR", this._previousTransforms[1]); - // store the previous (current, to be exact) transforms - this._previousTransforms[0].copyFrom(scene.getTransformMatrix()); - this._previousTransforms[1].copyFrom(scene._transformMatrixR); - }); - this._velocityMaterial.freeze(); - } - } - /** - * {@inheritDoc} - */ - render(useCameraPostProcess = false, dumpForDebug = false) { - // Swap to use velocity material - this._originalPairing.length = 0; - const scene = this.getScene(); - // set the velocity material to render the velocity RTT - if (scene && this._velocityMaterial) { - scene.getActiveMeshes().forEach((mesh) => { - this._originalPairing.push([mesh, mesh.material]); - mesh.material = this._velocityMaterial; - }); - } - super.render(useCameraPostProcess, dumpForDebug); - // Restore original materials - this._originalPairing.forEach((tuple) => { - tuple[0].material = tuple[1]; - }); - } - /** - * @internal - */ - _bindFrameBuffer() { - if (!this._renderTarget) { - return; - } - this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget); - } - /** - * Gets the number of views the corresponding to the texture (eg. a SpaceWarpRenderTarget will have > 1) - * @returns the view count - */ - getViewCount() { - return 2; - } - /** - * {@inheritdoc} - */ - dispose() { - super.dispose(); - this._velocityMaterial.dispose(); - this._previousTransforms.length = 0; - this._previousWorldMatrices.length = 0; - this._originalPairing.length = 0; - } -} -/** - * WebXR Space Warp Render Target Texture Provider - */ -class WebXRSpaceWarpRenderTargetTextureProvider { - constructor(_scene, _xrSessionManager, _xrWebGLBinding) { - this._scene = _scene; - this._xrSessionManager = _xrSessionManager; - this._xrWebGLBinding = _xrWebGLBinding; - this._lastSubImages = new Map(); - this._renderTargetTextures = new Map(); - this._engine = _scene.getEngine(); - } - _getSubImageForView(view) { - const layerWrapper = this._xrSessionManager._getBaseLayerWrapper(); - if (!layerWrapper) { - throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer."); - } - if (layerWrapper.layerType !== "XRProjectionLayer") { - throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".'); - } - const layer = layerWrapper.layer; - return this._xrWebGLBinding.getViewSubImage(layer, view); - } - _setViewportForSubImage(viewport, subImage) { - viewport.x = 0; - viewport.y = 0; - viewport.width = subImage.motionVectorTextureWidth; - viewport.height = subImage.motionVectorTextureHeight; - } - _createRenderTargetTexture(width, height, framebuffer, motionVectorTexture, depthStencilTexture) { - if (!this._engine) { - throw new Error("Engine is disposed"); - } - const textureSize = { width, height }; - // Create render target texture from the internal texture - const renderTargetTexture = new XRSpaceWarpRenderTarget(motionVectorTexture, depthStencilTexture, this._scene, textureSize); - const renderTargetWrapper = renderTargetTexture.renderTarget; - if (framebuffer) { - renderTargetWrapper._framebuffer = framebuffer; - } - // Create internal texture - renderTargetWrapper._colorTextureArray = motionVectorTexture; - renderTargetWrapper._depthStencilTextureArray = depthStencilTexture; - renderTargetTexture.disableRescaling(); - renderTargetTexture.renderListPredicate = () => true; - return renderTargetTexture; - } - _getRenderTargetForSubImage(subImage, view) { - const lastSubImage = this._lastSubImages.get(view); - let renderTargetTexture = this._renderTargetTextures.get(view.eye); - const width = subImage.motionVectorTextureWidth; - const height = subImage.motionVectorTextureHeight; - if (!renderTargetTexture || (lastSubImage === null || lastSubImage === void 0 ? void 0 : lastSubImage.textureWidth) !== width || (lastSubImage === null || lastSubImage === void 0 ? void 0 : lastSubImage.textureHeight) != height) { - renderTargetTexture = this._createRenderTargetTexture(width, height, null, subImage.motionVectorTexture, subImage.depthStencilTexture); - this._renderTargetTextures.set(view.eye, renderTargetTexture); - this._framebufferDimensions = { - framebufferWidth: width, - framebufferHeight: height, - }; - } - this._lastSubImages.set(view, subImage); - return renderTargetTexture; - } - /** - * {@inheritDoc} - */ - trySetViewportForView(viewport, view) { - const subImage = this._lastSubImages.get(view) || this._getSubImageForView(view); - if (subImage) { - this._setViewportForSubImage(viewport, subImage); - return true; - } - return false; - } - /** - * Access the motion vector (which will turn on Space Warp) - * @param view the view to access the motion vector texture for - */ - accessMotionVector(view) { - const subImage = this._getSubImageForView(view); - if (subImage) { - // Meta Quest Browser uses accessing these textures as a sign for turning on Space Warp - subImage.motionVectorTexture; - subImage.depthStencilTexture; - } - } - /** - * {@inheritDoc} - */ - getRenderTargetTextureForEye(_eye) { - return null; - } - /** - * {@inheritDoc} - */ - getRenderTargetTextureForView(view) { - const subImage = this._getSubImageForView(view); - if (subImage) { - return this._getRenderTargetForSubImage(subImage, view); - } - return null; - } - /** - * {@inheritDoc} - */ - dispose() { - this._renderTargetTextures.forEach((rtt) => rtt.dispose()); - this._renderTargetTextures.clear(); - } -} -/** - * the WebXR Space Warp feature. - */ -class WebXRSpaceWarp extends WebXRAbstractFeature { - /** - * constructor for the space warp feature - * @param _xrSessionManager the xr session manager for this feature - */ - constructor(_xrSessionManager) { - super(_xrSessionManager); - /** - * {@inheritdoc} - */ - this.dependsOn = [webXRFeaturesManager_WebXRFeatureName.LAYERS]; - this.xrNativeFeatureName = "space-warp"; - this._xrSessionManager.scene.needsPreviousWorldMatrices = true; - } - /** - * Attach this feature. - * Will usually be called by the features manager. - * - * @returns true if successful. - */ - attach() { - if (!super.attach()) { - return false; - } - const engine = this._xrSessionManager.scene.getEngine(); - this._glContext = engine._gl; - this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, this._glContext); - this.spaceWarpRTTProvider = new WebXRSpaceWarpRenderTargetTextureProvider(this._xrSessionManager.scene, this._xrSessionManager, this._xrWebGLBinding); - this._xrSessionManager.scene.onAfterRenderObservable.add(this._onAfterRender.bind(this)); - return true; - } - _onAfterRender() { - if (this.attached && this._renderTargetTexture) { - this._renderTargetTexture.render(false, false); - } - } - /** - * {@inheritdoc} - */ - isCompatible() { - return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat || false; - } - /** - * {@inheritdoc} - */ - dispose() { - super.dispose(); - } - _onXRFrame(_xrFrame) { - const pose = _xrFrame.getViewerPose(this._xrSessionManager.referenceSpace); - if (!pose) { - return; - } - // get the first view to which we will create a texture (or update it) - const view = pose.views[0]; - this._renderTargetTexture = this._renderTargetTexture || this.spaceWarpRTTProvider.getRenderTargetTextureForView(view); - this.spaceWarpRTTProvider.accessMotionVector(view); - } -} -/** - * The module's name - */ -WebXRSpaceWarp.Name = webXRFeaturesManager_WebXRFeatureName.SPACE_WARP; -/** - * The (Babylon) version of this module. - * This is an integer representing the implementation version. - * This number does not correspond to the WebXR specs version - */ -WebXRSpaceWarp.Version = 1; -//register the plugin -WebXRFeaturesManager.AddWebXRFeature(WebXRSpaceWarp.Name, (xrSessionManager) => { - return () => new WebXRSpaceWarp(xrSessionManager); -}, WebXRSpaceWarp.Version, false); -//# sourceMappingURL=WebXRSpaceWarp.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/features/index.js - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/motionController/webXRGenericHandController.js - - -/** - * A generic hand controller class that supports select and a secondary grasp - */ -class WebXRGenericHandController extends WebXRAbstractMotionController { - /** - * Create a new hand controller object, without loading a controller model - * @param scene the scene to use to create this controller - * @param gamepadObject the corresponding gamepad object - * @param handedness the handedness of the controller - */ - constructor(scene, gamepadObject, handedness) { - // Don't load the controller model - for now, hands have no real model. - super(scene, GenericHandSelectGraspProfile[handedness], gamepadObject, handedness, true); - this.profileId = "generic-hand-select-grasp"; - } - _getFilenameAndPath() { - return { - filename: "generic.babylon", - path: "https://controllers.babylonjs.com/generic/", - }; - } - _getModelLoadingConstraints() { - return true; - } - _processLoadedModel(_meshes) { - // no-op - } - _setRootMesh(meshes) { - // no-op - } - _updateModel() { - // no-op - } -} -// register the profiles -WebXRMotionControllerManager.RegisterController("generic-hand-select-grasp", (xrInput, scene) => { - return new WebXRGenericHandController(scene, xrInput.gamepad, xrInput.handedness); -}); -// https://github.com/immersive-web/webxr-input-profiles/blob/main/packages/registry/profiles/generic/generic-hand-select-grasp.json -const GenericHandSelectGraspProfile = { - left: { - selectComponentId: "xr-standard-trigger", - components: { - // eslint-disable-next-line @typescript-eslint/naming-convention - "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: { - // eslint-disable-next-line @typescript-eslint/naming-convention - "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: { - // eslint-disable-next-line @typescript-eslint/naming-convention - "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", - }, -}; -//# sourceMappingURL=webXRGenericHandController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/motionController/webXRMicrosoftMixedRealityController.js - - - - - - -/** - * The motion controller class for all microsoft mixed reality controllers - */ -class WebXRMicrosoftMixedRealityController extends WebXRAbstractMotionController { - constructor(scene, gamepadObject, handedness) { - super(scene, MixedRealityProfile["left-right"], gamepadObject, handedness); - // use this in the future - https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/assets/profiles/microsoft - 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", // TODO - use this for visual feedback - }, - "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 filename = ""; - if (this.handedness === "left") { - filename = WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME; - } - else { - // Right is the default if no hand is specified - filename = WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME; - } - const device = "default"; - const path = WebXRMicrosoftMixedRealityController.MODEL_BASE_URL + device + "/"; - return { - filename, - path, - }; - } - _getModelLoadingConstraints() { - const glbLoaded = sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb"); - if (!glbLoaded) { - logger_Logger.Warn("glTF / glb loaded was not registered, using generic controller instead"); - } - return glbLoaded; - } - _processLoadedModel(_meshes) { - if (!this.rootMesh) { - return; - } - // Button Meshes - this.getComponentIds().forEach((id, i) => { - if (this.disableAnimation) { - return; - } - if (id && this.rootMesh) { - const buttonMap = this._mapping.buttons[id]; - const buttonMeshName = buttonMap.rootNodeName; - if (!buttonMeshName) { - logger_Logger.Log("Skipping unknown button at index: " + i + " with mapped name: " + id); - return; - } - const buttonMesh = this._getChildByName(this.rootMesh, buttonMeshName); - if (!buttonMesh) { - logger_Logger.Warn("Missing button mesh with name: " + buttonMeshName); - return; - } - buttonMap.valueMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.valueNodeName); - buttonMap.pressedMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.pressedNodeName); - buttonMap.unpressedMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.unpressedNodeName); - if (buttonMap.valueMesh && buttonMap.pressedMesh && buttonMap.unpressedMesh) { - const comp = this.getComponent(id); - if (comp) { - comp.onButtonStateChangedObservable.add((component) => { - this._lerpTransform(buttonMap, component.value); - }, undefined, true); - } - } - else { - // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes. - logger_Logger.Warn("Missing button submesh under mesh with name: " + buttonMeshName); - } - } - }); - // Axis Meshes - this.getComponentIds().forEach((id) => { - const comp = this.getComponent(id); - if (!comp.isAxes()) { - return; - } - ["x-axis", "y-axis"].forEach((axis) => { - if (!this.rootMesh) { - return; - } - const axisMap = this._mapping.axes[id][axis]; - const axisMesh = this._getChildByName(this.rootMesh, axisMap.rootNodeName); - if (!axisMesh) { - logger_Logger.Warn("Missing axis mesh with name: " + axisMap.rootNodeName); - return; - } - axisMap.valueMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.valueNodeName); - axisMap.minMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.minNodeName); - axisMap.maxMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.maxNodeName); - if (axisMap.valueMesh && axisMap.minMesh && axisMap.maxMesh) { - if (comp) { - comp.onAxisValueChangedObservable.add((axisValues) => { - const value = axis === "x-axis" ? axisValues.x : axisValues.y; - this._lerpTransform(axisMap, value, true); - }, undefined, true); - } - } - else { - // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes. - logger_Logger.Warn("Missing axis submesh under mesh with name: " + axisMap.rootNodeName); - } - }); - }); - } - _setRootMesh(meshes) { - this.rootMesh = new mesh_Mesh(this.profileId + " " + this.handedness, this.scene); - this.rootMesh.isPickable = false; - let rootMesh; - // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh' - for (let i = 0; i < meshes.length; i++) { - const mesh = meshes[i]; - mesh.isPickable = false; - if (!mesh.parent) { - // Handle root node, attach to the new parentMesh - rootMesh = mesh; - } - } - if (rootMesh) { - rootMesh.setParent(this.rootMesh); - } - if (!this.scene.useRightHandedSystem) { - this.rootMesh.rotationQuaternion = math_vector_Quaternion.FromEulerAngles(0, Math.PI, 0); - } - } - _updateModel() { - // no-op. model is updated using observables. - } -} -/** - * The base url used to load the left and right controller models - */ -WebXRMicrosoftMixedRealityController.MODEL_BASE_URL = "https://controllers.babylonjs.com/microsoft/"; -/** - * The name of the left controller model file - */ -WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME = "left.glb"; -/** - * The name of the right controller model file - */ -WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME = "right.glb"; -// register the profile -WebXRMotionControllerManager.RegisterController("windows-mixed-reality", (xrInput, scene) => { - return new WebXRMicrosoftMixedRealityController(scene, xrInput.gamepad, xrInput.handedness); -}); -// https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/microsoft/microsoft-mixed-reality.json -const MixedRealityProfile = { - 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", - }, -}; -//# sourceMappingURL=webXRMicrosoftMixedRealityController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/motionController/webXROculusTouchMotionController.js - - - - -/** - * The motion controller class for oculus touch (quest, rift). - * This class supports legacy mapping as well the standard xr mapping - */ -class WebXROculusTouchMotionController extends WebXRAbstractMotionController { - constructor(scene, gamepadObject, handedness, _legacyMapping = false, _forceLegacyControllers = false) { - super(scene, OculusTouchLayouts[handedness], gamepadObject, handedness); - this._forceLegacyControllers = _forceLegacyControllers; - this.profileId = "oculus-touch"; - } - _getFilenameAndPath() { - let filename = ""; - if (this.handedness === "left") { - filename = WebXROculusTouchMotionController.MODEL_LEFT_FILENAME; - } - else { - // Right is the default if no hand is specified - filename = WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME; - } - const path = this._isQuest() ? WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL : WebXROculusTouchMotionController.MODEL_BASE_URL; - return { - filename, - path, - }; - } - _getModelLoadingConstraints() { - return true; - } - _processLoadedModel(_meshes) { - const isQuest = this._isQuest(); - const triggerDirection = this.handedness === "right" ? -1 : 1; - this.getComponentIds().forEach((id) => { - const comp = id && this.getComponent(id); - if (comp) { - comp.onButtonStateChangedObservable.add((component) => { - if (!this.rootMesh || this.disableAnimation) { - return; - } - switch (id) { - case "xr-standard-trigger": // index trigger - if (!isQuest) { - this._modelRootNode.getChildren()[3].rotation.x = -component.value * 0.2; - this._modelRootNode.getChildren()[3].position.y = -component.value * 0.005; - this._modelRootNode.getChildren()[3].position.z = -component.value * 0.005; - } - return; - case "xr-standard-squeeze": // secondary trigger - if (!isQuest) { - this._modelRootNode.getChildren()[4].position.x = triggerDirection * component.value * 0.0035; - } - return; - case "xr-standard-thumbstick": // thumbstick - return; - case "a-button": - case "x-button": - if (!isQuest) { - if (component.pressed) { - this._modelRootNode.getChildren()[1].position.y = -0.001; - } - else { - this._modelRootNode.getChildren()[1].position.y = 0; - } - } - return; - case "b-button": - case "y-button": - if (!isQuest) { - if (component.pressed) { - this._modelRootNode.getChildren()[2].position.y = -0.001; - } - else { - this._modelRootNode.getChildren()[2].position.y = 0; - } - } - return; - } - }, undefined, true); - } - }); - } - _setRootMesh(meshes) { - this.rootMesh = new mesh_Mesh(this.profileId + " " + this.handedness, this.scene); - if (!this.scene.useRightHandedSystem) { - this.rootMesh.rotationQuaternion = math_vector_Quaternion.FromEulerAngles(0, Math.PI, 0); - } - meshes.forEach((mesh) => { - mesh.isPickable = false; - }); - if (this._isQuest()) { - this._modelRootNode = meshes[0]; - } - else { - this._modelRootNode = meshes[1]; - this.rootMesh.position.y = 0.034; - this.rootMesh.position.z = 0.052; - } - this._modelRootNode.parent = this.rootMesh; - } - _updateModel() { - // no-op. model is updated using observables. - } - /** - * Is this the new type of oculus touch. At the moment both have the same profile and it is impossible to differentiate - * between the touch and touch 2. - */ - _isQuest() { - // this is SADLY the only way to currently check. Until proper profiles will be available. - return !!navigator.userAgent.match(/Quest/gi) && !this._forceLegacyControllers; - } -} -/** - * The base url used to load the left and right controller models - */ -WebXROculusTouchMotionController.MODEL_BASE_URL = "https://controllers.babylonjs.com/oculus/"; -/** - * The name of the left controller model file - */ -WebXROculusTouchMotionController.MODEL_LEFT_FILENAME = "left.babylon"; -/** - * The name of the right controller model file - */ -WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME = "right.babylon"; -/** - * Base Url for the Quest controller model. - */ -WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL = "https://controllers.babylonjs.com/oculusQuest/"; -// register the profile -WebXRMotionControllerManager.RegisterController("oculus-touch", (xrInput, scene) => { - return new WebXROculusTouchMotionController(scene, xrInput.gamepad, xrInput.handedness); -}); -WebXRMotionControllerManager.RegisterController("oculus-touch-legacy", (xrInput, scene) => { - return new WebXROculusTouchMotionController(scene, xrInput.gamepad, xrInput.handedness, true); -}); -const OculusTouchLayouts = { - 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", - }, -}; -//# sourceMappingURL=webXROculusTouchMotionController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/motionController/webXRHTCViveMotionController.js - - - - -/** - * The motion controller class for the standard HTC-Vive controllers - */ -class WebXRHTCViveMotionController extends WebXRAbstractMotionController { - /** - * Create a new Vive motion controller object - * @param scene the scene to use to create this controller - * @param gamepadObject the corresponding gamepad object - * @param handedness the handedness of the controller - */ - constructor(scene, gamepadObject, handedness) { - super(scene, HTCViveLayout[handedness], gamepadObject, handedness); - this.profileId = "htc-vive"; - } - _getFilenameAndPath() { - const filename = WebXRHTCViveMotionController.MODEL_FILENAME; - const path = WebXRHTCViveMotionController.MODEL_BASE_URL; - return { - filename, - path, - }; - } - _getModelLoadingConstraints() { - return true; - } - _processLoadedModel(_meshes) { - this.getComponentIds().forEach((id) => { - const comp = id && this.getComponent(id); - if (comp) { - comp.onButtonStateChangedObservable.add((component) => { - if (!this.rootMesh || this.disableAnimation) { - return; - } - switch (id) { - case "xr-standard-trigger": - this._modelRootNode.getChildren()[6].rotation.x = -component.value * 0.15; - return; - case "xr-standard-touchpad": - return; - case "xr-standard-squeeze": - return; - } - }, undefined, true); - } - }); - } - _setRootMesh(meshes) { - this.rootMesh = new mesh_Mesh(this.profileId + " " + this.handedness, this.scene); - meshes.forEach((mesh) => { - mesh.isPickable = false; - }); - this._modelRootNode = meshes[1]; - this._modelRootNode.parent = this.rootMesh; - if (!this.scene.useRightHandedSystem) { - this.rootMesh.rotationQuaternion = math_vector_Quaternion.FromEulerAngles(0, Math.PI, 0); - } - } - _updateModel() { - // no-op. model is updated using observables. - } -} -/** - * The base url used to load the left and right controller models - */ -WebXRHTCViveMotionController.MODEL_BASE_URL = "https://controllers.babylonjs.com/vive/"; -/** - * File name for the controller model. - */ -WebXRHTCViveMotionController.MODEL_FILENAME = "wand.babylon"; -// register the profile -WebXRMotionControllerManager.RegisterController("htc-vive", (xrInput, scene) => { - return new WebXRHTCViveMotionController(scene, xrInput.gamepad, xrInput.handedness); -}); -// WebXRMotionControllerManager.RegisterController("htc-vive-legacy", (xrInput: XRInputSource, scene: Scene) => { -// return new WebXRHTCViveMotionController(scene, <any>(xrInput.gamepad), xrInput.handedness, true); -// }); -const HTCViveLayout = { - 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", - }, -}; -//# sourceMappingURL=webXRHTCViveMotionController.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/motionController/index.js - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/native/nativeXRFrame.js - -/** @internal */ -class NativeXRFrame { - get session() { - return this._nativeImpl.session; - } - constructor(_nativeImpl) { - this._nativeImpl = _nativeImpl; - this._xrTransform = new XRRigidTransform(); - this._xrPose = { - transform: this._xrTransform, - emulatedPosition: false, - }; - // Enough space for position, orientation - this._xrPoseVectorData = new Float32Array(4 + 4); - 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 _a; - return (_a = this._nativeImpl._imageTrackingResults) !== null && _a !== void 0 ? _a : []; - }; - } - getPose(space, baseSpace) { - if (!this._nativeImpl.getPoseData(space, baseSpace, this._xrPoseVectorData.buffer, this._xrTransform.matrix.buffer)) { - return undefined; - } - const position = this._xrTransform.position; - position.x = this._xrPoseVectorData[0]; - position.y = this._xrPoseVectorData[1]; - position.z = this._xrPoseVectorData[2]; - position.w = this._xrPoseVectorData[3]; - const orientation = this._xrTransform.orientation; - orientation.x = this._xrPoseVectorData[4]; - orientation.y = this._xrPoseVectorData[5]; - orientation.z = this._xrPoseVectorData[6]; - orientation.w = this._xrPoseVectorData[7]; - return 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(view) { - throw new Error("This function is not available in Babylon Native"); - // return this._nativeImpl.getDepthInformation(view); - } -} -RegisterNativeTypeAsync("NativeXRFrame", NativeXRFrame); -//# sourceMappingURL=nativeXRFrame.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/native/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/XR/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/types.js - -/** @internal */ -/* interface DeepImmutableMap<K, V> extends ReadonlyMap<DeepImmutable<K>, DeepImmutable<V>> {} // es2015+ only */ -//# sourceMappingURL=types.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/Compat/index.js - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/flowGraphConnection.js -/** - * @experimental - * The type of a connection point - inpput or output. - */ -var flowGraphConnection_FlowGraphConnectionType; -(function (FlowGraphConnectionType) { - FlowGraphConnectionType[FlowGraphConnectionType["Input"] = 0] = "Input"; - FlowGraphConnectionType[FlowGraphConnectionType["Output"] = 1] = "Output"; -})(flowGraphConnection_FlowGraphConnectionType || (flowGraphConnection_FlowGraphConnectionType = {})); -/** - * @experimental - * The base connection class. - */ -class flowGraphConnection_FlowGraphConnection { - constructor(name, /** @internal */ _type, _ownerBlock) { - this.name = name; - this._type = _type; - this._ownerBlock = _ownerBlock; - /** @internal */ - this._connectedPoint = null; - } - /** - * The type of the connection - */ - get type() { - return this._type; - } - /** - * Connects two points together. - * @param point - */ - connectTo(point) { - if (this._type === point._type) { - throw new Error(`Cannot connect two points of type ${this.type}`); - } - this._connectedPoint = point; - point._connectedPoint = this; - } -} -//# sourceMappingURL=flowGraphConnection.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/flowGraphDataConnection.js - -/** - * @experimental - * Represents a connection point for data. - * An unconnected input point can have a default value. - * An output point will only have a value if it is connected to an input point. Furthermore, - * if the point belongs to a "function" node, the node will run its function to update the value. - */ -class flowGraphDataConnection_FlowGraphDataConnection extends (/* unused pure expression or super */ null && (FlowGraphConnection)) { - constructor(name, type, ownerBlock, _value) { - super(name, type, ownerBlock); - this._value = _value; - } - set value(value) { - this._value = value; - } - get value() { - if (this.type === FlowGraphConnectionType.Output) { - this._ownerBlock._updateOutputs(); - return this._value; - } - if (!this._connectedPoint) { - return this._value; - } - else { - return this._connectedPoint.value; - } - } -} -//# sourceMappingURL=flowGraphDataConnection.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/flowGraphBlock.js - - -/** - * @experimental - * A block in a flow graph. The most basic form - * of a block has inputs and outputs that contain - * data. - */ -class flowGraphBlock_FlowGraphBlock { - constructor(graph) { - /** - * The data inputs of the block. - */ - this.dataInputs = []; - /** - * The data outputs of the block. - */ - this.dataOutputs = []; - this._graph = graph; - this._graph._addBlock(this); - } - /** - * @internal - */ - _updateOutputs() { - // empty by default, overriden in data blocks - } - _registerDataInput(name, defaultValue) { - const input = new FlowGraphDataConnection(name, FlowGraphConnectionType.Input, this, defaultValue); - this.dataInputs.push(input); - return input; - } - _registerDataOutput(name, defaultValue) { - const output = new FlowGraphDataConnection(name, FlowGraphConnectionType.Output, this, defaultValue); - this.dataOutputs.push(output); - return output; - } -} -//# sourceMappingURL=flowGraphBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/flowGraphSignalConnection.js - -/** - * @experimental - * Represents a connection point for a signal. - * When an output point is activated, it will activate the connected input point. - * When an input point is activated, it will execute the block it belongs to. - */ -class flowGraphSignalConnection_FlowGraphSignalConnection extends (/* unused pure expression or super */ null && (FlowGraphConnection)) { - /** - * @internal - */ - _activateSignal() { - var _a; - if (this.type === FlowGraphConnectionType.Input) { - this._ownerBlock._execute(); - } - else { - (_a = this._connectedPoint) === null || _a === void 0 ? void 0 : _a._activateSignal(); - } - } -} -//# sourceMappingURL=flowGraphSignalConnection.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/flowGraphExecutionBlock.js - - - -/** - * @experimental - * A block that executes some action. Always has an input signal. - * Can have one or more output signals. - */ -class flowGraphExecutionBlock_FlowGraphExecutionBlock extends (/* unused pure expression or super */ null && (FlowGraphBlock)) { - constructor(graph) { - super(graph); - this._signalInputs = []; - this._signalOutputs = []; - this.onStart = this._registerSignalInput("onStart"); - } - _registerSignalInput(name) { - const input = new FlowGraphSignalConnection(name, FlowGraphConnectionType.Input, this); - this._signalInputs.push(input); - return input; - } - _registerSignalOutput(name) { - const output = new FlowGraphSignalConnection(name, FlowGraphConnectionType.Output, this); - this._signalOutputs.push(output); - return output; - } -} -//# sourceMappingURL=flowGraphExecutionBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/flowGraphWithOnDoneExecutionBlock.js - -class flowGraphWithOnDoneExecutionBlock_FlowGraphWithOnDoneExecutionBlock extends (/* unused pure expression or super */ null && (FlowGraphExecutionBlock)) { - constructor(graph) { - super(graph); - this.onDone = this._registerSignalOutput("onDone"); - } -} -//# sourceMappingURL=flowGraphWithOnDoneExecutionBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/flowGraphEventBlock.js - -/** - * @experimental - * A type of block that listens to an event observable and activates - * its output signal ("onTriggered"), when the event is triggered. - */ -class flowGraphEventBlock_FlowGraphEventBlock extends (/* unused pure expression or super */ null && (FlowGraphWithOnDoneExecutionBlock)) { - /** - * @internal - */ - _execute() { - this.onDone._activateSignal(); - } -} -//# sourceMappingURL=flowGraphEventBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/flowGraph.js - -/** - * @experimental - * Class used to represent a flow graph. - * A flow graph is a graph of blocks that can be used to create complex logic. - * Blocks can be added to the graph and connected to each other. - * The graph can then be started, which will init and start all of its event blocks. - */ -class FlowGraph { - constructor(_scene) { - this._scene = _scene; - this._blocks = []; - this._sceneDisposeObserver = this._scene.onDisposeObservable.add(this.dispose.bind(this)); - } - /** - * @internal - * @param block - */ - _addBlock(block) { - this._blocks.push(block); - } - /** - * Finds a block by its name. - * @param name - * @returns - */ - findBlockByName(name) { - return this._blocks.find((block) => block.name === name); - } - /** - * Starts the flow graph. - */ - start() { - for (const block of this._blocks) { - if (block instanceof FlowGraphEventBlock) { - block._startListening(); - } - } - } - /** - * Disposes of the flow graph. - */ - dispose() { - for (const block of this._blocks) { - if (block instanceof FlowGraphEventBlock) { - block._stopListening(); - } - } - this._blocks.length = 0; - this._scene.onDisposeObservable.remove(this._sceneDisposeObserver); - this._sceneDisposeObserver = null; - } -} -//# sourceMappingURL=flowGraph.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/flowGraphForLoopBlock.js - -/** - * @experimental - * Block that executes a loop. - */ -class FlowGraphForLoopBlock extends (/* unused pure expression or super */ null && (FlowGraphWithOnDoneExecutionBlock)) { - constructor(graph) { - super(graph); - this._currentIndex = 0; - this._cachedEndIndex = 0; - this._cachedStep = 0; - this.startIndex = this._registerDataInput("startIndex", 0); - this.endIndex = this._registerDataInput("endIndex", 0); - this.step = this._registerDataInput("step", 1); - this.index = this._registerDataOutput("index", 0); - this.onLoop = this._registerSignalOutput("onLoop"); - this.onDone = this._registerSignalOutput("onDone"); - } - _executeLoop() { - if (this._currentIndex < this._cachedEndIndex) { - this.index.value = this._currentIndex; - this.onLoop._activateSignal(); - this._currentIndex += this._cachedStep; - this._executeLoop(); - } - else { - this.onDone._activateSignal(); - } - } - /** - * @internal - */ - _execute() { - this._currentIndex = this.startIndex.value; - this._cachedEndIndex = this.endIndex.value; - this._cachedStep = this.step.value; - this._executeLoop(); - } -} -//# sourceMappingURL=flowGraphForLoopBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/flowGraphLogBlock.js - -/** - * @experimental - * Block that logs a message to the console. - */ -class FlowGraphLogBlock extends (/* unused pure expression or super */ null && (FlowGraphWithOnDoneExecutionBlock)) { - constructor(graph) { - super(graph); - this.message = this._registerDataInput("message", "Hello world"); - } - /** - * @internal - */ - _execute() { - const messageValue = this.message.value; - console.log(messageValue); - // activate the output flow block - this.onDone._activateSignal(); - } -} -//# sourceMappingURL=flowGraphLogBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/Blocks/Execution/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/Blocks/Data/flowGraphBinaryOpBlocks.js - -/** - * @experimental - */ -class FlowGraphBinaryOpBaseBlock extends (/* unused pure expression or super */ null && (FlowGraphBlock)) { - constructor(graph, defaultLeftValue, defaultRightValue, binOp) { - super(graph); - this._binOp = binOp; - this.left = this._registerDataInput("left", defaultLeftValue); - this.right = this._registerDataInput("right", defaultRightValue); - this.output = this._registerDataOutput("output", binOp(defaultLeftValue, defaultRightValue)); - } - /** - * @internal - */ - _updateOutputs() { - this.output.value = this._binOp(this.left.value, this.right.value); - } -} -/** - * @experimental - * Block that adds two numbers. - */ -class FlowGraphAddNumberBlock extends (/* unused pure expression or super */ null && (FlowGraphBinaryOpBaseBlock)) { - constructor(graph) { - super(graph, 0, 0, (left, right) => left + right); - } -} -//# sourceMappingURL=flowGraphBinaryOpBlocks.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/Blocks/Data/index.js - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/Blocks/Event/flowGraphMeshPickEventBlock.js - - -/** - * @experimental - * A block that activates when a mesh is picked. - */ -class FlowGraphMeshPickEventBlock extends (/* unused pure expression or super */ null && (FlowGraphEventBlock)) { - constructor(graph, meshToPick) { - super(graph); - this._meshToPick = meshToPick; - } - set meshToPick(mesh) { - if (this._meshToPick !== mesh) { - const wasListening = !!this._meshPickObserver; - if (wasListening) { - this._stopListening(); - } - this._meshToPick = mesh; - if (wasListening) { - this._startListening(); - } - } - } - get meshToPick() { - return this._meshToPick; - } - /** - * @internal - */ - _startListening() { - if (!this._meshPickObserver) { - this._meshPickObserver = this._meshToPick.getScene().onPointerObservable.add((pointerInfo) => { - var _a; - if (pointerInfo.type === PointerEventTypes.POINTERPICK && ((_a = pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) === this._meshToPick) { - this._execute(); - } - }); - this._meshDisposeObserver = this._meshToPick.onDisposeObservable.add(() => this._stopListening()); - } - } - /** - * @internal - */ - _stopListening() { - this._meshToPick.getScene().onPointerObservable.remove(this._meshPickObserver); - this._meshPickObserver = null; - this._meshToPick.onDisposeObservable.remove(this._meshDisposeObserver); - this._meshDisposeObserver = null; - } -} -//# sourceMappingURL=flowGraphMeshPickEventBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/Blocks/Event/flowGraphSceneReadyEventBlock.js - -/** - * @experimental - * Block that triggers when a scene is ready. - */ -class FlowGraphSceneReadyEventBlock extends (/* unused pure expression or super */ null && (FlowGraphEventBlock)) { - constructor(graph, scene) { - super(graph); - this._scene = scene; - } - /** - * @internal - */ - _startListening() { - if (!this._sceneReadyObserver) { - this._sceneReadyObserver = this._scene.onReadyObservable.add(() => { - this._execute(); - }); - } - } - /** - * @internal - */ - _stopListening() { - this._scene.onReadyObservable.remove(this._sceneReadyObserver); - this._sceneReadyObserver = null; - } -} -//# sourceMappingURL=flowGraphSceneReadyEventBlock.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/Blocks/Event/index.js - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/Blocks/index.js -/* eslint-disable import/no-internal-modules */ - - - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/FlowGraph/index.js - - - - - -// eslint-disable-next-line import/no-internal-modules - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@babylonjs/core/index.js -/* eslint-disable import/no-internal-modules */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.js.map - -/***/ }) - -}; -; \ No newline at end of file diff --git a/.next/server/chunks/984.js b/.next/server/chunks/984.js new file mode 100644 index 0000000..b8142a4 --- /dev/null +++ b/.next/server/chunks/984.js @@ -0,0 +1,11502 @@ +exports.id=984,exports.ids=[984],exports.modules={3642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return dynamic}});let r=i(85);i(9885);let s=r._(i(112));function convertModule(e){return{default:(null==e?void 0:e.default)||e}}function dynamic(e,t){let i=s.default,r={loading:e=>{let{error:t,isLoading:i,pastDelay:r}=e;return null}};"function"==typeof e&&(r.loader=e),Object.assign(r,t);let a=r.loader;return i({...r,loader:()=>null!=a?a().then(convertModule):Promise.resolve(convertModule(()=>null))})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6800:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NoSSR",{enumerable:!0,get:function(){return NoSSR}});let r=i(1118);function NoSSR(e){let{children:t}=e;return(0,r.throwWithNoSSR)(),t}},112:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}});let r=i(85),s=r._(i(9885)),a=i(6800);function Loadable(e){let t=Object.assign({loader:null,loading:null,ssr:!0},e);function LoadableComponent(e){let i=t.loading,r=s.default.createElement(i,{isLoading:!0,pastDelay:!0,error:null}),n=t.ssr?s.default.Fragment:a.NoSSR,o=t.lazy;return s.default.createElement(s.default.Suspense,{fallback:r},s.default.createElement(n,null,s.default.createElement(o,e)))}return t.lazy=s.default.lazy(t.loader),LoadableComponent.displayName="LoadableComponent",LoadableComponent}let n=Loadable},784:(e,t,i)=>{"use strict";e.exports=i(316).vendored["react-ssr"].ReactJsxRuntime},6224:function(e,t){/*! Tweakpane 3.1.10 (c) 2016 cocopon, licensed under the MIT license. */(function(e){"use strict";let Semver=class Semver{constructor(e){let[t,i]=e.split("-"),r=t.split(".");this.major=parseInt(r[0],10),this.minor=parseInt(r[1],10),this.patch=parseInt(r[2],10),this.prerelease=null!=i?i:null}toString(){let e=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[e,this.prerelease].join("-"):e}};let BladeApi=class BladeApi{constructor(e){this.controller_=e}get element(){return this.controller_.view.element}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(e){this.controller_.viewProps.set("disabled",e)}get hidden(){return this.controller_.viewProps.get("hidden")}set hidden(e){this.controller_.viewProps.set("hidden",e)}dispose(){this.controller_.viewProps.set("disposed",!0)}};let TpEvent=class TpEvent{constructor(e){this.target=e}};let TpChangeEvent=class TpChangeEvent extends TpEvent{constructor(e,t,i,r){super(e),this.value=t,this.presetKey=i,this.last=null==r||r}};let TpUpdateEvent=class TpUpdateEvent extends TpEvent{constructor(e,t,i){super(e),this.value=t,this.presetKey=i}};let TpFoldEvent=class TpFoldEvent extends TpEvent{constructor(e,t){super(e),this.expanded=t}};let TpTabSelectEvent=class TpTabSelectEvent extends TpEvent{constructor(e,t){super(e),this.index=t}};function isEmpty(e){return null==e}function deepEqualsArray(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}function isPropertyWritable(e,t){let i=e;do{let e=Object.getOwnPropertyDescriptor(i,t);if(e&&(void 0!==e.set||!0===e.writable))return!0;i=Object.getPrototypeOf(i)}while(null!==i);return!1}let t={alreadydisposed:()=>"View has been already disposed",invalidparams:e=>`Invalid parameters for '${e.name}'`,nomatchingcontroller:e=>`No matching controller for '${e.key}'`,nomatchingview:e=>`No matching view for '${JSON.stringify(e.params)}'`,notbindable:()=>"Value is not bindable",propertynotfound:e=>`Property '${e.name}' not found`,shouldneverhappen:()=>"This error should never happen"};let TpError=class TpError{static alreadyDisposed(){return new TpError({type:"alreadydisposed"})}static notBindable(){return new TpError({type:"notbindable"})}static propertyNotFound(e){return new TpError({type:"propertynotfound",context:{name:e}})}static shouldNeverHappen(){return new TpError({type:"shouldneverhappen"})}constructor(e){var i;this.message=null!==(i=t[e.type](e.context))&&void 0!==i?i:"Unexpected error",this.name=this.constructor.name,this.stack=Error(this.message).stack,this.type=e.type}};let BindingTarget=class BindingTarget{constructor(e,t,i){this.obj_=e,this.key_=t,this.presetKey_=null!=i?i:t}static isBindable(e){return null!==e&&("object"==typeof e||"function"==typeof e)}get key(){return this.key_}get presetKey(){return this.presetKey_}read(){return this.obj_[this.key_]}write(e){this.obj_[this.key_]=e}writeProperty(e,t){let i=this.read();if(!BindingTarget.isBindable(i))throw TpError.notBindable();if(!(e in i))throw TpError.propertyNotFound(e);i[e]=t}};let ButtonApi=class ButtonApi extends BladeApi{get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get title(){var e;return null!==(e=this.controller_.valueController.props.get("title"))&&void 0!==e?e:""}set title(e){this.controller_.valueController.props.set("title",e)}on(e,t){let i=t.bind(this),r=this.controller_.valueController.emitter;return r.on(e,()=>{i(new TpEvent(this))}),this}};let Emitter=class Emitter{constructor(){this.observers_={}}on(e,t){let i=this.observers_[e];return i||(i=this.observers_[e]=[]),i.push({handler:t}),this}off(e,t){let i=this.observers_[e];return i&&(this.observers_[e]=i.filter(e=>e.handler!==t)),this}emit(e,t){let i=this.observers_[e];i&&i.forEach(e=>{e.handler(t)})}};function ClassName(e){return(t,i)=>["tp","-",e,"v",t?`_${t}`:"",i?`-${i}`:""].join("")}function compose(e,t){return i=>t(e(i))}function extractValue(e){return e.rawValue}function bindValue(e,t){e.emitter.on("change",compose(extractValue,t)),t(e.rawValue)}function bindValueMap(e,t,i){bindValue(e.value(t),i)}function applyClass(e,t,i){i?e.classList.add(t):e.classList.remove(t)}function valueToClassName(e,t){return i=>{applyClass(e,t,i)}}function bindValueToTextContent(e,t){bindValue(e,e=>{t.textContent=null!=e?e:""})}let i=ClassName("btn");let ButtonView=class ButtonView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(i()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("button");r.classList.add(i("b")),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r;let s=e.createElement("div");s.classList.add(i("t")),bindValueToTextContent(t.props.value("title"),s),this.buttonElement.appendChild(s)}};let ButtonController=class ButtonController{constructor(e,t){this.emitter=new Emitter,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new ButtonView(e,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}};let BoundValue=class BoundValue{constructor(e,t){var i;this.constraint_=null==t?void 0:t.constraint,this.equals_=null!==(i=null==t?void 0:t.equals)&&void 0!==i?i:(e,t)=>e===t,this.emitter=new Emitter,this.rawValue_=e}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let i=null!=t?t:{forceEmit:!1,last:!0},r=this.constraint_?this.constraint_.constrain(e):e,s=this.rawValue_,a=!this.equals_(s,r);(a||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=r,this.emitter.emit("change",{options:i,previousRawValue:s,rawValue:r,sender:this}))}};let PrimitiveValue=class PrimitiveValue{constructor(e){this.emitter=new Emitter,this.value_=e}get rawValue(){return this.value_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let i=null!=t?t:{forceEmit:!1,last:!0},r=this.value_;(r!==e||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=e,this.emitter.emit("change",{options:i,previousRawValue:r,rawValue:this.value_,sender:this}))}};function createValue(e,t){let i=null==t?void 0:t.constraint,r=null==t?void 0:t.equals;return i||r?new BoundValue(e,t):new PrimitiveValue(e)}let ValueMap=class ValueMap{constructor(e){for(let t in this.emitter=new Emitter,this.valMap_=e,this.valMap_){let e=this.valMap_[t];e.emitter.on("change",()=>{this.emitter.emit("change",{key:t,sender:this})})}}static createCore(e){let t=Object.keys(e);return t.reduce((t,i)=>Object.assign(t,{[i]:createValue(e[i])}),{})}static fromObject(e){let t=this.createCore(e);return new ValueMap(t)}get(e){return this.valMap_[e].rawValue}set(e,t){this.valMap_[e].rawValue=t}value(e){return this.valMap_[e]}};function parseObject(e,t){let i=Object.keys(t),r=i.reduce((i,r)=>{if(void 0===i)return;let s=t[r],a=s(e[r]);return a.succeeded?Object.assign(Object.assign({},i),{[r]:a.value}):void 0},{});return r}function parseArray(e,t){return e.reduce((e,i)=>{if(void 0===e)return;let r=t(i);if(r.succeeded&&void 0!==r.value)return[...e,r.value]},[])}function isObject(e){return null!==e&&"object"==typeof e}function createParamsParserBuilder(e){return t=>i=>{if(!t&&void 0===i)return{succeeded:!1,value:void 0};if(t&&void 0===i)return{succeeded:!0,value:void 0};let r=e(i);return void 0!==r?{succeeded:!0,value:r}:{succeeded:!1,value:void 0}}}function createParamsParserBuilders(e){return{custom:t=>createParamsParserBuilder(t)(e),boolean:createParamsParserBuilder(e=>"boolean"==typeof e?e:void 0)(e),number:createParamsParserBuilder(e=>"number"==typeof e?e:void 0)(e),string:createParamsParserBuilder(e=>"string"==typeof e?e:void 0)(e),function:createParamsParserBuilder(e=>"function"==typeof e?e:void 0)(e),constant:t=>createParamsParserBuilder(e=>e===t?t:void 0)(e),raw:createParamsParserBuilder(e=>e)(e),object:t=>createParamsParserBuilder(e=>{if(isObject(e))return parseObject(e,t)})(e),array:t=>createParamsParserBuilder(e=>{if(Array.isArray(e))return parseArray(e,t)})(e)}}let r={optional:createParamsParserBuilders(!0),required:createParamsParserBuilders(!1)};function parseParams(e,t){let i=r.required.object(t)(e);return i.succeeded?i.value:void 0}function warnMissing(e){console.warn(`Missing '${e.key}' of ${e.target} in ${e.place}. Please rebuild plugins with the latest core package.`)}function disposeElement(e){return e&&e.parentElement&&e.parentElement.removeChild(e),null}let ReadonlyValue=class ReadonlyValue{constructor(e){this.value_=e}static create(e){return[new ReadonlyValue(e),(t,i)=>{e.setRawValue(t,i)}]}get emitter(){return this.value_.emitter}get rawValue(){return this.value_.rawValue}};let s=ClassName("");function valueToModifier(e,t){return valueToClassName(e,s(void 0,t))}let ViewProps=class ViewProps extends ValueMap{constructor(e){var t;super(e),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=ReadonlyValue.create(createValue(this.getGlobalDisabled_())),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(t=this.get("parent"))||void 0===t||t.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(e){var t,i,r;let s=null!=e?e:{};return new ViewProps(ValueMap.createCore({disabled:null!==(t=s.disabled)&&void 0!==t&&t,disposed:!1,hidden:null!==(i=s.hidden)&&void 0!==i&&i,parent:null!==(r=s.parent)&&void 0!==r?r:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(e){bindValue(this.globalDisabled_,valueToModifier(e,"disabled")),bindValueMap(this,"hidden",valueToModifier(e,"hidden"))}bindDisabled(e){bindValue(this.globalDisabled_,t=>{e.disabled=t})}bindTabIndex(e){bindValue(this.globalDisabled_,t=>{e.tabIndex=t?-1:0})}handleDispose(e){this.value("disposed").emitter.on("change",t=>{t&&e()})}getGlobalDisabled_(){let e=this.get("parent"),t=!!e&&e.globalDisabled.rawValue;return t||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(e){var t;let i=e.previousRawValue;null==i||i.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(t=this.get("parent"))||void 0===t||t.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}};function getAllBladePositions(){return["veryfirst","first","last","verylast"]}let a=ClassName(""),n={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"};let BladeController=class BladeController{constructor(e){this.parent_=null,this.blade=e.blade,this.view=e.view,this.viewProps=e.viewProps;let t=this.view.element;this.blade.value("positions").emitter.on("change",()=>{getAllBladePositions().forEach(e=>{t.classList.remove(a(void 0,n[e]))}),this.blade.get("positions").forEach(e=>{t.classList.add(a(void 0,n[e]))})}),this.viewProps.handleDispose(()=>{disposeElement(t)})}get parent(){return this.parent_}set parent(e){if(this.parent_=e,!("parent"in this.viewProps.valMap_)){warnMissing({key:"parent",target:ViewProps.name,place:"BladeController.parent"});return}this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}};let o="http://www.w3.org/2000/svg";function forceReflow(e){e.offsetHeight}function disableTransitionTemporarily(e,t){let i=e.style.transition;e.style.transition="none",t(),e.style.transition=i}function supportsTouch(e){return void 0!==e.ontouchstart}function getGlobalObject(){return globalThis}function getWindowDocument(){let e=getGlobalObject();return e.document}function getCanvasContext(e){let t=e.ownerDocument.defaultView;return t&&"document"in t?e.getContext("2d",{willReadFrequently:!0}):null}let l={check:'<path d="M2 8l4 4l8 -8"/>',dropdown:'<path d="M5 7h6l-3 3 z"/>',p2dpad:'<path d="M8 4v8"/><path d="M4 8h8"/><circle cx="12" cy="12" r="1.2"/>'};function createSvgIconElement(e,t){let i=e.createElementNS(o,"svg");return i.innerHTML=l[t],i}function insertElementAt(e,t,i){e.insertBefore(t,e.children[i])}function removeElement(e){e.parentElement&&e.parentElement.removeChild(e)}function removeChildElements(e){for(;e.children.length>0;)e.removeChild(e.children[0])}function removeChildNodes(e){for(;e.childNodes.length>0;)e.removeChild(e.childNodes[0])}function findNextTarget(e){return e.relatedTarget?e.relatedTarget:"explicitOriginalTarget"in e?e.explicitOriginalTarget:null}let h=ClassName("lbl");function createLabelNode(e,t){let i=e.createDocumentFragment(),r=t.split("\n").map(t=>e.createTextNode(t));return r.forEach((t,r)=>{r>0&&i.appendChild(e.createElement("br")),i.appendChild(t)}),i}let LabelView=class LabelView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(h()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(h("l")),bindValueMap(t.props,"label",t=>{isEmpty(t)?this.element.classList.add(h(void 0,"nol")):(this.element.classList.remove(h(void 0,"nol")),removeChildNodes(i),i.appendChild(createLabelNode(e,t)))}),this.element.appendChild(i),this.labelElement=i;let r=e.createElement("div");r.classList.add(h("v")),this.element.appendChild(r),this.valueElement=r}};let LabelController=class LabelController extends BladeController{constructor(e,t){let i=t.valueController.viewProps;super(Object.assign(Object.assign({},t),{view:new LabelView(e,{props:t.props,viewProps:i}),viewProps:i})),this.props=t.props,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}};let c={id:"button",type:"blade",accept(e){let t=parseParams(e,{title:r.required.string,view:r.required.constant("button"),label:r.optional.string});return t?{params:t}:null},controller:e=>new LabelController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:new ButtonController(e.document,{props:ValueMap.fromObject({title:e.params.title}),viewProps:e.viewProps})}),api:e=>e.controller instanceof LabelController&&e.controller.valueController instanceof ButtonController?new ButtonApi(e.controller):null};let ValueBladeController=class ValueBladeController extends BladeController{constructor(e){super(e),this.value=e.value}};function createBlade(){return new ValueMap({positions:createValue([],{equals:deepEqualsArray})})}let Foldable=class Foldable extends ValueMap{constructor(e){super(e)}static create(e){let t=ValueMap.createCore({completed:!0,expanded:e,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null});return new Foldable(t)}get styleExpanded(){var e;return null!==(e=this.get("temporaryExpanded"))&&void 0!==e?e:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";let e=this.get("expandedHeight");return this.get("shouldFixHeight")&&!isEmpty(e)?`${e}px`:"auto"}bindExpandedClass(e,t){let onExpand=()=>{let i=this.styleExpanded;i?e.classList.add(t):e.classList.remove(t)};bindValueMap(this,"expanded",onExpand),bindValueMap(this,"temporaryExpanded",onExpand)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}};function computeExpandedFolderHeight(e,t){let i=0;return disableTransitionTemporarily(t,()=>{e.set("expandedHeight",null),e.set("temporaryExpanded",!0),forceReflow(t),i=t.clientHeight,e.set("temporaryExpanded",null),forceReflow(t)}),i}function applyHeight(e,t){t.style.height=e.styleHeight}function bindFoldable(e,t){e.value("expanded").emitter.on("beforechange",()=>{if(e.set("completed",!1),isEmpty(e.get("expandedHeight"))){let i=computeExpandedFolderHeight(e,t);i>0&&e.set("expandedHeight",i)}e.set("shouldFixHeight",!0),forceReflow(t)}),e.emitter.on("change",()=>{applyHeight(e,t)}),applyHeight(e,t),t.addEventListener("transitionend",t=>{"height"===t.propertyName&&e.cleanUpTransition()})}let RackLikeApi=class RackLikeApi extends BladeApi{constructor(e,t){super(e),this.rackApi_=t}};function addButtonAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"button"}))}function addFolderAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"folder"}))}function addSeparatorAsBlade(e,t){let i=null!=t?t:{};return e.addBlade(Object.assign(Object.assign({},i),{view:"separator"}))}function addTabAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"tab"}))}let NestedOrderedSet=class NestedOrderedSet{constructor(e){this.emitter=new Emitter,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=e}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(e){for(let t of this.allItems())if(e(t))return t;return null}includes(e){return this.cache_.has(e)}add(e,t){if(this.includes(e))throw TpError.shouldNeverHappen();let i=void 0!==t?t:this.items_.length;this.items_.splice(i,0,e),this.cache_.add(e);let r=this.extract_(e);r&&(r.emitter.on("add",this.onSubListAdd_),r.emitter.on("remove",this.onSubListRemove_),r.allItems().forEach(e=>{this.cache_.add(e)})),this.emitter.emit("add",{index:i,item:e,root:this,target:this})}remove(e){let t=this.items_.indexOf(e);if(t<0)return;this.items_.splice(t,1),this.cache_.delete(e);let i=this.extract_(e);i&&(i.emitter.off("add",this.onSubListAdd_),i.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:t,item:e,root:this,target:this})}onSubListAdd_(e){this.cache_.add(e.item),this.emitter.emit("add",{index:e.index,item:e.item,root:this,target:e.target})}onSubListRemove_(e){this.cache_.delete(e.item),this.emitter.emit("remove",{index:e.index,item:e.item,root:this,target:e.target})}};let InputBindingApi=class InputBindingApi extends BladeApi{constructor(e){super(e),this.onBindingChange_=this.onBindingChange_.bind(this),this.emitter_=new Emitter,this.controller_.binding.emitter.on("change",this.onBindingChange_)}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}refresh(){this.controller_.binding.read()}onBindingChange_(e){let t=e.sender.target.read();this.emitter_.emit("change",{event:new TpChangeEvent(this,t,this.controller_.binding.target.presetKey,e.options.last)})}};let InputBindingController=class InputBindingController extends LabelController{constructor(e,t){super(e,t),this.binding=t.binding}};let MonitorBindingApi=class MonitorBindingApi extends BladeApi{constructor(e){super(e),this.onBindingUpdate_=this.onBindingUpdate_.bind(this),this.emitter_=new Emitter,this.controller_.binding.emitter.on("update",this.onBindingUpdate_)}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}refresh(){this.controller_.binding.read()}onBindingUpdate_(e){let t=e.sender.target.read();this.emitter_.emit("update",{event:new TpUpdateEvent(this,t,this.controller_.binding.target.presetKey)})}};let MonitorBindingController=class MonitorBindingController extends LabelController{constructor(e,t){super(e,t),this.binding=t.binding,this.viewProps.bindDisabled(this.binding.ticker),this.viewProps.handleDispose(()=>{this.binding.dispose()})}};function findSubBladeApiSet(e){return e instanceof RackApi?e.apiSet_:e instanceof RackLikeApi?e.rackApi_.apiSet_:null}function getApiByController(e,t){let i=e.find(e=>e.controller_===t);if(!i)throw TpError.shouldNeverHappen();return i}function createBindingTarget(e,t,i){if(!BindingTarget.isBindable(e))throw TpError.notBindable();return new BindingTarget(e,t,i)}let RackApi=class RackApi extends BladeApi{constructor(e,t){super(e),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this),this.onRackInputChange_=this.onRackInputChange_.bind(this),this.onRackMonitorUpdate_=this.onRackMonitorUpdate_.bind(this),this.emitter_=new Emitter,this.apiSet_=new NestedOrderedSet(findSubBladeApiSet),this.pool_=t;let i=this.controller_.rack;i.emitter.on("add",this.onRackAdd_),i.emitter.on("remove",this.onRackRemove_),i.emitter.on("inputchange",this.onRackInputChange_),i.emitter.on("monitorupdate",this.onRackMonitorUpdate_),i.children.forEach(e=>{this.setUpApi_(e)})}get children(){return this.controller_.rack.children.map(e=>getApiByController(this.apiSet_,e))}addInput(e,t,i){let r=null!=i?i:{},s=this.controller_.view.element.ownerDocument,a=this.pool_.createInput(s,createBindingTarget(e,t,r.presetKey),r),n=new InputBindingApi(a);return this.add(n,r.index)}addMonitor(e,t,i){let r=null!=i?i:{},s=this.controller_.view.element.ownerDocument,a=this.pool_.createMonitor(s,createBindingTarget(e,t),r),n=new MonitorBindingApi(a);return this.add(n,r.index)}addFolder(e){return addFolderAsBlade(this,e)}addButton(e){return addButtonAsBlade(this,e)}addSeparator(e){return addSeparatorAsBlade(this,e)}addTab(e){return addTabAsBlade(this,e)}add(e,t){this.controller_.rack.add(e.controller_,t);let i=this.apiSet_.find(t=>t.controller_===e.controller_);return i&&this.apiSet_.remove(i),this.apiSet_.add(e),e}remove(e){this.controller_.rack.remove(e.controller_)}addBlade(e){let t=this.controller_.view.element.ownerDocument,i=this.pool_.createBlade(t,e),r=this.pool_.createBladeApi(i);return this.add(r,e.index)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}setUpApi_(e){let t=this.apiSet_.find(t=>t.controller_===e);t||this.apiSet_.add(this.pool_.createBladeApi(e))}onRackAdd_(e){this.setUpApi_(e.bladeController)}onRackRemove_(e){if(e.isRoot){let t=getApiByController(this.apiSet_,e.bladeController);this.apiSet_.remove(t)}}onRackInputChange_(e){let t=e.bladeController;if(t instanceof InputBindingController){let i=getApiByController(this.apiSet_,t),r=t.binding;this.emitter_.emit("change",{event:new TpChangeEvent(i,r.target.read(),r.target.presetKey,e.options.last)})}else if(t instanceof ValueBladeController){let i=getApiByController(this.apiSet_,t);this.emitter_.emit("change",{event:new TpChangeEvent(i,t.value.rawValue,void 0,e.options.last)})}}onRackMonitorUpdate_(e){if(!(e.bladeController instanceof MonitorBindingController))throw TpError.shouldNeverHappen();let t=getApiByController(this.apiSet_,e.bladeController),i=e.bladeController.binding;this.emitter_.emit("update",{event:new TpUpdateEvent(t,i.target.read(),i.target.presetKey)})}};let FolderApi=class FolderApi extends RackLikeApi{constructor(e,t){super(e,new RackApi(e.rackController,t)),this.emitter_=new Emitter,this.controller_.foldable.value("expanded").emitter.on("change",e=>{this.emitter_.emit("fold",{event:new TpFoldEvent(this,e.sender.rawValue)})}),this.rackApi_.on("change",e=>{this.emitter_.emit("change",{event:e})}),this.rackApi_.on("update",e=>{this.emitter_.emit("update",{event:e})})}get expanded(){return this.controller_.foldable.get("expanded")}set expanded(e){this.controller_.foldable.set("expanded",e)}get title(){return this.controller_.props.get("title")}set title(e){this.controller_.props.set("title",e)}get children(){return this.rackApi_.children}addInput(e,t,i){return this.rackApi_.addInput(e,t,i)}addMonitor(e,t,i){return this.rackApi_.addMonitor(e,t,i)}addFolder(e){return this.rackApi_.addFolder(e)}addButton(e){return this.rackApi_.addButton(e)}addSeparator(e){return this.rackApi_.addSeparator(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){return this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addBlade(e){return this.rackApi_.addBlade(e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}};let RackLikeController=class RackLikeController extends BladeController{constructor(e){super({blade:e.blade,view:e.view,viewProps:e.rackController.viewProps}),this.rackController=e.rackController}};let PlainView=class PlainView{constructor(e,t){let i=ClassName(t.viewName);this.element=e.createElement("div"),this.element.classList.add(i()),t.viewProps.bindClassModifiers(this.element)}};function findInputBindingController(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r instanceof InputBindingController&&r.binding===t)return r}return null}function findMonitorBindingController(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r instanceof MonitorBindingController&&r.binding===t)return r}return null}function findValueBladeController(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r instanceof ValueBladeController&&r.value===t)return r}return null}function findSubRack(e){return e instanceof RackController?e.rack:e instanceof RackLikeController?e.rackController.rack:null}function findSubBladeControllerSet(e){let t=findSubRack(e);return t?t.bcSet_:null}let BladeRack=class BladeRack{constructor(e){var t,i;this.onBladePositionsChange_=this.onBladePositionsChange_.bind(this),this.onSetAdd_=this.onSetAdd_.bind(this),this.onSetRemove_=this.onSetRemove_.bind(this),this.onChildDispose_=this.onChildDispose_.bind(this),this.onChildPositionsChange_=this.onChildPositionsChange_.bind(this),this.onChildInputChange_=this.onChildInputChange_.bind(this),this.onChildMonitorUpdate_=this.onChildMonitorUpdate_.bind(this),this.onChildValueChange_=this.onChildValueChange_.bind(this),this.onChildViewPropsChange_=this.onChildViewPropsChange_.bind(this),this.onDescendantLayout_=this.onDescendantLayout_.bind(this),this.onDescendantInputChange_=this.onDescendantInputChange_.bind(this),this.onDescendantMonitorUpdate_=this.onDescendantMonitorUpdate_.bind(this),this.emitter=new Emitter,this.blade_=null!==(t=e.blade)&&void 0!==t?t:null,null===(i=this.blade_)||void 0===i||i.value("positions").emitter.on("change",this.onBladePositionsChange_),this.viewProps=e.viewProps,this.bcSet_=new NestedOrderedSet(findSubBladeControllerSet),this.bcSet_.emitter.on("add",this.onSetAdd_),this.bcSet_.emitter.on("remove",this.onSetRemove_)}get children(){return this.bcSet_.items}add(e,t){var i;null===(i=e.parent)||void 0===i||i.remove(e),isPropertyWritable(e,"parent")?e.parent=this:(e.parent_=this,warnMissing({key:"parent",target:"BladeController",place:"BladeRack.add"})),this.bcSet_.add(e,t)}remove(e){isPropertyWritable(e,"parent")?e.parent=null:(e.parent_=null,warnMissing({key:"parent",target:"BladeController",place:"BladeRack.remove"})),this.bcSet_.remove(e)}find(e){return this.bcSet_.allItems().filter(t=>t instanceof e)}onSetAdd_(e){this.updatePositions_();let t=e.target===e.root;if(this.emitter.emit("add",{bladeController:e.item,index:e.index,isRoot:t,sender:this}),!t)return;let i=e.item;if(i.viewProps.emitter.on("change",this.onChildViewPropsChange_),i.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),i.viewProps.handleDispose(this.onChildDispose_),i instanceof InputBindingController)i.binding.emitter.on("change",this.onChildInputChange_);else if(i instanceof MonitorBindingController)i.binding.emitter.on("update",this.onChildMonitorUpdate_);else if(i instanceof ValueBladeController)i.value.emitter.on("change",this.onChildValueChange_);else{let e=findSubRack(i);if(e){let t=e.emitter;t.on("layout",this.onDescendantLayout_),t.on("inputchange",this.onDescendantInputChange_),t.on("monitorupdate",this.onDescendantMonitorUpdate_)}}}onSetRemove_(e){this.updatePositions_();let t=e.target===e.root;if(this.emitter.emit("remove",{bladeController:e.item,isRoot:t,sender:this}),!t)return;let i=e.item;if(i instanceof InputBindingController)i.binding.emitter.off("change",this.onChildInputChange_);else if(i instanceof MonitorBindingController)i.binding.emitter.off("update",this.onChildMonitorUpdate_);else if(i instanceof ValueBladeController)i.value.emitter.off("change",this.onChildValueChange_);else{let e=findSubRack(i);if(e){let t=e.emitter;t.off("layout",this.onDescendantLayout_),t.off("inputchange",this.onDescendantInputChange_),t.off("monitorupdate",this.onDescendantMonitorUpdate_)}}}updatePositions_(){let e=this.bcSet_.items.filter(e=>!e.viewProps.get("hidden")),t=e[0],i=e[e.length-1];this.bcSet_.items.forEach(e=>{let r=[];e===t&&(r.push("first"),(!this.blade_||this.blade_.get("positions").includes("veryfirst"))&&r.push("veryfirst")),e===i&&(r.push("last"),(!this.blade_||this.blade_.get("positions").includes("verylast"))&&r.push("verylast")),e.blade.set("positions",r)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(e){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){let e=this.bcSet_.items.filter(e=>e.viewProps.get("disposed"));e.forEach(e=>{this.bcSet_.remove(e)})}onChildInputChange_(e){let t=findInputBindingController(this.find(InputBindingController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("inputchange",{bladeController:t,options:e.options,sender:this})}onChildMonitorUpdate_(e){let t=findMonitorBindingController(this.find(MonitorBindingController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("monitorupdate",{bladeController:t,sender:this})}onChildValueChange_(e){let t=findValueBladeController(this.find(ValueBladeController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("inputchange",{bladeController:t,options:e.options,sender:this})}onDescendantLayout_(e){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onDescendantInputChange_(e){this.emitter.emit("inputchange",{bladeController:e.bladeController,options:e.options,sender:this})}onDescendantMonitorUpdate_(e){this.emitter.emit("monitorupdate",{bladeController:e.bladeController,sender:this})}onBladePositionsChange_(){this.updatePositions_()}};let RackController=class RackController extends BladeController{constructor(e,t){super(Object.assign(Object.assign({},t),{view:new PlainView(e,{viewName:"brk",viewProps:t.viewProps})})),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this);let i=new BladeRack({blade:t.root?void 0:t.blade,viewProps:t.viewProps});i.emitter.on("add",this.onRackAdd_),i.emitter.on("remove",this.onRackRemove_),this.rack=i,this.viewProps.handleDispose(()=>{for(let e=this.rack.children.length-1;e>=0;e--){let t=this.rack.children[e];t.viewProps.set("disposed",!0)}})}onRackAdd_(e){e.isRoot&&insertElementAt(this.view.element,e.bladeController.view.element,e.index)}onRackRemove_(e){e.isRoot&&removeElement(e.bladeController.view.element)}};let u=ClassName("cnt");let FolderView=class FolderView{constructor(e,t){var i;this.className_=ClassName(null!==(i=t.viewName)&&void 0!==i?i:"fld"),this.element=e.createElement("div"),this.element.classList.add(this.className_(),u()),t.viewProps.bindClassModifiers(this.element),this.foldable_=t.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),bindValueMap(this.foldable_,"completed",valueToClassName(this.element,this.className_(void 0,"cpl")));let r=e.createElement("button");r.classList.add(this.className_("b")),bindValueMap(t.props,"title",e=>{isEmpty(e)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r;let s=e.createElement("div");s.classList.add(this.className_("i")),this.element.appendChild(s);let a=e.createElement("div");a.classList.add(this.className_("t")),bindValueToTextContent(t.props.value("title"),a),this.buttonElement.appendChild(a),this.titleElement=a;let n=e.createElement("div");n.classList.add(this.className_("m")),this.buttonElement.appendChild(n);let o=t.containerElement;o.classList.add(this.className_("c")),this.element.appendChild(o),this.containerElement=o}};let FolderController=class FolderController extends RackLikeController{constructor(e,t){var i;let r=Foldable.create(null===(i=t.expanded)||void 0===i||i),s=new RackController(e,{blade:t.blade,root:t.root,viewProps:t.viewProps});super(Object.assign(Object.assign({},t),{rackController:s,view:new FolderView(e,{containerElement:s.view.element,foldable:r,props:t.props,viewName:t.root?"rot":void 0,viewProps:t.viewProps})})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=t.props,this.foldable=r,bindFoldable(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}};let d={id:"folder",type:"blade",accept(e){let t=parseParams(e,{title:r.required.string,view:r.required.constant("folder"),expanded:r.optional.boolean});return t?{params:t}:null},controller:e=>new FolderController(e.document,{blade:e.blade,expanded:e.params.expanded,props:ValueMap.fromObject({title:e.params.title}),viewProps:e.viewProps}),api:e=>e.controller instanceof FolderController?new FolderApi(e.controller,e.pool):null};let LabeledValueController=class LabeledValueController extends ValueBladeController{constructor(e,t){let i=t.valueController.viewProps;super(Object.assign(Object.assign({},t),{value:t.valueController.value,view:new LabelView(e,{props:t.props,viewProps:i}),viewProps:i})),this.props=t.props,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}};let SeparatorApi=class SeparatorApi extends BladeApi{};let _=ClassName("spr");let SeparatorView=class SeparatorView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(_()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("hr");i.classList.add(_("r")),this.element.appendChild(i)}};let SeparatorController=class SeparatorController extends BladeController{constructor(e,t){super(Object.assign(Object.assign({},t),{view:new SeparatorView(e,{viewProps:t.viewProps})}))}};let p={id:"separator",type:"blade",accept(e){let t=parseParams(e,{view:r.required.constant("separator")});return t?{params:t}:null},controller:e=>new SeparatorController(e.document,{blade:e.blade,viewProps:e.viewProps}),api:e=>e.controller instanceof SeparatorController?new SeparatorApi(e.controller):null},f=ClassName("tbi");let TabItemView=class TabItemView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(f()),t.viewProps.bindClassModifiers(this.element),bindValueMap(t.props,"selected",e=>{e?this.element.classList.add(f(void 0,"sel")):this.element.classList.remove(f(void 0,"sel"))});let i=e.createElement("button");i.classList.add(f("b")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let r=e.createElement("div");r.classList.add(f("t")),bindValueToTextContent(t.props.value("title"),r),this.buttonElement.appendChild(r),this.titleElement=r}};let TabItemController=class TabItemController{constructor(e,t){this.emitter=new Emitter,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new TabItemView(e,{props:t.props,viewProps:t.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}};let TabPageController=class TabPageController{constructor(e,t){this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new TabItemController(e,{props:t.itemProps,viewProps:ViewProps.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.cc_=new RackController(e,{blade:createBlade(),viewProps:ViewProps.create()}),this.props=t.props,bindValueMap(this.props,"selected",e=>{this.itemController.props.set("selected",e),this.contentController.viewProps.set("hidden",!e)})}get itemController(){return this.ic_}get contentController(){return this.cc_}onItemClick_(){this.props.set("selected",!0)}};let TabPageApi=class TabPageApi{constructor(e,t){this.controller_=e,this.rackApi_=t}get title(){var e;return null!==(e=this.controller_.itemController.props.get("title"))&&void 0!==e?e:""}set title(e){this.controller_.itemController.props.set("title",e)}get selected(){return this.controller_.props.get("selected")}set selected(e){this.controller_.props.set("selected",e)}get children(){return this.rackApi_.children}addButton(e){return this.rackApi_.addButton(e)}addFolder(e){return this.rackApi_.addFolder(e)}addSeparator(e){return this.rackApi_.addSeparator(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addInput(e,t,i){return this.rackApi_.addInput(e,t,i)}addMonitor(e,t,i){return this.rackApi_.addMonitor(e,t,i)}addBlade(e){return this.rackApi_.addBlade(e)}};let TabApi=class TabApi extends RackLikeApi{constructor(e,t){super(e,new RackApi(e.rackController,t)),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.onSelect_=this.onSelect_.bind(this),this.emitter_=new Emitter,this.pageApiMap_=new Map,this.rackApi_.on("change",e=>{this.emitter_.emit("change",{event:e})}),this.rackApi_.on("update",e=>{this.emitter_.emit("update",{event:e})}),this.controller_.tab.selectedIndex.emitter.on("change",this.onSelect_),this.controller_.pageSet.emitter.on("add",this.onPageAdd_),this.controller_.pageSet.emitter.on("remove",this.onPageRemove_),this.controller_.pageSet.items.forEach(e=>{this.setUpPageApi_(e)})}get pages(){return this.controller_.pageSet.items.map(e=>{let t=this.pageApiMap_.get(e);if(!t)throw TpError.shouldNeverHappen();return t})}addPage(e){let t=this.controller_.view.element.ownerDocument,i=new TabPageController(t,{itemProps:ValueMap.fromObject({selected:!1,title:e.title}),props:ValueMap.fromObject({selected:!1})});this.controller_.add(i,e.index);let r=this.pageApiMap_.get(i);if(!r)throw TpError.shouldNeverHappen();return r}removePage(e){this.controller_.remove(e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}setUpPageApi_(e){let t=this.rackApi_.apiSet_.find(t=>t.controller_===e.contentController);if(!t)throw TpError.shouldNeverHappen();let i=new TabPageApi(e,t);this.pageApiMap_.set(e,i)}onPageAdd_(e){this.setUpPageApi_(e.item)}onPageRemove_(e){let t=this.pageApiMap_.get(e.item);if(!t)throw TpError.shouldNeverHappen();this.pageApiMap_.delete(e.item)}onSelect_(e){this.emitter_.emit("select",{event:new TpTabSelectEvent(this,e.rawValue)})}};let Tab=class Tab{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=createValue(!0),this.selectedIndex=createValue(-1),this.items_=[]}add(e,t){let i=null!=t?t:this.items_.length;this.items_.splice(i,0,e),e.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(e){let t=this.items_.indexOf(e);t<0||(this.items_.splice(t,1),e.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length){this.selectedIndex.rawValue=-1,this.empty.rawValue=!0;return}let e=this.items_.findIndex(e=>e.rawValue);e<0?(this.items_.forEach((e,t)=>{e.rawValue=0===t}),this.selectedIndex.rawValue=0):(this.items_.forEach((t,i)=>{t.rawValue=i===e}),this.selectedIndex.rawValue=e),this.empty.rawValue=!1}onItemSelectedChange_(e){if(e.rawValue){let t=this.items_.findIndex(t=>t===e.sender);this.items_.forEach((e,i)=>{e.rawValue=i===t}),this.selectedIndex.rawValue=t}else this.keepSelection_()}};let m=ClassName("tab");let TabView=class TabView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(m(),u()),t.viewProps.bindClassModifiers(this.element),bindValue(t.empty,valueToClassName(this.element,m(void 0,"nop")));let i=e.createElement("div");i.classList.add(m("t")),this.element.appendChild(i),this.itemsElement=i;let r=e.createElement("div");r.classList.add(m("i")),this.element.appendChild(r);let s=t.contentsElement;s.classList.add(m("c")),this.element.appendChild(s),this.contentsElement=s}};let TabController=class TabController extends RackLikeController{constructor(e,t){let i=new RackController(e,{blade:t.blade,viewProps:t.viewProps}),r=new Tab;super({blade:t.blade,rackController:i,view:new TabView(e,{contentsElement:i.view.element,empty:r.empty,viewProps:t.viewProps})}),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.pageSet_=new NestedOrderedSet(()=>null),this.pageSet_.emitter.on("add",this.onPageAdd_),this.pageSet_.emitter.on("remove",this.onPageRemove_),this.tab=r}get pageSet(){return this.pageSet_}add(e,t){this.pageSet_.add(e,t)}remove(e){this.pageSet_.remove(this.pageSet_.items[e])}onPageAdd_(e){let t=e.item;insertElementAt(this.view.itemsElement,t.itemController.view.element,e.index),t.itemController.viewProps.set("parent",this.viewProps),this.rackController.rack.add(t.contentController,e.index),this.tab.add(t.props.value("selected"))}onPageRemove_(e){let t=e.item;removeElement(t.itemController.view.element),t.itemController.viewProps.set("parent",null),this.rackController.rack.remove(t.contentController),this.tab.remove(t.props.value("selected"))}};let g={id:"tab",type:"blade",accept(e){let t=parseParams(e,{pages:r.required.array(r.required.object({title:r.required.string})),view:r.required.constant("tab")});return t&&0!==t.pages.length?{params:t}:null},controller(e){let t=new TabController(e.document,{blade:e.blade,viewProps:e.viewProps});return e.params.pages.forEach(i=>{let r=new TabPageController(e.document,{itemProps:ValueMap.fromObject({selected:!1,title:i.title}),props:ValueMap.fromObject({selected:!1})});t.add(r)}),t},api:e=>e.controller instanceof TabController?new TabApi(e.controller,e.pool):null};function createBladeController(e,t){let i=e.accept(t.params);if(!i)return null;let s=r.optional.boolean(t.params.disabled).value,a=r.optional.boolean(t.params.hidden).value;return e.controller({blade:createBlade(),document:t.document,params:Object.assign(Object.assign({},i.params),{disabled:s,hidden:a}),viewProps:ViewProps.create({disabled:s,hidden:a})})}let ManualTicker=class ManualTicker{constructor(){this.disabled=!1,this.emitter=new Emitter}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}};let IntervalTicker=class IntervalTicker{constructor(e,t){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=e,this.emitter=new Emitter,this.interval_=t,this.setTimer_()}get disabled(){return this.disabled_}set disabled(e){this.disabled_=e,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;let e=this.doc_.defaultView;e&&e.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;let e=this.doc_.defaultView;e&&(this.timerId_=e.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}};let InputBinding=class InputBinding{constructor(e){this.onValueChange_=this.onValueChange_.bind(this),this.reader=e.reader,this.writer=e.writer,this.emitter=new Emitter,this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.target=e.target,this.read()}read(){let e=this.target.read();void 0!==e&&(this.value.rawValue=this.reader(e))}write_(e){this.writer(this.target,e)}onValueChange_(e){this.write_(e.rawValue),this.emitter.emit("change",{options:e.options,rawValue:e.rawValue,sender:this})}};function fillBuffer(e,t){for(;e.length<t;)e.push(void 0)}function initializeBuffer(e){let t=[];return fillBuffer(t,e),createValue(t)}function createTrimmedBuffer(e){let t=e.indexOf(void 0);return t<0?e:e.slice(0,t)}function createPushedBuffer(e,t){let i=[...createTrimmedBuffer(e),t];return i.length>e.length?i.splice(0,i.length-e.length):fillBuffer(i,e.length),i}let MonitorBinding=class MonitorBinding{constructor(e){this.onTick_=this.onTick_.bind(this),this.reader_=e.reader,this.target=e.target,this.emitter=new Emitter,this.value=e.value,this.ticker=e.ticker,this.ticker.emitter.on("tick",this.onTick_),this.read()}dispose(){this.ticker.dispose()}read(){let e=this.target.read();if(void 0===e)return;let t=this.value.rawValue,i=this.reader_(e);this.value.rawValue=createPushedBuffer(t,i),this.emitter.emit("update",{rawValue:i,sender:this})}onTick_(e){this.read()}};let CompositeConstraint=class CompositeConstraint{constructor(e){this.constraints=e}constrain(e){return this.constraints.reduce((e,t)=>t.constrain(e),e)}};function findConstraint(e,t){if(e instanceof t)return e;if(e instanceof CompositeConstraint){let i=e.constraints.reduce((e,i)=>e||(i instanceof t?i:null),null);if(i)return i}return null}let DefiniteRangeConstraint=class DefiniteRangeConstraint{constructor(e){this.values=ValueMap.fromObject({max:e.max,min:e.min})}constrain(e){let t=this.values.get("max"),i=this.values.get("min");return Math.min(Math.max(e,i),t)}};let ListConstraint=class ListConstraint{constructor(e){this.values=ValueMap.fromObject({options:e})}get options(){return this.values.get("options")}constrain(e){let t=this.values.get("options");if(0===t.length)return e;let i=t.filter(t=>t.value===e).length>0;return i?e:t[0].value}};let RangeConstraint=class RangeConstraint{constructor(e){this.values=ValueMap.fromObject({max:e.max,min:e.min})}get maxValue(){return this.values.get("max")}get minValue(){return this.values.get("min")}constrain(e){let t=this.values.get("max"),i=this.values.get("min"),r=e;return isEmpty(i)||(r=Math.max(r,i)),isEmpty(t)||(r=Math.min(r,t)),r}};let StepConstraint=class StepConstraint{constructor(e,t=0){this.step=e,this.origin=t}constrain(e){let t=this.origin%this.step,i=Math.round((e-t)/this.step);return t+i*this.step}};let v=ClassName("lst");let ListView=class ListView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.props_=t.props,this.element=e.createElement("div"),this.element.classList.add(v()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("select");i.classList.add(v("s")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.selectElement=i;let r=e.createElement("div");r.classList.add(v("m")),r.appendChild(createSvgIconElement(e,"dropdown")),this.element.appendChild(r),t.value.emitter.on("change",this.onValueChange_),this.value_=t.value,bindValueMap(this.props_,"options",t=>{removeChildElements(this.selectElement),t.forEach(t=>{let i=e.createElement("option");i.textContent=t.text,this.selectElement.appendChild(i)}),this.update_()})}update_(){let e=this.props_.get("options").map(e=>e.value);this.selectElement.selectedIndex=e.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}};let ListController=class ListController{constructor(e,t){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new ListView(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(e){let t=e.currentTarget;this.value.rawValue=this.props.get("options")[t.selectedIndex].value}};let x=ClassName("pop");let PopupView=class PopupView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(x()),t.viewProps.bindClassModifiers(this.element),bindValue(t.shows,valueToClassName(this.element,x(void 0,"v")))}};let PopupController=class PopupController{constructor(e,t){this.shows=createValue(!1),this.viewProps=t.viewProps,this.view=new PopupView(e,{shows:this.shows,viewProps:this.viewProps})}};let b=ClassName("txt");let TextView=class TextView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.element=e.createElement("div"),this.element.classList.add(b()),t.viewProps.bindClassModifiers(this.element),this.props_=t.props,this.props_.emitter.on("change",this.onChange_);let i=e.createElement("input");i.classList.add(b("i")),i.type="text",t.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,t.value.emitter.on("change",this.onChange_),this.value_=t.value,this.refresh()}refresh(){let e=this.props_.get("formatter");this.inputElement.value=e(this.value_.rawValue)}onChange_(){this.refresh()}};let TextController=class TextController{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=t.parser,this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new TextView(e,{props:t.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(e){let t=e.currentTarget,i=t.value,r=this.parser_(i);isEmpty(r)||(this.value.rawValue=r),this.view.refresh()}};function boolToString(e){return String(e)}function boolFromUnknown(e){return"false"!==e&&!!e}function BooleanFormatter(e){return boolToString(e)}let NumberLiteralNode=class NumberLiteralNode{constructor(e){this.text=e}evaluate(){return Number(this.text)}toString(){return this.text}};let T={"**":(e,t)=>Math.pow(e,t),"*":(e,t)=>e*t,"/":(e,t)=>e/t,"%":(e,t)=>e%t,"+":(e,t)=>e+t,"-":(e,t)=>e-t,"<<":(e,t)=>e<<t,">>":(e,t)=>e>>t,">>>":(e,t)=>e>>>t,"&":(e,t)=>e&t,"^":(e,t)=>e^t,"|":(e,t)=>e|t};let BinaryOperationNode=class BinaryOperationNode{constructor(e,t,i){this.left=t,this.operator=e,this.right=i}evaluate(){let e=T[this.operator];if(!e)throw Error(`unexpected binary operator: '${this.operator}`);return e(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}};let S={"+":e=>e,"-":e=>-e,"~":e=>~e};let UnaryOperationNode=class UnaryOperationNode{constructor(e,t){this.operator=e,this.expression=t}evaluate(){let e=S[this.operator];if(!e)throw Error(`unexpected unary operator: '${this.operator}`);return e(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}};function combineReader(e){return(t,i)=>{for(let r=0;r<e.length;r++){let s=e[r](t,i);if(""!==s)return s}return""}}function readWhitespace(e,t){var i;let r=e.substr(t).match(/^\s+/);return null!==(i=r&&r[0])&&void 0!==i?i:""}function readNonZeroDigit(e,t){let i=e.substr(t,1);return i.match(/^[1-9]$/)?i:""}function readDecimalDigits(e,t){var i;let r=e.substr(t).match(/^[0-9]+/);return null!==(i=r&&r[0])&&void 0!==i?i:""}function readSignedInteger(e,t){let i=readDecimalDigits(e,t);if(""!==i)return i;let r=e.substr(t,1);if(t+=1,"-"!==r&&"+"!==r)return"";let s=readDecimalDigits(e,t);return""===s?"":r+s}function readExponentPart(e,t){let i=e.substr(t,1);if(t+=1,"e"!==i.toLowerCase())return"";let r=readSignedInteger(e,t);return""===r?"":i+r}function readDecimalIntegerLiteral(e,t){let i=e.substr(t,1);if("0"===i)return i;let r=readNonZeroDigit(e,t);return(t+=r.length,""===r)?"":r+readDecimalDigits(e,t)}function readDecimalLiteral1(e,t){let i=readDecimalIntegerLiteral(e,t);if(t+=i.length,""===i)return"";let r=e.substr(t,1);if(t+=r.length,"."!==r)return"";let s=readDecimalDigits(e,t);return t+=s.length,i+r+s+readExponentPart(e,t)}function readDecimalLiteral2(e,t){let i=e.substr(t,1);if(t+=i.length,"."!==i)return"";let r=readDecimalDigits(e,t);return(t+=r.length,""===r)?"":i+r+readExponentPart(e,t)}function readDecimalLiteral3(e,t){let i=readDecimalIntegerLiteral(e,t);return(t+=i.length,""===i)?"":i+readExponentPart(e,t)}let C=combineReader([readDecimalLiteral1,readDecimalLiteral2,readDecimalLiteral3]);function parseBinaryDigits(e,t){var i;let r=e.substr(t).match(/^[01]+/);return null!==(i=r&&r[0])&&void 0!==i?i:""}function readBinaryIntegerLiteral(e,t){let i=e.substr(t,2);if(t+=i.length,"0b"!==i.toLowerCase())return"";let r=parseBinaryDigits(e,t);return""===r?"":i+r}function readOctalDigits(e,t){var i;let r=e.substr(t).match(/^[0-7]+/);return null!==(i=r&&r[0])&&void 0!==i?i:""}function readOctalIntegerLiteral(e,t){let i=e.substr(t,2);if(t+=i.length,"0o"!==i.toLowerCase())return"";let r=readOctalDigits(e,t);return""===r?"":i+r}function readHexDigits(e,t){var i;let r=e.substr(t).match(/^[0-9a-f]+/i);return null!==(i=r&&r[0])&&void 0!==i?i:""}function readHexIntegerLiteral(e,t){let i=e.substr(t,2);if(t+=i.length,"0x"!==i.toLowerCase())return"";let r=readHexDigits(e,t);return""===r?"":i+r}let E=combineReader([readBinaryIntegerLiteral,readOctalIntegerLiteral,readHexIntegerLiteral]),y=combineReader([E,C]);function parseLiteral(e,t){let i=y(e,t);return(t+=i.length,""===i)?null:{evaluable:new NumberLiteralNode(i),cursor:t}}function parseParenthesizedExpression(e,t){let i=e.substr(t,1);if(t+=i.length,"("!==i)return null;let r=parseExpression(e,t);if(!r)return null;t=r.cursor,t+=readWhitespace(e,t).length;let s=e.substr(t,1);return(t+=s.length,")"!==s)?null:{evaluable:r.evaluable,cursor:t}}function parsePrimaryExpression(e,t){var i;return null!==(i=parseLiteral(e,t))&&void 0!==i?i:parseParenthesizedExpression(e,t)}function parseUnaryExpression(e,t){let i=parsePrimaryExpression(e,t);if(i)return i;let r=e.substr(t,1);if(t+=r.length,"+"!==r&&"-"!==r&&"~"!==r)return null;let s=parseUnaryExpression(e,t);return s?{cursor:t=s.cursor,evaluable:new UnaryOperationNode(r,s.evaluable)}:null}function readBinaryOperator(e,t,i){i+=readWhitespace(t,i).length;let r=e.filter(e=>t.startsWith(e,i))[0];return r?(i+=r.length,{cursor:i+=readWhitespace(t,i).length,operator:r}):null}function createBinaryOperationExpressionParser(e,t){return(i,r)=>{let s=e(i,r);if(!s)return null;r=s.cursor;let a=s.evaluable;for(;;){let s=readBinaryOperator(t,i,r);if(!s)break;r=s.cursor;let n=e(i,r);if(!n)return null;r=n.cursor,a=new BinaryOperationNode(s.operator,a,n.evaluable)}return a?{cursor:r,evaluable:a}:null}}let R=[["**"],["*","/","%"],["+","-"],["<<",">>>",">>"],["&"],["^"],["|"]].reduce((e,t)=>createBinaryOperationExpressionParser(e,t),parseUnaryExpression);function parseExpression(e,t){return t+=readWhitespace(e,t).length,R(e,t)}function parseEcmaNumberExpression(e){let t=parseExpression(e,0);if(!t)return null;let i=t.cursor+readWhitespace(e,t.cursor).length;return i!==e.length?null:t.evaluable}function parseNumber(e){var t;let i=parseEcmaNumberExpression(e);return null!==(t=null==i?void 0:i.evaluate())&&void 0!==t?t:null}function numberFromUnknown(e){if("number"==typeof e)return e;if("string"==typeof e){let t=parseNumber(e);if(!isEmpty(t))return t}return 0}function numberToString(e){return String(e)}function createNumberFormatter(e){return t=>t.toFixed(Math.max(Math.min(e,20),0))}let P=createNumberFormatter(0);function formatPercentage(e){return P(e)+"%"}function stringFromUnknown(e){return String(e)}function formatString(e){return e}function connectValues({primary:e,secondary:t,forward:i,backward:r}){let s=!1;function preventFeedback(e){s||(s=!0,e(),s=!1)}e.emitter.on("change",r=>{preventFeedback(()=>{t.setRawValue(i(e,t),r.options)})}),t.emitter.on("change",s=>{preventFeedback(()=>{e.setRawValue(r(e,t),s.options)}),preventFeedback(()=>{t.setRawValue(i(e,t),s.options)})}),preventFeedback(()=>{t.setRawValue(i(e,t),{forceEmit:!1,last:!0})})}function getStepForKey(e,t){let i=e*(t.altKey?.1:1)*(t.shiftKey?10:1);return t.upKey?+i:t.downKey?-i:0}function getVerticalStepKeys(e){return{altKey:e.altKey,downKey:"ArrowDown"===e.key,shiftKey:e.shiftKey,upKey:"ArrowUp"===e.key}}function getHorizontalStepKeys(e){return{altKey:e.altKey,downKey:"ArrowLeft"===e.key,shiftKey:e.shiftKey,upKey:"ArrowRight"===e.key}}function isVerticalArrowKey(e){return"ArrowUp"===e||"ArrowDown"===e}function isArrowKey(e){return isVerticalArrowKey(e)||"ArrowLeft"===e||"ArrowRight"===e}function computeOffset$1(e,t){var i,r;let s=t.ownerDocument.defaultView,a=t.getBoundingClientRect();return{x:e.pageX-((null!==(i=s&&s.scrollX)&&void 0!==i?i:0)+a.left),y:e.pageY-((null!==(r=s&&s.scrollY)&&void 0!==r?r:0)+a.top)}}let PointerHandler=class PointerHandler{constructor(e){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=e,this.emitter=new Emitter,e.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),e.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),e.addEventListener("touchend",this.onTouchEnd_),e.addEventListener("mousedown",this.onMouseDown_)}computePosition_(e){let t=this.elem_.getBoundingClientRect();return{bounds:{width:t.width,height:t.height},point:e?{x:e.x,y:e.y}:null}}onMouseDown_(e){var t;e.preventDefault(),null===(t=e.currentTarget)||void 0===t||t.focus();let i=this.elem_.ownerDocument;i.addEventListener("mousemove",this.onDocumentMouseMove_),i.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseMove_(e){this.emitter.emit("move",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseUp_(e){let t=this.elem_.ownerDocument;t.removeEventListener("mousemove",this.onDocumentMouseMove_),t.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onTouchStart_(e){e.preventDefault();let t=e.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-i.left,y:t.clientY-i.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchMove_(e){let t=e.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-i.left,y:t.clientY-i.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchEnd_(e){var t;let i=null!==(t=e.targetTouches.item(0))&&void 0!==t?t:this.lastTouch_,r=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:e.altKey,data:this.computePosition_(i?{x:i.clientX-r.left,y:i.clientY-r.top}:void 0),sender:this,shiftKey:e.shiftKey})}};function mapRange(e,t,i,r,s){return r+(e-t)/(i-t)*(s-r)}function getDecimalDigits(e){let t=String(e.toFixed(10)),i=t.split(".")[1];return i.replace(/0+$/,"").length}function constrainRange(e,t,i){return Math.min(Math.max(e,t),i)}let A=ClassName("txt");let NumberTextView=class NumberTextView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on("change",this.onChange_),this.element=e.createElement("div"),this.element.classList.add(A(),A(void 0,"num")),t.arrayPosition&&this.element.classList.add(A(void 0,t.arrayPosition)),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("input");i.classList.add(A("i")),i.type="text",t.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=t.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(A()),this.inputElement.classList.add(A("i"));let r=e.createElement("div");r.classList.add(A("k")),this.element.appendChild(r),this.knobElement=r;let s=e.createElementNS(o,"svg");s.classList.add(A("g")),this.knobElement.appendChild(s);let a=e.createElementNS(o,"path");a.classList.add(A("gb")),s.appendChild(a),this.guideBodyElem_=a;let n=e.createElementNS(o,"path");n.classList.add(A("gh")),s.appendChild(n),this.guideHeadElem_=n;let l=e.createElement("div");l.classList.add(ClassName("tt")()),this.knobElement.appendChild(l),this.tooltipElem_=l,t.value.emitter.on("change",this.onChange_),this.value=t.value,this.refresh()}onDraggingChange_(e){if(null===e.rawValue){this.element.classList.remove(A(void 0,"drg"));return}this.element.classList.add(A(void 0,"drg"));let t=e.rawValue/this.props_.get("draggingScale"),i=t+(t>0?-1:t<0?1:0),r=constrainRange(-i,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",`M ${i+r},0 L${i},4 L${i+r},8 M ${t},-1 L${t},9`),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${t},4`);let s=this.props_.get("formatter");this.tooltipElem_.textContent=s(this.value.rawValue),this.tooltipElem_.style.left=`${t}px`}refresh(){let e=this.props_.get("formatter");this.inputElement.value=e(this.value.rawValue)}onChange_(){this.refresh()}};let NumberTextController=class NumberTextController{constructor(e,t){var i;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=t.baseStep,this.parser_=t.parser,this.props=t.props,this.sliderProps_=null!==(i=t.sliderProps)&&void 0!==i?i:null,this.value=t.value,this.viewProps=t.viewProps,this.dragging_=createValue(null),this.view=new NumberTextView(e,{arrayPosition:t.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);let r=new PointerHandler(this.view.knobElement);r.emitter.on("down",this.onPointerDown_),r.emitter.on("move",this.onPointerMove_),r.emitter.on("up",this.onPointerUp_)}constrainValue_(e){var t,i;let r=null===(t=this.sliderProps_)||void 0===t?void 0:t.get("minValue"),s=null===(i=this.sliderProps_)||void 0===i?void 0:i.get("maxValue"),a=e;return void 0!==r&&(a=Math.max(a,r)),void 0!==s&&(a=Math.min(a,s)),a}onInputChange_(e){let t=e.currentTarget,i=t.value,r=this.parser_(i);isEmpty(r)||(this.value.rawValue=this.constrainValue_(r)),this.view.refresh()}onInputKeyDown_(e){let t=getStepForKey(this.baseStep_,getVerticalStepKeys(e));0!==t&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+t),{forceEmit:!1,last:!1})}onInputKeyUp_(e){let t=getStepForKey(this.baseStep_,getVerticalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(e){if(!e.point)return null;let t=e.point.x-e.bounds.width/2;return this.constrainValue_(this.originRawValue_+t*this.props.get("draggingScale"))}onPointerMove_(e){let t=this.computeDraggingValue_(e.data);null!==t&&(this.value.setRawValue(t,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(e){let t=this.computeDraggingValue_(e.data);null!==t&&(this.value.setRawValue(t,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}};let M=ClassName("sld");let SliderView=class SliderView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on("change",this.onChange_),this.element=e.createElement("div"),this.element.classList.add(M()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(M("t")),t.viewProps.bindTabIndex(i),this.element.appendChild(i),this.trackElement=i;let r=e.createElement("div");r.classList.add(M("k")),this.trackElement.appendChild(r),this.knobElement=r,t.value.emitter.on("change",this.onChange_),this.value=t.value,this.update_()}update_(){let e=constrainRange(mapRange(this.value.rawValue,this.props_.get("minValue"),this.props_.get("maxValue"),0,100),0,100);this.knobElement.style.width=`${e}%`}onChange_(){this.update_()}};let SliderController=class SliderController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=t.baseStep,this.value=t.value,this.viewProps=t.viewProps,this.props=t.props,this.view=new SliderView(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){e.point&&this.value.setRawValue(mapRange(constrainRange(e.point.x,0,e.bounds.width),0,e.bounds.width,this.props.get("minValue"),this.props.get("maxValue")),t)}onPointerDownOrMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(this.baseStep_,getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue+t,{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(this.baseStep_,getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let I=ClassName("sldtxt");let SliderTextView=class SliderTextView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(I());let i=e.createElement("div");i.classList.add(I("s")),this.sliderView_=t.sliderView,i.appendChild(this.sliderView_.element),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(I("t")),this.textView_=t.textView,r.appendChild(this.textView_.element),this.element.appendChild(r)}};let SliderTextController=class SliderTextController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.sliderC_=new SliderController(e,{baseStep:t.baseStep,props:t.sliderProps,value:t.value,viewProps:this.viewProps}),this.textC_=new NumberTextController(e,{baseStep:t.baseStep,parser:t.parser,props:t.textProps,sliderProps:t.sliderProps,value:t.value,viewProps:t.viewProps}),this.view=new SliderTextView(e,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}};function writePrimitive(e,t){e.write(t)}function parseListOptions(e){return Array.isArray(e)?r.required.array(r.required.object({text:r.required.string,value:r.required.raw}))(e).value:"object"==typeof e?r.required.raw(e).value:void 0}function parsePickerLayout(e){if("inline"===e||"popup"===e)return e}function parsePointDimensionParams(e){return r.required.object({max:r.optional.number,min:r.optional.number,step:r.optional.number})(e).value}function normalizeListOptions(e){if(Array.isArray(e))return e;let t=[];return Object.keys(e).forEach(i=>{t.push({text:i,value:e[i]})}),t}function createListConstraint(e){return isEmpty(e)?null:new ListConstraint(normalizeListOptions(e))}function findStep(e){let t=e?findConstraint(e,StepConstraint):null;return t?t.step:null}function getSuitableDecimalDigits(e,t){let i=e&&findConstraint(e,StepConstraint);return i?getDecimalDigits(i.step):Math.max(getDecimalDigits(t),2)}function getBaseStep(e){let t=findStep(e);return null!=t?t:1}function getSuitableDraggingScale(e,t){var i;let r=e&&findConstraint(e,StepConstraint),s=Math.abs(null!==(i=null==r?void 0:r.step)&&void 0!==i?i:t);return 0===s?.1:Math.pow(10,Math.floor(Math.log10(s))-1)}let D=ClassName("ckb");let CheckboxView=class CheckboxView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.element=e.createElement("div"),this.element.classList.add(D()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("label");i.classList.add(D("l")),this.element.appendChild(i);let r=e.createElement("input");r.classList.add(D("i")),r.type="checkbox",i.appendChild(r),this.inputElement=r,t.viewProps.bindDisabled(this.inputElement);let s=e.createElement("div");s.classList.add(D("w")),i.appendChild(s);let a=createSvgIconElement(e,"check");s.appendChild(a),t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}};let CheckboxController=class CheckboxController{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new CheckboxView(e,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(e){let t=e.currentTarget;this.value.rawValue=t.checked}};function createConstraint$6(e){let t=[],i=createListConstraint(e.options);return i&&t.push(i),new CompositeConstraint(t)}let O={id:"input-bool",type:"input",accept:(e,t)=>{if("boolean"!=typeof e)return null;let i=parseParams(t,{options:r.optional.custom(parseListOptions)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>boolFromUnknown,constraint:e=>createConstraint$6(e.params),writer:e=>writePrimitive},controller:e=>{let t=e.document,i=e.value,r=e.constraint,s=r&&findConstraint(r,ListConstraint);return s?new ListController(t,{props:new ValueMap({options:s.values.value("options")}),value:i,viewProps:e.viewProps}):new CheckboxController(t,{value:i,viewProps:e.viewProps})}},B=ClassName("col");let ColorView=class ColorView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(B()),t.foldable.bindExpandedClass(this.element,B(void 0,"expanded")),bindValueMap(t.foldable,"completed",valueToClassName(this.element,B(void 0,"cpl")));let i=e.createElement("div");i.classList.add(B("h")),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(B("s")),i.appendChild(r),this.swatchElement=r;let s=e.createElement("div");if(s.classList.add(B("t")),i.appendChild(s),this.textElement=s,"inline"===t.pickerLayout){let t=e.createElement("div");t.classList.add(B("p")),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}};function rgbToHslInt(e,t,i){let r=constrainRange(e/255,0,1),s=constrainRange(t/255,0,1),a=constrainRange(i/255,0,1),n=Math.max(r,s,a),o=Math.min(r,s,a),l=n-o,h=0,c=0;return 0!==l&&(c=l/(1-Math.abs(n+o-1)),h=(h=r===n?(s-a)/l:s===n?2+(a-r)/l:4+(r-s)/l)/6+(h<0?1:0)),[360*h,100*c,100*((o+n)/2)]}function hslToRgbInt(e,t,i){let r,s,a;let n=(e%360+360)%360,o=constrainRange(t/100,0,1),l=constrainRange(i/100,0,1),h=(1-Math.abs(2*l-1))*o,c=h*(1-Math.abs(n/60%2-1)),u=l-h/2;return n>=0&&n<60?[r,s,a]=[h,c,0]:n>=60&&n<120?[r,s,a]=[c,h,0]:n>=120&&n<180?[r,s,a]=[0,h,c]:n>=180&&n<240?[r,s,a]=[0,c,h]:n>=240&&n<300?[r,s,a]=[c,0,h]:[r,s,a]=[h,0,c],[(r+u)*255,(s+u)*255,(a+u)*255]}function rgbToHsvInt(e,t,i){let r=constrainRange(e/255,0,1),s=constrainRange(t/255,0,1),a=constrainRange(i/255,0,1),n=Math.max(r,s,a),o=n-Math.min(r,s,a);return[0===o?0:n===r?60*(((s-a)/o%6+6)%6):n===s?60*((a-r)/o+2):60*((r-s)/o+4),100*(0===n?0:o/n),100*n]}function hsvToRgbInt(e,t,i){let r,s,a;let n=(e%360+360)%360,o=constrainRange(t/100,0,1),l=constrainRange(i/100,0,1),h=l*o,c=h*(1-Math.abs(n/60%2-1)),u=l-h;return n>=0&&n<60?[r,s,a]=[h,c,0]:n>=60&&n<120?[r,s,a]=[c,h,0]:n>=120&&n<180?[r,s,a]=[0,h,c]:n>=180&&n<240?[r,s,a]=[0,c,h]:n>=240&&n<300?[r,s,a]=[c,0,h]:[r,s,a]=[h,0,c],[(r+u)*255,(s+u)*255,(a+u)*255]}function hslToHsvInt(e,t,i){let r=i+t*(100-Math.abs(2*i-100))/200;return[e,0!==r?t*(100-Math.abs(2*i-100))/r:0,i+t*(100-Math.abs(2*i-100))/200]}function hsvToHslInt(e,t,i){let r=100-Math.abs(i*(200-t)/100-100);return[e,0!==r?t*i/r:0,i*(200-t)/200]}function removeAlphaComponent(e){return[e[0],e[1],e[2]]}function appendAlphaComponent(e,t){return[e[0],e[1],e[2],t]}let N={hsl:{hsl:(e,t,i)=>[e,t,i],hsv:hslToHsvInt,rgb:hslToRgbInt},hsv:{hsl:hsvToHslInt,hsv:(e,t,i)=>[e,t,i],rgb:hsvToRgbInt},rgb:{hsl:rgbToHslInt,hsv:rgbToHsvInt,rgb:(e,t,i)=>[e,t,i]}};function getColorMaxComponents(e,t){return["float"===t?1:"rgb"===e?255:360,"float"===t?1:"rgb"===e?255:100,"float"===t?1:"rgb"===e?255:100]}function loopHueRange(e,t){return e===t?t:(e%t+t)%t}function constrainColorComponents(e,t,i){var r;let s=getColorMaxComponents(t,i);return["rgb"===t?constrainRange(e[0],0,s[0]):loopHueRange(e[0],s[0]),constrainRange(e[1],0,s[1]),constrainRange(e[2],0,s[2]),constrainRange(null!==(r=e[3])&&void 0!==r?r:1,0,1)]}function convertColorType(e,t,i,r){let s=getColorMaxComponents(t,i),a=getColorMaxComponents(t,r);return e.map((e,t)=>e/s[t]*a[t])}function convertColor(e,t,i){let r=convertColorType(e,t.mode,t.type,"int"),s=N[t.mode][i.mode](...r);return convertColorType(s,i.mode,"int",i.type)}function isRgbColorComponent(e,t){return!("object"!=typeof e||isEmpty(e))&&t in e&&"number"==typeof e[t]}let Color=class Color{static black(e="int"){return new Color([0,0,0],"rgb",e)}static fromObject(e,t="int"){let i="a"in e?[e.r,e.g,e.b,e.a]:[e.r,e.g,e.b];return new Color(i,"rgb",t)}static toRgbaObject(e,t="int"){return e.toRgbaObject(t)}static isRgbColorObject(e){return isRgbColorComponent(e,"r")&&isRgbColorComponent(e,"g")&&isRgbColorComponent(e,"b")}static isRgbaColorObject(e){return this.isRgbColorObject(e)&&isRgbColorComponent(e,"a")}static isColorObject(e){return this.isRgbColorObject(e)}static equals(e,t){if(e.mode!==t.mode)return!1;let i=e.comps_,r=t.comps_;for(let e=0;e<i.length;e++)if(i[e]!==r[e])return!1;return!0}constructor(e,t,i="int"){this.mode=t,this.type=i,this.comps_=constrainColorComponents(e,t,i)}getComponents(e,t="int"){return appendAlphaComponent(convertColor(removeAlphaComponent(this.comps_),{mode:this.mode,type:this.type},{mode:null!=e?e:this.mode,type:t}),this.comps_[3])}toRgbaObject(e="int"){let t=this.getComponents("rgb",e);return{r:t[0],g:t[1],b:t[2],a:t[3]}}};let F=ClassName("colp");let ColorPickerView=class ColorPickerView{constructor(e,t){this.alphaViews_=null,this.element=e.createElement("div"),this.element.classList.add(F()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(F("hsv"));let r=e.createElement("div");r.classList.add(F("sv")),this.svPaletteView_=t.svPaletteView,r.appendChild(this.svPaletteView_.element),i.appendChild(r);let s=e.createElement("div");s.classList.add(F("h")),this.hPaletteView_=t.hPaletteView,s.appendChild(this.hPaletteView_.element),i.appendChild(s),this.element.appendChild(i);let a=e.createElement("div");if(a.classList.add(F("rgb")),this.textView_=t.textView,a.appendChild(this.textView_.element),this.element.appendChild(a),t.alphaViews){this.alphaViews_={palette:t.alphaViews.palette,text:t.alphaViews.text};let i=e.createElement("div");i.classList.add(F("a"));let r=e.createElement("div");r.classList.add(F("ap")),r.appendChild(this.alphaViews_.palette.element),i.appendChild(r);let s=e.createElement("div");s.classList.add(F("at")),s.appendChild(this.alphaViews_.text.element),i.appendChild(s),this.element.appendChild(i)}}get allFocusableElements(){let e=[this.svPaletteView_.element,this.hPaletteView_.element,this.textView_.modeSelectElement,...this.textView_.textViews.map(e=>e.inputElement)];return this.alphaViews_&&e.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),e}};function parseColorType(e){return"int"===e?"int":"float"===e?"float":void 0}function parseColorInputParams(e){return parseParams(e,{alpha:r.optional.boolean,color:r.optional.object({alpha:r.optional.boolean,type:r.optional.custom(parseColorType)}),expanded:r.optional.boolean,picker:r.optional.custom(parsePickerLayout)})}function getBaseStepForColor(e){return e?.1:1}function extractColorType(e){var t;return null===(t=e.color)||void 0===t?void 0:t.type}function equalsStringColorFormat(e,t){return e.alpha===t.alpha&&e.mode===t.mode&&e.notation===t.notation&&e.type===t.type}function parseCssNumberOrPercentage(e,t){let i=e.match(/^(.+)%$/);return i?Math.min(.01*parseFloat(i[1])*t,t):Math.min(parseFloat(e),t)}let w={deg:e=>e,grad:e=>360*e/400,rad:e=>360*e/(2*Math.PI),turn:e=>360*e};function parseCssNumberOrAngle(e){let t=e.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!t)return parseFloat(e);let i=parseFloat(t[1]),r=t[2];return w[r](i)}function parseFunctionalRgbColorComponents(e){let t=e.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[parseCssNumberOrPercentage(t[1],255),parseCssNumberOrPercentage(t[2],255),parseCssNumberOrPercentage(t[3],255)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function createFunctionalRgbColorParser(e){return t=>{let i=parseFunctionalRgbColorComponents(t);return i?new Color(i,"rgb",e):null}}function parseFunctionalRgbaColorComponents(e){let t=e.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[parseCssNumberOrPercentage(t[1],255),parseCssNumberOrPercentage(t[2],255),parseCssNumberOrPercentage(t[3],255),parseCssNumberOrPercentage(t[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function createFunctionalRgbaColorParser(e){return t=>{let i=parseFunctionalRgbaColorComponents(t);return i?new Color(i,"rgb",e):null}}function parseHslColorComponents(e){let t=e.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[parseCssNumberOrAngle(t[1]),parseCssNumberOrPercentage(t[2],100),parseCssNumberOrPercentage(t[3],100)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function createHslColorParser(e){return t=>{let i=parseHslColorComponents(t);return i?new Color(i,"hsl",e):null}}function parseHslaColorComponents(e){let t=e.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[parseCssNumberOrAngle(t[1]),parseCssNumberOrPercentage(t[2],100),parseCssNumberOrPercentage(t[3],100),parseCssNumberOrPercentage(t[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function createHslaColorParser(e){return t=>{let i=parseHslaColorComponents(t);return i?new Color(i,"hsl",e):null}}function parseHexRgbColorComponents(e){let t=e.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)];let i=e.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]:null}function parseHexRgbColor(e){let t=parseHexRgbColorComponents(e);return t?new Color(t,"rgb","int"):null}function parseHexRgbaColorComponents(e){let t=e.match(/^#?([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16),mapRange(parseInt(t[4]+t[4],16),0,255,0,1)];let i=e.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16),mapRange(parseInt(i[4],16),0,255,0,1)]:null}function parseHexRgbaColor(e){let t=parseHexRgbaColorComponents(e);return t?new Color(t,"rgb","int"):null}function parseObjectRgbColorComponents(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let i=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function createObjectRgbColorParser(e){return t=>{let i=parseObjectRgbColorComponents(t);return i?new Color(i,"rgb",e):null}}function parseObjectRgbaColorComponents(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let i=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),parseFloat(t[4])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function createObjectRgbaColorParser(e){return t=>{let i=parseObjectRgbaColorComponents(t);return i?new Color(i,"rgb",e):null}}let L=[{parser:parseHexRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:parseHexRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:parseFunctionalRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:parseFunctionalRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:parseHslColorComponents,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:parseHslaColorComponents,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:parseObjectRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:parseObjectRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"object"}}];function detectStringColor(e){return L.reduce((t,{parser:i,result:r})=>t||(i(e)?r:null),null)}function detectStringColorFormat(e,t="int"){let i=detectStringColor(e);return i?"hex"===i.notation&&"float"!==t?Object.assign(Object.assign({},i),{type:"int"}):"func"===i.notation?Object.assign(Object.assign({},i),{type:t}):null:null}let V={int:[parseHexRgbColor,parseHexRgbaColor,createFunctionalRgbColorParser("int"),createFunctionalRgbaColorParser("int"),createHslColorParser("int"),createHslaColorParser("int"),createObjectRgbColorParser("int"),createObjectRgbaColorParser("int")],float:[createFunctionalRgbColorParser("float"),createFunctionalRgbaColorParser("float"),createHslColorParser("float"),createHslaColorParser("float"),createObjectRgbColorParser("float"),createObjectRgbaColorParser("float")]};function createColorStringBindingReader(e){let t=V[e];return i=>{if("string"!=typeof i)return Color.black(e);let r=t.reduce((e,t)=>e||t(i),null);return null!=r?r:Color.black(e)}}function createColorStringParser(e){let t=V[e];return e=>t.reduce((t,i)=>t||i(e),null)}function zerofill(e){let t=constrainRange(Math.floor(e),0,255).toString(16);return 1===t.length?`0${t}`:t}function colorToHexRgbString(e,t="#"){let i=removeAlphaComponent(e.getComponents("rgb")).map(zerofill).join("");return`${t}${i}`}function colorToHexRgbaString(e,t="#"){let i=e.getComponents("rgb"),r=[i[0],i[1],i[2],255*i[3]].map(zerofill).join("");return`${t}${r}`}function colorToFunctionalRgbString(e,t){let i=createNumberFormatter("float"===t?2:0),r=removeAlphaComponent(e.getComponents("rgb",t)).map(e=>i(e));return`rgb(${r.join(", ")})`}function createFunctionalRgbColorFormatter(e){return t=>colorToFunctionalRgbString(t,e)}function colorToFunctionalRgbaString(e,t){let i=createNumberFormatter(2),r=createNumberFormatter("float"===t?2:0),s=e.getComponents("rgb",t).map((e,t)=>(3===t?i:r)(e));return`rgba(${s.join(", ")})`}function createFunctionalRgbaColorFormatter(e){return t=>colorToFunctionalRgbaString(t,e)}function colorToFunctionalHslString(e){let t=[createNumberFormatter(0),formatPercentage,formatPercentage],i=removeAlphaComponent(e.getComponents("hsl")).map((e,i)=>t[i](e));return`hsl(${i.join(", ")})`}function colorToFunctionalHslaString(e){let t=[createNumberFormatter(0),formatPercentage,formatPercentage,createNumberFormatter(2)],i=e.getComponents("hsl").map((e,i)=>t[i](e));return`hsla(${i.join(", ")})`}function colorToObjectRgbString(e,t){let i=createNumberFormatter("float"===t?2:0),r=["r","g","b"],s=removeAlphaComponent(e.getComponents("rgb",t)).map((e,t)=>`${r[t]}: ${i(e)}`);return`{${s.join(", ")}}`}function createObjectRgbColorFormatter(e){return t=>colorToObjectRgbString(t,e)}function colorToObjectRgbaString(e,t){let i=createNumberFormatter(2),r=createNumberFormatter("float"===t?2:0),s=["r","g","b","a"],a=e.getComponents("rgb",t).map((e,t)=>`${s[t]}: ${(3===t?i:r)(e)}`);return`{${a.join(", ")}}`}function createObjectRgbaColorFormatter(e){return t=>colorToObjectRgbaString(t,e)}let U=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:colorToHexRgbString},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:colorToHexRgbaString},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:colorToFunctionalHslString},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:colorToFunctionalHslaString},...["int","float"].reduce((e,t)=>[...e,{format:{alpha:!1,mode:"rgb",notation:"func",type:t},stringifier:createFunctionalRgbColorFormatter(t)},{format:{alpha:!0,mode:"rgb",notation:"func",type:t},stringifier:createFunctionalRgbaColorFormatter(t)},{format:{alpha:!1,mode:"rgb",notation:"object",type:t},stringifier:createObjectRgbColorFormatter(t)},{format:{alpha:!0,mode:"rgb",notation:"object",type:t},stringifier:createObjectRgbaColorFormatter(t)}],[])];function findColorStringifier(e){return U.reduce((t,i)=>t||(equalsStringColorFormat(i.format,e)?i.stringifier:null),null)}let k=ClassName("apl");let APaletteView=class APaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(k()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let i=e.createElement("div");i.classList.add(k("b")),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(k("c")),i.appendChild(r),this.colorElem_=r;let s=e.createElement("div");s.classList.add(k("m")),this.element.appendChild(s),this.markerElem_=s;let a=e.createElement("div");a.classList.add(k("p")),this.markerElem_.appendChild(a),this.previewElem_=a,this.update_()}update_(){let e=this.value.rawValue,t=e.getComponents("rgb"),i=new Color([t[0],t[1],t[2],0],"rgb"),r=new Color([t[0],t[1],t[2],255],"rgb"),s=["to right",colorToFunctionalRgbaString(i),colorToFunctionalRgbaString(r)];this.colorElem_.style.background=`linear-gradient(${s.join(",")})`,this.previewElem_.style.backgroundColor=colorToFunctionalRgbaString(e);let a=mapRange(t[3],0,1,0,100);this.markerElem_.style.left=`${a}%`}onValueChange_(){this.update_()}};let APaletteController=class APaletteController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new APaletteView(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let i=e.point.x/e.bounds.width,r=this.value.rawValue,[s,a,n]=r.getComponents("hsv");this.value.setRawValue(new Color([s,a,n,i],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(getBaseStepForColor(!0),getHorizontalStepKeys(e));if(0===t)return;let i=this.value.rawValue,[r,s,a,n]=i.getComponents("hsv");this.value.setRawValue(new Color([r,s,a,n+t],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(getBaseStepForColor(!0),getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let G=ClassName("coltxt");function createModeSelectElement(e){let t=e.createElement("select");return t.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"}].reduce((t,i)=>{let r=e.createElement("option");return r.textContent=i.text,r.value=i.value,t.appendChild(r),t},e.createDocumentFragment())),t}let ColorTextView=class ColorTextView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(G()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(G("m")),this.modeElem_=createModeSelectElement(e),this.modeElem_.classList.add(G("ms")),i.appendChild(this.modeSelectElement),t.viewProps.bindDisabled(this.modeElem_);let r=e.createElement("div");r.classList.add(G("mm")),r.appendChild(createSvgIconElement(e,"dropdown")),i.appendChild(r),this.element.appendChild(i);let s=e.createElement("div");s.classList.add(G("w")),this.element.appendChild(s),this.textsElem_=s,this.textViews_=t.textViews,this.applyTextViews_(),bindValue(t.colorMode,e=>{this.modeElem_.value=e})}get modeSelectElement(){return this.modeElem_}get textViews(){return this.textViews_}set textViews(e){this.textViews_=e,this.applyTextViews_()}applyTextViews_(){removeChildElements(this.textsElem_);let e=this.element.ownerDocument;this.textViews_.forEach(t=>{let i=e.createElement("div");i.classList.add(G("c")),i.appendChild(t.element),this.textsElem_.appendChild(i)})}};function createFormatter$2(e){return createNumberFormatter("float"===e?2:0)}function createConstraint$5(e,t,i){let r=getColorMaxComponents(e,t)[i];return new DefiniteRangeConstraint({min:0,max:r})}function createComponentController(e,t,i){return new NumberTextController(e,{arrayPosition:0===i?"fst":2===i?"lst":"mid",baseStep:getBaseStepForColor(!1),parser:t.parser,props:ValueMap.fromObject({draggingScale:"float"===t.colorType?.01:1,formatter:createFormatter$2(t.colorType)}),value:createValue(0,{constraint:createConstraint$5(t.colorMode,t.colorType,i)}),viewProps:t.viewProps})}let ColorTextController=class ColorTextController{constructor(e,t){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=t.colorType,this.parser_=t.parser,this.value=t.value,this.viewProps=t.viewProps,this.colorMode=createValue(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(e),this.view=new ColorTextView(e,{colorMode:this.colorMode,textViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(e){let t={colorMode:this.colorMode.rawValue,colorType:this.colorType_,parser:this.parser_,viewProps:this.viewProps},i=[createComponentController(e,t,0),createComponentController(e,t,1),createComponentController(e,t,2)];return i.forEach((e,t)=>{connectValues({primary:this.value,secondary:e.value,forward:e=>e.rawValue.getComponents(this.colorMode.rawValue,this.colorType_)[t],backward:(e,i)=>{let r=this.colorMode.rawValue,s=e.rawValue.getComponents(r,this.colorType_);return s[t]=i.rawValue,new Color(appendAlphaComponent(removeAlphaComponent(s),s[3]),r,this.colorType_)}})}),i}onModeSelectChange_(e){let t=e.currentTarget;this.colorMode.rawValue=t.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.textViews=[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view]}};let z=ClassName("hpl");let HPaletteView=class HPaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(z()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let i=e.createElement("div");i.classList.add(z("c")),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(z("m")),this.element.appendChild(r),this.markerElem_=r,this.update_()}update_(){let e=this.value.rawValue,[t]=e.getComponents("hsv");this.markerElem_.style.backgroundColor=colorToFunctionalRgbString(new Color([t,100,100],"hsv"));let i=mapRange(t,0,360,0,100);this.markerElem_.style.left=`${i}%`}onValueChange_(){this.update_()}};let HPaletteController=class HPaletteController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new HPaletteView(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let i=mapRange(constrainRange(e.point.x,0,e.bounds.width),0,e.bounds.width,0,360),r=this.value.rawValue,[,s,a,n]=r.getComponents("hsv");this.value.setRawValue(new Color([i,s,a,n],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(getBaseStepForColor(!1),getHorizontalStepKeys(e));if(0===t)return;let i=this.value.rawValue,[r,s,a,n]=i.getComponents("hsv");this.value.setRawValue(new Color([r+t,s,a,n],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(getBaseStepForColor(!1),getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let W=ClassName("svp");let SvPaletteView=class SvPaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(W()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let i=e.createElement("canvas");i.height=64,i.width=64,i.classList.add(W("c")),this.element.appendChild(i),this.canvasElement=i;let r=e.createElement("div");r.classList.add(W("m")),this.element.appendChild(r),this.markerElem_=r,this.update_()}update_(){let e=getCanvasContext(this.canvasElement);if(!e)return;let t=this.value.rawValue,i=t.getComponents("hsv"),r=this.canvasElement.width,s=this.canvasElement.height,a=e.getImageData(0,0,r,s),n=a.data;for(let e=0;e<s;e++)for(let t=0;t<r;t++){let a=mapRange(t,0,r,0,100),o=mapRange(e,0,s,100,0),l=hsvToRgbInt(i[0],a,o),h=(e*r+t)*4;n[h]=l[0],n[h+1]=l[1],n[h+2]=l[2],n[h+3]=255}e.putImageData(a,0,0);let o=mapRange(i[1],0,100,0,100);this.markerElem_.style.left=`${o}%`;let l=mapRange(i[2],0,100,100,0);this.markerElem_.style.top=`${l}%`}onValueChange_(){this.update_()}};let SvPaletteController=class SvPaletteController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new SvPaletteView(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let i=mapRange(e.point.x,0,e.bounds.width,0,100),r=mapRange(e.point.y,0,e.bounds.height,100,0),[s,,,a]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Color([s,i,r,a],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){isArrowKey(e.key)&&e.preventDefault();let[t,i,r,s]=this.value.rawValue.getComponents("hsv"),a=getBaseStepForColor(!1),n=getStepForKey(a,getHorizontalStepKeys(e)),o=getStepForKey(a,getVerticalStepKeys(e));(0!==n||0!==o)&&this.value.setRawValue(new Color([t,i+n,r+o,s],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getBaseStepForColor(!1),i=getStepForKey(t,getHorizontalStepKeys(e)),r=getStepForKey(t,getVerticalStepKeys(e));(0!==i||0!==r)&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let ColorPickerController=class ColorPickerController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.hPaletteC_=new HPaletteController(e,{value:this.value,viewProps:this.viewProps}),this.svPaletteC_=new SvPaletteController(e,{value:this.value,viewProps:this.viewProps}),this.alphaIcs_=t.supportsAlpha?{palette:new APaletteController(e,{value:this.value,viewProps:this.viewProps}),text:new NumberTextController(e,{parser:parseNumber,baseStep:.1,props:ValueMap.fromObject({draggingScale:.01,formatter:createNumberFormatter(2)}),value:createValue(0,{constraint:new DefiniteRangeConstraint({min:0,max:1})}),viewProps:this.viewProps})}:null,this.alphaIcs_&&connectValues({primary:this.value,secondary:this.alphaIcs_.text.value,forward:e=>e.rawValue.getComponents()[3],backward:(e,t)=>{let i=e.rawValue.getComponents();return i[3]=t.rawValue,new Color(i,e.rawValue.mode)}}),this.textC_=new ColorTextController(e,{colorType:t.colorType,parser:parseNumber,value:this.value,viewProps:this.viewProps}),this.view=new ColorPickerView(e,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:t.supportsAlpha,svPaletteView:this.svPaletteC_.view,textView:this.textC_.view,viewProps:this.viewProps})}get textController(){return this.textC_}};let H=ClassName("colsw");let ColorSwatchView=class ColorSwatchView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.element=e.createElement("div"),this.element.classList.add(H()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(H("sw")),this.element.appendChild(i),this.swatchElem_=i;let r=e.createElement("button");r.classList.add(H("b")),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r,this.update_()}update_(){let e=this.value.rawValue;this.swatchElem_.style.backgroundColor=colorToHexRgbaString(e)}onValueChange_(){this.update_()}};let ColorSwatchController=class ColorSwatchController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new ColorSwatchView(e,{value:this.value,viewProps:this.viewProps})}};let ColorController=class ColorController{constructor(e,t){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=Foldable.create(t.expanded),this.swatchC_=new ColorSwatchController(e,{value:this.value,viewProps:this.viewProps});let i=this.swatchC_.view.buttonElement;i.addEventListener("blur",this.onButtonBlur_),i.addEventListener("click",this.onButtonClick_),this.textC_=new TextController(e,{parser:t.parser,props:ValueMap.fromObject({formatter:t.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new ColorView(e,{foldable:this.foldable_,pickerLayout:t.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===t.pickerLayout?new PopupController(e,{viewProps:this.viewProps}):null;let r=new ColorPickerController(e,{colorType:t.colorType,supportsAlpha:t.supportsAlpha,value:this.value,viewProps:this.viewProps});r.view.allFocusableElements.forEach(e=>{e.addEventListener("blur",this.onPopupChildBlur_),e.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=r,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(r.view.element),connectValues({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:e=>e.rawValue,backward:(e,t)=>t.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),bindFoldable(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,i=e.relatedTarget;i&&t.contains(i)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,i=findNextTarget(e);!(i&&t.contains(i))&&(!i||i!==this.swatchC_.view.buttonElement||supportsTouch(t.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?"Escape"===e.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===e.key&&this.swatchC_.view.buttonElement.focus()}};function colorFromObject(e,t){return Color.isColorObject(e)?Color.fromObject(e,t):Color.black(t)}function colorToRgbNumber(e){return removeAlphaComponent(e.getComponents("rgb")).reduce((e,t)=>e<<8|255&Math.floor(t),0)}function colorToRgbaNumber(e){return e.getComponents("rgb").reduce((e,t,i)=>e<<8|255&Math.floor(3===i?255*t:t),0)>>>0}function numberToRgbColor(e){return new Color([e>>16&255,e>>8&255,255&e],"rgb")}function numberToRgbaColor(e){return new Color([e>>24&255,e>>16&255,e>>8&255,mapRange(255&e,0,255,0,1)],"rgb")}function colorFromRgbNumber(e){return"number"!=typeof e?Color.black():numberToRgbColor(e)}function colorFromRgbaNumber(e){return"number"!=typeof e?Color.black():numberToRgbaColor(e)}function createColorStringWriter(e){let t=findColorStringifier(e);return t?(e,i)=>{writePrimitive(e,t(i))}:null}function createColorNumberWriter(e){let t=e?colorToRgbaNumber:colorToRgbNumber;return(e,i)=>{writePrimitive(e,t(i))}}function writeRgbaColorObject(e,t,i){let r=t.toRgbaObject(i);e.writeProperty("r",r.r),e.writeProperty("g",r.g),e.writeProperty("b",r.b),e.writeProperty("a",r.a)}function writeRgbColorObject(e,t,i){let r=t.toRgbaObject(i);e.writeProperty("r",r.r),e.writeProperty("g",r.g),e.writeProperty("b",r.b)}function createColorObjectWriter(e,t){return(i,r)=>{e?writeRgbaColorObject(i,r,t):writeRgbColorObject(i,r,t)}}function shouldSupportAlpha$1(e){var t;return null!=e&&!!e.alpha||null!==(t=null==e?void 0:e.color)&&void 0!==t&&!!t.alpha}function createFormatter$1(e){return e?e=>colorToHexRgbaString(e,"0x"):e=>colorToHexRgbString(e,"0x")}function isForColor(e){return"color"in e||"view"in e&&"color"===e.view}let X={id:"input-color-number",type:"input",accept:(e,t)=>{if("number"!=typeof e||!isForColor(t))return null;let i=parseColorInputParams(t);return i?{initialValue:e,params:i}:null},binding:{reader:e=>shouldSupportAlpha$1(e.params)?colorFromRgbaNumber:colorFromRgbNumber,equals:Color.equals,writer:e=>createColorNumberWriter(shouldSupportAlpha$1(e.params))},controller:e=>{let t=shouldSupportAlpha$1(e.params),i="expanded"in e.params?e.params.expanded:void 0,r="picker"in e.params?e.params.picker:void 0;return new ColorController(e.document,{colorType:"int",expanded:null!=i&&i,formatter:createFormatter$1(t),parser:createColorStringParser("int"),pickerLayout:null!=r?r:"popup",supportsAlpha:t,value:e.value,viewProps:e.viewProps})}};function shouldSupportAlpha(e){return Color.isRgbaColorObject(e)}function createColorObjectReader(e){return t=>colorFromObject(t,e)}function createColorObjectFormatter(e,t){return i=>e?colorToObjectRgbaString(i,t):colorToObjectRgbString(i,t)}let Y={id:"input-color-object",type:"input",accept:(e,t)=>{if(!Color.isColorObject(e))return null;let i=parseColorInputParams(t);return i?{initialValue:e,params:i}:null},binding:{reader:e=>createColorObjectReader(extractColorType(e.params)),equals:Color.equals,writer:e=>createColorObjectWriter(shouldSupportAlpha(e.initialValue),extractColorType(e.params))},controller:e=>{var t;let i=Color.isRgbaColorObject(e.initialValue),r="expanded"in e.params?e.params.expanded:void 0,s="picker"in e.params?e.params.picker:void 0,a=null!==(t=extractColorType(e.params))&&void 0!==t?t:"int";return new ColorController(e.document,{colorType:a,expanded:null!=r&&r,formatter:createColorObjectFormatter(i,a),parser:createColorStringParser(a),pickerLayout:null!=s?s:"popup",supportsAlpha:i,value:e.value,viewProps:e.viewProps})}},j={id:"input-color-string",type:"input",accept:(e,t)=>{if("string"!=typeof e||"view"in t&&"text"===t.view)return null;let i=detectStringColorFormat(e,extractColorType(t));if(!i)return null;let r=findColorStringifier(i);if(!r)return null;let s=parseColorInputParams(t);return s?{initialValue:e,params:s}:null},binding:{reader:e=>{var t;return createColorStringBindingReader(null!==(t=extractColorType(e.params))&&void 0!==t?t:"int")},equals:Color.equals,writer:e=>{let t=detectStringColorFormat(e.initialValue,extractColorType(e.params));if(!t)throw TpError.shouldNeverHappen();let i=createColorStringWriter(t);if(!i)throw TpError.notBindable();return i}},controller:e=>{let t=detectStringColorFormat(e.initialValue,extractColorType(e.params));if(!t)throw TpError.shouldNeverHappen();let i=findColorStringifier(t);if(!i)throw TpError.shouldNeverHappen();let r="expanded"in e.params?e.params.expanded:void 0,s="picker"in e.params?e.params.picker:void 0;return new ColorController(e.document,{colorType:t.type,expanded:null!=r&&r,formatter:i,parser:createColorStringParser(t.type),pickerLayout:null!=s?s:"popup",supportsAlpha:t.alpha,value:e.value,viewProps:e.viewProps})}};let PointNdConstraint=class PointNdConstraint{constructor(e){this.components=e.components,this.asm_=e.assembly}constrain(e){let t=this.asm_.toComponents(e).map((e,t)=>{var i,r;return null!==(r=null===(i=this.components[t])||void 0===i?void 0:i.constrain(e))&&void 0!==r?r:e});return this.asm_.fromComponents(t)}};let K=ClassName("pndtxt");let PointNdTextView=class PointNdTextView{constructor(e,t){this.textViews=t.textViews,this.element=e.createElement("div"),this.element.classList.add(K()),this.textViews.forEach(t=>{let i=e.createElement("div");i.classList.add(K("a")),i.appendChild(t.element),this.element.appendChild(i)})}};function createAxisController(e,t,i){return new NumberTextController(e,{arrayPosition:0===i?"fst":i===t.axes.length-1?"lst":"mid",baseStep:t.axes[i].baseStep,parser:t.parser,props:t.axes[i].textProps,value:createValue(0,{constraint:t.axes[i].constraint}),viewProps:t.viewProps})}let PointNdTextController=class PointNdTextController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.acs_=t.axes.map((i,r)=>createAxisController(e,t,r)),this.acs_.forEach((e,i)=>{connectValues({primary:this.value,secondary:e.value,forward:e=>t.assembly.toComponents(e.rawValue)[i],backward:(e,r)=>{let s=t.assembly.toComponents(e.rawValue);return s[i]=r.rawValue,t.assembly.fromComponents(s)}})}),this.view=new PointNdTextView(e,{textViews:this.acs_.map(e=>e.view)})}};function createStepConstraint(e,t){return"step"in e&&!isEmpty(e.step)?new StepConstraint(e.step,t):null}function createRangeConstraint(e){return isEmpty(e.max)||isEmpty(e.min)?isEmpty(e.max)&&isEmpty(e.min)?null:new RangeConstraint({max:e.max,min:e.min}):new DefiniteRangeConstraint({max:e.max,min:e.min})}function findNumberRange(e){let t=findConstraint(e,DefiniteRangeConstraint);if(t)return[t.values.get("min"),t.values.get("max")];let i=findConstraint(e,RangeConstraint);return i?[i.minValue,i.maxValue]:[void 0,void 0]}function createConstraint$4(e,t){let i=[],r=createStepConstraint(e,t);r&&i.push(r);let s=createRangeConstraint(e);s&&i.push(s);let a=createListConstraint(e.options);return a&&i.push(a),new CompositeConstraint(i)}let q={id:"input-number",type:"input",accept:(e,t)=>{if("number"!=typeof e)return null;let i=parseParams(t,{format:r.optional.function,max:r.optional.number,min:r.optional.number,options:r.optional.custom(parseListOptions),step:r.optional.number});return i?{initialValue:e,params:i}:null},binding:{reader:e=>numberFromUnknown,constraint:e=>createConstraint$4(e.params,e.initialValue),writer:e=>writePrimitive},controller:e=>{var t;let i=e.value,r=e.constraint,s=r&&findConstraint(r,ListConstraint);if(s)return new ListController(e.document,{props:new ValueMap({options:s.values.value("options")}),value:i,viewProps:e.viewProps});let a=null!==(t="format"in e.params?e.params.format:void 0)&&void 0!==t?t:createNumberFormatter(getSuitableDecimalDigits(r,i.rawValue)),n=r&&findConstraint(r,DefiniteRangeConstraint);return n?new SliderTextController(e.document,{baseStep:getBaseStep(r),parser:parseNumber,sliderProps:new ValueMap({maxValue:n.values.value("max"),minValue:n.values.value("min")}),textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(r,i.rawValue),formatter:a}),value:i,viewProps:e.viewProps}):new NumberTextController(e.document,{baseStep:getBaseStep(r),parser:parseNumber,props:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(r,i.rawValue),formatter:a}),value:i,viewProps:e.viewProps})}};let Point2d=class Point2d{constructor(e=0,t=0){this.x=e,this.y=t}getComponents(){return[this.x,this.y]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,i=e.y;return"number"==typeof t&&"number"==typeof i}static equals(e,t){return e.x===t.x&&e.y===t.y}toObject(){return{x:this.x,y:this.y}}};let $={toComponents:e=>e.getComponents(),fromComponents:e=>new Point2d(...e)},Q=ClassName("p2d");let Point2dView=class Point2dView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(Q()),t.viewProps.bindClassModifiers(this.element),bindValue(t.expanded,valueToClassName(this.element,Q(void 0,"expanded")));let i=e.createElement("div");i.classList.add(Q("h")),this.element.appendChild(i);let r=e.createElement("button");r.classList.add(Q("b")),r.appendChild(createSvgIconElement(e,"p2dpad")),t.viewProps.bindDisabled(r),i.appendChild(r),this.buttonElement=r;let s=e.createElement("div");if(s.classList.add(Q("t")),i.appendChild(s),this.textElement=s,"inline"===t.pickerLayout){let t=e.createElement("div");t.classList.add(Q("p")),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}};let Z=ClassName("p2dp");let Point2dPickerView=class Point2dPickerView{constructor(e,t){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.invertsY_=t.invertsY,this.maxValue_=t.maxValue,this.element=e.createElement("div"),this.element.classList.add(Z()),"popup"===t.layout&&this.element.classList.add(Z(void 0,"p")),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(Z("p")),t.viewProps.bindTabIndex(i),this.element.appendChild(i),this.padElement=i;let r=e.createElementNS(o,"svg");r.classList.add(Z("g")),this.padElement.appendChild(r),this.svgElem_=r;let s=e.createElementNS(o,"line");s.classList.add(Z("ax")),s.setAttributeNS(null,"x1","0"),s.setAttributeNS(null,"y1","50%"),s.setAttributeNS(null,"x2","100%"),s.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(s);let a=e.createElementNS(o,"line");a.classList.add(Z("ax")),a.setAttributeNS(null,"x1","50%"),a.setAttributeNS(null,"y1","0"),a.setAttributeNS(null,"x2","50%"),a.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(a);let n=e.createElementNS(o,"line");n.classList.add(Z("l")),n.setAttributeNS(null,"x1","50%"),n.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(n),this.lineElem_=n;let l=e.createElement("div");l.classList.add(Z("m")),this.padElement.appendChild(l),this.markerElem_=l,t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){let[e,t]=this.value.rawValue.getComponents(),i=this.maxValue_,r=mapRange(e,-i,+i,0,100),s=mapRange(t,-i,+i,0,100),a=this.invertsY_?100-s:s;this.lineElem_.setAttributeNS(null,"x2",`${r}%`),this.lineElem_.setAttributeNS(null,"y2",`${a}%`),this.markerElem_.style.left=`${r}%`,this.markerElem_.style.top=`${a}%`}onValueChange_(){this.update_()}onFoldableChange_(){this.update_()}};function computeOffset(e,t,i){return[getStepForKey(t[0],getHorizontalStepKeys(e)),getStepForKey(t[1],getVerticalStepKeys(e))*(i?1:-1)]}let Point2dPickerController=class Point2dPickerController{constructor(e,t){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.baseSteps_=t.baseSteps,this.maxValue_=t.maxValue,this.invertsY_=t.invertsY,this.view=new Point2dPickerView(e,{invertsY:this.invertsY_,layout:t.layout,maxValue:this.maxValue_,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let i=this.maxValue_,r=mapRange(e.point.x,0,e.bounds.width,-i,+i),s=mapRange(this.invertsY_?e.bounds.height-e.point.y:e.point.y,0,e.bounds.height,-i,+i);this.value.setRawValue(new Point2d(r,s),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onPadKeyDown_(e){isArrowKey(e.key)&&e.preventDefault();let[t,i]=computeOffset(e,this.baseSteps_,this.invertsY_);(0!==t||0!==i)&&this.value.setRawValue(new Point2d(this.value.rawValue.x+t,this.value.rawValue.y+i),{forceEmit:!1,last:!1})}onPadKeyUp_(e){let[t,i]=computeOffset(e,this.baseSteps_,this.invertsY_);(0!==t||0!==i)&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let Point2dController=class Point2dController{constructor(e,t){var i,r;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=Foldable.create(t.expanded),this.popC_="popup"===t.pickerLayout?new PopupController(e,{viewProps:this.viewProps}):null;let s=new Point2dPickerController(e,{baseSteps:[t.axes[0].baseStep,t.axes[1].baseStep],invertsY:t.invertsY,layout:t.pickerLayout,maxValue:t.maxValue,value:this.value,viewProps:this.viewProps});s.view.allFocusableElements.forEach(e=>{e.addEventListener("blur",this.onPopupChildBlur_),e.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=s,this.textC_=new PointNdTextController(e,{assembly:$,axes:t.axes,parser:t.parser,value:this.value,viewProps:this.viewProps}),this.view=new Point2dView(e,{expanded:this.foldable_.value("expanded"),pickerLayout:t.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("blur",this.onPadButtonBlur_),null===(r=this.view.buttonElement)||void 0===r||r.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),connectValues({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:e=>e.rawValue,backward:(e,t)=>t.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),bindFoldable(this.foldable_,this.view.pickerElement))}onPadButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,i=e.relatedTarget;i&&t.contains(i)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,i=findNextTarget(e);!(i&&t.contains(i))&&(!i||i!==this.view.buttonElement||supportsTouch(t.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?"Escape"===e.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===e.key&&this.view.buttonElement.focus()}};let Point3d=class Point3d{constructor(e=0,t=0,i=0){this.x=e,this.y=t,this.z=i}getComponents(){return[this.x,this.y,this.z]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,i=e.y,r=e.z;return"number"==typeof t&&"number"==typeof i&&"number"==typeof r}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}toObject(){return{x:this.x,y:this.y,z:this.z}}};let J={toComponents:e=>e.getComponents(),fromComponents:e=>new Point3d(...e)};function point3dFromUnknown(e){return Point3d.isObject(e)?new Point3d(e.x,e.y,e.z):new Point3d}function writePoint3d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y),e.writeProperty("z",t.z)}function createConstraint$3(e,t){return new PointNdConstraint({assembly:J,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y),createDimensionConstraint("z"in e?e.z:void 0,t.z)]})}function createAxis$2(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}let ee={id:"input-point3d",type:"input",accept:(e,t)=>{if(!Point3d.isObject(e))return null;let i=parseParams(t,{x:r.optional.custom(parsePointDimensionParams),y:r.optional.custom(parsePointDimensionParams),z:r.optional.custom(parsePointDimensionParams)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>point3dFromUnknown,constraint:e=>createConstraint$3(e.params,e.initialValue),equals:Point3d.equals,writer:e=>writePoint3d},controller:e=>{let t=e.value,i=e.constraint;if(!(i instanceof PointNdConstraint))throw TpError.shouldNeverHappen();return new PointNdTextController(e.document,{assembly:J,axes:[createAxis$2(t.rawValue.x,i.components[0]),createAxis$2(t.rawValue.y,i.components[1]),createAxis$2(t.rawValue.z,i.components[2])],parser:parseNumber,value:t,viewProps:e.viewProps})}};let Point4d=class Point4d{constructor(e=0,t=0,i=0,r=0){this.x=e,this.y=t,this.z=i,this.w=r}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,i=e.y,r=e.z,s=e.w;return"number"==typeof t&&"number"==typeof i&&"number"==typeof r&&"number"==typeof s}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}};let et={toComponents:e=>e.getComponents(),fromComponents:e=>new Point4d(...e)};function point4dFromUnknown(e){return Point4d.isObject(e)?new Point4d(e.x,e.y,e.z,e.w):new Point4d}function writePoint4d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y),e.writeProperty("z",t.z),e.writeProperty("w",t.w)}function createConstraint$2(e,t){return new PointNdConstraint({assembly:et,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y),createDimensionConstraint("z"in e?e.z:void 0,t.z),createDimensionConstraint("w"in e?e.w:void 0,t.w)]})}function createAxis$1(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}let ei={id:"input-point4d",type:"input",accept:(e,t)=>{if(!Point4d.isObject(e))return null;let i=parseParams(t,{x:r.optional.custom(parsePointDimensionParams),y:r.optional.custom(parsePointDimensionParams),z:r.optional.custom(parsePointDimensionParams),w:r.optional.custom(parsePointDimensionParams)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>point4dFromUnknown,constraint:e=>createConstraint$2(e.params,e.initialValue),equals:Point4d.equals,writer:e=>writePoint4d},controller:e=>{let t=e.value,i=e.constraint;if(!(i instanceof PointNdConstraint))throw TpError.shouldNeverHappen();return new PointNdTextController(e.document,{assembly:et,axes:t.rawValue.getComponents().map((e,t)=>createAxis$1(e,i.components[t])),parser:parseNumber,value:t,viewProps:e.viewProps})}};function createConstraint$1(e){let t=[],i=createListConstraint(e.options);return i&&t.push(i),new CompositeConstraint(t)}let er={id:"input-string",type:"input",accept:(e,t)=>{if("string"!=typeof e)return null;let i=parseParams(t,{options:r.optional.custom(parseListOptions)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>stringFromUnknown,constraint:e=>createConstraint$1(e.params),writer:e=>writePrimitive},controller:e=>{let t=e.document,i=e.value,r=e.constraint,s=r&&findConstraint(r,ListConstraint);return s?new ListController(t,{props:new ValueMap({options:s.values.value("options")}),value:i,viewProps:e.viewProps}):new TextController(t,{parser:e=>e,props:ValueMap.fromObject({formatter:formatString}),value:i,viewProps:e.viewProps})}},es={monitor:{defaultInterval:200,defaultLineCount:3}},ea=ClassName("mll");let MultiLogView=class MultiLogView{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement("div"),this.element.classList.add(ea()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("textarea");i.classList.add(ea("i")),i.style.height=`calc(var(--bld-us) * ${t.lineCount})`,i.readOnly=!0,t.viewProps.bindDisabled(i),this.element.appendChild(i),this.textareaElem_=i,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.textareaElem_,t=e.scrollTop===e.scrollHeight-e.clientHeight,i=[];this.value.rawValue.forEach(e=>{void 0!==e&&i.push(this.formatter_(e))}),e.textContent=i.join("\n"),t&&(e.scrollTop=e.scrollHeight)}onValueUpdate_(){this.update_()}};let MultiLogController=class MultiLogController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new MultiLogView(e,{formatter:t.formatter,lineCount:t.lineCount,value:this.value,viewProps:this.viewProps})}};let en=ClassName("sgl");let SingleLogView=class SingleLogView{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement("div"),this.element.classList.add(en()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("input");i.classList.add(en("i")),i.readOnly=!0,i.type="text",t.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.value.rawValue,t=e[e.length-1];this.inputElement.value=void 0!==t?this.formatter_(t):""}onValueUpdate_(){this.update_()}};let SingleLogController=class SingleLogController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new SingleLogView(e,{formatter:t.formatter,value:this.value,viewProps:this.viewProps})}};let eo={id:"monitor-bool",type:"monitor",accept:(e,t)=>{if("boolean"!=typeof e)return null;let i=parseParams(t,{lineCount:r.optional.number});return i?{initialValue:e,params:i}:null},binding:{reader:e=>boolFromUnknown},controller:e=>{var t;return 1===e.value.rawValue.length?new SingleLogController(e.document,{formatter:BooleanFormatter,value:e.value,viewProps:e.viewProps}):new MultiLogController(e.document,{formatter:BooleanFormatter,lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:es.monitor.defaultLineCount,value:e.value,viewProps:e.viewProps})}},el=ClassName("grl");let GraphLogView=class GraphLogView{constructor(e,t){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=e.createElement("div"),this.element.classList.add(el()),t.viewProps.bindClassModifiers(this.element),this.formatter_=t.formatter,this.props_=t.props,this.cursor_=t.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);let i=e.createElementNS(o,"svg");i.classList.add(el("g")),i.style.height=`calc(var(--bld-us) * ${t.lineCount})`,this.element.appendChild(i),this.svgElem_=i;let r=e.createElementNS(o,"polyline");this.svgElem_.appendChild(r),this.lineElem_=r;let s=e.createElement("div");s.classList.add(el("t"),ClassName("tt")()),this.element.appendChild(s),this.tooltipElem_=s,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}get graphElement(){return this.svgElem_}update_(){let e=this.svgElem_.getBoundingClientRect(),t=this.value.rawValue.length-1,i=this.props_.get("minValue"),r=this.props_.get("maxValue"),s=[];this.value.rawValue.forEach((a,n)=>{if(void 0===a)return;let o=mapRange(n,0,t,0,e.width),l=mapRange(a,i,r,e.height,0);s.push([o,l].join(","))}),this.lineElem_.setAttributeNS(null,"points",s.join(" "));let a=this.tooltipElem_,n=this.value.rawValue[this.cursor_.rawValue];if(void 0===n){a.classList.remove(el("t","a"));return}let o=mapRange(this.cursor_.rawValue,0,t,0,e.width),l=mapRange(n,i,r,e.height,0);a.style.left=`${o}px`,a.style.top=`${l}px`,a.textContent=`${this.formatter_(n)}`,a.classList.contains(el("t","a"))||(a.classList.add(el("t","a"),el("t","in")),forceReflow(a),a.classList.remove(el("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}};let GraphLogController=class GraphLogController{constructor(e,t){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props_=t.props,this.value=t.value,this.viewProps=t.viewProps,this.cursor_=createValue(-1),this.view=new GraphLogView(e,{cursor:this.cursor_,formatter:t.formatter,lineCount:t.lineCount,props:this.props_,value:this.value,viewProps:this.viewProps}),supportsTouch(e)){let e=new PointerHandler(this.view.element);e.emitter.on("down",this.onGraphPointerDown_),e.emitter.on("move",this.onGraphPointerMove_),e.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(e){let t=this.view.element.getBoundingClientRect();this.cursor_.rawValue=Math.floor(mapRange(e.offsetX,0,t.width,0,this.value.rawValue.length))}onGraphPointerDown_(e){this.onGraphPointerMove_(e)}onGraphPointerMove_(e){if(!e.data.point){this.cursor_.rawValue=-1;return}this.cursor_.rawValue=Math.floor(mapRange(e.data.point.x,0,e.data.bounds.width,0,this.value.rawValue.length))}onGraphPointerUp_(){this.cursor_.rawValue=-1}};function createFormatter(e){return"format"in e&&!isEmpty(e.format)?e.format:createNumberFormatter(2)}function createTextMonitor(e){var t;return 1===e.value.rawValue.length?new SingleLogController(e.document,{formatter:createFormatter(e.params),value:e.value,viewProps:e.viewProps}):new MultiLogController(e.document,{formatter:createFormatter(e.params),lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:es.monitor.defaultLineCount,value:e.value,viewProps:e.viewProps})}function createGraphMonitor(e){var t,i,r;return new GraphLogController(e.document,{formatter:createFormatter(e.params),lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:es.monitor.defaultLineCount,props:ValueMap.fromObject({maxValue:null!==(i="max"in e.params?e.params.max:null)&&void 0!==i?i:100,minValue:null!==(r="min"in e.params?e.params.min:null)&&void 0!==r?r:0}),value:e.value,viewProps:e.viewProps})}function shouldShowGraph(e){return"view"in e&&"graph"===e.view}let eh={id:"monitor-number",type:"monitor",accept:(e,t)=>{if("number"!=typeof e)return null;let i=parseParams(t,{format:r.optional.function,lineCount:r.optional.number,max:r.optional.number,min:r.optional.number,view:r.optional.string});return i?{initialValue:e,params:i}:null},binding:{defaultBufferSize:e=>shouldShowGraph(e)?64:1,reader:e=>numberFromUnknown},controller:e=>shouldShowGraph(e.params)?createGraphMonitor(e):createTextMonitor(e)},ec={id:"monitor-string",type:"monitor",accept:(e,t)=>{if("string"!=typeof e)return null;let i=parseParams(t,{lineCount:r.optional.number,multiline:r.optional.boolean});return i?{initialValue:e,params:i}:null},binding:{reader:e=>stringFromUnknown},controller:e=>{var t;let i=e.value,r=i.rawValue.length>1||"multiline"in e.params&&e.params.multiline;return r?new MultiLogController(e.document,{formatter:formatString,lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:es.monitor.defaultLineCount,value:i,viewProps:e.viewProps}):new SingleLogController(e.document,{formatter:formatString,value:i,viewProps:e.viewProps})}};function createInputBindingController(e,t){var i;let s=e.accept(t.target.read(),t.params);if(isEmpty(s))return null;let a={target:t.target,initialValue:s.initialValue,params:s.params},n=e.binding.reader(a),o=e.binding.constraint?e.binding.constraint(a):void 0,l=createValue(n(s.initialValue),{constraint:o,equals:e.binding.equals}),h=new InputBinding({reader:n,target:t.target,value:l,writer:e.binding.writer(a)}),c=r.optional.boolean(t.params.disabled).value,u=r.optional.boolean(t.params.hidden).value,d=e.controller({constraint:o,document:t.document,initialValue:s.initialValue,params:s.params,value:h.value,viewProps:ViewProps.create({disabled:c,hidden:u})});return new InputBindingController(t.document,{binding:h,blade:createBlade(),props:ValueMap.fromObject({label:"label"in t.params?null!==(i=r.optional.string(t.params.label).value)&&void 0!==i?i:null:t.target.key}),valueController:d})}function createTicker(e,t){return 0===t?new ManualTicker:new IntervalTicker(e,null!=t?t:es.monitor.defaultInterval)}function createMonitorBindingController(e,t){var i,s,a;let n=e.accept(t.target.read(),t.params);if(isEmpty(n))return null;let o={target:t.target,initialValue:n.initialValue,params:n.params},l=e.binding.reader(o),h=null!==(s=null!==(i=r.optional.number(t.params.bufferSize).value)&&void 0!==i?i:e.binding.defaultBufferSize&&e.binding.defaultBufferSize(n.params))&&void 0!==s?s:1,c=r.optional.number(t.params.interval).value,u=new MonitorBinding({reader:l,target:t.target,ticker:createTicker(t.document,c),value:initializeBuffer(h)}),d=r.optional.boolean(t.params.disabled).value,_=r.optional.boolean(t.params.hidden).value,p=e.controller({document:t.document,params:n.params,value:u.value,viewProps:ViewProps.create({disabled:d,hidden:_})});return new MonitorBindingController(t.document,{binding:u,blade:createBlade(),props:ValueMap.fromObject({label:"label"in t.params?null!==(a=r.optional.string(t.params.label).value)&&void 0!==a?a:null:t.target.key}),valueController:p})}let PluginPool=class PluginPool{constructor(){this.pluginsMap_={blades:[],inputs:[],monitors:[]}}getAll(){return[...this.pluginsMap_.blades,...this.pluginsMap_.inputs,...this.pluginsMap_.monitors]}register(e){"blade"===e.type?this.pluginsMap_.blades.unshift(e):"input"===e.type?this.pluginsMap_.inputs.unshift(e):"monitor"===e.type&&this.pluginsMap_.monitors.unshift(e)}createInput(e,t,i){let r=t.read();if(isEmpty(r))throw new TpError({context:{key:t.key},type:"nomatchingcontroller"});let s=this.pluginsMap_.inputs.reduce((r,s)=>null!=r?r:createInputBindingController(s,{document:e,target:t,params:i}),null);if(s)return s;throw new TpError({context:{key:t.key},type:"nomatchingcontroller"})}createMonitor(e,t,i){let r=this.pluginsMap_.monitors.reduce((r,s)=>null!=r?r:createMonitorBindingController(s,{document:e,params:i,target:t}),null);if(r)return r;throw new TpError({context:{key:t.key},type:"nomatchingcontroller"})}createBlade(e,t){let i=this.pluginsMap_.blades.reduce((i,r)=>null!=i?i:createBladeController(r,{document:e,params:t}),null);if(!i)throw new TpError({type:"nomatchingview",context:{params:t}});return i}createBladeApi(e){if(e instanceof InputBindingController)return new InputBindingApi(e);if(e instanceof MonitorBindingController)return new MonitorBindingApi(e);if(e instanceof RackController)return new RackApi(e,this);let t=this.pluginsMap_.blades.reduce((t,i)=>null!=t?t:i.api({controller:e,pool:this}),null);if(!t)throw TpError.shouldNeverHappen();return t}};function createDefaultPluginPool(){let e=new PluginPool;return[eu,ee,ei,er,q,j,Y,X,O,eo,ec,eh,c,d,p,g].forEach(t=>{e.register(t)}),e}function point2dFromUnknown(e){return Point2d.isObject(e)?new Point2d(e.x,e.y):new Point2d}function writePoint2d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y)}function createDimensionConstraint(e,t){if(!e)return;let i=[],r=createStepConstraint(e,t);r&&i.push(r);let s=createRangeConstraint(e);return s&&i.push(s),new CompositeConstraint(i)}function createConstraint(e,t){return new PointNdConstraint({assembly:$,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y)]})}function getSuitableMaxDimensionValue(e,t){let[i,r]=e?findNumberRange(e):[];if(!isEmpty(i)||!isEmpty(r))return Math.max(Math.abs(null!=i?i:0),Math.abs(null!=r?r:0));let s=getBaseStep(e);return Math.max(10*Math.abs(s),10*Math.abs(t))}function getSuitableMaxValue(e,t){let i=t instanceof PointNdConstraint?t.components[0]:void 0,r=t instanceof PointNdConstraint?t.components[1]:void 0,s=getSuitableMaxDimensionValue(i,e.x),a=getSuitableMaxDimensionValue(r,e.y);return Math.max(s,a)}function createAxis(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}function shouldInvertY(e){if(!("y"in e))return!1;let t=e.y;return!!t&&"inverted"in t&&!!t.inverted}let eu={id:"input-point2d",type:"input",accept:(e,t)=>{if(!Point2d.isObject(e))return null;let i=parseParams(t,{expanded:r.optional.boolean,picker:r.optional.custom(parsePickerLayout),x:r.optional.custom(parsePointDimensionParams),y:r.optional.object({inverted:r.optional.boolean,max:r.optional.number,min:r.optional.number,step:r.optional.number})});return i?{initialValue:e,params:i}:null},binding:{reader:e=>point2dFromUnknown,constraint:e=>createConstraint(e.params,e.initialValue),equals:Point2d.equals,writer:e=>writePoint2d},controller:e=>{let t=e.document,i=e.value,r=e.constraint;if(!(r instanceof PointNdConstraint))throw TpError.shouldNeverHappen();let s="expanded"in e.params?e.params.expanded:void 0,a="picker"in e.params?e.params.picker:void 0;return new Point2dController(t,{axes:[createAxis(i.rawValue.x,r.components[0]),createAxis(i.rawValue.y,r.components[1])],expanded:null!=s&&s,invertsY:shouldInvertY(e.params),maxValue:getSuitableMaxValue(i.rawValue,r),parser:parseNumber,pickerLayout:null!=a?a:"popup",value:i,viewProps:e.viewProps})}};let ListApi=class ListApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get options(){return this.controller_.valueController.props.get("options")}set options(e){this.controller_.valueController.props.set("options",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}};let SliderApi=class SliderApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get maxValue(){return this.controller_.valueController.sliderController.props.get("maxValue")}set maxValue(e){this.controller_.valueController.sliderController.props.set("maxValue",e)}get minValue(){return this.controller_.valueController.sliderController.props.get("minValue")}set minValue(e){this.controller_.valueController.sliderController.props.set("minValue",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}};let TextApi=class TextApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get formatter(){return this.controller_.valueController.props.get("formatter")}set formatter(e){this.controller_.valueController.props.set("formatter",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}};let ed={id:"list",type:"blade",accept(e){let t=parseParams(e,{options:r.required.custom(parseListOptions),value:r.required.raw,view:r.required.constant("list"),label:r.optional.string});return t?{params:t}:null},controller(e){let t=new ListConstraint(normalizeListOptions(e.params.options)),i=createValue(e.params.value,{constraint:t}),r=new ListController(e.document,{props:new ValueMap({options:t.values.value("options")}),value:i,viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:r})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof ListController?new ListApi(e.controller):null};function exportPresetJson(e){return e.reduce((e,t)=>Object.assign(e,{[t.presetKey]:t.read()}),{})}function importPresetJson(e,t){e.forEach(e=>{let i=t[e.target.presetKey];void 0!==i&&e.writer(e.target,e.reader(i))})}let RootApi=class RootApi extends FolderApi{constructor(e,t){super(e,t)}get element(){return this.controller_.view.element}importPreset(e){let t=this.controller_.rackController.rack.find(InputBindingController).map(e=>e.binding);importPresetJson(t,e),this.refresh()}exportPreset(){let e=this.controller_.rackController.rack.find(InputBindingController).map(e=>e.binding.target);return exportPresetJson(e)}refresh(){this.controller_.rackController.rack.find(InputBindingController).forEach(e=>{e.binding.read()}),this.controller_.rackController.rack.find(MonitorBindingController).forEach(e=>{e.binding.read()})}};let RootController=class RootController extends FolderController{constructor(e,t){super(e,{expanded:t.expanded,blade:t.blade,props:t.props,root:!0,viewProps:t.viewProps})}};let e_={id:"slider",type:"blade",accept(e){let t=parseParams(e,{max:r.required.number,min:r.required.number,view:r.required.constant("slider"),format:r.optional.function,label:r.optional.string,value:r.optional.number});return t?{params:t}:null},controller(e){var t,i;let r=null!==(t=e.params.value)&&void 0!==t?t:0,s=new DefiniteRangeConstraint({max:e.params.max,min:e.params.min}),a=new SliderTextController(e.document,{baseStep:1,parser:parseNumber,sliderProps:new ValueMap({maxValue:s.values.value("max"),minValue:s.values.value("min")}),textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(void 0,r),formatter:null!==(i=e.params.format)&&void 0!==i?i:numberToString}),value:createValue(r,{constraint:s}),viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:a})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof SliderTextController?new SliderApi(e.controller):null},ep={id:"text",type:"blade",accept(e){let t=parseParams(e,{parse:r.required.function,value:r.required.raw,view:r.required.constant("text"),format:r.optional.function,label:r.optional.string});return t?{params:t}:null},controller(e){var t;let i=new TextController(e.document,{parser:e.params.parse,props:ValueMap.fromObject({formatter:null!==(t=e.params.format)&&void 0!==t?t:e=>String(e)}),value:createValue(e.params.value),viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:i})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof TextController?new TextApi(e.controller):null};function createDefaultWrapperElement(e){let t=e.createElement("div");return t.classList.add(ClassName("dfw")()),e.body&&e.body.appendChild(t),t}function embedStyle(e,t,i){if(e.querySelector(`style[data-tp-style=${t}]`))return;let r=e.createElement("style");r.dataset.tpStyle=t,r.textContent=i,e.head.appendChild(r)}let Pane=class Pane extends RootApi{constructor(e){var t,i;let r=null!=e?e:{},s=null!==(t=r.document)&&void 0!==t?t:getWindowDocument(),a=createDefaultPluginPool(),n=new RootController(s,{expanded:r.expanded,blade:createBlade(),props:ValueMap.fromObject({title:r.title}),viewProps:ViewProps.create()});super(n,a),this.pool_=a,this.containerElem_=null!==(i=r.container)&&void 0!==i?i:createDefaultWrapperElement(s),this.containerElem_.appendChild(this.element),this.doc_=s,this.usesDefaultWrapper_=!r.container,this.setUpDefaultPlugins_()}get document(){if(!this.doc_)throw TpError.alreadyDisposed();return this.doc_}dispose(){let e=this.containerElem_;if(!e)throw TpError.alreadyDisposed();if(this.usesDefaultWrapper_){let t=e.parentElement;t&&t.removeChild(e)}this.containerElem_=null,this.doc_=null,super.dispose()}registerPlugin(e){let t="plugin"in e?[e.plugin]:"plugins"in e?e.plugins:[];t.forEach(e=>{this.pool_.register(e),this.embedPluginStyle_(e)})}embedPluginStyle_(e){e.css&&embedStyle(this.document,`plugin-${e.id}`,e.css)}setUpDefaultPlugins_(){embedStyle(this.document,"default",'.tp-tbiv_b,.tp-coltxtv_ms,.tp-ckbv_i,.tp-rotv_b,.tp-fldv_b,.tp-mllv_i,.tp-sglv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--elm-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--bld-us);line-height:var(--bld-us);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--bld-us);line-height:var(--bld-us);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-mllv_i,.tp-sglv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--mo-fg);height:var(--bld-us);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-mllv_i::-webkit-scrollbar,.tp-sglv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-mllv_i::-webkit-scrollbar-corner,.tp-sglv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-mllv_i::-webkit-scrollbar-thumb,.tp-sglv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-rotv{--font-family: var(--tp-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-br: var(--tp-base-border-radius, 6px);--cnt-h-p: var(--tp-container-horizontal-padding, 4px);--cnt-v-p: var(--tp-container-vertical-padding, 4px);--elm-br: var(--tp-element-border-radius, 2px);--bld-s: var(--tp-blade-spacing, 4px);--bld-us: var(--tp-blade-unit-size, 20px);--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tabv_c .tp-brkv>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-v-p))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tabv_c .tp-brkv>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--bld-s)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tabv_c .tp-brkv>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tabv_c .tp-brkv>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--elm-br);border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tabv_c .tp-brkv .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--elm-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);overflow:hidden;padding-left:var(--cnt-h-p);padding-right:calc(4px + var(--bld-us) + var(--cnt-h-p));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-h-p) + (var(--bld-us) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-v-p);padding-top:var(--cnt-v-p);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--elm-br);cursor:pointer;display:block;height:var(--bld-us);position:relative;width:var(--bld-us)}.tp-ckbv_w svg{bottom:0;display:block;height:16px;left:0;margin:auto;opacity:0;position:absolute;right:0;top:0;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--bld-us)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--bld-s);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--bld-s)}.tp-colpv_rgb{display:flex;margin-top:var(--bld-s);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-v-p);padding-top:calc(var(--cnt-v-p) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-h-p));position:absolute;right:calc(-1*var(--cnt-h-p));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--elm-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--bld-us)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--elm-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;pointer-events:none;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--elm-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;cursor:pointer;display:block;height:var(--bld-us);left:0;margin:0;outline:none;padding:0;position:absolute;top:0;width:var(--bld-us)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--elm-br);bottom:0;content:"";display:block;left:0;position:absolute;right:0;top:0}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--elm-br);color:var(--lbl-fg);cursor:pointer;height:var(--bld-us);line-height:var(--bld-us);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv.tp-fldv-not .tp-fldv_b{display:none}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--bld-us)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-h-p);padding-right:var(--cnt-h-p)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:160px}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding:0 4px}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--bld-us)*3);line-height:var(--bld-us);padding:0 4px;resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--bld-us);margin-right:4px;position:relative;width:var(--bld-us)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--bld-s);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-p2dpv{padding-left:calc(var(--bld-us) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:6px;box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:168px;padding:var(--cnt-v-p) var(--cnt-h-p);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--bld-us);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin:auto;position:absolute;right:0;top:0}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin-bottom:auto;margin-top:auto;position:absolute;right:0;top:0}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--elm-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--bld-us) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_c{padding-bottom:var(--cnt-v-p);padding-left:4px;padding-top:var(--cnt-v-p)}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-h-p) + 4px);padding-right:calc(var(--cnt-h-p) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);bottom:2px;content:"";left:0;pointer-events:none;position:absolute;right:0;top:0}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);opacity:.5;overflow:hidden;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-txtv{position:relative}.tp-txtv_i{padding:0 4px}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:-3px;position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--bld-us) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--elm-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--font-family);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--bld-us) + var(--cnt-h-p));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0}.tp-rotv.tp-rotv-not .tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}'),this.pool_.getAll().forEach(e=>{this.embedPluginStyle_(e)}),this.registerPlugin({plugins:[e_,ed,g,ep]})}};let ef=new Semver("3.1.10");e.BladeApi=BladeApi,e.ButtonApi=ButtonApi,e.FolderApi=FolderApi,e.InputBindingApi=InputBindingApi,e.ListApi=ListApi,e.MonitorBindingApi=MonitorBindingApi,e.Pane=Pane,e.SeparatorApi=SeparatorApi,e.SliderApi=SliderApi,e.TabApi=TabApi,e.TabPageApi=TabPageApi,e.TextApi=TextApi,e.TpChangeEvent=TpChangeEvent,e.VERSION=ef,Object.defineProperty(e,"__esModule",{value:!0})})(t)},4494:(e,t,i)=>{"use strict";let r,s,a;i.d(t,{YfP:()=>ArcRotateCamera,HEv:()=>math_color_Color4,Dso:()=>postProcess_PostProcess,xsS:()=>scene_Scene,xeF:()=>q,vGS:()=>ShaderStore,w1W:()=>tools_Tools,Pa4:()=>math_vector_Vector3,fWK:()=>webgpuEngine_WebGPUEngine});let AbstractScene=class AbstractScene{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,r){for(let s in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,s)&&this._BabylonFileParsers[s](e,t,i,r)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=(e=(e=(e=e.concat(this.meshes)).concat(this.lights)).concat(this.cameras)).concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}};AbstractScene._BabylonFileParsers={},AbstractScene._IndividualBabylonFileParsers={};let AbstractActionManager=class AbstractActionManager{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(let e in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(let e in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,e)){let t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(let t in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,t)){let i=parseInt(t);if(i===e)return!0}return!1}};AbstractActionManager.Triggers={};let EventState=class EventState{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}};let Observer=class Observer{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()}};let observable_Observable=class observable_Observable{static FromPromise(e,t){let i=new observable_Observable;return e.then(e=>{i.notifyObservers(e)}).catch(e=>{if(t)t.notifyObservers(e);else throw e}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=[],this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new EventState(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,s=!1){if(!e)return null;let a=new Observer(e,t,r);return a.unregisterOnNextCall=s,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(a,this._lastNotifiedValue),a._remove=()=>{this.remove(a)},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){if(!e)return!1;e._remove=null;let t=this._observers.indexOf(e);return -1!==t&&(this._deferUnregister(e),!0)}removeCallback(e,t){for(let i=0;i<this._observers.length;i++){let r=this._observers[i];if(!r._willBeUnregistered&&r.callback===e&&(!t||t===r.scope))return this._deferUnregister(r),!0}return!1}_deferUnregister(e){e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout(()=>{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;let i=this._observers.indexOf(e);return -1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;let a=this._eventState;for(let n of(a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.lastReturnValue=e,a.userInfo=s,this._observers))if(!n._willBeUnregistered&&(n.mask&t&&(n.unregisterOnNextCall&&this._deferUnregister(n),n.scope?a.lastReturnValue=n.callback.apply(n.scope,[e,a]):a.lastReturnValue=n.callback(e,a)),a.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;let r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){let 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(){let e=new observable_Observable;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(let t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}};let math_scalar_Scalar=class math_scalar_Scalar{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){let 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=math_scalar_Scalar.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){let i=math_scalar_Scalar.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let r=math_scalar_Scalar.Clamp(i);return t*(r=-2*r*r*r+3*r*r)+e*(1-r)}static MoveTowards(e,t,i){return Math.abs(t-e)<=i?t:e+math_scalar_Scalar.Sign(t-e)*i}static MoveTowardsAngle(e,t,i){let r=math_scalar_Scalar.DeltaAngle(e,t),s=0;return-i<r&&r<i?s=t:(t=e+r,s=math_scalar_Scalar.MoveTowards(e,t,i)),s}static Lerp(e,t,i){return e+(t-e)*i}static LerpAngle(e,t,i){let r=math_scalar_Scalar.Repeat(t-e,360);return r>180&&(r-=360),e+r*math_scalar_Scalar.Clamp(i)}static InverseLerp(e,t,i){return e!=t?math_scalar_Scalar.Clamp((i-e)/(t-e)):0}static Hermite(e,t,i,r,s){let a=s*s,n=s*a;return e*(2*n-3*a+1)+i*(-2*n+3*a)+t*(n-2*a+s)+r*(n-a)}static Hermite1stDerivative(e,t,i,r,s){let a=s*s;return(a-s)*6*e+(3*a-4*s+1)*t+(-a+s)*6*i+(3*a-2*s)*r}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-=math_scalar_Scalar.TwoPi*Math.floor((e+Math.PI)/math_scalar_Scalar.TwoPi)}static HCF(e,t){let i=e%t;return 0===i?t:math_scalar_Scalar.HCF(t,i)}};math_scalar_Scalar.TwoPi=2*Math.PI;let n=1/2.2,o=(1+Math.sqrt(5))/2;let arrayTools_ArrayTools=class arrayTools_ArrayTools{static BuildArray(e,t){let i=[];for(let r=0;r<e;++r)i.push(t());return i}static BuildTuple(e,t){return arrayTools_ArrayTools.BuildArray(e,t)}};function _observeArrayfunction(e,t,i){let r=e[t];if("function"!=typeof r)return null;let newFunction=function(){let r=e.length,s=newFunction.previous.apply(e,arguments);return i(t,r),s};return r.next=newFunction,newFunction.previous=r,e[t]=newFunction,()=>{let i=newFunction.previous;if(!i)return;let r=newFunction.next;r?(i.next=r,r.previous=i):(i.next=void 0,e[t]=i),newFunction.next=void 0,newFunction.previous=void 0}}let l=["push","splice","pop","shift","unshift"];function _ObserveArray(e,t){let i=l.map(i=>_observeArrayfunction(e,i,t));return()=>{i.forEach(e=>{null==e||e()})}}let h={};let performanceConfigurator_PerformanceConfigurator=class performanceConfigurator_PerformanceConfigurator{static SetMatrixPrecision(e){if(performanceConfigurator_PerformanceConfigurator.MatrixTrackPrecisionChange=!1,e&&!performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits&&performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices)for(let e=0;e<performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices.length;++e){let t=performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices[e],i=t._m;t._m=Array(16);for(let e=0;e<16;++e)t._m[e]=i[e]}performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits=e,performanceConfigurator_PerformanceConfigurator.MatrixCurrentType=performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits?Array:Float32Array,performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices=null}};performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits=!1,performanceConfigurator_PerformanceConfigurator.MatrixTrackPrecisionChange=!0,performanceConfigurator_PerformanceConfigurator.MatrixCurrentType=Float32Array,performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices=[];let engineStore_EngineStore=class engineStore_EngineStore{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}};engineStore_EngineStore.Instances=[],engineStore_EngineStore.OnEnginesDisposedObservable=new observable_Observable,engineStore_EngineStore._LastCreatedScene=null,engineStore_EngineStore.UseFallbackTexture=!0,engineStore_EngineStore.FallbackTexture="";let _ExtractAsInt=e=>parseInt(e.toString().replace(/\W/g,""));let math_vector_Vector2=class math_vector_Vector2{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=_ExtractAsInt(this.x),t=_ExtractAsInt(this.y);return 397*e^t}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return math_vector_Vector2.FromArrayToRef(e,t,this),this}asArray(){let e=[];return this.toArray(e,0),e}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}add(e){return new this.constructor(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new this.constructor(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.divideToRef(e,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){let t=new this.constructor(0,0);return this.scaleToRef(e,t),t}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=.001){return e&&math_scalar_Scalar.WithinEpsilon(this.x,e.x,t)&&math_scalar_Scalar.WithinEpsilon(this.y,e.y,t)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(e,t){let i=Math.cos(e),r=Math.sin(e),s=i*this.x-r*this.y,a=r*this.x+i*this.y;return t.x=s,t.y=a,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return math_vector_Vector2.NormalizeToRef(this,this),this}clone(){return new this.constructor(this.x,this.y)}static Zero(){return new math_vector_Vector2(0,0)}static One(){return new math_vector_Vector2(1,1)}static Random(e=0,t=1){return new math_vector_Vector2(math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t))}static get ZeroReadOnly(){return math_vector_Vector2._ZeroReadOnly}static FromArray(e,t=0){return new math_vector_Vector2(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static CatmullRom(e,t,i,r,s){let a=s*s,n=s*a,o=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-r.x)*a+(-e.x+3*t.x-3*i.x+r.x)*n),l=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-r.y)*a+(-e.y+3*t.y-3*i.y+r.y)*n);return new e.constructor(o,l)}static Clamp(e,t,i){let r=e.x;r=(r=r>i.x?i.x:r)<t.x?t.x:r;let s=e.y;return s=(s=s>i.y?i.y:s)<t.y?t.y:s,new e.constructor(r,s)}static Hermite(e,t,i,r,s){let a=s*s,n=s*a,o=2*n-3*a+1,l=-2*n+3*a,h=n-2*a+s,c=n-a,u=e.x*o+i.x*l+t.x*h+r.x*c,d=e.y*o+i.y*l+t.y*h+r.y*c;return new e.constructor(u,d)}static Hermite1stDerivative(e,t,i,r,s){let a=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let n=s*s;return a.x=(n-s)*6*e.x+(3*n-4*s+1)*t.x+(-n+s)*6*i.x+(3*n-2*s)*r.x,a.y=(n-s)*6*e.y+(3*n-4*s+1)*t.y+(-n+s)*6*i.y+(3*n-2*s)*r.y,a}static Lerp(e,t,i){let r=e.x+(t.x-e.x)*i,s=e.y+(t.y-e.y)*i;return new e.constructor(r,s)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){let t=new e.constructor;return this.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){let i=e.length();return 0===i||(t.x=e.x/i,t.y=e.y/i),t}static Minimize(e,t){let i=e.x<t.x?e.x:t.x,r=e.y<t.y?e.y:t.y;return new e.constructor(i,r)}static Maximize(e,t){let i=e.x>t.x?e.x:t.x,r=e.y>t.y?e.y:t.y;return new e.constructor(i,r)}static Transform(e,t){let i=new e.constructor;return math_vector_Vector2.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+r[12],a=e.x*r[1]+e.y*r[5]+r[13];return i.x=s,i.y=a,i}static PointInTriangle(e,t,i,r){let s=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),a=s<0?-1:1,n=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*a,o=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*a;return n>0&&o>0&&n+o<2*s*a}static Distance(e,t){return Math.sqrt(math_vector_Vector2.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y;return i*i+r*r}static Center(e,t){let i=new e.constructor;return math_vector_Vector2.CenterToRef(e,t,i)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){let r=math_vector_Vector2.DistanceSquared(t,i);if(0===r)return math_vector_Vector2.Distance(e,t);let s=i.subtract(t),a=Math.max(0,Math.min(1,math_vector_Vector2.Dot(e.subtract(t),s)/r)),n=t.add(s.multiplyByFloats(a,a));return math_vector_Vector2.Distance(e,n)}};math_vector_Vector2._ZeroReadOnly=math_vector_Vector2.Zero();let math_vector_Vector3=class math_vector_Vector3{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=_ExtractAsInt(this._x),t=_ExtractAsInt(this._y),i=_ExtractAsInt(this._z),r=e;return 397*(r=397*r^t)^i}asArray(){let e=[];return this.toArray(e,0),e}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return math_vector_Vector3.FromArrayToRef(e,t,this),this}toQuaternion(){return math_vector_Quaternion.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this.addInPlaceFromFloats(e._x,e._y,e._z)}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,r){return r.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new this.constructor(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){let t=this.length(),i=Math.acos(this.y/t),r=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;let s=t*Math.sin(i)*Math.cos(r),a=t*Math.cos(i),n=t*Math.sin(i)*Math.sin(r);return e.set(s,a,n),e}applyRotationQuaternionToRef(e,t){let i=this._x,r=this._y,s=this._z,a=e._x,n=e._y,o=e._z,l=e._w,h=2*(n*s-o*r),c=2*(o*i-a*s),u=2*(a*r-n*i);return t._x=i+l*h+n*u-o*c,t._y=r+l*c+o*h-a*u,t._z=s+l*u+a*c-n*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new this.constructor)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){let i=new this.constructor;return this.projectOnPlaneToRef(e,t,i),i}projectOnPlaneToRef(e,t,i){let r=e.normal,s=e.d,a=MathTmp.Vector3[0];this.subtractToRef(t,a),a.normalize();let n=math_vector_Vector3.Dot(a,r);if(1e-10>Math.abs(n))i.setAll(1/0);else{let e=-(math_vector_Vector3.Dot(t,r)+s)/n,o=a.scaleInPlace(e);t.addToRef(o,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=.001){return e&&math_scalar_Scalar.WithinEpsilon(this._x,e._x,t)&&math_scalar_Scalar.WithinEpsilon(this._y,e._y,t)&&math_scalar_Scalar.WithinEpsilon(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new this.constructor(this._x*e,this._y*t,this._z*i)}divide(e){return new this.constructor(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this.divideToRef(e,this)}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return e<this._x&&(this.x=e),t<this._y&&(this.y=t),i<this._z&&(this.z=i),this}maximizeInPlaceFromFloats(e,t,i){return e>this._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){let t=Math.abs(this._x),i=Math.abs(this._y);if(!math_scalar_Scalar.WithinEpsilon(t,i,e))return!0;let r=Math.abs(this._z);return!(math_scalar_Scalar.WithinEpsilon(t,r,e)&&math_scalar_Scalar.WithinEpsilon(i,r,e))}get isNonUniform(){let e=Math.abs(this._x),t=Math.abs(this._y);if(e!==t)return!0;let i=Math.abs(this._z);return e!==i}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){return"xyz"===(e=e.toLowerCase())||(MathTmp.Vector3[0].copyFrom(this),["x","y","z"].forEach((t,i)=>{this[t]=MathTmp.Vector3[0][e[i]]})),this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(MathTmp.Matrix[0]),math_vector_Vector3.TransformCoordinatesToRef(this,MathTmp.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,MathTmp.Vector3[0]),MathTmp.Vector3[0].rotateByQuaternionToRef(e,MathTmp.Vector3[0]),t.addToRef(MathTmp.Vector3[0],i),i}cross(e){let t=new this.constructor;return math_vector_Vector3.CrossToRef(this,e,t)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){let e=new this.constructor(0,0,0);return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,r){let s=math_vector_Vector3.Dot(e,i)-r,a=math_vector_Vector3.Dot(t,i)-r;return s/(s-a)}static GetAngleBetweenVectors(e,t,i){let r=e.normalizeToRef(MathTmp.Vector3[1]),s=t.normalizeToRef(MathTmp.Vector3[2]),a=math_vector_Vector3.Dot(r,s);a=math_scalar_Scalar.Clamp(a,-1,1);let n=Math.acos(a),o=MathTmp.Vector3[3];return(math_vector_Vector3.CrossToRef(r,s,o),math_vector_Vector3.Dot(o,i)>0)?isNaN(n)?0:n:isNaN(n)?-Math.PI:-Math.acos(a)}static GetAngleBetweenVectorsOnPlane(e,t,i){MathTmp.Vector3[0].copyFrom(e);let r=MathTmp.Vector3[0];MathTmp.Vector3[1].copyFrom(t);let s=MathTmp.Vector3[1];MathTmp.Vector3[2].copyFrom(i);let a=MathTmp.Vector3[2],n=MathTmp.Vector3[3],o=MathTmp.Vector3[4];r.normalize(),s.normalize(),a.normalize(),math_vector_Vector3.CrossToRef(a,r,n),math_vector_Vector3.CrossToRef(n,a,o);let l=Math.atan2(math_vector_Vector3.Dot(s,n),math_vector_Vector3.Dot(s,o));return math_scalar_Scalar.NormalizeRadians(l)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){let r=math_vector_TmpVectors.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(r.x**2+r.z**2),r.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){let i=math_vector_Vector3.Zero();return math_vector_Vector3.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,r){let s,a;i=math_scalar_Scalar.Clamp(i,0,1);let n=MathTmp.Vector3[0],o=MathTmp.Vector3[1];n.copyFrom(e);let l=n.length();n.normalizeFromLength(l),o.copyFrom(t);let h=o.length();o.normalizeFromLength(h);let c=math_vector_Vector3.Dot(n,o);if(c<.999){let e=Math.acos(c),t=1/Math.sin(e);s=Math.sin((1-i)*e)*t,a=Math.sin(i*e)*t}else s=1-i,a=i;return n.scaleInPlace(s),o.scaleInPlace(a),r.copyFrom(n).addInPlace(o),r.scaleInPlace(math_scalar_Scalar.Lerp(l,h,i)),r}static SmoothToRef(e,t,i,r,s){return math_vector_Vector3.SlerpToRef(e,t,0===r?1:i/r,s),s}static FromArray(e,t=0){return new math_vector_Vector3(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return math_vector_Vector3.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return math_vector_Vector3.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,r){return r.copyFromFloats(e,t,i),r}static Zero(){return new math_vector_Vector3(0,0,0)}static One(){return new math_vector_Vector3(1,1,1)}static Up(){return new math_vector_Vector3(0,1,0)}static get UpReadOnly(){return math_vector_Vector3._UpReadOnly}static get DownReadOnly(){return math_vector_Vector3._DownReadOnly}static get RightReadOnly(){return math_vector_Vector3._RightReadOnly}static get LeftReadOnly(){return math_vector_Vector3._LeftReadOnly}static get LeftHandedForwardReadOnly(){return math_vector_Vector3._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return math_vector_Vector3._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return math_vector_Vector3._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return math_vector_Vector3._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return math_vector_Vector3._ZeroReadOnly}static get OneReadOnly(){return math_vector_Vector3._OneReadOnly}static Down(){return new math_vector_Vector3(0,-1,0)}static Forward(e=!1){return new math_vector_Vector3(0,0,e?-1:1)}static Backward(e=!1){return new math_vector_Vector3(0,0,e?1:-1)}static Right(){return new math_vector_Vector3(1,0,0)}static Left(){return new math_vector_Vector3(-1,0,0)}static Random(e=0,t=1){return new math_vector_Vector3(math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t))}static TransformCoordinates(e,t){let i=math_vector_Vector3.Zero();return math_vector_Vector3.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let a=r.m,n=e*a[0]+t*a[4]+i*a[8]+a[12],o=e*a[1]+t*a[5]+i*a[9]+a[13],l=e*a[2]+t*a[6]+i*a[10]+a[14],h=1/(e*a[3]+t*a[7]+i*a[11]+a[15]);return s._x=n*h,s._y=o*h,s._z=l*h,s._isDirty=!0,s}static TransformNormal(e,t){let i=math_vector_Vector3.Zero();return math_vector_Vector3.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,r,s){let a=r.m;return s._x=e*a[0]+t*a[4]+i*a[8],s._y=e*a[1]+t*a[5]+i*a[9],s._z=e*a[2]+t*a[6]+i*a[10],s._isDirty=!0,s}static CatmullRom(e,t,i,r,s){let a=s*s,n=s*a,o=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-r._x)*a+(-e._x+3*t._x-3*i._x+r._x)*n),l=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-r._y)*a+(-e._y+3*t._y-3*i._y+r._y)*n),h=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-r._z)*a+(-e._z+3*t._z-3*i._z+r._z)*n);return new e.constructor(o,l,h)}static Clamp(e,t,i){let r=new e.constructor;return math_vector_Vector3.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){let s=e._x;s=(s=s>i._x?i._x:s)<t._x?t._x:s;let a=e._y;a=(a=a>i._y?i._y:a)<t._y?t._y:a;let n=e._z;return n=(n=n>i._z?i._z:n)<t._z?t._z:n,r.copyFromFloats(s,a,n),r}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static Hermite(e,t,i,r,s){let a=s*s,n=s*a,o=2*n-3*a+1,l=-2*n+3*a,h=n-2*a+s,c=n-a,u=e._x*o+i._x*l+t._x*h+r._x*c,d=e._y*o+i._y*l+t._y*h+r._y*c,_=e._z*o+i._z*l+t._z*h+r._z*c;return new e.constructor(u,d,_)}static Hermite1stDerivative(e,t,i,r,s){let a=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let n=s*s;return a._x=(n-s)*6*e._x+(3*n-4*s+1)*t._x+(-n+s)*6*i._x+(3*n-2*s)*r._x,a._y=(n-s)*6*e._y+(3*n-4*s+1)*t._y+(-n+s)*6*i._y+(3*n-2*s)*r._y,a._z=(n-s)*6*e._z+(3*n-4*s+1)*t._z+(-n+s)*6*i._z+(3*n-2*s)*r._z,a._isDirty=!0,a}static Lerp(e,t,i){let r=new e.constructor(0,0,0);return math_vector_Vector3.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){return r._x=e._x+(t._x-e._x)*i,r._y=e._y+(t._y-e._y)*i,r._z=e._z+(t._z-e._z)*i,r._isDirty=!0,r}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z}static Cross(e,t){let i=new e.constructor;return math_vector_Vector3.CrossToRef(e,t,i),i}static CrossToRef(e,t,i){let r=e._y*t._z-e._z*t._y,s=e._z*t._x-e._x*t._z,a=e._x*t._y-e._y*t._x;return i.copyFromFloats(r,s,a),i}static Normalize(e){let t=math_vector_Vector3.Zero();return math_vector_Vector3.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Project(e,t,i,r){let s=new e.constructor;return math_vector_Vector3.ProjectToRef(e,t,i,r,s),s}static ProjectToRef(e,t,i,r,s){let a=r.width,n=r.height,o=r.x,l=r.y,h=MathTmp.Matrix[1];math_vector_Matrix.FromValuesToRef(a/2,0,0,0,0,-n/2,0,0,0,0,.5,0,o+a/2,n/2+l,.5,1,h);let c=MathTmp.Matrix[0];return t.multiplyToRef(i,c),c.multiplyToRef(h,c),math_vector_Vector3.TransformCoordinatesToRef(e,c,s),s}static Reflect(e,t){return this.ReflectToRef(e,t,new math_vector_Vector3)}static ReflectToRef(e,t,i){let r=math_vector_TmpVectors.Vector3[0];return r.copyFrom(t).scaleInPlace(2*math_vector_Vector3.Dot(e,t)),i.copyFrom(e).subtractInPlace(r)}static _UnprojectFromInvertedMatrixToRef(e,t,i){math_vector_Vector3.TransformCoordinatesToRef(e,t,i);let r=t.m,s=e._x*r[3]+e._y*r[7]+e._z*r[11]+r[15];return math_scalar_Scalar.WithinEpsilon(s,1)&&i.scaleInPlace(1/s),i}static UnprojectFromTransform(e,t,i,r,s){return this.Unproject(e,t,i,r,s,math_vector_Matrix.IdentityReadOnly)}static Unproject(e,t,i,r,s,a){let n=new e.constructor;return math_vector_Vector3.UnprojectToRef(e,t,i,r,s,a,n),n}static UnprojectToRef(e,t,i,r,s,a,n){return math_vector_Vector3.UnprojectFloatsToRef(e._x,e._y,e._z,t,i,r,s,a,n),n}static UnprojectFloatsToRef(e,t,i,r,s,a,n,o,l){var h;let c=MathTmp.Matrix[0];a.multiplyToRef(n,c),c.multiplyToRef(o,c),c.invert();let u=MathTmp.Vector3[0];return u.x=e/r*2-1,u.y=-(t/s*2-1),(null===(h=engineStore_EngineStore.LastCreatedEngine)||void 0===h?void 0:h.isNDCHalfZRange)?u.z=i:u.z=2*i-1,math_vector_Vector3._UnprojectFromInvertedMatrixToRef(u,c,l),l}static Minimize(e,t){let i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){let i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(math_vector_Vector3.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e._x-t._x,r=e._y-t._y,s=e._z-t._z;return i*i+r*r+s*s}static ProjectOnTriangleToRef(e,t,i,r,s){let a,n,o;let l=MathTmp.Vector3[0],h=MathTmp.Vector3[1],c=MathTmp.Vector3[2],u=MathTmp.Vector3[3],d=MathTmp.Vector3[4];i.subtractToRef(t,l),r.subtractToRef(t,h),r.subtractToRef(i,c);let _=l.length(),p=h.length(),f=c.length();if(_<.001||p<.001||f<.001)return s.copyFrom(t),math_vector_Vector3.Distance(e,t);e.subtractToRef(t,d),math_vector_Vector3.CrossToRef(l,h,u);let m=u.length();if(m<.001)return s.copyFrom(t),math_vector_Vector3.Distance(e,t);u.normalizeFromLength(m);let g=d.length();if(g<.001)return s.copyFrom(t),0;d.normalizeFromLength(g);let v=math_vector_Vector3.Dot(u,d),x=MathTmp.Vector3[5],b=MathTmp.Vector3[6];x.copyFrom(u).scaleInPlace(-g*v),b.copyFrom(e).addInPlace(x);let T=MathTmp.Vector3[4],S=MathTmp.Vector3[5],C=MathTmp.Vector3[7],E=MathTmp.Vector3[8];T.copyFrom(l).scaleInPlace(1/_),E.copyFrom(h).scaleInPlace(1/p),T.addInPlace(E).scaleInPlace(-1),S.copyFrom(l).scaleInPlace(-1/_),E.copyFrom(c).scaleInPlace(1/f),S.addInPlace(E).scaleInPlace(-1),C.copyFrom(c).scaleInPlace(-1/f),E.copyFrom(h).scaleInPlace(-1/p),C.addInPlace(E).scaleInPlace(-1);let y=MathTmp.Vector3[9];y.copyFrom(b).subtractInPlace(t),math_vector_Vector3.CrossToRef(T,y,E),a=math_vector_Vector3.Dot(E,u);let R=a;y.copyFrom(b).subtractInPlace(i),math_vector_Vector3.CrossToRef(S,y,E),a=math_vector_Vector3.Dot(E,u);let P=a;y.copyFrom(b).subtractInPlace(r),math_vector_Vector3.CrossToRef(C,y,E),a=math_vector_Vector3.Dot(E,u);let A=a,M=MathTmp.Vector3[10];R>0&&P<0?(M.copyFrom(l),n=t,o=i):P>0&&A<0?(M.copyFrom(c),n=i,o=r):(M.copyFrom(h).scaleInPlace(-1),n=r,o=t);let I=MathTmp.Vector3[9],D=MathTmp.Vector3[4];n.subtractToRef(b,E),o.subtractToRef(b,I),math_vector_Vector3.CrossToRef(E,I,D);let O=0>math_vector_Vector3.Dot(D,u);if(!O)return s.copyFrom(b),Math.abs(g*v);let B=MathTmp.Vector3[5];math_vector_Vector3.CrossToRef(M,D,B),B.normalize();let N=MathTmp.Vector3[9];N.copyFrom(n).subtractInPlace(b);let F=N.length();if(F<.001)return s.copyFrom(n),math_vector_Vector3.Distance(e,n);N.normalizeFromLength(F);let w=math_vector_Vector3.Dot(B,N),L=MathTmp.Vector3[7];L.copyFrom(b).addInPlace(B.scaleInPlace(F*w)),E.copyFrom(L).subtractInPlace(n),g=M.length(),M.normalizeFromLength(g);let V=math_vector_Vector3.Dot(E,M)/Math.max(g,.001);return V=math_scalar_Scalar.Clamp(V,0,1),L.copyFrom(n).addInPlace(M.scaleInPlace(V*g)),s.copyFrom(L),math_vector_Vector3.Distance(e,L)}static Center(e,t){return math_vector_Vector3.CenterToRef(e,t,math_vector_Vector3.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)}static RotationFromAxis(e,t,i){let r=new e.constructor;return math_vector_Vector3.RotationFromAxisToRef(e,t,i,r),r}static RotationFromAxisToRef(e,t,i,r){let s=MathTmp.Quaternion[0];return math_vector_Quaternion.RotationQuaternionFromAxisToRef(e,t,i,s),s.toEulerAnglesToRef(r),r}};math_vector_Vector3._UpReadOnly=math_vector_Vector3.Up(),math_vector_Vector3._DownReadOnly=math_vector_Vector3.Down(),math_vector_Vector3._LeftHandedForwardReadOnly=math_vector_Vector3.Forward(!1),math_vector_Vector3._RightHandedForwardReadOnly=math_vector_Vector3.Forward(!0),math_vector_Vector3._LeftHandedBackwardReadOnly=math_vector_Vector3.Backward(!1),math_vector_Vector3._RightHandedBackwardReadOnly=math_vector_Vector3.Backward(!0),math_vector_Vector3._RightReadOnly=math_vector_Vector3.Right(),math_vector_Vector3._LeftReadOnly=math_vector_Vector3.Left(),math_vector_Vector3._ZeroReadOnly=math_vector_Vector3.Zero(),math_vector_Vector3._OneReadOnly=math_vector_Vector3.One();let math_vector_Vector4=class math_vector_Vector4{constructor(e=0,t=0,i=0,r=0){this.x=e,this.y=t,this.z=i,this.w=r}toString(){return`{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`}getClassName(){return"Vector4"}getHashCode(){let e=_ExtractAsInt(this.x),t=_ExtractAsInt(this.y),i=_ExtractAsInt(this.z),r=_ExtractAsInt(this.w),s=e;return 397*(s=397*(s=397*s^t)^i)^r}asArray(){let e=[];return this.toArray(e,0),e}toArray(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,this}fromArray(e,t=0){return math_vector_Vector4.FromArrayToRef(e,t,this),this}addInPlace(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}add(e){return new this.constructor(this.x+e.x,this.y+e.y,this.z+e.z,this.w+e.w)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,t.w=this.w+e.w,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subtract(e){return new this.constructor(this.x-e.x,this.y-e.y,this.z-e.z,this.w-e.w)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,t.w=this.w-e.w,t}subtractFromFloats(e,t,i,r){return new this.constructor(this.x-e,this.y-t,this.z-i,this.w-r)}subtractFromFloatsToRef(e,t,i,r,s){return s.x=this.x-e,s.y=this.y-t,s.z=this.z-i,s.w=this.w-r,s}negate(){return new this.constructor(-this.x,-this.y,-this.z,-this.w)}negateInPlace(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this}negateToRef(e){return e.copyFromFloats(-1*this.x,-1*this.y,-1*this.z,-1*this.w)}scaleInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}scale(e){return new this.constructor(this.x*e,this.y*e,this.z*e,this.w*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w}equalsWithEpsilon(e,t=.001){return e&&math_scalar_Scalar.WithinEpsilon(this.x,e.x,t)&&math_scalar_Scalar.WithinEpsilon(this.y,e.y,t)&&math_scalar_Scalar.WithinEpsilon(this.z,e.z,t)&&math_scalar_Scalar.WithinEpsilon(this.w,e.w,t)}equalsToFloats(e,t,i,r){return this.x===e&&this.y===t&&this.z===i&&this.w===r}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiply(e){return new this.constructor(this.x*e.x,this.y*e.y,this.z*e.z,this.w*e.w)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,t.w=this.w*e.w,t}multiplyByFloats(e,t,i,r){return new this.constructor(this.x*e,this.y*t,this.z*i,this.w*r)}divide(e){return new this.constructor(this.x/e.x,this.y/e.y,this.z/e.z,this.w/e.w)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,t.w=this.w/e.w,t}divideInPlace(e){return this.divideToRef(e,this)}minimizeInPlace(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this}maximizeInPlace(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){let e=this.length();return 0===e?this:this.scaleInPlace(1/e)}toVector3(){return new math_vector_Vector3(this.x,this.y,this.z)}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.x=this.y=this.z=this.w=e,this}static FromArray(e,t){return t||(t=0),new math_vector_Vector4(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return math_vector_Vector4.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,r,s){return s.x=e,s.y=t,s.z=i,s.w=r,s}static Zero(){return new math_vector_Vector4(0,0,0,0)}static One(){return new math_vector_Vector4(1,1,1,1)}static Random(e=0,t=1){return new math_vector_Vector4(math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t))}static get ZeroReadOnly(){return math_vector_Vector4._ZeroReadOnly}static Normalize(e){let t=math_vector_Vector4.Zero();return math_vector_Vector4.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return t.copyFrom(e),t.normalize(),t}static Minimize(e,t){let i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){let i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(math_vector_Vector4.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+r*r+s*s+a*a}static Center(e,t){return math_vector_Vector4.CenterToRef(e,t,math_vector_Vector4.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}static TransformCoordinates(e,t){let i=math_vector_Vector4.Zero();return math_vector_Vector4.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return math_vector_Vector4.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let a=r.m,n=e*a[0]+t*a[4]+i*a[8]+a[12],o=e*a[1]+t*a[5]+i*a[9]+a[13],l=e*a[2]+t*a[6]+i*a[10]+a[14],h=e*a[3]+t*a[7]+i*a[11]+a[15];return s.x=n,s.y=o,s.z=l,s.w=h,s}static TransformNormal(e,t){let i=new e.constructor;return math_vector_Vector4.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+e.z*r[8],a=e.x*r[1]+e.y*r[5]+e.z*r[9],n=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=s,i.y=a,i.z=n,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,r,s,a){let n=s.m;return a.x=e*n[0]+t*n[4]+i*n[8],a.y=e*n[1]+t*n[5]+i*n[9],a.z=e*n[2]+t*n[6]+i*n[10],a.w=r,a}static FromVector3(e,t=0){return new math_vector_Vector4(e._x,e._y,e._z,t)}};math_vector_Vector4._ZeroReadOnly=math_vector_Vector4.Zero();let math_vector_Quaternion=class math_vector_Quaternion{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,r=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=_ExtractAsInt(this._x),t=_ExtractAsInt(this._y),i=_ExtractAsInt(this._z),r=_ExtractAsInt(this._w),s=e;return 397*(s=397*(s=397*s^t)^i)^r}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=.001){return e&&math_scalar_Scalar.WithinEpsilon(this._x,e._x,t)&&math_scalar_Scalar.WithinEpsilon(this._y,e._y,t)&&math_scalar_Scalar.WithinEpsilon(this._z,e._z,t)&&math_scalar_Scalar.WithinEpsilon(this._w,e._w,t)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}subtract(e){return new this.constructor(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){let t=new this.constructor(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){let i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,a=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,r,s,a),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){let e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();let e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){let e=this.length();return 0===e||this.scaleInPlace(1/e),this}normalizeToNew(){let e=this.length();return 0===e?this.clone():this.scale(1/e)}toEulerAngles(){let e=math_vector_Vector3.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){let t=this._z,i=this._x,r=this._y,s=this._w,a=r*t-i*s;if(a<-.4999999)e._y=2*Math.atan2(r,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(a>.4999999)e._y=2*Math.atan2(r,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{let n=s*s,o=t*t,l=i*i,h=r*r;e._z=Math.atan2(2*(i*r+t*s),-o-l+h+n),e._x=Math.asin(-2*a),e._y=Math.atan2(2*(t*i+r*s),o-l-h+n),e._isDirty=!0}return e}toRotationMatrix(e){return math_vector_Matrix.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return math_vector_Quaternion.FromRotationMatrixToRef(e,this),this}static FromRotationMatrix(e){let t=new math_vector_Quaternion;return math_vector_Quaternion.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){let i;let r=e.m,s=r[0],a=r[4],n=r[8],o=r[1],l=r[5],h=r[9],c=r[2],u=r[6],d=r[10],_=s+l+d;return _>0?(i=.5/Math.sqrt(_+1),t._w=.25/i,t._x=(u-h)*i,t._y=(n-c)*i,t._z=(o-a)*i):s>l&&s>d?(i=2*Math.sqrt(1+s-l-d),t._w=(u-h)/i,t._x=.25*i,t._y=(a+o)/i,t._z=(n+c)/i):l>d?(i=2*Math.sqrt(1+l-s-d),t._w=(n-c)/i,t._x=(a+o)/i,t._y=.25*i,t._z=(h+u)/i):(i=2*Math.sqrt(1+d-s-l),t._w=(o-a)/i,t._x=(n+c)/i,t._y=(h+u)/i,t._z=.25*i),t._isDirty=!0,t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){let r=math_vector_Quaternion.Dot(e,t);return 1-r*r<=i}static SmoothToRef(e,t,i,r,s){let a=0===r?1:i/r;return a=math_scalar_Scalar.Clamp(a,0,1),math_vector_Quaternion.SlerpToRef(e,t,a,s),s}static Zero(){return new math_vector_Quaternion(0,0,0,0)}static Inverse(e){return new e.constructor(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new math_vector_Quaternion(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return math_vector_Quaternion.RotationAxisToRef(e,t,new math_vector_Quaternion)}static RotationAxisToRef(e,t,i){let r=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new math_vector_Quaternion(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromEulerAngles(e,t,i){let r=new math_vector_Quaternion;return math_vector_Quaternion.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerAnglesToRef(e,t,i,r){return math_vector_Quaternion.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerVector(e){let t=new math_vector_Quaternion;return math_vector_Quaternion.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return math_vector_Quaternion.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,r=.001){let s=math_vector_Vector3.Dot(e,t)+1;return s<r?Math.abs(e.x)>Math.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(math_vector_Vector3.CrossToRef(e,t,math_vector_TmpVectors.Vector3[0]),i.set(math_vector_TmpVectors.Vector3[0].x,math_vector_TmpVectors.Vector3[0].y,math_vector_TmpVectors.Vector3[0].z,s)),i.normalize()}static RotationYawPitchRoll(e,t,i){let r=new math_vector_Quaternion;return math_vector_Quaternion.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){let s=.5*i,a=.5*t,n=.5*e,o=Math.sin(s),l=Math.cos(s),h=Math.sin(a),c=Math.cos(a),u=Math.sin(n),d=Math.cos(n);return r._x=d*h*l+u*c*o,r._y=u*c*l-d*h*o,r._z=d*c*o-u*h*l,r._w=d*c*l+u*h*o,r._isDirty=!0,r}static RotationAlphaBetaGamma(e,t,i){let r=new math_vector_Quaternion;return math_vector_Quaternion.RotationAlphaBetaGammaToRef(e,t,i,r),r}static RotationAlphaBetaGammaToRef(e,t,i,r){let s=(i+e)*.5,a=(i-e)*.5,n=.5*t;return r._x=Math.cos(a)*Math.sin(n),r._y=Math.sin(a)*Math.sin(n),r._z=Math.sin(s)*Math.cos(n),r._w=Math.cos(s)*Math.cos(n),r._isDirty=!0,r}static RotationQuaternionFromAxis(e,t,i){let r=new math_vector_Quaternion(0,0,0,0);return math_vector_Quaternion.RotationQuaternionFromAxisToRef(e,t,i,r),r}static RotationQuaternionFromAxisToRef(e,t,i,r){let s=MathTmp.Matrix[0];return math_vector_Matrix.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),s),math_vector_Quaternion.FromRotationMatrixToRef(s,r),r}static FromLookDirectionLH(e,t){let i=new math_vector_Quaternion;return math_vector_Quaternion.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){let r=MathTmp.Matrix[0];return math_vector_Matrix.LookDirectionLHToRef(e,t,r),math_vector_Quaternion.FromRotationMatrixToRef(r,i),i}static FromLookDirectionRH(e,t){let i=new math_vector_Quaternion;return math_vector_Quaternion.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){let r=MathTmp.Matrix[0];return math_vector_Matrix.LookDirectionRHToRef(e,t,r),math_vector_Quaternion.FromRotationMatrixToRef(r,i)}static Slerp(e,t,i){let r=math_vector_Quaternion.Identity();return math_vector_Quaternion.SlerpToRef(e,t,i,r),r}static SlerpToRef(e,t,i,r){let s,a;let n=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,o=!1;if(n<0&&(o=!0,n=-n),n>.999999)a=1-i,s=o?-i:i;else{let e=Math.acos(n),t=1/Math.sin(e);a=Math.sin((1-i)*e)*t,s=o?-Math.sin(i*e)*t:Math.sin(i*e)*t}return r._x=a*e._x+s*t._x,r._y=a*e._y+s*t._y,r._z=a*e._z+s*t._z,r._w=a*e._w+s*t._w,r._isDirty=!0,r}static Hermite(e,t,i,r,s){let a=s*s,n=s*a,o=2*n-3*a+1,l=-2*n+3*a,h=n-2*a+s,c=n-a,u=e._x*o+i._x*l+t._x*h+r._x*c,d=e._y*o+i._y*l+t._y*h+r._y*c,_=e._z*o+i._z*l+t._z*h+r._z*c,p=e._w*o+i._w*l+t._w*h+r._w*c;return new e.constructor(u,d,_,p)}static Hermite1stDerivative(e,t,i,r,s){let a=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let n=s*s;return a._x=(n-s)*6*e._x+(3*n-4*s+1)*t._x+(-n+s)*6*i._x+(3*n-2*s)*r._x,a._y=(n-s)*6*e._y+(3*n-4*s+1)*t._y+(-n+s)*6*i._y+(3*n-2*s)*r._y,a._z=(n-s)*6*e._z+(3*n-4*s+1)*t._z+(-n+s)*6*i._z+(3*n-2*s)*r._z,a._w=(n-s)*6*e._w+(3*n-4*s+1)*t._w+(-n+s)*6*i._w+(3*n-2*s)*r._w,a._isDirty=!0,a}};let math_vector_Matrix=class math_vector_Matrix{static get Use64Bits(){return performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=math_vector_Matrix._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,r=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&r}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,performanceConfigurator_PerformanceConfigurator.MatrixTrackPrecisionChange&&performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices.push(this),this._m=new performanceConfigurator_PerformanceConfigurator.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;let e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]?this._isIdentity3x2=!1:0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;let e=this._m,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],n=e[5],o=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],_=e[12],p=e[13],f=e[14],m=e[15],g=u*m-f*d,v=c*m-p*d,x=c*f-p*u,b=h*m-_*d,T=h*f-u*_,S=h*p-_*c;return t*+(n*g-o*v+l*x)+-(i*(a*g-o*b+l*T))+r*+(a*v-n*b+l*S)+-(s*(a*x-n*T+o*S))}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} +${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]} +${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]} +${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return math_vector_Matrix.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){let t=new this.constructor;return this.addToRef(e,t),t}addToRef(e,t){let i=this._m,r=t._m,s=e.m;for(let e=0;e<16;e++)r[e]=i[e]+s[e];return t.markAsUpdated(),t}addToSelf(e){let t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}invertToRef(e){if(!0===this._isIdentity)return math_vector_Matrix.IdentityToRef(e),e;let t=this._m,i=t[0],r=t[1],s=t[2],a=t[3],n=t[4],o=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],_=t[11],p=t[12],f=t[13],m=t[14],g=t[15],v=d*g-m*_,x=u*g-f*_,b=u*m-f*d,T=c*g-p*_,S=c*m-d*p,C=c*f-p*u,E=+(o*v-l*x+h*b),y=-(n*v-l*T+h*S),R=+(n*x-o*T+h*C),P=-(n*b-o*S+l*C),A=i*E+r*y+s*R+a*P;if(0===A)return e.copyFrom(this),e;let M=1/A,I=l*g-m*h,D=o*g-f*h,O=o*m-f*l,B=n*g-p*h,N=n*m-p*l,F=n*f-p*o,w=l*_-d*h,L=o*_-u*h,V=o*d-u*l,U=n*_-c*h,k=n*d-c*l,G=n*u-c*o;return math_vector_Matrix.FromValuesToRef(E*M,-(r*v-s*x+a*b)*M,+(r*I-s*D+a*O)*M,-(r*w-s*L+a*V)*M,y*M,+(i*v-s*T+a*S)*M,-(i*I-s*B+a*N)*M,+(i*w-s*U+a*k)*M,R*M,-(i*x-r*T+a*C)*M,+(i*D-r*B+a*F)*M,-(i*L-r*U+a*G)*M,P*M,+(i*b-r*S+s*C)*M,-(i*O-r*N+s*F)*M,+(i*V-r*k+s*G)*M,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new math_vector_Vector3(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){let e=this.m;return math_vector_Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),this}multiply(e){let t=new this.constructor;return this.multiplyToRef(e,t),t}copyFrom(e){return e.copyToArray(this._m),this.updateFlag=e.updateFlag,this._updateIdentityStatus(e._isIdentity,e._isIdentityDirty,e._isIdentity3x2,e._isIdentity3x2Dirty),this}copyToArray(e,t=0){let i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiplyToRef(e,t){return this._isIdentity?t.copyFrom(e):e._isIdentity?t.copyFrom(this):(this.multiplyToArray(e,t._m,0),t.markAsUpdated()),t}multiplyToArray(e,t,i){let r=this._m,s=e.m,a=r[0],n=r[1],o=r[2],l=r[3],h=r[4],c=r[5],u=r[6],d=r[7],_=r[8],p=r[9],f=r[10],m=r[11],g=r[12],v=r[13],x=r[14],b=r[15],T=s[0],S=s[1],C=s[2],E=s[3],y=s[4],R=s[5],P=s[6],A=s[7],M=s[8],I=s[9],D=s[10],O=s[11],B=s[12],N=s[13],F=s[14],w=s[15];return t[i]=a*T+n*y+o*M+l*B,t[i+1]=a*S+n*R+o*I+l*N,t[i+2]=a*C+n*P+o*D+l*F,t[i+3]=a*E+n*A+o*O+l*w,t[i+4]=h*T+c*y+u*M+d*B,t[i+5]=h*S+c*R+u*I+d*N,t[i+6]=h*C+c*P+u*D+d*F,t[i+7]=h*E+c*A+u*O+d*w,t[i+8]=_*T+p*y+f*M+m*B,t[i+9]=_*S+p*R+f*I+m*N,t[i+10]=_*C+p*P+f*D+m*F,t[i+11]=_*E+p*A+f*O+m*w,t[i+12]=g*T+v*y+x*M+b*B,t[i+13]=g*S+v*R+x*I+b*N,t[i+14]=g*C+v*P+x*D+b*F,t[i+15]=g*E+v*A+x*O+b*w,this}equals(e){if(!e)return!1;if((this._isIdentity||e._isIdentity)&&!this._isIdentityDirty&&!e._isIdentityDirty)return this._isIdentity&&e._isIdentity;let t=this.m,i=e.m;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]}clone(){let e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=_ExtractAsInt(this._m[0]);for(let t=1;t<16;t++)e=397*e^_ExtractAsInt(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new math_vector_Quaternion,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,r){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;let s=this._m;if(i&&i.copyFromFloats(s[12],s[13],s[14]),(e=e||MathTmp.Vector3[0]).x=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]),e.y=Math.sqrt(s[4]*s[4]+s[5]*s[5]+s[6]*s[6]),e.z=Math.sqrt(s[8]*s[8]+s[9]*s[9]+s[10]*s[10]),r){let t=r.absoluteScaling.x<0?-1:1,i=r.absoluteScaling.y<0?-1:1,s=r.absoluteScaling.z<0?-1:1;e.x*=t,e.y*=i,e.z*=s}else 0>=this.determinant()&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){let i=1/e._x,r=1/e._y,a=1/e._z;math_vector_Matrix.FromValuesToRef(s[0]*i,s[1]*i,s[2]*i,0,s[4]*r,s[5]*r,s[6]*r,0,s[8]*a,s[9]*a,s[10]*a,0,0,0,0,1,MathTmp.Matrix[0]),math_vector_Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;let t=4*e;return new math_vector_Vector4(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<3){let i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){let e=new this.constructor;return math_vector_Matrix.TransposeToRef(this,e),e}transposeToRef(e){return math_vector_Matrix.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,r,s){if(e<0||e>3)return this;let a=4*e;return this._m[a+0]=t,this._m[a+1]=i,this._m[a+2]=r,this._m[a+3]=s,this.markAsUpdated(),this}scale(e){let t=new this.constructor;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}toNormalMatrix(e){let t=MathTmp.Matrix[0];this.invertToRef(t),t.transposeToRef(e);let i=e._m;return math_vector_Matrix.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){let e=new this.constructor;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){let t=MathTmp.Vector3[0];if(!this.decompose(t))return math_vector_Matrix.IdentityToRef(e),e;let i=this._m,r=1/t._x,s=1/t._y,a=1/t._z;return math_vector_Matrix.FromValuesToRef(i[0]*r,i[1]*r,i[2]*r,0,i[4]*s,i[5]*s,i[6]*s,0,i[8]*a,i[9]*a,i[10]*a,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){let e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){let e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){let i=new math_vector_Matrix;return math_vector_Matrix.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,r){for(let s=0;s<16;s++)r._m[s]=e[s+t]*i;return r.markAsUpdated(),r}static get IdentityReadOnly(){return math_vector_Matrix._IdentityReadOnly}static FromValuesToRef(e,t,i,r,s,a,n,o,l,h,c,u,d,_,p,f,m){let g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=s,g[5]=a,g[6]=n,g[7]=o,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated()}static FromValues(e,t,i,r,s,a,n,o,l,h,c,u,d,_,p,f){let m=new math_vector_Matrix,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=s,g[5]=a,g[6]=n,g[7]=o,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated(),m}static Compose(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.ComposeToRef(e,t,i,r),r}static ComposeToRef(e,t,i,r){let s=r._m,a=t._x,n=t._y,o=t._z,l=t._w,h=a+a,c=n+n,u=o+o,d=a*h,_=a*c,p=a*u,f=n*c,m=n*u,g=o*u,v=l*h,x=l*c,b=l*u,T=e._x,S=e._y,C=e._z;return s[0]=(1-(f+g))*T,s[1]=(_+b)*T,s[2]=(p-x)*T,s[3]=0,s[4]=(_-b)*S,s[5]=(1-(d+g))*S,s[6]=(m+v)*S,s[7]=0,s[8]=(p+x)*C,s[9]=(m-v)*C,s[10]=(1-(d+f))*C,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,r.markAsUpdated(),r}static Identity(){let e=math_vector_Matrix.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return math_vector_Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){let e=math_vector_Matrix.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){let t=new math_vector_Matrix;return math_vector_Matrix.RotationXToRef(e,t),t}static Invert(e){let t=new e.constructor;return e.invertToRef(t),t}static RotationXToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return math_vector_Matrix.FromValuesToRef(1,0,0,0,0,r,i,0,0,-i,r,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationY(e){let t=new math_vector_Matrix;return math_vector_Matrix.RotationYToRef(e,t),t}static RotationYToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return math_vector_Matrix.FromValuesToRef(r,0,-i,0,0,1,0,0,i,0,r,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationZ(e){let t=new math_vector_Matrix;return math_vector_Matrix.RotationZToRef(e,t),t}static RotationZToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return math_vector_Matrix.FromValuesToRef(r,i,0,0,-i,r,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationAxis(e,t){let i=new math_vector_Matrix;return math_vector_Matrix.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){let r=Math.sin(-t),s=Math.cos(-t),a=1-s;e.normalize();let n=i._m;return n[0]=e._x*e._x*a+s,n[1]=e._x*e._y*a-e._z*r,n[2]=e._x*e._z*a+e._y*r,n[3]=0,n[4]=e._y*e._x*a+e._z*r,n[5]=e._y*e._y*a+s,n[6]=e._y*e._z*a-e._x*r,n[7]=0,n[8]=e._z*e._x*a-e._y*r,n[9]=e._z*e._y*a+e._x*r,n[10]=e._z*e._z*a+s,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,r=!1){let s=math_vector_Vector3.Dot(t,e),a=i._m;if(s<-.999)a[0]=-1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=r?1:-1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=r?-1:1,a[11]=0;else{let i=math_vector_Vector3.Cross(t,e),r=1/(1+s);a[0]=i._x*i._x*r+s,a[1]=i._y*i._x*r-i._z,a[2]=i._z*i._x*r+i._y,a[3]=0,a[4]=i._x*i._y*r+i._z,a[5]=i._y*i._y*r+s,a[6]=i._z*i._y*r-i._x,a[7]=0,a[8]=i._x*i._z*r-i._y,a[9]=i._y*i._z*r+i._x,a[10]=i._z*i._z*r+s,a[11]=0}return a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){return math_vector_Quaternion.RotationYawPitchRollToRef(e,t,i,MathTmp.Quaternion[0]),MathTmp.Quaternion[0].toRotationMatrix(r),r}static Scaling(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.ScalingToRef(e,t,i,r),r}static ScalingToRef(e,t,i,r){return math_vector_Matrix.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,r),r._updateIdentityStatus(1===e&&1===t&&1===i),r}static Translation(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.TranslationToRef(e,t,i,r),r}static TranslationToRef(e,t,i,r){return math_vector_Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,r),r._updateIdentityStatus(0===e&&0===t&&0===i),r}static Lerp(e,t,i){let r=new e.constructor;return math_vector_Matrix.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){let s=r._m,a=e.m,n=t.m;for(let e=0;e<16;e++)s[e]=a[e]*(1-i)+n[e]*i;return r.markAsUpdated(),r}static DecomposeLerp(e,t,i){let r=new e.constructor;return math_vector_Matrix.DecomposeLerpToRef(e,t,i,r),r}static DecomposeLerpToRef(e,t,i,r){let s=MathTmp.Vector3[0],a=MathTmp.Quaternion[0],n=MathTmp.Vector3[1];e.decompose(s,a,n);let o=MathTmp.Vector3[2],l=MathTmp.Quaternion[1],h=MathTmp.Vector3[3];t.decompose(o,l,h);let c=MathTmp.Vector3[4];math_vector_Vector3.LerpToRef(s,o,i,c);let u=MathTmp.Quaternion[2];math_vector_Quaternion.SlerpToRef(a,l,i,u);let d=MathTmp.Vector3[5];return math_vector_Vector3.LerpToRef(n,h,i,d),math_vector_Matrix.ComposeToRef(c,u,d,r),r}static LookAtLH(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.LookAtLHToRef(e,t,i,r),r}static LookAtLHToRef(e,t,i,r){let s=MathTmp.Vector3[0],a=MathTmp.Vector3[1],n=MathTmp.Vector3[2];t.subtractToRef(e,n),n.normalize(),math_vector_Vector3.CrossToRef(i,n,s);let o=s.lengthSquared();0===o?s.x=1:s.normalizeFromLength(Math.sqrt(o)),math_vector_Vector3.CrossToRef(n,s,a),a.normalize();let l=-math_vector_Vector3.Dot(s,e),h=-math_vector_Vector3.Dot(a,e),c=-math_vector_Vector3.Dot(n,e);math_vector_Matrix.FromValuesToRef(s._x,a._x,n._x,0,s._y,a._y,n._y,0,s._z,a._z,n._z,0,l,h,c,1,r)}static LookAtRH(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.LookAtRHToRef(e,t,i,r),r}static LookAtRHToRef(e,t,i,r){let s=MathTmp.Vector3[0],a=MathTmp.Vector3[1],n=MathTmp.Vector3[2];e.subtractToRef(t,n),n.normalize(),math_vector_Vector3.CrossToRef(i,n,s);let o=s.lengthSquared();0===o?s.x=1:s.normalizeFromLength(Math.sqrt(o)),math_vector_Vector3.CrossToRef(n,s,a),a.normalize();let l=-math_vector_Vector3.Dot(s,e),h=-math_vector_Vector3.Dot(a,e),c=-math_vector_Vector3.Dot(n,e);return math_vector_Matrix.FromValuesToRef(s._x,a._x,n._x,0,s._y,a._y,n._y,0,s._z,a._z,n._z,0,l,h,c,1,r),r}static LookDirectionLH(e,t){let i=new math_vector_Matrix;return math_vector_Matrix.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){let r=MathTmp.Vector3[0];r.copyFrom(e),r.scaleInPlace(-1);let s=MathTmp.Vector3[1];return math_vector_Vector3.CrossToRef(t,r,s),math_vector_Matrix.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){let i=new math_vector_Matrix;return math_vector_Matrix.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){let r=MathTmp.Vector3[2];return math_vector_Vector3.CrossToRef(t,e,r),math_vector_Matrix.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,r,s){let a=new math_vector_Matrix;return math_vector_Matrix.OrthoLHToRef(e,t,i,r,a,s),a}static OrthoLHToRef(e,t,i,r,s,a){let n=2/e,o=2/t,l=2/(r-i),h=-(r+i)/(r-i);return math_vector_Matrix.FromValuesToRef(n,0,0,0,0,o,0,0,0,0,l,0,0,0,h,1,s),a&&s.multiplyToRef(c,s),s._updateIdentityStatus(1===n&&1===o&&1===l&&0===h),s}static OrthoOffCenterLH(e,t,i,r,s,a,n){let o=new math_vector_Matrix;return math_vector_Matrix.OrthoOffCenterLHToRef(e,t,i,r,s,a,o,n),o}static OrthoOffCenterLHToRef(e,t,i,r,s,a,n,o){return math_vector_Matrix.FromValuesToRef(2/(t-e),0,0,0,0,2/(r-i),0,0,0,0,2/(a-s),0,(e+t)/(e-t),(r+i)/(i-r),-(a+s)/(a-s),1,n),o&&n.multiplyToRef(c,n),n.markAsUpdated(),n}static ObliqueOffCenterLHToRef(e,t,i,r,s,a,n,o,l,h,c){let u=-n*Math.cos(o),d=-n*Math.sin(o);return math_vector_Matrix.TranslationToRef(0,0,-l,MathTmp.Matrix[1]),math_vector_Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,MathTmp.Matrix[0]),MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0],MathTmp.Matrix[0]),math_vector_Matrix.TranslationToRef(0,0,l,MathTmp.Matrix[1]),MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1],MathTmp.Matrix[0]),math_vector_Matrix.OrthoOffCenterLHToRef(e,t,i,r,s,a,h,c),MathTmp.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,r,s,a,n){let o=new math_vector_Matrix;return math_vector_Matrix.OrthoOffCenterRHToRef(e,t,i,r,s,a,o,n),o}static OrthoOffCenterRHToRef(e,t,i,r,s,a,n,o){return math_vector_Matrix.OrthoOffCenterLHToRef(e,t,i,r,s,a,n,o),n._m[10]*=-1,n}static ObliqueOffCenterRHToRef(e,t,i,r,s,a,n,o,l,h,c){let u=n*Math.cos(o),d=n*Math.sin(o);return math_vector_Matrix.TranslationToRef(0,0,l,MathTmp.Matrix[1]),math_vector_Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,MathTmp.Matrix[0]),MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0],MathTmp.Matrix[0]),math_vector_Matrix.TranslationToRef(0,0,-l,MathTmp.Matrix[1]),MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1],MathTmp.Matrix[0]),math_vector_Matrix.OrthoOffCenterRHToRef(e,t,i,r,s,a,h,c),MathTmp.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,r,s,a=0){let n=new math_vector_Matrix,o=Math.tan(a);return math_vector_Matrix.FromValuesToRef(2*i/e,0,0,0,0,2*i/t,0,o,0,0,(r+i)/(r-i),1,0,0,-2*r*i/(r-i),0,n),s&&n.multiplyToRef(c,n),n._updateIdentityStatus(!1),n}static PerspectiveFovLH(e,t,i,r,s,a=0,n=!1){let o=new math_vector_Matrix;return math_vector_Matrix.PerspectiveFovLHToRef(e,t,i,r,o,!0,s,a,n),o}static PerspectiveFovLHToRef(e,t,i,r,s,a=!0,n,o=0,l=!1){let h=1/Math.tan(.5*e),u=a?h/t:h,d=a?h:h*t,_=l&&0===i?-1:0!==r?(r+i)/(r-i):1,p=l&&0===i?2*r:0!==r?-2*r*i/(r-i):-2*i,f=Math.tan(o);return math_vector_Matrix.FromValuesToRef(u,0,0,0,0,d,0,f,0,0,_,1,0,0,p,0,s),n&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,r,s,a=!0,n,o=0){let l=1/Math.tan(.5*e),h=a?l/t:l,u=a?l:l*t,d=Math.tan(o);return math_vector_Matrix.FromValuesToRef(h,0,0,0,0,u,0,d,0,0,-i,1,0,0,1,0,s),n&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,r,s,a=0,n=!1){let o=new math_vector_Matrix;return math_vector_Matrix.PerspectiveFovRHToRef(e,t,i,r,o,!0,s,a,n),o}static PerspectiveFovRHToRef(e,t,i,r,s,a=!0,n,o=0,l=!1){let h=1/Math.tan(.5*e),u=a?h/t:h,d=a?h:h*t,_=l&&0===i?1:0!==r?-(r+i)/(r-i):-1,p=l&&0===i?2*r:0!==r?-2*r*i/(r-i):-2*i,f=Math.tan(o);return math_vector_Matrix.FromValuesToRef(u,0,0,0,0,d,0,f,0,0,_,-1,0,0,p,0,s),n&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,r,s,a=!0,n,o=0){let l=1/Math.tan(.5*e),h=a?l/t:l,u=a?l:l*t,d=Math.tan(o);return math_vector_Matrix.FromValuesToRef(h,0,0,0,0,u,0,d,0,0,-i,-1,0,0,-1,0,s),n&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(e,t,i,r,s,a){let n=e.width,o=e.height,l=e.x,h=e.y,c=math_vector_Matrix.FromValues(n/2,0,0,0,0,-o/2,0,0,0,0,a-s,0,l+n/2,o/2+h,s,1),u=new t.constructor;return t.multiplyToRef(i,u),u.multiplyToRef(r,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){let t=e.m,i=[t[0],t[1],t[4],t[5]];return performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){let t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){let t=new e.constructor;return math_vector_Matrix.TransposeToRef(e,t),t}static TransposeToRef(e,t){let i=e.m,r=i[0],s=i[4],a=i[8],n=i[12],o=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],_=i[10],p=i[14],f=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=r,x[1]=s,x[2]=a,x[3]=n,x[4]=o,x[5]=l,x[6]=h,x[7]=c,x[8]=u,x[9]=d,x[10]=_,x[11]=p,x[12]=f,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){let t=new math_vector_Matrix;return math_vector_Matrix.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();let i=e.normal.x,r=e.normal.y,s=e.normal.z,a=-2*i,n=-2*r,o=-2*s;return math_vector_Matrix.FromValuesToRef(a*i+1,n*i,o*i,0,a*r,n*r+1,o*r,0,a*s,n*s,o*s+1,0,a*e.d,n*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,r){return math_vector_Matrix.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static FromQuaternionToRef(e,t){let i=e._x*e._x,r=e._y*e._y,s=e._z*e._z,a=e._x*e._y,n=e._z*e._w,o=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(r+s),t._m[1]=2*(a+n),t._m[2]=2*(o-l),t._m[3]=0,t._m[4]=2*(a-n),t._m[5]=1-2*(s+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(o+l),t._m[9]=2*(h-c),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}};math_vector_Matrix._UpdateFlagSeed=0,math_vector_Matrix._IdentityReadOnly=math_vector_Matrix.Identity();let MathTmp=class MathTmp{};MathTmp.Vector3=arrayTools_ArrayTools.BuildTuple(11,math_vector_Vector3.Zero),MathTmp.Matrix=arrayTools_ArrayTools.BuildTuple(2,math_vector_Matrix.Identity),MathTmp.Quaternion=arrayTools_ArrayTools.BuildTuple(3,math_vector_Quaternion.Zero);let math_vector_TmpVectors=class math_vector_TmpVectors{};math_vector_TmpVectors.Vector2=arrayTools_ArrayTools.BuildTuple(3,math_vector_Vector2.Zero),math_vector_TmpVectors.Vector3=arrayTools_ArrayTools.BuildTuple(13,math_vector_Vector3.Zero),math_vector_TmpVectors.Vector4=arrayTools_ArrayTools.BuildTuple(3,math_vector_Vector4.Zero),math_vector_TmpVectors.Quaternion=arrayTools_ArrayTools.BuildTuple(2,math_vector_Quaternion.Zero),math_vector_TmpVectors.Matrix=arrayTools_ArrayTools.BuildTuple(8,math_vector_Matrix.Identity),h["BABYLON.Vector2"]=math_vector_Vector2,h["BABYLON.Vector3"]=math_vector_Vector3,h["BABYLON.Vector4"]=math_vector_Vector4,h["BABYLON.Matrix"]=math_vector_Matrix;let c=math_vector_Matrix.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);function colorChannelToLinearSpace(e){return Math.pow(e,2.2)}function colorChannelToLinearSpaceExact(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function colorChannelToGammaSpace(e){return Math.pow(e,n)}function colorChannelToGammaSpaceExact(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let math_color_Color3=class math_color_Color3{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return 397*(e=397*e^(255*this.g|0))^(255*this.b|0)}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return math_color_Color3.FromArrayToRef(e,t,this),this}toColor4(e=1){return new math_color_Color4(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return .3*this.r+.59*this.g+.11*this.b}multiply(e){return new math_color_Color3(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}scale(e){return new math_color_Color3(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this}clampToRef(e=0,t=1,i){return i.r=math_scalar_Scalar.Clamp(this.r,e,t),i.g=math_scalar_Scalar.Clamp(this.g,e,t),i.b=math_scalar_Scalar.Clamp(this.b,e,t),this}add(e){return new math_color_Color3(this.r+e.r,this.g+e.g,this.b+e.b)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this}subtract(e){return new math_color_Color3(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,this}clone(){return new math_color_Color3(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}toHexString(){let e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+math_scalar_Scalar.ToHex(e)+math_scalar_Scalar.ToHex(t)+math_scalar_Scalar.ToHex(i)}toHSV(){let e=new math_color_Color3;return this.toHSVToRef(e),e}toHSVToRef(e){let t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),a=Math.min(t,i,r),n=0,o=0,l=s-a;0!==s&&(o=l/s),s!=a&&(s==t?(n=(i-r)/l,i<r&&(n+=6)):s==i?n=(r-t)/l+2:s==r&&(n=(t-i)/l+4),n*=60),e.r=n,e.g=o,e.b=s}toLinearSpace(e=!1){let t=new math_color_Color3;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=colorChannelToLinearSpaceExact(this.r),e.g=colorChannelToLinearSpaceExact(this.g),e.b=colorChannelToLinearSpaceExact(this.b)):(e.r=colorChannelToLinearSpace(this.r),e.g=colorChannelToLinearSpace(this.g),e.b=colorChannelToLinearSpace(this.b)),this}toGammaSpace(e=!1){let t=new math_color_Color3;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=colorChannelToGammaSpaceExact(this.r),e.g=colorChannelToGammaSpaceExact(this.g),e.b=colorChannelToGammaSpaceExact(this.b)):(e.r=colorChannelToGammaSpace(this.r),e.g=colorChannelToGammaSpace(this.g),e.b=colorChannelToGammaSpace(this.b)),this}static HSVtoRGBToRef(e,t,i,r){let s=i*t,a=e/60,n=s*(1-Math.abs(a%2-1)),o=0,l=0,h=0;a>=0&&a<=1?(o=s,l=n):a>=1&&a<=2?(o=n,l=s):a>=2&&a<=3?(l=s,h=n):a>=3&&a<=4?(l=n,h=s):a>=4&&a<=5?(o=n,h=s):a>=5&&a<=6&&(o=s,h=n);let c=i-s;r.set(o+c,l+c,h+c)}static FromHSV(e,t,i){let r=new math_color_Color3(0,0,0);return math_color_Color3.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new math_color_Color3(0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16);return math_color_Color3.FromInts(t,i,r)}static FromArray(e,t=0){return new math_color_Color3(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 math_color_Color3(e/255,t/255,i/255)}static Lerp(e,t,i){let r=new math_color_Color3(0,0,0);return math_color_Color3.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){let a=s*s,n=s*a,o=2*n-3*a+1,l=-2*n+3*a,h=n-2*a+s,c=n-a,u=e.r*o+i.r*l+t.r*h+r.r*c,d=e.g*o+i.g*l+t.g*h+r.g*c,_=e.b*o+i.b*l+t.b*h+r.b*c;return new math_color_Color3(u,d,_)}static Hermite1stDerivative(e,t,i,r,s){let a=math_color_Color3.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let n=s*s;a.r=(n-s)*6*e.r+(3*n-4*s+1)*t.r+(-n+s)*6*i.r+(3*n-2*s)*r.r,a.g=(n-s)*6*e.g+(3*n-4*s+1)*t.g+(-n+s)*6*i.g+(3*n-2*s)*r.g,a.b=(n-s)*6*e.b+(3*n-4*s+1)*t.b+(-n+s)*6*i.b+(3*n-2*s)*r.b}static Red(){return new math_color_Color3(1,0,0)}static Green(){return new math_color_Color3(0,1,0)}static Blue(){return new math_color_Color3(0,0,1)}static Black(){return new math_color_Color3(0,0,0)}static get BlackReadOnly(){return math_color_Color3._BlackReadOnly}static White(){return new math_color_Color3(1,1,1)}static Purple(){return new math_color_Color3(.5,0,.5)}static Magenta(){return new math_color_Color3(1,0,1)}static Yellow(){return new math_color_Color3(1,1,0)}static Gray(){return new math_color_Color3(.5,.5,.5)}static Teal(){return new math_color_Color3(0,1,1)}static Random(){return new math_color_Color3(Math.random(),Math.random(),Math.random())}};math_color_Color3._BlackReadOnly=math_color_Color3.Black();let math_color_Color4=class math_color_Color4{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}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 math_color_Color4.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 math_color_Color4(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new math_color_Color4(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 math_color_Color4(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=math_scalar_Scalar.Clamp(this.r,e,t),i.g=math_scalar_Scalar.Clamp(this.g,e,t),i.b=math_scalar_Scalar.Clamp(this.b,e,t),i.a=math_scalar_Scalar.Clamp(this.a,e,t),this}multiply(e){return new math_color_Color4(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 397*(e=397*(e=397*e^(255*this.g|0))^(255*this.b|0))^(255*this.a|0)}clone(){return new math_color_Color4(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,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}toHexString(e=!1){let t=Math.round(255*this.r),i=Math.round(255*this.g),r=Math.round(255*this.b);if(e)return"#"+math_scalar_Scalar.ToHex(t)+math_scalar_Scalar.ToHex(i)+math_scalar_Scalar.ToHex(r);let s=Math.round(255*this.a);return"#"+math_scalar_Scalar.ToHex(t)+math_scalar_Scalar.ToHex(i)+math_scalar_Scalar.ToHex(r)+math_scalar_Scalar.ToHex(s)}toLinearSpace(e=!1){let t=new math_color_Color4;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=colorChannelToLinearSpaceExact(this.r),e.g=colorChannelToLinearSpaceExact(this.g),e.b=colorChannelToLinearSpaceExact(this.b)):(e.r=colorChannelToLinearSpace(this.r),e.g=colorChannelToLinearSpace(this.g),e.b=colorChannelToLinearSpace(this.b)),e.a=this.a,this}toGammaSpace(e=!1){let t=new math_color_Color4;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=colorChannelToGammaSpaceExact(this.r),e.g=colorChannelToGammaSpaceExact(this.g),e.b=colorChannelToGammaSpaceExact(this.b)):(e.r=colorChannelToGammaSpace(this.r),e.g=colorChannelToGammaSpace(this.g),e.b=colorChannelToGammaSpace(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new math_color_Color4(0,0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return math_color_Color4.FromInts(t,i,r,s)}static Lerp(e,t,i){let r=new math_color_Color4(0,0,0,0);return math_color_Color4.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,r,s){let a=s*s,n=s*a,o=2*n-3*a+1,l=-2*n+3*a,h=n-2*a+s,c=n-a,u=e.r*o+i.r*l+t.r*h+r.r*c,d=e.g*o+i.g*l+t.g*h+r.g*c,_=e.b*o+i.b*l+t.b*h+r.b*c,p=e.a*o+i.a*l+t.a*h+r.a*c;return new math_color_Color4(u,d,_,p)}static Hermite1stDerivative(e,t,i,r,s){let a=new math_color_Color4;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let n=s*s;a.r=(n-s)*6*e.r+(3*n-4*s+1)*t.r+(-n+s)*6*i.r+(3*n-2*s)*r.r,a.g=(n-s)*6*e.g+(3*n-4*s+1)*t.g+(-n+s)*6*i.g+(3*n-2*s)*r.g,a.b=(n-s)*6*e.b+(3*n-4*s+1)*t.b+(-n+s)*6*i.b+(3*n-2*s)*r.b,a.a=(n-s)*6*e.a+(3*n-4*s+1)*t.a+(-n+s)*6*i.a+(3*n-2*s)*r.a}static FromColor3(e,t=1){return new math_color_Color4(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new math_color_Color4(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new math_color_Color4(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===3*t){let t=[];for(let i=0;i<e.length;i+=3){let r=i/3*4;t[r]=e[i],t[r+1]=e[i+1],t[r+2]=e[i+2],t[r+3]=1}return t}return e}};let TmpColors=class TmpColors{};TmpColors.Color3=arrayTools_ArrayTools.BuildArray(3,math_color_Color3.Black),TmpColors.Color4=arrayTools_ArrayTools.BuildArray(3,()=>new math_color_Color4(0,0,0,0)),h["BABYLON.Color3"]=math_color_Color3,h["BABYLON.Color4"]=math_color_Color4;let Action=class Action{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new observable_Observable,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(){let e=this._condition;if(!e)return!0;let t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){let t=this._evaluateConditionForCurrentFrame();t&&(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){let i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){let e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}};Action._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof math_vector_Vector2?e.x+", "+e.y:e instanceof math_vector_Vector3?e.x+", "+e.y+", "+e.z:e instanceof math_color_Color3?e.r+", "+e.g+", "+e.b:e instanceof math_color_Color4?e.r+", "+e.g+", "+e.b+", "+e.a:e,Action._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),h["BABYLON.Action"]=Action;let ActionEvent=class ActionEvent{constructor(e,t,i,r,s,a){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=a}static CreateNew(e,t,i){let r=e.getScene();return new ActionEvent(e,r.pointerX,r.pointerY,r.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,r){return new ActionEvent(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,r)}static CreateNewFromScene(e,t){return new ActionEvent(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,r){return new ActionEvent(e,t.x,t.y,null,i,r)}};let Condition=class Condition{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}}};let ValueCondition=class ValueCondition extends Condition{static get IsEqual(){return ValueCondition._IsEqual}static get IsDifferent(){return ValueCondition._IsDifferent}static get IsGreater(){return ValueCondition._IsGreater}static get IsLesser(){return ValueCondition._IsLesser}constructor(e,t,i,r,s=ValueCondition.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case ValueCondition.IsGreater:return this._effectiveTarget[this._property]>this.value;case ValueCondition.IsLesser:return this._effectiveTarget[this._property]<this.value;case ValueCondition.IsEqual:case ValueCondition.IsDifferent:{let e;return e=this.value.equals?this.value.equals(this._effectiveTarget[this._property]):this.value===this._effectiveTarget[this._property],this.operator===ValueCondition.IsEqual?e:!e}}return!1}serialize(){return this._serialize({name:"ValueCondition",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)},{name:"operator",value:ValueCondition.GetOperatorName(this.operator)}]})}static GetOperatorName(e){switch(e){case ValueCondition._IsEqual:return"IsEqual";case ValueCondition._IsDifferent:return"IsDifferent";case ValueCondition._IsGreater:return"IsGreater";case ValueCondition._IsLesser:return"IsLesser";default:return""}}};ValueCondition._IsEqual=0,ValueCondition._IsDifferent=1,ValueCondition._IsGreater=2,ValueCondition._IsLesser=3;let PredicateCondition=class PredicateCondition extends Condition{constructor(e,t){super(e),this.predicate=t}isValid(){return this.predicate()}};let StateCondition=class StateCondition extends Condition{constructor(e,t,i){super(e),this.value=i,this._target=t}isValid(){return this._target.state===this.value}serialize(){return this._serialize({name:"StateCondition",properties:[Action._GetTargetProperty(this._target),{name:"value",value:this.value}]})}};h["BABYLON.ValueCondition"]=ValueCondition,h["BABYLON.PredicateCondition"]=PredicateCondition,h["BABYLON.StateCondition"]=StateCondition;let logger_Logger=class logger_Logger{static _CheckLimit(e,t){let i=logger_Logger._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},logger_Logger._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var i;let r=logger_Logger._LogLimitOutputs[e];if(!r||!logger_Logger.MessageLimitReached)return;let s=this._Levels[t];r.current===r.limit&&logger_Logger[s.name](logger_Logger.MessageLimitReached.replace(/%LIMIT%/g,""+r.limit).replace(/%TYPE%/g,null!==(i=s.name)&&void 0!==i?i:""))}static _AddLogEntry(e){logger_Logger._LogCache=e+logger_Logger._LogCache,logger_Logger.OnNewCacheEntry&&logger_Logger.OnNewCacheEntry(e)}static _FormatMessage(e){let padStr=e=>e<10?"0"+e:""+e,t=new Date;return"["+padStr(t.getHours())+":"+padStr(t.getMinutes())+":"+padStr(t.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){if(void 0!==i&&!logger_Logger._CheckLimit(t,i))return;let r=logger_Logger._FormatMessage(t),s=this._Levels[e];s.logFunc&&s.logFunc("BJS - "+r);let a=`<div style='color:${s.color}'>${r}</div><br>`;logger_Logger._AddLogEntry(a),logger_Logger._GenerateLimitMessage(t,e)}static get LogCache(){return logger_Logger._LogCache}static ClearLogCache(){logger_Logger._LogCache="",logger_Logger._LogLimitOutputs={},logger_Logger.errorsCount=0}static set LogLevels(e){logger_Logger.Log=logger_Logger._LogDisabled,logger_Logger.Warn=logger_Logger._LogDisabled,logger_Logger.Error=logger_Logger._LogDisabled,[logger_Logger.MessageLogLevel,logger_Logger.WarningLogLevel,logger_Logger.ErrorLogLevel].forEach(t=>{if((e&t)===t){let e=this._Levels[t];logger_Logger[e.name]=logger_Logger._LogEnabled.bind(logger_Logger,t)}})}};logger_Logger.NoneLogLevel=0,logger_Logger.MessageLogLevel=1,logger_Logger.WarningLogLevel=2,logger_Logger.ErrorLogLevel=4,logger_Logger.AllLogLevel=7,logger_Logger.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",logger_Logger._LogCache="",logger_Logger._LogLimitOutputs={},logger_Logger._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],logger_Logger.errorsCount=0,logger_Logger.Log=logger_Logger._LogEnabled.bind(logger_Logger,logger_Logger.MessageLogLevel),logger_Logger.Warn=logger_Logger._LogEnabled.bind(logger_Logger,logger_Logger.WarningLogLevel),logger_Logger.Error=logger_Logger._LogEnabled.bind(logger_Logger,logger_Logger.ErrorLogLevel);let SwitchBooleanAction=class SwitchBooleanAction extends Action{constructor(e,t,i,r){super(e,r),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}};let SetStateAction=class SetStateAction extends Action{constructor(e,t,i,r){super(e,r),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[Action._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}};let SetValueAction=class SetValueAction extends Action{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)}]},e)}};let IncrementValueAction=class IncrementValueAction extends Action{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&logger_Logger.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)}]},e)}};let PlayAnimationAction=class PlayAnimationAction extends Action{constructor(e,t,i,r,s,a){super(e,a),this.from=i,this.to=r,this.loop=s,this._target=t}_prepare(){}execute(){let e=this._actionManager.getScene();e.beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[Action._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Action._SerializeValueAsString(this.loop)||!1}]},e)}};let StopAnimationAction=class StopAnimationAction extends Action{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){let e=this._actionManager.getScene();e.stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[Action._GetTargetProperty(this._target)]},e)}};let DoNothingAction=class DoNothingAction extends Action{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}};let CombineAction=class CombineAction extends Action{constructor(e,t,i,r=!0){super(e,i),this.children=t,this.enableChildrenConditions=r}_prepare(){for(let e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()}execute(e){for(let t of this.children)(!this.enableChildrenConditions||t._evaluateConditionForCurrentFrame())&&t.execute(e)}serialize(e){let t=super._serialize({name:"CombineAction",properties:[],combine:[]},e);for(let e=0;e<this.children.length;e++)t.combine.push(this.children[e].serialize(null));return t}};let ExecuteCodeAction=class ExecuteCodeAction extends Action{constructor(e,t,i){super(e,i),this.func=t}execute(e){this.func(e)}};let SetParentAction=class SetParentAction extends Action{constructor(e,t,i,r){super(e,r),this._target=t,this._parent=i}_prepare(){}execute(){if(this._target.parent===this._parent)return;let e=this._parent.getWorldMatrix().clone();e.invert(),this._target.position=math_vector_Vector3.TransformCoordinates(this._target.position,e),this._target.parent=this._parent}serialize(e){return super._serialize({name:"SetParentAction",properties:[Action._GetTargetProperty(this._target),Action._GetTargetProperty(this._parent)]},e)}};h["BABYLON.SetParentAction"]=SetParentAction,h["BABYLON.ExecuteCodeAction"]=ExecuteCodeAction,h["BABYLON.DoNothingAction"]=DoNothingAction,h["BABYLON.StopAnimationAction"]=StopAnimationAction,h["BABYLON.PlayAnimationAction"]=PlayAnimationAction,h["BABYLON.IncrementValueAction"]=IncrementValueAction,h["BABYLON.SetValueAction"]=SetValueAction,h["BABYLON.SetStateAction"]=SetStateAction,h["BABYLON.SetParentAction"]=SetParentAction,h["BABYLON.SwitchBooleanAction"]=SwitchBooleanAction,h["BABYLON.CombineAction"]=CombineAction;let CloneValue=(e,t,i)=>!e||e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&("SubMesh"===e.getClassName()||"PhysicsBody"===e.getClassName())?e.clone(t):e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?Object.assign({},e):null;function GetAllPropertyNames(e){let t=[];do Object.getOwnPropertyNames(e).forEach(function(e){-1===t.indexOf(e)&&t.push(e)});while(e=Object.getPrototypeOf(e));return t}let DeepCopier=class DeepCopier{static DeepCopy(e,t,i,r,s=!1){let a=GetAllPropertyNames(e);for(let n of a){if("_"===n[0]&&(!r||-1===r.indexOf(n))||n.endsWith("Observable")||i&&-1!==i.indexOf(n))continue;let a=e[n],o=typeof a;if("function"!==o)try{if("object"===o){if(a instanceof Uint8Array)t[n]=Uint8Array.from(a);else if(a instanceof Array){if(t[n]=[],a.length>0){if("object"==typeof a[0])for(let e=0;e<a.length;e++){let i=CloneValue(a[e],t,s);-1===t[n].indexOf(i)&&t[n].push(i)}else t[n]=a.slice(0)}}else t[n]=CloneValue(a,t,s)}else t[n]=a}catch(e){logger_Logger.Warn(e.message)}}}};let ActionManager=class ActionManager extends AbstractActionManager{constructor(e){if(super(),!(e=e||engineStore_EngineStore.LastCreatedScene))return;this._scene=e,e.actionManagers.push(this)}dispose(){let e=this._scene.actionManagers.indexOf(this);for(let e=0;e<this.actions.length;e++){let t=this.actions[e];ActionManager.Triggers[t.trigger]--,0===ActionManager.Triggers[t.trigger]&&delete ActionManager.Triggers[t.trigger]}this.actions.length=0,e>-1&&this._scene.actionManagers.splice(e,1);let t=this._scene.meshes.filter(e=>e.actionManager===this);for(let e of t)e.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t<this.actions.length;t++){let i=this.actions[t];if(e.indexOf(i.trigger)>-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i<this.actions.length;i++){let r=this.actions[i];if(e==r.trigger||t==r.trigger)return!0}return!1}hasSpecificTrigger(e,t){for(let i=0;i<this.actions.length;i++){let r=this.actions[i];if(r.trigger===e&&(!t||t(r.getTriggerParameter())))return!0}return!1}get hasPointerTriggers(){for(let e=0;e<this.actions.length;e++){let t=this.actions[e];if(t.trigger>=ActionManager.OnPickTrigger&&t.trigger<=ActionManager.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e<this.actions.length;e++){let t=this.actions[e];if(t.trigger>=ActionManager.OnPickTrigger&&t.trigger<=ActionManager.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===ActionManager.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(logger_Logger.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,ActionManager.Triggers[e.trigger]?ActionManager.Triggers[e.trigger]++:ActionManager.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){let t=this.actions.indexOf(e);return -1!==t&&(this.actions.splice(t,1),ActionManager.Triggers[e.trigger]-=1,0===ActionManager.Triggers[e.trigger]&&delete ActionManager.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i<this.actions.length;i++){let r=this.actions[i];if(r.trigger===e){if(t&&(e===ActionManager.OnKeyUpTrigger||e===ActionManager.OnKeyDownTrigger)){let e=r.getTriggerParameter();if("function"==typeof e){if(!e(t))continue}else if(e&&e!==t.sourceEvent.keyCode){if(!e.toLowerCase)continue;let i=e.toLowerCase();if(i!==t.sourceEvent.key){let e=t.sourceEvent.charCode?t.sourceEvent.charCode:t.sourceEvent.keyCode,r=String.fromCharCode(e).toLowerCase();if(r!==i)continue}}}r._executeCurrent(t)}}}_getEffectiveTarget(e,t){let i=t.split(".");for(let t=0;t<i.length-1;t++)e=e[i[t]];return e}_getProperty(e){let t=e.split(".");return t[t.length-1]}serialize(e){let t={children:[],name:e,type:3,properties:[]};for(let e=0;e<this.actions.length;e++){let i={type:0,children:[],name:ActionManager.GetTriggerName(this.actions[e].trigger),properties:[]},r=this.actions[e].triggerOptions;if(r&&"number"!=typeof r){if(r.parameter instanceof Node)i.properties.push(Action._GetTargetProperty(r.parameter));else if("object"==typeof r.parameter){let e={};DeepCopier.DeepCopy(r.parameter,e,["mesh"]),r.parameter&&r.parameter.mesh&&(e._meshId=r.parameter.mesh.id),i.properties.push({name:"parameter",targetType:null,value:e})}else i.properties.push({name:"parameter",targetType:null,value:r.parameter})}this.actions[e].serialize(i),t.children.push(i)}return t}static Parse(e,t,i){let r=new ActionManager(i);null===t?i.actionManager=r:t.actionManager=r;let instantiate=(e,t)=>{let i=h["BABYLON."+e];return i&&new i(...t)},parseParameter=(e,t,i,r)=>{if(null===r){let e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}let s=r.split("."),a=t.split(",");for(let e=0;e<s.length;e++)i=i[s[e]];if("boolean"==typeof i)return"true"===a[0];if("string"==typeof i)return a[0];let n=[];for(let e=0;e<a.length;e++)n.push(parseFloat(a[e]));return i instanceof math_vector_Vector3?math_vector_Vector3.FromArray(n):i instanceof math_vector_Vector4?math_vector_Vector4.FromArray(n):i instanceof math_color_Color3?math_color_Color3.FromArray(n):i instanceof math_color_Color4?math_color_Color4.FromArray(n):parseFloat(a[0])},traverse=(e,t,s,a,n=null)=>{if(e.detached)return;let o=[],l=null,h=null,c=e.combine&&e.combine.length>0;if(2===e.type?o.push(r):o.push(t),c){let t=[];for(let i=0;i<e.combine.length;i++)traverse(e.combine[i],ActionManager.NothingTrigger,s,a,t);o.push(t)}else for(let t=0;t<e.properties.length;t++){let r=e.properties[t].value,s=e.properties[t].name,a=e.properties[t].targetType;"target"===s?r=l="SceneProperties"===a?i:"MaterialProperties"===a?i.getMaterialByName(r):i.getNodeByName(r):"parent"===s?r=i.getNodeByName(r):"sound"===s?i.getSoundByName&&(r=i.getSoundByName(r)):"propertyPath"!==s?r=2===e.type&&"operator"===s?ValueCondition[r]:parseParameter(s,r,l,"value"===s?h:null):h=r,o.push(r)}if(null===n?o.push(s):o.push(null),"InterpolateValueAction"===e.name){let e=o[o.length-2];o[o.length-1]=e,o[o.length-2]=s}let u=instantiate(e.name,o);if(u instanceof Condition&&null!==s){let e=new DoNothingAction(t,s);a?a.then(e):r.registerAction(e),a=e}null===n?u instanceof Condition?(s=u,u=a):(s=null,a?a.then(u):r.registerAction(u)):n.push(u);for(let i=0;i<e.children.length;i++)traverse(e.children[i],t,s,u,null)};for(let t=0;t<e.children.length;t++){let r;let s=e.children[t];if(s.properties.length>0){let e=s.properties[0].value,t=null===s.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),r={trigger:ActionManager[s.name],parameter:t}}else r=ActionManager[s.name];for(let e=0;e<s.children.length;e++)s.detached||traverse(s.children[e],r,null,null)}}static GetTriggerName(e){switch(e){case 0:return"NothingTrigger";case 1:return"OnPickTrigger";case 2:return"OnLeftPickTrigger";case 3:return"OnRightPickTrigger";case 4:return"OnCenterPickTrigger";case 5:return"OnPickDownTrigger";case 6:return"OnDoublePickTrigger";case 7:return"OnPickUpTrigger";case 8:return"OnLongPressTrigger";case 9:return"OnPointerOverTrigger";case 10:return"OnPointerOutTrigger";case 11:return"OnEveryFrameTrigger";case 12:return"OnIntersectionEnterTrigger";case 13:return"OnIntersectionExitTrigger";case 14:return"OnKeyDownTrigger";case 15:return"OnKeyUpTrigger";case 16:return"OnPickOutTrigger";default:return""}}};ActionManager.NothingTrigger=0,ActionManager.OnPickTrigger=1,ActionManager.OnLeftPickTrigger=2,ActionManager.OnRightPickTrigger=3,ActionManager.OnCenterPickTrigger=4,ActionManager.OnPickDownTrigger=5,ActionManager.OnDoublePickTrigger=6,ActionManager.OnPickUpTrigger=7,ActionManager.OnPickOutTrigger=16,ActionManager.OnLongPressTrigger=8,ActionManager.OnPointerOverTrigger=9,ActionManager.OnPointerOutTrigger=10,ActionManager.OnEveryFrameTrigger=11,ActionManager.OnIntersectionEnterTrigger=12,ActionManager.OnIntersectionExitTrigger=13,ActionManager.OnKeyDownTrigger=14,ActionManager.OnKeyUpTrigger=15;let PlaySoundAction=class PlaySoundAction extends Action{constructor(e,t,i){super(e,i),this._sound=t}_prepare(){}execute(){void 0!==this._sound&&this._sound.play()}serialize(e){return super._serialize({name:"PlaySoundAction",properties:[{name:"sound",value:this._sound.name}]},e)}};let StopSoundAction=class StopSoundAction extends Action{constructor(e,t,i){super(e,i),this._sound=t}_prepare(){}execute(){void 0!==this._sound&&this._sound.stop()}serialize(e){return super._serialize({name:"StopSoundAction",properties:[{name:"sound",value:this._sound.name}]},e)}};h["BABYLON.PlaySoundAction"]=PlaySoundAction,h["BABYLON.StopSoundAction"]=StopSoundAction;let AndOrNotEvaluator=class AndOrNotEvaluator{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,e=>(e=e.slice(1,e.length-1),AndOrNotEvaluator._HandleParenthesisContent(e,t))):AndOrNotEvaluator._HandleParenthesisContent(e,t))||"false"!==e&&AndOrNotEvaluator.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);let r=e.split("||");for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e)){let s=AndOrNotEvaluator._SimplifyNegation(r[e].trim()),a=s.split("&&");if(a.length>1)for(let e=0;e<a.length;++e){let r=AndOrNotEvaluator._SimplifyNegation(a[e].trim());if(!(i="true"!==r&&"false"!==r?"!"===r[0]?!t(r.substring(1)):t(r):"true"===r)){s="false";break}}if(i||"true"===s){i=!0;break}i="true"!==s&&"false"!==s?"!"===s[0]?!t(s.substring(1)):t(s):"true"===s}return i?"true":"false"}static _SimplifyNegation(e){return"!true"===(e=(e=e.replace(/^[\s!]+/,e=>(e=e.replace(/[\s]/g,()=>"")).length%2?"!":"")).trim())?e="false":"!false"===e&&(e="true"),e}};let Tags=class Tags{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Tags.HasTags(e),e.addTags=t=>Tags.AddTagsTo(e,t),e.removeTags=t=>Tags.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Tags.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;let t=e._tags;for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(!t)return e._tags;{let t=[];for(let i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}}static AddTagsTo(e,t){if(!t||"string"!=typeof t)return;let i=t.split(" ");i.forEach(function(t){Tags._AddTagTo(e,t)})}static _AddTagTo(e,t){""===(t=t.trim())||"true"===t||"false"===t||t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Tags.EnableFor(e),e._tags[t]=!0)}static RemoveTagsFrom(e,t){if(!Tags.HasTags(e))return;let i=t.split(" ");for(let t in i)Tags._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?Tags.HasTags(e):AndOrNotEvaluator.Eval(t,t=>Tags.HasTags(e)&&e._tags[t]))}};let u={};function _WarnImport(e,t=!1){if(!t||!u[e])return u[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}let d={},_={},_copySource=function(e,t,i,r={}){let s=e();Tags&&Tags.HasTags(t)&&Tags.AddTagsTo(s,Tags.GetTags(t,!0));let a=getMergedStore(s),n={};for(let e in a){let o=a[e],l=t[e],h=o.type;if(null!=l&&("uniqueId"!==e||decorators_SerializationHelper.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:s[e]=l;break;case 1:r.cloneTexturesOnlyOnce&&n[l.uniqueId]?s[e]=n[l.uniqueId]:(s[e]=i||l.isRenderTarget?l:l.clone(),n[l.uniqueId]=s[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[e]=i?l:l.clone()}}return s};function getDirectStore(e){let t=e.getClassName();return d[t]||(d[t]={}),d[t]}function getMergedStore(e){let t=e.getClassName();if(_[t])return _[t];_[t]={};let i=_[t],r=e,s=t;for(;s;){let e;let t=d[s];for(let e in t)i[e]=t[e];let a=!1;do{if(!(e=Object.getPrototypeOf(r)).getClassName){a=!0;break}if(e.getClassName()!==s)break;r=e}while(e);if(a)break;s=e.getClassName(),r=e}return i}function generateSerializableMember(e,t){return(i,r)=>{let s=getDirectStore(i);s[r]||(s[r]={type:e,sourceName:t})}}function generateExpandMember(e,t=null){return(i,r)=>{let s=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]===t||(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}function expandToProperty(e,t=null){return generateExpandMember(e,t)}function serialize(e){return generateSerializableMember(0,e)}function serializeAsTexture(e){return generateSerializableMember(1,e)}function serializeAsColor3(e){return generateSerializableMember(2,e)}function serializeAsFresnelParameters(e){return generateSerializableMember(3,e)}function serializeAsVector3(e){return generateSerializableMember(5,e)}function serializeAsMeshReference(e){return generateSerializableMember(6,e)}function serializeAsColorCurves(e){return generateSerializableMember(7,e)}function serializeAsQuaternion(e){return generateSerializableMember(10,e)}function serializeAsCameraReference(e){return generateSerializableMember(11,e)}let decorators_SerializationHelper=class decorators_SerializationHelper{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i<e.animations.length;i++){let r=e.animations[i];t.animations.push(r.serialize())}}}static Serialize(e,t){t||(t={}),Tags&&(t.tags=Tags.GetTags(e));let i=getMergedStore(e);for(let r in i){let s=i[r],a=s.sourceName||r,n=s.type,o=e[r];if(null!=o&&("uniqueId"!==r||decorators_SerializationHelper.AllowLoadingUniqueId))switch(n){case 0:t[a]=o;break;case 1:case 3:case 7:case 9:t[a]=o.serialize();break;case 2:case 4:case 5:case 8:case 10:case 12:t[a]=o.asArray();break;case 6:case 11:t[a]=o.id}}return t}static ParseProperties(e,t,i,r){r||(r="");let s=getMergedStore(t);for(let a in s){let n=s[a],o=e[n.sourceName||a],l=n.type;if(null!=o&&("uniqueId"!==a||decorators_SerializationHelper.AllowLoadingUniqueId))switch(l){case 0:t[a]=o;break;case 1:i&&(t[a]=decorators_SerializationHelper._TextureParser(o,i,r));break;case 2:t[a]=math_color_Color3.FromArray(o);break;case 3:t[a]=decorators_SerializationHelper._FresnelParametersParser(o);break;case 4:t[a]=math_vector_Vector2.FromArray(o);break;case 5:t[a]=math_vector_Vector3.FromArray(o);break;case 6:i&&(t[a]=i.getLastMeshById(o));break;case 7:t[a]=decorators_SerializationHelper._ColorCurvesParser(o);break;case 8:t[a]=math_color_Color4.FromArray(o);break;case 9:t[a]=decorators_SerializationHelper._ImageProcessingConfigurationParser(o);break;case 10:t[a]=math_vector_Quaternion.FromArray(o);break;case 11:i&&(t[a]=i.getCameraById(o));break;case 12:t[a]=math_vector_Matrix.FromArray(o)}}}static Parse(e,t,i,r=null){let s=e();return Tags&&Tags.AddTagsTo(s,t.tags),decorators_SerializationHelper.ParseProperties(t,s,i,r),s}static Clone(e,t,i={}){return _copySource(e,t,!1,i)}static Instanciate(e,t){return _copySource(e,t,!0)}};function nativeOverride(e,t,i,r){let s=i.value;i.value=(...i)=>{let a=s;if("undefined"!=typeof _native&&_native[t]){let e=_native[t];a=r?(...t)=>r(...t)?e(...t):s(...t):e}return e[t]=a,a(...i)}}decorators_SerializationHelper.AllowLoadingUniqueId=!1,decorators_SerializationHelper._ImageProcessingConfigurationParser=e=>{throw _WarnImport("ImageProcessingConfiguration")},decorators_SerializationHelper._FresnelParametersParser=e=>{throw _WarnImport("FresnelParameters")},decorators_SerializationHelper._ColorCurvesParser=e=>{throw _WarnImport("ColorCurves")},decorators_SerializationHelper._TextureParser=(e,t,i)=>{throw _WarnImport("Texture")},nativeOverride.filter=function(e){return(t,i,r)=>nativeOverride(t,i,r,e)},function(e){e[e.NONE=0]="NONE",e[e.STEP=1]="STEP"}(K||(K={}));let AnimationRange=class AnimationRange{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new AnimationRange(this.name,this.from,this.to)}};function __decorate(e,t,i,r){var s,a=arguments.length,n=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,i,r);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(n=(a<3?s(n):a>3?s(t,i,n):s(t,i))||n);return a>3&&n&&Object.defineProperty(t,i,n),n}Object.create,Object.create;let _InternalNodeDataInfo=class _InternalNodeDataInfo{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new observable_Observable,this._onClonedObservable=new observable_Observable}};let node_Node=class node_Node{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){let s=this._NodeConstructors[e];return s?s(t,i,r):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;let t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){let 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=[]),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){let 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 _InternalNodeDataInfo,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new observable_Observable,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=math_vector_Matrix.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new observable_Observable,this._onDisposeObserver=null,this._behaviors=[],this.name=e,this.id=e,this._scene=t||engineStore_EngineStore.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){let i=this._behaviors.indexOf(e);return -1!==i||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{e.attach(this)}):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){let 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(let 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 r=0;r<this._children.length;r++){let s=this._children[r];(!i||i(s))&&e.push(s),t||s._getDescendants(e,!1,i)}}getDescendants(e,t){let i=[];return this._getDescendants(i,e,t),i}getChildMeshes(e,t){let i=[];return this._getDescendants(i,e,e=>(!t||t(e))&&void 0!==e.cullingStrategy),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;t<this.animations.length;t++){let i=this.animations[t];if(i.name===e)return i}return null}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=node_Node._AnimationRangeFactory(e,t,i);for(let r=0,s=this.animations.length;r<s;r++)this.animations[r]&&this.animations[r].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,r=this.animations.length;i<r;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(e,t,i){let r=decorators_SerializationHelper.Clone(()=>new node_Node(e,this.getScene()),this);if(t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;i<t.length;i++){let s=t[i];s.clone(e+"."+s.name,r)}}return r}getAnimationRanges(){let e;let t=[];for(e in this._ranges)t.push(this._ranges[e]);return t}beginAnimation(e,t,i,r){let s=this.getAnimationRange(e);return s?this._scene.beginAnimation(this,s.from,s.to,t,i,r):null}serializeAnimationRanges(){let e=[];for(let t in this._ranges){let i=this._ranges[t];if(!i)continue;let r={};r.name=t,r.from=i.from,r.to=i.to,e.push(r)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=math_vector_Matrix.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){let i=this.getDescendants(!0);for(let r of i)r.dispose(e,t)}for(let e of(this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear(),this._behaviors))e.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,i){if(t.ranges)for(let i=0;i<t.ranges.length;i++){let r=t.ranges[i];e.createAnimationRange(r.name,r.from,r.to)}}getHierarchyBoundingVectors(e=!0,t=null){let i,r;if(this.getScene().incrementRenderId(),this.computeWorldMatrix(!0),this.getBoundingInfo&&this.subMeshes){let e=this.getBoundingInfo();i=e.boundingBox.minimumWorld.clone(),r=e.boundingBox.maximumWorld.clone()}else i=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new math_vector_Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){let e=this.getDescendants(!1);for(let s of e){if(s.computeWorldMatrix(!0),t&&!t(s)||!s.getBoundingInfo||0===s.getTotalVertices())continue;let e=s.getBoundingInfo(),a=e.boundingBox,n=a.minimumWorld,o=a.maximumWorld;math_vector_Vector3.CheckExtends(n,i,r),math_vector_Vector3.CheckExtends(o,i,r)}}return{min:i,max:r}}};node_Node._AnimationRangeFactory=(e,t,i)=>{throw _WarnImport("AnimationRange")},node_Node._NodeConstructors={},__decorate([serialize()],node_Node.prototype,"name",void 0),__decorate([serialize()],node_Node.prototype,"id",void 0),__decorate([serialize()],node_Node.prototype,"uniqueId",void 0),__decorate([serialize()],node_Node.prototype,"state",void 0),__decorate([serialize()],node_Node.prototype,"metadata",void 0);let Size=class Size{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){return 397*(0|this.width)^(0|this.height)}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new Size(this.width*e,this.height*t)}clone(){return new Size(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new Size(0,0)}add(e){let t=new Size(this.width+e.width,this.height+e.height);return t}subtract(e){let t=new Size(this.width-e.width,this.height-e.height);return t}static Lerp(e,t,i){let r=e.width+(t.width-e.width)*i,s=e.height+(t.height-e.height)*i;return new Size(r,s)}};function createXMLHttpRequest(){return"undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}let webRequest_WebRequest=class webRequest_WebRequest{constructor(){this._xhr=createXMLHttpRequest(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(webRequest_WebRequest.CustomRequestHeaders).length>0||webRequest_WebRequest.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(let e in webRequest_WebRequest.CustomRequestHeaders){let t=webRequest_WebRequest.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return webRequest_WebRequest.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){webRequest_WebRequest.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(let e of webRequest_WebRequest.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(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)}};webRequest_WebRequest.CustomRequestHeaders={},webRequest_WebRequest.CustomRequestModifiers=[],webRequest_WebRequest.SkipRequestModificationForBabylonCDN=!0;let p={key:0,repeatCount:0,loopMode:2};let animation_Animation=class animation_Animation{static _PrepareAnimation(e,t,i,r,s,a,n,o){let l;if(!isNaN(parseFloat(s))&&isFinite(s)?l=animation_Animation.ANIMATIONTYPE_FLOAT:s instanceof math_vector_Quaternion?l=animation_Animation.ANIMATIONTYPE_QUATERNION:s instanceof math_vector_Vector3?l=animation_Animation.ANIMATIONTYPE_VECTOR3:s instanceof math_vector_Vector2?l=animation_Animation.ANIMATIONTYPE_VECTOR2:s instanceof math_color_Color3?l=animation_Animation.ANIMATIONTYPE_COLOR3:s instanceof math_color_Color4?l=animation_Animation.ANIMATIONTYPE_COLOR4:s instanceof Size&&(l=animation_Animation.ANIMATIONTYPE_SIZE),void 0==l)return null;let h=new animation_Animation(e,t,i,l,n),c=[{frame:0,value:s},{frame:r,value:a}];return h.setKeys(c),void 0!==o&&h.setEasingFunction(o),h}static CreateAnimation(e,t,i,r){let s=new animation_Animation(e+"Animation",e,i,t,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,a,n,o,l,h,c){let u=animation_Animation._PrepareAnimation(e,i,r,s,a,n,o,l);return u&&(t.getScene&&(c=t.getScene()),c)?c.beginDirectAnimation(t,[u],0,s,1===u.loopMode,1,h):null}static CreateAndStartHierarchyAnimation(e,t,i,r,s,a,n,o,l,h,c){let u=animation_Animation._PrepareAnimation(e,r,s,a,n,o,l,h);if(!u)return null;let d=t.getScene();return d.beginDirectHierarchyAnimation(t,i,[u],0,a,1===u.loopMode,1,c)}static CreateMergeAndStartAnimation(e,t,i,r,s,a,n,o,l,h){let c=animation_Animation._PrepareAnimation(e,i,r,s,a,n,o,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,s,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,r=!1,s){var a,n;let o;let l=e;if((o="object"==typeof t?t:{referenceFrame:null!=t?t:0,range:i,cloneOriginalAnimation:r,clonedAnimationName:s}).cloneOriginalAnimation&&((l=e.clone()).name=o.clonedAnimationName||l.name),!l._keys.length)return l;let h=o.referenceFrame&&o.referenceFrame>=0?o.referenceFrame:0,c=0,u=l._keys[0],d=l._keys.length-1,_=l._keys[d],f={referenceValue:u.value,referencePosition:math_vector_TmpVectors.Vector3[0],referenceQuaternion:math_vector_TmpVectors.Quaternion[0],referenceScaling:math_vector_TmpVectors.Vector3[1],keyPosition:math_vector_TmpVectors.Vector3[2],keyQuaternion:math_vector_TmpVectors.Quaternion[1],keyScaling:math_vector_TmpVectors.Vector3[3]},m=u.frame,g=_.frame;if(o.range){let e=l.getRange(o.range);e&&(m=e.from,g=e.to)}else m=null!==(a=o.fromFrame)&&void 0!==a?a:m,g=null!==(n=o.toFrame)&&void 0!==n?n:g;if(m!==u.frame&&(c=l.createKeyForFrame(m)),g!==_.frame&&(d=l.createKeyForFrame(g)),1===l._keys.length){let e=l._getKeyValue(l._keys[0]);f.referenceValue=e.clone?e.clone():e}else if(h<=u.frame){let e=l._getKeyValue(u.value);f.referenceValue=e.clone?e.clone():e}else if(h>=_.frame){let e=l._getKeyValue(_.value);f.referenceValue=e.clone?e.clone():e}else{p.key=0;let e=l._interpolate(h,p);f.referenceValue=e.clone?e.clone():e}l.dataType===animation_Animation.ANIMATIONTYPE_QUATERNION?f.referenceValue.normalize().conjugateInPlace():l.dataType===animation_Animation.ANIMATIONTYPE_MATRIX&&(f.referenceValue.decompose(f.referenceScaling,f.referenceQuaternion,f.referencePosition),f.referenceQuaternion.normalize().conjugateInPlace());let v=Number.MAX_VALUE,x=o.clipKeys?[]:null;for(let e=c;e<=d;e++){let t=l._keys[e];if(x&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},v===Number.MAX_VALUE&&(v=t.frame),t.frame-=v,x.push(t)),!e||l.dataType===animation_Animation.ANIMATIONTYPE_FLOAT||t.value!==u.value)switch(l.dataType){case animation_Animation.ANIMATIONTYPE_MATRIX:t.value.decompose(f.keyScaling,f.keyQuaternion,f.keyPosition),f.keyPosition.subtractInPlace(f.referencePosition),f.keyScaling.divideInPlace(f.referenceScaling),f.referenceQuaternion.multiplyToRef(f.keyQuaternion,f.keyQuaternion),math_vector_Matrix.ComposeToRef(f.keyScaling,f.keyQuaternion,f.keyPosition,t.value);break;case animation_Animation.ANIMATIONTYPE_QUATERNION:f.referenceValue.multiplyToRef(t.value,t.value);break;case animation_Animation.ANIMATIONTYPE_VECTOR2:case animation_Animation.ANIMATIONTYPE_VECTOR3:case animation_Animation.ANIMATIONTYPE_COLOR3:case animation_Animation.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(f.referenceValue,t.value);break;case animation_Animation.ANIMATIONTYPE_SIZE:t.value.width-=f.referenceValue.width,t.value.height-=f.referenceValue.height;break;default:t.value-=f.referenceValue}}return x&&l.setKeys(x,!0),l}static TransitionTo(e,t,i,r,s,a,n,o=null){if(n<=0)return i[e]=t,o&&o(),null;let l=s*(n/1e3);a.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(a);let h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=o,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(let e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,a){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=a,this._easingFunction=null,this._runtimeAnimations=[],this._events=[],this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=void 0===s?animation_Animation.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=animation_Animation._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType]+", nKeys: "+(this._keys?this._keys.length:"none")+", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((e,t)=>e.frame-t.frame)}removeEvents(e){for(let t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)}getEvents(){return this._events}createRange(e,t,i){this._ranges[e]||(this._ranges[e]=new AnimationRange(e,t,i))}deleteRange(e,t=!0){let i=this._ranges[e];if(i){if(t){let e=i.from,t=i.to;for(let i=this._keys.length-1;i>=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e}getEasingFunction(){return this._easingFunction}setEasingFunction(e){this._easingFunction=e}floatInterpolateFunction(e,t,i){return math_scalar_Scalar.Lerp(e,t,i)}floatInterpolateFunctionWithTangents(e,t,i,r,s){return math_scalar_Scalar.Hermite(e,t,i,r,s)}quaternionInterpolateFunction(e,t,i){return math_vector_Quaternion.Slerp(e,t,i)}quaternionInterpolateFunctionWithTangents(e,t,i,r,s){return math_vector_Quaternion.Hermite(e,t,i,r,s).normalize()}vector3InterpolateFunction(e,t,i){return math_vector_Vector3.Lerp(e,t,i)}vector3InterpolateFunctionWithTangents(e,t,i,r,s){return math_vector_Vector3.Hermite(e,t,i,r,s)}vector2InterpolateFunction(e,t,i){return math_vector_Vector2.Lerp(e,t,i)}vector2InterpolateFunctionWithTangents(e,t,i,r,s){return math_vector_Vector2.Hermite(e,t,i,r,s)}sizeInterpolateFunction(e,t,i){return Size.Lerp(e,t,i)}color3InterpolateFunction(e,t,i){return math_color_Color3.Lerp(e,t,i)}color3InterpolateFunctionWithTangents(e,t,i,r,s){return math_color_Color3.Hermite(e,t,i,r,s)}color4InterpolateFunction(e,t,i){return math_color_Color4.Lerp(e,t,i)}color4InterpolateFunctionWithTangents(e,t,i,r,s){return math_color_Color4.Hermite(e,t,i,r,s)}_getKeyValue(e){return"function"==typeof e?e():e}evaluate(e){return p.key=0,this._interpolate(e,p)}_interpolate(e,t,i=!1){if(t.loopMode===animation_Animation.ANIMATIONLOOPMODE_CONSTANT&&t.repeatCount>0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;let r=this._keys,s=r.length,a=t.key;for(;a>=0&&e<r[a].frame;)--a;for(;a+1<=s-1&&e>=r[a+1].frame;)++a;if(t.key=a,a<0)return i?void 0:this._getKeyValue(r[0].value);if(a+1>s-1)return i?void 0:this._getKeyValue(r[s-1].value);let n=r[a],o=r[a+1];if(i&&(e===n.frame||e===o.frame))return;let l=this._getKeyValue(n.value),h=this._getKeyValue(o.value);if(n.interpolation===K.STEP)return o.frame>e?l:h;let c=void 0!==n.outTangent&&void 0!==o.inTangent,u=o.frame-n.frame,d=(e-n.frame)/u,_=this.getEasingFunction();switch(null!==_&&(d=_.ease(d)),this.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:{let e=c?this.floatInterpolateFunctionWithTangents(l,n.outTangent*u,h,o.inTangent*u,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+e}break}case animation_Animation.ANIMATIONTYPE_QUATERNION:{let e=c?this.quaternionInterpolateFunctionWithTangents(l,n.outTangent.scale(u),h,o.inTangent.scale(u),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:break;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.addInPlace(t.offsetValue.scale(t.repeatCount))}return e}case animation_Animation.ANIMATIONTYPE_VECTOR3:{let e=c?this.vector3InterpolateFunctionWithTangents(l,n.outTangent.scale(u),h,o.inTangent.scale(u),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_VECTOR2:{let e=c?this.vector2InterpolateFunctionWithTangents(l,n.outTangent.scale(u),h,o.inTangent.scale(u),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_SIZE:switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(l,h,d).add(t.offsetValue.scale(t.repeatCount))}break;case animation_Animation.ANIMATIONTYPE_COLOR3:{let e=c?this.color3InterpolateFunctionWithTangents(l,n.outTangent.scale(u),h,o.inTangent.scale(u),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_COLOR4:{let e=c?this.color4InterpolateFunctionWithTangents(l,n.outTangent.scale(u),h,o.inTangent.scale(u),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:if(animation_Animation.AllowMatricesInterpolation)return this.matrixInterpolateFunction(l,h,d,t.workValue);return l;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return l}}return 0}matrixInterpolateFunction(e,t,i,r){return animation_Animation.AllowMatrixDecomposeForInterpolation?r?(math_vector_Matrix.DecomposeLerpToRef(e,t,i,r),r):math_vector_Matrix.DecomposeLerp(e,t,i):r?(math_vector_Matrix.LerpToRef(e,t,i,r),r):math_vector_Matrix.Lerp(e,t,i)}clone(){let e=new animation_Animation(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)for(let t in e._ranges={},this._ranges){let i=this._ranges[t];i&&(e._ranges[t]=i.clone())}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){p.key=0;let t=this._interpolate(e,p,!0);if(!t)return p.key===e?p.key:p.key+1;let i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(p.key+1,0,i),p.key+1}serialize(){let 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;let t=this.dataType;e.keys=[];let i=this.getKeys();for(let r=0;r<i.length;r++){let s=i[r],a={};switch(a.frame=s.frame,t){case animation_Animation.ANIMATIONTYPE_FLOAT:a.values=[s.value],void 0!==s.inTangent&&a.values.push(s.inTangent),void 0!==s.outTangent&&(void 0===s.inTangent&&a.values.push(void 0),a.values.push(s.outTangent)),void 0!==s.interpolation&&(void 0===s.inTangent&&a.values.push(void 0),void 0===s.outTangent&&a.values.push(void 0),a.values.push(s.interpolation));break;case animation_Animation.ANIMATIONTYPE_QUATERNION:case animation_Animation.ANIMATIONTYPE_MATRIX:case animation_Animation.ANIMATIONTYPE_VECTOR3:case animation_Animation.ANIMATIONTYPE_COLOR3:case animation_Animation.ANIMATIONTYPE_COLOR4:a.values=s.value.asArray(),void 0!=s.inTangent&&a.values.push(s.inTangent.asArray()),void 0!=s.outTangent&&(void 0===s.inTangent&&a.values.push(void 0),a.values.push(s.outTangent.asArray())),void 0!==s.interpolation&&(void 0===s.inTangent&&a.values.push(void 0),void 0===s.outTangent&&a.values.push(void 0),a.values.push(s.interpolation))}e.keys.push(a)}for(let t in e.ranges=[],this._ranges){let i=this._ranges[t];if(!i)continue;let r={};r.name=t,r.from=i.from,r.to=i.to,e.ranges.push(r)}return e}static _UniversalLerp(e,t,i){let r=e.constructor;return r.Lerp?r.Lerp(e,t,i):r.Slerp?r.Slerp(e,t,i):e.toFixed?e*(1-i)+i*t:t}static Parse(e){let t,i;let r=new animation_Animation(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior),s=e.dataType,a=[];for(e.enableBlending&&(r.enableBlending=e.enableBlending),e.blendingSpeed&&(r.blendingSpeed=e.blendingSpeed),i=0;i<e.keys.length;i++){let r,n,o;let l=e.keys[i];switch(s){case animation_Animation.ANIMATIONTYPE_FLOAT:t=l.values[0],l.values.length>=2&&(r=l.values[1]),l.values.length>=3&&(n=l.values[2]),l.values.length>=4&&(o=l.values[3]);break;case animation_Animation.ANIMATIONTYPE_QUATERNION:if(t=math_vector_Quaternion.FromArray(l.values),l.values.length>=8){let e=math_vector_Quaternion.FromArray(l.values.slice(4,8));e.equals(math_vector_Quaternion.Zero())||(r=e)}if(l.values.length>=12){let e=math_vector_Quaternion.FromArray(l.values.slice(8,12));e.equals(math_vector_Quaternion.Zero())||(n=e)}l.values.length>=13&&(o=l.values[12]);break;case animation_Animation.ANIMATIONTYPE_MATRIX:t=math_vector_Matrix.FromArray(l.values),l.values.length>=17&&(o=l.values[16]);break;case animation_Animation.ANIMATIONTYPE_COLOR3:t=math_color_Color3.FromArray(l.values),l.values[3]&&(r=math_color_Color3.FromArray(l.values[3])),l.values[4]&&(n=math_color_Color3.FromArray(l.values[4])),l.values[5]&&(o=l.values[5]);break;case animation_Animation.ANIMATIONTYPE_COLOR4:t=math_color_Color4.FromArray(l.values),l.values[4]&&(r=math_color_Color4.FromArray(l.values[4])),l.values[5]&&(n=math_color_Color4.FromArray(l.values[5])),l.values[6]&&(o=math_color_Color4.FromArray(l.values[6]));break;case animation_Animation.ANIMATIONTYPE_VECTOR3:default:t=math_vector_Vector3.FromArray(l.values),l.values[3]&&(r=math_vector_Vector3.FromArray(l.values[3])),l.values[4]&&(n=math_vector_Vector3.FromArray(l.values[4])),l.values[5]&&(o=l.values[5])}let h={};h.frame=l.frame,h.value=t,void 0!=r&&(h.inTangent=r),void 0!=n&&(h.outTangent=n),void 0!=o&&(h.interpolation=o),a.push(h)}if(r.setKeys(a),e.ranges)for(i=0;i<e.ranges.length;i++)t=e.ranges[i],r.createRange(t.name,t.from,t.to);return r}static AppendSerializedAnimations(e,t){decorators_SerializationHelper.AppendSerializedAnimations(e,t)}static ParseFromFileAsync(e,t){return new Promise((i,r)=>{let s=new webRequest_WebRequest;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){let e=[];for(let i of t)e.push(this.Parse(i));i(e)}else{let r=this.Parse(t);e&&(r.name=e),i(r)}}else r("Unable to load the animation")}}),s.open("GET",t),s.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{let r=new webRequest_WebRequest;r.addEventListener("readystatechange",()=>{if(4==r.readyState){if(200==r.status){let i=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(i.animations){let r=JSON.parse(i.animations),s=[];for(let t of r.animations){let i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{let r=JSON.parse(i.animation),s=this.Parse(r);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)}}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}};animation_Animation._UniqueIdGenerator=0,animation_Animation.AllowMatricesInterpolation=!1,animation_Animation.AllowMatrixDecomposeForInterpolation=!0,animation_Animation.SnippetUrl="https://snippet.babylonjs.com",animation_Animation.ANIMATIONTYPE_FLOAT=0,animation_Animation.ANIMATIONTYPE_VECTOR3=1,animation_Animation.ANIMATIONTYPE_QUATERNION=2,animation_Animation.ANIMATIONTYPE_MATRIX=3,animation_Animation.ANIMATIONTYPE_COLOR3=4,animation_Animation.ANIMATIONTYPE_COLOR4=7,animation_Animation.ANIMATIONTYPE_VECTOR2=5,animation_Animation.ANIMATIONTYPE_SIZE=6,animation_Animation.ANIMATIONLOOPMODE_RELATIVE=0,animation_Animation.ANIMATIONLOOPMODE_CYCLE=1,animation_Animation.ANIMATIONLOOPMODE_CONSTANT=2,animation_Animation.ANIMATIONLOOPMODE_YOYO=4,animation_Animation.CreateFromSnippetAsync=animation_Animation.ParseFromSnippetAsync,h["BABYLON.Animation"]=animation_Animation,node_Node._AnimationRangeFactory=(e,t,i)=>new AnimationRange(e,t,i);let InterpolateValueAction=class InterpolateValueAction extends Action{constructor(e,t,i,r,s=1e3,a,n,o){super(e,a),this.duration=1e3,this.onInterpolationDoneObservable=new observable_Observable,this.propertyPath=i,this.value=r,this.duration=s,this.stopOtherAnimations=n,this.onInterpolationDone=o,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){let e;let t=this._actionManager.getScene(),i=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)e=animation_Animation.ANIMATIONTYPE_FLOAT;else if(this.value instanceof math_color_Color3)e=animation_Animation.ANIMATIONTYPE_COLOR3;else if(this.value instanceof math_vector_Vector3)e=animation_Animation.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof math_vector_Matrix)e=animation_Animation.ANIMATIONTYPE_MATRIX;else if(this.value instanceof math_vector_Quaternion)e=animation_Animation.ANIMATIONTYPE_QUATERNION;else{logger_Logger.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}let r=new animation_Animation("InterpolateValueAction",this._property,100*(1e3/this.duration),e,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);r.setKeys(i),this.stopOtherAnimations&&t.stopAnimation(this._effectiveTarget),t.beginDirectAnimation(this._effectiveTarget,[r],0,100,!1,1,()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()})}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)},{name:"duration",value:Action._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Action._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}};h["BABYLON.InterpolateValueAction"]=InterpolateValueAction;let f=Object.freeze(new math_vector_Quaternion(0,0,0,0)),m=Object.freeze(math_vector_Vector3.Zero()),g=Object.freeze(math_vector_Vector2.Zero()),v=Object.freeze(Size.Zero()),x=Object.freeze(math_color_Color3.Black());let RuntimeAnimation=class RuntimeAnimation{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,r){if(this._events=[],this._currentFrame=0,this._originalValue=[],this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===animation_Animation.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=math_vector_Matrix.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){let e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(let 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];let 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){let i=this._animation.targetPropertyPath;if(i.length>1){let r=e[i[0]];for(let e=1;e<i.length-1;e++)r=r[i[e]];this._targetPath=i[i.length-1],this._activeTargets[t]=r}else this._targetPath=i[0],this._activeTargets[t]=e}get animation(){return this._animation}reset(e=!1){if(e){if(this._target instanceof Array){let e=0;for(let t of this._target)void 0!==this._originalValue[e]&&this._setValue(t,this._activeTargets[e],this._originalValue[e],-1,e),e++}else void 0!==this._originalValue[0]&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0)}this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(let e=0;e<this._events.length;e++)this._events[e].isDone=!1}isStopped(){return this._stopped}dispose(){let e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;i<this._target.length;i++){let r=this._target[i];this._setValue(r,this._activeTargets[i],e,t,i)}return}this._setValue(this._target,this._directTarget,e,t,0)}_getOriginalValues(e=0){let t;let i=this._activeTargets[e];(t=i.getLocalMatrix&&"_matrix"===this._targetPath?i.getLocalMatrix():i[this._targetPath])&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t}_setValue(e,t,i,r,s){if(this._currentActiveTarget=t,this._weight=r,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){let e=t[this._targetPath];e.clone?this._originalBlendValue=e.clone():this._originalBlendValue=e}this._originalBlendValue.m?animation_Animation.AllowMatrixDecomposeForInterpolation?this._currentValue?math_vector_Matrix.DecomposeLerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=math_vector_Matrix.DecomposeLerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue?math_vector_Matrix.LerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=math_vector_Matrix.Lerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue=animation_Animation._UniversalLerp(this._originalBlendValue,i,this._blendingFactor);let r=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=r}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(i):this._currentValue=i:(null==i?void 0:i.clone)?this._currentValue=i.clone():this._currentValue=i;-1!==r?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[s]):t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)}_getCorrectLoopMode(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode}goToFrame(e){let t=this._animation.getKeys();e<t[0].frame?e=t[0].frame:e>t[t.length-1].frame&&(e=t[t.length-1].frame);let i=this._events;if(i.length)for(let t=0;t<i.length;t++)i[t].onlyOnce||(i[t].isDone=i[t].frame<e);this._currentFrame=e;let r=this._animation._interpolate(e,this._animationState);this.setValue(r,-1)}_prepareForSpeedRatioChange(e){let t=this._previousElapsedTime*(this._animation.framePerSecond*e)/1e3;this._absoluteFrameOffset=this._previousAbsoluteFrame-t}animate(e,t,i,r,s,a=-1){let n,o;let l=this._animation,h=l.targetPropertyPath;if(!h||h.length<1)return this._stopped=!0,!1;let c=!0;(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(i<this._minFrame||i>this._maxFrame)&&(i=this._maxFrame);let u=i-t,d=e*(l.framePerSecond*s)/1e3+this._absoluteFrameOffset,_=0;if(r&&this._animationState.loopMode===animation_Animation.ANIMATIONLOOPMODE_YOYO){let e=(d-t)/u;d=Math.abs(Math.sin(e*Math.PI))*u+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&d>=u)c=!1,_=l._getKeyValue(this._maxValue);else if(!r&&t>=i&&d<=u)c=!1,_=l._getKeyValue(this._minValue);else if(this._animationState.loopMode!==animation_Animation.ANIMATIONLOOPMODE_CYCLE){let e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=animation_Animation.ANIMATIONLOOPMODE_CYCLE;let r=l._interpolate(t,this._animationState),s=l._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),l.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=s-r;break;case animation_Animation.ANIMATIONTYPE_QUATERNION:case animation_Animation.ANIMATIONTYPE_VECTOR3:case animation_Animation.ANIMATIONTYPE_VECTOR2:case animation_Animation.ANIMATIONTYPE_SIZE:case animation_Animation.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=s.subtract(r)}this._highLimitsCache[e]=s}_=this._highLimitsCache[e],n=this._offsetsCache[e]}if(void 0===n)switch(l.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:n=0;break;case animation_Animation.ANIMATIONTYPE_QUATERNION:n=f;break;case animation_Animation.ANIMATIONTYPE_VECTOR3:n=m;break;case animation_Animation.ANIMATIONTYPE_VECTOR2:n=g;break;case animation_Animation.ANIMATIONTYPE_SIZE:n=v;break;case animation_Animation.ANIMATIONTYPE_COLOR3:n=x}if(this._host&&this._host.syncRoot){let e=this._host.syncRoot,i=(e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame);o=t+u*i}else o=d>0&&t>i||d<0&&t<i?c&&0!==u?i+d%u:t:c&&0!==u?t+d%u:i;let p=this._events;if(s>0&&this.currentFrame>o||s<0&&this.currentFrame<o){this._onLoop();for(let e=0;e<p.length;e++)p[e].onlyOnce||(p[e].isDone=!1);this._animationState.key=s>0?0:l.getKeys().length-1}this._currentFrame=o,this._animationState.repeatCount=0===u?0:d/u>>0,this._animationState.highLimitValue=_,this._animationState.offsetValue=n;let b=l._interpolate(o,this._animationState);if(this.setValue(b,a),p.length){for(let e=0;e<p.length;e++)if(u>0&&o>=p[e].frame&&p[e].frame>=t||u<0&&o<=p[e].frame&&p[e].frame<=t){let t=p[e];t.isDone||(t.onlyOnce&&(p.splice(e,1),e--),t.isDone=!0,t.action(o))}}return c||(this._stopped=!0),c}};function IsWindowObjectExist(){return"undefined"!=typeof window}function IsNavigatorAvailable(){return"undefined"!=typeof navigator}function IsDocumentAvailable(){return"undefined"!=typeof document}function GetDOMTextContent(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}let precisionDate_PrecisionDate=class precisionDate_PrecisionDate{static get Now(){return IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()}};let filesInputStore_FilesInputStore=class filesInputStore_FilesInputStore{};filesInputStore_FilesInputStore.FilesToLoad={};let RetryStrategy=class RetryStrategy{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>0!==r.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}};let BaseError=class BaseError extends Error{};BaseError._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));let b={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};let RuntimeError=class RuntimeError extends BaseError{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",BaseError._setPrototypeOf(this,RuntimeError.prototype)}};let stringTools_EncodeArrayBufferToBase64=e=>{let t,i,r,s,a,n,o;let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",c=0,u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c<u.length;)t=u[c++],i=c<u.length?u[c++]:Number.NaN,r=c<u.length?u[c++]:Number.NaN,s=t>>2,a=(3&t)<<4|i>>4,n=(15&i)<<2|r>>6,o=63&r,isNaN(i)?n=o=64:isNaN(r)&&(o=64),h+=l.charAt(s)+l.charAt(a)+l.charAt(n)+l.charAt(o);return h},DecodeBase64ToString=e=>atob(e),stringTools_DecodeBase64ToBinary=e=>{let t=DecodeBase64ToString(e),i=t.length,r=new Uint8Array(new ArrayBuffer(i));for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r.buffer};let ShaderCodeNode=class ShaderCodeNode{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,r,s,a,n,o,l;let h="";if(this.line){let c=this.line,u=t.processor;if(u){u.lineProcessor&&(c=u.lineProcessor(c,t.isFragment,t.processingContext));let h=null!==(r=null===(i=t.processor)||void 0===i?void 0:i.attributeKeywordName)&&void 0!==r?r:"attribute",d=t.isFragment&&(null===(s=t.processor)||void 0===s?void 0:s.varyingFragmentKeywordName)?null===(a=t.processor)||void 0===a?void 0:a.varyingFragmentKeywordName:!t.isFragment&&(null===(n=t.processor)||void 0===n?void 0:n.varyingVertexKeywordName)?null===(o=t.processor)||void 0===o?void 0:o.varyingVertexKeywordName:"varying";!t.isFragment&&u.attributeProcessor&&this.line.startsWith(h)?c=u.attributeProcessor(this.line,e,t.processingContext):u.varyingProcessor&&((null===(l=u.varyingCheck)||void 0===l?void 0:l.call(u,this.line,t.isFragment))||!u.varyingCheck&&this.line.startsWith(d))?c=u.varyingProcessor(this.line,t.isFragment,e,t.processingContext):u.uniformProcessor&&u.uniformRegexp&&u.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(c=u.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):u.uniformBufferProcessor&&u.uniformBufferRegexp&&u.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(c=u.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):u.textureProcessor&&u.textureRegexp&&u.textureRegexp.test(this.line)?c=u.textureProcessor(this.line,t.isFragment,e,t.processingContext):(u.uniformProcessor||u.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?u.uniformProcessor&&(c=u.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):u.uniformBufferProcessor&&(c=u.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,u.endOfUniformBufferProcessor&&(c=u.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}h+=c+"\n"}return this.children.forEach(i=>{h+=i.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),h}};let ShaderCodeCursor=class ShaderCodeCursor{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex<this._lines.length-1}set lines(e){for(let t of(this._lines.length=0,e)){if(!t||"\r"===t)continue;if("#"===t[0]){this._lines.push(t);continue}let e=t.trim();if(!e)continue;if(e.startsWith("//")){this._lines.push(t);continue}let i=e.indexOf(";");if(-1===i)this._lines.push(e);else if(i===e.length-1)e.length>1&&this._lines.push(e);else{let e=t.split(";");for(let t=0;t<e.length;t++){let i=e[t];i&&(i=i.trim())&&this._lines.push(i+(t!==e.length-1?";":""))}}}}};let ShaderCodeConditionNode=class ShaderCodeConditionNode extends ShaderCodeNode{process(e,t){for(let i=0;i<this.children.length;i++){let r=this.children[i];if(r.isValid(e))return r.process(e,t)}return""}};let ShaderCodeTestNode=class ShaderCodeTestNode extends ShaderCodeNode{isValid(e){return this.testExpression.isTrue(e)}};let ShaderDefineExpression=class ShaderDefineExpression{isTrue(e){return!0}static postfixToInfix(e){let t=[];for(let i of e)if(void 0===ShaderDefineExpression._OperatorPriority[i])t.push(i);else{let e=t[t.length-1],r=t[t.length-2];t.length-=2,t.push(`(${r}${i}${e})`)}return t[t.length-1]}static infixToPostfix(e){let t=ShaderDefineExpression._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!e.includes("&&")&&!e.includes("||")&&!e.includes(")")&&!e.includes("("))return[e];let i=[],r=-1,pushOperand=()=>{""!==(a=a.trim())&&(i.push(a),a="")},push=e=>{r<ShaderDefineExpression._Stack.length-1&&(ShaderDefineExpression._Stack[++r]=e)},peek=()=>ShaderDefineExpression._Stack[r],pop=()=>-1===r?"!!INVALID EXPRESSION!!":ShaderDefineExpression._Stack[r--],s=0,a="";for(;s<e.length;){let t=e.charAt(s),n=s<e.length-1?e.substr(s,2):"";if("("===t)a="",push(t);else if(")"===t){for(pushOperand();-1!==r&&"("!==peek();)i.push(pop());pop()}else if(ShaderDefineExpression._OperatorPriority[n]>1){for(pushOperand();-1!==r&&ShaderDefineExpression._OperatorPriority[peek()]>=ShaderDefineExpression._OperatorPriority[n];)i.push(pop());push(n),s++}else a+=t;s++}for(pushOperand();-1!==r;)"("===peek()?pop():i.push(pop());return ShaderDefineExpression._InfixToPostfixCache.size>=ShaderDefineExpression.InfixToPostfixCacheLimitSize&&ShaderDefineExpression.ClearCache(),ShaderDefineExpression._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){let e=Array.from(ShaderDefineExpression._InfixToPostfixCache.entries()).sort((e,t)=>e[1].accessTime-t[1].accessTime);for(let t=0;t<ShaderDefineExpression.InfixToPostfixCacheCleanupSize;t++)ShaderDefineExpression._InfixToPostfixCache.delete(e[t][0])}};ShaderDefineExpression.InfixToPostfixCacheLimitSize=5e4,ShaderDefineExpression.InfixToPostfixCacheCleanupSize=25e3,ShaderDefineExpression._InfixToPostfixCache=new Map,ShaderDefineExpression._OperatorPriority={")":0,"(":1,"||":2,"&&":3},ShaderDefineExpression._Stack=["","","","","","","","","","","","","","","","","","","",""];let ShaderDefineIsDefinedOperator=class ShaderDefineIsDefinedOperator extends ShaderDefineExpression{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=void 0!==e[this.define];return this.not&&(t=!t),t}};let ShaderDefineOrOperator=class ShaderDefineOrOperator extends ShaderDefineExpression{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}};let ShaderDefineAndOperator=class ShaderDefineAndOperator extends ShaderDefineExpression{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}};let ShaderDefineArithmeticOperator=class ShaderDefineArithmeticOperator extends ShaderDefineExpression{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}isTrue(e){let t=e[this.define];void 0===t&&(t=this.define);let i=!1,r=parseInt(t),s=parseInt(this.testValue);switch(this.operand){case">":i=r>s;break;case"<":i=r<s;break;case"<=":i=r<=s;break;case">=":i=r>=s;break;case"==":i=r===s;break;case"!=":i=r!==s}return i}};!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(q||(q={}));let T=/defined\s*?\((.+?)\)/g,S=/defined\s*?\[(.+?)\]/g,C=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,E=/__decl__/,y=/light\{X\}.(\w*)/g,R=/\{X\}/g,P=[];let ShaderProcessor=class ShaderProcessor{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,r){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));let s=this._ProcessShaderConversion(e,t,r);i(s,e)})}static PreProcess(e,t,i,r){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));let s=this._ApplyPreProcessing(e,t,r);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;let r=t.shouldUseHighPrecisionShader;return -1===e.indexOf("precision highp float")?e=r?"precision highp float;\n"+e:"precision mediump float;\n"+e:r||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){let t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new ShaderDefineIsDefinedOperator(t[1].trim(),"!"===e[0]);let i="",r=0;for(i of["==","!=",">=","<=","<",">"])if((r=e.indexOf(i))>-1)break;if(-1===r)return new ShaderDefineIsDefinedOperator(e);let s=e.substring(0,r).trim(),a=e.substring(r+i.length).trim();return new ShaderDefineArithmeticOperator(s,i,a)}static _BuildSubExpression(e){e=e.replace(T,"defined[$1]");let t=ShaderDefineExpression.infixToPostfix(e),i=[];for(let e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],r=i[i.length-2];i.length-=2;let s="&&"==e?new ShaderDefineAndOperator:new ShaderDefineOrOperator;"string"==typeof t&&(t=t.replace(S,"defined($1)")),"string"==typeof r&&(r=r.replace(S,"defined($1)")),s.leftOperand="string"==typeof r?this._ExtractOperation(r):r,s.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(s)}let r=i[i.length-1];return"string"==typeof r&&(r=r.replace(S,"defined($1)")),"string"==typeof r?this._ExtractOperation(r):r}static _BuildExpression(e,t){let i=new ShaderCodeTestNode,r=e.substring(0,t),s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),"#ifdef"===r?i.testExpression=new ShaderDefineIsDefinedOperator(s):"#ifndef"===r?i.testExpression=new ShaderDefineIsDefinedOperator(s,!0):i.testExpression=this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let r=e.currentLine;for(;this._MoveCursor(e,i);){r=e.currentLine;let s=r.substring(0,5).toLowerCase();if("#else"===s){let i=new ShaderCodeNode;t.children.push(i),this._MoveCursor(e,i);return}if("#elif"===s){let e=this._BuildExpression(r,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;let i=e.currentLine;if(i.indexOf("#")>=0){let r=ShaderProcessor._MoveCursorRegex.exec(i);if(r&&r.length){let s=r[0];switch(s){case"#ifdef":{let r=new ShaderCodeConditionNode;t.children.push(r);let s=this._BuildExpression(i,6);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{let r=new ShaderCodeConditionNode;t.children.push(r);let s=this._BuildExpression(i,7);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#if":{let r=new ShaderCodeConditionNode,s=this._BuildExpression(i,3);t.children.push(r),r.children.push(s),this._MoveCursorWithinIf(e,r,s)}}continue}}let r=new ShaderCodeNode;if(r.line=i,t.children.push(r),"#"===i[0]&&"d"===i[1]){let e=i.replace(";","").split(" ");r.additionalDefineKey=e[1],3===e.length&&(r.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){let r=new ShaderCodeNode,s=new ShaderCodeCursor;return s.lineIndex=-1,s.lines=e.split("\n"),this._MoveCursor(s,r),r.process(t,i)}static _PreparePreProcessors(e,t){var i;let r=e.defines,s={};for(let e of r){let t=e.replace("#define","").replace(";","").trim(),i=t.split(" ");s[i[0]]=i.length>1?i[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===q.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let r=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===q.GLSL&&-1!==r.indexOf("#version 3")&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;let s=t.defines,a=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,s,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,a,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ApplyPreProcessing(e,t,i){var r,s;let a=e,n=t.defines,o=this._PreparePreProcessors(t,i);return(null===(r=t.processor)||void 0===r?void 0:r.preProcessor)&&(a=t.processor.preProcessor(a,n,t.isFragment,t.processingContext)),a=this._EvaluatePreProcessors(a,o,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(a=t.processor.postProcessor(a,n,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(a=i.inlineShaderCode(a)),a}static _ProcessIncludes(e,t,i){let r;for(P.length=0;null!==(r=C.exec(e));)P.push(r);let s=String(e),a=[e],n=!1;for(let e of P){let r=e[1];if(-1!==r.indexOf("__decl__")&&(r=r.replace(E,""),t.supportsUniformBuffers&&(r=r.replace("Vertex","Ubo").replace("Fragment","Ubo")),r+="Declaration"),t.includesShadersStore[r]){let i=t.includesShadersStore[r];if(e[2]){let t=e[3].split(",");for(let e=0;e<t.length;e+=2){let r=RegExp(t[e],"g"),s=t[e+1];i=i.replace(r,s)}}if(e[4]){let r=e[5];if(-1!==r.indexOf("..")){let e=r.split(".."),s=parseInt(e[0]),a=parseInt(e[1]),n=i.slice(0);i="",isNaN(a)&&(a=t.indexParameters[e[1]]);for(let e=s;e<a;e++)t.supportsUniformBuffers||(n=n.replace(y,(e,t)=>t+"{X}")),i+=n.replace(R,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(y,(e,t)=>t+"{X}")),i=i.replace(R,r)}let s=[];for(let t of a){let r=t.split(e[0]);for(let e=0;e<r.length-1;e++)s.push(r[e]),s.push(i);s.push(r[r.length-1])}a=s,n=n||i.indexOf("#include<")>=0||i.indexOf("#include <")>=0}else{let e=t.shadersRepository+"ShadersInclude/"+r+".fx";ShaderProcessor._FileToolsLoadFile(e,e=>{t.includesShadersStore[r]=e,this._ProcessIncludes(a.join(""),t,i)});return}}P.length=0,s=a.join(""),n?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,r,s,a){throw _WarnImport("FileTools")}};ShaderProcessor._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;let ShaderStore=class ShaderStore{static GetShadersRepository(e=q.GLSL){return e===q.GLSL?ShaderStore.ShadersRepository:ShaderStore.ShadersRepositoryWGSL}static GetShadersStore(e=q.GLSL){return e===q.GLSL?ShaderStore.ShadersStore:ShaderStore.ShadersStoreWGSL}static GetIncludesShadersStore(e=q.GLSL){return e===q.GLSL?ShaderStore.IncludesShadersStore:ShaderStore.IncludesShadersStoreWGSL}};ShaderStore.ShadersRepository="src/Shaders/",ShaderStore.ShadersStore={},ShaderStore.IncludesShadersStore={},ShaderStore.ShadersRepositoryWGSL="src/ShadersWGSL/",ShaderStore.ShadersStoreWGSL={},ShaderStore.IncludesShadersStoreWGSL={};let effect_Effect=class effect_Effect{static get ShadersRepository(){return ShaderStore.ShadersRepository}static set ShadersRepository(e){ShaderStore.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new observable_Observable),this._onBindObservable}constructor(e,t,i,r=null,s,a=null,n=null,o=null,l=null,h,c="",u=q.GLSL){var d,_,p;if(this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new observable_Observable,this.onErrorObservable=new observable_Observable,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._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=c,t.attributes){if(this._engine=i,this._attributesNames=t.attributes,this._uniformsNames=t.uniformsNames.concat(t.samplers),this._samplerList=t.samplers.slice(),this.defines=t.defines,this.onError=t.onError,this.onCompiled=t.onCompiled,this._fallbacks=t.fallbacks,this._indexParameters=t.indexParameters,this._transformFeedbackVaryings=t.transformFeedbackVaryings||null,this._multiTarget=!!t.multiTarget,this._shaderLanguage=null!==(d=t.shaderLanguage)&&void 0!==d?d:q.GLSL,t.uniformBuffersNames){this._uniformBuffersNamesList=t.uniformBuffersNames.slice();for(let e=0;e<t.uniformBuffersNames.length;e++)this._uniformBuffersNames[t.uniformBuffersNames[e]]=e}this._processFinalCode=null!==(_=t.processFinalCode)&&void 0!==_?_:null,this._processCodeAfterIncludes=null!==(p=t.processCodeAfterIncludes)&&void 0!==p?p:void 0}else this._engine=s,this.defines=null==a?"":a,this._uniformsNames=i.concat(r),this._samplerList=r?r.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=u,this.onError=l,this.onCompiled=o,this._indexParameters=h,this._fallbacks=n;this._attributeLocationByName={},this.uniqueId=effect_Effect._UniqueIdSeed++,this._processShaderCode()}_processShaderCode(e=null,t=!1){let i,r;let s=this.name,a=IsWindowObjectExist()?this._engine.getHostDocument():null;s.vertexSource?i="source:"+s.vertexSource:s.vertexElement?(i=a?a.getElementById(s.vertexElement):null)||(i=s.vertexElement):i=s.vertex||s,s.fragmentSource?r="source:"+s.fragmentSource:s.fragmentElement?(r=a?a.getElementById(s.fragmentElement):null)||(r=s.fragmentElement):r=s.fragment||s,this._processingContext=this._engine._getShaderProcessingContext(this._shaderLanguage);let n={defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:null!=e?e:this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:ShaderStore.GetShadersRepository(this._shaderLanguage),includesShadersStore:ShaderStore.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes},o=[void 0,void 0],shadersLoaded=()=>{if(o[0]&&o[1]){n.isFragment=!0;let[e,i]=o;ShaderProcessor.Process(i,n,(i,r)=>{this._fragmentSourceCodeBeforeMigration=r,this._processFinalCode&&(i=this._processFinalCode("fragment",i));let a=ShaderProcessor.Finalize(e,i,n);n=null,this._useFinalCode(a.vertexCode,a.fragmentCode,s,t)},this._engine)}};this._loadShader(i,"Vertex","",e=>{ShaderProcessor.Initialize(n),ShaderProcessor.Process(e,n,(t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,this._processFinalCode&&(t=this._processFinalCode("vertex",t)),o[0]=t,shadersLoaded()},this._engine)}),this._loadShader(r,"Fragment","Pixel",e=>{this._rawFragmentSourceCode=e,o[1]=e,shadersLoaded()})}_useFinalCode(e,t,i,r=!1){if(i){let r=i.vertexElement||i.vertex||i.spectorName||i,s=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===q.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===q.WGSL?"//":"")+"#define SHADER_NAME fragment:"+s+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect(r)}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){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let s;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){let t=GetDOMTextContent(e);r(t);return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){let t=window.atob(e.substr(7));r(t);return}let a=ShaderStore.GetShadersStore(this._shaderLanguage);if(a[e+t+"Shader"]){r(a[e+t+"Shader"]);return}if(i&&a[e+i+"Shader"]){r(a[e+i+"Shader"]);return}s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:ShaderStore.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}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,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{r&&r(t)},this.onCompiled=()=>{let e=this.getEngine().scenes;if(e)for(let t=0;t<e.length;t++)e[t].markAllMaterialsAsDirty(63);this._pipelineContext._handlesSpectorRebuildCallback(i)},this._fallbacks=null,this._prepareEffect()}_prepareEffect(e=!1){var t;let i=this._attributesNames,r=this.defines,s=this._pipelineContext;this._isReady=!1;try{let a=this._engine;this._pipelineContext=null!==(t=e?s:void 0)&&void 0!==t?t:a.createPipelineContext(this._processingContext),this._pipelineContext._name=this._key.replace(/\r/g,"").replace(/\n/g,"|");let rebuildRebind=(e,t,i,r)=>this._rebuildProgram(e,t,i,r);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?a._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,rebuildRebind,null,this._transformFeedbackVaryings,this._key):a._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,rebuildRebind,r,this._transformFeedbackVaryings,this._key),a._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,i,this._attributes),i)for(let e=0;e<i.length;e++){let t=i[e];this._attributeLocationByName[t]=this._attributes[e]}a.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh(),s&&!e&&this.getEngine()._deletePipelineContext(s)}),this._pipelineContext.isAsync&&this._checkIsReady(s)}catch(e){this._processCompilationErrors(e,s)}}_getShaderCodeAndErrorLine(e,t,i){let r=null;if(t&&e){let s=t.match(i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/);if(s&&2===s.length){let t=parseInt(s[1]),a=e.split("\n",-1);a.length>=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${a[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i,r,s;this._compilationError=e.message;let a=this._attributesNames,n=this._fallbacks;if(logger_Logger.Error("Unable to compile effect:"),logger_Logger.Error("Uniforms: "+this._uniformsNames.map(function(e){return" "+e})),logger_Logger.Error("Attributes: "+a.map(function(e){return" "+e})),logger_Logger.Error("Defines:\n"+this.defines),effect_Effect.LogShaderCodeOnCompilationError){let e=null,t=null,a=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([a,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),a&&(logger_Logger.Error("Vertex code:"),logger_Logger.Error(a))),(null===(r=this._pipelineContext)||void 0===r?void 0:r._getFragmentShaderCode())&&([a,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),a&&(logger_Logger.Error("Fragment code:"),logger_Logger.Error(a))),e&&logger_Logger.Error(e),t&&logger_Logger.Error(t)}logger_Logger.Error("Error: "+this._compilationError);let notifyErrors=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,notifyErrors()),n?(this._pipelineContext=null,n.hasMoreFallbacks?(this._allFallbacksProcessed=!1,logger_Logger.Error("Trying next fallback."),this.defines=n.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,notifyErrors(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||notifyErrors())}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){let i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){let r=this._samplerList.indexOf(e);for(let e=1;e<t.length;e++){let t=i+(e-1).toString();this._samplerList.splice(r+e,0,t)}let s=0;for(let e of this._samplerList)this._samplers[e]=s,s+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}setTextureFromPostProcess(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)}setTextureFromPostProcessOutput(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)}bindUniformBuffer(e,t){let i=this._uniformBuffersNames[t];void 0===i||effect_Effect._BaseCache[i]===e&&this._engine._features.useUBOBindingCache||(effect_Effect._BaseCache[i]=e,this._engine.bindUniformBufferBase(e,i,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setInt3(e,t,i,r){return this._pipelineContext.setInt3(e,t,i,r),this}setInt4(e,t,i,r,s){return this._pipelineContext.setInt4(e,t,i,r,s),this}setIntArray(e,t){return this._pipelineContext.setIntArray(e,t),this}setIntArray2(e,t){return this._pipelineContext.setIntArray2(e,t),this}setIntArray3(e,t){return this._pipelineContext.setIntArray3(e,t),this}setIntArray4(e,t){return this._pipelineContext.setIntArray4(e,t),this}setUInt(e,t){return this._pipelineContext.setUInt(e,t),this}setUInt2(e,t,i){return this._pipelineContext.setUInt2(e,t,i),this}setUInt3(e,t,i,r){return this._pipelineContext.setUInt3(e,t,i,r),this}setUInt4(e,t,i,r,s){return this._pipelineContext.setUInt4(e,t,i,r,s),this}setUIntArray(e,t){return this._pipelineContext.setUIntArray(e,t),this}setUIntArray2(e,t){return this._pipelineContext.setUIntArray2(e,t),this}setUIntArray3(e,t){return this._pipelineContext.setUIntArray3(e,t),this}setUIntArray4(e,t){return this._pipelineContext.setUIntArray4(e,t),this}setFloatArray(e,t){return this._pipelineContext.setArray(e,t),this}setFloatArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setFloatArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setFloatArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setArray(e,t){return this._pipelineContext.setArray(e,t),this}setArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setMatrices(e,t){return this._pipelineContext.setMatrices(e,t),this}setMatrix(e,t){return this._pipelineContext.setMatrix(e,t),this}setMatrix3x3(e,t){return this._pipelineContext.setMatrix3x3(e,t),this}setMatrix2x2(e,t){return this._pipelineContext.setMatrix2x2(e,t),this}setFloat(e,t){return this._pipelineContext.setFloat(e,t),this}setBool(e,t){return this._pipelineContext.setInt(e,t?1:0),this}setVector2(e,t){return this._pipelineContext.setVector2(e,t),this}setFloat2(e,t,i){return this._pipelineContext.setFloat2(e,t,i),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,i,r){return this._pipelineContext.setFloat3(e,t,i,r),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,i,r,s){return this._pipelineContext.setFloat4(e,t,i,r,s),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,i){return this._pipelineContext.setColor4(e,t,i),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseEffect(this),this._isDisposed=!0}static RegisterShader(e,t,i,r=q.GLSL){t&&(ShaderStore.GetShadersStore(r)[`${e}PixelShader`]=t),i&&(ShaderStore.GetShadersStore(r)[`${e}VertexShader`]=i)}static ResetCache(){effect_Effect._BaseCache={}}};effect_Effect.LogShaderCodeOnCompilationError=!0,effect_Effect._UniqueIdSeed=0,effect_Effect._BaseCache={},effect_Effect.ShadersStore=ShaderStore.ShadersStore,effect_Effect.IncludesShadersStore=ShaderStore.IncludesShadersStore;let DepthCullingState=class DepthCullingState{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}};let StencilState=class StencilState{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=StencilState.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=StencilState.KEEP,this.opDepthFail=StencilState.KEEP,this.opStencilDepthPass=StencilState.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}};StencilState.ALWAYS=519,StencilState.KEEP=7680,StencilState.REPLACE=7681;let AlphaState=class AlphaState{constructor(){this._blendFunctionParameters=[,,,,],this._blendEquationParameters=[,,],this._blendConstants=[,,,,],this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,r){(this._blendConstants[0]!==e||this._blendConstants[1]!==t||this._blendConstants[2]!==i||this._blendConstants[3]!==r)&&(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=r,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,r){(this._blendFunctionParameters[0]!==e||this._blendFunctionParameters[1]!==t||this._blendFunctionParameters[2]!==i||this._blendFunctionParameters[3]!==r)&&(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=r,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){(this._blendEquationParameters[0]!==e||this._blendEquationParameters[1]!==t)&&(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}};let TextureSampler=class TextureSampler{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,r=1,s=2,a=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=s,this._comparisonFunction=a,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}};!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"}($||($={}));let internalTexture_InternalTexture=class internalTexture_InternalTexture extends TextureSampler{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 observable_Observable,this.onErrorObservable=new observable_Observable,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=$.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=internalTexture_InternalTexture._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;let t;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){let e=this.onRebuildCallback(this),swapAndSetIsReady=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};e.isAsync?e.proxy.then(swapAndSetIsReady):swapAndSetIsReady(e.proxy);return}switch(this.source){case $.Temp:break;case $.Url: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);return;case $.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))._swapAndDie(this,!1),this.isReady=!0;break;case $.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))._swapAndDie(this,!1),this.isReady=!0;break;case $.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))._swapAndDie(this,!1),this.isReady=!0;break;case $.Dynamic:(t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode))._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case $.Cube: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);return;case $.CubeRaw:(t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this,!1),this.isReady=!0;break;case $.CubeRawRGBD:return;case $.CubePrefiltered:(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))._sphericalPolynomial=this._sphericalPolynomial;return}}_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);let r=this._engine.getLoadedTexturesCache(),s=r.indexOf(this);-1!==s&&r.splice(s,1),-1===(s=r.indexOf(e))&&r.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}};internalTexture_InternalTexture._Counter=0;let WebGLShaderProcessor=class WebGLShaderProcessor{constructor(){this.shaderLanguage=q.GLSL}postProcessor(e,t,i,r,s){return s.getCaps().drawBuffersExtension||(e=e.replace(/#extension.+GL_EXT_draw_buffers.+(enable|require)/g,"")),e}};let A=/(flat\s)?\s*varying\s*.*/;let WebGL2ShaderProcessor=class WebGL2ShaderProcessor{constructor(){this.shaderLanguage=q.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return A.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){let r=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){let t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(r||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else{let i=-1!==t.indexOf("#define MULTIVIEW");if(i)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}return e}};let dataBuffer_DataBuffer=class dataBuffer_DataBuffer{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=dataBuffer_DataBuffer._Counter++}};dataBuffer_DataBuffer._Counter=0;let WebGLDataBuffer=class WebGLDataBuffer extends dataBuffer_DataBuffer{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}};let WebGLPipelineContext=class WebGLPipelineContext{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,r,s,a,n,o){let l;let h=this.engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);let c=this.engine.getUniforms(this,i);for(c.forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l<s.length;l++){let t=e.getUniform(s[l]);null==t&&(s.splice(l,1),l--)}for(let e of(s.forEach((e,t)=>{a[e]=t}),h.getAttributes(this,n)))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||2!==r.length)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,r],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==r&&(s[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,s){let a=this._valueCache[e];if(!a||4!==a.length)return a=[t,i,r,s],this._valueCache[e]=a,!0;let n=!1;return a[0]!==t&&(a[0]=t,n=!0),a[1]!==i&&(a[1]=i,n=!0),a[2]!==r&&(a[2]=r,n=!0),a[3]!==s&&(a[3]=s,n=!0),n}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setUInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&!this.engine.setMatrices(this._uniforms[e],t.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){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&!this.engine.setFloat2(this._uniforms[e],t.x,t.y)&&(this._valueCache[e]=null)}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setFloat2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&!this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)&&(this._valueCache[e]=null)}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setFloat3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setFloat4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&!this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)&&(this._valueCache[e]=null)}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(this._valueCache[e]=null)}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&!this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)&&(this._valueCache[e]=null)}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}};let WebGLHardwareTexture=class WebGLHardwareTexture{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw 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(let e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return null!==(i=null===(t=this._MSAARenderBuffers)||void 0===t?void 0:t[e])&&void 0!==i?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}};let drawWrapper_DrawWrapper=class drawWrapper_DrawWrapper{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 r;this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(r=this.drawContext)||void 0===r||r.reset())}dispose(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()}};let StencilStateComposer=class StencilStateComposer{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){var e;this.stencilMaterial=void 0,null===(e=this.stencilGlobal)||void 0===e||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var t;if(!e)return;let i=!this.useStencilGlobalOnly&&!!(null===(t=this.stencilMaterial)||void 0===t?void 0:t.enabled);this.enabled=i?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=i?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=i?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=i?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=i?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=i?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=i?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=i?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}};let BufferPointer=class BufferPointer{};let ThinEngine=class ThinEngine{static get NpmPackage(){return"babylonjs@6.28.1"}static get Version(){return"6.28.1"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return effect_Effect.ShadersRepository}static set ShadersRepository(e){effect_Effect.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){let e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);let i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return ThinEngine._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,r){var s,a,n,o,l,h,c,u,d,_,p;this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new observable_Observable,this._frameId=0,this._uniformBuffers=[],this._storageBuffers=[],this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=[],this.onContextLostObservable=new observable_Observable,this.onContextRestoredObservable=new observable_Observable,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new DepthCullingState,this._stencilStateComposer=new StencilStateComposer,this._stencilState=new StencilState,this._alphaState=new AlphaState,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=[],this._renderTargetWrapperCache=[],this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=[],this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=[],this._currentInstanceLocations=[],this._currentInstanceBuffers=[],this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=[],this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=[],this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new observable_Observable,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=precisionDate_PrecisionDate.Now;let f=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=null!=r&&r,this._stencilStateComposer.stencilGlobal=this._stencilState,performanceConfigurator_PerformanceConfigurator.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=null!=t?t:i.antialias,i.deterministicLockstep=null!==(s=i.deterministicLockstep)&&void 0!==s&&s,i.lockstepMaxSteps=null!==(a=i.lockstepMaxSteps)&&void 0!==a?a:4,i.timeStep=null!==(n=i.timeStep)&&void 0!==n?n:1/60,i.audioEngine=null===(o=i.audioEngine)||void 0===o||o,i.stencil=null===(l=i.stencil)||void 0===l||l,this._audioContext=null!==(c=null===(h=i.audioEngineOptions)||void 0===h?void 0:h.audioContext)&&void 0!==c?c:null,this._audioDestination=null!==(d=null===(u=i.audioEngineOptions)||void 0===u?void 0:u.audioDestination)&&void 0!==d?d:null,this.premultipliedAlpha=null===(_=i.premultipliedAlpha)||void 0===_||_,this.useExactSrgbConversions=null!==(p=i.useExactSrgbConversions)&&void 0!==p&&p,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,r=r||i.adaptToDeviceRatio||!1;let m=IsWindowObjectExist()&&window.devicePixelRatio||1,g=i.limitDeviceRatio||m;if(this._hardwareScalingLevel=r?1/Math.min(g,m):1,this._lastDevicePixelRatio=m,!e)return;if(e.getContext){if(f=e,this._renderingCanvas=f,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();let e=navigator.userAgent;for(let t of ThinEngine.ExceptionList){let r=t.key,s=t.targets,a=new RegExp(r);if(a.test(e)){if(t.capture&&t.captureConstraint){let i=t.capture,r=t.captureConstraint,s=new RegExp(i),a=s.exec(e);if(a&&a.length>0){let e=parseInt(a[a.length-1]);if(e>=r)continue}}for(let e of s)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,logger_Logger.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},f.addEventListener("webglcontextlost",this._onContextLost,!1),f.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=f.getContext("webgl2",i)||f.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!f)throw Error("The provided canvas is null or undefined.");try{this._gl=f.getContext("webgl",i)||f.getContext("experimental-webgl",i)}catch(e){throw Error("WebGL not supported")}}if(!this._gl)throw Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";let t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e<this._caps.maxVertexAttribs;e++)this._currentBufferPointers[e]=new BufferPointer;this._shaderProcessor=this.webGLVersion>1?new WebGL2ShaderProcessor:new WebGLShaderProcessor,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);let v=`Babylon.js v${ThinEngine.Version}`;console.log(v+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",v)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{let e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&IsDocumentAvailable()&&"ontouchend"in document},this._checkForMobile(),IsWindowObjectExist()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null;let i=this._depthCullingState.depthTest,r=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,a=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),null===(t=this._rebuildComputeEffects)||void 0===t||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=i,this._depthCullingState.depthFunc=r,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=a,logger_Logger.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){let e=this._internalTexturesCache.slice();for(let t of e)t._rebuild()}_rebuildRenderTargetWrappers(){let e=this._renderTargetWrapperCache.slice();for(let t of e)t._rebuild()}_rebuildEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}effect_Effect.ResetCache()}areAllEffectsReady(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];if(!t.isReady())return!1}return!0}_rebuildBuffers(){for(let e of this._uniformBuffers)e._rebuild();for(let e of this._storageBuffers)e._rebuild()}_initGLContext(){var e;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._glVersion=this._gl.getParameter(this._gl.VERSION);let t=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=t&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(null!==(e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))&&void 0!==e?e:0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{let e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{let e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{let e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{let e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){let e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{let e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{let e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!!(this._creationOptions&&this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e<this._maxSimultaneousTextures;e++)this._nextFreeTextureSlots.push(e);"Mali-G72"===this._glRenderer&&(this._caps.disableMorphTargetTexture=!0)}_initFeatures(){this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:1!==this._webGLVersion,supportDepthStencilTexture:1!==this._webGLVersion,supportShadowSamplers:1!==this._webGLVersion,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:1!==this._webGLVersion,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:1!==this._webGLVersion,basisNeedsPOT:1===this._webGLVersion,support3DTextures:1!==this._webGLVersion,needTypeSuffixInShaderConstants:1!==this._webGLVersion,supportMSAA:1!==this._webGLVersion,supportSSAO2:1!==this._webGLVersion,supportExtendedTextureFormats:1!==this._webGLVersion,supportSwitchCaseInShader:1!==this._webGLVersion,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}get isStencilEnable(){return this._isStencilEnable}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);let e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}resetTextureCache(){for(let e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}getLoadedTexturesCache(){return this._internalTexturesCache}getCaps(){return this._caps}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}let t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(this._renderingQueueLaunched&&this._frameHandler){if(this._renderingQueueLaunched=!1,IsWindowObjectExist()){let{cancelAnimationFrame:e}=this.getHostWindow()||window;if("function"==typeof e)return e(this._frameHandler)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(this._frameHandler);return clearTimeout(this._frameHandler)}}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e<this._activeRenderLoops.length;e++){let t=this._activeRenderLoops[e];t()}this.endFrame()}}this._activeRenderLoops.length>0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return IsWindowObjectExist()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}_queueNewFrame(e,t){return ThinEngine.QueueNewFrame(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=()=>this._renderLoop(),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,i,r=!1){var s,a;let n=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=n;let o=0;if(t&&e){let t=!0;if(this._currentRenderTarget){let i=null===(s=this._currentRenderTarget.texture)||void 0===s?void 0:s.format;if(8===i||9===i||10===i||11===i){let i=null===(a=this._currentRenderTarget.texture)||void 0===a?void 0:a.type;7===i||5===i?(ThinEngine._TempClearColorUint32[0]=255*e.r,ThinEngine._TempClearColorUint32[1]=255*e.g,ThinEngine._TempClearColorUint32[2]=255*e.b,ThinEngine._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,ThinEngine._TempClearColorUint32)):(ThinEngine._TempClearColorInt32[0]=255*e.r,ThinEngine._TempClearColorInt32[1]=255*e.g,ThinEngine._TempClearColorInt32[2]=255*e.b,ThinEngine._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,ThinEngine._TempClearColorInt32)),t=!1}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),o|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),o|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),o|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(o)}_viewport(e,t,i,r){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||r!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r,this._gl.viewport(e,t,i,r))}setViewport(e,t,i){let r=t||this.getRenderWidth(),s=i||this.getRenderHeight(),a=e.x||0,n=e.y||0;this._cachedViewport=e,this._viewport(a*r,n*s,r*e.width,s*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){let e=IsWindowObjectExist()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if(IsWindowObjectExist()&&IsDocumentAvailable()){if(this._renderingCanvas){let e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight}else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){return!!this._renderingCanvas&&(e|=0,t|=0,(!!i||this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)&&(this._renderingCanvas.width=e,this._renderingCanvas.height=t,!0))}bindFramebuffer(e,t=0,i,r,s,a=0,n=0){var o,l,h,c,u,d;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer);let _=this._gl;e.isMulti||(e.is2DArray?_.framebufferTextureLayer(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,null===(o=e.texture._hardwareTexture)||void 0===o?void 0:o.underlyingResource,a,n):e.isCube?_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(l=e.texture._hardwareTexture)||void 0===l?void 0:l.underlyingResource,a):e._currentLOD===a||(_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,null===(h=e.texture._hardwareTexture)||void 0===h?void 0:h.underlyingResource,a),e._currentLOD=a));let p=e._depthStencilTexture;if(p){let i=e._depthStencilTextureWithStencil?_.DEPTH_STENCIL_ATTACHMENT:_.DEPTH_ATTACHMENT;e.is2DArray?_.framebufferTextureLayer(_.FRAMEBUFFER,i,null===(c=p._hardwareTexture)||void 0===c?void 0:c.underlyingResource,a,n):e.isCube?_.framebufferTexture2D(_.FRAMEBUFFER,i,_.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(u=p._hardwareTexture)||void 0===u?void 0:u.underlyingResource,a):_.framebufferTexture2D(_.FRAMEBUFFER,i,_.TEXTURE_2D,null===(d=p._hardwareTexture)||void 0===d?void 0:d.underlyingResource,a)}this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,r):(!i&&(i=e.width,a&&(i/=Math.pow(2,a))),!r&&(r=e.height,a&&(r/=Math.pow(2,a))),this._viewport(0,0,i,r)),this.wipeCaches()}setState(e,t=0,i,r=!1,s,a,n=0){var o,l;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);let h=null===(l=null!==(o=this.cullBackFaces)&&void 0!==o?o:s)||void 0===l||l?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(n);let c=r?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==c||i)&&(this._depthCullingState.frontFace=c),this._stencilStateComposer.stencilMaterial=a}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){let e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){let e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,i){var r;this._currentRenderTarget=null;let s=this._gl;if(e._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}s.bindFramebuffer(s.READ_FRAMEBUFFER,e._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,e._framebuffer),s.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s.COLOR_BUFFER_BIT,s.NEAREST)}(null===(r=e.texture)||void 0===r?void 0:r.generateMipMaps)&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),i()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,t,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create vertex buffer");let r=new WebGLDataBuffer(i);return this.bindArrayBuffer(r),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),this._resetVertexBufferBinding(),r.references=1,r}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){let r=this._gl.createBuffer(),s=new WebGLDataBuffer(r);if(!r)throw Error("Unable to create index buffer");this.bindIndexBuffer(s);let a=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,a,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),s.references=1,s.is32Bits=4===a.BYTES_PER_ELEMENT,s}_normalizeIndexData(e){let t=e.BYTES_PER_ELEMENT;if(2===t)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let t=0;t<e.length;t++)if(e[t]>=65535)return new Uint32Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,s,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,r,s,a,n){let o=this._currentBufferPointers[t];if(!o)return;let l=!1;o.active?(o.buffer!==e&&(o.buffer=e,l=!0),o.size!==i&&(o.size=i,l=!0),o.type!==r&&(o.type=r,l=!0),o.normalized!==s&&(o.normalized=s,l=!0),o.stride!==a&&(o.stride=a,l=!0),o.offset!==n&&(o.offset=n,l=!0)):(l=!0,o.active=!0,o.index=t,o.size=i,o.type=r,o.normalized=s,o.stride=a,o.offset=n,o.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,a,n):this._gl.vertexAttribPointer(t,i,r,s,a,n))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){let r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s<r.length;s++){let a=t.getAttributeLocation(s);if(a>=0){let t=r[s],n=null;if(i&&(n=i[t]),n||(n=e[t]),!n)continue;this._gl.enableVertexAttribArray(a),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[a]=!0);let o=n.getBuffer();o&&(this._vertexAttribPointer(o,a,n.getSize(),n.type,n.normalized,n.byteStride,n.byteOffset),n.getIsInstanced()&&(this._gl.vertexAttribDivisor(a,n.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(a),this._currentInstanceBuffers.push(o))))}}}recordVertexArrayObject(e,t,i,r){let s=this._gl.createVertexArray();if(!s)throw Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,r,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;let t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let a=0;for(let n=0;n<t;n++)if(n<i.length){let t=s.getAttributeLocation(n);t>=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[n],this._gl.FLOAT,!1,r,a)),a+=4*i[n]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,r){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t<i;t++){let i=this._currentInstanceBuffers[t];e!=i&&i.references&&(e=i,this.bindArrayBuffer(i));let r=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(r,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0}releaseVertexArrayObject(e){this._gl.deleteVertexArray(e)}_releaseBuffer(e){return e.references--,0===e.references&&(this._deleteBuffer(e),!0)}_deleteBuffer(e){this._gl.deleteBuffer(e.underlyingResource)}updateAndBindInstancesBuffer(e,t,i){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==i[0].index)this.bindInstancesBuffer(e,i,!0);else for(let t=0;t<4;t++){let r=i[t];this._vertexAttribArraysEnabled[r]||(this._gl.enableVertexAttribArray(r),this._vertexAttribArraysEnabled[r]=!0),this._vertexAttribPointer(e,r,4,this._gl.FLOAT,!1,64,16*t),this._gl.vertexAttribDivisor(r,1),this._currentInstanceLocations.push(r),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,i=!0){this.bindArrayBuffer(e);let r=0;if(i)for(let e=0;e<t.length;e++){let i=t[e];r+=4*i.attributeSize}for(let i=0;i<t.length;i++){let s=t[i];void 0===s.index&&(s.index=this._currentEffect.getAttributeLocationByName(s.attributeName)),s.index<0||(this._vertexAttribArraysEnabled[s.index]||(this._gl.enableVertexAttribArray(s.index),this._vertexAttribArraysEnabled[s.index]=!0),this._vertexAttribPointer(e,s.index,s.attributeSize,s.attributeType||this._gl.FLOAT,s.normalized||!1,r,s.offset),this._gl.vertexAttribDivisor(s.index,void 0===s.divisor?1:s.divisor),this._currentInstanceLocations.push(s.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;let t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t,i=!1;for(;-1!==(t=this._currentInstanceLocations.indexOf(e));)this._currentInstanceLocations.splice(t,1),this._currentInstanceBuffers.splice(t,1),i=!0,t=this._currentInstanceLocations.indexOf(e);i&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))}disableAttributeByIndex(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1}draw(e,t,i,r){this.drawElementsType(e?0:1,t,i,r)}drawPointClouds(e,t,i){this.drawArraysType(2,e,t,i)}drawUnIndexed(e,t,i,r){this.drawArraysType(e?0:1,t,i,r)}drawElementsType(e,t,i,r){this.applyStates(),this._reportDrawCall();let s=this._drawMode(e),a=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,n=this._uintIndicesCurrentlySet?4:2;r?this._gl.drawElementsInstanced(s,i,a,t*n,r):this._gl.drawElements(s,i,a,t*n)}drawArraysType(e,t,i,r){this.applyStates(),this._reportDrawCall();let s=this._drawMode(e);r?this._gl.drawArraysInstanced(s,t,i,r):this._gl.drawArrays(s,t,i)}_drawMode(e){switch(e){case 0:default:return this._gl.TRIANGLES;case 2:case 3:return this._gl.POINTS;case 1:case 4:return this._gl.LINES;case 5:return this._gl.LINE_LOOP;case 6:return this._gl.LINE_STRIP;case 7:return this._gl.TRIANGLE_STRIP;case 8:return this._gl.TRIANGLE_FAN}}_reportDrawCall(){}_releaseEffect(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];let t=e.getPipelineContext();t&&this._deletePipelineContext(t)}_deletePipelineContext(e){e&&e.program&&(e.program.__SPECTOR_rebuildProgram=null,this._gl.deleteProgram(e.program))}_getGlobalDefines(e){if(e){this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS;return}{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}createEffect(e,t,i,r,s,a,n,o,l,h=q.GLSL){var c;let u=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,d=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,_=this._getGlobalDefines(),p=null!==(c=null!=s?s:t.defines)&&void 0!==c?c:"";_&&(p+=_);let f=u+"+"+d+"@"+p;if(this._compiledEffects[f]){let e=this._compiledEffects[f];return n&&e.isReady()&&n(e),e}let m=new effect_Effect(e,t,i,r,this,s,a,n,o,l,f,h);return this._compiledEffects[f]=m,m}static _ConcatenateShader(e,t,i=""){return i+(t?t+"\n":"")+e}_compileShader(e,t,i,r){return this._compileRawShader(ThinEngine._ConcatenateShader(e,i,r),t)}_compileRawShader(e,t){let i=this._gl,r=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!r){let e=i.NO_ERROR,r=i.NO_ERROR;for(;(r=i.getError())!==i.NO_ERROR;)e=r;throw Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${this._contextWasLost}`)}return i.shaderSource(r,e),i.compileShader(r),r}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,i,r,s=null){r=r||this._gl;let a=this._compileRawShader(t,"vertex"),n=this._compileRawShader(i,"fragment");return this._createShaderProgram(e,a,n,r,s)}createShaderProgram(e,t,i,r,s,a=null){s=s||this._gl;let n=this._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",o=this._compileShader(t,"vertex",r,n),l=this._compileShader(i,"fragment",r,n);return this._createShaderProgram(e,o,l,s,a)}inlineShaderCode(e){return e}createPipelineContext(e){let t=new WebGLPipelineContext;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,r,s=null){let a=r.createProgram();if(e.program=a,!a)throw Error("Unable to create program");return r.attachShader(a,t),r.attachShader(a,i),r.linkProgram(a),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),a}_finalizePipelineContext(e){let t=e.context,i=e.vertexShader,r=e.fragmentShader,s=e.program,a=t.getProgramParameter(s,t.LINK_STATUS);if(!a){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(i);if(t)throw e.vertexCompilationError=t,Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(r,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(r);if(t)throw e.fragmentCompilationError=t,Error("FRAGMENT SHADER "+t)}let a=t.getProgramInfoLog(s);if(a)throw e.programLinkError=a,Error(a)}if(this.validateShaderPrograms){t.validateProgram(s);let i=t.getProgramParameter(s,t.VALIDATE_STATUS);if(!i){let i=t.getProgramInfoLog(s);if(i)throw e.programValidationError=i,Error(i)}}t.deleteShader(i),t.deleteShader(r),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,r,s,a,n,o,l,h){r?e.program=this.createRawShaderProgram(e,t,i,void 0,l):e.program=this.createShaderProgram(e,t,i,o,void 0,l),e.program.__SPECTOR_rebuildProgram=n}_isRenderingStateCompiled(e){return!this._isDisposed&&!e._isDisposed&&!!this._gl.getProgramParameter(e.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(e),!0)}_executeWhenRenderingStateIsCompiled(e,t){if(!e.isParallelCompiled){t();return}let i=e.onCompiled;i?e.onCompiled=()=>{i(),t()}:e.onCompiled=t}getUniforms(e,t){let i=[];for(let r=0;r<t.length;r++)i.push(this._gl.getUniformLocation(e.program,t[r]));return i}getAttributes(e,t){let i=[];for(let r=0;r<t.length;r++)try{i.push(this._gl.getAttribLocation(e.program,t[r]))}catch(e){i.push(-1)}return i}enableEffect(e){(e=null!==e&&drawWrapper_DrawWrapper.IsWrapper(e)?e.effect:e)&&e!==this._currentEffect&&(this._stencilStateComposer.stencilMaterial=void 0,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return!!e&&(this._gl.uniform1i(e,t),!0)}setInt2(e,t,i){return!!e&&(this._gl.uniform2i(e,t,i),!0)}setInt3(e,t,i,r){return!!e&&(this._gl.uniform3i(e,t,i,r),!0)}setInt4(e,t,i,r,s){return!!e&&(this._gl.uniform4i(e,t,i,r,s),!0)}setIntArray(e,t){return!!e&&(this._gl.uniform1iv(e,t),!0)}setIntArray2(e,t){return!!e&&t.length%2==0&&(this._gl.uniform2iv(e,t),!0)}setIntArray3(e,t){return!!e&&t.length%3==0&&(this._gl.uniform3iv(e,t),!0)}setIntArray4(e,t){return!!e&&t.length%4==0&&(this._gl.uniform4iv(e,t),!0)}setUInt(e,t){return!!e&&(this._gl.uniform1ui(e,t),!0)}setUInt2(e,t,i){return!!e&&(this._gl.uniform2ui(e,t,i),!0)}setUInt3(e,t,i,r){return!!e&&(this._gl.uniform3ui(e,t,i,r),!0)}setUInt4(e,t,i,r,s){return!!e&&(this._gl.uniform4ui(e,t,i,r,s),!0)}setUIntArray(e,t){return!!e&&(this._gl.uniform1uiv(e,t),!0)}setUIntArray2(e,t){return!!e&&t.length%2==0&&(this._gl.uniform2uiv(e,t),!0)}setUIntArray3(e,t){return!!e&&t.length%3==0&&(this._gl.uniform3uiv(e,t),!0)}setUIntArray4(e,t){return!!e&&t.length%4==0&&(this._gl.uniform4uiv(e,t),!0)}setArray(e,t){return!!e&&!(t.length<1)&&(this._gl.uniform1fv(e,t),!0)}setArray2(e,t){return!!e&&t.length%2==0&&(this._gl.uniform2fv(e,t),!0)}setArray3(e,t){return!!e&&t.length%3==0&&(this._gl.uniform3fv(e,t),!0)}setArray4(e,t){return!!e&&t.length%4==0&&(this._gl.uniform4fv(e,t),!0)}setMatrices(e,t){return!!e&&(this._gl.uniformMatrix4fv(e,!1,t),!0)}setMatrix3x3(e,t){return!!e&&(this._gl.uniformMatrix3fv(e,!1,t),!0)}setMatrix2x2(e,t){return!!e&&(this._gl.uniformMatrix2fv(e,!1,t),!0)}setFloat(e,t){return!!e&&(this._gl.uniform1f(e,t),!0)}setFloat2(e,t,i){return!!e&&(this._gl.uniform2f(e,t,i),!0)}setFloat3(e,t,i,r){return!!e&&(this._gl.uniform3f(e,t,i,r),!0)}setFloat4(e,t,i,r,s){return!!e&&(this._gl.uniform4f(e,t,i,r,s),!0)}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;let e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}clearInternalTexturesCache(){this._internalTexturesCache.length=0}wipeCaches(e){(!this.preventCacheWipeBetweenFrames||e)&&(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){let i=this._gl,r=i.NEAREST,s=i.NEAREST;switch(e){case 11:r=i.LINEAR,s=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case 3:r=i.LINEAR,s=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case 8:r=i.NEAREST,s=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case 4:r=i.NEAREST,s=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case 5:r=i.NEAREST,s=t?i.LINEAR_MIPMAP_NEAREST:i.LINEAR;break;case 6:r=i.NEAREST,s=t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR;break;case 7:r=i.NEAREST,s=i.LINEAR;break;case 1:r=i.NEAREST,s=i.NEAREST;break;case 9:r=i.LINEAR,s=t?i.NEAREST_MIPMAP_NEAREST:i.NEAREST;break;case 10:r=i.LINEAR,s=t?i.NEAREST_MIPMAP_LINEAR:i.NEAREST;break;case 2:r=i.LINEAR,s=i.LINEAR;break;case 12:r=i.LINEAR,s=i.NEAREST}return{min:s,mag:r}}_createTexture(){let e=this._gl.createTexture();if(!e)throw Error("Unable to create texture");return e}_createHardwareTexture(){return new WebGLHardwareTexture(this._createTexture(),this._gl)}_createInternalTexture(e,t,i=!0,r=$.Unknown){var s;let a;let n=!1,o=0,l=3,h=5,c=!1,u=1;void 0!==t&&"object"==typeof t?(n=!!t.generateMipMaps,o=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,u=null!==(s=t.samples)&&void 0!==s?s:1,a=t.label):n=!!t,c&&(c=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(l=1),1!==o||this._caps.textureFloat||(o=0,logger_Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let d=this._gl,_=new internalTexture_InternalTexture(this,r),p=e.width||e,f=e.height||e,m=e.layers||0,g=this._getSamplingParameters(l,n),v=0!==m?d.TEXTURE_2D_ARRAY:d.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(o,h,c),b=this._getInternalFormat(h),T=this._getWebGLTextureType(o);return this._bindTextureDirectly(v,_),0!==m?(_.is2DArray=!0,d.texImage3D(v,0,x,p,f,m,0,b,T,null)):d.texImage2D(v,0,x,p,f,0,b,T,null),d.texParameteri(v,d.TEXTURE_MAG_FILTER,g.mag),d.texParameteri(v,d.TEXTURE_MIN_FILTER,g.min),d.texParameteri(v,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(v,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),_._useSRGBBuffer=c,_.baseWidth=p,_.baseHeight=f,_.width=p,_.height=f,_.depth=m,_.isReady=!0,_.samples=u,_.generateMipMaps=n,_.samplingMode=l,_.type=o,_.format=h,_.label=a,this._internalTexturesCache.push(_),_}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,r,s=3,a=null,n=null,o,l,h=null,c=null,u=null,d=null,_,p,f){e=e||"";let m="data:"===e.substr(0,5),g="blob:"===e.substr(0,5),v=m&&-1!==e.indexOf(";base64,"),x=c||new internalTexture_InternalTexture(this,$.Url);x!==c&&(x.label=e.substring(0,60));let b=e;!this._transformTextureUrl||v||c||h||(e=this._transformTextureUrl(e)),b!==e&&(x._originalUrl=b);let T=e.lastIndexOf("."),S=d||(T>-1?e.substring(T).toLowerCase():""),C=null,E=S.indexOf("?");for(let e of(E>-1&&(S=S.split("?")[0]),ThinEngine._TextureLoaders))if(e.canLoad(S,_)){C=e;break}r&&r.addPendingData(x),x.url=e,x.generateMipMaps=!t,x.samplingMode=s,x.invertY=i,x._useSRGBBuffer=this._getUseSRGBBuffer(!!f,t),this._doNotHandleContextLost||(x._buffer=h);let y=null;a&&!c&&(y=x.onLoadedObservable.add(a)),c||this._internalTexturesCache.push(x);let onInternalError=(i,c)=>{r&&r.removePendingData(x),e===b?(y&&x.onLoadedObservable.remove(y),engineStore_EngineStore.UseFallbackTexture&&this._createTextureBase(engineStore_EngineStore.FallbackTexture,t,x.invertY,r,s,null,n,o,l,h,x),i=(i||"Unknown error")+(engineStore_EngineStore.UseFallbackTexture?" - Fallback texture was used":""),x.onErrorObservable.notifyObservers({message:i,exception:c}),n&&n(i,c)):(logger_Logger.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,x.invertY,r,s,a,n,o,l,h,x,u,d,_,p,f))};if(C){let callback=e=>{C.loadData(e,x,(e,t,i,a,n,l)=>{l?onInternalError("TextureLoader failed to load data"):o(x,S,r,{width:e,height:t},x.invertY,!i,a,()=>(n(),!1),s)},p)};h?h instanceof ArrayBuffer?callback(new Uint8Array(h)):ArrayBuffer.isView(h)?callback(h):n&&n("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,e=>callback(new Uint8Array(e)),void 0,r?r.offlineProvider:void 0,!0,(e,t)=>{onInternalError("Unable to load "+(e&&e.responseURL,t))})}else{let onload=e=>{g&&!this._doNotHandleContextLost&&(x._buffer=e),o(x,S,r,e,x.invertY,t,!1,l,s)};!m||v?h&&("string"==typeof h.decoding||h.close)?onload(h):ThinEngine._FileToolsLoadImage(e,onload,onInternalError,r?r.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?ThinEngine._FileToolsLoadImage(h,onload,onInternalError,r?r.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&onload(h)}return x}createTexture(e,t,i,r,s=3,a=null,n=null,o=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,r,s,a,n,this._prepareWebGLTexture.bind(this),(e,t,i,s,a,n)=>{let o=this._gl,l=i.width===e&&i.height===t,c=this._getTexImageParametersForCreateTexture(h,s,a._useSRGBBuffer);if(l)return o.texImage2D(o.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),!1;let u=this._caps.maxTextureSize;if(i.width>u||i.height>u||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!!this._workingCanvas&&!!this._workingContext&&(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),o.texImage2D(o.TEXTURE_2D,0,c.internalFormat,c.format,c.type,this._workingCanvas),a.width=e,a.height=t,!1);{let e=new internalTexture_InternalTexture(this,$.Temp);this._bindTextureDirectly(o.TEXTURE_2D,e,!0),o.texImage2D(o.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),this._rescaleTexture(e,a,r,c.format,()=>{this._releaseTexture(e),this._bindTextureDirectly(o.TEXTURE_2D,a,!0),n()})}return!0},o,l,h,c,u,d,p)}_getTexImageParametersForCreateTexture(e,t,i){let r,s;return null==e&&(e=".jpg"!==t||i?5:4),1===this.webGLVersion?s=r=this._getInternalFormat(e,i):(r=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,i)),{internalFormat:s,format:r,type:this._gl.UNSIGNED_BYTE}}static _FileToolsLoadImage(e,t,i,r,s,a){throw _WarnImport("FileTools")}_rescaleTexture(e,t,i,r,s){}createRawTexture(e,t,i,r,s,a,n,o=null,l=0,h=0,c=!1){throw _WarnImport("Engine.RawTexture")}createRawCubeTexture(e,t,i,r,s,a,n,o=null){throw _WarnImport("Engine.RawTexture")}createRawTexture3D(e,t,i,r,s,a,n,o,l=null,h=0){throw _WarnImport("Engine.RawTexture")}createRawTexture2DArray(e,t,i,r,s,a,n,o,l=null,h=0){throw _WarnImport("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){let r=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,s.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e}updateTextureDimensions(e,t,i,r=1){}updateTextureWrappingMode(e,t,i=null,r=null){let s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(s,null)}_setupDepthStencilTexture(e,t,i,r,s,a=1){let n=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=n,e.baseHeight=o,e.width=n,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=a,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=0,e._comparisonFunction=s;let h=this._gl,c=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(c,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(c,h.TEXTURE_MIN_FILTER,u.min),h.texParameteri(c,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(c,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===s?(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,s),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,n=0){let o=this._gl,l=o.TEXTURE_2D;if(e.isCube&&(l=o.TEXTURE_CUBE_MAP_POSITIVE_X+a),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,n,t,i,r,0,s)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,a=!1){let n=this._gl,o=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=n.TEXTURE_2D;e.isCube&&(c=n.TEXTURE_CUBE_MAP_POSITIVE_X+i);let u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=a?e.width:Math.pow(2,Math.max(u-r,0)),p=a?e.height:Math.pow(2,Math.max(d-r,0));n.texImage2D(c,r,h,_,p,0,l,o,t)}updateTextureData(e,t,i,r,s,a,n=0,o=0,l=!1){let h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,_=h.TEXTURE_2D;e.isCube&&(_=h.TEXTURE_CUBE_MAP_POSITIVE_X+n,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(_,o,i,r,s,a,u,c,t),l&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){let s=this._gl,a=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(a,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(a,null,!0)}_prepareWebGLTextureContinuation(e,t,i,r,s){let a=this._gl;if(!a)return;let n=this._getSamplingParameters(s,!i);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,n.mag),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,n.min),i||r||a.generateMipmap(a.TEXTURE_2D),this._bindTextureDirectly(a.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,r,s,a,n,o,l=3){let h=this.getCaps().maxTextureSize,c=Math.min(h,this.needPOTTextures?ThinEngine.GetExponentOfTwo(r.width,h):r.width),u=Math.min(h,this.needPOTTextures?ThinEngine.GetExponentOfTwo(r.height,h):r.height),d=this._gl;if(d){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=r.width,e.baseHeight=r.height,e.width=c,e.height=u,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:".jpg"!==t||e._useSRGBBuffer?5:4,o(c,u,r,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,a,n,l)})||this._prepareWebGLTextureContinuation(e,i,a,n,l)}}_setupFramebufferDepthAttachments(e,t,i,r,s=1){let a=this._gl;if(e&&t)return this._createRenderBuffer(i,r,s,a.DEPTH_STENCIL,a.DEPTH24_STENCIL8,a.DEPTH_STENCIL_ATTACHMENT);if(t){let e=a.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=a.DEPTH_COMPONENT32F),this._createRenderBuffer(i,r,s,e,e,a.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,r,s,a.STENCIL_INDEX8,a.STENCIL_INDEX8,a.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,r,s,a,n=!0){let o=this._gl,l=o.createRenderbuffer();return this._updateRenderBuffer(l,e,t,i,r,s,a,n)}_updateRenderBuffer(e,t,i,r,s,a,n,o=!0){let l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),r>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,r,a,t,i):l.renderbufferStorage(l.RENDERBUFFER,s,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,n,l.RENDERBUFFER,e),o&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource),this.unbindAllTextures();let i=this._internalTexturesCache.indexOf(e);-1!==i&&this._internalTexturesCache.splice(i,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){let t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.program);let i=e.getSamplers();for(let t=0;t<i.length;t++){let r=e.getUniform(i[t]);r&&(this._boundUniforms[t]=r)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,i=!1,r=!1){var s,a;let n=!1,o=t&&t._associatedChannel>-1;i&&o&&(this._activeChannel=t._associatedChannel);let l=this._boundTexturesCache[this._activeChannel];if(l!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw console.error(e,t),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,null!==(a=null===(s=null==t?void 0:t._hardwareTexture)||void 0===s?void 0:s.underlyingResource)&&void 0!==a?a:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(n=!0,this._activateCurrentTexture());return o&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),n}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;let r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}unbindAllTextures(){for(let e=0;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){let i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:break;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,r=!1,s=""){let a;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;let i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;a=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&a&&(a._associatedChannel=e);let n=!0;this._boundTexturesCache[e]===a&&(i||this._bindSamplerUniformToChannel(a._associatedChannel,e),n=!1),this._activeChannel=e;let o=this._getTextureTarget(a);if(n&&this._bindTextureDirectly(o,a,i),a&&!a.isMultiview){if(a.isCube&&a._cachedCoordinatesMode!==t.coordinatesMode){a._cachedCoordinatesMode=t.coordinatesMode;let e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}a._cachedWrapU!==t.wrapU&&(a._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),a)),a._cachedWrapV!==t.wrapV&&(a._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),a)),a.is3D&&a._cachedWrapR!==t.wrapR&&(a._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),a)),this._setAnisotropicLevel(o,a,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,r){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t<i.length;t++){let r=i[t].getInternalTexture();r?(this._textureUnits[t]=e+t,r._associatedChannel=e+t):this._textureUnits[t]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let e=0;e<i.length;e++)this._setTexture(this._textureUnits[e],i[e],!0)}}_setAnisotropicLevel(e,t,i){let r=this._caps.textureAnisotropicFilterExtension;11!==t.samplingMode&&3!==t.samplingMode&&2!==t.samplingMode&&(i=1),r&&t._cachedAnisotropicFilteringLevel!==i&&(this._setTextureParameterFloat(e,r.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(i,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=i)}_setTextureParameterFloat(e,t,i,r){this._bindTextureDirectly(e,r,!0,!0),this._gl.texParameterf(e,t,i)}_setTextureParameterInteger(e,t,i,r){r&&this._bindTextureDirectly(e,r,!0,!0),this._gl.texParameteri(e,t,i)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e);return}for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)!(e>=this._caps.maxVertexAttribs)&&this._vertexAttribArraysEnabled[e]&&this.disableAttributeByIndex(e)}releaseEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e,t;for(let t of(this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),null===(e=this.releaseComputeEffects)||void 0===e||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},IsWindowObjectExist()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,effect_Effect.ResetCache(),this._activeRequests))t.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._creationOptions.loseContextOnDispose&&(null===(t=this._gl.getExtension("WEBGL_lose_context"))||void 0===t||t.loseContext())}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){let t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);let s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);let a=t.checkFramebufferStatus(t.FRAMEBUFFER);if((i=(i=i&&a===t.FRAMEBUFFER_COMPLETE)&&t.getError()===t.NO_ERROR)&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);let e=t.RGBA,r=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,r,s),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:break;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:break;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_getRGBAMultiSampleBufferFormat(e,t=5){switch(e){case 1:if(6===t)return this._gl.R32F;return this._gl.RGBA32F;case 2:if(6===t)return this._gl.R16F;return this._gl.RGBA16F}return this._gl.RGBA8}_loadFile(e,t,i,r,s,a){let n=ThinEngine._FileToolsLoadFile(e,t,i,r,s,a);return this._activeRequests.push(n),n.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),n}static _FileToolsLoadFile(e,t,i,r,s,a){throw _WarnImport("FileTools")}readPixels(e,t,i,r,s=!0,a=!0){let n=s?this._gl.RGBA:this._gl.RGB,o=new Uint8Array(r*i*(s?4:3));return a&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,r,n,this._gl.UNSIGNED_BYTE,o),Promise.resolve(o)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{let e=this._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{let e=this._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){let t=ThinEngine.CeilingPOT(e),i=ThinEngine.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let r;switch(i){case 1:r=ThinEngine.FloorPOT(e);break;case 2:r=ThinEngine.NearestPOT(e);break;default:r=ThinEngine.CeilingPOT(e)}return Math.min(r,t)}static QueueNewFrame(e,t){if(IsWindowObjectExist()){let{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:IsDocumentAvailable()?document:null}};ThinEngine._TempClearColorUint32=new Uint32Array(4),ThinEngine._TempClearColorInt32=new Int32Array(4),ThinEngine.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],ThinEngine._TextureLoaders=[],ThinEngine.CollisionsEpsilon=.001,ThinEngine._IsSupported=null,ThinEngine._HasMajorPerformanceCaveat=null;let TimingTools=class TimingTools{static SetImmediate(e){IsWindowObjectExist()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}};let M=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);let LoadFileError=class LoadFileError extends RuntimeError{constructor(e,t){super(e,b.LoadFileError),this.name="LoadFileError",BaseError._setPrototypeOf(this,LoadFileError.prototype),t instanceof webRequest_WebRequest?this.request=t:this.file=t}};let RequestFileError=class RequestFileError extends RuntimeError{constructor(e,t){super(e,b.RequestFileError),this.request=t,this.name="RequestFileError",BaseError._setPrototypeOf(this,RequestFileError.prototype)}};let ReadFileError=class ReadFileError extends RuntimeError{constructor(e,t){super(e,b.ReadFileError),this.file=t,this.name="ReadFileError",BaseError._setPrototypeOf(this,ReadFileError.prototype)}};let I={DefaultRetryStrategy:RetryStrategy.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e},_CleanUrl=e=>e=e.replace(/#/gm,"%23"),SetCorsBehavior=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&I.CorsBehavior){if("string"==typeof I.CorsBehavior||I.CorsBehavior instanceof String)t.crossOrigin=I.CorsBehavior;else{let i=I.CorsBehavior(e);i&&(t.crossOrigin=i)}}},LoadImage=(e,t,i,r,s="",a)=>{var n;let o;let l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(o=URL.createObjectURL(new Blob([e],{type:s})),l=!0):o=`data:${s};base64,`+stringTools_EncodeArrayBufferToBase64(e):e instanceof Blob?(o=URL.createObjectURL(e),l=!0):(o=_CleanUrl(e),o=I.PreprocessUrl(e));let h=engineStore_EngineStore.LastCreatedEngine,onErrorHandler=t=>{if(i){let r=o||e.toString();i(`Error while trying to load image: ${0===r.indexOf("http")||r.length<=128?r:r.slice(0,128)+"..."}`,t)}};if("undefined"==typeof Image||null!==(n=null==h?void 0:h._features.forceBitmapOverHTMLImageElement)&&void 0!==n&&n)return LoadFile(o,r=>{h.createImageBitmap(new Blob([r],{type:s}),Object.assign({premultiplyAlpha:"none"},a)).then(e=>{t(e),l&&URL.revokeObjectURL(o)}).catch(t=>{i&&i("Error while trying to load image: "+e,t)})},void 0,r||void 0,!0,(e,t)=>{onErrorHandler(t)}),null;let c=new Image;SetCorsBehavior(o,c);let u=[],unloadHandlersList=()=>{u.forEach(e=>{e.target.removeEventListener(e.name,e.handler)}),u.length=0};u.push({target:c,name:"load",handler:()=>{unloadHandlersList(),t(c),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{unloadHandlersList(),onErrorHandler(e),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;unloadHandlersList();let t=Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);engineStore_EngineStore.UseFallbackTexture=!1,onErrorHandler(t),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),u.forEach(e=>{e.target.addEventListener(e.name,e.handler)});let d="blob:"===o.substring(0,5),_="data:"===o.substring(0,5),noOfflineSupport=()=>{d||_||!webRequest_WebRequest.IsCustomRequestAvailable?c.src=o:LoadFile(o,(e,t,i)=>{let r=!s&&i?i:s,a=new Blob([e],{type:r}),n=URL.createObjectURL(a);l=!0,c.src=n},void 0,r||void 0,!0,(e,t)=>{onErrorHandler(t)})};if(!d&&!_&&r&&r.enableTexturesOffline)r.open(()=>{r&&r.loadImage(o,c)},noOfflineSupport);else{if(-1!==o.indexOf("file:")){let e=decodeURIComponent(o.substring(5).toLowerCase());if(filesInputStore_FilesInputStore.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(filesInputStore_FilesInputStore.FilesToLoad[e])}catch(i){t=URL.createObjectURL(filesInputStore_FilesInputStore.FilesToLoad[e])}c.src=t,l=!0}catch(e){c.src=""}return c}}noOfflineSupport()}return c},ReadFile=(e,t,i,r,s)=>{let a=new FileReader,n={onCompleteObservable:new observable_Observable,abort:()=>a.abort()};return a.onloadend=()=>n.onCompleteObservable.notifyObservers(n),s&&(a.onerror=()=>{s(new ReadFileError(`Unable to read ${e.name}`,e))}),a.onload=e=>{t(e.target.result)},i&&(a.onprogress=i),r?a.readAsArrayBuffer(e):a.readAsText(e),n},LoadFile=(e,t,i,r,s,a,n)=>{if(e.name)return ReadFile(e,t,i,s,a?e=>{a(void 0,e)}:void 0);if(-1!==e.indexOf("file:")){let r=decodeURIComponent(e.substring(5).toLowerCase());0===r.indexOf("./")&&(r=r.substring(2));let n=filesInputStore_FilesInputStore.FilesToLoad[r];if(n)return ReadFile(n,t,i,s,a?e=>a(void 0,new LoadFileError(e.message,e.file)):void 0)}let{match:o,type:l}=TestBase64DataUrl(e);if(o){let i={onCompleteObservable:new observable_Observable,abort:()=>()=>{}};try{let i=s?DecodeBase64UrlToBinary(e):DecodeBase64UrlToString(e);t(i,void 0,l)}catch(e){a?a(void 0,e):logger_Logger.Error(e.message||"Failed to parse the Data URL")}return TimingTools.SetImmediate(()=>{i.onCompleteObservable.notifyObservers(i)}),i}return RequestFile(e,(e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))},i,r,s,a?e=>{a(e.request,new LoadFileError(e.message,e.request))}:void 0,n)},RequestFile=(e,t,i,r,s,a,n)=>{e=_CleanUrl(e),e=I.PreprocessUrl(e);let o=I.BaseUrl+e,l=!1,h={onCompleteObservable:new observable_Observable,abort:()=>l=!0},requestFile=()=>{let e,r=new webRequest_WebRequest,c=null,unbindEvents=()=>{r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",onLoadEnd))},onLoadEnd=()=>{unbindEvents(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),i=void 0,e=null,onLoadEnd=null,a=void 0,n=void 0,t=void 0};h.abort=()=>{l=!0,onLoadEnd&&onLoadEnd(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==c&&(clearTimeout(c),c=null),r=null};let handleError=e=>{let t=e.message||"Unknown error";a&&r?a(new RequestFileError(t,r)):logger_Logger.Error(t)},retryLoop=h=>{if(r){if(r.open("GET",o),n)try{n(r)}catch(e){handleError(e);return}s&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),onLoadEnd&&r.addEventListener("loadend",onLoadEnd),e=()=>{if(!l&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status&&(!IsWindowObjectExist()||IsFileURL())){try{t&&t(s?r.response:r.responseText,r)}catch(e){handleError(e)}return}let i=I.DefaultRetryStrategy;if(i){let e=i(o,r,h);if(-1!==e){unbindEvents(),r=new webRequest_WebRequest,c=setTimeout(()=>retryLoop(h+1),e);return}}let n=new RequestFileError("Error status: "+r.status+" "+r.statusText+" - Unable to load "+o,r);a&&a(n)}},r.addEventListener("readystatechange",e),r.send()}};retryLoop(0)};if(r&&r.enableSceneOffline){let noOfflineSupport=e=>{e&&e.status>400?a&&a(e):requestFile()};r.open(()=>{r&&r.loadFile(I.BaseUrl+e,e=>{!l&&t&&t(e),h.onCompleteObservable.notifyObservers(h)},i?e=>{!l&&i&&i(e)}:void 0,noOfflineSupport,s)},noOfflineSupport)}else requestFile();return h},IsFileURL=()=>"undefined"!=typeof location&&"file:"===location.protocol,IsBase64DataUrl=e=>M.test(e),TestBase64DataUrl=e=>{let t=M.exec(e);if(null===t||0===t.length)return{match:!1,type:""};{let e=t[0].replace("data:","").replace("base64,","");return{match:!0,type:e}}};function DecodeBase64UrlToBinary(e){return stringTools_DecodeBase64ToBinary(e.split(",")[1])}let DecodeBase64UrlToString=e=>DecodeBase64ToString(e.split(",")[1]);ThinEngine._FileToolsLoadImage=LoadImage,ThinEngine._FileToolsLoadFile=LoadFile,ShaderProcessor._FileToolsLoadFile=LoadFile,((e,t,i,s,a,n,o,l,h,c)=>{Object.defineProperty(r={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:a,LoadFile:n,LoadImage:o,ReadFile:l,RequestFile:h,SetCorsBehavior:c},"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(r,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(r,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(r,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(DecodeBase64UrlToBinary,DecodeBase64UrlToString,I,IsBase64DataUrl,IsFileURL,LoadFile,LoadImage,ReadFile,RequestFile,SetCorsBehavior);let InstantiationTools=class InstantiationTools{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];let t=h[e];if(t)return t;logger_Logger.Warn(e+" not found, you may have missed an import.");let i=e.split("."),r=window||this;for(let e=0,t=i.length;e<t;e++)r=r[i[e]];return"function"!=typeof r?null:r}};function guid_RandomGUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}InstantiationTools.RegisteredExternalClasses={};let tools_Tools=class tools_Tools{static get BaseUrl(){return I.BaseUrl}static set BaseUrl(e){I.BaseUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||!(-1===e.indexOf("://")||-1===e.indexOf(".")||-1===e.indexOf("/")||e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://")<e.indexOf(".")||0===e.indexOf("data:")||0===e.indexOf("blob:"))}static set ScriptBaseUrl(e){I.ScriptBaseUrl=e}static get ScriptBaseUrl(){return I.ScriptBaseUrl}static set ScriptPreprocessUrl(e){I.ScriptPreprocessUrl=e}static get ScriptPreprocessUrl(){return I.ScriptPreprocessUrl}static get DefaultRetryStrategy(){return I.DefaultRetryStrategy}static set DefaultRetryStrategy(e){I.DefaultRetryStrategy=e}static get CorsBehavior(){return I.CorsBehavior}static set CorsBehavior(e){I.CorsBehavior=e}static get UseFallbackTexture(){return engineStore_EngineStore.UseFallbackTexture}static set UseFallbackTexture(e){engineStore_EngineStore.UseFallbackTexture=e}static get RegisteredExternalClasses(){return InstantiationTools.RegisteredExternalClasses}static set RegisteredExternalClasses(e){InstantiationTools.RegisteredExternalClasses=e}static get fallbackTexture(){return engineStore_EngineStore.FallbackTexture}static set fallbackTexture(e){engineStore_EngineStore.FallbackTexture=e}static FetchToRef(e,t,i,r,s,a){let n=((Math.abs(e)*i%i|0)+(Math.abs(t)*r%r|0)*i)*4;a.r=s[n]/255,a.g=s[n+1]/255,a.b=s[n+2]/255,a.a=s[n+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return InstantiationTools.Instantiate(e)}static SetImmediate(e){TimingTools.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do t*=2;while(t<e);return t===e}static FloatRound(e){return Math.fround(e)}static GetFilename(e){let t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){let i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return 180*e/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,i=.9){let r=this.ToRadians(e),s=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(s)+i*Math.sin(r),(1-i)*Math.cos(s)+i*Math.cos(r)))}static MakeArray(e,t){return!0!==t&&(void 0===e||null==e)?null:Array.isArray(e)?e:[e]}static GetPointerPrefix(e){let t="pointer";return IsWindowObjectExist()&&!window.PointerEvent&&(t="mouse"),!e._badDesktopOS||e._badOS||document&&"ontouchend"in document||(t="mouse"),t}static SetCorsBehavior(e,t){SetCorsBehavior(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static CleanUrl(e){return e=e.replace(/#/gm,"%23")}static get PreprocessUrl(){return I.PreprocessUrl}static set PreprocessUrl(e){I.PreprocessUrl=e}static LoadImage(e,t,i,r,s,a){return LoadImage(e,t,i,r,s,a)}static LoadFile(e,t,i,r,s,a){return LoadFile(e,t,i,r,s,a)}static LoadFileAsync(e,t=!0){return new Promise((i,r)=>{LoadFile(e,e=>{i(e)},void 0,void 0,t,(e,t)=>{r(t)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(tools_Tools.ScriptBaseUrl&&e.startsWith(tools_Tools._DefaultCdnUrl)){let t="/"===tools_Tools.ScriptBaseUrl[tools_Tools.ScriptBaseUrl.length-1]?tools_Tools.ScriptBaseUrl.substring(0,tools_Tools.ScriptBaseUrl.length-1):tools_Tools.ScriptBaseUrl;e=e.replace(tools_Tools._DefaultCdnUrl,t)}return e=tools_Tools.ScriptPreprocessUrl(e),t&&(e=tools_Tools.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=tools_Tools.GetBabylonScriptURL(e),tools_Tools.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=tools_Tools.GetBabylonScriptURL(e),tools_Tools.LoadScriptAsync(e)}static LoadScript(e,t,i,r){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){null==i||i(`Unable to load script '${e}' in worker`,t)}return}if(!IsWindowObjectExist()){null==i||i(`Cannot load script '${e}' outside of a window or a worker`);return}let s=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),r&&(a.id=r),a.onload=()=>{t&&t()},a.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},s.appendChild(a)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(e,t)=>{i(t||Error(e))})})}static ReadFileAsDataURL(e,t,i){let r=new FileReader,s={onCompleteObservable:new observable_Observable,abort:()=>r.abort()};return r.onloadend=()=>{s.onCompleteObservable.notifyObservers(s)},r.onload=e=>{t(e.target.result)},r.onprogress=i,r.readAsDataURL(e),s}static ReadFile(e,t,i,r,s){return ReadFile(e,t,i,r,s)}static FileAsURL(e){let t=new Blob([e]),i=window.URL,r=i.createObjectURL(t);return r}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){DeepCopier.DeepCopy(e,t,i,r)}static IsEmpty(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){let r=t[i];e.addEventListener(r.name,r.handler,!1);try{window.parent&&window.parent.addEventListener(r.name,r.handler,!1)}catch(e){}}}static UnregisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){let r=t[i];e.removeEventListener(r.name,r.handler);try{e.parent&&e.parent.removeEventListener(r.name,r.handler)}catch(e){}}}static async DumpFramebuffer(e,t,i,r,s="image/png",a,n){throw _WarnImport("DumpTools")}static DumpData(e,t,i,r,s="image/png",a,n=!1,o=!1,l){throw _WarnImport("DumpTools")}static DumpDataAsync(e,t,i,r="image/png",s,a=!1,n=!1,o){throw _WarnImport("DumpTools")}static _IsOffScreenCanvas(e){return void 0!==e.convertToBlob}static ToBlob(e,t,i="image/png",r){tools_Tools._IsOffScreenCanvas(e)||e.toBlob||(e.toBlob=function(e,t,i){setTimeout(()=>{let r=atob(this.toDataURL(t,i).split(",")[1]),s=r.length,a=new Uint8Array(s);for(let e=0;e<s;e++)a[e]=r.charCodeAt(e);e(new Blob([a]))})}),tools_Tools._IsOffScreenCanvas(e)?e.convertToBlob({type:i,quality:r}).then(e=>t(e)):e.toBlob(function(e){t(e)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){let e=new Date,i=(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2);t="screenshot_"+i+".png"}tools_Tools.Download(e,t)}else if(e&&"undefined"!=typeof URL){let t=URL.createObjectURL(e),i=window.open("");if(!i)return;let r=i.document.createElement("img");r.onload=function(){URL.revokeObjectURL(t)},r.src=t,i.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if("string"!=typeof r&&t){if(t){if(tools_Tools._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(e=>{let i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{let e=i.result;t(e)}});return}let r=e.toDataURL(i,s);t(r)}}else this.ToBlob(e,function(e){e&&tools_Tools.DownloadBlob(e,r),t&&t("")},i,s)}static Download(e,t){if("undefined"==typeof URL)return;let i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,r,s="image/png",a=!1,n){throw _WarnImport("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",s){throw _WarnImport("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",a=1,n=!1,o,l=!1,h=!1,c=!0,u){throw _WarnImport("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,a=!1,n,o=!1,l=!1,h=!0,c){throw _WarnImport("ScreenshotTools")}static RandomId(){return guid_RandomGUID()}static IsBase64(e){return IsBase64DataUrl(e)}static DecodeBase64(e){return DecodeBase64UrlToBinary(e)}static get errorsCount(){return logger_Logger.errorsCount}static Log(e){logger_Logger.Log(e)}static Warn(e){logger_Logger.Warn(e)}static Error(e){logger_Logger.Error(e)}static get LogCache(){return logger_Logger.LogCache}static ClearLogCache(){logger_Logger.ClearLogCache()}static set LogLevels(e){logger_Logger.LogLevels=e}static set PerformanceLogLevel(e){if((e&tools_Tools.PerformanceUserMarkLogLevel)===tools_Tools.PerformanceUserMarkLogLevel){tools_Tools.StartPerformanceCounter=tools_Tools._StartUserMark,tools_Tools.EndPerformanceCounter=tools_Tools._EndUserMark;return}if((e&tools_Tools.PerformanceConsoleLogLevel)===tools_Tools.PerformanceConsoleLogLevel){tools_Tools.StartPerformanceCounter=tools_Tools._StartPerformanceConsole,tools_Tools.EndPerformanceCounter=tools_Tools._EndPerformanceConsole;return}tools_Tools.StartPerformanceCounter=tools_Tools._StartPerformanceCounterDisabled,tools_Tools.EndPerformanceCounter=tools_Tools._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!tools_Tools._Performance){if(!IsWindowObjectExist())return;tools_Tools._Performance=window.performance}t&&tools_Tools._Performance.mark&&tools_Tools._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&tools_Tools._Performance.mark&&(tools_Tools._Performance.mark(e+"-End"),tools_Tools._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(tools_Tools._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(tools_Tools._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return precisionDate_PrecisionDate.Now}static GetClassName(e,t=!1){let i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__}i||(i=typeof e)}return i}static First(e,t){for(let i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return!!IsNavigatorAvailable()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}};tools_Tools.UseCustomRequestHeaders=!1,tools_Tools.CustomRequestHeaders=webRequest_WebRequest.CustomRequestHeaders,tools_Tools.GetDOMTextContent=GetDOMTextContent,tools_Tools._DefaultCdnUrl="https://cdn.babylonjs.com",tools_Tools.GetAbsoluteUrl="object"==typeof document?e=>{let t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},tools_Tools.NoneLogLevel=logger_Logger.NoneLogLevel,tools_Tools.MessageLogLevel=logger_Logger.MessageLogLevel,tools_Tools.WarningLogLevel=logger_Logger.WarningLogLevel,tools_Tools.ErrorLogLevel=logger_Logger.ErrorLogLevel,tools_Tools.AllLogLevel=logger_Logger.AllLogLevel,tools_Tools.IsWindowObjectExist=IsWindowObjectExist,tools_Tools.PerformanceNoneLogLevel=0,tools_Tools.PerformanceUserMarkLogLevel=1,tools_Tools.PerformanceConsoleLogLevel=2,tools_Tools.StartPerformanceCounter=tools_Tools._StartPerformanceCounterDisabled,tools_Tools.EndPerformanceCounter=tools_Tools._EndPerformanceCounterDisabled;let AsyncLoop=class AsyncLoop{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,i,r=0){let s=new AsyncLoop(e,t,i,r);return s.executeNext(),s}static SyncAsyncForLoop(e,t,i,r,s,a=0){return AsyncLoop.Run(Math.ceil(e/t),r=>{s&&s()?r.breakLoop():setTimeout(()=>{for(let a=0;a<t;++a){let n=r.index*t+a;if(n>=e)break;if(i(n),s&&s()){r.breakLoop();break}}r.executeNext()},a)},r)}};engineStore_EngineStore.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";let SmartArray=class SmartArray{constructor(e){this.length=0,this.data=Array(e),this._id=SmartArray._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){let t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return -1!==this.indexOf(e)}};SmartArray._GlobalId=0;let SmartArrayNoDuplicate=class SmartArrayNoDuplicate extends SmartArray{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=(this.length+e.length)*2);for(let t=0;t<e.length;t++){let i=(e.data||e)[t];this.pushNoDuplicate(i)}}}};let StringDictionary=class StringDictionary{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach((e,t)=>this.add(e,t))}get(e){let 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))&&this.add(e,i),i}getOrAdd(e,t){let 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){let 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(let t in this._data){let i=this._data[t];e(t,i)}}first(e){for(let t in this._data){let i=this._data[t],r=e(t,i);if(r)return r}return null}};let MaterialDefines=class MaterialDefines{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(let 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(){for(let e of(this._keys.length=0,Object.keys(this)))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(let e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;t<this._keys.length;t++){let i=this._keys[t];if(this[i]!==e[i])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){let i=this._keys[t];e[i]=this[i]}}reset(){this._keys.forEach(e=>this._setDefaultValue(e))}_setDefaultValue(e){var t,i,r,s,a;let n=null!==(r=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==r?r:typeof this[e],o=null===(a=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===a?void 0:a.default;switch(n){case"number":this[e]=null!=o?o:0;break;case"string":this[e]=null!=o?o:"";break;default:this[e]=null!=o&&o}}toString(){let e="";for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=this[i],s=typeof r;switch(s){case"number":case"string":e+="#define "+i+" "+r+"\n";break;default:r&&(e+="#define "+i+"\n")}}return e}};let ColorCurves=class ColorCurves{constructor(){this._dirty=!0,this._tempColor=new math_color_Color4(0,0,0,0),this._globalCurve=new math_color_Color4(0,0,0,0),this._highlightsCurve=new math_color_Color4(0,0,0,0),this._midtonesCurve=new math_color_Color4(0,0,0,0),this._shadowsCurve=new math_color_Color4(0,0,0,0),this._positiveCurve=new math_color_Color4(0,0,0,0),this._negativeCurve=new math_color_Color4(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",r="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}static PrepareUniforms(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}_getColorGradingDataToRef(e,t,i,r,s){null!=e&&(e=ColorCurves._Clamp(e,0,360),t=ColorCurves._Clamp(t,-100,100),i=ColorCurves._Clamp(i,-100,100),r=ColorCurves._Clamp(r,-100,100),t=.5*ColorCurves._ApplyColorGradingSliderNonlinear(t),r=ColorCurves._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),ColorCurves._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){let t=Math.abs(e/=100);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100}static _FromHSBToRef(e,t,i,r){let s=ColorCurves._Clamp(e,0,360),a=ColorCurves._Clamp(t/100,0,1),n=ColorCurves._Clamp(i/100,0,1);if(0===a)r.r=n,r.g=n,r.b=n;else{s/=60;let e=Math.floor(s),t=s-e,i=n*(1-a),o=n*(1-a*t),l=n*(1-a*(1-t));switch(e){case 0:r.r=n,r.g=l,r.b=i;break;case 1:r.r=o,r.g=n,r.b=i;break;case 2:r.r=i,r.g=n,r.b=l;break;case 3:r.r=i,r.g=o,r.b=n;break;case 4:r.r=l,r.g=i,r.b=n;break;default:r.r=n,r.g=i,r.b=o}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return decorators_SerializationHelper.Clone(()=>new ColorCurves,this)}serialize(){return decorators_SerializationHelper.Serialize(this)}static Parse(e){return decorators_SerializationHelper.Parse(()=>new ColorCurves,e,null,null)}};__decorate([serialize()],ColorCurves.prototype,"_globalHue",void 0),__decorate([serialize()],ColorCurves.prototype,"_globalDensity",void 0),__decorate([serialize()],ColorCurves.prototype,"_globalSaturation",void 0),__decorate([serialize()],ColorCurves.prototype,"_globalExposure",void 0),__decorate([serialize()],ColorCurves.prototype,"_highlightsHue",void 0),__decorate([serialize()],ColorCurves.prototype,"_highlightsDensity",void 0),__decorate([serialize()],ColorCurves.prototype,"_highlightsSaturation",void 0),__decorate([serialize()],ColorCurves.prototype,"_highlightsExposure",void 0),__decorate([serialize()],ColorCurves.prototype,"_midtonesHue",void 0),__decorate([serialize()],ColorCurves.prototype,"_midtonesDensity",void 0),__decorate([serialize()],ColorCurves.prototype,"_midtonesSaturation",void 0),__decorate([serialize()],ColorCurves.prototype,"_midtonesExposure",void 0),decorators_SerializationHelper._ColorCurvesParser=ColorCurves.Parse;let ImageProcessingConfigurationDefines=class ImageProcessingConfigurationDefines extends MaterialDefines{constructor(){super(),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.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}};let ImageProcessingConfiguration=class ImageProcessingConfiguration{constructor(){this.colorCurves=new ColorCurves,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=ImageProcessingConfiguration.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new math_color_Color4(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new observable_Observable}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}static PrepareUniforms(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&ColorCurves.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType===ImageProcessingConfiguration.TONEMAPPING_ACES)?e.TONEMAPPING_ACES=!0:e.TONEMAPPING_ACES=!1,e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&ColorCurves.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){let i=1/e.getEngine().getRenderWidth(),r=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){let s=null!=t?t:r/i,a=Math.tan(.5*this.vignetteCameraFov),n=a*s,o=Math.sqrt(n*a);n=tools_Tools.Mix(n,o,this.vignetteStretch),a=tools_Tools.Mix(a,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",n,a,-n*this.vignetteCenterX,-a*this.vignetteCenterY);let l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);let t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return decorators_SerializationHelper.Clone(()=>new ImageProcessingConfiguration,this)}serialize(){return decorators_SerializationHelper.Serialize(this)}static Parse(e){let t=decorators_SerializationHelper.Parse(()=>new ImageProcessingConfiguration,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}};ImageProcessingConfiguration.TONEMAPPING_STANDARD=0,ImageProcessingConfiguration.TONEMAPPING_ACES=1,ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY=0,ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE=1,__decorate([serializeAsColorCurves()],ImageProcessingConfiguration.prototype,"colorCurves",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_colorCurvesEnabled",void 0),__decorate([serializeAsTexture("colorGradingTexture")],ImageProcessingConfiguration.prototype,"_colorGradingTexture",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_colorGradingEnabled",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_colorGradingWithGreenDepth",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_colorGradingBGR",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_exposure",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_toneMappingEnabled",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_toneMappingType",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_contrast",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"vignetteStretch",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"vignetteCenterX",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"vignetteCenterY",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"vignetteWeight",void 0),__decorate([generateSerializableMember(8,void 0)],ImageProcessingConfiguration.prototype,"vignetteColor",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"vignetteCameraFov",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_vignetteBlendMode",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_vignetteEnabled",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_ditheringEnabled",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_ditheringIntensity",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_skipFinalColorClamp",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_applyByPostProcess",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_isEnabled",void 0),decorators_SerializationHelper._ImageProcessingConfigurationParser=ImageProcessingConfiguration.Parse,ThinEngine.prototype.createUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create uniform buffer");let r=new WebGLDataBuffer(i);return this.bindUniformBuffer(r),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),r.references=1,r},ThinEngine.prototype.createDynamicUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create dynamic uniform buffer");let r=new WebGLDataBuffer(i);return this.bindUniformBuffer(r),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),r.references=1,r},ThinEngine.prototype.updateUniformBuffer=function(e,t,i,r){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this.bindUniformBuffer(null)},ThinEngine.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},ThinEngine.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},ThinEngine.prototype.bindUniformBlock=function(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);4294967295!==s&&this._gl.uniformBlockBinding(r,s,i)};let UniformBuffer=class UniformBuffer{constructor(e,t,i,r,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=r?r:"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){let e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;let i=this._uniformLocationPointer-e;for(let e=0;e<i;e++)this._data.push(0)}}addUniform(e,t,i=0){let r;if(!this._noUBO&&void 0===this._uniformLocations[e]){if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t)t*=i;else{let e=4-t;t=t*i+e*i}r=[];for(let e=0;e<t;e++)r.push(0)}else{if(t instanceof Array)t=(r=t).length;else{r=[];for(let e=0;e<t;e++)r.push(0)}this._fillAlignment(t)}this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(let e=0;e<t;e++)this._data.push(r[e]);this._needSync=!0}}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.toArray()))}addFloat2(e,t,i){let r=[t,i];this.addUniform(e,r)}addFloat3(e,t,i,r){let s=[t,i,r];this.addUniform(e,s)}addColor3(e,t){let i=[t.r,t.g,t.b];this.addUniform(e,i)}addColor4(e,t,i){let r=[t.r,t.g,t.b,i];this.addUniform(e,r)}addVector3(e,t){let i=[t.x,t.y,t.z];this.addUniform(e,i)}addMatrix3x3(e){this.addUniform(e,12)}addMatrix2x2(e){this.addUniform(e,8)}create(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)}_getNames(){let e=[];for(let t in this._uniformLocations)e.push(t);return e.join(",")}_rebuild(){!this._noUBO&&this._bufferData&&(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()):this._buffer=this._engine.createUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()),this._engine._features.trackUbosInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}_copyBuffer(e,t){for(let i=0;i<e.length;++i)t[i]=e[i]}update(){if(!this._noUBO){if(this.bindUniformBuffer(),!this._buffer){this.create();return}if(!this._dynamic&&!this._needSync){this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}if(this._buffers&&this._buffers.length>1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(UniformBuffer._UpdatedUbosInFrame[this._name]||(UniformBuffer._UpdatedUbosInFrame[this._name]=0),UniformBuffer._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()}_checkNewFrame(){this._engine._features.trackUbosInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(void 0===r){if(this._buffer){logger_Logger.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e<i;e++)this._bufferData[r+e]=t[e];else{let e=!1;for(let s=0;s<i;s++)(16!==i||this._engine._features.uniformBufferHardCheckMatrix)&&this._bufferData[r+s]===Math.fround(t[s])||(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[r+s]=t[s]);this._needSync=this._needSync||e}}updateUniformArray(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(void 0===r){logger_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.");return}this._buffer||this.create();let s=this._uniformArraySizes[e];if(this._dynamic)for(let e=0;e<i;e++)this._bufferData[r+e]=t[e];else{let e=!1,a=0,n=0;for(let o=0;o<i;o++)if(this._bufferData[r+4*n+a]!==tools_Tools.FloatRound(t[o])&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[r+4*n+a]=t[o]),++a===s.strideSize){for(;a<4;a++)this._bufferData[r+4*n+a]=0;a=0,n++}this._needSync=this._needSync||e}}_cacheMatrix(e,t){this._checkNewFrame();let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_updateMatrix3x3ForUniform(e,t){for(let e=0;e<3;e++)UniformBuffer._TempBuffer[4*e]=t[3*e],UniformBuffer._TempBuffer[4*e+1]=t[3*e+1],UniformBuffer._TempBuffer[4*e+2]=t[3*e+2],UniformBuffer._TempBuffer[4*e+3]=0;this.updateUniform(e,UniformBuffer._TempBuffer,12)}_updateMatrix3x3ForEffect(e,t){this._currentEffect.setMatrix3x3(e,t)}_updateMatrix2x2ForEffect(e,t){this._currentEffect.setMatrix2x2(e,t)}_updateMatrix2x2ForUniform(e,t){for(let e=0;e<2;e++)UniformBuffer._TempBuffer[4*e]=t[2*e],UniformBuffer._TempBuffer[4*e+1]=t[2*e+1],UniformBuffer._TempBuffer[4*e+2]=0,UniformBuffer._TempBuffer[4*e+3]=0;this.updateUniform(e,UniformBuffer._TempBuffer,8)}_updateFloatForEffect(e,t){this._currentEffect.setFloat(e,t)}_updateFloatForUniform(e,t){UniformBuffer._TempBuffer[0]=t,this.updateUniform(e,UniformBuffer._TempBuffer,1)}_updateFloat2ForEffect(e,t,i,r=""){this._currentEffect.setFloat2(e+r,t,i)}_updateFloat2ForUniform(e,t,i){UniformBuffer._TempBuffer[0]=t,UniformBuffer._TempBuffer[1]=i,this.updateUniform(e,UniformBuffer._TempBuffer,2)}_updateFloat3ForEffect(e,t,i,r,s=""){this._currentEffect.setFloat3(e+s,t,i,r)}_updateFloat3ForUniform(e,t,i,r){UniformBuffer._TempBuffer[0]=t,UniformBuffer._TempBuffer[1]=i,UniformBuffer._TempBuffer[2]=r,this.updateUniform(e,UniformBuffer._TempBuffer,3)}_updateFloat4ForEffect(e,t,i,r,s,a=""){this._currentEffect.setFloat4(e+a,t,i,r,s)}_updateFloat4ForUniform(e,t,i,r,s){UniformBuffer._TempBuffer[0]=t,UniformBuffer._TempBuffer[1]=i,UniformBuffer._TempBuffer[2]=r,UniformBuffer._TempBuffer[3]=s,this.updateUniform(e,UniformBuffer._TempBuffer,4)}_updateFloatArrayForEffect(e,t){this._currentEffect.setFloatArray(e,t)}_updateFloatArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateArrayForEffect(e,t){this._currentEffect.setArray(e,t)}_updateArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateIntArrayForEffect(e,t){this._currentEffect.setIntArray(e,t)}_updateIntArrayForUniform(e,t){UniformBuffer._TempBufferInt32View.set(t),this.updateUniformArray(e,UniformBuffer._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){UniformBuffer._TempBufferUInt32View.set(t),this.updateUniformArray(e,UniformBuffer._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.toArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){UniformBuffer._TempBuffer[0]=t.x,UniformBuffer._TempBuffer[1]=t.y,UniformBuffer._TempBuffer[2]=t.z,this.updateUniform(e,UniformBuffer._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){UniformBuffer._TempBuffer[0]=t.x,UniformBuffer._TempBuffer[1]=t.y,UniformBuffer._TempBuffer[2]=t.z,UniformBuffer._TempBuffer[3]=t.w,this.updateUniform(e,UniformBuffer._TempBuffer,4)}_updateColor3ForEffect(e,t,i=""){this._currentEffect.setColor3(e+i,t)}_updateColor3ForUniform(e,t){UniformBuffer._TempBuffer[0]=t.r,UniformBuffer._TempBuffer[1]=t.g,UniformBuffer._TempBuffer[2]=t.b,this.updateUniform(e,UniformBuffer._TempBuffer,3)}_updateColor4ForEffect(e,t,i,r=""){this._currentEffect.setColor4(e+r,t,i)}_updateDirectColor4ForEffect(e,t,i=""){this._currentEffect.setDirectColor4(e+i,t)}_updateColor4ForUniform(e,t,i){UniformBuffer._TempBuffer[0]=t.r,UniformBuffer._TempBuffer[1]=t.g,UniformBuffer._TempBuffer[2]=t.b,UniformBuffer._TempBuffer[3]=i,this.updateUniform(e,UniformBuffer._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){UniformBuffer._TempBuffer[0]=t.r,UniformBuffer._TempBuffer[1]=t.g,UniformBuffer._TempBuffer[2]=t.b,UniformBuffer._TempBuffer[3]=t.a,this.updateUniform(e,UniformBuffer._TempBuffer,4)}_updateIntForEffect(e,t,i=""){this._currentEffect.setInt(e+i,t)}_updateIntForUniform(e,t){UniformBuffer._TempBufferInt32View[0]=t,this.updateUniform(e,UniformBuffer._TempBuffer,1)}_updateInt2ForEffect(e,t,i,r=""){this._currentEffect.setInt2(e+r,t,i)}_updateInt2ForUniform(e,t,i){UniformBuffer._TempBufferInt32View[0]=t,UniformBuffer._TempBufferInt32View[1]=i,this.updateUniform(e,UniformBuffer._TempBuffer,2)}_updateInt3ForEffect(e,t,i,r,s=""){this._currentEffect.setInt3(e+s,t,i,r)}_updateInt3ForUniform(e,t,i,r){UniformBuffer._TempBufferInt32View[0]=t,UniformBuffer._TempBufferInt32View[1]=i,UniformBuffer._TempBufferInt32View[2]=r,this.updateUniform(e,UniformBuffer._TempBuffer,3)}_updateInt4ForEffect(e,t,i,r,s,a=""){this._currentEffect.setInt4(e+a,t,i,r,s)}_updateInt4ForUniform(e,t,i,r,s){UniformBuffer._TempBufferInt32View[0]=t,UniformBuffer._TempBufferInt32View[1]=i,UniformBuffer._TempBufferInt32View[2]=r,UniformBuffer._TempBufferInt32View[3]=s,this.updateUniform(e,UniformBuffer._TempBuffer,4)}_updateUIntForEffect(e,t,i=""){this._currentEffect.setUInt(e+i,t)}_updateUIntForUniform(e,t){UniformBuffer._TempBufferUInt32View[0]=t,this.updateUniform(e,UniformBuffer._TempBuffer,1)}_updateUInt2ForEffect(e,t,i,r=""){this._currentEffect.setUInt2(e+r,t,i)}_updateUInt2ForUniform(e,t,i){UniformBuffer._TempBufferUInt32View[0]=t,UniformBuffer._TempBufferUInt32View[1]=i,this.updateUniform(e,UniformBuffer._TempBuffer,2)}_updateUInt3ForEffect(e,t,i,r,s=""){this._currentEffect.setUInt3(e+s,t,i,r)}_updateUInt3ForUniform(e,t,i,r){UniformBuffer._TempBufferUInt32View[0]=t,UniformBuffer._TempBufferUInt32View[1]=i,UniformBuffer._TempBufferUInt32View[2]=r,this.updateUniform(e,UniformBuffer._TempBuffer,3)}_updateUInt4ForEffect(e,t,i,r,s,a=""){this._currentEffect.setUInt4(e+a,t,i,r,s)}_updateUInt4ForUniform(e,t,i,r,s){UniformBuffer._TempBufferUInt32View[0]=t,UniformBuffer._TempBufferUInt32View[1]=i,UniformBuffer._TempBufferUInt32View[2]=r,UniformBuffer._TempBufferUInt32View[3]=s,this.updateUniform(e,UniformBuffer._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}bindTexture(e,t){this._currentEffect._bindTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t){let i=this._buffers[t];if(i[0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,!0}return!1}dispose(){if(this._noUBO)return;let e=this._engine._uniformBuffers,t=e.indexOf(this);if(-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._features.trackUbosInFrame&&this._buffers)for(let e=0;e<this._buffers.length;++e){let t=this._buffers[e][0];this._engine._releaseBuffer(t)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}};UniformBuffer._UpdatedUbosInFrame={},UniformBuffer._MAX_UNIFORM_SIZE=256,UniformBuffer._TempBuffer=new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE),UniformBuffer._TempBufferInt32View=new Int32Array(UniformBuffer._TempBuffer.buffer),UniformBuffer._TempBufferUInt32View=new Uint32Array(UniformBuffer._TempBuffer.buffer);let Buffer=class Buffer{get isDisposed(){return this._isDisposed}constructor(e,t,i,r=0,s=!1,a=!1,n=!1,o,l){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=a,this._divisor=o||1,this._label=l,t instanceof dataBuffer_DataBuffer?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=n?r:r*Float32Array.BYTES_PER_ELEMENT,s||this.create()}createVertexBuffer(e,t,i,r,s,a=!1,n){let o=a?t:t*Float32Array.BYTES_PER_ELEMENT,l=r?a?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new buffer_VertexBuffer(this._engine,this,e,this._updatable,!0,l,void 0===s?this._instanced:s,o,i,void 0,void 0,!0,this._divisor||n)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){(e||!this._buffer)&&(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label))}_rebuild(){this._buffer=null,this.create(this._data)}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),0===t&&void 0===i?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}};let buffer_VertexBuffer=class buffer_VertexBuffer{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){let t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get totalVertices(){let e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,r,s,a,n,o,l,h,c=!1,u=!1,d=1,_=!1){var p,f,m,g,v;this._isDisposed=!1;let x=!1;if(this.engine=e,"object"==typeof r&&null!==r?(x=null!==(p=r.updatable)&&void 0!==p&&p,s=r.postponeInternalCreation,a=r.stride,n=r.instanced,o=r.offset,l=r.size,h=r.type,c=null!==(f=r.normalized)&&void 0!==f&&f,u=null!==(m=r.useBytes)&&void 0!==m&&m,d=null!==(g=r.divisor)&&void 0!==g?g:1,_=null!==(v=r.takeBufferOwnership)&&void 0!==v&&v,this._label=r.label):x=!!r,t instanceof Buffer?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new Buffer(e,t,x,a,s,n,u,d,this._label),this._ownsBuffer=!0),this.uniqueId=buffer_VertexBuffer._Counter++,this._kind=i,void 0===h){let e=this.getData();this.type=e?buffer_VertexBuffer.GetDataType(e):buffer_VertexBuffer.FLOAT}else this.type=h;let b=buffer_VertexBuffer.GetTypeByteLength(this.type);u?(this._size=l||(a?a/b:buffer_VertexBuffer.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*b,this.byteOffset=o||0):(this._size=l||a||buffer_VertexBuffer.DeduceStride(i),this.byteStride=a?a*b:this._buffer.byteStride||this._size*b,this.byteOffset=(o||0)*b),this.normalized=c,this._instanced=void 0!==n&&n,this._instanceDivisor=n?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){var e;null===(e=this._buffer)||void 0===e||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){let i=this.getData();return i?(e=null!=e?e:this.totalVertices,buffer_VertexBuffer.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t)):null}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/buffer_VertexBuffer.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/buffer_VertexBuffer.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*buffer_VertexBuffer.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){buffer_VertexBuffer.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case buffer_VertexBuffer.UVKind:case buffer_VertexBuffer.UV2Kind:case buffer_VertexBuffer.UV3Kind:case buffer_VertexBuffer.UV4Kind:case buffer_VertexBuffer.UV5Kind:case buffer_VertexBuffer.UV6Kind:return 2;case buffer_VertexBuffer.NormalKind:case buffer_VertexBuffer.PositionKind:return 3;case buffer_VertexBuffer.ColorKind:case buffer_VertexBuffer.ColorInstanceKind:case buffer_VertexBuffer.MatricesIndicesKind:case buffer_VertexBuffer.MatricesIndicesExtraKind:case buffer_VertexBuffer.MatricesWeightsKind:case buffer_VertexBuffer.MatricesWeightsExtraKind:case buffer_VertexBuffer.TangentKind:return 4;default:throw Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?buffer_VertexBuffer.BYTE:e instanceof Uint8Array?buffer_VertexBuffer.UNSIGNED_BYTE:e instanceof Int16Array?buffer_VertexBuffer.SHORT:e instanceof Uint16Array?buffer_VertexBuffer.UNSIGNED_SHORT:e instanceof Int32Array?buffer_VertexBuffer.INT:e instanceof Uint32Array?buffer_VertexBuffer.UNSIGNED_INT:buffer_VertexBuffer.FLOAT}static GetTypeByteLength(e){switch(e){case buffer_VertexBuffer.BYTE:case buffer_VertexBuffer.UNSIGNED_BYTE:return 1;case buffer_VertexBuffer.SHORT:case buffer_VertexBuffer.UNSIGNED_SHORT:return 2;case buffer_VertexBuffer.INT:case buffer_VertexBuffer.UNSIGNED_INT:case buffer_VertexBuffer.FLOAT:return 4;default:throw Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,r,s,a,n,o){if(e instanceof Array){let s=t/4,n=i/4;for(let t=0;t<a;t+=r){for(let i=0;i<r;i++)o(e[s+i],t+i);s+=n}}else{let l=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),h=buffer_VertexBuffer.GetTypeByteLength(s);for(let e=0;e<a;e+=r){let a=t;for(let t=0;t<r;t++){let i=buffer_VertexBuffer._GetFloatValue(l,s,a,n);o(i,e+t),a+=h}t+=i}}}static _GetFloatValue(e,t,i,r){switch(t){case buffer_VertexBuffer.BYTE:{let t=e.getInt8(i);return r&&(t=Math.max(t/127,-1)),t}case buffer_VertexBuffer.UNSIGNED_BYTE:{let t=e.getUint8(i);return r&&(t/=255),t}case buffer_VertexBuffer.SHORT:{let t=e.getInt16(i,!0);return r&&(t=Math.max(t/32767,-1)),t}case buffer_VertexBuffer.UNSIGNED_SHORT:{let t=e.getUint16(i,!0);return r&&(t/=65535),t}case buffer_VertexBuffer.INT:return e.getInt32(i,!0);case buffer_VertexBuffer.UNSIGNED_INT:return e.getUint32(i,!0);case buffer_VertexBuffer.FLOAT:return e.getFloat32(i,!0);default:throw Error(`Invalid component type ${t}`)}}static GetFloatData(e,t,i,r,s,a,n,o){let l=t*buffer_VertexBuffer.GetTypeByteLength(i),h=n*t;if(i!==buffer_VertexBuffer.FLOAT||s!==l){let n=new Float32Array(h);return buffer_VertexBuffer.ForEach(e,r,s,t,i,h,a,(e,t)=>n[t]=e),n}if(!(e instanceof Array||e instanceof Float32Array)||0!==r||e.length!==h){if(e instanceof Array){let t=r/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,r,h);{let t=e.byteOffset+r;if(o){let i=new Float32Array(h),r=new Float32Array(e.buffer,t,h);return i.set(r),i}let i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return o?e.slice():e}};buffer_VertexBuffer._Counter=0,buffer_VertexBuffer.BYTE=5120,buffer_VertexBuffer.UNSIGNED_BYTE=5121,buffer_VertexBuffer.SHORT=5122,buffer_VertexBuffer.UNSIGNED_SHORT=5123,buffer_VertexBuffer.INT=5124,buffer_VertexBuffer.UNSIGNED_INT=5125,buffer_VertexBuffer.FLOAT=5126,buffer_VertexBuffer.PositionKind="position",buffer_VertexBuffer.NormalKind="normal",buffer_VertexBuffer.TangentKind="tangent",buffer_VertexBuffer.UVKind="uv",buffer_VertexBuffer.UV2Kind="uv2",buffer_VertexBuffer.UV3Kind="uv3",buffer_VertexBuffer.UV4Kind="uv4",buffer_VertexBuffer.UV5Kind="uv5",buffer_VertexBuffer.UV6Kind="uv6",buffer_VertexBuffer.ColorKind="color",buffer_VertexBuffer.ColorInstanceKind="instanceColor",buffer_VertexBuffer.MatricesIndicesKind="matricesIndices",buffer_VertexBuffer.MatricesWeightsKind="matricesWeights",buffer_VertexBuffer.MatricesIndicesExtraKind="matricesIndicesExtra",buffer_VertexBuffer.MatricesWeightsExtraKind="matricesWeightsExtra";let PickingInfo=class PickingInfo{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){let i;if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind))return null;let r=this.pickedMesh.getIndices();(null==r?void 0:r.length)===0&&(r=null);let s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[1],n=math_vector_TmpVectors.Vector3[2];if(t){let e=this.pickedMesh.getVerticesData(buffer_VertexBuffer.NormalKind),t=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId],s):s.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),o=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId+1],a):a.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),l=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId+2],n):n.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]);t=t.scale(this.bu),o=o.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new math_vector_Vector3(t.x+o.x+l.x,t.y+o.y+l.y,t.z+o.z+l.z)}else{let e=this.pickedMesh.getVerticesData(buffer_VertexBuffer.PositionKind),t=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId],s):s.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),o=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId+1],a):a.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),l=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId+2],n):n.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]),h=t.subtract(o),c=l.subtract(o);i=math_vector_Vector3.Cross(h,c)}let transformNormalToWorld=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(math_vector_TmpVectors.Matrix[0].copyFrom(i),(i=math_vector_TmpVectors.Matrix[0]).setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(math_vector_TmpVectors.Matrix[1]),i=math_vector_TmpVectors.Matrix[1]),math_vector_Vector3.TransformNormalToRef(t,i,t)};if(e&&transformNormalToWorld(this.pickedMesh,i),this.ray){let t=math_vector_TmpVectors.Vector3[0].copyFrom(i);e||transformNormalToWorld(this.pickedMesh,t),math_vector_Vector3.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=buffer_VertexBuffer.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;let t=this.pickedMesh.getIndices();if(!t)return null;let i=this.pickedMesh.getVerticesData(e);if(!i)return null;let r=math_vector_Vector2.FromArray(i,2*t[3*this.faceId]),s=math_vector_Vector2.FromArray(i,2*t[3*this.faceId+1]),a=math_vector_Vector2.FromArray(i,2*t[3*this.faceId+2]);return r=r.scale(this.bu),s=s.scale(this.bv),a=a.scale(1-this.bu-this.bv),new math_vector_Vector2(r.x+s.x+a.x,r.y+s.y+a.y)}};let PostProcessManager=class PostProcessManager{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[buffer_VertexBuffer.PositionKind])return;let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(this._scene.getEngine(),e,buffer_VertexBuffer.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){let 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(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){let i=this._scene.activeCamera;return!!(i&&(t=t||i._postProcesses.filter(e=>null!=e))&&0!==t.length&&this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!=t),!0)}directRender(e,t=null,i=!1,r=0,s=0,a=!1){var n;let o=this._scene.getEngine();for(let l=0;l<e.length;l++){l<e.length-1?e[l+1].activate(this._scene.activeCamera,null==t?void 0:t.texture):(t?o.bindFramebuffer(t,r,void 0,void 0,i,s):a||o.restoreDefaultFramebuffer(),null===(n=o._debugInsertMarker)||void 0===n||n.call(o,`post process ${e[l].name} output`));let h=e[l],c=h.apply();c&&(h.onBeforeRenderObservable.notifyObservers(c),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,c),o.drawElementsType(0,0,6),h.onAfterRenderObservable.notifyObservers(c))}o.setDepthBuffer(!0),o.setDepthWrite(!0)}_finalizeFrame(e,t,i,r,s=!1){var a;let n=this._scene.activeCamera;if(!n||0===(r=r||n._postProcesses.filter(e=>null!=e)).length||!this._scene.postProcessesEnabled)return;let o=this._scene.getEngine();for(let l=0,h=r.length;l<h;l++){let c=r[l];if(l<h-1?c._outputTexture=r[l+1].activate(n,null==t?void 0:t.texture):(t?(o.bindFramebuffer(t,i,void 0,void 0,s),c._outputTexture=t):(o.restoreDefaultFramebuffer(),c._outputTexture=null),null===(a=o._debugInsertMarker)||void 0===a||a.call(o,`post process ${r[l].name} output`)),e)break;let u=c.apply();u&&(c.onBeforeRenderObservable.notifyObservers(u),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,u),o.drawElementsType(0,0,6),c.onAfterRenderObservable.notifyObservers(u))}o.setDepthBuffer(!0),o.setDepthWrite(!0),o.setAlphaMode(0)}dispose(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&(e.dispose(),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}};let RenderingGroup=class RenderingGroup{set opaqueSortCompareFn(e){e?this._opaqueSortCompareFn=e:this._opaqueSortCompareFn=RenderingGroup.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){e?this._alphaTestSortCompareFn=e:this._alphaTestSortCompareFn=RenderingGroup.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=RenderingGroup.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,r=null,s=null){this.index=e,this._opaqueSubMeshes=new SmartArray(256),this._transparentSubMeshes=new SmartArray(256),this._alphaTestSubMeshes=new SmartArray(256),this._depthOnlySubMeshes=new SmartArray(256),this._particleSystems=new SmartArray(256),this._spriteManagers=new SmartArray(256),this._empty=!0,this._edgesRenderers=new SmartArrayNoDuplicate(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=r,this.transparentSortCompareFn=s}render(e,t,i,r){if(e){e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);return}let s=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(s.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),s.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);let a=s.getStencilBuffer();if(s.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(r),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency){if(s.setStencilBuffer(a),this._scene.useOrderIndependentTransparency){let e=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);e.length&&this._renderTransparent(e)}else this._renderTransparent(this._transparentSubMeshes);s.setAlphaMode(0)}if(s.setStencilBuffer(!1),this._edgesRenderers.length){for(let e=0;e<this._edgesRenderers.length;e++)this._edgesRenderers.data[e].render();s.setAlphaMode(0)}s.setStencilBuffer(a)}_renderOpaqueSorted(e){return RenderingGroup._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1)}_renderAlphaTestSorted(e){return RenderingGroup._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)}_renderTransparentSorted(e){return RenderingGroup._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0)}static _RenderSorted(e,t,i,r){let s,a=0,n=i?i.globalPosition:RenderingGroup._ZeroVector;if(r)for(;a<e.length;a++)(s=e.data[a])._alphaIndex=s.getMesh().alphaIndex,s._distanceToCamera=math_vector_Vector3.Distance(s.getBoundingInfo().boundingSphere.centerWorld,n);let o=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&o.sort(t);let l=o[0].getMesh().getScene();for(a=0;a<o.length;a++)if(s=o[a],!l._activeMeshesFrozenButKeepClipping||s.isInFrustum(l._frustumPlanes)){if(r){let e=s.getMaterial();if(e&&e.needDepthPrePass){let t=e.getScene().getEngine();t.setColorWrite(!1),t.setAlphaMode(0),s.render(!1),t.setColorWrite(!0)}}s.render(r)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:RenderingGroup.backToFrontSortCompare(e,t)}static backToFrontSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0}static PainterSortCompare(e,t){let i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._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;let t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i<this._particleSystems.length;i++){let r=this._particleSystems.data[i];if(0===(t&&t.layerMask&r.layerMask))continue;let s=r.emitter;s.position&&e&&-1===e.indexOf(s)||this._scene._activeParticles.addCount(r.render(),!1)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}_renderSprites(){if(!this._scene.spritesEnabled||0===this._spriteManagers.length)return;let e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(let t=0;t<this._spriteManagers.length;t++){let i=this._spriteManagers.data[t];0!==(e&&e.layerMask&i.layerMask)&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}};RenderingGroup._ZeroVector=math_vector_Vector3.Zero();let RenderingGroupInfo=class RenderingGroupInfo{};let RenderingManager=class RenderingManager{get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(let e of this._scene.meshes)if(e.subMeshes)for(let t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(let e of this._scene.spriteManagers)e._wasDispatched=!1;for(let e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._renderingGroups=[],this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new RenderingGroupInfo,this._maintainStateBetweenFrames=!1,this._scene=e;for(let e=RenderingManager.MIN_RENDERINGGROUPS;e<RenderingManager.MAX_RENDERINGGROUPS;e++)this._autoClearDepthStencil[e]={autoClear:!0,depth:!0,stencil:!0}}getRenderingGroup(e){let t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]}_clearDepthStencilBuffer(e=!0,t=!0){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)}render(e,t,i,r){let s=this._renderingGroupInfo;if(s.scene=this._scene,s.camera=this._scene.activeCamera,this._scene.spriteManagers&&r)for(let e=0;e<this._scene.spriteManagers.length;e++){let t=this._scene.spriteManagers[e];this.dispatchSprites(t)}for(let a=RenderingManager.MIN_RENDERINGGROUPS;a<RenderingManager.MAX_RENDERINGGROUPS;a++){this._depthStencilBufferAlreadyCleaned=a===RenderingManager.MIN_RENDERINGGROUPS;let n=this._renderingGroups[a];if(!n||n._empty)continue;let o=Math.pow(2,a);if(s.renderingGroupId=a,this._scene.onBeforeRenderingGroupObservable.notifyObservers(s,o),RenderingManager.AUTOCLEAR){let e=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(a):this._autoClearDepthStencil[a];e&&e.autoClear&&this._clearDepthStencilBuffer(e.depth,e.stencil)}for(let e of this._scene._beforeRenderingGroupDrawStage)e.action(a);for(let s of(n.render(e,r,i,t),this._scene._afterRenderingGroupDrawStage))s.action(a);this._scene.onAfterRenderingGroupObservable.notifyObservers(s,o)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=RenderingManager.MIN_RENDERINGGROUPS;e<RenderingManager.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=RenderingManager.MIN_RENDERINGGROUPS;e<RenderingManager.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.prepareSprites()}}dispose(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null}freeRenderingGroups(){for(let e=RenderingManager.MIN_RENDERINGGROUPS;e<RenderingManager.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){void 0===this._renderingGroups[e]&&(this._renderingGroups[e]=new RenderingGroup(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))}dispatchSprites(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))}dispatchParticles(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,i))}setRenderingOrder(e,t=null,i=null,r=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=r,this._renderingGroups[e]){let t=this._renderingGroups[e];t.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],t.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],t.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:r}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}};RenderingManager.MAX_RENDERINGGROUPS=4,RenderingManager.MIN_RENDERINGGROUPS=0,RenderingManager.AUTOCLEAR=!0;let sceneComponent_SceneComponentConstants=class sceneComponent_SceneComponentConstants{};sceneComponent_SceneComponentConstants.NAME_EFFECTLAYER="EffectLayer",sceneComponent_SceneComponentConstants.NAME_LAYER="Layer",sceneComponent_SceneComponentConstants.NAME_LENSFLARESYSTEM="LensFlareSystem",sceneComponent_SceneComponentConstants.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM="ParticleSystem",sceneComponent_SceneComponentConstants.NAME_GAMEPAD="Gamepad",sceneComponent_SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",sceneComponent_SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",sceneComponent_SceneComponentConstants.NAME_PREPASSRENDERER="PrePassRenderer",sceneComponent_SceneComponentConstants.NAME_DEPTHRENDERER="DepthRenderer",sceneComponent_SceneComponentConstants.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",sceneComponent_SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",sceneComponent_SceneComponentConstants.NAME_SPRITE="Sprite",sceneComponent_SceneComponentConstants.NAME_SUBSURFACE="SubSurface",sceneComponent_SceneComponentConstants.NAME_OUTLINERENDERER="Outline",sceneComponent_SceneComponentConstants.NAME_PROCEDURALTEXTURE="ProceduralTexture",sceneComponent_SceneComponentConstants.NAME_SHADOWGENERATOR="ShadowGenerator",sceneComponent_SceneComponentConstants.NAME_OCTREE="Octree",sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE="PhysicsEngine",sceneComponent_SceneComponentConstants.NAME_AUDIO="Audio",sceneComponent_SceneComponentConstants.NAME_FLUIDRENDERER="FluidRenderer",sceneComponent_SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER=0,sceneComponent_SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,sceneComponent_SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,sceneComponent_SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,sceneComponent_SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS=0,sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER=2,sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER=1,sceneComponent_SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS=0,sceneComponent_SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE=1,sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS=0,sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE=1,sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,sceneComponent_SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,sceneComponent_SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,sceneComponent_SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,sceneComponent_SceneComponentConstants.STEP_BEFORECLEAR_PREPASS=1,sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,sceneComponent_SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,sceneComponent_SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER=1,sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS=0,sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER=4,sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,sceneComponent_SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,sceneComponent_SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,sceneComponent_SceneComponentConstants.STEP_AFTERRENDER_AUDIO=0,sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,sceneComponent_SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,sceneComponent_SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,sceneComponent_SceneComponentConstants.STEP_POINTERMOVE_SPRITE=0,sceneComponent_SceneComponentConstants.STEP_POINTERDOWN_SPRITE=0,sceneComponent_SceneComponentConstants.STEP_POINTERUP_SPRITE=0;let Stage=class Stage extends Array{constructor(e){super(...e)}static Create(){return Object.create(Stage.prototype)}registerStep(e,t,i){let r=0;for(;r<this.length;r++){let t=this[r];if(e<t.index)break}this.splice(r,0,{index:e,component:t,action:i.bind(t)})}clear(){this.length=0}};let pointerEvents_PointerEventTypes=class pointerEvents_PointerEventTypes{};pointerEvents_PointerEventTypes.POINTERDOWN=1,pointerEvents_PointerEventTypes.POINTERUP=2,pointerEvents_PointerEventTypes.POINTERMOVE=4,pointerEvents_PointerEventTypes.POINTERWHEEL=8,pointerEvents_PointerEventTypes.POINTERPICK=16,pointerEvents_PointerEventTypes.POINTERTAP=32,pointerEvents_PointerEventTypes.POINTERDOUBLETAP=64;let PointerInfoBase=class PointerInfoBase{constructor(e,t){this.type=e,this.event=t}};let PointerInfoPre=class PointerInfoPre extends PointerInfoBase{constructor(e,t,i,r){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new math_vector_Vector2(i,r)}};let PointerInfo=class PointerInfo extends PointerInfoBase{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,r=null){super(e,t),this._pickInfo=i,this._inputManager=r}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}};let KeyboardEventTypes=class KeyboardEventTypes{};KeyboardEventTypes.KEYDOWN=1,KeyboardEventTypes.KEYUP=2;let KeyboardInfo=class KeyboardInfo{constructor(e,t){this.type=e,this.event=t}};let KeyboardInfoPre=class KeyboardInfoPre extends KeyboardInfo{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}};(function(e){e[e.Generic=0]="Generic",e[e.Keyboard=1]="Keyboard",e[e.Mouse=2]="Mouse",e[e.Touch=3]="Touch",e[e.DualShock=4]="DualShock",e[e.Xbox=5]="Xbox",e[e.Switch=6]="Switch",e[e.DualSense=7]="DualSense"})(Q||(Q={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.Move=12]="Move"}(Z||(Z={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.DeltaHorizontal=10]="DeltaHorizontal",e[e.DeltaVertical=11]="DeltaVertical"}(J||(J={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(ee||(ee={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Create=8]="Create",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(et||(et={})),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.LT=6]="LT",e[e.RT=7]="RT",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.LStickXAxis=17]="LStickXAxis",e[e.LStickYAxis=18]="LStickYAxis",e[e.RStickXAxis=19]="RStickXAxis",e[e.RStickYAxis=20]="RStickYAxis"}(ei||(ei={})),function(e){e[e.B=0]="B",e[e.A=1]="A",e[e.Y=2]="Y",e[e.X=3]="X",e[e.L=4]="L",e[e.R=5]="R",e[e.ZL=6]="ZL",e[e.ZR=7]="ZR",e[e.Minus=8]="Minus",e[e.Plus=9]="Plus",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.Capture=17]="Capture",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(er||(er={})),function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(es||(es={}));let EventConstants=class EventConstants{};EventConstants.DOM_DELTA_PIXEL=0,EventConstants.DOM_DELTA_LINE=1,EventConstants.DOM_DELTA_PAGE=2;let DeviceEventFactory=class DeviceEventFactory{static CreateDeviceEvent(e,t,i,r,s,a,n){switch(e){case Q.Keyboard:return this._CreateKeyboardEvent(i,r,s,a);case Q.Mouse:if(i===Z.MouseWheelX||i===Z.MouseWheelY||i===Z.MouseWheelZ)return this._CreateWheelEvent(e,t,i,r,s,a);case Q.Touch:return this._CreatePointerEvent(e,t,i,r,s,a,n);default:throw`Unable to generate event for device ${Q[e]}`}}static _CreatePointerEvent(e,t,i,r,s,a,n){let o;let l=this._CreateMouseEvent(e,t,i,r,s,a);return e===Q.Mouse?(l.deviceType=Q.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=Q.Touch,l.pointerId=null!=n?n:t,l.pointerType="touch"),o=0+s.pollInput(e,t,Z.LeftClick)+2*s.pollInput(e,t,Z.RightClick)+4*s.pollInput(e,t,Z.MiddleClick),l.buttons=o,i===Z.Move?l.type="pointermove":i>=Z.LeftClick&&i<=Z.RightClick&&(l.type=1===r?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,r,s,a){let n=this._CreateMouseEvent(e,t,i,r,s,a);switch(n.pointerId=1,n.type="wheel",n.deltaMode=EventConstants.DOM_DELTA_PIXEL,n.deltaX=0,n.deltaY=0,n.deltaZ=0,i){case Z.MouseWheelX:n.deltaX=r;break;case Z.MouseWheelY:n.deltaY=r;break;case Z.MouseWheelZ:n.deltaZ=r}return n}static _CreateMouseEvent(e,t,i,r,s,a){let n=this._CreateEvent(a),o=s.pollInput(e,t,Z.Horizontal),l=s.pollInput(e,t,Z.Vertical);return a?(n.movementX=0,n.movementY=0,n.offsetX=n.movementX-a.getBoundingClientRect().x,n.offsetY=n.movementY-a.getBoundingClientRect().y):(n.movementX=s.pollInput(e,t,J.DeltaHorizontal),n.movementY=s.pollInput(e,t,J.DeltaVertical),n.offsetX=0,n.offsetY=0),this._CheckNonCharacterKeys(n,s),n.clientX=o,n.clientY=l,n.x=o,n.y=l,n.deviceType=e,n.deviceSlot=t,n.inputIndex=i,n}static _CreateKeyboardEvent(e,t,i,r){let s=this._CreateEvent(r);return this._CheckNonCharacterKeys(s,i),s.deviceType=Q.Keyboard,s.deviceSlot=0,s.inputIndex=e,s.type=1===t?"keydown":"keyup",s.key=String.fromCharCode(e),s.keyCode=e,s}static _CheckNonCharacterKeys(e,t){let i=t.isDeviceAvailable(Q.Keyboard),r=i&&1===t.pollInput(Q.Keyboard,0,18),s=i&&1===t.pollInput(Q.Keyboard,0,17),a=i&&(1===t.pollInput(Q.Keyboard,0,91)||1===t.pollInput(Q.Keyboard,0,92)||1===t.pollInput(Q.Keyboard,0,93)),n=i&&1===t.pollInput(Q.Keyboard,0,16);e.altKey=r,e.ctrlKey=s,e.metaKey=a,e.shiftKey=n}static _CreateEvent(e){let t={};return t.preventDefault=()=>{},t.target=e,t}};let NativeDeviceInputSystem=class NativeDeviceInputSystem{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(e,t,r,s)=>{let a=DeviceEventFactory.CreateDeviceEvent(e,t,r,s,this);i(e,t,a)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Q.Mouse||e===Q.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}};let D=Object.keys(Z).length/2;let WebDeviceInputSystem=class WebDeviceInputSystem{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=tools_Tools.IsSafari(),this._usingMacOS=IsNavigatorAvailable()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=IsNavigatorAvailable()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=IsNavigatorAvailable()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=tools_Tools.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){let r=this._inputs[e][t];if(!r)throw`Unable to find device ${Q[e]}`;e>=Q.DualShock&&e<=Q.DualSense&&this._updateDevice(e,t,i);let s=r[i];if(void 0===s)throw`Unable to find input ${i} for device ${Q[e]} in slot ${t}`;return i===Z.Move&&tools_Tools.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),s}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){let e=this===null||void 0===this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(let e of this._inputs)if(e)for(let t in e){let i=+t,r=e[i];if(r)for(let e=0;e<r.length;e++)r[e]=0}}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=-1!==this._elementToAttachTo.tabIndex?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}}_disableEvents(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),this._usingMacOS&&this._isUsingChromium&&this._elementToAttachTo.removeEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){let e=navigator.getGamepads();for(let t of e)t&&this._addGamePad(t)}"function"==typeof matchMedia&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(Q.Mouse,0,0,0)}_addGamePad(e){let t=this._getGamepadDeviceType(e.id),i=e.index;this._gamepads=this._gamepads||Array(e.index+1),this._registerDevice(t,i,e.buttons.length+e.axes.length),this._gamepads[i]=t}_addPointerDevice(e,t,i,r){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,D);let s=this._inputs[e][t];s[0]=i,s[1]=r}_registerDevice(e,t,i){if(void 0===t)throw`Unable to register device ${Q[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){let r=Array(i);r.fill(0),this._inputs[e][t]=r,this._onDeviceConnected(e,t)}}_unregisterDevice(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))}_handleKeyActions(){this._keyboardDownEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Q.Keyboard,0,255));let t=this._inputs[Q.Keyboard][0];t&&(t[e.keyCode]=1,e.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&!this._metaKeys.includes(e.keyCode)&&this._metaKeys.push(e.keyCode),this._onInputChanged(Q.Keyboard,0,e))},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Q.Keyboard,0,255));let t=this._inputs[Q.Keyboard][0];if(t){if(t[e.keyCode]=0,e.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(let e of this._metaKeys){let i=DeviceEventFactory.CreateDeviceEvent(Q.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(Q.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Q.Keyboard,0,e)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){let e=this._inputs[Q.Keyboard][0];for(let t=0;t<e.length;t++)if(0!==e[t]){e[t]=0;let i=DeviceEventFactory.CreateDeviceEvent(Q.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Q.Keyboard,0,i)}this._usingMacOS&&this._metaKeys.splice(0,this._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)}_handlePointerActions(){this._maxTouchPoints=IsNavigatorAvailable()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=Array(this._maxTouchPoints));for(let e=0;e<this._maxTouchPoints;e++)this._activeTouchIds[e]=-1;this._pointerMoveEvent=e=>{let t=this._getPointerType(e),i=t===Q.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Q.Touch&&-1===i){let r=this._activeTouchIds.indexOf(-1);if(r>=0)i=r,this._activeTouchIds[r]=e.pointerId,this._onDeviceConnected(t,i);else{tools_Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);let r=this._inputs[t][i];r&&(e.inputIndex=Z.Move,r[Z.Horizontal]=e.clientX,r[Z.Vertical]=e.clientY,t===Q.Touch&&0===r[Z.LeftClick]&&(r[Z.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,e),this._usingSafari||-1===e.button||(e.inputIndex=e.button+2,r[e.button+2]=r[e.button+2]?0:1,this._onInputChanged(t,i,e)))},this._pointerDownEvent=e=>{let t=this._getPointerType(e),i=t===Q.Mouse?0:e.pointerId;if(t===Q.Touch){let t=this._activeTouchIds.indexOf(-1);if(t>=0)i=t,this._activeTouchIds[t]=e.pointerId;else{tools_Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===Q.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);let r=this._inputs[t][i];if(r){let s=r[Z.Horizontal],a=r[Z.Vertical];if(t===Q.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}r[Z.Horizontal]=e.clientX,r[Z.Vertical]=e.clientY,r[e.button+2]=1,e.inputIndex=e.button+2,this._onInputChanged(t,i,e),(s!==e.clientX||a!==e.clientY)&&(e.inputIndex=Z.Move,this._onInputChanged(t,i,e))}},this._pointerUpEvent=e=>{var t,i,r,s,a;let n=this._getPointerType(e),o=n===Q.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(n===Q.Touch){if(-1===o)return;this._activeTouchIds[o]=-1}let l=null===(t=this._inputs[n])||void 0===t?void 0:t[o];if(l&&0!==l[e.button+2]){let t=l[Z.Horizontal],h=l[Z.Vertical];l[Z.Horizontal]=e.clientX,l[Z.Vertical]=e.clientY,l[e.button+2]=0,void 0===e.pointerId&&(e.pointerId=this._mouseId),(t!==e.clientX||h!==e.clientY)&&(e.inputIndex=Z.Move,this._onInputChanged(n,o,e)),e.inputIndex=e.button+2,n===Q.Mouse&&this._mouseId>=0&&(null===(r=(i=this._elementToAttachTo).hasPointerCapture)||void 0===r?void 0:r.call(i,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&(null===(a=(s=this._elementToAttachTo).hasPointerCapture)||void 0===a?void 0:a.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(n,o,e),n===Q.Touch&&this._onDeviceDisconnected(n,o)}},this._pointerCancelEvent=e=>{var t,i,r,s;if("mouse"===e.pointerType){let e=this._inputs[Q.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=Z.LeftClick;t<=Z.BrowserForward;t++)if(1===e[t]){e[t]=0;let i=DeviceEventFactory.CreateDeviceEvent(Q.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Q.Mouse,0,i)}}else{let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;(null===(s=(r=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(r,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[Q.Touch][t][Z.LeftClick]=0;let i=DeviceEventFactory.CreateDeviceEvent(Q.Touch,t,Z.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(Q.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(Q.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1,noop=function(){};try{let t=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",noop,t),this._elementToAttachTo.removeEventListener("test",noop,t)}catch(e){}this._pointerBlurEvent=()=>{var e,t,i,r,s;if(this.isDeviceAvailable(Q.Mouse)){let i=this._inputs[Q.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=Z.LeftClick;e<=Z.BrowserForward;e++)if(1===i[e]){i[e]=0;let t=DeviceEventFactory.CreateDeviceEvent(Q.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(Q.Mouse,0,t)}}if(this.isDeviceAvailable(Q.Touch)){let e=this._inputs[Q.Touch];for(let t=0;t<this._activeTouchIds.length;t++){let a=this._activeTouchIds[t];if((null===(r=(i=this._elementToAttachTo).hasPointerCapture)||void 0===r?void 0:r.call(i,a))&&this._elementToAttachTo.releasePointerCapture(a),-1!==a&&(null===(s=e[t])||void 0===s?void 0:s[Z.LeftClick])===1){e[t][Z.LeftClick]=0;let i=DeviceEventFactory.CreateDeviceEvent(Q.Touch,t,Z.LeftClick,0,this,this._elementToAttachTo,a);this._onInputChanged(Q.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(Q.Touch,t)}}}},this._pointerWheelEvent=e=>{let t=Q.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,D));let i=this._inputs[t][0];i&&(i[Z.MouseWheelX]=e.deltaX||0,i[Z.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[Z.MouseWheelZ]=e.deltaZ||0,void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[Z.MouseWheelX]&&(e.inputIndex=Z.MouseWheelX,this._onInputChanged(t,0,e)),0!==i[Z.MouseWheelY]&&(e.inputIndex=Z.MouseWheelY,this._onInputChanged(t,0,e)),0!==i[Z.MouseWheelZ]&&(e.inputIndex=Z.MouseWheelZ,this._onInputChanged(t,0,e)))},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(Q.Mouse)){let e=this._inputs[Q.Mouse][0];e[Z.MouseWheelX]=0,e[Z.MouseWheelY]=0,e[Z.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){let 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){let r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){let s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return -1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?Q.DualSense:Q.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?Q.Xbox:-1!==e.indexOf("057e")?Q.Switch:Q.Generic}_getPointerType(e){let t=Q.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=Q.Touch),t}};let DeviceSource=class DeviceSource{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new observable_Observable,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}};let InternalDeviceSourceManager=class InternalDeviceSourceManager{constructor(e){this._registeredManagers=[],this._refCount=0,this.registerManager=e=>{for(let t=0;t<this._devices.length;t++){let i=this._devices[t];for(let r in i){let i=+r;e._addDevice(new DeviceSource(this._deviceInputSystem,t,i))}}this._registeredManagers.push(e)},this.unregisterManager=e=>{let t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};let t=Object.keys(Q).length/2;this._devices=Array(t);let onDeviceConnected=(e,t)=>{for(let i of(this._devices[e]||(this._devices[e]=[]),this._devices[e][t]||(this._devices[e][t]=t),this._registeredManagers)){let r=new DeviceSource(this._deviceInputSystem,e,t);i._addDevice(r)}},onDeviceDisconnected=(e,t)=>{var i;for(let r of((null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t],this._registeredManagers))r._removeDevice(e,t)},onInputChanged=(e,t,i)=>{if(i)for(let r of this._registeredManagers)r._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new NativeDeviceInputSystem(onDeviceConnected,onDeviceDisconnected,onInputChanged):this._deviceInputSystem=new WebDeviceInputSystem(e,onDeviceConnected,onDeviceDisconnected,onInputChanged)}dispose(){this._deviceInputSystem.dispose()}};let DeviceSourceManager=class DeviceSourceManager{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){let t=Object.keys(Q).length/2;this._devices=Array(t),this._firstDevice=Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new InternalDeviceSourceManager(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new observable_Observable(e=>{for(let t of this._devices)if(t)for(let i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)}),this.onDeviceDisconnectedObservable=new observable_Observable,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]=[]),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,r;let s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(r=this._devices[e])||void 0===r?void 0:r[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;null===(s=null===(r=this._devices[e])||void 0===r?void 0:r[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Q.Keyboard:case Q.Mouse:this._firstDevice[e]=0;break;case Q.Touch:case Q.DualSense:case Q.DualShock:case Q.Xbox:case Q.Switch:case Q.Generic:{delete this._firstDevice[e];let t=this._devices[e];if(t){for(let i=0;i<t.length;i++)if(t[i]){this._firstDevice[e]=i;break}}}}}};let _ClickInfo=class _ClickInfo{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}};let InputManager=class InputManager{constructor(e){if(this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new math_vector_Vector2(0,0),this._previousStartingPointerPosition=new math_vector_Vector2(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||engineStore_EngineStore.LastCreatedScene,!this._scene)return}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new math_vector_Vector2(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){let t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){let i;let r=this._scene,s=r.getEngine(),a=s.getInputElement();for(let i of(a&&(a.tabIndex=s.canvasTabIndex,r.doNotHandleCursors||(a.style.cursor=r.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,r),r._pointerMoveStage)){e=e||this._pickMove(t);let r=null!=e&&!!e.pickedMesh;e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,r,a)}let n=t.inputIndex>=Z.MouseWheelX&&t.inputIndex<=Z.MouseWheelZ?pointerEvents_PointerEventTypes.POINTERWHEEL:pointerEvents_PointerEventTypes.POINTERMOVE;r.onPointerMove&&(e=e||this._pickMove(t),r.onPointerMove(t,e,n)),e?(i=new PointerInfo(n,t,e),this._setRayOnPointerInfo(e,t)):(i=new PointerInfo(n,t,null,this),this._movePointerInfo=i),r.onPointerObservable.hasObservers()&&r.onPointerObservable.notifyObservers(i,n)}_setRayOnPointerInfo(e,t){let i=this._scene;e&&i._pickingAvailable&&!e.ray&&(e.ray=i.createPickingRay(t.offsetX,t.offsetY,math_vector_Matrix.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){let r=this._scene,s=new PointerInfoPre(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,e.originMesh&&(s.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){let 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){let r=i.getEngine(),s=r.getInputElement();if(null==e?void 0:e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){let e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){let i=new PointerEvent("pointermove",t);i.inputIndex=Z.Move,this._checkPrePointerObservable(e,i,pointerEvents_PointerEventTypes.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){let i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,pointerEvents_PointerEventTypes.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){let i;let r=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;let i=e.pickedMesh._getActionManagerForTrigger();if(i){if(i.hasPickTriggers)switch(i.processTrigger(5,ActionEvent.CreateNew(e.pickedMesh,t,e)),t.button){case 0:i.processTrigger(2,ActionEvent.CreateNew(e.pickedMesh,t,e));break;case 1:i.processTrigger(4,ActionEvent.CreateNew(e.pickedMesh,t,e));break;case 2:i.processTrigger(3,ActionEvent.CreateNew(e.pickedMesh,t,e))}i.hasSpecificTrigger(8)&&window.setTimeout(()=>{let e=r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh,!1,r.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&i&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>InputManager.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,i.processTrigger(8,ActionEvent.CreateNew(e.pickedMesh,t)))},InputManager.LongPressDelay)}}else for(let i of r._pointerDownStage)e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s=pointerEvents_PointerEventTypes.POINTERDOWN;e?(r.onPointerDown&&r.onPointerDown(t,e,s),i=new PointerInfo(s,t,e),this._setRayOnPointerInfo(e,t)):i=new PointerInfo(s,t,null,this),r.onPointerObservable.hasObservers()&&r.onPointerObservable.notifyObservers(i,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){let r=new PointerEvent("pointerup",t);r.inputIndex=Z.Move;let s=new _ClickInfo;i?s.doubleClick=!0:s.singleClick=!0,this._checkPrePointerObservable(e,r,pointerEvents_PointerEventTypes.POINTERUP)||this._processPointerUp(e,r,s)}_processPointerUp(e,t,i){let r=this._scene;if(null==e?void 0:e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){let i=pointerEvents_PointerEventTypes.POINTERPICK,s=new PointerInfo(i,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,i)}let s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,ActionEvent.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,ActionEvent.CreateNew(e.pickedMesh,t,e));let r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,ActionEvent.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(let s of r._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){let e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,ActionEvent.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){let s=new PointerInfo(pointerEvents_PointerEventTypes.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,pointerEvents_PointerEventTypes.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,pointerEvents_PointerEventTypes.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let s=0;if(i.singleClick?s=pointerEvents_PointerEventTypes.POINTERTAP:i.doubleClick&&(s=pointerEvents_PointerEventTypes.POINTERDOUBLETAP),s){let i=new PointerInfo(s,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(s)&&r.onPointerObservable.notifyObservers(i,s)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,r=null){let s=this._scene,a=s.getEngine();r||(r=a.getInputElement()),this._alreadyAttached&&this.detachControl(),r&&(this._alreadyAttachedTo=r),this._deviceSourceManager=new DeviceSourceManager(a),this._initActionManager=e=>{if(!this._meshPickProceed){let t=!s.skipPointerUpPicking&&(0!==s._registeredActions||this._checkForPicking()||s.onPointerUp)?s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,s.pointerUpFastCheck,s.cameraToUseForPointers):null;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>InputManager.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){let t=this._delayedClicks[e].evt,i=pointerEvents_PointerEventTypes.POINTERTAP,r=new PointerInfo(i,t,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(i)&&s.onPointerObservable.notifyObservers(r,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,r)=>{var s,a;let n=new _ClickInfo;this._currentPickResult=null;let o=null,l=e.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERPICK)||t.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERPICK)||e.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERTAP)||t.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERTAP)||e.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP)||t.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP);!l&&AbstractActionManager&&(o=this._initActionManager(o,n))&&(l=o.hasPickTriggers);let h=!1;if(l){let l=i.button;if(n.hasSwiped=this._isPointerSwiping(),!n.hasSwiped){let c=!InputManager.ExclusiveDoubleClickMode;if(!c&&(c=!e.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP)&&!t.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP))&&!AbstractActionManager.HasSpecificTrigger(6)&&(o=this._initActionManager(o,n))&&(c=!o.hasSpecificTrigger(6)),c)(Date.now()-this._previousStartingPointerTime>InputManager.DoubleClickDelay||l!==this._previousButtonPressed)&&(n.singleClick=!0,r(n,this._currentPickResult),h=!0);else{let e={evt:i,clickInfo:n,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,l,n,r),InputManager.DoubleClickDelay)};this._delayedClicks[l]=e}let u=e.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP)||t.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP);!u&&AbstractActionManager.HasSpecificTrigger(6)&&(o=this._initActionManager(o,n))&&(u=o.hasSpecificTrigger(6)),u&&(l===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<InputManager.DoubleClickDelay&&!this._doubleClickOccured?(n.hasSwiped||this._isPointerSwiping()?(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=l,InputManager.ExclusiveDoubleClickMode?(this._delayedClicks[l]&&(clearTimeout(null===(a=this._delayedClicks[l])||void 0===a?void 0:a.timeoutId),this._delayedClicks[l]=null),r(n,this._previousPickResult)):r(n,this._currentPickResult)):(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,n.doubleClick=!0,n.ignore=!1,InputManager.ExclusiveDoubleClickMode&&this._delayedClicks[l]&&(clearTimeout(null===(s=this._delayedClicks[l])||void 0===s?void 0:s.timeoutId),this._delayedClicks[l]=null),r(n,this._currentPickResult)),h=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=l))}}h||r(n,this._currentPickResult)},this._onPointerMove=e=>{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>InputManager.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>InputManager.DragMovementThreshold),a.isPointerLock&&a._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=Z.MouseWheelX&&e.inputIndex<=Z.MouseWheelZ?pointerEvents_PointerEventTypes.POINTERWHEEL:pointerEvents_PointerEventTypes.POINTERMOVE)||!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking){this._processPointerMove(new PickingInfo,e);return}s.pointerMovePredicate||(s.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&e.layerMask)!=0));let t=s._registeredActions>0||s.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;let i;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,InputManager.ExclusiveDoubleClickMode){for(let i=0;i<this._delayedClicks.length;i++)if(this._delayedClicks[i]){if(e.button===i)clearTimeout(null===(t=this._delayedClicks[i])||void 0===t?void 0:t.timeoutId);else{let e=this._delayedClicks[i].clickInfo;this._doubleClickOccured=!1,e.singleClick=!0,e.ignore=!1;let t=this._delayedClicks[i].evt,r=pointerEvents_PointerEventTypes.POINTERTAP,a=new PointerInfo(r,t,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(a,r),this._delayedClicks[i]=null}}}this._updatePointerPosition(e),-1===this._swipeButtonPressed&&(this._swipeButtonPressed=e.button),s.preventDefaultOnPointerDown&&r&&(e.preventDefault(),r.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),!this._checkPrePointerObservable(null,e,pointerEvents_PointerEventTypes.POINTERDOWN)&&(s.cameraToUseForPointers||s.activeCamera)&&(this._pointerCaptures[e.pointerId]=!0,s.pointerDownPredicate||(s.pointerDownPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&e.layerMask)!=0)),this._pickedDownMesh=null,i=!s.skipPointerDownPicking&&(0!==s._registeredActions||this._checkForPicking()||s.onPointerDown)?s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,s.pointerDownFastCheck,s.cameraToUseForPointers):new PickingInfo,this._processPointerDown(i,e))},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),s.preventDefaultOnPointerUp&&r&&(e.preventDefault(),r.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,e,(t,i)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,pointerEvents_PointerEventTypes.POINTERUP)){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1);return}!t.hasSwiped&&(t.singleClick&&s.onPrePointerObservable.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERTAP)&&this._checkPrePointerObservable(null,e,pointerEvents_PointerEventTypes.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&s.onPrePointerObservable.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,pointerEvents_PointerEventTypes.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[e.pointerId]){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(s.cameraToUseForPointers||s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&e.layerMask)!=0)),!this._meshPickProceed&&(AbstractActionManager&&AbstractActionManager.HasTriggers||this._checkForPicking()||s.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=e=>{let t=KeyboardEventTypes.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){let i=new KeyboardInfoPre(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let i=new KeyboardInfo(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(14,ActionEvent.CreateNewFromScene(s,e))},this._onKeyUp=e=>{let t=KeyboardEventTypes.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){let i=new KeyboardInfoPre(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let i=new KeyboardInfo(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(15,ActionEvent.CreateNewFromScene(s,e))},this._deviceSourceManager.onDeviceConnectedObservable.add(r=>{r.deviceType===Q.Mouse?r.onInputChangedObservable.add(s=>{s.inputIndex===Z.LeftClick||s.inputIndex===Z.MiddleClick||s.inputIndex===Z.RightClick||s.inputIndex===Z.BrowserBack||s.inputIndex===Z.BrowserForward?t&&1===r.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===r.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===Z.Move?this._onPointerMove(s):(s.inputIndex===Z.MouseWheelX||s.inputIndex===Z.MouseWheelY||s.inputIndex===Z.MouseWheelZ)&&this._onPointerMove(s))}):r.deviceType===Q.Touch?r.onInputChangedObservable.add(s=>{s.inputIndex===Z.LeftClick&&(t&&1===r.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===r.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===Z.Move&&this._onPointerMove(s)}):r.deviceType===Q.Keyboard&&r.onInputChangedObservable.add(e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,r){let s;if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;let a=this._meshUnderPointerId[t];a&&(s=a._getActionManagerForTrigger(10))&&s.processTrigger(10,ActionEvent.CreateNew(a,r,{pointerId:t})),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,(s=e._getActionManagerForTrigger(9))&&s.processTrigger(9,ActionEvent.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){for(let t in this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null),this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}};InputManager.DragMovementThreshold=10,InputManager.LongPressDelay=500,InputManager.DoubleClickDelay=300,InputManager.ExclusiveDoubleClickMode=!1;let perfCounter_PerfCounter=class perfCounter_PerfCounter{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){perfCounter_PerfCounter.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){perfCounter_PerfCounter.Enabled&&(this._startMonitoringTime=precisionDate_PrecisionDate.Now)}endMonitoring(e=!0){if(!perfCounter_PerfCounter.Enabled)return;e&&this.fetchNewFrame();let t=precisionDate_PrecisionDate.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;let e=precisionDate_PrecisionDate.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}};perfCounter_PerfCounter.Enabled=!0;let math_plane_Plane=class math_plane_Plane{constructor(e,t,i,r){this.normal=new math_vector_Vector3(e,t,i),this.d=r}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new math_plane_Plane(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){return 397*this.normal.getHashCode()^(0|this.d)}normalize(){let e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),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){let t=math_plane_Plane._TmpMatrix;e.invertToRef(t);let i=t.m,r=this.normal.x,s=this.normal.y,a=this.normal.z,n=this.d,o=r*i[0]+s*i[1]+a*i[2]+n*i[3],l=r*i[4]+s*i[5]+a*i[6]+n*i[7],h=r*i[8]+s*i[9]+a*i[10]+n*i[11],c=r*i[12]+s*i[13]+a*i[14]+n*i[15];return new math_plane_Plane(o,l,h,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){let r;let s=t.x-e.x,a=t.y-e.y,n=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,c=a*h-n*l,u=n*o-s*h,d=s*l-a*o,_=Math.sqrt(c*c+u*u+d*d);return r=0!==_?1/_:0,this.normal.x=c*r,this.normal.y=u*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){let i=math_vector_Vector3.Dot(this.normal,e);return i<=t}signedDistanceTo(e){return math_vector_Vector3.Dot(e,this.normal)+this.d}static FromArray(e){return new math_plane_Plane(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){let r=new math_plane_Plane(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){let i=new math_plane_Plane(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){let r=-(t.x*e.x+t.y*e.y+t.z*e.z);return math_vector_Vector3.Dot(i,t)+r}};math_plane_Plane._TmpMatrix=math_vector_Matrix.Identity();let Frustum=class Frustum{static GetPlanes(e){let t=[];for(let e=0;e<6;e++)t.push(new math_plane_Plane(0,0,0,0));return Frustum.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){let 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){let 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){let 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){let 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){let 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){let 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){Frustum.GetNearPlaneToRef(e,t[0]),Frustum.GetFarPlaneToRef(e,t[1]),Frustum.GetLeftPlaneToRef(e,t[2]),Frustum.GetRightPlaneToRef(e,t[3]),Frustum.GetTopPlaneToRef(e,t[4]),Frustum.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(0>t[i].dotCoordinate(e))return!1;return!0}};let UniqueIdGenerator=class UniqueIdGenerator{static get UniqueId(){let e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}};UniqueIdGenerator._UniqueIdCounter=1;let LightConstants=class LightConstants{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}};LightConstants.FALLOFF_DEFAULT=0,LightConstants.FALLOFF_PHYSICAL=1,LightConstants.FALLOFF_GLTF=2,LightConstants.FALLOFF_STANDARD=3,LightConstants.LIGHTMAP_DEFAULT=0,LightConstants.LIGHTMAP_SPECULAR=1,LightConstants.LIGHTMAP_SHADOWSONLY=2,LightConstants.INTENSITYMODE_AUTOMATIC=0,LightConstants.INTENSITYMODE_LUMINOUSPOWER=1,LightConstants.INTENSITYMODE_LUMINOUSINTENSITY=2,LightConstants.INTENSITYMODE_ILLUMINANCE=3,LightConstants.INTENSITYMODE_LUMINANCE=4,LightConstants.LIGHTTYPEID_POINTLIGHT=0,LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT=1,LightConstants.LIGHTTYPEID_SPOTLIGHT=2,LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT=3;let PointerPickingConfiguration=class PointerPickingConfiguration{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}};!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(ea||(ea={}));let scene_Scene=class scene_Scene extends AbstractScene{static DefaultMaterialFactory(e){throw _WarnImport("StandardMaterial")}static CollisionCoordinatorFactory(){throw _WarnImport("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case ea.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case ea.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case ea.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return InputManager.DragMovementThreshold}static set DragMovementThreshold(e){InputManager.DragMovementThreshold=e}static get LongPressDelay(){return InputManager.LongPressDelay}static set LongPressDelay(e){InputManager.LongPressDelay=e}static get DoubleClickDelay(){return InputManager.DoubleClickDelay}static set DoubleClickDelay(e){InputManager.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return InputManager.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){InputManager.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){let r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,s=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return math_vector_TmpVectors.Vector4[0].set(r.x,r.y,r.z,s?-1:1),e&&(i?e.setFloat3(t,math_vector_TmpVectors.Vector4[0].x,math_vector_TmpVectors.Vector4[0].y,math_vector_TmpVectors.Vector4[0].z):e.setVector4(t,math_vector_TmpVectors.Vector4[0])),math_vector_TmpVectors.Vector4[0]}finalizeSceneUbo(){let e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=_ObserveArray(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=scene_Scene.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=scene_Scene.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(let e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e),e.addFromContainer&&e.serialize&&this._serializableComponents.push(e)}_getComponent(e){for(let t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new InputManager(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new math_color_Color4(.2,.2,.3,1),this.ambientColor=new math_color_Color3(0,0,0),this.environmentIntensity=1,this._performancePriority=ea.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new observable_Observable,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new observable_Observable,this._onDisposeObserver=null,this.onBeforeRenderObservable=new observable_Observable,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new observable_Observable,this.onAfterRenderCameraObservable=new observable_Observable,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new observable_Observable,this.onAfterAnimationsObservable=new observable_Observable,this.onBeforeDrawPhaseObservable=new observable_Observable,this.onAfterDrawPhaseObservable=new observable_Observable,this.onReadyObservable=new observable_Observable,this.onBeforeCameraRenderObservable=new observable_Observable,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new observable_Observable,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new observable_Observable,this.onAfterActiveMeshesEvaluationObservable=new observable_Observable,this.onBeforeParticlesRenderingObservable=new observable_Observable,this.onAfterParticlesRenderingObservable=new observable_Observable,this.onDataLoadedObservable=new observable_Observable,this.onNewCameraAddedObservable=new observable_Observable,this.onCameraRemovedObservable=new observable_Observable,this.onNewLightAddedObservable=new observable_Observable,this.onLightRemovedObservable=new observable_Observable,this.onNewGeometryAddedObservable=new observable_Observable,this.onGeometryRemovedObservable=new observable_Observable,this.onNewTransformNodeAddedObservable=new observable_Observable,this.onTransformNodeRemovedObservable=new observable_Observable,this.onNewMeshAddedObservable=new observable_Observable,this.onMeshRemovedObservable=new observable_Observable,this.onNewSkeletonAddedObservable=new observable_Observable,this.onSkeletonRemovedObservable=new observable_Observable,this.onNewMaterialAddedObservable=new observable_Observable,this.onNewMultiMaterialAddedObservable=new observable_Observable,this.onMaterialRemovedObservable=new observable_Observable,this.onMultiMaterialRemovedObservable=new observable_Observable,this.onNewTextureAddedObservable=new observable_Observable,this.onTextureRemovedObservable=new observable_Observable,this.onBeforeRenderTargetsRenderObservable=new observable_Observable,this.onAfterRenderTargetsRenderObservable=new observable_Observable,this.onBeforeStepObservable=new observable_Observable,this.onAfterStepObservable=new observable_Observable,this.onActiveCameraChanged=new observable_Observable,this.onActiveCamerasChanged=new observable_Observable,this.onBeforeRenderingGroupObservable=new observable_Observable,this.onAfterRenderingGroupObservable=new observable_Observable,this.onMeshImportedObservable=new observable_Observable,this.onAnimationFileImportedObservable=new observable_Observable,this._registeredForLateAnimationBindings=new SmartArrayNoDuplicate(256),this._pointerPickingConfiguration=new PointerPickingConfiguration,this.onPrePointerObservable=new observable_Observable,this.onPointerObservable=new observable_Observable,this.onPreKeyboardObservable=new observable_Observable,this.onKeyboardObservable=new observable_Observable,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=scene_Scene.FOGMODE_NONE,this.fogColor=new math_color_Color3(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new math_vector_Vector3(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new SmartArrayNoDuplicate(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new perfCounter_PerfCounter,this._activeIndices=new perfCounter_PerfCounter,this._activeParticles=new perfCounter_PerfCounter,this._activeBones=new perfCounter_PerfCounter,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=Array(256),this._activeRequests=[],this._pendingData=[],this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new SmartArray(256),this._processedMaterials=new SmartArray(256),this._renderTargets=new SmartArrayNoDuplicate(256),this._materialsRenderTargets=new SmartArrayNoDuplicate(256),this._activeParticleSystems=new SmartArray(256),this._activeSkeletons=new SmartArrayNoDuplicate(32),this._softwareSkinnedMeshes=new SmartArrayNoDuplicate(32),this._activeAnimatables=[],this._transformMatrix=math_vector_Matrix.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Stage.Create(),this._beforeClearStage=Stage.Create(),this._beforeRenderTargetClearStage=Stage.Create(),this._gatherRenderTargetsStage=Stage.Create(),this._gatherActiveCameraRenderTargetsStage=Stage.Create(),this._isReadyForMeshStage=Stage.Create(),this._beforeEvaluateActiveMeshStage=Stage.Create(),this._evaluateSubMeshStage=Stage.Create(),this._preActiveMeshStage=Stage.Create(),this._cameraDrawRenderTargetStage=Stage.Create(),this._beforeCameraDrawStage=Stage.Create(),this._beforeRenderTargetDrawStage=Stage.Create(),this._beforeRenderingGroupDrawStage=Stage.Create(),this._beforeRenderingMeshStage=Stage.Create(),this._afterRenderingMeshStage=Stage.Create(),this._afterRenderingGroupDrawStage=Stage.Create(),this._afterCameraDrawStage=Stage.Create(),this._afterCameraPostProcessStage=Stage.Create(),this._afterRenderTargetDrawStage=Stage.Create(),this._afterRenderTargetPostProcessStage=Stage.Create(),this._afterRenderStage=Stage.Create(),this._pointerMoveStage=Stage.Create(),this._pointerDownStage=Stage.Create(),this._pointerUpStage=Stage.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];let i=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);e=this._engine=e||engineStore_EngineStore.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(engineStore_EngineStore._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new RenderingManager(this),PostProcessManager&&(this.postProcessManager=new PostProcessManager(this)),IsWindowObjectExist()&&this.attachControl(),this._createUbo(),ImageProcessingConfiguration&&(this._imageProcessingConfiguration=new ImageProcessingConfiguration),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,t&&t.virtual||e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var t,i,r;let s;if(this._isDisposed)return!1;let a=this.getEngine(),n=a.currentRenderPassId;a.currentRenderPassId=null!==(i=null===(t=this.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==i?i:n;let o=!0;for(this._pendingData.length>0&&(o=!1),null===(r=this.prePassRenderer)||void 0===r||r.update(),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),s=0;s<this.meshes.length;s++){let t=this.meshes[s];if(!t.subMeshes||0===t.subMeshes.length)continue;if(!t.isReady(!0)){o=!1;continue}let i=t.hasThinInstances||"InstancedMesh"===t.getClassName()||"InstancedLinesMesh"===t.getClassName()||a.getCaps().instancedArrays&&t.instances.length>0;for(let e of this._isReadyForMeshStage)e.action(t,i)||(o=!1);if(!e)continue;let r=t.material||this.defaultMaterial;if(r){if(r._storeEffectOnSubMeshes)for(let e of t.subMeshes){let t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else r.hasRenderTargetTextures&&null!=r.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(r)&&(this._processedMaterials.push(r),this._materialsRenderTargets.concatWithNoDuplicate(r.getRenderTargetTextures()))}}if(e)for(s=0;s<this._materialsRenderTargets.length;++s){let e=this._materialsRenderTargets.data[s];e.isReadyForRendering()||(o=!1)}for(s=0;s<this.geometries.length;s++){let e=this.geometries[s];2===e.delayLoadState&&(o=!1)}if(this.activeCameras&&this.activeCameras.length>0)for(let e of this.activeCameras)e.isReady(!0)||(o=!1);else this.activeCamera&&!this.activeCamera.isReady(!0)&&(o=!1);for(let e of this.particleSystems)e.isReady()||(o=!1);if(this.layers)for(let e of this.layers)e.isReady()||(o=!1);return a.areAllEffectsReady()||(o=!1),a.currentRenderPassId=n,o}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){let execFunc=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(execFunc)})};this.registerBeforeRender(execFunc)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){let t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_checkIsReady(e=!1){if(this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=precisionDate_PrecisionDate.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,r){i||r||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),(this._viewUpdateFlag!==e.updateFlag||this._projectionUpdateFlag!==t.updateFlag)&&(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Frustum.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){let t=new UniformBuffer(this._engine,void 0,!1,null!=e?e:"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return UniqueIdGenerator.UniqueId}addMesh(e,t=!1){!this._blockEntityCollection&&(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(e=>{this.addMesh(e)}))}removeMesh(e,t=!1){let i=this.meshes.indexOf(e);return -1===i||(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(e=>{this.removeMesh(e)}),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){let t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){let e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){let t=this.skeletons.indexOf(e);return -1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){let t=this.morphTargetManagers.indexOf(e);return -1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){let t=this.lights.indexOf(e);if(-1!==t){for(let t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){let t=this.cameras.indexOf(e);if(-1===t||(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){let t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){let t=this.particleSystems.indexOf(e);return -1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){let t=this.animations.indexOf(e);return -1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){let t=this.animationGroups.indexOf(e);return -1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){let t=this.multiMaterials.indexOf(e);return -1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){let t=e._indexInSceneMaterialArray;if(-1!==t&&t<this.materials.length){if(t!==this.materials.length-1){let e=this.materials[this.materials.length-1];this.materials[t]=e,e._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t}removeActionManager(e){let t=this.actionManagers.indexOf(e);return -1!==t&&this.actionManagers.splice(t,1),t}removeTexture(e){let t=this.textures.indexOf(e);return -1!==t&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t}addLight(e){if(!this._blockEntityCollection){for(let t of(this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes(),this.meshes))-1===t.lightSources.indexOf(e)&&(t.lightSources.push(e),t._resyncLightSources());this.onNewLightAddedObservable.notifyObservers(e)}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(LightConstants.CompareLightsPriority)}addCamera(e){!this._blockEntityCollection&&(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),this.onNewSkeletonAddedObservable.notifyObservers(e))}addParticleSystem(e){this._blockEntityCollection||this.particleSystems.push(e)}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||this.animationGroups.push(e)}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),this.onNewMultiMaterialAddedObservable.notifyObservers(e))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),this.onNewMaterialAddedObservable.notifyObservers(e))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}switchActiveCamera(e,t=!0){let i=this._engine.getInputElement();i&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){let t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){let t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null}_getMaterial(e,t){for(let e=0;e<this.materials.length;e++){let i=this.materials[e];if(t(i))return i}if(e)for(let e=0;e<this.multiMaterials.length;e++){let i=this.multiMaterials[e];if(t(i))return i}return null}getMaterialByUniqueID(e,t=!1){return this._getMaterial(t,t=>t.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,t=>t.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,t=>t.name===e)}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t){for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t]}return null}getTextureByUniqueId(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null}getTextureByName(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null}getCameraById(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null}getCameraByUniqueId(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null}getCameraByName(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null}getBoneById(e){for(let t=0;t<this.skeletons.length;t++){let i=this.skeletons[t];for(let t=0;t<i.bones.length;t++)if(i.bones[t].id===e)return i.bones[t]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){let i=this.skeletons[t];for(let t=0;t<i.bones.length;t++)if(i.bones[t].name===e)return i.bones[t]}return null}getLightByName(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null}getLightById(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null}getLightByUniqueId(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null}getParticleSystemById(e){for(let t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null}getGeometryById(e){for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null}_getGeometryByUniqueId(e){if(this._geometriesByUniqueId){let t=this._geometriesByUniqueId[e];if(void 0!==t)return this.geometries[t]}else for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null}pushGeometry(e,t){return!(!t&&this._getGeometryByUniqueId(e.uniqueId))&&(this.addGeometry(e),this.onNewGeometryAddedObservable.notifyObservers(e),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(void 0===(t=this._geometriesByUniqueId[e.uniqueId]))return!1}else if((t=this.geometries.indexOf(e))<0)return!1;if(t!==this.geometries.length-1){let e=this.geometries[this.geometries.length-1];e&&(this.geometries[t]=e,this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null}getMeshesById(e){return this.meshes.filter(function(t){return t.id===e})}getTransformNodeById(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getTransformNodeByUniqueId(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null}getTransformNodesById(e){return this.transformNodes.filter(function(t){return t.id===e})}getMeshByUniqueId(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null}getLastMeshById(e){for(let t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){let t=this.getMeshById(e);if(t)return t;let i=this.getTransformNodeById(e);if(i)return i;let r=this.getLightById(e);if(r)return r;let s=this.getCameraById(e);if(s)return s;let a=this.getBoneById(e);return a||null}getNodeByName(e){let t=this.getMeshByName(e);if(t)return t;let i=this.getTransformNodeByName(e);if(i)return i;let r=this.getLightByName(e);if(r)return r;let s=this.getCameraByName(e);if(s)return s;let a=this.getBoneByName(e);return a||null}getMeshByName(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null}getTransformNodeByName(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null}getLastSkeletonById(e){for(let t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null}getSkeletonById(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByName(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null}getMorphTargetManagerById(e){for(let t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null}getMorphTargetById(e){for(let t=0;t<this.morphTargetManagers.length;++t){let i=this.morphTargetManagers[t];for(let t=0;t<i.numTargets;++t){let r=i.getTarget(t);if(r.id===e)return r}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){let i=this.morphTargetManagers[t];for(let t=0;t<i.numTargets;++t){let r=i.getTarget(t);if(r.name===e)return r}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){let i=this.postProcesses[t];if(i.name===e)return i}return null}isActiveMesh(e){return -1!==this._activeMeshes.indexOf(e)}get uid(){return this._uid||(this._uid=tools_Tools.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new StringDictionary),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new StringDictionary),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,i,r){if(r||e.isInFrustum(this._frustumPlanes)){for(let i of this._evaluateSubMeshStage)i.action(t,e);let i=e.getMaterial();null!=i&&(i.hasRenderTargetTextures&&null!=i.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(i)&&(this._processedMaterials.push(i),this._materialsRenderTargets.concatWithNoDuplicate(i.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,i))}}freeProcessedMaterials(){this._processedMaterials.dispose()}get blockfreeActiveMeshesAndRenderingGroups(){return this._preventFreeActiveMeshesAndRenderingGroups}set blockfreeActiveMeshesAndRenderingGroups(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)}freeActiveMeshes(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(let e=0;e<this.activeCameras.length;e++){let t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}}freeRenderingGroups(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(let e=0;e<this.textures.length;e++){let t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}}_isInIntermediateRendering(){return this._intermediateRendering}freezeActiveMeshes(e=!1,t,i,r=!0,s=!1){return this.executeWhenReady(()=>{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,r)for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._freeze();t&&t()}),this}unfreezeActiveMeshes(){for(let e=0;e<this.meshes.length;e++){let t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this}_executeActiveContainerCleanup(e){let t=this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode;!t&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce(()=>e.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode){this._activeMeshes.length>0&&(null===(e=this.activeCamera)||void 0===e||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){let e=this._activeMeshes.length;for(let t=0;t<e;t++){let e=this._activeMeshes.data[t];e.computeWorldMatrix()}}if(this._activeParticleSystems){let e=this._activeParticleSystems.length;for(let t=0;t<e;t++)this._activeParticleSystems.data[t].animate()}this._renderingManager.resetSprites();return}if(!this.activeCamera)return;for(let e of(this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset(),this._beforeEvaluateActiveMeshStage))e.action();let t=this.getActiveMeshCandidates(),i=t.length;for(let e=0;e<i;e++){let i=t.data[e];if(i._internalAbstractMeshDataInfo._currentLODIsUpToDate=!1,i.isBlocked||(this._totalVertices.addCount(i.getTotalVertices(),!1),!i.isReady()||!i.isEnabled()||i.scaling.hasAZeroComponent))continue;i.computeWorldMatrix(),i.actionManager&&i.actionManager.hasSpecificTriggers2(12,13)&&this._meshesForIntersections.pushNoDuplicate(i);let r=this.customLODSelector?this.customLODSelector(i,this.activeCamera):i.getLOD(this.activeCamera);if(i._internalAbstractMeshDataInfo._currentLOD=r,i._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,null!=r&&(r!==i&&0!==r.billboardMode&&r.computeWorldMatrix(),i._preActivate(),i.isVisible&&i.visibility>0&&(i.layerMask&this.activeCamera.layerMask)!=0&&(this._skipFrustumClipping||i.alwaysSelectAsActiveMesh||i.isInFrustum(this._frustumPlanes)))){for(let e of(this._activeMeshes.push(i),this.activeCamera._activeMeshes.push(i),r!==i&&r._activate(this._renderId,!1),this._preActiveMeshStage))e.action(i);i._activate(this._renderId,!1)&&(i.isAnInstance?i._internalAbstractMeshDataInfo._actAsRegularMesh&&(r=i):r._internalAbstractMeshDataInfo._onlyForInstances=!1,r._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(i,r)),i._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e<this.particleSystems.length;e++){let t=this.particleSystems[e];if(!t.isStarted()||!t.emitter)continue;let i=t.emitter;(!i.position||i.isEnabled())&&(this._activeParticleSystems.push(t),t.animate(),this._renderingManager.dispatchParticles(t))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_activeMesh(e,t){this._skeletonsEnabled&&null!==t.skeleton&&void 0!==t.skeleton&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&(t.skeleton.prepare(),this._activeBones.addCount(t.skeleton.bones.length,!1)),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t));let i=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){let r=this.getActiveSubMeshCandidates(t),s=r.length;i=i||1===s;for(let a=0;a<s;a++){let s=r.data[a];this._evaluateSubMesh(s,t,e,i)}}}updateTransformMatrix(e){if(this.activeCamera){if(this.activeCamera._renderingMultiview){let t=this.activeCamera._rigCameras[0],i=this.activeCamera._rigCameras[1];this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e),i.getViewMatrix(),i.getProjectionMatrix(e))}else this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(e))}}_bindFrameBuffer(e,t=!0){e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer(),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(e&&e._multiviewTexture);else if(e&&e.outputRenderTarget&&!e._renderingMultiview){let t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):t.skipInitialClear||(this.autoClear&&this._engine.clear(t.clearColor||this.clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,i=!0){var r,s,a;if(e&&e._skipRendering)return;let n=this._engine;if(this._activeCamera=e,!this.activeCamera)throw Error("Active camera not set");if(n.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&i){let t=!0;e._renderingMultiview&&e.outputRenderTarget&&(t=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=t)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(let e=0;e<this._softwareSkinnedMeshes.length;e++){let t=this._softwareSkinnedMeshes.data[e];t.applySkeleton(t.skeleton)}for(let i of(this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture),this._gatherActiveCameraRenderTargetsStage))i.action(this._renderTargets);let o=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){tools_Tools.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e<this._renderTargets.length;e++){let t=this._renderTargets.data[e];if(t._shouldRender()){this._renderId++;let e=t.activeCamera&&t.activeCamera!==this.activeCamera;t.render(e,this.dumpNextRenderTargets),o=!0}}tools_Tools.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(let e of this._cameraDrawRenderTargetStage)o=e.action(this.activeCamera)||o;this._intermediateRendering=!1}for(let t of(this._engine.currentRenderPassId=null!==(a=null!==(s=null===(r=e.outputRenderTarget)||void 0===r?void 0:r.renderPassId)&&void 0!==s?s:e.renderPassId)&&void 0!==a?a:0,o&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame(),this._beforeCameraDrawStage))t.action(this.activeCamera);for(let e of(this.onBeforeDrawPhaseObservable.notifyObservers(this),n.snapshotRendering&&1===n.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this),this._afterCameraDrawStage))e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){let t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(let e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t<e._rigCameras.length;t++)this._renderForCamera(e._rigCameras[t],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)}_checkIntersections(){for(let e=0;e<this._meshesForIntersections.length;e++){let t=this._meshesForIntersections.data[e];if(t.actionManager)for(let e=0;t.actionManager&&e<t.actionManager.actions.length;e++){let i=t.actionManager.actions[e];if(12===i.trigger||13===i.trigger){let e=i.getTriggerParameter(),r=e.mesh?e.mesh:e,s=r.intersectsMesh(t,e.usePreciseIntersection),a=t._intersectionsInProgress.indexOf(r);s&&-1===a?12===i.trigger?(i._executeCurrent(ActionEvent.CreateNew(t,void 0,r)),t._intersectionsInProgress.push(r)):13===i.trigger&&t._intersectionsInProgress.push(r):s||!(a>-1)||(13===i.trigger&&i._executeCurrent(ActionEvent.CreateNew(t,void 0,r)),t.actionManager.hasSpecificTrigger(13,e=>{let t=e.mesh?e.mesh:e;return r===t})&&13!==i.trigger||t._intersectionsInProgress.splice(a,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(scene_Scene.MinDeltaTime,Math.min(this._engine.getDeltaTime(),scene_Scene.MaxDeltaTime))+this._timeAccumulator,t=this._engine.getTimeStep(),i=1e3/t/1e3,r=0,s=this._engine.getLockstepMaxSteps(),a=Math.floor(e/t);for(a=Math.min(a,s);e>0&&r<a;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*i,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,r++,e-=t;this._timeAccumulator=e<0?0:e}else{let e=this.useConstantAnimationDeltaTime?16:Math.max(scene_Scene.MinDeltaTime,Math.min(this._engine.getDeltaTime(),scene_Scene.MaxDeltaTime));this._animationRatio=.06*e,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}}_clear(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)}_checkCameraRenderTarget(e){var t;if((null==e?void 0:e.outputRenderTarget)&&!(null==e?void 0:e.isRigCamera)&&(e.outputRenderTarget._cleared=!1),null===(t=null==e?void 0:e.rigCameras)||void 0===t?void 0:t.length)for(let t=0;t<e.rigCameras.length;++t){let i=e.rigCameras[t].outputRenderTarget;i&&(i._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(let t of this.meshes)t.resetDrawCache(e)}render(e=!0,t=!1){var i,r,s;if(this.isDisposed)return;for(let e of(this.onReadyObservable.hasObservers()&&null===this._executeWhenReadyTimeoutId&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),(null===(i=this.activeCameras)||void 0===i?void 0:i.length)&&this.activeCameras.forEach(this._checkCameraRenderTarget),this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(11),t||this.animate(),this._beforeCameraUpdateStage))e.action();if(e){if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++){let t=this.activeCameras[e];if(t.update(),0!==t.cameraRigMode)for(let e=0;e<t._rigCameras.length;e++)t._rigCameras[e].update()}else if(this.activeCamera&&(this.activeCamera.update(),0!==this.activeCamera.cameraRigMode))for(let e=0;e<this.activeCamera._rigCameras.length;e++)this.activeCamera._rigCameras[e].update()}this.onBeforeRenderObservable.notifyObservers(this);let a=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);let n=(null===(r=this.activeCameras)||void 0===r?void 0:r.length)?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){tools_Tools.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(let e=0;e<this.customRenderTargets.length;e++){let t=this.customRenderTargets[e];if(t._shouldRender()){if(this._renderId++,this.activeCamera=t.activeCamera||this.activeCamera,!this.activeCamera)throw Error("Active camera not set");a.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),t.render(n!==this.activeCamera,this.dumpNextRenderTargets)}}tools_Tools.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}for(let e of(this._engine.currentRenderPassId=null!==(s=null==n?void 0:n.renderPassId)&&void 0!==s?s:0,this.activeCamera=n,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this._beforeClearStage))e.action();for(let e of(this._clearFrameBuffer(this.activeCamera),this._gatherRenderTargetsStage))e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++)this._processSubCameras(this.activeCameras[e],e>0);else{if(!this.activeCamera)throw Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}for(let e of(this._checkIntersections(),this._afterRenderStage))e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e<this._toBeDisposed.length;e++){let t=this._toBeDisposed[e];t&&t.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this.importedMeshesFiles=[],this.stopAllAnimations&&(this._activeAnimatables.forEach(e=>{e.onAnimationEndObservable.clear(),e.onAnimationEnd=null}),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;let e=this._activeRequests.slice();for(let t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){console.error("An error occurred while calling onDisposeObservable!",e)}this.detachControl();let t=this._engine.getInputElement();if(t)for(let e=0;e<this.cameras.length;e++)this.cameras[e].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._disposeList(this.meshes,e=>e.dispose(!0)),this._disposeList(this.transformNodes,e=>e.dispose(!0));let i=this.cameras;this._disposeList(i),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let r=this._engine.scenes.indexOf(this);r>-1&&this._engine.scenes.splice(r,1),engineStore_EngineStore._LastCreatedScene===this&&(this._engine.scenes.length>0?engineStore_EngineStore._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:engineStore_EngineStore._LastCreatedScene=null),(r=this._engine._virtualScenes.indexOf(this))>-1&&this._engine._virtualScenes.splice(r,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){let i=e.slice(0);for(let e of(t=null!=t?t:e=>e.dispose(),i))t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e<this.meshes.length;e++){let t=this.meshes[e],i=t.geometry;i&&i.clearCachedData()}}cleanCachedTextureBuffer(){for(let e of this.textures){let t=e._buffer;t&&(e._buffer=null)}}getWorldExtends(e){let t=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new math_vector_Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||(()=>!0),this.meshes.filter(e).forEach(e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;let r=e.getBoundingInfo(),s=r.boundingBox.minimumWorld,a=r.boundingBox.maximumWorld;math_vector_Vector3.CheckExtends(s,t,i),math_vector_Vector3.CheckExtends(a,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,r,s=!1){throw _WarnImport("Ray")}createPickingRayToRef(e,t,i,r,s,a=!1,n=!1){throw _WarnImport("Ray")}createPickingRayInCameraSpace(e,t,i){throw _WarnImport("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,r){throw _WarnImport("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,r,s,a){let n=_WarnImport("Ray",!0);return n&&logger_Logger.Warn(n),new PickingInfo}pickWithBoundingInfo(e,t,i,r,s){let a=_WarnImport("Ray",!0);return a&&logger_Logger.Warn(a),new PickingInfo}pickWithRay(e,t,i,r){throw _WarnImport("Ray")}multiPick(e,t,i,r,s){throw _WarnImport("Ray")}multiPickWithRay(e,t,i){throw _WarnImport("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of(this.postProcessManager&&this.postProcessManager._rebuild(),this._components))e.rebuild();for(let e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(let e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(let e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;let r=[];for(let s in e){let a=e[s];Tags&&Tags.MatchesQuery(a,t)&&(!i||i(a))&&r.push(a)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(let i of this.materials)(!t||t(i))&&i.markAsDirty(e)}_loadFile(e,t,i,r,s,a,n){let o=LoadFile(e,t,i,r?this.offlineProvider:void 0,s,a,n);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}_loadFileAsync(e,t,i,r,s){return new Promise((a,n)=>{this._loadFile(e,e=>{a(e)},t,i,r,(e,t)=>{n(t)},s)})}_requestFile(e,t,i,r,s,a,n){let o=RequestFile(e,t,i,r?this.offlineProvider:void 0,s,a,n);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}_requestFileAsync(e,t,i,r,s){return new Promise((a,n)=>{this._requestFile(e,e=>{a(e)},t,i,r,e=>{n(e)},s)})}_readFile(e,t,i,r,s){let a=ReadFile(e,t,i,r,s);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}_readFileAsync(e,t,i){return new Promise((r,s)=>{this._readFile(e,e=>{r(e)},t,i,e=>{s(e)})})}getPerfCollector(){throw _WarnImport("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}};scene_Scene.FOGMODE_NONE=0,scene_Scene.FOGMODE_EXP=1,scene_Scene.FOGMODE_EXP2=2,scene_Scene.FOGMODE_LINEAR=3,scene_Scene.MinDeltaTime=1,scene_Scene.MaxDeltaTime=1e3,function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(en||(en={}));let math_axis_Axis=class math_axis_Axis{};math_axis_Axis.X=new math_vector_Vector3(1,0,0),math_axis_Axis.Y=new math_vector_Vector3(0,1,0),math_axis_Axis.Z=new math_vector_Vector3(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(eo||(eo={}));let Bone=class Bone extends node_Node{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,r=null,s=null,a=null,n=null){var o;super(e,t.getScene()),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=null!==(o=null==r?void 0:r.clone())&&void 0!==o?o:math_vector_Matrix.Identity(),this._restMatrix=null!=s?s:this._localMatrix.clone(),this._bindMatrix=null!=a?a:this._localMatrix.clone(),this._index=n,this._absoluteMatrix=new math_vector_Matrix,this._absoluteBindMatrix=new math_vector_Matrix,this._absoluteInverseBindMatrix=new math_vector_Matrix,this._finalMatrix=new math_vector_Matrix,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){let 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){let t=math_vector_TmpVectors.Vector3[0],i=math_vector_TmpVectors.Quaternion[0],r=math_vector_TmpVectors.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:math_vector_Quaternion.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=math_vector_Vector3.Zero(),this._localRotation=math_vector_Quaternion.Zero(),this._localPosition=math_vector_Vector3.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,math_vector_Matrix.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e<this.children.length;e++)this.children[e]._updateAbsoluteBindMatrices();this._scalingDeterminant=0>this._absoluteBindMatrix.determinant()?-1:1}markAsDirty(){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this}_markAsDirtyAndCompose(){this.markAsDirty(),this._needToCompose=!0}_markAsDirtyAndDecompose(){this.markAsDirty(),this._needToDecompose=!0}_updatePosition(e,t=en.LOCAL,i,r=!0){let s=this.getLocalMatrix();if(t==en.LOCAL)r?(s.addAtIndex(12,e.x),s.addAtIndex(13,e.y),s.addAtIndex(14,e.z)):s.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let a=Bone._TmpMats[0],n=Bone._TmpVecs[0];this.parent?i&&t?(a.copyFrom(this.parent.getAbsoluteMatrix()),a.multiplyToRef(t,a)):a.copyFrom(this.parent.getAbsoluteMatrix()):math_vector_Matrix.IdentityToRef(a),r&&a.setTranslationFromFloats(0,0,0),a.invert(),math_vector_Vector3.TransformCoordinatesToRef(e,a,n),r?(s.addAtIndex(12,n.x),s.addAtIndex(13,n.y),s.addAtIndex(14,n.z)):s.setTranslationFromFloats(n.x,n.y,n.z)}this._markAsDirtyAndDecompose()}translate(e,t=en.LOCAL,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=en.LOCAL,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,en.WORLD,t)}scale(e,t,i,r=!1){let s=this.getLocalMatrix(),a=Bone._TmpMats[0];for(let r of(math_vector_Matrix.ScalingToRef(e,t,i,a),a.multiplyToRef(s,s),a.invert(),this.children)){let s=r.getLocalMatrix();s.multiplyToRef(a,s),s.multiplyAtIndex(12,e),s.multiplyAtIndex(13,t),s.multiplyAtIndex(14,i),r._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),r)for(let s of this.children)s.scale(e,t,i,r)}setScale(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()}getScale(){return this._decompose(),this._localScaling}getScaleToRef(e){this._decompose(),e.copyFrom(this._localScaling)}setYawPitchRoll(e,t,i,r=en.LOCAL,s){if(r===en.LOCAL){let a=Bone._TmpQuat;math_vector_Quaternion.RotationYawPitchRollToRef(e,t,i,a),this.setRotationQuaternion(a,r,s);return}let a=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(a,s))return;let n=Bone._TmpMats[1];math_vector_Matrix.RotationYawPitchRollToRef(e,t,i,n),a.multiplyToRef(n,n),this._rotateWithMatrix(n,r,s)}rotate(e,t,i=en.LOCAL,r){let s=Bone._TmpMats[0];s.setTranslationFromFloats(0,0,0),math_vector_Matrix.RotationAxisToRef(e,t,s),this._rotateWithMatrix(s,i,r)}setAxisAngle(e,t,i=en.LOCAL,r){if(i===en.LOCAL){let s=Bone._TmpQuat;math_vector_Quaternion.RotationAxisToRef(e,t,s),this.setRotationQuaternion(s,i,r);return}let s=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,r))return;let a=Bone._TmpMats[1];math_vector_Matrix.RotationAxisToRef(e,t,a),s.multiplyToRef(a,a),this._rotateWithMatrix(a,i,r)}setRotation(e,t=en.LOCAL,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=en.LOCAL,i){if(t===en.LOCAL){this._decompose(),this._localRotation.copyFrom(e),this._markAsDirtyAndCompose();return}let r=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=Bone._TmpMats[1];math_vector_Matrix.FromQuaternionToRef(e,s),r.multiplyToRef(s,s),this._rotateWithMatrix(s,t,i)}setRotationMatrix(e,t=en.LOCAL,i){if(t===en.LOCAL){let r=Bone._TmpQuat;math_vector_Quaternion.FromRotationMatrixToRef(e,r),this.setRotationQuaternion(r,t,i);return}let r=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=Bone._TmpMats[1];s.copyFrom(e),r.multiplyToRef(e,s),this._rotateWithMatrix(s,t,i)}_rotateWithMatrix(e,t=en.LOCAL,i){let r=this.getLocalMatrix(),s=r.m[12],a=r.m[13],n=r.m[14],o=this.getParent(),l=Bone._TmpMats[3],h=Bone._TmpMats[4];o&&t==en.WORLD?(i?(l.copyFrom(i.getWorldMatrix()),o.getAbsoluteMatrix().multiplyToRef(l,l)):l.copyFrom(o.getAbsoluteMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):t==en.WORLD&&i?(l.copyFrom(i.getWorldMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):r.multiplyToRef(e,r),r.setTranslationFromFloats(s,a,n),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){let i=Bone._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),math_vector_Matrix.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):math_vector_Matrix.IdentityToRef(i),e.invert(),!isNaN(e.m[0])&&(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=en.LOCAL,t=null){let i=math_vector_Vector3.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=en.LOCAL,t,i){if(e==en.LOCAL){let e=this.getLocalMatrix();i.x=e.m[12],i.y=e.m[13],i.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let r=Bone._TmpMats[0];t&&e?(r.copyFrom(this.getAbsoluteMatrix()),r.multiplyToRef(e,r)):r=this.getAbsoluteMatrix(),i.x=r.m[12],i.y=r.m[13],i.z=r.m[14]}}getAbsolutePosition(e=null){let t=math_vector_Vector3.Zero();return this.getPositionToRef(en.WORLD,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(en.WORLD,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);let e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}let e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].computeAbsoluteMatrices()}computeAbsoluteTransforms(){this.computeAbsoluteMatrices()}getDirection(e,t=null){let i=math_vector_Vector3.Zero();return this.getDirectionToRef(e,t,i),i}getDirectionToRef(e,t=null,i){let r=null;t&&(r=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let s=Bone._TmpMats[0];s.copyFrom(this.getAbsoluteMatrix()),t&&r&&s.multiplyToRef(r,s),math_vector_Vector3.TransformNormalToRef(e,s,i),i.normalize()}getRotation(e=en.LOCAL,t=null){let i=math_vector_Vector3.Zero();return this.getRotationToRef(e,t,i),i}getRotationToRef(e=en.LOCAL,t=null,i){let r=Bone._TmpQuat;this.getRotationQuaternionToRef(e,t,r),r.toEulerAnglesToRef(i)}getRotationQuaternion(e=en.LOCAL,t=null){let i=math_vector_Quaternion.Identity();return this.getRotationQuaternionToRef(e,t,i),i}getRotationQuaternionToRef(e=en.LOCAL,t=null,i){if(e==en.LOCAL)this._decompose(),i.copyFrom(this._localRotation);else{let e=Bone._TmpMats[0],r=this.getAbsoluteMatrix();t?r.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(r),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.decompose(void 0,i,void 0)}}getRotationMatrix(e=en.LOCAL,t){let i=math_vector_Matrix.Identity();return this.getRotationMatrixToRef(e,t,i),i}getRotationMatrixToRef(e=en.LOCAL,t,i){if(e==en.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(i);else{let e=Bone._TmpMats[0],r=this.getAbsoluteMatrix();t?r.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(r),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.getRotationMatrixToRef(i)}}getAbsolutePositionFromLocal(e,t=null){let i=math_vector_Vector3.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,i),i}getAbsolutePositionFromLocalToRef(e,t=null,i){let r=null;t&&(r=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let s=Bone._TmpMats[0];s.copyFrom(this.getAbsoluteMatrix()),t&&r&&s.multiplyToRef(r,s),math_vector_Vector3.TransformCoordinatesToRef(e,s,i)}getLocalPositionFromAbsolute(e,t=null){let i=math_vector_Vector3.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,i),i}getLocalPositionFromAbsoluteToRef(e,t=null,i){let r=null;t&&(r=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let s=Bone._TmpMats[0];s.copyFrom(this.getAbsoluteMatrix()),t&&r&&s.multiplyToRef(r,s),s.invert(),math_vector_Vector3.TransformCoordinatesToRef(e,s,i)}setCurrentPoseAsRest(){this.setRestMatrix(this.getLocalMatrix())}};Bone._TmpVecs=arrayTools_ArrayTools.BuildArray(2,math_vector_Vector3.Zero),Bone._TmpQuat=math_vector_Quaternion.Identity(),Bone._TmpMats=arrayTools_ArrayTools.BuildArray(5,math_vector_Matrix.Identity);let Animatable=class Animatable{get syncRoot(){return this._syncRoot}get masterFrame(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){if(-1===e){this._weight=-1;return}this._weight=Math.min(Math.max(e,0),1)}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t<this._runtimeAnimations.length;t++){let i=this._runtimeAnimations[t];i._prepareForSpeedRatioChange(e)}this._speedRatio=e,null!==this._goToFrame&&this.goToFrame(this._goToFrame)}get elapsedTime(){return null===this._localDelayOffset?0:this._scene._animationTime-this._localDelayOffset}constructor(e,t,i=0,r=100,s=!1,a=1,n,o,l,h=!1,c=0){this.target=t,this.fromFrame=i,this.toFrame=r,this.loopAnimation=s,this.onAnimationEnd=n,this.onAnimationLoop=l,this.isAdditive=h,this.playOrder=c,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=[],this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this._frameToSyncFromJump=null,this._goToFrame=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new observable_Observable,this.onAnimationLoopObservable=new observable_Observable,this._scene=e,o&&this.appendAnimations(t,o),this._speedRatio=a,e._activeAnimatables.push(this)}syncWith(e){if(this._syncRoot=e,e){let e=this._scene._activeAnimatables.indexOf(this);e>-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i<t.length;i++){let r=t[i],s=new RuntimeAnimation(e,r,this._scene,this);s._onLoop=()=>{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i].animation;return null}getRuntimeAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i];return null}reset(){let e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null}enableBlending(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)t[i].animation.enableBlending=!0,t[i].animation.blendingSpeed=e}disableBlending(){let e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].animation.enableBlending=!1}goToFrame(e){var t;let i=this._runtimeAnimations;if(i[0]){let r=i[0].animation.framePerSecond;this._frameToSyncFromJump=null!==(t=this._frameToSyncFromJump)&&void 0!==t?t:i[0].currentFrame;let s=0===this.speedRatio?0:(e-this._frameToSyncFromJump)/r*1e3/this.speedRatio;this._manualJumpDelay=-s}for(let t=0;t<i.length;t++)i[t].goToFrame(e);this._goToFrame=e}get paused(){return this._paused}pause(){this._paused||(this._paused=!0)}restart(){this._paused=!1}_raiseOnAnimationEnd(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)}stop(e,t,i=!1){if(e||t){let r=this._scene._activeAnimatables.indexOf(this);if(r>-1){let s=this._runtimeAnimations;for(let i=s.length-1;i>=0;i--){let r=s[i];(!e||r.animation.name==e)&&(!t||t(r.target))&&(r.dispose(),s.splice(i,1))}0==s.length&&(i||this._scene._activeAnimatables.splice(r,1),this._raiseOnAnimationEnd())}}else{let e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);let t=this._runtimeAnimations;for(let e=0;e<t.length;e++)t[e].dispose();this._runtimeAnimations.length=0,this._raiseOnAnimationEnd()}}}waitAsync(){return new Promise(e=>{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){let t;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 i=!1,r=this._runtimeAnimations;for(t=0;t<r.length;t++){let s=r[t],a=s.animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);i=i||a}if(this.animationStarted=i,!i){if(this.disposeOnEnd)for(t=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(t,1),t=0;t<r.length;t++)r[t].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return i}};scene_Scene.prototype._animate=function(){if(!this.animationsEnabled)return;let e=precisionDate_PrecisionDate.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;let t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;let i=this._animationTime;for(let e=0;e<t.length;e++){let r=t[e];!r._animate(i)&&r.disposeOnEnd&&e--}this._processLateAnimationBindings()},scene_Scene.prototype.sortActiveAnimatables=function(){this._activeAnimatables.sort((e,t)=>e.playOrder-t.playOrder)},scene_Scene.prototype.beginWeightedAnimation=function(e,t,i,r=1,s,a=1,n,o,l,h,c=!1){let u=this.beginAnimation(e,t,i,s,a,n,o,!1,l,h,c);return u.weight=r,u},scene_Scene.prototype.beginAnimation=function(e,t,i,r,s=1,a,n,o=!0,l,h,c=!1){t>i&&s>0&&(s*=-1),o&&this.stopAnimation(e,void 0,l),n||(n=new Animatable(this,e,t,i,r,s,a,void 0,h,c));let u=!l||l(e);if(e.animations&&u&&n.appendAnimations(e,e.animations),e.getAnimatables){let c=e.getAnimatables();for(let e=0;e<c.length;e++)this.beginAnimation(c[e],t,i,r,s,a,n,o,l,h)}return n.reset(),n},scene_Scene.prototype.beginHierarchyAnimation=function(e,t,i,r,s,a=1,n,o,l=!0,h,c,u=!1){let d=e.getDescendants(t),_=[];for(let t of(_.push(this.beginAnimation(e,i,r,s,a,n,o,l,h,void 0,u)),d))_.push(this.beginAnimation(t,i,r,s,a,n,o,l,h,void 0,u));return _},scene_Scene.prototype.beginDirectAnimation=function(e,t,i,r,s,a,n,o,l=!1){if(void 0===a&&(a=1),i>r&&a>0)a*=-1;else if(r>i&&a<0){let e=r;r=i,i=e}let h=new Animatable(this,e,i,r,s,a,n,t,o,l);return h},scene_Scene.prototype.beginDirectHierarchyAnimation=function(e,t,i,r,s,a,n,o,l,h=!1){let c=e.getDescendants(t),u=[];for(let t of(u.push(this.beginDirectAnimation(e,i,r,s,a,n,o,l,h)),c))u.push(this.beginDirectAnimation(t,i,r,s,a,n,o,l,h));return u},scene_Scene.prototype.getAnimatableByTarget=function(e){for(let t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},scene_Scene.prototype.getAllAnimatablesByTarget=function(e){let t=[];for(let i=0;i<this._activeAnimatables.length;i++)this._activeAnimatables[i].target===e&&t.push(this._activeAnimatables[i]);return t},scene_Scene.prototype.stopAnimation=function(e,t,i){let r=this.getAllAnimatablesByTarget(e);for(let e of r)e.stop(t,i)},scene_Scene.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(let e=0;e<this._activeAnimatables.length;e++)this._activeAnimatables[e].stop(void 0,void 0,!0);this._activeAnimatables.length=0}for(let e of this.animationGroups)e.stop()},scene_Scene.prototype._registerTargetForLateAnimationBinding=function(e,t){let i=e.target;this._registeredForLateAnimationBindings.pushNoDuplicate(i),i._lateAnimationHolders||(i._lateAnimationHolders={}),i._lateAnimationHolders[e.targetPath]||(i._lateAnimationHolders[e.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:t}),e.isAdditive?(i._lateAnimationHolders[e.targetPath].additiveAnimations.push(e),i._lateAnimationHolders[e.targetPath].totalAdditiveWeight+=e.weight):(i._lateAnimationHolders[e.targetPath].animations.push(e),i._lateAnimationHolders[e.targetPath].totalWeight+=e.weight)},scene_Scene.prototype._processLateAnimationBindingsForMatrices=function(e){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return e.originalValue;let t=1,i=math_vector_TmpVectors.Vector3[0],r=math_vector_TmpVectors.Vector3[1],s=math_vector_TmpVectors.Quaternion[0],a=0,n=e.animations[0],o=e.originalValue,l=1,h=!1;if(e.totalWeight<1)l=1-e.totalWeight,o.decompose(r,s,i);else{if(a=1,t=e.totalWeight,1==(l=n.weight/t)){if(!e.totalAdditiveWeight)return n.currentValue;h=!0}n.currentValue.decompose(r,s,i)}if(!h){r.scaleInPlace(l),i.scaleInPlace(l),s.scaleInPlace(l);for(let n=a;n<e.animations.length;n++){let a=e.animations[n];if(0===a.weight)continue;l=a.weight/t;let o=math_vector_TmpVectors.Vector3[2],h=math_vector_TmpVectors.Vector3[3],c=math_vector_TmpVectors.Quaternion[1];a.currentValue.decompose(h,c,o),h.scaleAndAddToRef(l,r),c.scaleAndAddToRef(math_vector_Quaternion.Dot(s,c)>0?l:-l,s),o.scaleAndAddToRef(l,i)}s.normalize()}for(let t=0;t<e.additiveAnimations.length;t++){let a=e.additiveAnimations[t];if(0===a.weight)continue;let n=math_vector_TmpVectors.Vector3[2],o=math_vector_TmpVectors.Vector3[3],l=math_vector_TmpVectors.Quaternion[1];a.currentValue.decompose(o,l,n),o.multiplyToRef(r,o),math_vector_Vector3.LerpToRef(r,o,a.weight,r),s.multiplyToRef(l,l),math_vector_Quaternion.SlerpToRef(s,l,a.weight,s),n.scaleAndAddToRef(a.weight,i)}let c=n?n._animationState.workValue:math_vector_TmpVectors.Matrix[0].clone();return math_vector_Matrix.ComposeToRef(r,s,i,c),c},scene_Scene.prototype._processLateAnimationBindingsForQuaternions=function(e,t){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return t;let i=e.animations[0],r=e.originalValue,s=t;if(0===e.totalWeight&&e.totalAdditiveWeight>0)s.copyFrom(r);else if(1===e.animations.length){if(math_vector_Quaternion.SlerpToRef(r,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,a,n=1;if(e.totalWeight<1){let t=1-e.totalWeight;a=[],(i=[]).push(r),a.push(t)}else{if(2===e.animations.length&&(math_vector_Quaternion.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],a=[],n=e.totalWeight}for(let t=0;t<e.animations.length;t++){let r=e.animations[t];i.push(r.currentValue),a.push(r.weight/n)}let o=0;for(let e=0;e<i.length;){if(!e){math_vector_Quaternion.SlerpToRef(i[e],i[e+1],a[e+1]/(a[e]+a[e+1]),t),s=t,o=a[e]+a[e+1],e+=2;continue}o+=a[e],math_vector_Quaternion.SlerpToRef(s,i[e],a[e]/o,s),e++}}for(let t=0;t<e.additiveAnimations.length;t++){let i=e.additiveAnimations[t];0!==i.weight&&(s.multiplyToRef(i.currentValue,math_vector_TmpVectors.Quaternion[0]),math_vector_Quaternion.SlerpToRef(s,math_vector_TmpVectors.Quaternion[0],i.weight,s))}return s},scene_Scene.prototype._processLateAnimationBindings=function(){if(this._registeredForLateAnimationBindings.length){for(let e=0;e<this._registeredForLateAnimationBindings.length;e++){let t=this._registeredForLateAnimationBindings.data[e];for(let e in t._lateAnimationHolders){let i=t._lateAnimationHolders[e],r=i.animations[0],s=i.originalValue;if(null==s)continue;let a=animation_Animation.AllowMatrixDecomposeForInterpolation&&s.m,n=t[e];if(a)n=this._processLateAnimationBindingsForMatrices(i);else{let e=void 0!==s.w;if(e)n=this._processLateAnimationBindingsForQuaternions(i,n||math_vector_Quaternion.Identity());else{let e=0,t=1;if(i.totalWeight<1)n=r&&s.scale?s.scale(1-i.totalWeight):r?s*(1-i.totalWeight):s.clone?s.clone():s;else if(r){t=i.totalWeight;let s=r.weight/t;n=1!==s?r.currentValue.scale?r.currentValue.scale(s):r.currentValue*s:r.currentValue,e=1}for(let r=e;r<i.animations.length;r++){let e=i.animations[r],s=e.weight/t;s&&(e.currentValue.scaleAndAddToRef?e.currentValue.scaleAndAddToRef(s,n):n+=e.currentValue*s)}for(let e=0;e<i.additiveAnimations.length;e++){let t=i.additiveAnimations[e],r=t.weight;r&&(t.currentValue.scaleAndAddToRef?t.currentValue.scaleAndAddToRef(r,n):n+=t.currentValue*r)}}}t[e]=n}t._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}},Bone.prototype.copyAnimationRange=function(e,t,i,r=!1,s=null){let a,n,o;0===this.animations.length&&(this.animations.push(new animation_Animation(this.name,"_matrix",e.animations[0].framePerSecond,animation_Animation.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));let l=e.animations[0].getRange(t);if(!l)return!1;let h=l.from,c=l.to,u=e.animations[0].getKeys(),d=e.length,_=e.getParent(),p=this.getParent(),f=r&&_&&d&&this.length&&d!==this.length,m=f&&p&&_?p.length/_.length:1,g=r&&!p&&s&&(1!==s.x||1!==s.y||1!==s.z),v=this.animations[0].getKeys();for(let e=0,t=u.length;e<t;e++)(a=u[e]).frame>=h&&a.frame<=c&&(r?(o=a.value.clone(),f?(n=o.getTranslation(),o.setTranslation(n.scaleInPlace(m))):g&&s?(n=o.getTranslation(),o.setTranslation(n.multiplyInPlace(s))):o=a.value):o=a.value,v.push({frame:a.frame+i,value:o}));return this.animations[0].createRange(t,h+i,c+i),!0},function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(el||(el={}));let Angle=class Angle{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){let i=t.subtract(e),r=Math.atan2(i.y,i.x);return new Angle(r)}static FromRadians(e){return new Angle(e)}static FromDegrees(e){return new Angle(e*Math.PI/180)}};let Arc2=class Arc2{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;let r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,a=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,n=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new math_vector_Vector2((s*(t.y-i.y)-a*(e.y-t.y))/n,((e.x-t.x)*a-(t.x-i.x)*s)/n),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Angle.BetweenTwoPoints(this.centerPoint,this.startPoint);let o=this.startAngle.degrees(),l=Angle.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=Angle.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-o>180&&(l-=360),l-o<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-o<0?el.CW:el.CCW,this.angle=Angle.FromDegrees(this.orientation===el.CW?o-h:h-o)}};let math_path_Path2=class math_path_Path2{constructor(e,t){this._points=[],this._length=0,this.closed=!1,this._points.push(new math_vector_Vector2(e,t))}addLineTo(e,t){if(this.closed)return this;let i=new math_vector_Vector2(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;let a=this._points[this._points.length-1],n=new math_vector_Vector2(e,t),o=new math_vector_Vector2(i,r),l=new Arc2(a,n,o),h=l.angle.radians()/s;l.orientation===el.CW&&(h*=-1);let c=l.startAngle.radians()+h;for(let e=0;e<s;e++){let e=Math.cos(c)*l.radius+l.centerPoint.x,t=Math.sin(c)*l.radius+l.centerPoint.y;this.addLineTo(e,t),c+=h}return this}addQuadraticCurveTo(e,t,i,r,s=36){if(this.closed)return this;let equation=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r,a=this._points[this._points.length-1];for(let n=0;n<=s;n++){let o=n/s,l=equation(o,a.x,e,i),h=equation(o,a.y,t,r);this.addLineTo(l,h)}return this}addBezierCurveTo(e,t,i,r,s,a,n=36){if(this.closed)return this;let equation=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s,o=this._points[this._points.length-1];for(let l=0;l<=n;l++){let h=l/n,c=equation(h,o.x,e,i,s),u=equation(h,o.y,t,r,a);this.addLineTo(c,u)}return this}isPointInside(e){let t=!1,i=this._points.length;for(let r=i-1,s=0;s<i;r=s++){let i=this._points[r],a=this._points[s],n=a.x-i.x,o=a.y-i.y;if(Math.abs(o)>Number.EPSILON){if(o<0&&(i=this._points[s],n=-n,a=this._points[r],o=-o),e.y<i.y||e.y>a.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{let r=o*(e.x-i.x)-n*(e.y-i.y);if(0===r)return!0;if(r<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(a.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=a.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){let t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){let e=this._points.length,t=0;for(let i=e-1,r=0;r<e;i=r++)t+=this._points[i].x*this._points[r].y-this._points[r].x*this._points[i].y;return .5*t}getPoints(){return this._points}getPointAtLengthPosition(e){if(e<0||e>1)return math_vector_Vector2.Zero();let t=e*this.length(),i=0;for(let e=0;e<this._points.length;e++){let r=(e+1)%this._points.length,s=this._points[e],a=this._points[r],n=a.subtract(s),o=n.length()+i;if(t>=i&&t<=o){let e=n.normalize(),r=t-i;return new math_vector_Vector2(s.x+e.x*r,s.y+e.y*r)}i=o}return math_vector_Vector2.Zero()}static StartingAt(e,t){return new math_path_Path2(e,t)}};let Path3D=class Path3D{constructor(e,t=null,i,r=!1){this.path=e,this._curve=[],this._distances=[],this._tangents=[],this._normals=[],this._binormals=[],this._pointAtData={id:0,point:math_vector_Vector3.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:math_vector_Matrix.Identity()};for(let t=0;t<e.length;t++)this._curve[t]=e[t].clone();this._raw=i||!1,this._alignTangentsWithPath=r,this._compute(t,r)}getCurve(){return this._curve}getPoints(){return this._curve}length(){return this._distances[this._distances.length-1]}getTangents(){return this._tangents}getNormals(){return this._normals}getBinormals(){return this._binormals}getDistances(){return this._distances}getPointAt(e){return this._updatePointAtData(e).point}getTangentAt(e,t=!1){return this._updatePointAtData(e,t),t?math_vector_Vector3.TransformCoordinates(math_vector_Vector3.Forward(),this._pointAtData.interpolationMatrix):this._tangents[this._pointAtData.previousPointArrayIndex]}getNormalAt(e,t=!1){return this._updatePointAtData(e,t),t?math_vector_Vector3.TransformCoordinates(math_vector_Vector3.Right(),this._pointAtData.interpolationMatrix):this._normals[this._pointAtData.previousPointArrayIndex]}getBinormalAt(e,t=!1){return this._updatePointAtData(e,t),t?math_vector_Vector3.TransformCoordinates(math_vector_Vector3.UpReadOnly,this._pointAtData.interpolationMatrix):this._binormals[this._pointAtData.previousPointArrayIndex]}getDistanceAt(e){return this.length()*e}getPreviousPointIndexAt(e){return this._updatePointAtData(e),this._pointAtData.previousPointArrayIndex}getSubPositionAt(e){return this._updatePointAtData(e),this._pointAtData.subPosition}getClosestPositionTo(e){let t=Number.MAX_VALUE,i=0;for(let r=0;r<this._curve.length-1;r++){let s=this._curve[r+0],a=this._curve[r+1].subtract(s).normalize(),n=this._distances[r+1]-this._distances[r+0],o=Math.min(Math.max(math_vector_Vector3.Dot(a,e.subtract(s).normalize()),0)*math_vector_Vector3.Distance(s,e)/n,1),l=math_vector_Vector3.Distance(s.add(a.scale(o*n)),e);l<t&&(t=l,i=(this._distances[r+0]+n*o)/this.length())}return i}slice(e=0,t=1){if(e<0&&(e=1- -1*e%1),t<0&&(t=1- -1*t%1),e>t){let i=e;e=t,t=i}let i=this.getCurve(),r=this.getPointAt(e),s=this.getPreviousPointIndexAt(e),a=this.getPointAt(t),n=this.getPreviousPointIndexAt(t)+1,o=[];return 0!==e&&(s++,o.push(r)),o.push(...i.slice(s,n)),(1!==t||1===e)&&o.push(a),new Path3D(o,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;t<e.length;t++)this._curve[t].x=e[t].x,this._curve[t].y=e[t].y,this._curve[t].z=e[t].z;return this._compute(t,i),this}_compute(e,t=!1){let i,r,s,a,n;let o=this._curve.length;if(o<2)return;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[o-1]=this._curve[o-1].subtract(this._curve[o-2]),this._raw||this._tangents[o-1].normalize();let l=this._tangents[0],h=this._normalVector(l,e);this._normals[0]=h,this._raw||this._normals[0].normalize(),this._binormals[0]=math_vector_Vector3.Cross(l,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(let e=1;e<o;e++)i=this._getLastNonNullVector(e),e<o-1&&(r=this._getFirstNonNullVector(e),this._tangents[e]=t?r:i.add(r),this._tangents[e].normalize()),this._distances[e]=this._distances[e-1]+this._curve[e].subtract(this._curve[e-1]).length(),s=this._tangents[e],n=this._binormals[e-1],this._normals[e]=math_vector_Vector3.Cross(n,s),this._raw||(0===this._normals[e].length()?(a=this._normals[e-1],this._normals[e]=a.clone()):this._normals[e].normalize()),this._binormals[e]=math_vector_Vector3.Cross(s,this._normals[e]),this._raw||this._binormals[e].normalize();this._pointAtData.id=NaN}_getFirstNonNullVector(e){let t=1,i=this._curve[e+t].subtract(this._curve[e]);for(;0===i.length()&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i}_getLastNonNullVector(e){let t=1,i=this._curve[e].subtract(this._curve[e-t]);for(;0===i.length()&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i;let r=e.length();if(0===r&&(r=1),null==t){let t;t=math_scalar_Scalar.WithinEpsilon(Math.abs(e.y)/r,1,.001)?math_scalar_Scalar.WithinEpsilon(Math.abs(e.x)/r,1,.001)?math_scalar_Scalar.WithinEpsilon(Math.abs(e.z)/r,1,.001)?math_vector_Vector3.Zero():new math_vector_Vector3(0,0,1):new math_vector_Vector3(1,0,0):new math_vector_Vector3(0,-1,0),i=math_vector_Vector3.Cross(e,t)}else i=math_vector_Vector3.Cross(e,t),math_vector_Vector3.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){let i;if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;let r=this.getPoints();if(e<=0)return this._setPointAtData(0,0,r[0],0,t);if(e>=1)return this._setPointAtData(1,1,r[r.length-1],r.length-1,t);let s=r[0],a=0,n=e*this.length();for(let o=1;o<r.length;o++){i=r[o];let l=math_vector_Vector3.Distance(s,i);if((a+=l)===n)return this._setPointAtData(e,1,i,o,t);if(a>n){let r=a-n,h=r/l,c=s.subtract(i),u=i.add(c.scaleInPlace(h));return this._setPointAtData(e,1-h,u,o-1,t)}s=i}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=math_vector_Matrix.Identity();let e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){let t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),a=this._tangents[t].clone(),n=this._normals[t].clone(),o=this._binormals[t].clone(),l=math_vector_Quaternion.RotationQuaternionFromAxis(r,s,i),h=math_vector_Quaternion.RotationQuaternionFromAxis(n,o,a),c=math_vector_Quaternion.Slerp(l,h,this._pointAtData.subPosition);c.toRotationMatrix(this._pointAtData.interpolationMatrix)}}};let Curve3=class Curve3{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;let s=[],equation=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;for(let a=0;a<=r;a++)s.push(new math_vector_Vector3(equation(a/r,e.x,t.x,i.x),equation(a/r,e.y,t.y,i.y),equation(a/r,e.z,t.z,i.z)));return new Curve3(s)}static CreateCubicBezier(e,t,i,r,s){s=s>3?s:4;let a=[],equation=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s;for(let n=0;n<=s;n++)a.push(new math_vector_Vector3(equation(n/s,e.x,t.x,i.x,r.x),equation(n/s,e.y,t.y,i.y,r.y),equation(n/s,e.z,t.z,i.z,r.z)));return new Curve3(a)}static CreateHermiteSpline(e,t,i,r,s){let a=[],n=1/s;for(let o=0;o<=s;o++)a.push(math_vector_Vector3.Hermite(e,t,i,r,o*n));return new Curve3(a)}static CreateCatmullRomSpline(e,t,i){let r=[],s=1/t,a=0;if(i){let i=e.length;for(let n=0;n<i;n++){a=0;for(let o=0;o<t;o++)r.push(math_vector_Vector3.CatmullRom(e[n%i],e[(n+1)%i],e[(n+2)%i],e[(n+3)%i],a)),a+=s}r.push(r[0])}else{let i=[];i.push(e[0].clone()),Array.prototype.push.apply(i,e),i.push(e[e.length-1].clone());let n=0;for(;n<i.length-3;n++){a=0;for(let e=0;e<t;e++)r.push(math_vector_Vector3.CatmullRom(i[n],i[n+1],i[n+2],i[n+3],a)),a+=s}n--,r.push(math_vector_Vector3.CatmullRom(i[n],i[n+1],i[n+2],i[n+3],a))}return new Curve3(r)}static ArcThru3Points(e,t,i,r=32,s=!1,a=!1){let n=[],o=t.subtract(e),l=i.subtract(t),h=e.subtract(i),c=math_vector_Vector3.Cross(o,l),u=c.length();if(u<1e-8)return new Curve3(n);let d=o.lengthSquared(),_=l.lengthSquared(),p=h.lengthSquared(),f=c.lengthSquared(),m=o.length(),g=l.length(),v=h.length(),x=.5*m*g*v/u,b=math_vector_Vector3.Dot(o,h),T=math_vector_Vector3.Dot(o,l),S=math_vector_Vector3.Dot(l,h),C=e.scale(-.5*_*b/f).add(t.scale(-.5*p*T/f)).add(i.scale(-.5*d*S/f)),E=e.subtract(C),y=E.normalize(),R=math_vector_Vector3.Cross(c,y).normalize();if(a){let t=2*Math.PI/r;for(let e=0;e<=2*Math.PI;e+=t)n.push(C.add(y.scale(x*Math.cos(e)).add(R.scale(x*Math.sin(e)))));n.push(e)}else{let t=1/r,a=0,o=math_vector_Vector3.Zero();do o=C.add(y.scale(x*Math.cos(a)).add(R.scale(x*Math.sin(a)))),n.push(o),a+=t;while(!o.equalsWithEpsilon(i,x*t*1.1));n.push(i),s&&n.push(e)}return new Curve3(n)}constructor(e){this._length=0,this._points=e,this._length=this._computeLength(e)}getPoints(){return this._points}length(){return this._length}continue(e){let t=this._points[this._points.length-1],i=this._points.slice(),r=e.getPoints();for(let e=1;e<r.length;e++)i.push(r[e].subtract(r[0]).add(t));let s=new Curve3(i);return s}_computeLength(e){let t=0;for(let i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t}};let EasingFunction=class EasingFunction{constructor(){this._easingMode=EasingFunction.EASINGMODE_EASEIN}setEasingMode(e){this._easingMode=Math.min(Math.max(e,0),2)}getEasingMode(){return this._easingMode}easeInCore(e){throw Error("You must implement this method")}ease(e){switch(this._easingMode){case EasingFunction.EASINGMODE_EASEIN:return this.easeInCore(e);case EasingFunction.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?(1-this.easeInCore((1-e)*2))*.5+.5:.5*this.easeInCore(2*e)}};EasingFunction.EASINGMODE_EASEIN=0,EasingFunction.EASINGMODE_EASEOUT=1,EasingFunction.EASINGMODE_EASEINOUT=2;let CircleEase=class CircleEase extends EasingFunction{easeInCore(e){return 1-Math.sqrt(1-(e=Math.max(0,Math.min(1,e)))*e)}};let BackEase=class BackEase extends EasingFunction{constructor(e=1){super(),this.amplitude=e}easeInCore(e){let t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}};let ExponentialEase=class ExponentialEase extends EasingFunction{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)}};let QuadraticEase=class QuadraticEase extends EasingFunction{easeInCore(e){return e*e}};let SineEase=class SineEase extends EasingFunction{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}};let TargetedAnimation=class TargetedAnimation{getClassName(){return"TargetedAnimation"}serialize(){let e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}};let AnimationGroup=class AnimationGroup{syncWithMask(){if(!this.mask){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let e=0;e<this._animatables.length;++e){let t=this._animatables[e];this.mask.retainsTarget(t.target.name)?(this._numActiveAnimatables++,t.paused&&t.restart()):t.paused||t.pause()}}removeUnmaskedAnimations(){if(this.mask){for(let e=0;e<this._animatables.length;++e){let t=this._animatables[e];!this.mask.retainsTarget(t.target.name)&&(t.stop(),this._animatables.splice(e,1),--e)}for(let e=0;e<this._targetedAnimations.length;e++){let t=this._targetedAnimations[e];!this.mask.retainsTarget(t.target.name)&&(this._targetedAnimations.splice(e,1),--e)}}}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;e<this._animatables.length;e++){let t=this._animatables[e];t.speedRatio=this._speedRatio}}}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.loopAnimation=this._loopAnimation}}}get isAdditive(){return this._isAdditive}set isAdditive(e){if(this._isAdditive!==e){this._isAdditive=e;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.isAdditive=this._isAdditive}}}get weight(){return this._weight}set weight(e){this._weight!==e&&(this._weight=e,this.setWeightForAllAnimatables(this._weight))}get targetedAnimations(){return this._targetedAnimations}get animatables(){return this._animatables}get children(){return this._targetedAnimations}get playOrder(){return this._playOrder}set playOrder(e){if(this._playOrder!==e&&(this._playOrder=e,this._animatables.length>0)){for(let e=0;e<this._animatables.length;e++)this._animatables[e].playOrder=this._playOrder;this._scene.sortActiveAnimatables()}}get enableBlending(){return this._enableBlending}set enableBlending(e){if(this._enableBlending!==e&&(this._enableBlending=e,null!==e))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=e}get blendingSpeed(){return this._blendingSpeed}set blendingSpeed(e){if(this._blendingSpeed!==e&&(this._blendingSpeed=e,null!==e))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.blendingSpeed=e}getLength(e,t){e=null!=e?e:this._from,t=null!=t?t:this._to;let i=this.targetedAnimations[0].animation.framePerSecond*this._speedRatio;return(t-e)/i}static MergeAnimationGroups(e,t=!0,i=!1,r){if(0===e.length)return null;r=null!=r?r:e[0].weight;let s=Number.MAX_VALUE,a=-Number.MAX_VALUE;if(i)for(let t of e)t.from<s&&(s=t.from),t.to>a&&(a=t.to);let n=new AnimationGroup(e[0].name+"_merged",e[0]._scene,r);for(let r of e){for(let e of(i&&r.normalize(s,a),r.targetedAnimations))n.addTargetedAnimation(e.animation,e.target);t&&r.dispose()}return n}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=[],this._animatables=[],this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new observable_Observable,this.onAnimationLoopObservable=new observable_Observable,this.onAnimationGroupLoopObservable=new observable_Observable,this.onAnimationGroupEndObservable=new observable_Observable,this.onAnimationGroupPauseObservable=new observable_Observable,this.onAnimationGroupPlayObservable=new observable_Observable,this.metadata=null,this._animationLoopFlags=[],this._scene=t||engineStore_EngineStore.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){let i=new TargetedAnimation;i.animation=e,i.target=t;let r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to<r[r.length-1].frame&&(this._to=r[r.length-1].frame),null!==this._enableBlending&&(e.enableBlending=this._enableBlending),null!==this._blendingSpeed&&(e.blendingSpeed=this._blendingSpeed),this._targetedAnimations.push(i),i}removeTargetedAnimation(e){for(let t=this._targetedAnimations.length-1;t>-1;t--){let i=this._targetedAnimations[t];i.animation===e&&this._targetedAnimations.splice(t,1)}}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;i<this._targetedAnimations.length;i++){let r=this._targetedAnimations[i],s=r.animation.getKeys(),a=s[0],n=s[s.length-1];if(a.frame>e){let t={frame:e,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};s.splice(0,0,t)}if(n.frame<t){let e={frame:t,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};s.push(e)}}return this._from=e,this._to=t,this}_processLoop(e,t,i){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount!==this._numActiveAnimatables||(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let a=0;a<this._targetedAnimations.length;a++){let n=this._targetedAnimations[a],o=this._scene.beginDirectAnimation(n.target,[n.animation],void 0!==i?i:this._from,void 0!==r?r:this._to,e,t,void 0,void 0,void 0!==s?s:this._isAdditive);o.weight=this._weight,o.playOrder=this._playOrder,o.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(n),this._checkAnimationGroupEnded(o)},this._processLoop(o,n,a),this._animatables.push(o)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.pause()}return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length===this._targetedAnimations.length?(void 0!==e&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this._isPaused=!1,this}reset(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(),this;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.reset()}return this}restart(){if(!this._isStarted)return this;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.restart()}return this.onAnimationGroupPlayObservable.notifyObservers(this),this}stop(){if(!this._isStarted)return this;let e=this._animatables.slice();for(let t=0;t<e.length;t++)e[t].stop(void 0,void 0,!0);let t=0;for(let e=0;e<this._scene._activeAnimatables.length;e++){let i=this._scene._activeAnimatables[e];i._runtimeAnimations.length>0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.weight=e}return this}syncAllAnimationsWith(e){for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.syncWith(e)}return this}goToFrame(e){if(!this._isStarted)return this;for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.goToFrame(e)}return this}dispose(){this._targetedAnimations.length=0,this._animatables.length=0;let e=this._scene.animationGroups.indexOf(this);if(e>-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){let 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){let 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){let r=new AnimationGroup(e||this.name,this._scene,this._weight,this._playOrder);for(let e of(r._from=this.from,r._to=this.to,r._speedRatio=this.speedRatio,r._loopAnimation=this.loopAnimation,r._isAdditive=this.isAdditive,r._enableBlending=this.enableBlending,r._blendingSpeed=this.blendingSpeed,r.metadata=this.metadata,r.mask=this.mask,this._targetedAnimations))r.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return r}serialize(){let e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){let i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return Tags&&Tags.HasTags(this)&&(e.tags=Tags.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t){let i=new AnimationGroup(e.name,t,e.weight,e.playOrder);for(let r=0;r<e.targetedAnimations.length;r++){let s=e.targetedAnimations[r],a=animation_Animation.Parse(s.animation),n=s.targetId;if("influence"===s.animation.property){let e=t.getMorphTargetById(n);e&&i.addTargetedAnimation(a,e)}else{let e=t.getNodeById(n);null!=e&&i.addTargetedAnimation(a,e)}}return Tags&&Tags.AddTagsTo(i,e.tags),null!==e.from&&null!==e.to&&i.normalize(e.from,e.to),void 0!==e.speedRatio&&(i._speedRatio=e.speedRatio),void 0!==e.loopAnimation&&(i._loopAnimation=e.loopAnimation),void 0!==e.isAdditive&&(i._isAdditive=e.isAdditive),void 0!==e.weight&&(i._weight=e.weight),void 0!==e.playOrder&&(i._playOrder=e.playOrder),void 0!==e.enableBlending&&(i._enableBlending=e.enableBlending),void 0!==e.blendingSpeed&&(i._blendingSpeed=e.blendingSpeed),void 0!==e.metadata&&(i.metadata=e.metadata),i}static MakeAnimationAdditive(e,t,i,r=!1,s){let a;let n=e;(a="object"==typeof t?t:{referenceFrame:t,range:i,cloneOriginalAnimationGroup:r,clonedAnimationName:s}).cloneOriginalAnimationGroup&&(n=e.clone(a.clonedAnimationGroupName||n.name));let o=n.targetedAnimations;for(let e=0;e<o.length;e++){let t=o[e];t.animation=animation_Animation.MakeAnimationAdditive(t.animation,a)}if(n.isAdditive=!0,a.clipKeys){let e=Number.MAX_VALUE,t=-Number.MAX_VALUE,i=n.targetedAnimations;for(let r=0;r<i.length;r++){let s=i[r],a=s.animation,n=a.getKeys();e>n[0].frame&&(e=n[0].frame),t<n[n.length-1].frame&&(t=n[n.length-1].frame)}n._from=e,n._to=t}return n}static ClipKeys(e,t,i,r,s){let a=e.clone(r||e.name);return AnimationGroup.ClipKeysInPlace(a,t,i,s)}static ClipKeysInPlace(e,t,i,r){return AnimationGroup.ClipInPlace(e,t,i,r,!1)}static ClipFrames(e,t,i,r,s){let a=e.clone(r||e.name);return AnimationGroup.ClipFramesInPlace(a,t,i,s)}static ClipFramesInPlace(e,t,i,r){return AnimationGroup.ClipInPlace(e,t,i,r,!0)}static ClipInPlace(e,t,i,r,s=!1){let a=Number.MAX_VALUE,n=-Number.MAX_VALUE,o=e.targetedAnimations;for(let e=0;e<o.length;e++){let l=o[e],h=r?l.animation:l.animation.clone();s&&(h.createKeyForFrame(t),h.createKeyForFrame(i));let c=h.getKeys(),u=[],d=Number.MAX_VALUE;for(let e=0;e<c.length;e++){let r=c[e];if(!s&&e>=t&&e<=i||s&&r.frame>=t&&r.frame<=i){let e={frame:r.frame,value:r.value.clone?r.value.clone():r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation,lockedTangent:r.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}if(0===u.length){o.splice(e,1),e--;continue}a>u[0].frame&&(a=u[0].frame),n<u[u.length-1].frame&&(n=u[u.length-1].frame),h.setKeys(u,!0),l.animation=h}return e._from=a,e._to=n,e}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from+", to: "+this._to+", isStarted: "+this._isStarted+", speedRatio: "+this._speedRatio+", targetedAnimations length: "+this._targetedAnimations.length+", animatables length: "+this._animatables),t}};function inlineScheduler(e,t,i){try{let r=e.next();r.done?t(r):r.value?r.value.then(()=>{r.value=void 0,t(r)},i):t(r)}catch(e){i(e)}}function createYieldingScheduler(e=25){let t;return(i,r,s)=>{let a=performance.now();void 0===t||a-t>e?(t=a,setTimeout(()=>{inlineScheduler(i,r,s)},0)):inlineScheduler(i,r,s)}}function runCoroutine(e,t,i,r,s){let resume=()=>{let a;let onStep=e=>{e.done?i(e.value):void 0===a?a=!0:resume()};do a=void 0,s&&s.aborted?r(Error("Aborted")):t(e,onStep,r),void 0===a&&(a=!1);while(a)};resume()}function runCoroutineSync(e,t){let i;return runCoroutine(e,inlineScheduler,e=>i=e,e=>{throw e},t),i}function runCoroutineAsync(e,t,i){return new Promise((r,s)=>{runCoroutine(e,t,r,s,i)})}function makeSyncFunction(e,t){return(...i)=>runCoroutineSync(e(...i),t)}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(eh||(eh={}));let math_viewport_Viewport=class math_viewport_Viewport{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new math_viewport_Viewport(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 math_viewport_Viewport(this.x,this.y,this.width,this.height)}};let camera_Camera=class camera_Camera extends node_Node{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,r;let s=0,a=0;if(this.mode===camera_Camera.PERSPECTIVE_CAMERA)this.fovMode===camera_Camera.FOVMODE_VERTICAL_FIXED?(a=2*this.minZ*Math.tan(this.fov/2),s=this.getEngine().getAspectRatio(this)*a):a=(s=2*this.minZ*Math.tan(this.fov/2))/this.getEngine().getAspectRatio(this);else{let n=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;s=(null!==(e=this.orthoRight)&&void 0!==e?e:n)-(null!==(t=this.orthoLeft)&&void 0!==t?t:-n),a=(null!==(i=this.orthoTop)&&void 0!==i?i:o)-(null!==(r=this.orthoBottom)&&void 0!==r?r:-o)}return s*a}set orthoLeft(e){for(let t of(this._orthoLeft=e,this._rigCameras))t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){for(let t of(this._orthoRight=e,this._rigCameras))t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){for(let t of(this._orthoBottom=e,this._rigCameras))t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){for(let t of(this._orthoTop=e,this._rigCameras))t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){for(let t of(this._mode=e,this._rigCameras))t.mode=e}get mode(){return this._mode}constructor(e,t,i,r=!0){super(e,i),this._position=math_vector_Vector3.Zero(),this._upVector=math_vector_Vector3.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=camera_Camera.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new math_viewport_Viewport(0,0,1,1),this.layerMask=268435455,this.fovMode=camera_Camera.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=camera_Camera.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new observable_Observable,this.onProjectionMatrixChangedObservable=new observable_Observable,this.onAfterCheckInputsObservable=new observable_Observable,this.onRestoreStateObservable=new observable_Observable,this.isRigCamera=!1,this._rigCameras=[],this._skipRendering=!1,this._projectionMatrix=new math_vector_Matrix,this._postProcesses=[],this._activeMeshes=new SmartArray(256),this._globalPosition=math_vector_Vector3.Zero(),this._computedViewMatrix=math_vector_Matrix.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=math_vector_Matrix.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=math_vector_Quaternion.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}applyVerticalCorrection(){let e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return -1!==this._activeMeshes.indexOf(e)}isReady(e=!1){if(e){for(let e of this._postProcesses)if(e&&!e.isReady())return!1}return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.obliqueAngle=void 0,this._cache.obliqueLength=void 0,this._cache.obliqueOffset=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return!!super._isSynchronized()&&this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent()}_isSynchronizedProjectionMatrix(){let e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;let t=this.getEngine();return this.mode===camera_Camera.PERSPECTIVE_CAMERA?e=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:(e=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight(),this.oblique&&(e=e&&this._cache.obliqueAngle===this.oblique.angle&&this._cache.obliqueLength===this.oblique.length&&this._cache.obliqueOffset===this.oblique.offset)),e}attachControl(e,t){}detachControl(e){}update(){this._checkInputs(),this.cameraRigMode!==camera_Camera.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(null!==this._postProcesses[e])return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){let e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let e=0,t=this._rigCameras.length;e<t;e++){let t=this._rigCameras[e],i=t._rigPostProcess;if(i){let e="pass"===i.getEffectName();e&&(t.isIntermediate=0===this._postProcesses.length),t._postProcesses=this._postProcesses.slice(0).concat(i),i.markTextureDirty()}else t._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(logger_Logger.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){let 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 math_vector_Matrix.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,r,s,a,n,o,l,h,c,u,d,_,p,f,m,g,v,x;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;let b=this.getEngine(),T=this.getScene(),S=b.useReverseDepthBuffer;if(this.mode===camera_Camera.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=b.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),(T.useRightHandedSystem?math_vector_Matrix.PerspectiveFovRHToRef:math_vector_Matrix.PerspectiveFovLHToRef)(this.fov,b.getAspectRatio(this),S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===camera_Camera.FOVMODE_VERTICAL_FIXED,b.isNDCHalfZRange,this.projectionPlaneTilt,S);else{let e=b.getRenderWidth()/2,C=b.getRenderHeight()/2;T.useRightHandedSystem?this.oblique?math_vector_Matrix.ObliqueOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(r=this.orthoBottom)&&void 0!==r?r:-C,null!==(s=this.orthoTop)&&void 0!==s?s:C,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,b.isNDCHalfZRange):math_vector_Matrix.OrthoOffCenterRHToRef(null!==(a=this.orthoLeft)&&void 0!==a?a:-e,null!==(n=this.orthoRight)&&void 0!==n?n:e,null!==(o=this.orthoBottom)&&void 0!==o?o:-C,null!==(l=this.orthoTop)&&void 0!==l?l:C,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this._projectionMatrix,b.isNDCHalfZRange):this.oblique?math_vector_Matrix.ObliqueOffCenterLHToRef(null!==(h=this.orthoLeft)&&void 0!==h?h:-e,null!==(c=this.orthoRight)&&void 0!==c?c:e,null!==(u=this.orthoBottom)&&void 0!==u?u:-C,null!==(d=this.orthoTop)&&void 0!==d?d:C,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,b.isNDCHalfZRange):math_vector_Matrix.OrthoOffCenterLHToRef(null!==(_=this.orthoLeft)&&void 0!==_?_:-e,null!==(p=this.orthoRight)&&void 0!==p?p:e,null!==(f=this.orthoBottom)&&void 0!==f?f:-C,null!==(m=this.orthoTop)&&void 0!==m?m:C,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this._projectionMatrix,b.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=null===(g=this.oblique)||void 0===g?void 0:g.angle,this._cache.obliqueLength=null===(v=this.oblique)||void 0===v?void 0:v.length,this._cache.obliqueOffset=null===(x=this.oblique)||void 0===x?void 0:x.offset,this._cache.renderWidth=b.getRenderWidth(),this._cache.renderHeight=b.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){return(this.radius||(this.target?math_vector_Vector3.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Frustum.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),!t||!(this.rigCameras.length>0))return e.isInFrustum(this._frustumPlanes);{let t=!1;return this.rigCameras.forEach(i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)}),t}}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw _WarnImport("Ray")}getForwardRayToRef(e,t=100,i,r){throw _WarnImport("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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){let 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!==camera_Camera.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){let 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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=tools_Tools.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==camera_Camera.RIG_MODE_NONE){let e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);let 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 math_vector_Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=tools_Tools.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){let e=decorators_SerializationHelper.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),decorators_SerializationHelper.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){let i=decorators_SerializationHelper.Clone(camera_Camera.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=e,i.parent=t,this.onClonedObservable.notifyObservers(i),i}getDirection(e){let t=math_vector_Vector3.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){math_vector_Vector3.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,r=0,s=!0){let a=node_Node.Construct(e,t,i,{interaxial_distance:r,isStereoscopicSideBySide:s});return a||(()=>camera_Camera._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){let i=e.type,r=camera_Camera.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=decorators_SerializationHelper.Parse(r,e,t);if(void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=math_vector_Vector3.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(math_vector_Vector3.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(math_vector_Vector3.FromArray(e.target)),e.cameraRigMode){let t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t<e.animations.length;t++){let i=e.animations[t],r=h["BABYLON.Animation"];r&&s.animations.push(r.Parse(i))}node_Node.ParseAnimationRanges(s,e,t)}return e.autoAnimate&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&s.setEnabled(e.isEnabled),s}_calculateHandednessMultiplier(){let e=this.getScene().useRightHandedSystem?-1:1;return this.parent&&0>this.parent._getWorldMatrixDeterminant()&&(e*=-1),e}};camera_Camera._CreateDefaultParsedCamera=(e,t)=>{throw _WarnImport("UniversalCamera")},camera_Camera.PERSPECTIVE_CAMERA=0,camera_Camera.ORTHOGRAPHIC_CAMERA=1,camera_Camera.FOVMODE_VERTICAL_FIXED=0,camera_Camera.FOVMODE_HORIZONTAL_FIXED=1,camera_Camera.RIG_MODE_NONE=0,camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED=14,camera_Camera.RIG_MODE_VR=20,camera_Camera.RIG_MODE_CUSTOM=22,camera_Camera.ForceAttachControlToAlwaysPreventDefault=!1,__decorate([serializeAsVector3("position")],camera_Camera.prototype,"_position",void 0),__decorate([serializeAsVector3("upVector")],camera_Camera.prototype,"_upVector",void 0),__decorate([serialize()],camera_Camera.prototype,"orthoLeft",null),__decorate([serialize()],camera_Camera.prototype,"orthoRight",null),__decorate([serialize()],camera_Camera.prototype,"orthoBottom",null),__decorate([serialize()],camera_Camera.prototype,"orthoTop",null),__decorate([serialize()],camera_Camera.prototype,"fov",void 0),__decorate([serialize()],camera_Camera.prototype,"projectionPlaneTilt",void 0),__decorate([serialize()],camera_Camera.prototype,"minZ",void 0),__decorate([serialize()],camera_Camera.prototype,"maxZ",void 0),__decorate([serialize()],camera_Camera.prototype,"inertia",void 0),__decorate([serialize()],camera_Camera.prototype,"mode",null),__decorate([serialize()],camera_Camera.prototype,"layerMask",void 0),__decorate([serialize()],camera_Camera.prototype,"fovMode",void 0),__decorate([serialize()],camera_Camera.prototype,"cameraRigMode",void 0),__decorate([serialize()],camera_Camera.prototype,"interaxialDistance",void 0),__decorate([serialize()],camera_Camera.prototype,"isStereoscopicSideBySide",void 0);let IntersectionInfo=class IntersectionInfo{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}};let boundingBox_BoundingBox=class boundingBox_BoundingBox{constructor(e,t,i){this.vectors=arrayTools_ArrayTools.BuildArray(8,math_vector_Vector3.Zero),this.center=math_vector_Vector3.Zero(),this.centerWorld=math_vector_Vector3.Zero(),this.extendSize=math_vector_Vector3.Zero(),this.extendSizeWorld=math_vector_Vector3.Zero(),this.directions=arrayTools_ArrayTools.BuildArray(3,math_vector_Vector3.Zero),this.vectorsWorld=arrayTools_ArrayTools.BuildArray(8,math_vector_Vector3.Zero),this.minimumWorld=math_vector_Vector3.Zero(),this.maximumWorld=math_vector_Vector3.Zero(),this.minimum=math_vector_Vector3.Zero(),this.maximum=math_vector_Vector3.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){let r=e.x,s=e.y,a=e.z,n=t.x,o=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(r,s,a),this.maximum.copyFromFloats(n,o,l),h[0].copyFromFloats(r,s,a),h[1].copyFromFloats(n,o,l),h[2].copyFromFloats(n,s,a),h[3].copyFromFloats(r,o,a),h[4].copyFromFloats(r,s,l),h[5].copyFromFloats(n,o,a),h[6].copyFromFloats(r,o,l),h[7].copyFromFloats(n,s,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||math_vector_Matrix.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){let t=boundingBox_BoundingBox._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);let s=r*e,a=i.scaleInPlace(.5*s),n=this.center.subtractToRef(a,t[1]),o=this.center.addToRef(a,t[2]);return this.reConstruct(n,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){let t=this.minimumWorld,i=this.maximumWorld,r=this.directions,s=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)s[e].copyFrom(a[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let r=0;r<8;++r){let n=s[r];math_vector_Vector3.TransformCoordinatesToRef(a[r],e,n),t.minimizeInPlace(n),i.maximizeInPlace(n)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}math_vector_Vector3.FromArrayToRef(e.m,0,r[0]),math_vector_Vector3.FromArrayToRef(e.m,4,r[1]),math_vector_Vector3.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return boundingBox_BoundingBox.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return boundingBox_BoundingBox.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){let t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,a=t.z,n=i.x,o=i.y,l=i.z,h=e.x,c=e.y,u=e.z;return!(n-h<-.001)&&!(-.001>h-r)&&!(o-c<-.001)&&!(-.001>c-s)&&!(l-u<-.001)&&!(-.001>u-a)}intersectsSphere(e){return boundingBox_BoundingBox.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){let i=this.minimumWorld,r=this.maximumWorld,s=i.x,a=i.y,n=i.z,o=r.x,l=r.y,h=r.z,c=e.x,u=e.y,d=e.z,_=t.x,p=t.y,f=t.z;return!(o<c)&&!(s>_)&&!(l<u)&&!(a>p)&&!(h<d)&&!(n>f)}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,r){let s=boundingBox_BoundingBox._TmpVector3[0];math_vector_Vector3.ClampToRef(i,e,t,s);let a=math_vector_Vector3.DistanceSquared(i,s);return a<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){let r=t[i];for(let t=0;t<8;++t)if(0>r.dotCoordinate(e[t]))return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0,s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){r=!1;break}if(r)return!1}return!0}};boundingBox_BoundingBox._TmpVector3=arrayTools_ArrayTools.BuildArray(3,math_vector_Vector3.Zero);let boundingSphere_BoundingSphere=class boundingSphere_BoundingSphere{constructor(e,t,i){this.center=math_vector_Vector3.Zero(),this.centerWorld=math_vector_Vector3.Zero(),this.minimum=math_vector_Vector3.Zero(),this.maximum=math_vector_Vector3.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);let r=math_vector_Vector3.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*r,this._update(i||math_vector_Matrix.IdentityReadOnly)}scale(e){let t=this.radius*e,i=boundingSphere_BoundingSphere._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),a=this.center.addToRef(r,i[2]);return this.reConstruct(s,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{math_vector_Vector3.TransformCoordinatesToRef(this.center,e,this.centerWorld);let t=boundingSphere_BoundingSphere._TmpVector3[0];math_vector_Vector3.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){let t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){let t=this.centerWorld;for(let i=0;i<6;i++)if(0>e[i].dotCoordinate(t))return!1;return!0}intersectsPoint(e){let t=math_vector_Vector3.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){let i=math_vector_Vector3.DistanceSquared(e.centerWorld,t.centerWorld),r=e.radiusWorld+t.radiusWorld;return!(r*r<i)}static CreateFromCenterAndRadius(e,t,i){this._TmpVector3[0].copyFrom(e),this._TmpVector3[1].copyFromFloats(0,0,t),this._TmpVector3[2].copyFrom(e),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);let r=new boundingSphere_BoundingSphere(this._TmpVector3[0],this._TmpVector3[2]);return i?r._worldMatrix=i:r._worldMatrix=math_vector_Matrix.Identity(),r}};boundingSphere_BoundingSphere._TmpVector3=arrayTools_ArrayTools.BuildArray(3,math_vector_Vector3.Zero);let O={min:0,max:0},B={min:0,max:0},computeBoxExtents=(e,t,i)=>{let r=math_vector_Vector3.Dot(t.centerWorld,e),s=Math.abs(math_vector_Vector3.Dot(t.directions[0],e))*t.extendSize.x,a=Math.abs(math_vector_Vector3.Dot(t.directions[1],e))*t.extendSize.y,n=Math.abs(math_vector_Vector3.Dot(t.directions[2],e))*t.extendSize.z,o=s+a+n;i.min=r-o,i.max=r+o},axisOverlap=(e,t,i)=>(computeBoxExtents(e,t,O),computeBoxExtents(e,i,B),!(O.min>B.max||B.min>O.max));let boundingInfo_BoundingInfo=class boundingInfo_BoundingInfo{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new boundingBox_BoundingBox(e,t,i),this.boundingSphere=new boundingSphere_BoundingSphere(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){let i=boundingInfo_BoundingInfo._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=boundingInfo_BoundingInfo._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){let t=math_vector_Vector3.Minimize(this.minimum,e),i=math_vector_Vector3.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){let t=math_vector_TmpVectors.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);let i=math_vector_TmpVectors.Vector3[0];return math_vector_Vector3.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),math_vector_Vector3.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!!((2===t||3===t)&&this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(1===t||3===t||this.boundingBox.isInFrustum(e))}get diagonalLength(){let e=this.boundingBox,t=e.maximumWorld.subtractToRef(e.minimumWorld,boundingInfo_BoundingInfo._TmpVector3[0]);return t.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(!boundingSphere_BoundingSphere.Intersects(this.boundingSphere,e.boundingSphere)||!boundingBox_BoundingBox.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;let i=this.boundingBox,r=e.boundingBox;return!!(axisOverlap(i.directions[0],i,r)&&axisOverlap(i.directions[1],i,r)&&axisOverlap(i.directions[2],i,r)&&axisOverlap(r.directions[0],i,r)&&axisOverlap(r.directions[1],i,r)&&axisOverlap(r.directions[2],i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[0],r.directions[0]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[0],r.directions[1]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[0],r.directions[2]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[1],r.directions[0]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[1],r.directions[1]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[1],r.directions[2]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[2],r.directions[0]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[2],r.directions[1]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[2],r.directions[2]),i,r))}};boundingInfo_BoundingInfo._TmpVector3=arrayTools_ArrayTools.BuildArray(2,math_vector_Vector3.Zero);let MathHelpers=class MathHelpers{static extractMinAndMaxIndexed(e,t,i,r,s,a){for(let n=i;n<i+r;n++){let i=3*t[n],r=e[i],o=e[i+1],l=e[i+2];s.minimizeInPlaceFromFloats(r,o,l),a.maximizeInPlaceFromFloats(r,o,l)}}static extractMinAndMax(e,t,i,r,s,a){for(let n=t,o=t*r;n<t+i;n++,o+=r){let t=e[o],i=e[o+1],r=e[o+2];s.minimizeInPlaceFromFloats(t,i,r),a.maximizeInPlaceFromFloats(t,i,r)}}};function extractMinAndMaxIndexed(e,t,i,r,s=null){let a=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new math_vector_Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return MathHelpers.extractMinAndMaxIndexed(e,t,i,r,a,n),s&&(a.x-=a.x*s.x+s.y,a.y-=a.y*s.x+s.y,a.z-=a.z*s.x+s.y,n.x+=n.x*s.x+s.y,n.y+=n.y*s.x+s.y,n.z+=n.z*s.x+s.y),{minimum:a,maximum:n}}function extractMinAndMax(e,t,i,r=null,s){let a=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),n=new math_vector_Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return s||(s=3),MathHelpers.extractMinAndMax(e,t,i,s,a,n),r&&(a.x-=a.x*r.x+r.y,a.y-=a.y*r.x+r.y,a.z-=a.z*r.x+r.y,n.x+=n.x*r.x+r.y,n.y+=n.y*r.x+r.y,n.z+=n.z*r.x+r.y),{minimum:a,maximum:n}}__decorate([nativeOverride.filter((...[e,t])=>!Array.isArray(e)&&!Array.isArray(t))],MathHelpers,"extractMinAndMaxIndexed",null),__decorate([nativeOverride.filter((...[e])=>!Array.isArray(e))],MathHelpers,"extractMinAndMax",null);let subMesh_SubMesh=class subMesh_SubMesh{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;let i=null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0);i.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 drawWrapper_DrawWrapper(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,r=!0){let s=this._drawWrapper;s.setEffect(e,t,r),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e){this._removeDrawWrapper(e);return}for(let e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,a,n,o=!0){return new subMesh_SubMesh(e,t,i,r,s,a,n,o)}constructor(e,t,i,r,s,a,n,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=a,this._renderingMesh=n||a,l&&a.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=a.subMeshes.length-1,o&&(this.refreshBoundingInfo(),a.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){let e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var t;let 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)){let 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){let t;if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(buffer_VertexBuffer.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;let i=this._renderingMesh.getIndices();if(0===this.indexStart&&this.indexCount===i.length){let e=this._renderingMesh.getBoundingInfo();t={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else t=extractMinAndMaxIndexed(e,i,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(t.minimum,t.maximum):this._boundingInfo=new boundingInfo_BoundingInfo(t.minimum,t.maximum),this}_checkCollision(e){let t=this.getBoundingInfo();return t._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){let t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){let 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){let i=[];for(let t=this.indexStart;t<this.indexStart+this.indexCount;t+=3)i.push(e[t],e[t+1],e[t+1],e[t+2],e[t+2],e[t]);this._linesIndexBuffer=t.createIndexBuffer(i),this._linesIndexCount=i.length}return this._linesIndexBuffer}canIntersects(e){let t=this.getBoundingInfo();return!!t&&e.intersectsBox(t.boundingBox)}intersects(e,t,i,r,s){let a=this.getMaterial();if(!a)return null;let n=3,o=!1;switch(a.fillMode){case 3:case 5:case 6:case 8:return null;case 7:n=1,o=!0}return 4===a.fillMode?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,r):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,r):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,r,s):this._intersectTriangles(e,t,i,n,o,r,s)}_intersectLines(e,t,i,r,s){let a=null;for(let n=this.indexStart;n<this.indexStart+this.indexCount;n+=2){let o=t[i[n]],l=t[i[n+1]],h=e.intersectionSegment(o,l,r);if(!(h<0)&&(s||!a||h<a.distance)&&((a=new IntersectionInfo(null,null,h)).faceId=n/2,s))break}return a}_intersectUnIndexedLines(e,t,i,r,s){let a=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=2){let n=t[i],o=t[i+1],l=e.intersectionSegment(n,o,r);if(!(l<0)&&(s||!a||l<a.distance)&&((a=new IntersectionInfo(null,null,l)).faceId=i/2,s))break}return a}_intersectTriangles(e,t,i,r,s,a,n){let o=null,l=-1;for(let h=this.indexStart;h<this.indexStart+this.indexCount-(3-r);h+=r){l++;let r=i[h],c=i[h+1],u=i[h+2];if(s&&4294967295===u){h+=2;continue}let d=t[r],_=t[c],p=t[u];if(!d||!_||!p||n&&!n(d,_,p,e,r,c,u))continue;let f=e.intersectsTriangle(d,_,p);if(f){if(f.distance<0)continue;if((a||!o||f.distance<o.distance)&&((o=f).faceId=l,a))break}}return o}_intersectUnIndexedTriangles(e,t,i,r,s){let a=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=3){let n=t[i],o=t[i+1],l=t[i+2];if(s&&!s(n,o,l,e,-1,-1,-1))continue;let h=e.intersectsTriangle(n,o,l);if(h){if(h.distance<0)continue;if((r||!a||h.distance<a.distance)&&((a=h).faceId=i/3,r))break}}return a}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){let i=new subMesh_SubMesh(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){let e=this.getBoundingInfo();if(!e)return i;i._boundingInfo=new boundingInfo_BoundingInfo(e.minimum,e.maximum)}return i}dispose(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);let e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1),this.resetDrawCache()}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,i,r,s,a=!0){let n=Number.MAX_VALUE,o=-Number.MAX_VALUE,l=s||r,h=l.getIndices();for(let e=t;e<t+i;e++){let t=h[e];t<n&&(n=t),t>o&&(o=t)}return new subMesh_SubMesh(e,n,o-n+1,t,i,r,s,a)}};let VertexDataMaterialInfo=class VertexDataMaterialInfo{};let mesh_vertexData_VertexData=class mesh_vertexData_VertexData{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=makeSyncFunction(this._applyToCoroutine.bind(this)),this.uniqueId=mesh_vertexData_VertexData._UniqueIDGenerator,mesh_vertexData_VertexData._UniqueIDGenerator++}set(e,t){switch(e.length||logger_Logger.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case buffer_VertexBuffer.PositionKind:this.positions=e;break;case buffer_VertexBuffer.NormalKind:this.normals=e;break;case buffer_VertexBuffer.TangentKind:this.tangents=e;break;case buffer_VertexBuffer.UVKind:this.uvs=e;break;case buffer_VertexBuffer.UV2Kind:this.uvs2=e;break;case buffer_VertexBuffer.UV3Kind:this.uvs3=e;break;case buffer_VertexBuffer.UV4Kind:this.uvs4=e;break;case buffer_VertexBuffer.UV5Kind:this.uvs5=e;break;case buffer_VertexBuffer.UV6Kind:this.uvs6=e;break;case buffer_VertexBuffer.ColorKind:this.colors=e;break;case buffer_VertexBuffer.MatricesIndicesKind:this.matricesIndices=e;break;case buffer_VertexBuffer.MatricesWeightsKind:this.matricesWeights=e;break;case buffer_VertexBuffer.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case buffer_VertexBuffer.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(buffer_VertexBuffer.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(buffer_VertexBuffer.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(buffer_VertexBuffer.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(buffer_VertexBuffer.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(buffer_VertexBuffer.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(buffer_VertexBuffer.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(buffer_VertexBuffer.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(buffer_VertexBuffer.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(buffer_VertexBuffer.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(buffer_VertexBuffer.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1)for(let t of(e.subMeshes=[],this.materialInfos))new subMesh_SubMesh(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,e);return this}_update(e,t,i){return this.positions&&e.updateVerticesData(buffer_VertexBuffer.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(buffer_VertexBuffer.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(buffer_VertexBuffer.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(buffer_VertexBuffer.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(buffer_VertexBuffer.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(buffer_VertexBuffer.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(buffer_VertexBuffer.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(buffer_VertexBuffer.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(buffer_VertexBuffer.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(buffer_VertexBuffer.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(buffer_VertexBuffer.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(buffer_VertexBuffer.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){let s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[1];for(let n=i;n<i+r;n+=3)math_vector_Vector3.FromArrayToRef(e,n,s),math_vector_Vector3.TransformCoordinatesToRef(s,t,a),e[n]=a.x,e[n+1]=a.y,e[n+2]=a.z}static _TransformVector3Normals(e,t,i=0,r=e.length){let s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[1];for(let n=i;n<i+r;n+=3)math_vector_Vector3.FromArrayToRef(e,n,s),math_vector_Vector3.TransformNormalToRef(s,t,a),e[n]=a.x,e[n+1]=a.y,e[n+2]=a.z}static _TransformVector4Normals(e,t,i=0,r=e.length){let s=math_vector_TmpVectors.Vector4[0],a=math_vector_TmpVectors.Vector4[1];for(let n=i;n<i+r;n+=4)math_vector_Vector4.FromArrayToRef(e,n,s),math_vector_Vector4.TransformNormalToRef(s,t,a),e[n]=a.x,e[n+1]=a.y,e[n+2]=a.z,e[n+3]=a.w}static _FlipFaces(e,t=0,i=e.length){for(let r=t;r<t+i;r+=3){let t=e[r+1];e[r+1]=e[r+2],e[r+2]=t}}transform(e){let t=0>e.determinant();return this.positions&&mesh_vertexData_VertexData._TransformVector3Coordinates(this.positions,e),this.normals&&mesh_vertexData_VertexData._TransformVector3Normals(this.normals,e),this.tangents&&mesh_vertexData_VertexData._TransformVector4Normals(this.tangents,e),t&&this.indices&&mesh_vertexData_VertexData._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];let e=[];for(let t of this.materialInfos){let i=new mesh_vertexData_VertexData;if(this.positions&&(i.positions=this.positions.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.normals&&(i.normals=this.normals.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.tangents&&(i.tangents=this.tangents.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.colors&&(i.colors=this.colors.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.uvs&&(i.uvs=this.uvs.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs2&&(i.uvs2=this.uvs2.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs3&&(i.uvs3=this.uvs3.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs4&&(i.uvs4=this.uvs4.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs5&&(i.uvs5=this.uvs5.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs6&&(i.uvs6=this.uvs6.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.indices){i.indices=[];for(let e=t.indexStart;e<t.indexStart+t.indexCount;e++)i.indices.push(this.indices[e]-t.verticesStart)}let r=new VertexDataMaterialInfo;r.indexStart=0,r.indexCount=i.indices?i.indices.length:0,r.materialIndex=t.materialIndex,r.verticesStart=0,r.verticesCount=(i.positions?i.positions.length:0)/3,i.materialInfos=[r],e.push(i)}return e}merge(e,t=!1,i=!1,r=!1,s=!1){let a=Array.isArray(e)?e.map(e=>({vertexData:e})):[{vertexData:e}];return runCoroutineSync(this._mergeCoroutine(void 0,a,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,a=!1,n=!1){var o,l,h,c;this._validate();let u=t.map(e=>e.vertexData),d=this;for(let e of u)if(e){if(e._validate(),n)!this.normals!=!e.normals&&(this.normals?e.normals=new Float32Array(e.positions.length):this.normals=new Float32Array(this.positions.length)),!this.tangents!=!e.tangents&&(this.tangents?e.tangents=new Float32Array(e.positions.length/3*4):this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs!=!e.uvs&&(this.uvs?e.uvs=new Float32Array(e.positions.length/3*2):this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2!=!e.uvs2&&(this.uvs2?e.uvs2=new Float32Array(e.positions.length/3*2):this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3!=!e.uvs3&&(this.uvs3?e.uvs3=new Float32Array(e.positions.length/3*2):this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4!=!e.uvs4&&(this.uvs4?e.uvs4=new Float32Array(e.positions.length/3*2):this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5!=!e.uvs5&&(this.uvs5?e.uvs5=new Float32Array(e.positions.length/3*2):this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6!=!e.uvs6&&(this.uvs6?e.uvs6=new Float32Array(e.positions.length/3*2):this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors!=!e.colors&&(this.colors?(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)):(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1))),!this.matricesIndices!=!e.matricesIndices&&(this.matricesIndices?e.matricesIndices=new Float32Array(e.positions.length/3*4):this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights!=!e.matricesWeights&&(this.matricesWeights?e.matricesWeights=new Float32Array(e.positions.length/3*4):this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra!=!e.matricesIndicesExtra&&(this.matricesIndicesExtra?e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4):this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra!=!e.matricesWeightsExtra&&(this.matricesWeightsExtra?e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4):this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4));else if(!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let i=0,r=0,s=0,a=[],n=null,o=[];for(let t of this.splitBasedOnMaterialID())o.push({vertexData:t,transform:e});for(let e of t)if(e.vertexData)for(let t of e.vertexData.splitBasedOnMaterialID())o.push({vertexData:t,transform:e.transform});for(let e of(o.sort((e,t)=>{let i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,r=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>r?1:i===r?0:-1}),o)){let t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,n&&n.materialIndex===i)n.indexCount+=t.indices.length,n.verticesCount+=t.positions.length/3;else{let e=new VertexDataMaterialInfo;e.materialIndex=i,e.indexStart=r,e.indexCount=t.indices.length,e.verticesStart=s,e.verticesCount=t.positions.length/3,a.push(e),n=e}r+=t.indices.length,s+=t.positions.length/3}let l=o.splice(0,1)[0];d=l.vertexData,e=l.transform,u=o.map(e=>e.vertexData),t=o,this.materialInfos=a}let _=u.reduce((e,t)=>{var i,r;return e+(null!==(r=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==r?r:0)},null!==(l=null===(o=d.indices)||void 0===o?void 0:o.length)&&void 0!==l?l:0),p=s||u.some(e=>e.indices===d.indices),f=p?null===(h=d.indices)||void 0===h?void 0:h.slice():d.indices;if(_>0){let s=null!==(c=null==f?void 0:f.length)&&void 0!==c?c:0;if(f||(f=Array(_)),f.length!==_){if(Array.isArray(f))f.length=_;else{let e=i||f instanceof Uint32Array?new Uint32Array(_):new Uint16Array(_);e.set(f),f=e}e&&0>e.determinant()&&mesh_vertexData_VertexData._FlipFaces(f,0,s)}let a=d.positions?d.positions.length/3:0;for(let{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t<e.indices.length;t++)f[s+t]=e.indices[t]+a;i&&0>i.determinant()&&mesh_vertexData_VertexData._FlipFaces(f,s,e.indices.length),a+=e.positions.length/3,s+=e.indices.length,r&&(yield)}}return this.indices=f,this.positions=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.PositionKind,d.positions,e,t.map(e=>[e.vertexData.positions,e.transform])),r&&(yield),d.normals&&(this.normals=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.NormalKind,d.normals,e,t.map(e=>[e.vertexData.normals,e.transform])),r&&(yield)),d.tangents&&(this.tangents=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.TangentKind,d.tangents,e,t.map(e=>[e.vertexData.tangents,e.transform])),r&&(yield)),d.uvs&&(this.uvs=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UVKind,d.uvs,e,t.map(e=>[e.vertexData.uvs,e.transform])),r&&(yield)),d.uvs2&&(this.uvs2=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV2Kind,d.uvs2,e,t.map(e=>[e.vertexData.uvs2,e.transform])),r&&(yield)),d.uvs3&&(this.uvs3=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV3Kind,d.uvs3,e,t.map(e=>[e.vertexData.uvs3,e.transform])),r&&(yield)),d.uvs4&&(this.uvs4=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV4Kind,d.uvs4,e,t.map(e=>[e.vertexData.uvs4,e.transform])),r&&(yield)),d.uvs5&&(this.uvs5=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV5Kind,d.uvs5,e,t.map(e=>[e.vertexData.uvs5,e.transform])),r&&(yield)),d.uvs6&&(this.uvs6=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV6Kind,d.uvs6,e,t.map(e=>[e.vertexData.uvs6,e.transform])),r&&(yield)),d.colors&&(this.colors=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.ColorKind,d.colors,e,t.map(e=>[e.vertexData.colors,e.transform])),r&&(yield)),d.matricesIndices&&(this.matricesIndices=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesIndicesKind,d.matricesIndices,e,t.map(e=>[e.vertexData.matricesIndices,e.transform])),r&&(yield)),d.matricesWeights&&(this.matricesWeights=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesWeightsKind,d.matricesWeights,e,t.map(e=>[e.vertexData.matricesWeights,e.transform])),r&&(yield)),d.matricesIndicesExtra&&(this.matricesIndicesExtra=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesIndicesExtraKind,d.matricesIndicesExtra,e,t.map(e=>[e.vertexData.matricesIndicesExtra,e.transform])),r&&(yield)),d.matricesWeightsExtra&&(this.matricesWeightsExtra=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesWeightsExtraKind,d.matricesWeightsExtra,e,t.map(e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,r){let s=r.filter(e=>null!==e[0]&&void 0!==e[0]);if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));let a=s.reduce((e,t)=>e+t[0].length,t.length),n=e===buffer_VertexBuffer.PositionKind?mesh_vertexData_VertexData._TransformVector3Coordinates:e===buffer_VertexBuffer.NormalKind?mesh_vertexData_VertexData._TransformVector3Normals:e===buffer_VertexBuffer.TangentKind?mesh_vertexData_VertexData._TransformVector4Normals:()=>{};if(t instanceof Float32Array){let e=new Float32Array(a);e.set(t),i&&n(e,i,0,t.length);let r=t.length;for(let[t,i]of s)e.set(t,r),i&&n(e,i,r,t.length),r+=t.length;return e}{let e=Array(a);for(let i=0;i<t.length;i++)e[i]=t[i];i&&n(e,i,0,t.length);let r=t.length;for(let[t,i]of s){for(let i=0;i<t.length;i++)e[r+i]=t[i];i&&n(e,i,r,t.length),r+=t.length}return e}}_validate(){if(!this.positions)throw new RuntimeError("Positions are required",b.MeshInvalidPositionsError);let getElementCount=(e,t)=>{let i=buffer_VertexBuffer.DeduceStride(e);if(t.length%i!=0)throw Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},e=getElementCount(buffer_VertexBuffer.PositionKind,this.positions),validateElementCount=(t,i)=>{let r=getElementCount(t,i);if(r!==e)throw Error("The "+t+"s element count ("+r+") does not match the positions count ("+e+")")};this.normals&&validateElementCount(buffer_VertexBuffer.NormalKind,this.normals),this.tangents&&validateElementCount(buffer_VertexBuffer.TangentKind,this.tangents),this.uvs&&validateElementCount(buffer_VertexBuffer.UVKind,this.uvs),this.uvs2&&validateElementCount(buffer_VertexBuffer.UV2Kind,this.uvs2),this.uvs3&&validateElementCount(buffer_VertexBuffer.UV3Kind,this.uvs3),this.uvs4&&validateElementCount(buffer_VertexBuffer.UV4Kind,this.uvs4),this.uvs5&&validateElementCount(buffer_VertexBuffer.UV5Kind,this.uvs5),this.uvs6&&validateElementCount(buffer_VertexBuffer.UV6Kind,this.uvs6),this.colors&&validateElementCount(buffer_VertexBuffer.ColorKind,this.colors),this.matricesIndices&&validateElementCount(buffer_VertexBuffer.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&validateElementCount(buffer_VertexBuffer.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&validateElementCount(buffer_VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&validateElementCount(buffer_VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){let e=this.serialize();return mesh_vertexData_VertexData.Parse(e)}serialize(){let e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors)),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos)for(let t of(e.materialInfos=[],this.materialInfos)){let i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}return e}static ExtractFromMesh(e,t,i){return mesh_vertexData_VertexData._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return mesh_vertexData_VertexData._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){let r=new mesh_vertexData_VertexData;return e.isVerticesDataPresent(buffer_VertexBuffer.PositionKind)&&(r.positions=e.getVerticesData(buffer_VertexBuffer.PositionKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)&&(r.normals=e.getVerticesData(buffer_VertexBuffer.NormalKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)&&(r.tangents=e.getVerticesData(buffer_VertexBuffer.TangentKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(r.uvs=e.getVerticesData(buffer_VertexBuffer.UVKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&(r.uvs2=e.getVerticesData(buffer_VertexBuffer.UV2Kind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UV3Kind)&&(r.uvs3=e.getVerticesData(buffer_VertexBuffer.UV3Kind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UV4Kind)&&(r.uvs4=e.getVerticesData(buffer_VertexBuffer.UV4Kind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UV5Kind)&&(r.uvs5=e.getVerticesData(buffer_VertexBuffer.UV5Kind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UV6Kind)&&(r.uvs6=e.getVerticesData(buffer_VertexBuffer.UV6Kind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.ColorKind)&&(r.colors=e.getVerticesData(buffer_VertexBuffer.ColorKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesKind)&&(r.matricesIndices=e.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)&&(r.matricesWeights=e.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesExtraKind)&&(r.matricesIndicesExtra=e.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsExtraKind)&&(r.matricesWeightsExtra=e.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind,t,i)),r.indices=e.getIndices(t,i),r}static CreateRibbon(e){throw _WarnImport("ribbonBuilder")}static CreateBox(e){throw _WarnImport("boxBuilder")}static CreateTiledBox(e){throw _WarnImport("tiledBoxBuilder")}static CreateTiledPlane(e){throw _WarnImport("tiledPlaneBuilder")}static CreateSphere(e){throw _WarnImport("sphereBuilder")}static CreateCylinder(e){throw _WarnImport("cylinderBuilder")}static CreateTorus(e){throw _WarnImport("torusBuilder")}static CreateLineSystem(e){throw _WarnImport("linesBuilder")}static CreateDashedLines(e){throw _WarnImport("linesBuilder")}static CreateGround(e){throw _WarnImport("groundBuilder")}static CreateTiledGround(e){throw _WarnImport("groundBuilder")}static CreateGroundFromHeightMap(e){throw _WarnImport("groundBuilder")}static CreatePlane(e){throw _WarnImport("planeBuilder")}static CreateDisc(e){throw _WarnImport("discBuilder")}static CreatePolygon(e,t,i,r,s,a,n){throw _WarnImport("polygonBuilder")}static CreateIcoSphere(e){throw _WarnImport("icoSphereBuilder")}static CreatePolyhedron(e){throw _WarnImport("polyhedronBuilder")}static CreateCapsule(e={orientation:math_vector_Vector3.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw _WarnImport("capsuleBuilder")}static CreateTorusKnot(e){throw _WarnImport("torusKnotBuilder")}static ComputeNormals(e,t,i,r){let s=0,a=0,n=0,o=0,l=0,h=0,c=0,u=0,d=0,_=0,p=0,f=0,m=0,g=0,v=0,x=0,b=0,T=0,S=0,C=0,E=!1,y=!1,R=!1,P=!1,A=1,M=0,I=null;r&&(E=!!r.facetNormals,y=!!r.facetPositions,R=!!r.facetPartitioning,A=!0===r.useRightHandedSystem?-1:1,M=r.ratio||0,P=!!r.depthSort,I=r.distanceTo,P&&void 0===I&&(I=math_vector_Vector3.Zero()));let D=0,O=0,B=0,N=0;for(R&&r&&r.bbSize&&(D=r.subDiv.X*M/r.bbSize.x,O=r.subDiv.Y*M/r.bbSize.y,B=r.subDiv.Z*M/r.bbSize.z,N=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0),s=0;s<e.length;s++)i[s]=0;let F=t.length/3|0;for(s=0;s<F;s++){if(m=(f=3*t[3*s])+1,g=f+2,x=(v=3*t[3*s+1])+1,b=v+2,S=(T=3*t[3*s+2])+1,C=T+2,a=e[f]-e[v],n=e[m]-e[x],o=e[g]-e[b],l=e[T]-e[v],h=e[S]-e[x],p=0===(p=Math.sqrt((u=A*(n*(c=e[C]-e[b])-o*h))*u+(d=A*(o*l-a*c))*d+(_=A*(a*h-n*l))*_))?1:p,u/=p,d/=p,_/=p,E&&r&&(r.facetNormals[s].x=u,r.facetNormals[s].y=d,r.facetNormals[s].z=_),y&&r&&(r.facetPositions[s].x=(e[f]+e[v]+e[T])/3,r.facetPositions[s].y=(e[m]+e[x]+e[S])/3,r.facetPositions[s].z=(e[g]+e[b]+e[C])/3),R&&r){let t=Math.floor((r.facetPositions[s].x-r.bInfo.minimum.x*M)*D),i=Math.floor((r.facetPositions[s].y-r.bInfo.minimum.y*M)*O),a=Math.floor((r.facetPositions[s].z-r.bInfo.minimum.z*M)*B),n=Math.floor((e[f]-r.bInfo.minimum.x*M)*D),o=Math.floor((e[m]-r.bInfo.minimum.y*M)*O),l=Math.floor((e[g]-r.bInfo.minimum.z*M)*B),h=Math.floor((e[v]-r.bInfo.minimum.x*M)*D),c=Math.floor((e[x]-r.bInfo.minimum.y*M)*O),u=Math.floor((e[b]-r.bInfo.minimum.z*M)*B),d=Math.floor((e[T]-r.bInfo.minimum.x*M)*D),_=Math.floor((e[S]-r.bInfo.minimum.y*M)*O),p=Math.floor((e[C]-r.bInfo.minimum.z*M)*B),E=n+r.subDiv.max*o+N*l,y=h+r.subDiv.max*c+N*u,R=d+r.subDiv.max*_+N*p,P=t+r.subDiv.max*i+N*a;r.facetPartitioning[P]=r.facetPartitioning[P]?r.facetPartitioning[P]:[],r.facetPartitioning[E]=r.facetPartitioning[E]?r.facetPartitioning[E]:[],r.facetPartitioning[y]=r.facetPartitioning[y]?r.facetPartitioning[y]:[],r.facetPartitioning[R]=r.facetPartitioning[R]?r.facetPartitioning[R]:[],r.facetPartitioning[E].push(s),y!=E&&r.facetPartitioning[y].push(s),R==y||R==E||r.facetPartitioning[R].push(s),P==E||P==y||P==R||r.facetPartitioning[P].push(s)}if(P&&r&&r.facetPositions){let e=r.depthSortedFacets[s];e.ind=3*s,e.sqDistance=math_vector_Vector3.DistanceSquared(r.facetPositions[s],I)}i[f]+=u,i[m]+=d,i[g]+=_,i[v]+=u,i[x]+=d,i[b]+=_,i[T]+=u,i[S]+=d,i[C]+=_}for(s=0;s<i.length/3;s++)p=0===(p=Math.sqrt((u=i[3*s])*u+(d=i[3*s+1])*d+(_=i[3*s+2])*_))?1:p,u/=p,d/=p,_/=p,i[3*s]=u,i[3*s+1]=d,i[3*s+2]=_}static _ComputeSides(e,t,i,r,s,a,n){let o,l;let h=i.length,c=r.length;switch(e=e||mesh_vertexData_VertexData.DEFAULTSIDE){case mesh_vertexData_VertexData.FRONTSIDE:break;case mesh_vertexData_VertexData.BACKSIDE:for(o=0;o<h;o+=3){let e=i[o];i[o]=i[o+2],i[o+2]=e}for(l=0;l<c;l++)r[l]=-r[l];break;case mesh_vertexData_VertexData.DOUBLESIDE:{let e=t.length,u=e/3;for(let i=0;i<e;i++)t[e+i]=t[i];for(o=0;o<h;o+=3)i[o+h]=i[o+2]+u,i[o+1+h]=i[o+1]+u,i[o+2+h]=i[o]+u;for(l=0;l<c;l++)r[c+l]=-r[l];let d=s.length,_=0;for(_=0;_<d;_++)s[_+d]=s[_];for(o=0,a=a||new math_vector_Vector4(0,0,1,1),n=n||new math_vector_Vector4(0,0,1,1),_=0;o<d/2;o++)s[_]=a.x+(a.z-a.x)*s[_],s[_+1]=a.y+(a.w-a.y)*s[_+1],s[_+d]=n.x+(n.z-n.x)*s[_+d],s[_+d+1]=n.y+(n.w-n.y)*s[_+d+1],_+=2}}}static Parse(e){let t=new mesh_vertexData_VertexData,i=e.positions;i&&t.set(i,buffer_VertexBuffer.PositionKind);let r=e.normals;r&&t.set(r,buffer_VertexBuffer.NormalKind);let s=e.tangents;s&&t.set(s,buffer_VertexBuffer.TangentKind);let a=e.uvs;a&&t.set(a,buffer_VertexBuffer.UVKind);let n=e.uvs2;n&&t.set(n,buffer_VertexBuffer.UV2Kind);let o=e.uvs3;o&&t.set(o,buffer_VertexBuffer.UV3Kind);let l=e.uvs4;l&&t.set(l,buffer_VertexBuffer.UV4Kind);let h=e.uvs5;h&&t.set(h,buffer_VertexBuffer.UV5Kind);let c=e.uvs6;c&&t.set(c,buffer_VertexBuffer.UV6Kind);let u=e.colors;u&&t.set(math_color_Color4.CheckColors4(u,i.length/3),buffer_VertexBuffer.ColorKind);let d=e.matricesIndices;d&&t.set(d,buffer_VertexBuffer.MatricesIndicesKind);let _=e.matricesWeights;_&&t.set(_,buffer_VertexBuffer.MatricesWeightsKind);let p=e.indices;p&&(t.indices=p);let f=e.materialInfos;if(f)for(let e of(t.materialInfos=[],f)){let i=new VertexDataMaterialInfo;i.indexCount=e.indexCount,i.indexStart=e.indexStart,i.verticesCount=e.verticesCount,i.verticesStart=e.verticesStart,i.materialIndex=e.materialIndex,t.materialInfos.push(i)}return t}static ImportVertexData(e,t){let i=mesh_vertexData_VertexData.Parse(e);t.setAllVerticesData(i,e.updatable)}};mesh_vertexData_VertexData.FRONTSIDE=0,mesh_vertexData_VertexData.BACKSIDE=1,mesh_vertexData_VertexData.DOUBLESIDE=2,mesh_vertexData_VertexData.DEFAULTSIDE=0,mesh_vertexData_VertexData._UniqueIDGenerator=0,__decorate([nativeOverride.filter((...[e])=>!Array.isArray(e))],mesh_vertexData_VertexData,"_TransformVector3Coordinates",null),__decorate([nativeOverride.filter((...[e])=>!Array.isArray(e))],mesh_vertexData_VertexData,"_TransformVector3Normals",null),__decorate([nativeOverride.filter((...[e])=>!Array.isArray(e))],mesh_vertexData_VertexData,"_TransformVector4Normals",null),__decorate([nativeOverride.filter((...[e])=>!Array.isArray(e))],mesh_vertexData_VertexData,"_FlipFaces",null);let SceneLoaderFlags=class SceneLoaderFlags{static get ForceFullSceneLoadingForIncremental(){return SceneLoaderFlags._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){SceneLoaderFlags._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return SceneLoaderFlags._ShowLoadingScreen}static set ShowLoadingScreen(e){SceneLoaderFlags._ShowLoadingScreen=e}static get loggingLevel(){return SceneLoaderFlags._LoggingLevel}static set loggingLevel(e){SceneLoaderFlags._LoggingLevel=e}static get CleanBoneMatrixWeights(){return SceneLoaderFlags._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){SceneLoaderFlags._CleanBoneMatrixWeights=e}};SceneLoaderFlags._ForceFullSceneLoadingForIncremental=!1,SceneLoaderFlags._ShowLoadingScreen=!0,SceneLoaderFlags._CleanBoneMatrixWeights=!1,SceneLoaderFlags._LoggingLevel=0;let CompatibilityOptions=class CompatibilityOptions{};CompatibilityOptions.UseOpenGLOrientationForUV=!1;let Geometry=class Geometry{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){let t=new Geometry(Geometry.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null){if(this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||engineStore_EngineStore.LastCreatedScene,!this._scene)return;this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0}_rebuild(){for(let e in this._vertexArrayObjects&&(this._vertexArrayObjects={}),0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),this._vertexBuffers){let t=this._vertexBuffers[e];t._rebuild()}}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,r){i&&Array.isArray(t)&&(t=new Float32Array(t));let s=new buffer_VertexBuffer(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:r,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){let r=e.getKind();this._vertexBuffers[r]&&i&&this._vertexBuffers[r].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[r]=e;let s=this._meshes,a=s.length;if(r===buffer_VertexBuffer.PositionKind){this._totalVertices=null!=t?t:e.totalVertices,this._updateExtend(e.getFloatData()),this._resetPointsArrayCache();let i=this._extend&&this._extend.minimum||new math_vector_Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),r=this._extend&&this._extend.maximum||new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e<a;e++){let t=s[e];t.buildBoundingInfo(i,r),t._createGlobalSubMesh(t.isUnIndexed),t.computeWorldMatrix(!0),t.synchronizeInstances()}}this._notifyUpdate(r)}updateVerticesDataDirectly(e,t,i,r=!1){let s=this.getVertexBuffer(e);s&&(s.updateDirectly(t,i,r),this._notifyUpdate(e))}updateVerticesData(e,t,i=!1){let r=this.getVertexBuffer(e);r&&(r.update(t),e===buffer_VertexBuffer.PositionKind&&this._updateBoundingInfo(i,t),this._notifyUpdate(e))}_updateBoundingInfo(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e){let e=this._meshes;for(let t of e){t.hasBoundingInfo?t.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):t.buildBoundingInfo(this._extend.minimum,this._extend.maximum);let e=t.subMeshes;for(let t of e)t.refreshBoundingInfo()}}}_bind(e,t,i,r){if(!e)return;void 0===t&&(t=this._indexBuffer);let s=this.getVertexBuffers();if(!s)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!r){this._engine.bindBuffers(s,t,e,i);return}let a=r||this._vertexArrayObjects;a[e.key]||(a[e.key]=this._engine.recordVertexArrayObject(s,t,e,i)),this._engine.bindVertexArrayObject(a[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,i){let r=this.getVertexBuffer(e);return r?r.getFloatData(this._totalVertices,i||t&&1!==this._meshes.length):null}isVertexBufferUpdatable(e){let t=this._vertexBuffers[e];return!!t&&t.isUpdatable()}getVertexBuffer(e){return this.isReady()?this._vertexBuffers[e]:null}getVertexBuffers(){return this.isReady()?this._vertexBuffers:null}isVerticesDataPresent(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}getVerticesDataKinds(){let e;let t=[];if(!this._vertexBuffers&&this._delayInfo)for(e in this._delayInfo)t.push(e);else for(e in this._vertexBuffers)t.push(e);return t}updateIndices(e,t,i=!1){if(this._indexBuffer){if(this._indexBufferIsUpdatable){let r=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),r)for(let e of this._meshes)e._createGlobalSubMesh(!0)}else this.setIndices(e,null,!0)}}setIndices(e,t=null,i=!1){for(let r of(this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i)),void 0!=t&&(this._totalVertices=t),this._meshes))r._createGlobalSubMesh(!0),r.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;let i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){let i=this._meshes,r=i.indexOf(e);-1!==r&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;let t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();let i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(buffer_VertexBuffer.PositionKind)))return;this._extend=extractMinAndMax(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){let t=this._meshes.length;for(let i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===buffer_VertexBuffer.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){for(let t of(this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects(),this._meshes))t._markSubMeshesAsAttributesDirty()}load(e,t){if(2!==this.delayLoadState){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);let r=this._meshes,s=r.length;for(let e=0;e<s;e++)this._applyToMesh(r[e]);t&&t()},void 0,!0))}toLeftHanded(){let e=this.getIndices(!1);if(null!=e&&e.length>0){for(let t=0;t<e.length;t+=3){let i=e[t+0];e[t+0]=e[t+2],e[t+2]=i}this.setIndices(e)}let t=this.getVerticesData(buffer_VertexBuffer.PositionKind,!1);if(null!=t&&t.length>0){for(let e=0;e<t.length;e+=3)t[e+2]=-t[e+2];this.setVerticesData(buffer_VertexBuffer.PositionKind,t,!1)}let i=this.getVerticesData(buffer_VertexBuffer.NormalKind,!1);if(null!=i&&i.length>0){for(let e=0;e<i.length;e+=3)i[e+2]=-i[e+2];this.setVerticesData(buffer_VertexBuffer.NormalKind,i,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;let e=this.getVerticesData(buffer_VertexBuffer.PositionKind);if(!e||0===e.length)return!1;for(let t=3*this._positionsCache.length,i=this._positionsCache.length;t<e.length;t+=3,++i)this._positionsCache[i]=math_vector_Vector3.FromArray(e,t);for(let t=0,i=0;t<e.length;t+=3,++i)this._positionsCache[i].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0}isDisposed(){return this._isDisposed}_disposeVertexArrayObjects(){if(this._vertexArrayObjects){for(let e in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);this._vertexArrayObjects={};let e=this._meshes,t=e.length;for(let i=0;i<t;i++)e[i]._invalidateInstanceVertexArrayObject()}}dispose(){let e;let t=this._meshes,i=t.length;for(e=0;e<i;e++)this.releaseForMesh(t[e]);for(let e in this._meshes.length=0,this._disposeVertexArrayObjects(),this._vertexBuffers)this._vertexBuffers[e].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=0,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){let e=this._parentContainer.geometries.indexOf(this);e>-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){let t;let i=new mesh_vertexData_VertexData;i.indices=[];let r=this.getIndices();if(r)for(let e=0;e<r.length;e++)i.indices.push(r[e]);let s=!1,a=!1;for(t in this._vertexBuffers){let e=this.getVerticesData(t);if(e&&(e instanceof Float32Array?i.set(new Float32Array(e),t):i.set(e.slice(0),t),!a)){let e=this.getVertexBuffer(t);e&&(a=!(s=e.isUpdatable()))}}let n=new Geometry(e,this._scene,i,s);for(t in n.delayLoadState=this.delayLoadState,n.delayLoadingFile=this.delayLoadingFile,n._delayLoadingFunction=this._delayLoadingFunction,this._delayInfo)n._delayInfo=n._delayInfo||[],n._delayInfo.push(t);return n._boundingInfo=new boundingInfo_BoundingInfo(this._extend.minimum,this._extend.maximum),n}serialize(){let e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,Tags&&Tags.HasTags(this)&&(e.tags=Tags.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){for(let e in this._indices=[],this._resetPointsArrayCache(),this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){let e=this.serialize();return this.isVerticesDataPresent(buffer_VertexBuffer.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.PositionKind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.NormalKind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.TangentKind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.TangentKind)&&(e.tangents._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UVKind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UV2Kind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.UV2Kind)&&(e.uvs2._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UV3Kind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.UV3Kind)&&(e.uvs3._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UV4Kind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.UV4Kind)&&(e.uvs4._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UV5Kind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.UV5Kind)&&(e.uvs5._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.UV6Kind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.UV6Kind)&&(e.uvs6._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.ColorKind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(buffer_VertexBuffer.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind)),this.isVertexBufferUpdatable(buffer_VertexBuffer.MatricesWeightsKind)&&(e.matricesWeights._updatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){let i=e._geometry;return i?i.copy(t):null}static RandomId(){return tools_Tools.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i<t.geometries.length;i++)if(t.geometries[i]._loadedUniqueId===e)return t.geometries[i];return null}static _ImportGeometry(e,t){let i=t.getScene(),r=e.geometryUniqueId,s=e.geometryId;if(r||s){let e=r?this._GetGeometryByLoadedUniqueId(r,i):i.getGeometryById(s);e&&e.applyToMesh(t)}else if(e instanceof ArrayBuffer){let i=t._binaryInfo;if(i.positionsAttrDesc&&i.positionsAttrDesc.count>0){let r=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(buffer_VertexBuffer.PositionKind,r,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){let r=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(buffer_VertexBuffer.NormalKind,r,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){let r=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(buffer_VertexBuffer.TangentKind,r,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){let r=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(buffer_VertexBuffer.UVKind,r,!1)}if(i.uvs2AttrDesc&&i.uvs2AttrDesc.count>0){let r=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(buffer_VertexBuffer.UV2Kind,r,!1)}if(i.uvs3AttrDesc&&i.uvs3AttrDesc.count>0){let r=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(buffer_VertexBuffer.UV3Kind,r,!1)}if(i.uvs4AttrDesc&&i.uvs4AttrDesc.count>0){let r=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(buffer_VertexBuffer.UV4Kind,r,!1)}if(i.uvs5AttrDesc&&i.uvs5AttrDesc.count>0){let r=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(buffer_VertexBuffer.UV5Kind,r,!1)}if(i.uvs6AttrDesc&&i.uvs6AttrDesc.count>0){let r=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(buffer_VertexBuffer.UV6Kind,r,!1)}if(i.colorsAttrDesc&&i.colorsAttrDesc.count>0){let r=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(buffer_VertexBuffer.ColorKind,r,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e<r.length;e++){let t=r[e];s.push(255&t),s.push((65280&t)>>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e<r.length;e++){let t=r[e];s.push(255&t),s.push((65280&t)>>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){let r=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,r,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){let r=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(r,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){let r=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e<i.subMeshesAttrDesc.count;e++){let i=r[5*e+0],s=r[5*e+1],a=r[5*e+2],n=r[5*e+3],o=r[5*e+4];subMesh_SubMesh.AddToMesh(i,s,a,n,o,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(buffer_VertexBuffer.PositionKind,e.positions,e.positions._updatable),t.setVerticesData(buffer_VertexBuffer.NormalKind,e.normals,e.normals._updatable),e.tangents&&t.setVerticesData(buffer_VertexBuffer.TangentKind,e.tangents,e.tangents._updatable),e.uvs&&t.setVerticesData(buffer_VertexBuffer.UVKind,e.uvs,e.uvs._updatable),e.uvs2&&t.setVerticesData(buffer_VertexBuffer.UV2Kind,e.uvs2,e.uvs2._updatable),e.uvs3&&t.setVerticesData(buffer_VertexBuffer.UV3Kind,e.uvs3,e.uvs3._updatable),e.uvs4&&t.setVerticesData(buffer_VertexBuffer.UV4Kind,e.uvs4,e.uvs4._updatable),e.uvs5&&t.setVerticesData(buffer_VertexBuffer.UV5Kind,e.uvs5,e.uvs5._updatable),e.uvs6&&t.setVerticesData(buffer_VertexBuffer.UV6Kind,e.uvs6,e.uvs6._updatable),e.colors&&t.setVerticesData(buffer_VertexBuffer.ColorKind,math_color_Color4.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices){if(e.matricesIndices._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable);else{let i=[];for(let t=0;t<e.matricesIndices.length;t++){let r=e.matricesIndices[t];i.push(255&r),i.push((65280&r)>>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,i,e.matricesIndices._updatable)}}if(e.matricesIndicesExtra){if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{let i=[];for(let t=0;t<e.matricesIndicesExtra.length;t++){let r=e.matricesIndicesExtra[t];i.push(255&r),i.push((65280&r)>>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}}e.matricesWeights&&(Geometry._CleanMatricesWeights(e,t),t.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i<e.subMeshes.length;i++){let r=e.subMeshes[i];subMesh_SubMesh.AddToMesh(r.materialIndex,r.verticesStart,r.verticesCount,r.indexStart,r.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),i.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){if(!SceneLoaderFlags.CleanBoneMatrixWeights)return;let i=0;if(!(e.skeletonId>-1))return;{let r=t.getScene().getLastSkeletonById(e.skeletonId);if(!r)return;i=r.bones.length}let r=t.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind),s=t.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind),a=e.matricesWeights,n=e.matricesWeightsExtra,o=e.numBoneInfluencer,l=a.length;for(let e=0;e<l;e+=4){let t=0,l=-1;for(let i=0;i<4;i++){let r=a[e+i];t+=r,r<.001&&l<0&&(l=i)}if(n)for(let i=0;i<4;i++){let r=n[e+i];t+=r,r<.001&&l<0&&(l=i+4)}if((l<0||l>o-1)&&(l=o-1),t>.001){let i=1/t;for(let t=0;t<4;t++)a[e+t]*=i;if(n)for(let t=0;t<4;t++)n[e+t]*=i}else l>=4?(n[e+l-4]=1-t,s[e+l-4]=i):(a[e+l]=1-t,r[e+l]=i)}t.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,s)}static Parse(e,t,i){let r=new Geometry(e.id,t,void 0,e.updatable);return r._loadedUniqueId=e.uniqueId,Tags&&Tags.AddTagsTo(r,e.tags),e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r._boundingInfo=new boundingInfo_BoundingInfo(math_vector_Vector3.FromArray(e.boundingBoxMinimum),math_vector_Vector3.FromArray(e.boundingBoxMaximum)),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(buffer_VertexBuffer.UVKind),e.hasUVs2&&r._delayInfo.push(buffer_VertexBuffer.UV2Kind),e.hasUVs3&&r._delayInfo.push(buffer_VertexBuffer.UV3Kind),e.hasUVs4&&r._delayInfo.push(buffer_VertexBuffer.UV4Kind),e.hasUVs5&&r._delayInfo.push(buffer_VertexBuffer.UV5Kind),e.hasUVs6&&r._delayInfo.push(buffer_VertexBuffer.UV6Kind),e.hasColors&&r._delayInfo.push(buffer_VertexBuffer.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(buffer_VertexBuffer.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(buffer_VertexBuffer.MatricesWeightsKind),r._delayLoadingFunction=mesh_vertexData_VertexData.ImportVertexData):mesh_vertexData_VertexData.ImportVertexData(e,r),t.pushGeometry(r,!0),r}};let PerformanceMonitor=class PerformanceMonitor{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new RollingAverage(e)}sampleFrame(e=precisionDate_PrecisionDate.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){let 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(){let 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()}};let RollingAverage=class RollingAverage{constructor(e){this._samples=Array(e),this.reset()}add(e){let t;if(this.isSaturated()){let 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;let 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){let t=this._samples.length;return(e%t+t)%t}};function allocateAndCopyTypedBuffer(e,t,i=!1,r){switch(e){case 3:{let e=(ArrayBuffer,new Int8Array(t));return r&&e.set(new Int8Array(r)),e}case 0:{let e=(ArrayBuffer,new Uint8Array(t));return r&&e.set(new Uint8Array(r)),e}case 4:{let e=new Int16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Int16Array(r)),e}case 5:case 8:case 9:case 10:case 2:{let e=new Uint16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Uint16Array(r)),e}case 6:{let e=new Int32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Int32Array(r)),e}case 7:case 11:case 12:case 13:case 14:case 15:{let e=new Uint32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Uint32Array(r)),e}case 1:{let e=new Float32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Float32Array(r)),e}}let s=(ArrayBuffer,new Uint8Array(t));return r&&s.set(new Uint8Array(r)),s}ThinEngine.prototype.setAlphaConstants=function(e,t,i,r){this._alphaState.setAlphaBlendConstants(e,t,i,r)},ThinEngine.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e){if(!t){let t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e},ThinEngine.prototype.getAlphaMode=function(){return this._alphaMode},ThinEngine.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},ThinEngine.prototype.getAlphaEquation=function(){return this._alphaEquation},ThinEngine.prototype._readTexturePixelsSync=function(e,t,i,r=-1,s=0,a=null,n=!0,o=!1,l=0,h=0){var c,u;let d=this._gl;if(!d)throw Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){let e=d.createFramebuffer();if(!e)throw Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}d.bindFramebuffer(d.FRAMEBUFFER,this._dummyFramebuffer),r>-1?d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+r,null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,s):d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,s);let _=void 0!==e.type?this._getWebGLTextureType(e.type):d.UNSIGNED_BYTE;return o?a||(a=allocateAndCopyTypedBuffer(e.type,4*t*i)):_===d.UNSIGNED_BYTE?(a||(a=new Uint8Array(4*t*i)),_=d.UNSIGNED_BYTE):(a||(a=new Float32Array(4*t*i)),_=d.FLOAT),n&&this.flushFramebuffer(),d.readPixels(l,h,t,i,d.RGBA,_,a),d.bindFramebuffer(d.FRAMEBUFFER,this._currentFramebuffer),a},ThinEngine.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,a=null,n=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,r,s,a,n,o,l,h))},ThinEngine.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let r;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},ThinEngine.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0);let s=t.byteLength||t.length;void 0===r||r>=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,r):new Uint8Array(t.buffer,t.byteOffset+i,r),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()};let engine_Engine=class engine_Engine extends ThinEngine{static get NpmPackage(){return ThinEngine.NpmPackage}static get Version(){return ThinEngine.Version}static get Instances(){return engineStore_EngineStore.Instances}static get LastCreatedEngine(){return engineStore_EngineStore.LastCreatedEngine}static get LastCreatedScene(){return engineStore_EngineStore.LastCreatedScene}_createImageBitmapFromSource(e,t){let i=new Promise((i,r)=>{let s=new Image;s.onload=()=>{s.decode().then(()=>{this.createImageBitmap(s,t).then(e=>{i(e)})})},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=e});return i}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){let r=this.createCanvas(t,i),s=r.getContext("2d");if(!s)throw Error("Unable to get 2d context for resizeImageBitmap");s.drawImage(e,0,0);let a=s.getImageData(0,0,t,i).data;return a}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i<engine_Engine.Instances.length;i++){let r=engine_Engine.Instances[i];for(let i=0;i<r.scenes.length;i++)r.scenes[i].markAllMaterialsAsDirty(e,t)}}static DefaultLoadingScreenFactory(e){throw _WarnImport("LoadingScreen")}get _supportsHardwareTextureRescaling(){return!!engine_Engine._RescalePostProcessFactory}get performanceMonitor(){return this._performanceMonitor}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}getInputElement(){return this._renderingCanvas}constructor(e,t,i,r=!1){if(super(e,t,i,r),this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.scenes=[],this._virtualScenes=[],this.onNewSceneAddedObservable=new observable_Observable,this.postProcesses=[],this.isPointerLock=!1,this.onResizeObservable=new observable_Observable,this.onCanvasBlurObservable=new observable_Observable,this.onCanvasFocusObservable=new observable_Observable,this.onCanvasPointerOutObservable=new observable_Observable,this.onBeginFrameObservable=new observable_Observable,this.customAnimationFrameRequester=null,this.onEndFrameObservable=new observable_Observable,this.onBeforeShaderCompilationObservable=new observable_Observable,this.onAfterShaderCompilationObservable=new observable_Observable,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this._fps=60,this._deltaTime=0,this._drawCalls=new perfCounter_PerfCounter,this.canvasTabIndex=1,this.disablePerformanceMonitorInBackground=!1,this._performanceMonitor=new PerformanceMonitor,this._compatibilityMode=!0,this.currentRenderPassId=0,this._renderPassNames=["main"],engine_Engine.Instances.push(this),!e)return;this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext&&this._sharedInit(e)}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),this._onCanvasFocus=()=>{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)};let 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(),!engine_Engine.audioEngine&&this._creationOptions.audioEngine&&engine_Engine.AudioEngineFactory&&(engine_Engine.audioEngine=engine_Engine.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),IsDocumentAvailable()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&engine_Engine._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!==engine_Engine.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){let 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){let 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,r){let s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){let s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){let e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise((r,s)=>{this._loadFile(e,e=>{r(e)},void 0,t,i,(e,t)=>{s(t)})})}getVertexShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))}setTextureFromPostProcess(e,t,i){var r;let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(r=null==s?void 0:s.texture)&&void 0!==r?r:null,i)}setTextureFromPostProcessOutput(e,t,i){var r,s;this._bindTexture(e,null!==(s=null===(r=null==t?void 0:t._outputTexture)||void 0===r?void 0:r.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(let e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(let e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++){let t=this._activeRenderLoops[e];t()}}_cancelFrame(){if(this._renderingQueueLaunched&&this.customAnimationFrameRequester){this._renderingQueueLaunched=!1;let{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}else super._cancelFrame()}_renderLoop(){if(!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){!this.isFullscreen&&(this._pointerLockRequested=e,this._renderingCanvas&&engine_Engine._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&engine_Engine._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&engine_Engine._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){engine_Engine._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this.onEndFrameObservable.notifyObservers(this)}setSize(e,t,i=!1){if(!this._renderingCanvas||!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e<this.scenes.length;e++){let t=this.scenes[e];for(let e=0;e<t.cameras.length;e++){let i=t.cameras[e];i._currentRenderId=0}}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0}_deletePipelineContext(e){e&&e.program&&e.transformFeedback&&(this.deleteTransformFeedback(e.transformFeedback),e.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,r,s,a=null){s=s||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);let n=super.createShaderProgram(e,t,i,r,s,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),n}_createShaderProgram(e,t,i,r,s=null){let a=r.createProgram();if(e.program=a,!a)throw Error("Unable to create program");if(r.attachShader(a,t),r.attachShader(a,i),this.webGLVersion>1&&s){let t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(a,s),e.transformFeedback=t}return r.linkProgram(a),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),a}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach(t=>{t.postProcesses.forEach(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){let t=++engine_Engine._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t<this.scenes.length;++t){let i=this.scenes[t];for(let t=0;t<i.meshes.length;++t){let r=i.meshes[t];if(r.subMeshes)for(let t=0;t<r.subMeshes.length;++t){let i=r.subMeshes[t];i._removeDrawWrapper(e)}}}}_rescaleTexture(e,t,i,r,s){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);let a=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&engine_Engine._RescalePostProcessFactory&&(this._rescalePostProcess=engine_Engine._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled(()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let n=i;n||(n=this.scenes[this.scenes.length-1]),n.postProcessManager.directRender([this._rescalePostProcess],a,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,r,0,0,t.width,t.height,0),this.unBindFramebuffer(a),a.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,r=0,s=0){let a=new WebGLHardwareTexture(e,this._gl),n=new internalTexture_InternalTexture(this,$.Unknown,!0);return n._hardwareTexture=a,n.baseWidth=r,n.baseHeight=s,n.width=r,n.height=s,n.isReady=!0,n.useMipMaps=t,this.updateTextureSamplingMode(i,n),n}_uploadImageToTexture(e,t,i=0,r=0){let s=this._gl,a=this._getWebGLTextureType(e.type),n=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,n),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,r,o,n,a,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion){logger_Logger.Error("WebGL 1 does not support texture comparison.");return}let 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){let t=this._gl.createBuffer();if(!t)throw Error("Unable to create instance buffer");let i=new WebGLDataBuffer(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){let r=this._gl;return new Promise((s,a)=>{let check=()=>{let n=r.clientWaitSync(e,t,0);if(n==r.WAIT_FAILED){a();return}if(n==r.TIMEOUT_EXPIRED){setTimeout(check,i);return}s()};check()})}_readPixelsAsync(e,t,i,r,s,a,n){if(this._webGLVersion<2)throw Error("_readPixelsAsync only work on WebGL2+");let o=this._gl,l=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.bufferData(o.PIXEL_PACK_BUFFER,n.byteLength,o.STREAM_READ),o.readPixels(e,t,i,r,s,a,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);let h=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(o.flush(),this._clientWaitAsync(h,0,10).then(()=>(o.deleteSync(h),o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,n),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(l),n))):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===engineStore_EngineStore.Instances.length&&engine_Engine.audioEngine&&(engine_Engine.audioEngine.dispose(),engine_Engine.audioEngine=null);let 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)),IsDocumentAvailable()&&(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();let t=engineStore_EngineStore.Instances.indexOf(this);t>=0&&engineStore_EngineStore.Instances.splice(t,1),engine_Engine.Instances.length||engineStore_EngineStore.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(!IsWindowObjectExist())return;let e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!IsWindowObjectExist())return;let e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=engine_Engine.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){let t=e.requestPointerLock();t instanceof Promise?t.then(()=>{e.focus()}).catch(()=>{}):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){let t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){let e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){let t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);let i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";let r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);let s=0,a=0;try{a=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:s,height:a,descent:a-s}}};engine_Engine.ALPHA_DISABLE=0,engine_Engine.ALPHA_ADD=1,engine_Engine.ALPHA_COMBINE=2,engine_Engine.ALPHA_SUBTRACT=3,engine_Engine.ALPHA_MULTIPLY=4,engine_Engine.ALPHA_MAXIMIZED=5,engine_Engine.ALPHA_ONEONE=6,engine_Engine.ALPHA_PREMULTIPLIED=7,engine_Engine.ALPHA_PREMULTIPLIED_PORTERDUFF=8,engine_Engine.ALPHA_INTERPOLATE=9,engine_Engine.ALPHA_SCREENMODE=10,engine_Engine.DELAYLOADSTATE_NONE=0,engine_Engine.DELAYLOADSTATE_LOADED=1,engine_Engine.DELAYLOADSTATE_LOADING=2,engine_Engine.DELAYLOADSTATE_NOTLOADED=4,engine_Engine.NEVER=512,engine_Engine.ALWAYS=519,engine_Engine.LESS=513,engine_Engine.EQUAL=514,engine_Engine.LEQUAL=515,engine_Engine.GREATER=516,engine_Engine.GEQUAL=518,engine_Engine.NOTEQUAL=517,engine_Engine.KEEP=7680,engine_Engine.REPLACE=7681,engine_Engine.INCR=7682,engine_Engine.DECR=7683,engine_Engine.INVERT=5386,engine_Engine.INCR_WRAP=34055,engine_Engine.DECR_WRAP=34056,engine_Engine.TEXTURE_CLAMP_ADDRESSMODE=0,engine_Engine.TEXTURE_WRAP_ADDRESSMODE=1,engine_Engine.TEXTURE_MIRROR_ADDRESSMODE=2,engine_Engine.TEXTUREFORMAT_ALPHA=0,engine_Engine.TEXTUREFORMAT_LUMINANCE=1,engine_Engine.TEXTUREFORMAT_LUMINANCE_ALPHA=2,engine_Engine.TEXTUREFORMAT_RGB=4,engine_Engine.TEXTUREFORMAT_RGBA=5,engine_Engine.TEXTUREFORMAT_RED=6,engine_Engine.TEXTUREFORMAT_R=6,engine_Engine.TEXTUREFORMAT_RG=7,engine_Engine.TEXTUREFORMAT_RED_INTEGER=8,engine_Engine.TEXTUREFORMAT_R_INTEGER=8,engine_Engine.TEXTUREFORMAT_RG_INTEGER=9,engine_Engine.TEXTUREFORMAT_RGB_INTEGER=10,engine_Engine.TEXTUREFORMAT_RGBA_INTEGER=11,engine_Engine.TEXTURETYPE_UNSIGNED_BYTE=0,engine_Engine.TEXTURETYPE_UNSIGNED_INT=0,engine_Engine.TEXTURETYPE_FLOAT=1,engine_Engine.TEXTURETYPE_HALF_FLOAT=2,engine_Engine.TEXTURETYPE_BYTE=3,engine_Engine.TEXTURETYPE_SHORT=4,engine_Engine.TEXTURETYPE_UNSIGNED_SHORT=5,engine_Engine.TEXTURETYPE_INT=6,engine_Engine.TEXTURETYPE_UNSIGNED_INTEGER=7,engine_Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,engine_Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,engine_Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,engine_Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,engine_Engine.TEXTURETYPE_UNSIGNED_INT_24_8=12,engine_Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,engine_Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,engine_Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,engine_Engine.TEXTURE_NEAREST_SAMPLINGMODE=1,engine_Engine.TEXTURE_BILINEAR_SAMPLINGMODE=2,engine_Engine.TEXTURE_TRILINEAR_SAMPLINGMODE=3,engine_Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,engine_Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,engine_Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,engine_Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,engine_Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,engine_Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,engine_Engine.TEXTURE_NEAREST_LINEAR=7,engine_Engine.TEXTURE_NEAREST_NEAREST=1,engine_Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,engine_Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,engine_Engine.TEXTURE_LINEAR_LINEAR=2,engine_Engine.TEXTURE_LINEAR_NEAREST=12,engine_Engine.TEXTURE_EXPLICIT_MODE=0,engine_Engine.TEXTURE_SPHERICAL_MODE=1,engine_Engine.TEXTURE_PLANAR_MODE=2,engine_Engine.TEXTURE_CUBIC_MODE=3,engine_Engine.TEXTURE_PROJECTION_MODE=4,engine_Engine.TEXTURE_SKYBOX_MODE=5,engine_Engine.TEXTURE_INVCUBIC_MODE=6,engine_Engine.TEXTURE_EQUIRECTANGULAR_MODE=7,engine_Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,engine_Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,engine_Engine.SCALEMODE_FLOOR=1,engine_Engine.SCALEMODE_NEAREST=2,engine_Engine.SCALEMODE_CEILING=3,engine_Engine._RescalePostProcessFactory=null,engine_Engine._RenderPassIdCounter=0;let N=math_vector_Matrix.Compose(math_vector_Vector3.One(),math_vector_Quaternion.FromEulerAngles(0,Math.PI,0),math_vector_Vector3.Zero());let transformNode_TransformNode=class transformNode_TransformNode extends node_Node{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&transformNode_TransformNode.BILLBOARDMODE_USE_POSITION)!=0,this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==transformNode_TransformNode.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 math_vector_Vector3(0,0,1),this._up=new math_vector_Vector3(0,1,0),this._right=new math_vector_Vector3(1,0,0),this._position=math_vector_Vector3.Zero(),this._rotation=math_vector_Vector3.Zero(),this._rotationQuaternion=null,this._scaling=math_vector_Vector3.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=transformNode_TransformNode.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=math_vector_Matrix.Zero(),this._usePivotMatrix=!1,this._absolutePosition=math_vector_Vector3.Zero(),this._absoluteScaling=math_vector_Vector3.Zero(),this._absoluteRotationQuaternion=math_vector_Quaternion.Identity(),this._pivotMatrix=math_vector_Matrix.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new observable_Observable,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 math_vector_Vector3.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return math_vector_Vector3.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return math_vector_Vector3.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._poseMatrix=e.clone(),this}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=math_vector_Matrix.Identity()),this._poseMatrix}_isSynchronized(){let e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===transformNode_TransformNode.BILLBOARDMODE_NONE&&!e.pivotMatrixUpdated&&!this._infiniteDistance&&!this._position._isDirty&&!this._scaling._isDirty&&(!this._rotationQuaternion||!this._rotationQuaternion._isDirty)&&!this._rotation._isDirty}_initCache(){super._initCache();let 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=math_vector_Matrix.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);for(let e of(r&&i&&i(this,r),this.getChildTransformNodes(!0)))e.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||math_vector_Quaternion.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){let t,i,r;if(!e)return this;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){let e=math_vector_TmpVectors.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),math_vector_Vector3.TransformCoordinatesFromFloatsToRef(t,i,r,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=math_vector_Vector3.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();let e=math_vector_TmpVectors.Matrix[0];return this._localMatrix.invertToRef(e),math_vector_Vector3.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=math_vector_Vector3.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=en.LOCAL){let a=transformNode_TransformNode._LookAtVectorCache,n=s===en.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(n,a),this.setDirection(a,t,i,r),s===en.WORLD&&this.parent){if(this.rotationQuaternion){let e=math_vector_TmpVectors.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);let t=math_vector_TmpVectors.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{let e=math_vector_TmpVectors.Quaternion[0];math_vector_Quaternion.FromEulerVectorToRef(this.rotation,e);let t=math_vector_TmpVectors.Matrix[0];e.toRotationMatrix(t);let i=math_vector_TmpVectors.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}}return this}getDirection(e){let t=math_vector_Vector3.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return math_vector_Vector3.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){let s=-Math.atan2(e.z,e.x)+Math.PI/2,a=Math.sqrt(e.x*e.x+e.z*e.z),n=-Math.atan2(e.y,a);return this.rotationQuaternion?math_vector_Quaternion.RotationYawPitchRollToRef(s+t,n+i,r,this.rotationQuaternion):(this.rotation.x=n+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=en.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);let i=this.getWorldMatrix();if(t==en.WORLD){let t=math_vector_TmpVectors.Matrix[0];i.invertToRef(t),e=math_vector_Vector3.TransformCoordinates(e,t)}return this.setPivotMatrix(math_vector_Matrix.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){let e=math_vector_Vector3.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(){let e=math_vector_Vector3.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),math_vector_Vector3.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(let t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;let r=math_vector_TmpVectors.Quaternion[0],s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[1],n=math_vector_TmpVectors.Matrix[1];math_vector_Matrix.IdentityToRef(n);let o=math_vector_TmpVectors.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=transformNode_TransformNode._TmpRotation,math_vector_Quaternion.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),math_vector_Matrix.ComposeToRef(this.scaling,l,this.position,o),this.parent&&o.multiplyToRef(this.parent.computeWorldMatrix(!0),o),e&&(e.computeWorldMatrix(!0).invertToRef(n),o.multiplyToRef(n,o)),o.decompose(a,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(a),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(math_vector_Matrix.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(!0),0>e.getFinalMatrix().determinant()&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(0>this.parent.getWorldMatrix().determinant()&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null):e&&(this.parent=this._currentParentWhenAttachingToBone),this}rotate(e,t,i){let r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==en.LOCAL){if(this.parent){let i=this.parent.getWorldMatrix(),r=math_vector_TmpVectors.Matrix[0];i.invertToRef(r),e=math_vector_Vector3.TransformNormal(e,r),0>i.determinant()&&(t*=-1)}(r=math_vector_Quaternion.RotationAxisToRef(e,t,transformNode_TransformNode._RotationAxisCache)).multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=math_vector_Quaternion.RotationAxisToRef(e,t,transformNode_TransformNode._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=math_vector_Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));let r=math_vector_TmpVectors.Vector3[0],s=math_vector_TmpVectors.Vector3[1],a=math_vector_TmpVectors.Vector3[2],n=math_vector_TmpVectors.Quaternion[0],o=math_vector_TmpVectors.Matrix[0],l=math_vector_TmpVectors.Matrix[1],h=math_vector_TmpVectors.Matrix[2],c=math_vector_TmpVectors.Matrix[3];return e.subtractToRef(this.position,r),math_vector_Matrix.TranslationToRef(r.x,r.y,r.z,o),math_vector_Matrix.TranslationToRef(-r.x,-r.y,-r.z,l),math_vector_Matrix.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(o,c),c.decompose(s,n,a),this.position.addInPlace(a),n.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){let r=e.scale(t);if(i&&i!==en.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(r));else{let e=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=math_vector_TmpVectors.Quaternion[1],math_vector_Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));let s=math_vector_TmpVectors.Quaternion[0];return math_vector_Quaternion.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==transformNode_TransformNode.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){let i;if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;let r=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===r||this.isSynchronized()))return this._currentRenderId=r,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();let s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=r,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;let a=this._getEffectiveParent(),n=transformNode_TransformNode._TmpScaling,o=this._position;if(this._infiniteDistance&&!this.parent&&t){let e=t.getWorldMatrix(),i=new math_vector_Vector3(e.m[12],e.m[13],e.m[14]);(o=transformNode_TransformNode._TmpTranslation).copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion){if(this._rotationQuaternion._isDirty=!1,i=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion){let e=this.rotation.lengthSquared();e&&(this._rotationQuaternion.multiplyInPlace(math_vector_Quaternion.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else i=transformNode_TransformNode._TmpRotation,math_vector_Quaternion.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,i);if(this._usePivotMatrix){let e=math_vector_TmpVectors.Matrix[1];math_vector_Matrix.ScalingToRef(n.x,n.y,n.z,e);let t=math_vector_TmpVectors.Matrix[0];i.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,math_vector_TmpVectors.Matrix[4]),math_vector_TmpVectors.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else math_vector_Matrix.ComposeToRef(n,i,o,this._localMatrix);if(a&&a.getWorldMatrix){if(e&&a.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),math_vector_TmpVectors.Matrix[7])}else math_vector_TmpVectors.Matrix[7].copyFrom(a.getWorldMatrix());let e=math_vector_TmpVectors.Vector3[5],t=math_vector_TmpVectors.Vector3[6],i=math_vector_TmpVectors.Quaternion[0];math_vector_TmpVectors.Matrix[7].decompose(t,i,e),math_vector_Matrix.ScalingToRef(t.x,t.y,t.z,math_vector_TmpVectors.Matrix[7]),math_vector_TmpVectors.Matrix[7].setTranslation(e),transformNode_TransformNode.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),math_vector_TmpVectors.Matrix[6]),math_vector_TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(a.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){let e=math_vector_TmpVectors.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),math_vector_TmpVectors.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&math_vector_TmpVectors.Matrix[1].multiplyToRef(N,math_vector_TmpVectors.Matrix[1]),math_vector_TmpVectors.Matrix[1].setTranslationFromFloats(0,0,0),math_vector_TmpVectors.Matrix[1].invertToRef(math_vector_TmpVectors.Matrix[0]),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_ALL)!==transformNode_TransformNode.BILLBOARDMODE_ALL){math_vector_TmpVectors.Matrix[0].decompose(void 0,math_vector_TmpVectors.Quaternion[0],void 0);let e=math_vector_TmpVectors.Vector3[1];math_vector_TmpVectors.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_X)!==transformNode_TransformNode.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_Y)!==transformNode_TransformNode.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_Z)!==transformNode_TransformNode.BILLBOARDMODE_Z&&(e.z=0),math_vector_Matrix.RotationYawPitchRollToRef(e.y,e.x,e.z,math_vector_TmpVectors.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(math_vector_TmpVectors.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){let e=math_vector_TmpVectors.Vector3[0];this._worldMatrix.getTranslationToRef(e);let i=t.globalPosition;this._worldMatrix.invertToRef(math_vector_TmpVectors.Matrix[1]);let r=math_vector_TmpVectors.Vector3[1];math_vector_Vector3.TransformCoordinatesToRef(i,math_vector_TmpVectors.Matrix[1],r),r.normalize();let s=-Math.atan2(r.z,r.x)+Math.PI/2,a=Math.sqrt(r.x*r.x+r.z*r.z),n=-Math.atan2(r.y,a);if(math_vector_Quaternion.RotationYawPitchRollToRef(s,n,0,math_vector_TmpVectors.Quaternion[0]),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_ALL)!==transformNode_TransformNode.BILLBOARDMODE_ALL){let e=math_vector_TmpVectors.Vector3[1];math_vector_TmpVectors.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_X)!==transformNode_TransformNode.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_Y)!==transformNode_TransformNode.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_Z)!==transformNode_TransformNode.BILLBOARDMODE_Z&&(e.z=0),math_vector_Matrix.RotationYawPitchRollToRef(e.y,e.x,e.z,math_vector_TmpVectors.Matrix[0])}else math_vector_Matrix.FromQuaternionToRef(math_vector_TmpVectors.Quaternion[0],math_vector_TmpVectors.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(math_vector_TmpVectors.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):a&&a._nonUniformScaling?this._updateNonUniformScalingState(a._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=math_vector_Matrix.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){let e=this.getChildren();for(let t=0;t<e.length;++t){let i=e[t];if(i){i.computeWorldMatrix();let e=math_vector_TmpVectors.Matrix[0];i._localMatrix.multiplyToRef(this._localMatrix,e);let t=math_vector_TmpVectors.Quaternion[0];e.decompose(i.scaling,t,i.position),i.rotationQuaternion?i.rotationQuaternion.copyFrom(t):t.toEulerAnglesToRef(i.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=math_vector_Quaternion.Identity()),this._worldMatrix=math_vector_Matrix.Identity()}_afterComputeWorldMatrix(){}registerAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this}unregisterAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this}getPositionInCameraSpace(e=null){return e||(e=this.getScene().activeCamera),math_vector_Vector3.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(e,t,i){let r=decorators_SerializationHelper.Clone(()=>new transformNode_TransformNode(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;i<t.length;i++){let s=t[i];s.clone&&s.clone(e+"."+s.name,r)}}return r}serialize(e){let t=decorators_SerializationHelper.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),t}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>new transformNode_TransformNode(e.name,t),e,t,i);return e.localMatrix?r.setPreTransformMatrix(math_vector_Matrix.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(math_vector_Matrix.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r}getChildTransformNodes(e,t){let i=[];return this._getDescendants(i,e,e=>(!t||t(e))&&e instanceof transformNode_TransformNode),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){let e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){let e=this.getChildTransformNodes(!0);for(let t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));let a=this.getHierarchyBoundingVectors(e,i),n=a.max.subtract(a.min),o=Math.max(n.x,n.y,n.z);return 0===o||(this.scaling.scaleInPlace(1/o),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r))),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}};transformNode_TransformNode.BILLBOARDMODE_NONE=0,transformNode_TransformNode.BILLBOARDMODE_X=1,transformNode_TransformNode.BILLBOARDMODE_Y=2,transformNode_TransformNode.BILLBOARDMODE_Z=4,transformNode_TransformNode.BILLBOARDMODE_ALL=7,transformNode_TransformNode.BILLBOARDMODE_USE_POSITION=128,transformNode_TransformNode.BillboardUseParentOrientation=!1,transformNode_TransformNode._TmpRotation=math_vector_Quaternion.Zero(),transformNode_TransformNode._TmpScaling=math_vector_Vector3.Zero(),transformNode_TransformNode._TmpTranslation=math_vector_Vector3.Zero(),transformNode_TransformNode._LookAtVectorCache=new math_vector_Vector3(0,0,0),transformNode_TransformNode._RotationAxisCache=new math_vector_Quaternion,__decorate([serializeAsVector3("position")],transformNode_TransformNode.prototype,"_position",void 0),__decorate([serializeAsVector3("rotation")],transformNode_TransformNode.prototype,"_rotation",void 0),__decorate([serializeAsQuaternion("rotationQuaternion")],transformNode_TransformNode.prototype,"_rotationQuaternion",void 0),__decorate([serializeAsVector3("scaling")],transformNode_TransformNode.prototype,"_scaling",void 0),__decorate([serialize("billboardMode")],transformNode_TransformNode.prototype,"_billboardMode",void 0),__decorate([serialize()],transformNode_TransformNode.prototype,"scalingDeterminant",void 0),__decorate([serialize("infiniteDistance")],transformNode_TransformNode.prototype,"_infiniteDistance",void 0),__decorate([serialize()],transformNode_TransformNode.prototype,"ignoreNonUniformScaling",void 0),__decorate([serialize()],transformNode_TransformNode.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);let _MeshCollisionData=class _MeshCollisionData{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new math_vector_Vector3(0,0,0),this._diffPositionForCollisions=new math_vector_Vector3(0,0,0),this._collisionResponse=!0}};let _FacetDataStorage=class _FacetDataStorage{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=math_vector_Vector3.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}};let _InternalAbstractMeshDataInfo=class _InternalAbstractMeshDataInfo{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new _FacetDataStorage,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 _MeshCollisionData,this._enableDistantPicking=!1,this._rawBoundingInfo=null}};let abstractMesh_AbstractMesh=class abstractMesh_AbstractMesh extends transformNode_TransformNode{static get BILLBOARDMODE_NONE(){return transformNode_TransformNode.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return transformNode_TransformNode.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return transformNode_TransformNode.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return transformNode_TransformNode.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return transformNode_TransformNode.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return transformNode_TransformNode.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;let 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){let 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 _InternalAbstractMeshDataInfo,this._waitingMaterialId=null,this.cullingStrategy=abstractMesh_AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new observable_Observable,this.onCollisionPositionChangeObservable=new observable_Observable,this.onMaterialChangedObservable=new observable_Observable,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=math_color_Color3.Red(),this.outlineWidth=.02,this.overlayColor=math_color_Color3.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 math_vector_Vector3(.5,1,.5),this.ellipsoidOffset=new math_vector_Vector3(0,0,0),this.edgesWidth=1,this.edgesColor=new math_color_Color4(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=[],this._unIndexed=!1,this._lightSources=[],this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new observable_Observable,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>engine_Engine.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 UniformBuffer(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case ea.Aggressive:this.doNotSyncBoundingInfo=!0;case ea.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){let 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);let i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode]+", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==transformNode_TransformNode.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){return this.actionManager&&(t||this.actionManager.isRecursive)&&(!e||this.actionManager.hasSpecificTrigger(e))?this.actionManager: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(let e of this.subMeshes)e._rebuild()}_resyncLightSources(){for(let e of(this._lightSources.length=0,this.getScene().lights))e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){let t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(let e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){let i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(let t of this.subMeshes)for(let i=0;i<t._drawWrappers.length;++i){let r=t._drawWrappers[i];r&&r.defines&&r.defines.markAllAsDirty&&e(r.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty(t=>t.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(let t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,r){return this}updateVerticesData(e,t,i,r){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){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 boundingInfo_BoundingInfo(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(buffer_VertexBuffer.MatricesIndicesKind)&&this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===transformNode_TransformNode.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){let r=new math_vector_Matrix,s=this.rotationQuaternion?this.rotationQuaternion:math_vector_Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z);s.toRotationMatrix(r);let a=math_vector_Vector3.Zero(),n=this.definedFacingForward?-1:1;return math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,r,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){let r=this.definedFacingForward?1:-1;return new math_vector_Vector3(e*r,t,i*r)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){let i=extractMinAndMax(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new boundingInfo_BoundingInfo(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t<this.subMeshes.length;t++)this.subMeshes[t].refreshBoundingInfo(e);this._updateBoundingInfo()}_getData(e=!1,t=!1,i,r=buffer_VertexBuffer.PositionKind){if((i=null!=i?i:this.getVerticesData(r).slice())&&t&&this.morphTargetManager){let e=0,t=0;for(let s=0;s<i.length;s++){for(let e=0;e<this.morphTargetManager.numTargets;e++){let t=this.morphTargetManager.getTarget(e),r=t.influence;if(r>0){let e=t.getPositions();e&&(i[s]+=(e[s]-i[s])*r)}}if(e++,r===buffer_VertexBuffer.PositionKind&&this._positions&&3===e){e=0;let r=3*t;this._positions[t++].copyFromFloats(i[r],i[r+1],i[r+2])}}}if(i&&e&&this.skeleton){let e=this.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind),t=this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind);if(t&&e){let s=this.numBoneInfluencers>4,a=s?this.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind):null,n=s?this.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind):null,o=this.skeleton.getTransformMatrices(this),l=math_vector_TmpVectors.Vector3[0],h=math_vector_TmpVectors.Matrix[0],c=math_vector_TmpVectors.Matrix[1],u=0;for(let d=0;d<i.length;d+=3,u+=4){let _,p;for(h.reset(),_=0;_<4;_++)(p=t[u+_])>0&&(math_vector_Matrix.FromFloat32ArrayToRefScaled(o,Math.floor(16*e[u+_]),p,c),h.addToSelf(c));if(s)for(_=0;_<4;_++)(p=n[u+_])>0&&(math_vector_Matrix.FromFloat32ArrayToRefScaled(o,Math.floor(16*a[u+_]),p,c),h.addToSelf(c));r===buffer_VertexBuffer.NormalKind?math_vector_Vector3.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],h,l):math_vector_Vector3.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],h,l),l.toArray(i,d),r===buffer_VertexBuffer.PositionKind&&this._positions&&this._positions[d/3].copyFrom(l)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,buffer_VertexBuffer.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,buffer_VertexBuffer.PositionKind)}_getPositionData(e,t){var i;let r=this.getVerticesData(buffer_VertexBuffer.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),r&&(e&&this.skeleton||t&&this.morphTargetManager)){if(r=r.slice(),this._generatePointsArray(),this._positions){let e=this._positions;this._internalAbstractMeshDataInfo._positions=Array(e.length);for(let t=0;t<e.length;t++)this._internalAbstractMeshDataInfo._positions[t]=(null===(i=e[t])||void 0===i?void 0:i.clone())||new math_vector_Vector3}return this.getPositionData(e,t,r)}return r}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new boundingInfo_BoundingInfo(math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;let t=this.subMeshes.length;for(let i=0;i<t;i++){let r=this.subMeshes[i];(t>1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){let r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(let i of this.getChildMeshes())if(i.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){let t=this.getAbsolutePosition();t.addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);let i=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=i.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];let i=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let s=i;s<r;s++)e._lastColliderWorldVertices.push(math_vector_Vector3.TransformCoordinates(this._positions[s],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),(null===(r=e.getMaterial())||void 0===r?void 0:r.fillMode)===7),this}_processCollisionsForSubMeshes(e,t){let i=this._scene.getCollidingSubMeshCandidates(this,e),r=i.length;for(let s=0;s<r;s++){let a=i.data[s];(!(r>1)||a._checkCollision(e))&&this._collideForSubMesh(a,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;let t=math_vector_TmpVectors.Matrix[0],i=math_vector_TmpVectors.Matrix[1];return math_vector_Matrix.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,a=!1){let n=new PickingInfo,o=this.getClassName(),l="InstancedLinesMesh"===o||"LinesMesh"===o||"GreasedLineMesh"===o?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(h.boundingSphere,l)||!e.intersectsBox(h.boundingBox,l)))return n;if(r)return n.hit=!a,n.pickedMesh=a?null:this,n.distance=a?0:math_vector_Vector3.Distance(e.origin,h.boundingSphere.center),n.subMeshId=0,n;if(!this._generatePointsArray())return n;let c=null,u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length,_=!1;for(let e=0;e<d;e++){let t=u.data[e],i=t.getMaterial();if(i&&(7==i.fillMode||0==i.fillMode||1==i.fillMode||2==i.fillMode||4==i.fillMode)){_=!0;break}}if(!_)return n.hit=!0,n.pickedMesh=this,n.distance=math_vector_Vector3.Distance(e.origin,h.boundingSphere.center),n.subMeshId=-1,n;for(let r=0;r<d;r++){let s=u.data[r];if(d>1&&!s.canIntersects(e))continue;let a=s.intersects(e,this._positions,this.getIndices(),t,i);if(a&&(t||!c||a.distance<c.distance)&&((c=a).subMeshId=r,t))break}if(c){let t=null!=s?s:this.getWorldMatrix(),i=math_vector_TmpVectors.Vector3[0],r=math_vector_TmpVectors.Vector3[1];math_vector_Vector3.TransformCoordinatesToRef(e.origin,t,i),e.direction.scaleToRef(c.distance,r);let a=math_vector_Vector3.TransformNormal(r,t),o=a.addInPlace(i);n.hit=!0,n.distance=math_vector_Vector3.Distance(i,o),n.pickedPoint=o,n.pickedMesh=this,n.bu=c.bu||0,n.bv=c.bv||0,n.subMeshFaceId=c.faceId,n.faceId=c.faceId+u.data[c.subMeshId].indexStart/(-1!==this.getClassName().indexOf("LinesMesh")?2:3),n.subMeshId=c.subMeshId}return n}clone(e,t,i){return null}releaseSubMeshes(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=[];return this}dispose(e,t=!1){let i;let r=this.getScene();for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),r.freeActiveMeshes(),r.freeRenderingGroups(),r.renderingManager.maintainStateBetweenFrames&&r.renderingManager.restoreDispachedFlags(),void 0!==this.actionManager&&null!==this.actionManager&&(this._scene.meshes.some(e=>e!==this&&e.actionManager===this.actionManager)||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i<this._intersectionsInProgress.length;i++){let e=this._intersectionsInProgress[i],t=e._intersectionsInProgress.indexOf(this);e._intersectionsInProgress.splice(t,1)}this._intersectionsInProgress.length=0;let s=r.lights;s.forEach(e=>{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),-1!==(t=e.excludedMeshes.indexOf(this))&&e.excludedMeshes.splice(t,1);let i=e.getShadowGenerators();if(i){let e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){let e=i.value,r=e.getShadowMap();r&&r.renderList&&-1!==(t=r.renderList.indexOf(this))&&r.renderList.splice(t,1)}}}),("InstancedMesh"!==this.getClassName()||"InstancedLinesMesh"!==this.getClassName())&&this.releaseSubMeshes();let a=r.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,a.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),a.wipeCaches(),r.removeMesh(this),this._parentContainer){let e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i<r.particleSystems.length;i++)r.particleSystems[i].emitter===this&&(r.particleSystems[i].dispose(),i--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}_initFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=[]),e.facetPositions||(e.facetPositions=[]),e.facetPartitioning||(e.facetPartitioning=[]),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=math_vector_Vector3.Zero(),e.facetPositions[t]=math_vector_Vector3.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();let t=this.getVerticesData(buffer_VertexBuffer.PositionKind),i=this.getIndices(),r=this.getVerticesData(buffer_VertexBuffer.NormalKind),s=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,i instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(i);else if(i instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(i);else{let t=!1;for(let e=0;e<i.length;e++)if(i[e]>65535){t=!0;break}t?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){let t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:math_vector_Vector3.Zero()}e.depthSortedFacets=[];for(let t=0;t<e.facetNb;t++){let i={ind:3*t,sqDistance:0};e.depthSortedFacets.push(i)}e.invertedMatrix=math_vector_Matrix.Identity(),e.facetDepthSortOrigin=math_vector_Vector3.Zero()}e.bbSize.x=s.maximum.x-s.minimum.x>.001?s.maximum.x-s.minimum.x:.001,e.bbSize.y=s.maximum.y-s.minimum.y>.001?s.maximum.y-s.minimum.y:.001,e.bbSize.z=s.maximum.z-s.minimum.z>.001?s.maximum.z-s.minimum.z:.001;let a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),math_vector_Vector3.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&mesh_vertexData_VertexData.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);let t=e.depthSortedIndices.length/3|0;for(let r=0;r<t;r++){let t=e.depthSortedFacets[r].ind;e.depthSortedIndices[3*r]=i[t],e.depthSortedIndices[3*r+1]=i[t+1],e.depthSortedIndices[3*r+2]=i[t+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this}getFacetLocalNormals(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals}getFacetLocalPositions(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions}getFacetLocalPartitioning(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning}getFacetPosition(e){let t=math_vector_Vector3.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){let i=this.getFacetLocalPositions()[e],r=this.getWorldMatrix();return math_vector_Vector3.TransformCoordinatesToRef(i,r,t),this}getFacetNormal(e){let t=math_vector_Vector3.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){let i=this.getFacetLocalNormals()[e];return math_vector_Vector3.TransformNormalToRef(i,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,i){let r=this.getBoundingInfo(),s=this._internalAbstractMeshDataInfo._facetData,a=Math.floor((e-r.minimum.x*s.partitioningBBoxRatio)*s.subDiv.X*s.partitioningBBoxRatio/s.bbSize.x),n=Math.floor((t-r.minimum.y*s.partitioningBBoxRatio)*s.subDiv.Y*s.partitioningBBoxRatio/s.bbSize.y),o=Math.floor((i-r.minimum.z*s.partitioningBBoxRatio)*s.subDiv.Z*s.partitioningBBoxRatio/s.bbSize.z);return a<0||a>s.subDiv.max||n<0||n>s.subDiv.max||o<0||o>s.subDiv.max?null:s.facetPartitioning[a+s.subDiv.max*n+s.subDiv.max*s.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,a=!0){let n=this.getWorldMatrix(),o=math_vector_TmpVectors.Matrix[5];n.invertToRef(o);let l=math_vector_TmpVectors.Vector3[8];math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e,t,i,o,l);let h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,r,s,a);return r&&math_vector_Vector3.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,n,r),h}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,a=!0){let n,o,l,h=null,c=0,u=0,d=0,_=0,p=0,f=0,m=0,g=0,v=this.getFacetLocalPositions(),x=this.getFacetLocalNormals(),b=this.getFacetsAtLocalCoordinates(e,t,i);if(!b)return null;let T=Number.MAX_VALUE,S=T;for(let C=0;C<b.length;C++)o=x[n=b[C]],_=(e-(l=v[n]).x)*o.x+(t-l.y)*o.y+(i-l.z)*o.z,(!s||s&&a&&_>=0||s&&!a&&_<=0)&&(_=o.x*l.x+o.y*l.y+o.z*l.z,p=-(o.x*e+o.y*t+o.z*i-_)/(o.x*o.x+o.y*o.y+o.z*o.z),f=e+o.x*p,m=t+o.y*p,g=i+o.z*p,(S=(c=f-e)*c+(u=m-t)*u+(d=g-i)*d)<T&&(T=S,h=n,r&&(r.x=f,r.y=m,r.z=g)));return h}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=[],e.facetNormals=[],e.facetPartitioning=[],e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,i=!1){return this}createNormals(e){let t;let i=this.getVerticesData(buffer_VertexBuffer.PositionKind),r=this.getIndices();return t=this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)?this.getVerticesData(buffer_VertexBuffer.NormalKind):[],mesh_vertexData_VertexData.ComputeNormals(i,r,t,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(buffer_VertexBuffer.NormalKind,t,e),this}alignWithNormal(e,t){t||(t=math_axis_Axis.Y);let i=math_vector_TmpVectors.Vector3[0],r=math_vector_TmpVectors.Vector3[1];return math_vector_Vector3.CrossToRef(t,e,r),math_vector_Vector3.CrossToRef(e,r,i),this.rotationQuaternion?math_vector_Quaternion.RotationQuaternionFromAxisToRef(i,e,r,this.rotationQuaternion):math_vector_Vector3.RotationFromAxisToRef(i,e,r,this.rotation),this}_checkOcclusionQuery(){return!1}disableEdgesRendering(){throw _WarnImport("EdgesRenderer")}enableEdgesRendering(e,t,i){throw _WarnImport("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter(e=>e.emitter===this)}};function addClipPlaneUniforms(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 prepareStringDefinesForClipPlanes(e,t,i){var r,s,a,n,o,l;let h=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),c=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),u=!!(null!==(a=e.clipPlane3)&&void 0!==a?a:t.clipPlane3),d=!!(null!==(n=e.clipPlane4)&&void 0!==n?n:t.clipPlane4),_=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),p=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);h&&i.push("#define CLIPPLANE"),c&&i.push("#define CLIPPLANE2"),u&&i.push("#define CLIPPLANE3"),d&&i.push("#define CLIPPLANE4"),_&&i.push("#define CLIPPLANE5"),p&&i.push("#define CLIPPLANE6")}function prepareDefinesForClipPlanes(e,t,i){var r,s,a,n,o,l;let h=!1,c=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),u=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),d=!!(null!==(a=e.clipPlane3)&&void 0!==a?a:t.clipPlane3),_=!!(null!==(n=e.clipPlane4)&&void 0!==n?n:t.clipPlane4),p=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==c&&(i.CLIPPLANE=c,h=!0),i.CLIPPLANE2!==u&&(i.CLIPPLANE2=u,h=!0),i.CLIPPLANE3!==d&&(i.CLIPPLANE3=d,h=!0),i.CLIPPLANE4!==_&&(i.CLIPPLANE4=_,h=!0),i.CLIPPLANE5!==p&&(i.CLIPPLANE5=p,h=!0),i.CLIPPLANE6!==f&&(i.CLIPPLANE6=f,h=!0),h}function bindClipPlane(e,t,i){var r,s,a,n,o,l;let h=null!==(r=t.clipPlane)&&void 0!==r?r:i.clipPlane;setClipPlane(e,"vClipPlane",h),setClipPlane(e,"vClipPlane2",h=null!==(s=t.clipPlane2)&&void 0!==s?s:i.clipPlane2),setClipPlane(e,"vClipPlane3",h=null!==(a=t.clipPlane3)&&void 0!==a?a:i.clipPlane3),setClipPlane(e,"vClipPlane4",h=null!==(n=t.clipPlane4)&&void 0!==n?n:i.clipPlane4),setClipPlane(e,"vClipPlane5",h=null!==(o=t.clipPlane5)&&void 0!==o?o:i.clipPlane5),setClipPlane(e,"vClipPlane6",h=null!==(l=t.clipPlane6)&&void 0!==l?l:i.clipPlane6)}function setClipPlane(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}abstractMesh_AbstractMesh.OCCLUSION_TYPE_NONE=0,abstractMesh_AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC=1,abstractMesh_AbstractMesh.OCCLUSION_TYPE_STRICT=2,abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,abstractMesh_AbstractMesh.CULLINGSTRATEGY_STANDARD=0,abstractMesh_AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,abstractMesh_AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,abstractMesh_AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,h["BABYLON.AbstractMesh"]=abstractMesh_AbstractMesh;let MaterialHelper=class MaterialHelper{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}static BindTextureMatrix(e,t,i){let r=e.getTextureMatrix();t.updateMatrix(i+"Matrix",r)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==scene_Scene.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,r,s,a,n,o=!1){n._areMiscDirty&&(n.LOGARITHMICDEPTH=i,n.POINTSIZE=r,n.FOG=s&&this.GetFogState(e,t),n.NONUNIFORMSCALING=e.nonUniformScaling,n.ALPHATEST=a,n.DECAL_AFTER_DETAIL=o)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){let r=t.CAMERA_ORTHOGRAPHIC?1:0,s=t.CAMERA_PERSPECTIVE?1:0,a=e.activeCamera.mode===camera_Camera.ORTHOGRAPHIC_CAMERA?1:0,n=e.activeCamera.mode===camera_Camera.PERSPECTIVE_CAMERA?1:0;(r^a||s^n)&&(t.CAMERA_ORTHOGRAPHIC=1===a,t.CAMERA_PERSPECTIVE=1===n,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,r,s,a=null,n=!1){let o=MaterialHelper.PrepareDefinesForCamera(e,r);!1!==a&&(o=prepareDefinesForClipPlanes(i,e,r)),!t.getColorWrite()!==r.DEPTHPREPASS&&(r.DEPTHPREPASS=!r.DEPTHPREPASS,o=!0),r.INSTANCES!==s&&(r.INSTANCES=s,o=!0),r.THIN_INSTANCES!==n&&(r.THIN_INSTANCES=n,o=!0),o&&r.markAsUnprocessed()}static PrepareDefinesForBones(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;let i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;let r=e.getScene().prePassRenderer;if(r&&r.enabled){let i=-1===r.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(e,t){let i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,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){let i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!i&&!!i.isEnabled}static PrepareDefinesForAttributes(e,t,i,r,s=!1,a=!0,n=!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(buffer_VertexBuffer.NormalKind),t._needNormals&&e.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){let i=e.useVertexColors&&e.isVerticesDataPresent(buffer_VertexBuffer.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&a}return e.isVerticesDataPresent(buffer_VertexBuffer.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),r&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),n&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){let i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){let r=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(r!==t.ORDER_INDEPENDENT_TRANSPARENCY||s!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){let r=t.PREPASS;if(!t._arePrePassDirty)return;let 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,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i<s.length;i++){let r=e.prePassRenderer.getIndex(s[i].type);-1!==r?(t[s[i].define]=!0,t[s[i].index]=r):t[s[i].define]=!1}}else{t.PREPASS=!1;for(let e=0;e<s.length;e++)t[s[e].define]=!1}t.PREPASS!=r&&(t.markAsUnprocessed(),t.markAsImageProcessingDirty())}static PrepareDefinesForLight(e,t,i,r,s,a,n){var o;switch(n.needNormals=!0,void 0===s["LIGHT"+r]&&(n.needRebuild=!0),s["LIGHT"+r]=!0,s["SPOTLIGHT"+r]=!1,s["HEMILIGHT"+r]=!1,s["POINTLIGHT"+r]=!1,s["DIRLIGHT"+r]=!1,i.prepareLightSpecificDefines(s,r),s["LIGHT_FALLOFF_PHYSICAL"+r]=!1,s["LIGHT_FALLOFF_GLTF"+r]=!1,s["LIGHT_FALLOFF_STANDARD"+r]=!1,i.falloffType){case LightConstants.FALLOFF_GLTF:s["LIGHT_FALLOFF_GLTF"+r]=!0;break;case LightConstants.FALLOFF_PHYSICAL:s["LIGHT_FALLOFF_PHYSICAL"+r]=!0;break;case LightConstants.FALLOFF_STANDARD:s["LIGHT_FALLOFF_STANDARD"+r]=!0}if(a&&!i.specular.equalsFloats(0,0,0)&&(n.specularEnabled=!0),s["SHADOW"+r]=!1,s["SHADOWCSM"+r]=!1,s["SHADOWCSMDEBUG"+r]=!1,s["SHADOWCSMNUM_CASCADES"+r]=!1,s["SHADOWCSMUSESHADOWMAXZ"+r]=!1,s["SHADOWCSMNOBLEND"+r]=!1,s["SHADOWCSM_RIGHTHANDED"+r]=!1,s["SHADOWPCF"+r]=!1,s["SHADOWPCSS"+r]=!1,s["SHADOWPOISSON"+r]=!1,s["SHADOWESM"+r]=!1,s["SHADOWCLOSEESM"+r]=!1,s["SHADOWCUBE"+r]=!1,s["SHADOWLOWQUALITY"+r]=!1,s["SHADOWMEDIUMQUALITY"+r]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){let t=null!==(o=i.getShadowGenerator(e.activeCamera))&&void 0!==o?o:i.getShadowGenerator();if(t){let e=t.getShadowMap();e&&e.renderList&&e.renderList.length>0&&(n.shadowEnabled=!0,t.prepareDefines(s,r))}}i.lightmapMode!=LightConstants.LIGHTMAP_DEFAULT?(n.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+r]=!0,s["LIGHTMAPNOSPECULAR"+r]=i.lightmapMode==LightConstants.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+r]=!1,s["LIGHTMAPNOSPECULAR"+r]=!1)}static PrepareDefinesForLights(e,t,i,r,s=4,a=!1){if(!i._areLightsDirty)return i._needNormals;let n=0,o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!a){for(let a of t.lightSources)if(this.PrepareDefinesForLight(e,t,a,n,i,r,o),++n===s)break}i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=n;e<s;e++)void 0!==i["LIGHT"+e]&&(i["LIGHT"+e]=!1,i["HEMILIGHT"+e]=!1,i["POINTLIGHT"+e]=!1,i["DIRLIGHT"+e]=!1,i["SPOTLIGHT"+e]=!1,i["SHADOW"+e]=!1,i["SHADOWCSM"+e]=!1,i["SHADOWCSMDEBUG"+e]=!1,i["SHADOWCSMNUM_CASCADES"+e]=!1,i["SHADOWCSMUSESHADOWMAXZ"+e]=!1,i["SHADOWCSMNOBLEND"+e]=!1,i["SHADOWCSM_RIGHTHANDED"+e]=!1,i["SHADOWPCF"+e]=!1,i["SHADOWPCSS"+e]=!1,i["SHADOWPOISSON"+e]=!1,i["SHADOWESM"+e]=!1,i["SHADOWCLOSEESM"+e]=!1,i["SHADOWCUBE"+e]=!1,i["SHADOWLOWQUALITY"+e]=!1,i["SHADOWMEDIUMQUALITY"+e]=!1);let l=e.getEngine().getCaps();return void 0===i.SHADOWFLOAT&&(o.needRebuild=!0),i.SHADOWFLOAT=o.shadowEnabled&&(l.textureFloatRender&&l.textureFloatLinearFiltering||l.textureHalfFloatRender&&l.textureHalfFloatLinearFiltering),i.LIGHTMAPEXCLUDED=o.lightmapMode,o.needRebuild&&i.rebuild(),o.needNormals}static PrepareUniformsAndSamplersForLight(e,t,i,r,s=null,a=!1){s&&s.push("Light"+e),!a&&(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),i.push("shadowSampler"+e),i.push("depthSampler"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),r&&(i.push("projectionLightSampler"+e),t.push("textureProjectionMatrix"+e)))}static PrepareUniformsAndSamplersList(e,t,i,r=4){let s;let a=null;e.uniformsNames?(s=e.uniformsNames,a=e.uniformBuffersNames,t=e.samplers,i=e.defines,r=e.maxSimultaneousLights||0):(s=e,t||(t=[]));for(let e=0;e<r&&i["LIGHT"+e];e++)this.PrepareUniformsAndSamplersForLight(e,s,t,i["PROJECTEDLIGHTTEXTURE"+e],a);i.NUM_MORPH_INFLUENCERS&&s.push("morphTargetInfluences"),i.BAKED_VERTEX_ANIMATION_TEXTURE&&(s.push("bakedVertexAnimationSettings"),s.push("bakedVertexAnimationTextureSizeInverted"),s.push("bakedVertexAnimationTime"),t.push("bakedVertexAnimationTexture"))}static HandleFallbacksForShadows(e,t,i=4,r=0){let s=0;for(let a=0;a<i&&e["LIGHT"+a];a++)a>0&&(s=r+a,t.addFallback(s,"LIGHT"+a)),!e.SHADOWS&&(e["SHADOW"+a]&&t.addFallback(r,"SHADOW"+a),e["SHADOWPCF"+a]&&t.addFallback(r,"SHADOWPCF"+a),e["SHADOWPCSS"+a]&&t.addFallback(r,"SHADOWPCSS"+a),e["SHADOWPOISSON"+a]&&t.addFallback(r,"SHADOWPOISSON"+a),e["SHADOWESM"+a]&&t.addFallback(r,"SHADOWESM"+a),e["SHADOWCLOSEESM"+a]&&t.addFallback(r,"SHADOWCLOSEESM"+a));return s++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){let r=i.NUM_MORPH_INFLUENCERS;if(r>0&&engineStore_EngineStore.LastCreatedEngine){let s=engineStore_EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs,a=t.morphTargetManager;if(null==a?void 0:a.isUsingTextureForTargets)return;let n=a&&a.supportsNormals&&i.NORMAL,o=a&&a.supportsTangents&&i.TANGENT,l=a&&a.supportsUVs&&i.UV1;for(let i=0;i<r;i++)e.push(buffer_VertexBuffer.PositionKind+i),n&&e.push(buffer_VertexBuffer.NormalKind+i),o&&e.push(buffer_VertexBuffer.TangentKind+i),l&&e.push(buffer_VertexBuffer.UVKind+"_"+i),e.length>s&&logger_Logger.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){let r=i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES;r&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,r){i.NUM_BONE_INFLUENCERS>0&&(r.addCPUSkinningFallback(0,t),e.push(buffer_VertexBuffer.MatricesIndicesKind),e.push(buffer_VertexBuffer.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(buffer_VertexBuffer.MatricesIndicesExtraKind),e.push(buffer_VertexBuffer.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(buffer_VertexBuffer.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,r,s,a=!0){e._bindLight(t,i,r,s,a)}static BindLights(e,t,i,r,s=4){let a=Math.min(t.lightSources.length,s);for(let s=0;s<a;s++){let a=t.lightSources[s];this.BindLight(a,s,e,i,"boolean"==typeof r?r:r.SPECULARTERM,t.receiveShadows)}}static BindFogParameters(e,t,i,r=!1){e.fogEnabled&&t.applyFog&&e.fogMode!==scene_Scene.FOGMODE_NONE&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),r?(e.fogColor.toLinearSpaceToRef(this._TempFogColor,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",this._TempFogColor)):i.setColor3("vFogColor",e.fogColor))}static BindBonesParameters(e,t,i){if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){let r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){let i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{let s=r.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]),MaterialHelper._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){let 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){let e=i.activeCamera;e.mode===camera_Camera.ORTHOGRAPHIC_CAMERA&&logger_Logger.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}};MaterialHelper._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},MaterialHelper._TempFogColor=math_color_Color3.Black();let MaterialStencilState=class MaterialStencilState{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){decorators_SerializationHelper.Clone(()=>e,this)}serialize(){return decorators_SerializationHelper.Serialize(this)}parse(e,t,i){decorators_SerializationHelper.Parse(()=>this,e,t,i)}};__decorate([serialize()],MaterialStencilState.prototype,"func",null),__decorate([serialize()],MaterialStencilState.prototype,"funcRef",null),__decorate([serialize()],MaterialStencilState.prototype,"funcMask",null),__decorate([serialize()],MaterialStencilState.prototype,"opStencilFail",null),__decorate([serialize()],MaterialStencilState.prototype,"opDepthFail",null),__decorate([serialize()],MaterialStencilState.prototype,"opStencilDepthPass",null),__decorate([serialize()],MaterialStencilState.prototype,"mask",null),__decorate([serialize()],MaterialStencilState.prototype,"enabled",null),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"}(ec||(ec={}));let material_Material=class material_Material{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;let t=this._alpha;this._alpha=e,(1===t||1===e)&&this.markAsDirty(material_Material.MiscDirtyFlag+material_Material.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(material_Material.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(material_Material.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 observable_Observable),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 observable_Observable),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new observable_Observable),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(material_Material.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(material_Material.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case material_Material.WireFrameFillMode:case material_Material.LineListDrawMode:case material_Material.LineLoopDrawMode:case material_Material.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?material_Material.WireFrameFillMode:material_Material.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case material_Material.PointFillMode:case material_Material.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?material_Material.PointFillMode:material_Material.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(material_Material.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 observable_Observable,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 MaterialStencilState,this._useUBO=!1,this._fillMode=material_Material.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=()=>void 0,this._callbackPluginEventIsReadyForSubMesh=()=>void 0,this._callbackPluginEventPrepareDefines=()=>void 0,this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>void 0,this._callbackPluginEventHardBindForSubMesh=()=>void 0,this._callbackPluginEventBindForSubMesh=()=>void 0,this._callbackPluginEventHasRenderTargetTextures=()=>void 0,this._callbackPluginEventFillRenderTargetTextures=()=>void 0,this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;let r=t||engineStore_EngineStore.LastCreatedScene;if(!r)return;this._scene=r,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||tools_Tools.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new drawWrapper_DrawWrapper(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=material_Material.ClockWiseSideOrientation:this.sideOrientation=material_Material.CounterClockWiseSideOrientation,this._uniformBuffer=new UniformBuffer(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),material_Material.OnEventObservable.notifyObservers(this,ec.Created)}toString(e){let t="Name: "+this.name;return t}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){let r=t.materialDefines;return!!r&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===material_Material.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===material_Material.MATERIAL_OPAQUE||this._transparencyMode===material_Material.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){let t=this.getScene().meshes;for(let i of t)if(i.subMeshes)for(let t of i.subMeshes)t.getMaterial()===this&&t.effect&&(t.effect._wasPreviouslyReady=!1,t.effect._wasPreviouslyUsingInstances=null,t.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(material_Material.AllDirtyFlag)}_preBind(e,t=null){let i=this._scene.getEngine(),r=null==t?this.sideOrientation:t,s=r===material_Material.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){let e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(ec.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){let r=i.effect;r&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1)}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,MaterialHelper.BindSceneUniformBuffer(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){let e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){let e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){let e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){if(this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction){let e=this._scene.getEngine();e.setDepthFunction(this._cachedDepthFunctionState)}if(this.disableDepthWrite){let e=this._scene.getEngine();e.setDepthWrite(this._cachedDepthWriteState)}if(this.disableColorWrite){let e=this._scene.getEngine();e.setColorWrite(this._cachedColorWriteState)}}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(ec.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(ec.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(ec.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){let i={};if(this._serializePlugins(i),material_Material._parsePlugins(i,e,this._scene,t),this.pluginManager)for(let t of this.pluginManager._plugins){let i=e.pluginManager.getPlugin(t.name);t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){let e=[];for(let t in this.meshMap){let i=this.meshMap[t];i&&e.push(i)}return e}{let e=this._scene.meshes;return e.filter(e=>e.material===this)}}forceCompilation(e,t,i,r){let s=Object.assign({clipPlane:!1,useInstances:!1},i),a=this.getScene(),n=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;let checkReady=()=>{if(!this._scene||!this._scene.getEngine())return;let i=a.clipPlane;if(s.clipPlane&&(a.clipPlane=new math_plane_Plane(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,a=null;if(e.subMeshes){let t=new subMesh_SubMesh(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()?a=t.effect.getCompilationError():(i=!1,setTimeout(checkReady,16)))}i&&(this.allowShaderHotSwapping=n,a&&r&&r(a),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=n,t&&t(this)):setTimeout(checkReady,16);s.clipPlane&&(a.clipPlane=i)};checkReady()}forceCompilationAsync(e,t){return new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,e=>{r(e)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(material_Material._DirtyCallbackArray.length=0,e&material_Material.TextureDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._TextureDirtyCallBack),e&material_Material.LightDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._LightsDirtyCallBack),e&material_Material.FresnelDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._FresnelDirtyCallBack),e&material_Material.AttributesDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._AttributeDirtyCallBack),e&material_Material.MiscDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._MiscDirtyCallBack),e&material_Material.PrePassDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._PrePassDirtyCallBack),material_Material._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(material_Material._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){let e=this.getScene().meshes;for(let t of e)if(t.subMeshes)for(let e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let t=this.getScene().meshes;for(let i of t)if(i.subMeshes){for(let t of i.subMeshes)if(t.getMaterial(!1)===this)for(let 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;let e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(material_Material._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(material_Material._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(material_Material._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(material_Material._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(material_Material._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(material_Material._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(material_Material._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(material_Material._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(material_Material._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(material_Material._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==ea.BackwardCompatible){this.checkReadyOnlyOnce=!0;let e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){let r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(ec.Disposed,this._eventInfo),this._parentContainer){let e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i){if(this.meshMap)for(let t in this.meshMap){let i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{let t=r.meshes;for(let 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){let i=e.geometry;if(i){if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(let r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){let e=decorators_SerializationHelper.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(let 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 logger_Logger.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";let r=tools_Tools.Instantiate(e.customType),s=r.Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _parsePlugins(e,t,i,r){var s;if(e.plugins)for(let a in e.plugins){let n=e.plugins[a],o=null===(s=t.pluginManager)||void 0===s?void 0:s.getPlugin(n.name);if(!o){let e=tools_Tools.Instantiate("BABYLON."+a);e&&(o=new e(t))}null==o||o.parse(n,i,r)}}};material_Material.TriangleFillMode=0,material_Material.WireFrameFillMode=1,material_Material.PointFillMode=2,material_Material.PointListDrawMode=3,material_Material.LineListDrawMode=4,material_Material.LineLoopDrawMode=5,material_Material.LineStripDrawMode=6,material_Material.TriangleStripDrawMode=7,material_Material.TriangleFanDrawMode=8,material_Material.ClockWiseSideOrientation=0,material_Material.CounterClockWiseSideOrientation=1,material_Material.TextureDirtyFlag=1,material_Material.LightDirtyFlag=2,material_Material.FresnelDirtyFlag=4,material_Material.AttributesDirtyFlag=8,material_Material.MiscDirtyFlag=16,material_Material.PrePassDirtyFlag=32,material_Material.AllDirtyFlag=63,material_Material.MATERIAL_OPAQUE=0,material_Material.MATERIAL_ALPHATEST=1,material_Material.MATERIAL_ALPHABLEND=2,material_Material.MATERIAL_ALPHATESTANDBLEND=3,material_Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,material_Material.MATERIAL_NORMALBLENDMETHOD_RNM=1,material_Material.OnEventObservable=new observable_Observable,material_Material._AllDirtyCallBack=e=>e.markAllAsDirty(),material_Material._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),material_Material._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),material_Material._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),material_Material._MiscDirtyCallBack=e=>e.markAsMiscDirty(),material_Material._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),material_Material._LightsDirtyCallBack=e=>e.markAsLightDirty(),material_Material._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),material_Material._FresnelAndMiscDirtyCallBack=e=>{material_Material._FresnelDirtyCallBack(e),material_Material._MiscDirtyCallBack(e)},material_Material._TextureAndMiscDirtyCallBack=e=>{material_Material._TextureDirtyCallBack(e),material_Material._MiscDirtyCallBack(e)},material_Material._DirtyCallbackArray=[],material_Material._RunDirtyCallBacks=e=>{for(let t of material_Material._DirtyCallbackArray)t(e)},__decorate([serialize()],material_Material.prototype,"id",void 0),__decorate([serialize()],material_Material.prototype,"uniqueId",void 0),__decorate([serialize()],material_Material.prototype,"name",void 0),__decorate([serialize()],material_Material.prototype,"metadata",void 0),__decorate([serialize()],material_Material.prototype,"checkReadyOnEveryCall",void 0),__decorate([serialize()],material_Material.prototype,"checkReadyOnlyOnce",void 0),__decorate([serialize()],material_Material.prototype,"state",void 0),__decorate([serialize("alpha")],material_Material.prototype,"_alpha",void 0),__decorate([serialize("backFaceCulling")],material_Material.prototype,"_backFaceCulling",void 0),__decorate([serialize("cullBackFaces")],material_Material.prototype,"_cullBackFaces",void 0),__decorate([serialize()],material_Material.prototype,"sideOrientation",void 0),__decorate([serialize("alphaMode")],material_Material.prototype,"_alphaMode",void 0),__decorate([serialize()],material_Material.prototype,"_needDepthPrePass",void 0),__decorate([serialize()],material_Material.prototype,"disableDepthWrite",void 0),__decorate([serialize()],material_Material.prototype,"disableColorWrite",void 0),__decorate([serialize()],material_Material.prototype,"forceDepthWrite",void 0),__decorate([serialize()],material_Material.prototype,"depthFunction",void 0),__decorate([serialize()],material_Material.prototype,"separateCullingPass",void 0),__decorate([serialize("fogEnabled")],material_Material.prototype,"_fogEnabled",void 0),__decorate([serialize()],material_Material.prototype,"pointSize",void 0),__decorate([serialize()],material_Material.prototype,"zOffset",void 0),__decorate([serialize()],material_Material.prototype,"zOffsetUnits",void 0),__decorate([serialize()],material_Material.prototype,"pointsCloud",null),__decorate([serialize()],material_Material.prototype,"fillMode",null),__decorate([serialize()],material_Material.prototype,"transparencyMode",null);let multiMaterial_MultiMaterial=class multiMaterial_MultiMaterial extends material_Material{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._markAllSubMeshesAsTexturesDirty(),s}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i<this.subMaterials.length;i++)if(null===(t=this.subMaterials[i])||void 0===t?void 0:t.hasTexture(e))return!0;return!1}getClassName(){return"MultiMaterial"}isReadyForSubMesh(e,t,i){for(let r=0;r<this.subMaterials.length;r++){let s=this.subMaterials[r];if(s){if(s._storeEffectOnSubMeshes){if(!s.isReadyForSubMesh(e,t,i))return!1;continue}if(!s.isReady(e))return!1}}return!0}clone(e,t){let i=new multiMaterial_MultiMaterial(e,this.getScene());for(let r=0;r<this.subMaterials.length;r++){let s=null,a=this.subMaterials[r];s=t&&a?a.clone(e+"-"+a.name):this.subMaterials[r],i.subMaterials.push(s)}return i}serialize(){let e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,Tags&&(e.tags=Tags.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){let i=this.subMaterials[t];i?(e.materialsUniqueIds.push(i.uniqueId),e.materials.push(i.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,i){let r=this.getScene();if(!r)return;if(i)for(let i=0;i<this.subMaterials.length;i++){let r=this.subMaterials[i];r&&r.dispose(e,t)}let s=r.multiMaterials.indexOf(this);s>=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){let i=new multiMaterial_MultiMaterial(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Tags&&Tags.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(e=>i.subMaterials.push(t.getLastMaterialById(e))),i}};h["BABYLON.MultiMaterial"]=multiMaterial_MultiMaterial;let MeshLODLevel=class MeshLODLevel{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}};let _CreationDataStorage=class _CreationDataStorage{};let _InstanceDataStorage=class _InstanceDataStorage{constructor(){this.visibleInstances={},this.batchCache=new _InstancesBatch,this.batchCacheReplacementModeInFrozenMode=new _InstancesBatch,this.instancesBufferSize=2048}};let _InstancesBatch=class _InstancesBatch{constructor(){this.mustReturn=!1,this.visibleInstances=[],this.renderSelf=[],this.hardwareInstancedRendering=[]}};let _ThinInstanceDataStorage=class _ThinInstanceDataStorage{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}};let _InternalMeshDataInfo=class _InternalMeshDataInfo{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=[],this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}};let mesh_Mesh=class mesh_Mesh extends abstractMesh_AbstractMesh{static _GetDefaultSideOrientation(e){return e||mesh_Mesh.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(buffer_VertexBuffer.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(buffer_VertexBuffer.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new observable_Observable),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new observable_Observable),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new observable_Observable),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new observable_Observable),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new observable_Observable),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){var e;return(null!==(e=this._thinInstanceDataStorage.instancesCount)&&void 0!==e?e:0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,r=null,s,a=!0){if(super(e,t),this._internalMeshDataInfo=new _InternalMeshDataInfo,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new _InstanceDataStorage,this._thinInstanceDataStorage=new _ThinInstanceDataStorage,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=mesh_Mesh.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},r){if(r._geometry&&r._geometry.applyToMesh(this),DeepCopier.DeepCopy(r,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=r,t.useClonedMeshMap&&(r._internalMeshDataInfo.meshMap||(r._internalMeshDataInfo.meshMap={}),r._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=r._originalBuilderSideOrientation,this._creationDataStorage=r._creationDataStorage,r._ranges){let e=r._ranges;for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(r.metadata&&r.metadata.clone?this.metadata=r.metadata.clone():this.metadata=r.metadata,this._internalMetadata=r._internalMetadata,Tags&&Tags.HasTags(r)&&Tags.AddTagsTo(this,Tags.GetTags(r,!0)),this.setEnabled(r.isEnabled(!1)),this.parent=r.parent,this.setPivotMatrix(r.getPivotMatrix()),this.id=e+"."+r.id,this.material=r.material,!s){let t=r.getDescendants(!0);for(let i=0;i<t.length;i++){let r=t[i];r.clone&&r.clone(e+"."+r.name,this)}}if(r.morphTargetManager&&(this.morphTargetManager=r.morphTargetManager),t.getPhysicsEngine){let e=t.getPhysicsEngine();if(a&&e){if(1===e.getPluginVersion()){let t=e.getImpostorForPhysicsObject(r);t&&(this.physicsImpostor=t.clone(this))}else 2===e.getPluginVersion()&&r.physicsBody&&r.physicsBody.clone(this)}}for(let e=0;e<t.particleSystems.length;e++){let i=t.particleSystems[e];i.emitter===r&&i.clone(i.name,this)}this.skeleton=r.skeleton,this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}null!==i&&(this.parent=i),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=e=>{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new observable_Observable(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){let r=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));for(let s of(r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r),this.getChildTransformNodes(!0)))"InstancedMesh"===s.getClassName()&&"Mesh"===r.getClassName()&&s.sourceMesh===this?s.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):s.instantiateHierarchy(r,t,i);return r}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices()+", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);if(e){if(this._geometry){let e=this.getIndices(),i=this.getVerticesData(buffer_VertexBuffer.PositionKind);i&&e&&(t+=", flat shading: "+(i.length/3===e.length?"YES":"NO"))}else t+=", flat shading: UNKNOWN"}return t}_unBindEffect(){for(let e of(super._unBindEffect(),this.instances))e._unBindEffect()}get hasLODLevels(){return this._internalMeshDataInfo._LODLevels.length>0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){let e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoverage<i.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>i.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return logger_Logger.Warn("You cannot use a mesh as LOD level twice"),this;let i=new MeshLODLevel(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){let t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++){let r=t._LODLevels[i];if(r.distanceOrScreenCoverage===e)return r.mesh}return null}removeLODLevel(e){let t=this._internalMeshDataInfo;for(let i=0;i<t._LODLevels.length;i++)t._LODLevels[i].mesh===e&&(t._LODLevels.splice(i,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){let i=this._internalMeshDataInfo;if(!i._LODLevels||0===i._LODLevels.length)return this;let r=t||this.getBoundingInfo().boundingSphere,s=e.mode===camera_Camera.ORTHOGRAPHIC_CAMERA?e.minZ:r.centerWorld.subtract(e.globalPosition).length(),a=s,n=1;if(i._useLODScreenCoverage){let t=e.screenArea,i=r.radiusWorld*e.minZ/s;a=(i=i*i*Math.PI)/t,n=-1}if(n*i._LODLevels[i._LODLevels.length-1].distanceOrScreenCoverage>n*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let e=0;e<i._LODLevels.length;e++){let t=i._LODLevels[e];if(n*t.distanceOrScreenCoverage<n*a){if(t.mesh){if(4===t.mesh.delayLoadState)return t.mesh._checkDelayState(),this;if(2===t.mesh.delayLoadState)return this;t.mesh._preActivate(),t.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,t.mesh),t.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return null===this._geometry||void 0===this._geometry?0:this._geometry.getTotalVertices()}getVerticesData(e,t,i,r){var s,a;if(!this._geometry)return null;let n=r?void 0:null===(a=null===(s=this._userInstancedBuffersStorage)||void 0===s?void 0:s.vertexBuffers[e])||void 0===a?void 0:a.getFloatData(this.instances.length+1,i||t&&1!==this._geometry.meshes.length);return n||(n=this._geometry.getVerticesData(e,t,i)),n}getVertexBuffer(e,t){var i,r;return this._geometry?null!==(r=t?void 0:null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])&&void 0!==r?r:this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){var i;return this._geometry?!t&&(null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])!==void 0||this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}isVertexBufferUpdatable(e,t){var i;if(!this._geometry)return!!this._delayInfo&&-1!==this._delayInfo.indexOf(e);if(!t){let t=null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e];if(t)return t.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){let e=[];return this._delayInfo&&this._delayInfo.forEach(function(t){e.push(t)}),e}let t=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(let e in this._userInstancedBuffersStorage.vertexBuffers)-1===t.indexOf(e)&&t.push(e);return t}getTotalIndices(){return this._geometry?this._geometry.getTotalIndices():0}getIndices(e,t){return this._geometry?this._geometry.getIndices(e,t):[]}get isBlocked(){return null!==this._masterMesh&&void 0!==this._masterMesh}isReady(e=!1,t=!1){var i,r,s,a,n,o,l;if(2===this.delayLoadState||!super.isReady(e))return!1;if(!this.subMeshes||0===this.subMeshes.length||!e)return!0;let h=this.getEngine(),c=this.getScene(),u=t||h.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();let d=this.material||c.defaultMaterial;if(d){if(d._storeEffectOnSubMeshes)for(let e of this.subMeshes){let t=e.getMaterial();if(t){if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,u))return!1}else if(!t.isReady(this,u))return!1}}else if(!d.isReady(this,u))return!1}let _=h.currentRenderPassId;for(let e of this.lightSources){let t=e.getShadowGenerators();if(!t)continue;let c=t.values();for(let e=c.next();!0!==e.done;e=c.next()){let t=e.value;if(t&&(!(null===(i=t.getShadowMap())||void 0===i?void 0:i.renderList)||(null===(r=t.getShadowMap())||void 0===r?void 0:r.renderList)&&(null===(a=null===(s=t.getShadowMap())||void 0===s?void 0:s.renderList)||void 0===a?void 0:a.indexOf(this))!==-1)){let e=t.getShadowMap(),i=null!==(n=e.renderPassIds)&&void 0!==n?n:[h.currentRenderPassId];for(let e=0;e<i.length;++e)for(let r of(h.currentRenderPassId=i[e],this.subMeshes))if(!t.isReady(r,u,null!==(l=null===(o=r.getMaterial())||void 0===o?void 0:o.needAlphaBlendingForMesh(this))&&void 0!==l&&l))return h.currentRenderPassId=_,!1;h.currentRenderPassId=_}}}for(let e of this._internalMeshDataInfo._LODLevels)if(e.mesh&&!e.mesh.isReady(u))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_preActivate(){let e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t||(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null),this}_preActivateForIntermediateRendering(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(void 0!==this._instanceDataStorage.previousRenderId&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=t,this._instanceDataStorage.visibleInstances[t]=[]),this._instanceDataStorage.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getPositionData(e,t),i),this}_createGlobalSubMesh(e){let t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){let i=this.getIndices();if(!i)return null;let r=i.length,s=!1;if(e)s=!0;else for(let e of this.subMeshes)if(e.indexStart+e.indexCount>r||e.verticesStart+e.verticesCount>t){s=!0;break}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new subMesh_SubMesh(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;let t=this.getTotalIndices(),i=t/e|0,r=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let s=0;s<e&&!(r>=t);s++)subMesh_SubMesh.CreateFromIndices(0,r,s===e-1?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,r){if(this._geometry)this._geometry.setVerticesData(e,t,i,r);else{let r=new mesh_vertexData_VertexData;r.set(t,e);let s=this.getScene();new Geometry(Geometry.RandomId(),s,r,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){let i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=Geometry.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,r){return this._geometry&&(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i)),this}updateMeshPositions(e,t=!0){let i=this.getVerticesData(buffer_VertexBuffer.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(buffer_VertexBuffer.PositionKind,i,!1,!1),t){let e=this.getIndices(),t=this.getVerticesData(buffer_VertexBuffer.NormalKind);if(!t)return this;mesh_vertexData_VertexData.ComputeNormals(i,e,t),this.updateVerticesData(buffer_VertexBuffer.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry||1===this._geometry.meshes.length)return this;let e=this._geometry,t=this._geometry.copy(Geometry.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{let t=new mesh_vertexData_VertexData;t.indices=e;let r=this.getScene();new Geometry(Geometry.RandomId(),r,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry&&this._geometry.updateIndices(e,t,i),this}toLeftHanded(){return this._geometry&&this._geometry.toLeftHanded(),this}_bind(e,t,i,r=!0){let s;if(!this._geometry)return this;let a=this.getScene().getEngine();if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)s=null;else switch(this._getRenderingFillMode(i)){case material_Material.PointFillMode:s=null;break;case material_Material.WireFrameFillMode:s=e._getLinesIndexBuffer(this.getIndices(),a);break;default:case material_Material.TriangleFillMode:s=this._geometry.getIndexBuffer()}return r&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,s,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,s),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);let r=this.getScene(),s=r.getEngine();return this._unIndexed||t==material_Material.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==material_Material.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}let i=this.getScene(),r=i._isInIntermediateRendering(),s=r?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=this._instanceDataStorage.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!s&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){let t=this._instanceDataStorage.visibleInstances,s=i.getRenderId(),n=r?t.intermediateDefaultRenderId:t.defaultRenderId;a.visibleInstances[e]=t[s],!a.visibleInstances[e]&&n&&(a.visibleInstances[e]=t[n])}return a.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==a.visibleInstances[e]&&void 0!==a.visibleInstances[e],this._instanceDataStorage.previousBatch=a,a}_renderWithInstances(e,t,i,r,s){var a;let n=i.visibleInstances[e._id],o=n?n.length:0,l=this._instanceDataStorage,h=l.instancesBufferSize,c=l.instancesBuffer,u=l.instancesPreviousBuffer,d=64*(o+1);for(;l.instancesBufferSize<d;)l.instancesBufferSize*=2;l.instancesData&&h==l.instancesBufferSize||(l.instancesData=new Float32Array(l.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!l.instancesPreviousData||h!=l.instancesBufferSize)&&(l.instancesPreviousData=new Float32Array(l.instancesBufferSize/4));let _=0,p=0,f=i.renderSelf[e._id],m=!c||h!==l.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!l.instancesPreviousBuffer;if(this._instanceDataStorage.manualUpdate||l.isFrozen&&!m)p=(f?1:0)+o;else{let t=this.getWorldMatrix();if(f&&(this._scene.needsPreviousWorldMatrices&&(l.masterMeshPreviousWorldMatrix?(l.masterMeshPreviousWorldMatrix.copyToArray(l.instancesPreviousData,_),l.masterMeshPreviousWorldMatrix.copyFrom(t)):(l.masterMeshPreviousWorldMatrix=t.clone(),l.masterMeshPreviousWorldMatrix.copyToArray(l.instancesPreviousData,_))),t.copyToArray(l.instancesData,_),_+=16,p++),n){if(mesh_Mesh.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&(null===(a=e.getMaterial())||void 0===a?void 0:a.needAlphaBlendingForMesh(e.getRenderingMesh()))){let e=this._scene.activeCamera.globalPosition;for(let t=0;t<n.length;t++){let i=n[t];i._distanceToCamera=math_vector_Vector3.Distance(i.getBoundingInfo().boundingSphere.centerWorld,e)}n.sort((e,t)=>e._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera<t._distanceToCamera?1:0)}for(let e=0;e<n.length;e++){let t=n[e],i=t.getWorldMatrix();i.copyToArray(l.instancesData,_),this._scene.needsPreviousWorldMatrices&&(t._previousWorldMatrix?(t._previousWorldMatrix.copyToArray(l.instancesPreviousData,_),t._previousWorldMatrix.copyFrom(i)):(t._previousWorldMatrix=i.clone(),t._previousWorldMatrix.copyToArray(l.instancesPreviousData,_))),_+=16,p++}}}return m?(c&&c.dispose(),u&&u.dispose(),c=new Buffer(s,l.instancesData,!0,16,!1,!0),l.instancesBuffer=c,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=c.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=c.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=c.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=c.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(u=new Buffer(s,l.instancesPreviousData,!0,16,!1,!0),l.instancesPreviousBuffer=u,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=u.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=u.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=u.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=u.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&(c.updateDirectly(l.instancesData,0,p),this._scene.needsPreviousWorldMatrices&&(!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.previousManualUpdate)&&u.updateDirectly(l.instancesPreviousData,0,p)),this._processInstancedBuffers(n,f),this.getScene()._activeIndices.addCount(e.indexCount*p,!1),s._currentDrawContext&&(s._currentDrawContext.useInstancing=!0),this._bind(e,r,t),this._draw(e,t,p),this._scene.needsPreviousWorldMatrices&&!m&&this._instanceDataStorage.manualUpdate&&(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&!this._instanceDataStorage.previousManualUpdate&&u.updateDirectly(l.instancesData,0,p),s.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,i,r){var s,a;let n=null!==(a=null===(s=this._thinInstanceDataStorage)||void 0===s?void 0:s.instancesCount)&&void 0!==a?a:0;this.getScene()._activeIndices.addCount(e.indexCount*n,!1),r._currentDrawContext&&(r._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,n),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,n):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),r.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,i,r,s,a,n,o){let l=this.getScene(),h=l.getEngine();if(r=this._getRenderingFillMode(r),a&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,r,i,h),this;if(a)this._renderWithInstances(t,r,s,i,h);else{h._currentDrawContext&&(h._currentDrawContext.useInstancing=!1);let i=0;s.renderSelf[t._id]&&(n&&n(!1,e.getWorldMatrix(),o),i++,this._draw(t,r,this._instanceDataStorage.overridenInstanceCount));let a=s.visibleInstances[t._id];if(a){let e=a.length;i+=e;for(let i=0;i<e;i++){let e=a[i],s=e.getWorldMatrix();n&&n(!0,s,o),this._draw(t,r)}}l._activeIndices.addCount(t.indexCount*i,!1)}return this}_rebuild(e=!1){if(this._instanceDataStorage.instancesBuffer&&(e&&this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),this._userInstancedBuffersStorage){for(let t in this._userInstancedBuffersStorage.vertexBuffers){let i=this._userInstancedBuffersStorage.vertexBuffers[t];i&&(e&&i.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(e)}_freeze(){if(this.subMeshes){for(let e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}}_unFreeze(){this._instanceDataStorage.isFrozen=!1,this._instanceDataStorage.previousBatch=null}renderWithRenderPassId(e,t,i,r,s=!0){let a=this._scene.getEngine(),n=a.currentRenderPassId;if(void 0!==e&&(a.currentRenderPassId=e),r)(!s||s&&r.isInFrustum(this._scene._frustumPlanes))&&this.render(r,!!t,i);else for(let e=0;e<this.subMeshes.length;e++){let r=this.subMeshes[e];(!s||s&&r.isInFrustum(this._scene._frustumPlanes))&&this.render(r,!!t,i)}return void 0!==e&&(a.currentRenderPassId=n),this}render(e,t,i){var r,s,a,n,o;let l,h;let c=this.getScene();this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1;let u=null!==(s=null===(r=c.activeCameras)||void 0===r?void 0:r.length)&&void 0!==s?s:0,d=u>1&&c.activeCamera===c.activeCameras[0]||u<=1;if(d&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;let _=this._getInstancesRenderList(e._id,!!i);if(_.mustReturn||!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let p=c.getEngine(),f=0,m=null;this.ignoreCameraMaxZ&&c.activeCamera&&!c._isInIntermediateRendering()&&(f=c.activeCamera.maxZ,m=c.activeCamera,c.activeCamera.maxZ=0,c.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);let g=e.getRenderingMesh(),v=_.hardwareInstancedRendering[e._id]||g.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,x=this._instanceDataStorage,b=e.getMaterial();if(!b)return m&&(m.maxZ=f,c.updateTransformMatrix(!0)),this;if(x.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===b){if(b._storeEffectOnSubMeshes&&!(null===(a=e.effect)||void 0===a?void 0:a._wasPreviouslyReady)||!b._storeEffectOnSubMeshes&&!(null===(n=b.getEffect())||void 0===n?void 0:n._wasPreviouslyReady))return m&&(m.maxZ=f,c.updateTransformMatrix(!0)),this}else{if(b._storeEffectOnSubMeshes){if(!b.isReadyForSubMesh(this,e,v))return m&&(m.maxZ=f,c.updateTransformMatrix(!0)),this}else if(!b.isReady(this,v))return m&&(m.maxZ=f,c.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=b}t&&p.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),l=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();let T=null!==(o=null==l?void 0:l.effect)&&void 0!==o?o:null;for(let t of c._beforeRenderingMeshStage)t.action(this,e,_,T);if(!l||!T)return m&&(m.maxZ=f,c.updateTransformMatrix(!0)),this;let S=i||this;if(!x.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||null!==this.overrideMaterialSideOrientation)){let e=S._getWorldMatrixDeterminant();null==(h=this.overrideMaterialSideOrientation)&&(h=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(h=h===material_Material.ClockWiseSideOrientation?material_Material.CounterClockWiseSideOrientation:material_Material.ClockWiseSideOrientation),x.sideOrientation=h}else h=x.sideOrientation;let C=this._internalMeshDataInfo._effectiveMaterial._preBind(l,h);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&p.setDepthWrite(!0);let E=this._internalMeshDataInfo._effectiveMaterial,y=E.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),v||this._bind(e,T,y,!1);let R=S.getWorldMatrix();for(let t of(E._storeEffectOnSubMeshes?E.bindForSubMesh(R,this,e):E.bind(R,this),!E.backFaceCulling&&E.separateCullingPass&&(p.setState(!0,E.zOffset,!1,!C,E.cullBackFaces,E.stencil,E.zOffsetUnits),this._processRendering(this,e,T,y,_,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),p.setState(!0,E.zOffset,!1,C,E.cullBackFaces,E.stencil,E.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,T,y,_,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind(),c._afterRenderingMeshStage))t.action(this,e,_,T);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),m&&(m.maxZ=f,c.updateTransformMatrix(!0)),c.performancePriority!==ea.Aggressive||x.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)&&(this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){let e=this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind),t=e.length;for(let i=0;i<t;i+=4){let t=e[i]+e[i+1]+e[i+2]+e[i+3];if(0===t)e[i]=1;else{let r=1/t;e[i]*=r,e[i+1]*=r,e[i+2]*=r,e[i+3]*=r}}this.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){let e=this.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind),t=this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind),i=t.length;for(let r=0;r<i;r+=4){let i=t[r]+t[r+1]+t[r+2]+t[r+3];if(0===(i+=e[r]+e[r+1]+e[r+2]+e[r+3]))t[r]=1;else{let s=1/i;t[r]*=s,t[r+1]*=s,t[r+2]*=s,t[r+3]*=s,e[r]*=s,e[r+1]*=s,e[r+2]*=s,e[r+3]*=s}}this.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,t),this.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,e)}validateSkinning(){let e=this.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind),t=this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind);if(null===t||null==this.skeleton)return{skinned:!1,valid:!0,report:"not skinned"};let i=t.length,r=0,s=0,a=0,n=0,o=null===e?4:8,l=[];for(let e=0;e<=o;e++)l[e]=0;for(let h=0;h<i;h+=4){let i=t[h],c=i,u=0===c?0:1;for(let s=1;s<o;s++){let a=s<4?t[h+s]:e[h+s-4];a>i&&r++,0!==a&&u++,c+=a,i=a}if(l[u]++,u>a&&(a=u),0===c)s++;else{let i=1/c,r=0;for(let s=0;s<o;s++)s<4?r+=Math.abs(t[h+s]-t[h+s]*i):r+=Math.abs(e[h+s-4]-e[h+s-4]*i);r>.001&&n++}}let h=this.skeleton.bones.length,c=this.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind),u=this.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind),d=0;for(let e=0;e<i;e+=4)for(let t=0;t<o;t++){let i=t<4?c[e+t]:u[e+t-4];(i>=h||i<0)&&d++}let _="Number of Weights = "+i/4+"\nMaximum influences = "+a+"\nMissing Weights = "+s+"\nNot Sorted = "+r+"\nNot Normalized = "+n+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d;return{skinned:!0,valid:0===s&&0===n&&0===d,report:_}}_checkDelayState(){let e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);let t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return tools_Tools.LoadFile(this.delayLoadingFile,t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach(e=>{e.refreshBoundingInfo(),e._syncSubMeshes()}),this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return!!(2!==this.delayLoadState&&super.isInFrustum(e))&&(this._checkDelayState(),!0)}setMaterialById(e){let t;let i=this.getScene().materials;for(t=i.length-1;t>-1;t--)if(i[t].id===e)return this.material=i[t],this;let r=this.getScene().multiMaterials;for(t=r.length-1;t>-1;t--)if(r[t].id===e){this.material=r[t];break}return this}getAnimatables(){let e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){let t;if(!this.isVerticesDataPresent(buffer_VertexBuffer.PositionKind))return this;let i=this.subMeshes.splice(0);this._resetPointsArrayCache();let r=this.getVerticesData(buffer_VertexBuffer.PositionKind),s=math_vector_Vector3.Zero();for(t=0;t<r.length;t+=3)math_vector_Vector3.TransformCoordinatesFromFloatsToRef(r[t],r[t+1],r[t+2],e,s).toArray(r,t);if(this.setVerticesData(buffer_VertexBuffer.PositionKind,r,this.getVertexBuffer(buffer_VertexBuffer.PositionKind).isUpdatable()),this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)){for(t=0,r=this.getVerticesData(buffer_VertexBuffer.NormalKind);t<r.length;t+=3)math_vector_Vector3.TransformNormalFromFloatsToRef(r[t],r[t+1],r[t+2],e,s).normalize().toArray(r,t);this.setVerticesData(buffer_VertexBuffer.NormalKind,r,this.getVertexBuffer(buffer_VertexBuffer.NormalKind).isUpdatable())}return 0>e.determinant()&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=i,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions?this._internalAbstractMeshDataInfo._positions:this._geometry?this._geometry._positions:null}_resetPointsArrayCache(){return this._geometry&&this._geometry._resetPointsArrayCache(),this}_generatePointsArray(){return!!this._geometry&&this._geometry._generatePointsArray()}clone(e="",t=null,i,r=!0){return new mesh_Mesh(e,this.getScene(),t,this,i,r)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);let i=this._internalMeshDataInfo;if(i._onBeforeDrawObservable&&i._onBeforeDrawObservable.clear(),i._onBeforeBindObservable&&i._onBeforeBindObservable.clear(),i._onBeforeRenderObservable&&i._onBeforeRenderObservable.clear(),i._onAfterRenderObservable&&i._onAfterRenderObservable.clear(),i._onBetweenPassObservable&&i._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(i.meshMap)for(let e in i.meshMap){let t=i.meshMap[e];t&&(t._internalMeshDataInfo._source=null,i.meshMap[e]=void 0)}i._source&&i._source._internalMeshDataInfo.meshMap&&(i._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{let e=this.getScene().meshes;for(let t of e)t._internalMeshDataInfo&&t._internalMeshDataInfo._source&&t._internalMeshDataInfo._source===this&&(t._internalMeshDataInfo._source=null)}i._source=null,this._instanceDataStorage.visibleInstances={},this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,i,r,s,a,n=!1){let o=this.getScene();return tools_Tools.LoadImage(e,e=>{let o=e.width,l=e.height,h=this.getEngine().createCanvas(o,l),c=h.getContext("2d");c.drawImage(e,0,0);let u=c.getImageData(0,0,o,l).data;this.applyDisplacementMapFromBuffer(u,o,l,t,i,s,a,n),r&&r(this)},()=>{},o.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,r,s,a,n,o=!1){if(!this.isVerticesDataPresent(buffer_VertexBuffer.PositionKind)||!this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)||!this.isVerticesDataPresent(buffer_VertexBuffer.UVKind))return logger_Logger.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;let l=this.getVerticesData(buffer_VertexBuffer.PositionKind,!0,!0),h=this.getVerticesData(buffer_VertexBuffer.NormalKind),c=this.getVerticesData(buffer_VertexBuffer.UVKind),u=math_vector_Vector3.Zero(),d=math_vector_Vector3.Zero(),_=math_vector_Vector2.Zero();a=a||math_vector_Vector2.Zero(),n=n||new math_vector_Vector2(1,1);for(let o=0;o<l.length;o+=3){math_vector_Vector3.FromArrayToRef(l,o,u),math_vector_Vector3.FromArrayToRef(h,o,d),math_vector_Vector2.FromArrayToRef(c,o/3*2,_);let p=Math.abs(_.x*n.x+a.x%1)*(t-1)%t|0,f=Math.abs(_.y*n.y+a.y%1)*(i-1)%i|0,m=(p+f*t)*4,g=e[m]/255,v=e[m+1]/255,x=e[m+2]/255,b=.3*g+.59*v+.11*x;d.normalize(),d.scaleInPlace(r+(s-r)*b),(u=u.add(d)).toArray(l,o)}return mesh_vertexData_VertexData.ComputeNormals(l,this.getIndices(),h),o?(this.setVerticesData(buffer_VertexBuffer.PositionKind,l),this.setVerticesData(buffer_VertexBuffer.NormalKind,h),this.setVerticesData(buffer_VertexBuffer.UVKind,c)):(this.updateVerticesData(buffer_VertexBuffer.PositionKind,l),this.updateVerticesData(buffer_VertexBuffer.NormalKind,h)),this}_getFlattenedNormals(e,t){let i=new Float32Array(3*e.length),r=0,s=this.overrideMaterialSideOrientation===(this._scene.useRightHandedSystem?1:0);for(let a=0;a<e.length;a+=3){let n=math_vector_Vector3.FromArray(t,3*e[a]),o=math_vector_Vector3.FromArray(t,3*e[a+1]),l=math_vector_Vector3.FromArray(t,3*e[a+2]),h=n.subtract(o),c=l.subtract(o),u=math_vector_Vector3.Normalize(math_vector_Vector3.Cross(h,c));s&&u.scaleInPlace(-1);for(let e=0;e<3;e++)i[r++]=u.x,i[r++]=u.y,i[r++]=u.z}return i}_convertToUnIndexedMesh(e=!1){let t=this.getVerticesDataKinds(),i=this.getIndices(),r={},separateVertices=(e,t)=>{let r=new Float32Array(i.length*t),s=0;for(let a=0;a<i.length;a++)for(let n=0;n<t;n++)r[s++]=e[i[a]*t+n];return r},s=this.geometry?this.subMeshes.slice(0):[];for(let e of t)r[e]=this.getVerticesData(e);for(let s of t){let t=this.getVertexBuffer(s),a=t.getStrideSize();if(e&&s===buffer_VertexBuffer.NormalKind){let e=this._getFlattenedNormals(i,r[buffer_VertexBuffer.PositionKind]);this.setVerticesData(buffer_VertexBuffer.NormalKind,e,t.isUpdatable(),a)}else this.setVerticesData(s,separateVertices(r[s],a),t.isUpdatable(),a)}if(this.morphTargetManager){for(let t=0;t<this.morphTargetManager.numTargets;t++){let r=this.morphTargetManager.getTarget(t),s=r.getPositions();r.setPositions(separateVertices(s,3));let a=r.getNormals();a&&r.setNormals(e?this._getFlattenedNormals(i,s):separateVertices(a,3));let n=r.getTangents();n&&r.setTangents(separateVertices(n,3));let o=r.getUVs();o&&r.setUVs(separateVertices(o,2))}this.morphTargetManager.synchronize()}for(let e=0;e<i.length;e++)i[e]=e;for(let e of(this.setIndices(i),this._unIndexed=!0,this.releaseSubMeshes(),s))subMesh_SubMesh.AddToMesh(e.materialIndex,e.indexStart,e.indexCount,e.indexStart,e.indexCount,this);return this.synchronizeInstances(),this}convertToFlatShadedMesh(){return this._convertToUnIndexedMesh(!0)}convertToUnIndexedMesh(){return this._convertToUnIndexedMesh()}flipFaces(e=!1){let t;let i=mesh_vertexData_VertexData.ExtractFromMesh(this);if(e&&this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)&&i.normals)for(t=0;t<i.normals.length;t++)i.normals[t]*=-1;if(i.indices){let e;for(t=0;t<i.indices.length;t+=3)e=i.indices[t+1],i.indices[t+1]=i.indices[t+2],i.indices[t+2]=e}return i.applyToMesh(this,this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind)),this}increaseVertices(e=1){let t=mesh_vertexData_VertexData.ExtractFromMesh(this),i=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,r=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,s=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,a=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(i&&r){let n,o,l,h,c;t.indices=i,t.positions=r,s&&(t.uvs=s),a&&(t.normals=a);let u=e+1,d=[];for(let e=0;e<u+1;e++)d[e]=[];let _=new math_vector_Vector3(0,0,0),p=new math_vector_Vector3(0,0,0),f=new math_vector_Vector2(0,0),m=[],g=[],v=[],x=r.length;s&&(h=s.length),a&&(c=a.length);for(let e=0;e<i.length;e+=3){g[0]=i[e],g[1]=i[e+1],g[2]=i[e+2];for(let e=0;e<3;e++)if(n=g[e],o=g[(e+1)%3],void 0===v[n]&&void 0===v[o]?(v[n]=[],v[o]=[]):(void 0===v[n]&&(v[n]=[]),void 0===v[o]&&(v[o]=[])),void 0===v[n][o]&&void 0===v[o][n]){v[n][o]=[],_.x=(r[3*o]-r[3*n])/u,_.y=(r[3*o+1]-r[3*n+1])/u,_.z=(r[3*o+2]-r[3*n+2])/u,a&&(p.x=(a[3*o]-a[3*n])/u,p.y=(a[3*o+1]-a[3*n+1])/u,p.z=(a[3*o+2]-a[3*n+2])/u),s&&(f.x=(s[2*o]-s[2*n])/u,f.y=(s[2*o+1]-s[2*n+1])/u),v[n][o].push(n);for(let e=1;e<u;e++)v[n][o].push(r.length/3),r[x++]=r[3*n]+e*_.x,r[x++]=r[3*n+1]+e*_.y,r[x++]=r[3*n+2]+e*_.z,a&&(a[c++]=a[3*n]+e*p.x,a[c++]=a[3*n+1]+e*p.y,a[c++]=a[3*n+2]+e*p.z),s&&(s[h++]=s[2*n]+e*f.x,s[h++]=s[2*n+1]+e*f.y);v[n][o].push(o),v[o][n]=[],l=v[n][o].length;for(let e=0;e<l;e++)v[o][n][e]=v[n][o][l-1-e]}d[0][0]=i[e],d[1][0]=v[i[e]][i[e+1]][1],d[1][1]=v[i[e]][i[e+2]][1];for(let t=2;t<u;t++){d[t][0]=v[i[e]][i[e+1]][t],d[t][t]=v[i[e]][i[e+2]][t],_.x=(r[3*d[t][t]]-r[3*d[t][0]])/t,_.y=(r[3*d[t][t]+1]-r[3*d[t][0]+1])/t,_.z=(r[3*d[t][t]+2]-r[3*d[t][0]+2])/t,a&&(p.x=(a[3*d[t][t]]-a[3*d[t][0]])/t,p.y=(a[3*d[t][t]+1]-a[3*d[t][0]+1])/t,p.z=(a[3*d[t][t]+2]-a[3*d[t][0]+2])/t),s&&(f.x=(s[2*d[t][t]]-s[2*d[t][0]])/t,f.y=(s[2*d[t][t]+1]-s[2*d[t][0]+1])/t);for(let e=1;e<t;e++)d[t][e]=r.length/3,r[x++]=r[3*d[t][0]]+e*_.x,r[x++]=r[3*d[t][0]+1]+e*_.y,r[x++]=r[3*d[t][0]+2]+e*_.z,a&&(a[c++]=a[3*d[t][0]]+e*p.x,a[c++]=a[3*d[t][0]+1]+e*p.y,a[c++]=a[3*d[t][0]+2]+e*p.z),s&&(s[h++]=s[2*d[t][0]]+e*f.x,s[h++]=s[2*d[t][0]+1]+e*f.y)}d[u]=v[i[e+1]][i[e+2]],m.push(d[0][0],d[1][0],d[1][1]);for(let e=1;e<u;e++){let t;for(t=0;t<e;t++)m.push(d[e][t],d[e+1][t],d[e+1][t+1]),m.push(d[e][t],d[e+1][t+1],d[e][t+1]);m.push(d[e][t],d[e+1][t],d[e+1][t+1])}}t.indices=m,t.applyToMesh(this,this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind))}else logger_Logger.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions")}forceSharedVertices(){let e=mesh_vertexData_VertexData.ExtractFromMesh(this),t=e.uvs,i=e.indices,r=e.positions,s=e.colors,a=e.matricesIndices,n=e.matricesWeights,o=e.matricesIndicesExtra,l=e.matricesWeightsExtra;if(void 0===i||void 0===r||null===i||null===r)logger_Logger.Warn("VertexData contains empty entries");else{let h,c;let u=[],d=[],_=[],p=[],f=[],m=[],g=[],v=[],x=[],b=0,T={};for(let e=0;e<i.length;e+=3){c=[i[e],i[e+1],i[e+2]],x=[];for(let e=0;e<3;e++){x[e]="";for(let t=0;t<3;t++)1e-8>Math.abs(r[3*c[e]+t])&&(r[3*c[e]+t]=0),x[e]+=r[3*c[e]+t]+"|"}if(!(x[0]==x[1]||x[0]==x[2]||x[1]==x[2]))for(let e=0;e<3;e++){if(void 0===(h=T[x[e]])){T[x[e]]=b,h=b++;for(let t=0;t<3;t++)u.push(r[3*c[e]+t]);if(null!=s)for(let t=0;t<4;t++)p.push(s[4*c[e]+t]);if(null!=t)for(let i=0;i<2;i++)_.push(t[2*c[e]+i]);if(null!=a)for(let t=0;t<4;t++)f.push(a[4*c[e]+t]);if(null!=n)for(let t=0;t<4;t++)m.push(n[4*c[e]+t]);if(null!=o)for(let t=0;t<4;t++)g.push(o[4*c[e]+t]);if(null!=l)for(let t=0;t<4;t++)v.push(l[4*c[e]+t])}d.push(h)}}let S=[];mesh_vertexData_VertexData.ComputeNormals(u,d,S),e.positions=u,e.indices=d,e.normals=S,null!=t&&(e.uvs=_),null!=s&&(e.colors=p),null!=a&&(e.matricesIndices=f),null!=n&&(e.matricesWeights=m),null!=o&&(e.matricesIndicesExtra=g),null!=n&&(e.matricesWeightsExtra=v),e.applyToMesh(this,this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind))}}static _instancedMeshFactory(e,t){throw _WarnImport("InstancedMesh")}static _PhysicsImpostorParser(e,t,i){throw _WarnImport("PhysicsImpostor")}createInstance(e){return mesh_Mesh._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e<this.instances.length;e++){let t=this.instances[e];t._syncSubMeshes()}return this}optimizeIndices(e){let t=this.getIndices(),i=this.getVerticesData(buffer_VertexBuffer.PositionKind);if(!i||!t)return this;let r=[];for(let e=0;e<i.length;e+=3)r.push(math_vector_Vector3.FromArray(i,e));let s=[];return AsyncLoop.SyncAsyncForLoop(r.length,40,e=>{let t=r.length-1-e,i=r[t];for(let e=0;e<t;++e){let a=r[e];if(i.equals(a)){s[t]=e;break}}},()=>{for(let e=0;e<t.length;++e)t[e]=s[t[e]]||t[e];let i=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=i,e&&e(this)}),this}serialize(e={}){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),Tags&&Tags.HasTags(this)&&(e.tags=Tags.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.checkCollisions=this.checkCollisions,e.isBlocker=this.isBlocker,e.overrideMaterialSideOrientation=this.overrideMaterialSideOrientation,this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;let t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(let t=0;t<this.subMeshes.length;t++){let i=this.subMeshes[t];e.subMeshes.push({materialIndex:i.materialIndex,verticesStart:i.verticesStart,verticesCount:i.verticesCount,indexStart:i.indexStart,indexCount:i.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE)){let t=this.getPhysicsImpostor();t&&(e.physicsMass=t.getParam("mass"),e.physicsFriction=t.getParam("friction"),e.physicsRestitution=t.getParam("mass"),e.physicsImpostor=t.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(let t=0;t<this.instances.length;t++){let i=this.instances[t];if(i.doNotSerialize)continue;let r={name:i.name,id:i.id,isEnabled:i.isEnabled(!1),isVisible:i.isVisible,isPickable:i.isPickable,checkCollisions:i.checkCollisions,position:i.position.asArray(),scaling:i.scaling.asArray()};if(i.parent&&i.parent._serializeAsParent(r),i.rotationQuaternion?r.rotationQuaternion=i.rotationQuaternion.asArray():i.rotation&&(r.rotation=i.rotation.asArray()),this.getScene()._getComponent(sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE)){let e=i.getPhysicsImpostor();e&&(r.physicsMass=e.getParam("mass"),r.physicsFriction=e.getParam("friction"),r.physicsRestitution=e.getParam("mass"),r.physicsImpostor=e.type)}i.metadata&&(r.metadata=i.metadata),i.actionManager&&(r.actions=i.actionManager.serialize(i.name)),e.instances.push(r),decorators_SerializationHelper.AppendSerializedAnimations(i,r),r.ranges=i.serializeAnimationRanges()}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){let t={data:{},sizes:{},strides:{}};for(let e in this._userThinInstanceBuffersStorage.data)t.data[e]=Array.from(this._userThinInstanceBuffersStorage.data[e]),t.sizes[e]=this._userThinInstanceBuffersStorage.sizes[e],t.strides[e]=this._userThinInstanceBuffersStorage.strides[e];e.thinInstances.userThinInstance=t}return decorators_SerializationHelper.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e}_syncGeometryWithMorphTargetManager(){if(!this.geometry)return;this._markSubMeshesAsAttributesDirty();let e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices()){logger_Logger.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),this.morphTargetManager=null;return}if(e.isUsingTextureForTargets)return;for(let t=0;t<e.numInfluencers;t++){let i=e.getActiveTarget(t),r=i.getPositions();if(!r){logger_Logger.Error("Invalid morph target. Target must have positions.");return}this.geometry.setVerticesData(buffer_VertexBuffer.PositionKind+t,r,!1,3);let s=i.getNormals();s&&this.geometry.setVerticesData(buffer_VertexBuffer.NormalKind+t,s,!1,3);let a=i.getTangents();a&&this.geometry.setVerticesData(buffer_VertexBuffer.TangentKind+t,a,!1,3);let n=i.getUVs();n&&this.geometry.setVerticesData(buffer_VertexBuffer.UVKind+"_"+t,n,!1,2)}}else{let e=0;for(;this.geometry.isVerticesDataPresent(buffer_VertexBuffer.PositionKind+e);)this.geometry.removeVerticesData(buffer_VertexBuffer.PositionKind+e),this.geometry.isVerticesDataPresent(buffer_VertexBuffer.NormalKind+e)&&this.geometry.removeVerticesData(buffer_VertexBuffer.NormalKind+e),this.geometry.isVerticesDataPresent(buffer_VertexBuffer.TangentKind+e)&&this.geometry.removeVerticesData(buffer_VertexBuffer.TangentKind+e),this.geometry.isVerticesDataPresent(buffer_VertexBuffer.UVKind+e)&&this.geometry.removeVerticesData(buffer_VertexBuffer.UVKind+"_"+e),e++}}static Parse(e,t,i){let r;if((r=e.type&&"LinesMesh"===e.type?mesh_Mesh._LinesMeshParser(e,t):e.type&&"GroundMesh"===e.type?mesh_Mesh._GroundMeshParser(e,t):e.type&&"GoldbergMesh"===e.type?mesh_Mesh._GoldbergMeshParser(e,t):e.type&&"GreasedLineMesh"===e.type?mesh_Mesh._GreasedLineMeshParser(e,t):e.type&&"TrailMesh"===e.type?mesh_Mesh._TrailMeshParser(e,t):new mesh_Mesh(e.name,t)).id=e.id,r._waitingParsedUniqueId=e.uniqueId,Tags&&Tags.AddTagsTo(r,e.tags),r.position=math_vector_Vector3.FromArray(e.position),void 0!==e.metadata&&(r.metadata=e.metadata),e.rotationQuaternion?r.rotationQuaternion=math_vector_Quaternion.FromArray(e.rotationQuaternion):e.rotation&&(r.rotation=math_vector_Vector3.FromArray(e.rotation)),r.scaling=math_vector_Vector3.FromArray(e.scaling),e.localMatrix?r.setPreTransformMatrix(math_vector_Matrix.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(math_vector_Matrix.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r.isVisible=e.isVisible,r.infiniteDistance=e.infiniteDistance,r.showBoundingBox=e.showBoundingBox,r.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,void 0!==e.applyFog&&(r.applyFog=e.applyFog),void 0!==e.pickable&&(r.isPickable=e.pickable),void 0!==e.alphaIndex&&(r.alphaIndex=e.alphaIndex),r.receiveShadows=e.receiveShadows,void 0!==e.billboardMode&&(r.billboardMode=e.billboardMode),void 0!==e.visibility&&(r.visibility=e.visibility),r.checkCollisions=e.checkCollisions,void 0!==e.overrideMaterialSideOrientation&&(r.overrideMaterialSideOrientation=e.overrideMaterialSideOrientation),void 0!==e.isBlocker&&(r.isBlocker=e.isBlocker),r._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(r._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.actions&&(r._waitingData.actions=e.actions),void 0!==e.overlayAlpha&&(r.overlayAlpha=e.overlayAlpha),void 0!==e.overlayColor&&(r.overlayColor=math_color_Color3.FromArray(e.overlayColor)),void 0!==e.renderOverlay&&(r.renderOverlay=e.renderOverlay),r.isUnIndexed=!!e.isUnIndexed,r.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r.buildBoundingInfo(math_vector_Vector3.FromArray(e.boundingBoxMinimum),math_vector_Vector3.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(r._binaryInfo=e._binaryInfo),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(buffer_VertexBuffer.UVKind),e.hasUVs2&&r._delayInfo.push(buffer_VertexBuffer.UV2Kind),e.hasUVs3&&r._delayInfo.push(buffer_VertexBuffer.UV3Kind),e.hasUVs4&&r._delayInfo.push(buffer_VertexBuffer.UV4Kind),e.hasUVs5&&r._delayInfo.push(buffer_VertexBuffer.UV5Kind),e.hasUVs6&&r._delayInfo.push(buffer_VertexBuffer.UV6Kind),e.hasColors&&r._delayInfo.push(buffer_VertexBuffer.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(buffer_VertexBuffer.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(buffer_VertexBuffer.MatricesWeightsKind),r._delayLoadingFunction=Geometry._ImportGeometry,SceneLoaderFlags.ForceFullSceneLoadingForIncremental&&r._checkDelayState()):Geometry._ImportGeometry(e,r),e.materialUniqueId?r._waitingMaterialId=e.materialUniqueId:e.materialId&&(r._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(r.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(r.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t<e.animations.length;t++){let i=e.animations[t],s=h["BABYLON.Animation"];s&&r.animations.push(s.Parse(i))}node_Node.ParseAnimationRanges(r,e,t)}if(e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?r.layerMask=Math.abs(parseInt(e.layerMask)):r.layerMask=268435455,e.physicsImpostor&&mesh_Mesh._PhysicsImpostorParser(t,r,e),e.lodMeshIds&&(r._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let i=0;i<e.instances.length;i++){let s=e.instances[i],a=r.createInstance(s.name);if(s.id&&(a.id=s.id),Tags&&(s.tags?Tags.AddTagsTo(a,s.tags):Tags.AddTagsTo(a,e.tags)),a.position=math_vector_Vector3.FromArray(s.position),void 0!==s.metadata&&(a.metadata=s.metadata),void 0!==s.parentId&&(a._waitingParentId=s.parentId),void 0!==s.parentInstanceIndex&&(a._waitingParentInstanceIndex=s.parentInstanceIndex),void 0!==s.isEnabled&&null!==s.isEnabled&&a.setEnabled(s.isEnabled),void 0!==s.isVisible&&null!==s.isVisible&&(a.isVisible=s.isVisible),void 0!==s.isPickable&&null!==s.isPickable&&(a.isPickable=s.isPickable),s.rotationQuaternion?a.rotationQuaternion=math_vector_Quaternion.FromArray(s.rotationQuaternion):s.rotation&&(a.rotation=math_vector_Vector3.FromArray(s.rotation)),a.scaling=math_vector_Vector3.FromArray(s.scaling),void 0!=s.checkCollisions&&null!=s.checkCollisions&&(a.checkCollisions=s.checkCollisions),void 0!=s.pickable&&null!=s.pickable&&(a.isPickable=s.pickable),void 0!=s.showBoundingBox&&null!=s.showBoundingBox&&(a.showBoundingBox=s.showBoundingBox),void 0!=s.showSubMeshesBoundingBox&&null!=s.showSubMeshesBoundingBox&&(a.showSubMeshesBoundingBox=s.showSubMeshesBoundingBox),void 0!=s.alphaIndex&&null!=s.showSubMeshesBoundingBox&&(a.alphaIndex=s.alphaIndex),s.physicsImpostor&&mesh_Mesh._PhysicsImpostorParser(t,a,s),void 0!==s.actions&&(a._waitingData.actions=s.actions),s.animations){for(let e=0;e<s.animations.length;e++){let t=s.animations[e],i=h["BABYLON.Animation"];i&&a.animations.push(i.Parse(t))}node_Node.ParseAnimationRanges(a,s,t),s.autoAnimate&&t.beginAnimation(a,s.autoAnimateFrom,s.autoAnimateTo,s.autoAnimateLoop,s.autoAnimateSpeed||1)}}if(e.thinInstances){let t=e.thinInstances;if(r.thinInstanceEnablePicking=!!t.enablePicking,t.matrixData?(r.thinInstanceSetBuffer("matrix",new Float32Array(t.matrixData),16,!1),r._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,r._thinInstanceDataStorage.instancesCount=t.instancesCount):r._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,e.thinInstances.userThinInstance){let t=e.thinInstances.userThinInstance;for(let e in t.data)r.thinInstanceSetBuffer(e,new Float32Array(t.data[e]),t.strides[e],!1),r._userThinInstanceBuffersStorage.sizes[e]=t.sizes[e]}}return r}setPositionsForCPUSkinning(){let e=this._internalMeshDataInfo;if(!e._sourcePositions){let t=this.getVerticesData(buffer_VertexBuffer.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind)||this.setVerticesData(buffer_VertexBuffer.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){let e=this._internalMeshDataInfo;if(!e._sourceNormals){let t=this.getVerticesData(buffer_VertexBuffer.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(buffer_VertexBuffer.NormalKind)||this.setVerticesData(buffer_VertexBuffer.NormalKind,t,!0)}return e._sourceNormals}applySkeleton(e){let t;if(!this.geometry||this.geometry._softwareSkinningFrameId==this.getScene().getFrameId()||(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(buffer_VertexBuffer.PositionKind)||!this.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesKind)||!this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)))return this;let i=this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind),r=this._internalMeshDataInfo;if(!r._sourcePositions){let e=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=e}i&&!r._sourceNormals&&this.setNormalsForCPUSkinning();let s=this.getVerticesData(buffer_VertexBuffer.PositionKind);if(!s)return this;s instanceof Float32Array||(s=new Float32Array(s));let a=this.getVerticesData(buffer_VertexBuffer.NormalKind);if(i){if(!a)return this;a instanceof Float32Array||(a=new Float32Array(a))}let n=this.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind),o=this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind);if(!o||!n)return this;let l=this.numBoneInfluencers>4,h=l?this.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),d=math_vector_Vector3.Zero(),_=new math_vector_Matrix,p=new math_vector_Matrix,f=0;for(let e=0;e<s.length;e+=3,f+=4){let m;for(t=0;t<4;t++)(m=o[f+t])>0&&(math_vector_Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*n[f+t]),m,p),_.addToSelf(p));if(l)for(t=0;t<4;t++)(m=c[f+t])>0&&(math_vector_Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*h[f+t]),m,p),_.addToSelf(p));math_vector_Vector3.TransformCoordinatesFromFloatsToRef(r._sourcePositions[e],r._sourcePositions[e+1],r._sourcePositions[e+2],_,d),d.toArray(s,e),i&&(math_vector_Vector3.TransformNormalFromFloatsToRef(r._sourceNormals[e],r._sourceNormals[e+1],r._sourceNormals[e+2],_,d),d.toArray(a,e)),_.reset()}return this.updateVerticesData(buffer_VertexBuffer.PositionKind,s),i&&this.updateVerticesData(buffer_VertexBuffer.NormalKind,a),this}static MinMax(e){let t=null,i=null;return(e.forEach(function(e){let r=e.getBoundingInfo(),s=r.boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)}),t&&i)?{min:t,max:i}:{min:math_vector_Vector3.Zero(),max:math_vector_Vector3.Zero()}}static Center(e){let t=e instanceof Array?mesh_Mesh.MinMax(e):e;return math_vector_Vector3.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,r,s,a){return runCoroutineSync(mesh_Mesh._MergeMeshesCoroutine(e,t,i,r,s,a,!1))}static MergeMeshesAsync(e,t=!0,i,r,s,a){return runCoroutineAsync(mesh_Mesh._MergeMeshesCoroutine(e,t,i,r,s,a,!0),createYieldingScheduler())}static*_MergeMeshesCoroutine(e,t=!0,i,r,s,a,n){let o;if(0===(e=e.filter(Boolean)).length)return null;if(!i){let t=0;for(o=0;o<e.length;o++)if((t+=e[o].getTotalVertices())>=65536)return logger_Logger.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}a&&(s=!1);let l=[],h=[],c=[],u=e[0].overrideMaterialSideOrientation;for(o=0;o<e.length;o++){let t=e[o];if(t.isAnInstance)return logger_Logger.Warn("Cannot merge instance meshes."),null;if(u!==t.overrideMaterialSideOrientation)return logger_Logger.Warn("Cannot merge meshes with different overrideMaterialSideOrientation values."),null;if(s&&c.push(t.getTotalIndices()),a){if(t.material){let e=t.material;if(e instanceof multiMaterial_MultiMaterial){for(let t=0;t<e.subMaterials.length;t++)0>l.indexOf(e.subMaterials[t])&&l.push(e.subMaterials[t]);for(let i=0;i<t.subMeshes.length;i++)h.push(l.indexOf(e.subMaterials[t.subMeshes[i].materialIndex])),c.push(t.subMeshes[i].indexCount)}else{0>l.indexOf(e)&&l.push(e);for(let i=0;i<t.subMeshes.length;i++)h.push(l.indexOf(e)),c.push(t.subMeshes[i].indexCount)}}else for(let e=0;e<t.subMeshes.length;e++)h.push(0),c.push(t.subMeshes[e].indexCount)}}let d=e[0],getVertexDataFromMesh=e=>{let t=e.computeWorldMatrix(!0),i=mesh_vertexData_VertexData.ExtractFromMesh(e,!1,!1);return{vertexData:i,transform:t}},{vertexData:_,transform:p}=getVertexDataFromMesh(d);n&&(yield);let f=Array(e.length-1);for(let t=1;t<e.length;t++)f[t-1]=getVertexDataFromMesh(e[t]),n&&(yield);let m=_._mergeCoroutine(p,f,i,n,!t),g=m.next();for(;!g.done;)n&&(yield),g=m.next();let v=g.value;r||(r=new mesh_Mesh(d.name+"_merged",d.getScene()));let x=v._applyToCoroutine(r,void 0,n),b=x.next();for(;!b.done;)n&&(yield),b=x.next();if(r.checkCollisions=d.checkCollisions,r.overrideMaterialSideOrientation=d.overrideMaterialSideOrientation,t)for(o=0;o<e.length;o++)e[o].dispose();if(s||a){r.releaseSubMeshes(),o=0;let e=0;for(;o<c.length;)subMesh_SubMesh.CreateFromIndices(0,e,c[o],r,void 0,!1),e+=c[o],o++;for(let e of r.subMeshes)e.refreshBoundingInfo();r.computeWorldMatrix(!0)}if(a){let e=new multiMaterial_MultiMaterial(d.name+"_merged",d.getScene());e.subMaterials=l;for(let e=0;e<r.subMeshes.length;e++)r.subMeshes[e].materialIndex=h[e];r.material=e}else r.material=d.material;return r}addInstance(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)}removeInstance(e){let t=e._indexInSourceMeshInstanceArray;if(-1!=t){if(t!==this.instances.length-1){let e=this.instances[this.instances.length-1];this.instances[t]=e,e._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}}_shouldConvertRHS(){return this.overrideMaterialSideOrientation===material_Material.CounterClockWiseSideOrientation}_getRenderingFillMode(e){var t;let i=this.getScene();return i.forcePointsCloud?material_Material.PointFillMode:i.forceWireframe?material_Material.WireFrameFillMode:null!==(t=this.overrideRenderingFillMode)&&void 0!==t?t:e}setMaterialByID(e){return this.setMaterialById(e)}static CreateRibbon(e,t,i,r,s,a,n,o,l){throw Error("Import MeshBuilder to populate this function")}static CreateDisc(e,t,i,r,s,a){throw Error("Import MeshBuilder to populate this function")}static CreateBox(e,t,i,r,s){throw Error("Import MeshBuilder to populate this function")}static CreateSphere(e,t,i,r,s,a){throw Error("Import MeshBuilder to populate this function")}static CreateHemisphere(e,t,i,r){throw Error("Import MeshBuilder to populate this function")}static CreateCylinder(e,t,i,r,s,a,n,o,l){throw Error("Import MeshBuilder to populate this function")}static CreateTorus(e,t,i,r,s,a,n){throw Error("Import MeshBuilder to populate this function")}static CreateTorusKnot(e,t,i,r,s,a,n,o,l,h){throw Error("Import MeshBuilder to populate this function")}static CreateLines(e,t,i,r,s){throw Error("Import MeshBuilder to populate this function")}static CreateDashedLines(e,t,i,r,s,a,n,o){throw Error("Import MeshBuilder to populate this function")}static CreatePolygon(e,t,i,r,s,a,n){throw Error("Import MeshBuilder to populate this function")}static ExtrudePolygon(e,t,i,r,s,a,n,o){throw Error("Import MeshBuilder to populate this function")}static ExtrudeShape(e,t,i,r,s,a,n,o,l,h){throw Error("Import MeshBuilder to populate this function")}static ExtrudeShapeCustom(e,t,i,r,s,a,n,o,l,h,c,u){throw Error("Import MeshBuilder to populate this function")}static CreateLathe(e,t,i,r,s,a,n){throw Error("Import MeshBuilder to populate this function")}static CreatePlane(e,t,i,r,s){throw Error("Import MeshBuilder to populate this function")}static CreateGround(e,t,i,r,s,a){throw Error("Import MeshBuilder to populate this function")}static CreateTiledGround(e,t,i,r,s,a,n,o,l){throw Error("Import MeshBuilder to populate this function")}static CreateGroundFromHeightMap(e,t,i,r,s,a,n,o,l,h,c){throw Error("Import MeshBuilder to populate this function")}static CreateTube(e,t,i,r,s,a,n,o,l,h){throw Error("Import MeshBuilder to populate this function")}static CreatePolyhedron(e,t,i){throw Error("Import MeshBuilder to populate this function")}static CreateIcoSphere(e,t,i){throw Error("Import MeshBuilder to populate this function")}static CreateDecal(e,t,i,r,s,a){throw Error("Import MeshBuilder to populate this function")}static CreateCapsule(e,t,i){throw Error("Import MeshBuilder to populate this function")}static ExtendToGoldberg(e){throw Error("Import MeshBuilder to populate this function")}};mesh_Mesh.FRONTSIDE=mesh_vertexData_VertexData.FRONTSIDE,mesh_Mesh.BACKSIDE=mesh_vertexData_VertexData.BACKSIDE,mesh_Mesh.DOUBLESIDE=mesh_vertexData_VertexData.DOUBLESIDE,mesh_Mesh.DEFAULTSIDE=mesh_vertexData_VertexData.DEFAULTSIDE,mesh_Mesh.NO_CAP=0,mesh_Mesh.CAP_START=1,mesh_Mesh.CAP_END=2,mesh_Mesh.CAP_ALL=3,mesh_Mesh.NO_FLIP=0,mesh_Mesh.FLIP_TILE=1,mesh_Mesh.ROTATE_TILE=2,mesh_Mesh.FLIP_ROW=3,mesh_Mesh.ROTATE_ROW=4,mesh_Mesh.FLIP_N_ROTATE_TILE=5,mesh_Mesh.FLIP_N_ROTATE_ROW=6,mesh_Mesh.CENTER=0,mesh_Mesh.LEFT=1,mesh_Mesh.RIGHT=2,mesh_Mesh.TOP=3,mesh_Mesh.BOTTOM=4,mesh_Mesh.INSTANCEDMESH_SORT_TRANSPARENT=!1,mesh_Mesh._GroundMeshParser=(e,t)=>{throw _WarnImport("GroundMesh")},mesh_Mesh._GoldbergMeshParser=(e,t)=>{throw _WarnImport("GoldbergMesh")},mesh_Mesh._LinesMeshParser=(e,t)=>{throw _WarnImport("LinesMesh")},mesh_Mesh._GreasedLineMeshParser=(e,t)=>{throw _WarnImport("GreasedLineMesh")},mesh_Mesh._GreasedLineRibbonMeshParser=(e,t)=>{throw _WarnImport("GreasedLineRibbonMesh")},mesh_Mesh._TrailMeshParser=(e,t)=>{throw _WarnImport("TrailMesh")},h["BABYLON.Mesh"]=mesh_Mesh,mesh_Mesh._instancedMeshFactory=(e,t)=>{let i=new instancedMesh_InstancedMesh(e,t);if(t.instancedBuffers)for(let e in i.instancedBuffers={},t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e];return i};let instancedMesh_InstancedMesh=class instancedMesh_InstancedMesh extends abstractMesh_AbstractMesh{constructor(e,t){for(let i of(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(),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&&tools_Tools.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&&tools_Tools.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&&tools_Tools.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&&tools_Tools.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&&logger_Logger.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,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i=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||logger_Logger.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){let i=this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0;if(i)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!==transformNode_TransformNode.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new math_vector_Matrix);let e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,math_vector_TmpVectors.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(math_vector_TmpVectors.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;let t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){let t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this}_generatePointsArray(){return this._sourceMesh._generatePointsArray()}_updateBoundingInfo(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}clone(e,t=null,i,r){let s=(r||this._sourceMesh).createInstance(e);if(DeepCopier.DeepCopy(this,s,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo"],[]),this.refreshBoundingInfo(),t&&(s.parent=t),!i)for(let e=0;e<this.getScene().meshes.length;e++){let t=this.getScene().meshes[e];t.parent===this&&t.clone(t.name,s)}return s.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(s),s}dispose(e,t=!1){this._sourceMesh.removeInstance(this),super.dispose(e,t)}_serializeAsParent(e){super._serializeAsParent(e),e.parentId=this._sourceMesh.uniqueId,e.parentInstanceIndex=this._indexInSourceMeshInstanceArray}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);for(let e of(r&&i&&i(this,r),this.getChildTransformNodes(!0)))e.instantiateHierarchy(r,t,i);return r}};mesh_Mesh.prototype.registerInstancedBuffer=function(e,t){var i,r;if(null===(r=null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])||void 0===r||r.dispose(),!this.instancedBuffers)for(let e of(this.instancedBuffers={},this.instances))e.instancedBuffers={};for(let i of(this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this.instancedBuffers[e]=null,this._userInstancedBuffersStorage.strides[e]=t,this._userInstancedBuffersStorage.sizes[e]=32*t,this._userInstancedBuffersStorage.data[e]=new Float32Array(this._userInstancedBuffersStorage.sizes[e]),this._userInstancedBuffersStorage.vertexBuffers[e]=new buffer_VertexBuffer(this.getEngine(),this._userInstancedBuffersStorage.data[e],e,!0,!1,t,!0),this.instances))i.instancedBuffers[e]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()},mesh_Mesh.prototype._processInstancedBuffers=function(e,t){let i=e?e.length:0;for(let r in this.instancedBuffers){let s=this._userInstancedBuffersStorage.sizes[r],a=this._userInstancedBuffersStorage.strides[r],n=(i+1)*a;for(;s<n;)s*=2;this._userInstancedBuffersStorage.data[r].length!=s&&(this._userInstancedBuffersStorage.data[r]=new Float32Array(s),this._userInstancedBuffersStorage.sizes[r]=s,this._userInstancedBuffersStorage.vertexBuffers[r]&&(this._userInstancedBuffersStorage.vertexBuffers[r].dispose(),this._userInstancedBuffersStorage.vertexBuffers[r]=null));let o=this._userInstancedBuffersStorage.data[r],l=0;if(t){let e=this.instancedBuffers[r];e.toArray?e.toArray(o,l):e.copyToArray?e.copyToArray(o,l):o[l]=e,l+=a}for(let t=0;t<i;t++){let i=e[t],s=i.instancedBuffers[r];s.toArray?s.toArray(o,l):s.copyToArray?s.copyToArray(o,l):o[l]=s,l+=a}this._userInstancedBuffersStorage.vertexBuffers[r]?this._userInstancedBuffersStorage.vertexBuffers[r].updateDirectly(o,0):(this._userInstancedBuffersStorage.vertexBuffers[r]=new buffer_VertexBuffer(this.getEngine(),this._userInstancedBuffersStorage.data[r],r,!0,!1,a,!0),this._invalidateInstanceVertexArrayObject())}},mesh_Mesh.prototype._invalidateInstanceVertexArrayObject=function(){if(this._userInstancedBuffersStorage&&void 0!==this._userInstancedBuffersStorage.vertexArrayObjects){for(let e in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[e]);this._userInstancedBuffersStorage.vertexArrayObjects={}}},mesh_Mesh.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(let e in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[e]&&this._userInstancedBuffersStorage.vertexBuffers[e].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}};let light_Light=class light_Light extends node_Node{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}constructor(e,t){super(e,t),this.diffuse=new math_color_Color3(1,1,1),this.specular=new math_color_Color3(1,1,1),this.falloffType=light_Light.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=light_Light.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=[],this._includedOnlyMeshesIds=[],this._isLight=!0,this.getScene().addLight(this),this._uniformBuffer=new UniformBuffer(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,r,s=!0){var a;let n=e.toString(),o=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+n),this._renderId!==t.getRenderId()||this._lastUseSpecular!==r||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=r;let e=this.getScaledIntensity();this.transferToEffect(i,n),this.diffuse.scaleToRef(e,TmpColors.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",TmpColors.Color3[0],this.range,n),r&&(this.specular.scaleToRef(e,TmpColors.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",TmpColors.Color3[1],this.radius,n)),o=!0}if(this.transferTexturesToEffect(i,n),t.shadowsEnabled&&this.shadowEnabled&&s){let e=null!==(a=this.getShadowGenerator(t.activeCamera))&&void 0!==a?a:this.getShadowGenerator();e&&(e.bindShadowLight(n,i),o=!0)}o?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}_syncParentEnabledState(){super._syncParentEnabledState(),this.isDisposed()||this._resyncMeshes()}setEnabled(e){super.setEnabled(e),this._resyncMeshes()}getShadowGenerator(e=null){var t;return null===this._shadowGenerators?null:null!==(t=this._shadowGenerators.get(e))&&void 0!==t?t:null}getShadowGenerators(){return this._shadowGenerators}getAbsolutePosition(){return math_vector_Vector3.Zero()}canAffectMesh(e){return!e||(!this.includedOnlyMeshes||!(this.includedOnlyMeshes.length>0)||-1!==this.includedOnlyMeshes.indexOf(e))&&(!this.excludedMeshes||!(this.excludedMeshes.length>0)||-1===this.excludedMeshes.indexOf(e))&&(0===this.includeOnlyWithLayerMask||(this.includeOnlyWithLayerMask&e.layerMask)!=0)&&(0===this.excludeWithLayerMask||!(this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){let e=t.value;e.dispose()}this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){let e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(let e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){let i=light_Light.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;let r=decorators_SerializationHelper.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){let e=decorators_SerializationHelper.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)})),decorators_SerializationHelper.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){let r=node_Node.Construct("Light_Type_"+e,t,i);return r||null}static Parse(e,t){let i=light_Light.GetConstructorFromName(e.type,e.name,t);if(!i)return null;let r=decorators_SerializationHelper.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(r.falloffType=e.falloffType),void 0!==e.lightmapMode&&(r.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t<e.animations.length;t++){let i=e.animations[t],s=h["BABYLON.Animation"];s&&r.animations.push(s.Parse(i))}node_Node.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&r.setEnabled(e.isEnabled),r}_hookArrayForExcluded(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);for(let e of i)e._resyncLightSource(this);return r};let i=e.splice;for(let t of(e.splice=(t,r)=>{let s=i.apply(e,[t,r]);for(let e of s)e._resyncLightSource(this);return s},e))t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._resyncMeshes(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(let e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(let e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0,t=this.getTypeID(),i=this.intensityMode;switch(i===light_Light.INTENSITYMODE_AUTOMATIC&&(i=t===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?light_Light.INTENSITYMODE_ILLUMINANCE:light_Light.INTENSITYMODE_LUMINOUSINTENSITY),t){case light_Light.LIGHTTYPEID_POINTLIGHT:case light_Light.LIGHTTYPEID_SPOTLIGHT:switch(i){case light_Light.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case light_Light.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case light_Light.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case light_Light.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case light_Light.INTENSITYMODE_ILLUMINANCE:e=1;break;case light_Light.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001);let i=2*Math.PI*(1-Math.cos(t));e=i}}break;case light_Light.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){let e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}};light_Light.FALLOFF_DEFAULT=LightConstants.FALLOFF_DEFAULT,light_Light.FALLOFF_PHYSICAL=LightConstants.FALLOFF_PHYSICAL,light_Light.FALLOFF_GLTF=LightConstants.FALLOFF_GLTF,light_Light.FALLOFF_STANDARD=LightConstants.FALLOFF_STANDARD,light_Light.LIGHTMAP_DEFAULT=LightConstants.LIGHTMAP_DEFAULT,light_Light.LIGHTMAP_SPECULAR=LightConstants.LIGHTMAP_SPECULAR,light_Light.LIGHTMAP_SHADOWSONLY=LightConstants.LIGHTMAP_SHADOWSONLY,light_Light.INTENSITYMODE_AUTOMATIC=LightConstants.INTENSITYMODE_AUTOMATIC,light_Light.INTENSITYMODE_LUMINOUSPOWER=LightConstants.INTENSITYMODE_LUMINOUSPOWER,light_Light.INTENSITYMODE_LUMINOUSINTENSITY=LightConstants.INTENSITYMODE_LUMINOUSINTENSITY,light_Light.INTENSITYMODE_ILLUMINANCE=LightConstants.INTENSITYMODE_ILLUMINANCE,light_Light.INTENSITYMODE_LUMINANCE=LightConstants.INTENSITYMODE_LUMINANCE,light_Light.LIGHTTYPEID_POINTLIGHT=LightConstants.LIGHTTYPEID_POINTLIGHT,light_Light.LIGHTTYPEID_DIRECTIONALLIGHT=LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT,light_Light.LIGHTTYPEID_SPOTLIGHT=LightConstants.LIGHTTYPEID_SPOTLIGHT,light_Light.LIGHTTYPEID_HEMISPHERICLIGHT=LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT,__decorate([serializeAsColor3()],light_Light.prototype,"diffuse",void 0),__decorate([serializeAsColor3()],light_Light.prototype,"specular",void 0),__decorate([serialize()],light_Light.prototype,"falloffType",void 0),__decorate([serialize()],light_Light.prototype,"intensity",void 0),__decorate([serialize()],light_Light.prototype,"range",null),__decorate([serialize()],light_Light.prototype,"intensityMode",null),__decorate([serialize()],light_Light.prototype,"radius",null),__decorate([serialize()],light_Light.prototype,"_renderPriority",void 0),__decorate([expandToProperty("_reorderLightsInScene")],light_Light.prototype,"renderPriority",void 0),__decorate([serialize("shadowEnabled")],light_Light.prototype,"_shadowEnabled",void 0),__decorate([serialize("excludeWithLayerMask")],light_Light.prototype,"_excludeWithLayerMask",void 0),__decorate([serialize("includeOnlyWithLayerMask")],light_Light.prototype,"_includeOnlyWithLayerMask",void 0),__decorate([serialize("lightmapMode")],light_Light.prototype,"_lightmapMode",void 0);let KeepAssets=class KeepAssets extends AbstractScene{};let InstantiatedEntries=class InstantiatedEntries{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}};let AssetContainer=class AssetContainer extends AbstractScene{constructor(e){if(super(),this._wasAddedToScene=!1,!(e=e||engineStore_EngineStore.LastCreatedScene))return;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(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of this.particleSystems)e.rebuild();for(let e of this.textures)e._rebuild()})}_topologicalSort(e){let t=new Map;for(let i of e)t.set(i.uniqueId,i);let i={dependsOn:new Map,dependedBy:new Map};for(let t of e){let e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(let r of e){let e=r.uniqueId,s=i.dependsOn.get(e);if(r instanceof instancedMesh_InstancedMesh){let a=r.sourceMesh;t.has(a.uniqueId)&&(s.add(a.uniqueId),i.dependedBy.get(a.uniqueId).add(e))}let a=i.dependedBy.get(e);for(let s of r.getDescendants()){let r=s.uniqueId;if(t.has(r)){a.add(r);let t=i.dependsOn.get(r);t.add(e)}}}let r=[],s=[];for(let r of e){let e=r.uniqueId;0===i.dependsOn.get(e).size&&(s.push(r),t.delete(e))}for(;s.length>0;){let e=s.shift();r.push(e);let a=i.dependedBy.get(e.uniqueId);for(let r of Array.from(a.values())){let a=i.dependsOn.get(r);a.delete(e.uniqueId),0===a.size&&t.get(r)&&(s.push(t.get(r)),t.delete(r))}}return t.size>0&&(console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(e=>console.error(e.name))),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId)))for(let s of(e.push(i),t.add(i.uniqueId),i.getDescendants(!0)))this._addNodeAndDescendantsToList(e,t,s,r)}_isNodeInContainer(e){return e instanceof mesh_Mesh&&-1!==this.meshes.indexOf(e)||e instanceof transformNode_TransformNode&&-1!==this.transformNodes.indexOf(e)||e instanceof light_Light&&-1!==this.lights.indexOf(e)||e instanceof camera_Camera&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(let e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return logger_Logger.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return logger_Logger.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return logger_Logger.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return logger_Logger.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||tools_Tools.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");let r={},s={},a=new InstantiatedEntries,n=[],o=[],l=Object.assign({doNotInstantiate:!0},i),onClone=(t,i)=>{if(r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof mesh_Mesh&&i.morphTargetManager){let e=t.morphTargetManager;i.morphTargetManager=e.clone();for(let t=0;t<e.numTargets;t++){let a=e.getTarget(t),n=i.morphTargetManager.getTarget(t);r[a.uniqueId]=n.uniqueId,s[n.uniqueId]=n}}},h=[],c=new Set;for(let e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);for(let e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);let u=this._topologicalSort(h),onNewCreated=(i,n)=>{if(onClone(i,n),i.parent){let e=r[i.parent.uniqueId],t=s[e];t?n.parent=t:n.parent=i.parent}if(n.position&&i.position&&n.position.copyFrom(i.position),n.rotationQuaternion&&i.rotationQuaternion&&n.rotationQuaternion.copyFrom(i.rotationQuaternion),n.rotation&&i.rotation&&n.rotation.copyFrom(i.rotation),n.scaling&&i.scaling&&n.scaling.copyFrom(i.scaling),n.material&&n.material){if(t){let t=i.material;if(-1===o.indexOf(t)){let i=t.clone(e?e(t.name):"Clone of "+t.name);if(o.push(t),r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,"MultiMaterial"===t.getClassName()){for(let a of t.subMaterials)a&&(i=a.clone(e?e(a.name):"Clone of "+a.name),o.push(a),r[a.uniqueId]=i.uniqueId,s[i.uniqueId]=i);t.subMaterials=t.subMaterials.map(e=>e&&s[r[e.uniqueId]])}}"InstancedMesh"!==n.getClassName()&&(n.material=s[r[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===n.parent&&a.rootNodes.push(n)};return u.forEach(e=>{if("InstancedMesh"===e.getClassName()){let t=e.sourceMesh,i=r[t.uniqueId],a="number"==typeof i?s[i]:t,n=a.createInstance(e.name);onNewCreated(e,n)}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);let i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw Error(`Could not clone or instantiate node on Asset Container ${e.name}`);onNewCreated(e,i)}}),this.skeletons.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name);for(let e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){let t=s[r[e.uniqueId]];if(!t||t.isAnInstance||(t.skeleton=i,-1!==n.indexOf(i)))continue;for(let e of(n.push(i),i.bones))e._linkedTransformNode&&(e._linkedTransformNode=s[r[e._linkedTransformNode.uniqueId]])}a.skeletons.push(i)}),this.animationGroups.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name,e=>{let t=s[r[e.uniqueId]];return t||e});a.animationGroups.push(i)}),a}addAllToScene(){if(!this._wasAddedToScene){for(let e of(this._isValidHierarchy()||tools_Tools.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture),this.scene._serializableComponents))e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){let t=[];for(let i of(this.cameras.forEach(i=>{(!e||e(i))&&(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{(!e||e(i))&&(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{(!e||e(i))&&(this.scene.addMesh(i),t.push(i))}),this.skeletons.forEach(t=>{(!e||e(t))&&this.scene.addSkeleton(t)}),this.animations.forEach(t=>{(!e||e(t))&&this.scene.addAnimation(t)}),this.animationGroups.forEach(t=>{(!e||e(t))&&this.scene.addAnimationGroup(t)}),this.multiMaterials.forEach(t=>{(!e||e(t))&&this.scene.addMultiMaterial(t)}),this.materials.forEach(t=>{(!e||e(t))&&this.scene.addMaterial(t)}),this.morphTargetManagers.forEach(t=>{(!e||e(t))&&this.scene.addMorphTargetManager(t)}),this.geometries.forEach(t=>{(!e||e(t))&&this.scene.addGeometry(t)}),this.transformNodes.forEach(i=>{(!e||e(i))&&(this.scene.addTransformNode(i),t.push(i))}),this.actionManagers.forEach(t=>{(!e||e(t))&&this.scene.addActionManager(t)}),this.textures.forEach(t=>{(!e||e(t))&&this.scene.addTexture(t)}),this.reflectionProbes.forEach(t=>{(!e||e(t))&&this.scene.addReflectionProbe(t)}),t))i.parent&&-1===this.scene.getNodes().indexOf(i.parent)&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){for(let e of(this._isValidHierarchy()||tools_Tools.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),this.scene._serializableComponents))e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach(t=>{(!e||e(t))&&this.scene.removeCamera(t)}),this.lights.forEach(t=>{(!e||e(t))&&this.scene.removeLight(t)}),this.meshes.forEach(t=>{(!e||e(t))&&this.scene.removeMesh(t,!0)}),this.skeletons.forEach(t=>{(!e||e(t))&&this.scene.removeSkeleton(t)}),this.animations.forEach(t=>{(!e||e(t))&&this.scene.removeAnimation(t)}),this.animationGroups.forEach(t=>{(!e||e(t))&&this.scene.removeAnimationGroup(t)}),this.multiMaterials.forEach(t=>{(!e||e(t))&&this.scene.removeMultiMaterial(t)}),this.materials.forEach(t=>{(!e||e(t))&&this.scene.removeMaterial(t)}),this.morphTargetManagers.forEach(t=>{(!e||e(t))&&this.scene.removeMorphTargetManager(t)}),this.geometries.forEach(t=>{(!e||e(t))&&this.scene.removeGeometry(t)}),this.transformNodes.forEach(t=>{(!e||e(t))&&this.scene.removeTransformNode(t)}),this.actionManagers.forEach(t=>{(!e||e(t))&&this.scene.removeActionManager(t)}),this.textures.forEach(t=>{(!e||e(t))&&this.scene.removeTexture(t)}),this.reflectionProbes.forEach(t=>{(!e||e(t))&&this.scene.removeReflectionProbe(t)})}dispose(){for(let e of(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),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(let r of e){let e=!0;if(i){for(let t of i)if(r===t){e=!1;break}}e&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){for(let t in this._wasAddedToScene=!1,void 0===e&&(e=new KeepAssets),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(){let e=new mesh_Mesh("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=engineStore_EngineStore.LastCreatedScene,t,i=null){if(!e)return logger_Logger.Error("No scene available to merge animations to"),[];let r=i||(t=>{let i=null,r=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(r){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i}),s=this.getNodes();s.forEach(e=>{let t=r(e);if(null!==t){for(let i of e.animations){let e=t.animations.filter(e=>e.targetProperty===i.targetProperty);for(let i of e){let e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}});let a=[];return this.animationGroups.slice().forEach(e=>{a.push(e.clone(e.name,r)),e.animatables.forEach(e=>{e.stop()})}),t.forEach(t=>{let i=r(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))}),a}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}),this.transformNodes.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}),this.lights.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}),this.cameras.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})}addAllAssetsToContainer(e){if(!e)return;let t=[],i=new Set;for(t.push(e);t.length>0;){let e=t.pop();if(e instanceof mesh_Mesh?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof transformNode_TransformNode?this.transformNodes.push(e):e instanceof light_Light?this.lights.push(e):e instanceof camera_Camera&&this.cameras.push(e),e instanceof abstractMesh_AbstractMesh){if(e.material&&-1===this.materials.indexOf(e.material))for(let t of(this.materials.push(e.material),e.material.getActiveTextures()))-1===this.textures.indexOf(t)&&this.textures.push(t);e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(let r of e.getChildren())i.has(r)||t.push(r);i.add(e)}this.populateRootNodes()}};engine_Engine.AudioEngineFactory=(e,t,i)=>new AudioEngine(e,t,i);let AudioEngine=class AudioEngine{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new observable_Observable,this.onAudioLockedObservable=new observable_Observable,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!IsWindowObjectExist())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);let r=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{r&&r.canPlayType&&(r.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||r.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{r&&r.canPlayType&&r.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if((null===(e=this._audioContext)||void 0===e?void 0:e.state)==="running"){this._hideMuteButton();return}this._tryToRun?null===(t=this._audioContext)||void 0===t||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return(null===(e=this._audioContext)||void 0===e?void 0:e.resume)?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,logger_Logger.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";let e=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",t=document.createElement("style");t.appendChild(document.createTextNode(".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); 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) }")),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",()=>{this._triggerRunningState()},!0),this._muteButton.addEventListener("click",()=>{this.unlock()},!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}};let Sound=class Sound{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=engine_Engine.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){let e=this.isPaused?0:engine_Engine.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;let t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,s){var a,n,o,l,h;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 observable_Observable,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=math_vector_Vector3.Zero(),this._localDirection=new math_vector_Vector3(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||engineStore_EngineStore.LastCreatedScene))return;if(this._scene=i,Sound._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(e,t,i,r,s)=>t<i?e*(1-t/i):0,s&&(this.autoplay=s.autoplay||!1,this._loop=s.loop||!1,void 0!==s.volume&&(this._volume=s.volume),this._spatialSound=null!==(a=s.spatialSound)&&void 0!==a&&a,this.maxDistance=null!==(n=s.maxDistance)&&void 0!==n?n:100,this.useCustomAttenuation=null!==(o=s.useCustomAttenuation)&&void 0!==o&&o,this.rolloffFactor=s.rolloffFactor||1,this.refDistance=s.refDistance||1,this.distanceModel=s.distanceModel||"linear",this._playbackRate=s.playbackRate||1,this._streaming=null!==(l=s.streaming)&&void 0!==l&&l,this._length=s.length,this._offset=s.offset),(null===(h=engine_Engine.audioEngine)||void 0===h?void 0:h.canUseWebAudio)&&engine_Engine.audioEngine.audioContext){this._soundGain=engine_Engine.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this._spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.addSound(this);let e=!0;if(t)try{"string"==typeof t?(this._urlType="String",this._url=t):t instanceof ArrayBuffer?this._urlType="ArrayBuffer":t instanceof HTMLMediaElement?this._urlType="MediaElement":t instanceof MediaStream?this._urlType="MediaStream":t instanceof AudioBuffer?this._urlType="AudioBuffer":Array.isArray(t)&&(this._urlType="Array");let i=[],r=!1;switch(this._urlType){case"MediaElement":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=engine_Engine.audioEngine.audioContext.createMediaElementSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=engine_Engine.audioEngine.audioContext.createMediaStreamSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":t.byteLength>0&&(r=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e<i.length;e++){let t=i[e];if(r=s&&s.skipCodecCheck||-1!==t.indexOf(".mp3",t.length-4)&&engine_Engine.audioEngine.isMP3supported||-1!==t.indexOf(".ogg",t.length-4)&&engine_Engine.audioEngine.isOGGsupported||-1!==t.indexOf(".wav",t.length-4)||-1!==t.indexOf(".m4a",t.length-4)||-1!==t.indexOf(".mp4",t.length-4)||-1!==t.indexOf("blob:")){this._streaming?(this._htmlAudioElement=new Audio(t),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,tools_Tools.SetCorsBehavior(t,this._htmlAudioElement),this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",()=>{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()}),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,e=>{this._soundLoaded(e)},void 0,!0,!0,e=>{e&&logger_Logger.Error("XHR "+e.status+" error on: "+t+"."),logger_Logger.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:e=!1}e?!r&&(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):logger_Logger.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){logger_Logger.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),engine_Engine.audioEngine&&!engine_Engine.audioEngine.WarnedWebAudioUnsupported&&(logger_Logger.Error("Web Audio is not supported by your browser."),engine_Engine.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(null===(e=engine_Engine.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),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){var t;(null===(t=engine_Engine.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=engine_Engine.audioEngine)||void 0===t?void 0:t.audioContext)&&engine_Engine.audioEngine.audioContext.decodeAudioData(e,e=>{this._audioBufferLoaded(e)},e=>{logger_Logger.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)})}setAudioBuffer(e){var t;(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,r,s,a,n,o,l,h,c,u;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!==(r=e.useCustomAttenuation)&&void 0!==r?r:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(a=e.refDistance)&&void 0!==a?a:this.refDistance,this.distanceModel=null!==(n=e.distanceModel)&&void 0!==n?n:this.distanceModel,this._playbackRate=null!==(o=e.playbackRate)&&void 0!==o?o:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this.spatialSound=null!==(h=e.spatialSound)&&void 0!==h?h:this._spatialSound,this._setOffset(null!==(c=e.offset)&&void 0!==c?c:void 0),this.setVolume(null!==(u=e.volume)&&void 0!==u?u: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=engine_Engine.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&engine_Engine.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:engine_Engine.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,null===(e=this._soundPanner)||void 0===e||e.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?(this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor),this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){var e;(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=engine_Engine.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){if(t<e){logger_Logger.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=e,this._coneOuterAngle=t,this._coneOuterGain=i,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){var t;if(e!=this._coneInnerAngle){if(this._coneOuterAngle<e){logger_Logger.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=e,(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){var t;if(e!=this._coneOuterAngle){if(e<this._coneInnerAngle){logger_Logger.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneOuterAngle=e,(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}}setPosition(e){var t;!e.equals(this._position)&&(this._position.copyFrom(e),(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z))}setLocalDirectionToMesh(e){var t;this._localDirection=e,(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()}_updateDirection(){if(!this._connectedTransformNode||!this._soundPanner)return;let e=this._connectedTransformNode.getWorldMatrix(),t=math_vector_Vector3.TransformNormal(this._localDirection,e);t.normalize(),this._soundPanner.orientationX.value=t.x,this._soundPanner.orientationY.value=t.y,this._soundPanner.orientationZ.value=t.z}updateDistanceFromListener(){var e;if((null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){let e=this._scene.audioListenerPositionProvider?this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length():this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,e,this.maxDistance,this.refDistance,this.rolloffFactor)}}setAttenuationFunction(e){this._customAttenuationFunction=e}play(e,t,i){var r,s,a,n;if(this._isReadyToPlay&&this._scene.audioEnabled&&(null===(r=engine_Engine.audioEngine)||void 0===r?void 0:r.audioContext))try{this._clearTimeoutsAndObservers();let r=e?(null===(s=engine_Engine.audioEngine)||void 0===s?void 0:s.audioContext.currentTime)+e:null===(a=engine_Engine.audioEngine)||void 0===a?void 0:a.audioContext.currentTime;if((!this._soundSource||!this._streamingSource)&&this._spatialSound&&this._soundPanner&&(isNaN(this._position.x)||isNaN(this._position.y)||isNaN(this._position.z)||(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=engine_Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=()=>{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){let tryToPlay=()=>{var e,t;if(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.unlocked){let e=this._htmlAudioElement.play();void 0!==e&&e.catch(()=>{var e,t;null===(e=engine_Engine.audioEngine)||void 0===e||e.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))};tryToPlay()}}else{let tryToPlay=()=>{var s,a,n,o;if(null===(s=engine_Engine.audioEngine)||void 0===s?void 0:s.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){let e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=null===(a=engine_Engine.audioEngine)||void 0===a?void 0:a.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},r=e?(null===(n=engine_Engine.audioEngine)||void 0===n?void 0:n.audioContext.currentTime)+e:engine_Engine.audioEngine.audioContext.currentTime;let s=((this.isPaused?this.currentTime:0)+(null!==(o=this._offset)&&void 0!==o?o:0))%this._soundSource.buffer.duration;this._soundSource.start(r,s,this.loop?void 0:i)}}};(null===(n=engine_Engine.audioEngine)||void 0===n?void 0:n.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var e;(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.audioContext.state)==="suspended"?(engine_Engine.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=engine_Engine.audioEngine.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))):tryToPlay()},500):tryToPlay()}this._startTime=r,this.isPlaying=!0,this.isPaused=!1}catch(e){logger_Logger.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){var t;if(this.isPlaying){if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){let t=e?engine_Engine.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=()=>void 0),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1}else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>void 0,this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=engine_Engine.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=engine_Engine.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&engine_Engine.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(engine_Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,engine_Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,engine_Engine.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){let t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{let setBufferAndRun=()=>{this._isReadyToPlay?(t._audioBuffer=this.getAudioBuffer(),t._isReadyToPlay=!0,t.autoplay&&t.play(0,this._offset,this._length)):setTimeout(setBufferAndRun,300)},e={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},t=new Sound(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,e);return this.useCustomAttenuation&&t.setAttenuationFunction(this._customAttenuationFunction),t.setPosition(this._position),t.setPlaybackRate(this._playbackRate),setBufferAndRun(),t}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){let e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,r){let s,a;let n=e.name;s=e.url?i+e.url:i+n;let o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};if(r){let setBufferAndRun=()=>{r._isReadyToPlay?(a._audioBuffer=r.getAudioBuffer(),a._isReadyToPlay=!0,a.autoplay&&a.play(0,a._offset,a._length)):setTimeout(setBufferAndRun,300)};a=new Sound(n,new ArrayBuffer(0),t,null,o),setBufferAndRun()}else a=new Sound(n,s,t,()=>{t.removePendingData(a)},o),t.addPendingData(a);if(e.position){let t=math_vector_Vector3.FromArray(e.position);a.setPosition(t)}if(e.isDirectional&&(a.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){let t=math_vector_Vector3.FromArray(e.localDirectionToMesh);a.setLocalDirectionToMesh(t)}if(e.connectedMeshId){let i=t.getMeshById(e.connectedMeshId);i&&a.attachToMesh(i)}return e.metadata&&(a.metadata=e.metadata),a}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(null===(e=engine_Engine.audioEngine)||void 0===e||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}};Sound._SceneComponentInitialization=e=>{throw _WarnImport("AudioSceneComponent")};let SoundTrack=class SoundTrack{constructor(e,t={}){if(this.id=-1,this._isInitialized=!1,!(e=e||engineStore_EngineStore.LastCreatedScene))return;this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}_initializeSoundTrackAudioGraph(){var e;(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&engine_Engine.audioEngine.audioContext&&(this._outputAudioNode=engine_Engine.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(engine_Engine.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(engine_Engine.audioEngine&&engine_Engine.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=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){let t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){var t;(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToHRTF()}switchPanningModelToEqualPower(){var e;if(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToEqualPower()}connectToAnalyser(e){var t;this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=e,(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,engine_Engine.audioEngine.masterGain))}};AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_AUDIO,(e,t,i,r)=>{var s;let a;let n=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,l=e.sounds.length;o<l;o++){let l=e.sounds[o];(null===(s=engine_Engine.audioEngine)||void 0===s?void 0:s.canUseWebAudio)?(l.url||(l.url=l.name),n[l.url]?i.sounds.push(Sound.Parse(l,t,r,n[l.url])):(a=Sound.Parse(l,t,r),n[l.url]=a,i.sounds.push(a))):i.sounds.push(new Sound(l.name,null,t))}n=[]}),Object.defineProperty(scene_Scene.prototype,"mainSoundTrack",{get:function(){let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),this._mainSoundTrack||(this._mainSoundTrack=new SoundTrack(this,{mainTrack:!0})),this._mainSoundTrack},enumerable:!0,configurable:!0}),scene_Scene.prototype.getSoundByName=function(e){let t;for(t=0;t<this.mainSoundTrack.soundCollection.length;t++)if(this.mainSoundTrack.soundCollection[t].name===e)return this.mainSoundTrack.soundCollection[t];if(this.soundTracks){for(let i=0;i<this.soundTracks.length;i++)for(t=0;t<this.soundTracks[i].soundCollection.length;t++)if(this.soundTracks[i].soundCollection[t].name===e)return this.soundTracks[i].soundCollection[t]}return null},Object.defineProperty(scene_Scene.prototype,"audioEnabled",{get:function(){let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),e.audioEnabled},set:function(e){let t=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);t||(t=new AudioSceneComponent(this),this._addComponent(t)),e?t.enableAudio():t.disableAudio()},enumerable:!0,configurable:!0}),Object.defineProperty(scene_Scene.prototype,"headphone",{get:function(){let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),e.headphone},set:function(e){let t=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);t||(t=new AudioSceneComponent(this),this._addComponent(t)),e?t.switchAudioModeForHeadphones():t.switchAudioModeForNormalSpeakers()},enumerable:!0,configurable:!0}),Object.defineProperty(scene_Scene.prototype,"audioListenerPositionProvider",{get:function(){let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),e.audioListenerPositionProvider},set:function(e){let t=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);if(t||(t=new AudioSceneComponent(this),this._addComponent(t)),e&&"function"!=typeof e)throw Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");t.audioListenerPositionProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(scene_Scene.prototype,"audioListenerRotationProvider",{get:function(){let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),e.audioListenerRotationProvider},set:function(e){let t=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);if(t||(t=new AudioSceneComponent(this),this._addComponent(t)),e&&"function"!=typeof e)throw Error("The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3");t.audioListenerRotationProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(scene_Scene.prototype,"audioPositioningRefreshRate",{get:function(){let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),e.audioPositioningRefreshRate},set:function(e){let t=this._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);t||(t=new AudioSceneComponent(this),this._addComponent(t)),t.audioPositioningRefreshRate=e},enumerable:!0,configurable:!0});let AudioSceneComponent=class AudioSceneComponent{get audioEnabled(){return this._audioEnabled}get headphone(){return this._headphone}constructor(e){if(this.name=sceneComponent_SceneComponentConstants.NAME_AUDIO,this._audioEnabled=!0,this._headphone=!1,this.audioPositioningRefreshRate=500,this.audioListenerPositionProvider=null,this.audioListenerRotationProvider=null,this._cachedCameraDirection=new math_vector_Vector3,this._cachedCameraPosition=new math_vector_Vector3,this._lastCheck=0,this._invertMatrixTemp=new math_vector_Matrix,this._cameraDirectionTemp=new math_vector_Vector3,!(e=e||engineStore_EngineStore.LastCreatedScene))return;this.scene=e,e.soundTracks=[],e.sounds=[]}register(){this.scene._afterRenderStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDER_AUDIO,this,this._afterRender)}rebuild(){}serialize(e){if(e.sounds=[],this.scene.soundTracks)for(let t=0;t<this.scene.soundTracks.length;t++){let i=this.scene.soundTracks[t];for(let t=0;t<i.soundCollection.length;t++)e.sounds.push(i.soundCollection[t].serialize())}}addFromContainer(e){e.sounds&&e.sounds.forEach(e=>{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(){let e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].dispose()}disableAudio(){let e;let t=this.scene;for(this._audioEnabled=!1,engine_Engine.audioEngine&&engine_Engine.audioEngine.audioContext&&engine_Engine.audioEngine.audioContext.suspend(),e=0;e<t.mainSoundTrack.soundCollection.length;e++)t.mainSoundTrack.soundCollection[e].pause();if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(let i=0;i<t.soundTracks[e].soundCollection.length;i++)t.soundTracks[e].soundCollection[i].pause()}enableAudio(){let e;let t=this.scene;for(this._audioEnabled=!0,engine_Engine.audioEngine&&engine_Engine.audioEngine.audioContext&&engine_Engine.audioEngine.audioContext.resume(),e=0;e<t.mainSoundTrack.soundCollection.length;e++)t.mainSoundTrack.soundCollection[e].isPaused&&t.mainSoundTrack.soundCollection[e].play();if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(let i=0;i<t.soundTracks[e].soundCollection.length;i++)t.soundTracks[e].soundCollection[i].isPaused&&t.soundTracks[e].soundCollection[i].play()}switchAudioModeForHeadphones(){let e=this.scene;if(this._headphone=!0,e.mainSoundTrack.switchPanningModelToHRTF(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToHRTF()}switchAudioModeForNormalSpeakers(){let e=this.scene;if(this._headphone=!1,e.mainSoundTrack.switchPanningModelToEqualPower(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToEqualPower()}_afterRender(){let e=precisionDate_PrecisionDate.Now;if(this._lastCheck&&e-this._lastCheck<this.audioPositioningRefreshRate)return;this._lastCheck=e;let t=this.scene;if(!this._audioEnabled||!t._mainSoundTrack||!t.soundTracks||0===t._mainSoundTrack.soundCollection.length&&1===t.soundTracks.length)return;let i=engine_Engine.audioEngine;if(i&&i.audioContext){let e,r=t.activeCamera;if(t.activeCameras&&t.activeCameras.length>0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){let e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){let e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),math_vector_Vector3.TransformNormalToRef(AudioSceneComponent._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<t.mainSoundTrack.soundCollection.length;e++){let i=t.mainSoundTrack.soundCollection[e];i.useCustomAttenuation&&i.updateDistanceFromListener()}if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(let i=0;i<t.soundTracks[e].soundCollection.length;i++){let r=t.soundTracks[e].soundCollection[i];r.useCustomAttenuation&&r.updateDistanceFromListener()}}}};AudioSceneComponent._CameraDirection=new math_vector_Vector3(0,0,-1),Sound._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);t||(t=new AudioSceneComponent(e),e._addComponent(t))};let BakedVertexAnimationManager=class BakedVertexAnimationManager{constructor(e){if(this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,!(e=e||engineStore_EngineStore.LastCreatedScene))return;this._scene=e,this.animationParameters=new math_vector_Vector4(0,0,0,30)}_markSubMeshesAsAttributesDirty(){for(let e of this._scene.meshes)e.bakedVertexAnimationManager===this&&e._markSubMeshesAsAttributesDirty()}bind(e,t=!1){if(!this._texture||!this._isEnabled)return;let i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}clone(){let e=new BakedVertexAnimationManager(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,r=30){this.animationParameters=new math_vector_Vector4(e,t,i,r)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){decorators_SerializationHelper.Clone(()=>e,this)}serialize(){return decorators_SerializationHelper.Serialize(this)}parse(e,t,i){decorators_SerializationHelper.Parse(()=>this,e,t,i)}};__decorate([serializeAsTexture(),expandToProperty("_markSubMeshesAsAttributesDirty")],BakedVertexAnimationManager.prototype,"texture",void 0),__decorate([serialize(),expandToProperty("_markSubMeshesAsAttributesDirty")],BakedVertexAnimationManager.prototype,"isEnabled",void 0),__decorate([serialize()],BakedVertexAnimationManager.prototype,"animationParameters",void 0),__decorate([serialize()],BakedVertexAnimationManager.prototype,"time",void 0);let thinTexture_ThinTexture=class thinTexture_ThinTexture{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(null==e?void 0:e._shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Size.Zero(),this._cachedBaseSize=Size.Zero(),this._initialSamplingMode=2,this._texture=thinTexture_ThinTexture._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;this._texture._size&&(this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size)}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.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight):(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)}};let baseTexture_BaseTexture=class baseTexture_BaseTexture extends thinTexture_ThinTexture{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){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=guid_RandomGUID()),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=baseTexture_BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new observable_Observable,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?baseTexture_BaseTexture._IsScene(e)?this._scene=e:this._engine=e:this._scene=engineStore_EngineStore.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 math_vector_Matrix.IdentityReadOnly}getReflectionTextureMatrix(){return math_vector_Matrix.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,a){let n=this._getEngine();if(!n)return null;let o=n._getUseSRGBBuffer(!!s,t),l=n.getLoadedTexturesCache();for(let n=0;n<l.length;n++){let h=l[n];if((void 0===s||o===h._useSRGBBuffer)&&(void 0===r||r===h.invertY)&&h.url===e&&!t===h.generateMipMaps&&(!i||i===h.samplingMode)&&(void 0===a||a===h.isCube))return h.incrementReferences(),h}return null}_rebuild(){}clone(){return null}get textureType(){return this._texture&&void 0!==this._texture.type?this._texture.type:0}get textureFormat(){return this._texture&&void 0!==this._texture.format?this._texture.format:5}_markAllSubMeshesAsTexturesDirty(){let e=this.getScene();e&&e.markAllMaterialsAsDirty(1)}readPixels(e=0,t=0,i=null,r=!0,s=!1,a=0,n=0,o=Number.MAX_VALUE,l=Number.MAX_VALUE){if(!this._texture)return null;let h=this._getEngine();if(!h)return null;let c=this.getSize(),u=c.width,d=c.height;0!==t&&(u/=Math.pow(2,t),d/=Math.pow(2,t),u=Math.round(u),d=Math.round(d)),o=Math.min(u,o),l=Math.min(d,l);try{if(this._texture.isCube)return h._readTexturePixels(this._texture,o,l,e,t,i,r,s,a,n);return h._readTexturePixels(this._texture,o,l,-1,t,i,r,s,a,n)}catch(e){return null}}_readPixelsSync(e=0,t=0,i=null,r=!0,s=!1){if(!this._texture)return null;let a=this.getSize(),n=a.width,o=a.height,l=this._getEngine();if(!l)return null;0!=t&&(n/=Math.pow(2,t),o/=Math.pow(2,t),n=Math.round(n),o=Math.round(o));try{if(this._texture.isCube)return l._readTexturePixelsSync(this._texture,n,o,e,t,i,r,s);return l._readTexturePixelsSync(this._texture,n,o,-1,t,i,r,s)}catch(e){return null}}get _lodTextureHigh(){return this._texture?this._texture._lodTextureHigh:null}get _lodTextureMid(){return this._texture?this._texture._lodTextureMid:null}get _lodTextureLow(){return this._texture?this._texture._lodTextureLow:null}dispose(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);let e=this._scene.textures.indexOf(this);if(e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){let 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;let t=decorators_SerializationHelper.Serialize(this);return decorators_SerializationHelper.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0===i){t();return}for(let r=0;r<e.length;r++){let s=e[r];if(s.isReady())0==--i&&t();else{let e=s.onLoadObservable;e?e.addOnce(()=>{0==--i&&t()}):0==--i&&t()}}}static _IsScene(e){return"Scene"===e.getClassName()}};function GenerateBase64StringFromPixelData(e,t,i=!1){let r=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT,i=new Uint8Array(t);for(;--t>=0;){let r=e[t];r<0?r=0:r>1&&(r=1),i[t]=255*r}e=i}let a=document.createElement("canvas");a.width=r,a.height=s;let n=a.getContext("2d");if(!n)return null;let o=n.createImageData(r,s),l=o.data;if(l.set(e),n.putImageData(o,0,0),i){let e=document.createElement("canvas");e.width=r,e.height=s;let t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(a,0,0),e.toDataURL("image/png")):null}return a.toDataURL("image/png")}function GenerateBase64StringFromTexture(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=e._readPixelsSync(t,i);return s?GenerateBase64StringFromPixelData(s,e.getSize(),r.invertY):null}async function GenerateBase64StringFromTextureAsync(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=await e.readPixels(t,i);return s?GenerateBase64StringFromPixelData(s,e.getSize(),r.invertY):null}baseTexture_BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,__decorate([serialize()],baseTexture_BaseTexture.prototype,"uniqueId",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"name",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"metadata",void 0),__decorate([serialize("hasAlpha")],baseTexture_BaseTexture.prototype,"_hasAlpha",void 0),__decorate([serialize("getAlphaFromRGB")],baseTexture_BaseTexture.prototype,"_getAlphaFromRGB",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"level",void 0),__decorate([serialize("coordinatesIndex")],baseTexture_BaseTexture.prototype,"_coordinatesIndex",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"optimizeUVAllocation",void 0),__decorate([serialize("coordinatesMode")],baseTexture_BaseTexture.prototype,"_coordinatesMode",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"wrapU",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"wrapV",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"wrapR",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"anisotropicFilteringLevel",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"isCube",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"is3D",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"is2DArray",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"gammaSpace",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"invertZ",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"lodLevelInAlpha",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"lodGenerationOffset",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"lodGenerationScale",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"linearSpecularLOD",null),__decorate([serializeAsTexture()],baseTexture_BaseTexture.prototype,"irradianceTexture",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"isRenderTarget",void 0);let texture_Texture=class texture_Texture extends baseTexture_BaseTexture{static _CreateVideoTexture(e,t,i,r=!1,s=!1,a=texture_Texture.TRILINEAR_SAMPLINGMODE,n={},o,l=5){throw _WarnImport("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,r,s=texture_Texture.TRILINEAR_SAMPLINGMODE,a=null,n=null,o=null,l=!1,h,c,u,d,_){var p,f,m,g,v,x,b,T,S,C;let E;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 observable_Observable,this._isBlocking=!0,this.name=e||"",this.url=e;let y=!1,R=null,P=!0;"object"==typeof i&&null!==i?(E=null!==(p=i.noMipmap)&&void 0!==p&&p,r=null!==(f=i.invertY)&&void 0!==f?f:!CompatibilityOptions.UseOpenGLOrientationForUV,s=null!==(m=i.samplingMode)&&void 0!==m?m:texture_Texture.TRILINEAR_SAMPLINGMODE,a=null!==(g=i.onLoad)&&void 0!==g?g:null,n=null!==(v=i.onError)&&void 0!==v?v:null,o=null!==(x=i.buffer)&&void 0!==x?x:null,l=null!==(b=i.deleteBuffer)&&void 0!==b&&b,h=i.format,c=i.mimeType,u=i.loaderOptions,d=i.creationFlags,y=null!==(T=i.useSRGBBuffer)&&void 0!==T&&T,R=null!==(S=i.internalTexture)&&void 0!==S?S:null,P=null!==(C=i.gammaSpace)&&void 0!==C?C:P):E=!!i,this._gammaSpace=P,this._noMipmap=E,this._invertY=void 0===r?!CompatibilityOptions.UseOpenGLOrientationForUV:r,this._initialSamplingMode=s,this._buffer=o,this._deleteBuffer=l,this._mimeType=c,this._loaderOptions=u,this._creationFlags=d,this._useSRGBBuffer=y,this._forcedExtension=_,h&&(this._format=h);let A=this.getScene(),M=this._getEngine();if(!M)return;M.onBeforeTextureInitObservable.notifyObservers(this);let load=()=>{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),a&&a(),!this.isBlocking&&A&&A.resetCachedMaterial()},errorHandler=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},n&&n(e,t),texture_Texture.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!R){this._delayedOnLoad=load,this._delayedOnError=errorHandler;return}if(this._texture=null!=R?R:this._getFromCache(this.url,E,s,this._invertY,y,this.isCube),this._texture){if(this._texture.isReady)TimingTools.SetImmediate(()=>load());else{let e=this._texture.onLoadedObservable.add(load);this._texture.onErrorObservable.add(t=>{var i;errorHandler(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)})}}else if(A&&A.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=load,this._delayedOnError=errorHandler;else{try{this._texture=M.createTexture(this.url,E,this._invertY,A,s,load,errorHandler,this._buffer,void 0,this._format,this._forcedExtension,c,u,d,y)}catch(e){throw errorHandler("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,e=>e.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;let e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?TimingTools.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}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=math_vector_Matrix.Zero(),this._rowGenerationMatrix=new math_vector_Matrix,this._t0=math_vector_Vector3.Zero(),this._t1=math_vector_Vector3.Zero(),this._t2=math_vector_Vector3.Zero()),math_vector_Matrix.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(math_vector_Matrix.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,math_vector_TmpVectors.Matrix[0]),math_vector_Matrix.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,math_vector_TmpVectors.Matrix[1]),math_vector_Matrix.ScalingToRef(this._cachedUScale,this._cachedVScale,0,math_vector_TmpVectors.Matrix[2]),math_vector_Matrix.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,math_vector_TmpVectors.Matrix[3]),math_vector_TmpVectors.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(math_vector_TmpVectors.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),math_vector_Matrix.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));let t=this.getScene();return t&&this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){let e=this.getScene();if(!e||this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode&&(this.coordinatesMode!==texture_Texture.PROJECTION_MODE||this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag))return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=math_vector_Matrix.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=math_vector_Matrix.Zero());let 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 texture_Texture.PLANAR_MODE:math_vector_Matrix.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 texture_Texture.PROJECTION_MODE:{math_vector_Matrix.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);let t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:math_vector_Matrix.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){let 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 decorators_SerializationHelper.Clone(()=>new texture_Texture(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;let i=this.name;!texture_Texture.SerializeBuffers&&this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");let r=super.serialize(texture_Texture._SerializeInternalTextureUniqueId);return r?((texture_Texture.SerializeBuffers||texture_Texture.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(r.base64String=this._buffer,r.name=r.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?r.base64String="data:image/png;base64,"+stringTools_EncodeArrayBufferToBase64(this._buffer):(texture_Texture.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(r.base64String=!this._engine||this._engine._features.supportSyncTextureRead?GenerateBase64StringFromTexture(this):GenerateBase64StringFromTextureAsync(this))),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r._creationFlags=this._creationFlags,r._useSRGBBuffer=this._useSRGBBuffer,texture_Texture._SerializeInternalTextureUniqueId&&(r.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),r.noMipmap=this._noMipmap,this.name=i,r):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){let r;if(e.customType){let r=InstantiationTools.Instantiate(e.customType),s=r.Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return texture_Texture._CubeTextureParser(e,t,i);let s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;if(s){let i=t.getEngine().getLoadedTexturesCache();for(let t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}let onLoaded=t=>{var i;if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){let i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i<e.animations.length;i++){let r=e.animations[i],s=h["BABYLON.Animation"];s&&t.animations.push(s.Parse(r))}s&&!r&&(null===(i=null==t?void 0:t._texture)||void 0===i||i._setUniqueId(e.internalTextureUniqueId))},a=decorators_SerializationHelper.Parse(()=>{var s,a,n;let o=!0;if(e.noMipmap&&(o=!1),e.mirrorPlane){let i=texture_Texture._CreateMirror(e.name,e.renderTargetSize,t,o);return i._waitingRenderList=e.renderList,i.mirrorPlane=math_plane_Plane.FromArray(e.mirrorPlane),onLoaded(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i<t.reflectionProbes.length;i++){let r=t.reflectionProbes[i];if(r.name===e.name)return r.cubeTexture}}else(i=texture_Texture._CreateRenderTargetTexture(e.name,e.renderTargetSize,t,o,null!==(s=e._creationFlags)&&void 0!==s?s:0))._waitingRenderList=e.renderList;return onLoaded(i),i}if(e.isVideo){let r=texture_Texture._CreateVideoTexture(i+(e.url||e.name),i+(e.src||e.url),t,o,e.invertY,e.samplingMode,e.settings||{});return onLoaded(r),r}{let s;if(e.base64String&&!r)(s=texture_Texture.CreateFromBase64String(e.base64String,e.base64String,t,!o,e.invertY,e.samplingMode,()=>{onLoaded(s)},null!==(a=e._creationFlags)&&void 0!==a?a:0,null!==(n=e._useSRGBBuffer)&&void 0!==n&&n)).name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||texture_Texture.UseSerializedUrlIfAny)&&(a=e.url);let n={noMipmap:!o,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{onLoaded(s)},internalTexture:r};s=new texture_Texture(a,t,n)}return s}},e,t);return a}static CreateFromBase64String(e,t,i,r,s,a=texture_Texture.TRILINEAR_SAMPLINGMODE,n=null,o=null,l=5,h){return new texture_Texture("data:"+t,i,r,s,a,n,o,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,r=!1,s,a=!0,n=texture_Texture.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,c){return"data:"!==e.substr(0,5)&&(e="data:"+e),new texture_Texture(e,i,s,a,n,o,l,t,r,h,void 0,void 0,c)}};function _convertRGBtoRGBATextureData(e,t,i,r){let s;let a=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),a=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r<t;r++)for(let n=0;n<i;n++){let i=(n*t+r)*3,o=(n*t+r)*4;s[o+0]=e[i+0],s[o+1]=e[i+1],s[o+2]=e[i+2],s[o+3]=a}return s}function _makeCreateRawTextureFunction(e){return function(t,i,r,s,a,n,o,l,h=null,c=0){let u=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,d=e?$.Raw3D:$.Raw2DArray,_=new internalTexture_InternalTexture(this,d);_.baseWidth=i,_.baseHeight=r,_.baseDepth=s,_.width=i,_.height=r,_.depth=s,_.format=a,_.type=c,_.generateMipMaps=n,_.samplingMode=l,e?_.is3D=!0:_.is2DArray=!0,this._doNotHandleContextLost||(_._bufferView=t),e?this.updateRawTexture3D(_,t,a,o,h,c):this.updateRawTexture2DArray(_,t,a,o,h,c),this._bindTextureDirectly(u,_,!0);let p=this._getSamplingParameters(l,n);return this._gl.texParameteri(u,this._gl.TEXTURE_MAG_FILTER,p.mag),this._gl.texParameteri(u,this._gl.TEXTURE_MIN_FILTER,p.min),n&&this._gl.generateMipmap(u),this._bindTextureDirectly(u,null),this._internalTexturesCache.push(_),_}}function _makeUpdateRawTextureFunction(e){return function(t,i,r,s,a=null,n=0){let o=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,l=this._getWebGLTextureType(n),h=this._getInternalFormat(r),c=this._getRGBABufferInternalSizedFormat(n,r);this._bindTextureDirectly(o,t,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(t._bufferView=i,t.format=r,t.invertY=s,t._compression=a),t.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),a&&i?this._gl.compressedTexImage3D(o,0,this.getCaps().s3tc[a],t.width,t.height,t.depth,0,i):this._gl.texImage3D(o,0,c,t.width,t.height,t.depth,0,h,l,i),t.generateMipMaps&&this._gl.generateMipmap(o),this._bindTextureDirectly(o,null),t.isReady=!0}}texture_Texture.SerializeBuffers=!0,texture_Texture.ForceSerializeBuffers=!1,texture_Texture.OnTextureLoadErrorObservable=new observable_Observable,texture_Texture._SerializeInternalTextureUniqueId=!1,texture_Texture._CubeTextureParser=(e,t,i)=>{throw _WarnImport("CubeTexture")},texture_Texture._CreateMirror=(e,t,i,r)=>{throw _WarnImport("MirrorTexture")},texture_Texture._CreateRenderTargetTexture=(e,t,i,r,s)=>{throw _WarnImport("RenderTargetTexture")},texture_Texture.NEAREST_SAMPLINGMODE=1,texture_Texture.NEAREST_NEAREST_MIPLINEAR=8,texture_Texture.BILINEAR_SAMPLINGMODE=2,texture_Texture.LINEAR_LINEAR_MIPNEAREST=11,texture_Texture.TRILINEAR_SAMPLINGMODE=3,texture_Texture.LINEAR_LINEAR_MIPLINEAR=3,texture_Texture.NEAREST_NEAREST_MIPNEAREST=4,texture_Texture.NEAREST_LINEAR_MIPNEAREST=5,texture_Texture.NEAREST_LINEAR_MIPLINEAR=6,texture_Texture.NEAREST_LINEAR=7,texture_Texture.NEAREST_NEAREST=1,texture_Texture.LINEAR_NEAREST_MIPNEAREST=9,texture_Texture.LINEAR_NEAREST_MIPLINEAR=10,texture_Texture.LINEAR_LINEAR=2,texture_Texture.LINEAR_NEAREST=12,texture_Texture.EXPLICIT_MODE=0,texture_Texture.SPHERICAL_MODE=1,texture_Texture.PLANAR_MODE=2,texture_Texture.CUBIC_MODE=3,texture_Texture.PROJECTION_MODE=4,texture_Texture.SKYBOX_MODE=5,texture_Texture.INVCUBIC_MODE=6,texture_Texture.EQUIRECTANGULAR_MODE=7,texture_Texture.FIXED_EQUIRECTANGULAR_MODE=8,texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,texture_Texture.CLAMP_ADDRESSMODE=0,texture_Texture.WRAP_ADDRESSMODE=1,texture_Texture.MIRROR_ADDRESSMODE=2,texture_Texture.UseSerializedUrlIfAny=!1,__decorate([serialize()],texture_Texture.prototype,"url",void 0),__decorate([serialize()],texture_Texture.prototype,"uOffset",void 0),__decorate([serialize()],texture_Texture.prototype,"vOffset",void 0),__decorate([serialize()],texture_Texture.prototype,"uScale",void 0),__decorate([serialize()],texture_Texture.prototype,"vScale",void 0),__decorate([serialize()],texture_Texture.prototype,"uAng",void 0),__decorate([serialize()],texture_Texture.prototype,"vAng",void 0),__decorate([serialize()],texture_Texture.prototype,"wAng",void 0),__decorate([serialize()],texture_Texture.prototype,"uRotationCenter",void 0),__decorate([serialize()],texture_Texture.prototype,"vRotationCenter",void 0),__decorate([serialize()],texture_Texture.prototype,"wRotationCenter",void 0),__decorate([serialize()],texture_Texture.prototype,"homogeneousRotationInUVTransform",void 0),__decorate([serialize()],texture_Texture.prototype,"isBlocking",null),h["BABYLON.Texture"]=texture_Texture,decorators_SerializationHelper._TextureParser=texture_Texture.Parse,ThinEngine.prototype.updateRawTexture=function(e,t,i,r,s=null,a=0,n=!1){if(!e)return;let o=this._getRGBABufferInternalSizedFormat(a,i,n),l=this._getInternalFormat(i),h=this._getWebGLTextureType(a);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=a,e.invertY=r,e._compression=s),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},ThinEngine.prototype.createRawTexture=function(e,t,i,r,s,a,n,o=null,l=0,h=0,c=!1){let u=new internalTexture_InternalTexture(this,$.Raw);u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=r,u.generateMipMaps=s,u.samplingMode=n,u.invertY=a,u._compression=o,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture(u,e,r,a,o,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);let d=this._getSamplingParameters(n,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},ThinEngine.prototype.createRawCubeTexture=function(e,t,i,r,s,a,n,o=null){let l=this._gl,h=new internalTexture_InternalTexture(this,$.CubeRaw);h.isCube=!0,h.format=i,h.type=r,this._doNotHandleContextLost||(h._bufferViewArray=e);let c=this._getWebGLTextureType(r),u=this._getInternalFormat(i);u===l.RGB&&(u=l.RGBA),c!==l.FLOAT||this._caps.textureFloatLinearFiltering?c!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?c!==l.FLOAT||this._caps.textureFloatRender?c!==l.HALF_FLOAT||this._caps.colorBufferFloat||(s=!1,logger_Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(s=!1,logger_Logger.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(s=!1,n=1,logger_Logger.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(s=!1,n=1,logger_Logger.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")),h.width=t,h.height=t,h.invertY=a,h._compression=o;let d=!this.needPOTTextures||tools_Tools.IsExponentOfTwo(h.width)&&tools_Tools.IsExponentOfTwo(h.height);if(d||(s=!1),e)this.updateRawCubeTexture(h,e,i,r,a,o);else{let e=this._getRGBABufferInternalSizedFormat(r);this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let t=0;t<6;t++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this.getCaps().s3tc[o],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,e,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);let _=this._getSamplingParameters(n,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,_.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,_.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=s,h.samplingMode=n,h.isReady=!0,h},ThinEngine.prototype.updateRawCubeTexture=function(e,t,i,r,s,a=null,n=0){e._bufferViewArray=t,e.format=i,e.type=r,e.invertY=s,e._compression=a;let o=this._gl,l=this._getWebGLTextureType(r),h=this._getInternalFormat(i),c=this._getRGBABufferInternalSizedFormat(r),u=!1;h===o.RGB&&(h=o.RGBA,u=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===s||!!s),e.width%4!=0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let s=t[i];a?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,n,this.getCaps().s3tc[a],e.width,e.height,0,s):(u&&(s=_convertRGBtoRGBATextureData(s,e.width,e.height,r)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,n,c,e.width,e.height,0,h,l,s))}let d=!this.needPOTTextures||tools_Tools.IsExponentOfTwo(e.width)&&tools_Tools.IsExponentOfTwo(e.height);d&&e.generateMipMaps&&0===n&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},ThinEngine.prototype.createRawCubeTextureFromUrl=function(e,t,i,r,s,a,n,o,l=null,h=null,c=3,u=!1){let d=this._gl,_=this.createRawCubeTexture(null,i,r,s,!a,u,c,null);null==t||t.addPendingData(_),_.url=e,_.isReady=!1,this._internalTexturesCache.push(_);let internalCallback=e=>{let i=_.width,a=n(e);if(a){if(o){let e=this._getWebGLTextureType(s),t=this._getInternalFormat(r),n=this._getRGBABufferInternalSizedFormat(s),l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);let h=o(a);for(let r=0;r<h.length;r++){let a=i>>r;for(let i=0;i<6;i++){let o=h[r][i];l&&(o=_convertRGBtoRGBATextureData(o,a,a,s)),d.texImage2D(i,r,n,a,a,0,t,e,o)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(_,a,r,s,u);_.isReady=!0,null==t||t.removePendingData(_),_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,e=>{internalCallback(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(_),h&&e&&h(e.status+" "+e.statusText,i)}),_},ThinEngine.prototype.createRawTexture2DArray=_makeCreateRawTextureFunction(!1),ThinEngine.prototype.createRawTexture3D=_makeCreateRawTextureFunction(!0),ThinEngine.prototype.updateRawTexture2DArray=_makeUpdateRawTextureFunction(!1),ThinEngine.prototype.updateRawTexture3D=_makeUpdateRawTextureFunction(!0);let rawTexture_RawTexture=class rawTexture_RawTexture extends texture_Texture{constructor(e,t,i,r,s,a=!0,n=!1,o=3,l=0,h,c){if(super(null,s,!a,n,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=r,!this._engine)return;this._engine._caps.textureFloatLinearFiltering||1!==l||(o=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(o=1),this._texture=this._engine.createRawTexture(e,t,i,r,a,n,o,null,l,null!=h?h:0,null!=c&&c),this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.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,r,s=!0,a=!1,n=3){return new rawTexture_RawTexture(e,t,i,1,r,s,a,n)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,a=!1,n=3){return new rawTexture_RawTexture(e,t,i,2,r,s,a,n)}static CreateAlphaTexture(e,t,i,r,s=!0,a=!1,n=3){return new rawTexture_RawTexture(e,t,i,0,r,s,a,n)}static CreateRGBTexture(e,t,i,r,s=!0,a=!1,n=3,o=0,l=0,h=!1){return new rawTexture_RawTexture(e,t,i,4,r,s,a,n,o,l,h)}static CreateRGBATexture(e,t,i,r,s=!0,a=!1,n=3,o=0,l=0,h=!1){return new rawTexture_RawTexture(e,t,i,5,r,s,a,n,o,l,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,a=!1,n=3,o=0,l=!1){return new rawTexture_RawTexture(e,t,i,5,r,s,a,n,o,1,l)}static CreateRTexture(e,t,i,r,s=!0,a=!1,n=texture_Texture.TRILINEAR_SAMPLINGMODE,o=1){return new rawTexture_RawTexture(e,t,i,6,r,s,a,n,o)}static CreateRStorageTexture(e,t,i,r,s=!0,a=!1,n=texture_Texture.TRILINEAR_SAMPLINGMODE,o=1){return new rawTexture_RawTexture(e,t,i,6,r,s,a,n,o,1)}};let AutoRotationBehavior=class AutoRotationBehavior{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;let t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===pointerEvents_PointerEventTypes.POINTERDOWN){this._isPointerDown=!0;return}e.type===pointerEvents_PointerEventTypes.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;let e=precisionDate_PrecisionDate.Now,t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();let i=e-this._lastInteractionTime-this._idleRotationWaitTime,r=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*r,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))})}detach(){if(!this._attachedCamera)return;let 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:precisionDate_PrecisionDate.Now}_reachTargetAlpha(){return!!this._attachedCamera&&!!this.targetAlpha&&.001>Math.abs(this._attachedCamera.alpha-this.targetAlpha)}_userIsZooming(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset}_shouldAnimationStopForInteraction(){if(!this._attachedCamera)return!1;let e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()}_applyUserInteraction(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=precisionDate_PrecisionDate.Now)}_userIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}};let BouncingBehavior=class BouncingBehavior{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=[]}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;let t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(e=>{if(!e)return;e.computeWorldMatrix(!0);let 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||(BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode),this._radiusBounceTransition=animation_Animation.CreateAnimation("radius",animation_Animation.ANIMATIONTYPE_FLOAT,60,BouncingBehavior.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;let t=animation_Animation.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()}};BouncingBehavior.EasingFunction=new BackEase(.3),BouncingBehavior.EasingMode=EasingFunction.EASINGMODE_EASEOUT;let FramingBehavior=class FramingBehavior{constructor(){this.onTargetFramingAnimationEndObservable=new observable_Observable,this._mode=FramingBehavior.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=[],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;let t=this._attachedCamera.getScene();FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===pointerEvents_PointerEventTypes.POINTERDOWN){this._isPointerDown=!0;return}e.type===pointerEvents_PointerEventTypes.POINTERUP&&(this._isPointerDown=!1)}),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;let 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);let r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){let r=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new math_vector_Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t<e.length;t++){let i=e[t].getHierarchyBoundingVectors(!0);math_vector_Vector3.CheckExtends(i.min,r,s),math_vector_Vector3.CheckExtends(i.max,r,s)}this.zoomOnBoundingInfo(r,s,t,i)}zoomOnBoundingInfo(e,t,i=!1,r=null){let s;if(!this._attachedCamera)return!1;let a=e.y,n=t.y,o=a+(n-a)*this._positionScale,l=t.subtract(e).scale(.5);if(i)s=new math_vector_Vector3(0,o,0);else{let t=e.add(l);s=new math_vector_Vector3(t.x,o,t.z)}this._vectorTransition||(this._vectorTransition=animation_Animation.CreateAnimation("target",animation_Animation.ANIMATIONTYPE_VECTOR3,60,FramingBehavior.EasingFunction)),this._betaIsAnimating=!0;let h=animation_Animation.TransitionTo("target",s,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);h&&this._animatables.push(h);let c=0;if(this._mode===FramingBehavior.FitFrustumSidesMode){let i=this._calculateLowerRadiusFromModelBoundingSphere(e,t);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=l.length()+this._attachedCamera.minZ),c=i}else this._mode===FramingBehavior.IgnoreBoundsSizeMode&&(c=this._calculateLowerRadiusFromModelBoundingSphere(e,t),this.autoCorrectCameraLimitsAndSensibility&&null===this._attachedCamera.lowerRadiusLimit&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){let i=t.subtract(e).length();this._attachedCamera.panningSensibility=5e3/i,this._attachedCamera.wheelPrecision=100/c}return this._radiusTransition||(this._radiusTransition=animation_Animation.CreateAnimation("radius",animation_Animation.ANIMATIONTYPE_FLOAT,60,FramingBehavior.EasingFunction)),(h=animation_Animation.TransitionTo("radius",c,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,()=>{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}))&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){let i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===FramingBehavior.IgnoreBoundsSizeMode&&(r=r<i.lowerRadiusLimit?i.lowerRadiusLimit:r),i.upperRadiusLimit&&(r=r>i.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;let e=precisionDate_PrecisionDate.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>.5*Math.PI&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=animation_Animation.CreateAnimation("beta",animation_Animation.ANIMATIONTYPE_FLOAT,60,FramingBehavior.EasingFunction));let e=animation_Animation.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=precisionDate_PrecisionDate.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)}};FramingBehavior.EasingFunction=new ExponentialEase,FramingBehavior.EasingMode=EasingFunction.EASINGMODE_EASEINOUT,FramingBehavior.IgnoreBoundsSizeMode=0,FramingBehavior.FitFrustumSidesMode=1;let ray_Ray=class ray_Ray{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new ray_Ray(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){let r,s,a,n;let o=ray_Ray._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),l=ray_Ray._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i),h=0,c=Number.MAX_VALUE;if(1e-7>Math.abs(this.direction.x)){if(this.origin.x<o.x||this.origin.x>l.x)return!1}else if(r=1/this.direction.x,s=(o.x-this.origin.x)*r,(a=(l.x-this.origin.x)*r)==-1/0&&(a=1/0),s>a&&(n=s,s=a,a=n),(h=Math.max(s,h))>(c=Math.min(a,c)))return!1;if(1e-7>Math.abs(this.direction.y)){if(this.origin.y<o.y||this.origin.y>l.y)return!1}else if(r=1/this.direction.y,s=(o.y-this.origin.y)*r,(a=(l.y-this.origin.y)*r)==-1/0&&(a=1/0),s>a&&(n=s,s=a,a=n),(h=Math.max(s,h))>(c=Math.min(a,c)))return!1;if(1e-7>Math.abs(this.direction.z)){if(this.origin.z<o.z||this.origin.z>l.z)return!1}else if(r=1/this.direction.z,s=(o.z-this.origin.z)*r,(a=(l.z-this.origin.z)*r)==-1/0&&(a=1/0),s>a&&(n=s,s=a,a=n),(h=Math.max(s,h))>(c=Math.min(a,c)))return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){let i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,a=i*i+r*r+s*s,n=e.radius+t,o=n*n;if(a<=o)return!0;let l=i*this.direction.x+r*this.direction.y+s*this.direction.z;return!(l<0)&&a-l*l<=o}intersectsTriangle(e,t,i){let r=ray_Ray._TmpVector3[0],s=ray_Ray._TmpVector3[1],a=ray_Ray._TmpVector3[2],n=ray_Ray._TmpVector3[3],o=ray_Ray._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),math_vector_Vector3.CrossToRef(this.direction,s,a);let l=math_vector_Vector3.Dot(r,a);if(0===l)return null;let h=1/l;this.origin.subtractToRef(e,n);let c=math_vector_Vector3.Dot(n,a)*h;if(c<0||c>1)return null;math_vector_Vector3.CrossToRef(n,r,o);let u=math_vector_Vector3.Dot(this.direction,o)*h;if(u<0||c+u>1)return null;let d=math_vector_Vector3.Dot(s,o)*h;return d>this.length?null:new IntersectionInfo(1-c-u,c,d)}intersectsPlane(e){let t;let i=math_vector_Vector3.Dot(e.normal,this.direction);if(999999997475243e-21>Math.abs(i))return null;{let r=math_vector_Vector3.Dot(e.normal,this.origin);return(t=(-e.d-r)/i)<0?t<-.000000999999997475243?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{let e=(this.origin.y-t)/this.direction.y;if(e>0)return null;return new math_vector_Vector3(this.origin.x+-(this.direction.x*e),t,this.origin.z+-(this.direction.z*e))}case"x":{let e=(this.origin.x-t)/this.direction.x;if(e>0)return null;return new math_vector_Vector3(t,this.origin.y+-(this.direction.y*e),this.origin.z+-(this.direction.z*e))}case"z":{let e=(this.origin.z-t)/this.direction.z;if(e>0)return null;return new math_vector_Vector3(this.origin.x+-(this.direction.x*e),this.origin.y+-(this.direction.y*e),t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,a=!1){let n=math_vector_TmpVectors.Matrix[0];return e.getWorldMatrix().invertToRef(n),this._tmpRay?ray_Ray.TransformToRef(this,n,this._tmpRay):this._tmpRay=ray_Ray.Transform(this,n),e.intersects(this._tmpRay,t,i,r,s,a)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;r<e.length;r++){let s=this.intersectsMesh(e[r],t);s.hit&&i.push(s)}return i.sort(this._comparePickingInfo),i}_comparePickingInfo(e,t){return e.distance<t.distance?-1:e.distance>t.distance?1:0}intersectionSegment(e,t,i){let r=this.origin,s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[1],n=math_vector_TmpVectors.Vector3[2],o=math_vector_TmpVectors.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(ray_Ray._Rayl,n),r.addToRef(n,a),e.subtractToRef(r,o);let l=math_vector_Vector3.Dot(s,s),h=math_vector_Vector3.Dot(s,n),c=math_vector_Vector3.Dot(n,n),u=math_vector_Vector3.Dot(s,o),d=math_vector_Vector3.Dot(n,o),_=l*c-h*h,p,f=_,m,g=_;_<ray_Ray._Smallnum?(p=0,f=1,m=d,g=c):(p=h*d-c*u,m=l*d-h*u,p<0?(p=0,m=d,g=c):p>f&&(p=f,m=d+h,g=c)),m<0?(m=0,0>-u?p=0:-u>l?p=f:(p=-u,f=l)):m>g&&(m=g,-u+h<0?p=0:-u+h>l?p=f:(p=-u+h,f=l));let v=Math.abs(p)<ray_Ray._Smallnum?0:p/f,x=Math.abs(m)<ray_Ray._Smallnum?0:m/g,b=math_vector_TmpVectors.Vector3[4];n.scaleToRef(x,b);let T=math_vector_TmpVectors.Vector3[5];s.scaleToRef(v,T),T.addInPlace(o);let S=math_vector_TmpVectors.Vector3[6];T.subtractToRef(b,S);let C=x>0&&x<=this.length&&S.lengthSquared()<i*i;return C?T.length():-1}update(e,t,i,r,s,a,n,o=!1){if(o){ray_Ray._RayDistant||(ray_Ray._RayDistant=ray_Ray.Zero()),ray_Ray._RayDistant.unprojectRayToRef(e,t,i,r,math_vector_Matrix.IdentityReadOnly,a,n);let o=math_vector_TmpVectors.Matrix[0];s.invertToRef(o),ray_Ray.TransformToRef(ray_Ray._RayDistant,o,this)}else this.unprojectRayToRef(e,t,i,r,s,a,n);return this}static Zero(){return new ray_Ray(math_vector_Vector3.Zero(),math_vector_Vector3.Zero())}static CreateNew(e,t,i,r,s,a,n){let o=ray_Ray.Zero();return o.update(e,t,i,r,s,a,n)}static CreateNewFromTo(e,t,i=math_vector_Matrix.IdentityReadOnly){let r=t.subtract(e),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),ray_Ray.Transform(new ray_Ray(e,r,s),i)}static Transform(e,t){let i=new ray_Ray(new math_vector_Vector3(0,0,0),new math_vector_Vector3(0,0,0));return ray_Ray.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){math_vector_Vector3.TransformCoordinatesToRef(e.origin,t,i.origin),math_vector_Vector3.TransformNormalToRef(e.direction,t,i.direction),i.length=e.length;let r=i.direction,s=r.length();if(!(0===s||1===s)){let e=1/s;r.x*=e,r.y*=e,r.z*=e,i.length*=s}}unprojectRayToRef(e,t,i,r,s,a,n){let o=math_vector_TmpVectors.Matrix[0];s.multiplyToRef(a,o),o.multiplyToRef(n,o),o.invert();let l=engineStore_EngineStore.LastCreatedEngine,h=math_vector_TmpVectors.Vector3[0];h.x=e/i*2-1,h.y=-(t/r*2-1),h.z=(null==l?void 0:l.useReverseDepthBuffer)?1:(null==l?void 0:l.isNDCHalfZRange)?0:-1;let c=math_vector_TmpVectors.Vector3[1].copyFromFloats(h.x,h.y,1-1e-8),u=math_vector_TmpVectors.Vector3[2],d=math_vector_TmpVectors.Vector3[3];math_vector_Vector3._UnprojectFromInvertedMatrixToRef(h,o,u),math_vector_Vector3._UnprojectFromInvertedMatrixToRef(c,o,d),this.origin.copyFrom(u),d.subtractToRef(u,this.direction),this.direction.normalize()}};ray_Ray._TmpVector3=arrayTools_ArrayTools.BuildArray(6,math_vector_Vector3.Zero),ray_Ray._RayDistant=ray_Ray.Zero(),ray_Ray._Smallnum=1e-8,ray_Ray._Rayl=1e9,scene_Scene.prototype.createPickingRay=function(e,t,i,r,s=!1){let a=ray_Ray.Zero();return this.createPickingRayToRef(e,t,i,a,r,s),a},scene_Scene.prototype.createPickingRayToRef=function(e,t,i,r,s,a=!1,n=!1){let o=this.getEngine();if(!s){if(!this.activeCamera)return this;s=this.activeCamera}let l=s.viewport,h=l.toGlobal(o.getRenderWidth(),o.getRenderHeight());return e=e/o.getHardwareScalingLevel()-h.x,t=t/o.getHardwareScalingLevel()-(o.getRenderHeight()-h.y-h.height),r.update(e,t,h.width,h.height,i||math_vector_Matrix.IdentityReadOnly,a?math_vector_Matrix.IdentityReadOnly:s.getViewMatrix(),s.getProjectionMatrix(),n),this},scene_Scene.prototype.createPickingRayInCameraSpace=function(e,t,i){let r=ray_Ray.Zero();return this.createPickingRayInCameraSpaceToRef(e,t,r,i),r},scene_Scene.prototype.createPickingRayInCameraSpaceToRef=function(e,t,i,r){if(!PickingInfo)return this;let s=this.getEngine();if(!r){if(!this.activeCamera)throw Error("Active camera not set");r=this.activeCamera}let a=r.viewport,n=a.toGlobal(s.getRenderWidth(),s.getRenderHeight()),o=math_vector_Matrix.Identity();return e=e/s.getHardwareScalingLevel()-n.x,t=t/s.getHardwareScalingLevel()-(s.getRenderHeight()-n.y-n.height),i.update(e,t,n.width,n.height,o,o,r.getProjectionMatrix()),this},scene_Scene.prototype._internalPickForMesh=function(e,t,i,r,s,a,n,o){let l=t(r,i.enableDistantPicking),h=i.intersects(l,s,n,a,r,o);return h&&h.hit&&(s||null==e||!(h.distance>=e.distance))?h:null},scene_Scene.prototype._internalPick=function(e,t,i,r,s){let a=null,n=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l<this.meshes.length;l++){let h=this.meshes[l];if(t){if(!t(h))continue}else if(!h.isEnabled()||!h.isVisible||!h.isPickable)continue;let c=n&&h.isWorldMatrixCameraDependent(),u=h.computeWorldMatrix(c,o);if(h.hasThinInstances&&h.thinInstanceEnablePicking){let t=this._internalPickForMesh(a,e,h,u,!0,!0,s);if(t){if(r)return t;let n=math_vector_TmpVectors.Matrix[1],o=h.thinInstanceGetWorldMatrices();for(let t=0;t<o.length;t++){let l=o[t];l.multiplyToRef(u,n);let c=this._internalPickForMesh(a,e,h,n,i,r,s,!0);if(c&&((a=c).thinInstanceIndex=t,i))return a}}}else{let t=this._internalPickForMesh(a,e,h,u,i,r,s);if(t&&(a=t,i))return a}}return a||new PickingInfo},scene_Scene.prototype._internalMultiPick=function(e,t,i){if(!PickingInfo)return null;let r=[],s=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let n=0;n<this.meshes.length;n++){let o=this.meshes[n];if(t){if(!t(o))continue}else if(!o.isEnabled()||!o.isVisible||!o.isPickable)continue;let l=s&&o.isWorldMatrixCameraDependent(),h=o.computeWorldMatrix(l,a);if(o.hasThinInstances&&o.thinInstanceEnablePicking){let t=this._internalPickForMesh(null,e,o,h,!0,!0,i);if(t){let t=math_vector_TmpVectors.Matrix[1],s=o.thinInstanceGetWorldMatrices();for(let a=0;a<s.length;a++){let n=s[a];n.multiplyToRef(h,t);let l=this._internalPickForMesh(null,e,o,t,!1,!1,i,!0);l&&(l.thinInstanceIndex=a,r.push(l))}}}else{let t=this._internalPickForMesh(null,e,o,h,!1,!1,i);t&&r.push(t)}}return r},scene_Scene.prototype.pickWithBoundingInfo=function(e,t,i,r,s){if(!PickingInfo)return null;let a=this._internalPick(i=>(this._tempPickingRay||(this._tempPickingRay=ray_Ray.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null),this._tempPickingRay),i,r,!0);return a&&(a.ray=this.createPickingRay(e,t,math_vector_Matrix.Identity(),s||null)),a},Object.defineProperty(scene_Scene.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),scene_Scene.prototype.pick=function(e,t,i,r,s,a,n=!1){let o=this._internalPick((i,r)=>(this._tempPickingRay||(this._tempPickingRay=ray_Ray.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null,!1,r),this._tempPickingRay),i,r,!1,a);return o&&(o.ray=this.createPickingRay(e,t,math_vector_Matrix.Identity(),s||null)),o},scene_Scene.prototype.pickWithRay=function(e,t,i,r){let s=this._internalPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=math_vector_Matrix.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ray_Ray.Zero()),ray_Ray.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i,!1,r);return s&&(s.ray=e),s},scene_Scene.prototype.multiPick=function(e,t,i,r,s){return this._internalMultiPick(i=>this.createPickingRay(e,t,i,r||null),i,s)},scene_Scene.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=math_vector_Matrix.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ray_Ray.Zero()),ray_Ray.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i)},camera_Camera.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new ray_Ray(math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),e),e,t,i)},camera_Camera.prototype.getForwardRayToRef=function(e,t=100,i,r){return i||(i=this.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(this.position),math_vector_TmpVectors.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),math_vector_Vector3.TransformNormalToRef(math_vector_TmpVectors.Vector3[2],i,math_vector_TmpVectors.Vector3[3]),math_vector_Vector3.NormalizeToRef(math_vector_TmpVectors.Vector3[3],e.direction),e};let pivotTools_PivotTools=class pivotTools_PivotTools{static _RemoveAndStorePivotPoint(e){e&&0===pivotTools_PivotTools._PivotCached&&(e.getPivotPointToRef(pivotTools_PivotTools._OldPivotPoint),pivotTools_PivotTools._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,pivotTools_PivotTools._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(math_vector_Matrix.IdentityReadOnly),pivotTools_PivotTools._OldPivotPoint.subtractToRef(e.getPivotPoint(),pivotTools_PivotTools._PivotTranslation),pivotTools_PivotTools._PivotTmpVector.copyFromFloats(1,1,1),pivotTools_PivotTools._PivotTmpVector.subtractInPlace(e.scaling),pivotTools_PivotTools._PivotTmpVector.multiplyInPlace(pivotTools_PivotTools._PivotTranslation),e.position.addInPlace(pivotTools_PivotTools._PivotTmpVector))),pivotTools_PivotTools._PivotCached++}static _RestorePivotPoint(e){e&&!pivotTools_PivotTools._OldPivotPoint.equalsToFloats(0,0,0)&&1===pivotTools_PivotTools._PivotCached&&(e.setPivotPoint(pivotTools_PivotTools._OldPivotPoint),e._postMultiplyPivotMatrix=pivotTools_PivotTools._PivotPostMultiplyPivotMatrix,pivotTools_PivotTools._PivotTmpVector.copyFromFloats(1,1,1),pivotTools_PivotTools._PivotTmpVector.subtractInPlace(e.scaling),pivotTools_PivotTools._PivotTmpVector.multiplyInPlace(pivotTools_PivotTools._PivotTranslation),e.position.subtractInPlace(pivotTools_PivotTools._PivotTmpVector)),this._PivotCached--}};function CreatePlaneVertexData(e){let t=[],i=[],r=[],s=[],a=e.width||e.size||1,n=e.height||e.size||1,o=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,l=a/2,h=n/2;i.push(-l,-h,0),r.push(0,0,-1),s.push(0,CompatibilityOptions.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),r.push(0,0,-1),s.push(1,CompatibilityOptions.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),r.push(0,0,-1),s.push(1,CompatibilityOptions.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),r.push(0,0,-1),s.push(0,CompatibilityOptions.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),mesh_vertexData_VertexData._ComputeSides(o,i,t,r,s,e.frontUVs,e.backUVs);let c=new mesh_vertexData_VertexData;return c.indices=t,c.positions=i,c.normals=r,c.uvs=s,c}function planeBuilder_CreatePlane(e,t={},i=null){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreatePlaneVertexData(t);return s.applyToMesh(r,t.updatable),t.sourcePlane&&(r.translate(t.sourcePlane.normal,-t.sourcePlane.d),r.setDirection(t.sourcePlane.normal.scale(-1))),r}pivotTools_PivotTools._PivotCached=0,pivotTools_PivotTools._OldPivotPoint=new math_vector_Vector3,pivotTools_PivotTools._PivotTranslation=new math_vector_Vector3,pivotTools_PivotTools._PivotTmpVector=new math_vector_Vector3,pivotTools_PivotTools._PivotPostMultiplyPivotMatrix=!1,mesh_vertexData_VertexData.CreatePlane=CreatePlaneVertexData,mesh_Mesh.CreatePlane=(e,t,i,r,s)=>planeBuilder_CreatePlane(e,{size:t,width:t,height:t,sideOrientation:s,updatable:r},i);let pointerDragBehavior_PointerDragBehavior=class pointerDragBehavior_PointerDragBehavior{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 observable_Observable,this.onDragStartObservable=new observable_Observable,this.onDragEndObservable=new observable_Observable,this.onEnabledObservable=new observable_Observable,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new math_vector_Vector3(0,0,0),this._alternatePickedPoint=new math_vector_Vector3(0,0,0),this._worldDragAxis=new math_vector_Vector3(0,0,0),this._targetPosition=new math_vector_Vector3(0,0,0),this._attachedToElement=!1,this._startDragRay=new ray_Ray(new math_vector_Vector3,new math_vector_Vector3),this._lastPointerRay={},this._dragDelta=new math_vector_Vector3,this._pointA=new math_vector_Vector3(0,0,0),this._pointC=new math_vector_Vector3(0,0,0),this._localAxis=new math_vector_Vector3(0,0,0),this._lookAt=new math_vector_Vector3(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,pointerDragBehavior_PointerDragBehavior._PlaneScene||(this._debugMode?pointerDragBehavior_PointerDragBehavior._PlaneScene=this._scene:(pointerDragBehavior_PointerDragBehavior._PlaneScene=new scene_Scene(this._scene.getEngine(),{virtual:!0}),pointerDragBehavior_PointerDragBehavior._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{pointerDragBehavior_PointerDragBehavior._PlaneScene.dispose(),pointerDragBehavior_PointerDragBehavior._PlaneScene=null}))),this._dragPlane=planeBuilder_CreatePlane("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:mesh_Mesh.DOUBLESIDE},pointerDragBehavior_PointerDragBehavior._PlaneScene),this.lastDragPosition=new math_vector_Vector3(0,0,0);let i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(e=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(e.type==pointerEvents_PointerEventTypes.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==pointerEvents_PointerEventTypes.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==e.event.pointerId&&(this._activeDragButton===e.event.button||-1===this._activeDragButton)&&this.releaseDrag();else if(e.type==pointerEvents_PointerEventTypes.POINTERMOVE){let t=e.event.pointerId;if(this.currentDraggingPointerId===pointerDragBehavior_PointerDragBehavior._AnyMouseId&&t!==pointerDragBehavior_PointerDragBehavior._AnyMouseId){let i=e.event,r="mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent;r&&(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 ray_Ray(new math_vector_Vector3,new math_vector_Vector3)),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))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let e=!1;pivotTools_PivotTools._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),pivotTools_PivotTools._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()){let 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=pointerDragBehavior_PointerDragBehavior._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===pointerDragBehavior_PointerDragBehavior._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;pivotTools_PivotTools._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);let r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),pivotTools_PivotTools._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;let t=this._pickWithRayOnDragPlane(e);if(t){pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?math_vector_Vector3.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=math_vector_Vector3.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),pivotTools_PivotTools._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(math_vector_Vector3.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(!this._useAlternatePickedPointAboveMaxDragAngle)return null;{this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*math_vector_Vector3.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);let t=math_vector_Vector3.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}}let i=pointerDragBehavior_PointerDragBehavior._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?math_vector_Vector3.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(math_vector_Vector3.Dot(this._localAxis,this._pointC))>.999?Math.abs(math_vector_Vector3.Dot(math_vector_Vector3.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(math_vector_Vector3.Right()):this._lookAt.copyFrom(math_vector_Vector3.UpReadOnly):(math_vector_Vector3.CrossToRef(this._localAxis,this._pointC,this._lookAt),math_vector_Vector3.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?math_vector_Vector3.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()}};pointerDragBehavior_PointerDragBehavior._AnyMouseId=-2;let webXRFeaturesManager_WebXRFeatureName=class webXRFeaturesManager_WebXRFeatureName{};webXRFeaturesManager_WebXRFeatureName.ANCHOR_SYSTEM="xr-anchor-system",webXRFeaturesManager_WebXRFeatureName.BACKGROUND_REMOVER="xr-background-remover",webXRFeaturesManager_WebXRFeatureName.HIT_TEST="xr-hit-test",webXRFeaturesManager_WebXRFeatureName.MESH_DETECTION="xr-mesh-detection",webXRFeaturesManager_WebXRFeatureName.PHYSICS_CONTROLLERS="xr-physics-controller",webXRFeaturesManager_WebXRFeatureName.PLANE_DETECTION="xr-plane-detection",webXRFeaturesManager_WebXRFeatureName.POINTER_SELECTION="xr-controller-pointer-selection",webXRFeaturesManager_WebXRFeatureName.TELEPORTATION="xr-controller-teleportation",webXRFeaturesManager_WebXRFeatureName.FEATURE_POINTS="xr-feature-points",webXRFeaturesManager_WebXRFeatureName.HAND_TRACKING="xr-hand-tracking",webXRFeaturesManager_WebXRFeatureName.IMAGE_TRACKING="xr-image-tracking",webXRFeaturesManager_WebXRFeatureName.NEAR_INTERACTION="xr-near-interaction",webXRFeaturesManager_WebXRFeatureName.DOM_OVERLAY="xr-dom-overlay",webXRFeaturesManager_WebXRFeatureName.MOVEMENT="xr-controller-movement",webXRFeaturesManager_WebXRFeatureName.LIGHT_ESTIMATION="xr-light-estimation",webXRFeaturesManager_WebXRFeatureName.EYE_TRACKING="xr-eye-tracking",webXRFeaturesManager_WebXRFeatureName.WALKING_LOCOMOTION="xr-walking-locomotion",webXRFeaturesManager_WebXRFeatureName.LAYERS="xr-layers",webXRFeaturesManager_WebXRFeatureName.DEPTH_SENSING="xr-depth-sensing",webXRFeaturesManager_WebXRFeatureName.SPACE_WARP="xr-space-warp";let WebXRFeaturesManager=class WebXRFeaturesManager{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)})}),this._xrSessionManager.onXRSessionEnded.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)})})}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){let s=this._AvailableFeatures[e][t];if(!s)throw Error("feature not found");return s(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){let t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){let t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){let t="string"==typeof e?e:e.Name,i=this._features[t];return!!i&&!!i.enabled&&(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0)}dispose(){this.getEnabledFeatures().forEach(e=>{this.disableFeature(e)})}enableFeature(e,t="latest",i={},r=!0,s=!0){let a="string"==typeof e?e:e.Name,n=0;if("string"==typeof t){if(!t)throw Error(`Error in provided version - ${a} (${t})`);if(-1===(n="stable"===t?WebXRFeaturesManager.GetStableVersionOfFeature(a):"latest"===t?WebXRFeaturesManager.GetLatestVersionOfFeature(a):+t)||isNaN(n))throw Error(`feature not found - ${a} (${t})`)}else n=t;let o=WebXRFeaturesManager._ConflictingFeatures[a];if(void 0!==o&&-1!==this.getEnabledFeatures().indexOf(o))throw Error(`Feature ${a} cannot be enabled while ${o} is enabled.`);let l=this._features[a],h=WebXRFeaturesManager.ConstructFeature(a,n,this._xrSessionManager,i);if(!h)throw Error(`feature not found - ${a}`);l&&this.disableFeature(a);let c=h();if(c.dependsOn){let e=c.dependsOn.every(e=>!!this._features[e]);if(!e)throw Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[a]={featureImplementation:c,enabled:!0,version:n,required:s},r?this._xrSessionManager.session&&!this._features[a].featureImplementation.attached&&this.attachFeature(a):this._features[a].featureImplementation.disableAutoAttach=!0,this._features[a].featureImplementation;if(!s)return tools_Tools.Warn(`Feature ${a} not compatible with the current environment/browser and was not enabled.`),c;throw Error("required feature not compatible")}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){let t=this.getEnabledFeatures();for(let i of t){let t=this._features[i],r=t.featureImplementation.xrNativeFeatureName;if(r&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(r)&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(r)&&e.optionalFeatures.push(r))),t.featureImplementation.getXRSessionInitExtension){let i=await t.featureImplementation.getXRSessionInitExtension();e=Object.assign(Object.assign({},e),i)}}return e}};WebXRFeaturesManager._AvailableFeatures={},WebXRFeaturesManager._ConflictingFeatures={[webXRFeaturesManager_WebXRFeatureName.TELEPORTATION]:webXRFeaturesManager_WebXRFeatureName.MOVEMENT,[webXRFeaturesManager_WebXRFeatureName.MOVEMENT]:webXRFeaturesManager_WebXRFeatureName.TELEPORTATION};let WebXRAbstractFeature=class WebXRAbstractFeature{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)})}};let PhysicsJoint=class PhysicsJoint{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)}};PhysicsJoint.DistanceJoint=0,PhysicsJoint.HingeJoint=1,PhysicsJoint.BallAndSocketJoint=2,PhysicsJoint.WheelJoint=3,PhysicsJoint.SliderJoint=4,PhysicsJoint.PrismaticJoint=5,PhysicsJoint.UniversalJoint=6,PhysicsJoint.Hinge2Joint=PhysicsJoint.WheelJoint,PhysicsJoint.PointToPointJoint=8,PhysicsJoint.SpringJoint=9,PhysicsJoint.LockJoint=10,mesh_Mesh._PhysicsImpostorParser=function(e,t,i){return new physicsImpostor_PhysicsImpostor(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};let physicsImpostor_PhysicsImpostor=class physicsImpostor_PhysicsImpostor{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;let e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){if(this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=[],this._onAfterPhysicsStepCallbacks=[],this._onPhysicsCollideCallbacks=[],this._deltaPosition=math_vector_Vector3.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new math_vector_Quaternion,this._tmpQuat2=new math_vector_Quaternion,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 math_vector_Quaternion),!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,physicsImpostor_PhysicsImpostor._TmpVecs[0]),this.object.translate(physicsImpostor_PhysicsImpostor._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||!this._physicsEngine)return;let 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){logger_Logger.Error("No object was provided. A physics object is obligatory");return}if(this.object.parent&&0!==i.mass&&logger_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."),!this._scene&&e.getScene&&(this._scene=e.getScene()),!this._scene)return;this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=math_vector_Quaternion.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new math_vector_Quaternion),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&&logger_Logger.Warn("You must affect impostors to children before affecting impostor to parent.")):logger_Logger.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){if(this.object.parent instanceof abstractMesh_AbstractMesh){let e=this.object.parent;return e.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)return physicsImpostor_PhysicsImpostor.DEFAULT_OBJECT_SIZE;{let e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=physicsImpostor_PhysicsImpostor.IDENTITY_QUATERNION;let i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);let r=this.object.getBoundingInfo(),s=r.boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}}getObjectCenter(){if(!this.object.getBoundingInfo)return this.object.position;{let e=this.object.getBoundingInfo();return e.boundingBox.centerWorld}}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):math_vector_Vector3.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):math_vector_Vector3.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){let t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):logger_Logger.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){let t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):logger_Logger.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e],r=-1,s=this._onPhysicsCollideCallbacks.some((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){let t=e.otherImpostors.every(e=>i.indexOf(e)>-1);return t&&(r=s),t}return!1});s?this._onPhysicsCollideCallbacks.splice(r,1):logger_Logger.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):math_vector_Quaternion.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){let r=new PhysicsJoint(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,s){if(!this._physicsEngine)return this;let a=this._physicsEngine.getPhysicsPlugin();return a.appendAnchor&&this._physicsEngine&&a.appendAnchor(this,e,t,i,r,s),this}addHook(e,t,i,r){if(!this._physicsEngine)return this;let s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor&&this._physicsEngine&&s.appendHook(this,e,t,i,r),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 physicsImpostor_PhysicsImpostor(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 math_vector_Quaternion),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,r,s){let a=physicsImpostor_PhysicsImpostor._TmpVecs[0],n=this.object;if(n.rotationQuaternion){if(s){let i=physicsImpostor_PhysicsImpostor._TmpQuat;n.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,en.WORLD,t)}else e.setRotationQuaternion(n.rotationQuaternion,en.WORLD,t)}a.x=0,a.y=0,a.z=0,i&&(a.x=i.x,a.y=i.y,a.z=i.z,e.getDirectionToRef(a,t,a),null==r&&(r=i.length()),a.x*=r,a.y*=r,a.z*=r),e.getParent()?(a.addInPlace(n.getAbsolutePosition()),e.setAbsolutePosition(a,t)):(t.setAbsolutePosition(n.getAbsolutePosition()),t.position.x-=a.x,t.position.y-=a.y,t.position.z-=a.z)}syncImpostorWithBone(e,t,i,r,s,a){let n=this.object;if(n.rotationQuaternion){if(s){let i=physicsImpostor_PhysicsImpostor._TmpQuat;e.getRotationQuaternionToRef(en.WORLD,t,i),i.multiplyToRef(s,n.rotationQuaternion)}else e.getRotationQuaternionToRef(en.WORLD,t,n.rotationQuaternion)}let o=physicsImpostor_PhysicsImpostor._TmpVecs[0],l=physicsImpostor_PhysicsImpostor._TmpVecs[1];a||((a=physicsImpostor_PhysicsImpostor._TmpVecs[2]).x=0,a.y=1,a.z=0),e.getDirectionToRef(a,t,l),e.getAbsolutePositionToRef(t,o),null==r&&i&&(r=i.length()),null!=r&&(o.x+=l.x*r,o.y+=l.y*r,o.z+=l.z*r),n.setAbsolutePosition(o)}};physicsImpostor_PhysicsImpostor.DEFAULT_OBJECT_SIZE=new math_vector_Vector3(1,1,1),physicsImpostor_PhysicsImpostor.IDENTITY_QUATERNION=math_vector_Quaternion.Identity(),physicsImpostor_PhysicsImpostor._TmpVecs=arrayTools_ArrayTools.BuildArray(3,math_vector_Vector3.Zero),physicsImpostor_PhysicsImpostor._TmpQuat=math_vector_Quaternion.Identity(),physicsImpostor_PhysicsImpostor.NoImpostor=0,physicsImpostor_PhysicsImpostor.SphereImpostor=1,physicsImpostor_PhysicsImpostor.BoxImpostor=2,physicsImpostor_PhysicsImpostor.PlaneImpostor=3,physicsImpostor_PhysicsImpostor.MeshImpostor=4,physicsImpostor_PhysicsImpostor.CapsuleImpostor=6,physicsImpostor_PhysicsImpostor.CylinderImpostor=7,physicsImpostor_PhysicsImpostor.ParticleImpostor=8,physicsImpostor_PhysicsImpostor.HeightmapImpostor=9,physicsImpostor_PhysicsImpostor.ConvexHullImpostor=10,physicsImpostor_PhysicsImpostor.CustomImpostor=100,physicsImpostor_PhysicsImpostor.RopeImpostor=101,physicsImpostor_PhysicsImpostor.ClothImpostor=102,physicsImpostor_PhysicsImpostor.SoftbodyImpostor=103,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(eu||(eu={}));let sceneLoader_SceneLoader=class sceneLoader_SceneLoader{static get ForceFullSceneLoadingForIncremental(){return SceneLoaderFlags.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){SceneLoaderFlags.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return SceneLoaderFlags.ShowLoadingScreen}static set ShowLoadingScreen(e){SceneLoaderFlags.ShowLoadingScreen=e}static get loggingLevel(){return SceneLoaderFlags.loggingLevel}static set loggingLevel(e){SceneLoaderFlags.loggingLevel=e}static get CleanBoneMatrixWeights(){return SceneLoaderFlags.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){SceneLoaderFlags.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return sceneLoader_SceneLoader._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){let t=sceneLoader_SceneLoader._RegisteredPlugins[e];return t||(logger_Logger.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"),sceneLoader_SceneLoader.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(let t in sceneLoader_SceneLoader._RegisteredPlugins){let i=sceneLoader_SceneLoader._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return sceneLoader_SceneLoader._RegisteredPlugins[t]}return sceneLoader_SceneLoader.GetDefaultPlugin()}static _GetPluginForFilename(e){let t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));let i=e.lastIndexOf("."),r=e.substring(i,e.length).toLowerCase();return sceneLoader_SceneLoader._GetPluginForExtension(r)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let r=e.rawData?"binary data":e.url,s="Unable to load from "+r;return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,r,s,a,n,o){let l;let h=sceneLoader_SceneLoader._GetDirectLoad(e.url);if(e.rawData&&!n)throw"When using ArrayBufferView to load data the file extension must be provided.";let c=n?sceneLoader_SceneLoader._GetPluginForExtension(n):h?sceneLoader_SceneLoader._GetPluginForDirectLoad(e.url):sceneLoader_SceneLoader._GetPluginForFilename(e.url);if(e.rawData&&!c.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";if(!(l=void 0!==c.plugin.createPlugin?c.plugin.createPlugin():c.plugin))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(sceneLoader_SceneLoader.OnPluginActivatedObservable.notifyObservers(l),h&&(l.canDirectLoad&&l.canDirectLoad(e.url)||!IsBase64DataUrl(e.url))){if(l.directLoad){let e=l.directLoad(t,h);e.then?e.then(e=>{i(l,e)}).catch(e=>{s("Error in directLoad of _loadData: "+e,e)}):i(l,e)}else i(l,h);return l}let u=c.isBinary,dataCallback=(e,r)=>{if(t.isDisposed){s("Scene has been disposed");return}i(l,e,r)},d=null,_=!1,p=l.onDisposeObservable;p&&p.add(()=>{_=!0,d&&(d.abort(),d=null),a()});let manifestChecked=()=>{if(_)return;let errorCallback=(e,t)=>{s(null==e?void 0:e.statusText,t)};if(!l.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";d=l.loadFile?l.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,dataCallback,r,u,errorCallback,o):t._loadFile(e.file||e.url,dataCallback,r,!0,u,errorCallback)},f=t.getEngine(),m=f.enableOfflineSupport;if(m){let i=!1;for(let r of t.disableOfflineSupportExceptionRules)if(r.test(e.url)){i=!0;break}m=!i}return m&&engine_Engine.OfflineProviderFactory?t.offlineProvider=engine_Engine.OfflineProviderFactory(e.url,manifestChecked,f.disableManifestCheck):manifestChecked(),l}static _GetFileInfo(e,t){let i,r;let s=null,a=null;if(t){if(t.name)i=`file:${t.name}`,r=t.name,s=t;else if(ArrayBuffer.isView(t))i="",r="arrayBuffer",a=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,r="";else{if("/"===t.substr(0,1))return tools_Tools.Error("Wrong sceneFilename parameter"),null;i=e+t,r=t}}else i=e,r=tools_Tools.GetFilename(e),e=tools_Tools.GetFolderPath(e);return{url:i,rootUrl:e,name:r,file:s,rawData:a}}static GetPluginForExtension(e){return sceneLoader_SceneLoader._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!sceneLoader_SceneLoader._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){let t=e.extensions;sceneLoader_SceneLoader._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{let t=e.extensions;Object.keys(t).forEach(i=>{sceneLoader_SceneLoader._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",r=engineStore_EngineStore.LastCreatedScene,s=null,a=null,n=null,o=null,l=""){if(!r)return logger_Logger.Error("No scene available to import mesh to"),null;let h=sceneLoader_SceneLoader._GetFileInfo(t,i);if(!h)return null;let c={};r.addPendingData(c);let disposeHandler=()=>{r.removePendingData(c)},errorHandler=(e,t)=>{let i=sceneLoader_SceneLoader._FormatErrorMessage(h,e,t);n?n(r,i,new RuntimeError(i,b.SceneLoaderError,t)):logger_Logger.Error(i),disposeHandler()},u=a?e=>{try{a(e)}catch(e){errorHandler("Error in onProgress callback: "+e,e)}}:void 0,successHandler=(e,t,i,a,n,o,l)=>{if(r.importedMeshesFiles.push(h.url),s)try{s(e,t,i,a,n,o,l)}catch(e){errorHandler("Error in onSuccess callback: "+e,e)}r.removePendingData(c)};return sceneLoader_SceneLoader._LoadData(h,r,(t,i,s)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,s)),t.importMesh){let s=[],a=[],n=[];t.importMesh(e,r,i,h.rootUrl,s,a,n,errorHandler)&&(r.loadingPluginName=t.name,successHandler(s,a,n,[],[],[],[]))}else t.importMeshAsync(e,r,i,h.rootUrl,u,h.name).then(e=>{r.loadingPluginName=t.name,successHandler(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)}).catch(e=>{errorHandler(e.message,e)})},u,errorHandler,disposeHandler,o,l)}static ImportMeshAsync(e,t,i="",r=engineStore_EngineStore.LastCreatedScene,s=null,a=null,n=""){return new Promise((o,l)=>{sceneLoader_SceneLoader.ImportMesh(e,t,i,r,(e,t,i,r,s,a,n)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:r,transformNodes:s,geometries:a,lights:n})},s,(e,t,i)=>{l(i||Error(t))},a,n)})}static Load(e,t="",i=engineStore_EngineStore.LastCreatedEngine,r=null,s=null,a=null,n=null,o=""){return i?sceneLoader_SceneLoader.Append(e,t,new scene_Scene(i),r,s,a,n,o):(tools_Tools.Error("No engine available"),null)}static LoadAsync(e,t="",i=engineStore_EngineStore.LastCreatedEngine,r=null,s=null,a=""){return new Promise((n,o)=>{sceneLoader_SceneLoader.Load(e,t,i,e=>{n(e)},r,(e,t,i)=>{o(i||Error(t))},s,a)})}static Append(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=null,s=null,a=null,n=null,o=""){if(!i)return logger_Logger.Error("No scene available to append to"),null;let l=sceneLoader_SceneLoader._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let disposeHandler=()=>{i.removePendingData(h)};sceneLoader_SceneLoader.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));let errorHandler=(e,t)=>{let r=sceneLoader_SceneLoader._FormatErrorMessage(l,e,t);a?a(i,r,new RuntimeError(r,b.SceneLoaderError,t)):logger_Logger.Error(r),disposeHandler()},c=s?e=>{try{s(e)}catch(e){errorHandler("Error in onProgress callback",e)}}:void 0,successHandler=()=>{if(r)try{r(i)}catch(e){errorHandler("Error in onSuccess callback",e)}i.removePendingData(h)};return sceneLoader_SceneLoader._LoadData(l,i,(e,t)=>{e.load?!e.load(i,t,l.rootUrl,errorHandler)||(i.loadingPluginName=e.name,successHandler()):e.loadAsync(i,t,l.rootUrl,c,l.name).then(()=>{i.loadingPluginName=e.name,successHandler()}).catch(e=>{errorHandler(e.message,e)})},c,errorHandler,disposeHandler,n,o)}static AppendAsync(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=null,s=null,a=""){return new Promise((n,o)=>{sceneLoader_SceneLoader.Append(e,t,i,e=>{n(e)},r,(e,t,i)=>{o(i||Error(t))},s,a)})}static LoadAssetContainer(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=null,s=null,a=null,n=null,o=""){if(!i)return logger_Logger.Error("No scene available to load asset container to"),null;let l=sceneLoader_SceneLoader._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let disposeHandler=()=>{i.removePendingData(h)},errorHandler=(e,t)=>{let r=sceneLoader_SceneLoader._FormatErrorMessage(l,e,t);a?a(i,r,new RuntimeError(r,b.SceneLoaderError,t)):logger_Logger.Error(r),disposeHandler()},c=s?e=>{try{s(e)}catch(e){errorHandler("Error in onProgress callback",e)}}:void 0,successHandler=e=>{if(r)try{r(e)}catch(e){errorHandler("Error in onSuccess callback",e)}i.removePendingData(h)};return sceneLoader_SceneLoader._LoadData(l,i,(e,t)=>{if(e.loadAssetContainer){let r=e.loadAssetContainer(i,t,l.rootUrl,errorHandler);r&&(r.populateRootNodes(),i.loadingPluginName=e.name,successHandler(r))}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,c,l.name).then(t=>{t.populateRootNodes(),i.loadingPluginName=e.name,successHandler(t)}).catch(e=>{errorHandler(e.message,e)}):errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},c,errorHandler,disposeHandler,n,o)}static LoadAssetContainerAsync(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=null,s=null){return new Promise((a,n)=>{sceneLoader_SceneLoader.LoadAssetContainer(e,t,i,e=>{a(e)},r,(e,t,i)=>{n(i||Error(t))},s)})}static ImportAnimations(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=!0,s=eu.Clean,a=null,n=null,o=null,l=null,h=null){if(!i){logger_Logger.Error("No scene available to load animations to");return}if(r){for(let e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(e=>{e.dispose()});let e=i.getNodes();e.forEach(e=>{e.animations&&(e.animations=[])})}else switch(s){case eu.Clean:i.animationGroups.slice().forEach(e=>{e.dispose()});break;case eu.Stop:i.animationGroups.forEach(e=>{e.stop()});break;case eu.Sync:i.animationGroups.forEach(e=>{e.reset(),e.restart()});break;case eu.NoSync:break;default:logger_Logger.Error("Unknown animation group loading mode value '"+s+"'");return}let c=i.animatables.length;this.LoadAssetContainer(e,t,i,e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),a),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),n&&n(i)},o,l,h)}static ImportAnimationsAsync(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=!0,s=eu.Clean,a=null,n=null,o=null,l=null,h=null){return new Promise((n,l)=>{sceneLoader_SceneLoader.ImportAnimations(e,t,i,r,s,a,e=>{n(e)},o,(e,t,i)=>{l(i||Error(t))},h)})}};sceneLoader_SceneLoader.NO_LOGGING=0,sceneLoader_SceneLoader.MINIMAL_LOGGING=1,sceneLoader_SceneLoader.SUMMARY_LOGGING=2,sceneLoader_SceneLoader.DETAILED_LOGGING=3,sceneLoader_SceneLoader.OnPluginActivatedObservable=new observable_Observable,sceneLoader_SceneLoader._RegisteredPlugins={},sceneLoader_SceneLoader._ShowingLoadingScreen=!1;let PushMaterial=class PushMaterial extends material_Material{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new math_vector_Matrix,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){let 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"})(ed||(ed={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(e_||(e_={}));let NodeMaterialBuildState=class NodeMaterialBuildState{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){let t=e.sharedData.emitComments,i=this.target===e_.Fragment;this.compilationString=` +${t?"//Entry point\n":""}void main(void) { +${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` +${t?"//Constants\n":""}${this._constantDeclaration} +${this.compilationString}`);let r="";for(let e in this.functions)r+=this.functions[e]+` +`;for(let e in this.compilationString=` +${r} +${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString} +${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString} +${this._injectAtEnd}`),this.compilationString=`${this.compilationString} +}`,this.sharedData.varyingDeclaration&&(this.compilationString=` +${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration} +${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=` +${t?"//Samplers\n":""}${this._samplerDeclaration} +${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=` +${t?"//Uniforms\n":""}${this._uniformDeclaration} +${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=` +${t?"//Attributes\n":""}${this._attributeDeclaration} +${this.compilationString}`),this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString),this.extensions){let t=this.extensions[e];this.compilationString=` +${t} +${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){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2D ${e}; +`,this.samplers.push(e))}_emit2DArraySampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2DArray ${e}; +`,this.samplers.push(e))}_getGLType(e){switch(e){case ed.Float:return"float";case ed.Int:return"int";case ed.Vector2:return"vec2";case ed.Color3:case ed.Vector3:return"vec3";case ed.Color4:case ed.Vector4:return"vec4";case ed.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i} +${t} +#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+` +`+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`;let r=effect_Effect.IncludesShadersStore[e]+"\n";if(this.sharedData.emitComments&&(r=t+` +`+r),!i)return r;if(i.replaceStrings)for(let e=0;e<i.replaceStrings.length;e++){let t=i.replaceStrings[e];r=r.replace(t.search,t.replace)}return r}_emitFunctionFromInclude(e,t,i,r=""){let s=e+r;if(!this.functions[s]){if(!i||!i.removeAttributes&&!i.removeUniforms&&!i.removeVaryings&&!i.removeIfDef&&!i.replaceStrings){i&&i.repeatKey?this.functions[s]=`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`:this.functions[s]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""} +`,this.sharedData.emitComments&&(this.functions[s]=t+` +`+this.functions[s]);return}if(this.functions[s]=effect_Effect.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+` +`+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;e<i.replaceStrings.length;e++){let t=i.replaceStrings[e];this.functions[s]=this.functions[s].replace(t.search,t.replace)}}}_registerTempVariable(e){return -1===this.sharedData.temps.indexOf(e)&&(this.sharedData.temps.push(e),!0)}_emitVaryingFromString(e,t,i="",r=!1){return -1===this.sharedData.varyings.indexOf(e)&&(this.sharedData.varyings.push(e),i&&(i.startsWith("defined(")?this.sharedData.varyingDeclaration+=`#if ${i} +`:this.sharedData.varyingDeclaration+=`${r?"#ifndef":"#ifdef"} ${i} +`),this.sharedData.varyingDeclaration+=`varying ${t} ${e}; +`,i&&(this.sharedData.varyingDeclaration+=`#endif +`),!0)}_emitUniformFromString(e,t,i="",r=!1){-1===this.uniforms.indexOf(e)&&(this.uniforms.push(e),i&&(i.startsWith("defined(")?this._uniformDeclaration+=`#if ${i} +`:this._uniformDeclaration+=`${r?"#ifndef":"#ifdef"} ${i} +`),this._uniformDeclaration+=`uniform ${t} ${e}; +`,i&&(this._uniformDeclaration+=`#endif +`))}_emitFloat(e){return e.toString()===e.toFixed(0)?`${e}.0`:e.toString()}};let NodeMaterialBuildStateSharedData=class NodeMaterialBuildStateSharedData{constructor(){this.temps=[],this.varyings=[],this.varyingDeclaration="",this.inputBlocks=[],this.textureBlocks=[],this.bindableBlocks=[],this.forcedBindableBlocks=[],this.blocksWithFallbacks=[],this.blocksWithDefines=[],this.repeatableContentBlocks=[],this.dynamicUniformBlocks=[],this.blockingBlocks=[],this.animatedInputs=[],this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:[]},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}emitErrors(){let e="";for(let t of(this.checks.emitVertex||this.allowEmptyVertexProgram||(e+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\n"),this.checks.emitFragment||(e+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\n"),this.checks.notConnectedNonOptionalInputs))e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. +`;if(e)throw"Build of NodeMaterial failed:\n"+e}};(function(e){e[e.Compatible=0]="Compatible",e[e.TypeIncompatible=1]="TypeIncompatible",e[e.TargetIncompatible=2]="TargetIncompatible",e[e.HierarchyIssue=3]="HierarchyIssue"})(ep||(ep={})),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(ef||(ef={}));let NodeMaterialConnectionPoint=class NodeMaterialConnectionPoint{static AreEquivalentTypes(e,t){switch(e){case ed.Vector3:if(t===ed.Color3)return!0;break;case ed.Vector4:if(t===ed.Color4)return!0;break;case ed.Color3:if(t===ed.Vector3)return!0;break;case ed.Color4:if(t===ed.Vector4)return!0}return!1}get direction(){return this._direction}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===ed.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===ed.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get target(){return this._prioritizeVertex&&this._ownerBlock&&this._target===e_.VertexAndFragment?this._ownerBlock.target===e_.Fragment?e_.Fragment:e_.Vertex:this._target}set target(e){this._target=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get isConnectedToInputBlock(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map(e=>e.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===e_.Vertex||(e.ownerBlock.target===e_.Neutral||e.ownerBlock.target===e_.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===e_.Vertex)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===e_.Vertex||e.target===e_.Vertex||(e.ownerBlock.target===e_.Neutral||e.ownerBlock.target===e_.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===e_.Fragment)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===e_.Fragment||(e.ownerBlock.target===e_.Neutral||e.ownerBlock.target===e_.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=[],this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=ed.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new observable_Observable,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=e_.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===ep.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(t.target===e_.Fragment){if(i.target===e_.Vertex)return ep.TargetIncompatible;for(let e of i.outputs)if(e.ownerBlock.target!=e_.Neutral&&e.isConnectedInVertexShader)return ep.TargetIncompatible}if(this.type!==e.type&&e.innerType!==ed.AutoDetect)return NodeMaterialConnectionPoint.AreEquivalentTypes(this.type,e.type)?ep.Compatible:e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&NodeMaterialConnectionPoint.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?ep.Compatible:ep.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return ep.TypeIncompatible;let r=i,s=t;return(this.direction===ef.Input&&(r=t,s=i),r.isAnAncestorOf(s))?ep.HierarchyIssue:ep.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){let 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<ed.All;)e&t||this.excludedConnectionPointTypes.push(t),t<<=1}serialize(e=!0){let t={};return t.name=this.name,t.displayName=this.displayName,e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name,t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),(this.isExposedOnFrame||this.exposedPortPosition>=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}};let NodeMaterialBlock=class NodeMaterialBlock{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){(this._target&e)==0&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}constructor(e,t=e_.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=[],this._outputs=[],this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===e_.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=UniqueIdGenerator.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===e_.Neutral}initialize(e){}bind(e,t,i,r){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){let t=e.connectedPoint;return t?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return -1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some(e=>e.isConnectedInFragmentShader)}registerInput(e,t,i=!1,r,s){return(s=null!=s?s:new NodeMaterialConnectionPoint(e,this,ef.Input)).type=t,s.isOptional=i,r&&(s.target=r),this._inputs.push(s),this}registerOutput(e,t,i,r){return(r=null!=r?r:new NodeMaterialConnectionPoint(e,this,ef.Output)).type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(let t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===ed.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(let t of this._outputs)if(!e||!e.target||e.target===e_.Neutral||(e.target&t.target)!=0)return t;return null}getSiblingOutput(e){let t=this._outputs.indexOf(e);return -1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){let s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),r=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,s){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput))&&this.target!==e_.Vertex&&!!((this.target===e_.VertexAndFragment||this.target===e_.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);let s=null!=t._vertexState,a=e._buildTarget===e_.Vertex&&e.target!==e_.VertexAndFragment;if(s&&((e.target&e._buildTarget)==0||(e.target&i.target)==0||this.target!==e_.VertexAndFragment&&a)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){let e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName}; +`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){for(let t of["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"])if(e===t)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(let t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(let i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==e_.Neutral&&((i.target&this.target)==0||(i.target&e.target)==0))continue;let r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log(`${e.target===e_.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case e_.Vertex:e.sharedData.checks.emitVertex=!0;break;case e_.Fragment:e.sharedData.checks.emitFragment=!0}for(let i of(!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=` +//${this.name} +`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target,this._outputs))if((i.target&e.target)!=0)for(let r of i.endpoints){let i=r.ownerBlock;i&&(i.target&e.target)!=0&&-1!==t.indexOf(i)&&this._processBuild(i,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector}; +${e}.visibleOnFrame = ${this.visibleOnFrame}; +${e}.target = ${this.target}; +`}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` +// ${this.getClassName()} +`;for(let i of(this.comments&&(r+=`// ${this.comments} +`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); +`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint,a=s.ownerBlock;-1===t.indexOf(a)&&(r+=a._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); +`}return t}clone(e,t=""){let i=this.serialize(),r=h[i.customType];if(r){let s=new r;return s._deserialize(i,e,t),s}return null}serialize(){let e={};for(let t of(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=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var r;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(r=e.target)&&void 0!==r?r:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let 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(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose()}};let TransformBlock=class TransformBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.complementW=1,this.complementZ=0,this.target=e_.Vertex,this.registerInput("vector",ed.AutoDetect),this.registerInput("transform",ed.Matrix),this.registerOutput("output",ed.Vector4),this.registerOutput("xyz",ed.Vector3),this._inputs[0].onConnectionObservable.add(e=>{if(e.ownerBlock.isInput){let 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);let t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){let r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),e.sharedData.blocksWithDefines.push(this);let s=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${s} = mat3(${i.associatedVariableName}); +`,e.compilationString+=`#ifdef NONUNIFORMSCALING +`,e.compilationString+=`${s} = transposeMat3(inverseMat3(${s})); +`,e.compilationString+=`#endif +`,t.connectedPoint.type){case ed.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); +`;break;case ed.Vector3:case ed.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); +`}}else{let r=i.associatedVariableName;switch(t.connectedPoint.type){case ed.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); +`;break;case ed.Vector3:case ed.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * ${t.associatedVariableName}; +`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; +`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){let 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(){return super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ}; +`+`${this._codeVariableName}.complementW = ${this.complementW}; +`}};h["BABYLON.TransformBlock"]=TransformBlock;let VertexOutputBlock=class VertexOutputBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Vertex,!0),this.registerInput("vector",ed.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e){for(let t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);let t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName}; +`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w; +`,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant; +`),this}};function editableInPropertyPage(e,t=em.Boolean,i="PROPERTIES",r){return(s,a)=>{let n=s._propStore;n||(n=[],s._propStore=n),n.push({propertyName:a,displayName:e,type:t,groupName:i,options:null!=r?r:{}})}}h["BABYLON.VertexOutputBlock"]=VertexOutputBlock,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"}(em||(em={}));let FragmentOutputBlock=class FragmentOutputBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",ed.Color4,!0),this.registerInput("rgb",ed.AutoDetect,!0),this.registerInput("a",ed.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.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&&MaterialHelper.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);let t=this.rgba,i=this.rgb,r=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||r.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");let s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)r.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${r.associatedVariableName}); +`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName}; +`;else if(i.connectedPoint){let t="1.0";r.connectedPoint&&(t=r.associatedVariableName),i.connectedPoint.type===ed.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t}); +`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t}); +`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`gl_FragColor = toLinearSpace(gl_FragColor); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`gl_FragColor = toGammaSpace(gl_FragColor); +`,e.compilationString+=`#endif +`,this.useLogarithmicDepth&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5; +`),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`gl_FragData[0] = gl_FragColor;\r +`,e.compilationString+=`#endif\r +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth}; +`}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(r=e.useLogarithmicDepth)&&void 0!==r&&r}};__decorate([editableInPropertyPage("Convert to gamma space",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],FragmentOutputBlock.prototype,"convertToGammaSpace",void 0),__decorate([editableInPropertyPage("Convert to linear space",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],FragmentOutputBlock.prototype,"convertToLinearSpace",void 0),__decorate([editableInPropertyPage("Use logarithmic depth",em.Boolean,"PROPERTIES")],FragmentOutputBlock.prototype,"useLogarithmicDepth",void 0),h["BABYLON.FragmentOutputBlock"]=FragmentOutputBlock,function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(eg||(eg={})),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"}(ev||(ev={})),function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime"}(ex||(ex={}));let F={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},w={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},L={particle_texturemask:!0};let InputBlock=class InputBlock extends NodeMaterialBlock{get type(){if(this._type===ed.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=ed.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=ed.Vector2,this._type;case"Vector3":return this._type=ed.Vector3,this._type;case"Vector4":return this._type=ed.Vector4,this._type;case"Color3":return this._type=ed.Color3,this._type;case"Color4":return this._type=ed.Color4,this._type;case"Matrix":return this._type=ed.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=ed.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=ed.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=ed.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=ed.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case ev.World:case ev.WorldView:case ev.WorldViewProjection:case ev.View:case ev.ViewProjection:case ev.Projection:this._type=ed.Matrix;break;case ev.CameraPosition:this._type=ed.Vector3;break;case ev.FogColor:this._type=ed.Color3;break;case ev.DeltaTime:case ev.MaterialAlpha:this._type=ed.Float;break;case ev.CameraParameters:this._type=ed.Vector4}}return this._type}constructor(e,t=e_.Vertex,i=ed.AutoDetect){super(e,t,!1),this._mode=eg.Undefined,this._animationType=ex.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new observable_Observable,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=eg.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===ed.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=eg.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=eg.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===eg.Undefined}get isUniform(){return this._mode===eg.Uniform}set isUniform(e){this._mode=e?eg.Uniform:eg.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===eg.Attribute}set isAttribute(e){this._mode=e?eg.Attribute:eg.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===eg.Varying}set isVarying(e){this._mode=e?eg.Varying:eg.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=eg.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case ex.Time:this.type===ed.Float&&(this.value+=.01*e.getAnimationRatio());break;case ex.RealTime:this.type===ed.Float&&(this.value=(precisionDate_PrecisionDate.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)} +`:`#ifdef ${e} +`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case ed.Float:this.value=0;break;case ed.Vector2:this.value=math_vector_Vector2.Zero();break;case ed.Vector3:this.value=math_vector_Vector3.Zero();break;case ed.Vector4:this.value=math_vector_Vector4.Zero();break;case ed.Color3:this.value=math_color_Color3.White();break;case ed.Color4:this.value=new math_color_Color4(1,1,1,1);break;case ed.Matrix:this.value=math_vector_Matrix.Identity()}}_emitConstant(e){switch(this.type){case ed.Float:return`${e._emitFloat(this.value)}`;case ed.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case ed.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case ed.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case ed.Color3:return TmpColors.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${TmpColors.Color3[0].r}, ${TmpColors.Color3[0].g}, ${TmpColors.Color3[0].b})`;case ed.Color4:return TmpColors.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${TmpColors.Color4[0].r}, ${TmpColors.Color4[0].g}, ${TmpColors.Color4[0].b}, ${TmpColors.Color4[0].a})`}return""}get _noContextSwitch(){return w[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;e.constants.push(this.associatedVariableName),e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)}; +`;return}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}; +`,t&&(e._uniformDeclaration+=`#endif +`);let i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case ev.WorldView:i.needWorldViewMatrix=!0;break;case ev.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==ex.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=null!==(i=F[this.name])&&void 0!==i?i:this.name,this.target===e_.Vertex&&e._vertexState){w[this.name]?L[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);return}if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),w[this.name]?L[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}; +`,t&&(e._attributeDeclaration+=`#endif +`))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;let s=this.associatedVariableName;switch(this._systemValue){case ev.World:e.setMatrix(s,t);break;case ev.WorldView:e.setMatrix(s,i);break;case ev.WorldViewProjection:e.setMatrix(s,r)}}_transmit(e,t,i){if(this.isAttribute)return;let r=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case ev.World:case ev.WorldView:case ev.WorldViewProjection:break;case ev.View:e.setMatrix(r,t.getViewMatrix());break;case ev.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case ev.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case ev.CameraPosition:t.bindEyePosition(e,r,!0);break;case ev.FogColor:e.setColor3(r,t.fogColor);break;case ev.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case ev.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case ev.MaterialAlpha:e.setFloat(r,i.alpha)}return}let s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case ed.Float:e.setFloat(r,s);break;case ed.Int:e.setInt(r,s);break;case ed.Color3:TmpColors.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,TmpColors.Color3[0]);break;case ed.Color4:TmpColors.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,TmpColors.Color4[0]);break;case ed.Vector2:e.setVector2(r,s);break;case ed.Vector3:e.setVector3(r,s);break;case ed.Vector4:e.setVector4(r,s);break;case ed.Matrix:e.setMatrix(r,s)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}"); +`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${ev[this._systemValue]}); +`;if(this.isUniform){let t=[],i="";switch(this.type){case ed.Float:i=`${this.value}`;break;case ed.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case ed.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case ed.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case ed.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ed.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 ed.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===ed.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${ex[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){let 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===eg.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===eg.Attribute&&e.type===ed.Vector3&&(this._type=ed.Vector4),e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=h[e.valueType];t&&(this._storedValue=t.FromArray(e.value))}}}};h["BABYLON.InputBlock"]=InputBlock;let CurrentScreenBlock=class CurrentScreenBlock extends NodeMaterialBlock{constructor(e){super(e,e_.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ed.AutoDetect,!1,e_.VertexAndFragment),this.registerOutput("rgba",ed.Color4,e_.Neutral),this.registerOutput("rgb",ed.Color3,e_.Neutral),this.registerOutput("r",ed.Float,e_.Neutral),this.registerOutput("g",ed.Float,e_.Neutral),this.registerOutput("b",ed.Float,e_.Neutral),this.registerOutput("a",ed.Float,e_.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector2|ed.Vector3|ed.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?e_.VertexAndFragment:e_.Fragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput){let i=t.connectedPoint.ownerBlock;i.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===e_.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); +`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===e_.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.blockingBlocks.indexOf(this)&&e.sharedData.blockingBlocks.push(this),0>e.sharedData.textureBlocks.indexOf(this)&&e.sharedData.textureBlocks.push(this),0>e.sharedData.blocksWithDefines.indexOf(this)&&e.sharedData.blocksWithDefines.push(this),e.target!==e_.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e),this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let 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=texture_Texture.Parse(e.texture,t,i))}};h["BABYLON.CurrentScreenBlock"]=CurrentScreenBlock;let ParticleTextureBlock=class ParticleTextureBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ed.AutoDetect,!1,e_.VertexAndFragment),this.registerOutput("rgba",ed.Color4,e_.Neutral),this.registerOutput("rgb",ed.Color3,e_.Neutral),this.registerOutput("r",ed.Float,e_.Neutral),this.registerOutput("g",ed.Float,e_.Neutral),this.registerOutput("b",ed.Float,e_.Neutral),this.registerOutput("a",ed.Float,e_.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector2|ed.Vector3|ed.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"particle_uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute("particle_uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`}_buildBlock(e){if(super._buildBlock(e),e.target===e_.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");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName}); +`,this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let 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=texture_Texture.Parse(e.texture,t,i))}};h["BABYLON.ParticleTextureBlock"]=ParticleTextureBlock;let ParticleRampGradientBlock=class ParticleRampGradientBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._isUnique=!0,this.registerInput("color",ed.Color4,!1,e_.Fragment),this.registerOutput("rampColor",ed.Color4,e_.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!==e_.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=` + #ifdef RAMPGRADIENT + vec4 baseColor = ${this.color.associatedVariableName}; + float alpha = ${this.color.associatedVariableName}.a; + + float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); + + vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.)); + baseColor.rgb *= rampColor.rgb; + + // Remapped alpha + float finalAlpha = baseColor.a; + baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0); + + ${this._declareOutput(this.rampColor,e)} = baseColor; + #else + ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName}; + #endif + `,this}};h["BABYLON.ParticleRampGradientBlock"]=ParticleRampGradientBlock;let ParticleBlendMultiplyBlock=class ParticleBlendMultiplyBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._isUnique=!0,this.registerInput("color",ed.Color4,!1,e_.Fragment),this.registerInput("alphaTexture",ed.Float,!1,e_.Fragment),this.registerInput("alphaColor",ed.Float,!1,e_.Fragment),this.registerOutput("blendColor",ed.Color4,e_.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!==e_.Vertex)return e.compilationString+=` + #ifdef BLENDMULTIPLYMODE + ${this._declareOutput(this.blendColor,e)}; + float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; + ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha); + ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a; + #else + ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName}; + #endif + `,this}};h["BABYLON.ParticleBlendMultiplyBlock"]=ParticleBlendMultiplyBlock;let EffectFallbacks=class EffectFallbacks{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=[]),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;let i=this._mesh.getScene();for(let e=0;e<i.meshes.length;e++){let r=i.meshes[e];if(!r.material){!this._mesh.material&&r.computeBonesUsingShaders&&r.numBoneInfluencers>0&&(r.computeBonesUsingShaders=!1);continue}if(r.computeBonesUsingShaders&&0!==r.numBoneInfluencers){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes)for(let e of r.subMeshes){let i=e.effect;if(i===t){r.computeBonesUsingShaders=!1;break}}}}}else{let t=this._defines[this._currentRank];if(t)for(let i=0;i<t.length;i++)e=e.replace("#define "+t[i],"");this._currentRank++}return e}};let V=`attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.postprocessVertexShader=V;let renderTargetWrapper_RenderTargetWrapper=class renderTargetWrapper_RenderTargetWrapper{get depthStencilTexture(){return this._depthStencilTexture}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get 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;let r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r,s){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){var n;return null===(n=this._depthStencilTexture)||void 0===n||n.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:a},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,r,s,a,n,o;let l=null;if(this._isMulti){let i=this.textures;if(i&&i.length>0){let r=!1,s=i.length,a=i[i.length-1]._source;(a===$.Depth||a===$.DepthStencil)&&(r=!0,s--);let n=[],o=[],h=[],c=[],u=[],d=[],_=[],p={};for(let r=0;r<s;++r){let s=i[r];n.push(s.samplingMode),o.push(s.type),h.push(s.format);let a=p[s.uniqueId];void 0!==a?(c.push(-1),_.push(0)):(p[s.uniqueId]=r,s.is2DArray?(c.push(35866),_.push(s.depth)):s.isCube?(c.push(34067),_.push(0)):s.is3D?(c.push(32879),_.push(s.depth)):(c.push(3553),_.push(0))),this._faceIndices&&u.push(null!==(e=this._faceIndices[r])&&void 0!==e?e:0),this._layerIndices&&d.push(null!==(t=this._layerIndices[r])&&void 0!==t?t:0)}let f={samplingModes:n,generateMipMaps:i[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:r,types:o,formats:h,textureCount:s,targetTypes:c,faceIndex:u,layerIndex:d,layerCounts:_},m={width:this.width,height:this.height};l=this._engine.createMultipleRenderTarget(m,f);for(let e=0;e<s;++e){if(-1!==c[e])continue;let t=p[i[e].uniqueId];l.setTexture(l.textures[t],e)}}}else{let e={};if(e.generateDepthBuffer=this._generateDepthBuffer,e.generateMipMaps=null!==(r=null===(i=this.texture)||void 0===i?void 0:i.generateMipMaps)&&void 0!==r&&r,e.generateStencilBuffer=this._generateStencilBuffer,e.samplingMode=null===(s=this.texture)||void 0===s?void 0:s.samplingMode,e.type=null===(a=this.texture)||void 0===a?void 0:a.type,e.format=null===(n=this.texture)||void 0===n?void 0:n.format,this.isCube)l=this._engine.createRenderTargetCubeTexture(this.width,e);else{let t={width:this.width,height:this.height,layers:this.is2DArray?null===(o=this.texture)||void 0===o?void 0:o.depth:void 0};l=this._engine.createRenderTargetTexture(t,e)}l.texture.isReady=!0}return l}_swapRenderTargetWrapper(e){if(this._textures&&e._textures)for(let t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null}_rebuild(){let e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){let t=this._depthStencilTexture.samplingMode;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,2===t||3===t||11===t,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let t=0;t<(null===(e=this._textures)||void 0===e?void 0:e.length);++t)this._textures[t].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)}};let WebGLRenderTargetWrapper=class WebGLRenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{constructor(e,t,i,r,s){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height)).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);let t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;let s=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;this._engine._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,s,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var s,a,n,o;if(!e._hardwareTexture)return;let l=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(l),this._engine.webGLVersion>1){let l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(a=null!=i?i:null===(s=this.layerIndices)||void 0===s?void 0:s[t])&&void 0!==a?a:0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=null!==(o=null!=i?i:null===(n=this.faceIndices)||void 0===n?void 0:n[t])&&void 0!==o?o:0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{let s=this._context,a=s["COLOR_ATTACHMENT"+t+"_WEBGL"],n=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,a,n,e._hardwareTexture.underlyingResource,r)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,r;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;let s=null!==(r=null===(i=this._attachments)||void 0===i?void 0:i.length)&&void 0!==r?r:this.textures.length;for(let e=0;e<s;e++){let t=this.textures[e];t&&(t.is2DArray||t.is3D?this._bindTextureRenderTarget(t,e,this.layerIndices[e]):t.isCube?this._bindTextureRenderTarget(t,e,this.faceIndices[e]):this._bindTextureRenderTarget(t,e))}}setLayerAndFaceIndex(e=0,t,i){if(super.setLayerAndFaceIndex(e,t,i),!this.textures||!this.layerIndices||!this.faceIndices)return;let r=this.textures[e];r.is2DArray||r.is3D?this._bindTextureRenderTarget(this.textures[e],e,this.layerIndices[e]):r.isCube&&this._bindTextureRenderTarget(this.textures[e],e,this.faceIndices[e])}dispose(e=this._disposeOnlyFramebuffers){let t=this._context;!e&&(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(t.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(t.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(t.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),super.dispose(e)}};ThinEngine.prototype._createHardwareRenderTargetWrapper=function(e,t,i){let r=new WebGLRenderTargetWrapper(e,t,i,this,this._gl);return this._renderTargetWrapperCache.push(r),r},ThinEngine.prototype.createRenderTargetTexture=function(e,t){var i,r;let s;let a=this._createHardwareRenderTargetWrapper(!1,!1,e),n=!0,o=!1,l=!1,h=1;void 0!==t&&"object"==typeof t&&(n=null===(i=t.generateDepthBuffer)||void 0===i||i,o=!!t.generateStencilBuffer,l=!!t.noColorAttachment,s=t.colorAttachment,h=null!==(r=t.samples)&&void 0!==r?r:1);let c=s||(l?null:this._createInternalTexture(e,t,!0,$.RenderTarget)),u=e.width||e,d=e.height||e,_=this._currentFramebuffer,p=this._gl,f=p.createFramebuffer();return this._bindUnboundFramebuffer(f),a._depthStencilBuffer=this._setupFramebufferDepthAttachments(o,n,u,d),c&&!c.is2DArray&&p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,c._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(_),a._framebuffer=f,a._generateDepthBuffer=n,a._generateStencilBuffer=o,a.setTextures(c),this.updateRenderTargetTextureSampleCount(a,h),a},ThinEngine.prototype.createDepthStencilTexture=function(e,t,i){if(!t.isCube)return this._createDepthStencilTexture(e,t,i);{let r=e.width||e;return this._createDepthStencilCubeTexture(r,t,i)}},ThinEngine.prototype._createDepthStencilTexture=function(e,t,i){let r=this._gl,s=e.layers||0,a=0!==s?r.TEXTURE_2D_ARRAY:r.TEXTURE_2D,n=new internalTexture_InternalTexture(this,$.DepthStencil);if(!this._caps.depthTextureExtension)return logger_Logger.Error("Depth texture is not supported by your browser or hardware."),n;let o=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t);if(this._bindTextureDirectly(a,n,!0),this._setupDepthStencilTexture(n,e,o.generateStencil,0!==o.comparisonFunction&&o.bilinearFiltering,o.comparisonFunction,o.samples),void 0!==o.depthTextureFormat){if(15!==o.depthTextureFormat&&16!==o.depthTextureFormat&&17!==o.depthTextureFormat&&13!==o.depthTextureFormat&&14!==o.depthTextureFormat&&18!==o.depthTextureFormat)return logger_Logger.Error("Depth texture format is not supported."),n;n.format=o.depthTextureFormat}else n.format=o.generateStencil?13:16;let l=17===n.format||13===n.format||18===n.format;i._depthStencilTexture=n,i._depthStencilTextureWithStencil=l;let h=r.UNSIGNED_INT;15===n.format?h=r.UNSIGNED_SHORT:17===n.format||13===n.format?h=r.UNSIGNED_INT_24_8:14===n.format?h=r.FLOAT:18===n.format&&(h=r.FLOAT_32_UNSIGNED_INT_24_8_REV);let c=l?r.DEPTH_STENCIL:r.DEPTH_COMPONENT,u=c;if(this.webGLVersion>1&&(15===n.format?u=r.DEPTH_COMPONENT16:16===n.format?u=r.DEPTH_COMPONENT24:17===n.format||13===n.format?u=r.DEPTH24_STENCIL8:14===n.format?u=r.DEPTH_COMPONENT32F:18===n.format&&(u=r.DEPTH32F_STENCIL8)),n.is2DArray?r.texImage3D(a,0,u,n.width,n.height,s,0,c,h,null):r.texImage2D(a,0,u,n.width,n.height,0,c,h,null),this._bindTextureDirectly(a,null),this._internalTexturesCache.push(n),i._depthStencilBuffer){let e=this._currentFramebuffer;this._bindUnboundFramebuffer(i._framebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),r.deleteRenderbuffer(i._depthStencilBuffer),i._depthStencilBuffer=null}return n},ThinEngine.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let 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);let r=e.texture._hardwareTexture;if(r.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){let s=i.createFramebuffer();if(!s)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);let a=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBAMultiSampleBufferFormat(e.texture.type),i.COLOR_ATTACHMENT0,!1);if(!a)throw Error("Unable to create multi sampled framebuffer");r.addMSAARenderBuffer(a)}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};let postProcess_PostProcess=class postProcess_PostProcess{static RegisterShaderCodeProcessing(e,t){if(!t){delete postProcess_PostProcess._CustomShaderCodeProcessing[null!=e?e:""];return}postProcess_PostProcess._CustomShaderCodeProcessing[null!=e?e:""]=t}static _GetShaderCodeProcessing(e){var t;return null!==(t=postProcess_PostProcess._CustomShaderCodeProcessing[e])&&void 0!==t?t:postProcess_PostProcess._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,r,s,a,n=1,o,l,h=null,c=0,u="postprocess",d,_=!1,p=5,f=q.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new SmartArray(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new math_vector_Vector2(1,1),this._texelSize=math_vector_Vector2.Zero(),this.onActivateObservable=new observable_Observable,this.onSizeChangedObservable=new observable_Observable,this.onApplyObservable=new observable_Observable,this.onBeforeRenderObservable=new observable_Observable,this.onAfterRenderObservable=new observable_Observable,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()):o&&(this._engine=o,this._engine.postProcesses.push(this)),this._options=s,this.renderTargetSamplingMode=n||1,this._reusable=l||!1,this._textureType=c,this._textureFormat=p,this._shaderLanguage=f,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=d,this._drawWrapper=new drawWrapper_DrawWrapper(this._engine),_||this.updateEffect(h)}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 SmartArray(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,a,n,o){var l,h;let c=postProcess_PostProcess._GetShaderCodeProcessing(this.name);if(null==c?void 0:c.defineCustomBindings){let r=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];r.push(...this._parameters);let s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=c.defineCustomBindings(this.name,e,r,s),t=r,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=n?n:this._vertexUrl,fragment:null!=o?o: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!=a?a:null,indexParameters:r||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 r=0;r<this._textureCache.length;r++)if(this._textureCache[r].texture.width===e.width&&this._textureCache[r].texture.height===e.height&&this._textureCache[r].postProcessChannel===i&&this._textureCache[r].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[r].texture.samples===t.samples)return this._textureCache[r].texture;let r=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:r,postProcessChannel:i,lastUsedRenderId:-1}),r}_flushTextureCache(){let e=this._renderId;for(let t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i<this._textures.length;i++)if(this._textures.data[i]===this._textureCache[t].texture){e=!0;break}e||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}_resize(e,t,i,r,s){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let a=null;for(let e=0;e<i._postProcesses.length;e++)if(null!==i._postProcesses[e]){a=i._postProcesses[e];break}let n={width:this.width,height:this.height},o={generateMipMaps:r,generateDepthBuffer:s||a===this,generateStencilBuffer:(s||a===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(n,o,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(n,o,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}activate(e,t=null,i){var r,s;let a;e=e||this._camera;let n=e.getScene(),o=n.getEngine(),l=o.getCaps().maxTextureSize,h=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,c=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0,u=this._options.width||h,d=this._options.height||c,_=7!==this.renderTargetSamplingMode&&1!==this.renderTargetSamplingMode&&2!==this.renderTargetSamplingMode;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){let e=o.currentViewport;e&&(u*=e.width,d*=e.height)}(_||this.alwaysForcePOT)&&(this._options.width||(u=o.needPOTTextures?engine_Engine.GetExponentOfTwo(u,l,this.scaleMode):u),this._options.height||(d=o.needPOTTextures?engine_Engine.GetExponentOfTwo(d,l,this.scaleMode):d)),(this.width!==u||this.height!==d)&&this._resize(u,d,e,_,i),this._textures.forEach(e=>{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)}),this._flushTextureCache(),this._renderId++}if(this._shareOutputWithPostProcess)a=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)a=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let e;a=this.inputTexture;for(let t=0;t<this._textureCache.length;t++)if(this._textureCache[t].texture===a){e=this._textureCache[t];break}e&&(e.lastUsedRenderId=this._renderId)}return this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(h/u,c/d),this._engine.bindFramebuffer(a,0,h,c,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(a,0,void 0,void 0,this.forceFullscreenViewport)),null===(s=(r=this._engine)._debugInsertMarker)||void 0===s||s.call(r,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:n.clearColor,n._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),a}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){var e,t;return null!==(t=null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}apply(){var e,t,i;let r;return(null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())?(this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),r=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",null==r?void 0:r.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),null===(i=null===(t=postProcess_PostProcess._GetShaderCodeProcessing(this.name))||void 0===t?void 0:t.bindCustomBindings)||void 0===i||i.call(t,this.name,this._drawWrapper.effect),this._drawWrapper.effect):null}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&-1!==(t=this._scene.postProcesses.indexOf(this))&&this._scene.postProcesses.splice(t,1),this._parentContainer){let e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(-1!==(t=this._engine.postProcesses.indexOf(this))&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),0===(t=e._postProcesses.indexOf(this))&&e._postProcesses.length>0){let e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){let e=decorators_SerializationHelper.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(){let e=this.serialize();e._engine=this._engine,e.cameraId=null;let t=postProcess_PostProcess.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){let r=h[e.customType];if(!r||!r._Parse)return null;let s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new postProcess_PostProcess(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,r)}};postProcess_PostProcess._CustomShaderCodeProcessing={},__decorate([serialize()],postProcess_PostProcess.prototype,"uniqueId",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"name",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"width",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"height",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"renderTargetSamplingMode",void 0),__decorate([generateSerializableMember(8,void 0)],postProcess_PostProcess.prototype,"clearColor",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"autoClear",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"forceAutoClearInAlphaMode",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"alphaMode",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"alphaConstants",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"enablePixelPerfectMode",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"forceFullscreenViewport",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"scaleMode",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"alwaysForcePOT",void 0),__decorate([serialize("samples")],postProcess_PostProcess.prototype,"_samples",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"adaptScaleToCurrentViewport",void 0),h["BABYLON.PostProcess"]=postProcess_PostProcess;let VectorMergerBlock=class VectorMergerBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",ed.Vector4,!0),this.registerInput("xyz ",ed.Vector3,!0),this.registerInput("xy ",ed.Vector2,!0),this.registerInput("zw ",ed.Vector2,!0),this.registerInput("x",ed.Float,!0),this.registerInput("y",ed.Float,!0),this.registerInput("z",ed.Float,!0),this.registerInput("w",ed.Float,!0),this.registerOutput("xyzw",ed.Vector4),this.registerOutput("xyz",ed.Vector3),this.registerOutput("xy",ed.Vector2),this.registerOutput("zw",ed.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){let t=this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle;return"."+t.substr(0,e)}_buildBlock(e){super._buildBlock(e);let t=this.x,i=this.y,r=this.z,s=this.w,a=this.xyIn,n=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; +`)):o.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${o.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${o.associatedVariableName}${this._buildSwizzle(3)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; +`)):(a.isConnected?(h.hasEndpoints&&(n.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${n.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)}; +`)):(h.hasEndpoints&&(n.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)}; +`)),d.hasEndpoints&&(n.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)}; +`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)}; +`)),this}serialize(){let 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 r,s,a,n;super._deserialize(e,t,i),this.xSwizzle=null!==(r=e.xSwizzle)&&void 0!==r?r:"x",this.ySwizzle=null!==(s=e.ySwizzle)&&void 0!==s?s:"y",this.zSwizzle=null!==(a=e.zSwizzle)&&void 0!==a?a:"z",this.wSwizzle=null!==(n=e.wSwizzle)&&void 0!==n?n:"w"}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}"; +${this._codeVariableName}.ySwizzle = "${this.ySwizzle}"; +${this._codeVariableName}.zSwizzle = "${this.zSwizzle}"; +${this._codeVariableName}.wSwizzle = "${this.wSwizzle}"; +`}};h["BABYLON.VectorMergerBlock"]=VectorMergerBlock;let RemapBlock=class RemapBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.sourceRange=new math_vector_Vector2(-1,1),this.targetRange=new math_vector_Vector2(0,1),this.registerInput("input",ed.AutoDetect),this.registerInput("sourceMin",ed.Float,!0),this.registerInput("sourceMax",ed.Float,!0),this.registerInput("targetMin",ed.Float,!0),this.registerInput("targetMax",ed.Float,!0),this.registerOutput("output",ed.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);let t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),a=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${a} - ${s}) / (${r} - ${i}); +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y}); +`+`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y}); +`}serialize(){let 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=math_vector_Vector2.FromArray(e.sourceRange),this.targetRange=math_vector_Vector2.FromArray(e.targetRange)}};__decorate([editableInPropertyPage("From",em.Vector2)],RemapBlock.prototype,"sourceRange",void 0),__decorate([editableInPropertyPage("To",em.Vector2)],RemapBlock.prototype,"targetRange",void 0),h["BABYLON.RemapBlock"]=RemapBlock;let MultiplyBlock=class MultiplyBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(ed.Float),this._inputs[1].acceptedConnectionPointTypes.push(ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName}; +`,this}};h["BABYLON.MultiplyBlock"]=MultiplyBlock,function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(eb||(eb={}));let BoxParticleEmitter=class BoxParticleEmitter{constructor(){this.direction1=new math_vector_Vector3(0,1,0),this.direction2=new math_vector_Vector3(0,1,0),this.minEmitBox=new math_vector_Vector3(-.5,-.5,-.5),this.maxEmitBox=new math_vector_Vector3(.5,.5,.5)}startDirectionFunction(e,t,i,r){let s=math_scalar_Scalar.RandomRange(this.direction1.x,this.direction2.x),a=math_scalar_Scalar.RandomRange(this.direction1.y,this.direction2.y),n=math_scalar_Scalar.RandomRange(this.direction1.z,this.direction2.z);if(r){t.x=s,t.y=a,t.z=n;return}math_vector_Vector3.TransformNormalFromFloatsToRef(s,a,n,e,t)}startPositionFunction(e,t,i,r){let s=math_scalar_Scalar.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),a=math_scalar_Scalar.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),n=math_scalar_Scalar.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(r){t.x=s,t.y=a,t.z=n;return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(s,a,n,e,t)}clone(){let e=new BoxParticleEmitter;return DeepCopier.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(){let 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){math_vector_Vector3.FromArrayToRef(e.direction1,0,this.direction1),math_vector_Vector3.FromArrayToRef(e.direction2,0,this.direction2),math_vector_Vector3.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),math_vector_Vector3.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}};let ConeParticleEmitter=class ConeParticleEmitter{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?math_vector_TmpVectors.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),math_vector_TmpVectors.Vector3[0]).normalize();let s=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),a=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),n=math_scalar_Scalar.RandomRange(0,this.directionRandomizer);t.x=math_vector_TmpVectors.Vector3[0].x+s,t.y=math_vector_TmpVectors.Vector3[0].y+a,t.z=math_vector_TmpVectors.Vector3[0].z+n,t.normalize()}startPositionFunction(e,t,i,r){let s;let a=math_scalar_Scalar.RandomRange(0,2*Math.PI);s=this.emitFromSpawnPointOnly?1e-4:1-(s=math_scalar_Scalar.RandomRange(0,this.heightRange))*s;let n=this._radius-math_scalar_Scalar.RandomRange(0,this._radius*this.radiusRange);n*=s;let o=n*Math.sin(a),l=n*Math.cos(a),h=s*this._height;if(r){t.x=o,t.y=h,t.z=l;return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(o,h,l,e,t)}clone(){let e=new ConeParticleEmitter(this._radius,this._angle,this.directionRandomizer);return DeepCopier.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(){let 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}};let CylinderParticleEmitter=class CylinderParticleEmitter{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=math_vector_Vector3.Zero()}startDirectionFunction(e,t,i,r,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),math_vector_Vector3.TransformNormalToRef(this._tempVector,s,this._tempVector);let a=math_scalar_Scalar.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),n=Math.atan2(this._tempVector.x,this._tempVector.z);if(n+=math_scalar_Scalar.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=a,this._tempVector.x=Math.sin(n),this._tempVector.z=Math.cos(n),this._tempVector.normalize(),r){t.copyFrom(this._tempVector);return}math_vector_Vector3.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){let s=math_scalar_Scalar.RandomRange(-this.height/2,this.height/2),a=math_scalar_Scalar.RandomRange(0,2*Math.PI),n=math_scalar_Scalar.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),o=Math.sqrt(n)*this.radius,l=o*Math.cos(a),h=o*Math.sin(a);if(r){t.copyFromFloats(l,s,h);return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(l,s,h,e,t)}clone(){let e=new CylinderParticleEmitter(this.radius,this.directionRandomizer);return DeepCopier.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(){let 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}};let CylinderDirectedParticleEmitter=class CylinderDirectedParticleEmitter extends CylinderParticleEmitter{constructor(e=1,t=1,i=1,r=new math_vector_Vector3(0,1,0),s=new math_vector_Vector3(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=s}startDirectionFunction(e,t){let i=math_scalar_Scalar.RandomRange(this.direction1.x,this.direction2.x),r=math_scalar_Scalar.RandomRange(this.direction1.y,this.direction2.y),s=math_scalar_Scalar.RandomRange(this.direction1.z,this.direction2.z);math_vector_Vector3.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new CylinderDirectedParticleEmitter(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return DeepCopier.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(){let 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)}};let HemisphericParticleEmitter=class HemisphericParticleEmitter{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),a=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),n=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),o=math_scalar_Scalar.RandomRange(0,this.directionRandomizer);if(s.x+=a,s.y+=n,s.z+=o,s.normalize(),r){t.copyFrom(s);return}math_vector_Vector3.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-math_scalar_Scalar.RandomRange(0,this.radius*this.radiusRange),a=math_scalar_Scalar.RandomRange(0,1),n=math_scalar_Scalar.RandomRange(0,2*Math.PI),o=Math.acos(2*a-1),l=s*Math.cos(n)*Math.sin(o),h=s*Math.cos(o),c=s*Math.sin(n)*Math.sin(o);if(r){t.copyFromFloats(l,Math.abs(h),c);return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){let e=new HemisphericParticleEmitter(this.radius,this.directionRandomizer);return DeepCopier.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(){let 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}};let PointParticleEmitter=class PointParticleEmitter{constructor(){this.direction1=new math_vector_Vector3(0,1,0),this.direction2=new math_vector_Vector3(0,1,0)}startDirectionFunction(e,t,i,r){let s=math_scalar_Scalar.RandomRange(this.direction1.x,this.direction2.x),a=math_scalar_Scalar.RandomRange(this.direction1.y,this.direction2.y),n=math_scalar_Scalar.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,a,n);return}math_vector_Vector3.TransformNormalFromFloatsToRef(s,a,n,e,t)}startPositionFunction(e,t,i,r){if(r){t.copyFromFloats(0,0,0);return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){let e=new PointParticleEmitter;return DeepCopier.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(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){math_vector_Vector3.FromArrayToRef(e.direction1,0,this.direction1),math_vector_Vector3.FromArrayToRef(e.direction2,0,this.direction2)}};let SphereParticleEmitter=class SphereParticleEmitter{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),a=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),n=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),o=math_scalar_Scalar.RandomRange(0,this.directionRandomizer);if(s.x+=a,s.y+=n,s.z+=o,s.normalize(),r){t.copyFrom(s);return}math_vector_Vector3.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-math_scalar_Scalar.RandomRange(0,this.radius*this.radiusRange),a=math_scalar_Scalar.RandomRange(0,1),n=math_scalar_Scalar.RandomRange(0,2*Math.PI),o=Math.acos(2*a-1),l=s*Math.cos(n)*Math.sin(o),h=s*Math.cos(o),c=s*Math.sin(n)*Math.sin(o);if(r){t.copyFromFloats(l,h,c);return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){let e=new SphereParticleEmitter(this.radius,this.directionRandomizer);return DeepCopier.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(){let 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}};let SphereDirectedParticleEmitter=class SphereDirectedParticleEmitter extends SphereParticleEmitter{constructor(e=1,t=new math_vector_Vector3(0,1,0),i=new math_vector_Vector3(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){let i=math_scalar_Scalar.RandomRange(this.direction1.x,this.direction2.x),r=math_scalar_Scalar.RandomRange(this.direction1.y,this.direction2.y),s=math_scalar_Scalar.RandomRange(this.direction1.z,this.direction2.z);math_vector_Vector3.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new SphereDirectedParticleEmitter(this.radius,this.direction1,this.direction2);return DeepCopier.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(){let 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)}};let CustomParticleEmitter=class CustomParticleEmitter{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){let s=math_vector_TmpVectors.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);let e=math_vector_TmpVectors.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);if(r){t.copyFrom(s);return}math_vector_Vector3.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,r){let s=math_vector_TmpVectors.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),r){t.copyFrom(s);return}math_vector_Vector3.TransformCoordinatesToRef(s,e,t)}clone(){let e=new CustomParticleEmitter;return DeepCopier.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e}parse(e){}};let MeshParticleEmitter=class MeshParticleEmitter{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(buffer_VertexBuffer.PositionKind),this._normals=e.getVerticesData(buffer_VertexBuffer.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=math_vector_Vector3.Zero(),this._mesh=null,this.direction1=new math_vector_Vector3(0,1,0),this.direction2=new math_vector_Vector3(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals){math_vector_Vector3.TransformNormalToRef(this._storedNormal,e,t);return}let s=math_scalar_Scalar.RandomRange(this.direction1.x,this.direction2.x),a=math_scalar_Scalar.RandomRange(this.direction1.y,this.direction2.y),n=math_scalar_Scalar.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,a,n);return}math_vector_Vector3.TransformNormalFromFloatsToRef(s,a,n,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;let s=3*Math.random()*(this._indices.length/3)|0,a=Math.random(),n=Math.random()*(1-a),o=1-a-n,l=this._indices[s],h=this._indices[s+1],c=this._indices[s+2],u=math_vector_TmpVectors.Vector3[0],d=math_vector_TmpVectors.Vector3[1],_=math_vector_TmpVectors.Vector3[2],p=math_vector_TmpVectors.Vector3[3];math_vector_Vector3.FromArrayToRef(this._positions,3*l,u),math_vector_Vector3.FromArrayToRef(this._positions,3*h,d),math_vector_Vector3.FromArrayToRef(this._positions,3*c,_),p.x=a*u.x+n*d.x+o*_.x,p.y=a*u.y+n*d.y+o*_.y,p.z=a*u.z+n*d.z+o*_.z,r?t.copyFromFloats(p.x,p.y,p.z):math_vector_Vector3.TransformCoordinatesFromFloatsToRef(p.x,p.y,p.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(math_vector_Vector3.FromArrayToRef(this._normals,3*l,u),math_vector_Vector3.FromArrayToRef(this._normals,3*h,d),math_vector_Vector3.FromArrayToRef(this._normals,3*c,_),this._storedNormal.x=a*u.x+n*d.x+o*_.x,this._storedNormal.y=a*u.y+n*d.y+o*_.y,this._storedNormal.z=a*u.z+n*d.z+o*_.z)}clone(){let e=new MeshParticleEmitter(this.mesh);return DeepCopier.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;let 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){math_vector_Vector3.FromArrayToRef(e.direction1,0,this.direction1),math_vector_Vector3.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}};let BaseParticleSystem=class BaseParticleSystem{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:math_vector_Vector3.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:math_vector_Vector3.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:math_vector_Vector3.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:math_vector_Vector3.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let r=0;for(let i of t){if(i.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=math_vector_Vector3.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 math_vector_Vector3(10,10,10),this.onAnimationEnd=null,this.blendMode=BaseParticleSystem.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 math_vector_Vector2(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new math_vector_Vector3(0,0,0),this._useLogarithmicDepth=!1,this.gravity=math_vector_Vector3.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 math_color_Color4(1,1,1,1),this.color2=new math_color_Color4(1,1,1,1),this.colorDead=new math_color_Color4(0,0,0,1),this.textureMask=new math_color_Color4(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new ImageProcessingConfigurationDefines,this.id=e,this.name=e}createPointEmitter(e,t){let i=new PointParticleEmitter;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){let i=new HemisphericParticleEmitter(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){let i=new SphereParticleEmitter(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new math_vector_Vector3(0,1,0),i=new math_vector_Vector3(0,1,0)){let r=new SphereDirectedParticleEmitter(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){let s=new CylinderParticleEmitter(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new math_vector_Vector3(0,1,0),s=new math_vector_Vector3(0,1,0)){let a=new CylinderDirectedParticleEmitter(e,t,i,r,s);return this.particleEmitterType=a,a}createConeEmitter(e=1,t=Math.PI/4){let i=new ConeParticleEmitter(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,r){let s=new BoxParticleEmitter;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}};BaseParticleSystem.BLENDMODE_ONEONE=0,BaseParticleSystem.BLENDMODE_STANDARD=1,BaseParticleSystem.BLENDMODE_ADD=2,BaseParticleSystem.BLENDMODE_MULTIPLY=3,BaseParticleSystem.BLENDMODE_MULTIPLYADD=4;let ColorSplitterBlock=class ColorSplitterBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("rgba",ed.Color4,!0),this.registerInput("rgb ",ed.Color3,!0),this.registerOutput("rgb",ed.Color3),this.registerOutput("r",ed.Float),this.registerOutput("g",ed.Float),this.registerOutput("b",ed.Float),this.registerOutput("a",ed.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);let t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;let i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],a=this._outputs[3],n=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb; +`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.r; +`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g; +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.b; +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.a; +`),this}};h["BABYLON.ColorSplitterBlock"]=ColorSplitterBlock,ThinEngine.prototype.createRenderTargetCubeTexture=function(e,t){let i=this._createHardwareRenderTargetWrapper(!1,!0,e),r=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},t);r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1);let s=this._gl,a=new internalTexture_InternalTexture(this,$.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,a,!0);let n=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);1!==r.type||this._caps.textureFloat||(r.type=0,logger_Logger.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,n.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,n.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let t=0;t<6;t++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);let o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,a.width=e,a.height=e,a.isReady=!0,a.isCube=!0,a.samples=1,a.generateMipMaps=r.generateMipMaps,a.samplingMode=r.samplingMode,a.type=r.type,a.format=r.format,this._internalTexturesCache.push(a),i.setTextures(a),i};let U={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};let EffectRenderer=class EffectRenderer{constructor(e,t=U){var i,r;this._fullscreenViewport=new math_viewport_Viewport(0,0,1,1);let s=null!==(i=t.positions)&&void 0!==i?i:U.positions,a=null!==(r=t.indices)&&void 0!==r?r:U.indices;this.engine=e,this._vertexBuffers={[buffer_VertexBuffer.PositionKind]:new buffer_VertexBuffer(e,s,buffer_VertexBuffer.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(a),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{for(let t in this._indexBuffer=e.createIndexBuffer(a),this._vertexBuffers){let e=this._vertexBuffers[t];e._rebuild()}})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();let 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(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[buffer_VertexBuffer.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}};let EffectWrapper=class EffectWrapper{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new observable_Observable;let 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)}));let r=e.defines?e.defines.join("\n"):"";this._drawWrapper=new drawWrapper_DrawWrapper(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,r,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new effect_Effect(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,r,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()}};let k="passPixelShader",G=`varying vec2 vUV;uniform sampler2D textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);}`;ShaderStore.ShadersStore[k]=G;let z={name:k,shader:G};let dumpTools_DumpTools=class dumpTools_DumpTools{static _CreateDumpRenderer(){if(!dumpTools_DumpTools._DumpToolsEngine){let e;let t=null,i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new ThinEngine(e,!1,i)}catch(r){t=new ThinEngine(e=document.createElement("canvas"),!1,i)}t.getCaps().parallelShaderCompile=void 0;let r=new EffectRenderer(t),s=new EffectWrapper({engine:t,name:z.name,fragmentShader:z.shader,samplerNames:["textureSampler"]});dumpTools_DumpTools._DumpToolsEngine={canvas:e,engine:t,renderer:r,wrapper:s}}return dumpTools_DumpTools._DumpToolsEngine}static async DumpFramebuffer(e,t,i,r,s="image/png",a,n){let o=await i.readPixels(0,0,e,t),l=new Uint8Array(o.buffer);dumpTools_DumpTools.DumpData(e,t,l,r,s,a,!0,void 0,n)}static DumpDataAsync(e,t,i,r="image/png",s,a=!1,n=!1,o){return new Promise(l=>{dumpTools_DumpTools.DumpData(e,t,i,e=>l(e),r,s,a,n,o)})}static DumpData(e,t,i,r,s="image/png",a,n=!1,o=!1,l){let h=dumpTools_DumpTools._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){let e=new Uint8Array(i.length),t=i.length;for(;t--;){let r=i[t];e[t]=Math.round(255*math_scalar_Scalar.Clamp(r))}i=e}let c=h.engine.createRawTexture(i,e,t,5,!1,!n,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),o?tools_Tools.ToBlob(h.canvas,e=>{let t=new FileReader;t.onload=e=>{let t=e.target.result;r&&r(t)},t.readAsArrayBuffer(e)},s,l):tools_Tools.EncodeScreenshotCanvasData(h.canvas,r,s,a,l),c.dispose()}static Dispose(){dumpTools_DumpTools._DumpToolsEngine&&(dumpTools_DumpTools._DumpToolsEngine.wrapper.dispose(),dumpTools_DumpTools._DumpToolsEngine.renderer.dispose(),dumpTools_DumpTools._DumpToolsEngine.engine.dispose()),dumpTools_DumpTools._DumpToolsEngine=null}};tools_Tools.DumpData=dumpTools_DumpTools.DumpData,tools_Tools.DumpDataAsync=dumpTools_DumpTools.DumpDataAsync,tools_Tools.DumpFramebuffer=dumpTools_DumpTools.DumpFramebuffer;let renderTargetTexture_RenderTargetTexture=class renderTargetTexture_RenderTargetTexture extends texture_Texture{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=_ObserveArray(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e<i.length;++e)for(let r=0;r<this._renderPassIds.length;++r)i[e].setMaterialForRenderPass(this._renderPassIds[r],void 0!==t?Array.isArray(t)?t[r]:t:void 0)}get isMulti(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e.isMulti)&&void 0!==t&&t}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e._depthStencilTexture)&&void 0!==t?t:null}constructor(e,t,i,r=!1,s=!0,a=0,n=!1,o=texture_Texture.TRILINEAR_SAMPLINGMODE,l=!0,h=!1,c=!1,u=5,d=!1,_,p,f=!1,m=!1){var g,v,x,b,T,S,C;let E;let y=!0;if("object"==typeof r){let e=r;r=!!e.generateMipMaps,s=null===(g=e.doNotChangeAspectRatio)||void 0===g||g,a=null!==(v=e.type)&&void 0!==v?v:0,n=!!e.isCube,o=null!==(x=e.samplingMode)&&void 0!==x?x:texture_Texture.TRILINEAR_SAMPLINGMODE,l=null===(b=e.generateDepthBuffer)||void 0===b||b,h=!!e.generateStencilBuffer,c=!!e.isMulti,u=null!==(T=e.format)&&void 0!==T?T:5,d=!!e.delayAllocation,_=e.samples,p=e.creationFlags,f=!!e.noColorAttachment,m=!!e.useSRGBBuffer,E=e.colorAttachment,y=null!==(S=e.gammaSpace)&&void 0!==S?S:y}if(super(null,i,!r,void 0,o,void 0,void 0,void 0,void 0,u),this._unObserveRenderList=null,this._renderListHasChanged=(e,t)=>{var i;let r=this._renderList?this._renderList.length:0;(0===t&&r>0||0===r)&&(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 observable_Observable,this.onAfterUnbindObservable=new observable_Observable,this.onBeforeRenderObservable=new observable_Observable,this.onAfterRenderObservable=new observable_Observable,this.onClearObservable=new observable_Observable,this.onResizeObservable=new observable_Observable,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=math_vector_Vector3.Zero(),!(i=this.getScene()))return;let R=this.getScene().getEngine();if(this._gammaSpace=y,this._coordinatesMode=texture_Texture.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=n,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=R.onResizeObservable.add(()=>{}),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=s,this._renderingManager=new RenderingManager(i),this._renderingManager._useSceneAutoClearSetup=!0,c)return;this._renderTargetOptions={generateMipMaps:r,type:a,format:null!==(C=this._format)&&void 0!==C?C:void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:_,creationFlags:p,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:E,label:this.name},this.samplingMode===texture_Texture.NEAREST_SAMPLINGMODE&&(this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE),d||(n?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=texture_Texture.INVCUBIC_MODE,this._textureMatrix=math_vector_Matrix.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,r=1,s=14){var a;null===(a=this._renderTarget)||void 0===a||a.createDepthStencilTexture(e,t,i,r,s)}_releaseRenderPassId(){if(this._scene){let e=this._scene.getEngine();for(let t=0;t<this._renderPassIds.length;++t)e.releaseRenderPassId(this._renderPassIds[t])}this._renderPassIds=[]}_createRenderPassId(){this._releaseRenderPassId();let e=this._scene.getEngine(),t=this._isCubeData?6:this.getRenderLayers()||1;for(let i=0;i<t;++i)this._renderPassIds[i]=e.createRenderPassId(`RenderTargetTexture - ${this.name}#${i}`)}_processSizeParameter(e,t=!0){if(e.ratio){this._sizeRatio=e.ratio;let t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e;t&&this._createRenderPassId()}get samples(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e.samples)&&void 0!==t?t:this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}addPostProcess(e){if(!this._postProcessManager){let e=this.getScene();if(!e)return;this._postProcessManager=new PostProcessManager(e),this._postProcesses=[]}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(let e of this._postProcesses)e.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;let t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return -1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){let e=this._size.layers;return e||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){let t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var t;let i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;let r=this.getScene();r&&(this._processSizeParameter(e,!1),i?this._renderTarget=r.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=r.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 r;let s=this.getScene();if(!s)return i;let a=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let e=0;e<this._waitingRenderList.length;e++){let t=this._waitingRenderList[e],i=s.getMeshById(t);i&&this.renderList.push(i)}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];let e=this.getScene();if(!e)return i;let t=e.meshes;for(let e=0;e<t.length;e++){let i=t[e];this.renderListPredicate(i)&&this.renderList.push(i)}}let n=a.currentRenderPassId;this.onBeforeBindObservable.notifyObservers(this);let o=null!==(r=this.activeCamera)&&void 0!==r?r:s.activeCamera,l=s.activeCamera;o&&(o!==s.activeCamera&&(s.setTransformMatrix(o.getViewMatrix(),o.getProjectionMatrix(!0)),s.activeCamera=o),a.setViewport(o.rigParent?o.rigParent.viewport:o.viewport,this.getRenderWidth(),this.getRenderHeight())),this._defaultRenderListPrepared=!1;let h=i;if(i){s.getViewMatrix()||s.updateTransformMatrix();let e=this.is2DArray?this.getRenderLayers():this.isCube?6:1;for(let t=0;t<e&&h;t++){let e=null,r=this.renderList?this.renderList:s.getActiveMeshes().data,n=this.renderList?this.renderList.length:s.getActiveMeshes().length;a.currentRenderPassId=this._renderPassIds[t],this.onBeforeRenderObservable.notifyObservers(t),this.getCustomRenderList&&(e=this.getCustomRenderList(t,r,n)),e||(e=r),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0);for(let t=0;t<e.length&&h;++t){let r=e[t];if(r.isEnabled()&&!r.isBlocked&&r.isVisible&&r.subMeshes){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(r,this.refreshRate,i)){h=!1;continue}}else if(!r.isReady(!0)){h=!1;continue}}}this.onAfterRenderObservable.notifyObservers(t),(this.is2DArray||this.isCube)&&(s.incrementRenderId(),s.resetCachedMaterial())}}else if(this.is2DArray&&!this.isMulti)for(let i=0;i<this.getRenderLayers();i++)this._renderToTarget(0,e,t,i,o),s.incrementRenderId(),s.resetCachedMaterial();else if(this.isCube&&!this.isMulti)for(let i=0;i<6;i++)this._renderToTarget(i,e,t,void 0,o),s.incrementRenderId(),s.resetCachedMaterial();else this._renderToTarget(0,e,t,void 0,o);return this.onAfterUnbindObservable.notifyObservers(this),a.currentRenderPassId=n,l&&(s.activeCamera=l,(s.getEngine().scenes.length>1||this.activeCamera&&this.activeCamera!==s.activeCamera)&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),a.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){let i=e*t,r=engine_Engine.NearestPOT(i+16384/(128+i));return Math.min(engine_Engine.FloorPOT(e),r)}_prepareRenderingManager(e,t,i,r){let s=this.getScene();if(!s)return;this._renderingManager.reset();let a=s.getRenderId();for(let n=0;n<t;n++){let t=e[n];if(t&&!t.isBlocked){let e;if(this.customIsReadyFunction){if(!this.customIsReadyFunction(t,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!t.isReady(0===this.refreshRate)){this.resetRefreshCounter();continue}if(!t._internalAbstractMeshDataInfo._currentLODIsUpToDate&&s.activeCamera&&(t._internalAbstractMeshDataInfo._currentLOD=s.customLODSelector?s.customLODSelector(t,this.activeCamera||s.activeCamera):t.getLOD(this.activeCamera||s.activeCamera),t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0),!t._internalAbstractMeshDataInfo._currentLOD)continue;let n=t._internalAbstractMeshDataInfo._currentLOD;if(n._preActivateForIntermediateRendering(a),e=!!r&&!!i&&(t.layerMask&i.layerMask)==0,t.isEnabled()&&t.isVisible&&t.subMeshes&&!e&&(n!==t&&n._activate(a,!0),t._activate(a,!0)&&t.subMeshes.length)){t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(n=t):n._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,n._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(let e=0;e<n.subMeshes.length;e++){let t=n.subMeshes[e];this._renderingManager.dispatch(t,n)}}}}for(let e=0;e<s.particleSystems.length;e++){let t=s.particleSystems[e],i=t.emitter;t.isStarted()&&i&&(!i.position||i.isEnabled())&&this._renderingManager.dispatchParticles(t)}}_bindFrameBuffer(e=0,t=0){let i=this.getScene();if(!i)return;let r=i.getEngine();this._renderTarget&&r.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):r&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0,s=null){var a,n,o,l,h,c;let u=this.getScene();if(!u)return;let d=u.getEngine();null===(a=d._debugPushGroup)||void 0===a||a.call(d,`render to face #${e} layer #${r}`,1),this._prepareFrame(u,e,r,t),this.is2DArray?(d.currentRenderPassId=this._renderPassIds[r],this.onBeforeRenderObservable.notifyObservers(r)):(d.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));let _=d.snapshotRendering&&1===d.snapshotRenderingMode;if(_)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||u.clearColor,!0,!0,!0);else{let a=null,c=this.renderList?this.renderList:u.getActiveMeshes().data,_=this.renderList?this.renderList.length:u.getActiveMeshes().length;for(let t of(this.getCustomRenderList&&(a=this.getCustomRenderList(this.is2DArray?r:e,c,_)),a?this._prepareRenderingManager(a,a.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(c,_,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),a=c),u._beforeRenderTargetClearStage))t.action(this,e,r);for(let t of(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||u.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||u.updateTransformMatrix(!0),u._beforeRenderTargetDrawStage))t.action(this,e,r);for(let t of(this._renderingManager.render(this.customRenderFunction,a,this.renderParticles,this.renderSprites),u._afterRenderTargetDrawStage))t.action(this,e,r);let p=null!==(o=null===(n=this._texture)||void 0===n?void 0:n.generateMipMaps)&&void 0!==o&&o;for(let i of(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&&u.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e),u._afterRenderTargetPostProcessStage))i.action(this,e,r);this._texture&&(this._texture.generateMipMaps=p),this._doNotChangeAspectRatio||u.updateTransformMatrix(!0),i&&dumpTools_DumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),d)}this._unbindFrameBuffer(d,e),this._texture&&this.isCube&&5===e&&d.generateMipMapsForCubemap(this._texture),null===(c=d._debugPopGroup)||void 0===c||c.call(d,1)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){let e=this.getSize(),t=new renderTargetTexture_RenderTargetTexture(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;let e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t<this.renderList.length;t++)e.renderList.push(this.renderList[t].id);return e}disposeFramebufferObjects(){var e;null===(e=this._renderTarget)||void 0===e||e.dispose(!0)}releaseInternalTexture(){var e;null===(e=this._renderTarget)||void 0===e||e.releaseTextures(),this._texture=null}dispose(){var e;this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._releaseRenderPassId(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;let t=this.getScene();if(!t)return;let i=t.customRenderTargets.indexOf(this);for(let e of(i>=0&&t.customRenderTargets.splice(i,1),t.cameras))(i=e.customRenderTargets.indexOf(this))>=0&&e.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}};renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE=0,renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME=1,renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,texture_Texture._CreateRenderTargetTexture=(e,t,i,r,s)=>new renderTargetTexture_RenderTargetTexture(e,t,i,r);let ProceduralTextureSceneComponent=class ProceduralTextureSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){tools_Tools.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e<this.scene.proceduralTextures.length;e++){let t=this.scene.proceduralTextures[e];t._shouldRender()&&t.render()}tools_Tools.EndPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0)}}};let W=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.proceduralVertexShader=W;let proceduralTexture_ProceduralTexture=class proceduralTexture_ProceduralTexture extends texture_Texture{constructor(e,t,i,r,s=null,a=!0,n=!1,o=0){super(null,r,!a),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new observable_Observable,this.onBeforeGenerationObservable=new observable_Observable,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=[],this._samplers=[],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 l=(r=this.getScene()||engineStore_EngineStore.LastCreatedScene)._getComponent(sceneComponent_SceneComponentConstants.NAME_PROCEDURALTEXTURE);l||(l=new ProceduralTextureSceneComponent(r),r._addComponent(l)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=o,this._generateMipMaps=a,this._drawWrapper=new drawWrapper_DrawWrapper(this._fullEngine),this.setFragment(i),this._fallbackTexture=s;let h=this._createRtWrapper(n,t,a,o);this._texture=h.texture;let c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(this._fullEngine,c,buffer_VertexBuffer.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r}),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(){let 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(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}isReady(){let e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;let t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;let i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[buffer_VertexBuffer.PositionKind],this._uniforms,this._samplers,t,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;let i=this._texture.isCube;this._rtWrapper.dispose();let r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return -1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;let r=this.getScene();if(!r)return;let s=this._fullEngine;if(s.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),s.setState(!1),!this.nodeMaterialSource){for(let e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(let e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(let e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(let e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(let e in this._colors4){let t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(let e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(let 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);let a=s.currentViewport;if(this.isCube)for(let e=0;e<6;e++)s.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(material_Material.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(r.clearColor,!0,!1,!1),s.drawElementsType(material_Material.TriangleFillMode,0,6);s.unBindFramebuffer(this._rtWrapper,this.isCube),a&&s.setViewport(a),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(){let e=this.getSize(),t=new proceduralTexture_ProceduralTexture(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(){let e=this.getScene();if(!e)return;let t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);let i=this._vertexBuffers[buffer_VertexBuffer.PositionKind];i&&(i.dispose(),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}};__decorate([serialize()],proceduralTexture_ProceduralTexture.prototype,"isEnabled",void 0),__decorate([serialize()],proceduralTexture_ProceduralTexture.prototype,"autoClear",void 0),__decorate([serialize()],proceduralTexture_ProceduralTexture.prototype,"_generateMipMaps",void 0),__decorate([serialize()],proceduralTexture_ProceduralTexture.prototype,"_size",void 0),__decorate([serialize()],proceduralTexture_ProceduralTexture.prototype,"refreshRate",null),h["BABYLON.ProceduralTexture"]=proceduralTexture_ProceduralTexture,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"}(eT||(eT={}));let TrigonometryBlock=class TrigonometryBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.operation=eT.Cos,this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.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);let t=this._outputs[0],i="";switch(this.operation){case eT.Cos:i="cos";break;case eT.Sin:i="sin";break;case eT.Abs:i="abs";break;case eT.Exp:i="exp";break;case eT.Exp2:i="exp2";break;case eT.Round:i="round";break;case eT.Floor:i="floor";break;case eT.Ceiling:i="ceil";break;case eT.Sqrt:i="sqrt";break;case eT.Log:i="log";break;case eT.Tan:i="tan";break;case eT.ArcTan:i="atan";break;case eT.ArcCos:i="acos";break;case eT.ArcSin:i="asin";break;case eT.Fract:i="fract";break;case eT.Sign:i="sign";break;case eT.Radians:i="radians";break;case eT.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName}); +`,this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${eT[this.operation]}; +`;return e}};h["BABYLON.TrigonometryBlock"]=TrigonometryBlock;let H={effect:null,subMesh:null};let NodeMaterialDefines=class NodeMaterialDefines extends MaterialDefines{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!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}};let NodeMaterial=class NodeMaterial extends PushMaterial{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()||"PrePassTextureBlock"===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||engineStore_EngineStore.LastCreatedScene),this._buildId=NodeMaterial._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new math_vector_Matrix,this._cachedWorldViewProjectionMatrix=new math_vector_Matrix,this._optimizers=[],this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new observable_Observable,this._vertexOutputNodes=[],this._fragmentOutputNodes=[],this.attachedBlocks=[],this._mode=eb.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),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){tools_Tools.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(let t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){let t=this._optimizers.indexOf(e);if(!(t>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){let t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return(e.target&e_.Vertex)!=0&&this._addVertexOutputNode(e),(e.target&e_.Fragment)!=0&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||((e.target&e_.Vertex)!=0&&this._removeVertexOutputNode(e),(e.target&e_.Fragment)!=0&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=e_.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){let 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=e_.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){let t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){e.target===e_.VertexAndFragment?i.push(e):t.target===e_.Fragment&&e.target===e_.Vertex&&e._preparationId!==this._buildId&&i.push(e),this._initializeBlock(e,t,i,r)}_initializeBlock(e,t,i,r=!0){if(e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){let t=e.getClassName();for(let 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(let s of e.inputs){s.associatedVariableName="";let a=s.connectedPoint;if(a){let s=a.ownerBlock;s!==e&&this._processInitializeOnLink(s,t,i,r)}}for(let s of(e.isTeleportOut&&e.entryPoint&&this._processInitializeOnLink(e.entryPoint,t,i,r),e.outputs))s.associatedVariableName=""}_resetDualBlocks(e,t){for(let i of(e.target===e_.VertexAndFragment&&(e.buildId=t),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._resetDualBlocks(e.entryPoint,t)}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;let r=this.getScene().getEngine(),s=this._mode===eb.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 NodeMaterialBuildState,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=e_.Vertex,this._fragmentCompilationState=new NodeMaterialBuildState,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=e_.Fragment,this._sharedData=new NodeMaterialBuildStateSharedData,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;let a=[],n=[];for(let e of this._vertexOutputNodes)a.push(e),this._initializeBlock(e,this._vertexCompilationState,n,i);for(let e of this._fragmentOutputNodes)n.push(e),this._initializeBlock(e,this._fragmentCompilationState,a,i);for(let e of(this.optimize(),a))e.build(this._vertexCompilationState,a);for(let e of(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,n))this._resetDualBlocks(e,this._buildId-1);for(let e of n)e.build(this._fragmentCompilationState,n);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=NodeMaterial._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);let o=this.getScene().meshes;for(let e of o)if(e.subMeshes)for(let t of e.subMeshes){if(t.getMaterial()!==this||!t.materialDefines)continue;let e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();let l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(let e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){let i=t.NORMAL,r=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(buffer_VertexBuffer.NormalKind),t.TANGENT=e.isVerticesDataPresent(buffer_VertexBuffer.TangentKind);let a=e.useVertexColors&&e.isVerticesDataPresent(buffer_VertexBuffer.ColorKind);t.VERTEXCOLOR_NME=a;let n=!1;for(let i=1;i<=6;++i){let r=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),n=n||t["UV"+i]!==r}let o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;MaterialHelper.PrepareDefinesForPrePass(this.getScene(),t,!o),(i!==t.NORMAL||r!==t.TANGENT||s!==t.VERTEXCOLOR_NME||n)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){let e=this.getBlockByPredicate(e=>"PrePassOutputBlock"===e.getClassName()),t=[4];return!e||this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t}get prePassTextureInputs(){let e=this.getAllTextureBlocks().filter(e=>"PrePassTextureBlock"===e.getClassName()),t=[];for(let i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){let t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");for(let r of(i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]})),t))i.texturesRequired.includes(r)||i.texturesRequired.push(r);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,r,s,a=0,n=5){return this.mode!==eb.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,s,a,n)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,s,a,n=0,o=5){let l=this.name+this._buildId,h=new NodeMaterialDefines,c=new abstractMesh_AbstractMesh(l+"PostProcess",this.getScene()),u=this._buildId;return this._processDefines(c,h),effect_Effect.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 postProcess_PostProcess(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,s,a,h.toString(),n,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,o),e.nodeMaterialSource=this,e.onApplyObservable.add(t=>{u!==this._buildId&&(delete effect_Effect.ShadersStore[l+"VertexShader"],delete effect_Effect.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId);let i=this._processDefines(c,h);i&&(effect_Effect.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),TimingTools.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!==eb.ProceduralTexture)return console.log("Incompatible material mode"),null;let i=this.name+this._buildId,r=new proceduralTexture_ProceduralTexture(i,e,null,t),s=new abstractMesh_AbstractMesh(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};let a=new NodeMaterialDefines,n=this._processDefines(s,a);effect_Effect.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[buffer_VertexBuffer.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),null==n?void 0:n.fallbacks,void 0);r.nodeMaterialSource=this,r._setEffect(o);let l=this._buildId;return r.onBeforeGenerationObservable.add(()=>{l!==this._buildId&&(delete effect_Effect.ShadersStore[i+"VertexShader"],delete effect_Effect.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,a.markAllAsDirty(),l=this._buildId);let e=this._processDefines(s,a);e&&(effect_Effect.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),TimingTools.SetImmediate(()=>{o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[buffer_VertexBuffer.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),null==e?void 0:e.fallbacks,void 0),r._setEffect(o)})),this._checkInternals(o)}),r}_createEffectForParticles(e,t,i,r,s,a,n,o=""){let l=this.name+this._buildId+"_"+t;a||(a=new NodeMaterialDefines),n||(n=this.getScene().getMeshByName(this.name+"Particle"))||((n=new abstractMesh_AbstractMesh(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId,c=[],u=o;if(!s){let o=this._processDefines(n,a);effect_Effect.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t),u=c.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString()+"\n"+u,null==o?void 0:o.fallbacks,i,r,e),e.setCustomEffect(s,t)}s.onBindObservable.add(s=>{h!==this._buildId&&(delete effect_Effect.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,a.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t);let d=c.join("\n");d!==u&&(a.markAllAsDirty(),u=d);let _=this._processDefines(n,a);if(_){effect_Effect.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString()+"\n"+u,null==_?void 0:_.fallbacks,i,r,e),e.setCustomEffect(s,t),this._createEffectForParticles(e,t,i,r,s,a,n,o);return}this._checkInternals(s)})}_checkInternals(e){if(this._sharedData.animatedInputs){let e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(let t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(let t of this._sharedData.bindableBlocks)t.bind(e,this);for(let t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){if(this.mode!==eb.Particle){console.log("Incompatible material mode");return}this._createEffectForParticles(e,BaseParticleSystem.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,BaseParticleSystem.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==eb.Material){console.log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,r){let s=null,a=this.getScene();if(MaterialHelper.PrepareDefinesForCamera(a,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(r=>{r.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(s=>{s.prepareDefines(e,this,t,i,r)}),t.isDirty){let 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)});let r=[];this._sharedData.dynamicUniformBlocks.forEach(e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,r)});let a=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(e=>{let t=a.indexOf(e);-1===t&&a.push(e)});let n=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(e=>{let t=n.indexOf(e);-1===t&&n.push(e)});let o=new EffectFallbacks;this._sharedData.blocksWithFallbacks.forEach(t=>{t.provideFallbacks(e,o)}),s={lightDisposed:i,uniformBuffers:r,mergedUniforms:a,mergedSamplers:n,fallbacks:o}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;let r=this.getScene();if(this._sharedData.animatedInputs){let e=r.getFrameId();if(this._animationFrame!==e){for(let e of this._sharedData.animatedInputs)e.animate(r);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new NodeMaterialDefines);let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=r.getEngine();if(this._prepareDefinesForAttributes(e,s),this._sharedData.blockingBlocks.some(t=>!t.isReady(e,this,s,i)))return!1;let n=this._processDefines(e,s,i,t);if(n){let e=t.effect,i=s.toString(),o=a.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:n.mergedUniforms,uniformBuffersNames:n.uniformBuffers,samplers:n.mergedSamplers,defines:i,fallbacks:n.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:s.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},a);if(o){if(this._onEffectCreatedObservable&&(H.effect=o,H.subMesh=t,this._onEffectCreatedObservable.notifyObservers(H)),this.allowShaderHotSwapping&&e&&!o.isReady()){if(o=e,s.markAsUnprocessed(),n.lightDisposed)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(o,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader +${this._vertexCompilationState.compilationString} + +// Fragment shader +${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){let t=this.getScene();if(!this._activeEffect)return;let i=this._sharedData.hints;for(let r of(i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),this._sharedData.inputBlocks))r._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);let a=this._mustRebind(r,s,t.visibility),n=this._sharedData;if(a){for(let e of n.bindableBlocks)e.bind(s,this,t,i);for(let e of n.forcedBindableBlocks)e.bind(s,this,t,i);for(let e of n.inputBlocks)e._transmit(s,r,this)}else if(!this.isFrozen)for(let e of n.forcedBindableBlocks)e.bind(s,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){let 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(){let e=[];for(let t of this.attachedBlocks)NodeMaterial._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(let t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(let e of this.getTextureBlocks().filter(e=>e.texture).map(e=>e.texture))e.dispose();for(let e of this.attachedBlocks)e.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){let 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){let i=e&&e.editorURL?e.editorURL:NodeMaterial.EditorURL;tools_Tools.LoadBabylonScript(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;let e=new InputBlock("Position");e.setAsAttribute("position");let t=new InputBlock("World");t.setAsSystemValue(ev.World);let i=new TransformBlock("WorldPos");e.connectTo(i),t.connectTo(i);let r=new InputBlock("ViewProjection");r.setAsSystemValue(ev.ViewProjection);let s=new TransformBlock("WorldPos * ViewProjectionTransform");i.connectTo(s),r.connectTo(s);let a=new VertexOutputBlock("VertexOutput");s.connectTo(a);let n=new InputBlock("color");n.value=new math_color_Color4(.8,.8,.8,1);let o=new FragmentOutputBlock("FragmentOutput");n.connectTo(o),this.addOutputNode(a),this.addOutputNode(o),this._mode=eb.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;let e=new InputBlock("Position");e.setAsAttribute("position2d");let t=new InputBlock("Constant1");t.isConstant=!0,t.value=1;let i=new VectorMergerBlock("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new VertexOutputBlock("VertexOutput");i.connectTo(r);let s=new InputBlock("Scale");s.visibleInInspector=!0,s.value=new math_vector_Vector2(1,1);let a=new RemapBlock("uv0");e.connectTo(a);let n=new MultiplyBlock("UV scale");a.connectTo(n),s.connectTo(n);let o=new CurrentScreenBlock("CurrentScreen");n.connectTo(o),o.texture=new texture_Texture("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());let l=new FragmentOutputBlock("FragmentOutput");o.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=eb.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;let e=new InputBlock("Position");e.setAsAttribute("position2d");let t=new InputBlock("Constant1");t.isConstant=!0,t.value=1;let i=new VectorMergerBlock("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new VertexOutputBlock("VertexOutput");i.connectTo(r);let s=new InputBlock("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=ex.Time,s.isConstant=!1;let a=new InputBlock("Color3");a.value=new math_color_Color3(1,1,1),a.isConstant=!1;let n=new FragmentOutputBlock("FragmentOutput"),o=new VectorMergerBlock("VectorMerger");o.visibleInInspector=!1;let l=new TrigonometryBlock("Cos");l.operation=eT.Cos,e.connectTo(o),s.output.connectTo(l.input),l.output.connectTo(o.z),o.xyzOut.connectTo(n.rgb),this.addOutputNode(r),this.addOutputNode(n),this._mode=eb.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;let e=new InputBlock("uv");e.setAsAttribute("particle_uv");let t=new ParticleTextureBlock("ParticleTexture");e.connectTo(t);let i=new InputBlock("Color");i.setAsAttribute("particle_color");let r=new MultiplyBlock("Texture * Color");t.connectTo(r),i.connectTo(r);let s=new ParticleRampGradientBlock("ParticleRampGradient");r.connectTo(s);let a=new ColorSplitterBlock("ColorSplitter");i.connectTo(a);let n=new ParticleBlendMultiplyBlock("ParticleBlendMultiply");s.connectTo(n),t.connectTo(n,{output:"a"}),a.connectTo(n,{output:"a"});let o=new FragmentOutputBlock("FragmentOutput");n.connectTo(o),this.addOutputNode(o),this._mode=eb.Particle}async loadAsync(e,t=""){return NodeMaterial.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}generateCode(){let e=[],t=[],i=["const","var","let"];for(let e of this._vertexOutputNodes)this._gatherBlocks(e,t);let r=[];for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,r);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); +`;for(let r of(s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${eb[this.mode]}; +`,t))r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(let t of r)t.isInput&&-1===e.indexOf(t)&&(s+=t._dumpCode(i,e));for(let t of(e=[],s+="\n// Connections\n",this._vertexOutputNodes))s+=t._dumpCodeForOutputConnections(e);for(let t of this._fragmentOutputNodes)s+=t._dumpCodeForOutputConnections(e);for(let e of(s+="\n// Output nodes\n",this._vertexOutputNodes))s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); +`;for(let e of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); +`;return s+`nodeMaterial.build(); +`}serialize(e){let t=e?{}:decorators_SerializationHelper.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{for(let e of(t.customType="BABYLON.NodeMaterial",t.outputNodes=[],this._vertexOutputNodes))this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}for(let e of(t.blocks=[],i))t.blocks.push(e.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let a=i[s.id];if(a){for(let n of s.inputs)if(i[n.targetBlockId]===e&&n.targetConnectionName===r.name){let e=a.getInputByName(n.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(a,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){var r;i||this.clear();let s={};for(let i of e.blocks){let e=h[i.customType];if(e){let r=new e;r._deserialize(i,this.getScene(),t),s[i.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;if(t){let i=s[t];i.attachToEndpoint(e)}}for(let t=0;t<e.blocks.length;t++){let r=e.blocks[t],a=s[r.id];a&&(!a.inputs.length||i)&&this._restoreConnections(a,e,s)}if(e.outputNodes)for(let t of e.outputNodes)this.addOutputNode(s[t]);if(e.locations||e.editorData&&e.editorData.locations){let t=e.locations||e.editorData.locations;for(let e of t)s[e.blockId]&&(e.blockId=s[e.blockId].uniqueId);i&&this.editorData&&this.editorData.locations&&t.concat(this.editorData.locations),e.locations?this.editorData={locations:t}:(this.editorData=e.editorData,this.editorData.locations=t);let r=[];for(let e in s)r[e]=s[e].uniqueId;this.editorData.map=r}this.comment=e.comment,void 0!==e.forceAlphaBlending&&(this.forceAlphaBlending=e.forceAlphaBlending),i||(this._mode=null!==(r=e.mode)&&void 0!==r?r:eb.Material)}loadFromSerialization(e,t="",i=!1){this.parseSerializedObject(e,t,i)}clone(e,t=!1){let i=this.serialize(),r=decorators_SerializationHelper.Clone(()=>new NodeMaterial(e,this.getScene(),this.options),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}whenTexturesReadyAsync(){let e=[];return this.getActiveTextures().forEach(t=>{let i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((e,t)=>{i.onLoadedObservable.addOnce(()=>{e()}),i.onErrorObservable.addOnce(e=>{t(e)})}))}),Promise.all(e)}static Parse(e,t,i=""){let r=decorators_SerializationHelper.Parse(()=>new NodeMaterial(e.name,t),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,r="",s=!1,a){let n=null!=a?a:new NodeMaterial(e,i),o=await i._loadFileAsync(t),l=JSON.parse(o);return n.parseSerializedObject(l,r),s||n.build(),n}static ParseFromSnippetAsync(e,t=engineStore_EngineStore.LastCreatedScene,i="",r,s=!1,a=!1){return"_BLANK"===e?Promise.resolve(NodeMaterial.CreateDefault("blank",t)):new Promise((n,o)=>{let l=new webRequest_WebRequest;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let h=JSON.parse(JSON.parse(l.responseText).jsonPayload),c=JSON.parse(h.nodeMaterial);r||((r=decorators_SerializationHelper.Parse(()=>new NodeMaterial(e,t),c,t,i)).uniqueId=t.getUniqueId()),r.parseSerializedObject(c),r.snippetId=e;try{s||r.build()}catch(e){o(e)}a?r.whenTexturesReadyAsync().then(()=>{n(r)}).catch(e=>{o(e)}):n(r)}else o("Unable to load the snippet "+e)}}),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()})}static CreateDefault(e,t){let i=new NodeMaterial(e,t);return i.setToDefault(),i.build(),i}};function CreateIcoSphereVertexData(e){let t;let i=e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,r=e.radius||1,s=void 0===e.flat||e.flat,a=0|(e.subdivisions||4),n=e.radiusX||r,o=e.radiusY||r,l=e.radiusZ||r,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],u=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],d=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],_=[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],p=138/1024,f=239/1024,m=60/1024,g=26/1024,v=-40/1024,x=20/1024,b=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],T=[],S=[],C=[],E=[],y=0,R=[,,,],P=[,,,];for(t=0;t<3;t++)R[t]=math_vector_Vector3.Zero(),P[t]=math_vector_Vector2.Zero();for(let e=0;e<20;e++){for(t=0;t<3;t++){let i=u[3*e+t];R[t].copyFromFloats(c[3*d[i]],c[3*d[i]+1],c[3*d[i]+2]),R[t].normalize(),P[t].copyFromFloats(_[2*i]*p+m+b[e]*v,_[2*i+1]*f+g+b[e]*x)}let interp_vertex=(e,t,i,r)=>{let h;let c=math_vector_Vector3.Lerp(R[0],R[2],t/a),u=math_vector_Vector3.Lerp(R[1],R[2],t/a),d=a===t?R[2]:math_vector_Vector3.Lerp(c,u,e/(a-t));if(d.normalize(),s){let e=math_vector_Vector3.Lerp(R[0],R[2],r/a),t=math_vector_Vector3.Lerp(R[1],R[2],r/a);h=math_vector_Vector3.Lerp(e,t,i/(a-r))}else h=new math_vector_Vector3(d.x,d.y,d.z);h.x/=n,h.y/=o,h.z/=l,h.normalize();let _=math_vector_Vector2.Lerp(P[0],P[2],t/a),p=math_vector_Vector2.Lerp(P[1],P[2],t/a),f=a===t?P[2]:math_vector_Vector2.Lerp(_,p,e/(a-t));S.push(d.x*n,d.y*o,d.z*l),C.push(h.x,h.y,h.z),E.push(f.x,CompatibilityOptions.UseOpenGLOrientationForUV?1-f.y:f.y),T.push(y),y++};for(let e=0;e<a;e++)for(let t=0;t+e<a;t++)interp_vertex(t,e,t+1/3,e+1/3),interp_vertex(t+1,e,t+1/3,e+1/3),interp_vertex(t,e+1,t+1/3,e+1/3),t+e+1<a&&(interp_vertex(t+1,e,t+2/3,e+2/3),interp_vertex(t+1,e+1,t+2/3,e+2/3),interp_vertex(t,e+1,t+2/3,e+2/3))}mesh_vertexData_VertexData._ComputeSides(i,S,T,C,E,e.frontUVs,e.backUVs);let A=new mesh_vertexData_VertexData;return A.indices=T,A.positions=S,A.normals=C,A.uvs=E,A}function CreateIcoSphere(e,t={},i=null){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateIcoSphereVertexData(t);return s.applyToMesh(r,t.updatable),r}NodeMaterial._BuildIdGenerator=0,NodeMaterial.EditorURL=`${tools_Tools._DefaultCdnUrl}/v${engine_Engine.Version}/nodeEditor/babylon.nodeEditor.js`,NodeMaterial.SnippetUrl="https://snippet.babylonjs.com",NodeMaterial.IgnoreTexturesAtLoadTime=!1,__decorate([serialize()],NodeMaterial.prototype,"ignoreAlpha",void 0),__decorate([serialize()],NodeMaterial.prototype,"maxSimultaneousLights",void 0),__decorate([serialize("mode")],NodeMaterial.prototype,"_mode",void 0),__decorate([serialize("comment")],NodeMaterial.prototype,"comment",void 0),__decorate([serialize()],NodeMaterial.prototype,"forceAlphaBlending",void 0),h["BABYLON.NodeMaterial"]=NodeMaterial,mesh_vertexData_VertexData.CreateIcoSphere=CreateIcoSphereVertexData,mesh_Mesh.CreateIcoSphere=(e,t,i)=>CreateIcoSphere(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(eS||(eS={})),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"}(eC||(eC={}));let X=[eC.WRIST,eC.THUMB_METACARPAL,eC.THUMB_PHALANX_PROXIMAL,eC.THUMB_PHALANX_DISTAL,eC.THUMB_TIP,eC.INDEX_FINGER_METACARPAL,eC.INDEX_FINGER_PHALANX_PROXIMAL,eC.INDEX_FINGER_PHALANX_INTERMEDIATE,eC.INDEX_FINGER_PHALANX_DISTAL,eC.INDEX_FINGER_TIP,eC.MIDDLE_FINGER_METACARPAL,eC.MIDDLE_FINGER_PHALANX_PROXIMAL,eC.MIDDLE_FINGER_PHALANX_INTERMEDIATE,eC.MIDDLE_FINGER_PHALANX_DISTAL,eC.MIDDLE_FINGER_TIP,eC.RING_FINGER_METACARPAL,eC.RING_FINGER_PHALANX_PROXIMAL,eC.RING_FINGER_PHALANX_INTERMEDIATE,eC.RING_FINGER_PHALANX_DISTAL,eC.RING_FINGER_TIP,eC.PINKY_FINGER_METACARPAL,eC.PINKY_FINGER_PHALANX_PROXIMAL,eC.PINKY_FINGER_PHALANX_INTERMEDIATE,eC.PINKY_FINGER_PHALANX_DISTAL,eC.PINKY_FINGER_TIP],Y={[eS.WRIST]:[eC.WRIST],[eS.THUMB]:[eC.THUMB_METACARPAL,eC.THUMB_PHALANX_PROXIMAL,eC.THUMB_PHALANX_DISTAL,eC.THUMB_TIP],[eS.INDEX]:[eC.INDEX_FINGER_METACARPAL,eC.INDEX_FINGER_PHALANX_PROXIMAL,eC.INDEX_FINGER_PHALANX_INTERMEDIATE,eC.INDEX_FINGER_PHALANX_DISTAL,eC.INDEX_FINGER_TIP],[eS.MIDDLE]:[eC.MIDDLE_FINGER_METACARPAL,eC.MIDDLE_FINGER_PHALANX_PROXIMAL,eC.MIDDLE_FINGER_PHALANX_INTERMEDIATE,eC.MIDDLE_FINGER_PHALANX_DISTAL,eC.MIDDLE_FINGER_TIP],[eS.RING]:[eC.RING_FINGER_METACARPAL,eC.RING_FINGER_PHALANX_PROXIMAL,eC.RING_FINGER_PHALANX_INTERMEDIATE,eC.RING_FINGER_PHALANX_DISTAL,eC.RING_FINGER_TIP],[eS.LITTLE]:[eC.PINKY_FINGER_METACARPAL,eC.PINKY_FINGER_PHALANX_PROXIMAL,eC.PINKY_FINGER_PHALANX_INTERMEDIATE,eC.PINKY_FINGER_PHALANX_DISTAL,eC.PINKY_FINGER_TIP]};let WebXRHand=class WebXRHand{get handMesh(){return this._handMesh}getHandPartMeshes(e){return Y[e].map(e=>this._jointMeshes[X.indexOf(e)])}getJointMesh(e){return this._jointMeshes[X.indexOf(e)]}constructor(e,t,i,r,s=!1,a=!1,n=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=s,this._jointsInvisible=a,this._jointScaleFactor=n,this._jointTransforms=Array(X.length),this._jointTransformMatrices=new Float32Array(16*X.length),this._tempJointMatrix=new math_vector_Matrix,this._jointRadii=new Float32Array(X.length),this._scene=t[0].getScene();for(let e=0;e<this._jointTransforms.length;e++){let i=this._jointTransforms[e]=new transformNode_TransformNode(X[e],this._scene);i.rotationQuaternion=new math_vector_Quaternion,t[e].rotationQuaternion=new math_vector_Quaternion}i&&this.setHandMesh(i,r),this.xrController.motionController&&(this.xrController.motionController.rootMesh?this.xrController.motionController.rootMesh.setEnabled(!1):this.xrController.motionController.onModelLoadedObservable.add(e=>{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){let e=this._handMesh.skeleton;X.forEach((i,r)=>{let s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[r])})}}updateFromXRFrame(e,t){let i=this.xrController.inputSource.hand;if(!i)return;let r=X.map(e=>i[e]||i.get(e)),s=!1;if(e.fillPoses&&e.fillJointRadii)s=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){s=!0;for(let i=0;i<r.length;i++){let a=e.getJointPose(r[i],t);if(a)this._jointTransformMatrices.set(a.transform.matrix,16*i),this._jointRadii[i]=a.radius||.008;else{s=!1;break}}}s&&(X.forEach((e,t)=>{let i=this._jointTransforms[t];math_vector_Matrix.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);let r=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(r),!this._scene.useRightHandedSystem&&(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}};let WebXRHandTracking=class WebXRHandTracking extends WebXRAbstractFeature{static _GenerateTrackedJointMeshes(e){let t={};return["left","right"].map(i=>{var r,s,a,n,o;let l=[],h=(null===(r=e.jointMeshes)||void 0===r?void 0:r.sourceMesh)||CreateIcoSphere("jointParent",WebXRHandTracking._ICOSPHERE_PARAMS);h.isVisible=!!(null===(s=e.jointMeshes)||void 0===s?void 0:s.keepOriginalVisible);for(let t=0;t<X.length;++t){let r=h.createInstance(`${i}-handJoint-${t}`);if(null===(a=e.jointMeshes)||void 0===a?void 0:a.onHandJointMeshGenerated){let s=e.jointMeshes.onHandJointMeshGenerated(r,t,i);s&&s!==r&&(r.dispose(),r=s)}if(r.isPickable=!1,null===(n=e.jointMeshes)||void 0===n?void 0:n.enablePhysics){let t=(null===(o=e.jointMeshes)||void 0===o?void 0:o.physicsProps)||{};r.scaling.setAll(.02);let i=void 0!==t.impostorType?t.impostorType:physicsImpostor_PhysicsImpostor.SphereImpostor;r.physicsImpostor=new physicsImpostor_PhysicsImpostor(r,i,Object.assign({mass:0},t))}r.rotationQuaternion=new math_vector_Quaternion,r.isVisible=!1,l.push(r)}t[i]=l}),{left:t.left,right:t.right}}static _GenerateDefaultHandMeshesAsync(e,t){return new Promise(async i=>{var r,s,a,n,o;let l={};(null===(s=null===(r=WebXRHandTracking._RightHandGLB)||void 0===r?void 0:r.meshes[1])||void 0===s?void 0:s.isDisposed())&&(WebXRHandTracking._RightHandGLB=null),(null===(n=null===(a=WebXRHandTracking._LeftHandGLB)||void 0===a?void 0:a.meshes[1])||void 0===n?void 0:n.isDisposed())&&(WebXRHandTracking._LeftHandGLB=null);let h=!!(WebXRHandTracking._RightHandGLB&&WebXRHandTracking._LeftHandGLB),c=await Promise.all([WebXRHandTracking._RightHandGLB||sceneLoader_SceneLoader.ImportMeshAsync("",WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL,WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),WebXRHandTracking._LeftHandGLB||sceneLoader_SceneLoader.ImportMeshAsync("",WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL,WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);WebXRHandTracking._RightHandGLB=c[0],WebXRHandTracking._LeftHandGLB=c[1];let u=new NodeMaterial("handShader",e,{emitComments:!1});await u.loadAsync(WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL),u.needDepthPrePass=!0,u.transparencyMode=material_Material.MATERIAL_ALPHABLEND,u.alphaMode=2,u.build(!1);let d=Object.assign({base:math_color_Color3.FromInts(116,63,203),fresnel:math_color_Color3.FromInts(149,102,229),fingerColor:math_color_Color3.FromInts(177,130,255),tipFresnel:math_color_Color3.FromInts(220,200,255)},null===(o=null==t?void 0:t.handMeshes)||void 0===o?void 0:o.customColors),_={base:u.getBlockByName("baseColor"),fresnel:u.getBlockByName("fresnelColor"),fingerColor:u.getBlockByName("fingerColor"),tipFresnel:u.getBlockByName("tipFresnelColor")};_.base.value=d.base,_.fresnel.value=d.fresnel,_.fingerColor.value=d.fingerColor,_.tipFresnel.value=d.tipFresnel,["left","right"].forEach(t=>{let i="left"==t?WebXRHandTracking._LeftHandGLB:WebXRHandTracking._RightHandGLB;if(!i)throw Error("Could not load hand model");let r=i.meshes[1];r._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,r.material=u.clone(`${t}HandShaderClone`,!0),r.isVisible=!1,l[t]=r,h||e.useRightHandedSystem||i.meshes[1].rotate(math_axis_Axis.Y,Math.PI)}),u.dispose(),i({left:l.left,right:l.right})})}static _GenerateDefaultHandMeshRigMapping(e){let t="right"==e?"R":"L";return{[eC.WRIST]:`wrist_${t}`,[eC.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[eC.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[eC.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[eC.THUMB_TIP]:`thumb_tip_${t}`,[eC.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[eC.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[eC.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[eC.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[eC.INDEX_FINGER_TIP]:`index_tip_${t}`,[eC.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[eC.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[eC.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[eC.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[eC.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[eC.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[eC.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[eC.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[eC.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[eC.RING_FINGER_TIP]:`ring_tip_${t}`,[eC.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[eC.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[eC.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[eC.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[eC.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 observable_Observable,this.onHandRemovedObservable=new observable_Observable,this._attachHand=e=>{var t,i,r;if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;let s=e.inputSource.handedness,a=new WebXRHand(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===(r=this.options.jointMeshes)||void 0===r?void 0:r.scaleFactor);this._attachedHands[e.uniqueId]=a,this._trackingHands[s]=a,this.onHandAddedObservable.notifyObservers(a)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";let 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||{};let e={},r={};[[i.rigMapping.left,e],[i.rigMapping.right,r]].forEach(e=>{let t=e[0],i=e[1];t.forEach((e,t)=>{i[X[t]]=e})}),t.handMeshes.customRigMappings={left:e,right:r}}}attach(){var e,t,i,r;return!!super.attach()&&(this._handResources={jointMeshes:WebXRHandTracking._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===(r=this.options.handMeshes)||void 0===r?void 0:r.disableDefaultMeshes)||WebXRHandTracking._GenerateDefaultHandMeshesAsync(engineStore_EngineStore.LastCreatedScene,this.options).then(e=>{var t,i;this._handResources.handMeshes=e,this._handResources.rigMappings={left:WebXRHandTracking._GenerateDefaultHandMeshRigMapping("left"),right:WebXRHandTracking._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;let i=this.getHandByControllerId(e);if(i){let r="left"==i.xrController.inputSource.handedness?"left":"right";(null===(t=this._trackingHands[r])||void 0===t?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[r]=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(),WebXRHandTracking._RightHandGLB=null,WebXRHandTracking._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(e=>e.dispose()),this._handResources.jointMeshes.right.forEach(e=>e.dispose()))}};WebXRHandTracking.Name=webXRFeaturesManager_WebXRFeatureName.HAND_TRACKING,WebXRHandTracking.Version=1,WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",WebXRHandTracking._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},WebXRHandTracking._RightHandGLB=null,WebXRHandTracking._LeftHandGLB=null,WebXRFeaturesManager.AddWebXRFeature(WebXRHandTracking.Name,(e,t)=>()=>new WebXRHandTracking(e,t),WebXRHandTracking.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"}(eE||(eE={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(ey||(ey={})),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"}(eR||(eR={}));let BoneIKController=class BoneIKController{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=math_vector_Vector3.Zero(),this.poleTargetPosition=math_vector_Vector3.Zero(),this.poleTargetLocalOffset=math_vector_Vector3.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=math_vector_Quaternion.Identity(),this._bone1Mat=math_vector_Matrix.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=math_vector_Vector3.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;let r=t.getParent();if(!r){this._notEnoughInformation=!0,logger_Logger.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=r,0===this._bone2.children.length&&!this._bone2.length){this._notEnoughInformation=!0,logger_Logger.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");return}this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();let 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){let 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);let t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone2Length=math_vector_Vector3.Distance(t,i),this._bone1Length=math_vector_Vector3.Distance(i,r)}else{e.computeWorldMatrix(!0);let t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;let i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone1Length=math_vector_Vector3.Distance(i,r)}this._bone1.getRotationMatrixToRef(en.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||void 0==e)&&(e=Math.PI),this._maxAngle=e;let 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;let e=this.targetPosition,t=this.poleTargetPosition,i=BoneIKController._TmpMats[0],r=BoneIKController._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&math_vector_Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);let s=BoneIKController._TmpVecs[0],a=BoneIKController._TmpVecs[1],n=BoneIKController._TmpVecs[2],o=BoneIKController._TmpVecs[3],l=BoneIKController._TmpVecs[4],h=BoneIKController._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(s,o),o.normalize(),math_vector_Vector3.CrossToRef(o,l,a),a.normalize(),math_vector_Vector3.CrossToRef(o,a,n),n.normalize(),math_vector_Matrix.FromXYZAxesToRef(n,o,a,i);let c=this._bone1Length,u=this._bone2Length,d=math_vector_Vector3.Distance(s,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let _=(u*u+d*d-c*c)/(2*u*d),p=(d*d+c*c-u*u)/(2*d*c);_>1&&(_=1),p>1&&(p=1),_<-1&&(_=-1),p<-1&&(p=-1);let f=Math.acos(_),m=Math.acos(p),g=-f-m;if(this._rightHandedSystem)math_vector_Matrix.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),math_vector_Matrix.RotationAxisToRef(this._bendAxis,m,r),r.multiplyToRef(i,i);else{let e=BoneIKController._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,math_vector_Matrix.RotationAxisToRef(e,-m,r),r.multiplyToRef(i,i)}this.poleAngle&&(math_vector_Matrix.RotationAxisToRef(o,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||math_vector_Quaternion.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),math_vector_Quaternion.FromRotationMatrixToRef(i,h),math_vector_Quaternion.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,en.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,en.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,en.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new math_vector_Quaternion),e.getRotationQuaternionToRef(en.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}};BoneIKController._TmpVecs=[math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),math_vector_Vector3.Zero()],BoneIKController._TmpQuat=math_vector_Quaternion.Identity(),BoneIKController._TmpMats=[math_vector_Matrix.Identity(),math_vector_Matrix.Identity()];let BoneLookController=class BoneLookController{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=math_vector_Vector3.Up(),this.upAxisSpace=en.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=math_vector_Quaternion.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=math_vector_Vector3.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),null!=r.maxYaw?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,null!=r.minYaw?this.minYaw=r.minYaw:this.minYaw=-Math.PI,null!=r.maxPitch?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,null!=r.minPitch?this.minPitch=r.minPitch:this.minPitch=-Math.PI,null!=r.slerpAmount&&(this.slerpAmount=r.slerpAmount),null!=r.upAxis&&(this.upAxis=r.upAxis),null!=r.upAxisSpace&&(this.upAxisSpace=r.upAxisSpace),null!=r.yawAxis||null!=r.pitchAxis){let e=math_axis_Axis.Y,t=math_axis_Axis.X;null!=r.yawAxis&&(e=r.yawAxis.clone()).normalize(),null!=r.pitchAxis&&(t=r.pitchAxis.clone()).normalize();let i=math_vector_Vector3.Cross(t,e);this._transformYawPitch=math_vector_Matrix.Identity(),math_vector_Matrix.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==r.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=en.BONE||(this.upAxisSpace=en.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped){this._firstFrameSkipped=!0;return}let e=this.bone,t=BoneLookController._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target,r=BoneLookController._TmpMats[0],s=BoneLookController._TmpMats[1],a=this.mesh,n=e.getParent(),o=BoneLookController._TmpVecs[1];o.copyFrom(this.upAxis),this.upAxisSpace==en.BONE&&n?(this._transformYawPitch&&math_vector_Vector3.TransformCoordinatesToRef(o,this._transformYawPitchInv,o),n.getDirectionToRef(o,this.mesh,o)):this.upAxisSpace==en.LOCAL&&(a.getDirectionToRef(o,o),(1!=a.scaling.x||1!=a.scaling.y||1!=a.scaling.z)&&o.normalize());let l=!1,h=!1;if((this._maxYaw!=Math.PI||this._minYaw!=-Math.PI)&&(l=!0),(this._maxPitch!=Math.PI||this._minPitch!=-Math.PI)&&(h=!0),l||h){let e=BoneLookController._TmpMats[2],r=BoneLookController._TmpMats[3];if(this.upAxisSpace==en.BONE&&1==o.y&&n)n.getRotationMatrixToRef(en.WORLD,this.mesh,e);else if(this.upAxisSpace!=en.LOCAL||1!=o.y||n){let t=BoneLookController._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&math_vector_Vector3.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),n?n.getDirectionToRef(t,this.mesh,t):a.getDirectionToRef(t,t);let i=math_vector_Vector3.Cross(o,t);i.normalize(),t=math_vector_Vector3.Cross(i,o),math_vector_Matrix.FromXYZAxesToRef(i,o,t,e)}else e.copyFrom(a.getWorldMatrix());e.invertToRef(r);let s=null;if(h){let a=BoneLookController._TmpVecs[3];i.subtractToRef(t,a),math_vector_Vector3.TransformCoordinatesToRef(a,r,a),s=Math.sqrt(a.x*a.x+a.z*a.z);let n=Math.atan2(a.y,s),o=n;n>this._maxPitch?(a.y=this._maxPitchTan*s,o=this._maxPitch):n<this._minPitch&&(a.y=this._minPitchTan*s,o=this._minPitch),n!=o&&(math_vector_Vector3.TransformCoordinatesToRef(a,e,a),a.addInPlace(t),i=a)}if(l){let a=BoneLookController._TmpVecs[4];i.subtractToRef(t,a),math_vector_Vector3.TransformCoordinatesToRef(a,r,a);let n=Math.atan2(a.x,a.z),o=this.useAbsoluteValueForYaw?Math.abs(n):n,l=n;if((o>this._maxYaw||o<this._minYaw)&&(null==s&&(s=Math.sqrt(a.x*a.x+a.z*a.z)),this._yawRange>Math.PI?this._isAngleBetween(n,this._maxYaw,this._midYawConstraint)?(a.z=this._maxYawCos*s,a.x=this._maxYawSin*s,l=this._maxYaw):this._isAngleBetween(n,this._midYawConstraint,this._minYaw)&&(a.z=this._minYawCos*s,a.x=this._minYawSin*s,l=this._minYaw):o>this._maxYaw?(a.z=this._maxYawCos*s,a.x=this._maxYawSin*s,n<0&&this.useAbsoluteValueForYaw&&(a.x*=-1),l=this._maxYaw):o<this._minYaw&&(a.z=this._minYawCos*s,a.x=this._minYawSin*s,n<0&&this.useAbsoluteValueForYaw&&(a.x*=-1),l=this._minYaw)),this._slerping&&this._yawRange>Math.PI){let e=BoneLookController._TmpVecs[8];e.copyFrom(math_axis_Axis.Z),this._transformYawPitch&&math_vector_Vector3.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);let t=BoneLookController._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),math_vector_Vector3.TransformCoordinatesToRef(e,t,e),math_vector_Vector3.TransformCoordinatesToRef(e,r,e);let i=Math.atan2(e.x,e.z),o=this._getAngleBetween(i,n),h=this._getAngleBetween(i,this._midYawConstraint);if(o>h){null==s&&(s=Math.sqrt(a.x*a.x+a.z*a.z));let e=this._getAngleBetween(i,this._maxYaw),t=this._getAngleBetween(i,this._minYaw);l=t<e?i+.75*Math.PI:i-.75*Math.PI,a.z=Math.cos(l)*s,a.x=Math.sin(l)*s}}n!=l&&(math_vector_Vector3.TransformCoordinatesToRef(a,e,a),a.addInPlace(t),i=a)}}let c=BoneLookController._TmpVecs[5],u=BoneLookController._TmpVecs[6],d=BoneLookController._TmpVecs[7],_=BoneLookController._TmpQuat;i.subtractToRef(t,c),c.normalize(),math_vector_Vector3.CrossToRef(o,c,u),u.normalize(),math_vector_Vector3.CrossToRef(c,u,d),d.normalize(),math_vector_Matrix.FromXYZAxesToRef(u,d,c,r),(0!==u.x||0!==u.y||0!==u.z)&&(0!==d.x||0!==d.y||0!==d.z)&&(0!==c.x||0!==c.y||0!==c.z)&&((this.adjustYaw||this.adjustPitch||this.adjustRoll)&&(math_vector_Matrix.RotationYawPitchRollToRef(this.adjustYaw,this.adjustPitch,this.adjustRoll,s),s.multiplyToRef(r,r)),this.slerpAmount<1?(this._slerping||this.bone.getRotationQuaternionToRef(en.WORLD,this.mesh,this._boneQuat),this._transformYawPitch&&this._transformYawPitch.multiplyToRef(r,r),math_vector_Quaternion.FromRotationMatrixToRef(r,_),math_vector_Quaternion.SlerpToRef(this._boneQuat,_,this.slerpAmount,this._boneQuat),this.bone.setRotationQuaternion(this._boneQuat,en.WORLD,this.mesh),this._slerping=!0):(this._transformYawPitch&&this._transformYawPitch.multiplyToRef(r,r),this.bone.setRotationMatrix(r,en.WORLD,this.mesh),this._slerping=!1),this._updateLinkedTransformRotation())}_getAngleDiff(e,t){let i=t-e;return(i%=2*Math.PI)>Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI;let i=0;return(i=e<(t=t<0?t+2*Math.PI:t)?t-e:e-t)>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,t<(i=i<0?i+2*Math.PI:i)){if(e>t&&e<i)return!0}else if(e>i&&e<t)return!0;return!1}_updateLinkedTransformRotation(){let e=this.bone;e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new math_vector_Quaternion),e.getRotationQuaternionToRef(en.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}};BoneLookController._TmpVecs=arrayTools_ArrayTools.BuildArray(10,math_vector_Vector3.Zero),BoneLookController._TmpQuat=math_vector_Quaternion.Identity(),BoneLookController._TmpMats=arrayTools_ArrayTools.BuildArray(5,math_vector_Matrix.Identity);let skeleton_Skeleton=class skeleton_Skeleton{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=[],this._identity=math_vector_Matrix.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new observable_Observable,this.bones=[],this._scene=i||engineStore_EngineStore.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;let r=this._scene.getEngine().getCaps();this._canUseTextureForBones=r.textureFloat&&r.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){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(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return -1}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=new AnimationRange(e,t,i);for(let r=0,s=this.bones.length;r<s;r++)this.bones[r].animations[0]&&this.bones[r].animations[0].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,r=this.bones.length;i<r;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}getAnimationRanges(){let e;let t=[];for(e in this._ranges)t.push(this._ranges[e]);return t}copyAnimationRange(e,t,i=!1){let r,s;if(this._ranges[t]||!e.getAnimationRange(t))return!1;let a=!0,n=this._getHighestAnimationFrame()+1,o={},l=e.bones;for(s=0,r=l.length;s<r;s++)o[l[s].name]=l[s];this.bones.length!==l.length&&(logger_Logger.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${l.length}`),a=!1);let h=i&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(s=0,r=this.bones.length;s<r;s++){let e=this.bones[s].name,r=o[e];r?a=a&&this.bones[s].copyAnimationRange(r,t,n,i,h):(logger_Logger.Warn("copyAnimationRange: not same rig, missing source bone "+e),a=!1)}let c=e.getAnimationRange(t);return c&&(this._ranges[t]=new AnimationRange(t,c.from+n,c.to+n)),a}returnToRest(){for(let e of this.bones)-1!==e._index&&e.returnToRest()}_getHighestAnimationFrame(){let e=0;for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){let i=this.bones[t].animations[0].getHighestFrame();e<i&&(e=i)}return e}beginAnimation(e,t,i,r){let s=this.getAnimationRange(e);return s?this._scene.beginAnimation(this,s.from,s.to,t,i,r):null}static MakeAnimationAdditive(e,t=0,i){let r=e.getAnimationRange(i);if(!r)return null;let s=e._scene.getAllAnimatablesByTarget(e),a=null;for(let e=0;e<s.length;e++){let t=s[e];if(t.fromFrame===(null==r?void 0:r.from)&&t.toFrame===(null==r?void 0:r.to)){a=t;break}}let n=e.getAnimatables();for(let e=0;e<n.length;e++){let r=n[e],s=r.animations;if(s)for(let e=0;e<s.length;e++)animation_Animation.MakeAnimationAdditive(s[e],t,i)}return a&&(a.isAdditive=!0),e}_markAsDirty(){this._isDirty=!0,this._absoluteTransformIsDirty=!0}_registerMeshWithPoseMatrix(e){this._meshesWithPoseMatrix.push(e)}_unregisterMeshWithPoseMatrix(e){let t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i<this.bones.length;i++){let r=this.bones[i];r._childUpdateId++;let s=r.getParent();if(s?r.getLocalMatrix().multiplyToRef(s.getFinalMatrix(),r.getFinalMatrix()):t?r.getLocalMatrix().multiplyToRef(t,r.getFinalMatrix()):r.getFinalMatrix().copyFrom(r.getLocalMatrix()),-1!==r._index){let t=null===r._index?i:r._index;r.getAbsoluteInverseBindMatrix().multiplyToArray(r.getFinalMatrix(),e,16*t)}}this._identity.copyToArray(e,16*this.bones.length)}prepare(e=!1){if(!e){let e=this.getScene().getRenderId();if(this._currentRenderId===e)return;this._currentRenderId=e}if(this._numBonesWithLinkedTransformNode>0){for(let e of this.bones)if(e._linkedTransformNode){let 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(let e of this._meshesWithPoseMatrix){let t=e.getPoseMatrix(),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){for(let i of(this._synchronizedWithMesh=e,this.bones))if(!i.getParent()){let e=i.getBindMatrix();e.multiplyToRef(t,math_vector_TmpVectors.Matrix[1]),i._updateAbsoluteBindMatrices(math_vector_TmpVectors.Matrix[1])}if(this.isUsingTextureForMatrices){let t=(this.bones.length+1)*4;e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=rawTexture_RawTexture.CreateRGBATexture(e._bonesTransformMatrices,(this.bones.length+1)*4,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=rawTexture_RawTexture.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables}clone(e,t){let i=new skeleton_Skeleton(e,t||e,this._scene);i.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let e=0;e<this.bones.length;e++){let t=this.bones[e],r=null,s=t.getParent();if(s){let e=this.bones.indexOf(s);r=i.bones[e]}let a=new Bone(t.name,i,r,t.getBindMatrix().clone(),t.getRestMatrix().clone());a._index=t._index,t._linkedTransformNode&&a.linkTransformNode(t._linkedTransformNode),DeepCopier.DeepCopy(t.animations,a.animations)}if(this._ranges)for(let e in i._ranges={},this._ranges){let t=this._ranges[e];t&&(i._ranges[e]=t.clone())}return this._isDirty=!0,i.prepare(!0),i}enableBlending(e=.01){this.bones.forEach(t=>{t.animations.forEach(t=>{t.enableBlending=!0,t.blendingSpeed=e})})}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){let 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;let 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;i<this.bones.length;i++){let r=this.bones[i],s=r.getParent(),a={parentBoneIndex:s?this.bones.indexOf(s):-1,index:r.getIndex(),name:r.name,id:r.id,matrix:r.getBindMatrix().toArray(),rest:r.getRestMatrix().toArray(),linkedTransformNodeId:null===(e=r.getTransformNode())||void 0===e?void 0:e.id};for(let e in t.bones.push(a),r.length&&(a.length=r.length),r.metadata&&(a.metadata=r.metadata),r.animations&&r.animations.length>0&&(a.animation=r.animations[0].serialize()),t.ranges=[],this._ranges){let i=this._ranges[e];if(!i)continue;let r={};r.name=e,r.from=i.from,r.to=i.to,t.ranges.push(r)}}return t}static Parse(e,t){let i;let r=new skeleton_Skeleton(e.name,e.id,t);for(e.dimensionsAtRest&&(r.dimensionsAtRest=math_vector_Vector3.FromArray(e.dimensionsAtRest)),r.needInitialSkinMatrix=e.needInitialSkinMatrix,i=0;i<e.bones.length;i++){let t=e.bones[i],s=e.bones[i].index,a=null;t.parentBoneIndex>-1&&(a=r.bones[t.parentBoneIndex]);let n=t.rest?math_vector_Matrix.FromArray(t.rest):null,o=new Bone(t.name,r,a,math_vector_Matrix.FromArray(t.matrix),n,null,s);void 0!==t.id&&null!==t.id&&(o.id=t.id),t.length&&(o.length=t.length),t.metadata&&(o.metadata=t.metadata),t.animation&&o.animations.push(animation_Animation.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(r._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(i=0;i<e.ranges.length;i++){let t=e.ranges[i];r.createAnimationRange(t.name,t.from,t.to)}return r}computeAbsoluteMatrices(e=!1){(this._absoluteTransformIsDirty||e)&&(this.bones[0].computeAbsoluteMatrices(),this._absoluteTransformIsDirty=!1)}computeAbsoluteTransforms(e=!1){this.computeAbsoluteMatrices(e)}getPoseMatrix(){let e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){let e=[],t=Array(this.bones.length);for(let i=0;i<this.bones.length;i++)this._sortBones(i,e,t);this.bones=e}_sortBones(e,t,i){if(i[e])return;i[e]=!0;let r=this.bones[e];if(!r)return;void 0===r._index&&(r._index=e);let s=r.getParent();s&&this._sortBones(this.bones.indexOf(s),t,i),t.push(r)}setCurrentPoseAsRest(){this.bones.forEach(e=>{e.setCurrentPoseAsRest()})}};let StorageBuffer=class StorageBuffer{constructor(e,t,i=3,r){this._engine=e,this._label=r,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t,this._label)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i){return this._engine.readFromStorageBuffer(this._buffer,e,t,i)}dispose(){let 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}};let j=(()=>{let e=new Uint8Array(4),t=new Uint32Array(e.buffer);return!!((t[0]=1)&e[0])})();Object.defineProperty(buffer_VertexBuffer.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(buffer_VertexBuffer.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(buffer_VertexBuffer.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),buffer_VertexBuffer.prototype._rebuild=function(){var e,t;null===(e=this._buffer)||void 0===e||e._rebuild(),null===(t=this._alignedBuffer)||void 0===t||t._rebuild()},buffer_VertexBuffer.prototype.dispose=function(){var e;this._ownsBuffer&&this._buffer.dispose(),null===(e=this._alignedBuffer)||void 0===e||e.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},buffer_VertexBuffer.prototype._alignBuffer=function(){var e,t;let i,r;let s=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideMultiple4Bytes||this.byteStride%4==0||!s)return;let a=buffer_VertexBuffer.GetTypeByteLength(this.type),n=this.byteStride+3&-4,o=n/a,l=this.totalVertices,h=l*n,c=h/a;if(Array.isArray(s)){let e=new Float32Array(s);i=new DataView(e.buffer,e.byteOffset,e.byteLength)}else i=s instanceof ArrayBuffer?new DataView(s,0,s.byteLength):new DataView(s.buffer,s.byteOffset,s.byteLength);r=this.type===buffer_VertexBuffer.BYTE?new Int8Array(c):this.type===buffer_VertexBuffer.UNSIGNED_BYTE?new Uint8Array(c):this.type===buffer_VertexBuffer.SHORT?new Int16Array(c):this.type===buffer_VertexBuffer.UNSIGNED_SHORT?new Uint16Array(c):this.type===buffer_VertexBuffer.INT?new Int32Array(c):this.type===buffer_VertexBuffer.UNSIGNED_INT?new Uint32Array(c):new Float32Array(c);let u=this.getSize(),d=this.byteOffset;for(let e=0;e<l;++e){for(let t=0;t<u;++t)switch(this.type){case buffer_VertexBuffer.BYTE:r[e*o+t]=i.getInt8(d+t);break;case buffer_VertexBuffer.UNSIGNED_BYTE:r[e*o+t]=i.getUint8(d+t);break;case buffer_VertexBuffer.SHORT:r[e*o+t]=i.getInt16(d+2*t,j);break;case buffer_VertexBuffer.UNSIGNED_SHORT:r[e*o+t]=i.getUint16(d+2*t,j);break;case buffer_VertexBuffer.INT:r[e*o+t]=i.getInt32(d+4*t,j);break;case buffer_VertexBuffer.UNSIGNED_INT:r[e*o+t]=i.getUint32(d+4*t,j);break;case buffer_VertexBuffer.FLOAT:r[e*o+t]=i.getFloat32(d+4*t,j)}d+=this.byteStride}null===(e=this._alignedBuffer)||void 0===e||e.dispose(),this._alignedBuffer=new Buffer(this.engine,r,!1,n,!1,this.getIsInstanced(),!0,this.instanceDivisor,(null!==(t=this._label)&&void 0!==t?t:"VertexBuffer")+"_aligned")};let BaseCameraMouseWheelInput=class BaseCameraMouseWheelInput{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new observable_Observable,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==pointerEvents_PointerEventTypes.POINTERWHEEL)return;let i=t.event,r=i.deltaMode===EventConstants.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,pointerEvents_PointerEventTypes.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"}};__decorate([serialize()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionX",void 0),__decorate([serialize()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionY",void 0),__decorate([serialize()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionZ",void 0);let BaseCameraPointersInput=class BaseCameraPointersInput{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement(),r=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=a=>{var n,o;let l=a.event,h="touch"===l.pointerType;if(a.type!==pointerEvents_PointerEventTypes.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;let 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){let e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else if(a.type!==pointerEvents_PointerEventTypes.POINTERDOWN&&h&&(null===(n=this._pointA)||void 0===n?void 0:n.pointerId)!==l.pointerId&&(null===(o=this._pointB)||void 0===o?void 0:o.pointerId)!==l.pointerId)return;else if(a.type===pointerEvents_PointerEventTypes.POINTERDOWN&&(-1===this._currentActiveButton||h)){try{null==c||c.setPointerCapture(l.pointerId)}catch(e){}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())}else if(a.type===pointerEvents_PointerEventTypes.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(a.type===pointerEvents_PointerEventTypes.POINTERUP&&(this._currentActiveButton===l.button||h)){try{null==c||c.releasePointerCapture(l.pointerId)}catch(e){}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!==r||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(a.type===pointerEvents_PointerEventTypes.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&null===this._pointB){let 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){let e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;let t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,n=t*t+i*i,o={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:a.type};this.onMultiTouch(this._pointA,this._pointB,r,n,s,o),s=o,r=n}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,pointerEvents_PointerEventTypes.POINTERDOWN|pointerEvents_PointerEventTypes.POINTERUP|pointerEvents_PointerEventTypes.POINTERMOVE|pointerEvents_PointerEventTypes.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);let a=this.camera.getScene().getEngine().getHostWindow();a&&tools_Tools.RegisterTopRootEvents(a,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){let e=this.camera.getScene().getEngine().getHostWindow();e&&tools_Tools.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){let e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,r,s,a){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}};__decorate([serialize()],BaseCameraPointersInput.prototype,"buttons",void 0);var K,q,$,Q,Z,J,ee,et,ei,er,es,ea,en,eo,el,eh,ec,eu,ed,e_,ep,ef,em,eg,ev,ex,eb,eT,eS,eC,eE,ey,eR,eP,eA,eM,eI,eD,eO,eB,eN,eF,ew,eL,eV,eU,ek,eG,ez,eW,eH,eX,eY,ej,eK,eq,e$,eQ,eZ,eJ,e0,e1,e2,e3,e4,e5,e6,e8,e7,e9,te,tt,ti,tr,ts,ta,tn,to,tl,th,tc,tu,td,t_,tp,tf,tm,tg,tv,tx,tb,tT,tS,tC,tE,ty,tR,tP,tA,tM,tI,tD,tO,tB,tN,tF,tw,tL,tV,tU,tk,tG,tz,tW,tH,tX,tY,tj,tK,tq,t$,tQ,tZ,tJ,t0,t1,t2,t3,t4,t5,t6,t8,t7,t9,ie,it,ii,ir,is,ia,io,il={};let CameraInputsManager=class CameraInputsManager{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){let t=e.getSimpleName();if(this.attached[t]){logger_Logger.Warn("camera input of type "+t+" already exists on camera");return}this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault)}remove(e){for(let t in this.attached){let i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(let t in this.attached){let i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){let t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement)for(let t in e=!camera_Camera.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e,this.attached)this.attached[t].attachControl(e)}detachElement(e=!1){for(let t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){for(let e in this.checkInputs=()=>{},this.attached){let 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){let t={};for(let e in this.attached){let i=this.attached[e],r=decorators_SerializationHelper.Serialize(i);t[i.getClassName()]=r}e.inputsmgr=t}parse(e){let t=e.inputsmgr;if(t)for(let e in this.clear(),t){let i=il[e];if(i){let r=t[e],s=decorators_SerializationHelper.Parse(()=>new i,r,null);this.add(s)}}else for(let t in this.attached){let i=il[this.attached[t].getClassName()];if(i){let r=decorators_SerializationHelper.Parse(()=>new i,e,null);this.remove(this.attached[t]),this.add(r)}}}};let Gamepad=class Gamepad{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,s=1,a=2,n=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=Gamepad.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=s,this._rightStickAxisX=a,this._rightStickAxisY=n,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(){}};Gamepad.GAMEPAD=0,Gamepad.GENERIC=1,Gamepad.XBOX=2,Gamepad.POSE_ENABLED=3,Gamepad.DUALSHOCK=4;let GenericPad=class GenericPad extends Gamepad{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new observable_Observable,this.onButtonUpObservable=new observable_Observable,this.type=Gamepad.GENERIC,this._buttons=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<this._buttons.length;e++)this._buttons[e]=this._setButtonValue(this.browserGamepad.buttons[e].value,this._buttons[e],e)}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear()}};let ArcRotateCameraGamepadInput=class ArcRotateCameraGamepadInput{constructor(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40,this._yAxisScale=1}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){let e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{e.type===Gamepad.POSE_ENABLED||this.gamepad&&e.type!==Gamepad.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Gamepad.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){let e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){let i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){let i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}let i=this.gamepad.leftStick;if(i&&0!=i.y){let e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}};__decorate([serialize()],ArcRotateCameraGamepadInput.prototype,"gamepadRotationSensibility",void 0),__decorate([serialize()],ArcRotateCameraGamepadInput.prototype,"gamepadMoveSensibility",void 0),il.ArcRotateCameraGamepadInput=ArcRotateCameraGamepadInput;let ArcRotateCameraKeyboardMoveInput=class ArcRotateCameraKeyboardMoveInput{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=[]}attachControl(e){e=tools_Tools.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=>{let i=t.event;if(!i.metaKey){if(t.type===KeyboardEventTypes.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t];-1!==this.keysLeft.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:-1!==this.keysUp.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:-1!==this.keysRight.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:-1!==this.keysDown.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:-1!==this.keysReset.indexOf(i)&&e.useInputToRestoreState&&e.restoreState()}}}getClassName(){return"ArcRotateCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}};__decorate([serialize()],ArcRotateCameraKeyboardMoveInput.prototype,"keysUp",void 0),__decorate([serialize()],ArcRotateCameraKeyboardMoveInput.prototype,"keysDown",void 0),__decorate([serialize()],ArcRotateCameraKeyboardMoveInput.prototype,"keysLeft",void 0),__decorate([serialize()],ArcRotateCameraKeyboardMoveInput.prototype,"keysRight",void 0),__decorate([serialize()],ArcRotateCameraKeyboardMoveInput.prototype,"keysReset",void 0),__decorate([serialize()],ArcRotateCameraKeyboardMoveInput.prototype,"panningSensibility",void 0),__decorate([serialize()],ArcRotateCameraKeyboardMoveInput.prototype,"zoomingSensibility",void 0),__decorate([serialize()],ArcRotateCameraKeyboardMoveInput.prototype,"useAltToZoom",void 0),__decorate([serialize()],ArcRotateCameraKeyboardMoveInput.prototype,"angularSpeed",void 0),il.ArcRotateCameraKeyboardMoveInput=ArcRotateCameraKeyboardMoveInput;let ArcRotateCameraMouseWheelInput=class ArcRotateCameraMouseWheelInput{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._viewOffset=new math_vector_Vector3(0,0,0),this._globalOffset=new math_vector_Vector3(0,0,0),this._inertialPanning=math_vector_Vector3.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let i=.01*e*this.wheelDeltaPercentage*t;return e>0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage)}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==pointerEvents_PointerEventTypes.POINTERWHEEL)return;let i=t.event,r=0,s=i.deltaMode===EventConstants.DOM_DELTA_LINE?40:1,a=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(a,this,i);else if(this.wheelDeltaPercentage){if((r=this._computeDeltaFromMouseWheelLegacyEvent(a,this.camera.radius))>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+r;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=math_scalar_Scalar.Clamp(e,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(a,e)}}else r=a/(40*this.wheelPrecision);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,pointerEvents_PointerEventTypes.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;let e=this.camera,t=0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset;t&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){let e=this.camera,t=e.target.subtract(e.position);this._hitPlane=math_plane_Plane.FromPositionAndNormal(e.target,t)}_getPosition(){var e;let t=this.camera,i=t.getScene(),r=i.createPickingRay(i.pointerX,i.pointerY,math_vector_Matrix.Identity(),t,!1);(0!==t.targetScreenOffset.x||0!==t.targetScreenOffset.y)&&(this._viewOffset.set(t.targetScreenOffset.x,t.targetScreenOffset.y,0),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),this._globalOffset=math_vector_Vector3.TransformNormal(this._viewOffset,t._cameraTransformMatrix),r.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=null!==(e=r.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),r.origin.addInPlace(r.direction.scaleInPlace(s))}_zoomToMouse(e){var t,i;let r=this.camera,s=1-r.inertia;if(r.lowerRadiusLimit){let i=null!==(t=r.lowerRadiusLimit)&&void 0!==t?t:0;r.radius-(r.inertialRadiusOffset+e)/s<i&&(e=(r.radius-i)*s-r.inertialRadiusOffset)}if(r.upperRadiusLimit){let t=null!==(i=r.upperRadiusLimit)&&void 0!==i?i:0;r.radius-(r.inertialRadiusOffset+e)/s>t&&(e=(r.radius-t)*s-r.inertialRadiusOffset)}let a=e/s,n=a/r.radius,o=this._getPosition(),l=math_vector_TmpVectors.Vector3[6];o.subtractToRef(r.target,l),l.scaleInPlace(n),l.scaleInPlace(s),this._inertialPanning.addInPlace(l),r.inertialRadiusOffset+=e}_zeroIfClose(e){.001>Math.abs(e.x)&&(e.x=0),.001>Math.abs(e.y)&&(e.y=0),.001>Math.abs(e.z)&&(e.z=0)}};__decorate([serialize()],ArcRotateCameraMouseWheelInput.prototype,"wheelPrecision",void 0),__decorate([serialize()],ArcRotateCameraMouseWheelInput.prototype,"zoomToMouseLocation",void 0),__decorate([serialize()],ArcRotateCameraMouseWheelInput.prototype,"wheelDeltaPercentage",void 0),il.ArcRotateCameraMouseWheelInput=ArcRotateCameraMouseWheelInput;let ArcRotateCameraPointersInput=class ArcRotateCameraPointersInput extends BaseCameraPointersInput{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.pinchZoom=!0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this.pinchInwards=!0,this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(0!==this.panningSensibility&&e&&t){let i=t.x-e.x,r=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=r/this.panningSensibility}}_computePinchZoom(e,t){let i=this.camera.radius||ArcRotateCameraPointersInput.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,r,s,a){(0!==i||null!==s)&&(0!==r||null!==a)&&(this.multiTouchPanAndZoom?(this._computePinchZoom(i,r),this._computeMultiTouchPanning(s,a)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(r)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,a)):this.multiTouchPanning?this._computeMultiTouchPanning(s,a):this.pinchZoom&&this._computePinchZoom(i,r))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}};ArcRotateCameraPointersInput.MinimumRadiusForPinch=.001,__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"buttons",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"angularSensibilityX",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"angularSensibilityY",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"pinchPrecision",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"pinchDeltaPercentage",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"useNaturalPinchZoom",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"pinchZoom",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"panningSensibility",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"multiTouchPanning",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"multiTouchPanAndZoom",void 0),il.ArcRotateCameraPointersInput=ArcRotateCameraPointersInput;let ArcRotateCameraInputsManager=class ArcRotateCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addMouseWheel(){return this.add(new ArcRotateCameraMouseWheelInput),this}addPointers(){return this.add(new ArcRotateCameraPointersInput),this}addKeyboard(){return this.add(new ArcRotateCameraKeyboardMoveInput),this}};ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation=function(){return this.add(new ArcRotateCameraVRDeviceOrientationInput),this};let ArcRotateCameraVRDeviceOrientationInput=class ArcRotateCameraVRDeviceOrientationInput{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);let 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):tools_Tools.Warn("Permission not granted.")}).catch(e=>{tools_Tools.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"}};il.ArcRotateCameraVRDeviceOrientationInput=ArcRotateCameraVRDeviceOrientationInput;let FlyCameraKeyboardInput=class FlyCameraKeyboardInput{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=[]}attachControl(e){e=tools_Tools.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=>{let i=t.event;if(t.type===KeyboardEventTypes.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=e._computeLocalCameraSpeed();-1!==this.keysForward.indexOf(i)?e._localDirection.copyFromFloats(0,0,r):-1!==this.keysBackward.indexOf(i)?e._localDirection.copyFromFloats(0,0,-r):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,r,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,-r,0):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(r,0,0):-1!==this.keysLeft.indexOf(i)&&e._localDirection.copyFromFloats(-r,0,0),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),math_vector_Vector3.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}};__decorate([serialize()],FlyCameraKeyboardInput.prototype,"keysForward",void 0),__decorate([serialize()],FlyCameraKeyboardInput.prototype,"keysBackward",void 0),__decorate([serialize()],FlyCameraKeyboardInput.prototype,"keysUp",void 0),__decorate([serialize()],FlyCameraKeyboardInput.prototype,"keysDown",void 0),__decorate([serialize()],FlyCameraKeyboardInput.prototype,"keysRight",void 0),__decorate([serialize()],FlyCameraKeyboardInput.prototype,"keysLeft",void 0),il.FlyCameraKeyboardInput=FlyCameraKeyboardInput;let FlyCameraMouseInput=class FlyCameraMouseInput{constructor(){this.buttons=[0,1,2],this.buttonsYaw=[-1,0,1],this.buttonsPitch=[-1,0,1],this.buttonsRoll=[2],this.activeButton=-1,this.angularSensibility=1e3,this._previousPosition=null}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this._noPreventDefault=e,this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(e=>{this._pointerInput(e)},pointerEvents_PointerEventTypes.POINTERDOWN|pointerEvents_PointerEventTypes.POINTERUP|pointerEvents_PointerEventTypes.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){let t=e.event,i=this.camera,r=i.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType||e.type!==pointerEvents_PointerEventTypes.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;let s=t.target;if(e.type===pointerEvents_PointerEventTypes.POINTERDOWN){try{null==s||s.setPointerCapture(t.pointerId)}catch(e){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),r.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===pointerEvents_PointerEventTypes.POINTERUP){try{null==s||s.releasePointerCapture(t.pointerId)}catch(e){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===pointerEvents_PointerEventTypes.POINTERMOVE){if(!this._previousPosition){r.isPointerLock&&this._onMouseMove(e.event);return}let i=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(i,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){let t=this.camera,i=t.getEngine();if(!i.isPointerLock)return;let r=e.movementX,s=e.movementY;this._rotateCamera(r,s),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){let i;let r=this.camera,s=r._calculateHandednessMultiplier();e*=s;let a=e/this.angularSensibility,n=t/this.angularSensibility,o=math_vector_Quaternion.RotationYawPitchRoll(r.rotation.y,r.rotation.x,r.rotation.z);if(this.buttonsPitch.some(e=>e===this.activeButton)&&(i=math_vector_Quaternion.RotationAxis(math_axis_Axis.X,n),o.multiplyInPlace(i)),this.buttonsYaw.some(e=>e===this.activeButton)){i=math_vector_Quaternion.RotationAxis(math_axis_Axis.Y,a),o.multiplyInPlace(i);let e=r.bankedTurnLimit+r._trackRoll;if(r.bankedTurn&&-e<r.rotation.z&&r.rotation.z<e){let e=-(r.bankedTurnMultiplier*a);i=math_vector_Quaternion.RotationAxis(math_axis_Axis.Z,e),o.multiplyInPlace(i)}}this.buttonsRoll.some(e=>e===this.activeButton)&&(i=math_vector_Quaternion.RotationAxis(math_axis_Axis.Z,-a),r._trackRoll-=a,o.multiplyInPlace(i)),o.toEulerAnglesToRef(r.rotation)}};__decorate([serialize()],FlyCameraMouseInput.prototype,"buttons",void 0),__decorate([serialize()],FlyCameraMouseInput.prototype,"angularSensibility",void 0),il.FlyCameraMouseInput=FlyCameraMouseInput;let FollowCameraKeyboardMoveInput=class FollowCameraKeyboardMoveInput{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=[]}attachControl(e){e=tools_Tools.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=>{let i=t.event;if(!i.metaKey){if(t.type===KeyboardEventTypes.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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}};__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetIncr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetDecr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierAlt",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierCtrl",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierShift",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetIncr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetDecr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierAlt",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierCtrl",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierShift",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusIncr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusDecr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierAlt",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierCtrl",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierShift",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"heightSensibility",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"rotationSensibility",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"radiusSensibility",void 0),il.FollowCameraKeyboardMoveInput=FollowCameraKeyboardMoveInput;let FollowCameraMouseWheelInput=class FollowCameraMouseWheelInput{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==pointerEvents_PointerEventTypes.POINTERWHEEL)return;let i=t.event,r=0,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?r=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=s*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,pointerEvents_PointerEventTypes.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}};__decorate([serialize()],FollowCameraMouseWheelInput.prototype,"axisControlRadius",void 0),__decorate([serialize()],FollowCameraMouseWheelInput.prototype,"axisControlHeight",void 0),__decorate([serialize()],FollowCameraMouseWheelInput.prototype,"axisControlRotation",void 0),__decorate([serialize()],FollowCameraMouseWheelInput.prototype,"wheelPrecision",void 0),__decorate([serialize()],FollowCameraMouseWheelInput.prototype,"wheelDeltaPercentage",void 0),il.FollowCameraMouseWheelInput=FollowCameraMouseWheelInput;let FollowCameraPointersInput=class FollowCameraPointersInput extends BaseCameraPointersInput{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,s,a){if(0===i&&null===s||0===r&&null===a)return;let n=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(n*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=n*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=n*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=n*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=n),this.axisPinchControlHeight&&(this.camera.heightOffset+=n),this.axisPinchControlRadius&&(this.camera.radius-=n))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;let 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)}};__decorate([serialize()],FollowCameraPointersInput.prototype,"angularSensibilityX",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"angularSensibilityY",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"pinchPrecision",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"pinchDeltaPercentage",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisXControlRadius",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisXControlHeight",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisXControlRotation",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisYControlRadius",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisYControlHeight",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisYControlRotation",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisPinchControlRadius",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisPinchControlHeight",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisPinchControlRotation",void 0),il.FollowCameraPointersInput=FollowCameraPointersInput;let FreeCameraKeyboardMoveInput=class FreeCameraKeyboardMoveInput{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=[]}attachControl(e){e=tools_Tools.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=>{let i=t.event;if(!i.metaKey){if(t.type===KeyboardEventTypes.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=e._computeLocalCameraSpeed();-1!==this.keysLeft.indexOf(i)?e._localDirection.copyFromFloats(-r,0,0):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,0,r):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(r,0,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,0,-r):-1!==this.keysUpward.indexOf(i)?e._localDirection.copyFromFloats(0,r,0):-1!==this.keysDownward.indexOf(i)?e._localDirection.copyFromFloats(0,-r,0):-1!==this.keysRotateLeft.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):-1!==this.keysRotateRight.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):-1!==this.keysRotateUp.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):-1!==this.keysRotateDown.indexOf(i)&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),math_vector_Vector3.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}getClassName(){return"FreeCameraKeyboardMoveInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}_getLocalRotation(){let e=this.camera._calculateHandednessMultiplier(),t=this.rotationSpeed*this._engine.getDeltaTime()/1e3*e;return t}};__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"keysUp",void 0),__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"keysUpward",void 0),__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"keysDown",void 0),__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"keysDownward",void 0),__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"keysLeft",void 0),__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"keysRight",void 0),__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"rotationSpeed",void 0),__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"keysRotateLeft",void 0),__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"keysRotateRight",void 0),__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"keysRotateUp",void 0),__decorate([serialize()],FreeCameraKeyboardMoveInput.prototype,"keysRotateDown",void 0),il.FreeCameraKeyboardMoveInput=FreeCameraKeyboardMoveInput;let FreeCameraMouseInput=class FreeCameraMouseInput{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new observable_Observable,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=r=>{let s=r.event,a="touch"===s.pointerType;if(!this.touchEnabled&&a||r.type!==pointerEvents_PointerEventTypes.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;let n=s.target;if(r.type===pointerEvents_PointerEventTypes.POINTERDOWN){if(a&&-1!==this._activePointerId||!a&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==n||n.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},!e&&(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===pointerEvents_PointerEventTypes.POINTERUP){if(a&&this._activePointerId!==s.pointerId||!a&&this._currentActiveButton!==s.button)return;try{null==n||n.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===pointerEvents_PointerEventTypes.POINTERMOVE&&(this._activePointerId===s.pointerId||!a)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){let t=this.camera._calculateHandednessMultiplier(),i=(s.clientX-this._previousPosition.x)*t,r=s.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=r/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:r}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;let r=this.camera._calculateHandednessMultiplier(),s=i.movementX*r;this.camera.cameraRotation.y+=s/this.angularSensibility;let a=i.movementY;this.camera.cameraRotation.x+=a/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,pointerEvents_PointerEventTypes.POINTERDOWN|pointerEvents_PointerEventTypes.POINTERUP|pointerEvents_PointerEventTypes.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}};__decorate([serialize()],FreeCameraMouseInput.prototype,"buttons",void 0),__decorate([serialize()],FreeCameraMouseInput.prototype,"angularSensibility",void 0),il.FreeCameraMouseInput=FreeCameraMouseInput,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(eP||(eP={}));let FreeCameraMouseWheelInput=class FreeCameraMouseWheelInput extends BaseCameraMouseWheelInput{constructor(){super(...arguments),this._moveRelative=math_vector_Vector3.Zero(),this._rotateRelative=math_vector_Vector3.Zero(),this._moveScene=math_vector_Vector3.Zero(),this._wheelXAction=eP.MoveRelative,this._wheelXActionCoordinate=eo.X,this._wheelYAction=eP.MoveRelative,this._wheelYActionCoordinate=eo.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){(null!==e||this._wheelXAction===eP.MoveRelative)&&(this._wheelXAction=eP.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==eP.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){(null!==e||this._wheelYAction===eP.MoveRelative)&&(this._wheelYAction=eP.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==eP.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){(null!==e||this._wheelZAction===eP.MoveRelative)&&(this._wheelZAction=eP.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==eP.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){(null!==e||this._wheelXAction===eP.RotateRelative)&&(this._wheelXAction=eP.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==eP.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){(null!==e||this._wheelYAction===eP.RotateRelative)&&(this._wheelYAction=eP.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==eP.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){(null!==e||this._wheelZAction===eP.RotateRelative)&&(this._wheelZAction=eP.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==eP.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){(null!==e||this._wheelXAction===eP.MoveScene)&&(this._wheelXAction=eP.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==eP.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){(null!==e||this._wheelYAction===eP.MoveScene)&&(this._wheelYAction=eP.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==eP.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){(null!==e||this._wheelZAction===eP.MoveScene)&&(this._wheelZAction=eP.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==eP.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);let e=math_vector_Matrix.Zero();this.camera.getViewMatrix().invertToRef(e);let t=math_vector_Vector3.Zero();math_vector_Vector3.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||null===t||null===i)return;let r=null;switch(t){case eP.MoveRelative:r=this._moveRelative;break;case eP.RotateRelative:r=this._rotateRelative;break;case eP.MoveScene:r=this._moveScene}switch(i){case eo.X:r.set(e,0,0);break;case eo.Y:r.set(0,e,0);break;case eo.Z:r.set(0,0,e)}}};__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelXMoveRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelYMoveRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelZMoveRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelXRotateRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelYRotateRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelZRotateRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelXMoveScene",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelYMoveScene",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelZMoveScene",null),il.FreeCameraMouseWheelInput=FreeCameraMouseWheelInput;let FreeCameraTouchInput=class FreeCameraTouchInput{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=[],this._isSafari=tools_Tools.IsSafari()}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{let r=i.event,s="mouse"===r.pointerType||this._isSafari&&void 0===r.pointerType;if(this.allowMouse||!s){if(i.type===pointerEvents_PointerEventTypes.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),1!==this._pointerPressed.length)return;t={x:r.clientX,y:r.clientY}}else if(i.type===pointerEvents_PointerEventTypes.POINTERUP){e||r.preventDefault();let i=this._pointerPressed.indexOf(r.pointerId);if(-1===i||(this._pointerPressed.splice(i,1),0!=i))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===pointerEvents_PointerEventTypes.POINTERMOVE){if(e||r.preventDefault(),!t)return;let i=this._pointerPressed.indexOf(r.pointerId);if(0!=i)return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,pointerEvents_PointerEventTypes.POINTERDOWN|pointerEvents_PointerEventTypes.POINTERUP|pointerEvents_PointerEventTypes.POINTERMOVE),this._onLostFocus){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.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||0===this._offsetX&&0===this._offsetY)return;let e=this.camera,t=e._calculateHandednessMultiplier();e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility;let i=this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1;if(i)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{let t=e._computeLocalCameraSpeed(),i=new math_vector_Vector3(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);math_vector_Matrix.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(math_vector_Vector3.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}};__decorate([serialize()],FreeCameraTouchInput.prototype,"touchAngularSensibility",void 0),__decorate([serialize()],FreeCameraTouchInput.prototype,"touchMoveSensibility",void 0),il.FreeCameraTouchInput=FreeCameraTouchInput;let FreeCameraInputsManager=class FreeCameraInputsManager extends CameraInputsManager{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new FreeCameraKeyboardMoveInput),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new FreeCameraMouseInput(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new FreeCameraMouseWheelInput,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new FreeCameraTouchInput),this}clear(){super.clear(),this._mouseInput=null}};FreeCameraInputsManager.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new FreeCameraDeviceOrientationInput,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};let FreeCameraDeviceOrientationInput=class FreeCameraDeviceOrientationInput{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let r=!1,eventHandler=()=>{window.removeEventListener("deviceorientation",eventHandler),r=!0,t()};e&&setTimeout(()=>{r||(window.removeEventListener("deviceorientation",eventHandler),i("WaitForOrientationChangeAsync timed out"))},e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"==e?window.addEventListener("deviceorientation",eventHandler):tools_Tools.Warn("Permission not granted.")}).catch(e=>{tools_Tools.Error(e)}):window.addEventListener("deviceorientation",eventHandler)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new math_vector_Quaternion,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new observable_Observable,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-tools_Tools.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?tools_Tools.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?tools_Tools.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?tools_Tools.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 math_vector_Quaternion(-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 math_vector_Quaternion),this._camera&&this._camera.onDisposeObservable.add(()=>{this._onDeviceOrientationChangedObservable.clear()})}attachControl(){let e=this.camera.getScene().getEngine().getHostWindow();if(e){let eventHandler=()=>{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?eventHandler():tools_Tools.Warn("Permission not granted.")}).catch(e=>{tools_Tools.Error(e)}):eventHandler()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(math_vector_Quaternion.RotationYawPitchRollToRef(tools_Tools.ToRadians(this._alpha),tools_Tools.ToRadians(this._beta),-tools_Tools.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"}};il.FreeCameraDeviceOrientationInput=FreeCameraDeviceOrientationInput;let FreeCameraGamepadInput=class FreeCameraGamepadInput{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=math_vector_Matrix.Identity(),this._deltaTransform=math_vector_Vector3.Zero(),this._vector3=math_vector_Vector3.Zero(),this._vector2=math_vector_Vector2.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){let e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{e.type===Gamepad.POSE_ENABLED||this.gamepad&&e.type!==Gamepad.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Gamepad.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){let 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):math_vector_Matrix.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);let r=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*r,0,-t.y*r),math_vector_Vector3.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"}};__decorate([serialize()],FreeCameraGamepadInput.prototype,"gamepadAngularSensibility",void 0),__decorate([serialize()],FreeCameraGamepadInput.prototype,"gamepadMoveSensibility",void 0),il.FreeCameraGamepadInput=FreeCameraGamepadInput,function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(eA||(eA={}));let VirtualJoystick=class VirtualJoystick{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;let i=Object.assign(Object.assign({},VirtualJoystick._GetDefaultOptions()),t);if(e?this._leftJoystick=!0:this._leftJoystick=!1,VirtualJoystick._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=eA.X,this._axisTargetedByUpAndDown=eA.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new StringDictionary,this.deltaPosition=math_vector_Vector3.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{VirtualJoystick._VJCanvasWidth=window.innerWidth,VirtualJoystick._VJCanvasHeight=window.innerHeight,VirtualJoystick.Canvas&&(VirtualJoystick.Canvas.width=VirtualJoystick._VJCanvasWidth,VirtualJoystick.Canvas.height=VirtualJoystick._VJCanvasHeight),VirtualJoystick._HalfWidth=VirtualJoystick._VJCanvasWidth/2},!VirtualJoystick.Canvas){window.addEventListener("resize",this._onResize,!1),VirtualJoystick.Canvas=document.createElement("canvas"),VirtualJoystick._VJCanvasWidth=window.innerWidth,VirtualJoystick._VJCanvasHeight=window.innerHeight,VirtualJoystick.Canvas.width=window.innerWidth,VirtualJoystick.Canvas.height=window.innerHeight,VirtualJoystick.Canvas.style.width="100%",VirtualJoystick.Canvas.style.height="100%",VirtualJoystick.Canvas.style.position="absolute",VirtualJoystick.Canvas.style.backgroundColor="transparent",VirtualJoystick.Canvas.style.top="0px",VirtualJoystick.Canvas.style.left="0px",VirtualJoystick.Canvas.style.zIndex="5",VirtualJoystick.Canvas.style.touchAction="none",VirtualJoystick.Canvas.setAttribute("touch-action","none");let e=VirtualJoystick.Canvas.getContext("2d");if(!e)throw Error("Unable to create canvas for virtual joystick");VirtualJoystick._VJCanvasContext=e,VirtualJoystick._VJCanvasContext.strokeStyle="#ffffff",VirtualJoystick._VJCanvasContext.lineWidth=2,document.body.appendChild(VirtualJoystick.Canvas)}VirtualJoystick._HalfWidth=VirtualJoystick.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&&VirtualJoystick._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new math_vector_Vector2(0,0),this._joystickPreviousPointerPos=new math_vector_Vector2(0,0),this._joystickPointerStartPos=new math_vector_Vector2(0,0),this._deltaJoystickVector=new math_vector_Vector2(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},VirtualJoystick.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("contextmenu",e=>{e.preventDefault()},!1),requestAnimationFrame(()=>{this._drawVirtualJoystick()})}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){e.preventDefault(),(!0===this._leftJoystick?e.clientX<VirtualJoystick._HalfWidth:e.clientX>VirtualJoystick._HalfWidth)&&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)):VirtualJoystick._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){let t=new math_vector_Vector2(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),0<VirtualJoystick._AlwaysVisibleSticks&&(this._leftJoystick?this._joystickPointerPos.x=Math.min(VirtualJoystick._HalfWidth,this._joystickPointerPos.x):this._joystickPointerPos.x=Math.max(VirtualJoystick._HalfWidth,this._joystickPointerPos.x));let t=this.reverseLeftRight?-1:1,i=t*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case eA.X:this.deltaPosition.x=Math.min(1,Math.max(-1,i));break;case eA.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,i));break;case eA.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,i))}let r=this.reverseUpDown?1:-1,s=r*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case eA.X:this.deltaPosition.x=Math.min(1,Math.max(-1,s));break;case eA.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,s));break;case eA.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,s))}}else{let t=this._touches.get(e.pointerId.toString());t&&(t.x=e.clientX,t.y=e.clientY)}}_onPointerUp(e){if(this._joystickPointerId==e.pointerId)this._clearPreviousDraw(),this._joystickPointerId=-1,this.pressed=!1;else{let t=this._touches.get(e.pointerId.toString());t&&VirtualJoystick._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())}setJoystickColor(e){this._joystickColor=e}set containerSize(e){this._joystickContainerSize=e,this._clearContainerSize=~~(2.1*this._joystickContainerSize),this._clearContainerSizeOffset=~~(this._clearContainerSize/2)}get containerSize(){return this._joystickContainerSize}set puckSize(e){this._joystickPuckSize=e,this._clearPuckSize=~~(2.1*this._joystickPuckSize),this._clearPuckSizeOffset=~~(this._clearPuckSize/2)}get puckSize(){return this._joystickPuckSize}clearPosition(){this.alwaysVisible=!1,this._joystickPosition=null}set alwaysVisible(e){this._alwaysVisible!==e&&(e&&this._joystickPosition?(VirtualJoystick._AlwaysVisibleSticks++,this._alwaysVisible=!0):(VirtualJoystick._AlwaysVisibleSticks--,this._alwaysVisible=!1))}get alwaysVisible(){return this._alwaysVisible}setPosition(e,t){this._joystickPointerStartPos&&this._clearPreviousDraw(),this._joystickPosition=new math_vector_Vector2(e,t)}setActionOnTouch(e){this._action=e}setAxisForLeftRight(e){switch(e){case eA.X:case eA.Y:case eA.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=eA.X}}setAxisForUpDown(e){switch(e){case eA.X:case eA.Y:case eA.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=eA.Y}}_clearPreviousDraw(){let e=this._joystickPosition||this._joystickPointerStartPos;VirtualJoystick._VJCanvasContext.clearRect(e.x-this._clearContainerSizeOffset,e.y-this._clearContainerSizeOffset,this._clearContainerSize,this._clearContainerSize),VirtualJoystick._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x-this._clearPuckSizeOffset-1,this._joystickPreviousPointerPos.y-this._clearPuckSizeOffset-1,this._clearPuckSize+2,this._clearPuckSize+2)}setContainerImage(e){let t=new Image;t.src=e,t.onload=()=>this._containerImage=t}setPuckImage(e){let t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){let e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?VirtualJoystick._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.lineWidth=2,VirtualJoystick._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath(),VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.lineWidth=6,VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?VirtualJoystick._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.lineWidth=2,VirtualJoystick._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._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()):(VirtualJoystick._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.fillStyle="white",VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle="red",VirtualJoystick._VJCanvasContext.lineWidth=6,VirtualJoystick._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){VirtualJoystick.Canvas&&(VirtualJoystick.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(VirtualJoystick.Canvas),VirtualJoystick.Canvas=null),this._released=!0}};VirtualJoystick._GlobalJoystickIndex=0,VirtualJoystick._AlwaysVisibleSticks=0,FreeCameraInputsManager.prototype.addVirtualJoystick=function(){return this.add(new FreeCameraVirtualJoystickInput),this};let FreeCameraVirtualJoystickInput=class FreeCameraVirtualJoystickInput{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){let e=this.camera,t=50*e._computeLocalCameraSpeed(),i=math_vector_Matrix.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=math_vector_Vector3.TransformCoordinates(new math_vector_Vector3(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new VirtualJoystick(!0),this._leftjoystick.setAxisForUpDown(eA.Z),this._leftjoystick.setAxisForLeftRight(eA.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new VirtualJoystick(!1),this._rightjoystick.setAxisForUpDown(eA.X),this._rightjoystick.setAxisForLeftRight(eA.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"}};il.FreeCameraVirtualJoystickInput=FreeCameraVirtualJoystickInput;let targetCamera_TargetCamera=class targetCamera_TargetCamera extends camera_Camera{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=math_vector_Vector3.Zero(),this._tmpTargetVector=math_vector_Vector3.Zero(),this.cameraDirection=new math_vector_Vector3(0,0,0),this.cameraRotation=new math_vector_Vector2(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new math_vector_Quaternion,this.rotation=new math_vector_Vector3(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=math_vector_Vector3.Zero(),this._initialFocalDistance=1,this._viewMatrix=math_vector_Matrix.Zero(),this._camMatrix=math_vector_Matrix.Zero(),this._cameraTransformMatrix=math_vector_Matrix.Zero(),this._cameraRotationMatrix=math_vector_Matrix.Zero(),this._referencePoint=new math_vector_Vector3(0,0,1),this._transformedReferencePoint=math_vector_Vector3.Zero(),this._deferredPositionUpdate=new math_vector_Vector3,this._deferredRotationQuaternionUpdate=new math_vector_Quaternion,this._deferredRotationUpdate=new math_vector_Vector3,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=math_vector_Vector3.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();let 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){let e=this.lockedTarget,t=e.computeWorldMatrix();t.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 math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new math_vector_Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();let 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;let 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(){let 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+=.001),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),math_vector_Matrix.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);let 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&&math_vector_Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent){this.parent.getWorldMatrix().invertToRef(math_vector_TmpVectors.Matrix[0]),math_vector_Vector3.TransformNormalToRef(this.cameraDirection,math_vector_TmpVectors.Matrix[0],math_vector_TmpVectors.Vector3[0]),this._deferredPositionUpdate.addInPlace(math_vector_TmpVectors.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){let e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint&&(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion)){let e=this._deferredRotationUpdate.lengthSquared();e&&(math_vector_Quaternion.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}t&&(Math.abs(this.cameraDirection.x)<.001*this.speed&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<.001*this.speed&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<.001*this.speed&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<.001*this.speed&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<.001*this.speed&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):math_vector_Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return math_vector_Vector3.TransformNormalToRef(this._defaultUp,this._cameraRotationMatrix,this.upVector),this}_getViewMatrix(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),math_vector_Vector3.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?math_axis_Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(math_vector_Quaternion.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),math_axis_Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.ignoreParentScaling){if(this.parent){let r=this.parent.getWorldMatrix();math_vector_Vector3.TransformCoordinatesToRef(e,r,this._globalPosition),math_vector_Vector3.TransformCoordinatesToRef(t,r,this._tmpTargetVector),math_vector_Vector3.TransformNormalToRef(i,r,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(i);this.getScene().useRightHandedSystem?math_vector_Matrix.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):math_vector_Matrix.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix);return}if(this.getScene().useRightHandedSystem?math_vector_Matrix.LookAtRHToRef(e,t,i,this._viewMatrix):math_vector_Matrix.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){let e=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(e,this._viewMatrix),this._viewMatrix.getTranslationToRef(this._globalPosition),this._viewMatrix.invert(),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e)}createRigCamera(e,t){if(this.cameraRigMode!==camera_Camera.RIG_MODE_NONE){let t=new targetCamera_TargetCamera(e,this.position.clone(),this.getScene());return t.isRigCamera=!0,t.rigParent=this,this.cameraRigMode===camera_Camera.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new math_vector_Quaternion),t._cameraRigParams={},t.rotationQuaternion=new math_vector_Quaternion),t.mode=this.mode,t.orthoLeft=this.orthoLeft,t.orthoRight=this.orthoRight,t.orthoTop=this.orthoTop,t.orthoBottom=this.orthoBottom,t}return null}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:{let i=this.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,r=this.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*r,t);break}case camera_Camera.RIG_MODE_VR:e.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),t.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),t.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),t.position.copyFrom(this.position)}super._updateRigCameras()}_getRigCamPositionAndTarget(e,t){let i=this.getTarget();i.subtractToRef(this.position,targetCamera_TargetCamera._TargetFocalPoint),targetCamera_TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);let r=targetCamera_TargetCamera._TargetFocalPoint.addInPlace(this.position);math_vector_Matrix.TranslationToRef(-r.x,-r.y,-r.z,targetCamera_TargetCamera._TargetTransformMatrix),targetCamera_TargetCamera._TargetTransformMatrix.multiplyToRef(math_vector_Matrix.RotationAxis(t.upVector,e),targetCamera_TargetCamera._RigCamTransformMatrix),math_vector_Matrix.TranslationToRef(r.x,r.y,r.z,targetCamera_TargetCamera._TargetTransformMatrix),targetCamera_TargetCamera._RigCamTransformMatrix.multiplyToRef(targetCamera_TargetCamera._TargetTransformMatrix,targetCamera_TargetCamera._RigCamTransformMatrix),math_vector_Vector3.TransformCoordinatesToRef(this.position,targetCamera_TargetCamera._RigCamTransformMatrix,t.position),t.setTarget(r)}getClassName(){return"TargetCamera"}};targetCamera_TargetCamera._RigCamTransformMatrix=new math_vector_Matrix,targetCamera_TargetCamera._TargetTransformMatrix=new math_vector_Matrix,targetCamera_TargetCamera._TargetFocalPoint=new math_vector_Vector3,__decorate([serializeAsVector3()],targetCamera_TargetCamera.prototype,"rotation",void 0),__decorate([serialize()],targetCamera_TargetCamera.prototype,"speed",void 0),__decorate([serializeAsMeshReference("lockedTargetId")],targetCamera_TargetCamera.prototype,"lockedTarget",void 0);let FreeCamera=class FreeCamera extends targetCamera_TargetCamera{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){let e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){let t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){let e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){let t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){let e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){let e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){let e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){let e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new math_vector_Vector3(.5,1,.5),this.ellipsoidOffset=new math_vector_Vector3(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=math_vector_Vector3.Zero(),this._diffPosition=math_vector_Vector3.Zero(),this._newPosition=math_vector_Vector3.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>engine_Engine.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new FreeCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new math_vector_Vector3(0,0,0),this.cameraRotation=new math_vector_Vector2(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?math_vector_Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=math_vector_Vector3.Zero(),this._transformedDirection=math_vector_Vector3.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"}};__decorate([serializeAsVector3()],FreeCamera.prototype,"ellipsoid",void 0),__decorate([serializeAsVector3()],FreeCamera.prototype,"ellipsoidOffset",void 0),__decorate([serialize()],FreeCamera.prototype,"checkCollisions",void 0),__decorate([serialize()],FreeCamera.prototype,"applyGravity",void 0),node_Node.AddNodeConstructor("TouchCamera",(e,t)=>()=>new TouchCamera(e,math_vector_Vector3.Zero(),t));let TouchCamera=class TouchCamera extends FreeCamera{get touchAngularSensibility(){let e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){let e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){let 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(){let e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}};node_Node.AddNodeConstructor("ArcRotateCamera",(e,t)=>()=>new ArcRotateCamera(e,0,0,1,math_vector_Vector3.Zero(),t));let ArcRotateCamera=class ArcRotateCamera extends targetCamera_TargetCamera{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 math_vector_Matrix,this._upToYMatrix=new math_vector_Matrix,this._upVector=math_vector_Vector3.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){math_vector_Matrix.RotationAlignToRef(math_vector_Vector3.UpReadOnly,this._upVector,this._yToUpMatrix),math_vector_Matrix.RotationAlignToRef(this._upVector,math_vector_Vector3.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){let e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){let t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){let e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){let t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){let e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){let t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){let e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){let t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){let e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){let e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){let t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){let e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){let 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 BouncingBehavior,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 FramingBehavior,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 AutoRotationBehavior,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,a,n=!0){super(e,math_vector_Vector3.Zero(),a,n),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=math_vector_Vector3.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=math_vector_Vector2.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new math_vector_Matrix,this.panningAxis=new math_vector_Vector3(1,1,0),this._transformedDirection=new math_vector_Vector3,this.mapPanning=!1,this.onMeshTargetChangedObservable=new observable_Observable,this.checkCollisions=!1,this.collisionRadius=new math_vector_Vector3(.5,.5,.5),this._previousPosition=math_vector_Vector3.Zero(),this._collisionVelocity=math_vector_Vector3.Zero(),this._newPosition=math_vector_Vector3.Zero(),this._computationVector=math_vector_Vector3.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);let r=Math.cos(this.alpha),s=Math.sin(this.alpha),a=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);let o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*r*n,this.radius*a,this.radius*s*n),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=(l=l.clone()).negate()),this._computeViewMatrix(this._position,o,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=math_vector_Vector3.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new ArcRotateCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new math_vector_Vector3(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=math_vector_Vector2.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){let e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}let 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,r=2){let s=arguments;t=tools_Tools.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){let e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier(),i=this.inertialAlphaOffset*t;this.beta<=0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,.001>Math.abs(this.inertialAlphaOffset)&&(this.inertialAlphaOffset=0),.001>Math.abs(this.inertialBetaOffset)&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<.001*this.speed&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){let e=new math_vector_Vector3(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.multiplyInPlace(this.panningAxis),math_vector_Vector3.TransformNormalToRef(e,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){let e=this.upVector,t=math_vector_Vector3.CrossToRef(this._transformedDirection,e,this._transformedDirection);math_vector_Vector3.CrossToRef(e,t,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);if(!this._targetHost){if(this.panningDistanceLimit){this._transformedDirection.addInPlace(this._target);let e=math_vector_Vector3.DistanceSquared(this._transformedDirection,this.panningOriginTarget);e<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)}else this._target.addInPlace(this._transformedDirection)}this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<.001*this.speed&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<.001*this.speed&&(this.inertialPanningY=0)}this._checkLimits(),super._checkInputs()}}_checkLimits(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),null!==this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(0!==this._upVector.x||1!==this._upVector.y||0!==this._upVector.z)&&math_vector_Vector3.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);let 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);let t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,r=!1){var s;if(r=null!==(s=this.overrideCloneAlphaBetaRadius)&&void 0!==s?s:r,e.getBoundingInfo)t?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{let t=this._getTargetPosition();if(t&&!i&&t.equals(e))return;this._targetHost=null,this._target=e,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){let e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);0===r&&(r=1e-4),0===this.radius&&(this.radius=1e-4);let s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(0!==this._upVector.x||1!==this._upVector.y||0!==this._upVector.z)&&math_vector_Vector3.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){let e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&r<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;let i=mesh_Mesh.MinMax(e),r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(void 0===e.min){let t=e||this.getScene().meshes;i=mesh_Mesh.MinMax(t),r=math_vector_Vector3.Distance(i.min,i.max)}else i=e,r=e.distance;this._target=mesh_Mesh.Center(i),t||(this.maxZ=2*r)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:case camera_Camera.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}let r=new ArcRotateCamera(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:case camera_Camera.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){let r=math_vector_Vector3.Distance(e,t),s=this.getScene().getEngine(),a=s.getAspectRatio(this),n=Math.tan(this.fov/2),o=n*a,l=.5*r*i;return Math.max(l*Math.sqrt(1+1/(o*o)),l*Math.sqrt(1+1/(n*n)))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}};__decorate([serialize()],ArcRotateCamera.prototype,"alpha",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"beta",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"radius",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"overrideCloneAlphaBetaRadius",void 0),__decorate([serializeAsVector3("target")],ArcRotateCamera.prototype,"_target",void 0),__decorate([serializeAsMeshReference("targetHost")],ArcRotateCamera.prototype,"_targetHost",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"inertialAlphaOffset",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"inertialBetaOffset",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"inertialRadiusOffset",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"lowerAlphaLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"upperAlphaLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"lowerBetaLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"upperBetaLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"lowerRadiusLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"upperRadiusLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"inertialPanningX",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"inertialPanningY",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"pinchToPanMaxDistance",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"panningDistanceLimit",void 0),__decorate([serializeAsVector3()],ArcRotateCamera.prototype,"panningOriginTarget",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"panningInertia",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"zoomToMouseLocation",null),__decorate([serialize()],ArcRotateCamera.prototype,"zoomOnFactor",void 0),__decorate([generateSerializableMember(4,void 0)],ArcRotateCamera.prototype,"targetScreenOffset",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"allowUpsideDown",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"useInputToRestoreState",void 0),node_Node.AddNodeConstructor("DeviceOrientationCamera",(e,t)=>()=>new DeviceOrientationCamera(e,math_vector_Vector3.Zero(),t));let DeviceOrientationCamera=class DeviceOrientationCamera extends FreeCamera{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new math_vector_Quaternion,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new math_vector_Quaternion,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 math_vector_Quaternion),math_vector_Quaternion.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=math_axis_Axis.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new math_vector_Quaternion),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))}};let FlyCameraInputsManager=class FlyCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addKeyboard(){return this.add(new FlyCameraKeyboardInput),this}addMouse(){return this.add(new FlyCameraMouseInput),this}};let FlyCamera=class FlyCamera extends targetCamera_TargetCamera{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){let e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){let t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){let e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){let t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new math_vector_Vector3(1,1,1),this.ellipsoidOffset=new math_vector_Vector3(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=math_vector_Vector3.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=math_vector_Vector3.Zero(),this._diffPosition=math_vector_Vector3.Zero(),this._newPosition=math_vector_Vector3.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()>engine_Engine.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new FlyCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new math_vector_Vector3(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?math_vector_Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=math_vector_Vector3.Zero(),this._transformedDirection=math_vector_Vector3.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){let t=this._trackRoll,i=this.rotation.z,r=t-i;Math.abs(r)>=.001&&(this.rotation.z+=r/e,.001>=Math.abs(t-this.rotation.z)&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}};__decorate([serializeAsVector3()],FlyCamera.prototype,"ellipsoid",void 0),__decorate([serializeAsVector3()],FlyCamera.prototype,"ellipsoidOffset",void 0),__decorate([serialize()],FlyCamera.prototype,"checkCollisions",void 0),__decorate([serialize()],FlyCamera.prototype,"applyGravity",void 0);let FollowCameraInputsManager=class FollowCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addKeyboard(){return this.add(new FollowCameraKeyboardMoveInput),this}addMouseWheel(){return this.add(new FollowCameraMouseWheelInput),this}addPointers(){return this.add(new FollowCameraPointersInput),this}addVRDeviceOrientation(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this}};node_Node.AddNodeConstructor("FollowCamera",(e,t)=>()=>new FollowCamera(e,math_vector_Vector3.Zero(),t)),node_Node.AddNodeConstructor("ArcFollowCamera",(e,t)=>()=>new ArcFollowCamera(e,0,0,1,null,t));let FollowCamera=class FollowCamera extends targetCamera_TargetCamera{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new FollowCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;let t=math_vector_TmpVectors.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);let i=Math.atan2(t.m[8],t.m[10]),r=tools_Tools.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),a=s.x+Math.sin(r)*this.radius,n=s.z+Math.cos(r)*this.radius,o=a-this.position.x,l=s.y+this.heightOffset-this.position.y,h=n-this.position.z,c=o*this.cameraAcceleration*2,u=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new math_vector_Vector3(this.position.x+c,this.position.y+u,this.position.z+d),this.setTarget(s)}attachControl(e,t){t=tools_Tools.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.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffset<this.lowerHeightOffsetLimit&&(this.heightOffset=this.lowerHeightOffsetLimit),null!==this.upperHeightOffsetLimit&&this.heightOffset>this.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffset<this.lowerRotationOffsetLimit&&(this.rotationOffset=this.lowerRotationOffsetLimit),null!==this.upperRotationOffsetLimit&&this.rotationOffset>this.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}};__decorate([serialize()],FollowCamera.prototype,"radius",void 0),__decorate([serialize()],FollowCamera.prototype,"lowerRadiusLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"upperRadiusLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"rotationOffset",void 0),__decorate([serialize()],FollowCamera.prototype,"lowerRotationOffsetLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"upperRotationOffsetLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"heightOffset",void 0),__decorate([serialize()],FollowCamera.prototype,"lowerHeightOffsetLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"upperHeightOffsetLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"cameraAcceleration",void 0),__decorate([serialize()],FollowCamera.prototype,"maxCameraSpeed",void 0),__decorate([serializeAsMeshReference("lockedTargetId")],FollowCamera.prototype,"lockedTarget",void 0);let ArcFollowCamera=class ArcFollowCamera extends targetCamera_TargetCamera{constructor(e,t,i,r,s,a){super(e,math_vector_Vector3.Zero(),a),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=math_vector_Vector3.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);let 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.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"})(eM||(eM={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(eI||(eI={}));let Xbox360Pad=class Xbox360Pad extends Gamepad{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new observable_Observable,this.onButtonUpObservable=new observable_Observable,this.onPadDownObservable=new observable_Observable,this.onPadUpObservable=new observable_Observable,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=Gamepad.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,eM.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,eM.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,eM.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,eM.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,eM.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,eM.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,eM.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,eM.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,eM.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,eM.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,eI.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,eI.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,eI.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,eI.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"})(eD||(eD={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(eO||(eO={}));let DualShockPad=class DualShockPad extends Gamepad{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 observable_Observable,this.onButtonUpObservable=new observable_Observable,this.onPadDownObservable=new observable_Observable,this.onPadUpObservable=new observable_Observable,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=Gamepad.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,eD.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,eD.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,eD.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,eD.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,eD.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,eD.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,eD.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,eD.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,eD.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,eD.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,eO.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,eO.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,eO.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,eO.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()}};let GamepadManager=class GamepadManager{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new observable_Observable,IsWindowObjectExist()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new observable_Observable(e=>{for(let t in this._babylonGamepads){let i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}}),this._onGamepadConnectedEvent=e=>{let t;let i=e.gamepad;i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected||(this._babylonGamepads[i.index]?((t=this._babylonGamepads[i.index]).browserGamepad=i,t._isConnected=!0):t=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(t),this._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=e=>{let t=e.gamepad;for(let e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){let t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport){if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){let 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=Gamepad.XBOX){for(let 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);let i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),r=-1!==e.id.search("Xbox One");return t=r||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Xbox360Pad(e.id,e.index,e,r):i?new DualShockPad(e.id,e.index,e):new GenericPad(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){for(let e in this._updateGamepadObjects(),this._babylonGamepads){let t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch(e){-1===this._loggedErrors.indexOf(t.index)&&(tools_Tools.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&engine_Engine.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){let e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t<e.length;t++){let i=e[t];if(i){if(this._babylonGamepads[i.index])this._babylonGamepads[t].browserGamepad=i,this._babylonGamepads[t].isConnected||(this._babylonGamepads[t]._isConnected=!0,this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[t]));else{let e=this._addNewGamepad(i);this.onGamepadConnectedObservable.notifyObservers(e)}}}}};Object.defineProperty(scene_Scene.prototype,"gamepadManager",{get:function(){if(!this._gamepadManager){this._gamepadManager=new GamepadManager(this);let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_GAMEPAD);e||(e=new GamepadSystemSceneComponent(this),this._addComponent(e))}return this._gamepadManager},enumerable:!0,configurable:!0}),FreeCameraInputsManager.prototype.addGamepad=function(){return this.add(new FreeCameraGamepadInput),this},ArcRotateCameraInputsManager.prototype.addGamepad=function(){return this.add(new ArcRotateCameraGamepadInput),this};let GamepadSystemSceneComponent=class GamepadSystemSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_GAMEPAD,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD,this,this._beforeCameraUpdate)}rebuild(){}dispose(){let e=this.scene._gamepadManager;e&&(e.dispose(),this.scene._gamepadManager=null)}_beforeCameraUpdate(){let e=this.scene._gamepadManager;e&&e._isMonitoring&&e._checkGamepadsStatus()}};node_Node.AddNodeConstructor("FreeCamera",(e,t)=>()=>new universalCamera_UniversalCamera(e,math_vector_Vector3.Zero(),t));let universalCamera_UniversalCamera=class universalCamera_UniversalCamera extends TouchCamera{get gamepadAngularSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}};camera_Camera._CreateDefaultParsedCamera=(e,t)=>new universalCamera_UniversalCamera(e,math_vector_Vector3.Zero(),t),node_Node.AddNodeConstructor("GamepadCamera",(e,t)=>()=>new GamepadCamera(e,math_vector_Vector3.Zero(),t));let GamepadCamera=class GamepadCamera extends universalCamera_UniversalCamera{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}};let ih=`varying vec2 vUV;uniform samplerCube textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 uv=vUV*2.0-1.0; +#ifdef POSITIVEX +gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); +#endif +#ifdef NEGATIVEX +gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); +#endif +#ifdef POSITIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); +#endif +#ifdef NEGATIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); +#endif +#ifdef POSITIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); +#endif +#ifdef NEGATIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); +#endif +}`;ShaderStore.ShadersStore.passCubePixelShader=ih;let PassPostProcess=class PassPostProcess extends postProcess_PostProcess{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,a,n=0,o=!1){super(e,"pass",null,null,t,i,r,s,a,void 0,n,void 0,null,o)}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new PassPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}};h["BABYLON.PassPostProcess"]=PassPostProcess,engine_Engine._RescalePostProcessFactory=e=>new PassPostProcess("rescale",1,null,2,e,!1,0);let ic=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`;ShaderStore.ShadersStore.anaglyphPixelShader=ic;let AnaglyphPostProcess=class AnaglyphPostProcess extends postProcess_PostProcess{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,s,a){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,s,a),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)})}};function setStereoscopicAnaglyphRigMode(e){e._rigCameras[0]._rigPostProcess=new PassPostProcess(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new AnaglyphPostProcess(e.name+"_anaglyph",1,e._rigCameras)}h["BABYLON.AnaglyphPostProcess"]=AnaglyphPostProcess,node_Node.AddNodeConstructor("AnaglyphArcRotateCamera",(e,t,i)=>()=>new AnaglyphArcRotateCamera(e,0,0,1,math_vector_Vector3.Zero(),i.interaxial_distance,t));let AnaglyphArcRotateCamera=class AnaglyphArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,a,n){super(e,t,i,r,s,n),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=a,this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:a})}getClassName(){return"AnaglyphArcRotateCamera"}};node_Node.AddNodeConstructor("AnaglyphFreeCamera",(e,t,i)=>()=>new AnaglyphFreeCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,t));let AnaglyphFreeCamera=class AnaglyphFreeCamera extends FreeCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}};node_Node.AddNodeConstructor("AnaglyphGamepadCamera",(e,t,i)=>()=>new AnaglyphGamepadCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,t));let AnaglyphGamepadCamera=class AnaglyphGamepadCamera extends GamepadCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}};node_Node.AddNodeConstructor("AnaglyphUniversalCamera",(e,t,i)=>()=>new AnaglyphUniversalCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,t));let AnaglyphUniversalCamera=class AnaglyphUniversalCamera extends universalCamera_UniversalCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}};let iu=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; +#ifdef IS_STEREOSCOPIC_HORIZ +useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); +#else +#ifdef IS_STEREOSCOPIC_INTERLACED +float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); +#else +useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); +#endif +#endif +if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} +gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} +`;ShaderStore.ShadersStore.stereoscopicInterlacePixelShader=iu;let StereoscopicInterlacePostProcessI=class StereoscopicInterlacePostProcessI extends postProcess_PostProcess{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,s,a,n){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,a,n,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new math_vector_Vector2(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new math_vector_Vector2(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 setStereoscopicRigMode(e){let t=e.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,r=e.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED;r?(e._rigCameras[0]._rigPostProcess=new PassPostProcess(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new StereoscopicInterlacePostProcessI(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new math_viewport_Viewport(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new math_viewport_Viewport(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}node_Node.AddNodeConstructor("StereoscopicArcRotateCamera",(e,t,i)=>()=>new StereoscopicArcRotateCamera(e,0,0,1,math_vector_Vector3.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicArcRotateCamera=class StereoscopicArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,a,n,o){super(e,t,i,r,s,o),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=a,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:a})}getClassName(){return"StereoscopicArcRotateCamera"}};node_Node.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new StereoscopicFreeCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicFreeCamera=class StereoscopicFreeCamera extends FreeCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}};node_Node.AddNodeConstructor("StereoscopicGamepadCamera",(e,t,i)=>()=>new StereoscopicGamepadCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicGamepadCamera=class StereoscopicGamepadCamera extends GamepadCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}};node_Node.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new StereoscopicUniversalCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicUniversalCamera=class StereoscopicUniversalCamera extends universalCamera_UniversalCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}};node_Node.AddNodeConstructor("VirtualJoysticksCamera",(e,t)=>()=>new VirtualJoysticksCamera(e,math_vector_Vector3.Zero(),t));let VirtualJoysticksCamera=class VirtualJoysticksCamera extends FreeCamera{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}};let VRCameraMetrics=class VRCameraMetrics{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(){let e=this.hScreenSize/4-this.lensSeparationDistance/2,t=4*e/this.hScreenSize;return math_vector_Matrix.Translation(t,0,0)}get rightHMatrix(){let e=this.hScreenSize/4-this.lensSeparationDistance/2,t=4*e/this.hScreenSize;return math_vector_Matrix.Translation(-t,0,0)}get leftPreViewMatrix(){return math_vector_Matrix.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return math_vector_Matrix.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){let e=new VRCameraMetrics;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}};let id=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; +float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) +gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;ShaderStore.ShadersStore.vrDistortionCorrectionPixelShader=id;let VRDistortionCorrectionPostProcess=class VRDistortionCorrectionPostProcess extends postProcess_PostProcess{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,texture_Texture.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new math_vector_Vector2(2,2/this.aspectRatio),this._scaleFactor=new math_vector_Vector2(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new math_vector_Vector2(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])})}};let i_=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;ShaderStore.ShadersStore.vrMultiviewToSingleviewPixelShader=i_;let MultiviewRenderTarget=class MultiviewRenderTarget extends renderTargetTexture_RenderTargetTexture{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 createMultiviewUbo(e,t){let i=new UniformBuffer(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}engine_Engine.prototype.createMultiviewRenderTargetTexture=function(e,t,i,r){let s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";let a=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});a._framebuffer=s.createFramebuffer();let n=new internalTexture_InternalTexture(this,$.Unknown,!0);return n.width=e,n.height=t,n.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)),a._colorTextureArray=i,r||(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,r),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),a._depthStencilTextureArray=r,n.isReady=!0,a.setTextures(n),a._depthStencilTexture=n,a},engine_Engine.prototype.bindMultiviewFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"},engine_Engine.prototype.bindSpaceWarpFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_ATTACHMENT,e._depthStencilTextureArray,0,0,2);else throw Error("Invalid Space Warp framebuffer")},camera_Camera.prototype._useMultiviewToSingleView=!1,camera_Camera.prototype._multiviewTexture=null,camera_Camera.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=e||this._multiviewTexture.getRenderHeight()!=t)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new MultiviewRenderTarget(this.getScene(),{width:e,height:t})):this._multiviewTexture=new MultiviewRenderTarget(this.getScene(),{width:e,height:t})};let ip=scene_Scene.prototype.createSceneUniformBuffer;scene_Scene.prototype._transformMatrixR=math_vector_Matrix.Zero(),scene_Scene.prototype._multiviewSceneUbo=null,scene_Scene.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=createMultiviewUbo(this.getEngine(),"scene_multiview")},scene_Scene.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?createMultiviewUbo(this.getEngine(),e):ip.bind(this)(e)},scene_Scene.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,math_vector_TmpVectors.Matrix[0]),Frustum.GetRightPlaneToRef(math_vector_TmpVectors.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))},scene_Scene.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<e._rigCameras.length;t++){let i=this.getEngine();this._activeCamera=e._rigCameras[t],i.setViewport(this._activeCamera.viewport),this.postProcessManager&&(this.postProcessManager._prepareFrame(),this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate))}};let VRMultiviewToSingleviewPostProcess=class VRMultiviewToSingleviewPostProcess extends postProcess_PostProcess{getClassName(){return"VRMultiviewToSingleviewPostProcess"}constructor(e,t,i){super(e,"vrMultiviewToSingleview",["imageIndex"],["multiviewSampler"],i,t,texture_Texture.BILINEAR_SAMPLINGMODE);let r=null!=t?t:this.getCamera();this.onSizeChangedObservable.add(()=>{}),this.onApplyObservable.add(e=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",r._multiviewTexture)})}};function setVRRigMode(e,t){let i=t.vrCameraMetrics||VRCameraMetrics.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new math_viewport_Viewport(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new math_vector_Matrix,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 math_viewport_Viewport(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new math_vector_Matrix,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 VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(logger_Logger.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}node_Node.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(e,t)=>()=>new VRDeviceOrientationArcRotateCamera(e,0,0,1,math_vector_Vector3.Zero(),t));let VRDeviceOrientationArcRotateCamera=class VRDeviceOrientationArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,a,n=!0,o=VRCameraMetrics.GetDefault()){super(e,t,i,r,s,a),this._setRigMode=e=>setVRRigMode(this,e),o.compensateDistortion=n,this.setCameraRigMode(camera_Camera.RIG_MODE_VR,{vrCameraMetrics:o}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}};node_Node.AddNodeConstructor("VRDeviceOrientationFreeCamera",(e,t)=>()=>new VRDeviceOrientationFreeCamera(e,math_vector_Vector3.Zero(),t));let VRDeviceOrientationFreeCamera=class VRDeviceOrientationFreeCamera extends DeviceOrientationCamera{constructor(e,t,i,r=!0,s=VRCameraMetrics.GetDefault()){super(e,t,i),this._setRigMode=e=>setVRRigMode(this,e),s.compensateDistortion=r,this.setCameraRigMode(camera_Camera.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}};node_Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(e,t)=>()=>new VRDeviceOrientationGamepadCamera(e,math_vector_Vector3.Zero(),t));let VRDeviceOrientationGamepadCamera=class VRDeviceOrientationGamepadCamera extends VRDeviceOrientationFreeCamera{constructor(e,t,i,r=!0,s=VRCameraMetrics.GetDefault()){super(e,t,i,r,s),this._setRigMode=e=>setVRRigMode(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}};let PrePassConfiguration=class PrePassConfiguration{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());let s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}};let MaterialFlags=class MaterialFlags{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}};MaterialFlags._DiffuseTextureEnabled=!0,MaterialFlags._DetailTextureEnabled=!0,MaterialFlags._DecalMapEnabled=!0,MaterialFlags._AmbientTextureEnabled=!0,MaterialFlags._OpacityTextureEnabled=!0,MaterialFlags._ReflectionTextureEnabled=!0,MaterialFlags._EmissiveTextureEnabled=!0,MaterialFlags._SpecularTextureEnabled=!0,MaterialFlags._BumpTextureEnabled=!0,MaterialFlags._LightmapTextureEnabled=!0,MaterialFlags._RefractionTextureEnabled=!0,MaterialFlags._ColorGradingTextureEnabled=!0,MaterialFlags._FresnelEnabled=!0,MaterialFlags._ClearCoatTextureEnabled=!0,MaterialFlags._ClearCoatBumpTextureEnabled=!0,MaterialFlags._ClearCoatTintTextureEnabled=!0,MaterialFlags._SheenTextureEnabled=!0,MaterialFlags._AnisotropicTextureEnabled=!0,MaterialFlags._ThicknessTextureEnabled=!0,MaterialFlags._RefractionIntensityTextureEnabled=!0,MaterialFlags._TranslucencyIntensityTextureEnabled=!0,MaterialFlags._IridescenceTextureEnabled=!0;let im=`#ifdef DECAL +uniform vec4 vDecalInfos; +#endif +`;ShaderStore.IncludesShadersStore.decalFragmentDeclaration=im;let ig=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; +#ifdef SPECULARTERM +uniform vec4 vSpecularColor; +#endif +uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; +#ifdef DIFFUSE +uniform vec2 vDiffuseInfos; +#endif +#ifdef AMBIENT +uniform vec2 vAmbientInfos; +#endif +#ifdef OPACITY +uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#ifdef ALPHATEST +uniform float alphaCutOff; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) +uniform mat4 view; +#endif +#ifdef REFRACTION +uniform vec4 vRefractionInfos; +#ifndef REFRACTIONMAP_3D +uniform mat4 refractionMatrix; +#endif +#ifdef REFRACTIONFRESNEL +uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; +#endif +#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) +uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; +#endif +#endif +#if defined(SPECULAR) && defined(SPECULARTERM) +uniform vec2 vSpecularInfos; +#endif +#ifdef DIFFUSEFRESNEL +uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; +#endif +#ifdef OPACITYFRESNEL +uniform vec4 opacityParts; +#endif +#ifdef EMISSIVEFRESNEL +uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos; +#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) +uniform mat4 reflectionMatrix; +#endif +#ifndef REFLECTIONMAP_SKYBOX +#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; +#endif +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos; +#endif +#include<decalFragmentDeclaration> +#define ADDITIONAL_FRAGMENT_DECLARATION +`;ShaderStore.IncludesShadersStore.defaultFragmentDeclaration=ig;let iv=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; +#ifdef MULTIVIEW +mat4 viewProjectionR; +#endif +mat4 view;mat4 projection;vec4 vEyePosition;}; +`;ShaderStore.IncludesShadersStore.sceneUboDeclaration=iv;let ix=`#ifdef WEBGL2 +uniform mat4 world;uniform float visibility; +#else +layout(std140,column_major) uniform;uniform Mesh +{mat4 world;float visibility;}; +#endif +#define WORLD_UBO +`;ShaderStore.IncludesShadersStore.meshUboDeclaration=ix;let ib=`layout(std140,column_major) uniform;uniform Material +{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; +#define ADDITIONAL_UBO_DECLARATION +}; +#include<sceneUboDeclaration> +#include<meshUboDeclaration> +`;ShaderStore.IncludesShadersStore.defaultUboDeclaration=ib;let iT=`#ifdef PREPASS +#extension GL_EXT_draw_buffers : require +layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; +#ifdef PREPASS_DEPTH +varying highp vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; +#endif +#endif +`;ShaderStore.IncludesShadersStore.prePassDeclaration=iT;let iS=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +#extension GL_EXT_draw_buffers : require +layout(location=0) out vec2 depth; +layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; +#define MAX_DEPTH 99999.0 +highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; +#endif +`;ShaderStore.IncludesShadersStore.oitDeclaration=iS;let iC=`#ifdef MAINUV{X} +varying vec2 vMainUV{X}; +#endif +`;ShaderStore.IncludesShadersStore.mainUVVaryingDeclaration=iC;let iE=`const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; +const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; +#define saturate(x) clamp(x,0.0,1.0) +#define absEps(x) abs(x)+Epsilon +#define maxEps(x) max(x,Epsilon) +#define saturateEps(x) clamp(x,Epsilon,1.0) +mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( +vec3(i0.x,i1.x,i2.x), +vec3(i0.y,i1.y,i2.y), +vec3(i0.z,i1.z,i2.z) +);return outMatrix;} +mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), +b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), +b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} +#if USE_EXACT_SRGB_CONVERSIONS +vec3 toLinearSpaceExact(vec3 color) +{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); +#else +return +vec3( +color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, +color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, +color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); +#endif +} +vec3 toGammaSpaceExact(vec3 color) +{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); +#else +return +vec3( +color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, +color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, +color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); +#endif +} +#endif +float toLinearSpace(float color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; +#else +return pow(color,LinearEncodePowerApprox); +#endif +} +vec3 toLinearSpace(vec3 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toLinearSpaceExact(color); +#else +return pow(color,vec3(LinearEncodePowerApprox)); +#endif +} +vec4 toLinearSpace(vec4 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toLinearSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); +#endif +} +float toGammaSpace(float color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; +#else +return pow(color,GammaEncodePowerApprox); +#endif +} +vec3 toGammaSpace(vec3 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toGammaSpaceExact(color); +#else +return pow(color,vec3(GammaEncodePowerApprox)); +#endif +} +vec4 toGammaSpace(vec4 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toGammaSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); +#endif +} +float square(float value) +{return value*value;} +vec3 square(vec3 value) +{return value*value;} +float pow5(float value) {float sq=value*value;return sq*sq*value;} +float getLuminance(vec3 color) +{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} +float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} +float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} +const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); } +vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} +vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} +`;ShaderStore.IncludesShadersStore.helperFunctions=iE;let iy=`#ifdef LIGHT{X} +uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; +#ifdef SPECULARTERM +uniform vec4 vLightSpecular{X}; +#else +vec4 vLightSpecular{X}=vec4(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DArrayShadow shadowSampler{X}; +#else +uniform highp sampler2DArray shadowSampler{X}; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] +( +vec3 ( 1.5,0.0,0.0 ), +vec3 ( 0.0,1.5,0.0 ), +vec3 ( 0.0,0.0,5.5 ), +vec3 ( 1.5,0.0,5.5 ), +vec3 ( 1.5,1.5,0.0 ), +vec3 ( 1.0,1.0,1.0 ), +vec3 ( 0.0,1.0,5.5 ), +vec3 ( 0.5,3.5,0.75 ) +);vec3 shadowDebug{X}; +#endif +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +int index{X}=-1; +#else +int index{X}=SHADOWCSMNUM_CASCADES{X}-1; +#endif +float diff{X}=0.; +#elif defined(SHADOWCUBE{X}) +uniform samplerCube shadowSampler{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowSampler{X}; +#else +uniform sampler2D shadowSampler{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; +#endif +#ifdef SPOTLIGHT{X} +uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; +#elif defined(POINTLIGHT{X}) +uniform vec4 vLightFalloff{X}; +#elif defined(HEMILIGHT{X}) +uniform vec3 vLightGround{X}; +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; +#endif +#endif +`;ShaderStore.IncludesShadersStore.lightFragmentDeclaration=iy;let iR=`#ifdef LIGHT{X} +uniform Light{X} +{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; +#ifdef SPOTLIGHT{X} +vec4 vLightDirection;vec4 vLightFalloff; +#elif defined(POINTLIGHT{X}) +vec4 vLightFalloff; +#elif defined(HEMILIGHT{X}) +vec3 vLightGround; +#endif +vec4 shadowsInfo;vec2 depthValues;} light{X}; +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DArrayShadow shadowSampler{X}; +#else +uniform highp sampler2DArray shadowSampler{X}; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] +( +vec3 ( 1.5,0.0,0.0 ), +vec3 ( 0.0,1.5,0.0 ), +vec3 ( 0.0,0.0,5.5 ), +vec3 ( 1.5,0.0,5.5 ), +vec3 ( 1.5,1.5,0.0 ), +vec3 ( 1.0,1.0,1.0 ), +vec3 ( 0.0,1.0,5.5 ), +vec3 ( 0.5,3.5,0.75 ) +);vec3 shadowDebug{X}; +#endif +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +int index{X}=-1; +#else +int index{X}=SHADOWCSMNUM_CASCADES{X}-1; +#endif +float diff{X}=0.; +#elif defined(SHADOWCUBE{X}) +uniform samplerCube shadowSampler{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowSampler{X}; +#else +uniform sampler2D shadowSampler{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStore.lightUboDeclaration=iR;let iP=`struct lightingInfo +{vec3 diffuse; +#ifdef SPECULARTERM +vec3 specular; +#endif +#ifdef NDOTL +float ndl; +#endif +};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) +{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} +else +{lightVectorW=normalize(-lightData.xyz);} +float ndl=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) +{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +result.diffuse=vec3(0.); +#ifdef SPECULARTERM +result.specular=vec3(0.); +#endif +#ifdef NDOTL +result.ndl=0.; +#endif +return result;} +lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=mix(groundColor,diffuseColor,ndl); +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; +#endif +return result;} +#define inline +vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;ShaderStore.IncludesShadersStore.lightsFragmentFunctions=iP;let iA=`#ifdef SHADOWS +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +#ifndef SHADOWFLOAT +float unpack(vec4 color) +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} +#endif +float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) +{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} +#define inline +float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +float shadow=unpack(textureCube(shadowSampler,directionToLight)); +#else +float shadow=textureCube(shadowSampler,directionToLight).x; +#endif +return depth>shadow ? darkness : 1.0;} +#define inline +float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); +#ifndef SHADOWFLOAT +if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25; +#else +if (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25; +#endif +return min(1.0,visibility+darkness);} +#define inline +float computeShadowWithESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight)); +#else +float shadowMapSample=textureCube(shadowSampler,directionToLight).x; +#endif +float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;} +#define inline +float computeShadowWithCloseESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight)); +#else +float shadowMapSample=textureCube(shadowSampler,directionToLight).x; +#endif +float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;} +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define inline +float computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);vec3 uvLayer=vec3(uv.x,uv.y,layer);float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadow=unpack(texture2D(shadowSampler,uvLayer)); +#else +float shadow=texture2D(shadowSampler,uvLayer).x; +#endif +return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} +#endif +#define inline +float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} +#define inline +float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); +#ifndef SHADOWFLOAT +if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25; +#else +if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25; +#endif +return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +#ifdef IS_NDC_HALF_ZRANGE +#define ZINCLIP clipSpace.z +#else +#define ZINCLIP uvDepth.z +#endif +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define GREATEST_LESS_THAN_ONE 0.99999994 +/* disable_uniformity_analysis */ +#define inline +float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +const vec3 PoissonSamplers32[64]=vec3[64]( +vec3(0.06407013,0.05409927,0.), +vec3(0.7366577,0.5789394,0.), +vec3(-0.6270542,-0.5320278,0.), +vec3(-0.4096107,0.8411095,0.), +vec3(0.6849564,-0.4990818,0.), +vec3(-0.874181,-0.04579735,0.), +vec3(0.9989998,0.0009880066,0.), +vec3(-0.004920578,-0.9151649,0.), +vec3(0.1805763,0.9747483,0.), +vec3(-0.2138451,0.2635818,0.), +vec3(0.109845,0.3884785,0.), +vec3(0.06876755,-0.3581074,0.), +vec3(0.374073,-0.7661266,0.), +vec3(0.3079132,-0.1216763,0.), +vec3(-0.3794335,-0.8271583,0.), +vec3(-0.203878,-0.07715034,0.), +vec3(0.5912697,0.1469799,0.), +vec3(-0.88069,0.3031784,0.), +vec3(0.5040108,0.8283722,0.), +vec3(-0.5844124,0.5494877,0.), +vec3(0.6017799,-0.1726654,0.), +vec3(-0.5554981,0.1559997,0.), +vec3(-0.3016369,-0.3900928,0.), +vec3(-0.5550632,-0.1723762,0.), +vec3(0.925029,0.2995041,0.), +vec3(-0.2473137,0.5538505,0.), +vec3(0.9183037,-0.2862392,0.), +vec3(0.2469421,0.6718712,0.), +vec3(0.3916397,-0.4328209,0.), +vec3(-0.03576927,-0.6220032,0.), +vec3(-0.04661255,0.7995201,0.), +vec3(0.4402924,0.3640312,0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.) +);const vec3 PoissonSamplers64[64]=vec3[64]( +vec3(-0.613392,0.617481,0.), +vec3(0.170019,-0.040254,0.), +vec3(-0.299417,0.791925,0.), +vec3(0.645680,0.493210,0.), +vec3(-0.651784,0.717887,0.), +vec3(0.421003,0.027070,0.), +vec3(-0.817194,-0.271096,0.), +vec3(-0.705374,-0.668203,0.), +vec3(0.977050,-0.108615,0.), +vec3(0.063326,0.142369,0.), +vec3(0.203528,0.214331,0.), +vec3(-0.667531,0.326090,0.), +vec3(-0.098422,-0.295755,0.), +vec3(-0.885922,0.215369,0.), +vec3(0.566637,0.605213,0.), +vec3(0.039766,-0.396100,0.), +vec3(0.751946,0.453352,0.), +vec3(0.078707,-0.715323,0.), +vec3(-0.075838,-0.529344,0.), +vec3(0.724479,-0.580798,0.), +vec3(0.222999,-0.215125,0.), +vec3(-0.467574,-0.405438,0.), +vec3(-0.248268,-0.814753,0.), +vec3(0.354411,-0.887570,0.), +vec3(0.175817,0.382366,0.), +vec3(0.487472,-0.063082,0.), +vec3(-0.084078,0.898312,0.), +vec3(0.488876,-0.783441,0.), +vec3(0.470016,0.217933,0.), +vec3(-0.696890,-0.549791,0.), +vec3(-0.149693,0.605762,0.), +vec3(0.034211,0.979980,0.), +vec3(0.503098,-0.308878,0.), +vec3(-0.016205,-0.872921,0.), +vec3(0.385784,-0.393902,0.), +vec3(-0.146886,-0.859249,0.), +vec3(0.643361,0.164098,0.), +vec3(0.634388,-0.049471,0.), +vec3(-0.688894,0.007843,0.), +vec3(0.464034,-0.188818,0.), +vec3(-0.440840,0.137486,0.), +vec3(0.364483,0.511704,0.), +vec3(0.034028,0.325968,0.), +vec3(0.099094,-0.308023,0.), +vec3(0.693960,-0.366253,0.), +vec3(0.678884,-0.204688,0.), +vec3(0.001801,0.780328,0.), +vec3(0.145177,-0.898984,0.), +vec3(0.062655,-0.611866,0.), +vec3(0.315226,-0.604297,0.), +vec3(-0.780145,0.486251,0.), +vec3(-0.371868,0.882138,0.), +vec3(0.200476,0.494430,0.), +vec3(-0.494552,-0.711051,0.), +vec3(0.612476,0.705252,0.), +vec3(-0.578845,-0.768792,0.), +vec3(-0.772454,-0.090976,0.), +vec3(0.504440,0.372295,0.), +vec3(0.155736,0.065157,0.), +vec3(0.391522,0.849605,0.), +vec3(-0.620106,-0.328104,0.), +vec3(0.789239,-0.419965,0.), +vec3(-0.545396,0.538133,0.), +vec3(-0.178564,-0.596057,0.) +); +#define inline +float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}} +float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec4 offset=vec4(poissonSamplers[i],0.);offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);} +shadow/=float(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);if (numBlocker<1.0) {return 1.0;} +else +{return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}} +if (numBlocker<1.0) {return 1.0;} +else +{float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec3 offset=poissonSamplers[i];offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);shadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);} +shadow/=float(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}} +#define inline +float computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) +{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);} +#define inline +float computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) +{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);} +#define inline +float computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) +{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);} +#define inline +float computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} +#define inline +float computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} +#define inline +float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} +#endif +#endif +`;ShaderStore.IncludesShadersStore.shadowsFragmentFunctions=iA;let iM=`#ifdef _DEFINENAME_ +#if _DEFINENAME_DIRECTUV==1 +#define v_VARYINGNAME_UV vMainUV1 +#elif _DEFINENAME_DIRECTUV==2 +#define v_VARYINGNAME_UV vMainUV2 +#elif _DEFINENAME_DIRECTUV==3 +#define v_VARYINGNAME_UV vMainUV3 +#elif _DEFINENAME_DIRECTUV==4 +#define v_VARYINGNAME_UV vMainUV4 +#elif _DEFINENAME_DIRECTUV==5 +#define v_VARYINGNAME_UV vMainUV5 +#elif _DEFINENAME_DIRECTUV==6 +#define v_VARYINGNAME_UV vMainUV6 +#else +varying vec2 v_VARYINGNAME_UV; +#endif +uniform sampler2D _SAMPLERNAME_Sampler; +#endif +`;ShaderStore.IncludesShadersStore.samplerFragmentDeclaration=iM;let iI=`#ifdef FRESNEL +float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power) +{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} +#endif +`;ShaderStore.IncludesShadersStore.fresnelFunction=iI;let iD=`vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) +{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); } +vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) +{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); } +vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) +{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);} +vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix) +{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);} +vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) +{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));} +vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) +{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0)); +#ifdef INVERTCUBICMAP +coords.y*=-1.0; +#endif +return coords;} +vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition) +{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0)); +#ifdef INVERTCUBICMAP +coords.y*=-1.0; +#endif +return coords;} +vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix) +{return vec3(reflectionMatrix*(view*worldPos));} +vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix) +{return vec3(reflectionMatrix*vec4(positionW,1.));} +#ifdef REFLECTION +vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal) +{ +#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED +vec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction); +#endif +#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED +vec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction); +#endif +#ifdef REFLECTIONMAP_EQUIRECTANGULAR +return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_SPHERICAL +return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_PLANAR +return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_CUBIC +#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC +return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition); +#else +return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); +#endif +#endif +#ifdef REFLECTIONMAP_PROJECTION +return computeProjectionCoords(worldPos,view,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_SKYBOX +return computeSkyBoxCoords(vPositionUVW,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_EXPLICIT +return vec3(0,0,0); +#endif +} +#endif +`;ShaderStore.IncludesShadersStore.reflectionFunction=iD;let iO=`#ifdef EXPOSURE +uniform float exposureLinear; +#endif +#ifdef CONTRAST +uniform float contrast; +#endif +#if defined(VIGNETTE) || defined(DITHER) +uniform vec2 vInverseScreenSize; +#endif +#ifdef VIGNETTE +uniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2; +#endif +#ifdef COLORCURVES +uniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive; +#endif +#ifdef COLORGRADING +#ifdef COLORGRADING3D +uniform highp sampler3D txColorTransform; +#else +uniform sampler2D txColorTransform; +#endif +uniform vec4 colorTransformSettings; +#endif +#ifdef DITHER +uniform float ditherIntensity; +#endif +`;ShaderStore.IncludesShadersStore.imageProcessingDeclaration=iO;let iB=`#if defined(COLORGRADING) && !defined(COLORGRADING3D) +/** +* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL. +* sampler3dSetting.x=textureOffset (0.5/textureSize). +* sampler3dSetting.y=textureSize. +*/ +#define inline +vec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting) +{float sliceSize=2.0*sampler3dSetting.x; +#ifdef SAMPLER3DGREENDEPTH +float sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y; +#else +float sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y; +#endif +float sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger; +#ifdef SAMPLER3DGREENDEPTH +vec2 sliceUV=color.rb; +#else +vec2 sliceUV=color.rg; +#endif +sliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction); +#ifdef SAMPLER3DBGRMAP +color.rgb=result.rgb; +#else +color.rgb=result.bgr; +#endif +return color;} +#endif +#ifdef TONEMAPPING_ACES +const mat3 ACESInputMat=mat3( +vec3(0.59719,0.07600,0.02840), +vec3(0.35458,0.90834,0.13383), +vec3(0.04823,0.01566,0.83777) +);const mat3 ACESOutputMat=mat3( +vec3( 1.60475,-0.10208,-0.00327), +vec3(-0.53108, 1.10813,-0.07276), +vec3(-0.07367,-0.00605, 1.07602) +);vec3 RRTAndODTFit(vec3 v) +{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;} +vec3 ACESFitted(vec3 color) +{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;} +#endif +#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS +vec4 applyImageProcessing(vec4 result) { +#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART +#ifdef EXPOSURE +result.rgb*=exposureLinear; +#endif +#ifdef VIGNETTE +vec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb; +#ifdef VIGNETTEBLENDMODEMULTIPLY +vec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier; +#endif +#ifdef VIGNETTEBLENDMODEOPAQUE +result.rgb=mix(vignetteColor,result.rgb,vignette); +#endif +#endif +#ifdef TONEMAPPING +#ifdef TONEMAPPING_ACES +result.rgb=ACESFitted(result.rgb); +#else +const float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb); +#endif +#endif +result.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb); +#ifdef CONTRAST +vec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);} +#endif +#ifdef COLORGRADING +vec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy; +#ifdef COLORGRADING3D +vec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb; +#else +vec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb; +#endif +result.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www); +#endif +#ifdef COLORCURVES +float luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a); +#endif +#ifdef DITHER +float rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither)); +#endif +#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND +return result;}`;ShaderStore.IncludesShadersStore.imageProcessingFunctions=iB;let iN=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) +#if defined(TANGENT) && defined(NORMAL) +varying mat3 vTBN; +#endif +#ifdef OBJECTSPACE_NORMALMAP +uniform mat4 normalMatrix; +#if defined(WEBGL2) || defined(WEBGPU) +mat4 toNormalMatrix(mat4 wMatrix) +{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;} +#else +mat4 toNormalMatrix(mat4 m) +{float +a00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3], +a10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3], +a20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3], +a30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3], +b00=a00*a11-a01*a10, +b01=a00*a12-a02*a10, +b02=a00*a13-a03*a10, +b03=a01*a12-a02*a11, +b04=a01*a13-a03*a11, +b05=a02*a13-a03*a12, +b06=a20*a31-a21*a30, +b07=a20*a32-a22*a30, +b08=a20*a33-a23*a30, +b09=a21*a32-a22*a31, +b10=a21*a33-a23*a31, +b11=a22*a33-a23*a32, +det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4( +a11*b11-a12*b10+a13*b09, +a02*b10-a01*b11-a03*b09, +a31*b05-a32*b04+a33*b03, +a22*b04-a21*b05-a23*b03, +a12*b08-a10*b11-a13*b07, +a00*b11-a02*b08+a03*b07, +a32*b02-a30*b05-a33*b01, +a20*b05-a22*b02+a23*b01, +a10*b10-a11*b08+a13*b06, +a01*b08-a00*b10-a03*b06, +a30*b04-a31*b02+a33*b00, +a21*b02-a20*b04-a23*b00, +a11*b07-a10*b09-a12*b06, +a00*b09-a01*b07+a02*b06, +a31*b01-a30*b03-a32*b00, +a20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0], +mi[0][1],mi[1][1],mi[2][1],mi[3][1], +mi[0][2],mi[1][2],mi[2][2],mi[3][2], +mi[0][3],mi[1][3],mi[2][3],mi[3][3]);} +#endif +#endif +vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale) +{ +#ifdef NORMALXYSCALE +normal=normalize(normal*vec3(scale,scale,1.0)); +#endif +return normalize(cotangentFrame*normal);} +vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale) +{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);} +mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams) +{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);} +#endif +`;ShaderStore.IncludesShadersStore.bumpFragmentMainFunctions=iN;let iF=`#if defined(BUMP) +#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) +#endif +#if defined(DETAIL) +#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) +#endif +#if defined(BUMP) && defined(PARALLAX) +const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; i<iMaxSamples; i++) +{currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;if (!keepWorking) +{} +else if (currSampledHeight>currRayHeight) +{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} +else +{currRayHeight-=stepSize;vLastOffset=vCurrOffset; +#ifdef PARALLAX_RHS +vCurrOffset-=stepSize*vMaxOffset; +#else +vCurrOffset+=stepSize*vMaxOffset; +#endif +lastSampledHeight=currSampledHeight;}} +return vCurrOffset;} +vec2 parallaxOffset(vec3 viewDir,float heightScale) +{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height; +#ifdef PARALLAX_RHS +return texCoordOffset; +#else +return -texCoordOffset; +#endif +} +#endif +`;ShaderStore.IncludesShadersStore.bumpFragmentFunctions=iF;let iw=`#ifdef CLIPPLANE +varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +varying float fClipDistance6; +#endif +`;ShaderStore.IncludesShadersStore.clipPlaneFragmentDeclaration=iw;let iL=`#ifdef LOGARITHMICDEPTH +uniform float logarithmicDepthConstant;varying float vFragmentDepth; +#endif +`;ShaderStore.IncludesShadersStore.logDepthDeclaration=iL;let iV=`#ifdef FOG +#define FOGMODE_NONE 0. +#define FOGMODE_EXP 1. +#define FOGMODE_EXP2 2. +#define FOGMODE_LINEAR 3. +#define E 2.71828 +uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() +{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) +{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} +else if (FOGMODE_EXP==vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDensity);} +else if (FOGMODE_EXP2==vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} +return clamp(fogCoeff,0.0,1.0);} +#endif +`;ShaderStore.IncludesShadersStore.fogFragmentDeclaration=iV;let iU=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +if (false) {} +#endif +#ifdef CLIPPLANE +else if (fClipDistance>0.0) +{discard;} +#endif +#ifdef CLIPPLANE2 +else if (fClipDistance2>0.0) +{discard;} +#endif +#ifdef CLIPPLANE3 +else if (fClipDistance3>0.0) +{discard;} +#endif +#ifdef CLIPPLANE4 +else if (fClipDistance4>0.0) +{discard;} +#endif +#ifdef CLIPPLANE5 +else if (fClipDistance5>0.0) +{discard;} +#endif +#ifdef CLIPPLANE6 +else if (fClipDistance6>0.0) +{discard;} +#endif +`;ShaderStore.IncludesShadersStore.clipPlaneFragment=iU;let ik=`vec2 uvOffset=vec2(0.0,0.0); +#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) +#ifdef NORMALXYSCALE +float normalScale=1.0; +#elif defined(BUMP) +float normalScale=vBumpInfos.y; +#else +float normalScale=1.0; +#endif +#if defined(TANGENT) && defined(NORMAL) +mat3 TBN=vTBN; +#elif defined(BUMP) +vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); +#else +vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); +#endif +#elif defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +mat3 TBN=vTBN; +#else +vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); +#endif +#endif +#ifdef PARALLAX +mat3 invTBN=transposeMat3(TBN); +#ifdef PARALLAXOCCLUSION +uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); +#else +uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); +#endif +#endif +#ifdef DETAIL +vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); +#endif +#ifdef BUMP +#ifdef OBJECTSPACE_NORMALMAP +#define CUSTOM_FRAGMENT_BUMP_FRAGMENT +normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); +#elif !defined(DETAIL) +normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); +#else +vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; +#if DETAIL_NORMALBLENDMETHOD==0 +detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); +#elif DETAIL_NORMALBLENDMETHOD==1 +detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; +#endif +normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); +#endif +#elif defined(DETAIL) +detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); +#endif +`;ShaderStore.IncludesShadersStore.bumpFragment=ik;let iG=`#ifdef DECAL +#ifdef GAMMADECAL +decalColor.rgb=toLinearSpace(decalColor.rgb); +#endif +#ifdef DECAL_SMOOTHALPHA +decalColor.a*=decalColor.a; +#endif +surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); +#endif +`;ShaderStore.IncludesShadersStore.decalFragment=iG;let iz=`#ifdef DEPTHPREPASS +gl_FragColor=vec4(0.,0.,0.,1.0);return; +#endif +`;ShaderStore.IncludesShadersStore.depthPrePass=iz;let iW=`#ifdef LIGHT{X} +#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) +#else +#ifdef PBR +#ifdef SPOTLIGHT{X} +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(POINTLIGHT{X}) +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(HEMILIGHT{X}) +preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(DIRLIGHT{X}) +preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#endif +preInfo.NdotV=NdotV; +#ifdef SPOTLIGHT{X} +#ifdef LIGHT_FALLOFF_GLTF{X} +preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); +#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) +preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); +#elif defined(LIGHT_FALLOFF_STANDARD{X}) +preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); +#else +preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); +#endif +#elif defined(POINTLIGHT{X}) +#ifdef LIGHT_FALLOFF_GLTF{X} +preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); +#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) +preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); +#elif defined(LIGHT_FALLOFF_STANDARD{X}) +preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); +#else +preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); +#endif +#else +preInfo.attenuation=1.0; +#endif +#ifdef HEMILIGHT{X} +preInfo.roughness=roughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +#ifdef IRIDESCENCE +preInfo.iridescenceIntensity=iridescenceIntensity; +#endif +#ifdef HEMILIGHT{X} +info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); +#elif defined(SS_TRANSLUCENCY) +info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); +#else +info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); +#endif +#ifdef SPECULARTERM +#ifdef ANISOTROPIC +info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#else +info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#endif +#endif +#ifdef SHEEN +#ifdef SHEEN_LINKWITHALBEDO +preInfo.roughness=sheenOut.sheenIntensity; +#else +#ifdef HEMILIGHT{X} +preInfo.roughness=sheenOut.sheenRoughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +#endif +info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#endif +#ifdef CLEARCOAT +#ifdef HEMILIGHT{X} +preInfo.roughness=clearcoatOut.clearCoatRoughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); +#ifdef CLEARCOAT_TINT +absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; +#ifdef SPECULARTERM +info.specular*=absorption; +#endif +#endif +info.diffuse*=info.clearCoat.w; +#ifdef SPECULARTERM +info.specular*=info.clearCoat.w; +#endif +#ifdef SHEEN +info.sheen*=info.clearCoat.w; +#endif +#endif +#else +#ifdef SPOTLIGHT{X} +info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); +#elif defined(HEMILIGHT{X}) +info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); +#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) +info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); +#endif +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X}); +#endif +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) +{ +#ifdef SHADOWCSM_RIGHTHANDED{X} +diff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z; +#else +diff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z; +#endif +if (diff{X}>=0.) {index{X}=i;break;}} +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +if (index{X}>=0) +#endif +{ +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#else +shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#endif +#else +shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; +#endif +#ifndef SHADOWCSMNOBLEND{X} +float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) +{index{X}+=1;float nextShadow=0.; +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#else +nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#endif +#else +nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +shadow=mix(nextShadow,shadow,diffRatio); +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); +#endif +} +#endif +} +#elif defined(SHADOWCLOSEESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPOISSON{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#else +#if defined(SHADOWCUBE{X}) +shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#endif +#ifdef SHADOWONLY +#ifndef SHADOWINUSE +#define SHADOWINUSE +#endif +globalShadow+=shadow;shadowLightCount+=1.0; +#endif +#else +shadow=1.; +#endif +aggShadow+=shadow;numLights+=1.0; +#ifndef SHADOWONLY +#ifdef CUSTOMUSERLIGHTING +diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); +#ifdef SPECULARTERM +specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); +#endif +#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) +diffuseBase+=lightmapColor.rgb*shadow; +#ifdef SPECULARTERM +#ifndef LIGHTMAPNOSPECULAR{X} +specularBase+=info.specular*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef CLEARCOAT +#ifndef LIGHTMAPNOSPECULAR{X} +clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef SHEEN +#ifndef LIGHTMAPNOSPECULAR{X} +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#else +#ifdef SHADOWCSMDEBUG{X} +diffuseBase+=info.diffuse*shadowDebug{X}; +#else +diffuseBase+=info.diffuse*shadow; +#endif +#ifdef SPECULARTERM +specularBase+=info.specular*shadow; +#endif +#ifdef CLEARCOAT +clearCoatBase+=info.clearCoat.rgb*shadow; +#endif +#ifdef SHEEN +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStore.lightFragment=iW;let iH=`#ifdef LOGARITHMICDEPTH +gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; +#endif +`;ShaderStore.IncludesShadersStore.logDepthFragment=iH;let iX=`#ifdef FOG +float fog=CalcFogFactor(); +#ifdef PBR +fog=toLinearSpace(fog); +#endif +color.rgb=mix(vFogColor,color.rgb,fog); +#endif +`;ShaderStore.IncludesShadersStore.fogFragment=iX;let iY=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +float fragDepth=gl_FragCoord.z; +#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS +uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; +#endif +ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); +#ifdef USE_REVERSE_DEPTHBUFFER +float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; +#else +float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; +#endif +float alphaMultiplier=1.0-lastFrontColor.a; +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepth>nearestDepth || fragDepth<furthestDepth) { +#else +if (fragDepth<nearestDepth || fragDepth>furthestDepth) { +#endif +return;} +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepth<nearestDepth && fragDepth>furthestDepth) { +#else +if (fragDepth>nearestDepth && fragDepth<furthestDepth) { +#endif +depth.rg=vec2(-fragDepth,fragDepth);return;} +#endif +`;ShaderStore.IncludesShadersStore.oitFragment=iY;let ij=`#include<__decl__defaultFragment> +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +#include<prePassDeclaration>[SCENE_MRT_COUNT] +#include<oitDeclaration> +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include<mainUVVaryingDeclaration>[1..7] +#include<helperFunctions> +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include<lightsFragmentFunctions> +#include<shadowsFragmentFunctions> +#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) +#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef REFRACTION +#ifdef REFRACTIONMAP_3D +uniform samplerCube refractionCubeSampler; +#else +uniform sampler2D refraction2DSampler; +#endif +#endif +#if defined(SPECULARTERM) +#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) +#endif +#include<fresnelFunction> +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +uniform samplerCube reflectionCubeSampler; +#else +uniform sampler2D reflection2DSampler; +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include<reflectionFunction> +#endif +#include<imageProcessingDeclaration> +#include<imageProcessingFunctions> +#include<bumpFragmentMainFunctions> +#include<bumpFragmentFunctions> +#include<clipPlaneFragmentDeclaration> +#include<logDepthDeclaration> +#include<fogFragmentDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); +#endif +#include<bumpFragment> +#ifdef TWOSIDEDLIGHTING +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +#ifdef DIFFUSE +baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); +#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) +if (baseColor.a<alphaCutOff) +discard; +#endif +#ifdef ALPHAFROMDIFFUSE +alpha*=baseColor.a; +#endif +#define CUSTOM_FRAGMENT_UPDATE_ALPHA +baseColor.rgb*=vDiffuseInfos.y; +#endif +#if defined(DECAL) && !defined(DECAL_AFTER_DETAIL) +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#include<depthPrePass> +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor.rgb*=vColor.rgb; +#endif +#ifdef DETAIL +baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); +#endif +#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE +vec3 baseAmbientColor=vec3(1.,1.,1.); +#ifdef AMBIENT +baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; +#endif +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +#ifdef SPECULARTERM +float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; +#ifdef SPECULAR +vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; +#ifdef GLOSSINESS +glossiness=glossiness*specularMapColor.a; +#endif +#endif +#else +float glossiness=0.; +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +float shadow=1.;float aggShadow=0.;float numLights=0.; +#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +#include<lightFragment>[0..maxSimultaneousLights] +aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); +#ifdef REFRACTION +vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); +#ifdef REFRACTIONMAP_3D +#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); +#endif +#ifdef RGBDREFRACTION +refractionColor.rgb=fromRGBD(refractionColor); +#endif +#ifdef IS_REFRACTION_LINEAR +refractionColor.rgb=toGammaSpace(refractionColor.rgb); +#endif +refractionColor.rgb*=vRefractionInfos.x; +#endif +vec4 reflectionColor=vec4(0.,0.,0.,1.); +#ifdef REFLECTION +vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +vReflectionUVW.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +#ifdef ROUGHNESS +float bias=vReflectionInfos.y; +#ifdef SPECULARTERM +#ifdef SPECULAR +#ifdef GLOSSINESS +bias*=(1.0-specularMapColor.a); +#endif +#endif +#endif +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); +#else +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); +#endif +#else +vec2 coords=vReflectionUVW.xy; +#ifdef REFLECTIONMAP_PROJECTION +coords/=vReflectionUVW.z; +#endif +coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef IS_REFLECTION_LINEAR +reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#ifdef REFLECTIONFRESNEL +float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); +#ifdef REFLECTIONFRESNELFROMSPECULAR +#ifdef SPECULARTERM +reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#endif +#endif +#ifdef REFRACTIONFRESNEL +float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#ifdef OPACITYRGB +opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; +#else +alpha*=opacityMap.a*vOpacityInfos.y; +#endif +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef OPACITYFRESNEL +float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; +#endif +#ifdef ALPHATEST +#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS +if (alpha<alphaCutOff) +discard; +#endif +#ifndef ALPHABLEND +alpha=1.0; +#endif +#endif +vec3 emissiveColor=vEmissiveColor; +#ifdef EMISSIVE +emissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y; +#endif +#ifdef EMISSIVEFRESNEL +float emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb; +#endif +#ifdef DIFFUSEFRESNEL +float diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);diffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb; +#endif +#ifdef EMISSIVEASILLUMINATION +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb; +#else +#ifdef LINKEMISSIVEWITHDIFFUSE +vec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb; +#else +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb; +#endif +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase*specularColor; +#ifdef SPECULAROVERALPHA +alpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.); +#endif +#else +vec3 finalSpecular=vec3(0.0); +#endif +#ifdef REFLECTIONOVERALPHA +alpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.); +#endif +#ifdef EMISSIVEASILLUMINATION +vec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha); +#else +vec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha); +#endif +#ifdef LIGHTMAP +#ifndef LIGHTMAPEXCLUDED +#ifdef USELIGHTMAPASSHADOWMAP +color.rgb*=lightmapColor.rgb; +#else +color.rgb+=lightmapColor.rgb; +#endif +#endif +#endif +#define CUSTOM_FRAGMENT_BEFORE_FOG +color.rgb=max(color.rgb,0.); +#include<logDepthFragment> +#include<fogFragment> +#ifdef IMAGEPROCESSINGPOSTPROCESS +color.rgb=toLinearSpace(color.rgb); +#else +#ifdef IMAGEPROCESSING +color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); +#endif +#endif +color.a*=visibility; +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_IRRADIANCE +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#if defined(SPECULARTERM) +#if defined(SPECULAR) +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; +#endif +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=color; +#endif +#include<oitFragment> +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} +#endif +#define CUSTOM_FRAGMENT_MAIN_END +} +`;ShaderStore.ShadersStore.defaultPixelShader=ij;let iK=`#ifdef DECAL +uniform vec4 vDecalInfos;uniform mat4 decalMatrix; +#endif +`;ShaderStore.IncludesShadersStore.decalVertexDeclaration=iK;let iq=`uniform mat4 viewProjection;uniform mat4 view; +#ifdef DIFFUSE +uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef AMBIENT +uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; +#endif +#ifdef OPACITY +uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; +#endif +#if defined(SPECULAR) && defined(SPECULARTERM) +uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; +#endif +#ifdef REFLECTION +uniform mat4 reflectionMatrix; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos;uniform mat4 detailMatrix; +#endif +#include<decalVertexDeclaration> +#define ADDITIONAL_VERTEX_DECLARATION +`;ShaderStore.IncludesShadersStore.defaultVertexDeclaration=iq;let i$=`#ifdef UV{X} +attribute vec2 uv{X}; +#endif +`;ShaderStore.IncludesShadersStore.uvAttributeDeclaration=i$;let iQ=`#if NUM_BONE_INFLUENCERS>0 +attribute vec4 matricesIndices;attribute vec4 matricesWeights; +#if NUM_BONE_INFLUENCERS>4 +attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; +#endif +#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#ifdef BONETEXTURE +uniform highp sampler2D boneSampler;uniform float boneTextureWidth; +#else +uniform mat4 mBones[BonesPerMesh]; +#ifdef BONES_VELOCITY_ENABLED +uniform mat4 mPreviousBones[BonesPerMesh]; +#endif +#endif +#ifdef BONETEXTURE +#define inline +mat4 readMatrixFromRawSampler(sampler2D smp,float index) +{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStore.bonesDeclaration=iQ;let iZ=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; +#ifdef INSTANCES +attribute vec4 bakedVertexAnimationSettingsInstanced; +#endif +#define inline +mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) +{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} +#endif +`;ShaderStore.IncludesShadersStore.bakedVertexAnimationDeclaration=iZ;let iJ=`#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#ifdef INSTANCESCOLOR +attribute vec4 instanceColor; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; +#ifdef THIN_INSTANCES +uniform mat4 previousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +uniform mat4 previousWorld; +#endif +#endif +`;ShaderStore.IncludesShadersStore.instancesDeclaration=iJ;let i0=`#ifdef PREPASS +#ifdef PREPASS_DEPTH +varying vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#endif +`;ShaderStore.IncludesShadersStore.prePassVertexDeclaration=i0;let i1=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +varying vec2 v_VARYINGNAME_UV; +#endif +`;ShaderStore.IncludesShadersStore.samplerVertexDeclaration=i1;let i2=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +varying mat3 vTBN; +#endif +#endif +`;ShaderStore.IncludesShadersStore.bumpVertexDeclaration=i2;let i3=`#ifdef CLIPPLANE +uniform vec4 vClipPlane;varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;varying float fClipDistance6; +#endif +`;ShaderStore.IncludesShadersStore.clipPlaneVertexDeclaration=i3;let i4=`#ifdef FOG +varying vec3 vFogDistance; +#endif +`;ShaderStore.IncludesShadersStore.fogVertexDeclaration=i4;let i5=`#ifdef LIGHT{X} +uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; +#ifdef SPECULARTERM +uniform vec4 vLightSpecular{X}; +#else +vec4 vLightSpecular{X}=vec4(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#elif defined(SHADOWCUBE{X}) +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; +#endif +uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; +#endif +#ifdef SPOTLIGHT{X} +uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; +#elif defined(POINTLIGHT{X}) +uniform vec4 vLightFalloff{X}; +#elif defined(HEMILIGHT{X}) +uniform vec3 vLightGround{X}; +#endif +#endif +`;ShaderStore.IncludesShadersStore.lightVxFragmentDeclaration=i5;let i6=`#ifdef LIGHT{X} +uniform Light{X} +{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; +#ifdef SPOTLIGHT{X} +vec4 vLightDirection;vec4 vLightFalloff; +#elif defined(POINTLIGHT{X}) +vec4 vLightFalloff; +#elif defined(HEMILIGHT{X}) +vec3 vLightGround; +#endif +vec4 shadowsInfo;vec2 depthValues;} light{X}; +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#elif defined(SHADOWCUBE{X}) +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStore.lightVxUboDeclaration=i6;let i8=`#ifdef MORPHTARGETS +uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; +#ifdef MORPHTARGETS_TEXTURE +uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) +{ +float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} +#endif +#endif +`;ShaderStore.IncludesShadersStore.morphTargetsVertexGlobalDeclaration=i8;let i7=`#ifdef MORPHTARGETS +#ifndef MORPHTARGETS_TEXTURE +attribute vec3 position{X}; +#ifdef MORPHTARGETS_NORMAL +attribute vec3 normal{X}; +#endif +#ifdef MORPHTARGETS_TANGENT +attribute vec3 tangent{X}; +#endif +#ifdef MORPHTARGETS_UV +attribute vec2 uv_{X}; +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStore.morphTargetsVertexDeclaration=i7;let i9=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +float vertexID; +#endif +#endif +`;ShaderStore.IncludesShadersStore.morphTargetsVertexGlobal=i9;let re=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];vertexID+=1.0; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}]; +#endif +#else +positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStore.morphTargetsVertex=re;let rt=`#ifdef INSTANCES +mat4 finalWorld=mat4(world0,world1,world2,world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +finalWorld=world*finalWorld; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +mat4 finalWorld=world; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +mat4 finalPreviousWorld=previousWorld; +#endif +#endif +`;ShaderStore.IncludesShadersStore.instancesVertex=rt;let ri=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#if NUM_BONE_INFLUENCERS>0 +mat4 influence; +#ifdef BONETEXTURE +influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; +#endif +#else +influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#endif +`;ShaderStore.IncludesShadersStore.bonesVertex=ri;let rr=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +{ +#ifdef INSTANCES +#define BVASNAME bakedVertexAnimationSettingsInstanced +#else +#define BVASNAME bakedVertexAnimationSettings +#endif +float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; +#endif +finalWorld=finalWorld*VATInfluence;} +#endif +`;ShaderStore.IncludesShadersStore.bakedVertexAnimation=rr;let rs=`#ifdef PREPASS_DEPTH +vViewPos=(view*worldPos).rgb; +#endif +#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*worldPos; +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +`;ShaderStore.IncludesShadersStore.prePassVertex=rs;let ra=`#if !defined(UV{X}) && defined(MAINUV{X}) +vec2 uv{X}=vec2(0.,0.); +#endif +#ifdef MAINUV{X} +vMainUV{X}=uv{X}; +#endif +`;ShaderStore.IncludesShadersStore.uvVariableDeclaration=ra;let rn=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +if (v_INFONAME_==0.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} +#ifdef UV2 +else if (v_INFONAME_==1.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));} +#endif +#ifdef UV3 +else if (v_INFONAME_==2.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} +#endif +#ifdef UV4 +else if (v_INFONAME_==3.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} +#endif +#ifdef UV5 +else if (v_INFONAME_==4.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} +#endif +#ifdef UV6 +else if (v_INFONAME_==5.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} +#endif +#endif +`;ShaderStore.IncludesShadersStore.samplerVertexImplementation=rn;let ro=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); +#endif +#endif +`;ShaderStore.IncludesShadersStore.bumpVertex=ro;let rl=`#ifdef CLIPPLANE +fClipDistance=dot(worldPos,vClipPlane); +#endif +#ifdef CLIPPLANE2 +fClipDistance2=dot(worldPos,vClipPlane2); +#endif +#ifdef CLIPPLANE3 +fClipDistance3=dot(worldPos,vClipPlane3); +#endif +#ifdef CLIPPLANE4 +fClipDistance4=dot(worldPos,vClipPlane4); +#endif +#ifdef CLIPPLANE5 +fClipDistance5=dot(worldPos,vClipPlane5); +#endif +#ifdef CLIPPLANE6 +fClipDistance6=dot(worldPos,vClipPlane6); +#endif +`;ShaderStore.IncludesShadersStore.clipPlaneVertex=rl;let rh=`#ifdef FOG +vFogDistance=(view*worldPos).xyz; +#endif +`;ShaderStore.IncludesShadersStore.fogVertex=rh;let rc=`#ifdef SHADOWS +#if defined(SHADOWCSM{X}) +vPositionFromCamera{X}=view*worldPos;for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos; +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y; +#else +vDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y; +#endif +} +#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X}) +vPositionFromLight{X}=lightMatrix{X}*worldPos; +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#else +vDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStore.shadowsVertex=rc;let ru=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +vColor=vec4(1.0); +#ifdef VERTEXCOLOR +#ifdef VERTEXALPHA +vColor*=color; +#else +vColor.rgb*=color.rgb; +#endif +#endif +#ifdef INSTANCESCOLOR +vColor*=instanceColor; +#endif +#endif +`;ShaderStore.IncludesShadersStore.vertexColorMixing=ru;let rd=`#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +`;ShaderStore.IncludesShadersStore.pointCloudVertex=rd;let r_=`#ifdef LOGARITHMICDEPTH +vFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant; +#endif +`;ShaderStore.IncludesShadersStore.logDepthVertex=r_;let rp=`#include<__decl__defaultVertex> +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include<uvAttributeDeclaration>[2..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include<helperFunctions> +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<instancesDeclaration> +#include<prePassVertexDeclaration> +#include<mainUVVaryingDeclaration>[1..7] +#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) +#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#if defined(SPECULARTERM) +#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) +#endif +#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include<bumpVertexDeclaration> +#include<clipPlaneVertexDeclaration> +#include<fogVertexDeclaration> +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include<logDepthDeclaration> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include<instancesVertex> +#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +vPositionW=vec3(worldPos); +#include<prePassVertex> +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#include<uvVariableDeclaration>[2..7] +#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#if defined(SPECULARTERM) +#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) +#endif +#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#include<bumpVertex> +#include<clipPlaneVertex> +#include<fogVertex> +#include<shadowsVertex>[0..maxSimultaneousLights] +#include<vertexColorMixing> +#include<pointCloudVertex> +#include<logDepthVertex> +#define CUSTOM_VERTEX_MAIN_END +} +`;ShaderStore.ShadersStore.defaultVertexShader=rp;let rf=RegExp("^([gimus]+)!");let MaterialPluginManager=class MaterialPluginManager{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e.name)return!1;if(this._material._uniformBufferLayoutBuilt)throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because this material has already been used for rendering! Please add plugins to materials before any rendering with this material occurs.`;let t=e.getClassName();MaterialPluginManager._MaterialPluginClassToMainDefine[t]||(MaterialPluginManager._MaterialPluginClassToMainDefine[t]="MATERIALPLUGIN_"+ ++MaterialPluginManager._MaterialPluginCounter),this._material._callbackPluginEventGeneric=(e,t)=>this._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort((e,t)=>e.priority-t.priority),this._codeInjectionPoints={};let i={};for(let e of(i[MaterialPluginManager._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0},this._plugins))e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.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;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null}_handlePluginEventIsReadyForSubMesh(e){let t=!0;for(let i of this._activePlugins)t=t&&i.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh);e.isReadyForSubMesh=t}_handlePluginEventPrepareDefinesBeforeAttributes(e){for(let t of this._activePlugins)t.prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)}_handlePluginEventPrepareDefines(e){for(let t of this._activePlugins)t.prepareDefines(e.defines,this._scene,e.mesh)}_handlePluginEventHardBindForSubMesh(e){for(let t of this._activePluginsForExtraEvents)t.hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventBindForSubMesh(e){for(let t of this._activePlugins)t.bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventHasRenderTargetTextures(e){let t=!1;for(let e of this._activePluginsForExtraEvents)if(t=e.hasRenderTargetTextures())break;e.hasRenderTargetTextures=t}_handlePluginEventFillRenderTargetTextures(e){for(let t of this._activePluginsForExtraEvents)t.fillRenderTargetTextures(e.renderTargets)}_handlePluginEvent(e,t){var i;switch(e){case ec.GetActiveTextures:for(let e of this._activePlugins)e.getActiveTextures(t.activeTextures);break;case ec.GetAnimatables:for(let e of this._activePlugins)e.getAnimatables(t.animatables);break;case ec.HasTexture:{let e=!1;for(let i of this._activePlugins)if(e=i.hasTexture(t.texture))break;t.hasTexture=e;break}case ec.Disposed:for(let e of this._plugins)e.dispose(t.forceDisposeTextures);break;case ec.GetDefineNames:t.defineNames=this._defineNamesFromPlugins;break;case ec.PrepareEffect:for(let e of this._activePlugins)t.fallbackRank=e.addFallbacks(t.defines,t.fallbacks,t.fallbackRank),e.getAttributes(t.attributes,this._scene,t.mesh);this._uniformList.length>0&&t.uniforms.push(...this._uniformList),this._samplerList.length>0&&t.samplers.push(...this._samplerList),this._uboList.length>0&&t.uniformBuffersNames.push(...this._uboList),t.customCode=this._injectCustomCode(t,t.customCode);break;case ec.PrepareUniformBuffer:for(let e of(this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[],this._plugins)){let r=e.getUniforms();if(r){if(r.ubo)for(let e of r.ubo){if(e.size&&e.type){let r=null!==(i=e.arraySize)&&void 0!==i?i:0;t.ubo.addUniform(e.name,e.size,r),this._uboDeclaration+=`${e.type} ${e.name}${r>0?`[${r}]`:""}; +`}this._uniformList.push(e.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\n")}e.getSamplers(this._samplerList),e.getUniformBuffersNames(this._uboList)}}}_collectPointNames(e,t){if(t)for(let i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var s,a;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));let n=null===(s=this._codeInjectionPoints)||void 0===s?void 0:s[i];if(!n)return r;let o=null;for(let t in n){let s="";for(let r of this._activePlugins){let n=null===(a=r.getCustomCode(i))||void 0===a?void 0:a[t];if(n){if(r.resolveIncludes){if(null===o){let t=q.GLSL;o={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:ShaderStore.GetShadersRepository(t),includesShadersStore:ShaderStore.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}o.isFragment="fragment"===i,ShaderProcessor._ProcessIncludes(n,o,e=>n=e)}s+=n+"\n"}}if(s.length>0){if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{let i=rf.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}0>e.indexOf("g")&&(e+="g");let i=r,a=new RegExp(t,e),n=a.exec(i);for(;null!==n;){let e=s;for(let t=0;t<n.length;++t)e=e.replace("$"+t,n[t]);r=r.replace(n[0],e),n=a.exec(i)}}else{let e="#define "+t;r=r.replace(e,"\n"+s+"\n"+e)}}}return r}}};MaterialPluginManager._MaterialPluginClassToMainDefine={},MaterialPluginManager._MaterialPluginCounter=0,engineStore_EngineStore.OnEnginesDisposedObservable.add(()=>{UnregisterAllMaterialPlugins()});let rm=[],rg=null;function UnregisterAllMaterialPlugins(){rm.length=0,material_Material.OnEventObservable.remove(rg),rg=null}let MaterialPluginBase=class MaterialPluginBase{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,r,s=!0,a=!1,n=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=n,e.pluginManager||(e.pluginManager=new MaterialPluginManager(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),a&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(let t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;let 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){decorators_SerializationHelper.Clone(()=>e,this)}serialize(){return decorators_SerializationHelper.Serialize(this)}parse(e,t,i){decorators_SerializationHelper.Parse(()=>this,e,t,i)}};__decorate([serialize()],MaterialPluginBase.prototype,"name",void 0),__decorate([serialize()],MaterialPluginBase.prototype,"priority",void 0),__decorate([serialize()],MaterialPluginBase.prototype,"resolveIncludes",void 0),__decorate([serialize()],MaterialPluginBase.prototype,"registerForExtraEvents",void 0);let MaterialDetailMapDefines=class MaterialDetailMapDefines extends MaterialDefines{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}};let material_detailMapConfiguration_DetailMapConfiguration=class material_detailMapConfiguration_DetailMapConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new MaterialDetailMapDefines,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=material_Material.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||!MaterialFlags.DetailTextureEnabled||!!this._texture.isReady()}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;let i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&MaterialFlags.DetailTextureEnabled&&this._isEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||!this._texture||!MaterialFlags.DetailTextureEnabled||(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),MaterialHelper.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&MaterialFlags.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"}]}}};__decorate([serializeAsTexture("detailTexture"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"texture",void 0),__decorate([serialize()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"diffuseBlendLevel",void 0),__decorate([serialize()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"roughnessBlendLevel",void 0),__decorate([serialize()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"bumpLevel",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"normalBlendMethod",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"isEnabled",void 0);let rv={effect:null,subMesh:null};let StandardMaterialDefines=class StandardMaterialDefines extends MaterialDefines{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!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.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){for(let t of["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"])this[t]=t===e}};let standardMaterial_StandardMaterial=class standardMaterial_StandardMaterial extends PushMaterial{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new math_color_Color3(0,0,0),this.diffuseColor=new math_color_Color3(1,1,1),this.specularColor=new math_color_Color3(1,1,1),this.emissiveColor=new math_color_Color3(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new SmartArray(16),this._worldViewProjectionMatrix=math_vector_Matrix.Zero(),this._globalAmbientColor=new math_color_Color3(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new material_detailMapConfiguration_DetailMapConfiguration(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new PrePassConfiguration,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),standardMaterial_StandardMaterial.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),standardMaterial_StandardMaterial.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!!standardMaterial_StandardMaterial.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||!!standardMaterial_StandardMaterial.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===material_Material.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==material_Material.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(ec.GetDefineNames,this._eventInfo),t.materialDefines=new StandardMaterialDefines(this._eventInfo.defineNames));let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=r.getEngine();s._needNormals=MaterialHelper.PrepareDefinesForLights(r,e,s,!0,this._maxSimultaneousLights,this._disableLighting),MaterialHelper.PrepareDefinesForMultiview(r,s);let n=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(MaterialHelper.PrepareDefinesForPrePass(r,s,this.canRenderToMRT&&!n),MaterialHelper.PrepareDefinesForOIT(r,s,n),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(r.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&&standardMaterial_StandardMaterial.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&standardMaterial_StandardMaterial.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===texture_Texture.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 texture_Texture.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case texture_Texture.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case texture_Texture.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case texture_Texture.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case texture_Texture.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case texture_Texture.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case texture_Texture.CUBIC_MODE:case texture_Texture.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&&standardMaterial_StandardMaterial.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&standardMaterial_StandardMaterial.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,s,"BUMP"),s.PARALLAX=this._useParallax,s.PARALLAX_RHS=r.useRightHandedSystem,s.PARALLAXOCCLUSION=this._useParallaxOcclusion,s.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else s.BUMP=!1,s.PARALLAX=!1,s.PARALLAX_RHS=!1,s.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&standardMaterial_StandardMaterial.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&&(standardMaterial_StandardMaterial.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),MaterialHelper.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s,this._applyDecalMapAfterDetailMap),MaterialHelper.PrepareDefinesForFrameBoundValues(r,a,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),MaterialHelper.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let o=!1;if(s.isDirty){let i=s._areLightsDisposed;s.markAsProcessed();let n=new EffectFallbacks;s.REFLECTION&&n.addFallback(0,"REFLECTION"),s.SPECULAR&&n.addFallback(0,"SPECULAR"),s.BUMP&&n.addFallback(0,"BUMP"),s.PARALLAX&&n.addFallback(1,"PARALLAX"),s.PARALLAX_RHS&&n.addFallback(1,"PARALLAX_RHS"),s.PARALLAXOCCLUSION&&n.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&n.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&n.addFallback(1,"FOG"),s.POINTSIZE&&n.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&n.addFallback(0,"LOGARITHMICDEPTH"),MaterialHelper.HandleFallbacksForShadows(s,n,this._maxSimultaneousLights),s.SPECULARTERM&&n.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&n.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&n.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&n.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&n.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&n.addFallback(4,"FRESNEL"),s.MULTIVIEW&&n.addFallback(0,"MULTIVIEW");let l=[buffer_VertexBuffer.PositionKind];s.NORMAL&&l.push(buffer_VertexBuffer.NormalKind),s.TANGENT&&l.push(buffer_VertexBuffer.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(buffer_VertexBuffer.ColorKind),MaterialHelper.PrepareAttributesForBones(l,e,s,n),MaterialHelper.PrepareAttributesForInstances(l,s),MaterialHelper.PrepareAttributesForMorphTargets(l,e,s),MaterialHelper.PrepareAttributesForBakedVertexAnimation(l,e,s);let h="default",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"],u=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=n,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=c,this._eventInfo.attributes=l,this._eventInfo.samplers=u,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(ec.PrepareEffect,this._eventInfo),PrePassConfiguration.AddUniforms(c),PrePassConfiguration.AddSamplers(u),ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(c,s),ImageProcessingConfiguration.PrepareSamplers(u,s)),MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),addClipPlaneUniforms(c);let p={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,d,u,s,l,p));let f=s.toString(),m=t.effect,g=r.getEngine().createEffect(h,{attributes:l,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:f,fallbacks:n,onCompiled:this.onCompiled,onError:this.onError,indexParameters:_,processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},a);if(this._eventInfo.customCode=void 0,g){if(this._onEffectCreatedObservable&&(rv.effect=g,rv.subMesh=t,this._onEffectCreatedObservable.notifyObservers(rv)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,s.markAsUnprocessed(),o=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!o,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let 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 r;let s=this.getScene(),a=i.materialDefines;if(!a)return;let n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),a.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let o=n._forceRebindOnNextCall||this._mustRebind(s,n,t.visibility);MaterialHelper.BindBonesParameters(t,n);let l=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!l.useUbo||!this.isFrozen||!l.isSync||n._forceRebindOnNextCall){if(standardMaterial_StandardMaterial.FresnelEnabled&&a.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new math_color_Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&standardMaterial_StandardMaterial.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),MaterialHelper.BindTextureMatrix(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),MaterialHelper.BindTextureMatrix(this._ambientTexture,l,"ambient")),this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),MaterialHelper.BindTextureMatrix(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&standardMaterial_StandardMaterial.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){let e=this._reflectionTexture;l.updateVector3("vReflectionPosition",e.boundingBoxPosition),l.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&standardMaterial_StandardMaterial.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),MaterialHelper.BindTextureMatrix(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),MaterialHelper.BindTextureMatrix(this._lightmapTexture,l,"lightmap")),this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),MaterialHelper.BindTextureMatrix(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&standardMaterial_StandardMaterial.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),MaterialHelper.BindTextureMatrix(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&standardMaterial_StandardMaterial.RefractionTextureEnabled){let e=1;if(!this._refractionTexture.isCube&&(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){let e=this._refractionTexture;l.updateVector3("vRefractionPosition",e.boundingBoxPosition),l.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),a.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",standardMaterial_StandardMaterial.EmissiveTextureEnabled?this.emissiveColor:math_color_Color3.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&standardMaterial_StandardMaterial.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&standardMaterial_StandardMaterial.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&standardMaterial_StandardMaterial.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&standardMaterial_StandardMaterial.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&standardMaterial_StandardMaterial.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),bindClipPlane(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&MaterialHelper.BindLights(s,t,n,a,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==scene_Scene.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||a.PREPASS)&&this.bindView(n),MaterialHelper.BindFogParameters(s,t,n),a.NUM_MORPH_INFLUENCERS&&MaterialHelper.BindMorphTargetParameters(t,n),a.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(r=t.bakedVertexAnimationManager)||void 0===r||r.bind(n,a.INSTANCES)),this.useLogarithmicDepth&&MaterialHelper.BindLogDepth(a,n,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),l.update()}getAnimatables(){let 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(){let 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,r,s,a,n,o,l,h,c;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(a=this._reflectionTexture)||void 0===a||a.dispose(),null===(n=this._emissiveTexture)||void 0===n||n.dispose(),null===(o=this._specularTexture)||void 0===o||o.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=""){let r=decorators_SerializationHelper.Clone(()=>new standardMaterial_StandardMaterial(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>new standardMaterial_StandardMaterial(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),material_Material._parsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return MaterialFlags.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){MaterialFlags.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return MaterialFlags.DetailTextureEnabled}static set DetailTextureEnabled(e){MaterialFlags.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return MaterialFlags.AmbientTextureEnabled}static set AmbientTextureEnabled(e){MaterialFlags.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return MaterialFlags.OpacityTextureEnabled}static set OpacityTextureEnabled(e){MaterialFlags.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return MaterialFlags.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){MaterialFlags.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return MaterialFlags.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){MaterialFlags.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return MaterialFlags.SpecularTextureEnabled}static set SpecularTextureEnabled(e){MaterialFlags.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return MaterialFlags.BumpTextureEnabled}static set BumpTextureEnabled(e){MaterialFlags.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return MaterialFlags.LightmapTextureEnabled}static set LightmapTextureEnabled(e){MaterialFlags.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return MaterialFlags.RefractionTextureEnabled}static set RefractionTextureEnabled(e){MaterialFlags.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return MaterialFlags.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){MaterialFlags.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return MaterialFlags.FresnelEnabled}static set FresnelEnabled(e){MaterialFlags.FresnelEnabled=e}};__decorate([serializeAsTexture("diffuseTexture")],standardMaterial_StandardMaterial.prototype,"_diffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"diffuseTexture",void 0),__decorate([serializeAsTexture("ambientTexture")],standardMaterial_StandardMaterial.prototype,"_ambientTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"ambientTexture",void 0),__decorate([serializeAsTexture("opacityTexture")],standardMaterial_StandardMaterial.prototype,"_opacityTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"opacityTexture",void 0),__decorate([serializeAsTexture("reflectionTexture")],standardMaterial_StandardMaterial.prototype,"_reflectionTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"reflectionTexture",void 0),__decorate([serializeAsTexture("emissiveTexture")],standardMaterial_StandardMaterial.prototype,"_emissiveTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"emissiveTexture",void 0),__decorate([serializeAsTexture("specularTexture")],standardMaterial_StandardMaterial.prototype,"_specularTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"specularTexture",void 0),__decorate([serializeAsTexture("bumpTexture")],standardMaterial_StandardMaterial.prototype,"_bumpTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"bumpTexture",void 0),__decorate([serializeAsTexture("lightmapTexture")],standardMaterial_StandardMaterial.prototype,"_lightmapTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"lightmapTexture",void 0),__decorate([serializeAsTexture("refractionTexture")],standardMaterial_StandardMaterial.prototype,"_refractionTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"refractionTexture",void 0),__decorate([serializeAsColor3("ambient")],standardMaterial_StandardMaterial.prototype,"ambientColor",void 0),__decorate([serializeAsColor3("diffuse")],standardMaterial_StandardMaterial.prototype,"diffuseColor",void 0),__decorate([serializeAsColor3("specular")],standardMaterial_StandardMaterial.prototype,"specularColor",void 0),__decorate([serializeAsColor3("emissive")],standardMaterial_StandardMaterial.prototype,"emissiveColor",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"specularPower",void 0),__decorate([serialize("useAlphaFromDiffuseTexture")],standardMaterial_StandardMaterial.prototype,"_useAlphaFromDiffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"useAlphaFromDiffuseTexture",void 0),__decorate([serialize("useEmissiveAsIllumination")],standardMaterial_StandardMaterial.prototype,"_useEmissiveAsIllumination",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useEmissiveAsIllumination",void 0),__decorate([serialize("linkEmissiveWithDiffuse")],standardMaterial_StandardMaterial.prototype,"_linkEmissiveWithDiffuse",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"linkEmissiveWithDiffuse",void 0),__decorate([serialize("useSpecularOverAlpha")],standardMaterial_StandardMaterial.prototype,"_useSpecularOverAlpha",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useSpecularOverAlpha",void 0),__decorate([serialize("useReflectionOverAlpha")],standardMaterial_StandardMaterial.prototype,"_useReflectionOverAlpha",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useReflectionOverAlpha",void 0),__decorate([serialize("disableLighting")],standardMaterial_StandardMaterial.prototype,"_disableLighting",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],standardMaterial_StandardMaterial.prototype,"disableLighting",void 0),__decorate([serialize("useObjectSpaceNormalMap")],standardMaterial_StandardMaterial.prototype,"_useObjectSpaceNormalMap",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useObjectSpaceNormalMap",void 0),__decorate([serialize("useParallax")],standardMaterial_StandardMaterial.prototype,"_useParallax",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useParallax",void 0),__decorate([serialize("useParallaxOcclusion")],standardMaterial_StandardMaterial.prototype,"_useParallaxOcclusion",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useParallaxOcclusion",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"parallaxScaleBias",void 0),__decorate([serialize("roughness")],standardMaterial_StandardMaterial.prototype,"_roughness",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"roughness",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"indexOfRefraction",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"invertRefractionY",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"alphaCutOff",void 0),__decorate([serialize("useLightmapAsShadowmap")],standardMaterial_StandardMaterial.prototype,"_useLightmapAsShadowmap",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useLightmapAsShadowmap",void 0),__decorate([serializeAsFresnelParameters("diffuseFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_diffuseFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"diffuseFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("opacityFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_opacityFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"opacityFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("reflectionFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_reflectionFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"reflectionFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("refractionFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_refractionFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"refractionFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("emissiveFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_emissiveFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"emissiveFresnelParameters",void 0),__decorate([serialize("useReflectionFresnelFromSpecular")],standardMaterial_StandardMaterial.prototype,"_useReflectionFresnelFromSpecular",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"useReflectionFresnelFromSpecular",void 0),__decorate([serialize("useGlossinessFromSpecularMapAlpha")],standardMaterial_StandardMaterial.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useGlossinessFromSpecularMapAlpha",void 0),__decorate([serialize("maxSimultaneousLights")],standardMaterial_StandardMaterial.prototype,"_maxSimultaneousLights",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],standardMaterial_StandardMaterial.prototype,"maxSimultaneousLights",void 0),__decorate([serialize("invertNormalMapX")],standardMaterial_StandardMaterial.prototype,"_invertNormalMapX",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"invertNormalMapX",void 0),__decorate([serialize("invertNormalMapY")],standardMaterial_StandardMaterial.prototype,"_invertNormalMapY",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"invertNormalMapY",void 0),__decorate([serialize("twoSidedLighting")],standardMaterial_StandardMaterial.prototype,"_twoSidedLighting",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"twoSidedLighting",void 0),__decorate([serialize("applyDecalMapAfterDetailMap")],standardMaterial_StandardMaterial.prototype,"_applyDecalMapAfterDetailMap",void 0),__decorate([expandToProperty("_markAllSubMeshesAsMiscDirty")],standardMaterial_StandardMaterial.prototype,"applyDecalMapAfterDetailMap",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"useLogarithmicDepth",null),h["BABYLON.StandardMaterial"]=standardMaterial_StandardMaterial,scene_Scene.DefaultMaterialFactory=e=>new standardMaterial_StandardMaterial("default material",e),ThinEngine.prototype.createDynamicTexture=function(e,t,i,r){let s=new internalTexture_InternalTexture(this,$.Dynamic);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?ThinEngine.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?ThinEngine.GetExponentOfTwo(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=r,this.updateTextureSamplingMode(r,s),this._internalTexturesCache.push(s),s},ThinEngine.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,a=!1,n=!1){if(!e)return;let o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,a);this._unpackFlipY(void 0===i?e.invertY:i),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);let c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(s||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);o.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0};let DynamicTexture=class DynamicTexture extends texture_Texture{constructor(e,t,i=null,r=!1,s=3,a=5,n){super(null,i,!r,n,s,void 0,void 0,void 0,void 0,a),this.name=e,this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=r;let o=this._getEngine();if(!o)return;t.getContext?(this._canvas=t,this._texture=o.createDynamicTexture(t.width,t.height,r,s)):(this._canvas=o.createCanvas(1,1),t.width||0===t.width?this._texture=o.createDynamicTexture(t.width,t.height,r,s):this._texture=o.createDynamicTexture(t,t,r,s));let 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){let t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){let i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(){let 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,r,s,a,n,o=!0){let l=this.getSize();if(a&&(this._context.fillStyle=a,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null==t){let i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){let e=parseInt(r.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),o&&this.update(n)}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new DynamicTexture(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(){let e=this.getScene();e&&!e.isReady()&&logger_Logger.Warn("The scene must be ready before serializing the dynamic texture");let t=super.serialize();return DynamicTexture._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()}};let WebXRLayerWrapper=class WebXRLayerWrapper{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){this.isFixedFoveationSupported&&(this.layer.fixedFoveation=Math.max(0,Math.min(1,e||0)))}constructor(e,t,i,r,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.createRenderTargetTextureProvider=s}};let WebXRLayerRenderTargetTextureProvider=class WebXRLayerRenderTargetTextureProvider{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=[],this._engine=e.getEngine()}_createInternalTexture(e,t){let i=new internalTexture_InternalTexture(this._engine,$.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new WebGLHardwareTexture(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,s,a){if(!this._engine)throw Error("Engine is disposed");let n={width:e,height:t},o=a?new MultiviewRenderTarget(this._scene,n):new renderTargetTexture_RenderTargetTexture("XR renderTargetTexture",n,this._scene),l=o.renderTarget;if(l._samples=o.samples,(i||!r)&&(l._framebuffer=i),r){if(a)l._colorTextureArray=r;else{let e=this._createInternalTexture(n,r);l.setTexture(e,0),o._texture=e}}return s&&(a?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(n,s)),o.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(o.skipInitialClear=!0),this._renderTargetTextures.push(o),o}_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}};let WebXRWebGLLayerWrapper=class WebXRWebGLLayerWrapper extends WebXRLayerWrapper{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new WebXRWebGLLayerRenderTargetTextureProvider(e.scene,this)),this.layer=e}};let WebXRWebGLLayerRenderTargetTextureProvider=class WebXRWebGLLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{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){let i=this._layer.getViewport(t);if(!i)return!1;let r=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/s,e.width=i.width/r,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){let t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&r===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}};let WebXRManagedOutputCanvasOptions=class WebXRManagedOutputCanvasOptions{static GetDefaults(e){let t=new WebXRManagedOutputCanvasOptions;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}};let WebXRManagedOutputCanvas=class WebXRManagedOutputCanvas{constructor(e,t=WebXRManagedOutputCanvasOptions.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new observable_Observable,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{let 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){let createLayer=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new WebXRWebGLLayerWrapper(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{tools_Tools.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")}).then(()=>createLayer()):Promise.resolve(createLayer())}_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)}};let NativeXRLayerWrapper=class NativeXRLayerWrapper extends WebXRLayerWrapper{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new NativeXRLayerRenderTargetTextureProvider(e,this)),this.layer=e}};let NativeXRLayerRenderTargetTextureProvider=class NativeXRLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{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}}};let NativeXRRenderTarget=class NativeXRRenderTarget{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(){}};let WebXRSessionManager=class WebXRSessionManager{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new observable_Observable,this.onXRReferenceSpaceChanged=new observable_Observable,this.onXRSessionEnded=new observable_Observable,this.onXRSessionInit=new observable_Observable,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(()=>{logger_Logger.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){let t=this.scene.getEngine();return this._xrNavigator.xr.native?new NativeXRRenderTarget(this):((e=e||WebXRManagedOutputCanvasOptions.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new WebXRManagedOutputCanvas(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 WebXRSessionManager.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),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=>(logger_Logger.Error("XR.requestReferenceSpace failed for the following reason: "),logger_Logger.Error(e),logger_Logger.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(e=>{let t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)},e=>{throw logger_Logger.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 NativeXRLayerWrapper(e.baseLayer):new WebXRWebGLLayerWrapper(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);let t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(e=>Promise.resolve(void 0===e||e)).catch(e=>(logger_Logger.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){this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=Math.max(0,Math.min(1,e||0)))}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(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"})(eB||(eB={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(eN||(eN={})),mesh_Mesh._GroundMeshParser=(e,t)=>GroundMesh.Parse(e,t);let GroundMesh=class GroundMesh extends mesh_Mesh{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e),this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){let i=this.getWorldMatrix(),r=math_vector_TmpVectors.Matrix[5];i.invertToRef(r);let s=math_vector_TmpVectors.Vector3[8];if(math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let a=this._getFacetAt(e,t),n=-(a.x*e+a.z*t+a.w)/a.y;return math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0,n,0,i,s),s.y}getNormalAtCoordinates(e,t){let i=new math_vector_Vector3(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){let r=this.getWorldMatrix(),s=math_vector_TmpVectors.Matrix[5];r.invertToRef(s);let a=math_vector_TmpVectors.Vector3[8];if(math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e,0,t,s,a),e=a.x,t=a.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let n=this._getFacetAt(e,t);return math_vector_Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,r,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){let i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i];return t<s.slope.x*e+s.slope.y?s.facet1:s.facet2}_initHeightQuads(){let e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=[];for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r={slope:math_vector_Vector2.Zero(),facet1:new math_vector_Vector4(0,0,0,0),facet2:new math_vector_Vector4(0,0,0,0)};this._heightQuads[i*e+t]=r}return this}_computeHeightQuads(){let e=this.getVerticesData(buffer_VertexBuffer.PositionKind);if(!e)return this;let t=math_vector_TmpVectors.Vector3[3],i=math_vector_TmpVectors.Vector3[2],r=math_vector_TmpVectors.Vector3[1],s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[4],n=math_vector_TmpVectors.Vector3[5],o=math_vector_TmpVectors.Vector3[6],l=math_vector_TmpVectors.Vector3[7],h=math_vector_TmpVectors.Vector3[8],c=0,u=0,d=0,_=0,p=0,f=0,m=0,g=this._subdivisionsX,v=this._subdivisionsY;for(let x=0;x<v;x++)for(let v=0;v<g;v++){c=3*v,u=x*(g+1)*3,d=(x+1)*(g+1)*3,t.x=e[u+c],t.y=e[u+c+1],t.z=e[u+c+2],i.x=e[u+c+3],i.y=e[u+c+4],i.z=e[u+c+5],r.x=e[d+c],r.y=e[d+c+1],r.z=e[d+c+2],s.x=e[d+c+3],s.y=e[d+c+4],s.z=e[d+c+5],_=(s.z-t.z)/(s.x-t.x),p=t.z-_*t.x,i.subtractToRef(t,a),r.subtractToRef(t,n),s.subtractToRef(t,o),math_vector_Vector3.CrossToRef(o,n,l),math_vector_Vector3.CrossToRef(a,o,h),l.normalize(),h.normalize(),f=-(l.x*t.x+l.y*t.y+l.z*t.z),m=-(h.x*i.x+h.y*i.y+h.z*i.z);let b=this._heightQuads[x*g+v];b.slope.copyFromFloats(_,p),b.facet1.copyFromFloats(l.x,l.y,l.z,f),b.facet2.copyFromFloats(h.x,h.y,h.z,m)}return this}serialize(e){super.serialize(e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height}static Parse(e,t){let i=new GroundMesh(e.name,t);return i._subdivisionsX=e.subdivisionsX||1,i._subdivisionsY=e.subdivisionsY||1,i._minX=e.minX,i._maxX=e.maxX,i._minZ=e.minZ,i._maxZ=e.maxZ,i._width=e.width,i._height=e.height,i}};function CreateGroundVertexData(e){let t,i;let r=[],s=[],a=[],n=[],o=e.width||1,l=e.height||1,h=0|(e.subdivisionsX||e.subdivisions||1),c=0|(e.subdivisionsY||e.subdivisions||1);for(t=0;t<=c;t++)for(i=0;i<=h;i++){let e=new math_vector_Vector3(i*o/h-o/2,0,(c-t)*l/c-l/2),r=new math_vector_Vector3(0,1,0);s.push(e.x,e.y,e.z),a.push(r.x,r.y,r.z),n.push(i/h,CompatibilityOptions.UseOpenGLOrientationForUV?t/c:1-t/c)}for(t=0;t<c;t++)for(i=0;i<h;i++)r.push(i+1+(t+1)*(h+1)),r.push(i+1+t*(h+1)),r.push(i+t*(h+1)),r.push(i+(t+1)*(h+1)),r.push(i+1+(t+1)*(h+1)),r.push(i+t*(h+1));let u=new mesh_vertexData_VertexData;return u.indices=r,u.positions=s,u.normals=a,u.uvs=n,u}function CreateTiledGroundVertexData(e){let t,i,r,s;let a=void 0!==e.xmin&&null!==e.xmin?e.xmin:-1,n=void 0!==e.zmin&&null!==e.zmin?e.zmin:-1,o=void 0!==e.xmax&&null!==e.xmax?e.xmax:1,l=void 0!==e.zmax&&null!==e.zmax?e.zmax:1,h=e.subdivisions||{w:1,h:1},c=e.precision||{w:1,h:1},u=[],d=[],_=[],p=[];h.h=h.h<1?1:h.h,h.w=h.w<1?1:h.w,c.w=c.w<1?1:c.w,c.h=c.h<1?1:c.h;let f={w:(o-a)/h.w,h:(l-n)/h.h};function applyTile(e,r,s,a){let n=d.length/3,o=c.w+1;for(t=0;t<c.h;t++)for(i=0;i<c.w;i++){let e=[n+i+t*o,n+(i+1)+t*o,n+(i+1)+(t+1)*o,n+i+(t+1)*o];u.push(e[1]),u.push(e[2]),u.push(e[3]),u.push(e[0]),u.push(e[1]),u.push(e[3])}let l=math_vector_Vector3.Zero(),h=new math_vector_Vector3(0,1,0);for(t=0;t<=c.h;t++)for(i=0,l.z=t*(a-r)/c.h+r;i<=c.w;i++)l.x=i*(s-e)/c.w+e,l.y=0,d.push(l.x,l.y,l.z),_.push(h.x,h.y,h.z),p.push(i/c.w,t/c.h)}for(r=0;r<h.h;r++)for(s=0;s<h.w;s++)applyTile(a+s*f.w,n+r*f.h,a+(s+1)*f.w,n+(r+1)*f.h);let m=new mesh_vertexData_VertexData;return m.indices=u,m.positions=d,m.normals=_,m.uvs=p,m}function CreateGroundFromHeightMapVertexData(e){let t,i;let r=[],s=[],a=[],n=[],o=e.colorFilter||new math_color_Color3(.3,.59,.11),l=e.alphaFilter||0,h=!1;if(e.minHeight>e.maxHeight){h=!0;let t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(t=0;t<=e.subdivisions;t++)for(i=0;i<=e.subdivisions;i++){let r=new math_vector_Vector3(i*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-t)*e.height/e.subdivisions-e.height/2),c=(r.x+e.width/2)/e.width*(e.bufferWidth-1)|0,u=(1-(r.z+e.height/2)/e.height)*(e.bufferHeight-1)|0,d=(c+u*e.bufferWidth)*4,_=e.buffer[d]/255,p=e.buffer[d+1]/255,f=e.buffer[d+2]/255,m=e.buffer[d+3]/255;h&&(_=1-_,p=1-p,f=1-f);let g=_*o.r+p*o.g+f*o.b;m>=l?r.y=e.minHeight+(e.maxHeight-e.minHeight)*g:r.y=e.minHeight-.001,s.push(r.x,r.y,r.z),a.push(0,0,0),n.push(i/e.subdivisions,1-t/e.subdivisions)}for(t=0;t<e.subdivisions;t++)for(i=0;i<e.subdivisions;i++){let a=i+1+(t+1)*(e.subdivisions+1),n=i+1+t*(e.subdivisions+1),o=i+t*(e.subdivisions+1),l=i+(t+1)*(e.subdivisions+1),h=s[3*a+1]>=e.minHeight,c=s[3*n+1]>=e.minHeight,u=s[3*o+1]>=e.minHeight;h&&c&&u&&(r.push(a),r.push(n),r.push(o));let d=s[3*l+1]>=e.minHeight;d&&h&&u&&(r.push(l),r.push(a),r.push(o))}mesh_vertexData_VertexData.ComputeNormals(s,r,a);let c=new mesh_vertexData_VertexData;return c.indices=r,c.positions=s,c.normals=a,c.uvs=n,c}function CreateGround(e,t={},i){let r=new GroundMesh(e,i);r._setReady(!1),r._subdivisionsX=t.subdivisionsX||t.subdivisions||1,r._subdivisionsY=t.subdivisionsY||t.subdivisions||1,r._width=t.width||1,r._height=t.height||1,r._maxX=r._width/2,r._maxZ=r._height/2,r._minX=-r._maxX,r._minZ=-r._maxZ;let s=CreateGroundVertexData(t);return s.applyToMesh(r,t.updatable),r._setReady(!0),r}function CreateTiledGround(e,t,i=null){let r=new mesh_Mesh(e,i),s=CreateTiledGroundVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateGroundFromHeightMap(e,t,i={},r=null){let s=i.width||10,a=i.height||10,n=i.subdivisions||1,o=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new math_color_Color3(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;r=r||engineStore_EngineStore.LastCreatedScene;let _=new GroundMesh(e,r);return _._subdivisionsX=n,_._subdivisionsY=n,_._width=s,_._height=a,_._maxX=_._width/2,_._maxZ=_._height/2,_._minX=-_._maxX,_._minZ=-_._maxZ,_._setReady(!1),tools_Tools.LoadImage(t,e=>{let t=e.width,i=e.height;if(r.isDisposed)return;let p=null==r?void 0:r.getEngine().resizeImageBitmap(e,t,i),f=CreateGroundFromHeightMapVertexData({width:s,height:a,subdivisions:n,minHeight:o,maxHeight:l,colorFilter:h,buffer:p,bufferWidth:t,bufferHeight:i,alphaFilter:c});f.applyToMesh(_,u),d&&d(_),_._setReady(!0)},()=>{},r.offlineProvider),_}function CreateTorusVertexData(e){let t=[],i=[],r=[],s=[],a=e.diameter||1,n=e.thickness||.5,o=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,h=o+1;for(let e=0;e<=o;e++){let l=e/o,c=e*Math.PI*2/o-Math.PI/2,u=math_vector_Matrix.Translation(a/2,0,0).multiply(math_vector_Matrix.RotationY(c));for(let a=0;a<=o;a++){let c=1-a/o,d=a*Math.PI*2/o+Math.PI,_=Math.cos(d),p=Math.sin(d),f=new math_vector_Vector3(_,p,0),m=f.scale(n/2),g=new math_vector_Vector2(l,c);m=math_vector_Vector3.TransformCoordinates(m,u),f=math_vector_Vector3.TransformNormal(f,u),i.push(m.x,m.y,m.z),r.push(f.x,f.y,f.z),s.push(g.x,CompatibilityOptions.UseOpenGLOrientationForUV?1-g.y:g.y);let v=(e+1)%h,x=(a+1)%h;t.push(e*h+a),t.push(e*h+x),t.push(v*h+a),t.push(e*h+x),t.push(v*h+x),t.push(v*h+a)}}mesh_vertexData_VertexData._ComputeSides(l,i,t,r,s,e.frontUVs,e.backUVs);let c=new mesh_vertexData_VertexData;return c.indices=t,c.positions=i,c.normals=r,c.uvs=s,c}function CreateTorus(e,t={},i){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateTorusVertexData(t);return s.applyToMesh(r,t.updatable),r}mesh_vertexData_VertexData.CreateGround=CreateGroundVertexData,mesh_vertexData_VertexData.CreateTiledGround=CreateTiledGroundVertexData,mesh_vertexData_VertexData.CreateGroundFromHeightMap=CreateGroundFromHeightMapVertexData,mesh_Mesh.CreateGround=(e,t,i,r,s,a)=>CreateGround(e,{width:t,height:i,subdivisions:r,updatable:a},s),mesh_Mesh.CreateTiledGround=(e,t,i,r,s,a,n,o,l)=>CreateTiledGround(e,{xmin:t,zmin:i,xmax:r,zmax:s,subdivisions:a,precision:n,updatable:l},o),mesh_Mesh.CreateGroundFromHeightMap=(e,t,i,r,s,a,n,o,l,h,c)=>CreateGroundFromHeightMap(e,t,{width:i,height:r,subdivisions:s,minHeight:a,maxHeight:n,updatable:l,onReady:h,alphaFilter:c},o),mesh_vertexData_VertexData.CreateTorus=CreateTorusVertexData,mesh_Mesh.CreateTorus=(e,t,i,r,s,a,n)=>CreateTorus(e,{diameter:t,thickness:i,tessellation:r,sideOrientation:n,updatable:a},s);let VRExperienceHelperGazer=class VRExperienceHelperGazer{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=VRExperienceHelperGazer._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=CreateTorus("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;let t=new standardMaterial_StandardMaterial("targetMat",e);t.specularColor=math_color_Color3.Black(),t.emissiveColor=new math_color_Color3(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new ray_Ray(math_vector_Vector3.Zero(),new math_vector_Vector3(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()}};VRExperienceHelperGazer._IdCounter=0;let VRExperienceHelperCameraGazer=class VRExperienceHelperCameraGazer extends VRExperienceHelperGazer{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){let t=this._getCamera();return t?t.getForwardRay(e):new ray_Ray(math_vector_Vector3.Zero(),math_vector_Vector3.Forward())}};let VRExperienceHelper=class VRExperienceHelper{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new observable_Observable,this.onAfterEnteringVRObservable=new observable_Observable,this.onExitingVRObservable=new observable_Observable,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new math_vector_Vector3(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new math_vector_Vector3(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new math_color_Color3(.2,.2,1),this._pickedGazeColor=new math_color_Color3(0,0,1),this.onNewMeshSelected=new observable_Observable,this.onNewMeshPicked=new observable_Observable,this.onBeforeCameraTeleport=new observable_Observable,this.onAfterCameraTeleport=new observable_Observable,this.onSelectedMeshUnselected=new observable_Observable,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==Gamepad.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged(e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))}),e.rightStick&&e.onrightstickchanged(e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)}),e.type===Gamepad.XBOX&&(e.onbuttondown(e=>{this._interactionsEnabled&&e===eM.A&&this._cameraGazer._selectionPointerDown()}),e.onbuttonup(e=>{this._interactionsEnabled&&e===eM.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=math_vector_Vector3.Zero(),this._workingQuaternion=math_vector_Quaternion.Identity(),this._workingMatrix=math_vector_Matrix.Identity(),logger_Logger.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();let i="getVRDisplays"in navigator;if(i||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new math_vector_Vector3(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new DeviceOrientationCamera("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 targetCamera_TargetCamera&&this._scene.activeCamera.rotation)){let e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(math_vector_Quaternion.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?WebXRSessionManager.IsSessionSupportedAsync("immersive-vr").then(i=>{i?(logger_Logger.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 VRExperienceHelperCameraGazer(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(e=>{switch(e){case eB.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case eB.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case eB.IN_XR:this._hasEnteredVR=!0;break;case eB.NOT_IN_XR:this._hasEnteredVR=!1}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new VRExperienceHelperCameraGazer(()=>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=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",t=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); 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) }";t+=".babylonVRicon.vrdisplaypresenting { display: none; }";let i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode||this.enterVR()});let i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())},pointerEvents_PointerEventTypes.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new CircleEase,this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===pointerEvents_PointerEventTypes.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===pointerEvents_PointerEventTypes.POINTERUP&&this._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===eB.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){let e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr){this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){logger_Logger.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=math_vector_Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}exitVR(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){logger_Logger.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr){this.xr.baseExperience.state===eB.IN_XR&&this.xr.pointerSelection.attach();return}this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>(!!this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t<this._floorMeshesCollection.length;t++)if(this._floorMeshesCollection[t].id===e.id)return!0;return!!this._floorMeshName&&e.name===this._floorMeshName}addFloorMesh(e){!this._floorMeshesCollection||this._floorMeshesCollection.indexOf(e)>-1||this._floorMeshesCollection.push(e)}removeFloorMesh(e){if(!this._floorMeshesCollection)return;let t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){let t=e.floorMeshes||[];if(!t.length){let i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr){t.forEach(e=>{this.xr.teleportation.addFloorMesh(e)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}if(!this.xrTestDone){let waitForXr=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(waitForXr),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(waitForXr);return}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);let t=new ImageProcessingConfiguration;t.vignetteColor=new math_color_Color4(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){(!this._teleportationRequestInitiated||t._teleportationRequestInitiated)&&(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)<this._padSensibilityDown&&(this._teleportActive&&this.teleportCamera(this._haloCenter),t._teleportationRequestInitiated=!1):e.y<-this._padSensibilityUp&&t._dpadPressed&&(t._activatePointer(),t._teleportationRequestInitiated=!0))}_checkRotate(e,t){!t._teleportationRequestInitiated&&(t._rotationLeftAsked?e.x>-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.x<this._padSensibilityDown&&(t._rotationRightAsked=!1):e.x>this._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=math_vector_Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,math_vector_Quaternion.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),math_vector_Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);let r=new ray_Ray(i,this._workingVector),s=this._scene.pickWithRay(r,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}}_createTeleportationCircles(){this._teleportationTarget=CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;let e=new DynamicTexture("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;let 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();let i=new standardMaterial_StandardMaterial("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;let r=CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);r.isPickable=!1,r.parent=this._teleportationTarget;let s=new animation_Animation("animationInnerCircle","position.y",30,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CYCLE),a=[];a.push({frame:0,value:0}),a.push({frame:30,value:.4}),a.push({frame:60,value:0}),s.setKeys(a);let n=new SineEase;n.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),s.setEasingFunction(n),r.animations=[],r.animations.push(s),this._scene.beginAnimation(r,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof FreeCamera))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];let t=math_vector_Quaternion.FromRotationMatrix(math_vector_Matrix.RotationY(Math.PI/4*this._rotationAngle)),i=new animation_Animation("animationRotation","rotationQuaternion",90,animation_Animation.ANIMATIONTYPE_QUATERNION,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];let s=new animation_Animation("animationPP","vignetteWeight",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:4}),a.push({frame:6,value:0}),s.setKeys(a),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);let n=new animation_Animation("animationPP2","vignetteStretch",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:3,value:10}),o.push({frame:6,value:0}),n.setKeys(o),n.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(n),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){let t,i;if(!(this.currentVRCamera instanceof FreeCamera))return;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED){i=90;let e=math_vector_Vector3.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];let r=new animation_Animation("animationCameraTeleportation","position",90,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];r.setKeys(s),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];let a=Math.round(i/2),n=new animation_Animation("animationPP","vignetteWeight",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:a,value:8}),o.push({frame:i,value:0}),n.setKeys(o),this._postProcessMove.animations.push(n);let l=new animation_Animation("animationPP2","vignetteStretch",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:a,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)}),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){if(!this.updateControllerLaserColor)return}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}};VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME=0,VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED=1;let intersectBoxAASphere=(e,t,i,r)=>!(e.x>i.x+r)&&!(i.x-r>t.x)&&!(e.y>i.y+r)&&!(i.y-r>t.y)&&!(e.z>i.z+r)&&!(i.z-r>t.z),rx=function(){let e={root:0,found:!1};return function(t,i,r,s){e.root=0,e.found=!1;let a=i*i-4*t*r;if(a<0)return e;let n=Math.sqrt(a),o=(-i-n)/(2*t),l=(-i+n)/(2*t);if(o>l){let e=l;l=o,o=e}return o>0&&o<s?(e.root=o,e.found=!0):l>0&&l<s&&(e.root=l,e.found=!0),e}}();let Collider=class Collider{constructor(){this._collisionPoint=math_vector_Vector3.Zero(),this._planeIntersectionPoint=math_vector_Vector3.Zero(),this._tempVector=math_vector_Vector3.Zero(),this._tempVector2=math_vector_Vector3.Zero(),this._tempVector3=math_vector_Vector3.Zero(),this._tempVector4=math_vector_Vector3.Zero(),this._edge=math_vector_Vector3.Zero(),this._baseToVertex=math_vector_Vector3.Zero(),this._destinationPoint=math_vector_Vector3.Zero(),this._slidePlaneNormal=math_vector_Vector3.Zero(),this._displacementVector=math_vector_Vector3.Zero(),this._radius=math_vector_Vector3.One(),this._retry=0,this._basePointWorld=math_vector_Vector3.Zero(),this._velocityWorld=math_vector_Vector3.Zero(),this._normalizedVelocity=math_vector_Vector3.Zero(),this._collisionMask=-1}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}get slidePlaneNormal(){return this._slidePlaneNormal}_initialize(e,t,i){this._velocity=t,this._velocitySquaredLength=this._velocity.lengthSquared();let r=Math.sqrt(this._velocitySquaredLength);0===r||1===r?this._normalizedVelocity.copyFromFloats(t._x,t._y,t._z):t.scaleToRef(1/r,this._normalizedVelocity),this._basePoint=e,e.multiplyToRef(this._radius,this._basePointWorld),t.multiplyToRef(this._radius,this._velocityWorld),this._velocityWorldLength=this._velocityWorld.length(),this._epsilon=i,this.collisionFound=!1}_checkPointInTriangle(e,t,i,r,s){t.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),math_vector_Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);let a=math_vector_Vector3.Dot(this._tempVector4,s);return!(a<0)&&(r.subtractToRef(e,this._tempVector3),math_vector_Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),!((a=math_vector_Vector3.Dot(this._tempVector4,s))<0)&&(math_vector_Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),(a=math_vector_Vector3.Dot(this._tempVector4,s))>=0))}_canDoCollision(e,t,i,r){let s=math_vector_Vector3.Distance(this._basePointWorld,e),a=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+a+t)&&!!intersectBoxAASphere(i,r,this._basePointWorld,this._velocityWorldLength+a)}_testTriangle(e,t,i,r,s,a,n){let o;let l=!1;t||(t=[]),t[e]||(t[e]=new math_plane_Plane(0,0,0,0),t[e].copyFromPoints(i,r,s));let h=t[e];if(!a&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;let c=h.signedDistanceTo(this._basePoint),u=math_vector_Vector3.Dot(h.normal,this._velocity);if(Collider.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(c)>=1)return;l=!0,o=0}else{o=(-1-c)/u;let e=(1-c)/u;if(o>e){let t=e;e=o,o=t}if(o>1||e<0)return;o<0&&(o=0),o>1&&(o=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,_=1;if(!l&&(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(o,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,s,h.normal)&&(d=!0,_=o,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*math_vector_Vector3.Dot(this._velocity,this._tempVector),a=this._tempVector.lengthSquared()-1,n=rx(e,t,a,_);n.found&&(_=n.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),(n=rx(e,t=2*math_vector_Vector3.Dot(this._velocity,this._tempVector),a=this._tempVector.lengthSquared()-1,_)).found&&(_=n.root,d=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(s,this._tempVector),(n=rx(e,t=2*math_vector_Vector3.Dot(this._velocity,this._tempVector),a=this._tempVector.lengthSquared()-1,_)).found&&(_=n.root,d=!0,this._collisionPoint.copyFrom(s)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let o=this._edge.lengthSquared(),l=math_vector_Vector3.Dot(this._edge,this._velocity),h=math_vector_Vector3.Dot(this._edge,this._baseToVertex);if((n=rx(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*math_vector_Vector3.Dot(this._velocity,this._baseToVertex)-l*h),a=o*(1-this._baseToVertex.lengthSquared())+h*h,_)).found){let e=(l*n.root-h)/o;e>=0&&e<=1&&(_=n.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=math_vector_Vector3.Dot(this._edge,this._velocity),h=math_vector_Vector3.Dot(this._edge,this._baseToVertex),(n=rx(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*math_vector_Vector3.Dot(this._velocity,this._baseToVertex)-l*h),a=o*(1-this._baseToVertex.lengthSquared())+h*h,_)).found){let e=(l*n.root-h)/o;e>=0&&e<=1&&(_=n.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=math_vector_Vector3.Dot(this._edge,this._velocity),h=math_vector_Vector3.Dot(this._edge,this._baseToVertex),(n=rx(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*math_vector_Vector3.Dot(this._velocity,this._baseToVertex)-l*h),a=o*(1-this._baseToVertex.lengthSquared())+h*h,_)).found){let e=(l*n.root-h)/o;e>=0&&e<=1&&(_=n.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(d){let e=_*_*this._velocitySquaredLength;(!this.collisionFound||e<this._nearestDistanceSquared)&&(n.collisionResponse&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this._nearestDistanceSquared=e,this._nearestDistance=Math.sqrt(e),this.collisionFound=!0),this.collidedMesh=n)}}_collide(e,t,i,r,s,a,n,o,l,h=!1){if(h){if(i&&0!==i.length)for(let a=r;a<s-2;a+=1){let r=i[a],s=i[a+1],h=i[a+2];if(4294967295===h){a+=2;continue}let c=t[r],u=t[s],d=t[h];c&&u&&d&&((l?1:0)^a%2?this._testTriangle(a,e,c,u,d,n,o):this._testTriangle(a,e,u,c,d,n,o))}else for(let i=0;i<t.length-2;i+=1){let r=t[i],s=t[i+1],a=t[i+2];r&&s&&a&&((l?1:0)^i%2?this._testTriangle(i,e,r,s,a,n,o):this._testTriangle(i,e,s,r,a,n,o))}}else if(i&&0!==i.length)for(let h=r;h<s;h+=3){let r=t[i[h]-a],s=t[i[h+1]-a],c=t[i[h+2]-a];l?this._testTriangle(h,e,r,s,c,n,o):this._testTriangle(h,e,c,s,r,n,o)}else for(let i=0;i<t.length;i+=3){let r=t[i],s=t[i+1],a=t[i+2];l?this._testTriangle(i,e,r,s,a,n,o):this._testTriangle(i,e,a,s,r,n,o)}}_getResponse(e,t){e.addToRef(t,this._destinationPoint),t.scaleInPlace(this._nearestDistance/t.length()),this._basePoint.addToRef(t,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this._epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(math_plane_Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,t)}};Collider.DoubleSidedCheck=!1;let DefaultCollisionCoordinator=class DefaultCollisionCoordinator{constructor(){this._scaledPosition=math_vector_Vector3.Zero(),this._scaledVelocity=math_vector_Vector3.Zero(),this._finalPosition=math_vector_Vector3.Zero()}getNewPosition(e,t,i,r,s,a,n){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,s),this._finalPosition.multiplyInPlace(i._radius),a(n,this._finalPosition,i.collidedMesh)}createCollider(){return new Collider}init(e){this._scene=e}_collideWithWorld(e,t,i,r,s,a=null){let n=10*engine_Engine.CollisionsEpsilon;if(i._retry>=r){s.copyFrom(e);return}let o=a?a.collisionMask:i.collisionMask;i._initialize(e,t,n);let l=a&&a.surroundingMeshes||this._scene.meshes;for(let e=0;e<l.length;e++){let t=l[e];t.isEnabled()&&t.checkCollisions&&t.subMeshes&&t!==a&&(o&t.collisionGroup)!=0&&t._checkCollision(i)}if(!i.collisionFound){e.addToRef(t,s);return}if((0!==t.x||0!==t.y||0!==t.z)&&i._getResponse(e,t),t.length()<=n){s.copyFrom(e);return}i._retry++,this._collideWithWorld(e,t,i,r,s,a)}};scene_Scene.CollisionCoordinatorFactory=()=>new DefaultCollisionCoordinator;let ComputeEffect=class ComputeEffect{constructor(e,t,i,r=""){var s,a;let n;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new observable_Observable,this.onErrorObservable=new observable_Observable,this.onBindObservable=new observable_Observable,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=q.WGSL,this.name=e,this._key=r,this._engine=i,this.uniqueId=ComputeEffect._UniqueIdSeed++,this.defines=null!==(s=t.defines)&&void 0!==s?s:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=null!==(a=t.entryPoint)&&void 0!==a?a:"main",this._shaderStore=ShaderStore.GetShadersStore(this._shaderLanguage),this._shaderRepository=ShaderStore.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=ShaderStore.GetIncludesShadersStore(this._shaderLanguage);let o=IsWindowObjectExist()?this._engine.getHostDocument():null;e.computeSource?n="source:"+e.computeSource:e.computeElement?(n=o?o.getElementById(e.computeElement):null)||(n=e.computeElement):n=e.compute||e;let l={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(n,"Compute","",i=>{ShaderProcessor.Initialize(l),ShaderProcessor.PreProcess(i,l,r=>{this._rawComputeSourceCode=i,t.processFinalCode&&(r=t.processFinalCode(r));let s=ShaderProcessor.Finalize(r,"",l);this._useFinalCode(s.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){let 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){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let s;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){let t=GetDOMTextContent(e);r(t);return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){let t=window.atob(e.substr(7));r(t);return}if(this._shaderStore[e+t+"Shader"]){r(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){r(this._shaderStore[e+i+"Shader"]);return}s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}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(){let e=this.defines,t=this._pipelineContext;this._isReady=!1;try{let 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(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t){let i=null;if(t&&e){let r=t.match(/COMPUTE SHADER ERROR: 0:(\d+?):/);if(r&&2===r.length){let t=parseInt(r[1]),s=e.split("\n",-1);s.length>=t&&(i=`Offending line [${t}] in compute code: ${s[t-1]}`)}}return[e,i]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,logger_Logger.Error("Unable to compile compute effect:"),logger_Logger.Error("Defines:\n"+this.defines),ComputeEffect.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&&(logger_Logger.Error("Compute code:"),logger_Logger.Error(t))),e&&logger_Logger.Error(e)}logger_Logger.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){ShaderStore.GetShadersStore(q.WGSL)[`${e}ComputeShader`]=t}};ComputeEffect._UniqueIdSeed=0,ComputeEffect.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",e[e.ExternalTexture=6]="ExternalTexture"}(eF||(eF={})),ThinEngine.prototype.createComputeEffect=function(e,t){throw Error("createComputeEffect: This engine does not support compute shaders!")},ThinEngine.prototype.createComputePipelineContext=function(){throw Error("createComputePipelineContext: This engine does not support compute shaders!")},ThinEngine.prototype.createComputeContext=function(){},ThinEngine.prototype.computeDispatch=function(e,t,i,r,s,a,n){throw Error("computeDispatch: This engine does not support compute shaders!")},ThinEngine.prototype.areAllComputeEffectsReady=function(){return!0},ThinEngine.prototype.releaseComputeEffects=function(){},ThinEngine.prototype._prepareComputePipelineContext=function(e,t,i,r,s){},ThinEngine.prototype._rebuildComputeEffects=function(){},ThinEngine.prototype._executeWhenComputeStateIsCompiled=function(e,t){t()},ThinEngine.prototype._releaseComputeEffect=function(e){},ThinEngine.prototype._deleteComputePipelineContext=function(e){};let ComputeShader=class ComputeShader{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,r={}){if(this._bindings={},this._samplers={},this._contextIsDirty=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=UniqueIdGenerator.UniqueId,!this._engine.getCaps().supportComputeShaders){logger_Logger.Error("This engine does not support compute shaders!");return}if(!r.bindingsMapping){logger_Logger.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!");return}this._context=t.createComputeContext(),this._shaderPath=i,this._options=Object.assign({bindingsMapping:{},defines:[]},r)}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){let r=this._bindings[e];this._bindings[e]={type:i?eF.Texture:eF.TextureWithoutSampler,object:t,indexInGroupEntries:null==r?void 0:r.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!r||r.object!==t||r.type!==this._bindings[e].type)}setStorageTexture(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:eF.StorageTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setExternalTexture(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:eF.ExternalTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setVideoTexture(e,t){return!!t.externalTexture&&(this.setExternalTexture(e,t.externalTexture),!0)}setUniformBuffer(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:eF.UniformBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setStorageBuffer(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:eF.StorageBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setTextureSampler(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:eF.Sampler,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}isReady(){let e=this._effect;for(let e in this._bindings){let t=this._bindings[e],i=t.type,r=t.object;switch(i){case eF.Texture:case eF.TextureWithoutSampler:case eF.StorageTexture:case eF.ExternalTexture:if(!r.isReady())return!1}}let t=[],i=this._shaderPath;if(this._options.defines)for(let e=0;e<this._options.defines.length;e++)t.push(this._options.defines[e]);let r=t.join("\n");return this._cachedDefines!==r&&(this._cachedDefines=r,e=this._engine.createComputeEffect(i,{defines:r,entryPoint:this._options.entryPoint,onCompiled:this.onCompiled,onError:this.onError}),this._effect=e),!!e.isReady()}dispatch(e,t,i){var r;if(!this.isReady())return!1;for(let e in this._bindings){let t=this._bindings[e];if(!this._options.bindingsMapping[e])throw Error("ComputeShader ('"+this.name+"'): No binding mapping has been provided for the property '"+e+"'");switch(t.type){case eF.Texture:{let i=this._samplers[e],s=t.object;i&&s._texture&&i.compareSampler(s._texture)||(this._samplers[e]=new TextureSampler().setParameters(s.wrapU,s.wrapV,s.wrapR,s.anisotropicFilteringLevel,s._texture.samplingMode,null===(r=s._texture)||void 0===r?void 0:r._comparisonFunction),this._contextIsDirty=!0);break}case eF.ExternalTexture:this._contextIsDirty=!0;break;case eF.UniformBuffer:{let e=t.object;e.getBuffer()!==t.buffer&&(t.buffer=e.getBuffer(),this._contextIsDirty=!0)}}}return this._contextIsDirty&&(this._contextIsDirty=!1,this._context.clear()),this._engine.computeDispatch(this._effect,this._context,this._bindings,e,t,i,this._options.bindingsMapping),!0}dispatchWhenReady(e,t,i,r=10){return new Promise(s=>{let check=()=>{this.dispatch(e,t,i)?s():setTimeout(check,r)};check()})}serialize(){let e=decorators_SerializationHelper.Serialize(this);for(let t in e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={},this._bindings){let i=this._bindings[t],r=i.object;switch(i.type){case eF.Texture:case eF.TextureWithoutSampler:case eF.StorageTexture:{let s=r.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type})}case eF.UniformBuffer:}}return e}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>new ComputeShader(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(let s in e.textures){let a=e.bindings[s],n=texture_Texture.Parse(e.textures[s],t,i);a.type===eF.Texture?r.setTexture(s,n):a.type===eF.TextureWithoutSampler?r.setTexture(s,n,!1):r.setStorageTexture(s,n)}return r}};__decorate([serialize()],ComputeShader.prototype,"name",void 0),h["BABYLON.ComputeShader"]=ComputeShader;let OctreeBlock=class OctreeBlock{constructor(e,t,i,r,s,a){this.entries=[],this._boundingVectors=[],this._capacity=i,this._depth=r,this._maxDepth=s,this._creationFunc=a,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.addEntry(e)}return}this._creationFunc(e,this),this.entries.length>this.capacity&&this._depth<this._maxDepth&&this.createInnerBlocks()}removeEntry(e){if(this.blocks){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.removeEntry(e)}return}let t=this.entries.indexOf(e);t>-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t<e.length;t++){let i=e[t];this.addEntry(i)}}select(e,t,i){if(boundingBox_BoundingBox.IsInFrustum(this._boundingVectors,e)){if(this.blocks){for(let r=0;r<this.blocks.length;r++){let s=this.blocks[r];s.select(e,t,i)}return}i?t.concat(this.entries):t.concatWithNoDuplicate(this.entries)}}intersects(e,t,i,r){if(boundingBox_BoundingBox.IntersectsSphere(this._minPoint,this._maxPoint,e,t)){if(this.blocks){for(let s=0;s<this.blocks.length;s++){let a=this.blocks[s];a.intersects(e,t,i,r)}return}r?i.concat(this.entries):i.concatWithNoDuplicate(this.entries)}}intersectsRay(e,t){if(e.intersectsBoxMinMax(this._minPoint,this._maxPoint)){if(this.blocks){for(let i=0;i<this.blocks.length;i++){let r=this.blocks[i];r.intersectsRay(e,t)}return}t.concatWithNoDuplicate(this.entries)}}createInnerBlocks(){OctreeBlock._CreateBlocks(this._minPoint,this._maxPoint,this.entries,this._capacity,this._depth,this._maxDepth,this,this._creationFunc),this.entries.splice(0)}static _CreateBlocks(e,t,i,r,s,a,n,o){n.blocks=[];let l=new math_vector_Vector3((t.x-e.x)/2,(t.y-e.y)/2,(t.z-e.z)/2);for(let t=0;t<2;t++)for(let h=0;h<2;h++)for(let c=0;c<2;c++){let u=e.add(l.multiplyByFloats(t,h,c)),d=e.add(l.multiplyByFloats(t+1,h+1,c+1)),_=new OctreeBlock(u,d,r,s+1,a,o);_.addEntries(i),n.blocks.push(_)}}};let Octree=class Octree{constructor(e,t,i=2){this.maxDepth=i,this.dynamicContent=[],this._maxBlockCapacity=t||64,this._selectionContent=new SmartArrayNoDuplicate(1024),this._creationFunc=e}update(e,t,i){OctreeBlock._CreateBlocks(e,t,i,this._maxBlockCapacity,0,this.maxDepth,this,this._creationFunc)}addMesh(e){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.addEntry(e)}}removeMesh(e){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.removeEntry(e)}}select(e,t){this._selectionContent.reset();for(let i=0;i<this.blocks.length;i++){let r=this.blocks[i];r.select(e,this._selectionContent,t)}return t?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}intersects(e,t,i){this._selectionContent.reset();for(let r=0;r<this.blocks.length;r++){let s=this.blocks[r];s.intersects(e,t,this._selectionContent,i)}return i?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}intersectsRay(e){this._selectionContent.reset();for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.intersectsRay(e,this._selectionContent)}return this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}};Octree.CreationFuncForMeshes=(e,t)=>{let i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Octree.CreationFuncForSubMeshes=(e,t)=>{let i=e.getBoundingInfo();i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},scene_Scene.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(sceneComponent_SceneComponentConstants.NAME_OCTREE);i||(i=new OctreeSceneComponent(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Octree(Octree.CreationFuncForMeshes,e,t));let r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},Object.defineProperty(scene_Scene.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),abstractMesh_AbstractMesh.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){let i=this.getScene(),r=i._getComponent(sceneComponent_SceneComponentConstants.NAME_OCTREE);r||(r=new OctreeSceneComponent(i),i._addComponent(r)),this._submeshesOctree||(this._submeshesOctree=new Octree(Octree.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);let s=this.getBoundingInfo(),a=s.boundingBox;return this._submeshesOctree.update(a.minimumWorld,a.maximumWorld,this.subMeshes),this._submeshesOctree};let OctreeSceneComponent=class OctreeSceneComponent{constructor(e){if(this.name=sceneComponent_SceneComponentConstants.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new ray_Ray(math_vector_Vector3.Zero(),new math_vector_Vector3(1,1,1)),!(e=e||engineStore_EngineStore.LastCreatedScene))return;this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t)}register(){this.scene.onMeshRemovedObservable.add(e=>{let t=this.scene.selectionOctree;if(null!=t){let i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}}),this.scene.onMeshImportedObservable.add(e=>{let 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){let t=e._submeshesOctree.select(this.scene.frustumPlanes);return t}return this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForPicking){ray_Ray.TransformToRef(t,e.getWorldMatrix(),this._tempRay);let i=e._submeshesOctree.intersectsRay(this._tempRay);return i}return this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){let i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z),r=e._submeshesOctree.intersects(t._basePointWorld,i);return r}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}};function CreateCylinderVertexData(e){let t,i,r,s,a,n,o;let l=e.height||2,h=0===e.diameterTop?0:e.diameterTop||e.diameter||1,c=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;h=h||1e-5,c=c||1e-5;let u=0|(e.tessellation||24),d=0|(e.subdivisions||1),_=!!e.hasRings,p=!!e.enclose,f=0===e.cap?0:e.cap||mesh_Mesh.CAP_ALL,m=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,g=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,v=e.faceUV||[,,,],x=e.faceColors,b=2+(1+(1!==m&&p?2:0))*(_?d:1);for(t=0;t<b;t++)x&&void 0===x[t]&&(x[t]=new math_color_Color4(1,1,1,1));for(t=0;t<b;t++)v&&void 0===v[t]&&(v[t]=new math_vector_Vector4(0,0,1,1));let T=[],S=[],C=[],E=[],y=[],R=2*Math.PI*m/u,P=(c-h)/2/l,A=math_vector_Vector3.Zero(),M=math_vector_Vector3.Zero(),I=math_vector_Vector3.Zero(),D=math_vector_Vector3.Zero(),O=math_vector_Vector3.Zero(),B=math_axis_Axis.Y,N=1,F=1,w=0,L=0;for(a=0;a<=d;a++)for(o=0,s=((r=a/d)*(h-c)+c)/2,N=_&&0!==a&&a!==d?2:1;o<N;o++){for(_&&(F+=o),p&&(F+=2*o),n=0;n<=u;n++)i=n*R,A.x=Math.cos(-i)*s,A.y=-l/2+r*l,A.z=Math.sin(-i)*s,0===h&&a===d?(M.x=C[C.length-(u+1)*3],M.y=C[C.length-(u+1)*3+1],M.z=C[C.length-(u+1)*3+2]):(M.x=A.x,M.z=A.z,M.y=Math.sqrt(M.x*M.x+M.z*M.z)*P,M.normalize()),0===n&&(I.copyFrom(A),D.copyFrom(M)),S.push(A.x,A.y,A.z),C.push(M.x,M.y,M.z),L=_?w!==F?v[F].y:v[F].w:v[F].y+(v[F].w-v[F].y)*r,E.push(v[F].x+(v[F].z-v[F].x)*n/u,CompatibilityOptions.UseOpenGLOrientationForUV?1-L:L),x&&y.push(x[F].r,x[F].g,x[F].b,x[F].a);1!==m&&p&&(S.push(A.x,A.y,A.z),S.push(0,A.y,0),S.push(0,A.y,0),S.push(I.x,I.y,I.z),math_vector_Vector3.CrossToRef(B,M,O),O.normalize(),C.push(O.x,O.y,O.z,O.x,O.y,O.z),math_vector_Vector3.CrossToRef(D,B,O),O.normalize(),C.push(O.x,O.y,O.z,O.x,O.y,O.z),L=_?w!==F?v[F+1].y:v[F+1].w:v[F+1].y+(v[F+1].w-v[F+1].y)*r,E.push(v[F+1].x,CompatibilityOptions.UseOpenGLOrientationForUV?1-L:L),E.push(v[F+1].z,CompatibilityOptions.UseOpenGLOrientationForUV?1-L:L),L=_?w!==F?v[F+2].y:v[F+2].w:v[F+2].y+(v[F+2].w-v[F+2].y)*r,E.push(v[F+2].x,CompatibilityOptions.UseOpenGLOrientationForUV?1-L:L),E.push(v[F+2].z,CompatibilityOptions.UseOpenGLOrientationForUV?1-L:L),x&&(y.push(x[F+1].r,x[F+1].g,x[F+1].b,x[F+1].a),y.push(x[F+1].r,x[F+1].g,x[F+1].b,x[F+1].a),y.push(x[F+2].r,x[F+2].g,x[F+2].b,x[F+2].a),y.push(x[F+2].r,x[F+2].g,x[F+2].b,x[F+2].a))),w!==F&&(w=F)}let V=1!==m&&p?u+4:u;for(F=0,a=0;F<d;F++){let e=0,t=0,i=0,r=0;for(n=0;n<u;n++)e=a*(V+1)+n,t=(a+1)*(V+1)+n,i=a*(V+1)+(n+1),r=(a+1)*(V+1)+(n+1),T.push(e,t,i),T.push(r,i,t);1!==m&&p&&(T.push(e+2,t+2,i+2),T.push(r+2,i+2,t+2),T.push(e+4,t+4,i+4),T.push(r+4,i+4,t+4)),a=_?a+2:a+1}let createCylinderCap=e=>{let t,i,r;let s=e?h/2:c/2;if(0===s)return;let a=e?v[b-1]:v[0],n=null;x&&(n=e?x[b-1]:x[0]);let o=S.length/3,d=e?l/2:-l/2,_=new math_vector_Vector3(0,d,0);S.push(_.x,_.y,_.z),C.push(0,e?1:-1,0);let p=a.y+(a.w-a.y)*.5;E.push(a.x+(a.z-a.x)*.5,CompatibilityOptions.UseOpenGLOrientationForUV?1-p:p),n&&y.push(n.r,n.g,n.b,n.a);let f=new math_vector_Vector2(.5,.5);for(r=0;r<=u;r++){t=2*Math.PI*r*m/u;let o=Math.cos(-t),l=Math.sin(-t);i=new math_vector_Vector3(o*s,d,l*s);let h=new math_vector_Vector2(o*f.x+.5,l*f.y+.5);S.push(i.x,i.y,i.z),C.push(0,e?1:-1,0);let c=a.y+(a.w-a.y)*h.y;E.push(a.x+(a.z-a.x)*h.x,CompatibilityOptions.UseOpenGLOrientationForUV?1-c:c),n&&y.push(n.r,n.g,n.b,n.a)}for(r=0;r<u;r++)e?(T.push(o),T.push(o+(r+2)),T.push(o+(r+1))):(T.push(o),T.push(o+(r+1)),T.push(o+(r+2)))};(f===mesh_Mesh.CAP_START||f===mesh_Mesh.CAP_ALL)&&createCylinderCap(!1),(f===mesh_Mesh.CAP_END||f===mesh_Mesh.CAP_ALL)&&createCylinderCap(!0),mesh_vertexData_VertexData._ComputeSides(g,S,T,C,E,e.frontUVs,e.backUVs);let U=new mesh_vertexData_VertexData;return U.indices=T,U.positions=S,U.normals=C,U.uvs=E,x&&(U.colors=y),U}function cylinderBuilder_CreateCylinder(e,t={},i){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateCylinderVertexData(t);return s.applyToMesh(r,t.updatable),r}mesh_vertexData_VertexData.CreateCylinder=CreateCylinderVertexData,mesh_Mesh.CreateCylinder=(e,t,i,r,s,a,n,o,l)=>{void 0!==n&&n instanceof scene_Scene||(void 0!==n&&(l=o||mesh_Mesh.DEFAULTSIDE,o=n),n=a,a=1);let h={height:t,diameterTop:i,diameterBottom:r,tessellation:s,subdivisions:a,sideOrientation:l,updatable:o};return cylinderBuilder_CreateCylinder(e,h,n)},node_Node.AddNodeConstructor("Light_Type_3",(e,t)=>()=>new HemisphericLight(e,math_vector_Vector3.Zero(),t));let HemisphericLight=class HemisphericLight extends light_Light{constructor(e,t,i){super(e,i),this.groundColor=new math_color_Color3(0,0,0),this.direction=t||math_vector_Vector3.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=math_vector_Vector3.Normalize(e.subtract(math_vector_Vector3.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){let i=math_vector_Vector3.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){let i=math_vector_Vector3.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=math_vector_Matrix.Identity()),this._worldMatrix}getTypeID(){return light_Light.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}};__decorate([serializeAsColor3()],HemisphericLight.prototype,"groundColor",void 0),__decorate([serializeAsVector3()],HemisphericLight.prototype,"direction",void 0);let utilityLayerRenderer_UtilityLayerRenderer=class utilityLayerRenderer_UtilityLayerRenderer{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 HemisphericLight("shared gizmo light",new math_vector_Vector3(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=math_color_Color3.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer?utilityLayerRenderer_UtilityLayerRenderer._CreateDefaultUtilityLayerFromScene(engineStore_EngineStore.LastCreatedScene):utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=new utilityLayerRenderer_UtilityLayerRenderer(e),utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=null}),utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer&&(utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=new utilityLayerRenderer_UtilityLayerRenderer(engineStore_EngineStore.LastCreatedScene),utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=null})),utilityLayerRenderer_UtilityLayerRenderer._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 observable_Observable,this.utilityLayerScene=new scene_Scene(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||!this.pickingEnabled||!this.processAllEvents&&t.type!==pointerEvents_PointerEventTypes.POINTERMOVE&&t.type!==pointerEvents_PointerEventTypes.POINTERUP&&t.type!==pointerEvents_PointerEventTypes.POINTERDOWN&&t.type!==pointerEvents_PointerEventTypes.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;let i=t.event;if(e.isPointerCaptured(i.pointerId)){this._pointerCaptures[i.pointerId]=!1;return}let getNearPickDataForScene=i=>{let r=null;if(t.nearInteractionPickingInfo)r=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new PickingInfo;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)r=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),r=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return r},r=getNearPickDataForScene(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=pointerEvents_PointerEventTypes.POINTERDOWN){t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(t.type,t.event,r),t.type),t.type===pointerEvents_PointerEventTypes.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{let i=getNearPickDataForScene(e),s=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,s),t.skipOnPointerObservable=!0):t.type===pointerEvents_PointerEventTypes.POINTERDOWN?this._pointerCaptures[s.pointerId]=!0:(t.type===pointerEvents_PointerEventTypes.POINTERMOVE||t.type===pointerEvents_PointerEventTypes.POINTERUP)&&(this._lastPointerEvents[s.pointerId]&&(this.onPointerOutObservable.notifyObservers(s.pointerId),delete this._lastPointerEvents[s.pointerId]),this._notifyObservers(t,i,s)):!this._pointerCaptures[s.pointerId]&&(r.distance<i.distance||0===i.distance)?(this._notifyObservers(t,r,s),t.skipOnPointerObservable||(t.skipOnPointerObservable=r.distance>0)):!this._pointerCaptures[s.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,s),t.skipOnPointerObservable=!0):((t.type===pointerEvents_PointerEventTypes.POINTERMOVE||t.type===pointerEvents_PointerEventTypes.POINTERUP)&&this._lastPointerEvents[s.pointerId]&&(this.onPointerOutObservable.notifyObservers(s.pointerId),delete this._lastPointerEvents[s.pointerId]),this._notifyObservers(t,r,s))),t.type===pointerEvents_PointerEventTypes.POINTERUP&&this._pointerCaptures[s.pointerId]&&(this._pointerCaptures[s.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 PointerInfo(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){let 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()}};utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=null,utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(ew||(ew={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(eL||(eL={}));let gizmo_Gizmo=class gizmo_Gizmo{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;let t=e==eL.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=utilityLayerRenderer_UtilityLayerRenderer.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=ew.Origin,this._updateScale=!0,this._coordinatesMode=eL.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=math_vector_Matrix.RotationY(Math.PI),this._rootMesh=new mesh_Mesh("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=math_vector_Quaternion.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==ew.Pivot&&e.getAbsolutePivotPoint){let t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{let t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new math_vector_Vector3(0,0,0);this._rootMesh.position.copyFrom(i)}}if(this.updateGizmoRotationToMatchAttachedMesh){let t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName(),i=t?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,gizmo_Gizmo.PreserveScaling?i:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){let t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,math_vector_TmpVectors.Vector3[0]);let r=this.scaleRatio;if(t.mode==camera_Camera.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){let e=t.orthoTop-t.orthoBottom;r*=e}}else{let e=t.getScene().useRightHandedSystem?math_vector_Vector3.RightHandedForwardReadOnly:math_vector_Vector3.LeftHandedForwardReadOnly,i=t.getDirection(e);r*=math_vector_Vector3.Dot(math_vector_TmpVectors.Vector3[0],i)}this._rootMesh.scaling.setAll(r),0>e._getWorldMatrixDeterminant()&&!gizmo_Gizmo.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_matrixChanged(){if(this._attachedNode){if(this._attachedNode._isCamera){let e,t;let i=this._attachedNode;if(i.parent){let t=math_vector_TmpVectors.Matrix[1];i.parent._worldMatrix.invertToRef(t),this._attachedNode._worldMatrix.multiplyToRef(t,math_vector_TmpVectors.Matrix[0]),e=math_vector_TmpVectors.Matrix[0]}else e=this._attachedNode._worldMatrix;i.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(e,math_vector_TmpVectors.Matrix[1]),t=math_vector_TmpVectors.Matrix[1]):t=e,t.decompose(math_vector_TmpVectors.Vector3[1],math_vector_TmpVectors.Quaternion[0],math_vector_TmpVectors.Vector3[0]);let r="FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName();if(r){let e=this._attachedNode;e.rotation=math_vector_TmpVectors.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(math_vector_TmpVectors.Quaternion[0]),e.rotationQuaternion.normalize())}i.position.copyFrom(math_vector_TmpVectors.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){let e=this._attachedNode;if(e.parent){let t=math_vector_TmpVectors.Matrix[0],i=math_vector_TmpVectors.Matrix[1];if(e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i),i.decompose(math_vector_TmpVectors.Vector3[0],math_vector_TmpVectors.Quaternion[0],e.position),math_vector_TmpVectors.Quaternion[0].normalize(),e.isUsingPivotMatrix()){let t=math_vector_TmpVectors.Quaternion[1];math_vector_Quaternion.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);let i=math_vector_TmpVectors.Matrix[2];math_vector_Matrix.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);let r=math_vector_TmpVectors.Matrix[2];t.toRotationMatrix(r);let s=e.getPivotMatrix(),a=math_vector_TmpVectors.Matrix[3];s.invertToRef(a),s.multiplyToRef(i,math_vector_TmpVectors.Matrix[4]),math_vector_TmpVectors.Matrix[4].multiplyToRef(r,math_vector_TmpVectors.Matrix[5]),math_vector_TmpVectors.Matrix[5].multiplyToRef(a,math_vector_TmpVectors.Matrix[6]),math_vector_TmpVectors.Matrix[6].getTranslationToRef(math_vector_TmpVectors.Vector3[1]),e.position.subtractInPlace(math_vector_TmpVectors.Vector3[1])}}else this._attachedNode._worldMatrix.decompose(math_vector_TmpVectors.Vector3[0],math_vector_TmpVectors.Quaternion[0],e.position,gizmo_Gizmo.PreserveScaling?e:void 0);math_vector_TmpVectors.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(math_vector_TmpVectors.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(math_vector_TmpVectors.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=math_vector_TmpVectors.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){let e=this._attachedNode,t=e.getParent();if(t){let i=math_vector_TmpVectors.Matrix[0],r=math_vector_TmpVectors.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r);let s=e.getLocalMatrix();s.copyFrom(r)}else{let t=e.getLocalMatrix();t.copyFrom(e.getFinalMatrix())}e.markAsDirty()}else{let e=this._attachedNode;if(e.getTypeID){let t=e.getTypeID();if(t===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT||t===light_Light.LIGHTTYPEID_SPOTLIGHT||t===light_Light.LIGHTTYPEID_POINTLIGHT){let t=e.parent;if(t){let i=math_vector_TmpVectors.Matrix[0],r=math_vector_TmpVectors.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,r),r.decompose(void 0,math_vector_TmpVectors.Quaternion[0],math_vector_TmpVectors.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,math_vector_TmpVectors.Quaternion[0],math_vector_TmpVectors.Vector3[0]);e.position=new math_vector_Vector3(math_vector_TmpVectors.Vector3[0].x,math_vector_TmpVectors.Vector3[0].y,math_vector_TmpVectors.Vector3[0].z),e.direction&&(e.direction=new math_vector_Vector3(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,r=e.utilityLayerScene.onPointerObservable.add(e=>{var r,s;if(e.pickInfo){if(e.type===pointerEvents_PointerEventTypes.POINTERMOVE){if(i)return;t.forEach(t=>{var i,r;if(t.colliderMeshes&&t.gizmoMeshes){let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,a=t.dragBehavior.enabled?s||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=a,e.color&&(e.color=a.diffuseColor)})}})}if(e.type===pointerEvents_PointerEventTypes.POINTERDOWN&&t.has(null===(r=e.pickInfo.pickedMesh)||void 0===r?void 0:r.parent)){i=!0;let r=t.get(null===(s=e.pickInfo.pickedMesh)||void 0===s?void 0:s.parent);r.active=!0,t.forEach(t=>{var i,r;let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,a=(s||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=a,e.color&&(e.color=a.diffuseColor)})})}e.type===pointerEvents_PointerEventTypes.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)})})}});return r}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}};gizmo_Gizmo.PreserveScaling=!1,Object.defineProperty(scene_Scene.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new DebugLayer(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"}(eV||(eV={}));let DebugLayer=class DebugLayer{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new observable_Observable),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new observable_Observable),this._onSelectionChangedObservable)}constructor(e){if(this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||engineStore_EngineStore.LastCreatedScene,!this._scene)return;this._scene.onDisposeObservable.add(()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()})}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(let e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(let e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}let t=Object.assign(Object.assign({},DebugLayer.Config),e);this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise(t=>{if(void 0===this.BJSINSPECTOR){let i=e&&e.inspectorURL?e.inspectorURL:DebugLayer.InspectorURL;tools_Tools.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}};function CreateBoxVertexData(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],i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[],s=[],a=e.width||e.size||1,n=e.height||e.size||1,o=e.depth||e.size||1,l=e.wrap||!1,h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],_=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],_=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,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]],r=[17,18,19,16],s=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),r.unshift(r.pop()),u--;for(;d>0;)i.unshift(i.pop()),s.unshift(s.pop()),d--;e=e.flat(),i=i.flat(),_=_.concat(e).concat(i),t.push(r[0],r[2],r[3],r[0],r[1],r[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}let p=[a/2,n/2,o/2];s=_.reduce((e,t,i)=>e.concat(t*p[i%3]),[]);let f=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,m=e.faceUV||Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new math_vector_Vector4(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new math_color_Color4(1,1,1,1));for(let e=0;e<6;e++)if(r.push(m[e].z,CompatibilityOptions.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,CompatibilityOptions.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,CompatibilityOptions.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),r.push(m[e].z,CompatibilityOptions.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);mesh_vertexData_VertexData._ComputeSides(f,s,t,i,r,e.frontUVs,e.backUVs);let x=new mesh_vertexData_VertexData;if(x.indices=t,x.positions=s,x.normals=i,x.uvs=r,g){let e=f===mesh_vertexData_VertexData.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function CreateSegmentedBoxVertexData(e){let t=e.width||e.size||1,i=e.height||e.size||1,r=e.depth||e.size||1,s=0|(e.widthSegments||e.segments||1),a=0|(e.heightSegments||e.segments||1),n=0|(e.depthSegments||e.segments||1),o=new math_vector_Matrix,l=new math_vector_Matrix,h=new math_vector_Matrix,c=CreateGroundVertexData({width:t,height:r,subdivisionsX:s,subdivisionsY:n});math_vector_Matrix.TranslationToRef(0,-i/2,0,l),math_vector_Matrix.RotationZToRef(Math.PI,o),o.multiplyToRef(l,h),c.transform(h);let u=CreateGroundVertexData({width:t,height:r,subdivisionsX:s,subdivisionsY:n});math_vector_Matrix.TranslationToRef(0,i/2,0,h),u.transform(h);let d=CreateGroundVertexData({width:i,height:r,subdivisionsX:a,subdivisionsY:n});math_vector_Matrix.TranslationToRef(-t/2,0,0,l),math_vector_Matrix.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,h),d.transform(h);let _=CreateGroundVertexData({width:i,height:r,subdivisionsX:a,subdivisionsY:n});math_vector_Matrix.TranslationToRef(t/2,0,0,l),math_vector_Matrix.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,h),_.transform(h);let p=CreateGroundVertexData({width:t,height:i,subdivisionsX:s,subdivisionsY:a});math_vector_Matrix.TranslationToRef(0,0,-r/2,l),math_vector_Matrix.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,h),p.transform(h);let f=CreateGroundVertexData({width:t,height:i,subdivisionsX:s,subdivisionsY:a});return math_vector_Matrix.TranslationToRef(0,0,r/2,l),math_vector_Matrix.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,h),f.transform(h),c.merge([u,_,d,p,f],!0),c}function boxBuilder_CreateBox(e,t={},i=null){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateBoxVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateSphereVertexData(e){let t=0|(e.segments||32),i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,n=e.slice&&e.slice<=0?1:e.slice||1,o=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new math_vector_Vector3(i/2,r/2,s/2),c=2+t,u=2*c,d=[],_=[],p=[],f=[];for(let e=0;e<=c;e++){let t=e/c,i=t*Math.PI*n;for(let e=0;e<=u;e++){let r=e/u,s=r*Math.PI*2*a,n=math_vector_Matrix.RotationZ(-i),o=math_vector_Matrix.RotationY(s),l=math_vector_Vector3.TransformCoordinates(math_vector_Vector3.Up(),n),c=math_vector_Vector3.TransformCoordinates(l,o),d=c.multiply(h),m=c.divide(h).normalize();_.push(d.x,d.y,d.z),p.push(m.x,m.y,m.z),f.push(r,CompatibilityOptions.UseOpenGLOrientationForUV?1-t:t)}if(e>0){let t=_.length/3;for(let i=t-2*(u+1);i+u+2<t;i++)l?(e>1&&(d.push(i),d.push(i+1),d.push(i+u+1)),(e<c||n<1)&&(d.push(i+u+1),d.push(i+1),d.push(i+u+2))):(d.push(i),d.push(i+1),d.push(i+u+1),d.push(i+u+1),d.push(i+1),d.push(i+u+2))}}mesh_vertexData_VertexData._ComputeSides(o,_,d,p,f,e.frontUVs,e.backUVs);let m=new mesh_vertexData_VertexData;return m.indices=d,m.positions=_,m.normals=p,m.uvs=f,m}function sphereBuilder_CreateSphere(e,t={},i=null){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateSphereVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateCapsuleVertexData(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){let t,i;let r=0|Math.max(e.subdivisions?e.subdivisions:2,1),s=0|Math.max(e.tessellation?e.tessellation:16,3),a=Math.max(e.height?e.height:1,0),n=Math.max(e.radius?e.radius:.25,0),o=0|Math.max(e.capSubdivisions?e.capSubdivisions:6,1),l=Math.max(e.radiusTop?e.radiusTop:n,0),h=Math.max(e.radiusBottom?e.radiusBottom:n,0),c=a-(l+h),u=2*Math.PI,d=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:o,1),_=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:o,1),p=Math.acos((h-l)/a),f=[],m=[],g=[],v=[],x=0,b=[],T=.5*c,S=.5*Math.PI,C=math_vector_Vector3.Zero(),E=math_vector_Vector3.Zero(),y=Math.cos(p),R=Math.sin(p),P=new math_vector_Vector2(l*R,T+l*y).subtract(new math_vector_Vector2(h*R,-T+h*y)).length(),A=l*p+P+h*(S-p),M=0;for(i=0;i<=d;i++){let e=[],r=S-p*(i/d);M+=l*p/d;let a=Math.cos(r),n=Math.sin(r),o=a*l;for(t=0;t<=s;t++){let i=t/s,r=i*u+0,h=Math.sin(r),c=Math.cos(r);E.x=o*h,E.y=T+n*l,E.z=o*c,m.push(E.x,E.y,E.z),C.set(a*h,n,a*c),g.push(C.x,C.y,C.z),v.push(i,CompatibilityOptions.UseOpenGLOrientationForUV?M/A:1-M/A),e.push(x),x++}b.push(e)}let I=a-l-h+y*l-y*h,D=R*(h-l)/I;for(i=1;i<=r;i++){let e=[];M+=P/r;let a=R*(i*(h-l)/r+l);for(t=0;t<=s;t++){let n=t/s,o=n*u+0,h=Math.sin(o),c=Math.cos(o);E.x=a*h,E.y=T+y*l-i*I/r,E.z=a*c,m.push(E.x,E.y,E.z),C.set(h,D,c).normalize(),g.push(C.x,C.y,C.z),v.push(n,CompatibilityOptions.UseOpenGLOrientationForUV?M/A:1-M/A),e.push(x),x++}b.push(e)}for(i=1;i<=_;i++){let e=[],r=S-p-(Math.PI-p)*(i/_);M+=h*p/_;let a=Math.cos(r),n=Math.sin(r),o=a*h;for(t=0;t<=s;t++){let i=t/s,r=i*u+0,l=Math.sin(r),c=Math.cos(r);E.x=o*l,E.y=-T+n*h,E.z=o*c,m.push(E.x,E.y,E.z),C.set(a*l,n,a*c),g.push(C.x,C.y,C.z),v.push(i,CompatibilityOptions.UseOpenGLOrientationForUV?M/A:1-M/A),e.push(x),x++}b.push(e)}for(t=0;t<s;t++)for(i=0;i<d+r+_;i++){let e=b[i][t],r=b[i+1][t],s=b[i+1][t+1],a=b[i][t+1];f.push(e),f.push(r),f.push(a),f.push(r),f.push(s),f.push(a)}if(f=f.reverse(),e.orientation&&!e.orientation.equals(math_vector_Vector3.Up())){let t=new math_vector_Matrix;e.orientation.clone().scale(.5*Math.PI).cross(math_vector_Vector3.Up()).toQuaternion().toRotationMatrix(t);let i=math_vector_Vector3.Zero();for(let e=0;e<m.length;e+=3)i.set(m[e],m[e+1],m[e+2]),math_vector_Vector3.TransformCoordinatesToRef(i.clone(),t,i),m[e]=i.x,m[e+1]=i.y,m[e+2]=i.z}let O=new mesh_vertexData_VertexData;return O.positions=m,O.normals=g,O.uvs=v,O.indices=f,O}function capsuleBuilder_CreateCapsule(e,t={orientation:math_vector_Vector3.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},i=null){let r=new mesh_Mesh(e,i),s=CreateCapsuleVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateRibbonVertexData(e){let t,i,r,s,a,n,o,l,h,c,u,d=e.pathArray,_=e.closeArray||!1,p=e.closePath||!1,f=e.invertUV||!1,m=Math.floor(d[0].length/2),g=e.offset||m;g=g>m?m:Math.floor(g);let v=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,x=e.uvs,b=e.colors,T=[],S=[],C=[],E=[],y=[],R=[],P=[],A=[],M=[],I=[];if(d.length<2){let e=[],t=[];for(r=0;r<d[0].length-g;r++)e.push(d[0][r]),t.push(d[0][r+g]);d=[e,t]}let D=0,O=p?1:0;for(i=0,t=d[0].length;i<d.length;i++){for(P[i]=0,y[i]=[0],t=t<(n=(a=d[i]).length)?t:n,s=0;s<n;)T.push(a[s].x,a[s].y,a[s].z),s>0&&(o=a[s].subtract(a[s-1]).length()+P[i],y[i].push(o),P[i]=o),s++;p&&(s--,T.push(a[0].x,a[0].y,a[0].z),o=a[s].subtract(a[0]).length()+P[i],y[i].push(o),P[i]=o),M[i]=n+O,I[i]=D,D+=n+O}let B=null,N=null;for(r=0;r<t+O;r++){for(i=0,A[r]=0,R[r]=[0];i<d.length-1;i++)l=d[i],h=d[i+1],r===t?(B=l[0],N=h[0]):(B=l[r],N=h[r]),o=N.subtract(B).length()+A[r],R[r].push(o),A[r]=o;_&&N&&B&&(l=d[i],h=d[0],r===t&&(N=h[0]),o=N.subtract(B).length()+A[r],A[r]=o)}if(x)for(i=0;i<x.length;i++)E.push(x[i].x,CompatibilityOptions.UseOpenGLOrientationForUV?1-x[i].y:x[i].y);else for(i=0;i<d.length;i++)for(r=0;r<t+O;r++)c=0!=P[i]?y[i][r]/P[i]:0,u=0!=A[r]?R[r][i]/A[r]:0,f?E.push(u,c):E.push(c,CompatibilityOptions.UseOpenGLOrientationForUV?1-u:u);let F=0,w=M[i=0]-1,L=M[i+1]-1,V=w<L?w:L,U=I[1]-I[0],k=_?M.length:M.length-1;for(;F<=V&&i<k;)S.push(F,F+U,F+1),S.push(F+U+1,F+1,F+U),(F+=1)===V&&(++i==M.length-1?(U=I[0]-I[i],w=M[i]-1,L=M[0]-1):(U=I[i+1]-I[i],w=M[i]-1,L=M[i+1]-1),F=I[i],V=w<L?w+F:L+F);if(mesh_vertexData_VertexData.ComputeNormals(T,S,C),p){let e=0,t=0;for(i=0;i<d.length;i++)e=3*I[i],t=i+1<d.length?(I[i+1]-1)*3:C.length-3,C[e]=(C[e]+C[t])*.5,C[e+1]=(C[e+1]+C[t+1])*.5,C[e+2]=(C[e+2]+C[t+2])*.5,C[t]=C[e],C[t+1]=C[e+1],C[t+2]=C[e+2]}mesh_vertexData_VertexData._ComputeSides(v,T,S,C,E,e.frontUVs,e.backUVs);let G=null;if(b){G=new Float32Array(4*b.length);for(let e=0;e<b.length;e++)G[4*e]=b[e].r,G[4*e+1]=b[e].g,G[4*e+2]=b[e].b,G[4*e+3]=b[e].a}let z=new mesh_vertexData_VertexData,W=new Float32Array(T),H=new Float32Array(C),X=new Float32Array(E);return z.indices=S,z.positions=W,z.normals=H,z.uvs=X,G&&z.set(G,buffer_VertexBuffer.ColorKind),p&&(z._idx=I),z}function CreateRibbon(e,t,i=null){let r=t.pathArray,s=t.closeArray,a=t.closePath,n=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),o=t.instance,l=t.updatable;if(o){let e=math_vector_TmpVectors.Vector3[0].setAll(Number.MAX_VALUE),i=math_vector_TmpVectors.Vector3[1].setAll(-Number.MAX_VALUE),s=o.getVerticesData(buffer_VertexBuffer.PositionKind);if((t=>{let s=r[0].length,a=0,n=o._originalBuilderSideOrientation===mesh_Mesh.DOUBLESIDE?2:1;for(let l=1;l<=n;++l)for(let n=0;n<r.length;++n){let l=r[n],h=l.length;s=s<h?s:h;for(let r=0;r<s;++r){let s=l[r];t[a]=s.x,t[a+1]=s.y,t[a+2]=s.z,e.minimizeInPlaceFromFloats(s.x,s.y,s.z),i.maximizeInPlaceFromFloats(s.x,s.y,s.z),a+=3}if(o._creationDataStorage&&o._creationDataStorage.closePath){let e=l[0];t[a]=e.x,t[a+1]=e.y,t[a+2]=e.z,a+=3}}})(s),o.hasBoundingInfo?o.getBoundingInfo().reConstruct(e,i,o._worldMatrix):o.buildBoundingInfo(e,i,o._worldMatrix),o.updateVerticesData(buffer_VertexBuffer.PositionKind,s,!1,!1),t.colors){let e=o.getVerticesData(buffer_VertexBuffer.ColorKind);for(let i=0,r=0;i<t.colors.length;i++,r+=4){let s=t.colors[i];e[r]=s.r,e[r+1]=s.g,e[r+2]=s.b,e[r+3]=s.a}o.updateVerticesData(buffer_VertexBuffer.ColorKind,e,!1,!1)}if(t.uvs){let e=o.getVerticesData(buffer_VertexBuffer.UVKind);for(let i=0;i<t.uvs.length;i++)e[2*i]=t.uvs[i].x,e[2*i+1]=CompatibilityOptions.UseOpenGLOrientationForUV?1-t.uvs[i].y:t.uvs[i].y;o.updateVerticesData(buffer_VertexBuffer.UVKind,e,!1,!1)}if(!o.areNormalsFrozen||o.isFacetDataEnabled){let e=o.getIndices(),t=o.getVerticesData(buffer_VertexBuffer.NormalKind),i=o.isFacetDataEnabled?o.getFacetDataParameters():null;if(mesh_vertexData_VertexData.ComputeNormals(s,e,t,i),o._creationDataStorage&&o._creationDataStorage.closePath){let e=0,i=0;for(let s=0;s<r.length;s++)e=3*o._creationDataStorage.idx[s],i=s+1<r.length?(o._creationDataStorage.idx[s+1]-1)*3:t.length-3,t[e]=(t[e]+t[i])*.5,t[e+1]=(t[e+1]+t[i+1])*.5,t[e+2]=(t[e+2]+t[i+2])*.5,t[i]=t[e],t[i+1]=t[e+1],t[i+2]=t[e+2]}o.areNormalsFrozen||o.updateVerticesData(buffer_VertexBuffer.NormalKind,t,!1,!1)}return o}{let r=new mesh_Mesh(e,i);r._originalBuilderSideOrientation=n,r._creationDataStorage=new _CreationDataStorage;let o=CreateRibbonVertexData(t);return a&&(r._creationDataStorage.idx=o._idx),r._creationDataStorage.closePath=a,r._creationDataStorage.closeArray=s,o.applyToMesh(r,l),r}}function CreateDiscVertexData(e){let t=[],i=[],r=[],s=[],a=e.radius||.5,n=e.tessellation||64,o=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);let h=2*Math.PI*o,c=1===o?h/n:h/(n-1),u=0;for(let e=0;e<n;e++){let e=Math.cos(u),i=Math.sin(u),r=(e+1)/2,n=(1-i)/2;t.push(a*e,a*i,0),s.push(r,CompatibilityOptions.UseOpenGLOrientationForUV?1-n:n),u+=c}1===o&&(t.push(t[3],t[4],t[5]),s.push(s[2],CompatibilityOptions.UseOpenGLOrientationForUV?1-s[3]:s[3]));let d=t.length/3;for(let e=1;e<d-1;e++)i.push(e+1,0,e);mesh_vertexData_VertexData.ComputeNormals(t,i,r),mesh_vertexData_VertexData._ComputeSides(l,t,i,r,s,e.frontUVs,e.backUVs);let _=new mesh_vertexData_VertexData;return _.indices=i,_.positions=t,_.normals=r,_.uvs=s,_}function discBuilder_CreateDisc(e,t={},i=null){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateDiscVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateTiledPlaneVertexData(e){let t=e.pattern||mesh_Mesh.NO_FLIP,i=e.tileWidth||e.tileSize||1,r=e.tileHeight||e.tileSize||1,s=e.alignHorizontal||0,a=e.alignVertical||0,n=e.width||e.size||1,o=Math.floor(n/i),l=n-o*i,h=e.height||e.size||1,c=Math.floor(h/r),u=h-c*r,d=i*o/2,_=r*c/2,p=0,f=0,m=0,g=0,v=0,x=0;if(l>0||u>0){switch(m=-d,g=-_,v=d,x=_,s){case mesh_Mesh.CENTER:l/=2,m-=l,v+=l;break;case mesh_Mesh.LEFT:v+=l,p=-l/2;break;case mesh_Mesh.RIGHT:m-=l,p=l/2}switch(a){case mesh_Mesh.CENTER:u/=2,g-=u,x+=u;break;case mesh_Mesh.BOTTOM:x+=u,f=-u/2;break;case mesh_Mesh.TOP:g-=u,f=u/2}}let b=[],T=[],S=[];S[0]=[0,0,1,0,1,1,0,1],S[1]=[0,0,1,0,1,1,0,1],(t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.ROTATE_ROW)&&(S[1]=[1,1,0,1,0,0,1,0]),(t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.FLIP_ROW)&&(S[1]=[1,0,0,0,0,1,1,1]),(t===mesh_Mesh.FLIP_N_ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_ROW)&&(S[1]=[0,1,1,1,1,0,0,0]);let C=[],E=[],y=[],R=0;for(let e=0;e<c;e++)for(let s=0;s<o;s++)b.push(-d+s*i+p,-_+e*r+f,0),b.push(-d+(s+1)*i+p,-_+e*r+f,0),b.push(-d+(s+1)*i+p,-_+(e+1)*r+f,0),b.push(-d+s*i+p,-_+(e+1)*r+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),C=t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_TILE?C.concat(S[(s%2+e%2)%2]):t===mesh_Mesh.FLIP_ROW||t===mesh_Mesh.ROTATE_ROW||t===mesh_Mesh.FLIP_N_ROTATE_ROW?C.concat(S[e%2]):C.concat(S[0]),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1),R+=4;if(l>0||u>0){let e,n,h,S;let P=u>0&&(a===mesh_Mesh.CENTER||a===mesh_Mesh.TOP),A=u>0&&(a===mesh_Mesh.CENTER||a===mesh_Mesh.BOTTOM),M=l>0&&(s===mesh_Mesh.CENTER||s===mesh_Mesh.RIGHT),I=l>0&&(s===mesh_Mesh.CENTER||s===mesh_Mesh.LEFT),D=[];if(P&&M&&(b.push(m+p,g+f,0),b.push(-d+p,g+f,0),b.push(-d+p,g+u+f,0),b.push(m+p,g+u+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,h=1,S=1,D=[e=1-l/i,n=1-u/r,h,n,h,S,e,S],t===mesh_Mesh.ROTATE_ROW&&(D=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),t===mesh_Mesh.FLIP_ROW&&(D=[1-e,n,1-h,n,1-h,S,1-e,S]),t===mesh_Mesh.FLIP_N_ROTATE_ROW&&(D=[e,1-n,h,1-n,h,1-S,e,1-S]),C=C.concat(D),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),P&&I&&(b.push(d+p,g+f,0),b.push(v+p,g+f,0),b.push(v+p,g+u+f,0),b.push(d+p,g+u+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,S=1,D=[e=0,n=1-u/r,h=l/i,n,h,S,e,S],(t===mesh_Mesh.ROTATE_ROW||t===mesh_Mesh.ROTATE_TILE&&o%2==0)&&(D=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_ROW||t===mesh_Mesh.FLIP_TILE&&o%2==0)&&(D=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_ROW||t===mesh_Mesh.FLIP_N_ROTATE_TILE&&o%2==0)&&(D=[e,1-n,h,1-n,h,1-S,e,1-S]),C=C.concat(D),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),A&&M&&(b.push(m+p,_+f,0),b.push(-d+p,_+f,0),b.push(-d+p,x+f,0),b.push(m+p,x+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,n=0,h=1,D=[e=1-l/i,n,h,n,h,S=u/r,e,S],(t===mesh_Mesh.ROTATE_ROW&&c%2==1||t===mesh_Mesh.ROTATE_TILE&&c%1==0)&&(D=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_ROW&&c%2==1||t===mesh_Mesh.FLIP_TILE&&c%2==0)&&(D=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_ROW&&c%2==1||t===mesh_Mesh.FLIP_N_ROTATE_TILE&&c%2==0)&&(D=[e,1-n,h,1-n,h,1-S,e,1-S]),C=C.concat(D),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),A&&I&&(b.push(d+p,_+f,0),b.push(v+p,_+f,0),b.push(v+p,x+f,0),b.push(d+p,x+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,D=[e=0,n=0,h=l/i,n,h,S=u/r,e,S],(t===mesh_Mesh.ROTATE_ROW&&c%2==1||t===mesh_Mesh.ROTATE_TILE&&(c+o)%2==1)&&(D=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_ROW&&c%2==1||t===mesh_Mesh.FLIP_TILE&&(c+o)%2==1)&&(D=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_ROW&&c%2==1||t===mesh_Mesh.FLIP_N_ROTATE_TILE&&(c+o)%2==1)&&(D=[e,1-n,h,1-n,h,1-S,e,1-S]),C=C.concat(D),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),P){let s=[];e=0,n=1-u/r,h=1,S=1,s[0]=[e,n,h,n,h,S,e,S],s[1]=[e,n,h,n,h,S,e,S],(t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.ROTATE_ROW)&&(s[1]=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.FLIP_ROW)&&(s[1]=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-n,h,1-n,h,1-S,e,1-S]);for(let e=0;e<o;e++)b.push(-d+e*i+p,g+f,0),b.push(-d+(e+1)*i+p,g+f,0),b.push(-d+(e+1)*i+p,g+u+f,0),b.push(-d+e*i+p,g+u+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,C=t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_TILE?C.concat(s[(e+1)%2]):t===mesh_Mesh.FLIP_ROW||t===mesh_Mesh.ROTATE_ROW||t===mesh_Mesh.FLIP_N_ROTATE_ROW?C.concat(s[1]):C.concat(s[0]),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(A){let s=[];e=0,n=0,h=1,S=u/r,s[0]=[e,n,h,n,h,S,e,S],s[1]=[e,n,h,n,h,S,e,S],(t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.ROTATE_ROW)&&(s[1]=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.FLIP_ROW)&&(s[1]=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-n,h,1-n,h,1-S,e,1-S]);for(let e=0;e<o;e++)b.push(-d+e*i+p,x-u+f,0),b.push(-d+(e+1)*i+p,x-u+f,0),b.push(-d+(e+1)*i+p,x+f,0),b.push(-d+e*i+p,x+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,C=t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_TILE?C.concat(s[(e+c)%2]):t===mesh_Mesh.FLIP_ROW||t===mesh_Mesh.ROTATE_ROW||t===mesh_Mesh.FLIP_N_ROTATE_ROW?C.concat(s[c%2]):C.concat(s[0]),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(M){let s=[];e=1-l/i,n=0,h=1,S=1,s[0]=[e,n,h,n,h,S,e,S],s[1]=[e,n,h,n,h,S,e,S],(t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.ROTATE_ROW)&&(s[1]=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.FLIP_ROW)&&(s[1]=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-n,h,1-n,h,1-S,e,1-S]);for(let e=0;e<c;e++)b.push(m+p,-_+e*r+f,0),b.push(m+l+p,-_+e*r+f,0),b.push(m+l+p,-_+(e+1)*r+f,0),b.push(m+p,-_+(e+1)*r+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,C=t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_TILE?C.concat(s[(e+1)%2]):t===mesh_Mesh.FLIP_ROW||t===mesh_Mesh.ROTATE_ROW||t===mesh_Mesh.FLIP_N_ROTATE_ROW?C.concat(s[e%2]):C.concat(s[0]),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(I){let i=[];e=0,n=0,h=l/r,S=1,i[0]=[e,n,h,n,h,S,e,S],i[1]=[e,n,h,n,h,S,e,S],(t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.ROTATE_ROW)&&(i[1]=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.FLIP_ROW)&&(i[1]=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_ROW)&&(i[1]=[e,1-n,h,1-n,h,1-S,e,1-S]);for(let e=0;e<c;e++)b.push(v-l+p,-_+e*r+f,0),b.push(v+p,-_+e*r+f,0),b.push(v+p,-_+(e+1)*r+f,0),b.push(v-l+p,-_+(e+1)*r+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,C=t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_TILE?C.concat(i[(e+o)%2]):t===mesh_Mesh.FLIP_ROW||t===mesh_Mesh.ROTATE_ROW||t===mesh_Mesh.FLIP_N_ROTATE_ROW?C.concat(i[e%2]):C.concat(i[0]),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}}let P=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE;mesh_vertexData_VertexData._ComputeSides(P,b,y,T,C,e.frontUVs,e.backUVs);let A=new mesh_vertexData_VertexData;A.indices=y,A.positions=b,A.normals=T,A.uvs=C;let M=P===mesh_vertexData_VertexData.DOUBLESIDE?E.concat(E):E;return A.colors=M,A}function CreateTiledBoxVertexData(e){let t=e.faceUV||Array(6),i=e.faceColors,r=e.pattern||mesh_Mesh.NO_FLIP,s=e.width||e.size||1,a=e.height||e.size||1,n=e.depth||e.size||1,o=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,c=e.alignVertical||0,u=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new math_vector_Vector4(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new math_color_Color4(1,1,1,1));let d=[];for(let e=0;e<2;e++)d[e]=CreateTiledPlaneVertexData({pattern:r,tileWidth:o,tileHeight:l,width:s,height:a,alignVertical:c,alignHorizontal:h,sideOrientation:u});for(let e=2;e<4;e++)d[e]=CreateTiledPlaneVertexData({pattern:r,tileWidth:o,tileHeight:l,width:n,height:a,alignVertical:c,alignHorizontal:h,sideOrientation:u});let _=c;c===mesh_Mesh.BOTTOM?_=mesh_Mesh.TOP:c===mesh_Mesh.TOP&&(_=mesh_Mesh.BOTTOM);for(let e=4;e<6;e++)d[e]=CreateTiledPlaneVertexData({pattern:r,tileWidth:o,tileHeight:l,width:s,height:n,alignVertical:_,alignHorizontal:h,sideOrientation:u});let p=[],f=[],m=[],g=[],v=[],x=[],b=[],T=[],S=0,C=0;for(let e=0;e<6;e++){let r=d[e].positions.length;x[e]=[],b[e]=[];for(let t=0;t<r/3;t++)x[e].push(new math_vector_Vector3(d[e].positions[3*t],d[e].positions[3*t+1],d[e].positions[3*t+2])),b[e].push(new math_vector_Vector3(d[e].normals[3*t],d[e].normals[3*t+1],d[e].normals[3*t+2]));S=d[e].uvs.length,T[e]=[];for(let i=0;i<S;i+=2)T[e][i]=t[e].x+(t[e].z-t[e].x)*d[e].uvs[i],T[e][i+1]=t[e].y+(t[e].w-t[e].y)*d[e].uvs[i+1],CompatibilityOptions.UseOpenGLOrientationForUV&&(T[e][i+1]=1-T[e][i+1]);if(m=m.concat(T[e]),g=g.concat(d[e].indices.map(e=>e+C)),C+=x[e].length,i)for(let t=0;t<4;t++)v.push(i[e].r,i[e].g,i[e].b,i[e].a)}let E=new math_vector_Vector3(0,0,n/2),y=math_vector_Matrix.RotationY(Math.PI);p=x[0].map(e=>math_vector_Vector3.TransformNormal(e,y).add(E)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),f=b[0].map(e=>math_vector_Vector3.TransformNormal(e,y)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),p=p.concat(x[1].map(e=>e.subtract(E)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(b[1].map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let R=new math_vector_Vector3(s/2,0,0),P=math_vector_Matrix.RotationY(-Math.PI/2);p=p.concat(x[2].map(e=>math_vector_Vector3.TransformNormal(e,P).add(R)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(b[2].map(e=>math_vector_Vector3.TransformNormal(e,P)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let A=math_vector_Matrix.RotationY(Math.PI/2);p=p.concat(x[3].map(e=>math_vector_Vector3.TransformNormal(e,A).subtract(R)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(b[3].map(e=>math_vector_Vector3.TransformNormal(e,A)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let M=new math_vector_Vector3(0,a/2,0),I=math_vector_Matrix.RotationX(Math.PI/2);p=p.concat(x[4].map(e=>math_vector_Vector3.TransformNormal(e,I).add(M)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(b[4].map(e=>math_vector_Vector3.TransformNormal(e,I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let D=math_vector_Matrix.RotationX(-Math.PI/2);p=p.concat(x[5].map(e=>math_vector_Vector3.TransformNormal(e,D).subtract(M)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(b[5].map(e=>math_vector_Vector3.TransformNormal(e,D)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),mesh_vertexData_VertexData._ComputeSides(u,p,g,f,m);let O=new mesh_vertexData_VertexData;if(O.indices=g,O.positions=p,O.normals=f,O.uvs=m,i){let e=u===mesh_vertexData_VertexData.DOUBLESIDE?v.concat(v):v;O.colors=e}return O}function CreateTorusKnotVertexData(e){let t,i;let r=[],s=[],a=[],n=[],o=e.radius||2,l=e.tube||.5,h=e.radialSegments||32,c=e.tubularSegments||32,u=e.p||2,d=e.q||3,_=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,getPos=e=>{let t=d/u*e,i=Math.cos(t),r=o*Math.sin(t)*.5;return new math_vector_Vector3(o*(2+i)*.5*Math.cos(e),o*(2+i)*Math.sin(e)*.5,r)};for(t=0;t<=h;t++){let e=t%h,r=e/h*2*u*Math.PI,a=getPos(r),o=getPos(r+.01),d=o.subtract(a),_=o.add(a),p=math_vector_Vector3.Cross(d,_);for(_=math_vector_Vector3.Cross(p,d),p.normalize(),_.normalize(),i=0;i<c;i++){let e=i%c,r=e/c*2*Math.PI,o=-l*Math.cos(r),u=l*Math.sin(r);s.push(a.x+o*_.x+u*p.x),s.push(a.y+o*_.y+u*p.y),s.push(a.z+o*_.z+u*p.z),n.push(t/h),n.push(CompatibilityOptions.UseOpenGLOrientationForUV?1-i/c:i/c)}}for(t=0;t<h;t++)for(i=0;i<c;i++){let e=(i+1)%c,s=t*c+i,a=(t+1)*c+i,n=(t+1)*c+e,o=t*c+e;r.push(o),r.push(a),r.push(s),r.push(o),r.push(n),r.push(a)}mesh_vertexData_VertexData.ComputeNormals(s,r,a),mesh_vertexData_VertexData._ComputeSides(_,s,r,a,n,e.frontUVs,e.backUVs);let p=new mesh_vertexData_VertexData;return p.indices=r,p.positions=s,p.normals=a,p.uvs=n,p}function CreateTorusKnot(e,t={},i){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateTorusKnotVertexData(t);return s.applyToMesh(r,t.updatable),r}DebugLayer.InspectorURL=`${tools_Tools._DefaultCdnUrl}/v${engine_Engine.Version}/inspector/babylon.inspector.bundle.js`,DebugLayer.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0},mesh_vertexData_VertexData.CreateBox=CreateBoxVertexData,mesh_Mesh.CreateBox=(e,t,i=null,r,s)=>boxBuilder_CreateBox(e,{size:t,sideOrientation:s,updatable:r},i),mesh_vertexData_VertexData.CreateSphere=CreateSphereVertexData,mesh_Mesh.CreateSphere=(e,t,i,r,s,a)=>sphereBuilder_CreateSphere(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:a,updatable:s},r),mesh_Mesh.CreateCapsule=(e,t,i)=>capsuleBuilder_CreateCapsule(e,t,i),mesh_vertexData_VertexData.CreateCapsule=CreateCapsuleVertexData,mesh_vertexData_VertexData.CreateRibbon=CreateRibbonVertexData,mesh_Mesh.CreateRibbon=(e,t,i=!1,r,s,a,n=!1,o,l)=>CreateRibbon(e,{pathArray:t,closeArray:i,closePath:r,offset:s,updatable:n,sideOrientation:o,instance:l},a),mesh_vertexData_VertexData.CreateDisc=CreateDiscVertexData,mesh_Mesh.CreateDisc=(e,t,i,r=null,s,a)=>discBuilder_CreateDisc(e,{radius:t,tessellation:i,sideOrientation:a,updatable:s},r),mesh_vertexData_VertexData.CreateTiledPlane=CreateTiledPlaneVertexData,mesh_vertexData_VertexData.CreateTiledBox=CreateTiledBoxVertexData,mesh_vertexData_VertexData.CreateTorusKnot=CreateTorusKnotVertexData,mesh_Mesh.CreateTorusKnot=(e,t,i,r,s,a,n,o,l,h)=>CreateTorusKnot(e,{radius:t,tube:i,radialSegments:r,tubularSegments:s,p:a,q:n,sideOrientation:h,updatable:l},o);let rb={effect:null,subMesh:null};let shaderMaterial_ShaderMaterial=class shaderMaterial_ShaderMaterial extends PushMaterial{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new math_vector_Matrix,this._cachedWorldViewProjectionMatrix=new math_vector_Matrix,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},r)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}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);let i=new Float32Array(16*t.length);for(let e=0;e<t.length;e++){let r=t[e];r.copyToArray(i,16*e)}return this._matrixArrays[e]=i,this}setMatrix3x3(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this}setMatrix2x2(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this}setArray2(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this}setArray3(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this}setArray4(e,t){return this._checkUniform(e),this._vectors4Arrays[e]=t,this}setUniformBuffer(e,t){return -1===this._options.uniformBuffers.indexOf(e)&&this._options.uniformBuffers.push(e),this._uniformBuffers[e]=t,this}setTextureSampler(e,t){return -1===this._options.samplerObjects.indexOf(e)&&this._options.samplerObjects.push(e),this._textureSamplers[e]=t,this}setStorageBuffer(e,t){return -1===this._options.storageBuffers.indexOf(e)&&this._options.storageBuffers.push(e),this._storageBuffers[e]=t,this}setDefine(e,t){let i=e.trimEnd()+" ",r=this.options.defines.findIndex(t=>t===e||t.startsWith(i));return r>=0&&this.options.defines.splice(r,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var r,s,a;let n=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){if(n){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{let e=this._drawWrapper.effect;if(e&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}}let o=this.getScene(),l=o.getEngine(),h=[],c=[],u=new EffectFallbacks,d=this._shaderPath,_=this._options.uniforms,p=this._options.uniformBuffers,f=this._options.samplers;l.getCaps().multiview&&o.activeCamera&&o.activeCamera.outputRenderTarget&&o.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,h.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let e=0;e<this._options.defines.length;e++){let t=0===this._options.defines[e].indexOf("#define")?this._options.defines[e]:`#define ${this._options.defines[e]}`;h.push(t)}for(let e=0;e<this._options.attributes.length;e++)c.push(this._options.attributes[e]);if(e&&e.isVerticesDataPresent(buffer_VertexBuffer.ColorKind)&&(-1===c.indexOf(buffer_VertexBuffer.ColorKind)&&c.push(buffer_VertexBuffer.ColorKind),h.push("#define VERTEXCOLOR")),t&&(h.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(c,this._materialHelperNeedsPreviousMatrices),(null==e?void 0:e.hasThinInstances)&&(h.push("#define THIN_INSTANCES"),e&&e.isVerticesDataPresent(buffer_VertexBuffer.ColorInstanceKind)&&(c.push(buffer_VertexBuffer.ColorInstanceKind),h.push("#define INSTANCESCOLOR")))),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){c.push(buffer_VertexBuffer.MatricesIndicesKind),c.push(buffer_VertexBuffer.MatricesWeightsKind),e.numBoneInfluencers>4&&(c.push(buffer_VertexBuffer.MatricesIndicesExtraKind),c.push(buffer_VertexBuffer.MatricesWeightsExtraKind));let t=e.skeleton;h.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),u.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(h.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")):(h.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else h.push("#define NUM_BONE_INFLUENCERS 0");let m=0,g=e?e.morphTargetManager:null;if(g){let e=g.supportsUVs&&-1!==h.indexOf("#define UV1"),t=g.supportsTangents&&-1!==h.indexOf("#define TANGENT"),i=g.supportsNormals&&-1!==h.indexOf("#define NORMAL");m=g.numInfluencers,e&&h.push("#define MORPHTARGETS_UV"),t&&h.push("#define MORPHTARGETS_TANGENT"),i&&h.push("#define MORPHTARGETS_NORMAL"),m>0&&h.push("#define MORPHTARGETS"),g.isUsingTextureForTargets&&(h.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")),h.push("#define NUM_MORPH_INFLUENCERS "+m);for(let r=0;r<m;r++)c.push(buffer_VertexBuffer.PositionKind+r),i&&c.push(buffer_VertexBuffer.NormalKind+r),t&&c.push(buffer_VertexBuffer.TangentKind+r),e&&c.push(buffer_VertexBuffer.UVKind+"_"+r);m>0&&((_=_.slice()).push("morphTargetInfluences"),_.push("morphTargetTextureInfo"),_.push("morphTargetTextureIndices"))}else h.push("#define NUM_MORPH_INFLUENCERS 0");if(e){let t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(h.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")),MaterialHelper.PrepareAttributesForBakedVertexAnimation(c,e,h)}for(let e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&h.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(addClipPlaneUniforms(_),prepareStringDefinesForClipPlanes(this,o,h)),this.customShaderNameResolve&&(_=_.slice(),p=p.slice(),f=f.slice(),d=this.customShaderNameResolve(d,_,p,f,h,c));let v=n?i._getDrawWrapper():this._drawWrapper,x=null!==(r=null==v?void 0:v.effect)&&void 0!==r?r:null,b=null!==(s=null==v?void 0:v.defines)&&void 0!==s?s:null,T=h.join("\n"),S=x;return b!==T&&(S=l.createEffect(d,{attributes:c,uniformsNames:_,uniformBuffersNames:p,samplers:f,defines:T,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage},l),n?i.setEffect(S,T,this._materialContext):v&&v.setEffect(S,T),this._onEffectCreatedObservable&&(rb.effect=S,rb.subMesh=null!==(a=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==a?a:null,this._onEffectCreatedObservable.notifyObservers(rb))),S._wasPreviouslyUsingInstances=!!t,!!(null==S?void 0:S.isReady())&&(x!==S&&o.resetCachedMaterial(),S._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){let i=this.getScene(),r=null!=t?t:this.getEffect();r&&(-1!==this._options.uniforms.indexOf("world")&&r.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var r;this.bind(e,t,null===(r=i._drawWrapperOverride)||void 0===r?void 0:r.effect,i)}bind(e,t,i,r){var s;let a=r&&this._storeEffectOnSubMeshes,n=null!=i?i:a?r.effect:this.getEffect();if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);let o=this._options.uniformBuffers,l=!1;if(n&&o&&o.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let i=0;i<o.length;++i){let r=o[i];switch(r){case"Mesh":t&&(t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e));break;case"Scene":MaterialHelper.BindSceneUniformBuffer(n,this.getScene().getSceneUniformBuffer()),this.getScene().finalizeSceneUbo(),l=!0}}let h=t&&a?this._mustRebind(this.getScene(),n,t.visibility):this.getScene().getCachedMaterial()!==this;if(n&&h){let e;for(e in l||-1===this._options.uniforms.indexOf("view")||n.setMatrix("view",this.getScene().getViewMatrix()),l||-1===this._options.uniforms.indexOf("projection")||n.setMatrix("projection",this.getScene().getProjectionMatrix()),!l&&-1!==this._options.uniforms.indexOf("viewProjection")&&(n.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._multiview&&n.setMatrix("viewProjectionR",this.getScene()._transformMatrixR)),this.getScene().activeCamera&&-1!==this._options.uniforms.indexOf("cameraPosition")&&n.setVector3("cameraPosition",this.getScene().activeCamera.globalPosition),MaterialHelper.BindBonesParameters(t,n),bindClipPlane(n,this,this.getScene()),this._textures)n.setTexture(e,this._textures[e]);for(e in this._textureArrays)n.setTextureArray(e,this._textureArrays[e]);for(e in this._externalTextures)n.setExternalTexture(e,this._externalTextures[e]);for(e in this._ints)n.setInt(e,this._ints[e]);for(e in this._uints)n.setUInt(e,this._uints[e]);for(e in this._floats)n.setFloat(e,this._floats[e]);for(e in this._floatsArrays)n.setArray(e,this._floatsArrays[e]);for(e in this._colors3)n.setColor3(e,this._colors3[e]);for(e in this._colors3Arrays)n.setArray3(e,this._colors3Arrays[e]);for(e in this._colors4){let t=this._colors4[e];n.setFloat4(e,t.r,t.g,t.b,t.a)}for(e in this._colors4Arrays)n.setArray4(e,this._colors4Arrays[e]);for(e in this._vectors2)n.setVector2(e,this._vectors2[e]);for(e in this._vectors3)n.setVector3(e,this._vectors3[e]);for(e in this._vectors4)n.setVector4(e,this._vectors4[e]);for(e in this._quaternions)n.setQuaternion(e,this._quaternions[e]);for(e in this._matrices)n.setMatrix(e,this._matrices[e]);for(e in this._matrixArrays)n.setMatrices(e,this._matrixArrays[e]);for(e in this._matrices3x3)n.setMatrix3x3(e,this._matrices3x3[e]);for(e in this._matrices2x2)n.setMatrix2x2(e,this._matrices2x2[e]);for(e in this._vectors2Arrays)n.setArray2(e,this._vectors2Arrays[e]);for(e in this._vectors3Arrays)n.setArray3(e,this._vectors3Arrays[e]);for(e in this._vectors4Arrays)n.setArray4(e,this._vectors4Arrays[e]);for(e in this._quaternionsArrays)n.setArray4(e,this._quaternionsArrays[e]);for(e in this._uniformBuffers){let t=this._uniformBuffers[e].getBuffer();t&&n.bindUniformBuffer(t,e)}for(e in this._textureSamplers)n.setTextureSampler(e,this._textureSamplers[e]);for(e in this._storageBuffers)n.setStorageBuffer(e,this._storageBuffers[e])}if(n&&t&&(h||!this.isFrozen)){let e=t.morphTargetManager;e&&e.numInfluencers>0&&MaterialHelper.BindMorphTargetParameters(t,n);let i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(n,!!n._wasPreviouslyUsingInstances))}this._afterBind(t,n)}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._textures)e.push(this._textures[t]);for(let t in this._textureArrays){let i=this._textureArrays[t];for(let t=0;t<i.length;t++)e.push(i[t])}return e}hasTexture(e){if(super.hasTexture(e))return!0;for(let t in this._textures)if(this._textures[t]===e)return!0;for(let t in this._textureArrays){let i=this._textureArrays[t];for(let t=0;t<i.length;t++)if(i[t]===e)return!0}return!1}clone(e){let t=decorators_SerializationHelper.Clone(()=>new shaderMaterial_ShaderMaterial(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);for(let i in 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=>{let t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))}),this.stencil.copyTo(t.stencil),this._textures)t.setTexture(i,this._textures[i]);for(let e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(let e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(let e in this._ints)t.setInt(e,this._ints[e]);for(let e in this._uints)t.setUInt(e,this._uints[e]);for(let e in this._floats)t.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(let e in this._colors3)t.setColor3(e,this._colors3[e]);for(let e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(let e in this._colors4)t.setColor4(e,this._colors4[e]);for(let e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(let e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(let e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(let e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(let e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(let e in this._matrices)t.setMatrix(e,this._matrices[e]);for(let e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(let e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(let e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(let e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(let e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(let e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(let e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(let e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(let e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){let t=this._textureArrays[e];for(let e=0;e<t.length;e++)t[e].dispose()}}this._textures={},super.dispose(e,t,i)}serialize(){let e;let t=decorators_SerializationHelper.Serialize(this);for(e in t.customType="BABYLON.ShaderMaterial",t.uniqueId=this.uniqueId,t.options=this._options,t.shaderPath=this._shaderPath,t.storeEffectOnSubMeshes=this._storeEffectOnSubMeshes,t.stencil=this.stencil.serialize(),t.textures={},this._textures)t.textures[e]=this._textures[e].serialize();for(e in t.textureArrays={},this._textureArrays){t.textureArrays[e]=[];let i=this._textureArrays[e];for(let r=0;r<i.length;r++)t.textureArrays[e].push(i[r].serialize())}for(e in t.ints={},this._ints)t.ints[e]=this._ints[e];for(e in t.uints={},this._uints)t.uints[e]=this._uints[e];for(e in t.floats={},this._floats)t.floats[e]=this._floats[e];for(e in t.FloatArrays={},this._floatsArrays)t.FloatArrays[e]=this._floatsArrays[e];for(e in t.colors3={},this._colors3)t.colors3[e]=this._colors3[e].asArray();for(e in t.colors3Arrays={},this._colors3Arrays)t.colors3Arrays[e]=this._colors3Arrays[e];for(e in t.colors4={},this._colors4)t.colors4[e]=this._colors4[e].asArray();for(e in t.colors4Arrays={},this._colors4Arrays)t.colors4Arrays[e]=this._colors4Arrays[e];for(e in t.vectors2={},this._vectors2)t.vectors2[e]=this._vectors2[e].asArray();for(e in t.vectors3={},this._vectors3)t.vectors3[e]=this._vectors3[e].asArray();for(e in t.vectors4={},this._vectors4)t.vectors4[e]=this._vectors4[e].asArray();for(e in t.quaternions={},this._quaternions)t.quaternions[e]=this._quaternions[e].asArray();for(e in t.matrices={},this._matrices)t.matrices[e]=this._matrices[e].asArray();for(e in t.matrixArray={},this._matrixArrays)t.matrixArray[e]=this._matrixArrays[e];for(e in t.matrices3x3={},this._matrices3x3)t.matrices3x3[e]=this._matrices3x3[e];for(e in t.matrices2x2={},this._matrices2x2)t.matrices2x2[e]=this._matrices2x2[e];for(e in t.vectors2Arrays={},this._vectors2Arrays)t.vectors2Arrays[e]=this._vectors2Arrays[e];for(e in t.vectors3Arrays={},this._vectors3Arrays)t.vectors3Arrays[e]=this._vectors3Arrays[e];for(e in t.vectors4Arrays={},this._vectors4Arrays)t.vectors4Arrays[e]=this._vectors4Arrays[e];for(e in t.quaternionsArrays={},this._quaternionsArrays)t.quaternionsArrays[e]=this._quaternionsArrays[e];return t}static Parse(e,t,i){let r;let s=decorators_SerializationHelper.Parse(()=>new shaderMaterial_ShaderMaterial(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,texture_Texture.Parse(e.textures[r],t,i));for(r in e.textureArrays){let a=e.textureArrays[r],n=[];for(let e=0;e<a.length;e++)n.push(texture_Texture.Parse(a[e],t,i));s.setTextureArray(r,n)}for(r in e.ints)s.setInt(r,e.ints[r]);for(r in e.uints)s.setUInt(r,e.uints[r]);for(r in e.floats)s.setFloat(r,e.floats[r]);for(r in e.floatsArrays)s.setFloats(r,e.floatsArrays[r]);for(r in e.colors3)s.setColor3(r,math_color_Color3.FromArray(e.colors3[r]));for(r in e.colors3Arrays){let t=e.colors3Arrays[r].reduce((e,t,i)=>(i%3==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>math_color_Color3.FromArray(e));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,math_color_Color4.FromArray(e.colors4[r]));for(r in e.colors4Arrays){let t=e.colors4Arrays[r].reduce((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>math_color_Color4.FromArray(e));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,math_vector_Vector2.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,math_vector_Vector3.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,math_vector_Vector4.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,math_vector_Quaternion.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,math_vector_Matrix.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,a)=>{let n=new webRequest_WebRequest;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let t=JSON.parse(n.responseText),a=this.Parse(t,i||engineStore_EngineStore.LastCreatedScene,r);e&&(a.name=e),s(a)}else a("Unable to load the ShaderMaterial")}}),n.open("GET",t),n.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((r,s)=>{let a=new webRequest_WebRequest;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let s=JSON.parse(JSON.parse(a.responseText).jsonPayload),n=JSON.parse(s.shaderMaterial),o=this.Parse(n,t||engineStore_EngineStore.LastCreatedScene,i);o.snippetId=e,r(o)}else s("Unable to load the snippet "+e)}}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}};shaderMaterial_ShaderMaterial.SnippetUrl="https://snippet.babylonjs.com",shaderMaterial_ShaderMaterial.CreateFromSnippetAsync=shaderMaterial_ShaderMaterial.ParseFromSnippetAsync,h["BABYLON.ShaderMaterial"]=shaderMaterial_ShaderMaterial;let rT=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +#define VERTEXCOLOR +varying vec4 vColor; +#else +uniform vec4 color; +#endif +#include<clipPlaneFragmentDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +gl_FragColor=vColor; +#else +gl_FragColor=color; +#endif +#define CUSTOM_FRAGMENT_MAIN_END +}`;ShaderStore.ShadersStore.colorPixelShader=rT;let rS=`attribute vec3 position; +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<clipPlaneVertexDeclaration> +#include<instancesDeclaration> +uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(position,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#include<clipPlaneVertex> +#include<vertexColorMixing> +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.colorVertexShader=rS,mesh_Mesh._LinesMeshParser=(e,t)=>LinesMesh.Parse(e,t);let LinesMesh=class LinesMesh extends mesh_Mesh{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,r=null,s,a,n,o){super(e,t,i,r,s),this.useVertexColor=a,this.useVertexAlpha=n,this.color=new math_color_Color3(1,1,1),this.alpha=1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;let l={attributes:[buffer_VertexBuffer.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===n?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),a?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(buffer_VertexBuffer.ColorKind)):(l.uniforms.push("color"),this._color4=new math_color_Color4),o?this.material=o:(this.material=new shaderMaterial_ShaderMaterial("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=material_Material.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;let i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){let{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;let r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(material_Material.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(material_Material.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 LinesMesh(e,this.getScene(),t,this,i)}createInstance(e){let t=new InstancedLinesMesh(e,this);if(this.instancedBuffers)for(let e in t.instancedBuffers={},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){let i=new LinesMesh(e.name,t);return i.color=math_color_Color3.FromArray(e.color),i.alpha=e.alpha,i}};let InstancedLinesMesh=class InstancedLinesMesh extends instancedMesh_InstancedMesh{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}};function CreateLineSystemVertexData(e){let t=[],i=[],r=e.lines,s=e.colors,a=[],n=0;for(let e=0;e<r.length;e++){let o=r[e];for(let r=0;r<o.length;r++){if(i.push(o[r].x,o[r].y,o[r].z),s){let t=s[e];a.push(t[r].r,t[r].g,t[r].b,t[r].a)}r>0&&(t.push(n-1),t.push(n)),n++}}let o=new mesh_vertexData_VertexData;return o.indices=t,o.positions=i,s&&(o.colors=a),o}function CreateDashedLinesVertexData(e){let t=e.dashSize||3,i=e.gapSize||1,r=e.dashNb||200,s=e.points,a=[],n=[],o=math_vector_Vector3.Zero(),l=0,h=0,c=0,u=0,d=0,_=0,p=0;for(p=0;p<s.length-1;p++)s[p+1].subtractToRef(s[p],o),l+=o.length();for(p=0,u=t*(c=l/r)/(t+i);p<s.length-1;p++){s[p+1].subtractToRef(s[p],o),h=Math.floor(o.length()/c),o.normalize();for(let e=0;e<h;e++)d=c*e,a.push(s[p].x+d*o.x,s[p].y+d*o.y,s[p].z+d*o.z),a.push(s[p].x+(d+u)*o.x,s[p].y+(d+u)*o.y,s[p].z+(d+u)*o.z),n.push(_,_+1),_+=2}let f=new mesh_vertexData_VertexData;return f.positions=a,f.indices=n,f}function CreateLineSystem(e,t,i=null){let r=t.instance,s=t.lines,a=t.colors;if(r){let e,t;let i=r.getVerticesData(buffer_VertexBuffer.PositionKind);a&&(e=r.getVerticesData(buffer_VertexBuffer.ColorKind));let n=0,o=0;for(let r=0;r<s.length;r++){let l=s[r];for(let s=0;s<l.length;s++)i[n]=l[s].x,i[n+1]=l[s].y,i[n+2]=l[s].z,a&&e&&(t=a[r],e[o]=t[s].r,e[o+1]=t[s].g,e[o+2]=t[s].b,e[o+3]=t[s].a,o+=4),n+=3}return r.updateVerticesData(buffer_VertexBuffer.PositionKind,i,!1,!1),a&&e&&r.updateVerticesData(buffer_VertexBuffer.ColorKind,e,!1,!1),r}let n=new LinesMesh(e,i,null,void 0,void 0,!!a,t.useVertexAlpha,t.material),o=CreateLineSystemVertexData(t);return o.applyToMesh(n,t.updatable),n}function linesBuilder_CreateLines(e,t,i=null){let r=t.colors?[t.colors]:null,s=CreateLineSystem(e,{lines:[t.points],updatable:t.updatable,instance:t.instance,colors:r,useVertexAlpha:t.useVertexAlpha,material:t.material},i);return s}function CreateDashedLines(e,t,i=null){let r=t.points,s=t.instance,a=t.gapSize||1,n=t.dashSize||3;if(s)return(t.dashNb||t.dashSize||t.gapSize||t.useVertexAlpha||t.material)&&logger_Logger.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."),s.updateMeshPositions(e=>{let t=math_vector_Vector3.Zero(),i=e.length/6,a=0,n=0,o=0,l=0,h=0,c=0,u=0,d=0;for(u=0;u<r.length-1;u++)r[u+1].subtractToRef(r[u],t),a+=t.length();o=a/i;let _=s._creationDataStorage.dashSize,p=s._creationDataStorage.gapSize;for(u=0,l=_*o/(_+p);u<r.length-1;u++)for(r[u+1].subtractToRef(r[u],t),n=Math.floor(t.length()/o),t.normalize(),d=0;d<n&&c<e.length;)h=o*d,e[c]=r[u].x+h*t.x,e[c+1]=r[u].y+h*t.y,e[c+2]=r[u].z+h*t.z,e[c+3]=r[u].x+(h+l)*t.x,e[c+4]=r[u].y+(h+l)*t.y,e[c+5]=r[u].z+(h+l)*t.z,c+=6,d++;for(;c<e.length;)e[c]=r[u].x,e[c+1]=r[u].y,e[c+2]=r[u].z,c+=3},!1),s;let o=new LinesMesh(e,i,null,void 0,void 0,void 0,t.useVertexAlpha,t.material),l=CreateDashedLinesVertexData(t);return l.applyToMesh(o,t.updatable),o._creationDataStorage=new _CreationDataStorage,o._creationDataStorage.dashSize=n,o._creationDataStorage.gapSize=a,o}mesh_vertexData_VertexData.CreateLineSystem=CreateLineSystemVertexData,mesh_vertexData_VertexData.CreateDashedLines=CreateDashedLinesVertexData,mesh_Mesh.CreateLines=(e,t,i=null,r=!1,s=null)=>linesBuilder_CreateLines(e,{points:t,updatable:r,instance:s},i),mesh_Mesh.CreateDashedLines=(e,t,i,r,s,a=null,n,o)=>CreateDashedLines(e,{points:t,dashSize:i,gapSize:r,dashNb:s,updatable:n,instance:o},a);let IndexedVector2=class IndexedVector2 extends math_vector_Vector2{constructor(e,t){super(e.x,e.y),this.index=t}};let PolygonPoints=class PolygonPoints{constructor(){this.elements=[]}add(e){let t=[];return e.forEach(e=>{let i=new IndexedVector2(e,this.elements.length);t.push(i),this.elements.push(i)}),t}computeBounds(){let e=new math_vector_Vector2(this.elements[0].x,this.elements[0].y),t=new math_vector_Vector2(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.x<e.x?e.x=i.x:i.x>t.x&&(t.x=i.x),i.y<e.y?e.y=i.y:i.y>t.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}};let PolygonMeshBuilder=class PolygonMeshBuilder{_addToepoint(e){for(let t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){let s;this._points=new PolygonPoints,this._outlinepoints=new PolygonPoints,this._holes=[],this._epoints=[],this._eholes=[],this.bjsEarcut=r,this._name=e,this._scene=i||engineStore_EngineStore.LastCreatedScene,s=t instanceof math_path_Path2?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&logger_Logger.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);let t=new PolygonPoints;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){let r=new mesh_Mesh(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(buffer_VertexBuffer.PositionKind,s.positions,e),r.setVerticesData(buffer_VertexBuffer.NormalKind,s.normals,e),r.setVerticesData(buffer_VertexBuffer.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){let i=new mesh_vertexData_VertexData,r=[],s=[],a=[],n=this._points.computeBounds();this._points.elements.forEach(e=>{r.push(0,1,0),s.push(e.x,0,e.y),a.push((e.x-n.min.x)/n.width,(e.y-n.min.y)/n.height)});let o=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e<l.length;e++)o.push(l[e]);if(e>0){let i=s.length/3;this._points.elements.forEach(t=>{r.push(0,-1,0),s.push(t.x,-e,t.y),a.push(1-(t.x-n.min.x)/n.width,1-(t.y-n.min.y)/n.height)});let l=o.length;for(let e=0;e<l;e+=3){let t=o[e+0],r=o[e+1],s=o[e+2];o.push(s+i),o.push(r+i),o.push(t+i)}this._addSide(s,r,a,o,n,this._outlinepoints,e,!1,t),this._holes.forEach(i=>{this._addSide(s,r,a,o,n,i,e,!0,t)})}return i.indices=o,i.positions=s,i.normals=r,i.uvs=a,i}_addSide(e,t,i,r,s,a,n,o,l){let h=e.length/3,c=0;for(let u=0;u<a.elements.length;u++){let d=a.elements[u],_=a.elements[(u+1)%a.elements.length];e.push(d.x,0,d.y),e.push(d.x,-n,d.y),e.push(_.x,0,_.y),e.push(_.x,-n,_.y);let p=a.elements[(u+a.elements.length-1)%a.elements.length],f=a.elements[(u+2)%a.elements.length],m=new math_vector_Vector3(-(_.y-d.y),0,_.x-d.x),g=new math_vector_Vector3(-(d.y-p.y),0,d.x-p.x),v=new math_vector_Vector3(-(f.y-_.y),0,f.x-_.x);o||(m=m.scale(-1),g=g.scale(-1),v=v.scale(-1));let x=m.normalizeToNew(),b=g.normalizeToNew(),T=v.normalizeToNew(),S=math_vector_Vector3.Dot(b,x);b=S>l?S<-.999?new math_vector_Vector3(d.x,0,d.y).subtract(new math_vector_Vector3(_.x,0,_.y)).normalize():g.add(m).normalize():x;let C=math_vector_Vector3.Dot(v,m);T=C>l?C<-.999?new math_vector_Vector3(_.x,0,_.y).subtract(new math_vector_Vector3(d.x,0,d.y)).normalize():v.add(m).normalize():x,i.push(c/s.width,0),i.push(c/s.width,1),c+=m.length(),i.push(c/s.width,0),i.push(c/s.width,1),t.push(b.x,b.y,b.z),t.push(b.x,b.y,b.z),t.push(T.x,T.y,T.z),t.push(T.x,T.y,T.z),o?(r.push(h),r.push(h+2),r.push(h+1),r.push(h+1),r.push(h+2),r.push(h+3)):(r.push(h),r.push(h+1),r.push(h+2),r.push(h+1),r.push(h+3),r.push(h+2)),h+=4}}};function CreatePolygonVertexData(e,t,i,r,s,a,n){let o=i||[,,,],l=[],h=n||!1;for(let e=0;e<3;e++)void 0===o[e]&&(o[e]=new math_vector_Vector4(0,0,1,1)),r&&void 0===r[e]&&(r[e]=new math_color_Color4(1,1,1,1));let c=e.getVerticesData(buffer_VertexBuffer.PositionKind),u=e.getVerticesData(buffer_VertexBuffer.NormalKind),d=e.getVerticesData(buffer_VertexBuffer.UVKind),_=e.getIndices(),p=c.length/9,f=0,m=0,g=0,v=0,x=[0];if(h)for(let e=p;e<c.length/3;e+=4)x.push(v+=Math.sqrt((m=c[3*(e+2)]-c[3*e])*m+(g=c[3*(e+2)+2]-c[3*e+2])*g));let b=0,T=0;for(let e=0;e<u.length;e+=3).001>Math.abs(u[e+1])&&(T=1),.001>Math.abs(u[e+1]-1)&&(T=0),.001>Math.abs(u[e+1]+1)&&(T=2),b=e/3,1===T?((f=b-p)%4<1.5?h?d[2*b]=o[T].x+(o[T].z-o[T].x)*x[Math.floor(f/4)]/v:d[2*b]=o[T].x:h?d[2*b]=o[T].x+(o[T].z-o[T].x)*x[Math.floor(f/4)+1]/v:d[2*b]=o[T].z,f%2==0?d[2*b+1]=CompatibilityOptions.UseOpenGLOrientationForUV?1-o[T].w:o[T].w:d[2*b+1]=CompatibilityOptions.UseOpenGLOrientationForUV?1-o[T].y:o[T].y):(d[2*b]=(1-d[2*b])*o[T].x+d[2*b]*o[T].z,d[2*b+1]=(1-d[2*b+1])*o[T].y+d[2*b+1]*o[T].w,CompatibilityOptions.UseOpenGLOrientationForUV&&(d[2*b+1]=1-d[2*b+1])),r&&l.push(r[T].r,r[T].g,r[T].b,r[T].a);mesh_vertexData_VertexData._ComputeSides(t,c,_,u,d,s,a);let S=new mesh_vertexData_VertexData;if(S.indices=_,S.positions=c,S.normals=u,S.uvs=d,r){let e=t===mesh_vertexData_VertexData.DOUBLESIDE?l.concat(l):l;S.colors=e}return S}function CreatePolygon(e,t,i=null,r=earcut){t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation);let s=t.shape,a=t.holes||[],n=t.depth||0,o=t.smoothingThreshold||2,l=[],h=[];for(let e=0;e<s.length;e++)l[e]=new math_vector_Vector2(s[e].x,s[e].z);l[0].equalsWithEpsilon(l[l.length-1],1e-8)&&l.pop();let c=new PolygonMeshBuilder(e,l,i||engineStore_EngineStore.LastCreatedScene,r);for(let e=0;e<a.length;e++){h=[];for(let t=0;t<a[e].length;t++)h.push(new math_vector_Vector2(a[e][t].x,a[e][t].z));c.addHole(h)}let u=c.build(!1,n,o);u._originalBuilderSideOrientation=t.sideOrientation;let d=CreatePolygonVertexData(u,t.sideOrientation,t.faceUV,t.faceColors,t.frontUVs,t.backUVs,t.wrap);return d.applyToMesh(u,t.updatable),u}function ExtrudePolygon(e,t,i=null,r=earcut){return CreatePolygon(e,t,i,r)}function ExtrudeShape(e,t,i=null){let r=t.path,s=t.shape,a=t.scale||1,n=t.rotation||0,o=0===t.cap?0:t.cap||mesh_Mesh.NO_CAP,l=t.updatable,h=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),c=t.instance||null,u=t.invertUV||!1,d=t.closeShape||!1,_=t.closePath||!1;return _ExtrudeShapeGeneric(e,s,r,a,n,null,null,_,d,o,!1,i,!!l,h,c,u,t.frontUVs||null,t.backUVs||null,t.firstNormal||null,!!t.adjustFrame)}function ExtrudeShapeCustom(e,t,i=null){let r=t.path,s=t.shape,a=t.scaleFunction||(()=>1),n=t.rotationFunction||(()=>0),o=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||mesh_Mesh.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1,_=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),p=t.instance,f=t.invertUV||!1;return _ExtrudeShapeGeneric(e,s,r,null,null,a,n,o,l,h,!0,i,!!c,_,p||null,f,t.frontUVs||null,t.backUVs||null,u,d)}function _ExtrudeShapeGeneric(e,t,i,r,s,a,n,o,l,h,c,u,d,_,p,f,m,g,v,x){let b,T;let extrusionPathArray=(e,t,i,r,s,a,n,o,l,h,c)=>{let u=i.getTangents(),d=i.getNormals(),_=i.getBinormals(),p=i.getDistances();if(c){for(let e=0;e<u.length;e++)if(0==u[e].x&&0==u[e].y&&0==u[e].z&&u[e].copyFrom(u[e-1]),0==d[e].x&&0==d[e].y&&0==d[e].z&&d[e].copyFrom(d[e-1]),0==_[e].x&&0==_[e].y&&0==_[e].z&&_[e].copyFrom(_[e-1]),e>0){let t=u[e-1];0>math_vector_Vector3.Dot(t,u[e])&&u[e].scaleInPlace(-1),t=d[e-1],0>math_vector_Vector3.Dot(t,d[e])&&d[e].scaleInPlace(-1),t=_[e-1],0>math_vector_Vector3.Dot(t,_[e])&&_[e].scaleInPlace(-1)}}let f=0,m=h&&o?o:()=>null!==a?a:0,g=h&&n?n:()=>null!==s?s:1,v=l===mesh_Mesh.NO_CAP||l===mesh_Mesh.CAP_END?0:2,x=math_vector_TmpVectors.Matrix[0];for(let i=0;i<t.length;i++){let s=[],a=m(i,p[i]),n=g(i,p[i]);math_vector_Matrix.RotationAxisToRef(u[i],f,x);for(let r=0;r<e.length;r++){let a=u[i].scale(e[r].z).add(d[i].scale(e[r].x)).add(_[i].scale(e[r].y)),o=math_vector_Vector3.Zero();math_vector_Vector3.TransformCoordinatesToRef(a,x,o),o.scaleInPlace(n).addInPlace(t[i]),s[r]=o}r[v]=s,f+=a,v++}let capPath=e=>{let t;let i=[],r=math_vector_Vector3.Zero();for(t=0;t<e.length;t++)r.addInPlace(e[t]);for(r.scaleInPlace(1/e.length),t=0;t<e.length;t++)i.push(r);return i};switch(l){case mesh_Mesh.NO_CAP:break;case mesh_Mesh.CAP_START:r[0]=capPath(r[2]),r[1]=r[2];break;case mesh_Mesh.CAP_END:r[v]=r[v-1],r[v+1]=capPath(r[v-1]);break;case mesh_Mesh.CAP_ALL:r[0]=capPath(r[2]),r[1]=r[2],r[v]=r[v-1],r[v+1]=capPath(r[v-1])}return r};if(p){let e=p._creationDataStorage;return b=v?e.path3D.update(i,v):e.path3D.update(i),p=CreateRibbon("",{pathArray:T=extrusionPathArray(t,i,e.path3D,e.pathArray,r,s,a,n,e.cap,c,x),closeArray:!1,closePath:!1,offset:0,updatable:!1,sideOrientation:0,instance:p},u||void 0)}b=v?new Path3D(i,v):new Path3D(i),T=extrusionPathArray(t,i,b,[],r,s,a,n,h=h<0||h>3?0:h,c,x);let S=CreateRibbon(e,{pathArray:T,closeArray:o,closePath:l,updatable:d,sideOrientation:_,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},u);return S._creationDataStorage.pathArray=T,S._creationDataStorage.path3D=b,S._creationDataStorage.cap=h,S}function CreateLathe(e,t,i=null){let r,s;let a=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,n=void 0===t.closed||t.closed,o=t.shape,l=t.radius||1,h=t.tessellation||64,c=t.clip||0,u=t.updatable,d=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),_=t.cap||mesh_Mesh.NO_CAP,p=[],f=t.invertUV||!1,m=0,g=0,v=2*Math.PI/h*a;for(m=0;m<=h-c;m++){for(s=[],(_==mesh_Mesh.CAP_START||_==mesh_Mesh.CAP_ALL)&&(s.push(new math_vector_Vector3(0,o[0].y,0)),s.push(new math_vector_Vector3(Math.cos(m*v)*o[0].x*l,o[0].y,Math.sin(m*v)*o[0].x*l))),g=0;g<o.length;g++)r=new math_vector_Vector3(Math.cos(m*v)*o[g].x*l,o[g].y,Math.sin(m*v)*o[g].x*l),s.push(r);(_==mesh_Mesh.CAP_END||_==mesh_Mesh.CAP_ALL)&&(s.push(new math_vector_Vector3(Math.cos(m*v)*o[o.length-1].x*l,o[o.length-1].y,Math.sin(m*v)*o[o.length-1].x*l)),s.push(new math_vector_Vector3(0,o[o.length-1].y,0))),p.push(s)}let x=CreateRibbon(e,{pathArray:p,closeArray:n,sideOrientation:d,updatable:u,invertUV:f,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return x}function CreateTube(e,t,i=null){let r,s;let a=t.path,n=t.instance,o=1;void 0!==t.radius?o=t.radius:n&&(o=n._creationDataStorage.radius);let l=t.tessellation||64,h=t.radiusFunction||null,c=t.cap||mesh_Mesh.NO_CAP,u=t.invertUV||!1,d=t.updatable,_=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;let tubePathArray=(e,t,i,r,s,a,n,o)=>{let l,h,c,u;let d=t.getTangents(),_=t.getNormals(),p=t.getDistances(),f=2*Math.PI/s*o,m=a||(()=>r),g=math_vector_TmpVectors.Matrix[0],v=n===mesh_Mesh.NO_CAP||n===mesh_Mesh.CAP_END?0:2;for(let t=0;t<e.length;t++){h=m(t,p[t]),l=[],c=_[t];for(let i=0;i<s;i++)math_vector_Matrix.RotationAxisToRef(d[t],f*i,g),u=l[i]?l[i]:math_vector_Vector3.Zero(),math_vector_Vector3.TransformCoordinatesToRef(c,g,u),u.scaleInPlace(h).addInPlace(e[t]),l[i]=u;i[v]=l,v++}let capPath=(t,i)=>{let r=[];for(let s=0;s<t;s++)r.push(e[i]);return r};switch(n){case mesh_Mesh.NO_CAP:break;case mesh_Mesh.CAP_START:i[0]=capPath(s,0),i[1]=i[2].slice(0);break;case mesh_Mesh.CAP_END:i[v]=i[v-1].slice(0),i[v+1]=capPath(s,e.length-1);break;case mesh_Mesh.CAP_ALL:i[0]=capPath(s,0),i[1]=i[2].slice(0),i[v]=i[v-1].slice(0),i[v+1]=capPath(s,e.length-1)}return i};if(n){let e=n._creationDataStorage,i=t.arc||e.arc;return r=e.path3D.update(a),n=CreateRibbon("",{pathArray:s=tubePathArray(a,r,e.pathArray,o,e.tessellation,h,e.cap,i),instance:n}),e.path3D=r,e.pathArray=s,e.arc=i,e.radius=o,n}r=new Path3D(a),s=tubePathArray(a,r,[],o,l,h,c=c<0||c>3?0:c,t.arc);let p=CreateRibbon(e,{pathArray:s,closePath:!0,closeArray:!1,updatable:d,sideOrientation:_,invertUV:u,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return p._creationDataStorage.pathArray=s,p._creationDataStorage.path3D=r,p._creationDataStorage.tessellation=l,p._creationDataStorage.cap=c,p._creationDataStorage.arc=t.arc,p._creationDataStorage.radius=o,p}function CreatePolyhedronVertexData(e){let t,i,r,s,a,n;let o=[];o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]};let l=e.type&&(e.type<0||e.type>=o.length)?0:e.type||0,h=e.size,c=e.sizeX||h||1,u=e.sizeY||h||1,d=e.sizeZ||h||1,_=e.custom||o[l],p=_.face.length,f=e.faceUV||Array(p),m=e.faceColors,g=void 0===e.flat||e.flat,v=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,x=[],b=[],T=[],S=[],C=[],E=0,y=0,R=[],P=0,A=0;if(g)for(A=0;A<p;A++)m&&void 0===m[A]&&(m[A]=new math_color_Color4(1,1,1,1)),f&&void 0===f[A]&&(f[A]=new math_vector_Vector4(0,0,1,1));if(g)for(A=0;A<p;A++){let e=_.face[A].length;for(P=0,s=.5*Math.tan((r=2*Math.PI/e)/2),a=.5;P<e;P++)x.push(_.vertex[_.face[A][P]][0]*c,_.vertex[_.face[A][P]][1]*u,_.vertex[_.face[A][P]][2]*d),R.push(E),E++,t=f[A].x+(f[A].z-f[A].x)*(.5+s),i=f[A].y+(f[A].w-f[A].y)*(a-.5),S.push(t,CompatibilityOptions.UseOpenGLOrientationForUV?1-i:i),n=s*Math.cos(r)-a*Math.sin(r),a=s*Math.sin(r)+a*Math.cos(r),s=n,m&&C.push(m[A].r,m[A].g,m[A].b,m[A].a);for(P=0;P<e-2;P++)b.push(R[0+y],R[P+2+y],R[P+1+y]);y+=e}else{for(P=0;P<_.vertex.length;P++)x.push(_.vertex[P][0]*c,_.vertex[P][1]*u,_.vertex[P][2]*d),S.push(0,CompatibilityOptions.UseOpenGLOrientationForUV?1:0);for(A=0;A<p;A++)for(P=0;P<_.face[A].length-2;P++)b.push(_.face[A][0],_.face[A][P+2],_.face[A][P+1])}mesh_vertexData_VertexData.ComputeNormals(x,b,T),mesh_vertexData_VertexData._ComputeSides(v,x,b,T,S,e.frontUVs,e.backUVs);let M=new mesh_vertexData_VertexData;return M.positions=x,M.indices=b,M.normals=T,M.uvs=S,m&&g&&(M.colors=C),M}function polyhedronBuilder_CreatePolyhedron(e,t={},i=null){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreatePolyhedronVertexData(t);return s.applyToMesh(r,t.updatable),r}mesh_vertexData_VertexData.CreatePolygon=CreatePolygonVertexData,mesh_Mesh.CreatePolygon=(e,t,i,r,s,a,n=earcut)=>CreatePolygon(e,{shape:t,holes:r,updatable:s,sideOrientation:a},i,n),mesh_Mesh.ExtrudePolygon=(e,t,i,r,s,a,n,o=earcut)=>ExtrudePolygon(e,{shape:t,holes:s,depth:i,updatable:a,sideOrientation:n},r,o),mesh_Mesh.ExtrudeShape=(e,t,i,r,s,a,n=null,o,l,h)=>{let c={shape:t,path:i,scale:r,rotation:s,cap:0===a?0:a||mesh_Mesh.NO_CAP,sideOrientation:l,instance:h,updatable:o};return ExtrudeShape(e,c,n)},mesh_Mesh.ExtrudeShapeCustom=(e,t,i,r,s,a,n,o,l,h,c,u)=>{let d={shape:t,path:i,scaleFunction:r,rotationFunction:s,ribbonCloseArray:a,ribbonClosePath:n,cap:0===o?0:o||mesh_Mesh.NO_CAP,sideOrientation:c,instance:u,updatable:h};return ExtrudeShapeCustom(e,d,l)},mesh_Mesh.CreateLathe=(e,t,i,r,s,a,n)=>CreateLathe(e,{shape:t,radius:i,tessellation:r,sideOrientation:n,updatable:a},s),mesh_Mesh.CreateTube=(e,t,i,r,s,a,n,o,l,h)=>CreateTube(e,{path:t,radius:i,tessellation:r,radiusFunction:s,arc:1,cap:a,updatable:o,sideOrientation:l,instance:h},n),mesh_vertexData_VertexData.CreatePolyhedron=CreatePolyhedronVertexData,mesh_Mesh.CreatePolyhedron=(e,t,i)=>polyhedronBuilder_CreatePolyhedron(e,t,i);let rC=new math_vector_Vector3(1,0,0),rE=new math_vector_Vector3(-1,0,0),ry=new math_vector_Vector3(0,1,0),rR=new math_vector_Vector3(0,-1,0),rP=new math_vector_Vector3(0,0,1),rA=new math_vector_Vector3(0,0,-1);let DecalVertex=class DecalVertex{constructor(e=math_vector_Vector3.Zero(),t=math_vector_Vector3.Up(),i=math_vector_Vector2.Zero(),r=0,s=0,a=null,n=null,o=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=a,this.localNormalOverride=n,this.matrixIndicesOverride=o,this.matrixWeightsOverride=l}clone(){var e,t,i,r;return new DecalVertex(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===(r=this.matrixWeightsOverride)||void 0===r?void 0:r.slice())}};function CreateDecal(e,t,i){var r,s,a,n;let o=!!t.skeleton,l=i.localMode||o,h=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,c=t.getIndices(),u=o?t.getPositionData(!0,!0):t.getVerticesData(buffer_VertexBuffer.PositionKind),d=o?t.getNormalsData(!0,!0):t.getVerticesData(buffer_VertexBuffer.NormalKind),_=l?o?t.getVerticesData(buffer_VertexBuffer.PositionKind):u:null,p=l?o?t.getVerticesData(buffer_VertexBuffer.NormalKind):d:null,f=t.getVerticesData(buffer_VertexBuffer.UVKind),m=o?t.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind):null,g=o?t.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind):null,v=o?t.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind):null,x=o?t.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind):null,b=i.position||math_vector_Vector3.Zero(),T=i.normal||math_vector_Vector3.Up(),S=i.size||math_vector_Vector3.One(),C=i.angle||0;if(!T){let e=new math_vector_Vector3(0,0,1),i=t.getScene().activeCamera,r=math_vector_Vector3.TransformCoordinates(e,i.getWorldMatrix());T=i.globalPosition.subtract(r)}let E=-Math.atan2(T.z,T.x)-Math.PI/2,y=Math.sqrt(T.x*T.x+T.z*T.z),R=Math.atan2(T.y,y),P=new mesh_vertexData_VertexData;P.indices=[],P.positions=[],P.normals=[],P.uvs=[],P.matricesIndices=o?[]:null,P.matricesWeights=o?[]:null,P.matricesIndicesExtra=v?[]:null,P.matricesWeightsExtra=x?[]:null;let A=0,extractDecalVector3=(e,t)=>{let r=new DecalVertex;if(!c||!u||!d)return r;let s=c[e];if(r.vertexIdx=3*s,r.vertexIdxForBones=4*s,r.position=new math_vector_Vector3(u[3*s],u[3*s+1],u[3*s+2]),math_vector_Vector3.TransformCoordinatesToRef(r.position,t,r.position),r.normal=new math_vector_Vector3(d[3*s],d[3*s+1],d[3*s+2]),math_vector_Vector3.TransformNormalToRef(r.normal,t,r.normal),i.captureUVS&&f){let e=f[2*s+1];r.uv=new math_vector_Vector2(f[2*s],CompatibilityOptions.UseOpenGLOrientationForUV?1-e:e)}return r},M=[0,0,0,0],clip=(e,t)=>{if(0===e.length)return e;let i=.5*Math.abs(math_vector_Vector3.Dot(S,t)),indexOf=(e,t,i,r)=>{for(let s=0;s<r;++s)if(e[i+s]===t)return i+s;return -1},clipVertices=(e,r)=>{var s,a,n,o,l,h,c,u,d,f,v,x,b,T,S,C;let E=math_vector_Vector3.GetClipFactor(e.position,r.position,t,i),y=M,R=M;if(m&&g){let t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=null!==(s=e.matrixIndicesOverride)&&void 0!==s?s:m,l=null!==(a=e.matrixWeightsOverride)&&void 0!==a?a:g,h=r.matrixIndicesOverride?0:r.vertexIdxForBones,c=null!==(n=r.matrixIndicesOverride)&&void 0!==n?n:m,u=null!==(o=r.matrixWeightsOverride)&&void 0!==o?o:g;y=[0,0,0,0],R=[0,0,0,0];let d=0;for(let e=0;e<4;++e)if(l[t+e]>0){let r=indexOf(c,i[t+e],h,4);y[d]=i[t+e],R[d]=math_scalar_Scalar.Lerp(l[t+e],r>=0?u[r]:0,E),d++}for(let e=0;e<4&&d<4;++e){let r=c[h+e];-1===indexOf(i,r,t,4)&&(y[d]=r,R[d]=math_scalar_Scalar.Lerp(0,u[h+e],E),d++)}let _=R[0]+R[1]+R[2]+R[3];R[0]/=_,R[1]/=_,R[2]/=_,R[3]/=_}let P=e.localPositionOverride?e.localPositionOverride[0]:null!==(l=null==_?void 0:_[e.vertexIdx])&&void 0!==l?l:0,A=e.localPositionOverride?e.localPositionOverride[1]:null!==(h=null==_?void 0:_[e.vertexIdx+1])&&void 0!==h?h:0,I=e.localPositionOverride?e.localPositionOverride[2]:null!==(c=null==_?void 0:_[e.vertexIdx+2])&&void 0!==c?c:0,D=r.localPositionOverride?r.localPositionOverride[0]:null!==(u=null==_?void 0:_[r.vertexIdx])&&void 0!==u?u:0,O=r.localPositionOverride?r.localPositionOverride[1]:null!==(d=null==_?void 0:_[r.vertexIdx+1])&&void 0!==d?d:0,B=r.localPositionOverride?r.localPositionOverride[2]:null!==(f=null==_?void 0:_[r.vertexIdx+2])&&void 0!==f?f:0,N=e.localNormalOverride?e.localNormalOverride[0]:null!==(v=null==p?void 0:p[e.vertexIdx])&&void 0!==v?v:0,F=e.localNormalOverride?e.localNormalOverride[1]:null!==(x=null==p?void 0:p[e.vertexIdx+1])&&void 0!==x?x:0,w=e.localNormalOverride?e.localNormalOverride[2]:null!==(b=null==p?void 0:p[e.vertexIdx+2])&&void 0!==b?b:0,L=r.localNormalOverride?r.localNormalOverride[0]:null!==(T=null==p?void 0:p[r.vertexIdx])&&void 0!==T?T:0,V=r.localNormalOverride?r.localNormalOverride[1]:null!==(S=null==p?void 0:p[r.vertexIdx+1])&&void 0!==S?S:0,U=r.localNormalOverride?r.localNormalOverride[2]:null!==(C=null==p?void 0:p[r.vertexIdx+2])&&void 0!==C?C:0,k=N+(L-N)*E,G=F+(V-F)*E,z=w+(U-w)*E,W=Math.sqrt(k*k+G*G+z*z);return new DecalVertex(math_vector_Vector3.Lerp(e.position,r.position,E),math_vector_Vector3.Lerp(e.normal,r.normal,E).normalize(),math_vector_Vector2.Lerp(e.uv,r.uv,E),-1,-1,_?[P+(D-P)*E,A+(O-A)*E,I+(B-I)*E]:null,p?[k/W,G/W,z/W]:null,y,R)},r=null;e.length>3&&(r=[]);for(let s=0;s<e.length;s+=3){let a=null,n=null,o=null,l=null,h=math_vector_Vector3.Dot(e[s].position,t)-i,c=math_vector_Vector3.Dot(e[s+1].position,t)-i,u=math_vector_Vector3.Dot(e[s+2].position,t)-i,d=h>0,_=c>0,p=u>0;switch((d?1:0)+(_?1:0)+(p?1:0)){case 0:e.length>3?(r.push(e[s]),r.push(e[s+1]),r.push(e[s+2])):r=e;break;case 1:if(r=null!=r?r:[],d&&(a=e[s+1],n=e[s+2],o=clipVertices(e[s],a),l=clipVertices(e[s],n)),_){a=e[s],n=e[s+2],o=clipVertices(e[s+1],a),l=clipVertices(e[s+1],n),r.push(o),r.push(n.clone()),r.push(a.clone()),r.push(n.clone()),r.push(o.clone()),r.push(l);break}p&&(a=e[s],n=e[s+1],o=clipVertices(e[s+2],a),l=clipVertices(e[s+2],n)),a&&n&&o&&l&&(r.push(a.clone()),r.push(n.clone()),r.push(o),r.push(l),r.push(o.clone()),r.push(n.clone()));break;case 2:r=null!=r?r:[],d||(n=clipVertices(a=e[s].clone(),e[s+1]),o=clipVertices(a,e[s+2]),r.push(a),r.push(n),r.push(o)),_||(n=clipVertices(a=e[s+1].clone(),e[s+2]),o=clipVertices(a,e[s]),r.push(a),r.push(n),r.push(o)),p||(n=clipVertices(a=e[s+2].clone(),e[s]),o=clipVertices(a,e[s+1]),r.push(a),r.push(n),r.push(o))}}return r},I=t instanceof mesh_Mesh?t:null,D=null==I?void 0:I._thinInstanceDataStorage.matrixData,O=(null==I?void 0:I.thinInstanceCount)||1,B=math_vector_TmpVectors.Matrix[0];B.copyFrom(math_vector_Matrix.IdentityReadOnly);for(let e=0;e<O;++e){if((null==I?void 0:I.hasThinInstances)&&D){let t=16*e;B.setRowFromFloats(0,D[t+0],D[t+1],D[t+2],D[t+3]),B.setRowFromFloats(1,D[t+4],D[t+5],D[t+6],D[t+7]),B.setRowFromFloats(2,D[t+8],D[t+9],D[t+10],D[t+11]),B.setRowFromFloats(3,D[t+12],D[t+13],D[t+14],D[t+15])}let r=math_vector_Matrix.RotationYawPitchRoll(E,R,C).multiply(math_vector_Matrix.Translation(b.x,b.y,b.z)),s=math_vector_Matrix.Invert(r),a=t.getWorldMatrix(),n=B.multiply(a).multiply(s),o=[,,,];for(let e=0;e<c.length;e+=3){let t=o;if(t[0]=extractDecalVector3(e,n),h&&l?(t[1]=extractDecalVector3(e+2,n),t[2]=extractDecalVector3(e+1,n)):(t[1]=extractDecalVector3(e+1,n),t[2]=extractDecalVector3(e+2,n)),!(i.cullBackFaces&&0>=-t[0].normal.z&&0>=-t[1].normal.z&&0>=-t[2].normal.z)&&(t=clip(t,rC))&&(t=clip(t,rE))&&(t=clip(t,ry))&&(t=clip(t,rR))&&(t=clip(t,rP))&&(t=clip(t,rA)))for(let e=0;e<t.length;e++){let r=t[e];if(P.indices.push(A),l?(r.localPositionOverride?(P.positions[3*A]=r.localPositionOverride[0],P.positions[3*A+1]=r.localPositionOverride[1],P.positions[3*A+2]=r.localPositionOverride[2]):_&&(P.positions[3*A]=_[r.vertexIdx],P.positions[3*A+1]=_[r.vertexIdx+1],P.positions[3*A+2]=_[r.vertexIdx+2]),r.localNormalOverride?(P.normals[3*A]=r.localNormalOverride[0],P.normals[3*A+1]=r.localNormalOverride[1],P.normals[3*A+2]=r.localNormalOverride[2]):p&&(P.normals[3*A]=p[r.vertexIdx],P.normals[3*A+1]=p[r.vertexIdx+1],P.normals[3*A+2]=p[r.vertexIdx+2])):(r.position.toArray(P.positions,3*A),r.normal.toArray(P.normals,3*A)),P.matricesIndices&&P.matricesWeights&&(r.matrixIndicesOverride?(P.matricesIndices[4*A]=r.matrixIndicesOverride[0],P.matricesIndices[4*A+1]=r.matrixIndicesOverride[1],P.matricesIndices[4*A+2]=r.matrixIndicesOverride[2],P.matricesIndices[4*A+3]=r.matrixIndicesOverride[3]):(m&&(P.matricesIndices[4*A]=m[r.vertexIdxForBones],P.matricesIndices[4*A+1]=m[r.vertexIdxForBones+1],P.matricesIndices[4*A+2]=m[r.vertexIdxForBones+2],P.matricesIndices[4*A+3]=m[r.vertexIdxForBones+3]),v&&P.matricesIndicesExtra&&(P.matricesIndicesExtra[4*A]=v[r.vertexIdxForBones],P.matricesIndicesExtra[4*A+1]=v[r.vertexIdxForBones+1],P.matricesIndicesExtra[4*A+2]=v[r.vertexIdxForBones+2],P.matricesIndicesExtra[4*A+3]=v[r.vertexIdxForBones+3])),r.matrixWeightsOverride?(P.matricesWeights[4*A]=r.matrixWeightsOverride[0],P.matricesWeights[4*A+1]=r.matrixWeightsOverride[1],P.matricesWeights[4*A+2]=r.matrixWeightsOverride[2],P.matricesWeights[4*A+3]=r.matrixWeightsOverride[3]):(g&&(P.matricesWeights[4*A]=g[r.vertexIdxForBones],P.matricesWeights[4*A+1]=g[r.vertexIdxForBones+1],P.matricesWeights[4*A+2]=g[r.vertexIdxForBones+2],P.matricesWeights[4*A+3]=g[r.vertexIdxForBones+3]),x&&P.matricesWeightsExtra&&(P.matricesWeightsExtra[4*A]=x[r.vertexIdxForBones],P.matricesWeightsExtra[4*A+1]=x[r.vertexIdxForBones+1],P.matricesWeightsExtra[4*A+2]=x[r.vertexIdxForBones+2],P.matricesWeightsExtra[4*A+3]=x[r.vertexIdxForBones+3]))),i.captureUVS)r.uv.toArray(P.uvs,2*A);else{P.uvs.push(.5+r.position.x/S.x);let e=.5+r.position.y/S.y;P.uvs.push(CompatibilityOptions.UseOpenGLOrientationForUV?1-e:e)}A++}}}0===P.indices.length&&(P.indices=null),0===P.positions.length&&(P.positions=null),0===P.normals.length&&(P.normals=null),0===P.uvs.length&&(P.uvs=null),(null===(r=P.matricesIndices)||void 0===r?void 0:r.length)===0&&(P.matricesIndices=null),(null===(s=P.matricesWeights)||void 0===s?void 0:s.length)===0&&(P.matricesWeights=null),(null===(a=P.matricesIndicesExtra)||void 0===a?void 0:a.length)===0&&(P.matricesIndicesExtra=null),(null===(n=P.matricesWeightsExtra)||void 0===n?void 0:n.length)===0&&(P.matricesWeightsExtra=null);let N=new mesh_Mesh(e,t.getScene());return P.applyToMesh(N),l?(N.skeleton=t.skeleton,N.parent=t):(N.position=b.clone(),N.rotation=new math_vector_Vector3(R,E,C)),N.computeWorldMatrix(!0),N.refreshBoundingInfo(!0,!0),N}mesh_Mesh.CreateDecal=(e,t,i,r,s,a)=>CreateDecal(e,t,{position:i,normal:r,size:s,angle:a});let _IsoVector=class _IsoVector{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&logger_Logger.Warn("x is not an integer, floor(x) used"),t!==Math.floor(t)&&logger_Logger.Warn("y is not an integer, floor(y) used")}clone(){return new _IsoVector(this.x,this.y)}rotate60About(e){let t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){let 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)&&logger_Logger.Warn("m not an integer only floor(m) used"),t!==Math.floor(t)&&logger_Logger.Warn("n not an integer only floor(n) used");let i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&logger_Logger.Warn("m is not an integer, floor(m) used"),t!==Math.floor(t)&&logger_Logger.Warn("n is not an integer, floor(n) used");let i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){let i=math_vector_Vector3.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 _IsoVector(0,0)}};let PolyhedronData=class PolyhedronData{constructor(e,t,i,r){this.name=e,this.category=t,this.vertex=i,this.face=r}};let GeodesicData=class GeodesicData extends PolyhedronData{innerToData(e,t){for(let i=0;i<t.innerFacets.length;i++)this.face.push(t.innerFacets[i].map(i=>t.vecToidx[e+i]))}mapABOBtoDATA(e,t){let i=t.IDATA.edgematch[e][0];for(let r=0;r<t.isoVecsABOB.length;r++){let s=[];for(let a=0;a<3;a++)0===t.vertexTypes[r][a]?s.push(e+"|"+t.isoVecsABOB[r][a].x+"|"+t.isoVecsABOB[r][a].y):s.push(i+"|"+t.isoVecsABOB[r][a].x+"|"+t.isoVecsABOB[r][a].y);this.face.push([t.vecToidx[s[0]],t.vecToidx[s[1]],t.vecToidx[s[2]]])}}mapOBOAtoDATA(e,t){let i=t.IDATA.edgematch[e][0];for(let r=0;r<t.isoVecsOBOA.length;r++){let s=[];for(let a=0;a<3;a++)1===t.vertexTypes[r][a]?s.push(e+"|"+t.isoVecsOBOA[r][a].x+"|"+t.isoVecsOBOA[r][a].y):s.push(i+"|"+t.isoVecsOBOA[r][a].x+"|"+t.isoVecsOBOA[r][a].y);this.face.push([t.vecToidx[s[0]],t.vecToidx[s[1]],t.vecToidx[s[2]]])}}mapBAOAtoDATA(e,t){let i=t.IDATA.edgematch[e][2];for(let r=0;r<t.isoVecsBAOA.length;r++){let s=[];for(let a=0;a<3;a++)1===t.vertexTypes[r][a]?s.push(e+"|"+t.isoVecsBAOA[r][a].x+"|"+t.isoVecsBAOA[r][a].y):s.push(i+"|"+t.isoVecsBAOA[r][a].x+"|"+t.isoVecsBAOA[r][a].y);this.face.push([t.vecToidx[s[0]],t.vecToidx[s[1]],t.vecToidx[s[2]]])}}orderData(e){let t=[];for(let e=0;e<13;e++)t[e]=[];let i=e.closestTo;for(let e=0;e<i.length;e++)i[e][0]>-1?i[e][1]>0&&t[i[e][0]].push([e,i[e][1]]):t[12].push([e,i[e][0]]);let r=[];for(let e=0;e<12;e++)r[e]=e;let s=12;for(let e=0;e<12;e++){t[e].sort((e,t)=>e[1]-t[1]);for(let i=0;i<t[e].length;i++)r[t[e][i][0]]=s++}for(let e=0;e<t[12].length;e++)r[t[12][e][0]]=s++;for(let e=0;e<this.vertex.length;e++)this.vertex[e].push(r[e]);this.vertex.sort((e,t)=>e[3]-t[3]);for(let e=0;e<this.vertex.length;e++)this.vertex[e].pop();for(let e=0;e<this.face.length;e++)for(let t=0;t<this.face[e].length;t++)this.face[e][t]=r[this.face[e][t]];this.sharedNodes=t[12].length,this.poleNodes=this.vertex.length-this.sharedNodes}setOrder(e,t){let i=[],r=[],s=t.pop();r.push(s);let a=this.face[s].indexOf(e);a=(a+2)%3;let n=this.face[s][a];i.push(n);let o=0;for(;t.length>0;)s=t[o],this.face[s].indexOf(n)>-1?(a=(this.face[s].indexOf(n)+1)%3,n=this.face[s][a],i.push(n),r.push(s),t.splice(o,1),o=0):o++;return this.adjacentFaces.push(i),r}toGoldbergPolyhedronData(){let e=new PolyhedronData("GeoDual","Goldberg",[],[]);e.name="GD dual";let t=this.vertex.length,i=Array(t);for(let e=0;e<t;e++)i[e]=[];for(let e=0;e<this.face.length;e++)for(let t=0;t<3;t++)i[this.face[e][t]].push(e);let r=0,s=0,a=0,n=[],o=[];this.adjacentFaces=[];for(let t=0;t<i.length;t++)e.face[t]=this.setOrder(t,i[t].concat([])),i[t].forEach(t=>{r=0,s=0,a=0,n=this.face[t];for(let e=0;e<3;e++)o=this.vertex[n[e]],r+=o[0],s+=o[1],a+=o[2];e.vertex[t]=[r/3,s/3,a/3]});return e}static BuildGeodesicData(e){let t=new GeodesicData("Geodesic-m-n","Geodesic",[[0,o,-1],[-o,1,0],[-1,0,-o],[1,0,-o],[o,1,0],[0,o,1],[-1,0,o],[-o,-1,0],[0,-o,-1],[o,-1,0],[1,0,o],[0,-o,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;i<e.IDATA.face.length;i++)e.MapToFace(i,t),t.innerToData(i,e),"B"===e.IDATA.edgematch[i][1]&&t.mapABOBtoDATA(i,e),"O"===e.IDATA.edgematch[i][1]&&t.mapOBOAtoDATA(i,e),"A"===e.IDATA.edgematch[i][3]&&t.mapBAOAtoDATA(i,e);return t.orderData(e),t.vertex=t.vertex.map(function(e){let t=e[0],i=e[1],r=e[2],s=Math.sqrt(t*t+i*i+r*r);return e[0]*=1/s,e[1]*=1/s,e[2]*=1/s,e}),t}};mesh_Mesh._GoldbergMeshParser=(e,t)=>GoldbergMesh.Parse(e,t);let GoldbergMesh=class GoldbergMesh extends mesh_Mesh{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&&(logger_Logger.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(logger_Logger.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(logger_Logger.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t<e.length;t++){let i=e[t][0],r=e[t][1],s=e[t][2];for(let e=i;e<r+1;e++)this.goldbergData.faceColors[e]=s}let t=[];for(let e=0;e<12;e++)for(let i=0;i<5;i++)t.push(this.goldbergData.faceColors[e].r,this.goldbergData.faceColors[e].g,this.goldbergData.faceColors[e].b,this.goldbergData.faceColors[e].a);for(let e=12;e<this.goldbergData.faceColors.length;e++)for(let i=0;i<6;i++)t.push(this.goldbergData.faceColors[e].r,this.goldbergData.faceColors[e].g,this.goldbergData.faceColors[e].b,this.goldbergData.faceColors[e].a);return t}setGoldbergFaceColors(e){let t=this._changeGoldbergFaceColors(e);this.setVerticesData(buffer_VertexBuffer.ColorKind,t)}updateGoldbergFaceColors(e){let t=this._changeGoldbergFaceColors(e);this.updateVerticesData(buffer_VertexBuffer.ColorKind,t)}_changeGoldbergFaceUVs(e){let t=this.getVerticesData(buffer_VertexBuffer.UVKind);for(let i=0;i<e.length;i++){let r,s;let a=e[i][0],n=e[i][1],o=e[i][2],l=e[i][3],h=e[i][4],c=[],u=[];for(let e=0;e<5;e++)r=o.x+l*Math.cos(h+e*Math.PI/2.5),s=o.y+l*Math.sin(h+e*Math.PI/2.5),r<0&&(r=0),r>1&&(r=1),c.push(r,s);for(let e=0;e<6;e++)r=o.x+l*Math.cos(h+e*Math.PI/3),s=o.y+l*Math.sin(h+e*Math.PI/3),r<0&&(r=0),r>1&&(r=1),u.push(r,s);for(let e=a;e<Math.min(12,n+1);e++)for(let i=0;i<5;i++)t[10*e+2*i]=c[2*i],t[10*e+2*i+1]=c[2*i+1];for(let e=Math.max(12,a);e<n+1;e++)for(let i=0;i<6;i++)t[12*e-24+2*i]=u[2*i],t[12*e-23+2*i]=u[2*i+1]}return t}setGoldbergFaceUVs(e){let t=this._changeGoldbergFaceUVs(e);this.setVerticesData(buffer_VertexBuffer.UVKind,t)}updateGoldbergFaceUVs(e){let t=this._changeGoldbergFaceUVs(e);this.updateVerticesData(buffer_VertexBuffer.UVKind,t)}placeOnGoldbergFaceAt(e,t,i){let r=math_vector_Vector3.RotationFromAxis(this.goldbergData.faceXaxis[t],this.goldbergData.faceYaxis[t],this.goldbergData.faceZaxis[t]);e.rotation=r,e.position=this.goldbergData.faceCenters[t].add(this.goldbergData.faceXaxis[t].scale(i.x)).add(this.goldbergData.faceYaxis[t].scale(i.y)).add(this.goldbergData.faceZaxis[t].scale(i.z))}serialize(e){super.serialize(e),e.type="GoldbergMesh";let t={};if(t.adjacentFaces=this.goldbergData.adjacentFaces,t.nbSharedFaces=this.goldbergData.nbSharedFaces,t.nbUnsharedFaces=this.goldbergData.nbUnsharedFaces,t.nbFaces=this.goldbergData.nbFaces,t.nbFacesAtPole=this.goldbergData.nbFacesAtPole,this.goldbergData.faceColors)for(let e of(t.faceColors=[],this.goldbergData.faceColors))t.faceColors.push(e.asArray());if(this.goldbergData.faceCenters)for(let e of(t.faceCenters=[],this.goldbergData.faceCenters))t.faceCenters.push(e.asArray());if(this.goldbergData.faceZaxis)for(let e of(t.faceZaxis=[],this.goldbergData.faceZaxis))t.faceZaxis.push(e.asArray());if(this.goldbergData.faceYaxis)for(let e of(t.faceYaxis=[],this.goldbergData.faceYaxis))t.faceYaxis.push(e.asArray());if(this.goldbergData.faceXaxis)for(let e of(t.faceXaxis=[],this.goldbergData.faceXaxis))t.faceXaxis.push(e.asArray());e.goldbergData=t}static Parse(e,t){let i=e.goldbergData;i.faceColors=i.faceColors.map(e=>math_color_Color4.FromArray(e)),i.faceCenters=i.faceCenters.map(e=>math_vector_Vector3.FromArray(e)),i.faceZaxis=i.faceZaxis.map(e=>math_vector_Vector3.FromArray(e)),i.faceXaxis=i.faceXaxis.map(e=>math_vector_Vector3.FromArray(e)),i.faceYaxis=i.faceYaxis.map(e=>math_vector_Vector3.FromArray(e));let r=new GoldbergMesh(e.name,t);return r.goldbergData=i,r}};let ShapePath=class ShapePath{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new math_path_Path2(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)}bezierCurveTo(e,t,i,r,s,a){this._currentPath.addBezierCurveTo(e,t,i,r,s,a,this._resolution)}extractHoles(){for(let e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){let 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 CreateShapePath(e,t,i,r,s,a){let n=a.glyphs[e]||a.glyphs["?"];if(!n)return null;let o=new ShapePath(s);if(n.o){let e=n.o.split(" ");for(let s=0,a=e.length;s<a;){let a=e[s++];switch(a){case"m":{let a=parseInt(e[s++])*t+i,n=parseInt(e[s++])*t+r;o.moveTo(a,n);break}case"l":{let a=parseInt(e[s++])*t+i,n=parseInt(e[s++])*t+r;o.lineTo(a,n);break}case"q":{let a=parseInt(e[s++])*t+i,n=parseInt(e[s++])*t+r,l=parseInt(e[s++])*t+i,h=parseInt(e[s++])*t+r;o.quadraticCurveTo(l,h,a,n);break}case"b":{let a=parseInt(e[s++])*t+i,n=parseInt(e[s++])*t+r,l=parseInt(e[s++])*t+i,h=parseInt(e[s++])*t+r,c=parseInt(e[s++])*t+i,u=parseInt(e[s++])*t+r;o.bezierCurveTo(l,h,c,u,a,n)}}}}return o.extractHoles(),{offsetX:n.ha*t,shapePath:o}}function CreateTextShapePaths(e,t,i,r){let s=Array.from(e),a=t/r.resolution,n=(r.boundingBox.yMax-r.boundingBox.yMin+r.underlineThickness)*a,o=[],l=0,h=0;for(let e=0;e<s.length;e++){let t=s[e];if("\n"===t)l=0,h-=n;else{let e=CreateShapePath(t,a,l,h,i,r);e&&(l+=e.offsetX,o.push(e.shapePath))}}return o}let SkeletonViewer=class SkeletonViewer{static CreateBoneWeightShader(e,t){var i,r,s,a,n,o;let l=e.skeleton,h=null!==(i=e.colorBase)&&void 0!==i?i:math_color_Color3.Black(),c=null!==(r=e.colorZero)&&void 0!==r?r:math_color_Color3.Blue(),u=null!==(s=e.colorQuarter)&&void 0!==s?s:math_color_Color3.Green(),d=null!==(a=e.colorHalf)&&void 0!==a?a:math_color_Color3.Yellow(),_=null!==(n=e.colorFull)&&void 0!==n?n:math_color_Color3.Red(),p=null!==(o=e.targetBoneIndex)&&void 0!==o?o:0;effect_Effect.ShadersStore["boneWeights:"+l.name+"VertexShader"]=`precision highp float; + + attribute vec3 position; + attribute vec2 uv; + + uniform mat4 view; + uniform mat4 projection; + uniform mat4 worldViewProjection; + + #include<bonesDeclaration> + #if NUM_BONE_INFLUENCERS == 0 + attribute vec4 matricesIndices; + attribute vec4 matricesWeights; + #endif + #include<bakedVertexAnimationDeclaration> + + #include<instancesDeclaration> + + varying vec3 vColor; + + uniform vec3 colorBase; + uniform vec3 colorZero; + uniform vec3 colorQuarter; + uniform vec3 colorHalf; + uniform vec3 colorFull; + + uniform float targetBoneIndex; + + void main() { + vec3 positionUpdated = position; + + #include<instancesVertex> + #include<bonesVertex> + #include<bakedVertexAnimation> + + vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); + + vec3 color = colorBase; + float totalWeight = 0.; + if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){ + totalWeight += matricesWeights[0]; + } + if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){ + totalWeight += matricesWeights[1]; + } + if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){ + totalWeight += matricesWeights[2]; + } + if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){ + totalWeight += matricesWeights[3]; + } + + color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight)); + color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight)); + color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight)); + color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight)); + vColor = color; + + gl_Position = projection * view * worldPos; + }`,effect_Effect.ShadersStore["boneWeights:"+l.name+"FragmentShader"]=` + precision highp float; + varying vec3 vPosition; + + varying vec3 vColor; + + void main() { + vec4 color = vec4(vColor, 1.0); + gl_FragColor = color; + } + `;let f=new shaderMaterial_ShaderMaterial("boneWeight:"+l.name,t,{vertex:"boneWeights:"+l.name,fragment:"boneWeights:"+l.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return f.setColor3("colorBase",h),f.setColor3("colorZero",c),f.setColor3("colorQuarter",u),f.setColor3("colorHalf",d),f.setColor3("colorFull",_),f.setFloat("targetBoneIndex",p),f.getClassName=()=>"BoneWeightShader",f.transparencyMode=material_Material.MATERIAL_OPAQUE,f}static CreateSkeletonMapShader(e,t){var i;let r=e.skeleton,s=null!==(i=e.colorMap)&&void 0!==i?i:[{color:new math_color_Color3(1,.38,.18),location:0},{color:new math_color_Color3(.59,.18,1),location:.2},{color:new math_color_Color3(.59,1,.18),location:.4},{color:new math_color_Color3(1,.87,.17),location:.6},{color:new math_color_Color3(1,.17,.42),location:.8},{color:new math_color_Color3(.17,.68,1),location:1}],a=r.bones.length+1,n=SkeletonViewer._CreateBoneMapColorBuffer(a,s,t),o=new shaderMaterial_ShaderMaterial("boneWeights:"+r.name,t,{vertexSource:`precision highp float; + + attribute vec3 position; + attribute vec2 uv; + + uniform mat4 view; + uniform mat4 projection; + uniform mat4 worldViewProjection; + uniform float colorMap[`+4*r.bones.length+`]; + + #include<bonesDeclaration> + #if NUM_BONE_INFLUENCERS == 0 + attribute vec4 matricesIndices; + attribute vec4 matricesWeights; + #endif + #include<bakedVertexAnimationDeclaration> + #include<instancesDeclaration> + + varying vec3 vColor; + + void main() { + vec3 positionUpdated = position; + + #include<instancesVertex> + #include<bonesVertex> + #include<bakedVertexAnimation> + + vec3 color = vec3(0.); + bool first = true; + + for (int i = 0; i < 4; i++) { + int boneIdx = int(matricesIndices[i]); + float boneWgt = matricesWeights[i]; + + vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]); + + if (boneWgt > 0.) { + if (first) { + first = false; + color = c; + } else { + color = mix(color, c, boneWgt); + } + } + } + + vColor = color; + + vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); + + gl_Position = projection * view * worldPos; + }`,fragmentSource:` + precision highp float; + varying vec3 vColor; + + void main() { + vec4 color = vec4( vColor, 1.0 ); + gl_FragColor = color; + } + `},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",n),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=material_Material.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){let r=new DynamicTexture("temp",{width:e,height:1},i,!1),s=r.getContext(),a=s.createLinearGradient(0,0,e,0);t.forEach(e=>{a.addColorStop(e.location,e.color.toHexString())}),s.fillStyle=a,s.fillRect(0,0,e,1),r.update();let n=[],o=s.getImageData(0,0,e,1).data,l=1/255;for(let e=0;e<o.length;e++)n.push(o[e]*l);return r.dispose(),n}get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get isReady(){return this._ready}set ready(e){this._ready=e}get debugMesh(){return this._debugMesh}set debugMesh(e){this._debugMesh=e}get displayMode(){return this.options.displayMode||SkeletonViewer.DISPLAY_LINES}set displayMode(e){e>SkeletonViewer.DISPLAY_SPHERE_AND_SPURS&&(e=SkeletonViewer.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,s=3,a={}){var n,o,l,h,c,u,d,_,p,f,m,g,v,x;this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=s,this.options=a,this.color=math_color_Color3.White(),this._debugLines=[],this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,a.pauseAnimations=null===(n=a.pauseAnimations)||void 0===n||n,a.returnToRest=null!==(o=a.returnToRest)&&void 0!==o&&o,a.displayMode=null!==(l=a.displayMode)&&void 0!==l?l:SkeletonViewer.DISPLAY_LINES,a.displayOptions=null!==(h=a.displayOptions)&&void 0!==h?h:{},a.displayOptions.midStep=null!==(c=a.displayOptions.midStep)&&void 0!==c?c:.235,a.displayOptions.midStepFactor=null!==(u=a.displayOptions.midStepFactor)&&void 0!==u?u:.155,a.displayOptions.sphereBaseSize=null!==(d=a.displayOptions.sphereBaseSize)&&void 0!==d?d:.15,a.displayOptions.sphereScaleUnit=null!==(_=a.displayOptions.sphereScaleUnit)&&void 0!==_?_:2,a.displayOptions.sphereFactor=null!==(p=a.displayOptions.sphereFactor)&&void 0!==p?p:.865,a.displayOptions.spurFollowsChild=null!==(f=a.displayOptions.spurFollowsChild)&&void 0!==f&&f,a.displayOptions.showLocalAxes=null!==(m=a.displayOptions.showLocalAxes)&&void 0!==m&&m,a.displayOptions.localAxesSize=null!==(g=a.displayOptions.localAxesSize)&&void 0!==g?g:.075,a.computeBonesUsingShaders=null===(v=a.computeBonesUsingShaders)||void 0===v||v,a.useAllBones=null===(x=a.useAllBones)||void 0===x||x;let b=t.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind),T=t.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind);if(this._boneIndices=new Set,!a.useAllBones&&b&&T)for(let e=0;e<b.length;++e){let t=b[e],i=T[e];0!==i&&this._boneIndices.add(t)}this._utilityLayer=new utilityLayerRenderer_UtilityLayerRenderer(this._scene,!1),this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!0;let S=this.options.displayMode||0;S>SkeletonViewer.DISPLAY_SPHERE_AND_SPURS&&(S=SkeletonViewer.DISPLAY_LINES),this.displayMode=S,this.update(),this._bindObs()}_bindObs(){this.displayMode===SkeletonViewer.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()}))}update(){switch(this.displayMode){case SkeletonViewer.DISPLAY_LINES:this._displayLinesUpdate();break;case SkeletonViewer.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,s=0,a=0){let n=math_vector_TmpVectors.Matrix[0],o=t.getParent();if(n.copyFrom(t.getLocalMatrix()),0!==r||0!==s||0!==a){let e=math_vector_TmpVectors.Matrix[1];math_vector_Matrix.IdentityToRef(e),e.setTranslationFromFloats(r,s,a),e.multiplyToRef(n,n)}o&&n.multiplyToRef(o.getAbsoluteMatrix(),n),n.multiplyToRef(i,n),e.x=n.m[12],e.y=n.m[13],e.z=n.m[14]}_getLinesForBonesWithLength(e,t){let i=e.length,r=this.mesh,s=r.position,a=0;for(let r=0;r<i;r++){let i=e[r],n=this._debugLines[a];-1!==i._index&&(this._boneIndices.has(i.getIndex())||this.options.useAllBones)&&(n||(n=[math_vector_Vector3.Zero(),math_vector_Vector3.Zero()],this._debugLines[a]=n),this._getBonePosition(n[0],i,t),this._getBonePosition(n[1],i,t,0,i.length,0),n[0].subtractInPlace(s),n[1].subtractInPlace(s),a++)}}_getLinesForBonesNoLength(e){let t=e.length,i=0,r=this.mesh,s=r.position;for(let a=t-1;a>=0;a--){let t=e[a],n=t.getParent();if(!n||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let o=this._debugLines[i];o||(o=[math_vector_Vector3.Zero(),math_vector_Vector3.Zero()],this._debugLines[i]=o),t.getAbsolutePositionToRef(r,o[0]),n.getAbsolutePositionToRef(r,o[1]),o[0].subtractInPlace(s),o[1].subtractInPlace(s),i++}}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){if(null===e||-1===e._index){t.copyFrom(math_vector_Matrix.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;let r=null===(t=this.utilityLayer)||void 0===t?void 0:t.utilityLayerScene,s=this.skeleton.bones,a=[],n=[],o=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,r.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let t=Number.NEGATIVE_INFINITY,l=this.options.displayOptions||{};for(let i=0;i<s.length;i++){let o=s[i];if(-1===o._index||!this._boneIndices.has(o.getIndex())&&!this.options.useAllBones)continue;let h=new math_vector_Matrix;this._getAbsoluteBindPoseToRef(o,h);let c=new math_vector_Vector3;h.decompose(void 0,void 0,c),o.children.forEach(i=>{let s=new math_vector_Matrix;i.getLocalMatrix().multiplyToRef(h,s);let a=new math_vector_Vector3;s.decompose(void 0,void 0,a);let u=math_vector_Vector3.Distance(c,a);if(u>t&&(t=u),e)return;let d=a.clone().subtract(c.clone()),_=d.length(),p=d.normalize().scale(_),f=l.midStep||.165,m=l.midStepFactor||.215,g=p.scale(f),v=ExtrudeShapeCustom("skeletonViewer",{shape:[new math_vector_Vector3(1,-1,0),new math_vector_Vector3(1,1,0),new math_vector_Vector3(-1,1,0),new math_vector_Vector3(-1,-1,0),new math_vector_Vector3(1,-1,0)],path:[math_vector_Vector3.Zero(),g,p],scaleFunction:e=>{switch(e){case 0:case 2:break;case 1:return _*m}return 0},sideOrientation:mesh_Mesh.DEFAULTSIDE,updatable:!1},r),x=v.getTotalVertices(),b=[],T=[];for(let e=0;e<x;e++)b.push(1,0,0,0),l.spurFollowsChild&&e>9?T.push(i.getIndex(),0,0,0):T.push(o.getIndex(),0,0,0);v.position=c.clone(),v.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,b,!1),v.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,T,!1),v.convertToFlatShadedMesh(),n.push(v)});let u=l.sphereBaseSize||.2,d=sphereBuilder_CreateSphere("skeletonViewer",{segments:6,diameter:u,updatable:!0},r),_=d.getTotalVertices(),p=[],f=[];for(let e=0;e<_;e++)p.push(1,0,0,0),f.push(o.getIndex(),0,0,0);d.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,p,!1),d.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,f,!1),d.position=c.clone(),a.push([d,o])}let h=l.sphereScaleUnit||2,c=l.sphereFactor||.85,u=[];for(let e=0;e<a.length;e++){let[i,r]=a[e],s=1/(h/t),n=0,o=r;for(;o.getParent()&&-1!==o.getParent().getIndex();)n++,o=o.getParent();i.scaling.scaleInPlace(s*Math.pow(c,n)),u.push(i)}this.debugMesh=mesh_Mesh.MergeMeshes(u.concat(n),!0,!0),this.debugMesh&&(this.debugMesh.renderingGroupId=this.renderingGroupId,this.debugMesh.skeleton=this.skeleton,this.debugMesh.parent=this.mesh,this.debugMesh.computeBonesUsingShaders=null===(i=this.options.computeBonesUsingShaders)||void 0===i||i,this.debugMesh.alwaysSelectAsActiveMesh=!0);let d=this.utilityLayer._getSharedGizmoLight();d.intensity=.7,this._revert(o),this.ready=!0}catch(e){console.error(e),this._revert(o),this.dispose()}}_buildLocalAxes(){var e;this._localAxes&&this._localAxes.dispose(),this._localAxes=null;let t=this.options.displayOptions||{};if(!t.showLocalAxes)return;let i=this._utilityLayer.utilityLayerScene,r=t.localAxesSize||.075,s=[],a=[],n=new math_color_Color4(1,0,0,1),o=new math_color_Color4(0,1,0,1),l=new math_color_Color4(0,0,1,1),h=[],c=[];for(let e in this.skeleton.bones){let t=this.skeleton.bones[e];if(-1===t._index||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let i=new math_vector_Matrix,u=new math_vector_Vector3;this._getAbsoluteBindPoseToRef(t,i),i.decompose(void 0,math_vector_TmpVectors.Quaternion[0],u);let d=new math_vector_Matrix;math_vector_TmpVectors.Quaternion[0].toRotationMatrix(d);let _=math_vector_Vector3.TransformCoordinates(new math_vector_Vector3(0+r,0,0),d),p=math_vector_Vector3.TransformCoordinates(new math_vector_Vector3(0,0+r,0),d),f=math_vector_Vector3.TransformCoordinates(new math_vector_Vector3(0,0,0+r),d),m=[u,u.add(_)],g=[u,u.add(p)],v=[u,u.add(f)],x=[m,g,v],b=[[n,n],[o,o],[l,l]];s.push(...x),a.push(...b);for(let e=0;e<6;e++)h.push(1,0,0,0),c.push(t.getIndex(),0,0,0)}this._localAxes=CreateLineSystem("localAxes",{lines:s,colors:a,updatable:!0},i),this._localAxes.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,h,!1),this._localAxes.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,c,!1),this._localAxes.skeleton=this.skeleton,this._localAxes.renderingGroupId=this.renderingGroupId+1,this._localAxes.parent=this.mesh,this._localAxes.computeBonesUsingShaders=null===(e=this.options.computeBonesUsingShaders)||void 0===e||e}_displayLinesUpdate(){if(!this._utilityLayer)return;this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh.getWorldMatrix());let e=this._utilityLayer.utilityLayerScene;e&&(this._debugMesh?CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},e):(this._debugMesh=CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:null},e),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.position.copyFrom(this.mesh.position),this._debugMesh.color=this.color)}changeDisplayMode(e){let t=!!this.isEnabled;this.displayMode!==e&&(this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this.displayMode=e,this.update(),this._bindObs(),this.isEnabled=t)}changeDisplayOptions(e,t){let i=!!this.isEnabled;this.options.displayOptions[e]=t,this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this.update(),this._bindObs(),this.isEnabled=i}dispose(){this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null),this.ready=!1}};SkeletonViewer.DISPLAY_LINES=0,SkeletonViewer.DISPLAY_SPHERES=1,SkeletonViewer.DISPLAY_SPHERE_AND_SPURS=2;let Constants=class Constants{};Constants.ALPHA_DISABLE=0,Constants.ALPHA_ADD=1,Constants.ALPHA_COMBINE=2,Constants.ALPHA_SUBTRACT=3,Constants.ALPHA_MULTIPLY=4,Constants.ALPHA_MAXIMIZED=5,Constants.ALPHA_ONEONE=6,Constants.ALPHA_PREMULTIPLIED=7,Constants.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Constants.ALPHA_INTERPOLATE=9,Constants.ALPHA_SCREENMODE=10,Constants.ALPHA_ONEONE_ONEONE=11,Constants.ALPHA_ALPHATOCOLOR=12,Constants.ALPHA_REVERSEONEMINUS=13,Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,Constants.ALPHA_ONEONE_ONEZERO=15,Constants.ALPHA_EXCLUSION=16,Constants.ALPHA_LAYER_ACCUMULATE=17,Constants.ALPHA_EQUATION_ADD=0,Constants.ALPHA_EQUATION_SUBSTRACT=1,Constants.ALPHA_EQUATION_REVERSE_SUBTRACT=2,Constants.ALPHA_EQUATION_MAX=3,Constants.ALPHA_EQUATION_MIN=4,Constants.ALPHA_EQUATION_DARKEN=5,Constants.DELAYLOADSTATE_NONE=0,Constants.DELAYLOADSTATE_LOADED=1,Constants.DELAYLOADSTATE_LOADING=2,Constants.DELAYLOADSTATE_NOTLOADED=4,Constants.NEVER=512,Constants.ALWAYS=519,Constants.LESS=513,Constants.EQUAL=514,Constants.LEQUAL=515,Constants.GREATER=516,Constants.GEQUAL=518,Constants.NOTEQUAL=517,Constants.KEEP=7680,Constants.ZERO=0,Constants.REPLACE=7681,Constants.INCR=7682,Constants.DECR=7683,Constants.INVERT=5386,Constants.INCR_WRAP=34055,Constants.DECR_WRAP=34056,Constants.TEXTURE_CLAMP_ADDRESSMODE=0,Constants.TEXTURE_WRAP_ADDRESSMODE=1,Constants.TEXTURE_MIRROR_ADDRESSMODE=2,Constants.TEXTURE_CREATIONFLAG_STORAGE=1,Constants.TEXTUREFORMAT_ALPHA=0,Constants.TEXTUREFORMAT_LUMINANCE=1,Constants.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Constants.TEXTUREFORMAT_RGB=4,Constants.TEXTUREFORMAT_RGBA=5,Constants.TEXTUREFORMAT_RED=6,Constants.TEXTUREFORMAT_R=6,Constants.TEXTUREFORMAT_RG=7,Constants.TEXTUREFORMAT_RED_INTEGER=8,Constants.TEXTUREFORMAT_R_INTEGER=8,Constants.TEXTUREFORMAT_RG_INTEGER=9,Constants.TEXTUREFORMAT_RGB_INTEGER=10,Constants.TEXTUREFORMAT_RGBA_INTEGER=11,Constants.TEXTUREFORMAT_BGRA=12,Constants.TEXTUREFORMAT_DEPTH24_STENCIL8=13,Constants.TEXTUREFORMAT_DEPTH32_FLOAT=14,Constants.TEXTUREFORMAT_DEPTH16=15,Constants.TEXTUREFORMAT_DEPTH24=16,Constants.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,Constants.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,Constants.TEXTUREFORMAT_STENCIL8=19,Constants.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,Constants.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,Constants.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,Constants.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,Constants.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,Constants.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,Constants.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,Constants.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,Constants.TEXTURETYPE_UNSIGNED_BYTE=0,Constants.TEXTURETYPE_UNSIGNED_INT=0,Constants.TEXTURETYPE_FLOAT=1,Constants.TEXTURETYPE_HALF_FLOAT=2,Constants.TEXTURETYPE_BYTE=3,Constants.TEXTURETYPE_SHORT=4,Constants.TEXTURETYPE_UNSIGNED_SHORT=5,Constants.TEXTURETYPE_INT=6,Constants.TEXTURETYPE_UNSIGNED_INTEGER=7,Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Constants.TEXTURETYPE_UNSIGNED_INT_24_8=12,Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Constants.TEXTURETYPE_UNDEFINED=16,Constants.TEXTURE_2D=3553,Constants.TEXTURE_2D_ARRAY=35866,Constants.TEXTURE_CUBE_MAP=34067,Constants.TEXTURE_CUBE_MAP_ARRAY=3735928559,Constants.TEXTURE_3D=32879,Constants.TEXTURE_NEAREST_SAMPLINGMODE=1,Constants.TEXTURE_NEAREST_NEAREST=1,Constants.TEXTURE_BILINEAR_SAMPLINGMODE=2,Constants.TEXTURE_LINEAR_LINEAR=2,Constants.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Constants.TEXTURE_NEAREST_LINEAR=7,Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Constants.TEXTURE_LINEAR_NEAREST=12,Constants.TEXTURE_EXPLICIT_MODE=0,Constants.TEXTURE_SPHERICAL_MODE=1,Constants.TEXTURE_PLANAR_MODE=2,Constants.TEXTURE_CUBIC_MODE=3,Constants.TEXTURE_PROJECTION_MODE=4,Constants.TEXTURE_SKYBOX_MODE=5,Constants.TEXTURE_INVCUBIC_MODE=6,Constants.TEXTURE_EQUIRECTANGULAR_MODE=7,Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Constants.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,Constants.TEXTURE_FILTERING_QUALITY_HIGH=64,Constants.TEXTURE_FILTERING_QUALITY_MEDIUM=16,Constants.TEXTURE_FILTERING_QUALITY_LOW=8,Constants.SCALEMODE_FLOOR=1,Constants.SCALEMODE_NEAREST=2,Constants.SCALEMODE_CEILING=3,Constants.MATERIAL_TextureDirtyFlag=1,Constants.MATERIAL_LightDirtyFlag=2,Constants.MATERIAL_FresnelDirtyFlag=4,Constants.MATERIAL_AttributesDirtyFlag=8,Constants.MATERIAL_MiscDirtyFlag=16,Constants.MATERIAL_PrePassDirtyFlag=32,Constants.MATERIAL_AllDirtyFlag=63,Constants.MATERIAL_TriangleFillMode=0,Constants.MATERIAL_WireFrameFillMode=1,Constants.MATERIAL_PointFillMode=2,Constants.MATERIAL_PointListDrawMode=3,Constants.MATERIAL_LineListDrawMode=4,Constants.MATERIAL_LineLoopDrawMode=5,Constants.MATERIAL_LineStripDrawMode=6,Constants.MATERIAL_TriangleStripDrawMode=7,Constants.MATERIAL_TriangleFanDrawMode=8,Constants.MATERIAL_ClockWiseSideOrientation=0,Constants.MATERIAL_CounterClockWiseSideOrientation=1,Constants.ACTION_NothingTrigger=0,Constants.ACTION_OnPickTrigger=1,Constants.ACTION_OnLeftPickTrigger=2,Constants.ACTION_OnRightPickTrigger=3,Constants.ACTION_OnCenterPickTrigger=4,Constants.ACTION_OnPickDownTrigger=5,Constants.ACTION_OnDoublePickTrigger=6,Constants.ACTION_OnPickUpTrigger=7,Constants.ACTION_OnPickOutTrigger=16,Constants.ACTION_OnLongPressTrigger=8,Constants.ACTION_OnPointerOverTrigger=9,Constants.ACTION_OnPointerOutTrigger=10,Constants.ACTION_OnEveryFrameTrigger=11,Constants.ACTION_OnIntersectionEnterTrigger=12,Constants.ACTION_OnIntersectionExitTrigger=13,Constants.ACTION_OnKeyDownTrigger=14,Constants.ACTION_OnKeyUpTrigger=15,Constants.PARTICLES_BILLBOARDMODE_Y=2,Constants.PARTICLES_BILLBOARDMODE_ALL=7,Constants.PARTICLES_BILLBOARDMODE_STRETCHED=8,Constants.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,Constants.MESHES_CULLINGSTRATEGY_STANDARD=0,Constants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Constants.SCENELOADER_NO_LOGGING=0,Constants.SCENELOADER_MINIMAL_LOGGING=1,Constants.SCENELOADER_SUMMARY_LOGGING=2,Constants.SCENELOADER_DETAILED_LOGGING=3,Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,Constants.PREPASS_POSITION_TEXTURE_TYPE=1,Constants.PREPASS_VELOCITY_TEXTURE_TYPE=2,Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,Constants.PREPASS_COLOR_TEXTURE_TYPE=4,Constants.PREPASS_DEPTH_TEXTURE_TYPE=5,Constants.PREPASS_NORMAL_TEXTURE_TYPE=6,Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,Constants.BUFFER_CREATIONFLAG_READ=1,Constants.BUFFER_CREATIONFLAG_WRITE=2,Constants.BUFFER_CREATIONFLAG_READWRITE=3,Constants.BUFFER_CREATIONFLAG_UNIFORM=4,Constants.BUFFER_CREATIONFLAG_VERTEX=8,Constants.BUFFER_CREATIONFLAG_INDEX=16,Constants.BUFFER_CREATIONFLAG_STORAGE=32,Constants.RENDERPASS_MAIN=0,Constants.INPUT_ALT_KEY=18,Constants.INPUT_CTRL_KEY=17,Constants.INPUT_META_KEY1=91,Constants.INPUT_META_KEY2=92,Constants.INPUT_META_KEY3=93,Constants.INPUT_SHIFT_KEY=16,Constants.SNAPSHOTRENDERING_STANDARD=0,Constants.SNAPSHOTRENDERING_FAST=1,Constants.PERSPECTIVE_CAMERA=0,Constants.ORTHOGRAPHIC_CAMERA=1,Constants.FOVMODE_VERTICAL_FIXED=0,Constants.FOVMODE_HORIZONTAL_FIXED=1,Constants.RIG_MODE_NONE=0,Constants.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Constants.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Constants.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Constants.RIG_MODE_VR=20,Constants.RIG_MODE_CUSTOM=22,Constants.MAX_SUPPORTED_UV_SETS=6,Constants.GL_ALPHA_EQUATION_ADD=32774,Constants.GL_ALPHA_EQUATION_MIN=32775,Constants.GL_ALPHA_EQUATION_MAX=32776,Constants.GL_ALPHA_EQUATION_SUBTRACT=32778,Constants.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,Constants.GL_ALPHA_FUNCTION_SRC=768,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,Constants.GL_ALPHA_FUNCTION_SRC_ALPHA=770,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,Constants.GL_ALPHA_FUNCTION_DST_ALPHA=772,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,Constants.GL_ALPHA_FUNCTION_DST_COLOR=774,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,Constants.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,Constants.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,Constants.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,Constants.SnippetUrl="https://snippet.babylonjs.com",ThinEngine.prototype._debugPushGroup=function(e,t){},ThinEngine.prototype._debugPopGroup=function(e){},ThinEngine.prototype._debugInsertMarker=function(e,t){},ThinEngine.prototype._debugFlushPendingCommands=function(){};let _TimeToken=class _TimeToken{constructor(){this._timeElapsedQueryEnded=!1}};let _OcclusionDataStorage=class _OcclusionDataStorage{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=abstractMesh_AbstractMesh.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}};engine_Engine.prototype.createQuery=function(){let e=this._gl.createQuery();if(!e)throw Error("Unable to create Occlusion Query");return e},engine_Engine.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},engine_Engine.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},engine_Engine.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},engine_Engine.prototype.beginOcclusionQuery=function(e,t){let i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},engine_Engine.prototype.endOcclusionQuery=function(e){let t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},engine_Engine.prototype._createTimeQuery=function(){let e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},engine_Engine.prototype._deleteTimeQuery=function(e){let t=this.getCaps().timerQuery;if(t.deleteQueryEXT){t.deleteQueryEXT(e);return}this.deleteQuery(e)},engine_Engine.prototype._getTimeQueryResult=function(e){let t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},engine_Engine.prototype._getTimeQueryAvailability=function(e){let t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},engine_Engine.prototype.startTimeQuery=function(){let e=this.getCaps(),t=e.timerQuery;if(!t)return null;let i=new _TimeToken;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery),this._currentNonTimestampToken=i}return i},engine_Engine.prototype.endTimeQuery=function(e){let t=this.getCaps(),i=t.timerQuery;if(!i||!e)return -1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return -1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return -1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}let r=this._gl.getParameter(i.GPU_DISJOINT_EXT),s=!1;if(e._endTimeQuery?s=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(s=this._getTimeQueryAvailability(e._timeElapsedQuery)),s&&!r){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return -1;let t=this._getTimeQueryResult(e._startTimeQuery),r=this._getTimeQueryResult(e._endTimeQuery);i=r-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return -1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return -1},engine_Engine.prototype._captureGPUFrameTime=!1,engine_Engine.prototype._gpuFrameTime=new perfCounter_PerfCounter,engine_Engine.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},engine_Engine.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add(()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(()=>{if(!this._gpuFrameTimeToken)return;let 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))},engine_Engine.prototype._getGlAlgorithmType=function(e){return e===abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(abstractMesh_AbstractMesh.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new _OcclusionDataStorage),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),abstractMesh_AbstractMesh.prototype._checkOcclusionQuery=function(){let e=this._occlusionDataStorage;if(e.occlusionType===abstractMesh_AbstractMesh.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;let t=this.getEngine();if(!t.getCaps().supportOcclusionQuery||!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery){let i=t.isQueryResultAvailable(this._occlusionQuery);if(i){let 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!==abstractMesh_AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==abstractMesh_AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}}let i=this.getScene();if(i.getBoundingBoxRenderer){let r=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded},engine_Engine.prototype.createTransformFeedback=function(){let e=this._gl.createTransformFeedback();if(!e)throw Error("Unable to create Transform Feedback");return e},engine_Engine.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},engine_Engine.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},engine_Engine.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},engine_Engine.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},engine_Engine.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},engine_Engine.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},ThinEngine.prototype.createExternalTexture=function(e){return null},ThinEngine.prototype.setExternalTexture=function(e,t){throw Error("setExternalTexture: This engine does not support external textures!")},ThinEngine.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;let r=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),a=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);let t=e._workingCanvas.getContext("2d");if(!t)throw Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),a||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},ThinEngine.prototype.restoreSingleAttachment=function(){let e=this._gl;this.bindAttachments([e.BACK])},ThinEngine.prototype.restoreSingleAttachmentForRenderTarget=function(){let e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},ThinEngine.prototype.buildTextureLayout=function(e){let t=this._gl,i=[];for(let r=0;r<e.length;r++)e[r]?i.push(t["COLOR_ATTACHMENT"+r]):i.push(t.NONE);return i},ThinEngine.prototype.bindAttachments=function(e){let t=this._gl;t.drawBuffers(e)},ThinEngine.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t=!1,i){this._currentRenderTarget=null;let r=this._gl,s=e._attachments,a=s.length;if(e._MSAAFramebuffer){r.bindFramebuffer(r.READ_FRAMEBUFFER,e._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,e._framebuffer);for(let t=0;t<a;t++){let i=e.textures[t];for(let e=0;e<a;e++)s[e]=r.NONE;s[t]=r[this.webGLVersion>1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],r.readBuffer(s[t]),r.drawBuffers(s),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(let e=0;e<a;e++)s[e]=r[this.webGLVersion>1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];r.drawBuffers(s)}for(let i=0;i<a;i++){let s=e.textures[i];(null==s?void 0:s.generateMipMaps)&&!t&&!s.isCube&&(this._bindTextureDirectly(r.TEXTURE_2D,s,!0),r.generateMipmap(r.TEXTURE_2D),this._bindTextureDirectly(r.TEXTURE_2D,null))}i&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),i()),this._bindUnboundFramebuffer(null)},ThinEngine.prototype.createMultipleRenderTarget=function(e,t,i=!0){var r;let s=!1,a=!0,n=!1,o=!1,l=15,h=1,c=[],u=[],d=[],_=[],p=[],f=[],m=[],g=[],v=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(s=void 0!==t.generateMipMaps&&t.generateMipMaps,a=void 0===t.generateDepthBuffer||t.generateDepthBuffer,n=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,o=void 0!==t.generateDepthTexture&&t.generateDepthTexture,h=t.textureCount||1,t.types&&(c=t.types),t.samplingModes&&(u=t.samplingModes),t.useSRGBBuffers&&(d=t.useSRGBBuffers),t.formats&&(_=t.formats),t.targetTypes&&(p=t.targetTypes),t.faceIndex&&(f=t.faceIndex),t.layerIndex&&(m=t.layerIndex),t.layerCounts&&(g=t.layerCounts),this.webGLVersion>1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(l=t.depthTextureFormat));let x=this._gl,b=x.createFramebuffer();this._bindUnboundFramebuffer(b);let T=e.width||e,S=e.height||e,C=[],E=[],y=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),R=this._setupFramebufferDepthAttachments(!y&&n,!o&&a,T,S);v._framebuffer=b,v._depthStencilBuffer=R,v._generateDepthBuffer=!o&&a,v._generateStencilBuffer=!y&&n,v._attachments=E;for(let e=0;e<h;e++){let t=u[e]||3,i=c[e]||0,a=d[e]||!1,n=_[e]||5,o=p[e]||3553,l=null!==(r=g[e])&&void 0!==r?r:1;(1!==i||this._caps.textureFloatLinearFiltering)&&(2!==i||this._caps.textureHalfFloatLinearFiltering)||(t=1);let h=this._getSamplingParameters(t,s);1!==i||this._caps.textureFloat||(i=0,logger_Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),a=a&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU);let f=this.webGLVersion>1,m=x[f?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(E.push(m),-1===o)continue;let v=new internalTexture_InternalTexture(this,$.MultiRenderTarget);C[e]=v,x.activeTexture(x["TEXTURE"+e]),x.bindTexture(o,v._hardwareTexture.underlyingResource),x.texParameteri(o,x.TEXTURE_MAG_FILTER,h.mag),x.texParameteri(o,x.TEXTURE_MIN_FILTER,h.min),x.texParameteri(o,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(o,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE);let b=this._getRGBABufferInternalSizedFormat(i,n,a),y=this._getInternalFormat(n),R=this._getWebGLTextureType(i);if(f&&(35866===o||32879===o))35866===o?v.is2DArray=!0:v.is3D=!0,v.baseDepth=v.depth=l,x.texImage3D(o,0,b,T,S,l,0,y,R,null);else if(34067===o){for(let e=0;e<6;e++)x.texImage2D(x.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,b,T,S,0,y,R,null);v.isCube=!0}else x.texImage2D(x.TEXTURE_2D,0,b,T,S,0,y,R,null);s&&x.generateMipmap(o),this._bindTextureDirectly(o,null),v.baseWidth=T,v.baseHeight=S,v.width=T,v.height=S,v.isReady=!0,v.samples=1,v.generateMipMaps=s,v.samplingMode=t,v.type=i,v._useSRGBBuffer=a,v.format=n,this._internalTexturesCache.push(v)}if(o&&this._caps.depthTextureExtension){let e=new internalTexture_InternalTexture(this,$.Depth),t=5,i=x.DEPTH_COMPONENT16,r=x.DEPTH_COMPONENT,a=x.UNSIGNED_SHORT,n=x.DEPTH_ATTACHMENT;this.webGLVersion<2?i=x.DEPTH_COMPONENT:14===l?(t=1,a=x.FLOAT,i=x.DEPTH_COMPONENT32F):18===l?(t=0,a=x.FLOAT_32_UNSIGNED_INT_24_8_REV,i=x.DEPTH32F_STENCIL8,r=x.DEPTH_STENCIL,n=x.DEPTH_STENCIL_ATTACHMENT):16===l?(t=0,a=x.UNSIGNED_INT,i=x.DEPTH_COMPONENT24,n=x.DEPTH_ATTACHMENT):(13===l||17===l)&&(t=12,a=x.UNSIGNED_INT_24_8,i=x.DEPTH24_STENCIL8,r=x.DEPTH_STENCIL,n=x.DEPTH_STENCIL_ATTACHMENT),x.activeTexture(x.TEXTURE0),x.bindTexture(x.TEXTURE_2D,e._hardwareTexture.underlyingResource),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MAG_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MIN_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE),x.texImage2D(x.TEXTURE_2D,0,i,T,S,0,r,a,null),x.framebufferTexture2D(x.FRAMEBUFFER,n,x.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=T,e.baseHeight=S,e.width=T,e.height=S,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 v.setTextures(C),i&&x.drawBuffers(E),this._bindUnboundFramebuffer(null),v.setLayerAndFaceIndices(m,f),this.resetTextureCache(),v},ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let r=e._attachments.length;if(0===r)return 1;let s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);let a=!!e._depthStencilBuffer;if(a&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof s.renderbufferStorageMultisample){let a=s.createFramebuffer();if(!a)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=a,this._bindUnboundFramebuffer(a);let n=[];for(let t=0;t<r;t++){let i=e.textures[t],r=i._hardwareTexture;r.releaseMSAARenderBuffers()}for(let i=0;i<r;i++){let r=e.textures[i],a=r._hardwareTexture,o=s[this.webGLVersion>1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(r.width,r.height,t,-1,this._getRGBAMultiSampleBufferFormat(r.type,r.format),o);if(!l)throw Error("Unable to create multi sampled framebuffer");a.addMSAARenderBuffer(l),r.samples=t,n.push(o)}i&&s.drawBuffers(n)}else this._bindUnboundFramebuffer(e._framebuffer);return a&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},ThinEngine.prototype._createDepthStencilCubeTexture=function(e,t,i){let r=new internalTexture_InternalTexture(this,$.DepthStencil);if(r.isCube=!0,1===this.webGLVersion)return logger_Logger.Error("Depth cube texture is not supported by WebGL 1."),r;let s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),a=this._gl;this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),i._depthStencilTexture=r,i._depthStencilTextureWithStencil=s.generateStencil;for(let t=0;t<6;t++)s.generateStencil?a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,a.DEPTH24_STENCIL8,e,e,0,a.DEPTH_STENCIL,a.UNSIGNED_INT_24_8,null):a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,a.DEPTH_COMPONENT24,e,e,0,a.DEPTH_COMPONENT,a.UNSIGNED_INT,null);return this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(r),r},ThinEngine.prototype._partialLoadFile=function(e,t,i,r,s=null){this._loadFile(e,e=>{i[t]=e,i._internalCount++,6===i._internalCount&&r(i)},void 0,void 0,!0,(e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)})},ThinEngine.prototype._cascadeLoadFiles=function(e,t,i,r=null){let s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,r)},ThinEngine.prototype._cascadeLoadImgs=function(e,t,i,r,s=null,a){let n=[];n._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(r[o],o,n,e,t,i,s,a)},ThinEngine.prototype._partialLoadImg=function(e,t,i,r,s,a,n=null,o){let l=guid_RandomGUID();LoadImage(e,e=>{i[t]=e,i._internalCount++,r&&r.removePendingData(l),6===i._internalCount&&a&&a(s,i)},(e,t)=>{r&&r.removePendingData(l),n&&n(e,t)},r?r.offlineProvider:null,o),r&&r.addPendingData(l)},ThinEngine.prototype._setCubeMapTextureParams=function(e,t,i){let r=this._gl;r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null)},ThinEngine.prototype.createCubeTextureBase=function(e,t,i,r,s=null,a=null,n,o=null,l=!1,h=0,c=0,u=null,d=null,_=null,p=!1){let f=u||new internalTexture_InternalTexture(this,$.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!r,f._lodGenerationScale=h,f._lodGenerationOffset=c,f._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!r),f!==u&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=o,f._files=i);let m=e;this._transformTextureUrl&&!u&&(e=this._transformTextureUrl(e));let g=e.split("?")[0],v=g.lastIndexOf("."),x=o||(v>-1?g.substring(v).toLowerCase():""),b=null;for(let e of ThinEngine._TextureLoaders)if(e.canLoad(x)){b=e;break}if(b){let onloaddata=e=>{d&&d(f,e),b.loadCubeData(e,f,l,s,a)};i&&6===i.length?b.supportCascades?this._cascadeLoadFiles(t,e=>onloaddata(e.map(e=>new Uint8Array(e))),i,a):a?a("Textures type does not support cascades."):logger_Logger.Warn("Texture loader does not support cascades."):this._loadFile(e,e=>onloaddata(new Uint8Array(e)),void 0,void 0,!0,(u,g)=>{e===m?a&&u&&a(u.status+" "+u.statusText,g):(logger_Logger.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!r,s,a,n,o,l,h,c,f,d,_,p))})}else{if(!i)throw Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,f,(e,t)=>{_&&_(e,t)},i,a)}return this._internalTexturesCache.push(f),f},ThinEngine.prototype.createCubeTexture=function(e,t,i,r,s=null,a=null,n,o=null,l=!1,h=0,c=0,u=null,d,_=!1){let p=this._gl;return this.createCubeTextureBase(e,t,i,!!r,s,a,n,o,l,h,c,u,e=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0),(e,t)=>{let i=this.needPOTTextures?ThinEngine.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,a=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);let o=n?this._getInternalFormat(n,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA,l=n?this._getInternalFormat(n):p.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(l=o);for(let e=0;e<a.length;e++)if(t[e].width!==i||t[e].height!==i){if(this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext){logger_Logger.Warn("Cannot create canvas to resize texture.");return}this._workingCanvas.width=i,this._workingCanvas.height=i,this._workingContext.drawImage(t[e],0,0,t[e].width,t[e].height,0,0,i,i),p.texImage2D(a[e],0,o,l,p.UNSIGNED_BYTE,this._workingCanvas)}else p.texImage2D(a[e],0,o,l,p.UNSIGNED_BYTE,t[e]);r||p.generateMipmap(p.TEXTURE_CUBE_MAP),this._setCubeMapTextureParams(e,!r),e.width=i,e.height=i,e.isReady=!0,n&&(e.format=n),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},!!_)},ThinEngine.prototype.setTextureSampler=function(e,t){throw Error("setTextureSampler: This engine does not support separate texture sampler objects!")};let rM=new observable_Observable,rI=new observable_Observable;function transformTextureUrl(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(t=>e&&(e===t||e.match(RegExp("\\b"+t+"\\b","g")))))return e;let t=e.lastIndexOf("."),i=e.lastIndexOf("?"),r=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+r}Object.defineProperty(engine_Engine.prototype,"onBeforeViewRenderObservable",{get:function(){return rM}}),Object.defineProperty(engine_Engine.prototype,"onAfterViewRenderObservable",{get:function(){return rI}}),Object.defineProperty(engine_Engine.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){var t;this._inputElement!==e&&(this._inputElement=e,null===(t=this._onEngineViewChanged)||void 0===t||t.call(this))}}),engine_Engine.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},engine_Engine.prototype.registerView=function(e,t,i){for(let t of(this.views||(this.views=[]),this.views))if(t.target===e)return t;let r=this.getRenderingCanvas();r&&(e.width=r.width,e.height=r.height);let s={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(s),t&&t.onDisposeObservable.add(()=>{this.unRegisterView(e)}),s},engine_Engine.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(let t of this.views)if(t.target===e){let e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},engine_Engine.prototype._renderViewStep=function(e){let t=e.target,i=t.getContext("2d");if(!i)return!0;let r=this.getRenderingCanvas();rM.notifyObservers(e);let s=e.camera,a=null,n=null;if(s){if(!(n=s.getScene())||n.activeCameras&&n.activeCameras.length)return!0;this.activeView=e,a=n.activeCamera,n.activeCamera=s}if(e.customResize)e.customResize(t);else{let e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||r.width!==t.width||i!==t.height||r.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!!r.width&&!!r.height&&(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),a&&n&&(n.activeCamera=a),rI.notifyObservers(e),!0)},engine_Engine.prototype._renderViews=function(){let e;if(!this.views||0===this.views.length)return!1;let t=this.getRenderingCanvas();if(!t)return!1;for(let t of this.views){if(!t.enabled)continue;let i=t.target;if(i===this.inputElement){e=t;continue}if(!this._renderViewStep(t))return!1}return(!e||!!this._renderViewStep(e))&&(this.activeView=null,!0)},ThinEngine.prototype.createStorageBuffer=function(e,t){throw Error("createStorageBuffer: Unsupported method in this engine!")},ThinEngine.prototype.updateStorageBuffer=function(e,t,i,r){},ThinEngine.prototype.readFromStorageBuffer=function(e,t,i,r){throw Error("readFromStorageBuffer: Unsupported method in this engine!")},ThinEngine.prototype.setStorageBuffer=function(e,t){throw Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(engine_Engine.prototype,"texturesSupported",{get:function(){let e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(engine_Engine.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),engine_Engine.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},engine_Engine.prototype.setTextureFormatToUse=function(e){let t=this.texturesSupported;for(let i=0,r=t.length;i<r;i++)for(let r=0,s=e.length;r<s;r++)if(t[i]===e[r].toLowerCase())return this._transformTextureUrl=transformTextureUrl.bind(this),this._textureFormatInUse=t[i];return this._textureFormatInUse="",this._transformTextureUrl=null,null};let NativeDataStream=class NativeDataStream{constructor(){let e=new ArrayBuffer(NativeDataStream.DEFAULT_BUFFER_SIZE);this._uint32s=new Uint32Array(e),this._int32s=new Int32Array(e),this._float32s=new Float32Array(e),this._length=NativeDataStream.DEFAULT_BUFFER_SIZE/4,this._position=0,this._nativeDataStream=new _native.NativeDataStream(()=>{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}};NativeDataStream.DEFAULT_BUFFER_SIZE=65536;let rD=[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))],rO=[()=>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],applySH3=(e,t)=>rD[e]*rO[e](t),rB=[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];let SphericalHarmonics=class SphericalHarmonics{constructor(){this.preScaled=!1,this.l00=math_vector_Vector3.Zero(),this.l1_1=math_vector_Vector3.Zero(),this.l10=math_vector_Vector3.Zero(),this.l11=math_vector_Vector3.Zero(),this.l2_2=math_vector_Vector3.Zero(),this.l2_1=math_vector_Vector3.Zero(),this.l20=math_vector_Vector3.Zero(),this.l21=math_vector_Vector3.Zero(),this.l22=math_vector_Vector3.Zero()}addLight(e,t,i){math_vector_TmpVectors.Vector3[0].set(t.r,t.g,t.b);let r=math_vector_TmpVectors.Vector3[0],s=math_vector_TmpVectors.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(applySH3(0,e),math_vector_TmpVectors.Vector3[2]),this.l00.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(1,e),math_vector_TmpVectors.Vector3[2]),this.l1_1.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(2,e),math_vector_TmpVectors.Vector3[2]),this.l10.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(3,e),math_vector_TmpVectors.Vector3[2]),this.l11.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(4,e),math_vector_TmpVectors.Vector3[2]),this.l2_2.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(5,e),math_vector_TmpVectors.Vector3[2]),this.l2_1.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(6,e),math_vector_TmpVectors.Vector3[2]),this.l20.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(7,e),math_vector_TmpVectors.Vector3[2]),this.l21.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(8,e),math_vector_TmpVectors.Vector3[2]),this.l22.addInPlace(math_vector_TmpVectors.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(rB[0]),this.l1_1.scaleInPlace(rB[1]),this.l10.scaleInPlace(rB[2]),this.l11.scaleInPlace(rB[3]),this.l2_2.scaleInPlace(rB[4]),this.l2_1.scaleInPlace(rB[5]),this.l20.scaleInPlace(rB[6]),this.l21.scaleInPlace(rB[7]),this.l22.scaleInPlace(rB[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(rD[0]),this.l1_1.scaleInPlace(rD[1]),this.l10.scaleInPlace(rD[2]),this.l11.scaleInPlace(rD[3]),this.l2_2.scaleInPlace(rD[4]),this.l2_1.scaleInPlace(rD[5]),this.l20.scaleInPlace(rD[6]),this.l21.scaleInPlace(rD[7]),this.l22.scaleInPlace(rD[8])}updateFromArray(e){return math_vector_Vector3.FromArrayToRef(e[0],0,this.l00),math_vector_Vector3.FromArrayToRef(e[1],0,this.l1_1),math_vector_Vector3.FromArrayToRef(e[2],0,this.l10),math_vector_Vector3.FromArrayToRef(e[3],0,this.l11),math_vector_Vector3.FromArrayToRef(e[4],0,this.l2_2),math_vector_Vector3.FromArrayToRef(e[5],0,this.l2_1),math_vector_Vector3.FromArrayToRef(e[6],0,this.l20),math_vector_Vector3.FromArrayToRef(e[7],0,this.l21),math_vector_Vector3.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return math_vector_Vector3.FromFloatsToRef(e[0],e[1],e[2],this.l00),math_vector_Vector3.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),math_vector_Vector3.FromFloatsToRef(e[6],e[7],e[8],this.l10),math_vector_Vector3.FromFloatsToRef(e[9],e[10],e[11],this.l11),math_vector_Vector3.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),math_vector_Vector3.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),math_vector_Vector3.FromFloatsToRef(e[18],e[19],e[20],this.l20),math_vector_Vector3.FromFloatsToRef(e[21],e[22],e[23],this.l21),math_vector_Vector3.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){let t=new SphericalHarmonics;return t.updateFromArray(e)}static FromPolynomial(e){let t=new SphericalHarmonics;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}};let SphericalPolynomial=class SphericalPolynomial{constructor(){this.x=math_vector_Vector3.Zero(),this.y=math_vector_Vector3.Zero(),this.z=math_vector_Vector3.Zero(),this.xx=math_vector_Vector3.Zero(),this.yy=math_vector_Vector3.Zero(),this.zz=math_vector_Vector3.Zero(),this.xy=math_vector_Vector3.Zero(),this.yz=math_vector_Vector3.Zero(),this.zx=math_vector_Vector3.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=SphericalHarmonics.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){math_vector_TmpVectors.Vector3[0].copyFromFloats(e.r,e.g,e.b);let t=math_vector_TmpVectors.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),math_vector_TmpVectors.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),math_vector_TmpVectors.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(math_vector_TmpVectors.Vector3[0]).addInPlace(math_vector_TmpVectors.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(math_vector_TmpVectors.Vector3[0]).subtractInPlace(math_vector_TmpVectors.Vector3[1]),this.zz.copyFrom(e.l00),math_vector_TmpVectors.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(math_vector_TmpVectors.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){let t=new SphericalPolynomial;return t.updateFromHarmonics(e)}static FromArray(e){let t=new SphericalPolynomial;return math_vector_Vector3.FromArrayToRef(e[0],0,t.x),math_vector_Vector3.FromArrayToRef(e[1],0,t.y),math_vector_Vector3.FromArrayToRef(e[2],0,t.z),math_vector_Vector3.FromArrayToRef(e[3],0,t.xx),math_vector_Vector3.FromArrayToRef(e[4],0,t.yy),math_vector_Vector3.FromArrayToRef(e[5],0,t.zz),math_vector_Vector3.FromArrayToRef(e[6],0,t.yz),math_vector_Vector3.FromArrayToRef(e[7],0,t.zx),math_vector_Vector3.FromArrayToRef(e[8],0,t.xy),t}};let rN=`varying vec2 vUV;uniform sampler2D textureSampler; +#include<helperFunctions> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;function CreateResizedCopy(e,t,i,r=!0){let s=e.getScene(),a=s.getEngine(),n=new renderTargetTexture_RenderTargetTexture("resized"+e.name,{width:t,height:i},s,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);n.wrapU=e.wrapU,n.wrapV=e.wrapV,n.uOffset=e.uOffset,n.vOffset=e.vOffset,n.uScale=e.uScale,n.vScale=e.vScale,n.uAng=e.uAng,n.vAng=e.vAng,n.wAng=e.wAng,n.coordinatesIndex=e.coordinatesIndex,n.level=e.level,n.anisotropicFilteringLevel=e.anisotropicFilteringLevel,n._texture.isReady=!1,e.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.wrapV=texture_Texture.CLAMP_ADDRESSMODE;let o=new PassPostProcess("pass",1,null,r?texture_Texture.BILINEAR_SAMPLINGMODE:texture_Texture.NEAREST_SAMPLINGMODE,a,!1,0);return o.externalTextureSamplerBinding=!0,o.getEffect().executeWhenCompiled(()=>{o.onApply=function(t){t.setTexture("textureSampler",e)};let t=n.renderTarget;t&&(s.postProcessManager.directRender([o],t),a.unBindFramebuffer(t),n.disposeFramebufferObjects(),o.dispose(),n.getInternalTexture().isReady=!0)}),n}function ApplyPostProcess(e,t,i,r,s,a,n,o){let l=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,r=null!=r?r:t.type,a=null!=a?a:t.format,n=null!=n?n:t.width,o=null!=o?o:t.height,-1===r&&(r=0),new Promise(h=>{let c=new postProcess_PostProcess("postprocess",e,null,null,1,null,s,l,!1,void 0,r,void 0,null,!1,a);c.externalTextureSamplerBinding=!0;let u=l.createRenderTargetTexture({width:n,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:r,format:a});c.getEffect().executeWhenCompiled(()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.type=r,t.format=5,t.isReady=!0,h(t)})})}function ToHalfFloat(e){s||(s=new Float32Array(1),a=new Int32Array(s.buffer)),s[0]=e;let t=a[0],i=t>>16&32768,r=t>>12&2047,n=t>>23&255;return n<103?i:n>142?(i|=31744,i|=(255==n?0:1)&&8388607&t):n<113?(r|=2048,i|=(r>>114-n)+(r>>113-n&1)):(i|=n-112<<10|r>>1,i+=1&r)}function FromHalfFloat(e){let t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*6103515625e-14*(r/1024):31==i?r?NaN:(t?-1:1)*(1/0):(t?-1:1)*Math.pow(2,i-15)*(1+r/1024)}ShaderStore.ShadersStore.rgbdDecodePixelShader=rN;let ProcessAsync=async(e,t,i,r,s)=>{let a;let n=e.getScene(),o=n.getEngine();a=e.isCube?new postProcess_PostProcess("lodCube","lodCube",["lod","gamma"],null,1,null,texture_Texture.NEAREST_NEAREST_MIPNEAREST,o,!1,["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"][r]):new postProcess_PostProcess("lod","lod",["lod","gamma"],null,1,null,texture_Texture.NEAREST_NEAREST_MIPNEAREST,o),await new Promise(e=>{a.getEffect().executeWhenCompiled(()=>{e(0)})});let l=new renderTargetTexture_RenderTargetTexture("temp",{width:t,height:i},n,!1);a.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",s),t.setBool("gamma",e.gammaSpace)};let h=e.getInternalTexture();try{if(l.renderTarget&&h){let r=h.samplingMode;0!==s?e.updateSamplingMode(texture_Texture.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(texture_Texture.NEAREST_NEAREST),n.postProcessManager.directRender([a],l.renderTarget,!0),e.updateSamplingMode(r);let c=await o.readPixels(0,0,t,i),u=new Uint8Array(c.buffer,0,c.byteLength);return o.unBindFramebuffer(l.renderTarget),u}throw Error("Render to texture failed.")}finally{l.dispose(),a.dispose()}};async function GetTextureDataAsync(e,t,i,r=0,s=0){return!e.isReady()&&e._texture&&await new Promise((t,i)=>{if(null===e._texture){i(0);return}e._texture.onLoadedObservable.addOnce(()=>{t(0)})}),await ProcessAsync(e,t,i,r,s)}let rF={CreateResizedCopy,ApplyPostProcess,ToHalfFloat,FromHalfFloat,GetTextureDataAsync};let RGBDTextureTools=class RGBDTextureTools{static ExpandRGBDTexture(e){let t=e._texture;if(!t||!e.isRGBD)return;let i=t.getEngine(),r=i.getCaps(),s=t.isReady,a=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(a=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(a=!0,t.type=1),a&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);let expandRGBDTexture=()=>{if(a){let r=new postProcess_PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);r.externalTextureSamplerBinding=!0;let s=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});r.getEffect().executeWhenCompiled(()=>{r.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([r],s,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),r&&r.dispose(),s._swapAndDie(t),t.isReady=!0})}};s?expandRGBDTexture():e.onLoadObservable.addOnce(expandRGBDTexture)}static EncodeTextureToRGBD(e,t,i=0){return ApplyPostProcess("rgbdEncode",e,t,i,1,5)}};let FileFaceOrientation=class FileFaceOrientation{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}};let CubeMapToSphericalPolynomialTools=class CubeMapToSphericalPolynomialTools{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;let i,r;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();let s=e.getSize().width,a=e.readPixels(0,void 0,void 0,!1),n=e.readPixels(1,void 0,void 0,!1);e.isRenderTarget?(i=e.readPixels(3,void 0,void 0,!1),r=e.readPixels(2,void 0,void 0,!1)):(i=e.readPixels(2,void 0,void 0,!1),r=e.readPixels(3,void 0,void 0,!1));let o=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,c=0;return(1==e.textureType||2==e.textureType)&&(c=1),new Promise(e=>{Promise.all([n,a,i,r,o,l]).then(([t,i,r,a,n,o])=>{let l={size:s,right:i,left:t,up:r,down:a,front:n,back:o,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){let t=new SphericalHarmonics,i=0,r=2/e.size,s=.5*r,a=s-1;for(let n=0;n<6;n++){let o=this._FileFaces[n],l=e[o.name],h=a,c=5===e.format?4:3;for(let n=0;n<e.size;n++){let u=a;for(let a=0;a<e.size;a++){let d=o.worldAxisForFileX.scale(u).add(o.worldAxisForFileY.scale(h)).add(o.worldAxisForNormal);d.normalize();let _=this._AreaElement(u-s,h-s)-this._AreaElement(u-s,h+s)-this._AreaElement(u+s,h-s)+this._AreaElement(u+s,h+s),p=l[n*e.size*c+a*c+0],f=l[n*e.size*c+a*c+1],m=l[n*e.size*c+a*c+2];isNaN(p)&&(p=0),isNaN(f)&&(f=0),isNaN(m)&&(m=0),0===e.type&&(p/=255,f/=255,m/=255),e.gammaSpace&&(p=Math.pow(math_scalar_Scalar.Clamp(p),2.2),f=Math.pow(math_scalar_Scalar.Clamp(f),2.2),m=Math.pow(math_scalar_Scalar.Clamp(m),2.2));let g=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){let e=Math.max(p,f,m);if(e>g){let t=g/e;p*=t,f*=t,m*=t}}else p=math_scalar_Scalar.Clamp(p,0,g),f=math_scalar_Scalar.Clamp(f,0,g),m=math_scalar_Scalar.Clamp(m,0,g);let v=new math_color_Color3(p,f,m);t.addLight(d,v,_),i+=_,u+=r}h+=r}}let n=4*Math.PI*6/6/i;return t.scaleInPlace(n),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),SphericalPolynomial.FromHarmonics(t)}};CubeMapToSphericalPolynomialTools._FileFaces=[new FileFaceOrientation("right",new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,0,-1),new math_vector_Vector3(0,-1,0)),new FileFaceOrientation("left",new math_vector_Vector3(-1,0,0),new math_vector_Vector3(0,0,1),new math_vector_Vector3(0,-1,0)),new FileFaceOrientation("up",new math_vector_Vector3(0,1,0),new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,0,1)),new FileFaceOrientation("down",new math_vector_Vector3(0,-1,0),new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,0,-1)),new FileFaceOrientation("front",new math_vector_Vector3(0,0,1),new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,-1,0)),new FileFaceOrientation("back",new math_vector_Vector3(0,0,-1),new math_vector_Vector3(-1,0,0),new math_vector_Vector3(0,-1,0))],CubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE=4096,CubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS=!1,baseTexture_BaseTexture.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(baseTexture_BaseTexture.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;this._texture.isReady&&!this._texture._sphericalPolynomialPromise&&(this._texture._sphericalPolynomialPromise=CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});let rw=`varying vec2 vUV;uniform sampler2D textureSampler; +#include<helperFunctions> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;ShaderStore.ShadersStore.rgbdEncodePixelShader=rw;let rL="image/png",rV=[134,22,135,150,246,214,150,54];function GetEnvInfo(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=0;for(let e=0;e<rV.length;e++)if(t.getUint8(i++)!==rV[e])return logger_Logger.Error("Not a babylon environment map"),null;let r="",s=0;for(;s=t.getUint8(i++);)r+=String.fromCharCode(s);let a=JSON.parse(r);return(a=normalizeEnvInfo(a)).specular&&(a.specular.specularDataPosition=i,a.specular.lodGenerationScale=a.specular.lodGenerationScale||.8),a}function normalizeEnvInfo(e){if(e.version>2)throw Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "2".`);return 2===e.version?e:e=Object.assign(Object.assign({},e),{version:2,imageType:rL})}function CreateImageDataArrayBufferViews(e,t){t=normalizeEnvInfo(t);let i=t.specular,r=math_scalar_Scalar.Log2(t.width);if(r=Math.round(r)+1,i.mipmaps.length!==6*r)throw Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);let s=Array(r);for(let t=0;t<r;t++){s[t]=Array(6);for(let r=0;r<6;r++){let a=i.mipmaps[6*t+r];s[t][r]=new Uint8Array(e.buffer,e.byteOffset+i.specularDataPosition+a.position,a.length)}}return s}function UploadEnvLevelsAsync(e,t,i){i=normalizeEnvInfo(i);let r=i.specular;if(!r)return Promise.resolve();e._lodGenerationScale=r.lodGenerationScale;let s=CreateImageDataArrayBufferViews(t,i);return UploadLevelsAsync(e,s,i.imageType)}function _OnImageReadyAsync(e,t,i,r,s,a,n,o,l,h,c){return new Promise((u,d)=>{if(i){let i=t.createTexture(null,!0,!0,null,1,null,e=>{d(e)},e);r.getEffect().executeWhenCompiled(()=>{r.externalTextureSamplerBinding=!0,r.onApply=r=>{r._bindTexture("textureSampler",i),r.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([r],h,!0,a,n),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),u())})}else{if(t._uploadImageToTexture(c,e,a,n),o){let i=l[n];i&&t._uploadImageToTexture(i._texture,e,a,0)}u()}})}function UploadLevelsAsync(e,t,i=rL){if(!tools_Tools.IsExponentOfTwo(e.width))throw Error("Texture size must be a power of two");let r=math_scalar_Scalar.ILog2(e.width)+1,s=e.getEngine(),a=!1,n=!1,o=null,l=null,h=null,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?(a=!0,e.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(a=!0,e.type=1):a=!1:(a=!1,n=!0,h={}),a)o=new postProcess_PostProcess("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,n){let t=e._lodGenerationScale,i=e._lodGenerationOffset;for(let a=0;a<3;a++){let n=a/2,o=1-n,l=(r-1)*t+i,c=i+(l-i)*o,u=Math.round(Math.min(Math.max(c,0),l)),d=new internalTexture_InternalTexture(s,$.Temp);d.isCube=!0,d.invertY=!0,d.generateMipMaps=!1,s.updateTextureSamplingMode(2,d);let _=new baseTexture_BaseTexture(null);switch(_._isCube=!0,_._texture=d,h[u]=_,a){case 0:e._lodTextureLow=_;break;case 1:e._lodTextureMid=_;break;case 2:e._lodTextureHigh=_}}}let u=[];for(let r=0;r<t.length;r++)for(let c=0;c<6;c++){let d;let _=t[r][c],p=new Blob([_],{type:i}),f=URL.createObjectURL(p);if("undefined"==typeof Image||s._features.forceBitmapOverHTMLImageElement)d=s.createImageBitmap(p,{premultiplyAlpha:"none"}).then(t=>_OnImageReadyAsync(t,s,a,o,f,c,r,n,h,l,e));else{let t=new Image;t.src=f,d=new Promise((i,u)=>{t.onload=()=>{_OnImageReadyAsync(t,s,a,o,f,c,r,n,h,l,e).then(()=>i()).catch(e=>{u(e)})},t.onerror=e=>{u(e)}})}u.push(d)}if(t.length<r){let i;let a=Math.pow(2,r-1-t.length),n=a*a*4;switch(e.type){case 0:i=new Uint8Array(n);break;case 2:i=new Uint16Array(n);break;case 1:i=new Float32Array(n)}for(let a=t.length;a<r;a++)for(let t=0;t<6;t++)s._uploadArrayBufferViewToTexture(e,i,t,a)}return Promise.all(u).then(()=>{l&&(s._releaseTexture(e),l._swapAndDie(e)),o&&o.dispose(),n&&(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 UploadEnvSpherical(e,t){t=normalizeEnvInfo(t);let i=t.irradiance;if(!i)return;let r=new SphericalPolynomial;math_vector_Vector3.FromArrayToRef(i.x,0,r.x),math_vector_Vector3.FromArrayToRef(i.y,0,r.y),math_vector_Vector3.FromArrayToRef(i.z,0,r.z),math_vector_Vector3.FromArrayToRef(i.xx,0,r.xx),math_vector_Vector3.FromArrayToRef(i.yy,0,r.yy),math_vector_Vector3.FromArrayToRef(i.zz,0,r.zz),math_vector_Vector3.FromArrayToRef(i.yz,0,r.yz),math_vector_Vector3.FromArrayToRef(i.zx,0,r.zx),math_vector_Vector3.FromArrayToRef(i.xy,0,r.xy),e._sphericalPolynomial=r}function ExtractBetweenMarkers(e,t,i,r){let s=r,a=0,n="";for(;s<i.length;){let r=i.charAt(s);if(n)r===n?'"'===n||"'"===n?"\\"!==i.charAt(s-1)&&(n=""):n="":"*/"===n&&"*"===r&&s+1<i.length&&("/"===i.charAt(s+1)&&(n=""),""===n&&s++);else switch(r){case e:a++;break;case t:a--;break;case'"':case"'":case"`":n=r;break;case"/":if(s+1<i.length){let e=i.charAt(s+1);"/"===e?n="\n":"*"===e&&(n="*/")}}if(s++,0===a)break}return 0===a?s-1:-1}function SkipWhitespaces(e,t){for(;t<e.length;){let i=e[t];if(" "!==i&&"\n"!==i&&"\r"!==i&&" "!==i&&"\n"!==i&&"\xa0"!==i)break;t++}return t}function IsIdentifierChar(e){let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function RemoveComments(e){let t=0,i="",r=!1,s=[];for(;t<e.length;){let a=e.charAt(t);if(i)a===i?'"'===i||"'"===i?("\\"!==e.charAt(t-1)&&(i=""),s.push(a)):(i="",r=!1):"*/"===i&&"*"===a&&t+1<e.length?("/"===e.charAt(t+1)&&(i=""),""===i&&(r=!1,t++)):r||s.push(a);else{switch(a){case'"':case"'":case"`":i=a;break;case"/":if(t+1<e.length){let s=e.charAt(t+1);"/"===s?(i="\n",r=!0):"*"===s&&(i="*/",r=!0)}}r||s.push(a)}t++}return s.join("")}function FindBackward(e,t,i){for(;t>=0&&e.charAt(t)!==i;)t--;return t}function EscapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}let ShaderCodeInliner=class ShaderCodeInliner{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<this._sourceCode.length;){let t=this._sourceCode.indexOf(this.inlineToken,e);if(t<0)break;let i=this._sourceCode.indexOf("(",t+this.inlineToken.length);if(i<0){this.debug&&console.warn(`Could not find the opening parenthesis after the token. startIndex=${e}`),e=t+this.inlineToken.length;continue}let r=ShaderCodeInliner._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(t+this.inlineToken.length,i));if(!r){this.debug&&console.warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(t+this.inlineToken.length,i)}`),e=t+this.inlineToken.length;continue}let[s,a]=[r[3],r[4]],n=ExtractBetweenMarkers("(",")",this._sourceCode,i);if(n<0){this.debug&&console.warn(`Could not extract the parameters the function '${a}' (type=${s}). funcParamsStartIndex=${i}`),e=t+this.inlineToken.length;continue}let o=this._sourceCode.substring(i+1,n),l=SkipWhitespaces(this._sourceCode,n+1);if(l===this._sourceCode.length){this.debug&&console.warn(`Could not extract the body of the function '${a}' (type=${s}). funcParamsEndIndex=${n}`),e=t+this.inlineToken.length;continue}let h=ExtractBetweenMarkers("{","}",this._sourceCode,l);if(h<0){this.debug&&console.warn(`Could not extract the body of the function '${a}' (type=${s}). funcBodyStartIndex=${l}`),e=t+this.inlineToken.length;continue}let c=this._sourceCode.substring(l,h+1),u=RemoveComments(o).split(","),d=[];for(let e=0;e<u.length;++e){let t=u[e].trim(),i=t.lastIndexOf(" ");i>=0&&d.push(t.substring(i+1))}"void"!==s&&d.push("return"),this._functionDescr.push({name:a,type:s,parameters:d,body:c,callIndex:0}),e=h+1;let _=t>0?this._sourceCode.substring(0,t):"",p=h+1<this._sourceCode.length-1?this._sourceCode.substring(h+1):"";this._sourceCode=_+p,e-=h+1-t}this.debug&&console.log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=`,this._functionDescr)}_processInlining(e=20){for(;e-- >=0&&this._replaceFunctionCallsByCode(););return this.debug&&console.log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(let t of this._functionDescr){let{name:i,type:r,parameters:s,body:a}=t,n=0;for(;n<this._sourceCode.length;){let o=this._sourceCode.indexOf(i,n);if(o<0)break;if(0===o||IsIdentifierChar(this._sourceCode.charAt(o-1))){n=o+i.length;continue}let l=SkipWhitespaces(this._sourceCode,o+i.length);if(l===this._sourceCode.length||"("!==this._sourceCode.charAt(l)){n=o+i.length;continue}let h=ExtractBetweenMarkers("(",")",this._sourceCode,l);if(h<0){this.debug&&console.warn(`Could not extract the parameters of the function call. Function '${i}' (type=${r}). callParamsStartIndex=${l}`),n=o+i.length;continue}let c=this._sourceCode.substring(l+1,h),splitParameterCall=e=>{let t=[],i=0,r=0;for(;i<e.length;){if("("===e.charAt(i)){let t=ExtractBetweenMarkers("(",")",e,i);if(t<0)return null;i=t}else","===e.charAt(i)&&(t.push(e.substring(r,i)),r=i+1);i++}return r<i&&t.push(e.substring(r,i)),t},u=splitParameterCall(RemoveComments(c));if(null===u){this.debug&&console.warn(`Invalid function call: can't extract the parameters of the function call. Function '${i}' (type=${r}). callParamsStartIndex=${l}, callParams=`+c),n=o+i.length;continue}let d=[];for(let e=0;e<u.length;++e){let t=u[e].trim();d.push(t)}let _="void"!==r?i+"_"+t.callIndex++:null;if(_&&d.push(_+" ="),d.length!==s.length){this.debug&&console.warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${i}' (type=${r}). function parameters=${s}, call parameters=${d}`),n=o+i.length;continue}n=h+1;let p=this._replaceNames(a,s,d),f=o>0?this._sourceCode.substring(0,o):"",m=h+1<this._sourceCode.length-1?this._sourceCode.substring(h+1):"";if(_){let e=FindBackward(this._sourceCode,o-1,"\n");f=this._sourceCode.substring(0,e+1);let t=this._sourceCode.substring(e+1,o);this._sourceCode=f+r+" "+_+";\n"+p+"\n"+t+_+m,this.debug&&console.log(`Replace function call by code. Function '${i}' (type=${r}). injectDeclarationIndex=${e}, call parameters=${d}`)}else this._sourceCode=f+p+m,n+=p.length-(h+1-o),this.debug&&console.log(`Replace function call by code. Function '${i}' (type=${r}). functionCallIndex=${o}, call parameters=${d}`);e=!0}}return e}_replaceNames(e,t,i){for(let r=0;r<t.length;++r){let s=RegExp(EscapeRegExp(t[r]),"g"),a=t[r].length,n=i[r];e=e.replace(s,(i,...s)=>{let o=s[0];return IsIdentifierChar(e.charAt(o-1))||IsIdentifierChar(e.charAt(o+a))?t[r]:n})}return e}};ShaderCodeInliner._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;let NativePipelineContext=class NativePipelineContext{get isAsync(){return this.isParallelCompiled}get isReady(){if(this.compilationError){let e=this.compilationError.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}_handlesSpectorRebuildCallback(e){throw Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,r,s,a,n,o){let l;let h=this._engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);let c=this._engine.getUniforms(this,i);for(c.forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l<s.length;l++){let t=e.getUniform(s[l]);null==t&&(s.splice(l,1),l--)}s.forEach((e,t)=>{a[e]=t}),o.push(...h.getAttributes(this,n))}dispose(){this._uniforms={}}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s)return s=[t,i,r],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==r&&(s[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,s){let a=this._valueCache[e];if(!a)return a=[t,i,r,s],this._valueCache[e]=a,!0;let n=!1;return a[0]!==t&&(a[0]=t,n=!0),a[1]!==i&&(a[1]=i,n=!0),a[2]!==r&&(a[2]=r,n=!0),a[3]!==s&&(a[3]=s,n=!0),n}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setUInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&!this._engine.setMatrices(this._uniforms[e],t.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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&!this._engine.setFloat2(this._uniforms[e],t.x,t.y)&&(this._valueCache[e]=null)}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setFloat2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&!this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)&&(this._valueCache[e]=null)}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setFloat3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setFloat4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&!this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)&&(this._valueCache[e]=null)}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(this._valueCache[e]=null)}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&!this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)&&(this._valueCache[e]=null)}};let NativeRenderTargetWrapper=class NativeRenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}};let NativeHardwareTexture=class NativeHardwareTexture{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}};function getNativeTextureFormat(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new RuntimeError(`Unsupported texture format or type: format ${e}, type ${t}.`,b.UnsupportedTextureError)}function 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 Error(`Unsupported sampling mode: ${e}.`)}}function getNativeAddressMode(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 Error("Unexpected wrap mode: "+e+".")}}function getNativeStencilFunc(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 Error(`Unsupported stencil func mode: ${e}.`)}}function getNativeStencilOpFail(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 Error(`Unsupported stencil OpFail mode: ${e}.`)}}function getNativeStencilDepthFail(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 Error(`Unsupported stencil depthFail mode: ${e}.`)}}function getNativeStencilDepthPass(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 Error(`Unsupported stencil opPass mode: ${e}.`)}}function 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 Error(`Unsupported alpha mode: ${e}.`)}}function getNativeAttribType(e){switch(e){case buffer_VertexBuffer.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case buffer_VertexBuffer.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case buffer_VertexBuffer.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case buffer_VertexBuffer.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case buffer_VertexBuffer.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw Error(`Unsupported attribute type: ${e}.`)}}let rU=new observable_Observable;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{(e=t)&&rU.notifyObservers(e)}})}function AcquireNativeObjectAsync(){return new Promise(e=>{"undefined"==typeof _native?rU.addOnce(t=>e(t)):e(_native)})}async function RegisterNativeTypeAsync(e,t){(await AcquireNativeObjectAsync())[e]=t}let NativeDataBuffer=class NativeDataBuffer extends dataBuffer_DataBuffer{};let CommandBufferEncoder=class CommandBufferEncoder{constructor(e){this._engine=e,this._pending=[],this._isCommandBufferScopeActive=!1,this._commandStream=NativeEngine._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw 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}};let NativeEngine=class NativeEngine extends engine_Engine{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 CommandBufferEncoder(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!==NativeEngine.PROTOCOL_VERSION)throw Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${NativeEngine.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:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1},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:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},tools_Tools.Log("Babylon Native (v"+engine_Engine.Version+") launched"),tools_Tools.LoadScript=function(e,t,i,r){tools_Tools.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 flat(){let e=isNaN(arguments[0])?1:Number(arguments[0]);return e?Array.prototype.reduce.call(this,function(t,i){return Array.isArray(i)?t.push.apply(t,flat.call(i,e-1)):t.push(i),t},[]):Array.prototype.slice.call(this)},writable:!0});let t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();let i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new WebGL2ShaderProcessor,this.onNewSceneAddedObservable.add(e=>{let 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 NativeDataStream}_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,r=!1){if(this.useReverseDepthBuffer)throw Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){let r=this._normalizeIndexData(e),s=new NativeDataBuffer;return s.references=1,s.is32Bits=4===r.BYTES_PER_ELEMENT,r.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,s.is32Bits,null!=t&&t)),s}createVertexBuffer(e,t,i){let r=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new NativeDataBuffer;return s.references=1,r.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,null!=t&&t)),s}_recordVertexArrayObject(e,t,i,r,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);let a=r.getAttributesNames();for(let i=0;i<a.length;i++){let n=r.getAttributeLocation(i);if(n>=0){let r=a[i],o=null;if(s&&(o=s[r]),o||(o=t[r]),o){let t=o.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,n,o.byteOffset,o.byteStride,o.getSize(),getNativeAttribType(o.type),o.normalized,o.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){let s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,r),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){return this._engine.getAttributes(e.nativeProgram,t)}drawElementsType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(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,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(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 NativePipelineContext(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,r,s,a,n,o){r?e.nativeProgram=this.createRawShaderProgram():e.nativeProgram=this.createShaderProgram(e,t,i,o)}isAsync(e){return!!(e.isAsync&&this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){if(!this.isAsync(e)){t();return}let i=e.onCompiled;i?e.onCompiled=()=>{i(),t()}:e.onCompiled=t}createRawShaderProgram(){throw Error("Not Supported")}createShaderProgram(e,t,i,r){if(e.nativeProgram)throw Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=new ShaderCodeInliner(t);s.processCode(),t=s.code;let a=new ShaderCodeInliner(i);a.processCode(),i=a.code,t=ThinEngine._ConcatenateShader(t,r),i=ThinEngine._ConcatenateShader(i,r);let onSuccess=()=>{var t;e.isCompiled=!0,null===(t=e.onCompiled)||void 0===t||t.call(e),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,onSuccess,t=>{e.compilationError=t});try{let r=e.nativeProgram=this._engine.createProgram(t,i);return onSuccess(),r}catch(t){let e=null==t?void 0:t.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}}inlineShaderCode(e){let t=new ShaderCodeInliner(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){e&&e.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){return this._engine.getUniforms(e.nativeProgram,t)}bindUniformBlock(e,t,i){throw Error("Not Implemented")}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.nativeProgram);let i=e.getSamplers();for(let t=0;t<i.length;t++){let r=e.getUniform(i[t]);r&&(this._boundUniforms[t]=r)}this._currentEffect=null}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._engine.getRenderWidth()}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._engine.getRenderHeight()}setViewport(e,t,i){this._cachedViewport=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.x),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.y),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.width),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.height),this._commandBufferEncoder.finishEncodingCommand()}enableScissor(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR),this._commandBufferEncoder.encodeCommandArgAsFloat32(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand()}disableScissor(){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.finishEncodingCommand()}setState(e,t=0,i,r=!1,s,a,n=0){var o,l;this._zOffset=t,this._zOffsetUnits=n,0!==this._zOffset&&tools_Tools.Warn("zOffset is not supported in Native engine."),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.encodeCommandArgAsUInt32(null===(l=null!==(o=this.cullBackFaces)&&void 0!==o?o:s)||void 0===l||l?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.finishEncodingCommand()}getInputElementClientRect(){let e={bottom:this.getRenderHeight(),height:this.getRenderHeight(),left:0,right:this.getRenderWidth(),top:0,width:this.getRenderWidth(),x:0,y:0,toJSON:()=>{}};return e}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,getNativeStencilOpFail(this._stencilOpStencilFail),getNativeStencilDepthFail(this._stencilOpDepthFail),getNativeStencilDepthPass(this._stencilOpStencilDepthPass),getNativeStencilFunc(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,r,s,a){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(a),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,r){throw Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;let i=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,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,r,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,r=!1,s){if(void 0===r&&(r=!1),e&&e._hardwareTexture){let i=t.getCanvasTexture(),r=e._hardwareTexture.underlyingResource;this._engine.copyTexture(r,i),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){let r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,s,a,n,o=null,l=0,h=0,c=!1){let u=new internalTexture_InternalTexture(this,$.Raw);if(u.format=r,u.generateMipMaps=s,u.samplingMode=n,u.invertY=a,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=o,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this.updateRawTexture(u,e,r,a,o,l,u._useSRGBBuffer),u._hardwareTexture){let e=u._hardwareTexture.underlyingResource,t=getNativeSamplingMode(n);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,r,s,a,n,o,l=null,h=0){let c=new internalTexture_InternalTexture(this,$.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=r,c.width=t,c.height=i,c.depth=r,c.format=s,c.type=h,c.generateMipMaps=a,c.samplingMode=o,c.is2DArray=!0,c._hardwareTexture){let l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,r,getNativeTextureFormat(s,h),a,n);let u=getNativeSamplingMode(o);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,r,s=null,a=0,n=!1){if(e){if(t&&e._hardwareTexture){let r=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(r,t,e.width,e.height,getNativeTextureFormat(i,a),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,s=3,a=null,n=null,o=null,l=null,h=null,c=null,u,d,_,p=!1){e=e||"";let f="data:"===e.substr(0,5),m=f&&-1!==e.indexOf(";base64,"),g=l||new internalTexture_InternalTexture(this,$.Url),v=e;!this._transformTextureUrl||m||l||o||(e=this._transformTextureUrl(e));let x=e.lastIndexOf("."),b=c||(x>-1?e.substring(x).toLowerCase():""),T=null;for(let e of engine_Engine._TextureLoaders)if(e.canLoad(b)){T=e;break}r&&r.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=s,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(p,t),this.doNotHandleContextLost||(g._buffer=o);let S=null;a&&!l&&(S=g.onLoadedObservable.add(a)),l||this._internalTexturesCache.push(g);let onInternalError=(i,l)=>{r&&r.removePendingData(g),e===v?(S&&g.onLoadedObservable.remove(S),engineStore_EngineStore.UseFallbackTexture&&this.createTexture(engineStore_EngineStore.FallbackTexture,t,g.invertY,r,s,null,n,o,g),n&&n((i||"Unknown error")+(engineStore_EngineStore.UseFallbackTexture?" - Fallback texture was used":""),l)):(logger_Logger.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,r,s,a,n,o,g,h,c,u,d))};if(T)throw Error("Loading textures from IInternalTextureLoader not yet implemented.");{let onload=e=>{if(!g._hardwareTexture){r&&r.removePendingData(g);return}let a=g._hardwareTexture.underlyingResource;this._engine.loadTexture(a,e,!t,i,g._useSRGBBuffer,()=>{g.baseWidth=this._engine.getTextureWidth(a),g.baseHeight=this._engine.getTextureHeight(a),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;let e=getNativeSamplingMode(s);this._setTextureSampling(a,e),r&&r.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>{throw Error("Could not load a native texture.")})};if(f&&o){if(o instanceof ArrayBuffer)onload(new Uint8Array(o));else if(ArrayBuffer.isView(o))onload(o);else if("string"==typeof o)onload(new Uint8Array(tools_Tools.DecodeBase64(o)));else throw Error("Unsupported buffer type")}else m?onload(new Uint8Array(tools_Tools.DecodeBase64(e))):this._loadFile(e,e=>onload(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{onInternalError("Unable to load "+(e&&e.responseURL,t))})}return g}wrapNativeTexture(e,t=!1,i=3){let r=new NativeHardwareTexture(e,this._engine),s=new internalTexture_InternalTexture(this,$.Unknown,!0);return s._hardwareTexture=r,s.baseWidth=this._engine.getTextureWidth(e),s.baseHeight=this._engine.getTextureHeight(e),s.width=s.baseWidth,s.height=s.baseHeight,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){var r,s;let a=t.generateStencil||!1,n=t.samples||1,o=new internalTexture_InternalTexture(this,$.DepthStencil),l=null!==(r=e.width)&&void 0!==r?r:e,h=null!==(s=e.height)&&void 0!==s?s:e,c=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,h,a,!0,n);return i._framebufferDepthStencil=c,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){let i=new Promise((t,i)=>{let r=this.createCanvasImage();r.onload=()=>{try{let e=this._engine.createImageBitmap(r);t(e)}catch(e){i(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{i(`Error loading image ${r.src} with exception: ${e}`)},r.src=e});return i}createImageBitmap(e,t){return new Promise((t,i)=>{if(Array.isArray(e)&&e.length){let i=this._engine.createImageBitmap(e[0]);if(i){t(i);return}}i("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,s=null,a=null,n,o=null,l=!1,h=0,c=0,u=null,d,_=!1){let p=u||new internalTexture_InternalTexture(this,$.Cube);p.isCube=!0,p.url=e,p.generateMipMaps=!r,p._lodGenerationScale=h,p._lodGenerationOffset=c,p._useSRGBBuffer=this._getUseSRGBBuffer(_,!!r),this._doNotHandleContextLost||(p._extension=o,p._files=i);let f=e.lastIndexOf("."),m=o||(f>-1?e.substring(f).toLowerCase():"");if(".env"===m){let onloaddata=e=>{let t=GetEnvInfo(e);p.width=t.width,p.height=t.width,UploadEnvSpherical(p,t);let i=t.specular;if(!i)throw Error("Nothing else parsed so far");p._lodGenerationScale=i.lodGenerationScale;let r=CreateImageDataArrayBufferViews(e,t);p.format=5,p.type=0,p.generateMipMaps=!0,p.getEngine().updateTextureSamplingMode(texture_Texture.TRILINEAR_SAMPLINGMODE,p),p._isRGBD=!0,p.invertY=!0,this._engine.loadCubeTextureWithMips(p._hardwareTexture.underlyingResource,r,!1,p._useSRGBBuffer,()=>{p.isReady=!0,s&&s()},()=>{throw Error("Could not load a native cube texture.")})};if(i&&6===i.length)throw Error("Multi-file loading not allowed on env files.");this._loadFile(e,e=>onloaddata(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{a&&e&&a(e.status+" "+e.statusText,t)})}else{if(!i||6!==i.length)throw Error("Cannot load cubemap because 6 files were not defined");let e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map(e=>tools_Tools.LoadFileAsync(e).then(e=>new Uint8Array(e)))).then(e=>new Promise((t,i)=>{this._engine.loadCubeTexture(p._hardwareTexture.underlyingResource,e,!r,!0,p._useSRGBBuffer,t,i)})).then(()=>{p.isReady=!0,s&&s()},e=>{a&&a(`Failed to load cubemap: ${e.message}`,e)})}return this._internalTexturesCache.push(p),p}_createHardwareTexture(){return new NativeHardwareTexture(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){let r=new NativeRenderTargetWrapper(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=$.Unknown){var s,a,n;let o;let l=!1,h=0,c=3,u=5,d=!1,_=1;void 0!==t&&"object"==typeof t?(l=!!t.generateMipMaps,h=void 0===t.type?0:t.type,c=void 0===t.samplingMode?3:t.samplingMode,u=void 0===t.format?5:t.format,d=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,_=null!==(s=t.samples)&&void 0!==s?s:1,o=t.label):l=!!t,d=this._getUseSRGBBuffer(d,!l),(1!==h||this._caps.textureFloatLinearFiltering)&&(2!==h||this._caps.textureHalfFloatLinearFiltering)||(c=1),1!==h||this._caps.textureFloat||(h=0,logger_Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let p=new internalTexture_InternalTexture(this,r),f=null!==(a=e.width)&&void 0!==a?a:e,m=null!==(n=e.height)&&void 0!==n?n:e,g=e.layers||0;if(0!==g)throw Error("Texture layers are not supported in Babylon Native");let v=p._hardwareTexture.underlyingResource,x=getNativeTextureFormat(u,h);return this._engine.initializeTexture(v,f,m,l,x,!0,d,_),this._setTextureSampling(v,getNativeSamplingMode(c)),p._useSRGBBuffer=d,p.baseWidth=f,p.baseHeight=m,p.width=f,p.height=m,p.depth=g,p.isReady=!0,p.samples=_,p.generateMipMaps=l,p.samplingMode=c,p.type=h,p.format=u,p.label=o,this._internalTexturesCache.push(p),p}createRenderTargetTexture(e,t){var i,r,s,a;let n;let o=this._createHardwareRenderTargetWrapper(!1,!1,e),l=!0,h=!1,c=!1,u=1;void 0!==t&&"object"==typeof t&&(l=null===(i=t.generateDepthBuffer)||void 0===i||i,h=!!t.generateStencilBuffer,c=!!t.noColorAttachment,n=t.colorAttachment,u=null!==(r=t.samples)&&void 0!==r?r:1);let d=n||(c?null:this._createInternalTexture(e,t,!0,$.RenderTarget)),_=null!==(s=e.width)&&void 0!==s?s:e,p=null!==(a=e.height)&&void 0!==a?a:e,f=this._engine.createFrameBuffer(d?d._hardwareTexture.underlyingResource:null,_,p,h,l,u);return o._framebuffer=f,o._generateDepthBuffer=l,o._generateStencilBuffer=h,o._samples=u,o.setTextures(d),o}updateRenderTargetTextureSampleCount(e,t){return logger_Logger.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){let i=getNativeSamplingMode(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,s){if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||r)throw Error("Required width/height for frame buffers not yet supported in NativeEngine.");e._framebufferDepthStencil?this._bindUnboundFramebuffer(e._framebufferDepthStencil):this._bindUnboundFramebuffer(e._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){let r=this._normalizeIndexData(t);e.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(e.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i,r){let s=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(e.nativeVertexBuffer,s.buffer,s.byteOffset+(null!=i?i:0),null!=r?r:s.byteLength)}_setTexture(e,t,i=!1,r=!1){let s;let a=this._boundUniforms[e];if(!a)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;return s=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!!s&&!!s._hardwareTexture&&(this._setTextureWrapMode(s._hardwareTexture.underlyingResource,getNativeAddressMode(t.wrapU),getNativeAddressMode(t.wrapV),getNativeAddressMode(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(a,s._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){let t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){let i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){let 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 Error("Native Canvas plugin not available.");let i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");let e=new _native.Image;return e}updateTextureData(e,t,i,r,s,a,n=0,o=0,l=!1){throw Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,n=0){throw Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,r,s,a,n,o,l,h){var c,u,d,_;if(void 0!==r&&-1!==r)throw Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);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!==(u=null==a?void 0:a.buffer)&&void 0!==u?u:null,null!==(d=null==a?void 0:a.byteOffset)&&void 0!==d?d:0,null!==(_=null==a?void 0:a.byteLength)&&void 0!==_?_:0).then(e=>(a||(a=new Uint8Array(e)),a))}};NativeEngine.PROTOCOL_VERSION=8,NativeEngine._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new ValidatedNativeDataStream:new NativeDataStream};let ValidatedNativeDataStream=class ValidatedNativeDataStream extends NativeDataStream{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)}};(function(e){e.LowPower="low-power",e.HighPerformance="high-performance"})(eU||(eU={})),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"}(ek||(ek={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(eG||(eG={})),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"}(ez||(ez={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(eW||(eW={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(eH||(eH={})),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"}(eX||(eX={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(eY||(eY={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(ej||(ej={})),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.RGB10A2UINT="rgb10a2uint",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.Depth32FloatStencil8="depth32float-stencil8"}(eK||(eK={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(eq||(eq={})),function(e){e.Nearest="nearest",e.Linear="linear"}(e$||(e$={})),function(e){e.Nearest="nearest",e.Linear="linear"}(eQ||(eQ={})),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"}(eZ||(eZ={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(eJ||(eJ={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(e0||(e0={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(e1||(e1={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(e2||(e2={})),(e3||(e3={})).WriteOnly="write-only",function(e){e.Error="error",e.Warning="warning",e.Info="info"}(e4||(e4={})),function(e){e.Validation="validation",e.Internal="internal"}(e5||(e5={})),(e6||(e6={})).Auto="auto",function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(e8||(e8={})),function(e){e.CCW="ccw",e.CW="cw"}(e7||(e7={})),function(e){e.None="none",e.Front="front",e.Back="back"}(e9||(e9={})),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"}(te||(te={})),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"}(tt||(tt={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(ti||(ti={})),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"}(tr||(tr={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(ts||(ts={})),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",e.UNORM10x10x10x2="unorm10-10-10-2"}(ta||(ta={})),function(e){e.Vertex="vertex",e.Instance="instance"}(tn||(tn={})),function(e){e.Beginning="beginning",e.End="end"}(to||(to={})),function(e){e.Beginning="beginning",e.End="end"}(tl||(tl={})),function(e){e.Load="load",e.Clear="clear"}(th||(th={})),function(e){e.Store="store",e.Discard="discard"}(tc||(tc={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(tu||(tu={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(td||(td={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(t_||(t_={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(tp||(tp={}));let WebGPUShaderProcessor=class WebGPUShaderProcessor{constructor(){this.shaderLanguage=q.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let r=0;[e,t,r]=this._getArraySize(e,t,i);for(let t=0;t<this._webgpuProcessingContext.leftOverUniforms.length;t++)if(this._webgpuProcessingContext.leftOverUniforms[t].name===e)return;this._webgpuProcessingContext.leftOverUniforms.push({name:e,type:t,length:r})}_buildLeftOverUBO(){if(!this._webgpuProcessingContext.leftOverUniforms.length)return"";let e=WebGPUShaderProcessor.LeftOvertUBOName,t=this._webgpuProcessingContext.availableBuffers[e];return t||(t={binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[e]=t,this._addBufferBindingDescription(e,t,e0.Uniform,!0),this._addBufferBindingDescription(e,t,e0.Uniform,!1)),this._generateLeftOverUBOCode(e,t)}_collectBindingNames(){for(let e=0;e<this._webgpuProcessingContext.bindGroupLayoutEntries.length;e++){let t=this._webgpuProcessingContext.bindGroupLayoutEntries[e];if(void 0===t){this._webgpuProcessingContext.bindGroupLayoutEntries[e]=[];continue}for(let i=0;i<t.length;i++){let t=this._webgpuProcessingContext.bindGroupLayoutEntries[e][i],r=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][t.binding].name,s=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][t.binding].nameInArrayOfTexture;t&&(t.texture||t.externalTexture||t.storageTexture?this._webgpuProcessingContext.textureNames.push(s):t.sampler?this._webgpuProcessingContext.samplerNames.push(r):t.buffer&&this._webgpuProcessingContext.bufferNames.push(r))}}}_preCreateBindGroupEntries(){let e=this._webgpuProcessingContext.bindGroupEntries;for(let t=0;t<this._webgpuProcessingContext.bindGroupLayoutEntries.length;t++){let i=this._webgpuProcessingContext.bindGroupLayoutEntries[t],r=[];for(let e=0;e<i.length;e++){let i=this._webgpuProcessingContext.bindGroupLayoutEntries[t][e];i.sampler||i.texture||i.storageTexture||i.externalTexture?r.push({binding:i.binding,resource:void 0}):i.buffer&&r.push({binding:i.binding,resource:{buffer:void 0,offset:0,size:0}})}e[t]=r}}_addTextureBindingDescription(e,t,i,r,s,a){let{groupIndex:n,bindingIndex:o}=t.textures[i];if(this._webgpuProcessingContext.bindGroupLayoutEntries[n]||(this._webgpuProcessingContext.bindGroupLayoutEntries[n]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][o]){let a;a=null===r?this._webgpuProcessingContext.bindGroupLayoutEntries[n].push({binding:o,visibility:0,externalTexture:{}}):s?this._webgpuProcessingContext.bindGroupLayoutEntries[n].push({binding:o,visibility:0,storageTexture:{access:e3.WriteOnly,format:s,viewDimension:r}}):this._webgpuProcessingContext.bindGroupLayoutEntries[n].push({binding:o,visibility:0,texture:{sampleType:t.sampleType,viewDimension:r,multisampled:!1}});let l=t.isTextureArray?e+i:e;this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][o]={name:e,index:a-1,nameInArrayOfTexture:l}}o=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[n][o].index,a?this._webgpuProcessingContext.bindGroupLayoutEntries[n][o].visibility|=eJ.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[n][o].visibility|=eJ.Fragment}_addSamplerBindingDescription(e,t,i){let{groupIndex:r,bindingIndex:s}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[r]||(this._webgpuProcessingContext.bindGroupLayoutEntries[r]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][s]){let i=this._webgpuProcessingContext.bindGroupLayoutEntries[r].push({binding:s,visibility:0,sampler:{type:t.type}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][s]={name:e,index:i-1}}s=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][s].index,i?this._webgpuProcessingContext.bindGroupLayoutEntries[r][s].visibility|=eJ.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[r][s].visibility|=eJ.Fragment}_addBufferBindingDescription(e,t,i,r){let{groupIndex:s,bindingIndex:a}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[s]||(this._webgpuProcessingContext.bindGroupLayoutEntries[s]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][a]){let t=this._webgpuProcessingContext.bindGroupLayoutEntries[s].push({binding:a,visibility:0,buffer:{type:i}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][a]={name:e,index:t-1}}a=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][a].index,r?this._webgpuProcessingContext.bindGroupLayoutEntries[s][a].visibility|=eJ.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[s][a].visibility|=eJ.Fragment}_injectStartingAndEndingCode(e,t,i,r){let s=e.indexOf(t);if(s<0)return console.error('No "main" function found in shader code! Processing aborted.'),e;if(i){for(;s++<e.length&&"{"!=e.charAt(s););if(s<e.length){let t=e.substring(0,s+1),r=e.substring(s+1);e=t+i+r}}if(r){let t=e.lastIndexOf("}");e=e.substring(0,t)+(r+"\n}")}return e}};WebGPUShaderProcessor.AutoSamplerSuffix="Sampler",WebGPUShaderProcessor.LeftOvertUBOName="LeftOver",WebGPUShaderProcessor.InternalsUBOName="Internals",WebGPUShaderProcessor.UniformSizes={bool:1,int:1,float:1,vec2:2,ivec2:2,uvec2:2,vec3:3,ivec3:3,uvec3:3,vec4:4,ivec4:4,uvec4:4,mat2:4,mat3:12,mat4:16,i32:1,u32:1,f32:1,mat2x2:4,mat3x3:12,mat4x4:16},WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType={sampler2D:"sampler2D",sampler2DArray:"sampler2DArray",sampler2DShadow:"sampler2DShadow",sampler2DArrayShadow:"sampler2DArrayShadow",samplerCube:"samplerCube",sampler3D:"sampler3D"},WebGPUShaderProcessor._TextureTypeByWebGLSamplerType={sampler2D:"texture2D",sampler2DArray:"texture2DArray",sampler2DShadow:"texture2D",sampler2DArrayShadow:"texture2DArray",samplerCube:"textureCube",samplerCubeArray:"textureCubeArray",sampler3D:"texture3D"},WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType={textureCube:eY.Cube,textureCubeArray:eY.CubeArray,texture2D:eY.E2d,texture2DArray:eY.E2dArray,texture3D:eY.E3d},WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType={sampler2DShadow:"samplerShadow",sampler2DArrayShadow:"samplerShadow"},WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType={samplerShadow:!0,samplerArrayShadow:!0,sampler:!1};let WebGPUPipelineContext=class WebGPUPipelineContext{get isAsync(){return!1}get isReady(){return!!this.stages}constructor(e,t){this.bindGroupLayouts={},this._name="unnamed",this.shaderProcessingContext=e,this._leftOverUniformsByName={},this.engine=t,this.vertexBufferKindToType={}}_handlesSpectorRebuildCallback(){}_fillEffectInformation(e,t,i,r,s,a,n,o){let l;let h=this.engine;e._fragmentSourceCode="",e._vertexSourceCode="";let c=this.shaderProcessingContext.availableTextures;for(l=0;l<s.length;l++){let e=s[l],t=c[s[l]];null==t||void 0==t?(s.splice(l,1),l--):a[e]=l}for(let e of h.getAttributes(this,n))o.push(e);this.buildUniformLayout();let u=[],d=[];for(l=0;l<n.length;l++){let e=o[l];e>=0&&(u.push(n[l]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){for(let e of(this.uniformBuffer=new UniformBuffer(this.engine,void 0,void 0,"leftOver-"+this._name),this.shaderProcessingContext.leftOverUniforms)){let t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=WebGPUShaderProcessor.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,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,r,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,r,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,r,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){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}};let rk={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};let WebGPUShaderProcessingContext=class WebGPUShaderProcessingContext{static get KnownUBOs(){return WebGPUShaderProcessingContext._SimplifiedKnownBindings?WebGPUShaderProcessingContext._SimplifiedKnownUBOs:WebGPUShaderProcessingContext._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(){let e=WebGPUShaderProcessingContext.KnownUBOs,t=[];for(let i in e){let r=e[i].binding;-1!==r.groupIndex&&(void 0===t[r.groupIndex]?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;let r=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=rk[e])&&void 0!==i?i:1)*(t||1),r}getVaryingNextLocation(e,t=0){var i;let r=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=rk[e])&&void 0!==i?i:1)*(t||1),r}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.";let t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}};WebGPUShaderProcessingContext._SimplifiedKnownBindings=!0,WebGPUShaderProcessingContext._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}}},WebGPUShaderProcessingContext._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}}};let WebGPUShaderProcessorGLSL=class WebGPUShaderProcessorGLSL extends WebGPUShaderProcessor{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=q.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0,s=e.indexOf("["),a=e.indexOf("]");if(s>0&&a>0){let t=e.substring(s+1,a);isNaN(r=+t)&&(r=+i[t.trim()]),e=e.substr(0,s)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){let i=`// Internals UBO +uniform ${WebGPUShaderProcessor.InternalsUBOName} { +float yFactor_; +float textureOutputHeight_; +}; +`,r=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){let i=t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/;return i.test(e)}varyingProcessor(e,t,i){var r;this._preProcessors=i;let 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,a=s.exec(e);if(null!==a){let s;let n=null!==(r=a[1])&&void 0!==r?r:"",o=a[2],l=a[3];t?(s=this._webgpuProcessingContext.availableVaryings[l],this._missingVaryings[s]="",void 0===s&&logger_Logger.Warn(`Invalid fragment shader: The varying named "${l}" is not declared in the vertex shader! This declaration will be ignored.`)):(s=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(l,o,i)[2]),this._webgpuProcessingContext.availableVaryings[l]=s,this._missingVaryings[s]=`layout(location = ${s}) ${n} in ${o} ${l};`),e=e.replace(a[0],void 0===s?"":`layout(location = ${s}) ${n} ${t?"in":"out"} ${o} ${l};`)}return e}attributeProcessor(e,t){this._preProcessors=t;let i=this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,r=i.exec(e);if(null!==r){let i=r[1],s=r[2],a=this._webgpuProcessingContext.getAttributeNextLocation(i,this._getArraySize(s,i,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=a,this._webgpuProcessingContext.orderedAttributes[a]=s;let n=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==n){let t=`_int_${s}_`;e=e.replace(r[0],`layout(location = ${a}) in ${n<0?-1===n?"int":"ivec"+-n:1===n?"uint":"uvec"+n} ${t}; ${i} ${s} = ${i}(${t});`)}else e=e.replace(r[0],`layout(location = ${a}) in ${i} ${s};`)}return e}uniformProcessor(e,t,i){var r;this._preProcessors=i;let s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let a=s[1],n=s[2];if(0===a.indexOf("sampler")||1===a.indexOf("sampler")){let s=0;[n,a,s]=this._getArraySize(n,a,i);let o=this._webgpuProcessingContext.availableTextures[n];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:e2.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}let l=null!==(r=WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[a])&&void 0!==r?r:"sampler",h=!!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[l],c=h?e1.Comparison:e1.Filtering,u=n+WebGPUShaderProcessor.AutoSamplerSuffix,d=this._webgpuProcessingContext.availableSamplers[u];d||(d={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:c});let _="u"===a.charAt(0)?"u":"i"===a.charAt(0)?"i":"";_&&(a=a.substr(1));let p=h?e2.Depth:"u"===_?e2.Uint:"i"===_?e2.Sint:e2.Float;o.sampleType=p;let f=s>0,m=d.binding.groupIndex,g=d.binding.bindingIndex,v=WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[a],x=WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[a],b=WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[x];if(f){let t=[];t.push(`layout(set = ${m}, binding = ${g}) uniform ${_}${l} ${u};`),e=` +`;for(let i=0;i<s;++i){let r=o.textures[i].groupIndex,s=o.textures[i].bindingIndex;t.push(`layout(set = ${r}, binding = ${s}) uniform ${x} ${n}Texture${i};`),e+=`${i>0?"\n":""}#define ${n}${i} ${_}${v}(${n}Texture${i}, ${u})`}e=t.join("\n")+e,this._textureArrayProcessing.push(n)}else s=1,e=`layout(set = ${m}, binding = ${g}) uniform ${l} ${u}; + layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${_}${x} ${n}Texture; + #define ${n} ${_}${v}(${n}Texture, ${u})`;this._webgpuProcessingContext.availableTextures[n]=o,this._webgpuProcessingContext.availableSamplers[u]=d,this._addSamplerBindingDescription(u,d,!t);for(let e=0;e<s;++e)this._addTextureBindingDescription(n,o,e,b,null,!t)}else this._addUniformToLeftOverUBO(n,a,i),e=""}return e}uniformBufferProcessor(e,t){let i=/uniform\s+(\w+)/gm.exec(e);if(null!==i){let r=i[1],s=this._webgpuProcessingContext.availableBuffers[r];if(!s){let e=WebGPUShaderProcessingContext.KnownUBOs[r];s={binding:e&&-1!==e.binding.groupIndex?e.binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[r]=s}this._addBufferBindingDescription(r,s,e0.Uniform,!t),e=e.replace("uniform",`layout(set = ${s.binding.groupIndex}, binding = ${s.binding.bindingIndex}) uniform`)}return e}postProcessor(e,t,i,r,s){let a=-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){let t=e.indexOf("gl_FragCoord")>=0,i=` + glFragCoord_ = gl_FragCoord; + if (yFactor_ == 1.) { + glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; + } + `,r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){let 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,(a||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",t?"vec4 glFragCoord_;\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");let i=-1!==t.indexOf("#define MULTIVIEW");if(i)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}if(!i){let t=e.lastIndexOf("}");e=e.substring(0,t)+"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){let i=RegExp(t+"\\s*\\[(.+)?\\]","gm"),r=i.exec(e);for(;null!==r;){let s=r[1],a=+s;this._preProcessors&&isNaN(a)&&(a=+this._preProcessors[s.trim()]),e=e.replace(r[0],t+a),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { + `;for(let e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}]; +`:i+=` ${e.type} ${e.name}; +`;return i+"};\n\n"}finalizeShaders(e,t){for(let i=0;i<this._textureArrayProcessing.length;++i){let r=this._textureArrayProcessing[i];e=this._applyTextureArrayProcessing(e,r),t=this._applyTextureArrayProcessing(t,r)}for(let e=0;e<this._missingVaryings.length;++e){let i=this._missingVaryings[e];i&&i.length>0&&(t=i+"\n"+t)}let i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}};let rG=`#if NUM_BONE_INFLUENCERS>0 +attribute matricesIndices : vec4<f32>;attribute matricesWeights : vec4<f32>; +#if NUM_BONE_INFLUENCERS>4 +attribute matricesIndicesExtra : vec4<f32>;attribute matricesWeightsExtra : vec4<f32>; +#endif +#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#ifdef BONETEXTURE +var boneSampler : texture_2d<f32>;uniform boneTextureWidth : f32; +#else +uniform mBones : array<mat4x4,BonesPerMesh>; +#ifdef BONES_VELOCITY_ENABLED +uniform mPreviousBones : array<mat4x4,BonesPerMesh>; +#endif +#endif +#ifdef BONETEXTURE +fn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4<f32> +{let offset=i32(index) *4; +let m0=textureLoad(smp,vec2<i32>(offset+0,0),0);let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);return mat4x4<f32>(m0,m1,m2,m3);} +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStoreWGSL.bonesDeclaration=rG;let rz=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#if NUM_BONE_INFLUENCERS>0 +var influence : mat4x4<f32>; +#ifdef BONETEXTURE +influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; +#endif +#else +influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#endif +`;ShaderStore.IncludesShadersStoreWGSL.bonesVertex=rz;let rW=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2<f32>;uniform bakedVertexAnimationSettings: vec4<f32>;var bakedVertexAnimationTexture : texture_2d<f32>; +#ifdef INSTANCES +attribute bakedVertexAnimationSettingsInstanced : vec4<f32>; +#endif +fn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32)->mat4x4<f32> +{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);return mat4x4<f32>(m0,m1,m2,m3);} +#endif +`;ShaderStore.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration=rW;let rH=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +{ +#ifdef INSTANCES +let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; +#else +let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; +#endif +let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4<f32>;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; +#endif +finalWorld=finalWorld*VATInfluence;} +#endif +`;ShaderStore.IncludesShadersStoreWGSL.bakedVertexAnimation=rH;let rX=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +if (false) {} +#endif +#ifdef CLIPPLANE +else if (fragmentInputs.fClipDistance>0.0) +{discard;} +#endif +#ifdef CLIPPLANE2 +else if (fragmentInputs.fClipDistance2>0.0) +{discard;} +#endif +#ifdef CLIPPLANE3 +else if (fragmentInputs.fClipDistance3>0.0) +{discard;} +#endif +#ifdef CLIPPLANE4 +else if (fragmentInputs.fClipDistance4>0.0) +{discard;} +#endif +#ifdef CLIPPLANE5 +else if (fragmentInputs.fClipDistance5>0.0) +{discard;} +#endif +#ifdef CLIPPLANE6 +else if (fragmentInputs.fClipDistance6>0.0) +{discard;} +#endif +`;ShaderStore.IncludesShadersStoreWGSL.clipPlaneFragment=rX;let rY=`#ifdef CLIPPLANE +varying fClipDistance: f32; +#endif +#ifdef CLIPPLANE2 +varying fClipDistance2: f32; +#endif +#ifdef CLIPPLANE3 +varying fClipDistance3: f32; +#endif +#ifdef CLIPPLANE4 +varying fClipDistance4: f32; +#endif +#ifdef CLIPPLANE5 +varying fClipDistance5: f32; +#endif +#ifdef CLIPPLANE6 +varying fClipDistance6: f32; +#endif +`;ShaderStore.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration=rY;let rj=`#ifdef CLIPPLANE +vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); +#endif +#ifdef CLIPPLANE2 +vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); +#endif +#ifdef CLIPPLANE3 +vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); +#endif +#ifdef CLIPPLANE4 +vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); +#endif +#ifdef CLIPPLANE5 +vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); +#endif +#ifdef CLIPPLANE6 +vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); +#endif +`;ShaderStore.IncludesShadersStoreWGSL.clipPlaneVertex=rj;let rK=`#ifdef CLIPPLANE +uniform vClipPlane: vec4<f32>;varying fClipDistance: f32; +#endif +#ifdef CLIPPLANE2 +uniform vClipPlane2: vec4<f32>;varying fClipDistance2: f32; +#endif +#ifdef CLIPPLANE3 +uniform vClipPlane3: vec4<f32>;varying fClipDistance3: f32; +#endif +#ifdef CLIPPLANE4 +uniform vClipPlane4: vec4<f32>;varying fClipDistance4: f32; +#endif +#ifdef CLIPPLANE5 +uniform vClipPlane5: vec4<f32>;varying fClipDistance5: f32; +#endif +#ifdef CLIPPLANE6 +uniform vClipPlane6: vec4<f32>;varying fClipDistance6: f32; +#endif +`;ShaderStore.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration=rK;let rq=`#ifdef INSTANCES +attribute world0 : vec4<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>; +#ifdef INSTANCESCOLOR +attribute instanceColor : vec4<f32>; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform world : mat4x4<f32>; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +attribute previousWorld0 : vec4<f32>;attribute previousWorld1 : vec4<f32>;attribute previousWorld2 : vec4<f32>;attribute previousWorld3 : vec4<f32>; +#ifdef THIN_INSTANCES +uniform previousWorld : mat4x4<f32>; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform world : mat4x4<f32>; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +uniform previousWorld : mat4x4<f32>; +#endif +#endif +`;ShaderStore.IncludesShadersStoreWGSL.instancesDeclaration=rq;let r$=`#ifdef INSTANCES +var finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +var finalPreviousWorld=mat4x4<f32>(previousWorld0,previousWorld1,previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +#if !defined(WORLD_UBO) +finalWorld=uniforms.world*finalWorld; +#else +finalWorld=mesh.world*finalWorld; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +var finalWorld=uniforms.world; +#else +var finalWorld=mesh.world; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +var finalPreviousWorld=previousWorld; +#endif +#endif +`;ShaderStore.IncludesShadersStoreWGSL.instancesVertex=r$;let rQ=`struct Mesh {world : mat4x4<f32>, +visibility : f32,};var<uniform> mesh : Mesh; +#define WORLD_UBO +`;ShaderStore.IncludesShadersStoreWGSL.meshUboDeclaration=rQ;let rZ=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#ifdef MORPHTARGETS_NORMAL +normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; +#endif +#else +positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStoreWGSL.morphTargetsVertex=rZ;let rJ=`#ifdef MORPHTARGETS +#ifndef MORPHTARGETS_TEXTURE +attribute position{X} : vec3<f32>; +#ifdef MORPHTARGETS_NORMAL +attribute normal{X} : vec3<f32>; +#endif +#ifdef MORPHTARGETS_TANGENT +attribute tangent{X} : vec3<f32>; +#endif +#ifdef MORPHTARGETS_UV +attribute uv_{X} : vec2<f32>; +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration=rJ;let r0=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +var vertexID : f32; +#endif +#endif +`;ShaderStore.IncludesShadersStoreWGSL.morphTargetsVertexGlobal=r0;let r1=`#ifdef MORPHTARGETS +uniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>; +#ifdef MORPHTARGETS_TEXTURE +uniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;uniform morphTargetTextureInfo : vec3<f32>;var morphTargets : texture_2d_array<f32>;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3<f32> +{ +let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2<f32>((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} +#endif +#endif +`;ShaderStore.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration=r1;let r2=`struct Scene {viewProjection : mat4x4<f32>, +#ifdef MULTIVIEW +viewProjectionR : mat4x4<f32>, +#endif +view : mat4x4<f32>, +projection : mat4x4<f32>, +vEyePosition : vec4<f32>,};var<uniform> scene : Scene; +`;ShaderStore.IncludesShadersStoreWGSL.sceneUboDeclaration=r2;let r3="fragmentOutputs.fragDepth",r4={texture_1d:eY.E1d,texture_2d:eY.E2d,texture_2d_array:eY.E2dArray,texture_3d:eY.E3d,texture_cube:eY.Cube,texture_cube_array:eY.CubeArray,texture_multisampled_2d:eY.E2d,texture_depth_2d:eY.E2d,texture_depth_2d_array:eY.E2dArray,texture_depth_cube:eY.Cube,texture_depth_cube_array:eY.CubeArray,texture_depth_multisampled_2d:eY.E2d,texture_storage_1d:eY.E1d,texture_storage_2d:eY.E2d,texture_storage_2d_array:eY.E2dArray,texture_storage_3d:eY.E3d,texture_external:null};let WebGPUShaderProcessorWGSL=class WebGPUShaderProcessorWGSL extends WebGPUShaderProcessor{constructor(){super(...arguments),this.shaderLanguage=q.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 r=0,s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;let a=t.substring(e+1,s);for(isNaN(r=+a)&&(r=+i[a.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${WebGPUShaderProcessor.InternalsUBOName} { + yFactor_: f32, + textureOutputHeight_: f32, +}; +var<uniform> internals : ${WebGPUShaderProcessor.InternalsUBOName}; +`+RemoveComments(e)}varyingProcessor(e,t,i){let r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==r){let s;let a=r[2],n=r[1];t?void 0===(s=this._webgpuProcessingContext.availableVaryings[n])&&logger_Logger.Warn(`Invalid fragment shader: The varying named "${n}" is not declared in the vertex shader! This declaration will be ignored.`):(s=this._webgpuProcessingContext.getVaryingNextLocation(a,this._getArraySize(n,a,i)[2]),this._webgpuProcessingContext.availableVaryings[n]=s,this._varyingsWGSL.push(` @location(${s}) ${n} : ${a},`),this._varyingNamesWGSL.push(n)),e=""}return e}attributeProcessor(e,t){let i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){let r=i[2],s=i[1],a=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=a,this._webgpuProcessingContext.orderedAttributes[a]=s;let n=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==n){let e=`_int_${s}_`;this._attributesInputWGSL.push(`@location(${a}) ${e} : ${n<0?-1===n?"i32":"vec"+-n+"<i32>":1===n?"u32":"vec"+n+"<u32>"},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = ${r}(vertexInputs_.${e});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${a}) ${s} : ${r},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = vertexInputs_.${s};`);e=""}return e}uniformProcessor(e,t,i){let r=this.uniformRegexp.exec(e);if(null!==r){let t=r[2],s=r[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){let r=this.textureRegexp.exec(e);if(null!==r){let s=r[1],a=r[2],n=!!r[3],o=r[4],l=o.indexOf("storage")>0,h=r[6],c=l?h.substring(0,h.indexOf(",")).trim():null,u=n?this._getArraySize(s,a,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[s];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:e2.Float},u=u||1;for(let e=0;e<u;++e)d.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}this._webgpuProcessingContext.availableTextures[s]=d;let _=o.indexOf("depth")>0,p=r4[o],f=_?e2.Depth:"u32"===h?e2.Uint:"i32"===h?e2.Sint:e2.Float;if(d.sampleType=f,void 0===p)throw`Can't get the texture dimension corresponding to the texture function "${o}"!`;for(let i=0;i<u;++i){let{groupIndex:r,bindingIndex:a}=d.textures[i];0===i&&(e=`@group(${r}) @binding(${a}) ${e}`),this._addTextureBindingDescription(s,d,i,p,c,!t)}}return e}postProcessor(e){return e}finalizeShaders(e,t){let i=t.indexOf("fragmentInputs.position")>=0?` + if (internals.yFactor_ == 1.) { + fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; + } + `:"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);let r=this._buildLeftOverUBO();e=r+e,t=r+t,e=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._attributesInputWGSL.length>0&&(s+=this._attributesInputWGSL.join("\n")),s+="\n};\nvar<private> vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(s+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n"+this._attributesWGSL.join("\n")+"\n};\nvar<private> vertexInputs : VertexInputs_;\n");let a="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n";this._varyingsWGSL.length>0&&(a+=this._varyingsWGSL.join("\n")),a+="\n};\nvar<private> vertexOutputs : FragmentInputs;\n",e=s+a+e;let n=` + vertexInputs${this._hasNonFloatAttribute?"_":""} = input; +`;this._hasNonFloatAttribute&&(n+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n"+this._attributesConversionCodeWGSL.join("\n")+"\n");let o=` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; + return vertexOutputs;`;e=this._injectStartingAndEndingCode(e,"fn main",n,o),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar<private> fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4<f32>,\n",c=!1,u=0;for(;!c&&!((u=t.indexOf(r3,u))<0);){let e=u;for(c=!0;u>1&&"\n"!==t.charAt(u);){if("/"===t.charAt(u)&&"/"===t.charAt(u-1)){c=!1;break}u--}u=e+r3.length}return c&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar<private> fragmentOutputs : FragmentOutputs;\n",t=l+h+t,t=this._injectStartingAndEndingCode(t,"fn main"," fragmentInputs = input;\n "+i," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} { +`;for(let t of this._webgpuProcessingContext.leftOverUniforms){let s=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),a=WebGPUShaderProcessor.UniformSizes[s];if(t.length>0){if(a<=2){let a=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${a} { + @size(16) + el: ${s}, + }`,this._stridedUniformArrays.push(t.name),r+=` @align(16) ${t.name} : array<${a}, ${t.length}>, +`}else r+=` ${t.name} : array<${t.type}, ${t.length}>, +`}else r+=` ${t.name} : ${t.type}, +`}return r+="};\n",r=`${i} +${r}@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var<uniform> uniforms : ${e}; +`}_processSamplers(e,t){let i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],a=r[2],n=s.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)===s.length-WebGPUShaderProcessor.AutoSamplerSuffix.length?s.substring(0,s.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)):null,o="sampler_comparison"===a?e1.Comparison:e1.Filtering;if(n){let e=this._webgpuProcessingContext.availableTextures[n];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:o},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);let h=e.substring(0,r.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,u=e.substring(r.index);e=h+c+u,i.lastIndex+=c.length}return e}_processCustomBuffers(e,t){let i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],a=r[3],n=r[4],o=r[5],l=this._webgpuProcessingContext.availableBuffers[n];if(!l){let e;let t="uniform"===s?WebGPUShaderProcessingContext.KnownUBOs[o]:null;t?(n=o,-1===(e=t.binding).groupIndex&&(e=this._webgpuProcessingContext.getNextFreeUBOBinding())):e=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:e},this._webgpuProcessingContext.availableBuffers[n]=l}this._addBufferBindingDescription(n,this._webgpuProcessingContext.availableBuffers[n],"read_write"===a?e0.Storage:"storage"===s?e0.ReadOnlyStorage:e0.Uniform,t);let h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,r.index),d=`@group(${h}) @binding(${c}) `,_=e.substring(r.index);e=u+d+_,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(let t of this._stridedUniformArrays)e=e.replace(RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}};let WebGPUHardwareTexture=class WebGPUHardwareTexture{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(let e of this._webgpuMSAATexture)null==e||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=eK.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,s){this.createView({format:this.format,dimension:i?eY.Cube:eY.E2d,mipLevelCount:t?math_scalar_Scalar.ILog2(Math.max(r,s))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:ej.All})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){let 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()}};let r5=` + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); + + layout(location = 0) out vec2 vTex; + + void main() { + vTex = tex[gl_VertexIndex]; + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,r6=` + layout(set = 0, binding = 0) uniform sampler imgSampler; + layout(set = 0, binding = 1) uniform texture2D img; + + layout(location = 0) in vec2 vTex; + layout(location = 0) out vec4 outColor; + + void main() { + outColor = texture(sampler2D(img, imgSampler), vTex); + } + `,r8=` + #extension GL_EXT_samplerless_texture_functions : enable + + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); + + layout(set = 0, binding = 0) uniform texture2D img; + + #ifdef INVERTY + layout(location = 0) out flat ivec2 vTextureSize; + #endif + + void main() { + #ifdef INVERTY + vTextureSize = textureSize(img, 0); + #endif + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,r7=` + #extension GL_EXT_samplerless_texture_functions : enable + + layout(set = 0, binding = 0) uniform texture2D img; + + #ifdef INVERTY + layout(location = 0) in flat ivec2 vTextureSize; + #endif + layout(location = 0) out vec4 outColor; + + void main() { + #ifdef INVERTY + vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0); + #else + vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color.rgb *= color.a; + #endif + outColor = color; + } + `,r9=` + #extension GL_EXT_samplerless_texture_functions : enable + + layout(set = 0, binding = 0) uniform texture2D img; + layout(set = 0, binding = 1) uniform Params { + float ofstX; + float ofstY; + float width; + float height; + }; + + #ifdef INVERTY + layout(location = 0) in flat ivec2 vTextureSize; + #endif + layout(location = 0) out vec4 outColor; + + void main() { + if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) { + discard; + } + if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) { + discard; + } + #ifdef INVERTY + vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0); + #else + vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color.rgb *= color.a; + #endif + outColor = color; + } + `,se=` + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + + void main() { + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,st=` + layout(set = 0, binding = 0) uniform Uniforms { + uniform vec4 color; + }; + + layout(location = 0) out vec4 outColor; + + void main() { + outColor = color; + } + `,si=` + struct VertexOutput { + @builtin(position) Position : vec4<f32>, + @location(0) fragUV : vec2<f32> + } + + @vertex + fn main( + @builtin(vertex_index) VertexIndex : u32 + ) -> VertexOutput { + var pos = array<vec2<f32>, 4>( + vec2(-1.0, 1.0), + vec2( 1.0, 1.0), + vec2(-1.0, -1.0), + vec2( 1.0, -1.0) + ); + var tex = array<vec2<f32>, 4>( + vec2(0.0, 0.0), + vec2(1.0, 0.0), + vec2(0.0, 1.0), + vec2(1.0, 1.0) + ); + + var output: VertexOutput; + + output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0); + output.fragUV = tex[VertexIndex]; + + return output; + } + `,sr=` + @group(0) @binding(0) var videoSampler: sampler; + @group(0) @binding(1) var videoTexture: texture_external; + + @fragment + fn main( + @location(0) fragUV: vec2<f32> + ) -> @location(0) vec4<f32> { + return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); + } + `,ss=` + @group(0) @binding(0) var videoSampler: sampler; + @group(0) @binding(1) var videoTexture: texture_external; + + @fragment + fn main( + @location(0) fragUV: vec2<f32> + ) -> @location(0) vec4<f32> { + return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2<f32>(fragUV.x, 1.0 - fragUV.y)); + } + `;(function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(tf||(tf={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(tm||(tm={}));let sa=[{vertex:r5,fragment:r6},{vertex:r8,fragment:r7},{vertex:se,fragment:st},{vertex:r8,fragment:r9}],sn={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};let WebGPUTextureHelper=class WebGPUTextureHelper{static ComputeNumMipmapLevels(e,t){return math_scalar_Scalar.ILog2(Math.max(e,t))+1}constructor(e,t,i,r,s){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=r,-1!==s.indexOf(ek.RG11B10UFloatRenderable)){let e=Object.keys(sn);sn[eK.RG11B10UFloat]=sn[e[e.length-1]]+1}this._mipmapSampler=e.createSampler({minFilter:e$.Linear}),this._videoSampler=e.createSampler({minFilter:e$.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,ez.Uniform|ez.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(eK.RGBA8Unorm),this._getVideoPipeline(eK.RGBA8Unorm)}_getPipeline(e,t=tf.MipMap,i){let r=t===tf.MipMap?1:t===tf.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===tf.Clear?8:t===tf.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][r];if(!s){let a="#version 450\n";(t===tf.InvertYPremultiplyAlpha||t===tf.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(a+="#define INVERTY\n"),i.premultiplyAlpha&&(a+="#define PREMULTIPLYALPHA\n"));let n=this._compiledShaders[r];if(!n){let e=this._glslang.compileGLSL(a+sa[t].vertex,"vertex"),i=this._glslang.compileGLSL(a+sa[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));let s=this._device.createShaderModule({code:e}),o=this._device.createShaderModule({code:i});n=this._compiledShaders[r]=[s,o]}let o=this._device.createRenderPipeline({layout:e6.Auto,vertex:{module:n[0],entryPoint:"main"},fragment:{module:n[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:e8.TriangleStrip,stripIndexFormat:ts.Uint16}});s=this._pipelines[e][r]=[o,o.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=tm.DontInvertY){let i=t===tm.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let t=this._videoCompiledShaders[i];if(!t){let e=this._device.createShaderModule({code:si}),r=this._device.createShaderModule({code:0===i?sr:ss});t=this._videoCompiledShaders[i]=[e,r]}let s=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:e6.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:e8.TriangleStrip,stripIndexFormat:ts.Uint16}});r=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return r}static _GetTextureTypeFromFormat(e){switch(e){case eK.R8Unorm:case eK.R8Snorm:case eK.R8Uint:case eK.R8Sint:case eK.RG8Unorm:case eK.RG8Snorm:case eK.RG8Uint:case eK.RG8Sint:case eK.RGBA8Unorm:case eK.RGBA8UnormSRGB:case eK.RGBA8Snorm:case eK.RGBA8Uint:case eK.RGBA8Sint:case eK.BGRA8Unorm:case eK.BGRA8UnormSRGB:case eK.RGB10A2UINT:case eK.RGB10A2Unorm:case eK.RGB9E5UFloat:case eK.RG11B10UFloat:case eK.Depth32FloatStencil8:case eK.BC7RGBAUnorm:case eK.BC7RGBAUnormSRGB:case eK.BC6HRGBUFloat:case eK.BC6HRGBFloat:case eK.BC5RGUnorm:case eK.BC5RGSnorm:case eK.BC3RGBAUnorm:case eK.BC3RGBAUnormSRGB:case eK.BC2RGBAUnorm:case eK.BC2RGBAUnormSRGB:case eK.BC4RUnorm:case eK.BC4RSnorm:case eK.BC1RGBAUnorm:case eK.BC1RGBAUnormSRGB:case eK.ETC2RGB8Unorm:case eK.ETC2RGB8UnormSRGB:case eK.ETC2RGB8A1Unorm:case eK.ETC2RGB8A1UnormSRGB:case eK.ETC2RGBA8Unorm:case eK.ETC2RGBA8UnormSRGB:case eK.EACR11Unorm:case eK.EACR11Snorm:case eK.EACRG11Unorm:case eK.EACRG11Snorm:case eK.ASTC4x4Unorm:case eK.ASTC4x4UnormSRGB:case eK.ASTC5x4Unorm:case eK.ASTC5x4UnormSRGB:case eK.ASTC5x5Unorm:case eK.ASTC5x5UnormSRGB:case eK.ASTC6x5Unorm:case eK.ASTC6x5UnormSRGB:case eK.ASTC6x6Unorm:case eK.ASTC6x6UnormSRGB:case eK.ASTC8x5Unorm:case eK.ASTC8x5UnormSRGB:case eK.ASTC8x6Unorm:case eK.ASTC8x6UnormSRGB:case eK.ASTC8x8Unorm:case eK.ASTC8x8UnormSRGB:case eK.ASTC10x5Unorm:case eK.ASTC10x5UnormSRGB:case eK.ASTC10x6Unorm:case eK.ASTC10x6UnormSRGB:case eK.ASTC10x8Unorm:case eK.ASTC10x8UnormSRGB:case eK.ASTC10x10Unorm:case eK.ASTC10x10UnormSRGB:case eK.ASTC12x10Unorm:case eK.ASTC12x10UnormSRGB:case eK.ASTC12x12Unorm:case eK.ASTC12x12UnormSRGB:break;case eK.R16Uint:case eK.R16Sint:case eK.RG16Uint:case eK.RG16Sint:case eK.RGBA16Uint:case eK.RGBA16Sint:case eK.Depth16Unorm:return 5;case eK.R16Float:case eK.RG16Float:case eK.RGBA16Float:return 2;case eK.R32Uint:case eK.R32Sint:case eK.RG32Uint:case eK.RG32Sint:case eK.RGBA32Uint:case eK.RGBA32Sint:return 7;case eK.R32Float:case eK.RG32Float:case eK.RGBA32Float:case eK.Depth32Float:return 1;case eK.Stencil8:throw"No fixed size for Stencil8 format!";case eK.Depth24Plus:throw"No fixed size for Depth24Plus format!";case eK.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0}static _GetBlockInformationFromFormat(e){switch(e){case eK.R8Unorm:case eK.R8Snorm:case eK.R8Uint:case eK.R8Sint:return{width:1,height:1,length:1};case eK.R16Uint:case eK.R16Sint:case eK.R16Float:case eK.RG8Unorm:case eK.RG8Snorm:case eK.RG8Uint:case eK.RG8Sint:return{width:1,height:1,length:2};case eK.R32Uint:case eK.R32Sint:case eK.R32Float:case eK.RG16Uint:case eK.RG16Sint:case eK.RG16Float:case eK.RGBA8Unorm:case eK.RGBA8UnormSRGB:case eK.RGBA8Snorm:case eK.RGBA8Uint:case eK.RGBA8Sint:case eK.BGRA8Unorm:case eK.BGRA8UnormSRGB:case eK.RGB9E5UFloat:case eK.RGB10A2UINT:case eK.RGB10A2Unorm:case eK.RG11B10UFloat:break;case eK.RG32Uint:case eK.RG32Sint:case eK.RG32Float:case eK.RGBA16Uint:case eK.RGBA16Sint:case eK.RGBA16Float:return{width:1,height:1,length:8};case eK.RGBA32Uint:case eK.RGBA32Sint:case eK.RGBA32Float:return{width:1,height:1,length:16};case eK.Stencil8:throw"No fixed size for Stencil8 format!";case eK.Depth16Unorm:return{width:1,height:1,length:2};case eK.Depth24Plus:throw"No fixed size for Depth24Plus format!";case eK.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case eK.Depth32Float:break;case eK.Depth32FloatStencil8:return{width:1,height:1,length:5};case eK.BC7RGBAUnorm:case eK.BC7RGBAUnormSRGB:case eK.BC6HRGBUFloat:case eK.BC6HRGBFloat:case eK.BC5RGUnorm:case eK.BC5RGSnorm:case eK.BC3RGBAUnorm:case eK.BC3RGBAUnormSRGB:case eK.BC2RGBAUnorm:case eK.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case eK.BC4RUnorm:case eK.BC4RSnorm:case eK.BC1RGBAUnorm:case eK.BC1RGBAUnormSRGB:case eK.ETC2RGB8Unorm:case eK.ETC2RGB8UnormSRGB:case eK.ETC2RGB8A1Unorm:case eK.ETC2RGB8A1UnormSRGB:case eK.EACR11Unorm:case eK.EACR11Snorm:return{width:4,height:4,length:8};case eK.ETC2RGBA8Unorm:case eK.ETC2RGBA8UnormSRGB:case eK.EACRG11Unorm:case eK.EACRG11Snorm:case eK.ASTC4x4Unorm:case eK.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case eK.ASTC5x4Unorm:case eK.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case eK.ASTC5x5Unorm:case eK.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case eK.ASTC6x5Unorm:case eK.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case eK.ASTC6x6Unorm:case eK.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case eK.ASTC8x5Unorm:case eK.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case eK.ASTC8x6Unorm:case eK.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case eK.ASTC8x8Unorm:case eK.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case eK.ASTC10x5Unorm:case eK.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case eK.ASTC10x6Unorm:case eK.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case eK.ASTC10x8Unorm:case eK.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case eK.ASTC10x10Unorm:case eK.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case eK.ASTC12x10Unorm:case eK.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case eK.ASTC12x12Unorm:case eK.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 eK.BC7RGBAUnormSRGB:case eK.BC7RGBAUnorm:case eK.BC6HRGBFloat:case eK.BC6HRGBUFloat:case eK.BC5RGSnorm:case eK.BC5RGUnorm:case eK.BC4RSnorm:case eK.BC4RUnorm:case eK.BC3RGBAUnormSRGB:case eK.BC3RGBAUnorm:case eK.BC2RGBAUnormSRGB:case eK.BC2RGBAUnorm:case eK.BC1RGBAUnormSRGB:case eK.BC1RGBAUnorm:case eK.ETC2RGB8Unorm:case eK.ETC2RGB8UnormSRGB:case eK.ETC2RGB8A1Unorm:case eK.ETC2RGB8A1UnormSRGB:case eK.ETC2RGBA8Unorm:case eK.ETC2RGBA8UnormSRGB:case eK.EACR11Unorm:case eK.EACR11Snorm:case eK.EACRG11Unorm:case eK.EACRG11Snorm:case eK.ASTC4x4Unorm:case eK.ASTC4x4UnormSRGB:case eK.ASTC5x4Unorm:case eK.ASTC5x4UnormSRGB:case eK.ASTC5x5Unorm:case eK.ASTC5x5UnormSRGB:case eK.ASTC6x5Unorm:case eK.ASTC6x5UnormSRGB:case eK.ASTC6x6Unorm:case eK.ASTC6x6UnormSRGB:case eK.ASTC8x5Unorm:case eK.ASTC8x5UnormSRGB:case eK.ASTC8x6Unorm:case eK.ASTC8x6UnormSRGB:case eK.ASTC8x8Unorm:case eK.ASTC8x8UnormSRGB:case eK.ASTC10x5Unorm:case eK.ASTC10x5UnormSRGB:case eK.ASTC10x6Unorm:case eK.ASTC10x6UnormSRGB:case eK.ASTC10x8Unorm:case eK.ASTC10x8UnormSRGB:case eK.ASTC10x10Unorm:case eK.ASTC10x10UnormSRGB:case eK.ASTC12x10Unorm:case eK.ASTC12x10UnormSRGB:case eK.ASTC12x12Unorm:case eK.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return eK.Depth16Unorm;case 16:return eK.Depth24Plus;case 13:return eK.Depth24PlusStencil8;case 14:return eK.Depth32Float;case 18:return eK.Depth32FloatStencil8;case 19:return eK.Stencil8;case 36492:return i?eK.BC7RGBAUnormSRGB:eK.BC7RGBAUnorm;case 36495:return eK.BC6HRGBUFloat;case 36494:return eK.BC6HRGBFloat;case 33779:return i?eK.BC3RGBAUnormSRGB:eK.BC3RGBAUnorm;case 33778:return i?eK.BC2RGBAUnormSRGB:eK.BC2RGBAUnorm;case 33777:case 33776:return i?eK.BC1RGBAUnormSRGB:eK.BC1RGBAUnorm;case 37808:return i?eK.ASTC4x4UnormSRGB:eK.ASTC4x4Unorm;case 36196:case 37492:return i?eK.ETC2RGB8UnormSRGB:eK.ETC2RGB8Unorm;case 37496:return i?eK.ETC2RGBA8UnormSRGB:eK.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return eK.R8Snorm;case 7:return eK.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return eK.R8Sint;case 9:return eK.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return eK.RGBA8Sint;default:return eK.RGBA8Snorm}case 0:switch(t){case 6:return eK.R8Unorm;case 7:return eK.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?eK.RGBA8UnormSRGB:eK.RGBA8Unorm;case 12:return i?eK.BGRA8UnormSRGB:eK.BGRA8Unorm;case 8:return eK.R8Uint;case 9:return eK.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return eK.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 eK.RGBA8Unorm}case 4:switch(t){case 8:return eK.R16Sint;case 9:return eK.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return eK.RGBA16Sint}case 5:switch(t){case 8:return eK.R16Uint;case 9:return eK.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return eK.RGBA16Uint}case 6:switch(t){case 8:return eK.R32Sint;case 9:return eK.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return eK.RGBA32Sint}case 7:switch(t){case 8:return eK.R32Uint;case 9:return eK.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return eK.RGBA32Uint}case 1:switch(t){case 6:return eK.R32Float;case 7:return eK.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return eK.RGBA32Float}case 2:switch(t){case 6:return eK.R16Float;case 7:return eK.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return eK.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return eK.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 eK.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 eK.RGB10A2Unorm;case 11:return eK.RGB10A2UINT}}return i?eK.RGBA8UnormSRGB:eK.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case eK.R8Unorm:case eK.R8Snorm:case eK.R8Uint:case eK.R8Sint:case eK.BC4RUnorm:case eK.BC4RSnorm:case eK.R16Uint:case eK.R16Sint:case eK.Depth16Unorm:case eK.R16Float:case eK.R32Uint:case eK.R32Sint:case eK.R32Float:case eK.Depth32Float:case eK.Stencil8:case eK.Depth24Plus:case eK.EACR11Unorm:case eK.EACR11Snorm:return 1;case eK.RG8Unorm:case eK.RG8Snorm:case eK.RG8Uint:case eK.RG8Sint:case eK.Depth32FloatStencil8:case eK.BC5RGUnorm:case eK.BC5RGSnorm:case eK.RG16Uint:case eK.RG16Sint:case eK.RG16Float:case eK.RG32Uint:case eK.RG32Sint:case eK.RG32Float:case eK.Depth24PlusStencil8:case eK.EACRG11Unorm:case eK.EACRG11Snorm:return 2;case eK.RGB9E5UFloat:case eK.RG11B10UFloat:case eK.BC6HRGBUFloat:case eK.BC6HRGBFloat:case eK.ETC2RGB8Unorm:case eK.ETC2RGB8UnormSRGB:return 3;case eK.RGBA8Unorm:case eK.RGBA8UnormSRGB:case eK.RGBA8Snorm:case eK.RGBA8Uint:case eK.RGBA8Sint:case eK.BGRA8Unorm:case eK.BGRA8UnormSRGB:case eK.RGB10A2UINT:case eK.RGB10A2Unorm:case eK.BC7RGBAUnorm:case eK.BC7RGBAUnormSRGB:case eK.BC3RGBAUnorm:case eK.BC3RGBAUnormSRGB:case eK.BC2RGBAUnorm:case eK.BC2RGBAUnormSRGB:case eK.BC1RGBAUnorm:case eK.BC1RGBAUnormSRGB:case eK.RGBA16Uint:case eK.RGBA16Sint:case eK.RGBA16Float:case eK.RGBA32Uint:case eK.RGBA32Sint:case eK.RGBA32Float:case eK.ETC2RGB8A1Unorm:case eK.ETC2RGB8A1UnormSRGB:case eK.ETC2RGBA8Unorm:case eK.ETC2RGBA8UnormSRGB:case eK.ASTC4x4Unorm:case eK.ASTC4x4UnormSRGB:case eK.ASTC5x4Unorm:case eK.ASTC5x4UnormSRGB:case eK.ASTC5x5Unorm:case eK.ASTC5x5UnormSRGB:case eK.ASTC6x5Unorm:case eK.ASTC6x5UnormSRGB:case eK.ASTC6x6Unorm:case eK.ASTC6x6UnormSRGB:case eK.ASTC8x5Unorm:case eK.ASTC8x5UnormSRGB:case eK.ASTC8x6Unorm:case eK.ASTC8x6UnormSRGB:case eK.ASTC8x8Unorm:case eK.ASTC8x8UnormSRGB:case eK.ASTC10x5Unorm:case eK.ASTC10x5UnormSRGB:case eK.ASTC10x6Unorm:case eK.ASTC10x6UnormSRGB:case eK.ASTC10x8Unorm:case eK.ASTC10x8UnormSRGB:case eK.ASTC10x10Unorm:case eK.ASTC10x10UnormSRGB:case eK.ASTC12x10Unorm:case eK.ASTC12x10UnormSRGB:case eK.ASTC12x12Unorm:case eK.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case eK.Stencil8:case eK.Depth32FloatStencil8:case eK.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case eK.Depth32FloatStencil8:case eK.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case eK.Depth16Unorm:return eK.Depth16Unorm;case eK.Depth24Plus:case eK.Depth24PlusStencil8:return eK.Depth24Plus;case eK.Depth32Float:case eK.Depth32FloatStencil8:return eK.Depth32Float}return e}copyVideoToTexture(e,t,i,r=!1,s){var a,n,o,l;let h=void 0===s,[c,u]=this._getVideoPipeline(i,r?tm.InvertY:tm.DontInvertY);h&&(s=this._device.createCommandEncoder({})),null===(n=(a=s).pushDebugGroup)||void 0===n||n.call(a,`copy video to texture - invertY=${r}`);let d=t._hardwareTexture,_={colorAttachments:[{view:d.underlyingResource.createView({format:i,dimension:eY.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:ej.All}),loadOp:th.Load,storeOp:tc.Store}]},p=s.beginRenderPass(_),f={layout:u,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},m=this._device.createBindGroup(f);p.setPipeline(c),p.setBindGroup(0,m),p.draw(4,1,0,0),p.end(),null===(l=(o=s).popDebugGroup)||void 0===l||l.call(o),h&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,r,s=!1,a=!1,n=0,o=0,l=1,h=0,c=0,u=0,d=0,_,p){var f,m,g,v,x,b;let T;let S=0!==u,C=void 0===_,[E,y]=this._getPipeline(r,S?tf.InvertYPremultiplyAlphaWithOfst:tf.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:a});if(n=Math.max(n,0),C&&(_=this._device.createCommandEncoder({})),null===(m=(f=_).pushDebugGroup)||void 0===m||m.call(f,`internal process texture - invertY=${s} premultiplyAlpha=${a}`),WebGPUTextureHelper._IsHardwareTexture(e)?(T=e.underlyingResource,s&&!a&&1===l&&0===n||(e=void 0)):(T=e,e=void 0),!T)return;S&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);let R=e,P=null!==(g=null==R?void 0:R._copyInvertYTempTexture)&&void 0!==g?g:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,_,eX.CopySrc|eX.RenderAttachment|eX.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),A=null!==(v=null==R?void 0:R._copyInvertYRenderPassDescr)&&void 0!==v?v:{colorAttachments:[{view:P.createView({format:r,dimension:eY.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:th.Load,storeOp:tc.Store}]},M=_.beginRenderPass(A),I=S?null==R?void 0:R._copyInvertYBindGroupWithOfst:null==R?void 0:R._copyInvertYBindGroup;if(!I){let e={layout:y,entries:[{binding:0,resource:T.createView({format:r,dimension:eY.E2d,baseMipLevel:o,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:n})}]};S&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),I=this._device.createBindGroup(e)}M.setPipeline(E),M.setBindGroup(0,I),M.draw(4,1,0,0),M.end(),_.copyTextureToTexture({texture:P},{texture:T,mipLevel:o,origin:{x:0,y:0,z:n}},{width:t,height:i,depthOrArrayLayers:1}),R?(R._copyInvertYTempTexture=P,R._copyInvertYRenderPassDescr=A,S?R._copyInvertYBindGroupWithOfst=I:R._copyInvertYBindGroup=I):this._deferredReleaseTextures.push([P,null]),null===(b=(x=_).popDebugGroup)||void 0===b||b.call(x),C&&(this._device.queue.submit([_.finish()]),_=null)}copyWithInvertY(e,t,i,r){var s,a,n,o;let l=void 0===r,[h,c]=this._getPipeline(t,tf.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});l&&(r=this._device.createCommandEncoder({})),null===(a=(s=r).pushDebugGroup)||void 0===a||a.call(s,"internal copy texture with invertY");let u=r.beginRenderPass(i),d=this._device.createBindGroup({layout:c,entries:[{binding:0,resource:e}]});u.setPipeline(h),u.setBindGroup(0,d),u.draw(4,1,0,0),u.end(),null===(o=(n=r).popDebugGroup)||void 0===o||o.call(n),l&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,s=!1,a=!1,n=eK.RGBA8Unorm,o=1,l,h=-1,c=0,u){o>1&&(o=4);let d=e.layers||1,_={width:e.width,height:e.height,depthOrArrayLayers:d},p=sn[n]?eX.RenderAttachment:0,f=WebGPUTextureHelper.IsCompressedFormat(n),m=t?WebGPUTextureHelper.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:eX.CopySrc|eX.CopyDst|eX.TextureBinding;c|=t&&!f?eX.CopySrc|p:0,f||a||(c|=p|eX.CopyDst);let v=this._device.createTexture({label:`Texture${a?"3D":"2D"}_${u?u+"_":""}${_.width}x${_.height}x${_.depthOrArrayLayers}_${t?"wmips":"womips"}_${n}_samples${o}`,size:_,dimension:a?eH.E3d:eH.E2d,format:n,usage:g|c,sampleCount:o,mipLevelCount:m});return WebGPUTextureHelper.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,n,0,0,r,s,0,0),t&&i&&this.generateMipmaps(v,n,m,0,l)),v}createCubeTexture(e,t=!1,i=!1,r=!1,s=!1,a=eK.RGBA8Unorm,n=1,o,l=-1,h=0,c){n>1&&(n=4);let u=WebGPUTextureHelper.IsImageBitmapArray(e)?e[0].width:e.width,d=WebGPUTextureHelper.IsImageBitmapArray(e)?e[0].height:e.height,_=sn[a]?eX.RenderAttachment:0,p=WebGPUTextureHelper.IsCompressedFormat(a),f=t?WebGPUTextureHelper.ComputeNumMipmapLevels(u,d):1,m=l>=0?l:eX.CopySrc|eX.CopyDst|eX.TextureBinding;h|=t&&!p?eX.CopySrc|_:0,p||(h|=_|eX.CopyDst);let g=this._device.createTexture({label:`TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${a}_samples${n}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:eH.E2d,format:a,usage:m|h,sampleCount:n,mipLevelCount:f});return WebGPUTextureHelper.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,u,d,a,r,s,0,0),t&&i&&this.generateCubeMipmaps(g,a,f,o)),g}generateCubeMipmaps(e,t,i,r){var s,a,n,o;let l=void 0===r;l&&(r=this._device.createCommandEncoder({})),null===(a=(s=r).pushDebugGroup)||void 0===a||a.call(s,`create cube mipmaps - ${i} levels`);for(let s=0;s<6;++s)this.generateMipmaps(e,t,i,s,r);null===(o=(n=r).popDebugGroup)||void 0===o||o.call(n),l&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,s){var a,n,o,l,h,c,u,d;let _;let p=void 0===s,[f,m]=this._getPipeline(t);if(r=Math.max(r,0),p&&(s=this._device.createCommandEncoder({})),null===(n=(a=s).pushDebugGroup)||void 0===n||n.call(a,`create mipmaps for face #${r} - ${i} levels`),WebGPUTextureHelper._IsHardwareTexture(e)?(_=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(_=e,e=void 0),!_)return;let g=e;for(let e=1;e<i;++e){let i=null!==(l=null===(o=null==g?void 0:g._mipmapGenRenderPassDescr[r])||void 0===o?void 0:o[e-1])&&void 0!==l?l:{colorAttachments:[{view:_.createView({format:t,dimension:eY.E2d,baseMipLevel:e,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:r}),loadOp:th.Load,storeOp:tc.Store}]};g&&(g._mipmapGenRenderPassDescr[r]=g._mipmapGenRenderPassDescr[r]||[],g._mipmapGenRenderPassDescr[r][e-1]=i);let a=s.beginRenderPass(i),n=null!==(c=null===(h=null==g?void 0:g._mipmapGenBindGroup[r])||void 0===h?void 0:h[e-1])&&void 0!==c?c:this._device.createBindGroup({layout:m,entries:[{binding:0,resource:this._mipmapSampler},{binding:1,resource:_.createView({format:t,dimension:eY.E2d,baseMipLevel:e-1,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:r})}]});g&&(g._mipmapGenBindGroup[r]=g._mipmapGenBindGroup[r]||[],g._mipmapGenBindGroup[r][e-1]=n),a.setPipeline(f),a.setBindGroup(0,n),a.draw(4,1,0,0),a.end()}null===(d=(u=s).popDebugGroup)||void 0===d||d.call(u),p&&(this._device.queue.submit([s.finish()]),s=null)}createGPUTextureForInternalTexture(e,t,i,r,s){let a;e._hardwareTexture||(e._hardwareTexture=new WebGPUHardwareTexture),void 0===t&&(t=e.width),void 0===i&&(i=e.height),void 0===r&&(r=e.depth);let n=e._hardwareTexture,o=((null!=s?s:0)&1)!=0;n.format=WebGPUTextureHelper.GetWebGPUTextureFormat(e.type,e.format,e._useSRGBBuffer),n.textureUsages=e._source===$.RenderTarget||e.source===$.MultiRenderTarget?eX.TextureBinding|eX.CopySrc|eX.RenderAttachment:e._source===$.DepthStencil?eX.TextureBinding|eX.RenderAttachment:-1,n.textureAdditionalUsages=o?eX.StorageBinding:0;let l=e.generateMipMaps,h=r||1;if(a=null!==e._maxLodLevel?e._maxLodLevel:l?WebGPUTextureHelper.ComputeNumMipmapLevels(t,i):1,e.isCube){let r=this.createCubeTexture({width:t,height:i},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,n.format,1,this._commandEncoderForCreation,n.textureUsages,n.textureAdditionalUsages,e.label);n.set(r),n.createView({format:WebGPUTextureHelper.GetDepthFormatOnly(n.format),dimension:eY.Cube,mipLevelCount:a,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:6,aspect:WebGPUTextureHelper.HasDepthAndStencilAspects(n.format)?ej.DepthOnly:ej.All},o)}else{let r=this.createTexture({width:t,height:i,layers:h},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,e.is3D,n.format,1,this._commandEncoderForCreation,n.textureUsages,n.textureAdditionalUsages,e.label);n.set(r),n.createView({format:WebGPUTextureHelper.GetDepthFormatOnly(n.format),dimension:e.is2DArray?eY.E2dArray:e.is3D?eH.E3d:eY.E2d,mipLevelCount:a,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:e.is3D?1:h,aspect:WebGPUTextureHelper.HasDepthAndStencilAspects(n.format)?ej.DepthOnly:ej.All},o)}return e.width=e.baseWidth=t,e.height=e.baseHeight=i,e.depth=e.baseDepth=r,this.createMSAATexture(e,e.samples),n}createMSAATexture(e,t,i=!0,r=-1){let s=e._hardwareTexture;if(i&&(null==s||s.releaseMSAATexture()),!s||(null!=t?t:1)<=1)return;let a=e.width,n=e.height,o=this.createTexture({width:a,height:n,layers:1},!1,!1,!1,!1,!1,s.format,t,this._commandEncoderForCreation,eX.RenderAttachment,0,e.label?"MSAA"+e.label:void 0);s.setMSAATexture(o,r)}updateCubeTextures(e,t,i,r,s,a=!1,n=!1,o=0,l=0){let h=[0,3,1,4,2,5];for(let c=0;c<h.length;++c){let u=e[h[c]];this.updateTexture(u,t,i,r,1,s,c,0,a,n,o,l)}}updateTexture(e,t,i,r,s,a,n=0,o=0,l=!1,h=!1,c=0,u=0,d){let _=WebGPUTextureHelper._IsInternalTexture(t)?t._hardwareTexture.underlyingResource:t,p=WebGPUTextureHelper._GetBlockInformationFromFormat(a),f=WebGPUTextureHelper._IsInternalTexture(t)?t._hardwareTexture:t,m={texture:_,origin:{x:c,y:u,z:Math.max(n,0)},mipLevel:o,premultipliedAlpha:h},g={width:Math.ceil(i/p.width)*p.width,height:Math.ceil(r/p.height)*p.height,depthOrArrayLayers:s||1};if(void 0!==e.byteLength){let v=Math.ceil(i/p.width)*p.length,x=256*Math.ceil(v/256)===v;if(x){let t=this._device.createCommandEncoder({}),i=this._bufferManager.createRawBuffer(e.byteLength,ez.MapWrite|ez.CopySrc,!0,"TempBufferForUpdateTexture"+(_?"_"+_.label:"")),s=i.getMappedRange();new Uint8Array(s).set(e),i.unmap(),t.copyBufferToTexture({buffer:i,offset:0,bytesPerRow:v,rowsPerImage:r},m,g),this._device.queue.submit([t.finish()]),this._bufferManager.releaseBuffer(i)}else this._device.queue.writeTexture(m,e,{offset:0,bytesPerRow:v,rowsPerImage:r},g);if(l||h){if(WebGPUTextureHelper._IsInternalTexture(t)){let e=0===c&&0===u&&i===t.width&&r===t.height;this.invertYPreMultiplyAlpha(f,t.width,t.height,a,l,h,n,o,s||1,c,u,e?0:i,e?0:r,void 0,d)}else throw"updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!"}}else if(l){if(m.premultipliedAlpha=!1,WebGPUTextureHelper._IsInternalTexture(t)&&0===c&&0===u&&i===t.width&&r===t.height)this._device.queue.copyExternalImageToTexture({source:e},m,g),this.invertYPreMultiplyAlpha(f,i,r,a,l,h,n,o,s||1,0,0,0,0,void 0,d);else{let t=this._device.createCommandEncoder({}),c=this.createTexture({width:i,height:r,layers:1},!1,!1,!1,!1,!1,a,1,t,eX.CopySrc|eX.TextureBinding,void 0,"TempTextureForUpdateTexture");this._deferredReleaseTextures.push([c,null]),g.depthOrArrayLayers=1,this._device.queue.copyExternalImageToTexture({source:e},{texture:c},g),g.depthOrArrayLayers=s||1,this.invertYPreMultiplyAlpha(c,i,r,a,l,h,n,o,s||1,0,0,0,0,t,d),t.copyTextureToTexture({texture:c},m,g),this._device.queue.submit([t.finish()])}}else this._device.queue.copyExternalImageToTexture({source:e},m,g)}readPixels(e,t,i,r,s,a,n=0,o=0,l=null,h=!1){let c=WebGPUTextureHelper._GetBlockInformationFromFormat(a),u=Math.ceil(r/c.width)*c.length,d=256*Math.ceil(u/256),_=d*s,p=this._bufferManager.createRawBuffer(_,ez.MapRead|ez.CopyDst,void 0,"TempBufferForReadPixels"+(e.label?"_"+e.label:"")),f=this._device.createCommandEncoder({});return f.copyTextureToBuffer({texture:e,mipLevel:o,origin:{x:t,y:i,z:Math.max(n,0)}},{buffer:p,offset:0,bytesPerRow:d},{width:r,height:s,depthOrArrayLayers:1}),this._device.queue.submit([f.finish()]),this._bufferManager.readDataFromBuffer(p,_,r,s,u,d,WebGPUTextureHelper._GetTextureTypeFromFormat(a),0,l,!0,h)}releaseTexture(e){if(WebGPUTextureHelper._IsInternalTexture(e)){let t=e._hardwareTexture,i=e._irradianceTexture;this._deferredReleaseTextures.push([t,i])}else this._deferredReleaseTextures.push([e,null])}destroyDeferredTextures(){for(let e=0;e<this._deferredReleaseTextures.length;++e){let[t,i]=this._deferredReleaseTextures[e];t&&(WebGPUTextureHelper._IsHardwareTexture(t)?t.release():t.destroy()),null==i||i.dispose()}this._deferredReleaseTextures.length=0}};let WebGPUDataBuffer=class WebGPUDataBuffer extends dataBuffer_DataBuffer{constructor(e,t=0){super(),this.capacity=t,this._buffer=e}get underlyingResource(){return this._buffer}};let WebGPUBufferManager=class WebGPUBufferManager{static _IsGPUBuffer(e){return void 0===e.underlyingResource}static _FlagsToString(e,t=""){let i=t;for(let t=0;t<=9;++t)e&1<<t&&(i&&(i+="_"),i+=ez[1<<t]);return i}constructor(e){this._deferredReleaseBuffers=[],this._device=e}createRawBuffer(e,t,i=!1,r){let s=void 0!==e.byteLength?e.byteLength+3&-4:e+3&-4,a={label:WebGPUBufferManager._FlagsToString(t,null!=r?r:"Buffer")+"_size"+s,mappedAtCreation:i,size:s,usage:t};return this._device.createBuffer(a)}createBuffer(e,t,i){let r=void 0!==e.byteLength,s=this.createRawBuffer(e,t,void 0,i),a=new WebGPUDataBuffer(s);return a.references=1,a.capacity=r?e.byteLength:e,r&&this.setSubData(a,0,e),a}setRawData(e,t,i,r,s){this._device.queue.writeBuffer(e,t,i.buffer,r,s)}setSubData(e,t,i,r=0,s=0){let a=e.underlyingResource;s=Math.min(s=s||i.byteLength,e.capacity-t);let n=i.byteOffset+r,o=n+s,l=s+3&-4;if(l!==s){let e=new Uint8Array(i.buffer.slice(n,o));(i=new Uint8Array(l)).set(e),r=0,n=0,o=l,s=l}let h=0;for(;o-(n+h)>15728640;)this._device.queue.writeBuffer(a,t+h,i.buffer,n+h,15728640),h+=15728640;this._device.queue.writeBuffer(a,t+h,i.buffer,n+h,s-h)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));let r=new Uint16Array(t);for(;e--;)i[e]=FromHalfFloat(r[e]);return i}readDataFromBuffer(e,t,i,r,s,a,n=0,o=0,l=null,h=!0,c=!1){let u=1===n?2:2===n?1:0;return new Promise((i,d)=>{e.mapAsync(eW.Read,o,t).then(()=>{let d=e.getMappedRange(o,t),_=l;if(c)_=null===_?allocateAndCopyTypedBuffer(n,t,!0,d):allocateAndCopyTypedBuffer(n,_.buffer,void 0,d);else if(null===_)switch(u){case 0:(_=new Uint8Array(t)).set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:(_=new Float32Array(t/4)).set(new Float32Array(d))}else switch(u){case 0:(_=new Uint8Array(_.buffer)).set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:(_=new Float32Array(_.buffer)).set(new Float32Array(d))}if(s!==a){1!==u||c||(s*=2,a*=2);let e=new Uint8Array(_.buffer),t=s,i=0;for(let n=1;n<r;++n){i=n*a;for(let r=0;r<s;++r)e[t++]=e[i++]}_=0===u||c?new Uint8Array(e.buffer,0,t):new Float32Array(e.buffer,0,t/4)}e.unmap(),h&&this.releaseBuffer(e),i(_)},e=>d(e))})}releaseBuffer(e){return WebGPUBufferManager._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e<this._deferredReleaseBuffers.length;++e)this._deferredReleaseBuffers[e].destroy();this._deferredReleaseBuffers.length=0}};let WebGPURenderPassWrapper=class WebGPURenderPassWrapper{constructor(){this.colorAttachmentGPUTextures=[],this.reset()}reset(e=!1){this.renderPass=null,e&&(this.renderPassDescriptor=null,this.colorAttachmentViewDescriptor=null,this.depthAttachmentViewDescriptor=null,this.colorAttachmentGPUTextures=[],this.depthTextureFormat=void 0)}};let so=[0,0,3,7,0,2,6,2,4,1,5,3,1],sl=[0,64,32,96,16,80,48,112,8],sh=[0,128,128,0,0,0,0,128,0,0,0,0,128];let WebGPUCacheSampler=class WebGPUCacheSampler{constructor(e){this._samplers={},this._device=e,this.disabled=!1}static GetSamplerHashCode(e){var t,i,r;let s=e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,a=so[e.samplingMode]+sl[(e._comparisonFunction||514)-512+1]+sh[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(r=e._cachedWrapR)&&void 0!==r?r:1)<<12)+((e.useMipMaps?1:0)<<14)+(s<<15);return a}static _GetSamplerFilterDescriptor(e,t){let i,r,s,a,n;let o=e.useMipMaps;switch(e.samplingMode){case 11:i=e$.Linear,r=e$.Linear,s=e$.Nearest,o||(a=n=0);break;case 3:case 3:i=e$.Linear,r=e$.Linear,o?s=e$.Linear:(s=e$.Nearest,a=n=0);break;case 8:i=e$.Nearest,r=e$.Nearest,o?s=e$.Linear:(s=e$.Nearest,a=n=0);break;case 4:i=e$.Nearest,r=e$.Nearest,s=e$.Nearest,o||(a=n=0);break;case 5:i=e$.Nearest,r=e$.Linear,s=e$.Nearest,o||(a=n=0);break;case 6:i=e$.Nearest,r=e$.Linear,o?s=e$.Linear:(s=e$.Nearest,a=n=0);break;case 7:i=e$.Nearest,r=e$.Linear,s=e$.Nearest,a=n=0;break;case 1:case 1:default:i=e$.Nearest,r=e$.Nearest,s=e$.Nearest,a=n=0;break;case 9:i=e$.Linear,r=e$.Nearest,s=e$.Nearest,o||(a=n=0);break;case 10:i=e$.Linear,r=e$.Nearest,o?s=e$.Linear:(s=e$.Nearest,a=n=0);break;case 2:case 2:i=e$.Linear,r=e$.Linear,s=e$.Nearest,a=n=0;break;case 12:i=e$.Linear,r=e$.Nearest,s=e$.Nearest,a=n=0}return t>1&&(0!==a||0!==n)&&s!==e$.Nearest?{magFilter:e$.Linear,minFilter:e$.Linear,mipmapFilter:e$.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:s,lodMinClamp:a,lodMaxClamp:n}}static _GetWrappingMode(e){switch(e){case 1:break;case 0:return eq.ClampToEdge;case 2:return eq.MirrorRepeat}return eq.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e){let 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?WebGPUCacheSampler.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:i.anisotropyEnabled?t:1})}static GetCompareFunction(e){switch(e){case 519:return eZ.Always;case 514:return eZ.Equal;case 516:return eZ.Greater;case 518:return eZ.GreaterEqual;case 513:default:return eZ.Less;case 515:return eZ.LessEqual;case 512:return eZ.Never;case 517:return eZ.NotEqual}}getSampler(e,t=!1,i=0){if(this.disabled)return this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(e));t?i=0:0===i&&(i=WebGPUCacheSampler.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(e)),t||(this._samplers[i]=r)),r}};!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"}(tg||(tg={}));let sc={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},su={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},sd={[buffer_VertexBuffer.PositionKind]:!0,[buffer_VertexBuffer.NormalKind]:!0,[buffer_VertexBuffer.TangentKind]:!0,[buffer_VertexBuffer.UVKind]:!0,[buffer_VertexBuffer.UV2Kind]:!0,[buffer_VertexBuffer.UV3Kind]:!0,[buffer_VertexBuffer.UV4Kind]:!0,[buffer_VertexBuffer.UV5Kind]:!0,[buffer_VertexBuffer.UV6Kind]:!0,[buffer_VertexBuffer.ColorKind]:!0,[buffer_VertexBuffer.ColorInstanceKind]:!0,[buffer_VertexBuffer.MatricesIndicesKind]:!0,[buffer_VertexBuffer.MatricesWeightsKind]:!0,[buffer_VertexBuffer.MatricesIndicesExtraKind]:!0,[buffer_VertexBuffer.MatricesWeightsExtraKind]:!0};let WebGPUCacheRenderPipeline=class WebGPUCacheRenderPipeline{static _IsSignedType(e){switch(e){case buffer_VertexBuffer.BYTE:case buffer_VertexBuffer.SHORT:case buffer_VertexBuffer.INT:case buffer_VertexBuffer.FLOAT:return!0;case buffer_VertexBuffer.UNSIGNED_BYTE:case buffer_VertexBuffer.UNSIGNED_SHORT:case buffer_VertexBuffer.UNSIGNED_INT:return!1;default:throw Error(`Invalid type '${e}'`)}}constructor(e,t,i){this.mrtTextureCount=0,this._device=e,this._useTextureStage=i,this._states=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=[eK.BGRA8Unorm],this.setColorFormat(eK.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(eK.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,r=0){if(i>1&&(i=4),this.disabled){let s=WebGPUCacheRenderPipeline._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,s,i),WebGPUCacheRenderPipeline.NumCacheMiss++,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,WebGPUCacheRenderPipeline.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return WebGPUCacheRenderPipeline.NumCacheHitWithHash++,this._parameter.pipeline;let s=WebGPUCacheRenderPipeline._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),WebGPUCacheRenderPipeline.NumCacheMiss++,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame=WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,s,a,n,o){this._depthWriteEnabled=n,this._depthTestEnabled=a,this._depthCompare=(null!=o?o:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[tg.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[tg.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=sn[null!=e?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i<e.length;++i)0!==e[i]&&(t+=1<<i);this._mrtEnabledMask!==t&&(this._mrtEnabledMask=t,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.MRTAttachments1))}setMRT(e,t){var i,r;if((t=null!=t?t:e.length)>10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;let s=[0,0],a=0,n=0,o=0;for(let l=0;l<t;++l){let t=e[l],h=null==t?void 0:t._hardwareTexture;this._mrtFormats[o]=null!==(i=null==h?void 0:h.format)&&void 0!==i?i:this._webgpuColorFormat[0],s[a]+=sn[null!==(r=this._mrtFormats[o])&&void 0!==r?r:""]<<n,n+=6,o++,n>=32&&(n=0,a++)}this._mrtFormats.length=o,(this._mrtAttachments1!==s[0]||this._mrtAttachments2!==s[1])&&(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[tg.MRTAttachments1]=s[0],this._states[tg.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.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:sn[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:su[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:su[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:su[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[tg.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[tg.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,s,a,n){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:519)-512,this._stencilFrontDepthFailOp=null===i?1:su[i],this._stencilFrontPassOp=null===r?2:su[r],this._stencilFrontFailOp=null===s?1:su[s],this.setStencilReadMask(a),this.setStencilWriteMask(n)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return e8.TriangleList;case 2:case 3:return e8.PointList;case 1:case 4:return e8.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return e8.LineStrip;case 7:return e8.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return ti.Add;case 32778:return ti.Subtract;case 32779:return ti.ReverseSubtract;case 32775:return ti.Min;case 32776:return ti.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return tt.Zero;case 1:default:return tt.One;case 768:return tt.Src;case 769:return tt.OneMinusSrc;case 770:return tt.SrcAlpha;case 771:return tt.OneMinusSrcAlpha;case 772:return tt.DstAlpha;case 773:return tt.OneMinusDstAlpha;case 774:return tt.Dst;case 775:return tt.OneMinusDst;case 776:return tt.SrcAlphaSaturated;case 32769:case 32771:return tt.Constant;case 32770:case 32772:return tt.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:break;case 1:return eZ.Less;case 2:return eZ.Equal;case 3:return eZ.LessEqual;case 4:return eZ.Greater;case 5:return eZ.NotEqual;case 6:return eZ.GreaterEqual;case 7:return eZ.Always}return eZ.Never}static _GetStencilOpFunction(e){switch(e){case 0:return tr.Zero;case 1:break;case 2:return tr.Replace;case 3:return tr.IncrementClamp;case 4:return tr.DecrementClamp;case 5:return tr.Invert;case 6:return tr.IncrementWrap;case 7:return tr.DecrementWrap}return tr.Keep}static _GetVertexInputDescriptorFormat(e){let t=e.type,i=e.normalized,r=e.getSize();switch(t){case buffer_VertexBuffer.BYTE:switch(r){case 1:case 2:return i?ta.Snorm8x2:ta.Sint8x2;case 3:case 4:return i?ta.Snorm8x4:ta.Sint8x4}break;case buffer_VertexBuffer.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?ta.Unorm8x2:ta.Uint8x2;case 3:case 4:return i?ta.Unorm8x4:ta.Uint8x4}break;case buffer_VertexBuffer.SHORT:switch(r){case 1:case 2:return i?ta.Snorm16x2:ta.Sint16x2;case 3:case 4:return i?ta.Snorm16x4:ta.Sint16x4}break;case buffer_VertexBuffer.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?ta.Unorm16x2:ta.Uint16x2;case 3:case 4:return i?ta.Unorm16x4:ta.Uint16x4}break;case buffer_VertexBuffer.INT:switch(r){case 1:return ta.Sint32;case 2:return ta.Sint32x2;case 3:return ta.Sint32x3;case 4:return ta.Sint32x4}break;case buffer_VertexBuffer.UNSIGNED_INT:switch(r){case 1:return ta.Uint32;case 2:return ta.Uint32x2;case 3:return ta.Uint32x3;case 4:return ta.Uint32x4}break;case buffer_VertexBuffer.FLOAT:switch(r){case 1:return ta.Float32;case 2:return ta.Float32x2;case 3:return ta.Float32x3;case 4:return ta.Float32x4}}throw Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[tg.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.ShaderStage))}_setRasterizationState(e,t){let i=this._frontFace,r=this._cullEnabled?this._cullFace:0,s=this._clampDepth?1:0,a=this._alphaToCoverageEnabled?1:0,n=i-1+(r<<1)+(s<<3)+(a<<4)+(e<<5)+(t<<8);this._rasterizationState!==n&&(this._rasterizationState=n,this._states[tg.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.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:sc[this._alphaBlendFuncParams[0]])<<0)+((null===this._alphaBlendFuncParams[1]?2:sc[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:sc[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:sc[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[tg.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.ColorStates))}_setDepthStencilState(){let 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[tg.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.DepthStencilState))}_setVertexState(e){var t,i;let r;let s=this._statesLength,a=tg.VertexState,n=e._pipelineContext,o=n.shaderProcessingContext.attributeNamesFromEffect,l=n.shaderProcessingContext.attributeLocationsFromEffect,h=0;for(let e=0;e<o.length;e++){let s=l[e],n=null!==(t=this._overrideVertexBuffers&&this._overrideVertexBuffers[o[e]])&&void 0!==t?t:this._vertexBuffers[o[e]];n||(n=this._emptyVertexBuffer);let c=null===(i=n.effectiveBuffer)||void 0===i?void 0:i.underlyingResource;if(void 0===n._validOffsetRange){let e=n.effectiveByteOffset,t=n.getSize(!0),i=n.effectiveByteStride;n._validOffsetRange=e+t<=this._kMaxVertexBufferStride&&0===i||0!==i&&e+t<=i}r&&r===c&&n._validOffsetRange||(this.vertexBuffers[h++]=n,r=n._validOffsetRange?c:null);let u=n.hashCode+(s<<7);this._isDirty=this._isDirty||this._states[a]!==u,this._states[a++]=u}this.vertexBuffers.length=h,this._statesLength=a,this._isDirty=this._isDirty||a!==s,this._isDirty&&(this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.VertexState))}_setTextureState(e){this._textureState!==e&&(this._textureState=e,this._states[tg.TextureStage]=this._textureState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.TextureStage))}_createPipelineLayout(e){if(this._useTextureStage)return this._createPipelineLayoutWithTextureStage(e);let t=[],i=e.shaderProcessingContext.bindGroupLayoutEntries;for(let e=0;e<i.length;e++){let r=i[e];t[e]=this._device.createBindGroupLayout({entries:r})}return e.bindGroupLayouts[0]=t,this._device.createPipelineLayout({bindGroupLayouts:t})}_createPipelineLayoutWithTextureStage(e){var t;let i=e.shaderProcessingContext,r=i.bindGroupLayoutEntries,s=1;for(let e=0;e<r.length;e++){let a=r[e];for(let n=0;n<a.length;n++){let a=r[e][n];if(a.texture){let n=i.bindGroupLayoutEntryInfo[e][a.binding].name,o=i.availableTextures[n],l=o.autoBindSampler?i.availableSamplers[n+WebGPUShaderProcessor.AutoSamplerSuffix]:null,h=o.sampleType,c=null!==(t=null==l?void 0:l.type)&&void 0!==t?t:e1.Filtering;if(this._textureState&s&&h!==e2.Depth&&(o.autoBindSampler&&(c=e1.NonFiltering),h=e2.UnfilterableFloat),a.texture.sampleType=h,l){let e=i.bindGroupLayoutEntryInfo[l.binding.groupIndex][l.binding.bindingIndex].index;r[l.binding.groupIndex][e].sampler.type=c}s<<=1}}}let a=[];for(let e=0;e<r.length;++e)a[e]=this._device.createBindGroupLayout({entries:r[e]});return e.bindGroupLayouts[this._textureState]=a,this._device.createPipelineLayout({bindGroupLayouts:a})}_getVertexInputDescriptor(e){var t,i;let r,s;let a=[],n=e._pipelineContext,o=n.shaderProcessingContext.attributeNamesFromEffect,l=n.shaderProcessingContext.attributeLocationsFromEffect;for(let e=0;e<o.length;e++){let n=l[e],h=null!==(t=this._overrideVertexBuffers&&this._overrideVertexBuffers[o[e]])&&void 0!==t?t:this._vertexBuffers[o[e]];h||(h=this._emptyVertexBuffer);let c=null===(i=h.effectiveBuffer)||void 0===i?void 0:i.underlyingResource,u=h.effectiveByteOffset,d=!h._validOffsetRange;if(!(r&&s&&r===c)||d){let e={arrayStride:h.effectiveByteStride,stepMode:h.getIsInstanced()?tn.Instance:tn.Vertex,attributes:[]};a.push(e),s=e.attributes,d&&(u=0,c=null)}s.push({shaderLocation:n,offset:u,format:WebGPUCacheRenderPipeline._GetVertexInputDescriptorFormat(h)}),r=c}return a}_processNonFloatVertexBuffers(e,t){let i=e.engine._getShaderProcessor(e.shaderProcessingContext.shaderLanguage),r=!1;for(let t in this._vertexBuffers){let s=this._vertexBuffers[t];if(!s||!sd[t])continue;let a=s.normalized?buffer_VertexBuffer.FLOAT:s.type,n=e.vertexBufferKindToType[t];(a!==buffer_VertexBuffer.FLOAT&&void 0===n||void 0!==n&&n!==a)&&(r=!0,e.vertexBufferKindToType[t]=a,a!==buffer_VertexBuffer.FLOAT&&(i.vertexBufferKindToNumberOfComponents[t]=buffer_VertexBuffer.DeduceStride(t),WebGPUCacheRenderPipeline._IsSignedType(a)&&(i.vertexBufferKindToNumberOfComponents[t]*=-1)))}r&&t._processShaderCode(i,!0)}_createRenderPipeline(e,t,i){var r,s,a;let n;let o=e._pipelineContext,l=this._getVertexInputDescriptor(e),h=this._createPipelineLayout(o),c=[],u=this._getAphaBlendState(),d=this._getColorBlendState();if(this._processNonFloatVertexBuffers(o,e),this._mrtAttachments1>0)for(let e=0;e<this._mrtFormats.length;++e){let t=this._mrtFormats[e];if(t){let i={format:t,writeMask:(this._mrtEnabledMask&1<<e)!=0?this._writeMask:0};u&&d&&(i.blend={alpha:u,color:d}),c.push(i)}else c.push(null)}else if(this._webgpuColorFormat[0]){let e={format:this._webgpuColorFormat[0],writeMask:this._writeMask};u&&d&&(e.blend={alpha:u,color:d}),c.push(e)}else c.push(null);let _={compare:WebGPUCacheRenderPipeline._GetCompareFunction(this._stencilEnabled?this._stencilFrontCompare:7),depthFailOp:WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontDepthFailOp:1),failOp:WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontFailOp:1),passOp:WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontPassOp:1)};(t===e8.LineStrip||t===e8.TriangleStrip)&&(n=!this._indexBuffer||this._indexBuffer.is32Bits?ts.Uint32:ts.Uint16);let p=!!this._webgpuDepthStencilFormat&&WebGPUTextureHelper.HasStencilAspect(this._webgpuDepthStencilFormat);return this._device.createRenderPipeline({label:`RenderPipeline_${null!==(s=null===(r=c[0])||void 0===r?void 0:r.format)&&void 0!==s?s:"nooutput"}_${null!==(a=this._webgpuDepthStencilFormat)&&void 0!==a?a:"nodepth"}_samples${i}_textureState${this._textureState}`,layout:h,vertex:{module:o.stages.vertexStage.module,entryPoint:o.stages.vertexStage.entryPoint,buffers:l},primitive:{topology:t,stripIndexFormat:n,frontFace:1===this._frontFace?e7.CCW:e7.CW,cullMode:this._cullEnabled?2===this._cullFace?e9.Front:e9.Back:e9.None},fragment:o.stages.fragmentStage?{module:o.stages.fragmentStage.module,entryPoint:o.stages.fragmentStage.entryPoint,targets:c}:void 0,multisample:{count:i},depthStencil:void 0===this._webgpuDepthStencilFormat?void 0:{depthWriteEnabled:this._depthWriteEnabled,depthCompare:this._depthTestEnabled?WebGPUCacheRenderPipeline._GetCompareFunction(this._depthCompare):eZ.Always,format:this._webgpuDepthStencilFormat,stencilFront:this._stencilEnabled&&p?_:void 0,stencilBack:this._stencilEnabled&&p?_:void 0,stencilReadMask:this._stencilEnabled&&p?this._stencilReadMask:void 0,stencilWriteMask:this._stencilEnabled&&p?this._stencilWriteMask:void 0,depthBias:this._depthBias,depthBiasClamp:this._depthBiasClamp,depthBiasSlopeScale:this._depthBiasSlopeScale}})}};WebGPUCacheRenderPipeline.NumCacheHitWithoutHash=0,WebGPUCacheRenderPipeline.NumCacheHitWithHash=0,WebGPUCacheRenderPipeline.NumCacheMiss=0,WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame=0,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame=0;let NodeState=class NodeState{constructor(){this.values={}}count(){let e=0,t=this.pipeline?1:0;for(let i in this.values){let r=this.values[i],[s,a]=r.count();e+=s,t+=a,e++}return[e,t]}};let WebGPUCacheRenderPipelineTree=class WebGPUCacheRenderPipelineTree extends WebGPUCacheRenderPipeline{static GetNodeCounts(){let e=WebGPUCacheRenderPipelineTree._Cache.count();return{nodeCount:e[0],pipelineCount:e[1]}}static _GetPipelines(e,t,i,r){if(e.pipeline){let e=i.slice();e.length=r,t.push(e)}for(let s in e.values){let a=e.values[s];i[r]=parseInt(s),WebGPUCacheRenderPipelineTree._GetPipelines(a,t,i,r+1)}}static GetPipelines(){let e=[];return WebGPUCacheRenderPipelineTree._GetPipelines(WebGPUCacheRenderPipelineTree._Cache,e,[],0),e}constructor(e,t,i){super(e,t,i),this._nodeStack=[],this._nodeStack[0]=WebGPUCacheRenderPipelineTree._Cache}_getRenderPipeline(e){let t=this._nodeStack[this._stateDirtyLowestIndex];for(let e=this._stateDirtyLowestIndex;e<this._statesLength;++e){let i=t.values[this._states[e]];i||(i=new NodeState,t.values[this._states[e]]=i),t=i,this._nodeStack[e+1]=t}e.token=t,e.pipeline=t.pipeline}_setRenderPipeline(e){e.token.pipeline=e.pipeline}};WebGPUCacheRenderPipelineTree._Cache=new NodeState;let WebGPUStencilStateComposer=class WebGPUStencilStateComposer extends StencilStateComposer{constructor(e){super(!1),this._cache=e,this.reset()}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._cache.setStencilCompare(e))}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._cache.setStencilReadMask(e))}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._cache.setStencilFailOp(e))}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._cache.setStencilDepthFailOp(e))}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._cache.setStencilPassOp(e))}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._cache.setStencilWriteMask(e))}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._cache.setStencilEnabled(e))}reset(){super.reset(),this._cache.resetStencilState()}apply(){var e;let t=null===(e=this.stencilMaterial)||void 0===e?void 0:e.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.enabled&&(this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask)}};let WebGPUDepthCullingState=class WebGPUDepthCullingState extends DepthCullingState{constructor(e){super(!1),this._cache=e,this.reset()}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0,this._cache.setDepthBiasSlopeScale(e))}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0,this._cache.setDepthBias(e))}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0,this._cache.setCullFace(null!=e?e:1))}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0,this._cache.setCullEnabled(!!e))}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0,this._cache.setDepthCompare(e))}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0,this._cache.setDepthWriteEnabled(e))}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0,this._cache.setDepthTestEnabled(e))}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0,this._cache.setFrontFace(null!=e?e:2))}reset(){super.reset(),this._cache.resetDepthCullingState()}apply(){}};let ExternalTexture=class ExternalTexture{static IsExternalTexture(e){return void 0!==e.underlyingResource}getClassName(){return"ExternalTexture"}get underlyingResource(){return this._video}constructor(e){this.useMipMaps=!1,this.type=16,this._video=e,this.uniqueId=internalTexture_InternalTexture._Counter++}isReady(){return this._video.readyState>=this._video.HAVE_CURRENT_DATA}dispose(){}};let WebGPUMaterialContext=class WebGPUMaterialContext{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatTextures(){return this._numFloatTextures>0}constructor(){this.uniqueId=WebGPUMaterialContext._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],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?WebGPUCacheSampler.GetSamplerHashCode(t):0;let s=r!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var i,r,s;let a=this.textures[e],n=-1;a?n=null!==(r=null===(i=a.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==r?r:-1:this.textures[e]=a={texture:t,isFloatTexture:!1,isExternalTexture:!1},a.isExternalTexture&&this._numExternalTextures--,a.isFloatTexture&&this._numFloatTextures--,t?(a.isFloatTexture=1===t.type,a.isExternalTexture=ExternalTexture.IsExternalTexture(t),a.isFloatTexture&&this._numFloatTextures++,a.isExternalTexture&&this._numExternalTextures++):(a.isFloatTexture=!1,a.isExternalTexture=!1),a.texture=t;let o=n!==(null!==(s=null==t?void 0:t.uniqueId)&&void 0!==s?s:-1);o&&this.updateId++,this.isDirty||(this.isDirty=o)}};WebGPUMaterialContext._Counter=0;let WebGPUDrawContext=class WebGPUDrawContext{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,ez.CopyDst|ez.Indirect|ez.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=WebGPUDrawContext._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}};WebGPUDrawContext._Counter=0;let WebGPUBindGroupCacheNode=class WebGPUBindGroupCacheNode{constructor(){this.values={}}};let WebGPUCacheBindGroups=class WebGPUCacheBindGroups{static get Statistics(){return{totalCreated:WebGPUCacheBindGroups.NumBindGroupsCreatedTotal,lastFrameCreated:WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame,lookupLastFrame:WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame,noLookupLastFrame:WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame=WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame,WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame=WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame,WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame=WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var r,s,a,n,o,l,h,c,u,d;let _;let p=WebGPUCacheBindGroups._Cache,f=this.disabled||i.forceBindGroupCreation;if(!f){if(!t.isDirty(i.updateId)&&!i.isDirty)return WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(let i of e.shaderProcessingContext.bufferNames){let e=null!==(s=null===(r=t.buffers[i])||void 0===r?void 0:r.uniqueId)&&void 0!==s?s:0,a=p.values[e];a||(a=new WebGPUBindGroupCacheNode,p.values[e]=a),p=a}for(let t of e.shaderProcessingContext.samplerNames){let e=null!==(n=null===(a=i.samplers[t])||void 0===a?void 0:a.hashCode)&&void 0!==n?n:0,r=p.values[e];r||(r=new WebGPUBindGroupCacheNode,p.values[e]=r),p=r}for(let t of e.shaderProcessingContext.textureNames){let e=null!==(h=null===(l=null===(o=i.textures[t])||void 0===o?void 0:o.texture)||void 0===l?void 0:l.uniqueId)&&void 0!==h?h:0,r=p.values[e];r||(r=new WebGPUBindGroupCacheNode,p.values[e]=r),p=r}_=p.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,_)return t.bindGroups=_,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame++,_;_=[],t.bindGroups=_,f||(p.bindGroups=_),WebGPUCacheBindGroups.NumBindGroupsCreatedTotal++,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame++;let m=e.bindGroupLayouts[i.textureState];for(let r=0;r<e.shaderProcessingContext.bindGroupLayoutEntries.length;r++){let s=e.shaderProcessingContext.bindGroupLayoutEntries[r],a=e.shaderProcessingContext.bindGroupEntries[r];for(let n=0;n<s.length;n++){let s=e.shaderProcessingContext.bindGroupLayoutEntries[r][n],o=e.shaderProcessingContext.bindGroupLayoutEntryInfo[r][s.binding],l=null!==(c=o.nameInArrayOfTexture)&&void 0!==c?c:o.name;if(s.sampler){let e=i.samplers[l];if(e){let t=e.sampler;if(!t){this._engine.dbgSanityChecks&&logger_Logger.Error(`Trying to bind a null sampler! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[n].resource=this._cacheSampler.getSampler(t,!1,e.hashCode)}else logger_Logger.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(s.texture||s.storageTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){logger_Logger.Error(`Trying to bind a null texture! entry=${JSON.stringify(s)}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||s.texture&&!t.view||s.storageTexture&&!t.viewForWriting)){logger_Logger.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, isReady=${null===(u=e.texture)||void 0===u?void 0:u.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[n].resource=s.storageTexture?t.viewForWriting:t.view}else logger_Logger.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(s.externalTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){logger_Logger.Error(`Trying to bind a null external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){logger_Logger.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, isReady=${null===(d=e.texture)||void 0===d?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[n].resource=this._device.importExternalTexture({source:t})}else logger_Logger.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(s.buffer){let e=t.buffers[l];if(e){let t=e.underlyingResource;a[n].resource.buffer=t,a[n].resource.size=e.capacity}else logger_Logger.Error(`Can't find buffer "${l}". entry=${JSON.stringify(s)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}let n=m[r];_[r]=this._device.createBindGroup({layout:n,entries:a})}return _}};WebGPUCacheBindGroups.NumBindGroupsCreatedTotal=0,WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame=0,WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame=0,WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame=0,WebGPUCacheBindGroups._Cache=new WebGPUBindGroupCacheNode,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame=0;let s_=`uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0), +vec2(1.0,1.0), +vec2(-1.0,-1.0), +vec2(1.0,-1.0)}; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +gl_Position=vec4(pos[gl_VertexID],depthValue,1.0); +#define CUSTOM_VERTEX_MAIN_END +} +`;ShaderStore.ShadersStore.clearQuadVertexShader=s_;let sp=`uniform vec4 color;void main() {gl_FragColor=color;} +`;ShaderStore.ShadersStore.clearQuadPixelShader=sp;let WebGPUClearQuad=class WebGPUClearQuad{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 WebGPUCacheRenderPipelineTree(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,r,s=1){var a,n;let o,l;let h=null,c=!!this._engine._currentRenderTarget;if(e)o=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t<this._cacheRenderPipeline.colorFormats.length;++t)this._keyTemp[e++]=sn[null!==(a=this._cacheRenderPipeline.colorFormats[t])&&void 0!==a?a:""];let u=sn[null!==(n=this._depthTextureFormat)&&void 0!==n?n:0];if(this._keyTemp[e]=(t?t.r+256*t.g+65536*t.b+16777216*t.a:0)+(i?4294967296:0)+(r?8589934592:0)+(this._engine.useReverseDepthBuffer?17179869184:0)+(c?34359738368:0)+(s>1?68719476736:0)+137438953472*u,l=this._keyTemp.join("_"),h=this._bundleCache[l])return h;o=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:s})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&WebGPUTextureHelper.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);let u=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),d=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),d.uniformBuffer.update();let _=c?this._engine._ubInvertY:this._engine._ubDontInvertY,p=d.uniformBuffer.getBuffer(),f=p.uniqueId+"-"+_.uniqueId,m=this._bindGroups[f];if(!m){let e=d.bindGroupLayouts[0];(m=this._bindGroups[f]=[]).push(this._device.createBindGroup({layout:e[0],entries:[]})),WebGPUShaderProcessingContext._SimplifiedKnownBindings||m.push(this._device.createBindGroup({layout:e[1],entries:[]})),m.push(this._device.createBindGroup({layout:e[WebGPUShaderProcessingContext._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:_.underlyingResource,size:_.capacity}},{binding:1,resource:{buffer:p.underlyingResource,size:p.capacity}}]}))}o.setPipeline(u);for(let e=0;e<m.length;++e)o.setBindGroup(e,m[e]);return o.draw(4,1,0,0),e||(h=o.finish(),this._bundleCache[l]=h),h}};let WebGPURenderItemViewport=class WebGPURenderItemViewport{constructor(e,t,i,r){this.x=Math.floor(e),this.y=Math.floor(t),this.w=Math.floor(i),this.h=Math.floor(r)}run(e){e.setViewport(this.x,this.y,this.w,this.h,0,1)}clone(){return new WebGPURenderItemViewport(this.x,this.y,this.w,this.h)}};let WebGPURenderItemScissor=class WebGPURenderItemScissor{constructor(e,t,i,r){this.x=e,this.y=t,this.w=i,this.h=r}run(e){e.setScissorRect(this.x,this.y,this.w,this.h)}clone(){return new WebGPURenderItemScissor(this.x,this.y,this.w,this.h)}};let WebGPURenderItemStencilRef=class WebGPURenderItemStencilRef{constructor(e){this.ref=e}run(e){e.setStencilReference(this.ref)}clone(){return new WebGPURenderItemStencilRef(this.ref)}};let WebGPURenderItemBlendColor=class WebGPURenderItemBlendColor{constructor(e){this.color=e}run(e){e.setBlendConstant(this.color)}clone(){return new WebGPURenderItemBlendColor(this.color)}};let WebGPURenderItemBeginOcclusionQuery=class WebGPURenderItemBeginOcclusionQuery{constructor(e){this.query=e}run(e){e.beginOcclusionQuery(this.query)}clone(){return new WebGPURenderItemBeginOcclusionQuery(this.query)}};let WebGPURenderItemEndOcclusionQuery=class WebGPURenderItemEndOcclusionQuery{constructor(){}run(e){e.endOcclusionQuery()}clone(){return new WebGPURenderItemEndOcclusionQuery}};let WebGPURenderItemBundles=class WebGPURenderItemBundles{constructor(){this.bundles=[]}run(e){e.executeBundles(this.bundles)}clone(){let e=new WebGPURenderItemBundles;return e.bundles=this.bundles,e}};let WebGPUBundleList=class WebGPUBundleList{constructor(e){this.numDrawCalls=0,this._device=e,this._list=Array(10),this._listLength=0}addBundle(e){if(!this._currentItemIsBundle){let e=new WebGPURenderItemBundles;this._list[this._listLength++]=e,this._currentBundleList=e.bundles,this._currentItemIsBundle=!0}e&&this._currentBundleList.push(e)}_finishBundle(){this._currentItemIsBundle&&this._bundleEncoder&&(this._currentBundleList.push(this._bundleEncoder.finish()),this._bundleEncoder=void 0,this._currentItemIsBundle=!1)}addItem(e){this._finishBundle(),this._list[this._listLength++]=e,this._currentItemIsBundle=!1}getBundleEncoder(e,t,i){return this._currentItemIsBundle||(this.addBundle(),this._bundleEncoder=this._device.createRenderBundleEncoder({colorFormats:e,depthStencilFormat:t,sampleCount:i})),this._bundleEncoder}close(){this._finishBundle()}run(e){this.close();for(let t=0;t<this._listLength;++t)this._list[t].run(e)}reset(){this._listLength=0,this._currentItemIsBundle=!1,this.numDrawCalls=0}clone(){this.close();let e=new WebGPUBundleList(this._device);e._list=Array(this._listLength),e._listLength=this._listLength,e.numDrawCalls=this.numDrawCalls;for(let t=0;t<this._listLength;++t)e._list[t]=this._list[t].clone();return e}};let WebGPUQuerySet=class WebGPUQuerySet{get querySet(){return this._querySet}constructor(e,t,i,r,s=!0,a){this._dstBuffers=[],this._device=i,this._bufferManager=r,this._count=e,this._canUseMultipleBuffers=s,this._querySet=i.createQuerySet({label:a,type:t,count:e}),this._queryBuffer=r.createRawBuffer(8*e,ez.QueryResolve|ez.CopySrc,void 0,"QueryBuffer"),s||this._dstBuffers.push(this._bufferManager.createRawBuffer(8*this._count,ez.MapRead|ez.CopyDst,void 0,"QueryBufferNoMultipleBuffers"))}_getBuffer(e,t){let i;if(!this._canUseMultipleBuffers&&0===this._dstBuffers.length)return null;let r=this._device.createCommandEncoder();return 0===this._dstBuffers.length?i=this._bufferManager.createRawBuffer(8*this._count,ez.MapRead|ez.CopyDst,void 0,"QueryBufferAdditionalBuffer"):(i=this._dstBuffers[this._dstBuffers.length-1],this._dstBuffers.length--),r.resolveQuerySet(this._querySet,e,t,this._queryBuffer,0),r.copyBufferToBuffer(this._queryBuffer,0,i,0,8*t),this._device.queue.submit([r.finish()]),i}async readValues(e=0,t=1){let i=this._getBuffer(e,t);if(null===i)return null;await i.mapAsync(eW.Read);let r=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,r}async readValue(e=0){let t=this._getBuffer(e,1);if(null===t)return null;await t.mapAsync(eW.Read);let i=new BigUint64Array(t.getMappedRange()),r=Number(i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r}async readTwoValuesAndSubtract(e=0){let t=this._getBuffer(e,2);if(null===t)return null;await t.mapAsync(eW.Read);let i=new BigUint64Array(t.getMappedRange()),r=Number(i[1]-i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e<this._dstBuffers.length;++e)this._bufferManager.releaseBuffer(this._dstBuffers[e])}};let WebGPUTimestampQuery=class WebGPUTimestampQuery{get gpuFrameTimeCounter(){return this._gpuFrameTimeCounter}constructor(e,t){this._enabled=!1,this._gpuFrameTimeCounter=new perfCounter_PerfCounter,this._measureDurationState=0,this._device=e,this._bufferManager=t}get enable(){return this._enabled}set enable(e){this._enabled!==e&&(this._enabled=e,this._measureDurationState=0,e?this._measureDuration=new WebGPUDurationMeasure(this._device,this._bufferManager):this._measureDuration.dispose())}startFrame(e){this._enabled&&0===this._measureDurationState&&(this._measureDuration.start(e),this._measureDurationState=1)}endFrame(e){1===this._measureDurationState&&(this._measureDurationState=2,this._measureDuration.stop(e).then(e=>{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0}))}};let WebGPUDurationMeasure=class WebGPUDurationMeasure{constructor(e,t){this._querySet=new WebGPUQuerySet(2,tu.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()}};let WebGPUOcclusionQuery=class WebGPUOcclusionQuery{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;let t=!1,i=this._engine._getCurrentRenderPassIndex();switch(i){case 0:t=void 0!==this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet;break;case 1:t=void 0!==this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet}return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,r=50,s=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(r)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();let e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e<this._lastBuffer.length}getQueryResult(e){var t,i;return Number(null!==(i=null===(t=this._lastBuffer)||void 0===t?void 0:t[e])&&void 0!==i?i:-1)}_retrieveQueryBuffer(){this._lastBuffer&&this._frameLastBuffer===this._engine.frameId||this._frameLastBuffer===this._engine.frameId||(this._frameLastBuffer=this._engine.frameId,this._querySet.readValues(0,this._currentTotalIndices).then(e=>{this._lastBuffer=e}))}_allocateNewIndices(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;t<e;++t)this._availableIndices.push(this._currentTotalIndices+t);this._currentTotalIndices+=e,this._querySet=new WebGPUQuerySet(this._currentTotalIndices,tu.Occlusion,this._device,this._bufferManager,!1,"QuerySet_OcclusionQuery_count_"+this._currentTotalIndices),this._frameQuerySetIsDirty=this._engine.frameId}_delayQuerySetDispose(){let e=this._querySet;e&&setTimeout(()=>e.dispose,1e3)}dispose(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0}};let WebGPUTintWASM=class WebGPUTintWASM{async initTwgsl(e){return WebGPUTintWASM._twgsl?void 0:(e=e||{},(e=Object.assign(Object.assign({},WebGPUTintWASM._TWgslDefaultOptions),e)).twgsl)?(WebGPUTintWASM._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await tools_Tools.LoadBabylonScriptAsync(e.jsPath),self.twgsl)?(WebGPUTintWASM._twgsl=await self.twgsl(tools_Tools.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available.")}convertSpirV2WGSL(e,t=!1){let i=WebGPUTintWASM._twgsl.convertSpirV2WGSL(e,WebGPUTintWASM.DisableUniformityAnalysis||t);return WebGPUTintWASM.ShowWGSLShaderCode&&(console.log(i),console.log("***********************************************")),WebGPUTintWASM.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}};WebGPUTintWASM._TWgslDefaultOptions={jsPath:`${tools_Tools._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${tools_Tools._DefaultCdnUrl}/twgsl/twgsl.wasm`},WebGPUTintWASM.ShowWGSLShaderCode=!1,WebGPUTintWASM.DisableUniformityAnalysis=!1,WebGPUTintWASM._twgsl=null;let WebGPUSnapshotRendering=class WebGPUSnapshotRendering{constructor(e,t,i,r){this._record=!1,this._play=!1,this._mainPassBundleList=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i,this._bundleListRenderTarget=r}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,r,s,a;if(this._play)null===(r=null===(i=t._bundleLists)||void 0===i?void 0:i[t._currentLayer])||void 0===r||r.run(e),1===this._mode&&this._engine._reportDrawCall(null===(a=null===(s=t._bundleLists)||void 0===s?void 0:s[t._currentLayer])||void 0===a?void 0:a.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<this._mainPassBundleList.length;++t)this._mainPassBundleList[t].run(e),1===this._mode&&this._engine._reportDrawCall(this._mainPassBundleList[t].numDrawCalls)}reset(){this.enabled=!1,this.enabled=!0}};let sf=`attribute position: vec2<f32>;uniform scale: vec2<f32>;varying vUV: vec2<f32>;const madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +} +`;ShaderStore.ShadersStoreWGSL.postprocessVertexShader=sf;let sm={label:"TextureView_SwapChain_ResolveTarget",dimension:eH.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},sg={label:"TextureView_SwapChain",dimension:eH.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},sv="/* disable_uniformity_analysis */",sx=new math_color_Color4;let webgpuEngine_WebGPUEngine=class webgpuEngine_WebGPUEngine extends engine_Engine{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return logger_Logger.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(){let e=this.name+this.version;return e}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={}){let i=new webgpuEngine_WebGPUEngine(e,t);return new Promise(e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>e(i))})}constructor(e,t={}){var i,r;if(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 WebGPURenderPassWrapper,this._rttRenderPassWrapper=new WebGPURenderPassWrapper,this._pendingDebugCommands=[],this._onAfterUnbindFrameBufferObservable=new observable_Observable,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!==(r=t.enableGPUDebugMarkers)&&void 0!==r&&r,logger_Logger.Log(`Babylon.js v${engine_Engine.Version} - ${this.description} engine`),!navigator.gpu){logger_Logger.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(e),this._shaderProcessor=new WebGPUShaderProcessorGLSL,this._shaderProcessorWGSL=new WebGPUShaderProcessorWGSL}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=webgpuEngine_WebGPUEngine.UseTWGSL?new WebGPUTintWASM: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 logger_Logger.Error("Can not initialize twgsl!"),logger_Logger.Error(e),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},e=>{throw logger_Logger.Error("Can not initialize glslang!"),logger_Logger.Error(e),Error("WebGPU initializations stopped.")}).then(e=>{var t,i,r;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});let s=null!==(i=this._options.deviceDescriptor)&&void 0!==i?i:{},a=null!==(r=null==s?void 0:s.requiredFeatures)&&void 0!==r?r:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(a){let e=[];for(let t of a)-1!==this._adapterSupportedExtensions.indexOf(t)&&e.push(t);s.requiredFeatures=e}if(this._options.setMaximumLimits&&!s.requiredLimits)for(let e in s.requiredLimits={},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 r=-1;this._device.addEventListener("uncapturederror",e=>{++r<this.numMaxUncapturedErrors?logger_Logger.Warn(`WebGPU uncaptured error (${r+1}): ${e.error} - ${e.error.message}`):r++===this.numMaxUncapturedErrors&&logger_Logger.Warn(`WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`)}),this._doNotHandleContextLost||null===(i=this._device.lost)||void 0===i||i.then(e=>{this._isDisposed||(this._contextWasLost=!0,logger_Logger.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(()=>this.initAsync()))})},e=>{logger_Logger.Error("Could not retrieve a WebGPU device."),logger_Logger.Error(e)}).then(()=>{this._bufferManager=new WebGPUBufferManager(this._device),this._textureHelper=new WebGPUTextureHelper(this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new WebGPUCacheSampler(this._device),this._cacheBindGroups=new WebGPUCacheBindGroups(this._device,this._cacheSampler,this),this._timestampQuery=new WebGPUTimestampQuery(this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new WebGPUOcclusionQuery(this,this._device,this._bufferManager):void 0,this._bundleList=new WebGPUBundleList(this._device),this._bundleListRenderTarget=new WebGPUBundleList(this._device),this._snapshotRendering=new WebGPUSnapshotRendering(this,this._snapshotRenderingMode,this._bundleList,this._bundleListRenderTarget),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),ez.Uniform|ez.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),ez.Uniform|ez.CopyDst,"UBDontInvertY"),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._initializeLimits(),this._emptyVertexBuffer=new buffer_VertexBuffer(this,[0],"",!1,!1,1,!1,0,1),this._cacheRenderPipeline=new WebGPUCacheRenderPipelineTree(this._device,this._emptyVertexBuffer,!this._caps.textureFloatLinearFiltering),this._depthCullingState=new WebGPUDepthCullingState(this._cacheRenderPipeline),this._stencilStateComposer=new WebGPUStencilStateComposer(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 WebGPUClearQuad(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=>{logger_Logger.Error("Can not create WebGPU Device and/or context."),logger_Logger.Error(e),console.trace&&console.trace()})}_initGlslang(e){return(e=e||{},(e=Object.assign(Object.assign({},webgpuEngine_WebGPUEngine._GLSLslangDefaultOptions),e)).glslang)?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?tools_Tools.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(tools_Tools.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(ek.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(ek.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(ek.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(ek.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(ek.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(ek.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,forceVertexBufferStrideMultiple4Bytes:!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 WebGPUHardwareTexture],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat}_initializeMainAttachments(){let e;if(!this._bufferManager)return;this.flushFramebuffer(!1),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};let t=new Float32Array([this.getRenderHeight(!0)]);if(this._bufferManager.setSubData(this._ubInvertY,4,t),this._bufferManager.setSubData(this._ubDontInvertY,4,t),this._options.antialias){let t={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:eH.E2d,format:this._options.swapChainFormat,usage:eX.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(t),e=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:eH.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new math_color_Color4(0,0,0,1),loadOp:th.Clear,storeOp:tc.Store}]}else e=[{view:void 0,clearValue:new math_color_Color4(0,0,0,1),loadOp:th.Clear,storeOp:tc.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?eK.Depth24PlusStencil8:eK.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);let i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:eH.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:eX.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);let r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:eH.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:th.Clear,depthStoreOp:tc.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?th.Clear:void 0,stencilStoreOp:this.isStencilEnable?tc.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:e,depthStencilAttachment:r}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:eX.RenderAttachment|eX.CopySrc,alphaMode:this.premultipliedAlpha?td.Premultiplied:td.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<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - setSize called -",e,t)),this._initializeMainAttachments(),this.snapshotRendering&&this.snapshotRenderingReset(),!0)}_getShaderProcessor(e){return e===q.WGSL?this._shaderProcessorWGSL:this._shaderProcessor}_getShaderProcessingContext(e){return new WebGPUShaderProcessingContext(e)}applyStates(){this._stencilStateComposer.apply(),this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend)}wipeCaches(e){(!this.preventCacheWipeBetweenFrames||e)&&(this._forceEnableEffect=!0,this._currentIndexBuffer=null,this._currentOverrideVertexBuffers=null,this._cacheRenderPipeline.setBuffers(null,null,null),e&&(this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=515,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters),this._cacheRenderPipeline.setAlphaBlendEnabled(!1),this.setColorWrite(!0)),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}setColorWrite(e){this._colorWriteLocal=e,this._cacheRenderPipeline.setWriteMask(e?15:0)}getColorWrite(){return this._colorWriteLocal}_resetCurrentViewport(e){this._viewportsCurrent[e].x=0,this._viewportsCurrent[e].y=0,this._viewportsCurrent[e].w=0,this._viewportsCurrent[e].h=0}_mustUpdateViewport(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._viewportCached.x,r=this._viewportCached.y,s=this._viewportCached.z,a=this._viewportCached.w,n=this._viewportsCurrent[t].x!==i||this._viewportsCurrent[t].y!==r||this._viewportsCurrent[t].w!==s||this._viewportsCurrent[t].h!==a;return n&&(this._viewportsCurrent[t].x=this._viewportCached.x,this._viewportsCurrent[t].y=this._viewportCached.y,this._viewportsCurrent[t].w=this._viewportCached.z,this._viewportsCurrent[t].h=this._viewportCached.w),n}_applyViewport(e){let t=Math.floor(this._viewportCached.y),i=Math.floor(this._viewportCached.w);this._currentRenderTarget||(t=this.getRenderHeight(!0)-t-i),e.setViewport(Math.floor(this._viewportCached.x),t,Math.floor(this._viewportCached.z),i,0,1),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - viewport applied - (",this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w,") current pass is main pass="+(e===this._mainRenderPassWrapper.renderPass)))}_viewport(e,t,i,r){this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r}_resetCurrentScissor(e){this._scissorsCurrent[e].x=0,this._scissorsCurrent[e].y=0,this._scissorsCurrent[e].w=0,this._scissorsCurrent[e].h=0}_mustUpdateScissor(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._scissorCached.x,r=this._scissorCached.y,s=this._scissorCached.z,a=this._scissorCached.w,n=this._scissorsCurrent[t].x!==i||this._scissorsCurrent[t].y!==r||this._scissorsCurrent[t].w!==s||this._scissorsCurrent[t].h!==a;return n&&(this._scissorsCurrent[t].x=this._scissorCached.x,this._scissorsCurrent[t].y=this._scissorCached.y,this._scissorsCurrent[t].w=this._scissorCached.z,this._scissorsCurrent[t].h=this._scissorCached.w),n}_applyScissor(e){e.setScissorRect(this._scissorCached.x,this._currentRenderTarget?this._scissorCached.y:this.getRenderHeight()-this._scissorCached.w-this._scissorCached.y,this._scissorCached.z,this._scissorCached.w),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - scissor applied - (",this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w,") current pass is main pass="+(e===this._mainRenderPassWrapper.renderPass)))}_scissorIsActive(){return 0!==this._scissorCached.x||0!==this._scissorCached.y||0!==this._scissorCached.z||0!==this._scissorCached.w}enableScissor(e,t,i,r){this._scissorCached.x=e,this._scissorCached.y=t,this._scissorCached.z=i,this._scissorCached.w=r}disableScissor(){this._scissorCached.x=0,this._scissorCached.y=0,this._scissorCached.z=0,this._scissorCached.w=0,this._resetCurrentScissor(0),this._resetCurrentScissor(1)}_resetCurrentStencilRef(e){this._stencilRefsCurrent[e]=-1}_mustUpdateStencilRef(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._stencilStateComposer.funcRef!==this._stencilRefsCurrent[t];return i&&(this._stencilRefsCurrent[t]=this._stencilStateComposer.funcRef),i}_applyStencilRef(e){var t;e.setStencilReference(null!==(t=this._stencilStateComposer.funcRef)&&void 0!==t?t:0)}_resetCurrentColorBlend(e){this._blendColorsCurrent[e][0]=this._blendColorsCurrent[e][1]=this._blendColorsCurrent[e][2]=this._blendColorsCurrent[e][3]=null}_mustUpdateBlendColor(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._alphaState._blendConstants,r=i[0]!==this._blendColorsCurrent[t][0]||i[1]!==this._blendColorsCurrent[t][1]||i[2]!==this._blendColorsCurrent[t][2]||i[3]!==this._blendColorsCurrent[t][3];return r&&(this._blendColorsCurrent[t][0]=i[0],this._blendColorsCurrent[t][1]=i[1],this._blendColorsCurrent[t][2]=i[2],this._blendColorsCurrent[t][3]=i[3]),r}_applyBlendColor(e){e.setBlendConstant(this._alphaState._blendConstants)}clear(e,t,i,r=!1){e&&void 0===e.a&&(e.a=1);let s=this._scissorIsActive();this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - clear called - backBuffer=",t," depth=",i," stencil=",r," scissor is active=",s)),this._currentRenderTarget?s?(this._rttRenderPassWrapper.renderPass||this._startRenderTargetRenderPass(this._currentRenderTarget,!1,t?e:null,i,r),this.compatibilityMode?this._applyScissor(this._currentRenderPass):this._bundleListRenderTarget.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),this._clearFullQuad(t?e:null,i,r)):(this._currentRenderPass&&this._endRenderTargetRenderPass(),this._startRenderTargetRenderPass(this._currentRenderTarget,!0,t?e:null,i,r)):(this._mainRenderPassWrapper.renderPass&&s||this._startMainRenderPass(!s,t?e:null,i,r),s&&(this.compatibilityMode?this._applyScissor(this._currentRenderPass):this._bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),this._clearFullQuad(t?e:null,i,r)))}_clearFullQuad(e,t,i){var r,s,a;let n=this.compatibilityMode?this._getCurrentRenderPass():null,o=this._getCurrentRenderPassIndex(),l=0===o?this._bundleList:this._bundleListRenderTarget;this._clearQuad.setColorFormat(this._colorFormat),this._clearQuad.setDepthStencilFormat(this._depthTextureFormat),this._clearQuad.setMRTAttachments(null!==(r=this._cacheRenderPipeline.mrtAttachments)&&void 0!==r?r:[],null!==(s=this._cacheRenderPipeline.mrtTextureArray)&&void 0!==s?s:[],this._cacheRenderPipeline.mrtTextureCount),this.compatibilityMode?n.setStencilReference(this._clearStencilValue):l.addItem(new WebGPURenderItemStencilRef(this._clearStencilValue));let h=this._clearQuad.clear(n,e,t,i,this.currentSampleCount);this.compatibilityMode?this._applyStencilRef(n):(l.addBundle(h),l.addItem(new WebGPURenderItemStencilRef(null!==(a=this._stencilStateComposer.funcRef)&&void 0!==a?a:0)),this._reportDrawCall())}createVertexBuffer(e,t,i){let r;r=e instanceof Array?new Float32Array(e):e instanceof ArrayBuffer?new Uint8Array(e):e;let s=this._bufferManager.createBuffer(r,ez.Vertex|ez.CopyDst,i);return s}createDynamicVertexBuffer(e,t){return this.createVertexBuffer(e,void 0,t)}createIndexBuffer(e,t,i){let r,s=!0;e instanceof Uint32Array||e instanceof Int32Array?r=e:e instanceof Uint16Array?(r=e,s=!1):e.length>65535?r=new Uint32Array(e):(r=new Uint16Array(e),s=!1);let a=this._bufferManager.createBuffer(r,ez.Index|ez.CopyDst,i);return a.is32Bits=s,a}_createBuffer(e,t,i){let r;r=e instanceof Array?new Float32Array(e):e instanceof ArrayBuffer?new Uint8Array(e):e;let s=0;return 1&t&&(s|=ez.CopySrc),2&t&&(s|=ez.CopyDst),4&t&&(s|=ez.Uniform),8&t&&(s|=ez.Vertex),16&t&&(s|=ez.Index),32&t&&(s|=ez.Storage),this._bufferManager.createBuffer(r,s,i)}bindBuffersDirectly(){throw"Not implemented on WebGPU"}updateAndBindInstancesBuffer(){throw"Not implemented on WebGPU"}bindBuffers(e,t,i,r){this._currentIndexBuffer=t,this._currentOverrideVertexBuffers=null!=r?r:null,this._cacheRenderPipeline.setBuffers(e,t,this._currentOverrideVertexBuffers)}_releaseBuffer(e){return this._bufferManager.releaseBuffer(e)}createEffect(e,t,i,r,s,a,n,o,l,h=q.GLSL){var c;let u=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,d=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,_=this._getGlobalDefines(),p=null!==(c=null!=s?s:t.defines)&&void 0!==c?c:"";_&&(p+="\n"+_);let f=u+"+"+d+"@"+p;if(this._compiledEffects[f]){let e=this._compiledEffects[f];return n&&e.isReady()&&n(e),e}let m=new effect_Effect(e,t,i,r,this,s,a,n,o,l,f,h);return this._compiledEffects[f]=m,m}_compileRawShaderToSpirV(e,t){return this._glslang.compileGLSL(e,t)}_compileShaderToSpirV(e,t,i,r){return this._compileRawShaderToSpirV(r+(i?i+"\n":"")+e,t)}_getWGSLShader(e,t,i){return(i=i?"//"+i.split("\n").join("\n//")+"\n":"")+e}_createPipelineStageDescriptor(e,t,i,r,s){return this._tintWASM&&i===q.GLSL&&(e=this._tintWASM.convertSpirV2WGSL(e,r),t=this._tintWASM.convertSpirV2WGSL(t,s)),{vertexStage:{module:this._device.createShaderModule({code:e}),entryPoint:"main"},fragmentStage:{module:this._device.createShaderModule({code:t}),entryPoint:"main"}}}_compileRawPipelineStageDescriptor(e,t,i){let r=e.indexOf(sv)>=0,s=t.indexOf(sv)>=0,a=i===q.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,n=i===q.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(a,n,i,r,s)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=e.indexOf(sv)>=0,a=t.indexOf(sv)>=0,n="#version 450\n",o=r===q.GLSL?this._compileShaderToSpirV(e,"vertex",i,n):this._getWGSLShader(e,"vertex",i),l=r===q.GLSL?this._compileShaderToSpirV(t,"fragment",i,n):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(o,l,r,s,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){let t=new ShaderCodeInliner(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new WebGPUPipelineContext(e,this)}createMaterialContext(){return new WebGPUMaterialContext}createDrawContext(){return new WebGPUDrawContext(this._bufferManager)}_preparePipelineContext(e,t,i,r,s,a,n,o){let l=e.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(o),console.log(t),console.log(i),console.log("***********************************************")),e.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:a},r?e.stages=this._compileRawPipelineStageDescriptor(t,i,l):e.stages=this._compilePipelineStageDescriptor(t,i,o,l)}getAttributes(e,t){let i=Array(t.length);for(let r=0;r<t.length;r++){let s=t[r],a=e.shaderProcessingContext.availableAttributes[s];void 0!==a&&(i[r]=a)}return i}enableEffect(e){if(!e)return;let t=!0;if(drawWrapper_DrawWrapper.IsWrapper(e)){if(e.effect&&(e.effect!==this._currentEffect||e.materialContext!==this._currentMaterialContext||e.drawContext!==this._currentDrawContext||this._forceEnableEffect)){if(t=e.effect!==this._currentEffect,this._currentEffect=e.effect,this._currentMaterialContext=e.materialContext,this._currentDrawContext=e.drawContext,this._counters.numEnableDrawWrapper++,!this._currentMaterialContext)throw console.error("drawWrapper=",e),"Invalid call to enableEffect: the materialContext property is empty!"}else{if(!e.effect&&this.dbgShowEmptyEnableEffectCalls)throw console.error("drawWrapper=",e),"Invalid call to enableEffect: the effect property is empty!";return}}else t=e!==this._currentEffect,this._currentEffect=e,this._currentMaterialContext=this._defaultMaterialContext,this._currentDrawContext=this._defaultDrawContext,this._counters.numEnableEffects++,this.dbgLogIfNotDrawWrapper&&logger_Logger.Warn(`enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=${e.uniqueId}, effect.name=${e.name}, effect.name.vertex=${e.name.vertex}, effect.name.fragment=${e.name.fragment}`,10);this._stencilStateComposer.stencilMaterial=void 0,this._forceEnableEffect=!t&&!this._forceEnableEffect&&this._forceEnableEffect,t&&(this._currentEffect.onBind&&this._currentEffect.onBind(this._currentEffect),this._currentEffect._onBindObservable&&this._currentEffect._onBindObservable.notifyObservers(this._currentEffect))}_releaseEffect(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],this._deletePipelineContext(e.getPipelineContext()))}releaseEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}_deletePipelineContext(e){e&&e.dispose()}get needPOTTextures(){return!1}_createHardwareTexture(){return new WebGPUHardwareTexture}_releaseTexture(e){let t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),this._textureHelper.releaseTexture(e)}_getRGBABufferInternalSizedFormat(){return 5}updateTextureComparisonFunction(e,t){e._comparisonFunction=t}_createInternalTexture(e,t,i=!0,r=$.Unknown){var s,a,n;let o={};void 0!==t&&"object"==typeof t?(o.generateMipMaps=t.generateMipMaps,o.type=void 0===t.type?0:t.type,o.samplingMode=void 0===t.samplingMode?3:t.samplingMode,o.format=void 0===t.format?5:t.format,o.samples=null!==(s=t.samples)&&void 0!==s?s:1,o.creationFlags=null!==(a=t.creationFlags)&&void 0!==a?a:0,o.useSRGBBuffer=null!==(n=t.useSRGBBuffer)&&void 0!==n&&n,o.label=t.label):(o.generateMipMaps=t,o.type=0,o.samplingMode=3,o.format=5,o.samples=1,o.creationFlags=0,o.useSRGBBuffer=!1),(1!==o.type||this._caps.textureFloatLinearFiltering)&&(2!==o.type||this._caps.textureHalfFloatLinearFiltering)||(o.samplingMode=1),1!==o.type||this._caps.textureFloat||(o.type=0,logger_Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let l=new internalTexture_InternalTexture(this,r),h=e.width||e,c=e.height||e,u=e.layers||0;return l.baseWidth=h,l.baseHeight=c,l.width=h,l.height=c,l.depth=u,l.isReady=!0,l.samples=o.samples,l.generateMipMaps=!!o.generateMipMaps,l.samplingMode=o.samplingMode,l.type=o.type,l.format=o.format,l.is2DArray=u>0,l._cachedWrapU=0,l._cachedWrapV=0,l._useSRGBBuffer=o.useSRGBBuffer,l.label=o.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,h,c,u||1,o.creationFlags),l}createTexture(e,t,i,r,s=3,a=null,n=null,o=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,r,s,a,n,(e,t,i,r,s,a,n,o)=>{var l;if(e.baseWidth=r.width,e.baseHeight=r.height,e.width=r.width,e.height=r.height,e.format=-1!==e.format?e.format:null!=h?h:5,e.type=-1!==e.type?e.type:0,o(e.width,e.height,r,t,e,()=>{}),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)a||n||this._generateMipmaps(e,this._uploadEncoder);else{let t=this._textureHelper.createGPUTextureForInternalTexture(e,r.width,r.height,void 0,_);!WebGPUTextureHelper.IsImageBitmap(r)||(this._textureHelper.updateTexture(r,e,r.width,r.height,e.depth,t.format,0,0,s,!1,0,0),a||n||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()},()=>!1,o,l,h,c,u,d,p)}wrapWebGPUTexture(e){let t=new WebGPUHardwareTexture(e),i=new internalTexture_InternalTexture(this,$.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;if(e.generateMipMaps){let i=null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource;i||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e,e.source===$.RenderTarget||e.source===$.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,r=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===r)return;let s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,s)}_setInternalTexture(e,t,i){if(i=null!=i?i:e,this._currentEffect){let r=this._currentEffect._pipelineContext,s=r.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){let e=i+WebGPUShaderProcessor.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let e=0;e<i.length;e++)this._setTexture(-1,i[e],!0,!1,r+e.toString(),r)}_setTexture(e,t,i=!1,r=!1,s="",a){if(a=null!=a?a:s,this._currentEffect){if(!t)return this._currentMaterialContext.setTexture(s,null),!1;if(t.video)t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let e=null;if((e=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture)&&!e.isMultiview){if(e.isCube&&e._cachedCoordinatesMode!==t.coordinatesMode){e._cachedCoordinatesMode=t.coordinatesMode;let i=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=i,t.wrapV=i}e._cachedWrapU=t.wrapU,e._cachedWrapV=t.wrapV,e.is3D&&(e._cachedWrapR=t.wrapR),this._setAnisotropicLevel(0,e,t.anisotropicFilteringLevel)}this._setInternalTexture(s,e,a)}else this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - _setTexture called with a null _currentEffect! texture=",t));return!0}_setAnisotropicLevel(e,t,i){t._cachedAnisotropicFilteringLevel!==i&&(t._cachedAnisotropicFilteringLevel=Math.min(i,this._caps.maxAnisotropy))}_bindTexture(e,t,i){void 0!==e&&this._setInternalTexture(i,t)}generateMipmaps(e){this._generateMipmaps(e,this._renderTargetEncoder)}_generateMipmaps(e,t){let i=e._hardwareTexture;if(!i)return;t=null!=t?t:this._currentRenderTarget&&!this._currentRenderPass?this._renderTargetEncoder:this._currentRenderPass?this._uploadEncoder:this._renderEncoder;let r=e._hardwareTexture.format,s=WebGPUTextureHelper.ComputeNumMipmapLevels(e.width,e.height);this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - generate mipmaps called - width=",e.width,"height=",e.height,"isCube=",e.isCube)),e.isCube?this._textureHelper.generateCubeMipmaps(i,r,s,t):this._textureHelper.generateMipmaps(i,r,s,0,t)}updateTextureData(e,t,i,r,s,a,n=0,o=0,l=!1){var h;let c=e._hardwareTexture;(null===(h=e._hardwareTexture)||void 0===h?void 0:h.underlyingResource)||(c=this._textureHelper.createGPUTextureForInternalTexture(e));let u=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(u,e,s,a,e.depth,c.format,n,o,e.invertY,!1,i,r),l&&this._generateMipmaps(e,this._renderTargetEncoder)}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,n=0){var o;let l=e._hardwareTexture;(null===(o=e._hardwareTexture)||void 0===o?void 0:o.underlyingResource)||(e.format=t,l=this._textureHelper.createGPUTextureForInternalTexture(e,i,r));let h=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);this._textureHelper.updateTexture(h,e,i,r,e.depth,l.format,a,n,!1,!1,0,0)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,a=!1){var n;let o=Math.round(Math.log(e.width)*Math.LOG2E),l=Math.round(Math.log(e.height)*Math.LOG2E),h=a?e.width:Math.pow(2,Math.max(o-r,0)),c=a?e.height:Math.pow(2,Math.max(l-r,0)),u=e._hardwareTexture;(null===(n=e._hardwareTexture)||void 0===n?void 0:n.underlyingResource)||(u=this._textureHelper.createGPUTextureForInternalTexture(e,h,c));let d=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(d,e,h,c,e.depth,u.format,i,r,e.invertY,!1,0,0)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){this._uploadDataToTextureDirectly(e,t,i,r)}_uploadImageToTexture(e,t,i=0,r=0){var s;let a=e._hardwareTexture;if((null===(s=e._hardwareTexture)||void 0===s?void 0:s.underlyingResource)||(a=this._textureHelper.createGPUTextureForInternalTexture(e)),t instanceof HTMLImageElement)throw"WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!";let n=Math.ceil(e.width/(1<<r)),o=Math.ceil(e.height/(1<<r));this._textureHelper.updateTexture(t,e,n,o,e.depth,a.format,i,r,e.invertY,!1,0,0)}readPixels(e,t,i,r,s=!0,a=!0){let n=this._rttRenderPassWrapper.renderPass?this._rttRenderPassWrapper:this._mainRenderPassWrapper,o=n.colorAttachmentGPUTextures[0];if(!o)return Promise.resolve(new Uint8Array(0));let l=o.underlyingResource,h=o.format;return l?(a&&this.flushFramebuffer(),this._textureHelper.readPixels(l,e,t,i,r,h)):Promise.resolve(new Uint8Array(0))}beginFrame(){super.beginFrame()}endFrame(){if(this._snapshotRendering.endFrame(this._mainRenderPassWrapper.renderPass),this._endMainRenderPass(),this._timestampQuery.endFrame(this._renderEncoder),this.flushFramebuffer(!1),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - counters")),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this._features._collectUbosUpdatedInFrame){if(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){let e=[];for(let t in UniformBuffer._UpdatedUbosInFrame)e.push(t+":"+UniformBuffer._UpdatedUbosInFrame[t]);console.log("frame #"+this._count+" - updated ubos -",e.join(", "))}UniformBuffer._UpdatedUbosInFrame={}}this.countersLastFrame.numEnableEffects=this._counters.numEnableEffects,this.countersLastFrame.numEnableDrawWrapper=this._counters.numEnableDrawWrapper,this.countersLastFrame.numBundleCreationNonCompatMode=this._counters.numBundleCreationNonCompatMode,this.countersLastFrame.numBundleReuseNonCompatMode=this._counters.numBundleReuseNonCompatMode,this._counters.numEnableEffects=0,this._counters.numEnableDrawWrapper=0,this._counters.numBundleCreationNonCompatMode=0,this._counters.numBundleReuseNonCompatMode=0,this._cacheRenderPipeline.endFrame(),this._cacheBindGroups.endFrame(),this._pendingDebugCommands.length=0,super.endFrame(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),this._count<this.dbgVerboseLogsNumFrames&&console.log("%c frame #"+this._count+" - end","background: #ffff00"),this._count<this.dbgVerboseLogsNumFrames&&(this._count++,this._count!==this.dbgVerboseLogsNumFrames&&console.log("%c frame #"+this._count+" - begin","background: #ffff00")))}flushFramebuffer(e=!0){let t=!this._currentRenderPass,i=0;this._currentRenderPass&&this._currentRenderTarget&&(i|=1,this._endRenderTargetRenderPass()),this._mainRenderPassWrapper.renderPass&&(i|=2,this._endMainRenderPass()),this._commandBuffers[0]=this._uploadEncoder.finish(),this._commandBuffers[1]=this._renderTargetEncoder.finish(),this._commandBuffers[2]=this._renderEncoder.finish(),this._device.queue.submit(this._commandBuffers),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._timestampQuery.startFrame(this._uploadEncoder),this._textureHelper.setCommandEncoder(this._uploadEncoder),this._bundleList.reset(),this._bundleListRenderTarget.reset(),e&&(2&i&&this._startMainRenderPass(!1),1&i&&this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1),t&&this._currentRenderTarget&&(this._currentRenderPass=null))}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentRenderTarget}_startRenderTargetRenderPass(e,t,i,r,s){var a,n,o,l,h,c,u,d;let _=e._depthStencilTexture,p=null==_?void 0:_._hardwareTexture,f=null==p?void 0:p.underlyingResource,m=null==p?void 0:p.getMSAATexture(),g=null==f?void 0:f.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),v=null==m?void 0:m.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),x=!!p&&WebGPUTextureHelper.HasStencilAspect(p.format),b=[];this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual(),i&&(sx.r=255*i.r,sx.g=255*i.g,sx.b=255*i.b,sx.a=255*i.a);let T=t&&i,S=t&&r,C=t&&s;if(e._attachments&&e.isMulti){this._mrtAttachments&&0!==this._mrtAttachments.length||(this._mrtAttachments=e._defaultAttachments);for(let t=0;t<this._mrtAttachments.length;++t){let r=this._mrtAttachments[t],s=e.textures[t],h=null==s?void 0:s._hardwareTexture,c=null==h?void 0:h.underlyingResource;if(h&&c){let u=h.getMSAATexture(t),d=null!==(n=null===(a=e.layerIndices)||void 0===a?void 0:a[t])&&void 0!==n?n:0,_=null!==(l=null===(o=e.faceIndices)||void 0===o?void 0:o[t])&&void 0!==l?l:0,p=Object.assign(Object.assign({},this._rttRenderPassWrapper.colorAttachmentViewDescriptor),{format:h.format,baseArrayLayer:s.isCube?6*d+_:d}),f=Object.assign(Object.assign({},this._rttRenderPassWrapper.colorAttachmentViewDescriptor),{format:h.format,baseArrayLayer:0}),m=7===s.type||5===s.type,g=c.createView(p),v=null==u?void 0:u.createView(f);b.push({view:v||g,resolveTarget:u?g:void 0,clearValue:0!==r&&T?m?sx:i:void 0,loadOp:0!==r&&T?th.Clear:th.Load,storeOp:tc.Store})}}this._cacheRenderPipeline.setMRT(e.textures,this._mrtAttachments.length),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)}else{let t=e.texture;if(t){let e=t._hardwareTexture,r=e.underlyingResource,s=e.getMSAATexture(),a=r.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),n=null==s?void 0:s.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),o=7===t.type||5===t.type;b.push({view:n||a,resolveTarget:s?a:void 0,clearValue:T?o?sx:i:void 0,loadOp:T?th.Clear:th.Load,storeOp:tc.Store})}else b.push(null)}if(null===(h=this._debugPushGroup)||void 0===h||h.call(this,"render target pass",1),this._rttRenderPassWrapper.renderPassDescriptor={label:(null!==(c=e.label)&&void 0!==c?c:"RTT")+"RenderPass",colorAttachments:b,depthStencilAttachment:_&&f?{view:v||g,depthClearValue:S?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,depthLoadOp:S?th.Clear:th.Load,depthStoreOp:tc.Store,stencilClearValue:e._depthStencilTextureWithStencil&&C?this._clearStencilValue:void 0,stencilLoadOp:x?e._depthStencilTextureWithStencil&&C?th.Clear:th.Load:void 0,stencilStoreOp:x?tc.Store:void 0}:void 0,occlusionQuerySet:(null===(u=this._occlusionQuery)||void 0===u?void 0:u.hasQueries)?this._occlusionQuery.querySet:void 0},this._rttRenderPassWrapper.renderPass=this._renderTargetEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){let t=e.texture;console.log("frame #"+this._count+" - render target begin pass - internalTexture.uniqueId=",t.uniqueId,"width=",t.width,"height=",t.height,this._rttRenderPassWrapper.renderPassDescriptor)}this._currentRenderPass=this._rttRenderPassWrapper.renderPass,null===(d=this._debugFlushPendingCommands)||void 0===d||d.call(this),this._resetCurrentViewport(1),this._resetCurrentScissor(1),this._resetCurrentStencilRef(1),this._resetCurrentColorBlend(1),p&&WebGPUTextureHelper.HasStencilAspect(p.format)||(this._stencilStateComposer.enabled=!1)}_endRenderTargetRenderPass(){var e,t,i,r;if(this._currentRenderPass){let s=null===(e=this._currentRenderTarget.texture)||void 0===e?void 0:e._hardwareTexture;!s||this._snapshotRendering.endRenderTargetPass(this._currentRenderPass,s)||this.compatibilityMode||(this._bundleListRenderTarget.run(this._currentRenderPass),this._bundleListRenderTarget.reset()),this._currentRenderPass.end(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - render target end pass - internalTexture.uniqueId=",null===(i=null===(t=this._currentRenderTarget)||void 0===t?void 0:t.texture)||void 0===i?void 0:i.uniqueId)),null===(r=this._debugPopGroup)||void 0===r||r.call(this,1),this._resetCurrentViewport(1),this._viewport(0,0,0,0),this._resetCurrentScissor(1),this._resetCurrentStencilRef(1),this._resetCurrentColorBlend(1),this._currentRenderPass=null,this._rttRenderPassWrapper.reset()}}_getCurrentRenderPass(){return this._currentRenderTarget&&!this._currentRenderPass?this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1):this._currentRenderPass||this._startMainRenderPass(!1),this._currentRenderPass}_getCurrentRenderPassIndex(){return null===this._currentRenderPass?-1:this._currentRenderPass===this._mainRenderPassWrapper.renderPass?0:1}_startMainRenderPass(e,t,i,r){var s,a,n;this._mainRenderPassWrapper.renderPass&&this.flushFramebuffer(!1),this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();let o=e&&t,l=e&&i,h=e&&r;this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue=o?t:void 0,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp=o?th.Clear:th.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue=l?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp=l?th.Clear:th.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue=h?this._clearStencilValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp=this.isStencilEnable?h?th.Clear:th.Load:void 0,this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet=(null===(s=this._occlusionQuery)||void 0===s?void 0:s.hasQueries)?this._occlusionQuery.querySet:void 0;let c=this._context.getCurrentTexture();this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(c),this._options.antialias?(sm.format=c.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget=c.createView(sm)):(sg.format=c.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view=c.createView(sg)),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - main begin pass - texture width="+this._mainTextureExtends.width," height="+this._mainTextureExtends.height,this._mainRenderPassWrapper.renderPassDescriptor)),null===(a=this._debugPushGroup)||void 0===a||a.call(this,"main pass",0),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor),this._mainRenderPassWrapper.renderPass=this._currentRenderPass,null===(n=this._debugFlushPendingCommands)||void 0===n||n.call(this),this._resetCurrentViewport(0),this._resetCurrentScissor(0),this._resetCurrentStencilRef(0),this._resetCurrentColorBlend(0),this._isStencilEnable||(this._stencilStateComposer.enabled=!1)}_endMainRenderPass(){var e;null!==this._mainRenderPassWrapper.renderPass&&(this._snapshotRendering.endMainRenderPass(),this.compatibilityMode||this._snapshotRendering.play||(this._bundleList.run(this._mainRenderPassWrapper.renderPass),this._bundleList.reset()),this._mainRenderPassWrapper.renderPass.end(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - main end pass")),null===(e=this._debugPopGroup)||void 0===e||e.call(this,0),this._resetCurrentViewport(0),this._resetCurrentScissor(0),this._resetCurrentStencilRef(0),this._resetCurrentColorBlend(0),this._mainRenderPassWrapper.renderPass===this._currentRenderPass&&(this._currentRenderPass=null),this._mainRenderPassWrapper.reset(!1))}bindFramebuffer(e,t=0,i,r,s,a=0,n=0){var o,l;let h=null===(o=e.texture)||void 0===o?void 0:o._hardwareTexture;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,h&&(h._currentLayer=e.isCube?6*n+t:n),this._rttRenderPassWrapper.colorAttachmentGPUTextures[0]=h,this._rttRenderPassWrapper.depthTextureFormat=this._currentRenderTarget._depthStencilTexture?WebGPUTextureHelper.GetWebGPUTextureFormat(-1,this._currentRenderTarget._depthStencilTexture.format):void 0,this._setDepthTextureFormat(this._rttRenderPassWrapper),this._setColorFormat(this._rttRenderPassWrapper),this._rttRenderPassWrapper.colorAttachmentViewDescriptor={format:this._colorFormat,dimension:eY.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?6*n+t:n,baseMipLevel:a,arrayLayerCount:1,aspect:ej.All},this._rttRenderPassWrapper.depthAttachmentViewDescriptor={format:this._depthTextureFormat,dimension:eY.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?6*n+t:n,baseMipLevel:0,arrayLayerCount:1,aspect:ej.All},this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - bindFramebuffer called - internalTexture.uniqueId=",null===(l=e.texture)||void 0===l?void 0:l.uniqueId,"face=",t,"lodLevel=",a,"layer=",n,this._rttRenderPassWrapper.colorAttachmentViewDescriptor,this._rttRenderPassWrapper.depthAttachmentViewDescriptor)),this._currentRenderPass=null,this.snapshotRendering&&1===this.snapshotRenderingMode&&this._getCurrentRenderPass(),this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,r):(!i&&(i=e.width,a&&(i/=Math.pow(2,a))),!r&&(r=e.height,a&&(r/=Math.pow(2,a))),this._viewport(0,0,i,r)),this.wipeCaches()}unBindFramebuffer(e,t=!1,i){var r,s;let a=this._currentRenderTarget;this._currentRenderTarget=null,i&&i(),this._currentRenderTarget=a,this._currentRenderPass&&this._currentRenderPass!==this._mainRenderPassWrapper.renderPass&&this._endRenderTargetRenderPass(),(null===(r=e.texture)||void 0===r?void 0:r.generateMipMaps)&&!t&&!e.isCube&&this._generateMipmaps(e.texture),this._currentRenderTarget=null,this._onAfterUnbindFrameBufferObservable.notifyObservers(this),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - unBindFramebuffer called - internalTexture.uniqueId=",null===(s=e.texture)||void 0===s?void 0:s.uniqueId)),this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments),this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):(this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)),this._currentRenderPass&&this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_setColorFormat(e){var t,i;let r=null!==(i=null===(t=e.colorAttachmentGPUTextures[0])||void 0===t?void 0:t.format)&&void 0!==i?i:null;this._cacheRenderPipeline.setColorFormat(r),this._colorFormat!==r&&(this._colorFormat=r)}_setDepthTextureFormat(e){this._cacheRenderPipeline.setDepthStencilFormat(e.depthTextureFormat),this._depthTextureFormat!==e.depthTextureFormat&&(this._depthTextureFormat=e.depthTextureFormat)}setDitheringState(){}setRasterizerState(){}setState(e,t=0,i,r=!1,s,a,n=0){var o,l;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);let h=null===(l=null!==(o=this.cullBackFaces)&&void 0!==o?o:s)||void 0===l||l?1:2;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(n);let c=r?this._currentRenderTarget?1:2:this._currentRenderTarget?2:1;(this._depthCullingState.frontFace!==c||i)&&(this._depthCullingState.frontFace=c),this._stencilStateComposer.stencilMaterial=a}_applyRenderPassChanges(e,t){var i;let r=this._mustUpdateViewport(e),s=this._mustUpdateScissor(e),a=!!this._stencilStateComposer.enabled&&this._mustUpdateStencilRef(e),n=!!this._alphaState.alphaBlend&&this._mustUpdateBlendColor(e);t?(r&&t.addItem(new WebGPURenderItemViewport(this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w)),s&&t.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),a&&t.addItem(new WebGPURenderItemStencilRef(null!==(i=this._stencilStateComposer.funcRef)&&void 0!==i?i:0)),n&&t.addItem(new WebGPURenderItemBlendColor(this._alphaState._blendConstants.slice()))):(r&&this._applyViewport(e),s&&this._applyScissor(e),a&&this._applyStencilRef(e),n&&this._applyBlendColor(e))}_draw(e,t,i,r,s){var a;let n=this._getCurrentRenderPass(),o=this._getCurrentRenderPassIndex(),l=0===o?this._bundleList:this._bundleListRenderTarget;this.applyStates();let h=this._currentEffect._pipelineContext;if(this.bindUniformBufferBase(this._currentRenderTarget?this._ubInvertY:this._ubDontInvertY,0,WebGPUShaderProcessor.InternalsUBOName),h.uniformBuffer&&(h.uniformBuffer.update(),this.bindUniformBufferBase(h.uniformBuffer.getBuffer(),0,WebGPUShaderProcessor.LeftOvertUBOName)),this._snapshotRendering.play){this._reportDrawCall();return}!this.compatibilityMode&&(this._currentDrawContext.isDirty(this._currentMaterialContext.updateId)||this._currentMaterialContext.isDirty||this._currentMaterialContext.forceBindGroupCreation)&&(this._currentDrawContext.fastBundle=void 0);let c=!this.compatibilityMode&&this._currentDrawContext.fastBundle,u=n;if(c||this._snapshotRendering.record){if(this._applyRenderPassChanges(n,l),!this._snapshotRendering.record){this._counters.numBundleReuseNonCompatMode++,this._currentDrawContext.indirectDrawBuffer&&this._currentDrawContext.setIndirectData(r,s||1,i),l.addBundle(this._currentDrawContext.fastBundle),this._reportDrawCall();return}u=l.getBundleEncoder(this._cacheRenderPipeline.colorFormats,this._depthTextureFormat,this.currentSampleCount),l.numDrawCalls++}let d=0;if(!this._caps.textureFloatLinearFiltering&&this._currentMaterialContext.hasFloatTextures){let e=1;for(let t=0;t<h.shaderProcessingContext.textureNames.length;++t){let i=h.shaderProcessingContext.textureNames[t],r=null===(a=this._currentMaterialContext.textures[i])||void 0===a?void 0:a.texture;(null==r?void 0:r.type)===1&&(d|=e),e<<=1}}this._currentMaterialContext.textureState=d;let _=this._cacheRenderPipeline.getRenderPipeline(t,this._currentEffect,this.currentSampleCount,d),p=this._cacheBindGroups.getBindGroups(h,this._currentDrawContext,this._currentMaterialContext);this._snapshotRendering.record||(this._applyRenderPassChanges(n,this.compatibilityMode?null:l),this.compatibilityMode||(this._counters.numBundleCreationNonCompatMode++,u=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:this.currentSampleCount}))),u.setPipeline(_),this._currentIndexBuffer&&u.setIndexBuffer(this._currentIndexBuffer.underlyingResource,this._currentIndexBuffer.is32Bits?ts.Uint32:ts.Uint16,0);let f=this._cacheRenderPipeline.vertexBuffers;for(let e=0;e<f.length;e++){let t=f[e],i=t.effectiveBuffer;i&&u.setVertexBuffer(e,i.underlyingResource,t._validOffsetRange?0:t.byteOffset)}for(let e=0;e<p.length;e++)u.setBindGroup(e,p[e]);let m=!this.compatibilityMode&&!this._snapshotRendering.record;m&&this._currentDrawContext.indirectDrawBuffer?(this._currentDrawContext.setIndirectData(r,s||1,i),0===e?u.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer,0):u.drawIndirect(this._currentDrawContext.indirectDrawBuffer,0)):0===e?u.drawIndexed(r,s||1,i,0,0):u.draw(r,s||1,i,0),m&&(this._currentDrawContext.fastBundle=u.finish(),l.addBundle(this._currentDrawContext.fastBundle)),this._reportDrawCall()}drawElementsType(e,t,i,r=1){this._draw(0,e,t,i,r)}drawArraysType(e,t,i,r=1){this._currentIndexBuffer=null,this._draw(1,e,t,i,r)}dispose(){var e,t;this._isDisposed=!0,null===(e=this._mainTexture)||void 0===e||e.destroy(),null===(t=this._depthTexture)||void 0===t||t.destroy(),this._device.destroy(),super.dispose()}getRenderWidth(e=!1){var t,i;return!e&&this._currentRenderTarget?this._currentRenderTarget.width:null!==(i=null===(t=this._renderingCanvas)||void 0===t?void 0:t.width)&&void 0!==i?i:0}getRenderHeight(e=!1){var t,i;return!e&&this._currentRenderTarget?this._currentRenderTarget.height:null!==(i=null===(t=this._renderingCanvas)||void 0===t?void 0:t.height)&&void 0!==i?i:0}getError(){return 0}bindSamplers(){}_bindTextureDirectly(){return!1}areAllEffectsReady(){return!0}_executeWhenRenderingStateIsCompiled(e,t){t()}_isRenderingStateCompiled(){return!0}_getUnpackAlignement(){return 1}_unpackFlipY(){}_bindUnboundFramebuffer(){throw"_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead"}_getSamplingParameters(){throw"_getSamplingParameters is not available in WebGPU"}getUniforms(){return[]}setIntArray(){return!1}setIntArray2(){return!1}setIntArray3(){return!1}setIntArray4(){return!1}setArray(){return!1}setArray2(){return!1}setArray3(){return!1}setArray4(){return!1}setMatrices(){return!1}setMatrix3x3(){return!1}setMatrix2x2(){return!1}setFloat(){return!1}setFloat2(){return!1}setFloat3(){return!1}setFloat4(){return!1}};webgpuEngine_WebGPUEngine._GLSLslangDefaultOptions={jsPath:`${tools_Tools._DefaultCdnUrl}/glslang/glslang.js`,wasmPath:`${tools_Tools._DefaultCdnUrl}/glslang/glslang.wasm`},webgpuEngine_WebGPUEngine.UseTWGSL=!0,webgpuEngine_WebGPUEngine.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e&&(0===e&&!this._alphaState.alphaBlend||0!==e&&this._alphaState.alphaBlend)){if(!t){let t=0===e;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}return}switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0}t||(this.setDepthWrite(e===engine_Engine.ALPHA_DISABLE),this._cacheRenderPipeline.setDepthWriteEnabled(e===engine_Engine.ALPHA_DISABLE)),this._alphaMode=e,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)},webgpuEngine_WebGPUEngine.prototype.setAlphaEquation=function(e){engine_Engine.prototype.setAlphaEquation.call(this,e),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};let WebGPUComputeContext=class WebGPUComputeContext{getBindGroups(e,t,i){if(!i)throw Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(0===this._bindGroups.length){let r=this._bindGroupEntries.length>0;for(let t in e){let s=e[t],a=i[t],n=a.group,o=a.binding,l=s.type,h=s.object,c=s.indexInGroupEntries,u=this._bindGroupEntries[n];switch(u||(u=this._bindGroupEntries[n]=[]),l){case eF.Sampler:void 0!==c&&r?u[c].resource=this._cacheSampler.getSampler(h):(s.indexInGroupEntries=u.length,u.push({binding:o,resource:this._cacheSampler.getSampler(h)}));break;case eF.Texture:case eF.TextureWithoutSampler:{let e=h._texture._hardwareTexture;void 0!==c&&r?(l===eF.Texture&&(u[c++].resource=this._cacheSampler.getSampler(h._texture)),u[c].resource=e.view):(s.indexInGroupEntries=u.length,l===eF.Texture&&u.push({binding:o-1,resource:this._cacheSampler.getSampler(h._texture)}),u.push({binding:o,resource:e.view}));break}case eF.StorageTexture:{let e=h._texture._hardwareTexture;(e.textureAdditionalUsages&eX.StorageBinding)==0&&logger_Logger.Error(`computeDispatch: The texture (name=${h.name}, uniqueId=${h.uniqueId}) is not a storage texture!`,50),void 0!==c&&r?u[c].resource=e.viewForWriting:(s.indexInGroupEntries=u.length,u.push({binding:o,resource:e.viewForWriting}));break}case eF.ExternalTexture:{let e=h.underlyingResource;void 0!==c&&r?u[c].resource=this._device.importExternalTexture({source:e}):(s.indexInGroupEntries=u.length,u.push({binding:o,resource:this._device.importExternalTexture({source:e})}));break}case eF.UniformBuffer:case eF.StorageBuffer:{let e=(eF.UniformBuffer,h),t=e.getBuffer(),i=t.underlyingResource;void 0!==c&&r?(u[c].resource.buffer=i,u[c].resource.size=t.capacity):(s.indexInGroupEntries=u.length,u.push({binding:o,resource:{buffer:i,offset:0,size:t.capacity}}))}}}for(let e=0;e<this._bindGroupEntries.length;++e){let i=this._bindGroupEntries[e];if(!i){this._bindGroups[e]=void 0;continue}this._bindGroups[e]=this._device.createBindGroup({layout:t.getBindGroupLayout(e),entries:i})}this._bindGroups.length=this._bindGroupEntries.length}return this._bindGroups}constructor(e,t){this._device=e,this._cacheSampler=t,this.uniqueId=WebGPUComputeContext._Counter++,this._bindGroupEntries=[],this.clear()}clear(){this._bindGroups=[]}};WebGPUComputeContext._Counter=0;let WebGPUComputePipelineContext=class WebGPUComputePipelineContext{get isAsync(){return!1}get isReady(){return!!this.stage}constructor(e){this._name="unnamed",this.engine=e}_getComputeShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.compute}dispose(){}};webgpuEngine_WebGPUEngine.prototype.createComputeContext=function(){return new WebGPUComputeContext(this._device,this._cacheSampler)},webgpuEngine_WebGPUEngine.prototype.createComputeEffect=function(e,t){let i=e.computeElement||e.compute||e.computeToken||e.computeSource||e,r=i+"@"+t.defines;if(this._compiledComputeEffects[r]){let e=this._compiledComputeEffects[r];return t.onCompiled&&e.isReady()&&t.onCompiled(e),e}let s=new ComputeEffect(e,t,this,r);return this._compiledComputeEffects[r]=s,s},webgpuEngine_WebGPUEngine.prototype.createComputePipelineContext=function(){return new WebGPUComputePipelineContext(this)},webgpuEngine_WebGPUEngine.prototype.areAllComputeEffectsReady=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e];if(!t.isReady())return!1}return!0},webgpuEngine_WebGPUEngine.prototype.computeDispatch=function(e,t,i,r,s,a,n){if(this._currentRenderTarget){this._onAfterUnbindFrameBufferObservable.addOnce(()=>{this.computeDispatch(e,t,i,r,s,a,n)});return}let o=e._pipelineContext;o.computePipeline||(o.computePipeline=this._device.createComputePipeline({layout:e6.Auto,compute:o.stage}));let l=this._renderTargetEncoder,h=l.beginComputePass();h.setPipeline(o.computePipeline);let c=t.getBindGroups(i,o.computePipeline,n);for(let e=0;e<c.length;++e){let t=c[e];t&&h.setBindGroup(e,t)}h.dispatchWorkgroups(r,s,a),h.end()},webgpuEngine_WebGPUEngine.prototype.releaseComputeEffects=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},webgpuEngine_WebGPUEngine.prototype._prepareComputePipelineContext=function(e,t,i,r,s){this.dbgShowShaderCode&&(console.log(r),console.log(t)),e.sources={compute:t,rawCompute:i},e.stage=this._createComputePipelineStageDescriptor(t,r,s)},webgpuEngine_WebGPUEngine.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},webgpuEngine_WebGPUEngine.prototype._rebuildComputeEffects=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},webgpuEngine_WebGPUEngine.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},webgpuEngine_WebGPUEngine.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},webgpuEngine_WebGPUEngine.prototype._createDepthStencilCubeTexture=function(e,t){let i=new internalTexture_InternalTexture(this,$.DepthStencil);i.isCube=!0;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1},t);return i.format=r.generateStencil?13:14,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},webgpuEngine_WebGPUEngine.prototype.createCubeTexture=function(e,t,i,r,s=null,a=null,n,o=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(e,t,i,!!r,s,a,n,o,l,h,c,u,null,(e,t)=>{let i=t[0].width;this._setCubeMapTextureParams(e,!r),e.format=null!=n?n:-1;let a=this._textureHelper.createGPUTextureForInternalTexture(e,i,i);this._textureHelper.updateCubeTextures(t,a.underlyingResource,i,i,a.format,!1,!1,0,0),r||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},!!d)},webgpuEngine_WebGPUEngine.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},webgpuEngine_WebGPUEngine.prototype._debugPushGroup=function(e,t){if(this._options.enableGPUDebugMarkers){if(0===t||1===t){let i=0===t?this._renderEncoder:this._renderTargetEncoder;i.pushDebugGroup(e)}else this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e])}},webgpuEngine_WebGPUEngine.prototype._debugPopGroup=function(e){if(this._options.enableGPUDebugMarkers){if(0===e||1===e){let t=0===e?this._renderEncoder:this._renderTargetEncoder;t.popDebugGroup()}else this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null])}},webgpuEngine_WebGPUEngine.prototype._debugInsertMarker=function(e,t){if(this._options.enableGPUDebugMarkers){if(0===t||1===t){let i=0===t?this._renderEncoder:this._renderTargetEncoder;i.insertDebugMarker(e)}else this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e])}},webgpuEngine_WebGPUEngine.prototype._debugFlushPendingCommands=function(){for(let e=0;e<this._pendingDebugCommands.length;++e){let[t,i]=this._pendingDebugCommands[e];switch(t){case"push":this._debugPushGroup(i);break;case"pop":this._debugPopGroup();break;case"insert":this._debugInsertMarker(i)}}this._pendingDebugCommands.length=0},webgpuEngine_WebGPUEngine.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let r;r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._bufferManager.setSubData(e,i,r)},webgpuEngine_WebGPUEngine.prototype.updateDynamicVertexBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(e,i,s,0,r)},webgpuEngine_WebGPUEngine.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,a,n){var o;if(!e)return;let l=t.width,h=t.height,c=e._hardwareTexture;(null===(o=e._hardwareTexture)||void 0===o?void 0:o.underlyingResource)||(c=this._textureHelper.createGPUTextureForInternalTexture(e,l,h)),this._textureHelper.updateTexture(t,e,l,h,e.depth,c.format,0,0,i,r,0,0,n),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0};let WebGPUExternalTexture=class WebGPUExternalTexture extends ExternalTexture{constructor(e){super(e)}};function engine_rawTexture_convertRGBtoRGBATextureData(e,t,i,r){let s;let a=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),a=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r<t;r++)for(let n=0;n<i;n++){let i=(n*t+r)*3,o=(n*t+r)*4;s[o+0]=e[i+0],s[o+1]=e[i+1],s[o+2]=e[i+2],s[o+3]=a}return s}effect_Effect.prototype.setExternalTexture=function(e,t){this._engine.setExternalTexture(e,t)},webgpuEngine_WebGPUEngine.prototype.createExternalTexture=function(e){let t=new WebGPUExternalTexture(e);return t},webgpuEngine_WebGPUEngine.prototype.setExternalTexture=function(e,t){if(!t){this._currentMaterialContext.setTexture(e,null);return}this._setInternalTexture(e,t)},webgpuEngine_WebGPUEngine.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t=!1,i){i&&i();let r=e._attachments,s=r.length;this._currentRenderPass&&this._currentRenderPass!==this._mainRenderPassWrapper.renderPass&&this._endRenderTargetRenderPass();for(let i=0;i<s;i++){let r=e.textures[i];!r.generateMipMaps||t||r.isCube||this._generateMipmaps(r)}this._currentRenderTarget=null,this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments),this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)},webgpuEngine_WebGPUEngine.prototype.createMultipleRenderTarget=function(e,t,i){var r,s;let a=!1,n=!0,o=!1,l=!1,h=15,c=1,u=[],d=[],_=[],p=[],f=[],m=[],g=[],v=[],x=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(a=void 0!==t.generateMipMaps&&t.generateMipMaps,n=void 0===t.generateDepthBuffer||t.generateDepthBuffer,o=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,l=void 0!==t.generateDepthTexture&&t.generateDepthTexture,c=t.textureCount||1,h=null!==(r=t.depthTextureFormat)&&void 0!==r?r:15,t.types&&(u=t.types),t.samplingModes&&(d=t.samplingModes),t.useSRGBBuffers&&(_=t.useSRGBBuffers),t.formats&&(p=t.formats),t.targetTypes&&(f=t.targetTypes),t.faceIndex&&(m=t.faceIndex),t.layerIndex&&(g=t.layerIndex),t.layerCounts&&(v=t.layerCounts));let b=e.width||e,T=e.height||e,S=null;(n||o||l)&&(l||(h=n&&o?13:n?14:19),S=x.createDepthStencilTexture(0,!1,o,1,h));let C=[],E=[],y=[];x._generateDepthBuffer=n,x._generateStencilBuffer=o,x._attachments=E,x._defaultAttachments=y;for(let e=0;e<c;e++){let t=d[e]||3,r=u[e]||0,n=p[e]||5,o=(_[e]||!1)&&this._caps.supportSRGBBuffers,l=f[e]||3553,h=null!==(s=v[e])&&void 0!==s?s:1;if((1!==r||this._caps.textureFloatLinearFiltering)&&(2!==r||this._caps.textureHalfFloatLinearFiltering)||(t=1),1!==r||this._caps.textureFloat||(r=0,logger_Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),E.push(e+1),y.push(i?e+1:0===e?1:0),-1===l)continue;let c=new internalTexture_InternalTexture(this,$.MultiRenderTarget);switch(C[e]=c,l){case 34067:c.isCube=!0;break;case 32879:c.is3D=!0,c.baseDepth=c.depth=h;break;case 35866:c.is2DArray=!0,c.baseDepth=c.depth=h}c.baseWidth=b,c.baseHeight=T,c.width=b,c.height=T,c.isReady=!0,c.samples=1,c.generateMipMaps=a,c.samplingMode=t,c.type=r,c._cachedWrapU=0,c._cachedWrapV=0,c._useSRGBBuffer=o,c.format=n,this._internalTexturesCache.push(c),this._textureHelper.createGPUTextureForInternalTexture(c)}return S&&(S.incrementReferences(),C[c]=S,this._internalTexturesCache.push(S)),x.setTextures(C),x.setLayerAndFaceIndices(g,m),x},webgpuEngine_WebGPUEngine.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(!e||!e.textures||e.textures[0].samples===t)return t;let i=e.textures.length;if(0===i)return 1;t=Math.min(t,this.getCaps().maxMSAASamples);for(let t=0;t<i;++t){let i=e.textures[t],r=i._hardwareTexture;null==r||r.releaseMSAATexture()}let r=e._depthStencilTexture===e.textures[i-1];for(let s=0;s<i;++s){let a=e.textures[s];this._textureHelper.createMSAATexture(a,t,!1,s===i-1&&r?0:s),a.samples=t}return e._depthStencilTexture&&!r&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),t},webgpuEngine_WebGPUEngine.prototype.bindAttachments=function(e){0!==e.length&&this._currentRenderTarget&&(this._mrtAttachments=e,this._currentRenderPass&&this._cacheRenderPipeline.setMRTAttachments(e))},webgpuEngine_WebGPUEngine.prototype.buildTextureLayout=function(e){let t=[];for(let i=0;i<e.length;i++)e[i]?t.push(i+1):t.push(0);return t},webgpuEngine_WebGPUEngine.prototype.restoreSingleAttachment=function(){},webgpuEngine_WebGPUEngine.prototype.restoreSingleAttachmentForRenderTarget=function(){},webgpuEngine_WebGPUEngine.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter},webgpuEngine_WebGPUEngine.prototype.captureGPUFrameTime=function(e){this._timestampQuery.enable=e&&!!this._caps.timerQuery},webgpuEngine_WebGPUEngine.prototype.createQuery=function(){return this._occlusionQuery.createQuery()},webgpuEngine_WebGPUEngine.prototype.deleteQuery=function(e){return this._occlusionQuery.deleteQuery(e),this},webgpuEngine_WebGPUEngine.prototype.isQueryResultAvailable=function(e){return this._occlusionQuery.isQueryResultAvailable(e)},webgpuEngine_WebGPUEngine.prototype.getQueryResult=function(e){return this._occlusionQuery.getQueryResult(e)},webgpuEngine_WebGPUEngine.prototype.beginOcclusionQuery=function(e,t){var i;if(this.compatibilityMode){if(this._occlusionQuery.canBeginQuery(t))return null===(i=this._currentRenderPass)||void 0===i||i.beginOcclusionQuery(t),!0}else{let e=this._getCurrentRenderPassIndex(),i=0===e?this._bundleList:this._bundleListRenderTarget;return i.addItem(new WebGPURenderItemBeginOcclusionQuery(t)),!0}return!1},webgpuEngine_WebGPUEngine.prototype.endOcclusionQuery=function(){var e;if(this.compatibilityMode)null===(e=this._currentRenderPass)||void 0===e||e.endOcclusionQuery();else{let e=this._getCurrentRenderPassIndex(),t=0===e?this._bundleList:this._bundleListRenderTarget;t.addItem(new WebGPURenderItemEndOcclusionQuery)}return this},webgpuEngine_WebGPUEngine.prototype.createRawTexture=function(e,t,i,r,s,a,n,o=null,l=0,h=0,c=!1){let u=new internalTexture_InternalTexture(this,$.Raw);return u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=r,u.generateMipMaps=s,u.samplingMode=n,u.invertY=a,u._compression=o,u.type=l,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(u,t,i,void 0,h),this.updateRawTexture(u,e,r,a,o,l,c),this._internalTexturesCache.push(u),u},webgpuEngine_WebGPUEngine.prototype.updateRawTexture=function(e,t,i,r,s=null,a=0,n=!1){if(e){if(this._doNotHandleContextLost||(e._bufferView=t,e.invertY=r,e._compression=s,e._useSRGBBuffer=n),t){let s=e._hardwareTexture;4===i&&(t=engine_rawTexture_convertRGBtoRGBATextureData(t,e.width,e.height,a));let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(n,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0}},webgpuEngine_WebGPUEngine.prototype.createRawCubeTexture=function(e,t,i,r,s,a,n,o=null){let l=new internalTexture_InternalTexture(this,$.CubeRaw);return 1!==r||this._caps.textureFloatLinearFiltering?2!==r||this._caps.textureHalfFloatLinearFiltering?1!==r||this._caps.textureFloatRender?2!==r||this._caps.colorBufferFloat||(s=!1,logger_Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(s=!1,logger_Logger.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(s=!1,n=1,logger_Logger.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(s=!1,n=1,logger_Logger.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")),l.isCube=!0,l.format=4===i?5:i,l.type=r,l.generateMipMaps=s,l.width=t,l.height=t,l.samplingMode=n,this._doNotHandleContextLost||(l._bufferViewArray=e),l.invertY=a,l._compression=o,l._cachedWrapU=0,l._cachedWrapV=0,this._textureHelper.createGPUTextureForInternalTexture(l),e&&this.updateRawCubeTexture(l,e,i,r,a,o),l.isReady=!0,l},webgpuEngine_WebGPUEngine.prototype.updateRawCubeTexture=function(e,t,i,r,s,a=null){e._bufferViewArray=t,e.invertY=s,e._compression=a;let n=e._hardwareTexture,o=4===i,l=[];for(let i=0;i<t.length;++i){let s=t[i];o&&(s=engine_rawTexture_convertRGBtoRGBATextureData(t[i],e.width,e.height,r)),l.push(new Uint8Array(s.buffer,s.byteOffset,s.byteLength))}this._textureHelper.updateCubeTextures(l,n.underlyingResource,e.width,e.height,n.format,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0},webgpuEngine_WebGPUEngine.prototype.createRawCubeTextureFromUrl=function(e,t,i,r,s,a,n,o,l=null,h=null,c=3,u=!1){let d=this.createRawCubeTexture(null,i,r,s,!a,u,c,null);null==t||t.addPendingData(d),d.url=e,this._internalTexturesCache.push(d);let internalCallback=e=>{let i=d.width,a=n(e);if(!a)return;let h=[0,2,4,1,3,5];if(o){let e=4===r,t=o(a),n=d._hardwareTexture,l=[0,1,2,3,4,5];for(let r=0;r<t.length;r++){let a=i>>r,o=[];for(let i=0;i<6;i++){let n=t[r][l[i]];e&&(n=engine_rawTexture_convertRGBtoRGBATextureData(n,a,a,s)),o.push(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}this._textureHelper.updateCubeTextures(o,n.underlyingResource,a,a,n.format,u,!1,0,0)}}else{let e=[];for(let t=0;t<6;t++)e.push(a[h[t]]);this.updateRawCubeTexture(d,e,r,s,u)}d.isReady=!0,null==t||t.removePendingData(d),l&&l()};return this._loadFile(e,e=>{internalCallback(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)}),d},webgpuEngine_WebGPUEngine.prototype.createRawTexture3D=function(e,t,i,r,s,a,n,o,l=null,h=0,c=0){let u=$.Raw3D,d=new internalTexture_InternalTexture(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=a,d.samplingMode=o,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,c),this.updateRawTexture3D(d,e,s,n,l,h),this._internalTexturesCache.push(d),d},webgpuEngine_WebGPUEngine.prototype.updateRawTexture3D=function(e,t,i,r,s=null,a=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture,n=4===i;n&&(t=engine_rawTexture_convertRGBtoRGBATextureData(t,e.width,e.height,a));let o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},webgpuEngine_WebGPUEngine.prototype.createRawTexture2DArray=function(e,t,i,r,s,a,n,o,l=null,h=0,c=0){let u=$.Raw2DArray,d=new internalTexture_InternalTexture(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=a,d.samplingMode=o,d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,r,c),this.updateRawTexture2DArray(d,e,s,n,l,h),this._internalTexturesCache.push(d),d},webgpuEngine_WebGPUEngine.prototype.updateRawTexture2DArray=function(e,t,i,r,s=null,a=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture,n=4===i;n&&(t=engine_rawTexture_convertRGBtoRGBATextureData(t,e.width,e.height,a));let o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},webgpuEngine_WebGPUEngine.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,a=null,n=!0,o=!1,l=0,h=0){let c=e._hardwareTexture;return n&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,r,s,a,o)},webgpuEngine_WebGPUEngine.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};let WebGPURenderTargetWrapper=class WebGPURenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{};function IsExternalTexture(e){return!!e&&void 0!==e.underlyingResource}webgpuEngine_WebGPUEngine.prototype._createHardwareRenderTargetWrapper=function(e,t,i){let r=new WebGPURenderTargetWrapper(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},webgpuEngine_WebGPUEngine.prototype.createRenderTargetTexture=function(e,t){var i,r,s;let a=this._createHardwareRenderTargetWrapper(!1,!1,e),n={};void 0!==t&&"object"==typeof t?(n.generateMipMaps=t.generateMipMaps,n.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,n.generateStencilBuffer=n.generateDepthBuffer&&t.generateStencilBuffer,n.samplingMode=void 0===t.samplingMode?3:t.samplingMode,n.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,n.noColorAttachment=!!t.noColorAttachment,n.samples=t.samples,n.label=t.label):(n.generateMipMaps=t,n.generateDepthBuffer=!0,n.generateStencilBuffer=!1,n.samplingMode=3,n.creationFlags=0,n.noColorAttachment=!1);let o=n.noColorAttachment?null:this._createInternalTexture(e,t,!0,$.RenderTarget);return a.label=null!==(r=n.label)&&void 0!==r?r:"RenderTargetWrapper",a._samples=null!==(s=n.samples)&&void 0!==s?s:1,a._generateDepthBuffer=n.generateDepthBuffer,a._generateStencilBuffer=!!n.generateStencilBuffer,a.setTextures(o),(a._generateDepthBuffer||a._generateStencilBuffer)&&a.createDepthStencilTexture(0,this._caps.textureFloatLinearFiltering&&(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),a._generateStencilBuffer,a.samples,n.generateStencilBuffer?13:14,n.label?n.label+"-DepthStencil":void 0),o&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!n.generateMipMaps&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o,void 0,void 0,void 0,n.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!n.generateMipMaps&&(o.generateMipMaps=!1)),a},webgpuEngine_WebGPUEngine.prototype._createDepthStencilTexture=function(e,t){let i=new internalTexture_InternalTexture(this,$.DepthStencil);i.label=t.label;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14},t);return i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},webgpuEngine_WebGPUEngine.prototype._setupDepthStencilTexture=function(e,t,i,r,s,a=1){let n=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=n,e.baseHeight=o,e.width=n,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=a,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=1,e._comparisonFunction=s,e._cachedWrapU=0,e._cachedWrapV=0},webgpuEngine_WebGPUEngine.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},webgpuEngine_WebGPUEngine.prototype.createRenderTargetCubeTexture=function(e,t){var i;let r=this._createHardwareRenderTargetWrapper(!1,!0,e),s=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},t);s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,r.label=null!==(i=s.label)&&void 0!==i?i:"RenderTargetWrapper",r._generateDepthBuffer=s.generateDepthBuffer,r._generateStencilBuffer=s.generateStencilBuffer;let a=new internalTexture_InternalTexture(this,$.RenderTarget);return a.width=e,a.height=e,a.depth=0,a.isReady=!0,a.isCube=!0,a.samples=s.samples,a.generateMipMaps=s.generateMipMaps,a.samplingMode=s.samplingMode,a.type=s.type,a.format=s.format,this._internalTexturesCache.push(a),r.setTextures(a),(r._generateDepthBuffer||r._generateStencilBuffer)&&r.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,r._generateStencilBuffer,r.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(a.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(a),t&&t.createMipMaps&&!s.generateMipMaps&&(a.generateMipMaps=!1),r},effect_Effect.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},webgpuEngine_WebGPUEngine.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},effect_Effect.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},webgpuEngine_WebGPUEngine.prototype.createStorageBuffer=function(e,t,i){return this._createBuffer(e,32|t,i)},webgpuEngine_WebGPUEngine.prototype.updateStorageBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(e,i,s,0,r)},webgpuEngine_WebGPUEngine.prototype.readFromStorageBuffer=function(e,t,i,r){i=i||e.capacity;let s=this._bufferManager.createRawBuffer(i,ez.MapRead|ez.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderTargetEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,s,0,i),new Promise((e,t)=>{this.onEndFrameObservable.addOnce(()=>{s.mapAsync(eW.Read,0,i).then(()=>{let t=s.getMappedRange(0,i),a=r;if(void 0===a)(a=new Uint8Array(i)).set(new Uint8Array(t));else{let e=a.constructor;(a=new e(a.buffer)).set(new e(t))}s.unmap(),this._bufferManager.releaseBuffer(s),e(a)},e=>t(e))})})},webgpuEngine_WebGPUEngine.prototype.setStorageBuffer=function(e,t){var i,r;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(r=null==t?void 0:t.getBuffer())&&void 0!==r?r:null)},webgpuEngine_WebGPUEngine.prototype.createUniformBuffer=function(e,t){let i;i=e instanceof Array?new Float32Array(e):e;let r=this._bufferManager.createBuffer(i,ez.Uniform|ez.CopyDst,t);return r},webgpuEngine_WebGPUEngine.prototype.createDynamicUniformBuffer=function(e,t){return this.createUniformBuffer(e,t)},webgpuEngine_WebGPUEngine.prototype.updateUniformBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Float32Array?t:new Float32Array(t)).byteLength:s=t instanceof Float32Array?t:new Float32Array(t),this._bufferManager.setSubData(e,i,s,0,r)},webgpuEngine_WebGPUEngine.prototype.bindUniformBufferBase=function(e,t,i){this._currentDrawContext.setBuffer(i,e)},webgpuEngine_WebGPUEngine.prototype.bindUniformBlock=function(){},webgpuEngine_WebGPUEngine.prototype.updateVideoTexture=function(e,t,i){var r;if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;(null===(r=e._hardwareTexture)||void 0===r?void 0:r.underlyingResource)||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),IsExternalTexture(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0):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})};let ClipboardEventTypes=class ClipboardEventTypes{};ClipboardEventTypes.COPY=1,ClipboardEventTypes.CUT=2,ClipboardEventTypes.PASTE=3;let planeRotationGizmo_PlaneRotationGizmo=class planeRotationGizmo_PlaneRotationGizmo extends gizmo_Gizmo{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=math_color_Color3.Gray(),i=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer,r=32,s=null,a=!1,n=1){var o;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new observable_Observable,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new math_vector_Vector3,this._parent=s,this._coloredMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new math_color_Color3(.1,.1,.1)),this._hoverMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=math_color_Color3.Yellow(),this._disableMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._disableMaterial.diffuseColor=math_color_Color3.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new mesh_Mesh("",i.utilityLayerScene);let{rotationMesh:l,collider:h}=this._createGizmoMesh(this._gizmoMesh,n,r);this._rotationDisplayPlane=planeBuilder_CreatePlane("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),effect_Effect.ShadersStore.rotationGizmoVertexShader=planeRotationGizmo_PlaneRotationGizmo._RotationGizmoVertexShader,effect_Effect.ShadersStore.rotationGizmoFragmentShader=planeRotationGizmo_PlaneRotationGizmo._RotationGizmoFragmentShader,this._rotationShaderMaterial=new shaderMaterial_ShaderMaterial("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,gizmo_Gizmo.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new pointerDragBehavior_PointerDragBehavior({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);let c=new math_vector_Vector3,u=new math_vector_Matrix,d=new math_vector_Vector3,_=new math_vector_Vector3;this.dragBehavior.onDragStartObservable.add(e=>{this.attachedNode&&(c.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(u),math_vector_Vector3.TransformCoordinatesToRef(e.dragPlanePoint,u,c),this._angles.x=Math.atan2(c.y,c.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,c.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});let p={snapDistance:0},f=0,m=new math_vector_Matrix,g=new math_vector_Quaternion;this.dragBehavior.onDragObservable.add(t=>{if(this.attachedNode){let r=new math_vector_Vector3(1,1,1),s=new math_vector_Quaternion(0,0,0,1),a=new math_vector_Vector3(0,0,0);this.attachedNode.getWorldMatrix().decompose(r,s,a);let n=.001>=Math.abs(Math.abs(r.x)-Math.abs(r.y))&&.001>=Math.abs(Math.abs(r.x)-Math.abs(r.z));if(!n&&this.updateGizmoRotationToMatchAttachedMesh){logger_Logger.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}s.normalize();let o=this.updateGizmoPositionToMatchAttachedMesh?a:this._rootMesh.absolutePosition,l=t.dragPlanePoint.subtract(o).normalize(),h=c.subtract(o).normalize(),v=math_vector_Vector3.Cross(l,h),x=math_vector_Vector3.Dot(l,h),b=Math.atan2(v.length(),x)*this.sensitivity;d.copyFrom(e),_.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(u),_=math_vector_Vector3.TransformCoordinates(d,u));let T=!1;if(i.utilityLayerScene.activeCamera){let e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();math_vector_Vector3.Dot(e,_)>0&&(d.scaleInPlace(-1),_.scaleInPlace(-1),T=!0)}let S=math_vector_Vector3.Dot(_,v)>0;S&&(b=-b),math_vector_TmpVectors.Vector3[0].set(b,0,0),this.dragBehavior.validateDrag(math_vector_TmpVectors.Vector3[0])||(b=0);let C=!1;if(0!=this.snapDistance){if(Math.abs(f+=b)>this.snapDistance){let e=Math.floor(Math.abs(f)/this.snapDistance);f<0&&(e*=-1),f%=this.snapDistance,b=this.snapDistance*e,C=!0}else b=0}let E=Math.sin(b/2);if(g.set(d.x*E,d.y*E,d.z*E,Math.cos(b/2)),m.determinant()>0){let e=new math_vector_Vector3;g.toEulerAnglesToRef(e),math_vector_Quaternion.RotationYawPitchRollToRef(e.y,-e.x,-e.z,g)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(g,s),s.normalize(),math_vector_Matrix.ComposeToRef(r,s,a,this.attachedNode.getWorldMatrix());else{g.toRotationMatrix(math_vector_TmpVectors.Matrix[0]);let e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(math_vector_TmpVectors.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}c.copyFrom(t.dragPlanePoint),C&&(p.snapDistance=b,this.onSnapObservable.notifyObservers(p)),this._angles.y+=b,this.angle+=T?-b:b,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});let v=i._getSharedGizmoLight();v.includedOnlyMeshes=v.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));let x={colliderMeshes:[h],gizmoMeshes:[l],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(o=this._parent)||void 0===o||o.addToAxisCache(this._gizmoMesh,x),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(e=>{var t;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle,this._isHovered=-1!=x.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh),!this._parent)){let e=x.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(x.gizmoMeshes,e)}}),this.dragBehavior.onEnabledObservable.add(e=>{this._setGizmoMeshMaterial(x.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){let r=CreateTorus("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;let s=CreateTorus("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(s,gizmo_Gizmo.PreserveScaling),e.addChild(r,gizmo_Gizmo.PreserveScaling),{rotationMesh:s,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}};planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle=9*Math.PI/20,planeRotationGizmo_PlaneRotationGizmo._RotationGizmoVertexShader=` + precision highp float; + attribute vec3 position; + attribute vec2 uv; + uniform mat4 worldViewProjection; + varying vec3 vPosition; + varying vec2 vUV; + void main(void) { + gl_Position = worldViewProjection * vec4(position, 1.0); + vUV = uv; + }`,planeRotationGizmo_PlaneRotationGizmo._RotationGizmoFragmentShader=` + precision highp float; + varying vec2 vUV; + varying vec3 vPosition; + uniform vec3 angles; + #define twopi 6.283185307 + void main(void) { + vec2 uv = vUV - vec2(0.5); + float angle = atan(uv.y, uv.x) + 3.141592; + float delta = gl_FrontFacing ? angles.y : -angles.y; + float begin = angles.x - delta * angles.z; + float start = (begin < (begin + delta)) ? begin : (begin + delta); + float end = (begin > (begin + delta)) ? begin : (begin + delta); + float len = sqrt(dot(uv,uv)); + float opacity = 1. - step(0.5, len); + + float base = abs(floor(start / twopi)) * twopi; + start += base; + end += base; + + float intensity = 0.; + for (int i = 0; i < 5; i++) + { + intensity += max(step(start, angle) - step(end, angle), 0.); + angle += twopi; + } + gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity; + }`;let ShadowLight=class ShadowLight extends light_Light{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=math_vector_Vector3.Zero()),math_vector_Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=math_vector_Vector3.Zero()),math_vector_Vector3.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=math_vector_Vector3.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();let e=math_vector_Vector3.Cross(this.direction,math_axis_Axis.Y),t=math_vector_Vector3.Cross(e,this.direction);return math_vector_Vector3.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=math_vector_Vector3.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?this._currentRenderId=this.getScene().getRenderId():(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=math_vector_Matrix.Identity()),math_vector_Matrix.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)}};__decorate([serializeAsVector3()],ShadowLight.prototype,"position",null),__decorate([serializeAsVector3()],ShadowLight.prototype,"direction",null),__decorate([serialize()],ShadowLight.prototype,"shadowMinZ",null),__decorate([serialize()],ShadowLight.prototype,"shadowMaxZ",null),node_Node.AddNodeConstructor("Light_Type_1",(e,t)=>()=>new DirectionalLight(e,math_vector_Vector3.Zero(),t));let DirectionalLight=class DirectionalLight extends ShadowLight{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 light_Light.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){let t=this.getScene().activeCamera;t&&math_vector_Matrix.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){let r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){let e=math_vector_Vector3.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let r=Number.MAX_VALUE,s=-Number.MAX_VALUE;for(let a=0;a<i.length;a++){let n=i[a];if(!n)continue;let o=n.getBoundingInfo(),l=o.boundingBox;for(let i=0;i<l.vectorsWorld.length;i++)math_vector_Vector3.TransformCoordinatesToRef(l.vectorsWorld[i],t,e),e.x<this._orthoLeft&&(this._orthoLeft=e.x),e.y<this._orthoBottom&&(this._orthoBottom=e.y),e.x>this._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.z<r&&(r=e.z),e.z>s&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=r,this._shadowMaxZ=s)}let s=this._orthoRight-this._orthoLeft,a=this._orthoTop-this._orthoBottom,n=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;math_vector_Matrix.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-a*this.shadowOrthoScale,this._orthoTop+a*this.shadowOrthoScale,l?o:n,l?n:o,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t):this._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):e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this}getDepthMinZ(e){let t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){let t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}};function CreateHemisphere(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);let r=sphereBuilder_CreateSphere("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=discBuilder_CreateDisc("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=r;let a=mesh_Mesh.MergeMeshes([s,r],!0);return a.name=e,a}__decorate([serialize()],DirectionalLight.prototype,"shadowFrustumSize",null),__decorate([serialize()],DirectionalLight.prototype,"shadowOrthoScale",null),__decorate([serialize()],DirectionalLight.prototype,"autoUpdateExtends",void 0),__decorate([serialize()],DirectionalLight.prototype,"autoCalcShadowZBounds",void 0),__decorate([serialize("orthoLeft")],DirectionalLight.prototype,"_orthoLeft",void 0),__decorate([serialize("orthoRight")],DirectionalLight.prototype,"_orthoRight",void 0),__decorate([serialize("orthoTop")],DirectionalLight.prototype,"_orthoTop",void 0),__decorate([serialize("orthoBottom")],DirectionalLight.prototype,"_orthoBottom",void 0),mesh_Mesh.CreateHemisphere=(e,t,i,r)=>CreateHemisphere(e,{segments:t,diameter:i},r),node_Node.AddNodeConstructor("Light_Type_2",(e,t)=>()=>new SpotLight(e,math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),0,0,t));let SpotLight=class SpotLight extends ShadowLight{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()&&(SpotLight._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):SpotLight._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()})))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,r,s,a){super(e,a),this._innerAngle=0,this._projectionTextureMatrix=math_vector_Matrix.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=math_vector_Vector3.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=math_vector_Vector3.Zero(),this._projectionTextureViewLightMatrix=math_vector_Matrix.Zero(),this._projectionTextureProjectionLightMatrix=math_vector_Matrix.Zero(),this._projectionTextureScalingMatrix=math_vector_Matrix.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return light_Light.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;let s=this._shadowAngleScale*this._angle,a=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;math_vector_Matrix.PerspectiveFovLHToRef(s,1,o?n:a,o?a:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.direction,this._projectionTextureViewTargetVector),math_vector_Matrix.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;let e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);math_vector_Matrix.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof texture_Texture){let e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;math_vector_Matrix.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=math_vector_Vector3.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=math_vector_Vector3.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()?math_vector_Vector3.Normalize(this.transformedDirection):math_vector_Vector3.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){let 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){let 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())}};__decorate([serialize()],SpotLight.prototype,"angle",null),__decorate([serialize()],SpotLight.prototype,"innerAngle",null),__decorate([serialize()],SpotLight.prototype,"shadowAngleScale",null),__decorate([serialize()],SpotLight.prototype,"exponent",void 0),__decorate([serialize()],SpotLight.prototype,"projectionTextureLightNear",null),__decorate([serialize()],SpotLight.prototype,"projectionTextureLightFar",null),__decorate([serialize()],SpotLight.prototype,"projectionTextureUpDirection",null),__decorate([serializeAsTexture("projectedLightTexture")],SpotLight.prototype,"_projectionTexture",void 0);let LightGizmo=class LightGizmo extends gizmo_Gizmo{constructor(e=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer){super(e),this._cachedPosition=new math_vector_Vector3,this._cachedForward=new math_vector_Vector3(0,0,1),this._pointerObserver=null,this.onClickedObservable=new observable_Observable,this._light=null,this.attachedMesh=new abstractMesh_AbstractMesh("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new transformNode_TransformNode("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new standardMaterial_StandardMaterial("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new math_color_Color3(.5,.5,.5),this._material.specularColor=new math_color_Color3(.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))},pointerEvents_PointerEventTypes.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(),e instanceof HemisphericLight?this._lightMesh=LightGizmo._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof DirectionalLight?this._lightMesh=LightGizmo._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof SpotLight?this._lightMesh=LightGizmo._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=LightGizmo._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._lightMesh.parent=this._rootMesh;let t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new math_vector_Quaternion,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);let t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(math_vector_TmpVectors.Vector3[0]),e=math_vector_TmpVectors.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position){if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{let e=this.attachedMesh.position;this._light.position=new math_vector_Vector3(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}}if(this._light.direction){let e=this._getMeshForward();math_vector_Vector3.DistanceSquared(e,this._cachedForward)>1e-4?(this._light.direction=new math_vector_Vector3(e.x,e.y,e.z),this._cachedForward.copyFrom(e)):math_vector_Vector3.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){let t=new mesh_Mesh("hemisphereLight",e),i=CreateHemisphere(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;let r=this._CreateLightLines(3,e);return r.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){let t=new mesh_Mesh("pointLight",e),i=sphereBuilder_CreateSphere(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;let r=this._CreateLightLines(5,e);return r.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){let t=new mesh_Mesh("spotLight",e),i=sphereBuilder_CreateSphere(t.name,{segments:10,diameter:1},e);i.parent=t;let r=CreateHemisphere(t.name,{segments:10,diameter:2},e);r.parent=t,r.rotation.x=-Math.PI/2;let s=this._CreateLightLines(2,e);return s.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){let t=new mesh_Mesh("directionalLight",e),i=new mesh_Mesh(t.name,e);i.parent=t;let r=sphereBuilder_CreateSphere(t.name,{diameter:1.2,segments:10},e);r.parent=i;let s=cylinderBuilder_CreateCylinder(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let a=s.clone(t.name);a.scaling.y=.5,a.position.x+=1.25;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;let o=cylinderBuilder_CreateCylinder(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,(a=o.clone(t.name)).position.y=1.5,a.position.x+=1.25,(n=o.clone(t.name)).position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(LightGizmo._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}};LightGizmo._Scale=.007,LightGizmo._CreateLightLines=(e,t)=>{let i=new mesh_Mesh("root",t);i.rotation.x=Math.PI/2;let r=new mesh_Mesh("linePivot",t);r.parent=i;let s=cylinderBuilder_CreateCylinder("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=r,e<2)return r;for(let e=0;e<4;e++){let t=r.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<5)return i;let a=r.clone("linePivotClone");return a.rotation.z=Math.PI,i};let CameraGizmo=class CameraGizmo extends gizmo_Gizmo{constructor(e=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer){super(e),this._pointerObserver=null,this.onClickedObservable=new observable_Observable,this._camera=null,this._invProjection=new math_vector_Matrix,this._material=new standardMaterial_StandardMaterial("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new math_color_Color3(.5,.5,.5),this._material.specularColor=new math_color_Color3(.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))},pointerEvents_PointerEventTypes.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=CameraGizmo._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraLinesMesh=CameraGizmo._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;let 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){let t=new mesh_Mesh("rootCameraGizmo",e),i=new mesh_Mesh(t.name,e);i.parent=t;let r=boxBuilder_CreateBox(t.name,{width:1,height:.8,depth:.5},e);r.parent=i;let s=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;let a=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);a.parent=i,a.position.y=.5,a.position.x=.4,a.rotation.x=.5*Math.PI;let n=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(CameraGizmo._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e){let t=new mesh_Mesh("rootCameraGizmo",e),i=new mesh_Mesh(t.name,e);i.parent=t;for(let t=0;t<4;t+=2)for(let r=0;r<4;r+=2){let s=linesBuilder_CreateLines("lines",{points:[new math_vector_Vector3(-1+r,-1+t,-1),new math_vector_Vector3(-1+r,-1+t,1)]},e);s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=linesBuilder_CreateLines("lines",{points:[new math_vector_Vector3(-1,-1+r,-1+t),new math_vector_Vector3(1,-1+r,-1+t)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=linesBuilder_CreateLines("lines",{points:[new math_vector_Vector3(-1+r,-1,-1+t),new math_vector_Vector3(-1+r,1,-1+t)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1}return t}};CameraGizmo._Scale=.05,ShaderStore.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";let sb=`vec4 pack(float depth) +{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} +float unpack(vec4 color) +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;ShaderStore.IncludesShadersStore.packingFunctions=sb;let sT=`#ifdef DOF +factor=sampleCoC(sampleCoord{X}); +computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; +#else +blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; +#endif +`;ShaderStore.IncludesShadersStore.kernelBlurFragment=sT;let sS=`#ifdef DOF +factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_DEP_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; +#else +blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; +#endif +`;ShaderStore.IncludesShadersStore.kernelBlurFragment2=sS;let sC=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; +#ifdef DOF +uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } +#endif +#include<kernelBlurVaryingDeclaration>[0..varyingCount] +#ifdef PACKEDFLOAT +#include<packingFunctions> +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float computedWeight=0.0; +#ifdef PACKEDFLOAT +float blend=0.; +#else +vec4 blend=vec4(0.); +#endif +#ifdef DOF +float sumOfWeights=CENTER_WEIGHT; +float factor=0.0; +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; +#else +blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; +#endif +#endif +#include<kernelBlurFragment>[0..varyingCount] +#include<kernelBlurFragment2>[0..depCount] +#ifdef PACKEDFLOAT +gl_FragColor=pack(blend); +#else +gl_FragColor=blend; +#endif +#ifdef DOF +gl_FragColor/=sumOfWeights; +#endif +}`;ShaderStore.ShadersStore.kernelBlurPixelShader=sC,ShaderStore.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";let sE=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; +#include<kernelBlurVaryingDeclaration>[0..varyingCount] +const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +sampleCenter=(position*madd+madd); +#include<kernelBlurVertex>[0..varyingCount] +gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.kernelBlurVertexShader=sE;let BlurPostProcess=class BlurPostProcess extends postProcess_PostProcess{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,r,s,a=texture_Texture.BILINEAR_SAMPLINGMODE,n,o,l=0,h="",c=!1,u=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],r,s,a,n,o,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,u),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,r,s,a){this._updateParameters(s,a)}_updateParameters(e,t){let i=this._kernel,r=(i-1)/2,s=[],a=[],n=0;for(let e=0;e<i;e++){let t=e/(i-1),o=this._gaussianWeight(2*t-1);s[e]=e-r,a[e]=o,n+=o}for(let e=0;e<a.length;e++)a[e]/=n;let o=[],l=[],h=[];for(let e=0;e<=r;e+=2){let t=Math.min(e+1,Math.floor(r)),i=e===t;if(i)h.push({o:s[e],w:a[e]});else{let i=t===r,n=a[e]+a[t]*(i?.5:1),o=s[e]+1/(1+a[e]/a[t]);0===o?(h.push({o:s[e],w:a[e]}),h.push({o:s[e+1],w:a[e+1]})):(h.push({o:o,w:n}),h.push({o:-o,w:n}))}}for(let e=0;e<h.length;e++)l[e]=h[e].o,o[e]=h[e].w;s=l,a=o;let c=this.getEngine().getCaps().maxVaryingVectors,u=Math.max(c,0)-1,d=Math.min(s.length,u),_="";_+=this._staticDefines,-1!=this._staticDefines.indexOf("DOF")&&(_+=`#define CENTER_WEIGHT ${this._glslFloat(a[d-1])} +`,d--);for(let e=0;e<d;e++)_+=`#define KERNEL_OFFSET${e} ${this._glslFloat(s[e])} +#define KERNEL_WEIGHT${e} ${this._glslFloat(a[e])} +`;let p=0;for(let e=u;e<s.length;e++)_+=`#define KERNEL_DEP_OFFSET${p} ${this._glslFloat(s[e])} +#define KERNEL_DEP_WEIGHT${p} ${this._glslFloat(a[e])} +`,p++;this.packedFloat&&(_+="#define PACKEDFLOAT 1"),this._blockCompilation=!1,super.updateEffect(_,null,null,{varyingCount:d,depCount:p},e,t)}_nearestBestKernel(e){let t=Math.round(e);for(let e of[t,t-1,t+1,t-2,t+2])if(e%2!=0&&Math.floor(e/2)%2==0&&e>0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){let t=1/3;return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(-(e*e/(2*t*t)))}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new BlurPostProcess(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}};__decorate([serialize("kernel")],BlurPostProcess.prototype,"_kernel",void 0),__decorate([serialize("packedFloat")],BlurPostProcess.prototype,"_packedFloat",void 0),__decorate([generateSerializableMember(4,void 0)],BlurPostProcess.prototype,"direction",void 0),h["BABYLON.BlurPostProcess"]=BlurPostProcess;let MirrorTexture=class MirrorTexture extends renderTargetTexture_RenderTargetTexture{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(){let 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(){let e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,s=0,a=texture_Texture.BILINEAR_SAMPLINGMODE,n=!0){let o;if(super(e,t,i,r,!0,s,!1,a,n),this.mirrorPlane=new math_plane_Plane(0,1,0,1),this._transformMatrix=math_vector_Matrix.Zero(),this._mirrorMatrix=math_vector_Matrix.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()});let l=i.getEngine();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()),math_vector_Matrix.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),o=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=math_vector_Vector3.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=o})}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){let e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new BlurPostProcess("horizontal blur",new math_vector_Vector2(1,0),this._blurKernelX,this._blurRatio,null,texture_Texture.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 BlurPostProcess("vertical blur",new math_vector_Vector2(0,1),this._blurKernelY,this._blurRatio,null,texture_Texture.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(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new MirrorTexture(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;let e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();let t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}};texture_Texture._CreateMirror=(e,t,i,r)=>new MirrorTexture(e,t,i,r);let cubeTexture_CubeTexture=class cubeTexture_CubeTexture extends baseTexture_BaseTexture{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(math_vector_Matrix.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let r="";return e.forEach(e=>r+=e),new cubeTexture_CubeTexture(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){let s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;let a=new cubeTexture_CubeTexture(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=s,a}constructor(e,t,i=null,r=!1,s=null,a=null,n=null,o=5,l=!1,h=null,c=!1,u=.8,d=0,_,p){var f;if(super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new observable_Observable,this.boundingBoxPosition=math_vector_Vector3.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new math_vector_Matrix,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this._format=o,this.isCube=!0,this._textureMatrix=math_vector_Matrix.Identity(),this._createPolynomials=c,this.coordinatesMode=texture_Texture.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=h,this._loaderOptions=_,this._useSRGBBuffer=p,this._lodScale=u,this._lodOffset=d,!e&&!s)return;this.updateURL(e,h,a,l,n,i,null===(f=this.getScene())||void 0===f?void 0:f.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,r=!1,s=null,a=null,n=!1,o=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);let l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),u=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(u?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(d||u||c||a||(a=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,a){for(let t=0;t<a.length;t++)this._files.push(e+a[t]);this._extensions=a}n?(this.delayLoadState=4,this._delayedOnLoad=i,this._delayedOnError=s):this._loadTexture(i,s)}delayLoad(e){4===this.delayLoadState&&(e&&(this._forcedExtension=e),this.delayLoadState=1,this._loadTexture(this._delayedOnLoad,this._delayedOnError))}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t,i;if(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))),this._textureMatrix=e,!(null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem)))return;let r=math_vector_TmpVectors.Vector3[0],s=math_vector_TmpVectors.Quaternion[0],a=math_vector_TmpVectors.Vector3[1];this._textureMatrix.decompose(r,s,a),s.z*=-1,s.w*=-1,math_vector_Matrix.ComposeToRef(r,s,a,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;let r=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);let onLoadProcessing=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},errorHandler=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),texture_Texture.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?tools_Tools.SetImmediate(()=>onLoadProcessing()):this._texture.onLoadedObservable.add(()=>onLoadProcessing()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,r,this._lodScale,this._lodOffset,e,errorHandler,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,r,this._files,this._noMipmap,e,errorHandler,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){let r=decorators_SerializationHelper.Parse(()=>{var r;let s=!1;return e.prefiltered&&(s=e.prefiltered),new cubeTexture_CubeTexture(i+(null!==(r=e.url)&&void 0!==r?r:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=math_vector_Vector3.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=math_vector_Vector3.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t<e.animations.length;t++){let i=e.animations[t],s=h["BABYLON.Animation"];s&&r.animations.push(s.Parse(i))}return r}clone(){let e=0,t=decorators_SerializationHelper.Clone(()=>{let t=new cubeTexture_CubeTexture(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t},this);return t.uniqueId=e,t}};__decorate([serialize()],cubeTexture_CubeTexture.prototype,"url",void 0),__decorate([serializeAsVector3()],cubeTexture_CubeTexture.prototype,"boundingBoxPosition",void 0),__decorate([serializeAsVector3()],cubeTexture_CubeTexture.prototype,"boundingBoxSize",null),__decorate([serialize("rotationY")],cubeTexture_CubeTexture.prototype,"rotationY",null),__decorate([serialize("files")],cubeTexture_CubeTexture.prototype,"_files",void 0),__decorate([serialize("forcedExtension")],cubeTexture_CubeTexture.prototype,"_forcedExtension",void 0),__decorate([serialize("extensions")],cubeTexture_CubeTexture.prototype,"_extensions",void 0),__decorate([generateSerializableMember(12,"textureMatrix")],cubeTexture_CubeTexture.prototype,"_textureMatrix",void 0),__decorate([generateSerializableMember(12,"textureMatrixRefraction")],cubeTexture_CubeTexture.prototype,"_textureMatrixRefraction",void 0),texture_Texture._CubeTextureParser=cubeTexture_CubeTexture.Parse,h["BABYLON.CubeTexture"]=cubeTexture_CubeTexture;let sy=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +uniform vec4 vPrimaryColorShadow; +#endif +uniform float shadowLevel;uniform float alpha; +#ifdef DIFFUSE +uniform vec2 vDiffuseInfos; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; +#endif +#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) +uniform vec3 vBackgroundCenter; +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 vReflectionControl; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) +uniform mat4 view; +#endif +#ifdef PROJECTED_GROUND +uniform vec2 projectedGroundInfos; +#endif +`;ShaderStore.IncludesShadersStore.backgroundFragmentDeclaration=sy;let sR=`layout(std140,column_major) uniform;uniform Material +{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;}; +#include<sceneUboDeclaration> +`;ShaderStore.IncludesShadersStore.backgroundUboDeclaration=sR;let sP=`#ifdef TEXTURELODSUPPORT +#extension GL_EXT_shader_texture_lod : enable +#endif +precision highp float; +#include<__decl__backgroundFragment> +#include<helperFunctions> +varying vec3 vPositionW; +#ifdef MAINUV1 +varying vec2 vMainUV1; +#endif +#ifdef MAINUV2 +varying vec2 vMainUV2; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef DIFFUSE +#if DIFFUSEDIRECTUV==1 +#define vDiffuseUV vMainUV1 +#elif DIFFUSEDIRECTUV==2 +#define vDiffuseUV vMainUV2 +#else +varying vec2 vDiffuseUV; +#endif +uniform sampler2D diffuseSampler; +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +#define sampleReflection(s,c) textureCube(s,c) +uniform samplerCube reflectionSampler; +#ifdef TEXTURELODSUPPORT +#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#else +#define sampleReflection(s,c) texture2D(s,c) +uniform sampler2D reflectionSampler; +#ifdef TEXTURELODSUPPORT +#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include<reflectionFunction> +#endif +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE; +#endif +#ifndef SHADOWONLY +#define SHADOWONLY; +#endif +#include<imageProcessingDeclaration> +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include<lightsFragmentFunctions> +#include<shadowsFragmentFunctions> +#include<imageProcessingFunctions> +#include<clipPlaneFragmentDeclaration> +#include<fogFragmentDeclaration> +#ifdef REFLECTIONFRESNEL +#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) +{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#ifdef PROJECTED_GROUND +float diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; } +vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)<r*r) ? t : 1e6;} +float sphereIntersect(vec3 ro,vec3 rd,float ra) {float b=dot(ro,rd);float c=dot(ro,ro)-ra*ra;float h=b*b-c;if(h<0.0) { return -1.0; } +h=sqrt(h);return-b+h;} +vec3 project(vec3 viewDirectionW,vec3 eyePosition) {float radius=projectedGroundInfos.x;float height=projectedGroundInfos.y;vec3 camDir=-viewDirectionW;float skySphereDistance=sphereIntersect(eyePosition,camDir,radius);vec3 skySpherePositionW=eyePosition+camDir*skySphereDistance;vec3 p=normalize(skySpherePositionW);eyePosition.y-=height;float sIntersection=sphereIntersect(eyePosition,p,radius);vec3 h=vec3(0.0,-height,0.0);float dIntersection=diskIntersectWithBackFaceCulling(eyePosition,p,h,radius);p=(eyePosition+min(sIntersection,dIntersection)*p);return p;} +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(0.0,1.0,0.0); +#endif +float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.; +#include<lightFragment>[0..maxSimultaneousLights] +#ifdef SHADOWINUSE +globalShadow/=shadowLightCount; +#else +globalShadow=1.0; +#endif +#ifndef BACKMAT_SHADOWONLY +vec4 reflectionColor=vec4(1.,1.,1.,1.); +#ifdef REFLECTION +#ifdef PROJECTED_GROUND +vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.)); +#else +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords=reflectionVector; +#else +vec2 reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +#ifdef REFLECTIONBLUR +float reflectionLOD=vReflectionInfos.y; +#ifdef TEXTURELODSUPPORT +reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); +#else +float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( +sampleReflection(reflectionSamplerHigh,reflectionCoords), +reflectionSpecularMid, +lodReflectionNormalizedDoubled +);} else {reflectionColor=mix( +reflectionSpecularMid, +sampleReflection(reflectionSamplerLow,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#else +vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef GAMMAREFLECTION +reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); +#endif +#ifdef REFLECTIONBGR +reflectionColor.rgb=reflectionColor.bgr; +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#endif +vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; +#ifdef DIFFUSE +vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); +#ifdef GAMMADIFFUSE +diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); +#endif +diffuseMap.rgb*=vDiffuseInfos.y; +#ifdef DIFFUSEHASALPHA +finalAlpha*=diffuseMap.a; +#endif +diffuseColor=diffuseMap.rgb; +#endif +#ifdef REFLECTIONFRESNEL +vec3 colorBase=diffuseColor; +#else +vec3 colorBase=reflectionColor.rgb*diffuseColor; +#endif +colorBase=max(colorBase,0.0); +#ifdef USERGBCOLOR +vec3 finalColor=colorBase; +#else +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); +#else +vec3 mainColor=vPrimaryColor.rgb; +#endif +vec3 finalColor=colorBase*mainColor; +#endif +#ifdef REFLECTIONFRESNEL +vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; +#ifdef REFLECTIONFALLOFF +float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; +#endif +finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); +#endif +#ifdef OPACITYFRESNEL +float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; +#endif +#ifdef SHADOWINUSE +finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); +#endif +vec4 color=vec4(finalColor,finalAlpha); +#else +vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); +#endif +#include<fogFragment> +#ifdef IMAGEPROCESSINGPOSTPROCESS +#if !defined(SKIPFINALCOLORCLAMP) +color.rgb=clamp(color.rgb,0.,30.0); +#endif +#else +color=applyImageProcessing(color); +#endif +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#ifdef NOISE +color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); +#endif +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +} +`;ShaderStore.ShadersStore.backgroundPixelShader=sP;let sA=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; +#ifdef DIFFUSE +uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +`;ShaderStore.IncludesShadersStore.backgroundVertexDeclaration=sA;let sM=`precision highp float; +#include<__decl__backgroundVertex> +#include<helperFunctions> +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<instancesDeclaration> +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef MAINUV1 +varying vec2 vMainUV1; +#endif +#ifdef MAINUV2 +varying vec2 vMainUV2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +varying vec2 vDiffuseUV; +#endif +#include<clipPlaneVertexDeclaration> +#include<fogVertexDeclaration> +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=position; +#endif +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} +#else +gl_Position=viewProjection*finalWorld*vec4(position,1.0); +#endif +vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normal); +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); +#ifdef EQUIRECTANGULAR_RELFECTION_FOV +mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} +#endif +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uv; +#endif +#ifdef MAINUV2 +vMainUV2=uv2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +if (vDiffuseInfos.x==0.) +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} +else +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} +#endif +#include<clipPlaneVertex> +#include<fogVertex> +#include<shadowsVertex>[0..maxSimultaneousLights] +#ifdef VERTEXCOLOR +vColor=color; +#endif +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;ShaderStore.ShadersStore.backgroundVertexShader=sM;let BackgroundMaterialDefines=class BackgroundMaterialDefines extends MaterialDefines{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!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()}};let BackgroundMaterial=class BackgroundMaterial extends PushMaterial{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=BackgroundMaterial.StandardReflectance0*t,this.reflectionReflectance90=BackgroundMaterial.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=BackgroundMaterial.StandardReflectance0+(1-BackgroundMaterial.StandardReflectance0)*t,this.reflectionReflectance90=BackgroundMaterial.StandardReflectance90+(1-BackgroundMaterial.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()})))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=math_color_Color3.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=math_vector_Vector3.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new SmartArray(16),this._reflectionControls=math_vector_Vector4.Zero(),this._white=math_color_Color3.White(),this._primaryShadowColor=math_color_Color3.Black(),this._primaryHighlightColor=math_color_Color3.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 BackgroundMaterialDefines);let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=r.getEngine();if(MaterialHelper.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,MaterialHelper.PrepareDefinesForMultiview(r,s),s._areTexturesDirty){if(s._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;MaterialHelper.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;let e=this._reflectionTexture;if(e&&MaterialFlags.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===texture_Texture.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 texture_Texture.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case texture_Texture.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case texture_Texture.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case texture_Texture.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case texture_Texture.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case texture_Texture.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.CUBIC_MODE:case texture_Texture.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(s._areMiscDirty&&(s.REFLECTIONMAP_3D&&this._enableGroundProjection?(s.PROJECTED_GROUND=!0,s.REFLECTIONMAP_SKYBOX=!0):s.PROJECTED_GROUND=!1),MaterialHelper.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),MaterialHelper.PrepareDefinesForFrameBoundValues(r,a,this,s,i,null,t.getRenderingMesh().hasThinInstances),MaterialHelper.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&!r.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)&&(e.createNormals(!0),logger_Logger.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();let i=new EffectFallbacks;s.FOG&&i.addFallback(0,"FOG"),s.POINTSIZE&&i.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),MaterialHelper.HandleFallbacksForShadows(s,i,this._maxSimultaneousLights);let n=[buffer_VertexBuffer.PositionKind];s.NORMAL&&n.push(buffer_VertexBuffer.NormalKind),s.UV1&&n.push(buffer_VertexBuffer.UVKind),s.UV2&&n.push(buffer_VertexBuffer.UV2Kind),MaterialHelper.PrepareAttributesForBones(n,e,s,i),MaterialHelper.PrepareAttributesForInstances(n,s);let o=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos"];addClipPlaneUniforms(o);let l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(o,s),ImageProcessingConfiguration.PrepareSamplers(l,s)),MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});let c=s.toString(),u=r.getEngine().createEffect("background",{attributes:n,uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},a);t.setEffect(u,s,this._materialContext),this.buildUniformLayout()}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.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.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,this.bindOnlyWorldMatrix(e),MaterialHelper.BindBonesParameters(t,this._activeEffect);let n=this._mustRebind(r,a,t.visibility);if(n){this._uniformBuffer.bindToEffect(a,"Material"),this.bindViewProjection(a);let e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(r.texturesEnabled&&(this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&MaterialFlags.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&MaterialFlags.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),s.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),bindClipPlane(this._activeEffect,this,r),r.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(a,"Material"),this._needToBindSceneUbo=!0);(n||!this.isFrozen)&&(r.lightsEnabled&&MaterialHelper.BindLights(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(a),MaterialHelper.BindFogParameters(r,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 decorators_SerializationHelper.Clone(()=>new BackgroundMaterial(e,this.getScene()),this)}serialize(){let e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return decorators_SerializationHelper.Parse(()=>new BackgroundMaterial(e.name,t),e,t,i)}};BackgroundMaterial.StandardReflectance0=.05,BackgroundMaterial.StandardReflectance90=.5,__decorate([serializeAsColor3()],BackgroundMaterial.prototype,"_primaryColor",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"primaryColor",void 0),__decorate([serializeAsColor3()],BackgroundMaterial.prototype,"__perceptualColor",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_primaryColorShadowLevel",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_primaryColorHighlightLevel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"primaryColorHighlightLevel",null),__decorate([serializeAsTexture()],BackgroundMaterial.prototype,"_reflectionTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionTexture",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionBlur",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionBlur",void 0),__decorate([serializeAsTexture()],BackgroundMaterial.prototype,"_diffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"diffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"shadowLights",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_shadowLevel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"shadowLevel",void 0),__decorate([serializeAsVector3()],BackgroundMaterial.prototype,"_sceneCenter",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"sceneCenter",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_opacityFresnel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"opacityFresnel",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionFresnel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionFresnel",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionFalloffDistance",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionFalloffDistance",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionAmount",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionAmount",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionReflectance0",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionReflectance0",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionReflectance90",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionReflectance90",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_useRGBColor",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"useRGBColor",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_enableNoise",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"enableNoise",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_maxSimultaneousLights",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"maxSimultaneousLights",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_shadowOnly",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"shadowOnly",void 0),__decorate([generateSerializableMember(9,void 0)],BackgroundMaterial.prototype,"_imageProcessingConfiguration",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],BackgroundMaterial.prototype,"enableGroundProjection",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"projectedGroundRadius",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"projectedGroundHeight",void 0),h["BABYLON.BackgroundMaterial"]=BackgroundMaterial;let EnvironmentHelper=class EnvironmentHelper{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new math_color_Color3(.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 math_color_Color3(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:math_vector_Vector3.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({},EnvironmentHelper._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new observable_Observable,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){let 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 math_color_Color4(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 baseTexture_BaseTexture){this._scene.environmentTexture=this._options.environmentTexture;return}let e=cubeTexture_CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new mesh_Mesh("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;let 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};let r=this._scene.getWorldExtends(e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox),s=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof ArcRotateCamera&&this._scene.activeCamera.upperRadiusLimit&&(t=e=2*this._scene.activeCamera.upperRadiusLimit);let a=s.length();a>e&&(t=e=2*a),e*=1.1,t*=1.5,(i=r.min.add(s.scale(.5))).y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=planeBuilder_CreatePlane("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 BackgroundMaterial("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof baseTexture_BaseTexture){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new texture_Texture(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){let t=texture_Texture.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new MirrorTexture("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,texture_Texture.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new math_plane_Plane(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e<this._scene.meshes.length;e++){let t=this._scene.meshes[e];t!==this._ground&&t!==this._skybox&&t!==this._rootMesh&&this._groundMirror.renderList.push(t)}let i=this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions);this._groundMirror.clearColor=new math_color_Color4(i.r,i.g,i.b,1),this._groundMirror.adaptiveBlurKernel=this._options.groundMirrorBlurKernel}_setupMirrorInGroundMaterial(){this._groundMaterial&&(this._groundMaterial.reflectionTexture=this._groundMirror,this._groundMaterial.reflectionFresnel=!0,this._groundMaterial.reflectionAmount=this._options.groundMirrorAmount,this._groundMaterial.reflectionStandardFresnelWeight=this._options.groundMirrorFresnelWeight,this._groundMaterial.reflectionFalloffDistance=this._options.groundMirrorFallOffDistance)}_setupSkybox(e){(!this._skybox||this._skybox.isDisposed())&&(this._skybox=boxBuilder_CreateBox("BackgroundSkybox",{size:e.skyboxSize,sideOrientation:mesh_Mesh.BACKSIDE},this._scene),this._skybox.onDisposeObservable.add(()=>{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new BackgroundMaterial("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){if(this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof baseTexture_BaseTexture){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new cubeTexture_CubeTexture(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=texture_Texture.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)}};EnvironmentHelper._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",EnvironmentHelper._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",EnvironmentHelper._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";let TextureDome=class TextureDome extends transformNode_TransformNode{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=TextureDome.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new observable_Observable,this.onLoadObservable=new observable_Observable,r=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=!!i.clickToPlay,i.autoPlay=void 0===i.autoPlay||!!i.autoPlay,i.loop=void 0===i.loop||!!i.loop,i.size=Math.abs(i.size)||(r.activeCamera?.48*r.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=sphereBuilder_CreateSphere(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:mesh_Mesh.BACKSIDE},r);let a=this._material=new BackgroundMaterial(e+"_material",r);a.useEquirectangularFOV=!0,a.fovMultiplier=1,a.opacityFresnel=!1;let n=this._initTexture(t,r,i);if(this.texture=n,this._mesh.material=a,this._mesh.parent=this,this._halfDomeMask=sphereBuilder_CreateSphere("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:mesh_Mesh.BACKSIDE},r),this._halfDomeMask.rotate(math_axis_Axis.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce(()=>{this._setReady(!0)}),i.faceForward&&r.activeCamera){let e=r.activeCamera,t=math_vector_Vector3.Forward(),i=math_vector_Vector3.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(math_vector_Vector3.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 TextureDome.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case TextureDome.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;let e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(i=>{let r=i.isRightCamera;this._crossEye&&(r=!r),r?this._texture.uOffset=e:this._texture.uOffset=t});break}case TextureDome.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)}};TextureDome.MODE_MONOSCOPIC=0,TextureDome.MODE_TOPBOTTOM=1,TextureDome.MODE_SIDEBYSIDE=2;let PhotoDome=class PhotoDome extends TextureDome{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 texture_Texture(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)})}};PhotoDome.MODE_MONOSCOPIC=TextureDome.MODE_MONOSCOPIC,PhotoDome.MODE_TOPBOTTOM=TextureDome.MODE_TOPBOTTOM,PhotoDome.MODE_SIDEBYSIDE=TextureDome.MODE_SIDEBYSIDE;let sI=0,GetEnvironmentBRDFTexture=e=>{if(!e.environmentBRDFTexture){let t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;let i=e._blockEntityCollection;e._blockEntityCollection=!1;let r=texture_Texture.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+sI++,e,!0,!1,texture_Texture.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;let s=e.getEngine().getLoadedTexturesCache(),a=s.indexOf(r.getInternalTexture());-1!==a&&s.splice(a,1),r.isRGBD=!0,r.wrapU=texture_Texture.CLAMP_ADDRESSMODE,r.wrapV=texture_Texture.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=r,e.useDelayedTextureLoading=t,RGBDTextureTools.ExpandRGBDTexture(r);let n=e.getEngine().onContextRestoredObservable.add(()=>{r.isRGBD=!0;let checkReady=()=>{r.isReady()?RGBDTextureTools.ExpandRGBDTexture(r):tools_Tools.SetImmediate(checkReady)};checkReady()});e.onDisposeObservable.add(()=>{e.getEngine().onContextRestoredObservable.remove(n)})}return e.environmentBRDFTexture};let MaterialBRDFDefines=class MaterialBRDFDefines extends MaterialDefines{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}};let pbrBRDFConfiguration_PBRBRDFConfiguration=class pbrBRDFConfiguration_PBRBRDFConfiguration extends MaterialPluginBase{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new MaterialBRDFDefines,t),this._useEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.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"}};pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useEnergyConservation",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSmithVisibilityHeightCorrelated",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSphericalHarmonics",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);let sD=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; +#ifdef ALBEDO +uniform vec2 vAlbedoInfos; +#endif +#ifdef AMBIENT +uniform vec4 vAmbientInfos; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#ifdef OPACITY +uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos; +#endif +#ifdef REFLECTIVITY +uniform vec3 vReflectivityInfos; +#endif +#ifdef MICROSURFACEMAP +uniform vec2 vMicroSurfaceSamplerInfos; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) +uniform mat4 view; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos; +#ifdef REALTIME_FILTERING +uniform vec2 vReflectionFilteringInfo; +#endif +uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; +#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) +uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; +#endif +#ifdef CLEARCOAT +uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; +#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform vec4 vClearCoatInfos; +#endif +#ifdef CLEARCOAT_TEXTURE +uniform mat4 clearCoatMatrix; +#endif +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS +uniform mat4 clearCoatRoughnessMatrix; +#endif +#ifdef CLEARCOAT_BUMP +uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; +#endif +#ifdef CLEARCOAT_TINT +uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; +#ifdef CLEARCOAT_TINT_TEXTURE +uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; +#endif +#endif +#endif +#ifdef IRIDESCENCE +uniform vec4 vIridescenceParams; +#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) +uniform vec4 vIridescenceInfos; +#endif +#ifdef IRIDESCENCE_TEXTURE +uniform mat4 iridescenceMatrix; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +uniform mat4 iridescenceThicknessMatrix; +#endif +#endif +#ifdef ANISOTROPIC +uniform vec3 vAnisotropy; +#ifdef ANISOTROPIC_TEXTURE +uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; +#endif +#endif +#ifdef SHEEN +uniform vec4 vSheenColor; +#ifdef SHEEN_ROUGHNESS +uniform float vSheenRoughness; +#endif +#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) +uniform vec4 vSheenInfos; +#endif +#ifdef SHEEN_TEXTURE +uniform mat4 sheenMatrix; +#endif +#ifdef SHEEN_TEXTURE_ROUGHNESS +uniform mat4 sheenRoughnessMatrix; +#endif +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; +#ifdef REALTIME_FILTERING +uniform vec2 vRefractionFilteringInfo; +#endif +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; +#endif +uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity; +#endif +#ifdef PREPASS +#ifdef SS_SCATTERING +uniform float scatteringDiffusionProfile; +#endif +#endif +#if DEBUGMODE>0 +uniform vec2 vDebugMode; +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos; +#endif +#include<decalFragmentDeclaration> +#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; +#else +uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; +#endif +#endif +#define ADDITIONAL_FRAGMENT_DECLARATION +`;ShaderStore.IncludesShadersStore.pbrFragmentDeclaration=sD;let sO=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; +#define ADDITIONAL_UBO_DECLARATION +}; +#include<sceneUboDeclaration> +#include<meshUboDeclaration> +`;ShaderStore.IncludesShadersStore.pbrUboDeclaration=sO;let sB=`varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#include<mainUVVaryingDeclaration>[1..7] +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +`;ShaderStore.IncludesShadersStore.pbrFragmentExtraDeclaration=sB;let sN=`#ifdef _DEFINENAME_ +#if _DEFINENAME_DIRECTUV==1 +#define v_VARYINGNAME_UV vMainUV1 +#elif _DEFINENAME_DIRECTUV==2 +#define v_VARYINGNAME_UV vMainUV2 +#elif _DEFINENAME_DIRECTUV==3 +#define v_VARYINGNAME_UV vMainUV3 +#elif _DEFINENAME_DIRECTUV==4 +#define v_VARYINGNAME_UV vMainUV4 +#elif _DEFINENAME_DIRECTUV==5 +#define v_VARYINGNAME_UV vMainUV5 +#elif _DEFINENAME_DIRECTUV==6 +#define v_VARYINGNAME_UV vMainUV6 +#else +varying vec2 v_VARYINGNAME_UV; +#endif +#endif +`;ShaderStore.IncludesShadersStore.samplerFragmentAlternateDeclaration=sN;let sF=`#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) +#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) +#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) +#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) +#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) +#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef CLEARCOAT +#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) +#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) +uniform sampler2D clearCoatRoughnessSampler; +#endif +#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) +#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) +#endif +#ifdef IRIDESCENCE +#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) +#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) +#endif +#ifdef SHEEN +#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) +#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) +uniform sampler2D sheenRoughnessSampler; +#endif +#endif +#ifdef ANISOTROPIC +#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +#define sampleReflection(s,c) textureCube(s,c) +uniform samplerCube reflectionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#ifdef USEIRRADIANCEMAP +uniform samplerCube irradianceSampler; +#endif +#else +#define sampleReflection(s,c) texture2D(s,c) +uniform sampler2D reflectionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; +#endif +#ifdef USEIRRADIANCEMAP +uniform sampler2D irradianceSampler; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#endif +#ifdef ENVIRONMENTBRDF +uniform sampler2D environmentBrdfSampler; +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +#ifdef SS_REFRACTIONMAP_3D +#define sampleRefraction(s,c) textureCube(s,c) +uniform samplerCube refractionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; +#endif +#else +#define sampleRefraction(s,c) texture2D(s,c) +uniform sampler2D refractionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; +#endif +#endif +#endif +#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) +#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) +#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) +#endif +`;ShaderStore.IncludesShadersStore.pbrFragmentSamplersDeclaration=sF;let sw=`bool testLightingForSSS(float diffusionProfile) +{return diffusionProfile<1.;}`;ShaderStore.IncludesShadersStore.subSurfaceScatteringFunctions=sw;let sL=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { +float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;ShaderStore.IncludesShadersStore.importanceSampling=sL;let sV=`#define MINIMUMVARIANCE 0.0005 +float convertRoughnessToAverageSlope(float roughness) +{return square(roughness)+MINIMUMVARIANCE;} +float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} +vec2 getAARoughnessFactors(vec3 normalVector) { +#ifdef SPECULARAA +vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); +#else +return vec2(0.); +#endif +} +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_LEGACY +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} +#else +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} +#endif +#endif +#if defined(CLEARCOAT) || defined(SS_REFRACTION) +vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} +vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} +vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} +vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), +cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), +clearCoatIntensity);return clearCoatAbsorption;} +#endif +#ifdef MICROSURFACEAUTOMATIC +float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) +{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} +#endif +`;ShaderStore.IncludesShadersStore.pbrHelperFunctions=sV;let sU=`#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 ++ vSphericalL1_1*(normal.y) ++ vSphericalL10*(normal.z) ++ vSphericalL11*(normal.x) ++ vSphericalL2_2*(normal.y*normal.x) ++ vSphericalL2_1*(normal.y*normal.z) ++ vSphericalL20*((3.0*normal.z*normal.z)-1.0) ++ vSphericalL21*(normal.z*normal.x) ++ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} +#else +vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} +#endif +#endif +`;ShaderStore.IncludesShadersStore.harmonicsFunctions=sU;let sk=`struct preLightingInfo +{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; +#ifdef IRIDESCENCE +float iridescenceIntensity; +#endif +};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; +#ifdef SPECULARTERM +result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); +#endif +return result;}`;ShaderStore.IncludesShadersStore.pbrDirectLightingSetupFunctions=sk;let sG=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) +{return max(0.,1.0-length(lightOffset)/range);} +float computeDistanceLightFalloff_Physical(float lightDistanceSquared) +{return 1.0/maxEps(lightDistanceSquared);} +float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) +{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} +float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDistanceLightFalloff_Physical(lightDistanceSquared); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); +#else +return computeDistanceLightFalloff_Standard(lightOffset,range); +#endif +} +float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) +{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) +{falloff=max(0.,pow(cosAngle,exponent));} +return falloff;} +float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) +{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; +float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} +float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) +{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} +float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); +#else +return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); +#endif +}`;ShaderStore.IncludesShadersStore.pbrDirectLightingFalloffFunctions=sG;let sz=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} +#endif +#ifdef ENVIRONMENTBRDF +vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); +#ifdef ENVIRONMENTBRDF_RGBD +brdfLookup.rgb=fromRGBD(brdfLookup.rgba); +#endif +return brdfLookup.rgb;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; +#endif +return reflectance;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; +#endif +return reflectance;} +#endif +/* NOT USED +#if defined(SHEEN) && defined(SHEEN_SOFTER) +float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) +{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} +#endif +*/ +#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) +vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) +{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +/** +* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. +* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table +*/ +vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} +#endif +vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +#ifdef CLEARCOAT +vec3 getR0RemappedForClearCoat(vec3 f0) { +#ifdef CLEARCOAT_DEFAULTIOR +#ifdef MOBILE +return saturate(f0*(f0*0.526868+0.529324)-0.0482256); +#else +return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); +#endif +#else +vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); +#endif +} +#endif +#ifdef IRIDESCENCE +const mat3 XYZ_TO_REC709=mat3( +3.2404542,-0.9692660, 0.0556434, +-1.5371385, 1.8760108,-0.2040259, +-0.4985314, 0.0415560, 1.0572252 +);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} +vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} +float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} +vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} +vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} +float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR<outsideIOR) phi12=PI;float phi21=PI-phi12;vec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999)); +vec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);vec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));vec3 phi23=vec3(0.0);if (baseIOR[0]<iridescenceIOR) phi23[0]=PI;if (baseIOR[1]<iridescenceIOR) phi23[1]=PI;if (baseIOR[2]<iridescenceIOR) phi23[2]=PI;float opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;vec3 phi=vec3(phi21)+phi23;vec3 R123=clamp(R12*R23,1e-5,0.9999);vec3 r123=sqrt(R123);vec3 Rs=square(T121)*R23/(vec3(1.0)-R123);vec3 C0=R12+Rs;I=C0;vec3 Cm=Rs-T121;for (int m=1; m<=2; ++m) +{Cm*=r123;vec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);I+=Cm*Sm;} +return max(I,vec3(0.0));} +#endif +float normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG) +{float a2=square(alphaG);float d=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);} +#ifdef SHEEN +float normalDistributionFunction_CharlieSheen(float NdotH,float alphaG) +{float invR=1./alphaG;float cos2h=NdotH*NdotH;float sin2h=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);} +#endif +#ifdef ANISOTROPIC +float normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {float a2=alphaTB.x*alphaTB.y;vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);float v2=dot(v,v);float w2=a2/v2;return a2*w2*w2*RECIPROCAL_PI;} +#endif +#ifdef BRDF_V_HEIGHT_CORRELATED +float smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) { +#ifdef MOBILE +float GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL); +#else +float a2=alphaG*alphaG;float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL); +#endif +} +#else +float smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG) +{ +#ifdef MOBILE +return 1.0/(dot+alphaG+(1.0-alphaG)*dot )); +#else +float alphaSquared=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot)); +#endif +} +float smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG) +{float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;} +#endif +#ifdef ANISOTROPIC +float smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));float v=0.5/(lambdaV+lambdaL);return v;} +#endif +#ifdef CLEARCOAT +float visibility_Kelemen(float VdotH) {return 0.25/(VdotH*VdotH); } +#endif +#ifdef SHEEN +float visibility_Ashikhmin(float NdotL,float NdotV) +{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));} +/* NOT USED +#ifdef SHEEN_SOFTER +float l(float x,float alphaG) +{float oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);float a=mix(21.5473,25.3245,oneMinusAlphaSq);float b=mix(3.82987,3.32435,oneMinusAlphaSq);float c=mix(0.19823,0.16801,oneMinusAlphaSq);float d=mix(-1.97760,-1.27393,oneMinusAlphaSq);float e=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;} +float lambdaSheen(float cosTheta,float alphaG) +{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));} +float visibility_CharlieSheen(float NdotL,float NdotV,float alphaG) +{float G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);} +#endif +*/ +#endif +float diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;float fresnel = +(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) * +(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;} +#ifdef SS_TRANSLUCENCY +vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);} +float computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);} +#endif +`;ShaderStore.IncludesShadersStore.pbrBRDFFunctions=sz;let sW=`#ifdef NUM_SAMPLES +#if NUM_SAMPLES>0 +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +float radicalInverse_VdC(uint bits) +{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } +vec2 hammersley(uint i,uint N) +{return vec2(float(i)/float(N),radicalInverse_VdC(i));} +#else +float vanDerCorpus(int n,int base) +{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) +{if(n>0) +{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} +return result;} +vec2 hammersley(int i,int N) +{return vec2(float(i)/float(N),vanDerCorpus(i,2));} +#endif +float log4(float x) {return log2(x)/2.;} +const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; +#define inline +vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) +{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +for(uint i=0u; i<NUM_SAMPLES; ++i) +#else +for(int i=0; i<NUM_SAMPLES; ++i) +#endif +{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 Ls=hemisphereCosSample(Xi);Ls=normalize(Ls);vec3 Ns=vec3(0.,0.,1.);float NoL=dot(Ns,Ls);if (NoL>0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +result+=c;}} +result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} +#define inline +vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) +{vec3 n=normalize(inputN);if (alphaG==0.) {vec3 c=textureCube(inputTexture,n).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +for(uint i=0u; i<NUM_SAMPLES; ++i) +#else +for(int i=0; i<NUM_SAMPLES; ++i) +#endif +{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);float NoV=1.;float NoH=H.z;float NoH2=H.z*H.z;float NoL=2.*NoH2-1.;vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +result+=c*NoL;}} +result=result/weight;return result;}} +#endif +#endif +`;ShaderStore.IncludesShadersStore.hdrFilteringFunctions=sW;let sH=`#define CLEARCOATREFLECTANCE90 1.0 +struct lightingInfo +{vec3 diffuse; +#ifdef SPECULARTERM +vec3 specular; +#endif +#ifdef CLEARCOAT +vec4 clearCoat; +#endif +#ifdef SHEEN +vec3 sheen; +#endif +};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { +#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) +float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; +#else +return roughness; +#endif +} +vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} +vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} +#define inline +vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} +#ifdef SS_TRANSLUCENCY +vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} +#endif +#ifdef SPECULARTERM +vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); +#ifdef BRDF_V_HEIGHT_CORRELATED +float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); +#else +float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); +#endif +vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef ANISOTROPIC +vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef CLEARCOAT +vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( +clearCoatTerm*info.attenuation*NccdotL*lightColor, +1.0-fresnel +);} +vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} +#endif +#ifdef SHEEN +vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER +float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); +#else */ +float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ +float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} +#endif +`;ShaderStore.IncludesShadersStore.pbrDirectLightingFunctions=sH;let sX=`#if defined(REFLECTION) || defined(SS_REFRACTION) +float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} +float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} +#endif +#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) +float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} +#endif +#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) +float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} +#endif +#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) +#define UNPACK_LOD(x) (1.0-x)*255.0 +float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} +#endif +`;ShaderStore.IncludesShadersStore.pbrIBLFunctions=sX;let sY=`struct albedoOpacityOutParams +{vec3 surfaceAlbedo;float alpha;}; +#define pbr_inline +void albedoOpacityBlock( +in vec4 vAlbedoColor, +#ifdef ALBEDO +in vec4 albedoTexture, +in vec2 albedoInfos, +#endif +#ifdef OPACITY +in vec4 opacityMap, +in vec2 vOpacityInfos, +#endif +#ifdef DETAIL +in vec4 detailColor, +in vec4 vDetailInfos, +#endif +#ifdef DECAL +in vec4 decalColor, +in vec4 vDecalInfos, +#endif +out albedoOpacityOutParams outParams +) +{vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; +#ifdef ALBEDO +#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) +alpha*=albedoTexture.a; +#endif +#ifdef GAMMAALBEDO +surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); +#else +surfaceAlbedo*=albedoTexture.rgb; +#endif +surfaceAlbedo*=albedoInfos.y; +#endif +#ifndef DECAL_AFTER_DETAIL +#include<decalFragment> +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +surfaceAlbedo*=vColor.rgb; +#endif +#ifdef DETAIL +float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; +#endif +#ifdef DECAL_AFTER_DETAIL +#include<decalFragment> +#endif +#define CUSTOM_FRAGMENT_UPDATE_ALBEDO +#ifdef OPACITY +#ifdef OPACITYRGB +alpha=getLuminance(opacityMap.rgb); +#else +alpha*=opacityMap.a; +#endif +alpha*=vOpacityInfos.y; +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) +#ifdef ALPHATEST +#if DEBUGMODE != 88 +if (alpha<ALPHATESTVALUE) +discard; +#endif +#ifndef ALPHABLEND +alpha=1.0; +#endif +#endif +#endif +outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;} +`;ShaderStore.IncludesShadersStore.pbrBlockAlbedoOpacity=sY;let sj=`struct reflectivityOutParams +{float microSurface;float roughness;vec3 surfaceReflectivityColor; +#ifdef METALLICWORKFLOW +vec3 surfaceAlbedo; +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +vec3 ambientOcclusionColor; +#endif +#if DEBUGMODE>0 +#ifdef METALLICWORKFLOW +vec2 metallicRoughness; +#ifdef REFLECTIVITY +vec4 surfaceMetallicColorMap; +#endif +#ifndef FROSTBITE_REFLECTANCE +vec3 metallicF0; +#endif +#else +#ifdef REFLECTIVITY +vec4 surfaceReflectivityColorMap; +#endif +#endif +#endif +}; +#define pbr_inline +void reflectivityBlock( +in vec4 vReflectivityColor, +#ifdef METALLICWORKFLOW +in vec3 surfaceAlbedo, +in vec4 metallicReflectanceFactors, +#endif +#ifdef REFLECTIVITY +in vec3 reflectivityInfos, +in vec4 surfaceMetallicOrReflectivityColorMap, +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +in vec3 ambientOcclusionColorIn, +#endif +#ifdef MICROSURFACEMAP +in vec4 microSurfaceTexel, +#endif +#ifdef DETAIL +in vec4 detailColor, +in vec4 vDetailInfos, +#endif +out reflectivityOutParams outParams +) +{float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +vec2 metallicRoughness=surfaceReflectivityColor.rg; +#ifdef REFLECTIVITY +#if DEBUGMODE>0 +outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef AOSTOREINMETALMAPRED +vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); +#endif +#ifdef METALLNESSSTOREINMETALMAPBLUE +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; +#else +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; +#endif +#ifdef ROUGHNESSSTOREINMETALMAPALPHA +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; +#else +#ifdef ROUGHNESSSTOREINMETALMAPGREEN +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; +#endif +#endif +#endif +#ifdef DETAIL +float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); +#endif +#ifdef MICROSURFACEMAP +metallicRoughness.g*=microSurfaceTexel.r; +#endif +#if DEBUGMODE>0 +outParams.metallicRoughness=metallicRoughness; +#endif +#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS +microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; +#ifdef FROSTBITE_REFLECTANCE +outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); +#else +vec3 metallicF0=metallicReflectanceFactors.rgb; +#if DEBUGMODE>0 +outParams.metallicF0=metallicF0; +#endif +outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); +#endif +#else +#ifdef REFLECTIVITY +surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; +#if DEBUGMODE>0 +outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef MICROSURFACEFROMREFLECTIVITYMAP +microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; +#else +#ifdef MICROSURFACEAUTOMATIC +microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); +#endif +#ifdef MICROSURFACEMAP +microSurface*=microSurfaceTexel.r; +#endif +#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE +#endif +#endif +#endif +microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;} +`;ShaderStore.IncludesShadersStore.pbrBlockReflectivity=sj;let sK=`struct ambientOcclusionOutParams +{vec3 ambientOcclusionColor; +#if DEBUGMODE>0 && defined(AMBIENT) +vec3 ambientOcclusionColorMap; +#endif +}; +#define pbr_inline +void ambientOcclusionBlock( +#ifdef AMBIENT +in vec3 ambientOcclusionColorMap_, +in vec4 vAmbientInfos, +#endif +out ambientOcclusionOutParams outParams +) +{vec3 ambientOcclusionColor=vec3(1.,1.,1.); +#ifdef AMBIENT +vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; +#ifdef AMBIENTINGRAYSCALE +ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); +#endif +ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); +#if DEBUGMODE>0 +outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; +#endif +#endif +outParams.ambientOcclusionColor=ambientOcclusionColor;} +`;ShaderStore.IncludesShadersStore.pbrBlockAmbientOcclusion=sK;let sq=`#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +struct alphaFresnelOutParams +{float alpha;}; +#define pbr_inline +void alphaFresnelBlock( +in vec3 normalW, +in vec3 viewDirectionW, +in float alpha, +in float microSurface, +out alphaFresnelOutParams outParams +) +{float opacityPerceptual=alpha; +#ifdef LINEARALPHAFRESNEL +float opacity0=opacityPerceptual; +#else +float opacity0=opacityPerceptual*opacityPerceptual; +#endif +float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; +#ifdef ALPHATEST +if (outParams.alpha<ALPHATESTVALUE) +discard; +#ifndef ALPHABLEND +outParams.alpha=1.0; +#endif +#endif +} +#endif +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockAlphaFresnel=sq;let s$=`#ifdef ANISOTROPIC +struct anisotropicOutParams +{float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal; +#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE) +vec3 anisotropyMapData; +#endif +}; +#define pbr_inline +void anisotropicBlock( +in vec3 vAnisotropy, +in float roughness, +#ifdef ANISOTROPIC_TEXTURE +in vec3 anisotropyMapData, +#endif +in mat3 TBN, +in vec3 normalW, +in vec3 viewDirectionW, +out anisotropicOutParams outParams +) +{float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); +#ifdef ANISOTROPIC_TEXTURE +anisotropy*=anisotropyMapData.b; +#if DEBUGMODE>0 +outParams.anisotropyMapData=anisotropyMapData; +#endif +anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; +#ifdef ANISOTROPIC_LEGACY +anisotropyDirection.rg*=anisotropyMapData.rg; +#else +anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); +#endif +#endif +mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);} +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockAnisotropic=s$;let sQ=`#ifdef REFLECTION +struct reflectionOutParams +{vec4 environmentRadiance;vec3 environmentIrradiance; +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords; +#else +vec2 reflectionCoords; +#endif +#ifdef SS_TRANSLUCENCY +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +vec3 irradianceVector; +#endif +#endif +#endif +}; +#define pbr_inline +void createReflectionCoords( +in vec3 vPositionW, +in vec3 normalW, +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#ifdef REFLECTIONMAP_3D +out vec3 reflectionCoords +#else +out vec2 reflectionCoords +#endif +) +{ +#ifdef ANISOTROPIC +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); +#else +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +reflectionCoords=reflectionVector; +#else +reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +} +#define pbr_inline +#define inline +void sampleReflectionTexture( +in float alphaG, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +in float NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +in float roughness, +#endif +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +const vec3 reflectionCoords, +#else +in sampler2D reflectionSampler, +const vec2 reflectionCoords, +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +out vec4 environmentRadiance +) +{ +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); +#elif defined(LINEARSPECULARREFLECTION) +float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); +#else +float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); +#endif +#ifdef LODBASEDMICROSFURACE +reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; +#ifdef LODINREFLECTIONALPHA +float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); +#else +float requestedReflectionLOD=reflectionLOD; +#endif +#ifdef REALTIME_FILTERING +environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); +#else +environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); +#endif +#else +float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( +sampleReflection(reflectionSamplerHigh,reflectionCoords), +environmentMid, +lodReflectionNormalizedDoubled +);} else {environmentRadiance=mix( +environmentMid, +sampleReflection(reflectionSamplerLow,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#ifdef RGBDREFLECTION +environmentRadiance.rgb=fromRGBD(environmentRadiance); +#endif +#ifdef GAMMAREFLECTION +environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); +#endif +environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} +#define pbr_inline +#define inline +void reflectionBlock( +in vec3 vPositionW, +in vec3 normalW, +in float alphaG, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +in float NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +in float roughness, +#endif +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +#else +in sampler2D reflectionSampler, +#endif +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +in vec3 vEnvironmentIrradiance, +#endif +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +in mat4 reflectionMatrix, +#endif +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +in samplerCube irradianceSampler, +#else +in sampler2D irradianceSampler, +#endif +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +out reflectionOutParams outParams +) +{vec4 environmentRadiance=vec4(0.,0.,0.,0.); +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords=vec3(0.); +#else +vec2 reflectionCoords=vec2(0.); +#endif +createReflectionCoords( +vPositionW, +normalW, +#ifdef ANISOTROPIC +anisotropicOut, +#endif +reflectionCoords +);sampleReflectionTexture( +alphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +roughness, +#endif +#ifdef REFLECTIONMAP_3D +reflectionSampler, +reflectionCoords, +#else +reflectionSampler, +reflectionCoords, +#endif +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentRadiance +);vec3 environmentIrradiance=vec3(0.,0.,0.); +#ifdef USESPHERICALFROMREFLECTIONMAP +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +environmentIrradiance=vEnvironmentIrradiance; +#else +#ifdef ANISOTROPIC +vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; +#else +vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#if defined(REALTIME_FILTERING) +environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo); +#else +environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); +#endif +#ifdef SS_TRANSLUCENCY +outParams.irradianceVector=irradianceVector; +#endif +#endif +#elif defined(USEIRRADIANCEMAP) +vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; +#ifdef RGBDREFLECTION +environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); +#endif +#ifdef GAMMAREFLECTION +environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); +#endif +#endif +environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;} +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockReflection=sQ;let sZ=`#ifdef SHEEN +struct sheenOutParams +{float sheenIntensity;vec3 sheenColor;float sheenRoughness; +#ifdef SHEEN_LINKWITHALBEDO +vec3 surfaceAlbedo; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +float sheenAlbedoScaling; +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +vec3 finalSheenRadianceScaled; +#endif +#if DEBUGMODE>0 +#ifdef SHEEN_TEXTURE +vec4 sheenMapData; +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +vec3 sheenEnvironmentReflectance; +#endif +#endif +}; +#define pbr_inline +#define inline +void sheenBlock( +in vec4 vSheenColor, +#ifdef SHEEN_ROUGHNESS +in float vSheenRoughness, +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +in vec4 sheenMapRoughnessData, +#endif +#endif +in float roughness, +#ifdef SHEEN_TEXTURE +in vec4 sheenMapData, +in float sheenMapLevel, +#endif +in float reflectance, +#ifdef SHEEN_LINKWITHALBEDO +in vec3 baseColor, +in vec3 surfaceAlbedo, +#endif +#ifdef ENVIRONMENTBRDF +in float NdotV, +in vec3 environmentBrdf, +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +in vec2 AARoughnessFactors, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +in vec4 vLightingIntensity, +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +in vec3 reflectionCoords, +#else +in sampler2D reflectionSampler, +in vec2 reflectionCoords, +#endif +in float NdotVUnclamped, +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +in float seo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +in float eho, +#endif +#endif +out sheenOutParams outParams +) +{float sheenIntensity=vSheenColor.a; +#ifdef SHEEN_TEXTURE +#if DEBUGMODE>0 +outParams.sheenMapData=sheenMapData; +#endif +#endif +#ifdef SHEEN_LINKWITHALBEDO +float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#else +vec3 sheenColor=vSheenColor.rgb; +#ifdef SHEEN_TEXTURE +#ifdef SHEEN_GAMMATEXTURE +sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); +#else +sheenColor.rgb*=sheenMapData.rgb; +#endif +sheenColor.rgb*=sheenMapLevel; +#endif +#ifdef SHEEN_ROUGHNESS +float sheenRoughness=vSheenRoughness; +#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE +#if defined(SHEEN_TEXTURE) +sheenRoughness*=sheenMapData.a; +#endif +#elif defined(SHEEN_TEXTURE_ROUGHNESS) +#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL +sheenRoughness*=sheenMapData.a; +#else +sheenRoughness*=sheenMapRoughnessData.a; +#endif +#endif +#else +float sheenRoughness=roughness; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#endif +#if !defined(SHEEN_ALBEDOSCALING) +sheenIntensity*=(1.-reflectance); +#endif +sheenColor*=sheenIntensity; +#endif +#ifdef ENVIRONMENTBRDF +/*#ifdef SHEEN_SOFTER +vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); +#else*/ +#ifdef SHEEN_ROUGHNESS +vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); +#else +vec3 environmentSheenBrdf=environmentBrdf; +#endif +/*#endif*/ +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); +#ifdef SPECULARAA +sheenAlphaG+=AARoughnessFactors.y; +#endif +vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( +sheenAlphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +sheenRoughness, +#endif +reflectionSampler, +reflectionCoords, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentSheenRadiance +);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +sheenEnvironmentReflectance*=seo; +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +sheenEnvironmentReflectance*=eho; +#endif +#if DEBUGMODE>0 +outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; +#endif +outParams.finalSheenRadianceScaled= +environmentSheenRadiance.rgb * +sheenEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; +#endif +outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;} +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockSheen=sZ;let sJ=`struct clearcoatOutParams +{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; +#ifdef REFLECTION +vec3 finalClearCoatRadianceScaled; +#endif +#ifdef CLEARCOAT_TINT +vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; +#endif +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +vec3 energyConservationFactorClearCoat; +#endif +#if DEBUGMODE>0 +#ifdef CLEARCOAT_BUMP +mat3 TBNClearCoat; +#endif +#ifdef CLEARCOAT_TEXTURE +vec2 clearCoatMapData; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +vec4 clearCoatTintMapData; +#endif +#ifdef REFLECTION +vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; +#endif +float clearCoatNdotV; +#endif +}; +#ifdef CLEARCOAT +#define pbr_inline +#define inline +void clearcoatBlock( +in vec3 vPositionW, +in vec3 geometricNormalW, +in vec3 viewDirectionW, +in vec2 vClearCoatParams, +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +in vec4 clearCoatMapRoughnessData, +#endif +in vec3 specularEnvironmentR0, +#ifdef CLEARCOAT_TEXTURE +in vec2 clearCoatMapData, +#endif +#ifdef CLEARCOAT_TINT +in vec4 vClearCoatTintParams, +in float clearCoatColorAtDistance, +in vec4 vClearCoatRefractionParams, +#ifdef CLEARCOAT_TINT_TEXTURE +in vec4 clearCoatTintMapData, +#endif +#endif +#ifdef CLEARCOAT_BUMP +in vec2 vClearCoatBumpInfos, +in vec4 clearCoatBumpMapData, +in vec2 vClearCoatBumpUV, +#if defined(TANGENT) && defined(NORMAL) +in mat3 vTBN, +#else +in vec2 vClearCoatTangentSpaceParams, +#endif +#ifdef OBJECTSPACE_NORMALMAP +in mat4 normalMatrix, +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +in vec3 faceNormal, +#endif +#ifdef REFLECTION +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +in vec4 vLightingIntensity, +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +#else +in sampler2D reflectionSampler, +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +in float ambientMonochrome, +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +in float frontFacingMultiplier, +#endif +out clearcoatOutParams outParams +) +{float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE +clearCoatRoughness*=clearCoatMapData.y; +#endif +#if DEBUGMODE>0 +outParams.clearCoatMapData=clearCoatMapData; +#endif +#endif +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL +clearCoatRoughness*=clearCoatMapData.y; +#else +clearCoatRoughness*=clearCoatMapRoughnessData.y; +#endif +#endif +outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; +#ifdef CLEARCOAT_TINT +vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; +#ifdef CLEARCOAT_TINT_TEXTURE +#ifdef CLEARCOAT_TINT_GAMMATEXTURE +clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); +#else +clearCoatColor*=clearCoatTintMapData.rgb; +#endif +clearCoatThickness*=clearCoatTintMapData.a; +#if DEBUGMODE>0 +outParams.clearCoatTintMapData=clearCoatTintMapData; +#endif +#endif +outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; +#endif +#ifdef CLEARCOAT_REMAP_F0 +vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); +#else +vec3 specularEnvironmentR0Updated=specularEnvironmentR0; +#endif +outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; +#ifdef CLEARCOAT_BUMP +#ifdef NORMALXYSCALE +float clearCoatNormalScale=1.0; +#else +float clearCoatNormalScale=vClearCoatBumpInfos.y; +#endif +#if defined(TANGENT) && defined(NORMAL) +mat3 TBNClearCoat=vTBN; +#else +vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); +#endif +#if DEBUGMODE>0 +outParams.TBNClearCoat=TBNClearCoat; +#endif +#ifdef OBJECTSPACE_NORMALMAP +clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); +#else +clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; +#endif +outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); +#if DEBUGMODE>0 +outParams.clearCoatNdotV=clearCoatNdotV; +#endif +#ifdef CLEARCOAT_TINT +vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); +#endif +#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) +vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); +#endif +#if defined(REFLECTION) +float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); +#ifdef SPECULARAA +clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; +#endif +vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +clearCoatReflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +vec3 clearCoatReflectionCoords=clearCoatReflectionVector; +#else +vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +clearCoatReflectionCoords/=clearCoatReflectionVector.z; +#endif +clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; +#endif +sampleReflectionTexture( +clearCoatAlphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +clearCoatNdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +clearCoatRoughness, +#endif +reflectionSampler, +clearCoatReflectionCoords, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentClearCoatRadiance +); +#if DEBUGMODE>0 +outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; +#endif +#endif +#endif +#else +vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); +#endif +clearCoatEnvironmentReflectance*=clearCoatIntensity; +#if DEBUGMODE>0 +outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; +#endif +outParams.finalClearCoatRadianceScaled= +environmentClearCoatRadiance.rgb * +clearCoatEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(CLEARCOAT_TINT) +outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); +#endif +float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); +#endif +} +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockClearcoat=sJ;let s0=`struct iridescenceOutParams +{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; +#ifdef IRIDESCENCE +#define pbr_inline +#define inline +void iridescenceBlock( +in vec4 vIridescenceParams, +in float viewAngle, +in vec3 specularEnvironmentR0, +#ifdef IRIDESCENCE_TEXTURE +in vec2 iridescenceMapData, +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +in vec2 iridescenceThicknessMapData, +#endif +#ifdef CLEARCOAT +in float NdotVUnclamped, +#ifdef CLEARCOAT_TEXTURE +in vec2 clearCoatMapData, +#endif +#endif +out iridescenceOutParams outParams +) +{float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; +#ifdef IRIDESCENCE_TEXTURE +iridescenceIntensity*=iridescenceMapData.x; +#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE +iridescenceThicknessWeight=iridescenceMapData.g; +#endif +#endif +#if defined(IRIDESCENCE_THICKNESS_TEXTURE) +iridescenceThicknessWeight=iridescenceThicknessMapData.g; +#endif +float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; +#ifdef CLEARCOAT +float clearCoatIntensity=vClearCoatParams.x; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#endif +topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); +#endif +vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;} +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockIridescence=s0;let s1=`struct subSurfaceOutParams +{vec3 specularEnvironmentReflectance; +#ifdef SS_REFRACTION +vec3 finalRefraction;vec3 surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +float alpha; +#endif +#ifdef REFLECTION +float refractionFactorForIrradiance; +#endif +#endif +#ifdef SS_TRANSLUCENCY +vec3 transmittance;float translucencyIntensity; +#ifdef REFLECTION +vec3 refractionIrradiance; +#endif +#endif +#if DEBUGMODE>0 +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec4 thicknessMap; +#endif +#ifdef SS_REFRACTION +vec4 environmentRefraction;vec3 refractionTransmittance; +#endif +#endif +}; +#ifdef SUBSURFACE +#define pbr_inline +#define inline +void subSurfaceBlock( +in vec3 vSubSurfaceIntensity, +in vec2 vThicknessParam, +in vec4 vTintColor, +in vec3 normalW, +in vec3 specularEnvironmentReflectance, +#ifdef SS_THICKNESSANDMASK_TEXTURE +in vec4 thicknessMap, +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +in vec4 refractionIntensityMap, +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +in vec4 translucencyIntensityMap, +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +in mat4 reflectionMatrix, +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +in vec3 irradianceVector_, +#endif +#if defined(REALTIME_FILTERING) +in samplerCube reflectionSampler, +in vec2 vReflectionFilteringInfo, +#endif +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +in samplerCube irradianceSampler, +#else +in sampler2D irradianceSampler, +#endif +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +in vec3 surfaceAlbedo, +#endif +#ifdef SS_REFRACTION +in vec3 vPositionW, +in vec3 viewDirectionW, +in mat4 view, +in vec4 vRefractionInfos, +in mat4 refractionMatrix, +in vec4 vRefractionMicrosurfaceInfos, +in vec4 vLightingIntensity, +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +in float alpha, +#endif +#ifdef SS_LODINREFRACTIONALPHA +in float NdotVUnclamped, +#endif +#ifdef SS_LINEARSPECULARREFRACTION +in float roughness, +#endif +in float alphaG, +#ifdef SS_REFRACTIONMAP_3D +in samplerCube refractionSampler, +#ifndef LODBASEDMICROSFURACE +in samplerCube refractionSamplerLow, +in samplerCube refractionSamplerHigh, +#endif +#else +in sampler2D refractionSampler, +#ifndef LODBASEDMICROSFURACE +in sampler2D refractionSamplerLow, +in sampler2D refractionSamplerHigh, +#endif +#endif +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#ifdef REALTIME_FILTERING +in vec2 vRefractionFilteringInfo, +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +in vec3 refractionPosition, +in vec3 refractionSize, +#endif +#endif +#ifdef SS_TRANSLUCENCY +in vec3 vDiffusionDistance, +#endif +out subSurfaceOutParams outParams +) +{outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; +#ifdef SS_REFRACTION +float refractionIntensity=vSubSurfaceIntensity.x; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; +#endif +#endif +#ifdef SS_TRANSLUCENCY +float translucencyIntensity=vSubSurfaceIntensity.y; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +#if defined(SS_USE_GLTF_TEXTURES) +float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; +#else +float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; +#endif +#if DEBUGMODE>0 +outParams.thicknessMap=thicknessMap; +#endif +#ifdef SS_MASK_FROM_THICKNESS_TEXTURE +#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE) +#if defined(SS_USE_GLTF_TEXTURES) +refractionIntensity*=thicknessMap.r; +#else +refractionIntensity*=thicknessMap.g; +#endif +#endif +#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE) +translucencyIntensity*=thicknessMap.b; +#endif +#endif +#else +float thickness=vThicknessParam.y; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +#ifdef SS_USE_GLTF_TEXTURES +refractionIntensity*=refractionIntensityMap.r; +#else +refractionIntensity*=refractionIntensityMap.g; +#endif +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +translucencyIntensity*=translucencyIntensityMap.b; +#endif +#ifdef SS_TRANSLUCENCY +thickness=maxEps(thickness);vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; +#endif +#ifdef SS_REFRACTION +vec4 environmentRefraction=vec4(0.,0.,0.,0.); +#ifdef ANISOTROPIC +vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y); +#else +vec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y); +#endif +#ifdef SS_REFRACTIONMAP_OPPOSITEZ +refractionVector.z*=-1.0; +#endif +#ifdef SS_REFRACTIONMAP_3D +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); +#else +#ifdef SS_USE_THICKNESS_AS_DEPTH +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); +#endif +vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; +#endif +#ifdef SS_HAS_THICKNESS +float ior=vRefractionInfos.y; +#else +float ior=vRefractionMicrosurfaceInfos.w; +#endif +#ifdef SS_LODINREFRACTIONALPHA +float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); +#elif defined(SS_LINEARSPECULARREFRACTION) +float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); +#else +float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); +#endif +#ifdef LODBASEDMICROSFURACE +refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; +#ifdef SS_LODINREFRACTIONALPHA +float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); +#else +float requestedRefractionLOD=refractionLOD; +#endif +#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) +environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); +#else +environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); +#endif +#else +float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( +sampleRefraction(refractionSamplerHigh,refractionCoords), +environmentRefractionMid, +lodRefractionNormalizedDoubled +);} else {environmentRefraction=mix( +environmentRefractionMid, +sampleRefraction(refractionSamplerLow,refractionCoords), +lodRefractionNormalizedDoubled-1.0 +);} +#endif +#ifdef SS_RGBDREFRACTION +environmentRefraction.rgb=fromRGBD(environmentRefraction); +#endif +#ifdef SS_GAMMAREFRACTION +environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); +#endif +environmentRefraction.rgb*=vRefractionInfos.x; +#endif +#ifdef SS_REFRACTION +vec3 refractionTransmittance=vec3(refractionIntensity); +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); +#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) +float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; +#else +vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); +#endif +#ifdef SS_ALBEDOFORREFRACTIONTINT +environmentRefraction.rgb*=surfaceAlbedo.rgb; +#endif +outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); +#ifdef REFLECTION +outParams.refractionFactorForIrradiance=(1.-refractionIntensity); +#endif +#ifdef UNUSED_MULTIPLEBOUNCES +vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); +#endif +refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; +#if DEBUGMODE>0 +outParams.refractionTransmittance=refractionTransmittance; +#endif +outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; +#if DEBUGMODE>0 +outParams.environmentRefraction=environmentRefraction; +#endif +#endif +#if defined(REFLECTION) && defined(SS_TRANSLUCENCY) +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) +vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#else +vec3 irradianceVector=irradianceVector_; +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) +#if defined(REALTIME_FILTERING) +vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo); +#else +vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); +#endif +#elif defined(USEIRRADIANCEMAP) +#ifdef REFLECTIONMAP_3D +vec3 irradianceCoords=irradianceVector; +#else +vec2 irradianceCoords=irradianceVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +irradianceCoords/=irradianceVector.z; +#endif +irradianceCoords.y=1.0-irradianceCoords.y; +#endif +vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); +#ifdef RGBDREFLECTION +refractionIrradiance.rgb=fromRGBD(refractionIrradiance); +#endif +#ifdef GAMMAREFLECTION +refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); +#endif +#else +vec4 refractionIrradiance=vec4(0.); +#endif +refractionIrradiance.rgb*=transmittance; +#ifdef SS_ALBEDOFORTRANSLUCENCYTINT +refractionIrradiance.rgb*=surfaceAlbedo.rgb; +#endif +outParams.refractionIrradiance=refractionIrradiance.rgb; +#endif +} +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockSubSurface=s1;let s2=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; +#endif +vec3 geometricNormalW=normalW; +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockNormalGeometric=s2;let s3=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) +vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; +#if defined(TWOSIDEDLIGHTING) +faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; +#endif +normalW*=sign(dot(normalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockNormalFinal=s3;let s4=`#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +#ifdef GAMMALIGHTMAP +lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockLightmapInit=s4;let s5=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); +#ifdef SPECULARAA +alphaG+=AARoughnessFactors.y; +#endif +#if defined(ENVIRONMENTBRDF) +vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +#ifdef AMBIENTINGRAYSCALE +float ambientMonochrome=aoOut.ambientOcclusionColor.r; +#else +float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); +#endif +float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); +#endif +#endif +#endif +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockGeometryInfo=s5;let s6=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); +#else +vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); +#endif +#ifdef ALPHAFRESNEL +float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockReflectance0=s6;let s8=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); +#ifdef RADIANCEOCCLUSION +specularEnvironmentReflectance*=seo; +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +specularEnvironmentReflectance*=eho; +#endif +#endif +#endif +#else +vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); +#endif +#ifdef CLEARCOAT +specularEnvironmentReflectance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +specularEnvironmentReflectance*=clearcoatOut.absorption; +#endif +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockReflectance=s8;let s7=`vec3 diffuseBase=vec3(0.,0.,0.); +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +#ifdef CLEARCOAT +vec3 clearCoatBase=vec3(0.,0.,0.); +#endif +#ifdef SHEEN +vec3 sheenBase=vec3(0.,0.,0.); +#endif +preLightingInfo preInfo;lightingInfo info;float shadow=1.; +float aggShadow=0.;float numLights=0.; +#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +vec3 absorption=vec3(0.); +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockDirectLighting=s7;let s9=`aggShadow=aggShadow/numLights; +#if defined(ENVIRONMENTBRDF) +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); +#endif +#endif +#ifndef METALLICWORKFLOW +#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION +surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; +#endif +#endif +#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) +surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; +#endif +#ifdef REFLECTION +vec3 finalIrradiance=reflectionOut.environmentIrradiance; +#if defined(CLEARCOAT) +finalIrradiance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +finalIrradiance*=clearcoatOut.absorption; +#endif +#endif +#if defined(SS_REFRACTION) +finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; +#endif +#if defined(SS_TRANSLUCENCY) +finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; +#endif +finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalSpecularScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalSpecularScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef REFLECTION +vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalRadianceScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalRadianceScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef SHEEN +vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; +#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef CLEARCOAT +vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; +#ifdef CLEARCOAT_TINT +subSurfaceOut.finalRefraction*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef ALPHABLEND +float luminanceOverAlpha=0.0; +#if defined(REFLECTION) && defined(RADIANCEOVERALPHA) +luminanceOverAlpha+=getLuminance(finalRadianceScaled); +#if defined(CLEARCOAT) +luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); +#endif +#endif +#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) +luminanceOverAlpha+=getLuminance(finalSpecularScaled); +#endif +#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) +luminanceOverAlpha+=getLuminance(finalClearCoatScaled); +#endif +#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) +alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); +#endif +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockFinalLitComponents=s9;let ae=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; +#ifdef EMISSIVE +vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; +#ifdef GAMMAEMISSIVE +finalEmissive*=toLinearSpace(emissiveColorTex.rgb); +#else +finalEmissive*=emissiveColorTex.rgb; +#endif +finalEmissive*= vEmissiveInfos.y; +#endif +finalEmissive*=vLightingIntensity.y; +#ifdef AMBIENT +vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); +#else +vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; +#endif +finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; +`;ShaderStore.IncludesShadersStore.pbrBlockFinalUnlitComponents=ae;let at=`vec4 finalColor=vec4( +#ifndef UNLIT +#ifdef REFLECTION +finalIrradiance + +#endif +#ifdef SPECULARTERM +finalSpecularScaled + +#endif +#ifdef SHEEN +finalSheenScaled + +#endif +#ifdef CLEARCOAT +finalClearCoatScaled + +#endif +#ifdef REFLECTION +finalRadianceScaled + +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled + +#endif +#ifdef CLEARCOAT +clearcoatOut.finalClearCoatRadianceScaled + +#endif +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction + +#endif +#endif +finalAmbient + +finalDiffuse, +alpha); +#ifdef LIGHTMAP +#ifndef LIGHTMAPEXCLUDED +#ifdef USELIGHTMAPASSHADOWMAP +finalColor.rgb*=lightmapColor.rgb; +#else +finalColor.rgb+=lightmapColor.rgb; +#endif +#endif +#endif +finalColor.rgb+=finalEmissive; +#define CUSTOM_FRAGMENT_BEFORE_FOG +finalColor=max(finalColor,0.0); +`;ShaderStore.IncludesShadersStore.pbrBlockFinalColorComposition=at;let ai=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) +#if !defined(SKIPFINALCOLORCLAMP) +finalColor.rgb=clamp(finalColor.rgb,0.,30.0); +#endif +#else +finalColor=applyImageProcessing(finalColor); +#endif +finalColor.a*=visibility; +#ifdef PREMULTIPLYALPHA +finalColor.rgb*=finalColor.a; +#endif +`;ShaderStore.IncludesShadersStore.pbrBlockImageProcessing=ai;let ar=`#if DEBUGMODE>0 +if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { +#if DEBUGMODE==1 +gl_FragColor.rgb=vPositionW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==2 && defined(NORMAL) +gl_FragColor.rgb=vNormalW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) +gl_FragColor.rgb=TBN[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) +gl_FragColor.rgb=TBN[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==5 +gl_FragColor.rgb=normalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==6 && defined(MAINUV1) +gl_FragColor.rgb=vec3(vMainUV1,0.0); +#elif DEBUGMODE==7 && defined(MAINUV2) +gl_FragColor.rgb=vec3(vMainUV2,0.0); +#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==10 && defined(CLEARCOAT) +gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==11 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicNormal; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==12 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicTangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==13 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==20 && defined(ALBEDO) +gl_FragColor.rgb=albedoTexture.rgb; +#ifndef GAMMAALBEDO +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==21 && defined(AMBIENT) +gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; +#elif DEBUGMODE==22 && defined(OPACITY) +gl_FragColor.rgb=opacityMap.rgb; +#elif DEBUGMODE==23 && defined(EMISSIVE) +gl_FragColor.rgb=emissiveColorTex.rgb; +#ifndef GAMMAEMISSIVE +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==24 && defined(LIGHTMAP) +gl_FragColor.rgb=lightmapColor.rgb; +#ifndef GAMMALIGHTMAP +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; +#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); +#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; +#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) +gl_FragColor.rgb=sheenOut.sheenMapData.rgb; +#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) +gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; +#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) +gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; +#elif DEBUGMODE==32 && defined(BUMP) +gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; +#elif DEBUGMODE==40 && defined(SS_REFRACTION) +gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==41 && defined(REFLECTION) +gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) +gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==50 +gl_FragColor.rgb=diffuseBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==51 && defined(SPECULARTERM) +gl_FragColor.rgb=specularBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==52 && defined(CLEARCOAT) +gl_FragColor.rgb=clearCoatBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==53 && defined(SHEEN) +gl_FragColor.rgb=sheenBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==54 && defined(REFLECTION) +gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==60 +gl_FragColor.rgb=surfaceAlbedo.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==61 +gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==62 && defined(METALLICWORKFLOW) +gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); +#elif DEBUGMODE==71 && defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.metallicF0; +#elif DEBUGMODE==63 +gl_FragColor.rgb=vec3(roughness); +#elif DEBUGMODE==64 +gl_FragColor.rgb=vec3(alphaG); +#elif DEBUGMODE==65 +gl_FragColor.rgb=vec3(NdotV); +#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==67 && defined(CLEARCOAT) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); +#elif DEBUGMODE==68 && defined(CLEARCOAT) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); +#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) +gl_FragColor.rgb=subSurfaceOut.transmittance; +#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) +gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; +#elif DEBUGMODE==72 +gl_FragColor.rgb=vec3(microSurface); +#elif DEBUGMODE==73 +gl_FragColor.rgb=vAlbedoColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) +gl_FragColor.rgb=vReflectivityColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==75 +gl_FragColor.rgb=vEmissiveColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) +gl_FragColor.rgb=vec3(seo); +#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) +gl_FragColor.rgb=vec3(eho); +#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) +gl_FragColor.rgb=vec3(energyConservationFactor); +#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +gl_FragColor.rgb=specularEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) +gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==86 && defined(ALPHABLEND) +gl_FragColor.rgb=vec3(luminanceOverAlpha); +#elif DEBUGMODE==87 +gl_FragColor.rgb=vec3(alpha); +#elif DEBUGMODE==88 && defined(ALBEDO) +gl_FragColor.rgb=vec3(albedoTexture.a); +#else +float stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); +#endif +gl_FragColor.rgb*=vDebugMode.y; +#ifdef DEBUGMODE_NORMALIZE +gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; +#endif +#ifdef DEBUGMODE_GAMMA +gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); +#endif +gl_FragColor.a=1.0; +#ifdef PREPASS +gl_FragData[0]=toLinearSpace(gl_FragColor); +gl_FragData[1]=vec4(0.,0.,0.,0.); +#endif +#ifdef DEBUGMODE_FORCERETURN +return; +#endif +} +#endif +`;ShaderStore.IncludesShadersStore.pbrDebug=ar;let as=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#extension GL_OES_standard_derivatives : enable +#endif +#ifdef LODBASEDMICROSFURACE +#extension GL_EXT_shader_texture_lod : enable +#endif +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include<prePassDeclaration>[SCENE_MRT_COUNT] +precision highp float; +#include<oitDeclaration> +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE +#endif +#include<__decl__pbrFragment> +#include<pbrFragmentExtraDeclaration> +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include<pbrFragmentSamplersDeclaration> +#include<imageProcessingDeclaration> +#include<clipPlaneFragmentDeclaration> +#include<logDepthDeclaration> +#include<fogFragmentDeclaration> +#include<helperFunctions> +#include<subSurfaceScatteringFunctions> +#include<importanceSampling> +#include<pbrHelperFunctions> +#include<imageProcessingFunctions> +#include<shadowsFragmentFunctions> +#include<harmonicsFunctions> +#include<pbrDirectLightingSetupFunctions> +#include<pbrDirectLightingFalloffFunctions> +#include<pbrBRDFFunctions> +#include<hdrFilteringFunctions> +#include<pbrDirectLightingFunctions> +#include<pbrIBLFunctions> +#include<bumpFragmentMainFunctions> +#include<bumpFragmentFunctions> +#ifdef REFLECTION +#include<reflectionFunction> +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +#include<pbrBlockAlbedoOpacity> +#include<pbrBlockReflectivity> +#include<pbrBlockAmbientOcclusion> +#include<pbrBlockAlphaFresnel> +#include<pbrBlockAnisotropic> +#include<pbrBlockReflection> +#include<pbrBlockSheen> +#include<pbrBlockClearcoat> +#include<pbrBlockIridescence> +#include<pbrBlockSubSurface> +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +#include<pbrBlockNormalGeometric> +#include<bumpFragment> +#include<pbrBlockNormalFinal> +albedoOpacityOutParams albedoOpacityOut; +#ifdef ALBEDO +vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#endif +#ifdef DECAL +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#endif +albedoOpacityBlock( +vAlbedoColor, +#ifdef ALBEDO +albedoTexture, +vAlbedoInfos, +#endif +#ifdef OPACITY +opacityMap, +vOpacityInfos, +#endif +#ifdef DETAIL +detailColor, +vDetailInfos, +#endif +#ifdef DECAL +decalColor, +vDecalInfos, +#endif +albedoOpacityOut +);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; +#define CUSTOM_FRAGMENT_UPDATE_ALPHA +#include<depthPrePass> +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +ambientOcclusionOutParams aoOut; +#ifdef AMBIENT +vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; +#endif +ambientOcclusionBlock( +#ifdef AMBIENT +ambientOcclusionColorMap, +vAmbientInfos, +#endif +aoOut +); +#include<pbrBlockLightmapInit> +#ifdef UNLIT +vec3 diffuseBase=vec3(1.,1.,1.); +#else +vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; +#if defined(REFLECTIVITY) +vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; +#ifndef METALLICWORKFLOW +#ifdef REFLECTIVITY_GAMMA +surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); +#endif +surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; +#endif +#endif +#if defined(MICROSURFACEMAP) +vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; +#endif +#ifdef METALLICWORKFLOW +vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; +#ifdef REFLECTANCE +vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); +#ifdef REFLECTANCE_GAMMA +reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); +#endif +metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; +#endif +#ifdef METALLIC_REFLECTANCE +vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); +#ifdef METALLIC_REFLECTANCE_GAMMA +metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); +#endif +#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY +metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; +#endif +metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; +#endif +#endif +reflectivityBlock( +vReflectivityColor, +#ifdef METALLICWORKFLOW +surfaceAlbedo, +metallicReflectanceFactors, +#endif +#ifdef REFLECTIVITY +vReflectivityInfos, +surfaceMetallicOrReflectivityColorMap, +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +aoOut.ambientOcclusionColor, +#endif +#ifdef MICROSURFACEMAP +microSurfaceTexel, +#endif +#ifdef DETAIL +detailColor, +vDetailInfos, +#endif +reflectivityOut +);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; +#ifdef METALLICWORKFLOW +surfaceAlbedo=reflectivityOut.surfaceAlbedo; +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; +#endif +#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +alphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock( +normalW, +viewDirectionW, +alpha, +microSurface, +alphaFresnelOut +);alpha=alphaFresnelOut.alpha; +#endif +#endif +#include<pbrBlockGeometryInfo> +#ifdef ANISOTROPIC +anisotropicOutParams anisotropicOut; +#ifdef ANISOTROPIC_TEXTURE +vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; +#endif +anisotropicBlock( +vAnisotropy, +roughness, +#ifdef ANISOTROPIC_TEXTURE +anisotropyMapData, +#endif +TBN, +normalW, +viewDirectionW, +anisotropicOut +); +#endif +#ifdef REFLECTION +reflectionOutParams reflectionOut; +#ifndef USE_CUSTOM_REFLECTION +reflectionBlock( +vPositionW, +normalW, +alphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#ifdef ANISOTROPIC +anisotropicOut, +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +roughness, +#endif +reflectionSampler, +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +vEnvironmentIrradiance, +#endif +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +reflectionMatrix, +#endif +#endif +#ifdef USEIRRADIANCEMAP +irradianceSampler, +#endif +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +reflectionOut +); +#else +#define CUSTOM_REFLECTION +#endif +#endif +#include<pbrBlockReflectance0> +#ifdef SHEEN +sheenOutParams sheenOut; +#ifdef SHEEN_TEXTURE +vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); +#endif +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; +#endif +sheenBlock( +vSheenColor, +#ifdef SHEEN_ROUGHNESS +vSheenRoughness, +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +sheenMapRoughnessData, +#endif +#endif +roughness, +#ifdef SHEEN_TEXTURE +sheenMapData, +vSheenInfos.y, +#endif +reflectance, +#ifdef SHEEN_LINKWITHALBEDO +baseColor, +surfaceAlbedo, +#endif +#ifdef ENVIRONMENTBRDF +NdotV, +environmentBrdf, +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +AARoughnessFactors, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +vLightingIntensity, +reflectionSampler, +reflectionOut.reflectionCoords, +NdotVUnclamped, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +seo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +eho, +#endif +#endif +sheenOut +); +#ifdef SHEEN_LINKWITHALBEDO +surfaceAlbedo=sheenOut.surfaceAlbedo; +#endif +#endif +#ifdef CLEARCOAT +#ifdef CLEARCOAT_TEXTURE +vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; +#endif +#endif +#ifdef IRIDESCENCE +iridescenceOutParams iridescenceOut; +#ifdef IRIDESCENCE_TEXTURE +vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; +#endif +iridescenceBlock( +vIridescenceParams, +NdotV, +specularEnvironmentR0, +#ifdef IRIDESCENCE_TEXTURE +iridescenceMapData, +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +iridescenceThicknessMapData, +#endif +#ifdef CLEARCOAT +NdotVUnclamped, +#ifdef CLEARCOAT_TEXTURE +clearCoatMapData, +#endif +#endif +iridescenceOut +);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; +#endif +clearcoatOutParams clearcoatOut; +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); +#endif +#ifdef CLEARCOAT_BUMP +vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); +#endif +clearcoatBlock( +vPositionW, +geometricNormalW, +viewDirectionW, +vClearCoatParams, +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +clearCoatMapRoughnessData, +#endif +specularEnvironmentR0, +#ifdef CLEARCOAT_TEXTURE +clearCoatMapData, +#endif +#ifdef CLEARCOAT_TINT +vClearCoatTintParams, +clearCoatColorAtDistance, +vClearCoatRefractionParams, +#ifdef CLEARCOAT_TINT_TEXTURE +clearCoatTintMapData, +#endif +#endif +#ifdef CLEARCOAT_BUMP +vClearCoatBumpInfos, +clearCoatBumpMapData, +vClearCoatBumpUV, +#if defined(TANGENT) && defined(NORMAL) +vTBN, +#else +vClearCoatTangentSpaceParams, +#endif +#ifdef OBJECTSPACE_NORMALMAP +normalMatrix, +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +faceNormal, +#endif +#ifdef REFLECTION +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +vLightingIntensity, +reflectionSampler, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +ambientMonochrome, +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +(gl_FrontFacing ? 1. : -1.), +#endif +clearcoatOut +); +#else +clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; +#endif +#include<pbrBlockReflectance> +subSurfaceOutParams subSurfaceOut; +#ifdef SUBSURFACE +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); +#endif +subSurfaceBlock( +vSubSurfaceIntensity, +vThicknessParam, +vTintColor, +normalW, +specularEnvironmentReflectance, +#ifdef SS_THICKNESSANDMASK_TEXTURE +thicknessMap, +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +refractionIntensityMap, +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +translucencyIntensityMap, +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +reflectionMatrix, +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +reflectionOut.irradianceVector, +#endif +#if defined(REALTIME_FILTERING) +reflectionSampler, +vReflectionFilteringInfo, +#endif +#endif +#ifdef USEIRRADIANCEMAP +irradianceSampler, +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +surfaceAlbedo, +#endif +#ifdef SS_REFRACTION +vPositionW, +viewDirectionW, +view, +vRefractionInfos, +refractionMatrix, +vRefractionMicrosurfaceInfos, +vLightingIntensity, +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha, +#endif +#ifdef SS_LODINREFRACTIONALPHA +NdotVUnclamped, +#endif +#ifdef SS_LINEARSPECULARREFRACTION +roughness, +#endif +alphaG, +refractionSampler, +#ifndef LODBASEDMICROSFURACE +refractionSamplerLow, +refractionSamplerHigh, +#endif +#ifdef ANISOTROPIC +anisotropicOut, +#endif +#ifdef REALTIME_FILTERING +vRefractionFilteringInfo, +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +vRefractionPosition, +vRefractionSize, +#endif +#endif +#ifdef SS_TRANSLUCENCY +vDiffusionDistance, +#endif +subSurfaceOut +); +#ifdef SS_REFRACTION +surfaceAlbedo=subSurfaceOut.surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha=subSurfaceOut.alpha; +#endif +#endif +#else +subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; +#endif +#include<pbrBlockDirectLighting> +#include<lightFragment>[0..maxSimultaneousLights] +#include<pbrBlockFinalLitComponents> +#endif +#include<pbrBlockFinalUnlitComponents> +#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION +#include<pbrBlockFinalColorComposition> +#include<logDepthFragment> +#include<fogFragment>(color,finalColor) +#include<pbrBlockImageProcessing> +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +vec3 sqAlbedo=sqrt(surfaceAlbedo); +#endif +#ifdef PREPASS_IRRADIANCE +vec3 irradiance=finalDiffuse; +#ifndef UNLIT +#ifdef REFLECTION +irradiance+=finalIrradiance; +#endif +#endif +#ifdef SS_SCATTERING +gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); +irradiance/=sqAlbedo; +#else +gl_FragData[0]=finalColor; +float scatteringDiffusionProfile=255.; +#endif +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); +#else +gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#ifndef UNLIT +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=finalColor; +#endif +#include<oitFragment> +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} +#endif +#include<pbrDebug> +#define CUSTOM_FRAGMENT_MAIN_END +} +`;ShaderStore.ShadersStore.pbrPixelShader=as;let aa=`uniform mat4 view;uniform mat4 viewProjection; +#ifdef ALBEDO +uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; +#endif +#ifdef AMBIENT +uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; +#endif +#ifdef OPACITY +uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; +#endif +#ifdef REFLECTIVITY +uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; +#endif +#ifdef METALLIC_REFLECTANCE +uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; +#endif +#ifdef REFLECTANCE +uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; +#endif +#ifdef MICROSURFACEMAP +uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; +#endif +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform vec4 vClearCoatInfos; +#endif +#ifdef CLEARCOAT_TEXTURE +uniform mat4 clearCoatMatrix; +#endif +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS +uniform mat4 clearCoatRoughnessMatrix; +#endif +#ifdef CLEARCOAT_BUMP +uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; +#endif +#ifdef CLEARCOAT_TINT_TEXTURE +uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; +#endif +#endif +#ifdef IRIDESCENCE +#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) +uniform vec4 vIridescenceInfos; +#endif +#ifdef IRIDESCENCE_TEXTURE +uniform mat4 iridescenceMatrix; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +uniform mat4 iridescenceThicknessMatrix; +#endif +#endif +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_TEXTURE +uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; +#endif +#endif +#ifdef SHEEN +#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) +uniform vec4 vSheenInfos; +#endif +#ifdef SHEEN_TEXTURE +uniform mat4 sheenMatrix; +#endif +#ifdef SHEEN_TEXTURE_ROUGHNESS +uniform mat4 sheenRoughnessMatrix; +#endif +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; +#endif +#endif +#ifdef NORMAL +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; +#else +uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; +#endif +#endif +#endif +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos;uniform mat4 detailMatrix; +#endif +#include<decalVertexDeclaration> +#define ADDITIONAL_VERTEX_DECLARATION +`;ShaderStore.IncludesShadersStore.pbrVertexDeclaration=aa;let an=`precision highp float; +#include<__decl__pbrVertex> +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include<uvAttributeDeclaration>[2..7] +#include<mainUVVaryingDeclaration>[1..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include<helperFunctions> +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<instancesDeclaration> +#include<prePassVertexDeclaration> +#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) +#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) +#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) +#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) +#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) +#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +#ifdef CLEARCOAT +#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) +#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) +#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) +#endif +#ifdef IRIDESCENCE +#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) +#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) +#endif +#ifdef SHEEN +#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) +#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#endif +#ifdef ANISOTROPIC +#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) +#endif +#ifdef SUBSURFACE +#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) +#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) +#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) +#endif +varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#include<harmonicsFunctions> +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include<bumpVertexDeclaration> +#include<clipPlaneVertexDeclaration> +#include<fogVertexDeclaration> +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include<logDepthDeclaration> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include<instancesVertex> +#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); +#include<prePassVertex> +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#if DEBUGMODE>0 +vClipSpacePosition=gl_Position; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#include<uvVariableDeclaration>[2..7] +#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#ifdef CLEARCOAT +#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) +#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) +#endif +#ifdef IRIDESCENCE +#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) +#endif +#ifdef SHEEN +#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z) +#endif +#ifdef ANISOTROPIC +#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) +#endif +#ifdef SUBSURFACE +#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) +#endif +#include<bumpVertex> +#include<clipPlaneVertex> +#include<fogVertex> +#include<shadowsVertex>[0..maxSimultaneousLights] +#include<vertexColorMixing> +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#include<logDepthVertex> +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.pbrVertexShader=an;let MaterialClearCoatDefines=class MaterialClearCoatDefines extends MaterialDefines{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}};let pbrClearCoatConfiguration_PBRClearCoatConfiguration=class pbrClearCoatConfiguration_PBRClearCoatConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new MaterialClearCoatDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,this.indexOfRefraction=pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=math_color_Color3.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;let r=this._material._disableBumpMap;return!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.ClearCoatTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!MaterialFlags.ClearCoatTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())&&(!i.getCaps().standardDerivatives||!this._bumpTexture||!MaterialFlags.ClearCoatBumpTextureEnabled||!!r||!!this._bumpTexture.isReady())&&(!this._isTintEnabled||!this._tintTexture||!MaterialFlags.ClearCoatTintTextureEnabled||!!this._tintTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_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.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.ClearCoatTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&MaterialFlags.ClearCoatTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&MaterialFlags.ClearCoatBumpTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,r){var s,a,n,o,l,h,c,u;if(!this._isEnabled)return;let d=r.materialDefines,_=this._material.isFrozen,p=this._material._disableBumpMap,f=this._material._invertNormalMapX,m=this._material._invertNormalMapY,g=d.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!_||!e.isSync){g&&MaterialFlags.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),MaterialHelper.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&MaterialFlags.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",null!==(a=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==a?a:0,null!==(o=null===(n=this._texture)||void 0===n?void 0:n.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(u=null===(c=this._textureRoughness)||void 0===c?void 0:c.level)&&void 0!==u?u:0),this._texture&&MaterialHelper.BindTextureMatrix(this._texture,e,"clearCoat"),!this._textureRoughness||g||d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE||MaterialHelper.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&MaterialFlags.ClearCoatTextureEnabled&&!p&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),MaterialHelper.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",f?1:-1,m?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",f?-1:1,m?-1:1)),this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),MaterialHelper.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);let r=1-this._indexOfRefraction,_=1+this._indexOfRefraction,v=Math.pow(-r/_,2),x=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",v,x,r,_),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&MaterialFlags.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!g&&!d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialFlags.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&MaterialFlags.ClearCoatBumpTextureEnabled&&!p&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||this._textureRoughness===e||this._bumpTexture===e||this._tintTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,r,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(r=this._bumpTexture)||void 0===r||r.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"}]}}};pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction=1.5,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"isEnabled",void 0),__decorate([serialize()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"intensity",void 0),__decorate([serialize()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"roughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"indexOfRefraction",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"texture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"useRoughnessFromMainTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"textureRoughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"remapF0OnInterfaceChange",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"bumpTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"isTintEnabled",void 0),__decorate([serializeAsColor3()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintColor",void 0),__decorate([serialize()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintColorAtDistance",void 0),__decorate([serialize()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintThickness",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintTexture",void 0);let MaterialIridescenceDefines=class MaterialIridescenceDefines extends MaterialDefines{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}};let pbrIridescenceConfiguration_PBRIridescenceConfiguration=class pbrIridescenceConfiguration_PBRIridescenceConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new MaterialIridescenceDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMinimumThickness,this.maximumThickness=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness,this.indexOfRefraction=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.IridescenceTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._thicknessTexture||!MaterialFlags.IridescenceTextureEnabled||!!this._thicknessTexture.isReadyOrNotBlocking())}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&&MaterialFlags.IridescenceTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&MaterialFlags.IridescenceTextureEnabled?MaterialHelper.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,r){var s,a,n,o,l,h,c,u;if(!this._isEnabled)return;let d=r.materialDefines,_=this._material.isFrozen,p=d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&_&&e.isSync||(p&&MaterialFlags.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),MaterialHelper.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&MaterialFlags.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(a=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==a?a:0,null!==(o=null===(n=this._texture)||void 0===n?void 0:n.level)&&void 0!==o?o:0,null!==(h=null===(l=this._thicknessTexture)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(u=null===(c=this._thicknessTexture)||void 0===c?void 0:c.level)&&void 0!==u?u:0),this._texture&&MaterialHelper.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||p||d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||MaterialHelper.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&MaterialFlags.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!p&&!d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&MaterialFlags.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"}]}}};pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMinimumThickness=100,pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness=400,pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction=1.3,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"isEnabled",void 0),__decorate([serialize()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"intensity",void 0),__decorate([serialize()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"minimumThickness",void 0),__decorate([serialize()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"maximumThickness",void 0),__decorate([serialize()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"indexOfRefraction",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"texture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"thicknessTexture",void 0);let MaterialAnisotropicDefines=class MaterialAnisotropicDefines extends MaterialDefines{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}};let pbrAnisotropicConfiguration_PBRAnisotropicConfiguration=class pbrAnisotropicConfiguration_PBRAnisotropicConfiguration extends MaterialPluginBase{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 MaterialAnisotropicDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new math_vector_Vector2(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||!MaterialFlags.AnisotropicTextureEnabled||!!this._texture.isReadyOrNotBlocking()}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.AnisotropicTextureEnabled?MaterialHelper.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;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&MaterialFlags.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),MaterialHelper.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&MaterialFlags.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)}};__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"isEnabled",void 0),__decorate([serialize()],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"intensity",void 0),__decorate([generateSerializableMember(4,void 0)],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"direction",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"texture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"legacy",void 0);let MaterialSheenDefines=class MaterialSheenDefines extends MaterialDefines{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}};let pbrSheenConfiguration_PBRSheenConfiguration=class pbrSheenConfiguration_PBRSheenConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new MaterialSheenDefines,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=math_color_Color3.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.SheenTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!MaterialFlags.SheenTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())}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&&MaterialFlags.SheenTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&MaterialFlags.SheenTextureEnabled?MaterialHelper.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,r){var s,a,n,o,l,h,c,u;if(!this._isEnabled)return;let d=r.materialDefines,_=this._material.isFrozen,p=d.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&_&&e.isSync||(p&&MaterialFlags.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),MaterialHelper.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&MaterialFlags.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(a=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==a?a:0,null!==(o=null===(n=this._texture)||void 0===n?void 0:n.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(u=null===(c=this._textureRoughness)||void 0===c?void 0:c.level)&&void 0!==u?u:0),this._texture&&MaterialHelper.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||p||d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||MaterialHelper.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&&MaterialFlags.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!p&&!d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialFlags.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"}]}}};__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"isEnabled",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"linkSheenWithAlbedo",void 0),__decorate([serialize()],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"intensity",void 0),__decorate([serializeAsColor3()],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"color",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"texture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"useRoughnessFromMainTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"roughness",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"textureRoughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"albedoScaling",void 0);let MaterialSubSurfaceDefines=class MaterialSubSurfaceDefines extends MaterialDefines{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}};let pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration=class pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration extends MaterialPluginBase{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new MaterialSubSurfaceDefines,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=math_color_Color3.White(),this.tintColorAtDistance=1,this.diffusionDistance=math_color_Color3.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&&MaterialFlags.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;let e=this._getRefractionTexture(t);if(e&&MaterialFlags.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){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,e.SS_USE_GLTF_TEXTURES=!1;return}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;let i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,r=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(r||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&!s&&MaterialHelper.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&!s&&MaterialHelper.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){let i=this._getRefractionTexture(t);i&&MaterialFlags.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;r.getRenderingMesh().getWorldMatrix().decompose(math_vector_TmpVectors.Vector3[0]);let s=Math.max(Math.abs(math_vector_TmpVectors.Vector3[0].x),Math.abs(math_vector_TmpVectors.Vector3[0].y),Math.abs(math_vector_TmpVectors.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;let s=r.materialDefines,a=this._material.isFrozen,n=this._material.realTimeFiltering,o=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!a||!e.isSync){if(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),MaterialHelper.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),MaterialHelper.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),MaterialHelper.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&MaterialFlags.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;!l.isCube&&l.depth&&(t=l.depth);let i=l.getSize().width,r=this.volumeIndexOfRefraction;e.updateFloat4("vRefractionInfos",l.level,1/r,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),n&&e.updateFloat2("vRefractionFilteringInfo",i,math_scalar_Scalar.Log2(i)),l.boundingBoxSize&&(e.updateVector3("vRefractionPosition",l.boundingBoxPosition),e.updateVector3("vRefractionSize",l.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&&MaterialFlags.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&MaterialFlags.RefractionTextureEnabled&&(o?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){MaterialFlags.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!MaterialFlags.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"}]}}};__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isRefractionEnabled",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isTranslucencyEnabled",void 0),__decorate([serialize(),expandToProperty("_markScenePrePassDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isScatteringEnabled",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"_scatteringDiffusionProfileIndex",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionIntensity",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"translucencyIntensity",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useAlbedoToTintRefraction",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useAlbedoToTintTranslucency",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"thicknessTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"indexOfRefraction",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"_volumeIndexOfRefraction",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"volumeIndexOfRefraction",null),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"invertRefractionY",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"linkRefractionWithTransparency",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"minimumThickness",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"maximumThickness",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useThicknessAsDepth",void 0),__decorate([serializeAsColor3()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"tintColor",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"tintColorAtDistance",void 0),__decorate([serializeAsColor3()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"diffusionDistance",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useMaskFromThicknessTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionIntensityTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"translucencyIntensityTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useGltfStyleTextures",void 0);let ao={effect:null,subMesh:null};let PBRMaterialDefines=class PBRMaterialDefines extends MaterialDefines{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!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.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}};let pbrBaseMaterial_PBRBaseMaterial=class pbrBaseMaterial_PBRBaseMaterial extends PushMaterial{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new math_vector_Vector4(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=pbrBaseMaterial_PBRBaseMaterial.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=math_color_Color3.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new math_color_Color3(0,0,0),this._albedoColor=new math_color_Color3(1,1,1),this._reflectivityColor=new math_color_Color3(1,1,1),this._reflectionColor=new math_color_Color3(1,1,1),this._emissiveColor=new math_color_Color3(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=pbrBaseMaterial_PBRBaseMaterial.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 SmartArray(16),this._globalAmbientColor=new math_color_Color3(0,0,0),this._useLogarithmicDepth=!1,this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new pbrBRDFConfiguration_PBRBRDFConfiguration(this),this.clearCoat=new pbrClearCoatConfiguration_PBRClearCoatConfiguration(this),this.iridescence=new pbrIridescenceConfiguration_PBRIridescenceConfiguration(this),this.anisotropy=new pbrAnisotropicConfiguration_PBRAnisotropicConfiguration(this),this.sheen=new pbrSheenConfiguration_PBRSheenConfiguration(this),this.subSurface=new pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration(this),this.detailMap=new material_detailMapConfiguration_DetailMapConfiguration(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),MaterialFlags.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this.getScene()),this.prePassConfiguration=new PrePassConfiguration}get hasRenderTargetTextures(){return!!MaterialFlags.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===pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE||this._transparencyMode===pbrBaseMaterial_PBRBaseMaterial.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||!e.disableAlphaBlending)&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var r;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(ec.GetDefineNames,this._eventInfo),t.materialDefines=new PBRMaterialDefines(this._eventInfo.defineNames));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=this.getScene(),n=a.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){if(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;let e=this._getReflectionTexture();if(e&&MaterialFlags.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&(null===(r=e.getInternalTexture())||void 0===r?void 0:r._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(MaterialFlags.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(n.getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&MaterialFlags.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;n.getCaps().standardDerivatives||e.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)||(e.createNormals(!0),logger_Logger.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));let o=t.effect,l=s._areLightsDisposed,h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h){if(this._onEffectCreatedObservable&&(ao.effect=h,ao.subMesh=t,this._onEffectCreatedObservable.notifyObservers(ao)),this.allowShaderHotSwapping&&o&&!h.isReady()){if(h=o,s.markAsUnprocessed(),c=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else a.resetCachedMaterial(),t.setEffect(h,s,this._materialContext)}return!!(t.effect&&t.effect.isReady())&&(s._renderId=a.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,r=null,s=null,a=null,n){if(this._prepareDefines(e,t,s,a,n),!t.isDirty)return null;t.markAsProcessed();let o=this.getScene(),l=o.getEngine(),h=new EffectFallbacks,c=0;t.USESPHERICALINVERTEX&&h.addFallback(c++,"USESPHERICALINVERTEX"),t.FOG&&h.addFallback(c,"FOG"),t.SPECULARAA&&h.addFallback(c,"SPECULARAA"),t.POINTSIZE&&h.addFallback(c,"POINTSIZE"),t.LOGARITHMICDEPTH&&h.addFallback(c,"LOGARITHMICDEPTH"),t.PARALLAX&&h.addFallback(c,"PARALLAX"),t.PARALLAX_RHS&&h.addFallback(c,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&h.addFallback(c++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&h.addFallback(c++,"ENVIRONMENTBRDF"),t.TANGENT&&h.addFallback(c++,"TANGENT"),t.BUMP&&h.addFallback(c++,"BUMP"),c=MaterialHelper.HandleFallbacksForShadows(t,h,this._maxSimultaneousLights,c++),t.SPECULARTERM&&h.addFallback(c++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&h.addFallback(c++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&h.addFallback(c++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&h.addFallback(c++,"LIGHTMAP"),t.NORMAL&&h.addFallback(c++,"NORMAL"),t.AMBIENT&&h.addFallback(c++,"AMBIENT"),t.EMISSIVE&&h.addFallback(c++,"EMISSIVE"),t.VERTEXCOLOR&&h.addFallback(c++,"VERTEXCOLOR"),t.MORPHTARGETS&&h.addFallback(c++,"MORPHTARGETS"),t.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");let u=[buffer_VertexBuffer.PositionKind];t.NORMAL&&u.push(buffer_VertexBuffer.NormalKind),t.TANGENT&&u.push(buffer_VertexBuffer.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&u.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&u.push(buffer_VertexBuffer.ColorKind),t.INSTANCESCOLOR&&u.push(buffer_VertexBuffer.ColorInstanceKind),MaterialHelper.PrepareAttributesForBones(u,e,t,h),MaterialHelper.PrepareAttributesForInstances(u,t),MaterialHelper.PrepareAttributesForMorphTargets(u,e,t),MaterialHelper.PrepareAttributesForBakedVertexAnimation(u,e,t);let d="pbr",_=["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"],m={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=c,this._eventInfo.defines=t,this._eventInfo.uniforms=_,this._eventInfo.attributes=u,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(ec.PrepareEffect,this._eventInfo),PrePassConfiguration.AddUniforms(_),PrePassConfiguration.AddSamplers(p),addClipPlaneUniforms(_),ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(_,t),ImageProcessingConfiguration.PrepareSamplers(p,t)),MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:_,uniformBuffersNames:f,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});let g={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,_,f,p,t,u,g));let v=t.toString(),x=l.createEffect(d,{attributes:u,uniformsNames:_,uniformBuffersNames:f,samplers:p,defines:v,fallbacks:h,onCompiled:i,onError:r,indexParameters:m,processFinalCode:g.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},l);return this._eventInfo.customCode=void 0,x}_prepareDefines(e,t,i=null,r=null,s=!1){var a;let n=this.getScene(),o=n.getEngine();MaterialHelper.PrepareDefinesForLights(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,MaterialHelper.PrepareDefinesForMultiview(n,t);let l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(MaterialHelper.PrepareDefinesForPrePass(n,t,this.canRenderToMRT&&!l),MaterialHelper.PrepareDefinesForOIT(n,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(n.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&MaterialFlags.AmbientTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&MaterialFlags.OpacityTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;let e=this._getReflectionTexture();if(e&&MaterialFlags.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===texture_Texture.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 texture_Texture.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case texture_Texture.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case texture_Texture.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case texture_Texture.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case texture_Texture.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case texture_Texture.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.CUBIC_MODE:case texture_Texture.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==texture_Texture.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;if(this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,MaterialFlags.SpecularTextureEnabled){if(this._metallicTexture?(MaterialHelper.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?(MaterialHelper.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){let e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(a=this._reflectanceTexture)||void 0===a?void 0:a._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(MaterialHelper.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)?(MaterialHelper.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap?(MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=n.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&MaterialFlags.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===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(MaterialHelper.PrepareDefinesForMisc(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(buffer_VertexBuffer.NormalKind),t.DEBUGMODE=this._debugMode),MaterialHelper.PrepareDefinesForFrameBoundValues(n,o,this,t,!!i,r,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),MaterialHelper.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){let r=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(ec.GetDefineNames,this._eventInfo);let s=new PBRMaterialDefines(this._eventInfo.defineNames),a=this._prepareEffect(e,s,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(ao.effect=a,ao.subMesh=null,this._onEffectCreatedObservable.notifyObservers(ao)),a.isReady()?t&&t(this):a.onCompileObservable.add(()=>{t&&t(this)})}buildUniformLayout(){let 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 r,s,a,n;let o=this.getScene(),l=i.materialDefines;if(!l)return;let h=i.effect;if(!h)return;this._activeEffect=h,t.getMeshUniformBuffer().bindToEffect(h,"Mesh"),t.transferToEffect(e);let c=o.getEngine();this._uniformBuffer.bindToEffect(h,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,o,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),l.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let u=h._forceRebindOnNextCall||this._mustRebind(o,h,t.visibility);MaterialHelper.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let d=null,_=this._uniformBuffer;if(u){if(this.bindViewProjection(h),d=this._getReflectionTexture(),!_.useUbo||!this.isFrozen||!_.isSync||h._forceRebindOnNextCall){if(o.texturesEnabled){if(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&(_.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),MaterialHelper.BindTextureMatrix(this._albedoTexture,_,"albedo")),this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&(_.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),MaterialHelper.BindTextureMatrix(this._ambientTexture,_,"ambient")),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&(_.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),MaterialHelper.BindTextureMatrix(this._opacityTexture,_,"opacity")),d&&MaterialFlags.ReflectionTextureEnabled){if(_.updateMatrix("reflectionMatrix",d.getReflectionTextureMatrix()),_.updateFloat2("vReflectionInfos",d.level,0),d.boundingBoxSize){let e=d;_.updateVector3("vReflectionPosition",e.boundingBoxPosition),_.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){let e=d.getSize().width;_.updateFloat2("vReflectionFilteringInfo",e,math_scalar_Scalar.Log2(e))}if(!l.USEIRRADIANCEMAP){let e=d.sphericalPolynomial;if(l.USESPHERICALFROMREFLECTIONMAP&&e){if(l.SPHERICAL_HARMONICS){let t=e.preScaledHarmonics;_.updateVector3("vSphericalL00",t.l00),_.updateVector3("vSphericalL1_1",t.l1_1),_.updateVector3("vSphericalL10",t.l10),_.updateVector3("vSphericalL11",t.l11),_.updateVector3("vSphericalL2_2",t.l2_2),_.updateVector3("vSphericalL2_1",t.l2_1),_.updateVector3("vSphericalL20",t.l20),_.updateVector3("vSphericalL21",t.l21),_.updateVector3("vSphericalL22",t.l22)}else _.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),_.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),_.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),_.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),_.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),_.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),_.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),_.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),_.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}}_.updateFloat3("vReflectionMicrosurfaceInfos",d.getSize().width,d.lodGenerationScale,d.lodGenerationOffset)}this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&(_.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),MaterialHelper.BindTextureMatrix(this._emissiveTexture,_,"emissive")),this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&(_.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),MaterialHelper.BindTextureMatrix(this._lightmapTexture,_,"lightmap")),MaterialFlags.SpecularTextureEnabled&&(this._metallicTexture?(_.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),MaterialHelper.BindTextureMatrix(this._metallicTexture,_,"reflectivity")):this._reflectivityTexture&&(_.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),MaterialHelper.BindTextureMatrix(this._reflectivityTexture,_,"reflectivity")),this._metallicReflectanceTexture&&(_.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),MaterialHelper.BindTextureMatrix(this._metallicReflectanceTexture,_,"metallicReflectance")),this._reflectanceTexture&&l.REFLECTANCE&&(_.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),MaterialHelper.BindTextureMatrix(this._reflectanceTexture,_,"reflectance")),this._microSurfaceTexture&&(_.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),MaterialHelper.BindTextureMatrix(this._microSurfaceTexture,_,"microSurfaceSampler"))),this._bumpTexture&&c.getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&(_.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),MaterialHelper.BindTextureMatrix(this._bumpTexture,_,"bump"),o._mirroredCameraPosition?_.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):_.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&_.updateFloat("pointSize",this.pointSize),l.METALLICWORKFLOW){TmpColors.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,TmpColors.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,_.updateColor4("vReflectivityColor",TmpColors.Color3[0],1);let e=null!==(s=null===(r=this.subSurface)||void 0===r?void 0:r._indexOfRefraction)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((e-1)/(e+1),2)*this._metallicF0Factor,TmpColors.Color3[0]);let t=this._metallicF0Factor;_.updateColor4("vMetallicReflectanceFactors",TmpColors.Color3[0],t)}else _.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);_.updateColor3("vEmissiveColor",MaterialFlags.EmissiveTextureEnabled?this._emissiveColor:math_color_Color3.BlackReadOnly),_.updateColor3("vReflectionColor",this._reflectionColor),!l.SS_REFRACTION&&(null===(a=this.subSurface)||void 0===a?void 0:a._linkRefractionWithTransparency)?_.updateColor4("vAlbedoColor",this._albedoColor,1):_.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*o.environmentIntensity,this._lightingInfos.w=this._specularIntensity,_.updateVector4("vLightingIntensity",this._lightingInfos),o.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),_.updateColor3("vAmbientColor",this._globalAmbientColor),_.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}o.texturesEnabled&&(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&_.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&_.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&_.setTexture("opacitySampler",this._opacityTexture),d&&MaterialFlags.ReflectionTextureEnabled&&(l.LODBASEDMICROSFURACE?_.setTexture("reflectionSampler",d):(_.setTexture("reflectionSampler",d._lodTextureMid||d),_.setTexture("reflectionSamplerLow",d._lodTextureLow||d),_.setTexture("reflectionSamplerHigh",d._lodTextureHigh||d)),l.USEIRRADIANCEMAP&&_.setTexture("irradianceSampler",d.irradianceTexture)),l.ENVIRONMENTBRDF&&_.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&_.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&_.setTexture("lightmapSampler",this._lightmapTexture),MaterialFlags.SpecularTextureEnabled&&(this._metallicTexture?_.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&_.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&_.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&l.REFLECTANCE&&_.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&_.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&c.getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&_.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(h),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),bindClipPlane(this._activeEffect,this,o),this.bindEyePosition(h)}else o.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(u||!this.isFrozen)&&(o.lightsEnabled&&!this._disableLighting&&MaterialHelper.BindLights(o,t,this._activeEffect,l,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==scene_Scene.FOGMODE_NONE||d||this.subSurface.refractionTexture||t.receiveShadows||l.PREPASS)&&this.bindView(h),MaterialHelper.BindFogParameters(o,t,this._activeEffect,!0),l.NUM_MORPH_INFLUENCERS&&MaterialHelper.BindMorphTargetParameters(t,this._activeEffect),l.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(n=t.bakedVertexAnimationManager)||void 0===n||n.bind(h,l.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),MaterialHelper.BindLogDepth(l,this._activeEffect,o)),this._afterBind(t,this._activeEffect),_.update()}getAnimatables(){let 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(){let 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;let t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,r,s,a,n,o,l,h,c,u,d,_;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(a=this._reflectionTexture)||void 0===a||a.dispose(),null===(n=this._emissiveTexture)||void 0===n||n.dispose(),null===(o=this._metallicTexture)||void 0===o||o.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===(u=this._metallicReflectanceTexture)||void 0===u||u.dispose(),null===(d=this._reflectanceTexture)||void 0===d||d.dispose(),null===(_=this._microSurfaceTexture)||void 0===_||_.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}};pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE=material_Material.MATERIAL_OPAQUE,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST=material_Material.MATERIAL_ALPHATEST,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHABLEND=material_Material.MATERIAL_ALPHABLEND,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND=material_Material.MATERIAL_ALPHATESTANDBLEND,pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL=0,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF=1,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD=2,__decorate([generateSerializableMember(9,void 0)],pbrBaseMaterial_PBRBaseMaterial.prototype,"_imageProcessingConfiguration",void 0),__decorate([expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrBaseMaterial_PBRBaseMaterial.prototype,"debugMode",void 0),__decorate([serialize()],pbrBaseMaterial_PBRBaseMaterial.prototype,"useLogarithmicDepth",null);let pbrMaterial_PBRMaterial=class pbrMaterial_PBRMaterial extends pbrBaseMaterial_PBRBaseMaterial{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===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF:this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.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=pbrMaterial_PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=math_color_Color3.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new math_color_Color3(0,0,0),this.albedoColor=new math_color_Color3(1,1,1),this.reflectivityColor=new math_color_Color3(1,1,1),this.reflectionColor=new math_color_Color3(1,1,1),this.emissiveColor=new math_color_Color3(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){let r=decorators_SerializationHelper.Clone(()=>new pbrMaterial_PBRMaterial(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>new pbrMaterial_PBRMaterial(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),material_Material._parsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};function FourCCToInt32(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function Int32ToFourCC(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}pbrMaterial_PBRMaterial.PBRMATERIAL_OPAQUE=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHATEST=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHABLEND=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHABLEND,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND,pbrMaterial_PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"directIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"environmentIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"specularIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"disableBumpMap",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"albedoTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTextureStrength",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"opacityTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectionTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectivityTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallic",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"roughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicF0Factor",void 0),__decorate([serializeAsColor3(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicReflectanceColor",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicReflectanceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectanceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"microSurfaceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"bumpTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],pbrMaterial_PBRMaterial.prototype,"lightmapTexture",void 0),__decorate([serializeAsColor3("ambient"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientColor",void 0),__decorate([serializeAsColor3("albedo"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"albedoColor",void 0),__decorate([serializeAsColor3("reflectivity"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectivityColor",void 0),__decorate([serializeAsColor3("reflection"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectionColor",void 0),__decorate([serializeAsColor3("emissive"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveColor",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"microSurface",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useLightmapAsShadowmap",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"useAlphaFromAlbedoTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"forceAlphaTest",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"alphaCutOff",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useSpecularOverAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRoughnessFromMetallicTextureGreen",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useMetallnessFromMetallicTextureBlue",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAmbientInGrayScale",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),__decorate([serialize()],pbrMaterial_PBRMaterial.prototype,"usePhysicalLightFalloff",null),__decorate([serialize()],pbrMaterial_PBRMaterial.prototype,"useGLTFLightFalloff",null),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRadianceOverAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useObjectSpaceNormalMap",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useParallax",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useParallaxOcclusion",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"parallaxScaleBias",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsLightsDirty")],pbrMaterial_PBRMaterial.prototype,"disableLighting",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"forceIrradianceInFragment",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsLightsDirty")],pbrMaterial_PBRMaterial.prototype,"maxSimultaneousLights",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"invertNormalMapX",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"invertNormalMapY",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"twoSidedLighting",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAlphaFresnel",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useLinearAlphaFresnel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"environmentBRDFTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"forceNormalForward",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"enableSpecularAntiAliasing",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useHorizonOcclusion",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRadianceOcclusion",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrMaterial_PBRMaterial.prototype,"unlit",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrMaterial_PBRMaterial.prototype,"applyDecalMapAfterDetailMap",void 0),h["BABYLON.PBRMaterial"]=pbrMaterial_PBRMaterial;let al=FourCCToInt32("DXT1"),ah=FourCCToInt32("DXT3"),ac=FourCCToInt32("DXT5"),au=FourCCToInt32("DX10");let DDSTools=class DDSTools{static GetDDSInfo(e){let t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35),r=1;131072&t[2]&&(r=Math.max(1,t[7]));let s=t[21],a=s===au?i[32]:0,n=0;switch(s){case 113:n=2;break;case 116:n=1;break;case au:if(10===a){n=2;break}2===a&&(n=1)}return{width:t[4],height:t[3],mipmapCount:r,isFourCC:(4&t[20])==4,isRGB:(64&t[20])==64,isLuminance:(131072&t[20])==131072,isCube:(512&t[28])==512,isCompressed:s===al||s===ah||s===ac,dxgiFormat:a,textureType:n}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,a){let n=new Float32Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;n[l]=FromHalfFloat(o[r]),n[l+1]=FromHalfFloat(o[r+1]),n[l+2]=FromHalfFloat(o[r+2]),DDSTools.StoreLODInAlphaChannel?n[l+3]=a:n[l+3]=FromHalfFloat(o[r+3]),l+=4}return n}static _GetHalfFloatRGBAArrayBuffer(e,t,i,r,s,a){if(DDSTools.StoreLODInAlphaChannel){let n=new Uint16Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;n[l]=o[r],n[l+1]=o[r+1],n[l+2]=o[r+2],n[l+3]=ToHalfFloat(a),l+=4}return n}return new Uint16Array(s,i,r)}static _GetFloatRGBAArrayBuffer(e,t,i,r,s,a){if(DDSTools.StoreLODInAlphaChannel){let n=new Float32Array(r),o=new Float32Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;n[l]=o[r],n[l+1]=o[r+1],n[l+2]=o[r+2],n[l+3]=a,l+=4}return n}return new Float32Array(s,i,r)}static _GetFloatAsHalfFloatRGBAArrayBuffer(e,t,i,r,s,a){let n=new Uint16Array(r),o=new Float32Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++)n[l]=ToHalfFloat(o[l]),n[l+1]=ToHalfFloat(o[l+1]),n[l+2]=ToHalfFloat(o[l+2]),DDSTools.StoreLODInAlphaChannel?n[l+3]=ToHalfFloat(a):n[l+3]=ToHalfFloat(o[l+3]),l+=4;return n}static _GetFloatAsUIntRGBAArrayBuffer(e,t,i,r,s,a){let n=new Uint8Array(r),o=new Float32Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;n[l]=255*math_scalar_Scalar.Clamp(o[r]),n[l+1]=255*math_scalar_Scalar.Clamp(o[r+1]),n[l+2]=255*math_scalar_Scalar.Clamp(o[r+2]),DDSTools.StoreLODInAlphaChannel?n[l+3]=a:n[l+3]=255*math_scalar_Scalar.Clamp(o[r+3]),l+=4}return n}static _GetHalfFloatAsUIntRGBAArrayBuffer(e,t,i,r,s,a){let n=new Uint8Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;n[l]=255*math_scalar_Scalar.Clamp(FromHalfFloat(o[r])),n[l+1]=255*math_scalar_Scalar.Clamp(FromHalfFloat(o[r+1])),n[l+2]=255*math_scalar_Scalar.Clamp(FromHalfFloat(o[r+2])),DDSTools.StoreLODInAlphaChannel?n[l+3]=a:n[l+3]=255*math_scalar_Scalar.Clamp(FromHalfFloat(o[r+3])),l+=4}return n}static _GetRGBAArrayBuffer(e,t,i,r,s,a,n,o,l){let h=new Uint8Array(r),c=new Uint8Array(s,i),u=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;h[u]=c[r+a],h[u+1]=c[r+n],h[u+2]=c[r+o],h[u+3]=c[r+l],u+=4}return h}static _ExtractLongWordOrder(e){return 0===e||255===e||-16777216===e?0:1+DDSTools._ExtractLongWordOrder(e>>8)}static _GetRGBArrayBuffer(e,t,i,r,s,a,n,o){let l=new Uint8Array(r),h=new Uint8Array(s,i),c=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*3;l[c]=h[r+a],l[c+1]=h[r+n],l[c+2]=h[r+o],c+=3}return l}static _GetLuminanceArrayBuffer(e,t,i,r,s){let a=new Uint8Array(r),n=new Uint8Array(s,i),o=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=t+i*e;a[o]=n[r],o++}return a}static UploadDDSLevels(e,t,i,r,s,a,n=-1,o,l=!0){let h,c,u,d=null;r.sphericalPolynomial&&(d=[]);let _=!!e.getCaps().s3tc;t.generateMipMaps=s;let p=new Int32Array(i.buffer,i.byteOffset,31),f,m,g,v=0,x,b=0,T=1;if(542327876!==p[0]){logger_Logger.Error("Invalid magic number in DDS header");return}if(!r.isFourCC&&!r.isRGB&&!r.isLuminance){logger_Logger.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");return}if(r.isCompressed&&!_){logger_Logger.Error("Compressed textures are not supported on this platform.");return}let S=p[22];x=p[1]+4;let C=!1;if(r.isFourCC)switch(f=p[21]){case al:T=8,b=33777;break;case ah:T=16,b=33778;break;case ac:T=16,b=33779;break;case 113:C=!0,S=64;break;case 116:C=!0,S=128;break;case au:{x+=20;let e=!1;switch(r.dxgiFormat){case 10:C=!0,S=64,e=!0;break;case 2:C=!0,S=128,e=!0;break;case 88:r.isRGB=!0,r.isFourCC=!1,S=32,e=!0}if(e)break}default:console.error("Unsupported FourCC code:",Int32ToFourCC(f));return}let E=DDSTools._ExtractLongWordOrder(p[23]),y=DDSTools._ExtractLongWordOrder(p[24]),R=DDSTools._ExtractLongWordOrder(p[25]),P=DDSTools._ExtractLongWordOrder(p[26]);C&&(b=e._getRGBABufferInternalSizedFormat(r.textureType)),c=1,131072&p[2]&&!1!==s&&(c=Math.max(1,p[7]));let A=o||0,M=e.getCaps();for(let s=A;s<a;s++){for(u=0,m=p[4],g=p[3];u<c;++u){if(-1===n||n===u){let a=-1===n?u:0;if(!r.isCompressed&&r.isFourCC){t.format=5,v=m*g*4;let r=null;if(e._badOS||e._badDesktopOS||!M.textureHalfFloat&&!M.textureFloat)128===S?(r=DDSTools._GetFloatAsUIntRGBAArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,a),d&&0==a&&d.push(DDSTools._GetFloatRGBAArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,a))):64===S&&(r=DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,a),d&&0==a&&d.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,a))),t.type=0;else{let e;let s=M.textureFloat&&(l&&M.textureFloatLinearFiltering||!l),n=M.textureHalfFloat&&(l&&M.textureHalfFloatLinearFiltering||!l),o=(128===S||64===S&&!n)&&s?1:(64===S||128===S&&!s)&&n?2:0,h=null;if(128===S)switch(o){case 1:e=DDSTools._GetFloatRGBAArrayBuffer,h=null;break;case 2:e=DDSTools._GetFloatAsHalfFloatRGBAArrayBuffer,h=DDSTools._GetFloatRGBAArrayBuffer;break;case 0:e=DDSTools._GetFloatAsUIntRGBAArrayBuffer,h=DDSTools._GetFloatRGBAArrayBuffer}else switch(o){case 1:e=DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer,h=null;break;case 2:e=DDSTools._GetHalfFloatRGBAArrayBuffer,h=DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;break;case 0:e=DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer,h=DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer}t.type=o,r=e(m,g,i.byteOffset+x,v,i.buffer,a),d&&0==a&&d.push(h?h(m,g,i.byteOffset+x,v,i.buffer,a):r)}r&&e._uploadDataToTextureDirectly(t,r,s,a)}else if(r.isRGB)t.type=0,24===S?(t.format=4,v=m*g*3,h=DDSTools._GetRGBArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,E,y,R)):(t.format=5,v=m*g*4,h=DDSTools._GetRGBAArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,E,y,R,P)),e._uploadDataToTextureDirectly(t,h,s,a);else if(r.isLuminance){let r=e._getUnpackAlignement(),n=m,o=Math.floor((m+r-1)/r)*r;v=o*(g-1)+n,h=DDSTools._GetLuminanceArrayBuffer(m,g,i.byteOffset+x,v,i.buffer),t.format=1,t.type=0,e._uploadDataToTextureDirectly(t,h,s,a)}else v=Math.max(4,m)/4*Math.max(4,g)/4*T,h=new Uint8Array(i.buffer,i.byteOffset+x,v),t.type=0,e._uploadCompressedDataToTextureDirectly(t,b,m,g,h,s,a)}x+=S?m*g*(S/8):v,m*=.5,g*=.5,m=Math.max(1,m),g=Math.max(1,g)}if(void 0!==o)break}d&&d.length>0?r.sphericalPolynomial=CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({size:p[4],right:d[0],left:d[1],up:d[2],down:d[3],front:d[4],back:d[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}};DDSTools.StoreLODInAlphaChannel=!1,ThinEngine.prototype.createPrefilteredCubeTexture=function(e,t,i,r,s=null,a=null,n,o=null,l=!0){return this.createCubeTexture(e,t,null,!1,e=>{if(!e){s&&s(null);return}let a=e.texture;if(l?e.info.sphericalPolynomial&&(a._sphericalPolynomial=e.info.sphericalPolynomial):a._sphericalPolynomial=new SphericalPolynomial,a._source=$.CubePrefiltered,this.getCaps().textureLOD){s&&s(a);return}let n=this._gl,o=e.width;if(!o)return;let h=[];for(let s=0;s<3;s++){let l=s/2,c=1-l,u=math_scalar_Scalar.Log2(o)*i+r,d=r+(u-r)*c,_=Math.round(Math.min(Math.max(d,0),u)),p=new internalTexture_InternalTexture(this,$.Temp);if(p.type=a.type,p.format=a.format,p.width=Math.pow(2,Math.max(math_scalar_Scalar.Log2(o)-_,0)),p.height=p.width,p.isCube=!0,p._cachedWrapU=0,p._cachedWrapV=0,this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,p,!0),p.samplingMode=2,n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,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.isDDS){let t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),DDSTools.UploadDDSLevels(this,p,i,t,!0,6,_)}else logger_Logger.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null);let f=new baseTexture_BaseTexture(t);f._isCube=!0,f._texture=p,p.isReady=!0,h.push(f)}a._lodTextureHigh=h[2],a._lodTextureMid=h[1],a._lodTextureLow=h[0],s&&s(a)},a,n,o,l,i,r)};let _DDSTextureLoader=class _DDSTextureLoader{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,r){let s;let a=t.getEngine(),n=!1,o=1e3;if(Array.isArray(e))for(let i=0;i<e.length;i++){let r=e[i];s=DDSTools.GetDDSInfo(r),t.width=s.width,t.height=s.height,n=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,a._unpackFlipY(s.isCompressed),DDSTools.UploadDDSLevels(a,t,r,s,n,6,-1,i),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:a.generateMipMapsForCubemap(t)}else s=DDSTools.GetDDSInfo(e),t.width=s.width,t.height=s.height,i&&(s.sphericalPolynomial=new SphericalPolynomial),n=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,a._unpackFlipY(s.isCompressed),DDSTools.UploadDDSLevels(a,t,e,s,n,6),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:a.generateMipMapsForCubemap(t,!1);a._setCubeMapTextureParams(t,n,o),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:s,data:e,texture:t})}loadData(e,t,i){let r=DDSTools.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&r.width>>r.mipmapCount-1==1;i(r.width,r.height,s,r.isFourCC,()=>{DDSTools.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}};engine_Engine._TextureLoaders.push(new _DDSTextureLoader);let _ENVTextureLoader=class _ENVTextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let a=GetEnvInfo(e);if(a){t.width=a.width,t.height=a.width;try{UploadEnvSpherical(t,a),UploadEnvLevelsAsync(t,e,a).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},e=>{null==s||s("Can not upload environment levels",e)})}catch(e){null==s||s("Can not upload environment file",e)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}};engine_Engine._TextureLoaders.push(new _ENVTextureLoader);let KhronosTextureContainer=class KhronosTextureContainer{constructor(e,t){if(this.data=e,this.isInvalid=!1,!KhronosTextureContainer.IsValid(e)){this.isInvalid=!0,logger_Logger.Error("texture missing KTX identifier");return}let i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=r.getUint32(0,!0),a=67305985===s;if(this.glType=r.getUint32(1*i,a),this.glTypeSize=r.getUint32(2*i,a),this.glFormat=r.getUint32(3*i,a),this.glInternalFormat=r.getUint32(4*i,a),this.glBaseInternalFormat=r.getUint32(5*i,a),this.pixelWidth=r.getUint32(6*i,a),this.pixelHeight=r.getUint32(7*i,a),this.pixelDepth=r.getUint32(8*i,a),this.numberOfArrayElements=r.getUint32(9*i,a),this.numberOfFaces=r.getUint32(10*i,a),this.numberOfMipmapLevels=r.getUint32(11*i,a),this.bytesOfKeyValueData=r.getUint32(12*i,a),0!==this.glType){logger_Logger.Error("only compressed formats currently supported"),this.isInvalid=!0;return}if(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth){logger_Logger.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(0!==this.numberOfArrayElements){logger_Logger.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){logger_Logger.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=KhronosTextureContainer.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case KhronosTextureContainer.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case KhronosTextureContainer.TEX_2D:case KhronosTextureContainer.COMPRESSED_3D:case KhronosTextureContainer.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=KhronosTextureContainer.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight,a=t?this.numberOfMipmapLevels:1;for(let t=0;t<a;t++){let a=new Int32Array(this.data.buffer,this.data.byteOffset+i,1)[0];i+=4;for(let n=0;n<this.numberOfFaces;n++){let o=new Uint8Array(this.data.buffer,this.data.byteOffset+i,a),l=e.getEngine();l._uploadCompressedDataToTextureDirectly(e,e.format,r,s,o,n,t),i+=a+(3-(a+3)%4)}r=Math.max(1,.5*r),s=Math.max(1,.5*s)}}static IsValid(e){if(e.byteLength>=12){let 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}};KhronosTextureContainer.HEADER_LEN=64,KhronosTextureContainer.COMPRESSED_2D=0,KhronosTextureContainer.COMPRESSED_3D=1,KhronosTextureContainer.TEX_2D=2,KhronosTextureContainer.TEX_3D=3;let WorkerPool=class WorkerPool{constructor(e){this._pendingActions=[],this._workerInfos=e.map(e=>({workerPromise:Promise.resolve(e),idle:!0}))}dispose(){for(let 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(let 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,()=>{let t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0})})}};let AutoReleaseWorkerPool=class AutoReleaseWorkerPool extends WorkerPool{constructor(e,t,i=AutoReleaseWorkerPool.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e)){if(this._workerInfos.length<this._maxWorkers){let t={workerPromise:this._createWorkerAsync(),idle:!1};this._workerInfos.push(t),this._execute(t,e)}else this._pendingActions.push(e)}}_execute(e,t){e.timeoutId&&(clearTimeout(e.timeoutId),delete e.timeoutId),super._execute(e,(i,r)=>{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(e=>{e.terminate()});let t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)},this._options.idleTimeElapsedBeforeRelease))})})}};function applyConfig(e){e.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}AutoReleaseWorkerPool.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(tv||(tv={})),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"}(tx||(tx={})),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"}(tb||(tb={}));let DefaultKTX2DecoderOptions=class DefaultKTX2DecoderOptions{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;let e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[tx.BC1_RGB,tx.BC3_RGBA],yes:{transcodeFormat:tx.RGBA32,engineFormat:tb.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}};let KhronosTextureContainer2=class KhronosTextureContainer2{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(KhronosTextureContainer2._WorkerPoolPromise||KhronosTextureContainer2._DecoderModulePromise)return;let t={jsDecoderModule:tools_Tools.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:tools_Tools.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?KhronosTextureContainer2._WorkerPoolPromise=new Promise(i=>{let r=`${applyConfig}(${workerFunc})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new AutoReleaseWorkerPool(e,()=>new Promise((e,i)=>{let r=new Worker(s),onError=e=>{r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),i(e)},onMessage=t=>{"init"===t.data.action&&(r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),e(r))};r.addEventListener("error",onError),r.addEventListener("message",onMessage),r.postMessage({action:"init",urls:t})})))}):"undefined"==typeof KTX2DECODER?KhronosTextureContainer2._DecoderModulePromise=tools_Tools.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,applyConfig(t),new KTX2DECODER.KTX2Decoder)):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,KhronosTextureContainer2._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=KhronosTextureContainer2.DefaultNumWorkers){this._engine=e,KhronosTextureContainer2._Initialize(t)}uploadAsync(e,t,i){let r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(KhronosTextureContainer2._WorkerPoolPromise)return KhronosTextureContainer2._WorkerPoolPromise.then(r=>new Promise((a,n)=>{r.push((r,o)=>{let onError=e=>{r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),n(e),o()},onMessage=e=>{if("decoded"===e.data.action){if(r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),e.data.success)try{this._createTexture(e.data.decodedData,t,i),a()}catch(e){n({message:e})}else n({message:e.data.msg});o()}};r.addEventListener("error",onError),r.addEventListener("message",onMessage),r.postMessage({action:"setDefaultDecoderOptions",options:KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions()});let l=new Uint8Array(e.byteLength);l.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),r.postMessage({action:"decode",data:l,caps:s,options:i},[l.buffer])})}));if(KhronosTextureContainer2._DecoderModulePromise)return KhronosTextureContainer2._DecoderModulePromise.then(i=>(KhronosTextureContainer2.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((s,a)=>{i.decode(e,r).then(e=>{this._createTexture(e,t),s()}).catch(e=>{a({message:e})})})));throw Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let r=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,r=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i<e.mipmaps.length;++i){let s=e.mipmaps[i];if(!s||!s.data)throw Error("KTX2 container - could not transcode one of the image");r?(t.width=s.width,t.height=s.height,this._engine._uploadDataToTextureDirectly(t,s.data,0,i,void 0,!0)):this._engine._uploadCompressedDataToTextureDirectly(t,e.transcodedFormat,s.width,s.height,s.data,0,i)}t._extension=".ktx2",t.width=e.mipmaps[0].width,t.height=e.mipmaps[0].height,t.isReady=!0,this._engine._bindTextureDirectly(3553,null)}static IsValid(e){if(e.byteLength>=12){let 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 workerFunc(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{let i=t.data.urls;importScripts(i.jsDecoderModule),applyConfig(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=>{let t=[];for(let i=0;i<e.mipmaps.length;++i){let r=e.mipmaps[i];r&&r.data&&t.push(r.data.buffer)}postMessage({action:"decoded",success:!0,decodedData:e},t)}).catch(e=>{postMessage({action:"decoded",success:!1,msg:e})})}}}function mapSRGBToLinear(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}KhronosTextureContainer2.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},KhronosTextureContainer2.DefaultNumWorkers=KhronosTextureContainer2.GetDefaultNumWorkers(),KhronosTextureContainer2.DefaultDecoderOptions=new DefaultKTX2DecoderOptions;let _KTXTextureLoader=class _KTXTextureLoader{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;let s=t.getEngine(),a=new KhronosTextureContainer(e,6),n=a.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(t,t.generateMipMaps),t.width=a.pixelWidth,t.height=a.pixelHeight,s._setCubeMapTextureParams(t,n,a.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(KhronosTextureContainer.IsValid(e)){t._invertVScale=!t.invertY;let r=new KhronosTextureContainer(e,1),s=mapSRGBToLinear(r.glInternalFormat);s?(t.format=s,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=r.glInternalFormat,i(r.pixelWidth,r.pixelHeight,t.generateMipMaps,!0,()=>{r.uploadLevels(t,t.generateMipMaps)},r.isInvalid)}else if(KhronosTextureContainer2.IsValid(e)){let s=new KhronosTextureContainer2(t.getEngine());s.uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},e=>{logger_Logger.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,()=>{},!0)})}else logger_Logger.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0)}};engine_Engine._TextureLoaders.unshift(new _KTXTextureLoader);let WebXRCamera=class WebXRCamera extends FreeCamera{constructor(e,t,i){super(e,math_vector_Vector3.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=math_vector_Quaternion.Identity(),this._referencedPosition=new math_vector_Vector3,this._trackingState=eN.NOT_TRACKING,this.onXRCameraInitializedObservable=new observable_Observable,this.onBeforeCameraTeleport=new observable_Observable,this.onAfterCameraTeleport=new observable_Observable,this.onTrackingStateChanged=new observable_Observable,this.compensateOnFirstFrame=!0,this._rotate180=new math_vector_Quaternion(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new math_vector_Quaternion,this.cameraRigMode=camera_Camera.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add(()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame}),this._xrSessionManager.onXRFrameObservable.add(()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()},void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){let 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 math_viewport_Viewport(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new math_viewport_Viewport(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){if(!e||e===this)return;let i=e.computeWorldMatrix();i.decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,math_vector_Quaternion.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){let t=math_vector_TmpVectors.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();let i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),math_vector_Quaternion.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(eN.NOT_TRACKING);return}let t=e.emulatedPosition?eN.TRACKING_LOST:eN.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){let 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){let t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;let 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;let r=this.rigCameras[t];r.isLeftCamera||r.isRightCamera||("right"===e.eye?r._isRightCamera=!0:"left"!==e.eye||(r._isLeftCamera=!0));let s=e.transform.position,a=e.transform.orientation;r.parent=this.parent,r.position.set(s.x,s.y,s.z),r.rotationQuaternion.set(a.x,a.y,a.z,a.w),this._scene.useRightHandedSystem?r.rotationQuaternion.multiplyInPlace(this._rotate180):(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1),math_vector_Matrix.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,r._projectionMatrix),this._scene.useRightHandedSystem||r._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(r._projectionMatrix);let n=this._xrSessionManager.getRenderTargetTextureForView(e);this._renderingMultiview=(null===(i=null==n?void 0:n._texture)||void 0===i?void 0:i.isMultiview)||!1,this._renderingMultiview?0==t&&(this._xrSessionManager.trySetViewportForView(this.viewport,e),this.outputRenderTarget=n):(this._xrSessionManager.trySetViewportForView(r.viewport,e),r.outputRenderTarget=n||this._xrSessionManager.getRenderTargetTextureForView(e)),r.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.length<e;){let e=new targetCamera_TargetCamera("XR-RigCamera: "+this.rigCameras.length,math_vector_Vector3.Zero(),this.getScene());e.minZ=.1,e.rotationQuaternion=new math_vector_Quaternion,e.updateUpVectorFromRotation=!0,e.isRigCamera=!0,e.rigParent=this,e.freezeProjectionMatrix(),this.rigCameras.push(e)}for(;this.rigCameras.length>e;){let e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){let e=math_vector_TmpVectors.Matrix[0],t=math_vector_TmpVectors.Matrix[1],i=math_vector_TmpVectors.Matrix[2];math_vector_Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),math_vector_Matrix.ComposeToRef(WebXRCamera._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);let r=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(r)}}};WebXRCamera._ScaleReadOnly=math_vector_Vector3.One();let WebXRExperienceHelper=class WebXRExperienceHelper{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 observable_Observable,this.onStateChangedObservable=new observable_Observable,this.state=eB.NOT_IN_XR,this.sessionManager=new WebXRSessionManager(e),this.camera=new WebXRCamera("webxr",e,this.sessionManager),this.featuresManager=new WebXRFeaturesManager(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){let t=new WebXRExperienceHelper(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(e=>{throw t._setState(eB.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(),r={}){var s,a,n;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(eB.ENTERING_XR),"viewer"!==t&&"local"!==t&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),"immersive-ar"===e&&"unbounded"!==t&&logger_Logger.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);let o=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(webXRFeaturesManager_WebXRFeatureName.LAYERS)||(l.baseLayer=o),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(a=null===(s=this._nonVRCamera)||void 0===s?void 0:s.inputs)||void 0===a?void 0:a.attachedToElement),null===(n=this._nonVRCamera)||void 0===n||n.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!==eB.EXITING_XR&&this._setState(eB.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(eB.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(eB.IN_XR)}),this.sessionManager}catch(e){throw console.log(e),console.log(e.message),this._setState(eB.NOT_IN_XR),e}}exitXRAsync(){return this.state!==eB.IN_XR?Promise.resolve():(this._setState(eB.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){let t=(null==e?void 0:e.fps)?e.fps:1e3,i=1/t*1e3,r=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,updateSpectatorCamera=()=>{if(this._spectatorCamera){let e=this.sessionManager.currentTimestamp-this._lastTimestamp;e>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[r].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[r].absoluteRotation))}};if(this._spectatorMode){if(r>=this.camera.rigCameras.length)throw Error("the preferred camera index is beyond the length of rig camera array.");let onStateChanged=()=>{this.state===eB.IN_XR?(this._spectatorCamera=new universalCamera_UniversalCamera("webxr-spectator",math_vector_Vector3.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new math_vector_Quaternion,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(updateSpectatorCamera),this._scene.onAfterRenderCameraObservable.add(e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===eB.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera),this._scene.activeCameras=null)};this.onStateChangedObservable.add(onStateChanged),onStateChanged()}else this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera),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))}};let WebXRControllerComponent=class WebXRControllerComponent{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new observable_Observable,this.onButtonStateChangedObservable=new observable_Observable}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()){let 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))}};WebXRControllerComponent.BUTTON_TYPE="button",WebXRControllerComponent.SQUEEZE_TYPE="squeeze",WebXRControllerComponent.THUMBSTICK_TYPE="thumbstick",WebXRControllerComponent.TOUCHPAD_TYPE="touchpad",WebXRControllerComponent.TRIGGER_TYPE="trigger";let WebXRAbstractMotionController=class WebXRAbstractMotionController{constructor(e,t,i,r,s=!1,a){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=a,this._initComponent=e=>{if(!e)return;let t=this.layout.components[e],i=t.type,r=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new WebXRControllerComponent(e,i,r,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new observable_Observable,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(){let e=!this._getModelLoadingConstraints(),t=this._getGenericFilenameAndPath();return e?logger_Logger.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,r)=>{let meshesLoaded=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){let e=this._controllerCache.filter(e=>e.filename===t.filename&&e.path===t.path);if(e[0]){e[0].meshes.forEach(e=>e.setEnabled(!0)),meshesLoaded(e[0].meshes);return}}sceneLoader_SceneLoader.ImportMesh("",t.path,t.filename,this.scene,e=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:e})),meshesLoaded(e)},null,(e,i)=>{logger_Logger.Log(i),logger_Logger.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(i)})})}updateFromXRFrame(e){this.getComponentIds().forEach(e=>this.getComponent(e).update(this.gamepadObject)),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren(e=>e.name===t,!1)[0]}_getImmediateChildByName(e,t){return e.getChildren(e=>e.name==t,!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh||!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;let r=i?.5*t+.5:t;math_vector_Quaternion.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),math_vector_Vector3.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new mesh_Mesh(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=math_vector_Quaternion.FromEulerAngles(0,Math.PI,0)}};let WebXRGenericTriggerMotionController=class WebXRGenericTriggerMotionController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,ad[i],t,i),this.profileId=WebXRGenericTriggerMotionController.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new mesh_Mesh(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=math_vector_Quaternion.FromEulerAngles(0,Math.PI,0)}_updateModel(){}};WebXRGenericTriggerMotionController.ProfileId="generic-trigger";let ad={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"}};let WebXRProfiledMotionController=class WebXRProfiledMotionController extends WebXRAbstractMotionController{constructor(e,t,i,r,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=r,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach(e=>{this._touchDots[e].dispose()})}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){let e=sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb");return e||logger_Logger.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach(i=>{let r=t.visualResponses[i];if("transform"===r.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{let s=t.type===WebXRControllerComponent.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===WebXRControllerComponent.TOUCHPAD_TYPE&&!this._touchDots[i]){let t=sphereBuilder_CreateSphere(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new standardMaterial_StandardMaterial(i+"mat",this.scene),t.material.diffuseColor=math_color_Color3.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}})})}_setRootMesh(e){let t;this.rootMesh=new mesh_Mesh(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i<e.length;i++){let r=e[i];r.isPickable=!1,r.parent||(t=r)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||this.rootMesh.rotate(math_axis_Axis.Y,Math.PI,en.WORLD)}_updateModel(e){this.disableAnimation||this.getComponentIds().forEach(e=>{let t=this.getComponent(e);if(!t.hasChanges)return;let i=this._buttonMeshMapping[e],r=this.layout.components[e];Object.keys(r.visualResponses).forEach(e=>{let s=r.visualResponses[e],a=t.value;if("xAxis"===s.componentProperty?a=t.axes.x:"yAxis"===s.componentProperty&&(a=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],a,"button"!==s.componentProperty);else{let r=i.states[e].valueMesh;r&&(r.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}})})}};let a_=[];let WebXRMotionControllerManager=class WebXRMotionControllerManager{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){let t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){let r=[];i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&r.push("oculus-touch-v2");let s=r.indexOf("windows-mixed-reality");if(-1!==s&&r.splice(s,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),!this.UseOnlineRepository)return this._LoadProfilesFromAvailableControllers(r,e,t);{let i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,r,e,t).catch(()=>s.call(this,r,e,t))}}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=tools_Tools.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e.toString())),this._ProfilesList}static ClearControllerCache(){a_.forEach(e=>{e.meshes.forEach(e=>{e.dispose(!1,!0)})}),a_.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(t=>{for(let i=0;i<e.length;++i)if(e[i]&&t[e[i]])return e[i];throw Error(`neither controller ${e[0]} nor all fallbacks were found in the repository,`)}).then(e=>(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=tools_Tools.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then(e=>JSON.parse(e))),this._ProfileLoadingPromises[e])).then(e=>new WebXRProfiledMotionController(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:a_))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;r<e.length;++r){if(!e[r])continue;let s=this.FindFallbackWithProfileId(e[r]);for(let e=0;e<s.length;++e){let r=this._AvailableControllers[s[e]];if(r)return Promise.resolve(r(t,i))}}throw Error("no controller requested was found in the available controllers list")}};WebXRMotionControllerManager._AvailableControllers={},WebXRMotionControllerManager._Fallbacks={},WebXRMotionControllerManager._ProfileLoadingPromises={},WebXRMotionControllerManager.BaseRepositoryUrl="https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist",WebXRMotionControllerManager.PrioritizeOnlineRepository=!0,WebXRMotionControllerManager.UseOnlineRepository=!0,WebXRMotionControllerManager.DisableControllerCache=!0,WebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId,(e,t)=>new WebXRGenericTriggerMotionController(t,e.gamepad,e.handedness)),WebXRMotionControllerManager.DefaultFallbacks();let ap=0;let WebXRInputSource=class WebXRInputSource{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new math_vector_Vector3,this._disposed=!1,this.onDisposeObservable=new observable_Observable,this.onMeshLoadedObservable=new observable_Observable,this.onMotionControllerInitObservable=new observable_Observable,this._uniqueId=`controller-${ap++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new abstractMesh_AbstractMesh(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new math_vector_Quaternion,this.inputSource.gripSpace&&(this.grip=new abstractMesh_AbstractMesh(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new math_vector_Quaternion),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&WebXRMotionControllerManager.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())})},()=>{tools_Tools.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){let i=t&&this.grip?this.grip:this.pointer;math_vector_Vector3.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){let r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){let e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z);let t=r.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){let r=e.getPose(this.inputSource.gripSpace,t);if(r){let e=r.transform.position,t=r.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)}};let WebXRInput=class WebXRInput{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new observable_Observable,this.onControllerRemovedObservable=new observable_Observable,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&&(WebXRMotionControllerManager.BaseRepositoryUrl=this._options.customControllersRepositoryURL),WebXRMotionControllerManager.UseOnlineRepository=!this._options.disableOnlineControllerRepository,WebXRMotionControllerManager.UseOnlineRepository)try{WebXRMotionControllerManager.UpdateProfilesList().catch(()=>{WebXRMotionControllerManager.UseOnlineRepository=!1})}catch(e){WebXRMotionControllerManager.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){let i=this.controllers.map(e=>e.inputSource);for(let t of e)if(-1===i.indexOf(t)){let e=new WebXRInputSource(this.xrSessionManager.scene,t,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)}let r=[],s=[];this.controllers.forEach(e=>{-1===t.indexOf(e.inputSource)?r.push(e):s.push(e)}),this.controllers=r,s.forEach(e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()})}dispose(){this.controllers.forEach(e=>{e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),WebXRMotionControllerManager.ClearControllerCache()}};let WebXRControllerPointerSelection=class WebXRControllerPointerSelection extends WebXRAbstractFeature{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;let{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 ray_Ray(new math_vector_Vector3,new math_vector_Vector3),disabledByNearInteraction:!1,id:WebXRControllerPointerSelection._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 math_vector_Vector3,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new math_color_Color3(.9,.9,.9),this.laserPointerDefaultColor=new math_color_Color3(.7,.7,.7),this.selectionMeshDefaultColor=new math_color_Color3(.8,.8,.8),this.selectionMeshPickedColor=new math_color_Color3(.3,.3,1),this._identityMatrix=math_vector_Matrix.Identity(),this._screenCoordinatesRef=math_vector_Vector3.Zero(),this._viewportRef=new math_viewport_Viewport(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){let 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 ray_Ray(new math_vector_Vector3,new math_vector_Vector3),disabledByNearInteraction:!1,id:WebXRControllerPointerSelection._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){let t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null}_getPointerSelectionDisabledByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].disabledByNearInteraction;return!0}_setPointerSelectionDisabledByPointerId(e,t){let i=Object.keys(this._controllers);for(let r=0;r<i.length;++r)if(this._controllers[i[r]].id===e){this._controllers[i[r]].disabledByNearInteraction=t;return}}_onXRFrame(e){Object.keys(this._controllers).forEach(e=>{let t;let i=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||i.disabledByNearInteraction){i.selectionMesh.isVisible=!1,i.laserPointer.isVisible=!1,i.pick=null;return}if(i.laserPointer.isVisible=this.displayLaserPointer,i.xrController)t=i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay);else{if(!i.webXRCamera)return;t=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay)}if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&t){let e=this._xrSessionManager.scene,r=this._options.xrInput.xrCamera;!r||(r.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),math_vector_Vector3.ProjectToRef(t,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,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));let s=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);r&&r.hit?s&&s.hit?r.distance<s.distance?i.pick=r:i.pick=s:i.pick=r:i.pick=s,i.pick&&i.xrController&&(i.pick.aimTransform=i.xrController.pointer,i.pick.gripTransform=i.xrController.grip||null);let a=i.pick;if(a&&a.pickedPoint&&a.hit){this._updatePointerDistance(i.laserPointer,a.distance),i.selectionMesh.position.copyFrom(a.pickedPoint),i.selectionMesh.scaling.x=Math.sqrt(a.distance),i.selectionMesh.scaling.y=Math.sqrt(a.distance),i.selectionMesh.scaling.z=Math.sqrt(a.distance);let e=this._convertNormalToDirectionOfRay(a.getNormal(!0),i.tmpRay);if(i.selectionMesh.position.copyFrom(a.pickedPoint),e){let t=math_vector_Vector3.Cross(math_axis_Axis.Y,e),r=math_vector_Vector3.Cross(e,t);math_vector_Vector3.RotationFromAxisToRef(r,e,t,i.selectionMesh.rotation),i.selectionMesh.position.addInPlace(e.scale(.001))}i.selectionMesh.isVisible=this.displaySelectionMesh,i.meshUnderPointer=a.pickedMesh}else i.selectionMesh.isVisible=!1,this._updatePointerDistance(i.laserPointer,1),i.meshUnderPointer=null})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene}_attachGazeMode(e){let t=this._controllers[e&&e.uniqueId||"camera"],i=this._options.timeToSelect||3e3,r=this._options.useUtilityLayer?this._utilityLayerScene:this._scene,s=new PickingInfo,a=CreateTorus("selection",{diameter:.0525,thickness:.015,tessellation:20},r);a.isVisible=!1,a.isPickable=!1,a.parent=t.selectionMesh;let n=0,o=!1,l={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,a.isVisible=!1,t.pick.hit){if(this._pickingMoved(s,t.pick))o&&!this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),o=!1,n=0;else if(n>i/10&&(a.isVisible=!0),(n+=this._scene.getEngine().getDeltaTime())>=i)this._scene.simulatePointerDown(t.pick,l),o=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),a.isVisible=!1;else{let e=1-n/i;a.scaling.set(e,e,e)}}else o=!1,n=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}}),void 0!==this._options.renderingGroupId&&(a.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&o&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),a.dispose()})}_attachScreenRayMode(e){let t=this._controllers[e.uniqueId],i=!1,r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),t.pick&&(!this._options.disablePointerUpOnTouchOut||!i)&&(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)})})}_attachTrackedPointerRayMode(e){let t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);let 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){let init=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(r=>{if(r.changes.pressed){let s=r.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?init(e.motionController):e.onMotionControllerInitObservable.add(init)}else{let selectStartListener=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)},selectEndListener=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:selectEndListener,selectstart:selectStartListener},this._xrSessionManager.session.addEventListener("selectstart",selectStartListener),this._xrSessionManager.session.addEventListener("selectend",selectEndListener)}}_convertNormalToDirectionOfRay(e,t){if(e){let i=Math.acos(math_vector_Vector3.Dot(e,t.direction));i<Math.PI/2&&e.scaleInPlace(-1)}return e}_detachController(e){let t=this._controllers[e];if(t){if(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=>{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),!t.finalPointerUpTriggered&&t.pointerDownTriggered){let e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame(()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new PickingInfo,e),t.finalPointerUpTriggered=!0})}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){tools_Tools.Warn("controller already detached.")}})}}_generateNewMeshPair(e){let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():cylinderBuilder_CreateCylinder("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;let r=new standardMaterial_StandardMaterial("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;let s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():CreateTorus("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;let a=new standardMaterial_StandardMaterial("targetMat",t);return a.specularColor=math_color_Color3.Black(),a.emissiveColor=this.selectionMeshDefaultColor,a.backFaceCulling=!1,s.material=a,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||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||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));let r=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance,s=this._tmpVectorForPickCompare.length();return s>r}_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}};WebXRControllerPointerSelection._IdCounter=200,WebXRControllerPointerSelection.Name=webXRFeaturesManager_WebXRFeatureName.POINTER_SELECTION,WebXRControllerPointerSelection.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name,(e,t)=>()=>new WebXRControllerPointerSelection(e,t),WebXRControllerPointerSelection.Version,!0),subMesh_SubMesh.prototype._projectOnTrianglesToRef=function(e,t,i,r,s,a){let n=math_vector_TmpVectors.Vector3[0],o=math_vector_TmpVectors.Vector3[1],l=Infinity;for(let a=this.indexStart;a<this.indexStart+this.indexCount-(3-r);a+=r){let r=i[a],h=i[a+1],c=i[a+2];if(s&&4294967295===c){a+=2;continue}let u=t[r],d=t[h],_=t[c];if(!u||!d||!_)continue;let p=math_vector_Vector3.ProjectOnTriangleToRef(e,u,d,_,o);p<l&&(n.copyFrom(o),l=p)}return a.copyFrom(n),l},subMesh_SubMesh.prototype._projectOnUnIndexedTrianglesToRef=function(e,t,i,r){let s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[1],n=Infinity;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=3){let r=t[i],o=t[i+1],l=t[i+2],h=math_vector_Vector3.ProjectOnTriangleToRef(e,r,o,l,a);h<n&&(s.copyFrom(a),n=h)}return r.copyFrom(s),n},subMesh_SubMesh.prototype.projectToRef=function(e,t,i,r){let s=this.getMaterial();if(!s)return -1;let a=3,n=!1;switch(s.fillMode){case 3:case 5:case 6:case 8:return -1;case 7:a=1,n=!0}return 4===s.fillMode?-1:!i.length&&this._mesh._unIndexed?this._projectOnUnIndexedTrianglesToRef(e,t,i,r):this._projectOnTrianglesToRef(e,t,i,a,n,r)},function(e){e[e.DEHYDRATED=0]="DEHYDRATED",e[e.HOVER=1]="HOVER",e[e.TOUCH=2]="TOUCH"}(tT||(tT={})),function(e){e[e.DISABLED=0]="DISABLED",e[e.CENTERED_ON_CONTROLLER=1]="CENTERED_ON_CONTROLLER",e[e.CENTERED_IN_FRONT=2]="CENTERED_IN_FRONT"}(tS||(tS={}));let WebXRNearInteraction=class WebXRNearInteraction extends WebXRAbstractFeature{constructor(e,t){super(e),this._options=t,this._tmpRay=new ray_Ray(new math_vector_Vector3,new math_vector_Vector3),this._attachController=e=>{if(this._controllers[e.uniqueId])return;let{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r,currentAnimationState:tT.DEHYDRATED,grabRay:new ray_Ray(new math_vector_Vector3,new math_vector_Vector3),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:WebXRNearInteraction._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 math_color_Color3(.8,.8,.8),this.selectionMeshPickedColor=new math_color_Color3(.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=tS.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){let t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null}setFarInteractionFeature(e){this._farInteractionFeature=e}_nearPickPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearPickable}_nearGrabPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearGrabbable}_nearInteractionPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&(e.isNearPickable||e.isNearGrabbable)}_controllerAvailablePredicate(e,t){let i=e;for(;i;){if(i.reservedDataStore&&i.reservedDataStore.nearInteraction&&i.reservedDataStore.nearInteraction.excludedControllerId===t)return!1;i=i.parent}return!0}_handleTransitionAnimation(e,t){var i;if(e.currentAnimationState!==t&&this._options.nearInteractionControllerMode===tS.CENTERED_IN_FRONT&&(null===(i=e.xrController)||void 0===i||!i.inputSource.hand)){if(t>e.currentAnimationState)switch(e.currentAnimationState){case tT.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===tT.HOVER)break;case tT.HOVER:e.touchCollisionMeshFunction(!0),tT.TOUCH}else switch(e.currentAnimationState){case tT.TOUCH:if(e.touchCollisionMeshFunction(!1),t===tT.HOVER)break;case tT.HOVER:e.hydrateCollisionMeshFunction(!1),tT.DEHYDRATED}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var r;let s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(math_vector_TmpVectors.Vector3[0]),s.grabRay.direction.copyFrom(math_vector_TmpVectors.Vector3[0]),this._options.nearInteractionControllerMode!==tS.CENTERED_IN_FRONT||(null===(r=s.xrController)||void 0===r?void 0:r.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;let r=this._controllers[t],s=null===(i=r.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!r.xrController||!s&&(!this._options.nearInteractionControllerMode||!r.xrController.inputSource.gamepad)){r.pick=null;return}if(r.hoverInteraction=!1,r.nearInteraction=!1,!r.xrController)return;if(s){let i=s.get("index-finger-tip");if(i){let r=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(r&&r.transform){let e=this._scene.useRightHandedSystem?1:-1;math_vector_TmpVectors.Vector3[0].set(r.transform.position.x,r.transform.position.y,r.transform.position.z*e),math_vector_TmpVectors.Quaternion[0].set(r.transform.orientation.x,r.transform.orientation.y,r.transform.orientation.z*e,r.transform.orientation.w*e),this._processTouchPoint(t,math_vector_TmpVectors.Vector3[0],math_vector_TmpVectors.Quaternion[0])}}}else if(r.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==tS.DISABLED){let e=r.xrController.pointer;r.xrController.grip&&this._options.nearInteractionControllerMode===tS.CENTERED_ON_CONTROLLER&&(e=r.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}let accuratePickInfo=(e,t)=>t&&t.hit?e&&e.hit?t.distance<e.distance?t:e:t:e,populateNearInteractionInfo=e=>{let t=new PickingInfo,i=!1,r=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),r&&!i&&(t=e),t};if(!r.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,this._hoverRadius,this._utilityLayerScene,e=>this._nearInteractionPredicate(e)));let i=this._pickWithSphere(r,this._hoverRadius,this._scene,e=>this._nearInteractionPredicate(e)),a=accuratePickInfo(i,t);if(a&&a.hit&&(e=populateNearInteractionInfo(a)).hit&&(r.hoverInteraction=!0),r.hoverInteraction){let t=null,i=s?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,i,this._utilityLayerScene,e=>this._nearPickPredicate(e)));let a=this._pickWithSphere(r,i,this._scene,e=>this._nearPickPredicate(e)),n=accuratePickInfo(a,t),o=populateNearInteractionInfo(n);o.hit&&(e=o,r.nearInteraction=!0)}r.stalePick=r.pick,r.pick=e,r.pick&&r.pick.pickedPoint&&r.pick.hit?(r.meshUnderPointer=r.pick.pickedMesh,r.pickedPointVisualCue.position.copyFrom(r.pick.pickedPoint),r.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!0)):(r.meshUnderPointer=null,r.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!1))}let a=tT.DEHYDRATED;r.grabInteraction||r.nearInteraction?a=tT.TOUCH:r.hoverInteraction&&(a=tT.HOVER),this._handleTransitionAnimation(r,a)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,t=sphereBuilder_CreateSphere("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=math_vector_Quaternion.Identity();let i=new standardMaterial_StandardMaterial("targetMat",e);return i.specularColor=math_color_Color3.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){let 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))});let grabCheck=r=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),r&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!r||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){let init=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(e=>{if(e.changes.pressed){let t=e.changes.pressed.current;grabCheck(t)}}):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(e=>{if(e.changes.pressed){let t=e.changes.pressed.current;grabCheck(t)}}))};e.motionController?init(e.motionController):e.onMotionControllerInitObservable.add(init)}else{let selectStartListener=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))},selectEndListener=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:selectEndListener,selectstart:selectStartListener},this._xrSessionManager.session.addEventListener("selectstart",selectStartListener),this._xrSessionManager.session.addEventListener("selectend",selectEndListener)}}_detachController(e){let 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=>{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{let e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new PickingInfo,e)}),delete this._controllers[e],this._attachedController===e)){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,t=sphereBuilder_CreateSphere("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:NodeMaterial.ParseFromSnippetAsync("8RUNKL#3",e).then(e=>{t.material=e});let i=new QuadraticEase;i.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);let r=new math_vector_Vector3(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),s=this._controllerPickRadius*(4/3),a=new math_vector_Vector3(s,s,s),n=this._controllerPickRadius*(7/6),o=new math_vector_Vector3(n,n,n),l=.8*this._controllerPickRadius,h=new math_vector_Vector3(l,l,l),c=1.5*this._controllerPickRadius,u=new math_vector_Vector3(c,c,c),d=[{frame:0,value:r},{frame:10,value:u},{frame:18,value:a}],_=[{frame:0,value:a},{frame:10,value:h},{frame:18,value:r}],p=[{frame:0,value:math_vector_Vector3.ZeroReadOnly},{frame:12,value:o},{frame:15,value:r}],f=[{frame:0,value:r},{frame:10,value:math_vector_Vector3.ZeroReadOnly},{frame:15,value:math_vector_Vector3.ZeroReadOnly}],m=new animation_Animation("touch","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),g=new animation_Animation("release","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),v=new animation_Animation("hydrate","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),x=new animation_Animation("dehydrate","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),x.setEasingFunction(i),m.setKeys(d),g.setKeys(_),v.setKeys(p),x.setKeys(f),{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{let r=i?m:g;e.beginDirectAnimation(t,[r],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{let r=i?v:x;i&&(t.isVisible=!0),e.beginDirectAnimation(t,[r],0,15,!1,1,()=>{i||(t.isVisible=!1)})}}}_pickWithSphere(e,t,i,r){let s=new PickingInfo;if(s.distance=Infinity,e.touchCollisionMesh&&e.xrController){let a=e.touchCollisionMesh.position,n=boundingSphere_BoundingSphere.CreateFromCenterAndRadius(a,t);for(let t=0;t<i.meshes.length;t++){let a=i.meshes[t];if(!r(a)||!this._controllerAvailablePredicate(a,e.xrController.uniqueId))continue;let o=WebXRNearInteraction.PickMeshWithSphere(a,n);o&&o.hit&&o.distance<s.distance&&(s.hit=o.hit,s.pickedMesh=a,s.pickedPoint=o.pickedPoint,s.aimTransform=e.xrController.pointer,s.gripTransform=e.xrController.grip||null,s.originMesh=e.touchCollisionMesh,s.distance=o.distance)}}return s}static PickMeshWithSphere(e,t,i=!1){let r,s,a;let n=e.subMeshes,o=new PickingInfo,l=e.getBoundingInfo();if(!e._generatePointsArray()||!e.subMeshes||!l||!i&&!boundingSphere_BoundingSphere.Intersects(l.boundingSphere,t))return o;let h=math_vector_TmpVectors.Vector3[0],c=math_vector_TmpVectors.Vector3[1],u=Infinity,d=math_vector_TmpVectors.Vector3[2],_=math_vector_TmpVectors.Matrix[0];_.copyFrom(e.getWorldMatrix()),_.invert(),math_vector_Vector3.TransformCoordinatesToRef(t.center,_,d);for(let i=0;i<n.length;i++){let o=n[i];o.projectToRef(d,e._positions,e.getIndices(),c),math_vector_Vector3.TransformCoordinatesToRef(c,e.getWorldMatrix(),c),r=math_vector_Vector3.Distance(c,t.center),a=math_vector_Vector3.Distance(c,e.getAbsolutePosition()),-1!==(s=math_vector_Vector3.Distance(t.center,e.getAbsolutePosition()))&&-1!==a&&a>s&&(r=0,c.copyFrom(t.center)),-1!==r&&r<u&&(u=r,h.copyFrom(c))}return u<t.radius&&(o.hit=!0,o.distance=u,o.pickedMesh=e,o.pickedPoint=h.clone()),o}};WebXRNearInteraction._IdCounter=200,WebXRNearInteraction.Name=webXRFeaturesManager_WebXRFeatureName.NEAR_INTERACTION,WebXRNearInteraction.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRNearInteraction.Name,(e,t)=>()=>new WebXRNearInteraction(e,t),WebXRNearInteraction.Version,!0);let WebXREnterExitUIButton=class WebXREnterExitUIButton{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}};let WebXREnterExitUI=class WebXREnterExitUI{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new observable_Observable,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 tools_Tools.Warn("WebXR can only be served over HTTPS"),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;";let e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor",r="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",s=".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("+r+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';let a=document.createElement("style");a.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(a);let n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new WebXREnterExitUIButton(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}let 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;let i=this._buttons.map(t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode));e.onStateChangedObservable.add(e=>{e==eB.NOT_IN_XR&&this._updateButtons(null)});let r=await Promise.all(i);r.forEach((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):tools_Tools.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){let r=new WebXREnterExitUI(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(this._helper.state==eB.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==eB.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(r){this._updateButtons(null);let t=this._buttons[e].element,i=t.title;t.title="Error entering XR session : "+i,t.classList.add("xr-error"),this.options.onError&&this.options.onError(r)}}dispose(){let 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 setAndStartTimer(e){var t;let i=0,r=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};let s=e.contextObservable.add(t=>{let a=Date.now();i=a-r;let n={startTime:r,currentTime:a,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(n),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(n)),i>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(n))},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"}(tC||(tC={}));let AdvancedTimer=class AdvancedTimer{constructor(e){var t,i;this.onEachCountObservable=new observable_Observable,this.onTimerAbortedObservable=new observable_Observable,this.onTimerEndedObservable=new observable_Observable,this.onStateChangedObservable=new observable_Observable,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{let t=Date.now();this._timer=t-this._startTime;let i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},r=this._breakOnNextTick||this._breakCondition(i);r||this._timer>=this._timeToEnd?this._stop(i,r):this.onEachCountObservable.notifyObservers(i)},this._setState(tC.INIT),this._contextObservable=e.contextObservable,this._observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{},this._breakCondition=null!==(i=e.breakCondition)&&void 0!==i?i:()=>!1,this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===tC.STARTED)throw Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(tC.STARTED)}stop(){this._state===tC.STARTED&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(tC.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}};let WebXRMotionControllerTeleportation=class WebXRMotionControllerTeleportation extends WebXRAbstractFeature{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){let 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 math_color_Color4(1,1,1,1),this._tmpRay=new ray_Ray(new math_vector_Vector3,new math_vector_Vector3),this._tmpVector=new math_vector_Vector3,this._tmpQuaternion=new math_vector_Quaternion,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 observable_Observable,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}};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let initMotionController=()=>{if(e.motionController){let i=e.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){let 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;let r=this._options.timeToTeleport||3e3;setAndStartTimer({timeout:r,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,math_vector_Quaternion.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);let 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;let e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);math_vector_Quaternion.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?initMotionController():e.onMotionControllerInitObservable.addOnce(()=>{initMotionController()})}else this._xrSessionManager.scene.onPointerObservable.add(i=>{if(i.type===pointerEvents_PointerEventTypes.POINTERDOWN){t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0;let i=this._options.timeToTeleport||3e3;setAndStartTimer({timeout:i,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else i.type===pointerEvents_PointerEventTypes.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 math_color_Color4(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){let t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];let t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){let 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<this._snapToPositions.length;++i)if(this._snapToPositions[i].equals(e)){t=i;break}}return -1!==t&&(this._snapToPositions.splice(t,1),!0)}setSelectionFeature(e){this._selectionFeature=e}_onXRFrame(e){let t=this._xrSessionManager.currentFrame,i=this._xrSessionManager.scene;if(!this.attach||!t)return;let r=this._options.teleportationTargetMesh;if(this._currentTeleportationControllerId){if(!r)return;r.rotationQuaternion=r.rotationQuaternion||new math_vector_Quaternion;let e=this._controllers[this._currentTeleportationControllerId];if(e&&e.teleportationState.forward){math_vector_Quaternion.RotationYawPitchRollToRef(e.teleportationState.currentRotation+e.teleportationState.baseRotation,0,0,r.rotationQuaternion);let t=!1;if(e.xrController.getWorldPointerRayToRef(this._tmpRay),this.straightRayEnabled){let r=i.pickWithRay(this._tmpRay,e=>{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;let t=this._floorMeshes.indexOf(e);return -1!==t&&this._floorMeshes[t].absolutePosition.y<this._options.xrInput.xrCamera.globalPosition.y});if(r&&r.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(r.pickedMesh)){e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(r);return}r&&r.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(r),this._setTargetMeshVisibility(!0),this._showParabolicPath(r))}if(this.parabolicRayEnabled&&!t){let r=e.xrController.pointer.rotationQuaternion.toEulerAngles().x,s=this.parabolicCheckRadius*(1+(Math.PI/2-Math.abs(r)));this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(2*s),this._tmpVector),this._tmpVector.y=this._tmpRay.origin.y,this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(s)),this._tmpVector.subtractToRef(this._tmpRay.origin,this._tmpRay.direction),this._tmpRay.direction.normalize();let a=i.pickWithRay(this._tmpRay,e=>!!this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e)||-1!==this._floorMeshes.indexOf(e));if(a&&a.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(a.pickedMesh)){e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(a);return}a&&a.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0),this._showParabolicPath(a))}this._setTargetMeshVisibility(t)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{let i=new DynamicTexture("teleportationPlaneDynamicTexture",512,e,!0);i.hasAlpha=!0;let r=i.getContext();r.beginPath(),r.arc(256,256,200,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),i.update();let s=new standardMaterial_StandardMaterial("teleportationPlaneMaterial",e);s.diffuseTexture=i,t.material=s}let i=CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){let t=new animation_Animation("animationInnerCircle","position.y",30,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),t.setKeys(r);let s=new SineEase;s.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}let r=cylinderBuilder_CreateCylinder("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate(math_axis_Axis.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{let t=new standardMaterial_StandardMaterial("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new math_color_Color3(.3,.3,1):t.diffuseColor=new math_color_Color3(.3,.3,1),t.alpha=.9,i.material=t,r.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){let t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){let s=t*t;this._snapToPositions.forEach(t=>{let a=math_vector_Vector3.DistanceSquared(t,e);a<=s&&a<r&&(r=a,i=t)})}return i}_setTargetMeshPosition(e){let t=e.pickedPoint;if(!this._options.teleportationTargetMesh||!t)return;let i=this._findClosestSnapPointWithRadius(t);this._snappedToPoint=!!i,this.snapPointsOnly&&!this._snappedToPoint&&this._teleportationRingMaterial?this._teleportationRingMaterial.diffuseColor.set(1,.3,.3):this.snapPointsOnly&&this._snappedToPoint&&this._teleportationRingMaterial&&this._teleportationRingMaterial.diffuseColor.set(.3,.3,1),this._options.teleportationTargetMesh.position.copyFrom(i||t),this._options.teleportationTargetMesh.position.y+=.01,this.onTargetMeshPositionUpdatedObservable.notifyObservers(e)}_setTargetMeshVisibility(e,t){this._options.teleportationTargetMesh&&(this._options.teleportationTargetMesh.isVisible!==e||t)&&(this._options.teleportationTargetMesh.isVisible=e,this._options.teleportationTargetMesh.getChildren(void 0,!1).forEach(t=>{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;let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=Curve3.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,a=Array(26).fill(s||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=linesBuilder_CreateLines("teleportation path line",{points:r.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:a},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){let t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint)){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){let 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,math_vector_Quaternion.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)}}}};WebXRMotionControllerTeleportation.Name=webXRFeaturesManager_WebXRFeatureName.TELEPORTATION,WebXRMotionControllerTeleportation.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name,(e,t)=>()=>new WebXRMotionControllerTeleportation(e,t),WebXRMotionControllerTeleportation.Version,!0);let WebXRDefaultExperience=class WebXRDefaultExperience{constructor(){}static CreateAsync(e,t={}){let i=new WebXRDefaultExperience;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){let r=Object.assign({renderTarget:i.renderTarget},t.uiOptions||{});t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new WebXREnterExitUI(e,r)}return WebXRExperienceHelper.CreateAsync(e).then(e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new WebXRInput(e.sessionManager,e.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){let e=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.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(WebXRNearInteraction.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=>(logger_Logger.Error("Error initializing XR"),logger_Logger.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 removeSource(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}scene_Scene.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;e<this.lights.length;e++)this.lights[e].dispose();0===this.lights.length&&new HemisphericLight("default light",math_vector_Vector3.Up(),this)},scene_Scene.prototype.createDefaultCamera=function(e=!1,t=!1,i=!1){if(t&&this.activeCamera&&(this.activeCamera.dispose(),this.activeCamera=null),!this.activeCamera){let t;let r=this.getWorldExtends(e=>e.isVisible&&e.isEnabled()),s=r.max.subtract(r.min),a=r.min.add(s.scale(.5)),n=1.5*s.length();if(isFinite(n)||(n=1,a.copyFromFloats(0,0,0)),e){let e=new ArcRotateCamera("default camera",-(Math.PI/2),Math.PI/2,n,a,this);e.lowerRadiusLimit=.01*n,e.wheelPrecision=100/n,t=e}else{let e=new FreeCamera("default camera",new math_vector_Vector3(a.x,a.y,-n),this);e.setTarget(a),t=e}t.minZ=.01*n,t.maxZ=1e3*n,t.speed=.2*n,this.activeCamera=t,i&&t.attachControl()}},scene_Scene.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},scene_Scene.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,r=0,s=!0){if(!e)return logger_Logger.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);let a=boxBuilder_CreateBox("hdrSkyBox",{size:i},this);if(t){let t=new pbrMaterial_PBRMaterial("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=texture_Texture.SKYBOX_MODE),t.microSurface=1-r,t.disableLighting=!0,t.twoSidedLighting=!0,a.material=t}else{let t=new standardMaterial_StandardMaterial("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=texture_Texture.SKYBOX_MODE),t.disableLighting=!0,a.material=t}return a.isPickable=!1,a.infiniteDistance=!0,a.ignoreCameraMaxZ=!0,a},scene_Scene.prototype.createDefaultEnvironment=function(e){return EnvironmentHelper?new EnvironmentHelper(e,this):null},scene_Scene.prototype.createDefaultVRExperience=function(e={}){return new VRExperienceHelper(this,e)},scene_Scene.prototype.createDefaultXRExperienceAsync=function(e={}){return WebXRDefaultExperience.CreateAsync(this,e).then(e=>e)};let VideoTexture=class VideoTexture extends texture_Texture{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new observable_Observable),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):logger_Logger.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if((null==e?void 0:e.name)==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}if(!this.video.muted){logger_Logger.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,this.video.play().catch(e=>{this._processError(e)});return}}this._processError(e)})}constructor(e,t,i,r=!1,s=!1,a=texture_Texture.TRILINEAR_SAMPLINGMODE,n={},o,l=5){var h,c;super(null,i,!r,s),this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{var e;null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||tools_Tools.IsExponentOfTwo(this.video.videoWidth)&&tools_Tools.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=texture_Texture.WRAP_ADDRESSMODE,this.wrapV=texture_Texture.WRAP_ADDRESSMODE):(this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.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{let 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||this.video.readyState<this.video.HAVE_CURRENT_DATA||this._displayingPosterTexture)return;let e=this.getScene().getFrameId();this._frameId!==e&&(this._frameId=e,this._getEngine().updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:this.video,this._invertY))},this._settings=Object.assign({autoPlay:!0,loop:!0,autoUpdateTexture:!0},n),this._onError=o,this._generateMipMaps=r,this._initialSamplingMode=a,this.autoUpdateTexture=this._settings.autoUpdateTexture,this._currentSrc=t,this.name=e||this._getName(t),this.video=this._getVideo(t),this._externalTexture=null!==(c=null===(h=this._engine)||void 0===h?void 0:h.createExternalTexture(this.video))&&void 0!==c?c:null,!this._settings.independentVideoSource&&(this._settings.poster&&(this.video.poster=this._settings.poster),void 0!==this._settings.autoPlay&&(this.video.autoplay=this._settings.autoPlay),void 0!==this._settings.loop&&(this.video.loop=this._settings.loop),void 0!==this._settings.muted&&(this.video.muted=this._settings.muted),this.video.setAttribute("playsinline",""),this.video.addEventListener("paused",this._updateInternalTexture),this.video.addEventListener("seeked",this._updateInternalTexture),this.video.addEventListener("emptied",this._reset),this._settings.autoPlay&&this._handlePlay()),this._createInternalTextureOnEvent=this._settings.poster&&!this._settings.autoPlay?"play":"canplay",this.video.addEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._format=l;let u=this.video.readyState>=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return tools_Tools.SetCorsBehavior(e.currentSrc,e),e;let t=document.createElement("video");return"string"==typeof e?(tools_Tools.SetCorsBehavior(e,t),t.src=e):(tools_Tools.SetCorsBehavior(e[0],t),e.forEach(e=>{let i=document.createElement("source");i.src=e,t.appendChild(i)})),this.onDisposeObservable.addOnce(()=>{removeSource(t)}),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){!e||this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture())}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new VideoTexture(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,r=!0){let 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=>{let onPlaying=()=>{let i=new VideoTexture("video",s,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&i.onDisposeObservable.addOnce(()=>{s.remove()}),i.onDisposeObservable.addOnce(()=>{removeSource(s)}),t(i),s.removeEventListener("playing",onPlaying)};s.addEventListener("playing",onPlaying),s.play()})}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){let s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),a=await this.CreateFromStreamAsync(e,s,t,r);return a.onDisposeObservable.addOnce(()=>{s.getTracks().forEach(e=>{e.stop()})}),a}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,s=!0){this.CreateFromWebCamAsync(e,i,r,s).then(function(e){t&&t(e)}).catch(function(e){logger_Logger.Error(e.name)})}};__decorate([serialize("settings")],VideoTexture.prototype,"_settings",void 0),__decorate([serialize("src")],VideoTexture.prototype,"_currentSrc",void 0),__decorate([serialize()],VideoTexture.prototype,"isVideo",void 0),texture_Texture._CreateVideoTexture=(e,t,i,r=!1,s=!1,a=texture_Texture.TRILINEAR_SAMPLINGMODE,n={},o,l=5)=>new VideoTexture(e,t,i,r,s,a,n,o,l),h["BABYLON.VideoTexture"]=VideoTexture;let VideoDome=class VideoDome extends TextureDome{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){let r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new VideoTexture((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,texture_Texture.TRILINEAR_SAMPLINGMODE,r);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()},pointerEvents_PointerEventTypes.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)}};VideoDome.MODE_MONOSCOPIC=TextureDome.MODE_MONOSCOPIC,VideoDome.MODE_TOPBOTTOM=TextureDome.MODE_TOPBOTTOM,VideoDome.MODE_SIDEBYSIDE=TextureDome.MODE_SIDEBYSIDE;let af=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) +#include<helperFunctions> +#endif +#ifdef DIFFUSE +varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; +#endif +#ifdef OPACITY +varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; +#endif +#ifdef EMISSIVE +varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; +#endif +#ifdef VERTEXALPHA +varying vec4 vColor; +#endif +uniform vec4 glowColor;uniform float glowIntensity; +#include<clipPlaneFragmentDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include<clipPlaneFragment> +vec4 finalColor=glowColor; +#ifdef DIFFUSE +vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); +#ifdef DIFFUSE_ISLINEAR +albedoTexture=toGammaSpace(albedoTexture); +#endif +#ifdef GLOW +finalColor.a*=albedoTexture.a; +#endif +#ifdef HIGHLIGHT +finalColor.a=albedoTexture.a; +#endif +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); +#ifdef OPACITYRGB +finalColor.a*=getLuminance(opacityMap.rgb); +#else +finalColor.a*=opacityMap.a; +#endif +finalColor.a*=opacityIntensity; +#endif +#ifdef VERTEXALPHA +finalColor.a*=vColor.a; +#endif +#ifdef ALPHATEST +if (finalColor.a<ALPHATESTVALUE) +discard; +#endif +#ifdef EMISSIVE +vec4 emissive=texture2D(emissiveSampler,vUVEmissive); +#ifdef EMISSIVE_ISLINEAR +emissive=toGammaSpace(emissive); +#endif +gl_FragColor=emissive*finalColor*glowIntensity; +#else +gl_FragColor=finalColor*glowIntensity; +#endif +#ifdef HIGHLIGHT +gl_FragColor.a=glowColor.a; +#endif +}`;ShaderStore.ShadersStore.glowMapGenerationPixelShader=af;let am=`attribute vec3 position; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<clipPlaneVertexDeclaration> +#include<instancesDeclaration> +uniform mat4 viewProjection;varying vec4 vPosition; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef DIFFUSE +varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; +#endif +#ifdef OPACITY +varying vec2 vUVOpacity;uniform mat4 opacityMatrix; +#endif +#ifdef EMISSIVE +varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; +#endif +#ifdef VERTEXALPHA +attribute vec4 color;varying vec4 vColor; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef CUBEMAP +vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); +#else +vPosition=viewProjection*worldPos;gl_Position=vPosition; +#endif +#ifdef DIFFUSE +#ifdef DIFFUSEUV1 +vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef DIFFUSEUV2 +vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef OPACITY +#ifdef OPACITYUV1 +vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef OPACITYUV2 +vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef EMISSIVE +#ifdef EMISSIVEUV1 +vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef EMISSIVEUV2 +vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef VERTEXALPHA +vColor=color; +#endif +#include<clipPlaneVertex> +}`;ShaderStore.ShadersStore.glowMapGenerationVertexShader=am;let EffectLayer=class EffectLayer{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i<e.length;++i){let r=e[i];t?this._materialForRendering[r.uniqueId]=[r,t]:delete this._materialForRendering[r.uniqueId]}else t?this._materialForRendering[e.uniqueId]=[e,t]:delete this._materialForRendering[e.uniqueId]}getEffectIntensity(e){var t;return null!==(t=this._effectIntensity[e.uniqueId])&&void 0!==t?t:1}setEffectIntensity(e,t){this._effectIntensity[e.uniqueId]=t}constructor(e,t){this._vertexBuffers={},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._shouldRender=!0,this._postProcesses=[],this._textures=[],this._emissiveTextureAndColor={texture:null,color:new math_color_Color4},this._effectIntensity={},this.neutralColor=new math_color_Color4,this.isEnabled=!0,this.disableBoundingBoxesFromEffectLayer=!1,this.onDisposeObservable=new observable_Observable,this.onBeforeRenderMainTextureObservable=new observable_Observable,this.onBeforeComposeObservable=new observable_Observable,this.onBeforeRenderMeshToEffect=new observable_Observable,this.onAfterRenderMeshToEffect=new observable_Observable,this.onAfterComposeObservable=new observable_Observable,this.onSizeChangedObservable=new observable_Observable,this._materialForRendering={},this.name=e,this._scene=t||engineStore_EngineStore.LastCreatedScene,EffectLayer._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.effectLayers.push(this),this._mergeDrawWrapper=[],this._generateIndexBuffer(),this._generateVertexBuffer()}_numInternalDraws(){return 1}_init(e){this._effectLayerOptions=Object.assign({mainTextureRatio:.5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,generateStencilBuffer:!1},e),this._setMainTextureSize(),this._createMainTexture(),this._createTextureAndPostProcesses()}_generateIndexBuffer(){let e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._engine.createIndexBuffer(e)}_generateVertexBuffer(){let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1);let t=new buffer_VertexBuffer(this._engine,e,buffer_VertexBuffer.PositionKind,!1,!1,2);this._vertexBuffers[buffer_VertexBuffer.PositionKind]=t}_setMainTextureSize(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?engine_Engine.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?engine_Engine.GetExponentOfTwo(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)}_createMainTexture(){for(let e in this._mainTexture=new renderTargetTexture_RenderTargetTexture("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,!1,!0,this._effectLayerOptions.mainTextureType,!1,texture_Texture.TRILINEAR_SAMPLINGMODE,!0,this._effectLayerOptions.generateStencilBuffer),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._materialForRendering){let[t,i]=this._materialForRendering[e];this._mainTexture.setMaterialForRendering(t,i)}if(this._mainTexture.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){let i=e.subMeshes[t],r=i.getMaterial(),s=i.getRenderingMesh();if(!r)continue;let a=s._getInstancesRenderList(i._id,!!i.getReplacementMesh()),n=a.hardwareInstancedRendering[i._id]||s.hasThinInstances;if(this._setEmissiveTextureAndColor(s,i,r),!this._isReady(i,n,this._emissiveTextureAndColor.texture))return!1}return!0},this._mainTexture.customRenderFunction=(e,t,i,r)=>{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);let a=this._scene.getEngine();if(r.length){for(a.setColorWrite(!1),s=0;s<r.length;s++)this._renderSubMesh(r.data[s]);a.setColorWrite(!0)}for(s=0;s<e.length;s++)this._renderSubMesh(e.data[s]);for(s=0;s<t.length;s++)this._renderSubMesh(t.data[s]);let n=a.getAlphaMode();for(s=0;s<i.length;s++)this._renderSubMesh(i.data[s],!0);a.setAlphaMode(n)},this._mainTexture.onClearObservable.add(e=>{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){let 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 r;let s=this._scene.getEngine(),a=e.getMesh(),n=null===(r=a._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(a,e,t);let o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);let l=[],h=[buffer_VertexBuffer.PositionKind],c=!1,u=!1;if(o){let e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(l.push("#define DIFFUSE"),a.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&1===t.coordinatesIndex?(l.push("#define DIFFUSEUV2"),u=!0):a.isVerticesDataPresent(buffer_VertexBuffer.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"));let r=o.opacityTexture;r&&(l.push("#define OPACITY"),a.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&1===r.coordinatesIndex?(l.push("#define OPACITYUV2"),u=!0):a.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(l.push("#define OPACITYUV1"),c=!0))}i&&(l.push("#define EMISSIVE"),a.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),u=!0):a.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(l.push("#define EMISSIVEUV1"),c=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),a.useVertexColors&&a.isVerticesDataPresent(buffer_VertexBuffer.ColorKind)&&a.hasVertexAlpha&&o.transparencyMode!==material_Material.MATERIAL_OPAQUE&&(h.push(buffer_VertexBuffer.ColorKind),l.push("#define VERTEXALPHA")),c&&(h.push(buffer_VertexBuffer.UVKind),l.push("#define UV1")),u&&(h.push(buffer_VertexBuffer.UV2Kind),l.push("#define UV2"));let d=new EffectFallbacks;if(a.useBones&&a.computeBonesUsingShaders){h.push(buffer_VertexBuffer.MatricesIndicesKind),h.push(buffer_VertexBuffer.MatricesWeightsKind),a.numBoneInfluencers>4&&(h.push(buffer_VertexBuffer.MatricesIndicesExtraKind),h.push(buffer_VertexBuffer.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers);let e=a.skeleton;e&&e.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),a.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,a)}else l.push("#define NUM_BONE_INFLUENCERS 0");let _=a.morphTargetManager,p=0;_&&_.numInfluencers>0&&(l.push("#define MORPHTARGETS"),p=_.numInfluencers,l.push("#define NUM_MORPH_INFLUENCERS "+p),_.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(h,a,p)),t&&(l.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),prepareStringDefinesForClipPlanes(o,this._scene,l),this._addCustomEffectDefines(l);let f=e._getDrawWrapper(void 0,!0),m=f.defines,g=l.join("\n");if(m!==g){let e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];addClipPlaneUniforms(e),f.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:p}),g)}return f.effect.isReady()}render(){for(let e=0;e<this._postProcesses.length;e++)if(!this._postProcesses[e].isReady())return;let e=this._scene.getEngine(),t=this._numInternalDraws(),i=!0;for(let e=0;e<t;++e){let t=this._mergeDrawWrapper[e];t||(t=this._mergeDrawWrapper[e]=new drawWrapper_DrawWrapper(this._engine)).setEffect(this._createMergeEffect()),i=i&&t.effect.isReady()}if(!i)return;this.onBeforeComposeObservable.notifyObservers(this);let r=e.getAlphaMode();for(let i=0;i<t;++i){let t=this._mergeDrawWrapper[i];e.enableEffect(t),e.setState(!1),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t.effect),e.setAlphaMode(this._effectLayerOptions.alphaBlendingMode),this._internalRender(t.effect,i)}e.setAlphaMode(r),this.onAfterComposeObservable.notifyObservers(this);let s=this._mainTexture.getSize();this._setMainTextureSize(),(s.width!==this._mainTextureDesiredSize.width||s.height!==this._mainTextureDesiredSize.height)&&0!==this._mainTextureDesiredSize.width&&0!==this._mainTextureDesiredSize.height&&(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses())}hasMesh(e){return -1===this.renderingGroupId||e.renderingGroupId===this.renderingGroupId}shouldRender(){return this.isEnabled&&this._shouldRender}_shouldRenderMesh(e){return!0}_canRenderMesh(e,t){return!t.needAlphaBlendingForMesh(e)}_shouldRenderEmissiveTextureForMesh(){return!0}_renderSubMesh(e,t=!1){var i,r;if(!this.shouldRender())return;let s=e.getMaterial(),a=e.getMesh(),n=e.getReplacementMesh(),o=e.getRenderingMesh(),l=e.getEffectiveMesh(),h=this._scene,c=h.getEngine();if(l._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!s||!this._canRenderMesh(o,s))return;let u=null!==(i=o.overrideMaterialSideOrientation)&&void 0!==i?i:s.sideOrientation,d=l._getWorldMatrixDeterminant();d<0&&(u=u===material_Material.ClockWiseSideOrientation?material_Material.CounterClockWiseSideOrientation:material_Material.ClockWiseSideOrientation);let _=u===material_Material.ClockWiseSideOrientation;c.setState(s.backFaceCulling,s.zOffset,void 0,_,s.cullBackFaces,void 0,s.zOffsetUnits);let p=o._getInstancesRenderList(e._id,!!n);if(p.mustReturn||!this._shouldRenderMesh(o))return;let f=p.hardwareInstancedRendering[e._id]||o.hasThinInstances;if(this._setEmissiveTextureAndColor(o,e,s),this.onBeforeRenderMeshToEffect.notifyObservers(a),this._useMeshMaterial(o))o.render(e,t,n||void 0);else if(this._isReady(e,f,this._emissiveTextureAndColor.texture)){let i=null===(r=l._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[c.currentRenderPassId],a=e._getDrawWrapper();if(!a&&i&&(a=i._getDrawWrapper()),!a)return;let n=a.effect;if(c.enableEffect(a),f||o._bind(e,n,s.fillMode),i?i.bindForSubMesh(l.getWorldMatrix(),l,e):(n.setMatrix("viewProjection",h.getTransformMatrix()),n.setMatrix("world",l.getWorldMatrix()),n.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!i){let e=s.needAlphaTesting(),i=s.getAlphaTestTexture(),r=i&&i.hasAlpha&&(s.useAlphaFromDiffuseTexture||s._useAlphaFromAlbedoTexture);if(i&&(e||r)){n.setTexture("diffuseSampler",i);let e=i.getTextureMatrix();e&&n.setMatrix("diffuseMatrix",e)}let a=s.opacityTexture;if(a){n.setTexture("opacitySampler",a),n.setFloat("opacityIntensity",a.level);let e=a.getTextureMatrix();e&&n.setMatrix("opacityMatrix",e)}if(this._emissiveTextureAndColor.texture&&(n.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),n.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),o.useBones&&o.computeBonesUsingShaders&&o.skeleton){let e=o.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(o);if(!t)return;n.setTexture("boneSampler",t),n.setFloat("boneTextureWidth",4*(e.bones.length+1))}else n.setMatrices("mBones",e.getTransformMatrices(o))}MaterialHelper.BindMorphTargetParameters(o,n),o.morphTargetManager&&o.morphTargetManager.isUsingTextureForTargets&&o.morphTargetManager._bind(n),t&&c.setAlphaMode(s.alphaMode),n.setFloat("glowIntensity",this.getEffectIntensity(o)),bindClipPlane(n,s,h)}o._processRendering(l,e,n,s.fillMode,p,f,(e,t)=>n.setMatrix("world",t))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(a)}_useMeshMaterial(e){return!1}_rebuild(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e<this._postProcesses.length;e++)this._postProcesses[e]&&this._postProcesses[e].dispose();this._postProcesses=[];for(let e=0;e<this._textures.length;e++)this._textures[e]&&this._textures[e].dispose();this._textures=[]}dispose(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];for(let t of(e&&(e.dispose(),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._mergeDrawWrapper))t.dispose();this._mergeDrawWrapper=[],this._disposeTextureAndPostProcesses();let t=this._scene.effectLayers.indexOf(this,0);t>-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){let r=tools_Tools.Instantiate(e.customType);return r.Parse(e,t,i)}};EffectLayer._SceneComponentInitialization=e=>{throw _WarnImport("EffectLayerSceneComponent")},__decorate([serialize()],EffectLayer.prototype,"name",void 0),__decorate([generateSerializableMember(8,void 0)],EffectLayer.prototype,"neutralColor",void 0),__decorate([serialize()],EffectLayer.prototype,"isEnabled",void 0),__decorate([serializeAsCameraReference()],EffectLayer.prototype,"camera",null),__decorate([serialize()],EffectLayer.prototype,"renderingGroupId",null),__decorate([serialize()],EffectLayer.prototype,"disableBoundingBoxesFromEffectLayer",void 0),AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_EFFECTLAYER,(e,t,i,r)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let s=0;s<e.effectLayers.length;s++){let a=EffectLayer.Parse(e.effectLayers[s],t,r);i.effectLayers.push(a)}}}),AbstractScene.prototype.removeEffectLayer=function(e){let t=this.effectLayers.indexOf(e);return -1!==t&&this.effectLayers.splice(t,1),t},AbstractScene.prototype.addEffectLayer=function(e){this.effectLayers.push(e)};let EffectLayerSceneComponent=class EffectLayerSceneComponent{constructor(e){if(this.name=sceneComponent_SceneComponentConstants.NAME_EFFECTLAYER,this._renderEffects=!1,this._needStencil=!1,this._previousStencilState=!1,this.scene=e||engineStore_EngineStore.LastCreatedScene,!this.scene)return;this._engine=this.scene.getEngine(),this.scene.effectLayers=[]}register(){this.scene._isReadyForMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER,this,this._isReadyForMesh),this.scene._cameraDrawRenderTargetStage.registerStep(sceneComponent_SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER,this,this._renderMainTexture),this.scene._beforeCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER,this,this._setStencil),this.scene._afterRenderingGroupDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW,this,this._drawRenderingGroup),this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER,this,this._setStencilBack),this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW,this,this._drawCamera)}rebuild(){let e=this.scene.effectLayers;for(let t of e)t._rebuild()}serialize(e){e.effectLayers=[];let t=this.scene.effectLayers;for(let i of t)i.serialize&&e.effectLayers.push(i.serialize())}addFromContainer(e){e.effectLayers&&e.effectLayers.forEach(e=>{this.scene.addEffectLayer(e)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(e=>{this.scene.removeEffectLayer(e),t&&e.dispose()})}dispose(){let e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){let i=this._engine.currentRenderPassId,r=this.scene.effectLayers;for(let s of r){if(!s.hasMesh(e))continue;let r=s._mainTexture;for(let a of(this._engine.currentRenderPassId=r.renderPassId,e.subMeshes))if(!s.isReady(a,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1,i=this.scene.effectLayers;if(i&&i.length>0){for(let r of(this._previousStencilState=this._engine.getStencilBuffer(),i))if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===camera_Camera.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==camera_Camera.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();let e=r._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);let t=this.scene.effectLayers;for(let i=0;i<t.length;i++){let r=t[i];r.renderingGroupId===e&&r.shouldRender()&&r.render()}this._engine.setDepthBuffer(!0)}}_drawCamera(){this._renderEffects&&this._draw(-1)}_drawRenderingGroup(e){!this.scene._isInIntermediateRendering()&&this._renderEffects&&this._draw(e)}};EffectLayer._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_EFFECTLAYER);t||(t=new EffectLayerSceneComponent(e),e._addComponent(t))};let ag=`varying vec2 vUV;uniform sampler2D textureSampler; +#ifdef EMISSIVE +uniform sampler2D textureSampler2; +#endif +uniform float offset; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV); +#ifdef EMISSIVE +baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; +#else +baseColor.a=abs(offset-baseColor.a); +#ifdef STROKE +float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; +#endif +#endif +#if LDR +baseColor=clamp(baseColor,0.,1.0); +#endif +gl_FragColor=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`;ShaderStore.ShadersStore.glowMapMergePixelShader=ag;let av=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.glowMapMergeVertexShader=av,AbstractScene.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()===GlowLayer.EffectName)return this.effectLayers[i];return null};let GlowLayer=class GlowLayer extends EffectLayer{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;let 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 math_color_Color4(0,0,0,1),this._options=Object.assign({mainTextureRatio:GlowLayer.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType,generateStencilBuffer:this._options.generateStencilBuffer})}getEffectName(){return GlowLayer.EffectName}_createMergeEffect(){let e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[buffer_VertexBuffer.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?engine_Engine.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?engine_Engine.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new renderTargetTexture_RenderTargetTexture("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;let r=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new renderTargetTexture_RenderTargetTexture("GlowLayerBlurRTT2",{width:r,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];let a=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new BlurPostProcess("GlowLayerHBP1",new math_vector_Vector2(1,0),a,{width:e,height:t},null,texture_Texture.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 BlurPostProcess("GlowLayerVBP1",new math_vector_Vector2(0,1),a,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new BlurPostProcess("GlowLayerHBP2",new math_vector_Vector2(1,0),a,{width:r,height:s},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new BlurPostProcess("GlowLayerVBP2",new math_vector_Vector2(0,1),a,{width:r,height:s},null,texture_Texture.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(()=>{let e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);let 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){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;let 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);let t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(material_Material.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var r;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){let e=null!==(r=i.emissiveIntensity)&&void 0!==r?r:1;s*=e,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){let 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){let 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(){let e;let t=decorators_SerializationHelper.Serialize(this);if(t.customType="BABYLON.GlowLayer",t.includedMeshes=[],this._includedOnlyMeshes.length)for(e=0;e<this._includedOnlyMeshes.length;e++){let i=this._scene.getMeshByUniqueId(this._includedOnlyMeshes[e]);i&&t.includedMeshes.push(i.id)}if(t.excludedMeshes=[],this._excludedMeshes.length)for(e=0;e<this._excludedMeshes.length;e++){let i=this._scene.getMeshByUniqueId(this._excludedMeshes[e]);i&&t.excludedMeshes.push(i.id)}return t}static Parse(e,t,i){let r;let s=decorators_SerializationHelper.Parse(()=>new GlowLayer(e.name,t,e.options),e,t,i);for(r=0;r<e.excludedMeshes.length;r++){let i=t.getMeshById(e.excludedMeshes[r]);i&&s.addExcludedMesh(i)}for(r=0;r<e.includedMeshes.length;r++){let i=t.getMeshById(e.includedMeshes[r]);i&&s.addIncludedOnlyMesh(i)}return s}};GlowLayer.EffectName="GlowLayer",GlowLayer.DefaultBlurKernelSize=32,GlowLayer.DefaultTextureRatio=.5,__decorate([serialize()],GlowLayer.prototype,"blurKernelSize",null),__decorate([serialize()],GlowLayer.prototype,"intensity",null),__decorate([serialize("options")],GlowLayer.prototype,"_options",void 0),h["BABYLON.GlowLayer"]=GlowLayer;let ax=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color) +{return dot(color,vec3(0.2126,0.7152,0.0722));} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++) +{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;} +gl_FragColor=baseColor;}`;ShaderStore.ShadersStore.glowBlurPostProcessPixelShader=ax,AbstractScene.prototype.getHighlightLayerByName=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()===HighlightLayer.EffectName)return this.effectLayers[i];return null};let GlowBlurPostProcess=class GlowBlurPostProcess extends postProcess_PostProcess{constructor(e,t,i,r,s,a=texture_Texture.BILINEAR_SAMPLINGMODE,n,o){super(e,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,r,s,a,n,o),this.direction=t,this.kernel=i,this.onApplyObservable.add(e=>{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)})}};let HighlightLayer=class HighlightLayer extends EffectLayer{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 observable_Observable,this.onAfterBlurObservable=new observable_Observable,this._instanceGlowingMeshStencilReference=HighlightLayer.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=HighlightLayer.NeutralColor,this._engine.isStencilEnable||logger_Logger.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 HighlightLayer.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[buffer_VertexBuffer.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?engine_Engine.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?engine_Engine.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new renderTargetTexture_RenderTargetTexture("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(texture_Texture.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new PassPostProcess("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new GlowBlurPostProcess("HighlightLayerHBP",new math_vector_Vector2(1,0),this._options.blurHorizontalSize,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new GlowBlurPostProcess("HighlightLayerVBP",new math_vector_Vector2(0,1),this._options.blurVerticalSize,1,null,texture_Texture.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 BlurPostProcess("HighlightLayerHBP",new math_vector_Vector2(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,texture_Texture.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 BlurPostProcess("HighlightLayerVBP",new math_vector_Vector2(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);let 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){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null,a=this._meshes[r.uniqueId];return a&&a.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);let 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(material_Material.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(material_Material.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){let r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];if(!t){let 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;let 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;let r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(e=>{this.isEnabled&&this._defaultStencilReference(e)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;let t=this._meshes[e.uniqueId];for(let i in t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1,this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(let e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){let t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(let e in this._meshes){let 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(let e in this._excludedMeshes){let 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(){let e=decorators_SerializationHelper.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(let t in this._meshes){let 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(let t in this._excludedMeshes){let i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){let r;let s=decorators_SerializationHelper.Parse(()=>new HighlightLayer(e.name,t,e.options),e,t,i);for(r=0;r<e.excludedMeshes.length;r++){let i=t.getMeshById(e.excludedMeshes[r]);i&&s.addExcludedMesh(i)}for(r=0;r<e.meshes.length;r++){let i=e.meshes[r],a=t.getMeshById(i.meshId);a&&s.addMesh(a,math_color_Color3.FromArray(i.color),i.glowEmissiveOnly)}return s}};HighlightLayer.EffectName="HighlightLayer",HighlightLayer.NeutralColor=new math_color_Color4(0,0,0,0),HighlightLayer.GlowingMeshStencilReference=2,HighlightLayer.NormalMeshStencilReference=1,__decorate([serialize()],HighlightLayer.prototype,"innerGlow",void 0),__decorate([serialize()],HighlightLayer.prototype,"outerGlow",void 0),__decorate([serialize()],HighlightLayer.prototype,"blurHorizontalSize",null),__decorate([serialize()],HighlightLayer.prototype,"blurVerticalSize",null),__decorate([serialize("options")],HighlightLayer.prototype,"_options",void 0),h["BABYLON.HighlightLayer"]=HighlightLayer;let ab=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; +#include<helperFunctions> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV); +#ifdef LINEAR +baseColor.rgb=toGammaSpace(baseColor.rgb); +#endif +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +gl_FragColor=baseColor*color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;ShaderStore.ShadersStore.layerPixelShader=ab;let aT=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.layerVertexShader=aT;let LensFlare=class LensFlare{static AddFlare(e,t,i,r,s){return new LensFlare(e,t,i,r,s)}constructor(e,t,i,r,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new math_color_Color3(1,1,1),this.texture=r?new texture_Texture(r,s.getScene(),!0):null,this._system=s;let a=s.scene.getEngine();this._drawWrapper=new drawWrapper_DrawWrapper(a),this._drawWrapper.effect=a.createEffect("lensFlare",[buffer_VertexBuffer.PositionKind],["color","viewportMatrix"],["textureSampler"],""),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();let e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}};let aS=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;ShaderStore.ShadersStore.lensFlarePixelShader=aS;let aC=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.lensFlareVertexShader=aC;let LensFlareSystem=class LensFlareSystem{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||engineStore_EngineStore.LastCreatedScene,LensFlareSystem._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&(e.layerMask&i.activeCamera.layerMask)!=0;let r=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(r,s,buffer_VertexBuffer.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){let 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=math_vector_Vector3.Project(t,math_vector_Matrix.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=math_vector_Vector3.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);let i=this._scene.useRightHandedSystem,r=t.z>0&&!i||t.z<0&&i;return!!r&&(this._positionX>e.x&&this._positionX<e.x+e.width&&this._positionY>e.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;let e=this.getEmitterPosition(),t=e.subtract(this._scene.activeCamera.globalPosition),i=t.length();t.normalize();let r=new ray_Ray(this._scene.activeCamera.globalPosition,t),s=this._scene.pickWithRay(r,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>i}render(){let e,t;if(!this._scene.activeCamera)return!1;let i=this._scene.getEngine(),r=this._scene.activeCamera.viewport,s=r.toGlobal(i.getRenderWidth(!0),i.getRenderHeight(!0));if(!this.computeEffectivePosition(s)||!this._isVisible())return!1;let a=(e=this._positionX<this.borderLimit+s.x?this.borderLimit+s.x-this._positionX:this._positionX>s.x+s.width-this.borderLimit?this._positionX-s.x-s.width+this.borderLimit:0)>(t=this._positionY<this.borderLimit+s.y?this.borderLimit+s.y-this._positionY:this._positionY>s.y+s.height-this.borderLimit?this._positionY-s.y-s.height+this.borderLimit:0)?e:t;(a-=this.viewportBorder)>this.borderLimit&&(a=this.borderLimit);let n=1-math_scalar_Scalar.Clamp(a/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(s.x+=this.viewportBorder,s.y+=this.viewportBorder,s.width-=2*this.viewportBorder,s.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);let o=s.x+s.width/2,l=s.y+s.height/2,h=o-this._positionX,c=l-this._positionY;i.setState(!1),i.setDepthBuffer(!1);for(let e=0;e<this.lensFlares.length;e++){let t=this.lensFlares[e];if(!t._drawWrapper.effect.isReady()||t.texture&&!t.texture.isReady())continue;i.enableEffect(t._drawWrapper),i.bindBuffers(this._vertexBuffers,this._indexBuffer,t._drawWrapper.effect),i.setAlphaMode(t.alphaMode);let r=o-h*t.position,a=l-c*t.position,u=t.size,d=t.size*i.getAspectRatio(this._scene.activeCamera,!0),_=2*(r/(s.width+2*s.x))-1,p=1-2*(a/(s.height+2*s.y)),f=math_vector_Matrix.FromValues(u/2,0,0,0,0,d/2,0,0,0,0,1,0,_,p,0,1);t._drawWrapper.effect.setMatrix("viewportMatrix",f),t._drawWrapper.effect.setTexture("textureSampler",t.texture),t._drawWrapper.effect.setFloat4("color",t.color.r*n,t.color.g*n,t.color.b*n,1),i.drawElementsType(material_Material.TriangleFillMode,0,6)}return i.setDepthBuffer(!0),i.setAlphaMode(0),!0}rebuild(){var e;for(let t in this._createIndexBuffer(),this._vertexBuffers)null===(e=this._vertexBuffers[t])||void 0===e||e._rebuild()}dispose(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];for(e&&(e.dispose(),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);this.lensFlares.length;)this.lensFlares[0].dispose();let t=this._scene.lensFlareSystems.indexOf(this);this._scene.lensFlareSystems.splice(t,1)}static Parse(e,t,i){let r=t.getLastEntryById(e.emitterId),s=e.name||"lensFlareSystem#"+e.emitterId,a=new LensFlareSystem(s,r,t);a.id=e.id||s,a.borderLimit=e.borderLimit;for(let t=0;t<e.flares.length;t++){let r=e.flares[t];LensFlare.AddFlare(r.size,r.position,math_color_Color3.FromArray(r.color),r.textureName?i+r.textureName:"",a)}return a}serialize(){let e={};e.id=this.id,e.name=this.name,e.emitterId=this.getEmitter().id,e.borderLimit=this.borderLimit,e.flares=[];for(let t=0;t<this.lensFlares.length;t++){let i=this.lensFlares[t];e.flares.push({size:i.size,position:i.position,color:i.color.asArray(),textureName:tools_Tools.GetFilename(i.texture?i.texture.name:"")})}return e}};LensFlareSystem._SceneComponentInitialization=e=>{throw _WarnImport("LensFlareSystemSceneComponent")},AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_LENSFLARESYSTEM,(e,t,i,r)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let s=0,a=e.lensFlareSystems.length;s<a;s++){let a=e.lensFlareSystems[s],n=LensFlareSystem.Parse(a,t,r);i.lensFlareSystems.push(n)}}}),AbstractScene.prototype.getLensFlareSystemByName=function(e){for(let t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].name===e)return this.lensFlareSystems[t];return null},AbstractScene.prototype.getLensFlareSystemById=function(e){for(let t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].id===e)return this.lensFlareSystems[t];return null},AbstractScene.prototype.getLensFlareSystemByID=function(e){return this.getLensFlareSystemById(e)},AbstractScene.prototype.removeLensFlareSystem=function(e){let t=this.lensFlareSystems.indexOf(e);return -1!==t&&this.lensFlareSystems.splice(t,1),t},AbstractScene.prototype.addLensFlareSystem=function(e){this.lensFlareSystems.push(e)};let LensFlareSystemSceneComponent=class LensFlareSystemSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_LENSFLARESYSTEM,this.scene=e,e.lensFlareSystems=[]}register(){this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM,this,this._draw)}rebuild(){for(let e=0;e<this.scene.lensFlareSystems.length;e++)this.scene.lensFlareSystems[e].rebuild()}addFromContainer(e){e.lensFlareSystems&&e.lensFlareSystems.forEach(e=>{this.scene.addLensFlareSystem(e)})}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach(e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()})}serialize(e){e.lensFlareSystems=[];let t=this.scene.lensFlareSystems;for(let i of t)e.lensFlareSystems.push(i.serialize())}dispose(){let e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){let t=this.scene.lensFlareSystems;for(let i of(tools_Tools.StartPerformanceCounter("Lens flares",t.length>0),t))(e.layerMask&i.layerMask)!=0&&i.render();tools_Tools.EndPerformanceCounter("Lens flares",t.length>0)}}};LensFlareSystem._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_LENSFLARESYSTEM);t||(t=new LensFlareSystemSceneComponent(e),e._addComponent(t))};let aE=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} +float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); +vec2 P2=floor(0.5*mod(_P,4.0)); +return 4.0*bayerDither2(P1)+bayerDither2(P2);} +float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); +vec2 P2=floor(0.5 *mod(_P,4.0)); +vec2 P4=floor(0.25*mod(_P,8.0)); +return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} +`;ShaderStore.IncludesShadersStore.bayerDitherFunctions=aE;let ay=`#if SM_FLOAT==0 +#include<packingFunctions> +#endif +#if SM_SOFTTRANSPARENTSHADOW==1 +#include<bayerDitherFunctions> +uniform float softTransparentShadowSM; +#endif +varying float vDepthMetricSM; +#if SM_USEDISTANCE==1 +uniform vec3 lightDataSM;varying vec3 vPositionWSM; +#endif +uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying float zSM; +#endif +`;ShaderStore.IncludesShadersStore.shadowMapFragmentExtraDeclaration=ay;let aR=`float depthSM=vDepthMetricSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +#if SM_USEDISTANCE==1 +depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#endif +#ifdef USE_REVERSE_DEPTHBUFFER +gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); +#else +gl_FragDepth=clamp(depthSM,0.0,1.0); +#endif +#elif SM_USEDISTANCE==1 +depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#if SM_ESM==1 +depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); +#endif +#if SM_FLOAT==1 +gl_FragColor=vec4(depthSM,1.0,1.0,1.0); +#else +gl_FragColor=pack(depthSM); +#endif +return;`;ShaderStore.IncludesShadersStore.shadowMapFragment=aR;let aP=`#include<shadowMapFragmentExtraDeclaration> +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include<clipPlaneFragmentDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include<clipPlaneFragment> +#ifdef ALPHATEXTURE +float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; +#ifdef ALPHATESTVALUE +if (alphaFromAlphaTexture<ALPHATESTVALUE) +discard; +#endif +#endif +#if SM_SOFTTRANSPARENTSHADOW==1 +#ifdef ALPHATEXTURE +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alphaFromAlphaTexture) discard; +#else +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard; +#endif +#endif +#include<shadowMapFragment> +}`;ShaderStore.ShadersStore.shadowMapPixelShader=aP;let aA=`uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; +`;ShaderStore.IncludesShadersStore.sceneVertexDeclaration=aA;let aM=`uniform mat4 world;uniform float visibility; +`;ShaderStore.IncludesShadersStore.meshVertexDeclaration=aM;let aI=`#include<sceneVertexDeclaration> +#include<meshVertexDeclaration> +`;ShaderStore.IncludesShadersStore.shadowMapVertexDeclaration=aI;let aD=`layout(std140,column_major) uniform; +#include<sceneUboDeclaration> +#include<meshUboDeclaration> +`;ShaderStore.IncludesShadersStore.shadowMapUboDeclaration=aD;let aO=`#if SM_NORMALBIAS==1 +uniform vec3 lightDataSM; +#endif +uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; +#if SM_USEDISTANCE==1 +varying vec3 vPositionWSM; +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying float zSM; +#endif +`;ShaderStore.IncludesShadersStore.shadowMapVertexExtraDeclaration=aO;let aB=`#if SM_NORMALBIAS==1 +#if SM_DIRECTIONINLIGHTDATA==1 +vec3 worldLightDirSM=normalize(-lightDataSM.xyz); +#else +vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); +#endif +float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; +#endif +`;ShaderStore.IncludesShadersStore.shadowMapVertexNormalBias=aB;let aN=`#if SM_USEDISTANCE==1 +vPositionWSM=worldPos.xyz; +#endif +#if SM_DEPTHTEXTURE==1 +#ifdef IS_NDC_HALF_ZRANGE +#define BIASFACTOR 0.5 +#else +#define BIASFACTOR 1.0 +#endif +#ifdef USE_REVERSE_DEPTHBUFFER +gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; +#else +gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; +#endif +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +zSM=gl_Position.z;gl_Position.z=0.0; +#elif SM_USEDISTANCE==0 +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#endif +`;ShaderStore.IncludesShadersStore.shadowMapVertexMetric=aN;let aF=`attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#endif +#include<helperFunctions> +#include<__decl__shadowMapVertex> +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#include<shadowMapVertexExtraDeclaration> +#include<clipPlaneVertexDeclaration> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normWorldSM=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vec3 vNormalW=normalize(normWorldSM*normalUpdated); +#endif +#endif +#include<shadowMapVertexNormalBias> +gl_Position=viewProjection*worldPos; +#include<shadowMapVertexMetric> +#ifdef ALPHATEXTURE +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#include<clipPlaneVertex> +}`;ShaderStore.ShadersStore.shadowMapVertexShader=aF;let aw=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) +for (int y=-OFFSET; y<=OFFSET; y++) +colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;ShaderStore.ShadersStore.depthBoxBlurPixelShader=aw;let aL=`#if SM_SOFTTRANSPARENTSHADOW==1 +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; +#endif +`;ShaderStore.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow=aL;let shadowGenerator_ShadowGenerator=class shadowGenerator_ShadowGenerator{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===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}if(e===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}if(e===shadowGenerator_ShadowGenerator.FILTER_PCF||e===shadowGenerator_ShadowGenerator.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===shadowGenerator_ShadowGenerator.FILTER_PCF||e===shadowGenerator_ShadowGenerator.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING}set usePoissonSampling(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_PCF}set usePercentageCloserFiltering(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_PCF);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCF)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.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===shadowGenerator_ShadowGenerator.FILTER_PCSS}set useContactHardeningShadow(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_PCSS);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCSS)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return shadowGenerator_ShadowGenerator.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(let t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;let i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(let t of e.getChildren())this.removeShadowCaster(t);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,r,s){this.onBeforeShadowMapRenderObservable=new observable_Observable,this.onAfterShadowMapRenderObservable=new observable_Observable,this.onBeforeShadowMapRenderMeshObservable=new observable_Observable,this.onAfterShadowMapRenderMeshObservable=new observable_Observable,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=shadowGenerator_ShadowGenerator.FILTER_NONE,this._filteringQuality=shadowGenerator_ShadowGenerator.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=math_vector_Vector3.Zero(),this._viewMatrix=math_vector_Matrix.Zero(),this._projectionMatrix=math_vector_Matrix.Zero(),this._transformMatrix=math_vector_Matrix.Zero(),this._cachedPosition=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=math_vector_Matrix.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=r?r:null,this._useRedTextureType=!!s;let a=t._shadowGenerators;a||(a=t._shadowGenerators=new Map),a.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}")`))),shadowGenerator_ShadowGenerator._SceneComponentInitialization(this._scene);let n=this._scene.getEngine().getCaps();i?n.textureFloatRender&&n.textureFloatLinearFiltering?this._textureType=1:n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?this._textureType=2:n.textureFloatRender&&n.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){let e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new renderTargetTexture_RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new renderTargetTexture_RenderTargetTexture(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=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,r)=>this._renderForShadowMap(e,t,i,r),this._shadowMap.customIsReadyFunction=()=>!0;let 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===shadowGenerator_ShadowGenerator.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===shadowGenerator_ShadowGenerator.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){null===(t=e._debugPopGroup)||void 0===t||t.call(e,1);return}let r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))});let t=new math_color_Color4(0,0,0,0),i=new math_color_Color4(1,1,1,1);this._shadowMap.onClearObservable.add(e=>{this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let e=RenderingManager.MIN_RENDERINGGROUPS;e<RenderingManager.MAX_RENDERINGGROUPS;e++)this._shadowMap.setRenderingAutoClearDepthStencil(e,!1)}_initializeBlurRTTAndPostProcesses(){let e=this._scene.getEngine(),t=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new renderTargetTexture_RenderTargetTexture(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new BlurPostProcess(this._light.name+"KernelBlurX",new math_vector_Vector2(1,0),this.blurKernel,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=t,this._kernelBlurXPostprocess.height=t,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new BlurPostProcess(this._light.name+"KernelBlurY",new math_vector_Vector2(0,1),this.blurKernel,1,null,texture_Texture.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 postProcess_PostProcess(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,texture_Texture.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,r){let s;if(r.length)for(s=0;s<r.length;s++)this._renderSubMeshForShadowMap(r.data[s]);for(s=0;s<e.length;s++)this._renderSubMeshForShadowMap(e.data[s]);for(s=0;s<t.length;s++)this._renderSubMeshForShadowMap(t.data[s]);if(this._transparencyShadow)for(s=0;s<i.length;s++)this._renderSubMeshForShadowMap(i.data[s],!0);else for(s=0;s<i.length;s++)i.data[s].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}_bindCustomEffectForRenderSubMeshForShadowMap(e,t,i){t.setMatrix("viewProjection",this.getTransformMatrix())}_renderSubMeshForShadowMap(e,t=!1){var i,r;let s=e.getRenderingMesh(),a=e.getEffectiveMesh(),n=this._scene,o=n.getEngine(),l=e.getMaterial();if(a._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!l||0===e.verticesCount||e._renderId===n.getRenderId())return;let h=0>a._getWorldMatrixDeterminant(),c=null!==(i=s.overrideMaterialSideOrientation)&&void 0!==i?i:l.sideOrientation;h&&(c=0===c?1:0);let u=0===c;o.setState(l.backFaceCulling,void 0,void 0,u,l.cullBackFaces);let d=s._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;let _=o.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||s.hasThinInstances);if(!this.customAllowRendering||this.customAllowRendering(e)){if(this.isReady(e,_,t)){e._renderId=n.getRenderId();let i=l.shadowDepthWrapper,h=null!==(r=null==i?void 0:i.getEffect(e,this,o.currentRenderPassId))&&void 0!==r?r:e._getDrawWrapper(),c=drawWrapper_DrawWrapper.GetEffect(h);o.enableEffect(h),_||s._bind(e,c,l.fillMode),this.getTransformMatrix(),c.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?c.setVector3("lightDataSM",this._cachedDirection):c.setVector3("lightDataSM",this._cachedPosition);let u=this._getCamera();if(u&&c.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(u),this.getLight().getDepthMinZ(u)+this.getLight().getDepthMaxZ(u)),t&&this.enableSoftTransparentShadow&&c.setFloat("softTransparentShadowSM",a.visibility*l.alpha),i)e._setMainDrawWrapperOverride(h),i.standalone?i.baseMaterial.bindForSubMesh(a.getWorldMatrix(),s,e):l.bindForSubMesh(a.getWorldMatrix(),s,e),e._setMainDrawWrapperOverride(null);else{if(this._opacityTexture&&(c.setTexture("diffuseSampler",this._opacityTexture),c.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),s.useBones&&s.computeBonesUsingShaders&&s.skeleton){let e=s.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(s);if(!t)return;c.setTexture("boneSampler",t),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",e.getTransformMatrices(s))}MaterialHelper.BindMorphTargetParameters(s,c),s.morphTargetManager&&s.morphTargetManager.isUsingTextureForTargets&&s.morphTargetManager._bind(c),bindClipPlane(c,l,n)}this._useUBO||i||this._bindCustomEffectForRenderSubMeshForShadowMap(e,c,a),MaterialHelper.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();let p=a.getWorldMatrix();_&&(a.getMeshUniformBuffer().bindToEffect(c,"Mesh"),a.transferToEffect(p)),this.forceBackFacesOnly&&o.setState(!0,0,!1,!0,l.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(s),this.onBeforeShadowMapRenderObservable.notifyObservers(c),s._processRendering(a,e,c,l.fillMode,d,_,(e,t)=>{a===s||e?(a.getMeshUniformBuffer().bindToEffect(c,"Mesh"),a.transferToEffect(e?t:p)):(s.getMeshUniformBuffer().bindToEffect(c,"Mesh"),s.transferToEffect(t))}),this.forceBackFacesOnly&&o.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===shadowGenerator_ShadowGenerator.FILTER_NONE||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCSS?this._shadowMap.updateSamplingMode(texture_Texture.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){let i=Object.assign({useInstances:!1},t),r=this.getShadowMap();if(!r){e&&e(this);return}let s=r.renderList;if(!s){e&&e(this);return}let a=[];for(let e of s)a.push(...e.subMeshes);if(0===a.length){e&&e(this);return}let n=0,checkReady=()=>{var t,r;if(this._scene&&this._scene.getEngine()){for(;this.isReady(a[n],i.useInstances,null!==(r=null===(t=a[n].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(a[n].getMesh()))&&void 0!==r&&r);)if(++n>=a.length){e&&e(this);return}setTimeout(checkReady,16)}};checkReady()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));let s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var r;let s=e.getMaterial(),a=null==s?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;let n=[];if(this._prepareShadowDefines(e,t,n,i),a){if(!a.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{let i=e._getDrawWrapper(void 0,!0),a=i.effect,o=i.defines,l=[buffer_VertexBuffer.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)&&(l.push(buffer_VertexBuffer.NormalKind),n.push("#define NORMAL"),h.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));let 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;let e=null!==(r=s.alphaCutOff)&&void 0!==r?r:shadowGenerator_ShadowGenerator.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),c&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(l.push(buffer_VertexBuffer.UVKind),n.push("#define UV1")),h.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(l.push(buffer_VertexBuffer.UV2Kind),n.push("#define UV2"))}let u=new EffectFallbacks;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(buffer_VertexBuffer.MatricesIndicesKind),l.push(buffer_VertexBuffer.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(buffer_VertexBuffer.MatricesIndicesExtraKind),l.push(buffer_VertexBuffer.MatricesWeightsExtraKind));let e=h.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");let d=h.morphTargetManager,_=0;if(d&&d.numInfluencers>0&&(n.push("#define MORPHTARGETS"),_=d.numInfluencers,n.push("#define NUM_MORPH_INFLUENCERS "+_),d.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(l,h,_)),prepareStringDefinesForClipPlanes(s,this._scene,n),t&&(n.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(let e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);let p=n.join("\n");if(o!==p){o=p;let e="shadowMap",t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],r=["diffuseSampler","boneSampler","morphTargets"];if(addClipPlaneUniforms(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(let e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(let e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(let e of this.customShaderOptions.samplers)-1===r.indexOf(e)&&r.push(e)}let s=this._scene.getEngine();a=s.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:["Scene","Mesh"],samplers:r,defines:p,fallbacks:u,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:_}},s),i.setEffect(a,o)}if(!a.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){let i=this._scene,r=this._light;i.shadowsEnabled&&r.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let a=this.getShadowMap();a&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a.getSize().width,1/a.getSize().width,this.frustumEdgeFalloff,e)):this._filter===shadowGenerator_ShadowGenerator.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a.getSize().width,this._contactHardeningLightSizeUVRatio*a.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/a.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e))}getTransformMatrix(){let 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),math_vector_Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(math_vector_Vector3.Dot(this._lightDirection,math_vector_Vector3.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),math_vector_Matrix.LookAtLHToRef(t,t.add(this._lightDirection),math_vector_Vector3.Up(),this._viewMatrix);let e=this.getShadowMap();if(e){let t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){let e=this._shadowMap;if(!e)return;let t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t)for(let e of(this._shadowMap.renderList||(this._shadowMap.renderList=[]),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(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){let e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){let[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;let 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 e=0;e<i.renderList.length;e++){let r=i.renderList[e];t.renderList.push(r.id)}return t}static Parse(e,t,i){let r=t.getLightById(e.lightId),s=void 0!==e.cameraId?t.getCameraById(e.cameraId):null,a=i?i(e.mapSize,r,s):new shadowGenerator_ShadowGenerator(e.mapSize,r,void 0,s),n=a.getShadowMap();for(let i=0;i<e.renderList.length;i++){let r=t.getMeshesById(e.renderList[i]);r.forEach(function(e){n&&(n.renderList||(n.renderList=[]),n.renderList.push(e))})}return void 0!==e.id&&(a.id=e.id),a.forceBackFacesOnly=!!e.forceBackFacesOnly,void 0!==e.darkness&&a.setDarkness(e.darkness),e.transparencyShadow&&a.setTransparencyShadow(!0),void 0!==e.frustumEdgeFalloff&&(a.frustumEdgeFalloff=e.frustumEdgeFalloff),void 0!==e.bias&&(a.bias=e.bias),void 0!==e.normalBias&&(a.normalBias=e.normalBias),e.usePercentageCloserFiltering?a.usePercentageCloserFiltering=!0:e.useContactHardeningShadow?a.useContactHardeningShadow=!0:e.usePoissonSampling?a.usePoissonSampling=!0:e.useExponentialShadowMap?a.useExponentialShadowMap=!0:e.useBlurExponentialShadowMap?a.useBlurExponentialShadowMap=!0:e.useCloseExponentialShadowMap?a.useCloseExponentialShadowMap=!0:e.useBlurCloseExponentialShadowMap?a.useBlurCloseExponentialShadowMap=!0:e.useVarianceShadowMap?a.useExponentialShadowMap=!0:e.useBlurVarianceShadowMap&&(a.useBlurExponentialShadowMap=!0),void 0!==e.contactHardeningLightSizeUVRatio&&(a.contactHardeningLightSizeUVRatio=e.contactHardeningLightSizeUVRatio),void 0!==e.filteringQuality&&(a.filteringQuality=e.filteringQuality),e.depthScale&&(a.depthScale=e.depthScale),e.blurScale&&(a.blurScale=e.blurScale),e.blurBoxOffset&&(a.blurBoxOffset=e.blurBoxOffset),e.useKernelBlur&&(a.useKernelBlur=e.useKernelBlur),e.blurKernel&&(a.blurKernel=e.blurKernel),a}};shadowGenerator_ShadowGenerator.CLASSNAME="ShadowGenerator",shadowGenerator_ShadowGenerator.FILTER_NONE=0,shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP=1,shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING=2,shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP=3,shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP=4,shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP=5,shadowGenerator_ShadowGenerator.FILTER_PCF=6,shadowGenerator_ShadowGenerator.FILTER_PCSS=7,shadowGenerator_ShadowGenerator.QUALITY_HIGH=0,shadowGenerator_ShadowGenerator.QUALITY_MEDIUM=1,shadowGenerator_ShadowGenerator.QUALITY_LOW=2,shadowGenerator_ShadowGenerator.DEFAULT_ALPHA_CUTOFF=.5,shadowGenerator_ShadowGenerator._SceneComponentInitialization=e=>{throw _WarnImport("ShadowGeneratorSceneComponent")};let aV=`#ifdef ALPHATEST +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include<clipPlaneFragmentDeclaration> +varying float vDepthMetric; +#ifdef PACKED +#include<packingFunctions> +#endif +#ifdef STORE_CAMERASPACE_Z +varying vec4 vViewPos; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include<clipPlaneFragment> +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +#ifdef STORE_CAMERASPACE_Z +#ifdef PACKED +gl_FragColor=pack(vViewPos.z); +#else +gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); +#endif +#else +#ifdef NONLINEARDEPTH +#ifdef PACKED +gl_FragColor=pack(gl_FragCoord.z); +#else +gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); +#endif +#else +#ifdef PACKED +gl_FragColor=pack(vDepthMetric); +#else +gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); +#endif +#endif +#endif +}`;ShaderStore.ShadersStore.depthPixelShader=aV;let aU=`attribute vec3 position; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<clipPlaneVertexDeclaration> +#include<instancesDeclaration> +uniform mat4 viewProjection;uniform vec2 depthValues; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#ifdef STORE_CAMERASPACE_Z +uniform mat4 view;varying vec4 vViewPos; +#endif +varying float vDepthMetric; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#include<clipPlaneVertex> +gl_Position=viewProjection*worldPos; +#ifdef STORE_CAMERASPACE_Z +vViewPos=view*worldPos; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); +#else +vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); +#endif +#endif +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +} +`;ShaderStore.ShadersStore.depthVertexShader=aU;let DepthRenderer=class DepthRenderer{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,s=texture_Texture.TRILINEAR_SAMPLINGMODE,a=!1,n){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=a,this.isPacked=0===t,this.isPacked?this.clearColor=new math_color_Color4(1,1,1,1):this.clearColor=new math_color_Color4(a?1e8:1,0,0,1),DepthRenderer._SceneComponentInitialization(this._scene);let o=e.getEngine();this._camera=i,s===texture_Texture.NEAREST_SAMPLINGMODE||(1!==t||o._caps.textureFloatLinearFiltering||(s=texture_Texture.NEAREST_SAMPLINGMODE),2!==t||o._caps.textureHalfFloatLinearFiltering||(s=texture_Texture.NEAREST_SAMPLINGMODE));let l=this.isPacked||!o._features.supportExtendedTextureFormats?5:6;this._depthMap=new renderTargetTexture_RenderTargetTexture(null!=n?n:"DepthRenderer",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,l),this._depthMap.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=texture_Texture.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=o._debugPushGroup)||void 0===e||e.call(o,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var e;null===(e=o._debugPopGroup)||void 0===e||e.call(o,1)}),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){let i=e.subMeshes[t],r=i.getRenderingMesh(),s=r._getInstancesRenderList(i._id,!!i.getReplacementMesh()),a=o.getCaps().instancedArrays&&(null!==s.visibleInstances[i._id]&&void 0!==s.visibleInstances[i._id]||r.hasThinInstances);if(!this.isReady(i,a))return!1}return!0};let renderSubMesh=e=>{var t,i;let r=e.getRenderingMesh(),s=e.getEffectiveMesh(),a=this._scene,n=a.getEngine(),o=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!o||s.infiniteDistance||o.disableDepthWrite||0===e.verticesCount||e._renderId===a.getRenderId())return;let l=0>s._getWorldMatrixDeterminant(),h=null!==(t=r.overrideMaterialSideOrientation)&&void 0!==t?t:o.sideOrientation;l&&(h=0===h?1:0);let c=0===h;n.setState(o.backFaceCulling,0,!1,c,this.reverseCulling?!o.cullBackFaces:o.cullBackFaces);let u=r._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(u.mustReturn)return;let d=n.getCaps().instancedArrays&&(null!==u.visibleInstances[e._id]&&void 0!==u.visibleInstances[e._id]||r.hasThinInstances),_=this._camera||a.activeCamera;if(this.isReady(e,d)&&_){let t,l;e._renderId=a.getRenderId();let h=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[n.currentRenderPassId],c=e._getDrawWrapper();!c&&h&&(c=h._getDrawWrapper());let p=_.mode===camera_Camera.ORTHOGRAPHIC_CAMERA;if(!c)return;let f=c.effect;if(n.enableEffect(c),d||r._bind(e,f,o.fillMode),h?h.bindForSubMesh(s.getWorldMatrix(),s,e):(f.setMatrix("viewProjection",a.getTransformMatrix()),f.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&f.setMatrix("view",a.getViewMatrix())),p?(t=!n.useReverseDepthBuffer&&n.isNDCHalfZRange?0:1,l=n.useReverseDepthBuffer&&n.isNDCHalfZRange?0:1):(t=n.useReverseDepthBuffer&&n.isNDCHalfZRange?_.minZ:n.isNDCHalfZRange?0:_.minZ,l=n.useReverseDepthBuffer&&n.isNDCHalfZRange?0:_.maxZ),f.setFloat2("depthValues",t,t+l),!h){if(o.needAlphaTesting()){let e=o.getAlphaTestTexture();e&&(f.setTexture("diffuseSampler",e),f.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){let e=r.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(r);if(!t)return;f.setTexture("boneSampler",t),f.setFloat("boneTextureWidth",4*(e.bones.length+1))}else f.setMatrices("mBones",e.getTransformMatrices(r))}bindClipPlane(f,o,a),MaterialHelper.BindMorphTargetParameters(r,f),r.morphTargetManager&&r.morphTargetManager.isUsingTextureForTargets&&r.morphTargetManager._bind(f)}r._processRendering(s,e,f,o.fillMode,u,d,(e,t)=>f.setMatrix("world",t))}};this._depthMap.customRenderFunction=(e,t,i,r)=>{let s;if(r.length)for(s=0;s<r.length;s++)renderSubMesh(r.data[s]);for(s=0;s<e.length;s++)renderSubMesh(e.data[s]);for(s=0;s<t.length;s++)renderSubMesh(t.data[s]);if(this.forceDepthWriteTransparentMeshes)for(s=0;s<i.length;s++)renderSubMesh(i.data[s]);else for(s=0;s<i.length;s++)i.data[s].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}}isReady(e,t){var i;let r=this._scene.getEngine(),s=e.getMesh(),a=s.getScene(),n=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[r.currentRenderPassId];if(n)return n.isReadyForSubMesh(s,e,t);let o=e.getMaterial();if(!o||o.disableDepthWrite)return!1;let l=[],h=[buffer_VertexBuffer.PositionKind];if(o&&o.needAlphaTesting()&&o.getAlphaTestTexture()&&(l.push("#define ALPHATEST"),s.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(h.push(buffer_VertexBuffer.UVKind),l.push("#define UV1")),s.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&(h.push(buffer_VertexBuffer.UV2Kind),l.push("#define UV2"))),s.useBones&&s.computeBonesUsingShaders){h.push(buffer_VertexBuffer.MatricesIndicesKind),h.push(buffer_VertexBuffer.MatricesWeightsKind),s.numBoneInfluencers>4&&(h.push(buffer_VertexBuffer.MatricesIndicesExtraKind),h.push(buffer_VertexBuffer.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));let t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");let c=s.morphTargetManager,u=0;c&&c.numInfluencers>0&&(u=c.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+u),c.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(h,s,u)),t&&(l.push("#define INSTANCES"),MaterialHelper.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"),prepareStringDefinesForClipPlanes(o,a,l);let d=e._getDrawWrapper(void 0,!0),_=d.defines,p=l.join("\n");if(_!==p){let e=["world","mBones","boneTextureWidth","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];addClipPlaneUniforms(e),d.setEffect(r.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],p,void 0,void 0,void 0,{maxSimultaneousMorphTargets:u}),p)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){let e=[];for(let t in this._scene._depthRenderer){let i=this._scene._depthRenderer[t];i===this&&e.push(t)}if(e.length>0)for(let t of(this._depthMap.dispose(),e))delete this._scene._depthRenderer[t]}};DepthRenderer._SceneComponentInitialization=e=>{throw _WarnImport("DepthRendererSceneComponent")};let ak=`varying vec2 vUV;uniform sampler2D textureSampler; +#if defined(INITIAL) +uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); +#ifdef DEPTH_REDUX +float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); +#else +float maxz=max(max(max(f1,f2),f3),f4); +#endif +glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(MAIN) +uniform vec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(ONEBEFORELAST) +uniform ivec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(LAST) +void main(void) +{glFragColor=vec4(0.);if (true) { +discard;}} +#endif +`;ShaderStore.ShadersStore.minmaxReduxPixelShader=ak;let MinMaxReducer=class MinMaxReducer{constructor(e){this.onAfterReductionPerformed=new observable_Observable,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new PostProcessManager(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){var s,a,n,o;if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;let l=this._camera.getScene(),h=new postProcess_PostProcess("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,l.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);h.autoClear=!1,h.forceFullscreenViewport=r;let c=this._sourceTexture.getRenderWidth(),u=this._sourceTexture.getRenderHeight();h.onApply=(s=c,a=u,e=>{e.setTexture("sourceTexture",this._sourceTexture),e.setFloat2("texSize",s,a)}),this._reductionSteps.push(h);let d=1;for(;c>1||u>1;){c=Math.max(Math.round(c/2),1),u=Math.max(Math.round(u/2),1);let e=new postProcess_PostProcess("Reduction phase "+d,"minmaxRedux",["texSize"],null,{width:c,height:u},null,1,l.getEngine(),!1,"#define "+(1==c&&1==u?"LAST":1==c||1==u?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=r,e.onApply=(n=c,o=u,e=>{1==n||1==o?e.setInt2("texSize",n,o):e.setFloat2("texSize",n,o)}),this._reductionSteps.push(e),d++,1==c&&1==u){let func=(e,t,i)=>{let r=new Float32Array(4*e*t),s={min:0,max:0};return()=>{l.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,r,!1),s.min=r[0],s.max=r[1],this.onAfterReductionPerformed.notifyObservers(s)}};e.onAfterRenderObservable.add(func(c,u,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;let 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;e<this._reductionSteps.length;++e)this._reductionSteps[e].dispose();this._reductionSteps=null}this._postProcessManager&&e&&this._postProcessManager.dispose(),this._sourceTexture=null}};let DepthReducer=class DepthReducer extends MinMaxReducer{get depthRenderer(){return this._depthRenderer}constructor(e){super(e)}setDepthRenderer(e=null,t=2,i=!0){let r=this._camera.getScene();this._depthRenderer&&(delete r._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),null===e&&(r._depthRenderer||(r._depthRenderer={}),(e=this._depthRenderer=new DepthRenderer(r,t,this._camera,!1,1)).enabled=!1,this._depthRendererId="minmax"+this._camera.id,r._depthRenderer[this._depthRendererId]=e),super.setSourceTexture(e.getDepthMap(),!0,t,i)}setSourceTexture(e,t,i=2,r=!0){super.setSourceTexture(e,t,i,r)}activate(){this._depthRenderer&&(this._depthRenderer.enabled=!0),super.activate()}deactivate(){super.deactivate(),this._depthRenderer&&(this._depthRenderer.enabled=!1)}dispose(e=!0){if(super.dispose(e),this._depthRenderer&&e){let e=this._depthRenderer.getDepthMap().getScene();e&&delete e._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null}}};let aG=math_vector_Vector3.Up(),az=math_vector_Vector3.Zero(),aW=new math_vector_Vector3,aH=new math_vector_Vector3,aX=new math_vector_Matrix;let CascadedShadowGenerator=class CascadedShadowGenerator extends shadowGenerator_ShadowGenerator{_validateFilter(e){return e===shadowGenerator_ShadowGenerator.FILTER_NONE||e===shadowGenerator_ShadowGenerator.FILTER_PCF||e===shadowGenerator_ShadowGenerator.FILTER_PCSS?e:(console.error('Unsupported filter "'+e+'"!'),shadowGenerator_ShadowGenerator.FILTER_NONE)}get numCascades(){return this._numCascades}set numCascades(e){(e=Math.min(Math.max(e,CascadedShadowGenerator.MIN_CASCADES_COUNT),CascadedShadowGenerator.MAX_CASCADES_COUNT))!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())}get freezeShadowCastersBoundingInfo(){return this._freezeShadowCastersBoundingInfo}set freezeShadowCastersBoundingInfo(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._freezeShadowCastersBoundingInfoObservable||e||(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(()=>this._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){let e=this._shadowMap.renderList;for(let t=0;t<e.length;t++){let i=e[t];if(!i)continue;let r=i.getBoundingInfo(),s=r.boundingBox;this._scbiMin.minimizeInPlace(s.minimumWorld),this._scbiMax.maximizeInPlace(s.maximumWorld)}let t=this._scene.meshes;for(let e=0;e<t.length;e++){let i=t[e];if(!i||!i.isVisible||!i.isEnabled||!i.receiveShadows)continue;let r=i.getBoundingInfo(),s=r.boundingBox;this._scbiMin.minimizeInPlace(s.minimumWorld),this._scbiMax.maximizeInPlace(s.maximumWorld)}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)}get shadowCastersBoundingInfo(){return this._shadowCastersBoundingInfo}set shadowCastersBoundingInfo(e){this._shadowCastersBoundingInfo=e}setMinMaxDistance(e,t){(this._minDistance!==e||this._maxDistance!==t)&&(e>t&&(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 CascadedShadowGenerator.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null}getCascadeMaxExtents(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null}get shadowMaxZ(){return this._getCamera()?this._shadowMaxZ:0}set shadowMaxZ(e){let t=this._getCamera();if(!t){this._shadowMaxZ=e;return}this._shadowMaxZ===e||e<t.minZ||e>t.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){let t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null}getCascadeProjectionMatrix(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null}getCascadeTransformMatrix(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null}setDepthRenderer(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)}get autoCalcDepthBounds(){return this._autoCalcDepthBounds}set autoCalcDepthBounds(e){let t=this._getCamera();if(t){if(this._autoCalcDepthBounds=e,!e){this._depthReducer&&this._depthReducer.deactivate(),this.setMinMaxDistance(0,1);return}this._depthReducer||(this._depthReducer=new DepthReducer(t),this._depthReducer.onAfterReductionPerformed.add(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(){let e=this._getCamera();if(!e)return;let t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,a=this._shadowMaxZ<i&&this._shadowMaxZ>=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,n=t+s*r,o=t+a*r,l=o-n,h=o/n;for(let e=0;e<this._cascades.length;++e){let i=(e+1)/this._numCascades,a=n*h**i,o=n+l*i,c=this._lambda*(a-o)+o;this._cascades[e].prevBreakDistance=0===e?s:this._cascades[e-1].breakDistance,this._cascades[e].breakDistance=(c-t)/r,this._viewSpaceFrustumsZ[e]=c,this._frustumLengths[e]=(this._cascades[e].breakDistance-this._cascades[e].prevBreakDistance)*r}this._breaksAreDirty=!1}_computeMatrices(){let e=this._scene,t=this._getCamera();if(!t)return;math_vector_Vector3.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),1===Math.abs(math_vector_Vector3.Dot(this._lightDirection,math_vector_Vector3.Up()))&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);let i=e.getEngine().useReverseDepthBuffer;for(let t=0;t<this._numCascades;++t){this._computeFrustumInWorldSpace(t),this._computeCascadeFrustum(t),this._cascadeMaxExtents[t].subtractToRef(this._cascadeMinExtents[t],aW),this._frustumCenter[t].addToRef(this._lightDirection.scale(this._cascadeMinExtents[t].z),this._shadowCameraPos[t]),math_vector_Matrix.LookAtLHToRef(this._shadowCameraPos[t],this._frustumCenter[t],aG,this._viewMatrices[t]);let r=0,s=aW.z,a=this._shadowCastersBoundingInfo;a.update(this._viewMatrices[t]),s=Math.min(s,a.boundingBox.maximumWorld.z),r=this._depthClamp&&this.filter!==shadowGenerator_ShadowGenerator.FILTER_PCSS?Math.max(r,a.boundingBox.minimumWorld.z):Math.min(r,a.boundingBox.minimumWorld.z),math_vector_Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[t].x,this._cascadeMaxExtents[t].x,this._cascadeMinExtents[t].y,this._cascadeMaxExtents[t].y,i?s:r,i?r:s,this._projectionMatrices[t],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[t].z=r,this._cascadeMaxExtents[t].z=s,this._viewMatrices[t].multiplyToRef(this._projectionMatrices[t],this._transformMatrices[t]),math_vector_Vector3.TransformCoordinatesToRef(az,this._transformMatrices[t],aW),aW.scaleInPlace(this._mapSize/2),aH.copyFromFloats(Math.round(aW.x),Math.round(aW.y),Math.round(aW.z)),aH.subtractInPlace(aW).scaleInPlace(2/this._mapSize),math_vector_Matrix.TranslationToRef(aH.x,aH.y,0,aX),this._projectionMatrices[t].multiplyToRef(aX,this._projectionMatrices[t]),this._viewMatrices[t].multiplyToRef(this._projectionMatrices[t],this._transformMatrices[t]),this._transformMatrices[t].copyToArray(this._transformMatricesAsArray,16*t)}}_computeFrustumInWorldSpace(e){let t=this._getCamera();if(!t)return;let i=this._cascades[e].prevBreakDistance,r=this._cascades[e].breakDistance,s=this._scene.getEngine().isNDCHalfZRange;t.getViewMatrix();let a=0===t.maxZ,n=t.maxZ;a&&(t.maxZ=this._shadowMaxZ,t.getProjectionMatrix(!0));let o=math_vector_Matrix.Invert(t.getTransformationMatrix());a&&(t.maxZ=n,t.getProjectionMatrix(!0));let l=this._scene.getEngine().useReverseDepthBuffer?4:0;for(let t=0;t<CascadedShadowGenerator._FrustumCornersNDCSpace.length;++t)aW.copyFrom(CascadedShadowGenerator._FrustumCornersNDCSpace[(t+l)%CascadedShadowGenerator._FrustumCornersNDCSpace.length]),s&&-1===aW.z&&(aW.z=0),math_vector_Vector3.TransformCoordinatesToRef(aW,o,this._frustumCornersWorldSpace[e][t]);for(let t=0;t<CascadedShadowGenerator._FrustumCornersNDCSpace.length/2;++t)aW.copyFrom(this._frustumCornersWorldSpace[e][t+4]).subtractInPlace(this._frustumCornersWorldSpace[e][t]),aH.copyFrom(aW).scaleInPlace(i),aW.scaleInPlace(r),aW.addInPlace(this._frustumCornersWorldSpace[e][t]),this._frustumCornersWorldSpace[e][t+4].copyFrom(aW),this._frustumCornersWorldSpace[e][t].addInPlace(aH)}_computeCascadeFrustum(e){this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0);let t=this._getCamera();if(t){for(let t=0;t<this._frustumCornersWorldSpace[e].length;++t)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][t]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){let t=0;for(let i=0;i<this._frustumCornersWorldSpace[e].length;++i){let r=this._frustumCornersWorldSpace[e][i].subtractToRef(this._frustumCenter[e],aW).length();t=Math.max(t,r)}t=Math.ceil(16*t)/16,this._cascadeMaxExtents[e].copyFromFloats(t,t,t),this._cascadeMinExtents[e].copyFromFloats(-t,-t,-t)}else{let t=this._frustumCenter[e];this._frustumCenter[e].addToRef(this._lightDirection,aW),math_vector_Matrix.LookAtLHToRef(t,aW,aG,aX);for(let t=0;t<this._frustumCornersWorldSpace[e].length;++t)math_vector_Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][t],aX,aW),this._cascadeMinExtents[e].minimizeInPlace(aW),this._cascadeMaxExtents[e].maximizeInPlace(aW)}}}_recreateSceneUBOs(){if(this._disposeSceneUBOs(),this._sceneUBOs)for(let e=0;e<this._numCascades;++e)this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${e})`))}static get IsSupported(){let e=engineStore_EngineStore.LastCreatedEngine;return!!e&&e._features.supportCSM}constructor(e,t,i,r,s=!0){if(!CascadedShadowGenerator.IsSupported){logger_Logger.Error("CascadedShadowMap is not supported by the current engine.");return}super(e,t,i,r,s),this.usePercentageCloserFiltering=!0}_initializeGenerator(){var e,t,i,r,s,a,n,o,l,h,c,u,d,_,p,f,m,g,v,x;this.penumbraDarkness=null!==(e=this.penumbraDarkness)&&void 0!==e?e:1,this._numCascades=null!==(t=this._numCascades)&&void 0!==t?t:CascadedShadowGenerator.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=null!==(i=this.stabilizeCascades)&&void 0!==i&&i,this._freezeShadowCastersBoundingInfoObservable=null!==(r=this._freezeShadowCastersBoundingInfoObservable)&&void 0!==r?r:null,this.freezeShadowCastersBoundingInfo=null!==(s=this.freezeShadowCastersBoundingInfo)&&void 0!==s&&s,this._scbiMin=null!==(a=this._scbiMin)&&void 0!==a?a:new math_vector_Vector3(0,0,0),this._scbiMax=null!==(n=this._scbiMax)&&void 0!==n?n:new math_vector_Vector3(0,0,0),this._shadowCastersBoundingInfo=null!==(o=this._shadowCastersBoundingInfo)&&void 0!==o?o:new boundingInfo_BoundingInfo(new math_vector_Vector3(0,0,0),new math_vector_Vector3(0,0,0)),this._breaksAreDirty=null===(l=this._breaksAreDirty)||void 0===l||l,this._minDistance=null!==(h=this._minDistance)&&void 0!==h?h:0,this._maxDistance=null!==(c=this._maxDistance)&&void 0!==c?c:1,this._currentLayer=null!==(u=this._currentLayer)&&void 0!==u?u:0,this._shadowMaxZ=null!==(p=null!==(d=this._shadowMaxZ)&&void 0!==d?d:null===(_=this._getCamera())||void 0===_?void 0:_.maxZ)&&void 0!==p?p:1e4,this._debug=null!==(f=this._debug)&&void 0!==f&&f,this._depthClamp=null===(m=this._depthClamp)||void 0===m||m,this._cascadeBlendPercentage=null!==(g=this._cascadeBlendPercentage)&&void 0!==g?g:.1,this._lambda=null!==(v=this._lambda)&&void 0!==v?v:.5,this._autoCalcDepthBounds=null!==(x=this._autoCalcDepthBounds)&&void 0!==x&&x,this._recreateSceneUBOs(),super._initializeGenerator()}_createTargetRenderTexture(){let e=this._scene.getEngine(),t={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new renderTargetTexture_RenderTargetTexture(this._light.name+"_CSMShadowMap",t,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(super._initializeShadowMap(),null===this._shadowMap)return;this._transformMatricesAsArray=new Float32Array(16*this._numCascades),this._viewSpaceFrustumsZ=Array(this._numCascades),this._frustumLengths=Array(this._numCascades),this._lightSizeUVCorrection=Array(2*this._numCascades),this._depthCorrection=Array(this._numCascades),this._cascades=[],this._viewMatrices=[],this._projectionMatrices=[],this._transformMatrices=[],this._cascadeMinExtents=[],this._cascadeMaxExtents=[],this._frustumCenter=[],this._shadowCameraPos=[],this._frustumCornersWorldSpace=[];for(let e=0;e<this._numCascades;++e){this._cascades[e]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[e]=math_vector_Matrix.Zero(),this._projectionMatrices[e]=math_vector_Matrix.Zero(),this._transformMatrices[e]=math_vector_Matrix.Zero(),this._cascadeMinExtents[e]=new math_vector_Vector3,this._cascadeMaxExtents[e]=new math_vector_Vector3,this._frustumCenter[e]=new math_vector_Vector3,this._shadowCameraPos[e]=new math_vector_Vector3,this._frustumCornersWorldSpace[e]=Array(CascadedShadowGenerator._FrustumCornersNDCSpace.length);for(let t=0;t<CascadedShadowGenerator._FrustumCornersNDCSpace.length;++t)this._frustumCornersWorldSpace[e][t]=new math_vector_Vector3}let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.clear(),this._shadowMap.onBeforeRenderObservable.clear(),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===shadowGenerator_ShadowGenerator.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!==shadowGenerator_ShadowGenerator.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);let i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;let s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let a=this.getShadowMap();if(!a)return;let n=a.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===shadowGenerator_ShadowGenerator.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===shadowGenerator_ShadowGenerator.FILTER_PCSS){for(let e=0;e<this._numCascades;++e)this._lightSizeUVCorrection[2*e+0]=0===e?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[e].x-this._cascadeMinExtents[e].x),this._lightSizeUVCorrection[2*e+1]=0===e?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[e].y-this._cascadeMinExtents[e].y),this._depthCorrection[e]=0===e?1:(this._cascadeMaxExtents[e].z-this._cascadeMinExtents[e].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);t.setDepthStencilTexture("shadowSampler"+e,a),t.setTexture("depthSampler"+e,a),t.setArray2("lightSizeUVCorrection"+e,this._lightSizeUVCorrection),t.setArray("depthCorrection"+e,this._depthCorrection),t.setFloat("penumbraDarkness"+e,this.penumbraDarkness),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/n,this._contactHardeningLightSizeUVRatio*n,this.frustumEdgeFalloff,e)}else t.setTexture("shadowSampler"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}getTransformMatrix(){return this.getCascadeTransformMatrix(0)}dispose(){super.dispose(),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)}serialize(){let e=super.serialize(),t=this.getShadowMap();if(!t)return e;if(e.numCascades=this._numCascades,e.debug=this._debug,e.stabilizeCascades=this.stabilizeCascades,e.lambda=this._lambda,e.cascadeBlendPercentage=this.cascadeBlendPercentage,e.depthClamp=this._depthClamp,e.autoCalcDepthBounds=this.autoCalcDepthBounds,e.shadowMaxZ=this._shadowMaxZ,e.penumbraDarkness=this.penumbraDarkness,e.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,e.minDistance=this.minDistance,e.maxDistance=this.maxDistance,e.renderList=[],t.renderList)for(let i=0;i<t.renderList.length;i++){let r=t.renderList[i];e.renderList.push(r.id)}return e}static Parse(e,t){let i=shadowGenerator_ShadowGenerator.Parse(e,t,(e,t,i)=>new CascadedShadowGenerator(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}};CascadedShadowGenerator._FrustumCornersNDCSpace=[new math_vector_Vector3(-1,1,-1),new math_vector_Vector3(1,1,-1),new math_vector_Vector3(1,-1,-1),new math_vector_Vector3(-1,-1,-1),new math_vector_Vector3(-1,1,1),new math_vector_Vector3(1,1,1),new math_vector_Vector3(1,-1,1),new math_vector_Vector3(-1,-1,1)],CascadedShadowGenerator.CLASSNAME="CascadedShadowGenerator",CascadedShadowGenerator.DEFAULT_CASCADES_COUNT=4,CascadedShadowGenerator.MIN_CASCADES_COUNT=2,CascadedShadowGenerator.MAX_CASCADES_COUNT=4,CascadedShadowGenerator._SceneComponentInitialization=e=>{throw _WarnImport("ShadowGeneratorSceneComponent")},AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_SHADOWGENERATOR,(e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,r=e.shadowGenerators.length;i<r;i++){let r=e.shadowGenerators[i];r.className===CascadedShadowGenerator.CLASSNAME?CascadedShadowGenerator.Parse(r,t):shadowGenerator_ShadowGenerator.Parse(r,t)}});let ShadowGeneratorSceneComponent=class ShadowGeneratorSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_SHADOWGENERATOR,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)}rebuild(){}serialize(e){e.shadowGenerators=[];let t=this.scene.lights;for(let i of t){let t=i.getShadowGenerators();if(t){let i=t.values();for(let t=i.next();!0!==t.done;t=i.next()){let i=t.value;e.shadowGenerators.push(i.serialize())}}}}addFromContainer(e){}removeFromContainer(e,t){}dispose(){}_gatherRenderTargets(e){let t=this.scene;if(this.scene.shadowsEnabled)for(let i=0;i<t.lights.length;i++){let r=t.lights[i],s=r.getShadowGenerators();if(r.isEnabled()&&r.shadowEnabled&&s){let i=s.values();for(let r=i.next();!0!==r.done;r=i.next()){let i=r.value,s=i.getShadowMap();-1!==t.textures.indexOf(s)&&e.push(s)}}}}};shadowGenerator_ShadowGenerator._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_SHADOWGENERATOR);t||(t=new ShadowGeneratorSceneComponent(e),e._addComponent(t))},node_Node.AddNodeConstructor("Light_Type_0",(e,t)=>()=>new PointLight(e,math_vector_Vector3.Zero(),t));let PointLight=class PointLight extends ShadowLight{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){let t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){let e=t.value;e.recreateShadowMap()}}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return light_Light.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new math_vector_Vector3(1,0,0);case 1:return new math_vector_Vector3(-1,0,0);case 2:return new math_vector_Vector3(0,-1,0);case 3:return new math_vector_Vector3(0,1,0);case 4:return new math_vector_Vector3(0,0,1);case 5:return new math_vector_Vector3(0,0,-1)}return math_vector_Vector3.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;let s=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,n=this.getScene().getEngine().useReverseDepthBuffer;math_vector_Matrix.PerspectiveFovLHToRef(this.shadowAngle,1,n?a:s,n?s:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,n)}_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}};__decorate([serialize()],PointLight.prototype,"shadowAngle",null);let DefaultLoadingScreen=class DefaultLoadingScreen{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{let 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";let e=`@-webkit-keyframes spin1 {\ + 0% { -webkit-transform: rotate(0deg);} + 100% { -webkit-transform: rotate(360deg);} + }\ + @keyframes spin1 {\ + 0% { transform: rotate(0deg);} + 100% { transform: rotate(360deg);} + }`;this._style.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(this._style);let t=!!window.SVGSVGElement,i=new Image;DefaultLoadingScreen.DefaultLogoUrl?i.src=DefaultLoadingScreen.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";let r=document.createElement("div");r.style.width="300px",r.style.gridColumn="1",r.style.gridRow="1",r.style.top="50%",r.style.left="50%",r.style.transform="translate(-50%, -50%)",r.style.position="absolute";let s=new Image;if(DefaultLoadingScreen.DefaultSpinnerUrl?s.src=DefaultLoadingScreen.DefaultSpinnerUrl:s.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!t){let e={w:16,h:18.5},t={w:30,h:30};i.style.width=`${e.w}vh`,i.style.height=`${e.h}vh`,i.style.left=`calc(50% - ${e.w/2}vh)`,i.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${t.w}vh`,s.style.height=`${t.h}vh`,s.style.left=`calc(50% - ${t.w/2}vh)`,s.style.top=`calc(50% - ${t.h/2}vh)`}r.appendChild(s),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)}))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}};DefaultLoadingScreen.DefaultLogoUrl="",DefaultLoadingScreen.DefaultSpinnerUrl="",engine_Engine.DefaultLoadingScreenFactory=e=>new DefaultLoadingScreen(e);let PanoramaToCubeMapTools=class PanoramaToCubeMapTools{static ConvertPanoramaToCubemap(e,t,i,r,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";let a=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s),n=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s),o=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s),l=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s),h=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s),c=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s);return{front:a,back:n,left:o,right:l,up:h,down:c,size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,a=!1){let n=new ArrayBuffer(e*e*12),o=new Float32Array(n),l=a?Math.max(1,Math.round(r/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),_=1/e,p=0;for(let a=0;a<e;a++)for(let n=0;n<l;n++){let n=t[0],f=t[2];for(let t=0;t<e;t++)for(let h=0;h<l;h++){let l=f.subtract(n).scale(p).add(n);l.normalize();let h=this.CalcProjectionSpherical(l,i,r,s);o[a*e*3+3*t+0]+=h.r*c,o[a*e*3+3*t+1]+=h.g*c,o[a*e*3+3*t+2]+=h.b*c,n=n.add(u),f=f.add(d)}p+=_*h}return o}static CalcProjectionSpherical(e,t,i,r){let s=Math.atan2(e.z,e.x),a=Math.acos(e.y);for(;s<-Math.PI;)s+=2*Math.PI;for(;s>Math.PI;)s-=2*Math.PI;let n=s/Math.PI,o=Math.round((n=.5*n+.5)*i);o<0?o=0:o>=i&&(o=i-1);let l=Math.round(a/Math.PI*r);l<0?l=0:l>=r&&(l=r-1);let h=r-l-1,c=t[h*i*3+3*o+0],u=t[h*i*3+3*o+1],d=t[h*i*3+3*o+2];return{r:c,g:u,b:d}}};PanoramaToCubeMapTools.FACE_LEFT=[new math_vector_Vector3(-1,-1,-1),new math_vector_Vector3(1,-1,-1),new math_vector_Vector3(-1,1,-1),new math_vector_Vector3(1,1,-1)],PanoramaToCubeMapTools.FACE_RIGHT=[new math_vector_Vector3(1,-1,1),new math_vector_Vector3(-1,-1,1),new math_vector_Vector3(1,1,1),new math_vector_Vector3(-1,1,1)],PanoramaToCubeMapTools.FACE_FRONT=[new math_vector_Vector3(1,-1,-1),new math_vector_Vector3(1,-1,1),new math_vector_Vector3(1,1,-1),new math_vector_Vector3(1,1,1)],PanoramaToCubeMapTools.FACE_BACK=[new math_vector_Vector3(-1,-1,1),new math_vector_Vector3(-1,-1,-1),new math_vector_Vector3(-1,1,1),new math_vector_Vector3(-1,1,-1)],PanoramaToCubeMapTools.FACE_DOWN=[new math_vector_Vector3(1,1,-1),new math_vector_Vector3(1,1,1),new math_vector_Vector3(-1,1,-1),new math_vector_Vector3(-1,1,1)],PanoramaToCubeMapTools.FACE_UP=[new math_vector_Vector3(-1,-1,-1),new math_vector_Vector3(-1,-1,1),new math_vector_Vector3(1,-1,-1),new math_vector_Vector3(1,-1,1)];let HDRTools=class HDRTools{static _Ldexp(e,t){return t>1023?898846567431158e293*e*Math.pow(2,t-1023):t<-1074?5e-324*e*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,r,s,a){s>0?(s=this._Ldexp(1,s-136),e[a+0]=t*s,e[a+1]=i*s,e[a+2]=r*s):(e[a+0]=0,e[a+1]=0,e[a+2]=0)}static _ReadStringLine(e,t){let i="",r="";for(let s=t;s<e.length-t&&"\n"!=(r=String.fromCharCode(e[s]));s++)i+=r;return i}static RGBE_ReadHeader(e){let t=0,i=0,r=this._ReadStringLine(e,0);if("#"!=r[0]||"?"!=r[1])throw"Bad HDR Format.";let s=!1,a=!1,n=0;do n+=r.length+1,"FORMAT=32-bit_rle_rgbe"==(r=this._ReadStringLine(e,n))?a=!0:0==r.length&&(s=!0);while(!s);if(!a)throw"HDR Bad header format, unsupported FORMAT";n+=r.length+1,r=this._ReadStringLine(e,n);let o=/^-Y (.*) \+X (.*)$/g.exec(r);if(!o||o.length<3)throw"HDR Bad header format, no size";if(i=parseInt(o[2]),t=parseInt(o[1]),i<8||i>32767)throw"HDR Bad header format, unsupported size";return{height:t,width:i,dataPosition:n+=r.length+1}}static GetCubeMapTextureData(e,t,i=!1){let r=new Uint8Array(e),s=this.RGBE_ReadHeader(r),a=this.RGBE_ReadPixels(r,s),n=PanoramaToCubeMapTools.ConvertPanoramaToCubemap(a,s.width,s.height,t,i);return n}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i,r,s,a,n,o=t.height,l=t.width,h=t.dataPosition,c=0,u=0,d=0,_=new ArrayBuffer(4*l),p=new Uint8Array(_),f=new ArrayBuffer(t.width*t.height*12),m=new Float32Array(f);for(;o>0;){if(i=e[h++],r=e[h++],s=e[h++],a=e[h++],2!=i||2!=r||128&s||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((s<<8|a)!=l)throw"HDR Bad header format, wrong scan line width";for(d=0,c=0;d<4;d++)for(u=(d+1)*l;c<u;)if(i=e[h++],r=e[h++],i>128){if(0==(n=i-128)||n>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;n-- >0;)p[c++]=r}else{if(0==(n=i)||n>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(p[c++]=r,--n>0)for(let t=0;t<n;t++)p[c++]=e[h++]}for(d=0;d<l;d++)i=p[d],r=p[d+l],s=p[d+2*l],a=p[d+3*l],this._Rgbe2float(m,i,r,s,a,(t.height-o)*l*3+3*d);o--}return m}static _RGBEReadPixelsNOTRLE(e,t){let i,r,s,a,n,o=t.height,l=t.width,h=t.dataPosition,c=new ArrayBuffer(t.width*t.height*12),u=new Float32Array(c);for(;o>0;){for(n=0;n<t.width;n++)i=e[h++],r=e[h++],s=e[h++],a=e[h++],this._Rgbe2float(u,i,r,s,a,(t.height-o)*l*3+3*n);o--}return u}};let aY=`attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +mat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.hdrFilteringVertexShader=aY;let aj=`#include<helperFunctions> +#include<importanceSampling> +#include<pbrBRDFFunctions> +#include<hdrFilteringFunctions> +uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`;ShaderStore.ShadersStore.hdrFilteringPixelShader=aj;let HDRFiltering=class HDRFiltering{constructor(e,t={}){this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}_createRenderTarget(e){let t=0;this._engine.getCaps().textureHalfFloatRender?t=2:this._engine.getCaps().textureFloatRender&&(t=1);let i=this._engine.createRenderTargetCubeTexture(e,{format:5,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(i.texture,0,0,0),this._engine.updateTextureSamplingMode(3,i.texture,!0),i}_prefilterInternal(e){let t=e.getSize().width,i=math_scalar_Scalar.ILog2(t)+1,r=this._effectWrapper.effect,s=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();let a=e.getInternalTexture();a&&this._engine.updateTextureSamplingMode(3,a,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let n=[[new math_vector_Vector3(0,0,-1),new math_vector_Vector3(0,-1,0),new math_vector_Vector3(1,0,0)],[new math_vector_Vector3(0,0,1),new math_vector_Vector3(0,-1,0),new math_vector_Vector3(-1,0,0)],[new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,0,1),new math_vector_Vector3(0,1,0)],[new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,0,-1),new math_vector_Vector3(0,-1,0)],[new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,-1,0),new math_vector_Vector3(0,0,1)],[new math_vector_Vector3(-1,0,0),new math_vector_Vector3(0,-1,0),new math_vector_Vector3(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let e=0;e<6;e++){r.setVector3("up",n[e][0]),r.setVector3("right",n[e][1]),r.setVector3("front",n[e][2]);for(let a=0;a<i;a++){this._engine.bindFramebuffer(s,e,void 0,void 0,!0,a),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let i=Math.pow(2,(a-this._lodGenerationOffset)/this._lodGenerationScale)/t;0===a&&(i=0),r.setFloat("alphaG",i),this._effectRenderer.draw()}}this._effectRenderer.restoreStates(),this._engine.restoreDefaultFramebuffer(),this._engine._releaseTexture(e._texture);let o=s.texture.type,l=s.texture.format;return s._swapAndDie(e._texture),e._texture.type=o,e._texture.format=l,e.gammaSpace=!1,e.lodGenerationOffset=this._lodGenerationOffset,e.lodGenerationScale=this._lodGenerationScale,e._prefiltered=!0,e}_createEffect(e,t){let i=[];e.gammaSpace&&i.push("#define GAMMA_INPUT"),i.push("#define NUM_SAMPLES "+this.quality+"u");let r=new EffectWrapper({engine:this._engine,name:"hdrFiltering",vertexShader:"hdrFiltering",fragmentShader:"hdrFiltering",samplerNames:["inputTexture"],uniformNames:["vSampleDirections","vWeights","up","right","front","vFilteringInfo","hdrScale","alphaG"],useShaderStore:!0,defines:i,onCompiled:t});return r}isReady(e){return e.isReady()&&this._effectWrapper.effect.isReady()}prefilter(e,t=null){return this._engine._features.allowTexturePrefiltering?new Promise(i=>{this._effectRenderer=new EffectRenderer(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(logger_Logger.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."))}};let hdrCubeTexture_HDRCubeTexture=class hdrCubeTexture_HDRCubeTexture extends baseTexture_BaseTexture{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(math_vector_Matrix.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,s=!0,a=!1,n=!1,o=null,l=null,h=!1){var c;if(super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=math_vector_Vector3.Zero(),this.onLoadObservable=new observable_Observable,!e)return;this._coordinatesMode=texture_Texture.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=math_vector_Matrix.Identity(),this._prefilterOnLoad=n,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),o&&o()},this._onError=l,this.gammaSpace=a,this._noMipmap=r,this._size=i,this._supersample=h,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?tools_Tools.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):(null===(c=this.getScene())||void 0===c?void 0:c.useDelayedTextureLoading)?this.delayLoadState=4:this._loadTexture()}getClassName(){return"HDRCubeTexture"}_loadTexture(){let e=this._getEngine(),t=e.getCaps(),i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){let t=this._onLoad,i=new HDRFiltering(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;let t=HDRTools.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){let e=CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}let r=[],s=null,a=null;for(let e=0;e<6;e++){2===i?a=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));let o=t[hdrCubeTexture_HDRCubeTexture._FacesMapping[e]];if(this.gammaSpace||a||s){for(let e=0;e<this._size*this._size;e++)if(this.gammaSpace&&(o[3*e+0]=Math.pow(o[3*e+0],n),o[3*e+1]=Math.pow(o[3*e+1],n),o[3*e+2]=Math.pow(o[3*e+2],n)),a&&(a[3*e+0]=ToHalfFloat(o[3*e+0]),a[3*e+1]=ToHalfFloat(o[3*e+1]),a[3*e+2]=ToHalfFloat(o[3*e+2])),s){let t=Math.max(255*o[3*e+0],0),i=Math.max(255*o[3*e+1],0),r=Math.max(255*o[3*e+2],0),a=Math.max(Math.max(t,i),r);if(a>255){let e=255/a;t*=e,i*=e,r*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=r}}a?r.push(a):s?r.push(s):r.push(o)}return r},null,this._onLoad,this._onError)}clone(){let e=new hdrCubeTexture_HDRCubeTexture(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 r=null;return e.name&&!e.isRenderTarget&&((r=new hdrCubeTexture_HDRCubeTexture(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=math_vector_Vector3.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=math_vector_Vector3.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;let 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}};hdrCubeTexture_HDRCubeTexture._FacesMapping=["right","left","up","down","front","back"],h["BABYLON.HDRCubeTexture"]=hdrCubeTexture_HDRCubeTexture;let MorphTarget=class MorphTarget{get influence(){return this._influence}set influence(e){if(this._influence===e)return;let t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new observable_Observable,this._onDataLayoutChanged=new observable_Observable,this._animationPropertiesOverride=null,this._scene=i||engineStore_EngineStore.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){let t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){let t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){let t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){let t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){let e=decorators_SerializationHelper.Clone(()=>new MorphTarget(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(){let 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())),decorators_SerializationHelper.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){let i=new MorphTarget(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t<e.animations.length;t++){let r=e.animations[t],s=h["BABYLON.Animation"];s&&i.animations.push(s.Parse(r))}e.autoAnimate&&t&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1)}return i}static FromMesh(e,t,i){t||(t=e.name);let r=new MorphTarget(t,i,e.getScene());return r.setPositions(e.getVerticesData(buffer_VertexBuffer.PositionKind)),e.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)&&r.setNormals(e.getVerticesData(buffer_VertexBuffer.NormalKind)),e.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)&&r.setTangents(e.getVerticesData(buffer_VertexBuffer.TangentKind)),e.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&r.setUVs(e.getVerticesData(buffer_VertexBuffer.UVKind)),r}};__decorate([serialize()],MorphTarget.prototype,"id",void 0);let RawTexture2DArray=class RawTexture2DArray extends texture_Texture{get depth(){return this._depth}constructor(e,t,i,r,s,a,n=!0,o=!1,l=texture_Texture.TRILINEAR_SAMPLINGMODE,h=0,c){super(null,a,!n,o),this.format=s,this._texture=a.getEngine().createRawTexture2DArray(e,t,i,r,s,n,o,l,null,h,c),this._depth=r,this.is2DArray=!0}update(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}static CreateRGBATexture(e,t,i,r,s,a=!0,n=!1,o=3,l=0){return new RawTexture2DArray(e,t,i,r,5,s,a,n,o,l)}};let morphTargetManager_MorphTargetManager=class morphTargetManager_MorphTargetManager{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null){if(this._targets=[],this._targetInfluenceChangedObservers=[],this._targetDataLayoutChangedObservers=[],this._activeTargets=new SmartArray(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=[],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=engineStore_EngineStore.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();let 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 morphTargetManager_MorphTargetManager.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){let 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(){let e=new morphTargetManager_MorphTargetManager(this._scene);for(let t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){let e={};for(let t of(e.id=this.uniqueId,e.targets=[],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(let e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=morphTargetManager_MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;let r=e.getPositions();if(r){let e=r.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e){logger_Logger.Error("Incompatible target. Targets must all have the same vertices count.");return}}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e<t;e++)this._influences[e]=this._tempInfluences[e];e&&this.synchronize()}synchronize(){if(this._scene&&!this.areUpdatesFrozen){if(this.isUsingTextureForTargets&&this._vertexCount){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride,this._textureHeight=1;let e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){let 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();let e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4),i=0;for(let r=0;r<e;r++){let e=this._targets[r],s=e.getPositions(),a=e.getNormals(),n=e.getUVs(),o=e.getTangents();if(!s){0===r&&logger_Logger.Error("Invalid morph target. Target must have positions.");return}i=r*this._textureWidth*this._textureHeight*4;for(let e=0;e<this._vertexCount;e++)t[i]=s[3*e],t[i+1]=s[3*e+1],t[i+2]=s[3*e+2],i+=4,this._supportsNormals&&a&&(t[i]=a[3*e],t[i+1]=a[3*e+1],t[i+2]=a[3*e+2],i+=4),this._supportsUVs&&n&&(t[i]=n[2*e],t[i+1]=n[2*e+1],i+=4),this._supportsTangents&&o&&(t[i]=o[3*e],t[i+1]=o[3*e+1],t[i+2]=o[3*e+2],i+=4)}this._targetStoreTexture=RawTexture2DArray.CreateRGBATexture(t,this._textureWidth,this._textureHeight,e,this._scene,!1,!1,1,1)}}for(let e of this._scene.meshes)e.morphTargetManager===this&&e._syncGeometryWithMorphTargetManager()}}dispose(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this._scene){if(this._scene.removeMorphTargetManager(this),this._parentContainer){let e=this._parentContainer.morphTargetManagers.indexOf(this);e>-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(let e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){let i=new morphTargetManager_MorphTargetManager(t);for(let r of(i._uniqueId=e.id,e.targets))i.addTarget(MorphTarget.Parse(r,t));return i}};morphTargetManager_MorphTargetManager.EnableTextureStorage=!0,morphTargetManager_MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode=8;let PhysicsRaycastResult=class PhysicsRaycastResult{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=math_vector_Vector3.Zero(),this._hitPointWorld=math_vector_Vector3.Zero(),this._rayFromWorld=math_vector_Vector3.Zero(),this._rayToWorld=math_vector_Vector3.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=math_vector_Vector3.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=math_vector_Vector3.Zero(),t=math_vector_Vector3.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,this.body=void 0,this.bodyIndex=void 0}};let PhysicsEngine=class PhysicsEngine{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw _WarnImport("CannonJSPlugin")}constructor(e,t=PhysicsEngine.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new math_vector_Vector3(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){let t=this._impostors.indexOf(e);if(t>-1){let i=this._impostors.splice(t,1);i.length&&this.getPhysicsPlugin().removePhysicsBody(e)}}addJoint(e,t,i){let r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){let r=this._joints.filter(function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e});r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach(e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t<this._impostors.length;++t)if(this._impostors[t].object===e)return this._impostors[t];return null}getImpostorWithPhysicsBody(e){for(let t=0;t<this._impostors.length;++t)if(this._impostors[t].physicsBody===e)return this._impostors[t];return null}raycast(e,t){return this._physicsPlugin.raycast(e,t)}raycastToRef(e,t,i){return this._physicsPlugin.raycastToRef(e,t,i)}};let CannonJSPlugin=class CannonJSPlugin{constructor(e=!0,t=10,i=CANNON){if(this._useDeltaForWorldStep=e,this.name="CannonJSPlugin",this._physicsMaterials=[],this._fixedTimeStep=1/60,this._physicsBodiesToRemoveAfterStep=[],this._firstFrame=!0,this._tmpQuaternion=new math_vector_Quaternion,this._minus90X=new math_vector_Quaternion(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new math_vector_Quaternion(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=math_vector_Vector3.Zero(),this._tmpDeltaPosition=math_vector_Vector3.Zero(),this._tmpUnityRotation=new math_vector_Quaternion,this.BJSCANNON=i,!this.isSupported()){logger_Logger.Error("CannonJS is not available. Please make sure you included the js file.");return}this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=t,this._cannonRaycastResult=new this.BJSCANNON.RaycastResult,this._raycastResult=new PhysicsRaycastResult}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this._fixedTimeStep=e}getTimeStep(){return this._fixedTimeStep}executeStep(e,t){if(this._firstFrame)for(let e of(this._firstFrame=!1,t))e.type==physicsImpostor_PhysicsImpostor.HeightmapImpostor||e.type===physicsImpostor_PhysicsImpostor.PlaneImpostor||e.beforeStep();this.world.step(this._useDeltaForWorldStep?e:this._fixedTimeStep),this._removeMarkedPhysicsBodiesFromWorld()}_removeMarkedPhysicsBodiesFromWorld(){this._physicsBodiesToRemoveAfterStep.length>0&&(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){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,r)}applyForce(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){let t=this._createShape(e);if(!t){logger_Logger.Warn("It was not possible to create a physics body for this object.");return}let i=e.physicsBody;i&&this.removePhysicsBody(e);let r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:r},a=e.getParam("nativeOptions");for(let e in a)Object.prototype.hasOwnProperty.call(a,e)&&(s[e]=a[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){let r=i[t];e.physicsBody[t].set(r.x,r.y,r.z)}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}_processChildMeshes(e){let 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){let processMesh=t=>{if(!t.rotationQuaternion)return;let i=t.getPhysicsImpostor();if(i){let r=i.parent;if(r!==e&&t.parent){let r=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);i.physicsBody&&(this.removePhysicsBody(i),i.physicsBody=null),i.parent=e,i.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(i),new this.BJSCANNON.Vec3(r.x,r.y,r.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=i.getParam("mass")}}t.getChildMeshes(!0).filter(e=>!!e.physicsImpostor).forEach(processMesh)};t.filter(e=>!!e.physicsImpostor).forEach(processMesh)}}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){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,a={pivotA:s.mainPivot?new this.BJSCANNON.Vec3().set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?new this.BJSCANNON.Vec3().set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?new this.BJSCANNON.Vec3().set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?new this.BJSCANNON.Vec3().set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case PhysicsJoint.HingeJoint:case PhysicsJoint.Hinge2Joint:t=new this.BJSCANNON.HingeConstraint(i,r,a);break;case PhysicsJoint.DistanceJoint:t=new this.BJSCANNON.DistanceConstraint(i,r,s.maxDistance||2);break;case PhysicsJoint.SpringJoint:t=new this.BJSCANNON.Spring(i,r,{restLength:s.length,stiffness:s.stiffness,damping:s.damping,localAnchorA:a.pivotA,localAnchorB:a.pivotB});break;case PhysicsJoint.LockJoint:t=new this.BJSCANNON.LockConstraint(i,r,a);break;case PhysicsJoint.PointToPointJoint:case PhysicsJoint.BallAndSocketJoint:default:t=new this.BJSCANNON.PointToPointConstraint(i,a.pivotA,r,a.pivotB,a.maxForce)}t.collideConnected=!!s.collision,e.joint.physicsJoint=t,e.joint.type!==PhysicsJoint.SpringJoint?this.world.addConstraint(t):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){t.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==PhysicsJoint.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,s;for(r=0;r<this._physicsMaterials.length;r++)if((s=this._physicsMaterials[r]).friction===t&&s.restitution===i)return s;let a=new this.BJSCANNON.Material(e);return a.friction=t,a.restitution=i,this._physicsMaterials.push(a),a}_checkWithEpsilon(e){return e<.001?.001:e}_createShape(e){let t;let i=e.object,r=e.getObjectExtents();switch(e.type){case physicsImpostor_PhysicsImpostor.SphereImpostor:{let e=r.x,i=r.y,s=r.z;t=new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(e),this._checkWithEpsilon(i),this._checkWithEpsilon(s))/2);break}case physicsImpostor_PhysicsImpostor.CylinderImpostor:{let i=e.getParam("nativeOptions");i||(i={});let s=void 0!==i.radiusTop?i.radiusTop:this._checkWithEpsilon(r.x)/2,a=void 0!==i.radiusBottom?i.radiusBottom:this._checkWithEpsilon(r.x)/2,n=void 0!==i.height?i.height:this._checkWithEpsilon(r.y),o=void 0!==i.numSegments?i.numSegments:16;t=new this.BJSCANNON.Cylinder(s,a,n,o);let l=new this.BJSCANNON.Quaternion;l.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0),-Math.PI/2);let h=new this.BJSCANNON.Vec3(0,0,0);t.transformAllPoints(h,l);break}case physicsImpostor_PhysicsImpostor.BoxImpostor:{let e=r.scale(.5);t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(e.x),this._checkWithEpsilon(e.y),this._checkWithEpsilon(e.z)));break}case physicsImpostor_PhysicsImpostor.PlaneImpostor:logger_Logger.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),t=new this.BJSCANNON.Plane;break;case physicsImpostor_PhysicsImpostor.MeshImpostor:{let r;let s=i.getVerticesData?i.getVerticesData(buffer_VertexBuffer.PositionKind):[],a=i.getIndices?i.getIndices():[];if(!s){logger_Logger.Warn("Tried to create a MeshImpostor for an object without vertices. This will fail.");return}let n=i.position.clone(),o=i.rotation&&i.rotation.clone(),l=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace();let h=i.computeWorldMatrix(!0),c=[];for(r=0;r<s.length;r+=3)math_vector_Vector3.TransformCoordinates(math_vector_Vector3.FromArray(s,r),h).toArray(c,r);logger_Logger.Warn("MeshImpostor only collides against spheres."),t=new this.BJSCANNON.Trimesh(c,a),i.position.copyFrom(n),o&&i.rotation&&i.rotation.copyFrom(o),l&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(l);break}case physicsImpostor_PhysicsImpostor.HeightmapImpostor:{let r=i.position.clone(),s=i.rotation&&i.rotation.clone(),a=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace(),i.rotationQuaternion&&i.rotationQuaternion.multiplyInPlace(this._minus90X),t=this._createHeightmap(i),i.position.copyFrom(r),s&&i.rotation&&i.rotation.copyFrom(s),a&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(a),i.computeWorldMatrix(!0);break}case physicsImpostor_PhysicsImpostor.ParticleImpostor:t=new this.BJSCANNON.Particle;break;case physicsImpostor_PhysicsImpostor.NoImpostor:t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0))}return t}_createHeightmap(e,t){let i,r=e.getVerticesData(buffer_VertexBuffer.PositionKind),s=e.computeWorldMatrix(!0),a=[];for(i=0;i<r.length;i+=3)math_vector_Vector3.TransformCoordinates(math_vector_Vector3.FromArray(r,i),s).toArray(a,i);r=a;let n=[],o=t||~~(Math.sqrt(r.length/3)-1),l=e.getBoundingInfo(),h=Math.min(l.boundingBox.extendSizeWorld.x,l.boundingBox.extendSizeWorld.y),c=l.boundingBox.extendSizeWorld.z,u=2*h/o;for(let e=0;e<r.length;e+=3){let t=Math.round(r[e+0]/u+o/2),i=Math.round(-((r[e+1]/u-o/2)*1)),s=-r[e+2]+c;n[t]||(n[t]=[]),n[t][i]||(n[t][i]=s),n[t][i]=Math.max(s,n[t][i])}for(let e=0;e<=o;++e){if(!n[e]){let t=1;for(;!n[(e+t)%o];)t++;n[e]=n[(e+t)%o].slice()}for(let t=0;t<=o;++t)if(!n[e][t]){let i,r=1;for(;void 0===i;)i=n[e][(t+r++)%o];n[e][t]=i}}let d=new this.BJSCANNON.Heightfield(n,{elementSize:u});return d.minY=c,d}_updatePhysicsBodyTransformation(e){let t=e.object;if(t.computeWorldMatrix&&t.computeWorldMatrix(!0),!t.getBoundingInfo())return;let i=e.getObjectCenter();this._tmpDeltaPosition.copyFrom(t.getAbsolutePivotPoint().subtract(i)),this._tmpDeltaPosition.divideInPlace(e.object.scaling),this._tmpPosition.copyFrom(i);let r=t.rotationQuaternion;if(r){if((e.type===physicsImpostor_PhysicsImpostor.PlaneImpostor||e.type===physicsImpostor_PhysicsImpostor.HeightmapImpostor)&&(r=r.multiply(this._minus90X),e.setDeltaRotation(this._plus90X)),e.type===physicsImpostor_PhysicsImpostor.HeightmapImpostor){let e=t.getBoundingInfo(),r=t.rotationQuaternion;t.rotationQuaternion=this._tmpUnityRotation,t.computeWorldMatrix(!0);let s=i.clone(),a=t.getPivotMatrix();a=a?a.clone():math_vector_Matrix.Identity();let n=math_vector_Matrix.Translation(e.boundingBox.extendSizeWorld.x,0,-e.boundingBox.extendSizeWorld.z);t.setPreTransformMatrix(n),t.computeWorldMatrix(!0),e=t.getBoundingInfo();let o=e.boundingBox.centerWorld.subtract(i).subtract(t.position).negate();this._tmpPosition.copyFromFloats(o.x,o.y-e.boundingBox.extendSizeWorld.y,o.z),this._tmpDeltaPosition.copyFrom(e.boundingBox.centerWorld.subtract(s)),this._tmpDeltaPosition.y+=e.boundingBox.extendSizeWorld.y,t.rotationQuaternion=r,t.setPreTransformMatrix(a),t.computeWorldMatrix(!0)}else e.type===physicsImpostor_PhysicsImpostor.MeshImpostor&&this._tmpDeltaPosition.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpDeltaPosition),e.physicsBody.position.set(this._tmpPosition.x,this._tmpPosition.y,this._tmpPosition.z),e.physicsBody.quaternion.set(r.x,r.y,r.z,r.w)}}setTransformationFromPhysicsBody(e){if(e.object.position.set(e.physicsBody.position.x,e.physicsBody.position.y,e.physicsBody.position.z),e.object.rotationQuaternion){let t=e.physicsBody.quaternion;e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}setPhysicsBodyTransformation(e,t,i){e.physicsBody.position.set(t.x,t.y,t.z),e.physicsBody.quaternion.set(i.x,i.y,i.z,i.w)}isSupported(){return void 0!==this.BJSCANNON}setLinearVelocity(e,t){e.physicsBody.velocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){let t=e.physicsBody.velocity;return t?new math_vector_Vector3(t.x,t.y,t.z):null}getAngularVelocity(e){let t=e.physicsBody.angularVelocity;return t?new math_vector_Vector3(t.x,t.y,t.z):null}setBodyMass(e,t){e.physicsBody.mass=t,e.physicsBody.updateMassProperties()}getBodyMass(e){return e.physicsBody.mass}getBodyFriction(e){return e.physicsBody.material.friction}setBodyFriction(e,t){e.physicsBody.material.friction=t}getBodyRestitution(e){return e.physicsBody.material.restitution}setBodyRestitution(e,t){e.physicsBody.material.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.wakeUp()}updateDistanceJoint(e,t){e.physicsJoint.distance=t}setMotor(e,t,i,r){!r&&(e.physicsJoint.enableMotor(),e.physicsJoint.setMotorSpeed(t),i&&this.setLimit(e,i))}setLimit(e,t,i){e.physicsJoint.motorEquation.maxForce=i,e.physicsJoint.motorEquation.minForce=void 0===t?-t:t}syncMeshWithImpostor(e,t){let 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.quaternion.x,e.rotationQuaternion.y=i.quaternion.y,e.rotationQuaternion.z=i.quaternion.z,e.rotationQuaternion.w=i.quaternion.w)}getRadius(e){let t=e.physicsBody.shapes[0];return t.boundingSphereRadius}getBoxSizeToRef(e,t){let i=e.physicsBody.shapes[0];t.x=2*i.halfExtents.x,t.y=2*i.halfExtents.y,t.z=2*i.halfExtents.z}dispose(){}_extendNamespace(){let e=new this.BJSCANNON.Vec3,t=this.BJSCANNON;this.BJSCANNON.World.prototype.step=function(i,r,s){if(s=s||10,0===(r=r||0))this.internalStep(i),this.time+=i;else{let a=Math.floor((this.time+r)/i)-Math.floor(this.time/i);a=Math.min(a,s)||1;let n=performance.now();for(let e=0;e!==a&&(this.internalStep(i),!(performance.now()-n>1e3*i));e++);this.time+=r;let o=this.time%i,l=o/i,h=this.bodies;for(let i=0;i!==h.length;i++){let r=h[i];r.type!==t.Body.STATIC&&r.sleepState!==t.Body.SLEEPING?(r.position.vsub(r.previousPosition,e),e.scale(l,e),r.position.vadd(e,r.interpolatedPosition)):(r.interpolatedPosition.set(r.position.x,r.position.y,r.position.z),r.interpolatedQuaternion.set(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.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))}};PhysicsEngine.DefaultPluginFactory=()=>new CannonJSPlugin;let OimoJSPlugin=class OimoJSPlugin{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=math_vector_Vector3.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new PhysicsRaycastResult}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}let e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];if(!e||!t){i=i.next;continue}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}}applyImpulse(e,t,i){let r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){logger_Logger.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){var t;let i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},r=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach(function(e){e.physicsImpostor&&r.push(e.physicsImpostor)});let checkWithEpsilon=e=>Math.max(e,.001),s=new math_vector_Quaternion;r.forEach(t=>{if(!t.object.rotationQuaternion)return;let r=t.object.rotationQuaternion;s.copyFrom(r),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);let a=s.toEulerAngles(),n=t.getObjectExtents();if(t===e){let t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{let e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(57.29577951308232*a.x,57.29577951308232*a.y,57.29577951308232*a.z)}switch(t.object.rotationQuaternion.copyFrom(s),t.type){case physicsImpostor_PhysicsImpostor.ParticleImpostor:logger_Logger.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case physicsImpostor_PhysicsImpostor.SphereImpostor:{let e=n.x,t=n.y,r=n.z,s=Math.max(checkWithEpsilon(e),checkWithEpsilon(t),checkWithEpsilon(r))/2;i.type.push("sphere"),i.size.push(s),i.size.push(s),i.size.push(s);break}case physicsImpostor_PhysicsImpostor.CylinderImpostor:{let e=checkWithEpsilon(n.x)/2,t=checkWithEpsilon(n.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case physicsImpostor_PhysicsImpostor.PlaneImpostor:case physicsImpostor_PhysicsImpostor.BoxImpostor:default:{let e=checkWithEpsilon(n.x),t=checkWithEpsilon(n.y),r=checkWithEpsilon(n.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(r)}}t.object.rotationQuaternion=r}),e.physicsBody=this.world.add(i),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){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,a=s.nativeParams||{},n={body1:i,body2:r,axe1:a.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:a.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:a.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:a.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:a.min,max:a.max,collision:a.collision||s.collision,spring:a.spring,world:this.world};switch(e.joint.type){case PhysicsJoint.BallAndSocketJoint:t="jointBall";break;case PhysicsJoint.SpringJoint:logger_Logger.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead"),n.min=s.length||n.min,n.max=Math.max(n.min,n.max);case PhysicsJoint.DistanceJoint:t="jointDistance",n.max=s.maxDistance;break;case PhysicsJoint.PrismaticJoint:t="jointPrisme";break;case PhysicsJoint.SliderJoint:t="jointSlide";break;case PhysicsJoint.WheelJoint:t="jointWheel";break;case PhysicsJoint.HingeJoint:default:t="jointHinge"}n.type=t,e.joint.physicsJoint=this.world.add(n)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){logger_Logger.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{let t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){let t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){let t=e.physicsBody.linearVelocity;return t?new math_vector_Vector3(t.x,t.y,t.z):null}getAngularVelocity(e){let t=e.physicsBody.angularVelocity;return t?new math_vector_Vector3(t.x,t.y,t.z):null}setBodyMass(e,t){let i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){void 0!==i?logger_Logger.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,r){let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){let 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){let 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 logger_Logger.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){logger_Logger.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}};let AmmoJSPlugin=class AmmoJSPlugin{constructor(e=!0,t=Ammo,i=null){if(this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new math_vector_Quaternion,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new math_vector_Vector3,this._tmpContactNormal=new math_vector_Vector3,this._tmpVec3=new math_vector_Vector3,this._tmpMatrix=new math_vector_Matrix,"function"==typeof t){logger_Logger.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}if(this.bjsAMMO=t,!this.isSupported()){logger_Logger.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint);let t=e.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 PhysicsRaycastResult,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i<i?(this.world.stepSimulation(e,0),e=0):(e-=i,this.world.stepSimulation(i,0)),t--}executeStep(e,t){for(let e of t)e.soft||e.beforeStep();for(let i of(this._stepSimulation(this._useDeltaForWorldStep?e:this._timeStep,this._maxSteps,this._fixedTimeStep),t))if(i.soft?this._afterSoftStep(i):i.afterStep(),i._onPhysicsCollideCallbacks.length>0&&this._isImpostorInContact(i))for(let e of i._onPhysicsCollideCallbacks)for(let 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===physicsImpostor_PhysicsImpostor.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){let t,i,r,s;let a=e.physicsBody.get_m_nodes(),n=a.size(),o=[];for(let e=0;e<n;e++)i=(t=a.at(e).get_m_x()).x(),r=t.y(),s=t.z(),o.push(new math_vector_Vector3(i,r,s));let l=e.object,h=e.getParam("shape");e._isFromLine?e.object=linesBuilder_CreateLines("lines",{points:o,instance:l}):e.object=ExtrudeShape("ext",{shape:h,path:o,instance:l})}_softbodyOrClothStep(e){let t,i,r,s,a,n,o,l;let h=e.type===physicsImpostor_PhysicsImpostor.ClothImpostor?1:-1,c=e.object,u=c.getVerticesData(buffer_VertexBuffer.PositionKind);u||(u=[]);let d=c.getVerticesData(buffer_VertexBuffer.NormalKind);d||(d=[]);let _=u.length/3,p=e.physicsBody.get_m_nodes();for(let e=0;e<_;e++){r=(i=(t=p.at(e)).get_m_x()).x(),s=i.y(),a=i.z()*h;let c=t.get_m_n();n=c.x(),o=c.y(),l=c.z()*h,u[3*e]=r,u[3*e+1]=s,u[3*e+2]=a,d[3*e]=n,d[3*e+1]=o,d[3*e+2]=l}let f=new mesh_vertexData_VertexData;f.positions=u,f.normals=d,f.uvs=c.getVerticesData(buffer_VertexBuffer.UVKind),f.colors=c.getVerticesData(buffer_VertexBuffer.ColorKind),c&&c.getIndices&&(f.indices=c.getIndices()),f.applyToMesh(c)}applyImpulse(e,t,i){if(e.soft)logger_Logger.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();let r=this._tmpAmmoVectorA,s=this._tmpAmmoVectorB;e.object&&e.object.getWorldMatrix&&i.subtractInPlace(e.object.getWorldMatrix().getTranslation()),r.setValue(i.x,i.y,i.z),s.setValue(t.x,t.y,t.z),e.physicsBody.applyImpulse(s,r)}}applyForce(e,t,i){if(e.soft)logger_Logger.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();let r=this._tmpAmmoVectorA,s=this._tmpAmmoVectorB;if(e.object&&e.object.getWorldMatrix){let t=e.object.getWorldMatrix().getTranslation();r.setValue(i.x-t.x,i.y-t.y,i.z-t.z)}else r.setValue(i.x,i.y,i.z);s.setValue(t.x,t.y,t.z),e.physicsBody.applyForce(s,r)}}generatePhysicsBody(e){if(e._pluginData.toDispose=[],e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){let t=this._createShape(e),i=e.getParam("mass");if(e._pluginData.mass=i,e.soft)t.get_m_cfg().set_collisions(17),t.get_m_cfg().set_kDP(e.getParam("damping")),this.bjsAMMO.castObject(t,this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(e.getParam("margin")),t.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG),this.world.addSoftBody(t,1,-1),e.physicsBody=t,e._pluginData.toDispose.push(t),this.setBodyPressure(e,0),e.type===physicsImpostor_PhysicsImpostor.SoftbodyImpostor&&this.setBodyPressure(e,e.getParam("pressure")),this.setBodyStiffness(e,e.getParam("stiffness")),this.setBodyVelocityIterations(e,e.getParam("velocityIterations")),this.setBodyPositionIterations(e,e.getParam("positionIterations"));else{let r=new this.bjsAMMO.btVector3(0,0,0),s=new this.bjsAMMO.btTransform;e.object.computeWorldMatrix(!0),s.setIdentity(),0!==i&&t.calculateLocalInertia(i,r),this._tmpAmmoVectorA.setValue(e.object.position.x,e.object.position.y,e.object.position.z),this._tmpAmmoQuaternion.setValue(e.object.rotationQuaternion.x,e.object.rotationQuaternion.y,e.object.rotationQuaternion.z,e.object.rotationQuaternion.w),s.setOrigin(this._tmpAmmoVectorA),s.setRotation(this._tmpAmmoQuaternion);let a=new this.bjsAMMO.btDefaultMotionState(s),n=new this.bjsAMMO.btRigidBodyConstructionInfo(i,a,t,r),o=new this.bjsAMMO.btRigidBody(n);if(0===i&&(o.setCollisionFlags(o.getCollisionFlags()|AmmoJSPlugin._KINEMATIC_FLAG),o.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG)),e.type!=physicsImpostor_PhysicsImpostor.NoImpostor||t.getChildShape||o.setCollisionFlags(o.getCollisionFlags()|AmmoJSPlugin._DISABLE_COLLISION_FLAG),e.type!==physicsImpostor_PhysicsImpostor.MeshImpostor&&e.type!==physicsImpostor_PhysicsImpostor.NoImpostor){let t=e.object.getBoundingInfo();this._tmpVec3.copyFrom(e.object.getAbsolutePosition()),this._tmpVec3.subtractInPlace(t.boundingBox.centerWorld),this._tmpVec3.x/=e.object.scaling.x,this._tmpVec3.y/=e.object.scaling.y,this._tmpVec3.z/=e.object.scaling.z,e.setDeltaPosition(this._tmpVec3)}let l=e.getParam("group"),h=e.getParam("mask");l&&h?this.world.addRigidBody(o,l,h):this.world.addRigidBody(o),e.physicsBody=o,e._pluginData.toDispose=e._pluginData.toDispose.concat([o,n,a,s,r,t])}this.setBodyRestitution(e,e.getParam("restitution")),this.setBodyFriction(e,e.getParam("friction"))}}removePhysicsBody(e){this.world&&(e.soft?this.world.removeSoftBody(e.physicsBody):this.world.removeRigidBody(e.physicsBody),e._pluginData&&(e._pluginData.toDispose.forEach(e=>{this.bjsAMMO.destroy(e)}),e._pluginData.toDispose=[]))}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData;switch(s.mainPivot||(s.mainPivot=new math_vector_Vector3(0,0,0)),s.connectedPivot||(s.connectedPivot=new math_vector_Vector3(0,0,0)),e.joint.type){case PhysicsJoint.DistanceJoint:{let e=s.maxDistance;e&&(s.mainPivot=new math_vector_Vector3(0,-e/2,0),s.connectedPivot=new math_vector_Vector3(0,e/2,0)),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case PhysicsJoint.HingeJoint:{s.mainAxis||(s.mainAxis=new math_vector_Vector3(0,0,0)),s.connectedAxis||(s.connectedAxis=new math_vector_Vector3(0,0,0));let e=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),a=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);t=new this.bjsAMMO.btHingeConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),e,a);break}case PhysicsJoint.BallAndSocketJoint:t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:logger_Logger.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z))}this.world.addConstraint(t,!e.joint.jointData.collision),e.joint.physicsJoint=t}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s,a=i.getIndices();a||(a=[]);let n=i.getVerticesData(buffer_VertexBuffer.PositionKind);if(n||(n=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?math_vector_Quaternion.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):math_vector_Quaternion.Identity();let r=math_vector_Matrix.Compose(math_vector_Vector3.One(),e,t.position);r.invertToRef(this._tmpMatrix);let a=i.computeWorldMatrix(!1);s=a.multiply(this._tmpMatrix)}else math_vector_Matrix.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),s=this._tmpMatrix;let o=a.length/3;for(let t=0;t<o;t++){let i=[];for(let e=0;e<3;e++){let r,o=new math_vector_Vector3(n[3*a[3*t+e]+0],n[3*a[3*t+e]+1],n[3*a[3*t+e]+2]);o=math_vector_Vector3.TransformCoordinates(o,s),(r=0==e?this._tmpAmmoVectorA:1==e?this._tmpAmmoVectorB:this._tmpAmmoVectorC).setValue(o.x,o.y,o.z),i.push(r)}e.addTriangle(i[0],i[1],i[2]),r++}i.getChildMeshes().forEach(i=>{r+=this._addMeshVerts(e,t,i)})}return r}_softVertexData(e){let t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(buffer_VertexBuffer.PositionKind);i||(i=[]);let r=t.getVerticesData(buffer_VertexBuffer.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);let s=[],a=[];for(let e=0;e<i.length;e+=3){let n=new math_vector_Vector3(i[e],i[e+1],i[e+2]),o=new math_vector_Vector3(r[e],r[e+1],r[e+2]);n=math_vector_Vector3.TransformCoordinates(n,t.getWorldMatrix()),o=math_vector_Vector3.TransformNormal(o,t.getWorldMatrix()),s.push(n.x,n.y,n.z),a.push(o.x,o.y,o.z)}let n=new mesh_vertexData_VertexData;return n.positions=s,n.normals=a,n.uvs=t.getVerticesData(buffer_VertexBuffer.UVKind),n.colors=t.getVerticesData(buffer_VertexBuffer.ColorKind),t&&t.getIndices&&(n.indices=t.getIndices()),n.applyToMesh(t),t.position=math_vector_Vector3.Zero(),t.rotationQuaternion=null,t.rotation=math_vector_Vector3.Zero(),t.computeWorldMatrix(!0),n}return mesh_vertexData_VertexData.ExtractFromMesh(t)}_createSoftbody(e){let t=e.object;if(t&&t.getIndices){let i=t.getIndices();i||(i=[]);let r=this._softVertexData(e),s=r.positions,a=r.normals;if(null===s||null===a)return new this.bjsAMMO.btCompoundShape;{let e;let r=[],n=[];for(let e=0;e<s.length;e+=3){let t=new math_vector_Vector3(s[e],s[e+1],s[e+2]),i=new math_vector_Vector3(a[e],a[e+1],a[e+2]);r.push(t.x,t.y,-t.z),n.push(i.x,i.y,-i.z)}let o=new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(),r,t.getIndices(),i.length/3,!0),l=s.length/3,h=o.get_m_nodes();for(let t=0;t<l;t++)(e=h.at(t).get_m_n()).setX(n[3*t]),e.setY(n[3*t+1]),e.setZ(n[3*t+2]);return o}}}_createCloth(e){let t=e.object;if(t&&t.getIndices){let i=t.getIndices();i||(i=[]);let r=this._softVertexData(e),s=r.positions,a=r.normals;if(null===s||null===a)return new this.bjsAMMO.btCompoundShape;{let t=s.length,i=Math.sqrt(t/3);e.segments=i;let r=i-1;this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[3*r],s[3*r+1],s[3*r+2]),this._tmpAmmoVectorD.setValue(s[t-3],s[t-2],s[t-1]),this._tmpAmmoVectorC.setValue(s[t-3-3*r],s[t-2-3*r],s[t-1-3*r]);let a=new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,this._tmpAmmoVectorC,this._tmpAmmoVectorD,i,i,e.getParam("fixedPoints"),!0);return a}}}_createRope(e){let t,i;let r=this._softVertexData(e),s=r.positions,a=r.normals;if(null===s||null===a)return new this.bjsAMMO.btCompoundShape;r.applyToMesh(e.object,!0),e._isFromLine=!0;let n=a.map(e=>e*e),o=n.reduce((e,t)=>e+t);if(0===o)i=(t=s.length)/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;let r=e.getParam("path"),s=e.getParam("shape");if(null===s)return logger_Logger.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;i=(t=r.length)-1,this._tmpAmmoVectorA.setValue(r[0].x,r[0].y,r[0].z),this._tmpAmmoVectorB.setValue(r[t-1].x,r[t-1].y,r[t-1].z)}e.segments=i;let l=e.getParam("fixedPoints");l=l>3?3:l;let h=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,l);return h.get_m_cfg().set_collisions(17),h}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let a=i.getVerticesData(buffer_VertexBuffer.PositionKind);a||(a=[]),i.computeWorldMatrix(!1);let n=s.length/3;for(let t=0;t<n;t++){let n=[];for(let e=0;e<3;e++){let r,o=new math_vector_Vector3(a[3*s[3*t+e]+0],a[3*s[3*t+e]+1],a[3*s[3*t+e]+2]);math_vector_Matrix.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),o=math_vector_Vector3.TransformCoordinates(o,this._tmpMatrix),(r=0==e?this._tmpAmmoVectorA:1==e?this._tmpAmmoVectorB:this._tmpAmmoVectorC).setValue(o.x,o.y,o.z),n.push(r)}e.addPoint(n[0],!0),e.addPoint(n[1],!0),e.addPoint(n[2],!0),r++}i.getChildMeshes().forEach(i=>{r+=this._addHullVerts(e,t,i)})}return r}_createShape(e,t=!1){let i;let r=e.object,s=e.getObjectExtents();if(!t){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];i=new this.bjsAMMO.btCompoundShape;let r=0;if(t.forEach(e=>{let t=e.getPhysicsImpostor();if(t){if(t.type==physicsImpostor_PhysicsImpostor.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";let s=this._createShape(t),a=e.parent.getWorldMatrix().clone(),n=new math_vector_Vector3;a.decompose(n),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*n.x,e.position.y*n.y,e.position.z*n.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),i.addChildShape(this._tmpAmmoTransform,s),t.dispose(),r++}}),r>0){if(e.type!=physicsImpostor_PhysicsImpostor.NoImpostor){let 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),i.addChildShape(this._tmpAmmoTransform,t))}return i}this.bjsAMMO.destroy(i),i=null}switch(e.type){case physicsImpostor_PhysicsImpostor.SphereImpostor:if(math_scalar_Scalar.WithinEpsilon(s.x,s.y,1e-4)&&math_scalar_Scalar.WithinEpsilon(s.x,s.z,1e-4))i=new this.bjsAMMO.btSphereShape(s.x/2);else{let e=[new this.bjsAMMO.btVector3(0,0,0)];(i=new this.bjsAMMO.btMultiSphereShape(e,[1],1)).setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case physicsImpostor_PhysicsImpostor.CapsuleImpostor:{let e=s.x/2;i=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case physicsImpostor_PhysicsImpostor.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case physicsImpostor_PhysicsImpostor.PlaneImpostor:case physicsImpostor_PhysicsImpostor.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case physicsImpostor_PhysicsImpostor.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)i=this.onCreateCustomMeshImpostor(e);else{let t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);let s=this._addMeshVerts(t,r,r);i=0==s?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case physicsImpostor_PhysicsImpostor.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)i=this.onCreateCustomConvexHullImpostor(e);else{let t=new this.bjsAMMO.btConvexHullShape,s=this._addHullVerts(t,r,r);0==s?(e._pluginData.toDispose.push(t),i=new this.bjsAMMO.btCompoundShape):i=t}break;case physicsImpostor_PhysicsImpostor.NoImpostor:i=new this.bjsAMMO.btSphereShape(s.x/2);break;case physicsImpostor_PhysicsImpostor.CustomImpostor:i=this._createCustom(e);break;case physicsImpostor_PhysicsImpostor.SoftbodyImpostor:i=this._createSoftbody(e);break;case physicsImpostor_PhysicsImpostor.ClothImpostor:i=this._createCloth(e);break;case physicsImpostor_PhysicsImpostor.RopeImpostor:i=this._createRope(e);break;default:logger_Logger.Warn("The impostor type is not currently supported by the ammo plugin.")}return i}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){let r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>.001||Math.abs(r.getOrigin().y()-t.y)>.001||Math.abs(r.getOrigin().z()-t.z)>.001||Math.abs(r.getRotation().x()-i.x)>.001||Math.abs(r.getRotation().y()-i.y)>.001||Math.abs(r.getRotation().z()-i.z)>.001||Math.abs(r.getRotation().w()-i.w)>.001){if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),0==e.mass){let t=e.physicsBody.getMotionState();t&&t.setWorldTransform(r)}else e.physicsBody.activate()}}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(!(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity()))return null;let i=new math_vector_Vector3(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()))return null;let i=new math_vector_Vector3(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:(logger_Logger.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===physicsImpostor_PhysicsImpostor.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):logger_Logger.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(logger_Logger.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):logger_Logger.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(logger_Logger.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):logger_Logger.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(logger_Logger.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):logger_Logger.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,s=1,a=!1){let n=e.segments;e.physicsBody.appendAnchor(Math.round((n-1)*i)+n*(n-1-Math.round((n-1)*r)),t.physicsBody,a,s)}appendHook(e,t,i,r=1,s=!1){let a=Math.round(e.segments*i);e.physicsBody.appendAnchor(a,t.physicsBody,s,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){logger_Logger.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){logger_Logger.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){let i=t.physicsBody;i.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){let t=e.getObjectExtents();return t.x/2}getBoxSizeToRef(e,t){let 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);let r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}};AmmoJSPlugin._DISABLE_COLLISION_FLAG=4,AmmoJSPlugin._KINEMATIC_FLAG=2,AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG=4,AbstractScene.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return -1;let t=this.reflectionProbes.indexOf(e);return -1!==t&&this.reflectionProbes.splice(t,1),t},AbstractScene.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};let reflectionProbe_ReflectionProbe=class reflectionProbe_ReflectionProbe{constructor(e,t,i,r=!0,s=!1,a=!1){let n;if(this.name=e,this._viewMatrix=math_vector_Matrix.Identity(),this._target=math_vector_Vector3.Zero(),this._add=math_vector_Vector3.Zero(),this._invertYAxis=!1,this.position=math_vector_Vector3.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(s){let e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new renderTargetTexture_RenderTargetTexture(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!a,this._renderTargetTexture.invertZ=i.useRightHandedSystem;let l=i.getEngine().useReverseDepthBuffer;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);let t=i.useRightHandedSystem?math_vector_Matrix.LookAtRHToRef:math_vector_Matrix.LookAtLHToRef,r=i.useRightHandedSystem?math_vector_Matrix.PerspectiveFovRH:math_vector_Matrix.PerspectiveFovLH;t(this.position,this._target,math_vector_Vector3.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=r(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,r;this._currentSceneUBO=i.getSceneUniformBuffer(),null===(r=(t=i.getEngine())._debugPushGroup)||void 0===r||r.call(t,`reflection probe generation for ${e}`,1),n=this._scene.imageProcessingConfiguration.applyByPostProcess,a&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var e,t;i.imageProcessingConfiguration.applyByPostProcess=n,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}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){let e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){let 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(let 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(){let e=decorators_SerializationHelper.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let i=0;i<t.reflectionProbes.length;i++){let s=t.reflectionProbes[i];if(s.name===e.name){r=s;break}}return(r=decorators_SerializationHelper.Parse(()=>r||new reflectionProbe_ReflectionProbe(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i)).cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}};__decorate([serializeAsMeshReference()],reflectionProbe_ReflectionProbe.prototype,"_attachedMesh",void 0),__decorate([serializeAsVector3()],reflectionProbe_ReflectionProbe.prototype,"position",void 0);let BabylonFileLoaderConfiguration=class BabylonFileLoaderConfiguration{};BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine=void 0;let aK={},aq={},parseMaterialByPredicate=(e,t,i,r)=>{if(!t.materials)return null;for(let s=0,a=t.materials.length;s<a;s++){let a=t.materials[s];if(e(a))return{parsedMaterial:a,material:material_Material.Parse(a,i,r)}}return null},isDescendantOf=(e,t,i)=>{for(let r in t)if(e.name===t[r])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},logOperation=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),loadDetailLevels=(e,t)=>{if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){let i=t._waitingData.lods.ids,r=t.isEnabled(!1);if(t._waitingData.lods.distances){let s=t._waitingData.lods.distances;if(s.length>=i.length){let a=s.length>i.length?s[s.length-1]:0;t.setEnabled(!1);for(let r=0;r<i.length;r++){let a=i[r],n=e.getMeshById(a);null!=n&&t.addLODLevel(s[r],n)}a>0&&t.addLODLevel(a,null),!0===r&&t.setEnabled(!0)}else tools_Tools.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},findParent=(e,t,i)=>{if("number"!=typeof e){let r=i.getLastEntryById(e);if(r&&null!=t){let e=r.instances[parseInt(t)];return e}return r}let r=aK[e];if(r&&null!=t){let e=r.instances[parseInt(t)];return e}return r},findMaterial=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):aq[e],loadAssetContainer=(e,t,i,r,s=!1)=>{let a=new AssetContainer(e),n="importScene has failed JSON parse";try{let r,s;var o=JSON.parse(t);n="";let l=sceneLoader_SceneLoader.loggingLevel===sceneLoader_SceneLoader.DETAILED_LOGGING;if(void 0!==o.environmentTexture&&null!==o.environmentTexture){let t=void 0===o.isPBR||o.isPBR;if(o.environmentTextureType&&"BABYLON.HDRCubeTexture"===o.environmentTextureType){let r=o.environmentTextureSize?o.environmentTextureSize:128,s=new hdrCubeTexture_HDRCubeTexture((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,r,!0,!t,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(s.rotationY=o.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof o.environmentTexture){let t=cubeTexture_CubeTexture.Parse(o.environmentTexture,e,i);e.environmentTexture=t}else if(o.environmentTexture.endsWith(".env")){let t=new cubeTexture_CubeTexture((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}else{let t=cubeTexture_CubeTexture.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}if(!0===o.createDefaultSkybox){let i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,r=o.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,r)}a.environmentTexture=e.environmentTexture}if(void 0!==o.environmentIntensity&&null!==o.environmentIntensity&&(e.environmentIntensity=o.environmentIntensity),void 0!==o.lights&&null!==o.lights)for(r=0,s=o.lights.length;r<s;r++){let t=o.lights[r],i=light_Light.Parse(t,e);i&&(aK[t.uniqueId]=i,a.lights.push(i),i._parentContainer=a,n+=(0===r?"\n Lights:":"")+"\n "+i.toString(l))}if(void 0!==o.reflectionProbes&&null!==o.reflectionProbes)for(r=0,s=o.reflectionProbes.length;r<s;r++){let t=o.reflectionProbes[r],s=reflectionProbe_ReflectionProbe.Parse(t,e,i);s&&(a.reflectionProbes.push(s),s._parentContainer=a,n+=(0===r?"\n Reflection Probes:":"")+"\n "+s.toString(l))}if(void 0!==o.animations&&null!==o.animations)for(r=0,s=o.animations.length;r<s;r++){let t=o.animations[r],i=h["BABYLON.Animation"];if(i){let s=i.Parse(t);e.animations.push(s),a.animations.push(s),n+=(0===r?"\n Animations:":"")+"\n "+s.toString(l)}}if(void 0!==o.materials&&null!==o.materials)for(r=0,s=o.materials.length;r<s;r++){let t=o.materials[r],s=material_Material.Parse(t,e,i);if(s){aq[t.uniqueId||t.id]=s,a.materials.push(s),s._parentContainer=a,n+=(0===r?"\n Materials:":"")+"\n "+s.toString(l);let e=s.getActiveTextures();e.forEach(e=>{-1==a.textures.indexOf(e)&&(a.textures.push(e),e._parentContainer=a)})}}if(void 0!==o.multiMaterials&&null!==o.multiMaterials)for(r=0,s=o.multiMaterials.length;r<s;r++){let t=o.multiMaterials[r],i=multiMaterial_MultiMaterial.ParseMultiMaterial(t,e);aq[t.uniqueId||t.id]=i,a.multiMaterials.push(i),i._parentContainer=a,n+=(0===r?"\n MultiMaterials:":"")+"\n "+i.toString(l);let s=i.getActiveTextures();s.forEach(e=>{-1==a.textures.indexOf(e)&&(a.textures.push(e),e._parentContainer=a)})}if(void 0!==o.morphTargetManagers&&null!==o.morphTargetManagers)for(let t of o.morphTargetManagers){let i=morphTargetManager_MorphTargetManager.Parse(t,e);a.morphTargetManagers.push(i),i._parentContainer=a}if(void 0!==o.skeletons&&null!==o.skeletons)for(r=0,s=o.skeletons.length;r<s;r++){let t=o.skeletons[r],i=skeleton_Skeleton.Parse(t,e);a.skeletons.push(i),i._parentContainer=a,n+=(0===r?"\n Skeletons:":"")+"\n "+i.toString(l)}let c=o.geometries;if(null!=c){let t=[],n=c.vertexData;if(null!=n)for(r=0,s=n.length;r<s;r++){let s=n[r];t.push(Geometry.Parse(s,e,i))}t.forEach(e=>{e&&(a.geometries.push(e),e._parentContainer=a)})}if(void 0!==o.transformNodes&&null!==o.transformNodes)for(r=0,s=o.transformNodes.length;r<s;r++){let t=o.transformNodes[r],s=transformNode_TransformNode.Parse(t,e,i);aK[t.uniqueId]=s,a.transformNodes.push(s),s._parentContainer=a}if(void 0!==o.meshes&&null!==o.meshes)for(r=0,s=o.meshes.length;r<s;r++){let t=o.meshes[r],s=mesh_Mesh.Parse(t,e,i);if(aK[t.uniqueId]=s,a.meshes.push(s),s._parentContainer=a,s.hasInstances)for(let e of s.instances)a.meshes.push(e),e._parentContainer=a;n+=(0===r?"\n Meshes:":"")+"\n "+s.toString(l)}if(void 0!==o.cameras&&null!==o.cameras)for(r=0,s=o.cameras.length;r<s;r++){let t=o.cameras[r],i=camera_Camera.Parse(t,e);aK[t.uniqueId]=i,a.cameras.push(i),i._parentContainer=a,n+=(0===r?"\n Cameras:":"")+"\n "+i.toString(l)}if(void 0!==o.postProcesses&&null!==o.postProcesses)for(r=0,s=o.postProcesses.length;r<s;r++){let t=o.postProcesses[r],s=postProcess_PostProcess.Parse(t,e,i);s&&(a.postProcesses.push(s),s._parentContainer=a,n+=(0===r?"\nPostprocesses:":"")+"\n "+s.toString())}if(void 0!==o.animationGroups&&null!==o.animationGroups)for(r=0,s=o.animationGroups.length;r<s;r++){let t=o.animationGroups[r],i=AnimationGroup.Parse(t,e);a.animationGroups.push(i),i._parentContainer=a,n+=(0===r?"\n AnimationGroups:":"")+"\n "+i.toString(l)}for(r=0,s=e.cameras.length;r<s;r++){let t=e.cameras[r];null!==t._waitingParentId&&(t.parent=findParent(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,s=e.lights.length;r<s;r++){let t=e.lights[r];t&&null!==t._waitingParentId&&(t.parent=findParent(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,s=e.transformNodes.length;r<s;r++){let t=e.transformNodes[r];null!==t._waitingParentId&&(t.parent=findParent(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,s=e.meshes.length;r<s;r++){let t=e.meshes[r];null!==t._waitingParentId&&(t.parent=findParent(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null),t._waitingData.lods&&loadDetailLevels(e,t)}for(e.multiMaterials.forEach(t=>{t._waitingSubMaterialsUniqueIds.forEach(i=>{t.subMaterials.push(findMaterial(i,e))}),t._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(t=>{null!==t._waitingMaterialId&&(t.material=findMaterial(t._waitingMaterialId,e),t._waitingMaterialId=null)}),r=0,s=e.skeletons.length;r<s;r++){let t=e.skeletons[r];t._hasWaitingData&&(null!=t.bones&&t.bones.forEach(t=>{if(t._waitingTransformNodeId){let i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}}),t._hasWaitingData=null)}for(r=0,s=e.meshes.length;r<s;r++){let t=e.meshes[r];t._waitingData.freezeWorldMatrix?(t.freezeWorldMatrix(),t._waitingData.freezeWorldMatrix=null):t.computeWorldMatrix(!0)}for(r=0,s=e.lights.length;r<s;r++){let t=e.lights[r];if(t._excludedMeshesIds.length>0){for(let i=0;i<t._excludedMeshesIds.length;i++){let r=e.getMeshById(t._excludedMeshesIds[i]);r&&t.excludedMeshes.push(r)}t._excludedMeshesIds=[]}if(t._includedOnlyMeshesIds.length>0){for(let i=0;i<t._includedOnlyMeshesIds.length;i++){let r=e.getMeshById(t._includedOnlyMeshesIds[i]);r&&t.includedOnlyMeshes.push(r)}t._includedOnlyMeshesIds=[]}}for(e.geometries.forEach(e=>{e._loadedUniqueId=""}),AbstractScene.Parse(o,e,a,i),r=0,s=e.meshes.length;r<s;r++){let t=e.meshes[r];t._waitingData.actions&&(ActionManager.Parse(t._waitingData.actions,t,e),t._waitingData.actions=null)}void 0!==o.actions&&null!==o.actions&&ActionManager.Parse(o.actions,null,e)}catch(t){let e=logOperation("loadAssets",o?o.producer:"Unknown")+n;if(r)r(e,t);else throw logger_Logger.Log(e),t}finally{aK={},aq={},s||a.removeAllFromScene(),null!==n&&sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.NO_LOGGING&&logger_Logger.Log(logOperation("loadAssets",o?o.producer:"Unknown")+(sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.MINIMAL_LOGGING?n:""))}return a};sceneLoader_SceneLoader.RegisterPlugin({name:"babylon.js",extensions:".babylon",canDirectLoad:e=>-1!==e.indexOf("babylon"),importMesh:(e,t,i,r,s,a,n,o)=>{var l;let h="importMesh has failed JSON parse";try{var c=JSON.parse(i);h="";let o=sceneLoader_SceneLoader.loggingLevel===sceneLoader_SceneLoader.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;let u=[],d=new Map,_=[];if(void 0!==c.transformNodes&&null!==c.transformNodes)for(let e=0,i=c.transformNodes.length;e<i;e++){let i=c.transformNodes[e],s=transformNode_TransformNode.Parse(i,t,r);_.push(s),d.set(s._waitingParsedUniqueId,s),s._waitingParsedUniqueId=null}if(void 0!==c.meshes&&null!==c.meshes){let i;let a=[],p=[],f=[],m=[];for(let i=0,l=c.meshes.length;i<l;i++){let l=c.meshes[i];if(null===e||isDescendantOf(l,e,u)){if(null!==e&&delete e[e.indexOf(l.name)],void 0!==l.geometryId&&null!==l.geometryId&&void 0!==c.geometries&&null!==c.geometries){let e=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach(i=>{!0!==e&&c.geometries[i]&&Array.isArray(c.geometries[i])&&c.geometries[i].forEach(s=>{s.id===l.geometryId&&("vertexData"===i&&Geometry.Parse(s,t,r),e=!0)})}),!1===e&&logger_Logger.Warn("Geometry not found for mesh "+l.id)}if(l.materialUniqueId||l.materialId){let e=l.materialUniqueId?f:p,i=-1!==e.indexOf(l.materialUniqueId||l.materialId);if(!1===i&&void 0!==c.multiMaterials&&null!==c.multiMaterials){let loadSubMaterial=(i,s)=>{e.push(i);let a=parseMaterialByPredicate(s,c,t,r);a&&a.material&&(aq[a.parsedMaterial.uniqueId||a.parsedMaterial.id]=a.material,h+="\n Material "+a.material.toString(o))};for(let r=0,s=c.multiMaterials.length;r<s;r++){let s=c.multiMaterials[r];if(l.materialUniqueId&&s.uniqueId===l.materialUniqueId||s.id===l.materialId){s.materialsUniqueIds?s.materialsUniqueIds.forEach(e=>loadSubMaterial(e,t=>t.uniqueId===e)):s.materials.forEach(e=>loadSubMaterial(e,t=>t.id===e)),e.push(s.uniqueId||s.id);let r=multiMaterial_MultiMaterial.ParseMultiMaterial(s,t);aq[s.uniqueId||s.id]=r,r&&(i=!0,h+="\n Multi-Material "+r.toString(o));break}}}if(!1===i){e.push(l.materialUniqueId||l.materialId);let i=parseMaterialByPredicate(e=>l.materialUniqueId&&e.uniqueId===l.materialUniqueId||e.id===l.materialId,c,t,r);i&&i.material?(aq[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,h+="\n Material "+i.material.toString(o)):logger_Logger.Warn("Material not found for mesh "+l.id)}}if(null!==l.skeletonId&&void 0!==l.skeletonId&&-1!==c.skeletonId&&void 0!==c.skeletons&&null!==c.skeletons){let e=a.indexOf(l.skeletonId)>-1;if(!e)for(let e=0,i=c.skeletons.length;e<i;e++){let i=c.skeletons[e];if(i.id===l.skeletonId){let e=skeleton_Skeleton.Parse(i,t);n.push(e),a.push(i.id),h+="\n Skeleton "+e.toString(o)}}}if(l.morphTargetManagerId>-1&&void 0!==c.morphTargetManagers&&null!==c.morphTargetManagers){let e=m.indexOf(l.morphTargetManagerId)>-1;if(!e)for(let e=0,i=c.morphTargetManagers.length;e<i;e++){let i=c.morphTargetManagers[e];if(i.id===l.morphTargetManagerId){let e=morphTargetManager_MorphTargetManager.Parse(i,t);m.push(e.uniqueId),h+="\nMorph target "+e.toString()}}}let i=mesh_Mesh.Parse(l,t,r);s.push(i),d.set(i._waitingParsedUniqueId,i),i._waitingParsedUniqueId=null,h+="\n Mesh "+i.toString(o)}}t.multiMaterials.forEach(e=>{e._waitingSubMaterialsUniqueIds.forEach(i=>{e.subMaterials.push(findMaterial(i,t))}),e._waitingSubMaterialsUniqueIds=[]}),t.meshes.forEach(e=>{null!==e._waitingMaterialId&&(e.material=findMaterial(e._waitingMaterialId,t),e._waitingMaterialId=null)});for(let e=0,i=t.transformNodes.length;e<i;e++){let i=t.transformNodes[e];if(null!==i._waitingParentId){let e=d.get(parseInt(i._waitingParentId))||null;null===e&&(e=t.getLastEntryById(i._waitingParentId));let r=e;i._waitingParentInstanceIndex&&(r=e.instances[parseInt(i._waitingParentInstanceIndex)],i._waitingParentInstanceIndex=null),i.parent=r,i._waitingParentId=null}}for(let e=0,r=t.meshes.length;e<r;e++){if((i=t.meshes[e])._waitingParentId){let e=d.get(parseInt(i._waitingParentId))||null;null===e&&(e=t.getLastEntryById(i._waitingParentId));let r=e;if(i._waitingParentInstanceIndex&&(r=e.instances[parseInt(i._waitingParentInstanceIndex)],i._waitingParentInstanceIndex=null),i.parent=r,(null===(l=i.parent)||void 0===l?void 0:l.getClassName())==="TransformNode"){let e=_.indexOf(i.parent);e>-1&&_.splice(e,1)}i._waitingParentId=null}i._waitingData.lods&&loadDetailLevels(t,i)}for(let e of _)e.dispose();for(let e=0,i=t.skeletons.length;e<i;e++){let i=t.skeletons[e];i._hasWaitingData&&(null!=i.bones&&i.bones.forEach(e=>{if(e._waitingTransformNodeId){let i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}}),i._hasWaitingData=null)}for(let e=0,r=t.meshes.length;e<r;e++)(i=t.meshes[e])._waitingData.freezeWorldMatrix?(i.freezeWorldMatrix(),i._waitingData.freezeWorldMatrix=null):i.computeWorldMatrix(!0)}if(void 0!==c.particleSystems&&null!==c.particleSystems){let e=AbstractScene.GetIndividualParser(sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM);if(e)for(let i=0,s=c.particleSystems.length;i<s;i++){let s=c.particleSystems[i];-1!==u.indexOf(s.emitterId)&&a.push(e(s,t,r))}}return t.geometries.forEach(e=>{e._loadedUniqueId=""}),!0}catch(t){let e=logOperation("importMesh",c?c.producer:"Unknown")+h;if(o)o(e,t);else throw logger_Logger.Log(e),t}finally{null!==h&&sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.NO_LOGGING&&logger_Logger.Log(logOperation("importMesh",c?c.producer:"Unknown")+(sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.MINIMAL_LOGGING?h:"")),aq={}}return!1},load:(e,t,i,r)=>{let s="importScene has failed JSON parse";try{var a=JSON.parse(t);if(s="",void 0!==a.useDelayedTextureLoading&&null!==a.useDelayedTextureLoading&&(e.useDelayedTextureLoading=a.useDelayedTextureLoading&&!sceneLoader_SceneLoader.ForceFullSceneLoadingForIncremental),void 0!==a.autoClear&&null!==a.autoClear&&(e.autoClear=a.autoClear),void 0!==a.clearColor&&null!==a.clearColor&&(e.clearColor=math_color_Color4.FromArray(a.clearColor)),void 0!==a.ambientColor&&null!==a.ambientColor&&(e.ambientColor=math_color_Color3.FromArray(a.ambientColor)),void 0!==a.gravity&&null!==a.gravity&&(e.gravity=math_vector_Vector3.FromArray(a.gravity)),void 0!==a.useRightHandedSystem&&(e.useRightHandedSystem=!!a.useRightHandedSystem),a.fogMode&&0!==a.fogMode)switch(e.fogMode=a.fogMode,e.fogColor=math_color_Color3.FromArray(a.fogColor),e.fogStart=a.fogStart,e.fogEnd=a.fogEnd,e.fogDensity=a.fogDensity,s+=" Fog mode for scene: ",e.fogMode){case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(a.physicsEnabled){let t;"cannon"===a.physicsEngine||a.physicsEngine===CannonJSPlugin.name?t=new CannonJSPlugin(void 0,void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine):"oimo"===a.physicsEngine||a.physicsEngine===OimoJSPlugin.name?t=new OimoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine):("ammo"===a.physicsEngine||a.physicsEngine===AmmoJSPlugin.name)&&(t=new AmmoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(a.physicsEngine?a.physicsEngine:"oimo")+" enabled\n";let i=a.physicsGravity?math_vector_Vector3.FromArray(a.physicsGravity):null;e.enablePhysics(i,t)}void 0!==a.metadata&&null!==a.metadata&&(e.metadata=a.metadata),void 0!==a.collisionsEnabled&&null!==a.collisionsEnabled&&(e.collisionsEnabled=a.collisionsEnabled);let n=loadAssetContainer(e,t,i,r,!0);if(!n)return!1;return a.autoAnimate&&e.beginAnimation(e,a.autoAnimateFrom,a.autoAnimateTo,a.autoAnimateLoop,a.autoAnimateSpeed||1),void 0!==a.activeCameraID&&null!==a.activeCameraID&&e.setActiveCameraById(a.activeCameraID),!0}catch(t){let e=logOperation("importScene",a?a.producer:"Unknown")+s;if(r)r(e,t);else throw logger_Logger.Log(e),t}finally{null!==s&&sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.NO_LOGGING&&logger_Logger.Log(logOperation("importScene",a?a.producer:"Unknown")+(sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,r)=>{let s=loadAssetContainer(e,t,i,r);return s}});let FresnelParameters=class FresnelParameters{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,engine_Engine.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||math_color_Color3.White(),this.rightColor=e.rightColor||math_color_Color3.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){let e=new FresnelParameters;return DeepCopier.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 FresnelParameters({isEnabled:e.isEnabled,leftColor:math_color_Color3.FromArray(e.leftColor),rightColor:math_color_Color3.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}};decorators_SerializationHelper._FresnelParametersParser=FresnelParameters.Parse;let PBRBaseSimpleMaterial=class PBRBaseSimpleMaterial extends pbrBaseMaterial_PBRBaseMaterial{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 math_color_Color3(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}};__decorate([serialize(),expandToProperty("_markAllSubMeshesAsLightsDirty")],PBRBaseSimpleMaterial.prototype,"maxSimultaneousLights",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsLightsDirty")],PBRBaseSimpleMaterial.prototype,"disableLighting",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],PBRBaseSimpleMaterial.prototype,"environmentTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"invertNormalMapX",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"invertNormalMapY",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],PBRBaseSimpleMaterial.prototype,"normalTexture",void 0),__decorate([serializeAsColor3("emissive"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"emissiveColor",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"emissiveTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],PBRBaseSimpleMaterial.prototype,"occlusionStrength",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],PBRBaseSimpleMaterial.prototype,"occlusionTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],PBRBaseSimpleMaterial.prototype,"alphaCutOff",void 0),__decorate([serialize()],PBRBaseSimpleMaterial.prototype,"doubleSided",null),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],PBRBaseSimpleMaterial.prototype,"lightmapTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"useLightmapAsShadowmap",void 0);let PBRMetallicRoughnessMaterial=class PBRMetallicRoughnessMaterial extends PBRBaseSimpleMaterial{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){let t=decorators_SerializationHelper.Clone(()=>new PBRMetallicRoughnessMaterial(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(){let e=decorators_SerializationHelper.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){let r=decorators_SerializationHelper.Parse(()=>new PBRMetallicRoughnessMaterial(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};__decorate([serializeAsColor3(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],PBRMetallicRoughnessMaterial.prototype,"baseColor",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],PBRMetallicRoughnessMaterial.prototype,"baseTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRMetallicRoughnessMaterial.prototype,"metallic",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRMetallicRoughnessMaterial.prototype,"roughness",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],PBRMetallicRoughnessMaterial.prototype,"metallicRoughnessTexture",void 0),h["BABYLON.PBRMetallicRoughnessMaterial"]=PBRMetallicRoughnessMaterial;let PBRSpecularGlossinessMaterial=class PBRSpecularGlossinessMaterial extends PBRBaseSimpleMaterial{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){let t=decorators_SerializationHelper.Clone(()=>new PBRSpecularGlossinessMaterial(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(){let e=decorators_SerializationHelper.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){let r=decorators_SerializationHelper.Parse(()=>new PBRSpecularGlossinessMaterial(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};__decorate([serializeAsColor3("diffuse"),expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],PBRSpecularGlossinessMaterial.prototype,"diffuseColor",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],PBRSpecularGlossinessMaterial.prototype,"diffuseTexture",void 0),__decorate([serializeAsColor3("specular"),expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],PBRSpecularGlossinessMaterial.prototype,"specularColor",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_microSurface")],PBRSpecularGlossinessMaterial.prototype,"glossiness",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],PBRSpecularGlossinessMaterial.prototype,"specularGlossinessTexture",void 0),h["BABYLON.PBRSpecularGlossinessMaterial"]=PBRSpecularGlossinessMaterial;let ColorGradingTexture=class ColorGradingTexture extends baseTexture_BaseTexture{constructor(e,t,i=null){if(super(t),!e)return;if(this._textureMatrix=math_vector_Matrix.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{let e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){let e;let t=this._getEngine();e=t._features.support3DTextures?t.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):t.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=e,this._texture.isReady=!1,this.isCube=!1,this.is3D=t._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;let callback=i=>{let r;if("string"!=typeof i)return;let s=null,a=null,n=i.split("\n"),o=0,l=0,h=0,c=0,u=0;for(let e=0;e<n.length;e++){if(r=n[e],!ColorGradingTexture._NoneEmptyLineRegex.test(r)||0===r.indexOf("#"))continue;let t=r.split(" ");if(0===o){o=t.length,s=new Uint8Array(o*o*o*4),a=new Float32Array(o*o*o*4);continue}if(0!=o){let e=Math.max(parseInt(t[0]),0),i=Math.max(parseInt(t[1]),0),r=Math.max(parseInt(t[2]),0);u=Math.max(r,u=Math.max(i,u=Math.max(e,u)));let s=(l+c*o+h*o*o)*4;a&&(a[s+0]=e,a[s+1]=i,a[s+2]=r),++h%o==0&&(h=0,++c%o==0&&(l++,c=0))}}if(a&&s)for(let e=0;e<a.length;e++)if(e>0&&(e+1)%4==0)s[e]=255;else{let t=a[e];s[e]=t/u*255}e.is3D?(e.updateSize(o,o,o),t.updateRawTexture3D(e,s,5,!1)):(e.updateSize(o*o,o),t.updateRawTexture(e,s,5,!1)),e.isReady=!0,this._triggerOnLoad()},i=this.getScene();return i?i._loadFile(this.url,callback):t._loadFile(this.url,callback),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){let e=new ColorGradingTexture(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 ColorGradingTexture(e.name,t)).name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}};ColorGradingTexture._NoneEmptyLineRegex=/\S+/,h["BABYLON.ColorGradingTexture"]=ColorGradingTexture;let equiRectangularCubeTexture_EquiRectangularCubeTexture=class equiRectangularCubeTexture_EquiRectangularCubeTexture extends baseTexture_BaseTexture{constructor(e,t,i,r=!1,s=!0,a=null,n=null,o=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw Error("Image url is not set");this._coordinatesMode=texture_Texture.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=o,this._noMipmap=r,this.gammaSpace=s,this._onLoad=a,this._onError=n,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?a&&(this._texture.isReady?tools_Tools.SetImmediate(()=>a()):this._texture.onLoadedObservable.add(a)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(()=>this._loadTexture(),this._onError)}_loadImage(e,t){let i=this.getScene();if(!i)return;let r=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,this._noMipmap,!1,3);r.generateMipMaps=!this._noMipmap,i.addPendingData(r),r.url=this.url,r.isReady=!1,i.getEngine()._internalTexturesCache.push(r),this._texture=r;let s=document.createElement("canvas");LoadImage(this.url,t=>{this._width=t.width,this._height=t.height,s.width=this._width,s.height=this._height;let i=s.getContext("2d");i.drawImage(t,0,0);let r=i.getImageData(0,0,t.width,t.height);this._buffer=r.data.buffer,s.remove(),e()},(e,s)=>{i.removePendingData(r),t&&t(`${this.getClassName()} could not be loaded`,s)},i?i.offlineProvider:null)}_loadTexture(){let e=this.getScene();if(!e)return;let t=(()=>{let e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=PanoramaToCubeMapTools.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){let r=t[equiRectangularCubeTexture_EquiRectangularCubeTexture._FacesMapping[e]];i.push(r)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){let t=new DataView(e),i=new Float32Array(3*e.byteLength/4),r=0;for(let s=0;s<e.byteLength;s++)(s+1)%4!=0&&(i[r++]=t.getUint8(s)/255);return i}getClassName(){return"EquiRectangularCubeTexture"}clone(){let e=this.getScene();if(!e)return this;let t=new equiRectangularCubeTexture_EquiRectangularCubeTexture(this.url,e,this._size,this._noMipmap,this.gammaSpace);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t}};equiRectangularCubeTexture_EquiRectangularCubeTexture._FacesMapping=["right","left","up","down","front","back"];let HtmlElementTexture=class HtmlElementTexture extends baseTexture_BaseTexture{constructor(e,t,i){var r,s;if(super(i.scene||i.engine),this.onLoadObservable=new observable_Observable,!t||!i.engine&&!i.scene)return;i=Object.assign(Object.assign({},HtmlElementTexture._DefaultOptions),i),this._generateMipMaps=i.generateMipMaps,this._samplingMode=i.samplingMode,this._textureMatrix=math_vector_Matrix.Identity(),this._format=i.format,this.name=e,this.element=t,this._isVideo=!!t.getVideoPlaybackQuality,this._externalTexture=this._isVideo&&null!==(s=null===(r=this._engine)||void 0===r?void 0:r.createExternalTexture(t))&&void 0!==s?s:null,this.anisotropicFilteringLevel=1,this._createInternalTexture()}_createInternalTexture(){let e=0,t=0;this._isVideo?(e=this.element.videoWidth,t=this.element.videoHeight):(e=this.element.width,t=this.element.height);let i=this._getEngine();i&&(this._texture=i.createDynamicTexture(e,t,this._generateMipMaps,this._samplingMode),this._texture.format=this._format),this.update()}getTextureMatrix(){return this._textureMatrix}update(e=null){let t=this._getEngine();if(null==this._texture||null==t)return;let i=this.isReady();if(this._isVideo){let i=this.element;if(i.readyState<i.HAVE_CURRENT_DATA)return;t.updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:i,null===e||e)}else{let i=this.element;t.updateDynamicTexture(this._texture,i,null===e||e,!1,this._format)}!i&&this.isReady()&&this.onLoadObservable.notifyObservers(this)}dispose(){this.onLoadObservable.clear(),super.dispose()}};function GetTGAHeader(e){let t=0,i={id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]};return i}function UploadContent(e,t){let i,r,s,a,n,o,l,h;if(t.length<19){logger_Logger.Error("Unable to load TGA file - Not enough data to contain header");return}let c=18,u=GetTGAHeader(t);if(u.id_length+c>t.length){logger_Logger.Error("Unable to load TGA file - Not enough data");return}c+=u.id_length;let d=!1,_=!1,p=!1;switch(u.image_type){case 9:d=!0;case 1:_=!0;break;case 10:d=!0;case 2:break;case 11:d=!0;case 3:p=!0}let f=u.pixel_size>>3,m=u.width*u.height*f;if(_&&(r=t.subarray(c,c+=u.colormap_length*(u.colormap_size>>3))),d){let e,r,s;i=new Uint8Array(m);let a=0,n=new Uint8Array(f);for(;c<m&&a<m;)if(r=(127&(e=t[c++]))+1,128&e){for(s=0;s<f;++s)n[s]=t[c++];for(s=0;s<r;++s)i.set(n,a+s*f);a+=f*r}else{for(r*=f,s=0;s<r;++s)i[a+s]=t[c++];a+=r}}else i=t.subarray(c,c+=_?u.width*u.height:m);switch((48&u.flags)>>4){default:case 2:s=0,n=1,h=u.width,a=0,o=1,l=u.height;break;case 0:s=0,n=1,h=u.width,a=u.height-1,o=-1,l=-1;break;case 3:s=u.width-1,n=-1,h=-1,a=0,o=1,l=u.height;break;case 1:s=u.width-1,n=-1,h=-1,a=u.height-1,o=-1,l=-1}let g="_getImageData"+(p?"Grey":"")+u.pixel_size+"bits",v=a$[g](u,r,i,a,o,l,s,n,h),x=e.getEngine();x._uploadDataToTextureDirectly(e,v)}function _getImageData8bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u,d=0,_,p,f=new Uint8Array(h*c*4);for(p=r;p!==a;p+=s)for(_=n;_!==l;_+=o,d++)u=i[d],f[(_+h*p)*4+3]=255,f[(_+h*p)*4+2]=t[3*u+0],f[(_+h*p)*4+1]=t[3*u+1],f[(_+h*p)*4+0]=t[3*u+2];return f}function _getImageData16bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u,d=0,_,p,f=new Uint8Array(h*c*4);for(p=r;p!==a;p+=s)for(_=n;_!==l;_+=o,d+=2){u=i[d+0]+(i[d+1]<<8);let e=((31744&u)>>10)*255/31|0,t=((992&u)>>5)*255/31|0,r=(31&u)*255/31|0;f[(_+h*p)*4+0]=e,f[(_+h*p)*4+1]=t,f[(_+h*p)*4+2]=r,f[(_+h*p)*4+3]=32768&u?0:255}return f}function _getImageData24bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u=0,d,_,p=new Uint8Array(h*c*4);for(_=r;_!==a;_+=s)for(d=n;d!==l;d+=o,u+=3)p[(d+h*_)*4+3]=255,p[(d+h*_)*4+2]=i[u+0],p[(d+h*_)*4+1]=i[u+1],p[(d+h*_)*4+0]=i[u+2];return p}function _getImageData32bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u=0,d,_,p=new Uint8Array(h*c*4);for(_=r;_!==a;_+=s)for(d=n;d!==l;d+=o,u+=4)p[(d+h*_)*4+2]=i[u+0],p[(d+h*_)*4+1]=i[u+1],p[(d+h*_)*4+0]=i[u+2],p[(d+h*_)*4+3]=i[u+3];return p}function _getImageDataGrey8bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u,d=0,_,p,f=new Uint8Array(h*c*4);for(p=r;p!==a;p+=s)for(_=n;_!==l;_+=o,d++)u=i[d],f[(_+h*p)*4+0]=u,f[(_+h*p)*4+1]=u,f[(_+h*p)*4+2]=u,f[(_+h*p)*4+3]=255;return f}function _getImageDataGrey16bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u=0,d,_,p=new Uint8Array(h*c*4);for(_=r;_!==a;_+=s)for(d=n;d!==l;d+=o,u+=2)p[(d+h*_)*4+0]=i[u+0],p[(d+h*_)*4+1]=i[u+0],p[(d+h*_)*4+2]=i[u+0],p[(d+h*_)*4+3]=i[u+1];return p}HtmlElementTexture._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};let a$={GetTGAHeader,UploadContent,_getImageData8bits,_getImageData16bits,_getImageData24bits,_getImageData32bits,_getImageDataGrey8bits,_getImageDataGrey16bits};let _TGATextureLoader=class _TGATextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=GetTGAHeader(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{UploadContent(t,r)})}};engine_Engine._TextureLoaders.push(new _TGATextureLoader);let _HDRTextureLoader=class _HDRTextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=HDRTools.RGBE_ReadHeader(r),a=HDRTools.RGBE_ReadPixels(r,s),n=s.width*s.height,o=new Float32Array(4*n);for(let e=0;e<n;e+=1)o[4*e]=a[3*e],o[4*e+1]=a[3*e+1],o[4*e+2]=a[3*e+2],o[4*e+3]=1;i(s.width,s.height,t.generateMipMaps,!1,()=>{let e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,o)})}};engine_Engine._TextureLoaders.push(new _HDRTextureLoader),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"}(tE||(tE={}));let aQ={JSModuleURL:`${tools_Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${tools_Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},aZ=null,aJ=null,a0=0,_CreateWorkerAsync=()=>(aZ||(aZ=new Promise((e,t)=>{aJ?e(aJ):tools_Tools.LoadFileAsync(tools_Tools.GetBabylonScriptURL(aQ.WasmModuleURL)).then(i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");let r=URL.createObjectURL(new Blob([`(${basis_workerFunc})()`],{type:"application/javascript"}));aJ=new Worker(r);let initHandler=i=>{"init"===i.data.action?(aJ.removeEventListener("message",initHandler),e(aJ)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};aJ.addEventListener("message",initHandler),aJ.postMessage({action:"init",url:tools_Tools.GetBabylonScriptURL(aQ.JSModuleURL),wasmBinary:i})}).catch(t)})),aZ),TranscodeAsync=(e,t)=>{let i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise((e,r)=>{_CreateWorkerAsync().then(()=>{let s=a0++,messageHandler=t=>{"transcode"===t.data.action&&t.data.id===s&&(aJ.removeEventListener("message",messageHandler),t.data.success?e(t.data):r("Transcode is not supported on this device"))};aJ.addEventListener("message",messageHandler);let a=new Uint8Array(i.byteLength);a.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),aJ.postMessage({action:"transcode",id:s,imageData:a,config:t,ignoreSupportedFormats:!1},[a.buffer])},e=>{r(e)})})},BindTexture=(e,t)=>{var i,r;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(r=t._gl)||void 0===r?void 0:r.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},LoadTextureFromTranscodeResult=(e,t)=>{let i=e.getEngine();for(let r=0;r<t.fileInfo.images.length;r++){let s=t.fileInfo.images[r].levels[0];if(e._invertVScale=e.invertY,-1===t.format||t.format===tE.cTFRGB565){if(e.type=10,e.format=4,i._features.basisNeedsPOT&&(math_scalar_Scalar.Log2(s.width)%1!=0||math_scalar_Scalar.Log2(s.height)%1!=0)){let t=new internalTexture_InternalTexture(i,$.Temp);e._invertVScale=e.invertY,t.type=10,t.format=4,t.width=s.width+3&-4,t.height=s.height+3&-4,BindTexture(t,i),i._uploadDataToTextureDirectly(t,new Uint16Array(s.transcodedPixels.buffer),r,0,4,!0),i._rescaleTexture(t,e,i.scenes[0],i._getInternalFormat(4),()=>{i._releaseTexture(t),BindTexture(e,i)})}else e._invertVScale=!e.invertY,e.width=s.width+3&-4,e.height=s.height+3&-4,e.samplingMode=2,BindTexture(e,i),i._uploadDataToTextureDirectly(e,new Uint16Array(s.transcodedPixels.buffer),r,0,4,!0)}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[r].levels.length>1;let a=a1.GetInternalFormatFromBasisFormat(t.format,i);e.format=a,BindTexture(e,i),t.fileInfo.images[r].levels.forEach((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,a,t.width,t.height,t.transcodedPixels,r,s)}),i._features.basisNeedsPOT&&(math_scalar_Scalar.Log2(e.width)%1!=0||math_scalar_Scalar.Log2(e.height)%1!=0)&&(tools_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."),e._cachedWrapU=texture_Texture.CLAMP_ADDRESSMODE,e._cachedWrapV=texture_Texture.CLAMP_ADDRESSMODE)}}},a1={JSModuleURL:aQ.JSModuleURL,WasmModuleURL:aQ.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case tE.cTFETC1:i=36196;break;case tE.cTFBC1:i=33776;break;case tE.cTFBC4:i=33779;break;case tE.cTFASTC_4x4:i=37808;break;case tE.cTFETC2:i=37496;break;case tE.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync,LoadTextureFromTranscodeResult};function basis_workerFunc(){let e={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFRGB565:14},t=null;function GetSupportedTranscodeFormat(t,i){let r=null;return t.supportedCompressionFormats&&(r=t.supportedCompressionFormats.astc?e.cTFASTC_4x4:t.supportedCompressionFormats.bc7?e.cTFBC7:t.supportedCompressionFormats.s3tc?i.hasAlpha?e.cTFBC3:e.cTFBC1:t.supportedCompressionFormats.pvrtc?i.hasAlpha?e.cTFPVRTC1_4_RGBA:e.cTFPVRTC1_4_RGB:t.supportedCompressionFormats.etc2?e.cTFETC2:t.supportedCompressionFormats.etc1?e.cTFETC1:e.cTFRGB565),r}function GetFileInfo(e){let t=e.getHasAlpha(),i=e.getNumImages(),r=[];for(let t=0;t<i;t++){let i={levels:[]},s=e.getNumLevels(t);for(let r=0;r<s;r++){let s={width:e.getImageWidth(t,r),height:e.getImageHeight(t,r)};i.levels.push(s)}r.push(i)}return{hasAlpha:t,images:r}}function TranscodeLevel(e,t,i,r,s){let a=e.getImageTranscodedSizeInBytes(t,i,r),n=new Uint8Array(a);if(!e.transcodeImage(n,t,i,r,1,0))return null;if(s){let r=e.getImageWidth(t,i)+3&-4,s=e.getImageHeight(t,i)+3&-4;n=ConvertDxtToRgb565(n,0,r,s)}return n}function ConvertDxtToRgb565(e,t,i,r){let s=new Uint16Array(4),a=new Uint16Array(i*r),n=i/4,o=r/4;for(let r=0;r<o;r++)for(let o=0;o<n;o++){let l=t+8*(r*n+o);s[0]=e[l]|e[l+1]<<8,s[1]=e[l+2]|e[l+3]<<8,s[2]=(2*(31&s[0])+1*(31&s[1]))/3|(2*(2016&s[0])+1*(2016&s[1]))/3&2016|(2*(63488&s[0])+1*(63488&s[1]))/3&63488,s[3]=(2*(31&s[1])+1*(31&s[0]))/3|(2*(2016&s[1])+1*(2016&s[0]))/3&2016|(2*(63488&s[1])+1*(63488&s[0]))/3&63488;for(let t=0;t<4;t++){let n=e[l+4+t],h=(4*r+t)*i+4*o;a[h++]=s[3&n],a[h++]=s[n>>2&3],a[h++]=s[n>>4&3],a[h++]=s[n>>6&3]}}return a}onmessage=i=>{if("init"===i.data.action){if(!t){try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}t=BASIS({wasmBinary:i.data.wasmBinary})}null!==t&&t.then(e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})})}else if("transcode"===i.data.action){let t=i.data.config,r=i.data.imageData,s=new BASIS.BasisFile(r),a=GetFileInfo(s),n=i.data.ignoreSupportedFormats?null:GetSupportedTranscodeFormat(i.data.config,a),o=!1;null===n&&(o=!0,n=a.hasAlpha?e.cTFBC3:e.cTFBC1);let l=!0;s.startTranscoding()||(l=!1);let h=[];for(let e=0;e<a.images.length&&l;e++){let i=a.images[e];if(void 0===t.loadSingleImage||t.loadSingleImage===e){let r=i.levels.length;!1===t.loadMipmapLevels&&(r=1);for(let t=0;t<r;t++){let r=i.levels[t],a=TranscodeLevel(s,e,t,n,o);if(!a){l=!1;break}r.transcodedPixels=a,h.push(r.transcodedPixels.buffer)}}}s.close(),s.delete(),o&&(n=-1),l?postMessage({action:"transcode",success:l,id:i.data.id,fileInfo:a,format:n},h):postMessage({action:"transcode",success:l,id:i.data.id})}}}Object.defineProperty(a1,"JSModuleURL",{get:function(){return aQ.JSModuleURL},set:function(e){aQ.JSModuleURL=e}}),Object.defineProperty(a1,"WasmModuleURL",{get:function(){return aQ.WasmModuleURL},set:function(e){aQ.WasmModuleURL=e}});let _BasisTextureLoader=class _BasisTextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let a=t.getEngine().getCaps(),n={supportedCompressionFormats:{etc1:!!a.etc1,s3tc:!!a.s3tc,pvrtc:!!a.pvrtc,etc2:!!a.etc2,astc:!!a.astc,bc7:!!a.bptc}};TranscodeAsync(e,n).then(e=>{let i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;LoadTextureFromTranscodeResult(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(e=>{tools_Tools.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(e)})}loadData(e,t,i){let r=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};TranscodeAsync(e,s).then(e=>{let r=e.fileInfo.images[0].levels[0],s=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(r.width,r.height,s,-1!==e.format,()=>{LoadTextureFromTranscodeResult(t,e)})}).catch(e=>{tools_Tools.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),tools_Tools.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,()=>{},!0)})}};engine_Engine._TextureLoaders.push(new _BasisTextureLoader);let MultiRenderTarget=class MultiRenderTarget extends renderTargetTexture_RenderTargetTexture{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;t<this._textures.length;t++)this._textures[t].wrapU=e}set wrapV(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapV=e}constructor(e,t,i,r,s,a){let n=!!s&&!!s.generateMipMaps&&s.generateMipMaps,o=!!s&&!!s.generateDepthTexture&&s.generateDepthTexture,l=s&&s.depthTextureFormat?s.depthTextureFormat:15,h=!s||void 0===s.doNotChangeAspectRatio||s.doNotChangeAspectRatio,c=!!s&&!!s.drawOnlyOnFirstAttachmentByDefault&&s.drawOnlyOnFirstAttachmentByDefault;if(super(e,t,r,n,h,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0),!this.isSupported){this.dispose();return}this._textureNames=a;let u=[],d=[],_=[],p=[],f=[],m=[],g=[],v=[];this._initTypes(i,u,d,_,p,f,m,g,v,s);let x=!s||void 0===s.generateDepthBuffer||s.generateDepthBuffer,b=!!s&&void 0!==s.generateStencilBuffer&&s.generateStencilBuffer;this._multiRenderTargetOptions={samplingModes:d,generateMipMaps:n,generateDepthBuffer:x,generateStencilBuffer:b,generateDepthTexture:o,depthTextureFormat:l,types:u,textureCount:i,useSRGBBuffers:_,formats:p,targetTypes:f,faceIndex:m,layerIndex:g,layerCounts:v},this._count=i,this._drawOnlyOnFirstAttachmentByDefault=c,i>0&&(this._createInternalTextures(),this._createTextures(a))}_initTypes(e,t,i,r,s,a,n,o,l,h){for(let c=0;c<e;c++)h&&h.types&&void 0!==h.types[c]?t.push(h.types[c]):t.push(h&&h.defaultType?h.defaultType:0),h&&h.samplingModes&&void 0!==h.samplingModes[c]?i.push(h.samplingModes[c]):i.push(texture_Texture.BILINEAR_SAMPLINGMODE),h&&h.useSRGBBuffers&&void 0!==h.useSRGBBuffers[c]?r.push(h.useSRGBBuffers[c]):r.push(!1),h&&h.formats&&void 0!==h.formats[c]?s.push(h.formats[c]):s.push(5),h&&h.targetTypes&&void 0!==h.targetTypes[c]?a.push(h.targetTypes[c]):a.push(3553),h&&h.faceIndex&&void 0!==h.faceIndex[c]?n.push(h.faceIndex[c]):n.push(0),h&&h.layerIndex&&void 0!==h.layerIndex[c]?o.push(h.layerIndex[c]):o.push(0),h&&h.layerCounts&&void 0!==h.layerCounts[c]?l.push(h.layerCounts[c]):l.push(1)}_createInternaTextureIndexMapping(){let e={},t=[];if(!this._renderTarget)return t;let i=this._renderTarget.textures;for(let r=0;r<i.length;r++){let s=i[r];if(!s)continue;let a=e[s.uniqueId];void 0!==a?t[r]=a:e[s.uniqueId]=r}return t}_rebuild(e=!1,t){if(this._count<1)return;let i=this._createInternaTextureIndexMapping();this.releaseInternalTextures(),this._createInternalTextures(),e&&(this._releaseTextures(),this._createTextures(t));let r=this._renderTarget.textures;for(let e=0;e<r.length;e++){let t=this._textures[e];void 0!==i[e]&&this._renderTarget.setTexture(r[i[e]],e),t._texture=r[e],t._texture&&(t._noMipmap=!t._texture.useMipMaps,t._useSRGBBuffer=t._texture._useSRGBBuffer)}1!==this.samples&&this._renderTarget.setSamples(this.samples,!this._drawOnlyOnFirstAttachmentByDefault,!0)}_createInternalTextures(){this._renderTarget=this._getEngine().createMultipleRenderTarget(this._size,this._multiRenderTargetOptions,!this._drawOnlyOnFirstAttachmentByDefault),this._texture=this._renderTarget.texture}_releaseTextures(){if(this._textures)for(let e=0;e<this._textures.length;e++)this._textures[e]._texture=null,this._textures[e].dispose()}_createTextures(e){let t=this._renderTarget.textures;this._textures=[];for(let i=0;i<t.length;i++){let r=new texture_Texture(null,this.getScene());(null==e?void 0:e[i])&&(r.name=e[i]),r._texture=t[i],r._texture&&(r._noMipmap=!r._texture.useMipMaps,r._useSRGBBuffer=r._texture._useSRGBBuffer),this._textures.push(r)}}setInternalTexture(e,t,i=!0){var r,s;if(this.renderTarget&&(0===t&&(this._texture=e),this.renderTarget.setTexture(e,t,i),this.textures[t]||(this.textures[t]=new texture_Texture(null,this.getScene()),this.textures[t].name=null!==(s=null===(r=this._textureNames)||void 0===r?void 0:r[t])&&void 0!==s?s:this.textures[t].name),this.textures[t]._texture=e,this.textures[t]._noMipmap=!e.useMipMaps,this.textures[t]._useSRGBBuffer=e._useSRGBBuffer,this._count=this.renderTarget.textures?this.renderTarget.textures.length:0,this._multiRenderTargetOptions.types&&(this._multiRenderTargetOptions.types[t]=e.type),this._multiRenderTargetOptions.samplingModes&&(this._multiRenderTargetOptions.samplingModes[t]=e.samplingMode),this._multiRenderTargetOptions.useSRGBBuffers&&(this._multiRenderTargetOptions.useSRGBBuffers[t]=e._useSRGBBuffer),this._multiRenderTargetOptions.targetTypes&&-1!==this._multiRenderTargetOptions.targetTypes[t])){let i=0;i=e.is2DArray?35866:e.isCube?34067:e.is3D?32879:3553,this._multiRenderTargetOptions.targetTypes[t]=i}}setLayerAndFaceIndex(e,t=-1,i=-1){this.textures[e]&&this.renderTarget&&(this._multiRenderTargetOptions.layerIndex&&(this._multiRenderTargetOptions.layerIndex[e]=t),this._multiRenderTargetOptions.faceIndex&&(this._multiRenderTargetOptions.faceIndex[e]=i),this.renderTarget.setLayerAndFaceIndex(e,t,i))}setLayerAndFaceIndices(e,t){this.renderTarget&&(this._multiRenderTargetOptions.layerIndex=e,this._multiRenderTargetOptions.faceIndex=t,this.renderTarget.setLayerAndFaceIndices(e,t))}get samples(){return this._samples}set samples(e){this._renderTarget?this._samples=this._renderTarget.setSamples(e):this._samples=e}resize(e){this._processSizeParameter(e,!1),this._rebuild(void 0,this._textureNames)}updateCount(e,t,i){this._multiRenderTargetOptions.textureCount=e,this._count=e;let r=[],s=[],a=[],n=[],o=[],l=[],h=[],c=[];this._textureNames=i,this._initTypes(e,r,s,a,n,o,l,h,c,t),this._multiRenderTargetOptions.types=r,this._multiRenderTargetOptions.samplingModes=s,this._multiRenderTargetOptions.useSRGBBuffers=a,this._multiRenderTargetOptions.formats=n,this._multiRenderTargetOptions.targetTypes=o,this._multiRenderTargetOptions.faceIndex=l,this._multiRenderTargetOptions.layerIndex=h,this._multiRenderTargetOptions.layerCounts=c,this._rebuild(!0,i)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindMultiColorAttachmentFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;let 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}}};let TexturePackerFrame=class TexturePackerFrame{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}};let TexturePacker=class TexturePacker{constructor(e,t,i,r){var s,a,n,o,l,h,c,u,d,_,p,f,m;return this.name=e,this.meshes=t,this.scene=r,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!==(a=this.options.uvsIn)&&void 0!==a?a:buffer_VertexBuffer.UVKind,this.options.uvsOut=null!==(n=this.options.uvsOut)&&void 0!==n?n:buffer_VertexBuffer.UVKind,this.options.layout=null!==(o=this.options.layout)&&void 0!==o?o:TexturePacker.LAYOUT_STRIP,this.options.layout===TexturePacker.LAYOUT_COLNUM&&(this.options.colnum=null!==(l=this.options.colnum)&&void 0!==l?l:8),this.options.updateInputMeshes=null===(h=this.options.updateInputMeshes)||void 0===h||h,this.options.disposeSources=null===(c=this.options.disposeSources)||void 0===c||c,this._expecting=0,this.options.fillBlanks=null===(u=this.options.fillBlanks)||void 0===u||u,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(d=this.options.customFillColor)&&void 0!==d?d:"black"),this.options.frameSize=null!==(_=this.options.frameSize)&&void 0!==_?_:256,this.options.paddingRatio=null!==(p=this.options.paddingRatio)&&void 0!==p?p:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=null!==(f=this.options.paddingMode)&&void 0!==f?f:TexturePacker.SUBUV_WRAP,this.options.paddingMode===TexturePacker.SUBUV_COLOR&&(this.options.paddingColor=null!==(m=this.options.paddingColor)&&void 0!==m?m:new math_color_Color4(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){let t=this._calculateSize(),i=new math_vector_Vector2(1,1).divide(t),r=0,s=this._expecting,a=this.meshes.length,n=Object.keys(this.sets);for(let e=0;e<n.length;e++){let i=n[e],r=new DynamicTexture(this.name+".TexturePack."+i+"Set",{width:t.x,height:t.y},this.scene,!0,texture_Texture.TRILINEAR_SAMPLINGMODE,engine_Engine.TEXTUREFORMAT_RGBA),s=r.getContext();s.fillStyle="rgba(0,0,0,0)",s.fillRect(0,0,t.x,t.y),r.update(!1),this.sets[i]=r}let o=this.options.frameSize||256,l=this._paddingValue,h=o+2*l,done=()=>{this._calculateMeshUVFrames(o,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i<a;i++){let a=this.meshes[i],c=a.material;for(let a=0;a<n.length;a++){let u=new DynamicTexture("temp",h,this.scene,!0),d=u.getContext(),_=this._getFrameOffset(i),updateDt=()=>{r++,u.update(!1);let i=d.getImageData(0,0,h,h),a=this.sets[p],n=a.getContext();if(n.putImageData(i,t.x*_.x,t.y*_.y),u.dispose(),a.update(!1),r==s){done(),e();return}},p=n[a]||"_blank";if(c&&null!==c[p]){let e=c[p],t=new Image;e instanceof DynamicTexture?t.src=e.getContext().canvas.toDataURL("image/png"):t.src=e.url,tools_Tools.SetCorsBehavior(t.src,t),t.onload=()=>{d.fillStyle="rgba(0,0,0,0)",d.fillRect(0,0,h,h),u.update(!1),d.setTransform(1,0,0,-1,0,0);let 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++)d.drawImage(t,0,0,t.width,t.height,l+o*e[i],l+o*e[i+1]-h,o,o);break;case 1:for(let e=0;e<l;e++)d.drawImage(t,0,0,t.width,t.height,e+0*o,l-h,o,o),d.drawImage(t,0,0,t.width,t.height,2*l-e,l-h,o,o),d.drawImage(t,0,0,t.width,t.height,l,e-h,o,o),d.drawImage(t,0,0,t.width,t.height,l,2*l-e-h,o,o);d.drawImage(t,0,0,t.width,t.height,l+0*o,l+0*o-h,o,o);break;case 2:d.fillStyle=(this.options.paddingColor||math_color_Color3.Black()).toHexString(),d.fillRect(0,0,h,-h),d.clearRect(l,l,o,o),d.drawImage(t,0,0,t.width,t.height,l+0*o,l+0*o-h,o,o)}d.setTransform(1,0,0,1,0,0),updateDt()}}else d.fillStyle="rgba(0,0,0,0)",this.options.fillBlanks&&(d.fillStyle=this.options.customFillColor),d.fillRect(0,0,h,h),updateDt()}}}_calculateSize(){let e=this.meshes.length||0,t=this.options.frameSize||0,i=this._paddingValue||0;switch(this.options.layout){case 0:return new math_vector_Vector2(t*e+2*i*e,t+2*i);case 1:{let r=Math.max(2,Math.ceil(Math.sqrt(e))),s=t*r+2*i*r;return new math_vector_Vector2(s,s)}case 2:{let r=this.options.colnum||1,s=Math.max(1,Math.ceil(e/r));return new math_vector_Vector2(t*r+2*i*r,t*s+2*i*s)}}return math_vector_Vector2.Zero()}_calculateMeshUVFrames(e,t,i,r,s){let a=this.meshes.length;for(let n=0;n<a;n++){let a=this.meshes[n],o=new math_vector_Vector2(e/i.x,e/i.y),l=r.clone().scale(t),h=this._getFrameOffset(n),c=h.add(l),u=new TexturePackerFrame(n,o,c);this.frames.push(u),s&&(this._updateMeshUV(a,n),this._updateTextureReferences(a))}}_getFrameOffset(e){let t,i,r;let s=this.meshes.length;switch(this.options.layout){case 0:return new math_vector_Vector2(e*(t=1/s),0);case 1:{let a=Math.max(2,Math.ceil(Math.sqrt(s)));return i=Math.floor(e/a),new math_vector_Vector2((r=e-i*a)*(t=1/a),i*t)}case 2:{let a=this.options.colnum||1,n=Math.max(1,Math.ceil(s/a));return r=Math.floor(e/n),i=e-r*n,t=new math_vector_Vector2(1/a,1/n),new math_vector_Vector2(r*t.x,i*t.y)}}return math_vector_Vector2.Zero()}_updateMeshUV(e,t){let i=this.frames[t],r=e.getVerticesData(this.options.uvsIn||buffer_VertexBuffer.UVKind),s=[],a=0;r.length&&(a=r.length||0);for(let e=0;e<a;e+=2)s.push(r[e]*i.scale.x+i.offset.x,r[e+1]*i.scale.y+i.offset.y);e.setVerticesData(this.options.uvsOut||buffer_VertexBuffer.UVKind,s)}_updateTextureReferences(e,t=!1){let i=e.material,r=Object.keys(this.sets),_dispose=e=>{e.dispose&&e.dispose()};for(let e=0;e<r.length;e++){let s=r[e];if(t)null!==i[s]&&_dispose(i[s]),i[s]=this.sets[s];else{if(!i)return;null!==i[s]&&(_dispose(i[s]),i[s]=this.sets[s])}}}setMeshToFrame(e,t,i=!1){this._updateMeshUV(e,t),i&&this._updateTextureReferences(e,!0)}processAsync(){return new Promise((e,t)=>{try{if(0===this.meshes.length){e();return}let t=0,doneCheck=i=>{if(t++,this.options.map){for(let e=0;e<this.options.map.length;e++){let t=this.options.map[e],r=i[t];null!==r&&(this.sets[this.options.map[e]]||(this.sets[this.options.map[e]]=!0),this._expecting++)}t===this.meshes.length&&this._createFrames(e)}};for(let i=0;i<this.meshes.length;i++){let r=this.meshes[i],s=r.material;if(!s){if(++t===this.meshes.length)return this._createFrames(e);continue}s.forceCompilationAsync(r).then(()=>{doneCheck(s)})}}catch(e){return t(e)}})}dispose(){let e=Object.keys(this.sets);for(let t=0;t<e.length;t++){let i=e[t];this.sets[i].dispose()}}download(e="png",t=1){setTimeout(()=>{let i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;s<r.length;s++){let a=r[s],n=this.sets[a];i.sets[a]=n.getContext().canvas.toDataURL("image/"+e,t)}for(let e=0;e<s.length;e++){let t=s[e];i.options[t]=this.options[t]}for(let e=0;e<this.frames.length;e++){let t=this.frames[e];i.frames.push(t.scale.x,t.scale.y,t.offset.x,t.offset.y)}}catch(e){logger_Logger.Warn("Unable to download: "+e);return}let a="data:text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(i,null,4)),n=document.createElement("a");n.setAttribute("href",a),n.setAttribute("download",this.name+"_texurePackage.json"),document.body.appendChild(n),n.click(),n.remove()},0)}updateFromJSON(e){try{let t=JSON.parse(e);this.name=t.name;let i=Object.keys(t.options);for(let e=0;e<i.length;e++)this.options[i[e]]=t.options[i[e]];for(let e=0;e<t.frames.length;e+=4){let i=new TexturePackerFrame(e/4,new math_vector_Vector2(t.frames[e],t.frames[e+1]),new math_vector_Vector2(t.frames[e+2],t.frames[e+3]));this.frames.push(i)}let r=Object.keys(t.sets);for(let e=0;e<r.length;e++){let i=new texture_Texture(t.sets[r[e]],this.scene,!1,!1);this.sets[r[e]]=i}}catch(e){logger_Logger.Warn("Unable to update from JSON: "+e)}}};TexturePacker.LAYOUT_STRIP=0,TexturePacker.LAYOUT_POWER2=1,TexturePacker.LAYOUT_COLNUM=2,TexturePacker.SUBUV_WRAP=0,TexturePacker.SUBUV_EXTEND=1,TexturePacker.SUBUV_COLOR=2;let a2=`uniform float brightness;uniform float persistence;uniform float timeScale;varying vec2 vUV;vec2 hash22(vec2 p) +{p=p*mat2(127.1,311.7,269.5,183.3);p=-1.0+2.0*fract(sin(p)*43758.5453123);return sin(p*6.283+timeScale);} +float interpolationNoise(vec2 p) +{vec2 pi=floor(p);vec2 pf=p-pi;vec2 w=pf*pf*(3.-2.*pf);float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));float xm1=mix(f00,f10,w.x);float xm2=mix(f01,f11,w.x);float ym=mix(xm1,xm2,w.y); +return ym;} +float perlinNoise2D(float x,float y) +{float sum=0.0;float frequency=0.0;float amplitude=0.0;for(int i=0; i<OCTAVES; i++) +{frequency=pow(2.0,float(i));amplitude=pow(persistence,float(i));sum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;} +return sum;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float x=abs(vUV.x);float y=abs(vUV.y);float noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);gl_FragColor=vec4(noise,noise,noise,1.0);} +`;ShaderStore.ShadersStore.noisePixelShader=a2;let NoiseProceduralTexture=class NoiseProceduralTexture extends proceduralTexture_ProceduralTexture{constructor(e,t=256,i=engineStore_EngineStore.LastCreatedScene,r,s){super(e,t,"noise",i,r,s),this.time=0,this.brightness=.2,this.octaves=3,this.persistence=.8,this.animationSpeedFactor=1,this.autoClear=!1,this._updateShaderUniforms()}_updateShaderUniforms(){let e=this.getScene();e&&(this.time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this.time))}_getDefines(){return"#define OCTAVES "+(0|this.octaves)}render(e){this._updateShaderUniforms(),super.render(e)}serialize(){let e={};return e.customType="BABYLON.NoiseProceduralTexture",e.brightness=this.brightness,e.octaves=this.octaves,e.persistence=this.persistence,e.animationSpeedFactor=this.animationSpeedFactor,e.size=this.getSize().width,e.generateMipMaps=this._generateMipMaps,e.time=this.time,e}clone(){let e=this.getSize(),t=new NoiseProceduralTexture(this.name,e.width,this.getScene(),this._fallbackTexture?this._fallbackTexture:void 0,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t.brightness=this.brightness,t.octaves=this.octaves,t.persistence=this.persistence,t.animationSpeedFactor=this.animationSpeedFactor,t.time=this.time,t}static Parse(e,t){var i;let r=new NoiseProceduralTexture(e.name,e.size,t,void 0,e.generateMipMaps);return r.brightness=e.brightness,r.octaves=e.octaves,r.persistence=e.persistence,r.animationSpeedFactor=e.animationSpeedFactor,r.time=null!==(i=e.time)&&void 0!==i?i:0,r}};h["BABYLON.NoiseProceduralTexture"]=NoiseProceduralTexture;let NodeMaterialConnectionPointCustomObject=class NodeMaterialConnectionPointCustomObject extends NodeMaterialConnectionPoint{constructor(e,t,i,r,s){super(e,t,i),this._blockType=r,this._blockName=s,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof NodeMaterialConnectionPointCustomObject&&e._blockName===this._blockName?ep.Compatible:ep.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}};let BonesBlock=class BonesBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Vertex),this.registerInput("matricesIndices",ed.Vector4),this.registerInput("matricesWeights",ed.Vector4),this.registerInput("matricesIndicesExtra",ed.Vector4,!0),this.registerInput("matricesWeightsExtra",ed.Vector4,!0),this.registerInput("world",ed.Matrix),this.registerOutput("output",ed.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesIndices"===e.name&&t(e));i||(i=new InputBlock("matricesIndices")).setAsAttribute("matricesIndices"),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesWeights"===e.name&&t(e));i||(i=new InputBlock("matricesWeights")).setAsAttribute("matricesWeights"),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(ev.World),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){MaterialHelper.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&MaterialHelper.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");let t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});let i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});let r=this._outputs[0],s=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 +`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName} * ${i}; +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName}; +`,e.compilationString+=`#endif +`,this}};h["BABYLON.BonesBlock"]=BonesBlock;let InstancesBlock=class InstancesBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Vertex),this.registerInput("world0",ed.Vector4),this.registerInput("world1",ed.Vector4),this.registerInput("world2",ed.Vector4),this.registerInput("world3",ed.Vector4),this.registerInput("world",ed.Matrix,!0),this.registerOutput("output",ed.Matrix),this.registerOutput("instanceID",ed.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=()=>!0){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world0"===e.name&&t(e));i||(i=new InputBlock("world0")).setAsAttribute("world0"),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world1"===e.name&&t(e));i||(i=new InputBlock("world1")).setAsAttribute("world1"),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world2"===e.name&&t(e));i||(i=new InputBlock("world2")).setAsAttribute("world2"),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world3"===e.name&&t(e));i||(i=new InputBlock("world3")).setAsAttribute("world3"),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world"===e.name&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(ev.World),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,s){let a=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),a=!0),s&&!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)!==i.THIN_INSTANCES&&(i.setValue("THIN_INSTANCES",!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)),a=!0),a&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);let t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);let i=this._outputs[0],r=this._outputs[1],s=this.world0,a=this.world1,n=this.world2,o=this.world3;return e.compilationString+=`#ifdef INSTANCES +`,e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${a.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}); +`,e.compilationString+=`#ifdef THIN_INSTANCES +`,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName}; +`,e.compilationString+=`#endif +`,t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(r,e)+` = float(gl_InstanceID); +`:e.compilationString+=this._declareOutput(r,e)+` = 0.0; +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName}; +`,e.compilationString+=this._declareOutput(r,e)+` = 0.0; +`,e.compilationString+=`#endif +`,this}};h["BABYLON.InstancesBlock"]=InstancesBlock;let MorphTargetsBlock=class MorphTargetsBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Vertex),this.registerInput("position",ed.Vector3),this.registerInput("normal",ed.Vector3),this.registerInput("tangent",ed.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(ed.Color4|ed.Vector4|ed.Vector3),this.registerInput("uv",ed.Vector2),this.registerOutput("positionOutput",ed.Vector3),this.registerOutput("normalOutput",ed.Vector3),this.registerOutput("tangentOutput",ed.Vector4),this.registerOutput("uvOutput",ed.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new InputBlock("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new InputBlock("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&t(e));i||(i=new InputBlock("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute("uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){let t=e.morphTargetManager;(null==t?void 0:t.isUsingTextureForTargets)&&t.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&MaterialHelper.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(MaterialHelper.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){let s=this.position,a=this.normal,n=this.tangent,o=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=r.NUM_MORPH_INFLUENCERS,_=i.morphTargetManager,p=_&&_.supportsNormals&&r.NORMAL,f=_&&_.supportsTangents&&r.TANGENT,m=_&&_.supportsUVs&&r.UV1,g="";(null==_?void 0:_.isUsingTextureForTargets)&&d>0&&(g+=`float vertexID; +`);for(let e=0;e<d;e++)g+=`#ifdef MORPHTARGETS +`,(null==_?void 0:_.isUsingTextureForTargets)?g+=`vertexID = float(gl_VertexID) * morphTargetTextureInfo.x; +${l.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID) - ${s.associatedVariableName}) * morphTargetInfluences[${e}]; +vertexID += 1.0; +`:g+=`${l.associatedVariableName} += (position${e} - ${s.associatedVariableName}) * morphTargetInfluences[${e}]; +`,p&&(g+=`#ifdef MORPHTARGETS_NORMAL +`,(null==_?void 0:_.isUsingTextureForTargets)?g+=`${h.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID) - ${a.associatedVariableName}) * morphTargetInfluences[${e}]; +vertexID += 1.0; +`:g+=`${h.associatedVariableName} += (normal${e} - ${a.associatedVariableName}) * morphTargetInfluences[${e}]; +`,g+=`#endif +`),m&&(g+=`#ifdef MORPHTARGETS_UV +`,(null==_?void 0:_.isUsingTextureForTargets)?g+=`${u.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID).xy - ${o.associatedVariableName}) * morphTargetInfluences[${e}]; +vertexID += 1.0; +`:g+=`${u.associatedVariableName}.xy += (uv_${e} - ${o.associatedVariableName}.xy) * morphTargetInfluences[${e}]; +`,g+=`#endif +`),f&&(g+=`#ifdef MORPHTARGETS_TANGENT +`,(null==_?void 0:_.isUsingTextureForTargets)?g+=`${c.associatedVariableName}.xyz += (readVector3FromRawSampler(${e}, vertexID) - ${n.associatedVariableName}.xyz) * morphTargetInfluences[${e}]; +`:g+=`${c.associatedVariableName}.xyz += (tangent${e} - ${n.associatedVariableName}.xyz) * morphTargetInfluences[${e}]; +`,n.type===ed.Vector4?g+=`${c.associatedVariableName}.w = ${n.associatedVariableName}.w; +`:g+=`${c.associatedVariableName}.w = 1.; +`,g+=`#endif +`),g+=`#endif +`;if(e.compilationString=e.compilationString.replace(this._repeatableContentAnchor,g),d>0)for(let t=0;t<d;t++)e.attributes.push(buffer_VertexBuffer.PositionKind+t),p&&e.attributes.push(buffer_VertexBuffer.NormalKind+t),f&&e.attributes.push(buffer_VertexBuffer.TangentKind+t),m&&e.attributes.push(buffer_VertexBuffer.UVKind+"_"+t)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);let t=this.position,i=this.normal,r=this.tangent,s=this.uv,a=this.positionOutput,n=this.normalOutput,o=this.tangentOutput,l=this.uvOutput,h=`//${this.name}`;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",h),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",h,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=`${this._declareOutput(a,e)} = ${t.associatedVariableName}; +`,e.compilationString+=`#ifdef NORMAL +`,e.compilationString+=`${this._declareOutput(n,e)} = ${i.associatedVariableName}; +`,e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(n,e)} = vec3(0., 0., 0.); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef TANGENT +`,e.compilationString+=`${this._declareOutput(o,e)} = ${r.associatedVariableName}; +`,e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(o,e)} = vec4(0., 0., 0., 0.); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef UV1 +`,e.compilationString+=`${this._declareOutput(l,e)} = ${s.associatedVariableName}; +`,e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(l,e)} = vec2(0., 0.); +`,e.compilationString+=`#endif +`,this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this}};h["BABYLON.MorphTargetsBlock"]=MorphTargetsBlock;let LightInformationBlock=class LightInformationBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Vertex),this.registerInput("worldPosition",ed.Vector4,!1,e_.Vertex),this.registerOutput("direction",ed.Vector3),this.registerOutput("color",ed.Color3),this.registerOutput("intensity",ed.Float),this.registerOutput("shadowBias",ed.Float),this.registerOutput("shadowNormalBias",ed.Float),this.registerOutput("shadowDepthScale",ed.Float),this.registerOutput("shadowDepthRange",ed.Vector2)}getClassName(){return"LightInformationBlock"}get worldPosition(){return this._inputs[0]}get direction(){return this._outputs[0]}get color(){return this._outputs[1]}get intensity(){return this._outputs[2]}get shadowBias(){return this._outputs[3]}get shadowNormalBias(){return this._outputs[4]}get shadowDepthScale(){return this._outputs[5]}get shadowDepthRange(){return this._outputs[6]}bind(e,t,i){if(!i)return;this.light&&this.light.isDisposed()&&(this.light=null);let r=this.light,s=t.getScene();if(!r&&s.lights.length&&(r=this.light=s.lights[0],this._forcePrepareDefines=!0),!r||!r.isEnabled){e.setFloat3(this._lightDataUniformName,0,0,0),e.setFloat4(this._lightColorUniformName,0,0,0,0);return}r.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,r.diffuse,r.intensity);let a=r.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(a?e.setFloat3(this._lightShadowUniformName,a.bias,a.normalBias,a.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange){if(a&&s.activeCamera){let t=r;e.setFloat2(this._lightShadowExtraUniformName,t.getDepthMinZ(s.activeCamera),t.getDepthMinZ(s.activeCamera)+t.getDepthMaxZ(s.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}}prepareDefines(e,t,i){if(!i._areLightsDirty&&!this._forcePrepareDefines)return;this._forcePrepareDefines=!1;let r=this.light;i.setValue(this._lightTypeDefineName,!!r&&r instanceof PointLight,!0)}_buildBlock(e){super._buildBlock(e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);let t=this.direction,i=this.color,r=this.intensity,s=this.shadowBias,a=this.shadowNormalBias,n=this.shadowDepthScale,o=this.shadowDepthRange;return this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightShadowUniformName=e._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=e._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE"),e._emitUniformFromString(this._lightDataUniformName,"vec3"),e._emitUniformFromString(this._lightColorUniformName,"vec4"),e.compilationString+=`#ifdef ${this._lightTypeDefineName} +`,e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName}); +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(t,e)+` = ${this._lightDataUniformName}; +`,e.compilationString+=`#endif +`,e.compilationString+=this._declareOutput(i,e)+` = ${this._lightColorUniformName}.rgb; +`,e.compilationString+=this._declareOutput(r,e)+` = ${this._lightColorUniformName}.a; +`,(s.hasEndpoints||a.hasEndpoints||n.hasEndpoints)&&(e._emitUniformFromString(this._lightShadowUniformName,"vec3"),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${this._lightShadowUniformName}.x; +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${this._lightShadowUniformName}.y; +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${this._lightShadowUniformName}.z; +`)),o.hasEndpoints&&(e._emitUniformFromString(this._lightShadowExtraUniformName,"vec2"),e.compilationString+=this._declareOutput(o,e)+` = ${this._lightShadowUniformName}; +`),this}serialize(){let e=super.serialize();return 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))}};h["BABYLON.LightInformationBlock"]=LightInformationBlock;let ImageProcessingBlock=class ImageProcessingBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.convertInputToLinearSpace=!0,this.registerInput("color",ed.AutoDetect),this.registerOutput("output",ed.Color4),this.registerOutput("rgb",ed.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Color4|ed.Vector3|ed.Vector4)}getClassName(){return"ImageProcessingBlock"}get color(){return this._inputs[0]}get output(){return this._outputs[0]}get rgb(){return this._outputs[1]}initialize(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")}isReady(e,t,i){return!i._areImageProcessingDirty||!t.imageProcessingConfiguration||!!t.imageProcessingConfiguration.isReady()}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_buildBlock(e){var t;super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity");let i=this.color,r=this._outputs[0],s=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("imageProcessingDeclaration",s),e._emitFunctionFromInclude("imageProcessingFunctions",s),(null===(t=i.connectedPoint)||void 0===t?void 0:t.isConnected)&&(i.connectedPoint.type===ed.Color4||i.connectedPoint.type===ed.Vector4?e.compilationString+=`${this._declareOutput(r,e)} = ${i.associatedVariableName}; +`:e.compilationString+=`${this._declareOutput(r,e)} = vec4(${i.associatedVariableName}, 1.0); +`,e.compilationString+=`#ifdef IMAGEPROCESSINGPOSTPROCESS +`,this.convertInputToLinearSpace&&(e.compilationString+=`${r.associatedVariableName}.rgb = toLinearSpace(${i.associatedVariableName}.rgb); +`),e.compilationString+=`#else +`,e.compilationString+=`#ifdef IMAGEPROCESSING +`,this.convertInputToLinearSpace&&(e.compilationString+=`${r.associatedVariableName}.rgb = toLinearSpace(${i.associatedVariableName}.rgb); +`),e.compilationString+=`${r.associatedVariableName} = applyImageProcessing(${r.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#endif +`,this.rgb.hasEndpoints&&(e.compilationString+=this._declareOutput(this.rgb,e)+` = ${this.output.associatedVariableName}.xyz; +`)),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace}; +`}serialize(){let e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.convertInputToLinearSpace=null===(r=e.convertInputToLinearSpace)||void 0===r||r}};__decorate([editableInPropertyPage("Convert input to linear space",em.Boolean,"ADVANCED")],ImageProcessingBlock.prototype,"convertInputToLinearSpace",void 0),h["BABYLON.ImageProcessingBlock"]=ImageProcessingBlock;let TBNBlock=class TBNBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment,!0),this.registerInput("normal",ed.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(ed.Color4|ed.Vector4|ed.Vector3),this.registerInput("tangent",ed.Vector4,!1),this.registerInput("world",ed.Matrix,!1),this.registerOutput("TBN",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("TBN",this,ef.Output,TBNBlock,"TBNBlock")),this.registerOutput("row0",ed.Vector3,e_.Fragment),this.registerOutput("row1",ed.Vector3,e_.Fragment),this.registerOutput("row2",ed.Vector3,e_.Fragment)}getClassName(){return"TBNBlock"}initialize(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")}get normal(){return this._inputs[0]}get tangent(){return this._inputs[1]}get world(){return this._inputs[2]}get TBN(){return this._outputs[0]}get row0(){return this._outputs[1]}get row1(){return this._outputs[2]}get row2(){return this._outputs[3]}get target(){return e_.Fragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.isSystemValue&&e.systemValue===ev.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(ev.World),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new InputBlock("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&e.type===ed.Vector4&&t(e));i||(i=new InputBlock("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var r,s,a,n;let o=this.normal,l=this.tangent,h=o.isConnected;(null===(r=o.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(s=o.connectInputBlock)||void 0===s?void 0:s.name)&&(h=!1);let c=l.isConnected;(null===(a=l.connectInputBlock)||void 0===a?void 0:a.isAttribute)&&!e.isVerticesDataPresent(null===(n=l.connectInputBlock)||void 0===n?void 0:n.name)&&(c=!1);let u=h&&c;i.setValue("TBNBLOCK",u,!0)}_buildBlock(e){super._buildBlock(e);let t=this.normal,i=this.tangent,r=this.world,s=this.TBN,a=this.row0,n=this.row1,o=this.row2;return e.target===e_.Fragment&&(e.compilationString+=` + // ${this.name} + vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz; + vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz); + vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; + mat3 ${s.associatedVariableName} = mat3(${r.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); + `,a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]); +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]); +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]); +`),e.sharedData.blocksWithDefines.push(this)),this}};h["BABYLON.TBNBlock"]=TBNBlock;let PerturbNormalBlock=class PerturbNormalBlock extends NodeMaterialBlock{constructor(e){super(e,e_.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",ed.Vector4,!1),this.registerInput("worldNormal",ed.Vector4,!1),this.registerInput("worldTangent",ed.Vector4,!0),this.registerInput("uv",ed.Vector2,!1),this.registerInput("normalMapColor",ed.Color3,!1),this.registerInput("strength",ed.Float,!1),this.registerInput("viewDirection",ed.Vector3,!0),this.registerInput("parallaxScale",ed.Float,!0),this.registerInput("parallaxHeight",ed.Float,!0),this.registerInput("TBN",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("TBN",this,ef.Input,TBNBlock,"TBNBlock")),this.registerInput("world",ed.Matrix,!0),this.registerOutput("output",ed.Vector4),this.registerOutput("uvOffset",ed.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){let r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute(),i.output.connectTo(this.uv)}if(!this.strength.isConnected){let e=new InputBlock("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`,i=this.uv,r=this.worldPosition,s=this.worldNormal,a=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 n=null;this.normalMapColor.connectedPoint&&(n=this.normalMapColor.connectedPoint._ownerBlock.samplerName);let o=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&n||!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?` +#if !defined(NORMALXYSCALE) +1.0/ +#endif +${e._emitFloat(this.strength.connectInputBlock.value)}`:` +#if !defined(NORMALXYSCALE) +1.0/ +#endif +${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let c={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},u=this.TBN;u.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${u.associatedVariableName}; + #endif + `:a.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnTangent = normalize(${a.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +`,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),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<samplerFragmentDeclaration>\(_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\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_"}]});let d=o&&n?`texture2D(${n}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${d}`},{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, ${d}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o&&this.useParallaxOcclusion?n:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${o?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:r.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:o?this.viewDirection.associatedVariableName:"vec3(0.)"},c]}),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX}; +`+`${this._codeVariableName}.invertY = ${this.invertY}; +${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion}; +${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap}; +`}serialize(){let 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}};__decorate([editableInPropertyPage("Invert X axis",em.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"invertX",void 0),__decorate([editableInPropertyPage("Invert Y axis",em.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"invertY",void 0),__decorate([editableInPropertyPage("Use parallax occlusion",em.Boolean)],PerturbNormalBlock.prototype,"useParallaxOcclusion",void 0),__decorate([editableInPropertyPage("Object Space Mode",em.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"useObjectSpaceNormalMap",void 0),h["BABYLON.PerturbNormalBlock"]=PerturbNormalBlock;let DiscardBlock=class DiscardBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment,!0),this.registerInput("value",ed.Float,!0),this.registerInput("cutoff",ed.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard; +`,this}};h["BABYLON.DiscardBlock"]=DiscardBlock;let FrontFacingBlock=class FrontFacingBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerOutput("output",ed.Float,e_.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===e_.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = gl_FrontFacing ? 1.0 : 0.0; +`,this}};h["BABYLON.FrontFacingBlock"]=FrontFacingBlock;let DerivativeBlock=class DerivativeBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerInput("input",ed.AutoDetect,!1),this.registerOutput("dx",ed.BasedOnInput),this.registerOutput("dy",ed.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);let 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}); +`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName}); +`),this}};h["BABYLON.DerivativeBlock"]=DerivativeBlock;let FragCoordBlock=class FragCoordBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerOutput("xy",ed.Vector2,e_.Fragment),this.registerOutput("xyz",ed.Vector3,e_.Fragment),this.registerOutput("xyzw",ed.Vector4,e_.Fragment),this.registerOutput("x",ed.Float,e_.Fragment),this.registerOutput("y",ed.Float,e_.Fragment),this.registerOutput("z",ed.Float,e_.Fragment),this.registerOutput("w",ed.Float,e_.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(let i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name}; +`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===e_.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}};h["BABYLON.FragCoordBlock"]=FragCoordBlock;let ScreenSizeBlock=class ScreenSizeBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerOutput("xy",ed.Vector2,e_.Fragment),this.registerOutput("x",ed.Float,e_.Fragment),this.registerOutput("y",ed.Float,e_.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){let t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; +`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===e_.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}};h["BABYLON.ScreenSizeBlock"]=ScreenSizeBlock;let ScreenSpaceBlock=class ScreenSpaceBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerInput("vector",ed.AutoDetect),this.registerInput("worldViewProjection",ed.Matrix),this.registerOutput("output",ed.Vector2),this.registerOutput("x",ed.Float),this.registerOutput("y",ed.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.WorldViewProjection&&t(e));i||(i=new InputBlock("worldViewProjection")).setAsSystemValue(ev.WorldViewProjection),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;let r=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case ed.Vector3:e.compilationString+=`vec4 ${s} = ${r} * vec4(${t.associatedVariableName}, 1.0); +`;break;case ed.Vector4:e.compilationString+=`vec4 ${s} = ${r} * ${t.associatedVariableName}; +`}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; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y; +`),this}};h["BABYLON.ScreenSpaceBlock"]=ScreenSpaceBlock;let TwirlBlock=class TwirlBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerInput("input",ed.Vector2),this.registerInput("strength",ed.Float),this.registerInput("center",ed.Vector2),this.registerInput("offset",ed.Vector2),this.registerOutput("output",ed.Vector2),this.registerOutput("x",ed.Float),this.registerOutput("y",ed.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){let e=new InputBlock("center");e.value=new math_vector_Vector2(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){let e=new InputBlock("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){let e=new InputBlock("offset");e.value=new math_vector_Vector2(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);let t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),a=e._getFreeVariableName("result");return e.compilationString+=` + vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; + float ${i} = ${this.strength.associatedVariableName} * length(${t}); + float ${r} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; + float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; + vec2 ${a} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); + `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${a}; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${a}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${a}.y; +`),this}};h["BABYLON.TwirlBlock"]=TwirlBlock;let HeightToNormalBlock=class HeightToNormalBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",ed.Float),this.registerInput("worldPosition",ed.Vector3),this.registerInput("worldNormal",ed.Vector3),this.registerInput("worldTangent",ed.AutoDetect,!0),this.registerOutput("output",ed.Vector4),this.registerOutput("xyz",ed.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.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);let t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`);let i=this.generateInWorldSpace?"":` + vec3 biTangent = cross(normal, tangent); + mat3 TBN = mat3(tangent, biTangent, normal); + `,r=this.generateInWorldSpace?"":` + result = TBN * result; + result = result * vec3(0.5) + vec3(0.5); + `,s=` + vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { + ${i} + ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""} + ${this.automaticNormalizationNormal?"normal = normalize(normal);":""} + vec3 worlddX = dFdx(position); + vec3 worlddY = dFdy(position); + vec3 crossX = cross(normal, worlddX); + vec3 crossY = cross(normal, worlddY); + float d = abs(dot(crossY, worlddX)); + vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); + inToNormal.y *= -1.0; + vec3 result = normalize((d * normal) - inToNormal); + ${r} + return vec4(result, 0.); + }`;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}); +`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; +`),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace}; +${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal}; +${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent}; +`}serialize(){let 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}};__decorate([editableInPropertyPage("Generate in world space instead of tangent space",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"generateInWorldSpace",void 0),__decorate([editableInPropertyPage("Force normalization for the worldNormal input",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"automaticNormalizationNormal",void 0),__decorate([editableInPropertyPage("Force normalization for the worldTangent input",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"automaticNormalizationTangent",void 0),h["BABYLON.HeightToNormalBlock"]=HeightToNormalBlock;let FragDepthBlock=class FragDepthBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment,!0),this.registerInput("depth",ed.Float,!0),this.registerInput("worldPos",ed.Vector4,!0),this.registerInput("viewProjection",ed.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName}; +`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=` + vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; + float v = p.z / p.w; + #ifndef IS_NDC_HALF_ZRANGE + v = v * 0.5 + 0.5; + #endif + gl_FragDepth = v; + + `:console.warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}};h["BABYLON.FragDepthBlock"]=FragDepthBlock;let ShadowMapBlock=class ShadowMapBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerInput("worldPosition",ed.Vector4,!1),this.registerInput("viewProjection",ed.Matrix,!1),this.registerInput("worldNormal",ed.AutoDetect,!0),this.registerOutput("depth",ed.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.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);let 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}; +`,e.compilationString+=`vec3 vPositionWSM; +`,e.compilationString+=`float vDepthMetricSM = 0.0; +`,e.compilationString+=`float zSM; +`,this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos; +`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+=` + #if SM_DEPTHTEXTURE == 1 + #ifdef IS_NDC_HALF_ZRANGE + gl_FragDepth = (clipPos.z / clipPos.w); + #else + gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5; + #endif + #endif + `,e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.); +`,this}};h["BABYLON.ShadowMapBlock"]=ShadowMapBlock;let PrePassOutputBlock=class PrePassOutputBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment,!0),this.registerInput("viewDepth",ed.Float,!0),this.registerInput("worldPosition",ed.AutoDetect,!0),this.registerInput("viewNormal",ed.AutoDetect,!0),this.registerInput("reflectivity",ed.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(ed.Vector3|ed.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(ed.Vector3|ed.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(ed.Vector3|ed.Vector4|ed.Color3|ed.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);let t=this.worldPosition,i=this.viewNormal,r=this.viewDepth,s=this.reflectivity;e.sharedData.blocksWithDefines.push(this);let a=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",a),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`#ifdef PREPASS_DEPTH\r +`,r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${r.associatedVariableName}, 0.0, 0.0, 1.0);\r +`:e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_POSITION\r +`,t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===ed.Vector4?t.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_NORMAL\r +`,i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===ed.Vector4?i.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r +`,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${s.associatedVariableName}.rgb, ${s.connectedPoint.type===ed.Vector4?s.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#endif\r +`,this}};h["BABYLON.PrePassOutputBlock"]=PrePassOutputBlock;let FogBlock=class FogBlock extends NodeMaterialBlock{constructor(e){super(e,e_.VertexAndFragment,!1),this.registerInput("worldPosition",ed.Vector4,!1,e_.Vertex),this.registerInput("view",ed.Matrix,!1,e_.Vertex),this.registerInput("input",ed.AutoDetect,!1,e_.Fragment),this.registerInput("fogColor",ed.AutoDetect,!1,e_.Fragment),this.registerOutput("output",ed.Color3,e_.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(ev.View),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.FogColor&&t(e));i||(i=new InputBlock("fogColor",void 0,ed.Color3)).setAsSystemValue(ev.FogColor),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){let r=e.getScene();i.setValue("FOG",t.fogEnabled&&MaterialHelper.GetFogState(e,r))}bind(e,t,i){if(!i)return;let r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===e_.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)"}]});let t=e._getFreeVariableName("fog"),i=this.input,r=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");let s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+=`#ifdef FOG +`,e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters}); +`,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${r.associatedVariableName}.rgb; +`,e.compilationString+=`#else +${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb; +`,e.compilationString+=`#endif +`}else{let 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; +`}return this}};h["BABYLON.FogBlock"]=FogBlock;let LightBlock=class LightBlock extends NodeMaterialBlock{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?e_.Fragment:e_.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?e_.Fragment:e_.Vertex}constructor(e){super(e,e_.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",ed.Vector4,!1,e_.Vertex),this.registerInput("worldNormal",ed.Vector4,!1,e_.Fragment),this.registerInput("cameraPosition",ed.Vector3,!1,e_.Fragment),this.registerInput("glossiness",ed.Float,!0,e_.Fragment),this.registerInput("glossPower",ed.Float,!0,e_.Fragment),this.registerInput("diffuseColor",ed.Color3,!0,e_.Fragment),this.registerInput("specularColor",ed.Color3,!0,e_.Fragment),this.registerInput("view",ed.Matrix,!0),this.registerOutput("diffuseOutput",ed.Color3,e_.Fragment),this.registerOutput("specularOutput",ed.Color3,e_.Fragment),this.registerOutput("shadow",ed.Float,e_.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(ev.CameraPosition),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;let r=e.getScene();if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};MaterialHelper.PrepareDefinesForLight(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else MaterialHelper.PrepareDefinesForLights(r,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s<t.maxSimultaneousLights&&i["LIGHT"+s];s++){let t=e.uniforms.indexOf("vLightData"+s)>=0;MaterialHelper.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}bind(e,t,i){if(!i)return;let r=i.getScene();this.light?MaterialHelper.BindLight(this.light,this._lightId,r,e,!0):MaterialHelper.BindLights(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){let 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));let r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${t.associatedVariableName}; +`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==e_.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);let t=`//${this.name}`,i=this.worldPosition,r=i.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${r}; +`,t),e.compilationString+=`${r} = ${i.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):r="v_"+r+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),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} - ${r}); +`),e.compilationString+=`lightingInfo info; +`,e.compilationString+=`float shadow = 1.; +`,e.compilationString+=`float aggShadow = 0.; +`,e.compilationString+=`float numLights = 0.; +`,e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; +`,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.); +`,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.); +`,e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz; +`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),0===this._lightId&&(e.compilationString+=`aggShadow = aggShadow / numLights; +`);let s=this.diffuseOutput,a=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; +`,a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""}; +`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = aggShadow; +`),this}serialize(){let 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()}};__decorate([editableInPropertyPage("Generate only fragment code",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:LightBlock._OnGenerateOnlyFragmentCodeChanged}})],LightBlock.prototype,"generateOnlyFragmentCode",void 0),h["BABYLON.LightBlock"]=LightBlock;let ImageSourceBlock=class ImageSourceBlock extends NodeMaterialBlock{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:engineStore_EngineStore.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,e_.VertexAndFragment),this.registerOutput("source",ed.Object,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,ef.Output,ImageSourceBlock,"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===e_.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}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let 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&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};h["BABYLON.ImageSourceBlock"]=ImageSourceBlock;let TextureBlock=class TextureBlock extends NodeMaterialBlock{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;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}static _IsPrePassTextureBlock(e){return(null==e?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return TextureBlock._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!TextureBlock._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:engineStore_EngineStore.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)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?e_.Fragment:e_.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",ed.AutoDetect,!1,e_.VertexAndFragment),this.registerInput("source",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,ef.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerInput("layer",ed.Float,!0),this.registerInput("lod",ed.Float,!0),this.registerOutput("rgba",ed.Color4,e_.Neutral),this.registerOutput("rgb",ed.Color3,e_.Neutral),this.registerOutput("r",ed.Float,e_.Neutral),this.registerOutput("g",ed.Float,e_.Neutral),this.registerOutput("b",ed.Float,e_.Neutral),this.registerOutput("a",ed.Float,e_.Neutral),this.registerOutput("level",ed.Float,e_.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector2|ed.Vector3|ed.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 e_.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return e_.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===e_.Fragment)return e_.Fragment;if(e.target===e_.Vertex)break;if(e.target===e_.Neutral||e.target===e_.VertexAndFragment){let t=e.ownerBlock;if(t.target===e_.Fragment)return e_.Fragment;for(let i of(e=null,t.inputs))if(i.connectedPoint){e=i.connectedPoint;break}}}return e_.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){if(e.mode===eb.PostProcess){let i=e.getBlockByPredicate(e=>"uv"===e.name&&t(e));i&&i.connectTo(this)}else{let i=e.mode===eb.Particle?"particle_uv":"uv",r=e.getInputBlockByPredicate(e=>e.isAttribute&&e.name===i&&t(e));r||(r=new InputBlock("uv")).setAsAttribute(i),r.output.connectTo(this.uv)}}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix){this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0));return}let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),void 0==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==e_.Fragment}_injectVertexCode(e){let 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} +`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0)); +`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) +`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,e.compilationString+=`#endif +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}_getUVW(e){var t,i,r;let s=e,a=null!==(r=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==r&&r;if(a){let t=this.layer.isConnected?this.layer.associatedVariableName:"0";s=`vec3(${e}, ${t})`}return s}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){let t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName} +`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix}); +`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) +`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix}); +`,e.compilationString+=`#endif +`}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===e_.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix}); +`;return}this._generateTextureLookup(e)}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} + ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); + #endif + `),e.compilationString+=`#ifdef ${this._gammaDefineName} + ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); + #endif + `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===e_.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s}; +`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,r,s;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===e_.Vertex||this._fragmentOnly||e.target===e_.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===e_.Fragment||this._isMixed&&e.target===e_.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!==e_.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((null===(s=null===(r=this._texture)||void 0===r?void 0:r._texture)||void 0===s?void 0:s.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));let a=`//${this.name}`;for(let t of(e._emitFunctionFromInclude("helperFunctions",a),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; +`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let 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&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};h["BABYLON.TextureBlock"]=TextureBlock;let ReflectionTextureBaseBlock=class ReflectionTextureBaseBlock extends NodeMaterialBlock{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:engineStore_EngineStore.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?e_.Fragment:e_.VertexAndFragment)}constructor(e){super(e,e_.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new InputBlock("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(ev.World),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(ev.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this._getTexture();r&&r.getTextureMatrix&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===r.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===r.coordinatesMode,!0),i.setValue(this._defineCubicName,3===r.coordinatesMode||6===r.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===r.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===r.coordinatesMode,!0),i.setValue(this._definePlanarName,2===r.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===r.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===r.coordinatesMode,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){let r=this._getTexture();i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize&&(e.setVector3(this._reflectionPositionName,r.boundingBoxPosition),e.setVector3(this._reflectionSizeName,r.boundingBoxSize)))}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===e_.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");let i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName}; +`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName} +${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; +#endif +`),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) +${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0))); +#endif +`),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName} +`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; +`,e._samplerDeclaration+=`#else +`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; +`,e._samplerDeclaration+=`#endif +`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,r=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);let s=this._reflectionMatrixName,a=`normalize(${this._directionWName})`,n=`${this._positionUVWName}`,o=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=` + #ifdef ${this._defineMirroredEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${a}); + #endif + + #ifdef ${this._defineEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${a}); + #endif + + #ifdef ${this._defineEquirectangularName} + vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + + #ifdef ${this._defineSphericalName} + vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s}); + #endif + + #ifdef ${this._definePlanarName} + vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + + #ifdef ${this._defineCubicName} + #ifdef ${this._defineLocalCubicName} + vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${o}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); + #else + vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + #endif + + #ifdef ${this._defineProjectionName} + vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s}); + #endif + + #ifdef ${this._defineSkyboxName} + vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${n}, ${s}); + #endif + + #ifdef ${this._defineExplicitName} + vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); + #endif +`;return r||(h+=`#ifdef ${this._defineOppositeZ} + ${this._reflectionVectorName}.z *= -1.0; + #endif +`),i||(h+=` + #ifdef ${this._define3DName} + vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName}; + #else + vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy; + #ifdef ${this._defineProjectionName} + ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; + #endif + ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; + #endif +`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i="vec"+(0===t.length?"4":t.length-1),r=`${i} ${this._reflectionColorName}; + #ifdef ${this._define3DName} +`;return e?r+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t}; +`:r+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t}; +`,r+=` + #else +`,e?r+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t}; +`:r+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t}; +`,r+=`#endif +`}writeOutputs(e,t){let i="";if(e.target===e_.Fragment)for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; +`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){let t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"}); +`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null); +`;return e+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`}serialize(){let 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&&!NodeMaterial.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=cubeTexture_CubeTexture.Parse(e.texture,t,i):this.texture=texture_Texture.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}};__decorate([editableInPropertyPage("Generate only fragment code",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:ReflectionTextureBaseBlock._OnGenerateOnlyFragmentCodeChanged}})],ReflectionTextureBaseBlock.prototype,"generateOnlyFragmentCode",void 0),h["BABYLON.ReflectionTextureBaseBlock"]=ReflectionTextureBaseBlock;let ReflectionTextureBlock=class ReflectionTextureBlock extends ReflectionTextureBaseBlock{_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?e_.Fragment:e_.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?e_.Fragment:e_.Vertex}constructor(e){super(e),this.registerInput("position",ed.AutoDetect,!1,e_.Vertex),this.registerInput("worldPosition",ed.Vector4,!1,e_.Vertex),this.registerInput("worldNormal",ed.Vector4,!1,e_.Fragment),this.registerInput("world",ed.Matrix,!1,e_.Vertex),this.registerInput("cameraPosition",ed.Vector3,!1,e_.Fragment),this.registerInput("view",ed.Matrix,!1,e_.Fragment),this.registerOutput("rgb",ed.Color3,e_.Fragment),this.registerOutput("rgba",ed.Color4,e_.Fragment),this.registerOutput("r",ed.Float,e_.Fragment),this.registerOutput("g",ed.Float,e_.Fragment),this.registerOutput("b",ed.Float,e_.Fragment),this.registerOutput("a",ed.Float,e_.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=()=>!0){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(ev.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==e_.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);let t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName}); +`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}};h["BABYLON.ReflectionTextureBlock"]=ReflectionTextureBlock;let SceneDepthBlock=class SceneDepthBlock extends NodeMaterialBlock{constructor(e){super(e,e_.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",ed.AutoDetect,!1,e_.VertexAndFragment),this.registerOutput("depth",ed.Float,e_.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector2|ed.Vector3|ed.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?e_.VertexAndFragment:e_.Fragment}_getTexture(e){let t=e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ);return t.getDepthMap()}bind(e,t){let i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput){let i=t.connectedPoint.ownerBlock;i.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===ed.Vector3?"3":t.type===ed.Vector4?"4":"2"))}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===e_.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); +`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===e_.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.bindableBlocks.indexOf(this)&&e.sharedData.bindableBlocks.push(this),e.target!==e_.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(this._outputs.some(e=>e.isConnectedInFragmentShader)){for(let t of(e._emit2DSampler(this._samplerName),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){let 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}};__decorate([editableInPropertyPage("Use non linear depth",em.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],SceneDepthBlock.prototype,"useNonLinearDepth",void 0),__decorate([editableInPropertyPage("Store Camera space Z",em.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],SceneDepthBlock.prototype,"storeCameraSpaceZ",void 0),__decorate([editableInPropertyPage("Force 32 bits float",em.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>null==e?void 0:e.disableDepthRenderer()}})],SceneDepthBlock.prototype,"force32itsFloat",void 0),h["BABYLON.SceneDepthBlock"]=SceneDepthBlock;let ClipPlanesBlock=class ClipPlanesBlock extends NodeMaterialBlock{constructor(e){super(e,e_.VertexAndFragment,!0),this.registerInput("worldPosition",ed.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 e_.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var r,s,a,n,o,l;let h=e.getScene(),c=null!==(r=t.clipPlane)&&void 0!==r?!!r:!!h.clipPlane,u=null!==(s=t.clipPlane2)&&void 0!==s?!!s:!!h.clipPlane2,d=null!==(a=t.clipPlane3)&&void 0!==a?!!a:!!h.clipPlane3,_=null!==(n=t.clipPlane4)&&void 0!==n?!!n:!!h.clipPlane4,p=null!==(o=t.clipPlane5)&&void 0!==o?!!o:!!h.clipPlane5,f=null!==(l=t.clipPlane6)&&void 0!==l?!!l:!!h.clipPlane6;i.setValue("CLIPPLANE",c,!0),i.setValue("CLIPPLANE2",u,!0),i.setValue("CLIPPLANE3",d,!0),i.setValue("CLIPPLANE4",_,!0),i.setValue("CLIPPLANE5",p,!0),i.setValue("CLIPPLANE6",f,!0)}bind(e,t,i){if(!i)return;let r=i.getScene();bindClipPlane(e,t,r)}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;if(e.target!==e_.Fragment){let i=this.worldPosition;e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),e._emitUniformFromString("vClipPlane6","vec4");return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}};h["BABYLON.ClipPlanesBlock"]=ClipPlanesBlock;let PrePassTextureBlock=class PrePassTextureBlock extends NodeMaterialBlock{get texture(){return null}set texture(e){}constructor(e,t=e_.VertexAndFragment){super(e,t,!1),this.registerOutput("position",ed.Object,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("position",this,ef.Output,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("depth",ed.Object,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("depth",this,ef.Output,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("normal",ed.Object,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("normal",this,ef.Output,ImageSourceBlock,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==e_.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){let i=t.getScene(),r=i.enablePrePassRenderer();if(!r)return;let s=r.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[r.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[r.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[r.getIndex(6)]))}};h["BABYLON.PrePassTextureBlock"]=PrePassTextureBlock;let NodeMaterialTeleportInBlock=class NodeMaterialTeleportInBlock extends NodeMaterialBlock{get endpoints(){return this._endpoints}constructor(e){super(e,e_.Neutral),this._endpoints=[],this.registerInput("input",ed.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some(e=>e.output.isConnectedInFragmentShader)}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){for(let e of(super.dispose(),this._endpoints))this.detachFromEndpoint(e);this._endpoints=[]}};h["BABYLON.NodeMaterialTeleportInBlock"]=NodeMaterialTeleportInBlock;let NodeMaterialTeleportOutBlock=class NodeMaterialTeleportOutBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",ed.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){(this._target&e)==0&&(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName}; +`)}clone(e,t=""){let i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); +`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}};h["BABYLON.NodeMaterialTeleportOutBlock"]=NodeMaterialTeleportOutBlock;let AddBlock=class AddBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(ed.Float),this._inputs[1].acceptedConnectionPointTypes.push(ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName}; +`,this}};h["BABYLON.AddBlock"]=AddBlock;let ScaleBlock=class ScaleBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.AutoDetect),this.registerInput("factor",ed.Float),this.registerOutput("output",ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName}; +`,this}};h["BABYLON.ScaleBlock"]=ScaleBlock;let ClampBlock=class ClampBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",ed.AutoDetect),this.registerOutput("output",ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)}); +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; +`+`${this._codeVariableName}.maximum = ${this.maximum}; +`}serialize(){let 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}};__decorate([editableInPropertyPage("Minimum",em.Float)],ClampBlock.prototype,"minimum",void 0),__decorate([editableInPropertyPage("Maximum",em.Float)],ClampBlock.prototype,"maximum",void 0),h["BABYLON.ClampBlock"]=ClampBlock;let CrossBlock=class CrossBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ed.Vector2),this._inputs[1].excludedConnectionPointTypes.push(ed.Float),this._inputs[1].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz); +`,this}};h["BABYLON.CrossBlock"]=CrossBlock;let CustomBlock=class CustomBlock extends NodeMaterialBlock{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),a=e._getGLType(r.type);t=t.replace(s,a),i=i.replace(s,a)}),this._outputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),a=e._getGLType(r.type);t=t.replace(s,a),i=i.replace(s,a)}),e._emitFunction(i,t,""),this._outputs.forEach(t=>{e.compilationString+=this._declareOutput(t,e)+";\n"}),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach((t,i)=>{var s,a,n;i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=null!==(n=null===(a=null===(s=t.connectedPoint)||void 0===s?void 0:s.ownerBlock)||void 0===a?void 0:a.samplerName)&&void 0!==n?n:t.associatedVariableName:e.compilationString+=t.associatedVariableName,r=!0}),this._outputs.forEach((t,i)=>{(i>0||r)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName}),e.compilationString+=");\n",this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.options = ${JSON.stringify(this._options)}; +`}serialize(){let 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,r;this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=e_[e.target],null===(t=e.inParameters)||void 0===t||t.forEach((e,t)=>{let i=ed[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject(e.name,this,ef.Input,ImageSourceBlock,"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,ed[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===(r=e.inLinkedConnectionTypes)||void 0===r||r.forEach(e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t<this._inputs.length;t++)if(this._inputs[t].name===e)return[this._inputs[t],t];return null}};h["BABYLON.CustomBlock"]=CustomBlock;let DotBlock=class DotBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ed.Float),this._inputs[1].excludedConnectionPointTypes.push(ed.Matrix)}getClassName(){return"DotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = dot(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}};h["BABYLON.DotBlock"]=DotBlock;let NormalizeBlock=class NormalizeBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix)}getClassName(){return"NormalizeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${i.associatedVariableName}); +`,this}};h["BABYLON.NormalizeBlock"]=NormalizeBlock;let ColorMergerBlock=class ColorMergerBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.rSwizzle="r",this.gSwizzle="g",this.bSwizzle="b",this.aSwizzle="a",this.registerInput("rgb ",ed.Color3,!0),this.registerInput("r",ed.Float,!0),this.registerInput("g",ed.Float,!0),this.registerInput("b",ed.Float,!0),this.registerInput("a",ed.Float,!0),this.registerOutput("rgba",ed.Color4),this.registerOutput("rgb",ed.Color3)}getClassName(){return"ColorMergerBlock"}get rgbIn(){return this._inputs[0]}get r(){return this._inputs[1]}get g(){return this._inputs[2]}get b(){return this._inputs[3]}get a(){return this._inputs[4]}get rgba(){return this._outputs[0]}get rgbOut(){return this._outputs[1]}get rgb(){return this.rgbOut}_inputRename(e){return"rgb "===e?"rgbIn":e}_buildSwizzle(e){let t=this.rSwizzle+this.gSwizzle+this.bSwizzle+this.aSwizzle;return"."+t.substr(0,e)}_buildBlock(e){super._buildBlock(e);let t=this.r,i=this.g,r=this.b,s=this.a,a=this.rgbIn,n=this._outputs[0],o=this._outputs[1];return a.isConnected?(n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec4(${a.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${a.associatedVariableName}${this._buildSwizzle(3)}; +`)):(n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; +`)),this}serialize(){let e=super.serialize();return e.rSwizzle=this.rSwizzle,e.gSwizzle=this.gSwizzle,e.bSwizzle=this.bSwizzle,e.aSwizzle=this.aSwizzle,e}_deserialize(e,t,i){var r,s,a,n;super._deserialize(e,t,i),this.rSwizzle=null!==(r=e.rSwizzle)&&void 0!==r?r:"r",this.gSwizzle=null!==(s=e.gSwizzle)&&void 0!==s?s:"g",this.bSwizzle=null!==(a=e.bSwizzle)&&void 0!==a?a:"b",this.aSwizzle=null!==(n=e.aSwizzle)&&void 0!==n?n:"a"}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.rSwizzle = "${this.rSwizzle}"; +${this._codeVariableName}.gSwizzle = "${this.gSwizzle}"; +${this._codeVariableName}.bSwizzle = "${this.bSwizzle}"; +${this._codeVariableName}.aSwizzle = "${this.aSwizzle}"; +`}};h["BABYLON.ColorMergerBlock"]=ColorMergerBlock;let VectorSplitterBlock=class VectorSplitterBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("xyzw",ed.Vector4,!0),this.registerInput("xyz ",ed.Vector3,!0),this.registerInput("xy ",ed.Vector2,!0),this.registerOutput("xyz",ed.Vector3),this.registerOutput("xy",ed.Vector2),this.registerOutput("zw",ed.Vector2),this.registerOutput("x",ed.Float),this.registerOutput("y",ed.Float),this.registerOutput("z",ed.Float),this.registerOutput("w",ed.Float),this.inputsAreExclusive=!0}getClassName(){return"VectorSplitterBlock"}get xyzw(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get xyzOut(){return this._outputs[0]}get xyOut(){return this._outputs[1]}get zw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get w(){return this._outputs[6]}_inputRename(e){switch(e){case"xy ":return"xyIn";case"xyz ":return"xyzIn";default:return e}}_outputRename(e){switch(e){case"xy":return"xyOut";case"xyz":return"xyzOut";default:return e}}_buildBlock(e){super._buildBlock(e);let t=this.xyzw.isConnected?this.xyzw:this.xyzIn.isConnected?this.xyzIn:this.xyIn,i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],a=this._outputs[3],n=this._outputs[4],o=this._outputs[5],l=this._outputs[6];return i.hasEndpoints&&(t===this.xyIn?e.compilationString+=this._declareOutput(i,e)+` = vec3(${t.associatedVariableName}, 0.0); +`:e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.xyz; +`),s.hasEndpoints&&this.xyzw.isConnected&&(e.compilationString+=this._declareOutput(s,e)+` = ${this.xyzw.associatedVariableName}.zw; +`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.xy; +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.x; +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.y; +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.z; +`),l.hasEndpoints&&(e.compilationString+=this._declareOutput(l,e)+` = ${t.associatedVariableName}.w; +`),this}};h["BABYLON.VectorSplitterBlock"]=VectorSplitterBlock;let LerpBlock=class LerpBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerInput("gradient",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(ed.Float)}getClassName(){return"LerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName}); +`,this}};h["BABYLON.LerpBlock"]=LerpBlock;let DivideBlock=class DivideBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(ed.Float),this._inputs[1].acceptedConnectionPointTypes.push(ed.Float)}getClassName(){return"DivideBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} / ${this.right.associatedVariableName}; +`,this}};h["BABYLON.DivideBlock"]=DivideBlock;let SubtractBlock=class SubtractBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(ed.Float),this._inputs[1].acceptedConnectionPointTypes.push(ed.Float)}getClassName(){return"SubtractBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} - ${this.right.associatedVariableName}; +`,this}};h["BABYLON.SubtractBlock"]=SubtractBlock;let StepBlock=class StepBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.Float),this.registerInput("edge",ed.Float),this.registerOutput("output",ed.Float)}getClassName(){return"StepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = step(${this.edge.associatedVariableName}, ${this.value.associatedVariableName}); +`,this}};h["BABYLON.StepBlock"]=StepBlock;let OneMinusBlock=class OneMinusBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[0].excludedConnectionPointTypes.push(ed.Matrix)}getClassName(){return"OneMinusBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = 1. - ${this.input.associatedVariableName}; +`,this}};h["BABYLON.OneMinusBlock"]=OneMinusBlock,h["BABYLON.OppositeBlock"]=OneMinusBlock;let ViewDirectionBlock=class ViewDirectionBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("worldPosition",ed.Vector4),this.registerInput("cameraPosition",ed.Vector3),this.registerOutput("output",ed.Vector3)}getClassName(){return"ViewDirectionBlock"}get worldPosition(){return this._inputs[0]}get cameraPosition(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(ev.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz); +`,this}};h["BABYLON.ViewDirectionBlock"]=ViewDirectionBlock;let FresnelBlock=class FresnelBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("worldNormal",ed.Vector4),this.registerInput("viewDirection",ed.Vector3),this.registerInput("bias",ed.Float),this.registerInput("power",ed.Float),this.registerOutput("fresnel",ed.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){let t=new ViewDirectionBlock("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){let e=new InputBlock("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){let e=new InputBlock("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);let 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}); +`,this}};h["BABYLON.FresnelBlock"]=FresnelBlock;let MaxBlock=class MaxBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}};h["BABYLON.MaxBlock"]=MaxBlock;let MinBlock=class MinBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}};h["BABYLON.MinBlock"]=MinBlock;let DistanceBlock=class DistanceBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ed.Float),this._inputs[1].excludedConnectionPointTypes.push(ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName}); +`,this}};h["BABYLON.DistanceBlock"]=DistanceBlock;let LengthBlock=class LengthBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerOutput("output",ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName}); +`,this}};h["BABYLON.LengthBlock"]=LengthBlock;let NegateBlock=class NegateBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerOutput("output",ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName}; +`,this}};h["BABYLON.NegateBlock"]=NegateBlock;let PowBlock=class PowBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerInput("power",ed.AutoDetect),this.registerOutput("output",ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName}); +`,this}};h["BABYLON.PowBlock"]=PowBlock;let RandomNumberBlock=class RandomNumberBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("seed",ed.AutoDetect),this.registerOutput("output",ed.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector2|ed.Vector3|ed.Vector4|ed.Color3|ed.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy); +`,this}};h["BABYLON.RandomNumberBlock"]=RandomNumberBlock;let ArcTan2Block=class ArcTan2Block extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("x",ed.Float),this.registerInput("y",ed.Float),this.registerOutput("output",ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName}); +`,this}};h["BABYLON.ArcTan2Block"]=ArcTan2Block;let SmoothStepBlock=class SmoothStepBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerInput("edge0",ed.Float),this.registerInput("edge1",ed.Float),this.registerOutput("output",ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName}); +`,this}};h["BABYLON.SmoothStepBlock"]=SmoothStepBlock;let ReciprocalBlock=class ReciprocalBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.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);let t=this._outputs[0];return this.input.type===ed.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); +`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName}; +`,this}};h["BABYLON.ReciprocalBlock"]=ReciprocalBlock;let ReplaceColorBlock=class ReplaceColorBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerInput("reference",ed.AutoDetect),this.registerInput("distance",ed.Float),this.registerInput("replacement",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ed.Float),this._inputs[1].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[3].excludedConnectionPointTypes.push(ed.Float),this._inputs[3].excludedConnectionPointTypes.push(ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+`; +`,e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) { +`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName}; +`,e.compilationString+=`} else { +`,e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName}; +`,e.compilationString+=`} +`,this}};h["BABYLON.ReplaceColorBlock"]=ReplaceColorBlock;let PosterizeBlock=class PosterizeBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerInput("steps",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ed.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);let 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}); +`,this}};h["BABYLON.PosterizeBlock"]=PosterizeBlock,function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(ty||(ty={}));let WaveBlock=class WaveBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.kind=ty.SawTooth,this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];switch(this.kind){case ty.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); +`;break;case ty.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); +`;break;case ty.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0; +`}return this}serialize(){let e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}};h["BABYLON.WaveBlock"]=WaveBlock;let GradientBlockColorStep=class GradientBlockColorStep{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}};let GradientBlock=class GradientBlock extends NodeMaterialBlock{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,e_.Neutral),this.colorSteps=[new GradientBlockColorStep(0,math_color_Color3.Black()),new GradientBlockColorStep(1,math_color_Color3.White())],this.onValueChangedObservable=new observable_Observable,this.registerInput("gradient",ed.AutoDetect),this.registerOutput("output",ed.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Float|ed.Vector2|ed.Vector3|ed.Vector4|ed.Color3|ed.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){let t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=this._declareOutput(t,e)+` = vec3(0., 0., 0.); +`;return}let i=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)}; +`,e.compilationString+=`float ${r}; +`;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==ed.Float&&(s+=".x");for(let t=1;t<this.colorSteps.length;t++){let a=this.colorSteps[t],n=this.colorSteps[t-1];e.compilationString+=`${r} = clamp((${s} - ${e._emitFloat(n.step)}) / (${e._emitFloat(a.step)} - ${e._emitFloat(n.step)}), 0.0, 1.0) * step(${e._emitFloat(t)}, ${e._emitFloat(this.colorSteps.length-1)}); +`,e.compilationString+=`${i} = mix(${i}, ${this._writeColorConstant(t)}, ${r}); +`}return e.compilationString+=this._declareOutput(t,e)+` = ${i}; +`,this}serialize(){let e=super.serialize();for(let t of(e.colorSteps=[],this.colorSteps))e.colorSteps.push({step:t.step,color:{r:t.color.r,g:t.color.g,b:t.color.b}});return e}_deserialize(e,t,i){for(let r of(super._deserialize(e,t,i),this.colorSteps.length=0,e.colorSteps))this.colorSteps.push(new GradientBlockColorStep(r.step,new math_color_Color3(r.color.r,r.color.g,r.color.b)))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();for(let t of(e+=`${this._codeVariableName}.colorSteps = []; +`,this.colorSteps))e+=`${this._codeVariableName}.colorSteps.push(new BABYLON.GradientBlockColorStep(${t.step}, new BABYLON.Color3(${t.color.r}, ${t.color.g}, ${t.color.b}))); +`;return e}};h["BABYLON.GradientBlock"]=GradientBlock;let NLerpBlock=class NLerpBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerInput("gradient",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(ed.Float)}getClassName(){return"NLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName})); +`,this}};h["BABYLON.NLerpBlock"]=NLerpBlock;let WorleyNoise3DBlock=class WorleyNoise3DBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.manhattanDistance=!1,this.registerInput("seed",ed.Vector3),this.registerInput("jitter",ed.Float),this.registerOutput("output",ed.Vector2),this.registerOutput("x",ed.Float),this.registerOutput("y",ed.Float)}getClassName(){return"WorleyNoise3DBlock"}get seed(){return this._inputs[0]}get jitter(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected||!this.output.hasEndpoints&&!this.x.hasEndpoints&&!this.y.hasEndpoints)return;let t=`vec3 permute(vec3 x){ +`;t+=` return mod((34.0 * x + 1.0) * x, 289.0); +} + +vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){ + return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z); +} + +vec2 worley(vec3 P, float jitter, bool manhattanDistance){ + float K = 0.142857142857; // 1/7 + float Ko = 0.428571428571; // 1/2-K/2 + float K2 = 0.020408163265306; // 1/(7*7) + float Kz = 0.166666666667; // 1/6 + float Kzo = 0.416666666667; // 1/2-1/6*2 + + vec3 Pi = mod(floor(P), 289.0); + vec3 Pf = fract(P) - 0.5; + + vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0); + vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0); + vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0); + + vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0)); + vec3 p1 = permute(p + Pi.y - 1.0); + vec3 p2 = permute(p + Pi.y); + vec3 p3 = permute(p + Pi.y + 1.0); + + vec3 p11 = permute(p1 + Pi.z - 1.0); + vec3 p12 = permute(p1 + Pi.z); + vec3 p13 = permute(p1 + Pi.z + 1.0); + + vec3 p21 = permute(p2 + Pi.z - 1.0); + vec3 p22 = permute(p2 + Pi.z); + vec3 p23 = permute(p2 + Pi.z + 1.0); + + vec3 p31 = permute(p3 + Pi.z - 1.0); + vec3 p32 = permute(p3 + Pi.z); + vec3 p33 = permute(p3 + Pi.z + 1.0); + + vec3 ox11 = fract(p11*K) - Ko; + vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko; + vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed + + vec3 ox12 = fract(p12*K) - Ko; + vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko; + vec3 oz12 = floor(p12*K2)*Kz - Kzo; + + vec3 ox13 = fract(p13*K) - Ko; + vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko; + vec3 oz13 = floor(p13*K2)*Kz - Kzo; + + vec3 ox21 = fract(p21*K) - Ko; + vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko; + vec3 oz21 = floor(p21*K2)*Kz - Kzo; + + vec3 ox22 = fract(p22*K) - Ko; + vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko; + vec3 oz22 = floor(p22*K2)*Kz - Kzo; + + vec3 ox23 = fract(p23*K) - Ko; + vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko; + vec3 oz23 = floor(p23*K2)*Kz - Kzo; + + vec3 ox31 = fract(p31*K) - Ko; + vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko; + vec3 oz31 = floor(p31*K2)*Kz - Kzo; + + vec3 ox32 = fract(p32*K) - Ko; + vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko; + vec3 oz32 = floor(p32*K2)*Kz - Kzo; + + vec3 ox33 = fract(p33*K) - Ko; + vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko; + vec3 oz33 = floor(p33*K2)*Kz - Kzo; + + vec3 dx11 = Pfx + jitter*ox11; + vec3 dy11 = Pfy.x + jitter*oy11; + vec3 dz11 = Pfz.x + jitter*oz11; + + vec3 dx12 = Pfx + jitter*ox12; + vec3 dy12 = Pfy.x + jitter*oy12; + vec3 dz12 = Pfz.y + jitter*oz12; + + vec3 dx13 = Pfx + jitter*ox13; + vec3 dy13 = Pfy.x + jitter*oy13; + vec3 dz13 = Pfz.z + jitter*oz13; + + vec3 dx21 = Pfx + jitter*ox21; + vec3 dy21 = Pfy.y + jitter*oy21; + vec3 dz21 = Pfz.x + jitter*oz21; + + vec3 dx22 = Pfx + jitter*ox22; + vec3 dy22 = Pfy.y + jitter*oy22; + vec3 dz22 = Pfz.y + jitter*oz22; + + vec3 dx23 = Pfx + jitter*ox23; + vec3 dy23 = Pfy.y + jitter*oy23; + vec3 dz23 = Pfz.z + jitter*oz23; + + vec3 dx31 = Pfx + jitter*ox31; + vec3 dy31 = Pfy.z + jitter*oy31; + vec3 dz31 = Pfz.x + jitter*oz31; + + vec3 dx32 = Pfx + jitter*ox32; + vec3 dy32 = Pfy.z + jitter*oy32; + vec3 dz32 = Pfz.y + jitter*oz32; + + vec3 dx33 = Pfx + jitter*ox33; + vec3 dy33 = Pfy.z + jitter*oy33; + vec3 dz33 = Pfz.z + jitter*oz33; + + vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance); + vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance); + vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance); + vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance); + vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance); + vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance); + vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance); + vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance); + vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance); + + vec3 d1a = min(d11, d12); + d12 = max(d11, d12); + d11 = min(d1a, d13); // Smallest now not in d12 or d13 + d13 = max(d1a, d13); + d12 = min(d12, d13); // 2nd smallest now not in d13 + vec3 d2a = min(d21, d22); + d22 = max(d21, d22); + d21 = min(d2a, d23); // Smallest now not in d22 or d23 + d23 = max(d2a, d23); + d22 = min(d22, d23); // 2nd smallest now not in d23 + vec3 d3a = min(d31, d32); + d32 = max(d31, d32); + d31 = min(d3a, d33); // Smallest now not in d32 or d33 + d33 = max(d3a, d33); + d32 = min(d32, d33); // 2nd smallest now not in d33 + vec3 da = min(d11, d21); + d21 = max(d11, d21); + d11 = min(da, d31); // Smallest now in d11 + d31 = max(da, d31); // 2nd smallest now not in d31 + d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx; + d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest + d12 = min(d12, d21); // 2nd smallest now not in d21 + d12 = min(d12, d22); // nor in d22 + d12 = min(d12, d31); // nor in d31 + d12 = min(d12, d32); // nor in d32 + d11.yz = min(d11.yz,d12.xy); // nor in d12.yz + d11.y = min(d11.y,d12.z); // Only two more to go + d11.y = min(d11.y,d11.z); // Done! (Phew!) + return sqrt(d11.xy); // F1, F2 +} + +`,e._emitFunction("worley3D",t,"// Worley3D");let i=e._getFreeVariableName("worleyTemp");return e.compilationString+=`vec2 ${i} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance}); +`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${i}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${i}.y; +`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance}; +`;return e}serialize(){let e=super.serialize();return e.manhattanDistance=this.manhattanDistance,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.manhattanDistance=e.manhattanDistance}};__decorate([editableInPropertyPage("Use Manhattan Distance",em.Boolean,"PROPERTIES",{notifiers:{update:!1}})],WorleyNoise3DBlock.prototype,"manhattanDistance",void 0),h["BABYLON.WorleyNoise3DBlock"]=WorleyNoise3DBlock;let SimplexPerlin3DBlock=class SimplexPerlin3DBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("seed",ed.Vector3),this.registerOutput("output",ed.Float)}getClassName(){return"SimplexPerlin3DBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;let t=`const float SKEWFACTOR = 1.0/3.0; +`;return t+=`const float UNSKEWFACTOR = 1.0/6.0; +const float SIMPLEX_CORNER_POS = 0.5; +const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485; +float SimplexPerlin3D( vec3 P ){ + P.x = P == vec3(0., 0., 0.) ? 0.00001 : P.x; + P *= SIMPLEX_TETRAHADRON_HEIGHT; + vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) ); vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) ); + vec3 g = step(x0.yzx, x0.xyz); + vec3 l = 1.0 - g; + vec3 Pi_1 = min( g.xyz, l.zxy ); + vec3 Pi_2 = max( g.xyz, l.zxy ); + vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR; + vec3 x2 = x0 - Pi_2 + SKEWFACTOR; + vec3 x3 = x0 - SIMPLEX_CORNER_POS; + vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x ); + vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y ); + vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z ); + Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0; + vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 ); + vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy; + Pt *= Pt; + vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) ); + Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w ); + const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 ); + const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 ); + vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) ); + vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) ); + Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods; + Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods; + vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999; + vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999; + vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999; + 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 ); + const float FINAL_NORMALIZATION = 37.837227241611314102871574478976; + vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z; + kernel_weights = max(0.5 - kernel_weights, 0.0); + kernel_weights = kernel_weights*kernel_weights*kernel_weights; + return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION; +} +`,e._emitFunction("SimplexPerlin3D",t,"// SimplexPerlin3D"),e.compilationString+=this._declareOutput(this._outputs[0],e)+` = SimplexPerlin3D(${this.seed.associatedVariableName}); +`,this}};h["BABYLON.SimplexPerlin3DBlock"]=SimplexPerlin3DBlock;let NormalBlendBlock=class NormalBlendBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("normalMap0",ed.AutoDetect),this.registerInput("normalMap1",ed.AutoDetect),this.registerOutput("output",ed.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Color4|ed.Vector3|ed.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Color4|ed.Vector3|ed.Vector4)}getClassName(){return"NormalBlendBlock"}get normalMap0(){return this._inputs[0]}get normalMap1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0],r=this._inputs[1],s=e._getFreeVariableName("stepR"),a=e._getFreeVariableName("stepG");return e.compilationString+=`float ${s} = step(0.5, ${i.associatedVariableName}.r); +`,e.compilationString+=`float ${a} = step(0.5, ${i.associatedVariableName}.g); +`,e.compilationString+=this._declareOutput(t,e)+`; +`,e.compilationString+=`${t.associatedVariableName}.r = (1.0 - ${s}) * ${i.associatedVariableName}.r * ${r.associatedVariableName}.r * 2.0 + ${s} * (1.0 - (1.0 - ${i.associatedVariableName}.r) * (1.0 - ${r.associatedVariableName}.r) * 2.0); +`,e.compilationString+=`${t.associatedVariableName}.g = (1.0 - ${a}) * ${i.associatedVariableName}.g * ${r.associatedVariableName}.g * 2.0 + ${a} * (1.0 - (1.0 - ${i.associatedVariableName}.g) * (1.0 - ${r.associatedVariableName}.g) * 2.0); +`,e.compilationString+=`${t.associatedVariableName}.b = ${i.associatedVariableName}.b * ${r.associatedVariableName}.b; +`,this}};h["BABYLON.NormalBlendBlock"]=NormalBlendBlock;let Rotate2dBlock=class Rotate2dBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.Vector2),this.registerInput("angle",ed.Float),this.registerOutput("output",ed.Vector2)}getClassName(){return"Rotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new InputBlock("angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.angle,r=this.input;return e.compilationString+=this._declareOutput(t,e)+` = vec2(cos(${i.associatedVariableName}) * ${r.associatedVariableName}.x - sin(${i.associatedVariableName}) * ${r.associatedVariableName}.y, sin(${i.associatedVariableName}) * ${r.associatedVariableName}.x + cos(${i.associatedVariableName}) * ${r.associatedVariableName}.y); +`,this}};h["BABYLON.Rotate2dBlock"]=Rotate2dBlock;let ReflectBlock=class ReflectBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("incident",ed.AutoDetect),this.registerInput("normal",ed.AutoDetect),this.registerOutput("output",ed.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector3|ed.Vector4|ed.Color3|ed.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ed.Vector3|ed.Vector4|ed.Color3|ed.Color4)}getClassName(){return"ReflectBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz); +`,this}};h["BABYLON.ReflectBlock"]=ReflectBlock;let RefractBlock=class RefractBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("incident",ed.AutoDetect),this.registerInput("normal",ed.AutoDetect),this.registerInput("ior",ed.Float),this.registerOutput("output",ed.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector3|ed.Vector4|ed.Color3|ed.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ed.Vector3|ed.Vector4|ed.Color3|ed.Color4)}getClassName(){return"RefractBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get ior(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName}); +`,this}};h["BABYLON.RefractBlock"]=RefractBlock;let DesaturateBlock=class DesaturateBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("color",ed.Color3),this.registerInput("level",ed.Float),this.registerOutput("output",ed.Color3)}getClassName(){return"DesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.color,r=i.associatedVariableName,s=e._getFreeVariableName("colorMin"),a=e._getFreeVariableName("colorMax"),n=e._getFreeVariableName("colorMerge");return e.compilationString+=`float ${s} = min(min(${r}.x, ${r}.y), ${r}.z); +`,e.compilationString+=`float ${a} = max(max(${r}.x, ${r}.y), ${r}.z); +`,e.compilationString+=`float ${n} = 0.5 * (${s} + ${a}); +`,e.compilationString+=this._declareOutput(t,e)+` = mix(${r}, vec3(${n}, ${n}, ${n}), ${this.level.associatedVariableName}); +`,this}};h["BABYLON.DesaturateBlock"]=DesaturateBlock;let SheenBlock=class SheenBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.albedoScaling=!1,this.linkSheenWithAlbedo=!1,this._isUnique=!0,this.registerInput("intensity",ed.Float,!0,e_.Fragment),this.registerInput("color",ed.Color3,!0,e_.Fragment),this.registerInput("roughness",ed.Float,!0,e_.Fragment),this.registerOutput("sheen",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("sheen",this,ef.Output,SheenBlock,"SheenBlock"))}initialize(e){e._excludeVariableName("sheenOut"),e._excludeVariableName("sheenMapData"),e._excludeVariableName("vSheenColor"),e._excludeVariableName("vSheenRoughness")}getClassName(){return"SheenBlock"}get intensity(){return this._inputs[0]}get color(){return this._inputs[1]}get roughness(){return this._inputs[2]}get sheen(){return this._outputs[0]}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("SHEEN",!0),i.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("SHEEN_LINKWITHALBEDO",this.linkSheenWithAlbedo,!0),i.setValue("SHEEN_ROUGHNESS",this.roughness.isConnected,!0),i.setValue("SHEEN_ALBEDOSCALING",this.albedoScaling,!0)}getCode(e){let t=this.color.isConnected?this.color.associatedVariableName:"vec3(1.)",i=this.intensity.isConnected?this.intensity.associatedVariableName:"1.",r=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return`#ifdef SHEEN + sheenOutParams sheenOut; + + vec4 vSheenColor = vec4(${t}, ${i}); + + sheenBlock( + vSheenColor, + #ifdef SHEEN_ROUGHNESS + ${r}, + #endif + roughness, + #ifdef SHEEN_TEXTURE + vec4(0.), + 1.0, + #endif + reflectance, + #ifdef SHEEN_LINKWITHALBEDO + baseColor, + surfaceAlbedo, + #endif + #ifdef ENVIRONMENTBRDF + NdotV, + environmentBrdf, + #endif + #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) + AARoughnessFactors, + ${null==e?void 0:e._vReflectionMicrosurfaceInfosName}, + ${null==e?void 0:e._vReflectionInfosName}, + ${null==e?void 0:e.reflectionColor}, + vLightingIntensity, + #ifdef ${null==e?void 0:e._define3DName} + ${null==e?void 0:e._cubeSamplerName}, + #else + ${null==e?void 0:e._2DSamplerName}, + #endif + reflectionOut.reflectionCoords, + NdotVUnclamped, + #ifndef LODBASEDMICROSFURACE + #ifdef ${null==e?void 0:e._define3DName} + ${null==e?void 0:e._cubeSamplerName}, + ${null==e?void 0:e._cubeSamplerName}, + #else + ${null==e?void 0:e._2DSamplerName}, + ${null==e?void 0:e._2DSamplerName}, + #endif + #endif + #if !defined(${null==e?void 0:e._defineSkyboxName}) && defined(RADIANCEOCCLUSION) + seo, + #endif + #if !defined(${null==e?void 0:e._defineSkyboxName}) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(${null==e?void 0:e._define3DName}) + eho, + #endif + #endif + sheenOut + ); + + #ifdef SHEEN_LINKWITHALBEDO + surfaceAlbedo = sheenOut.surfaceAlbedo; + #endif + #endif +`}_buildBlock(e){return e.target===e_.Fragment&&e.sharedData.blocksWithDefines.push(this),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.albedoScaling = ${this.albedoScaling}; +${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo}; +`}serialize(){let e=super.serialize();return e.albedoScaling=this.albedoScaling,e.linkSheenWithAlbedo=this.linkSheenWithAlbedo,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.albedoScaling=e.albedoScaling,this.linkSheenWithAlbedo=e.linkSheenWithAlbedo}};__decorate([editableInPropertyPage("Albedo scaling",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],SheenBlock.prototype,"albedoScaling",void 0),__decorate([editableInPropertyPage("Link sheen with albedo",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],SheenBlock.prototype,"linkSheenWithAlbedo",void 0),h["BABYLON.SheenBlock"]=SheenBlock;let AnisotropyBlock=class AnisotropyBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._tangentCorrectionFactorName="",this._isUnique=!0,this.registerInput("intensity",ed.Float,!0,e_.Fragment),this.registerInput("direction",ed.Vector2,!0,e_.Fragment),this.registerInput("uv",ed.Vector2,!0),this.registerInput("worldTangent",ed.Vector4,!0),this.registerInput("TBN",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("TBN",this,ef.Input,TBNBlock,"TBNBlock")),this.registerInput("roughness",ed.Float,!0,e_.Fragment),this.registerOutput("anisotropy",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("anisotropy",this,ef.Output,AnisotropyBlock,"AnisotropyBlock"))}initialize(e){e._excludeVariableName("anisotropicOut"),e._excludeVariableName("TBN")}getClassName(){return"AnisotropyBlock"}get intensity(){return this._inputs[0]}get direction(){return this._inputs[1]}get uv(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get TBN(){return this._inputs[4]}get roughness(){return this._inputs[5]}get anisotropy(){return this._outputs[0]}_generateTBNSpace(e){let t="",i=`//${this.name}`,r=this.uv,s=this.worldPositionConnectionPoint,a=this.worldNormalConnectionPoint,n=this.worldTangent;r.isConnected||console.error("You must connect the 'uv' input of the Anisotropy block!"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let o={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},l=this.TBN;return l.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${l.associatedVariableName}; + #endif + `:n.isConnected&&(t+=`vec3 tbnNormal = normalize(${a.associatedVariableName}.xyz); +vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); +vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),t+=` + #if defined(${n.isConnected?"TANGENT":"IGNORE"}) && defined(NORMAL) + mat3 TBN = vTBN; + #else + mat3 TBN = cotangent_frame(${a.associatedVariableName+".xyz"}, ${"v_"+s.associatedVariableName+".xyz"}, ${r.isConnected?r.associatedVariableName:"vec2(0.)"}, vec2(1., 1.)); + #endif +`,e._emitFunctionFromInclude("bumpFragmentMainFunctions",i,{replaceStrings:[o]}),t}getCode(e,t=!1){let i="";t&&(i+=this._generateTBNSpace(e));let r=this.intensity.isConnected?this.intensity.associatedVariableName:"1.0",s=this.direction.isConnected?this.direction.associatedVariableName:"vec2(1., 0.)",a=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return i+`anisotropicOutParams anisotropicOut; + anisotropicBlock( + vec3(${s}, ${r}), + ${a}, + #ifdef ANISOTROPIC_TEXTURE + vec3(0.), + #endif + TBN, + normalW, + viewDirectionW, + anisotropicOut + ); +`}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("ANISOTROPIC",!0),i.setValue("ANISOTROPIC_TEXTURE",!1,!0),i.setValue("ANISOTROPIC_LEGACY",!this.roughness.isConnected)}bind(e,t,i){super.bind(e,t,i),i&&e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1)}_buildBlock(e){return e.target===e_.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}};h["BABYLON.AnisotropyBlock"]=AnisotropyBlock;let ReflectionBlock=class ReflectionBlock extends ReflectionTextureBaseBlock{_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._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?e_.Fragment:e_.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",ed.AutoDetect,!1,e_.Vertex),this.registerInput("world",ed.Matrix,!1,e_.Vertex),this.registerInput("color",ed.Color3,!0,e_.Fragment),this.registerOutput("reflection",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("reflection",this,ef.Output,ReflectionBlock,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4)}getClassName(){return"ReflectionBlock"}get position(){return this._inputs[0]}get worldPosition(){return this.worldPositionConnectionPoint}get worldNormal(){return this.worldNormalConnectionPoint}get world(){return this._inputs[1]}get cameraPosition(){return this.cameraPositionConnectionPoint}get view(){return this.viewConnectionPoint}get color(){return this._inputs[2]}get reflection(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}get reflectionColor(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("REFLECTION",s,!0),s&&(i.setValue(this._defineLODReflectionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!r.invertZ:r.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",r.gammaSpace,!0),i.setValue("RGBDREFLECTION",r.isRGBD,!0),r&&r.coordinatesMode!==texture_Texture.SKYBOX_MODE&&r.isCube&&(i.setValue("USESPHERICALFROMREFLECTIONMAP",!0),i.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?i.setValue("USESPHERICALINVERTEX",!1):i.setValue("USESPHERICALINVERTEX",!0)))}bind(e,t,i,r){super.bind(e,t,i);let s=this._getTexture();if(!s||!r)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s);let a=s.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,a,s.lodGenerationScale,s.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,a,math_scalar_Scalar.Log2(a));let n=r.materialDefines,o=s.sphericalPolynomial;if(n.USESPHERICALFROMREFLECTIONMAP&&o){if(n.SPHERICAL_HARMONICS){let t=o.preScaledHarmonics;e.setVector3("vSphericalL00",t.l00),e.setVector3("vSphericalL1_1",t.l1_1),e.setVector3("vSphericalL10",t.l10),e.setVector3("vSphericalL11",t.l11),e.setVector3("vSphericalL2_2",t.l2_2),e.setVector3("vSphericalL2_1",t.l2_1),e.setVector3("vSphericalL20",t.l20),e.setVector3("vSphericalL21",t.l21),e.setVector3("vSphericalL22",t.l22)}else e.setFloat3("vSphericalX",o.x.x,o.x.y,o.x.z),e.setFloat3("vSphericalY",o.y.x,o.y.y,o.y.z),e.setFloat3("vSphericalZ",o.z.x,o.z.y,o.z.z),e.setFloat3("vSphericalXX_ZZ",o.xx.x-o.zz.x,o.xx.y-o.zz.y,o.xx.z-o.zz.z),e.setFloat3("vSphericalYY_ZZ",o.yy.x-o.zz.x,o.yy.y-o.zz.y,o.yy.z-o.zz.z),e.setFloat3("vSphericalZZ",o.zz.x,o.zz.y,o.zz.z),e.setFloat3("vSphericalXY",o.xy.x,o.xy.y,o.xy.z),e.setFloat3("vSphericalYZ",o.yz.x,o.yz.y,o.yz.z),e.setFloat3("vSphericalZX",o.zx.x,o.zx.y,o.zx.z)}}handleVertexSide(e){let t=super.handleVertexSide(e);e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});let i=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,"vec3","defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX","vec3","SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) + vec3 ${i} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; + #ifdef ${this._defineOppositeZ} + ${i}.z *= -1.0; + #endif + ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${i}); + #endif +`}getCode(e,t){let i="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection",` + #ifdef ${this._define3DName} + #define sampleReflection(s, c) textureCube(s, c) + #else + #define sampleReflection(s, c) texture2D(s, c) + #endif +`,`//${this.name}`),e._emitFunction("sampleReflectionLod",` + #ifdef ${this._define3DName} + #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l) + #else + #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l) + #endif +`,`//${this.name}`);let r=` + vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) { + ${this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0,!0)} + return ${this._reflectionVectorName}; + } +`;return e._emitFunction("computeReflectionCoordsPBR",r,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,"vec3"),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,"vec2"),i+=`#ifdef REFLECTION + vec2 ${this._vReflectionInfosName} = vec2(1., 0.); + + reflectionOutParams reflectionOut; + + reflectionBlock( + ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName}.xyz, + ${t}, + alphaG, + ${this._vReflectionMicrosurfaceInfosName}, + ${this._vReflectionInfosName}, + ${this.reflectionColor}, + #ifdef ANISOTROPIC + anisotropicOut, + #endif + #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName}) + NdotVUnclamped, + #endif + #ifdef ${this._defineLinearSpecularReflection} + roughness, + #endif + #ifdef ${this._define3DName} + ${this._cubeSamplerName}, + #else + ${this._2DSamplerName}, + #endif + #if defined(NORMAL) && defined(USESPHERICALINVERTEX) + ${this._vEnvironmentIrradianceName}, + #endif + #ifdef USESPHERICALFROMREFLECTIONMAP + #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) + ${this._reflectionMatrixName}, + #endif + #endif + #ifdef USEIRRADIANCEMAP + irradianceSampler, // ** not handled ** + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${this._define3DName} + ${this._cubeSamplerName}, + ${this._cubeSamplerName}, + #else + ${this._2DSamplerName}, + ${this._2DSamplerName}, + #endif + #endif + #ifdef REALTIME_FILTERING + ${this._vReflectionFilteringInfoName}, + #endif + reflectionOut + ); + #endif +`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==e_.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace}; +`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics}; +${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment}; +`}serialize(){var e,t;let i=super.serialize();return i.useSphericalHarmonics=this.useSphericalHarmonics,i.forceIrradianceInFragment=this.forceIrradianceInFragment,i.gammaSpace=null===(t=null===(e=this.texture)||void 0===e?void 0:e.gammaSpace)||void 0===t||t,i}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}};__decorate([editableInPropertyPage("Spherical Harmonics",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],ReflectionBlock.prototype,"useSphericalHarmonics",void 0),__decorate([editableInPropertyPage("Force irradiance in fragment",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],ReflectionBlock.prototype,"forceIrradianceInFragment",void 0),h["BABYLON.ReflectionBlock"]=ReflectionBlock;let ClearCoatBlock=class ClearCoatBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",ed.Float,!1,e_.Fragment),this.registerInput("roughness",ed.Float,!0,e_.Fragment),this.registerInput("indexOfRefraction",ed.Float,!0,e_.Fragment),this.registerInput("normalMapColor",ed.Color3,!0,e_.Fragment),this.registerInput("uv",ed.Vector2,!0,e_.Fragment),this.registerInput("tintColor",ed.Color3,!0,e_.Fragment),this.registerInput("tintAtDistance",ed.Float,!0,e_.Fragment),this.registerInput("tintThickness",ed.Float,!0,e_.Fragment),this.registerInput("worldTangent",ed.Vector4,!0),this.registerInput("worldNormal",ed.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(ed.Color4|ed.Vector4|ed.Vector3),this.registerInput("TBN",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("TBN",this,ef.Input,TBNBlock,"TBNBlock")),this.registerOutput("clearcoat",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("clearcoat",this,ef.Output,ClearCoatBlock,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new InputBlock("ClearCoat intensity",e_.Fragment,ed.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var r,s;super.bind(e,t,i);let a=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,n=1-a,o=1+a,l=Math.pow(-n/o,2);e.setFloat4("vClearCoatRefractionParams",l,1/a,n,o);let h=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,c=(null==h?void 0:h.perturbedNormal.isConnected)?h.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",(null==c?void 0:c.invertX)?1:-1,(null==c?void 0:c.invertY)?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",(null==c?void 0:c.invertX)?-1:1,(null==c?void 0:c.invertY)?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1)}_generateTBNSpace(e,t,i){let r="",s=`//${this.name}`,a=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let n={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},o=this.TBN;return o.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${o.associatedVariableName}; + #endif + `:a.isConnected&&(r+=`vec3 tbnNormal = normalize(${i}.xyz); +vec3 tbnTangent = normalize(${a.associatedVariableName}.xyz); +vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[n]}),r}static GetCode(e,t,i,r,s,a,n){let o="",l=(null==t?void 0:t.intensity.isConnected)?t.intensity.associatedVariableName:"1.",h=(null==t?void 0:t.roughness.isConnected)?t.roughness.associatedVariableName:"0.",c=(null==t?void 0:t.normalMapColor.isConnected)?t.normalMapColor.associatedVariableName:"vec3(0.)",u=(null==t?void 0:t.uv.isConnected)?t.uv.associatedVariableName:"vec2(0.)",d=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",_=(null==t?void 0:t.tintThickness.isConnected)?t.tintThickness.associatedVariableName:"1.",p=(null==t?void 0:t.tintAtDistance.isConnected)?t.tintAtDistance.associatedVariableName:"1.";if(t){e._emitUniformFromString("vClearCoatRefractionParams","vec4"),e._emitUniformFromString("vClearCoatTangentSpaceParams","vec2");let i=t.worldNormal;o+=`vec3 vGeometricNormaClearCoatW = ${i.isConnected?"normalize("+i.associatedVariableName+".xyz)":"geometricNormalW"}; +`}else o+=`vec3 vGeometricNormaClearCoatW = geometricNormalW; +`;return s&&t&&(o+=t._generateTBNSpace(e,r,n),a=t.worldTangent.isConnected),o+=`clearcoatOutParams clearcoatOut; + + #ifdef CLEARCOAT + vec2 vClearCoatParams = vec2(${l}, ${h}); + vec4 vClearCoatTintParams = vec4(${d}, ${_}); + + clearcoatBlock( + ${r}.xyz, + vGeometricNormaClearCoatW, + viewDirectionW, + vClearCoatParams, + specularEnvironmentR0, + #ifdef CLEARCOAT_TEXTURE + vec2(0.), + #endif + #ifdef CLEARCOAT_TINT + vClearCoatTintParams, + ${p}, + vClearCoatRefractionParams, + #ifdef CLEARCOAT_TINT_TEXTURE + vec4(0.), + #endif + #endif + #ifdef CLEARCOAT_BUMP + vec2(0., 1.), + vec4(${c}, 0.), + ${u}, + #if defined(${a?"TANGENT":"IGNORE"}) && defined(NORMAL) + vTBN, + #else + vClearCoatTangentSpaceParams, + #endif + #ifdef OBJECTSPACE_NORMALMAP + normalMatrix, + #endif + #endif + #if defined(FORCENORMALFORWARD) && defined(NORMAL) + faceNormal, + #endif + #ifdef REFLECTION + ${null==i?void 0:i._vReflectionMicrosurfaceInfosName}, + ${null==i?void 0:i._vReflectionInfosName}, + ${null==i?void 0:i.reflectionColor}, + vLightingIntensity, + #ifdef ${null==i?void 0:i._define3DName} + ${null==i?void 0:i._cubeSamplerName}, + #else + ${null==i?void 0:i._2DSamplerName}, + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${null==i?void 0:i._define3DName} + ${null==i?void 0:i._cubeSamplerName}, + ${null==i?void 0:i._cubeSamplerName}, + #else + ${null==i?void 0:i._2DSamplerName}, + ${null==i?void 0:i._2DSamplerName}, + #endif + #endif + #endif + #if defined(ENVIRONMENTBRDF) && !defined(${null==i?void 0:i._defineSkyboxName}) + #ifdef RADIANCEOCCLUSION + ambientMonochrome, + #endif + #endif + #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) + (gl_FrontFacing ? 1. : -1.), + #endif + clearcoatOut + ); + #else + clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0; + #endif +`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===e_.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange}; +`}serialize(){let e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.remapF0OnInterfaceChange=null===(r=e.remapF0OnInterfaceChange)||void 0===r||r}};__decorate([editableInPropertyPage("Remap F0 on interface change",em.Boolean,"ADVANCED")],ClearCoatBlock.prototype,"remapF0OnInterfaceChange",void 0),h["BABYLON.ClearCoatBlock"]=ClearCoatBlock;let IridescenceBlock=class IridescenceBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._isUnique=!0,this.registerInput("intensity",ed.Float,!0,e_.Fragment),this.registerInput("indexOfRefraction",ed.Float,!0,e_.Fragment),this.registerInput("thickness",ed.Float,!0,e_.Fragment),this.registerOutput("iridescence",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("iridescence",this,ef.Output,IridescenceBlock,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new InputBlock("Iridescence intensity",e_.Fragment,ed.Float);e.value=1,e.output.connectTo(this.intensity);let t=new InputBlock("Iridescence ior",e_.Fragment,ed.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);let i=new InputBlock("Iridescence thickness",e_.Fragment,ed.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e){let t=(null==e?void 0:e.intensity.isConnected)?e.intensity.associatedVariableName:"1.",i=(null==e?void 0:e.indexOfRefraction.isConnected)?e.indexOfRefraction.associatedVariableName:pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction,r=(null==e?void 0:e.thickness.isConnected)?e.thickness.associatedVariableName:pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness;return`iridescenceOutParams iridescenceOut; + + #ifdef IRIDESCENCE + iridescenceBlock( + vec4(${t}, ${i}, 1., ${r}), + NdotV, + specularEnvironmentR0, + #ifdef CLEARCOAT + NdotVUnclamped, + #endif + iridescenceOut + ); + + float iridescenceIntensity = iridescenceOut.iridescenceIntensity; + specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; + #endif +`}_buildBlock(e){return e.target===e_.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){let e=super.serialize();return e}_deserialize(e,t,i){super._deserialize(e,t,i)}};h["BABYLON.IridescenceBlock"]=IridescenceBlock;let RefractionBlock=class RefractionBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",ed.Float,!1,e_.Fragment),this.registerInput("tintAtDistance",ed.Float,!0,e_.Fragment),this.registerInput("volumeIndexOfRefraction",ed.Float,!0,e_.Fragment),this.registerOutput("refraction",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("refraction",this,ef.Output,RefractionBlock,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e,t=()=>!0){if(!this.intensity.isConnected){let e=new InputBlock("Refraction intensity",e_.Fragment,ed.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(ev.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){var r,s,a,n;super.bind(e,t,i);let o=this._getTexture();if(!o)return;o.isCube?e.setTexture(this._cubeSamplerName,o):e.setTexture(this._2DSamplerName,o),e.setMatrix(this._refractionMatrixName,o.getRefractionTextureMatrix());let l=1;!o.isCube&&o.depth&&(l=o.depth);let h=null!==(n=null!==(s=null===(r=this.volumeIndexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:null===(a=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===a?void 0:a.value)&&void 0!==n?n:1.5;e.setFloat4(this._vRefractionInfosName,o.level,1/h,l,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,o.getSize().width,o.lodGenerationScale,o.lodGenerationOffset,1/h);let c=o.getSize().width;e.setFloat2(this._vRefractionFilteringInfoName,c,math_scalar_Scalar.Log2(c)),o.boundingBoxSize&&(e.setVector3("vRefractionPosition",o.boundingBoxPosition),e.setVector3("vRefractionSize",o.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} +`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; +`,e._samplerDeclaration+=`#else +`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; +`,e._samplerDeclaration+=`#endif +`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",` + #ifdef ${this._define3DName} + #define sampleRefraction(s, c) textureCube(s, c) + #else + #define sampleRefraction(s, c) texture2D(s, c) + #endif +`,`//${this.name}`),e._emitFunction("sampleRefractionLod",` + #ifdef ${this._define3DName} + #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) + #else + #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) + #endif +`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"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}"); +`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}"); +`)+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency}; +${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY}; +${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth}; +`}serialize(){let 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=cubeTexture_CubeTexture.Parse(e.texture,t,i):this.texture=texture_Texture.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}};__decorate([editableInPropertyPage("Link refraction to transparency",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"linkRefractionWithTransparency",void 0),__decorate([editableInPropertyPage("Invert refraction Y",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"invertRefractionY",void 0),__decorate([editableInPropertyPage("Use thickness as depth",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"useThicknessAsDepth",void 0),h["BABYLON.RefractionBlock"]=RefractionBlock;let SubSurfaceBlock=class SubSurfaceBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._isUnique=!0,this.registerInput("thickness",ed.Float,!1,e_.Fragment),this.registerInput("tintColor",ed.Color3,!0,e_.Fragment),this.registerInput("translucencyIntensity",ed.Float,!0,e_.Fragment),this.registerInput("translucencyDiffusionDist",ed.Color3,!0,e_.Fragment),this.registerInput("refraction",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("refraction",this,ef.Input,RefractionBlock,"RefractionBlock")),this.registerOutput("subsurface",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("subsurface",this,ef.Output,SubSurfaceBlock,"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){let e=new InputBlock("SubSurface thickness",e_.Fragment,ed.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0)}static GetCode(e,t,i,r){var s,a,n,o,l,h,c,u,d,_,p,f,m,g,v,x;let b=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",T=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",S=(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.)",E=(null==t?void 0:t.refraction.isConnected)?null===(s=null==t?void 0:t.refraction.connectedPoint)||void 0===s?void 0:s.ownerBlock:null,y=(null==E?void 0:E.tintAtDistance.isConnected)?E.tintAtDistance.associatedVariableName:"1.",R=(null==E?void 0:E.intensity.isConnected)?E.intensity.associatedVariableName:"1.",P=(null==E?void 0:E.view.isConnected)?E.view.associatedVariableName:"";return""+(null!==(a=null==E?void 0:E.getCode(e))&&void 0!==a?a:"")+`subSurfaceOutParams subSurfaceOut; + + #ifdef SUBSURFACE + vec2 vThicknessParam = vec2(0., ${b}); + vec4 vTintColor = vec4(${T}, ${y}); + vec3 vSubSurfaceIntensity = vec3(${R}, ${S}, 0.); + + subSurfaceBlock( + vSubSurfaceIntensity, + vThicknessParam, + vTintColor, + normalW, + specularEnvironmentReflectance, + #ifdef SS_THICKNESSANDMASK_TEXTURE + vec4(0.), + #endif + #ifdef REFLECTION + #ifdef SS_TRANSLUCENCY + ${null==i?void 0:i._reflectionMatrixName}, + #ifdef USESPHERICALFROMREFLECTIONMAP + #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) + reflectionOut.irradianceVector, + #endif + #if defined(REALTIME_FILTERING) + ${null==i?void 0:i._cubeSamplerName}, + ${null==i?void 0:i._vReflectionFilteringInfoName}, + #endif + #endif + #ifdef USEIRRADIANCEMAP + irradianceSampler, + #endif + #endif + #endif + #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) + surfaceAlbedo, + #endif + #ifdef SS_REFRACTION + ${r}.xyz, + viewDirectionW, + ${P}, + ${null!==(n=null==E?void 0:E._vRefractionInfosName)&&void 0!==n?n:""}, + ${null!==(o=null==E?void 0:E._refractionMatrixName)&&void 0!==o?o:""}, + ${null!==(l=null==E?void 0:E._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:""}, + vLightingIntensity, + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha, + #endif + #ifdef ${null!==(h=null==E?void 0:E._defineLODRefractionAlpha)&&void 0!==h?h:"IGNORE"} + NdotVUnclamped, + #endif + #ifdef ${null!==(c=null==E?void 0:E._defineLinearSpecularRefraction)&&void 0!==c?c:"IGNORE"} + roughness, + #endif + alphaG, + #ifdef ${null!==(u=null==E?void 0:E._define3DName)&&void 0!==u?u:"IGNORE"} + ${null!==(d=null==E?void 0:E._cubeSamplerName)&&void 0!==d?d:""}, + #else + ${null!==(_=null==E?void 0:E._2DSamplerName)&&void 0!==_?_:""}, + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${null!==(p=null==E?void 0:E._define3DName)&&void 0!==p?p:"IGNORE"} + ${null!==(f=null==E?void 0:E._cubeSamplerName)&&void 0!==f?f:""}, + ${null!==(m=null==E?void 0:E._cubeSamplerName)&&void 0!==m?m:""}, + #else + ${null!==(g=null==E?void 0:E._2DSamplerName)&&void 0!==g?g:""}, + ${null!==(v=null==E?void 0:E._2DSamplerName)&&void 0!==v?v:""}, + #endif + #endif + #ifdef ANISOTROPIC + anisotropicOut, + #endif + #ifdef REALTIME_FILTERING + ${null!==(x=null==E?void 0:E._vRefractionFilteringInfoName)&&void 0!==x?x:""}, + #endif + #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC + vRefractionPosition, + vRefractionSize, + #endif + #endif + #ifdef SS_TRANSLUCENCY + ${C}, + #endif + subSurfaceOut + ); + + #ifdef SS_REFRACTION + surfaceAlbedo = subSurfaceOut.surfaceAlbedo; + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha = subSurfaceOut.alpha; + #endif + #endif + #else + subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; + #endif +`}_buildBlock(e){return e.target===e_.Fragment&&e.sharedData.blocksWithDefines.push(this),this}};h["BABYLON.SubSurfaceBlock"]=SubSurfaceBlock;let a3={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};let PBRMetallicRoughnessBlock=class PBRMetallicRoughnessBlock extends NodeMaterialBlock{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?e_.Fragment:e_.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?e_.Fragment:e_.Vertex}constructor(e){super(e,e_.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=math_color_Color3.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",ed.Vector4,!1,e_.Vertex),this.registerInput("worldNormal",ed.Vector4,!1,e_.Fragment),this.registerInput("view",ed.Matrix,!1),this.registerInput("cameraPosition",ed.Vector3,!1,e_.Fragment),this.registerInput("perturbedNormal",ed.Vector4,!0,e_.Fragment),this.registerInput("baseColor",ed.Color3,!0,e_.Fragment),this.registerInput("metallic",ed.Float,!1,e_.Fragment),this.registerInput("roughness",ed.Float,!1,e_.Fragment),this.registerInput("ambientOcc",ed.Float,!0,e_.Fragment),this.registerInput("opacity",ed.Float,!0,e_.Fragment),this.registerInput("indexOfRefraction",ed.Float,!0,e_.Fragment),this.registerInput("ambientColor",ed.Color3,!0,e_.Fragment),this.registerInput("reflection",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("reflection",this,ef.Input,ReflectionBlock,"ReflectionBlock")),this.registerInput("clearcoat",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("clearcoat",this,ef.Input,ClearCoatBlock,"ClearCoatBlock")),this.registerInput("sheen",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("sheen",this,ef.Input,SheenBlock,"SheenBlock")),this.registerInput("subsurface",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("subsurface",this,ef.Input,SubSurfaceBlock,"SubSurfaceBlock")),this.registerInput("anisotropy",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("anisotropy",this,ef.Input,AnisotropyBlock,"AnisotropyBlock")),this.registerInput("iridescence",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("iridescence",this,ef.Input,IridescenceBlock,"IridescenceBlock")),this.registerOutput("ambientClr",ed.Color3,e_.Fragment),this.registerOutput("diffuseDir",ed.Color3,e_.Fragment),this.registerOutput("specularDir",ed.Color3,e_.Fragment),this.registerOutput("clearcoatDir",ed.Color3,e_.Fragment),this.registerOutput("sheenDir",ed.Color3,e_.Fragment),this.registerOutput("diffuseInd",ed.Color3,e_.Fragment),this.registerOutput("specularInd",ed.Color3,e_.Fragment),this.registerOutput("clearcoatInd",ed.Color3,e_.Fragment),this.registerOutput("sheenInd",ed.Color3,e_.Fragment),this.registerOutput("refraction",ed.Color3,e_.Fragment),this.registerOutput("lighting",ed.Color3,e_.Fragment),this.registerOutput("shadow",ed.Float,e_.Fragment),this.registerOutput("alpha",ed.Float,e_.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(ev.CameraPosition),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(ev.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));let r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",0>r.indexOf(".")?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);let s=e.getScene(),a=s.getEngine();if(a._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&&MaterialFlags.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){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};MaterialHelper.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else MaterialHelper.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,MaterialHelper.PrepareDefinesForMultiview(s,i)}}updateUniformsAndSamples(e,t,i,r){for(let s=0;s<t.maxSimultaneousLights&&i["LIGHT"+s];s++){let t=e.uniforms.indexOf("vLightData"+s)>=0;MaterialHelper.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}isReady(e,t,i){return(!this._environmentBRDFTexture||!!this._environmentBRDFTexture.isReady())&&(!i._areImageProcessingDirty||!t.imageProcessingConfiguration||!!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var r,s;if(!i)return;let a=i.getScene();this.light?MaterialHelper.BindLight(this.light,this._lightId,a,e,!0):MaterialHelper.BindLights(a,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);let n=this._scene.ambientColor;n&&e.setColor3("ambientFromScene",n);let o=a.useRightHandedSystem===(null!=a._mirroredCameraPosition);e.setFloat(this._invertNormalName,o?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);let l=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((l-1)/(l+1),2)*this._metallicF0Factor,TmpColors.Color3[0]);let h=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,TmpColors.Color3[0],h),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;let r=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));let a="v_"+r.associatedVariableName;e._emitVaryingFromString(a,"vec4")&&(e.compilationString+=`${a} = ${r.associatedVariableName}; +`);let n=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;n&&(n.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==n?void 0:n.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 +`,e._injectAtEnd+=`vClipSpacePosition = gl_Position; +`,e._injectAtEnd+=`#endif +`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:r.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${r.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e=`albedoOpacityOutParams albedoOpacityOut; +`,t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+`albedoOpacityBlock( + vec4(${t}, 1.), + #ifdef ALBEDO + vec4(1.), + vec2(1., 1.), + #endif + #ifdef OPACITY + vec4(${i}), + vec2(1., 1.), + #endif + albedoOpacityOut + ); + + vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; + float alpha = albedoOpacityOut.alpha; +`}_getAmbientOcclusionCode(){let e=`ambientOcclusionOutParams aoOut; +`,t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+`ambientOcclusionBlock( + #ifdef AMBIENT + vec3(${t}), + vec4(0., 1.0, 1.0, 0.), + #endif + aoOut + ); +`}_getReflectivityCode(e){let t=`reflectivityOutParams reflectivityOut; +`;return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo; + + reflectivityBlock( + vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.), + #ifdef METALLICWORKFLOW + surfaceAlbedo, + ${this._vMetallicReflectanceFactorsName}, + #endif + #ifdef REFLECTIVITY + vec3(0., 0., 1.), + vec4(1.), + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + aoOut.ambientOcclusionColor, + #endif + #ifdef MICROSURFACEMAP + microSurfaceTexel, <== not handled! + #endif + reflectivityOut + ); + + float microSurface = reflectivityOut.microSurface; + float roughness = reflectivityOut.roughness; + + #ifdef METALLICWORKFLOW + surfaceAlbedo = reflectivityOut.surfaceAlbedo; + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; + #endif +`}_buildBlock(e){var t,i,r,s,a,n,o,l,h,c,u,d,_,p,f,m,g,v,x,b,T,S,C,E,y,R,P,A,M,I,D,O,B,N,F,w,L,V,U,k,G;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this._scene));let 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!==e_.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);let W=`//${this.name}`,H=this.perturbedNormal,X=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(X=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${X}; +`,W),e.compilationString+=`${X} = ${this.worldPosition.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 +`,e.compilationString+=`vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0); +`,e.compilationString+=`#endif +`):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),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}); +`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${X}.xyz); +`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz; +`,e.compilationString+=`vec3 normalW = ${H.isConnected?"normalize("+H.associatedVariableName+".xyz)":"geometricNormalW"}; +`,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 + vec3 diffuseBase = vec3(1., 1., 1.); + #else +`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(r=null==z?void 0:z._defineSkyboxName)&&void 0!==r?r:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==z?void 0:z._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"}]});let Y=this.anisotropy.isConnected?null===(a=this.anisotropy.connectedPoint)||void 0===a?void 0:a.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!==(n=null==z?void 0:z._define3DName)&&void 0!==n?n:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(o=null==z?void 0:z._defineOppositeZ)&&void 0!==o?o:"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!==(u=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==u?u:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(d=null==z?void 0:z._vReflectionFilteringInfoName)&&void 0!==d?d:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",W,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});let j=this.sheen.isConnected?null===(_=this.sheen.connectedPoint)||void 0===_?void 0:_.ownerBlock:null;j&&(e.compilationString+=j.getCode(z)),e._emitFunctionFromInclude("pbrBlockSheen",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(p=null==z?void 0:z._define3DName)&&void 0!==p?p:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(f=null==z?void 0:z._defineSkyboxName)&&void 0!==f?f:"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"}]});let K=this.iridescence.isConnected?null===(v=this.iridescence.connectedPoint)||void 0===v?void 0:v.ownerBlock:null;e.compilationString+=IridescenceBlock.GetCode(K),e._emitFunctionFromInclude("pbrBlockIridescence",W,{replaceStrings:[]});let q=this.clearcoat.isConnected?null===(x=this.clearcoat.connectedPoint)||void 0===x?void 0:x.ownerBlock:null,$=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Q=this.perturbedNormal.isConnected&&(null===(T=(null===(b=this.perturbedNormal.connectedPoint)||void 0===b?void 0:b.ownerBlock).worldTangent)||void 0===T?void 0:T.isConnected),Z=this.anisotropy.isConnected&&(null===(S=this.anisotropy.connectedPoint)||void 0===S?void 0:S.ownerBlock).worldTangent.isConnected,J=Q||!this.perturbedNormal.isConnected&&Z;e.compilationString+=ClearCoatBlock.GetCode(e,q,z,X,$,J,this.worldNormal.associatedVariableName),$&&(J=null!==(C=null==q?void 0:q.worldTangent.isConnected)&&void 0!==C&&C),e._emitFunctionFromInclude("pbrBlockClearcoat",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(E=null==z?void 0:z._define3DName)&&void 0!==E?E:"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!==(R=null==z?void 0:z._defineProjectionName)&&void 0!==R?R:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(P=null==z?void 0:z._defineSkyboxName)&&void 0!==P?P:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(A=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==A?A:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(M=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==M?M:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:J?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(I=null==z?void 0:z._defineSkyboxName)&&void 0!==I?I:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(D=null==z?void 0:z._define3DName)&&void 0!==D?D:"REFLECTIONMAP_3D"}]});let ee=this.subsurface.isConnected?null===(O=this.subsurface.connectedPoint)||void 0===O?void 0:O.ownerBlock:null,et=this.subsurface.isConnected?null===(N=(null===(B=this.subsurface.connectedPoint)||void 0===B?void 0:B.ownerBlock).refraction.connectedPoint)||void 0===N?void 0:N.ownerBlock:null;et&&(et.viewConnectionPoint=this.view,et.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=SubSurfaceBlock.GetCode(e,ee,z,X),e._emitFunctionFromInclude("pbrBlockSubSurface",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(F=null==z?void 0:z._define3DName)&&void 0!==F?F:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(w=null==z?void 0:z._defineOppositeZ)&&void 0!==w?w:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(L=null==z?void 0:z._defineProjectionName)&&void 0!==L?L:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:null!==(V=null==et?void 0:et._define3DName)&&void 0!==V?V:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(U=null==et?void 0:et._defineLODRefractionAlpha)&&void 0!==U?U:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(k=null==et?void 0:et._defineLinearSpecularRefraction)&&void 0!==k?k:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(G=null==et?void 0:et._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()},{search:/vPositionW/g,replace:X+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{repeatKey:"maxSimultaneousLights",replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",W),e.compilationString+=`#endif +`;let ei=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",er=pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();for(let t of(-1===er.indexOf(".")&&(er+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",W,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:ei+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:er}]}),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.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]}),this._outputs))if(t.hasEndpoints){let i=a3[t.name];if(i){let[r,s]=i;s&&(e.compilationString+=`#if ${s} +`),e.compilationString+=`${this._declareOutput(t,e)} = ${r}; +`,s&&(e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(t,e)} = vec3(0.); +`,e.compilationString+=`#endif +`)}else console.error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lightFalloff = ${this.lightFalloff}; +${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest}; +${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff}; +${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending}; +${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha}; +${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha}; +${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing}; +${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering}; +${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality}; +${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation}; +${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion}; +${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion}; +${this._codeVariableName}.unlit = ${this.unlit}; +${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward}; +${this._codeVariableName}.debugMode = ${this.debugMode}; +${this._codeVariableName}.debugLimit = ${this.debugLimit}; +${this._codeVariableName}.debugFactor = ${this.debugFactor}; +`}serialize(){let 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 r,s;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=null!==(r=e.lightFalloff)&&void 0!==r?r: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()}};__decorate([editableInPropertyPage("Direct lights",em.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"directIntensity",void 0),__decorate([editableInPropertyPage("Environment lights",em.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"environmentIntensity",void 0),__decorate([editableInPropertyPage("Specular highlights",em.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"specularIntensity",void 0),__decorate([editableInPropertyPage("Light falloff",em.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF},{label:"Standard",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD}]})],PBRMetallicRoughnessBlock.prototype,"lightFalloff",void 0),__decorate([editableInPropertyPage("Alpha Testing",em.Boolean,"OPACITY")],PBRMetallicRoughnessBlock.prototype,"useAlphaTest",void 0),__decorate([editableInPropertyPage("Alpha CutOff",em.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"alphaTestCutoff",void 0),__decorate([editableInPropertyPage("Alpha blending",em.Boolean,"OPACITY")],PBRMetallicRoughnessBlock.prototype,"useAlphaBlending",void 0),__decorate([editableInPropertyPage("Radiance over alpha",em.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useRadianceOverAlpha",void 0),__decorate([editableInPropertyPage("Specular over alpha",em.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useSpecularOverAlpha",void 0),__decorate([editableInPropertyPage("Specular anti-aliasing",em.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"enableSpecularAntiAliasing",void 0),__decorate([editableInPropertyPage("Realtime filtering",em.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"realTimeFiltering",void 0),__decorate([editableInPropertyPage("Realtime filtering quality",em.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],PBRMetallicRoughnessBlock.prototype,"realTimeFilteringQuality",void 0),__decorate([editableInPropertyPage("Energy Conservation",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useEnergyConservation",void 0),__decorate([editableInPropertyPage("Radiance occlusion",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useRadianceOcclusion",void 0),__decorate([editableInPropertyPage("Horizon occlusion",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useHorizonOcclusion",void 0),__decorate([editableInPropertyPage("Unlit",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"unlit",void 0),__decorate([editableInPropertyPage("Force normal forward",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"forceNormalForward",void 0),__decorate([editableInPropertyPage("Generate only fragment code",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:PBRMetallicRoughnessBlock._OnGenerateOnlyFragmentCodeChanged}})],PBRMetallicRoughnessBlock.prototype,"generateOnlyFragmentCode",void 0),__decorate([editableInPropertyPage("Debug mode",em.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}]})],PBRMetallicRoughnessBlock.prototype,"debugMode",void 0),__decorate([editableInPropertyPage("Split position",em.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"debugLimit",void 0),__decorate([editableInPropertyPage("Output factor",em.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"debugFactor",void 0),h["BABYLON.PBRMetallicRoughnessBlock"]=PBRMetallicRoughnessBlock;let ModBlock=class ModBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}};h["BABYLON.ModBlock"]=ModBlock;let MatrixBuilderBlock=class MatrixBuilderBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("row0",ed.Vector4),this.registerInput("row1",ed.Vector4),this.registerInput("row2",ed.Vector4),this.registerInput("row3",ed.Vector4),this.registerOutput("output",ed.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){let e=new InputBlock("row0");e.value=new math_vector_Vector4(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){let e=new InputBlock("row1");e.value=new math_vector_Vector4(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){let e=new InputBlock("row2");e.value=new math_vector_Vector4(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){let e=new InputBlock("row3");e.value=new math_vector_Vector4(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.row0,r=this.row1,s=this.row2,a=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${r.associatedVariableName}, ${s.associatedVariableName}, ${a.associatedVariableName}); +`,this}};h["BABYLON.MatrixBuilder"]=MatrixBuilderBlock,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"}(tR||(tR={}));let ConditionalBlock=class ConditionalBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.condition=tR.LessThan,this.registerInput("a",ed.Float),this.registerInput("b",ed.Float),this.registerInput("true",ed.AutoDetect,!0),this.registerInput("false",ed.AutoDetect,!0),this.registerOutput("output",ed.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=ed.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);let t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case tR.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case tR.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case tR.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case tR.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case tR.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case tR.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case tR.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${r}; +`;break;case tR.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${r}; +`;break;case tR.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${r}; +`}return this}serialize(){let e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${tR[this.condition]}; +`;return e}};h["BABYLON.ConditionalBlock"]=ConditionalBlock;let CloudBlock=class CloudBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.octaves=6,this.registerInput("seed",ed.AutoDetect),this.registerInput("chaos",ed.AutoDetect,!0),this.registerInput("offsetX",ed.Float,!0),this.registerInput("offsetY",ed.Float,!0),this.registerInput("offsetZ",ed.Float,!0),this.registerOutput("output",ed.Float),this._inputs[0].acceptedConnectionPointTypes.push(ed.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(ed.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||!this._outputs[0].hasEndpoints)return;let r=` + + float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } + + // Based on Morgan McGuire @morgan3d + // https://www.shadertoy.com/view/4dS3Wd + float cloudNoise(in vec2 x, in vec2 chaos) { + vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); + + vec2 i = floor(x); + vec2 f = fract(x); + + float n = dot(i, step); + + vec2 u = f * f * (3.0 - 2.0 * f); + return mix( + mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), + mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), + u.y + ); + } + + float cloudNoise(in vec3 x, in vec3 chaos) { + vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); + + vec3 i = floor(x); + vec3 f = fract(x); + + float n = dot(i, step); + + vec3 u = f * f * (3.0 - 2.0 * f); + return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), + mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), + mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), + mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); + }`,s=` + float fbm(in vec2 st, in vec2 chaos) { + // Initial values + float value = 0.0; + float amplitude = .5; + float frequency = 0.; + + // Loop of octaves + for (int i = 0; i < OCTAVES; i++) { + value += amplitude * cloudNoise(st, chaos); + st *= 2.0; + amplitude *= 0.5; + } + return value; + } + + float fbm(in vec3 x, in vec3 chaos) { + // Initial values + float value = 0.0; + float amplitude = 0.5; + for (int i = 0; i < OCTAVES; ++i) { + value += amplitude * cloudNoise(x, chaos); + x = x * 2.0; + amplitude *= 0.5; + } + return value; + }`,a=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",r,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,s.replace(/fbm/gi,a).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");let n=e._getFreeVariableName("st"),o=(null===(t=this.seed.connectedPoint)||void 0===t?void 0:t.type)===ed.Vector2?"vec2":"vec3";e.compilationString+=`${o} ${n} = ${this.seed.associatedVariableName}; +`,this.offsetX.isConnected&&(e.compilationString+=`${n}.x += 0.1 * ${this.offsetX.associatedVariableName}; +`),this.offsetY.isConnected&&(e.compilationString+=`${n}.y += 0.1 * ${this.offsetY.associatedVariableName}; +`),this.offsetZ.isConnected&&"vec3"===o&&(e.compilationString+=`${n}.z += 0.1 * ${this.offsetZ.associatedVariableName}; +`);let l="";return l=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===ed.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${a}(${n}, ${l}); +`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves}; +`;return e}serialize(){let e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}};__decorate([editableInPropertyPage("Octaves",em.Int)],CloudBlock.prototype,"octaves",void 0),h["BABYLON.CloudBlock"]=CloudBlock;let VoronoiNoiseBlock=class VoronoiNoiseBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("seed",ed.Vector2),this.registerInput("offset",ed.Float),this.registerInput("density",ed.Float),this.registerOutput("output",ed.Float),this.registerOutput("cells",ed.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t=`vec2 voronoiRandom(vec2 seed, float offset){ + mat2 m = mat2(15.27, 47.63, 99.41, 89.98); + vec2 uv = fract(sin(m * seed) * 46839.32); + return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5); + } + `;e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ + vec2 g = floor(seed * density); + vec2 f = fract(seed * density); + float t = 8.0; + vec3 res = vec3(8.0, 0.0, 0.0); + + for(int y=-1; y<=1; y++) + { + for(int x=-1; x<=1; x++) + { + vec2 lattice = vec2(x,y); + vec2 randomOffset = voronoiRandom(lattice + g, offset); + float d = distance(lattice + randomOffset, f); + if(d < res.x) + { + res = vec3(d, randomOffset.x, randomOffset.y); + outValue = res.x; + cells = res.y; + } + } + } + } + `,e._emitFunction("voronoi",t,"// Voronoi");let i=e._getFreeVariableName("tempOutput"),r=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0; +`,e.compilationString+=`float ${r} = 0.0; +`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${r}); +`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; +`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${r}; +`),this}};h["BABYLON.VoronoiNoiseBlock"]=VoronoiNoiseBlock;let ElbowBlock=class ElbowBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.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(){let e=this._inputs[0];if(e.isConnected){let t=e.connectedPoint.ownerBlock;if(t.target!==e_.VertexAndFragment)return t.target;if(e.connectedPoint.target!==e_.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){(this._target&e)==0&&(this._target=e)}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName}; +`,this}};h["BABYLON.ElbowBlock"]=ElbowBlock;let TriPlanarBlock=class TriPlanarBlock extends NodeMaterialBlock{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;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:engineStore_EngineStore.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(){let 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)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:engineStore_EngineStore.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)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,e_.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",ed.AutoDetect,!1),this.registerInput("normal",ed.AutoDetect,!1),this.registerInput("sharpness",ed.Float,!0),this.registerInput("source",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,ef.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerInput("sourceY",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("sourceY",this,ef.Input,ImageSourceBlock,"ImageSourceBlock")),t||this.registerInput("sourceZ",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("sourceZ",this,ef.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("rgba",ed.Color4,e_.Neutral),this.registerOutput("rgb",ed.Color3,e_.Neutral),this.registerOutput("r",ed.Float,e_.Neutral),this.registerOutput("g",ed.Float,e_.Neutral),this.registerOutput("b",ed.Float,e_.Neutral),this.registerOutput("a",ed.Float,e_.Neutral),this.registerOutput("level",ed.Float,e_.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.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;let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){var t,i;let r=this.samplerName,s=null!==(t=this.samplerYName)&&void 0!==t?t:r,a=null!==(i=this.samplerZName)&&void 0!==i?i:r,n=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",o=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),c=e._getFreeVariableName("w"),u=e._getFreeVariableName("n"),d=e._getFreeVariableName("uvx"),_=e._getFreeVariableName("uvy"),p=e._getFreeVariableName("uvz");e.compilationString+=` + vec3 ${u} = ${this.normal.associatedVariableName}.xyz; + + vec2 ${d} = ${this.position.associatedVariableName}.yz; + vec2 ${_} = ${this.position.associatedVariableName}.zx; + vec2 ${p} = ${this.position.associatedVariableName}.xy; + `,this.projectAsCube&&(e.compilationString+=` + ${d}.xy = ${d}.yx; + + if (${u}.x >= 0.0) { + ${d}.x = -${d}.x; + } + if (${u}.y < 0.0) { + ${_}.y = -${_}.y; + } + if (${u}.z < 0.0) { + ${p}.x = -${p}.x; + } + `),e.compilationString+=` + vec4 ${o} = texture2D(${r}, ${d}); + vec4 ${l} = texture2D(${s}, ${_}); + vec4 ${h} = texture2D(${a}, ${p}); + + // blend weights + vec3 ${c} = pow(abs(${u}), vec3(${n})); + + // blend and return + vec4 ${this._tempTextureRead} = (${o}*${c}.x + ${l}*${c}.y + ${h}*${c}.z) / (${c}.x + ${c}.y + ${c}.z); + `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} + ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); + #endif + `),e.compilationString+=`#ifdef ${this._gammaDefineName} + ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); + #endif + `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r}; +`,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);let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e),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}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; +${this._codeVariableName}.projectAsCube = ${this.projectAsCube}; +`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let 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&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};__decorate([editableInPropertyPage("Project as cube",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],TriPlanarBlock.prototype,"projectAsCube",void 0),h["BABYLON.TriPlanarBlock"]=TriPlanarBlock;let BiPlanarBlock=class BiPlanarBlock extends TriPlanarBlock{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;let i=this.samplerName,r=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",a=e._getFreeVariableName("dpdx"),n=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),c=e._getFreeVariableName("me"),u=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),_=e._getFreeVariableName("y");e.compilationString+=` + // grab coord derivatives for texturing + vec3 ${a} = dFdx(${this.position.associatedVariableName}.xyz); + vec3 ${n} = dFdy(${this.position.associatedVariableName}.xyz); + vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz); + + // determine major axis (in x; yz are following axis) + ivec3 ${l} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) : + (${o}.y>${o}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine minor axis (in x; yz are following axis) + ivec3 ${h} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) : + (${o}.y<${o}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine median axis (in x; yz are following axis) + ivec3 ${c} = ivec3(3) - ${h} - ${l}; + + // project+fetch + vec4 ${u} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), + vec2(${a}[${l}.y],${a}[${l}.z]), + vec2(${n}[${l}.y],${n}[${l}.z]) ); + vec4 ${d} = textureGrad( ${r}, vec2( ${this.position.associatedVariableName}[${c}.y], ${this.position.associatedVariableName}[${c}.z]), + vec2(${a}[${c}.y],${a}[${c}.z]), + vec2(${n}[${c}.y],${n}[${c}.z]) ); + + // blend factors + vec2 ${_} = vec2(${o}[${l}.x],${o}[${c}.x]); + // make local support + ${_} = clamp( (${_}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); + // shape transition + ${_} = pow( ${_}, vec2(${s}/8.0) ); + // blend and return + vec4 ${this._tempTextureRead} = (${u}*${_}.x + ${d}*${_}.y) / (${_}.x + ${_}.y); + `}};h["BABYLON.BiPlanarBlock"]=BiPlanarBlock;let MatrixDeterminantBlock=class MatrixDeterminantBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.Matrix),this.registerOutput("output",ed.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName}); +`,this}};h["BABYLON.MatrixDeterminantBlock"]=MatrixDeterminantBlock;let MatrixTransposeBlock=class MatrixTransposeBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.Matrix),this.registerOutput("output",ed.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName}); +`,this}};h["BABYLON.MatrixTransposeBlock"]=MatrixTransposeBlock,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"}(tP||(tP={}));let MeshAttributeExistsBlock=class MeshAttributeExistsBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.attributeType=tP.None,this.registerInput("input",ed.AutoDetect),this.registerInput("fallback",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(e=>{var t;if(this.attributeType)return;let i=e.ownerBlock;if(i instanceof InputBlock&&i.isAttribute)switch(i.name){case"color":this.attributeType=tP.VertexColor;break;case"normal":this.attributeType=tP.Normal;break;case"tangent":this.attributeType=tP.Tangent;break;case"uv":this.attributeType=tP.UV1;break;case"uv2":this.attributeType=tP.UV2;break;case"uv3":this.attributeType=tP.UV3;break;case"uv4":this.attributeType=tP.UV4;break;case"uv5":this.attributeType=tP.UV5;break;case"uv6":this.attributeType=tP.UV6}else if(i instanceof MorphTargetsBlock)switch(null===(t=this.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":this.attributeType=tP.Normal;break;case"tangentOutput":this.attributeType=tP.Tangent;break;case"uvOutput":this.attributeType=tP.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 tP.VertexColor:t="VERTEXCOLOR_NME";break;case tP.Normal:t="NORMAL";break;case tP.Tangent:t="TANGENT";break;case tP.UV1:t="UV1";break;case tP.UV2:t="UV2";break;case tP.UV3:t="UV3";break;case tP.UV4:t="UV4";break;case tP.UV5:t="UV5";break;case tP.UV6:t="UV6"}let i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t} +`),e.compilationString+=`${i} = ${this.input.associatedVariableName}; +`,t&&(e.compilationString+=`#else +`,e.compilationString+=`${i} = ${this.fallback.associatedVariableName}; +`,e.compilationString+=`#endif +`),this}serialize(){let e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.attributeType=null!==(r=e.attributeType)&&void 0!==r?r:tP.None}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.attributeType = ${this.attributeType}; +`}};__decorate([editableInPropertyPage("Attribute lookup",em.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:tP.None},{label:"Normal",value:tP.Normal},{label:"Tangent",value:tP.Tangent},{label:"Vertex Color",value:tP.VertexColor},{label:"UV1",value:tP.UV1},{label:"UV2",value:tP.UV2},{label:"UV3",value:tP.UV3},{label:"UV4",value:tP.UV4},{label:"UV5",value:tP.UV5},{label:"UV6",value:tP.UV6}]})],MeshAttributeExistsBlock.prototype,"attributeType",void 0),h["BABYLON.MeshAttributeExistsBlock"]=MeshAttributeExistsBlock,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"}(tA||(tA={}));let CurveBlock=class CurveBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.type=tA.EaseInOutSine,this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ed.Object),this._inputs[0].excludedConnectionPointTypes.push(ed.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);let i=parseInt(t.replace("vec","")),r=` + vec${i} ret = vec${i}(0.0); + `;for(let t=1;t<=i;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+"return ret;\n"}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="",r="",s="";switch(this.input.type){case ed.Float:s="float";break;case ed.Vector2:s="vec2";break;case ed.Vector3:case ed.Color3:s="vec3";break;case ed.Vector4:case ed.Color4:s="vec4"}switch(r=tA[this.type]+"_"+s,this.type){case tA.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case tA.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case tA.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case tA.EaseInQuad:i="return v * v";break;case tA.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case tA.EaseInOutQuad:i=this._duplicateVector("VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0",s);break;case tA.EaseInCubic:i="return v * v * v";break;case tA.EaseOutCubic:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",s);break;case tA.EaseInOutCubic:i=this._duplicateVector("VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0",s);break;case tA.EaseInQuart:i="return v * v * v * v";break;case tA.EaseOutQuart:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",s);break;case tA.EaseInOutQuart:i=this._duplicateVector("VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0",s);break;case tA.EaseInQuint:i="return v * v * v * v * v";break;case tA.EaseOutQuint:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",s);break;case tA.EaseInOutQuint:i=this._duplicateVector("VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0",s);break;case tA.EaseInExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)",s);break;case tA.EaseOutExpo:i=this._duplicateVector("VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)",s);break;case tA.EaseInOutExpo:i=this._duplicateVector("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",s);break;case tA.EaseInCirc:i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",s);break;case tA.EaseOutCirc:i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",s);break;case tA.EaseInOutCirc:i=this._duplicateVector("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",s);break;case tA.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case tA.EaseOutBack:i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",s);break;case tA.EaseInOutBack:i=this._duplicateVector("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",s);break;case tA.EaseInElastic:i=this._duplicateVector("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))",s);break;case tA.EaseOutElastic:i=this._duplicateVector("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",s);break;case tA.EaseInOutElastic:i=this._duplicateVector("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",s)}return e._emitFunction(r,`${s} ${r}(${s} v) {${i};} +`,""),e.compilationString+=this._declareOutput(t,e)+` = ${r}(${this.input.associatedVariableName}); +`,this}serialize(){let e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${tA[this.type]}; +`;return e}};h["BABYLON.CurveBlock"]=CurveBlock;let DecalMapDefines=class DecalMapDefines extends MaterialDefines{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}};let DecalMapConfiguration=class DecalMapConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new DecalMapDefines,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,r){let s=r.getMesh().decalMap;return!this._isEnabled||null==s||!s.texture||!MaterialFlags.DecalMapEnabled||!t.texturesEnabled||s.isReady()}prepareDefines(e,t,i){let r=i.decalMap;if(this._isEnabled&&(null==r?void 0:r.texture)&&MaterialFlags.DecalMapEnabled&&t.texturesEnabled){let t=!e.DECAL||e.GAMMADECAL!==r.texture.gammaSpace;t&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=r.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,MaterialHelper.PrepareDefinesForMergedUV(r.texture,e,"DECAL")}else{let t=e.DECAL;t&&e.markAsTexturesDirty(),e.DECAL=!1}}hardBindForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;if(!this._isEnabled||!(null==s?void 0:s.texture)||!MaterialFlags.DecalMapEnabled||!t.texturesEnabled)return;let a=this._material.isFrozen,n=s.texture;e.useUbo&&a&&e.isSync||(e.updateFloat4("vDecalInfos",n.coordinatesIndex,0,0,0),MaterialHelper.BindTextureMatrix(n,e,"decal")),e.setTexture("decalSampler",n)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}};__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],DecalMapConfiguration.prototype,"isEnabled",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],DecalMapConfiguration.prototype,"smoothAlpha",void 0),h["BABYLON.DecalMapConfiguration"]=DecalMapConfiguration,function(e){e[e.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",e[e.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",e[e.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"}(tM||(tM={})),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"}(tI||(tI={})),function(e){e[e.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",e[e.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"}(tD||(tD={}));let greasedLineMaterialDefaults_GreasedLineMaterialDefaults=class greasedLineMaterialDefaults_GreasedLineMaterialDefaults{};greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR=math_color_Color3.White(),greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED=1,greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH=.1;let greasedLineTools_GreasedLineTools=class greasedLineTools_GreasedLineTools{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 math_vector_Vector3){let t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push(r.x,r.y,r.z)}return[t]}if(e.length>0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof math_vector_Vector3){let 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){let t=[];return e.forEach(e=>{t.push(Array.from(e))}),t}return[]}static OmitZeroLengthPredicate(e,t,i){let r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),0===r.length?null:r}static OmitDuplicatesPredicate(e,t,i,r){let s=[];return greasedLineTools_GreasedLineTools._SearchInPoints(e,t,r)||s.push([e,t]),greasedLineTools_GreasedLineTools._SearchInPoints(t,i,r)||s.push([t,i]),greasedLineTools_GreasedLineTools._SearchInPoints(i,e,r)||s.push([i,e]),0===s.length?null:s}static _SearchInPoints(e,t,i){var r,s,a;for(let n of i)for(let i=0;i<n.length;i++)if((null===(r=n[i])||void 0===r?void 0:r.equals(e))&&((null===(s=n[i+1])||void 0===s?void 0:s.equals(t))||(null===(a=n[i-1])||void 0===a?void 0:a.equals(t))))return!0;return!1}static MeshesToLines(e,t){let i=[];return e.forEach((e,r)=>{let s=e.getVerticesData(buffer_VertexBuffer.PositionKind),a=e.getIndices();if(s&&a)for(let n=0,o=0;n<a.length;n++){let l=3*a[o++],h=3*a[o++],c=3*a[o++],u=new math_vector_Vector3(s[l],s[l+1],s[l+2]),d=new math_vector_Vector3(s[h],s[h+1],s[h+2]),_=new math_vector_Vector3(s[c],s[c+1],s[c+2]);if(t){let o=t(u,d,_,i,n,l,e,r,s,a);if(o)for(let e of o)i.push(e)}else i.push([u,d],[d,_],[_,u])}}),i}static ToVector3Array(e){if(Array.isArray(e[0])){let t=[];for(let i of e){let e=[];for(let t=0;t<i.length;t+=3)e.push(new math_vector_Vector3(i[t],i[t+1],i[t+2]));t.push(e)}return t}let t=[];for(let i=0;i<e.length;i+=3)t.push(new math_vector_Vector3(e[i],e[i+1],e[i+2]));return t}static ToNumberArray(e){return e.flatMap(e=>[e.x,e.y,e.z])}static GetPointsCountInfo(e){let t=Array(e.length),i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){let t;if(0===e.length)return 0;t="number"==typeof e[0]?greasedLineTools_GreasedLineTools.ToVector3Array(e):e;let i=math_vector_TmpVectors.Vector3[0],r=0;for(let e=0;e<t.length-1;e++){let s=t[e],a=t[e+1];r+=a.subtractToRef(s,i).length()}return r}static SegmentizeSegmentByCount(e,t,i){let r=[],s=t.subtract(e),a=math_vector_TmpVectors.Vector3[0];a.setAll(i);let n=math_vector_TmpVectors.Vector3[1];s.divideToRef(a,n);let o=e.clone();r.push(o);for(let e=0;e<i;e++)r.push((o=o.clone()).addInPlace(n));return r}static SegmentizeLineBySegmentLength(e,t){let i=e[0]instanceof math_vector_Vector3?greasedLineTools_GreasedLineTools.GetLineSegments(e):"number"==typeof e[0]?greasedLineTools_GreasedLineTools.GetLineSegments(greasedLineTools_GreasedLineTools.ToVector3Array(e)):e,r=[];return i.forEach(e=>{if(e.length>t){let i=greasedLineTools_GreasedLineTools.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t));i.forEach(e=>{r.push(e)})}else r.push(e.point1),r.push(e.point2)}),r}static SegmentizeLineBySegmentCount(e,t){let i="number"==typeof e[0]?greasedLineTools_GreasedLineTools.ToVector3Array(e):e,r=greasedLineTools_GreasedLineTools.GetLineLength(i)/t;return greasedLineTools_GreasedLineTools.SegmentizeLineBySegmentLength(i,r)}static GetLineSegments(e){let t=[];for(let i=0;i<e.length-1;i++){let r=e[i],s=e[i+1],a=s.subtract(r).length();t.push({point1:r,point2:s,length:a})}return t}static GetMinMaxSegmentLength(e){let t=greasedLineTools_GreasedLineTools.GetLineSegments(e),i=t.sort(e=>e.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){let s=t*i,a=0,n=0,o=e.length;for(let t=0;t<o;t++){if(s<=a+e[t].length){n=t;break}a+=e[t].length}let l=(s-a)/e[n].length;return e[n].point2.subtractToRef(e[n].point1,math_vector_TmpVectors.Vector3[0]),math_vector_TmpVectors.Vector3[1]=math_vector_TmpVectors.Vector3[0].multiplyByFloats(l,l,l),r||math_vector_TmpVectors.Vector3[1].addInPlace(e[n].point1),math_vector_TmpVectors.Vector3[1].clone()}static GetCircleLinePoints(e,t,i=0,r=e,s=2*Math.PI/t){let a=[];for(let n=0;n<=t;n++)a.push(new math_vector_Vector3(Math.cos(n*s)*e,Math.sin(n*s)*r,i));return a}static GetBezierLinePoints(e,t,i,r){return Curve3.CreateQuadraticBezier(e,t,i,r).getPoints().flatMap(e=>[e.x,e.y,e.z])}static GetArrowCap(e,t,i,r,s,a=0,n=0){let o=[e.clone(),e.add(t.multiplyByFloats(i,i,i))];return{points:o,widths:[r,s,a,n]}}static GetPointsFromText(e,t,i,r,s=0,a=!0){let n=[],o=CreateTextShapePaths(e,t,i,r);for(let e of o){for(let t of e.paths){let e=[],i=t.getPoints();for(let t of i)e.push(t.x,t.y,s);n.push(e)}if(a)for(let t of e.holes){let e=[],i=t.getPoints();for(let t of i)e.push(t.x,t.y,s);n.push(e)}}return n}static Color3toRGBAUint8(e){let t=new Uint8Array(4*e.length);for(let i=0,r=0;i<e.length;i++)t[r++]=255*e[i].r,t[r++]=255*e[i].g,t[r++]=255*e[i].b,t[r++]=255;return t}static CreateColorsTexture(e,t,i,r){let s=greasedLineTools_GreasedLineTools.Color3toRGBAUint8(t),a=new rawTexture_RawTexture(s,t.length,1,engine_Engine.TEXTUREFORMAT_RGBA,r,!1,!0,i);return a.name=e,a}static PrepareEmptyColorsTexture(e){if(!greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture){let t=new Uint8Array(4);greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture=new rawTexture_RawTexture(t,1,1,engine_Engine.TEXTUREFORMAT_RGBA,e,!1,!1,rawTexture_RawTexture.NEAREST_NEAREST),greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture.name="grlEmptyColorsTexture"}}static DisposeEmptyColorsTexture(){var e;null===(e=greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture)||void 0===e||e.dispose(),greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}};let MaterialGreasedLineDefines=class MaterialGreasedLineDefines extends MaterialDefines{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1,this.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=!1,this.GREASED_LINE_CAMERA_FACING=!0}};let greasedLinePluginMaterial_GreasedLinePluginMaterial=class greasedLinePluginMaterial_GreasedLinePluginMaterial extends MaterialPluginBase{constructor(e,t,i){var r,s,a,n,o,l,h,c,u,d,_,p,f,m,g,v,x;i=i||{color:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR};let b=new MaterialGreasedLineDefines;b.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,b.GREASED_LINE_SIZE_ATTENUATION=null!==(r=i.sizeAttenuation)&&void 0!==r&&r,b.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===tD.COLOR_DISTRIBUTION_TYPE_LINE,b.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(null!=t?t:e.getScene()).useRightHandedSystem,b.GREASED_LINE_CAMERA_FACING=null===(s=i.cameraFacing)||void 0===s||s,super(e,greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME,200,b),this.colorsTexture=null,this._scene=null!=t?t:e.getScene(),this._engine=this._scene.getEngine(),this._cameraFacing=null===(a=i.cameraFacing)||void 0===a||a,this.visibility=null!==(n=i.visibility)&&void 0!==n?n:1,this.useDash=null!==(o=i.useDash)&&void 0!==o&&o,this.dashRatio=null!==(l=i.dashRatio)&&void 0!==l?l:.5,this.dashOffset=null!==(h=i.dashOffset)&&void 0!==h?h:0,this.width=i.width?i.width:i.sizeAttenuation?greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH,this._sizeAttenuation=null!==(c=i.sizeAttenuation)&&void 0!==c&&c,this.colorMode=null!==(u=i.colorMode)&&void 0!==u?u:tI.COLOR_MODE_SET,this._color=null!==(d=i.color)&&void 0!==d?d:null,this.useColors=null!==(_=i.useColors)&&void 0!==_&&_,this._colorsDistributionType=null!==(p=i.colorDistributionType)&&void 0!==p?p:tD.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=null!==(f=i.colorsSampling)&&void 0!==f?f:rawTexture_RawTexture.NEAREST_NEAREST,this._colors=null!==(m=i.colors)&&void 0!==m?m:null,this.dashCount=null!==(g=i.dashCount)&&void 0!==g?g:1,this.resolution=null!==(v=i.resolution)&&void 0!==v?v:new math_vector_Vector2(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=null!==(x=this._color)&&void 0!==x?x:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR,greasedLineTools_GreasedLineTools.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add(()=>{greasedLineTools_GreasedLineTools.DisposeEmptyColorsTexture()}),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){let e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?` + uniform vec4 grl_aspect_resolution_lineWidth; + uniform mat4 grl_projection; + `:"",fragment:` + uniform vec4 grl_dashOptions; + uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; + uniform vec3 grl_singleColor; + `}}get isEnabled(){return!0}bindForSubMesh(e){var t;if(this._cameraFacing){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}else throw Error("GreasedLinePluginMaterial requires an active camera.");let i=math_vector_TmpVectors.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}let i=math_vector_TmpVectors.Vector4[0];i.x=greasedLineTools_GreasedLineTools.BooleanToNumber(this.useDash),i.y=this._dashArray,i.z=this.dashOffset,i.w=this.dashRatio,e.updateVector4("grl_dashOptions",i);let r=math_vector_TmpVectors.Vector4[1];r.x=this.colorMode,r.y=this.visibility,r.z=this.colorsTexture?this.colorsTexture.getSize().width:0,r.w=greasedLineTools_GreasedLineTools.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",r),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",null!==(t=this.colorsTexture)&&void 0!==t?t:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===tD.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){let e={CUSTOM_VERTEX_DEFINITIONS:` + attribute float grl_widths; + attribute vec3 grl_offsets; + attribute float grl_colorPointers; + + varying float grlCounters; + varying float grlColorPointer; + + #ifdef GREASED_LINE_CAMERA_FACING + attribute vec4 grl_previousAndSide; + attribute vec4 grl_nextAndCounters; + + vec2 grlFix( vec4 i, float aspect ) { + vec2 res = i.xy / i.w; + res.x *= aspect; + return res; + } + #else + attribute vec3 grl_slopes; + attribute float grl_counters; + #endif + `,CUSTOM_VERTEX_UPDATE_POSITION:` + #ifdef GREASED_LINE_CAMERA_FACING + vec3 grlPositionOffset = grl_offsets; + positionUpdated += grlPositionOffset; + #else + positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths); + #endif + `,CUSTOM_VERTEX_MAIN_END:` + grlColorPointer = grl_colorPointers; + + #ifdef GREASED_LINE_CAMERA_FACING + + float grlAspect = grl_aspect_resolution_lineWidth.x; + float grlBaseWidth = grl_aspect_resolution_lineWidth.w; + + + vec3 grlPrevious = grl_previousAndSide.xyz; + float grlSide = grl_previousAndSide.w; + + vec3 grlNext = grl_nextAndCounters.xyz; + grlCounters = grl_nextAndCounters.w; + + mat4 grlMatrix = viewProjection * finalWorld; + vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 ); + vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 ); + vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 ); + + vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect ); + vec2 grlPrevP = grlFix( grlPrevPos, grlAspect ); + vec2 grlNextP = grlFix( grlNextPos, grlAspect ); + + float grlWidth = grlBaseWidth * grl_widths; + + vec2 grlDir; + if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP ); + else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP ); + else { + vec2 grlDir1 = normalize( grlCurrentP - grlPrevP ); + vec2 grlDir2 = normalize( grlNextP - grlCurrentP ); + grlDir = normalize( grlDir1 + grlDir2 ); + } + vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. ); + #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM + grlNormal.xy *= -.5 * grlWidth; + #else + grlNormal.xy *= .5 * grlWidth; + #endif + + grlNormal *= grl_projection; + + #ifdef GREASED_LINE_SIZE_ATTENUATION + grlNormal.xy *= grlFinalPosition.w; + grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy; + #endif + + grlFinalPosition.xy += grlNormal.xy * grlSide; + gl_Position = grlFinalPosition; + + vPositionW = vec3(grlFinalPosition); + #else + grlCounters = grl_counters; + #endif + `};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:` + varying float grlCounters; + varying float grlColorPointer; + uniform sampler2D grl_colors; + `,CUSTOM_FRAGMENT_MAIN_END:` + float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; + float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; + float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; + float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; + + float grlUseDash = grl_dashOptions.x; + float grlDashArray = grl_dashOptions.y; + float grlDashOffset = grl_dashOptions.z; + float grlDashRatio = grl_dashOptions.w; + + gl_FragColor.a *= step(grlCounters, grlVisibility); + if( gl_FragColor.a == 0. ) discard; + + if(grlUseDash == 1.){ + gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); + if (gl_FragColor.a == 0.) discard; + } + + #ifdef GREASED_LINE_HAS_COLOR + if (grlColorMode == ${tI.COLOR_MODE_SET}.) { + gl_FragColor.rgb = grl_singleColor; + } else if (grlColorMode == ${tI.COLOR_MODE_ADD}.) { + gl_FragColor.rgb += grl_singleColor; + } else if (grlColorMode == ${tI.COLOR_MODE_MULTIPLY}.) { + gl_FragColor.rgb *= grl_singleColor; + } + #else + if (grlUseColors == 1.) { + #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE + vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); + #else + vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.); + #endif + if (grlColorMode == ${tI.COLOR_MODE_SET}.) { + gl_FragColor = grlColor; + } else if (grlColorMode == ${tI.COLOR_MODE_ADD}.) { + gl_FragColor += grlColor; + } else if (grlColorMode == ${tI.COLOR_MODE_MULTIPLY}.) { + gl_FragColor *= grlColor; + } + } + #endif + + `}:null}dispose(){var e;null===(e=this.colorsTexture)||void 0===e||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,a,n;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(a=this.colorsTexture)||void 0===a||a.dispose();return}if(!t||i){if(this.colorsTexture&&o===e.length&&!i){let t=greasedLineTools_GreasedLineTools.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else null===(n=this.colorsTexture)||void 0===n||n.dispose(),this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,t||this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r;super.parse(e,t,i);let s=e.greasedLineMaterialOptions;null===(r=this.colorsTexture)||void 0===r||r.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):greasedLineTools_GreasedLineTools.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var t;null===(t=e.colorsTexture)||void 0===t||t.dispose(),this._colors&&(e.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${e._material.name}-colors-texture`,this._colors,e.colorsSampling,this._scene)),e.setColor(this.color,!0),e.colorsDistributionType=this.colorsDistributionType,e.colorsSampling=this.colorsSampling,e.colorMode=this.colorMode,e.useColors=this.useColors,e.visibility=this.visibility,e.useDash=this.useDash,e.dashCount=this.dashCount,e.dashRatio=this.dashRatio,e.dashOffset=this.dashOffset,e.width=this.width,e.sizeAttenuation=this.sizeAttenuation,e.resolution=this.resolution,e.markAllDefinesAsDirty()}};greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",h[`BABYLON.${greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}`]=greasedLinePluginMaterial_GreasedLinePluginMaterial;let a4=`precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} +if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { +textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} +if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}} +`;ShaderStore.ShadersStore.greasedLinePixelShader=a4;let a5=`precision highp float; +#include<instancesDeclaration> +attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer; +#ifdef GREASED_LINE_CAMERA_FACING +attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} +#else +attribute vec3 grl_slopes;attribute float grl_counters; +#endif +void main() { +#include<instancesVertex> +grlColorPointer=grl_colorPointers; +#ifdef GREASED_LINE_CAMERA_FACING +float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=viewProjection*finalWorld ;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );} +vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); +#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM +grlNormal.xy*=-.5*grlWidth; +#else +grlNormal.xy*=.5*grlWidth; +#endif +grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} +grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition; +#else +grlCounters=grl_counters;vec4 grlFinalPosition=worldViewProjection*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition; +#endif +} +`;ShaderStore.ShadersStore.greasedLineVertexShader=a5;let greasedLineSimpleMaterial_GreasedLineSimpleMaterial=class greasedLineSimpleMaterial_GreasedLineSimpleMaterial extends shaderMaterial_ShaderMaterial{constructor(e,t,i){var r,s,a,n,o,l,h,c,u,d,_,p,f,m;let g=[`COLOR_DISTRIBUTION_TYPE_LINE ${tD.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${tD.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${tI.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${tI.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${tI.COLOR_MODE_MULTIPLY}.`],v=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&g.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(g.push("GREASED_LINE_CAMERA_FACING"),v.push("grl_previousAndSide","grl_nextAndCounters")):(v.push("grl_slopes"),v.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:v,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:g}),this._color=math_color_Color3.White(),this._colorsDistributionType=tD.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR};let x=t.getEngine();this.visibility=null!==(r=i.visibility)&&void 0!==r?r:1,this.useDash=null!==(s=i.useDash)&&void 0!==s&&s,this.dashRatio=null!==(a=i.dashRatio)&&void 0!==a?a:.5,this.dashOffset=null!==(n=i.dashOffset)&&void 0!==n?n:0,this.dashCount=null!==(o=i.dashCount)&&void 0!==o?o:1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH,this.sizeAttenuation=null!==(l=i.sizeAttenuation)&&void 0!==l&&l,this.color=null!==(h=i.color)&&void 0!==h?h:math_color_Color3.White(),this.useColors=null!==(c=i.useColors)&&void 0!==c&&c,this.colorsDistributionType=null!==(u=i.colorDistributionType)&&void 0!==u?u:tD.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=null!==(d=i.colorsSampling)&&void 0!==d?d:rawTexture_RawTexture.NEAREST_NEAREST,this.colorMode=null!==(_=i.colorMode)&&void 0!==_?_:tI.COLOR_MODE_SET,this._colors=null!==(p=i.colors)&&void 0!==p?p:null,this._cameraFacing=null===(f=i.cameraFacing)||void 0===f||f,this.resolution=null!==(m=i.resolution)&&void 0!==m?m:new math_vector_Vector2(x.getRenderWidth(),x.getRenderHeight()),i.colorsTexture&&(this.colorsTexture=i.colorsTexture),this._colors&&this.setColors(this._colors),x.onDisposeObservable.add(()=>{greasedLineTools_GreasedLineTools.DisposeEmptyColorsTexture()})}dispose(){var e;null===(e=this._colorsTexture)||void 0===e||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new math_vector_Vector2(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,a,n;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(a=this._colorsTexture)||void 0===a||a.dispose();return}if(!t||i){if(this._colorsTexture&&o===e.length&&!i){let t=greasedLineTools_GreasedLineTools.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else null===(n=this._colorsTexture)||void 0===n||n.dispose(),this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}}get colorsTexture(){var e;return null!==(e=this._colorsTexture)&&void 0!==e?e:null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=null!=e?e:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r,s;let a=e.greasedLineMaterialOptions;null===(r=this._colorsTexture)||void 0===r||r.dispose(),a.color&&(this.color=a.color),a.colorDistributionType&&(this.colorsDistributionType=a.colorDistributionType),a.colorsSampling&&(this.colorsSampling=a.colorsSampling),a.colorMode&&(this.colorMode=a.colorMode),a.useColors&&(this.useColors=a.useColors),a.visibility&&(this.visibility=a.visibility),a.useDash&&(this.useDash=a.useDash),a.dashCount&&(this.dashCount=a.dashCount),a.dashRatio&&(this.dashRatio=a.dashRatio),a.dashOffset&&(this.dashOffset=a.dashOffset),a.width&&(this.width=a.width),a.sizeAttenuation&&(this.sizeAttenuation=a.sizeAttenuation),a.resolution&&(this.resolution=a.resolution),a.colors?this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`,a.colors,this.colorsSampling,this.getScene()):greasedLineTools_GreasedLineTools.PrepareEmptyColorsTexture(t),this._cameraFacing=null===(s=a.cameraFacing)||void 0===s||s,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}};let a6=`#if defined(DBG_ENABLED) +attribute float dbg_initialPass; +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; +#endif`,a8=`#if defined(DBG_ENABLED) +float dbg_vertexIndex = mod(float(gl_VertexID), 3.); +if (dbg_vertexIndex == 0.0) { + dbg_vBarycentric = vec3(1.,0.,0.); +} +else if (dbg_vertexIndex == 1.0) { + dbg_vBarycentric = vec3(0.,1.,0.); +} +else { + dbg_vBarycentric = vec3(0.,0.,1.); +} + +dbg_vVertexWorldPos = vPositionW; +dbg_vPass = dbg_initialPass; +#endif`,a7=`#if defined(DBG_ENABLED) +uniform vec3 dbg_shadedDiffuseColor; +uniform vec4 dbg_shadedSpecularColorPower; +uniform vec3 dbg_thicknessRadiusScale; + +#if DBG_MODE == 2 || DBG_MODE == 3 + uniform vec3 dbg_vertexColor; +#endif + +#if DBG_MODE == 1 + uniform vec3 dbg_wireframeTrianglesColor; +#elif DBG_MODE == 3 + uniform vec3 dbg_wireframeVerticesColor; +#elif DBG_MODE == 4 || DBG_MODE == 5 + uniform vec3 dbg_uvPrimaryColor; + uniform vec3 dbg_uvSecondaryColor; +#elif DBG_MODE == 7 + uniform vec3 dbg_materialColor; +#endif +#endif`,a9=`#if defined(DBG_ENABLED) +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; + +#if !defined(DBG_MULTIPLY) + vec3 dbg_applyShading(vec3 color) { + vec3 N = vNormalW.xyz; + vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); + vec3 H = normalize(L + L); + float LdotN = clamp(dot(L,N), 0., 1.); + float HdotN = clamp(dot(H,N), 0., 1.); + float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); + color *= (LdotN / PI); + color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); + return color; + } +#endif + +#if DBG_MODE == 1 || DBG_MODE == 3 + float dbg_edgeFactor() { + vec3 d = fwidth(dbg_vBarycentric); + vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); + return min(min(a3.x, a3.y), a3.z); + } +#endif + +#if DBG_MODE == 2 || DBG_MODE == 3 + float dbg_cornerFactor() { + vec3 worldPos = vPositionW; + float dist = length(worldPos - dbg_vVertexWorldPos); + float camDist = length(worldPos - vEyePosition.xyz); + float d = sqrt(camDist) * .001; + return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); + } +#endif + +#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) + float dbg_checkerboardFactor(vec2 uv) { + vec2 f = fract(uv * dbg_thicknessRadiusScale.z); + f -= .5; + return (f.x * f.y) > 0. ? 1. : 0.; + } +#endif +#endif`,ne=`#if defined(DBG_ENABLED) +vec3 dbg_color = vec3(1.); +#if DBG_MODE == 1 + dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); +#elif DBG_MODE == 2 || DBG_MODE == 3 + float dbg_cornerFactor = dbg_cornerFactor(); + if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; + dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); + #if DBG_MODE == 3 + dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); + #endif +#elif DBG_MODE == 4 && defined(UV1) + dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); +#elif DBG_MODE == 5 && defined(UV2) + dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); +#elif DBG_MODE == 6 && defined(VERTEXCOLOR) + dbg_color = vColor.rgb; +#elif DBG_MODE == 7 + dbg_color = dbg_materialColor; +#endif + +#if defined(DBG_MULTIPLY) + gl_FragColor *= vec4(dbg_color, 1.); +#else + #if DBG_MODE != 6 + gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); + #else + gl_FragColor = vec4(dbg_color, 1.); + #endif +#endif +#endif`,nt=[new math_color_Color3(.98,.26,.38),new math_color_Color3(.47,.75,.3),new math_color_Color3(0,.26,.77),new math_color_Color3(.97,.6,.76),new math_color_Color3(.19,.63,.78),new math_color_Color3(.98,.8,.6),new math_color_Color3(.65,.43,.15),new math_color_Color3(.15,.47,.22),new math_color_Color3(.67,.71,.86),new math_color_Color3(.09,.46,.56),new math_color_Color3(.8,.98,.02),new math_color_Color3(.39,.29,.13),new math_color_Color3(.53,.63,.06),new math_color_Color3(.95,.96,.41),new math_color_Color3(1,.72,.94),new math_color_Color3(.63,.08,.31),new math_color_Color3(.66,.96,.95),new math_color_Color3(.22,.14,.19),new math_color_Color3(.14,.65,.59),new math_color_Color3(.93,1,.68),new math_color_Color3(.93,.14,.44),new math_color_Color3(.47,.86,.67),new math_color_Color3(.85,.07,.78),new math_color_Color3(.53,.64,.98),new math_color_Color3(.43,.37,.56),new math_color_Color3(.71,.65,.25),new math_color_Color3(.66,.19,.01),new math_color_Color3(.94,.53,.12),new math_color_Color3(.41,.44,.44),new math_color_Color3(.24,.71,.96),new math_color_Color3(.57,.28,.56),new math_color_Color3(.44,.98,.42)];!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(tO||(tO={}));let MeshDebugDefines=class MeshDebugDefines extends MaterialDefines{constructor(){super(...arguments),this.DBG_MODE=tO.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}};let MeshDebugPluginMaterial=class MeshDebugPluginMaterial extends MaterialPluginBase{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){var i,r,s,a,n,o,l,h,c,u,d,_,p;let f=new MeshDebugDefines;f.DBG_MODE=null!==(i=t.mode)&&void 0!==i?i:f.DBG_MODE,f.DBG_MULTIPLY=null!==(r=t.multiply)&&void 0!==r?r:f.DBG_MULTIPLY,super(e,"MeshDebug",200,f,!0,!0),this._mode=f.DBG_MODE,this._multiply=f.DBG_MULTIPLY,this.shadedDiffuseColor=null!==(s=t.shadedDiffuseColor)&&void 0!==s?s:new math_color_Color3(1,1,1),this.shadedSpecularColor=null!==(a=t.shadedSpecularColor)&&void 0!==a?a:new math_color_Color3(.8,.8,.8),this.shadedSpecularPower=null!==(n=t.shadedSpecularPower)&&void 0!==n?n:10,this.wireframeThickness=null!==(o=t.wireframeThickness)&&void 0!==o?o:.7,this.wireframeTrianglesColor=null!==(l=t.wireframeTrianglesColor)&&void 0!==l?l:new math_color_Color3(0,0,0),this.wireframeVerticesColor=null!==(h=t.wireframeVerticesColor)&&void 0!==h?h:new math_color_Color3(.8,.8,.8),this.vertexColor=null!==(c=t.vertexColor)&&void 0!==c?c:new math_color_Color3(0,0,0),this.vertexRadius=null!==(u=t.vertexRadius)&&void 0!==u?u:1.2,this.uvScale=null!==(d=t.uvScale)&&void 0!==d?d:20,this.uvPrimaryColor=null!==(_=t.uvPrimaryColor)&&void 0!==_?_:new math_color_Color3(1,1,1),this.uvSecondaryColor=null!==(p=t.uvSecondaryColor)&&void 0!==p?p:new math_color_Color3(.5,.5,.5),this._materialColor=MeshDebugPluginMaterial.MaterialColors[MeshDebugPluginMaterial._PluginCount++%MeshDebugPluginMaterial.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().webGLVersion){logger_Logger.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=tO.VERTICES&&this._mode!=tO.TRIANGLES&&this._mode!=tO.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||logger_Logger.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:a7}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:a6,CUSTOM_VERTEX_MAIN_END:a8}:{CUSTOM_FRAGMENT_DEFINITIONS:a9,CUSTOM_FRAGMENT_MAIN_END:ne}}static Reset(){this._PluginCount=0,this.MaterialColors=nt}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let rollback=()=>{};if(0==e.getTotalIndices())return rollback;if(t){let t=e.getVerticesDataKinds(),i=e.getIndices(),r={};for(let i of t)r[i]=e.getVerticesData(i);rollback=function(){for(let s of(e.setIndices(i),t)){let t=e.getVertexBuffer(s).getStrideSize();e.setVerticesData(s,r[s],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let i=Array.from(e.getIndices()),r=[];for(let e=0;e<i.length;e+=3)r.push(i[e+1],i[e+2],i[e+0]);e.setIndices(i.concat(r)),e.convertToUnIndexedMesh(),e.isUnIndexed=!1,i=Array.from(e.getIndices());let s=[];for(let e=i.length/2;e<i.length;e+=3)s.push(i[e+1],i[e+2],i[e+0]);e.setIndices(i.concat(s));let a=e.getTotalVertices(),n=a/2,o=Array(a).fill(1,0,n).fill(0,n,a);return e.setVerticesData("dbg_initialPass",o,!1,1),rollback}};function createDecoderAsync(e){return new Promise(t=>{DracoDecoderModule({wasmBinary:e}).then(e=>{t({module:e})})})}function decodeMesh(e,t,i,r,s){let a=null,n=null,o=null;try{let l;a=new e.Decoder,(n=new e.DecoderBuffer).Init(t,t.byteLength);let h=a.GetEncodedGeometryType(n);switch(h){case e.TRIANGULAR_MESH:{let t=new e.Mesh;if(!(l=a.DecodeBufferToMesh(n,t)).ok()||0===t.ptr)throw Error(l.error_msg());let i=t.num_faces(),s=3*i,h=4*s,c=e._malloc(h);try{a.GetTrianglesUInt32Array(t,h,c);let i=new Uint32Array(s);i.set(new Uint32Array(e.HEAPF32.buffer,c,s)),r(i)}finally{e._free(c)}o=t;break}case e.POINT_CLOUD:{let t=new e.PointCloud;if(!(l=a.DecodeBufferToPointCloud(n,t)).ok()||!t.ptr)throw Error(l.error_msg());o=t;break}default:throw Error(`Invalid geometry type ${h}`)}let c=o.num_points(),processAttribute=(t,i,r,a)=>{let n=a.data_type(),o=a.num_components(),l=a.normalized(),h=a.byte_stride(),u=a.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}},_=d[n];if(!_)throw Error(`Invalid data type ${n}`);let p=c*o,f=p*_.typedArrayConstructor.BYTES_PER_ELEMENT,m=e._malloc(f);try{t.GetAttributeDataArrayForAllPoints(i,a,n,f,m);let e=new _.typedArrayConstructor(_.heap.buffer,m,p);s(r,e.slice(),o,u,h,l)}finally{e._free(m)}};if(i)for(let e in i){let t=i[e],r=a.GetAttributeByUniqueId(o,t);processAttribute(a,o,e,r)}else{let t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(let e in t){let i=a.GetAttributeId(o,t[e]);if(-1!==i){let t=a.GetAttribute(o,i);processAttribute(a,o,e,t)}}}return c}finally{o&&e.destroy(o),n&&e.destroy(n),a&&e.destroy(a)}}function worker(){let e;onmessage=t=>{let i=t.data;switch(i.id){case"init":{let t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw Error("Draco decoder module is not available");e.then(e=>{let t=decodeMesh(e,i.dataView,i.attributes,e=>{postMessage({id:"indices",data:e},[e.buffer])},(e,t,i,r,s,a)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:r,byteStride:s,normalized:a},[t.buffer])});postMessage({id:"decodeMeshDone",totalVertices:t})})}}}MeshDebugPluginMaterial._PluginCount=0,MeshDebugPluginMaterial.MaterialColors=nt,__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"_materialColor",void 0),__decorate([serialize()],MeshDebugPluginMaterial.prototype,"_isEnabled",void 0),__decorate([serialize(),expandToProperty("_markAllDefinesAsDirty")],MeshDebugPluginMaterial.prototype,"mode",void 0),__decorate([serialize(),expandToProperty("_markAllDefinesAsDirty")],MeshDebugPluginMaterial.prototype,"multiply",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"shadedDiffuseColor",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"shadedSpecularColor",void 0),__decorate([serialize()],MeshDebugPluginMaterial.prototype,"shadedSpecularPower",void 0),__decorate([serialize()],MeshDebugPluginMaterial.prototype,"wireframeThickness",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"wireframeTrianglesColor",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"wireframeVerticesColor",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"vertexColor",void 0),__decorate([serialize()],MeshDebugPluginMaterial.prototype,"vertexRadius",void 0),__decorate([serialize()],MeshDebugPluginMaterial.prototype,"uvScale",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"uvPrimaryColor",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"uvSecondaryColor",void 0),h["BABYLON.MeshDebugPluginMaterial"]=MeshDebugPluginMaterial,Object.defineProperty(standardMaterial_StandardMaterial.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new DecalMapConfiguration(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(pbrBaseMaterial_PBRBaseMaterial.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new DecalMapConfiguration(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});let DracoCompression=class DracoCompression{static get DecoderAvailable(){let e=DracoCompression.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 DracoCompression._Default||(DracoCompression._Default=new DracoCompression),DracoCompression._Default}constructor(e=DracoCompression.DefaultNumWorkers){let t=DracoCompression.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:tools_Tools.GetBabylonScriptURL(t.wasmUrl,!0),wasmBinaryPromise:tools_Tools.LoadFileAsync(tools_Tools.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:tools_Tools.GetBabylonScriptURL(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then(t=>{let r=`${decodeMesh}(${worker})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));return new AutoReleaseWorkerPool(e,()=>new Promise((e,r)=>{let a=new Worker(s),onError=e=>{a.removeEventListener("error",onError),a.removeEventListener("message",onMessage),r(e)},onMessage=t=>{"initDone"===t.data.id&&(a.removeEventListener("error",onError),a.removeEventListener("message",onMessage),e(a))};a.addEventListener("error",onError),a.addEventListener("message",onMessage),a.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))}):this._decoderModulePromise=i.wasmBinaryPromise.then(e=>{if(!i.url)throw Error("Draco decoder module is not available");return tools_Tools.LoadBabylonScriptAsync(i.url).then(()=>createDecoderAsync(e))})}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){let r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),applyGltfNormalizedOverride=(e,t)=>i&&void 0!==i[e]?(t!==i[e]&&logger_Logger.Warn(`Normalized flag from Draco data (${t}) does not match normalized flag from glTF accessor (${i[e]}). Using flag from glTF accessor.`),i[e]):t;if(this._workerPoolPromise)return this._workerPoolPromise.then(e=>new Promise((i,s)=>{e.push((e,a)=>{let n=null,o=[],onError=t=>{e.removeEventListener("error",onError),e.removeEventListener("message",onMessage),s(t),a()},onMessage=t=>{let r=t.data;switch(r.id){case"decodeMeshDone":e.removeEventListener("error",onError),e.removeEventListener("message",onMessage),i({indices:n,attributes:o,totalVertices:r.totalVertices}),a();break;case"indices":n=r.data;break;case"attribute":o.push({kind:r.kind,data:r.data,size:r.size,byteOffset:r.byteOffset,byteStride:r.byteStride,normalized:applyGltfNormalizedOverride(r.kind,r.normalized)})}};e.addEventListener("error",onError),e.addEventListener("message",onMessage);let l=r.slice();e.postMessage({id:"decodeMesh",dataView:l,attributes:t},[l.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(e=>{let i=null,s=[],a=decodeMesh(e.module,r,t,e=>{i=e},(e,t,i,r,a,n)=>{s.push({kind:e,data:t,size:i,byteOffset:r,byteStride:a,normalized:n})});return{indices:i,attributes:s,totalVertices:a}});throw Error("Draco decoder module is not available")}decodeMeshToGeometryAsync(e,t,i,r){return this._decodeMeshAsync(i,r).then(i=>{let r=new Geometry(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new buffer_VertexBuffer(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}_decodeMeshToGeometryForGltfAsync(e,t,i,r,s){return this._decodeMeshAsync(i,r,s).then(i=>{let r=new Geometry(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new buffer_VertexBuffer(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}decodeMeshAsync(e,t){return this._decodeMeshAsync(e,t).then(e=>{let t=new mesh_vertexData_VertexData;for(let i of(e.indices&&(t.indices=e.indices),e.attributes)){let r=buffer_VertexBuffer.GetFloatData(i.data,i.size,buffer_VertexBuffer.GetDataType(i.data),i.byteOffset,i.byteStride,i.normalized,e.totalVertices);t.set(r,i.kind)}return t})}};DracoCompression.Configuration={decoder:{wasmUrl:`${tools_Tools._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${tools_Tools._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${tools_Tools._DefaultCdnUrl}/draco_decoder_gltf.js`}},DracoCompression.DefaultNumWorkers=DracoCompression.GetDefaultNumWorkers(),DracoCompression._Default=null;let MeshoptCompression=class MeshoptCompression{static get Default(){return MeshoptCompression._Default||(MeshoptCompression._Default=new MeshoptCompression),MeshoptCompression._Default}constructor(){let e=MeshoptCompression.Configuration.decoder;this._decoderModulePromise=tools_Tools.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,s){return this._decoderModulePromise.then(()=>{let a=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(a,t,i,e,r,s),a})}};MeshoptCompression.Configuration={decoder:{url:`${tools_Tools._DefaultCdnUrl}/meshopt_decoder.js`}},MeshoptCompression._Default=null;let ni=0;let Vertex=class Vertex{constructor(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}clone(){var e,t;return new Vertex(this.pos.clone(),this.normal.clone(),null===(e=this.uv)||void 0===e?void 0:e.clone(),null===(t=this.vertColor)||void 0===t?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new Vertex(math_vector_Vector3.Lerp(this.pos,e.pos,t),math_vector_Vector3.Lerp(this.normal,e.normal,t),this.uv&&e.uv?math_vector_Vector2.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?math_color_Color4.Lerp(this.vertColor,e.vertColor,t):void 0)}};let csg_Plane=class csg_Plane{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){let r=i.subtract(e),s=t.subtract(e);if(0===r.lengthSquared()||0===s.lengthSquared())return null;let a=math_vector_Vector3.Normalize(math_vector_Vector3.Cross(r,s));return new csg_Plane(a,math_vector_Vector3.Dot(a,e))}clone(){return new csg_Plane(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,s){let a,n;let o=0,l=[];for(a=0;a<e.vertices.length;a++){n=math_vector_Vector3.Dot(this.normal,e.vertices[a].pos)-this.w;let t=n<-csg_Plane.EPSILON?2:n>csg_Plane.EPSILON?1:0;o|=t,l.push(t)}switch(o){case 0:(math_vector_Vector3.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:s.push(e);break;case 3:{let t;let i=[],o=[];for(a=0;a<e.vertices.length;a++){let t=(a+1)%e.vertices.length,r=l[a],s=l[t],h=e.vertices[a],c=e.vertices[t];if(2!==r&&i.push(h),1!==r&&o.push(2!==r?h.clone():h),(r|s)==3){n=(this.w-math_vector_Vector3.Dot(this.normal,h.pos))/math_vector_Vector3.Dot(this.normal,c.pos.subtract(h.pos));let e=h.interpolate(c,n);i.push(e),o.push(e.clone())}}i.length>=3&&(t=new csg_Polygon(i,e.shared)).plane&&r.push(t),o.length>=3&&(t=new csg_Polygon(o,e.shared)).plane&&s.push(t)}}}};csg_Plane.EPSILON=1e-5;let csg_Polygon=class csg_Polygon{constructor(e,t){this.vertices=e,this.shared=t,this.plane=csg_Plane.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){let e=this.vertices.map(e=>e.clone());return new csg_Polygon(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}};let csg_Node=class csg_Node{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=[],e&&this.build(e)}clone(){let e=new csg_Node;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map(e=>e.clone()),e}invert(){for(let e=0;e<this._polygons.length;e++)this._polygons[e].flip();this._plane&&this._plane.flip(),this._front&&this._front.invert(),this._back&&this._back.invert();let e=this._front;this._front=this._back,this._back=e}clipPolygons(e){if(!this._plane)return e.slice();let t=[],i=[];for(let r=0;r<e.length;r++)this._plane.splitPolygon(e[r],t,i,t,i);return this._front&&(t=this._front.clipPolygons(t)),i=this._back?this._back.clipPolygons(i):[],t.concat(i)}clipTo(e){this._polygons=e.clipPolygons(this._polygons),this._front&&this._front.clipTo(e),this._back&&this._back.clipTo(e)}allPolygons(){let e=this._polygons.slice();return this._front&&(e=e.concat(this._front.allPolygons())),this._back&&(e=e.concat(this._back.allPolygons())),e}build(e){if(!e.length)return;this._plane||(this._plane=e[0].plane.clone());let t=[],i=[];for(let r=0;r<e.length;r++)this._plane.splitPolygon(e[r],this._polygons,this._polygons,t,i);t.length&&(this._front||(this._front=new csg_Node),this._front.build(t)),i.length&&(this._back||(this._back=new csg_Node),this._back.build(i))}};let CSG=class CSG{constructor(){this._polygons=[]}static FromVertexData(e){let t,i,r;let s=[],a=e.indices,n=e.positions,o=e.normals,l=e.uvs,h=e.colors;if(!a||!n)throw"BABYLON.CSG: VertexData must at least contain positions and indices";for(let e=0;e<a.length;e+=3){r=[];for(let i=0;i<3;i++){let s=e+i,c=a[s],u=o?math_vector_Vector3.FromArray(o,3*c):math_vector_Vector3.Zero(),d=l?math_vector_Vector2.FromArray(l,2*c):void 0,_=h?math_color_Color4.FromArray(h,4*c):void 0,p=math_vector_Vector3.FromArray(n,3*c);t=new Vertex(p,u,d,_),r.push(t)}(i=new csg_Polygon(r,{subMeshId:0,meshId:ni,materialIndex:0})).plane&&s.push(i)}let c=CSG._FromPolygons(s);return c.matrix=math_vector_Matrix.Identity(),c.position=math_vector_Vector3.Zero(),c.rotation=math_vector_Vector3.Zero(),c.scaling=math_vector_Vector3.One(),c.rotationQuaternion=math_vector_Quaternion.Identity(),ni++,c}static FromMesh(e,t=!1){let i,r,s,a,n;let o=[],l,h,c,u=null,d,_=!1;if(e instanceof mesh_Mesh)e.computeWorldMatrix(!0),l=e.getWorldMatrix(),h=e.position.clone(),c=e.rotation.clone(),e.rotationQuaternion&&(u=e.rotationQuaternion.clone()),d=e.scaling.clone(),e.material&&t&&(_=0===e.material.sideOrientation);else throw"BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh";let p=e.getIndices(),f=e.getVerticesData(buffer_VertexBuffer.PositionKind),m=e.getVerticesData(buffer_VertexBuffer.NormalKind),g=e.getVerticesData(buffer_VertexBuffer.UVKind),v=e.getVerticesData(buffer_VertexBuffer.ColorKind),x=e.subMeshes;for(let e=0,t=x.length;e<t;e++)for(let t=x[e].indexStart,h=x[e].indexCount+x[e].indexStart;t<h;t+=3){n=[];for(let e=0;e<3;e++){let a=0===e?t+e:_?t+3-e:t+e,o=new math_vector_Vector3(m[3*p[a]],m[3*p[a]+1],m[3*p[a]+2]);g&&(r=new math_vector_Vector2(g[2*p[a]],g[2*p[a]+1])),v&&(s=new math_color_Color4(v[4*p[a]],v[4*p[a]+1],v[4*p[a]+2],v[4*p[a]+3]));let h=new math_vector_Vector3(f[3*p[a]],f[3*p[a]+1],f[3*p[a]+2]);i=new Vertex(math_vector_Vector3.TransformCoordinates(h,l),math_vector_Vector3.TransformNormal(o,l),r,s),n.push(i)}(a=new csg_Polygon(n,{subMeshId:e,meshId:ni,materialIndex:x[e].materialIndex})).plane&&o.push(a)}let b=CSG._FromPolygons(o);return b.matrix=t?math_vector_Matrix.Identity():l,b.position=t?math_vector_Vector3.Zero():h,b.rotation=t?math_vector_Vector3.Zero():c,b.scaling=t?math_vector_Vector3.One():d,b.rotationQuaternion=t&&u?math_vector_Quaternion.Identity():u,ni++,b}static _FromPolygons(e){let t=new CSG;return t._polygons=e,t}clone(){let e=new CSG;return e._polygons=this._polygons.map(e=>e.clone()),e.copyTransformAttributes(this),e}union(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){let e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map(e=>{e.flip()})}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){let i;let r=this.matrix.clone();r.invert();let s=this._polygons,a=[],n=[],o=[],l=null,h=null,c=math_vector_Vector3.Zero(),u=math_vector_Vector3.Zero(),d=math_vector_Vector2.Zero(),_=new math_color_Color4(0,0,0,0),p=[0,0,0],f={};for(let m=0,g=s.length;m<g;m++){let g=s[m];e&&e(g);for(let e=2,s=g.vertices.length;e<s;e++){p[0]=0,p[1]=e-1,p[2]=e;for(let e=0;e<3;e++){c.copyFrom(g.vertices[p[e]].pos),u.copyFrom(g.vertices[p[e]].normal),g.vertices[p[e]].uv&&(l||(l=[]),d.copyFrom(g.vertices[p[e]].uv)),g.vertices[p[e]].vertColor&&(h||(h=[]),_.copyFrom(g.vertices[p[e]].vertColor));let s=math_vector_Vector3.TransformCoordinates(c,r),m=math_vector_Vector3.TransformNormal(u,r);i=f[s.x+","+s.y+","+s.z];let v=!1;l&&!(l[2*i]===d.x||l[2*i+1]===d.y)&&(v=!0);let x=!1;h&&!(h[4*i]===_.r||h[4*i+1]===_.g||h[4*i+2]===_.b||h[4*i+3]===_.a)&&(x=!0),(!(void 0!==i&&o[3*i]===m.x&&o[3*i+1]===m.y&&o[3*i+2]===m.z)||v||x)&&(a.push(s.x,s.y,s.z),l&&l.push(d.x,d.y),o.push(u.x,u.y,u.z),h&&h.push(_.r,_.g,_.b,_.a),i=f[s.x+","+s.y+","+s.z]=a.length/3-1),n.push(i),t&&t()}}}let m=new mesh_vertexData_VertexData;return m.positions=a,m.normals=o,l&&(m.uvs=l),h&&(m.colors=h),m.indices=n,m}buildMeshGeometry(e,t,i){let r;let s=new mesh_Mesh(e,t),a=this._polygons,n=0,o={};i&&a.sort((e,t)=>e.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId);let l=this.toVertexData(e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:Infinity,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),r=o[e.shared.meshId][e.shared.subMeshId]},()=>{r.indexStart=Math.min(n,r.indexStart),r.indexEnd=Math.max(n,r.indexEnd),n++});if(l.applyToMesh(s),i){let e=0,t;for(let i in s.subMeshes=[],o){for(let a in t=-1,o[i])r=o[i][a],subMesh_SubMesh.CreateFromIndices(r.materialIndex+e,r.indexStart,r.indexEnd-r.indexStart+1,s),t=Math.max(r.materialIndex,t);e+=++t}}return s}toMesh(e,t=null,i,r){let s=this.buildMeshGeometry(e,i,r);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}};let nr=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<instancesDeclaration> +void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vNormalW=normalize(normWorldSM*normalUpdated); +#endif +vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);} +`;ShaderStore.ShadersStore.meshUVSpaceRendererVertexShader=nr;let ns=`precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} +gl_FragColor=texture2D(textureSampler,vDecalTC);} +`;ShaderStore.ShadersStore.meshUVSpaceRendererPixelShader=ns,mesh_Mesh._TrailMeshParser=(e,t)=>TrailMesh.Parse(e,t);let TrailMesh=class TrailMesh extends mesh_Mesh{constructor(e,t,i,r=1,s=60,a=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=a,this._generator=t,this.diameter=r,this._length=s,this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=math_vector_Vector3.Zero(),this._sectionNormalVectors[e]=math_vector_Vector3.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){let e=new mesh_vertexData_VertexData,t=[],i=[],r=[],s=math_vector_Vector3.Zero();s=this._generator instanceof abstractMesh_AbstractMesh&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.position;let a=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<this._sectionPolygonPointsCount;e++)t.push(s.x+Math.cos(e*a)*this.diameter,s.y+Math.sin(e*a)*this.diameter,s.z);for(let e=1;e<=this._length;e++){for(let e=0;e<this._sectionPolygonPointsCount;e++)t.push(s.x+Math.cos(e*a)*this.diameter,s.y+Math.sin(e*a)*this.diameter,s.z);let e=t.length/3-2*this._sectionPolygonPointsCount;for(let t=0;t<this._sectionPolygonPointsCount-1;t++)r.push(e+t,e+t+this._sectionPolygonPointsCount,e+t+this._sectionPolygonPointsCount+1),r.push(e+t,e+t+this._sectionPolygonPointsCount+1,e+t+1);r.push(e+this._sectionPolygonPointsCount-1,e+this._sectionPolygonPointsCount-1+this._sectionPolygonPointsCount,e+this._sectionPolygonPointsCount),r.push(e+this._sectionPolygonPointsCount-1,e+this._sectionPolygonPointsCount,e)}mesh_vertexData_VertexData.ComputeNormals(t,r,i),e.positions=t,e.normals=i,e.indices=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add(()=>{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){let e=this.getVerticesData(buffer_VertexBuffer.PositionKind),t=this.getVerticesData(buffer_VertexBuffer.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let i=3*this._sectionPolygonPointsCount;i<e.length;i++)e[i-3*this._sectionPolygonPointsCount]=e[i]-t[i]/this._length*this.diameter;for(let e=3*this._sectionPolygonPointsCount;e<t.length;e++)t[e-3*this._sectionPolygonPointsCount]=t[e];let r=e.length-3*this._sectionPolygonPointsCount,s=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<this._sectionPolygonPointsCount;e++)this._sectionVectors[e].copyFromFloats(Math.cos(e*s)*this.diameter,Math.sin(e*s)*this.diameter,0),this._sectionNormalVectors[e].copyFromFloats(Math.cos(e*s),Math.sin(e*s),0),math_vector_Vector3.TransformCoordinatesToRef(this._sectionVectors[e],i,this._sectionVectors[e]),math_vector_Vector3.TransformNormalToRef(this._sectionNormalVectors[e],i,this._sectionNormalVectors[e]);for(let i=0;i<this._sectionPolygonPointsCount;i++)e[r+3*i]=this._sectionVectors[i].x,e[r+3*i+1]=this._sectionVectors[i].y,e[r+3*i+2]=this._sectionVectors[i].z,t[r+3*i]=this._sectionNormalVectors[i].x,t[r+3*i+1]=this._sectionNormalVectors[i].y,t[r+3*i+2]=this._sectionNormalVectors[i].z;this.updateVerticesData(buffer_VertexBuffer.PositionKind,e,!0,!1),this.updateVerticesData(buffer_VertexBuffer.NormalKind,t,!0,!1)}}clone(e="",t){return new TrailMesh(e,void 0===t?this._generator:t,this.getScene(),this.diameter,this._length,this._autoStart)}serialize(e){super.serialize(e),e.generatorId=this._generator.id}static Parse(e,t){var i,r;let s=null!==(i=t.getLastMeshById(e.generatorId))&&void 0!==i?i:t.getLastTransformNodeById(e.generatorId);if(!s)throw Error("TrailMesh: generator not found with ID "+e.generatorId);return new TrailMesh(e.name,s,t,null!==(r=e.diameter)&&void 0!==r?r:e._diameter,e._length,e._autoStart)}};let SimplificationQueue=class SimplificationQueue{constructor(){this.running=!1,this._simplificationArray=[]}addTask(e){this._simplificationArray.push(e)}executeNext(){let e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1}runSimplification(e){if(e.parallelProcessing)e.settings.forEach(t=>{let i=this._getSimplifier(e);i.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{let t=this._getSimplifier(e),runDecimation=(i,r)=>{t.simplify(i,t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,r()})};AsyncLoop.Run(e.settings.length,t=>{runDecimation(e.settings[t.index],()=>{t.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){return e.simplificationType,tB.QUADRATIC,new QuadraticErrorSimplification(e.mesh)}};!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(tB||(tB={}));let DecimationTriangle=class DecimationTriangle{constructor(e){this._vertices=e,this.error=[,,,,],this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}};let DecimationVertex=class DecimationVertex{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new QuadraticMatrix,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}};let QuadraticMatrix=class QuadraticMatrix{constructor(e){this.data=Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,s,a,n,o,l){let h=this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[r]*this.data[o]+this.data[t]*this.data[a]*this.data[n]-this.data[i]*this.data[s]*this.data[n]-this.data[e]*this.data[a]*this.data[o]-this.data[t]*this.data[r]*this.data[l];return h}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){let t=new QuadraticMatrix;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}};let Reference=class Reference{constructor(e,t){this.vertexId=e,this.triangleId=t}};let QuadraticErrorSimplification=class QuadraticErrorSimplification{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=.001}simplify(e,t){this._initDecimatedMesh(),AsyncLoop.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){let r=~~(this._triangles.length*e.quality),s=0,a=this._triangles.length,iterationFunction=(e,t)=>{setTimeout(()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e<this._triangles.length;++e)this._triangles[e].isDirty=!1;let i=1e-9*Math.pow(e+3,this.aggressiveness);AsyncLoop.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=~~((this._triangles.length/2+e)%this._triangles.length),r=this._triangles[t];if(r&&!(r.error[3]>i)&&!r.deleted&&!r.isDirty){for(let e=0;e<3;++e)if(r.error[e]<i){let t=[],i=[],a=r._vertices[e],n=r._vertices[(e+1)%3];if(a.isBorder||n.isBorder)continue;let o=math_vector_Vector3.Zero();this._calculateError(a,n,o);let l=[];if(this._isFlipped(a,n,o,t,l)||this._isFlipped(n,a,o,i,l)||0>t.indexOf(!0)||0>i.indexOf(!0))continue;let h=[];if(l.forEach(e=>{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))}),h.length%2!=0)continue;a.q=n.q.add(a.q),a.updatePosition(o);let c=this._references.length;s=this._updateTriangles(a,a,t,s),s=this._updateTriangles(a,n,i,s);let u=this._references.length-c;if(u<=a.triangleCount){if(u)for(let e=0;e<u;e++)this._references[a.triangleStart+e]=this._references[c+e]}else a.triangleStart=c;a.triangleCount=u;break}}},t,()=>a-s<=r)},0)};AsyncLoop.Run(this.decimationIterations,e=>{a-s<=r?e.breakLoop():iterationFunction(e.index,()=>{e.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];let r=this._mesh.getVerticesData(buffer_VertexBuffer.PositionKind),s=this._mesh.getIndices(),a=this._mesh.subMeshes[e],findInVertices=e=>{if(i){for(let t=0;t<this._vertices.length;++t)if(this._vertices[t].position.equalsWithEpsilon(e,1e-4))return this._vertices[t]}return null},n=[],o=a.verticesCount;AsyncLoop.SyncAsyncForLoop(o,this.syncIterations/4>>0,e=>{if(!r)return;let t=e+a.verticesStart,i=math_vector_Vector3.FromArray(r,3*t),s=findInVertices(i)||new DecimationVertex(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),n.push(s.id)},()=>{AsyncLoop.SyncAsyncForLoop(a.indexCount/3,this.syncIterations,e=>{if(!s)return;let t=a.indexStart/3+e,i=3*t,r=s[i+0],o=s[i+1],l=s[i+2],h=this._vertices[n[r-a.verticesStart]],c=this._vertices[n[o-a.verticesStart]],u=this._vertices[n[l-a.verticesStart]],d=new DecimationTriangle([h,c,u]);d.originalOffset=i,this._triangles.push(d)},()=>{this._init(t)})})}_init(e){AsyncLoop.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];t.normal=math_vector_Vector3.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-math_vector_Vector3.Dot(t.normal,t._vertices[0].position)))},()=>{AsyncLoop.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])},()=>{e()})})}_reconstructMesh(e){let t,i,r;let s=[];for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleCount=0;for(t=0;t<this._triangles.length;++t)if(!this._triangles[t].deleted){for(r=0,i=this._triangles[t];r<3;++r)i._vertices[r].triangleCount=1;s.push(i)}let a=this._reconstructedMesh.getVerticesData(buffer_VertexBuffer.PositionKind)||[],n=this._reconstructedMesh.getVerticesData(buffer_VertexBuffer.NormalKind)||[],o=this._reconstructedMesh.getVerticesData(buffer_VertexBuffer.UVKind)||[],l=this._reconstructedMesh.getVerticesData(buffer_VertexBuffer.ColorKind)||[],h=this._mesh.getVerticesData(buffer_VertexBuffer.NormalKind),c=this._mesh.getVerticesData(buffer_VertexBuffer.UVKind),u=this._mesh.getVerticesData(buffer_VertexBuffer.ColorKind),d=0;for(t=0;t<this._vertices.length;++t){let e=this._vertices[t];e.id=d,e.triangleCount&&e.originalOffsets.forEach(t=>{a.push(e.position.x),a.push(e.position.y),a.push(e.position.z),h&&h.length&&(n.push(h[3*t]),n.push(h[3*t+1]),n.push(h[3*t+2])),c&&c.length&&(o.push(c[2*t]),o.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d})}let _=this._reconstructedMesh.getTotalIndices(),p=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];let m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(t=0;t<s.length;++t)i=s[t],[0,1,2].forEach(e=>{let t=g[i.originalOffset+e],r=i._vertices[e].originalOffsets.indexOf(t);r<0&&(r=0),m.push(i._vertices[e].id+r+p)});this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.PositionKind,a),n.length>0&&this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.NormalKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.UVKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.ColorKind,l);let v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach(e=>{subMesh_SubMesh.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())}),subMesh_SubMesh.AddToMesh(v.materialIndex,p,d,_,3*s.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new mesh_Mesh(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,r,s){for(let a=0;a<e.triangleCount;++a){let n=this._triangles[this._references[e.triangleStart+a].triangleId];if(n.deleted)continue;let o=this._references[e.triangleStart+a].vertexId,l=n._vertices[(o+1)%3],h=n._vertices[(o+2)%3];if(l===t||h===t){r[a]=!0,s.push(n);continue}let c=l.position.subtract(i);c=c.normalize();let u=h.position.subtract(i);if(u=u.normalize(),Math.abs(math_vector_Vector3.Dot(c,u))>.999)return!0;let d=math_vector_Vector3.Cross(c,u).normalize();if(r[a]=!1,.2>math_vector_Vector3.Dot(d,n.normal))return!0}return!1}_updateTriangles(e,t,i,r){let s=r;for(let r=0;r<t.triangleCount;++r){let a=this._references[t.triangleStart+r],n=this._triangles[a.triangleId];if(!n.deleted){if(i[r]&&n.deletePending){n.deleted=!0,s++;continue}n._vertices[a.vertexId]=e,n.isDirty=!0,n.error[0]=this._calculateError(n._vertices[0],n._vertices[1])+n.borderFactor/2,n.error[1]=this._calculateError(n._vertices[1],n._vertices[2])+n.borderFactor/2,n.error[2]=this._calculateError(n._vertices[2],n._vertices[0])+n.borderFactor/2,n.error[3]=Math.min(n.error[0],n.error[1],n.error[2]),this._references.push(a)}}return s}_identifyBorder(){for(let e=0;e<this._vertices.length;++e){let t;let i=[],r=[],s=this._vertices[e];for(t=0;t<s.triangleCount;++t){let e=this._triangles[this._references[s.triangleStart+t].triangleId];for(let t=0;t<3;t++){let s=0,a=e._vertices[t];for(;s<i.length&&r[s]!==a.id;)++s;s===i.length?(i.push(1),r.push(a.id)):i[s]++}}for(t=0;t<i.length;++t)1===i[t]?this._vertices[r[t]].isBorder=!0:this._vertices[r[t]].isBorder=!1}}_updateMesh(e=!1){let t,i,r,s;if(!e){let e=[];for(t=0;t<this._triangles.length;++t)this._triangles[t].deleted||e.push(this._triangles[t]);this._triangles=e}for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleCount=0,this._vertices[t].triangleStart=0;for(t=0;t<this._triangles.length;++t)for(r=0,i=this._triangles[t];r<3;++r)s=i._vertices[r],s.triangleCount++;let a=0;for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleStart=a,a+=this._vertices[t].triangleCount,this._vertices[t].triangleCount=0;let n=Array(3*this._triangles.length);for(t=0;t<this._triangles.length;++t)for(r=0,i=this._triangles[t];r<3;++r)n[(s=i._vertices[r]).triangleStart+s.triangleCount]=new Reference(r,t),s.triangleCount++;this._references=n,e&&this._identifyBorder()}_vertexError(e,t){let i=t.x,r=t.y,s=t.z;return e.data[0]*i*i+2*e.data[1]*i*r+2*e.data[2]*i*s+2*e.data[3]*i+e.data[4]*r*r+2*e.data[5]*r*s+2*e.data[6]*r+e.data[7]*s*s+2*e.data[8]*s+e.data[9]}_calculateError(e,t,i){let r=e.q.add(t.q),s=e.isBorder&&t.isBorder,a=0,n=r.det(0,1,2,1,4,5,2,5,7);if(0===n||s){let s=e.position.add(t.position).divide(new math_vector_Vector3(2,2,2)),n=this._vertexError(r,e.position),o=this._vertexError(r,t.position),l=this._vertexError(r,s);(a=Math.min(n,o,l))===n?i&&i.copyFrom(e.position):a===o?i&&i.copyFrom(t.position):i&&i.copyFrom(s)}else i||(i=math_vector_Vector3.Zero()),i.x=-1/n*r.det(1,2,3,4,5,6,5,7,8),i.y=1/n*r.det(0,2,3,1,5,6,2,7,8),i.z=-1/n*r.det(0,1,3,1,4,6,2,5,8),a=this._vertexError(r,i);return a}};Object.defineProperty(scene_Scene.prototype,"simplificationQueue",{get:function(){if(!this._simplificationQueue){this._simplificationQueue=new SimplificationQueue;let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);e||(e=new SimplicationQueueSceneComponent(this),this._addComponent(e))}return this._simplificationQueue},set:function(e){this._simplificationQueue=e},enumerable:!0,configurable:!0}),mesh_Mesh.prototype.simplify=function(e,t=!0,i=tB.QUADRATIC,r){return this.getScene().simplificationQueue.addTask({settings:e,parallelProcessing:t,mesh:this,simplificationType:i,successCallback:r}),this};let SimplicationQueueSceneComponent=class SimplicationQueueSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE,this,this._beforeCameraUpdate)}rebuild(){}dispose(){}_beforeCameraUpdate(){this.scene._simplificationQueue&&!this.scene._simplificationQueue.running&&this.scene._simplificationQueue.executeNext()}};(function(e){e[e.POINTS_MODE_POINTS=0]="POINTS_MODE_POINTS",e[e.POINTS_MODE_PATHS=1]="POINTS_MODE_PATHS"})(tN||(tN={})),function(e){e[e.FACES_MODE_SINGLE_SIDED=0]="FACES_MODE_SINGLE_SIDED",e[e.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING=1]="FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING",e[e.FACES_MODE_DOUBLE_SIDED=2]="FACES_MODE_DOUBLE_SIDED"}(tF||(tF={})),function(e){e[e.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT=0]="AUTO_DIRECTIONS_FROM_FIRST_SEGMENT",e[e.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS=1]="AUTO_DIRECTIONS_FROM_ALL_SEGMENTS",e[e.AUTO_DIRECTIONS_ENHANCED=2]="AUTO_DIRECTIONS_ENHANCED",e[e.AUTO_DIRECTIONS_NONE=99]="AUTO_DIRECTIONS_NONE"}(tw||(tw={}));let GreasedLineBaseMesh=class GreasedLineBaseMesh extends mesh_Mesh{constructor(e,t,i){var r,s,a,n;super(e,t,null,null,!1,!1),this.name=e,this._options=i,this._lazy=!1,this._updatable=!1,this._engine=t.getEngine(),this._lazy=null!==(r=i.lazy)&&void 0!==r&&r,this._updatable=null!==(s=i.updatable)&&void 0!==s&&s,this._vertexPositions=[],this._indices=[],this._uvs=[],this._points=[],this._colorPointers=null!==(a=i.colorPointers)&&void 0!==a?a:[],this._widths=null!==(n=i.widths)&&void 0!==n?n:Array(i.points.length).fill(1)}getClassName(){return"GreasedLineMesh"}_updateWidthsWithValue(e){let t=0;for(let e of this._points)t+=e.length;let i=t/3*2-this._widths.length;for(let t=0;t<i;t++)this._widths.push(e)}updateLazy(){var e,t;this._setPoints(this._points),this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(null===(e=this._options.ribbonOptions)||void 0===e?void 0:e.smoothShading),this.refreshBoundingInfo(),null===(t=this.greasedLineMaterial)||void 0===t||t.updateLazy()}addPoints(e,t){for(let t of e)this._points.push(t);this._lazy||this.setPoints(this._points,t)}dispose(){super.dispose()}isLazy(){return this._lazy}get offsets(){return this._offsets}set offsets(e){this._offsets=e,this._offsetsBuffer?this._offsetsBuffer.update(e):this._createOffsetsBuffer(e)}get widths(){return this._widths}set widths(e){this._widths=e,!this._lazy&&this._widthsBuffer&&this._widthsBuffer.update(e)}get colorPointers(){return this._colorPointers}set colorPointers(e){this._colorPointers=e,!this._lazy&&this._colorPointersBuffer&&this._colorPointersBuffer.update(e)}get greasedLineMaterial(){var e,t;if(this.material&&this.material instanceof greasedLineSimpleMaterial_GreasedLineSimpleMaterial)return this.material;let i=null===(t=null===(e=this.material)||void 0===e?void 0:e.pluginManager)||void 0===t?void 0:t.getPlugin(greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME);if(i)return i}get points(){let e=[];return DeepCopier.DeepCopy(this._points,e),e}setPoints(e,t){this._points=e,this._updateWidths(),(null==t?void 0:t.colorPointers)||this._updateColorPointers(),this._setPoints(e,t)}_initGreasedLine(){this._vertexPositions=[],this._indices=[],this._uvs=[]}_createLineOptions(){let e={points:this._points,colorPointers:this._colorPointers,lazy:this._lazy,updatable:this._updatable,uvs:this._uvs,widths:this._widths,ribbonOptions:this._options.ribbonOptions};return e}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions()}_createVertexBuffers(e=!1){let t=new mesh_vertexData_VertexData;return t.positions=this._vertexPositions,t.indices=this._indices,t.uvs=this._uvs,e&&(t.normals=[],mesh_vertexData_VertexData.ComputeNormals(this._vertexPositions,this._indices,t.normals)),t.applyToMesh(this,this._options.updatable),t}_createOffsetsBuffer(e){let t=this._scene.getEngine(),i=new Buffer(t,e,this._updatable,3);this.setVerticesBuffer(i.createVertexBuffer("grl_offsets",0,3)),this._offsetsBuffer=i}};mesh_Mesh._GreasedLineMeshParser=(e,t)=>greasedLineMesh_GreasedLineMesh.Parse(e,t);let greasedLineMesh_GreasedLineMesh=class greasedLineMesh_GreasedLineMesh extends GreasedLineBaseMesh{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(greasedLineTools_GreasedLineTools.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach(t=>{for(let i=0;i<t.length;i+=3)this._colorPointers.push(e),this._colorPointers.push(e++)})}_updateWidths(){super._updateWidthsWithValue(0)}_setPoints(e){this._points=e,this._options.points=e,this._initGreasedLine();let t=0;e.forEach(e=>{var i;let r=[],s=[],a=[],n=greasedLineTools_GreasedLineTools.GetLineLength(e);for(let i=0,o=0;o<e.length;i++,o+=3){let l=e.slice(0,o+3),h=greasedLineTools_GreasedLineTools.GetLineLength(l),c=h/n;if(s.push(e[o],e[o+1],e[o+2]),s.push(e[o],e[o+1],e[o+2]),r.push(c),r.push(c),o<e.length-3){let e=2*i+t;a.push(e,e+1,e+2),a.push(e+2,e+1,e+3)}}t+=e.length/3*2;let o=[],l=[],h=[],c=[];for(let e of(this._preprocess(s,o,l,h,c),s))this._vertexPositions.push(e);for(let e of a)this._indices.push(e);for(let e=0;e<h.length;e++)this._previousAndSide.push(o[3*e],o[3*e+1],o[3*e+2],h[e]),this._nextAndCounters.push(l[3*e],l[3*e+1],l[3*e+2],r[e]);for(let e of c=null!==(i=this._options.uvs)&&void 0!==i?i:c)this._uvs.push(e)}),this._lazy||(this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(),this.refreshBoundingInfo())}clone(e=`${this.name}-cloned`,t){let i=this._createLineOptions(),r={};DeepCopier.DeepCopy(i,r,["instance"],void 0,!0);let s=new greasedLineMesh_GreasedLineMesh(e,this._scene,r);return t&&(s.parent=t),s.material=this.material,s}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions()}static Parse(e,t){let i=e.lineOptions,r=e.name,s=new greasedLineMesh_GreasedLineMesh(r,t,i);return s}_initGreasedLine(){super._initGreasedLine(),this._previousAndSide=[],this._nextAndCounters=[]}intersects(e,t,i,r=!1,s,a=!1){let n=new PickingInfo,o=this.findAllIntersections(e,t,i,r,s,a,!0);if((null==o?void 0:o.length)===1){let t=o[0];n.hit=!0,n.distance=t.distance,n.ray=e,n.pickedMesh=this,n.pickedPoint=t.point}return n}findAllIntersections(e,t,i,r=!1,s,a=!1,n=!1){var o,l;if(r&&!a&&!1===e.intersectsSphere(this._boundingSphere,this.intersectionThreshold))return;let h=this.getIndices(),c=this.getVerticesData(buffer_VertexBuffer.PositionKind),u=this._widths,d=null!==(l=null===(o=this.greasedLineMaterial)||void 0===o?void 0:o.width)&&void 0!==l?l:1,_=[];if(h&&c&&u){let t=0,i=0;for(t=0,i=h.length-1;t<i;t+=3){let i=h[t],r=h[t+1];greasedLineMesh_GreasedLineMesh._V_START.fromArray(c,3*i),greasedLineMesh_GreasedLineMesh._V_END.fromArray(c,3*r),this._offsets&&(greasedLineMesh_GreasedLineMesh._V_OFFSET_START.fromArray(this._offsets,3*i),greasedLineMesh_GreasedLineMesh._V_OFFSET_END.fromArray(this._offsets,3*r),greasedLineMesh_GreasedLineMesh._V_START.addInPlace(greasedLineMesh_GreasedLineMesh._V_OFFSET_START),greasedLineMesh_GreasedLineMesh._V_END.addInPlace(greasedLineMesh_GreasedLineMesh._V_OFFSET_END));let s=Math.floor(t/3),a=void 0!==u[s]?u[s]:1,o=this.intersectionThreshold*(d*a)/2,l=e.intersectionSegment(greasedLineMesh_GreasedLineMesh._V_START,greasedLineMesh_GreasedLineMesh._V_END,o);if(-1!==l&&(_.push({distance:l,point:e.direction.normalize().multiplyByFloats(l,l,l).add(e.origin)}),n))return _}t=i}return _}get _boundingSphere(){return this.getBoundingInfo().boundingSphere}static _CompareV3(e,t,i){let r=6*e,s=6*t;return i[r]===i[s]&&i[r+1]===i[s+1]&&i[r+2]===i[s+2]}static _CopyV3(e,t){let i=6*e;return[t[i],t[i+1],t[i+2]]}_preprocess(e,t,i,r,s){let a=e.length/6,n=[];n=greasedLineMesh_GreasedLineMesh._CompareV3(0,a-1,e)?greasedLineMesh_GreasedLineMesh._CopyV3(a-2,e):greasedLineMesh_GreasedLineMesh._CopyV3(0,e),t.push(n[0],n[1],n[2]),t.push(n[0],n[1],n[2]);for(let o=0;o<a;o++)r.push(1),r.push(-1),this._options.uvs||(s.push(o/(a-1),0),s.push(o/(a-1),1)),o<a-1&&(n=greasedLineMesh_GreasedLineMesh._CopyV3(o,e),t.push(n[0],n[1],n[2]),t.push(n[0],n[1],n[2])),o>0&&(n=greasedLineMesh_GreasedLineMesh._CopyV3(o,e),i.push(n[0],n[1],n[2]),i.push(n[0],n[1],n[2]));return n=greasedLineMesh_GreasedLineMesh._CompareV3(a-1,0,e)?greasedLineMesh_GreasedLineMesh._CopyV3(1,e):greasedLineMesh_GreasedLineMesh._CopyV3(a-1,e),i.push(n[0],n[1],n[2]),i.push(n[0],n[1],n[2]),{previous:t,next:i,uvs:s,side:r}}_createVertexBuffers(){let e=super._createVertexBuffers(),t=this._scene.getEngine(),i=new Buffer(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));let r=new Buffer(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(r.createVertexBuffer("grl_nextAndCounters",0,4));let s=new Buffer(t,this._widths,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s;let a=new Buffer(t,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(a.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=a,e}};greasedLineMesh_GreasedLineMesh._V_START=new math_vector_Vector3,greasedLineMesh_GreasedLineMesh._V_END=new math_vector_Vector3,greasedLineMesh_GreasedLineMesh._V_OFFSET_START=new math_vector_Vector3,greasedLineMesh_GreasedLineMesh._V_OFFSET_END=new math_vector_Vector3,mesh_Mesh._GreasedLineRibbonMeshParser=(e,t)=>greasedLineRibbonMesh_GreasedLineRibbonMesh.Parse(e,t);let greasedLineRibbonMesh_GreasedLineRibbonMesh=class greasedLineRibbonMesh_GreasedLineRibbonMesh extends GreasedLineBaseMesh{constructor(e,t,i,r){var s;if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=null!==(s=i.widths)&&void 0!==s?s:[],this._ribbonWidths=[],this._pathsOptions=null!=r?r:[],i.points&&this.addPoints(greasedLineTools_GreasedLineTools.ConvertPoints(i.points),i,!!r)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t<this._pathsOptions.length;t++){let{options:i,pathCount:r}=this._pathsOptions[t],s=this._points[t];if(i.ribbonOptions.pointsMode===tN.POINTS_MODE_POINTS)for(let t=0;t<r;t++)for(let t=0;t<s.length;t+=3)this._colorPointers.push(e),this._colorPointers.push(e++);else for(let t=0;t<s.length;t+=3){for(let t=0;t<r;t++)this._colorPointers.push(e);e++}}}_updateWidths(){super._updateWidthsWithValue(1)}_setPoints(e,t){var i,r;let s;if(!this._options.ribbonOptions)throw"No 'GreasedLineMeshOptions.ribbonOptions' provided.";this._points=e,this._options.points=e,this._initGreasedLine();let a=0;for(let t=0,n=0;t<this._pathsOptions.length;t++){let{options:o,pathCount:l}=this._pathsOptions[t],h=e.slice(n,n+l);if(n+=l,(null===(i=o.ribbonOptions)||void 0===i?void 0:i.pointsMode)===tN.POINTS_MODE_PATHS)a=this._preprocess(greasedLineTools_GreasedLineTools.ToVector3Array(h),a,o);else{if((null===(r=o.ribbonOptions)||void 0===r?void 0:r.directionsAutoMode)===tw.AUTO_DIRECTIONS_NONE){if(!o.ribbonOptions.directions)throw"In GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_NONE 'GreasedLineMeshOptions.ribbonOptions.directions' must be defined.";s=greasedLineRibbonMesh_GreasedLineRibbonMesh._GetDirectionPlanesFromDirectionsOption(h.length,o.ribbonOptions.directions)}h.forEach((e,t)=>{let i=greasedLineRibbonMesh_GreasedLineRibbonMesh._ConvertToRibbonPath(e,o.ribbonOptions,this._scene.useRightHandedSystem,s?s[t]:s);a=this._preprocess(i,a,o)})}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:Array(e).fill(t)}static _CreateRibbonVertexData(e,t){var i,r,s;let a=e.length;if(a<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";let n=[],o=[],l=e[0];for(let t=0;t<l.length;t++)for(let i=0;i<e.length;i++){let r=e[i][t];n.push(r.x,r.y,r.z)}let h=[1,0,a],c=(null===(i=t.ribbonOptions)||void 0===i?void 0:i.facesMode)===tF.FACES_MODE_DOUBLE_SIDED,u=(null===(s=t.ribbonOptions)||void 0===s?void 0:s.pointsMode)===tN.POINTS_MODE_PATHS&&t.ribbonOptions.closePath;if(a>2)for(let e=0;e<l.length-1;e++){h[0]=1+a*e,h[1]=a*e,h[2]=(e+1)*a;for(let e=0;e<(a-1)*2;e++)e%2!=0&&(h[2]+=1),e%2==0&&e>0&&(h[0]+=1,h[1]+=1),o.push(h[1]+(e%2!=0?a:0),h[0],h[2]),c&&o.push(h[0],h[1]+(e%2!=0?a:0),h[2])}else for(let e=0;e<n.length/3-3;e+=2)o.push(e,e+1,e+2),o.push(e+2,e+1,e+3),c&&(o.push(e+1,e,e+2),o.push(e+1,e+2,e+3));if(u){let e=a*(l.length-1);for(let t=0;t<a-1;t++)o.push(e,t+1,t),o.push(e+1,t+1,e),c&&(o.push(t,t+1,e),o.push(e,t+1,e+1)),e++}return{positions:n,indices:o}}_preprocess(e,t,i){var r,s,a,n;this._paths=e;let o=greasedLineRibbonMesh_GreasedLineRibbonMesh._CreateRibbonVertexData(e,i),l=o.positions;if(!this._options.widths)throw"No 'GreasedLineMeshOptions.widths' table is specified.";for(let e of l)this._vertexPositions.push(e);let h=e;if((null===(r=i.ribbonOptions)||void 0===r?void 0:r.pointsMode)===tN.POINTS_MODE_PATHS&&i.ribbonOptions.closePath){h=[];for(let t=0;t<e.length;t++){let i=e[t].slice();i.push(e[t][0].clone()),h.push(i)}}this._calculateSegmentLengths(h);let c=h.length,u=Array(c).fill(0);for(let e=0;e<h[0].length;e++){let t=0;for(let i=0;i<c;i++){let r=u[i]+this._vSegmentLengths[i][e]/this._vTotalLengths[i];this._counters.push(r),this._uvs.push(r,t),u[i]=r,t+=this._uSegmentLengths[e][i]/this._uTotalLengths[e]}}for(let e=0,t=0;e<h[0].length;e++){let i=this._uSegmentLengths[e][0]/2,r=this._uSegmentLengths[e][c-1]/2;this._ribbonWidths.push(((null!==(s=this._widths[t++])&&void 0!==s?s:1)-1)*i);for(let e=0;e<c-2;e++)this._ribbonWidths.push(0);this._ribbonWidths.push(((null!==(a=this._widths[t++])&&void 0!==a?a:1)-1)*r)}let d=(null===(n=i.ribbonOptions)||void 0===n?void 0:n.pointsMode)===tN.POINTS_MODE_PATHS?Array(h[0].length*h.length*6).fill(0):greasedLineRibbonMesh_GreasedLineRibbonMesh._CalculateSlopes(h);for(let e of d)this._slopes.push(e);if(o.indices)for(let e=0;e<o.indices.length;e++)this._indices.push(o.indices[e]+t);return t+=l.length/3}static _ConvertToRibbonPath(e,t,i,r){if(t.pointsMode===tN.POINTS_MODE_POINTS&&!t.width)throw"'GreasedLineMeshOptions.ribbonOptiosn.width' must be specified in GreasedLineRibbonPointsMode.POINTS_MODE_POINTS.";let s=[],a=[];if(t.pointsMode===tN.POINTS_MODE_POINTS){let n=t.width/2,o=greasedLineTools_GreasedLineTools.ToVector3Array(e),l=null,h=null;t.directionsAutoMode===tw.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT&&(r=greasedLineRibbonMesh_GreasedLineRibbonMesh._GetDirectionFromPoints(o[0],o[1],null));for(let e=0;e<o.length-(r?0:1);e++){let c=o[e],u=o[e+1];if(r)l=r;else if(t.directionsAutoMode===tw.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS)l=greasedLineRibbonMesh_GreasedLineRibbonMesh._GetDirectionFromPoints(c,u,l);else{let e=u.subtract(c);e.applyRotationQuaternionInPlace(e.x>e.y&&e.x>e.z?i?greasedLineRibbonMesh_GreasedLineRibbonMesh._RightHandedForwardReadOnlyQuaternion:greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftHandedForwardReadOnlyQuaternion:greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(n,n,n),s.push(c.add(h)),a.push(c.subtract(h))}r||(s.push(o[o.length-1].add(h)),a.push(o[o.length-1].subtract(h)))}return[s,a]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&(null==i?void 0:i.x)!==1?e.y===t.y?greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XZ:e.z===t.z?greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XY:greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XZ:greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){let i=this._createLineOptions(),r={},s=[];DeepCopier.DeepCopy(this._pathsOptions,s,void 0,void 0,!0),DeepCopier.DeepCopy(i,r,["instance"],void 0,!0);let a=new greasedLineRibbonMesh_GreasedLineRibbonMesh(e,this._scene,r,s);return t&&(a.parent=t),a.material=this.material,a}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){let i=e.lineOptions,r=e.name,s=e.pathOptions,a=new greasedLineRibbonMesh_GreasedLineRibbonMesh(r,t,i,s);return a}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){let t=e.length;this._vSegmentLengths=Array(t),this._vTotalLengths=Array(t);let i=0;for(let r=0;r<t;r++){let t=e[r];this._vSegmentLengths[r]=[0],i=0;for(let e=0;e<t.length-1;e++){let s=Math.abs(t[e].subtract(t[e+1]).lengthSquared());i+=s,this._vSegmentLengths[r].push(s)}this._vTotalLengths[r]=i}let r=e[0].length;this._uSegmentLengths=Array(r).fill([]),this._uTotalLengths=Array(r).fill([]);let s=new math_vector_Vector3;for(let a=0;a<r;a++){i=0;for(let r=1;r<t;r++){e[r][a].subtractToRef(e[r-1][a],s);let t=s.length();i+=t,this._uSegmentLengths[a].push(t)}this._uTotalLengths[a]=i}}static _CalculateSlopes(e){let t=e[0],i=2===e.length?e[1]:e[e.length-1],r=[],s=new math_vector_Vector3;for(let a=0;a<t.length;a++)for(let n=0;n<e.length;n++)0===n||n===e.length-1?(t[a].subtract(i[a]).normalizeToRef(s),r.push(s.x,s.y,s.z),r.push(-s.x,-s.y,-s.z)):r.push(0,0,0,0,0,0);return r}_createVertexBuffers(){var e,t;this._uvs=null!==(e=this._options.uvs)&&void 0!==e?e:this._uvs;let i=super._createVertexBuffers(null===(t=this._options.ribbonOptions)||void 0===t?void 0:t.smoothShading),r=new Buffer(this._engine,this._counters,this._updatable,1);this.setVerticesBuffer(r.createVertexBuffer("grl_counters",0,1));let s=new Buffer(this._engine,this._colorPointers,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_colorPointers",0,1));let a=new Buffer(this._engine,this._slopes,this._updatable,3);this.setVerticesBuffer(a.createVertexBuffer("grl_slopes",0,3));let n=new Buffer(this._engine,this._ribbonWidths,this._updatable,1);return this.setVerticesBuffer(n.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=n,i}};greasedLineRibbonMesh_GreasedLineRibbonMesh.DEFAULT_WIDTH=.1,greasedLineRibbonMesh_GreasedLineRibbonMesh._RightHandedForwardReadOnlyQuaternion=math_vector_Quaternion.RotationAxis(math_vector_Vector3.RightHandedForwardReadOnly,Math.PI/2),greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftHandedForwardReadOnlyQuaternion=math_vector_Quaternion.RotationAxis(math_vector_Vector3.LeftHandedForwardReadOnly,Math.PI/2),greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftReadOnlyQuaternion=math_vector_Quaternion.RotationAxis(math_vector_Vector3.LeftReadOnly,Math.PI/2),greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XY=math_vector_Vector3.LeftHandedForwardReadOnly,greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XZ=math_vector_Vector3.UpReadOnly,greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_YZ=math_vector_Vector3.LeftReadOnly,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"}(tL||(tL={})),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"}(tV||(tV={})),mesh_Mesh.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return logger_Logger.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);let i=this._thinInstanceDataStorage.instancesCount;if(Array.isArray(e))for(let i=0;i<e.length;++i)this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e[i],i===e.length-1&&t);else this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e,t);return i},mesh_Mesh.prototype.thinInstanceAddSelf=function(e=!0){return this.thinInstanceAdd(math_vector_Matrix.IdentityReadOnly,e)},mesh_Mesh.prototype.thinInstanceRegisterAttribute=function(e,t){e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind),this.removeVerticesData(e),this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.strides[e]=t,this._userThinInstanceBuffersStorage.sizes[e]=t*Math.max(32,this._thinInstanceDataStorage.instancesCount),this._userThinInstanceBuffersStorage.data[e]=new Float32Array(this._userThinInstanceBuffersStorage.sizes[e]),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new buffer_VertexBuffer(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!0,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])},mesh_Mesh.prototype.thinInstanceSetMatrixAt=function(e,t,i=!0){if(!this._thinInstanceDataStorage.matrixData||e>=this._thinInstanceDataStorage.instancesCount)return!1;let r=this._thinInstanceDataStorage.matrixData;return t.copyToArray(r,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},mesh_Mesh.prototype.thinInstanceSetAttributeAt=function(e,t,i,r=!0){return e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind),!!this._userThinInstanceBuffersStorage&&!!this._userThinInstanceBuffersStorage.data[e]&&!(t>=this._thinInstanceDataStorage.instancesCount)&&(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),r&&this.thinInstanceBufferUpdated(e),!0)},Object.defineProperty(mesh_Mesh.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;let r=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData,s=r?r.length/16:0;e<=s&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),mesh_Mesh.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind);let r=new Buffer(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(r.createVertexBuffer(e+t,4*t,4));return r},mesh_Mesh.prototype.thinInstanceSetBuffer=function(e,t,i=0,r=!1){var s,a,n;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,r),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(null===(a=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===a||a.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,r))):(e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind),null===t?(null===(n=this._userThinInstanceBuffersStorage)||void 0===n?void 0:n.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 buffer_VertexBuffer(this.getEngine(),t,e,!r,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},mesh_Mesh.prototype.thinInstanceBufferUpdated=function(e){var t,i,r;"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===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},mesh_Mesh.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var r;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},mesh_Mesh.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];let e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;t<this._thinInstanceDataStorage.instancesCount;++t)this._thinInstanceDataStorage.worldMatrices[t]=math_vector_Matrix.FromArray(e,16*t)}return this._thinInstanceDataStorage.worldMatrices},mesh_Mesh.prototype.thinInstanceRefreshBoundingInfo=function(e=!1,t=!1,i=!1){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return;let r=this._thinInstanceDataStorage.boundingVectors;if(e||!this.rawBoundingInfo){r.length=0,this.refreshBoundingInfo(t,i);let e=this.getBoundingInfo();this.rawBoundingInfo=new boundingInfo_BoundingInfo(e.minimum,e.maximum)}let s=this.getBoundingInfo(),a=this._thinInstanceDataStorage.matrixData;if(0===r.length)for(let e=0;e<s.boundingBox.vectors.length;++e)r.push(s.boundingBox.vectors[e].clone());math_vector_TmpVectors.Vector3[0].setAll(Number.POSITIVE_INFINITY),math_vector_TmpVectors.Vector3[1].setAll(Number.NEGATIVE_INFINITY);for(let e=0;e<this._thinInstanceDataStorage.instancesCount;++e){math_vector_Matrix.FromArrayToRef(a,16*e,math_vector_TmpVectors.Matrix[0]);for(let e=0;e<r.length;++e)math_vector_Vector3.TransformCoordinatesToRef(r[e],math_vector_TmpVectors.Matrix[0],math_vector_TmpVectors.Vector3[2]),math_vector_TmpVectors.Vector3[0].minimizeInPlace(math_vector_TmpVectors.Vector3[2]),math_vector_TmpVectors.Vector3[1].maximizeInPlace(math_vector_TmpVectors.Vector3[2])}s.reConstruct(math_vector_TmpVectors.Vector3[0],math_vector_TmpVectors.Vector3[1]),this._updateBoundingInfo()},mesh_Mesh.prototype._thinInstanceUpdateBufferSize=function(e,t=1){var i,r,s;e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind);let a="matrix"===e;if(!a&&(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.strides[e]))return;let n=a?16:this._userThinInstanceBuffersStorage.strides[e],o=a?this._thinInstanceDataStorage.matrixBufferSize:this._userThinInstanceBuffersStorage.sizes[e],l=a?this._thinInstanceDataStorage.matrixData:this._userThinInstanceBuffersStorage.data[e],h=(this._thinInstanceDataStorage.instancesCount+t)*n,c=o;for(;c<h;)c*=2;if(!l||o!=c){if(l){let e=new Float32Array(c);e.set(l,0),l=e}else l=new Float32Array(c);a?(null===(i=this._thinInstanceDataStorage.matrixBuffer)||void 0===i||i.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",l,!1),this._thinInstanceDataStorage.matrixData=l,this._thinInstanceDataStorage.matrixBufferSize=c,this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&(null===(r=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===r||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",l,!1))):(null===(s=this._userThinInstanceBuffersStorage.vertexBuffers[e])||void 0===s||s.dispose(),this._userThinInstanceBuffersStorage.data[e]=l,this._userThinInstanceBuffersStorage.sizes[e]=c,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new buffer_VertexBuffer(this.getEngine(),l,e,!0,!1,n,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))}},mesh_Mesh.prototype._thinInstanceInitializeUserStorage=function(){this._userThinInstanceBuffersStorage||(this._userThinInstanceBuffersStorage={data:{},sizes:{},vertexBuffers:{},strides:{}})},mesh_Mesh.prototype._disposeThinInstanceSpecificData=function(){var e;(null===(e=this._thinInstanceDataStorage)||void 0===e?void 0:e.matrixBuffer)&&(this._thinInstanceDataStorage.matrixBuffer.dispose(),this._thinInstanceDataStorage.matrixBuffer=null)},function(e){e[e.Int=1]="Int",e[e.Float=2]="Float",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Matrix=32]="Matrix",e[e.Geometry=64]="Geometry",e[e.Texture=128]="Texture",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.Undefined=4096]="Undefined",e[e.All=4095]="All"}(tU||(tU={})),function(e){e[e.Compatible=0]="Compatible",e[e.TypeIncompatible=1]="TypeIncompatible",e[e.HierarchyIssue=2]="HierarchyIssue"}(tk||(tk={})),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(tG||(tG={}));let NodeGeometryConnectionPoint=class NodeGeometryConnectionPoint{get direction(){return this._direction}get type(){if(this._type===tU.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===tU.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map(e=>e.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}getConnectedValue(e){var t,i,r;return this.isConnected?(null===(t=this._connectedPoint)||void 0===t?void 0:t._storedFunction)?null===(i=this._connectedPoint)||void 0===i?void 0:i._storedFunction(e):null===(r=this._connectedPoint)||void 0===r?void 0:r._storedValue:this.value}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=[],this._type=tU.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new observable_Observable,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===tk.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==tU.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?tk.Compatible:tk.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return tk.TypeIncompatible;let r=i,s=t;return(this.direction===tG.Input&&(r=t,s=i),r.isAnAncestorOf(s))?tk.HierarchyIssue:tk.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t<tU.All;)e&t||this.excludedConnectionPointTypes.push(t),t<<=1}serialize(e=!0){let t={};return t.name=this.name,t.displayName=this.displayName,void 0!==this.value&&null!==this.value&&(this.value.asArray?(t.valueType="BABYLON."+this.value.getClassName(),t.value=this.value.asArray()):(t.valueType="number",t.value=this.value)),e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name),t}dispose(){this.onConnectionObservable.clear()}};let NodeGeometryBlock=class NodeGeometryBlock{get buildExecutionTime(){return this._buildExecutionTime}get inputs(){return this._inputs}get outputs(){return this._outputs}get name(){return this._name}set name(e){this._name=e}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isDebug(){return this._isDebug}get isUnique(){return this._isUnique}getClassName(){return"NodeGeometryBlock"}_inputRename(e){return e}_outputRename(e){return e}isAnAncestorOf(e){for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock.isAnAncestorOfType(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(let t of this._outputs)if(t.hasEndpoints)for(let i of t.endpoints){let t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}constructor(e){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this._buildExecutionTime=0,this.onBuildObservable=new observable_Observable,this._inputs=[],this._outputs=[],this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=UniqueIdGenerator.UniqueId}registerInput(e,t,i=!1,r,s,a){let n=new NodeGeometryConnectionPoint(e,this,tG.Input);return n.type=t,n.isOptional=i,n.defaultValue=r,n.value=r,n.valueMin=s,n.valueMax=a,this._inputs.push(n),this}registerOutput(e,t,i){return(i=null!=i?i:new NodeGeometryConnectionPoint(e,this,tG.Output)).type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}build(e){if(this._buildId===e.buildId)return!0;if(this._outputs.length>0&&!this._outputs.some(e=>e.hasEndpoints)&&!this.isDebug)return!1;for(let t of(this._buildId=e.buildId,this._inputs)){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}let i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&console.log(`Building ${this.name} [${this.getClassName()}]`);let t=precisionDate_PrecisionDate.Now;for(let i of(this._buildBlock(e),this._buildExecutionTime=precisionDate_PrecisionDate.Now-t,this._outputs))for(let t of i.endpoints){let i=t.ownerBlock;i&&i.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}serialize(){let e={};for(let t of(e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.inputs=[],e.outputs=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach(e=>{let t=this.inputs.find(t=>t.name===e.name);if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value)){if("number"===e.valueType)t.value=e.value;else{let i=h[e.valueType];i&&(t.value=i.FromArray(e.value))}}}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleOnFrame = ${this.visibleOnFrame}; +`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); +`}return t}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` +// ${this.getClassName()} +`;for(let i of(this.comments&&(r+=`// ${this.comments} +`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); +`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint,a=s.ownerBlock;-1===t.indexOf(a)&&(r+=a._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){let e=this.serialize(),t=h[e.customType];if(t){let i=new t;return i._deserialize(e),i}return null}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose();this.onBuildObservable.clear()}};__decorate([serialize("comment")],NodeGeometryBlock.prototype,"comments",void 0);let GeometryOutputBlock=class GeometryOutputBlock extends NodeGeometryBlock{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",tU.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}};h["BABYLON.GeometryOutputBlock"]=GeometryOutputBlock,function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID"}(tz||(tz={}));let NodeGeometryBuildState=class NodeGeometryBuildState{constructor(){this._rotationMatrix=new math_vector_Matrix,this._scalingMatrix=new math_vector_Matrix,this._positionMatrix=new math_vector_Matrix,this._scalingRotationMatrix=new math_vector_Matrix,this._transformMatrix=new math_vector_Matrix,this._tempVector3=new math_vector_Vector3,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;let i=this.executionContext.getExecutionIndex();switch(e){case tz.Positions:if(this.executionContext.getOverridePositionsContextualValue)return this.executionContext.getOverridePositionsContextualValue();if(!this.geometryContext||!this.geometryContext.positions)return math_vector_Vector3.Zero();return math_vector_Vector3.FromArray(this.geometryContext.positions,3*i);case tz.Normals:if(this.executionContext.getOverrideNormalsContextualValue)return this.executionContext.getOverrideNormalsContextualValue();if(!this.geometryContext||!this.geometryContext.normals)return math_vector_Vector3.Zero();return math_vector_Vector3.FromArray(this.geometryContext.normals,3*i);case tz.Colors:if(!this.geometryContext||!this.geometryContext.colors)return math_vector_Vector4.Zero();return math_vector_Vector4.FromArray(this.geometryContext.colors,4*i);case tz.Tangents:if(!this.geometryContext||!this.geometryContext.tangents)return math_vector_Vector4.Zero();return math_vector_Vector4.FromArray(this.geometryContext.tangents,4*i);case tz.UV:if(this.executionContext.getOverrideUVs1ContextualValue)return this.executionContext.getOverrideUVs1ContextualValue();if(!this.geometryContext||!this.geometryContext.uvs)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs,2*i);case tz.UV2:if(!this.geometryContext||!this.geometryContext.uvs2)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs2,2*i);case tz.UV3:if(!this.geometryContext||!this.geometryContext.uvs3)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs3,2*i);case tz.UV4:if(!this.geometryContext||!this.geometryContext.uvs4)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs4,2*i);case tz.UV5:if(!this.geometryContext||!this.geometryContext.uvs5)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs5,2*i);case tz.UV6:if(!this.geometryContext||!this.geometryContext.uvs6)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs6,2*i);case tz.VertexID:return i;case tz.FaceID:return this.executionContext.getExecutionFaceIndex();case tz.LoopID:return this.executionContext.getExecutionLoopIndex();case tz.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case tz.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case tz.CollectionID:if(!this.geometryContext||!this.geometryContext.metadata)return 0;return this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){let i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case tU.Vector2:return new math_vector_Vector2(i,i);case tU.Vector3:return new math_vector_Vector3(i,i,i);case tU.Vector4:return new math_vector_Vector4(i,i,i,i)}return null}adaptInput(e,t,i){var r;if(!e.isConnected)return e.value||i;let s=e.getConnectedValue(this);if((null===(r=e._connectedPoint)||void 0===r?void 0:r.type)===t)return s;switch(t){case tU.Vector2:return new math_vector_Vector2(s,s);case tU.Vector3:return new math_vector_Vector3(s,s,s);case tU.Vector4:return new math_vector_Vector4(s,s,s,s)}return null}emitErrors(){let e="";for(let t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. +`;for(let t of this.noContextualData)e+=`Contextual input ${tz[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block). +`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,r,s){math_vector_Matrix.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),math_vector_Matrix.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),math_vector_Matrix.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;t<e.positions.length;t+=3)this._tempVector3.fromArray(e.positions,t),math_vector_Vector3.TransformCoordinatesToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.positions,t),e.normals&&(this._tempVector3.fromArray(e.normals,t),math_vector_Vector3.TransformNormalToRef(this._tempVector3,this._scalingRotationMatrix,this._tempVector3),this._tempVector3.toArray(e.normals,t));s.push(e)}_instantiateWithMatrix(e,t,i){for(let i=0;i<e.positions.length;i+=3)this._tempVector3.fromArray(e.positions,i),math_vector_Vector3.TransformCoordinatesToRef(this._tempVector3,t,this._tempVector3),this._tempVector3.toArray(e.positions,i),e.normals&&(this._tempVector3.fromArray(e.normals,i),math_vector_Vector3.TransformNormalToRef(this._tempVector3,t,this._tempVector3),this._tempVector3.toArray(e.normals,i));i.push(e)}_instantiateWithPositionAndMatrix(e,t,i,r){math_vector_Matrix.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),i.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;t<e.positions.length;t+=3)this._tempVector3.fromArray(e.positions,t),math_vector_Vector3.TransformCoordinatesToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.positions,t),e.normals&&(this._tempVector3.fromArray(e.normals,t),math_vector_Vector3.TransformNormalToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.normals,t));r.push(e)}};let GeometryInputBlock=class GeometryInputBlock extends NodeGeometryBlock{get type(){if(this._type===tU.AutoDetect&&null!=this.value){if(!isNaN(this.value))return this._type=tU.Float,this._type;switch(this.value.getClassName()){case"Vector2":this._type=tU.Vector2;break;case"Vector3":this._type=tU.Vector3;break;case"Vector4":this._type=tU.Vector4;break;case"Matrix":this._type=tU.Matrix}}return this._type}get isContextual(){return this._contextualSource!==tz.None}get contextualValue(){return this._contextualSource}set contextualValue(e){switch(this._contextualSource=e,e){case tz.Positions:case tz.Normals:this._type=tU.Vector3;break;case tz.Colors:case tz.Tangents:this._type=tU.Vector4;break;case tz.UV:case tz.UV2:case tz.UV3:case tz.UV4:case tz.UV5:case tz.UV6:this._type=tU.Vector2;break;case tz.VertexID:case tz.GeometryID:case tz.CollectionID:case tz.FaceID:case tz.LoopID:case tz.InstanceID:this._type=tU.Int}this.output&&(this.output.type=this._type)}constructor(e,t=tU.AutoDetect){super(e),this._type=tU.Undefined,this._contextualSource=tz.None,this.min=0,this.max=0,this.groupInInspector="",this.onValueChangedObservable=new observable_Observable,this._type=t,this._isInput=!0,this.setDefaultValue(),this.registerOutput("output",t)}get value(){return this._storedValue}set value(e){this.type===tU.Float&&this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e)),this._storedValue=e,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e}getClassName(){return"GeometryInputBlock"}get output(){return this._outputs[0]}setDefaultValue(){switch(this.contextualValue=tz.None,this.type){case tU.Int:case tU.Float:this.value=0;break;case tU.Vector2:this.value=math_vector_Vector2.Zero();break;case tU.Vector3:this.value=math_vector_Vector3.Zero();break;case tU.Vector4:this.value=math_vector_Vector4.Zero();break;case tU.Matrix:this.value=math_vector_Matrix.Identity()}}_buildBlock(e){super._buildBlock(e),this.isContextual?(this.output._storedValue=null,this.output._storedFunction=e=>e.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${tz[this._contextualSource]}; +`;let t=[],i="";switch(this.type){case tU.Float:case tU.Int:i=`${this.value}`;break;case tU.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case tU.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case tU.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),(this.type===tU.Float||this.type===tU.Int)&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){let e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=h[e.valueType];t&&(this._storedValue=t.FromArray(e.value))}}}};h["BABYLON.GeometryInputBlock"]=GeometryInputBlock;let BoxBlock=class BoxBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",tU.Float,!0,1),this.registerInput("width",tU.Float,!0,0),this.registerInput("height",tU.Float,!0,0),this.registerInput("depth",tU.Float,!0,0),this.registerInput("subdivisions",tU.Int,!0,1),this.registerInput("subdivisionsX",tU.Int,!0,0),this.registerInput("subdivisionsY",tU.Int,!0,0),this.registerInput("subdivisionsZ",tU.Int,!0,0),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){let e=new GeometryInputBlock("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){let e=new GeometryInputBlock("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){let t={},func=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);let i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e),a=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),r&&(t.widthSegments=r),s&&(t.heightSegments=s),a&&(t.depthSegments=a),CreateSegmentedBoxVertexData(t)};if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],BoxBlock.prototype,"evaluateContext",void 0),h["BABYLON.BoxBlock"]=BoxBlock;let NodeGeometry=class NodeGeometry{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=NodeGeometry._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new observable_Observable,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){tools_Tools.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise(t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){let i=e&&e.editorURL?e.editorURL:NodeGeometry.EditorURL;tools_Tools.LoadBabylonScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){let t=Object.assign({nodeGeometry:this},e);this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";let r=precisionDate_PrecisionDate.Now;this._initializeBlock(this.outputBlock,i);let s=new NodeGeometryBuildState;s.buildId=this._buildId,s.verbose=e,this.outputBlock.build(s),t&&(this._buildId=NodeGeometry._BuildIdGenerator++),this._buildExecutionTime=precisionDate_PrecisionDate.Now-r,s.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=s.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;let i=new mesh_Mesh(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){for(let i of(e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();let i={};for(let t of e.blocks){let e=h[t.customType];if(e){let r=new e;r._deserialize(t),i[t.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;if(t){let r=i[t];r.attachToEndpoint(e)}}for(let r=0;r<e.blocks.length;r++){let s=e.blocks[r],a=i[s.id];!a||a.inputs.length&&s.inputs.some(e=>e.targetConnectionName)&&!t||this._restoreConnections(a,e,i)}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){let r=e.locations||e.editorData.locations;for(let e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);let s=[];for(let e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let a=i[s.id];if(a){for(let n of s.inputs)if(i[n.targetBlockId]===e&&n.targetConnectionName===r.name){let e=a.getInputByName(n.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(a,t,i);continue}}}}generateCode(){let e=[],t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); +`;for(let s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));return this.outputBlock&&(e=[],r+="// Connections\n"+this.outputBlock._dumpCodeForOutputConnections(e)+"// Output nodes\n"+`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; +`+`nodeGeometry.build(); +`),r}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}setToDefault(){this.clear(),this.editorData=null;let e=new BoxBlock("Box");e.autoConfigure();let t=new GeometryOutputBlock("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){let t=this.serialize(),i=decorators_SerializationHelper.Clone(()=>new NodeGeometry(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){let t=e?{}:decorators_SerializationHelper.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];for(let r of(e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[],i))t.blocks.push(r.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){let t=new NodeGeometry(e);return t.setToDefault(),t.build(),t}static Parse(e){let t=decorators_SerializationHelper.Parse(()=>new NodeGeometry(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(NodeGeometry.CreateDefault("blank")):new Promise((r,s)=>{let a=new webRequest_WebRequest;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let n=JSON.parse(JSON.parse(a.responseText).jsonPayload),o=JSON.parse(n.nodeGeometry);t||(t=decorators_SerializationHelper.Parse(()=>new NodeGeometry(e),o,null)),t.parseSerializedObject(o),t.snippetId=e;try{i||t.build(),r(t)}catch(e){s(e)}}else s("Unable to load the snippet "+e)}}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}};NodeGeometry._BuildIdGenerator=0,NodeGeometry.EditorURL=`${tools_Tools._DefaultCdnUrl}/v${engine_Engine.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,NodeGeometry.SnippetUrl="https://snippet.babylonjs.com",__decorate([serialize()],NodeGeometry.prototype,"name",void 0),__decorate([serialize("comment")],NodeGeometry.prototype,"comment",void 0);let GeometryOptimizeBlock=class GeometryOptimizeBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=.001,this.registerInput("geometry",tU.Geometry),this.registerOutput("output",tU.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e),i=[],r={};for(let e=0;e<t.positions.length;e+=3){let s=t.positions[e],a=t.positions[e+1],n=t.positions[e+2],o=!1;for(let t=0;t<i.length;t+=3)if(math_scalar_Scalar.WithinEpsilon(s,i[t],this.epsilon)&&math_scalar_Scalar.WithinEpsilon(a,i[t+1],this.epsilon)&&math_scalar_Scalar.WithinEpsilon(n,i[t+2],this.epsilon)){r[e/3]=t/3,o=!0;continue}o||(r[e/3]=i.length/3,i.push(s,a,n))}let s=new mesh_vertexData_VertexData;return s.positions=i,s.indices=t.indices.map(e=>r[e]),s};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`+`${this._codeVariableName}.epsilon = ${this.epsilon}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryOptimizeBlock.prototype,"evaluateContext",void 0),__decorate([editableInPropertyPage("Epsilon",em.Float,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryOptimizeBlock.prototype,"epsilon",void 0),h["BABYLON.GeometryOptimizeBlock"]=GeometryOptimizeBlock;let PlaneBlock=class PlaneBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",tU.Float,!0,1),this.registerInput("width",tU.Float,!0,0),this.registerInput("height",tU.Float,!0,0),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){let e=new GeometryInputBlock("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){let t={},func=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),CreatePlaneVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],PlaneBlock.prototype,"evaluateContext",void 0),h["BABYLON.PlaneBlock"]=PlaneBlock;let MeshBlock=class MeshBlock extends NodeGeometryBlock{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",tU.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}let e=mesh_vertexData_VertexData.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;t<e.indices.length;t+=3){let i=e.indices[t];e.indices[t]=e.indices[t+2],e.indices[t+2]=i}this.geometry._storedFunction=()=>e.clone()}serialize(){let e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=mesh_vertexData_VertexData.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=mesh_vertexData_VertexData.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}};__decorate([editableInPropertyPage("Serialize cached data",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],MeshBlock.prototype,"serializedCachedData",void 0),h["BABYLON.MeshBlock"]=MeshBlock;let IcoSphereBlock=class IcoSphereBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",tU.Float,!0,1),this.registerInput("radiusX",tU.Float,!0,0),this.registerInput("radiusY",tU.Float,!0,0),this.registerInput("radiusZ",tU.Float,!0,0),this.registerInput("subdivisions",tU.Int,!0,4),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),CreateIcoSphereVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],IcoSphereBlock.prototype,"evaluateContext",void 0),h["BABYLON.IcoSphereBlock"]=IcoSphereBlock;let SphereBlock=class SphereBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",tU.Int,!0,32),this.registerInput("diameter",tU.Float,!0,1),this.registerInput("diameterX",tU.Float,!0,0),this.registerInput("diameterY",tU.Float,!0,0),this.registerInput("diameterZ",tU.Float,!0,0),this.registerInput("arc",tU.Float,!0,1),this.registerInput("slice",tU.Float,!0,1),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},func=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),CreateSphereVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SphereBlock.prototype,"evaluateContext",void 0),h["BABYLON.SphereBlock"]=SphereBlock;let GridBlock=class GridBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",tU.Float,!0,1),this.registerInput("height",tU.Float,!0,1),this.registerInput("subdivisions",tU.Int,!0,1),this.registerInput("subdivisionsX",tU.Int,!0,0),this.registerInput("subdivisionsY",tU.Int,!0,0),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},func=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),CreateGroundVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GridBlock.prototype,"evaluateContext",void 0),h["BABYLON.GridBlock"]=GridBlock;let TorusBlock=class TorusBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",tU.Float,!0,1),this.registerInput("thickness",tU.Float,!0,.5),this.registerInput("tessellation",tU.Int,!0,16),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},func=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),CreateTorusVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],TorusBlock.prototype,"evaluateContext",void 0),h["BABYLON.TorusBlock"]=TorusBlock;let CylinderBlock=class CylinderBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",tU.Float,!0,25),this.registerInput("diameter",tU.Float,!0,1),this.registerInput("diameterTop",tU.Float,!0,-1),this.registerInput("diameterBottom",tU.Float,!0,-1),this.registerInput("subdivisions",tU.Int,!0,1),this.registerInput("tessellation",tU.Int,!0,24),this.registerInput("arc",tU.Float,!0,1),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},func=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),CreateCylinderVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CylinderBlock.prototype,"evaluateContext",void 0),h["BABYLON.CylinderBlock"]=CylinderBlock;let CapsuleBlock=class CapsuleBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",tU.Float,!0,1),this.registerInput("radius",tU.Float,!0,.25),this.registerInput("tessellation",tU.Int,!0,16),this.registerInput("subdivisions",tU.Int,!0,2),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),CreateCapsuleVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CapsuleBlock.prototype,"evaluateContext",void 0),h["BABYLON.CapsuleBlock"]=CapsuleBlock;let DiscBlock=class DiscBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",tU.Float,!0,.5),this.registerInput("tessellation",tU.Int,!0,64),this.registerInput("arc",tU.Float,!0,1),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),CreateDiscVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],DiscBlock.prototype,"evaluateContext",void 0),h["BABYLON.DiscBlock"]=DiscBlock;let NullBlock=class NullBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}};h["BABYLON.NullBlock"]=NullBlock;let SetPositionsBlock=class SetPositionsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("positions",tU.Vector3),this.registerOutput("output",tU.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.positions.getConnectedValue(e);t&&t.toArray(this._vertexData.positions,3*this._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetPositionsBlock.prototype,"evaluateContext",void 0),h["BABYLON.SetPositionsBlock"]=SetPositionsBlock;let SetNormalsBlock=class SetNormalsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("normals",tU.Vector3),this.registerOutput("output",tU.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetNormalsBlock"}get geometry(){return this._inputs[0]}get normals(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.normals.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.normals||(this._vertexData.normals=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.normals.getConnectedValue(e);t&&t.toArray(this._vertexData.normals,3*this._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetNormalsBlock.prototype,"evaluateContext",void 0),h["BABYLON.SetNormalsBlock"]=SetNormalsBlock;let SetUVsBlock=class SetUVsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.textureCoordinateIndex=0,this.registerInput("geometry",tU.Geometry),this.registerInput("uvs",tU.Vector2),this.registerOutput("output",tU.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetUVsBlock"}get geometry(){return this._inputs[0]}get uvs(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.uvs.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}let t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<i;this._currentIndex++){let i=this.uvs.getConnectedValue(e);i&&i.toArray(t,2*this._currentIndex)}switch(this.textureCoordinateIndex){case 0:this._vertexData.uvs=t;break;case 1:this._vertexData.uvs2=t;break;case 2:this._vertexData.uvs3=t;break;case 3:this._vertexData.uvs4=t;break;case 4:this._vertexData.uvs5=t;break;case 5:this._vertexData.uvs6=t}return e.restoreGeometryContext(),e.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.textureCoordinateIndex}; +`+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.textureCoordinateIndex=this.textureCoordinateIndex,e}_deserialize(e){super._deserialize(e),this.textureCoordinateIndex=e.textureCoordinateIndex,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetUVsBlock.prototype,"evaluateContext",void 0),__decorate([editableInPropertyPage("Texture coordinates index",em.List,"ADVANCED",{notifiers:{update:!0},options:[{label:"UV1",value:0},{label:"UV2",value:1},{label:"UV3",value:2},{label:"UV4",value:3},{label:"UV5",value:4},{label:"UV6",value:5}]})],SetUVsBlock.prototype,"textureCoordinateIndex",void 0),h["BABYLON.SetUVsBlock"]=SetUVsBlock;let SetColorsBlock=class SetColorsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("colors",tU.Vector4),this.registerOutput("output",tU.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetColorsBlock"}get geometry(){return this._inputs[0]}get colors(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.colors.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.colors||(this._vertexData.colors=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.colors.getConnectedValue(e);t&&t.toArray(this._vertexData.colors,4*this._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetColorsBlock.prototype,"evaluateContext",void 0),h["BABYLON.SetColorsBlock"]=SetColorsBlock;let SetTangentsBlock=class SetTangentsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("tangents",tU.Vector4),this.registerOutput("output",tU.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetTangentsBlock"}get geometry(){return this._inputs[0]}get tangents(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.tangents.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.tangents||(this._vertexData.tangents=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.tangents.getConnectedValue(e);t&&t.toArray(this._vertexData.tangents,4*this._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetTangentsBlock.prototype,"evaluateContext",void 0),h["BABYLON.SetTangentsBlock"]=SetTangentsBlock,function(e){e[e.Add=0]="Add",e[e.Subtract=1]="Subtract",e[e.Multiply=2]="Multiply",e[e.Divide=3]="Divide",e[e.Max=4]="Max",e[e.Min=5]="Min"}(tW||(tW={}));let MathBlock=class MathBlock extends NodeGeometryBlock{constructor(e){super(e),this.operation=tW.Add,this.registerInput("left",tU.AutoDetect),this.registerInput("right",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture),this._inputs[1].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[1].excludedConnectionPointTypes.push(tU.Texture),this._inputs[1].acceptedConnectionPointTypes.push(tU.Float),this._linkConnectionTypes(0,1)}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;let t=this.left,i=this.right;if(!t.isConnected||!i.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let r=t.type===tU.Float||t.type===tU.Int;switch(this.operation){case tW.Add:e=r?e=>t.getConnectedValue(e)+i.getConnectedValue(e):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case tW.Subtract:e=r?e=>t.getConnectedValue(e)-i.getConnectedValue(e):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case tW.Multiply:e=r?e=>t.getConnectedValue(e)*i.getConnectedValue(e):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case tW.Divide:e=r?e=>t.getConnectedValue(e)/i.getConnectedValue(e):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case tW.Min:if(r)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case tU.Vector2:e=e=>math_vector_Vector2.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tU.Vector3:e=e=>math_vector_Vector3.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tU.Vector4:e=e=>math_vector_Vector4.Minimize(t.getConnectedValue(e),e.adapt(i,t.type))}break;case tW.Max:if(r)e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case tU.Vector2:e=e=>math_vector_Vector2.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tU.Vector3:e=e=>math_vector_Vector3.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tU.Vector4:e=e=>math_vector_Vector4.Maximize(t.getConnectedValue(e),e.adapt(i,t.type))}}this.output._storedFunction=i=>t.type===tU.Int?0|e(i):e(i)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${tW[this.operation]}; +`;return e}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}};__decorate([editableInPropertyPage("Operation",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:tW.Add},{label:"Subtract",value:tW.Subtract},{label:"Multiply",value:tW.Multiply},{label:"Divide",value:tW.Divide},{label:"Max",value:tW.Max},{label:"Min",value:tW.Min}]})],MathBlock.prototype,"operation",void 0),h["BABYLON.MathBlock"]=MathBlock;let MapRangeBlock=class MapRangeBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("value",tU.AutoDetect),this.registerInput("fromMin",tU.Float,!0,0),this.registerInput("fromMax",tU.Float,!0,1),this.registerInput("toMin",tU.Float,!0,0),this.registerInput("toMax",tU.Float,!0,1),this.registerOutput("output",tU.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(tU.Vector2),this._inputs[0].excludedConnectionPointTypes.push(tU.Vector3),this._inputs[0].excludedConnectionPointTypes.push(tU.Vector4),this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.output._storedFunction=e=>{let t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),a=this.toMax.getConnectedValue(e),n=(t-i)/(r-i)*(a-s)+s;return this.output.type===tU.Int?Math.floor(n):n}}};h["BABYLON.MapRangeBlock"]=MapRangeBlock,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"}(tH||(tH={}));let ConditionBlock=class ConditionBlock extends NodeGeometryBlock{constructor(e){super(e),this.test=tH.Equal,this.registerInput("left",tU.Float),this.registerInput("right",tU.Float,!0,0),this.registerInput("ifTrue",tU.AutoDetect,!0,1),this.registerInput("ifFalse",tU.AutoDetect,!0,0),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=tU.Float,this._inputs[0].acceptedConnectionPointTypes.push(tU.Int),this._inputs[1].acceptedConnectionPointTypes.push(tU.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e),r=!1;switch(this.test){case tH.Equal:r=math_scalar_Scalar.WithinEpsilon(t,i,.001);break;case tH.NotEqual:r=t!==i;break;case tH.LessThan:r=t<i;break;case tH.GreaterThan:r=t>i;break;case tH.LessOrEqual:r=t<=i;break;case tH.GreaterOrEqual:r=t>=i;break;case tH.Xor:r=!!t&&!i||!t&&!!i;break;case tH.Or:r=!!t||!!i;break;case tH.And:r=!!t&&!!i}return r};this.output._storedFunction=e=>func(e)?this.ifTrue.getConnectedValue(e):this.ifFalse.getConnectedValue(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${tH[this.test]}; +`;return e}serialize(){let e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}};__decorate([editableInPropertyPage("Test",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:tH.Equal},{label:"NotEqual",value:tH.NotEqual},{label:"LessThan",value:tH.LessThan},{label:"GreaterThan",value:tH.GreaterThan},{label:"LessOrEqual",value:tH.LessOrEqual},{label:"GreaterOrEqual",value:tH.GreaterOrEqual},{label:"Xor",value:tH.Xor},{label:"Or",value:tH.Or},{label:"And",value:tH.And}]})],ConditionBlock.prototype,"test",void 0),h["BABYLON.ConditionBlock"]=ConditionBlock,function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID"}(tX||(tX={}));let RandomBlock=class RandomBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentLockId=-1,this.lockMode=tX.None,this.registerInput("min",tU.AutoDetect),this.registerInput("max",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture),this._inputs[1].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[1].excludedConnectionPointTypes.push(tU.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){let e=new GeometryInputBlock("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){let e=new GeometryInputBlock("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case tU.Int:case tU.Float:e=e=>{let t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case tU.Vector2:e=e=>{let t=this.min.getConnectedValue(e)||math_vector_Vector2.Zero(),i=this.max.getConnectedValue(e)||math_vector_Vector2.Zero();return new math_vector_Vector2(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case tU.Vector3:e=e=>{let t=this.min.getConnectedValue(e)||math_vector_Vector3.Zero(),i=this.max.getConnectedValue(e)||math_vector_Vector3.Zero();return new math_vector_Vector3(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case tU.Vector4:e=e=>{let t=this.min.getConnectedValue(e)||math_vector_Vector4.Zero(),i=this.max.getConnectedValue(e)||math_vector_Vector4.Zero();return new math_vector_Vector4(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==tX.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case tX.InstanceID:i=t.getContextualValue(tz.InstanceID,!0)||0;break;case tX.LoopID:i=t.getContextualValue(tz.LoopID,!0)||0}return this._currentLockId!==i&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${tX[this.lockMode]}; +`;return e}serialize(){let e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}};__decorate([editableInPropertyPage("LockMode",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:tX.None},{label:"LoopID",value:tX.LoopID},{label:"InstanceID",value:tX.InstanceID}]})],RandomBlock.prototype,"lockMode",void 0),h["BABYLON.RandomBlock"]=RandomBlock;let NoiseBlock=class NoiseBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("offset",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scale",tU.Float,!0,1),this.registerInput("octaves",tU.Float,!0,2,0,16),this.registerInput("roughness",tU.Float,!0,.5,0,1),this.registerOutput("output",tU.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,r){let s=15&e,a=s<8?t:i,n=12===s||14==s?t:r,o=s<4?i:n;return this._negateIf(a,s&a)+this._negateIf(o,2&s)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<<t|e>>32-t}_hash(e,t,i){let r,s,a;return r=s=a=3735928584,a+=i,s+=t,r+=e,a^=s,a-=this._hashBitRotate(s,14),r^=a,r-=this._hashBitRotate(a,11),s^=r,s-=this._hashBitRotate(r,25),a^=s,a-=this._hashBitRotate(s,16),r^=a,r-=this._hashBitRotate(a,4),s^=r,s-=this._hashBitRotate(r,14),a^=s,a-=this._hashBitRotate(s,24)}_mix(e,t,i,r,s,a,n,o,l,h,c){let u=1-l,d=1-h;return(1-c)*(d*(e*u+t*l)+h*(i*u+r*l))+c*(d*(s*u+a*l)+h*(n*u+o*l))}_perlinNoise(e){let t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),r=(0|e.z)-(e.z<0?1:0),s=e.x-t,a=e.y-i,n=e.z-r,o=this._fade(s),l=this._fade(a),h=this._fade(n);return this._mix(this._noiseGrad(this._hash(t,i,r),s,a,n),this._noiseGrad(this._hash(t+1,i,r),s-1,a,n),this._noiseGrad(this._hash(t,i+1,r),s,a-1,n),this._noiseGrad(this._hash(t+1,i+1,r),s-1,a-1,n),this._noiseGrad(this._hash(t,i,r+1),s,a,n-1),this._noiseGrad(this._hash(t+1,i,r+1),s-1,a,n-1),this._noiseGrad(this._hash(t,i+1,r+1),s,a-1,n-1),this._noiseGrad(this._hash(t+1,i+1,r+1),s-1,a-1,n-1),o,l,h)}_perlinSigned(e){return .982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,s){let a=new math_vector_Vector3(i.x*s+r.x,i.y*s+r.y,i.z*s+r.z),n=1,o=1,l=0,h=0;e=math_scalar_Scalar.Clamp(e,0,15);let c=0|e;for(let e=0;e<=c;e++){let e=this._perlin(a.scale(n));h+=e*o,l+=o,o*=math_scalar_Scalar.Clamp(t,0,1),n*=2}let u=e-Math.floor(e);if(0==u)return h/l;let d=this._perlin(a.scale(n)),_=h+d*o;return(1-u)*(h/=l)+u*(_/=l+o)}_buildBlock(){this.output._storedFunction=e=>{let t=e.getContextualValue(tz.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),a=this.scale.getConnectedValue(e);return this.noise(i,r,t,s,a)}}};h["BABYLON.NoiseBlock"]=NoiseBlock;let MergeGeometryBlock=class MergeGeometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",tU.Geometry),this.registerInput("geometry1",tU.Geometry,!0),this.registerInput("geometry2",tU.Geometry,!0),this.registerInput("geometry3",tU.Geometry,!0),this.registerInput("geometry4",tU.Geometry,!0),this.registerOutput("output",tU.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{let t=this.geometry0.getConnectedValue(e),i=[];if(this.geometry1.isConnected){let t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){let t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){let t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){let t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],MergeGeometryBlock.prototype,"evaluateContext",void 0),h["BABYLON.MergeGeometryBlock"]=MergeGeometryBlock;let GeometryCollectionBlock=class GeometryCollectionBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",tU.Geometry,!0),this.registerInput("geometry1",tU.Geometry,!0),this.registerInput("geometry2",tU.Geometry,!0),this.registerInput("geometry3",tU.Geometry,!0),this.registerInput("geometry4",tU.Geometry,!0),this.registerInput("geometry5",tU.Geometry,!0),this.registerInput("geometry6",tU.Geometry,!0),this.registerInput("geometry7",tU.Geometry,!0),this.registerInput("geometry8",tU.Geometry,!0),this.registerInput("geometry9",tU.Geometry,!0),this.registerOutput("output",tU.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){let s=e.getConnectedValue(t);s&&(s.metadata=s.metadata||{},s.metadata.collectionId=i,r.push(s))}}_buildBlock(e){let func=e=>{let t=[];return(this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length)?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryCollectionBlock.prototype,"evaluateContext",void 0),h["BABYLON.GeometryCollectionBlock"]=GeometryCollectionBlock;let GeometryElbowBlock=class GeometryElbowBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("input",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}};h["BABYLON.GeometryElbowBlock"]=GeometryElbowBlock;let ComputeNormalsBlock=class ComputeNormalsBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",tU.Geometry),this.registerOutput("output",tU.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),mesh_vertexData_VertexData.ComputeNormals(t.positions,t.indices,t.normals),t}}};h["BABYLON.ComputeNormalsBlock"]=ComputeNormalsBlock;let VectorConverterBlock=class VectorConverterBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("xyzw ",tU.Vector4,!0),this.registerInput("xyz ",tU.Vector3,!0),this.registerInput("xy ",tU.Vector2,!0),this.registerInput("zw ",tU.Vector2,!0),this.registerInput("x ",tU.Float,!0),this.registerInput("y ",tU.Float,!0),this.registerInput("z ",tU.Float,!0),this.registerInput("w ",tU.Float,!0),this.registerOutput("xyzw",tU.Vector4),this.registerOutput("xyz",tU.Vector3),this.registerOutput("xy",tU.Vector2),this.registerOutput("zw",tU.Vector2),this.registerOutput("x",tU.Float),this.registerOutput("y",tU.Float),this.registerOutput("z",tU.Float),this.registerOutput("w",tU.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);let t=this.xIn,i=this.yIn,r=this.zIn,s=this.wIn,a=this.xyIn,n=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,c=this.xyzOut,u=this.xyOut,d=this.zwOut,_=this.xOut,p=this.yOut,f=this.zOut,m=this.wOut,getData=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,c=0,u=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(c=i.getConnectedValue(e)),r.isConnected&&(u=r.getConnectedValue(e)),s.isConnected&&(d=s.getConnectedValue(e)),a.isConnected){let t=a.getConnectedValue(e);t&&(h=t.x,c=t.y)}if(n.isConnected){let t=n.getConnectedValue(e);t&&(u=t.x,d=t.y)}if(o.isConnected){let t=o.getConnectedValue(e);t&&(h=t.x,c=t.y,u=t.z)}return new math_vector_Vector4(h,c,u,d)};h._storedFunction=e=>getData(e),c._storedFunction=e=>{let t=getData(e);return new math_vector_Vector3(t.x,t.y,t.z)},u._storedFunction=e=>{let t=getData(e);return new math_vector_Vector2(t.x,t.y)},d._storedFunction=e=>{let t=getData(e);return new math_vector_Vector2(t.z,t.w)},_._storedFunction=e=>getData(e).x,p._storedFunction=e=>getData(e).y,f._storedFunction=e=>getData(e).z,m._storedFunction=e=>getData(e).w}};h["BABYLON.VectorConverterBlock"]=VectorConverterBlock;let NormalizeVectorBlock=class NormalizeVectorBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("input",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(tU.Float),this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),this.output._storedFunction=null,!this.input.isConnected){this.output._storedValue=null;return}this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize()}};h["BABYLON.NormalizeVectorBlock"]=NormalizeVectorBlock;let SetMaterialIDBlock=class SetMaterialIDBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("id",tU.Int,!0,0),this.registerOutput("output",tU.Geometry),this.id.acceptedConnectionPointTypes.push(tU.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;let i=new VertexDataMaterialInfo;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetMaterialIDBlock.prototype,"evaluateContext",void 0),h["BABYLON.SetMaterialIDBlock"]=SetMaterialIDBlock,function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Round=4]="Round",e[e.Floor=5]="Floor",e[e.Ceiling=6]="Ceiling",e[e.Sqrt=7]="Sqrt",e[e.Log=8]="Log",e[e.Tan=9]="Tan",e[e.ArcTan=10]="ArcTan",e[e.ArcCos=11]="ArcCos",e[e.ArcSin=12]="ArcSin",e[e.Sign=13]="Sign",e[e.Negate=14]="Negate",e[e.OneMinus=15]="OneMinus",e[e.Reciprocal=16]="Reciprocal",e[e.ToDegrees=17]="ToDegrees",e[e.ToRadians=18]="ToRadians"}(tY||(tY={}));let GeometryTrigonometryBlock=class GeometryTrigonometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.operation=tY.Cos,this.registerInput("input",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case tY.Cos:t=e=>Math.cos(e);break;case tY.Sin:t=e=>Math.sin(e);break;case tY.Abs:t=e=>Math.abs(e);break;case tY.Exp:t=e=>Math.exp(e);break;case tY.Round:t=e=>Math.round(e);break;case tY.Floor:t=e=>Math.floor(e);break;case tY.Ceiling:t=e=>Math.ceil(e);break;case tY.Sqrt:t=e=>Math.sqrt(e);break;case tY.Log:t=e=>Math.log(e);break;case tY.Tan:t=e=>Math.tan(e);break;case tY.ArcTan:t=e=>Math.atan(e);break;case tY.ArcCos:t=e=>Math.acos(e);break;case tY.ArcSin:t=e=>Math.asin(e);break;case tY.Sign:t=e=>Math.sign(e);break;case tY.Negate:t=e=>-e;break;case tY.OneMinus:t=e=>1-e;break;case tY.Reciprocal:t=e=>1/e;break;case tY.ToRadians:t=e=>e*Math.PI/180;break;case tY.ToDegrees:t=e=>180*e/Math.PI}if(!t){this.input._storedFunction=null,this.input._storedValue=null;return}switch(this.input.type){case tU.Int:case tU.Float:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return t(i)};break;case tU.Vector2:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new math_vector_Vector2(t(i.x),t(i.y))};break;case tU.Vector3:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new math_vector_Vector3(t(i.x),t(i.y),t(i.z))};break;case tU.Vector4:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new math_vector_Vector4(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${tY[this.operation]}; +`;return e}};__decorate([editableInPropertyPage("Operation",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:tY.Cos},{label:"Sin",value:tY.Sin},{label:"Abs",value:tY.Abs},{label:"Exp",value:tY.Exp},{label:"Round",value:tY.Round},{label:"Floor",value:tY.Floor},{label:"Ceiling",value:tY.Ceiling},{label:"Sqrt",value:tY.Sqrt},{label:"Log",value:tY.Log},{label:"Tan",value:tY.Tan},{label:"ArcTan",value:tY.ArcTan},{label:"ArcCos",value:tY.ArcCos},{label:"ArcSin",value:tY.ArcSin},{label:"Sign",value:tY.Sign},{label:"Negate",value:tY.Negate},{label:"OneMinus",value:tY.OneMinus},{label:"Reciprocal",value:tY.Reciprocal},{label:"ToDegrees",value:tY.ToDegrees},{label:"ToRadians",value:tY.ToRadians}]})],GeometryTrigonometryBlock.prototype,"operation",void 0),h["BABYLON.GeometryTrigonometryBlock"]=GeometryTrigonometryBlock;let GeometryTransformBlock=class GeometryTransformBlock extends NodeGeometryBlock{constructor(e){super(e),this._rotationMatrix=new math_vector_Matrix,this._scalingMatrix=new math_vector_Matrix,this._translationMatrix=new math_vector_Matrix,this._scalingRotationMatrix=new math_vector_Matrix,this._transformMatrix=new math_vector_Matrix,this.evaluateContext=!0,this.registerInput("value",tU.AutoDetect),this.registerInput("matrix",tU.Matrix,!0),this.registerInput("translation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("rotation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scaling",tU.Vector3,!0,math_vector_Vector3.One()),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tU.Float),this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t;let i=this.value.getConnectedValue(e);if(!i)return null;if(this.matrix.isConnected)t=this.matrix.getConnectedValue(e);else{let i=this.scaling.getConnectedValue(e),r=this.rotation.getConnectedValue(e),s=this.translation.getConnectedValue(e);math_vector_Matrix.ScalingToRef(i.x,i.y,i.z,this._scalingMatrix),math_vector_Matrix.RotationYawPitchRollToRef(r.y,r.x,r.z,this._rotationMatrix),math_vector_Matrix.TranslationToRef(s.x,s.y,s.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),t=this._transformMatrix}switch(this.value.type){case tU.Geometry:{let e=i.clone();return e.transform(t),e}case tU.Vector2:return math_vector_Vector2.Transform(i,t);case tU.Vector3:return math_vector_Vector3.TransformCoordinates(i,t);case tU.Vector4:return math_vector_Vector4.TransformCoordinates(i,t)}return null};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryTransformBlock.prototype,"evaluateContext",void 0),h["BABYLON.GeometryTransformBlock"]=GeometryTransformBlock;let RotationXBlock=class RotationXBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",tU.Float,!1,0),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>math_vector_Matrix.RotationX(this.angle.getConnectedValue(e))}};h["BABYLON.RotationXBlock"]=RotationXBlock;let RotationYBlock=class RotationYBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",tU.Float,!1,0),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>math_vector_Matrix.RotationY(this.angle.getConnectedValue(e))}};h["BABYLON.RotationYBlock"]=RotationYBlock;let RotationZBlock=class RotationZBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",tU.Float,!1,0),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>math_vector_Matrix.RotationZ(this.angle.getConnectedValue(e))}};h["BABYLON.RotationZBlock"]=RotationZBlock;let ScalingBlock=class ScalingBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("scale",tU.Vector3,!1,math_vector_Vector3.One()),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){let e=new GeometryInputBlock("Scale");e.value=new math_vector_Vector3(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.scale.getConnectedValue(e);return math_vector_Matrix.Scaling(t.x,t.y,t.z)}}};h["BABYLON.ScalingBlock"]=ScalingBlock;let AlignBlock=class AlignBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("source",tU.Vector3,!0,math_vector_Vector3.Up()),this.registerInput("target",tU.Vector3,!0,math_vector_Vector3.Left()),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),r=new math_vector_Matrix;return t.normalize(),i.normalize(),math_vector_Matrix.RotationAlignToRef(t,i,r,!0),r}}};h["BABYLON.AlignBlock"]=AlignBlock;let TranslationBlock=class TranslationBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("translation",tU.Vector3,!1,math_vector_Vector3.Zero()),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){let e=new GeometryInputBlock("Translation");e.value=new math_vector_Vector3(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.translation.getConnectedValue(e);return math_vector_Matrix.Translation(t.x,t.y,t.z)}}};h["BABYLON.TranslationBlock"]=TranslationBlock;let InstantiateOnVerticesBlock=class InstantiateOnVerticesBlock extends NodeGeometryBlock{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("instance",tU.Geometry,!0),this.registerInput("density",tU.Float,!0,1,0,1),this.registerInput("matrix",tU.Matrix,!0),this.registerInput("rotation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scaling",tU.Vector3,!0,math_vector_Vector3.One()),this.scaling.acceptedConnectionPointTypes.push(tU.Float),this.registerOutput("output",tU.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3,i=[],r=new math_vector_Vector3,s=[],a=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let e=a[3*this._currentIndex],t=a[3*this._currentIndex+1],i=a[3*this._currentIndex+2],r=!1;for(let a=0;a<s.length;a+=3)if(.001>Math.abs(s[a]-e)&&.001>Math.abs(s[a+1]-t)&&.001>Math.abs(s[a+2]-i)){r=!0;break}r||(this._indexTranslation[s.length/3]=this._currentIndex,s.push(e,t,i))}t=(a=s).length/3}else this._indexTranslation=null;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.instance.getConnectedValue(e);if(!t||!t.positions||0===t.positions.length)continue;let s=this.density.getConnectedValue(e);if(s<1&&Math.random()>s)continue;r.fromArray(a,3*this._currentIndex);let n=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(n,r,t,i)}else{let t=e.adaptInput(this.scaling,tU.Vector3,math_vector_Vector3.OneReadOnly),s=this.rotation.getConnectedValue(e)||math_vector_Vector3.ZeroReadOnly;e._instantiate(n,r,s,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"}; +`+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnVerticesBlock.prototype,"evaluateContext",void 0),__decorate([editableInPropertyPage("Remove duplicated positions",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],InstantiateOnVerticesBlock.prototype,"removeDuplicatedPositions",void 0),h["BABYLON.InstantiateOnVerticesBlock"]=InstantiateOnVerticesBlock;let InstantiateOnFacesBlock=class InstantiateOnFacesBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentPosition=new math_vector_Vector3,this._currentUV=new math_vector_Vector2,this._vertex0=new math_vector_Vector3,this._vertex1=new math_vector_Vector3,this._vertex2=new math_vector_Vector3,this._tempVector0=new math_vector_Vector3,this._tempVector1=new math_vector_Vector3,this._uv0=new math_vector_Vector2,this._uv1=new math_vector_Vector2,this._uv2=new math_vector_Vector2,this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("instance",tU.Geometry,!0),this.registerInput("count",tU.Int,!0,256),this.registerInput("matrix",tU.Matrix,!0),this.registerInput("rotation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scaling",tU.Vector3,!0,math_vector_Vector3.One()),this.scaling.acceptedConnectionPointTypes.push(tU.Float),this.registerOutput("output",tU.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),math_vector_Vector3.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=this._vertexData.indices.length/3,s=i/r,a=0,n=[],o=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex<r;this._currentFaceIndex++){a+=s;let r=(0|a)-o;if(r<1)continue;let l=this._vertexData.indices[3*this._currentFaceIndex],h=this._vertexData.indices[3*this._currentFaceIndex+1],c=this._vertexData.indices[3*this._currentFaceIndex+2];this._vertex0.fromArray(this._vertexData.positions,3*l),this._vertex1.fromArray(this._vertexData.positions,3*h),this._vertex2.fromArray(this._vertexData.positions,3*c),this._vertexData.uvs&&(this._uv0.fromArray(this._vertexData.uvs,2*l),this._uv1.fromArray(this._vertexData.uvs,2*h),this._uv2.fromArray(this._vertexData.uvs,2*c));for(let l=0;l<r&&!(o>=i);l++){let i=Math.random(),r=Math.random();if(i>r){let e=i;i=r,r=e}let l=i,h=r-i,c=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+c*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+c*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+c*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+c*this._uv2.x,l*this._uv0.y+h*this._uv1.y+c*this._uv2.y),!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length){a-=s;continue}let u=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,n)}else{let t=e.adaptInput(this.scaling,tU.Vector3,math_vector_Vector3.OneReadOnly),i=this.rotation.getConnectedValue(e)||math_vector_Vector3.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,n)}o++,this._currentLoopIndex++}}if(n.length){if(1===n.length)this._vertexData=n[0];else{let e=n.splice(0,1)[0];this._vertexData=e.merge(n,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnFacesBlock.prototype,"evaluateContext",void 0),h["BABYLON.InstantiateOnFacesBlock"]=InstantiateOnFacesBlock;let InstantiateOnVolumeBlock=class InstantiateOnVolumeBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentPosition=new math_vector_Vector3,this._vertex0=new math_vector_Vector3,this._vertex1=new math_vector_Vector3,this._vertex2=new math_vector_Vector3,this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("instance",tU.Geometry,!0),this.registerInput("count",tU.Int,!0,256),this.registerInput("matrix",tU.Matrix,!0),this.registerInput("rotation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scaling",tU.Vector3,!0,math_vector_Vector3.One()),this.scaling.acceptedConnectionPointTypes.push(tU.Float),this.registerOutput("output",tU.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=[],s=extractMinAndMax(this._vertexData.positions,0,this._vertexData.positions.length/3),a=s.minimum,n=s.maximum,o=new math_vector_Vector3(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let s=0;s<i;s++){this._currentPosition.set(Math.random()*(n.x-a.x)+a.x,Math.random()*(n.y-a.y)+a.y,Math.random()*(n.z-a.z)+a.z);let i=new ray_Ray(this._currentPosition,o),h=0;for(let e=0;e<l;e++){this._vertex0.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*e]),this._vertex1.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*e+1]),this._vertex2.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*e+2]);let t=i.intersectsTriangle(this._vertex0,this._vertex1,this._vertex2);t&&t.distance>0&&h++}if(h%2==0){s--;continue}if(!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length)continue;let c=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,r)}else{let t=e.adaptInput(this.scaling,tU.Vector3,math_vector_Vector3.OneReadOnly),i=this.rotation.getConnectedValue(e)||math_vector_Vector3.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,r)}this._currentLoopIndex++}if(r.length){if(1===r.length)this._vertexData=r[0];else{let e=r.splice(0,1)[0];this._vertexData=e.merge(r,!0,!1,!0,!0)}}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnVolumeBlock.prototype,"evaluateContext",void 0),h["BABYLON.InstantiateOnVolumeBlock"]=InstantiateOnVolumeBlock;let InstantiateBaseBlock=class InstantiateBaseBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",tU.Geometry,!0),this.registerInput("count",tU.Int,!0,1),this.registerOutput("output",tU.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateBaseBlock.prototype,"evaluateContext",void 0);let InstantiateBlock=class InstantiateBlock extends InstantiateBaseBlock{constructor(e){super(e),this.registerInput("matrix",tU.Matrix,!0),this.registerInput("position",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("rotation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scaling",tU.Vector3,!0,math_vector_Vector3.One()),this.scaling.acceptedConnectionPointTypes.push(tU.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){let func=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.instance.getConnectedValue(e);if(!t||!t.positions||0===t.positions.length)continue;let r=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithMatrix(r,t,i)}else{let t=this.position.getConnectedValue(e)||math_vector_Vector3.ZeroReadOnly,s=e.adaptInput(this.scaling,tU.Vector3,math_vector_Vector3.OneReadOnly),a=this.rotation.getConnectedValue(e)||math_vector_Vector3.ZeroReadOnly;e._instantiate(r,t,a,s,i)}}if(i.length){if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}};h["BABYLON.InstantiateBlock"]=InstantiateBlock;let InstantiateLinearBlock=class InstantiateLinearBlock extends InstantiateBaseBlock{constructor(e){super(e),this.registerInput("direction",tU.Vector3,!0,new math_vector_Vector3(1,0,0)),this.registerInput("rotation",tU.Vector3,!0,new math_vector_Vector3(0,0,0)),this.registerInput("scaling",tU.Vector3,!0,new math_vector_Vector3(0,0,0)),this.scaling.acceptedConnectionPointTypes.push(tU.Float)}getClassName(){return"InstantiateLinearBlock"}get direction(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}_buildBlock(e){let func=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=math_vector_Matrix.Identity(),s=math_vector_Vector3.Zero(),a=math_vector_Vector3.Zero(),n=math_vector_Vector3.Zero();for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.instance.getConnectedValue(e);if(!t||!t.positions||0===t.positions.length)continue;let o=t.clone(),l=this.direction.getConnectedValue(e),h=this.rotation.getConnectedValue(e),c=e.adaptInput(this.scaling,tU.Vector3,math_vector_Vector3.OneReadOnly);s.copyFrom(l.clone().scale(this._currentIndex)),a.copyFrom(h.clone().scale(this._currentIndex)),n.copyFrom(c.clone().scale(this._currentIndex)),n.addInPlaceFromFloats(1,1,1),math_vector_Matrix.ComposeToRef(n,math_vector_Quaternion.FromEulerAngles(a.x,a.y,a.z),s,r),e._instantiateWithMatrix(o,r,i)}if(i.length){if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}};h["BABYLON.InstantiateLinearBlock"]=InstantiateLinearBlock;let InstantiateRadialBlock=class InstantiateRadialBlock extends InstantiateBaseBlock{constructor(e){super(e),this.registerInput("radius",tU.Int,!0,0,0),this.registerInput("angleStart",tU.Float,!0,0),this.registerInput("angleEnd",tU.Float,!0,2*Math.PI),this.registerInput("transform",tU.Vector3,!0,new math_vector_Vector3(0,0,0)),this.registerInput("rotation",tU.Vector3,!0,new math_vector_Vector3(0,0,0)),this.registerInput("scaling",tU.Vector3,!0,new math_vector_Vector3(0,0,0)),this.scaling.acceptedConnectionPointTypes.push(tU.Float)}getClassName(){return"InstantiateRadialBlock"}get radius(){return this._inputs[2]}get angleStart(){return this._inputs[3]}get angleEnd(){return this._inputs[4]}get transform(){return this._inputs[5]}get rotation(){return this._inputs[6]}get scaling(){return this._inputs[7]}_buildBlock(e){let func=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=math_vector_Matrix.Identity(),s=math_vector_Matrix.Identity(),a=math_vector_Matrix.Identity(),n=math_vector_Vector3.Zero(),o=math_vector_Vector3.Zero(),l=math_vector_Vector3.Zero();for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let h=this.instance.getConnectedValue(e);if(!h||!h.positions||0===h.positions.length)continue;let c=h.clone(),u=this.radius.getConnectedValue(e),d=this.angleStart.getConnectedValue(e),_=this.angleEnd.getConnectedValue(e),p=this.transform.getConnectedValue(e),f=this.rotation.getConnectedValue(e),m=e.adaptInput(this.scaling,tU.Vector3,math_vector_Vector3.OneReadOnly),g=_-d,v=g/t,x=d+v*this._currentIndex,b=math_vector_Quaternion.FromEulerAngles(0,x,0);n.copyFrom(p.clone().scale(this._currentIndex)),o.copyFrom(f.clone().scale(this._currentIndex)),l.copyFrom(m.clone().scale(this._currentIndex)),l.addInPlaceFromFloats(1,1,1),math_vector_Matrix.RotationYawPitchRollToRef(o.y,o.x,o.z,r),s.setTranslationFromFloats(0,0,u),math_vector_Matrix.ComposeToRef(l,b,n,a),r.multiplyToRef(s,s),s.multiplyToRef(a,a),e._instantiateWithMatrix(c,a,i)}if(i.length){if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}};h["BABYLON.InstantiateRadialBlock"]=InstantiateRadialBlock;let IntFloatConverterBlock=class IntFloatConverterBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("float ",tU.Float,!0),this.registerInput("int ",tU.Int,!0),this.registerOutput("float",tU.Float),this.registerOutput("int",tU.Int)}getClassName(){return"IntFloatConverterBlock"}get floatIn(){return this._inputs[0]}get intIn(){return this._inputs[1]}get floatOut(){return this._outputs[0]}get intOut(){return this._outputs[1]}_inputRename(e){return"float "===e?"floatIn":"int "===e?"intIn":e}_buildBlock(){this.floatOut._storedFunction=e=>this.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}};h["BABYLON.IntFloatConverterBlock"]=IntFloatConverterBlock;let DebugBlock=class DebugBlock extends NodeGeometryBlock{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.log=[];let func=e=>{let t=this.input.getConnectedValue(e);return null==t?this.log.push("null"):this.log.push(t.toString()),t};this.output.isConnected?this.output._storedFunction=func:this.output._storedValue=func(e)}};h["BABYLON.DebugBlock"]=DebugBlock;let GeometryInfoBlock=class GeometryInfoBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",tU.Geometry),this.registerOutput("output",tU.Geometry),this.registerOutput("id",tU.Int),this.registerOutput("collectionId",tU.Int),this.registerOutput("verticesCount",tU.Int),this.registerOutput("facesCount",tU.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected){this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,this.output._storedFunction=null;return}this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}};h["BABYLON.GeometryInfoBlock"]=GeometryInfoBlock,function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(tj||(tj={}));let MappingBlock=class MappingBlock extends NodeGeometryBlock{constructor(e){super(e),this.mapping=tj.Spherical,this.registerInput("position",tU.Vector3),this.registerInput("normal",tU.Vector3),this.registerInput("center",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerOutput("uv",tU.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected){this.uv._storedFunction=null,this.uv._storedValue=null;return}let e=math_vector_Vector3.Zero(),func=t=>{let i=this.position.getConnectedValue(t)||math_vector_Vector3.Zero(),r=this.normal.getConnectedValue(t)||math_vector_Vector3.Zero(),s=this.center.getConnectedValue(t),a=math_vector_Vector2.Zero();switch(this.mapping){case tj.Spherical:{i.subtractToRef(s,e);let t=e.length();t>0&&(a.x=Math.acos(e.y/t)/Math.PI,(0!==e.x||0!==e.z)&&(a.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case tj.Cylindrical:{i.subtractToRef(s,e);let t=e.length();t>0&&(a.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),a.y=(e.y+1)/2);break}case tj.Cubic:{let e=Math.abs(r.x),t=Math.abs(r.y),n=Math.abs(r.z),o=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),l=0,h=0;e>=t&&e>=n?(l=i.y/o-s.y,h=i.z/o-s.z):t>=e&&t>=n?(l=i.x/o-s.x,h=i.z/o-s.z):(l=i.x/o-s.x,h=i.y/o-s.y),a.x=(l+1)/2,a.y=(h+1)/2}}return a};this.uv._storedFunction=e=>func(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${tj[this.mapping]}; +`;return e}serialize(){let e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}};__decorate([editableInPropertyPage("Mapping",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:tj.Spherical},{label:"Cylindrical",value:tj.Cylindrical},{label:"Cubic",value:tj.Cubic}]})],MappingBlock.prototype,"mapping",void 0),h["BABYLON.MappingBlock"]=MappingBlock;let MatrixComposeBlock=class MatrixComposeBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("matrix0",tU.Matrix),this.registerInput("matrix1",tU.Matrix),this.registerOutput("output",tU.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;let t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}};h["BABYLON.MatrixComposeBlock"]=MatrixComposeBlock;let TeleportInBlock=class TeleportInBlock extends NodeGeometryBlock{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",tU.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(let t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(let t of this.endpoints){let i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(let e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}};h["BABYLON.TeleportInBlock"]=TeleportInBlock;let TeleportOutBlock=class TeleportOutBlock extends NodeGeometryBlock{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",tU.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){let e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); +`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}};h["BABYLON.TeleportOutBlock"]=TeleportOutBlock;let GeometryTextureBlock=class GeometryTextureBlock extends NodeGeometryBlock{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",tU.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{let r=new Image,s=document.createElement("canvas"),a=s.getContext("2d");r.onload=()=>{s.width=r.width,s.height=r.height,a.drawImage(r,0,0);let e=a.getImageData(0,0,r.width,r.height),i=e.data,n=new Float32Array(i.length);for(let e=0;e<i.length;e++)n[e]=i[e]/255;this._data=n,this._width=r.width,this._height=r.height,t()},r.onerror=()=>{this._data=null,i()},r.src=e})}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise((t,i)=>{if(!e.isReady()){e.onLoadObservable.addOnce(()=>this.extractFromTextureAsync(e).then(t).catch(i));return}let r=e.getSize();rF.GetTextureDataAsync(e,r.width,r.height).then(async e=>{let i=new Float32Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/255;this._data=i,this._width=r.width,this._height=r.height,t()}).catch(i)})}_buildBlock(){if(!this._data){this.texture._storedValue=null;return}let e={data:this._data,width:this._width,height:this._height};this.texture._storedValue=e}serialize(){let e=super.serialize();return e.width=this._width,e.height=this._height,e.serializedCachedData=this.serializedCachedData,this._data&&this.serializedCachedData&&(e.data=Array.from(this._data)),e}_deserialize(e){super._deserialize(e),this._width=e.width,this._height=e.height,e.data?(this._data=new Float32Array(e.data),this.serializedCachedData=!0):this.serializedCachedData=!!e.serializedCachedData}};__decorate([editableInPropertyPage("Serialize cached data",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryTextureBlock.prototype,"serializedCachedData",void 0),h["BABYLON.GeometryTextureBlock"]=GeometryTextureBlock;let GeometryTextureFetchBlock=class GeometryTextureFetchBlock extends NodeGeometryBlock{constructor(e){super(e),this.clampCoordinates=!0,this.registerInput("texture",tU.Texture),this.registerInput("coordinates",tU.Vector2),this.registerOutput("rgba",tU.Vector4),this.registerOutput("rgb",tU.Vector3),this.registerOutput("r",tU.Float),this.registerOutput("g",tU.Float),this.registerOutput("b",tU.Float),this.registerOutput("a",tU.Float)}getClassName(){return"GeometryTextureFetchBlock"}get texture(){return this.inputs[0]}get coordinates(){return this.inputs[1]}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]}_repeatClamp(e){return e>=0?e%1:1-Math.abs(e)%1}_buildBlock(){let func=e=>{let t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;let i=this.coordinates.getConnectedValue(e);if(!i)return null;let r=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),s=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),a=Math.floor(r*(t.width-1)),n=Math.floor(s*(t.height-1)),o=a+t.width*n;return math_vector_Vector4.FromArray(t.data,4*o)};this.rgba._storedFunction=e=>func(e),this.rgb._storedFunction=e=>{let t=func(e);return t?t.toVector3():null},this.r._storedFunction=e=>{let t=func(e);return t?t.x:null},this.g._storedFunction=e=>{let t=func(e);return t?t.y:null},this.b._storedFunction=e=>{let t=func(e);return t?t.z:null},this.a._storedFunction=e=>{let t=func(e);return t?t.w:null}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates}; +`;return e}serialize(){let e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}};__decorate([editableInPropertyPage("Clamp Coordinates",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryTextureFetchBlock.prototype,"clampCoordinates",void 0),h["BABYLON.GeometryTextureFetchBlock"]=GeometryTextureFetchBlock;let BoundingBlock=class BoundingBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",tU.Geometry),this.registerOutput("min",tU.Vector3),this.registerOutput("max",tU.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);if(!t)return null;let i=extractMinAndMax(t.positions,0,t.positions.length/3);return i.minimum},this.max._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);if(!t)return null;let i=extractMinAndMax(t.positions,0,t.positions.length/3);return i.maximum}}};h["BABYLON.BoundingBlock"]=BoundingBlock,function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}(tK||(tK={}));let BooleanGeometryBlock=class BooleanGeometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.operation=tK.Intersect,this.registerInput("geometry0",tU.Geometry),this.registerInput("geometry1",tU.Geometry),this.registerOutput("output",tU.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{let t;let i=this.geometry0.getConnectedValue(e),r=this.geometry1.getConnectedValue(e);if(!i||!r)return null;let s=i.positions.length/3;!i.normals&&r.normals&&(i.normals=Array(i.positions.length)),!r.normals&&i.normals&&(r.normals=Array(r.positions.length)),!i.uvs&&r.uvs&&(i.uvs=Array(2*s)),!r.uvs&&i.uvs&&(r.uvs=Array(2*s)),!i.colors&&r.colors&&(i.colors=Array(4*s)),!r.colors&&i.colors&&(r.colors=Array(4*s));let a=CSG.FromVertexData(i),n=CSG.FromVertexData(r);switch(this.operation){case tK.Intersect:t=a.intersect(n);break;case tK.Subtract:t=a.subtract(n);break;case tK.Union:t=a.union(n)}return t.toVertexData()};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`+`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${tK[this.operation]}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],BooleanGeometryBlock.prototype,"evaluateContext",void 0),__decorate([editableInPropertyPage("Operation",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:tK.Intersect},{label:"Subtract",value:tK.Subtract},{label:"Union",value:tK.Union}]})],BooleanGeometryBlock.prototype,"operation",void 0),h["BABYLON.BooleanGeometryBlock"]=BooleanGeometryBlock,engine_Engine.OfflineProviderFactory=(e,t,i=!1)=>new Database(e,t,i);let Database=class Database{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=Database._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,Database.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,tools_Tools.SetImmediate(()=>{t(!0)})):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){let noManifestFile=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},createManifestURL=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){let e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`},t=!1,i=createManifestURL(),r=new webRequest_WebRequest;navigator.onLine&&(t=!0,i=i+(null==i.match(/\?/)?"?":"&")+Date.now()),r.open("GET",i),r.addEventListener("load",()=>{if(200===r.status||Database._ValidateXHRData(r,1))try{let t=JSON.parse(r.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&Database._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){noManifestFile()}else noManifestFile()},!1),r.addEventListener("error",()=>{if(t){t=!1;let e=createManifestURL();r.open("GET",e),r.send()}else noManifestFile()},!1);try{r.send()}catch(t){logger_Logger.Error("Error on XHR send request."),e(!1)}}open(e,t){let handleError=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline)){if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;let t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{handleError()},t.onblocked=()=>{logger_Logger.Error("IDB request blocked. Please reload the page."),handleError()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){logger_Logger.Error("Error while creating object stores. Exception: "+e.message),handleError()}}}}else this._isSupported=!1,t&&t()}loadImage(e,t){let i=Database._ReturnFullUrlLocation(e),saveAndLoadImage=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?saveAndLoadImage():this._loadImageFromDBAsync(i,t,saveAndLoadImage)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let r;let s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;r&&"function"==typeof URL?(s=URL.createObjectURL(r.data),t.onerror=()=>{logger_Logger.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};let a=s.objectStore("textures").get(e);a.onsuccess=e=>{r=e.target.result},a.onerror=()=>{logger_Logger.Error("Error loading texture "+e+" from DB."),t.src=e}}else logger_Logger.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){let generateBlobUrl=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(Database._IsUASupportingBlobStorage){let r=new webRequest_WebRequest;r.open("GET",e),r.responseType="blob",r.addEventListener("load",()=>{if(200===r.status&&this._db){i=r.response;let s=this._db.transaction(["textures"],"readwrite");s.onabort=e=>{try{let t=e.target,i=t.error;i&&"QuotaExceededError"===i.name&&(this._hasReachedQuota=!0)}catch(e){}generateBlobUrl()},s.oncomplete=()=>{generateBlobUrl()};let a={textureUrl:e,data:i};try{let e=s.objectStore("textures").put(a);e.onsuccess=()=>{},e.onerror=()=>{generateBlobUrl()}}catch(i){25===i.code&&(Database._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),r.addEventListener("error",()=>{logger_Logger.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),r.send()}else t.src=e}else logger_Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,()=>{this._saveVersionIntoDBAsync(e,t)})}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let r;try{let s=this._db.transaction(["versions"]);s.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};let a=s.objectStore("versions").get(e);a.onsuccess=e=>{r=e.target.result},a.onerror=()=>{logger_Logger.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){logger_Logger.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else logger_Logger.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{let i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};let r={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(r);s.onsuccess=()=>{},s.onerror=()=>{logger_Logger.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){logger_Logger.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,r,s){let a=Database._ReturnFullUrlLocation(e),saveAndLoadFile=()=>{this._saveFileAsync(a,t,i,s,r)};this._checkVersionFromDB(a,e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(a,t,i,s,r):this._loadFileAsync(a,t,saveAndLoadFile):r&&r()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let r,s;r=-1!==e.indexOf(".babylon")?"scenes":"textures";let a=this._db.transaction([r]);a.oncomplete=()=>{s?t(s.data):i()},a.onabort=()=>{i()};let n=a.objectStore(r).get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{logger_Logger.Error("Error loading file "+e+" from DB."),i()}}else logger_Logger.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,s){if(this._isSupported){let a,n;a=-1!==e.indexOf(".babylon")?"scenes":"textures";let o=new webRequest_WebRequest;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(200===o.status||o.status<400&&Database._ValidateXHRData(o,r?6:1)){if(n=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){let i;let r=this._db.transaction([a],"readwrite");r.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(n)},r.oncomplete=()=>{t(n)},i="scenes"===a?{sceneUrl:e,data:n,version:this._manifestVersionFound}:{textureUrl:e,data:n};try{let e=r.objectStore(a).put(i);e.onsuccess=()=>{},e.onerror=()=>{logger_Logger.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(n)}}else t(n)}else o.status>=400&&s?s(o):t()},!1),o.addEventListener("error",()=>{logger_Logger.Error("error on XHR request."),s&&s()},!1),o.send()}else logger_Logger.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){let i=GetTGAHeader(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){let t=new Uint8Array(e.response,0,3);if(68===t[0]&&68===t[1]&&83===t[2])return!0}}catch(e){}return!1}};Database._IsUASupportingBlobStorage=!0,Database.IDBStorageEnabled=!1,Database._ParseURL=e=>{let t=document.createElement("a");t.href=e;let i=e.substring(0,e.lastIndexOf("#")),r=e.substring(i.lastIndexOf("/")+1,e.length),s=e.substring(0,e.indexOf(r,0));return s},Database._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?Database._ParseURL(window.location.href)+e:e;let UniformBufferEffectCommonAccessor=class UniformBufferEffectCommonAccessor{_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))}};let na=`#version 300 es +void main() {discard;} +`;ShaderStore.ShadersStore.gpuUpdateParticlesPixelShader=na;let nn=`#version 300 es +#define PI 3.14159 +uniform float currentCount;uniform float timeDelta;uniform float stopFactor; +#ifndef LOCAL +uniform mat4 emitterWM; +#endif +uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; +#ifndef COLORGRADIENTS +uniform vec4 color1;uniform vec4 color2; +#endif +uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; +#ifdef BOXEMITTER +uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; +#endif +#ifdef POINTEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#endif +#ifdef HEMISPHERICEMITTER +uniform float radius;uniform float radiusRange;uniform float directionRandomizer; +#endif +#ifdef SPHEREEMITTER +uniform float radius;uniform float radiusRange; +#ifdef DIRECTEDSPHEREEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +#ifdef CYLINDEREMITTER +uniform float radius;uniform float height;uniform float radiusRange; +#ifdef DIRECTEDCYLINDEREMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +#ifdef CONEEMITTER +uniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer; +#endif +in vec3 position; +#ifdef CUSTOMEMITTER +in vec3 initialPosition; +#endif +in float age;in float life;in vec4 seed;in vec3 size; +#ifndef COLORGRADIENTS +in vec4 color; +#endif +in vec3 direction; +#ifndef BILLBOARD +in vec3 initialDirection; +#endif +#ifdef ANGULARSPEEDGRADIENTS +in float angle; +#else +in vec2 angle; +#endif +#ifdef ANIMATESHEET +in float cellIndex; +#ifdef ANIMATESHEETRANDOMSTART +in float cellStartOffset; +#endif +#endif +#ifdef NOISE +in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; +#endif +out vec3 outPosition; +#ifdef CUSTOMEMITTER +out vec3 outInitialPosition; +#endif +out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; +#ifndef COLORGRADIENTS +out vec4 outColor; +#endif +out vec3 outDirection; +#ifndef BILLBOARD +out vec3 outInitialDirection; +#endif +#ifdef ANGULARSPEEDGRADIENTS +out float outAngle; +#else +out vec2 outAngle; +#endif +#ifdef ANIMATESHEET +out float outCellIndex; +#ifdef ANIMATESHEETRANDOMSTART +out float outCellStartOffset; +#endif +#endif +#ifdef NOISE +out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; +#endif +#ifdef SIZEGRADIENTS +uniform sampler2D sizeGradientSampler; +#endif +#ifdef ANGULARSPEEDGRADIENTS +uniform sampler2D angularSpeedGradientSampler; +#endif +#ifdef VELOCITYGRADIENTS +uniform sampler2D velocityGradientSampler; +#endif +#ifdef LIMITVELOCITYGRADIENTS +uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; +#endif +#ifdef DRAGGRADIENTS +uniform sampler2D dragGradientSampler; +#endif +#ifdef NOISE +uniform vec3 noiseStrength;uniform sampler2D noiseSampler; +#endif +#ifdef ANIMATESHEET +uniform vec4 cellInfos; +#endif +vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} +vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} +void main() {float newAge=age+timeDelta; +if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; +#ifdef SIZEGRADIENTS +outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; +#else +outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; +#endif +outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; +#ifndef COLORGRADIENTS +outColor=color1+(color2-color1)*randoms.b; +#endif +#ifndef ANGULARSPEEDGRADIENTS +outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; +#else +outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; +#endif +#ifdef POINTEMITTER +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; +#elif defined(BOXEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; +#elif defined(HEMISPHERICEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; +#elif defined(SPHEREEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); +#ifdef DIRECTEDSPHEREEMITTER +newDirection=normalize(direction1+(direction2-direction1)*randoms3); +#else +newDirection=normalize(newPosition+directionRandomizer*randoms3); +#endif +#elif defined(CYLINDEREMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); +#ifdef DIRECTEDCYLINDEREMITTER +newDirection=direction1+(direction2-direction1)*randoms3; +#else +angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); +#endif +#elif defined(CONEEMITTER) +vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; +#ifdef CONEEMITTERSPAWNPOINT +float h=0.0001; +#else +float h=randoms2.y*height.y;h=1.-h*h; +#endif +float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); +if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); } +#elif defined(CUSTOMEMITTER) +newPosition=initialPosition;outInitialPosition=initialPosition; +#else +newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); +#endif +float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; +#ifdef LOCAL +outPosition=newPosition; +#else +outPosition=(emitterWM*vec4(newPosition,1.)).xyz; +#endif +#ifdef CUSTOMEMITTER +outDirection=direction; +#ifndef BILLBOARD +outInitialDirection=direction; +#endif +#else +#ifdef LOCAL +vec3 initial=newDirection; +#else +vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; +#endif +outDirection=initial*power; +#ifndef BILLBOARD +outInitialDirection=initial; +#endif +#endif +#ifdef ANIMATESHEET +outCellIndex=cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +outCellStartOffset=randoms.a*outLife; +#endif +#endif +#ifdef NOISE +outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; +#endif +} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; +#ifdef VELOCITYGRADIENTS +directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; +#endif +#ifdef DRAGGRADIENTS +directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; +#endif +#if defined(CUSTOMEMITTER) +outPosition=position+(direction-position)*ageGradient; +outInitialPosition=initialPosition; +#else +outPosition=position+direction*directionScale; +#endif +outLife=life;outSeed=seed; +#ifndef COLORGRADIENTS +outColor=color; +#endif +#ifdef SIZEGRADIENTS +outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; +#else +outSize=size; +#endif +#ifndef BILLBOARD +outInitialDirection=initialDirection; +#endif +#ifdef CUSTOMEMITTER +outDirection=direction; +#else +vec3 updatedDirection=direction+gravity*timeDelta; +#ifdef LIMITVELOCITYGRADIENTS +float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} +#endif +outDirection=updatedDirection; +#ifdef NOISE +float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; +#endif +#endif +#ifdef ANGULARSPEEDGRADIENTS +float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; +#else +outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); +#endif +#ifdef ANIMATESHEET +float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; +#else +float cellStartOffset=0.; +#endif +float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} +else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} +outCellIndex=float(int(cellInfos.x+ratio*dist)); +#endif +}}`;ShaderStore.ShadersStore.gpuUpdateParticlesVertexShader=nn;let WebGL2ParticleSystem=class WebGL2ParticleSystem{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e,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 CustomParticleEmitter&&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 effect_Effect("gpuUpdateParticles",this._updateEffectOptions,this._engine),new UniformBufferEffectCommonAccessor(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){let e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw 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);let r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e<this._updateVAO.length;e++)this._engine.releaseVertexArrayObject(this._updateVAO[e]);this._updateVAO.length=0;for(let e=0;e<this._renderVAO.length;e++)this._engine.releaseVertexArrayObject(this._renderVAO[e]);this._renderVAO.length=0}_createUpdateVAO(e){let t={};t.position=e.createVertexBuffer("position",0,3);let i=3;t.age=e.createVertexBuffer("age",i,1),i+=1,t.size=e.createVertexBuffer("size",i,3),i+=3,t.life=e.createVertexBuffer("life",i,1),i+=1,t.seed=e.createVertexBuffer("seed",i,4),i+=4,t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._parent.particleEmitterType instanceof CustomParticleEmitter&&(t.initialPosition=e.createVertexBuffer("initialPosition",i,3),i+=3),this._parent._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),this._parent._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._parent.noiseTexture&&(t.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",i,3),i+=3,t.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",i,3),i+=3),this._parent._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._parent._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1,this._parent.spriteRandomStartCell&&(t.cellStartOffset=e.createVertexBuffer("cellStartOffset",i,1),i+=1));let r=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),r}};h["BABYLON.WebGL2ParticleSystem"]=WebGL2ParticleSystem;let no=`struct Particle {position : vec3<f32>, +age : f32, +size : vec3<f32>, +life : f32, +seed : vec4<f32>, +direction : vec3<f32>, +dummy0: f32, +#ifdef CUSTOMEMITTER +initialPosition : vec3<f32>, +dummy1: f32, +#endif +#ifndef COLORGRADIENTS +color : vec4<f32>, +#endif +#ifndef BILLBOARD +initialDirection : vec3<f32>, +dummy2: f32, +#endif +#ifdef NOISE +noiseCoordinates1 : vec3<f32>, +dummy3: f32, +noiseCoordinates2 : vec3<f32>, +dummy4: f32, +#endif +#ifdef ANGULARSPEEDGRADIENTS +angle : f32, +#else +angle : vec2<f32>, +#endif +#ifdef ANIMATESHEET +cellIndex : f32, +#ifdef ANIMATESHEETRANDOMSTART +cellStartOffset : f32, +#endif +#endif +};struct Particles {particles : array<Particle>,};struct SimParams {currentCount : f32, +timeDelta : f32, +stopFactor : f32, +randomTextureSize: i32, +lifeTime : vec2<f32>, +emitPower : vec2<f32>, +#ifndef COLORGRADIENTS +color1 : vec4<f32>, +color2 : vec4<f32>, +#endif +sizeRange : vec2<f32>, +scaleRange : vec4<f32>, +angleRange : vec4<f32>, +gravity : vec3<f32>, +#ifdef LIMITVELOCITYGRADIENTS +limitVelocityDamping : f32, +#endif +#ifdef ANIMATESHEET +cellInfos : vec4<f32>, +#endif +#ifdef NOISE +noiseStrength : vec3<f32>, +#endif +#ifndef LOCAL +emitterWM : mat4x4<f32>, +#endif +#ifdef BOXEMITTER +direction1 : vec3<f32>, +direction2 : vec3<f32>, +minEmitBox : vec3<f32>, +maxEmitBox : vec3<f32>, +#endif +#ifdef CONEEMITTER +radius : vec2<f32>, +coneAngle : f32, +height : vec2<f32>, +directionRandomizer : f32, +#endif +#ifdef CYLINDEREMITTER +radius : f32, +height : f32, +radiusRange : f32, +#ifdef DIRECTEDCYLINDEREMITTER +direction1 : vec3<f32>, +direction2 : vec3<f32>, +#else +directionRandomizer : f32, +#endif +#endif +#ifdef HEMISPHERICEMITTER +radius : f32, +radiusRange : f32, +directionRandomizer : f32, +#endif +#ifdef POINTEMITTER +direction1 : vec3<f32>, +direction2 : vec3<f32>, +#endif +#ifdef SPHEREEMITTER +radius : f32, +radiusRange : f32, +#ifdef DIRECTEDSPHEREEMITTER +direction1 : vec3<f32>, +direction2 : vec3<f32>, +#else +directionRandomizer : f32, +#endif +#endif +};@binding(0) @group(0) var<uniform> params : SimParams;@binding(1) @group(0) var<storage,read> particlesIn : Particles;@binding(2) @group(0) var<storage,read_write> particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d<f32>;@binding(4) @group(0) var randomTexture2 : texture_2d<f32>; +#ifdef SIZEGRADIENTS +@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d<f32>; +#endif +#ifdef ANGULARSPEEDGRADIENTS +@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d<f32>; +#endif +#ifdef VELOCITYGRADIENTS +@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d<f32>; +#endif +#ifdef LIMITVELOCITYGRADIENTS +@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d<f32>; +#endif +#ifdef DRAGGRADIENTS +@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d<f32>; +#endif +#ifdef NOISE +@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d<f32>; +#endif +fn getRandomVec3(offset : f32,vertexID : f32)->vec3<f32> {return textureLoad(randomTexture2,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} +fn getRandomVec4(offset : f32,vertexID : f32)->vec4<f32> {return textureLoad(randomTexture,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3<u32>) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} +let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4<f32>=particlesIn.particles[index].seed;let direction : vec3<f32>=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3<f32>;var newDirection : vec3<f32>;let randoms : vec4<f32>=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; +#ifdef SIZEGRADIENTS +sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(0.,0.),0.).r; +#else +sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; +#endif +particlesOut.particles[index].size=vec3<f32>( +sizex, +params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, +params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); +#ifndef COLORGRADIENTS +particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; +#endif +#ifndef ANGULARSPEEDGRADIENTS +particlesOut.particles[index].angle=vec2<f32>( +params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, +params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); +#else +particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; +#endif +#if defined(POINTEMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=vec3<f32>(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#elif defined(BOXEMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#elif defined(HEMISPHERICEMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); +#elif defined(SPHEREEMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,randY,randZ); +#ifdef DIRECTEDSPHEREEMITTER +newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); +#else +newDirection=normalize(newPosition+params.directionRandomizer*randoms3); +#endif +#elif defined(CYLINDEREMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3<f32>(xPos,yPos,zPos); +#ifdef DIRECTEDCYLINDEREMITTER +newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#else +angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3<f32>(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); +#endif +#elif defined(CONEEMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; +#ifdef CONEEMITTERSPAWNPOINT +let h : f32=0.0001; +#else +var h : f32=randoms2.y*params.height.y;h=1.-h*h; +#endif +var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3<f32>(randX,randY,randZ); +if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3<f32>(0.,1.0,0.);} else {let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } +#elif defined(CUSTOMEMITTER) +newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; +#else +newPosition=vec3<f32>(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3<f32>(0.5,0.5,0.5)); +#endif +let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; +#ifdef LOCAL +particlesOut.particles[index].position=newPosition; +#else +particlesOut.particles[index].position=(params.emitterWM*vec4<f32>(newPosition,1.)).xyz; +#endif +#ifdef CUSTOMEMITTER +particlesOut.particles[index].direction=direction; +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=direction; +#endif +#else +#ifdef LOCAL +let initial : vec3<f32>=newDirection; +#else +let initial : vec3<f32>=(params.emitterWM*vec4<f32>(newDirection,0.)).xyz; +#endif +particlesOut.particles[index].direction=initial*power; +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=initial; +#endif +#endif +#ifdef ANIMATESHEET +particlesOut.particles[index].cellIndex=params.cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +particlesOut.particles[index].cellStartOffset=randoms.a*outLife; +#endif +#endif +#ifdef NOISE +particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; +#endif +} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; +#ifdef VELOCITYGRADIENTS +directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r; +#endif +#ifdef DRAGGRADIENTS +directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2<f32>(ageGradient,0.),0.).r); +#endif +let position : vec3<f32>=particlesIn.particles[index].position; +#if defined(CUSTOMEMITTER) +particlesOut.particles[index].position=position+(direction-position)*ageGradient; +particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; +#else +particlesOut.particles[index].position=position+direction*directionScale; +#endif +particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; +#ifndef COLORGRADIENTS +particlesOut.particles[index].color=particlesIn.particles[index].color; +#endif +#ifdef SIZEGRADIENTS +particlesOut.particles[index].size=vec3<f32>( +textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(ageGradient,0.),0.).r, +particlesIn.particles[index].size.yz); +#else +particlesOut.particles[index].size=particlesIn.particles[index].size; +#endif +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; +#endif +#ifdef CUSTOMEMITTER +particlesOut.particles[index].direction=direction; +#else +var updatedDirection : vec3<f32>=direction+params.gravity*timeDelta; +#ifdef LIMITVELOCITYGRADIENTS +let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} +#endif +particlesOut.particles[index].direction=updatedDirection; +#ifdef NOISE +let noiseCoordinates1 : vec3<f32>=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3<f32>=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.x,noiseCoordinates1.y)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.z,noiseCoordinates2.x)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates2.y,noiseCoordinates2.z)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let force : vec3<f32>=vec3<f32>(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; +#endif +#endif +#ifdef ANGULARSPEEDGRADIENTS +let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2<f32>(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; +#else +let angle : vec2<f32>=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2<f32>(angle.x+angle.y*timeDelta,angle.y); +#endif +#ifdef ANIMATESHEET +var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; +#else +let cellStartOffset : f32=0.; +#endif +var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} +else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} +particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); +#endif +}} +`;ShaderStore.ShadersStoreWGSL.gpuUpdateParticlesComputeShader=no;let ComputeShaderParticleSystem=class ComputeShaderParticleSystem{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}contextLost(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateComputeShader)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){var t;let i={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new ComputeShader("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split("\n")}),null===(t=this._simParamsComputeShader)||void 0===t||t.dispose(),this._simParamsComputeShader=new UniformBuffer(this._engine),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new UniformBufferEffectCommonAccessor(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){let t=new StorageBuffer(this._engine,4*e.length,11);return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)}preUpdateParticleBuffer(){}updateParticleBuffer(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[1^e]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let e=0;e<this._bufferComputeShader.length;++e)this._bufferComputeShader[e].dispose();this._bufferComputeShader.length=0,null===(e=this._simParamsComputeShader)||void 0===e||e.dispose(),this._simParamsComputeShader=null,this._updateComputeShader=null}releaseVertexBuffers(){this._renderVertexBuffers.length=0}};h["BABYLON.ComputeShaderParticleSystem"]=ComputeShaderParticleSystem;let ColorGradient=class ColorGradient{constructor(e,t,i){this.gradient=e,this.color1=t,this.color2=i}getColorToRef(e){if(!this.color2){e.copyFrom(this.color1);return}math_color_Color4.LerpToRef(this.color1,this.color2,Math.random(),e)}};let Color3Gradient=class Color3Gradient{constructor(e,t){this.gradient=e,this.color=t}};let FactorGradient=class FactorGradient{constructor(e,t,i){this.gradient=e,this.factor1=t,this.factor2=i}getFactor(){return void 0===this.factor2||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()}};let GradientHelper=class GradientHelper{static GetCurrentGradient(e,t,i){if(t[0].gradient>e){i(t[0],t[0],1);return}for(let r=0;r<t.length-1;r++){let s=t[r],a=t[r+1];if(e>=s.gradient&&e<=a.gradient){let t=(e-s.gradient)/(a.gradient-s.gradient);i(s,a,t);return}}let r=t.length-1;i(t[r],t[r],1)}};let Particle=class Particle{constructor(e){if(this.particleSystem=e,this.position=math_vector_Vector3.Zero(),this.direction=math_vector_Vector3.Zero(),this.color=new math_color_Color4(0,0,0,0),this.colorStep=new math_color_Color4(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new math_vector_Vector2(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new math_color_Color4(0,0,0,0),this._currentColor2=new math_color_Color4(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=Particle._Count++,!this.particleSystem.isAnimationSheetEnabled)return;this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e,t=this.age,i=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===i?(i=1,t=this._randomCellOffset):t+=this._randomCellOffset);let r=this._initialEndSpriteCellID-this._initialStartSpriteCellID;e=this._initialSpriteCellLoop?math_scalar_Scalar.Clamp(t*i%this.lifeTime/this.lifeTime):math_scalar_Scalar.Clamp(t*i/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+e*r|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){let t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){let e=math_vector_TmpVectors.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else{let t=e.particleSystem.emitter;t.copyFrom(this.position)}this.direction.scaleToRef(e.inheritedVelocityAmount/2,math_vector_TmpVectors.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(math_vector_TmpVectors.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=Particle._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 math_vector_Vector4(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()))}};Particle._Count=0,function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(tq||(tq={}));let SubEmitter=class SubEmitter{constructor(e){if(this.particleSystem=e,this.type=tq.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){let t=h["BABYLON.AbstractMesh"];e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(e){if(e instanceof math_vector_Vector3)e=e.clone();else if(-1!==e.getClassName().indexOf("Mesh")){let t=h["BABYLON.Mesh"];(e=new t("",e.getScene())).isVisible=!1}}else e=new math_vector_Vector3;let t=new SubEmitter(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){let t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw _WarnImport("ParseParticle")}static Parse(e,t,i){let r=e.particleSystem,s=new SubEmitter(SubEmitter._ParseParticleSystem(r,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}};let nl=`#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; +#include<clipPlaneFragmentDeclaration> +#include<imageProcessingDeclaration> +#include<logDepthDeclaration> +#include<helperFunctions> +#include<imageProcessingFunctions> +#ifdef RAMPGRADIENT +varying vec4 remapRanges;uniform sampler2D rampSampler; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; +#ifdef RAMPGRADIENT +float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); +#endif +#ifdef BLENDMULTIPLYMODE +float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); +#endif +#include<logDepthFragment> +#ifdef IMAGEPROCESSINGPOSTPROCESS +baseColor.rgb=toLinearSpace(baseColor.rgb); +#else +#ifdef IMAGEPROCESSING +baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); +#endif +#endif +gl_FragColor=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`;ShaderStore.ShadersStore.particlesPixelShader=nl;let nh=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; +#ifdef ANIMATESHEET +attribute float cellIndex; +#endif +#ifndef BILLBOARD +attribute vec3 direction; +#endif +#ifdef BILLBOARDSTRETCHED +attribute vec3 direction; +#endif +#ifdef RAMPGRADIENT +attribute vec4 remapData; +#endif +attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; +#ifdef ANIMATESHEET +uniform vec3 particlesInfos; +#endif +varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; +#ifdef RAMPGRADIENT +varying vec4 remapRanges; +#endif +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform mat4 invView; +#endif +#include<clipPlaneVertexDeclaration> +#include<logDepthDeclaration> +#ifdef BILLBOARD +uniform vec3 eyePosition; +#endif +vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} +#ifdef BILLBOARDSTRETCHED +vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); +#ifdef BILLBOARDSTRETCHED_LOCAL +vec3 row1=direction; +#else +vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); +#endif +mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; +#ifdef BILLBOARD +vec3 rotatedCorner; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; +#else +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; +#endif +#ifdef RAMPGRADIENT +remapRanges=remapData; +#endif +gl_Position=projection*vec4(viewPos,1.0); +#else +vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); +#endif +vColor=color; +#ifdef ANIMATESHEET +float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; +#else +vUV=offset; +#endif +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include<clipPlaneVertex> +#include<logDepthVertex> +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.particlesVertexShader=nh;let particleSystem_ParticleSystem=class particleSystem_ParticleSystem extends BaseParticleSystem{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 drawWrapper_DrawWrapper(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 observable_Observable),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,s=!1,a=.01){super(e),this._emitterInverseWorldMatrix=math_vector_Matrix.Identity(),this._inheritedVelocityOffset=new math_vector_Vector3,this.onDisposeObservable=new observable_Observable,this.onStoppedObservable=new observable_Observable,this._particles=[],this._stockParticles=[],this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new math_color_Color4(0,0,0,0),this._colorDiff=new math_color_Color4(0,0,0,0),this._scaledDirection=math_vector_Vector3.Zero(),this._scaledGravity=math_vector_Vector3.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=>{let 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())._reset():e=new Particle(this),this._subEmitters&&this._subEmitters.length>0){let t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(t=>{if(t.type===tq.ATTACHED){let i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}})}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;let t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach(t=>{if(t.type===tq.END){let i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}})},this._capacity=t,this._epsilon=a,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=math_vector_Matrix.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||engineStore_EngineStore.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 drawWrapper_DrawWrapper(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new BoxParticleEmitter;let n=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=>{n=e}));let r=e===this._particles;for(let t=0;t<e.length;t++){let s=e[t],a=this._scaledUpdateSpeed,o=s.age;if(s.age+=a,s.age>s.lifeTime){let e=s.age-o,t=s.lifeTime-o;a=t*a/e,s.age=s.lifeTime}let l=s.age/s.lifeTime;this._colorGradients&&this._colorGradients.length>0?GradientHelper.GetCurrentGradient(l,this._colorGradients,(e,t,i)=>{e!==s._currentColorGradient&&(s._currentColor1.copyFrom(s._currentColor2),t.getColorToRef(s._currentColor2),s._currentColorGradient=e),math_color_Color4.LerpToRef(s._currentColor1,s._currentColor2,i,s.color)}):(s.colorStep.scaleToRef(a,this._scaledColorStep),s.color.addInPlace(this._scaledColorStep),s.color.a<0&&(s.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._angularSpeedGradients,(e,t,i)=>{e!==s._currentAngularSpeedGradient&&(s._currentAngularSpeed1=s._currentAngularSpeed2,s._currentAngularSpeed2=t.getFactor(),s._currentAngularSpeedGradient=e),s.angularSpeed=math_scalar_Scalar.Lerp(s._currentAngularSpeed1,s._currentAngularSpeed2,i)}),s.angle+=s.angularSpeed*a;let h=a;if(this._velocityGradients&&this._velocityGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._velocityGradients,(e,t,i)=>{e!==s._currentVelocityGradient&&(s._currentVelocity1=s._currentVelocity2,s._currentVelocity2=t.getFactor(),s._currentVelocityGradient=e),h*=math_scalar_Scalar.Lerp(s._currentVelocity1,s._currentVelocity2,i)}),s.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._limitVelocityGradients,(e,t,i)=>{e!==s._currentLimitVelocityGradient&&(s._currentLimitVelocity1=s._currentLimitVelocity2,s._currentLimitVelocity2=t.getFactor(),s._currentLimitVelocityGradient=e);let r=math_scalar_Scalar.Lerp(s._currentLimitVelocity1,s._currentLimitVelocity2,i),a=s.direction.length();a>r&&s.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._dragGradients,(e,t,i)=>{e!==s._currentDragGradient&&(s._currentDrag1=s._currentDrag2,s._currentDrag2=t.getFactor(),s._currentDragGradient=e);let r=math_scalar_Scalar.Lerp(s._currentDrag1,s._currentDrag2,i);this._scaledDirection.scaleInPlace(1-r)}),this.isLocal&&s._localPosition?(s._localPosition.addInPlace(this._scaledDirection),math_vector_Vector3.TransformCoordinatesToRef(s._localPosition,this._emitterWorldMatrix,s.position)):s.position.addInPlace(this._scaledDirection),n&&i&&s._randomNoiseCoordinates1){let e=this._fetchR(s._randomNoiseCoordinates1.x,s._randomNoiseCoordinates1.y,i.width,i.height,n),t=this._fetchR(s._randomNoiseCoordinates1.z,s._randomNoiseCoordinates2.x,i.width,i.height,n),r=this._fetchR(s._randomNoiseCoordinates2.y,s._randomNoiseCoordinates2.z,i.width,i.height,n),o=math_vector_TmpVectors.Vector3[0],l=math_vector_TmpVectors.Vector3[1];o.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*t-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),o.scaleToRef(a,l),s.direction.addInPlace(l)}if(this.gravity.scaleToRef(a,this._scaledGravity),s.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._sizeGradients,(e,t,i)=>{e!==s._currentSizeGradient&&(s._currentSize1=s._currentSize2,s._currentSize2=t.getFactor(),s._currentSizeGradient=e),s.size=math_scalar_Scalar.Lerp(s._currentSize1,s._currentSize2,i)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._colorRemapGradients,(e,t,i)=>{let r=math_scalar_Scalar.Lerp(e.factor1,t.factor1,i),a=math_scalar_Scalar.Lerp(e.factor2,t.factor2,i);s.remapData.x=r,s.remapData.y=a-r}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._alphaRemapGradients,(e,t,i)=>{let r=math_scalar_Scalar.Lerp(e.factor1,t.factor1,i),a=math_scalar_Scalar.Lerp(e.factor2,t.factor2,i);s.remapData.z=r,s.remapData.w=a-r})),this._isAnimationSheetEnabled&&s.updateCellIndex(),s._inheritParticleInfoToSubEmitters(),s.age>=s.lifeTime){this._emitFromParticle(s),s._attachedSubEmitters&&(s._attachedSubEmitters.forEach(e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()}),s._attachedSubEmitters=null),this.recycleParticle(s),r&&t--;continue}}}}_addFactorGradient(e,t,i,r){let s=new FactorGradient(t,i,r);e.push(s),e.sort((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(let r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;let e=new Uint8Array(4*this._rawTextureWidth),t=TmpColors.Color3[0];for(let i=0;i<this._rawTextureWidth;i++){let r=i/this._rawTextureWidth;GradientHelper.GetCurrentGradient(r,this._rampGradients,(r,s,a)=>{math_color_Color3.LerpToRef(r.color,s.color,a,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=rawTexture_RawTexture.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.gradient<t.gradient?-1:e.gradient>t.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);let i=new Color3Gradient(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=[]);let r=new ColorGradient(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(let i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(let e of this._drawWrappers)if(e)for(let t of e)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,s){e=.5*Math.abs(e)+.5,t=.5*Math.abs(t)+.5;let a=e*i%i|0,n=t*r%r|0;return s[(a+n*i)*4]/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(){let e;this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);let t=this._engine,i=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*i),this._vertexBuffer=new Buffer(t,this._vertexData,!0,i);let r=0,s=this._vertexBuffer.createVertexBuffer(buffer_VertexBuffer.PositionKind,r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[buffer_VertexBuffer.PositionKind]=s,r+=3;let a=this._vertexBuffer.createVertexBuffer(buffer_VertexBuffer.ColorKind,r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[buffer_VertexBuffer.ColorKind]=a,r+=4;let n=this._vertexBuffer.createVertexBuffer("angle",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,r+=1;let o=this._vertexBuffer.createVertexBuffer("size",r,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,r+=2,this._isAnimationSheetEnabled){let e=this._vertexBuffer.createVertexBuffer("cellIndex",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,r+=1}if(!this._isBillboardBased||this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED||this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL){let e=this._vertexBuffer.createVertexBuffer("direction",r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,r+=3}if(this._useRampGradients){let e=this._vertexBuffer.createVertexBuffer("remapData",r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,r+=4}if(this._useInstancing){let i=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Buffer(t,i,!1,2),e=this._spriteBuffer.createVertexBuffer("offset",0,2)}else e=this._vertexBuffer.createVertexBuffer("offset",r,2,this._vertexBufferSize,this._useInstancing),r+=2;this._vertexBuffers.offset=e,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));return}let e=[],t=[],i=0;for(let r=0;r<this._capacity;r++)e.push(i),e.push(i+1),e.push(i+2),e.push(i),e.push(i+2),e.push(i+3),t.push(i,i+1,i+1,i+2,i+2,i+3,i+3,i,i,i+3),i+=4;this._indexBuffer=this._engine.createIndexBuffer(e),this._linesIndexBuffer=this._engine.createIndexBuffer(t)}getCapacity(){return this._capacity}isAlive(){return this._alive}isStarted(){return this._started}_prepareSubEmitterInternalArray(){this._subEmitters=[],this.subEmitters&&this.subEmitters.forEach(e=>{e instanceof particleSystem_ParticleSystem?this._subEmitters.push([new SubEmitter(e)]):e instanceof SubEmitter?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);return}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[]),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){(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);let e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce(()=>{setTimeout(()=>{for(let t=0;t<this.preWarmCycles;t++)this.animate(!0),e.render()})});else for(let e=0;e<this.preWarmCycles;e++)this.animate(!0)}this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&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,r){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED||this.billboardMode===particleSystem_ParticleSystem.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&&(math_vector_Vector3.TransformNormalToRef(e,this._emitterWorldMatrix,math_vector_TmpVectors.Vector3[0]),e=math_vector_TmpVectors.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&&(math_vector_Vector3.TransformNormalToRef(e,this._emitterWorldMatrix,math_vector_TmpVectors.Vector3[0]),e=math_vector_TmpVectors.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=r)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;let e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){let t;if(this._alive=this._particles.length>0,this.emitter.position){let e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{let e=this.emitter;this._emitterWorldMatrix=math_vector_Matrix.Translation(e.x,e.y,e.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i<e&&this._particles.length!==this._capacity;i++){if(t=this._createParticle(),this._particles.push(t),this.targetStopDuration&&this._lifeTimeGradients&&this._lifeTimeGradients.length>0){let e=math_scalar_Scalar.Clamp(this._actualFrame/this.targetStopDuration);GradientHelper.GetCurrentGradient(e,this._lifeTimeGradients,(i,r)=>{let s=i.getFactor(),a=r.getFactor(),n=(e-i.gradient)/(r.gradient-i.gradient);t.lifeTime=math_scalar_Scalar.Lerp(s,a,n)})}else t.lifeTime=math_scalar_Scalar.RandomRange(this.minLifeTime,this.maxLifeTime);let e=math_scalar_Scalar.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(),math_vector_Vector3.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=math_scalar_Scalar.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(math_scalar_Scalar.RandomRange(this.minScaleX,this.maxScaleX),math_scalar_Scalar.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){let e=this._actualFrame/this.targetStopDuration;GradientHelper.GetCurrentGradient(e,this._startSizeGradients,(e,i,r)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);let s=math_scalar_Scalar.Lerp(this._currentStartSize1,this._currentStartSize2,r);t.scale.scaleInPlace(s)})}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=math_scalar_Scalar.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=math_scalar_Scalar.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{let e=math_scalar_Scalar.RandomRange(0,1);math_color_Color4.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 math_vector_Vector4(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 math_vector_Vector3(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new math_vector_Vector3(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){let r=[buffer_VertexBuffer.PositionKind,buffer_VertexBuffer.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1){let i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return addClipPlaneUniforms(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&prepareStringDefinesForClipPlanes(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===particleSystem_ParticleSystem.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case particleSystem_ParticleSystem.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED:case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case particleSystem_ParticleSystem.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(...particleSystem_ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...particleSystem_ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ImageProcessingConfiguration.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0,s=this._drawWrappers[r];s||(s=this._drawWrappers[r]=[]);let a=s[e];a||((a=new drawWrapper_DrawWrapper(this._engine)).drawContext&&(a.drawContext.useInstancing=this._useInstancing),s[e]=a);let n=i.join("\n");if(a.defines!==n){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),a.setEffect(this._engine.createEffect("particles",e,t,i,n),n)}return a}animate(e=!1){var t;let i;if(this._started){if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}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){let t=this._actualFrame/this.targetStopDuration;GradientHelper.GetCurrentGradient(t,this._emitRateGradients,(t,i,r)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=math_scalar_Scalar.Lerp(this._currentEmitRate1,this._currentEmitRate2,r)})}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<this._particles.length;t++){let i=this._particles[t];this._appendParticleVertices(e,i),e+=this._useInstancing?1:4}this._vertexBuffer&&this._vertexBuffer.updateDirectly(this._vertexData,0,this._particles.length)}0===this.manualEmitCount&&this.disposeOnStop&&this.stop()}}_appendParticleVertices(e,t){this._appendParticleVertex(e++,t,0,0),this._useInstancing||(this._appendParticleVertex(e++,t,1,0),this._appendParticleVertex(e++,t,1,1),this._appendParticleVertex(e++,t,0,1))}rebuild(){var e,t;for(let i in this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._createIndexBuffer(),null===(e=this._spriteBuffer)||void 0===e||e._rebuild(),null===(t=this._vertexBuffer)||void 0===t||t._rebuild(),this._vertexBuffers)this._vertexBuffers[i]._rebuild();this.resetDrawCache()}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_ADD).effect.isReady())return!1;return!0}_render(e){var t,i,r,s,a,n,o,l;let h=this._getWrapper(e),c=h.effect,u=this._engine;u.enableEffect(h);let d=null!==(t=this.defaultViewMatrix)&&void 0!==t?t:this._scene.getViewMatrix();if(c.setTexture("diffuseSampler",this.particleTexture),c.setMatrix("view",d),c.setMatrix("projection",null!==(i=this.defaultProjectionMatrix)&&void 0!==i?i:this._scene.getProjectionMatrix()),this._isAnimationSheetEnabled&&this.particleTexture){let e=this.particleTexture.getBaseSize();c.setFloat3("particlesInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,this.spriteCellWidth/e.width)}if(c.setVector2("translationPivot",this.translationPivot),c.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._isBillboardBased&&this._scene){let e=this._scene.activeCamera;c.setVector3("eyePosition",e.globalPosition)}this._rampGradientsTexture&&(this._rampGradients&&this._rampGradients.length||(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),c.setTexture("rampSampler",this._rampGradientsTexture));let _=c.defines;switch(this._scene&&bindClipPlane(c,this,this._scene),_.indexOf("#define BILLBOARDMODE_ALL")>=0&&(d.invertToRef(math_vector_TmpVectors.Matrix[0]),c.setMatrix("invView",math_vector_TmpVectors.Matrix[0])),void 0!==this._vertexArrayObject?(null===(r=this._scene)||void 0===r?void 0:r.forceWireframe)?u.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,c):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,c)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?u.bindBuffers(this._vertexBuffers,(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._linesIndexBuffer:this._indexBuffer,c):u.bindBuffers(this._vertexBuffers,(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)?this._linesIndexBufferUseInstancing:null,c),this.useLogarithmicDepth&&this._scene&&MaterialHelper.BindLogDepth(_,c,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(c),e){case particleSystem_ParticleSystem.BLENDMODE_ADD:u.setAlphaMode(1);break;case particleSystem_ParticleSystem.BLENDMODE_ONEONE:u.setAlphaMode(6);break;case particleSystem_ParticleSystem.BLENDMODE_STANDARD:u.setAlphaMode(2);break;case particleSystem_ParticleSystem.BLENDMODE_MULTIPLY:u.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(c),this._useInstancing?(null===(o=this._scene)||void 0===o?void 0:o.forceWireframe)?u.drawElementsType(6,0,10,this._particles.length):u.drawArraysType(7,0,4,this._particles.length):(null===(l=this._scene)||void 0===l?void 0:l.forceWireframe)?u.drawElementsType(1,0,10*this._particles.length):u.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;let e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD?this._render(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY)+this._render(particleSystem_ParticleSystem.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._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let e=0;e<this._subEmitters.length;e++)for(let t of this._subEmitters[e])t.dispose();this._subEmitters=[],this.subEmitters=[]}if(this._disposeEmitterOnDispose&&this.emitter&&this.emitter.dispose&&this.emitter.dispose(!0),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){let e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){let r=Object.assign({},this._customWrappers),s=null,a=this._engine;if(a.createEffectForParticles&&null!=this.customShader){s=this.customShader;let e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=a.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);r[0]?r[0].effect=t:this.setCustomEffect(t,0)}let n=this.serialize(i),o=particleSystem_ParticleSystem.Parse(n,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,this.preventAutoStart||o.start(),o}serialize(e=!1){let t={};if(particleSystem_ParticleSystem._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters)for(let i of(t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray(),this._subEmitters)){let r=[];for(let t of i)r.push(t.serialize(e));t.subEmitters.push(r)}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){let i=t.emitter;e.emitterId=i.id}else{let 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,decorators_SerializationHelper.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;let r=t.getColorGradients();if(r)for(let t of(e.colorGradients=[],r)){let i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}let s=t.getRampGradients();if(s){for(let t of(e.rampGradients=[],s)){let i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}let a=t.getColorRemapGradients();if(a)for(let t of(e.colorRemapGradients=[],a)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}let n=t.getAlphaRemapGradients();if(n)for(let t of(e.alphaRemapGradients=[],n)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}let o=t.getSizeGradients();if(o)for(let t of(e.sizeGradients=[],o)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}let l=t.getAngularSpeedGradients();if(l)for(let t of(e.angularSpeedGradients=[],l)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}let h=t.getVelocityGradients();if(h)for(let t of(e.velocityGradients=[],h)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}let c=t.getDragGradients();if(c)for(let t of(e.dragGradients=[],c)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}let u=t.getEmitRateGradients();if(u)for(let t of(e.emitRateGradients=[],u)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}let d=t.getStartSizeGradients();if(d)for(let t of(e.startSizeGradients=[],d)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}let _=t.getLifeTimeGradients();if(_)for(let t of(e.lifeTimeGradients=[],_)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}let p=t.getLimitVelocityGradients();if(p){for(let t of(e.limitVelocityGradients=[],p)){let 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,r){var s,a,n;let o,l;o=i instanceof ThinEngine?null:i;let c=h["BABYLON.Texture"];if(c&&o&&(e.texture?t.particleTexture=c.Parse(e.texture,o,r):e.textureName&&(t.particleTexture=new c(r+e.textureName,o,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&o?t.emitter=o.getLastMeshById(e.emitterId):t.emitter=math_vector_Vector3.FromArray(e.emitter):t.emitter=math_vector_Vector3.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;i<e.animations.length;i++){let r=e.animations[i],s=h["BABYLON.Animation"];s&&t.animations.push(s.Parse(r))}t.beginAnimationOnStart=e.beginAnimationOnStart,t.beginAnimationFrom=e.beginAnimationFrom,t.beginAnimationTo=e.beginAnimationTo,t.beginAnimationLoop=e.beginAnimationLoop}if(e.autoAnimate&&o&&o.beginAnimation(t,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),t.startDelay=0|e.startDelay,t.minAngularSpeed=e.minAngularSpeed,t.maxAngularSpeed=e.maxAngularSpeed,t.minSize=e.minSize,t.maxSize=e.maxSize,e.minScaleX&&(t.minScaleX=e.minScaleX,t.maxScaleX=e.maxScaleX,t.minScaleY=e.minScaleY,t.maxScaleY=e.maxScaleY),void 0!==e.preWarmCycles&&(t.preWarmCycles=e.preWarmCycles,t.preWarmStepOffset=e.preWarmStepOffset),void 0!==e.minInitialRotation&&(t.minInitialRotation=e.minInitialRotation,t.maxInitialRotation=e.maxInitialRotation),t.minLifeTime=e.minLifeTime,t.maxLifeTime=e.maxLifeTime,t.minEmitPower=e.minEmitPower,t.maxEmitPower=e.maxEmitPower,t.emitRate=e.emitRate,t.gravity=math_vector_Vector3.FromArray(e.gravity),e.noiseStrength&&(t.noiseStrength=math_vector_Vector3.FromArray(e.noiseStrength)),t.color1=math_color_Color4.FromArray(e.color1),t.color2=math_color_Color4.FromArray(e.color2),t.colorDead=math_color_Color4.FromArray(e.colorDead),t.updateSpeed=e.updateSpeed,t.targetStopDuration=e.targetStopDuration,t.blendMode=e.blendMode,e.colorGradients)for(let i of e.colorGradients)t.addColorGradient(i.gradient,math_color_Color4.FromArray(i.color1),i.color2?math_color_Color4.FromArray(i.color2):void 0);if(e.rampGradients){for(let i of e.rampGradients)t.addRampGradient(i.gradient,math_color_Color3.FromArray(i.color));t.useRampGradients=e.useRampGradients}if(e.colorRemapGradients)for(let i of e.colorRemapGradients)t.addColorRemapGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.alphaRemapGradients)for(let i of e.alphaRemapGradients)t.addAlphaRemapGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.sizeGradients)for(let i of e.sizeGradients)t.addSizeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.angularSpeedGradients)for(let i of e.angularSpeedGradients)t.addAngularSpeedGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.velocityGradients)for(let i of e.velocityGradients)t.addVelocityGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.dragGradients)for(let i of e.dragGradients)t.addDragGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.emitRateGradients)for(let i of e.emitRateGradients)t.addEmitRateGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.startSizeGradients)for(let i of e.startSizeGradients)t.addStartSizeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.lifeTimeGradients)for(let i of e.lifeTimeGradients)t.addLifeTimeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.limitVelocityGradients){for(let i of e.limitVelocityGradients)t.addLimitVelocityGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);t.limitVelocityDamping=e.limitVelocityDamping}if(e.noiseTexture&&o){let i=h["BABYLON.ProceduralTexture"];t.noiseTexture=i.Parse(e.noiseTexture,o,r)}if(e.particleEmitterType){switch(e.particleEmitterType.type){case"SphereParticleEmitter":l=new SphereParticleEmitter;break;case"SphereDirectedParticleEmitter":l=new SphereDirectedParticleEmitter;break;case"ConeEmitter":case"ConeParticleEmitter":l=new ConeParticleEmitter;break;case"CylinderParticleEmitter":l=new CylinderParticleEmitter;break;case"CylinderDirectedParticleEmitter":l=new CylinderDirectedParticleEmitter;break;case"HemisphericParticleEmitter":l=new HemisphericParticleEmitter;break;case"PointParticleEmitter":l=new PointParticleEmitter;break;case"MeshParticleEmitter":l=new MeshParticleEmitter;break;default:l=new BoxParticleEmitter}l.parse(e.particleEmitterType,o)}else(l=new BoxParticleEmitter).parse(e,o);t.particleEmitterType=l,t.startSpriteCellID=e.startSpriteCellID,t.endSpriteCellID=e.endSpriteCellID,t.spriteCellLoop=null===(s=e.spriteCellLoop)||void 0===s||s,t.spriteCellWidth=e.spriteCellWidth,t.spriteCellHeight=e.spriteCellHeight,t.spriteCellChangeSpeed=e.spriteCellChangeSpeed,t.spriteRandomStartCell=e.spriteRandomStartCell,t.disposeOnStop=null!==(a=e.disposeOnStop)&&void 0!==a&&a,t.manualEmitCount=null!==(n=e.manualEmitCount)&&void 0!==n?n:-1}static Parse(e,t,i,r=!1,s){let a;let n=e.name,o=null,l=null;if(a=t instanceof ThinEngine?t:t.getEngine(),e.customShader&&a.createEffectForParticles){l=e.customShader;let t=l.shaderOptions.defines.length>0?l.shaderOptions.defines.join("\n"):"";o=a.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,t)}let h=new particleSystem_ParticleSystem(n,s||e.capacity,t,o,e.isAnimationSheetEnabled);if(h.customShader=l,h._rootUrl=i,e.id&&(h.id=e.id),e.subEmitters)for(let r of(h.subEmitters=[],e.subEmitters)){let e=[];for(let s of r)e.push(SubEmitter.Parse(s,t,i));h.subEmitters.push(e)}return particleSystem_ParticleSystem._Parse(e,h,t,i),e.textureMask&&(h.textureMask=math_color_Color4.FromArray(e.textureMask)),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),r||h.preventAutoStart||h.start(),h}};particleSystem_ParticleSystem.BILLBOARDMODE_Y=2,particleSystem_ParticleSystem.BILLBOARDMODE_ALL=7,particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED=8,particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL=9,SubEmitter._ParseParticleSystem=particleSystem_ParticleSystem.Parse;let nc=`#ifdef CLIPPLANE +in float fClipDistance; +#endif +#ifdef CLIPPLANE2 +in float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +in float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +in float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +in float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +in float fClipDistance6; +#endif +`;ShaderStore.IncludesShadersStore.clipPlaneFragmentDeclaration2=nc;let nu=`precision highp float; +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; +#include<clipPlaneFragmentDeclaration2> +#include<imageProcessingDeclaration> +#include<logDepthDeclaration> +#include<helperFunctions> +#include<imageProcessingFunctions> +void main() { +#include<clipPlaneFragment> +vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; +#ifdef BLENDMULTIPLYMODE +float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); +#endif +#include<logDepthFragment> +#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); +#else +#ifdef IMAGEPROCESSING +gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); +#endif +#endif +} +`;ShaderStore.ShadersStore.gpuRenderParticlesPixelShader=nu;let nd=`#ifdef CLIPPLANE +uniform vec4 vClipPlane;out float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;out float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;out float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;out float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;out float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;out float fClipDistance6; +#endif +`;ShaderStore.IncludesShadersStore.clipPlaneVertexDeclaration2=nd;let n_=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; +#ifdef LOCAL +uniform mat4 emitterWM; +#endif +attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; +#ifndef BILLBOARD +attribute vec3 initialDirection; +#endif +#ifdef BILLBOARDSTRETCHED +attribute vec3 direction; +#endif +attribute float angle; +#ifdef ANIMATESHEET +attribute float cellIndex; +#endif +attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform mat4 invView; +#endif +#include<clipPlaneVertexDeclaration2> +#include<logDepthDeclaration> +#ifdef COLORGRADIENTS +uniform sampler2D colorGradientSampler; +#else +uniform vec4 colorDead;attribute vec4 color; +#endif +#ifdef ANIMATESHEET +uniform vec3 sheetInfos; +#endif +#ifdef BILLBOARD +uniform vec3 eyePosition; +#endif +vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; +#ifdef LOCAL +return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; +#else +return (position+worldOffset)+alignedCorner; +#endif +} +#ifdef BILLBOARDSTRETCHED +vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; +#ifdef LOCAL +return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; +#else +return (position+worldOffset)+alignedCorner; +#endif +} +#endif +void main() { +#ifdef ANIMATESHEET +float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; +#else +vUV=uv; +#endif +float ratio=age/life; +#ifdef COLORGRADIENTS +vColor=texture2D(colorGradientSampler,vec2(ratio,0)); +#else +vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); +#endif +vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; +#ifdef BILLBOARD +vec4 rotatedCorner;rotatedCorner.w=0.; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); +#else +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; +#ifdef LOCAL +vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; +#else +vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; +#endif +vPositionW=(invView*viewPosition).xyz; +#endif +#else +vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); +#endif +gl_Position=projection*viewPosition; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include<clipPlaneVertex> +#include<logDepthVertex> +}`;ShaderStore.ShadersStore.gpuRenderParticlesVertexShader=n_;let GPUParticleSystem=class GPUParticleSystem extends BaseParticleSystem{static get IsSupported(){if(!engineStore_EngineStore.LastCreatedEngine)return!1;let e=engineStore_EngineStore.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]))}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t,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 drawWrapper_DrawWrapper(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new observable_Observable),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=[]);let i=new ColorGradient(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.gradient<t.gradient?-1:e.gradient>t.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(let t in this._drawWrappers){let i=this._drawWrappers[t];null===(e=i.drawContext)||void 0===e||e.reset()}}_addFactorGradient(e,t,i){let r=new FactorGradient(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){e&&(i&&e.sort((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0),this[t]&&(this[t].dispose(),this[t]=null))}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this.onDisposeObservable=new observable_Observable,this.onStoppedObservable=new observable_Observable,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=math_vector_Matrix.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||engineStore_EngineStore.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!h["BABYLON.ComputeShaderParticleSystem"])throw Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new h["BABYLON.ComputeShaderParticleSystem"](this,this._engine)}else{if(!h["BABYLON.WebGL2ParticleSystem"])throw Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new h["BABYLON.WebGL2ParticleSystem"](this,this._engine)}this._customWrappers={0:new drawWrapper_DrawWrapper(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new drawWrapper_DrawWrapper(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=null!=t?t:{}).randomTextureSize||delete t.randomTextureSize;let a=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),n=t;isFinite(n)&&(a.capacity=n),this._capacity=a.capacity,this._maxActiveParticleCount=a.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new BoxParticleEmitter;let o=Math.min(this._engine.getCaps().maxTextureSize,a.randomTextureSize),l=[];for(let e=0;e<o;++e)l.push(Math.random()),l.push(Math.random()),l.push(Math.random()),l.push(Math.random());this._randomTexture=new rawTexture_RawTexture(new Float32Array(l),o,1,5,i,!1,!1,1,1),this._randomTexture.name="GPUParticleSystem_random1",this._randomTexture.wrapU=1,this._randomTexture.wrapV=1,l=[];for(let e=0;e<o;++e)l.push(Math.random()),l.push(Math.random()),l.push(Math.random()),l.push(Math.random());this._randomTexture2=new rawTexture_RawTexture(new Float32Array(l),o,1,5,i,!1,!1,1,1),this._randomTexture2.name="GPUParticleSystem_random2",this._randomTexture2.wrapU=1,this._randomTexture2.wrapV=1,this._randomTextureSize=o}_reset(){this._releaseBuffers()}_createVertexBuffers(e,t,i){let r={};r.position=t.createVertexBuffer("position",0,3,this._attributesStrideSize,!0);let s=3;r.age=t.createVertexBuffer("age",s,1,this._attributesStrideSize,!0),s+=1,r.size=t.createVertexBuffer("size",s,3,this._attributesStrideSize,!0),s+=3,r.life=t.createVertexBuffer("life",s,1,this._attributesStrideSize,!0),s+=5,this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED&&(r.direction=t.createVertexBuffer("direction",s,3,this._attributesStrideSize,!0)),s+=3,this._platform.alignDataInBuffer&&(s+=1),this.particleEmitterType instanceof CustomParticleEmitter&&(s+=3,this._platform.alignDataInBuffer&&(s+=1)),this._colorGradientsTexture||(r.color=t.createVertexBuffer("color",s,4,this._attributesStrideSize,!0),s+=4),!this._isBillboardBased&&(r.initialDirection=t.createVertexBuffer("initialDirection",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1)),this.noiseTexture&&(r.noiseCoordinates1=t.createVertexBuffer("noiseCoordinates1",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1),r.noiseCoordinates2=t.createVertexBuffer("noiseCoordinates2",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1)),r.angle=t.createVertexBuffer("angle",s,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?s++:s+=2,this._isAnimationSheetEnabled&&(r.cellIndex=t.createVertexBuffer("cellIndex",s,1,this._attributesStrideSize,!0),s+=1,this.spriteRandomStartCell&&(r.cellStartOffset=t.createVertexBuffer("cellStartOffset",s,1,this._attributesStrideSize,!0),s+=1)),r.offset=i.createVertexBuffer("offset",0,2),r.uv=i.createVertexBuffer("uv",2,2),this._renderVertexBuffers.push(r),this._platform.createVertexBuffers(e,r),this.resetDrawCache()}_initialize(e=!1){if(this._buffer0&&!e)return;let t=this._engine,i=[];this._attributesStrideSize=21,this._targetIndex=0,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1),this.particleEmitterType instanceof CustomParticleEmitter&&(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),!this.isBillboardBased&&(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1,this.spriteRandomStartCell&&(this._attributesStrideSize+=1)),this.noiseTexture&&(this._attributesStrideSize+=6,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=2)),this._platform.alignDataInBuffer&&(this._attributesStrideSize+=3-(this._attributesStrideSize+3&3));let r=this.particleEmitterType instanceof CustomParticleEmitter,s=math_vector_TmpVectors.Vector3[0],a=0;for(let e=0;e<this._capacity;e++)if(i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),r?(this.particleEmitterType.particleDestinationGenerator(e,null,s),i.push(s.x),i.push(s.y),i.push(s.z)):(i.push(0),i.push(0),i.push(0)),this._platform.alignDataInBuffer&&i.push(0),a+=16,r&&(this.particleEmitterType.particlePositionGenerator(e,null,s),i.push(s.x),i.push(s.y),i.push(s.z),this._platform.alignDataInBuffer&&i.push(0),a+=4),this._colorGradientsTexture||(i.push(0),i.push(0),i.push(0),i.push(0),a+=4),this.isBillboardBased||(i.push(0),i.push(0),i.push(0),this._platform.alignDataInBuffer&&i.push(0),a+=4),this.noiseTexture&&(i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),a+=8),i.push(0),a+=1,this._angularSpeedGradientsTexture||(i.push(0),a+=1),this._isAnimationSheetEnabled&&(i.push(0),a+=1,this.spriteRandomStartCell&&(i.push(0),a+=1)),this._platform.alignDataInBuffer){let e=3-(a+3&3);for(a+=e;e-- >0;)i.push(0)}let n=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),o=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new Buffer(t,o,!1,this._attributesStrideSize),this._buffer1=new Buffer(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new Buffer(t,n,!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){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||((r=new drawWrapper_DrawWrapper(this._engine)).drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);let s=i.join("\n");if(r.defines!==s){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){let s=[buffer_VertexBuffer.PositionKind,"age","life","size","angle"];return e||s.push(buffer_VertexBuffer.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),r&&s.push("direction"),s.push("offset",buffer_VertexBuffer.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1){let i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return addClipPlaneUniforms(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&prepareStringDefinesForClipPlanes(this,this._scene,e),t===particleSystem_ParticleSystem.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 particleSystem_ParticleSystem.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case particleSystem_ParticleSystem.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(...GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED)),e.push(...GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ImageProcessingConfiguration.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){let i=this[t];if(!e||!e.length||i)return;let r=new Float32Array(this._rawTextureWidth);for(let t=0;t<this._rawTextureWidth;t++){let i=t/this._rawTextureWidth;GradientHelper.GetCurrentGradient(i,e,(e,i,s)=>{r[t]=math_scalar_Scalar.Lerp(e.factor1,i.factor1,s)})}this[t]=rawTexture_RawTexture.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;let e=new Uint8Array(4*this._rawTextureWidth),t=TmpColors.Color4[0];for(let i=0;i<this._rawTextureWidth;i++){let r=i/this._rawTextureWidth;GradientHelper.GetCurrentGradient(r,this._colorGradients,(r,s,a)=>{math_color_Color4.LerpToRef(r.color1,s.color1,a,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=rawTexture_RawTexture.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,r,s,a,n;let o=this._getWrapper(e),l=o.effect;this._engine.enableEffect(o);let h=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||math_vector_Matrix.IdentityReadOnly;if(l.setMatrix("view",h),l.setMatrix("projection",null!==(r=this.defaultProjectionMatrix)&&void 0!==r?r:this._scene.getProjectionMatrix()),l.setTexture("diffuseSampler",this.particleTexture),l.setVector2("translationPivot",this.translationPivot),l.setVector3("worldOffset",this.worldOffset),this.isLocal&&l.setMatrix("emitterWM",t),this._colorGradientsTexture?l.setTexture("colorGradientSampler",this._colorGradientsTexture):l.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){let e=this.particleTexture.getBaseSize();l.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){let e=this._scene.activeCamera;l.setVector3("eyePosition",e.globalPosition)}let c=l.defines;if(this._scene&&bindClipPlane(l,this,this._scene),c.indexOf("#define BILLBOARDMODE_ALL")>=0){let e=h.clone();e.invert(),l.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&MaterialHelper.BindLogDepth(c,l,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(l),e){case particleSystem_ParticleSystem.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case particleSystem_ParticleSystem.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case particleSystem_ParticleSystem.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case particleSystem_ParticleSystem.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,l,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(l),(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect())return;if(!e){if(this.emitter.position){let t=this.emitter;e=t.getWorldMatrix()}else{let t=this.emitter;e=math_vector_TmpVectors.Matrix[0],math_vector_Matrix.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);let t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){let i;if(!this._started||!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e<this.preWarmCycles;e++)this.animate(!0),this.render(!0,!0);this._preWarmDone=!0}if(this._currentRenderId===this._scene.getRenderId()&&(!this._scene.activeCamera||this._scene.activeCamera&&this._currentRenderingCameraUniqueId===this._scene.activeCamera.uniqueId))return 0;this._currentRenderId=this._scene.getRenderId(),this._scene.activeCamera&&(this._currentRenderingCameraUniqueId=this._scene.activeCamera.uniqueId)}if(this._initialize(),this._accumulatedCount+=this.emitRate*this._timeDelta,this._accumulatedCount>1){let e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;if(this.emitter.position){let e=this.emitter;i=e.getWorldMatrix()}else{let e=this.emitter;i=math_vector_TmpVectors.Matrix[0],math_vector_Matrix.TranslationToRef(e.x,e.y,e.z,i)}let r=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),s=this.blendMode===particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD?this._render(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY,i)+this._render(particleSystem_ParticleSystem.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){let checkUpdateEffect=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?this._initialize(!0):setTimeout(checkUpdateEffect,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),checkUpdateEffect()}_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(let e in this._drawWrappers){let t=this._drawWrappers[e];t.dispose()}if(this._drawWrappers={},this._scene){let e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e<this._renderVertexBuffers.length;++e){let t=this._renderVertexBuffers[e];for(let e in t)t[e].dispose()}this._renderVertexBuffers=[],this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._limitVelocityGradientsTexture&&(this._limitVelocityGradientsTexture.dispose(),this._limitVelocityGradientsTexture=null),this._dragGradientsTexture&&(this._dragGradientsTexture.dispose(),this._dragGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onStoppedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}clone(e,t,i=!1){let r=Object.assign({},this._customWrappers),s=null,a=this._engine;if(a.createEffectForParticles&&null!=this.customShader){s=this.customShader;let e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"";r[0]=a.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}let n=this.serialize(i),o=GPUParticleSystem.Parse(n,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,o}serialize(e=!1){let t={};return particleSystem_ParticleSystem._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,s){let a;let n=e.name;a=t instanceof ThinEngine?t:t.getEngine();let o=new GPUParticleSystem(n,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(o._rootUrl=i,e.customShader&&a.createEffectForParticles){let t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",r=a.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,o);o.setCustomEffect(r,0),o.customShader=t}return e.id&&(o.id=e.id),e.activeParticleCount&&(o.activeParticleCount=e.activeParticleCount),particleSystem_ParticleSystem._Parse(e,o,t,i),e.preventAutoStart&&(o.preventAutoStart=e.preventAutoStart),r||o.preventAutoStart||o.start(),o}};let ParticleSystemSet=class ParticleSystemSet{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){for(let t of(this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1),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};let r=sphereBuilder_CreateSphere("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;let s=new standardMaterial_StandardMaterial("emitterSphereMaterial",i);for(let t of(s.emissiveColor=e.color,r.material=s,this.systems))t.emitter=r;this._emitterNode=r}start(e){for(let t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(let e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){let t={};for(let i of(t.systems=[],this.systems))t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){let s=new ParticleSystemSet,a=this.BaseAssetsUrl+"/textures/";for(let n of(t=t||engineStore_EngineStore.LastCreatedScene,e.systems))s.systems.push(i?GPUParticleSystem.Parse(n,t,a,!0,r):particleSystem_ParticleSystem.Parse(n,t,a,!0,r));if(e.emitter){let i=e.emitter.options;"Sphere"===e.emitter.kind&&s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:math_color_Color3.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}};ParticleSystemSet.BaseAssetsUrl="https://assets.babylonjs.com/particles";let ParticleHelper=class ParticleHelper{static CreateDefault(e,t=500,i,r=!1){let s;return(s=r?new GPUParticleSystem("default system",{capacity:t},i):new particleSystem_ParticleSystem("default system",t,i)).emitter=e,s.particleTexture=new texture_Texture("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new math_color_Color4(1,1,1,1),s.color2=new math_color_Color4(1,1,1,1),s.colorDead=new math_color_Color4(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,r){t||(t=engineStore_EngineStore.LastCreatedScene);let s={};return t.addPendingData(s),new Promise((a,n)=>{if(i&&!GPUParticleSystem.IsSupported)return t.removePendingData(s),n("Particle system with GPU is not supported.");tools_Tools.LoadFile(`${ParticleHelper.BaseAssetsUrl}/systems/${e}.json`,e=>{t.removePendingData(s);let n=JSON.parse(e.toString());return a(ParticleSystemSet.Parse(n,t,i,r))},void 0,void 0,void 0,()=>(t.removePendingData(s),n(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){let t=new ParticleSystemSet;for(let i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,s="",a){return new Promise((n,o)=>{let l=new webRequest_WebRequest;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let t;let o=JSON.parse(l.responseText);t=r?GPUParticleSystem.Parse(o,i,s,!1,a):particleSystem_ParticleSystem.Parse(o,i,s,!1,a),e&&(t.name=e),n(t)}else o("Unable to load the particle system")}}),l.open("GET",t),l.send()})}static ParseFromSnippetAsync(e,t,i=!1,r="",s){if("_BLANK"===e){let e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise((a,n)=>{let o=new webRequest_WebRequest;o.addEventListener("readystatechange",()=>{if(4==o.readyState){if(200==o.status){let n;let l=JSON.parse(JSON.parse(o.responseText).jsonPayload),h=JSON.parse(l.particleSystem);(n=i?GPUParticleSystem.Parse(h,t,r,!1,s):particleSystem_ParticleSystem.Parse(h,t,r,!1,s)).snippetId=e,a(n)}else n("Unable to load the snippet "+e)}}),o.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),o.send()})}};ParticleHelper.BaseAssetsUrl=ParticleSystemSet.BaseAssetsUrl,ParticleHelper.SnippetUrl="https://snippet.babylonjs.com",ParticleHelper.CreateFromSnippetAsync=ParticleHelper.ParseFromSnippetAsync,AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM,(e,t,i,r)=>{let s=AbstractScene.GetIndividualParser(sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM);if(s&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let a=0,n=e.particleSystems.length;a<n;a++){let n=e.particleSystems[a];i.particleSystems.push(s(n,t,r))}}),AbstractScene.AddIndividualParser(sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM,(e,t,i)=>{if(e.activeParticleCount){let r=GPUParticleSystem.Parse(e,t,i);return r}{let r=particleSystem_ParticleSystem.Parse(e,t,i);return r}}),engine_Engine.prototype.createEffectForParticles=function(e,t=[],i=[],r="",s,a,n,o){var l;let h=[],c=[],u=[];return o?o.fillUniformsAttributesAndSamplerNames(c,h,u):(h=particleSystem_ParticleSystem._GetAttributeNamesOrOptions(),c=particleSystem_ParticleSystem._GetEffectCreationOptions()),-1===r.indexOf(" BILLBOARD")&&(r+="\n#define BILLBOARD\n"),(null==o?void 0:o.isAnimationSheetEnabled)&&-1===r.indexOf(" ANIMATESHEET")&&(r+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==o?void 0:o.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},h,c.concat(t),u.concat(i),r,s,a,n)},mesh_Mesh.prototype.getEmittedParticleSystems=function(){let e=[];for(let t=0;t<this.getScene().particleSystems.length;t++){let i=this.getScene().particleSystems[t];i.emitter===this&&e.push(i)}return e},mesh_Mesh.prototype.getHierarchyEmittedParticleSystems=function(){let e=[],t=this.getDescendants();t.push(this);for(let i=0;i<this.getScene().particleSystems.length;i++){let r=this.getScene().particleSystems[i],s=r.emitter;s.position&&-1!==t.indexOf(s)&&e.push(r)}return e},function(e){e[e.Color=2]="Color",e[e.UV=1]="UV",e[e.Random=0]="Random",e[e.Stated=3]="Stated"}(t$||(t$={})),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0}),abstractMesh_AbstractMesh.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},abstractMesh_AbstractMesh.prototype.applyImpulse=function(e,t){return this.physicsImpostor&&this.physicsImpostor.applyImpulse(e,t),this},abstractMesh_AbstractMesh.prototype.setPhysicsLinkWith=function(e,t,i,r){return this.physicsImpostor&&e.physicsImpostor&&this.physicsImpostor.createJoint(e.physicsImpostor,PhysicsJoint.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:r}),this};let physicsEngine_PhysicsEngine=class physicsEngine_PhysicsEngine{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw _WarnImport("")}constructor(e,t=physicsEngine_PhysicsEngine.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new math_vector_Vector3(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){let t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){let r=new PhysicsRaycastResult;return this._physicsPlugin.raycast(e,t,r,i),r}};(function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"})(tQ||(tQ={})),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"}(tZ||(tZ={})),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"}(tJ||(tJ={})),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"}(t0||(t0={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(t1||(t1={})),function(e){e.COLLISION_STARTED="COLLISION_STARTED",e.COLLISION_CONTINUED="COLLISION_CONTINUED",e.COLLISION_FINISHED="COLLISION_FINISHED",e.TRIGGER_ENTERED="TRIGGER_ENTERED",e.TRIGGER_EXITED="TRIGGER_EXITED"}(t2||(t2={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(t3||(t3={})),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"}(t4||(t4={})),scene_Scene.prototype.getPhysicsEngine=function(){return this._physicsEngine},scene_Scene.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE);i||(i=new PhysicsEngineSceneComponent(this),this._addComponent(i));try{if(t&&(null==t?void 0:t.getPluginVersion())!==1){if((null==t?void 0:t.getPluginVersion())===2)this._physicsEngine=new physicsEngine_PhysicsEngine(e,t);else throw Error("Unsupported Physics plugin version.")}else this._physicsEngine=new PhysicsEngine(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return logger_Logger.Error(e.message),!1}},scene_Scene.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},scene_Scene.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},scene_Scene.prototype.deleteCompoundImpostor=function(e){let t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},scene_Scene.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){let 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)}};let PhysicsEngineSceneComponent=class PhysicsEngineSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new observable_Observable,this.scene.onAfterPhysicsObservable=new observable_Observable,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(transformNode_TransformNode.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}),transformNode_TransformNode.prototype.getPhysicsBody=function(){return this.physicsBody},transformNode_TransformNode.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this};let HelperTools=class HelperTools{static GetContactPointToRef(e,t,i,r,s){let a=e.getScene().getPhysicsEngine(),n=null==a?void 0:a.getPluginVersion();if(1===n){let s=new ray_Ray(t,i),a=s.intersectsMesh(e);if(a.hit&&a.pickedPoint)return r.copyFrom(a.pickedPoint),!0}else if(2===n)return e.physicsBody.getObjectCenterWorldToRef(r,s),!0;return!1}static HasAppliedForces(e,t){var i,r,s;return e.getMotionType(t)===t3.STATIC||(null!==(r=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==r?r:0)===0||(null===(s=e.transformNode)||void 0===s?void 0:s.getTotalVertices())===0}static IsInsideCylinder(e,t,i,r){let s=math_vector_TmpVectors.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=r}};let PhysicsUpdraftEvent=class PhysicsUpdraftEvent{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=math_vector_Vector3.Zero(),this._originDirection=math_vector_Vector3.Zero(),this._cylinderPosition=math_vector_Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new PhysicsUpdraftEventOptions),this._options),this._origin.addToRef(new math_vector_Vector3(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new math_vector_Vector3(0,this._options.height,0),this._originTop),this._options.updraftMode===t6.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout(()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)},0))}_getHitData(e,t){let i;i=this._options.updraftMode===t6.Perpendicular?this._originDirection:e.subtract(this._originTop);let r=math_vector_Vector3.Distance(this._origin,e),s=-1*this._options.strength,a=i.multiplyByFloats(s,s,s);t.force.copyFrom(a),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(HelperTools.HasAppliedForces(e))return!1;let r=e.getObjectCenterWorld(i);return!!HelperTools.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){let e=PhysicsUpdraftEvent._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=cylinderBuilder_CreateCylinder("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))}};PhysicsUpdraftEvent._HitData={force:new math_vector_Vector3,contactPoint:new math_vector_Vector3,distanceFromOrigin:0};let PhysicsVortexEvent=class PhysicsVortexEvent{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=math_vector_Vector3.Zero(),this._cylinderPosition=math_vector_Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new PhysicsVortexEventOptions),this._options),this._origin.addToRef(new math_vector_Vector3(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new math_vector_Vector3(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout(()=>{this._dataFetched||this._cylinder.dispose()},0))}_getHitData(e,t,i){let r,s,a;let n=PhysicsVortexEvent.originOnPlane;n.set(this._origin.x,t.y,this._origin.z);let o=math_vector_TmpVectors.Vector3[0];t.subtractToRef(n,o);let l=math_vector_TmpVectors.Vector3[1],h=HelperTools.GetContactPointToRef(e,n,o,l,i.instanceIndex);if(!h)return!1;let c=math_vector_Vector3.Distance(l,n),u=c/this._options.radius,d=math_vector_TmpVectors.Vector3[2];if(l.normalizeToRef(d),u>this._options.centripetalForceThreshold&&d.negateInPlace(),u>this._options.centripetalForceThreshold)r=d.x*this._options.centripetalForceMultiplier,s=d.y*this._options.updraftForceMultiplier,a=d.z*this._options.centripetalForceMultiplier;else{let e=math_vector_Vector3.Cross(n,t).normalize();r=(e.x+d.x)*this._options.centrifugalForceMultiplier,s=this._originTop.y*this._options.updraftForceMultiplier,a=(e.z+d.z)*this._options.centrifugalForceMultiplier}let _=math_vector_TmpVectors.Vector3[3];return _.set(r,s,a),_.scaleInPlace(this._options.strength),i.force.copyFrom(_),i.contactPoint.copyFrom(t),i.distanceFromOrigin=u,!0}_getBodyHitData(e,t,i){if(HelperTools.HasAppliedForces(e,i))return!1;let r=e.transformNode,s=e.getObjectCenterWorld(i);return!!HelperTools.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,s,t))}_getImpostorHitData(e,t){if(0===e.mass||"Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){let e=PhysicsVortexEvent.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=cylinderBuilder_CreateCylinder("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)}};PhysicsVortexEvent.originOnPlane=math_vector_Vector3.Zero(),PhysicsVortexEvent.hitData={force:new math_vector_Vector3,contactPoint:new math_vector_Vector3,distanceFromOrigin:0};let PhysicsUpdraftEventOptions=class PhysicsUpdraftEventOptions{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=t6.Center}};let PhysicsVortexEventOptions=class PhysicsVortexEventOptions{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"})(t5||(t5={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(t6||(t6={}));let np=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); +vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;ShaderStore.ShadersStore.blackAndWhitePixelShader=np;let BlackAndWhitePostProcess=class BlackAndWhitePostProcess extends postProcess_PostProcess{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,r,s,a){super(e,"blackAndWhite",["degree"],null,t,i,r,s,a),this.degree=1,this.onApplyObservable.add(e=>{e.setFloat("degree",this.degree)})}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new BlackAndWhitePostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};__decorate([serialize()],BlackAndWhitePostProcess.prototype,"degree",void 0),h["BABYLON.BlackAndWhitePostProcess"]=BlackAndWhitePostProcess;let postProcessRenderEffect_PostProcessRenderEffect=class postProcessRenderEffect_PostProcessRenderEffect{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(let e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){let t=this._postProcesses[e];for(let e=0;e<t.length;e++)if(!t[e].isSupported)return!1}return!0}_update(){}_attachCameras(e){let t;let i=tools_Tools.MakeArray(e||this._cameras);if(i)for(let e=0;e<i.length;e++){let r=i[e];if(!r)continue;let s=r.name;if(t=this._singleInstance?0:s,!this._postProcesses[t]){let e=this._getPostProcesses();e&&(this._postProcesses[t]=Array.isArray(e)?e:[e])}this._indicesForCamera[s]||(this._indicesForCamera[s]=[]),this._postProcesses[t].forEach(e=>{let t=r.attachPostProcess(e);this._indicesForCamera[s].push(t)}),this._cameras[s]||(this._cameras[s]=r)}}_detachCameras(e){let t=tools_Tools.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){let i=t[e],r=i.name,s=this._postProcesses[this._singleInstance?0:r];s&&s.forEach(e=>{i.detachPostProcess(e)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){let t=tools_Tools.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){let i=t[e],r=i.name,s=this._singleInstance?0:r;for(let a=0;a<this._indicesForCamera[r].length;a++){let n=this._indicesForCamera[r][a],o=i._postProcesses[n];null==o&&t[e].attachPostProcess(this._postProcesses[s][a],n)}}}_disable(e){let t=tools_Tools.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){let i=t[e],r=i.name;this._postProcesses[this._singleInstance?0:r].forEach(e=>{i.detachPostProcess(e)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}};let nf=`#include<helperFunctions> +varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;ShaderStore.ShadersStore.extractHighlightsPixelShader=nf;let ExtractHighlightsPostProcess=class ExtractHighlightsPostProcess extends postProcess_PostProcess{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,r,s,a,o=0,l=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,r,s,a,null,o,void 0,null,l),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,n)),e.setFloat("exposure",this._exposure)})}};__decorate([serialize()],ExtractHighlightsPostProcess.prototype,"threshold",void 0),h["BABYLON.ExtractHighlightsPostProcess"]=ExtractHighlightsPostProcess;let nm=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } +`;ShaderStore.ShadersStore.bloomMergePixelShader=nm;let BloomMergePostProcess=class BloomMergePostProcess extends postProcess_PostProcess{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,s,a,n,o,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,a,n,o,l,null,h,void 0,null,!0),this.weight=1,this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)}),c||this.updateEffect()}};__decorate([serialize()],BloomMergePostProcess.prototype,"weight",void 0),h["BABYLON.BloomMergePostProcess"]=BloomMergePostProcess;let BloomEffect=class BloomEffect extends postProcessRenderEffect_PostProcessRenderEffect{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,r,s=0,a=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new ExtractHighlightsPostProcess("highlights",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,a),this._blurX=new BlurPostProcess("horizontal blur",new math_vector_Vector2(1,0),10,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,a),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new BlurPostProcess("vertical blur",new math_vector_Vector2(0,1),10,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,a),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new BloomMergePostProcess("bloomMerge",this._downscale,this._blurY,i,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,a),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){for(let e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0}};let ng=`uniform sampler2D textureSampler; +uniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);} +float radius2=centered_screen_pos.x*centered_screen_pos.x ++ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec4 original=texture2D(textureSampler,vUV);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);original.r=texture2D(textureSampler,ref_coords_r).r;original.g=texture2D(textureSampler,ref_coords_g).g;original.b=texture2D(textureSampler,ref_coords_b).b;original.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);gl_FragColor=original;}`;ShaderStore.ShadersStore.chromaticAberrationPixelShader=ng;let ChromaticAberrationPostProcess=class ChromaticAberrationPostProcess extends postProcess_PostProcess{getClassName(){return"ChromaticAberrationPostProcess"}constructor(e,t,i,r,s,a,n,o,l=0,h=!1){super(e,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],r,s,a,n,o,null,l,void 0,null,h),this.aberrationAmount=30,this.radialIntensity=0,this.direction=new math_vector_Vector2(.707,.707),this.centerPosition=new math_vector_Vector2(.5,.5),this.screenWidth=t,this.screenHeight=i,this.onApplyObservable.add(e=>{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,r){return decorators_SerializationHelper.Parse(()=>new ChromaticAberrationPostProcess(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}};__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"aberrationAmount",void 0),__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"radialIntensity",void 0),__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"direction",void 0),__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"centerPosition",void 0),__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"screenWidth",void 0),__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"screenHeight",void 0),h["BABYLON.ChromaticAberrationPostProcess"]=ChromaticAberrationPostProcess;let nv=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float depth=texture2D(depthSampler,vUV).r; +#define CUSTOM_COC_DEPTH +float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; +#define CUSTOM_COC_PIXELDISTANCE +float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} +`;ShaderStore.ShadersStore.circleOfConfusionPixelShader=nv;let CircleOfConfusionPostProcess=class CircleOfConfusionPostProcess extends postProcess_PostProcess{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,s,a,n,o=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,r,s,a,n,null,o,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){logger_Logger.Warn("No depth texture set on CircleOfConfusionPostProcess");return}e.setTexture("depthSampler",this._depthTexture);let t=this.lensSize/this.fStop,i=t*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",i);let r=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",r.minZ,r.maxZ-r.minZ)})}set depthTexture(e){this._depthTexture=e}};__decorate([serialize()],CircleOfConfusionPostProcess.prototype,"lensSize",void 0),__decorate([serialize()],CircleOfConfusionPostProcess.prototype,"fStop",void 0),__decorate([serialize()],CircleOfConfusionPostProcess.prototype,"focusDistance",void 0),__decorate([serialize()],CircleOfConfusionPostProcess.prototype,"focalLength",void 0),h["BABYLON.CircleOfConfusionPostProcess"]=CircleOfConfusionPostProcess;let nx=`uniform sampler2D textureSampler; +uniform sampler2D colorTable; +varying vec2 vUV;const float SLICE_COUNT=16.0; +vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; +float slicePixelSize=sliceSize/width; +float sliceInnerSize=slicePixelSize*(width-1.0); +float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;ShaderStore.ShadersStore.colorCorrectionPixelShader=nx;let ColorCorrectionPostProcess=class ColorCorrectionPostProcess extends postProcess_PostProcess{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,s,a,n){super(e,"colorCorrection",null,["colorTable"],i,r,s,a,n);let o=(null==r?void 0:r.getScene())||null;this._colorTableTexture=new texture_Texture(t,o,!0,!1,texture_Texture.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new ColorCorrectionPostProcess(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};__decorate([serialize()],ColorCorrectionPostProcess.prototype,"colorTableUrl",void 0),h["BABYLON.ColorCorrectionPostProcess"]=ColorCorrectionPostProcess;let nb=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = +texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + +texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + +texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + +texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + +texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + +texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + +texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + +texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + +texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = +kernel[0] + +kernel[1] + +kernel[2] + +kernel[3] + +kernel[4] + +kernel[5] + +kernel[6] + +kernel[7] + +kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} +gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;ShaderStore.ShadersStore.convolutionPixelShader=nb;let ConvolutionPostProcess=class ConvolutionPostProcess extends postProcess_PostProcess{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,s,a,n,o=0){super(e,"convolution",["kernel","screenSize"],null,i,r,s,a,n,null,o),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new ConvolutionPostProcess(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,r)}};ConvolutionPostProcess.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],ConvolutionPostProcess.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],ConvolutionPostProcess.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],ConvolutionPostProcess.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],ConvolutionPostProcess.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],ConvolutionPostProcess.GaussianKernel=[0,1,0,1,1,1,0,1,0],__decorate([serialize()],ConvolutionPostProcess.prototype,"kernel",void 0),h["BABYLON.ConvolutionPostProcess"]=ConvolutionPostProcess;let DepthOfFieldBlurPostProcess=class DepthOfFieldBlurPostProcess extends BlurPostProcess{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,s,a,n,o=null,l=texture_Texture.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,_=5){super(e,i,r,s,a,2,h,c,u,`#define DOF 1 +`,d,_),this.direction=i,this.externalTextureSamplerBinding=!!o,this.onApplyObservable.add(e=>{null!=o&&e.setTextureFromPostProcess("textureSampler",o),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",n)})}};__decorate([serialize()],DepthOfFieldBlurPostProcess.prototype,"direction",void 0),h["BABYLON.DepthOfFieldBlurPostProcess"]=DepthOfFieldBlurPostProcess;let nT=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; +#if BLUR_LEVEL>0 +uniform sampler2D blurStep1; +#endif +#if BLUR_LEVEL>1 +uniform sampler2D blurStep2; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; +#if BLUR_LEVEL==0 +vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); +#endif +#if BLUR_LEVEL==1 +if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} +#endif +#if BLUR_LEVEL==2 +if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} +#endif +} +`;ShaderStore.ShadersStore.depthOfFieldMergePixelShader=nT;let DepthOfFieldMergePostProcess=class DepthOfFieldMergePostProcess extends postProcess_PostProcess{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,s,a,n,o,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,a,n,o,l,null,h,void 0,null,!0),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(r.length-i-1),t)})}),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,r,s,a){e||(e="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,r,s,a)}};!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(t8||(t8={}));let DepthOfFieldEffect=class DepthOfFieldEffect extends postProcessRenderEffect_PostProcessRenderEffect{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=t8.Low,r=0,s=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];let a=e.getEngine(),n=a.isWebGPU||a.webGLVersion>1?6:5;this._circleOfConfusion=new CircleOfConfusionPostProcess("circleOfConfusion",t,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,a,!1,r,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let o=1,l=15;switch(i){case t8.High:o=3,l=51;break;case t8.Medium:o=2,l=31;break;default:l=15,o=1}let h=l/Math.pow(2,o-1),c=1;for(let t=0;t<o;t++){let i=new DepthOfFieldBlurPostProcess("vertical blur",e,new math_vector_Vector2(0,1),h,c,null,this._circleOfConfusion,0==t?this._circleOfConfusion:null,texture_Texture.BILINEAR_SAMPLINGMODE,a,!1,r,s,0==t?n:5);i.autoClear=!1,c=.75/Math.pow(2,t);let o=new DepthOfFieldBlurPostProcess("horizontal blur",e,new math_vector_Vector2(1,0),h,c,null,this._circleOfConfusion,null,texture_Texture.BILINEAR_SAMPLINGMODE,a,!1,r,s);o.autoClear=!1,this._depthOfFieldBlurY.push(i),this._depthOfFieldBlurX.push(o)}this._effects=[this._circleOfConfusion];for(let e=0;e<this._depthOfFieldBlurX.length;e++)this._effects.push(this._depthOfFieldBlurY[e]),this._effects.push(this._depthOfFieldBlurX[e]);this._dofMerge=new DepthOfFieldMergePostProcess("dofMerge",this._circleOfConfusion,this._circleOfConfusion,this._depthOfFieldBlurX,c,null,texture_Texture.BILINEAR_SAMPLINGMODE,a,!1,r,s),this._dofMerge.autoClear=!1,this._effects.push(this._dofMerge)}getClassName(){return"DepthOfFieldEffect"}set depthTexture(e){this._circleOfConfusion.depthTexture=e}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){for(let e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0}};let nS=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(passSampler,vUV);}`;ShaderStore.ShadersStore.displayPassPixelShader=nS;let DisplayPassPostProcess=class DisplayPassPostProcess extends postProcess_PostProcess{getClassName(){return"DisplayPassPostProcess"}constructor(e,t,i,r,s,a){super(e,"displayPass",["passSampler"],["passSampler"],t,i,r,s,a)}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new DisplayPassPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};h["BABYLON.DisplayPassPostProcess"]=DisplayPassPostProcess;let nC=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;ShaderStore.ShadersStore.filterPixelShader=nC;let FilterPostProcess=class FilterPostProcess extends postProcess_PostProcess{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,s,a,n){super(e,"filter",["kernelMatrix"],null,i,r,s,a,n),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new FilterPostProcess(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};__decorate([generateSerializableMember(12,void 0)],FilterPostProcess.prototype,"kernelMatrix",void 0),h["BABYLON.FilterPostProcess"]=FilterPostProcess;let nE=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); +#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) +void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); +#ifndef MALI +if(range<rangeMaxClamped) +{gl_FragColor=rgbyM;return;} +#endif +float lumaNW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNW,0.0));float lumaSE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSE,0.0));float lumaNE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNE,0.0));float lumaSW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSW,0.0));float lumaNS=lumaN+lumaS;float lumaWE=lumaW+lumaE;float subpixRcpRange=1.0/range;float subpixNSWE=lumaNS+lumaWE;float edgeHorz1=(-2.0*lumaM)+lumaNS;float edgeVert1=(-2.0*lumaM)+lumaWE;float lumaNESE=lumaNE+lumaSE;float lumaNWNE=lumaNW+lumaNE;float edgeHorz2=(-2.0*lumaE)+lumaNESE;float edgeVert2=(-2.0*lumaN)+lumaNWNE;float lumaNWSW=lumaNW+lumaSW;float lumaSWSE=lumaSW+lumaSE;float edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);float edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);float edgeHorz3=(-2.0*lumaW)+lumaNWSW;float edgeVert3=(-2.0*lumaS)+lumaSWSE;float edgeHorz=abs(edgeHorz3)+edgeHorz4;float edgeVert=abs(edgeVert3)+edgeVert4;float subpixNWSWNESE=lumaNWSW+lumaNESE;float lengthSign=texelSize.x;bool horzSpan=edgeHorz>=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) +{lumaN=lumaW;} +if (!horzSpan) +{lumaS=lumaE;} +if (horzSpan) +{lengthSign=texelSize.y;} +float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) +{lengthSign=-lengthSign;} +float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) +{posB.x+=lengthSign*0.5;} +if (horzSpan) +{posB.y+=lengthSign*0.5;} +vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) +{lumaNN=lumaSS;} +float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) +{posN.x-=offNP.x*3.0;} +if (!doneN) +{posN.y-=offNP.y*3.0;} +bool doneNP=(!doneN) || (!doneP);if (!doneP) +{posP.x+=offNP.x*3.0;} +if (!doneP) +{posP.y+=offNP.y*3.0;} +if (doneNP) +{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} +float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) +{dstN=posM.y-posN.y;} +if (!horzSpan) +{dstP=posP.y-posM.y;} +bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN<dstP;float dst=min(dstN,dstP);bool goodSpan=directionN ? goodSpanN : goodSpanP;float subpixG=subpixF*subpixF;float pixelOffset=(dst*(-spanLengthRcp))+0.5;float subpixH=subpixG*fxaaQualitySubpix;float pixelOffsetGood=goodSpan ? pixelOffset : 0.0;float pixelOffsetSubpix=max(pixelOffsetGood,subpixH);if (!horzSpan) +{posM.x+=pixelOffsetSubpix*lengthSign;} +if (horzSpan) +{posM.y+=pixelOffsetSubpix*lengthSign;} +#ifdef MALI +if(range<rangeMaxClamped) +{gl_FragColor=rgbyM;} +else +{gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);} +#else +gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0); +#endif +}`;ShaderStore.ShadersStore.fxaaPixelShader=nE;let ny=`attribute vec2 position;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.fxaaVertexShader=ny;let FxaaPostProcess=class FxaaPostProcess extends postProcess_PostProcess{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,r,s,a,n=0){super(e,"fxaa",["texelSize"],null,t,i,r||texture_Texture.BILINEAR_SAMPLINGMODE,s,a,null,n,"fxaa",void 0,!0);let o=this._getDefines();this.updateEffect(o),this.onApplyObservable.add(e=>{let t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)})}_getDefines(){let e=this.getEngine();if(!e)return null;let t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new FxaaPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};h["BABYLON.FxaaPostProcess"]=FxaaPostProcess;let nR=`#include<helperFunctions> +uniform sampler2D textureSampler; +uniform float intensity;uniform float animatedSeed;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`;ShaderStore.ShadersStore.grainPixelShader=nR;let GrainPostProcess=class GrainPostProcess extends postProcess_PostProcess{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,s,a,n=0,o=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,s,a,null,n,void 0,null,o),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,r){return decorators_SerializationHelper.Parse(()=>new GrainPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};__decorate([serialize()],GrainPostProcess.prototype,"intensity",void 0),__decorate([serialize()],GrainPostProcess.prototype,"animated",void 0),h["BABYLON.GrainPostProcess"]=GrainPostProcess;let nP=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;ShaderStore.ShadersStore.highlightsPixelShader=nP;let nA=`varying vec2 vUV;uniform sampler2D textureSampler; +#include<imageProcessingDeclaration> +#include<helperFunctions> +#include<imageProcessingFunctions> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 result=texture2D(textureSampler,vUV); +#ifdef IMAGEPROCESSING +#ifndef FROMLINEARSPACE +result.rgb=toLinearSpace(result.rgb); +#endif +result=applyImageProcessing(result); +#else +#ifdef FROMLINEARSPACE +result=applyImageProcessing(result); +#endif +#endif +gl_FragColor=result;}`;ShaderStore.ShadersStore.imageProcessingPixelShader=nA;let ImageProcessingPostProcess=class ImageProcessingPostProcess extends postProcess_PostProcess{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,t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){let i=t.scenes;e=i[i.length-1]}else e=engineStore_EngineStore.LastCreatedScene;e?this._imageProcessingConfiguration=e.imageProcessingConfiguration:this._imageProcessingConfiguration=new ImageProcessingConfiguration}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get isSupported(){let e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,s,a,n=0,o){super(e,"imageProcessing",[],[],t,i,r,s,a,null,n,"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},o?(o.applyByPostProcess=!0,this._attachImageProcessingConfiguration(o,!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(let t in this._defines)this._defines[t]&&(e+=`#define ${t}; +`);let t=["textureSampler"],i=["scale"];ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareSamplers(t,this._defines),ImageProcessingConfiguration.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)}};__decorate([serialize()],ImageProcessingPostProcess.prototype,"_fromLinearSpace",void 0);let nM=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +layout(location=0) out vec4 glFragData[{X}]; +#endif +`;ShaderStore.IncludesShadersStore.mrtFragmentDeclaration=nM;let nI=`#extension GL_EXT_draw_buffers : require +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +precision highp float; +#ifdef BUMP +varying mat4 vWorldView;varying vec3 vNormalW; +#else +varying vec3 vNormalV; +#endif +varying vec4 vViewPos; +#if defined(POSITION) || defined(BUMP) +varying vec3 vPositionW; +#endif +#ifdef VELOCITY +varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#ifdef NEED_UV +varying vec2 vUV; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#if defined(REFLECTIVITY) +#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; +#endif +#ifdef ALBEDOTEXTURE +varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; +#endif +#ifdef REFLECTIVITYCOLOR +uniform vec3 reflectivityColor; +#endif +#ifdef ALBEDOCOLOR +uniform vec3 albedoColor; +#endif +#ifdef METALLIC +uniform float metallic; +#endif +#if defined(ROUGHNESS) || defined(GLOSSINESS) +uniform float glossiness; +#endif +#endif +#if defined(ALPHATEST) && defined(NEED_UV) +uniform sampler2D diffuseSampler; +#endif +#include<clipPlaneFragmentDeclaration> +#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT] +#include<bumpFragmentMainFunctions> +#include<bumpFragmentFunctions> +#include<helperFunctions> +void main() { +#include<clipPlaneFragment> +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +vec3 normalOutput; +#ifdef BUMP +vec3 normalW=normalize(vNormalW); +#include<bumpFragment> +#ifdef NORMAL_WORLDSPACE +normalOutput=normalW; +#else +normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); +#endif +#else +normalOutput=normalize(vNormalV); +#endif +#ifdef PREPASS +#ifdef PREPASS_DEPTH +gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); +#endif +#ifdef PREPASS_NORMAL +gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); +#endif +#else +gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); +#endif +#ifdef POSITION +gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); +#endif +#ifdef VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); +#endif +#ifdef REFLECTIVITY +vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); +#ifdef METALLICWORKFLOW +float metal=1.0;float roughness=1.0; +#ifdef ORMTEXTURE +metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; +#endif +#ifdef METALLIC +metal*=metallic; +#endif +#ifdef ROUGHNESS +roughness*=(1.0-glossiness); +#endif +reflectivity.a-=roughness;vec3 color=vec3(1.0); +#ifdef ALBEDOTEXTURE +color=texture2D(albedoSampler,vAlbedoUV).rgb; +#ifdef GAMMAALBEDO +color=toLinearSpace(color); +#endif +#endif +#ifdef ALBEDOCOLOR +color*=albedoColor.xyz; +#endif +reflectivity.rgb=mix(vec3(0.04),color,metal); +#else +#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +reflectivity=texture2D(reflectivitySampler,vReflectivityUV); +#ifdef GAMMAREFLECTIVITYTEXTURE +reflectivity.rgb=toLinearSpace(reflectivity.rgb); +#endif +#else +#ifdef REFLECTIVITYCOLOR +reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; +#endif +#endif +#ifdef GLOSSINESSS +reflectivity.a*=glossiness; +#endif +#endif +gl_FragData[REFLECTIVITY_INDEX]=reflectivity; +#endif +} +`;ShaderStore.ShadersStore.geometryPixelShader=nI,ShaderStore.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";let nD=`#include<sceneUboDeclaration> +`;ShaderStore.IncludesShadersStore.geometryUboDeclaration=nD;let nO=`precision highp float; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<instancesDeclaration> +#include<__decl__geometryVertex> +#include<clipPlaneVertexDeclaration> +attribute vec3 position;attribute vec3 normal; +#ifdef NEED_UV +varying vec2 vUV; +#ifdef ALPHATEST +uniform mat4 diffuseMatrix; +#endif +#ifdef BUMP +uniform mat4 bumpMatrix;varying vec2 vBumpUV; +#endif +#ifdef REFLECTIVITY +uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#ifdef BUMP +varying mat4 vWorldView; +#endif +#ifdef BUMP +varying vec3 vNormalW; +#else +varying vec3 vNormalV; +#endif +varying vec4 vViewPos; +#if defined(POSITION) || defined(BUMP) +varying vec3 vPositionW; +#endif +#ifdef VELOCITY +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position;vec3 normalUpdated=normal; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); +#ifdef BUMP +vWorldView=view*finalWorld;vNormalW=normalUpdated; +#else +#ifdef NORMAL_WORLDSPACE +vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0))); +#else +vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); +#endif +#endif +vViewPos=view*worldPos; +#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +#if defined(POSITION) || defined(BUMP) +vPositionW=worldPos.xyz/worldPos.w; +#endif +gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#include<clipPlaneVertex> +#ifdef NEED_UV +#ifdef UV1 +#if defined(ALPHATEST) && defined(ALPHATEST_UV1) +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#else +vUV=uv; +#endif +#ifdef BUMP_UV1 +vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef REFLECTIVITY_UV1 +vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef ALBEDO_UV1 +vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#endif +#ifdef UV2 +#if defined(ALPHATEST) && defined(ALPHATEST_UV2) +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#else +vUV=uv2; +#endif +#ifdef BUMP_UV2 +vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); +#endif +#ifdef REFLECTIVITY_UV2 +vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); +#endif +#ifdef ALBEDO_UV2 +vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#endif +#include<bumpVertex> +} +`;ShaderStore.ShadersStore.geometryVertexShader=nO;let nB=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];addClipPlaneUniforms(nB);let GeometryBufferRenderer=class GeometryBufferRenderer{_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===GeometryBufferRenderer.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===GeometryBufferRenderer.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===GeometryBufferRenderer.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 GeometryBufferRenderer.POSITION_TEXTURE_TYPE:return this._positionIndex;case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case GeometryBufferRenderer.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case GeometryBufferRenderer.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return -1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return this._ratio}constructor(e,t=1,i=15){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new math_color_Color4(0,0,0,0),this._clearDepthColor=new math_color_Color4(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,GeometryBufferRenderer._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){let i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;let r=[],s=[buffer_VertexBuffer.PositionKind,buffer_VertexBuffer.NormalKind],a=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&MaterialFlags.BumpTextureEnabled&&(r.push("#define BUMP"),r.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&r.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&r.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&r.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&r.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}e&&(r.push("#define NEED_UV"),a.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(s.push(buffer_VertexBuffer.UVKind),r.push("#define UV1")),a.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&(s.push(buffer_VertexBuffer.UV2Kind),r.push("#define UV2")))}this._linkedWithPrePass&&(r.push("#define PREPASS"),-1!==this._depthIndex&&(r.push("#define DEPTH_INDEX "+this._depthIndex),r.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(r.push("#define NORMAL_INDEX "+this._normalIndex),r.push("#define PREPASS_NORMAL"))),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(a)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),a.useBones&&a.computeBonesUsingShaders?(s.push(buffer_VertexBuffer.MatricesIndicesKind),s.push(buffer_VertexBuffer.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(buffer_VertexBuffer.MatricesIndicesExtraKind),s.push(buffer_VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),r.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");let n=a.morphTargetManager,o=0;n&&n.numInfluencers>0&&(o=n.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+o),n.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(s,a,o)),t&&(r.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):r.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),prepareStringDefinesForClipPlanes(i,this._scene,r);let l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=r.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:nB,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:o}},l),u),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){if(this._resizeObserver){let e=this._scene.getEngine();e.onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null}this.getGBuffer().dispose()}_assignRenderTargetIndices(){let e=[],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(){let e=this._scene.getEngine(),[t,i]=this._assignRenderTargetIndices(),r=0;if(e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2),this._multiRenderTarget=new MultiRenderTarget("gBuffer",{width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio},t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:r,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;let s=[!0],a=[!1],n=[!0];for(let e=1;e<t;++e)s.push(!0),n.push(!1),a.push(!0);let o=e.buildTextureLayout(s),l=e.buildTextureLayout(a),h=e.buildTextureLayout(n);this._multiRenderTarget.onClearObservable.add(e=>{e.bindAttachments(this.useSpecificClearForDepthTexture?l:o),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(h),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(o)}),this._resizeObserver=e.onResizeObservable.add(()=>{this._multiRenderTarget&&this._multiRenderTarget.resize({width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio})});let renderSubMesh=e=>{let t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),a=e.getMaterial();if(!a)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:math_vector_Matrix.Identity(),viewProjection:r.getTransformMatrix()},t.skeleton)){let e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}let n=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(n.mustReturn)return;let o=s.getCaps().instancedArrays&&(null!==n.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,o)){let h;let c=e._getDrawWrapper();if(!c)return;let u=c.effect;s.enableEffect(c),o||t._bind(e,u,a.fillMode),this._useUbo?(MaterialHelper.BindSceneUniformBuffer(u,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(u.setMatrix("viewProjection",r.getTransformMatrix()),u.setMatrix("view",r.getViewMatrix()));let d=t._instanceDataStorage;if(!d.isFrozen&&(a.backFaceCulling||null!==t.overrideMaterialSideOrientation)){let e=i._getWorldMatrixDeterminant();null===(h=t.overrideMaterialSideOrientation)&&(h=a.sideOrientation),e<0&&(h=h===material_Material.ClockWiseSideOrientation?material_Material.CounterClockWiseSideOrientation:material_Material.ClockWiseSideOrientation)}else h=d.sideOrientation;if(a._preBind(c,h),a.needAlphaTesting()){let e=a.getAlphaTestTexture();e&&(u.setTexture("diffuseSampler",e),u.setMatrix("diffuseMatrix",e.getTextureMatrix()))}a.bumpTexture&&r.getEngine().getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&(u.setFloat3("vBumpInfos",a.bumpTexture.coordinatesIndex,1/a.bumpTexture.level,a.parallaxScaleBias),u.setMatrix("bumpMatrix",a.bumpTexture.getTextureMatrix()),u.setTexture("bumpSampler",a.bumpTexture),u.setFloat2("vTangentSpaceParams",a.invertNormalMapX?-1:1,a.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===a.getClassName()?(null!==a.metallicRoughnessTexture&&(u.setTexture("reflectivitySampler",a.metallicRoughnessTexture),u.setMatrix("reflectivityMatrix",a.metallicRoughnessTexture.getTextureMatrix())),null!==a.metallic&&u.setFloat("metallic",a.metallic),null!==a.roughness&&u.setFloat("glossiness",1-a.roughness),null!==a.baseTexture&&(u.setTexture("albedoSampler",a.baseTexture),u.setMatrix("albedoMatrix",a.baseTexture.getTextureMatrix())),null!==a.baseColor&&u.setColor3("albedoColor",a.baseColor)):"PBRSpecularGlossinessMaterial"===a.getClassName()?(null!==a.specularGlossinessTexture?(u.setTexture("reflectivitySampler",a.specularGlossinessTexture),u.setMatrix("reflectivityMatrix",a.specularGlossinessTexture.getTextureMatrix())):null!==a.specularColor&&u.setColor3("reflectivityColor",a.specularColor),null!==a.glossiness&&u.setFloat("glossiness",a.glossiness)):"PBRMaterial"===a.getClassName()?(null!==a.metallicTexture&&(u.setTexture("reflectivitySampler",a.metallicTexture),u.setMatrix("reflectivityMatrix",a.metallicTexture.getTextureMatrix())),null!==a.metallic&&u.setFloat("metallic",a.metallic),null!==a.roughness&&u.setFloat("glossiness",1-a.roughness),null!==a.roughness||null!==a.metallic||null!==a.metallicTexture?(null!==a.albedoTexture&&(u.setTexture("albedoSampler",a.albedoTexture),u.setMatrix("albedoMatrix",a.albedoTexture.getTextureMatrix())),null!==a.albedoColor&&u.setColor3("albedoColor",a.albedoColor)):(null!==a.reflectivityTexture?(u.setTexture("reflectivitySampler",a.reflectivityTexture),u.setMatrix("reflectivityMatrix",a.reflectivityTexture.getTextureMatrix())):null!==a.reflectivityColor&&u.setColor3("reflectivityColor",a.reflectivityColor),null!==a.microSurface&&u.setFloat("glossiness",a.microSurface))):"StandardMaterial"===a.getClassName()&&(null!==a.specularTexture&&(u.setTexture("reflectivitySampler",a.specularTexture),u.setMatrix("reflectivityMatrix",a.specularTexture.getTextureMatrix())),null!==a.specularColor&&u.setColor3("reflectivityColor",a.specularColor))),bindClipPlane(u,a,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&(u.setMatrices("mBones",t.skeleton.getTransformMatrices(t)),this._enableVelocity&&u.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])),MaterialHelper.BindMorphTargetParameters(t,u),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(u),this._enableVelocity&&(u.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),u.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),o&&t.hasThinInstances&&u.setMatrix("world",l),t._processRendering(i,e,u,a.fillMode,n,o,(e,t)=>{e||u.setMatrix("world",t)})}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,r)=>{if((r||0===i)&&t.subMeshes)for(let i=0;i<t.subMeshes.length;++i){let r=t.subMeshes[i],s=r.getMaterial(),a=r.getRenderingMesh();if(!s)continue;let n=a._getInstancesRenderList(r._id,!!r.getReplacementMesh()),o=e.getCaps().instancedArrays&&(null!==n.visibleInstances[r._id]||a.hasThinInstances);if(!this.isReady(r,o))return!1}return!0},this._multiRenderTarget.customRenderFunction=(t,i,r,s)=>{let a;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),a=0;a<s.length;a++)renderSubMesh(s.data[a]);e.setColorWrite(!0)}for(a=0;a<t.length;a++)renderSubMesh(t.data[a]);for(e.setDepthWrite(!1),a=0;a<i.length;a++)renderSubMesh(i.data[a]);if(this.renderTransparentMeshes)for(a=0;a<r.length;a++)renderSubMesh(r.data[a]);e.setDepthWrite(!0)}}_copyBonesTransformationMatrices(e,t){for(let i=0;i<e.length;i++)t[i]=e[i];return t}};GeometryBufferRenderer.DEPTH_TEXTURE_TYPE=0,GeometryBufferRenderer.NORMAL_TEXTURE_TYPE=1,GeometryBufferRenderer.POSITION_TEXTURE_TYPE=2,GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE=3,GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE=4,GeometryBufferRenderer._SceneComponentInitialization=e=>{throw _WarnImport("GeometryBufferRendererSceneComponent")};let MotionBlurConfiguration=class MotionBlurConfiguration{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}};Object.defineProperty(scene_Scene.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),scene_Scene.prototype.enableGeometryBufferRenderer=function(e=1,t=15){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new GeometryBufferRenderer(this,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},scene_Scene.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};let GeometryBufferRendererSceneComponent=class GeometryBufferRendererSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}};GeometryBufferRenderer._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);t||(t=new GeometryBufferRendererSceneComponent(e),e._addComponent(t))};let nN=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; +#ifdef OBJECT_BASED +uniform sampler2D velocitySampler; +#else +uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#ifdef GEOMETRY_SUPPORTED +#ifdef OBJECT_BASED +vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) +{if (i>=samplesCount) +break;vec2 offset=vUV+velocity*(hlim+float(i)); +#if defined(WEBGPU) +result+=texture2DLodEXT(textureSampler,offset,0.0); +#else +result+=texture2D(textureSampler,offset); +#endif +} +gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; +#else +vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; +vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) {if (i>=nSamples) +break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); +#if defined(WEBGPU) +result+=texture2DLodEXT(textureSampler,offset1,0.0); +#else +result+=texture2D(textureSampler,offset1); +#endif +} +gl_FragColor=result/float(nSamples); +#endif +#else +gl_FragColor=texture2D(textureSampler,vUV); +#endif +} +`;ShaderStore.ShadersStore.motionBlurPixelShader=nN;let MotionBlurPostProcess=class MotionBlurPostProcess extends postProcess_PostProcess{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,s,a,n,o=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,s,a,n,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",o,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new MotionBlurConfiguration)),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}let 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 logger_Logger.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=math_vector_Matrix.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 math_vector_Vector2(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){let t=math_vector_TmpVectors.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 math_vector_Vector2(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){let e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new MotionBlurPostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}};__decorate([serialize()],MotionBlurPostProcess.prototype,"motionStrength",void 0),__decorate([serialize()],MotionBlurPostProcess.prototype,"motionBlurSamples",null),__decorate([serialize()],MotionBlurPostProcess.prototype,"isObjectBased",null),h["BABYLON.MotionBlurPostProcess"]=MotionBlurPostProcess,ShaderStore.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";let RefractionPostProcess=class RefractionPostProcess extends postProcess_PostProcess{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,s,a,n,o,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,n,o,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add(e=>{this._refTexture=this._refTexture||new texture_Texture(t,e.getScene())}),this.onApplyObservable.add(e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new RefractionPostProcess(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};__decorate([serialize()],RefractionPostProcess.prototype,"color",void 0),__decorate([serialize()],RefractionPostProcess.prototype,"depth",void 0),__decorate([serialize()],RefractionPostProcess.prototype,"colorLevel",void 0),__decorate([serialize()],RefractionPostProcess.prototype,"refractionTextureUrl",void 0),h["BABYLON.RefractionPostProcess"]=RefractionPostProcess;let nF=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + +texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + +texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + +texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - +color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;ShaderStore.ShadersStore.sharpenPixelShader=nF;let SharpenPostProcess=class SharpenPostProcess extends postProcess_PostProcess{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,s,a,n=0,o=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,s,a,null,n,void 0,null,o),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,r){return decorators_SerializationHelper.Parse(()=>new SharpenPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};__decorate([serialize()],SharpenPostProcess.prototype,"colorAmount",void 0),__decorate([serialize()],SharpenPostProcess.prototype,"edgeAmount",void 0),h["BABYLON.SharpenPostProcess"]=SharpenPostProcess;let postProcessRenderPipeline_PostProcessRenderPipeline=class postProcessRenderPipeline_PostProcessRenderPipeline{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=[],this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(let 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){let i=this._renderEffects[e];i&&i._enable(tools_Tools.MakeArray(t||this._cameras))}_disableEffect(e,t){let i=this._renderEffects[e];i&&i._disable(tools_Tools.MakeArray(t||this._cameras))}_attachCameras(e,t){let i;let r=tools_Tools.MakeArray(e||this._cameras);if(!r)return;let s=[];for(i=0;i<r.length;i++){let e=r[i];e&&(-1===this._cameras.indexOf(e)?this._cameras.push(e):t&&s.push(i))}for(i=0;i<s.length;i++)r.splice(s[i],1);for(let e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._attachCameras(r)}_detachCameras(e){let t=tools_Tools.MakeArray(e||this._cameras);if(t){for(let e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._detachCameras(t);for(let e=0;e<t.length;e++)this._cameras.splice(this._cameras.indexOf(t[e]),1)}}_update(){for(let e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._update();for(let e=0;e<this._cameras.length;e++){if(!this._cameras[e])continue;let t=this._cameras[e].name;this._renderEffectsForIsolatedPass[t]&&this._renderEffectsForIsolatedPass[t]._update()}}_reset(){this._renderEffects={},this._renderEffectsForIsolatedPass=[]}_enableMSAAOnFirstPostProcess(e){if(!this._engine._features.supportMSAA)return!1;let t=Object.keys(this._renderEffects);if(t.length>0){let i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){let e=Object.keys(this._renderEffects);for(let t of e){let e=this._renderEffects[t].getPostProcesses();if(e)for(let t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}};__decorate([serialize()],postProcessRenderPipeline_PostProcessRenderPipeline.prototype,"_name",void 0);let PostProcessRenderPipelineManager=class PostProcessRenderPipelineManager{constructor(){this._renderPipelines={}}get supportedPipelines(){let e=[];for(let t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){let 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){let r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){let i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t._rebuild()}}dispose(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.dispose()}}};Object.defineProperty(scene_Scene.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new PostProcessRenderPipelineManagerSceneComponent(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new PostProcessRenderPipelineManager}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});let PostProcessRenderPipelineManagerSceneComponent=class PostProcessRenderPipelineManagerSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.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()}};let DefaultRenderingPipeline=class DefaultRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{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(){let e=this.bloom;this.bloom=new BloomEffect(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;t<this._cameras.length;t++)e.disposeEffects(this._cameras[t])}get depthOfFieldEnabled(){return this._depthOfFieldEnabled}set depthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get depthOfFieldBlurLevel(){return this._depthOfFieldBlurLevel}set depthOfFieldBlurLevel(e){if(this._depthOfFieldBlurLevel===e)return;this._depthOfFieldBlurLevel=e;let t=this.depthOfField;this.depthOfField=new DepthOfFieldEffect(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!1),this.depthOfField.focalLength=t.focalLength,this.depthOfField.focusDistance=t.focusDistance,this.depthOfField.fStop=t.fStop,this.depthOfField.lensSize=t.lensSize;for(let e=0;e<this._cameras.length;e++)t.disposeEffects(this._cameras[e]);this._buildPipeline()}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}set imageProcessingEnabled(e){this._imageProcessingEnabled!==e&&(this._scene.imageProcessingConfiguration.isEnabled=e)}get imageProcessingEnabled(){return this._imageProcessingEnabled}set glowLayerEnabled(e){e&&!this._glowLayer?this._glowLayer=new GlowLayer("",this._scene):!e&&this._glowLayer&&(this._glowLayer.dispose(),this._glowLayer=null)}get glowLayerEnabled(){return null!=this._glowLayer}get glowLayer(){return this._glowLayer}set chromaticAberrationEnabled(e){this._chromaticAberrationEnabled!==e&&(this._chromaticAberrationEnabled=e,this._buildPipeline())}get chromaticAberrationEnabled(){return this._chromaticAberrationEnabled}set grainEnabled(e){this._grainEnabled!==e&&(this._grainEnabled=e,this._buildPipeline())}get grainEnabled(){return this._grainEnabled}constructor(e="",t=!0,i=engineStore_EngineStore.LastCreatedScene,r,s=!0){super(i.getEngine(),e),this._camerasToBeAttached=[],this.SharpenPostProcessId="SharpenPostProcessEffect",this.ImageProcessingPostProcessId="ImageProcessingPostProcessEffect",this.FxaaPostProcessId="FxaaPostProcessEffect",this.ChromaticAberrationPostProcessId="ChromaticAberrationPostProcessEffect",this.GrainPostProcessId="GrainPostProcessEffect",this._glowLayer=null,this.animations=[],this._imageProcessingConfigurationObserver=null,this._sharpenEnabled=!1,this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._depthOfFieldBlurLevel=t8.Low,this._fxaaEnabled=!1,this._imageProcessingEnabled=!0,this._bloomScale=.5,this._chromaticAberrationEnabled=!1,this._grainEnabled=!1,this._buildAllowed=!0,this.onBuildObservable=new observable_Observable,this._resizeObserver=null,this._hardwareScaleLevel=1,this._bloomKernel=64,this._bloomWeight=.15,this._bloomThreshold=.9,this._samples=1,this._hasCleared=!1,this._prevPostProcess=null,this._prevPrevPostProcess=null,this._depthOfFieldSceneObserver=null,this._activeCameraChangedObserver=null,this._activeCamerasChangedObserver=null,this._cameras=r||i.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._buildAllowed=s,this._scene=i;let a=this._scene.getEngine().getCaps();this._hdr=t&&(a.textureHalfFloatRender||a.textureFloatRender),this._hdr?a.textureHalfFloatRender?this._defaultPipelineTextureType=2:a.textureFloatRender&&(this._defaultPipelineTextureType=1):this._defaultPipelineTextureType=0,i.postProcessRenderPipelineManager.addPipeline(this);let n=this._scene.getEngine();this.sharpen=new SharpenPostProcess("sharpen",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,n,!1,this._defaultPipelineTextureType,!0),this._sharpenEffect=new postProcessRenderEffect_PostProcessRenderEffect(n,this.SharpenPostProcessId,()=>this.sharpen,!0),this.depthOfField=new DepthOfFieldEffect(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=n.getHardwareScalingLevel(),this._resizeObserver=n.onResizeObservable.add(()=>{this._hardwareScaleLevel=n.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new BloomEffect(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new ChromaticAberrationPostProcess("ChromaticAberration",n.getRenderWidth(),n.getRenderHeight(),1,null,texture_Texture.BILINEAR_SAMPLINGMODE,n,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new postProcessRenderEffect_PostProcessRenderEffect(n,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new GrainPostProcess("Grain",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,n,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new postProcessRenderEffect_PostProcessRenderEffect(n,this.GrainPostProcessId,()=>this.grain,!0);let o=!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,o?tools_Tools.SetImmediate(()=>{this._buildPipeline()}):this._buildPipeline())}),this._buildPipeline(),o=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){let 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;let 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(let e of this._cameras){let t=this._scene.enableDepthRenderer(e);t.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);let 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 ImageProcessingPostProcess("imageProcessing",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(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 FxaaPostProcess("fxaa",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e,this.FxaaPostProcessId,()=>this.fxaa,!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add(()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)})),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add(()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)})),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&logger_Logger.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;t<this._cameras.length;t++){let i=this._cameras[t];this.imageProcessing&&this.imageProcessing.dispose(i),this.fxaa&&this.fxaa.dispose(i),e&&(this.sharpen&&this.sharpen.dispose(i),this.depthOfField&&(this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver),this.depthOfField.disposeEffects(i)),this.bloom&&this.bloom.disposeEffects(i),this.chromaticAberration&&this.chromaticAberration.dispose(i),this.grain&&this.grain.dispose(i),this._glowLayer&&this._glowLayer.dispose())}this.imageProcessing=null,this.fxaa=null,e&&(this.sharpen=null,this._sharpenEffect=null,this.depthOfField=null,this.bloom=null,this.chromaticAberration=null,this._chromaticAberrationEffect=null,this.grain=null,this._grainEffect=null,this._glowLayer=null)}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){let t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._buildAllowed=!1,this.onBuildObservable.clear(),this._disposePostProcesses(!0),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._scene._postProcessRenderPipelineManager.removePipeline(this.name),this._scene.autoClear=!0,this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver),this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver),this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver),super.dispose()}serialize(){let e=decorators_SerializationHelper.Serialize(this);return e.customType="DefaultRenderingPipeline",e}static Parse(e,t,i){return decorators_SerializationHelper.Parse(()=>new DefaultRenderingPipeline(e._name,e._name._hdr,t),e,t,i)}};__decorate([serialize()],DefaultRenderingPipeline.prototype,"sharpenEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"bloomKernel",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"_bloomWeight",void 0),__decorate([serialize()],DefaultRenderingPipeline.prototype,"_bloomThreshold",void 0),__decorate([serialize()],DefaultRenderingPipeline.prototype,"_hdr",void 0),__decorate([serialize()],DefaultRenderingPipeline.prototype,"bloomWeight",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"bloomThreshold",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"bloomScale",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"bloomEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"depthOfFieldEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"depthOfFieldBlurLevel",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"fxaaEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"samples",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"imageProcessingEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"glowLayerEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"chromaticAberrationEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"grainEnabled",null),h["BABYLON.DefaultRenderingPipeline"]=DefaultRenderingPipeline;let nw=`uniform sampler2D textureSampler; +uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } +else { lum_threshold=0.5+0.44*threshold; } +luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} +float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); +#ifdef PENTAGON +blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); +#else +blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); +#endif +blurred/=39.0;gl_FragColor=blurred;}`;ShaderStore.ShadersStore.lensHighlightsPixelShader=nw;let nL=`uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; +uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; +#define PI 3.14159265 +#define TWOPI 6.28318530 +#define inverse_focal_length 0.1 +vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) +{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} +vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } +vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} +float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} +float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} +vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} +if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} +col/=total_weight; +if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} +return col;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); +vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); +float depth=texture2D(depthSampler,distorted_coords).r; +float distance=near+(far-near)*depth; +vec4 color=texture2D(textureSampler,vUV); +float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } +float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} +float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} +else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} +if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} +if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} +`;ShaderStore.ShadersStore.depthOfFieldPixelShader=nL;let SSAO2Configuration=class SSAO2Configuration{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}};let nV=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSAO +float scales[16]=float[16]( +0.1, +0.11406250000000001, +0.131640625, +0.15625, +0.187890625, +0.2265625, +0.272265625, +0.325, +0.384765625, +0.4515625, +0.525390625, +0.60625, +0.694140625, +0.7890625, +0.891015625, +1.0 +);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() +{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=depth/abs(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i<SAMPLES; ++i) {vec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];samplePosition=samplePosition*correctedRadius+origin;vec4 offset=vec4(samplePosition,1.0);offset=projection*offset;offset.xyz/=offset.w;offset.xy=offset.xy*0.5+0.5;if (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {continue;} +float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} +occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} +#endif +#ifdef BLUR +uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; +#ifndef BLUR_BYPASS +uniform sampler2D depthSampler; +#ifdef BLUR_LEGACY +#define inline +float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} +#endif +#endif +void main() +{float result=0.0; +#ifdef BLUR_BYPASS +result=textureLod(textureSampler,vUV,0.0).r; +#else +#ifdef BLUR_H +vec2 step=vec2(1.0/outSize,0.0); +#else +vec2 step=vec2(0.0,1.0/outSize); +#endif +#ifdef BLUR_LEGACY +result=blur13Bilateral(textureSampler,vUV,step); +#else +float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i<samples; i+=2) +{vec2 samplePos=vUV+step*(float(i)+0.5);float sampleDepth=abs(textureLod(depthSampler,samplePos,0.0).r);float falloff=smoothstep(0.0, +float(samples), +float(samples)-abs(float(i))*soften);float minDivider=tolerance*0.5+0.003;float weight=falloff/( minDivider+abs(compareDepth-sampleDepth));result+=textureLod(textureSampler,samplePos,0.0).r*weight;weightSum+=weight;} +result/=weightSum; +#endif +#endif +gl_FragColor.rgb=vec3(result);gl_FragColor.a=1.0;} +#endif +`;ShaderStore.ShadersStore.ssao2PixelShader=nV;let nU=`uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);vec4 sceneColor=texture2D(originalColor,vUV);gl_FragColor=sceneColor*ssaoColor; +#define CUSTOM_FRAGMENT_MAIN_END +} +`;ShaderStore.ShadersStore.ssaoCombinePixelShader=nU;let SSAO2RenderingPipeline=class SSAO2RenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{set epsilon(e){this._epsilon=e,this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO())}get epsilon(){return this._epsilon}set samples(e){this._samples=e,this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO()),this._sampleSphere=this._generateHemisphere()}get samples(){return this._samples}set textureSamples(e){this._textureSamples=e,this._prePassRenderer?this._prePassRenderer.samples=e:this._originalColorPostProcess.samples=e}get textureSamples(){return this._textureSamples}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}set bypassBlur(e){let t=this._getDefinesForBlur(this.expensiveBlur,e),i=this._getSamplersForBlur(e);this._blurHPostProcess.updateEffect(t.h,null,i),this._blurVPostProcess.updateEffect(t.v,null,i),this._bypassBlur=e}get bypassBlur(){return this._bypassBlur}set expensiveBlur(e){let t=this._getDefinesForBlur(e,this._bypassBlur);this._blurHPostProcess.updateEffect(t.h),this._blurVPostProcess.updateEffect(t.v),this._expensiveBlur=e}get expensiveBlur(){return this._expensiveBlur}static get IsSupported(){let e=engineStore_EngineStore.LastCreatedEngine;return!!e&&e._features.supportSSAO2}get scene(){return this._scene}constructor(e,t,i,r,s=!1,a=0){var n,o;if(super(t.getEngine(),e),this.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",this.SSAORenderEffect="SSAORenderEffect",this.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",this.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",this.SSAOCombineRenderEffect="SSAOCombineRenderEffect",this.totalStrength=1,this.maxZ=100,this.minZAspect=.2,this._epsilon=.02,this._samples=8,this._textureSamples=1,this._forceGeometryBuffer=!1,this.radius=2,this.base=0,this._bypassBlur=!1,this._expensiveBlur=!0,this.bilateralSamples=16,this.bilateralSoften=0,this.bilateralTolerance=0,this._bits=new Uint32Array(1),this._scene=t,this._ratio=i,this._textureType=a,this._forceGeometryBuffer=s,!this.isSupported){logger_Logger.Error("The current engine does not support SSAO 2.");return}let l=this._ratio.ssaoRatio||i,h=this._ratio.blurRatio||i;this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),(null===(n=t.geometryBufferRenderer)||void 0===n?void 0:n.generateNormalsInWorldSpace)&&console.error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!")):(t.enablePrePassRenderer(),(null===(o=t.prePassRenderer)||void 0===o?void 0:o.generateNormalsInWorldSpace)&&console.error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!")),this._createRandomTexture(),this._originalColorPostProcess=new PassPostProcess("SSAOOriginalSceneColor",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),void 0,this._textureType),this._originalColorPostProcess.samples=this.textureSamples,this._createSSAOPostProcess(1,a),this._createBlurPostProcess(l,h,this._textureType),this._createSSAOCombinePostProcess(h,this._textureType),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOOriginalSceneColorEffect,()=>this._originalColorPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e<this._scene.cameras.length;e++){let t=this._scene.cameras[e];this._originalColorPostProcess.dispose(t),this._ssaoPostProcess.dispose(t),this._blurHPostProcess.dispose(t),this._blurVPostProcess.dispose(t),this._ssaoCombinePostProcess.dispose(t)}this._randomTexture.dispose(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),super.dispose()}_rebuild(){super._rebuild()}_getSamplersForBlur(e){return e?["textureSampler"]:["textureSampler","depthSampler"]}_getDefinesForBlur(e,t){let i="#define BLUR\n";return t&&(i+="#define BLUR_BYPASS\n"),e||(i+="#define BLUR_LEGACY\n"),{h:i+"#define BLUR_H\n",v:i}}_createBlurPostProcess(e,t,i){let r=this._getDefinesForBlur(this.expensiveBlur,this.bypassBlur),s=this._getSamplersForBlur(this.bypassBlur);this._blurHPostProcess=this._createBlurFilter("BlurH",s,e,r.h,i,!0),this._blurVPostProcess=this._createBlurFilter("BlurV",s,t,r.v,i,!1)}_createBlurFilter(e,t,i,r,s,a){let n=new postProcess_PostProcess(e,"ssao2",["outSize","samples","soften","tolerance"],t,i,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,r,s);return n.onApply=e=>{if(!this._scene.activeCamera)return;let t=a?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=a?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)])},n.samples=this.textureSamples,n}_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,23283064365386963e-26*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){let i=2*t*Math.PI,r=1-.85*e,s=Math.sqrt(1-r*r);return new math_vector_Vector3(Math.cos(i)*s,Math.sin(i)*s,r)}_generateHemisphere(){let e;let t=this.samples,i=[],r=0;for(;r<t;){if(t<16)e=this._hemisphereSample_uniform(Math.random(),Math.random());else{let i=this._hammersley(r,t);e=this._hemisphereSample_uniform(i[0],i[1])}i.push(e.x,e.y,e.z),r++}return i}_getDefinesForSSAO(){let e=`#define SSAO +#define SAMPLES ${this.samples} +#define EPSILON ${this.epsilon.toFixed(4)}`;return e}_createSSAOPostProcess(e,t){this._sampleSphere=this._generateHemisphere();let i=this._getDefinesForSSAO();this._ssaoPostProcess=new postProcess_PostProcess("ssao2","ssao2",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","base","range","projection","near","texelSize","xViewport","yViewport","maxZ","minZAspect","depthProjection"],["randomSampler","depthSampler","normalSampler"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i,t),this._ssaoPostProcess.onApply=e=>{var t,i,r,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===camera_Camera.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",SSAO2RenderingPipeline.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{let a=this._scene.getEngine().getRenderWidth()/2,n=this._scene.getEngine().getRenderHeight()/2,o=null!==(t=this._scene.activeCamera.orthoLeft)&&void 0!==t?t:-a,l=null!==(i=this._scene.activeCamera.orthoRight)&&void 0!==i?i:a,h=null!==(r=this._scene.activeCamera.orthoBottom)&&void 0!==r?r:-n,c=null!==(s=this._scene.activeCamera.orthoTop)&&void 0!==s?s:n;e.setMatrix3x3("depthProjection",SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",(l-o)*.5),e.setFloat("yViewport",(c-h)*.5)}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 SSAO2Configuration)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new postProcess_PostProcess("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{let t=this._scene.activeCamera.viewport;e.setVector4("viewport",math_vector_TmpVectors.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){let e=new Uint8Array(65536),t=math_vector_Vector2.Zero();for(let i=0;i<e.length;)t.set(math_scalar_Scalar.RandomRange(0,1),math_scalar_Scalar.RandomRange(0,1)).normalize().scaleInPlace(255),e[i++]=Math.floor(t.x),e[i++]=Math.floor(t.y),e[i++]=0,e[i++]=255;let i=rawTexture_RawTexture.CreateRGBATexture(e,128,128,this._scene,!1,!1,2);i.name="SSAORandomTexture",i.wrapU=texture_Texture.WRAP_ADDRESSMODE,i.wrapV=texture_Texture.WRAP_ADDRESSMODE,this._randomTexture=i}serialize(){let e=decorators_SerializationHelper.Serialize(this);return e.customType="SSAO2RenderingPipeline",e}static Parse(e,t,i){return decorators_SerializationHelper.Parse(()=>new SSAO2RenderingPipeline(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}};SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],__decorate([serialize()],SSAO2RenderingPipeline.prototype,"totalStrength",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"maxZ",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"minZAspect",void 0),__decorate([serialize("epsilon")],SSAO2RenderingPipeline.prototype,"_epsilon",void 0),__decorate([serialize("samples")],SSAO2RenderingPipeline.prototype,"_samples",void 0),__decorate([serialize("textureSamples")],SSAO2RenderingPipeline.prototype,"_textureSamples",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"_forceGeometryBuffer",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"_ratio",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"_textureType",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"radius",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"base",void 0),__decorate([serialize("bypassBlur")],SSAO2RenderingPipeline.prototype,"_bypassBlur",void 0),__decorate([serialize("expensiveBlur")],SSAO2RenderingPipeline.prototype,"_expensiveBlur",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"bilateralSamples",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"bilateralSoften",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"bilateralTolerance",void 0),h["BABYLON.SSAO2RenderingPipeline"]=SSAO2RenderingPipeline;let nk=`uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSAO +uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) +{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} +void main() +{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; i<SAMPLES; i++) +{ray=radiusDepth*reflect(sampleSphere[i],random);hemiRay=position+sign(dot(ray,normal))*ray;occlusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;difference=depth-occlusionDepth;occlusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));} +float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor.r=result;gl_FragColor.g=result;gl_FragColor.b=result;gl_FragColor.a=1.0;} +#endif +`;ShaderStore.ShadersStore.ssaoPixelShader=nk;let SSAORenderingPipeline=class SSAORenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{get scene(){return this._scene}constructor(e,t,i,r){super(t.getEngine(),e),this.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",this.SSAORenderEffect="SSAORenderEffect",this.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",this.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",this.SSAOCombineRenderEffect="SSAOCombineRenderEffect",this.totalStrength=1,this.radius=1e-4,this.area=.0075,this.fallOff=1e-6,this.base=.5,this._firstUpdate=!0,this._scene=t,this._createRandomTexture();let s=i.ssaoRatio||i,a=i.combineRatio||i;this._originalColorPostProcess=new PassPostProcess("SSAOOriginalSceneColor",a,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1),this._createSSAOPostProcess(s),this._createBlurPostProcess(s),this._createSSAOCombinePostProcess(a),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOOriginalSceneColorEffect,()=>this._originalColorPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){for(let i of(super._attachCameras(e,t),this._cameras))this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e<this._scene.cameras.length;e++){let t=this._scene.cameras[e];this._originalColorPostProcess.dispose(t),this._ssaoPostProcess.dispose(t),this._blurHPostProcess.dispose(t),this._blurVPostProcess.dispose(t),this._ssaoCombinePostProcess.dispose(t)}this._randomTexture.dispose(),e&&this._scene.disableDepthRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),super.dispose()}_createBlurPostProcess(e){this._blurHPostProcess=new BlurPostProcess("BlurH",new math_vector_Vector2(1,0),16,e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,0),this._blurVPostProcess=new BlurPostProcess("BlurV",new math_vector_Vector2(0,1),16,e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,0),this._blurHPostProcess.onActivateObservable.add(()=>{let e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e}),this._blurVPostProcess.onActivateObservable.add(()=>{let e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e})}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){let 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 postProcess_PostProcess("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,texture_Texture.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 postProcess_PostProcess("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",math_vector_TmpVectors.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){let e=new Uint8Array(1048576);for(let t=0;t<e.length;)e[t++]=Math.floor(255*Math.max(0,math_scalar_Scalar.RandomRange(-1,1))),e[t++]=Math.floor(255*Math.max(0,math_scalar_Scalar.RandomRange(-1,1))),e[t++]=Math.floor(255*Math.max(0,math_scalar_Scalar.RandomRange(-1,1))),e[t++]=255;let t=rawTexture_RawTexture.CreateRGBATexture(e,512,512,this._scene,!1,!1,2);t.name="SSAORandomTexture",t.wrapU=texture_Texture.WRAP_ADDRESSMODE,t.wrapV=texture_Texture.WRAP_ADDRESSMODE,this._randomTexture=t}};__decorate([serialize()],SSAORenderingPipeline.prototype,"totalStrength",void 0),__decorate([serialize()],SSAORenderingPipeline.prototype,"radius",void 0),__decorate([serialize()],SSAORenderingPipeline.prototype,"area",void 0),__decorate([serialize()],SSAORenderingPipeline.prototype,"fallOff",void 0),__decorate([serialize()],SSAORenderingPipeline.prototype,"base",void 0);let ScreenSpaceReflectionsConfiguration=class ScreenSpaceReflectionsConfiguration{constructor(){this.enabled=!1,this.name="screenSpaceReflections",this.texturesRequired=[6,3,1]}};let nG=`uniform sampler2D textureSampler; +#ifdef SSR_SUPPORTED +uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler; +#endif +uniform mat4 view;uniform mat4 projection;uniform float stepSize;uniform float strength;uniform float threshold;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;varying vec2 vUV; +#ifdef SSR_SUPPORTED +struct ReflectionInfo {vec3 color;vec4 coords;};/** +* According to specular,see https: +*/ +vec3 fresnelSchlick(float cosTheta,vec3 F0) +{return F0+(1.0-F0)*pow(1.0-cosTheta,5.0);} +/** +* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit +* by sampling multiple reflection pixels. +*/ +ReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord) +{ReflectionInfo info;info.color=vec3(0.0);vec4 projectedCoord;float sampledDepth;for(int i=0; i<SMOOTH_STEPS; i++) +{projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z;dir*=0.5;if(depth>0.0) +hitCoord-=dir;else +hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} +projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} +/** +* Tests the given world position (hitCoord) according to the given reflection vector (dir) +* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). +*/ +ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) +{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i<REFLECTION_SAMPLES; i++) +{hitCoord+=dir;projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z; +#ifdef RIGHT_HANDED_SCENE +depth*=-1.0; +#endif +if(((depth-dir.z)<threshold) && depth<=0.0) +{ +#ifdef ENABLE_SMOOTH_REFLECTIONS +return smoothReflectionInfo(dir,hitCoord); +#else +info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info; +#endif +}} +info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info;} +vec3 hash(vec3 a) +{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} +#endif +void main() +{ +#ifdef SSR_SUPPORTED +vec4 albedoFull=texture2D(textureSampler,vUV);vec3 albedo=albedoFull.rgb;float spec=texture2D(reflectivitySampler,vUV).r;if (spec==0.0) {gl_FragColor=albedoFull;return;} +vec3 normal=(texture2D(normalSampler,vUV)).xyz;vec3 position=(view*texture2D(positionSampler,vUV)).xyz;vec3 reflected=normalize(reflect(normalize(position),normalize(normal)));float roughness=1.0-texture2D(reflectivitySampler,vUV).a;vec3 jitt=mix(vec3(0.0),hash(position),roughness)*roughnessFactor;ReflectionInfo info=getReflectionInfo(jitt+reflected,position);vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-info.coords.xy));float screenEdgefactor=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);vec3 F0=vec3(0.04);F0 =mix(F0,albedo,spec);vec3 fresnel=fresnelSchlick(max(dot(normalize(normal),normalize(position)),0.0),F0); +#ifdef RIGHT_HANDED_SCENE +reflected.z*=-1.0; +#endif +float reflectionMultiplier=clamp(pow(spec*strength,reflectionSpecularFalloffExponent)*screenEdgefactor*reflected.z,0.0,0.9);float albedoMultiplier=1.0-reflectionMultiplier;vec3 SSR=info.color*fresnel;gl_FragColor=vec4((albedo*albedoMultiplier)+(SSR*reflectionMultiplier),albedoFull.a); +#else +gl_FragColor=texture2D(textureSampler,vUV); +#endif +} +`;ShaderStore.ShadersStore.screenSpaceReflectionPixelShader=nG;let ScreenSpaceReflectionPostProcess=class ScreenSpaceReflectionPostProcess extends postProcess_PostProcess{get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"ScreenSpaceReflectionPostProcess"}constructor(e,t,i,r,s,a,n,o=0,l=!1,h=!1){if(super(e,"screenSpaceReflection",["projection","view","threshold","reflectionSpecularFalloffExponent","strength","stepSize","roughnessFactor"],["textureSampler","normalSampler","positionSampler","reflectivitySampler"],i,r,s,a,n,"#define SSR_SUPPORTED\n#define REFLECTION_SAMPLES 64\n#define SMOOTH_STEPS 5\n",o,void 0,null,l),this.threshold=1.2,this.strength=1,this.reflectionSpecularFalloffExponent=3,this.step=1,this.roughnessFactor=.2,this._forceGeometryBuffer=!1,this._enableSmoothReflections=!1,this._reflectionSamples=64,this._smoothSteps=5,this._forceGeometryBuffer=h,this._forceGeometryBuffer){let e=t.enableGeometryBufferRenderer();e&&e.isSupported&&(e.enablePosition=!0,e.enableReflectivity=!0,e.generateNormalsInWorldSpace&&console.error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"))}else{let e=t.enablePrePassRenderer();null==e||e.markAsDirty(),(null==e?void 0:e.generateNormalsInWorldSpace)&&console.error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the prepass renderer!"),this._prePassEffectConfiguration=new ScreenSpaceReflectionsConfiguration}this._updateEffectDefines(),this.onApply=e=>{let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(!r&&!i)return;if(i){let t=i.getTextureIndex(GeometryBufferRenderer.POSITION_TEXTURE_TYPE),r=i.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[r])}else if(r){let t=r.getIndex(1),i=r.getIndex(3),s=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[s]),e.setTexture("positionSampler",r.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",r.getRenderTarget().textures[i])}let s=t.activeCamera;if(!s)return;let a=s.getViewMatrix(!0),n=s.getProjectionMatrix(!0);e.setMatrix("projection",n),e.setMatrix("view",a),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(){let 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,r){return decorators_SerializationHelper.Parse(()=>new ScreenSpaceReflectionPostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"threshold",void 0),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"strength",void 0),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"reflectionSpecularFalloffExponent",void 0),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"step",void 0),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"roughnessFactor",void 0),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"enableSmoothReflections",null),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"reflectionSamples",null),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"smoothSteps",null),h["BABYLON.ScreenSpaceReflectionPostProcess"]=ScreenSpaceReflectionPostProcess;let nz=`uniform sampler2D textureSampler;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +#if defined(PASS_POST_PROCESS) +void main(void) +{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} +#endif +#if defined(DOWN_SAMPLE_X4) +uniform vec2 dsOffsets[16];void main(void) +{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} +#endif +#if defined(BRIGHT_PASS) +uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) +{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminance<brightThreshold) {average=vec4(0.0,0.0,0.0,1.0);} +gl_FragColor=average;} +#endif +#if defined(TEXTURE_ADDER) +uniform sampler2D otherSampler;uniform sampler2D lensSampler;uniform float exposure;void main(void) +{vec3 colour=texture2D(textureSampler,vUV).rgb;colour*=exposure;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;colour+=colour*texture2D(lensSampler,vUV).rgb;vec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);gl_FragColor=finalColor;} +#endif +#if defined(VLS) +#define PI 3.1415926535897932384626433832795 +uniform mat4 shadowViewProjection;uniform mat4 lightWorld;uniform vec3 cameraPosition;uniform vec3 sunDirection;uniform vec3 sunColor;uniform vec2 depthValues;uniform float scatteringCoefficient;uniform float scatteringPower;uniform sampler2D shadowMapSampler;uniform sampler2D positionSampler;float computeScattering(float lightDotView) +{float result=1.0-scatteringCoefficient*scatteringCoefficient;result/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));return result;} +void main(void) +{vec3 worldPos=texture2D(positionSampler,vUV).rgb;vec3 startPosition=cameraPosition;vec3 rayVector=worldPos-startPosition;float rayLength=length(rayVector);vec3 rayDirection=rayVector/rayLength;float stepLength=rayLength/NB_STEPS;vec3 stepL=rayDirection*stepLength;vec3 currentPosition=startPosition;vec3 accumFog=vec3(0.0);for (int i=0; i<int(NB_STEPS); i++) +{vec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);float depthMetric= (worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depthMetric,0.0,1.0);worldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;worldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);float shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;if (shadowMapValue>shadowPixelDepth) +accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} +accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} +#endif +#if defined(VLSMERGE) +uniform sampler2D originalSampler;void main(void) +{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} +#endif +#if defined(LUMINANCE) +uniform vec2 lumOffsets[4];void main() +{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) +{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); +#ifdef WEIGHTED_AVERAGE +float GreyValue=dot(color.rgb,weight); +#endif +#ifdef BRIGHTNESS +float GreyValue=max(color.r,max(color.g,color.b)); +#endif +#ifdef HSL_COMPONENT +float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); +#endif +#ifdef MAGNITUDE +float GreyValue=length(color.rgb); +#endif +maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} +average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} +#endif +#if defined(LUMINANCE_DOWN_SAMPLE) +uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; +#ifdef FINAL_DOWN_SAMPLER +#include<packingFunctions> +#endif +void main() +{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) +{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} +average/=9.0; +#ifdef FINAL_DOWN_SAMPLER +gl_FragColor=pack(average); +#else +gl_FragColor=vec4(average,average,0.0,1.0); +#endif +} +#endif +#if defined(HDR) +uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() +{vec4 color=texture2D(textureAdderSampler,vUV); +#ifndef AUTO_EXPOSURE +vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; +#endif +gl_FragColor=color;} +#endif +#if defined(LENS_FLARE) +#define GHOSTS 3 +uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) +{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} +float noise(in vec2 p) +{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), +hash(i+vec2(1.0,0.0)),u.x), +mix(hash(i+vec2(0.0,1.0)), +hash(i+vec2(1.0,1.0)),u.x),u.y);} +float fbm(vec2 p) +{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} +vec3 pattern(vec2 uv) +{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} +float luminance(vec3 color) +{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} +vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) +{return vec4( +texture2D(tex,texcoord+direction*distortion.r).r, +texture2D(tex,texcoord+direction*distortion.g).g, +texture2D(tex,texcoord+direction*distortion.b).b, +1.0 +);} +void main(void) +{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i<GHOSTS; ++i) +{vec2 offset=fract(uv+ghostDir*ghostIndice);float weight=length(vec2(0.5)-offset)/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;ghostIndice+=1.0;} +vec2 haloVec=normalize(ghostDir)*haloWidth;float weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;result*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));gl_FragColor=result;} +#endif +#if defined(LENS_FLARE_COMPOSE) +uniform sampler2D otherSampler;uniform sampler2D lensDirtSampler;uniform sampler2D lensStarSampler;uniform mat4 lensStarMatrix;void main(void) +{vec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;vec4 lensMod=texture2D(lensDirtSampler,vUV);lensMod+=texture2D(lensStarSampler,vUV/*lensFlareCoords*/);vec4 result=texture2D(textureSampler,vUV)*lensMod;gl_FragColor=texture2D(otherSampler,vUV)+result;} +#endif +#if defined(DEPTH_OF_FIELD) +uniform sampler2D otherSampler;uniform sampler2D depthSampler;uniform float distance;void main(void) +{vec4 sharp=texture2D(otherSampler,vUV);vec4 blur=texture2D(textureSampler,vUV);float dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);float factor=0.0;if (dist<0.05) +factor=1.0;else if (dist<0.1) +factor=20.0*(0.1-dist);else if (dist<0.5) +factor=0.0;else +factor=2.0*(dist-0.5);factor=clamp(factor,0.0,0.90);gl_FragColor=mix(sharp,blur,factor);} +#endif +#if defined(MOTION_BLUR) +uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform vec2 screenSize;uniform float motionScale;uniform float motionStrength;uniform sampler2D depthSampler;void main(void) +{vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=cpos*inverseViewProjection;vec4 ppos=cpos*prevViewProjection;ppos.xyz/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {if (i>=nSamples) +break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} +gl_FragColor=result/float(nSamples);} +#endif +`;ShaderStore.ShadersStore.standardPixelShader=nz;let StandardRenderingPipeline=class StandardRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{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){let 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){let 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){let e=this._scene.enableGeometryBufferRenderer();if(!e){logger_Logger.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");return}}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){let 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 ScreenSpaceReflectionPostProcess("HDRPass",t,e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new postProcess_PostProcess("HDRPass","standard",[],[],e,null,texture_Texture.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 postProcessRenderEffect_PostProcessRenderEffect(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 postProcess_PostProcess("HDRDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new postProcess_PostProcess("HDRVLSFinal","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new postProcess_PostProcess("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new postProcess_PostProcess("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(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 FxaaPostProcess("fxaa",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&logger_Logger.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){let i=Array(32);this.downSampleX4PostProcess=new postProcess_PostProcess("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0,r=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let a=-2;a<2;a++)i[t]=(e+.5)*(1/r),i[t+1]=(a+.5)*(1/s),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){let i=Array(8);this.brightPassPostProcess=new postProcess_PostProcess("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{let t=1/this.brightPassPostProcess.width,r=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*r,i[2]=.5*t,i[3]=.5*r,i[4]=-.5*t,i[5]=-.5*r,i[6]=.5*t,i[7]=-.5*r,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){let s=e.getEngine(),a=new BlurPostProcess("HDRBlurH_"+i,new math_vector_Vector2(1,0),this[r],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),n=new BlurPostProcess("HDRBlurV_"+i,new math_vector_Vector2(0,1),this[r],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);a.onActivateObservable.add(()=>{let e=a.width/s.getRenderWidth();a.kernel=this[r]*e}),n.onActivateObservable.add(()=>{let e=n.height/s.getRenderHeight();n.kernel=this.horizontalBlur?64*e:this[r]*e}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBlurH"+i,()=>a,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBlurV"+i,()=>n,!0)),this.blurHPostProcesses.push(a),this.blurVPostProcesses.push(n)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new postProcess_PostProcess("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,texture_Texture.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 postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){let i=e.enableGeometryBufferRenderer();i.enablePosition=!0;let r=i.getGBuffer();this.volumetricLightPostProcess=new postProcess_PostProcess("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));let s=math_vector_Vector2.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){let t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new postProcess_PostProcess("HDRVLSMerge","standard",[],["originalSampler"],t,null,texture_Texture.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 postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,StandardRenderingPipeline.LuminanceSteps);this.luminancePostProcess=new postProcess_PostProcess("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);let r=[];this.luminancePostProcess.onApply=e=>{let t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;r[0]=-.5*t,r[1]=.5*i,r[2]=.5*t,r[3]=.5*i,r[4]=-.5*t,r[5]=-.5*i,r[6]=.5*t,r[7]=-.5*i,e.setArray2("lumOffsets",r)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let r=StandardRenderingPipeline.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let s="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(s+="#define FINAL_DOWN_SAMPLER");let a=new postProcess_PostProcess("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,t);this.luminanceDownSamplePostProcesses.push(a)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((t,i)=>{let r=Array(18);t.onApply=e=>{if(!s)return;let a=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)r[a]=e/s.width,r[a+1]=t/s.height,a+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{let t=e.getEngine().readPixels(0,0,1,1),i=new math_vector_Vector4(6030862941101084e-23,1/65025,1/255,1);t.then(e=>{let 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 postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLuminanceDownSample"+i,()=>t,!0))})}_createHdrPostProcess(e,t){let i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new postProcess_PostProcess("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let r=1,s=0,a=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{let e=(a-s)/1e3;this._hdrCurrentLuminance<r+this.hdrDecreaseRate*e?r+=this.hdrDecreaseRate*e:this._hdrCurrentLuminance>r-this.hdrIncreaseRate*e?r-=this.hdrIncreaseRate*e:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=math_scalar_Scalar.Clamp(r,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),a=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new postProcess_PostProcess("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new postProcess_PostProcess("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));let i=new math_vector_Vector2(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)};let r=math_vector_Matrix.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=math_vector_Matrix.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);let t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2),a=math_vector_Vector3.Dot(t.toVector3(),new math_vector_Vector3(1,0,0))+math_vector_Vector3.Dot(i.toVector3(),new math_vector_Vector3(0,0,1));a*=4;let n=math_vector_Matrix.FromValues(.5*Math.cos(a),-Math.sin(a),0,0,Math.sin(a),.5*Math.cos(a),0,0,0,0,1,0,0,0,0,1),o=s.multiply(n).multiply(r);e.setMatrix("lensStarMatrix",o),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new postProcess_PostProcess("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,texture_Texture.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 postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){let i=new MotionBlurPostProcess("HDRMotionBlur",e,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new postProcess_PostProcess("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,r=math_vector_Matrix.Identity(),s=math_vector_Matrix.Identity(),a=math_vector_Matrix.Identity(),n=math_vector_Vector2.Zero();this.motionBlurPostProcess.onApply=t=>{(a=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",r),r=a,n.x=this.motionBlurPostProcess.width,n.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",n),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRMotionBlur",()=>this.motionBlurPostProcess,!0))}_getDepthTexture(){if(this._scene.getEngine().getCaps().drawBuffersExtension){let e=this._scene.enableGeometryBufferRenderer();return e.getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;e<this._cameras.length;e++){let t=this._cameras[e];this.originalPostProcess&&this.originalPostProcess.dispose(t),this.screenSpaceReflectionPostProcess&&this.screenSpaceReflectionPostProcess.dispose(t),this.downSampleX4PostProcess&&this.downSampleX4PostProcess.dispose(t),this.brightPassPostProcess&&this.brightPassPostProcess.dispose(t),this.textureAdderPostProcess&&this.textureAdderPostProcess.dispose(t),this.volumetricLightPostProcess&&this.volumetricLightPostProcess.dispose(t),this.volumetricLightSmoothXPostProcess&&this.volumetricLightSmoothXPostProcess.dispose(t),this.volumetricLightSmoothYPostProcess&&this.volumetricLightSmoothYPostProcess.dispose(t),this.volumetricLightMergePostProces&&this.volumetricLightMergePostProces.dispose(t),this.volumetricLightFinalPostProcess&&this.volumetricLightFinalPostProcess.dispose(t),this.lensFlarePostProcess&&this.lensFlarePostProcess.dispose(t),this.lensFlareComposePostProcess&&this.lensFlareComposePostProcess.dispose(t);for(let e=0;e<this.luminanceDownSamplePostProcesses.length;e++)this.luminanceDownSamplePostProcesses[e].dispose(t);this.luminancePostProcess&&this.luminancePostProcess.dispose(t),this.hdrPostProcess&&this.hdrPostProcess.dispose(t),this.hdrFinalPostProcess&&this.hdrFinalPostProcess.dispose(t),this.depthOfFieldPostProcess&&this.depthOfFieldPostProcess.dispose(t),this.motionBlurPostProcess&&this.motionBlurPostProcess.dispose(t),this.fxaaPostProcess&&this.fxaaPostProcess.dispose(t);for(let e=0;e<this.blurHPostProcesses.length;e++)this.blurHPostProcesses[e].dispose(t);for(let e=0;e<this.blurVPostProcesses.length;e++)this.blurVPostProcesses[e].dispose(t)}this.originalPostProcess=null,this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.textureAdderPostProcess=null,this.textureAdderFinalPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.luminancePostProcess=null,this.hdrPostProcess=null,this.hdrFinalPostProcess=null,this.depthOfFieldPostProcess=null,this.motionBlurPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.luminanceDownSamplePostProcesses.length=0,this.blurHPostProcesses.length=0,this.blurVPostProcesses.length=0}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}serialize(){let e=decorators_SerializationHelper.Serialize(this);return this.sourceLight&&(e.sourceLightId=this.sourceLight.id),this.screenSpaceReflectionPostProcess&&(e.screenSpaceReflectionPostProcess=decorators_SerializationHelper.Serialize(this.screenSpaceReflectionPostProcess)),e.customType="StandardRenderingPipeline",e}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>new StandardRenderingPipeline(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&decorators_SerializationHelper.Parse(()=>r.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),r}};StandardRenderingPipeline.LuminanceSteps=6,__decorate([serialize()],StandardRenderingPipeline.prototype,"brightThreshold",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"blurWidth",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"horizontalBlur",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"exposure",null),__decorate([serializeAsTexture("lensTexture")],StandardRenderingPipeline.prototype,"lensTexture",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"volumetricLightCoefficient",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"volumetricLightPower",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"volumetricLightBlurScale",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"hdrMinimumLuminance",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"hdrDecreaseRate",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"hdrIncreaseRate",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"hdrAutoExposure",null),__decorate([serializeAsTexture("lensColorTexture")],StandardRenderingPipeline.prototype,"lensColorTexture",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"lensFlareStrength",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"lensFlareGhostDispersal",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"lensFlareHaloWidth",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"lensFlareDistortionStrength",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"lensFlareBlurWidth",void 0),__decorate([serializeAsTexture("lensStarTexture")],StandardRenderingPipeline.prototype,"lensStarTexture",void 0),__decorate([serializeAsTexture("lensFlareDirtTexture")],StandardRenderingPipeline.prototype,"lensFlareDirtTexture",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"depthOfFieldDistance",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"depthOfFieldBlurWidth",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"motionStrength",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"objectBasedMotionBlur",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"_ratio",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"BloomEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"DepthOfFieldEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"LensFlareEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"HDREnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"VLSEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"MotionBlurEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"fxaaEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"screenSpaceReflectionsEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"volumetricLightStepsCount",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"motionBlurSamples",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"samples",null),h["BABYLON.StandardRenderingPipeline"]=StandardRenderingPipeline;let ScreenSpaceReflections2Configuration=class ScreenSpaceReflections2Configuration{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}};let nW=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } +/** +param csOrigin Camera-space ray origin,which must be +within the view volume and must have z>0.01 and project within the valid screen rectangle +param csDirection Unit length camera-space ray direction +param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates +(**not** [-1,+1] normalized device coordinates). +param csZBuffer The camera-space Z buffer +param csZBufferSize Dimensions of csZBuffer +param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer +param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value +for clipping rays headed towards the camera +param stride Step in horizontal or vertical pixels between samples. This is a float +because integer math is slow on GPUs,but should be set to an integer>=1 +param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units +to conceal banding artifacts,plus the stride ray offset. +param maxSteps Maximum number of iterations. Higher gives better images but may be slow +param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss +param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. +1 is a reasonable value,depending on the scene you may need to set this value to 2 +param hitPixel Pixel coordinates of the first intersection with the scene +param numIterations number of iterations performed +param csHitPoint Camera space location of the ray hit +*/ +#define inline +bool traceScreenSpaceRay1( +vec3 csOrigin, +vec3 csDirection, +mat4 projectToPixelMatrix, +sampler2D csZBuffer, +vec2 csZBufferSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +sampler2D csZBackBuffer, +float csZBackSizeFactor, +#endif +float csZThickness, +float nearPlaneZ, +float stride, +float jitterFraction, +float maxSteps, +float maxRayTraceDistance, +float selfCollisionNumSkip, +out vec2 startPixel, +out vec2 hitPixel, +out vec3 csHitPoint, +out float numIterations +#ifdef SSRAYTRACE_DEBUG +,out vec3 debugColor +#endif +) +{ +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; +#else +float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)<nearPlaneZ ? (nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; +#endif +vec3 csEndPoint=csOrigin+csDirection*rayLength;hitPixel=vec2(-1.0,-1.0);vec4 H0=projectToPixelMatrix*vec4(csOrigin,1.0);vec4 H1=projectToPixelMatrix*vec4(csEndPoint,1.0);float k0=1.0/H0.w;float k1=1.0/H1.w;vec3 Q0=csOrigin*k0;vec3 Q1=csEndPoint*k1;vec2 P0=H0.xy*k0;vec2 P1=H1.xy*k1; +#ifdef SSRAYTRACE_CLIP_TO_FRUSTUM +float xMax=csZBufferSize.x-0.5,xMin=0.5,yMax=csZBufferSize.y-0.5,yMin=0.5;float alpha=0.0;if ((P1.y>yMax) || (P1.y<yMin)) {alpha=(P1.y-((P1.y>yMax) ? yMax : yMin))/(P1.y-P0.y);} +if ((P1.x>xMax) || (P1.x<xMin)) {alpha=max(alpha,(P1.x-((P1.x>xMax) ? xMax : xMin))/(P1.x-P0.x));} +P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); +#endif +P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)<abs(delta.y)) { +permute=true;delta=delta.yx;P0=P0.yx;P1=P1.yx; } +float stepDirection=sign(delta.x);float invdx=stepDirection/delta.x;vec2 dP=vec2(stepDirection,delta.y*invdx);vec3 dQ=(Q1-Q0)*invdx;float dk=(k1-k0)*invdx;float zMin=min(csEndPoint.z,csOrigin.z);float zMax=max(csEndPoint.z,csOrigin.z);dP*=stride; dQ*=stride; dk*=stride;P0+=dP*jitterFraction; Q0+=dQ*jitterFraction; k0+=dk*jitterFraction;vec4 pqk=vec4(P0,Q0.z,k0);vec4 dPQK=vec4(dP,dQ.z,dk);startPixel=permute ? P0.yx : P0.xy;float prevZMaxEstimate=csOrigin.z;float rayZMin=prevZMaxEstimate,rayZMax=prevZMaxEstimate;float sceneZMax=rayZMax+1e4;float end=P1.x*stepDirection;bool hit=false;float stepCount;for (stepCount=0.0;stepCount<=selfCollisionNumSkip || +(pqk.x*stepDirection)<=end && +stepCount<maxSteps && +!hit && +sceneZMax != 0.0; +pqk+=dPQK,++stepCount) +{hitPixel=permute ? pqk.yx : pqk.xy;rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;if (rayZMin>rayZMax) { +float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} +sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); +#else +hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); +#endif +#else +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); +#else +hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); +#endif +#endif +} +pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} +#ifdef SSRAYTRACE_ENABLE_REFINEMENT +if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || +(refinementStepCount<=stride*1.4) && +(rayZMax<sceneZMax) && (sceneZMax != 0.0);pqk+=dPQK,refinementStepCount+=1.0) +{rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;rayZMax=max(rayZMax,rayZMin);hitPixel=permute ? pqk.yx : pqk.xy;sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;} +pqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;} +#endif +Q0.xy+=dQ.xy*stepCount;Q0.z=pqk.z;csHitPoint=Q0/pqk.w;numIterations=stepCount+1.0; +#ifdef SSRAYTRACE_DEBUG +if (((pqk.x+dPQK.x)*stepDirection)>end) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} +#endif +return hit;} +/** +texCoord: in the [0,1] range +depth: depth in view space (range [znear,zfar]]) +*/ +vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +ndc.z=-projection[2].z-projection[3].z/depth; +#else +ndc.z=projection[2].z+projection[3].z/depth; +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +`;ShaderStore.IncludesShadersStore.screenSpaceRayTrace=nW;let nH=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSR_SUPPORTED +uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +uniform sampler2D backDepthSampler;uniform float backSizeFactor; +#endif +#ifdef SSR_USE_ENVIRONMENT_CUBE +uniform samplerCube envCubeSampler; +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; +#include<helperFunctions> +#include<pbrBRDFFunctions> +#include<screenSpaceRayTrace> +vec3 hash(vec3 a) +{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} +float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; +#ifdef SSR_ATTENUATE_SCREEN_BORDERS +vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE +attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS +attenuation*=1.0-(numIterations/maxSteps); +#endif +#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION +vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; +#endif +return attenuation;} +#endif +void main() +{ +#ifdef SSR_SUPPORTED +vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { +#ifdef SSR_USE_BLUR +gl_FragColor=vec4(0.); +#else +gl_FragColor=colorFull; +#endif +return;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpace(color); +#endif +vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; +float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal); +#ifdef SSR_USE_ENVIRONMENT_CUBE +vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); +#endif +#ifdef SSR_INVERTCUBICMAP +wReflectedVector.y*=-1.0; +#endif +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +wReflectedVector.z*=-1.0; +#endif +vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; +#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE +envColor=toLinearSpace(envColor); +#endif +#else +vec3 envColor=color; +#endif +float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; +#ifdef SSRAYTRACE_DEBUG +vec3 debugColor; +#endif +#ifdef SSR_ATTENUATE_FACING_CAMERA +reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); +#endif +if (reflectionAttenuation>0.0) { +#ifdef SSR_USE_BLUR +vec3 jitt=vec3(0.); +#else +float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; +#endif +vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); +rayHasHit=traceScreenSpaceRay1( +csPosition, +normalize(csReflectedVector+jitt), +projectionPixel, +depthSampler, +texSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +backDepthSampler, +backSizeFactor, +#endif +thickness, +nearPlaneZ, +stepSize, +jitter, +maxSteps, +maxDistance, +selfCollisionNumSkip, +startPixel, +hitPixel, +hitPoint, +numIterations +#ifdef SSRAYTRACE_DEBUG +,debugColor +#endif +);} +#ifdef SSRAYTRACE_DEBUG +gl_FragColor=vec4(debugColor,1.);return; +#endif +vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; +#ifdef SSR_INPUT_IS_GAMMA_SPACE +reflectedColor=toLinearSpace(reflectedColor); +#endif +reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} +#ifndef SSR_BLEND_WITH_FRESNEL +SSR*=fresnel; +#endif +#ifdef SSR_USE_BLUR +float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; +float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} +gl_FragColor=vec4(SSR,blur_radius/255.0); +#else +#ifdef SSR_BLEND_WITH_FRESNEL +vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#else +vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#endif +vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpace(finalColor); +#endif +gl_FragColor=vec4(finalColor,colorFull.a); +#endif +#else +gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); +#endif +} +`;ShaderStore.ShadersStore.screenSpaceReflection2PixelShader=nH;let nX=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) +{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} +void main() +{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} +float blurRadius=colorFull.a*255.0; +vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} +`;ShaderStore.ShadersStore.screenSpaceReflection2BlurPixelShader=nX;let nY=`uniform sampler2D textureSampler; +uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; +#include<helperFunctions> +#ifdef SSR_BLEND_WITH_FRESNEL +#include<pbrBRDFFunctions> +#include<screenSpaceRayTrace> +uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler; +#endif +void main() +{ +#ifdef SSRAYTRACE_DEBUG +gl_FragColor=texture2D(textureSampler,vUV); +#else +vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpace(color); +#endif +#ifdef SSR_BLEND_WITH_FRESNEL +vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#else +vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#endif +vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpace(finalColor); +#endif +gl_FragColor=vec4(finalColor,color.a); +#endif +} +`;ShaderStore.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader=nY;let nj=math_vector_Matrix.Compose(new math_vector_Vector3(.5,.5,.5),math_vector_Quaternion.Identity(),new math_vector_Vector3(.5,.5,.5)),nK=math_vector_Matrix.Compose(new math_vector_Vector3(.5,.5,1),math_vector_Quaternion.Identity(),new math_vector_Vector3(.5,.5,0));let SSRRenderingPipeline=class SSRRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{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;let 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(){let e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!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=r,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){let e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0,e.generateNormalsInWorldSpace&&console.error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"))}else{let e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty(),e.generateNormalsInWorldSpace&&console.error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!"))}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){let 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;let i=this._scene.getEngine(),r=this._prePassRenderer,s={width:i.getRenderWidth(),height:i.getRenderHeight()};if(r&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){let e=r.getRenderTarget();e&&e.textures&&(s=e.textures[r.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;let 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){this._isDirty=!0;return}this._isDirty=!1;let 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){let t=null===(e=this._cameras)||void 0===e?void 0:e[0];t&&(this._depthRendererCamera=t,this._depthRenderer=new DepthRenderer(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 postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRCombineRenderEffect,()=>this._blurCombinerPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;let e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==r)&&this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){let 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,r;for(let s=0;s<this._cameras.length;s++){let a=this._cameras[s];null===(e=this._ssrPostProcess)||void 0===e||e.dispose(a),null===(t=this._blurPostProcessX)||void 0===t||t.dispose(a),null===(i=this._blurPostProcessY)||void 0===i||i.dispose(a),null===(r=this._blurCombinerPostProcess)||void 0===r||r.dispose(a)}this._ssrPostProcess=null,this._blurPostProcessX=null,this._blurPostProcessY=null,this._blurCombinerPostProcess=null}_createSSRPostProcess(){this._ssrPostProcess=new postProcess_PostProcess("ssr","screenSpaceReflection2",["projection","invProjectionMatrix","view","invView","thickness","reflectionSpecularFalloffExponent","strength","stepSize","maxSteps","roughnessFactor","projectionPixel","nearPlaneZ","maxDistance","selfCollisionNumSkip","vReflectionPosition","vReflectionSize","backSizeFactor","reflectivityThreshold"],["textureSampler","normalSampler","reflectivitySampler","depthSampler","envCubeSampler","backDepthSampler"],1,null,this._textureType,this._scene.getEngine(),!1,"",this._textureType),this._updateEffectDefines(),this._ssrPostProcess.onApply=e=>{this._resizeDepthRenderer();let t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){let i=t.getTextureIndex(GeometryBufferRenderer.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){let t=i.getIndex(5),r=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[r])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));let r=this._scene.activeCamera;if(!r)return;let s=r.getViewMatrix(!0),a=r.getProjectionMatrix(!0);a.invertToRef(math_vector_TmpVectors.Matrix[0]),s.invertToRef(math_vector_TmpVectors.Matrix[1]),e.setMatrix("projection",a),e.setMatrix("view",s),e.setMatrix("invView",math_vector_TmpVectors.Matrix[1]),e.setMatrix("invProjectionMatrix",math_vector_TmpVectors.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",r.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);let n=this._getTextureSize();math_vector_Matrix.ScalingToRef(n.width,n.height,1,math_vector_TmpVectors.Matrix[2]),a.multiplyToRef(this._scene.getEngine().isWebGPU?nK:nj,math_vector_TmpVectors.Matrix[3]),math_vector_TmpVectors.Matrix[3].multiplyToRef(math_vector_TmpVectors.Matrix[2],math_vector_TmpVectors.Matrix[4]),e.setMatrix("projectionPixel",math_vector_TmpVectors.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 ScreenSpaceReflections2Configuration)}_createBlurAndCombinerPostProcesses(){let e=this._scene.getEngine();this._blurPostProcessX=new postProcess_PostProcess("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;let r=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/r,0)}),this._blurPostProcessY=new postProcess_PostProcess("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;let r=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/r)});let t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"],r="";this._debug&&(r+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(r+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(r+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(r+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(r+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new postProcess_PostProcess("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,r,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(e=>{var t;let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(r||i){if(r&&(null===(t=this._scene.activeCamera)||void 0===t?void 0:t._getFirstPostProcess())===this._ssrPostProcess){let t=r.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[r.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(i){let t=i.getTextureIndex(GeometryBufferRenderer.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(r){let t=r.getIndex(3);if(e.setTexture("reflectivitySampler",r.getRenderTarget().textures[t]),this.useFresnel){let t=r.getIndex(5),i=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[i]),e.setTexture("depthSampler",r.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();i.invertToRef(math_vector_TmpVectors.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",math_vector_TmpVectors.Matrix[0])}}}})}serialize(){let e=decorators_SerializationHelper.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return decorators_SerializationHelper.Parse(()=>new SSRRenderingPipeline(e._name,t,e._ratio),e,t,i)}};__decorate([serialize()],SSRRenderingPipeline.prototype,"samples",null),__decorate([serialize()],SSRRenderingPipeline.prototype,"maxDistance",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"step",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"thickness",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"strength",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"reflectionSpecularFalloffExponent",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"maxSteps",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"roughnessFactor",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"selfCollisionNumSkip",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"_reflectivityThreshold",void 0),__decorate([serialize("_ssrDownsample")],SSRRenderingPipeline.prototype,"_ssrDownsample",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"ssrDownsample",null),__decorate([serialize("blurDispersionStrength")],SSRRenderingPipeline.prototype,"_blurDispersionStrength",void 0),__decorate([serialize("blurDownsample")],SSRRenderingPipeline.prototype,"_blurDownsample",void 0),__decorate([serialize("enableSmoothReflections")],SSRRenderingPipeline.prototype,"_enableSmoothReflections",void 0),__decorate([serialize("environmentTexture")],SSRRenderingPipeline.prototype,"_environmentTexture",void 0),__decorate([serialize("environmentTextureIsProbe")],SSRRenderingPipeline.prototype,"_environmentTextureIsProbe",void 0),__decorate([serialize("attenuateScreenBorders")],SSRRenderingPipeline.prototype,"_attenuateScreenBorders",void 0),__decorate([serialize("attenuateIntersectionDistance")],SSRRenderingPipeline.prototype,"_attenuateIntersectionDistance",void 0),__decorate([serialize("attenuateIntersectionIterations")],SSRRenderingPipeline.prototype,"_attenuateIntersectionIterations",void 0),__decorate([serialize("attenuateFacingCamera")],SSRRenderingPipeline.prototype,"_attenuateFacingCamera",void 0),__decorate([serialize("attenuateBackfaceReflection")],SSRRenderingPipeline.prototype,"_attenuateBackfaceReflection",void 0),__decorate([serialize("clipToFrustum")],SSRRenderingPipeline.prototype,"_clipToFrustum",void 0),__decorate([serialize("useFresnel")],SSRRenderingPipeline.prototype,"_useFresnel",void 0),__decorate([serialize("enableAutomaticThicknessComputation")],SSRRenderingPipeline.prototype,"_enableAutomaticThicknessComputation",void 0),__decorate([serialize("backfaceDepthTextureDownsample")],SSRRenderingPipeline.prototype,"_backfaceDepthTextureDownsample",void 0),__decorate([serialize("backfaceForceDepthWriteTransparentMeshes")],SSRRenderingPipeline.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),__decorate([serialize("isEnabled")],SSRRenderingPipeline.prototype,"_isEnabled",void 0),__decorate([serialize("inputTextureColorIsInGammaSpace")],SSRRenderingPipeline.prototype,"_inputTextureColorIsInGammaSpace",void 0),__decorate([serialize("generateOutputInGammaSpace")],SSRRenderingPipeline.prototype,"_generateOutputInGammaSpace",void 0),__decorate([serialize("debug")],SSRRenderingPipeline.prototype,"_debug",void 0),h["BABYLON.SSRRenderingPipeline"]=SSRRenderingPipeline;let nq=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; +#if defined(HABLE_TONEMAPPING) +const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2; +#endif +float Luminance(vec3 c) +{return dot(c,vec3(0.22,0.707,0.071));} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 colour=texture2D(textureSampler,vUV).rgb; +#if defined(REINHARD_TONEMAPPING) +float lum=Luminance(colour.rgb); +float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); +colour*=scale/lum; +#elif defined(HABLE_TONEMAPPING) +colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; +#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) +colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; +#elif defined(PHOTOGRAPHIC_TONEMAPPING) +colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); +#endif +gl_FragColor=vec4(colour.rgb,1.0);}`;ShaderStore.ShadersStore.tonemapPixelShader=nq,function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(t7||(t7={}));let n$=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i<NUM_SAMPLES; i++) {tc-=deltaTexCoord;vec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;dataSample*=illuminationDecay*weight;color+=dataSample;illuminationDecay*=decay;} +vec4 realColor=texture2D(textureSampler,vUV);gl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4))); +#define CUSTOM_FRAGMENT_MAIN_END +} +`;ShaderStore.ShadersStore.volumetricLightScatteringPixelShader=n$;let nQ=`attribute vec3 position; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<instancesDeclaration> +uniform mat4 viewProjection;uniform vec2 depthValues; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +} +`;ShaderStore.ShadersStore.volumetricLightScatteringPassVertexShader=nQ;let nZ=`#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV; +#endif +#if defined(ALPHATEST) +uniform sampler2D diffuseSampler; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#if defined(ALPHATEST) +vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) +discard; +#endif +gl_FragColor=vec4(0.0,0.0,0.0,1.0);} +`;ShaderStore.ShadersStore.volumetricLightScatteringPassPixelShader=nZ;let VolumetricLightScatteringPostProcess=class VolumetricLightScatteringPostProcess extends postProcess_PostProcess{get useDiffuseColor(){return logger_Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){logger_Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,r,s=100,a=texture_Texture.BILINEAR_SAMPLINGMODE,n,o,l){var h,c;super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,a,n,o,"#define NUM_SAMPLES "+s),this._screenCoordinates=math_vector_Vector2.Zero(),this.customMeshPosition=math_vector_Vector3.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,n=(l=null!==(c=null!==(h=null==i?void 0:i.getScene())&&void 0!==h?h:l)&&void 0!==c?c:this._scene).getEngine(),this._viewPort=new math_viewport_Viewport(0,0,1,1).toGlobal(n.getRenderWidth(),n.getRenderHeight()),this.mesh=null!=r?r:VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh",l),this._createPass(l,t.passRatio||t),this.onActivate=e=>{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add(e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;let r=e.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);let s=null===(i=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(r,e,t);let a=[],n=[buffer_VertexBuffer.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&a.push("#define ALPHATEST"),r.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(n.push(buffer_VertexBuffer.UVKind),a.push("#define UV1")),r.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&(n.push(buffer_VertexBuffer.UV2Kind),a.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(n.push(buffer_VertexBuffer.MatricesIndicesKind),n.push(buffer_VertexBuffer.MatricesWeightsKind),a.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),a.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):a.push("#define NUM_BONE_INFLUENCERS 0"),t&&(a.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(n),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES"));let l=e._getDrawWrapper(void 0,!0),h=l.defines,c=a.join("\n");return h!==c&&l.setEffect(r.getScene().getEngine().createEffect("volumetricLightScatteringPass",n,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:r.numBoneInfluencers}),c),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){let 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){let i;let r=e.getEngine();this._volumetricLightScatteringRTT=new renderTargetTexture_RenderTargetTexture("volumetricLightScatteringMap",{width:r.getRenderWidth()*t,height:r.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;let s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);let renderSubMesh=e=>{var t;let i=e.getRenderingMesh(),r=e.getEffectiveMesh();if(this._meshExcluded(i))return;r._internalAbstractMeshDataInfo._isActiveIntermediate=!1;let s=e.getMaterial();if(!s)return;let a=i.getScene(),n=a.getEngine();n.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);let o=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;let l=n.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||i.hasThinInstances);if(this._isReady(e,l)){let h=null===(t=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[n.currentRenderPassId],c=e._getDrawWrapper();if(i!==this.mesh||c||(c=s._getDrawWrapper()),!c)return;let u=c.effect;if(n.enableEffect(c),l||i._bind(e,u,s.fillMode),i===this.mesh)s.bind(r.getWorldMatrix(),i);else if(h)h.bindForSubMesh(r.getWorldMatrix(),r,e);else{if(u.setMatrix("viewProjection",a.getTransformMatrix()),s&&s.needAlphaTesting()){let e=s.getAlphaTestTexture();u.setTexture("diffuseSampler",e),e&&u.setMatrix("diffuseMatrix",e.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&u.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}l&&i.hasThinInstances&&u.setMatrix("world",r.getWorldMatrix()),i._processRendering(r,e,u,material_Material.TriangleFillMode,o,l,(e,t)=>{e||u.setMatrix("world",t)})}},a=new math_color_Color4(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{i=e.clearColor,e.clearColor=a}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=i}),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){let i=e.subMeshes[t],s=i.getMaterial(),a=i.getRenderingMesh();if(!s)continue;let n=a._getInstancesRenderList(i._id,!!i.getReplacementMesh()),o=r.getCaps().instancedArrays&&(null!==n.visibleInstances[i._id]||a.hasThinInstances);if(!this._isReady(i,o))return!1}return!0},this._volumetricLightScatteringRTT.customRenderFunction=(t,i,r,s)=>{let a;let n=e.getEngine();if(s.length){for(n.setColorWrite(!1),a=0;a<s.length;a++)renderSubMesh(s.data[a]);n.setColorWrite(!0)}for(a=0;a<t.length;a++)renderSubMesh(t.data[a]);for(a=0;a<i.length;a++)renderSubMesh(i.data[a]);if(r.length){for(a=0;a<r.length;a++){let t=r.data[a],i=t.getBoundingInfo();i&&e.activeCamera&&(t._alphaIndex=t.getMesh().alphaIndex,t._distanceToCamera=i.boundingSphere.centerWorld.subtract(e.activeCamera.position).length())}let t=r.data.slice(0,r.length);for(t.sort((e,t)=>e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0),n.setAlphaMode(2),a=0;a<t.length;a++)renderSubMesh(t[a]);n.setAlphaMode(0)}}}_updateMeshScreenCoordinates(e){let t;let i=e.getTransformMatrix();t=this.useCustomMeshPosition?this.customMeshPosition:this.attachedNode?this.attachedNode.position:this.mesh.parent?this.mesh.getAbsolutePosition():this.mesh.position;let r=math_vector_Vector3.Project(t,math_vector_Matrix.Identity(),i,this._viewPort);this._screenCoordinates.x=r.x/this._viewPort.width,this._screenCoordinates.y=r.y/this._viewPort.height,this.invert&&(this._screenCoordinates.y=1-this._screenCoordinates.y)}static CreateDefaultMesh(e,t){let i=planeBuilder_CreatePlane(e,{size:1},t);i.billboardMode=abstractMesh_AbstractMesh.BILLBOARDMODE_ALL;let r=new standardMaterial_StandardMaterial(e+"Material",t);return r.emissiveColor=new math_color_Color3(1,1,1),i.material=r,i}};__decorate([serializeAsVector3()],VolumetricLightScatteringPostProcess.prototype,"customMeshPosition",void 0),__decorate([serialize()],VolumetricLightScatteringPostProcess.prototype,"useCustomMeshPosition",void 0),__decorate([serialize()],VolumetricLightScatteringPostProcess.prototype,"invert",void 0),__decorate([serializeAsMeshReference()],VolumetricLightScatteringPostProcess.prototype,"mesh",void 0),__decorate([serialize()],VolumetricLightScatteringPostProcess.prototype,"excludedMeshes",void 0),__decorate([serialize()],VolumetricLightScatteringPostProcess.prototype,"includedMeshes",void 0),__decorate([serialize()],VolumetricLightScatteringPostProcess.prototype,"exposure",void 0),__decorate([serialize()],VolumetricLightScatteringPostProcess.prototype,"decay",void 0),__decorate([serialize()],VolumetricLightScatteringPostProcess.prototype,"weight",void 0),__decorate([serialize()],VolumetricLightScatteringPostProcess.prototype,"density",void 0),h["BABYLON.VolumetricLightScatteringPostProcess"]=VolumetricLightScatteringPostProcess;let nJ=`precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform float curvature_ridge;uniform float curvature_valley; +#ifndef CURVATURE_OFFSET +#define CURVATURE_OFFSET 1 +#endif +float curvature_soft_clamp(float curvature,float control) +{if (curvature<0.5/control) +return curvature*(1.0-curvature*control);return 0.25/control;} +float calculate_curvature(ivec2 texel,float ridge,float valley) +{vec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;vec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;vec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;vec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;float normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));if (normal_diff<0.0) +return -2.0*curvature_soft_clamp(-normal_diff,valley);return 2.0*curvature_soft_clamp(normal_diff,ridge);} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ivec2 texel=ivec2(gl_FragCoord.xy);vec4 baseColor=texture2D(textureSampler,vUV);float curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);baseColor.rgb*=curvature+1.0;gl_FragColor=baseColor;}`;ShaderStore.ShadersStore.screenSpaceCurvaturePixelShader=nJ;let ScreenSpaceCurvaturePostProcess=class ScreenSpaceCurvaturePostProcess extends postProcess_PostProcess{getClassName(){return"ScreenSpaceCurvaturePostProcess"}constructor(e,t,i,r,s,a,n,o=0,l=!1){super(e,"screenSpaceCurvature",["curvature_ridge","curvature_valley"],["textureSampler","normalSampler"],i,r,s,a,n,void 0,o,void 0,null,l),this.ridge=1,this.valley=1,this._geometryBufferRenderer=t.enableGeometryBufferRenderer(),this._geometryBufferRenderer?(this._geometryBufferRenderer.generateNormalsInWorldSpace&&console.error("ScreenSpaceCurvaturePostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"),this.onApply=e=>{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));let t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):logger_Logger.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){let e=engineStore_EngineStore.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new ScreenSpaceCurvaturePostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};__decorate([serialize()],ScreenSpaceCurvaturePostProcess.prototype,"ridge",void 0),__decorate([serialize()],ScreenSpaceCurvaturePostProcess.prototype,"valley",void 0),h["BABYLON.ScreenSpaceCurvaturePostProcess"]=ScreenSpaceCurvaturePostProcess;let n0=`uniform vec4 color; +`;ShaderStore.IncludesShadersStore.boundingBoxRendererFragmentDeclaration=n0;let n1=`#ifdef WEBGL2 +uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +#else +layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; +#endif +`;ShaderStore.IncludesShadersStore.boundingBoxRendererUboDeclaration=n1;let n2=`#include<__decl__boundingBoxRendererFragment> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;ShaderStore.ShadersStore.boundingBoxRendererPixelShader=n2;let n3=`uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +`;ShaderStore.IncludesShadersStore.boundingBoxRendererVertexDeclaration=n3;let n4=`attribute vec3 position; +#include<__decl__boundingBoxRendererVertex> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec4 worldPos=world*vec4(position,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;ShaderStore.ShadersStore.boundingBoxRendererVertexShader=n4,Object.defineProperty(scene_Scene.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),scene_Scene.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new BoundingBoxRenderer(this)),this._boundingBoxRenderer},Object.defineProperty(abstractMesh_AbstractMesh.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});let BoundingBoxRenderer=class BoundingBoxRenderer{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_BOUNDINGBOXRENDERER,this.frontColor=new math_color_Color3(1,1,1),this.backColor=new math_color_Color3(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new observable_Observable,this.onAfterBoxRenderingObservable=new observable_Observable,this.onResourcesReadyObservable=new observable_Observable,this.enabled=!0,this.renderList=new SmartArray(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new UniformBuffer(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new UniformBuffer(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(sceneComponent_SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){let i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){let t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new shaderMaterial_ShaderMaterial("colorShader",this.scene,"boundingBoxRenderer",{attributes:[buffer_VertexBuffer.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new shaderMaterial_ShaderMaterial("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[buffer_VertexBuffer.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};let e=this.scene.getEngine(),t=CreateBoxVertexData({size:1});this._vertexBuffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(e,t.positions,buffer_VertexBuffer.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){let 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(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(0===this.renderList.length||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;let r=this.scene.getEngine();r.setDepthWrite(!1);let s=this.scene.getTransformMatrix();for(let a=0;a<this.renderList.length;a++){let n=this.renderList.data[a];if(n._tag!==e)continue;this._createWrappersForBoundingBox(n),this.onBeforeBoxRenderingObservable.notifyObservers(n);let o=n.minimum,l=n.maximum,h=l.subtract(o),c=o.add(h.scale(.5)),u=math_vector_Matrix.Scaling(h.x,h.y,h.z).multiply(math_vector_Matrix.Translation(c.x,c.y,c.z)).multiply(n.getWorldMatrix()),d=r.useReverseDepthBuffer;if(this.showBackLines){let e=null!==(t=n._drawWrapperBack)&&void 0!==t?t:this._colorShader._getDrawWrapper();this._colorShader._preBind(e),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),d?r.setDepthFunctionToLessOrEqual():r.setDepthFunctionToGreaterOrEqual(),this._uniformBufferBack.bindToEffect(e.effect,"BoundingBoxRenderer"),this._uniformBufferBack.updateColor4("color",this.backColor,1),this._uniformBufferBack.updateMatrix("world",u),this._uniformBufferBack.updateMatrix("viewProjection",s),this._uniformBufferBack.update(),r.drawElementsType(material_Material.LineListDrawMode,0,24)}let _=null!==(i=n._drawWrapperFront)&&void 0!==i?i:this._colorShader._getDrawWrapper();this._colorShader._preBind(_),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),d?r.setDepthFunctionToGreater():r.setDepthFunctionToLess(),this._uniformBufferFront.bindToEffect(_.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateColor4("color",this.frontColor,1),this._uniformBufferFront.updateMatrix("world",u),this._uniformBufferFront.updateMatrix("viewProjection",s),this._uniformBufferFront.update(),r.drawElementsType(material_Material.LineListDrawMode,0,24),this.onAfterBoxRenderingObservable.notifyObservers(n)}this._colorShader.unbind(),r.setDepthFunctionToLessOrEqual(),r.setDepthWrite(!0)}_createWrappersForBoundingBox(e){if(!e._drawWrapperFront){let t=this.scene.getEngine();e._drawWrapperFront=new drawWrapper_DrawWrapper(t),e._drawWrapperBack=new drawWrapper_DrawWrapper(t),e._drawWrapperFront.setEffect(this._colorShader.getEffect()),e._drawWrapperBack.setEffect(this._colorShader.getEffect())}}renderOcclusionBoundingBox(e){let t=this.scene.getEngine();void 0===this._renderPassIdForOcclusionQuery&&(this._renderPassIdForOcclusionQuery=t.createRenderPassId("Render pass for occlusion query"));let i=t.currentRenderPassId;t.currentRenderPassId=this._renderPassIdForOcclusionQuery,this._prepareResources();let r=e.subMeshes[0];if(!this._colorShaderForOcclusionQuery.isReady(e,void 0,r)||!e.hasBoundingInfo){t.currentRenderPassId=i;return}this._fillIndexBuffer||(this._fillIndexBuffer=t.createIndexBuffer(this._fillIndexData));let s=t.useReverseDepthBuffer;t.setDepthWrite(!1),t.setColorWrite(!1);let a=e.getBoundingInfo().boundingBox,n=a.minimum,o=a.maximum,l=o.subtract(n),h=n.add(l.scale(.5)),c=math_vector_Matrix.Scaling(l.x,l.y,l.z).multiply(math_vector_Matrix.Translation(h.x,h.y,h.z)).multiply(a.getWorldMatrix()),u=r._drawWrapper;this._colorShaderForOcclusionQuery._preBind(u),t.bindBuffers(this._vertexBuffers,this._fillIndexBuffer,u.effect),s?t.setDepthFunctionToGreater():t.setDepthFunctionToLess(),this.scene.resetCachedMaterial(),this._uniformBufferFront.bindToEffect(u.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateMatrix("world",c),this._uniformBufferFront.updateMatrix("viewProjection",this.scene.getTransformMatrix()),this._uniformBufferFront.update(),t.drawElementsType(material_Material.TriangleFillMode,0,36),this._colorShaderForOcclusionQuery.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0),t.setColorWrite(!0),t.currentRenderPassId=i}dispose(){if(void 0!==this._renderPassIdForOcclusionQuery&&(this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery),this._renderPassIdForOcclusionQuery=void 0),!this._colorShader)return;this.onBeforeBoxRenderingObservable.clear(),this.onAfterBoxRenderingObservable.clear(),this.onResourcesReadyObservable.clear(),this.renderList.dispose(),this._colorShader.dispose(),this._colorShaderForOcclusionQuery.dispose(),this._uniformBufferFront.dispose(),this._uniformBufferBack.dispose();let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&(e.dispose(),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=null),this.scene.getEngine()._releaseBuffer(this._indexBuffer),this._fillIndexBuffer&&(this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer),this._fillIndexBuffer=null)}};scene_Scene.prototype.enableDepthRenderer=function(e,t=!1,i=!1,r=3,s=!1){if(!(e=e||this.activeCamera))throw"No camera available to enable depth renderer";if(this._depthRenderer||(this._depthRenderer={}),!this._depthRenderer[e.id]){let a=!!this.getEngine().getCaps().textureFloatRender,n=0;n=!this.getEngine().getCaps().textureHalfFloatRender||i&&a?a?1:0:2,this._depthRenderer[e.id]=new DepthRenderer(this,n,e,t,r,s)}return this._depthRenderer[e.id]},scene_Scene.prototype.disableDepthRenderer=function(e){(e=e||this.activeCamera)&&this._depthRenderer&&this._depthRenderer[e.id]&&this._depthRenderer[e.id].dispose()};let DepthRendererSceneComponent=class DepthRendererSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_DEPTHRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER,this,this._gatherRenderTargets),this.scene._gatherActiveCameraRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER,this,this._gatherActiveCameraRenderTargets)}rebuild(){}dispose(){for(let e in this.scene._depthRenderer)this.scene._depthRenderer[e].dispose()}_gatherRenderTargets(e){if(this.scene._depthRenderer)for(let t in this.scene._depthRenderer){let i=this.scene._depthRenderer[t];i.enabled&&!i.useOnlyInActiveCamera&&e.push(i.getDepthMap())}}_gatherActiveCameraRenderTargets(e){if(this.scene._depthRenderer)for(let t in this.scene._depthRenderer){let i=this.scene._depthRenderer[t];i.enabled&&i.useOnlyInActiveCamera&&this.scene.activeCamera.id===t&&e.push(i.getDepthMap())}}};DepthRenderer._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_DEPTHRENDERER);t||(t=new DepthRendererSceneComponent(e),e._addComponent(t))};let n5=`precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( +frontColor.rgb+alphaMultiplier*backColor.rgb, +frontColor.a+backColor.a +);}`;ShaderStore.ShadersStore.oitFinalPixelShader=n5;let n6=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { +discard;}}`;ShaderStore.ShadersStore.oitBackBlendPixelShader=n6;let DepthPeelingEffectConfiguration=class DepthPeelingEffectConfiguration{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}};let DepthPeelingRenderer=class DepthPeelingRenderer{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){let 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 SmartArray(10),this._excludedSubMeshes=new SmartArray(10),this._excludedMeshes=[],this._colorCache=[new math_color_Color4(DepthPeelingRenderer._DEPTH_CLEAR_VALUE,DepthPeelingRenderer._DEPTH_CLEAR_VALUE,0,0),new math_color_Color4(-DepthPeelingRenderer._MIN_DEPTH,DepthPeelingRenderer._MAX_DEPTH,0,0),new math_color_Color4(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){logger_Logger.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let e=0;e<this._layoutCacheFormat.length;++e)this._layoutCache[e]=this._engine.buildTextureLayout(this._layoutCacheFormat[e]);this._renderPassIds=[],this.useRenderPasses=!1,this._prePassEffectConfiguration=new DepthPeelingEffectConfiguration,this._createTextures(),this._createEffects()}_createRenderPassIds(){if(this._releaseRenderPassIds(),this._useRenderPasses)for(let e=0;e<this._passCount+1;++e)this._renderPassIds[e]||(this._renderPassIds[e]=this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${e}`))}_releaseRenderPassIds(){for(let e=0;e<this._renderPassIds.length;++e)this._engine.releaseRenderPassId(this._renderPassIds[e]);this._renderPassIds=[]}_createTextures(){let e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()};this._depthMrts=[new MultiRenderTarget("depthPeelingDepth0",e,3,this._scene),new MultiRenderTarget("depthPeelingDepth1",e,3,this._scene)],this._colorMrts=[new MultiRenderTarget("depthPeelingColor0",e,2,this._scene,{generateDepthBuffer:!1}),new MultiRenderTarget("depthPeelingColor1",e,2,this._scene,{generateDepthBuffer:!1})],this._blendBackMrt=new MultiRenderTarget("depthPeelingBack",e,1,this._scene,{generateDepthBuffer:!1}),this._outputRT=new renderTargetTexture_RenderTargetTexture("depthPeelingOutput",e,this._scene,!1);let t=[{format:7,samplingMode:1,type:this._engine.getCaps().textureFloatLinearFiltering?1:2,label:"DepthPeelingRenderer-DepthTexture"},{format:5,samplingMode:1,type:2,label:"DepthPeelingRenderer-ColorTexture"}];for(let i=0;i<2;i++){let r=this._engine._createInternalTexture(e,t[0],!1),s=this._engine._createInternalTexture(e,t[1],!1),a=this._engine._createInternalTexture(e,t[1],!1);this._depthMrts[i].setInternalTexture(r,0),this._depthMrts[i].setInternalTexture(s,1),this._depthMrts[i].setInternalTexture(a,2),this._colorMrts[i].setInternalTexture(s,0),this._colorMrts[i].setInternalTexture(a,1),this._thinTextures.push(new thinTexture_ThinTexture(r),new thinTexture_ThinTexture(s),new thinTexture_ThinTexture(a))}}_disposeTextures(){for(let e=0;e<this._thinTextures.length;e++)6!==e&&this._thinTextures[e].dispose();for(let e=0;e<2;e++)this._depthMrts[e].dispose(!0),this._colorMrts[e].dispose(!0),this._blendBackMrt.dispose(!0);this._outputRT.dispose(),this._thinTextures=[],this._colorMrts=[],this._depthMrts=[]}_updateTextures(){return(this._depthMrts[0].getSize().width!==this._engine.getRenderWidth()||this._depthMrts[0].getSize().height!==this._engine.getRenderHeight())&&(this._disposeTextures(),this._createTextures()),this._updateTextureReferences()}_updateTextureReferences(){var e;let t=this._scene.prePassRenderer;if(!t)return!1;let i=t.getIndex(4),r=(null===(e=t.defaultRT.textures)||void 0===e?void 0:e.length)?t.defaultRT.textures[i].getInternalTexture():null;return!!r&&(this._blendBackTexture!==r&&(this._blendBackTexture=r,this._blendBackMrt.setInternalTexture(this._blendBackTexture,0),this._thinTextures[6]&&this._thinTextures[6].dispose(),this._thinTextures[6]=new thinTexture_ThinTexture(this._blendBackTexture),t.defaultRT.renderTarget._shareDepth(this._depthMrts[0].renderTarget)),!0)}_createEffects(){this._blendBackEffectWrapper=new EffectWrapper({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._blendBackEffectWrapperPingPong=new EffectWrapper({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._finalEffectWrapper=new EffectWrapper({fragmentShader:"oitFinal",useShaderStore:!0,engine:this._engine,samplerNames:["uFrontColor","uBackColor"],uniformNames:[]}),this._effectRenderer=new EffectRenderer(this._engine)}setPrePassRenderer(e){e.addEffectConfiguration(this._prePassEffectConfiguration)}bind(e){e.setTexture("oitDepthSampler",this._thinTextures[3*this._currentPingPongState]),e.setTexture("oitFrontColorSampler",this._thinTextures[3*this._currentPingPongState+1])}_renderSubMeshes(e){let t;this._useRenderPasses&&(t={});for(let i=0;i<e.length;i++){let r;let s=e.data[i].getMaterial(),a=!0,n=!1,o=e.data[i],l=!1;if(this._useRenderPasses&&(l=!(r=o._getDrawWrapper())),s&&(a=s.allowShaderHotSwapping,n=s.backFaceCulling,s.allowShaderHotSwapping=!1,s.backFaceCulling=!1),o.render(!1),l&&(r=o._getDrawWrapper()).materialContext){let e=t[r.materialContext.uniqueId];e||(e=t[r.materialContext.uniqueId]=this._engine.createMaterialContext()),o._getDrawWrapper().materialContext=e}s&&(s.allowShaderHotSwapping=a,s.backFaceCulling=n)}}_finalCompose(e){var t;let i=null===(t=this._scene.prePassRenderer)||void 0===t?void 0:t.setCustomOutput(this._outputRT);i?this._engine.bindFramebuffer(this._outputRT.renderTarget):this._engine.restoreDefaultFramebuffer(),this._engine.setAlphaMode(0),this._engine.applyStates(),this._engine.enableEffect(this._finalEffectWrapper._drawWrapper),this._finalEffectWrapper.effect.setTexture("uFrontColor",this._thinTextures[3*e+1]),this._finalEffectWrapper.effect.setTexture("uBackColor",this._thinTextures[6]),this._effectRenderer.render(this._finalEffectWrapper)}render(e){if(this._candidateSubMeshes.length=0,this._excludedSubMeshes.length=0,!this._blendBackEffectWrapper.effect.isReady()||!this._blendBackEffectWrapperPingPong.effect.isReady()||!this._finalEffectWrapper.effect.isReady()||!this._updateTextures())return this._excludedSubMeshes;this._scene.activeCamera&&this._engine.setViewport(this._scene.activeCamera.viewport);for(let t=0;t<e.length;t++){let i=e.data[t],r=i.getMaterial(),s=r&&i.getRenderingMesh()._getRenderingFillMode(r.fillMode);r&&(s===material_Material.TriangleFanDrawMode||s===material_Material.TriangleFillMode||s===material_Material.TriangleStripDrawMode)&&-1===this._excludedMeshes.indexOf(i.getMesh().uniqueId)?this._candidateSubMeshes.push(i):this._excludedSubMeshes.push(i)}if(!this._candidateSubMeshes.length)return this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._finalCompose(1),this._excludedSubMeshes;let t=this._engine.currentRenderPassId;this._scene.prePassRenderer._enabled=!1,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[0]),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[1],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaMode(11),this._engine.setAlphaEquation(3),this._engine.depthCullingState.depthMask=!1,this._engine.depthCullingState.depthTest=!0,this._engine.applyStates(),this._currentPingPongState=1,this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._scene.resetCachedMaterial();let i=0,r=0;for(let e=0;e<this._passCount;e++){r=1-(i=e%2),this._currentPingPongState=i,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[e+1]),this._scene.activeCamera&&this._engine.setViewport(this._scene.activeCamera.viewport),this._engine.bindFramebuffer(this._depthMrts[r].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[r].renderTarget),this._engine.bindFramebuffer(this._colorMrts[r].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[r].renderTarget),this._engine.bindFramebuffer(this._depthMrts[r].renderTarget),this._engine.bindAttachments(this._layoutCache[2]),this._engine.setAlphaMode(11),this._engine.setAlphaEquation(3),this._engine.depthCullingState.depthTest=!1,this._engine.applyStates(),this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[r].renderTarget),this._scene.resetCachedMaterial(),this._engine.bindFramebuffer(this._blendBackMrt.renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaEquation(0),this._engine.setAlphaMode(17),this._engine.applyStates();let t=0!==r&&this._useRenderPasses?this._blendBackEffectWrapperPingPong:this._blendBackEffectWrapper;this._engine.enableEffect(t._drawWrapper),t.effect.setTexture("uBackColor",this._thinTextures[3*r+2]),this._effectRenderer.render(t),this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget)}return this._engine.currentRenderPassId=t,this._finalCompose(r),this._scene.prePassRenderer._enabled=!0,this._engine.depthCullingState.depthMask=!0,this._engine.depthCullingState.depthTest=!0,this._excludedSubMeshes}dispose(){this._disposeTextures(),this._blendBackEffectWrapper.dispose(),this._finalEffectWrapper.dispose(),this._effectRenderer.dispose(),this._releaseRenderPassIds()}};DepthPeelingRenderer._DEPTH_CLEAR_VALUE=-99999,DepthPeelingRenderer._MIN_DEPTH=0,DepthPeelingRenderer._MAX_DEPTH=1,Object.defineProperty(scene_Scene.prototype,"depthPeelingRenderer",{get:function(){if(!this._depthPeelingRenderer){let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_DEPTHPEELINGRENDERER);e||(e=new DepthPeelingSceneComponent(this),this._addComponent(e))}return this._depthPeelingRenderer},set:function(e){this._depthPeelingRenderer=e},enumerable:!0,configurable:!0}),Object.defineProperty(scene_Scene.prototype,"useOrderIndependentTransparency",{get:function(){return this._useOrderIndependentTransparency},set:function(e){var t;this._useOrderIndependentTransparency!==e&&(this._useOrderIndependentTransparency=e,this.markAllMaterialsAsDirty(63),null===(t=this.prePassRenderer)||void 0===t||t.markAsDirty())},enumerable:!0,configurable:!0});let DepthPeelingSceneComponent=class DepthPeelingSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_DEPTHPEELINGRENDERER,this.scene=e,e.depthPeelingRenderer=new DepthPeelingRenderer(e)}register(){}rebuild(){}dispose(){var e;null===(e=this.scene.depthPeelingRenderer)||void 0===e||e.dispose(),this.scene.depthPeelingRenderer=null}};let n8=`#include<clipPlaneFragmentDeclaration> +uniform vec4 color; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;ShaderStore.ShadersStore.linePixelShader=n8;let n7=`#include<instancesDeclaration> +#include<clipPlaneVertexDeclaration> +attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include<instancesVertex> +mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=finalWorld*vec4(position,1.0); +#include<clipPlaneVertex> +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.lineVertexShader=n7,abstractMesh_AbstractMesh.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},abstractMesh_AbstractMesh.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new EdgesRenderer(this,e,t,!0,i),this},Object.defineProperty(abstractMesh_AbstractMesh.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),LinesMesh.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new LineEdgesRenderer(this,e,t),this},InstancedLinesMesh.prototype.enableEdgesRendering=function(e=.95,t=!1){return LinesMesh.prototype.enableEdgesRendering.apply(this,arguments),this};let FaceAdjacencies=class FaceAdjacencies{constructor(){this.edges=[],this.edgesConnectedCount=0}};let EdgesRenderer=class EdgesRenderer{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){let t=new shaderMaterial_ShaderMaterial("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,r=!0,s){var a;this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=[],this._linesNormals=[],this._linesIndices=[],this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new SmartArray(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=null!=s?s:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new drawWrapper_DrawWrapper(e.getEngine())),this._prepareRessources(),r&&(null===(a=null==s?void 0:s.useAlternateEdgeFinder)||void 0===a||a?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=EdgesRenderer._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[buffer_VertexBuffer.PositionKind];e&&e._rebuild(),(e=this._buffers[buffer_VertexBuffer.NormalKind])&&e._rebuild();let t=this._source.getScene(),i=t.getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[buffer_VertexBuffer.PositionKind];t&&(t.dispose(),this._buffers[buffer_VertexBuffer.PositionKind]=null),(t=this._buffers[buffer_VertexBuffer.NormalKind])&&(t.dispose(),this._buffers[buffer_VertexBuffer.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,r,s){return e===i&&t===r||e===r&&t===i?0:e===r&&t===s||e===s&&t===r?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,s){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)?1:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)?2:-1}_checkEdge(e,t,i,r,s){let a;if(void 0===t)a=!0;else{let r=math_vector_Vector3.Dot(i[e],i[t]);a=r<this._epsilon}a&&this.createLine(r,s,this._linesPositions.length/3)}createLine(e,t,i){this._linesPositions.push(e.x,e.y,e.z,e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z),this._linesNormals.push(t.x,t.y,t.z,-1,t.x,t.y,t.z,1,e.x,e.y,e.z,-1,e.x,e.y,e.z,1),this._linesIndices.push(i,i+1,i+2,i,i+2,i+3)}_tessellateTriangle(e,t,i,r){let makePointList=(e,t,i)=>{i>=0&&t.push(i);for(let i=0;i<e.length;++i)t.push(e[i][0])},s=0;e[1].length>=e[0].length&&e[1].length>=e[2].length?s=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(s=2);for(let t=0;t<3;++t)t===s?e[t].sort((e,t)=>e[1]<t[1]?-1:e[1]>t[1]?1:0):e[t].sort((e,t)=>e[1]>t[1]?-1:e[1]<t[1]?1:0);let a=[],n=[];makePointList(e[s],a,-1);let o=a.length;for(let a=s+2;a>=s+1;--a)makePointList(e[a%3],n,a!==s+2?r[i[t+(a+1)%3]]:-1);let l=n.length;i.push(r[i[t+s]],a[0],n[0]),i.push(r[i[t+(s+1)%3]],n[l-1],a[o-1]);let h=o<=l,c=h?o:l,u=h?l:o,d=h?o-1:l-1,_=h?0:1,p=o+l-2,f=0,m=0,g=h?a:n,v=h?n:a,x=0;for(;p-- >0;){let e;_?i.push(g[f],v[m]):i.push(v[m],g[f]),(x+=c)>=u&&f<d?(e=g[++f],x-=u):e=v[++m],i.push(e)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3}_generateEdgesLinesAlternate(){var e,t,i,r,s,a,n,o,l,h;let c=this._source.getVerticesData(buffer_VertexBuffer.PositionKind),u=this._source.getIndices();if(!u||!c)return;Array.isArray(u)||(u=Array.from(u));let d=null===(t=null===(e=this._options)||void 0===e?void 0:e.useFastVertexMerger)||void 0===t||t,_=d?Math.round(-Math.log(null!==(r=null===(i=this._options)||void 0===i?void 0:i.epsilonVertexMerge)&&void 0!==r?r:1e-6)/Math.log(10)):null!==(a=null===(s=this._options)||void 0===s?void 0:s.epsilonVertexMerge)&&void 0!==a?a:1e-6,p=[],f=[];if(d){let e={};for(let t=0;t<c.length;t+=3){let i=c[t+0],r=c[t+1],s=c[t+2],a=i.toFixed(_)+"|"+r.toFixed(_)+"|"+s.toFixed(_);if(void 0!==e[a])p.push(e[a]);else{let i=t/3;e[a]=i,p.push(i),f.push(i)}}}else for(let e=0;e<c.length;e+=3){let t=c[e+0],i=c[e+1],r=c[e+2],s=!1;for(let a=0;a<e&&!s;a+=3){let e=c[a+0],n=c[a+1],o=c[a+2];if(Math.abs(t-e)<_&&Math.abs(i-n)<_&&Math.abs(r-o)<_){p.push(a/3),s=!0;break}}s||(p.push(e/3),f.push(e/3))}if(null===(n=this._options)||void 0===n?void 0:n.applyTessellation){let e=null!==(l=null===(o=this._options)||void 0===o?void 0:o.epsilonVertexAligned)&&void 0!==l?l:1e-6,t=[];for(let i=0;i<u.length;i+=3){let r;for(let s=0;s<3;++s){let a=p[u[i+s]],n=p[u[i+(s+1)%3]],o=p[u[i+(s+2)%3]];if(a===n)continue;let l=c[3*a+0],h=c[3*a+1],d=c[3*a+2],_=c[3*n+0],m=c[3*n+1],g=c[3*n+2],v=Math.sqrt((_-l)*(_-l)+(m-h)*(m-h)+(g-d)*(g-d));for(let u=0;u<f.length-1;u++){let p=f[u];if(p===a||p===n||p===o)continue;let x=c[3*p+0],b=c[3*p+1],T=c[3*p+2],S=Math.sqrt((x-l)*(x-l)+(b-h)*(b-h)+(T-d)*(T-d)),C=Math.sqrt((x-_)*(x-_)+(b-m)*(b-m)+(T-g)*(T-g));Math.abs(S+C-v)<e&&(r||(r={index:i,edgesPoints:[[],[],[]]},t.push(r)),r.edgesPoints[s].push([p,S]))}}}for(let e=0;e<t.length;++e){let i=t[e];this._tessellateTriangle(i.edgesPoints,i.index,u,p)}t.length=0}let m={};for(let e=0;e<u.length;e+=3){let t;for(let i=0;i<3;++i){let r=p[u[e+i]],s=p[u[e+(i+1)%3]],a=p[u[e+(i+2)%3]];if(r===s||(r===a||s===a)&&(null===(h=this._options)||void 0===h?void 0:h.removeDegeneratedTriangles))continue;if(math_vector_TmpVectors.Vector3[0].copyFromFloats(c[3*r+0],c[3*r+1],c[3*r+2]),math_vector_TmpVectors.Vector3[1].copyFromFloats(c[3*s+0],c[3*s+1],c[3*s+2]),math_vector_TmpVectors.Vector3[2].copyFromFloats(c[3*a+0],c[3*a+1],c[3*a+2]),t||(math_vector_TmpVectors.Vector3[1].subtractToRef(math_vector_TmpVectors.Vector3[0],math_vector_TmpVectors.Vector3[3]),math_vector_TmpVectors.Vector3[2].subtractToRef(math_vector_TmpVectors.Vector3[1],math_vector_TmpVectors.Vector3[4]),(t=math_vector_Vector3.Cross(math_vector_TmpVectors.Vector3[3],math_vector_TmpVectors.Vector3[4])).normalize()),r>s){let e=r;r=s,s=e}let n=r+"_"+s,o=m[n];if(o){if(!o.done){let e=math_vector_Vector3.Dot(t,o.normal);e<this._epsilon&&this.createLine(math_vector_TmpVectors.Vector3[0],math_vector_TmpVectors.Vector3[1],this._linesPositions.length/3),o.done=!0}}else m[n]={normal:t,done:!1,index:e,i:i}}}for(let e in m){let t=m[e];if(!t.done){let e=p[u[t.index+t.i]],i=p[u[t.index+(t.i+1)%3]];math_vector_TmpVectors.Vector3[0].copyFromFloats(c[3*e+0],c[3*e+1],c[3*e+2]),math_vector_TmpVectors.Vector3[1].copyFromFloats(c[3*i+0],c[3*i+1],c[3*i+2]),this.createLine(math_vector_TmpVectors.Vector3[0],math_vector_TmpVectors.Vector3[1],this._linesPositions.length/3)}}let g=this._source.getScene().getEngine();this._buffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(g,this._linesPositions,buffer_VertexBuffer.PositionKind,!1),this._buffers[buffer_VertexBuffer.NormalKind]=new buffer_VertexBuffer(g,this._linesNormals,buffer_VertexBuffer.NormalKind,!1,!1,4),this._buffersForInstances[buffer_VertexBuffer.PositionKind]=this._buffers[buffer_VertexBuffer.PositionKind],this._buffersForInstances[buffer_VertexBuffer.NormalKind]=this._buffers[buffer_VertexBuffer.NormalKind],this._ib=g.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}_generateEdgesLines(){let e,t;let i=this._source.getVerticesData(buffer_VertexBuffer.PositionKind),r=this._source.getIndices();if(!r||!i)return;let s=[],a=[];for(e=0;e<r.length;e+=3){t=new FaceAdjacencies;let n=r[e],o=r[e+1],l=r[e+2];t.p0=new math_vector_Vector3(i[3*n],i[3*n+1],i[3*n+2]),t.p1=new math_vector_Vector3(i[3*o],i[3*o+1],i[3*o+2]),t.p2=new math_vector_Vector3(i[3*l],i[3*l+1],i[3*l+2]);let h=math_vector_Vector3.Cross(t.p1.subtract(t.p0),t.p2.subtract(t.p1));h.normalize(),a.push(h),s.push(t)}for(e=0;e<s.length;e++){t=s[e];for(let i=e+1;i<s.length;i++){let a=s[i];if(3===t.edgesConnectedCount)break;if(3===a.edgesConnectedCount)continue;let n=r[3*i],o=r[3*i+1],l=r[3*i+2];for(let s=0;s<3;s++){let h=0;if(void 0===t.edges[s]){switch(s){case 0:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(t.p0,t.p1,a.p0,a.p1,a.p2):this._processEdgeForAdjacencies(r[3*e],r[3*e+1],n,o,l);break;case 1:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(t.p1,t.p2,a.p0,a.p1,a.p2):this._processEdgeForAdjacencies(r[3*e+1],r[3*e+2],n,o,l);break;case 2:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(t.p2,t.p0,a.p0,a.p1,a.p2):this._processEdgeForAdjacencies(r[3*e+2],r[3*e],n,o,l)}if(-1!==h&&(t.edges[s]=i,a.edges[h]=e,t.edgesConnectedCount++,a.edgesConnectedCount++,3===t.edgesConnectedCount))break}}}}for(e=0;e<s.length;e++){let t=s[e];this._checkEdge(e,t.edges[0],a,t.p0,t.p1),this._checkEdge(e,t.edges[1],a,t.p1,t.p2),this._checkEdge(e,t.edges[2],a,t.p2,t.p0)}let n=this._source.getScene().getEngine();this._buffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(n,this._linesPositions,buffer_VertexBuffer.PositionKind,!1),this._buffers[buffer_VertexBuffer.NormalKind]=new buffer_VertexBuffer(n,this._linesNormals,buffer_VertexBuffer.NormalKind,!1,!1,4),this._buffersForInstances[buffer_VertexBuffer.PositionKind]=this._buffers[buffer_VertexBuffer.PositionKind],this._buffersForInstances[buffer_VertexBuffer.NormalKind]=this._buffers[buffer_VertexBuffer.NormalKind],this._ib=n.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}isReady(){return this._lineShader.isReady(this._source,this._source.hasInstances&&this.customInstances.length>0||this._source.hasThinInstances)}render(){let e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}let i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances,s=0;if(r){if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){let e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!e.isFrozen){let t=0;for(let i=0;i<s;++i)this.customInstances.data[i].copyToArray(e.instancesData,t),t+=16;e.instancesBuffer.updateDirectly(e.instancesData,0,s)}}else s=this._source.thinInstanceCount}let a=e.getEngine();this._lineShader._preBind(),1!==this._source.edgesColor.a?a.setAlphaMode(2):a.setAlphaMode(0),a.bindBuffers(r?this._buffersForInstances:this._buffers,this._ib,this._lineShader.getEffect()),e.resetCachedMaterial(),this._lineShader.setColor4("color",this._source.edgesColor),e.activeCamera.mode===camera_Camera.ORTHOGRAPHIC_CAMERA?this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForOrthographic):this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForPerspective),this._lineShader.setFloat("aspectRatio",a.getAspectRatio(e.activeCamera)),this._lineShader.bind(this._source.getWorldMatrix()),a.drawElementsType(material_Material.TriangleFillMode,0,this._indicesCount,s),this._lineShader.unbind(),r&&a.unbindInstanceAttributes(),this._source.getScene()._activeMeshesFrozen||this.customInstances.reset(),this._lineShader._setDrawWrapper(t)}};let LineEdgesRenderer=class LineEdgesRenderer extends EdgesRenderer{constructor(e,t=.95,i=!1){super(e,t,i,!1),this._generateEdgesLines()}_generateEdgesLines(){let e=this._source.getVerticesData(buffer_VertexBuffer.PositionKind),t=this._source.getIndices();if(!t||!e)return;let i=math_vector_TmpVectors.Vector3[0],r=math_vector_TmpVectors.Vector3[1],s=t.length-1;for(let a=0,n=0;a<s;a+=2,n+=4)math_vector_Vector3.FromArrayToRef(e,3*t[a],i),math_vector_Vector3.FromArrayToRef(e,3*t[a+1],r),this.createLine(i,r,n);let a=this._source.getScene().getEngine();this._buffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(a,this._linesPositions,buffer_VertexBuffer.PositionKind,!1),this._buffers[buffer_VertexBuffer.NormalKind]=new buffer_VertexBuffer(a,this._linesNormals,buffer_VertexBuffer.NormalKind,!1,!1,4),this._ib=a.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}};let PrePassRenderTarget=class PrePassRenderTarget extends MultiRenderTarget{constructor(e,t,i,r,s,a){super(e,i,r,s,a),this._beforeCompositionPostProcesses=[],this._internalTextureDirty=!1,this.enabled=!1,this.renderTargetTexture=null,this.renderTargetTexture=t}_createCompositionEffect(){this.imageProcessingPostProcess=new ImageProcessingPostProcess("prePassComposition",1,null,void 0,this._engine),this.imageProcessingPostProcess._updateParameters()}_checkSize(){let e=this._engine.getRenderWidth(!0),t=this._engine.getRenderHeight(!0),i=this.getRenderWidth(),r=this.getRenderHeight();(i!==e||r!==t)&&(this.resize({width:e,height:t}),this._internalTextureDirty=!0)}updateCount(e,t,i){super.updateCount(e,t,i),this._internalTextureDirty=!0}_resetPostProcessChain(){this._beforeCompositionPostProcesses.length=0}dispose(){let e=this._scene;if(super.dispose(),e&&e.prePassRenderer){let t=e.prePassRenderer.renderTargets.indexOf(this);-1!==t&&e.prePassRenderer.renderTargets.splice(t,1)}this.imageProcessingPostProcess&&this.imageProcessingPostProcess.dispose(),this.renderTargetTexture&&(this.renderTargetTexture._prePassRenderTarget=null),this._outputPostProcess&&(this._outputPostProcess.autoClear=!0,this._outputPostProcess.restoreDefaultInputTexture())}};let PrePassRenderer=class PrePassRenderer{get generateNormalsInWorldSpace(){return this._generateNormalsInWorldSpace}set generateNormalsInWorldSpace(e){this._generateNormalsInWorldSpace!==e&&(this._generateNormalsInWorldSpace=e,this._markAllMaterialsAsPrePassDirty())}getIndex(e){return this._textureIndices[e]}get samples(){return this.defaultRT.samples}set samples(e){this.defaultRT.samples=e}get useSpecificClearForDepthTexture(){return this._useSpecificClearForDepthTexture}set useSpecificClearForDepthTexture(e){this._useSpecificClearForDepthTexture!==e&&(this._useSpecificClearForDepthTexture=e,this._isDirty=!0)}getRenderTarget(){return this._currentTarget}_setRenderTarget(e){var t,i;e?this._currentTarget=e:(this._currentTarget=this.defaultRT,this._engine.currentRenderPassId=null!==(i=null===(t=this._scene.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==i?i:this._currentTarget.renderPassId)}get currentRTisSceneRT(){return this._currentTarget===this.defaultRT}_refreshGeometryBufferRendererLink(){if(this.doNotUseGeometryRendererFallback)this._geometryBuffer&&this._geometryBuffer._unlinkPrePassRenderer(),this._geometryBuffer=null,this._scene.disableGeometryBufferRenderer();else{if(this._geometryBuffer=this._scene.enableGeometryBufferRenderer(),!this._geometryBuffer){this.doNotUseGeometryRendererFallback=!0;return}this._geometryBuffer._linkPrePassRenderer(this)}}get enabled(){return this._enabled}constructor(e){this.excludedSkinnedMesh=[],this.excludedMaterials=[],this.mrtCount=0,this._mrtTypes=[],this._mrtFormats=[],this._mrtLayout=[],this._mrtNames=[],this._textureIndices=[],this._generateNormalsInWorldSpace=!1,this._useSpecificClearForDepthTexture=!1,this._isDirty=!0,this._effectConfigurations=[],this.doNotUseGeometryRendererFallback=!0,this.renderTargets=[],this._clearColor=new math_color_Color4(0,0,0,0),this._clearDepthColor=new math_color_Color4(1e8,0,0,1),this._enabled=!1,this._needsCompositionForThisPass=!1,this.disableGammaTransform=!1,this._scene=e,this._engine=e.getEngine();let t=0;if(this._engine._caps.textureFloat&&this._engine._caps.textureFloatLinearFiltering?t=1:this._engine._caps.textureHalfFloat&&this._engine._caps.textureHalfFloatLinearFiltering&&(t=2),1!==t)for(let e=0;e<PrePassRenderer.TextureFormats.length;++e)1===PrePassRenderer.TextureFormats[e].type&&(PrePassRenderer.TextureFormats[5].type=t);PrePassRenderer._SceneComponentInitialization(this._scene),this.defaultRT=this._createRenderTarget("sceneprePassRT",null),this._currentTarget=this.defaultRT}_createRenderTarget(e,t){let i=new PrePassRenderTarget(e,t,{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},0,this._scene,{generateMipMaps:!1,generateStencilBuffer:this._engine.isStencilEnable,defaultType:0,types:[],drawOnlyOnFirstAttachmentByDefault:!0});return this.renderTargets.push(i),this._enabled&&this._update(),i}get isSupported(){return this._scene.getEngine().getCaps().drawBuffersExtension}bindAttachmentsForEffect(e,t){let i=t.getMaterial(),r=i&&i.isPrePassCapable,s=i&&-1!==this.excludedMaterials.indexOf(i);this.enabled&&this._currentTarget.enabled&&(e._multiTarget&&r&&!s?this._engine.bindAttachments(this._multiRenderAttachments):(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment(),this._geometryBuffer&&this.currentRTisSceneRT&&!s&&this._geometryBuffer.renderList.push(t.getRenderingMesh())))}_reinitializeAttachments(){let e=[],t=[!1],i=[!1],r=[!0];for(let s=0;s<this.mrtCount;s++)e.push(!0),s>0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;e<PrePassRenderer.TextureFormats.length;e++)this._textureIndices[PrePassRenderer.TextureFormats[e].purpose]=-1;this._textureIndices[4]=0,this._mrtLayout=[4],this._mrtTypes=[PrePassRenderer.TextureFormats[4].type],this._mrtFormats=[PrePassRenderer.TextureFormats[4].format],this._mrtNames=[PrePassRenderer.TextureFormats[4].name],this.mrtCount=1}_updateGeometryBufferLayout(){if(this._refreshGeometryBufferRendererLink(),this._geometryBuffer){this._geometryBuffer._resetLayout();let e=[];for(let t=0;t<this._mrtLayout.length;t++)e.push(!1);this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture());let t=[{prePassConstant:5,geometryBufferConstant:GeometryBufferRenderer.DEPTH_TEXTURE_TYPE},{prePassConstant:6,geometryBufferConstant:GeometryBufferRenderer.NORMAL_TEXTURE_TYPE},{prePassConstant:1,geometryBufferConstant:GeometryBufferRenderer.POSITION_TEXTURE_TYPE},{prePassConstant:3,geometryBufferConstant:GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE},{prePassConstant:2,geometryBufferConstant:GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE}];for(let i=0;i<t.length;i++){let r=this._mrtLayout.indexOf(t[i].prePassConstant);-1!==r&&(this._geometryBuffer._forceTextureType(t[i].geometryBufferConstant,r),e[r]=!0)}this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(e))}}restoreAttachments(){this.enabled&&this._currentTarget.enabled&&this._defaultAttachments&&(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment())}_beforeDraw(e,t,i){this._isDirty&&this._update(),this._enabled&&this._currentTarget.enabled&&(this._geometryBuffer&&(this._geometryBuffer.renderList=[]),this._setupOutputForThisPass(this._currentTarget,e))}_prepareFrame(e,t,i){e.renderTargetTexture?e.renderTargetTexture._prepareFrame(this._scene,t,i,e.renderTargetTexture.useCameraPostProcesses):this._postProcessesSourceForThisPass.length?this._scene.postProcessManager._prepareFrame():this._engine.restoreDefaultFramebuffer()}setCustomOutput(e){let t=this._postProcessesSourceForThisPass[0];return!!t&&(t.inputTexture=e.renderTarget,!0)}_renderPostProcesses(e,t){var i;let r=this._postProcessesSourceForThisPass[0],s=r?r.inputTexture:e.renderTargetTexture?e.renderTargetTexture.renderTarget:null,a=this._currentTarget._beforeCompositionPostProcesses;this._needsCompositionForThisPass&&(a=a.concat([this._currentTarget.imageProcessingPostProcess])),a.length&&(this._scene.postProcessManager._prepareFrame(null===(i=this._currentTarget.renderTarget)||void 0===i?void 0:i.texture,a),this._scene.postProcessManager.directRender(a,s,!1,t))}_afterDraw(e,t){this._enabled&&this._currentTarget.enabled&&(this._prepareFrame(this._currentTarget,e,t),this._renderPostProcesses(this._currentTarget,e))}_clear(){this._enabled&&this._currentTarget.enabled&&(this._bindFrameBuffer(),this._engine.bindAttachments(this._clearAttachments),this._engine.clear(this._clearColor,!0,!1,!1),this._useSpecificClearForDepthTexture&&(this._engine.bindAttachments(this._clearDepthAttachments),this._engine.clear(this._clearDepthColor,!0,!1,!1)),this._engine.bindAttachments(this._defaultAttachments))}_bindFrameBuffer(){if(this._enabled&&this._currentTarget.enabled){this._currentTarget._checkSize();let e=this._currentTarget.renderTarget;e&&this._engine.bindFramebuffer(e)}}_setEnabled(e){this._enabled=e}_setRenderTargetEnabled(e,t){e.enabled=t,t||this._unlinkInternalTexture(e)}addEffectConfiguration(e){for(let t=0;t<this._effectConfigurations.length;t++)if(this._effectConfigurations[t].name===e.name)return this._effectConfigurations[t];return this._effectConfigurations.push(e),e}getEffectConfiguration(e){for(let t=0;t<this._effectConfigurations.length;t++)if(this._effectConfigurations[t].name===e)return this._effectConfigurations[t];return null}_enable(){let e=this.mrtCount;for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled&&this._enableTextures(this._effectConfigurations[e].texturesRequired);for(let t=0;t<this.renderTargets.length;t++){(this.mrtCount!==e||this.renderTargets[t].count!==this.mrtCount)&&this.renderTargets[t].updateCount(this.mrtCount,{types:this._mrtTypes,formats:this._mrtFormats},this._mrtNames.concat("prePass_DepthBuffer")),this.renderTargets[t]._resetPostProcessChain();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled&&(!this._effectConfigurations[e].postProcess&&this._effectConfigurations[e].createPostProcess&&this._effectConfigurations[e].createPostProcess(),this._effectConfigurations[e].postProcess&&this.renderTargets[t]._beforeCompositionPostProcesses.push(this._effectConfigurations[e].postProcess))}this._reinitializeAttachments(),this._setEnabled(!0),this._updateGeometryBufferLayout()}_disable(){this._setEnabled(!1);for(let e=0;e<this.renderTargets.length;e++)this._setRenderTargetEnabled(this.renderTargets[e],!1);this._resetLayout();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled=!1}_getPostProcessesSource(e,t){if(t)return t._postProcesses;if(!e.renderTargetTexture)return this._scene.activeCamera?this._scene.activeCamera._postProcesses:[];if(e.renderTargetTexture.useCameraPostProcesses){let t=e.renderTargetTexture.activeCamera?e.renderTargetTexture.activeCamera:this._scene.activeCamera;return t?t._postProcesses:[]}return e.renderTargetTexture.postProcesses?e.renderTargetTexture.postProcesses:[]}_setupOutputForThisPass(e,t){let i=t&&this._scene.activeCameras&&!!this._scene.activeCameras.length&&0!==this._scene.activeCameras.indexOf(t);this._postProcessesSourceForThisPass=this._getPostProcessesSource(e,t),this._postProcessesSourceForThisPass=this._postProcessesSourceForThisPass.filter(e=>null!=e),this._scene.autoClear=!0;let r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;let s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),a=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0],n=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),a?n=a:this._needsCompositionForThisPass?n=e.imageProcessingPostProcess:s&&(n=s),this._bindFrameBuffer(),this._linkInternalTexture(e,n)}_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;e<this._effectConfigurations.length;e++)if(this._effectConfigurations[e].enabled&&this._effectConfigurations[e].needsImageProcessing)return!0;return!1}_hasImageProcessing(e){var t;let i=!1;if(e){for(let r=0;r<e.length;r++)if((null===(t=e[r])||void 0===t?void 0:t.getClassName())==="ImageProcessingPostProcess"){i=!0;break}}return i}_getFirstPostProcess(e){for(let t=0;t<e.length;t++)if(null!==e[t])return e[t];return null}markAsDirty(){this._isDirty=!0}_enableTextures(e){this._scene.needsPreviousWorldMatrices=!1;for(let t=0;t<e.length;t++){let i=e[t];-1===this._textureIndices[i]&&(this._textureIndices[i]=this._mrtLayout.length,this._mrtLayout.push(i),this._mrtTypes.push(PrePassRenderer.TextureFormats[i].type),this._mrtFormats.push(PrePassRenderer.TextureFormats[i].format),this._mrtNames.push(PrePassRenderer.TextureFormats[i].name),this.mrtCount++),2===i&&(this._scene.needsPreviousWorldMatrices=!0)}}update(){this._isDirty&&this._update()}_update(){let e;this._disable();let t=!1;this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._scene._depthPeelingRenderer&&this._scene.useOrderIndependentTransparency&&(this._scene._depthPeelingRenderer.setPrePassRenderer(this),t=!0);for(let e=0;e<this._scene.materials.length;e++)this._scene.materials[e].setPrePassRenderer(this)&&(t=!0);t&&this._setRenderTargetEnabled(this.defaultRT,!0);for(let i=0;i<this.renderTargets.length;i++){if(this.renderTargets[i].renderTargetTexture)e=this._getPostProcessesSource(this.renderTargets[i]);else{let t=this._scene.activeCamera;if(!t)continue;e=t._postProcesses}if(e&&(e=e.filter(e=>null!=e))){for(let r=0;r<e.length;r++)e[r].setPrePassRenderer(this)&&(this._setRenderTargetEnabled(this.renderTargets[i],!0),t=!0);this._hasImageProcessing(e)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!0)}}this._markAllMaterialsAsPrePassDirty(),this._isDirty=!1,t&&this._enable()}_markAllMaterialsAsPrePassDirty(){let e=this._scene.materials;for(let t=0;t<e.length;t++)e[t].markAsDirty(material_Material.PrePassDirtyFlag)}dispose(){for(let e=this.renderTargets.length-1;e>=0;e--)this.renderTargets[e].dispose();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].dispose&&this._effectConfigurations[e].dispose()}};PrePassRenderer._SceneComponentInitialization=e=>{throw _WarnImport("PrePassRendererSceneComponent")},PrePassRenderer.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(scene_Scene.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),scene_Scene.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new PrePassRenderer(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,logger_Logger.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},scene_Scene.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};let PrePassRendererSceneComponent=class PrePassRendererSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,r){if(!r)return;let s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){let t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}};PrePassRenderer._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_PREPASSRENDERER);t||(t=new PrePassRendererSceneComponent(e),e._addComponent(t))};let n9=`#define rcp(x) 1./x +#define GOLDEN_RATIO 1.618033988749895 +#define TWO_PI 6.2831855 +vec2 Golden2dSeq(int i,float n) +{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} +vec2 SampleDiskGolden(int i,int sampleCount) +{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;ShaderStore.IncludesShadersStore.fibonacci=n9,ShaderStore.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";let oe=`#include<fibonacci> +#include<helperFunctions> +#include<subSurfaceScatteringFunctions> +#include<diffusionProfile> +varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; +#define rcp(x) 1./x +#define Sq(x) x*x +#define SSS_BILATERAL_FILTER true +vec3 EvalBurleyDiffusionProfile(float r,vec3 S) +{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); +vec3 expSum=exp_13*(1.+exp_13*exp_13); +return (S*rcp(8.*PI))*expSum; } +vec2 SampleBurleyDiffusionProfile(float u,float rcpS) +{u=1.-u; +float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); +float p=(g*n)*n; +float c=1.+p+n; +float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); +float x=(3./LOG2_E)*log2(c)-d; +float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; +return vec2(r,rcpPdf);} +vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) +{ +#ifndef SSS_BILATERAL_FILTER +z=0.; +#endif +float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; +#if SSS_CLAMP_ARTIFACT +return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); +#else +return EvalBurleyDiffusionProfile(r,S)*area; +#endif +} +void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, +float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) +{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; +float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; +vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; +float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) +{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} +else +{}} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) +{centerDepth=texture2D(depthSampler,vUV).r;} +if (!passedStencilTest) { +gl_FragColor=inputColor;return;} +float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; +vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; +float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) +{ +#ifdef DEBUG_SSS_SAMPLES +vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; +#endif +gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} +#ifdef DEBUG_SSS_SAMPLES +vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; +#endif +float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); +vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i<n; i++) +{EvaluateSample(i,n,S,d,centerPosVS,mmPerUnit,pixelsPerMm, +phase,totalIrradiance,totalWeight);} +totalWeight=max(totalWeight,HALF_MIN);gl_FragColor=vec4(inputColor.rgb+albedo*max(totalIrradiance/totalWeight,vec3(0.0)),1.);}`;ShaderStore.ShadersStore.subSurfaceScatteringPixelShader=oe;let SubSurfaceScatteringPostProcess=class SubSurfaceScatteringPostProcess extends postProcess_PostProcess{getClassName(){return"SubSurfaceScatteringPostProcess"}constructor(e,t,i,r=null,s,a,n,o=0){super(e,"subSurfaceScattering",["texelSize","viewportSize","metersPerUnit"],["diffusionS","diffusionD","filterRadii","irradianceSampler","depthSampler","albedoSampler"],i,r,s||texture_Texture.BILINEAR_SAMPLINGMODE,a,n,null,o,"postprocess",void 0,!0),this._scene=t,this.updateEffect(),this.onApplyObservable.add(e=>{if(!t.prePassRenderer||!t.subSurfaceConfiguration){logger_Logger.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}let 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)})}};let SubSurfaceConfiguration=class SubSurfaceConfiguration{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=sceneComponent_SceneComponentConstants.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new math_color_Color3(1,1,1)),this._scene=e,SubSurfaceConfiguration._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return logger_Logger.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t<this._ssDiffusionS.length/3;t++)if(this._ssDiffusionS[3*t]===e.r&&this._ssDiffusionS[3*t+1]===e.g&&this._ssDiffusionS[3*t+2]===e.b)return t;return this._ssDiffusionS.push(e.r,e.b,e.g),this._ssDiffusionD.push(Math.max(Math.max(e.r,e.b),e.g)),this._ssFilterRadii.push(this.getDiffusionProfileParameters(e)),this.ssDiffusionProfileColors.push(e),this._ssDiffusionD.length-1}createPostProcess(){return this.postProcess=new SubSurfaceScatteringPostProcess("subSurfaceScattering",this._scene,1,null,void 0,this._scene.getEngine()),this.postProcess.autoClear=!1,this.postProcess}clearAllDiffusionProfiles(){this._ssDiffusionD=[],this._ssDiffusionS=[],this._ssFilterRadii=[],this.ssDiffusionProfileColors=[]}dispose(){this.clearAllDiffusionProfiles(),this.postProcess&&this.postProcess.dispose()}getDiffusionProfileParameters(e){let t=Math.max(e.r,e.g,e.b);return this._sampleBurleyDiffusionProfile(.997,t)}_sampleBurleyDiffusionProfile(e,t){e=1-e;let i=1+4*e*(2*e+Math.sqrt(1+4*e*e)),r=Math.pow(i,-1/3),s=3*Math.log((1+i*r*r+r)/(4*e));return s*t}};SubSurfaceConfiguration._SceneComponentInitialization=e=>{throw _WarnImport("SubSurfaceSceneComponent")},AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_SUBSURFACE,(e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,r=e.ssDiffusionProfileColors.length;i<r;i++){let r=e.ssDiffusionProfileColors[i];t.subSurfaceConfiguration.addDiffusionProfile(new math_color_Color3(r.r,r.g,r.b))}}),Object.defineProperty(scene_Scene.prototype,"subSurfaceConfiguration",{get:function(){return this._subSurfaceConfiguration},set:function(e){e&&this.enablePrePassRenderer()&&(this._subSurfaceConfiguration=e)},enumerable:!0,configurable:!0}),scene_Scene.prototype.enableSubSurfaceForPrePass=function(){if(this._subSurfaceConfiguration)return this._subSurfaceConfiguration;let e=this.enablePrePassRenderer();return e?(this._subSurfaceConfiguration=new SubSurfaceConfiguration(this),e.addEffectConfiguration(this._subSurfaceConfiguration),this._subSurfaceConfiguration):null},scene_Scene.prototype.disableSubSurfaceForPrePass=function(){this._subSurfaceConfiguration&&(this._subSurfaceConfiguration.dispose(),this._subSurfaceConfiguration=null)};let SubSurfaceSceneComponent=class SubSurfaceSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_PREPASSRENDERER,this.scene=e}register(){}serialize(e){if(!this.scene.subSurfaceConfiguration)return;let t=this.scene.subSurfaceConfiguration.ssDiffusionProfileColors;e.ssDiffusionProfileColors=[];for(let i=0;i<t.length;i++)e.ssDiffusionProfileColors.push({r:t[i].r,g:t[i].g,b:t[i].b})}addFromContainer(){}removeFromContainer(){this.scene.prePassRenderer&&this.scene.subSurfaceConfiguration&&this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles()}rebuild(){}dispose(){}};SubSurfaceConfiguration._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_SUBSURFACE);t||(t=new SubSurfaceSceneComponent(e),e._addComponent(t))};let ot=`#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform vec4 color; +#ifdef ALPHATEST +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include<clipPlaneFragmentDeclaration> +#include<logDepthDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +#include<logDepthFragment> +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;ShaderStore.ShadersStore.outlinePixelShader=ot;let oi=`attribute vec3 position;attribute vec3 normal; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<clipPlaneVertexDeclaration> +uniform float offset; +#include<instancesDeclaration> +uniform mat4 viewProjection; +#ifdef ALPHATEST +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#include<logDepthDeclaration> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position;vec3 normalUpdated=normal; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +vec3 offsetPosition=positionUpdated+(normalUpdated*offset); +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; +#ifdef ALPHATEST +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#include<clipPlaneVertex> +#include<logDepthVertex> +} +`;ShaderStore.ShadersStore.outlineVertexShader=oi,scene_Scene.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new OutlineRenderer(this)),this._outlineRenderer},Object.defineProperty(mesh_Mesh.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(mesh_Mesh.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});let OutlineRenderer=class OutlineRenderer{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e<this._passIdForDrawWrapper.length;++e)this._engine.releaseRenderPassId(this._passIdForDrawWrapper[e])}render(e,t,i=!1,r){r=null!=r?r:this._passIdForDrawWrapper[0];let s=this.scene,a=s.getEngine(),n=a.getCaps().instancedArrays&&(null!==t.visibleInstances[e._id]&&void 0!==t.visibleInstances[e._id]||e.getRenderingMesh().hasThinInstances);if(!this.isReady(e,n,r))return;let o=e.getMesh(),l=o._internalAbstractMeshDataInfo._actAsRegularMesh?o:null,h=e.getRenderingMesh(),c=l||h,u=e.getMaterial();if(!u||!s.activeCamera)return;let d=e._getDrawWrapper(r),_=drawWrapper_DrawWrapper.GetEffect(d);if(a.enableEffect(d),u.useLogarithmicDepth&&_.setFloat("logarithmicDepthConstant",2/(Math.log(s.activeCamera.maxZ+1)/Math.LN2)),_.setFloat("offset",i?0:h.outlineWidth),_.setColor4("color",i?h.overlayColor:h.outlineColor,i?h.overlayAlpha:u.alpha),_.setMatrix("viewProjection",s.getTransformMatrix()),_.setMatrix("world",c.getWorldMatrix()),h.useBones&&h.computeBonesUsingShaders&&h.skeleton&&_.setMatrices("mBones",h.skeleton.getTransformMatrices(h)),h.morphTargetManager&&h.morphTargetManager.isUsingTextureForTargets&&h.morphTargetManager._bind(_),MaterialHelper.BindMorphTargetParameters(h,_),n||h._bind(e,_,u.fillMode),u&&u.needAlphaTesting()){let e=u.getAlphaTestTexture();e&&(_.setTexture("diffuseSampler",e),_.setMatrix("diffuseMatrix",e.getTextureMatrix()))}bindClipPlane(_,u,s),a.setZOffset(-this.zOffset),a.setZOffsetUnits(-this.zOffsetUnits),h._processRendering(c,e,_,u.fillMode,t,n,(e,t)=>{_.setMatrix("world",t)}),a.setZOffset(0),a.setZOffsetUnits(0)}isReady(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];let r=[],s=[buffer_VertexBuffer.PositionKind,buffer_VertexBuffer.NormalKind],a=e.getMesh(),n=e.getMaterial();if(!n)return!1;let o=a.getScene();n.needAlphaTesting()&&(r.push("#define ALPHATEST"),a.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(s.push(buffer_VertexBuffer.UVKind),r.push("#define UV1")),a.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&(s.push(buffer_VertexBuffer.UV2Kind),r.push("#define UV2"))),n.useLogarithmicDepth&&r.push("#define LOGARITHMICDEPTH"),prepareStringDefinesForClipPlanes(n,o,r),a.useBones&&a.computeBonesUsingShaders?(s.push(buffer_VertexBuffer.MatricesIndicesKind),s.push(buffer_VertexBuffer.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(buffer_VertexBuffer.MatricesIndicesExtraKind),s.push(buffer_VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),r.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");let l=a.morphTargetManager,h=0;l&&l.numInfluencers>0&&(h=l.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(s,a,h)),t&&(r.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(s),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));let c=e._getDrawWrapper(i,!0),u=c.defines,d=r.join("\n");if(u!==d){let e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];addClipPlaneUniforms(e),c.setEffect(this.scene.getEngine().createEffect("outline",s,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){let r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(OutlineRenderer._StencilReference),this._engine.setStencilFunctionReference(OutlineRenderer._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){let e=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}};OutlineRenderer._StencilReference=4;let FluidRenderingObject=class FluidRenderingObject{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 observable_Observable,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){let 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 EffectWrapper({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new EffectWrapper({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;let e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){let e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;let 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(){let e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;let 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()}};let FluidRenderingObjectParticleSystem=class FluidRenderingObjectParticleSystem extends FluidRenderingObject{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}};let FluidRenderingTextures=class FluidRenderingTextures{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){let 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,r,s,a,n=1,o=6,l=1,h=6,c=!1,u=null,d=!0,_=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 observable_Observable,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=r,this._blurTextureSizeX=s,this._blurTextureSizeY=a,this._textureType=n,this._textureFormat=o,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=c,this._generateDepthBuffer=d,this._samples=_,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==a,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){let[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}`});let e=this._rt.texture;e.incrementReferences(),this._texture=new texture_Texture(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,r,s,a=!1){let n=this._scene.getEngine(),o=new math_vector_Vector2(Math.floor(this._blurTextureSizeX/r),Math.floor(this._blurTextureSizeY/r)),l=1===t&&n.getCaps().textureFloatLinearFiltering||2===t&&n.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:o.x,height:o.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${s}`}),c=h.texture;c.incrementReferences();let u=new texture_Texture(null,this._scene);if(u.name="rttBlurred"+s,u._texture=c,u.wrapU=texture_Texture.CLAMP_ADDRESSMODE,u.wrapV=texture_Texture.CLAMP_ADDRESSMODE,u.anisotropicFilteringLevel=1,a){let r=new postProcess_PostProcess("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,n,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),r.onSizeChangedObservable.add(()=>{r._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(r);let s=new postProcess_PostProcess("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,n,!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=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s),r.autoClear=!1,s.autoClear=!1;let a=[];for(let e=0;e<2*this._blurNumIterations;++e)a[e]=1&e?s:r;return[h,u,a]}{let r=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],s=new postProcess_PostProcess("BilateralBlurX","fluidRenderingBilateralBlur",r,null,1,null,1,n,!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=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s);let a=new postProcess_PostProcess("BilateralBlurY","fluidRenderingBilateralBlur",r,null,1,null,1,n,!0,null,t,void 0,void 0,void 0,i);a.samples=this._samples,a.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++}),a.onSizeChangedObservable.add(()=>{a._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(a),s.autoClear=!1,a.autoClear=!1;let o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?a:s;return[h,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,r;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===(r=this._textureBlurred)||void 0===r||r.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"}(t9||(t9={}));let FluidRenderingTargetRenderer=class FluidRenderingTargetRenderer{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 math_color_Color3(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new math_vector_Vector3(-2,-1,1).normalize(),this._debugFeature=t9.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 observable_Observable,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 math_vector_Matrix,this._depthClearColor=new math_color_Color4(1e6,1e6,1e6,1),this._thicknessClearColor=new math_color_Color4(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;let r=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 FluidRenderingTextures("Depth",this._scene,r,s,r,s,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){let 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 FluidRenderingTextures("Diffuse",this._scene,e,i,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}let a=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),n=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new FluidRenderingTextures("Thickness",this._scene,a,n,a,n,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;let t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],r=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;let a=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,n=new math_vector_Vector2(1/a.getSize().width,1/a.getSize().height);if(this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap){let t=null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture;t&&(r.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT"))}this._diffuseRenderTarget?(r.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(r.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),r.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),r.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===t9.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===t9.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),r.push("debugSampler"),(this._debugFeature===t9.DepthTexture||this._debugFeature===t9.DepthBlurredTexture)&&s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new postProcess_PostProcess("FluidRendering","fluidRenderingRender",i,r,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,r,s,a,o,l,h,c,u,d,_,p,f,m,g,v,x,b,T,S,C,E,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!==(a=null===(s=this._depthRenderTarget.textureBlur)||void 0===s?void 0:s.getInternalTexture())&&void 0!==a?a:null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(r=null===(i=this._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==r?r: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!==(u=this._bgDepthTexture)&&void 0!==u?u:null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(f=null===(p=this._thicknessRenderTarget.textureBlur)||void 0===p?void 0:p.getInternalTexture())&&void 0!==f?f:null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(_=null===(d=this._thicknessRenderTarget.texture)||void 0===d?void 0:d.getInternalTexture())&&void 0!==_?_:null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){let 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",n),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 t9.DepthTexture:i=this._depthRenderTarget.texture;break;case t9.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case t9.ThicknessTexture:i=null!==(x=null===(v=this._thicknessRenderTarget)||void 0===v?void 0:v.texture)&&void 0!==x?x:null;break;case t9.ThicknessBlurredTexture:i=(null===(b=this._thicknessRenderTarget)||void 0===b?void 0:b.enableBlur)?null!==(S=null===(T=this._thicknessRenderTarget)||void 0===T?void 0:T.textureBlur)&&void 0!==S?S:null:null!==(E=null===(C=this._thicknessRenderTarget)||void 0===C?void 0:C.texture)&&void 0!==E?E:null;break;case t9.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==t9.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,r,s,a,n;if(this._needInitialization||!e.isReady())return;let o=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===(r=this._thicknessRenderTarget)||void 0===r?void 0:r.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===(a=this._diffuseRenderTarget)||void 0===a||a.applyBlurPostProcesses(),null===(n=this._thicknessRenderTarget)||void 0===n||n.applyBlurPostProcesses(),o&&this._engine.bindFramebuffer(o)}dispose(e=!1){var t,i,r,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===(r=this._thicknessRenderTarget)||void 0===r||r.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}};let FluidRenderingObjectCustomParticles=class FluidRenderingObjectCustomParticles extends FluidRenderingObject{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(let t in e){let i;let r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1}this._vertexBuffers[t]=new buffer_VertexBuffer(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new EffectWrapper({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 buffer_VertexBuffer(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(){let e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;let 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;for(let t in super.dispose(),null===(e=this._diffuseEffectWrapper)||void 0===e||e.dispose(),this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}};let or=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; +#include<helperFunctions> +void main(void) +{vec4 color=texture2D(textureSampler,vUV); +#ifdef DEPTH_TEXTURE +gl_FragDepth=color.r; +#else +if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} +gl_FragColor=color; +#endif +} +`;ShaderStore.ShadersStore.copyTextureToTexturePixelShader=or,function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(ie||(ie={}));let CopyTextureToTexture=class CopyTextureToTexture{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new EffectRenderer(e),this._effectWrapper=new EffectWrapper({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=ie.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;let r=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&r&&(this._engine.depthCullingState.depthFunc=r),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}};let FluidRenderingDepthTextureCopy=class FluidRenderingDepthTextureCopy{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new CopyTextureToTexture(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil")}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}};let os=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +#ifdef FLUIDRENDERING_VELOCITY +attribute vec3 velocity;varying float velocityNorm; +#endif +void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; +#ifdef FLUIDRENDERING_VELOCITY +velocityNorm=length(velocity); +#endif +} +`;ShaderStore.ShadersStore.fluidRenderingParticleDepthVertexShader=os;let oa=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +#ifdef FLUIDRENDERING_VELOCITY +varying float velocityNorm; +#endif +void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); +#ifndef FLUIDRENDERING_RHS +normal.z=-normal.z; +#endif +vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; +#ifdef WEBGPU +gl_FragDepth=clipSpacePos.z/clipSpacePos.w; +#else +gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; +#endif +#ifdef FLUIDRENDERING_RHS +realViewPos.z=-realViewPos.z; +#endif +#ifdef FLUIDRENDERING_VELOCITY +glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); +#else +glFragColor=vec4(realViewPos.z,0.,0.,1.); +#endif +} +`;ShaderStore.ShadersStore.fluidRenderingParticleDepthPixelShader=oa;let on=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} +`;ShaderStore.ShadersStore.fluidRenderingParticleThicknessVertexShader=on;let oo=`uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} +`;ShaderStore.ShadersStore.fluidRenderingParticleThicknessPixelShader=oo;let ol=`attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} +`;ShaderStore.ShadersStore.fluidRenderingParticleDiffuseVertexShader=ol;let oh=`uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} +`;ShaderStore.ShadersStore.fluidRenderingParticleDiffusePixelShader=oh;let oc=`uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} +int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} +glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} +`;ShaderStore.ShadersStore.fluidRenderingBilateralBlurPixelShader=oc;let ou=`uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} +float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} +sum/=wsum;glFragColor=vec4(sum.rgb,1.);} +`;ShaderStore.ShadersStore.fluidRenderingStandardBlurPixelShader=ou;let od=`/* disable_uniformity_analysis */ +#define IOR 1.333 +#define ETA 1.0/IOR +#define F0 0.02 +uniform sampler2D textureSampler;uniform sampler2D depthSampler; +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +uniform sampler2D diffuseSampler; +#else +uniform vec3 diffuseColor; +#endif +#ifdef FLUIDRENDERING_FIXED_THICKNESS +uniform float thickness;uniform sampler2D bgDepthSampler; +#else +uniform float minimumThickness;uniform sampler2D thicknessSampler; +#endif +#ifdef FLUIDRENDERING_ENVIRONMENT +uniform samplerCube reflectionSampler; +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +uniform sampler2D debugSampler; +#endif +uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; +#ifdef FLUIDRENDERING_RHS +ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; +#else +ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} +void main(void) {vec2 texCoord=vUV; +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +vec4 color=texture2D(debugSampler,texCoord); +#ifdef FLUIDRENDERING_DEBUG_DEPTH +glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} +#else +glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} +#endif +return; +#endif +vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; +#ifndef FLUIDRENDERING_FIXED_THICKNESS +float thickness=texture2D(thicknessSampler,texCoord).x; +#else +float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; +#endif +vec4 backColor=texture2D(textureSampler,texCoord); +#ifndef FLUIDRENDERING_FIXED_THICKNESS +if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { +#else +if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { +#endif +glFragColor=backColor;return;} +vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} +vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} +vec3 normal=normalize(cross(ddy,ddx)); +#ifdef FLUIDRENDERING_RHS +normal=-normal; +#endif +#ifndef WEBGPU +if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) +glFragColor=vec4(normal*0.5+0.5,1.0);return; +#endif +vec3 rayDir=normalize(viewPos); +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; +#endif +vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); +#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING +float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; +#endif +vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); +vec3 refractionColor=transmitted.rgb*transmittance; +#ifdef FLUIDRENDERING_ENVIRONMENT +vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; +#else +vec3 finalColor=refractionColor+specular; +#endif +#ifdef FLUIDRENDERING_VELOCITY +float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); +#endif +glFragColor=vec4(finalColor,transmitted.a);} +`;function IsParticleSystemObject(e){return!!e.particleSystem}ShaderStore.ShadersStore.fluidRenderingRenderPixelShader=od,Object.defineProperty(scene_Scene.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),scene_Scene.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new FluidRenderer(this)),this._fluidRenderer},scene_Scene.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};let FluidRendererSceneComponent=class FluidRendererSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.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()}};let FluidRenderer=class FluidRenderer{static _SceneComponentInitialization(e){let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_FLUIDRENDERER);t||(t=new FluidRendererSceneComponent(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,FluidRenderer._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add(()=>{this._initialize()})}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){let t=this._getParticleSystemIndex(e);return -1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){let s=new FluidRenderingObjectParticleSystem(this._scene,e);s.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new FluidRenderingTargetRenderer(this._scene,r),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==t&&(i.generateDiffuseTexture=t);let a={object:s,targetRenderer:i};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}addCustomParticles(e,t,i,r,s){let a=new FluidRenderingObjectCustomParticles(this._scene,e,t);a.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),r||(r=new FluidRenderingTargetRenderer(this._scene,s),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==i&&(r.generateDiffuseTexture=i);let n={object:a,targetRenderer:r};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}removeRenderObject(e,t=!0){let 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.priority<t.object.priority?-1:e.object.priority>t.object.priority?1:0)}_removeUnusedTargetRenderers(){let e={};for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t].targetRenderer;e[this.targetRenderers.indexOf(i)]=!0}let t=!1,i=[];for(let r=0;r<this.targetRenderers.length;++r)e[r]?i.push(this.targetRenderers[r]):(this.targetRenderers[r].dispose(),t=!0);return t&&(this.targetRenderers.length=0,this.targetRenderers.push(...i)),t}_getParticleSystemIndex(e){for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t].object;if(IsParticleSystemObject(i)&&i.particleSystem===e)return t}return -1}_initialize(){for(let e=0;e<this.targetRenderers.length;++e)this.targetRenderers[e].dispose();let e=new Map;for(let t=0;t<this.targetRenderers.length;++t){let i=this.targetRenderers[t];if(i._initialize(),i.camera&&i._renderPostProcess){let r=e.get(i.camera);r||(r=[[],{}],e.set(i.camera,r)),r[0].push(i),i.camera.attachPostProcess(i._renderPostProcess,t)}}let t=e.keys();for(let i=t.next();!0!==i.done;i=t.next()){let t=i.value,r=e.get(t),s=t._getFirstPostProcess();if(!s)continue;let[a,n]=r;s.onSizeChangedObservable.add(()=>{var e;for(let t of(s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,a[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`),a)){let i=null===(e=t._thicknessRenderTarget)||void 0===e?void 0:e.renderTarget,r=null==i?void 0:i.texture;if(i&&r){let e=r.width+"_"+r.height,t=n[e];t||(t=n[e]=new FluidRenderingDepthTextureCopy(this._engine,r.width,r.height)),t.depthRTWrapper._shareDepth(i)}}})}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){let t=i.value,r=this._cameras.get(t),s=r[1],a=e.get(t);if(a)for(let e in s)a[1][e]||s[e].dispose();else for(let e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){let e=new Map;for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t],r=e.get(i.targetRenderer);void 0===r&&(r=0),e.set(i.targetRenderer,Math.max(r,i.object.particleSize))}e.forEach((e,t)=>{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)})}_setUseVelocityForRenderObject(){for(let e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(let e of this.targetRenderers)if(e.needInitialization){this._initialize();return}}_render(e){var t;for(let t=0;t<this.targetRenderers.length;++t)e&&this.targetRenderers[t].camera!==e||this.targetRenderers[t]._clearTargets();let i=this._cameras.keys();for(let r=i.next();!0!==r.done;r=i.next()){let i=r.value,s=this._cameras.get(i);if(e&&i!==e)continue;let a=i._getFirstPostProcess();if(!a)continue;let n=null===(t=a.inputTexture)||void 0===t?void 0:t.depthStencilTexture;if(n){let[e,t]=s;for(let t of e)t._bgDepthTexture=n;for(let e in t)t[e].copy(n)}}for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t];e&&i.targetRenderer.camera!==e||i.targetRenderer._render(i.object)}}dispose(){this._engine.onResizeObservable.remove(this._onEngineResizeObserver),this._onEngineResizeObserver=null;for(let e=0;e<this.renderObjects.length;++e)this.renderObjects[e].object.dispose();for(let e=0;e<this.targetRenderers.length;++e)this.targetRenderers[e].dispose();this._cameras.forEach(e=>{let t=e[1];for(let e in t)t[e].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}};let ThinSprite=class ThinSprite{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,e<t?this._direction=1:(this._direction=-1,this._toIndex=e,this._fromIndex=t),this.cellIndex=e,this._time=0}stopAnimation(){this._animationStarted=!1}_animate(e){this._animationStarted&&(this._time+=e,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex<this._fromIndex)&&(this._loopAnimation?this.cellIndex=this._direction>0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}};let Sprite=class Sprite extends ThinSprite{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=[],this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new observable_Observable,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new math_color_Color4(1,1,1,1),this.position=math_vector_Vector3.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,r,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1);this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}serialize(){let e={};return e.name=this.name,e.position=this.position.asArray(),e.color=this.color.asArray(),e.width=this.width,e.height=this.height,e.angle=this.angle,e.cellIndex=this.cellIndex,e.cellRef=this.cellRef,e.invertU=this.invertU,e.invertV=this.invertV,e.disposeWhenFinishedAnimating=this.disposeWhenFinishedAnimating,e.isPickable=this.isPickable,e.isVisible=this.isVisible,e.useAlphaForPicking=this.useAlphaForPicking,e.animationStarted=this.animationStarted,e.fromIndex=this.fromIndex,e.toIndex=this.toIndex,e.loopAnimation=this.loopAnimation,e.delay=this.delay,e}static Parse(e,t){let i=new Sprite(e.name,t);return i.position=math_vector_Vector3.FromArray(e.position),i.color=math_color_Color4.FromArray(e.color),i.width=e.width,i.height=e.height,i.angle=e.angle,i.cellIndex=e.cellIndex,i.cellRef=e.cellRef,i.invertU=e.invertU,i.invertV=e.invertV,i.disposeWhenFinishedAnimating=e.disposeWhenFinishedAnimating,i.isPickable=e.isPickable,i.isVisible=e.isVisible,i.useAlphaForPicking=e.useAlphaForPicking,i._fromIndex=e.fromIndex,i._toIndex=e.toIndex,i._loopAnimation=e.loopAnimation,i._delay=e.delay,e.animationStarted&&i.playAnimation(i.fromIndex,i.toIndex,i.loopAnimation,i.delay),i}};scene_Scene.prototype._internalPickSprites=function(e,t,i,r){if(!PickingInfo)return null;let s=null;if(!r){if(!this.activeCamera)return null;r=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let a=0;a<this.spriteManagers.length;a++){let n=this.spriteManagers[a];if(!n.isPickable)continue;let o=n.intersects(e,r,t,i);if(o&&o.hit&&(i||null==s||!(o.distance>=s.distance))&&(s=o,i))break}return s||new PickingInfo},scene_Scene.prototype._internalMultiPickSprites=function(e,t,i){if(!PickingInfo)return null;let r=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s<this.spriteManagers.length;s++){let a=this.spriteManagers[s];if(!a.isPickable)continue;let n=a.multiIntersects(e,i,t);null!==n&&(r=r.concat(n))}return r},scene_Scene.prototype.pickSprite=function(e,t,i,r,s){if(!this._tempSpritePickingRay)return null;this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,s);let a=this._internalPickSprites(this._tempSpritePickingRay,i,r,s);return a&&(a.ray=this.createPickingRayInCameraSpace(e,t,s)),a},scene_Scene.prototype.pickSpriteWithRay=function(e,t,i,r){if(!this._tempSpritePickingRay)return null;if(!r){if(!this.activeCamera)return null;r=this.activeCamera}ray_Ray.TransformToRef(e,r.getViewMatrix(),this._tempSpritePickingRay);let s=this._internalPickSprites(this._tempSpritePickingRay,t,i,r);return s&&(s.ray=e),s},scene_Scene.prototype.multiPickSprite=function(e,t,i,r){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,r),this._internalMultiPickSprites(this._tempSpritePickingRay,i,r)},scene_Scene.prototype.multiPickSpriteWithRay=function(e,t,i){if(!this._tempSpritePickingRay)return null;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}return ray_Ray.TransformToRef(e,i.getViewMatrix(),this._tempSpritePickingRay),this._internalMultiPickSprites(this._tempSpritePickingRay,t,i)},scene_Scene.prototype.setPointerOverSprite=function(e){this._pointerOverSprite!==e&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(10,ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=e,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(9,ActionEvent.CreateNewFromSprite(this._pointerOverSprite,this)))},scene_Scene.prototype.getPointerOverSprite=function(){return this._pointerOverSprite};let SpriteSceneComponent=class SpriteSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_SPRITE,this.scene=e,this.scene.spriteManagers=[],this.scene._tempSpritePickingRay=ray_Ray?ray_Ray.Zero():null,this.scene.onBeforeSpritesRenderingObservable=new observable_Observable,this.scene.onAfterSpritesRenderingObservable=new observable_Observable,this._spritePredicate=e=>!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(sceneComponent_SceneComponentConstants.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(sceneComponent_SceneComponentConstants.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(sceneComponent_SceneComponentConstants.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();let e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,s){let a=this.scene.pickSprite(t,i,this._spritePredicate,r,s);return a&&(a.ray=e?e.ray:null),a}_pointerMove(e,t,i,r,s){let a=this.scene;return r?a.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,a.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(a.setPointerOverSprite(i.pickedSprite),!a.doNotHandleCursors&&s&&(a._pointerOverSprite&&a._pointerOverSprite.actionManager&&a._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=a._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=a.hoverCursor)):a.setPointerOverSprite(null),i}_pointerDown(e,t,i,r){let s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,ActionEvent.CreateNewFromSprite(i.pickedSprite,s,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,ActionEvent.CreateNewFromSprite(i.pickedSprite,s,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,ActionEvent.CreateNewFromSprite(i.pickedSprite,s,r))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,ActionEvent.CreateNewFromSprite(i.pickedSprite,s,r))}return i}_pointerUp(e,t,i,r,s){let a=this.scene;if(a.spriteManagers&&a.spriteManagers.length>0){let i=a.pickSprite(e,t,this._spritePredicate,!1,a.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,ActionEvent.CreateNewFromSprite(i.pickedSprite,a,r)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,ActionEvent.CreateNewFromSprite(i.pickedSprite,a,r)),s&&i.pickedSprite.actionManager.processTrigger(6,ActionEvent.CreateNewFromSprite(i.pickedSprite,a,r)))),a._pickedDownSprite&&a._pickedDownSprite.actionManager&&a._pickedDownSprite!==i.pickedSprite&&a._pickedDownSprite.actionManager.processTrigger(16,ActionEvent.CreateNewFromSprite(a._pickedDownSprite,a,r)))}return i}};let o_=`#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); +#endif +`;ShaderStore.IncludesShadersStore.imageProcessingCompatibility=o_;let op=`uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; +#include<fogFragmentDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +#ifdef PIXEL_PERFECT +vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} +#endif +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#ifdef PIXEL_PERFECT +vec2 uv=uvPixelPerfect(vUV); +#else +vec2 uv=vUV; +#endif +vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) +{if (color.a<0.95) +discard;} +color*=vColor; +#include<fogFragment> +gl_FragColor=color; +#include<imageProcessingCompatibility> +#define CUSTOM_FRAGMENT_MAIN_END +}`;ShaderStore.ShadersStore.spritesPixelShader=op;let of=`attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; +#include<fogVertexDeclaration> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; +vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); +vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; +#ifdef FOG +vFogDistance=viewPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.spritesVertexShader=of;let SpriteRenderer=class SpriteRenderer{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,r=null){let s;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=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Buffer(e,this._vertexData,!0,this._vertexBufferSize);let a=this._buffer.createVertexBuffer(buffer_VertexBuffer.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing),o=6;if(this._useInstancing){let t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Buffer(e,t,!1,2),s=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else s=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;let l=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(buffer_VertexBuffer.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[buffer_VertexBuffer.PositionKind]=a,this._vertexBuffers.options=n,this._vertexBuffers.offsets=s,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[buffer_VertexBuffer.ColorKind]=c,this._createEffects()}_createEffects(){var e,t,i,r;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===(r=this._drawWrapperFogDepth)||void 0===r||r.dispose(),this._drawWrapperBase=new drawWrapper_DrawWrapper(this._engine),this._drawWrapperFog=new drawWrapper_DrawWrapper(this._engine),this._drawWrapperDepth=new drawWrapper_DrawWrapper(this._engine,!1),this._drawWrapperFogDepth=new drawWrapper_DrawWrapper(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);let s=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[buffer_VertexBuffer.PositionKind,"options","offsets","inverts","cellInfo",buffer_VertexBuffer.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",[buffer_VertexBuffer.PositionKind,"options","offsets","inverts","cellInfo",buffer_VertexBuffer.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,r,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let a=this._drawWrapperBase,n=this._drawWrapperDepth,o=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(a=this._drawWrapperFog,n=this._drawWrapperFogDepth,o=!0);let l=a.effect;if(!l.isReady())return;let h=this._engine,c=!!(this._scene&&this._scene.useRightHandedSystem),u=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length),_=0,p=!0;for(let i=0;i<d;i++){let r=e[i];r&&r.isVisible&&(p=!1,r._animate(t),this._appendSpriteVertex(_++,r,0,0,u,c,s),this._useInstancing||(this._appendSpriteVertex(_++,r,1,0,u,c,s),this._appendSpriteVertex(_++,r,1,1,u,c,s),this._appendSpriteVertex(_++,r,0,1,u,c,s)))}if(p)return;this._buffer.update(this._vertexData);let f=!!h.depthCullingState.cull,m=h.depthCullingState.zOffset,g=h.depthCullingState.zOffsetUnits;if(h.setState(f,m,!1,!1,void 0,void 0,g),h.enableEffect(a),l.setTexture("diffuseSampler",this.texture),l.setMatrix("view",i),l.setMatrix("projection",r),o){let e=this._scene;l.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),l.setColor3("vFogColor",e.fogColor)}this._useVAO?(this._vertexArrayObject||(this._vertexArrayObject=h.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,l)),h.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):h.bindBuffers(this._vertexBuffers,this._indexBuffer,l),h.depthCullingState.depthFunc=h.useReverseDepthBuffer?518:515,this.disableDepthWrite||(l.setBool("alphaTest",!0),h.setColorWrite(!1),h.enableEffect(n),this._useInstancing?h.drawArraysType(7,0,4,_):h.drawElementsType(0,0,_/4*6),h.enableEffect(a),h.setColorWrite(!0),l.setBool("alphaTest",!1)),h.setAlphaMode(this.blendMode),this._useInstancing?h.drawArraysType(7,0,4,_):h.drawElementsType(0,0,_/4*6),this.autoResetAlpha&&h.setAlphaMode(0),c&&this._scene.getEngine().setState(f,m,!1,!0,void 0,void 0,g),h.unbindInstanceAttributes()}_appendSpriteVertex(e,t,i,r,s,a,n){let o=e*this._vertexBufferSize;if(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon),n)n(t,s);else{t.cellIndex||(t.cellIndex=0);let e=s.width/this.cellWidth,i=t.cellIndex/e>>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[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._useInstancing?o-=2:(this._vertexData[o+6]=i,this._vertexData[o+7]=r),a?this._vertexData[o+8]=t.invertU?0:1:this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0,this._vertexData[o+10]=t._xOffset,this._vertexData[o+11]=t._yOffset,this._vertexData[o+12]=t._xSize/s.width,this._vertexData[o+13]=t._ySize/s.height,this._vertexData[o+14]=t.color.r,this._vertexData[o+15]=t.color.g,this._vertexData[o+16]=t.color.b,this._vertexData[o+17]=t.color.a}_buildIndexBuffer(){let e=[],t=0;for(let i=0;i<this._capacity;i++)e.push(t),e.push(t+1),e.push(t+2),e.push(t),e.push(t+2),e.push(t+3),t+=4;this._indexBuffer=this._engine.createIndexBuffer(e)}rebuild(){var e;for(let e in this._indexBuffer&&this._buildIndexBuffer(),this._useVAO&&(this._vertexArrayObject=void 0),this._buffer._rebuild(),this._vertexBuffers){let t=this._vertexBuffers[e];t._rebuild()}null===(e=this._spriteBuffer)||void 0===e||e._rebuild()}dispose(){this._buffer&&(this._buffer.dispose(),this._buffer=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),this.texture&&(this.texture.dispose(),this.texture=null),this._drawWrapperBase.dispose(),this._drawWrapperFog.dispose(),this._drawWrapperDepth.dispose(),this._drawWrapperFogDepth.dispose()}};let spriteManager_SpriteManager=class spriteManager_SpriteManager{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get children(){return this.sprites}get scene(){return this._scene}get capacity(){return this._spriteRenderer.capacity}get texture(){return this._spriteRenderer.texture}set texture(e){e.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._spriteRenderer.texture=e,this._textureContent=null}get cellWidth(){return this._spriteRenderer.cellWidth}set cellWidth(e){this._spriteRenderer.cellWidth=e}get cellHeight(){return this._spriteRenderer.cellHeight}set cellHeight(e){this._spriteRenderer.cellHeight=e}get fogEnabled(){return this._spriteRenderer.fogEnabled}set fogEnabled(e){this._spriteRenderer.fogEnabled=e}get blendMode(){return this._spriteRenderer.blendMode}set blendMode(e){this._spriteRenderer.blendMode=e}get disableDepthWrite(){return this._disableDepthWrite}set disableDepthWrite(e){this._disableDepthWrite=e,this._spriteRenderer.disableDepthWrite=e}get pixelPerfect(){return this._spriteRenderer.pixelPerfect}set pixelPerfect(e){this._spriteRenderer.pixelPerfect=e,e&&3!==this.texture.samplingMode&&this.texture.updateSamplingMode(3)}constructor(e,t,i,r,s,a=.01,n=texture_Texture.TRILINEAR_SAMPLINGMODE,o=!1,l=null){this.name=e,this.sprites=[],this.renderingGroupId=0,this.layerMask=268435455,this.isPickable=!1,this.metadata=null,this._wasDispatched=!1,this.onDisposeObservable=new observable_Observable,this._disableDepthWrite=!1,this._packedAndReady=!1,this._customUpdate=(e,t)=>{e.cellRef||(e.cellIndex=0);let 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=engineStore_EngineStore.LastCreatedScene),s._getComponent(sceneComponent_SceneComponentConstants.NAME_SPRITE)||s._addComponent(new SpriteSceneComponent(s)),this._fromPacked=o,this._scene=s;let h=this._scene.getEngine();if(this._spriteRenderer=new SpriteRenderer(h,i,a,s),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else if(void 0!==r)this.cellWidth=r,this.cellHeight=r;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new texture_Texture(t,s,!0,!1,n)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if((e="string"==typeof t?JSON.parse(t):t).frames.length){let t={};for(let i=0;i<e.frames.length;i++){let r=e.frames[i];if("string"!=typeof Object.keys(r)[0])throw Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter.");let s=r[Object.keys(r)[0]];t[s]=r}e.frames=t}let i=Reflect.ownKeys(e.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=e.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,Error("Invalid JSON from string. Spritesheet managed with constant cell size.")}else{let t;let i=/\./g;do t=i.lastIndex,i.test(e);while(i.lastIndex>0);let r=e.substring(0,t-1)+".json";tools_Tools.LoadFile(r,e=>{try{let t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,Error("Invalid JSON format. Please check documentation for format specifications.")}},void 0,void 0,!1,()=>{logger_Logger.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1})}}_checkTextureAlpha(e,t,i,r,s){if(!e.useAlphaForPicking||!this.texture)return!0;let a=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(a.width*a.height*4),this.texture.readPixels(0,0,this._textureContent));let n=math_vector_TmpVectors.Vector3[0];n.copyFrom(t.direction),n.normalize(),n.scaleInPlace(i),n.addInPlace(t.origin);let o=(n.x-r.x)/(s.x-r.x),l=1-(n.y-r.y)/(s.y-r.y),h=e._xOffset*a.width+o*e._xSize|0,c=e._yOffset*a.height+l*e._ySize|0,u=this._textureContent[(h+c*a.width)*4+3];return u>.5}intersects(e,t,i,r){let s=Math.min(this.capacity,this.sprites.length),a=math_vector_Vector3.Zero(),n=math_vector_Vector3.Zero(),o=Number.MAX_VALUE,l=null,h=math_vector_TmpVectors.Vector3[0],c=math_vector_TmpVectors.Vector3[1],u=t.getViewMatrix(),d=e,_=e;for(let t=0;t<s;t++){let s=this.sprites[t];if(s){if(i){if(!i(s))continue}else if(!s.isPickable)continue;if(math_vector_Vector3.TransformCoordinatesToRef(s.position,u,c),s.angle?(math_vector_Matrix.TranslationToRef(-c.x,-c.y,0,math_vector_TmpVectors.Matrix[1]),math_vector_Matrix.TranslationToRef(c.x,c.y,0,math_vector_TmpVectors.Matrix[2]),math_vector_Matrix.RotationZToRef(-s.angle,math_vector_TmpVectors.Matrix[3]),math_vector_TmpVectors.Matrix[1].multiplyToRef(math_vector_TmpVectors.Matrix[3],math_vector_TmpVectors.Matrix[4]),math_vector_TmpVectors.Matrix[4].multiplyToRef(math_vector_TmpVectors.Matrix[2],math_vector_TmpVectors.Matrix[0]),d=e.clone(),math_vector_Vector3.TransformCoordinatesToRef(e.origin,math_vector_TmpVectors.Matrix[0],d.origin),math_vector_Vector3.TransformNormalToRef(e.direction,math_vector_TmpVectors.Matrix[0],d.direction)):d=e,a.copyFromFloats(c.x-s.width/2,c.y-s.height/2,c.z),n.copyFromFloats(c.x+s.width/2,c.y+s.height/2,c.z),d.intersectsBoxMinMax(a,n)){let e=math_vector_Vector3.Distance(c,d.origin);if(o>e){if(!this._checkTextureAlpha(s,d,e,a,n))continue;if(_=d,o=e,l=s,r)break}}}}if(l){let e=new PickingInfo;u.invertToRef(math_vector_TmpVectors.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=o;let t=math_vector_TmpVectors.Vector3[2];return t.copyFrom(_.direction),t.normalize(),t.scaleInPlace(o),_.origin.addToRef(t,h),e.pickedPoint=math_vector_Vector3.TransformCoordinates(h,math_vector_TmpVectors.Matrix[0]),e}return null}multiIntersects(e,t,i){let r;let s=Math.min(this.capacity,this.sprites.length),a=math_vector_Vector3.Zero(),n=math_vector_Vector3.Zero(),o=[],l=math_vector_TmpVectors.Vector3[0].copyFromFloats(0,0,0),h=math_vector_TmpVectors.Vector3[1].copyFromFloats(0,0,0),c=t.getViewMatrix();for(let t=0;t<s;t++){let s=this.sprites[t];if(s){if(i){if(!i(s))continue}else if(!s.isPickable)continue;if(math_vector_Vector3.TransformCoordinatesToRef(s.position,c,h),a.copyFromFloats(h.x-s.width/2,h.y-s.height/2,h.z),n.copyFromFloats(h.x+s.width/2,h.y+s.height/2,h.z),e.intersectsBoxMinMax(a,n)){if(r=math_vector_Vector3.Distance(h,e.origin),!this._checkTextureAlpha(s,e,r,a,n))continue;let t=new PickingInfo;o.push(t),c.invertToRef(math_vector_TmpVectors.Matrix[0]),t.hit=!0,t.pickedSprite=s,t.distance=r;let i=math_vector_TmpVectors.Vector3[2];i.copyFrom(e.direction),i.normalize(),i.scaleInPlace(r),e.origin.addToRef(i,l),t.pickedPoint=math_vector_Vector3.TransformCoordinates(l,math_vector_TmpVectors.Matrix[0])}}}return o}render(){if(this._fromPacked&&(!this._packedAndReady||!this._spriteMap||!this._cellData))return;let e=this._scene.getEngine(),t=e.getDeltaTime();this._packedAndReady?this._spriteRenderer.render(this.sprites,t,this._scene.getViewMatrix(),this._scene.getProjectionMatrix(),this._customUpdate):this._spriteRenderer.render(this.sprites,t,this._scene.getViewMatrix(),this._scene.getProjectionMatrix())}rebuild(){var e;null===(e=this._spriteRenderer)||void 0===e||e.rebuild()}dispose(){if(this._spriteRenderer&&(this._spriteRenderer.dispose(),this._spriteRenderer=null),this._textureContent=null,this._scene.spriteManagers){let e=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(e,1)}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null}serialize(e=!1){let t={};for(let i of(t.name=this.name,t.capacity=this.capacity,t.cellWidth=this.cellWidth,t.cellHeight=this.cellHeight,t.fogEnabled=this.fogEnabled,t.blendMode=this.blendMode,t.disableDepthWrite=this.disableDepthWrite,t.pixelPerfect=this.pixelPerfect,this.texture&&(e?t.texture=this.texture.serialize():(t.textureUrl=this.texture.name,t.invertY=this.texture._invertY)),t.sprites=[],this.sprites))t.sprites.push(i.serialize());return t.metadata=this.metadata,t}static Parse(e,t,i){let r=new spriteManager_SpriteManager(e.name,"",e.capacity,{width:e.cellWidth,height:e.cellHeight},t);for(let s of(void 0!==e.fogEnabled&&(r.fogEnabled=e.fogEnabled),void 0!==e.blendMode&&(r.blendMode=e.blendMode),void 0!==e.disableDepthWrite&&(r.disableDepthWrite=e.disableDepthWrite),void 0!==e.pixelPerfect&&(r.pixelPerfect=e.pixelPerfect),void 0!==e.metadata&&(r.metadata=e.metadata),e.texture?r.texture=texture_Texture.Parse(e.texture,t,i):e.textureName&&(r.texture=new texture_Texture(i+e.textureUrl,t,!1,void 0===e.invertY||e.invertY)),e.sprites))Sprite.Parse(s,r);return r}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,a)=>{let n=new webRequest_WebRequest;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let t=JSON.parse(n.responseText),a=spriteManager_SpriteManager.Parse(t,i||engineStore_EngineStore.LastCreatedScene,r);e&&(a.name=e),s(a)}else a("Unable to load the sprite manager")}}),n.open("GET",t),n.send()})}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new spriteManager_SpriteManager("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((r,s)=>{let a=new webRequest_WebRequest;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let s=JSON.parse(JSON.parse(a.responseText).jsonPayload),n=JSON.parse(s.spriteManager),o=spriteManager_SpriteManager.Parse(n,t||engineStore_EngineStore.LastCreatedScene,i);o.snippetId=e,r(o)}else s("Unable to load the snippet "+e)}}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}};spriteManager_SpriteManager.SnippetUrl="https://snippet.babylonjs.com",spriteManager_SpriteManager.CreateFromSnippetAsync=spriteManager_SpriteManager.ParseFromSnippetAsync;let om=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4( +texture2D(frameMap,vec2(fX,0.),0.), +texture2D(frameMap,vec2(fX,fdStep*1.),0.), +texture2D(frameMap,vec2(fX,fdStep*2.),0.), +vec4(0.) +);} +void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV); +#ifdef FLIPU +tileUV.y=1.0-tileUV.y; +#endif +vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i<LAYERS; i++) {float frameID; +#define LAYER_ID_SWITCH +vec4 animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,0.),0.);if(animationData.y>0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; f<MAX_ANIMATION_FRAMES; f++){if(animationData.y>mt){frameID=animationData.x;break;} +animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}} +mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;} +vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} +color.xyz*=colorMul;gl_FragColor=color;}`;ShaderStore.ShadersStore.spriteMapPixelShader=om;let og=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; +gl_Position=worldViewProjection*p;}`;ShaderStore.ShadersStore.spriteMapVertexShader=og,function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(it||(it={})),observable_Observable.prototype.notifyObserversWithPromise=async function(e,t=-1,i,r,s){let a=Promise.resolve(e);if(!this.observers.length)return a;let n=this._eventState;return n.mask=t,n.target=i,n.currentTarget=r,n.skipNextObservers=!1,n.userInfo=s,this.observers.forEach(i=>{!n.skipNextObservers&&!i._willBeUnregistered&&i.mask&t&&(a=i.scope?a.then(t=>(n.lastReturnValue=t,i.callback.apply(i.scope,[e,n]))):a.then(t=>(n.lastReturnValue=t,i.callback(e,n))),i.unregisterOnNextCall&&this._deferUnregister(i))}),await a,e};let SceneOptimization=class SceneOptimization{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}};let MergeMeshesOptimization=class MergeMeshesOptimization extends SceneOptimization{constructor(){super(...arguments),this._canBeMerged=e=>e instanceof mesh_Mesh&&!e.isDisposed()&&!!e.isVisible&&!!e.isEnabled()&&!(e.instances.length>0)&&!e.skeleton&&!e.hasLODLevels&&0!==e.getTotalVertices()}static get UpdateSelectionTree(){return MergeMeshesOptimization._UpdateSelectionTree}static set UpdateSelectionTree(e){MergeMeshesOptimization._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){let r=e.meshes.slice(0),s=r.length;for(let e=0;e<s;e++){let t=[],i=r[e];if(this._canBeMerged(i)){t.push(i);for(let a=e+1;a<s;a++){let e=r[a];this._canBeMerged(e)&&e.material===i.material&&e.checkCollisions===i.checkCollisions&&(t.push(e),s--,r.splice(a,1),a--)}t.length<2||mesh_Mesh.MergeMeshes(t,void 0,!0)}}return e.createOrUpdateSelectionOctree&&(void 0!=i?i&&e.createOrUpdateSelectionOctree():MergeMeshesOptimization.UpdateSelectionTree&&e.createOrUpdateSelectionOctree()),!0}};MergeMeshesOptimization._UpdateSelectionTree=!1;let ov=[],SerializeGeometry=(e,t)=>{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),ov[e.id]=!0)},SerializeMesh=(e,t)=>{let i={},r=e._geometry;return r&&!e.getScene().getGeometryById(r.id)&&SerializeGeometry(r,t.geometries),e.serialize&&e.serialize(i),i},FinalizeSingleNode=(e,t)=>{if(e._isMesh){if(1===e.delayLoadState||0===e.delayLoadState){let serializeMaterial=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 multiMaterial_MultiMaterial){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some(t=>t.id===e.material.id))for(let i of(t.multiMaterials.push(e.material.serialize()),e.material.subMaterials))i&&serializeMaterial(i)}else serializeMaterial(e.material)}else e.material||serializeMaterial(e.getScene().defaultMaterial);let i=e._geometry;i&&(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=[]),SerializeGeometry(i,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(SerializeMesh(e,t))}}else"TransformNode"===e.getClassName()?t.transformNodes.push(e.serialize()):-1!==e.getClassName().indexOf("Camera")?t.cameras.push(e.serialize()):-1!==e.getClassName().indexOf("Light")&&t.lights.push(e.serialize())};let sceneSerializer_SceneSerializer=class sceneSerializer_SceneSerializer{static ClearCache(){ov=[]}static Serialize(e){return sceneSerializer_SceneSerializer._Serialize(e)}static _Serialize(e,t=!0){let i,r,s;let a={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&texture_Texture.ForceSerializeBuffers&&console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),sceneSerializer_SceneSerializer.ClearCache(),a.useDelayedTextureLoading=e.useDelayedTextureLoading,a.autoClear=e.autoClear,a.clearColor=e.clearColor.asArray(),a.ambientColor=e.ambientColor.asArray(),a.gravity=e.gravity.asArray(),a.collisionsEnabled=e.collisionsEnabled,a.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(a.fogMode=e.fogMode,a.fogColor=e.fogColor.asArray(),a.fogStart=e.fogStart,a.fogEnd=e.fogEnd,a.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){let t=e.getPhysicsEngine();t&&(a.physicsEnabled=!0,a.physicsGravity=t.gravity.asArray(),a.physicsEngine=t.getPhysicsPluginName())}for(let t of(e.metadata&&(a.metadata=e.metadata),a.morphTargetManagers=[],e.meshes)){let e=t.morphTargetManager;e&&a.morphTargetManagers.push(e.serialize())}for(i=0,a.lights=[];i<e.lights.length;i++)(r=e.lights[i]).doNotSerialize||a.lights.push(r.serialize());for(i=0,a.cameras=[];i<e.cameras.length;i++){let t=e.cameras[i];t.doNotSerialize||a.cameras.push(t.serialize())}if(e.activeCamera&&(a.activeCameraID=e.activeCamera.id),decorators_SerializationHelper.AppendSerializedAnimations(e,a),e.animationGroups&&e.animationGroups.length>0){a.animationGroups=[];for(let t=0;t<e.animationGroups.length;t++){let i=e.animationGroups[t];a.animationGroups.push(i.serialize())}}if(e.reflectionProbes&&e.reflectionProbes.length>0)for(i=0,a.reflectionProbes=[];i<e.reflectionProbes.length;i++){let t=e.reflectionProbes[i];a.reflectionProbes.push(t.serialize())}for(i=0,a.materials=[],a.multiMaterials=[];i<e.materials.length;i++)(s=e.materials[i]).doNotSerialize||a.materials.push(s.serialize());for(i=0,a.multiMaterials=[];i<e.multiMaterials.length;i++){let t=e.multiMaterials[i];a.multiMaterials.push(t.serialize())}for(e.environmentTexture&&(e.environmentTexture._files?a.environmentTexture=e.environmentTexture.serialize():(a.environmentTexture=e.environmentTexture.name,a.environmentTextureRotationY=e.environmentTexture.rotationY)),a.environmentIntensity=e.environmentIntensity,a.skeletons=[],i=0;i<e.skeletons.length;i++){let t=e.skeletons[i];t.doNotSerialize||a.skeletons.push(t.serialize())}for(i=0,a.transformNodes=[];i<e.transformNodes.length;i++)e.transformNodes[i].doNotSerialize||a.transformNodes.push(e.transformNodes[i].serialize());a.geometries={},a.geometries.boxes=[],a.geometries.spheres=[],a.geometries.cylinders=[],a.geometries.toruses=[],a.geometries.grounds=[],a.geometries.planes=[],a.geometries.torusKnots=[],a.geometries.vertexData=[],ov=[];let n=e.getGeometries();for(i=0;i<n.length;i++){let e=n[i];e.isReady()&&SerializeGeometry(e,a.geometries)}for(i=0,a.meshes=[];i<e.meshes.length;i++){let t=e.meshes[i];t instanceof mesh_Mesh&&!t.doNotSerialize&&(1===t.delayLoadState||0===t.delayLoadState)&&a.meshes.push(SerializeMesh(t,a))}for(i=0,a.particleSystems=[];i<e.particleSystems.length;i++)a.particleSystems.push(e.particleSystems[i].serialize(!1));for(i=0,a.postProcesses=[];i<e.postProcesses.length;i++)a.postProcesses.push(e.postProcesses[i].serialize());for(let t of(e.actionManager&&(a.actions=e.actionManager.serialize("scene")),e._serializableComponents))t.serialize(a);return a}static SerializeAsync(e){let t=sceneSerializer_SceneSerializer._Serialize(e,!1),i=[];return this._CollectPromises(t,i),Promise.all(i).then(()=>t)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;i<e.length;++i){let r=e[i];r instanceof Promise?t.push(r.then(t=>e[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object){for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];r instanceof Promise?t.push(r.then(t=>e[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}}static SerializeMesh(e,t=!1,i=!1){let r={};if(r.meshes=[],r.transformNodes=[],r.cameras=[],r.lights=[],sceneSerializer_SceneSerializer.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let r=0;r<e.length;++r)i&&e[r].getDescendants().forEach(t=>{0>e.indexOf(t)&&!t.doNotSerialize&&e.push(t)}),t&&e[r].parent&&0>e.indexOf(e[r].parent)&&!e[r].parent.doNotSerialize&&e.push(e[r].parent);return e.forEach(e=>{FinalizeSingleNode(e,r)}),r}};let VideoRecorder=class VideoRecorder{static IsSupported(e){let t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!VideoRecorder.IsSupported(e))throw"Your browser does not support recording so far.";let 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({},VideoRecorder._DefaultOptions),t);let r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(let e of this._options.audioTracks)r.addTrack(e);this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._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)this._reject(e.error);else throw new e.error}_handleStop(){this.stopRecording();let e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&tools_Tools.Download(e,this._fileName)}};VideoRecorder._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let ox=null;function CreateScreenshot(e,t,i,r,s="image/png",a=!1,n){let{height:o,width:l}=_GetScreenshotSize(e,t,i);if(!(o&&l)){logger_Logger.Error("Invalid 'size' parameter !");return}ox||(ox=document.createElement("canvas")),ox.width=l,ox.height=o;let h=ox.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight(),u=l,d=u/c;d>o&&(u=(d=o)*c);let _=Math.max(0,l-u)/2,p=Math.max(0,o-d)/2,f=t.getScene();f.activeCamera!==t?CreateScreenshotUsingRenderTarget(e,t,i,e=>{if(a){let t=new Blob([e]);tools_Tools.DownloadBlob(t),r&&r("")}else r&&r(e)},s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,n):e.onEndFrameObservable.addOnce(()=>{let t=e.getRenderingCanvas();h&&t&&h.drawImage(t,_,p,u,d),ox&&(a?(tools_Tools.EncodeScreenshotCanvasData(ox,void 0,s,void 0,n),r&&r("")):tools_Tools.EncodeScreenshotCanvasData(ox,r,s,void 0,n))})}function CreateScreenshotAsync(e,t,i,r="image/png",s){return new Promise((a,n)=>{CreateScreenshot(e,t,i,e=>{void 0!==e?a(e):n(Error("Data is undefined"))},r,void 0,s)})}function CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",a=1,n=!1,o,l=!1,h=!1,c=!0,u,d){let{height:_,width:p,finalWidth:f,finalHeight:m}=_GetScreenshotSize(e,t,i);if(!(_&&p)){logger_Logger.Error("Invalid 'size' parameter !");return}let g={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(p,_);let v=t.getScene(),x=new renderTargetTexture_RenderTargetTexture("screenShot",{width:p,height:_},v,!1,!1,0,!1,texture_Texture.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,a);x.renderList=v.meshes.slice(),x.samples=a,x.renderSprites=l,x.activeCamera=t,x.forceLayerMaskCheck=c,null==d||d(x);let renderWhenReady=()=>{x.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce(()=>{f===p&&m===_?x.readPixels(void 0,void 0,void 0,!1).then(e=>{dumpTools_DumpTools.DumpData(p,_,e,r,s,o,!0,void 0,u),x.dispose()}):ApplyPostProcess("pass",x.getInternalTexture(),v,void 0,void 0,void 0,f,m).then(t=>{e._readTexturePixels(t,f,m,-1,0,null,!0,!1,0,0).then(e=>{dumpTools_DumpTools.DumpData(f,m,e,r,s,o,!0,void 0,u),t.dispose()})})}),x.render(!0),v.incrementRenderId(),v.resetCachedMaterial(),e.setSize(g.width,g.height),t.getProjectionMatrix(!0),v.render()):setTimeout(renderWhenReady,16)},renderToTexture=()=>{v.incrementRenderId(),v.resetCachedMaterial(),renderWhenReady()};if(n){let e=new FxaaPostProcess("antialiasing",1,v.activeCamera);x.addPostProcess(e),e.getEffect().isReady()?renderToTexture():e.getEffect().onCompiled=()=>{renderToTexture()}}else renderToTexture()}function CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,a=!1,n,o=!1,l=!1,h=!0,c){return new Promise((u,d)=>{CreateScreenshotUsingRenderTarget(e,t,i,e=>{void 0!==e?u(e):d(Error("Data is undefined"))},r,s,a,n,o,l,h,c)})}function _GetScreenshotSize(e,t,i){let r=0,s=0,a=0,n=0;if("object"==typeof i){let o=i.precision?Math.abs(i.precision):1;i.width&&i.height?(r=i.height*o,s=i.width*o):i.width&&!i.height?r=Math.round((s=i.width*o)/e.getAspectRatio(t)):i.height&&!i.width?s=Math.round((r=i.height*o)*e.getAspectRatio(t)):r=Math.round((s=Math.round(e.getRenderWidth()*o))/e.getAspectRatio(t)),i.finalWidth&&i.finalHeight?(n=i.finalHeight,a=i.finalWidth):i.finalWidth&&!i.finalHeight?n=Math.round((a=i.finalWidth)/e.getAspectRatio(t)):i.finalHeight&&!i.finalWidth?a=Math.round((n=i.finalHeight)*e.getAspectRatio(t)):(a=s,n=r)}else isNaN(i)||(r=i,s=i,a=i,n=i);return s&&(s=Math.floor(s)),r&&(r=Math.floor(r)),a&&(a=Math.floor(a)),n&&(n=Math.floor(n)),{height:0|r,width:0|s,finalWidth:0|a,finalHeight:0|n}}tools_Tools.CreateScreenshot=CreateScreenshot,tools_Tools.CreateScreenshotAsync=CreateScreenshotAsync,tools_Tools.CreateScreenshotUsingRenderTarget=CreateScreenshotUsingRenderTarget,tools_Tools.CreateScreenshotUsingRenderTargetAsync=CreateScreenshotUsingRenderTargetAsync,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"}(ii||(ii={}));let DataStorage=class DataStorage{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(t){let e={};return{getItem:t=>{let i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){let i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){let 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){let i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}};DataStorage._Storage=DataStorage._GetStorage(),function(e){let Alphabet=class Alphabet{serialize(){let e={},t=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){let t=JSON.parse(e),i=new Alphabet(t.characters);return i._insertionCosts=t.insertionCosts,i._deletionCosts=t.deletionCosts,i._substitutionCosts=t.substitutionCosts,i}constructor(e,t=null,i=null,r=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,r=null!=r?r:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=Array(e.length),this._deletionCosts=Array(e.length),this._substitutionCosts=Array(e.length);for(let a=0;a<e.length;++a){s=e[a],this._characterToIdx.set(s,a),this._insertionCosts[a]=t(s),this._deletionCosts[a]=i(s),this._substitutionCosts[a]=Array(e.length);for(let t=a;t<e.length;++t)this._substitutionCosts[a][t]=r(s,e[t])}}getCharacterIdx(e){return this._characterToIdx.get(e)}getInsertionCost(e){return this._insertionCosts[e]}getDeletionCost(e){return this._deletionCosts[e]}getSubstitutionCost(e,t){return this._substitutionCosts[Math.min(e,t)][Math.max(e,t)]}};e.Alphabet=Alphabet;let Sequence=class Sequence{serialize(){return JSON.stringify(this._characters)}static Deserialize(e,t){let i=new Sequence([],t);return i._characters=JSON.parse(e),i}constructor(e,t){if(e.length>Sequence._MAX_SEQUENCE_LENGTH)throw Error("Sequences longer than "+Sequence._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map(e=>this._alphabet.getCharacterIdx(e))}distance(e){return Sequence._Distance(this,e)}static _Distance(e,t){let i=e._alphabet;if(i!==t._alphabet)throw Error("Cannot Levenshtein compare Sequences built from different alphabets.");let r=e._characters,s=t._characters,a=r.length,n=s.length,o=Sequence._CostMatrix;o[0][0]=0;for(let e=0;e<a;++e)o[e+1][0]=o[e][0]+i.getInsertionCost(r[e]);for(let e=0;e<n;++e)o[0][e+1]=o[0][e]+i.getInsertionCost(s[e]);for(let e=0;e<a;++e)for(let t=0;t<n;++t)Sequence._InsertionCost=o[e+1][t]+i.getInsertionCost(s[t]),Sequence._DeletionCost=o[e][t+1]+i.getDeletionCost(r[e]),Sequence._SubstitutionCost=o[e][t]+i.getSubstitutionCost(r[e],s[t]),o[e+1][t+1]=Math.min(Sequence._InsertionCost,Sequence._DeletionCost,Sequence._SubstitutionCost);return o[a][n]}};Sequence._MAX_SEQUENCE_LENGTH=256,Sequence._CostMatrix=[...Array(Sequence._MAX_SEQUENCE_LENGTH+1)].map(()=>Array(Sequence._MAX_SEQUENCE_LENGTH+1)),e.Sequence=Sequence}(ir||(ir={}));let Trajectory=class Trajectory{serialize(){return JSON.stringify(this)}static Deserialize(e){let t=JSON.parse(e),i=new Trajectory(t._segmentLength);return i._points=t._points.map(e=>new math_vector_Vector3(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{let getT=()=>this._segmentLength/math_vector_Vector3.Distance(this._points[t-1],e);for(let i=getT();i<=1;i=getT()){let r=this._points[t-1].scale(1-i);e.scaleAndAddToRef(i,r),this._points.push(r),++t}}}resampleAtTargetResolution(e){let t=new Trajectory(this.getLength()/e);return this._points.forEach(e=>{t.add(e)}),t}tokenize(e){let t=[],i=new math_vector_Vector3;for(let r=2;r<this._points.length;++r)Trajectory._TransformSegmentDirToRef(this._points[r-2],this._points[r-1],this._points[r],i)&&t.push(Trajectory._TokenizeSegment(i,e));return t}static _TransformSegmentDirToRef(e,t,i,r){return t.subtractToRef(e,Trajectory._ForwardDir),Trajectory._ForwardDir.normalize(),t.scaleToRef(-1,Trajectory._InverseFromVec),Trajectory._InverseFromVec.normalize(),!(Math.abs(math_vector_Vector3.Dot(Trajectory._ForwardDir,Trajectory._InverseFromVec))>.98)&&(math_vector_Vector3.CrossToRef(Trajectory._ForwardDir,Trajectory._InverseFromVec,Trajectory._UpDir),Trajectory._UpDir.normalize(),math_vector_Matrix.LookAtLHToRef(e,t,Trajectory._UpDir,Trajectory._LookMatrix),i.subtractToRef(t,Trajectory._FromToVec),Trajectory._FromToVec.normalize(),math_vector_Vector3.TransformNormalToRef(Trajectory._FromToVec,Trajectory._LookMatrix,r),!0)}static _TokenizeSegment(e,t){Trajectory._BestMatch=0,Trajectory._Score=math_vector_Vector3.Dot(e,t[0]),Trajectory._BestScore=Trajectory._Score;for(let i=1;i<t.length;++i)Trajectory._Score=math_vector_Vector3.Dot(e,t[i]),Trajectory._Score>Trajectory._BestScore&&(Trajectory._BestMatch=i,Trajectory._BestScore=Trajectory._Score);return Trajectory._BestMatch}};Trajectory._ForwardDir=new math_vector_Vector3,Trajectory._InverseFromVec=new math_vector_Vector3,Trajectory._UpDir=new math_vector_Vector3,Trajectory._FromToVec=new math_vector_Vector3,Trajectory._LookMatrix=new math_vector_Matrix;let TrajectoryDescriptor=class TrajectoryDescriptor{serialize(){return JSON.stringify(this._sequences.map(e=>e.serialize()))}static Deserialize(e,t){let i=new TrajectoryDescriptor;return i._sequences=JSON.parse(e).map(e=>ir.Sequence.Deserialize(e,t)),i}static CreateFromTrajectory(e,t,i){return TrajectoryDescriptor.CreateFromTokenizationPyramid(TrajectoryDescriptor._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){let i=new TrajectoryDescriptor;return i._sequences=e.map(e=>new ir.Sequence(e,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION){let r=[];for(let s=i;s>4;s=Math.floor(s/2))r.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return r}distance(e){let t=0;for(let i=0;i<this._sequences.length;++i)t+=Math.pow(2,i)*this._sequences[i].distance(e._sequences[i]);return t}};TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION=32;let TrajectoryClass=class TrajectoryClass{serialize(){let e={};return e.descriptors=this._descriptors.map(e=>e.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){let i=JSON.parse(e),r=new TrajectoryClass;return r._descriptors=i.descriptors.map(e=>TrajectoryDescriptor.Deserialize(e,t)),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map(t=>t.distance(e)))}_refreshDescription(){let e;this._centroidIdx=-1;let t=this._descriptors.map(t=>(e=0,this._descriptors.forEach(i=>{e+=t.distance(i)}),e));for(let e=0;e<t.length;++e)(this._centroidIdx<0||t[e]<t[this._centroidIdx])&&(this._centroidIdx=e);this._averageDistance=0,this._descriptors.forEach(e=>{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])}),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,TrajectoryClass._MIN_AVERAGE_DISTANCE))}};TrajectoryClass._MIN_AVERAGE_DISTANCE=1;let Reflector=class Reflector{constructor(e,t,i){this._scene=e,logger_Logger.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{let t=e.data;if(t.startsWith(Reflector._SERVER_PREFIX)){let e=t.substr(Reflector._SERVER_PREFIX.length);logger_Logger.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),this._handleServerMessage(e);return}logger_Logger.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{logger_Logger.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&sceneSerializer_SceneSerializer.SerializeAsync(this._scene).then(e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)})}_handleClientMessage(){}};Reflector._SERVER_PREFIX="$$";let DynamicFloat32Array=class DynamicFloat32Array{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(){let e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}};let ob="timestamp",oT="numPoints",oS=/\r/g;let PerformanceViewerCollector=class PerformanceViewerCollector{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{let e=precisionDate_PrecisionDate.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength,r=0;if(i>0){let e=this.datasets.startingIndices.at(i-1);r=e+this.datasets.data.at(e+PerformanceViewerCollector.NumberOfPointsOffset)+PerformanceViewerCollector.SliceDataOffset}if(this.datasets.startingIndices.push(r),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())}),this.datasetObservable.hasObservers()){let i=[e,t];for(let e=0;e<t;e++)i.push(this.datasets.data.at(r+PerformanceViewerCollector.SliceDataOffset+e));this.datasetObservable.notifyObservers(i)}},this.datasets={ids:[],data:new DynamicFloat32Array(1800),startingIndices:new DynamicFloat32Array(1800)},this._strategies=new Map,this._datasetMeta=new Map,this._eventRestoreSet=new Set,this._customEventObservable=new observable_Observable,this.datasetObservable=new observable_Observable,this.metadataObservable=new observable_Observable(e=>e.callback(this._datasetMeta,new EventState(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var r;return this._strategies.has(e)&&!t?void 0:(this._strategies.has(e)&&t&&(null===(r=this._strategies.get(e))||void 0===r||r.dispose(),this._strategies.delete(e)),this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,r=0,s=t.onAfterRenderObservable.add(()=>{r=i,i=0}),a=this._customEventObservable.add(t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)});return{id:e,getData:()=>r,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(a)}}},category:i}),{name:e})}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach(e=>{this.registerEvent(e,!0)})}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:r}of e){let e=t(this._scene);if(this._strategies.has(e.id)){e.dispose();continue}this.datasets.ids.push(e.id),i&&(i=i.replace(RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:r}),this._strategies.set(e.id,e)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);let i="#";for(let e=0;e<24;e+=8){let r=t>>e&255;i+=("0"+r.toString(16)).substr(-2)}return i}getCurrentSlice(){let e=precisionDate_PrecisionDate.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasetObservable.hasObservers()&&i.push(t.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){let r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new DynamicFloat32Array(1800),this.datasets.ids.length=0,this.datasets.startingIndices=new DynamicFloat32Array(1800),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){let i=e.replace(oS,"").split("\n").map(e=>e.split(",").filter(e=>e.length>0)).filter(e=>e.length>0),r=PerformanceViewerCollector.NumberOfPointsOffset;if(i.length<2)return!1;let s={ids:[],data:new DynamicFloat32Array(1800),startingIndices:new DynamicFloat32Array(1800)},[a,...n]=i;if(a.length<2||a[0]!==ob||a[r]!==oT)return!1;let o=new Map;for(let e=PerformanceViewerCollector.SliceDataOffset;e<a.length;e++){let[t,i]=a[e].split("@");s.ids.push(t),o.set(t,i)}let l=0;for(let e of n){if(e.length<2)return!1;let t=parseFloat(e[0]),i=parseInt(e[r]);if(isNaN(i)||isNaN(t)||(s.data.push(t),s.data.push(i),i+PerformanceViewerCollector.SliceDataOffset!==e.length))return!1;for(let t=PerformanceViewerCollector.SliceDataOffset;t<e.length;t++){let i=parseFloat(e[t]);if(isNaN(i))return!1;s.data.push(i)}s.startingIndices.push(l),l+=e.length}if(this.datasets.ids=s.ids,this.datasets.data=s.data,this.datasets.startingIndices=s.startingIndices,t||this._datasetMeta.clear(),this._strategies.forEach(e=>e.dispose()),this._strategies.clear(),!t)for(let e of this.datasets.ids){let t=o.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${ob},${oT}`;for(let t=0;t<this.datasets.ids.length;t++)if(e+=`,${this.datasets.ids[t]}`,this._datasetMeta){let i=this._datasetMeta.get(this.datasets.ids[t]);(null==i?void 0:i.category)&&(e+=`@${i.category}`)}e+="\n";for(let t=0;t<this.datasets.startingIndices.itemLength;t++){let i=this.datasets.startingIndices.at(t),r=this.datasets.data.at(i),s=this.datasets.data.at(i+PerformanceViewerCollector.NumberOfPointsOffset);e+=`${r},${s}`;for(let t=0;t<s;t++)e+=`,${this.datasets.data.at(i+PerformanceViewerCollector.SliceDataOffset+t)}`;for(let t=0;t<this.datasets.ids.length-s;t++)e+=",";e+="\n"}let t=`${new Date().toISOString()}-perfdata.csv`;tools_Tools.Download(new Blob([e],{type:"text/csv"}),t)}start(e){e?void 0===this._startingTimestamp&&(this._startingTimestamp=precisionDate_PrecisionDate.Now):(this.datasets.data=new DynamicFloat32Array(1800),this.datasets.startingIndices=new DynamicFloat32Array(1800),this._startingTimestamp=precisionDate_PrecisionDate.Now),this._scene.onAfterRenderObservable.add(this._collectDataAtFrame),this._restoreStringEvents(),this._isStarted=!0}stop(){this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame),this._isStarted=!1}get isStarted(){return this._isStarted}dispose(){this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame),this._datasetMeta.clear(),this._strategies.forEach(e=>{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}};function CreateObservableScheduler(e){let t=[],i=[],r=[],s=e.add(()=>{let e=t.length;for(let s=0;s<e;s++)inlineScheduler(t.shift(),i.shift(),r.shift())});return{scheduler:(e,s,a)=>{t.push(e),i.push(s),r.push(a)},dispose:()=>{e.remove(s)}}}scene_Scene.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new PerformanceViewerCollector(this)),this._perfCollector},observable_Observable.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){let e=CreateObservableScheduler(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return runCoroutineAsync(e,this._coroutineScheduler)},observable_Observable.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};let oC=`#ifdef GL_ES +precision highp float; +#endif +#define M_PI 3.1415926535897932384626433832795 +varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3( +- sin( longitude )*sin( latitude ), +cos( latitude ), +- cos( longitude )*sin( latitude ) +);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;ShaderStore.ShadersStore.equirectangularPanoramaPixelShader=oC;let WebXRHitTestLegacy=class WebXRHitTestLegacy extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this._direction=new math_vector_Vector3(0,0,-1),this._mat=new math_vector_Matrix,this._onSelectEnabled=!1,this._origin=new math_vector_Vector3(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new observable_Observable,this._onHitTestResults=e=>{let t=e.map(e=>{let t=math_vector_Matrix.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&&WebXRHitTestLegacy.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",tools_Tools.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then(e=>{let t=r||(e=>!!e.hitMatrix);return e.filter(t)})}static XRHitTestWithSelectEvent(e,t){let i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);let r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;math_vector_Matrix.FromArrayToRef(t.transform.matrix,0,this._mat),math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();let 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});WebXRHitTestLegacy.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}};WebXRHitTestLegacy.Name=webXRFeaturesManager_WebXRFeatureName.HIT_TEST,WebXRHitTestLegacy.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRHitTestLegacy.Name,(e,t)=>()=>new WebXRHitTestLegacy(e,t),WebXRHitTestLegacy.Version,!1);let oE=0;let WebXRAnchorSystem=class WebXRAnchorSystem extends WebXRAbstractFeature{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 observable_Observable,this.onAnchorRemovedObservable=new observable_Observable,this.onAnchorUpdatedObservable=new observable_Observable,this._tmpVector=new math_vector_Vector3,this._tmpQuaternion=new math_vector_Quaternion,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 math_vector_Vector3,i=new math_vector_Quaternion){this._populateTmpTransformation(t,i);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(e.xrHitResult.createAnchor)try{let t=await e.xrHitResult.createAnchor(r);return new Promise((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:r,resolve:e,reject:i})})}catch(e){throw Error(e)}else throw this.detach(),Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new math_vector_Quaternion,i=!1){this._populateTmpTransformation(e,t);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:r,resolve:e,reject:t})})}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){let e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;let t=e.trackedAnchors;if(t){let i=this._trackedAnchors.filter(e=>!t.has(e.xrAnchor)).map(e=>{let t=this._trackedAnchors.indexOf(e);return t}),r=0;i.forEach(e=>{let t=this._trackedAnchors.splice(e-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),r++}),t.forEach(t=>{if(this._lastFrameDetected.has(t)){let i=this._findIndexInAnchorArray(t),r=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,r,e),r.attachedNode&&(r.attachedNode.rotationQuaternion=r.attachedNode.rotationQuaternion||new math_vector_Quaternion,r.transformationMatrix.decompose(r.attachedNode.scaling,r.attachedNode.rotationQuaternion,r.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(r)}catch(e){tools_Tools.Warn("Anchor could not be updated")}}else{let i={id:oE++,xrAnchor:t,remove:()=>t.delete()},r=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(r),this.onAnchorAddedObservable.notifyObservers(r);let s=this._futureAnchors.filter(e=>e.nativeAnchor===t),a=s[0];a&&(a.resolve(r),a.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<this._trackedAnchors.length;++t)if(this._trackedAnchors[t].xrAnchor===e)return t;return -1}_updateAnchorWithXRFrame(e,t,i){let r=i.getPose(e.anchorSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new math_vector_Matrix;math_vector_Matrix.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}async _createAnchorAtTransformation(e,t){var i;if(t.createAnchor)try{return t.createAnchor(e,null!==(i=this._referenceSpaceForFrameAnchors)&&void 0!==i?i:this._xrSessionManager.referenceSpace)}catch(e){throw Error(e)}else throw this.detach(),Error("Anchors are not enabled in your browser")}};WebXRAnchorSystem.Name=webXRFeaturesManager_WebXRFeatureName.ANCHOR_SYSTEM,WebXRAnchorSystem.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRAnchorSystem.Name,(e,t)=>()=>new WebXRAnchorSystem(e,t),WebXRAnchorSystem.Version);let oy=0;let WebXRPlaneDetector=class WebXRPlaneDetector extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new observable_Observable,this.onPlaneRemovedObservable=new observable_Observable,this.onPlaneUpdatedObservable=new observable_Observable,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;){let e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){var t;if(!this.attached||!this._enabled||!e)return;let i=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(i){for(let e=0;e<this._detectedPlanes.length;e++){let t=this._detectedPlanes[e];i.has(t.xrPlane)||(this._detectedPlanes.splice(e--,1),this.onPlaneRemovedObservable.notifyObservers(t))}i.forEach(t=>{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._findIndexInPlaneArray(t),r=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,r,e),this.onPlaneUpdatedObservable.notifyObservers(r)}}else{let i={id:oy++,xrPlane:t,polygonDefinition:[]},r=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(r),this.onPlaneAddedObservable.notifyObservers(r)}}),this._lastFrameDetected=i}}_init(){let internalInit=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};if(this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),!this._xrSessionManager.session.updateWorldTrackingState){internalInit();return}this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),internalInit()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map(e=>{let t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new math_vector_Vector3(e.x,e.y,e.z*t)});let r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new math_vector_Matrix;math_vector_Matrix.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t<this._detectedPlanes.length;++t)if(this._detectedPlanes[t].xrPlane===e)return t;return -1}};WebXRPlaneDetector.Name=webXRFeaturesManager_WebXRFeatureName.PLANE_DETECTION,WebXRPlaneDetector.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRPlaneDetector.Name,(e,t)=>()=>new WebXRPlaneDetector(e,t),WebXRPlaneDetector.Version);let WebXRBackgroundRemover=class WebXRBackgroundRemover extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new observable_Observable}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){let t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper){if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){let i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){let i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{let i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(t=>t.setEnabled(e)),this.onBackgroundStateChangedObservable.notifyObservers(e)}};WebXRBackgroundRemover.Name=webXRFeaturesManager_WebXRFeatureName.BACKGROUND_REMOVER,WebXRBackgroundRemover.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRBackgroundRemover.Name,(e,t)=>()=>new WebXRBackgroundRemover(e,t),WebXRBackgroundRemover.Version,!0);let WebXRControllerPhysics=class WebXRControllerPhysics extends WebXRAbstractFeature{_createPhysicsImpostor(e){let t=this._options.physicsProperties.impostorType||physicsImpostor_PhysicsImpostor.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=sphereBuilder_CreateSphere("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new math_vector_Quaternion;let s=e.grip||e.pointer;r.position.copyFrom(s.position),r.rotationQuaternion.copyFrom(s.rotationQuaternion);let a=new physicsImpostor_PhysicsImpostor(r,t,Object.assign({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:a,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||logger_Logger.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(()=>{let i=new physicsImpostor_PhysicsImpostor(t.rootMesh,physicsImpostor_PhysicsImpostor.MeshImpostor,Object.assign({mass:0},this._options.physicsProperties)),r=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:r.position.clone(),oldRotation:r.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new math_vector_Quaternion,this._tmpVector=new math_vector_Vector3,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach(e=>{let 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){let e=this._options.headsetImpostorParams||{impostorType:physicsImpostor_PhysicsImpostor.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=sphereBuilder_CreateSphere("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 math_vector_Quaternion,this._headsetMesh.isVisible=!1,this._headsetImpostor=new physicsImpostor_PhysicsImpostor(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){let 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){let 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){let 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;let r=this._controllers[e],s=r.xrController.grip||r.xrController.pointer,a=r.oldPos||r.impostorMesh.position;if(null===(t=r.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){let e=r.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setLinearVelocity(this._tmpVector)}else s.position.subtractToRef(a,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),r.impostor.setLinearVelocity(this._tmpVector);a.copyFrom(s.position),this._debugMode&&console.log(this._tmpVector,"linear");let n=r.oldRotation||r.impostorMesh.rotationQuaternion;if(null===(i=r.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){let e=r.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setAngularVelocity(this._tmpVector)}else if(!n.equalsWithEpsilon(s.rotationQuaternion)){n.conjugateInPlace().multiplyToRef(s.rotationQuaternion,this._tmpQuaternion);let 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{let t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}r.impostor.setAngularVelocity(this._tmpVector)}n.copyFrom(s.rotationQuaternion),this._debugMode&&console.log(this._tmpVector,this._tmpQuaternion,"angular")})}_detachController(e){let t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}};WebXRControllerPhysics.Name=webXRFeaturesManager_WebXRFeatureName.PHYSICS_CONTROLLERS,WebXRControllerPhysics.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPhysics.Name,(e,t)=>()=>new WebXRControllerPhysics(e,t),WebXRControllerPhysics.Version,!0);let WebXRHitTest=class WebXRHitTest extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new math_vector_Matrix,this._tmpPos=new math_vector_Vector3,this._tmpQuat=new math_vector_Quaternion,this._initHitTestSource=e=>{if(!e)return;let t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};if(this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),!i.space){tools_Tools.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(i).then(e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new observable_Observable,this.paused=!1,this.xrNativeFeatureName="hit-test",tools_Tools.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach()||!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){let 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){let t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}if(this._transientXrHitTestSource){let t=e.getHitTestResultsForTransientInput(this._transientXrHitTestSource);t.forEach(e=>{this._processWebXRHitTestResult(e.results,e.inputSource)})}}}_processWebXRHitTestResult(e,t){let i=[];e.forEach(e=>{let r=e.getPose(this._xrSessionManager.referenceSpace);if(!r)return;let s=r.transform.position,a=r.transform.orientation;this._tmpPos.set(s.x,s.y,s.z),this._tmpQuat.set(a.x,a.y,a.z,a.w),math_vector_Matrix.FromFloat32ArrayToRefScaled(r.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());let n={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(n)}),this.onHitTestResultObservable.notifyObservers(i)}};WebXRHitTest.Name=webXRFeaturesManager_WebXRFeatureName.HIT_TEST,WebXRHitTest.Version=2,WebXRFeaturesManager.AddWebXRFeature(WebXRHitTest.Name,(e,t)=>()=>new WebXRHitTest(e,t),WebXRHitTest.Version,!1);let WebXRFeaturePointSystem=class WebXRFeaturePointSystem extends WebXRAbstractFeature{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new observable_Observable,this.onFeaturePointsUpdatedObservable=new observable_Observable,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;let t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw Error("Received malformed feature point cloud of length: "+t.length);let e=t.length/5,i=[],r=[];for(let s=0;s<e;s++){let e=5*s,a=t[e+4];this._featurePointCloud[a]?i.push(a):(this._featurePointCloud[a]={position:new math_vector_Vector3,confidenceValue:0},r.push(a)),this._featurePointCloud[a].position.x=t[e],this._featurePointCloud[a].position.y=t[e+1],this._featurePointCloud[a].position.z=t[e+2],this._featurePointCloud[a].confidenceValue=t[e+3]}r.length>0&&this.onFeaturePointsAddedObservable.notifyObservers(r),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}};WebXRFeaturePointSystem.Name=webXRFeaturesManager_WebXRFeatureName.FEATURE_POINTS,WebXRFeaturePointSystem.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRFeaturePointSystem.Name,e=>()=>new WebXRFeaturePointSystem(e),WebXRFeaturePointSystem.Version);let oR=0;let WebXRMeshDetector=class WebXRMeshDetector extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new observable_Observable,this.onMeshRemovedObservable=new observable_Observable,this.onMeshUpdatedObservable=new observable_Observable,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;let i=null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes;if(i){let t=new Set;this._detectedMeshes.forEach((e,r)=>{i.has(r)||t.add(r)}),t.forEach(e=>{let 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){let i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{let i={id:oR++,xrMesh:t},r=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,r),this.onMeshAddedObservable.notifyObservers(r)}})}}catch(e){console.log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){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<e.positions.length;i+=3)t.positions[i]=e.positions[i],t.positions[i+1]=e.positions[i+1],t.positions[i+2]=-1*e.positions[i+2];if(e.normals){t.normals=new Float32Array(e.normals.length);for(let i=0;i<e.normals.length;i+=3)t.normals[i]=e.normals[i],t.normals[i+1]=e.normals[i+1],t.normals[i+2]=-1*e.normals[i+2]}}t.indices=e.indices;let r=i.getPose(e.meshSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new math_vector_Matrix;math_vector_Matrix.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}}return t}};WebXRMeshDetector.Name=webXRFeaturesManager_WebXRFeatureName.MESH_DETECTION,WebXRMeshDetector.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRMeshDetector.Name,(e,t)=>()=>new WebXRMeshDetector(e,t),WebXRMeshDetector.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(is||(is={}));let WebXRImageTracking=class WebXRImageTracking extends WebXRAbstractFeature{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new observable_Observable,this.onTrackableImageFoundObservable=new observable_Observable,this.onTrackedImageUpdatedObservable=new observable_Observable,this._trackableScoreStatus=is.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{};let e=this.options.images.map(e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src));try{let t=await Promise.all(e);return this._originalTrackingRequest=t.map((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch(e){return tools_Tools.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===is.Waiting)return;if(this._trackableScoreStatus===is.NotReceived){this._checkScoresAsync();return}let t=e.getImageTrackingResults();for(let i of t){let t=!1,r=i.index,s=this._trackedImages[r];if(!s)continue;s.xrTrackingResult=i,s.realWorldWidth!==i.measuredWidthInMeters&&(s.realWorldWidth=i.measuredWidthInMeters,t=!0);let a=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(a){let e=s.transformationMatrix;math_vector_Matrix.FromArrayToRef(a.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}let n=i.trackingState,o="emulated"===n;s.emulated!==o&&(s.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==is.NotReceived)return;this._trackableScoreStatus=is.Waiting;let e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||0===e.length){this._trackableScoreStatus=is.NotReceived;return}for(let t=0;t<e.length;++t)if("untrackable"==e[t])this.onUntrackableImageFoundObservable.notifyObservers(t);else{let e=this._originalTrackingRequest[t].image,i={id:t,originalBitmap:e,transformationMatrix:new math_vector_Matrix,ratio:e.width/e.height};this._trackedImages[t]=i,this.onTrackableImageFoundObservable.notifyObservers(i)}this._trackableScoreStatus=e.length>0?is.Received:is.NotReceived}};WebXRImageTracking.Name=webXRFeaturesManager_WebXRFeatureName.IMAGE_TRACKING,WebXRImageTracking.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRImageTracking.Name,(e,t)=>()=>new WebXRImageTracking(e,t),WebXRImageTracking.Version,!1);let WebXRDomOverlay=class WebXRDomOverlay extends WebXRAbstractFeature{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",tools_Tools.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 tools_Tools.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){let e=document.querySelector(this.options.element);if(null===e)return tools_Tools.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}}}};WebXRDomOverlay.Name=webXRFeaturesManager_WebXRFeatureName.DOM_OVERLAY,WebXRDomOverlay.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRDomOverlay.Name,(e,t)=>()=>new WebXRDomOverlay(e,t),WebXRDomOverlay.Version,!1);let WebXRControllerMovement=class WebXRControllerMovement extends WebXRAbstractFeature{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,r,s,a,n,o;if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new math_vector_Quaternion,this._tmpRotationMatrix=math_vector_Matrix.Identity(),this._tmpTranslationDirection=new math_vector_Vector3,this._tmpMovementTranslation=new math_vector_Vector3,this._tempCacheQuaternion=new math_vector_Quaternion,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let initController=()=>{if(e.motionController)for(let i of this._currentRegistrationConfigurations){let r=null;if(i.allowedComponentTypes)for(let t of i.allowedComponentTypes){let i=e.motionController.getComponentOfType(t);if(null!==i){r=i;break}}if(i.mainComponentOnly){let t=e.motionController.getMainComponent();if(null===t)continue;r=t}if("function"==typeof i.componentSelectionPredicate&&(r=i.componentSelectionPredicate(e)),r&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness||null===r)continue;let s={registrationConfiguration:i,component:r};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=r.onAxisValueChangedObservable.add(e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in i&&(s.onButtonChangedObserver=r.onButtonStateChangedObservable.add(()=>{r.changes.pressed&&i.buttonChangedhandler(r.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};e.motionController?initController():e.onMotionControllerInitObservable.addOnce(()=>{initController()})}},!t||void 0===t.xrInput){tools_Tools.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=WebXRControllerMovement.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(i=t.movementOrientationFollowsViewerPose)||void 0===i||i,movementSpeed:null!==(r=t.movementSpeed)&&void 0!==r?r:1,movementThreshold:null!==(s=t.movementThreshold)&&void 0!==s?s:.25,rotationEnabled:null===(a=t.rotationEnabled)||void 0===a||a,rotationSpeed:null!==(n=t.rotationSpeed)&&void 0!==n?n:1,rotationThreshold:null!==(o=t.rotationThreshold)&&void 0!==o?o:.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){let e=this._xrSessionManager.scene.getEngine().getDeltaTime(),t=.001*e*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=t,math_vector_Quaternion.RotationYawPitchRollToRef(t,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(math_vector_Quaternion.RotationYawPitchRollToRef(3*t,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(math_vector_Matrix.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),math_vector_Vector3.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){let t=this._controllers[e];if(t){for(let e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}};WebXRControllerMovement.Name=webXRFeaturesManager_WebXRFeatureName.MOVEMENT,WebXRControllerMovement.REGISTRATIONS={default:[{allowedComponentTypes:[WebXRControllerComponent.THUMBSTICK_TYPE,WebXRControllerComponent.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:[WebXRControllerComponent.THUMBSTICK_TYPE,WebXRControllerComponent.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}}]},WebXRControllerMovement.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerMovement.Name,(e,t)=>()=>new WebXRControllerMovement(e,t),WebXRControllerMovement.Version,!0);let WebXRLightEstimation=class WebXRLightEstimation extends WebXRAbstractFeature{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=math_vector_Vector3.Up().negateInPlace(),this._lightColor=math_color_Color3.White(),this._intensity=1,this._sphericalHarmonics=new SphericalHarmonics,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new observable_Observable,this._updateReflectionCubeMap=()=>{var e;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){let e=Date.now();if(e-this._cubeMapPollTime<this.options.cubeMapPollInterval)return;this._cubeMapPollTime=e}let t=this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe);if(t&&this._reflectionCubeMap){if(this._reflectionCubeMap._texture)null===(e=this._reflectionCubeMap._texture._hardwareTexture)||void 0===e||e.set(t),this._reflectionCubeMap._texture.getEngine().resetTextureCache();else{let e=new internalTexture_InternalTexture(this._xrSessionManager.scene.getEngine(),$.Unknown);e.isCube=!0,e.invertY=!1,e._useSRGBBuffer="srgba8"===this.options.reflectionFormat,e.format=5,e.generateMipMaps=!0,e.type="srgba8"!==this.options.reflectionFormat?2:0,e.samplingMode=3,e.width=this._reflectionCubeMapTextureSize,e.height=this._reflectionCubeMapTextureSize,e._cachedWrapU=1,e._cachedWrapV=1,e._hardwareTexture=new WebGLHardwareTexture(t,this._getCanvasContext()),this._reflectionCubeMap._texture=e}this._reflectionCubeMap._texture.isReady=!0,this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap)}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new DirectionalLight("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new math_vector_Vector3(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=LightConstants.FALLOFF_GLTF),tools_Tools.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){let e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){var e;if(!super.attach())return!1;let t=null!==(e=this.options.reflectionFormat)&&void 0!==e?e:this._xrSessionManager.session.preferredReflectionFormat||"srgba8";return this.options.reflectionFormat=t,this._xrSessionManager.session.requestLightProbe({reflectionFormat:t}).then(e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(!this._reflectionCubeMap&&(this._reflectionCubeMap=new baseTexture_BaseTexture(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(){let 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){let e=Date.now();if(e-this._lightEstimationPollTime<this.options.lightEstimationPollInterval)return;this._lightEstimationPollTime=e}if(this._xrLightEstimate=e.getLightEstimate(this._xrLightProbe),this._xrLightEstimate){this._intensity=Math.max(1,this._xrLightEstimate.primaryLightIntensity.x,this._xrLightEstimate.primaryLightIntensity.y,this._xrLightEstimate.primaryLightIntensity.z);let e=this._xrSessionManager.scene.useRightHandedSystem?1:-1;this.options.disableVectorReuse&&(this._lightDirection=new math_vector_Vector3,this._lightColor=new math_color_Color3,this.directionalLight&&(this.directionalLight.direction=this._lightDirection,this.directionalLight.diffuse=this._lightColor)),this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x,this._xrLightEstimate.primaryLightDirection.y,this._xrLightEstimate.primaryLightDirection.z*e),this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x/this._intensity,this._xrLightEstimate.primaryLightIntensity.y/this._intensity,this._xrLightEstimate.primaryLightIntensity.z/this._intensity),this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients),this._reflectionCubeMap&&!this.options.disableSphericalPolynomial&&(this._reflectionCubeMap.sphericalPolynomial=this._reflectionCubeMap.sphericalPolynomial||new SphericalPolynomial,null===(t=this._reflectionCubeMap.sphericalPolynomial)||void 0===t||t.updateFromHarmonics(this._sphericalHarmonics)),this._lightDirection.negateInPlace(),this.directionalLight&&(this.directionalLight.direction.copyFrom(this._lightDirection),this.directionalLight.intensity=Math.min(this._intensity,1),this.directionalLight.diffuse.copyFrom(this._lightColor))}}}};WebXRLightEstimation.Name=webXRFeaturesManager_WebXRFeatureName.LIGHT_ESTIMATION,WebXRLightEstimation.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRLightEstimation.Name,(e,t)=>()=>new WebXRLightEstimation(e,t),WebXRLightEstimation.Version,!1);let WebXREyeTracking=class WebXREyeTracking extends WebXRAbstractFeature{constructor(e){super(e),this.onEyeTrackingStartedObservable=new observable_Observable,this.onEyeTrackingEndedObservable=new observable_Observable,this.onEyeTrackingFrameUpdateObservable=new observable_Observable,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new ray_Ray(math_vector_Vector3.Zero(),math_vector_Vector3.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){let 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);let e=t.transform.orientation;math_vector_TmpVectors.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?math_vector_Vector3.RightHandedForwardReadOnly.rotateByQuaternionToRef(math_vector_TmpVectors.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,math_vector_TmpVectors.Quaternion[0].z*=-1,math_vector_TmpVectors.Quaternion[0].w*=-1,math_vector_Vector3.LeftHandedForwardReadOnly.rotateByQuaternionToRef(math_vector_TmpVectors.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))}};WebXREyeTracking.Name=webXRFeaturesManager_WebXRFeatureName.EYE_TRACKING,WebXREyeTracking.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXREyeTracking.Name,e=>()=>new WebXREyeTracking(e),WebXREyeTracking.Version,!1);let CircleBuffer=class CircleBuffer{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i<e;++i)this._samples.push(t?t():math_vector_Vector2.Zero())}get length(){return this._samples.length}push(e,t){this._idx=(this._idx+this._samples.length-1)%this._samples.length,this.at(0).copyFromFloats(e,t)}at(e){if(e>=this._samples.length)throw Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}};let FirstStepDetector=class FirstStepDetector{constructor(){this._samples=new CircleBuffer(20),this._entropy=0,this.onFirstStepDetected=new observable_Observable}update(e,t,i,r){let s,a;this._samples.push(e,t);let n=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=math_vector_Vector2.Distance(n,this._samples.at(1)),this._entropy>this._entropyThreshold)return;for(s=this._samePointCheckStartIdx;s<this._samples.length&&!(math_vector_Vector2.DistanceSquared(n,this._samples.at(s))<this._samePointSquaredDistanceThreshold);++s);if(s===this._samples.length)return;let o=-1,l=0;for(let e,t=1;t<s;++t)(e=math_vector_Vector2.DistanceSquared(n,this._samples.at(t)))>o&&(l=t,o=e);if(o<this._apexSquaredDistanceThreshold)return;let h=this._samples.at(l),c=h.subtract(n);c.normalize();let u=math_vector_TmpVectors.Vector2[0],d=0;for(let e=1;e<s;++e)this._samples.at(e).subtractToRef(n,u),a=math_vector_Vector2.Dot(c,u),d+=u.lengthSquared()-a*a;if(d>s*this._squaredProjectionDistanceThreshold)return;let _=math_vector_TmpVectors.Vector3[0];_.set(i,r,0);let p=math_vector_TmpVectors.Vector3[1];p.set(c.x,c.y,0);let f=math_vector_Vector3.Cross(_,p).z>0,m=n.clone(),g=n.clone();h.subtractToRef(n,c),f?(c.scaleAndAddToRef(this._axisToApexShrinkFactor,m),c.scaleAndAddToRef(this._axisToApexExtendFactor,g)):(c.scaleAndAddToRef(this._axisToApexExtendFactor,m),c.scaleAndAddToRef(this._axisToApexShrinkFactor,g)),this.onFirstStepDetected.notifyObservers({leftApex:m,rightApex:g,currentPosition:n,currentStepDirection:f?"right":"left"})}reset(){for(let e=0;e<this._samples.length;++e)this._samples.at(e).copyFromFloats(0,0)}get _samePointCheckStartIdx(){return Math.floor(this._samples.length/3)}get _samePointSquaredDistanceThreshold(){return 9e-4}get _apexSquaredDistanceThreshold(){return .0081}get _squaredProjectionDistanceThreshold(){return 9e-4}get _axisToApexShrinkFactor(){return .8}get _axisToApexExtendFactor(){return -1.6}get _entropyDecayFactor(){return .93}get _entropyThreshold(){return .4}};let WalkingTracker=class WalkingTracker{constructor(e,t,i,r){this._leftApex=new math_vector_Vector2,this._rightApex=new math_vector_Vector2,this._currentPosition=new math_vector_Vector2,this._axis=new math_vector_Vector2,this._axisLength=-1,this._forward=new math_vector_Vector2,this._steppingLeft=!1,this._t=-1,this._maxT=-1,this._maxTPosition=new math_vector_Vector2,this._vitality=0,this.onMovement=new observable_Observable,this.onFootfall=new observable_Observable,this._reset(e,t,i,"left"===r)}_reset(e,t,i,r){this._leftApex.copyFrom(e),this._rightApex.copyFrom(t),this._steppingLeft=r,this._steppingLeft?(this._leftApex.subtractToRef(this._rightApex,this._axis),this._forward.copyFromFloats(-this._axis.y,this._axis.x)):(this._rightApex.subtractToRef(this._leftApex,this._axis),this._forward.copyFromFloats(this._axis.y,-this._axis.x)),this._axisLength=this._axis.length(),this._forward.scaleInPlace(1/this._axisLength),this._updateTAndVitality(i.x,i.y),this._maxT=this._t,this._maxTPosition.copyFrom(i),this._vitality=1}_updateTAndVitality(e,t){this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._currentPosition.subtractInPlace(this._rightApex):this._currentPosition.subtractInPlace(this._leftApex);let i=this._t,r=math_vector_Vector2.Dot(this._currentPosition,this._axis);this._t=r/(this._axisLength*this._axisLength);let s=this._currentPosition.lengthSquared()-r/this._axisLength*(r/this._axisLength);this._vitality*=.92-100*Math.max(s-.0016,0)+Math.max(this._t-i,0)}update(e,t){if(this._vitality<this._vitalityThreshold)return!1;let i=this._t;return this._updateTAndVitality(e,t),this._t>this._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitality<this._vitalityThreshold)&&(this._t>i&&(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}};let Walker=class Walker{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new FirstStepDetector,this._walker=null,this._movement=new math_vector_Vector2,this._millisecondsSinceLastUpdate=Walker._MillisecondsPerUpdate,this.movementThisFrame=math_vector_Vector3.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(e=>{this._walker||(this._walker=new WalkingTracker(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>=Walker._MillisecondsPerUpdate){if(this._millisecondsSinceLastUpdate-=Walker._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker){let t=this._walker.update(e.x,e.z);t||(this._walker=null)}this._movement.scaleInPlace(.85)}this.movementThisFrame.set(this._movement.x,0,this._movement.y)}};let WebXRWalkingLocomotion=class WebXRWalkingLocomotion extends WebXRAbstractFeature{static get Name(){return webXRFeaturesManager_WebXRFeatureName.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 math_vector_Vector3,this._forward=new math_vector_Vector3,this._position=new math_vector_Vector3,this._movement=new math_vector_Vector3,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&logger_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")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!!(this.isCompatible&&super.attach())&&(this._walker=new Walker(this._sessionManager.scene.getEngine()),!0)}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){let t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;let i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||math_vector_Vector3.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}};WebXRFeaturesManager.AddWebXRFeature(WebXRWalkingLocomotion.Name,(e,t)=>()=>new WebXRWalkingLocomotion(e,t),WebXRWalkingLocomotion.Version,!1);let WebXRCompositionLayerWrapper=class WebXRCompositionLayerWrapper extends WebXRLayerWrapper{constructor(e,t,i,r,s,a){super(e,t,i,r,a),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=s,this.createRTTProvider=a}};let WebXRCompositionLayerRenderTargetTextureProvider=class WebXRCompositionLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{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,r,s,a;let n=this._lastSubImages.get(t),o="left"==t?0:1,l=null!==(i=e.colorTextureWidth)&&void 0!==i?i:e.textureWidth,h=null!==(r=e.colorTextureHeight)&&void 0!==r?r:e.textureHeight;if(!this._renderTargetTextures[o]||(null==n?void 0:n.textureWidth)!==l||(null==n?void 0:n.textureHeight)!==h){let t;let i=null!==(s=e.depthStencilTextureWidth)&&void 0!==s?s:l,r=null!==(a=e.depthStencilTextureHeight)&&void 0!==a?a:h;(l===i||h===r)&&(t=e.depthStencilTexture),this._renderTargetTextures[o]=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[o]}_getSubImageForEye(e){let t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){let t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}_setViewportForSubImage(e,t){var i,r;let s=null!==(i=t.colorTextureWidth)&&void 0!==i?i:t.textureWidth,a=null!==(r=t.colorTextureWidth)&&void 0!==r?r:t.textureHeight,n=t.viewport;e.x=n.x/s,e.y=n.y/a,e.width=n.width/s,e.height=n.height/a}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}};let WebXRProjectionLayerWrapper=class WebXRProjectionLayerWrapper extends WebXRCompositionLayerWrapper{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,e=>new WebXRProjectionLayerRenderTargetTextureProvider(e,i,this)),this.layer=e}};let WebXRProjectionLayerRenderTargetTextureProvider=class WebXRProjectionLayerRenderTargetTextureProvider extends WebXRCompositionLayerRenderTargetTextureProvider{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){let t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}};let oP={},oA={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};let WebXRLayers=class WebXRLayers extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;let t=Object.assign({},oA),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=oP){let t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new WebXRWebGLLayerWrapper(t)}createProjectionLayer(e=oA,t=!1){if(t&&"texture-array"!==e.textureType)throw 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 Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.");let i=this._xrWebGLBinding.createProjectionLayer(e);return new WebXRProjectionLayerWrapper(i,t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;let 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){}};WebXRLayers.Name=webXRFeaturesManager_WebXRFeatureName.LAYERS,WebXRLayers.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRLayers.Name,(e,t)=>()=>new WebXRLayers(e,t),WebXRLayers.Version,!1);let WebXRDepthSensing=class WebXRDepthSensing extends WebXRAbstractFeature{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;let i=this._xrSessionManager.scene.getEngine(),r=new internalTexture_InternalTexture(i,$.Unknown);return r.isCube=!1,r.invertY=!1,r._useSRGBBuffer=!1,r.format="ushort"===this.depthDataFormat?2:5,r.generateMipMaps=!1,r.type="ushort"===this.depthDataFormat?5:1,r.samplingMode=7,r.width=null!==(e=this.width)&&void 0!==e?e:0,r.height=null!==(t=this.height)&&void 0!==t?t:0,r._cachedWrapU=1,r._cachedWrapV=1,r._hardwareTexture=new WebGLHardwareTexture(this._cachedWebGLTexture,i._gl),r}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 observable_Observable,this.xrNativeFeatureName="depth-sensing",tools_Tools.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){if(!super.attach(e))return!1;let t=null==this._xrSessionManager.session.depthDataFormat||null==this._xrSessionManager.session.depthUsage;return!t&&(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){let t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(let t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:tools_Tools.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{data:s,width:a,height:n,rawValueToMeters:o,getDepthInMeters:l}=r;switch(this._width=a,this._height=n,this._rawValueToMeters=o,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=rawTexture_RawTexture.CreateRTexture(null,a,n,this._xrSessionManager.scene,!1,!0,texture_Texture.NEAREST_SAMPLINGMODE,engine_Engine.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map(e=>e*o));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map(e=>e*o))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{texture:s,width:a,height:n}=r;this._width=a,this._height=n,this._cachedWebGLTexture=s;let o=this._xrSessionManager.scene,l=o.getEngine(),h=l.wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=rawTexture_RawTexture.CreateRTexture(null,a,n,o,!1,!0,texture_Texture.NEAREST_SAMPLINGMODE,"ushort"===i?engine_Engine.TEXTURETYPE_UNSIGNED_BYTE:engine_Engine.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=h}getXRSessionInitExtension(){let 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){let e=this.options.usagePreference.map(e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),t=this.options.dataFormatPreference.map(e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:e,dataFormatPreference:t}})}else i({})})}};WebXRDepthSensing.Name=webXRFeaturesManager_WebXRFeatureName.DEPTH_SENSING,WebXRDepthSensing.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRDepthSensing.Name,(e,t)=>()=>new WebXRDepthSensing(e,t),WebXRDepthSensing.Version,!1);let oM=`precision highp float; +#define CUSTOM_FRAGMENT_BEGIN +varying vec4 clipPos;varying vec4 previousClipPos; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; +#define CUSTOM_FRAGMENT_MAIN_END +}`;ShaderStore.ShadersStore.velocityPixelShader=oM;let oI=`#define CUSTOM_VERTEX_BEGIN +#define VELOCITY +attribute vec3 position; +#include<instancesDeclaration> +uniform mat4 viewProjection;uniform mat4 previousViewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; +#endif +varying vec4 clipPos;varying vec4 previousClipPos; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#include<instancesVertex> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} +#elif +clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;ShaderStore.ShadersStore.velocityVertexShader=oI;let XRSpaceWarpRenderTarget=class XRSpaceWarpRenderTarget extends renderTargetTexture_RenderTargetTexture{constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[math_vector_Matrix.Identity(),math_vector_Matrix.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 shaderMaterial_ShaderMaterial("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;let 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}};let WebXRSpaceWarpRenderTargetTextureProvider=class WebXRSpaceWarpRenderTargetTextureProvider{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){let t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw Error('For Space Warp, the base layer type should "XRProjectionLayer".');let i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,s){if(!this._engine)throw Error("Engine is disposed");let a=new XRSpaceWarpRenderTarget(r,s,this._scene,{width:e,height:t}),n=a.renderTarget;return i&&(n._framebuffer=i),n._colorTextureArray=r,n._depthStencilTextureArray=s,a.disableRescaling(),a.renderListPredicate=()=>!0,a}_getRenderTargetForSubImage(e,t){let i=this._lastSubImages.get(t),r=this._renderTargetTextures.get(t.eye),s=e.motionVectorTextureWidth,a=e.motionVectorTextureHeight;return r&&(null==i?void 0:i.textureWidth)===s&&(null==i?void 0:i.textureHeight)==a||(r=this._createRenderTargetTexture(s,a,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:a}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){let i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){let t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){let t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}};let WebXRSpaceWarp=class WebXRSpaceWarp extends WebXRAbstractFeature{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[webXRFeaturesManager_WebXRFeatureName.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new WebXRSpaceWarpRenderTargetTextureProvider(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add(()=>this._onAfterRender()),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;let i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}};WebXRSpaceWarp.Name=webXRFeaturesManager_WebXRFeatureName.SPACE_WARP,WebXRSpaceWarp.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRSpaceWarp.Name,e=>()=>new WebXRSpaceWarp(e),WebXRSpaceWarp.Version,!1);let WebXRGenericHandController=class WebXRGenericHandController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,oD[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(){}};WebXRMotionControllerManager.RegisterController("generic-hand-select-grasp",(e,t)=>new WebXRGenericHandController(t,e.gamepad,e.handedness));let oD={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"}};let WebXRMicrosoftMixedRealityController=class WebXRMicrosoftMixedRealityController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,oO["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?WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME:WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME;let t=WebXRMicrosoftMixedRealityController.MODEL_BASE_URL+"default/";return{filename:e,path:t}}_getModelLoadingConstraints(){let e=sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb");return e||logger_Logger.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){let i=this._mapping.buttons[e],r=i.rootNodeName;if(!r){logger_Logger.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);return}let s=this._getChildByName(this.rootMesh,r);if(!s){logger_Logger.Warn("Missing button mesh with name: "+r);return}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){let t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add(e=>{this._lerpTransform(i,e.value)},void 0,!0)}else logger_Logger.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(e=>{let t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach(i=>{if(!this.rootMesh)return;let r=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,r.rootNodeName);if(!s){logger_Logger.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?t&&t.onAxisValueChangedObservable.add(e=>{let t="x-axis"===i?e.x:e.y;this._lerpTransform(r,t,!0)},void 0,!0):logger_Logger.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){let t;this.rootMesh=new mesh_Mesh(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i<e.length;i++){let r=e[i];r.isPickable=!1,r.parent||(t=r)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=math_vector_Quaternion.FromEulerAngles(0,Math.PI,0))}_updateModel(){}};WebXRMicrosoftMixedRealityController.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME="left.glb",WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME="right.glb",WebXRMotionControllerManager.RegisterController("windows-mixed-reality",(e,t)=>new WebXRMicrosoftMixedRealityController(t,e.gamepad,e.handedness));let oO={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"}};let WebXROculusTouchMotionController=class WebXROculusTouchMotionController extends WebXRAbstractMotionController{constructor(e,t,i,r=!1,s=!1){super(e,oB[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";e="left"===this.handedness?WebXROculusTouchMotionController.MODEL_LEFT_FILENAME:WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME;let t=this._isQuest()?WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL:WebXROculusTouchMotionController.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){let t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach(e=>{let r=e&&this.getComponent(e);r&&r.onButtonStateChangedObservable.add(r=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-(.2*r.value),this._modelRootNode.getChildren()[3].position.y=-(.005*r.value),this._modelRootNode.getChildren()[3].position.z=-(.005*r.value));return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*r.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(r.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(r.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new mesh_Mesh(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=math_vector_Quaternion.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}};WebXROculusTouchMotionController.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",WebXROculusTouchMotionController.MODEL_LEFT_FILENAME="left.babylon",WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME="right.babylon",WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",WebXRMotionControllerManager.RegisterController("oculus-touch",(e,t)=>new WebXROculusTouchMotionController(t,e.gamepad,e.handedness)),WebXRMotionControllerManager.RegisterController("oculus-touch-legacy",(e,t)=>new WebXROculusTouchMotionController(t,e.gamepad,e.handedness,!0));let oB={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"}};let WebXRHTCViveMotionController=class WebXRHTCViveMotionController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,oN[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){let e=WebXRHTCViveMotionController.MODEL_FILENAME,t=WebXRHTCViveMotionController.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add(t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-(.15*t.value);return;case"xr-standard-touchpad":case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new mesh_Mesh(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=math_vector_Quaternion.FromEulerAngles(0,Math.PI,0))}_updateModel(){}};WebXRHTCViveMotionController.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",WebXRHTCViveMotionController.MODEL_FILENAME="wand.babylon",WebXRMotionControllerManager.RegisterController("htc-vive",(e,t)=>new WebXRHTCViveMotionController(t,e.gamepad,e.handedness));let oN={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"}};let NativeXRFrame=class NativeXRFrame{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 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 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;let i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];let r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw Error("This function is not available in Babylon Native")}};RegisterNativeTypeAsync("NativeXRFrame",NativeXRFrame),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(ia||(ia={}));let FlowGraphConnection=class FlowGraphConnection{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=guid_RandomGUID(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){for(let t of(e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName(),this._connectedPoint))e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){let i=tools_Tools.Instantiate(e.className),r=new i(e.name,e._connectionType,t);return r.deserialize(e),r}};let RichType=class RichType{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new RichType(e.typeName,e.defaultValue)}};let oF=new RichType("any",void 0),ow=new RichType("string",""),oL=new RichType("number",0),oV=new RichType("boolean",!1),oU=new RichType("Vector2",math_vector_Vector2.Zero()),ok=new RichType("Vector3",math_vector_Vector3.Zero()),oG=new RichType("Vector4",math_vector_Vector4.Zero()),oz=new RichType("Matrix",math_vector_Matrix.Identity()),oW=new RichType("Color3",math_color_Color3.Black()),oH=new RichType("Color4",new math_color_Color4(0,0,0,0)),oX=new RichType("Quaternion",math_vector_Quaternion.Identity());function getRichTypeFromValue(e){switch(typeof e){case"string":return ow;case"number":return oL;case"boolean":return oV;case"object":if(e instanceof math_vector_Vector2)return oU;if(e instanceof math_vector_Vector3)return ok;if(e instanceof math_vector_Vector4)return oG;if(e instanceof math_color_Color3)return oW;else if(e instanceof math_color_Color4)return oH;else if(e instanceof math_vector_Quaternion)return oX;else return oF;default:return oF}}let FlowGraphDataConnection=class FlowGraphDataConnection extends FlowGraphConnection{constructor(e,t,i,r){super(e,t,i),this.richType=r}_isSingularConnection(){return this.connectionType===ia.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===ia.Output?(this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){let i=FlowGraphConnection.Parse(e,t);return i.richType=RichType.Parse(e.richType),i}};h.FGDataConnection=FlowGraphDataConnection;let FlowGraphBlock=class FlowGraphBlock{constructor(e){this.config=e,this.uniqueId=guid_RandomGUID(),this.configure()}configure(){var e,t;this.name=null!==(t=null===(e=this.config)||void 0===e?void 0:e.name)&&void 0!==t?t:this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}_registerDataInput(e,t){let i=new FlowGraphDataConnection(e,ia.Input,this,t);return this.dataInputs.push(i),i}_registerDataOutput(e,t){let i=new FlowGraphDataConnection(e,ia.Output,this,t);return this.dataOutputs.push(i),i}serialize(e={}){for(let t of(e.uniqueId=this.uniqueId,e.config=this.config,e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName(),this.dataInputs)){let i={};t.serialize(i),e.dataInputs.push(i)}for(let t of this.dataOutputs){let i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e){let t=tools_Tools.Instantiate(e.className),i=new t(e.config);i.uniqueId=e.uniqueId;for(let t=0;t<e.dataInputs.length;t++)i.dataInputs[t].deserialize(e.dataInputs[t]);for(let t=0;t<e.dataOutputs.length;t++)i.dataOutputs[t].deserialize(e.dataOutputs[t]);if(i instanceof FlowGraphExecutionBlock){for(let t=0;t<e.signalInputs.length;t++)i.signalInputs[t].deserialize(e.signalInputs[t]);for(let t=0;t<e.signalOutputs.length;t++)i.signalOutputs[t].deserialize(e.signalOutputs[t])}return i}};let FlowGraphSignalConnection=class FlowGraphSignalConnection extends FlowGraphConnection{_isSingularConnection(){return this.connectionType===ia.Output}_activateSignal(e){var t;this.connectionType===ia.Input?(this._ownerBlock._execute(e,this),e._increaseExecutionId()):null===(t=this._connectedPoint[0])||void 0===t||t._activateSignal(e)}};h.FlowGraphSignalConnection=FlowGraphSignalConnection;let FlowGraphExecutionBlock=class FlowGraphExecutionBlock extends FlowGraphBlock{constructor(e){super(e),this.onStart=this._registerSignalInput("onStart")}configure(){super.configure(),this.signalInputs=[],this.signalOutputs=[]}_registerSignalInput(e){let t=new FlowGraphSignalConnection(e,ia.Input,this);return this.signalInputs.push(t),t}_registerSignalOutput(e){let t=new FlowGraphSignalConnection(e,ia.Output,this);return this.signalOutputs.push(t),t}serialize(e={}){for(let t of(super.serialize(e),e.signalInputs=[],e.signalOutputs=[],this.signalInputs)){let i={};t.serialize(i),e.signalInputs.push(i)}for(let t of this.signalOutputs){let i={};t.serialize(i),e.signalOutputs.push(i)}}getClassName(){return"FGExecutionBlock"}static Parse(e={}){let t=super.Parse(e);for(let i=0;i<e.signalInputs.length;i++)t.signalInputs[i].deserialize(e.signalInputs[i]);for(let i=0;i<e.signalOutputs.length;i++)t.signalOutputs[i].deserialize(e.signalOutputs[i]);return t}};let FlowGraphAsyncExecutionBlock=class FlowGraphAsyncExecutionBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.onDone=this._registerSignalOutput("onDone")}_startPendingTasks(e){this._preparePendingTasks(e),e._addPendingBlock(this)}};let FlowGraphEventBlock=class FlowGraphEventBlock extends FlowGraphAsyncExecutionBlock{_execute(e){this.onDone._activateSignal(e)}};function isMeshClassName(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function defaultValueSerializationFunction(e,t,i){(null==t?void 0:t.getClassName)&&isMeshClassName(null==t?void 0:t.getClassName())?i[e]={name:t.name,className:t.getClassName()}:i[e]=t}function defaultValueParseFunction(e,t,i){let r=t[e],s=null==r?void 0:r.className;return isMeshClassName(s)?i.getMeshByName(r.name):r}let FlowGraphContext=class FlowGraphContext{constructor(e){this.uniqueId=guid_RandomGUID(),this._userVariables=new Map,this._executionVariables=new Map,this._connectionValues=new Map,this._pendingBlocks=[],this._executionId=0,this._configuration=e}hasVariable(e){return this._userVariables.has(e)}setVariable(e,t){this._userVariables.set(e,t)}getVariable(e){return this._userVariables.get(e)}_getUniqueIdPrefixedName(e,t){return`${e.uniqueId}_${t}`}_setExecutionVariable(e,t,i){this._executionVariables.set(this._getUniqueIdPrefixedName(e,t),i)}_getExecutionVariable(e,t,i){return this._hasExecutionVariable(e,t)?this._executionVariables.get(this._getUniqueIdPrefixedName(e,t)):i}_deleteExecutionVariable(e,t){this._executionVariables.delete(this._getUniqueIdPrefixedName(e,t))}_hasExecutionVariable(e,t){return this._executionVariables.has(this._getUniqueIdPrefixedName(e,t))}_hasConnectionValue(e){return this._connectionValues.has(e.uniqueId)}_setConnectionValue(e,t){this._connectionValues.set(e.uniqueId,t)}_getConnectionValue(e){return this._connectionValues.get(e.uniqueId)}get configuration(){return this._configuration}_addPendingBlock(e){this._pendingBlocks.push(e)}_removePendingBlock(e){let t=this._pendingBlocks.indexOf(e);-1!==t&&this._pendingBlocks.splice(t,1)}_clearPendingBlocks(){for(let e of this._pendingBlocks)e._cancelPendingTasks(this);this._pendingBlocks.length=0}_increaseExecutionId(){this._executionId++}get executionId(){return this._executionId}serialize(e={},t=defaultValueSerializationFunction){e.uniqueId=this.uniqueId,e._userVariables={},this._userVariables.forEach((i,r)=>{t(r,i,e._userVariables)}),e._connectionValues={},this._connectionValues.forEach((i,r)=>{t(r,i,e._connectionValues)})}getClassName(){return"FGContext"}static Parse(e={},t,i=defaultValueParseFunction){let r=t.createContext();for(let t in r.uniqueId=e.uniqueId,e._userVariables){let s=i(t,e._userVariables,r._configuration.scene);r._userVariables.set(t,s)}for(let t in e._connectionValues){let s=i(t,e._connectionValues,r._configuration.scene);r._connectionValues.set(t,s)}return r}};__decorate([serialize()],FlowGraphContext.prototype,"uniqueId",void 0);let FlowGraphVariableDefinitions=class FlowGraphVariableDefinitions{constructor(){this._definitions=new Map}defineVariable(e,t){this._definitions.set(e,t)}generateContext(e){let t=new FlowGraphContext(e);return this._definitions.forEach((e,i)=>{t.setVariable(i,e)}),t}serialize(e){this._definitions.forEach((t,i)=>{e[i]=t})}deserialize(e){for(let t in this._definitions.clear(),e)this._definitions.set(t,e[t])}};!function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(io||(io={}));let FlowGraph=class FlowGraph{constructor(e){this.variableDefinitions=new FlowGraphVariableDefinitions,this._eventBlocks=[],this._executionContexts=[],this.state=io.Stopped,this._scene=e.scene,this._eventCoordinator=e.eventCoordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){let e=this.variableDefinitions.generateContext({scene:this._scene,eventCoordinator:this._eventCoordinator});return this._executionContexts.push(e),e}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==io.Started)for(let e of(this.state=io.Started,0===this._executionContexts.length&&this.createContext(),this._executionContexts))for(let t of this._eventBlocks)t._startPendingTasks(e)}dispose(){if(this.state!==io.Stopped){for(let e of(this.state=io.Stopped,this._executionContexts))e._clearPendingBlocks();this._executionContexts.length=0,this._eventBlocks.length=0,this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null}}visitAllBlocks(e){let t=[],i=new Set;for(let e of this._eventBlocks)t.push(e),i.add(e.uniqueId);for(;t.length>0;){let r=t.pop();for(let s of(e(r),r.dataInputs))for(let e of s._connectedPoint)i.has(e._ownerBlock.uniqueId)||(t.push(e._ownerBlock),i.add(e._ownerBlock.uniqueId));if(r instanceof FlowGraphExecutionBlock)for(let e of r.signalOutputs)for(let r of e._connectedPoint)i.has(r._ownerBlock.uniqueId)||(t.push(r._ownerBlock),i.add(r._ownerBlock.uniqueId))}}serialize(e={},t){for(let i of(e.variableDefinitions={},this.variableDefinitions.serialize(e.variableDefinitions),e.allBlocks=[],this.visitAllBlocks(t=>{let i={};t.serialize(i),e.allBlocks.push(i)}),e.executionContexts=[],this._executionContexts)){let r={};i.serialize(r,t),e.executionContexts.push(r)}}static GetDataOutConnectionByUniqueId(e,t){for(let i of e)for(let e of i.dataOutputs)if(e.uniqueId===t)return e;throw Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(let i of e)if(i instanceof FlowGraphExecutionBlock){for(let e of i.signalInputs)if(e.uniqueId===t)return e}throw Error("Could not find signal in connection with unique id "+t)}static Parse(e,t,i){let r=t.createGraph();r.variableDefinitions.deserialize(e.variableDefinitions);let s=[];for(let t of e.allBlocks){let e=FlowGraphBlock.Parse(t);s.push(e),e instanceof FlowGraphEventBlock&&r.addEventBlock(e)}for(let e of s){for(let t of e.dataInputs)for(let e of t.connectedPointIds){let i=FlowGraph.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof FlowGraphExecutionBlock)for(let t of e.signalOutputs)for(let e of t.connectedPointIds){let i=FlowGraph.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(let t of e.executionContexts)FlowGraphContext.Parse(t,r,i);return r}};let FlowGraphEventCoordinator=class FlowGraphEventCoordinator{constructor(){this._customEventsMap=new Map}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new observable_Observable,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){let i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}};let FlowGraphCoordinator=class FlowGraphCoordinator{constructor(e){var t;this._config=e,this._flowGraphs=[],this.eventCoordinator=new FlowGraphEventCoordinator,this._config.scene.onDisposeObservable.add(()=>{this.dispose()});let i=null!==(t=FlowGraphCoordinator.SceneCoordinators.get(this._config.scene))&&void 0!==t?t:[];i.push(this)}createGraph(){let e=new FlowGraph({scene:this._config.scene,eventCoordinator:this.eventCoordinator});return this._flowGraphs.push(e),e}removeGraph(e){let t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach(e=>e.start())}dispose(){var e;this._flowGraphs.forEach(e=>e.dispose()),this._flowGraphs.length=0;let t=null!==(e=FlowGraphCoordinator.SceneCoordinators.get(this._config.scene))&&void 0!==e?e:[],i=t.indexOf(this);-1!==i&&t.splice(i,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach(i=>{let r={};i.serialize(r,t),e._flowGraphs.push(r)})}static Parse(e,t,i){var r;let s=new FlowGraphCoordinator({scene:t});return null===(r=e._flowGraphs)||void 0===r||r.forEach(e=>{FlowGraph.Parse(e,s,i)}),s}};FlowGraphCoordinator.SceneCoordinators=new Map;let FlowGraphWithOnDoneExecutionBlock=class FlowGraphWithOnDoneExecutionBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.onDone=this._registerSignalOutput("onDone")}};let FlowGraphLogBlock=class FlowGraphLogBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.message=this._registerDataInput("message",oF)}_execute(e){let t=this.message.getValue(e);console.log(t),this.onDone._activateSignal(e)}getClassName(){return"FGLogBlock"}};h.FGLogBlock=FlowGraphLogBlock;let FlowGraphSetVariableBlock=class FlowGraphSetVariableBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.variableName=this._registerDataInput("variableName",ow),this.input=this._registerDataInput("input",oF)}_execute(e){let t=this.variableName.getValue(e),i=this.input.getValue(e);e.setVariable(t,i),this.onDone._activateSignal(e)}getClassName(){return"FGSetVariableBlock"}};h.FGSetVariableBlock=FlowGraphSetVariableBlock;let FlowGraphSetPropertyBlock=class FlowGraphSetPropertyBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.target=this._registerDataInput("target",oF),this.property=this._registerDataInput("property",ow),this.value=this._registerDataInput("value",oF)}_setProperty(e,t,i){let r=t.split("."),s=e;for(let e=0;e<r.length-1;e++)s=s[r[e]];s[r[r.length-1]]=i}_execute(e){let t=this.target.getValue(e),i=this.property.getValue(e),r=this.value.getValue(e);if(t&&i&&r)this._setProperty(t,i,r);else throw Error("Invalid target, property or value.");this.onDone._activateSignal(e)}getClassName(){return"FGSetPropertyBlock"}};h.FGSetPropertyBlock=FlowGraphSetPropertyBlock;let FlowGraphSendCustomEventBlock=class FlowGraphSendCustomEventBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.eventId=this._registerDataInput("eventId",ow),this.eventData=this._registerDataInput("eventData",oF)}_execute(e){let t=this.eventId.getValue(e),i=this.eventData.getValue(e);e.configuration.eventCoordinator.notifyCustomEvent(t,i),this.onDone._activateSignal(e)}getClassName(){return"FGSendCustomEventBlock"}};h.FGSendCustomEventBlock=FlowGraphSendCustomEventBlock;let FlowGraphBranchBlock=class FlowGraphBranchBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.condition=this._registerDataInput("condition",oV),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}};h.FGBranchBlock=FlowGraphBranchBlock;let FlowGraphDoNBlock=class FlowGraphDoNBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.reset=this._registerSignalInput("reset"),this.maxNumberOfExecutions=this._registerDataInput("numberOfExecutions",oL),this.currentCount=this._registerDataOutput("currentCount",oL)}_execute(e,t){if(t===this.reset)this.currentCount.setValue(0,e);else{let t=this.currentCount.getValue(e);t<this.maxNumberOfExecutions.getValue(e)&&(this.currentCount.setValue(t+1,e),this.onDone._activateSignal(e))}}getClassName(){return"FGDoNBlock"}};h.FGDoNBlock=FlowGraphDoNBlock;let FlowGraphForLoopBlock=class FlowGraphForLoopBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.startIndex=this._registerDataInput("startIndex",oL),this.endIndex=this._registerDataInput("endIndex",oL),this.step=this._registerDataInput("step",oL),this.index=this._registerDataOutput("index",oL),this.onLoop=this._registerSignalOutput("onLoop"),this.onDone=this._registerSignalOutput("onDone")}_executeLoop(e){let t=e._getExecutionVariable(this,"index"),i=e._getExecutionVariable(this,"endIndex");if(t<i){this.index.setValue(t,e),this.onLoop._activateSignal(e);let i=e._getExecutionVariable(this,"step",1);t+=i,e._setExecutionVariable(this,"index",t),this._executeLoop(e)}else this.onDone._activateSignal(e)}_execute(e){let t=this.startIndex.getValue(e),i=this.endIndex.getValue(e),r=this.step.getValue(e);e._setExecutionVariable(this,"index",t),e._setExecutionVariable(this,"endIndex",i),e._setExecutionVariable(this,"step",r),this._executeLoop(e)}getClassName(){return"FGForLoopBlock"}};h.FGForLoopBlock=FlowGraphForLoopBlock;let FlowGraphThrottleBlock=class FlowGraphThrottleBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.reset=this._registerSignalInput("reset"),this.duration=this._registerDataInput("duration",oL),this.timeRemaining=this._registerDataOutput("timeRemaining",oL)}_execute(e,t){let i=e._getExecutionVariable(this,"lastExecutedTime"),r=this.duration.getValue(e),s=Date.now();if(t===this.reset||void 0===i||s-i>r)this.timeRemaining.setValue(0,e),this.onDone._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",s);else{let t=r-(s-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}};h.FGThrottleBlock=FlowGraphThrottleBlock;let FlowGraphTimerBlock=class FlowGraphTimerBlock extends FlowGraphAsyncExecutionBlock{constructor(e){super(e),this.timeout=this._registerDataInput("timeout",oL),this.onTimerDone=this._registerSignalOutput("onTimerDone")}_preparePendingTasks(e){let t=this.timeout.getValue(e);if(void 0!==t&&t>=0){let i=e._getExecutionVariable(this,"runningTimers")||[],r=e.configuration.scene,s=new AdvancedTimer({timeout:t,contextObservable:r.onBeforeRenderObservable,onEnded:()=>this._onEnded(s,e)});s.start(),i.push(s),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.onDone._activateSignal(e)}_onEnded(e,t){let i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);-1!==r?i.splice(r,1):tools_Tools.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.onTimerDone._activateSignal(t)}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"runningTimers")||[];for(let e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return"FGTimerBlock"}};h.FGTimerBlock=FlowGraphTimerBlock;let FlowGraphMultiGateBlock=class FlowGraphMultiGateBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this._registerDataOutput("currentIndex",oL)}configure(){super.configure(),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e<this.config.numberOutputFlows;e++)this.outFlows.push(this._registerSignalOutput(`out${e}`))}_getUnusedIndexes(e){let t=this._cachedUnusedIndexes;if(t.length=0,e._hasExecutionVariable(this,"unusedIndexes")){let i=e._getExecutionVariable(this,"unusedIndexes");for(let e=0;e<i.length;e++)t.push(i[e])}else for(let e=0;e<this.config.numberOutputFlows;e++)t.push(e);return t}_getNextOutput(e,t){if(!this.config.isRandom)return e+1;{let e=Math.floor(Math.random()*t.length);return t[e]}}_execute(e,t){var i;let r=null!==(i=e._getExecutionVariable(this,"currentIndex"))&&void 0!==i?i:this.config.startIndex-1,s=this._getUnusedIndexes(e);if(t===this.reset){e._deleteExecutionVariable(this,"currentIndex"),e._deleteExecutionVariable(this,"unusedIndexes");return}let a=this._getNextOutput(r,s);if(a>=this.config.numberOutputFlows&&this.config.loop)a=0;else if(a>=this.config.numberOutputFlows&&!this.config.loop)return;if(0===(s=s.filter(e=>e!==a)).length)for(let e=0;e<this.config.numberOutputFlows;e++)s.push(e);e._setExecutionVariable(this,"unusedIndexes",s),e._setExecutionVariable(this,"currentIndex",a),this.currentIndex.setValue(a,e),this.outFlows[a]._activateSignal(e)}getClassName(){return"FGMultiGateBlock"}};h.FGMultiGateBlock=FlowGraphMultiGateBlock;let FlowGraphSwitchBlock=class FlowGraphSwitchBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.config=e,this.selection=this._registerDataInput("selection",oF)}configure(){super.configure(),this.outputFlows=[];for(let e=0;e<=this.config.cases.length;e++)this.outputFlows.push(this._registerSignalOutput(`out${e}`))}_execute(e,t){let i=this.selection.getValue(e);for(let t=0;t<this.config.cases.length;t++)if(i===this.config.cases[t]){this.outputFlows[t]._activateSignal(e);return}this.outputFlows[this.outputFlows.length-1]._activateSignal(e)}getClassName(){return"FGSwitchBlock"}};h.FGSwitchBlock=FlowGraphSwitchBlock;let FlowGraphWaitAllBlock=class FlowGraphWaitAllBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.config=e,this.inFlows=[],this._cachedActivationState=[],this.reset=this._registerSignalInput("reset")}configure(){for(let e=1;e<this.config.numberInputFlows;e++)this.inFlows.push(this._registerSignalInput(`in${e}`))}_getCurrentActivationState(e){let t=this._cachedActivationState;if(t.length=0,e._hasExecutionVariable(this,"activationState")){let i=e._getExecutionVariable(this,"activationState");for(let e=0;e<i.length;e++)t.push(i[e])}else for(let e=0;e<this.config.numberInputFlows;e++)t.push(!1);return t}_execute(e,t){let i=this._getCurrentActivationState(e);if(t===this.reset)for(let e=0;e<this.config.numberInputFlows;e++)i[e]=!1;else if(t===this.onStart)i[0]=!0;else{let e=this.inFlows.indexOf(t);e>=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(e=>e)){this.onDone._activateSignal(e);for(let e=0;e<this.config.numberInputFlows;e++)i[e]=!1}}getClassName(){return"FGWaitAllBlock"}};h.FGWaitAllBlock=FlowGraphWaitAllBlock;let FlowGraphCounterBlock=class FlowGraphCounterBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.count=this._registerDataOutput("count",oL),this.reset=this._registerSignalInput("reset")}_execute(e,t){var i;if(t===this.reset){e._setExecutionVariable(this,"count",0),this.count.setValue(0,e);return}let r=(null!==(i=e._getExecutionVariable(this,"count"))&&void 0!==i?i:0)+1;e._setExecutionVariable(this,"count",r),this.count.setValue(r,e),this.onDone._activateSignal(e)}getClassName(){return"FGCounterBlock"}};h.FGCounterBlock=FlowGraphCounterBlock;let FlowGraphWhileLoopBlock=class FlowGraphWhileLoopBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.config=e,this.condition=this._registerDataInput("condition",oV),this.loopBody=this._registerSignalOutput("loopBody")}_execute(e,t){var i;let r=this.condition.getValue(e);for((null===(i=this.config)||void 0===i?void 0:i.isDo)&&!r&&this.loopBody._activateSignal(e);r;)this.loopBody._activateSignal(e),r=this.condition.getValue(e);this.onDone._activateSignal(e)}getClassName(){return"FGWhileLoopBlock"}};h.FGWhileLoopBlock=FlowGraphWhileLoopBlock;let FlowGraphDebounceBlock=class FlowGraphDebounceBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.count=this._registerDataInput("count",oL),this.reset=this._registerSignalInput("reset"),this.currentCount=this._registerDataOutput("currentCount",oL)}_execute(e,t){if(t===this.reset){e._setExecutionVariable(this,"debounceCount",0);return}let i=this.count.getValue(e),r=e._getExecutionVariable(this,"debounceCount",0),s=r+1;this.currentCount.setValue(s,e),e._setExecutionVariable(this,"debounceCount",s),s>=i&&(this.onDone._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}};h.FGDebounceBlock=FlowGraphDebounceBlock;let FlowGraphFlipFlopBlock=class FlowGraphFlipFlopBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this._registerDataOutput("isOn",oV)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}};h.FGFlipFlopBlock=FlowGraphFlipFlopBlock;let FlowGraphPlayAnimationBlock=class FlowGraphPlayAnimationBlock extends FlowGraphAsyncExecutionBlock{constructor(e){super(e),this.target=this._registerDataInput("target",oF),this.animation=this._registerDataInput("animation",oF),this.speed=this._registerDataInput("speed",oL),this.loop=this._registerDataInput("loop",oV),this.from=this._registerDataInput("from",oL),this.to=this._registerDataInput("to",oL),this.onAnimationEnd=this._registerSignalOutput("onAnimationEnd"),this.runningAnimatable=this._registerDataOutput("runningAnimatable",oF)}_preparePendingTasks(e){var t;let i=this.target.getValue(e),r=this.animation.getValue(e);if(!i||!r)throw Error("Cannot play animation without target or animation");let s=null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[],a=this.runningAnimatable.getValue(e);if(a&&a.paused)a.restart();else{let t=e.configuration.scene,a=t.beginDirectAnimation(i,[r],this.from.getValue(e),this.to.getValue(e),this.loop.getValue(e),this.speed.getValue(e),()=>this._onAnimationEnd(a,e));this.runningAnimatable.setValue(a,e),s.push(a)}e._setExecutionVariable(this,"runningAnimatables",s)}_execute(e){this._startPendingTasks(e),this.onDone._activateSignal(e)}_onAnimationEnd(e,t){var i;let r=null!==(i=t._getExecutionVariable(this,"runningAnimatables"))&&void 0!==i?i:[],s=r.indexOf(e);-1!==s&&r.splice(s,1),t._removePendingBlock(this),this.onAnimationEnd._activateSignal(t)}_cancelPendingTasks(e){var t;let i=null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[];for(let e of i)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return"FGPlayAnimationBlock"}};h.FGPlayAnimationBlock=FlowGraphPlayAnimationBlock;let FlowGraphStopAnimationBlock=class FlowGraphStopAnimationBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.animationToStop=this._registerDataInput("animationToStop",oF)}_execute(e){let t=this.animationToStop.getValue(e);t.stop(),this.onDone._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}};h.FGStopAnimationBlock=FlowGraphStopAnimationBlock;let FlowGraphPauseAnimationBlock=class FlowGraphPauseAnimationBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.animationToPause=this._registerDataInput("animationToPause",oF)}_execute(e){let t=this.animationToPause.getValue(e);t.pause(),this.onDone._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}};h.FGPauseAnimationBlock=FlowGraphPauseAnimationBlock;let FlowGraphPlayAudioBlock=class FlowGraphPlayAudioBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.audio=this._registerDataInput("audio",oF)}_execute(e,t){let i=this.audio.getValue(e);i instanceof Sound&&i.play(),this.onDone._activateSignal(e)}getClassName(){return"FGPlayAudioBlock"}};h.FGPlayAudioBlock=FlowGraphPlayAudioBlock;let FlowGraphStopAudioBlock=class FlowGraphStopAudioBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.audio=this._registerDataInput("audio",oF)}_execute(e,t){let i=this.audio.getValue(e);i instanceof Sound&&i.stop()}getClassName(){return"FGStopAudioBlock"}};h.FGStopAudioBlock=FlowGraphStopAudioBlock;let FlowGraphConditionalDataBlock=class FlowGraphConditionalDataBlock extends FlowGraphBlock{constructor(e){super(e),this.condition=this._registerDataInput("condition",oV),this.trueValue=this._registerDataInput("trueValue",oF),this.falseValue=this._registerDataInput("falseValue",oF),this.output=this._registerDataOutput("output",oF)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}};h.FGConditionalDataBlock=FlowGraphConditionalDataBlock;let FlowGraphGetVariableBlock=class FlowGraphGetVariableBlock extends FlowGraphBlock{constructor(e){super(e),this.variableName=this._registerDataInput("variableName",ow),this.output=this._registerDataOutput("output",oF)}_updateOutputs(e){let t=this.variableName.getValue(e);e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return"FGGetVariableBlock"}};h.FGGetVariableBlock=FlowGraphGetVariableBlock;let FlowGraphCoordinateTransformBlock=class FlowGraphCoordinateTransformBlock extends FlowGraphBlock{constructor(e){super(e),this.sourceSystem=this._registerDataInput("sourceSystem",oF),this.destinationSystem=this._registerDataInput("destinationSystem",oF),this.inputCoordinates=this._registerDataInput("inputCoordinates",ok),this.outputCoordinates=this._registerDataOutput("outputCoordinates",ok)}_updateOutputs(e){let t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),s=t.getWorldMatrix(),a=i.getWorldMatrix(),n=math_vector_TmpVectors.Matrix[0].copyFrom(a);n.invert();let o=math_vector_TmpVectors.Matrix[1];n.multiplyToRef(s,o);let l=this.outputCoordinates.getValue(e);math_vector_Vector3.TransformCoordinatesToRef(r,o,l)}getClassName(){return"FGCoordinateTransformBlock"}};h.FGCoordinateTransformBlock=FlowGraphCoordinateTransformBlock;let FlowGraphConstantBlock=class FlowGraphConstantBlock extends FlowGraphBlock{constructor(e){super(e),this.config=e,this.output=this._registerDataOutput("output",getRichTypeFromValue(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}};h.FGConstantBlock=FlowGraphConstantBlock;let oY="cachedOperationValue",oj="cachedExecutionId";let FlowGraphCachedOperationBlock=class FlowGraphCachedOperationBlock extends FlowGraphBlock{constructor(e,t){super(t),this.output=this._registerDataOutput("output",e)}_updateOutputs(e){let t=e._getExecutionVariable(this,oj),i=e._getExecutionVariable(this,oY);if(void 0!==i&&t===e.executionId)this.output.setValue(i,e);else{let t=this._doOperation(e);e._setExecutionVariable(this,oY,t),e._setExecutionVariable(this,oj,e.executionId),this.output.setValue(t,e)}}};let FlowGraphBinaryOperationBlock=class FlowGraphBinaryOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r,s,a){super(i,a),this._operation=r,this._className=s,this.leftInput=this._registerDataInput("leftInput",e),this.rightInput=this._registerDataInput("rightInput",t)}_doOperation(e){return this._operation(this.leftInput.getValue(e),this.rightInput.getValue(e))}getClassName(){return this._className}};let FlowGraphUnaryOperationBlock=class FlowGraphUnaryOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r,s){super(t,s),this._operation=i,this._className=r,this.input=this._registerDataInput("input",e)}_doOperation(e){return this._operation(this.input.getValue(e))}getClassName(){return this._className}};let oK="FGBitwise",oq="AndBlock",o$="OrBlock",oQ="XorBlock",oZ="NotBlock",oJ="LeftShiftBlock",o0="RightShiftBlock",o1="CountLeadingZerosBlock",o2="CountTrailingZerosBlock";let FlowGraphBitwiseAndBlock=class FlowGraphBitwiseAndBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e&t,`${oK}${oq}`,e)}};h[`${oK}${oq}`]=FlowGraphBitwiseAndBlock;let FlowGraphBitwiseOrBlock=class FlowGraphBitwiseOrBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e|t,`${oK}${o$}`,e)}};h[`${oK}${o$}`]=FlowGraphBitwiseOrBlock;let FlowGraphBitwiseXorBlock=class FlowGraphBitwiseXorBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e^t,`${oK}${oQ}`,e)}};h[`${oK}${oQ}`]=FlowGraphBitwiseXorBlock;let FlowGraphBitwiseNotBlock=class FlowGraphBitwiseNotBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>~e,`${oK}${oZ}`,e)}};h[`${oK}${oZ}`]=FlowGraphBitwiseNotBlock;let FlowGraphBitwiseLeftShiftBlock=class FlowGraphBitwiseLeftShiftBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e<<t,`${oK}${oJ}`,e)}};h[`${oK}${oJ}`]=FlowGraphBitwiseLeftShiftBlock;let FlowGraphBitwiseRightShiftBlock=class FlowGraphBitwiseRightShiftBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e>>t,`${oK}${o0}`,e)}};h[`${oK}${o0}`]=FlowGraphBitwiseRightShiftBlock;let FlowGraphCountLeadingZerosBlock=class FlowGraphCountLeadingZerosBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.clz32(e),`${oK}${o1}`,e)}};h[`${oK}${o1}`]=FlowGraphCountLeadingZerosBlock;let FlowGraphCountTrailingZerosBlock=class FlowGraphCountTrailingZerosBlock extends FlowGraphUnaryOperationBlock{_ctrz(e){return 0==(e>>>=0)?32:31-Math.clz32(e&=-e)}constructor(e){super(oL,oL,e=>this._ctrz(e),`${oK}${o2}`,e)}};h[`${oK}${o2}`]=FlowGraphCountTrailingZerosBlock;let o3="FGLogic",o4="AndBlock",o5="OrBlock",o6="NotBlock";let FlowGraphLogicAndBlock=class FlowGraphLogicAndBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oV,oV,oV,(e,t)=>e&&t,`${o3}${o4}`,e)}};h[`${o3}${o4}`]=FlowGraphLogicAndBlock;let FlowGraphLogicOrBlock=class FlowGraphLogicOrBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oV,oV,oV,(e,t)=>e||t,`${o3}${o5}`,e)}};h[`${o3}${o5}`]=FlowGraphLogicOrBlock;let FlowGraphLogicNotBlock=class FlowGraphLogicNotBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oV,oV,e=>!e,`${o3}${o6}`,e)}};h[`${o3}${o6}`]=FlowGraphLogicNotBlock;let FlowGraphConstantOperationBlock=class FlowGraphConstantOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r){super(e,r),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}};let o8="FGAddNumberBlock";let FlowGraphAddNumberBlock=class FlowGraphAddNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e+t,o8,e)}};h[o8]=FlowGraphAddNumberBlock;let o7="FGSubtractNumberBlock";let FlowGraphSubtractNumberBlock=class FlowGraphSubtractNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e-t,o7,e)}};h[o7]=FlowGraphSubtractNumberBlock;let o9="FGMultiplyNumberBlock";let FlowGraphMultiplyNumberBlock=class FlowGraphMultiplyNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e*t,o9,e)}};h[o9]=FlowGraphMultiplyNumberBlock;let le="FGDivideNumberBlock";let FlowGraphDivideNumberBlock=class FlowGraphDivideNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e/t,le,e)}};h[le]=FlowGraphDivideNumberBlock;let lt="FGModNumberBlock";let FlowGraphModNumberBlock=class FlowGraphModNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e%t,lt,e)}};h[lt]=FlowGraphModNumberBlock;let li="FGPowNumberBlock";let FlowGraphPowNumberBlock=class FlowGraphPowNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>Math.pow(e,t),li,e)}};h[li]=FlowGraphPowNumberBlock;let lr="FGIsNaNNumberBlock";let FlowGraphIsNaNNumberBlock=class FlowGraphIsNaNNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oV,e=>isNaN(e),lr,e)}};h[lr]=FlowGraphIsNaNNumberBlock;let ls="FGIsInfinityNumberBlock";let FlowGraphIsInfinityNumberBlock=class FlowGraphIsInfinityNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oV,e=>!isFinite(e),ls,e)}};h[ls]=FlowGraphIsInfinityNumberBlock;let la="FGSqrtNumberBlock";let FlowGraphSqrtNumberBlock=class FlowGraphSqrtNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.sqrt(e),la,e)}};h[la]=FlowGraphSqrtNumberBlock;let ln="FGAbsNumberBlock";let FlowGraphAbsNumberBlock=class FlowGraphAbsNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.abs(e),ln,e)}};h[ln]=FlowGraphAbsNumberBlock;let lo="FGNegateNumberBlock";let FlowGraphNegateNumberBlock=class FlowGraphNegateNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>-e,lo,e)}};h[lo]=FlowGraphNegateNumberBlock;let ll="FGFloorNumberBlock";let FlowGraphFloorNumberBlock=class FlowGraphFloorNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.floor(e),ll,e)}};h[ll]=FlowGraphFloorNumberBlock;let lh="FGCeilNumberBlock";let FlowGraphCeilNumberBlock=class FlowGraphCeilNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.ceil(e),lh,e)}};h[lh]=FlowGraphCeilNumberBlock;let lc="FGRoundNumberBlock";let FlowGraphRoundNumberBlock=class FlowGraphRoundNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>Math.round(e/Math.pow(10,t))/Math.pow(10,t),lc,e)}};h[lc]=FlowGraphRoundNumberBlock;let lu="FGTruncNumberBlock";let FlowGraphTruncNumberBlock=class FlowGraphTruncNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.trunc(e),lu,e)}};h[lu]=FlowGraphTruncNumberBlock;let ld="FGExpNumberBlock";let FlowGraphExpNumberBlock=class FlowGraphExpNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.exp(e),ld,e)}};h[ld]=FlowGraphExpNumberBlock;let l_="FGLog10NumberBlock";let FlowGraphLog10NumberBlock=class FlowGraphLog10NumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.log10(e),l_,e)}};h[l_]=FlowGraphLog10NumberBlock;let lp="FGLogNumberBlock";let FlowGraphLogNumberBlock=class FlowGraphLogNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.log(e),lp,e)}};h[lp]=FlowGraphLogNumberBlock;let lf="FGLnNumberBlock";let FlowGraphLnNumberBlock=class FlowGraphLnNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.log(e)/Math.LN2,lf,e)}};h[lf]=FlowGraphLnNumberBlock;let lm="FGSineNumberBlock";let FlowGraphSinNumberBlock=class FlowGraphSinNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.sin(e),lm,e)}};h[lm]=FlowGraphSinNumberBlock;let lg="FGCosNumberBlock";let FlowGraphCosNumberBlock=class FlowGraphCosNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.cos(e),lg,e)}};h[lg]=FlowGraphCosNumberBlock;let lv="FGTanNumberBlock";let FlowGraphTanNumberBlock=class FlowGraphTanNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.tan(e),lv,e)}};h[lv]=FlowGraphTanNumberBlock;let lx="FGASineNumberBlock";let FlowGraphASinNumberBlock=class FlowGraphASinNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.asin(e),lx,e)}};h[lx]=FlowGraphASinNumberBlock;let lb="FGACosNumberBlock";let FlowGraphACosNumberBlock=class FlowGraphACosNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.acos(e),lb,e)}};h[lb]=FlowGraphACosNumberBlock;let lT="FGATanNumberBlock";let FlowGraphATanNumberBlock=class FlowGraphATanNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.atan(e),lT,e)}};h[lT]=FlowGraphATanNumberBlock;let lS="FGENumberBlock";let FlowGraphENumberBlock=class FlowGraphENumberBlock extends FlowGraphConstantOperationBlock{constructor(e){super(oL,()=>Math.E,lS,e)}};h[lS]=FlowGraphENumberBlock;let lC="FGPiNumberBlock";let FlowGraphPiNumberBlock=class FlowGraphPiNumberBlock extends FlowGraphConstantOperationBlock{constructor(e){super(oL,()=>Math.PI,lC,e)}};h[lC]=FlowGraphPiNumberBlock;let lE="FGATan2NumberBlock";let FlowGraphATan2NumberBlock=class FlowGraphATan2NumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>Math.atan2(e,t),lE,e)}};h[lE]=FlowGraphATan2NumberBlock;let ly="FGRandomNumberBlock";let FlowGraphRandomNumberBlock=class FlowGraphRandomNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e+Math.random()*(t-e),ly,e)}};h[ly]=FlowGraphRandomNumberBlock;let lR="FGMinNumberBlock";let FlowGraphMinNumberBlock=class FlowGraphMinNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>Math.min(e,t),lR,e)}};h[lR]=FlowGraphMinNumberBlock;let lP="FGMaxNumberBlock";let FlowGraphMaxNumberBlock=class FlowGraphMaxNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>Math.max(e,t),lP,e)}};h[lP]=FlowGraphMaxNumberBlock;let lA="FGEqualsNumberBlock";let FlowGraphEqualsNumberBlock=class FlowGraphEqualsNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oV,(e,t)=>e===t,lA,e)}};h[lA]=FlowGraphEqualsNumberBlock;let lM="FGGreaterThanNumberBlock";let FlowGraphGreaterThanNumberBlock=class FlowGraphGreaterThanNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oV,(e,t)=>e>t,lM,e)}};h[lM]=FlowGraphGreaterThanNumberBlock;let lI="FGGreaterThanOrEqualsNumberBlock";let FlowGraphGreaterThanOrEqualsNumberBlock=class FlowGraphGreaterThanOrEqualsNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oV,(e,t)=>e>=t,lI,e)}};h[lI]=FlowGraphGreaterThanOrEqualsNumberBlock;let lD="FGLessThanNumberBlock";let FlowGraphLessThanNumberBlock=class FlowGraphLessThanNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oV,(e,t)=>e<t,lD,e)}};h[lD]=FlowGraphLessThanNumberBlock;let lO="FGLessThanOrEqualsNumberBlock";let FlowGraphLessThanOrEqualsNumberBlock=class FlowGraphLessThanOrEqualsNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oV,(e,t)=>e<=t,lO,e)}};h[lO]=FlowGraphLessThanOrEqualsNumberBlock;let lB="FGMixNumberBlock";let FlowGraphMixNumberBlock=class FlowGraphMixNumberBlock extends FlowGraphBlock{constructor(e){super(e),this.leftInput=this._registerDataInput("leftInput",oL),this.rightInput=this._registerDataInput("rightInput",oL),this.alphaInput=this._registerDataInput("alphaInput",oL),this.resultOutput=this._registerDataOutput("resultOutput",oL)}_updateOutputs(e){let t=this.leftInput.getValue(e),i=this.rightInput.getValue(e),r=this.alphaInput.getValue(e);this.resultOutput.setValue(t+(i-t)*r,e)}getClassName(){return lB}};h[lB]=FlowGraphMixNumberBlock;let lN="FGAddVector2Block";let FlowGraphAddVector2Block=class FlowGraphAddVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oU,oU,oU,(e,t)=>e.add(t),lN,e)}};h[lN]=FlowGraphAddVector2Block;let lF="FGSubtractVector2Block";let FlowGraphSubtractVector2Block=class FlowGraphSubtractVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oU,oU,oU,(e,t)=>e.subtract(t),lF,e)}};h[lF]=FlowGraphSubtractVector2Block;let lw="FGMultiplyVector2Block";let FlowGraphMultiplyVector2Block=class FlowGraphMultiplyVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oU,oU,oU,(e,t)=>e.multiply(t),lw,e)}};h[lw]=FlowGraphMultiplyVector2Block;let lL="FGDivideVector2Block";let FlowGraphDivideVector2Block=class FlowGraphDivideVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oU,oU,oU,(e,t)=>e.divide(t),lL,e)}};h[lL]=FlowGraphDivideVector2Block;let lV="FGScaleVector2Block";let FlowGraphScaleVector2Block=class FlowGraphScaleVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oU,oL,oU,(e,t)=>e.scale(t),lV,e)}};h[lV]=FlowGraphScaleVector2Block;let lU="FGLengthVector2Block";let FlowGraphLengthVector2Block=class FlowGraphLengthVector2Block extends FlowGraphUnaryOperationBlock{constructor(e){super(oU,oL,e=>e.length(),lU,e)}};h[lU]=FlowGraphLengthVector2Block;let lk="FGNormalizeVector2Block";let FlowGraphNormalizeVector2Block=class FlowGraphNormalizeVector2Block extends FlowGraphUnaryOperationBlock{constructor(e){super(oU,oU,e=>{let t=e.clone();return t.normalize(),t},lk,e)}};h[lk]=FlowGraphNormalizeVector2Block;let FlowGraphCreateVector2Block=class FlowGraphCreateVector2Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=math_vector_Vector2.Zero(),this.x=this._registerDataInput("x",oL),this.y=this._registerDataInput("y",oL),this.vector=this._registerDataOutput("vector",oU)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this.vector.setValue(this._cachedVector,e)}};h.FGCreateVector2Block=FlowGraphCreateVector2Block;let FlowGraphSplitVector2Block=class FlowGraphSplitVector2Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",oU),this.x=this._registerDataOutput("x",oL),this.y=this._registerDataOutput("y",oL)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e)}};h.FGSplitVector2Block=FlowGraphSplitVector2Block;let FlowGraphRotate2dVector2Block=class FlowGraphRotate2dVector2Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=math_vector_Vector2.Zero(),this.input=this._registerDataInput("input",oU),this.angle=this._registerDataInput("angle",oL),this.output=this._registerDataOutput("output",oU)}_updateOutputs(e){let t=this.input.getValue(e),i=this.angle.getValue(e);this._cachedVector.x=t.x*Math.cos(i)-t.y*Math.sin(i),this._cachedVector.y=t.x*Math.sin(i)+t.y*Math.cos(i),this.output.setValue(this._cachedVector,e)}};h.FGRotate2dVector2Block=FlowGraphRotate2dVector2Block;let lG="FGAddVector3Block";let FlowGraphAddVector3Block=class FlowGraphAddVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,ok,(e,t)=>e.add(t),lG,e)}};h[lG]=FlowGraphAddVector3Block;let lz="FGSubtractVector3Block";let FlowGraphSubtractVector3Block=class FlowGraphSubtractVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,ok,(e,t)=>e.subtract(t),lz,e)}};h[lz]=FlowGraphSubtractVector3Block;let lW="FGMultiplyVector3Block";let FlowGraphMultiplyVector3Block=class FlowGraphMultiplyVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,ok,(e,t)=>e.multiply(t),lW,e)}};h[lW]=FlowGraphMultiplyVector3Block;let lH="FGDivideVector3Block";let FlowGraphDivideVector3Block=class FlowGraphDivideVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,ok,(e,t)=>e.divide(t),lH,e)}};h[lH]=FlowGraphDivideVector3Block;let lX="FGScaleVector3Block";let FlowGraphScaleVector3Block=class FlowGraphScaleVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,oL,ok,(e,t)=>e.scale(t),lX,e)}};h[lX]=FlowGraphScaleVector3Block;let lY="FGLengthVector3Block";let FlowGraphLengthVector3Block=class FlowGraphLengthVector3Block extends FlowGraphUnaryOperationBlock{constructor(e){super(ok,oL,e=>e.length(),lY,e)}};h[lY]=FlowGraphLengthVector3Block;let lj="FGNormalizeVector3Block";let FlowGraphNormalizeVector3Block=class FlowGraphNormalizeVector3Block extends FlowGraphUnaryOperationBlock{constructor(e){super(ok,ok,e=>e.normalizeToNew(),lj,e)}};h[lj]=FlowGraphNormalizeVector3Block;let lK="FGDotVector3Block";let FlowGraphDotVector3Block=class FlowGraphDotVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,oL,(e,t)=>math_vector_Vector3.Dot(e,t),lK,e)}};h[lK]=FlowGraphDotVector3Block;let lq="FGCrossVector3Block";let FlowGraphCrossVector3Block=class FlowGraphCrossVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,ok,(e,t)=>math_vector_Vector3.Cross(e,t),lq,e)}};h[lq]=FlowGraphCrossVector3Block;let l$="FGCreateVector3Block";let FlowGraphCreateVector3Block=class FlowGraphCreateVector3Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=math_vector_Vector3.Zero(),this.x=this._registerDataInput("x",oL),this.y=this._registerDataInput("y",oL),this.z=this._registerDataInput("y",oL),this.vector=this._registerDataOutput("vector",ok)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this._cachedVector.z=this.z.getValue(e),this.vector.setValue(this._cachedVector,e)}getClassName(){return l$}};h[l$]=FlowGraphCreateVector3Block;let lQ="FGSplitVector3Block";let FlowGraphSplitVector3Block=class FlowGraphSplitVector3Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",ok),this.x=this._registerDataOutput("x",oL),this.y=this._registerDataOutput("y",oL),this.z=this._registerDataOutput("z",oL)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e),this.z.setValue(t.z,e)}getClassName(){return lQ}};h[lQ]=FlowGraphSplitVector3Block;let lZ="FGRotateVector3Block";let FlowGraphRotate3dVector3Block=class FlowGraphRotate3dVector3Block extends FlowGraphBlock{constructor(e){super(e),this._cachedQuaternion=new math_vector_Quaternion,this.input=this._registerDataInput("input",ok),this.angle=this._registerDataInput("angle",oL),this.output=this._registerDataOutput("output",ok)}_updateOutputs(e){let t=math_vector_Quaternion.RotationAxisToRef(this.axis.getValue(e),this.angle.getValue(e),this._cachedQuaternion),i=this.input.getValue(e),r=this.output.getValue(e);i.applyRotationQuaternionToRef(t,r)}getClassName(){return lZ}};h[lZ]=FlowGraphRotate3dVector3Block;let lJ="FGTransformVector3Block";let FlowGraphTransformVector3Block=class FlowGraphTransformVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,ok,ok,(e,t)=>math_vector_Vector3.TransformCoordinatesToRef(t,e,this._cachedResult),lJ,e),this._cachedResult=math_vector_Vector3.Zero()}};h[lJ]=FlowGraphTransformVector3Block;let l0="FGAddVector4Block";let FlowGraphAddVector4Block=class FlowGraphAddVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oG,oG,oG,(e,t)=>e.add(t),l0,e)}};h[l0]=FlowGraphAddVector4Block;let l1="FGSubtractVector4Block";let FlowGraphSubtractVector4Block=class FlowGraphSubtractVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oG,oG,oG,(e,t)=>e.subtract(t),l1,e)}};h[l1]=FlowGraphSubtractVector4Block;let l2="FGMultiplyVector4Block";let FlowGraphMultiplyVector4Block=class FlowGraphMultiplyVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oG,oG,oG,(e,t)=>e.multiply(t),l2,e)}};h[l2]=FlowGraphMultiplyVector4Block;let l3="FGDivideVector4Block";let FlowGraphDivideVector4Block=class FlowGraphDivideVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oG,oG,oG,(e,t)=>e.divide(t),l3,e)}};h[l3]=FlowGraphDivideVector4Block;let l4="FGScaleVector4Block";let FlowGraphScaleVector4Block=class FlowGraphScaleVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oG,oL,oG,(e,t)=>e.scale(t),l4,e)}};h[l4]=FlowGraphScaleVector4Block;let l5="FGLengthVector4Block";let FlowGraphLengthVector4Block=class FlowGraphLengthVector4Block extends FlowGraphUnaryOperationBlock{constructor(e){super(oG,oL,e=>e.length(),l5,e)}};h[l5]=FlowGraphLengthVector4Block;let l6="FGNormalizeVector4Block";let FlowGraphNormalizeVector4Block=class FlowGraphNormalizeVector4Block extends FlowGraphUnaryOperationBlock{constructor(e){super(oG,oG,e=>{let t=e.clone();return t.normalize(),t},l6,e)}getClassName(){return l6}};h[l6]=FlowGraphNormalizeVector4Block;let l8="FGCreateVector4Block";let FlowGraphCreateVector4Block=class FlowGraphCreateVector4Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=math_vector_Vector4.Zero(),this.x=this._registerDataInput("x",oL),this.y=this._registerDataInput("y",oL),this.z=this._registerDataInput("y",oL),this.w=this._registerDataInput("w",oL),this.vector=this._registerDataOutput("vector",oG)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this._cachedVector.z=this.z.getValue(e),this._cachedVector.w=this.w.getValue(e),this.vector.setValue(this._cachedVector,e)}getClassName(){return l8}};h[l8]=FlowGraphCreateVector4Block;let l7="FGSplitVector4Block";let FlowGraphSplitVector4Block=class FlowGraphSplitVector4Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",oG),this.x=this._registerDataOutput("x",oL),this.y=this._registerDataOutput("y",oL),this.z=this._registerDataOutput("z",oL),this.w=this._registerDataOutput("w",oL)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e),this.z.setValue(t.z,e),this.w.setValue(t.w,e)}getClassName(){return l7}};h[l7]=FlowGraphSplitVector4Block;let l9="FGAddMatrixBlock";let FlowGraphAddMatrixBlock=class FlowGraphAddMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oz,oz,(e,t)=>e.addToRef(t,this._cachedMatrix),l9,e),this._cachedMatrix=math_vector_Matrix.Zero()}};h[l9]=FlowGraphAddMatrixBlock;let he="FGAddMatrixAndNumberBlock";let FlowGraphAddMatrixAndNumberBlock=class FlowGraphAddMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oL,oz,(e,t)=>{for(let i=0;i<e.m.length;i++)this._cachedArray[i]=e.m[i]+t;return math_vector_Matrix.FromArrayToRef(this._cachedArray,0,this._cachedMatrix)},he,e),this._cachedArray=new Float32Array(16),this._cachedMatrix=math_vector_Matrix.Zero()}};h[he]=FlowGraphAddMatrixAndNumberBlock;let ht="FGSubtractMatrixBlock";let FlowGraphSubtractMatrixBlock=class FlowGraphSubtractMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oz,oz,(e,t)=>e.addToRef(t.scaleToRef(-1,math_vector_TmpVectors.Matrix[0]),this._cachedMatrix),ht,e),this._cachedMatrix=math_vector_Matrix.Zero()}};h[ht]=FlowGraphSubtractMatrixBlock;let hi="FGSubtractMatrixAndNumberBlock";let FlowGraphSubtractMatrixAndNumberBlock=class FlowGraphSubtractMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oL,oz,(e,t)=>{for(let i=0;i<e.m.length;i++)this._cachedArray[i]=e.m[i]-t;return math_vector_Matrix.FromArrayToRef(this._cachedArray,0,this._cachedMatrix)},hi,e),this._cachedArray=new Float32Array(16),this._cachedMatrix=math_vector_Matrix.Zero()}};h[hi]=FlowGraphSubtractMatrixAndNumberBlock;let hr="FGMultiplyMatrixBlock";let FlowGraphMultiplyMatrixBlock=class FlowGraphMultiplyMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oz,oz,(e,t)=>e.multiplyToRef(t,this._cachedMatrix),hr,e),this._cachedMatrix=math_vector_Matrix.Zero()}};h[hr]=FlowGraphMultiplyMatrixBlock;let hs="FGDivideMatrixBlock";let FlowGraphDivideMatrixBlock=class FlowGraphDivideMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oz,oz,(e,t)=>e.multiplyToRef(t.invertToRef(math_vector_TmpVectors.Matrix[0]),this._cachedResultMatrix),hs,e),this._cachedResultMatrix=math_vector_Matrix.Zero()}};h[hs]=FlowGraphDivideMatrixBlock;let ha="FGDivideMatrixAndNumberBlock";let FlowGraphDivideMatrixAndNumberBlock=class FlowGraphDivideMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oL,oz,(e,t)=>{for(let i=0;i<e.m.length;i++)this._cachedArray[i]=e.m[i]/t;return math_vector_Matrix.FromArrayToRef(this._cachedArray,0,this._cachedMatrix)},ha,e),this._cachedArray=new Float32Array(16),this._cachedMatrix=math_vector_Matrix.Zero()}};h[ha]=FlowGraphDivideMatrixAndNumberBlock;let hn="FGScaleMatrixBlock";let FlowGraphScaleMatrixBlock=class FlowGraphScaleMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oL,oz,(e,t)=>e.scaleToRef(t,this._cachedMatrix),hn,e),this._cachedMatrix=math_vector_Matrix.Zero()}};h[hn]=FlowGraphScaleMatrixBlock;let ho="FGClampMatrixBlock";let FlowGraphClampMatrixBlock=class FlowGraphClampMatrixBlock extends FlowGraphBlock{constructor(e){super(e),this._cachedArray=new Float32Array(16),this._cachedMatrix=math_vector_Matrix.Identity(),this.input=this._registerDataInput("input",oz),this.min=this._registerDataInput("min",oL),this.max=this._registerDataInput("max",oL),this.output=this._registerDataOutput("output",oz)}_updateOutputs(e){let t=this.input.getValue(e),i=this.min.getValue(e),r=this.max.getValue(e);for(let e=0;e<t.m.length;e++)this._cachedArray[e]=Math.min(Math.max(t.m[e],i),r);math_vector_Matrix.FromArrayToRef(this._cachedArray,0,this._cachedMatrix),this.output.setValue(this._cachedMatrix,e)}getClassName(){return ho}};h[ho]=FlowGraphClampMatrixBlock;let hl="FGDecomposeMatrixBlock";let FlowGraphDecomposeMatrixBlock=class FlowGraphDecomposeMatrixBlock extends FlowGraphBlock{constructor(e){super(e),this._cachedTranslation=new math_vector_Vector3,this._cachedRotation=new math_vector_Quaternion,this._cachedScale=new math_vector_Vector3,this.input=this._registerDataInput("input",oz),this.translation=this._registerDataOutput("translation",ok),this.rotation=this._registerDataOutput("rotation",oX),this.scale=this._registerDataOutput("scale",ok)}_updateOutputs(e){let t=this.input.getValue(e);t.decompose(this._cachedScale,this._cachedRotation,this._cachedTranslation),this.translation.setValue(this._cachedTranslation,e),this.rotation.setValue(this._cachedRotation,e),this.scale.setValue(this._cachedScale,e)}getClassName(){return hl}};h[hl]=FlowGraphDecomposeMatrixBlock;let hh="FGComposeMatrixBlock";let FlowGraphComposeMatrixBlock=class FlowGraphComposeMatrixBlock extends FlowGraphBlock{constructor(e){super(e),this._cachedMatrix=new math_vector_Matrix,this.output=this._registerDataOutput("input",oz),this.translation=this._registerDataInput("translation",ok),this.rotation=this._registerDataInput("rotation",oX),this.scale=this._registerDataInput("scale",ok)}_updateOutputs(e){let t=this.translation.getValue(e),i=this.rotation.getValue(e),r=this.scale.getValue(e);math_vector_Matrix.ComposeToRef(r,i,t,this._cachedMatrix),this.output.setValue(this._cachedMatrix,e)}getClassName(){return hh}};h[hh]=FlowGraphComposeMatrixBlock;let hc="FGQuaternionToRotationMatrixBlock";let FlowGraphQuaternionToRotationMatrixBlock=class FlowGraphQuaternionToRotationMatrixBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oX,oz,e=>math_vector_Matrix.FromQuaternionToRef(e,this._cachedMatrix),hc,e),this._cachedMatrix=new math_vector_Matrix}};h[hc]=FlowGraphQuaternionToRotationMatrixBlock;let hu="FGGetTransformationMatrixBlock";let FlowGraphGetTransformationMatrixBlock=class FlowGraphGetTransformationMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oF,oF,oz,(e,t)=>{let i=e.getWorldMatrix(),r=t.getWorldMatrix(),s=r.invertToRef(math_vector_TmpVectors.Matrix[0]),a=s.multiplyToRef(i,this._cachedResult);return a},hu,e),this._cachedResult=math_vector_Matrix.Zero()}};h[hu]=FlowGraphGetTransformationMatrixBlock;let FlowGraphMeshPickEventBlock=class FlowGraphMeshPickEventBlock extends FlowGraphEventBlock{constructor(e){super(e),this.config=e}configure(){super.configure(),this._meshVariableName=this.config.meshVariableName}_preparePendingTasks(e){let t=e._getExecutionVariable(this,"meshPickObserver");if(!t){let i=e.getVariable(this._meshVariableName);t=i.getScene().onPointerObservable.add(t=>{var r;t.type===pointerEvents_PointerEventTypes.POINTERPICK&&(null===(r=t.pickInfo)||void 0===r?void 0:r.pickedMesh)===i&&this._execute(e)});let r=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",r)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){let t=e.getVariable(this._meshVariableName),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return"FGMeshPickEventBlock"}};h.FGMeshPickEventBlock=FlowGraphMeshPickEventBlock;let FlowGraphSceneReadyEventBlock=class FlowGraphSceneReadyEventBlock extends FlowGraphEventBlock{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){let t=e.configuration.scene,i=t.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",i)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneReadyObserver"),i=e.configuration.scene;i.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return"FGSceneReadyEventBlock"}};h.FGSceneReadyEventBlock=FlowGraphSceneReadyEventBlock;let FlowGraphReceiveCustomEventBlock=class FlowGraphReceiveCustomEventBlock extends FlowGraphEventBlock{constructor(e){super(e),this.config=e,this.eventData=this._registerDataOutput("eventData",oF)}_preparePendingTasks(e){let t=e.configuration.eventCoordinator.getCustomEventObservable(this.config.eventId);this._eventObserver=t.add(t=>{this.eventData.setValue(t,e),this._execute(e)})}_cancelPendingTasks(e){let t=e.configuration.eventCoordinator.getCustomEventObservable(this.config.eventId);t?t.remove(this._eventObserver):tools_Tools.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this.config.eventId}`)}getClassName(){return"FGReceiveCustomEventBlock"}};h.FGReceiveCustomEventBlock=FlowGraphReceiveCustomEventBlock;let FlowGraphSceneTickEventBlock=class FlowGraphSceneTickEventBlock extends FlowGraphEventBlock{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneBeforeRender")){let t=e.configuration.scene,i=t.onBeforeRenderObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",i)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneBeforeRender"),i=e.configuration.scene;i.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return"FGSceneTickEventBlock"}};h.FGSceneTickEventBlock=FlowGraphSceneTickEventBlock}}; \ No newline at end of file diff --git a/.next/server/client-reference-manifest.js b/.next/server/client-reference-manifest.js deleted file mode 100644 index 6b429cb..0000000 --- a/.next/server/client-reference-manifest.js +++ /dev/null @@ -1 +0,0 @@ -self.__RSC_MANIFEST={"ssrModuleMapping":{"476":{"*":{"id":"7711","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"":{"id":"7711","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"default":{"id":"7711","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false}},"553":{"*":{"id":"7711","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"":{"id":"7711","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"default":{"id":"7711","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false}},"1010":{"*":{"id":"7844","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"7844","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"7844","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"1785":{"*":{"id":"606","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"606","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"606","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"RedirectErrorBoundary":{"id":"606","name":"RedirectErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"RedirectBoundary":{"id":"606","name":"RedirectBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"1899":{"*":{"id":"5121","name":"*","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"":{"id":"5121","name":"","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"default":{"id":"5121","name":"default","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"metadata":{"id":"5121","name":"metadata","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false}},"2645":{"*":{"id":"5157","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"":{"id":"5157","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"default":{"id":"5157","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false}},"3866":{"*":{"id":"7711","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"":{"id":"7711","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"default":{"id":"7711","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"getParameters":{"id":"7711","name":"getParameters","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false}},"4143":{"*":{"id":"3100","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"3100","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"3100","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"4463":{"*":{"id":"6249","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"6249","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"6249","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"6828":{"*":{"id":"969","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"969","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"969","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"7069":{"*":{"id":"701","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"":{"id":"701","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"suspense":{"id":"701","name":"suspense","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"NoSSR":{"id":"701","name":"NoSSR","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false}},"8707":{"*":{"id":"7649","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"":{"id":"7649","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"default":{"id":"7649","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false}},"8827":{"*":{"id":"125","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"125","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"125","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"getServerActionDispatcher":{"id":"125","name":"getServerActionDispatcher","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"urlToUrlWithoutFlightMarker":{"id":"125","name":"urlToUrlWithoutFlightMarker","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"9126":{"*":{"id":"1522","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"1522","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"1522","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"ErrorBoundaryHandler":{"id":"1522","name":"ErrorBoundaryHandler","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"ErrorBoundary":{"id":"1522","name":"ErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"9209":{"*":{"id":"9040","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"":{"id":"9040","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"default":{"id":"9040","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"defaultHead":{"id":"9040","name":"defaultHead","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false}}},"edgeSSRModuleMapping":{},"cssFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/3930d1a0ca01c66f.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"]},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":"8827","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":"8827","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js#":{"id":"8827","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js#":{"id":"8827","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js#default":{"id":"8827","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js#default":{"id":"8827","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js#getServerActionDispatcher":{"id":"8827","name":"getServerActionDispatcher","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js#getServerActionDispatcher":{"id":"8827","name":"getServerActionDispatcher","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js#urlToUrlWithoutFlightMarker":{"id":"8827","name":"urlToUrlWithoutFlightMarker","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js#urlToUrlWithoutFlightMarker":{"id":"8827","name":"urlToUrlWithoutFlightMarker","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":"9126","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":"9126","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js#":{"id":"9126","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js#":{"id":"9126","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js#default":{"id":"9126","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js#default":{"id":"9126","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js#ErrorBoundaryHandler":{"id":"9126","name":"ErrorBoundaryHandler","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js#ErrorBoundaryHandler":{"id":"9126","name":"ErrorBoundaryHandler","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js#ErrorBoundary":{"id":"9126","name":"ErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js#ErrorBoundary":{"id":"9126","name":"ErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":"4463","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":"4463","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js#":{"id":"4463","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js#":{"id":"4463","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js#default":{"id":"4463","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js#default":{"id":"4463","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js":{"id":"1785","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\redirect-boundary.js":{"id":"1785","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js#":{"id":"1785","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\redirect-boundary.js#":{"id":"1785","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js#default":{"id":"1785","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\redirect-boundary.js#default":{"id":"1785","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js#RedirectErrorBoundary":{"id":"1785","name":"RedirectErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\redirect-boundary.js#RedirectErrorBoundary":{"id":"1785","name":"RedirectErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js#RedirectBoundary":{"id":"1785","name":"RedirectBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\redirect-boundary.js#RedirectBoundary":{"id":"1785","name":"RedirectBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":"1010","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":"1010","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js#":{"id":"1010","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js#":{"id":"1010","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js#default":{"id":"1010","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js#default":{"id":"1010","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\fetch-server-response.js":{"id":"6828","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\router-reducer\\fetch-server-response.js":{"id":"6828","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\fetch-server-response.js#":{"id":"6828","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\router-reducer\\fetch-server-response.js#":{"id":"6828","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\fetch-server-response.js#default":{"id":"6828","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\router-reducer\\fetch-server-response.js#default":{"id":"6828","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":"4143","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":"4143","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js#":{"id":"4143","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js#":{"id":"4143","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js#default":{"id":"4143","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js#default":{"id":"4143","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js":{"id":"6406","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js":{"id":"6406","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#":{"id":"6406","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#":{"id":"6406","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#CacheStates":{"id":"6406","name":"CacheStates","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#CacheStates":{"id":"6406","name":"CacheStates","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#AppRouterContext":{"id":"6406","name":"AppRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#AppRouterContext":{"id":"6406","name":"AppRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#LayoutRouterContext":{"id":"6406","name":"LayoutRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#LayoutRouterContext":{"id":"6406","name":"LayoutRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#GlobalLayoutRouterContext":{"id":"6406","name":"GlobalLayoutRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#GlobalLayoutRouterContext":{"id":"6406","name":"GlobalLayoutRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#TemplateContext":{"id":"6406","name":"TemplateContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#TemplateContext":{"id":"6406","name":"TemplateContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hooks-client-context.js":{"id":"1416","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\hooks-client-context.js":{"id":"1416","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hooks-client-context.js#":{"id":"1416","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\hooks-client-context.js#":{"id":"1416","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hooks-client-context.js#SearchParamsContext":{"id":"1416","name":"SearchParamsContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\hooks-client-context.js#SearchParamsContext":{"id":"1416","name":"SearchParamsContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hooks-client-context.js#PathnameContext":{"id":"1416","name":"PathnameContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\hooks-client-context.js#PathnameContext":{"id":"1416","name":"PathnameContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\server-inserted-html.js":{"id":"3063","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\server-inserted-html.js":{"id":"3063","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\server-inserted-html.js#":{"id":"3063","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\server-inserted-html.js#":{"id":"3063","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\server-inserted-html.js#ServerInsertedHTMLContext":{"id":"3063","name":"ServerInsertedHTMLContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\server-inserted-html.js#ServerInsertedHTMLContext":{"id":"3063","name":"ServerInsertedHTMLContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\server-inserted-html.js#useServerInsertedHTML":{"id":"3063","name":"useServerInsertedHTML","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\server-inserted-html.js#useServerInsertedHTML":{"id":"3063","name":"useServerInsertedHTML","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss#":{"id":"null","name":"default","chunks":["static/css/3930d1a0ca01c66f.css"]},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}#":{"id":"null","name":"default","chunks":["static/css/3930d1a0ca01c66f.css"]},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss#":{"id":"null","name":"default","chunks":["static/css/60c69e914bf8dd4b.css"]},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":"2645","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx#":{"id":"2645","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx#default":{"id":"2645","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\Card.tsx":{"id":"2645","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\Card.tsx#":{"id":"2645","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\Card.tsx#default":{"id":"2645","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\image.js":{"id":"8707","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\image.js":{"id":"8707","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\image.js#":{"id":"8707","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\image.js#":{"id":"8707","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\image.js#default":{"id":"8707","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\image.js#default":{"id":"8707","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head.js":{"id":"9209","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\head.js":{"id":"9209","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head.js#":{"id":"9209","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\head.js#":{"id":"9209","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head.js#default":{"id":"9209","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\head.js#default":{"id":"9209","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head.js#defaultHead":{"id":"9209","name":"defaultHead","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\head.js#defaultHead":{"id":"9209","name":"defaultHead","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx":{"id":"1899","name":"*","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx#":{"id":"1899","name":"","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx#default":{"id":"1899","name":"default","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx#metadata":{"id":"1899","name":"metadata","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js":{"id":"7069","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js":{"id":"7069","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#":{"id":"7069","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#":{"id":"7069","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#suspense":{"id":"7069","name":"suspense","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#suspense":{"id":"7069","name":"suspense","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#NoSSR":{"id":"7069","name":"NoSSR","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#NoSSR":{"id":"7069","name":"NoSSR","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonInteractivity.tsx":{"id":"553","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonInteractivity.tsx#":{"id":"553","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonInteractivity.tsx#default":{"id":"553","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\ParameterPanel.tsx":{"id":"3866","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\ParameterPanel.tsx#":{"id":"3866","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\ParameterPanel.tsx#default":{"id":"3866","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\ParameterPanel.tsx#getParameters":{"id":"3866","name":"getParameters","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx":{"id":"476","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx#":{"id":"476","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx#default":{"id":"476","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonScene.tsx":{"id":"6716","name":"*","chunks":["716:static/chunks/716.9317a587abbcf60a.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonScene.tsx#":{"id":"6716","name":"","chunks":["716:static/chunks/716.9317a587abbcf60a.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonScene.tsx#default":{"id":"6716","name":"default","chunks":["716:static/chunks/716.9317a587abbcf60a.js"],"async":false}}} \ No newline at end of file diff --git a/.next/server/client-reference-manifest.json b/.next/server/client-reference-manifest.json deleted file mode 100644 index 99d9723..0000000 --- a/.next/server/client-reference-manifest.json +++ /dev/null @@ -1 +0,0 @@ -{"ssrModuleMapping":{"476":{"*":{"id":"7711","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"":{"id":"7711","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"default":{"id":"7711","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false}},"553":{"*":{"id":"7711","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"":{"id":"7711","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"default":{"id":"7711","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false}},"1010":{"*":{"id":"7844","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"7844","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"7844","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"1785":{"*":{"id":"606","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"606","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"606","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"RedirectErrorBoundary":{"id":"606","name":"RedirectErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"RedirectBoundary":{"id":"606","name":"RedirectBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"1899":{"*":{"id":"5121","name":"*","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"":{"id":"5121","name":"","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"default":{"id":"5121","name":"default","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"metadata":{"id":"5121","name":"metadata","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false}},"2645":{"*":{"id":"5157","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"":{"id":"5157","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"default":{"id":"5157","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false}},"3866":{"*":{"id":"7711","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"":{"id":"7711","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"default":{"id":"7711","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"getParameters":{"id":"7711","name":"getParameters","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false}},"4143":{"*":{"id":"3100","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"3100","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"3100","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"4463":{"*":{"id":"6249","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"6249","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"6249","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"6828":{"*":{"id":"969","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"969","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"969","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"7069":{"*":{"id":"701","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"":{"id":"701","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"suspense":{"id":"701","name":"suspense","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"NoSSR":{"id":"701","name":"NoSSR","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false}},"8707":{"*":{"id":"7649","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"":{"id":"7649","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"default":{"id":"7649","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false}},"8827":{"*":{"id":"125","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"125","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"125","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"getServerActionDispatcher":{"id":"125","name":"getServerActionDispatcher","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"urlToUrlWithoutFlightMarker":{"id":"125","name":"urlToUrlWithoutFlightMarker","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"9126":{"*":{"id":"1522","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"":{"id":"1522","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"default":{"id":"1522","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"ErrorBoundaryHandler":{"id":"1522","name":"ErrorBoundaryHandler","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"ErrorBoundary":{"id":"1522","name":"ErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false}},"9209":{"*":{"id":"9040","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"":{"id":"9040","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"default":{"id":"9040","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"defaultHead":{"id":"9040","name":"defaultHead","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false}}},"edgeSSRModuleMapping":{},"cssFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/3930d1a0ca01c66f.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"]},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":"8827","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":"8827","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js#":{"id":"8827","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js#":{"id":"8827","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js#default":{"id":"8827","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js#default":{"id":"8827","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js#getServerActionDispatcher":{"id":"8827","name":"getServerActionDispatcher","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js#getServerActionDispatcher":{"id":"8827","name":"getServerActionDispatcher","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js#urlToUrlWithoutFlightMarker":{"id":"8827","name":"urlToUrlWithoutFlightMarker","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js#urlToUrlWithoutFlightMarker":{"id":"8827","name":"urlToUrlWithoutFlightMarker","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":"9126","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":"9126","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js#":{"id":"9126","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js#":{"id":"9126","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js#default":{"id":"9126","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js#default":{"id":"9126","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js#ErrorBoundaryHandler":{"id":"9126","name":"ErrorBoundaryHandler","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js#ErrorBoundaryHandler":{"id":"9126","name":"ErrorBoundaryHandler","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js#ErrorBoundary":{"id":"9126","name":"ErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js#ErrorBoundary":{"id":"9126","name":"ErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":"4463","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":"4463","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js#":{"id":"4463","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js#":{"id":"4463","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js#default":{"id":"4463","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js#default":{"id":"4463","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js":{"id":"1785","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\redirect-boundary.js":{"id":"1785","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js#":{"id":"1785","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\redirect-boundary.js#":{"id":"1785","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js#default":{"id":"1785","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\redirect-boundary.js#default":{"id":"1785","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js#RedirectErrorBoundary":{"id":"1785","name":"RedirectErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\redirect-boundary.js#RedirectErrorBoundary":{"id":"1785","name":"RedirectErrorBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js#RedirectBoundary":{"id":"1785","name":"RedirectBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\redirect-boundary.js#RedirectBoundary":{"id":"1785","name":"RedirectBoundary","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":"1010","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":"1010","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js#":{"id":"1010","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js#":{"id":"1010","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js#default":{"id":"1010","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js#default":{"id":"1010","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\fetch-server-response.js":{"id":"6828","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\router-reducer\\fetch-server-response.js":{"id":"6828","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\fetch-server-response.js#":{"id":"6828","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\router-reducer\\fetch-server-response.js#":{"id":"6828","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\fetch-server-response.js#default":{"id":"6828","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\router-reducer\\fetch-server-response.js#default":{"id":"6828","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":"4143","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":"4143","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js#":{"id":"4143","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js#":{"id":"4143","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js#default":{"id":"4143","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js#default":{"id":"4143","name":"default","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js":{"id":"6406","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js":{"id":"6406","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#":{"id":"6406","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#":{"id":"6406","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#CacheStates":{"id":"6406","name":"CacheStates","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#CacheStates":{"id":"6406","name":"CacheStates","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#AppRouterContext":{"id":"6406","name":"AppRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#AppRouterContext":{"id":"6406","name":"AppRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#LayoutRouterContext":{"id":"6406","name":"LayoutRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#LayoutRouterContext":{"id":"6406","name":"LayoutRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#GlobalLayoutRouterContext":{"id":"6406","name":"GlobalLayoutRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#GlobalLayoutRouterContext":{"id":"6406","name":"GlobalLayoutRouterContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.js#TemplateContext":{"id":"6406","name":"TemplateContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\app-router-context.js#TemplateContext":{"id":"6406","name":"TemplateContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hooks-client-context.js":{"id":"1416","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\hooks-client-context.js":{"id":"1416","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hooks-client-context.js#":{"id":"1416","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\hooks-client-context.js#":{"id":"1416","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hooks-client-context.js#SearchParamsContext":{"id":"1416","name":"SearchParamsContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\hooks-client-context.js#SearchParamsContext":{"id":"1416","name":"SearchParamsContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hooks-client-context.js#PathnameContext":{"id":"1416","name":"PathnameContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\hooks-client-context.js#PathnameContext":{"id":"1416","name":"PathnameContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\server-inserted-html.js":{"id":"3063","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\server-inserted-html.js":{"id":"3063","name":"*","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\server-inserted-html.js#":{"id":"3063","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\server-inserted-html.js#":{"id":"3063","name":"","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\server-inserted-html.js#ServerInsertedHTMLContext":{"id":"3063","name":"ServerInsertedHTMLContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\server-inserted-html.js#ServerInsertedHTMLContext":{"id":"3063","name":"ServerInsertedHTMLContext","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\server-inserted-html.js#useServerInsertedHTML":{"id":"3063","name":"useServerInsertedHTML","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\server-inserted-html.js#useServerInsertedHTML":{"id":"3063","name":"useServerInsertedHTML","chunks":["272:static/chunks/webpack-54b114c68857d808.js","667:static/chunks/2443530c-097fe1871e1d7679.js","488:static/chunks/488-66ca2c1db348e680.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss#":{"id":"null","name":"default","chunks":["static/css/3930d1a0ca01c66f.css"]},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}#":{"id":"null","name":"default","chunks":["static/css/3930d1a0ca01c66f.css"]},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss#":{"id":"null","name":"default","chunks":["static/css/60c69e914bf8dd4b.css"]},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":"2645","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx#":{"id":"2645","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx#default":{"id":"2645","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\Card.tsx":{"id":"2645","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\Card.tsx#":{"id":"2645","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\Card.tsx#default":{"id":"2645","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\image.js":{"id":"8707","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\image.js":{"id":"8707","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\image.js#":{"id":"8707","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\image.js#":{"id":"8707","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\image.js#default":{"id":"8707","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\image.js#default":{"id":"8707","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head.js":{"id":"9209","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\head.js":{"id":"9209","name":"*","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head.js#":{"id":"9209","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\head.js#":{"id":"9209","name":"","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head.js#default":{"id":"9209","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\head.js#default":{"id":"9209","name":"default","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head.js#defaultHead":{"id":"9209","name":"defaultHead","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\head.js#defaultHead":{"id":"9209","name":"defaultHead","chunks":["931:static/chunks/app/page-8204c3b0f59bd205.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx":{"id":"1899","name":"*","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx#":{"id":"1899","name":"","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx#default":{"id":"1899","name":"default","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx#metadata":{"id":"1899","name":"metadata","chunks":["619:static/chunks/app/wiston/page-becb82f49ed47545.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js":{"id":"7069","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js":{"id":"7069","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#":{"id":"7069","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#":{"id":"7069","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#suspense":{"id":"7069","name":"suspense","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#suspense":{"id":"7069","name":"suspense","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#NoSSR":{"id":"7069","name":"NoSSR","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js#NoSSR":{"id":"7069","name":"NoSSR","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonInteractivity.tsx":{"id":"553","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonInteractivity.tsx#":{"id":"553","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonInteractivity.tsx#default":{"id":"553","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\ParameterPanel.tsx":{"id":"3866","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\ParameterPanel.tsx#":{"id":"3866","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\ParameterPanel.tsx#default":{"id":"3866","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\ParameterPanel.tsx#getParameters":{"id":"3866","name":"getParameters","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx":{"id":"476","name":"*","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx#":{"id":"476","name":"","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx#default":{"id":"476","name":"default","chunks":["995:static/chunks/f75787ed-011198ef7e5d7754.js","267:static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","9:static/chunks/f126df28-0647fc1012c29407.js","669:static/chunks/51231e76-cf1b2fc1d6b83e48.js","369:static/chunks/53417c1a-c755bb806ffa7a5d.js","23:static/chunks/23-fb41cbadaf19fac2.js","514:static/chunks/app/space/page-aa0f5917bd776cea.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonScene.tsx":{"id":"6716","name":"*","chunks":["716:static/chunks/716.9317a587abbcf60a.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonScene.tsx#":{"id":"6716","name":"","chunks":["716:static/chunks/716.9317a587abbcf60a.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonScene.tsx#default":{"id":"6716","name":"default","chunks":["716:static/chunks/716.9317a587abbcf60a.js"],"async":false}}} \ No newline at end of file diff --git a/.next/server/flight-server-css-manifest.js b/.next/server/flight-server-css-manifest.js deleted file mode 100644 index 1cdf6d3..0000000 --- a/.next/server/flight-server-css-manifest.js +++ /dev/null @@ -1 +0,0 @@ -self.__RSC_CSS_MANIFEST={"cssImports":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss"]},"cssModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}"]}} \ No newline at end of file diff --git a/.next/server/flight-server-css-manifest.json b/.next/server/flight-server-css-manifest.json deleted file mode 100644 index 43db000..0000000 --- a/.next/server/flight-server-css-manifest.json +++ /dev/null @@ -1 +0,0 @@ -{"cssImports":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss"]},"cssModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page":["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}"]}} \ No newline at end of file diff --git a/.next/server/functions-config-manifest.json b/.next/server/functions-config-manifest.json new file mode 100644 index 0000000..c534788 --- /dev/null +++ b/.next/server/functions-config-manifest.json @@ -0,0 +1 @@ +{"version":1,"functions":{"/wiston":{}}} \ No newline at end of file diff --git a/.next/server/middleware-build-manifest.js b/.next/server/middleware-build-manifest.js index 174ff9f..60342d1 100644 --- a/.next/server/middleware-build-manifest.js +++ b/.next/server/middleware-build-manifest.js @@ -1 +1 @@ -self.__BUILD_MANIFEST={polyfillFiles:["static/chunks/polyfills-c67a75d1b6f99dc8.js"],devFiles:[],ampDevFiles:[],lowPriorityFiles:["static/Qb5fVlqLpQAODnw100j4z/_buildManifest.js","static/Qb5fVlqLpQAODnw100j4z/_ssgManifest.js"],rootMainFiles:["static/chunks/webpack-54b114c68857d808.js","static/chunks/2443530c-097fe1871e1d7679.js","static/chunks/488-66ca2c1db348e680.js","static/chunks/main-app-0be5dce44311dbbf.js"],pages:{"/_app":["static/chunks/webpack-54b114c68857d808.js","static/chunks/framework-8883d1e9be70c3da.js","static/chunks/main-dba5d122367f02b7.js","static/chunks/pages/_app-b555d5e1eab47959.js"],"/_error":["static/chunks/webpack-54b114c68857d808.js","static/chunks/framework-8883d1e9be70c3da.js","static/chunks/main-dba5d122367f02b7.js","static/chunks/pages/_error-d79168f986538ac0.js"]},ampFirstPages:[]}; \ No newline at end of file +self.__BUILD_MANIFEST={polyfillFiles:["static/chunks/polyfills-c67a75d1b6f99dc8.js"],devFiles:[],ampDevFiles:[],lowPriorityFiles:["static/9CqSqX2Hqhh4fwiD8kSfJ/_buildManifest.js","static/9CqSqX2Hqhh4fwiD8kSfJ/_ssgManifest.js"],rootMainFiles:["static/chunks/webpack-c42a79c5d8b7c910.js","static/chunks/fd9d1056-ba10bf844a47945b.js","static/chunks/472-51fd3a56159f1e5b.js","static/chunks/main-app-cf3eb22ffef632f7.js"],pages:{"/_app":["static/chunks/webpack-c42a79c5d8b7c910.js","static/chunks/framework-8883d1e9be70c3da.js","static/chunks/main-07bf56c05aa7cd6e.js","static/chunks/pages/_app-1534f180665c857f.js"],"/_error":["static/chunks/webpack-c42a79c5d8b7c910.js","static/chunks/framework-8883d1e9be70c3da.js","static/chunks/main-07bf56c05aa7cd6e.js","static/chunks/pages/_error-b646007f40c4f0a8.js"]},ampFirstPages:[]}; \ No newline at end of file diff --git a/.next/server/middleware-react-loadable-manifest.js b/.next/server/middleware-react-loadable-manifest.js index bebba06..170749e 100644 --- a/.next/server/middleware-react-loadable-manifest.js +++ b/.next/server/middleware-react-loadable-manifest.js @@ -1 +1 @@ -self.__REACT_LOADABLE_MANIFEST={}; \ No newline at end of file +self.__REACT_LOADABLE_MANIFEST="{}"; \ No newline at end of file diff --git a/.next/server/next-font-manifest.js b/.next/server/next-font-manifest.js index fc97220..8267a50 100644 --- a/.next/server/next-font-manifest.js +++ b/.next/server/next-font-manifest.js @@ -1 +1 @@ -self.__NEXT_FONT_MANIFEST={pages:{},app:{},appUsingSizeAdjust:!1,pagesUsingSizeAdjust:!1}; \ No newline at end of file +self.__NEXT_FONT_MANIFEST='{"pages":{},"app":{},"appUsingSizeAdjust":false,"pagesUsingSizeAdjust":false}'; \ No newline at end of file diff --git a/.next/server/next-font-manifest.json b/.next/server/next-font-manifest.json index e0cc400..25f78e7 100644 --- a/.next/server/next-font-manifest.json +++ b/.next/server/next-font-manifest.json @@ -1,6 +1 @@ -{ - "pages": {}, - "app": {}, - "appUsingSizeAdjust": false, - "pagesUsingSizeAdjust": false -} \ No newline at end of file +{"pages":{},"app":{},"appUsingSizeAdjust":false,"pagesUsingSizeAdjust":false} \ No newline at end of file diff --git a/.next/server/pages-manifest.json b/.next/server/pages-manifest.json index ec0b049..15d96be 100644 --- a/.next/server/pages-manifest.json +++ b/.next/server/pages-manifest.json @@ -1,6 +1 @@ -{ - "/_app": "pages/_app.js", - "/_error": "pages/_error.js", - "/_document": "pages/_document.js", - "/404": "pages/404.html" -} \ No newline at end of file +{"/_error":"pages/_error.js","/_app":"pages/_app.js","/_document":"pages/_document.js","/404":"pages/404.html"} \ No newline at end of file diff --git a/.next/server/pages/404.html b/.next/server/pages/404.html index abaefe7..adf7e8f 100644 --- a/.next/server/pages/404.html +++ b/.next/server/pages/404.html @@ -1 +1 @@ -<!DOCTYPE html><html><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width"/><title>404: This page could not be found

    404

    This page could not be found.

    \ No newline at end of file +404: This page could not be found.sukadia.dev

    404

    This page could not be found.

    \ No newline at end of file diff --git a/.next/server/pages/500.html b/.next/server/pages/500.html index 26ea14e..8673f90 100644 --- a/.next/server/pages/500.html +++ b/.next/server/pages/500.html @@ -1 +1 @@ -500: Internal Server Error

    500

    Internal Server Error.

    \ No newline at end of file +500: Internal Server Error

    500

    Internal Server Error.

    \ No newline at end of file diff --git a/.next/server/pages/_app.js b/.next/server/pages/_app.js index 596587a..fe4e34d 100644 --- a/.next/server/pages/_app.js +++ b/.next/server/pages/_app.js @@ -1,94 +1 @@ -"use strict"; -(() => { -var exports = {}; -exports.id = 888; -exports.ids = [888]; -exports.modules = { - -/***/ 1767: -/***/ ((module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "default", ({ - enumerable: true, - get: function() { - return App; - } -})); -const _interop_require_default = __webpack_require__(167); -const _react = /*#__PURE__*/ _interop_require_default._(__webpack_require__(6689)); -const _utils = __webpack_require__(9232); -/** - * `App` component is used for initialize of pages. It allows for overwriting and full control of the `page` initialization. - * This allows for keeping state between navigation, custom error handling, injecting additional data. - */ async function appGetInitialProps(param) { - let { Component , ctx } = param; - const pageProps = await (0, _utils.loadGetInitialProps)(Component, ctx); - return { - pageProps - }; -} -class App extends _react.default.Component { - render() { - const { Component , pageProps } = this.props; - return /*#__PURE__*/ _react.default.createElement(Component, pageProps); - } -} -(()=>{ - App.origGetInitialProps = appGetInitialProps; -})(); -(()=>{ - App.getInitialProps = appGetInitialProps; -})(); -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=_app.js.map - - -/***/ }), - -/***/ 9232: -/***/ ((module) => { - -module.exports = require("next/dist/shared/lib/utils.js"); - -/***/ }), - -/***/ 6689: -/***/ ((module) => { - -module.exports = require("react"); - -/***/ }), - -/***/ 167: -/***/ ((__unused_webpack_module, exports) => { - - - -exports._ = exports._interop_require_default = _interop_require_default; -function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { default: obj }; -} - - -/***/ }) - -}; -; - -// load runtime -var __webpack_require__ = require("../webpack-runtime.js"); -__webpack_require__.C(exports); -var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId)) -var __webpack_exports__ = (__webpack_exec__(1767)); -module.exports = __webpack_exports__; - -})(); \ No newline at end of file +"use strict";(()=>{var e={};e.id=888,e.ids=[888],e.modules={6689:e=>{e.exports=require("react")}};var r=require("../webpack-runtime.js");r.C(e);var __webpack_exec__=e=>r(r.s=e),_=r.X(0,[310,840],()=>__webpack_exec__(2840));module.exports=_})(); \ No newline at end of file diff --git a/.next/server/pages/_app.js.nft.json b/.next/server/pages/_app.js.nft.json index 366fe67..2859415 100644 --- a/.next/server/pages/_app.js.nft.json +++ b/.next/server/pages/_app.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../webpack-runtime.js","../../package.json","../../../node_modules/next/dist/shared/lib/utils.js","../../../node_modules/next/package.json","../../../node_modules/react/package.json","../../../node_modules/react/index.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/cjs/react.development.js","../../../package.json","../../../node_modules/next/dist/pages/_app.js"]} \ No newline at end of file +{"version":1,"files":["../../../node_modules/next/dist/pages/_app.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/index.js","../../../node_modules/react/package.json","../../../package.json","../../package.json","../chunks/106.js","../chunks/2.js","../chunks/201.js","../chunks/310.js","../chunks/323.js","../chunks/622.js","../chunks/676.js","../chunks/837.js","../chunks/840.js","../chunks/862.js","../chunks/984.js","../chunks/font-manifest.json","../webpack-runtime.js"]} \ No newline at end of file diff --git a/.next/server/pages/_document.js b/.next/server/pages/_document.js index 19c1e1e..35a176d 100644 --- a/.next/server/pages/_document.js +++ b/.next/server/pages/_document.js @@ -1,930 +1 @@ -"use strict"; -(() => { -var exports = {}; -exports.id = 660; -exports.ids = [660]; -exports.modules = { - -/***/ 7248: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - Head: function() { - return Head; - }, - NextScript: function() { - return NextScript; - }, - Html: function() { - return Html; - }, - Main: function() { - return Main; - }, - /** - * `Document` component handles the initial `document` markup and renders only on the server side. - * Commonly used for implementing server side rendering for `css-in-js` libraries. - */ default: function() { - return Document; - } -}); -const _react = /*#__PURE__*/ _interop_require_wildcard(__webpack_require__(6689)); -const _constants = __webpack_require__(6724); -const _getpagefiles = __webpack_require__(4140); -const _htmlescape = __webpack_require__(9716); -const _iserror = /*#__PURE__*/ _interop_require_default(__webpack_require__(676)); -const _htmlcontext = __webpack_require__(8743); -function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -} -function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -} -function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) { - return obj; - } - if (obj === null || typeof obj !== "object" && typeof obj !== "function") { - return { - default: obj - }; - } - var cache = _getRequireWildcardCache(nodeInterop); - if (cache && cache.has(obj)) { - return cache.get(obj); - } - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for(var key in obj){ - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - newObj.default = obj; - if (cache) { - cache.set(obj, newObj); - } - return newObj; -} -/** Set of pages that have triggered a large data warning on production mode. */ const largePageDataWarnings = new Set(); -function getDocumentFiles(buildManifest, pathname, inAmpMode) { - const sharedFiles = (0, _getpagefiles.getPageFiles)(buildManifest, "/_app"); - const pageFiles = true && inAmpMode ? [] : (0, _getpagefiles.getPageFiles)(buildManifest, pathname); - return { - sharedFiles, - pageFiles, - allFiles: [ - ...new Set([ - ...sharedFiles, - ...pageFiles - ]) - ] - }; -} -function getPolyfillScripts(context, props) { - // polyfills.js has to be rendered as nomodule without async - // It also has to be the first script to load - const { assetPrefix , buildManifest , devOnlyCacheBusterQueryString , disableOptimizedLoading , crossOrigin } = context; - return buildManifest.polyfillFiles.filter((polyfill)=>polyfill.endsWith(".js") && !polyfill.endsWith(".module.js")).map((polyfill)=>/*#__PURE__*/ _react.default.createElement("script", { - key: polyfill, - defer: !disableOptimizedLoading, - nonce: props.nonce, - crossOrigin: props.crossOrigin || crossOrigin, - noModule: true, - src: `${assetPrefix}/_next/${polyfill}${devOnlyCacheBusterQueryString}` - })); -} -function hasComponentProps(child) { - return !!child && !!child.props; -} -function AmpStyles({ styles }) { - if (!styles) return null; - // try to parse styles from fragment for backwards compat - const curStyles = Array.isArray(styles) ? styles : []; - if (styles.props && // @ts-ignore Property 'props' does not exist on type ReactElement - Array.isArray(styles.props.children)) { - const hasStyles = (el)=>{ - var _el_props, _el_props_dangerouslySetInnerHTML; - return el == null ? void 0 : (_el_props = el.props) == null ? void 0 : (_el_props_dangerouslySetInnerHTML = _el_props.dangerouslySetInnerHTML) == null ? void 0 : _el_props_dangerouslySetInnerHTML.__html; - }; - // @ts-ignore Property 'props' does not exist on type ReactElement - styles.props.children.forEach((child)=>{ - if (Array.isArray(child)) { - child.forEach((el)=>hasStyles(el) && curStyles.push(el)); - } else if (hasStyles(child)) { - curStyles.push(child); - } - }); - } - /* Add custom styles before AMP styles to prevent accidental overrides */ return /*#__PURE__*/ _react.default.createElement("style", { - "amp-custom": "", - dangerouslySetInnerHTML: { - __html: curStyles.map((style)=>style.props.dangerouslySetInnerHTML.__html).join("").replace(/\/\*# sourceMappingURL=.*\*\//g, "").replace(/\/\*@ sourceURL=.*?\*\//g, "") - } - }); -} -function getDynamicChunks(context, props, files) { - const { dynamicImports , assetPrefix , isDevelopment , devOnlyCacheBusterQueryString , disableOptimizedLoading , crossOrigin } = context; - return dynamicImports.map((file)=>{ - if (!file.endsWith(".js") || files.allFiles.includes(file)) return null; - return /*#__PURE__*/ _react.default.createElement("script", { - async: !isDevelopment && disableOptimizedLoading, - defer: !disableOptimizedLoading, - key: file, - src: `${assetPrefix}/_next/${encodeURI(file)}${devOnlyCacheBusterQueryString}`, - nonce: props.nonce, - crossOrigin: props.crossOrigin || crossOrigin - }); - }); -} -function getScripts(context, props, files) { - var _buildManifest_lowPriorityFiles; - const { assetPrefix , buildManifest , isDevelopment , devOnlyCacheBusterQueryString , disableOptimizedLoading , crossOrigin } = context; - const normalScripts = files.allFiles.filter((file)=>file.endsWith(".js")); - const lowPriorityScripts = (_buildManifest_lowPriorityFiles = buildManifest.lowPriorityFiles) == null ? void 0 : _buildManifest_lowPriorityFiles.filter((file)=>file.endsWith(".js")); - return [ - ...normalScripts, - ...lowPriorityScripts - ].map((file)=>{ - return /*#__PURE__*/ _react.default.createElement("script", { - key: file, - src: `${assetPrefix}/_next/${encodeURI(file)}${devOnlyCacheBusterQueryString}`, - nonce: props.nonce, - async: !isDevelopment && disableOptimizedLoading, - defer: !disableOptimizedLoading, - crossOrigin: props.crossOrigin || crossOrigin - }); - }); -} -function getPreNextWorkerScripts(context, props) { - const { assetPrefix , scriptLoader , crossOrigin , nextScriptWorkers } = context; - // disable `nextScriptWorkers` in edge runtime - if (!nextScriptWorkers || "nodejs" === "edge") return null; - try { - let { partytownSnippet } = require("@builder.io/partytown/integration"); - const children = Array.isArray(props.children) ? props.children : [ - props.children - ]; - // Check to see if the user has defined their own Partytown configuration - const userDefinedConfig = children.find((child)=>{ - var _child_props, _child_props_dangerouslySetInnerHTML; - return hasComponentProps(child) && (child == null ? void 0 : (_child_props = child.props) == null ? void 0 : (_child_props_dangerouslySetInnerHTML = _child_props.dangerouslySetInnerHTML) == null ? void 0 : _child_props_dangerouslySetInnerHTML.__html.length) && "data-partytown-config" in child.props; - }); - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, !userDefinedConfig && /*#__PURE__*/ _react.default.createElement("script", { - "data-partytown-config": "", - dangerouslySetInnerHTML: { - __html: ` - partytown = { - lib: "${assetPrefix}/_next/static/~partytown/" - }; - ` - } - }), /*#__PURE__*/ _react.default.createElement("script", { - "data-partytown": "", - dangerouslySetInnerHTML: { - __html: partytownSnippet() - } - }), (scriptLoader.worker || []).map((file, index)=>{ - const { strategy , src , children: scriptChildren , dangerouslySetInnerHTML , ...scriptProps } = file; - let srcProps = {}; - if (src) { - // Use external src if provided - srcProps.src = src; - } else if (dangerouslySetInnerHTML && dangerouslySetInnerHTML.__html) { - // Embed inline script if provided with dangerouslySetInnerHTML - srcProps.dangerouslySetInnerHTML = { - __html: dangerouslySetInnerHTML.__html - }; - } else if (scriptChildren) { - // Embed inline script if provided with children - srcProps.dangerouslySetInnerHTML = { - __html: typeof scriptChildren === "string" ? scriptChildren : Array.isArray(scriptChildren) ? scriptChildren.join("") : "" - }; - } else { - throw new Error("Invalid usage of next/script. Did you forget to include a src attribute or an inline script? https://nextjs.org/docs/messages/invalid-script"); - } - return /*#__PURE__*/ _react.default.createElement("script", { - ...srcProps, - ...scriptProps, - type: "text/partytown", - key: src || index, - nonce: props.nonce, - "data-nscript": "worker", - crossOrigin: props.crossOrigin || crossOrigin - }); - })); - } catch (err) { - if ((0, _iserror.default)(err) && err.code !== "MODULE_NOT_FOUND") { - console.warn(`Warning: ${err.message}`); - } - return null; - } -} -function getPreNextScripts(context, props) { - const { scriptLoader , disableOptimizedLoading , crossOrigin } = context; - const webWorkerScripts = getPreNextWorkerScripts(context, props); - const beforeInteractiveScripts = (scriptLoader.beforeInteractive || []).filter((script)=>script.src).map((file, index)=>{ - const { strategy , ...scriptProps } = file; - return /*#__PURE__*/ _react.default.createElement("script", { - ...scriptProps, - key: scriptProps.src || index, - defer: scriptProps.defer ?? !disableOptimizedLoading, - nonce: props.nonce, - "data-nscript": "beforeInteractive", - crossOrigin: props.crossOrigin || crossOrigin - }); - }); - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, webWorkerScripts, beforeInteractiveScripts); -} -function getHeadHTMLProps(props) { - const { crossOrigin , nonce , ...restProps } = props; - // This assignment is necessary for additional type checking to avoid unsupported attributes in - const headProps = restProps; - return headProps; -} -function getAmpPath(ampPath, asPath) { - return ampPath || `${asPath}${asPath.includes("?") ? "&" : "?"}amp=1`; -} -function getNextFontLinkTags(nextFontManifest, dangerousAsPath, assetPrefix = "") { - if (!nextFontManifest) { - return { - preconnect: null, - preload: null - }; - } - const appFontsEntry = nextFontManifest.pages["/_app"]; - const pageFontsEntry = nextFontManifest.pages[dangerousAsPath]; - const preloadedFontFiles = [ - ...appFontsEntry ?? [], - ...pageFontsEntry ?? [] - ]; - // If no font files should preload but there's an entry for the path, add a preconnect tag. - const preconnectToSelf = !!(preloadedFontFiles.length === 0 && (appFontsEntry || pageFontsEntry)); - return { - preconnect: preconnectToSelf ? /*#__PURE__*/ _react.default.createElement("link", { - "data-next-font": nextFontManifest.pagesUsingSizeAdjust ? "size-adjust" : "", - rel: "preconnect", - href: "/", - crossOrigin: "anonymous" - }) : null, - preload: preloadedFontFiles ? preloadedFontFiles.map((fontFile)=>{ - const ext = /\.(woff|woff2|eot|ttf|otf)$/.exec(fontFile)[1]; - return /*#__PURE__*/ _react.default.createElement("link", { - key: fontFile, - rel: "preload", - href: `${assetPrefix}/_next/${encodeURI(fontFile)}`, - as: "font", - type: `font/${ext}`, - crossOrigin: "anonymous", - "data-next-font": fontFile.includes("-s") ? "size-adjust" : "" - }); - }) : null - }; -} -class Head extends _react.default.Component { - static #_ = (()=>{ - this.contextType = _htmlcontext.HtmlContext; - })(); - getCssLinks(files) { - const { assetPrefix , devOnlyCacheBusterQueryString , dynamicImports , crossOrigin , optimizeCss , optimizeFonts } = this.context; - const cssFiles = files.allFiles.filter((f)=>f.endsWith(".css")); - const sharedFiles = new Set(files.sharedFiles); - // Unmanaged files are CSS files that will be handled directly by the - // webpack runtime (`mini-css-extract-plugin`). - let unmangedFiles = new Set([]); - let dynamicCssFiles = Array.from(new Set(dynamicImports.filter((file)=>file.endsWith(".css")))); - if (dynamicCssFiles.length) { - const existing = new Set(cssFiles); - dynamicCssFiles = dynamicCssFiles.filter((f)=>!(existing.has(f) || sharedFiles.has(f))); - unmangedFiles = new Set(dynamicCssFiles); - cssFiles.push(...dynamicCssFiles); - } - let cssLinkElements = []; - cssFiles.forEach((file)=>{ - const isSharedFile = sharedFiles.has(file); - if (!optimizeCss) { - cssLinkElements.push(/*#__PURE__*/ _react.default.createElement("link", { - key: `${file}-preload`, - nonce: this.props.nonce, - rel: "preload", - href: `${assetPrefix}/_next/${encodeURI(file)}${devOnlyCacheBusterQueryString}`, - as: "style", - crossOrigin: this.props.crossOrigin || crossOrigin - })); - } - const isUnmanagedFile = unmangedFiles.has(file); - cssLinkElements.push(/*#__PURE__*/ _react.default.createElement("link", { - key: file, - nonce: this.props.nonce, - rel: "stylesheet", - href: `${assetPrefix}/_next/${encodeURI(file)}${devOnlyCacheBusterQueryString}`, - crossOrigin: this.props.crossOrigin || crossOrigin, - "data-n-g": isUnmanagedFile ? undefined : isSharedFile ? "" : undefined, - "data-n-p": isUnmanagedFile ? undefined : isSharedFile ? undefined : "" - })); - }); - if ( true && optimizeFonts) { - cssLinkElements = this.makeStylesheetInert(cssLinkElements); - } - return cssLinkElements.length === 0 ? null : cssLinkElements; - } - getPreloadDynamicChunks() { - const { dynamicImports , assetPrefix , devOnlyCacheBusterQueryString , crossOrigin } = this.context; - return dynamicImports.map((file)=>{ - if (!file.endsWith(".js")) { - return null; - } - return /*#__PURE__*/ _react.default.createElement("link", { - rel: "preload", - key: file, - href: `${assetPrefix}/_next/${encodeURI(file)}${devOnlyCacheBusterQueryString}`, - as: "script", - nonce: this.props.nonce, - crossOrigin: this.props.crossOrigin || crossOrigin - }); - }) // Filter out nulled scripts - .filter(Boolean); - } - getPreloadMainLinks(files) { - const { assetPrefix , devOnlyCacheBusterQueryString , scriptLoader , crossOrigin } = this.context; - const preloadFiles = files.allFiles.filter((file)=>{ - return file.endsWith(".js"); - }); - return [ - ...(scriptLoader.beforeInteractive || []).map((file)=>/*#__PURE__*/ _react.default.createElement("link", { - key: file.src, - nonce: this.props.nonce, - rel: "preload", - href: file.src, - as: "script", - crossOrigin: this.props.crossOrigin || crossOrigin - })), - ...preloadFiles.map((file)=>/*#__PURE__*/ _react.default.createElement("link", { - key: file, - nonce: this.props.nonce, - rel: "preload", - href: `${assetPrefix}/_next/${encodeURI(file)}${devOnlyCacheBusterQueryString}`, - as: "script", - crossOrigin: this.props.crossOrigin || crossOrigin - })) - ]; - } - getBeforeInteractiveInlineScripts() { - const { scriptLoader } = this.context; - const { nonce , crossOrigin } = this.props; - return (scriptLoader.beforeInteractive || []).filter((script)=>!script.src && (script.dangerouslySetInnerHTML || script.children)).map((file, index)=>{ - const { strategy , children , dangerouslySetInnerHTML , src , ...scriptProps } = file; - let html = ""; - if (dangerouslySetInnerHTML && dangerouslySetInnerHTML.__html) { - html = dangerouslySetInnerHTML.__html; - } else if (children) { - html = typeof children === "string" ? children : Array.isArray(children) ? children.join("") : ""; - } - return /*#__PURE__*/ _react.default.createElement("script", { - ...scriptProps, - dangerouslySetInnerHTML: { - __html: html - }, - key: scriptProps.id || index, - nonce: nonce, - "data-nscript": "beforeInteractive", - crossOrigin: crossOrigin || undefined - }); - }); - } - getDynamicChunks(files) { - return getDynamicChunks(this.context, this.props, files); - } - getPreNextScripts() { - return getPreNextScripts(this.context, this.props); - } - getScripts(files) { - return getScripts(this.context, this.props, files); - } - getPolyfillScripts() { - return getPolyfillScripts(this.context, this.props); - } - makeStylesheetInert(node) { - return _react.default.Children.map(node, (c)=>{ - var _c_props, _c_props1; - if ((c == null ? void 0 : c.type) === "link" && (c == null ? void 0 : (_c_props = c.props) == null ? void 0 : _c_props.href) && _constants.OPTIMIZED_FONT_PROVIDERS.some(({ url })=>{ - var _c_props, _c_props_href; - return c == null ? void 0 : (_c_props = c.props) == null ? void 0 : (_c_props_href = _c_props.href) == null ? void 0 : _c_props_href.startsWith(url); - })) { - const newProps = { - ...c.props || {}, - "data-href": c.props.href, - href: undefined - }; - return /*#__PURE__*/ _react.default.cloneElement(c, newProps); - } else if (c == null ? void 0 : (_c_props1 = c.props) == null ? void 0 : _c_props1.children) { - const newProps = { - ...c.props || {}, - children: this.makeStylesheetInert(c.props.children) - }; - return /*#__PURE__*/ _react.default.cloneElement(c, newProps); - } - return c; - // @types/react bug. Returned value from .map will not be `null` if you pass in `[null]` - }).filter(Boolean); - } - render() { - const { styles , ampPath , inAmpMode , hybridAmp , canonicalBase , __NEXT_DATA__ , dangerousAsPath , headTags , unstable_runtimeJS , unstable_JsPreload , disableOptimizedLoading , optimizeCss , optimizeFonts , assetPrefix , nextFontManifest } = this.context; - const disableRuntimeJS = unstable_runtimeJS === false; - const disableJsPreload = unstable_JsPreload === false || !disableOptimizedLoading; - this.context.docComponentsRendered.Head = true; - let { head } = this.context; - let cssPreloads = []; - let otherHeadElements = []; - if (head) { - head.forEach((c)=>{ - let metaTag; - if (this.context.strictNextHead) { - metaTag = /*#__PURE__*/ _react.default.createElement("meta", { - name: "next-head", - content: "1" - }); - } - if (c && c.type === "link" && c.props["rel"] === "preload" && c.props["as"] === "style") { - metaTag && cssPreloads.push(metaTag); - cssPreloads.push(c); - } else { - if (c) { - if (metaTag && (c.type !== "meta" || !c.props["charSet"])) { - otherHeadElements.push(metaTag); - } - otherHeadElements.push(c); - } - } - }); - head = cssPreloads.concat(otherHeadElements); - } - let children = _react.default.Children.toArray(this.props.children).filter(Boolean); - // show a warning if Head contains (only in development) - if (false) {} - if ( true && optimizeFonts && !( true && inAmpMode)) { - children = this.makeStylesheetInert(children); - } - let hasAmphtmlRel = false; - let hasCanonicalRel = false; - // show warning and remove conflicting amp head tags - head = _react.default.Children.map(head || [], (child)=>{ - if (!child) return child; - const { type , props } = child; - if ( true && inAmpMode) { - let badProp = ""; - if (type === "meta" && props.name === "viewport") { - badProp = 'name="viewport"'; - } else if (type === "link" && props.rel === "canonical") { - hasCanonicalRel = true; - } else if (type === "script") { - // only block if - // 1. it has a src and isn't pointing to ampproject's CDN - // 2. it is using dangerouslySetInnerHTML without a type or - // a type of text/javascript - if (props.src && props.src.indexOf("ampproject") < -1 || props.dangerouslySetInnerHTML && (!props.type || props.type === "text/javascript")) { - badProp = "<script"; - Object.keys(props).forEach((prop)=>{ - badProp += ` ${prop}="${props[prop]}"`; - }); - badProp += "/>"; - } - } - if (badProp) { - console.warn(`Found conflicting amp tag "${child.type}" with conflicting prop ${badProp} in ${__NEXT_DATA__.page}. https://nextjs.org/docs/messages/conflicting-amp-tag`); - return null; - } - } else { - // non-amp mode - if (type === "link" && props.rel === "amphtml") { - hasAmphtmlRel = true; - } - } - return child; - // @types/react bug. Returned value from .map will not be `null` if you pass in `[null]` - }); - const files = getDocumentFiles(this.context.buildManifest, this.context.__NEXT_DATA__.page, true && inAmpMode); - const nextFontLinkTags = getNextFontLinkTags(nextFontManifest, dangerousAsPath, assetPrefix); - return /*#__PURE__*/ _react.default.createElement("head", getHeadHTMLProps(this.props), this.context.isDevelopment && /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement("style", { - "data-next-hide-fouc": true, - "data-ampdevmode": true && inAmpMode ? "true" : undefined, - dangerouslySetInnerHTML: { - __html: `body{display:none}` - } - }), /*#__PURE__*/ _react.default.createElement("noscript", { - "data-next-hide-fouc": true, - "data-ampdevmode": true && inAmpMode ? "true" : undefined - }, /*#__PURE__*/ _react.default.createElement("style", { - dangerouslySetInnerHTML: { - __html: `body{display:block}` - } - }))), head, this.context.strictNextHead ? null : /*#__PURE__*/ _react.default.createElement("meta", { - name: "next-head-count", - content: _react.default.Children.count(head || []).toString() - }), children, optimizeFonts && /*#__PURE__*/ _react.default.createElement("meta", { - name: "next-font-preconnect" - }), nextFontLinkTags.preconnect, nextFontLinkTags.preload, true && inAmpMode && /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement("meta", { - name: "viewport", - content: "width=device-width,minimum-scale=1,initial-scale=1" - }), !hasCanonicalRel && /*#__PURE__*/ _react.default.createElement("link", { - rel: "canonical", - href: canonicalBase + (__webpack_require__(6368).cleanAmpPath)(dangerousAsPath) - }), /*#__PURE__*/ _react.default.createElement("link", { - rel: "preload", - as: "script", - href: "https://cdn.ampproject.org/v0.js" - }), /*#__PURE__*/ _react.default.createElement(AmpStyles, { - styles: styles - }), /*#__PURE__*/ _react.default.createElement("style", { - "amp-boilerplate": "", - dangerouslySetInnerHTML: { - __html: `body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}` - } - }), /*#__PURE__*/ _react.default.createElement("noscript", null, /*#__PURE__*/ _react.default.createElement("style", { - "amp-boilerplate": "", - dangerouslySetInnerHTML: { - __html: `body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}` - } - })), /*#__PURE__*/ _react.default.createElement("script", { - async: true, - src: "https://cdn.ampproject.org/v0.js" - })), !( true && inAmpMode) && /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, !hasAmphtmlRel && hybridAmp && /*#__PURE__*/ _react.default.createElement("link", { - rel: "amphtml", - href: canonicalBase + getAmpPath(ampPath, dangerousAsPath) - }), this.getBeforeInteractiveInlineScripts(), !optimizeCss && this.getCssLinks(files), !optimizeCss && /*#__PURE__*/ _react.default.createElement("noscript", { - "data-n-css": this.props.nonce ?? "" - }), !disableRuntimeJS && !disableJsPreload && this.getPreloadDynamicChunks(), !disableRuntimeJS && !disableJsPreload && this.getPreloadMainLinks(files), !disableOptimizedLoading && !disableRuntimeJS && this.getPolyfillScripts(), !disableOptimizedLoading && !disableRuntimeJS && this.getPreNextScripts(), !disableOptimizedLoading && !disableRuntimeJS && this.getDynamicChunks(files), !disableOptimizedLoading && !disableRuntimeJS && this.getScripts(files), optimizeCss && this.getCssLinks(files), optimizeCss && /*#__PURE__*/ _react.default.createElement("noscript", { - "data-n-css": this.props.nonce ?? "" - }), this.context.isDevelopment && // this element is used to mount development styles so the - // ordering matches production - // (by default, style-loader injects at the bottom of <head />) - /*#__PURE__*/ _react.default.createElement("noscript", { - id: "__next_css__DO_NOT_USE__" - }), styles || null), /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, {}, ...headTags || [])); - } -} -function handleDocumentScriptLoaderItems(scriptLoader, __NEXT_DATA__, props) { - var _children_find, _children_find_props, _children_find1, _children_find_props1; - if (!props.children) return; - const scriptLoaderItems = []; - const children = Array.isArray(props.children) ? props.children : [ - props.children - ]; - const headChildren = (_children_find = children.find((child)=>child.type === Head)) == null ? void 0 : (_children_find_props = _children_find.props) == null ? void 0 : _children_find_props.children; - const bodyChildren = (_children_find1 = children.find((child)=>child.type === "body")) == null ? void 0 : (_children_find_props1 = _children_find1.props) == null ? void 0 : _children_find_props1.children; - // Scripts with beforeInteractive can be placed inside Head or <body> so children of both needs to be traversed - const combinedChildren = [ - ...Array.isArray(headChildren) ? headChildren : [ - headChildren - ], - ...Array.isArray(bodyChildren) ? bodyChildren : [ - bodyChildren - ] - ]; - _react.default.Children.forEach(combinedChildren, (child)=>{ - var _child_type; - if (!child) return; - // When using the `next/script` component, register it in script loader. - if ((_child_type = child.type) == null ? void 0 : _child_type.__nextScript) { - if (child.props.strategy === "beforeInteractive") { - scriptLoader.beforeInteractive = (scriptLoader.beforeInteractive || []).concat([ - { - ...child.props - } - ]); - return; - } else if ([ - "lazyOnload", - "afterInteractive", - "worker" - ].includes(child.props.strategy)) { - scriptLoaderItems.push(child.props); - return; - } - } - }); - __NEXT_DATA__.scriptLoader = scriptLoaderItems; -} -class NextScript extends _react.default.Component { - static #_ = (()=>{ - this.contextType = _htmlcontext.HtmlContext; - })(); - getDynamicChunks(files) { - return getDynamicChunks(this.context, this.props, files); - } - getPreNextScripts() { - return getPreNextScripts(this.context, this.props); - } - getScripts(files) { - return getScripts(this.context, this.props, files); - } - getPolyfillScripts() { - return getPolyfillScripts(this.context, this.props); - } - static getInlineScriptSource(context) { - const { __NEXT_DATA__ , largePageDataBytes } = context; - try { - const data = JSON.stringify(__NEXT_DATA__); - if (largePageDataWarnings.has(__NEXT_DATA__.page)) { - return (0, _htmlescape.htmlEscapeJsonString)(data); - } - const bytes = false ? 0 : Buffer.from(data).byteLength; - const prettyBytes = (__webpack_require__(5955)/* ["default"] */ .Z); - if (largePageDataBytes && bytes > largePageDataBytes) { - if (true) { - largePageDataWarnings.add(__NEXT_DATA__.page); - } - console.warn(`Warning: data for page "${__NEXT_DATA__.page}"${__NEXT_DATA__.page === context.dangerousAsPath ? "" : ` (path "${context.dangerousAsPath}")`} is ${prettyBytes(bytes)} which exceeds the threshold of ${prettyBytes(largePageDataBytes)}, this amount of data can reduce performance.\nSee more info here: https://nextjs.org/docs/messages/large-page-data`); - } - return (0, _htmlescape.htmlEscapeJsonString)(data); - } catch (err) { - if ((0, _iserror.default)(err) && err.message.indexOf("circular structure") !== -1) { - throw new Error(`Circular structure in "getInitialProps" result of page "${__NEXT_DATA__.page}". https://nextjs.org/docs/messages/circular-structure`); - } - throw err; - } - } - render() { - const { assetPrefix , inAmpMode , buildManifest , unstable_runtimeJS , docComponentsRendered , devOnlyCacheBusterQueryString , disableOptimizedLoading , crossOrigin } = this.context; - const disableRuntimeJS = unstable_runtimeJS === false; - docComponentsRendered.NextScript = true; - if ( true && inAmpMode) { - if (true) { - return null; - } - const ampDevFiles = [ - ...buildManifest.devFiles, - ...buildManifest.polyfillFiles, - ...buildManifest.ampDevFiles - ]; - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, disableRuntimeJS ? null : /*#__PURE__*/ _react.default.createElement("script", { - id: "__NEXT_DATA__", - type: "application/json", - nonce: this.props.nonce, - crossOrigin: this.props.crossOrigin || crossOrigin, - dangerouslySetInnerHTML: { - __html: NextScript.getInlineScriptSource(this.context) - }, - "data-ampdevmode": true - }), ampDevFiles.map((file)=>/*#__PURE__*/ _react.default.createElement("script", { - key: file, - src: `${assetPrefix}/_next/${file}${devOnlyCacheBusterQueryString}`, - nonce: this.props.nonce, - crossOrigin: this.props.crossOrigin || crossOrigin, - "data-ampdevmode": true - }))); - } - if (false) {} - const files = getDocumentFiles(this.context.buildManifest, this.context.__NEXT_DATA__.page, true && inAmpMode); - return /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, !disableRuntimeJS && buildManifest.devFiles ? buildManifest.devFiles.map((file)=>/*#__PURE__*/ _react.default.createElement("script", { - key: file, - src: `${assetPrefix}/_next/${encodeURI(file)}${devOnlyCacheBusterQueryString}`, - nonce: this.props.nonce, - crossOrigin: this.props.crossOrigin || crossOrigin - })) : null, disableRuntimeJS ? null : /*#__PURE__*/ _react.default.createElement("script", { - id: "__NEXT_DATA__", - type: "application/json", - nonce: this.props.nonce, - crossOrigin: this.props.crossOrigin || crossOrigin, - dangerouslySetInnerHTML: { - __html: NextScript.getInlineScriptSource(this.context) - } - }), disableOptimizedLoading && !disableRuntimeJS && this.getPolyfillScripts(), disableOptimizedLoading && !disableRuntimeJS && this.getPreNextScripts(), disableOptimizedLoading && !disableRuntimeJS && this.getDynamicChunks(files), disableOptimizedLoading && !disableRuntimeJS && this.getScripts(files)); - } -} -function Html(props) { - const { inAmpMode , docComponentsRendered , locale , scriptLoader , __NEXT_DATA__ } = (0, _react.useContext)(_htmlcontext.HtmlContext); - docComponentsRendered.Html = true; - handleDocumentScriptLoaderItems(scriptLoader, __NEXT_DATA__, props); - return /*#__PURE__*/ _react.default.createElement("html", { - ...props, - lang: props.lang || locale || undefined, - amp: true && inAmpMode ? "" : undefined, - "data-ampdevmode": true && inAmpMode && "production" !== "production" ? 0 : undefined - }); -} -function Main() { - const { docComponentsRendered } = (0, _react.useContext)(_htmlcontext.HtmlContext); - docComponentsRendered.Main = true; - // @ts-ignore - return /*#__PURE__*/ _react.default.createElement("next-js-internal-body-render-target", null); -} -class Document extends _react.default.Component { - /** - * `getInitialProps` hook returns the context object with the addition of `renderPage`. - * `renderPage` callback executes `React` rendering logic synchronously to support server-rendering wrappers - */ static getInitialProps(ctx) { - return ctx.defaultGetInitialProps(ctx); - } - render() { - return /*#__PURE__*/ _react.default.createElement(Html, null, /*#__PURE__*/ _react.default.createElement(Head, null), /*#__PURE__*/ _react.default.createElement("body", null, /*#__PURE__*/ _react.default.createElement(Main, null), /*#__PURE__*/ _react.default.createElement(NextScript, null))); - } -} -// Add a special property to the built-in `Document` component so later we can -// identify if a user customized `Document` is used or not. -const InternalFunctionDocument = function InternalFunctionDocument() { - return /*#__PURE__*/ _react.default.createElement(Html, null, /*#__PURE__*/ _react.default.createElement(Head, null), /*#__PURE__*/ _react.default.createElement("body", null, /*#__PURE__*/ _react.default.createElement(Main, null), /*#__PURE__*/ _react.default.createElement(NextScript, null))); -}; -Document[_constants.NEXT_BUILTIN_DOCUMENT] = InternalFunctionDocument; //# sourceMappingURL=_document.js.map - - -/***/ }), - -/***/ 676: -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - default: function() { - return isError; - }, - getProperError: function() { - return getProperError; - } -}); -const _isplainobject = __webpack_require__(8524); -function isError(err) { - return typeof err === "object" && err !== null && "name" in err && "message" in err; -} -function getProperError(err) { - if (isError(err)) { - return err; - } - if (false) {} - return new Error((0, _isplainobject.isPlainObject)(err) ? JSON.stringify(err) : err + ""); -} - -//# sourceMappingURL=is-error.js.map - -/***/ }), - -/***/ 5955: -/***/ ((__unused_webpack_module, exports) => { - -var __webpack_unused_export__; -/* -MIT License - -Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -__webpack_unused_export__ = ({ - value: true -}); -Object.defineProperty(exports, "Z", ({ - enumerable: true, - get: function() { - return prettyBytes; - } -})); -const UNITS = [ - "B", - "kB", - "MB", - "GB", - "TB", - "PB", - "EB", - "ZB", - "YB" -]; -/* -Formats the given number using `Number#toLocaleString`. -- If locale is a string, the value is expected to be a locale-key (for example: `de`). -- If locale is true, the system default locale is used for translation. -- If no value for locale is specified, the number is returned unmodified. -*/ const toLocaleString = (number, locale)=>{ - let result = number; - if (typeof locale === "string") { - result = number.toLocaleString(locale); - } else if (locale === true) { - result = number.toLocaleString(); - } - return result; -}; -function prettyBytes(number, options) { - if (!Number.isFinite(number)) { - throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`); - } - options = Object.assign({}, options); - if (options.signed && number === 0) { - return " 0 B"; - } - const isNegative = number < 0; - const prefix = isNegative ? "-" : options.signed ? "+" : ""; - if (isNegative) { - number = -number; - } - if (number < 1) { - const numberString = toLocaleString(number, options.locale); - return prefix + numberString + " B"; - } - const exponent = Math.min(Math.floor(Math.log10(number) / 3), UNITS.length - 1); - number = Number((number / Math.pow(1000, exponent)).toPrecision(3)); - const numberString = toLocaleString(number, options.locale); - const unit = UNITS[exponent]; - return prefix + numberString + " " + unit; -} - -//# sourceMappingURL=pretty-bytes.js.map - -/***/ }), - -/***/ 4140: -/***/ ((module) => { - -module.exports = require("next/dist/server/get-page-files.js"); - -/***/ }), - -/***/ 9716: -/***/ ((module) => { - -module.exports = require("next/dist/server/htmlescape.js"); - -/***/ }), - -/***/ 6368: -/***/ ((module) => { - -module.exports = require("next/dist/server/utils.js"); - -/***/ }), - -/***/ 6724: -/***/ ((module) => { - -module.exports = require("next/dist/shared/lib/constants.js"); - -/***/ }), - -/***/ 8743: -/***/ ((module) => { - -module.exports = require("next/dist/shared/lib/html-context.js"); - -/***/ }), - -/***/ 8524: -/***/ ((module) => { - -module.exports = require("next/dist/shared/lib/is-plain-object.js"); - -/***/ }), - -/***/ 6689: -/***/ ((module) => { - -module.exports = require("react"); - -/***/ }) - -}; -; - -// load runtime -var __webpack_require__ = require("../webpack-runtime.js"); -__webpack_require__.C(exports); -var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId)) -var __webpack_exports__ = (__webpack_exec__(7248)); -module.exports = __webpack_exports__; - -})(); \ No newline at end of file +"use strict";(()=>{var e={};e.id=660,e.ids=[660,888],e.modules={2785:e=>{e.exports=require("next/dist/compiled/next-server/pages.runtime.prod.js")},6689:e=>{e.exports=require("react")},1017:e=>{e.exports=require("path")}};var r=require("../webpack-runtime.js");r.C(e);var __webpack_exec__=e=>r(r.s=e),s=r.X(0,[310,676],()=>__webpack_exec__(8676));module.exports=s})(); \ No newline at end of file diff --git a/.next/server/pages/_document.js.nft.json b/.next/server/pages/_document.js.nft.json index 3fe9553..096bf32 100644 --- a/.next/server/pages/_document.js.nft.json +++ b/.next/server/pages/_document.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../webpack-runtime.js","../../package.json","../../../node_modules/next/dist/server/get-page-files.js","../../../node_modules/next/dist/server/htmlescape.js","../../../node_modules/next/dist/server/utils.js","../../../node_modules/next/dist/shared/lib/utils.js","../../../node_modules/next/dist/shared/lib/constants.js","../../../node_modules/next/dist/shared/lib/html-context.js","../../../node_modules/next/package.json","../../../node_modules/next/dist/shared/lib/is-plain-object.js","../../../node_modules/react/package.json","../../../node_modules/react/index.js","../../../node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js","../../../node_modules/next/dist/shared/lib/page-path/normalize-page-path.js","../../../node_modules/next/dist/shared/lib/modern-browserslist-target.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js","../../../node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js","../../../node_modules/next/dist/shared/lib/router/utils/index.js","../../../node_modules/next/dist/shared/lib/router/utils/sorted-routes.js","../../../node_modules/next/dist/shared/lib/router/utils/is-dynamic.js","../../../node_modules/@swc/helpers/_/_interop_require_default/package.json","../../../node_modules/@swc/helpers/package.json","../../../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../../../package.json","../../../node_modules/next/dist/pages/_document.js"]} \ No newline at end of file +{"version":1,"files":["../../../node_modules/client-only/index.js","../../../node_modules/client-only/package.json","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/jsonwebtoken/index.js","../../../node_modules/next/dist/compiled/jsonwebtoken/package.json","../../../node_modules/next/dist/compiled/lru-cache/index.js","../../../node_modules/next/dist/compiled/lru-cache/package.json","../../../node_modules/next/dist/compiled/next-server/pages.runtime.prod.js","../../../node_modules/next/dist/compiled/node-html-parser/index.js","../../../node_modules/next/dist/compiled/node-html-parser/package.json","../../../node_modules/next/dist/lib/semver-noop.js","../../../node_modules/next/dist/pages/_document.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../../../node_modules/react-dom/package.json","../../../node_modules/react-dom/server.browser.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/index.js","../../../node_modules/react/package.json","../../../node_modules/styled-jsx/dist/index/index.js","../../../node_modules/styled-jsx/index.js","../../../node_modules/styled-jsx/package.json","../../../package.json","../../package.json","../chunks/106.js","../chunks/2.js","../chunks/201.js","../chunks/310.js","../chunks/323.js","../chunks/622.js","../chunks/676.js","../chunks/837.js","../chunks/840.js","../chunks/862.js","../chunks/984.js","../chunks/font-manifest.json","../webpack-runtime.js"]} \ No newline at end of file diff --git a/.next/server/pages/_error.js b/.next/server/pages/_error.js index ff38ede..54b6e4e 100644 --- a/.next/server/pages/_error.js +++ b/.next/server/pages/_error.js @@ -1,412 +1 @@ -"use strict"; -(() => { -var exports = {}; -exports.id = 820; -exports.ids = [820]; -exports.modules = { - -/***/ 8476: -/***/ ((module, exports, __webpack_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "default", ({ - enumerable: true, - get: function() { - return Error; - } -})); -const _interop_require_default = __webpack_require__(167); -const _react = /*#__PURE__*/ _interop_require_default._(__webpack_require__(6689)); -const _head = /*#__PURE__*/ _interop_require_default._(__webpack_require__(8044)); -const statusCodes = { - 400: "Bad Request", - 404: "This page could not be found", - 405: "Method Not Allowed", - 500: "Internal Server Error" -}; -function _getInitialProps(param) { - let { res , err } = param; - const statusCode = res && res.statusCode ? res.statusCode : err ? err.statusCode : 404; - return { - statusCode - }; -} -const styles = { - error: { - // https://github.com/sindresorhus/modern-normalize/blob/main/modern-normalize.css#L38-L52 - fontFamily: 'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"', - height: "100vh", - textAlign: "center", - display: "flex", - flexDirection: "column", - alignItems: "center", - justifyContent: "center" - }, - desc: { - display: "inline-block", - textAlign: "left" - }, - h1: { - display: "inline-block", - margin: "0 20px 0 0", - paddingRight: 23, - fontSize: 24, - fontWeight: 500, - verticalAlign: "top", - lineHeight: "49px" - }, - h2: { - fontSize: 14, - fontWeight: 400, - lineHeight: "49px", - margin: 0 - } -}; -class Error extends _react.default.Component { - render() { - const { statusCode , withDarkMode =true } = this.props; - const title = this.props.title || statusCodes[statusCode] || "An unexpected error has occurred"; - return /*#__PURE__*/ _react.default.createElement("div", { - style: styles.error - }, /*#__PURE__*/ _react.default.createElement(_head.default, null, /*#__PURE__*/ _react.default.createElement("title", null, statusCode ? statusCode + ": " + title : "Application error: a client-side exception has occurred")), /*#__PURE__*/ _react.default.createElement("div", null, /*#__PURE__*/ _react.default.createElement("style", { - dangerouslySetInnerHTML: { - /* CSS minified from - body { margin: 0; color: #000; background: #fff; } - .next-error-h1 { - border-right: 1px solid rgba(0, 0, 0, .3); - } - - ${ - withDarkMode - ? `@media (prefers-color-scheme: dark) { - body { color: #fff; background: #000; } - .next-error-h1 { - border-right: 1px solid rgba(255, 255, 255, .3); - } - }` - : '' - } - */ __html: "body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}" + (withDarkMode ? "@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}" : "") - } - }), statusCode ? /*#__PURE__*/ _react.default.createElement("h1", { - className: "next-error-h1", - style: styles.h1 - }, statusCode) : null, /*#__PURE__*/ _react.default.createElement("div", { - style: styles.desc - }, /*#__PURE__*/ _react.default.createElement("h2", { - style: styles.h2 - }, this.props.title || statusCode ? title : /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, "Application error: a client-side exception has occurred (see the browser console for more information)"), ".")))); - } -} -(()=>{ - Error.displayName = "ErrorPage"; -})(); -(()=>{ - Error.getInitialProps = _getInitialProps; -})(); -(()=>{ - Error.origGetInitialProps = _getInitialProps; -})(); -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=_error.js.map - - -/***/ }), - -/***/ 8044: -/***/ ((module, exports, __webpack_require__) => { - -/* __next_internal_client_entry_do_not_use__ cjs */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -0 && (0); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - defaultHead: function() { - return defaultHead; - }, - default: function() { - return _default; - } -}); -const _interop_require_default = __webpack_require__(167); -const _interop_require_wildcard = __webpack_require__(8760); -const _react = /*#__PURE__*/ _interop_require_wildcard._(__webpack_require__(6689)); -const _sideeffect = /*#__PURE__*/ _interop_require_default._(__webpack_require__(2470)); -const _ampcontext = __webpack_require__(3918); -const _headmanagercontext = __webpack_require__(2796); -const _ampmode = __webpack_require__(5732); -const _warnonce = __webpack_require__(618); -function defaultHead(inAmpMode) { - if (inAmpMode === void 0) inAmpMode = false; - const head = [ - /*#__PURE__*/ _react.default.createElement("meta", { - charSet: "utf-8" - }) - ]; - if (!inAmpMode) { - head.push(/*#__PURE__*/ _react.default.createElement("meta", { - name: "viewport", - content: "width=device-width" - })); - } - return head; -} -function onlyReactElement(list, child) { - // React children can be "string" or "number" in this case we ignore them for backwards compat - if (typeof child === "string" || typeof child === "number") { - return list; - } - // Adds support for React.Fragment - if (child.type === _react.default.Fragment) { - return list.concat(_react.default.Children.toArray(child.props.children).reduce((fragmentList, fragmentChild)=>{ - if (typeof fragmentChild === "string" || typeof fragmentChild === "number") { - return fragmentList; - } - return fragmentList.concat(fragmentChild); - }, [])); - } - return list.concat(child); -} -const METATYPES = [ - "name", - "httpEquiv", - "charSet", - "itemProp" -]; -/* - returns a function for filtering head child elements - which shouldn't be duplicated, like <title/> - Also adds support for deduplicated `key` properties -*/ function unique() { - const keys = new Set(); - const tags = new Set(); - const metaTypes = new Set(); - const metaCategories = {}; - return (h)=>{ - let isUnique = true; - let hasKey = false; - if (h.key && typeof h.key !== "number" && h.key.indexOf("$") > 0) { - hasKey = true; - const key = h.key.slice(h.key.indexOf("$") + 1); - if (keys.has(key)) { - isUnique = false; - } else { - keys.add(key); - } - } - // eslint-disable-next-line default-case - switch(h.type){ - case "title": - case "base": - if (tags.has(h.type)) { - isUnique = false; - } else { - tags.add(h.type); - } - break; - case "meta": - for(let i = 0, len = METATYPES.length; i < len; i++){ - const metatype = METATYPES[i]; - if (!h.props.hasOwnProperty(metatype)) continue; - if (metatype === "charSet") { - if (metaTypes.has(metatype)) { - isUnique = false; - } else { - metaTypes.add(metatype); - } - } else { - const category = h.props[metatype]; - const categories = metaCategories[metatype] || new Set(); - if ((metatype !== "name" || !hasKey) && categories.has(category)) { - isUnique = false; - } else { - categories.add(category); - metaCategories[metatype] = categories; - } - } - } - break; - } - return isUnique; - }; -} -/** - * - * @param headChildrenElements List of children of <Head> - */ function reduceComponents(headChildrenElements, props) { - const { inAmpMode } = props; - return headChildrenElements.reduce(onlyReactElement, []).reverse().concat(defaultHead(inAmpMode).reverse()).filter(unique()).reverse().map((c, i)=>{ - const key = c.key || i; - if ( true && !inAmpMode) { - if (c.type === "link" && c.props["href"] && // TODO(prateekbh@): Replace this with const from `constants` when the tree shaking works. - [ - "https://fonts.googleapis.com/css", - "https://use.typekit.net/" - ].some((url)=>c.props["href"].startsWith(url))) { - const newProps = { - ...c.props || {} - }; - newProps["data-href"] = newProps["href"]; - newProps["href"] = undefined; - // Add this attribute to make it easy to identify optimized tags - newProps["data-optimized-fonts"] = true; - return /*#__PURE__*/ _react.default.cloneElement(c, newProps); - } - } - if (false) {} - return /*#__PURE__*/ _react.default.cloneElement(c, { - key - }); - }); -} -/** - * This component injects elements to `<head>` of your page. - * To avoid duplicated `tags` in `<head>` you can use the `key` property, which will make sure every tag is only rendered once. - */ function Head(param) { - let { children } = param; - const ampState = (0, _react.useContext)(_ampcontext.AmpStateContext); - const headManager = (0, _react.useContext)(_headmanagercontext.HeadManagerContext); - return /*#__PURE__*/ _react.default.createElement(_sideeffect.default, { - reduceComponentsToState: reduceComponents, - headManager: headManager, - inAmpMode: (0, _ampmode.isInAmpMode)(ampState) - }, children); -} -const _default = Head; -if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { - Object.defineProperty(exports.default, "__esModule", { - value: true - }); - Object.assign(exports.default, exports); - module.exports = exports.default; -} //# sourceMappingURL=head.js.map - - -/***/ }), - -/***/ 3918: -/***/ ((module) => { - -module.exports = require("next/dist/shared/lib/amp-context.js"); - -/***/ }), - -/***/ 5732: -/***/ ((module) => { - -module.exports = require("next/dist/shared/lib/amp-mode.js"); - -/***/ }), - -/***/ 2796: -/***/ ((module) => { - -module.exports = require("next/dist/shared/lib/head-manager-context.js"); - -/***/ }), - -/***/ 2470: -/***/ ((module) => { - -module.exports = require("next/dist/shared/lib/side-effect.js"); - -/***/ }), - -/***/ 618: -/***/ ((module) => { - -module.exports = require("next/dist/shared/lib/utils/warn-once.js"); - -/***/ }), - -/***/ 6689: -/***/ ((module) => { - -module.exports = require("react"); - -/***/ }), - -/***/ 167: -/***/ ((__unused_webpack_module, exports) => { - - - -exports._ = exports._interop_require_default = _interop_require_default; -function _interop_require_default(obj) { - return obj && obj.__esModule ? obj : { default: obj }; -} - - -/***/ }), - -/***/ 8760: -/***/ ((__unused_webpack_module, exports) => { - - - -function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - - var cacheBabelInterop = new WeakMap(); - var cacheNodeInterop = new WeakMap(); - - return (_getRequireWildcardCache = function(nodeInterop) { - return nodeInterop ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); -} -exports._ = exports._interop_require_wildcard = _interop_require_wildcard; -function _interop_require_wildcard(obj, nodeInterop) { - if (!nodeInterop && obj && obj.__esModule) return obj; - if (obj === null || typeof obj !== "object" && typeof obj !== "function") return { default: obj }; - - var cache = _getRequireWildcardCache(nodeInterop); - - if (cache && cache.has(obj)) return cache.get(obj); - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc); - else newObj[key] = obj[key]; - } - } - - newObj.default = obj; - - if (cache) cache.set(obj, newObj); - - return newObj; -} - - -/***/ }) - -}; -; - -// load runtime -var __webpack_require__ = require("../webpack-runtime.js"); -__webpack_require__.C(exports); -var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId)) -var __webpack_exports__ = (__webpack_exec__(8476)); -module.exports = __webpack_exports__; - -})(); \ No newline at end of file +"use strict";(()=>{var e={};e.id=820,e.ids=[820,888,660],e.modules={6051:(e,t,r)=>{r.r(t),r.d(t,{config:()=>d,default:()=>c,getServerSideProps:()=>S,getStaticPaths:()=>g,getStaticProps:()=>_,reportWebVitals:()=>P,routeModule:()=>f,unstable_getServerProps:()=>x,unstable_getServerSideProps:()=>h,unstable_getStaticParams:()=>v,unstable_getStaticPaths:()=>m,unstable_getStaticProps:()=>b});var a=r(7093),s=r(5244),i=r(1323),l=r(8676),o=r.n(l),n=r(2840),p=r.n(n),u=r(2534);let c=(0,i.l)(u,"default"),_=(0,i.l)(u,"getStaticProps"),g=(0,i.l)(u,"getStaticPaths"),S=(0,i.l)(u,"getServerSideProps"),d=(0,i.l)(u,"config"),P=(0,i.l)(u,"reportWebVitals"),b=(0,i.l)(u,"unstable_getStaticProps"),m=(0,i.l)(u,"unstable_getStaticPaths"),v=(0,i.l)(u,"unstable_getStaticParams"),x=(0,i.l)(u,"unstable_getServerProps"),h=(0,i.l)(u,"unstable_getServerSideProps"),f=new a.PagesRouteModule({definition:{kind:s.x.PAGES,page:"/_error",pathname:"/_error",bundlePath:"",filename:""},components:{App:p(),Document:o()},userland:u})},2785:e=>{e.exports=require("next/dist/compiled/next-server/pages.runtime.prod.js")},6689:e=>{e.exports=require("react")},1017:e=>{e.exports=require("path")}};var t=require("../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),r=t.X(0,[310,676,840,2],()=>__webpack_exec__(6051));module.exports=r})(); \ No newline at end of file diff --git a/.next/server/pages/_error.js.nft.json b/.next/server/pages/_error.js.nft.json index 1d70372..e79ee65 100644 --- a/.next/server/pages/_error.js.nft.json +++ b/.next/server/pages/_error.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../webpack-runtime.js","../../package.json","../../../node_modules/next/package.json","../../../node_modules/next/dist/shared/lib/amp-context.js","../../../node_modules/next/dist/shared/lib/amp-mode.js","../../../node_modules/next/dist/shared/lib/side-effect.js","../../../node_modules/next/dist/shared/lib/head-manager-context.js","../../../node_modules/next/dist/shared/lib/utils/warn-once.js","../../../node_modules/react/package.json","../../../node_modules/react/index.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/@swc/helpers/_/_interop_require_default/package.json","../../../node_modules/@swc/helpers/_/_interop_require_wildcard/package.json","../../../node_modules/@swc/helpers/package.json","../../../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../../../node_modules/@swc/helpers/cjs/_interop_require_wildcard.cjs","../../../package.json","../../../node_modules/next/dist/pages/_error.js"]} \ No newline at end of file +{"version":1,"files":["../../../node_modules/client-only/index.js","../../../node_modules/client-only/package.json","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/jsonwebtoken/index.js","../../../node_modules/next/dist/compiled/jsonwebtoken/package.json","../../../node_modules/next/dist/compiled/lru-cache/index.js","../../../node_modules/next/dist/compiled/lru-cache/package.json","../../../node_modules/next/dist/compiled/next-server/pages.runtime.prod.js","../../../node_modules/next/dist/compiled/node-html-parser/index.js","../../../node_modules/next/dist/compiled/node-html-parser/package.json","../../../node_modules/next/dist/lib/semver-noop.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../../../node_modules/react-dom/package.json","../../../node_modules/react-dom/server.browser.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/index.js","../../../node_modules/react/package.json","../../../node_modules/styled-jsx/dist/index/index.js","../../../node_modules/styled-jsx/index.js","../../../node_modules/styled-jsx/package.json","../../package.json","../chunks/106.js","../chunks/2.js","../chunks/201.js","../chunks/310.js","../chunks/323.js","../chunks/622.js","../chunks/676.js","../chunks/837.js","../chunks/840.js","../chunks/862.js","../chunks/984.js","../chunks/font-manifest.json","../webpack-runtime.js"]} \ No newline at end of file diff --git a/.next/server/server-reference-manifest.js b/.next/server/server-reference-manifest.js index e98dcee..02b3210 100644 --- a/.next/server/server-reference-manifest.js +++ b/.next/server/server-reference-manifest.js @@ -1 +1 @@ -self.__RSC_SERVER_MANIFEST={"node":{},"edge":{}} \ No newline at end of file +self.__RSC_SERVER_MANIFEST="{\"node\":{},\"edge\":{},\"encryptionKey\":\"aRJMCG/3RXVxjEJMErLKZvLaM7Ew1P5c9XmTb2XsL7A=\"}" \ No newline at end of file diff --git a/.next/server/server-reference-manifest.json b/.next/server/server-reference-manifest.json index 5eaa653..02441bb 100644 --- a/.next/server/server-reference-manifest.json +++ b/.next/server/server-reference-manifest.json @@ -1 +1 @@ -{"node":{},"edge":{}} \ No newline at end of file +{"node":{},"edge":{},"encryptionKey":"aRJMCG/3RXVxjEJMErLKZvLaM7Ew1P5c9XmTb2XsL7A="} \ No newline at end of file diff --git a/.next/server/webpack-runtime.js b/.next/server/webpack-runtime.js index 4b0eebe..5757df7 100644 --- a/.next/server/webpack-runtime.js +++ b/.next/server/webpack-runtime.js @@ -1,190 +1 @@ -/******/ (() => { // webpackBootstrap -/******/ "use strict"; -/******/ var __webpack_modules__ = ({}); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ // no module.id needed -/******/ // no module.loaded needed -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ var threw = true; -/******/ try { -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ threw = false; -/******/ } finally { -/******/ if(threw) delete __webpack_module_cache__[moduleId]; -/******/ } -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = __webpack_modules__; -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/compat get default export */ -/******/ (() => { -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = (module) => { -/******/ var getter = module && module.__esModule ? -/******/ () => (module['default']) : -/******/ () => (module); -/******/ __webpack_require__.d(getter, { a: getter }); -/******/ return getter; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/create fake namespace object */ -/******/ (() => { -/******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__); -/******/ var leafPrototypes; -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 16: return value when it's Promise-like -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = this(value); -/******/ if(mode & 8) return value; -/******/ if(typeof value === 'object' && value) { -/******/ if((mode & 4) && value.__esModule) return value; -/******/ if((mode & 16) && typeof value.then === 'function') return value; -/******/ } -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ var def = {}; -/******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)]; -/******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) { -/******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key]))); -/******/ } -/******/ def['default'] = () => (value); -/******/ __webpack_require__.d(ns, def); -/******/ return ns; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/ensure chunk */ -/******/ (() => { -/******/ __webpack_require__.f = {}; -/******/ // This file contains only the entry chunk. -/******/ // The chunk loading function for additional chunks -/******/ __webpack_require__.e = (chunkId) => { -/******/ return Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => { -/******/ __webpack_require__.f[key](chunkId, promises); -/******/ return promises; -/******/ }, [])); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/get javascript chunk filename */ -/******/ (() => { -/******/ // This function allow to reference async chunks and sibling chunks for the entrypoint -/******/ __webpack_require__.u = (chunkId) => { -/******/ // return url for filenames based on template -/******/ return "" + chunkId + ".js"; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/******/ /* webpack/runtime/make namespace object */ -/******/ (() => { -/******/ // define __esModule on exports -/******/ __webpack_require__.r = (exports) => { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/startup entrypoint */ -/******/ (() => { -/******/ __webpack_require__.X = (result, chunkIds, fn) => { -/******/ // arguments: chunkIds, moduleId are deprecated -/******/ var moduleId = chunkIds; -/******/ if(!fn) chunkIds = result, fn = () => (__webpack_require__(__webpack_require__.s = moduleId)); -/******/ chunkIds.map(__webpack_require__.e, __webpack_require__) -/******/ var r = fn(); -/******/ return r === undefined ? result : r; -/******/ } -/******/ })(); -/******/ -/******/ /* webpack/runtime/require chunk loading */ -/******/ (() => { -/******/ // no baseURI -/******/ -/******/ // object to store loaded chunks -/******/ // "1" means "loaded", otherwise not loaded yet -/******/ var installedChunks = { -/******/ 658: 1 -/******/ }; -/******/ -/******/ // no on chunks loaded -/******/ -/******/ var installChunk = (chunk) => { -/******/ var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime; -/******/ for(var moduleId in moreModules) { -/******/ if(__webpack_require__.o(moreModules, moduleId)) { -/******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; -/******/ } -/******/ } -/******/ if(runtime) runtime(__webpack_require__); -/******/ for(var i = 0; i < chunkIds.length; i++) -/******/ installedChunks[chunkIds[i]] = 1; -/******/ -/******/ }; -/******/ -/******/ // require() chunk loading for javascript -/******/ __webpack_require__.f.require = (chunkId, promises) => { -/******/ // "1" is the signal for "already loaded" -/******/ if(!installedChunks[chunkId]) { -/******/ if(658 != chunkId) { -/******/ installChunk(require("./chunks/" + __webpack_require__.u(chunkId))); -/******/ } else installedChunks[chunkId] = 1; -/******/ } -/******/ }; -/******/ -/******/ module.exports = __webpack_require__; -/******/ __webpack_require__.C = installChunk; -/******/ -/******/ // no HMR -/******/ -/******/ // no HMR manifest -/******/ })(); -/******/ -/************************************************************************/ -/******/ -/******/ -/******/ })() -; \ No newline at end of file +(()=>{"use strict";var e={},_={};function __webpack_require__(r){var a=_[r];if(void 0!==a)return a.exports;var t=_[r]={exports:{}},u=!0;try{e[r].call(t.exports,t,t.exports,__webpack_require__),u=!1}finally{u&&delete _[r]}return t.exports}__webpack_require__.m=e,__webpack_require__.amdO={},__webpack_require__.n=e=>{var _=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(_,{a:_}),_},(()=>{var e,_=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;__webpack_require__.t=function(r,a){if(1&a&&(r=this(r)),8&a||"object"==typeof r&&r&&(4&a&&r.__esModule||16&a&&"function"==typeof r.then))return r;var t=Object.create(null);__webpack_require__.r(t);var u={};e=e||[null,_({}),_([]),_(_)];for(var i=2&a&&r;"object"==typeof i&&!~e.indexOf(i);i=_(i))Object.getOwnPropertyNames(i).forEach(e=>u[e]=()=>r[e]);return u.default=()=>r,__webpack_require__.d(t,u),t}})(),__webpack_require__.d=(e,_)=>{for(var r in _)__webpack_require__.o(_,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:_[r]})},__webpack_require__.f={},__webpack_require__.e=e=>Promise.all(Object.keys(__webpack_require__.f).reduce((_,r)=>(__webpack_require__.f[r](e,_),_),[])),__webpack_require__.u=e=>""+e+".js",__webpack_require__.o=(e,_)=>Object.prototype.hasOwnProperty.call(e,_),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.X=(e,_,r)=>{var a=_;r||(_=e,r=()=>__webpack_require__(__webpack_require__.s=a)),_.map(__webpack_require__.e,__webpack_require__);var t=r();return void 0===t?e:t},(()=>{var e={658:1},installChunk=_=>{var r=_.modules,a=_.ids,t=_.runtime;for(var u in r)__webpack_require__.o(r,u)&&(__webpack_require__.m[u]=r[u]);t&&t(__webpack_require__);for(var i=0;i<a.length;i++)e[a[i]]=1};__webpack_require__.f.require=(_,r)=>{e[_]||(658!=_?installChunk(require("./chunks/"+__webpack_require__.u(_))):e[_]=1)},module.exports=__webpack_require__,__webpack_require__.C=installChunk})()})(); \ No newline at end of file diff --git a/.next/static/9CqSqX2Hqhh4fwiD8kSfJ/_buildManifest.js b/.next/static/9CqSqX2Hqhh4fwiD8kSfJ/_buildManifest.js new file mode 100644 index 0000000..4c143f6 --- /dev/null +++ b/.next/static/9CqSqX2Hqhh4fwiD8kSfJ/_buildManifest.js @@ -0,0 +1 @@ +self.__BUILD_MANIFEST={__rewrites:{afterFiles:[],beforeFiles:[],fallback:[]},"/_error":["static/chunks/pages/_error-b646007f40c4f0a8.js"],sortedPages:["/_app","/_error"]},self.__BUILD_MANIFEST_CB&&self.__BUILD_MANIFEST_CB(); \ No newline at end of file diff --git a/.next/static/Qb5fVlqLpQAODnw100j4z/_ssgManifest.js b/.next/static/9CqSqX2Hqhh4fwiD8kSfJ/_ssgManifest.js similarity index 100% rename from .next/static/Qb5fVlqLpQAODnw100j4z/_ssgManifest.js rename to .next/static/9CqSqX2Hqhh4fwiD8kSfJ/_ssgManifest.js diff --git a/.next/static/Qb5fVlqLpQAODnw100j4z/_buildManifest.js b/.next/static/Qb5fVlqLpQAODnw100j4z/_buildManifest.js deleted file mode 100644 index 33b75e4..0000000 --- a/.next/static/Qb5fVlqLpQAODnw100j4z/_buildManifest.js +++ /dev/null @@ -1 +0,0 @@ -self.__BUILD_MANIFEST={__rewrites:{beforeFiles:[],afterFiles:[],fallback:[]},"/_error":["static/chunks/pages/_error-d79168f986538ac0.js"],sortedPages:["/_app","/_error"]},self.__BUILD_MANIFEST_CB&&self.__BUILD_MANIFEST_CB(); \ No newline at end of file diff --git a/.next/static/chunks/173-2ffa9652644381a8.js b/.next/static/chunks/173-2ffa9652644381a8.js new file mode 100644 index 0000000..8a88dc8 --- /dev/null +++ b/.next/static/chunks/173-2ffa9652644381a8.js @@ -0,0 +1,11507 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[173],{8811:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return dynamic}});let r=i(1024);i(2265);let s=r._(i(7075));function convertModule(e){return{default:(null==e?void 0:e.default)||e}}function dynamic(e,t){let i=s.default,r={loading:e=>{let{error:t,isLoading:i,pastDelay:r}=e;return null}};"function"==typeof e&&(r.loader=e),Object.assign(r,t);let n=r.loader;return i({...r,loader:()=>null!=n?n().then(convertModule):Promise.resolve(convertModule(()=>null))})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9167:function(e,t,i){function NoSSR(e){let{children:t}=e;return t}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NoSSR",{enumerable:!0,get:function(){return NoSSR}}),i(1283)},7075:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let r=i(1024),s=r._(i(2265)),n=i(9167);function Loadable(e){let t=Object.assign({loader:null,loading:null,ssr:!0},e);function LoadableComponent(e){let i=t.loading,r=s.default.createElement(i,{isLoading:!0,pastDelay:!0,error:null}),a=t.ssr?s.default.Fragment:n.NoSSR,o=t.lazy;return s.default.createElement(s.default.Suspense,{fallback:r},s.default.createElement(a,null,s.default.createElement(o,e)))}return t.lazy=s.default.lazy(t.loader),LoadableComponent.displayName="LoadableComponent",LoadableComponent}let a=Loadable},622:function(e,t,i){/** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var r=i(2265),s=Symbol.for("react.element"),n=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,o=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function q(e,t,i){var r,n={},h=null,u=null;for(r in void 0!==i&&(h=""+i),void 0!==t.key&&(h=""+t.key),void 0!==t.ref&&(u=t.ref),t)a.call(t,r)&&!l.hasOwnProperty(r)&&(n[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===n[r]&&(n[r]=t[r]);return{$$typeof:s,type:e,key:h,ref:u,props:n,_owner:o.current}}t.Fragment=n,t.jsx=q,t.jsxs=q},7437:function(e,t,i){e.exports=i(622)},3621:function(e,t,i){i.d(t,{O:function(){return AbstractActionManager}});let AbstractActionManager=class AbstractActionManager{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(let e in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(let e in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,e)){let t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(let t in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,t)){let i=parseInt(t);if(i===e)return!0}return!1}};AbstractActionManager.Triggers={}},9528:function(e,t,i){i.d(t,{V:function(){return ActionEvent}});let ActionEvent=class ActionEvent{constructor(e,t,i,r,s,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=n}static CreateNew(e,t,i){let r=e.getScene();return new ActionEvent(e,r.pointerX,r.pointerY,r.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,r){return new ActionEvent(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,r)}static CreateNewFromScene(e,t){return new ActionEvent(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,r){return new ActionEvent(e,t.x,t.y,null,i,r)}}},1295:function(e,t,i){i.d(t,{l:function(){return Buffer},o:function(){return VertexBuffer}});var r=i(9185);let Buffer=class Buffer{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,n=!1,a=!1,o=!1,l,h){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=a,this._divisor=l||1,this._label=h,t instanceof r.h?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=o?s:s*Float32Array.BYTES_PER_ELEMENT,n||this.create()}createVertexBuffer(e,t,i,r,s,n=!1,a){let o=n?t:t*Float32Array.BYTES_PER_ELEMENT,l=r?n?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new VertexBuffer(this._engine,this,e,this._updatable,!0,l,void 0===s?this._instanced:s,o,i,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){(e||!this._buffer)&&(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label))}_rebuild(){this._buffer=null,this.create(this._data)}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),0===t&&void 0===i?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}};let VertexBuffer=class VertexBuffer{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){let t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get totalVertices(){let e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,r,s,n,a,o,l,h,u=!1,c=!1,d=1,p=!1){var _,f,m,g,v;this._isDisposed=!1;let x=!1;if(this.engine=e,"object"==typeof r&&null!==r?(x=null!==(_=r.updatable)&&void 0!==_&&_,s=r.postponeInternalCreation,n=r.stride,a=r.instanced,o=r.offset,l=r.size,h=r.type,u=null!==(f=r.normalized)&&void 0!==f&&f,c=null!==(m=r.useBytes)&&void 0!==m&&m,d=null!==(g=r.divisor)&&void 0!==g?g:1,p=null!==(v=r.takeBufferOwnership)&&void 0!==v&&v,this._label=r.label):x=!!r,t instanceof Buffer?(this._buffer=t,this._ownsBuffer=p):(this._buffer=new Buffer(e,t,x,n,s,a,c,d,this._label),this._ownsBuffer=!0),this.uniqueId=VertexBuffer._Counter++,this._kind=i,void 0===h){let e=this.getData();this.type=e?VertexBuffer.GetDataType(e):VertexBuffer.FLOAT}else this.type=h;let T=VertexBuffer.GetTypeByteLength(this.type);c?(this._size=l||(n?n/T:VertexBuffer.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*T,this.byteOffset=o||0):(this._size=l||n||VertexBuffer.DeduceStride(i),this.byteStride=n?n*T:this._buffer.byteStride||this._size*T,this.byteOffset=(o||0)*T),this.normalized=u,this._instanced=void 0!==a&&a,this._instanceDivisor=a?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){var e;null===(e=this._buffer)||void 0===e||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){let i=this.getData();return i?(e=null!=e?e:this.totalVertices,VertexBuffer.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t)):null}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/VertexBuffer.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/VertexBuffer.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*VertexBuffer.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){VertexBuffer.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case VertexBuffer.UVKind:case VertexBuffer.UV2Kind:case VertexBuffer.UV3Kind:case VertexBuffer.UV4Kind:case VertexBuffer.UV5Kind:case VertexBuffer.UV6Kind:return 2;case VertexBuffer.NormalKind:case VertexBuffer.PositionKind:return 3;case VertexBuffer.ColorKind:case VertexBuffer.ColorInstanceKind:case VertexBuffer.MatricesIndicesKind:case VertexBuffer.MatricesIndicesExtraKind:case VertexBuffer.MatricesWeightsKind:case VertexBuffer.MatricesWeightsExtraKind:case VertexBuffer.TangentKind:return 4;default:throw Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?VertexBuffer.BYTE:e instanceof Uint8Array?VertexBuffer.UNSIGNED_BYTE:e instanceof Int16Array?VertexBuffer.SHORT:e instanceof Uint16Array?VertexBuffer.UNSIGNED_SHORT:e instanceof Int32Array?VertexBuffer.INT:e instanceof Uint32Array?VertexBuffer.UNSIGNED_INT:VertexBuffer.FLOAT}static GetTypeByteLength(e){switch(e){case VertexBuffer.BYTE:case VertexBuffer.UNSIGNED_BYTE:return 1;case VertexBuffer.SHORT:case VertexBuffer.UNSIGNED_SHORT:return 2;case VertexBuffer.INT:case VertexBuffer.UNSIGNED_INT:case VertexBuffer.FLOAT:return 4;default:throw Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,r,s,n,a,o){if(e instanceof Array){let s=t/4,a=i/4;for(let t=0;t<n;t+=r){for(let i=0;i<r;i++)o(e[s+i],t+i);s+=a}}else{let l=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),h=VertexBuffer.GetTypeByteLength(s);for(let e=0;e<n;e+=r){let n=t;for(let t=0;t<r;t++){let i=VertexBuffer._GetFloatValue(l,s,n,a);o(i,e+t),n+=h}t+=i}}}static _GetFloatValue(e,t,i,r){switch(t){case VertexBuffer.BYTE:{let t=e.getInt8(i);return r&&(t=Math.max(t/127,-1)),t}case VertexBuffer.UNSIGNED_BYTE:{let t=e.getUint8(i);return r&&(t/=255),t}case VertexBuffer.SHORT:{let t=e.getInt16(i,!0);return r&&(t=Math.max(t/32767,-1)),t}case VertexBuffer.UNSIGNED_SHORT:{let t=e.getUint16(i,!0);return r&&(t/=65535),t}case VertexBuffer.INT:return e.getInt32(i,!0);case VertexBuffer.UNSIGNED_INT:return e.getUint32(i,!0);case VertexBuffer.FLOAT:return e.getFloat32(i,!0);default:throw Error(`Invalid component type ${t}`)}}static GetFloatData(e,t,i,r,s,n,a,o){let l=t*VertexBuffer.GetTypeByteLength(i),h=a*t;if(i!==VertexBuffer.FLOAT||s!==l){let a=new Float32Array(h);return VertexBuffer.ForEach(e,r,s,t,i,h,n,(e,t)=>a[t]=e),a}if(!(e instanceof Array||e instanceof Float32Array)||0!==r||e.length!==h){if(e instanceof Array){let t=r/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,r,h);{let t=e.byteOffset+r;if(o){let i=new Float32Array(h),r=new Float32Array(e.buffer,t,h);return i.set(r),i}let i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return o?e.slice():e}};VertexBuffer._Counter=0,VertexBuffer.BYTE=5120,VertexBuffer.UNSIGNED_BYTE=5121,VertexBuffer.SHORT=5122,VertexBuffer.UNSIGNED_SHORT=5123,VertexBuffer.INT=5124,VertexBuffer.UNSIGNED_INT=5125,VertexBuffer.FLOAT=5126,VertexBuffer.PositionKind="position",VertexBuffer.NormalKind="normal",VertexBuffer.TangentKind="tangent",VertexBuffer.UVKind="uv",VertexBuffer.UV2Kind="uv2",VertexBuffer.UV3Kind="uv3",VertexBuffer.UV4Kind="uv4",VertexBuffer.UV5Kind="uv5",VertexBuffer.UV6Kind="uv6",VertexBuffer.ColorKind="color",VertexBuffer.ColorInstanceKind="instanceColor",VertexBuffer.MatricesIndicesKind="matricesIndices",VertexBuffer.MatricesWeightsKind="matricesWeights",VertexBuffer.MatricesIndicesExtraKind="matricesIndicesExtra",VertexBuffer.MatricesWeightsExtraKind="matricesWeightsExtra"},9185:function(e,t,i){i.d(t,{h:function(){return DataBuffer}});let DataBuffer=class DataBuffer{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=DataBuffer._Counter++}};DataBuffer._Counter=0},555:function(e,t,i){i.d(t,{V:function(){return Camera}});var r=i(9956),s=i(1760),n=i(8355),a=i(5132),o=i(4800),l=i(78),h=i(208),u=i(9626),c=i(3048),d=i(6131),p=i(6329),_=i(2975);let Camera=class Camera extends h.N{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,r;let s=0,n=0;if(this.mode===Camera.PERSPECTIVE_CAMERA)this.fovMode===Camera.FOVMODE_VERTICAL_FIXED?(n=2*this.minZ*Math.tan(this.fov/2),s=this.getEngine().getAspectRatio(this)*n):n=(s=2*this.minZ*Math.tan(this.fov/2))/this.getEngine().getAspectRatio(this);else{let a=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;s=(null!==(e=this.orthoRight)&&void 0!==e?e:a)-(null!==(t=this.orthoLeft)&&void 0!==t?t:-a),n=(null!==(i=this.orthoTop)&&void 0!==i?i:o)-(null!==(r=this.orthoBottom)&&void 0!==r?r:-o)}return s*n}set orthoLeft(e){for(let t of(this._orthoLeft=e,this._rigCameras))t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){for(let t of(this._orthoRight=e,this._rigCameras))t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){for(let t of(this._orthoBottom=e,this._rigCameras))t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){for(let t of(this._orthoTop=e,this._rigCameras))t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){for(let t of(this._mode=e,this._rigCameras))t.mode=e}get mode(){return this._mode}constructor(e,t,i,r=!0){super(e,i),this._position=l.P.Zero(),this._upVector=l.P.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=Camera.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new p.l(0,0,1,1),this.layerMask=268435455,this.fovMode=Camera.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=Camera.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new o.y$,this.onProjectionMatrixChangedObservable=new o.y$,this.onAfterCheckInputsObservable=new o.y$,this.onRestoreStateObservable=new o.y$,this.isRigCamera=!1,this._rigCameras=[],this._skipRendering=!1,this._projectionMatrix=new l.y3,this._postProcesses=[],this._activeMeshes=new n.t(256),this._globalPosition=l.P.Zero(),this._computedViewMatrix=l.y3.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=l.y3.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=l._f.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}applyVerticalCorrection(){let e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return -1!==this._activeMeshes.indexOf(e)}isReady(e=!1){if(e){for(let e of this._postProcesses)if(e&&!e.isReady())return!1}return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new l.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new l.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.obliqueAngle=void 0,this._cache.obliqueLength=void 0,this._cache.obliqueOffset=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return!!super._isSynchronized()&&this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent()}_isSynchronizedProjectionMatrix(){let e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;let t=this.getEngine();return this.mode===Camera.PERSPECTIVE_CAMERA?e=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:(e=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight(),this.oblique&&(e=e&&this._cache.obliqueAngle===this.oblique.angle&&this._cache.obliqueLength===this.oblique.length&&this._cache.obliqueOffset===this.oblique.offset)),e}attachControl(e,t){}detachControl(e){}update(){this._checkInputs(),this.cameraRigMode!==Camera.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(null!==this._postProcesses[e])return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){let e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let e=0,t=this._rigCameras.length;e<t;e++){let t=this._rigCameras[e],i=t._rigPostProcess;if(i){let e="pass"===i.getEffectName();e&&(t.isIntermediate=0===this._postProcesses.length),t._postProcesses=this._postProcesses.slice(0).concat(i),i.markTextureDirty()}else t._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(u.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){let 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,r,s,n,a,o,h,u,c,d,p,_,f,m,g,v,x,T;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;let S=this.getEngine(),C=this.getScene(),E=S.useReverseDepthBuffer;if(this.mode===Camera.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=S.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),(C.useRightHandedSystem?l.y3.PerspectiveFovRHToRef:l.y3.PerspectiveFovLHToRef)(this.fov,S.getAspectRatio(this),E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===Camera.FOVMODE_VERTICAL_FIXED,S.isNDCHalfZRange,this.projectionPlaneTilt,E);else{let e=S.getRenderWidth()/2,b=S.getRenderHeight()/2;C.useRightHandedSystem?this.oblique?l.y3.ObliqueOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(r=this.orthoBottom)&&void 0!==r?r:-b,null!==(s=this.orthoTop)&&void 0!==s?s:b,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,S.isNDCHalfZRange):l.y3.OrthoOffCenterRHToRef(null!==(n=this.orthoLeft)&&void 0!==n?n:-e,null!==(a=this.orthoRight)&&void 0!==a?a:e,null!==(o=this.orthoBottom)&&void 0!==o?o:-b,null!==(h=this.orthoTop)&&void 0!==h?h:b,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this._projectionMatrix,S.isNDCHalfZRange):this.oblique?l.y3.ObliqueOffCenterLHToRef(null!==(u=this.orthoLeft)&&void 0!==u?u:-e,null!==(c=this.orthoRight)&&void 0!==c?c:e,null!==(d=this.orthoBottom)&&void 0!==d?d:-b,null!==(p=this.orthoTop)&&void 0!==p?p:b,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,S.isNDCHalfZRange):l.y3.OrthoOffCenterLHToRef(null!==(_=this.orthoLeft)&&void 0!==_?_:-e,null!==(f=this.orthoRight)&&void 0!==f?f:e,null!==(m=this.orthoBottom)&&void 0!==m?m:-b,null!==(g=this.orthoTop)&&void 0!==g?g:b,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this._projectionMatrix,S.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=null===(v=this.oblique)||void 0===v?void 0:v.angle,this._cache.obliqueLength=null===(x=this.oblique)||void 0===x?void 0:x.length,this._cache.obliqueOffset=null===(T=this.oblique)||void 0===T?void 0:T.offset,this._cache.renderWidth=S.getRenderWidth(),this._cache.renderHeight=S.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){return(this.radius||(this.target?l.P.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?_.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=_.i.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),!t||!(this.rigCameras.length>0))return e.isInFrustum(this._frustumPlanes);{let t=!1;return this.rigCameras.forEach(i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)}),t}}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,d.S)("Ray")}getForwardRayToRef(e,t=100,i,r){throw(0,d.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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){let 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!==Camera.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){let 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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=a.w1.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==Camera.RIG_MODE_NONE){let e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);let 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}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=a.w1.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){let e=s.p4.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),s.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){let i=s.p4.Clone(Camera.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=e,i.parent=t,this.onClonedObservable.notifyObservers(i),i}getDirection(e){let t=l.P.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){l.P.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,r=0,s=!0){let n=h.N.Construct(e,t,i,{interaxial_distance:r,isStereoscopicSideBySide:s});return n||(()=>Camera._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){let i=e.type,r=Camera.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),n=s.p4.Parse(r,e,t);if(void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),n.inputs&&(n.inputs.parse(e),n._setupInputs()),e.upVector&&(n.upVector=l.P.FromArray(e.upVector)),n.setPosition&&(n.position.copyFromFloats(0,0,0),n.setPosition(l.P.FromArray(e.position))),e.target&&n.setTarget&&n.setTarget(l.P.FromArray(e.target)),e.cameraRigMode){let t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};n.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t<e.animations.length;t++){let i=e.animations[t],r=(0,c.q)("BABYLON.Animation");r&&n.animations.push(r.Parse(i))}h.N.ParseAnimationRanges(n,e,t)}return e.autoAnimate&&t.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&n.setEnabled(e.isEnabled),n}_calculateHandednessMultiplier(){let e=this.getScene().useRightHandedSystem?-1:1;return this.parent&&0>this.parent._getWorldMatrixDeterminant()&&(e*=-1),e}};Camera._CreateDefaultParsedCamera=(e,t)=>{throw(0,d.S)("UniversalCamera")},Camera.PERSPECTIVE_CAMERA=0,Camera.ORTHOGRAPHIC_CAMERA=1,Camera.FOVMODE_VERTICAL_FIXED=0,Camera.FOVMODE_HORIZONTAL_FIXED=1,Camera.RIG_MODE_NONE=0,Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Camera.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Camera.RIG_MODE_VR=20,Camera.RIG_MODE_CUSTOM=22,Camera.ForceAttachControlToAlwaysPreventDefault=!1,(0,r.gn)([(0,s.hd)("position")],Camera.prototype,"_position",void 0),(0,r.gn)([(0,s.hd)("upVector")],Camera.prototype,"_upVector",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"orthoLeft",null),(0,r.gn)([(0,s.qC)()],Camera.prototype,"orthoRight",null),(0,r.gn)([(0,s.qC)()],Camera.prototype,"orthoBottom",null),(0,r.gn)([(0,s.qC)()],Camera.prototype,"orthoTop",null),(0,r.gn)([(0,s.qC)()],Camera.prototype,"fov",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"projectionPlaneTilt",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"minZ",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"maxZ",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"inertia",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"mode",null),(0,r.gn)([(0,s.qC)()],Camera.prototype,"layerMask",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"fovMode",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"cameraRigMode",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"interaxialDistance",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"isStereoscopicSideBySide",void 0)},6491:function(e,t,i){i.d(t,{c:function(){return IntersectionInfo}});let IntersectionInfo=class IntersectionInfo{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}},5790:function(e,t,i){i.d(t,{a:function(){return _MeshCollisionData}});var r=i(78);let _MeshCollisionData=class _MeshCollisionData{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new r.P(0,0,0),this._diffPositionForCollisions=new r.P(0,0,0),this._collisionResponse=!0}}},2248:function(e,t,i){i.d(t,{p:function(){return PickingInfo}});var r=i(78),s=i(1295);let PickingInfo=class PickingInfo{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){let i;if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(s.o.NormalKind))return null;let n=this.pickedMesh.getIndices();(null==n?void 0:n.length)===0&&(n=null);let a=r.jp.Vector3[0],o=r.jp.Vector3[1],l=r.jp.Vector3[2];if(t){let e=this.pickedMesh.getVerticesData(s.o.NormalKind),t=n?r.P.FromArrayToRef(e,3*n[3*this.faceId],a):a.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),h=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+1],o):o.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),u=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]);t=t.scale(this.bu),h=h.scale(this.bv),u=u.scale(1-this.bu-this.bv),i=new r.P(t.x+h.x+u.x,t.y+h.y+u.y,t.z+h.z+u.z)}else{let e=this.pickedMesh.getVerticesData(s.o.PositionKind),t=n?r.P.FromArrayToRef(e,3*n[3*this.faceId],a):a.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),h=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+1],o):o.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),u=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]),c=t.subtract(h),d=u.subtract(h);i=r.P.Cross(c,d)}let transformNormalToWorld=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(r.jp.Matrix[0].copyFrom(i),(i=r.jp.Matrix[0]).setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(r.jp.Matrix[1]),i=r.jp.Matrix[1]),r.P.TransformNormalToRef(t,i,t)};if(e&&transformNormalToWorld(this.pickedMesh,i),this.ray){let t=r.jp.Vector3[0].copyFrom(i);e||transformNormalToWorld(this.pickedMesh,t),r.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;let t=this.pickedMesh.getIndices();if(!t)return null;let i=this.pickedMesh.getVerticesData(e);if(!i)return null;let n=r.FM.FromArray(i,2*t[3*this.faceId]),a=r.FM.FromArray(i,2*t[3*this.faceId+1]),o=r.FM.FromArray(i,2*t[3*this.faceId+2]);return n=n.scale(this.bu),a=a.scale(this.bv),o=o.scale(1-this.bu-this.bv),new r.FM(n.x+a.x+o.x,n.y+a.y+o.y)}}},6705:function(e,t,i){i.d(t,{e:function(){return CompatibilityOptions}});let CompatibilityOptions=class CompatibilityOptions{};CompatibilityOptions.UseOpenGLOrientationForUV=!1},4347:function(e,t,i){i.d(t,{k:function(){return BoundingBox}});var r=i(4254),s=i(78),n=i(9806);let BoundingBox=class BoundingBox{constructor(e,t,i){this.vectors=r.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=r.B.BuildArray(3,s.P.Zero),this.vectorsWorld=r.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){let r=e.x,n=e.y,a=e.z,o=t.x,l=t.y,h=t.z,u=this.vectors;this.minimum.copyFromFloats(r,n,a),this.maximum.copyFromFloats(o,l,h),u[0].copyFromFloats(r,n,a),u[1].copyFromFloats(o,l,h),u[2].copyFromFloats(o,n,a),u[3].copyFromFloats(r,l,a),u[4].copyFromFloats(r,n,h),u[5].copyFromFloats(o,l,a),u[6].copyFromFloats(r,l,h),u[7].copyFromFloats(o,n,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){let t=BoundingBox._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);let s=r*e,n=i.scaleInPlace(.5*s),a=this.center.subtractToRef(n,t[1]),o=this.center.addToRef(n,t[2]);return this.reConstruct(a,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){let t=this.minimumWorld,i=this.maximumWorld,r=this.directions,n=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)n[e].copyFrom(a[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let r=0;r<8;++r){let o=n[r];s.P.TransformCoordinatesToRef(a[r],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}s.P.FromArrayToRef(e.m,0,r[0]),s.P.FromArrayToRef(e.m,4,r[1]),s.P.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return BoundingBox.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){let t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,a=t.z,o=i.x,l=i.y,h=i.z,u=e.x,c=e.y,d=e.z,p=-n.kn;return!(o-u<p)&&!(p>u-r)&&!(l-c<p)&&!(p>c-s)&&!(h-d<p)&&!(p>d-a)}intersectsSphere(e){return BoundingBox.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){let i=this.minimumWorld,r=this.maximumWorld,s=i.x,n=i.y,a=i.z,o=r.x,l=r.y,h=r.z,u=e.x,c=e.y,d=e.z,p=t.x,_=t.y,f=t.z;return!(o<u)&&!(s>p)&&!(l<c)&&!(n>_)&&!(h<d)&&!(a>f)}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,r){let n=BoundingBox._TmpVector3[0];s.P.ClampToRef(i,e,t,n);let a=s.P.DistanceSquared(i,n);return a<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){let r=t[i];for(let t=0;t<8;++t)if(0>r.dotCoordinate(e[t]))return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0,s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){r=!1;break}if(r)return!1}return!0}};BoundingBox._TmpVector3=r.B.BuildArray(3,s.P.Zero)},5681:function(e,t,i){i.d(t,{j:function(){return BoundingInfo}});var r=i(4254),s=i(78),n=i(4347),a=i(3592);let o={min:0,max:0},l={min:0,max:0},computeBoxExtents=(e,t,i)=>{let r=s.P.Dot(t.centerWorld,e),n=Math.abs(s.P.Dot(t.directions[0],e))*t.extendSize.x,a=Math.abs(s.P.Dot(t.directions[1],e))*t.extendSize.y,o=Math.abs(s.P.Dot(t.directions[2],e))*t.extendSize.z,l=n+a+o;i.min=r-l,i.max=r+l},axisOverlap=(e,t,i)=>(computeBoxExtents(e,t,o),computeBoxExtents(e,i,l),!(o.min>l.max||l.min>o.max));let BoundingInfo=class BoundingInfo{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new n.k(e,t,i),this.boundingSphere=new a.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){let i=BoundingInfo._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=BoundingInfo._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){let 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){let t=s.jp.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);let 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){return!!((2===t||3===t)&&this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(1===t||3===t||this.boundingBox.isInFrustum(e))}get diagonalLength(){let e=this.boundingBox,t=e.maximumWorld.subtractToRef(e.minimumWorld,BoundingInfo._TmpVector3[0]);return t.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(!a.K.Intersects(this.boundingSphere,e.boundingSphere)||!n.k.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;let i=this.boundingBox,r=e.boundingBox;return!!(axisOverlap(i.directions[0],i,r)&&axisOverlap(i.directions[1],i,r)&&axisOverlap(i.directions[2],i,r)&&axisOverlap(r.directions[0],i,r)&&axisOverlap(r.directions[1],i,r)&&axisOverlap(r.directions[2],i,r)&&axisOverlap(s.P.Cross(i.directions[0],r.directions[0]),i,r)&&axisOverlap(s.P.Cross(i.directions[0],r.directions[1]),i,r)&&axisOverlap(s.P.Cross(i.directions[0],r.directions[2]),i,r)&&axisOverlap(s.P.Cross(i.directions[1],r.directions[0]),i,r)&&axisOverlap(s.P.Cross(i.directions[1],r.directions[1]),i,r)&&axisOverlap(s.P.Cross(i.directions[1],r.directions[2]),i,r)&&axisOverlap(s.P.Cross(i.directions[2],r.directions[0]),i,r)&&axisOverlap(s.P.Cross(i.directions[2],r.directions[1]),i,r)&&axisOverlap(s.P.Cross(i.directions[2],r.directions[2]),i,r))}};BoundingInfo._TmpVector3=r.B.BuildArray(2,s.P.Zero)},3592:function(e,t,i){i.d(t,{K:function(){return BoundingSphere}});var r=i(4254),s=i(78);let BoundingSphere=class BoundingSphere{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);let r=s.P.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*r,this._update(i||s.y3.IdentityReadOnly)}scale(e){let t=this.radius*e,i=BoundingSphere._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),n=this.center.addToRef(r,i[2]);return this.reConstruct(s,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{s.P.TransformCoordinatesToRef(this.center,e,this.centerWorld);let t=BoundingSphere._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){let t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){let t=this.centerWorld;for(let i=0;i<6;i++)if(0>e[i].dotCoordinate(t))return!1;return!0}intersectsPoint(e){let t=s.P.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){let i=s.P.DistanceSquared(e.centerWorld,t.centerWorld),r=e.radiusWorld+t.radiusWorld;return!(r*r<i)}static CreateFromCenterAndRadius(e,t,i){this._TmpVector3[0].copyFrom(e),this._TmpVector3[1].copyFromFloats(0,0,t),this._TmpVector3[2].copyFrom(e),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);let r=new BoundingSphere(this._TmpVector3[0],this._TmpVector3[2]);return i?r._worldMatrix=i:r._worldMatrix=s.y3.Identity(),r}};BoundingSphere._TmpVector3=r.B.BuildArray(3,s.P.Zero)},6822:function(e,t,i){var r,s,n,a,o,l,h,u,c,d,p,_,f,m;i.d(t,{FP:function(){return n},Fz:function(){return s},Yi:function(){return r}}),(u=r||(r={}))[u.Generic=0]="Generic",u[u.Keyboard=1]="Keyboard",u[u.Mouse=2]="Mouse",u[u.Touch=3]="Touch",u[u.DualShock=4]="DualShock",u[u.Xbox=5]="Xbox",u[u.Switch=6]="Switch",u[u.DualSense=7]="DualSense",(c=s||(s={}))[c.Horizontal=0]="Horizontal",c[c.Vertical=1]="Vertical",c[c.LeftClick=2]="LeftClick",c[c.MiddleClick=3]="MiddleClick",c[c.RightClick=4]="RightClick",c[c.BrowserBack=5]="BrowserBack",c[c.BrowserForward=6]="BrowserForward",c[c.MouseWheelX=7]="MouseWheelX",c[c.MouseWheelY=8]="MouseWheelY",c[c.MouseWheelZ=9]="MouseWheelZ",c[c.Move=12]="Move",(d=n||(n={}))[d.Horizontal=0]="Horizontal",d[d.Vertical=1]="Vertical",d[d.LeftClick=2]="LeftClick",d[d.MiddleClick=3]="MiddleClick",d[d.RightClick=4]="RightClick",d[d.BrowserBack=5]="BrowserBack",d[d.BrowserForward=6]="BrowserForward",d[d.MouseWheelX=7]="MouseWheelX",d[d.MouseWheelY=8]="MouseWheelY",d[d.MouseWheelZ=9]="MouseWheelZ",d[d.DeltaHorizontal=10]="DeltaHorizontal",d[d.DeltaVertical=11]="DeltaVertical",(p=a||(a={}))[p.Cross=0]="Cross",p[p.Circle=1]="Circle",p[p.Square=2]="Square",p[p.Triangle=3]="Triangle",p[p.L1=4]="L1",p[p.R1=5]="R1",p[p.L2=6]="L2",p[p.R2=7]="R2",p[p.Share=8]="Share",p[p.Options=9]="Options",p[p.L3=10]="L3",p[p.R3=11]="R3",p[p.DPadUp=12]="DPadUp",p[p.DPadDown=13]="DPadDown",p[p.DPadLeft=14]="DPadLeft",p[p.DPadRight=15]="DPadRight",p[p.Home=16]="Home",p[p.TouchPad=17]="TouchPad",p[p.LStickXAxis=18]="LStickXAxis",p[p.LStickYAxis=19]="LStickYAxis",p[p.RStickXAxis=20]="RStickXAxis",p[p.RStickYAxis=21]="RStickYAxis",(_=o||(o={}))[_.Cross=0]="Cross",_[_.Circle=1]="Circle",_[_.Square=2]="Square",_[_.Triangle=3]="Triangle",_[_.L1=4]="L1",_[_.R1=5]="R1",_[_.L2=6]="L2",_[_.R2=7]="R2",_[_.Create=8]="Create",_[_.Options=9]="Options",_[_.L3=10]="L3",_[_.R3=11]="R3",_[_.DPadUp=12]="DPadUp",_[_.DPadDown=13]="DPadDown",_[_.DPadLeft=14]="DPadLeft",_[_.DPadRight=15]="DPadRight",_[_.Home=16]="Home",_[_.TouchPad=17]="TouchPad",_[_.LStickXAxis=18]="LStickXAxis",_[_.LStickYAxis=19]="LStickYAxis",_[_.RStickXAxis=20]="RStickXAxis",_[_.RStickYAxis=21]="RStickYAxis",(f=l||(l={}))[f.A=0]="A",f[f.B=1]="B",f[f.X=2]="X",f[f.Y=3]="Y",f[f.LB=4]="LB",f[f.RB=5]="RB",f[f.LT=6]="LT",f[f.RT=7]="RT",f[f.Back=8]="Back",f[f.Start=9]="Start",f[f.LS=10]="LS",f[f.RS=11]="RS",f[f.DPadUp=12]="DPadUp",f[f.DPadDown=13]="DPadDown",f[f.DPadLeft=14]="DPadLeft",f[f.DPadRight=15]="DPadRight",f[f.Home=16]="Home",f[f.LStickXAxis=17]="LStickXAxis",f[f.LStickYAxis=18]="LStickYAxis",f[f.RStickXAxis=19]="RStickXAxis",f[f.RStickYAxis=20]="RStickYAxis",(m=h||(h={}))[m.B=0]="B",m[m.A=1]="A",m[m.Y=2]="Y",m[m.X=3]="X",m[m.L=4]="L",m[m.R=5]="R",m[m.ZL=6]="ZL",m[m.ZR=7]="ZR",m[m.Minus=8]="Minus",m[m.Plus=9]="Plus",m[m.LS=10]="LS",m[m.RS=11]="RS",m[m.DPadUp=12]="DPadUp",m[m.DPadDown=13]="DPadDown",m[m.DPadLeft=14]="DPadLeft",m[m.DPadRight=15]="DPadRight",m[m.Home=16]="Home",m[m.Capture=17]="Capture",m[m.LStickXAxis=18]="LStickXAxis",m[m.LStickYAxis=19]="LStickYAxis",m[m.RStickXAxis=20]="RStickXAxis",m[m.RStickYAxis=21]="RStickYAxis"},6327:function(e,t,i){i.d(t,{p:function(){return DeviceSource}});var r=i(4800);let DeviceSource=class DeviceSource{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new r.y$,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}},8479:function(e,t,i){i.d(t,{U:function(){return DeviceSourceManager}});var r=i(6822),s=i(4800),n=i(5294);let DeviceEventFactory=class DeviceEventFactory{static CreateDeviceEvent(e,t,i,s,n,a,o){switch(e){case r.Yi.Keyboard:return this._CreateKeyboardEvent(i,s,n,a);case r.Yi.Mouse:if(i===r.Fz.MouseWheelX||i===r.Fz.MouseWheelY||i===r.Fz.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,n,a);case r.Yi.Touch:return this._CreatePointerEvent(e,t,i,s,n,a,o);default:throw`Unable to generate event for device ${r.Yi[e]}`}}static _CreatePointerEvent(e,t,i,s,n,a,o){let l;let h=this._CreateMouseEvent(e,t,i,s,n,a);return e===r.Yi.Mouse?(h.deviceType=r.Yi.Mouse,h.pointerId=1,h.pointerType="mouse"):(h.deviceType=r.Yi.Touch,h.pointerId=null!=o?o:t,h.pointerType="touch"),l=0+n.pollInput(e,t,r.Fz.LeftClick)+2*n.pollInput(e,t,r.Fz.RightClick)+4*n.pollInput(e,t,r.Fz.MiddleClick),h.buttons=l,i===r.Fz.Move?h.type="pointermove":i>=r.Fz.LeftClick&&i<=r.Fz.RightClick&&(h.type=1===s?"pointerdown":"pointerup",h.button=i-2),h}static _CreateWheelEvent(e,t,i,s,a,o){let l=this._CreateMouseEvent(e,t,i,s,a,o);switch(l.pointerId=1,l.type="wheel",l.deltaMode=n.G.DOM_DELTA_PIXEL,l.deltaX=0,l.deltaY=0,l.deltaZ=0,i){case r.Fz.MouseWheelX:l.deltaX=s;break;case r.Fz.MouseWheelY:l.deltaY=s;break;case r.Fz.MouseWheelZ:l.deltaZ=s}return l}static _CreateMouseEvent(e,t,i,s,n,a){let o=this._CreateEvent(a),l=n.pollInput(e,t,r.Fz.Horizontal),h=n.pollInput(e,t,r.Fz.Vertical);return a?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-a.getBoundingClientRect().x,o.offsetY=o.movementY-a.getBoundingClientRect().y):(o.movementX=n.pollInput(e,t,r.FP.DeltaHorizontal),o.movementY=n.pollInput(e,t,r.FP.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,n),o.clientX=l,o.clientY=h,o.x=l,o.y=h,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){let n=this._CreateEvent(s);return this._CheckNonCharacterKeys(n,i),n.deviceType=r.Yi.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=1===t?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n}static _CheckNonCharacterKeys(e,t){let i=t.isDeviceAvailable(r.Yi.Keyboard),s=i&&1===t.pollInput(r.Yi.Keyboard,0,18),n=i&&1===t.pollInput(r.Yi.Keyboard,0,17),a=i&&(1===t.pollInput(r.Yi.Keyboard,0,91)||1===t.pollInput(r.Yi.Keyboard,0,92)||1===t.pollInput(r.Yi.Keyboard,0,93)),o=i&&1===t.pollInput(r.Yi.Keyboard,0,16);e.altKey=s,e.ctrlKey=n,e.metaKey=a,e.shiftKey=o}static _CreateEvent(e){let t={};return t.preventDefault=()=>{},t.target=e,t}};let NativeDeviceInputSystem=class NativeDeviceInputSystem{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(e,t,r,s)=>{let n=DeviceEventFactory.CreateDeviceEvent(e,t,r,s,this);i(e,t,n)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===r.Yi.Mouse||e===r.Yi.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}};var a=i(7209),o=i(5132);let l=Object.keys(r.Fz).length/2;let WebDeviceInputSystem=class WebDeviceInputSystem{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=o.w1.IsSafari(),this._usingMacOS=(0,a.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._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=(0,a.up)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=(0,a.up)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=o.w1.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){let s=this._inputs[e][t];if(!s)throw`Unable to find device ${r.Yi[e]}`;e>=r.Yi.DualShock&&e<=r.Yi.DualSense&&this._updateDevice(e,t,i);let n=s[i];if(void 0===n)throw`Unable to find input ${i} for device ${r.Yi[e]} in slot ${t}`;return i===r.Fz.Move&&o.w1.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){let e=this===null||void 0===this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(let e of this._inputs)if(e)for(let t in e){let i=+t,r=e[i];if(r)for(let e=0;e<r.length;e++)r[e]=0}}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=-1!==this._elementToAttachTo.tabIndex?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}}_disableEvents(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),this._usingMacOS&&this._isUsingChromium&&this._elementToAttachTo.removeEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){let e=navigator.getGamepads();for(let t of e)t&&this._addGamePad(t)}"function"==typeof matchMedia&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(r.Yi.Mouse,0,0,0)}_addGamePad(e){let t=this._getGamepadDeviceType(e.id),i=e.index;this._gamepads=this._gamepads||Array(e.index+1),this._registerDevice(t,i,e.buttons.length+e.axes.length),this._gamepads[i]=t}_addPointerDevice(e,t,i,r){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,l);let s=this._inputs[e][t];s[0]=i,s[1]=r}_registerDevice(e,t,i){if(void 0===t)throw`Unable to register device ${r.Yi[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){let r=Array(i);r.fill(0),this._inputs[e][t]=r,this._onDeviceConnected(e,t)}}_unregisterDevice(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))}_handleKeyActions(){this._keyboardDownEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.Yi.Keyboard,0,255));let t=this._inputs[r.Yi.Keyboard][0];t&&(t[e.keyCode]=1,e.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&!this._metaKeys.includes(e.keyCode)&&this._metaKeys.push(e.keyCode),this._onInputChanged(r.Yi.Keyboard,0,e))},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.Yi.Keyboard,0,255));let t=this._inputs[r.Yi.Keyboard][0];if(t){if(t[e.keyCode]=0,e.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(let e of this._metaKeys){let i=DeviceEventFactory.CreateDeviceEvent(r.Yi.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(r.Yi.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(r.Yi.Keyboard,0,e)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){let e=this._inputs[r.Yi.Keyboard][0];for(let t=0;t<e.length;t++)if(0!==e[t]){e[t]=0;let i=DeviceEventFactory.CreateDeviceEvent(r.Yi.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(r.Yi.Keyboard,0,i)}this._usingMacOS&&this._metaKeys.splice(0,this._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)}_handlePointerActions(){this._maxTouchPoints=(0,a.up)()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=Array(this._maxTouchPoints));for(let e=0;e<this._maxTouchPoints;e++)this._activeTouchIds[e]=-1;this._pointerMoveEvent=e=>{let t=this._getPointerType(e),i=t===r.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===r.Yi.Touch&&-1===i){let r=this._activeTouchIds.indexOf(-1);if(r>=0)i=r,this._activeTouchIds[r]=e.pointerId,this._onDeviceConnected(t,i);else{o.w1.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);let s=this._inputs[t][i];s&&(e.inputIndex=r.Fz.Move,s[r.Fz.Horizontal]=e.clientX,s[r.Fz.Vertical]=e.clientY,t===r.Yi.Touch&&0===s[r.Fz.LeftClick]&&(s[r.Fz.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,e),this._usingSafari||-1===e.button||(e.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,e)))},this._pointerDownEvent=e=>{let t=this._getPointerType(e),i=t===r.Yi.Mouse?0:e.pointerId;if(t===r.Yi.Touch){let t=this._activeTouchIds.indexOf(-1);if(t>=0)i=t,this._activeTouchIds[t]=e.pointerId;else{o.w1.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===r.Yi.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);let s=this._inputs[t][i];if(s){let n=s[r.Fz.Horizontal],a=s[r.Fz.Vertical];if(t===r.Yi.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[r.Fz.Horizontal]=e.clientX,s[r.Fz.Vertical]=e.clientY,s[e.button+2]=1,e.inputIndex=e.button+2,this._onInputChanged(t,i,e),(n!==e.clientX||a!==e.clientY)&&(e.inputIndex=r.Fz.Move,this._onInputChanged(t,i,e))}},this._pointerUpEvent=e=>{var t,i,s,n,a;let o=this._getPointerType(e),l=o===r.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(o===r.Yi.Touch){if(-1===l)return;this._activeTouchIds[l]=-1}let h=null===(t=this._inputs[o])||void 0===t?void 0:t[l];if(h&&0!==h[e.button+2]){let t=h[r.Fz.Horizontal],u=h[r.Fz.Vertical];h[r.Fz.Horizontal]=e.clientX,h[r.Fz.Vertical]=e.clientY,h[e.button+2]=0,void 0===e.pointerId&&(e.pointerId=this._mouseId),(t!==e.clientX||u!==e.clientY)&&(e.inputIndex=r.Fz.Move,this._onInputChanged(o,l,e)),e.inputIndex=e.button+2,o===r.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===(a=(n=this._elementToAttachTo).hasPointerCapture)||void 0===a?void 0:a.call(n,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(o,l,e),o===r.Yi.Touch&&this._onDeviceDisconnected(o,l)}},this._pointerCancelEvent=e=>{var t,i,s,n;if("mouse"===e.pointerType){let e=this._inputs[r.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=r.Fz.LeftClick;t<=r.Fz.BrowserForward;t++)if(1===e[t]){e[t]=0;let i=DeviceEventFactory.CreateDeviceEvent(r.Yi.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(r.Yi.Mouse,0,i)}}else{let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;(null===(n=(s=this._elementToAttachTo).hasPointerCapture)||void 0===n?void 0:n.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[r.Yi.Touch][t][r.Fz.LeftClick]=0;let i=DeviceEventFactory.CreateDeviceEvent(r.Yi.Touch,t,r.Fz.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(r.Yi.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(r.Yi.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1,noop=function(){};try{let t=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",noop,t),this._elementToAttachTo.removeEventListener("test",noop,t)}catch(e){}this._pointerBlurEvent=()=>{var e,t,i,s,n;if(this.isDeviceAvailable(r.Yi.Mouse)){let i=this._inputs[r.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=r.Fz.LeftClick;e<=r.Fz.BrowserForward;e++)if(1===i[e]){i[e]=0;let t=DeviceEventFactory.CreateDeviceEvent(r.Yi.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(r.Yi.Mouse,0,t)}}if(this.isDeviceAvailable(r.Yi.Touch)){let e=this._inputs[r.Yi.Touch];for(let t=0;t<this._activeTouchIds.length;t++){let a=this._activeTouchIds[t];if((null===(s=(i=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(i,a))&&this._elementToAttachTo.releasePointerCapture(a),-1!==a&&(null===(n=e[t])||void 0===n?void 0:n[r.Fz.LeftClick])===1){e[t][r.Fz.LeftClick]=0;let i=DeviceEventFactory.CreateDeviceEvent(r.Yi.Touch,t,r.Fz.LeftClick,0,this,this._elementToAttachTo,a);this._onInputChanged(r.Yi.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(r.Yi.Touch,t)}}}},this._pointerWheelEvent=e=>{let t=r.Yi.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,l));let i=this._inputs[t][0];i&&(i[r.Fz.MouseWheelX]=e.deltaX||0,i[r.Fz.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[r.Fz.MouseWheelZ]=e.deltaZ||0,void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[r.Fz.MouseWheelX]&&(e.inputIndex=r.Fz.MouseWheelX,this._onInputChanged(t,0,e)),0!==i[r.Fz.MouseWheelY]&&(e.inputIndex=r.Fz.MouseWheelY,this._onInputChanged(t,0,e)),0!==i[r.Fz.MouseWheelZ]&&(e.inputIndex=r.Fz.MouseWheelZ,this._onInputChanged(t,0,e)))},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(r.Yi.Mouse)){let e=this._inputs[r.Yi.Mouse][0];e[r.Fz.MouseWheelX]=0,e[r.Fz.MouseWheelY]=0,e[r.Fz.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){let 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){let r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){let s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return -1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?r.Yi.DualSense:r.Yi.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?r.Yi.Xbox:-1!==e.indexOf("057e")?r.Yi.Switch:r.Yi.Generic}_getPointerType(e){let t=r.Yi.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=r.Yi.Touch),t}};var h=i(6327);let InternalDeviceSourceManager=class InternalDeviceSourceManager{constructor(e){this._registeredManagers=[],this._refCount=0,this.registerManager=e=>{for(let t=0;t<this._devices.length;t++){let i=this._devices[t];for(let r in i){let i=+r;e._addDevice(new h.p(this._deviceInputSystem,t,i))}}this._registeredManagers.push(e)},this.unregisterManager=e=>{let t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};let t=Object.keys(r.Yi).length/2;this._devices=Array(t);let onDeviceConnected=(e,t)=>{for(let i of(this._devices[e]||(this._devices[e]=[]),this._devices[e][t]||(this._devices[e][t]=t),this._registeredManagers)){let r=new h.p(this._deviceInputSystem,e,t);i._addDevice(r)}},onDeviceDisconnected=(e,t)=>{var i;for(let r of((null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t],this._registeredManagers))r._removeDevice(e,t)},onInputChanged=(e,t,i)=>{if(i)for(let r of this._registeredManagers)r._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new NativeDeviceInputSystem(onDeviceConnected,onDeviceDisconnected,onInputChanged):this._deviceInputSystem=new WebDeviceInputSystem(e,onDeviceConnected,onDeviceDisconnected,onInputChanged)}dispose(){this._deviceInputSystem.dispose()}};let DeviceSourceManager=class DeviceSourceManager{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){let t=Object.keys(r.Yi).length/2;this._devices=Array(t),this._firstDevice=Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new InternalDeviceSourceManager(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new s.y$(e=>{for(let t of this._devices)if(t)for(let 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]=[]),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,r;let s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(r=this._devices[e])||void 0===r?void 0:r[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;null===(s=null===(r=this._devices[e])||void 0===r?void 0:r[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case r.Yi.Keyboard:case r.Yi.Mouse:this._firstDevice[e]=0;break;case r.Yi.Touch:case r.Yi.DualSense:case r.Yi.DualShock:case r.Yi.Xbox:case r.Yi.Switch:case r.Yi.Generic:{delete this._firstDevice[e];let t=this._devices[e];if(t){for(let i=0;i<t.length;i++)if(t[i]){this._firstDevice[e]=i;break}}}}}}},6628:function(e,t,i){var r=i(6465);r.B.prototype.setAlphaConstants=function(e,t,i,r){this._alphaState.setAlphaBlendConstants(e,t,i,r)},r.B.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e){if(!t){let t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e},r.B.prototype.getAlphaMode=function(){return this._alphaMode},r.B.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},r.B.prototype.getAlphaEquation=function(){return this._alphaEquation}},6529:function(e,t,i){var r=i(6465);r.B.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let r;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},r.B.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0);let s=t.byteLength||t.length;void 0===r||r>=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,r):new Uint8Array(t.buffer,t.byteOffset+i,r),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()}},9255:function(e,t,i){i.d(t,{A:function(){return allocateAndCopyTypedBuffer}});var r=i(6465);function allocateAndCopyTypedBuffer(e,t,i=!1,r){switch(e){case 3:{let e=(ArrayBuffer,new Int8Array(t));return r&&e.set(new Int8Array(r)),e}case 0:{let e=(ArrayBuffer,new Uint8Array(t));return r&&e.set(new Uint8Array(r)),e}case 4:{let e=new Int16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Int16Array(r)),e}case 5:case 8:case 9:case 10:case 2:{let e=new Uint16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Uint16Array(r)),e}case 6:{let e=new Int32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Int32Array(r)),e}case 7:case 11:case 12:case 13:case 14:case 15:{let e=new Uint32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Uint32Array(r)),e}case 1:{let e=new Float32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Float32Array(r)),e}}let s=(ArrayBuffer,new Uint8Array(t));return r&&s.set(new Uint8Array(r)),s}r.B.prototype._readTexturePixelsSync=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){var u,c;let d=this._gl;if(!d)throw Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){let e=d.createFramebuffer();if(!e)throw Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}d.bindFramebuffer(d.FRAMEBUFFER,this._dummyFramebuffer),r>-1?d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+r,null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,s):d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,s);let p=void 0!==e.type?this._getWebGLTextureType(e.type):d.UNSIGNED_BYTE;return o?n||(n=allocateAndCopyTypedBuffer(e.type,4*t*i)):p===d.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),p=d.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),p=d.FLOAT),a&&this.flushFramebuffer(),d.readPixels(l,h,t,i,d.RGBA,p,n),d.bindFramebuffer(d.FRAMEBUFFER,this._currentFramebuffer),n},r.B.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,r,s,n,a,o,l,h))}},68:function(e,t,i){var r=i(6465),s=i(998);r.B.prototype.createUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create uniform buffer");let r=new s.M(i);return this.bindUniformBuffer(r),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),r.references=1,r},r.B.prototype.createDynamicUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create dynamic uniform buffer");let r=new s.M(i);return this.bindUniformBuffer(r),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),r.references=1,r},r.B.prototype.updateUniformBuffer=function(e,t,i,r){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this.bindUniformBuffer(null)},r.B.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},r.B.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},r.B.prototype.bindUniformBlock=function(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);4294967295!==s&&this._gl.uniformBlockBinding(r,s,i)}},7790:function(e,t,i){i.d(t,{L:function(){return ShaderProcessor}});let ShaderCodeNode=class ShaderCodeNode{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,r,s,n,a,o,l;let h="";if(this.line){let u=this.line,c=t.processor;if(c){c.lineProcessor&&(u=c.lineProcessor(u,t.isFragment,t.processingContext));let h=null!==(r=null===(i=t.processor)||void 0===i?void 0:i.attributeKeywordName)&&void 0!==r?r:"attribute",d=t.isFragment&&(null===(s=t.processor)||void 0===s?void 0:s.varyingFragmentKeywordName)?null===(n=t.processor)||void 0===n?void 0:n.varyingFragmentKeywordName:!t.isFragment&&(null===(a=t.processor)||void 0===a?void 0:a.varyingVertexKeywordName)?null===(o=t.processor)||void 0===o?void 0:o.varyingVertexKeywordName:"varying";!t.isFragment&&c.attributeProcessor&&this.line.startsWith(h)?u=c.attributeProcessor(this.line,e,t.processingContext):c.varyingProcessor&&((null===(l=c.varyingCheck)||void 0===l?void 0:l.call(c,this.line,t.isFragment))||!c.varyingCheck&&this.line.startsWith(d))?u=c.varyingProcessor(this.line,t.isFragment,e,t.processingContext):c.uniformProcessor&&c.uniformRegexp&&c.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&c.uniformBufferRegexp&&c.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):c.textureProcessor&&c.textureRegexp&&c.textureRegexp.test(this.line)?u=c.textureProcessor(this.line,t.isFragment,e,t.processingContext):(c.uniformProcessor||c.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?c.uniformProcessor&&(u=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&(u=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,c.endOfUniformBufferProcessor&&(u=c.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}h+=u+"\n"}return this.children.forEach(i=>{h+=i.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),h}};let ShaderCodeCursor=class ShaderCodeCursor{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex<this._lines.length-1}set lines(e){for(let t of(this._lines.length=0,e)){if(!t||"\r"===t)continue;if("#"===t[0]){this._lines.push(t);continue}let e=t.trim();if(!e)continue;if(e.startsWith("//")){this._lines.push(t);continue}let i=e.indexOf(";");if(-1===i)this._lines.push(e);else if(i===e.length-1)e.length>1&&this._lines.push(e);else{let e=t.split(";");for(let t=0;t<e.length;t++){let i=e[t];i&&(i=i.trim())&&this._lines.push(i+(t!==e.length-1?";":""))}}}}};let ShaderCodeConditionNode=class ShaderCodeConditionNode extends ShaderCodeNode{process(e,t){for(let i=0;i<this.children.length;i++){let r=this.children[i];if(r.isValid(e))return r.process(e,t)}return""}};let ShaderCodeTestNode=class ShaderCodeTestNode extends ShaderCodeNode{isValid(e){return this.testExpression.isTrue(e)}};let ShaderDefineExpression=class ShaderDefineExpression{isTrue(e){return!0}static postfixToInfix(e){let t=[];for(let i of e)if(void 0===ShaderDefineExpression._OperatorPriority[i])t.push(i);else{let e=t[t.length-1],r=t[t.length-2];t.length-=2,t.push(`(${r}${i}${e})`)}return t[t.length-1]}static infixToPostfix(e){let t=ShaderDefineExpression._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!e.includes("&&")&&!e.includes("||")&&!e.includes(")")&&!e.includes("("))return[e];let i=[],r=-1,pushOperand=()=>{""!==(n=n.trim())&&(i.push(n),n="")},push=e=>{r<ShaderDefineExpression._Stack.length-1&&(ShaderDefineExpression._Stack[++r]=e)},peek=()=>ShaderDefineExpression._Stack[r],pop=()=>-1===r?"!!INVALID EXPRESSION!!":ShaderDefineExpression._Stack[r--],s=0,n="";for(;s<e.length;){let t=e.charAt(s),a=s<e.length-1?e.substr(s,2):"";if("("===t)n="",push(t);else if(")"===t){for(pushOperand();-1!==r&&"("!==peek();)i.push(pop());pop()}else if(ShaderDefineExpression._OperatorPriority[a]>1){for(pushOperand();-1!==r&&ShaderDefineExpression._OperatorPriority[peek()]>=ShaderDefineExpression._OperatorPriority[a];)i.push(pop());push(a),s++}else n+=t;s++}for(pushOperand();-1!==r;)"("===peek()?pop():i.push(pop());return ShaderDefineExpression._InfixToPostfixCache.size>=ShaderDefineExpression.InfixToPostfixCacheLimitSize&&ShaderDefineExpression.ClearCache(),ShaderDefineExpression._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){let e=Array.from(ShaderDefineExpression._InfixToPostfixCache.entries()).sort((e,t)=>e[1].accessTime-t[1].accessTime);for(let t=0;t<ShaderDefineExpression.InfixToPostfixCacheCleanupSize;t++)ShaderDefineExpression._InfixToPostfixCache.delete(e[t][0])}};ShaderDefineExpression.InfixToPostfixCacheLimitSize=5e4,ShaderDefineExpression.InfixToPostfixCacheCleanupSize=25e3,ShaderDefineExpression._InfixToPostfixCache=new Map,ShaderDefineExpression._OperatorPriority={")":0,"(":1,"||":2,"&&":3},ShaderDefineExpression._Stack=["","","","","","","","","","","","","","","","","","","",""];let ShaderDefineIsDefinedOperator=class ShaderDefineIsDefinedOperator extends ShaderDefineExpression{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=void 0!==e[this.define];return this.not&&(t=!t),t}};let ShaderDefineOrOperator=class ShaderDefineOrOperator extends ShaderDefineExpression{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}};let ShaderDefineAndOperator=class ShaderDefineAndOperator extends ShaderDefineExpression{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}};let ShaderDefineArithmeticOperator=class ShaderDefineArithmeticOperator extends ShaderDefineExpression{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}isTrue(e){let t=e[this.define];void 0===t&&(t=this.define);let i=!1,r=parseInt(t),s=parseInt(this.testValue);switch(this.operand){case">":i=r>s;break;case"<":i=r<s;break;case"<=":i=r<=s;break;case">=":i=r>=s;break;case"==":i=r===s;break;case"!=":i=r!==s}return i}};var r=i(6131),s=i(5550);let n=/defined\s*?\((.+?)\)/g,a=/defined\s*?\[(.+?)\]/g,o=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,l=/__decl__/,h=/light\{X\}.(\w*)/g,u=/\{X\}/g,c=[];let ShaderProcessor=class ShaderProcessor{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,r){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));let s=this._ProcessShaderConversion(e,t,r);i(s,e)})}static PreProcess(e,t,i,r){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));let s=this._ApplyPreProcessing(e,t,r);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;let r=t.shouldUseHighPrecisionShader;return -1===e.indexOf("precision highp float")?e=r?"precision highp float;\n"+e:"precision mediump float;\n"+e:r||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){let t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new ShaderDefineIsDefinedOperator(t[1].trim(),"!"===e[0]);let i="",r=0;for(i of["==","!=",">=","<=","<",">"])if((r=e.indexOf(i))>-1)break;if(-1===r)return new ShaderDefineIsDefinedOperator(e);let s=e.substring(0,r).trim(),n=e.substring(r+i.length).trim();return new ShaderDefineArithmeticOperator(s,i,n)}static _BuildSubExpression(e){e=e.replace(n,"defined[$1]");let t=ShaderDefineExpression.infixToPostfix(e),i=[];for(let e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],r=i[i.length-2];i.length-=2;let s="&&"==e?new ShaderDefineAndOperator:new ShaderDefineOrOperator;"string"==typeof t&&(t=t.replace(a,"defined($1)")),"string"==typeof r&&(r=r.replace(a,"defined($1)")),s.leftOperand="string"==typeof r?this._ExtractOperation(r):r,s.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(s)}let r=i[i.length-1];return"string"==typeof r&&(r=r.replace(a,"defined($1)")),"string"==typeof r?this._ExtractOperation(r):r}static _BuildExpression(e,t){let i=new ShaderCodeTestNode,r=e.substring(0,t),s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),"#ifdef"===r?i.testExpression=new ShaderDefineIsDefinedOperator(s):"#ifndef"===r?i.testExpression=new ShaderDefineIsDefinedOperator(s,!0):i.testExpression=this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let r=e.currentLine;for(;this._MoveCursor(e,i);){r=e.currentLine;let s=r.substring(0,5).toLowerCase();if("#else"===s){let i=new ShaderCodeNode;t.children.push(i),this._MoveCursor(e,i);return}if("#elif"===s){let e=this._BuildExpression(r,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;let i=e.currentLine;if(i.indexOf("#")>=0){let r=ShaderProcessor._MoveCursorRegex.exec(i);if(r&&r.length){let s=r[0];switch(s){case"#ifdef":{let r=new ShaderCodeConditionNode;t.children.push(r);let s=this._BuildExpression(i,6);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{let r=new ShaderCodeConditionNode;t.children.push(r);let s=this._BuildExpression(i,7);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#if":{let r=new ShaderCodeConditionNode,s=this._BuildExpression(i,3);t.children.push(r),r.children.push(s),this._MoveCursorWithinIf(e,r,s)}}continue}}let r=new ShaderCodeNode;if(r.line=i,t.children.push(r),"#"===i[0]&&"d"===i[1]){let e=i.replace(";","").split(" ");r.additionalDefineKey=e[1],3===e.length&&(r.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){let r=new ShaderCodeNode,s=new ShaderCodeCursor;return s.lineIndex=-1,s.lines=e.split("\n"),this._MoveCursor(s,r),r.process(t,i)}static _PreparePreProcessors(e,t){var i;let r=e.defines,n={};for(let e of r){let t=e.replace("#define","").replace(";","").trim(),i=t.split(" ");n[i[0]]=i.length>1?i[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===s.x.GLSL&&(n.GL_ES="true"),n.__VERSION__=e.version,n[e.platformName]="true",t._getGlobalDefines(n),n}static _ProcessShaderConversion(e,t,i){let r=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===s.x.GLSL&&-1!==r.indexOf("#version 3")&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;let n=t.defines,a=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,n,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,a,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,n,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ApplyPreProcessing(e,t,i){var r,s;let n=e,a=t.defines,o=this._PreparePreProcessors(t,i);return(null===(r=t.processor)||void 0===r?void 0:r.preProcessor)&&(n=t.processor.preProcessor(n,a,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,o,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(n=t.processor.postProcessor(n,a,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ProcessIncludes(e,t,i){let r;for(c.length=0;null!==(r=o.exec(e));)c.push(r);let s=String(e),n=[e],a=!1;for(let e of c){let r=e[1];if(-1!==r.indexOf("__decl__")&&(r=r.replace(l,""),t.supportsUniformBuffers&&(r=r.replace("Vertex","Ubo").replace("Fragment","Ubo")),r+="Declaration"),t.includesShadersStore[r]){let i=t.includesShadersStore[r];if(e[2]){let t=e[3].split(",");for(let e=0;e<t.length;e+=2){let r=RegExp(t[e],"g"),s=t[e+1];i=i.replace(r,s)}}if(e[4]){let r=e[5];if(-1!==r.indexOf("..")){let e=r.split(".."),s=parseInt(e[0]),n=parseInt(e[1]),a=i.slice(0);i="",isNaN(n)&&(n=t.indexParameters[e[1]]);for(let e=s;e<n;e++)t.supportsUniformBuffers||(a=a.replace(h,(e,t)=>t+"{X}")),i+=a.replace(u,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(h,(e,t)=>t+"{X}")),i=i.replace(u,r)}let s=[];for(let t of n){let r=t.split(e[0]);for(let e=0;e<r.length-1;e++)s.push(r[e]),s.push(i);s.push(r[r.length-1])}n=s,a=a||i.indexOf("#include<")>=0||i.indexOf("#include <")>=0}else{let e=t.shadersRepository+"ShadersInclude/"+r+".fx";ShaderProcessor._FileToolsLoadFile(e,e=>{t.includesShadersStore[r]=e,this._ProcessIncludes(n.join(""),t,i)});return}}c.length=0,s=n.join(""),a?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,s,n,a){throw(0,r.S)("FileTools")}};ShaderProcessor._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/},7666:function(e,t,i){i.d(t,{C:function(){return WebGL2ShaderProcessor}});var r=i(5550);let s=/(flat\s)?\s*varying\s*.*/;let WebGL2ShaderProcessor=class WebGL2ShaderProcessor{constructor(){this.shaderLanguage=r.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){let r=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){let t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(r||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else{let i=-1!==t.indexOf("#define MULTIVIEW");if(i)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}return e}}},5342:function(e,t,i){i.d(t,{B:function(){return WebGLHardwareTexture}});let WebGLHardwareTexture=class WebGLHardwareTexture{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw 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(let e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return null!==(i=null===(t=this._MSAARenderBuffers)||void 0===t?void 0:t[e])&&void 0!==i?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},856:function(e,t,i){i.d(t,{y:function(){return WebGLPipelineContext}});let WebGLPipelineContext=class WebGLPipelineContext{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this.engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);let u=this.engine.getUniforms(this,i);for(u.forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l<s.length;l++){let t=e.getUniform(s[l]);null==t&&(s.splice(l,1),l--)}for(let e of(s.forEach((e,t)=>{n[e]=t}),h.getAttributes(this,a)))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||2!==r.length)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,r,s],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),n[3]!==s&&(n[3]=s,a=!0),a}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setUInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&!this.engine.setMatrices(this._uniforms[e],t.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){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&!this.engine.setFloat2(this._uniforms[e],t.x,t.y)&&(this._valueCache[e]=null)}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setFloat2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&!this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)&&(this._valueCache[e]=null)}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setFloat3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setFloat4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&!this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)&&(this._valueCache[e]=null)}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(this._valueCache[e]=null)}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&!this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)&&(this._valueCache[e]=null)}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}},5410:function(e,t,i){i.d(t,{f:function(){return WebGLShaderProcessor}});var r=i(5550);let WebGLShaderProcessor=class WebGLShaderProcessor{constructor(){this.shaderLanguage=r.x.GLSL}postProcessor(e,t,i,r,s){return s.getCaps().drawBuffersExtension||(e=e.replace(/#extension.+GL_EXT_draw_buffers.+(enable|require)/g,"")),e}}},8906:function(e,t,i){i.d(t,{D:function(){return Engine}});var r=i(4800),s=i(3912),n=i(7209),a=i(6030),o=i(6131),l=i(6465),h=i(8786),u=i(7263),c=i(998),d=i(9626),p=i(5342);i(6628),i(9255),i(6529);let Engine=class Engine extends l.B{static get NpmPackage(){return l.B.NpmPackage}static get Version(){return l.B.Version}static get Instances(){return a.l.Instances}static get LastCreatedEngine(){return a.l.LastCreatedEngine}static get LastCreatedScene(){return a.l.LastCreatedScene}_createImageBitmapFromSource(e,t){let i=new Promise((i,r)=>{let s=new Image;s.onload=()=>{s.decode().then(()=>{this.createImageBitmap(s,t).then(e=>{i(e)})})},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=e});return i}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){let r=this.createCanvas(t,i),s=r.getContext("2d");if(!s)throw Error("Unable to get 2d context for resizeImageBitmap");s.drawImage(e,0,0);let n=s.getImageData(0,0,t,i).data;return n}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i<Engine.Instances.length;i++){let r=Engine.Instances[i];for(let i=0;i<r.scenes.length;i++)r.scenes[i].markAllMaterialsAsDirty(e,t)}}static DefaultLoadingScreenFactory(e){throw(0,o.S)("LoadingScreen")}get _supportsHardwareTextureRescaling(){return!!Engine._RescalePostProcessFactory}get performanceMonitor(){return this._performanceMonitor}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}getInputElement(){return this._renderingCanvas}constructor(e,t,i,s=!1){if(super(e,t,i,s),this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.scenes=[],this._virtualScenes=[],this.onNewSceneAddedObservable=new r.y$,this.postProcesses=[],this.isPointerLock=!1,this.onResizeObservable=new r.y$,this.onCanvasBlurObservable=new r.y$,this.onCanvasFocusObservable=new r.y$,this.onCanvasPointerOutObservable=new r.y$,this.onBeginFrameObservable=new r.y$,this.customAnimationFrameRequester=null,this.onEndFrameObservable=new r.y$,this.onBeforeShaderCompilationObservable=new r.y$,this.onAfterShaderCompilationObservable=new r.y$,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this._fps=60,this._deltaTime=0,this._drawCalls=new u.z,this.canvasTabIndex=1,this.disablePerformanceMonitorInBackground=!1,this._performanceMonitor=new h.A,this._compatibilityMode=!0,this.currentRenderPassId=0,this._renderPassNames=["main"],Engine.Instances.push(this),!e)return;this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext&&this._sharedInit(e)}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),this._onCanvasFocus=()=>{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)};let 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(),!Engine.audioEngine&&this._creationOptions.audioEngine&&Engine.AudioEngineFactory&&(Engine.audioEngine=Engine.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),(0,n.n5)()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&Engine._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!==Engine.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){let 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){let 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,r){let s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){let s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){let e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise((r,s)=>{this._loadFile(e,e=>{r(e)},void 0,t,i,(e,t)=>{s(t)})})}getVertexShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))}setTextureFromPostProcess(e,t,i){var r;let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(r=null==s?void 0:s.texture)&&void 0!==r?r:null,i)}setTextureFromPostProcessOutput(e,t,i){var r,s;this._bindTexture(e,null!==(s=null===(r=null==t?void 0:t._outputTexture)||void 0===r?void 0:r.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(let e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(let e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++){let t=this._activeRenderLoops[e];t()}}_cancelFrame(){if(this._renderingQueueLaunched&&this.customAnimationFrameRequester){this._renderingQueueLaunched=!1;let{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}else super._cancelFrame()}_renderLoop(){if(!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){!this.isFullscreen&&(this._pointerLockRequested=e,this._renderingCanvas&&Engine._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&Engine._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&Engine._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){Engine._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this.onEndFrameObservable.notifyObservers(this)}setSize(e,t,i=!1){if(!this._renderingCanvas||!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e<this.scenes.length;e++){let t=this.scenes[e];for(let e=0;e<t.cameras.length;e++){let i=t.cameras[e];i._currentRenderId=0}}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0}_deletePipelineContext(e){e&&e.program&&e.transformFeedback&&(this.deleteTransformFeedback(e.transformFeedback),e.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,r,s,n=null){s=s||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);let a=super.createShaderProgram(e,t,i,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),a}_createShaderProgram(e,t,i,r,s=null){let n=r.createProgram();if(e.program=n,!n)throw Error("Unable to create program");if(r.attachShader(n,t),r.attachShader(n,i),this.webGLVersion>1&&s){let t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,s),e.transformFeedback=t}return r.linkProgram(n),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach(t=>{t.postProcesses.forEach(t=>{t._outputTexture===e&&(t._outputTexture=null)}),t.cameras.forEach(t=>{t._postProcesses.forEach(t=>{t&&t._outputTexture===e&&(t._outputTexture=null)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){let t=++Engine._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t<this.scenes.length;++t){let i=this.scenes[t];for(let t=0;t<i.meshes.length;++t){let r=i.meshes[t];if(r.subMeshes)for(let t=0;t<r.subMeshes.length;++t){let i=r.subMeshes[t];i._removeDrawWrapper(e)}}}}_rescaleTexture(e,t,i,r,s){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);let n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&Engine._RescalePostProcessFactory&&(this._rescalePostProcess=Engine._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled(()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=i;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,r,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),s&&s()}))}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,r=0,n=0){let a=new p.B(e,this._gl),o=new s.l(this,s.S.Unknown,!0);return o._hardwareTexture=a,o.baseWidth=r,o.baseHeight=n,o.width=r,o.height=n,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,r=0){let s=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,r,o,a,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion){d.Y.Error("WebGL 1 does not support texture comparison.");return}let 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){let t=this._gl.createBuffer();if(!t)throw Error("Unable to create instance buffer");let i=new c.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){let r=this._gl;return new Promise((s,n)=>{let check=()=>{let a=r.clientWaitSync(e,t,0);if(a==r.WAIT_FAILED){n();return}if(a==r.TIMEOUT_EXPIRED){setTimeout(check,i);return}s()};check()})}_readPixelsAsync(e,t,i,r,s,n,a){if(this._webGLVersion<2)throw Error("_readPixelsAsync only work on WebGL2+");let o=this._gl,l=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,i,r,s,n,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);let h=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(o.flush(),this._clientWaitAsync(h,0,10).then(()=>(o.deleteSync(h),o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(l),a))):null}dispose(){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===a.l.Instances.length&&Engine.audioEngine&&(Engine.audioEngine.dispose(),Engine.audioEngine=null);let 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,n.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();let t=a.l.Instances.indexOf(this);t>=0&&a.l.Instances.splice(t,1),Engine.Instances.length||a.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,n.CG)())return;let e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!(0,n.CG)())return;let e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Engine.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){let t=e.requestPointerLock();t instanceof Promise?t.then(()=>{e.focus()}).catch(()=>{}):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){let t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){let e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){let t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);let i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";let r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);let s=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:s,height:n,descent:n-s}}};Engine.ALPHA_DISABLE=0,Engine.ALPHA_ADD=1,Engine.ALPHA_COMBINE=2,Engine.ALPHA_SUBTRACT=3,Engine.ALPHA_MULTIPLY=4,Engine.ALPHA_MAXIMIZED=5,Engine.ALPHA_ONEONE=6,Engine.ALPHA_PREMULTIPLIED=7,Engine.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Engine.ALPHA_INTERPOLATE=9,Engine.ALPHA_SCREENMODE=10,Engine.DELAYLOADSTATE_NONE=0,Engine.DELAYLOADSTATE_LOADED=1,Engine.DELAYLOADSTATE_LOADING=2,Engine.DELAYLOADSTATE_NOTLOADED=4,Engine.NEVER=512,Engine.ALWAYS=519,Engine.LESS=513,Engine.EQUAL=514,Engine.LEQUAL=515,Engine.GREATER=516,Engine.GEQUAL=518,Engine.NOTEQUAL=517,Engine.KEEP=7680,Engine.REPLACE=7681,Engine.INCR=7682,Engine.DECR=7683,Engine.INVERT=5386,Engine.INCR_WRAP=34055,Engine.DECR_WRAP=34056,Engine.TEXTURE_CLAMP_ADDRESSMODE=0,Engine.TEXTURE_WRAP_ADDRESSMODE=1,Engine.TEXTURE_MIRROR_ADDRESSMODE=2,Engine.TEXTUREFORMAT_ALPHA=0,Engine.TEXTUREFORMAT_LUMINANCE=1,Engine.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Engine.TEXTUREFORMAT_RGB=4,Engine.TEXTUREFORMAT_RGBA=5,Engine.TEXTUREFORMAT_RED=6,Engine.TEXTUREFORMAT_R=6,Engine.TEXTUREFORMAT_RG=7,Engine.TEXTUREFORMAT_RED_INTEGER=8,Engine.TEXTUREFORMAT_R_INTEGER=8,Engine.TEXTUREFORMAT_RG_INTEGER=9,Engine.TEXTUREFORMAT_RGB_INTEGER=10,Engine.TEXTUREFORMAT_RGBA_INTEGER=11,Engine.TEXTURETYPE_UNSIGNED_BYTE=0,Engine.TEXTURETYPE_UNSIGNED_INT=0,Engine.TEXTURETYPE_FLOAT=1,Engine.TEXTURETYPE_HALF_FLOAT=2,Engine.TEXTURETYPE_BYTE=3,Engine.TEXTURETYPE_SHORT=4,Engine.TEXTURETYPE_UNSIGNED_SHORT=5,Engine.TEXTURETYPE_INT=6,Engine.TEXTURETYPE_UNSIGNED_INTEGER=7,Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Engine.TEXTURETYPE_UNSIGNED_INT_24_8=12,Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Engine.TEXTURE_NEAREST_SAMPLINGMODE=1,Engine.TEXTURE_BILINEAR_SAMPLINGMODE=2,Engine.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Engine.TEXTURE_NEAREST_LINEAR=7,Engine.TEXTURE_NEAREST_NEAREST=1,Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Engine.TEXTURE_LINEAR_LINEAR=2,Engine.TEXTURE_LINEAR_NEAREST=12,Engine.TEXTURE_EXPLICIT_MODE=0,Engine.TEXTURE_SPHERICAL_MODE=1,Engine.TEXTURE_PLANAR_MODE=2,Engine.TEXTURE_CUBIC_MODE=3,Engine.TEXTURE_PROJECTION_MODE=4,Engine.TEXTURE_SKYBOX_MODE=5,Engine.TEXTURE_INVCUBIC_MODE=6,Engine.TEXTURE_EQUIRECTANGULAR_MODE=7,Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Engine.SCALEMODE_FLOOR=1,Engine.SCALEMODE_NEAREST=2,Engine.SCALEMODE_CEILING=3,Engine._RescalePostProcessFactory=null,Engine._RenderPassIdCounter=0},6030:function(e,t,i){i.d(t,{l:function(){return EngineStore}});var r=i(4800);let EngineStore=class EngineStore{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}};EngineStore.Instances=[],EngineStore.OnEnginesDisposedObservable=new r.y$,EngineStore._LastCreatedScene=null,EngineStore.UseFallbackTexture=!0,EngineStore.FallbackTexture=""},4548:function(e,t,i){i.d(t,{Z:function(){return PerformanceConfigurator}});let PerformanceConfigurator=class PerformanceConfigurator{static SetMatrixPrecision(e){if(PerformanceConfigurator.MatrixTrackPrecisionChange=!1,e&&!PerformanceConfigurator.MatrixUse64Bits&&PerformanceConfigurator.MatrixTrackedMatrices)for(let e=0;e<PerformanceConfigurator.MatrixTrackedMatrices.length;++e){let t=PerformanceConfigurator.MatrixTrackedMatrices[e],i=t._m;t._m=Array(16);for(let e=0;e<16;++e)t._m[e]=i[e]}PerformanceConfigurator.MatrixUse64Bits=e,PerformanceConfigurator.MatrixCurrentType=PerformanceConfigurator.MatrixUse64Bits?Array:Float32Array,PerformanceConfigurator.MatrixTrackedMatrices=null}};PerformanceConfigurator.MatrixUse64Bits=!1,PerformanceConfigurator.MatrixTrackPrecisionChange=!0,PerformanceConfigurator.MatrixCurrentType=Float32Array,PerformanceConfigurator.MatrixTrackedMatrices=[]},513:function(e,t,i){i.d(t,{v:function(){return ShaderStore}});var r=i(5550);let ShaderStore=class ShaderStore{static GetShadersRepository(e=r.x.GLSL){return e===r.x.GLSL?ShaderStore.ShadersRepository:ShaderStore.ShadersRepositoryWGSL}static GetShadersStore(e=r.x.GLSL){return e===r.x.GLSL?ShaderStore.ShadersStore:ShaderStore.ShadersStoreWGSL}static GetIncludesShadersStore(e=r.x.GLSL){return e===r.x.GLSL?ShaderStore.IncludesShadersStore:ShaderStore.IncludesShadersStoreWGSL}};ShaderStore.ShadersRepository="src/Shaders/",ShaderStore.ShadersStore={},ShaderStore.IncludesShadersStore={},ShaderStore.ShadersRepositoryWGSL="src/ShadersWGSL/",ShaderStore.ShadersStoreWGSL={},ShaderStore.IncludesShadersStoreWGSL={}},5294:function(e,t,i){var r,s;i.d(t,{G:function(){return EventConstants}}),(s=r||(r={}))[s.PointerMove=0]="PointerMove",s[s.PointerDown=1]="PointerDown",s[s.PointerUp=2]="PointerUp";let EventConstants=class EventConstants{};EventConstants.DOM_DELTA_PIXEL=0,EventConstants.DOM_DELTA_LINE=1,EventConstants.DOM_DELTA_PAGE=2},7534:function(e,t,i){i.d(t,{NG:function(){return KeyboardInfo},OG:function(){return KeyboardEventTypes},WZ:function(){return KeyboardInfoPre}});let KeyboardEventTypes=class KeyboardEventTypes{};KeyboardEventTypes.KEYDOWN=1,KeyboardEventTypes.KEYUP=2;let KeyboardInfo=class KeyboardInfo{constructor(e,t){this.type=e,this.event=t}};let KeyboardInfoPre=class KeyboardInfoPre extends KeyboardInfo{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}},6114:function(e,t,i){i.d(t,{FV:function(){return PointerInfoPre},R5:function(){return PointerInfo},kD:function(){return PointerEventTypes}});var r=i(78);let PointerEventTypes=class PointerEventTypes{};PointerEventTypes.POINTERDOWN=1,PointerEventTypes.POINTERUP=2,PointerEventTypes.POINTERMOVE=4,PointerEventTypes.POINTERWHEEL=8,PointerEventTypes.POINTERPICK=16,PointerEventTypes.POINTERTAP=32,PointerEventTypes.POINTERDOUBLETAP=64;let PointerInfoBase=class PointerInfoBase{constructor(e,t){this.type=e,this.event=t}};let PointerInfoPre=class PointerInfoPre extends PointerInfoBase{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new r.FM(i,s)}};let PointerInfo=class PointerInfo extends PointerInfoBase{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,r=null){super(e,t),this._pickInfo=i,this._inputManager=r}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}},7077:function(e,t,i){i.d(t,{M:function(){return PointerPickingConfiguration}});let PointerPickingConfiguration=class PointerPickingConfiguration{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}},8668:function(e,t,i){i.d(t,{$:function(){return InputManager}});var r=i(6114),s=i(3621),n=i(2248),a=i(78),o=i(9528),l=i(7534),h=i(6822),u=i(8479),c=i(6030);let _ClickInfo=class _ClickInfo{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}};let InputManager=class InputManager{constructor(e){if(this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new a.FM(0,0),this._previousStartingPointerPosition=new a.FM(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||c.l.LastCreatedScene,!this._scene)return}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new a.FM(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){let t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){let i;let s=this._scene,n=s.getEngine(),a=n.getInputElement();for(let i of(a&&(a.tabIndex=n.canvasTabIndex,s.doNotHandleCursors||(a.style.cursor=s.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,s),s._pointerMoveStage)){e=e||this._pickMove(t);let r=null!=e&&!!e.pickedMesh;e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,r,a)}let o=t.inputIndex>=h.Fz.MouseWheelX&&t.inputIndex<=h.Fz.MouseWheelZ?r.kD.POINTERWHEEL:r.kD.POINTERMOVE;s.onPointerMove&&(e=e||this._pickMove(t),s.onPointerMove(t,e,o)),e?(i=new r.R5(o,t,e),this._setRayOnPointerInfo(e,t)):(i=new r.R5(o,t,null,this),this._movePointerInfo=i),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(i,o)}_setRayOnPointerInfo(e,t){let i=this._scene;e&&i._pickingAvailable&&!e.ray&&(e.ray=i.createPickingRay(t.offsetX,t.offsetY,a.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){let s=this._scene,n=new r.FV(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(n.originalPickingInfo=e,n.ray=e.ray,e.originMesh&&(n.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(n,i),!!n.skipOnPointerObservable}_pickMove(e){let 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){let r=i.getEngine(),s=r.getInputElement();if(null==e?void 0:e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){let e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){let i=new PointerEvent("pointermove",t);i.inputIndex=h.Fz.Move,this._checkPrePointerObservable(e,i,r.kD.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){let i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,r.kD.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){let i;let s=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;let i=e.pickedMesh._getActionManagerForTrigger();if(i){if(i.hasPickTriggers)switch(i.processTrigger(5,o.V.CreateNew(e.pickedMesh,t,e)),t.button){case 0:i.processTrigger(2,o.V.CreateNew(e.pickedMesh,t,e));break;case 1:i.processTrigger(4,o.V.CreateNew(e.pickedMesh,t,e));break;case 2:i.processTrigger(3,o.V.CreateNew(e.pickedMesh,t,e))}i.hasSpecificTrigger(8)&&window.setTimeout(()=>{let e=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh,!1,s.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&i&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>InputManager.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,i.processTrigger(8,o.V.CreateNew(e.pickedMesh,t)))},InputManager.LongPressDelay)}}else for(let i of s._pointerDownStage)e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let n=r.kD.POINTERDOWN;e?(s.onPointerDown&&s.onPointerDown(t,e,n),i=new r.R5(n,t,e),this._setRayOnPointerInfo(e,t)):i=new r.R5(n,t,null,this),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(i,n)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){let s=new PointerEvent("pointerup",t);s.inputIndex=h.Fz.Move;let n=new _ClickInfo;i?n.doubleClick=!0:n.singleClick=!0,this._checkPrePointerObservable(e,s,r.kD.POINTERUP)||this._processPointerUp(e,s,n)}_processPointerUp(e,t,i){let 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)){let i=r.kD.POINTERPICK,n=new r.R5(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,i)}let n=e.pickedMesh._getActionManagerForTrigger();if(n&&!i.ignore){n.processTrigger(7,o.V.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&n.processTrigger(1,o.V.CreateNew(e.pickedMesh,t,e));let r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,o.V.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(let r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){let e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,o.V.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){let n=new r.R5(r.kD.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,r.kD.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,r.kD.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=r.kD.POINTERTAP:i.doubleClick&&(n=r.kD.POINTERDOUBLETAP),n){let i=new r.R5(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(i,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,a=null){let c=this._scene,d=c.getEngine();a||(a=d.getInputElement()),this._alreadyAttached&&this.detachControl(),a&&(this._alreadyAttachedTo=a),this._deviceSourceManager=new u.U(d),this._initActionManager=e=>{if(!this._meshPickProceed){let t=!c.skipPointerUpPicking&&(0!==c._registeredActions||this._checkForPicking()||c.onPointerUp)?c.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,c.pointerUpPredicate,c.pointerUpFastCheck,c.cameraToUseForPointers):null;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>InputManager.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){let t=this._delayedClicks[e].evt,i=r.kD.POINTERTAP,s=new r.R5(i,t,this._currentPickResult);c.onPointerObservable.hasObservers()&&c.onPointerObservable.hasSpecificMask(i)&&c.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,n)=>{var a,o;let l=new _ClickInfo;this._currentPickResult=null;let h=null,u=e.hasSpecificMask(r.kD.POINTERPICK)||t.hasSpecificMask(r.kD.POINTERPICK)||e.hasSpecificMask(r.kD.POINTERTAP)||t.hasSpecificMask(r.kD.POINTERTAP)||e.hasSpecificMask(r.kD.POINTERDOUBLETAP)||t.hasSpecificMask(r.kD.POINTERDOUBLETAP);!u&&s.O&&(h=this._initActionManager(h,l))&&(u=h.hasPickTriggers);let c=!1;if(u){let u=i.button;if(l.hasSwiped=this._isPointerSwiping(),!l.hasSwiped){let d=!InputManager.ExclusiveDoubleClickMode;if(!d&&(d=!e.hasSpecificMask(r.kD.POINTERDOUBLETAP)&&!t.hasSpecificMask(r.kD.POINTERDOUBLETAP))&&!s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l))&&(d=!h.hasSpecificTrigger(6)),d)(Date.now()-this._previousStartingPointerTime>InputManager.DoubleClickDelay||u!==this._previousButtonPressed)&&(l.singleClick=!0,n(l,this._currentPickResult),c=!0);else{let e={evt:i,clickInfo:l,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,u,l,n),InputManager.DoubleClickDelay)};this._delayedClicks[u]=e}let p=e.hasSpecificMask(r.kD.POINTERDOUBLETAP)||t.hasSpecificMask(r.kD.POINTERDOUBLETAP);!p&&s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l))&&(p=h.hasSpecificTrigger(6)),p&&(u===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<InputManager.DoubleClickDelay&&!this._doubleClickOccured?(l.hasSwiped||this._isPointerSwiping()?(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=u,InputManager.ExclusiveDoubleClickMode?(this._delayedClicks[u]&&(clearTimeout(null===(o=this._delayedClicks[u])||void 0===o?void 0:o.timeoutId),this._delayedClicks[u]=null),n(l,this._previousPickResult)):n(l,this._currentPickResult)):(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,l.doubleClick=!0,l.ignore=!1,InputManager.ExclusiveDoubleClickMode&&this._delayedClicks[u]&&(clearTimeout(null===(a=this._delayedClicks[u])||void 0===a?void 0:a.timeoutId),this._delayedClicks[u]=null),n(l,this._currentPickResult)),c=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=u))}}c||n(l,this._currentPickResult)},this._onPointerMove=e=>{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>InputManager.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>InputManager.DragMovementThreshold),d.isPointerLock&&d._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=h.Fz.MouseWheelX&&e.inputIndex<=h.Fz.MouseWheelZ?r.kD.POINTERWHEEL:r.kD.POINTERMOVE)||!c.cameraToUseForPointers&&!c.activeCamera)return;if(c.skipPointerMovePicking){this._processPointerMove(new n.p,e);return}c.pointerMovePredicate||(c.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||c.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0));let t=c._registeredActions>0||c.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;let i;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,InputManager.ExclusiveDoubleClickMode){for(let i=0;i<this._delayedClicks.length;i++)if(this._delayedClicks[i]){if(e.button===i)clearTimeout(null===(t=this._delayedClicks[i])||void 0===t?void 0:t.timeoutId);else{let e=this._delayedClicks[i].clickInfo;this._doubleClickOccured=!1,e.singleClick=!0,e.ignore=!1;let t=this._delayedClicks[i].evt,s=r.kD.POINTERTAP,n=new r.R5(s,t,this._currentPickResult);c.onPointerObservable.hasObservers()&&c.onPointerObservable.hasSpecificMask(s)&&c.onPointerObservable.notifyObservers(n,s),this._delayedClicks[i]=null}}}this._updatePointerPosition(e),-1===this._swipeButtonPressed&&(this._swipeButtonPressed=e.button),c.preventDefaultOnPointerDown&&a&&(e.preventDefault(),a.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),!this._checkPrePointerObservable(null,e,r.kD.POINTERDOWN)&&(c.cameraToUseForPointers||c.activeCamera)&&(this._pointerCaptures[e.pointerId]=!0,c.pointerDownPredicate||(c.pointerDownPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0)),this._pickedDownMesh=null,i=!c.skipPointerDownPicking&&(0!==c._registeredActions||this._checkForPicking()||c.onPointerDown)?c.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,c.pointerDownPredicate,c.pointerDownFastCheck,c.cameraToUseForPointers):new n.p,this._processPointerDown(i,e))},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),c.preventDefaultOnPointerUp&&a&&(e.preventDefault(),a.focus()),this._initClickEvent(c.onPrePointerObservable,c.onPointerObservable,e,(t,i)=>{if(c.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,r.kD.POINTERUP)){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1);return}!t.hasSwiped&&(t.singleClick&&c.onPrePointerObservable.hasSpecificMask(r.kD.POINTERTAP)&&this._checkPrePointerObservable(null,e,r.kD.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&c.onPrePointerObservable.hasSpecificMask(r.kD.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,r.kD.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[e.pointerId]){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(c.cameraToUseForPointers||c.activeCamera)&&(c.pointerUpPredicate||(c.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0)),!this._meshPickProceed&&(s.O&&s.O.HasTriggers||this._checkForPicking()||c.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._onKeyDown=e=>{let t=l.OG.KEYDOWN;if(c.onPreKeyboardObservable.hasObservers()){let i=new l.WZ(t,e);if(c.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(c.onKeyboardObservable.hasObservers()){let i=new l.NG(t,e);c.onKeyboardObservable.notifyObservers(i,t)}c.actionManager&&c.actionManager.processTrigger(14,o.V.CreateNewFromScene(c,e))},this._onKeyUp=e=>{let t=l.OG.KEYUP;if(c.onPreKeyboardObservable.hasObservers()){let i=new l.WZ(t,e);if(c.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(c.onKeyboardObservable.hasObservers()){let i=new l.NG(t,e);c.onKeyboardObservable.notifyObservers(i,t)}c.actionManager&&c.actionManager.processTrigger(15,o.V.CreateNewFromScene(c,e))},this._deviceSourceManager.onDeviceConnectedObservable.add(r=>{r.deviceType===h.Yi.Mouse?r.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===r.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===r.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))}):r.deviceType===h.Yi.Touch?r.onInputChangedObservable.add(s=>{s.inputIndex===h.Fz.LeftClick&&(t&&1===r.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===r.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===h.Fz.Move&&this._onPointerMove(s)}):r.deviceType===h.Yi.Keyboard&&r.onInputChangedObservable.add(e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,r){let s;if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;let n=this._meshUnderPointerId[t];n&&(s=n._getActionManagerForTrigger(10))&&s.processTrigger(10,o.V.CreateNew(n,r,{pointerId:t})),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,(s=e._getActionManagerForTrigger(9))&&s.processTrigger(9,o.V.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){for(let t in this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null),this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}};InputManager.DragMovementThreshold=10,InputManager.LongPressDelay=500,InputManager.DoubleClickDelay=300,InputManager.ExclusiveDoubleClickMode=!1},6972:function(e,t,i){i.d(t,{m:function(){return LightConstants}});let LightConstants=class LightConstants{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}};LightConstants.FALLOFF_DEFAULT=0,LightConstants.FALLOFF_PHYSICAL=1,LightConstants.FALLOFF_GLTF=2,LightConstants.FALLOFF_STANDARD=3,LightConstants.LIGHTMAP_DEFAULT=0,LightConstants.LIGHTMAP_SPECULAR=1,LightConstants.LIGHTMAP_SHADOWSONLY=2,LightConstants.INTENSITYMODE_AUTOMATIC=0,LightConstants.INTENSITYMODE_LUMINOUSPOWER=1,LightConstants.INTENSITYMODE_LUMINOUSINTENSITY=2,LightConstants.INTENSITYMODE_ILLUMINANCE=3,LightConstants.INTENSITYMODE_LUMINANCE=4,LightConstants.LIGHTTYPEID_POINTLIGHT=0,LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT=1,LightConstants.LIGHTTYPEID_SPOTLIGHT=2,LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT=3},2697:function(e,t,i){i.d(t,{Z:function(){return SceneLoaderFlags}});let SceneLoaderFlags=class SceneLoaderFlags{static get ForceFullSceneLoadingForIncremental(){return SceneLoaderFlags._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){SceneLoaderFlags._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return SceneLoaderFlags._ShowLoadingScreen}static set ShowLoadingScreen(e){SceneLoaderFlags._ShowLoadingScreen=e}static get loggingLevel(){return SceneLoaderFlags._LoggingLevel}static set loggingLevel(e){SceneLoaderFlags._LoggingLevel=e}static get CleanBoneMatrixWeights(){return SceneLoaderFlags._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){SceneLoaderFlags._CleanBoneMatrixWeights=e}};SceneLoaderFlags._ForceFullSceneLoadingForIncremental=!1,SceneLoaderFlags._ShowLoadingScreen=!0,SceneLoaderFlags._CleanBoneMatrixWeights=!1,SceneLoaderFlags._LoggingLevel=0},3912:function(e,t,i){i.d(t,{S:function(){return s},l:function(){return InternalTexture}});var r,s,n=i(4800),a=i(7584);(r=s||(s={}))[r.Unknown=0]="Unknown",r[r.Url=1]="Url",r[r.Temp=2]="Temp",r[r.Raw=3]="Raw",r[r.Dynamic=4]="Dynamic",r[r.RenderTarget=5]="RenderTarget",r[r.MultiRenderTarget=6]="MultiRenderTarget",r[r.Cube=7]="Cube",r[r.CubeRaw=8]="CubeRaw",r[r.CubePrefiltered=9]="CubePrefiltered",r[r.Raw3D=10]="Raw3D",r[r.Raw2DArray=11]="Raw2DArray",r[r.DepthStencil=12]="DepthStencil",r[r.CubeRawRGBD=13]="CubeRawRGBD",r[r.Depth=14]="Depth";let InternalTexture=class InternalTexture extends a.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 n.y$,this.onErrorObservable=new n.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=s.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=InternalTexture._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;let t;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){let e=this.onRebuildCallback(this),swapAndSetIsReady=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};e.isAsync?e.proxy.then(swapAndSetIsReady):swapAndSetIsReady(e.proxy);return}switch(this.source){case s.Temp:break;case s.Url: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);return;case s.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))._swapAndDie(this,!1),this.isReady=!0;break;case s.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))._swapAndDie(this,!1),this.isReady=!0;break;case s.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))._swapAndDie(this,!1),this.isReady=!0;break;case s.Dynamic:(t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode))._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case s.Cube: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);return;case s.CubeRaw:(t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this,!1),this.isReady=!0;break;case s.CubeRawRGBD:return;case s.CubePrefiltered:(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))._sphericalPolynomial=this._sphericalPolynomial;return}}_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);let r=this._engine.getLoadedTexturesCache(),s=r.indexOf(this);-1!==s&&r.splice(s,1),-1===(s=r.indexOf(e))&&r.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}};InternalTexture._Counter=0},7584:function(e,t,i){i.d(t,{a:function(){return TextureSampler}});let TextureSampler=class TextureSampler{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,r=1,s=2,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=s,this._comparisonFunction=n,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}},6962:function(e,t,i){function addClipPlaneUniforms(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 prepareStringDefinesForClipPlanes(e,t,i){var r,s,n,a,o,l;let h=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),u=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),c=!!(null!==(n=e.clipPlane3)&&void 0!==n?n:t.clipPlane3),d=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),p=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),_=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);h&&i.push("#define CLIPPLANE"),u&&i.push("#define CLIPPLANE2"),c&&i.push("#define CLIPPLANE3"),d&&i.push("#define CLIPPLANE4"),p&&i.push("#define CLIPPLANE5"),_&&i.push("#define CLIPPLANE6")}function prepareDefinesForClipPlanes(e,t,i){var r,s,n,a,o,l;let h=!1,u=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),c=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),d=!!(null!==(n=e.clipPlane3)&&void 0!==n?n:t.clipPlane3),p=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),_=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==u&&(i.CLIPPLANE=u,h=!0),i.CLIPPLANE2!==c&&(i.CLIPPLANE2=c,h=!0),i.CLIPPLANE3!==d&&(i.CLIPPLANE3=d,h=!0),i.CLIPPLANE4!==p&&(i.CLIPPLANE4=p,h=!0),i.CLIPPLANE5!==_&&(i.CLIPPLANE5=_,h=!0),i.CLIPPLANE6!==f&&(i.CLIPPLANE6=f,h=!0),h}function bindClipPlane(e,t,i){var r,s,n,a,o,l;let h=null!==(r=t.clipPlane)&&void 0!==r?r:i.clipPlane;setClipPlane(e,"vClipPlane",h),setClipPlane(e,"vClipPlane2",h=null!==(s=t.clipPlane2)&&void 0!==s?s:i.clipPlane2),setClipPlane(e,"vClipPlane3",h=null!==(n=t.clipPlane3)&&void 0!==n?n:i.clipPlane3),setClipPlane(e,"vClipPlane4",h=null!==(a=t.clipPlane4)&&void 0!==a?a:i.clipPlane4),setClipPlane(e,"vClipPlane5",h=null!==(o=t.clipPlane5)&&void 0!==o?o:i.clipPlane5),setClipPlane(e,"vClipPlane6",h=null!==(l=t.clipPlane6)&&void 0!==l?l:i.clipPlane6)}function setClipPlane(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}i.d(t,{AN:function(){return prepareDefinesForClipPlanes},an:function(){return bindClipPlane},lK:function(){return prepareStringDefinesForClipPlanes},qx:function(){return addClipPlaneUniforms}})},9087:function(e,t,i){i.d(t,{U:function(){return ColorCurves}});var r=i(9956),s=i(1760),n=i(2983);let ColorCurves=class ColorCurves{constructor(){this._dirty=!0,this._tempColor=new n.HE(0,0,0,0),this._globalCurve=new n.HE(0,0,0,0),this._highlightsCurve=new n.HE(0,0,0,0),this._midtonesCurve=new n.HE(0,0,0,0),this._shadowsCurve=new n.HE(0,0,0,0),this._positiveCurve=new n.HE(0,0,0,0),this._negativeCurve=new n.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",r="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}static PrepareUniforms(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}_getColorGradingDataToRef(e,t,i,r,s){null!=e&&(e=ColorCurves._Clamp(e,0,360),t=ColorCurves._Clamp(t,-100,100),i=ColorCurves._Clamp(i,-100,100),r=ColorCurves._Clamp(r,-100,100),t=.5*ColorCurves._ApplyColorGradingSliderNonlinear(t),r=ColorCurves._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),ColorCurves._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){let t=Math.abs(e/=100);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100}static _FromHSBToRef(e,t,i,r){let s=ColorCurves._Clamp(e,0,360),n=ColorCurves._Clamp(t/100,0,1),a=ColorCurves._Clamp(i/100,0,1);if(0===n)r.r=a,r.g=a,r.b=a;else{s/=60;let e=Math.floor(s),t=s-e,i=a*(1-n),o=a*(1-n*t),l=a*(1-n*(1-t));switch(e){case 0:r.r=a,r.g=l,r.b=i;break;case 1:r.r=o,r.g=a,r.b=i;break;case 2:r.r=i,r.g=a,r.b=l;break;case 3:r.r=i,r.g=o,r.b=a;break;case 4:r.r=l,r.g=i,r.b=a;break;default:r.r=a,r.g=i,r.b=o}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return s.p4.Clone(()=>new ColorCurves,this)}serialize(){return s.p4.Serialize(this)}static Parse(e){return s.p4.Parse(()=>new ColorCurves,e,null,null)}};(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_globalHue",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_globalDensity",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_globalSaturation",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_globalExposure",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_highlightsHue",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_highlightsDensity",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_highlightsSaturation",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_highlightsExposure",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_midtonesHue",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_midtonesDensity",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_midtonesSaturation",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_midtonesExposure",void 0),s.p4._ColorCurvesParser=ColorCurves.Parse},1606:function(e,t,i){i.d(t,{q:function(){return DrawWrapper}});let DrawWrapper=class DrawWrapper{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 r;this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(r=this.drawContext)||void 0===r||r.reset())}dispose(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()}}},1088:function(e,t,i){i.d(t,{Q:function(){return Effect}});var r=i(4800),s=i(7209),n=i(9626),a=i(7790),o=i(513),l=i(5550);let Effect=class Effect{static get ShadersRepository(){return o.v.ShadersRepository}static set ShadersRepository(e){o.v.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new r.y$),this._onBindObservable}constructor(e,t,i,s=null,n,a=null,o=null,h=null,u=null,c,d="",p=l.x.GLSL){var _,f,m;if(this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new r.y$,this.onErrorObservable=new r.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._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=d,t.attributes){if(this._engine=i,this._attributesNames=t.attributes,this._uniformsNames=t.uniformsNames.concat(t.samplers),this._samplerList=t.samplers.slice(),this.defines=t.defines,this.onError=t.onError,this.onCompiled=t.onCompiled,this._fallbacks=t.fallbacks,this._indexParameters=t.indexParameters,this._transformFeedbackVaryings=t.transformFeedbackVaryings||null,this._multiTarget=!!t.multiTarget,this._shaderLanguage=null!==(_=t.shaderLanguage)&&void 0!==_?_:l.x.GLSL,t.uniformBuffersNames){this._uniformBuffersNamesList=t.uniformBuffersNames.slice();for(let e=0;e<t.uniformBuffersNames.length;e++)this._uniformBuffersNames[t.uniformBuffersNames[e]]=e}this._processFinalCode=null!==(f=t.processFinalCode)&&void 0!==f?f:null,this._processCodeAfterIncludes=null!==(m=t.processCodeAfterIncludes)&&void 0!==m?m:void 0}else this._engine=n,this.defines=null==a?"":a,this._uniformsNames=i.concat(s),this._samplerList=s?s.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=p,this.onError=u,this.onCompiled=h,this._indexParameters=c,this._fallbacks=o;this._attributeLocationByName={},this.uniqueId=Effect._UniqueIdSeed++,this._processShaderCode()}_processShaderCode(e=null,t=!1){let i,r;let n=this.name,l=(0,s.CG)()?this._engine.getHostDocument():null;n.vertexSource?i="source:"+n.vertexSource:n.vertexElement?(i=l?l.getElementById(n.vertexElement):null)||(i=n.vertexElement):i=n.vertex||n,n.fragmentSource?r="source:"+n.fragmentSource:n.fragmentElement?(r=l?l.getElementById(n.fragmentElement):null)||(r=n.fragmentElement):r=n.fragment||n,this._processingContext=this._engine._getShaderProcessingContext(this._shaderLanguage);let h={defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:null!=e?e:this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:o.v.GetShadersRepository(this._shaderLanguage),includesShadersStore:o.v.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes},u=[void 0,void 0],shadersLoaded=()=>{if(u[0]&&u[1]){h.isFragment=!0;let[e,i]=u;a.L.Process(i,h,(i,r)=>{this._fragmentSourceCodeBeforeMigration=r,this._processFinalCode&&(i=this._processFinalCode("fragment",i));let s=a.L.Finalize(e,i,h);h=null,this._useFinalCode(s.vertexCode,s.fragmentCode,n,t)},this._engine)}};this._loadShader(i,"Vertex","",e=>{a.L.Initialize(h),a.L.Process(e,h,(t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,this._processFinalCode&&(t=this._processFinalCode("vertex",t)),u[0]=t,shadersLoaded()},this._engine)}),this._loadShader(r,"Fragment","Pixel",e=>{this._rawFragmentSourceCode=e,u[1]=e,shadersLoaded()})}_useFinalCode(e,t,i,r=!1){if(i){let r=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:"+r+"\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(r)}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){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let n;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){let t=(0,s.v)(e);r(t);return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){let t=window.atob(e.substr(7));r(t);return}let a=o.v.GetShadersStore(this._shaderLanguage);if(a[e+t+"Shader"]){r(a[e+t+"Shader"]);return}if(i&&a[e+i+"Shader"]){r(a[e+i+"Shader"]);return}n="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:o.v.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",r)}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,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{r&&r(t)},this.onCompiled=()=>{let e=this.getEngine().scenes;if(e)for(let t=0;t<e.length;t++)e[t].markAllMaterialsAsDirty(63);this._pipelineContext._handlesSpectorRebuildCallback(i)},this._fallbacks=null,this._prepareEffect()}_prepareEffect(e=!1){var t;let i=this._attributesNames,r=this.defines,s=this._pipelineContext;this._isReady=!1;try{let n=this._engine;this._pipelineContext=null!==(t=e?s:void 0)&&void 0!==t?t:n.createPipelineContext(this._processingContext),this._pipelineContext._name=this._key.replace(/\r/g,"").replace(/\n/g,"|");let rebuildRebind=(e,t,i,r)=>this._rebuildProgram(e,t,i,r);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?n._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,rebuildRebind,null,this._transformFeedbackVaryings,this._key):n._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,rebuildRebind,r,this._transformFeedbackVaryings,this._key),n._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,i,this._attributes),i)for(let e=0;e<i.length;e++){let t=i[e];this._attributeLocationByName[t]=this._attributes[e]}n.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh(),s&&!e&&this.getEngine()._deletePipelineContext(s)}),this._pipelineContext.isAsync&&this._checkIsReady(s)}catch(e){this._processCompilationErrors(e,s)}}_getShaderCodeAndErrorLine(e,t,i){let r=null;if(t&&e){let s=t.match(i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/);if(s&&2===s.length){let t=parseInt(s[1]),n=e.split("\n",-1);n.length>=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i,r,s;this._compilationError=e.message;let a=this._attributesNames,o=this._fallbacks;if(n.Y.Error("Unable to compile effect:"),n.Y.Error("Uniforms: "+this._uniformsNames.map(function(e){return" "+e})),n.Y.Error("Attributes: "+a.map(function(e){return" "+e})),n.Y.Error("Defines:\n"+this.defines),Effect.LogShaderCodeOnCompilationError){let e=null,t=null,a=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([a,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),a&&(n.Y.Error("Vertex code:"),n.Y.Error(a))),(null===(r=this._pipelineContext)||void 0===r?void 0:r._getFragmentShaderCode())&&([a,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),a&&(n.Y.Error("Fragment code:"),n.Y.Error(a))),e&&n.Y.Error(e),t&&n.Y.Error(t)}n.Y.Error("Error: "+this._compilationError);let notifyErrors=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,notifyErrors()),o?(this._pipelineContext=null,o.hasMoreFallbacks?(this._allFallbacksProcessed=!1,n.Y.Error("Trying next fallback."),this.defines=o.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,notifyErrors(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||notifyErrors())}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){let i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){let r=this._samplerList.indexOf(e);for(let e=1;e<t.length;e++){let t=i+(e-1).toString();this._samplerList.splice(r+e,0,t)}let s=0;for(let e of this._samplerList)this._samplers[e]=s,s+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}setTextureFromPostProcess(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)}setTextureFromPostProcessOutput(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)}bindUniformBuffer(e,t){let i=this._uniformBuffersNames[t];void 0===i||Effect._BaseCache[i]===e&&this._engine._features.useUBOBindingCache||(Effect._BaseCache[i]=e,this._engine.bindUniformBufferBase(e,i,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setInt3(e,t,i,r){return this._pipelineContext.setInt3(e,t,i,r),this}setInt4(e,t,i,r,s){return this._pipelineContext.setInt4(e,t,i,r,s),this}setIntArray(e,t){return this._pipelineContext.setIntArray(e,t),this}setIntArray2(e,t){return this._pipelineContext.setIntArray2(e,t),this}setIntArray3(e,t){return this._pipelineContext.setIntArray3(e,t),this}setIntArray4(e,t){return this._pipelineContext.setIntArray4(e,t),this}setUInt(e,t){return this._pipelineContext.setUInt(e,t),this}setUInt2(e,t,i){return this._pipelineContext.setUInt2(e,t,i),this}setUInt3(e,t,i,r){return this._pipelineContext.setUInt3(e,t,i,r),this}setUInt4(e,t,i,r,s){return this._pipelineContext.setUInt4(e,t,i,r,s),this}setUIntArray(e,t){return this._pipelineContext.setUIntArray(e,t),this}setUIntArray2(e,t){return this._pipelineContext.setUIntArray2(e,t),this}setUIntArray3(e,t){return this._pipelineContext.setUIntArray3(e,t),this}setUIntArray4(e,t){return this._pipelineContext.setUIntArray4(e,t),this}setFloatArray(e,t){return this._pipelineContext.setArray(e,t),this}setFloatArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setFloatArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setFloatArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setArray(e,t){return this._pipelineContext.setArray(e,t),this}setArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setMatrices(e,t){return this._pipelineContext.setMatrices(e,t),this}setMatrix(e,t){return this._pipelineContext.setMatrix(e,t),this}setMatrix3x3(e,t){return this._pipelineContext.setMatrix3x3(e,t),this}setMatrix2x2(e,t){return this._pipelineContext.setMatrix2x2(e,t),this}setFloat(e,t){return this._pipelineContext.setFloat(e,t),this}setBool(e,t){return this._pipelineContext.setInt(e,t?1:0),this}setVector2(e,t){return this._pipelineContext.setVector2(e,t),this}setFloat2(e,t,i){return this._pipelineContext.setFloat2(e,t,i),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,i,r){return this._pipelineContext.setFloat3(e,t,i,r),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,i,r,s){return this._pipelineContext.setFloat4(e,t,i,r,s),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,i){return this._pipelineContext.setColor4(e,t,i),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseEffect(this),this._isDisposed=!0}static RegisterShader(e,t,i,r=l.x.GLSL){t&&(o.v.GetShadersStore(r)[`${e}PixelShader`]=t),i&&(o.v.GetShadersStore(r)[`${e}VertexShader`]=i)}static ResetCache(){Effect._BaseCache={}}};Effect.LogShaderCodeOnCompilationError=!0,Effect._UniqueIdSeed=0,Effect._BaseCache={},Effect.ShadersStore=o.v.ShadersStore,Effect.IncludesShadersStore=o.v.IncludesShadersStore},1974:function(e,t,i){i.d(t,{$:function(){return ImageProcessingConfiguration},b:function(){return ImageProcessingConfigurationDefines}});var r=i(9956),s=i(1760),n=i(4800),a=i(5132),o=i(2983),l=i(5377),h=i(9087);let ImageProcessingConfigurationDefines=class ImageProcessingConfigurationDefines extends l.H{constructor(){super(),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.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}};let ImageProcessingConfiguration=class ImageProcessingConfiguration{constructor(){this.colorCurves=new h.U,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=ImageProcessingConfiguration.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new o.HE(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new n.y$}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}static PrepareUniforms(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&h.U.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType===ImageProcessingConfiguration.TONEMAPPING_ACES)?e.TONEMAPPING_ACES=!0:e.TONEMAPPING_ACES=!1,e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&h.U.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){let i=1/e.getEngine().getRenderWidth(),r=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){let s=null!=t?t:r/i,n=Math.tan(.5*this.vignetteCameraFov),o=n*s,l=Math.sqrt(o*n);o=a.w1.Mix(o,l,this.vignetteStretch),n=a.w1.Mix(n,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*this.vignetteCenterX,-n*this.vignetteCenterY);let h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);let t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return s.p4.Clone(()=>new ImageProcessingConfiguration,this)}serialize(){return s.p4.Serialize(this)}static Parse(e){let t=s.p4.Parse(()=>new ImageProcessingConfiguration,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}};ImageProcessingConfiguration.TONEMAPPING_STANDARD=0,ImageProcessingConfiguration.TONEMAPPING_ACES=1,ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY=0,ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE=1,(0,r.gn)([(0,s.N$)()],ImageProcessingConfiguration.prototype,"colorCurves",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_colorCurvesEnabled",void 0),(0,r.gn)([(0,s.oU)("colorGradingTexture")],ImageProcessingConfiguration.prototype,"_colorGradingTexture",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_colorGradingEnabled",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_colorGradingWithGreenDepth",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_colorGradingBGR",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_exposure",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_toneMappingEnabled",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_toneMappingType",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_contrast",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"vignetteStretch",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"vignetteCenterX",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"vignetteCenterY",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"vignetteWeight",void 0),(0,r.gn)([(0,s.XX)()],ImageProcessingConfiguration.prototype,"vignetteColor",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"vignetteCameraFov",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_vignetteBlendMode",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_vignetteEnabled",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_ditheringEnabled",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_ditheringIntensity",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_skipFinalColorClamp",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_applyByPostProcess",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_isEnabled",void 0),s.p4._ImageProcessingConfigurationParser=ImageProcessingConfiguration.Parse},2515:function(e,t,i){i.d(t,{F:function(){return Material}});var r=i(9956),s=i(1760),n=i(5132),a=i(4800),o=i(6030),l=i(1091),h=i(9691),u=i(9626),c=i(1564),d=i(3385),p=i(1606);let MaterialStencilState=class MaterialStencilState{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,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"func",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"funcRef",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"funcMask",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"opStencilFail",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"opDepthFail",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"opStencilDepthPass",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"mask",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"enabled",null);var _=i(6540),f=i(4885);let Material=class Material{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;let t=this._alpha;this._alpha=e,(1===t||1===e)&&this.markAsDirty(Material.MiscDirtyFlag+Material.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Material.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Material.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 a.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 a.y$),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new a.y$),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Material.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(Material.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Material.WireFrameFillMode:case Material.LineListDrawMode:case Material.LineLoopDrawMode:case Material.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Material.WireFrameFillMode:Material.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Material.PointFillMode:case Material.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Material.PointFillMode:Material.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Material.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 a.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 MaterialStencilState,this._useUBO=!1,this._fillMode=Material.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=()=>void 0,this._callbackPluginEventIsReadyForSubMesh=()=>void 0,this._callbackPluginEventPrepareDefines=()=>void 0,this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>void 0,this._callbackPluginEventHardBindForSubMesh=()=>void 0,this._callbackPluginEventBindForSubMesh=()=>void 0,this._callbackPluginEventHasRenderTargetTextures=()=>void 0,this._callbackPluginEventFillRenderTargetTextures=()=>void 0,this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;let r=t||o.l.LastCreatedScene;if(!r)return;this._scene=r,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||n.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=Material.ClockWiseSideOrientation:this.sideOrientation=Material.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={}),Material.OnEventObservable.notifyObservers(this,f.S.Created)}toString(e){let t="Name: "+this.name;return t}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){let r=t.materialDefines;return!!r&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Material.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Material.MATERIAL_OPAQUE||this._transparencyMode===Material.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){let t=this.getScene().meshes;for(let i of t)if(i.subMeshes)for(let t of i.subMeshes)t.getMaterial()===this&&t.effect&&(t.effect._wasPreviouslyReady=!1,t.effect._wasPreviouslyUsingInstances=null,t.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(Material.AllDirtyFlag)}_preBind(e,t=null){let i=this._scene.getEngine(),r=null==t?this.sideOrientation:t,s=r===Material.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){let e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(f.S.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){let r=i.effect;r&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1)}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,d.G.BindSceneUniformBuffer(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){let e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){let e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){let e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){if(this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction){let e=this._scene.getEngine();e.setDepthFunction(this._cachedDepthFunctionState)}if(this.disableDepthWrite){let e=this._scene.getEngine();e.setDepthWrite(this._cachedDepthWriteState)}if(this.disableColorWrite){let e=this._scene.getEngine();e.setColorWrite(this._cachedColorWriteState)}}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(f.S.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(f.S.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(f.S.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){let i={};if(this._serializePlugins(i),Material._parsePlugins(i,e,this._scene,t),this.pluginManager)for(let t of this.pluginManager._plugins){let i=e.pluginManager.getPlugin(t.name);t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){let e=[];for(let t in this.meshMap){let i=this.meshMap[t];i&&e.push(i)}return e}{let e=this._scene.meshes;return e.filter(e=>e.material===this)}}forceCompilation(e,t,i,r){let s=Object.assign({clipPlane:!1,useInstances:!1},i),n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;let checkReady=()=>{if(!this._scene||!this._scene.getEngine())return;let i=n.clipPlane;if(s.clipPlane&&(n.clipPlane=new c.J(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){let 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()?n=t.effect.getCompilationError():(i=!1,setTimeout(checkReady,16)))}i&&(this.allowShaderHotSwapping=a,n&&r&&r(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(checkReady,16);s.clipPlane&&(n.clipPlane=i)};checkReady()}forceCompilationAsync(e,t){return new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,e=>{r(e)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Material._DirtyCallbackArray.length=0,e&Material.TextureDirtyFlag&&Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack),e&Material.LightDirtyFlag&&Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack),e&Material.FresnelDirtyFlag&&Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack),e&Material.AttributesDirtyFlag&&Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack),e&Material.MiscDirtyFlag&&Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack),e&Material.PrePassDirtyFlag&&Material._DirtyCallbackArray.push(Material._PrePassDirtyCallBack),Material._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){let e=this.getScene().meshes;for(let t of e)if(t.subMeshes)for(let e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let t=this.getScene().meshes;for(let i of t)if(i.subMeshes){for(let t of i.subMeshes)if(t.getMaterial(!1)===this)for(let 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;let e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Material._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==_.a.BackwardCompatible){this.checkReadyOnlyOnce=!0;let e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){let r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(f.S.Disposed,this._eventInfo),this._parentContainer){let e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i){if(this.meshMap)for(let t in this.meshMap){let i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{let t=r.meshes;for(let 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){let i=e.geometry;if(i){if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(let r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){let 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(let 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 u.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";let r=n.w1.Instantiate(e.customType),s=r.Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _parsePlugins(e,t,i,r){var s;if(e.plugins)for(let a in e.plugins){let o=e.plugins[a],l=null===(s=t.pluginManager)||void 0===s?void 0:s.getPlugin(o.name);if(!l){let e=n.w1.Instantiate("BABYLON."+a);e&&(l=new e(t))}null==l||l.parse(o,i,r)}}};Material.TriangleFillMode=0,Material.WireFrameFillMode=1,Material.PointFillMode=2,Material.PointListDrawMode=3,Material.LineListDrawMode=4,Material.LineLoopDrawMode=5,Material.LineStripDrawMode=6,Material.TriangleStripDrawMode=7,Material.TriangleFanDrawMode=8,Material.ClockWiseSideOrientation=0,Material.CounterClockWiseSideOrientation=1,Material.TextureDirtyFlag=1,Material.LightDirtyFlag=2,Material.FresnelDirtyFlag=4,Material.AttributesDirtyFlag=8,Material.MiscDirtyFlag=16,Material.PrePassDirtyFlag=32,Material.AllDirtyFlag=63,Material.MATERIAL_OPAQUE=0,Material.MATERIAL_ALPHATEST=1,Material.MATERIAL_ALPHABLEND=2,Material.MATERIAL_ALPHATESTANDBLEND=3,Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,Material.MATERIAL_NORMALBLENDMETHOD_RNM=1,Material.OnEventObservable=new a.y$,Material._AllDirtyCallBack=e=>e.markAllAsDirty(),Material._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),Material._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),Material._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),Material._MiscDirtyCallBack=e=>e.markAsMiscDirty(),Material._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),Material._LightsDirtyCallBack=e=>e.markAsLightDirty(),Material._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),Material._FresnelAndMiscDirtyCallBack=e=>{Material._FresnelDirtyCallBack(e),Material._MiscDirtyCallBack(e)},Material._TextureAndMiscDirtyCallBack=e=>{Material._TextureDirtyCallBack(e),Material._MiscDirtyCallBack(e)},Material._DirtyCallbackArray=[],Material._RunDirtyCallBacks=e=>{for(let t of Material._DirtyCallbackArray)t(e)},(0,r.gn)([(0,s.qC)()],Material.prototype,"id",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"uniqueId",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"name",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"metadata",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"checkReadyOnEveryCall",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"checkReadyOnlyOnce",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"state",void 0),(0,r.gn)([(0,s.qC)("alpha")],Material.prototype,"_alpha",void 0),(0,r.gn)([(0,s.qC)("backFaceCulling")],Material.prototype,"_backFaceCulling",void 0),(0,r.gn)([(0,s.qC)("cullBackFaces")],Material.prototype,"_cullBackFaces",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"sideOrientation",void 0),(0,r.gn)([(0,s.qC)("alphaMode")],Material.prototype,"_alphaMode",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"_needDepthPrePass",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"disableDepthWrite",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"disableColorWrite",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"forceDepthWrite",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"depthFunction",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"separateCullingPass",void 0),(0,r.gn)([(0,s.qC)("fogEnabled")],Material.prototype,"_fogEnabled",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"pointSize",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"zOffset",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"zOffsetUnits",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"pointsCloud",null),(0,r.gn)([(0,s.qC)()],Material.prototype,"fillMode",null),(0,r.gn)([(0,s.qC)()],Material.prototype,"transparencyMode",null)},5377:function(e,t,i){i.d(t,{H:function(){return MaterialDefines}});let MaterialDefines=class MaterialDefines{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(let 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(){for(let e of(this._keys.length=0,Object.keys(this)))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(let e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;t<this._keys.length;t++){let i=this._keys[t];if(this[i]!==e[i])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){let i=this._keys[t];e[i]=this[i]}}reset(){this._keys.forEach(e=>this._setDefaultValue(e))}_setDefaultValue(e){var t,i,r,s,n;let a=null!==(r=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==r?r:typeof this[e],o=null===(n=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===n?void 0:n.default;switch(a){case"number":this[e]=null!=o?o:0;break;case"string":this[e]=null!=o?o:"";break;default:this[e]=null!=o&&o}}toString(){let e="";for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=this[i],s=typeof r;switch(s){case"number":case"string":e+="#define "+i+" "+r+"\n";break;default:r&&(e+="#define "+i+"\n")}}return e}}},3385:function(e,t,i){i.d(t,{G:function(){return MaterialHelper}});var r=i(9626),s=i(555),n=i(6540),a=i(6030),o=i(1295),l=i(6972),h=i(2983),u=i(6962);let MaterialHelper=class MaterialHelper{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}static BindTextureMatrix(e,t,i){let r=e.getTextureMatrix();t.updateMatrix(i+"Matrix",r)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==n.x.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,r,s,n,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=r,a.FOG=s&&this.GetFogState(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=o)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){let r=t.CAMERA_ORTHOGRAPHIC?1:0,n=t.CAMERA_PERSPECTIVE?1:0,a=e.activeCamera.mode===s.V.ORTHOGRAPHIC_CAMERA?1:0,o=e.activeCamera.mode===s.V.PERSPECTIVE_CAMERA?1:0;(r^a||n^o)&&(t.CAMERA_ORTHOGRAPHIC=1===a,t.CAMERA_PERSPECTIVE=1===o,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,r,s,n=null,a=!1){let o=MaterialHelper.PrepareDefinesForCamera(e,r);!1!==n&&(o=(0,u.AN)(i,e,r)),!t.getColorWrite()!==r.DEPTHPREPASS&&(r.DEPTHPREPASS=!r.DEPTHPREPASS,o=!0),r.INSTANCES!==s&&(r.INSTANCES=s,o=!0),r.THIN_INSTANCES!==a&&(r.THIN_INSTANCES=a,o=!0),o&&r.markAsUnprocessed()}static PrepareDefinesForBones(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;let i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;let r=e.getScene().prePassRenderer;if(r&&r.enabled){let i=-1===r.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(e,t){let i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,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){let i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!i&&!!i.isEnabled}static PrepareDefinesForAttributes(e,t,i,r,s=!1,n=!0,a=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(o.o.NormalKind),t._needNormals&&e.isVerticesDataPresent(o.o.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){let i=e.useVertexColors&&e.isVerticesDataPresent(o.o.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent(o.o.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),r&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),a&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){let i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){let r=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(r!==t.ORDER_INDEPENDENT_TRANSPARENCY||s!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){let r=t.PREPASS;if(!t._arePrePassDirty)return;let 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,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i<s.length;i++){let r=e.prePassRenderer.getIndex(s[i].type);-1!==r?(t[s[i].define]=!0,t[s[i].index]=r):t[s[i].define]=!1}}else{t.PREPASS=!1;for(let e=0;e<s.length;e++)t[s[e].define]=!1}t.PREPASS!=r&&(t.markAsUnprocessed(),t.markAsImageProcessingDirty())}static PrepareDefinesForLight(e,t,i,r,s,n,a){var o;switch(a.needNormals=!0,void 0===s["LIGHT"+r]&&(a.needRebuild=!0),s["LIGHT"+r]=!0,s["SPOTLIGHT"+r]=!1,s["HEMILIGHT"+r]=!1,s["POINTLIGHT"+r]=!1,s["DIRLIGHT"+r]=!1,i.prepareLightSpecificDefines(s,r),s["LIGHT_FALLOFF_PHYSICAL"+r]=!1,s["LIGHT_FALLOFF_GLTF"+r]=!1,s["LIGHT_FALLOFF_STANDARD"+r]=!1,i.falloffType){case l.m.FALLOFF_GLTF:s["LIGHT_FALLOFF_GLTF"+r]=!0;break;case l.m.FALLOFF_PHYSICAL:s["LIGHT_FALLOFF_PHYSICAL"+r]=!0;break;case l.m.FALLOFF_STANDARD:s["LIGHT_FALLOFF_STANDARD"+r]=!0}if(n&&!i.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),s["SHADOW"+r]=!1,s["SHADOWCSM"+r]=!1,s["SHADOWCSMDEBUG"+r]=!1,s["SHADOWCSMNUM_CASCADES"+r]=!1,s["SHADOWCSMUSESHADOWMAXZ"+r]=!1,s["SHADOWCSMNOBLEND"+r]=!1,s["SHADOWCSM_RIGHTHANDED"+r]=!1,s["SHADOWPCF"+r]=!1,s["SHADOWPCSS"+r]=!1,s["SHADOWPOISSON"+r]=!1,s["SHADOWESM"+r]=!1,s["SHADOWCLOSEESM"+r]=!1,s["SHADOWCUBE"+r]=!1,s["SHADOWLOWQUALITY"+r]=!1,s["SHADOWMEDIUMQUALITY"+r]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){let t=null!==(o=i.getShadowGenerator(e.activeCamera))&&void 0!==o?o:i.getShadowGenerator();if(t){let e=t.getShadowMap();e&&e.renderList&&e.renderList.length>0&&(a.shadowEnabled=!0,t.prepareDefines(s,r))}}i.lightmapMode!=l.m.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+r]=!0,s["LIGHTMAPNOSPECULAR"+r]=i.lightmapMode==l.m.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+r]=!1,s["LIGHTMAPNOSPECULAR"+r]=!1)}static PrepareDefinesForLights(e,t,i,r,s=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let a=0,o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n){for(let n of t.lightSources)if(this.PrepareDefinesForLight(e,t,n,a,i,r,o),++a===s)break}i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e<s;e++)void 0!==i["LIGHT"+e]&&(i["LIGHT"+e]=!1,i["HEMILIGHT"+e]=!1,i["POINTLIGHT"+e]=!1,i["DIRLIGHT"+e]=!1,i["SPOTLIGHT"+e]=!1,i["SHADOW"+e]=!1,i["SHADOWCSM"+e]=!1,i["SHADOWCSMDEBUG"+e]=!1,i["SHADOWCSMNUM_CASCADES"+e]=!1,i["SHADOWCSMUSESHADOWMAXZ"+e]=!1,i["SHADOWCSMNOBLEND"+e]=!1,i["SHADOWCSM_RIGHTHANDED"+e]=!1,i["SHADOWPCF"+e]=!1,i["SHADOWPCSS"+e]=!1,i["SHADOWPOISSON"+e]=!1,i["SHADOWESM"+e]=!1,i["SHADOWCLOSEESM"+e]=!1,i["SHADOWCUBE"+e]=!1,i["SHADOWLOWQUALITY"+e]=!1,i["SHADOWMEDIUMQUALITY"+e]=!1);let l=e.getEngine().getCaps();return void 0===i.SHADOWFLOAT&&(o.needRebuild=!0),i.SHADOWFLOAT=o.shadowEnabled&&(l.textureFloatRender&&l.textureFloatLinearFiltering||l.textureHalfFloatRender&&l.textureHalfFloatLinearFiltering),i.LIGHTMAPEXCLUDED=o.lightmapMode,o.needRebuild&&i.rebuild(),o.needNormals}static PrepareUniformsAndSamplersForLight(e,t,i,r,s=null,n=!1){s&&s.push("Light"+e),!n&&(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),i.push("shadowSampler"+e),i.push("depthSampler"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),r&&(i.push("projectionLightSampler"+e),t.push("textureProjectionMatrix"+e)))}static PrepareUniformsAndSamplersList(e,t,i,r=4){let s;let n=null;e.uniformsNames?(s=e.uniformsNames,n=e.uniformBuffersNames,t=e.samplers,i=e.defines,r=e.maxSimultaneousLights||0):(s=e,t||(t=[]));for(let e=0;e<r&&i["LIGHT"+e];e++)this.PrepareUniformsAndSamplersForLight(e,s,t,i["PROJECTEDLIGHTTEXTURE"+e],n);i.NUM_MORPH_INFLUENCERS&&s.push("morphTargetInfluences"),i.BAKED_VERTEX_ANIMATION_TEXTURE&&(s.push("bakedVertexAnimationSettings"),s.push("bakedVertexAnimationTextureSizeInverted"),s.push("bakedVertexAnimationTime"),t.push("bakedVertexAnimationTexture"))}static HandleFallbacksForShadows(e,t,i=4,r=0){let s=0;for(let n=0;n<i&&e["LIGHT"+n];n++)n>0&&(s=r+n,t.addFallback(s,"LIGHT"+n)),!e.SHADOWS&&(e["SHADOW"+n]&&t.addFallback(r,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(r,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(r,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(r,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(r,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(r,"SHADOWCLOSEESM"+n));return s++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){let s=i.NUM_MORPH_INFLUENCERS;if(s>0&&a.l.LastCreatedEngine){let n=a.l.LastCreatedEngine.getCaps().maxVertexAttribs,l=t.morphTargetManager;if(null==l?void 0:l.isUsingTextureForTargets)return;let h=l&&l.supportsNormals&&i.NORMAL,u=l&&l.supportsTangents&&i.TANGENT,c=l&&l.supportsUVs&&i.UV1;for(let i=0;i<s;i++)e.push(o.o.PositionKind+i),h&&e.push(o.o.NormalKind+i),u&&e.push(o.o.TangentKind+i),c&&e.push(o.o.UVKind+"_"+i),e.length>n&&r.Y.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){let r=i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES;r&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,r){i.NUM_BONE_INFLUENCERS>0&&(r.addCPUSkinningFallback(0,t),e.push(o.o.MatricesIndicesKind),e.push(o.o.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(o.o.MatricesIndicesExtraKind),e.push(o.o.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(o.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,r,s,n=!0){e._bindLight(t,i,r,s,n)}static BindLights(e,t,i,r,s=4){let n=Math.min(t.lightSources.length,s);for(let s=0;s<n;s++){let n=t.lightSources[s];this.BindLight(n,s,e,i,"boolean"==typeof r?r:r.SPECULARTERM,t.receiveShadows)}}static BindFogParameters(e,t,i,r=!1){e.fogEnabled&&t.applyFog&&e.fogMode!==n.x.FOGMODE_NONE&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),r?(e.fogColor.toLinearSpaceToRef(this._TempFogColor,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",this._TempFogColor)):i.setColor3("vFogColor",e.fogColor))}static BindBonesParameters(e,t,i){if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){let r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){let i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{let s=r.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]),MaterialHelper._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){let 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){let e=i.activeCamera;e.mode===s.V.ORTHOGRAPHIC_CAMERA&&r.Y.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}};MaterialHelper._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},MaterialHelper._TempFogColor=h.Wo.Black()},4885:function(e,t,i){var r,s;i.d(t,{S:function(){return r}}),(s=r||(r={}))[s.Created=1]="Created",s[s.Disposed=2]="Disposed",s[s.GetDefineNames=4]="GetDefineNames",s[s.PrepareUniformBuffer=8]="PrepareUniformBuffer",s[s.IsReadyForSubMesh=16]="IsReadyForSubMesh",s[s.PrepareDefines=32]="PrepareDefines",s[s.BindForSubMesh=64]="BindForSubMesh",s[s.PrepareEffect=128]="PrepareEffect",s[s.GetAnimatables=256]="GetAnimatables",s[s.GetActiveTextures=512]="GetActiveTextures",s[s.HasTexture=1024]="HasTexture",s[s.FillRenderTargetTextures=2048]="FillRenderTargetTextures",s[s.HasRenderTargetTextures=4096]="HasRenderTargetTextures",s[s.HardBindForSubMesh=8192]="HardBindForSubMesh"},5461:function(e,t,i){i.d(t,{G:function(){return MultiMaterial}});var r=i(2515),s=i(1803),n=i(3048);let MultiMaterial=class MultiMaterial extends r.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=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._markAllSubMeshesAsTexturesDirty(),s}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i<this.subMaterials.length;i++)if(null===(t=this.subMaterials[i])||void 0===t?void 0:t.hasTexture(e))return!0;return!1}getClassName(){return"MultiMaterial"}isReadyForSubMesh(e,t,i){for(let r=0;r<this.subMaterials.length;r++){let s=this.subMaterials[r];if(s){if(s._storeEffectOnSubMeshes){if(!s.isReadyForSubMesh(e,t,i))return!1;continue}if(!s.isReady(e))return!1}}return!0}clone(e,t){let i=new MultiMaterial(e,this.getScene());for(let r=0;r<this.subMaterials.length;r++){let s=null,n=this.subMaterials[r];s=t&&n?n.clone(e+"-"+n.name):this.subMaterials[r],i.subMaterials.push(s)}return i}serialize(){let e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,s.$&&(e.tags=s.$.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){let i=this.subMaterials[t];i?(e.materialsUniqueIds.push(i.uniqueId),e.materials.push(i.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,i){let r=this.getScene();if(!r)return;if(i)for(let i=0;i<this.subMaterials.length;i++){let r=this.subMaterials[i];r&&r.dispose(e,t)}let s=r.multiMaterials.indexOf(this);s>=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){let i=new MultiMaterial(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,n.H)("BABYLON.MultiMaterial",MultiMaterial)},5550:function(e,t,i){var r,s;i.d(t,{x:function(){return r}}),(s=r||(r={}))[s.GLSL=0]="GLSL",s[s.WGSL=1]="WGSL"},9691:function(e,t,i){i.d(t,{M:function(){return UniformBuffer}});var r=i(9626),s=i(5132);i(68);let UniformBuffer=class UniformBuffer{constructor(e,t,i,r,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=r?r:"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){let e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;let i=this._uniformLocationPointer-e;for(let e=0;e<i;e++)this._data.push(0)}}addUniform(e,t,i=0){let r;if(!this._noUBO&&void 0===this._uniformLocations[e]){if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t)t*=i;else{let e=4-t;t=t*i+e*i}r=[];for(let e=0;e<t;e++)r.push(0)}else{if(t instanceof Array)t=(r=t).length;else{r=[];for(let e=0;e<t;e++)r.push(0)}this._fillAlignment(t)}this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(let e=0;e<t;e++)this._data.push(r[e]);this._needSync=!0}}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.toArray()))}addFloat2(e,t,i){let r=[t,i];this.addUniform(e,r)}addFloat3(e,t,i,r){let s=[t,i,r];this.addUniform(e,s)}addColor3(e,t){let i=[t.r,t.g,t.b];this.addUniform(e,i)}addColor4(e,t,i){let r=[t.r,t.g,t.b,i];this.addUniform(e,r)}addVector3(e,t){let i=[t.x,t.y,t.z];this.addUniform(e,i)}addMatrix3x3(e){this.addUniform(e,12)}addMatrix2x2(e){this.addUniform(e,8)}create(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)}_getNames(){let e=[];for(let t in this._uniformLocations)e.push(t);return e.join(",")}_rebuild(){!this._noUBO&&this._bufferData&&(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()):this._buffer=this._engine.createUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()),this._engine._features.trackUbosInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}_copyBuffer(e,t){for(let i=0;i<e.length;++i)t[i]=e[i]}update(){if(!this._noUBO){if(this.bindUniformBuffer(),!this._buffer){this.create();return}if(!this._dynamic&&!this._needSync){this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}if(this._buffers&&this._buffers.length>1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(UniformBuffer._UpdatedUbosInFrame[this._name]||(UniformBuffer._UpdatedUbosInFrame[this._name]=0),UniformBuffer._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()}_checkNewFrame(){this._engine._features.trackUbosInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(void 0===s){if(this._buffer){r.Y.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e<i;e++)this._bufferData[s+e]=t[e];else{let e=!1;for(let r=0;r<i;r++)(16!==i||this._engine._features.uniformBufferHardCheckMatrix)&&this._bufferData[s+r]===Math.fround(t[r])||(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[s+r]=t[r]);this._needSync=this._needSync||e}}updateUniformArray(e,t,i){this._checkNewFrame();let n=this._uniformLocations[e];if(void 0===n){r.Y.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.");return}this._buffer||this.create();let a=this._uniformArraySizes[e];if(this._dynamic)for(let e=0;e<i;e++)this._bufferData[n+e]=t[e];else{let e=!1,r=0,o=0;for(let l=0;l<i;l++)if(this._bufferData[n+4*o+r]!==s.w1.FloatRound(t[l])&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[n+4*o+r]=t[l]),++r===a.strideSize){for(;r<4;r++)this._bufferData[n+4*o+r]=0;r=0,o++}this._needSync=this._needSync||e}}_cacheMatrix(e,t){this._checkNewFrame();let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_updateMatrix3x3ForUniform(e,t){for(let e=0;e<3;e++)UniformBuffer._TempBuffer[4*e]=t[3*e],UniformBuffer._TempBuffer[4*e+1]=t[3*e+1],UniformBuffer._TempBuffer[4*e+2]=t[3*e+2],UniformBuffer._TempBuffer[4*e+3]=0;this.updateUniform(e,UniformBuffer._TempBuffer,12)}_updateMatrix3x3ForEffect(e,t){this._currentEffect.setMatrix3x3(e,t)}_updateMatrix2x2ForEffect(e,t){this._currentEffect.setMatrix2x2(e,t)}_updateMatrix2x2ForUniform(e,t){for(let e=0;e<2;e++)UniformBuffer._TempBuffer[4*e]=t[2*e],UniformBuffer._TempBuffer[4*e+1]=t[2*e+1],UniformBuffer._TempBuffer[4*e+2]=0,UniformBuffer._TempBuffer[4*e+3]=0;this.updateUniform(e,UniformBuffer._TempBuffer,8)}_updateFloatForEffect(e,t){this._currentEffect.setFloat(e,t)}_updateFloatForUniform(e,t){UniformBuffer._TempBuffer[0]=t,this.updateUniform(e,UniformBuffer._TempBuffer,1)}_updateFloat2ForEffect(e,t,i,r=""){this._currentEffect.setFloat2(e+r,t,i)}_updateFloat2ForUniform(e,t,i){UniformBuffer._TempBuffer[0]=t,UniformBuffer._TempBuffer[1]=i,this.updateUniform(e,UniformBuffer._TempBuffer,2)}_updateFloat3ForEffect(e,t,i,r,s=""){this._currentEffect.setFloat3(e+s,t,i,r)}_updateFloat3ForUniform(e,t,i,r){UniformBuffer._TempBuffer[0]=t,UniformBuffer._TempBuffer[1]=i,UniformBuffer._TempBuffer[2]=r,this.updateUniform(e,UniformBuffer._TempBuffer,3)}_updateFloat4ForEffect(e,t,i,r,s,n=""){this._currentEffect.setFloat4(e+n,t,i,r,s)}_updateFloat4ForUniform(e,t,i,r,s){UniformBuffer._TempBuffer[0]=t,UniformBuffer._TempBuffer[1]=i,UniformBuffer._TempBuffer[2]=r,UniformBuffer._TempBuffer[3]=s,this.updateUniform(e,UniformBuffer._TempBuffer,4)}_updateFloatArrayForEffect(e,t){this._currentEffect.setFloatArray(e,t)}_updateFloatArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateArrayForEffect(e,t){this._currentEffect.setArray(e,t)}_updateArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateIntArrayForEffect(e,t){this._currentEffect.setIntArray(e,t)}_updateIntArrayForUniform(e,t){UniformBuffer._TempBufferInt32View.set(t),this.updateUniformArray(e,UniformBuffer._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){UniformBuffer._TempBufferUInt32View.set(t),this.updateUniformArray(e,UniformBuffer._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.toArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){UniformBuffer._TempBuffer[0]=t.x,UniformBuffer._TempBuffer[1]=t.y,UniformBuffer._TempBuffer[2]=t.z,this.updateUniform(e,UniformBuffer._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){UniformBuffer._TempBuffer[0]=t.x,UniformBuffer._TempBuffer[1]=t.y,UniformBuffer._TempBuffer[2]=t.z,UniformBuffer._TempBuffer[3]=t.w,this.updateUniform(e,UniformBuffer._TempBuffer,4)}_updateColor3ForEffect(e,t,i=""){this._currentEffect.setColor3(e+i,t)}_updateColor3ForUniform(e,t){UniformBuffer._TempBuffer[0]=t.r,UniformBuffer._TempBuffer[1]=t.g,UniformBuffer._TempBuffer[2]=t.b,this.updateUniform(e,UniformBuffer._TempBuffer,3)}_updateColor4ForEffect(e,t,i,r=""){this._currentEffect.setColor4(e+r,t,i)}_updateDirectColor4ForEffect(e,t,i=""){this._currentEffect.setDirectColor4(e+i,t)}_updateColor4ForUniform(e,t,i){UniformBuffer._TempBuffer[0]=t.r,UniformBuffer._TempBuffer[1]=t.g,UniformBuffer._TempBuffer[2]=t.b,UniformBuffer._TempBuffer[3]=i,this.updateUniform(e,UniformBuffer._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){UniformBuffer._TempBuffer[0]=t.r,UniformBuffer._TempBuffer[1]=t.g,UniformBuffer._TempBuffer[2]=t.b,UniformBuffer._TempBuffer[3]=t.a,this.updateUniform(e,UniformBuffer._TempBuffer,4)}_updateIntForEffect(e,t,i=""){this._currentEffect.setInt(e+i,t)}_updateIntForUniform(e,t){UniformBuffer._TempBufferInt32View[0]=t,this.updateUniform(e,UniformBuffer._TempBuffer,1)}_updateInt2ForEffect(e,t,i,r=""){this._currentEffect.setInt2(e+r,t,i)}_updateInt2ForUniform(e,t,i){UniformBuffer._TempBufferInt32View[0]=t,UniformBuffer._TempBufferInt32View[1]=i,this.updateUniform(e,UniformBuffer._TempBuffer,2)}_updateInt3ForEffect(e,t,i,r,s=""){this._currentEffect.setInt3(e+s,t,i,r)}_updateInt3ForUniform(e,t,i,r){UniformBuffer._TempBufferInt32View[0]=t,UniformBuffer._TempBufferInt32View[1]=i,UniformBuffer._TempBufferInt32View[2]=r,this.updateUniform(e,UniformBuffer._TempBuffer,3)}_updateInt4ForEffect(e,t,i,r,s,n=""){this._currentEffect.setInt4(e+n,t,i,r,s)}_updateInt4ForUniform(e,t,i,r,s){UniformBuffer._TempBufferInt32View[0]=t,UniformBuffer._TempBufferInt32View[1]=i,UniformBuffer._TempBufferInt32View[2]=r,UniformBuffer._TempBufferInt32View[3]=s,this.updateUniform(e,UniformBuffer._TempBuffer,4)}_updateUIntForEffect(e,t,i=""){this._currentEffect.setUInt(e+i,t)}_updateUIntForUniform(e,t){UniformBuffer._TempBufferUInt32View[0]=t,this.updateUniform(e,UniformBuffer._TempBuffer,1)}_updateUInt2ForEffect(e,t,i,r=""){this._currentEffect.setUInt2(e+r,t,i)}_updateUInt2ForUniform(e,t,i){UniformBuffer._TempBufferUInt32View[0]=t,UniformBuffer._TempBufferUInt32View[1]=i,this.updateUniform(e,UniformBuffer._TempBuffer,2)}_updateUInt3ForEffect(e,t,i,r,s=""){this._currentEffect.setUInt3(e+s,t,i,r)}_updateUInt3ForUniform(e,t,i,r){UniformBuffer._TempBufferUInt32View[0]=t,UniformBuffer._TempBufferUInt32View[1]=i,UniformBuffer._TempBufferUInt32View[2]=r,this.updateUniform(e,UniformBuffer._TempBuffer,3)}_updateUInt4ForEffect(e,t,i,r,s,n=""){this._currentEffect.setUInt4(e+n,t,i,r,s)}_updateUInt4ForUniform(e,t,i,r,s){UniformBuffer._TempBufferUInt32View[0]=t,UniformBuffer._TempBufferUInt32View[1]=i,UniformBuffer._TempBufferUInt32View[2]=r,UniformBuffer._TempBufferUInt32View[3]=s,this.updateUniform(e,UniformBuffer._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}bindTexture(e,t){this._currentEffect._bindTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t){let i=this._buffers[t];if(i[0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,!0}return!1}dispose(){if(this._noUBO)return;let e=this._engine._uniformBuffers,t=e.indexOf(this);if(-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._features.trackUbosInFrame&&this._buffers)for(let e=0;e<this._buffers.length;++e){let t=this._buffers[e][0];this._engine._releaseBuffer(t)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}};UniformBuffer._UpdatedUbosInFrame={},UniformBuffer._MAX_UNIFORM_SIZE=256,UniformBuffer._TempBuffer=new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE),UniformBuffer._TempBufferInt32View=new Int32Array(UniformBuffer._TempBuffer.buffer),UniformBuffer._TempBufferUInt32View=new Uint32Array(UniformBuffer._TempBuffer.buffer)},524:function(e,t,i){i.d(t,{RD:function(){return Axis},T:function(){return n},c7:function(){return a}});var r,s,n,a,o=i(78);(r=n||(n={}))[r.LOCAL=0]="LOCAL",r[r.WORLD=1]="WORLD",r[r.BONE=2]="BONE";let Axis=class Axis{};Axis.X=new o.P(1,0,0),Axis.Y=new o.P(0,1,0),Axis.Z=new o.P(0,0,1),(s=a||(a={}))[s.X=0]="X",s[s.Y=1]="Y",s[s.Z=2]="Z"},2983:function(e,t,i){i.d(t,{HE:function(){return Color4},Wo:function(){return Color3},zZ:function(){return TmpColors}});var r=i(5762),s=i(9806),n=i(4254),a=i(3048);function colorChannelToLinearSpace(e){return Math.pow(e,s.Nn)}function colorChannelToLinearSpaceExact(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function colorChannelToGammaSpace(e){return Math.pow(e,s.zp)}function colorChannelToGammaSpaceExact(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Color3=class Color3{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return 397*(e=397*e^(255*this.g|0))^(255*this.b|0)}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Color3.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Color4(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return .3*this.r+.59*this.g+.11*this.b}multiply(e){return new Color3(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}scale(e){return new Color3(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this}clampToRef(e=0,t=1,i){return i.r=r.R.Clamp(this.r,e,t),i.g=r.R.Clamp(this.g,e,t),i.b=r.R.Clamp(this.b,e,t),this}add(e){return new Color3(this.r+e.r,this.g+e.g,this.b+e.b)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this}subtract(e){return new Color3(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,this}clone(){return new Color3(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}toHexString(){let e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+r.R.ToHex(e)+r.R.ToHex(t)+r.R.ToHex(i)}toHSV(){let e=new Color3;return this.toHSVToRef(e),e}toHSVToRef(e){let t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),n=Math.min(t,i,r),a=0,o=0,l=s-n;0!==s&&(o=l/s),s!=n&&(s==t?(a=(i-r)/l,i<r&&(a+=6)):s==i?a=(r-t)/l+2:s==r&&(a=(t-i)/l+4),a*=60),e.r=a,e.g=o,e.b=s}toLinearSpace(e=!1){let t=new Color3;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=colorChannelToLinearSpaceExact(this.r),e.g=colorChannelToLinearSpaceExact(this.g),e.b=colorChannelToLinearSpaceExact(this.b)):(e.r=colorChannelToLinearSpace(this.r),e.g=colorChannelToLinearSpace(this.g),e.b=colorChannelToLinearSpace(this.b)),this}toGammaSpace(e=!1){let t=new Color3;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=colorChannelToGammaSpaceExact(this.r),e.g=colorChannelToGammaSpaceExact(this.g),e.b=colorChannelToGammaSpaceExact(this.b)):(e.r=colorChannelToGammaSpace(this.r),e.g=colorChannelToGammaSpace(this.g),e.b=colorChannelToGammaSpace(this.b)),this}static HSVtoRGBToRef(e,t,i,r){let s=i*t,n=e/60,a=s*(1-Math.abs(n%2-1)),o=0,l=0,h=0;n>=0&&n<=1?(o=s,l=a):n>=1&&n<=2?(o=a,l=s):n>=2&&n<=3?(l=s,h=a):n>=3&&n<=4?(l=a,h=s):n>=4&&n<=5?(o=a,h=s):n>=5&&n<=6&&(o=s,h=a);let u=i-s;r.set(o+u,l+u,h+u)}static FromHSV(e,t,i){let r=new Color3(0,0,0);return Color3.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new Color3(0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16);return Color3.FromInts(t,i,r)}static FromArray(e,t=0){return new Color3(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 Color3(e/255,t/255,i/255)}static Lerp(e,t,i){let r=new Color3(0,0,0);return Color3.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n,c=e.r*o+i.r*l+t.r*h+r.r*u,d=e.g*o+i.g*l+t.g*h+r.g*u,p=e.b*o+i.b*l+t.b*h+r.b*u;return new Color3(c,d,p)}static Hermite1stDerivative(e,t,i,r,s){let n=Color3.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;n.r=(a-s)*6*e.r+(3*a-4*s+1)*t.r+(-a+s)*6*i.r+(3*a-2*s)*r.r,n.g=(a-s)*6*e.g+(3*a-4*s+1)*t.g+(-a+s)*6*i.g+(3*a-2*s)*r.g,n.b=(a-s)*6*e.b+(3*a-4*s+1)*t.b+(-a+s)*6*i.b+(3*a-2*s)*r.b}static Red(){return new Color3(1,0,0)}static Green(){return new Color3(0,1,0)}static Blue(){return new Color3(0,0,1)}static Black(){return new Color3(0,0,0)}static get BlackReadOnly(){return Color3._BlackReadOnly}static White(){return new Color3(1,1,1)}static Purple(){return new Color3(.5,0,.5)}static Magenta(){return new Color3(1,0,1)}static Yellow(){return new Color3(1,1,0)}static Gray(){return new Color3(.5,.5,.5)}static Teal(){return new Color3(0,1,1)}static Random(){return new Color3(Math.random(),Math.random(),Math.random())}};Color3._BlackReadOnly=Color3.Black();let Color4=class Color4{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}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 Color4.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 Color4(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new Color4(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 Color4(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=r.R.Clamp(this.r,e,t),i.g=r.R.Clamp(this.g,e,t),i.b=r.R.Clamp(this.b,e,t),i.a=r.R.Clamp(this.a,e,t),this}multiply(e){return new Color4(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 397*(e=397*(e=397*e^(255*this.g|0))^(255*this.b|0))^(255*this.a|0)}clone(){return new Color4(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,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}toHexString(e=!1){let t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+r.R.ToHex(t)+r.R.ToHex(i)+r.R.ToHex(s);let n=Math.round(255*this.a);return"#"+r.R.ToHex(t)+r.R.ToHex(i)+r.R.ToHex(s)+r.R.ToHex(n)}toLinearSpace(e=!1){let t=new Color4;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=colorChannelToLinearSpaceExact(this.r),e.g=colorChannelToLinearSpaceExact(this.g),e.b=colorChannelToLinearSpaceExact(this.b)):(e.r=colorChannelToLinearSpace(this.r),e.g=colorChannelToLinearSpace(this.g),e.b=colorChannelToLinearSpace(this.b)),e.a=this.a,this}toGammaSpace(e=!1){let t=new Color4;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=colorChannelToGammaSpaceExact(this.r),e.g=colorChannelToGammaSpaceExact(this.g),e.b=colorChannelToGammaSpaceExact(this.b)):(e.r=colorChannelToGammaSpace(this.r),e.g=colorChannelToGammaSpace(this.g),e.b=colorChannelToGammaSpace(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new Color4(0,0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return Color4.FromInts(t,i,r,s)}static Lerp(e,t,i){let r=new Color4(0,0,0,0);return Color4.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n,c=e.r*o+i.r*l+t.r*h+r.r*u,d=e.g*o+i.g*l+t.g*h+r.g*u,p=e.b*o+i.b*l+t.b*h+r.b*u,_=e.a*o+i.a*l+t.a*h+r.a*u;return new Color4(c,d,p,_)}static Hermite1stDerivative(e,t,i,r,s){let n=new Color4;return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;n.r=(a-s)*6*e.r+(3*a-4*s+1)*t.r+(-a+s)*6*i.r+(3*a-2*s)*r.r,n.g=(a-s)*6*e.g+(3*a-4*s+1)*t.g+(-a+s)*6*i.g+(3*a-2*s)*r.g,n.b=(a-s)*6*e.b+(3*a-4*s+1)*t.b+(-a+s)*6*i.b+(3*a-2*s)*r.b,n.a=(a-s)*6*e.a+(3*a-4*s+1)*t.a+(-a+s)*6*i.a+(3*a-2*s)*r.a}static FromColor3(e,t=1){return new Color4(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Color4(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new Color4(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===3*t){let t=[];for(let i=0;i<e.length;i+=3){let r=i/3*4;t[r]=e[i],t[r+1]=e[i+1],t[r+2]=e[i+2],t[r+3]=1}return t}return e}};let TmpColors=class TmpColors{};TmpColors.Color3=n.B.BuildArray(3,Color3.Black),TmpColors.Color4=n.B.BuildArray(3,()=>new Color4(0,0,0,0)),(0,a.H)("BABYLON.Color3",Color3),(0,a.H)("BABYLON.Color4",Color4)},9806:function(e,t,i){i.d(t,{Nn:function(){return s},Q_:function(){return n},kn:function(){return a},zp:function(){return r}});let r=1/2.2,s=2.2,n=(1+Math.sqrt(5))/2,a=.001},2975:function(e,t,i){i.d(t,{i:function(){return Frustum}});var r=i(1564);let Frustum=class Frustum{static GetPlanes(e){let t=[];for(let e=0;e<6;e++)t.push(new r.J(0,0,0,0));return Frustum.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){let 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){let 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){let 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){let 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){let 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){let 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){Frustum.GetNearPlaneToRef(e,t[0]),Frustum.GetFarPlaneToRef(e,t[1]),Frustum.GetLeftPlaneToRef(e,t[2]),Frustum.GetRightPlaneToRef(e,t[3]),Frustum.GetTopPlaneToRef(e,t[4]),Frustum.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(0>t[i].dotCoordinate(e))return!1;return!0}}},7383:function(e,t,i){i.d(t,{k:function(){return extractMinAndMax},y:function(){return extractMinAndMaxIndexed}});var r=i(9956),s=i(78),n=i(1760);let MathHelpers=class MathHelpers{static extractMinAndMaxIndexed(e,t,i,r,s,n){for(let a=i;a<i+r;a++){let i=3*t[a],r=e[i],o=e[i+1],l=e[i+2];s.minimizeInPlaceFromFloats(r,o,l),n.maximizeInPlaceFromFloats(r,o,l)}}static extractMinAndMax(e,t,i,r,s,n){for(let a=t,o=t*r;a<t+i;a++,o+=r){let t=e[o],i=e[o+1],r=e[o+2];s.minimizeInPlaceFromFloats(t,i,r),n.maximizeInPlaceFromFloats(t,i,r)}}};function extractMinAndMaxIndexed(e,t,i,r,n=null){let a=new s.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new s.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return MathHelpers.extractMinAndMaxIndexed(e,t,i,r,a,o),n&&(a.x-=a.x*n.x+n.y,a.y-=a.y*n.x+n.y,a.z-=a.z*n.x+n.y,o.x+=o.x*n.x+n.y,o.y+=o.y*n.x+n.y,o.z+=o.z*n.x+n.y),{minimum:a,maximum:o}}function extractMinAndMax(e,t,i,r=null,n){let a=new s.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new s.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return n||(n=3),MathHelpers.extractMinAndMax(e,t,i,n,a,o),r&&(a.x-=a.x*r.x+r.y,a.y-=a.y*r.x+r.y,a.z-=a.z*r.x+r.y,o.x+=o.x*r.x+r.y,o.y+=o.y*r.x+r.y,o.z+=o.z*r.x+r.y),{minimum:a,maximum:o}}(0,r.gn)([n.G6.filter((...[e,t])=>!Array.isArray(e)&&!Array.isArray(t))],MathHelpers,"extractMinAndMaxIndexed",null),(0,r.gn)([n.G6.filter((...[e])=>!Array.isArray(e))],MathHelpers,"extractMinAndMax",null)},1564:function(e,t,i){i.d(t,{J:function(){return Plane}});var r=i(78);let Plane=class Plane{constructor(e,t,i,s){this.normal=new r.P(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Plane(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){return 397*this.normal.getHashCode()^(0|this.d)}normalize(){let e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),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){let t=Plane._TmpMatrix;e.invertToRef(t);let i=t.m,r=this.normal.x,s=this.normal.y,n=this.normal.z,a=this.d,o=r*i[0]+s*i[1]+n*i[2]+a*i[3],l=r*i[4]+s*i[5]+n*i[6]+a*i[7],h=r*i[8]+s*i[9]+n*i[10]+a*i[11],u=r*i[12]+s*i[13]+n*i[14]+a*i[15];return new Plane(o,l,h,u)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){let r;let s=t.x-e.x,n=t.y-e.y,a=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,u=n*h-a*l,c=a*o-s*h,d=s*l-n*o,p=Math.sqrt(u*u+c*c+d*d);return r=0!==p?1/p:0,this.normal.x=u*r,this.normal.y=c*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){let i=r.P.Dot(this.normal,e);return i<=t}signedDistanceTo(e){return r.P.Dot(e,this.normal)+this.d}static FromArray(e){return new Plane(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){let r=new Plane(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){let i=new Plane(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){let s=-(t.x*e.x+t.y*e.y+t.z*e.z);return r.P.Dot(i,t)+s}};Plane._TmpMatrix=r.y3.Identity()},5762:function(e,t,i){i.d(t,{R:function(){return Scalar}});let Scalar=class Scalar{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){let 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=Scalar.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){let i=Scalar.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let r=Scalar.Clamp(i);return t*(r=-2*r*r*r+3*r*r)+e*(1-r)}static MoveTowards(e,t,i){return Math.abs(t-e)<=i?t:e+Scalar.Sign(t-e)*i}static MoveTowardsAngle(e,t,i){let r=Scalar.DeltaAngle(e,t),s=0;return-i<r&&r<i?s=t:(t=e+r,s=Scalar.MoveTowards(e,t,i)),s}static Lerp(e,t,i){return e+(t-e)*i}static LerpAngle(e,t,i){let r=Scalar.Repeat(t-e,360);return r>180&&(r-=360),e+r*Scalar.Clamp(i)}static InverseLerp(e,t,i){return e!=t?Scalar.Clamp((i-e)/(t-e)):0}static Hermite(e,t,i,r,s){let n=s*s,a=s*n;return e*(2*a-3*n+1)+i*(-2*a+3*n)+t*(a-2*n+s)+r*(a-n)}static Hermite1stDerivative(e,t,i,r,s){let n=s*s;return(n-s)*6*e+(3*n-4*s+1)*t+(-n+s)*6*i+(3*n-2*s)*r}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-=Scalar.TwoPi*Math.floor((e+Math.PI)/Scalar.TwoPi)}static HCF(e,t){let i=e%t;return 0===i?t:Scalar.HCF(t,i)}};Scalar.TwoPi=2*Math.PI},6329:function(e,t,i){i.d(t,{l:function(){return Viewport}});let Viewport=class Viewport{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new Viewport(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 Viewport(this.x,this.y,this.width,this.height)}}},998:function(e,t,i){i.d(t,{M:function(){return WebGLDataBuffer}});var r=i(9185);let WebGLDataBuffer=class WebGLDataBuffer extends r.h{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},7042:function(e,t,i){i.d(t,{x:function(){return AbstractMesh}});var r=i(4800),s=i(6540),n=i(78),a=i(8906),o=i(1295),l=i(2696),h=i(8061),u=i(2248),c=i(5681),d=i(9691),p=i(5790),_=i(6131),f=i(7383),m=i(2983),g=i(9806),v=i(524),x=i(3048);let _FacetDataStorage=class _FacetDataStorage{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=n.P.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}};let _InternalAbstractMeshDataInfo=class _InternalAbstractMeshDataInfo{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new _FacetDataStorage,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}};let AbstractMesh=class AbstractMesh 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;let 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){let 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 _InternalAbstractMeshDataInfo,this._waitingMaterialId=null,this.cullingStrategy=AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new r.y$,this.onCollisionPositionChangeObservable=new r.y$,this.onMaterialChangedObservable=new r.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 n.P(.5,1,.5),this.ellipsoidOffset=new n.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=[],this._unIndexed=!1,this._lightSources=[],this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new r.y$,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>a.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 d.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){let 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);let i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode]+", 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){return this.actionManager&&(t||this.actionManager.isRecursive)&&(!e||this.actionManager.hasSpecificTrigger(e))?this.actionManager: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(let e of this.subMeshes)e._rebuild()}_resyncLightSources(){for(let e of(this._lightSources.length=0,this.getScene().lights))e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){let t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(let e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){let i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(let t of this.subMeshes)for(let i=0;i<t._drawWrappers.length;++i){let r=t._drawWrappers[i];r&&r.defines&&r.defines.markAllAsDirty&&e(r.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty(t=>t.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(let t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,r){return this}updateVerticesData(e,t,i,r){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){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 c.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(o.o.MatricesIndicesKind)&&this.isVerticesDataPresent(o.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){let r=new n.y3,s=this.rotationQuaternion?this.rotationQuaternion:n._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z);s.toRotationMatrix(r);let a=n.P.Zero(),o=this.definedFacingForward?-1:1;return n.P.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,r,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){let r=this.definedFacingForward?1:-1;return new n.P(e*r,t,i*r)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){let i=(0,f.k)(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new c.j(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t<this.subMeshes.length;t++)this.subMeshes[t].refreshBoundingInfo(e);this._updateBoundingInfo()}_getData(e=!1,t=!1,i,r=o.o.PositionKind){if((i=null!=i?i:this.getVerticesData(r).slice())&&t&&this.morphTargetManager){let e=0,t=0;for(let s=0;s<i.length;s++){for(let e=0;e<this.morphTargetManager.numTargets;e++){let t=this.morphTargetManager.getTarget(e),r=t.influence;if(r>0){let e=t.getPositions();e&&(i[s]+=(e[s]-i[s])*r)}}if(e++,r===o.o.PositionKind&&this._positions&&3===e){e=0;let r=3*t;this._positions[t++].copyFromFloats(i[r],i[r+1],i[r+2])}}}if(i&&e&&this.skeleton){let e=this.getVerticesData(o.o.MatricesIndicesKind),t=this.getVerticesData(o.o.MatricesWeightsKind);if(t&&e){let s=this.numBoneInfluencers>4,a=s?this.getVerticesData(o.o.MatricesIndicesExtraKind):null,l=s?this.getVerticesData(o.o.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this),u=n.jp.Vector3[0],c=n.jp.Matrix[0],d=n.jp.Matrix[1],p=0;for(let _=0;_<i.length;_+=3,p+=4){let f,m;for(c.reset(),f=0;f<4;f++)(m=t[p+f])>0&&(n.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*e[p+f]),m,d),c.addToSelf(d));if(s)for(f=0;f<4;f++)(m=l[p+f])>0&&(n.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*a[p+f]),m,d),c.addToSelf(d));r===o.o.NormalKind?n.P.TransformNormalFromFloatsToRef(i[_],i[_+1],i[_+2],c,u):n.P.TransformCoordinatesFromFloatsToRef(i[_],i[_+1],i[_+2],c,u),u.toArray(i,_),r===o.o.PositionKind&&this._positions&&this._positions[_/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,o.o.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,o.o.PositionKind)}_getPositionData(e,t){var i;let r=this.getVerticesData(o.o.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),r&&(e&&this.skeleton||t&&this.morphTargetManager)){if(r=r.slice(),this._generatePointsArray(),this._positions){let e=this._positions;this._internalAbstractMeshDataInfo._positions=Array(e.length);for(let t=0;t<e.length;t++)this._internalAbstractMeshDataInfo._positions[t]=(null===(i=e[t])||void 0===i?void 0:i.clone())||new n.P}return this.getPositionData(e,t,r)}return r}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new c.j(n.P.Zero(),n.P.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;let t=this.subMeshes.length;for(let i=0;i<t;i++){let r=this.subMeshes[i];(t>1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){let r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(let i of this.getChildMeshes())if(i.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){let t=this.getAbsolutePosition();t.addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);let i=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=i.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];let i=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let s=i;s<r;s++)e._lastColliderWorldVertices.push(n.P.TransformCoordinates(this._positions[s],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),(null===(r=e.getMaterial())||void 0===r?void 0:r.fillMode)===7),this}_processCollisionsForSubMeshes(e,t){let i=this._scene.getCollidingSubMeshCandidates(this,e),r=i.length;for(let s=0;s<r;s++){let n=i.data[s];(!(r>1)||n._checkCollision(e))&&this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;let t=n.jp.Matrix[0],i=n.jp.Matrix[1];return n.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,r=!1,s,a=!1){let o=new u.p,l=this.getClassName(),h="InstancedLinesMesh"===l||"LinesMesh"===l||"GreasedLineMesh"===l?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(c.boundingSphere,h)||!e.intersectsBox(c.boundingBox,h)))return o;if(r)return o.hit=!a,o.pickedMesh=a?null:this,o.distance=a?0:n.P.Distance(e.origin,c.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let d=null,p=this._scene.getIntersectingSubMeshCandidates(this,e),_=p.length,f=!1;for(let e=0;e<_;e++){let t=p.data[e],i=t.getMaterial();if(i&&(7==i.fillMode||0==i.fillMode||1==i.fillMode||2==i.fillMode||4==i.fillMode)){f=!0;break}}if(!f)return o.hit=!0,o.pickedMesh=this,o.distance=n.P.Distance(e.origin,c.boundingSphere.center),o.subMeshId=-1,o;for(let r=0;r<_;r++){let s=p.data[r];if(_>1&&!s.canIntersects(e))continue;let n=s.intersects(e,this._positions,this.getIndices(),t,i);if(n&&(t||!d||n.distance<d.distance)&&((d=n).subMeshId=r,t))break}if(d){let t=null!=s?s:this.getWorldMatrix(),i=n.jp.Vector3[0],r=n.jp.Vector3[1];n.P.TransformCoordinatesToRef(e.origin,t,i),e.direction.scaleToRef(d.distance,r);let a=n.P.TransformNormal(r,t),l=a.addInPlace(i);o.hit=!0,o.distance=n.P.Distance(i,l),o.pickedPoint=l,o.pickedMesh=this,o.bu=d.bu||0,o.bv=d.bv||0,o.subMeshFaceId=d.faceId,o.faceId=d.faceId+p.data[d.subMeshId].indexStart/(-1!==this.getClassName().indexOf("LinesMesh")?2:3),o.subMeshId=d.subMeshId}return o}clone(e,t,i){return null}releaseSubMeshes(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=[];return this}dispose(e,t=!1){let i;let r=this.getScene();for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),r.freeActiveMeshes(),r.freeRenderingGroups(),r.renderingManager.maintainStateBetweenFrames&&r.renderingManager.restoreDispachedFlags(),void 0!==this.actionManager&&null!==this.actionManager&&(this._scene.meshes.some(e=>e!==this&&e.actionManager===this.actionManager)||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i<this._intersectionsInProgress.length;i++){let e=this._intersectionsInProgress[i],t=e._intersectionsInProgress.indexOf(this);e._intersectionsInProgress.splice(t,1)}this._intersectionsInProgress.length=0;let s=r.lights;s.forEach(e=>{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),-1!==(t=e.excludedMeshes.indexOf(this))&&e.excludedMeshes.splice(t,1);let i=e.getShadowGenerators();if(i){let e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){let e=i.value,r=e.getShadowMap();r&&r.renderList&&-1!==(t=r.renderList.indexOf(this))&&r.renderList.splice(t,1)}}}),("InstancedMesh"!==this.getClassName()||"InstancedLinesMesh"!==this.getClassName())&&this.releaseSubMeshes();let n=r.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),r.removeMesh(this),this._parentContainer){let e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i<r.particleSystems.length;i++)r.particleSystems[i].emitter===this&&(r.particleSystems[i].dispose(),i--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}_initFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=[]),e.facetPositions||(e.facetPositions=[]),e.facetPartitioning||(e.facetPartitioning=[]),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=n.P.Zero(),e.facetPositions[t]=n.P.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();let t=this.getVerticesData(o.o.PositionKind),i=this.getIndices(),r=this.getVerticesData(o.o.NormalKind),s=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,i instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(i);else if(i instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(i);else{let t=!1;for(let e=0;e<i.length;e++)if(i[e]>65535){t=!0;break}t?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){let t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:n.P.Zero()}e.depthSortedFacets=[];for(let t=0;t<e.facetNb;t++){let i={ind:3*t,sqDistance:0};e.depthSortedFacets.push(i)}e.invertedMatrix=n.y3.Identity(),e.facetDepthSortOrigin=n.P.Zero()}e.bbSize.x=s.maximum.x-s.minimum.x>g.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 a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),n.P.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&l.x.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);let t=e.depthSortedIndices.length/3|0;for(let r=0;r<t;r++){let t=e.depthSortedFacets[r].ind;e.depthSortedIndices[3*r]=i[t],e.depthSortedIndices[3*r+1]=i[t+1],e.depthSortedIndices[3*r+2]=i[t+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this}getFacetLocalNormals(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals}getFacetLocalPositions(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions}getFacetLocalPartitioning(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning}getFacetPosition(e){let t=n.P.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){let i=this.getFacetLocalPositions()[e],r=this.getWorldMatrix();return n.P.TransformCoordinatesToRef(i,r,t),this}getFacetNormal(e){let t=n.P.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){let i=this.getFacetLocalNormals()[e];return n.P.TransformNormalToRef(i,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,i){let r=this.getBoundingInfo(),s=this._internalAbstractMeshDataInfo._facetData,n=Math.floor((e-r.minimum.x*s.partitioningBBoxRatio)*s.subDiv.X*s.partitioningBBoxRatio/s.bbSize.x),a=Math.floor((t-r.minimum.y*s.partitioningBBoxRatio)*s.subDiv.Y*s.partitioningBBoxRatio/s.bbSize.y),o=Math.floor((i-r.minimum.z*s.partitioningBBoxRatio)*s.subDiv.Z*s.partitioningBBoxRatio/s.bbSize.z);return n<0||n>s.subDiv.max||a<0||a>s.subDiv.max||o<0||o>s.subDiv.max?null:s.facetPartitioning[n+s.subDiv.max*a+s.subDiv.max*s.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,a=!0){let o=this.getWorldMatrix(),l=n.jp.Matrix[5];o.invertToRef(l);let h=n.jp.Vector3[8];n.P.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);let u=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,r,s,a);return r&&n.P.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),u}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,n=!0){let a,o,l,h=null,u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=0,v=this.getFacetLocalPositions(),x=this.getFacetLocalNormals(),T=this.getFacetsAtLocalCoordinates(e,t,i);if(!T)return null;let S=Number.MAX_VALUE,C=S;for(let E=0;E<T.length;E++)o=x[a=T[E]],p=(e-(l=v[a]).x)*o.x+(t-l.y)*o.y+(i-l.z)*o.z,(!s||s&&n&&p>=0||s&&!n&&p<=0)&&(p=o.x*l.x+o.y*l.y+o.z*l.z,_=-(o.x*e+o.y*t+o.z*i-p)/(o.x*o.x+o.y*o.y+o.z*o.z),f=e+o.x*_,m=t+o.y*_,g=i+o.z*_,(C=(u=f-e)*u+(c=m-t)*c+(d=g-i)*d)<S&&(S=C,h=a,r&&(r.x=f,r.y=m,r.z=g)));return h}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=[],e.facetNormals=[],e.facetPartitioning=[],e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,i=!1){return this}createNormals(e){let t;let i=this.getVerticesData(o.o.PositionKind),r=this.getIndices();return t=this.isVerticesDataPresent(o.o.NormalKind)?this.getVerticesData(o.o.NormalKind):[],l.x.ComputeNormals(i,r,t,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(o.o.NormalKind,t,e),this}alignWithNormal(e,t){t||(t=v.RD.Y);let i=n.jp.Vector3[0],r=n.jp.Vector3[1];return n.P.CrossToRef(t,e,r),n.P.CrossToRef(e,r,i),this.rotationQuaternion?n._f.RotationQuaternionFromAxisToRef(i,e,r,this.rotationQuaternion):n.P.RotationFromAxisToRef(i,e,r,this.rotation),this}_checkOcclusionQuery(){return!1}disableEdgesRendering(){throw(0,_.S)("EdgesRenderer")}enableEdgesRendering(e,t,i){throw(0,_.S)("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter(e=>e.emitter===this)}};AbstractMesh.OCCLUSION_TYPE_NONE=0,AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC=1,AbstractMesh.OCCLUSION_TYPE_STRICT=2,AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,AbstractMesh.CULLINGSTRATEGY_STANDARD=0,AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,(0,x.H)("BABYLON.AbstractMesh",AbstractMesh)},1687:function(e,t,i){i.d(t,{Z:function(){return Geometry}});var r=i(78),s=i(2983),n=i(2696),a=i(1295),o=i(1091),l=i(2697),h=i(5681),u=i(5132),c=i(1803),d=i(7383),p=i(6030),_=i(6705);let Geometry=class Geometry{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){let t=new Geometry(Geometry.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null){if(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)return;this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0}_rebuild(){for(let e in this._vertexArrayObjects&&(this._vertexArrayObjects={}),0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),this._vertexBuffers){let t=this._vertexBuffers[e];t._rebuild()}}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,r){i&&Array.isArray(t)&&(t=new Float32Array(t));let s=new a.o(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:r,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){let s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;let n=this._meshes,o=n.length;if(s===a.o.PositionKind){this._totalVertices=null!=t?t:e.totalVertices,this._updateExtend(e.getFloatData()),this._resetPointsArrayCache();let i=this._extend&&this._extend.minimum||new r.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new r.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e<o;e++){let t=n[e];t.buildBoundingInfo(i,s),t._createGlobalSubMesh(t.isUnIndexed),t.computeWorldMatrix(!0),t.synchronizeInstances()}}this._notifyUpdate(s)}updateVerticesDataDirectly(e,t,i,r=!1){let s=this.getVertexBuffer(e);s&&(s.updateDirectly(t,i,r),this._notifyUpdate(e))}updateVerticesData(e,t,i=!1){let r=this.getVertexBuffer(e);r&&(r.update(t),e===a.o.PositionKind&&this._updateBoundingInfo(i,t),this._notifyUpdate(e))}_updateBoundingInfo(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e){let e=this._meshes;for(let t of e){t.hasBoundingInfo?t.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):t.buildBoundingInfo(this._extend.minimum,this._extend.maximum);let e=t.subMeshes;for(let t of e)t.refreshBoundingInfo()}}}_bind(e,t,i,r){if(!e)return;void 0===t&&(t=this._indexBuffer);let s=this.getVertexBuffers();if(!s)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!r){this._engine.bindBuffers(s,t,e,i);return}let n=r||this._vertexArrayObjects;n[e.key]||(n[e.key]=this._engine.recordVertexArrayObject(s,t,e,i)),this._engine.bindVertexArrayObject(n[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,i){let r=this.getVertexBuffer(e);return r?r.getFloatData(this._totalVertices,i||t&&1!==this._meshes.length):null}isVertexBufferUpdatable(e){let t=this._vertexBuffers[e];return!!t&&t.isUpdatable()}getVertexBuffer(e){return this.isReady()?this._vertexBuffers[e]:null}getVertexBuffers(){return this.isReady()?this._vertexBuffers:null}isVerticesDataPresent(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}getVerticesDataKinds(){let e;let t=[];if(!this._vertexBuffers&&this._delayInfo)for(e in this._delayInfo)t.push(e);else for(e in this._vertexBuffers)t.push(e);return t}updateIndices(e,t,i=!1){if(this._indexBuffer){if(this._indexBufferIsUpdatable){let r=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),r)for(let e of this._meshes)e._createGlobalSubMesh(!0)}else this.setIndices(e,null,!0)}}setIndices(e,t=null,i=!1){for(let r of(this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i)),void 0!=t&&(this._totalVertices=t),this._meshes))r._createGlobalSubMesh(!0),r.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;let i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){let i=this._meshes,r=i.indexOf(e);-1!==r&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;let t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();let i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(a.o.PositionKind)))return;this._extend=(0,d.k)(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){let t=this._meshes.length;for(let i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===a.o.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){for(let t of(this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects(),this._meshes))t._markSubMeshesAsAttributesDirty()}load(e,t){if(2!==this.delayLoadState){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);let r=this._meshes,s=r.length;for(let e=0;e<s;e++)this._applyToMesh(r[e]);t&&t()},void 0,!0))}toLeftHanded(){let e=this.getIndices(!1);if(null!=e&&e.length>0){for(let t=0;t<e.length;t+=3){let i=e[t+0];e[t+0]=e[t+2],e[t+2]=i}this.setIndices(e)}let t=this.getVerticesData(a.o.PositionKind,!1);if(null!=t&&t.length>0){for(let e=0;e<t.length;e+=3)t[e+2]=-t[e+2];this.setVerticesData(a.o.PositionKind,t,!1)}let i=this.getVerticesData(a.o.NormalKind,!1);if(null!=i&&i.length>0){for(let e=0;e<i.length;e+=3)i[e+2]=-i[e+2];this.setVerticesData(a.o.NormalKind,i,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;let e=this.getVerticesData(a.o.PositionKind);if(!e||0===e.length)return!1;for(let t=3*this._positionsCache.length,i=this._positionsCache.length;t<e.length;t+=3,++i)this._positionsCache[i]=r.P.FromArray(e,t);for(let t=0,i=0;t<e.length;t+=3,++i)this._positionsCache[i].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0}isDisposed(){return this._isDisposed}_disposeVertexArrayObjects(){if(this._vertexArrayObjects){for(let e in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);this._vertexArrayObjects={};let e=this._meshes,t=e.length;for(let i=0;i<t;i++)e[i]._invalidateInstanceVertexArrayObject()}}dispose(){let e;let t=this._meshes,i=t.length;for(e=0;e<i;e++)this.releaseForMesh(t[e]);for(let e in this._meshes.length=0,this._disposeVertexArrayObjects(),this._vertexBuffers)this._vertexBuffers[e].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=0,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){let e=this._parentContainer.geometries.indexOf(this);e>-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){let t;let i=new n.x;i.indices=[];let r=this.getIndices();if(r)for(let e=0;e<r.length;e++)i.indices.push(r[e]);let s=!1,a=!1;for(t in this._vertexBuffers){let e=this.getVerticesData(t);if(e&&(e instanceof Float32Array?i.set(new Float32Array(e),t):i.set(e.slice(0),t),!a)){let e=this.getVertexBuffer(t);e&&(a=!(s=e.isUpdatable()))}}let o=new Geometry(e,this._scene,i,s);for(t in o.delayLoadState=this.delayLoadState,o.delayLoadingFile=this.delayLoadingFile,o._delayLoadingFunction=this._delayLoadingFunction,this._delayInfo)o._delayInfo=o._delayInfo||[],o._delayInfo.push(t);return o._boundingInfo=new h.j(this._extend.minimum,this._extend.maximum),o}serialize(){let e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,c.$&&c.$.HasTags(this)&&(e.tags=c.$.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){for(let e in this._indices=[],this._resetPointsArrayCache(),this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){let e=this.serialize();return this.isVerticesDataPresent(a.o.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(a.o.PositionKind)),this.isVertexBufferUpdatable(a.o.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(a.o.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(a.o.NormalKind)),this.isVertexBufferUpdatable(a.o.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(a.o.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(a.o.TangentKind)),this.isVertexBufferUpdatable(a.o.TangentKind)&&(e.tangents._updatable=!0)),this.isVerticesDataPresent(a.o.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(a.o.UVKind)),this.isVertexBufferUpdatable(a.o.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(a.o.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(a.o.UV2Kind)),this.isVertexBufferUpdatable(a.o.UV2Kind)&&(e.uvs2._updatable=!0)),this.isVerticesDataPresent(a.o.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(a.o.UV3Kind)),this.isVertexBufferUpdatable(a.o.UV3Kind)&&(e.uvs3._updatable=!0)),this.isVerticesDataPresent(a.o.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(a.o.UV4Kind)),this.isVertexBufferUpdatable(a.o.UV4Kind)&&(e.uvs4._updatable=!0)),this.isVerticesDataPresent(a.o.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(a.o.UV5Kind)),this.isVertexBufferUpdatable(a.o.UV5Kind)&&(e.uvs5._updatable=!0)),this.isVerticesDataPresent(a.o.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(a.o.UV6Kind)),this.isVertexBufferUpdatable(a.o.UV6Kind)&&(e.uvs6._updatable=!0)),this.isVerticesDataPresent(a.o.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(a.o.ColorKind)),this.isVertexBufferUpdatable(a.o.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(a.o.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(a.o.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(a.o.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(a.o.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(a.o.MatricesWeightsKind)),this.isVertexBufferUpdatable(a.o.MatricesWeightsKind)&&(e.matricesWeights._updatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){let i=e._geometry;return i?i.copy(t):null}static RandomId(){return u.w1.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i<t.geometries.length;i++)if(t.geometries[i]._loadedUniqueId===e)return t.geometries[i];return null}static _ImportGeometry(e,t){let i=t.getScene(),r=e.geometryUniqueId,n=e.geometryId;if(r||n){let e=r?this._GetGeometryByLoadedUniqueId(r,i):i.getGeometryById(n);e&&e.applyToMesh(t)}else if(e instanceof ArrayBuffer){let i=t._binaryInfo;if(i.positionsAttrDesc&&i.positionsAttrDesc.count>0){let r=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(a.o.PositionKind,r,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){let r=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(a.o.NormalKind,r,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){let r=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(a.o.TangentKind,r,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){let r=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UVKind,r,!1)}if(i.uvs2AttrDesc&&i.uvs2AttrDesc.count>0){let r=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UV2Kind,r,!1)}if(i.uvs3AttrDesc&&i.uvs3AttrDesc.count>0){let r=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UV3Kind,r,!1)}if(i.uvs4AttrDesc&&i.uvs4AttrDesc.count>0){let r=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UV4Kind,r,!1)}if(i.uvs5AttrDesc&&i.uvs5AttrDesc.count>0){let r=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UV5Kind,r,!1)}if(i.uvs6AttrDesc&&i.uvs6AttrDesc.count>0){let r=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UV6Kind,r,!1)}if(i.colorsAttrDesc&&i.colorsAttrDesc.count>0){let r=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(a.o.ColorKind,r,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e<r.length;e++){let t=r[e];s.push(255&t),s.push((65280&t)>>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(a.o.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e<r.length;e++){let t=r[e];s.push(255&t),s.push((65280&t)>>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(a.o.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){let r=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(a.o.MatricesWeightsKind,r,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){let r=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(r,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){let r=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e<i.subMeshesAttrDesc.count;e++){let i=r[5*e+0],s=r[5*e+1],n=r[5*e+2],a=r[5*e+3],l=r[5*e+4];o.P.AddToMesh(i,s,n,a,l,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(a.o.PositionKind,e.positions,e.positions._updatable),t.setVerticesData(a.o.NormalKind,e.normals,e.normals._updatable),e.tangents&&t.setVerticesData(a.o.TangentKind,e.tangents,e.tangents._updatable),e.uvs&&t.setVerticesData(a.o.UVKind,e.uvs,e.uvs._updatable),e.uvs2&&t.setVerticesData(a.o.UV2Kind,e.uvs2,e.uvs2._updatable),e.uvs3&&t.setVerticesData(a.o.UV3Kind,e.uvs3,e.uvs3._updatable),e.uvs4&&t.setVerticesData(a.o.UV4Kind,e.uvs4,e.uvs4._updatable),e.uvs5&&t.setVerticesData(a.o.UV5Kind,e.uvs5,e.uvs5._updatable),e.uvs6&&t.setVerticesData(a.o.UV6Kind,e.uvs6,e.uvs6._updatable),e.colors&&t.setVerticesData(a.o.ColorKind,s.HE.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices){if(e.matricesIndices._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(a.o.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable);else{let i=[];for(let t=0;t<e.matricesIndices.length;t++){let r=e.matricesIndices[t];i.push(255&r),i.push((65280&r)>>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(a.o.MatricesIndicesKind,i,e.matricesIndices._updatable)}}if(e.matricesIndicesExtra){if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(a.o.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{let i=[];for(let t=0;t<e.matricesIndicesExtra.length;t++){let r=e.matricesIndicesExtra[t];i.push(255&r),i.push((65280&r)>>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(a.o.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}}e.matricesWeights&&(Geometry._CleanMatricesWeights(e,t),t.setVerticesData(a.o.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(a.o.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i<e.subMeshes.length;i++){let r=e.subMeshes[i];o.P.AddToMesh(r.materialIndex,r.verticesStart,r.verticesCount,r.indexStart,r.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),i.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){if(!l.Z.CleanBoneMatrixWeights)return;let i=0;if(!(e.skeletonId>-1))return;{let r=t.getScene().getLastSkeletonById(e.skeletonId);if(!r)return;i=r.bones.length}let r=t.getVerticesData(a.o.MatricesIndicesKind),s=t.getVerticesData(a.o.MatricesIndicesExtraKind),n=e.matricesWeights,o=e.matricesWeightsExtra,h=e.numBoneInfluencer,u=n.length;for(let e=0;e<u;e+=4){let t=0,a=-1;for(let i=0;i<4;i++){let r=n[e+i];t+=r,r<.001&&a<0&&(a=i)}if(o)for(let i=0;i<4;i++){let r=o[e+i];t+=r,r<.001&&a<0&&(a=i+4)}if((a<0||a>h-1)&&(a=h-1),t>.001){let i=1/t;for(let t=0;t<4;t++)n[e+t]*=i;if(o)for(let t=0;t<4;t++)o[e+t]*=i}else a>=4?(o[e+a-4]=1-t,s[e+a-4]=i):(n[e+a]=1-t,r[e+a]=i)}t.setVerticesData(a.o.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(a.o.MatricesIndicesExtraKind,s)}static Parse(e,t,i){let s=new Geometry(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,c.$&&c.$.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new h.j(r.P.FromArray(e.boundingBoxMinimum),r.P.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(a.o.UVKind),e.hasUVs2&&s._delayInfo.push(a.o.UV2Kind),e.hasUVs3&&s._delayInfo.push(a.o.UV3Kind),e.hasUVs4&&s._delayInfo.push(a.o.UV4Kind),e.hasUVs5&&s._delayInfo.push(a.o.UV5Kind),e.hasUVs6&&s._delayInfo.push(a.o.UV6Kind),e.hasColors&&s._delayInfo.push(a.o.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(a.o.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(a.o.MatricesWeightsKind),s._delayLoadingFunction=n.x.ImportVertexData):n.x.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}},2696:function(e,t,i){i.d(t,{D:function(){return VertexDataMaterialInfo},x:function(){return VertexData}});var r=i(9956),s=i(78),n=i(1295),a=i(6131),o=i(2983),l=i(9626),h=i(1760),u=i(7521),c=i(3477),d=i(1091);let VertexDataMaterialInfo=class VertexDataMaterialInfo{};let VertexData=class VertexData{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=(0,u.vp)(this._applyToCoroutine.bind(this)),this.uniqueId=VertexData._UniqueIDGenerator,VertexData._UniqueIDGenerator++}set(e,t){switch(e.length||l.Y.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case n.o.PositionKind:this.positions=e;break;case n.o.NormalKind:this.normals=e;break;case n.o.TangentKind:this.tangents=e;break;case n.o.UVKind:this.uvs=e;break;case n.o.UV2Kind:this.uvs2=e;break;case n.o.UV3Kind:this.uvs3=e;break;case n.o.UV4Kind:this.uvs4=e;break;case n.o.UV5Kind:this.uvs5=e;break;case n.o.UV6Kind:this.uvs6=e;break;case n.o.ColorKind:this.colors=e;break;case n.o.MatricesIndicesKind:this.matricesIndices=e;break;case n.o.MatricesWeightsKind:this.matricesWeights=e;break;case n.o.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case n.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){if(this.positions&&(e.setVerticesData(n.o.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(n.o.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(n.o.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(n.o.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(n.o.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(n.o.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(n.o.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(n.o.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(n.o.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(n.o.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(n.o.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(n.o.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1)for(let t of(e.subMeshes=[],this.materialInfos))new d.P(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,e);return this}_update(e,t,i){return this.positions&&e.updateVerticesData(n.o.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(n.o.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(n.o.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(n.o.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(n.o.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(n.o.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(n.o.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(n.o.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(n.o.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(n.o.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(n.o.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(n.o.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){let n=s.jp.Vector3[0],a=s.jp.Vector3[1];for(let o=i;o<i+r;o+=3)s.P.FromArrayToRef(e,o,n),s.P.TransformCoordinatesToRef(n,t,a),e[o]=a.x,e[o+1]=a.y,e[o+2]=a.z}static _TransformVector3Normals(e,t,i=0,r=e.length){let n=s.jp.Vector3[0],a=s.jp.Vector3[1];for(let o=i;o<i+r;o+=3)s.P.FromArrayToRef(e,o,n),s.P.TransformNormalToRef(n,t,a),e[o]=a.x,e[o+1]=a.y,e[o+2]=a.z}static _TransformVector4Normals(e,t,i=0,r=e.length){let n=s.jp.Vector4[0],a=s.jp.Vector4[1];for(let o=i;o<i+r;o+=4)s.Lt.FromArrayToRef(e,o,n),s.Lt.TransformNormalToRef(n,t,a),e[o]=a.x,e[o+1]=a.y,e[o+2]=a.z,e[o+3]=a.w}static _FlipFaces(e,t=0,i=e.length){for(let r=t;r<t+i;r+=3){let t=e[r+1];e[r+1]=e[r+2],e[r+2]=t}}transform(e){let t=0>e.determinant();return this.positions&&VertexData._TransformVector3Coordinates(this.positions,e),this.normals&&VertexData._TransformVector3Normals(this.normals,e),this.tangents&&VertexData._TransformVector4Normals(this.tangents,e),t&&this.indices&&VertexData._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];let e=[];for(let t of this.materialInfos){let i=new VertexData;if(this.positions&&(i.positions=this.positions.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.normals&&(i.normals=this.normals.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.tangents&&(i.tangents=this.tangents.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.colors&&(i.colors=this.colors.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.uvs&&(i.uvs=this.uvs.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs2&&(i.uvs2=this.uvs2.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs3&&(i.uvs3=this.uvs3.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs4&&(i.uvs4=this.uvs4.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs5&&(i.uvs5=this.uvs5.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs6&&(i.uvs6=this.uvs6.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.indices){i.indices=[];for(let e=t.indexStart;e<t.indexStart+t.indexCount;e++)i.indices.push(this.indices[e]-t.verticesStart)}let r=new VertexDataMaterialInfo;r.indexStart=0,r.indexCount=i.indices?i.indices.length:0,r.materialIndex=t.materialIndex,r.verticesStart=0,r.verticesCount=(i.positions?i.positions.length:0)/3,i.materialInfos=[r],e.push(i)}return e}merge(e,t=!1,i=!1,r=!1,s=!1){let n=Array.isArray(e)?e.map(e=>({vertexData:e})):[{vertexData:e}];return(0,u.s3)(this._mergeCoroutine(void 0,n,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,a=!1,o=!1){var l,h,u,c;this._validate();let d=t.map(e=>e.vertexData),p=this;for(let e of d)if(e){if(e._validate(),o)!this.normals!=!e.normals&&(this.normals?e.normals=new Float32Array(e.positions.length):this.normals=new Float32Array(this.positions.length)),!this.tangents!=!e.tangents&&(this.tangents?e.tangents=new Float32Array(e.positions.length/3*4):this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs!=!e.uvs&&(this.uvs?e.uvs=new Float32Array(e.positions.length/3*2):this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2!=!e.uvs2&&(this.uvs2?e.uvs2=new Float32Array(e.positions.length/3*2):this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3!=!e.uvs3&&(this.uvs3?e.uvs3=new Float32Array(e.positions.length/3*2):this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4!=!e.uvs4&&(this.uvs4?e.uvs4=new Float32Array(e.positions.length/3*2):this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5!=!e.uvs5&&(this.uvs5?e.uvs5=new Float32Array(e.positions.length/3*2):this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6!=!e.uvs6&&(this.uvs6?e.uvs6=new Float32Array(e.positions.length/3*2):this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors!=!e.colors&&(this.colors?(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)):(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1))),!this.matricesIndices!=!e.matricesIndices&&(this.matricesIndices?e.matricesIndices=new Float32Array(e.positions.length/3*4):this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights!=!e.matricesWeights&&(this.matricesWeights?e.matricesWeights=new Float32Array(e.positions.length/3*4):this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra!=!e.matricesIndicesExtra&&(this.matricesIndicesExtra?e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4):this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra!=!e.matricesWeightsExtra&&(this.matricesWeightsExtra?e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4):this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4));else if(!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let i=0,r=0,s=0,n=[],a=null,o=[];for(let t of this.splitBasedOnMaterialID())o.push({vertexData:t,transform:e});for(let e of t)if(e.vertexData)for(let t of e.vertexData.splitBasedOnMaterialID())o.push({vertexData:t,transform:e.transform});for(let e of(o.sort((e,t)=>{let i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,r=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>r?1:i===r?0:-1}),o)){let t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,a&&a.materialIndex===i)a.indexCount+=t.indices.length,a.verticesCount+=t.positions.length/3;else{let e=new VertexDataMaterialInfo;e.materialIndex=i,e.indexStart=r,e.indexCount=t.indices.length,e.verticesStart=s,e.verticesCount=t.positions.length/3,n.push(e),a=e}r+=t.indices.length,s+=t.positions.length/3}let l=o.splice(0,1)[0];p=l.vertexData,e=l.transform,d=o.map(e=>e.vertexData),t=o,this.materialInfos=n}let _=d.reduce((e,t)=>{var i,r;return e+(null!==(r=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==r?r:0)},null!==(h=null===(l=p.indices)||void 0===l?void 0:l.length)&&void 0!==h?h:0),f=s||d.some(e=>e.indices===p.indices),m=f?null===(u=p.indices)||void 0===u?void 0:u.slice():p.indices;if(_>0){let s=null!==(c=null==m?void 0:m.length)&&void 0!==c?c:0;if(m||(m=Array(_)),m.length!==_){if(Array.isArray(m))m.length=_;else{let e=i||m instanceof Uint32Array?new Uint32Array(_):new Uint16Array(_);e.set(m),m=e}e&&0>e.determinant()&&VertexData._FlipFaces(m,0,s)}let n=p.positions?p.positions.length/3:0;for(let{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t<e.indices.length;t++)m[s+t]=e.indices[t]+n;i&&0>i.determinant()&&VertexData._FlipFaces(m,s,e.indices.length),n+=e.positions.length/3,s+=e.indices.length,r&&(yield)}}return this.indices=m,this.positions=VertexData._MergeElement(n.o.PositionKind,p.positions,e,t.map(e=>[e.vertexData.positions,e.transform])),r&&(yield),p.normals&&(this.normals=VertexData._MergeElement(n.o.NormalKind,p.normals,e,t.map(e=>[e.vertexData.normals,e.transform])),r&&(yield)),p.tangents&&(this.tangents=VertexData._MergeElement(n.o.TangentKind,p.tangents,e,t.map(e=>[e.vertexData.tangents,e.transform])),r&&(yield)),p.uvs&&(this.uvs=VertexData._MergeElement(n.o.UVKind,p.uvs,e,t.map(e=>[e.vertexData.uvs,e.transform])),r&&(yield)),p.uvs2&&(this.uvs2=VertexData._MergeElement(n.o.UV2Kind,p.uvs2,e,t.map(e=>[e.vertexData.uvs2,e.transform])),r&&(yield)),p.uvs3&&(this.uvs3=VertexData._MergeElement(n.o.UV3Kind,p.uvs3,e,t.map(e=>[e.vertexData.uvs3,e.transform])),r&&(yield)),p.uvs4&&(this.uvs4=VertexData._MergeElement(n.o.UV4Kind,p.uvs4,e,t.map(e=>[e.vertexData.uvs4,e.transform])),r&&(yield)),p.uvs5&&(this.uvs5=VertexData._MergeElement(n.o.UV5Kind,p.uvs5,e,t.map(e=>[e.vertexData.uvs5,e.transform])),r&&(yield)),p.uvs6&&(this.uvs6=VertexData._MergeElement(n.o.UV6Kind,p.uvs6,e,t.map(e=>[e.vertexData.uvs6,e.transform])),r&&(yield)),p.colors&&(this.colors=VertexData._MergeElement(n.o.ColorKind,p.colors,e,t.map(e=>[e.vertexData.colors,e.transform])),r&&(yield)),p.matricesIndices&&(this.matricesIndices=VertexData._MergeElement(n.o.MatricesIndicesKind,p.matricesIndices,e,t.map(e=>[e.vertexData.matricesIndices,e.transform])),r&&(yield)),p.matricesWeights&&(this.matricesWeights=VertexData._MergeElement(n.o.MatricesWeightsKind,p.matricesWeights,e,t.map(e=>[e.vertexData.matricesWeights,e.transform])),r&&(yield)),p.matricesIndicesExtra&&(this.matricesIndicesExtra=VertexData._MergeElement(n.o.MatricesIndicesExtraKind,p.matricesIndicesExtra,e,t.map(e=>[e.vertexData.matricesIndicesExtra,e.transform])),r&&(yield)),p.matricesWeightsExtra&&(this.matricesWeightsExtra=VertexData._MergeElement(n.o.MatricesWeightsExtraKind,p.matricesWeightsExtra,e,t.map(e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,r){let s=r.filter(e=>null!==e[0]&&void 0!==e[0]);if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));let a=s.reduce((e,t)=>e+t[0].length,t.length),o=e===n.o.PositionKind?VertexData._TransformVector3Coordinates:e===n.o.NormalKind?VertexData._TransformVector3Normals:e===n.o.TangentKind?VertexData._TransformVector4Normals:()=>{};if(t instanceof Float32Array){let e=new Float32Array(a);e.set(t),i&&o(e,i,0,t.length);let r=t.length;for(let[t,i]of s)e.set(t,r),i&&o(e,i,r,t.length),r+=t.length;return e}{let e=Array(a);for(let i=0;i<t.length;i++)e[i]=t[i];i&&o(e,i,0,t.length);let r=t.length;for(let[t,i]of s){for(let i=0;i<t.length;i++)e[r+i]=t[i];i&&o(e,i,r,t.length),r+=t.length}return e}}_validate(){if(!this.positions)throw new c.LH("Positions are required",c.SM.MeshInvalidPositionsError);let getElementCount=(e,t)=>{let i=n.o.DeduceStride(e);if(t.length%i!=0)throw Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},e=getElementCount(n.o.PositionKind,this.positions),validateElementCount=(t,i)=>{let r=getElementCount(t,i);if(r!==e)throw Error("The "+t+"s element count ("+r+") does not match the positions count ("+e+")")};this.normals&&validateElementCount(n.o.NormalKind,this.normals),this.tangents&&validateElementCount(n.o.TangentKind,this.tangents),this.uvs&&validateElementCount(n.o.UVKind,this.uvs),this.uvs2&&validateElementCount(n.o.UV2Kind,this.uvs2),this.uvs3&&validateElementCount(n.o.UV3Kind,this.uvs3),this.uvs4&&validateElementCount(n.o.UV4Kind,this.uvs4),this.uvs5&&validateElementCount(n.o.UV5Kind,this.uvs5),this.uvs6&&validateElementCount(n.o.UV6Kind,this.uvs6),this.colors&&validateElementCount(n.o.ColorKind,this.colors),this.matricesIndices&&validateElementCount(n.o.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&validateElementCount(n.o.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&validateElementCount(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&validateElementCount(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){let e=this.serialize();return VertexData.Parse(e)}serialize(){let e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors)),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos)for(let t of(e.materialInfos=[],this.materialInfos)){let i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}return e}static ExtractFromMesh(e,t,i){return VertexData._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return VertexData._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){let r=new VertexData;return e.isVerticesDataPresent(n.o.PositionKind)&&(r.positions=e.getVerticesData(n.o.PositionKind,t,i)),e.isVerticesDataPresent(n.o.NormalKind)&&(r.normals=e.getVerticesData(n.o.NormalKind,t,i)),e.isVerticesDataPresent(n.o.TangentKind)&&(r.tangents=e.getVerticesData(n.o.TangentKind,t,i)),e.isVerticesDataPresent(n.o.UVKind)&&(r.uvs=e.getVerticesData(n.o.UVKind,t,i)),e.isVerticesDataPresent(n.o.UV2Kind)&&(r.uvs2=e.getVerticesData(n.o.UV2Kind,t,i)),e.isVerticesDataPresent(n.o.UV3Kind)&&(r.uvs3=e.getVerticesData(n.o.UV3Kind,t,i)),e.isVerticesDataPresent(n.o.UV4Kind)&&(r.uvs4=e.getVerticesData(n.o.UV4Kind,t,i)),e.isVerticesDataPresent(n.o.UV5Kind)&&(r.uvs5=e.getVerticesData(n.o.UV5Kind,t,i)),e.isVerticesDataPresent(n.o.UV6Kind)&&(r.uvs6=e.getVerticesData(n.o.UV6Kind,t,i)),e.isVerticesDataPresent(n.o.ColorKind)&&(r.colors=e.getVerticesData(n.o.ColorKind,t,i)),e.isVerticesDataPresent(n.o.MatricesIndicesKind)&&(r.matricesIndices=e.getVerticesData(n.o.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(n.o.MatricesWeightsKind)&&(r.matricesWeights=e.getVerticesData(n.o.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(n.o.MatricesIndicesExtraKind)&&(r.matricesIndicesExtra=e.getVerticesData(n.o.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(n.o.MatricesWeightsExtraKind)&&(r.matricesWeightsExtra=e.getVerticesData(n.o.MatricesWeightsExtraKind,t,i)),r.indices=e.getIndices(t,i),r}static CreateRibbon(e){throw(0,a.S)("ribbonBuilder")}static CreateBox(e){throw(0,a.S)("boxBuilder")}static CreateTiledBox(e){throw(0,a.S)("tiledBoxBuilder")}static CreateTiledPlane(e){throw(0,a.S)("tiledPlaneBuilder")}static CreateSphere(e){throw(0,a.S)("sphereBuilder")}static CreateCylinder(e){throw(0,a.S)("cylinderBuilder")}static CreateTorus(e){throw(0,a.S)("torusBuilder")}static CreateLineSystem(e){throw(0,a.S)("linesBuilder")}static CreateDashedLines(e){throw(0,a.S)("linesBuilder")}static CreateGround(e){throw(0,a.S)("groundBuilder")}static CreateTiledGround(e){throw(0,a.S)("groundBuilder")}static CreateGroundFromHeightMap(e){throw(0,a.S)("groundBuilder")}static CreatePlane(e){throw(0,a.S)("planeBuilder")}static CreateDisc(e){throw(0,a.S)("discBuilder")}static CreatePolygon(e,t,i,r,s,n,o){throw(0,a.S)("polygonBuilder")}static CreateIcoSphere(e){throw(0,a.S)("icoSphereBuilder")}static CreatePolyhedron(e){throw(0,a.S)("polyhedronBuilder")}static CreateCapsule(e={orientation:s.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw(0,a.S)("capsuleBuilder")}static CreateTorusKnot(e){throw(0,a.S)("torusKnotBuilder")}static ComputeNormals(e,t,i,r){let n=0,a=0,o=0,l=0,h=0,u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=0,v=0,x=0,T=0,S=0,C=0,E=0,b=0,y=!1,P=!1,R=!1,A=!1,I=1,M=0,D=null;r&&(y=!!r.facetNormals,P=!!r.facetPositions,R=!!r.facetPartitioning,I=!0===r.useRightHandedSystem?-1:1,M=r.ratio||0,A=!!r.depthSort,D=r.distanceTo,A&&void 0===D&&(D=s.P.Zero()));let O=0,N=0,F=0,B=0;for(R&&r&&r.bbSize&&(O=r.subDiv.X*M/r.bbSize.x,N=r.subDiv.Y*M/r.bbSize.y,F=r.subDiv.Z*M/r.bbSize.z,B=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0),n=0;n<e.length;n++)i[n]=0;let L=t.length/3|0;for(n=0;n<L;n++){if(g=(m=3*t[3*n])+1,v=m+2,T=(x=3*t[3*n+1])+1,S=x+2,E=(C=3*t[3*n+2])+1,b=C+2,a=e[m]-e[x],o=e[g]-e[T],l=e[v]-e[S],h=e[C]-e[x],u=e[E]-e[T],f=0===(f=Math.sqrt((d=I*(o*(c=e[b]-e[S])-l*u))*d+(p=I*(l*h-a*c))*p+(_=I*(a*u-o*h))*_))?1:f,d/=f,p/=f,_/=f,y&&r&&(r.facetNormals[n].x=d,r.facetNormals[n].y=p,r.facetNormals[n].z=_),P&&r&&(r.facetPositions[n].x=(e[m]+e[x]+e[C])/3,r.facetPositions[n].y=(e[g]+e[T]+e[E])/3,r.facetPositions[n].z=(e[v]+e[S]+e[b])/3),R&&r){let t=Math.floor((r.facetPositions[n].x-r.bInfo.minimum.x*M)*O),i=Math.floor((r.facetPositions[n].y-r.bInfo.minimum.y*M)*N),s=Math.floor((r.facetPositions[n].z-r.bInfo.minimum.z*M)*F),a=Math.floor((e[m]-r.bInfo.minimum.x*M)*O),o=Math.floor((e[g]-r.bInfo.minimum.y*M)*N),l=Math.floor((e[v]-r.bInfo.minimum.z*M)*F),h=Math.floor((e[x]-r.bInfo.minimum.x*M)*O),u=Math.floor((e[T]-r.bInfo.minimum.y*M)*N),c=Math.floor((e[S]-r.bInfo.minimum.z*M)*F),d=Math.floor((e[C]-r.bInfo.minimum.x*M)*O),p=Math.floor((e[E]-r.bInfo.minimum.y*M)*N),_=Math.floor((e[b]-r.bInfo.minimum.z*M)*F),f=a+r.subDiv.max*o+B*l,y=h+r.subDiv.max*u+B*c,P=d+r.subDiv.max*p+B*_,R=t+r.subDiv.max*i+B*s;r.facetPartitioning[R]=r.facetPartitioning[R]?r.facetPartitioning[R]:[],r.facetPartitioning[f]=r.facetPartitioning[f]?r.facetPartitioning[f]:[],r.facetPartitioning[y]=r.facetPartitioning[y]?r.facetPartitioning[y]:[],r.facetPartitioning[P]=r.facetPartitioning[P]?r.facetPartitioning[P]:[],r.facetPartitioning[f].push(n),y!=f&&r.facetPartitioning[y].push(n),P==y||P==f||r.facetPartitioning[P].push(n),R==f||R==y||R==P||r.facetPartitioning[R].push(n)}if(A&&r&&r.facetPositions){let e=r.depthSortedFacets[n];e.ind=3*n,e.sqDistance=s.P.DistanceSquared(r.facetPositions[n],D)}i[m]+=d,i[g]+=p,i[v]+=_,i[x]+=d,i[T]+=p,i[S]+=_,i[C]+=d,i[E]+=p,i[b]+=_}for(n=0;n<i.length/3;n++)f=0===(f=Math.sqrt((d=i[3*n])*d+(p=i[3*n+1])*p+(_=i[3*n+2])*_))?1:f,d/=f,p/=f,_/=f,i[3*n]=d,i[3*n+1]=p,i[3*n+2]=_}static _ComputeSides(e,t,i,r,n,a,o){let l,h;let u=i.length,c=r.length;switch(e=e||VertexData.DEFAULTSIDE){case VertexData.FRONTSIDE:break;case VertexData.BACKSIDE:for(l=0;l<u;l+=3){let e=i[l];i[l]=i[l+2],i[l+2]=e}for(h=0;h<c;h++)r[h]=-r[h];break;case VertexData.DOUBLESIDE:{let e=t.length,d=e/3;for(let i=0;i<e;i++)t[e+i]=t[i];for(l=0;l<u;l+=3)i[l+u]=i[l+2]+d,i[l+1+u]=i[l+1]+d,i[l+2+u]=i[l]+d;for(h=0;h<c;h++)r[c+h]=-r[h];let p=n.length,_=0;for(_=0;_<p;_++)n[_+p]=n[_];for(l=0,a=a||new s.Lt(0,0,1,1),o=o||new s.Lt(0,0,1,1),_=0;l<p/2;l++)n[_]=a.x+(a.z-a.x)*n[_],n[_+1]=a.y+(a.w-a.y)*n[_+1],n[_+p]=o.x+(o.z-o.x)*n[_+p],n[_+p+1]=o.y+(o.w-o.y)*n[_+p+1],_+=2}}}static Parse(e){let t=new VertexData,i=e.positions;i&&t.set(i,n.o.PositionKind);let r=e.normals;r&&t.set(r,n.o.NormalKind);let s=e.tangents;s&&t.set(s,n.o.TangentKind);let a=e.uvs;a&&t.set(a,n.o.UVKind);let l=e.uvs2;l&&t.set(l,n.o.UV2Kind);let h=e.uvs3;h&&t.set(h,n.o.UV3Kind);let u=e.uvs4;u&&t.set(u,n.o.UV4Kind);let c=e.uvs5;c&&t.set(c,n.o.UV5Kind);let d=e.uvs6;d&&t.set(d,n.o.UV6Kind);let p=e.colors;p&&t.set(o.HE.CheckColors4(p,i.length/3),n.o.ColorKind);let _=e.matricesIndices;_&&t.set(_,n.o.MatricesIndicesKind);let f=e.matricesWeights;f&&t.set(f,n.o.MatricesWeightsKind);let m=e.indices;m&&(t.indices=m);let g=e.materialInfos;if(g)for(let e of(t.materialInfos=[],g)){let i=new VertexDataMaterialInfo;i.indexCount=e.indexCount,i.indexStart=e.indexStart,i.verticesCount=e.verticesCount,i.verticesStart=e.verticesStart,i.materialIndex=e.materialIndex,t.materialInfos.push(i)}return t}static ImportVertexData(e,t){let i=VertexData.Parse(e);t.setAllVerticesData(i,e.updatable)}};VertexData.FRONTSIDE=0,VertexData.BACKSIDE=1,VertexData.DOUBLESIDE=2,VertexData.DEFAULTSIDE=0,VertexData._UniqueIDGenerator=0,(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],VertexData,"_TransformVector3Coordinates",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],VertexData,"_TransformVector3Normals",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],VertexData,"_TransformVector4Normals",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],VertexData,"_FlipFaces",null)},4926:function(e,t,i){i.d(t,{g:function(){return MeshLODLevel}});let MeshLODLevel=class MeshLODLevel{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}},1091:function(e,t,i){i.d(t,{P:function(){return SubMesh}});var r=i(1295),s=i(6491),n=i(5681),a=i(7383),o=i(1606);let SubMesh=class SubMesh{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;let i=null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0);i.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 o.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,r=!0){let s=this._drawWrapper;s.setEffect(e,t,r),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e){this._removeDrawWrapper(e);return}for(let e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,n,a,o=!0){return new SubMesh(e,t,i,r,s,n,a,o)}constructor(e,t,i,r,s,n,a,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=a||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,o&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){let e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var t;let 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)){let 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){let t;if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(r.o.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;let i=this._renderingMesh.getIndices();if(0===this.indexStart&&this.indexCount===i.length){let e=this._renderingMesh.getBoundingInfo();t={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else t=(0,a.y)(e,i,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(t.minimum,t.maximum):this._boundingInfo=new n.j(t.minimum,t.maximum),this}_checkCollision(e){let t=this.getBoundingInfo();return t._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){let t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){let 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){let i=[];for(let t=this.indexStart;t<this.indexStart+this.indexCount;t+=3)i.push(e[t],e[t+1],e[t+1],e[t+2],e[t+2],e[t]);this._linesIndexBuffer=t.createIndexBuffer(i),this._linesIndexCount=i.length}return this._linesIndexBuffer}canIntersects(e){let t=this.getBoundingInfo();return!!t&&e.intersectsBox(t.boundingBox)}intersects(e,t,i,r,s){let n=this.getMaterial();if(!n)return null;let a=3,o=!1;switch(n.fillMode){case 3:case 5:case 6:case 8:return null;case 7:a=1,o=!0}return 4===n.fillMode?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,r):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,r):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,r,s):this._intersectTriangles(e,t,i,a,o,r,s)}_intersectLines(e,t,i,r,n){let a=null;for(let o=this.indexStart;o<this.indexStart+this.indexCount;o+=2){let l=t[i[o]],h=t[i[o+1]],u=e.intersectionSegment(l,h,r);if(!(u<0)&&(n||!a||u<a.distance)&&((a=new s.c(null,null,u)).faceId=o/2,n))break}return a}_intersectUnIndexedLines(e,t,i,r,n){let a=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=2){let o=t[i],l=t[i+1],h=e.intersectionSegment(o,l,r);if(!(h<0)&&(n||!a||h<a.distance)&&((a=new s.c(null,null,h)).faceId=i/2,n))break}return a}_intersectTriangles(e,t,i,r,s,n,a){let o=null,l=-1;for(let h=this.indexStart;h<this.indexStart+this.indexCount-(3-r);h+=r){l++;let r=i[h],u=i[h+1],c=i[h+2];if(s&&4294967295===c){h+=2;continue}let d=t[r],p=t[u],_=t[c];if(!d||!p||!_||a&&!a(d,p,_,e,r,u,c))continue;let f=e.intersectsTriangle(d,p,_);if(f){if(f.distance<0)continue;if((n||!o||f.distance<o.distance)&&((o=f).faceId=l,n))break}}return o}_intersectUnIndexedTriangles(e,t,i,r,s){let n=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=3){let a=t[i],o=t[i+1],l=t[i+2];if(s&&!s(a,o,l,e,-1,-1,-1))continue;let h=e.intersectsTriangle(a,o,l);if(h){if(h.distance<0)continue;if((r||!n||h.distance<n.distance)&&((n=h).faceId=i/3,r))break}}return n}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){let i=new SubMesh(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){let e=this.getBoundingInfo();if(!e)return i;i._boundingInfo=new n.j(e.minimum,e.maximum)}return i}dispose(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);let e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1),this.resetDrawCache()}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,i,r,s,n=!0){let a=Number.MAX_VALUE,o=-Number.MAX_VALUE,l=s||r,h=l.getIndices();for(let e=t;e<t+i;e++){let t=h[e];t<a&&(a=t),t>o&&(o=t)}return new SubMesh(e,a,o-a+1,t,i,r,s,n)}}},8061:function(e,t,i){i.d(t,{Y:function(){return TransformNode}});var r=i(9956),s=i(1760),n=i(4800),a=i(78),o=i(208),l=i(524);let h=a.y3.Compose(a.P.One(),a._f.FromEulerAngles(0,Math.PI,0),a.P.Zero());let TransformNode=class TransformNode extends o.N{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&TransformNode.BILLBOARDMODE_USE_POSITION)!=0,this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==TransformNode.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 a.P(0,0,1),this._up=new a.P(0,1,0),this._right=new a.P(1,0,0),this._position=a.P.Zero(),this._rotation=a.P.Zero(),this._rotationQuaternion=null,this._scaling=a.P.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=TransformNode.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=a.y3.Zero(),this._usePivotMatrix=!1,this._absolutePosition=a.P.Zero(),this._absoluteScaling=a.P.Zero(),this._absoluteRotationQuaternion=a._f.Identity(),this._pivotMatrix=a.y3.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new n.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 a.P.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return a.P.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return a.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._poseMatrix=e.clone(),this}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=a.y3.Identity()),this._poseMatrix}_isSynchronized(){let e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===TransformNode.BILLBOARDMODE_NONE&&!e.pivotMatrixUpdated&&!this._infiniteDistance&&!this._position._isDirty&&!this._scaling._isDirty&&(!this._rotationQuaternion||!this._rotationQuaternion._isDirty)&&!this._rotation._isDirty}_initCache(){super._initCache();let 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=a.y3.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);for(let e of(r&&i&&i(this,r),this.getChildTransformNodes(!0)))e.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||a._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){let t,i,r;if(!e)return this;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){let e=a.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),a.P.TransformCoordinatesFromFloatsToRef(t,i,r,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=a.P.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();let e=a.jp.Matrix[0];return this._localMatrix.invertToRef(e),a.P.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=a.P.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=l.T.LOCAL){let n=TransformNode._LookAtVectorCache,o=s===l.T.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,r),s===l.T.WORLD&&this.parent){if(this.rotationQuaternion){let e=a.jp.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);let t=a.jp.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{let e=a.jp.Quaternion[0];a._f.FromEulerVectorToRef(this.rotation,e);let t=a.jp.Matrix[0];e.toRotationMatrix(t);let i=a.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){let t=a.P.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return a.P.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){let s=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?a._f.RotationYawPitchRollToRef(s+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=l.T.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);let i=this.getWorldMatrix();if(t==l.T.WORLD){let t=a.jp.Matrix[0];i.invertToRef(t),e=a.P.TransformCoordinates(e,t)}return this.setPivotMatrix(a.y3.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){let e=a.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(){let e=a.P.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),a.P.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(let t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;let r=a.jp.Quaternion[0],s=a.jp.Vector3[0],n=a.jp.Vector3[1],o=a.jp.Matrix[1];a.y3.IdentityToRef(o);let l=a.jp.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=TransformNode._TmpRotation,a._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),a.y3.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(n,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(a.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(!0),0>e.getFinalMatrix().determinant()&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(0>this.parent.getWorldMatrix().determinant()&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null):e&&(this.parent=this._currentParentWhenAttachingToBone),this}rotate(e,t,i){let r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==l.T.LOCAL){if(this.parent){let i=this.parent.getWorldMatrix(),r=a.jp.Matrix[0];i.invertToRef(r),e=a.P.TransformNormal(e,r),0>i.determinant()&&(t*=-1)}(r=a._f.RotationAxisToRef(e,t,TransformNode._RotationAxisCache)).multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=a._f.RotationAxisToRef(e,t,TransformNode._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=a._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));let r=a.jp.Vector3[0],s=a.jp.Vector3[1],n=a.jp.Vector3[2],o=a.jp.Quaternion[0],l=a.jp.Matrix[0],h=a.jp.Matrix[1],u=a.jp.Matrix[2],c=a.jp.Matrix[3];return e.subtractToRef(this.position,r),a.y3.TranslationToRef(r.x,r.y,r.z,l),a.y3.TranslationToRef(-r.x,-r.y,-r.z,h),a.y3.RotationAxisToRef(t,i,u),h.multiplyToRef(u,c),c.multiplyToRef(l,c),c.decompose(s,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){let r=e.scale(t);if(i&&i!==l.T.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(r));else{let e=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=a.jp.Quaternion[1],a._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));let s=a.jp.Quaternion[0];return a._f.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==TransformNode.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){let i;if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;let r=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===r||this.isSynchronized()))return this._currentRenderId=r,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();let s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=r,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;let n=this._getEffectiveParent(),o=TransformNode._TmpScaling,l=this._position;if(this._infiniteDistance&&!this.parent&&t){let e=t.getWorldMatrix(),i=new a.P(e.m[12],e.m[13],e.m[14]);(l=TransformNode._TmpTranslation).copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(o.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion){if(this._rotationQuaternion._isDirty=!1,i=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion){let e=this.rotation.lengthSquared();e&&(this._rotationQuaternion.multiplyInPlace(a._f.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else i=TransformNode._TmpRotation,a._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,i);if(this._usePivotMatrix){let e=a.jp.Matrix[1];a.y3.ScalingToRef(o.x,o.y,o.z,e);let t=a.jp.Matrix[0];i.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,a.jp.Matrix[4]),a.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 a.y3.ComposeToRef(o,i,l,this._localMatrix);if(n&&n.getWorldMatrix){if(e&&n.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),a.jp.Matrix[7])}else a.jp.Matrix[7].copyFrom(n.getWorldMatrix());let e=a.jp.Vector3[5],t=a.jp.Vector3[6],i=a.jp.Quaternion[0];a.jp.Matrix[7].decompose(t,i,e),a.y3.ScalingToRef(t.x,t.y,t.z,a.jp.Matrix[7]),a.jp.Matrix[7].setTranslation(e),TransformNode.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(a.jp.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),a.jp.Matrix[6]),a.jp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(n.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){let e=a.jp.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),a.jp.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&a.jp.Matrix[1].multiplyToRef(h,a.jp.Matrix[1]),a.jp.Matrix[1].setTranslationFromFloats(0,0,0),a.jp.Matrix[1].invertToRef(a.jp.Matrix[0]),(this.billboardMode&TransformNode.BILLBOARDMODE_ALL)!==TransformNode.BILLBOARDMODE_ALL){a.jp.Matrix[0].decompose(void 0,a.jp.Quaternion[0],void 0);let e=a.jp.Vector3[1];a.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&TransformNode.BILLBOARDMODE_X)!==TransformNode.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&TransformNode.BILLBOARDMODE_Y)!==TransformNode.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&TransformNode.BILLBOARDMODE_Z)!==TransformNode.BILLBOARDMODE_Z&&(e.z=0),a.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,a.jp.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(a.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(a.jp.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){let e=a.jp.Vector3[0];this._worldMatrix.getTranslationToRef(e);let i=t.globalPosition;this._worldMatrix.invertToRef(a.jp.Matrix[1]);let r=a.jp.Vector3[1];a.P.TransformCoordinatesToRef(i,a.jp.Matrix[1],r),r.normalize();let s=-Math.atan2(r.z,r.x)+Math.PI/2,n=Math.sqrt(r.x*r.x+r.z*r.z),o=-Math.atan2(r.y,n);if(a._f.RotationYawPitchRollToRef(s,o,0,a.jp.Quaternion[0]),(this.billboardMode&TransformNode.BILLBOARDMODE_ALL)!==TransformNode.BILLBOARDMODE_ALL){let e=a.jp.Vector3[1];a.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&TransformNode.BILLBOARDMODE_X)!==TransformNode.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&TransformNode.BILLBOARDMODE_Y)!==TransformNode.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&TransformNode.BILLBOARDMODE_Z)!==TransformNode.BILLBOARDMODE_Z&&(e.z=0),a.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,a.jp.Matrix[0])}else a.y3.FromQuaternionToRef(a.jp.Quaternion[0],a.jp.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(a.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(a.jp.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):n&&n._nonUniformScaling?this._updateNonUniformScalingState(n._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=a.y3.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){let e=this.getChildren();for(let t=0;t<e.length;++t){let i=e[t];if(i){i.computeWorldMatrix();let e=a.jp.Matrix[0];i._localMatrix.multiplyToRef(this._localMatrix,e);let t=a.jp.Quaternion[0];e.decompose(i.scaling,t,i.position),i.rotationQuaternion?i.rotationQuaternion.copyFrom(t):t.toEulerAnglesToRef(i.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=a._f.Identity()),this._worldMatrix=a.y3.Identity()}_afterComputeWorldMatrix(){}registerAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this}unregisterAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this}getPositionInCameraSpace(e=null){return e||(e=this.getScene().activeCamera),a.P.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(e,t,i){let r=s.p4.Clone(()=>new TransformNode(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;i<t.length;i++){let s=t[i];s.clone&&s.clone(e+"."+s.name,r)}}return r}serialize(e){let t=s.p4.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),t}static Parse(e,t,i){let r=s.p4.Parse(()=>new TransformNode(e.name,t),e,t,i);return e.localMatrix?r.setPreTransformMatrix(a.y3.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(a.y3.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r}getChildTransformNodes(e,t){let i=[];return this._getDescendants(i,e,e=>(!t||t(e))&&e instanceof TransformNode),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){let e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){let e=this.getChildTransformNodes(!0);for(let t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));let n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),o=Math.max(a.x,a.y,a.z);return 0===o||(this.scaling.scaleInPlace(1/o),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r))),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}};TransformNode.BILLBOARDMODE_NONE=0,TransformNode.BILLBOARDMODE_X=1,TransformNode.BILLBOARDMODE_Y=2,TransformNode.BILLBOARDMODE_Z=4,TransformNode.BILLBOARDMODE_ALL=7,TransformNode.BILLBOARDMODE_USE_POSITION=128,TransformNode.BillboardUseParentOrientation=!1,TransformNode._TmpRotation=a._f.Zero(),TransformNode._TmpScaling=a.P.Zero(),TransformNode._TmpTranslation=a.P.Zero(),TransformNode._LookAtVectorCache=new a.P(0,0,0),TransformNode._RotationAxisCache=new a._f,(0,r.gn)([(0,s.hd)("position")],TransformNode.prototype,"_position",void 0),(0,r.gn)([(0,s.hd)("rotation")],TransformNode.prototype,"_rotation",void 0),(0,r.gn)([(0,s.mv)("rotationQuaternion")],TransformNode.prototype,"_rotationQuaternion",void 0),(0,r.gn)([(0,s.hd)("scaling")],TransformNode.prototype,"_scaling",void 0),(0,r.gn)([(0,s.qC)("billboardMode")],TransformNode.prototype,"_billboardMode",void 0),(0,r.gn)([(0,s.qC)()],TransformNode.prototype,"scalingDeterminant",void 0),(0,r.gn)([(0,s.qC)("infiniteDistance")],TransformNode.prototype,"_infiniteDistance",void 0),(0,r.gn)([(0,s.qC)()],TransformNode.prototype,"ignoreNonUniformScaling",void 0),(0,r.gn)([(0,s.qC)()],TransformNode.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0)},1146:function(e,t,i){i.d(t,{q:function(){return AndOrNotEvaluator}});let AndOrNotEvaluator=class AndOrNotEvaluator{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,e=>(e=e.slice(1,e.length-1),AndOrNotEvaluator._HandleParenthesisContent(e,t))):AndOrNotEvaluator._HandleParenthesisContent(e,t))||"false"!==e&&AndOrNotEvaluator.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);let r=e.split("||");for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e)){let s=AndOrNotEvaluator._SimplifyNegation(r[e].trim()),n=s.split("&&");if(n.length>1)for(let e=0;e<n.length;++e){let r=AndOrNotEvaluator._SimplifyNegation(n[e].trim());if(!(i="true"!==r&&"false"!==r?"!"===r[0]?!t(r.substring(1)):t(r):"true"===r)){s="false";break}}if(i||"true"===s){i=!0;break}i="true"!==s&&"false"!==s?"!"===s[0]?!t(s.substring(1)):t(s):"true"===s}return i?"true":"false"}static _SimplifyNegation(e){return"!true"===(e=(e=e.replace(/^[\s!]+/,e=>(e=e.replace(/[\s]/g,()=>"")).length%2?"!":"")).trim())?e="false":"!false"===e&&(e="true"),e}}},4254:function(e,t,i){i.d(t,{B:function(){return ArrayTools},M:function(){return _ObserveArray}});let ArrayTools=class ArrayTools{static BuildArray(e,t){let i=[];for(let r=0;r<e;++r)i.push(t());return i}static BuildTuple(e,t){return ArrayTools.BuildArray(e,t)}};function _observeArrayfunction(e,t,i){let r=e[t];if("function"!=typeof r)return null;let newFunction=function(){let r=e.length,s=newFunction.previous.apply(e,arguments);return i(t,r),s};return r.next=newFunction,newFunction.previous=r,e[t]=newFunction,()=>{let i=newFunction.previous;if(!i)return;let r=newFunction.next;r?(i.next=r,r.previous=i):(i.next=void 0,e[t]=i),newFunction.next=void 0,newFunction.previous=void 0}}let r=["push","splice","pop","shift","unshift"];function _ObserveArray(e,t){let i=r.map(i=>_observeArrayfunction(e,i,t));return()=>{i.forEach(e=>{null==e||e()})}}},7521:function(e,t,i){function inlineScheduler(e,t,i){try{let r=e.next();r.done?t(r):r.value?r.value.then(()=>{r.value=void 0,t(r)},i):t(r)}catch(e){i(e)}}function createYieldingScheduler(e=25){let t;return(i,r,s)=>{let n=performance.now();void 0===t||n-t>e?(t=n,setTimeout(()=>{inlineScheduler(i,r,s)},0)):inlineScheduler(i,r,s)}}function runCoroutine(e,t,i,r,s){let resume=()=>{let n;let onStep=e=>{e.done?i(e.value):void 0===n?n=!0:resume()};do n=void 0,s&&s.aborted?r(Error("Aborted")):t(e,onStep,r),void 0===n&&(n=!1);while(n)};resume()}function runCoroutineSync(e,t){let i;return runCoroutine(e,inlineScheduler,e=>i=e,e=>{throw e},t),i}function runCoroutineAsync(e,t,i){return new Promise((r,s)=>{runCoroutine(e,t,r,s,i)})}function makeSyncFunction(e,t){return(...i)=>runCoroutineSync(e(...i),t)}i.d(t,{KO:function(){return createYieldingScheduler},WP:function(){return inlineScheduler},s3:function(){return runCoroutineSync},sM:function(){return runCoroutineAsync},vp:function(){return makeSyncFunction}})},1760:function(e,t,i){i.d(t,{G6:function(){return nativeOverride},N$:function(){return serializeAsColorCurves},QC:function(){return serializeAsVector2},RR:function(){return serializeAsMeshReference},VE:function(){return serializeAsCameraReference},XX:function(){return serializeAsColor4},hd:function(){return serializeAsVector3},mv:function(){return serializeAsQuaternion},n9:function(){return serializeAsColor3},oQ:function(){return serializeAsMatrix},oU:function(){return serializeAsTexture},p4:function(){return SerializationHelper},qC:function(){return serialize},qQ:function(){return serializeAsFresnelParameters},rX:function(){return serializeAsImageProcessingConfiguration},wz:function(){return expandToProperty}});var r=i(1803),s=i(78),n=i(6131),a=i(2983);let o={},l={},_copySource=function(e,t,i,s={}){let n=e();r.$&&r.$.HasTags(t)&&r.$.AddTagsTo(n,r.$.GetTags(t,!0));let a=getMergedStore(n),o={};for(let e in a){let r=a[e],l=t[e],h=r.type;if(null!=l&&("uniqueId"!==e||SerializationHelper.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:n[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&o[l.uniqueId]?n[e]=o[l.uniqueId]:(n[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=n[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:n[e]=i?l:l.clone()}}return n};function getDirectStore(e){let t=e.getClassName();return o[t]||(o[t]={}),o[t]}function getMergedStore(e){let t=e.getClassName();if(l[t])return l[t];l[t]={};let i=l[t],r=e,s=t;for(;s;){let e;let t=o[s];for(let e in t)i[e]=t[e];let n=!1;do{if(!(e=Object.getPrototypeOf(r)).getClassName){n=!0;break}if(e.getClassName()!==s)break;r=e}while(e);if(n)break;s=e.getClassName(),r=e}return i}function generateSerializableMember(e,t){return(i,r)=>{let s=getDirectStore(i);s[r]||(s[r]={type:e,sourceName:t})}}function generateExpandMember(e,t=null){return(i,r)=>{let s=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]===t||(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}function expandToProperty(e,t=null){return generateExpandMember(e,t)}function serialize(e){return generateSerializableMember(0,e)}function serializeAsTexture(e){return generateSerializableMember(1,e)}function serializeAsColor3(e){return generateSerializableMember(2,e)}function serializeAsFresnelParameters(e){return generateSerializableMember(3,e)}function serializeAsVector2(e){return generateSerializableMember(4,e)}function serializeAsVector3(e){return generateSerializableMember(5,e)}function serializeAsMeshReference(e){return generateSerializableMember(6,e)}function serializeAsColorCurves(e){return generateSerializableMember(7,e)}function serializeAsColor4(e){return generateSerializableMember(8,e)}function serializeAsImageProcessingConfiguration(e){return generateSerializableMember(9,e)}function serializeAsQuaternion(e){return generateSerializableMember(10,e)}function serializeAsMatrix(e){return generateSerializableMember(12,e)}function serializeAsCameraReference(e){return generateSerializableMember(11,e)}let SerializationHelper=class SerializationHelper{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i<e.animations.length;i++){let r=e.animations[i];t.animations.push(r.serialize())}}}static Serialize(e,t){t||(t={}),r.$&&(t.tags=r.$.GetTags(e));let i=getMergedStore(e);for(let r in i){let s=i[r],n=s.sourceName||r,a=s.type,o=e[r];if(null!=o&&("uniqueId"!==r||SerializationHelper.AllowLoadingUniqueId))switch(a){case 0:t[n]=o;break;case 1:case 3:case 7:case 9:t[n]=o.serialize();break;case 2:case 4:case 5:case 8:case 10:case 12:t[n]=o.asArray();break;case 6:case 11:t[n]=o.id}}return t}static ParseProperties(e,t,i,r){r||(r="");let n=getMergedStore(t);for(let o in n){let l=n[o],h=e[l.sourceName||o],u=l.type;if(null!=h&&("uniqueId"!==o||SerializationHelper.AllowLoadingUniqueId))switch(u){case 0:t[o]=h;break;case 1:i&&(t[o]=SerializationHelper._TextureParser(h,i,r));break;case 2:t[o]=a.Wo.FromArray(h);break;case 3:t[o]=SerializationHelper._FresnelParametersParser(h);break;case 4:t[o]=s.FM.FromArray(h);break;case 5:t[o]=s.P.FromArray(h);break;case 6:i&&(t[o]=i.getLastMeshById(h));break;case 7:t[o]=SerializationHelper._ColorCurvesParser(h);break;case 8:t[o]=a.HE.FromArray(h);break;case 9:t[o]=SerializationHelper._ImageProcessingConfigurationParser(h);break;case 10:t[o]=s._f.FromArray(h);break;case 11:i&&(t[o]=i.getCameraById(h));break;case 12:t[o]=s.y3.FromArray(h)}}}static Parse(e,t,i,s=null){let n=e();return r.$&&r.$.AddTagsTo(n,t.tags),SerializationHelper.ParseProperties(t,n,i,s),n}static Clone(e,t,i={}){return _copySource(e,t,!1,i)}static Instanciate(e,t){return _copySource(e,t,!0)}};function nativeOverride(e,t,i,r){let s=i.value;i.value=(...i)=>{let n=s;if("undefined"!=typeof _native&&_native[t]){let e=_native[t];n=r?(...t)=>r(...t)?e(...t):s(...t):e}return e[t]=n,n(...i)}}SerializationHelper.AllowLoadingUniqueId=!1,SerializationHelper._ImageProcessingConfigurationParser=e=>{throw(0,n.S)("ImageProcessingConfiguration")},SerializationHelper._FresnelParametersParser=e=>{throw(0,n.S)("FresnelParameters")},SerializationHelper._ColorCurvesParser=e=>{throw(0,n.S)("ColorCurves")},SerializationHelper._TextureParser=(e,t,i)=>{throw(0,n.S)("Texture")},nativeOverride.filter=function(e){return(t,i,r)=>nativeOverride(t,i,r,e)}},3189:function(e,t,i){i.d(t,{j:function(){return DeepCopier}});var r=i(9626);let CloneValue=(e,t,i)=>!e||e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&("SubMesh"===e.getClassName()||"PhysicsBody"===e.getClassName())?e.clone(t):e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?Object.assign({},e):null;function GetAllPropertyNames(e){let t=[];do Object.getOwnPropertyNames(e).forEach(function(e){-1===t.indexOf(e)&&t.push(e)});while(e=Object.getPrototypeOf(e));return t}let DeepCopier=class DeepCopier{static DeepCopy(e,t,i,s,n=!1){let a=GetAllPropertyNames(e);for(let o of a){if("_"===o[0]&&(!s||-1===s.indexOf(o))||o.endsWith("Observable")||i&&-1!==i.indexOf(o))continue;let a=e[o],l=typeof a;if("function"!==l)try{if("object"===l){if(a instanceof Uint8Array)t[o]=Uint8Array.from(a);else if(a instanceof Array){if(t[o]=[],a.length>0){if("object"==typeof a[0])for(let e=0;e<a.length;e++){let i=CloneValue(a[e],t,n);-1===t[o].indexOf(i)&&t[o].push(i)}else t[o]=a.slice(0)}}else t[o]=CloneValue(a,t,n)}else t[o]=a}catch(e){r.Y.Warn(e.message)}}}}},6131:function(e,t,i){i.d(t,{S:function(){return _WarnImport}});let r={};function _WarnImport(e,t=!1){if(!t||!r[e])return r[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}},7209:function(e,t,i){function IsWindowObjectExist(){return"undefined"!=typeof window}function IsNavigatorAvailable(){return"undefined"!=typeof navigator}function IsDocumentAvailable(){return"undefined"!=typeof document}function GetDOMTextContent(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}i.d(t,{CG:function(){return IsWindowObjectExist},n5:function(){return IsDocumentAvailable},up:function(){return IsNavigatorAvailable},v:function(){return GetDOMTextContent}})},3477:function(e,t,i){i.d(t,{GU:function(){return BaseError},LH:function(){return RuntimeError},SM:function(){return r}});let BaseError=class BaseError extends Error{};BaseError._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));let r={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};let RuntimeError=class RuntimeError extends BaseError{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",BaseError._setPrototypeOf(this,RuntimeError.prototype)}}},1166:function(e,t,i){let r;i.d(t,{$K:function(){return DecodeBase64UrlToBinary},$M:function(){return SetCorsBehavior},FV:function(){return RequestFile},Ip:function(){return ReadFile},VL:function(){return IsBase64DataUrl},r6:function(){return LoadImage},rN:function(){return g},vP:function(){return LoadFile}});var s=i(2962),n=i(7209),a=i(4800),o=i(320),l=i(9983),h=i(3477),u=i(9005),c=i(7790),d=i(6465),p=i(6030),_=i(9626),f=i(4490);let m=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);let LoadFileError=class LoadFileError extends h.LH{constructor(e,t){super(e,h.SM.LoadFileError),this.name="LoadFileError",h.GU._setPrototypeOf(this,LoadFileError.prototype),t instanceof s.g?this.request=t:this.file=t}};let RequestFileError=class RequestFileError extends h.LH{constructor(e,t){super(e,h.SM.RequestFileError),this.request=t,this.name="RequestFileError",h.GU._setPrototypeOf(this,RequestFileError.prototype)}};let ReadFileError=class ReadFileError extends h.LH{constructor(e,t){super(e,h.SM.ReadFileError),this.file=t,this.name="ReadFileError",h.GU._setPrototypeOf(this,ReadFileError.prototype)}};let g={DefaultRetryStrategy:l.b.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e},_CleanUrl=e=>e=e.replace(/#/gm,"%23"),SetCorsBehavior=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&g.CorsBehavior){if("string"==typeof g.CorsBehavior||g.CorsBehavior instanceof String)t.crossOrigin=g.CorsBehavior;else{let i=g.CorsBehavior(e);i&&(t.crossOrigin=i)}}},LoadImage=(e,t,i,r,n="",a)=>{var l;let h;let c=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(h=URL.createObjectURL(new Blob([e],{type:n})),c=!0):h=`data:${n};base64,`+(0,u.Gh)(e):e instanceof Blob?(h=URL.createObjectURL(e),c=!0):(h=_CleanUrl(e),h=g.PreprocessUrl(e));let d=p.l.LastCreatedEngine,onErrorHandler=t=>{if(i){let r=h||e.toString();i(`Error while trying to load image: ${0===r.indexOf("http")||r.length<=128?r:r.slice(0,128)+"..."}`,t)}};if("undefined"==typeof Image||null!==(l=null==d?void 0:d._features.forceBitmapOverHTMLImageElement)&&void 0!==l&&l)return LoadFile(h,r=>{d.createImageBitmap(new Blob([r],{type:n}),Object.assign({premultiplyAlpha:"none"},a)).then(e=>{t(e),c&&URL.revokeObjectURL(h)}).catch(t=>{i&&i("Error while trying to load image: "+e,t)})},void 0,r||void 0,!0,(e,t)=>{onErrorHandler(t)}),null;let _=new Image;SetCorsBehavior(h,_);let f=[],unloadHandlersList=()=>{f.forEach(e=>{e.target.removeEventListener(e.name,e.handler)}),f.length=0};f.push({target:_,name:"load",handler:()=>{unloadHandlersList(),t(_),c&&_.src&&URL.revokeObjectURL(_.src)}}),f.push({target:_,name:"error",handler:e=>{unloadHandlersList(),onErrorHandler(e),c&&_.src&&URL.revokeObjectURL(_.src)}}),f.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==_.src)return;unloadHandlersList();let t=Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);p.l.UseFallbackTexture=!1,onErrorHandler(t),c&&_.src&&URL.revokeObjectURL(_.src),_.src=""}}),f.forEach(e=>{e.target.addEventListener(e.name,e.handler)});let m="blob:"===h.substring(0,5),v="data:"===h.substring(0,5),noOfflineSupport=()=>{m||v||!s.g.IsCustomRequestAvailable?_.src=h:LoadFile(h,(e,t,i)=>{let r=!n&&i?i:n,s=new Blob([e],{type:r}),a=URL.createObjectURL(s);c=!0,_.src=a},void 0,r||void 0,!0,(e,t)=>{onErrorHandler(t)})};if(!m&&!v&&r&&r.enableTexturesOffline)r.open(()=>{r&&r.loadImage(h,_)},noOfflineSupport);else{if(-1!==h.indexOf("file:")){let e=decodeURIComponent(h.substring(5).toLowerCase());if(o.X.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(o.X.FilesToLoad[e])}catch(i){t=URL.createObjectURL(o.X.FilesToLoad[e])}_.src=t,c=!0}catch(e){_.src=""}return _}}noOfflineSupport()}return _},ReadFile=(e,t,i,r,s)=>{let n=new FileReader,o={onCompleteObservable:new a.y$,abort:()=>n.abort()};return n.onloadend=()=>o.onCompleteObservable.notifyObservers(o),s&&(n.onerror=()=>{s(new ReadFileError(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),r?n.readAsArrayBuffer(e):n.readAsText(e),o},LoadFile=(e,t,i,r,s,n,l)=>{if(e.name)return ReadFile(e,t,i,s,n?e=>{n(void 0,e)}:void 0);if(-1!==e.indexOf("file:")){let r=decodeURIComponent(e.substring(5).toLowerCase());0===r.indexOf("./")&&(r=r.substring(2));let a=o.X.FilesToLoad[r];if(a)return ReadFile(a,t,i,s,n?e=>n(void 0,new LoadFileError(e.message,e.file)):void 0)}let{match:h,type:u}=TestBase64DataUrl(e);if(h){let i={onCompleteObservable:new a.y$,abort:()=>()=>{}};try{let i=s?DecodeBase64UrlToBinary(e):DecodeBase64UrlToString(e);t(i,void 0,u)}catch(e){n?n(void 0,e):_.Y.Error(e.message||"Failed to parse the Data URL")}return f.Q.SetImmediate(()=>{i.onCompleteObservable.notifyObservers(i)}),i}return RequestFile(e,(e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))},i,r,s,n?e=>{n(e.request,new LoadFileError(e.message,e.request))}:void 0,l)},RequestFile=(e,t,i,r,o,l,h)=>{e=_CleanUrl(e),e=g.PreprocessUrl(e);let u=g.BaseUrl+e,c=!1,d={onCompleteObservable:new a.y$,abort:()=>c=!0},requestFile=()=>{let e,r=new s.g,a=null,unbindEvents=()=>{r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",onLoadEnd))},onLoadEnd=()=>{unbindEvents(),d.onCompleteObservable.notifyObservers(d),d.onCompleteObservable.clear(),i=void 0,e=null,onLoadEnd=null,l=void 0,h=void 0,t=void 0};d.abort=()=>{c=!0,onLoadEnd&&onLoadEnd(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==a&&(clearTimeout(a),a=null),r=null};let handleError=e=>{let t=e.message||"Unknown error";l&&r?l(new RequestFileError(t,r)):_.Y.Error(t)},retryLoop=d=>{if(r){if(r.open("GET",u),h)try{h(r)}catch(e){handleError(e);return}o&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),onLoadEnd&&r.addEventListener("loadend",onLoadEnd),e=()=>{if(!c&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status&&(!(0,n.CG)()||IsFileURL())){try{t&&t(o?r.response:r.responseText,r)}catch(e){handleError(e)}return}let i=g.DefaultRetryStrategy;if(i){let e=i(u,r,d);if(-1!==e){unbindEvents(),r=new s.g,a=setTimeout(()=>retryLoop(d+1),e);return}}let h=new RequestFileError("Error status: "+r.status+" "+r.statusText+" - Unable to load "+u,r);l&&l(h)}},r.addEventListener("readystatechange",e),r.send()}};retryLoop(0)};if(r&&r.enableSceneOffline){let noOfflineSupport=e=>{e&&e.status>400?l&&l(e):requestFile()};r.open(()=>{r&&r.loadFile(g.BaseUrl+e,e=>{!c&&t&&t(e),d.onCompleteObservable.notifyObservers(d)},i?e=>{!c&&i&&i(e)}:void 0,noOfflineSupport,o)},noOfflineSupport)}else requestFile();return d},IsFileURL=()=>"undefined"!=typeof location&&"file:"===location.protocol,IsBase64DataUrl=e=>m.test(e),TestBase64DataUrl=e=>{let t=m.exec(e);if(null===t||0===t.length)return{match:!1,type:""};{let e=t[0].replace("data:","").replace("base64,","");return{match:!0,type:e}}};function DecodeBase64UrlToBinary(e){return(0,u.HQ)(e.split(",")[1])}let DecodeBase64UrlToString=e=>(0,u.rP)(e.split(",")[1]);d.B._FileToolsLoadImage=LoadImage,d.B._FileToolsLoadFile=LoadFile,c.L._FileToolsLoadFile=LoadFile,Object.defineProperty(r={DecodeBase64UrlToBinary:DecodeBase64UrlToBinary,DecodeBase64UrlToString:DecodeBase64UrlToString,DefaultRetryStrategy:g.DefaultRetryStrategy,BaseUrl:g.BaseUrl,CorsBehavior:g.CorsBehavior,PreprocessUrl:g.PreprocessUrl,IsBase64DataUrl:IsBase64DataUrl,IsFileURL:IsFileURL,LoadFile:LoadFile,LoadImage:LoadImage,ReadFile:ReadFile,RequestFile:RequestFile,SetCorsBehavior:SetCorsBehavior},"DefaultRetryStrategy",{get:function(){return g.DefaultRetryStrategy},set:function(e){g.DefaultRetryStrategy=e}}),Object.defineProperty(r,"BaseUrl",{get:function(){return g.BaseUrl},set:function(e){g.BaseUrl=e}}),Object.defineProperty(r,"PreprocessUrl",{get:function(){return g.PreprocessUrl},set:function(e){g.PreprocessUrl=e}}),Object.defineProperty(r,"CorsBehavior",{get:function(){return g.CorsBehavior},set:function(e){g.CorsBehavior=e}})},320:function(e,t,i){i.d(t,{X:function(){return FilesInputStore}});let FilesInputStore=class FilesInputStore{};FilesInputStore.FilesToLoad={}},1032:function(e,t,i){i.d(t,{f:function(){return RandomGUID}});function RandomGUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}},4406:function(e,t,i){i.d(t,{K:function(){return InstantiationTools}});var r=i(9626),s=i(3048);let InstantiationTools=class InstantiationTools{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];let t=(0,s.q)(e);if(t)return t;r.Y.Warn(e+" not found, you may have missed an import.");let i=e.split("."),n=window||this;for(let e=0,t=i.length;e<t;e++)n=n[i[e]];return"function"!=typeof n?null:n}};InstantiationTools.RegisteredExternalClasses={}},9626:function(e,t,i){i.d(t,{Y:function(){return Logger}});let Logger=class Logger{static _CheckLimit(e,t){let i=Logger._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},Logger._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var i;let r=Logger._LogLimitOutputs[e];if(!r||!Logger.MessageLimitReached)return;let s=this._Levels[t];r.current===r.limit&&Logger[s.name](Logger.MessageLimitReached.replace(/%LIMIT%/g,""+r.limit).replace(/%TYPE%/g,null!==(i=s.name)&&void 0!==i?i:""))}static _AddLogEntry(e){Logger._LogCache=e+Logger._LogCache,Logger.OnNewCacheEntry&&Logger.OnNewCacheEntry(e)}static _FormatMessage(e){let padStr=e=>e<10?"0"+e:""+e,t=new Date;return"["+padStr(t.getHours())+":"+padStr(t.getMinutes())+":"+padStr(t.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){if(void 0!==i&&!Logger._CheckLimit(t,i))return;let r=Logger._FormatMessage(t),s=this._Levels[e];s.logFunc&&s.logFunc("BJS - "+r);let n=`<div style='color:${s.color}'>${r}</div><br>`;Logger._AddLogEntry(n),Logger._GenerateLimitMessage(t,e)}static get LogCache(){return Logger._LogCache}static ClearLogCache(){Logger._LogCache="",Logger._LogLimitOutputs={},Logger.errorsCount=0}static set LogLevels(e){Logger.Log=Logger._LogDisabled,Logger.Warn=Logger._LogDisabled,Logger.Error=Logger._LogDisabled,[Logger.MessageLogLevel,Logger.WarningLogLevel,Logger.ErrorLogLevel].forEach(t=>{if((e&t)===t){let e=this._Levels[t];Logger[e.name]=Logger._LogEnabled.bind(Logger,t)}})}};Logger.NoneLogLevel=0,Logger.MessageLogLevel=1,Logger.WarningLogLevel=2,Logger.ErrorLogLevel=4,Logger.AllLogLevel=7,Logger.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",Logger._LogCache="",Logger._LogLimitOutputs={},Logger._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],Logger.errorsCount=0,Logger.Log=Logger._LogEnabled.bind(Logger,Logger.MessageLogLevel),Logger.Warn=Logger._LogEnabled.bind(Logger,Logger.WarningLogLevel),Logger.Error=Logger._LogEnabled.bind(Logger,Logger.ErrorLogLevel)},4800:function(e,t,i){i.d(t,{he:function(){return EventState},y$:function(){return Observable}});let EventState=class EventState{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}};let Observer=class Observer{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()}};let Observable=class Observable{static FromPromise(e,t){let i=new Observable;return e.then(e=>{i.notifyObservers(e)}).catch(e=>{if(t)t.notifyObservers(e);else throw e}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=[],this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new EventState(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,s=!1){if(!e)return null;let n=new Observer(e,t,r);return n.unregisterOnNextCall=s,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){if(!e)return!1;e._remove=null;let t=this._observers.indexOf(e);return -1!==t&&(this._deferUnregister(e),!0)}removeCallback(e,t){for(let i=0;i<this._observers.length;i++){let r=this._observers[i];if(!r._willBeUnregistered&&r.callback===e&&(!t||t===r.scope))return this._deferUnregister(r),!0}return!1}_deferUnregister(e){e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout(()=>{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;let i=this._observers.indexOf(e);return -1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;let n=this._eventState;for(let a of(n.mask=t,n.target=i,n.currentTarget=r,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=s,this._observers))if(!a._willBeUnregistered&&(a.mask&t&&(a.unregisterOnNextCall&&this._deferUnregister(a),a.scope?n.lastReturnValue=a.callback.apply(a.scope,[e,n]):n.lastReturnValue=a.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;let r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){let 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(){let e=new Observable;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(let t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}},7263:function(e,t,i){i.d(t,{z:function(){return PerfCounter}});var r=i(7662);let PerfCounter=class PerfCounter{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){PerfCounter.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){PerfCounter.Enabled&&(this._startMonitoringTime=r.F.Now)}endMonitoring(e=!0){if(!PerfCounter.Enabled)return;e&&this.fetchNewFrame();let t=r.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;let e=r.F.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}};PerfCounter.Enabled=!0},8786:function(e,t,i){i.d(t,{A:function(){return PerformanceMonitor}});var r=i(7662);let PerformanceMonitor=class PerformanceMonitor{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new RollingAverage(e)}sampleFrame(e=r.F.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){let 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(){let 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()}};let RollingAverage=class RollingAverage{constructor(e){this._samples=Array(e),this.reset()}add(e){let t;if(this.isSaturated()){let 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;let 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){let t=this._samples.length;return(e%t+t)%t}}},7662:function(e,t,i){i.d(t,{F:function(){return PrecisionDate}});var r=i(7209);let PrecisionDate=class PrecisionDate{static get Now(){return(0,r.CG)()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},9983:function(e,t,i){i.d(t,{b:function(){return RetryStrategy}});let RetryStrategy=class RetryStrategy{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>0!==r.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}},8355:function(e,t,i){i.d(t,{f:function(){return SmartArrayNoDuplicate},t:function(){return SmartArray}});let SmartArray=class SmartArray{constructor(e){this.length=0,this.data=Array(e),this._id=SmartArray._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){let t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return -1!==this.indexOf(e)}};SmartArray._GlobalId=0;let SmartArrayNoDuplicate=class SmartArrayNoDuplicate extends SmartArray{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=(this.length+e.length)*2);for(let t=0;t<e.length;t++){let i=(e.data||e)[t];this.pushNoDuplicate(i)}}}}},1186:function(e,t,i){i.d(t,{x:function(){return StringDictionary}});let StringDictionary=class StringDictionary{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach((e,t)=>this.add(e,t))}get(e){let 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))&&this.add(e,i),i}getOrAdd(e,t){let 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){let 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(let t in this._data){let i=this._data[t];e(t,i)}}first(e){for(let t in this._data){let i=this._data[t],r=e(t,i);if(r)return r}return null}}},9005:function(e,t,i){i.d(t,{Gh:function(){return EncodeArrayBufferToBase64},HQ:function(){return DecodeBase64ToBinary},rP:function(){return DecodeBase64ToString}});let EncodeArrayBufferToBase64=e=>{let t,i,r,s,n,a,o;let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",u=0,c=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;u<c.length;)t=c[u++],i=u<c.length?c[u++]:Number.NaN,r=u<c.length?c[u++]:Number.NaN,s=t>>2,n=(3&t)<<4|i>>4,a=(15&i)<<2|r>>6,o=63&r,isNaN(i)?a=o=64:isNaN(r)&&(o=64),h+=l.charAt(s)+l.charAt(n)+l.charAt(a)+l.charAt(o);return h},DecodeBase64ToString=e=>atob(e),DecodeBase64ToBinary=e=>{let t=DecodeBase64ToString(e),i=t.length,r=new Uint8Array(new ArrayBuffer(i));for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r.buffer}},1803:function(e,t,i){i.d(t,{$:function(){return Tags}});var r=i(1146);let Tags=class Tags{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Tags.HasTags(e),e.addTags=t=>Tags.AddTagsTo(e,t),e.removeTags=t=>Tags.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Tags.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;let t=e._tags;for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(!t)return e._tags;{let t=[];for(let i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}}static AddTagsTo(e,t){if(!t||"string"!=typeof t)return;let i=t.split(" ");i.forEach(function(t){Tags._AddTagTo(e,t)})}static _AddTagTo(e,t){""===(t=t.trim())||"true"===t||"false"===t||t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Tags.EnableFor(e),e._tags[t]=!0)}static RemoveTagsFrom(e,t){if(!Tags.HasTags(e))return;let i=t.split(" ");for(let t in i)Tags._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?Tags.HasTags(e):r.q.Eval(t,t=>Tags.HasTags(e)&&e._tags[t]))}}},4490:function(e,t,i){i.d(t,{Q:function(){return TimingTools}});var r=i(7209);let TimingTools=class TimingTools{static SetImmediate(e){(0,r.CG)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}},5132:function(e,t,i){i.d(t,{$g:function(){return AsyncLoop},w1:function(){return Tools}});var r=i(4800),s=i(7209),n=i(9626),a=i(3189),o=i(7662),l=i(6131),h=i(2962),u=i(6030),c=i(1166),d=i(4490),p=i(4406),_=i(1032);let Tools=class Tools{static get BaseUrl(){return c.rN.BaseUrl}static set BaseUrl(e){c.rN.BaseUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||!(-1===e.indexOf("://")||-1===e.indexOf(".")||-1===e.indexOf("/")||e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://")<e.indexOf(".")||0===e.indexOf("data:")||0===e.indexOf("blob:"))}static set ScriptBaseUrl(e){c.rN.ScriptBaseUrl=e}static get ScriptBaseUrl(){return c.rN.ScriptBaseUrl}static set ScriptPreprocessUrl(e){c.rN.ScriptPreprocessUrl=e}static get ScriptPreprocessUrl(){return c.rN.ScriptPreprocessUrl}static get DefaultRetryStrategy(){return c.rN.DefaultRetryStrategy}static set DefaultRetryStrategy(e){c.rN.DefaultRetryStrategy=e}static get CorsBehavior(){return c.rN.CorsBehavior}static set CorsBehavior(e){c.rN.CorsBehavior=e}static get UseFallbackTexture(){return u.l.UseFallbackTexture}static set UseFallbackTexture(e){u.l.UseFallbackTexture=e}static get RegisteredExternalClasses(){return p.K.RegisteredExternalClasses}static set RegisteredExternalClasses(e){p.K.RegisteredExternalClasses=e}static get fallbackTexture(){return u.l.FallbackTexture}static set fallbackTexture(e){u.l.FallbackTexture=e}static FetchToRef(e,t,i,r,s,n){let a=((Math.abs(e)*i%i|0)+(Math.abs(t)*r%r|0)*i)*4;n.r=s[a]/255,n.g=s[a+1]/255,n.b=s[a+2]/255,n.a=s[a+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return p.K.Instantiate(e)}static SetImmediate(e){d.Q.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do t*=2;while(t<e);return t===e}static FloatRound(e){return Math.fround(e)}static GetFilename(e){let t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){let i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return 180*e/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,i=.9){let r=this.ToRadians(e),s=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(s)+i*Math.sin(r),(1-i)*Math.cos(s)+i*Math.cos(r)))}static MakeArray(e,t){return!0!==t&&(void 0===e||null==e)?null:Array.isArray(e)?e:[e]}static GetPointerPrefix(e){let t="pointer";return(0,s.CG)()&&!window.PointerEvent&&(t="mouse"),!e._badDesktopOS||e._badOS||document&&"ontouchend"in document||(t="mouse"),t}static SetCorsBehavior(e,t){(0,c.$M)(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static CleanUrl(e){return e=e.replace(/#/gm,"%23")}static get PreprocessUrl(){return c.rN.PreprocessUrl}static set PreprocessUrl(e){c.rN.PreprocessUrl=e}static LoadImage(e,t,i,r,s,n){return(0,c.r6)(e,t,i,r,s,n)}static LoadFile(e,t,i,r,s,n){return(0,c.vP)(e,t,i,r,s,n)}static LoadFileAsync(e,t=!0){return new Promise((i,r)=>{(0,c.vP)(e,e=>{i(e)},void 0,void 0,t,(e,t)=>{r(t)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(Tools.ScriptBaseUrl&&e.startsWith(Tools._DefaultCdnUrl)){let t="/"===Tools.ScriptBaseUrl[Tools.ScriptBaseUrl.length-1]?Tools.ScriptBaseUrl.substring(0,Tools.ScriptBaseUrl.length-1):Tools.ScriptBaseUrl;e=e.replace(Tools._DefaultCdnUrl,t)}return e=Tools.ScriptPreprocessUrl(e),t&&(e=Tools.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=Tools.GetBabylonScriptURL(e),Tools.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Tools.GetBabylonScriptURL(e),Tools.LoadScriptAsync(e)}static LoadScript(e,t,i,r){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){null==i||i(`Unable to load script '${e}' in worker`,t)}return}if(!(0,s.CG)()){null==i||i(`Cannot load script '${e}' outside of a window or a worker`);return}let n=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),r&&(a.id=r),a.onload=()=>{t&&t()},a.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},n.appendChild(a)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(e,t)=>{i(t||Error(e))})})}static ReadFileAsDataURL(e,t,i){let s=new FileReader,n={onCompleteObservable:new r.y$,abort:()=>s.abort()};return s.onloadend=()=>{n.onCompleteObservable.notifyObservers(n)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),n}static ReadFile(e,t,i,r,s){return(0,c.Ip)(e,t,i,r,s)}static FileAsURL(e){let t=new Blob([e]),i=window.URL,r=i.createObjectURL(t);return r}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){a.j.DeepCopy(e,t,i,r)}static IsEmpty(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){let r=t[i];e.addEventListener(r.name,r.handler,!1);try{window.parent&&window.parent.addEventListener(r.name,r.handler,!1)}catch(e){}}}static UnregisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){let r=t[i];e.removeEventListener(r.name,r.handler);try{e.parent&&e.parent.removeEventListener(r.name,r.handler)}catch(e){}}}static async DumpFramebuffer(e,t,i,r,s="image/png",n,a){throw(0,l.S)("DumpTools")}static DumpData(e,t,i,r,s="image/png",n,a=!1,o=!1,h){throw(0,l.S)("DumpTools")}static DumpDataAsync(e,t,i,r="image/png",s,n=!1,a=!1,o){throw(0,l.S)("DumpTools")}static _IsOffScreenCanvas(e){return void 0!==e.convertToBlob}static ToBlob(e,t,i="image/png",r){Tools._IsOffScreenCanvas(e)||e.toBlob||(e.toBlob=function(e,t,i){setTimeout(()=>{let r=atob(this.toDataURL(t,i).split(",")[1]),s=r.length,n=new Uint8Array(s);for(let e=0;e<s;e++)n[e]=r.charCodeAt(e);e(new Blob([n]))})}),Tools._IsOffScreenCanvas(e)?e.convertToBlob({type:i,quality:r}).then(e=>t(e)):e.toBlob(function(e){t(e)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){let e=new Date,i=(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2);t="screenshot_"+i+".png"}Tools.Download(e,t)}else if(e&&"undefined"!=typeof URL){let t=URL.createObjectURL(e),i=window.open("");if(!i)return;let r=i.document.createElement("img");r.onload=function(){URL.revokeObjectURL(t)},r.src=t,i.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if("string"!=typeof r&&t){if(t){if(Tools._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(e=>{let i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{let e=i.result;t(e)}});return}let r=e.toDataURL(i,s);t(r)}}else this.ToBlob(e,function(e){e&&Tools.DownloadBlob(e,r),t&&t("")},i,s)}static Download(e,t){if("undefined"==typeof URL)return;let i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,r,s="image/png",n=!1,a){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",s){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",n=1,a=!1,o,h=!1,u=!1,c=!0,d){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,n=!1,a,o=!1,h=!1,u=!0,c){throw(0,l.S)("ScreenshotTools")}static RandomId(){return(0,_.f)()}static IsBase64(e){return(0,c.VL)(e)}static DecodeBase64(e){return(0,c.$K)(e)}static get errorsCount(){return n.Y.errorsCount}static Log(e){n.Y.Log(e)}static Warn(e){n.Y.Warn(e)}static Error(e){n.Y.Error(e)}static get LogCache(){return n.Y.LogCache}static ClearLogCache(){n.Y.ClearLogCache()}static set LogLevels(e){n.Y.LogLevels=e}static set PerformanceLogLevel(e){if((e&Tools.PerformanceUserMarkLogLevel)===Tools.PerformanceUserMarkLogLevel){Tools.StartPerformanceCounter=Tools._StartUserMark,Tools.EndPerformanceCounter=Tools._EndUserMark;return}if((e&Tools.PerformanceConsoleLogLevel)===Tools.PerformanceConsoleLogLevel){Tools.StartPerformanceCounter=Tools._StartPerformanceConsole,Tools.EndPerformanceCounter=Tools._EndPerformanceConsole;return}Tools.StartPerformanceCounter=Tools._StartPerformanceCounterDisabled,Tools.EndPerformanceCounter=Tools._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Tools._Performance){if(!(0,s.CG)())return;Tools._Performance=window.performance}t&&Tools._Performance.mark&&Tools._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Tools._Performance.mark&&(Tools._Performance.mark(e+"-End"),Tools._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Tools._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Tools._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return o.F.Now}static GetClassName(e,t=!1){let i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__}i||(i=typeof e)}return i}static First(e,t){for(let i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return!!(0,s.up)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}};Tools.UseCustomRequestHeaders=!1,Tools.CustomRequestHeaders=h.g.CustomRequestHeaders,Tools.GetDOMTextContent=s.v,Tools._DefaultCdnUrl="https://cdn.babylonjs.com",Tools.GetAbsoluteUrl="object"==typeof document?e=>{let t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},Tools.NoneLogLevel=n.Y.NoneLogLevel,Tools.MessageLogLevel=n.Y.MessageLogLevel,Tools.WarningLogLevel=n.Y.WarningLogLevel,Tools.ErrorLogLevel=n.Y.ErrorLogLevel,Tools.AllLogLevel=n.Y.AllLogLevel,Tools.IsWindowObjectExist=s.CG,Tools.PerformanceNoneLogLevel=0,Tools.PerformanceUserMarkLogLevel=1,Tools.PerformanceConsoleLogLevel=2,Tools.StartPerformanceCounter=Tools._StartPerformanceCounterDisabled,Tools.EndPerformanceCounter=Tools._EndPerformanceCounterDisabled;let AsyncLoop=class AsyncLoop{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,i,r=0){let s=new AsyncLoop(e,t,i,r);return s.executeNext(),s}static SyncAsyncForLoop(e,t,i,r,s,n=0){return AsyncLoop.Run(Math.ceil(e/t),r=>{s&&s()?r.breakLoop():setTimeout(()=>{for(let n=0;n<t;++n){let a=r.index*t+n;if(a>=e)break;if(i(a),s&&s()){r.breakLoop();break}}r.executeNext()},n)},r)}};u.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"},3048:function(e,t,i){i.d(t,{H:function(){return RegisterClass},q:function(){return GetClass}});let r={};function RegisterClass(e,t){r[e]=t}function GetClass(e){return r[e]}},7531:function(e,t,i){i.d(t,{K:function(){return UniqueIdGenerator}});let UniqueIdGenerator=class UniqueIdGenerator{static get UniqueId(){let e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}};UniqueIdGenerator._UniqueIdCounter=1},2962:function(e,t,i){function createXMLHttpRequest(){return"undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}i.d(t,{g:function(){return WebRequest}});let WebRequest=class WebRequest{constructor(){this._xhr=createXMLHttpRequest(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(WebRequest.CustomRequestHeaders).length>0||WebRequest.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(let e in WebRequest.CustomRequestHeaders){let t=WebRequest.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return WebRequest.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){WebRequest.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(let e of WebRequest.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(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)}};WebRequest.CustomRequestHeaders={},WebRequest.CustomRequestModifiers=[],WebRequest.SkipRequestModificationForBabylonCDN=!0},5184:function(e,t,i){i.d(t,{O:function(){return PostProcessManager}});var r=i(1295);let PostProcessManager=class PostProcessManager{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[r.o.PositionKind])return;let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[r.o.PositionKind]=new r.o(this._scene.getEngine(),e,r.o.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){let 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(){let e=this._vertexBuffers[r.o.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){let i=this._scene.activeCamera;return!!(i&&(t=t||i._postProcesses.filter(e=>null!=e))&&0!==t.length&&this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!=t),!0)}directRender(e,t=null,i=!1,r=0,s=0,n=!1){var a;let o=this._scene.getEngine();for(let l=0;l<e.length;l++){l<e.length-1?e[l+1].activate(this._scene.activeCamera,null==t?void 0:t.texture):(t?o.bindFramebuffer(t,r,void 0,void 0,i,s):n||o.restoreDefaultFramebuffer(),null===(a=o._debugInsertMarker)||void 0===a||a.call(o,`post process ${e[l].name} output`));let h=e[l],u=h.apply();u&&(h.onBeforeRenderObservable.notifyObservers(u),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,u),o.drawElementsType(0,0,6),h.onAfterRenderObservable.notifyObservers(u))}o.setDepthBuffer(!0),o.setDepthWrite(!0)}_finalizeFrame(e,t,i,r,s=!1){var n;let a=this._scene.activeCamera;if(!a||0===(r=r||a._postProcesses.filter(e=>null!=e)).length||!this._scene.postProcessesEnabled)return;let o=this._scene.getEngine();for(let l=0,h=r.length;l<h;l++){let u=r[l];if(l<h-1?u._outputTexture=r[l+1].activate(a,null==t?void 0:t.texture):(t?(o.bindFramebuffer(t,i,void 0,void 0,s),u._outputTexture=t):(o.restoreDefaultFramebuffer(),u._outputTexture=null),null===(n=o._debugInsertMarker)||void 0===n||n.call(o,`post process ${r[l].name} output`)),e)break;let c=u.apply();c&&(u.onBeforeRenderObservable.notifyObservers(c),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,c),o.drawElementsType(0,0,6),u.onAfterRenderObservable.notifyObservers(c))}o.setDepthBuffer(!0),o.setDepthWrite(!0),o.setAlphaMode(0)}dispose(){let e=this._vertexBuffers[r.o.PositionKind];e&&(e.dispose(),this._vertexBuffers[r.o.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}},7254:function(e,t,i){i.d(t,{S:function(){return RenderingGroup}});var r=i(8355),s=i(78);let RenderingGroup=class RenderingGroup{set opaqueSortCompareFn(e){e?this._opaqueSortCompareFn=e:this._opaqueSortCompareFn=RenderingGroup.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){e?this._alphaTestSortCompareFn=e:this._alphaTestSortCompareFn=RenderingGroup.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=RenderingGroup.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,s=null,n=null){this.index=e,this._opaqueSubMeshes=new r.t(256),this._transparentSubMeshes=new r.t(256),this._alphaTestSubMeshes=new r.t(256),this._depthOnlySubMeshes=new r.t(256),this._particleSystems=new r.t(256),this._spriteManagers=new r.t(256),this._empty=!0,this._edgesRenderers=new r.f(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=s,this.transparentSortCompareFn=n}render(e,t,i,r){if(e){e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);return}let s=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(s.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),s.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);let n=s.getStencilBuffer();if(s.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(r),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency){if(s.setStencilBuffer(n),this._scene.useOrderIndependentTransparency){let e=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);e.length&&this._renderTransparent(e)}else this._renderTransparent(this._transparentSubMeshes);s.setAlphaMode(0)}if(s.setStencilBuffer(!1),this._edgesRenderers.length){for(let e=0;e<this._edgesRenderers.length;e++)this._edgesRenderers.data[e].render();s.setAlphaMode(0)}s.setStencilBuffer(n)}_renderOpaqueSorted(e){return RenderingGroup._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1)}_renderAlphaTestSorted(e){return RenderingGroup._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)}_renderTransparentSorted(e){return RenderingGroup._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0)}static _RenderSorted(e,t,i,r){let n,a=0,o=i?i.globalPosition:RenderingGroup._ZeroVector;if(r)for(;a<e.length;a++)(n=e.data[a])._alphaIndex=n.getMesh().alphaIndex,n._distanceToCamera=s.P.Distance(n.getBoundingInfo().boundingSphere.centerWorld,o);let l=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&l.sort(t);let h=l[0].getMesh().getScene();for(a=0;a<l.length;a++)if(n=l[a],!h._activeMeshesFrozenButKeepClipping||n.isInFrustum(h._frustumPlanes)){if(r){let e=n.getMaterial();if(e&&e.needDepthPrePass){let t=e.getScene().getEngine();t.setColorWrite(!1),t.setAlphaMode(0),n.render(!1),t.setColorWrite(!0)}}n.render(r)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:RenderingGroup.backToFrontSortCompare(e,t)}static backToFrontSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0}static PainterSortCompare(e,t){let i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._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;let t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i<this._particleSystems.length;i++){let r=this._particleSystems.data[i];if(0===(t&&t.layerMask&r.layerMask))continue;let s=r.emitter;s.position&&e&&-1===e.indexOf(s)||this._scene._activeParticles.addCount(r.render(),!1)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}_renderSprites(){if(!this._scene.spritesEnabled||0===this._spriteManagers.length)return;let e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(let t=0;t<this._spriteManagers.length;t++){let i=this._spriteManagers.data[t];0!==(e&&e.layerMask&i.layerMask)&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}};RenderingGroup._ZeroVector=s.P.Zero()},2195:function(e,t,i){i.d(t,{$:function(){return RenderingManager}});var r=i(7254);let RenderingGroupInfo=class RenderingGroupInfo{};let RenderingManager=class RenderingManager{get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(let e of this._scene.meshes)if(e.subMeshes)for(let t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(let e of this._scene.spriteManagers)e._wasDispatched=!1;for(let e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._renderingGroups=[],this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new RenderingGroupInfo,this._maintainStateBetweenFrames=!1,this._scene=e;for(let e=RenderingManager.MIN_RENDERINGGROUPS;e<RenderingManager.MAX_RENDERINGGROUPS;e++)this._autoClearDepthStencil[e]={autoClear:!0,depth:!0,stencil:!0}}getRenderingGroup(e){let t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]}_clearDepthStencilBuffer(e=!0,t=!0){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)}render(e,t,i,r){let s=this._renderingGroupInfo;if(s.scene=this._scene,s.camera=this._scene.activeCamera,this._scene.spriteManagers&&r)for(let e=0;e<this._scene.spriteManagers.length;e++){let t=this._scene.spriteManagers[e];this.dispatchSprites(t)}for(let n=RenderingManager.MIN_RENDERINGGROUPS;n<RenderingManager.MAX_RENDERINGGROUPS;n++){this._depthStencilBufferAlreadyCleaned=n===RenderingManager.MIN_RENDERINGGROUPS;let a=this._renderingGroups[n];if(!a||a._empty)continue;let o=Math.pow(2,n);if(s.renderingGroupId=n,this._scene.onBeforeRenderingGroupObservable.notifyObservers(s,o),RenderingManager.AUTOCLEAR){let e=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(n):this._autoClearDepthStencil[n];e&&e.autoClear&&this._clearDepthStencilBuffer(e.depth,e.stencil)}for(let e of this._scene._beforeRenderingGroupDrawStage)e.action(n);for(let s of(a.render(e,r,i,t),this._scene._afterRenderingGroupDrawStage))s.action(n);this._scene.onAfterRenderingGroupObservable.notifyObservers(s,o)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=RenderingManager.MIN_RENDERINGGROUPS;e<RenderingManager.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=RenderingManager.MIN_RENDERINGGROUPS;e<RenderingManager.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.prepareSprites()}}dispose(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null}freeRenderingGroups(){for(let e=RenderingManager.MIN_RENDERINGGROUPS;e<RenderingManager.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){void 0===this._renderingGroups[e]&&(this._renderingGroups[e]=new r.S(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))}dispatchSprites(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))}dispatchParticles(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,i))}setRenderingOrder(e,t=null,i=null,r=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=r,this._renderingGroups[e]){let t=this._renderingGroups[e];t.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],t.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],t.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:r}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}};RenderingManager.MAX_RENDERINGGROUPS=4,RenderingManager.MIN_RENDERINGGROUPS=0,RenderingManager.AUTOCLEAR=!0},3609:function(e,t,i){i.d(t,{Q:function(){return AlphaState}});let AlphaState=class AlphaState{constructor(){this._blendFunctionParameters=[,,,,],this._blendEquationParameters=[,,],this._blendConstants=[,,,,],this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,r){(this._blendConstants[0]!==e||this._blendConstants[1]!==t||this._blendConstants[2]!==i||this._blendConstants[3]!==r)&&(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=r,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,r){(this._blendFunctionParameters[0]!==e||this._blendFunctionParameters[1]!==t||this._blendFunctionParameters[2]!==i||this._blendFunctionParameters[3]!==r)&&(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=r,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){(this._blendEquationParameters[0]!==e||this._blendEquationParameters[1]!==t)&&(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}},7987:function(e,t,i){i.d(t,{k:function(){return DepthCullingState}});let DepthCullingState=class DepthCullingState{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}},6807:function(e,t,i){i.d(t,{s:function(){return StencilState}});let StencilState=class StencilState{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=StencilState.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=StencilState.KEEP,this.opDepthFail=StencilState.KEEP,this.opStencilDepthPass=StencilState.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}};StencilState.ALWAYS=519,StencilState.KEEP=7680,StencilState.REPLACE=7681},5122:function(e,t,i){i.d(t,{C:function(){return StencilStateComposer}});let StencilStateComposer=class StencilStateComposer{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){var e;this.stencilMaterial=void 0,null===(e=this.stencilGlobal)||void 0===e||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var t;if(!e)return;let i=!this.useStencilGlobalOnly&&!!(null===(t=this.stencilMaterial)||void 0===t?void 0:t.enabled);this.enabled=i?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=i?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=i?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=i?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=i?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=i?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=i?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=i?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}},800:function(e,t,i){i.d(t,{p:function(){return AbstractScene}});let AbstractScene=class AbstractScene{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,r){for(let s in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,s)&&this._BabylonFileParsers[s](e,t,i,r)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=(e=(e=(e=e.concat(this.meshes)).concat(this.lights)).concat(this.cameras)).concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}};AbstractScene._BabylonFileParsers={},AbstractScene._IndividualBabylonFileParsers={}},9111:function(e,t,i){let r,s;i.d(t,{YfP:function(){return ArcRotateCamera},HEv:function(){return rg.HE},Dso:function(){return postProcess_PostProcess},xsS:function(){return rN.x},xeF:function(){return sg.x},vGS:function(){return s_.v},w1W:function(){return rW.w1},Pa4:function(){return rm.P},fWK:function(){return webgpuEngine_WebGPUEngine}});var n,a,o,l,h,u,c,d,p,_,f,m,g,v,x,T,S,C,E,b,y,P,R,A,I,M,D,O,N,F,B,L,w,U,V,k,G,z,W,H,X,Y,j,K,$,Q,Z,J,ee,et,ei,er,es,en,ea,eo,el,eh,eu,ec,ed,ep,e_,ef,em,eg,ev,ex,eT,eS,eC,eE,eb,ey,eP,eR,eA,eI,eM,eD,eO,eN,eF,eB,eL,ew,eU,eV,ek,eG,ez,eW,eH,eX,eY,ej,eq,eK,e$,eQ,eZ,eJ,e0,e1,e2,e3,e4,e5,e6,e8,e7,e9,te,tt,ti,tr,ts,tn,ta,to,tl,th,tu,tc,td,tp,t_,tf,tm,tg,tv,tx,tT,tS,tC,tE,tb,ty,tP,tR,tA,tI,tM,tD,tO,tN,tF,tB,tL,tw,tU,tV,tk,tG,tz,tW,tH,tX,tY,tj,tq,tK,t$,tQ,tZ,tJ,t0,t1,t2,t3,t4,t5,t6,t8,t7,t9,ie,it,ii,ir,is,ia,io,il,ih,iu,ic,id,ip,i_,im,ig,iv,ix,iT,iS,iC,iE,ib,iy,iP,iR,iA,iI,iM,iD,iO,iN,iF,iB,iL,iw,iU,iV,ik,iG,iz,iW,iH,iX,iY,ij,iq,iK,i$,iQ,iZ,iJ,i0,i1,i2,i3,i4,i5,i6,i8,i7,i9,re,rt,ri,rr,rs,rn,ra,ro,rl,rh,ru,rc,rd,rp=i(800),r_=i(3621),rf=i(4800),rm=i(78),rg=i(2983),rv=i(3048);let Action=class Action{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new rf.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(){let e=this._condition;if(!e)return!0;let t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){let t=this._evaluateConditionForCurrentFrame();t&&(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){let i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){let e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}};Action._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof rm.FM?e.x+", "+e.y:e instanceof rm.P?e.x+", "+e.y+", "+e.z:e instanceof rg.Wo?e.r+", "+e.g+", "+e.b:e instanceof rg.HE?e.r+", "+e.g+", "+e.b+", "+e.a:e,Action._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,rv.H)("BABYLON.Action",Action);var rx=i(9528);let Condition=class Condition{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}}};let ValueCondition=class ValueCondition extends Condition{static get IsEqual(){return ValueCondition._IsEqual}static get IsDifferent(){return ValueCondition._IsDifferent}static get IsGreater(){return ValueCondition._IsGreater}static get IsLesser(){return ValueCondition._IsLesser}constructor(e,t,i,r,s=ValueCondition.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case ValueCondition.IsGreater:return this._effectiveTarget[this._property]>this.value;case ValueCondition.IsLesser:return this._effectiveTarget[this._property]<this.value;case ValueCondition.IsEqual:case ValueCondition.IsDifferent:{let e;return e=this.value.equals?this.value.equals(this._effectiveTarget[this._property]):this.value===this._effectiveTarget[this._property],this.operator===ValueCondition.IsEqual?e:!e}}return!1}serialize(){return this._serialize({name:"ValueCondition",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)},{name:"operator",value:ValueCondition.GetOperatorName(this.operator)}]})}static GetOperatorName(e){switch(e){case ValueCondition._IsEqual:return"IsEqual";case ValueCondition._IsDifferent:return"IsDifferent";case ValueCondition._IsGreater:return"IsGreater";case ValueCondition._IsLesser:return"IsLesser";default:return""}}};ValueCondition._IsEqual=0,ValueCondition._IsDifferent=1,ValueCondition._IsGreater=2,ValueCondition._IsLesser=3;let PredicateCondition=class PredicateCondition extends Condition{constructor(e,t){super(e),this.predicate=t}isValid(){return this.predicate()}};let StateCondition=class StateCondition extends Condition{constructor(e,t,i){super(e),this.value=i,this._target=t}isValid(){return this._target.state===this.value}serialize(){return this._serialize({name:"StateCondition",properties:[Action._GetTargetProperty(this._target),{name:"value",value:this.value}]})}};(0,rv.H)("BABYLON.ValueCondition",ValueCondition),(0,rv.H)("BABYLON.PredicateCondition",PredicateCondition),(0,rv.H)("BABYLON.StateCondition",StateCondition);var rT=i(9626);let SwitchBooleanAction=class SwitchBooleanAction extends Action{constructor(e,t,i,r){super(e,r),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}};let SetStateAction=class SetStateAction extends Action{constructor(e,t,i,r){super(e,r),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[Action._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}};let SetValueAction=class SetValueAction extends Action{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)}]},e)}};let IncrementValueAction=class IncrementValueAction extends Action{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&rT.Y.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)}]},e)}};let PlayAnimationAction=class PlayAnimationAction extends Action{constructor(e,t,i,r,s,n){super(e,n),this.from=i,this.to=r,this.loop=s,this._target=t}_prepare(){}execute(){let e=this._actionManager.getScene();e.beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[Action._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Action._SerializeValueAsString(this.loop)||!1}]},e)}};let StopAnimationAction=class StopAnimationAction extends Action{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){let e=this._actionManager.getScene();e.stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[Action._GetTargetProperty(this._target)]},e)}};let DoNothingAction=class DoNothingAction extends Action{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}};let CombineAction=class CombineAction extends Action{constructor(e,t,i,r=!0){super(e,i),this.children=t,this.enableChildrenConditions=r}_prepare(){for(let e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()}execute(e){for(let t of this.children)(!this.enableChildrenConditions||t._evaluateConditionForCurrentFrame())&&t.execute(e)}serialize(e){let t=super._serialize({name:"CombineAction",properties:[],combine:[]},e);for(let e=0;e<this.children.length;e++)t.combine.push(this.children[e].serialize(null));return t}};let ExecuteCodeAction=class ExecuteCodeAction extends Action{constructor(e,t,i){super(e,i),this.func=t}execute(e){this.func(e)}};let SetParentAction=class SetParentAction extends Action{constructor(e,t,i,r){super(e,r),this._target=t,this._parent=i}_prepare(){}execute(){if(this._target.parent===this._parent)return;let e=this._parent.getWorldMatrix().clone();e.invert(),this._target.position=rm.P.TransformCoordinates(this._target.position,e),this._target.parent=this._parent}serialize(e){return super._serialize({name:"SetParentAction",properties:[Action._GetTargetProperty(this._target),Action._GetTargetProperty(this._parent)]},e)}};(0,rv.H)("BABYLON.SetParentAction",SetParentAction),(0,rv.H)("BABYLON.ExecuteCodeAction",ExecuteCodeAction),(0,rv.H)("BABYLON.DoNothingAction",DoNothingAction),(0,rv.H)("BABYLON.StopAnimationAction",StopAnimationAction),(0,rv.H)("BABYLON.PlayAnimationAction",PlayAnimationAction),(0,rv.H)("BABYLON.IncrementValueAction",IncrementValueAction),(0,rv.H)("BABYLON.SetValueAction",SetValueAction),(0,rv.H)("BABYLON.SetStateAction",SetStateAction),(0,rv.H)("BABYLON.SetParentAction",SetParentAction),(0,rv.H)("BABYLON.SwitchBooleanAction",SwitchBooleanAction),(0,rv.H)("BABYLON.CombineAction",CombineAction);var rS=i(6030),rC=i(3189);let ActionManager=class ActionManager extends r_.O{constructor(e){if(super(),!(e=e||rS.l.LastCreatedScene))return;this._scene=e,e.actionManagers.push(this)}dispose(){let e=this._scene.actionManagers.indexOf(this);for(let e=0;e<this.actions.length;e++){let t=this.actions[e];ActionManager.Triggers[t.trigger]--,0===ActionManager.Triggers[t.trigger]&&delete ActionManager.Triggers[t.trigger]}this.actions.length=0,e>-1&&this._scene.actionManagers.splice(e,1);let t=this._scene.meshes.filter(e=>e.actionManager===this);for(let e of t)e.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t<this.actions.length;t++){let i=this.actions[t];if(e.indexOf(i.trigger)>-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i<this.actions.length;i++){let r=this.actions[i];if(e==r.trigger||t==r.trigger)return!0}return!1}hasSpecificTrigger(e,t){for(let i=0;i<this.actions.length;i++){let r=this.actions[i];if(r.trigger===e&&(!t||t(r.getTriggerParameter())))return!0}return!1}get hasPointerTriggers(){for(let e=0;e<this.actions.length;e++){let t=this.actions[e];if(t.trigger>=ActionManager.OnPickTrigger&&t.trigger<=ActionManager.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e<this.actions.length;e++){let t=this.actions[e];if(t.trigger>=ActionManager.OnPickTrigger&&t.trigger<=ActionManager.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===ActionManager.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(rT.Y.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,ActionManager.Triggers[e.trigger]?ActionManager.Triggers[e.trigger]++:ActionManager.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){let t=this.actions.indexOf(e);return -1!==t&&(this.actions.splice(t,1),ActionManager.Triggers[e.trigger]-=1,0===ActionManager.Triggers[e.trigger]&&delete ActionManager.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i<this.actions.length;i++){let r=this.actions[i];if(r.trigger===e){if(t&&(e===ActionManager.OnKeyUpTrigger||e===ActionManager.OnKeyDownTrigger)){let e=r.getTriggerParameter();if("function"==typeof e){if(!e(t))continue}else if(e&&e!==t.sourceEvent.keyCode){if(!e.toLowerCase)continue;let i=e.toLowerCase();if(i!==t.sourceEvent.key){let e=t.sourceEvent.charCode?t.sourceEvent.charCode:t.sourceEvent.keyCode,r=String.fromCharCode(e).toLowerCase();if(r!==i)continue}}}r._executeCurrent(t)}}}_getEffectiveTarget(e,t){let i=t.split(".");for(let t=0;t<i.length-1;t++)e=e[i[t]];return e}_getProperty(e){let t=e.split(".");return t[t.length-1]}serialize(e){let t={children:[],name:e,type:3,properties:[]};for(let e=0;e<this.actions.length;e++){let i={type:0,children:[],name:ActionManager.GetTriggerName(this.actions[e].trigger),properties:[]},r=this.actions[e].triggerOptions;if(r&&"number"!=typeof r){if(r.parameter instanceof Node)i.properties.push(Action._GetTargetProperty(r.parameter));else if("object"==typeof r.parameter){let e={};rC.j.DeepCopy(r.parameter,e,["mesh"]),r.parameter&&r.parameter.mesh&&(e._meshId=r.parameter.mesh.id),i.properties.push({name:"parameter",targetType:null,value:e})}else i.properties.push({name:"parameter",targetType:null,value:r.parameter})}this.actions[e].serialize(i),t.children.push(i)}return t}static Parse(e,t,i){let r=new ActionManager(i);null===t?i.actionManager=r:t.actionManager=r;let instantiate=(e,t)=>{let i=(0,rv.q)("BABYLON."+e);return i&&new i(...t)},parseParameter=(e,t,i,r)=>{if(null===r){let e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}let s=r.split("."),n=t.split(",");for(let e=0;e<s.length;e++)i=i[s[e]];if("boolean"==typeof i)return"true"===n[0];if("string"==typeof i)return n[0];let a=[];for(let e=0;e<n.length;e++)a.push(parseFloat(n[e]));return i instanceof rm.P?rm.P.FromArray(a):i instanceof rm.Lt?rm.Lt.FromArray(a):i instanceof rg.Wo?rg.Wo.FromArray(a):i instanceof rg.HE?rg.HE.FromArray(a):parseFloat(n[0])},traverse=(e,t,s,n,a=null)=>{if(e.detached)return;let o=[],l=null,h=null,u=e.combine&&e.combine.length>0;if(2===e.type?o.push(r):o.push(t),u){let t=[];for(let i=0;i<e.combine.length;i++)traverse(e.combine[i],ActionManager.NothingTrigger,s,n,t);o.push(t)}else for(let t=0;t<e.properties.length;t++){let r=e.properties[t].value,s=e.properties[t].name,n=e.properties[t].targetType;"target"===s?r=l="SceneProperties"===n?i:"MaterialProperties"===n?i.getMaterialByName(r):i.getNodeByName(r):"parent"===s?r=i.getNodeByName(r):"sound"===s?i.getSoundByName&&(r=i.getSoundByName(r)):"propertyPath"!==s?r=2===e.type&&"operator"===s?ValueCondition[r]:parseParameter(s,r,l,"value"===s?h:null):h=r,o.push(r)}if(null===a?o.push(s):o.push(null),"InterpolateValueAction"===e.name){let e=o[o.length-2];o[o.length-1]=e,o[o.length-2]=s}let c=instantiate(e.name,o);if(c instanceof Condition&&null!==s){let e=new DoNothingAction(t,s);n?n.then(e):r.registerAction(e),n=e}null===a?c instanceof Condition?(s=c,c=n):(s=null,n?n.then(c):r.registerAction(c)):a.push(c);for(let i=0;i<e.children.length;i++)traverse(e.children[i],t,s,c,null)};for(let t=0;t<e.children.length;t++){let r;let s=e.children[t];if(s.properties.length>0){let e=s.properties[0].value,t=null===s.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),r={trigger:ActionManager[s.name],parameter:t}}else r=ActionManager[s.name];for(let e=0;e<s.children.length;e++)s.detached||traverse(s.children[e],r,null,null)}}static GetTriggerName(e){switch(e){case 0:return"NothingTrigger";case 1:return"OnPickTrigger";case 2:return"OnLeftPickTrigger";case 3:return"OnRightPickTrigger";case 4:return"OnCenterPickTrigger";case 5:return"OnPickDownTrigger";case 6:return"OnDoublePickTrigger";case 7:return"OnPickUpTrigger";case 8:return"OnLongPressTrigger";case 9:return"OnPointerOverTrigger";case 10:return"OnPointerOutTrigger";case 11:return"OnEveryFrameTrigger";case 12:return"OnIntersectionEnterTrigger";case 13:return"OnIntersectionExitTrigger";case 14:return"OnKeyDownTrigger";case 15:return"OnKeyUpTrigger";case 16:return"OnPickOutTrigger";default:return""}}};ActionManager.NothingTrigger=0,ActionManager.OnPickTrigger=1,ActionManager.OnLeftPickTrigger=2,ActionManager.OnRightPickTrigger=3,ActionManager.OnCenterPickTrigger=4,ActionManager.OnPickDownTrigger=5,ActionManager.OnDoublePickTrigger=6,ActionManager.OnPickUpTrigger=7,ActionManager.OnPickOutTrigger=16,ActionManager.OnLongPressTrigger=8,ActionManager.OnPointerOverTrigger=9,ActionManager.OnPointerOutTrigger=10,ActionManager.OnEveryFrameTrigger=11,ActionManager.OnIntersectionEnterTrigger=12,ActionManager.OnIntersectionExitTrigger=13,ActionManager.OnKeyDownTrigger=14,ActionManager.OnKeyUpTrigger=15;let PlaySoundAction=class PlaySoundAction extends Action{constructor(e,t,i){super(e,i),this._sound=t}_prepare(){}execute(){void 0!==this._sound&&this._sound.play()}serialize(e){return super._serialize({name:"PlaySoundAction",properties:[{name:"sound",value:this._sound.name}]},e)}};let StopSoundAction=class StopSoundAction extends Action{constructor(e,t,i){super(e,i),this._sound=t}_prepare(){}execute(){void 0!==this._sound&&this._sound.stop()}serialize(e){return super._serialize({name:"StopSoundAction",properties:[{name:"sound",value:this._sound.name}]},e)}};(0,rv.H)("BABYLON.PlaySoundAction",PlaySoundAction),(0,rv.H)("BABYLON.StopSoundAction",StopSoundAction);var rE=i(5762),rb=i(1760);(n=td||(td={}))[n.NONE=0]="NONE",n[n.STEP=1]="STEP";let AnimationRange=class AnimationRange{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new AnimationRange(this.name,this.from,this.to)}};var ry=i(208);let Size=class Size{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){return 397*(0|this.width)^(0|this.height)}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new Size(this.width*e,this.height*t)}clone(){return new Size(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new Size(0,0)}add(e){let t=new Size(this.width+e.width,this.height+e.height);return t}subtract(e){let t=new Size(this.width-e.width,this.height-e.height);return t}static Lerp(e,t,i){let r=e.width+(t.width-e.width)*i,s=e.height+(t.height-e.height)*i;return new Size(r,s)}};var rP=i(2962);let rR={key:0,repeatCount:0,loopMode:2};let animation_Animation=class animation_Animation{static _PrepareAnimation(e,t,i,r,s,n,a,o){let l;if(!isNaN(parseFloat(s))&&isFinite(s)?l=animation_Animation.ANIMATIONTYPE_FLOAT:s instanceof rm._f?l=animation_Animation.ANIMATIONTYPE_QUATERNION:s instanceof rm.P?l=animation_Animation.ANIMATIONTYPE_VECTOR3:s instanceof rm.FM?l=animation_Animation.ANIMATIONTYPE_VECTOR2:s instanceof rg.Wo?l=animation_Animation.ANIMATIONTYPE_COLOR3:s instanceof rg.HE?l=animation_Animation.ANIMATIONTYPE_COLOR4:s instanceof Size&&(l=animation_Animation.ANIMATIONTYPE_SIZE),void 0==l)return null;let h=new animation_Animation(e,t,i,l,a),u=[{frame:0,value:s},{frame:r,value:n}];return h.setKeys(u),void 0!==o&&h.setEasingFunction(o),h}static CreateAnimation(e,t,i,r){let s=new animation_Animation(e+"Animation",e,i,t,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,n,a,o,l,h,u){let c=animation_Animation._PrepareAnimation(e,i,r,s,n,a,o,l);return c&&(t.getScene&&(u=t.getScene()),u)?u.beginDirectAnimation(t,[c],0,s,1===c.loopMode,1,h):null}static CreateAndStartHierarchyAnimation(e,t,i,r,s,n,a,o,l,h,u){let c=animation_Animation._PrepareAnimation(e,r,s,n,a,o,l,h);if(!c)return null;let d=t.getScene();return d.beginDirectHierarchyAnimation(t,i,[c],0,n,1===c.loopMode,1,u)}static CreateMergeAndStartAnimation(e,t,i,r,s,n,a,o,l,h){let u=animation_Animation._PrepareAnimation(e,i,r,s,n,a,o,l);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,s,1===u.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,r=!1,s){var n,a;let o;let l=e;if((o="object"==typeof t?t:{referenceFrame:null!=t?t:0,range:i,cloneOriginalAnimation:r,clonedAnimationName:s}).cloneOriginalAnimation&&((l=e.clone()).name=o.clonedAnimationName||l.name),!l._keys.length)return l;let h=o.referenceFrame&&o.referenceFrame>=0?o.referenceFrame:0,u=0,c=l._keys[0],d=l._keys.length-1,p=l._keys[d],_={referenceValue:c.value,referencePosition:rm.jp.Vector3[0],referenceQuaternion:rm.jp.Quaternion[0],referenceScaling:rm.jp.Vector3[1],keyPosition:rm.jp.Vector3[2],keyQuaternion:rm.jp.Quaternion[1],keyScaling:rm.jp.Vector3[3]},f=c.frame,m=p.frame;if(o.range){let e=l.getRange(o.range);e&&(f=e.from,m=e.to)}else f=null!==(n=o.fromFrame)&&void 0!==n?n:f,m=null!==(a=o.toFrame)&&void 0!==a?a:m;if(f!==c.frame&&(u=l.createKeyForFrame(f)),m!==p.frame&&(d=l.createKeyForFrame(m)),1===l._keys.length){let e=l._getKeyValue(l._keys[0]);_.referenceValue=e.clone?e.clone():e}else if(h<=c.frame){let e=l._getKeyValue(c.value);_.referenceValue=e.clone?e.clone():e}else if(h>=p.frame){let e=l._getKeyValue(p.value);_.referenceValue=e.clone?e.clone():e}else{rR.key=0;let e=l._interpolate(h,rR);_.referenceValue=e.clone?e.clone():e}l.dataType===animation_Animation.ANIMATIONTYPE_QUATERNION?_.referenceValue.normalize().conjugateInPlace():l.dataType===animation_Animation.ANIMATIONTYPE_MATRIX&&(_.referenceValue.decompose(_.referenceScaling,_.referenceQuaternion,_.referencePosition),_.referenceQuaternion.normalize().conjugateInPlace());let g=Number.MAX_VALUE,v=o.clipKeys?[]:null;for(let e=u;e<=d;e++){let t=l._keys[e];if(v&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},g===Number.MAX_VALUE&&(g=t.frame),t.frame-=g,v.push(t)),!e||l.dataType===animation_Animation.ANIMATIONTYPE_FLOAT||t.value!==c.value)switch(l.dataType){case animation_Animation.ANIMATIONTYPE_MATRIX:t.value.decompose(_.keyScaling,_.keyQuaternion,_.keyPosition),_.keyPosition.subtractInPlace(_.referencePosition),_.keyScaling.divideInPlace(_.referenceScaling),_.referenceQuaternion.multiplyToRef(_.keyQuaternion,_.keyQuaternion),rm.y3.ComposeToRef(_.keyScaling,_.keyQuaternion,_.keyPosition,t.value);break;case animation_Animation.ANIMATIONTYPE_QUATERNION:_.referenceValue.multiplyToRef(t.value,t.value);break;case animation_Animation.ANIMATIONTYPE_VECTOR2:case animation_Animation.ANIMATIONTYPE_VECTOR3:case animation_Animation.ANIMATIONTYPE_COLOR3:case animation_Animation.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(_.referenceValue,t.value);break;case animation_Animation.ANIMATIONTYPE_SIZE:t.value.width-=_.referenceValue.width,t.value.height-=_.referenceValue.height;break;default:t.value-=_.referenceValue}}return v&&l.setKeys(v,!0),l}static TransitionTo(e,t,i,r,s,n,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;let l=s*(a/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);let h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=o,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(let e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=[],this._events=[],this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=void 0===s?animation_Animation.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=animation_Animation._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType]+", nKeys: "+(this._keys?this._keys.length:"none")+", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((e,t)=>e.frame-t.frame)}removeEvents(e){for(let t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)}getEvents(){return this._events}createRange(e,t,i){this._ranges[e]||(this._ranges[e]=new AnimationRange(e,t,i))}deleteRange(e,t=!0){let i=this._ranges[e];if(i){if(t){let e=i.from,t=i.to;for(let i=this._keys.length-1;i>=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e}getEasingFunction(){return this._easingFunction}setEasingFunction(e){this._easingFunction=e}floatInterpolateFunction(e,t,i){return rE.R.Lerp(e,t,i)}floatInterpolateFunctionWithTangents(e,t,i,r,s){return rE.R.Hermite(e,t,i,r,s)}quaternionInterpolateFunction(e,t,i){return rm._f.Slerp(e,t,i)}quaternionInterpolateFunctionWithTangents(e,t,i,r,s){return rm._f.Hermite(e,t,i,r,s).normalize()}vector3InterpolateFunction(e,t,i){return rm.P.Lerp(e,t,i)}vector3InterpolateFunctionWithTangents(e,t,i,r,s){return rm.P.Hermite(e,t,i,r,s)}vector2InterpolateFunction(e,t,i){return rm.FM.Lerp(e,t,i)}vector2InterpolateFunctionWithTangents(e,t,i,r,s){return rm.FM.Hermite(e,t,i,r,s)}sizeInterpolateFunction(e,t,i){return Size.Lerp(e,t,i)}color3InterpolateFunction(e,t,i){return rg.Wo.Lerp(e,t,i)}color3InterpolateFunctionWithTangents(e,t,i,r,s){return rg.Wo.Hermite(e,t,i,r,s)}color4InterpolateFunction(e,t,i){return rg.HE.Lerp(e,t,i)}color4InterpolateFunctionWithTangents(e,t,i,r,s){return rg.HE.Hermite(e,t,i,r,s)}_getKeyValue(e){return"function"==typeof e?e():e}evaluate(e){return rR.key=0,this._interpolate(e,rR)}_interpolate(e,t,i=!1){if(t.loopMode===animation_Animation.ANIMATIONLOOPMODE_CONSTANT&&t.repeatCount>0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;let r=this._keys,s=r.length,n=t.key;for(;n>=0&&e<r[n].frame;)--n;for(;n+1<=s-1&&e>=r[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(r[0].value);if(n+1>s-1)return i?void 0:this._getKeyValue(r[s-1].value);let a=r[n],o=r[n+1];if(i&&(e===a.frame||e===o.frame))return;let l=this._getKeyValue(a.value),h=this._getKeyValue(o.value);if(a.interpolation===td.STEP)return o.frame>e?l:h;let u=void 0!==a.outTangent&&void 0!==o.inTangent,c=o.frame-a.frame,d=(e-a.frame)/c,p=this.getEasingFunction();switch(null!==p&&(d=p.ease(d)),this.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:{let e=u?this.floatInterpolateFunctionWithTangents(l,a.outTangent*c,h,o.inTangent*c,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+e}break}case animation_Animation.ANIMATIONTYPE_QUATERNION:{let e=u?this.quaternionInterpolateFunctionWithTangents(l,a.outTangent.scale(c),h,o.inTangent.scale(c),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:break;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.addInPlace(t.offsetValue.scale(t.repeatCount))}return e}case animation_Animation.ANIMATIONTYPE_VECTOR3:{let e=u?this.vector3InterpolateFunctionWithTangents(l,a.outTangent.scale(c),h,o.inTangent.scale(c),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_VECTOR2:{let e=u?this.vector2InterpolateFunctionWithTangents(l,a.outTangent.scale(c),h,o.inTangent.scale(c),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_SIZE:switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(l,h,d).add(t.offsetValue.scale(t.repeatCount))}break;case animation_Animation.ANIMATIONTYPE_COLOR3:{let e=u?this.color3InterpolateFunctionWithTangents(l,a.outTangent.scale(c),h,o.inTangent.scale(c),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_COLOR4:{let e=u?this.color4InterpolateFunctionWithTangents(l,a.outTangent.scale(c),h,o.inTangent.scale(c),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:if(animation_Animation.AllowMatricesInterpolation)return this.matrixInterpolateFunction(l,h,d,t.workValue);return l;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return l}}return 0}matrixInterpolateFunction(e,t,i,r){return animation_Animation.AllowMatrixDecomposeForInterpolation?r?(rm.y3.DecomposeLerpToRef(e,t,i,r),r):rm.y3.DecomposeLerp(e,t,i):r?(rm.y3.LerpToRef(e,t,i,r),r):rm.y3.Lerp(e,t,i)}clone(){let e=new animation_Animation(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)for(let t in e._ranges={},this._ranges){let i=this._ranges[t];i&&(e._ranges[t]=i.clone())}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){rR.key=0;let t=this._interpolate(e,rR,!0);if(!t)return rR.key===e?rR.key:rR.key+1;let i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(rR.key+1,0,i),rR.key+1}serialize(){let 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;let t=this.dataType;e.keys=[];let i=this.getKeys();for(let r=0;r<i.length;r++){let s=i[r],n={};switch(n.frame=s.frame,t){case animation_Animation.ANIMATIONTYPE_FLOAT:n.values=[s.value],void 0!==s.inTangent&&n.values.push(s.inTangent),void 0!==s.outTangent&&(void 0===s.inTangent&&n.values.push(void 0),n.values.push(s.outTangent)),void 0!==s.interpolation&&(void 0===s.inTangent&&n.values.push(void 0),void 0===s.outTangent&&n.values.push(void 0),n.values.push(s.interpolation));break;case animation_Animation.ANIMATIONTYPE_QUATERNION:case animation_Animation.ANIMATIONTYPE_MATRIX:case animation_Animation.ANIMATIONTYPE_VECTOR3:case animation_Animation.ANIMATIONTYPE_COLOR3:case animation_Animation.ANIMATIONTYPE_COLOR4:n.values=s.value.asArray(),void 0!=s.inTangent&&n.values.push(s.inTangent.asArray()),void 0!=s.outTangent&&(void 0===s.inTangent&&n.values.push(void 0),n.values.push(s.outTangent.asArray())),void 0!==s.interpolation&&(void 0===s.inTangent&&n.values.push(void 0),void 0===s.outTangent&&n.values.push(void 0),n.values.push(s.interpolation))}e.keys.push(n)}for(let t in e.ranges=[],this._ranges){let i=this._ranges[t];if(!i)continue;let r={};r.name=t,r.from=i.from,r.to=i.to,e.ranges.push(r)}return e}static _UniversalLerp(e,t,i){let r=e.constructor;return r.Lerp?r.Lerp(e,t,i):r.Slerp?r.Slerp(e,t,i):e.toFixed?e*(1-i)+i*t:t}static Parse(e){let t,i;let r=new animation_Animation(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior),s=e.dataType,n=[];for(e.enableBlending&&(r.enableBlending=e.enableBlending),e.blendingSpeed&&(r.blendingSpeed=e.blendingSpeed),i=0;i<e.keys.length;i++){let r,a,o;let l=e.keys[i];switch(s){case animation_Animation.ANIMATIONTYPE_FLOAT:t=l.values[0],l.values.length>=2&&(r=l.values[1]),l.values.length>=3&&(a=l.values[2]),l.values.length>=4&&(o=l.values[3]);break;case animation_Animation.ANIMATIONTYPE_QUATERNION:if(t=rm._f.FromArray(l.values),l.values.length>=8){let e=rm._f.FromArray(l.values.slice(4,8));e.equals(rm._f.Zero())||(r=e)}if(l.values.length>=12){let e=rm._f.FromArray(l.values.slice(8,12));e.equals(rm._f.Zero())||(a=e)}l.values.length>=13&&(o=l.values[12]);break;case animation_Animation.ANIMATIONTYPE_MATRIX:t=rm.y3.FromArray(l.values),l.values.length>=17&&(o=l.values[16]);break;case animation_Animation.ANIMATIONTYPE_COLOR3:t=rg.Wo.FromArray(l.values),l.values[3]&&(r=rg.Wo.FromArray(l.values[3])),l.values[4]&&(a=rg.Wo.FromArray(l.values[4])),l.values[5]&&(o=l.values[5]);break;case animation_Animation.ANIMATIONTYPE_COLOR4:t=rg.HE.FromArray(l.values),l.values[4]&&(r=rg.HE.FromArray(l.values[4])),l.values[5]&&(a=rg.HE.FromArray(l.values[5])),l.values[6]&&(o=rg.HE.FromArray(l.values[6]));break;case animation_Animation.ANIMATIONTYPE_VECTOR3:default:t=rm.P.FromArray(l.values),l.values[3]&&(r=rm.P.FromArray(l.values[3])),l.values[4]&&(a=rm.P.FromArray(l.values[4])),l.values[5]&&(o=l.values[5])}let h={};h.frame=l.frame,h.value=t,void 0!=r&&(h.inTangent=r),void 0!=a&&(h.outTangent=a),void 0!=o&&(h.interpolation=o),n.push(h)}if(r.setKeys(n),e.ranges)for(i=0;i<e.ranges.length;i++)t=e.ranges[i],r.createRange(t.name,t.from,t.to);return r}static AppendSerializedAnimations(e,t){rb.p4.AppendSerializedAnimations(e,t)}static ParseFromFileAsync(e,t){return new Promise((i,r)=>{let s=new rP.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){let e=[];for(let i of t)e.push(this.Parse(i));i(e)}else{let r=this.Parse(t);e&&(r.name=e),i(r)}}else r("Unable to load the animation")}}),s.open("GET",t),s.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{let r=new rP.g;r.addEventListener("readystatechange",()=>{if(4==r.readyState){if(200==r.status){let i=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(i.animations){let r=JSON.parse(i.animations),s=[];for(let t of r.animations){let i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{let r=JSON.parse(i.animation),s=this.Parse(r);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)}}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}};animation_Animation._UniqueIdGenerator=0,animation_Animation.AllowMatricesInterpolation=!1,animation_Animation.AllowMatrixDecomposeForInterpolation=!0,animation_Animation.SnippetUrl="https://snippet.babylonjs.com",animation_Animation.ANIMATIONTYPE_FLOAT=0,animation_Animation.ANIMATIONTYPE_VECTOR3=1,animation_Animation.ANIMATIONTYPE_QUATERNION=2,animation_Animation.ANIMATIONTYPE_MATRIX=3,animation_Animation.ANIMATIONTYPE_COLOR3=4,animation_Animation.ANIMATIONTYPE_COLOR4=7,animation_Animation.ANIMATIONTYPE_VECTOR2=5,animation_Animation.ANIMATIONTYPE_SIZE=6,animation_Animation.ANIMATIONLOOPMODE_RELATIVE=0,animation_Animation.ANIMATIONLOOPMODE_CYCLE=1,animation_Animation.ANIMATIONLOOPMODE_CONSTANT=2,animation_Animation.ANIMATIONLOOPMODE_YOYO=4,animation_Animation.CreateFromSnippetAsync=animation_Animation.ParseFromSnippetAsync,(0,rv.H)("BABYLON.Animation",animation_Animation),ry.N._AnimationRangeFactory=(e,t,i)=>new AnimationRange(e,t,i);let InterpolateValueAction=class InterpolateValueAction extends Action{constructor(e,t,i,r,s=1e3,n,a,o){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new rf.y$,this.propertyPath=i,this.value=r,this.duration=s,this.stopOtherAnimations=a,this.onInterpolationDone=o,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){let e;let t=this._actionManager.getScene(),i=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)e=animation_Animation.ANIMATIONTYPE_FLOAT;else if(this.value instanceof rg.Wo)e=animation_Animation.ANIMATIONTYPE_COLOR3;else if(this.value instanceof rm.P)e=animation_Animation.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof rm.y3)e=animation_Animation.ANIMATIONTYPE_MATRIX;else if(this.value instanceof rm._f)e=animation_Animation.ANIMATIONTYPE_QUATERNION;else{rT.Y.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}let r=new animation_Animation("InterpolateValueAction",this._property,100*(1e3/this.duration),e,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);r.setKeys(i),this.stopOtherAnimations&&t.stopAnimation(this._effectiveTarget),t.beginDirectAnimation(this._effectiveTarget,[r],0,100,!1,1,()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()})}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)},{name:"duration",value:Action._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Action._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}};(0,rv.H)("BABYLON.InterpolateValueAction",InterpolateValueAction);let rA=Object.freeze(new rm._f(0,0,0,0)),rI=Object.freeze(rm.P.Zero()),rM=Object.freeze(rm.FM.Zero()),rD=Object.freeze(Size.Zero()),rO=Object.freeze(rg.Wo.Black());let RuntimeAnimation=class RuntimeAnimation{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,r){if(this._events=[],this._currentFrame=0,this._originalValue=[],this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===animation_Animation.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=rm.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){let e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(let 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];let 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){let i=this._animation.targetPropertyPath;if(i.length>1){let r=e[i[0]];for(let e=1;e<i.length-1;e++)r=r[i[e]];this._targetPath=i[i.length-1],this._activeTargets[t]=r}else this._targetPath=i[0],this._activeTargets[t]=e}get animation(){return this._animation}reset(e=!1){if(e){if(this._target instanceof Array){let e=0;for(let t of this._target)void 0!==this._originalValue[e]&&this._setValue(t,this._activeTargets[e],this._originalValue[e],-1,e),e++}else void 0!==this._originalValue[0]&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0)}this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(let e=0;e<this._events.length;e++)this._events[e].isDone=!1}isStopped(){return this._stopped}dispose(){let e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;i<this._target.length;i++){let r=this._target[i];this._setValue(r,this._activeTargets[i],e,t,i)}return}this._setValue(this._target,this._directTarget,e,t,0)}_getOriginalValues(e=0){let t;let i=this._activeTargets[e];(t=i.getLocalMatrix&&"_matrix"===this._targetPath?i.getLocalMatrix():i[this._targetPath])&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t}_setValue(e,t,i,r,s){if(this._currentActiveTarget=t,this._weight=r,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){let e=t[this._targetPath];e.clone?this._originalBlendValue=e.clone():this._originalBlendValue=e}this._originalBlendValue.m?animation_Animation.AllowMatrixDecomposeForInterpolation?this._currentValue?rm.y3.DecomposeLerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=rm.y3.DecomposeLerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue?rm.y3.LerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=rm.y3.Lerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue=animation_Animation._UniversalLerp(this._originalBlendValue,i,this._blendingFactor);let r=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=r}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(i):this._currentValue=i:(null==i?void 0:i.clone)?this._currentValue=i.clone():this._currentValue=i;-1!==r?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[s]):t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)}_getCorrectLoopMode(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode}goToFrame(e){let t=this._animation.getKeys();e<t[0].frame?e=t[0].frame:e>t[t.length-1].frame&&(e=t[t.length-1].frame);let i=this._events;if(i.length)for(let t=0;t<i.length;t++)i[t].onlyOnce||(i[t].isDone=i[t].frame<e);this._currentFrame=e;let r=this._animation._interpolate(e,this._animationState);this.setValue(r,-1)}_prepareForSpeedRatioChange(e){let t=this._previousElapsedTime*(this._animation.framePerSecond*e)/1e3;this._absoluteFrameOffset=this._previousAbsoluteFrame-t}animate(e,t,i,r,s,n=-1){let a,o;let l=this._animation,h=l.targetPropertyPath;if(!h||h.length<1)return this._stopped=!0,!1;let u=!0;(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(i<this._minFrame||i>this._maxFrame)&&(i=this._maxFrame);let c=i-t,d=e*(l.framePerSecond*s)/1e3+this._absoluteFrameOffset,p=0;if(r&&this._animationState.loopMode===animation_Animation.ANIMATIONLOOPMODE_YOYO){let e=(d-t)/c;d=Math.abs(Math.sin(e*Math.PI))*c+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&d>=c)u=!1,p=l._getKeyValue(this._maxValue);else if(!r&&t>=i&&d<=c)u=!1,p=l._getKeyValue(this._minValue);else if(this._animationState.loopMode!==animation_Animation.ANIMATIONLOOPMODE_CYCLE){let e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=animation_Animation.ANIMATIONLOOPMODE_CYCLE;let r=l._interpolate(t,this._animationState),s=l._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),l.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=s-r;break;case animation_Animation.ANIMATIONTYPE_QUATERNION:case animation_Animation.ANIMATIONTYPE_VECTOR3:case animation_Animation.ANIMATIONTYPE_VECTOR2:case animation_Animation.ANIMATIONTYPE_SIZE:case animation_Animation.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=s.subtract(r)}this._highLimitsCache[e]=s}p=this._highLimitsCache[e],a=this._offsetsCache[e]}if(void 0===a)switch(l.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:a=0;break;case animation_Animation.ANIMATIONTYPE_QUATERNION:a=rA;break;case animation_Animation.ANIMATIONTYPE_VECTOR3:a=rI;break;case animation_Animation.ANIMATIONTYPE_VECTOR2:a=rM;break;case animation_Animation.ANIMATIONTYPE_SIZE:a=rD;break;case animation_Animation.ANIMATIONTYPE_COLOR3:a=rO}if(this._host&&this._host.syncRoot){let e=this._host.syncRoot,i=(e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame);o=t+c*i}else o=d>0&&t>i||d<0&&t<i?u&&0!==c?i+d%c:t:u&&0!==c?t+d%c:i;let _=this._events;if(s>0&&this.currentFrame>o||s<0&&this.currentFrame<o){this._onLoop();for(let e=0;e<_.length;e++)_[e].onlyOnce||(_[e].isDone=!1);this._animationState.key=s>0?0:l.getKeys().length-1}this._currentFrame=o,this._animationState.repeatCount=0===c?0:d/c>>0,this._animationState.highLimitValue=p,this._animationState.offsetValue=a;let f=l._interpolate(o,this._animationState);if(this.setValue(f,n),_.length){for(let e=0;e<_.length;e++)if(c>0&&o>=_[e].frame&&_[e].frame>=t||c<0&&o<=_[e].frame&&_[e].frame<=t){let t=_[e];t.isDone||(t.onlyOnce&&(_.splice(e,1),e--),t.isDone=!0,t.action(o))}}return u||(this._stopped=!0),u}};var rN=i(6540),rF=i(7662),rB=i(4254),rL=i(524);let Bone=class Bone extends ry.N{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,r=null,s=null,n=null,a=null){var o;super(e,t.getScene()),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=null!==(o=null==r?void 0:r.clone())&&void 0!==o?o:rm.y3.Identity(),this._restMatrix=null!=s?s:this._localMatrix.clone(),this._bindMatrix=null!=n?n:this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new rm.y3,this._absoluteBindMatrix=new rm.y3,this._absoluteInverseBindMatrix=new rm.y3,this._finalMatrix=new rm.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){let 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){let t=rm.jp.Vector3[0],i=rm.jp.Quaternion[0],r=rm.jp.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:rm._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=rm.P.Zero(),this._localRotation=rm._f.Zero(),this._localPosition=rm.P.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,rm.y3.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e<this.children.length;e++)this.children[e]._updateAbsoluteBindMatrices();this._scalingDeterminant=0>this._absoluteBindMatrix.determinant()?-1:1}markAsDirty(){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this}_markAsDirtyAndCompose(){this.markAsDirty(),this._needToCompose=!0}_markAsDirtyAndDecompose(){this.markAsDirty(),this._needToDecompose=!0}_updatePosition(e,t=rL.T.LOCAL,i,r=!0){let s=this.getLocalMatrix();if(t==rL.T.LOCAL)r?(s.addAtIndex(12,e.x),s.addAtIndex(13,e.y),s.addAtIndex(14,e.z)):s.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let n=Bone._TmpMats[0],a=Bone._TmpVecs[0];this.parent?i&&t?(n.copyFrom(this.parent.getAbsoluteMatrix()),n.multiplyToRef(t,n)):n.copyFrom(this.parent.getAbsoluteMatrix()):rm.y3.IdentityToRef(n),r&&n.setTranslationFromFloats(0,0,0),n.invert(),rm.P.TransformCoordinatesToRef(e,n,a),r?(s.addAtIndex(12,a.x),s.addAtIndex(13,a.y),s.addAtIndex(14,a.z)):s.setTranslationFromFloats(a.x,a.y,a.z)}this._markAsDirtyAndDecompose()}translate(e,t=rL.T.LOCAL,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=rL.T.LOCAL,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,rL.T.WORLD,t)}scale(e,t,i,r=!1){let s=this.getLocalMatrix(),n=Bone._TmpMats[0];for(let r of(rm.y3.ScalingToRef(e,t,i,n),n.multiplyToRef(s,s),n.invert(),this.children)){let s=r.getLocalMatrix();s.multiplyToRef(n,s),s.multiplyAtIndex(12,e),s.multiplyAtIndex(13,t),s.multiplyAtIndex(14,i),r._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),r)for(let s of this.children)s.scale(e,t,i,r)}setScale(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()}getScale(){return this._decompose(),this._localScaling}getScaleToRef(e){this._decompose(),e.copyFrom(this._localScaling)}setYawPitchRoll(e,t,i,r=rL.T.LOCAL,s){if(r===rL.T.LOCAL){let n=Bone._TmpQuat;rm._f.RotationYawPitchRollToRef(e,t,i,n),this.setRotationQuaternion(n,r,s);return}let n=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(n,s))return;let a=Bone._TmpMats[1];rm.y3.RotationYawPitchRollToRef(e,t,i,a),n.multiplyToRef(a,a),this._rotateWithMatrix(a,r,s)}rotate(e,t,i=rL.T.LOCAL,r){let s=Bone._TmpMats[0];s.setTranslationFromFloats(0,0,0),rm.y3.RotationAxisToRef(e,t,s),this._rotateWithMatrix(s,i,r)}setAxisAngle(e,t,i=rL.T.LOCAL,r){if(i===rL.T.LOCAL){let s=Bone._TmpQuat;rm._f.RotationAxisToRef(e,t,s),this.setRotationQuaternion(s,i,r);return}let s=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,r))return;let n=Bone._TmpMats[1];rm.y3.RotationAxisToRef(e,t,n),s.multiplyToRef(n,n),this._rotateWithMatrix(n,i,r)}setRotation(e,t=rL.T.LOCAL,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=rL.T.LOCAL,i){if(t===rL.T.LOCAL){this._decompose(),this._localRotation.copyFrom(e),this._markAsDirtyAndCompose();return}let r=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=Bone._TmpMats[1];rm.y3.FromQuaternionToRef(e,s),r.multiplyToRef(s,s),this._rotateWithMatrix(s,t,i)}setRotationMatrix(e,t=rL.T.LOCAL,i){if(t===rL.T.LOCAL){let r=Bone._TmpQuat;rm._f.FromRotationMatrixToRef(e,r),this.setRotationQuaternion(r,t,i);return}let r=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=Bone._TmpMats[1];s.copyFrom(e),r.multiplyToRef(e,s),this._rotateWithMatrix(s,t,i)}_rotateWithMatrix(e,t=rL.T.LOCAL,i){let r=this.getLocalMatrix(),s=r.m[12],n=r.m[13],a=r.m[14],o=this.getParent(),l=Bone._TmpMats[3],h=Bone._TmpMats[4];o&&t==rL.T.WORLD?(i?(l.copyFrom(i.getWorldMatrix()),o.getAbsoluteMatrix().multiplyToRef(l,l)):l.copyFrom(o.getAbsoluteMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):t==rL.T.WORLD&&i?(l.copyFrom(i.getWorldMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):r.multiplyToRef(e,r),r.setTranslationFromFloats(s,n,a),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){let i=Bone._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),rm.y3.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):rm.y3.IdentityToRef(i),e.invert(),!isNaN(e.m[0])&&(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=rL.T.LOCAL,t=null){let i=rm.P.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=rL.T.LOCAL,t,i){if(e==rL.T.LOCAL){let e=this.getLocalMatrix();i.x=e.m[12],i.y=e.m[13],i.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let r=Bone._TmpMats[0];t&&e?(r.copyFrom(this.getAbsoluteMatrix()),r.multiplyToRef(e,r)):r=this.getAbsoluteMatrix(),i.x=r.m[12],i.y=r.m[13],i.z=r.m[14]}}getAbsolutePosition(e=null){let t=rm.P.Zero();return this.getPositionToRef(rL.T.WORLD,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(rL.T.WORLD,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);let e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}let e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].computeAbsoluteMatrices()}computeAbsoluteTransforms(){this.computeAbsoluteMatrices()}getDirection(e,t=null){let i=rm.P.Zero();return this.getDirectionToRef(e,t,i),i}getDirectionToRef(e,t=null,i){let r=null;t&&(r=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let s=Bone._TmpMats[0];s.copyFrom(this.getAbsoluteMatrix()),t&&r&&s.multiplyToRef(r,s),rm.P.TransformNormalToRef(e,s,i),i.normalize()}getRotation(e=rL.T.LOCAL,t=null){let i=rm.P.Zero();return this.getRotationToRef(e,t,i),i}getRotationToRef(e=rL.T.LOCAL,t=null,i){let r=Bone._TmpQuat;this.getRotationQuaternionToRef(e,t,r),r.toEulerAnglesToRef(i)}getRotationQuaternion(e=rL.T.LOCAL,t=null){let i=rm._f.Identity();return this.getRotationQuaternionToRef(e,t,i),i}getRotationQuaternionToRef(e=rL.T.LOCAL,t=null,i){if(e==rL.T.LOCAL)this._decompose(),i.copyFrom(this._localRotation);else{let e=Bone._TmpMats[0],r=this.getAbsoluteMatrix();t?r.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(r),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.decompose(void 0,i,void 0)}}getRotationMatrix(e=rL.T.LOCAL,t){let i=rm.y3.Identity();return this.getRotationMatrixToRef(e,t,i),i}getRotationMatrixToRef(e=rL.T.LOCAL,t,i){if(e==rL.T.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(i);else{let e=Bone._TmpMats[0],r=this.getAbsoluteMatrix();t?r.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(r),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.getRotationMatrixToRef(i)}}getAbsolutePositionFromLocal(e,t=null){let i=rm.P.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,i),i}getAbsolutePositionFromLocalToRef(e,t=null,i){let r=null;t&&(r=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let s=Bone._TmpMats[0];s.copyFrom(this.getAbsoluteMatrix()),t&&r&&s.multiplyToRef(r,s),rm.P.TransformCoordinatesToRef(e,s,i)}getLocalPositionFromAbsolute(e,t=null){let i=rm.P.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,i),i}getLocalPositionFromAbsoluteToRef(e,t=null,i){let r=null;t&&(r=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let s=Bone._TmpMats[0];s.copyFrom(this.getAbsoluteMatrix()),t&&r&&s.multiplyToRef(r,s),s.invert(),rm.P.TransformCoordinatesToRef(e,s,i)}setCurrentPoseAsRest(){this.setRestMatrix(this.getLocalMatrix())}};Bone._TmpVecs=rB.B.BuildArray(2,rm.P.Zero),Bone._TmpQuat=rm._f.Identity(),Bone._TmpMats=rB.B.BuildArray(5,rm.y3.Identity);let Animatable=class Animatable{get syncRoot(){return this._syncRoot}get masterFrame(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){if(-1===e){this._weight=-1;return}this._weight=Math.min(Math.max(e,0),1)}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t<this._runtimeAnimations.length;t++){let i=this._runtimeAnimations[t];i._prepareForSpeedRatioChange(e)}this._speedRatio=e,null!==this._goToFrame&&this.goToFrame(this._goToFrame)}get elapsedTime(){return null===this._localDelayOffset?0:this._scene._animationTime-this._localDelayOffset}constructor(e,t,i=0,r=100,s=!1,n=1,a,o,l,h=!1,u=0){this.target=t,this.fromFrame=i,this.toFrame=r,this.loopAnimation=s,this.onAnimationEnd=a,this.onAnimationLoop=l,this.isAdditive=h,this.playOrder=u,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=[],this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this._frameToSyncFromJump=null,this._goToFrame=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new rf.y$,this.onAnimationLoopObservable=new rf.y$,this._scene=e,o&&this.appendAnimations(t,o),this._speedRatio=n,e._activeAnimatables.push(this)}syncWith(e){if(this._syncRoot=e,e){let e=this._scene._activeAnimatables.indexOf(this);e>-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i<t.length;i++){let r=t[i],s=new RuntimeAnimation(e,r,this._scene,this);s._onLoop=()=>{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i].animation;return null}getRuntimeAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i];return null}reset(){let e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null}enableBlending(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)t[i].animation.enableBlending=!0,t[i].animation.blendingSpeed=e}disableBlending(){let e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].animation.enableBlending=!1}goToFrame(e){var t;let i=this._runtimeAnimations;if(i[0]){let r=i[0].animation.framePerSecond;this._frameToSyncFromJump=null!==(t=this._frameToSyncFromJump)&&void 0!==t?t:i[0].currentFrame;let s=0===this.speedRatio?0:(e-this._frameToSyncFromJump)/r*1e3/this.speedRatio;this._manualJumpDelay=-s}for(let t=0;t<i.length;t++)i[t].goToFrame(e);this._goToFrame=e}get paused(){return this._paused}pause(){this._paused||(this._paused=!0)}restart(){this._paused=!1}_raiseOnAnimationEnd(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)}stop(e,t,i=!1){if(e||t){let r=this._scene._activeAnimatables.indexOf(this);if(r>-1){let s=this._runtimeAnimations;for(let i=s.length-1;i>=0;i--){let r=s[i];(!e||r.animation.name==e)&&(!t||t(r.target))&&(r.dispose(),s.splice(i,1))}0==s.length&&(i||this._scene._activeAnimatables.splice(r,1),this._raiseOnAnimationEnd())}}else{let e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);let t=this._runtimeAnimations;for(let e=0;e<t.length;e++)t[e].dispose();this._runtimeAnimations.length=0,this._raiseOnAnimationEnd()}}}waitAsync(){return new Promise(e=>{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){let t;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 i=!1,r=this._runtimeAnimations;for(t=0;t<r.length;t++){let s=r[t],n=s.animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);i=i||n}if(this.animationStarted=i,!i){if(this.disposeOnEnd)for(t=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(t,1),t=0;t<r.length;t++)r[t].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return i}};rN.x.prototype._animate=function(){if(!this.animationsEnabled)return;let e=rF.F.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;let t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;let i=this._animationTime;for(let e=0;e<t.length;e++){let r=t[e];!r._animate(i)&&r.disposeOnEnd&&e--}this._processLateAnimationBindings()},rN.x.prototype.sortActiveAnimatables=function(){this._activeAnimatables.sort((e,t)=>e.playOrder-t.playOrder)},rN.x.prototype.beginWeightedAnimation=function(e,t,i,r=1,s,n=1,a,o,l,h,u=!1){let c=this.beginAnimation(e,t,i,s,n,a,o,!1,l,h,u);return c.weight=r,c},rN.x.prototype.beginAnimation=function(e,t,i,r,s=1,n,a,o=!0,l,h,u=!1){t>i&&s>0&&(s*=-1),o&&this.stopAnimation(e,void 0,l),a||(a=new Animatable(this,e,t,i,r,s,n,void 0,h,u));let c=!l||l(e);if(e.animations&&c&&a.appendAnimations(e,e.animations),e.getAnimatables){let u=e.getAnimatables();for(let e=0;e<u.length;e++)this.beginAnimation(u[e],t,i,r,s,n,a,o,l,h)}return a.reset(),a},rN.x.prototype.beginHierarchyAnimation=function(e,t,i,r,s,n=1,a,o,l=!0,h,u,c=!1){let d=e.getDescendants(t),p=[];for(let t of(p.push(this.beginAnimation(e,i,r,s,n,a,o,l,h,void 0,c)),d))p.push(this.beginAnimation(t,i,r,s,n,a,o,l,h,void 0,c));return p},rN.x.prototype.beginDirectAnimation=function(e,t,i,r,s,n,a,o,l=!1){if(void 0===n&&(n=1),i>r&&n>0)n*=-1;else if(r>i&&n<0){let e=r;r=i,i=e}let h=new Animatable(this,e,i,r,s,n,a,t,o,l);return h},rN.x.prototype.beginDirectHierarchyAnimation=function(e,t,i,r,s,n,a,o,l,h=!1){let u=e.getDescendants(t),c=[];for(let t of(c.push(this.beginDirectAnimation(e,i,r,s,n,a,o,l,h)),u))c.push(this.beginDirectAnimation(t,i,r,s,n,a,o,l,h));return c},rN.x.prototype.getAnimatableByTarget=function(e){for(let t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},rN.x.prototype.getAllAnimatablesByTarget=function(e){let t=[];for(let i=0;i<this._activeAnimatables.length;i++)this._activeAnimatables[i].target===e&&t.push(this._activeAnimatables[i]);return t},rN.x.prototype.stopAnimation=function(e,t,i){let r=this.getAllAnimatablesByTarget(e);for(let e of r)e.stop(t,i)},rN.x.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(let e=0;e<this._activeAnimatables.length;e++)this._activeAnimatables[e].stop(void 0,void 0,!0);this._activeAnimatables.length=0}for(let e of this.animationGroups)e.stop()},rN.x.prototype._registerTargetForLateAnimationBinding=function(e,t){let i=e.target;this._registeredForLateAnimationBindings.pushNoDuplicate(i),i._lateAnimationHolders||(i._lateAnimationHolders={}),i._lateAnimationHolders[e.targetPath]||(i._lateAnimationHolders[e.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:t}),e.isAdditive?(i._lateAnimationHolders[e.targetPath].additiveAnimations.push(e),i._lateAnimationHolders[e.targetPath].totalAdditiveWeight+=e.weight):(i._lateAnimationHolders[e.targetPath].animations.push(e),i._lateAnimationHolders[e.targetPath].totalWeight+=e.weight)},rN.x.prototype._processLateAnimationBindingsForMatrices=function(e){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return e.originalValue;let t=1,i=rm.jp.Vector3[0],r=rm.jp.Vector3[1],s=rm.jp.Quaternion[0],n=0,a=e.animations[0],o=e.originalValue,l=1,h=!1;if(e.totalWeight<1)l=1-e.totalWeight,o.decompose(r,s,i);else{if(n=1,t=e.totalWeight,1==(l=a.weight/t)){if(!e.totalAdditiveWeight)return a.currentValue;h=!0}a.currentValue.decompose(r,s,i)}if(!h){r.scaleInPlace(l),i.scaleInPlace(l),s.scaleInPlace(l);for(let a=n;a<e.animations.length;a++){let n=e.animations[a];if(0===n.weight)continue;l=n.weight/t;let o=rm.jp.Vector3[2],h=rm.jp.Vector3[3],u=rm.jp.Quaternion[1];n.currentValue.decompose(h,u,o),h.scaleAndAddToRef(l,r),u.scaleAndAddToRef(rm._f.Dot(s,u)>0?l:-l,s),o.scaleAndAddToRef(l,i)}s.normalize()}for(let t=0;t<e.additiveAnimations.length;t++){let n=e.additiveAnimations[t];if(0===n.weight)continue;let a=rm.jp.Vector3[2],o=rm.jp.Vector3[3],l=rm.jp.Quaternion[1];n.currentValue.decompose(o,l,a),o.multiplyToRef(r,o),rm.P.LerpToRef(r,o,n.weight,r),s.multiplyToRef(l,l),rm._f.SlerpToRef(s,l,n.weight,s),a.scaleAndAddToRef(n.weight,i)}let u=a?a._animationState.workValue:rm.jp.Matrix[0].clone();return rm.y3.ComposeToRef(r,s,i,u),u},rN.x.prototype._processLateAnimationBindingsForQuaternions=function(e,t){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return t;let i=e.animations[0],r=e.originalValue,s=t;if(0===e.totalWeight&&e.totalAdditiveWeight>0)s.copyFrom(r);else if(1===e.animations.length){if(rm._f.SlerpToRef(r,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,n,a=1;if(e.totalWeight<1){let t=1-e.totalWeight;n=[],(i=[]).push(r),n.push(t)}else{if(2===e.animations.length&&(rm._f.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],a=e.totalWeight}for(let t=0;t<e.animations.length;t++){let r=e.animations[t];i.push(r.currentValue),n.push(r.weight/a)}let o=0;for(let e=0;e<i.length;){if(!e){rm._f.SlerpToRef(i[e],i[e+1],n[e+1]/(n[e]+n[e+1]),t),s=t,o=n[e]+n[e+1],e+=2;continue}o+=n[e],rm._f.SlerpToRef(s,i[e],n[e]/o,s),e++}}for(let t=0;t<e.additiveAnimations.length;t++){let i=e.additiveAnimations[t];0!==i.weight&&(s.multiplyToRef(i.currentValue,rm.jp.Quaternion[0]),rm._f.SlerpToRef(s,rm.jp.Quaternion[0],i.weight,s))}return s},rN.x.prototype._processLateAnimationBindings=function(){if(this._registeredForLateAnimationBindings.length){for(let e=0;e<this._registeredForLateAnimationBindings.length;e++){let t=this._registeredForLateAnimationBindings.data[e];for(let e in t._lateAnimationHolders){let i=t._lateAnimationHolders[e],r=i.animations[0],s=i.originalValue;if(null==s)continue;let n=animation_Animation.AllowMatrixDecomposeForInterpolation&&s.m,a=t[e];if(n)a=this._processLateAnimationBindingsForMatrices(i);else{let e=void 0!==s.w;if(e)a=this._processLateAnimationBindingsForQuaternions(i,a||rm._f.Identity());else{let e=0,t=1;if(i.totalWeight<1)a=r&&s.scale?s.scale(1-i.totalWeight):r?s*(1-i.totalWeight):s.clone?s.clone():s;else if(r){t=i.totalWeight;let s=r.weight/t;a=1!==s?r.currentValue.scale?r.currentValue.scale(s):r.currentValue*s:r.currentValue,e=1}for(let r=e;r<i.animations.length;r++){let e=i.animations[r],s=e.weight/t;s&&(e.currentValue.scaleAndAddToRef?e.currentValue.scaleAndAddToRef(s,a):a+=e.currentValue*s)}for(let e=0;e<i.additiveAnimations.length;e++){let t=i.additiveAnimations[e],r=t.weight;r&&(t.currentValue.scaleAndAddToRef?t.currentValue.scaleAndAddToRef(r,a):a+=t.currentValue*r)}}}t[e]=a}t._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}},Bone.prototype.copyAnimationRange=function(e,t,i,r=!1,s=null){let n,a,o;0===this.animations.length&&(this.animations.push(new animation_Animation(this.name,"_matrix",e.animations[0].framePerSecond,animation_Animation.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));let l=e.animations[0].getRange(t);if(!l)return!1;let h=l.from,u=l.to,c=e.animations[0].getKeys(),d=e.length,p=e.getParent(),_=this.getParent(),f=r&&p&&d&&this.length&&d!==this.length,m=f&&_&&p?_.length/p.length:1,g=r&&!_&&s&&(1!==s.x||1!==s.y||1!==s.z),v=this.animations[0].getKeys();for(let e=0,t=c.length;e<t;e++)(n=c[e]).frame>=h&&n.frame<=u&&(r?(o=n.value.clone(),f?(a=o.getTranslation(),o.setTranslation(a.scaleInPlace(m))):g&&s?(a=o.getTranslation(),o.setTranslation(a.multiplyInPlace(s))):o=n.value):o=n.value,v.push({frame:n.frame+i,value:o}));return this.animations[0].createRange(t,h+i,u+i),!0};var rw=i(9806);(a=tp||(tp={}))[a.CW=0]="CW",a[a.CCW=1]="CCW";let Angle=class Angle{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){let i=t.subtract(e),r=Math.atan2(i.y,i.x);return new Angle(r)}static FromRadians(e){return new Angle(e)}static FromDegrees(e){return new Angle(e*Math.PI/180)}};let Arc2=class Arc2{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;let r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,n=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new rm.FM((s*(t.y-i.y)-n*(e.y-t.y))/a,((e.x-t.x)*n-(t.x-i.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Angle.BetweenTwoPoints(this.centerPoint,this.startPoint);let o=this.startAngle.degrees(),l=Angle.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=Angle.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-o>180&&(l-=360),l-o<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-o<0?tp.CW:tp.CCW,this.angle=Angle.FromDegrees(this.orientation===tp.CW?o-h:h-o)}};let math_path_Path2=class math_path_Path2{constructor(e,t){this._points=[],this._length=0,this.closed=!1,this._points.push(new rm.FM(e,t))}addLineTo(e,t){if(this.closed)return this;let i=new rm.FM(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;let n=this._points[this._points.length-1],a=new rm.FM(e,t),o=new rm.FM(i,r),l=new Arc2(n,a,o),h=l.angle.radians()/s;l.orientation===tp.CW&&(h*=-1);let u=l.startAngle.radians()+h;for(let e=0;e<s;e++){let e=Math.cos(u)*l.radius+l.centerPoint.x,t=Math.sin(u)*l.radius+l.centerPoint.y;this.addLineTo(e,t),u+=h}return this}addQuadraticCurveTo(e,t,i,r,s=36){if(this.closed)return this;let equation=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r,n=this._points[this._points.length-1];for(let a=0;a<=s;a++){let o=a/s,l=equation(o,n.x,e,i),h=equation(o,n.y,t,r);this.addLineTo(l,h)}return this}addBezierCurveTo(e,t,i,r,s,n,a=36){if(this.closed)return this;let equation=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s,o=this._points[this._points.length-1];for(let l=0;l<=a;l++){let h=l/a,u=equation(h,o.x,e,i,s),c=equation(h,o.y,t,r,n);this.addLineTo(u,c)}return this}isPointInside(e){let t=!1,i=this._points.length;for(let r=i-1,s=0;s<i;r=s++){let i=this._points[r],n=this._points[s],a=n.x-i.x,o=n.y-i.y;if(Math.abs(o)>Number.EPSILON){if(o<0&&(i=this._points[s],a=-a,n=this._points[r],o=-o),e.y<i.y||e.y>n.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{let r=o*(e.x-i.x)-a*(e.y-i.y);if(0===r)return!0;if(r<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){let t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){let e=this._points.length,t=0;for(let i=e-1,r=0;r<e;i=r++)t+=this._points[i].x*this._points[r].y-this._points[r].x*this._points[i].y;return .5*t}getPoints(){return this._points}getPointAtLengthPosition(e){if(e<0||e>1)return rm.FM.Zero();let t=e*this.length(),i=0;for(let e=0;e<this._points.length;e++){let r=(e+1)%this._points.length,s=this._points[e],n=this._points[r],a=n.subtract(s),o=a.length()+i;if(t>=i&&t<=o){let e=a.normalize(),r=t-i;return new rm.FM(s.x+e.x*r,s.y+e.y*r)}i=o}return rm.FM.Zero()}static StartingAt(e,t){return new math_path_Path2(e,t)}};let Path3D=class Path3D{constructor(e,t=null,i,r=!1){this.path=e,this._curve=[],this._distances=[],this._tangents=[],this._normals=[],this._binormals=[],this._pointAtData={id:0,point:rm.P.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:rm.y3.Identity()};for(let t=0;t<e.length;t++)this._curve[t]=e[t].clone();this._raw=i||!1,this._alignTangentsWithPath=r,this._compute(t,r)}getCurve(){return this._curve}getPoints(){return this._curve}length(){return this._distances[this._distances.length-1]}getTangents(){return this._tangents}getNormals(){return this._normals}getBinormals(){return this._binormals}getDistances(){return this._distances}getPointAt(e){return this._updatePointAtData(e).point}getTangentAt(e,t=!1){return this._updatePointAtData(e,t),t?rm.P.TransformCoordinates(rm.P.Forward(),this._pointAtData.interpolationMatrix):this._tangents[this._pointAtData.previousPointArrayIndex]}getNormalAt(e,t=!1){return this._updatePointAtData(e,t),t?rm.P.TransformCoordinates(rm.P.Right(),this._pointAtData.interpolationMatrix):this._normals[this._pointAtData.previousPointArrayIndex]}getBinormalAt(e,t=!1){return this._updatePointAtData(e,t),t?rm.P.TransformCoordinates(rm.P.UpReadOnly,this._pointAtData.interpolationMatrix):this._binormals[this._pointAtData.previousPointArrayIndex]}getDistanceAt(e){return this.length()*e}getPreviousPointIndexAt(e){return this._updatePointAtData(e),this._pointAtData.previousPointArrayIndex}getSubPositionAt(e){return this._updatePointAtData(e),this._pointAtData.subPosition}getClosestPositionTo(e){let t=Number.MAX_VALUE,i=0;for(let r=0;r<this._curve.length-1;r++){let s=this._curve[r+0],n=this._curve[r+1].subtract(s).normalize(),a=this._distances[r+1]-this._distances[r+0],o=Math.min(Math.max(rm.P.Dot(n,e.subtract(s).normalize()),0)*rm.P.Distance(s,e)/a,1),l=rm.P.Distance(s.add(n.scale(o*a)),e);l<t&&(t=l,i=(this._distances[r+0]+a*o)/this.length())}return i}slice(e=0,t=1){if(e<0&&(e=1- -1*e%1),t<0&&(t=1- -1*t%1),e>t){let i=e;e=t,t=i}let i=this.getCurve(),r=this.getPointAt(e),s=this.getPreviousPointIndexAt(e),n=this.getPointAt(t),a=this.getPreviousPointIndexAt(t)+1,o=[];return 0!==e&&(s++,o.push(r)),o.push(...i.slice(s,a)),(1!==t||1===e)&&o.push(n),new Path3D(o,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;t<e.length;t++)this._curve[t].x=e[t].x,this._curve[t].y=e[t].y,this._curve[t].z=e[t].z;return this._compute(t,i),this}_compute(e,t=!1){let i,r,s,n,a;let o=this._curve.length;if(o<2)return;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[o-1]=this._curve[o-1].subtract(this._curve[o-2]),this._raw||this._tangents[o-1].normalize();let l=this._tangents[0],h=this._normalVector(l,e);this._normals[0]=h,this._raw||this._normals[0].normalize(),this._binormals[0]=rm.P.Cross(l,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(let e=1;e<o;e++)i=this._getLastNonNullVector(e),e<o-1&&(r=this._getFirstNonNullVector(e),this._tangents[e]=t?r:i.add(r),this._tangents[e].normalize()),this._distances[e]=this._distances[e-1]+this._curve[e].subtract(this._curve[e-1]).length(),s=this._tangents[e],a=this._binormals[e-1],this._normals[e]=rm.P.Cross(a,s),this._raw||(0===this._normals[e].length()?(n=this._normals[e-1],this._normals[e]=n.clone()):this._normals[e].normalize()),this._binormals[e]=rm.P.Cross(s,this._normals[e]),this._raw||this._binormals[e].normalize();this._pointAtData.id=NaN}_getFirstNonNullVector(e){let t=1,i=this._curve[e+t].subtract(this._curve[e]);for(;0===i.length()&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i}_getLastNonNullVector(e){let t=1,i=this._curve[e].subtract(this._curve[e-t]);for(;0===i.length()&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i;let r=e.length();if(0===r&&(r=1),null==t){let t;t=rE.R.WithinEpsilon(Math.abs(e.y)/r,1,rw.kn)?rE.R.WithinEpsilon(Math.abs(e.x)/r,1,rw.kn)?rE.R.WithinEpsilon(Math.abs(e.z)/r,1,rw.kn)?rm.P.Zero():new rm.P(0,0,1):new rm.P(1,0,0):new rm.P(0,-1,0),i=rm.P.Cross(e,t)}else i=rm.P.Cross(e,t),rm.P.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){let i;if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;let r=this.getPoints();if(e<=0)return this._setPointAtData(0,0,r[0],0,t);if(e>=1)return this._setPointAtData(1,1,r[r.length-1],r.length-1,t);let s=r[0],n=0,a=e*this.length();for(let o=1;o<r.length;o++){i=r[o];let l=rm.P.Distance(s,i);if((n+=l)===a)return this._setPointAtData(e,1,i,o,t);if(n>a){let r=n-a,h=r/l,u=s.subtract(i),c=i.add(u.scaleInPlace(h));return this._setPointAtData(e,1-h,c,o-1,t)}s=i}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=rm.y3.Identity();let e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){let t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),n=this._tangents[t].clone(),a=this._normals[t].clone(),o=this._binormals[t].clone(),l=rm._f.RotationQuaternionFromAxis(r,s,i),h=rm._f.RotationQuaternionFromAxis(a,o,n),u=rm._f.Slerp(l,h,this._pointAtData.subPosition);u.toRotationMatrix(this._pointAtData.interpolationMatrix)}}};let Curve3=class Curve3{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;let s=[],equation=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;for(let n=0;n<=r;n++)s.push(new rm.P(equation(n/r,e.x,t.x,i.x),equation(n/r,e.y,t.y,i.y),equation(n/r,e.z,t.z,i.z)));return new Curve3(s)}static CreateCubicBezier(e,t,i,r,s){s=s>3?s:4;let n=[],equation=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s;for(let a=0;a<=s;a++)n.push(new rm.P(equation(a/s,e.x,t.x,i.x,r.x),equation(a/s,e.y,t.y,i.y,r.y),equation(a/s,e.z,t.z,i.z,r.z)));return new Curve3(n)}static CreateHermiteSpline(e,t,i,r,s){let n=[],a=1/s;for(let o=0;o<=s;o++)n.push(rm.P.Hermite(e,t,i,r,o*a));return new Curve3(n)}static CreateCatmullRomSpline(e,t,i){let r=[],s=1/t,n=0;if(i){let i=e.length;for(let a=0;a<i;a++){n=0;for(let o=0;o<t;o++)r.push(rm.P.CatmullRom(e[a%i],e[(a+1)%i],e[(a+2)%i],e[(a+3)%i],n)),n+=s}r.push(r[0])}else{let i=[];i.push(e[0].clone()),Array.prototype.push.apply(i,e),i.push(e[e.length-1].clone());let a=0;for(;a<i.length-3;a++){n=0;for(let e=0;e<t;e++)r.push(rm.P.CatmullRom(i[a],i[a+1],i[a+2],i[a+3],n)),n+=s}a--,r.push(rm.P.CatmullRom(i[a],i[a+1],i[a+2],i[a+3],n))}return new Curve3(r)}static ArcThru3Points(e,t,i,r=32,s=!1,n=!1){let a=[],o=t.subtract(e),l=i.subtract(t),h=e.subtract(i),u=rm.P.Cross(o,l),c=u.length();if(c<1e-8)return new Curve3(a);let d=o.lengthSquared(),p=l.lengthSquared(),_=h.lengthSquared(),f=u.lengthSquared(),m=o.length(),g=l.length(),v=h.length(),x=.5*m*g*v/c,T=rm.P.Dot(o,h),S=rm.P.Dot(o,l),C=rm.P.Dot(l,h),E=e.scale(-.5*p*T/f).add(t.scale(-.5*_*S/f)).add(i.scale(-.5*d*C/f)),b=e.subtract(E),y=b.normalize(),P=rm.P.Cross(u,y).normalize();if(n){let t=2*Math.PI/r;for(let e=0;e<=2*Math.PI;e+=t)a.push(E.add(y.scale(x*Math.cos(e)).add(P.scale(x*Math.sin(e)))));a.push(e)}else{let t=1/r,n=0,o=rm.P.Zero();do o=E.add(y.scale(x*Math.cos(n)).add(P.scale(x*Math.sin(n)))),a.push(o),n+=t;while(!o.equalsWithEpsilon(i,x*t*1.1));a.push(i),s&&a.push(e)}return new Curve3(a)}constructor(e){this._length=0,this._points=e,this._length=this._computeLength(e)}getPoints(){return this._points}length(){return this._length}continue(e){let t=this._points[this._points.length-1],i=this._points.slice(),r=e.getPoints();for(let e=1;e<r.length;e++)i.push(r[e].subtract(r[0]).add(t));let s=new Curve3(i);return s}_computeLength(e){let t=0;for(let i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t}};let EasingFunction=class EasingFunction{constructor(){this._easingMode=EasingFunction.EASINGMODE_EASEIN}setEasingMode(e){this._easingMode=Math.min(Math.max(e,0),2)}getEasingMode(){return this._easingMode}easeInCore(e){throw Error("You must implement this method")}ease(e){switch(this._easingMode){case EasingFunction.EASINGMODE_EASEIN:return this.easeInCore(e);case EasingFunction.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?(1-this.easeInCore((1-e)*2))*.5+.5:.5*this.easeInCore(2*e)}};EasingFunction.EASINGMODE_EASEIN=0,EasingFunction.EASINGMODE_EASEOUT=1,EasingFunction.EASINGMODE_EASEINOUT=2;let CircleEase=class CircleEase extends EasingFunction{easeInCore(e){return 1-Math.sqrt(1-(e=Math.max(0,Math.min(1,e)))*e)}};let BackEase=class BackEase extends EasingFunction{constructor(e=1){super(),this.amplitude=e}easeInCore(e){let t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}};let ExponentialEase=class ExponentialEase extends EasingFunction{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)}};let QuadraticEase=class QuadraticEase extends EasingFunction{easeInCore(e){return e*e}};let SineEase=class SineEase extends EasingFunction{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}};var rU=i(1803);let TargetedAnimation=class TargetedAnimation{getClassName(){return"TargetedAnimation"}serialize(){let e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}};let AnimationGroup=class AnimationGroup{syncWithMask(){if(!this.mask){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let e=0;e<this._animatables.length;++e){let t=this._animatables[e];this.mask.retainsTarget(t.target.name)?(this._numActiveAnimatables++,t.paused&&t.restart()):t.paused||t.pause()}}removeUnmaskedAnimations(){if(this.mask){for(let e=0;e<this._animatables.length;++e){let t=this._animatables[e];!this.mask.retainsTarget(t.target.name)&&(t.stop(),this._animatables.splice(e,1),--e)}for(let e=0;e<this._targetedAnimations.length;e++){let t=this._targetedAnimations[e];!this.mask.retainsTarget(t.target.name)&&(this._targetedAnimations.splice(e,1),--e)}}}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;e<this._animatables.length;e++){let t=this._animatables[e];t.speedRatio=this._speedRatio}}}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.loopAnimation=this._loopAnimation}}}get isAdditive(){return this._isAdditive}set isAdditive(e){if(this._isAdditive!==e){this._isAdditive=e;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.isAdditive=this._isAdditive}}}get weight(){return this._weight}set weight(e){this._weight!==e&&(this._weight=e,this.setWeightForAllAnimatables(this._weight))}get targetedAnimations(){return this._targetedAnimations}get animatables(){return this._animatables}get children(){return this._targetedAnimations}get playOrder(){return this._playOrder}set playOrder(e){if(this._playOrder!==e&&(this._playOrder=e,this._animatables.length>0)){for(let e=0;e<this._animatables.length;e++)this._animatables[e].playOrder=this._playOrder;this._scene.sortActiveAnimatables()}}get enableBlending(){return this._enableBlending}set enableBlending(e){if(this._enableBlending!==e&&(this._enableBlending=e,null!==e))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=e}get blendingSpeed(){return this._blendingSpeed}set blendingSpeed(e){if(this._blendingSpeed!==e&&(this._blendingSpeed=e,null!==e))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.blendingSpeed=e}getLength(e,t){e=null!=e?e:this._from,t=null!=t?t:this._to;let i=this.targetedAnimations[0].animation.framePerSecond*this._speedRatio;return(t-e)/i}static MergeAnimationGroups(e,t=!0,i=!1,r){if(0===e.length)return null;r=null!=r?r:e[0].weight;let s=Number.MAX_VALUE,n=-Number.MAX_VALUE;if(i)for(let t of e)t.from<s&&(s=t.from),t.to>n&&(n=t.to);let a=new AnimationGroup(e[0].name+"_merged",e[0]._scene,r);for(let r of e){for(let e of(i&&r.normalize(s,n),r.targetedAnimations))a.addTargetedAnimation(e.animation,e.target);t&&r.dispose()}return a}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=[],this._animatables=[],this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new rf.y$,this.onAnimationLoopObservable=new rf.y$,this.onAnimationGroupLoopObservable=new rf.y$,this.onAnimationGroupEndObservable=new rf.y$,this.onAnimationGroupPauseObservable=new rf.y$,this.onAnimationGroupPlayObservable=new rf.y$,this.metadata=null,this._animationLoopFlags=[],this._scene=t||rS.l.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){let i=new TargetedAnimation;i.animation=e,i.target=t;let r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to<r[r.length-1].frame&&(this._to=r[r.length-1].frame),null!==this._enableBlending&&(e.enableBlending=this._enableBlending),null!==this._blendingSpeed&&(e.blendingSpeed=this._blendingSpeed),this._targetedAnimations.push(i),i}removeTargetedAnimation(e){for(let t=this._targetedAnimations.length-1;t>-1;t--){let i=this._targetedAnimations[t];i.animation===e&&this._targetedAnimations.splice(t,1)}}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;i<this._targetedAnimations.length;i++){let r=this._targetedAnimations[i],s=r.animation.getKeys(),n=s[0],a=s[s.length-1];if(n.frame>e){let t={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};s.splice(0,0,t)}if(a.frame<t){let e={frame:t,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};s.push(e)}}return this._from=e,this._to=t,this}_processLoop(e,t,i){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount!==this._numActiveAnimatables||(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n<this._targetedAnimations.length;n++){let a=this._targetedAnimations[n],o=this._scene.beginDirectAnimation(a.target,[a.animation],void 0!==i?i:this._from,void 0!==r?r:this._to,e,t,void 0,void 0,void 0!==s?s:this._isAdditive);o.weight=this._weight,o.playOrder=this._playOrder,o.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(a),this._checkAnimationGroupEnded(o)},this._processLoop(o,a,n),this._animatables.push(o)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.pause()}return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length===this._targetedAnimations.length?(void 0!==e&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this._isPaused=!1,this}reset(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(),this;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.reset()}return this}restart(){if(!this._isStarted)return this;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.restart()}return this.onAnimationGroupPlayObservable.notifyObservers(this),this}stop(){if(!this._isStarted)return this;let e=this._animatables.slice();for(let t=0;t<e.length;t++)e[t].stop(void 0,void 0,!0);let t=0;for(let e=0;e<this._scene._activeAnimatables.length;e++){let i=this._scene._activeAnimatables[e];i._runtimeAnimations.length>0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.weight=e}return this}syncAllAnimationsWith(e){for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.syncWith(e)}return this}goToFrame(e){if(!this._isStarted)return this;for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.goToFrame(e)}return this}dispose(){this._targetedAnimations.length=0,this._animatables.length=0;let e=this._scene.animationGroups.indexOf(this);if(e>-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){let 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){let 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){let r=new AnimationGroup(e||this.name,this._scene,this._weight,this._playOrder);for(let e of(r._from=this.from,r._to=this.to,r._speedRatio=this.speedRatio,r._loopAnimation=this.loopAnimation,r._isAdditive=this.isAdditive,r._enableBlending=this.enableBlending,r._blendingSpeed=this.blendingSpeed,r.metadata=this.metadata,r.mask=this.mask,this._targetedAnimations))r.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return r}serialize(){let e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){let i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return rU.$&&rU.$.HasTags(this)&&(e.tags=rU.$.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t){let i=new AnimationGroup(e.name,t,e.weight,e.playOrder);for(let r=0;r<e.targetedAnimations.length;r++){let s=e.targetedAnimations[r],n=animation_Animation.Parse(s.animation),a=s.targetId;if("influence"===s.animation.property){let e=t.getMorphTargetById(a);e&&i.addTargetedAnimation(n,e)}else{let e=t.getNodeById(a);null!=e&&i.addTargetedAnimation(n,e)}}return rU.$&&rU.$.AddTagsTo(i,e.tags),null!==e.from&&null!==e.to&&i.normalize(e.from,e.to),void 0!==e.speedRatio&&(i._speedRatio=e.speedRatio),void 0!==e.loopAnimation&&(i._loopAnimation=e.loopAnimation),void 0!==e.isAdditive&&(i._isAdditive=e.isAdditive),void 0!==e.weight&&(i._weight=e.weight),void 0!==e.playOrder&&(i._playOrder=e.playOrder),void 0!==e.enableBlending&&(i._enableBlending=e.enableBlending),void 0!==e.blendingSpeed&&(i._blendingSpeed=e.blendingSpeed),void 0!==e.metadata&&(i.metadata=e.metadata),i}static MakeAnimationAdditive(e,t,i,r=!1,s){let n;let a=e;(n="object"==typeof t?t:{referenceFrame:t,range:i,cloneOriginalAnimationGroup:r,clonedAnimationName:s}).cloneOriginalAnimationGroup&&(a=e.clone(n.clonedAnimationGroupName||a.name));let o=a.targetedAnimations;for(let e=0;e<o.length;e++){let t=o[e];t.animation=animation_Animation.MakeAnimationAdditive(t.animation,n)}if(a.isAdditive=!0,n.clipKeys){let e=Number.MAX_VALUE,t=-Number.MAX_VALUE,i=a.targetedAnimations;for(let r=0;r<i.length;r++){let s=i[r],n=s.animation,a=n.getKeys();e>a[0].frame&&(e=a[0].frame),t<a[a.length-1].frame&&(t=a[a.length-1].frame)}a._from=e,a._to=t}return a}static ClipKeys(e,t,i,r,s){let n=e.clone(r||e.name);return AnimationGroup.ClipKeysInPlace(n,t,i,s)}static ClipKeysInPlace(e,t,i,r){return AnimationGroup.ClipInPlace(e,t,i,r,!1)}static ClipFrames(e,t,i,r,s){let n=e.clone(r||e.name);return AnimationGroup.ClipFramesInPlace(n,t,i,s)}static ClipFramesInPlace(e,t,i,r){return AnimationGroup.ClipInPlace(e,t,i,r,!0)}static ClipInPlace(e,t,i,r,s=!1){let n=Number.MAX_VALUE,a=-Number.MAX_VALUE,o=e.targetedAnimations;for(let e=0;e<o.length;e++){let l=o[e],h=r?l.animation:l.animation.clone();s&&(h.createKeyForFrame(t),h.createKeyForFrame(i));let u=h.getKeys(),c=[],d=Number.MAX_VALUE;for(let e=0;e<u.length;e++){let r=u[e];if(!s&&e>=t&&e<=i||s&&r.frame>=t&&r.frame<=i){let e={frame:r.frame,value:r.value.clone?r.value.clone():r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation,lockedTangent:r.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,c.push(e)}}if(0===c.length){o.splice(e,1),e--;continue}n>c[0].frame&&(n=c[0].frame),a<c[c.length-1].frame&&(a=c[c.length-1].frame),h.setKeys(c,!0),l.animation=h}return e._from=n,e._to=a,e}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from+", to: "+this._to+", isStarted: "+this._isStarted+", speedRatio: "+this._speedRatio+", targetedAnimations length: "+this._targetedAnimations.length+", animatables length: "+this._animatables),t}};(o=t_||(t_={}))[o.Include=0]="Include",o[o.Exclude=1]="Exclude";var rV=i(3249),rk=i(8061),rG=i(7042),rz=i(1295),rW=i(5132);rV.Kj._instancedMeshFactory=(e,t)=>{let i=new instancedMesh_InstancedMesh(e,t);if(t.instancedBuffers)for(let e in i.instancedBuffers={},t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e];return i};let instancedMesh_InstancedMesh=class instancedMesh_InstancedMesh extends rG.x{constructor(e,t){for(let i of(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(),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&&rW.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&&rW.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&&rW.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&&rW.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&&rT.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,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i=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||rT.Y.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){let i=this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0;if(i)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!==rk.Y.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new rm.y3);let e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,rm.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(rm.jp.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;let t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){let t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this}_generatePointsArray(){return this._sourceMesh._generatePointsArray()}_updateBoundingInfo(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}clone(e,t=null,i,r){let s=(r||this._sourceMesh).createInstance(e);if(rC.j.DeepCopy(this,s,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo"],[]),this.refreshBoundingInfo(),t&&(s.parent=t),!i)for(let e=0;e<this.getScene().meshes.length;e++){let t=this.getScene().meshes[e];t.parent===this&&t.clone(t.name,s)}return s.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(s),s}dispose(e,t=!1){this._sourceMesh.removeInstance(this),super.dispose(e,t)}_serializeAsParent(e){super._serializeAsParent(e),e.parentId=this._sourceMesh.uniqueId,e.parentInstanceIndex=this._indexInSourceMeshInstanceArray}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);for(let e of(r&&i&&i(this,r),this.getChildTransformNodes(!0)))e.instantiateHierarchy(r,t,i);return r}};rV.Kj.prototype.registerInstancedBuffer=function(e,t){var i,r;if(null===(r=null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])||void 0===r||r.dispose(),!this.instancedBuffers)for(let e of(this.instancedBuffers={},this.instances))e.instancedBuffers={};for(let i of(this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this.instancedBuffers[e]=null,this._userInstancedBuffersStorage.strides[e]=t,this._userInstancedBuffersStorage.sizes[e]=32*t,this._userInstancedBuffersStorage.data[e]=new Float32Array(this._userInstancedBuffersStorage.sizes[e]),this._userInstancedBuffersStorage.vertexBuffers[e]=new rz.o(this.getEngine(),this._userInstancedBuffersStorage.data[e],e,!0,!1,t,!0),this.instances))i.instancedBuffers[e]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()},rV.Kj.prototype._processInstancedBuffers=function(e,t){let i=e?e.length:0;for(let r in this.instancedBuffers){let s=this._userInstancedBuffersStorage.sizes[r],n=this._userInstancedBuffersStorage.strides[r],a=(i+1)*n;for(;s<a;)s*=2;this._userInstancedBuffersStorage.data[r].length!=s&&(this._userInstancedBuffersStorage.data[r]=new Float32Array(s),this._userInstancedBuffersStorage.sizes[r]=s,this._userInstancedBuffersStorage.vertexBuffers[r]&&(this._userInstancedBuffersStorage.vertexBuffers[r].dispose(),this._userInstancedBuffersStorage.vertexBuffers[r]=null));let o=this._userInstancedBuffersStorage.data[r],l=0;if(t){let e=this.instancedBuffers[r];e.toArray?e.toArray(o,l):e.copyToArray?e.copyToArray(o,l):o[l]=e,l+=n}for(let t=0;t<i;t++){let i=e[t],s=i.instancedBuffers[r];s.toArray?s.toArray(o,l):s.copyToArray?s.copyToArray(o,l):o[l]=s,l+=n}this._userInstancedBuffersStorage.vertexBuffers[r]?this._userInstancedBuffersStorage.vertexBuffers[r].updateDirectly(o,0):(this._userInstancedBuffersStorage.vertexBuffers[r]=new rz.o(this.getEngine(),this._userInstancedBuffersStorage.data[r],r,!0,!1,n,!0),this._invalidateInstanceVertexArrayObject())}},rV.Kj.prototype._invalidateInstanceVertexArrayObject=function(){if(this._userInstancedBuffersStorage&&void 0!==this._userInstancedBuffersStorage.vertexArrayObjects){for(let e in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[e]);this._userInstancedBuffersStorage.vertexArrayObjects={}}},rV.Kj.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(let e in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[e]&&this._userInstancedBuffersStorage.vertexBuffers[e].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}};var rH=i(9956),rX=i(9691),rY=i(6972);let light_Light=class light_Light extends ry.N{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}constructor(e,t){super(e,t),this.diffuse=new rg.Wo(1,1,1),this.specular=new rg.Wo(1,1,1),this.falloffType=light_Light.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=light_Light.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=[],this._includedOnlyMeshesIds=[],this._isLight=!0,this.getScene().addLight(this),this._uniformBuffer=new rX.M(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,r,s=!0){var n;let a=e.toString(),o=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+a),this._renderId!==t.getRenderId()||this._lastUseSpecular!==r||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=r;let e=this.getScaledIntensity();this.transferToEffect(i,a),this.diffuse.scaleToRef(e,rg.zZ.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",rg.zZ.Color3[0],this.range,a),r&&(this.specular.scaleToRef(e,rg.zZ.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",rg.zZ.Color3[1],this.radius,a)),o=!0}if(this.transferTexturesToEffect(i,a),t.shadowsEnabled&&this.shadowEnabled&&s){let e=null!==(n=this.getShadowGenerator(t.activeCamera))&&void 0!==n?n:this.getShadowGenerator();e&&(e.bindShadowLight(a,i),o=!0)}o?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}_syncParentEnabledState(){super._syncParentEnabledState(),this.isDisposed()||this._resyncMeshes()}setEnabled(e){super.setEnabled(e),this._resyncMeshes()}getShadowGenerator(e=null){var t;return null===this._shadowGenerators?null:null!==(t=this._shadowGenerators.get(e))&&void 0!==t?t:null}getShadowGenerators(){return this._shadowGenerators}getAbsolutePosition(){return rm.P.Zero()}canAffectMesh(e){return!e||(!this.includedOnlyMeshes||!(this.includedOnlyMeshes.length>0)||-1!==this.includedOnlyMeshes.indexOf(e))&&(!this.excludedMeshes||!(this.excludedMeshes.length>0)||-1===this.excludedMeshes.indexOf(e))&&(0===this.includeOnlyWithLayerMask||(this.includeOnlyWithLayerMask&e.layerMask)!=0)&&(0===this.excludeWithLayerMask||!(this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){let e=t.value;e.dispose()}this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){let e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(let e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){let i=light_Light.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;let r=rb.p4.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){let e=rb.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)})),rb.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){let r=ry.N.Construct("Light_Type_"+e,t,i);return r||null}static Parse(e,t){let i=light_Light.GetConstructorFromName(e.type,e.name,t);if(!i)return null;let r=rb.p4.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(r.falloffType=e.falloffType),void 0!==e.lightmapMode&&(r.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t<e.animations.length;t++){let i=e.animations[t],s=(0,rv.q)("BABYLON.Animation");s&&r.animations.push(s.Parse(i))}ry.N.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&r.setEnabled(e.isEnabled),r}_hookArrayForExcluded(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);for(let e of i)e._resyncLightSource(this);return r};let i=e.splice;for(let t of(e.splice=(t,r)=>{let s=i.apply(e,[t,r]);for(let e of s)e._resyncLightSource(this);return s},e))t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._resyncMeshes(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(let e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(let e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0,t=this.getTypeID(),i=this.intensityMode;switch(i===light_Light.INTENSITYMODE_AUTOMATIC&&(i=t===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?light_Light.INTENSITYMODE_ILLUMINANCE:light_Light.INTENSITYMODE_LUMINOUSINTENSITY),t){case light_Light.LIGHTTYPEID_POINTLIGHT:case light_Light.LIGHTTYPEID_SPOTLIGHT:switch(i){case light_Light.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case light_Light.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case light_Light.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case light_Light.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case light_Light.INTENSITYMODE_ILLUMINANCE:e=1;break;case light_Light.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001);let i=2*Math.PI*(1-Math.cos(t));e=i}}break;case light_Light.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){let e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}};light_Light.FALLOFF_DEFAULT=rY.m.FALLOFF_DEFAULT,light_Light.FALLOFF_PHYSICAL=rY.m.FALLOFF_PHYSICAL,light_Light.FALLOFF_GLTF=rY.m.FALLOFF_GLTF,light_Light.FALLOFF_STANDARD=rY.m.FALLOFF_STANDARD,light_Light.LIGHTMAP_DEFAULT=rY.m.LIGHTMAP_DEFAULT,light_Light.LIGHTMAP_SPECULAR=rY.m.LIGHTMAP_SPECULAR,light_Light.LIGHTMAP_SHADOWSONLY=rY.m.LIGHTMAP_SHADOWSONLY,light_Light.INTENSITYMODE_AUTOMATIC=rY.m.INTENSITYMODE_AUTOMATIC,light_Light.INTENSITYMODE_LUMINOUSPOWER=rY.m.INTENSITYMODE_LUMINOUSPOWER,light_Light.INTENSITYMODE_LUMINOUSINTENSITY=rY.m.INTENSITYMODE_LUMINOUSINTENSITY,light_Light.INTENSITYMODE_ILLUMINANCE=rY.m.INTENSITYMODE_ILLUMINANCE,light_Light.INTENSITYMODE_LUMINANCE=rY.m.INTENSITYMODE_LUMINANCE,light_Light.LIGHTTYPEID_POINTLIGHT=rY.m.LIGHTTYPEID_POINTLIGHT,light_Light.LIGHTTYPEID_DIRECTIONALLIGHT=rY.m.LIGHTTYPEID_DIRECTIONALLIGHT,light_Light.LIGHTTYPEID_SPOTLIGHT=rY.m.LIGHTTYPEID_SPOTLIGHT,light_Light.LIGHTTYPEID_HEMISPHERICLIGHT=rY.m.LIGHTTYPEID_HEMISPHERICLIGHT,(0,rH.gn)([(0,rb.n9)()],light_Light.prototype,"diffuse",void 0),(0,rH.gn)([(0,rb.n9)()],light_Light.prototype,"specular",void 0),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"falloffType",void 0),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"range",null),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"intensityMode",null),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"radius",null),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"_renderPriority",void 0),(0,rH.gn)([(0,rb.wz)("_reorderLightsInScene")],light_Light.prototype,"renderPriority",void 0),(0,rH.gn)([(0,rb.qC)("shadowEnabled")],light_Light.prototype,"_shadowEnabled",void 0),(0,rH.gn)([(0,rb.qC)("excludeWithLayerMask")],light_Light.prototype,"_excludeWithLayerMask",void 0),(0,rH.gn)([(0,rb.qC)("includeOnlyWithLayerMask")],light_Light.prototype,"_includeOnlyWithLayerMask",void 0),(0,rH.gn)([(0,rb.qC)("lightmapMode")],light_Light.prototype,"_lightmapMode",void 0);var rj=i(555);let KeepAssets=class KeepAssets extends rp.p{};let InstantiatedEntries=class InstantiatedEntries{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}};let AssetContainer=class AssetContainer extends rp.p{constructor(e){if(super(),this._wasAddedToScene=!1,!(e=e||rS.l.LastCreatedScene))return;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(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of this.particleSystems)e.rebuild();for(let e of this.textures)e._rebuild()})}_topologicalSort(e){let t=new Map;for(let i of e)t.set(i.uniqueId,i);let i={dependsOn:new Map,dependedBy:new Map};for(let t of e){let e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(let r of e){let e=r.uniqueId,s=i.dependsOn.get(e);if(r instanceof instancedMesh_InstancedMesh){let n=r.sourceMesh;t.has(n.uniqueId)&&(s.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}let n=i.dependedBy.get(e);for(let s of r.getDescendants()){let r=s.uniqueId;if(t.has(r)){n.add(r);let t=i.dependsOn.get(r);t.add(e)}}}let r=[],s=[];for(let r of e){let e=r.uniqueId;0===i.dependsOn.get(e).size&&(s.push(r),t.delete(e))}for(;s.length>0;){let e=s.shift();r.push(e);let n=i.dependedBy.get(e.uniqueId);for(let r of Array.from(n.values())){let n=i.dependsOn.get(r);n.delete(e.uniqueId),0===n.size&&t.get(r)&&(s.push(t.get(r)),t.delete(r))}}return t.size>0&&(console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(e=>console.error(e.name))),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId)))for(let s of(e.push(i),t.add(i.uniqueId),i.getDescendants(!0)))this._addNodeAndDescendantsToList(e,t,s,r)}_isNodeInContainer(e){return e instanceof rV.Kj&&-1!==this.meshes.indexOf(e)||e instanceof rk.Y&&-1!==this.transformNodes.indexOf(e)||e instanceof light_Light&&-1!==this.lights.indexOf(e)||e instanceof rj.V&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(let e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return rT.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return rT.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return rT.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return rT.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||rW.w1.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");let r={},s={},n=new InstantiatedEntries,a=[],o=[],l=Object.assign({doNotInstantiate:!0},i),onClone=(t,i)=>{if(r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof rV.Kj&&i.morphTargetManager){let e=t.morphTargetManager;i.morphTargetManager=e.clone();for(let t=0;t<e.numTargets;t++){let n=e.getTarget(t),a=i.morphTargetManager.getTarget(t);r[n.uniqueId]=a.uniqueId,s[a.uniqueId]=a}}},h=[],u=new Set;for(let e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,u,e,l.predicate);for(let e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,u,e,l.predicate);let c=this._topologicalSort(h),onNewCreated=(i,a)=>{if(onClone(i,a),i.parent){let e=r[i.parent.uniqueId],t=s[e];t?a.parent=t:a.parent=i.parent}if(a.position&&i.position&&a.position.copyFrom(i.position),a.rotationQuaternion&&i.rotationQuaternion&&a.rotationQuaternion.copyFrom(i.rotationQuaternion),a.rotation&&i.rotation&&a.rotation.copyFrom(i.rotation),a.scaling&&i.scaling&&a.scaling.copyFrom(i.scaling),a.material&&a.material){if(t){let t=i.material;if(-1===o.indexOf(t)){let i=t.clone(e?e(t.name):"Clone of "+t.name);if(o.push(t),r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,"MultiMaterial"===t.getClassName()){for(let n of t.subMaterials)n&&(i=n.clone(e?e(n.name):"Clone of "+n.name),o.push(n),r[n.uniqueId]=i.uniqueId,s[i.uniqueId]=i);t.subMaterials=t.subMaterials.map(e=>e&&s[r[e.uniqueId]])}}"InstancedMesh"!==a.getClassName()&&(a.material=s[r[t.uniqueId]])}else"MultiMaterial"===a.material.getClassName()?-1===this.scene.multiMaterials.indexOf(a.material)&&this.scene.addMultiMaterial(a.material):-1===this.scene.materials.indexOf(a.material)&&this.scene.addMaterial(a.material)}null===a.parent&&n.rootNodes.push(a)};return c.forEach(e=>{if("InstancedMesh"===e.getClassName()){let t=e.sourceMesh,i=r[t.uniqueId],n="number"==typeof i?s[i]:t,a=n.createInstance(e.name);onNewCreated(e,a)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);let i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw Error(`Could not clone or instantiate node on Asset Container ${e.name}`);onNewCreated(e,i)}}),this.skeletons.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name);for(let e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){let t=s[r[e.uniqueId]];if(!t||t.isAnInstance||(t.skeleton=i,-1!==a.indexOf(i)))continue;for(let e of(a.push(i),i.bones))e._linkedTransformNode&&(e._linkedTransformNode=s[r[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)}),this.animationGroups.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name,e=>{let t=s[r[e.uniqueId]];return t||e});n.animationGroups.push(i)}),n}addAllToScene(){if(!this._wasAddedToScene){for(let e of(this._isValidHierarchy()||rW.w1.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture),this.scene._serializableComponents))e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){let t=[];for(let i of(this.cameras.forEach(i=>{(!e||e(i))&&(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{(!e||e(i))&&(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{(!e||e(i))&&(this.scene.addMesh(i),t.push(i))}),this.skeletons.forEach(t=>{(!e||e(t))&&this.scene.addSkeleton(t)}),this.animations.forEach(t=>{(!e||e(t))&&this.scene.addAnimation(t)}),this.animationGroups.forEach(t=>{(!e||e(t))&&this.scene.addAnimationGroup(t)}),this.multiMaterials.forEach(t=>{(!e||e(t))&&this.scene.addMultiMaterial(t)}),this.materials.forEach(t=>{(!e||e(t))&&this.scene.addMaterial(t)}),this.morphTargetManagers.forEach(t=>{(!e||e(t))&&this.scene.addMorphTargetManager(t)}),this.geometries.forEach(t=>{(!e||e(t))&&this.scene.addGeometry(t)}),this.transformNodes.forEach(i=>{(!e||e(i))&&(this.scene.addTransformNode(i),t.push(i))}),this.actionManagers.forEach(t=>{(!e||e(t))&&this.scene.addActionManager(t)}),this.textures.forEach(t=>{(!e||e(t))&&this.scene.addTexture(t)}),this.reflectionProbes.forEach(t=>{(!e||e(t))&&this.scene.addReflectionProbe(t)}),t))i.parent&&-1===this.scene.getNodes().indexOf(i.parent)&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){for(let e of(this._isValidHierarchy()||rW.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),this.scene._serializableComponents))e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach(t=>{(!e||e(t))&&this.scene.removeCamera(t)}),this.lights.forEach(t=>{(!e||e(t))&&this.scene.removeLight(t)}),this.meshes.forEach(t=>{(!e||e(t))&&this.scene.removeMesh(t,!0)}),this.skeletons.forEach(t=>{(!e||e(t))&&this.scene.removeSkeleton(t)}),this.animations.forEach(t=>{(!e||e(t))&&this.scene.removeAnimation(t)}),this.animationGroups.forEach(t=>{(!e||e(t))&&this.scene.removeAnimationGroup(t)}),this.multiMaterials.forEach(t=>{(!e||e(t))&&this.scene.removeMultiMaterial(t)}),this.materials.forEach(t=>{(!e||e(t))&&this.scene.removeMaterial(t)}),this.morphTargetManagers.forEach(t=>{(!e||e(t))&&this.scene.removeMorphTargetManager(t)}),this.geometries.forEach(t=>{(!e||e(t))&&this.scene.removeGeometry(t)}),this.transformNodes.forEach(t=>{(!e||e(t))&&this.scene.removeTransformNode(t)}),this.actionManagers.forEach(t=>{(!e||e(t))&&this.scene.removeActionManager(t)}),this.textures.forEach(t=>{(!e||e(t))&&this.scene.removeTexture(t)}),this.reflectionProbes.forEach(t=>{(!e||e(t))&&this.scene.removeReflectionProbe(t)})}dispose(){for(let e of(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),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(let r of e){let e=!0;if(i){for(let t of i)if(r===t){e=!1;break}}e&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){for(let t in this._wasAddedToScene=!1,void 0===e&&(e=new KeepAssets),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(){let e=new rV.Kj("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=rS.l.LastCreatedScene,t,i=null){if(!e)return rT.Y.Error("No scene available to merge animations to"),[];let r=i||(t=>{let i=null,r=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(r){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i}),s=this.getNodes();s.forEach(e=>{let t=r(e);if(null!==t){for(let i of e.animations){let e=t.animations.filter(e=>e.targetProperty===i.targetProperty);for(let i of e){let e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}});let n=[];return this.animationGroups.slice().forEach(e=>{n.push(e.clone(e.name,r)),e.animatables.forEach(e=>{e.stop()})}),t.forEach(t=>{let i=r(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))}),n}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}),this.transformNodes.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}),this.lights.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}),this.cameras.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})}addAllAssetsToContainer(e){if(!e)return;let t=[],i=new Set;for(t.push(e);t.length>0;){let e=t.pop();if(e instanceof rV.Kj?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof rk.Y?this.transformNodes.push(e):e instanceof light_Light?this.lights.push(e):e instanceof rj.V&&this.cameras.push(e),e instanceof rG.x){if(e.material&&-1===this.materials.indexOf(e.material))for(let t of(this.materials.push(e.material),e.material.getActiveTextures()))-1===this.textures.indexOf(t)&&this.textures.push(t);e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(let r of e.getChildren())i.has(r)||t.push(r);i.add(e)}this.populateRootNodes()}};var rq=i(8906),rK=i(7209);rq.D.AudioEngineFactory=(e,t,i)=>new AudioEngine(e,t,i);let AudioEngine=class AudioEngine{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new rf.y$,this.onAudioLockedObservable=new rf.y$,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,rK.CG)())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);let r=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{r&&r.canPlayType&&(r.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||r.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{r&&r.canPlayType&&r.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if((null===(e=this._audioContext)||void 0===e?void 0:e.state)==="running"){this._hideMuteButton();return}this._tryToRun?null===(t=this._audioContext)||void 0===t||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return(null===(e=this._audioContext)||void 0===e?void 0:e.resume)?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,rT.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";let e=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",t=document.createElement("style");t.appendChild(document.createTextNode(".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); 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) }")),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",()=>{this._triggerRunningState()},!0),this._muteButton.addEventListener("click",()=>{this.unlock()},!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}};var r$=i(6131);let Sound=class Sound{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=rq.D.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){let e=this.isPaused?0:rq.D.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;let t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,s){var n,a,o,l,h;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 rf.y$,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=rm.P.Zero(),this._localDirection=new rm.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||rS.l.LastCreatedScene))return;if(this._scene=i,Sound._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(e,t,i,r,s)=>t<i?e*(1-t/i):0,s&&(this.autoplay=s.autoplay||!1,this._loop=s.loop||!1,void 0!==s.volume&&(this._volume=s.volume),this._spatialSound=null!==(n=s.spatialSound)&&void 0!==n&&n,this.maxDistance=null!==(a=s.maxDistance)&&void 0!==a?a:100,this.useCustomAttenuation=null!==(o=s.useCustomAttenuation)&&void 0!==o&&o,this.rolloffFactor=s.rolloffFactor||1,this.refDistance=s.refDistance||1,this.distanceModel=s.distanceModel||"linear",this._playbackRate=s.playbackRate||1,this._streaming=null!==(l=s.streaming)&&void 0!==l&&l,this._length=s.length,this._offset=s.offset),(null===(h=rq.D.audioEngine)||void 0===h?void 0:h.canUseWebAudio)&&rq.D.audioEngine.audioContext){this._soundGain=rq.D.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this._spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.addSound(this);let e=!0;if(t)try{"string"==typeof t?(this._urlType="String",this._url=t):t instanceof ArrayBuffer?this._urlType="ArrayBuffer":t instanceof HTMLMediaElement?this._urlType="MediaElement":t instanceof MediaStream?this._urlType="MediaStream":t instanceof AudioBuffer?this._urlType="AudioBuffer":Array.isArray(t)&&(this._urlType="Array");let i=[],r=!1;switch(this._urlType){case"MediaElement":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=rq.D.audioEngine.audioContext.createMediaElementSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=rq.D.audioEngine.audioContext.createMediaStreamSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":t.byteLength>0&&(r=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e<i.length;e++){let t=i[e];if(r=s&&s.skipCodecCheck||-1!==t.indexOf(".mp3",t.length-4)&&rq.D.audioEngine.isMP3supported||-1!==t.indexOf(".ogg",t.length-4)&&rq.D.audioEngine.isOGGsupported||-1!==t.indexOf(".wav",t.length-4)||-1!==t.indexOf(".m4a",t.length-4)||-1!==t.indexOf(".mp4",t.length-4)||-1!==t.indexOf("blob:")){this._streaming?(this._htmlAudioElement=new Audio(t),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,rW.w1.SetCorsBehavior(t,this._htmlAudioElement),this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",()=>{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()}),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,e=>{this._soundLoaded(e)},void 0,!0,!0,e=>{e&&rT.Y.Error("XHR "+e.status+" error on: "+t+"."),rT.Y.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:e=!1}e?!r&&(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):rT.Y.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){rT.Y.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),rq.D.audioEngine&&!rq.D.audioEngine.WarnedWebAudioUnsupported&&(rT.Y.Error("Web Audio is not supported by your browser."),rq.D.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(null===(e=rq.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),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){var t;(null===(t=rq.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=rq.D.audioEngine)||void 0===t?void 0:t.audioContext)&&rq.D.audioEngine.audioContext.decodeAudioData(e,e=>{this._audioBufferLoaded(e)},e=>{rT.Y.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)})}setAudioBuffer(e){var t;(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,r,s,n,a,o,l,h,u,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!==(r=e.useCustomAttenuation)&&void 0!==r?r:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(n=e.refDistance)&&void 0!==n?n:this.refDistance,this.distanceModel=null!==(a=e.distanceModel)&&void 0!==a?a:this.distanceModel,this._playbackRate=null!==(o=e.playbackRate)&&void 0!==o?o:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this.spatialSound=null!==(h=e.spatialSound)&&void 0!==h?h:this._spatialSound,this._setOffset(null!==(u=e.offset)&&void 0!==u?u: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=rq.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&rq.D.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:rq.D.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,null===(e=this._soundPanner)||void 0===e||e.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?(this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor),this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){var e;(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=rq.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){if(t<e){rT.Y.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=e,this._coneOuterAngle=t,this._coneOuterGain=i,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){var t;if(e!=this._coneInnerAngle){if(this._coneOuterAngle<e){rT.Y.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=e,(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){var t;if(e!=this._coneOuterAngle){if(e<this._coneInnerAngle){rT.Y.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneOuterAngle=e,(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}}setPosition(e){var t;!e.equals(this._position)&&(this._position.copyFrom(e),(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z))}setLocalDirectionToMesh(e){var t;this._localDirection=e,(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()}_updateDirection(){if(!this._connectedTransformNode||!this._soundPanner)return;let e=this._connectedTransformNode.getWorldMatrix(),t=rm.P.TransformNormal(this._localDirection,e);t.normalize(),this._soundPanner.orientationX.value=t.x,this._soundPanner.orientationY.value=t.y,this._soundPanner.orientationZ.value=t.z}updateDistanceFromListener(){var e;if((null===(e=rq.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){let e=this._scene.audioListenerPositionProvider?this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length():this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,e,this.maxDistance,this.refDistance,this.rolloffFactor)}}setAttenuationFunction(e){this._customAttenuationFunction=e}play(e,t,i){var r,s,n,a;if(this._isReadyToPlay&&this._scene.audioEnabled&&(null===(r=rq.D.audioEngine)||void 0===r?void 0:r.audioContext))try{this._clearTimeoutsAndObservers();let r=e?(null===(s=rq.D.audioEngine)||void 0===s?void 0:s.audioContext.currentTime)+e:null===(n=rq.D.audioEngine)||void 0===n?void 0:n.audioContext.currentTime;if((!this._soundSource||!this._streamingSource)&&this._spatialSound&&this._soundPanner&&(isNaN(this._position.x)||isNaN(this._position.y)||isNaN(this._position.z)||(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=rq.D.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=()=>{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){let tryToPlay=()=>{var e,t;if(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.unlocked){let e=this._htmlAudioElement.play();void 0!==e&&e.catch(()=>{var e,t;null===(e=rq.D.audioEngine)||void 0===e||e.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(t=rq.D.audioEngine)||void 0===t?void 0:t.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(t=rq.D.audioEngine)||void 0===t?void 0:t.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))};tryToPlay()}}else{let tryToPlay=()=>{var s,n,a,o;if(null===(s=rq.D.audioEngine)||void 0===s?void 0:s.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){let e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=null===(n=rq.D.audioEngine)||void 0===n?void 0:n.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},r=e?(null===(a=rq.D.audioEngine)||void 0===a?void 0:a.audioContext.currentTime)+e:rq.D.audioEngine.audioContext.currentTime;let s=((this.isPaused?this.currentTime:0)+(null!==(o=this._offset)&&void 0!==o?o:0))%this._soundSource.buffer.duration;this._soundSource.start(r,s,this.loop?void 0:i)}}};(null===(a=rq.D.audioEngine)||void 0===a?void 0:a.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var e;(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.audioContext.state)==="suspended"?(rq.D.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=rq.D.audioEngine.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))):tryToPlay()},500):tryToPlay()}this._startTime=r,this.isPlaying=!0,this.isPaused=!1}catch(e){rT.Y.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){var t;if(this.isPlaying){if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((null===(t=rq.D.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){let t=e?rq.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=()=>void 0),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1}else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>void 0,this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=rq.D.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=rq.D.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&rq.D.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(rq.D.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,rq.D.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,rq.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){let t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{let setBufferAndRun=()=>{this._isReadyToPlay?(t._audioBuffer=this.getAudioBuffer(),t._isReadyToPlay=!0,t.autoplay&&t.play(0,this._offset,this._length)):setTimeout(setBufferAndRun,300)},e={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},t=new Sound(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,e);return this.useCustomAttenuation&&t.setAttenuationFunction(this._customAttenuationFunction),t.setPosition(this._position),t.setPlaybackRate(this._playbackRate),setBufferAndRun(),t}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){let e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,r){let s,n;let a=e.name;s=e.url?i+e.url:i+a;let o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};if(r){let setBufferAndRun=()=>{r._isReadyToPlay?(n._audioBuffer=r.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play(0,n._offset,n._length)):setTimeout(setBufferAndRun,300)};n=new Sound(a,new ArrayBuffer(0),t,null,o),setBufferAndRun()}else n=new Sound(a,s,t,()=>{t.removePendingData(n)},o),t.addPendingData(n);if(e.position){let t=rm.P.FromArray(e.position);n.setPosition(t)}if(e.isDirectional&&(n.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){let t=rm.P.FromArray(e.localDirectionToMesh);n.setLocalDirectionToMesh(t)}if(e.connectedMeshId){let i=t.getMeshById(e.connectedMeshId);i&&n.attachToMesh(i)}return e.metadata&&(n.metadata=e.metadata),n}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(null===(e=rq.D.audioEngine)||void 0===e||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}};Sound._SceneComponentInitialization=e=>{throw(0,r$.S)("AudioSceneComponent")};let SoundTrack=class SoundTrack{constructor(e,t={}){if(this.id=-1,this._isInitialized=!1,!(e=e||rS.l.LastCreatedScene))return;this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}_initializeSoundTrackAudioGraph(){var e;(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&rq.D.audioEngine.audioContext&&(this._outputAudioNode=rq.D.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(rq.D.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(rq.D.audioEngine&&rq.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=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){let t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){var t;(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToHRTF()}switchPanningModelToEqualPower(){var e;if(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToEqualPower()}connectToAnalyser(e){var t;this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=e,(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,rq.D.audioEngine.masterGain))}};var rQ=i(7609);rp.p.AddParser(rQ.l.NAME_AUDIO,(e,t,i,r)=>{var s;let n;let a=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,l=e.sounds.length;o<l;o++){let l=e.sounds[o];(null===(s=rq.D.audioEngine)||void 0===s?void 0:s.canUseWebAudio)?(l.url||(l.url=l.name),a[l.url]?i.sounds.push(Sound.Parse(l,t,r,a[l.url])):(n=Sound.Parse(l,t,r),a[l.url]=n,i.sounds.push(n))):i.sounds.push(new Sound(l.name,null,t))}a=[]}),Object.defineProperty(rN.x.prototype,"mainSoundTrack",{get:function(){let e=this._getComponent(rQ.l.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),this._mainSoundTrack||(this._mainSoundTrack=new SoundTrack(this,{mainTrack:!0})),this._mainSoundTrack},enumerable:!0,configurable:!0}),rN.x.prototype.getSoundByName=function(e){let t;for(t=0;t<this.mainSoundTrack.soundCollection.length;t++)if(this.mainSoundTrack.soundCollection[t].name===e)return this.mainSoundTrack.soundCollection[t];if(this.soundTracks){for(let i=0;i<this.soundTracks.length;i++)for(t=0;t<this.soundTracks[i].soundCollection.length;t++)if(this.soundTracks[i].soundCollection[t].name===e)return this.soundTracks[i].soundCollection[t]}return null},Object.defineProperty(rN.x.prototype,"audioEnabled",{get:function(){let e=this._getComponent(rQ.l.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),e.audioEnabled},set:function(e){let t=this._getComponent(rQ.l.NAME_AUDIO);t||(t=new AudioSceneComponent(this),this._addComponent(t)),e?t.enableAudio():t.disableAudio()},enumerable:!0,configurable:!0}),Object.defineProperty(rN.x.prototype,"headphone",{get:function(){let e=this._getComponent(rQ.l.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),e.headphone},set:function(e){let t=this._getComponent(rQ.l.NAME_AUDIO);t||(t=new AudioSceneComponent(this),this._addComponent(t)),e?t.switchAudioModeForHeadphones():t.switchAudioModeForNormalSpeakers()},enumerable:!0,configurable:!0}),Object.defineProperty(rN.x.prototype,"audioListenerPositionProvider",{get:function(){let e=this._getComponent(rQ.l.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),e.audioListenerPositionProvider},set:function(e){let t=this._getComponent(rQ.l.NAME_AUDIO);if(t||(t=new AudioSceneComponent(this),this._addComponent(t)),e&&"function"!=typeof e)throw Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");t.audioListenerPositionProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(rN.x.prototype,"audioListenerRotationProvider",{get:function(){let e=this._getComponent(rQ.l.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),e.audioListenerRotationProvider},set:function(e){let t=this._getComponent(rQ.l.NAME_AUDIO);if(t||(t=new AudioSceneComponent(this),this._addComponent(t)),e&&"function"!=typeof e)throw Error("The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3");t.audioListenerRotationProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(rN.x.prototype,"audioPositioningRefreshRate",{get:function(){let e=this._getComponent(rQ.l.NAME_AUDIO);return e||(e=new AudioSceneComponent(this),this._addComponent(e)),e.audioPositioningRefreshRate},set:function(e){let t=this._getComponent(rQ.l.NAME_AUDIO);t||(t=new AudioSceneComponent(this),this._addComponent(t)),t.audioPositioningRefreshRate=e},enumerable:!0,configurable:!0});let AudioSceneComponent=class AudioSceneComponent{get audioEnabled(){return this._audioEnabled}get headphone(){return this._headphone}constructor(e){if(this.name=rQ.l.NAME_AUDIO,this._audioEnabled=!0,this._headphone=!1,this.audioPositioningRefreshRate=500,this.audioListenerPositionProvider=null,this.audioListenerRotationProvider=null,this._cachedCameraDirection=new rm.P,this._cachedCameraPosition=new rm.P,this._lastCheck=0,this._invertMatrixTemp=new rm.y3,this._cameraDirectionTemp=new rm.P,!(e=e||rS.l.LastCreatedScene))return;this.scene=e,e.soundTracks=[],e.sounds=[]}register(){this.scene._afterRenderStage.registerStep(rQ.l.STEP_AFTERRENDER_AUDIO,this,this._afterRender)}rebuild(){}serialize(e){if(e.sounds=[],this.scene.soundTracks)for(let t=0;t<this.scene.soundTracks.length;t++){let i=this.scene.soundTracks[t];for(let t=0;t<i.soundCollection.length;t++)e.sounds.push(i.soundCollection[t].serialize())}}addFromContainer(e){e.sounds&&e.sounds.forEach(e=>{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(){let e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].dispose()}disableAudio(){let e;let t=this.scene;for(this._audioEnabled=!1,rq.D.audioEngine&&rq.D.audioEngine.audioContext&&rq.D.audioEngine.audioContext.suspend(),e=0;e<t.mainSoundTrack.soundCollection.length;e++)t.mainSoundTrack.soundCollection[e].pause();if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(let i=0;i<t.soundTracks[e].soundCollection.length;i++)t.soundTracks[e].soundCollection[i].pause()}enableAudio(){let e;let t=this.scene;for(this._audioEnabled=!0,rq.D.audioEngine&&rq.D.audioEngine.audioContext&&rq.D.audioEngine.audioContext.resume(),e=0;e<t.mainSoundTrack.soundCollection.length;e++)t.mainSoundTrack.soundCollection[e].isPaused&&t.mainSoundTrack.soundCollection[e].play();if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(let i=0;i<t.soundTracks[e].soundCollection.length;i++)t.soundTracks[e].soundCollection[i].isPaused&&t.soundTracks[e].soundCollection[i].play()}switchAudioModeForHeadphones(){let e=this.scene;if(this._headphone=!0,e.mainSoundTrack.switchPanningModelToHRTF(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToHRTF()}switchAudioModeForNormalSpeakers(){let e=this.scene;if(this._headphone=!1,e.mainSoundTrack.switchPanningModelToEqualPower(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToEqualPower()}_afterRender(){let e=rF.F.Now;if(this._lastCheck&&e-this._lastCheck<this.audioPositioningRefreshRate)return;this._lastCheck=e;let t=this.scene;if(!this._audioEnabled||!t._mainSoundTrack||!t.soundTracks||0===t._mainSoundTrack.soundCollection.length&&1===t.soundTracks.length)return;let i=rq.D.audioEngine;if(i&&i.audioContext){let e,r=t.activeCamera;if(t.activeCameras&&t.activeCameras.length>0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){let e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){let e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),rm.P.TransformNormalToRef(AudioSceneComponent._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<t.mainSoundTrack.soundCollection.length;e++){let i=t.mainSoundTrack.soundCollection[e];i.useCustomAttenuation&&i.updateDistanceFromListener()}if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(let i=0;i<t.soundTracks[e].soundCollection.length;i++){let r=t.soundTracks[e].soundCollection[i];r.useCustomAttenuation&&r.updateDistanceFromListener()}}}};AudioSceneComponent._CameraDirection=new rm.P(0,0,-1),Sound._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_AUDIO);t||(t=new AudioSceneComponent(e),e._addComponent(t))};let BakedVertexAnimationManager=class BakedVertexAnimationManager{constructor(e){if(this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,!(e=e||rS.l.LastCreatedScene))return;this._scene=e,this.animationParameters=new rm.Lt(0,0,0,30)}_markSubMeshesAsAttributesDirty(){for(let e of this._scene.meshes)e.bakedVertexAnimationManager===this&&e._markSubMeshesAsAttributesDirty()}bind(e,t=!1){if(!this._texture||!this._isEnabled)return;let i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}clone(){let e=new BakedVertexAnimationManager(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,r=30){this.animationParameters=new rm.Lt(e,t,i,r)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){rb.p4.Clone(()=>e,this)}serialize(){return rb.p4.Serialize(this)}parse(e,t,i){rb.p4.Parse(()=>this,e,t,i)}};(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markSubMeshesAsAttributesDirty")],BakedVertexAnimationManager.prototype,"texture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markSubMeshesAsAttributesDirty")],BakedVertexAnimationManager.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],BakedVertexAnimationManager.prototype,"animationParameters",void 0),(0,rH.gn)([(0,rb.qC)()],BakedVertexAnimationManager.prototype,"time",void 0);var rZ=i(1032),rJ=i(1166);let thinTexture_ThinTexture=class thinTexture_ThinTexture{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(null==e?void 0:e._shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Size.Zero(),this._cachedBaseSize=Size.Zero(),this._initialSamplingMode=2,this._texture=thinTexture_ThinTexture._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;this._texture._size&&(this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size)}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.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight):(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)}};let baseTexture_BaseTexture=class baseTexture_BaseTexture extends thinTexture_ThinTexture{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){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=(0,rZ.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=baseTexture_BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new rf.y$,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?baseTexture_BaseTexture._IsScene(e)?this._scene=e:this._engine=e:this._scene=rS.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 rm.y3.IdentityReadOnly}getReflectionTextureMatrix(){return rm.y3.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,n){let a=this._getEngine();if(!a)return null;let o=a._getUseSRGBBuffer(!!s,t),l=a.getLoadedTexturesCache();for(let a=0;a<l.length;a++){let h=l[a];if((void 0===s||o===h._useSRGBBuffer)&&(void 0===r||r===h.invertY)&&h.url===e&&!t===h.generateMipMaps&&(!i||i===h.samplingMode)&&(void 0===n||n===h.isCube))return h.incrementReferences(),h}return null}_rebuild(){}clone(){return null}get textureType(){return this._texture&&void 0!==this._texture.type?this._texture.type:0}get textureFormat(){return this._texture&&void 0!==this._texture.format?this._texture.format:5}_markAllSubMeshesAsTexturesDirty(){let e=this.getScene();e&&e.markAllMaterialsAsDirty(1)}readPixels(e=0,t=0,i=null,r=!0,s=!1,n=0,a=0,o=Number.MAX_VALUE,l=Number.MAX_VALUE){if(!this._texture)return null;let h=this._getEngine();if(!h)return null;let u=this.getSize(),c=u.width,d=u.height;0!==t&&(c/=Math.pow(2,t),d/=Math.pow(2,t),c=Math.round(c),d=Math.round(d)),o=Math.min(c,o),l=Math.min(d,l);try{if(this._texture.isCube)return h._readTexturePixels(this._texture,o,l,e,t,i,r,s,n,a);return h._readTexturePixels(this._texture,o,l,-1,t,i,r,s,n,a)}catch(e){return null}}_readPixelsSync(e=0,t=0,i=null,r=!0,s=!1){if(!this._texture)return null;let n=this.getSize(),a=n.width,o=n.height,l=this._getEngine();if(!l)return null;0!=t&&(a/=Math.pow(2,t),o/=Math.pow(2,t),a=Math.round(a),o=Math.round(o));try{if(this._texture.isCube)return l._readTexturePixelsSync(this._texture,a,o,e,t,i,r,s);return l._readTexturePixelsSync(this._texture,a,o,-1,t,i,r,s)}catch(e){return null}}get _lodTextureHigh(){return this._texture?this._texture._lodTextureHigh:null}get _lodTextureMid(){return this._texture?this._texture._lodTextureMid:null}get _lodTextureLow(){return this._texture?this._texture._lodTextureLow:null}dispose(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);let e=this._scene.textures.indexOf(this);if(e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){let 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;let t=rb.p4.Serialize(this);return rb.p4.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0===i){t();return}for(let r=0;r<e.length;r++){let s=e[r];if(s.isReady())0==--i&&t();else{let e=s.onLoadObservable;e?e.addOnce(()=>{0==--i&&t()}):0==--i&&t()}}}static _IsScene(e){return"Scene"===e.getClassName()}};baseTexture_BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"uniqueId",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"name",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"metadata",void 0),(0,rH.gn)([(0,rb.qC)("hasAlpha")],baseTexture_BaseTexture.prototype,"_hasAlpha",void 0),(0,rH.gn)([(0,rb.qC)("getAlphaFromRGB")],baseTexture_BaseTexture.prototype,"_getAlphaFromRGB",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"level",void 0),(0,rH.gn)([(0,rb.qC)("coordinatesIndex")],baseTexture_BaseTexture.prototype,"_coordinatesIndex",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"optimizeUVAllocation",void 0),(0,rH.gn)([(0,rb.qC)("coordinatesMode")],baseTexture_BaseTexture.prototype,"_coordinatesMode",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"wrapU",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"wrapV",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"wrapR",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"anisotropicFilteringLevel",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"isCube",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"is3D",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"is2DArray",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"gammaSpace",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"invertZ",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"lodLevelInAlpha",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"lodGenerationOffset",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"lodGenerationScale",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"linearSpecularLOD",null),(0,rH.gn)([(0,rb.oU)()],baseTexture_BaseTexture.prototype,"irradianceTexture",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"isRenderTarget",void 0);var r0=i(4490),r1=i(4406),r2=i(1564),r3=i(9005);function GenerateBase64StringFromPixelData(e,t,i=!1){let r=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT,i=new Uint8Array(t);for(;--t>=0;){let r=e[t];r<0?r=0:r>1&&(r=1),i[t]=255*r}e=i}let n=document.createElement("canvas");n.width=r,n.height=s;let a=n.getContext("2d");if(!a)return null;let o=a.createImageData(r,s),l=o.data;if(l.set(e),a.putImageData(o,0,0),i){let e=document.createElement("canvas");e.width=r,e.height=s;let t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}function GenerateBase64StringFromTexture(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=e._readPixelsSync(t,i);return s?GenerateBase64StringFromPixelData(s,e.getSize(),r.invertY):null}async function GenerateBase64StringFromTextureAsync(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=await e.readPixels(t,i);return s?GenerateBase64StringFromPixelData(s,e.getSize(),r.invertY):null}var r4=i(6705);let texture_Texture=class texture_Texture extends baseTexture_BaseTexture{static _CreateVideoTexture(e,t,i,r=!1,s=!1,n=texture_Texture.TRILINEAR_SAMPLINGMODE,a={},o,l=5){throw(0,r$.S)("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,r,s=texture_Texture.TRILINEAR_SAMPLINGMODE,n=null,a=null,o=null,l=!1,h,u,c,d,p){var _,f,m,g,v,x,T,S,C,E;let b;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 rf.y$,this._isBlocking=!0,this.name=e||"",this.url=e;let y=!1,P=null,R=!0;"object"==typeof i&&null!==i?(b=null!==(_=i.noMipmap)&&void 0!==_&&_,r=null!==(f=i.invertY)&&void 0!==f?f:!r4.e.UseOpenGLOrientationForUV,s=null!==(m=i.samplingMode)&&void 0!==m?m:texture_Texture.TRILINEAR_SAMPLINGMODE,n=null!==(g=i.onLoad)&&void 0!==g?g:null,a=null!==(v=i.onError)&&void 0!==v?v:null,o=null!==(x=i.buffer)&&void 0!==x?x:null,l=null!==(T=i.deleteBuffer)&&void 0!==T&&T,h=i.format,u=i.mimeType,c=i.loaderOptions,d=i.creationFlags,y=null!==(S=i.useSRGBBuffer)&&void 0!==S&&S,P=null!==(C=i.internalTexture)&&void 0!==C?C:null,R=null!==(E=i.gammaSpace)&&void 0!==E?E:R):b=!!i,this._gammaSpace=R,this._noMipmap=b,this._invertY=void 0===r?!r4.e.UseOpenGLOrientationForUV:r,this._initialSamplingMode=s,this._buffer=o,this._deleteBuffer=l,this._mimeType=u,this._loaderOptions=c,this._creationFlags=d,this._useSRGBBuffer=y,this._forcedExtension=p,h&&(this._format=h);let A=this.getScene(),I=this._getEngine();if(!I)return;I.onBeforeTextureInitObservable.notifyObservers(this);let load=()=>{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),n&&n(),!this.isBlocking&&A&&A.resetCachedMaterial()},errorHandler=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),texture_Texture.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!P){this._delayedOnLoad=load,this._delayedOnError=errorHandler;return}if(this._texture=null!=P?P:this._getFromCache(this.url,b,s,this._invertY,y,this.isCube),this._texture){if(this._texture.isReady)r0.Q.SetImmediate(()=>load());else{let e=this._texture.onLoadedObservable.add(load);this._texture.onErrorObservable.add(t=>{var i;errorHandler(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)})}}else if(A&&A.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=load,this._delayedOnError=errorHandler;else{try{this._texture=I.createTexture(this.url,b,this._invertY,A,s,load,errorHandler,this._buffer,void 0,this._format,this._forcedExtension,u,c,d,y)}catch(e){throw errorHandler("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,e=>e.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;let e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?r0.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,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,rm.P.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}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=rm.y3.Zero(),this._rowGenerationMatrix=new rm.y3,this._t0=rm.P.Zero(),this._t1=rm.P.Zero(),this._t2=rm.P.Zero()),rm.y3.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(rm.y3.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,rm.jp.Matrix[0]),rm.y3.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,rm.jp.Matrix[1]),rm.y3.ScalingToRef(this._cachedUScale,this._cachedVScale,0,rm.jp.Matrix[2]),rm.y3.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,rm.jp.Matrix[3]),rm.jp.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rm.jp.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rm.jp.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rm.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),rm.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));let t=this.getScene();return t&&this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){let e=this.getScene();if(!e||this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode&&(this.coordinatesMode!==texture_Texture.PROJECTION_MODE||this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag))return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=rm.y3.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=rm.y3.Zero());let 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 texture_Texture.PLANAR_MODE:rm.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 texture_Texture.PROJECTION_MODE:{rm.y3.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);let t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:rm.y3.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){let 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 rb.p4.Clone(()=>new texture_Texture(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;let i=this.name;!texture_Texture.SerializeBuffers&&this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");let r=super.serialize(texture_Texture._SerializeInternalTextureUniqueId);return r?((texture_Texture.SerializeBuffers||texture_Texture.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(r.base64String=this._buffer,r.name=r.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?r.base64String="data:image/png;base64,"+(0,r3.Gh)(this._buffer):(texture_Texture.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(r.base64String=!this._engine||this._engine._features.supportSyncTextureRead?GenerateBase64StringFromTexture(this):GenerateBase64StringFromTextureAsync(this))),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r._creationFlags=this._creationFlags,r._useSRGBBuffer=this._useSRGBBuffer,texture_Texture._SerializeInternalTextureUniqueId&&(r.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),r.noMipmap=this._noMipmap,this.name=i,r):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){let r;if(e.customType){let r=r1.K.Instantiate(e.customType),s=r.Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return texture_Texture._CubeTextureParser(e,t,i);let s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;if(s){let i=t.getEngine().getLoadedTexturesCache();for(let t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}let onLoaded=t=>{var i;if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){let i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i<e.animations.length;i++){let r=e.animations[i],s=(0,rv.q)("BABYLON.Animation");s&&t.animations.push(s.Parse(r))}s&&!r&&(null===(i=null==t?void 0:t._texture)||void 0===i||i._setUniqueId(e.internalTextureUniqueId))},n=rb.p4.Parse(()=>{var s,n,a;let o=!0;if(e.noMipmap&&(o=!1),e.mirrorPlane){let i=texture_Texture._CreateMirror(e.name,e.renderTargetSize,t,o);return i._waitingRenderList=e.renderList,i.mirrorPlane=r2.J.FromArray(e.mirrorPlane),onLoaded(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i<t.reflectionProbes.length;i++){let r=t.reflectionProbes[i];if(r.name===e.name)return r.cubeTexture}}else(i=texture_Texture._CreateRenderTargetTexture(e.name,e.renderTargetSize,t,o,null!==(s=e._creationFlags)&&void 0!==s?s:0))._waitingRenderList=e.renderList;return onLoaded(i),i}if(e.isVideo){let r=texture_Texture._CreateVideoTexture(i+(e.url||e.name),i+(e.src||e.url),t,o,e.invertY,e.samplingMode,e.settings||{});return onLoaded(r),r}{let s;if(e.base64String&&!r)(s=texture_Texture.CreateFromBase64String(e.base64String,e.base64String,t,!o,e.invertY,e.samplingMode,()=>{onLoaded(s)},null!==(n=e._creationFlags)&&void 0!==n?n:0,null!==(a=e._useSRGBBuffer)&&void 0!==a&&a)).name=e.name;else{let n;n=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||texture_Texture.UseSerializedUrlIfAny)&&(n=e.url);let a={noMipmap:!o,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{onLoaded(s)},internalTexture:r};s=new texture_Texture(n,t,a)}return s}},e,t);return n}static CreateFromBase64String(e,t,i,r,s,n=texture_Texture.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=5,h){return new texture_Texture("data:"+t,i,r,s,n,a,o,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,r=!1,s,n=!0,a=texture_Texture.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new texture_Texture(e,i,s,n,a,o,l,t,r,h,void 0,void 0,u)}};texture_Texture.SerializeBuffers=!0,texture_Texture.ForceSerializeBuffers=!1,texture_Texture.OnTextureLoadErrorObservable=new rf.y$,texture_Texture._SerializeInternalTextureUniqueId=!1,texture_Texture._CubeTextureParser=(e,t,i)=>{throw(0,r$.S)("CubeTexture")},texture_Texture._CreateMirror=(e,t,i,r)=>{throw(0,r$.S)("MirrorTexture")},texture_Texture._CreateRenderTargetTexture=(e,t,i,r,s)=>{throw(0,r$.S)("RenderTargetTexture")},texture_Texture.NEAREST_SAMPLINGMODE=1,texture_Texture.NEAREST_NEAREST_MIPLINEAR=8,texture_Texture.BILINEAR_SAMPLINGMODE=2,texture_Texture.LINEAR_LINEAR_MIPNEAREST=11,texture_Texture.TRILINEAR_SAMPLINGMODE=3,texture_Texture.LINEAR_LINEAR_MIPLINEAR=3,texture_Texture.NEAREST_NEAREST_MIPNEAREST=4,texture_Texture.NEAREST_LINEAR_MIPNEAREST=5,texture_Texture.NEAREST_LINEAR_MIPLINEAR=6,texture_Texture.NEAREST_LINEAR=7,texture_Texture.NEAREST_NEAREST=1,texture_Texture.LINEAR_NEAREST_MIPNEAREST=9,texture_Texture.LINEAR_NEAREST_MIPLINEAR=10,texture_Texture.LINEAR_LINEAR=2,texture_Texture.LINEAR_NEAREST=12,texture_Texture.EXPLICIT_MODE=0,texture_Texture.SPHERICAL_MODE=1,texture_Texture.PLANAR_MODE=2,texture_Texture.CUBIC_MODE=3,texture_Texture.PROJECTION_MODE=4,texture_Texture.SKYBOX_MODE=5,texture_Texture.INVCUBIC_MODE=6,texture_Texture.EQUIRECTANGULAR_MODE=7,texture_Texture.FIXED_EQUIRECTANGULAR_MODE=8,texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,texture_Texture.CLAMP_ADDRESSMODE=0,texture_Texture.WRAP_ADDRESSMODE=1,texture_Texture.MIRROR_ADDRESSMODE=2,texture_Texture.UseSerializedUrlIfAny=!1,(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"url",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"uOffset",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"vOffset",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"uScale",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"vScale",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"uAng",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"vAng",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"wAng",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"uRotationCenter",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"vRotationCenter",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"wRotationCenter",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"homogeneousRotationInUVTransform",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"isBlocking",null),(0,rv.H)("BABYLON.Texture",texture_Texture),rb.p4._TextureParser=texture_Texture.Parse;var r5=i(3912),r6=i(6465);function _convertRGBtoRGBATextureData(e,t,i,r){let s;let n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r<t;r++)for(let a=0;a<i;a++){let i=(a*t+r)*3,o=(a*t+r)*4;s[o+0]=e[i+0],s[o+1]=e[i+1],s[o+2]=e[i+2],s[o+3]=n}return s}function _makeCreateRawTextureFunction(e){return function(t,i,r,s,n,a,o,l,h=null,u=0){let c=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,d=e?r5.S.Raw3D:r5.S.Raw2DArray,p=new r5.l(this,d);p.baseWidth=i,p.baseHeight=r,p.baseDepth=s,p.width=i,p.height=r,p.depth=s,p.format=n,p.type=u,p.generateMipMaps=a,p.samplingMode=l,e?p.is3D=!0:p.is2DArray=!0,this._doNotHandleContextLost||(p._bufferView=t),e?this.updateRawTexture3D(p,t,n,o,h,u):this.updateRawTexture2DArray(p,t,n,o,h,u),this._bindTextureDirectly(c,p,!0);let _=this._getSamplingParameters(l,a);return this._gl.texParameteri(c,this._gl.TEXTURE_MAG_FILTER,_.mag),this._gl.texParameteri(c,this._gl.TEXTURE_MIN_FILTER,_.min),a&&this._gl.generateMipmap(c),this._bindTextureDirectly(c,null),this._internalTexturesCache.push(p),p}}function _makeUpdateRawTextureFunction(e){return function(t,i,r,s,n=null,a=0){let o=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,l=this._getWebGLTextureType(a),h=this._getInternalFormat(r),u=this._getRGBABufferInternalSizedFormat(a,r);this._bindTextureDirectly(o,t,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(t._bufferView=i,t.format=r,t.invertY=s,t._compression=n),t.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),n&&i?this._gl.compressedTexImage3D(o,0,this.getCaps().s3tc[n],t.width,t.height,t.depth,0,i):this._gl.texImage3D(o,0,u,t.width,t.height,t.depth,0,h,l,i),t.generateMipMaps&&this._gl.generateMipmap(o),this._bindTextureDirectly(o,null),t.isReady=!0}}r6.B.prototype.updateRawTexture=function(e,t,i,r,s=null,n=0,a=!1){if(!e)return;let o=this._getRGBABufferInternalSizedFormat(n,i,a),l=this._getInternalFormat(i),h=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=n,e.invertY=r,e._compression=s),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},r6.B.prototype.createRawTexture=function(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){let c=new r5.l(this,r5.S.Raw);c.baseWidth=t,c.baseHeight=i,c.width=t,c.height=i,c.format=r,c.generateMipMaps=s,c.samplingMode=a,c.invertY=n,c._compression=o,c.type=l,c._useSRGBBuffer=this._getUseSRGBBuffer(u,!s),this._doNotHandleContextLost||(c._bufferView=e),this.updateRawTexture(c,e,r,n,o,l,c._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,c,!0);let d=this._getSamplingParameters(a,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(c),c},r6.B.prototype.createRawCubeTexture=function(e,t,i,r,s,n,a,o=null){let l=this._gl,h=new r5.l(this,r5.S.CubeRaw);h.isCube=!0,h.format=i,h.type=r,this._doNotHandleContextLost||(h._bufferViewArray=e);let u=this._getWebGLTextureType(r),c=this._getInternalFormat(i);c===l.RGB&&(c=l.RGBA),u!==l.FLOAT||this._caps.textureFloatLinearFiltering?u!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?u!==l.FLOAT||this._caps.textureFloatRender?u!==l.HALF_FLOAT||this._caps.colorBufferFloat||(s=!1,rT.Y.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(s=!1,rT.Y.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(s=!1,a=1,rT.Y.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(s=!1,a=1,rT.Y.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")),h.width=t,h.height=t,h.invertY=n,h._compression=o;let d=!this.needPOTTextures||rW.w1.IsExponentOfTwo(h.width)&&rW.w1.IsExponentOfTwo(h.height);if(d||(s=!1),e)this.updateRawCubeTexture(h,e,i,r,n,o);else{let e=this._getRGBABufferInternalSizedFormat(r);this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let t=0;t<6;t++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this.getCaps().s3tc[o],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,e,h.width,h.height,0,c,u,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);let p=this._getSamplingParameters(a,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,p.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,p.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=s,h.samplingMode=a,h.isReady=!0,h},r6.B.prototype.updateRawCubeTexture=function(e,t,i,r,s,n=null,a=0){e._bufferViewArray=t,e.format=i,e.type=r,e.invertY=s,e._compression=n;let o=this._gl,l=this._getWebGLTextureType(r),h=this._getInternalFormat(i),u=this._getRGBABufferInternalSizedFormat(r),c=!1;h===o.RGB&&(h=o.RGBA,c=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===s||!!s),e.width%4!=0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let s=t[i];n?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,this.getCaps().s3tc[n],e.width,e.height,0,s):(c&&(s=_convertRGBtoRGBATextureData(s,e.width,e.height,r)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,u,e.width,e.height,0,h,l,s))}let d=!this.needPOTTextures||rW.w1.IsExponentOfTwo(e.width)&&rW.w1.IsExponentOfTwo(e.height);d&&e.generateMipMaps&&0===a&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},r6.B.prototype.createRawCubeTextureFromUrl=function(e,t,i,r,s,n,a,o,l=null,h=null,u=3,c=!1){let d=this._gl,p=this.createRawCubeTexture(null,i,r,s,!n,c,u,null);null==t||t.addPendingData(p),p.url=e,p.isReady=!1,this._internalTexturesCache.push(p);let internalCallback=e=>{let i=p.width,n=a(e);if(n){if(o){let e=this._getWebGLTextureType(s),t=this._getInternalFormat(r),a=this._getRGBABufferInternalSizedFormat(s),l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);let h=o(n);for(let r=0;r<h.length;r++){let n=i>>r;for(let i=0;i<6;i++){let o=h[r][i];l&&(o=_convertRGBtoRGBATextureData(o,n,n,s)),d.texImage2D(i,r,a,n,n,0,t,e,o)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(p,n,r,s,c);p.isReady=!0,null==t||t.removePendingData(p),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,e=>{internalCallback(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},r6.B.prototype.createRawTexture2DArray=_makeCreateRawTextureFunction(!1),r6.B.prototype.createRawTexture3D=_makeCreateRawTextureFunction(!0),r6.B.prototype.updateRawTexture2DArray=_makeUpdateRawTextureFunction(!1),r6.B.prototype.updateRawTexture3D=_makeUpdateRawTextureFunction(!0);let rawTexture_RawTexture=class rawTexture_RawTexture extends texture_Texture{constructor(e,t,i,r,s,n=!0,a=!1,o=3,l=0,h,u){if(super(null,s,!n,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=r,!this._engine)return;this._engine._caps.textureFloatLinearFiltering||1!==l||(o=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(o=1),this._texture=this._engine.createRawTexture(e,t,i,r,n,a,o,null,l,null!=h?h:0,null!=u&&u),this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.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,r,s=!0,n=!1,a=3){return new rawTexture_RawTexture(e,t,i,1,r,s,n,a)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,n=!1,a=3){return new rawTexture_RawTexture(e,t,i,2,r,s,n,a)}static CreateAlphaTexture(e,t,i,r,s=!0,n=!1,a=3){return new rawTexture_RawTexture(e,t,i,0,r,s,n,a)}static CreateRGBTexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=0,h=!1){return new rawTexture_RawTexture(e,t,i,4,r,s,n,a,o,l,h)}static CreateRGBATexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=0,h=!1){return new rawTexture_RawTexture(e,t,i,5,r,s,n,a,o,l,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=!1){return new rawTexture_RawTexture(e,t,i,5,r,s,n,a,o,1,l)}static CreateRTexture(e,t,i,r,s=!0,n=!1,a=texture_Texture.TRILINEAR_SAMPLINGMODE,o=1){return new rawTexture_RawTexture(e,t,i,6,r,s,n,a,o)}static CreateRStorageTexture(e,t,i,r,s=!0,n=!1,a=texture_Texture.TRILINEAR_SAMPLINGMODE,o=1){return new rawTexture_RawTexture(e,t,i,6,r,s,n,a,o,1)}};var r8=i(6114);let AutoRotationBehavior=class AutoRotationBehavior{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;let t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===r8.kD.POINTERDOWN){this._isPointerDown=!0;return}e.type===r8.kD.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;let e=rF.F.Now,t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();let i=e-this._lastInteractionTime-this._idleRotationWaitTime,r=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*r,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))})}detach(){if(!this._attachedCamera)return;let 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:rF.F.Now}_reachTargetAlpha(){return!!this._attachedCamera&&!!this.targetAlpha&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)<rw.kn}_userIsZooming(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset}_shouldAnimationStopForInteraction(){if(!this._attachedCamera)return!1;let e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()}_applyUserInteraction(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=rF.F.Now)}_userIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}};let BouncingBehavior=class BouncingBehavior{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=[]}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;let t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(e=>{if(!e)return;e.computeWorldMatrix(!0);let 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||(BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode),this._radiusBounceTransition=animation_Animation.CreateAnimation("radius",animation_Animation.ANIMATIONTYPE_FLOAT,60,BouncingBehavior.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;let t=animation_Animation.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()}};BouncingBehavior.EasingFunction=new BackEase(.3),BouncingBehavior.EasingMode=EasingFunction.EASINGMODE_EASEOUT;let FramingBehavior=class FramingBehavior{constructor(){this.onTargetFramingAnimationEndObservable=new rf.y$,this._mode=FramingBehavior.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=[],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;let t=this._attachedCamera.getScene();FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===r8.kD.POINTERDOWN){this._isPointerDown=!0;return}e.type===r8.kD.POINTERUP&&(this._isPointerDown=!1)}),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;let 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);let r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){let r=new rm.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new rm.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t<e.length;t++){let i=e[t].getHierarchyBoundingVectors(!0);rm.P.CheckExtends(i.min,r,s),rm.P.CheckExtends(i.max,r,s)}this.zoomOnBoundingInfo(r,s,t,i)}zoomOnBoundingInfo(e,t,i=!1,r=null){let s;if(!this._attachedCamera)return!1;let n=e.y,a=t.y,o=n+(a-n)*this._positionScale,l=t.subtract(e).scale(.5);if(i)s=new rm.P(0,o,0);else{let t=e.add(l);s=new rm.P(t.x,o,t.z)}this._vectorTransition||(this._vectorTransition=animation_Animation.CreateAnimation("target",animation_Animation.ANIMATIONTYPE_VECTOR3,60,FramingBehavior.EasingFunction)),this._betaIsAnimating=!0;let h=animation_Animation.TransitionTo("target",s,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);h&&this._animatables.push(h);let u=0;if(this._mode===FramingBehavior.FitFrustumSidesMode){let i=this._calculateLowerRadiusFromModelBoundingSphere(e,t);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=l.length()+this._attachedCamera.minZ),u=i}else this._mode===FramingBehavior.IgnoreBoundsSizeMode&&(u=this._calculateLowerRadiusFromModelBoundingSphere(e,t),this.autoCorrectCameraLimitsAndSensibility&&null===this._attachedCamera.lowerRadiusLimit&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){let i=t.subtract(e).length();this._attachedCamera.panningSensibility=5e3/i,this._attachedCamera.wheelPrecision=100/u}return this._radiusTransition||(this._radiusTransition=animation_Animation.CreateAnimation("radius",animation_Animation.ANIMATIONTYPE_FLOAT,60,FramingBehavior.EasingFunction)),(h=animation_Animation.TransitionTo("radius",u,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,()=>{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}))&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){let i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===FramingBehavior.IgnoreBoundsSizeMode&&(r=r<i.lowerRadiusLimit?i.lowerRadiusLimit:r),i.upperRadiusLimit&&(r=r>i.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;let e=rF.F.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>.5*Math.PI&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=animation_Animation.CreateAnimation("beta",animation_Animation.ANIMATIONTYPE_FLOAT,60,FramingBehavior.EasingFunction));let e=animation_Animation.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=rF.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)}};FramingBehavior.EasingFunction=new ExponentialEase,FramingBehavior.EasingMode=EasingFunction.EASINGMODE_EASEINOUT,FramingBehavior.IgnoreBoundsSizeMode=0,FramingBehavior.FitFrustumSidesMode=1;var r7=i(2248),r9=i(6491);let ray_Ray=class ray_Ray{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new ray_Ray(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){let r,s,n,a;let o=ray_Ray._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),l=ray_Ray._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i),h=0,u=Number.MAX_VALUE;if(1e-7>Math.abs(this.direction.x)){if(this.origin.x<o.x||this.origin.x>l.x)return!1}else if(r=1/this.direction.x,s=(o.x-this.origin.x)*r,(n=(l.x-this.origin.x)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;if(1e-7>Math.abs(this.direction.y)){if(this.origin.y<o.y||this.origin.y>l.y)return!1}else if(r=1/this.direction.y,s=(o.y-this.origin.y)*r,(n=(l.y-this.origin.y)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;if(1e-7>Math.abs(this.direction.z)){if(this.origin.z<o.z||this.origin.z>l.z)return!1}else if(r=1/this.direction.z,s=(o.z-this.origin.z)*r,(n=(l.z-this.origin.z)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){let i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,n=i*i+r*r+s*s,a=e.radius+t,o=a*a;if(n<=o)return!0;let l=i*this.direction.x+r*this.direction.y+s*this.direction.z;return!(l<0)&&n-l*l<=o}intersectsTriangle(e,t,i){let r=ray_Ray._TmpVector3[0],s=ray_Ray._TmpVector3[1],n=ray_Ray._TmpVector3[2],a=ray_Ray._TmpVector3[3],o=ray_Ray._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),rm.P.CrossToRef(this.direction,s,n);let l=rm.P.Dot(r,n);if(0===l)return null;let h=1/l;this.origin.subtractToRef(e,a);let u=rm.P.Dot(a,n)*h;if(u<0||u>1)return null;rm.P.CrossToRef(a,r,o);let c=rm.P.Dot(this.direction,o)*h;if(c<0||u+c>1)return null;let d=rm.P.Dot(s,o)*h;return d>this.length?null:new r9.c(1-u-c,u,d)}intersectsPlane(e){let t;let i=rm.P.Dot(e.normal,this.direction);if(999999997475243e-21>Math.abs(i))return null;{let r=rm.P.Dot(e.normal,this.origin);return(t=(-e.d-r)/i)<0?t<-.000000999999997475243?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{let e=(this.origin.y-t)/this.direction.y;if(e>0)return null;return new rm.P(this.origin.x+-(this.direction.x*e),t,this.origin.z+-(this.direction.z*e))}case"x":{let e=(this.origin.x-t)/this.direction.x;if(e>0)return null;return new rm.P(t,this.origin.y+-(this.direction.y*e),this.origin.z+-(this.direction.z*e))}case"z":{let e=(this.origin.z-t)/this.direction.z;if(e>0)return null;return new rm.P(this.origin.x+-(this.direction.x*e),this.origin.y+-(this.direction.y*e),t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,n=!1){let a=rm.jp.Matrix[0];return e.getWorldMatrix().invertToRef(a),this._tmpRay?ray_Ray.TransformToRef(this,a,this._tmpRay):this._tmpRay=ray_Ray.Transform(this,a),e.intersects(this._tmpRay,t,i,r,s,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;r<e.length;r++){let s=this.intersectsMesh(e[r],t);s.hit&&i.push(s)}return i.sort(this._comparePickingInfo),i}_comparePickingInfo(e,t){return e.distance<t.distance?-1:e.distance>t.distance?1:0}intersectionSegment(e,t,i){let r=this.origin,s=rm.jp.Vector3[0],n=rm.jp.Vector3[1],a=rm.jp.Vector3[2],o=rm.jp.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(ray_Ray._Rayl,a),r.addToRef(a,n),e.subtractToRef(r,o);let l=rm.P.Dot(s,s),h=rm.P.Dot(s,a),u=rm.P.Dot(a,a),c=rm.P.Dot(s,o),d=rm.P.Dot(a,o),p=l*u-h*h,_,f=p,m,g=p;p<ray_Ray._Smallnum?(_=0,f=1,m=d,g=u):(_=h*d-u*c,m=l*d-h*c,_<0?(_=0,m=d,g=u):_>f&&(_=f,m=d+h,g=u)),m<0?(m=0,0>-c?_=0:-c>l?_=f:(_=-c,f=l)):m>g&&(m=g,-c+h<0?_=0:-c+h>l?_=f:(_=-c+h,f=l));let v=Math.abs(_)<ray_Ray._Smallnum?0:_/f,x=Math.abs(m)<ray_Ray._Smallnum?0:m/g,T=rm.jp.Vector3[4];a.scaleToRef(x,T);let S=rm.jp.Vector3[5];s.scaleToRef(v,S),S.addInPlace(o);let C=rm.jp.Vector3[6];S.subtractToRef(T,C);let E=x>0&&x<=this.length&&C.lengthSquared()<i*i;return E?S.length():-1}update(e,t,i,r,s,n,a,o=!1){if(o){ray_Ray._RayDistant||(ray_Ray._RayDistant=ray_Ray.Zero()),ray_Ray._RayDistant.unprojectRayToRef(e,t,i,r,rm.y3.IdentityReadOnly,n,a);let o=rm.jp.Matrix[0];s.invertToRef(o),ray_Ray.TransformToRef(ray_Ray._RayDistant,o,this)}else this.unprojectRayToRef(e,t,i,r,s,n,a);return this}static Zero(){return new ray_Ray(rm.P.Zero(),rm.P.Zero())}static CreateNew(e,t,i,r,s,n,a){let o=ray_Ray.Zero();return o.update(e,t,i,r,s,n,a)}static CreateNewFromTo(e,t,i=rm.y3.IdentityReadOnly){let r=t.subtract(e),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),ray_Ray.Transform(new ray_Ray(e,r,s),i)}static Transform(e,t){let i=new ray_Ray(new rm.P(0,0,0),new rm.P(0,0,0));return ray_Ray.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){rm.P.TransformCoordinatesToRef(e.origin,t,i.origin),rm.P.TransformNormalToRef(e.direction,t,i.direction),i.length=e.length;let r=i.direction,s=r.length();if(!(0===s||1===s)){let e=1/s;r.x*=e,r.y*=e,r.z*=e,i.length*=s}}unprojectRayToRef(e,t,i,r,s,n,a){let o=rm.jp.Matrix[0];s.multiplyToRef(n,o),o.multiplyToRef(a,o),o.invert();let l=rS.l.LastCreatedEngine,h=rm.jp.Vector3[0];h.x=e/i*2-1,h.y=-(t/r*2-1),h.z=(null==l?void 0:l.useReverseDepthBuffer)?1:(null==l?void 0:l.isNDCHalfZRange)?0:-1;let u=rm.jp.Vector3[1].copyFromFloats(h.x,h.y,1-1e-8),c=rm.jp.Vector3[2],d=rm.jp.Vector3[3];rm.P._UnprojectFromInvertedMatrixToRef(h,o,c),rm.P._UnprojectFromInvertedMatrixToRef(u,o,d),this.origin.copyFrom(c),d.subtractToRef(c,this.direction),this.direction.normalize()}};ray_Ray._TmpVector3=rB.B.BuildArray(6,rm.P.Zero),ray_Ray._RayDistant=ray_Ray.Zero(),ray_Ray._Smallnum=1e-8,ray_Ray._Rayl=1e9,rN.x.prototype.createPickingRay=function(e,t,i,r,s=!1){let n=ray_Ray.Zero();return this.createPickingRayToRef(e,t,i,n,r,s),n},rN.x.prototype.createPickingRayToRef=function(e,t,i,r,s,n=!1,a=!1){let o=this.getEngine();if(!s){if(!this.activeCamera)return this;s=this.activeCamera}let l=s.viewport,h=l.toGlobal(o.getRenderWidth(),o.getRenderHeight());return e=e/o.getHardwareScalingLevel()-h.x,t=t/o.getHardwareScalingLevel()-(o.getRenderHeight()-h.y-h.height),r.update(e,t,h.width,h.height,i||rm.y3.IdentityReadOnly,n?rm.y3.IdentityReadOnly:s.getViewMatrix(),s.getProjectionMatrix(),a),this},rN.x.prototype.createPickingRayInCameraSpace=function(e,t,i){let r=ray_Ray.Zero();return this.createPickingRayInCameraSpaceToRef(e,t,r,i),r},rN.x.prototype.createPickingRayInCameraSpaceToRef=function(e,t,i,r){if(!r7.p)return this;let s=this.getEngine();if(!r){if(!this.activeCamera)throw Error("Active camera not set");r=this.activeCamera}let n=r.viewport,a=n.toGlobal(s.getRenderWidth(),s.getRenderHeight()),o=rm.y3.Identity();return e=e/s.getHardwareScalingLevel()-a.x,t=t/s.getHardwareScalingLevel()-(s.getRenderHeight()-a.y-a.height),i.update(e,t,a.width,a.height,o,o,r.getProjectionMatrix()),this},rN.x.prototype._internalPickForMesh=function(e,t,i,r,s,n,a,o){let l=t(r,i.enableDistantPicking),h=i.intersects(l,s,a,n,r,o);return h&&h.hit&&(s||null==e||!(h.distance>=e.distance))?h:null},rN.x.prototype._internalPick=function(e,t,i,r,s){let n=null,a=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l<this.meshes.length;l++){let h=this.meshes[l];if(t){if(!t(h))continue}else if(!h.isEnabled()||!h.isVisible||!h.isPickable)continue;let u=a&&h.isWorldMatrixCameraDependent(),c=h.computeWorldMatrix(u,o);if(h.hasThinInstances&&h.thinInstanceEnablePicking){let t=this._internalPickForMesh(n,e,h,c,!0,!0,s);if(t){if(r)return t;let a=rm.jp.Matrix[1],o=h.thinInstanceGetWorldMatrices();for(let t=0;t<o.length;t++){let l=o[t];l.multiplyToRef(c,a);let u=this._internalPickForMesh(n,e,h,a,i,r,s,!0);if(u&&((n=u).thinInstanceIndex=t,i))return n}}}else{let t=this._internalPickForMesh(n,e,h,c,i,r,s);if(t&&(n=t,i))return n}}return n||new r7.p},rN.x.prototype._internalMultiPick=function(e,t,i){if(!r7.p)return null;let r=[],s=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let a=0;a<this.meshes.length;a++){let o=this.meshes[a];if(t){if(!t(o))continue}else if(!o.isEnabled()||!o.isVisible||!o.isPickable)continue;let l=s&&o.isWorldMatrixCameraDependent(),h=o.computeWorldMatrix(l,n);if(o.hasThinInstances&&o.thinInstanceEnablePicking){let t=this._internalPickForMesh(null,e,o,h,!0,!0,i);if(t){let t=rm.jp.Matrix[1],s=o.thinInstanceGetWorldMatrices();for(let n=0;n<s.length;n++){let a=s[n];a.multiplyToRef(h,t);let l=this._internalPickForMesh(null,e,o,t,!1,!1,i,!0);l&&(l.thinInstanceIndex=n,r.push(l))}}}else{let t=this._internalPickForMesh(null,e,o,h,!1,!1,i);t&&r.push(t)}}return r},rN.x.prototype.pickWithBoundingInfo=function(e,t,i,r,s){if(!r7.p)return null;let n=this._internalPick(i=>(this._tempPickingRay||(this._tempPickingRay=ray_Ray.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null),this._tempPickingRay),i,r,!0);return n&&(n.ray=this.createPickingRay(e,t,rm.y3.Identity(),s||null)),n},Object.defineProperty(rN.x.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),rN.x.prototype.pick=function(e,t,i,r,s,n,a=!1){let o=this._internalPick((i,r)=>(this._tempPickingRay||(this._tempPickingRay=ray_Ray.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null,!1,r),this._tempPickingRay),i,r,!1,n);return o&&(o.ray=this.createPickingRay(e,t,rm.y3.Identity(),s||null)),o},rN.x.prototype.pickWithRay=function(e,t,i,r){let s=this._internalPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=rm.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ray_Ray.Zero()),ray_Ray.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i,!1,r);return s&&(s.ray=e),s},rN.x.prototype.multiPick=function(e,t,i,r,s){return this._internalMultiPick(i=>this.createPickingRay(e,t,i,r||null),i,s)},rN.x.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=rm.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ray_Ray.Zero()),ray_Ray.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i)},rj.V.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new ray_Ray(rm.P.Zero(),rm.P.Zero(),e),e,t,i)},rj.V.prototype.getForwardRayToRef=function(e,t=100,i,r){return i||(i=this.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(this.position),rm.jp.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),rm.P.TransformNormalToRef(rm.jp.Vector3[2],i,rm.jp.Vector3[3]),rm.P.NormalizeToRef(rm.jp.Vector3[3],e.direction),e};let pivotTools_PivotTools=class pivotTools_PivotTools{static _RemoveAndStorePivotPoint(e){e&&0===pivotTools_PivotTools._PivotCached&&(e.getPivotPointToRef(pivotTools_PivotTools._OldPivotPoint),pivotTools_PivotTools._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,pivotTools_PivotTools._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(rm.y3.IdentityReadOnly),pivotTools_PivotTools._OldPivotPoint.subtractToRef(e.getPivotPoint(),pivotTools_PivotTools._PivotTranslation),pivotTools_PivotTools._PivotTmpVector.copyFromFloats(1,1,1),pivotTools_PivotTools._PivotTmpVector.subtractInPlace(e.scaling),pivotTools_PivotTools._PivotTmpVector.multiplyInPlace(pivotTools_PivotTools._PivotTranslation),e.position.addInPlace(pivotTools_PivotTools._PivotTmpVector))),pivotTools_PivotTools._PivotCached++}static _RestorePivotPoint(e){e&&!pivotTools_PivotTools._OldPivotPoint.equalsToFloats(0,0,0)&&1===pivotTools_PivotTools._PivotCached&&(e.setPivotPoint(pivotTools_PivotTools._OldPivotPoint),e._postMultiplyPivotMatrix=pivotTools_PivotTools._PivotPostMultiplyPivotMatrix,pivotTools_PivotTools._PivotTmpVector.copyFromFloats(1,1,1),pivotTools_PivotTools._PivotTmpVector.subtractInPlace(e.scaling),pivotTools_PivotTools._PivotTmpVector.multiplyInPlace(pivotTools_PivotTools._PivotTranslation),e.position.subtractInPlace(pivotTools_PivotTools._PivotTmpVector)),this._PivotCached--}};pivotTools_PivotTools._PivotCached=0,pivotTools_PivotTools._OldPivotPoint=new rm.P,pivotTools_PivotTools._PivotTranslation=new rm.P,pivotTools_PivotTools._PivotTmpVector=new rm.P,pivotTools_PivotTools._PivotPostMultiplyPivotMatrix=!1;var se=i(2696);function CreatePlaneVertexData(e){let t=[],i=[],r=[],s=[],n=e.width||e.size||1,a=e.height||e.size||1,o=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,l=n/2,h=a/2;i.push(-l,-h,0),r.push(0,0,-1),s.push(0,r4.e.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),r.push(0,0,-1),s.push(1,r4.e.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),r.push(0,0,-1),s.push(1,r4.e.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),r.push(0,0,-1),s.push(0,r4.e.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),se.x._ComputeSides(o,i,t,r,s,e.frontUVs,e.backUVs);let u=new se.x;return u.indices=t,u.positions=i,u.normals=r,u.uvs=s,u}function planeBuilder_CreatePlane(e,t={},i=null){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreatePlaneVertexData(t);return s.applyToMesh(r,t.updatable),t.sourcePlane&&(r.translate(t.sourcePlane.normal,-t.sourcePlane.d),r.setDirection(t.sourcePlane.normal.scale(-1))),r}se.x.CreatePlane=CreatePlaneVertexData,rV.Kj.CreatePlane=(e,t,i,r,s)=>planeBuilder_CreatePlane(e,{size:t,width:t,height:t,sideOrientation:s,updatable:r},i);let pointerDragBehavior_PointerDragBehavior=class pointerDragBehavior_PointerDragBehavior{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 rf.y$,this.onDragStartObservable=new rf.y$,this.onDragEndObservable=new rf.y$,this.onEnabledObservable=new rf.y$,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new rm.P(0,0,0),this._alternatePickedPoint=new rm.P(0,0,0),this._worldDragAxis=new rm.P(0,0,0),this._targetPosition=new rm.P(0,0,0),this._attachedToElement=!1,this._startDragRay=new ray_Ray(new rm.P,new rm.P),this._lastPointerRay={},this._dragDelta=new rm.P,this._pointA=new rm.P(0,0,0),this._pointC=new rm.P(0,0,0),this._localAxis=new rm.P(0,0,0),this._lookAt=new rm.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,pointerDragBehavior_PointerDragBehavior._PlaneScene||(this._debugMode?pointerDragBehavior_PointerDragBehavior._PlaneScene=this._scene:(pointerDragBehavior_PointerDragBehavior._PlaneScene=new rN.x(this._scene.getEngine(),{virtual:!0}),pointerDragBehavior_PointerDragBehavior._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{pointerDragBehavior_PointerDragBehavior._PlaneScene.dispose(),pointerDragBehavior_PointerDragBehavior._PlaneScene=null}))),this._dragPlane=planeBuilder_CreatePlane("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:rV.Kj.DOUBLESIDE},pointerDragBehavior_PointerDragBehavior._PlaneScene),this.lastDragPosition=new rm.P(0,0,0);let i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(e=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(e.type==r8.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==r8.kD.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==e.event.pointerId&&(this._activeDragButton===e.event.button||-1===this._activeDragButton)&&this.releaseDrag();else if(e.type==r8.kD.POINTERMOVE){let t=e.event.pointerId;if(this.currentDraggingPointerId===pointerDragBehavior_PointerDragBehavior._AnyMouseId&&t!==pointerDragBehavior_PointerDragBehavior._AnyMouseId){let i=e.event,r="mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent;r&&(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 ray_Ray(new rm.P,new rm.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))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let e=!1;pivotTools_PivotTools._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),pivotTools_PivotTools._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()){let 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=pointerDragBehavior_PointerDragBehavior._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===pointerDragBehavior_PointerDragBehavior._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;pivotTools_PivotTools._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);let r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),pivotTools_PivotTools._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;let t=this._pickWithRayOnDragPlane(e);if(t){pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?rm.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=rm.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),pivotTools_PivotTools._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(rm.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)return null;{this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*rm.P.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);let t=rm.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}}let i=pointerDragBehavior_PointerDragBehavior._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?rm.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(rm.P.Dot(this._localAxis,this._pointC))>.999?Math.abs(rm.P.Dot(rm.P.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(rm.P.Right()):this._lookAt.copyFrom(rm.P.UpReadOnly):(rm.P.CrossToRef(this._localAxis,this._pointC,this._lookAt),rm.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?rm.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()}};pointerDragBehavior_PointerDragBehavior._AnyMouseId=-2;let webXRFeaturesManager_WebXRFeatureName=class webXRFeaturesManager_WebXRFeatureName{};webXRFeaturesManager_WebXRFeatureName.ANCHOR_SYSTEM="xr-anchor-system",webXRFeaturesManager_WebXRFeatureName.BACKGROUND_REMOVER="xr-background-remover",webXRFeaturesManager_WebXRFeatureName.HIT_TEST="xr-hit-test",webXRFeaturesManager_WebXRFeatureName.MESH_DETECTION="xr-mesh-detection",webXRFeaturesManager_WebXRFeatureName.PHYSICS_CONTROLLERS="xr-physics-controller",webXRFeaturesManager_WebXRFeatureName.PLANE_DETECTION="xr-plane-detection",webXRFeaturesManager_WebXRFeatureName.POINTER_SELECTION="xr-controller-pointer-selection",webXRFeaturesManager_WebXRFeatureName.TELEPORTATION="xr-controller-teleportation",webXRFeaturesManager_WebXRFeatureName.FEATURE_POINTS="xr-feature-points",webXRFeaturesManager_WebXRFeatureName.HAND_TRACKING="xr-hand-tracking",webXRFeaturesManager_WebXRFeatureName.IMAGE_TRACKING="xr-image-tracking",webXRFeaturesManager_WebXRFeatureName.NEAR_INTERACTION="xr-near-interaction",webXRFeaturesManager_WebXRFeatureName.DOM_OVERLAY="xr-dom-overlay",webXRFeaturesManager_WebXRFeatureName.MOVEMENT="xr-controller-movement",webXRFeaturesManager_WebXRFeatureName.LIGHT_ESTIMATION="xr-light-estimation",webXRFeaturesManager_WebXRFeatureName.EYE_TRACKING="xr-eye-tracking",webXRFeaturesManager_WebXRFeatureName.WALKING_LOCOMOTION="xr-walking-locomotion",webXRFeaturesManager_WebXRFeatureName.LAYERS="xr-layers",webXRFeaturesManager_WebXRFeatureName.DEPTH_SENSING="xr-depth-sensing",webXRFeaturesManager_WebXRFeatureName.SPACE_WARP="xr-space-warp";let WebXRFeaturesManager=class WebXRFeaturesManager{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)})}),this._xrSessionManager.onXRSessionEnded.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)})})}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){let s=this._AvailableFeatures[e][t];if(!s)throw Error("feature not found");return s(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){let t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){let t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){let t="string"==typeof e?e:e.Name,i=this._features[t];return!!i&&!!i.enabled&&(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0)}dispose(){this.getEnabledFeatures().forEach(e=>{this.disableFeature(e)})}enableFeature(e,t="latest",i={},r=!0,s=!0){let n="string"==typeof e?e:e.Name,a=0;if("string"==typeof t){if(!t)throw Error(`Error in provided version - ${n} (${t})`);if(-1===(a="stable"===t?WebXRFeaturesManager.GetStableVersionOfFeature(n):"latest"===t?WebXRFeaturesManager.GetLatestVersionOfFeature(n):+t)||isNaN(a))throw Error(`feature not found - ${n} (${t})`)}else a=t;let o=WebXRFeaturesManager._ConflictingFeatures[n];if(void 0!==o&&-1!==this.getEnabledFeatures().indexOf(o))throw Error(`Feature ${n} cannot be enabled while ${o} is enabled.`);let l=this._features[n],h=WebXRFeaturesManager.ConstructFeature(n,a,this._xrSessionManager,i);if(!h)throw Error(`feature not found - ${n}`);l&&this.disableFeature(n);let u=h();if(u.dependsOn){let e=u.dependsOn.every(e=>!!this._features[e]);if(!e)throw Error(`Dependant features missing. Make sure the following features are enabled - ${u.dependsOn.join(", ")}`)}if(u.isCompatible())return this._features[n]={featureImplementation:u,enabled:!0,version:a,required:s},r?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(!s)return rW.w1.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),u;throw Error("required feature not compatible")}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){let t=this.getEnabledFeatures();for(let i of t){let t=this._features[i],r=t.featureImplementation.xrNativeFeatureName;if(r&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(r)&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(r)&&e.optionalFeatures.push(r))),t.featureImplementation.getXRSessionInitExtension){let i=await t.featureImplementation.getXRSessionInitExtension();e=Object.assign(Object.assign({},e),i)}}return e}};WebXRFeaturesManager._AvailableFeatures={},WebXRFeaturesManager._ConflictingFeatures={[webXRFeaturesManager_WebXRFeatureName.TELEPORTATION]:webXRFeaturesManager_WebXRFeatureName.MOVEMENT,[webXRFeaturesManager_WebXRFeatureName.MOVEMENT]:webXRFeaturesManager_WebXRFeatureName.TELEPORTATION};let WebXRAbstractFeature=class WebXRAbstractFeature{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)})}};let PhysicsJoint=class PhysicsJoint{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)}};PhysicsJoint.DistanceJoint=0,PhysicsJoint.HingeJoint=1,PhysicsJoint.BallAndSocketJoint=2,PhysicsJoint.WheelJoint=3,PhysicsJoint.SliderJoint=4,PhysicsJoint.PrismaticJoint=5,PhysicsJoint.UniversalJoint=6,PhysicsJoint.Hinge2Joint=PhysicsJoint.WheelJoint,PhysicsJoint.PointToPointJoint=8,PhysicsJoint.SpringJoint=9,PhysicsJoint.LockJoint=10,rV.Kj._PhysicsImpostorParser=function(e,t,i){return new physicsImpostor_PhysicsImpostor(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};let physicsImpostor_PhysicsImpostor=class physicsImpostor_PhysicsImpostor{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;let e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){if(this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=[],this._onAfterPhysicsStepCallbacks=[],this._onPhysicsCollideCallbacks=[],this._deltaPosition=rm.P.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new rm._f,this._tmpQuat2=new rm._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 rm._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,physicsImpostor_PhysicsImpostor._TmpVecs[0]),this.object.translate(physicsImpostor_PhysicsImpostor._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||!this._physicsEngine)return;let 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){rT.Y.Error("No object was provided. A physics object is obligatory");return}if(this.object.parent&&0!==i.mass&&rT.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)return;this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=rm._f.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new rm._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&&rT.Y.Warn("You must affect impostors to children before affecting impostor to parent.")):rT.Y.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){if(this.object.parent instanceof rG.x){let e=this.object.parent;return e.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)return physicsImpostor_PhysicsImpostor.DEFAULT_OBJECT_SIZE;{let e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=physicsImpostor_PhysicsImpostor.IDENTITY_QUATERNION;let i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);let r=this.object.getBoundingInfo(),s=r.boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}}getObjectCenter(){if(!this.object.getBoundingInfo)return this.object.position;{let e=this.object.getBoundingInfo();return e.boundingBox.centerWorld}}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):rm.P.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):rm.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){let t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):rT.Y.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){let t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):rT.Y.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e],r=-1,s=this._onPhysicsCollideCallbacks.some((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){let t=e.otherImpostors.every(e=>i.indexOf(e)>-1);return t&&(r=s),t}return!1});s?this._onPhysicsCollideCallbacks.splice(r,1):rT.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):rm._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){let r=new PhysicsJoint(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,s){if(!this._physicsEngine)return this;let n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor&&this._physicsEngine&&n.appendAnchor(this,e,t,i,r,s),this}addHook(e,t,i,r){if(!this._physicsEngine)return this;let s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor&&this._physicsEngine&&s.appendHook(this,e,t,i,r),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 physicsImpostor_PhysicsImpostor(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 rm._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,r,s){let n=physicsImpostor_PhysicsImpostor._TmpVecs[0],a=this.object;if(a.rotationQuaternion){if(s){let i=physicsImpostor_PhysicsImpostor._TmpQuat;a.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,rL.T.WORLD,t)}else e.setRotationQuaternion(a.rotationQuaternion,rL.T.WORLD,t)}n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==r&&(r=i.length()),n.x*=r,n.y*=r,n.z*=r),e.getParent()?(n.addInPlace(a.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(a.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,r,s,n){let a=this.object;if(a.rotationQuaternion){if(s){let i=physicsImpostor_PhysicsImpostor._TmpQuat;e.getRotationQuaternionToRef(rL.T.WORLD,t,i),i.multiplyToRef(s,a.rotationQuaternion)}else e.getRotationQuaternionToRef(rL.T.WORLD,t,a.rotationQuaternion)}let o=physicsImpostor_PhysicsImpostor._TmpVecs[0],l=physicsImpostor_PhysicsImpostor._TmpVecs[1];n||((n=physicsImpostor_PhysicsImpostor._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,o),null==r&&i&&(r=i.length()),null!=r&&(o.x+=l.x*r,o.y+=l.y*r,o.z+=l.z*r),a.setAbsolutePosition(o)}};physicsImpostor_PhysicsImpostor.DEFAULT_OBJECT_SIZE=new rm.P(1,1,1),physicsImpostor_PhysicsImpostor.IDENTITY_QUATERNION=rm._f.Identity(),physicsImpostor_PhysicsImpostor._TmpVecs=rB.B.BuildArray(3,rm.P.Zero),physicsImpostor_PhysicsImpostor._TmpQuat=rm._f.Identity(),physicsImpostor_PhysicsImpostor.NoImpostor=0,physicsImpostor_PhysicsImpostor.SphereImpostor=1,physicsImpostor_PhysicsImpostor.BoxImpostor=2,physicsImpostor_PhysicsImpostor.PlaneImpostor=3,physicsImpostor_PhysicsImpostor.MeshImpostor=4,physicsImpostor_PhysicsImpostor.CapsuleImpostor=6,physicsImpostor_PhysicsImpostor.CylinderImpostor=7,physicsImpostor_PhysicsImpostor.ParticleImpostor=8,physicsImpostor_PhysicsImpostor.HeightmapImpostor=9,physicsImpostor_PhysicsImpostor.ConvexHullImpostor=10,physicsImpostor_PhysicsImpostor.CustomImpostor=100,physicsImpostor_PhysicsImpostor.RopeImpostor=101,physicsImpostor_PhysicsImpostor.ClothImpostor=102,physicsImpostor_PhysicsImpostor.SoftbodyImpostor=103;var st=i(2697),si=i(3477);(l=tf||(tf={}))[l.Clean=0]="Clean",l[l.Stop=1]="Stop",l[l.Sync=2]="Sync",l[l.NoSync=3]="NoSync";let sceneLoader_SceneLoader=class sceneLoader_SceneLoader{static get ForceFullSceneLoadingForIncremental(){return st.Z.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){st.Z.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return st.Z.ShowLoadingScreen}static set ShowLoadingScreen(e){st.Z.ShowLoadingScreen=e}static get loggingLevel(){return st.Z.loggingLevel}static set loggingLevel(e){st.Z.loggingLevel=e}static get CleanBoneMatrixWeights(){return st.Z.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){st.Z.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return sceneLoader_SceneLoader._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){let t=sceneLoader_SceneLoader._RegisteredPlugins[e];return t||(rT.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"),sceneLoader_SceneLoader.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(let t in sceneLoader_SceneLoader._RegisteredPlugins){let i=sceneLoader_SceneLoader._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return sceneLoader_SceneLoader._RegisteredPlugins[t]}return sceneLoader_SceneLoader.GetDefaultPlugin()}static _GetPluginForFilename(e){let t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));let i=e.lastIndexOf("."),r=e.substring(i,e.length).toLowerCase();return sceneLoader_SceneLoader._GetPluginForExtension(r)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let r=e.rawData?"binary data":e.url,s="Unable to load from "+r;return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,r,s,n,a,o){let l;let h=sceneLoader_SceneLoader._GetDirectLoad(e.url);if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";let u=a?sceneLoader_SceneLoader._GetPluginForExtension(a):h?sceneLoader_SceneLoader._GetPluginForDirectLoad(e.url):sceneLoader_SceneLoader._GetPluginForFilename(e.url);if(e.rawData&&!u.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";if(!(l=void 0!==u.plugin.createPlugin?u.plugin.createPlugin():u.plugin))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(sceneLoader_SceneLoader.OnPluginActivatedObservable.notifyObservers(l),h&&(l.canDirectLoad&&l.canDirectLoad(e.url)||!(0,rJ.VL)(e.url))){if(l.directLoad){let e=l.directLoad(t,h);e.then?e.then(e=>{i(l,e)}).catch(e=>{s("Error in directLoad of _loadData: "+e,e)}):i(l,e)}else i(l,h);return l}let c=u.isBinary,dataCallback=(e,r)=>{if(t.isDisposed){s("Scene has been disposed");return}i(l,e,r)},d=null,p=!1,_=l.onDisposeObservable;_&&_.add(()=>{p=!0,d&&(d.abort(),d=null),n()});let manifestChecked=()=>{if(p)return;let errorCallback=(e,t)=>{s(null==e?void 0:e.statusText,t)};if(!l.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";d=l.loadFile?l.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,dataCallback,r,c,errorCallback,o):t._loadFile(e.file||e.url,dataCallback,r,!0,c,errorCallback)},f=t.getEngine(),m=f.enableOfflineSupport;if(m){let i=!1;for(let r of t.disableOfflineSupportExceptionRules)if(r.test(e.url)){i=!0;break}m=!i}return m&&rq.D.OfflineProviderFactory?t.offlineProvider=rq.D.OfflineProviderFactory(e.url,manifestChecked,f.disableManifestCheck):manifestChecked(),l}static _GetFileInfo(e,t){let i,r;let s=null,n=null;if(t){if(t.name)i=`file:${t.name}`,r=t.name,s=t;else if(ArrayBuffer.isView(t))i="",r="arrayBuffer",n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,r="";else{if("/"===t.substr(0,1))return rW.w1.Error("Wrong sceneFilename parameter"),null;i=e+t,r=t}}else i=e,r=rW.w1.GetFilename(e),e=rW.w1.GetFolderPath(e);return{url:i,rootUrl:e,name:r,file:s,rawData:n}}static GetPluginForExtension(e){return sceneLoader_SceneLoader._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!sceneLoader_SceneLoader._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){let t=e.extensions;sceneLoader_SceneLoader._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{let t=e.extensions;Object.keys(t).forEach(i=>{sceneLoader_SceneLoader._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",r=rS.l.LastCreatedScene,s=null,n=null,a=null,o=null,l=""){if(!r)return rT.Y.Error("No scene available to import mesh to"),null;let h=sceneLoader_SceneLoader._GetFileInfo(t,i);if(!h)return null;let u={};r.addPendingData(u);let disposeHandler=()=>{r.removePendingData(u)},errorHandler=(e,t)=>{let i=sceneLoader_SceneLoader._FormatErrorMessage(h,e,t);a?a(r,i,new si.LH(i,si.SM.SceneLoaderError,t)):rT.Y.Error(i),disposeHandler()},c=n?e=>{try{n(e)}catch(e){errorHandler("Error in onProgress callback: "+e,e)}}:void 0,successHandler=(e,t,i,n,a,o,l)=>{if(r.importedMeshesFiles.push(h.url),s)try{s(e,t,i,n,a,o,l)}catch(e){errorHandler("Error in onSuccess callback: "+e,e)}r.removePendingData(u)};return sceneLoader_SceneLoader._LoadData(h,r,(t,i,s)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,s)),t.importMesh){let s=[],n=[],a=[];t.importMesh(e,r,i,h.rootUrl,s,n,a,errorHandler)&&(r.loadingPluginName=t.name,successHandler(s,n,a,[],[],[],[]))}else t.importMeshAsync(e,r,i,h.rootUrl,c,h.name).then(e=>{r.loadingPluginName=t.name,successHandler(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)}).catch(e=>{errorHandler(e.message,e)})},c,errorHandler,disposeHandler,o,l)}static ImportMeshAsync(e,t,i="",r=rS.l.LastCreatedScene,s=null,n=null,a=""){return new Promise((o,l)=>{sceneLoader_SceneLoader.ImportMesh(e,t,i,r,(e,t,i,r,s,n,a)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:r,transformNodes:s,geometries:n,lights:a})},s,(e,t,i)=>{l(i||Error(t))},n,a)})}static Load(e,t="",i=rS.l.LastCreatedEngine,r=null,s=null,n=null,a=null,o=""){return i?sceneLoader_SceneLoader.Append(e,t,new rN.x(i),r,s,n,a,o):(rW.w1.Error("No engine available"),null)}static LoadAsync(e,t="",i=rS.l.LastCreatedEngine,r=null,s=null,n=""){return new Promise((a,o)=>{sceneLoader_SceneLoader.Load(e,t,i,e=>{a(e)},r,(e,t,i)=>{o(i||Error(t))},s,n)})}static Append(e,t="",i=rS.l.LastCreatedScene,r=null,s=null,n=null,a=null,o=""){if(!i)return rT.Y.Error("No scene available to append to"),null;let l=sceneLoader_SceneLoader._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let disposeHandler=()=>{i.removePendingData(h)};sceneLoader_SceneLoader.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));let errorHandler=(e,t)=>{let r=sceneLoader_SceneLoader._FormatErrorMessage(l,e,t);n?n(i,r,new si.LH(r,si.SM.SceneLoaderError,t)):rT.Y.Error(r),disposeHandler()},u=s?e=>{try{s(e)}catch(e){errorHandler("Error in onProgress callback",e)}}:void 0,successHandler=()=>{if(r)try{r(i)}catch(e){errorHandler("Error in onSuccess callback",e)}i.removePendingData(h)};return sceneLoader_SceneLoader._LoadData(l,i,(e,t)=>{e.load?!e.load(i,t,l.rootUrl,errorHandler)||(i.loadingPluginName=e.name,successHandler()):e.loadAsync(i,t,l.rootUrl,u,l.name).then(()=>{i.loadingPluginName=e.name,successHandler()}).catch(e=>{errorHandler(e.message,e)})},u,errorHandler,disposeHandler,a,o)}static AppendAsync(e,t="",i=rS.l.LastCreatedScene,r=null,s=null,n=""){return new Promise((a,o)=>{sceneLoader_SceneLoader.Append(e,t,i,e=>{a(e)},r,(e,t,i)=>{o(i||Error(t))},s,n)})}static LoadAssetContainer(e,t="",i=rS.l.LastCreatedScene,r=null,s=null,n=null,a=null,o=""){if(!i)return rT.Y.Error("No scene available to load asset container to"),null;let l=sceneLoader_SceneLoader._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let disposeHandler=()=>{i.removePendingData(h)},errorHandler=(e,t)=>{let r=sceneLoader_SceneLoader._FormatErrorMessage(l,e,t);n?n(i,r,new si.LH(r,si.SM.SceneLoaderError,t)):rT.Y.Error(r),disposeHandler()},u=s?e=>{try{s(e)}catch(e){errorHandler("Error in onProgress callback",e)}}:void 0,successHandler=e=>{if(r)try{r(e)}catch(e){errorHandler("Error in onSuccess callback",e)}i.removePendingData(h)};return sceneLoader_SceneLoader._LoadData(l,i,(e,t)=>{if(e.loadAssetContainer){let r=e.loadAssetContainer(i,t,l.rootUrl,errorHandler);r&&(r.populateRootNodes(),i.loadingPluginName=e.name,successHandler(r))}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,u,l.name).then(t=>{t.populateRootNodes(),i.loadingPluginName=e.name,successHandler(t)}).catch(e=>{errorHandler(e.message,e)}):errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},u,errorHandler,disposeHandler,a,o)}static LoadAssetContainerAsync(e,t="",i=rS.l.LastCreatedScene,r=null,s=null){return new Promise((n,a)=>{sceneLoader_SceneLoader.LoadAssetContainer(e,t,i,e=>{n(e)},r,(e,t,i)=>{a(i||Error(t))},s)})}static ImportAnimations(e,t="",i=rS.l.LastCreatedScene,r=!0,s=tf.Clean,n=null,a=null,o=null,l=null,h=null){if(!i){rT.Y.Error("No scene available to load animations to");return}if(r){for(let e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(e=>{e.dispose()});let e=i.getNodes();e.forEach(e=>{e.animations&&(e.animations=[])})}else switch(s){case tf.Clean:i.animationGroups.slice().forEach(e=>{e.dispose()});break;case tf.Stop:i.animationGroups.forEach(e=>{e.stop()});break;case tf.Sync:i.animationGroups.forEach(e=>{e.reset(),e.restart()});break;case tf.NoSync:break;default:rT.Y.Error("Unknown animation group loading mode value '"+s+"'");return}let u=i.animatables.length;this.LoadAssetContainer(e,t,i,e=>{e.mergeAnimationsTo(i,i.animatables.slice(u),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)},o,l,h)}static ImportAnimationsAsync(e,t="",i=rS.l.LastCreatedScene,r=!0,s=tf.Clean,n=null,a=null,o=null,l=null,h=null){return new Promise((a,l)=>{sceneLoader_SceneLoader.ImportAnimations(e,t,i,r,s,n,e=>{a(e)},o,(e,t,i)=>{l(i||Error(t))},h)})}};sceneLoader_SceneLoader.NO_LOGGING=0,sceneLoader_SceneLoader.MINIMAL_LOGGING=1,sceneLoader_SceneLoader.SUMMARY_LOGGING=2,sceneLoader_SceneLoader.DETAILED_LOGGING=3,sceneLoader_SceneLoader.OnPluginActivatedObservable=new rf.y$,sceneLoader_SceneLoader._RegisteredPlugins={},sceneLoader_SceneLoader._ShowingLoadingScreen=!1;var sr=i(2515);let PushMaterial=class PushMaterial extends sr.F{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new rm.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){let 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)}};(h=tm||(tm={}))[h.Float=1]="Float",h[h.Int=2]="Int",h[h.Vector2=4]="Vector2",h[h.Vector3=8]="Vector3",h[h.Vector4=16]="Vector4",h[h.Color3=32]="Color3",h[h.Color4=64]="Color4",h[h.Matrix=128]="Matrix",h[h.Object=256]="Object",h[h.AutoDetect=1024]="AutoDetect",h[h.BasedOnInput=2048]="BasedOnInput",h[h.All=4095]="All",(u=tg||(tg={}))[u.Vertex=1]="Vertex",u[u.Fragment=2]="Fragment",u[u.Neutral=4]="Neutral",u[u.VertexAndFragment=3]="VertexAndFragment";var ss=i(1088);let NodeMaterialBuildState=class NodeMaterialBuildState{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){let t=e.sharedData.emitComments,i=this.target===tg.Fragment;this.compilationString=` +${t?"//Entry point\n":""}void main(void) { +${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` +${t?"//Constants\n":""}${this._constantDeclaration} +${this.compilationString}`);let r="";for(let e in this.functions)r+=this.functions[e]+` +`;for(let e in this.compilationString=` +${r} +${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString} +${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString} +${this._injectAtEnd}`),this.compilationString=`${this.compilationString} +}`,this.sharedData.varyingDeclaration&&(this.compilationString=` +${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration} +${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=` +${t?"//Samplers\n":""}${this._samplerDeclaration} +${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=` +${t?"//Uniforms\n":""}${this._uniformDeclaration} +${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=` +${t?"//Attributes\n":""}${this._attributeDeclaration} +${this.compilationString}`),this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString),this.extensions){let t=this.extensions[e];this.compilationString=` +${t} +${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){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2D ${e}; +`,this.samplers.push(e))}_emit2DArraySampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2DArray ${e}; +`,this.samplers.push(e))}_getGLType(e){switch(e){case tm.Float:return"float";case tm.Int:return"int";case tm.Vector2:return"vec2";case tm.Color3:case tm.Vector3:return"vec3";case tm.Color4:case tm.Vector4:return"vec4";case tm.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i} +${t} +#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+` +`+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`;let r=ss.Q.IncludesShadersStore[e]+"\n";if(this.sharedData.emitComments&&(r=t+` +`+r),!i)return r;if(i.replaceStrings)for(let e=0;e<i.replaceStrings.length;e++){let t=i.replaceStrings[e];r=r.replace(t.search,t.replace)}return r}_emitFunctionFromInclude(e,t,i,r=""){let s=e+r;if(!this.functions[s]){if(!i||!i.removeAttributes&&!i.removeUniforms&&!i.removeVaryings&&!i.removeIfDef&&!i.replaceStrings){i&&i.repeatKey?this.functions[s]=`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`:this.functions[s]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""} +`,this.sharedData.emitComments&&(this.functions[s]=t+` +`+this.functions[s]);return}if(this.functions[s]=ss.Q.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+` +`+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;e<i.replaceStrings.length;e++){let t=i.replaceStrings[e];this.functions[s]=this.functions[s].replace(t.search,t.replace)}}}_registerTempVariable(e){return -1===this.sharedData.temps.indexOf(e)&&(this.sharedData.temps.push(e),!0)}_emitVaryingFromString(e,t,i="",r=!1){return -1===this.sharedData.varyings.indexOf(e)&&(this.sharedData.varyings.push(e),i&&(i.startsWith("defined(")?this.sharedData.varyingDeclaration+=`#if ${i} +`:this.sharedData.varyingDeclaration+=`${r?"#ifndef":"#ifdef"} ${i} +`),this.sharedData.varyingDeclaration+=`varying ${t} ${e}; +`,i&&(this.sharedData.varyingDeclaration+=`#endif +`),!0)}_emitUniformFromString(e,t,i="",r=!1){-1===this.uniforms.indexOf(e)&&(this.uniforms.push(e),i&&(i.startsWith("defined(")?this._uniformDeclaration+=`#if ${i} +`:this._uniformDeclaration+=`${r?"#ifndef":"#ifdef"} ${i} +`),this._uniformDeclaration+=`uniform ${t} ${e}; +`,i&&(this._uniformDeclaration+=`#endif +`))}_emitFloat(e){return e.toString()===e.toFixed(0)?`${e}.0`:e.toString()}};let NodeMaterialBuildStateSharedData=class NodeMaterialBuildStateSharedData{constructor(){this.temps=[],this.varyings=[],this.varyingDeclaration="",this.inputBlocks=[],this.textureBlocks=[],this.bindableBlocks=[],this.forcedBindableBlocks=[],this.blocksWithFallbacks=[],this.blocksWithDefines=[],this.repeatableContentBlocks=[],this.dynamicUniformBlocks=[],this.blockingBlocks=[],this.animatedInputs=[],this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:[]},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}emitErrors(){let e="";for(let t of(this.checks.emitVertex||this.allowEmptyVertexProgram||(e+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\n"),this.checks.emitFragment||(e+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\n"),this.checks.notConnectedNonOptionalInputs))e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. +`;if(e)throw"Build of NodeMaterial failed:\n"+e}};var sn=i(5377);(c=tv||(tv={}))[c.Compatible=0]="Compatible",c[c.TypeIncompatible=1]="TypeIncompatible",c[c.TargetIncompatible=2]="TargetIncompatible",c[c.HierarchyIssue=3]="HierarchyIssue",(d=tx||(tx={}))[d.Input=0]="Input",d[d.Output=1]="Output";let NodeMaterialConnectionPoint=class NodeMaterialConnectionPoint{static AreEquivalentTypes(e,t){switch(e){case tm.Vector3:if(t===tm.Color3)return!0;break;case tm.Vector4:if(t===tm.Color4)return!0;break;case tm.Color3:if(t===tm.Vector3)return!0;break;case tm.Color4:if(t===tm.Vector4)return!0}return!1}get direction(){return this._direction}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===tm.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===tm.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get target(){return this._prioritizeVertex&&this._ownerBlock&&this._target===tg.VertexAndFragment?this._ownerBlock.target===tg.Fragment?tg.Fragment:tg.Vertex:this._target}set target(e){this._target=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get isConnectedToInputBlock(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map(e=>e.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tg.Vertex||(e.ownerBlock.target===tg.Neutral||e.ownerBlock.target===tg.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===tg.Vertex)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tg.Vertex||e.target===tg.Vertex||(e.ownerBlock.target===tg.Neutral||e.ownerBlock.target===tg.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===tg.Fragment)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tg.Fragment||(e.ownerBlock.target===tg.Neutral||e.ownerBlock.target===tg.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=[],this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=tm.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new rf.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=tg.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===tv.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(t.target===tg.Fragment){if(i.target===tg.Vertex)return tv.TargetIncompatible;for(let e of i.outputs)if(e.ownerBlock.target!=tg.Neutral&&e.isConnectedInVertexShader)return tv.TargetIncompatible}if(this.type!==e.type&&e.innerType!==tm.AutoDetect)return NodeMaterialConnectionPoint.AreEquivalentTypes(this.type,e.type)?tv.Compatible:e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&NodeMaterialConnectionPoint.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?tv.Compatible:tv.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return tv.TypeIncompatible;let r=i,s=t;return(this.direction===tx.Input&&(r=t,s=i),r.isAnAncestorOf(s))?tv.HierarchyIssue:tv.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){let 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<tm.All;)e&t||this.excludedConnectionPointTypes.push(t),t<<=1}serialize(e=!0){let t={};return t.name=this.name,t.displayName=this.displayName,e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name,t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),(this.isExposedOnFrame||this.exposedPortPosition>=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}};var sa=i(7531);let NodeMaterialBlock=class NodeMaterialBlock{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){(this._target&e)==0&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}constructor(e,t=tg.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=[],this._outputs=[],this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===tg.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=sa.K.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===tg.Neutral}initialize(e){}bind(e,t,i,r){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){let t=e.connectedPoint;return t?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return -1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some(e=>e.isConnectedInFragmentShader)}registerInput(e,t,i=!1,r,s){return(s=null!=s?s:new NodeMaterialConnectionPoint(e,this,tx.Input)).type=t,s.isOptional=i,r&&(s.target=r),this._inputs.push(s),this}registerOutput(e,t,i,r){return(r=null!=r?r:new NodeMaterialConnectionPoint(e,this,tx.Output)).type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(let t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===tm.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(let t of this._outputs)if(!e||!e.target||e.target===tg.Neutral||(e.target&t.target)!=0)return t;return null}getSiblingOutput(e){let t=this._outputs.indexOf(e);return -1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){let s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),r=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,s){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput))&&this.target!==tg.Vertex&&!!((this.target===tg.VertexAndFragment||this.target===tg.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);let s=null!=t._vertexState,n=e._buildTarget===tg.Vertex&&e.target!==tg.VertexAndFragment;if(s&&((e.target&e._buildTarget)==0||(e.target&i.target)==0||this.target!==tg.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){let e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName}; +`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){for(let t of["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"])if(e===t)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(let t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(let i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==tg.Neutral&&((i.target&this.target)==0||(i.target&e.target)==0))continue;let r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log(`${e.target===tg.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case tg.Vertex:e.sharedData.checks.emitVertex=!0;break;case tg.Fragment:e.sharedData.checks.emitFragment=!0}for(let i of(!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=` +//${this.name} +`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target,this._outputs))if((i.target&e.target)!=0)for(let r of i.endpoints){let i=r.ownerBlock;i&&(i.target&e.target)!=0&&-1!==t.indexOf(i)&&this._processBuild(i,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector}; +${e}.visibleOnFrame = ${this.visibleOnFrame}; +${e}.target = ${this.target}; +`}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` +// ${this.getClassName()} +`;for(let i of(this.comments&&(r+=`// ${this.comments} +`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); +`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint,n=s.ownerBlock;-1===t.indexOf(n)&&(r+=n._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); +`}return t}clone(e,t=""){let i=this.serialize(),r=(0,rv.q)(i.customType);if(r){let s=new r;return s._deserialize(i,e,t),s}return null}serialize(){let e={};for(let t of(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=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var r;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(r=e.target)&&void 0!==r?r:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let 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(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose()}};let TransformBlock=class TransformBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.complementW=1,this.complementZ=0,this.target=tg.Vertex,this.registerInput("vector",tm.AutoDetect),this.registerInput("transform",tm.Matrix),this.registerOutput("output",tm.Vector4),this.registerOutput("xyz",tm.Vector3),this._inputs[0].onConnectionObservable.add(e=>{if(e.ownerBlock.isInput){let 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);let t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){let r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),e.sharedData.blocksWithDefines.push(this);let s=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${s} = mat3(${i.associatedVariableName}); +`,e.compilationString+=`#ifdef NONUNIFORMSCALING +`,e.compilationString+=`${s} = transposeMat3(inverseMat3(${s})); +`,e.compilationString+=`#endif +`,t.connectedPoint.type){case tm.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); +`;break;case tm.Vector3:case tm.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); +`}}else{let r=i.associatedVariableName;switch(t.connectedPoint.type){case tm.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); +`;break;case tm.Vector3:case tm.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * ${t.associatedVariableName}; +`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; +`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){let 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(){return super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ}; +`+`${this._codeVariableName}.complementW = ${this.complementW}; +`}};(0,rv.H)("BABYLON.TransformBlock",TransformBlock);let VertexOutputBlock=class VertexOutputBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Vertex,!0),this.registerInput("vector",tm.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e){for(let t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);let t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName}; +`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w; +`,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant; +`),this}};function editableInPropertyPage(e,t=tT.Boolean,i="PROPERTIES",r){return(s,n)=>{let a=s._propStore;a||(a=[],s._propStore=a),a.push({propertyName:n,displayName:e,type:t,groupName:i,options:null!=r?r:{}})}}(0,rv.H)("BABYLON.VertexOutputBlock",VertexOutputBlock),(p=tT||(tT={}))[p.Boolean=0]="Boolean",p[p.Float=1]="Float",p[p.Int=2]="Int",p[p.Vector2=3]="Vector2",p[p.List=4]="List";var so=i(3385);let FragmentOutputBlock=class FragmentOutputBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",tm.Color4,!0),this.registerInput("rgb",tm.AutoDetect,!0),this.registerInput("a",tm.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.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&&so.G.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);let t=this.rgba,i=this.rgb,r=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||r.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");let s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)r.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${r.associatedVariableName}); +`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName}; +`;else if(i.connectedPoint){let t="1.0";r.connectedPoint&&(t=r.associatedVariableName),i.connectedPoint.type===tm.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t}); +`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t}); +`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`gl_FragColor = toLinearSpace(gl_FragColor); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`gl_FragColor = toGammaSpace(gl_FragColor); +`,e.compilationString+=`#endif +`,this.useLogarithmicDepth&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5; +`),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`gl_FragData[0] = gl_FragColor;\r +`,e.compilationString+=`#endif\r +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth}; +`}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(r=e.useLogarithmicDepth)&&void 0!==r&&r}};(0,rH.gn)([editableInPropertyPage("Convert to gamma space",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],FragmentOutputBlock.prototype,"convertToGammaSpace",void 0),(0,rH.gn)([editableInPropertyPage("Convert to linear space",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],FragmentOutputBlock.prototype,"convertToLinearSpace",void 0),(0,rH.gn)([editableInPropertyPage("Use logarithmic depth",tT.Boolean,"PROPERTIES")],FragmentOutputBlock.prototype,"useLogarithmicDepth",void 0),(0,rv.H)("BABYLON.FragmentOutputBlock",FragmentOutputBlock),(_=tS||(tS={}))[_.Uniform=0]="Uniform",_[_.Attribute=1]="Attribute",_[_.Varying=2]="Varying",_[_.Undefined=3]="Undefined",(f=tC||(tC={}))[f.World=1]="World",f[f.View=2]="View",f[f.Projection=3]="Projection",f[f.ViewProjection=4]="ViewProjection",f[f.WorldView=5]="WorldView",f[f.WorldViewProjection=6]="WorldViewProjection",f[f.CameraPosition=7]="CameraPosition",f[f.FogColor=8]="FogColor",f[f.DeltaTime=9]="DeltaTime",f[f.CameraParameters=10]="CameraParameters",f[f.MaterialAlpha=11]="MaterialAlpha";var sl=i(2975),sh=i(6329);(m=tE||(tE={}))[m.None=0]="None",m[m.Time=1]="Time",m[m.RealTime=2]="RealTime";let su={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},sc={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},sd={particle_texturemask:!0};let InputBlock=class InputBlock extends NodeMaterialBlock{get type(){if(this._type===tm.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=tm.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=tm.Vector2,this._type;case"Vector3":return this._type=tm.Vector3,this._type;case"Vector4":return this._type=tm.Vector4,this._type;case"Color3":return this._type=tm.Color3,this._type;case"Color4":return this._type=tm.Color4,this._type;case"Matrix":return this._type=tm.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=tm.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=tm.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=tm.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=tm.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case tC.World:case tC.WorldView:case tC.WorldViewProjection:case tC.View:case tC.ViewProjection:case tC.Projection:this._type=tm.Matrix;break;case tC.CameraPosition:this._type=tm.Vector3;break;case tC.FogColor:this._type=tm.Color3;break;case tC.DeltaTime:case tC.MaterialAlpha:this._type=tm.Float;break;case tC.CameraParameters:this._type=tm.Vector4}}return this._type}constructor(e,t=tg.Vertex,i=tm.AutoDetect){super(e,t,!1),this._mode=tS.Undefined,this._animationType=tE.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new rf.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=tS.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===tm.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=tS.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=tS.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===tS.Undefined}get isUniform(){return this._mode===tS.Uniform}set isUniform(e){this._mode=e?tS.Uniform:tS.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===tS.Attribute}set isAttribute(e){this._mode=e?tS.Attribute:tS.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===tS.Varying}set isVarying(e){this._mode=e?tS.Varying:tS.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=tS.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case tE.Time:this.type===tm.Float&&(this.value+=.01*e.getAnimationRatio());break;case tE.RealTime:this.type===tm.Float&&(this.value=(rF.F.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)} +`:`#ifdef ${e} +`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case tm.Float:this.value=0;break;case tm.Vector2:this.value=rm.FM.Zero();break;case tm.Vector3:this.value=rm.P.Zero();break;case tm.Vector4:this.value=rm.Lt.Zero();break;case tm.Color3:this.value=rg.Wo.White();break;case tm.Color4:this.value=new rg.HE(1,1,1,1);break;case tm.Matrix:this.value=rm.y3.Identity()}}_emitConstant(e){switch(this.type){case tm.Float:return`${e._emitFloat(this.value)}`;case tm.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case tm.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case tm.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case tm.Color3:return rg.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&rg.zZ.Color3[0].toGammaSpaceToRef(rg.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rg.zZ.Color3[0].toLinearSpaceToRef(rg.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${rg.zZ.Color3[0].r}, ${rg.zZ.Color3[0].g}, ${rg.zZ.Color3[0].b})`;case tm.Color4:return rg.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&rg.zZ.Color4[0].toGammaSpaceToRef(rg.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rg.zZ.Color4[0].toLinearSpaceToRef(rg.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${rg.zZ.Color4[0].r}, ${rg.zZ.Color4[0].g}, ${rg.zZ.Color4[0].b}, ${rg.zZ.Color4[0].a})`}return""}get _noContextSwitch(){return sc[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;e.constants.push(this.associatedVariableName),e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)}; +`;return}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}; +`,t&&(e._uniformDeclaration+=`#endif +`);let i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case tC.WorldView:i.needWorldViewMatrix=!0;break;case tC.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==tE.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=null!==(i=su[this.name])&&void 0!==i?i:this.name,this.target===tg.Vertex&&e._vertexState){sc[this.name]?sd[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);return}if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),sc[this.name]?sd[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}; +`,t&&(e._attributeDeclaration+=`#endif +`))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;let s=this.associatedVariableName;switch(this._systemValue){case tC.World:e.setMatrix(s,t);break;case tC.WorldView:e.setMatrix(s,i);break;case tC.WorldViewProjection:e.setMatrix(s,r)}}_transmit(e,t,i){if(this.isAttribute)return;let r=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case tC.World:case tC.WorldView:case tC.WorldViewProjection:break;case tC.View:e.setMatrix(r,t.getViewMatrix());break;case tC.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case tC.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case tC.CameraPosition:t.bindEyePosition(e,r,!0);break;case tC.FogColor:e.setColor3(r,t.fogColor);break;case tC.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case tC.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case tC.MaterialAlpha:e.setFloat(r,i.alpha)}return}let s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case tm.Float:e.setFloat(r,s);break;case tm.Int:e.setInt(r,s);break;case tm.Color3:rg.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&rg.zZ.Color3[0].toGammaSpaceToRef(rg.zZ.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rg.zZ.Color3[0].toLinearSpaceToRef(rg.zZ.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,rg.zZ.Color3[0]);break;case tm.Color4:rg.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&rg.zZ.Color4[0].toGammaSpaceToRef(rg.zZ.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rg.zZ.Color4[0].toLinearSpaceToRef(rg.zZ.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,rg.zZ.Color4[0]);break;case tm.Vector2:e.setVector2(r,s);break;case tm.Vector3:e.setVector3(r,s);break;case tm.Vector4:e.setVector4(r,s);break;case tm.Matrix:e.setMatrix(r,s)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}"); +`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${tC[this._systemValue]}); +`;if(this.isUniform){let t=[],i="";switch(this.type){case tm.Float:i=`${this.value}`;break;case tm.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case tm.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case tm.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case tm.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case tm.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 tm.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===tm.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${tE[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){let 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===tS.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===tS.Attribute&&e.type===tm.Vector3&&(this._type=tm.Vector4),e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=(0,rv.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}};(0,rv.H)("BABYLON.InputBlock",InputBlock);let CurrentScreenBlock=class CurrentScreenBlock extends NodeMaterialBlock{constructor(e){super(e,tg.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",tm.AutoDetect,!1,tg.VertexAndFragment),this.registerOutput("rgba",tm.Color4,tg.Neutral),this.registerOutput("rgb",tm.Color3,tg.Neutral),this.registerOutput("r",tm.Float,tg.Neutral),this.registerOutput("g",tm.Float,tg.Neutral),this.registerOutput("b",tm.Float,tg.Neutral),this.registerOutput("a",tm.Float,tg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector2|tm.Vector3|tm.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?tg.VertexAndFragment:tg.Fragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput){let i=t.connectedPoint.ownerBlock;i.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tg.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); +`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tg.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.blockingBlocks.indexOf(this)&&e.sharedData.blockingBlocks.push(this),0>e.sharedData.textureBlocks.indexOf(this)&&e.sharedData.textureBlocks.push(this),0>e.sharedData.blocksWithDefines.indexOf(this)&&e.sharedData.blocksWithDefines.push(this),e.target!==tg.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e),this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let 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=texture_Texture.Parse(e.texture,t,i))}};(0,rv.H)("BABYLON.CurrentScreenBlock",CurrentScreenBlock);let ParticleTextureBlock=class ParticleTextureBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",tm.AutoDetect,!1,tg.VertexAndFragment),this.registerOutput("rgba",tm.Color4,tg.Neutral),this.registerOutput("rgb",tm.Color3,tg.Neutral),this.registerOutput("r",tm.Float,tg.Neutral),this.registerOutput("g",tm.Float,tg.Neutral),this.registerOutput("b",tm.Float,tg.Neutral),this.registerOutput("a",tm.Float,tg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector2|tm.Vector3|tm.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"particle_uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute("particle_uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`}_buildBlock(e){if(super._buildBlock(e),e.target===tg.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");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName}); +`,this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let 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=texture_Texture.Parse(e.texture,t,i))}};(0,rv.H)("BABYLON.ParticleTextureBlock",ParticleTextureBlock);let ParticleRampGradientBlock=class ParticleRampGradientBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._isUnique=!0,this.registerInput("color",tm.Color4,!1,tg.Fragment),this.registerOutput("rampColor",tm.Color4,tg.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!==tg.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=` + #ifdef RAMPGRADIENT + vec4 baseColor = ${this.color.associatedVariableName}; + float alpha = ${this.color.associatedVariableName}.a; + + float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); + + vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.)); + baseColor.rgb *= rampColor.rgb; + + // Remapped alpha + float finalAlpha = baseColor.a; + baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0); + + ${this._declareOutput(this.rampColor,e)} = baseColor; + #else + ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName}; + #endif + `,this}};(0,rv.H)("BABYLON.ParticleRampGradientBlock",ParticleRampGradientBlock);let ParticleBlendMultiplyBlock=class ParticleBlendMultiplyBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._isUnique=!0,this.registerInput("color",tm.Color4,!1,tg.Fragment),this.registerInput("alphaTexture",tm.Float,!1,tg.Fragment),this.registerInput("alphaColor",tm.Float,!1,tg.Fragment),this.registerOutput("blendColor",tm.Color4,tg.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!==tg.Vertex)return e.compilationString+=` + #ifdef BLENDMULTIPLYMODE + ${this._declareOutput(this.blendColor,e)}; + float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; + ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha); + ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a; + #else + ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName}; + #endif + `,this}};(0,rv.H)("BABYLON.ParticleBlendMultiplyBlock",ParticleBlendMultiplyBlock);let EffectFallbacks=class EffectFallbacks{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=[]),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;let i=this._mesh.getScene();for(let e=0;e<i.meshes.length;e++){let r=i.meshes[e];if(!r.material){!this._mesh.material&&r.computeBonesUsingShaders&&r.numBoneInfluencers>0&&(r.computeBonesUsingShaders=!1);continue}if(r.computeBonesUsingShaders&&0!==r.numBoneInfluencers){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes)for(let e of r.subMeshes){let i=e.effect;if(i===t){r.computeBonesUsingShaders=!1;break}}}}}else{let t=this._defines[this._currentRank];if(t)for(let i=0;i<t.length;i++)e=e.replace("#define "+t[i],"");this._currentRank++}return e}};var sp=i(8355),s_=i(513);let sf=`attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.postprocessVertexShader=sf;let renderTargetWrapper_RenderTargetWrapper=class renderTargetWrapper_RenderTargetWrapper{get depthStencilTexture(){return this._depthStencilTexture}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get 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;let r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r,s){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,n){var a;return null===(a=this._depthStencilTexture)||void 0===a||a.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:n},this),this._depthStencilTexture}_shareDepth(e){this._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,r,s,n,a,o;let l=null;if(this._isMulti){let i=this.textures;if(i&&i.length>0){let r=!1,s=i.length,n=i[i.length-1]._source;(n===r5.S.Depth||n===r5.S.DepthStencil)&&(r=!0,s--);let a=[],o=[],h=[],u=[],c=[],d=[],p=[],_={};for(let r=0;r<s;++r){let s=i[r];a.push(s.samplingMode),o.push(s.type),h.push(s.format);let n=_[s.uniqueId];void 0!==n?(u.push(-1),p.push(0)):(_[s.uniqueId]=r,s.is2DArray?(u.push(35866),p.push(s.depth)):s.isCube?(u.push(34067),p.push(0)):s.is3D?(u.push(32879),p.push(s.depth)):(u.push(3553),p.push(0))),this._faceIndices&&c.push(null!==(e=this._faceIndices[r])&&void 0!==e?e:0),this._layerIndices&&d.push(null!==(t=this._layerIndices[r])&&void 0!==t?t:0)}let f={samplingModes:a,generateMipMaps:i[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:r,types:o,formats:h,textureCount:s,targetTypes:u,faceIndex:c,layerIndex:d,layerCounts:p},m={width:this.width,height:this.height};l=this._engine.createMultipleRenderTarget(m,f);for(let e=0;e<s;++e){if(-1!==u[e])continue;let t=_[i[e].uniqueId];l.setTexture(l.textures[t],e)}}}else{let e={};if(e.generateDepthBuffer=this._generateDepthBuffer,e.generateMipMaps=null!==(r=null===(i=this.texture)||void 0===i?void 0:i.generateMipMaps)&&void 0!==r&&r,e.generateStencilBuffer=this._generateStencilBuffer,e.samplingMode=null===(s=this.texture)||void 0===s?void 0:s.samplingMode,e.type=null===(n=this.texture)||void 0===n?void 0:n.type,e.format=null===(a=this.texture)||void 0===a?void 0:a.format,this.isCube)l=this._engine.createRenderTargetCubeTexture(this.width,e);else{let t={width:this.width,height:this.height,layers:this.is2DArray?null===(o=this.texture)||void 0===o?void 0:o.depth:void 0};l=this._engine.createRenderTargetTexture(t,e)}l.texture.isReady=!0}return l}_swapRenderTargetWrapper(e){if(this._textures&&e._textures)for(let t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null}_rebuild(){let e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){let t=this._depthStencilTexture.samplingMode;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,2===t||3===t||11===t,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let t=0;t<(null===(e=this._textures)||void 0===e?void 0:e.length);++t)this._textures[t].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)}};let WebGLRenderTargetWrapper=class WebGLRenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{constructor(e,t,i,r,s){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height)).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);let t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;let s=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;this._engine._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,s,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var s,n,a,o;if(!e._hardwareTexture)return;let l=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(l),this._engine.webGLVersion>1){let l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(n=null!=i?i:null===(s=this.layerIndices)||void 0===s?void 0:s[t])&&void 0!==n?n:0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=null!==(o=null!=i?i:null===(a=this.faceIndices)||void 0===a?void 0:a[t])&&void 0!==o?o:0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{let s=this._context,n=s["COLOR_ATTACHMENT"+t+"_WEBGL"],a=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,n,a,e._hardwareTexture.underlyingResource,r)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,r;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;let s=null!==(r=null===(i=this._attachments)||void 0===i?void 0:i.length)&&void 0!==r?r:this.textures.length;for(let e=0;e<s;e++){let t=this.textures[e];t&&(t.is2DArray||t.is3D?this._bindTextureRenderTarget(t,e,this.layerIndices[e]):t.isCube?this._bindTextureRenderTarget(t,e,this.faceIndices[e]):this._bindTextureRenderTarget(t,e))}}setLayerAndFaceIndex(e=0,t,i){if(super.setLayerAndFaceIndex(e,t,i),!this.textures||!this.layerIndices||!this.faceIndices)return;let r=this.textures[e];r.is2DArray||r.is3D?this._bindTextureRenderTarget(this.textures[e],e,this.layerIndices[e]):r.isCube&&this._bindTextureRenderTarget(this.textures[e],e,this.faceIndices[e])}dispose(e=this._disposeOnlyFramebuffers){let t=this._context;!e&&(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(t.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(t.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(t.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),super.dispose(e)}};r6.B.prototype._createHardwareRenderTargetWrapper=function(e,t,i){let r=new WebGLRenderTargetWrapper(e,t,i,this,this._gl);return this._renderTargetWrapperCache.push(r),r},r6.B.prototype.createRenderTargetTexture=function(e,t){var i,r;let s;let n=this._createHardwareRenderTargetWrapper(!1,!1,e),a=!0,o=!1,l=!1,h=1;void 0!==t&&"object"==typeof t&&(a=null===(i=t.generateDepthBuffer)||void 0===i||i,o=!!t.generateStencilBuffer,l=!!t.noColorAttachment,s=t.colorAttachment,h=null!==(r=t.samples)&&void 0!==r?r:1);let u=s||(l?null:this._createInternalTexture(e,t,!0,r5.S.RenderTarget)),c=e.width||e,d=e.height||e,p=this._currentFramebuffer,_=this._gl,f=_.createFramebuffer();return this._bindUnboundFramebuffer(f),n._depthStencilBuffer=this._setupFramebufferDepthAttachments(o,a,c,d),u&&!u.is2DArray&&_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,u._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(p),n._framebuffer=f,n._generateDepthBuffer=a,n._generateStencilBuffer=o,n.setTextures(u),this.updateRenderTargetTextureSampleCount(n,h),n},r6.B.prototype.createDepthStencilTexture=function(e,t,i){if(!t.isCube)return this._createDepthStencilTexture(e,t,i);{let r=e.width||e;return this._createDepthStencilCubeTexture(r,t,i)}},r6.B.prototype._createDepthStencilTexture=function(e,t,i){let r=this._gl,s=e.layers||0,n=0!==s?r.TEXTURE_2D_ARRAY:r.TEXTURE_2D,a=new r5.l(this,r5.S.DepthStencil);if(!this._caps.depthTextureExtension)return rT.Y.Error("Depth texture is not supported by your browser or hardware."),a;let o=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t);if(this._bindTextureDirectly(n,a,!0),this._setupDepthStencilTexture(a,e,o.generateStencil,0!==o.comparisonFunction&&o.bilinearFiltering,o.comparisonFunction,o.samples),void 0!==o.depthTextureFormat){if(15!==o.depthTextureFormat&&16!==o.depthTextureFormat&&17!==o.depthTextureFormat&&13!==o.depthTextureFormat&&14!==o.depthTextureFormat&&18!==o.depthTextureFormat)return rT.Y.Error("Depth texture format is not supported."),a;a.format=o.depthTextureFormat}else a.format=o.generateStencil?13:16;let l=17===a.format||13===a.format||18===a.format;i._depthStencilTexture=a,i._depthStencilTextureWithStencil=l;let h=r.UNSIGNED_INT;15===a.format?h=r.UNSIGNED_SHORT:17===a.format||13===a.format?h=r.UNSIGNED_INT_24_8:14===a.format?h=r.FLOAT:18===a.format&&(h=r.FLOAT_32_UNSIGNED_INT_24_8_REV);let u=l?r.DEPTH_STENCIL:r.DEPTH_COMPONENT,c=u;if(this.webGLVersion>1&&(15===a.format?c=r.DEPTH_COMPONENT16:16===a.format?c=r.DEPTH_COMPONENT24:17===a.format||13===a.format?c=r.DEPTH24_STENCIL8:14===a.format?c=r.DEPTH_COMPONENT32F:18===a.format&&(c=r.DEPTH32F_STENCIL8)),a.is2DArray?r.texImage3D(n,0,c,a.width,a.height,s,0,u,h,null):r.texImage2D(n,0,c,a.width,a.height,0,u,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(a),i._depthStencilBuffer){let e=this._currentFramebuffer;this._bindUnboundFramebuffer(i._framebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),r.deleteRenderbuffer(i._depthStencilBuffer),i._depthStencilBuffer=null}return a},r6.B.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let 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);let r=e.texture._hardwareTexture;if(r.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){let s=i.createFramebuffer();if(!s)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);let n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBAMultiSampleBufferFormat(e.texture.type),i.COLOR_ATTACHMENT0,!1);if(!n)throw Error("Unable to create multi sampled framebuffer");r.addMSAARenderBuffer(n)}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 sm=i(1606),sg=i(5550);let postProcess_PostProcess=class postProcess_PostProcess{static RegisterShaderCodeProcessing(e,t){if(!t){delete postProcess_PostProcess._CustomShaderCodeProcessing[null!=e?e:""];return}postProcess_PostProcess._CustomShaderCodeProcessing[null!=e?e:""]=t}static _GetShaderCodeProcessing(e){var t;return null!==(t=postProcess_PostProcess._CustomShaderCodeProcessing[e])&&void 0!==t?t:postProcess_PostProcess._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,r,s,n,a=1,o,l,h=null,u=0,c="postprocess",d,p=!1,_=5,f=sg.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=[],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 sp.t(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new rm.FM(1,1),this._texelSize=rm.FM.Zero(),this.onActivateObservable=new rf.y$,this.onSizeChangedObservable=new rf.y$,this.onApplyObservable=new rf.y$,this.onBeforeRenderObservable=new rf.y$,this.onAfterRenderObservable=new rf.y$,this.name=e,null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):o&&(this._engine=o,this._engine.postProcesses.push(this)),this._options=s,this.renderTargetSamplingMode=a||1,this._reusable=l||!1,this._textureType=u,this._textureFormat=_,this._shaderLanguage=f,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=c,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=d,this._drawWrapper=new sm.q(this._engine),p||this.updateEffect(h)}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 sp.t(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,n,a,o){var l,h;let u=postProcess_PostProcess._GetShaderCodeProcessing(this.name);if(null==u?void 0:u.defineCustomBindings){let r=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];r.push(...this._parameters);let s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=u.defineCustomBindings(this.name,e,r,s),t=r,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=a?a:this._vertexUrl,fragment:null!=o?o: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!=n?n:null,indexParameters:r||this._indexParameters,processCodeAfterIncludes:(null==u?void 0:u.processCodeAfterIncludes)?(e,t)=>u.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:(null==u?void 0:u.processFinalCode)?(e,t)=>u.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 r=0;r<this._textureCache.length;r++)if(this._textureCache[r].texture.width===e.width&&this._textureCache[r].texture.height===e.height&&this._textureCache[r].postProcessChannel===i&&this._textureCache[r].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[r].texture.samples===t.samples)return this._textureCache[r].texture;let r=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:r,postProcessChannel:i,lastUsedRenderId:-1}),r}_flushTextureCache(){let e=this._renderId;for(let t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i<this._textures.length;i++)if(this._textures.data[i]===this._textureCache[t].texture){e=!0;break}e||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}_resize(e,t,i,r,s){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let n=null;for(let e=0;e<i._postProcesses.length;e++)if(null!==i._postProcesses[e]){n=i._postProcesses[e];break}let a={width:this.width,height:this.height},o={generateMipMaps:r,generateDepthBuffer:s||n===this,generateStencilBuffer:(s||n===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(a,o,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(a,o,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}activate(e,t=null,i){var r,s;let n;e=e||this._camera;let a=e.getScene(),o=a.getEngine(),l=o.getCaps().maxTextureSize,h=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,u=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0,c=this._options.width||h,d=this._options.height||u,p=7!==this.renderTargetSamplingMode&&1!==this.renderTargetSamplingMode&&2!==this.renderTargetSamplingMode;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){let e=o.currentViewport;e&&(c*=e.width,d*=e.height)}(p||this.alwaysForcePOT)&&(this._options.width||(c=o.needPOTTextures?rq.D.GetExponentOfTwo(c,l,this.scaleMode):c),this._options.height||(d=o.needPOTTextures?rq.D.GetExponentOfTwo(d,l,this.scaleMode):d)),(this.width!==c||this.height!==d)&&this._resize(c,d,e,p,i),this._textures.forEach(e=>{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)}),this._flushTextureCache(),this._renderId++}if(this._shareOutputWithPostProcess)n=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)n=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let e;n=this.inputTexture;for(let t=0;t<this._textureCache.length;t++)if(this._textureCache[t].texture===n){e=this._textureCache[t];break}e&&(e.lastUsedRenderId=this._renderId)}return this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(h/c,u/d),this._engine.bindFramebuffer(n,0,h,u,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(n,0,void 0,void 0,this.forceFullscreenViewport)),null===(s=(r=this._engine)._debugInsertMarker)||void 0===s||s.call(r,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:a.clearColor,a._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),n}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){var e,t;return null!==(t=null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}apply(){var e,t,i;let r;return(null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())?(this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),r=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",null==r?void 0:r.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),null===(i=null===(t=postProcess_PostProcess._GetShaderCodeProcessing(this.name))||void 0===t?void 0:t.bindCustomBindings)||void 0===i||i.call(t,this.name,this._drawWrapper.effect),this._drawWrapper.effect):null}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&-1!==(t=this._scene.postProcesses.indexOf(this))&&this._scene.postProcesses.splice(t,1),this._parentContainer){let e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(-1!==(t=this._engine.postProcesses.indexOf(this))&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),0===(t=e._postProcesses.indexOf(this))&&e._postProcesses.length>0){let e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){let e=rb.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(){let e=this.serialize();e._engine=this._engine,e.cameraId=null;let t=postProcess_PostProcess.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){let r=(0,rv.q)(e.customType);if(!r||!r._Parse)return null;let s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new postProcess_PostProcess(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,r)}};postProcess_PostProcess._CustomShaderCodeProcessing={},(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"uniqueId",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"name",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"width",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"height",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"renderTargetSamplingMode",void 0),(0,rH.gn)([(0,rb.XX)()],postProcess_PostProcess.prototype,"clearColor",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"autoClear",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"forceAutoClearInAlphaMode",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"alphaMode",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"alphaConstants",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"enablePixelPerfectMode",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"forceFullscreenViewport",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"scaleMode",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"alwaysForcePOT",void 0),(0,rH.gn)([(0,rb.qC)("samples")],postProcess_PostProcess.prototype,"_samples",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"adaptScaleToCurrentViewport",void 0),(0,rv.H)("BABYLON.PostProcess",postProcess_PostProcess);let VectorMergerBlock=class VectorMergerBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",tm.Vector4,!0),this.registerInput("xyz ",tm.Vector3,!0),this.registerInput("xy ",tm.Vector2,!0),this.registerInput("zw ",tm.Vector2,!0),this.registerInput("x",tm.Float,!0),this.registerInput("y",tm.Float,!0),this.registerInput("z",tm.Float,!0),this.registerInput("w",tm.Float,!0),this.registerOutput("xyzw",tm.Vector4),this.registerOutput("xyz",tm.Vector3),this.registerOutput("xy",tm.Vector2),this.registerOutput("zw",tm.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){let t=this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle;return"."+t.substr(0,e)}_buildBlock(e){super._buildBlock(e);let t=this.x,i=this.y,r=this.z,s=this.w,n=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],u=this._outputs[1],c=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; +`)):o.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${o.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; +`)):(n.isConnected?(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${a.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)}; +`)):(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${a.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)}; +`)),d.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)}; +`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)}; +`)),this}serialize(){let 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 r,s,n,a;super._deserialize(e,t,i),this.xSwizzle=null!==(r=e.xSwizzle)&&void 0!==r?r:"x",this.ySwizzle=null!==(s=e.ySwizzle)&&void 0!==s?s:"y",this.zSwizzle=null!==(n=e.zSwizzle)&&void 0!==n?n:"z",this.wSwizzle=null!==(a=e.wSwizzle)&&void 0!==a?a:"w"}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}"; +${this._codeVariableName}.ySwizzle = "${this.ySwizzle}"; +${this._codeVariableName}.zSwizzle = "${this.zSwizzle}"; +${this._codeVariableName}.wSwizzle = "${this.wSwizzle}"; +`}};(0,rv.H)("BABYLON.VectorMergerBlock",VectorMergerBlock);let RemapBlock=class RemapBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.sourceRange=new rm.FM(-1,1),this.targetRange=new rm.FM(0,1),this.registerInput("input",tm.AutoDetect),this.registerInput("sourceMin",tm.Float,!0),this.registerInput("sourceMax",tm.Float,!0),this.registerInput("targetMin",tm.Float,!0),this.registerInput("targetMax",tm.Float,!0),this.registerOutput("output",tm.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);let t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${s}) / (${r} - ${i}); +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y}); +`+`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y}); +`}serialize(){let 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=rm.FM.FromArray(e.sourceRange),this.targetRange=rm.FM.FromArray(e.targetRange)}};(0,rH.gn)([editableInPropertyPage("From",tT.Vector2)],RemapBlock.prototype,"sourceRange",void 0),(0,rH.gn)([editableInPropertyPage("To",tT.Vector2)],RemapBlock.prototype,"targetRange",void 0),(0,rv.H)("BABYLON.RemapBlock",RemapBlock);let MultiplyBlock=class MultiplyBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(tm.Float),this._inputs[1].acceptedConnectionPointTypes.push(tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName}; +`,this}};(0,rv.H)("BABYLON.MultiplyBlock",MultiplyBlock),(g=tb||(tb={}))[g.Material=0]="Material",g[g.PostProcess=1]="PostProcess",g[g.Particle=2]="Particle",g[g.ProceduralTexture=3]="ProceduralTexture";var sv=i(1974);let BoxParticleEmitter=class BoxParticleEmitter{constructor(){this.direction1=new rm.P(0,1,0),this.direction2=new rm.P(0,1,0),this.minEmitBox=new rm.P(-.5,-.5,-.5),this.maxEmitBox=new rm.P(.5,.5,.5)}startDirectionFunction(e,t,i,r){let s=rE.R.RandomRange(this.direction1.x,this.direction2.x),n=rE.R.RandomRange(this.direction1.y,this.direction2.y),a=rE.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.x=s,t.y=n,t.z=a;return}rm.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){let s=rE.R.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),n=rE.R.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=rE.R.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(r){t.x=s,t.y=n,t.z=a;return}rm.P.TransformCoordinatesFromFloatsToRef(s,n,a,e,t)}clone(){let e=new BoxParticleEmitter;return rC.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(){let 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){rm.P.FromArrayToRef(e.direction1,0,this.direction1),rm.P.FromArrayToRef(e.direction2,0,this.direction2),rm.P.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),rm.P.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}};let ConeParticleEmitter=class ConeParticleEmitter{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?rm.jp.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),rm.jp.Vector3[0]).normalize();let s=rE.R.RandomRange(0,this.directionRandomizer),n=rE.R.RandomRange(0,this.directionRandomizer),a=rE.R.RandomRange(0,this.directionRandomizer);t.x=rm.jp.Vector3[0].x+s,t.y=rm.jp.Vector3[0].y+n,t.z=rm.jp.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,r){let s;let n=rE.R.RandomRange(0,2*Math.PI);s=this.emitFromSpawnPointOnly?1e-4:1-(s=rE.R.RandomRange(0,this.heightRange))*s;let a=this._radius-rE.R.RandomRange(0,this._radius*this.radiusRange);a*=s;let o=a*Math.sin(n),l=a*Math.cos(n),h=s*this._height;if(r){t.x=o,t.y=h,t.z=l;return}rm.P.TransformCoordinatesFromFloatsToRef(o,h,l,e,t)}clone(){let e=new ConeParticleEmitter(this._radius,this._angle,this.directionRandomizer);return rC.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(){let 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}};let CylinderParticleEmitter=class CylinderParticleEmitter{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=rm.P.Zero()}startDirectionFunction(e,t,i,r,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),rm.P.TransformNormalToRef(this._tempVector,s,this._tempVector);let n=rE.R.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),a=Math.atan2(this._tempVector.x,this._tempVector.z);if(a+=rE.R.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),r){t.copyFrom(this._tempVector);return}rm.P.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){let s=rE.R.RandomRange(-this.height/2,this.height/2),n=rE.R.RandomRange(0,2*Math.PI),a=rE.R.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),o=Math.sqrt(a)*this.radius,l=o*Math.cos(n),h=o*Math.sin(n);if(r){t.copyFromFloats(l,s,h);return}rm.P.TransformCoordinatesFromFloatsToRef(l,s,h,e,t)}clone(){let e=new CylinderParticleEmitter(this.radius,this.directionRandomizer);return rC.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(){let 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}};let CylinderDirectedParticleEmitter=class CylinderDirectedParticleEmitter extends CylinderParticleEmitter{constructor(e=1,t=1,i=1,r=new rm.P(0,1,0),s=new rm.P(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=s}startDirectionFunction(e,t){let i=rE.R.RandomRange(this.direction1.x,this.direction2.x),r=rE.R.RandomRange(this.direction1.y,this.direction2.y),s=rE.R.RandomRange(this.direction1.z,this.direction2.z);rm.P.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new CylinderDirectedParticleEmitter(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return rC.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(){let 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)}};let HemisphericParticleEmitter=class HemisphericParticleEmitter{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),n=rE.R.RandomRange(0,this.directionRandomizer),a=rE.R.RandomRange(0,this.directionRandomizer),o=rE.R.RandomRange(0,this.directionRandomizer);if(s.x+=n,s.y+=a,s.z+=o,s.normalize(),r){t.copyFrom(s);return}rm.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-rE.R.RandomRange(0,this.radius*this.radiusRange),n=rE.R.RandomRange(0,1),a=rE.R.RandomRange(0,2*Math.PI),o=Math.acos(2*n-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),u=s*Math.sin(a)*Math.sin(o);if(r){t.copyFromFloats(l,Math.abs(h),u);return}rm.P.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),u,e,t)}clone(){let e=new HemisphericParticleEmitter(this.radius,this.directionRandomizer);return rC.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(){let 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}};let PointParticleEmitter=class PointParticleEmitter{constructor(){this.direction1=new rm.P(0,1,0),this.direction2=new rm.P(0,1,0)}startDirectionFunction(e,t,i,r){let s=rE.R.RandomRange(this.direction1.x,this.direction2.x),n=rE.R.RandomRange(this.direction1.y,this.direction2.y),a=rE.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,n,a);return}rm.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){if(r){t.copyFromFloats(0,0,0);return}rm.P.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){let e=new PointParticleEmitter;return rC.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(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){rm.P.FromArrayToRef(e.direction1,0,this.direction1),rm.P.FromArrayToRef(e.direction2,0,this.direction2)}};let SphereParticleEmitter=class SphereParticleEmitter{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),n=rE.R.RandomRange(0,this.directionRandomizer),a=rE.R.RandomRange(0,this.directionRandomizer),o=rE.R.RandomRange(0,this.directionRandomizer);if(s.x+=n,s.y+=a,s.z+=o,s.normalize(),r){t.copyFrom(s);return}rm.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-rE.R.RandomRange(0,this.radius*this.radiusRange),n=rE.R.RandomRange(0,1),a=rE.R.RandomRange(0,2*Math.PI),o=Math.acos(2*n-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),u=s*Math.sin(a)*Math.sin(o);if(r){t.copyFromFloats(l,h,u);return}rm.P.TransformCoordinatesFromFloatsToRef(l,h,u,e,t)}clone(){let e=new SphereParticleEmitter(this.radius,this.directionRandomizer);return rC.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(){let 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}};let SphereDirectedParticleEmitter=class SphereDirectedParticleEmitter extends SphereParticleEmitter{constructor(e=1,t=new rm.P(0,1,0),i=new rm.P(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){let i=rE.R.RandomRange(this.direction1.x,this.direction2.x),r=rE.R.RandomRange(this.direction1.y,this.direction2.y),s=rE.R.RandomRange(this.direction1.z,this.direction2.z);rm.P.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new SphereDirectedParticleEmitter(this.radius,this.direction1,this.direction2);return rC.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(){let 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)}};let CustomParticleEmitter=class CustomParticleEmitter{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){let s=rm.jp.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);let e=rm.jp.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);if(r){t.copyFrom(s);return}rm.P.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,r){let s=rm.jp.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),r){t.copyFrom(s);return}rm.P.TransformCoordinatesToRef(s,e,t)}clone(){let e=new CustomParticleEmitter;return rC.j.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e}parse(e){}};let MeshParticleEmitter=class MeshParticleEmitter{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(rz.o.PositionKind),this._normals=e.getVerticesData(rz.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=rm.P.Zero(),this._mesh=null,this.direction1=new rm.P(0,1,0),this.direction2=new rm.P(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals){rm.P.TransformNormalToRef(this._storedNormal,e,t);return}let s=rE.R.RandomRange(this.direction1.x,this.direction2.x),n=rE.R.RandomRange(this.direction1.y,this.direction2.y),a=rE.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,n,a);return}rm.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;let s=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),a=Math.random()*(1-n),o=1-n-a,l=this._indices[s],h=this._indices[s+1],u=this._indices[s+2],c=rm.jp.Vector3[0],d=rm.jp.Vector3[1],p=rm.jp.Vector3[2],_=rm.jp.Vector3[3];rm.P.FromArrayToRef(this._positions,3*l,c),rm.P.FromArrayToRef(this._positions,3*h,d),rm.P.FromArrayToRef(this._positions,3*u,p),_.x=n*c.x+a*d.x+o*p.x,_.y=n*c.y+a*d.y+o*p.y,_.z=n*c.z+a*d.z+o*p.z,r?t.copyFromFloats(_.x,_.y,_.z):rm.P.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(rm.P.FromArrayToRef(this._normals,3*l,c),rm.P.FromArrayToRef(this._normals,3*h,d),rm.P.FromArrayToRef(this._normals,3*u,p),this._storedNormal.x=n*c.x+a*d.x+o*p.x,this._storedNormal.y=n*c.y+a*d.y+o*p.y,this._storedNormal.z=n*c.z+a*d.z+o*p.z)}clone(){let e=new MeshParticleEmitter(this.mesh);return rC.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;let 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){rm.P.FromArrayToRef(e.direction1,0,this.direction1),rm.P.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}};i(6529);let BaseParticleSystem=class BaseParticleSystem{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:rm.P.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:rm.P.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:rm.P.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:rm.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 r=0;for(let i of t){if(i.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=rm.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 rm.P(10,10,10),this.onAnimationEnd=null,this.blendMode=BaseParticleSystem.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 rm.FM(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new rm.P(0,0,0),this._useLogarithmicDepth=!1,this.gravity=rm.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 rg.HE(1,1,1,1),this.color2=new rg.HE(1,1,1,1),this.colorDead=new rg.HE(0,0,0,1),this.textureMask=new rg.HE(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new sv.b,this.id=e,this.name=e}createPointEmitter(e,t){let i=new PointParticleEmitter;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){let i=new HemisphericParticleEmitter(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){let i=new SphereParticleEmitter(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new rm.P(0,1,0),i=new rm.P(0,1,0)){let r=new SphereDirectedParticleEmitter(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){let s=new CylinderParticleEmitter(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new rm.P(0,1,0),s=new rm.P(0,1,0)){let n=new CylinderDirectedParticleEmitter(e,t,i,r,s);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){let i=new ConeParticleEmitter(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,r){let s=new BoxParticleEmitter;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}};BaseParticleSystem.BLENDMODE_ONEONE=0,BaseParticleSystem.BLENDMODE_STANDARD=1,BaseParticleSystem.BLENDMODE_ADD=2,BaseParticleSystem.BLENDMODE_MULTIPLY=3,BaseParticleSystem.BLENDMODE_MULTIPLYADD=4;let ColorSplitterBlock=class ColorSplitterBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("rgba",tm.Color4,!0),this.registerInput("rgb ",tm.Color3,!0),this.registerOutput("rgb",tm.Color3),this.registerOutput("r",tm.Float),this.registerOutput("g",tm.Float),this.registerOutput("b",tm.Float),this.registerOutput("a",tm.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);let t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;let i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],n=this._outputs[3],a=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb; +`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.r; +`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g; +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.b; +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.a; +`),this}};(0,rv.H)("BABYLON.ColorSplitterBlock",ColorSplitterBlock);var sx=i(5184),sT=i(2195);r6.B.prototype.createRenderTargetCubeTexture=function(e,t){let i=this._createHardwareRenderTargetWrapper(!1,!0,e),r=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},t);r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1);let s=this._gl,n=new r5.l(this,r5.S.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,n,!0);let a=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);1!==r.type||this._caps.textureFloat||(r.type=0,rT.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,a.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,a.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let t=0;t<6;t++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);let o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n.format=r.format,this._internalTexturesCache.push(n),i.setTextures(n),i};let sS={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};let EffectRenderer=class EffectRenderer{constructor(e,t=sS){var i,r;this._fullscreenViewport=new sh.l(0,0,1,1);let s=null!==(i=t.positions)&&void 0!==i?i:sS.positions,n=null!==(r=t.indices)&&void 0!==r?r:sS.indices;this.engine=e,this._vertexBuffers={[rz.o.PositionKind]:new rz.o(e,s,rz.o.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{for(let t in this._indexBuffer=e.createIndexBuffer(n),this._vertexBuffers){let e=this._vertexBuffers[t];e._rebuild()}})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();let 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(){let e=this._vertexBuffers[rz.o.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[rz.o.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}};let EffectWrapper=class EffectWrapper{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new rf.y$;let 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)}));let r=e.defines?e.defines.join("\n"):"";this._drawWrapper=new sm.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,r,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new ss.Q(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,r,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()}};let sC="passPixelShader",sE=`varying vec2 vUV;uniform sampler2D textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);}`;s_.v.ShadersStore[sC]=sE;let sb={name:sC,shader:sE};let dumpTools_DumpTools=class dumpTools_DumpTools{static _CreateDumpRenderer(){if(!dumpTools_DumpTools._DumpToolsEngine){let e;let t=null,i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new r6.B(e,!1,i)}catch(r){e=document.createElement("canvas"),t=new r6.B(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;let r=new EffectRenderer(t),s=new EffectWrapper({engine:t,name:sb.name,fragmentShader:sb.shader,samplerNames:["textureSampler"]});dumpTools_DumpTools._DumpToolsEngine={canvas:e,engine:t,renderer:r,wrapper:s}}return dumpTools_DumpTools._DumpToolsEngine}static async DumpFramebuffer(e,t,i,r,s="image/png",n,a){let o=await i.readPixels(0,0,e,t),l=new Uint8Array(o.buffer);dumpTools_DumpTools.DumpData(e,t,l,r,s,n,!0,void 0,a)}static DumpDataAsync(e,t,i,r="image/png",s,n=!1,a=!1,o){return new Promise(l=>{dumpTools_DumpTools.DumpData(e,t,i,e=>l(e),r,s,n,a,o)})}static DumpData(e,t,i,r,s="image/png",n,a=!1,o=!1,l){let h=dumpTools_DumpTools._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){let e=new Uint8Array(i.length),t=i.length;for(;t--;){let r=i[t];e[t]=Math.round(255*rE.R.Clamp(r))}i=e}let u=h.engine.createRawTexture(i,e,t,5,!1,!a,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",u),h.renderer.draw(),o?rW.w1.ToBlob(h.canvas,e=>{let t=new FileReader;t.onload=e=>{let t=e.target.result;r&&r(t)},t.readAsArrayBuffer(e)},s,l):rW.w1.EncodeScreenshotCanvasData(h.canvas,r,s,n,l),u.dispose()}static Dispose(){dumpTools_DumpTools._DumpToolsEngine&&(dumpTools_DumpTools._DumpToolsEngine.wrapper.dispose(),dumpTools_DumpTools._DumpToolsEngine.renderer.dispose(),dumpTools_DumpTools._DumpToolsEngine.engine.dispose()),dumpTools_DumpTools._DumpToolsEngine=null}};rW.w1.DumpData=dumpTools_DumpTools.DumpData,rW.w1.DumpDataAsync=dumpTools_DumpTools.DumpDataAsync,rW.w1.DumpFramebuffer=dumpTools_DumpTools.DumpFramebuffer;let renderTargetTexture_RenderTargetTexture=class renderTargetTexture_RenderTargetTexture extends texture_Texture{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=(0,rB.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 e=0;e<i.length;++e)for(let r=0;r<this._renderPassIds.length;++r)i[e].setMaterialForRenderPass(this._renderPassIds[r],void 0!==t?Array.isArray(t)?t[r]:t:void 0)}get isMulti(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e.isMulti)&&void 0!==t&&t}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e._depthStencilTexture)&&void 0!==t?t:null}constructor(e,t,i,r=!1,s=!0,n=0,a=!1,o=texture_Texture.TRILINEAR_SAMPLINGMODE,l=!0,h=!1,u=!1,c=5,d=!1,p,_,f=!1,m=!1){var g,v,x,T,S,C,E;let b;let y=!0;if("object"==typeof r){let e=r;r=!!e.generateMipMaps,s=null===(g=e.doNotChangeAspectRatio)||void 0===g||g,n=null!==(v=e.type)&&void 0!==v?v:0,a=!!e.isCube,o=null!==(x=e.samplingMode)&&void 0!==x?x:texture_Texture.TRILINEAR_SAMPLINGMODE,l=null===(T=e.generateDepthBuffer)||void 0===T||T,h=!!e.generateStencilBuffer,u=!!e.isMulti,c=null!==(S=e.format)&&void 0!==S?S:5,d=!!e.delayAllocation,p=e.samples,_=e.creationFlags,f=!!e.noColorAttachment,m=!!e.useSRGBBuffer,b=e.colorAttachment,y=null!==(C=e.gammaSpace)&&void 0!==C?C:y}if(super(null,i,!r,void 0,o,void 0,void 0,void 0,void 0,c),this._unObserveRenderList=null,this._renderListHasChanged=(e,t)=>{var i;let r=this._renderList?this._renderList.length:0;(0===t&&r>0||0===r)&&(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 rf.y$,this.onAfterUnbindObservable=new rf.y$,this.onBeforeRenderObservable=new rf.y$,this.onAfterRenderObservable=new rf.y$,this.onClearObservable=new rf.y$,this.onResizeObservable=new rf.y$,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=rm.P.Zero(),!(i=this.getScene()))return;let P=this.getScene().getEngine();if(this._gammaSpace=y,this._coordinatesMode=texture_Texture.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=a,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=P.onResizeObservable.add(()=>{}),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=s,this._renderingManager=new sT.$(i),this._renderingManager._useSceneAutoClearSetup=!0,u)return;this._renderTargetOptions={generateMipMaps:r,type:n,format:null!==(E=this._format)&&void 0!==E?E:void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:p,creationFlags:_,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:b,label:this.name},this.samplingMode===texture_Texture.NEAREST_SAMPLINGMODE&&(this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE),d||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=texture_Texture.INVCUBIC_MODE,this._textureMatrix=rm.y3.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0===p||(this.samples=p))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14){var n;null===(n=this._renderTarget)||void 0===n||n.createDepthStencilTexture(e,t,i,r,s)}_releaseRenderPassId(){if(this._scene){let e=this._scene.getEngine();for(let t=0;t<this._renderPassIds.length;++t)e.releaseRenderPassId(this._renderPassIds[t])}this._renderPassIds=[]}_createRenderPassId(){this._releaseRenderPassId();let e=this._scene.getEngine(),t=this._isCubeData?6:this.getRenderLayers()||1;for(let i=0;i<t;++i)this._renderPassIds[i]=e.createRenderPassId(`RenderTargetTexture - ${this.name}#${i}`)}_processSizeParameter(e,t=!0){if(e.ratio){this._sizeRatio=e.ratio;let t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e;t&&this._createRenderPassId()}get samples(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e.samples)&&void 0!==t?t:this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}addPostProcess(e){if(!this._postProcessManager){let e=this.getScene();if(!e)return;this._postProcessManager=new sx.O(e),this._postProcesses=[]}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(let e of this._postProcesses)e.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;let t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return -1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){let e=this._size.layers;return e||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){let t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var t;let i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;let r=this.getScene();r&&(this._processSizeParameter(e,!1),i?this._renderTarget=r.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=r.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 r;let s=this.getScene();if(!s)return i;let n=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let e=0;e<this._waitingRenderList.length;e++){let t=this._waitingRenderList[e],i=s.getMeshById(t);i&&this.renderList.push(i)}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];let e=this.getScene();if(!e)return i;let t=e.meshes;for(let e=0;e<t.length;e++){let i=t[e];this.renderListPredicate(i)&&this.renderList.push(i)}}let a=n.currentRenderPassId;this.onBeforeBindObservable.notifyObservers(this);let o=null!==(r=this.activeCamera)&&void 0!==r?r:s.activeCamera,l=s.activeCamera;o&&(o!==s.activeCamera&&(s.setTransformMatrix(o.getViewMatrix(),o.getProjectionMatrix(!0)),s.activeCamera=o),n.setViewport(o.rigParent?o.rigParent.viewport:o.viewport,this.getRenderWidth(),this.getRenderHeight())),this._defaultRenderListPrepared=!1;let h=i;if(i){s.getViewMatrix()||s.updateTransformMatrix();let e=this.is2DArray?this.getRenderLayers():this.isCube?6:1;for(let t=0;t<e&&h;t++){let e=null,r=this.renderList?this.renderList:s.getActiveMeshes().data,a=this.renderList?this.renderList.length:s.getActiveMeshes().length;n.currentRenderPassId=this._renderPassIds[t],this.onBeforeRenderObservable.notifyObservers(t),this.getCustomRenderList&&(e=this.getCustomRenderList(t,r,a)),e||(e=r),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0);for(let t=0;t<e.length&&h;++t){let r=e[t];if(r.isEnabled()&&!r.isBlocked&&r.isVisible&&r.subMeshes){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(r,this.refreshRate,i)){h=!1;continue}}else if(!r.isReady(!0)){h=!1;continue}}}this.onAfterRenderObservable.notifyObservers(t),(this.is2DArray||this.isCube)&&(s.incrementRenderId(),s.resetCachedMaterial())}}else if(this.is2DArray&&!this.isMulti)for(let i=0;i<this.getRenderLayers();i++)this._renderToTarget(0,e,t,i,o),s.incrementRenderId(),s.resetCachedMaterial();else if(this.isCube&&!this.isMulti)for(let i=0;i<6;i++)this._renderToTarget(i,e,t,void 0,o),s.incrementRenderId(),s.resetCachedMaterial();else this._renderToTarget(0,e,t,void 0,o);return this.onAfterUnbindObservable.notifyObservers(this),n.currentRenderPassId=a,l&&(s.activeCamera=l,(s.getEngine().scenes.length>1||this.activeCamera&&this.activeCamera!==s.activeCamera)&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),n.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){let i=e*t,r=rq.D.NearestPOT(i+16384/(128+i));return Math.min(rq.D.FloorPOT(e),r)}_prepareRenderingManager(e,t,i,r){let s=this.getScene();if(!s)return;this._renderingManager.reset();let n=s.getRenderId();for(let a=0;a<t;a++){let t=e[a];if(t&&!t.isBlocked){let e;if(this.customIsReadyFunction){if(!this.customIsReadyFunction(t,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!t.isReady(0===this.refreshRate)){this.resetRefreshCounter();continue}if(!t._internalAbstractMeshDataInfo._currentLODIsUpToDate&&s.activeCamera&&(t._internalAbstractMeshDataInfo._currentLOD=s.customLODSelector?s.customLODSelector(t,this.activeCamera||s.activeCamera):t.getLOD(this.activeCamera||s.activeCamera),t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0),!t._internalAbstractMeshDataInfo._currentLOD)continue;let a=t._internalAbstractMeshDataInfo._currentLOD;if(a._preActivateForIntermediateRendering(n),e=!!r&&!!i&&(t.layerMask&i.layerMask)==0,t.isEnabled()&&t.isVisible&&t.subMeshes&&!e&&(a!==t&&a._activate(n,!0),t._activate(n,!0)&&t.subMeshes.length)){t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(a=t):a._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,a._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(let e=0;e<a.subMeshes.length;e++){let t=a.subMeshes[e];this._renderingManager.dispatch(t,a)}}}}for(let e=0;e<s.particleSystems.length;e++){let t=s.particleSystems[e],i=t.emitter;t.isStarted()&&i&&(!i.position||i.isEnabled())&&this._renderingManager.dispatchParticles(t)}}_bindFrameBuffer(e=0,t=0){let i=this.getScene();if(!i)return;let r=i.getEngine();this._renderTarget&&r.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):r&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0,s=null){var n,a,o,l,h,u;let c=this.getScene();if(!c)return;let d=c.getEngine();null===(n=d._debugPushGroup)||void 0===n||n.call(d,`render to face #${e} layer #${r}`,1),this._prepareFrame(c,e,r,t),this.is2DArray?(d.currentRenderPassId=this._renderPassIds[r],this.onBeforeRenderObservable.notifyObservers(r)):(d.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));let p=d.snapshotRendering&&1===d.snapshotRenderingMode;if(p)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||c.clearColor,!0,!0,!0);else{let n=null,u=this.renderList?this.renderList:c.getActiveMeshes().data,p=this.renderList?this.renderList.length:c.getActiveMeshes().length;for(let t of(this.getCustomRenderList&&(n=this.getCustomRenderList(this.is2DArray?r:e,u,p)),n?this._prepareRenderingManager(n,n.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(u,p,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),n=u),c._beforeRenderTargetClearStage))t.action(this,e,r);for(let t of(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||c.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||c.updateTransformMatrix(!0),c._beforeRenderTargetDrawStage))t.action(this,e,r);for(let t of(this._renderingManager.render(this.customRenderFunction,n,this.renderParticles,this.renderSprites),c._afterRenderTargetDrawStage))t.action(this,e,r);let _=null!==(o=null===(a=this._texture)||void 0===a?void 0:a.generateMipMaps)&&void 0!==o&&o;for(let i of(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&&c.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e),c._afterRenderTargetPostProcessStage))i.action(this,e,r);this._texture&&(this._texture.generateMipMaps=_),this._doNotChangeAspectRatio||c.updateTransformMatrix(!0),i&&dumpTools_DumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),d)}this._unbindFrameBuffer(d,e),this._texture&&this.isCube&&5===e&&d.generateMipMapsForCubemap(this._texture),null===(u=d._debugPopGroup)||void 0===u||u.call(d,1)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){let e=this.getSize(),t=new renderTargetTexture_RenderTargetTexture(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;let e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t<this.renderList.length;t++)e.renderList.push(this.renderList[t].id);return e}disposeFramebufferObjects(){var e;null===(e=this._renderTarget)||void 0===e||e.dispose(!0)}releaseInternalTexture(){var e;null===(e=this._renderTarget)||void 0===e||e.releaseTextures(),this._texture=null}dispose(){var e;this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._releaseRenderPassId(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;let t=this.getScene();if(!t)return;let i=t.customRenderTargets.indexOf(this);for(let e of(i>=0&&t.customRenderTargets.splice(i,1),t.cameras))(i=e.customRenderTargets.indexOf(this))>=0&&e.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}};renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE=0,renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME=1,renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,texture_Texture._CreateRenderTargetTexture=(e,t,i,r,s)=>new renderTargetTexture_RenderTargetTexture(e,t,i,r);let ProceduralTextureSceneComponent=class ProceduralTextureSceneComponent{constructor(e){this.name=rQ.l.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(rQ.l.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){rW.w1.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e<this.scene.proceduralTextures.length;e++){let t=this.scene.proceduralTextures[e];t._shouldRender()&&t.render()}rW.w1.EndPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0)}}};let sy=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.proceduralVertexShader=sy;let proceduralTexture_ProceduralTexture=class proceduralTexture_ProceduralTexture extends texture_Texture{constructor(e,t,i,r,s=null,n=!0,a=!1,o=0){super(null,r,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new rf.y$,this.onBeforeGenerationObservable=new rf.y$,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=[],this._samplers=[],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 l=(r=this.getScene()||rS.l.LastCreatedScene)._getComponent(rQ.l.NAME_PROCEDURALTEXTURE);l||(l=new ProceduralTextureSceneComponent(r),r._addComponent(l)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=o,this._generateMipMaps=n,this._drawWrapper=new sm.q(this._fullEngine),this.setFragment(i),this._fallbackTexture=s;let h=this._createRtWrapper(a,t,n,o);this._texture=h.texture;let u=[];u.push(1,1),u.push(-1,1),u.push(-1,-1),u.push(1,-1),this._vertexBuffers[rz.o.PositionKind]=new rz.o(this._fullEngine,u,rz.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r}),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(){let 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(){let e=this._vertexBuffers[rz.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}isReady(){let e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;let t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;let i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[rz.o.PositionKind],this._uniforms,this._samplers,t,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;let i=this._texture.isCube;this._rtWrapper.dispose();let r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return -1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;let r=this.getScene();if(!r)return;let s=this._fullEngine;if(s.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),s.setState(!1),!this.nodeMaterialSource){for(let e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(let e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(let e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(let e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(let e in this._colors4){let t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(let e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(let 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);let n=s.currentViewport;if(this.isCube)for(let e=0;e<6;e++)s.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(sr.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(r.clearColor,!0,!1,!1),s.drawElementsType(sr.F.TriangleFillMode,0,6);s.unBindFramebuffer(this._rtWrapper,this.isCube),n&&s.setViewport(n),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(){let e=this.getSize(),t=new proceduralTexture_ProceduralTexture(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(){let e=this.getScene();if(!e)return;let t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);let i=this._vertexBuffers[rz.o.PositionKind];i&&(i.dispose(),this._vertexBuffers[rz.o.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}};(0,rH.gn)([(0,rb.qC)()],proceduralTexture_ProceduralTexture.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],proceduralTexture_ProceduralTexture.prototype,"autoClear",void 0),(0,rH.gn)([(0,rb.qC)()],proceduralTexture_ProceduralTexture.prototype,"_generateMipMaps",void 0),(0,rH.gn)([(0,rb.qC)()],proceduralTexture_ProceduralTexture.prototype,"_size",void 0),(0,rH.gn)([(0,rb.qC)()],proceduralTexture_ProceduralTexture.prototype,"refreshRate",null),(0,rv.H)("BABYLON.ProceduralTexture",proceduralTexture_ProceduralTexture),(v=ty||(ty={}))[v.Cos=0]="Cos",v[v.Sin=1]="Sin",v[v.Abs=2]="Abs",v[v.Exp=3]="Exp",v[v.Exp2=4]="Exp2",v[v.Round=5]="Round",v[v.Floor=6]="Floor",v[v.Ceiling=7]="Ceiling",v[v.Sqrt=8]="Sqrt",v[v.Log=9]="Log",v[v.Tan=10]="Tan",v[v.ArcTan=11]="ArcTan",v[v.ArcCos=12]="ArcCos",v[v.ArcSin=13]="ArcSin",v[v.Fract=14]="Fract",v[v.Sign=15]="Sign",v[v.Radians=16]="Radians",v[v.Degrees=17]="Degrees";let TrigonometryBlock=class TrigonometryBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.operation=ty.Cos,this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.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);let t=this._outputs[0],i="";switch(this.operation){case ty.Cos:i="cos";break;case ty.Sin:i="sin";break;case ty.Abs:i="abs";break;case ty.Exp:i="exp";break;case ty.Exp2:i="exp2";break;case ty.Round:i="round";break;case ty.Floor:i="floor";break;case ty.Ceiling:i="ceil";break;case ty.Sqrt:i="sqrt";break;case ty.Log:i="log";break;case ty.Tan:i="tan";break;case ty.ArcTan:i="atan";break;case ty.ArcCos:i="acos";break;case ty.ArcSin:i="asin";break;case ty.Fract:i="fract";break;case ty.Sign:i="sign";break;case ty.Radians:i="radians";break;case ty.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName}); +`,this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${ty[this.operation]}; +`;return e}};(0,rv.H)("BABYLON.TrigonometryBlock",TrigonometryBlock);let sP={effect:null,subMesh:null};let NodeMaterialDefines=class NodeMaterialDefines extends sn.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.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!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}};let NodeMaterial=class NodeMaterial extends PushMaterial{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()||"PrePassTextureBlock"===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||rS.l.LastCreatedScene),this._buildId=NodeMaterial._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new rm.y3,this._cachedWorldViewProjectionMatrix=new rm.y3,this._optimizers=[],this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new rf.y$,this._vertexOutputNodes=[],this._fragmentOutputNodes=[],this.attachedBlocks=[],this._mode=tb.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),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){rW.w1.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(let t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){let t=this._optimizers.indexOf(e);if(!(t>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){let t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return(e.target&tg.Vertex)!=0&&this._addVertexOutputNode(e),(e.target&tg.Fragment)!=0&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||((e.target&tg.Vertex)!=0&&this._removeVertexOutputNode(e),(e.target&tg.Fragment)!=0&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=tg.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){let 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=tg.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){let t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){e.target===tg.VertexAndFragment?i.push(e):t.target===tg.Fragment&&e.target===tg.Vertex&&e._preparationId!==this._buildId&&i.push(e),this._initializeBlock(e,t,i,r)}_initializeBlock(e,t,i,r=!0){if(e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){let t=e.getClassName();for(let 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(let s of e.inputs){s.associatedVariableName="";let n=s.connectedPoint;if(n){let s=n.ownerBlock;s!==e&&this._processInitializeOnLink(s,t,i,r)}}for(let s of(e.isTeleportOut&&e.entryPoint&&this._processInitializeOnLink(e.entryPoint,t,i,r),e.outputs))s.associatedVariableName=""}_resetDualBlocks(e,t){for(let i of(e.target===tg.VertexAndFragment&&(e.buildId=t),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._resetDualBlocks(e.entryPoint,t)}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;let r=this.getScene().getEngine(),s=this._mode===tb.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 NodeMaterialBuildState,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=tg.Vertex,this._fragmentCompilationState=new NodeMaterialBuildState,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=tg.Fragment,this._sharedData=new NodeMaterialBuildStateSharedData,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;let n=[],a=[];for(let e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,a,i);for(let e of this._fragmentOutputNodes)a.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);for(let e of(this.optimize(),n))e.build(this._vertexCompilationState,n);for(let e of(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,a))this._resetDualBlocks(e,this._buildId-1);for(let e of a)e.build(this._fragmentCompilationState,a);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=NodeMaterial._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);let o=this.getScene().meshes;for(let e of o)if(e.subMeshes)for(let t of e.subMeshes){if(t.getMaterial()!==this||!t.materialDefines)continue;let e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();let l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(let e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){let i=t.NORMAL,r=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(rz.o.NormalKind),t.TANGENT=e.isVerticesDataPresent(rz.o.TangentKind);let n=e.useVertexColors&&e.isVerticesDataPresent(rz.o.ColorKind);t.VERTEXCOLOR_NME=n;let a=!1;for(let i=1;i<=6;++i){let r=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),a=a||t["UV"+i]!==r}let o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;so.G.PrepareDefinesForPrePass(this.getScene(),t,!o),(i!==t.NORMAL||r!==t.TANGENT||s!==t.VERTEXCOLOR_NME||a)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){let e=this.getBlockByPredicate(e=>"PrePassOutputBlock"===e.getClassName()),t=[4];return!e||this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t}get prePassTextureInputs(){let e=this.getAllTextureBlocks().filter(e=>"PrePassTextureBlock"===e.getClassName()),t=[];for(let i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){let t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");for(let r of(i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]})),t))i.texturesRequired.includes(r)||i.texturesRequired.push(r);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,r,s,n=0,a=5){return this.mode!==tb.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,s,n,a)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,s,n,a=0,o=5){let l=this.name+this._buildId,h=new NodeMaterialDefines,u=new rG.x(l+"PostProcess",this.getScene()),c=this._buildId;return this._processDefines(u,h),ss.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 postProcess_PostProcess(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,s,n,h.toString(),a,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,o),e.nodeMaterialSource=this,e.onApplyObservable.add(t=>{c!==this._buildId&&(delete ss.Q.ShadersStore[l+"VertexShader"],delete ss.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),c=this._buildId);let i=this._processDefines(u,h);i&&(ss.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),r0.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!==tb.ProceduralTexture)return console.log("Incompatible material mode"),null;let i=this.name+this._buildId,r=new proceduralTexture_ProceduralTexture(i,e,null,t),s=new rG.x(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};let n=new NodeMaterialDefines,a=this._processDefines(s,n);ss.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[rz.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),null==a?void 0:a.fallbacks,void 0);r.nodeMaterialSource=this,r._setEffect(o);let l=this._buildId;return r.onBeforeGenerationObservable.add(()=>{l!==this._buildId&&(delete ss.Q.ShadersStore[i+"VertexShader"],delete ss.Q.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);let e=this._processDefines(s,n);e&&(ss.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),r0.Q.SetImmediate(()=>{o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[rz.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),null==e?void 0:e.fallbacks,void 0),r._setEffect(o)})),this._checkInternals(o)}),r}_createEffectForParticles(e,t,i,r,s,n,a,o=""){let l=this.name+this._buildId+"_"+t;n||(n=new NodeMaterialDefines),a||(a=this.getScene().getMeshByName(this.name+"Particle"))||((a=new rG.x(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId,u=[],c=o;if(!s){let o=this._processDefines(a,n);ss.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(u,t),c=u.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+c,null==o?void 0:o.fallbacks,i,r,e),e.setCustomEffect(s,t)}s.onBindObservable.add(s=>{h!==this._buildId&&(delete ss.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),u.length=0,e.fillDefines(u,t);let d=u.join("\n");d!==c&&(n.markAllAsDirty(),c=d);let p=this._processDefines(a,n);if(p){ss.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+c,null==p?void 0:p.fallbacks,i,r,e),e.setCustomEffect(s,t),this._createEffectForParticles(e,t,i,r,s,n,a,o);return}this._checkInternals(s)})}_checkInternals(e){if(this._sharedData.animatedInputs){let e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(let t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(let t of this._sharedData.bindableBlocks)t.bind(e,this);for(let t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){if(this.mode!==tb.Particle){console.log("Incompatible material mode");return}this._createEffectForParticles(e,BaseParticleSystem.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,BaseParticleSystem.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==tb.Material){console.log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,r){let s=null,n=this.getScene();if(so.G.PrepareDefinesForCamera(n,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(r=>{r.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(s=>{s.prepareDefines(e,this,t,i,r)}),t.isDirty){let 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)});let r=[];this._sharedData.dynamicUniformBlocks.forEach(e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,r)});let n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(e=>{let t=n.indexOf(e);-1===t&&n.push(e)});let a=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(e=>{let t=a.indexOf(e);-1===t&&a.push(e)});let o=new EffectFallbacks;this._sharedData.blocksWithFallbacks.forEach(t=>{t.provideFallbacks(e,o)}),s={lightDisposed:i,uniformBuffers:r,mergedUniforms:n,mergedSamplers:a,fallbacks:o}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;let r=this.getScene();if(this._sharedData.animatedInputs){let e=r.getFrameId();if(this._animationFrame!==e){for(let e of this._sharedData.animatedInputs)e.animate(r);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new NodeMaterialDefines);let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();if(this._prepareDefinesForAttributes(e,s),this._sharedData.blockingBlocks.some(t=>!t.isReady(e,this,s,i)))return!1;let a=this._processDefines(e,s,i,t);if(a){let e=t.effect,i=s.toString(),o=n.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:s.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},n);if(o){if(this._onEffectCreatedObservable&&(sP.effect=o,sP.subMesh=t,this._onEffectCreatedObservable.notifyObservers(sP)),this.allowShaderHotSwapping&&e&&!o.isReady()){if(o=e,s.markAsUnprocessed(),a.lightDisposed)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(o,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader +${this._vertexCompilationState.compilationString} + +// Fragment shader +${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){let t=this.getScene();if(!this._activeEffect)return;let i=this._sharedData.hints;for(let r of(i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),this._sharedData.inputBlocks))r._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);let n=this._mustRebind(r,s,t.visibility),a=this._sharedData;if(n){for(let e of a.bindableBlocks)e.bind(s,this,t,i);for(let e of a.forcedBindableBlocks)e.bind(s,this,t,i);for(let e of a.inputBlocks)e._transmit(s,r,this)}else if(!this.isFrozen)for(let e of a.forcedBindableBlocks)e.bind(s,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){let 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(){let e=[];for(let t of this.attachedBlocks)NodeMaterial._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(let t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(let e of this.getTextureBlocks().filter(e=>e.texture).map(e=>e.texture))e.dispose();for(let e of this.attachedBlocks)e.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){let 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){let i=e&&e.editorURL?e.editorURL:NodeMaterial.EditorURL;rW.w1.LoadBabylonScript(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;let e=new InputBlock("Position");e.setAsAttribute("position");let t=new InputBlock("World");t.setAsSystemValue(tC.World);let i=new TransformBlock("WorldPos");e.connectTo(i),t.connectTo(i);let r=new InputBlock("ViewProjection");r.setAsSystemValue(tC.ViewProjection);let s=new TransformBlock("WorldPos * ViewProjectionTransform");i.connectTo(s),r.connectTo(s);let n=new VertexOutputBlock("VertexOutput");s.connectTo(n);let a=new InputBlock("color");a.value=new rg.HE(.8,.8,.8,1);let o=new FragmentOutputBlock("FragmentOutput");a.connectTo(o),this.addOutputNode(n),this.addOutputNode(o),this._mode=tb.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;let e=new InputBlock("Position");e.setAsAttribute("position2d");let t=new InputBlock("Constant1");t.isConstant=!0,t.value=1;let i=new VectorMergerBlock("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new VertexOutputBlock("VertexOutput");i.connectTo(r);let s=new InputBlock("Scale");s.visibleInInspector=!0,s.value=new rm.FM(1,1);let n=new RemapBlock("uv0");e.connectTo(n);let a=new MultiplyBlock("UV scale");n.connectTo(a),s.connectTo(a);let o=new CurrentScreenBlock("CurrentScreen");a.connectTo(o),o.texture=new texture_Texture("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());let l=new FragmentOutputBlock("FragmentOutput");o.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=tb.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;let e=new InputBlock("Position");e.setAsAttribute("position2d");let t=new InputBlock("Constant1");t.isConstant=!0,t.value=1;let i=new VectorMergerBlock("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new VertexOutputBlock("VertexOutput");i.connectTo(r);let s=new InputBlock("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=tE.Time,s.isConstant=!1;let n=new InputBlock("Color3");n.value=new rg.Wo(1,1,1),n.isConstant=!1;let a=new FragmentOutputBlock("FragmentOutput"),o=new VectorMergerBlock("VectorMerger");o.visibleInInspector=!1;let l=new TrigonometryBlock("Cos");l.operation=ty.Cos,e.connectTo(o),s.output.connectTo(l.input),l.output.connectTo(o.z),o.xyzOut.connectTo(a.rgb),this.addOutputNode(r),this.addOutputNode(a),this._mode=tb.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;let e=new InputBlock("uv");e.setAsAttribute("particle_uv");let t=new ParticleTextureBlock("ParticleTexture");e.connectTo(t);let i=new InputBlock("Color");i.setAsAttribute("particle_color");let r=new MultiplyBlock("Texture * Color");t.connectTo(r),i.connectTo(r);let s=new ParticleRampGradientBlock("ParticleRampGradient");r.connectTo(s);let n=new ColorSplitterBlock("ColorSplitter");i.connectTo(n);let a=new ParticleBlendMultiplyBlock("ParticleBlendMultiply");s.connectTo(a),t.connectTo(a,{output:"a"}),n.connectTo(a,{output:"a"});let o=new FragmentOutputBlock("FragmentOutput");a.connectTo(o),this.addOutputNode(o),this._mode=tb.Particle}async loadAsync(e,t=""){return NodeMaterial.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}generateCode(){let e=[],t=[],i=["const","var","let"];for(let e of this._vertexOutputNodes)this._gatherBlocks(e,t);let r=[];for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,r);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); +`;for(let r of(s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${tb[this.mode]}; +`,t))r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(let t of r)t.isInput&&-1===e.indexOf(t)&&(s+=t._dumpCode(i,e));for(let t of(e=[],s+="\n// Connections\n",this._vertexOutputNodes))s+=t._dumpCodeForOutputConnections(e);for(let t of this._fragmentOutputNodes)s+=t._dumpCodeForOutputConnections(e);for(let e of(s+="\n// Output nodes\n",this._vertexOutputNodes))s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); +`;for(let e of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); +`;return s+`nodeMaterial.build(); +`}serialize(e){let t=e?{}:rb.p4.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{for(let e of(t.customType="BABYLON.NodeMaterial",t.outputNodes=[],this._vertexOutputNodes))this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}for(let e of(t.blocks=[],i))t.blocks.push(e.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let n=i[s.id];if(n){for(let a of s.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===r.name){let e=n.getInputByName(a.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){var r;i||this.clear();let s={};for(let i of e.blocks){let e=(0,rv.q)(i.customType);if(e){let r=new e;r._deserialize(i,this.getScene(),t),s[i.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;if(t){let i=s[t];i.attachToEndpoint(e)}}for(let t=0;t<e.blocks.length;t++){let r=e.blocks[t],n=s[r.id];n&&(!n.inputs.length||i)&&this._restoreConnections(n,e,s)}if(e.outputNodes)for(let t of e.outputNodes)this.addOutputNode(s[t]);if(e.locations||e.editorData&&e.editorData.locations){let t=e.locations||e.editorData.locations;for(let e of t)s[e.blockId]&&(e.blockId=s[e.blockId].uniqueId);i&&this.editorData&&this.editorData.locations&&t.concat(this.editorData.locations),e.locations?this.editorData={locations:t}:(this.editorData=e.editorData,this.editorData.locations=t);let r=[];for(let e in s)r[e]=s[e].uniqueId;this.editorData.map=r}this.comment=e.comment,void 0!==e.forceAlphaBlending&&(this.forceAlphaBlending=e.forceAlphaBlending),i||(this._mode=null!==(r=e.mode)&&void 0!==r?r:tb.Material)}loadFromSerialization(e,t="",i=!1){this.parseSerializedObject(e,t,i)}clone(e,t=!1){let i=this.serialize(),r=rb.p4.Clone(()=>new NodeMaterial(e,this.getScene(),this.options),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}whenTexturesReadyAsync(){let e=[];return this.getActiveTextures().forEach(t=>{let i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((e,t)=>{i.onLoadedObservable.addOnce(()=>{e()}),i.onErrorObservable.addOnce(e=>{t(e)})}))}),Promise.all(e)}static Parse(e,t,i=""){let r=rb.p4.Parse(()=>new NodeMaterial(e.name,t),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,r="",s=!1,n){let a=null!=n?n:new NodeMaterial(e,i),o=await i._loadFileAsync(t),l=JSON.parse(o);return a.parseSerializedObject(l,r),s||a.build(),a}static ParseFromSnippetAsync(e,t=rS.l.LastCreatedScene,i="",r,s=!1,n=!1){return"_BLANK"===e?Promise.resolve(NodeMaterial.CreateDefault("blank",t)):new Promise((a,o)=>{let l=new rP.g;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let h=JSON.parse(JSON.parse(l.responseText).jsonPayload),u=JSON.parse(h.nodeMaterial);r||((r=rb.p4.Parse(()=>new NodeMaterial(e,t),u,t,i)).uniqueId=t.getUniqueId()),r.parseSerializedObject(u),r.snippetId=e;try{s||r.build()}catch(e){o(e)}n?r.whenTexturesReadyAsync().then(()=>{a(r)}).catch(e=>{o(e)}):a(r)}else o("Unable to load the snippet "+e)}}),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()})}static CreateDefault(e,t){let i=new NodeMaterial(e,t);return i.setToDefault(),i.build(),i}};function CreateIcoSphereVertexData(e){let t;let i=e.sideOrientation||se.x.DEFAULTSIDE,r=e.radius||1,s=void 0===e.flat||e.flat,n=0|(e.subdivisions||4),a=e.radiusX||r,o=e.radiusY||r,l=e.radiusZ||r,h=(1+Math.sqrt(5))/2,u=[-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],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],d=[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],_=138/1024,f=239/1024,m=60/1024,g=26/1024,v=-40/1024,x=20/1024,T=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],S=[],C=[],E=[],b=[],y=0,P=[,,,],R=[,,,];for(t=0;t<3;t++)P[t]=rm.P.Zero(),R[t]=rm.FM.Zero();for(let e=0;e<20;e++){for(t=0;t<3;t++){let i=c[3*e+t];P[t].copyFromFloats(u[3*d[i]],u[3*d[i]+1],u[3*d[i]+2]),P[t].normalize(),R[t].copyFromFloats(p[2*i]*_+m+T[e]*v,p[2*i+1]*f+g+T[e]*x)}let interp_vertex=(e,t,i,r)=>{let h;let u=rm.P.Lerp(P[0],P[2],t/n),c=rm.P.Lerp(P[1],P[2],t/n),d=n===t?P[2]:rm.P.Lerp(u,c,e/(n-t));if(d.normalize(),s){let e=rm.P.Lerp(P[0],P[2],r/n),t=rm.P.Lerp(P[1],P[2],r/n);h=rm.P.Lerp(e,t,i/(n-r))}else h=new rm.P(d.x,d.y,d.z);h.x/=a,h.y/=o,h.z/=l,h.normalize();let p=rm.FM.Lerp(R[0],R[2],t/n),_=rm.FM.Lerp(R[1],R[2],t/n),f=n===t?R[2]:rm.FM.Lerp(p,_,e/(n-t));C.push(d.x*a,d.y*o,d.z*l),E.push(h.x,h.y,h.z),b.push(f.x,r4.e.UseOpenGLOrientationForUV?1-f.y:f.y),S.push(y),y++};for(let e=0;e<n;e++)for(let t=0;t+e<n;t++)interp_vertex(t,e,t+1/3,e+1/3),interp_vertex(t+1,e,t+1/3,e+1/3),interp_vertex(t,e+1,t+1/3,e+1/3),t+e+1<n&&(interp_vertex(t+1,e,t+2/3,e+2/3),interp_vertex(t+1,e+1,t+2/3,e+2/3),interp_vertex(t,e+1,t+2/3,e+2/3))}se.x._ComputeSides(i,C,S,E,b,e.frontUVs,e.backUVs);let A=new se.x;return A.indices=S,A.positions=C,A.normals=E,A.uvs=b,A}function CreateIcoSphere(e,t={},i=null){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateIcoSphereVertexData(t);return s.applyToMesh(r,t.updatable),r}NodeMaterial._BuildIdGenerator=0,NodeMaterial.EditorURL=`${rW.w1._DefaultCdnUrl}/v${rq.D.Version}/nodeEditor/babylon.nodeEditor.js`,NodeMaterial.SnippetUrl="https://snippet.babylonjs.com",NodeMaterial.IgnoreTexturesAtLoadTime=!1,(0,rH.gn)([(0,rb.qC)()],NodeMaterial.prototype,"ignoreAlpha",void 0),(0,rH.gn)([(0,rb.qC)()],NodeMaterial.prototype,"maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.qC)("mode")],NodeMaterial.prototype,"_mode",void 0),(0,rH.gn)([(0,rb.qC)("comment")],NodeMaterial.prototype,"comment",void 0),(0,rH.gn)([(0,rb.qC)()],NodeMaterial.prototype,"forceAlphaBlending",void 0),(0,rv.H)("BABYLON.NodeMaterial",NodeMaterial),se.x.CreateIcoSphere=CreateIcoSphereVertexData,rV.Kj.CreateIcoSphere=(e,t,i)=>CreateIcoSphere(e,t,i),(x=tP||(tP={})).WRIST="wrist",x.THUMB="thumb",x.INDEX="index",x.MIDDLE="middle",x.RING="ring",x.LITTLE="little",(T=tR||(tR={})).WRIST="wrist",T.THUMB_METACARPAL="thumb-metacarpal",T.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",T.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",T.THUMB_TIP="thumb-tip",T.INDEX_FINGER_METACARPAL="index-finger-metacarpal",T.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",T.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",T.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",T.INDEX_FINGER_TIP="index-finger-tip",T.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",T.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",T.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",T.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",T.MIDDLE_FINGER_TIP="middle-finger-tip",T.RING_FINGER_METACARPAL="ring-finger-metacarpal",T.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",T.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",T.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",T.RING_FINGER_TIP="ring-finger-tip",T.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",T.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",T.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",T.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",T.PINKY_FINGER_TIP="pinky-finger-tip";let sR=[tR.WRIST,tR.THUMB_METACARPAL,tR.THUMB_PHALANX_PROXIMAL,tR.THUMB_PHALANX_DISTAL,tR.THUMB_TIP,tR.INDEX_FINGER_METACARPAL,tR.INDEX_FINGER_PHALANX_PROXIMAL,tR.INDEX_FINGER_PHALANX_INTERMEDIATE,tR.INDEX_FINGER_PHALANX_DISTAL,tR.INDEX_FINGER_TIP,tR.MIDDLE_FINGER_METACARPAL,tR.MIDDLE_FINGER_PHALANX_PROXIMAL,tR.MIDDLE_FINGER_PHALANX_INTERMEDIATE,tR.MIDDLE_FINGER_PHALANX_DISTAL,tR.MIDDLE_FINGER_TIP,tR.RING_FINGER_METACARPAL,tR.RING_FINGER_PHALANX_PROXIMAL,tR.RING_FINGER_PHALANX_INTERMEDIATE,tR.RING_FINGER_PHALANX_DISTAL,tR.RING_FINGER_TIP,tR.PINKY_FINGER_METACARPAL,tR.PINKY_FINGER_PHALANX_PROXIMAL,tR.PINKY_FINGER_PHALANX_INTERMEDIATE,tR.PINKY_FINGER_PHALANX_DISTAL,tR.PINKY_FINGER_TIP],sA={[tP.WRIST]:[tR.WRIST],[tP.THUMB]:[tR.THUMB_METACARPAL,tR.THUMB_PHALANX_PROXIMAL,tR.THUMB_PHALANX_DISTAL,tR.THUMB_TIP],[tP.INDEX]:[tR.INDEX_FINGER_METACARPAL,tR.INDEX_FINGER_PHALANX_PROXIMAL,tR.INDEX_FINGER_PHALANX_INTERMEDIATE,tR.INDEX_FINGER_PHALANX_DISTAL,tR.INDEX_FINGER_TIP],[tP.MIDDLE]:[tR.MIDDLE_FINGER_METACARPAL,tR.MIDDLE_FINGER_PHALANX_PROXIMAL,tR.MIDDLE_FINGER_PHALANX_INTERMEDIATE,tR.MIDDLE_FINGER_PHALANX_DISTAL,tR.MIDDLE_FINGER_TIP],[tP.RING]:[tR.RING_FINGER_METACARPAL,tR.RING_FINGER_PHALANX_PROXIMAL,tR.RING_FINGER_PHALANX_INTERMEDIATE,tR.RING_FINGER_PHALANX_DISTAL,tR.RING_FINGER_TIP],[tP.LITTLE]:[tR.PINKY_FINGER_METACARPAL,tR.PINKY_FINGER_PHALANX_PROXIMAL,tR.PINKY_FINGER_PHALANX_INTERMEDIATE,tR.PINKY_FINGER_PHALANX_DISTAL,tR.PINKY_FINGER_TIP]};let WebXRHand=class WebXRHand{get handMesh(){return this._handMesh}getHandPartMeshes(e){return sA[e].map(e=>this._jointMeshes[sR.indexOf(e)])}getJointMesh(e){return this._jointMeshes[sR.indexOf(e)]}constructor(e,t,i,r,s=!1,n=!1,a=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=s,this._jointsInvisible=n,this._jointScaleFactor=a,this._jointTransforms=Array(sR.length),this._jointTransformMatrices=new Float32Array(16*sR.length),this._tempJointMatrix=new rm.y3,this._jointRadii=new Float32Array(sR.length),this._scene=t[0].getScene();for(let e=0;e<this._jointTransforms.length;e++){let i=this._jointTransforms[e]=new rk.Y(sR[e],this._scene);i.rotationQuaternion=new rm._f,t[e].rotationQuaternion=new rm._f}i&&this.setHandMesh(i,r),this.xrController.motionController&&(this.xrController.motionController.rootMesh?this.xrController.motionController.rootMesh.setEnabled(!1):this.xrController.motionController.onModelLoadedObservable.add(e=>{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){let e=this._handMesh.skeleton;sR.forEach((i,r)=>{let s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[r])})}}updateFromXRFrame(e,t){let i=this.xrController.inputSource.hand;if(!i)return;let r=sR.map(e=>i[e]||i.get(e)),s=!1;if(e.fillPoses&&e.fillJointRadii)s=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){s=!0;for(let i=0;i<r.length;i++){let n=e.getJointPose(r[i],t);if(n)this._jointTransformMatrices.set(n.transform.matrix,16*i),this._jointRadii[i]=n.radius||.008;else{s=!1;break}}}s&&(sR.forEach((e,t)=>{let i=this._jointTransforms[t];rm.y3.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);let r=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(r),!this._scene.useRightHandedSystem&&(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}};let WebXRHandTracking=class WebXRHandTracking extends WebXRAbstractFeature{static _GenerateTrackedJointMeshes(e){let t={};return["left","right"].map(i=>{var r,s,n,a,o;let l=[],h=(null===(r=e.jointMeshes)||void 0===r?void 0:r.sourceMesh)||CreateIcoSphere("jointParent",WebXRHandTracking._ICOSPHERE_PARAMS);h.isVisible=!!(null===(s=e.jointMeshes)||void 0===s?void 0:s.keepOriginalVisible);for(let t=0;t<sR.length;++t){let r=h.createInstance(`${i}-handJoint-${t}`);if(null===(n=e.jointMeshes)||void 0===n?void 0:n.onHandJointMeshGenerated){let s=e.jointMeshes.onHandJointMeshGenerated(r,t,i);s&&s!==r&&(r.dispose(),r=s)}if(r.isPickable=!1,null===(a=e.jointMeshes)||void 0===a?void 0:a.enablePhysics){let t=(null===(o=e.jointMeshes)||void 0===o?void 0:o.physicsProps)||{};r.scaling.setAll(.02);let i=void 0!==t.impostorType?t.impostorType:physicsImpostor_PhysicsImpostor.SphereImpostor;r.physicsImpostor=new physicsImpostor_PhysicsImpostor(r,i,Object.assign({mass:0},t))}r.rotationQuaternion=new rm._f,r.isVisible=!1,l.push(r)}t[i]=l}),{left:t.left,right:t.right}}static _GenerateDefaultHandMeshesAsync(e,t){return new Promise(async i=>{var r,s,n,a,o;let l={};(null===(s=null===(r=WebXRHandTracking._RightHandGLB)||void 0===r?void 0:r.meshes[1])||void 0===s?void 0:s.isDisposed())&&(WebXRHandTracking._RightHandGLB=null),(null===(a=null===(n=WebXRHandTracking._LeftHandGLB)||void 0===n?void 0:n.meshes[1])||void 0===a?void 0:a.isDisposed())&&(WebXRHandTracking._LeftHandGLB=null);let h=!!(WebXRHandTracking._RightHandGLB&&WebXRHandTracking._LeftHandGLB),u=await Promise.all([WebXRHandTracking._RightHandGLB||sceneLoader_SceneLoader.ImportMeshAsync("",WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL,WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),WebXRHandTracking._LeftHandGLB||sceneLoader_SceneLoader.ImportMeshAsync("",WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL,WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);WebXRHandTracking._RightHandGLB=u[0],WebXRHandTracking._LeftHandGLB=u[1];let c=new NodeMaterial("handShader",e,{emitComments:!1});await c.loadAsync(WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL),c.needDepthPrePass=!0,c.transparencyMode=sr.F.MATERIAL_ALPHABLEND,c.alphaMode=2,c.build(!1);let d=Object.assign({base:rg.Wo.FromInts(116,63,203),fresnel:rg.Wo.FromInts(149,102,229),fingerColor:rg.Wo.FromInts(177,130,255),tipFresnel:rg.Wo.FromInts(220,200,255)},null===(o=null==t?void 0:t.handMeshes)||void 0===o?void 0:o.customColors),p={base:c.getBlockByName("baseColor"),fresnel:c.getBlockByName("fresnelColor"),fingerColor:c.getBlockByName("fingerColor"),tipFresnel:c.getBlockByName("tipFresnelColor")};p.base.value=d.base,p.fresnel.value=d.fresnel,p.fingerColor.value=d.fingerColor,p.tipFresnel.value=d.tipFresnel,["left","right"].forEach(t=>{let i="left"==t?WebXRHandTracking._LeftHandGLB:WebXRHandTracking._RightHandGLB;if(!i)throw Error("Could not load hand model");let r=i.meshes[1];r._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,r.material=c.clone(`${t}HandShaderClone`,!0),r.isVisible=!1,l[t]=r,h||e.useRightHandedSystem||i.meshes[1].rotate(rL.RD.Y,Math.PI)}),c.dispose(),i({left:l.left,right:l.right})})}static _GenerateDefaultHandMeshRigMapping(e){let t="right"==e?"R":"L";return{[tR.WRIST]:`wrist_${t}`,[tR.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[tR.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[tR.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[tR.THUMB_TIP]:`thumb_tip_${t}`,[tR.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[tR.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[tR.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[tR.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[tR.INDEX_FINGER_TIP]:`index_tip_${t}`,[tR.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[tR.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[tR.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[tR.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[tR.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[tR.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[tR.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[tR.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[tR.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[tR.RING_FINGER_TIP]:`ring_tip_${t}`,[tR.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[tR.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[tR.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[tR.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[tR.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 rf.y$,this.onHandRemovedObservable=new rf.y$,this._attachHand=e=>{var t,i,r;if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;let s=e.inputSource.handedness,n=new WebXRHand(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===(r=this.options.jointMeshes)||void 0===r?void 0:r.scaleFactor);this._attachedHands[e.uniqueId]=n,this._trackingHands[s]=n,this.onHandAddedObservable.notifyObservers(n)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";let 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||{};let e={},r={};[[i.rigMapping.left,e],[i.rigMapping.right,r]].forEach(e=>{let t=e[0],i=e[1];t.forEach((e,t)=>{i[sR[t]]=e})}),t.handMeshes.customRigMappings={left:e,right:r}}}attach(){var e,t,i,r;return!!super.attach()&&(this._handResources={jointMeshes:WebXRHandTracking._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===(r=this.options.handMeshes)||void 0===r?void 0:r.disableDefaultMeshes)||WebXRHandTracking._GenerateDefaultHandMeshesAsync(rS.l.LastCreatedScene,this.options).then(e=>{var t,i;this._handResources.handMeshes=e,this._handResources.rigMappings={left:WebXRHandTracking._GenerateDefaultHandMeshRigMapping("left"),right:WebXRHandTracking._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;let i=this.getHandByControllerId(e);if(i){let r="left"==i.xrController.inputSource.handedness?"left":"right";(null===(t=this._trackingHands[r])||void 0===t?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[r]=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(),WebXRHandTracking._RightHandGLB=null,WebXRHandTracking._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(e=>e.dispose()),this._handResources.jointMeshes.right.forEach(e=>e.dispose()))}};WebXRHandTracking.Name=webXRFeaturesManager_WebXRFeatureName.HAND_TRACKING,WebXRHandTracking.Version=1,WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",WebXRHandTracking._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},WebXRHandTracking._RightHandGLB=null,WebXRHandTracking._LeftHandGLB=null,WebXRFeaturesManager.AddWebXRFeature(WebXRHandTracking.Name,(e,t)=>()=>new WebXRHandTracking(e,t),WebXRHandTracking.Version,!1),(S=tA||(tA={}))[S.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",S[S.RADIAL_SIDE=1]="RADIAL_SIDE",S[S.ULNAR_SIDE=2]="ULNAR_SIDE",S[S.BELOW_WRIST=3]="BELOW_WRIST",(C=tI||(tI={}))[C.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",C[C.HAND_ROTATION=1]="HAND_ROTATION",(E=tM||(tM={}))[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";let BoneIKController=class BoneIKController{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=rm.P.Zero(),this.poleTargetPosition=rm.P.Zero(),this.poleTargetLocalOffset=rm.P.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=rm._f.Identity(),this._bone1Mat=rm.y3.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=rm.P.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;let r=t.getParent();if(!r){this._notEnoughInformation=!0,rT.Y.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=r,0===this._bone2.children.length&&!this._bone2.length){this._notEnoughInformation=!0,rT.Y.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");return}this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();let 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){let 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);let t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone2Length=rm.P.Distance(t,i),this._bone1Length=rm.P.Distance(i,r)}else{e.computeWorldMatrix(!0);let t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;let i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone1Length=rm.P.Distance(i,r)}this._bone1.getRotationMatrixToRef(rL.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||void 0==e)&&(e=Math.PI),this._maxAngle=e;let 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;let e=this.targetPosition,t=this.poleTargetPosition,i=BoneIKController._TmpMats[0],r=BoneIKController._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&rm.P.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);let s=BoneIKController._TmpVecs[0],n=BoneIKController._TmpVecs[1],a=BoneIKController._TmpVecs[2],o=BoneIKController._TmpVecs[3],l=BoneIKController._TmpVecs[4],h=BoneIKController._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(s,o),o.normalize(),rm.P.CrossToRef(o,l,n),n.normalize(),rm.P.CrossToRef(o,n,a),a.normalize(),rm.y3.FromXYZAxesToRef(a,o,n,i);let u=this._bone1Length,c=this._bone2Length,d=rm.P.Distance(s,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let p=(c*c+d*d-u*u)/(2*c*d),_=(d*d+u*u-c*c)/(2*d*u);p>1&&(p=1),_>1&&(_=1),p<-1&&(p=-1),_<-1&&(_=-1);let f=Math.acos(p),m=Math.acos(_),g=-f-m;if(this._rightHandedSystem)rm.y3.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),rm.y3.RotationAxisToRef(this._bendAxis,m,r),r.multiplyToRef(i,i);else{let e=BoneIKController._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,rm.y3.RotationAxisToRef(e,-m,r),r.multiplyToRef(i,i)}this.poleAngle&&(rm.y3.RotationAxisToRef(o,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||rm._f.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),rm._f.FromRotationMatrixToRef(i,h),rm._f.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,rL.T.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,rL.T.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,rL.T.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new rm._f),e.getRotationQuaternionToRef(rL.T.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}};BoneIKController._TmpVecs=[rm.P.Zero(),rm.P.Zero(),rm.P.Zero(),rm.P.Zero(),rm.P.Zero(),rm.P.Zero()],BoneIKController._TmpQuat=rm._f.Identity(),BoneIKController._TmpMats=[rm.y3.Identity(),rm.y3.Identity()];let BoneLookController=class BoneLookController{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=rm.P.Up(),this.upAxisSpace=rL.T.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=rm._f.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=rm.P.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),null!=r.maxYaw?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,null!=r.minYaw?this.minYaw=r.minYaw:this.minYaw=-Math.PI,null!=r.maxPitch?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,null!=r.minPitch?this.minPitch=r.minPitch:this.minPitch=-Math.PI,null!=r.slerpAmount&&(this.slerpAmount=r.slerpAmount),null!=r.upAxis&&(this.upAxis=r.upAxis),null!=r.upAxisSpace&&(this.upAxisSpace=r.upAxisSpace),null!=r.yawAxis||null!=r.pitchAxis){let e=rL.RD.Y,t=rL.RD.X;null!=r.yawAxis&&(e=r.yawAxis.clone()).normalize(),null!=r.pitchAxis&&(t=r.pitchAxis.clone()).normalize();let i=rm.P.Cross(t,e);this._transformYawPitch=rm.y3.Identity(),rm.y3.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==r.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=rL.T.BONE||(this.upAxisSpace=rL.T.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped){this._firstFrameSkipped=!0;return}let e=this.bone,t=BoneLookController._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target,r=BoneLookController._TmpMats[0],s=BoneLookController._TmpMats[1],n=this.mesh,a=e.getParent(),o=BoneLookController._TmpVecs[1];o.copyFrom(this.upAxis),this.upAxisSpace==rL.T.BONE&&a?(this._transformYawPitch&&rm.P.TransformCoordinatesToRef(o,this._transformYawPitchInv,o),a.getDirectionToRef(o,this.mesh,o)):this.upAxisSpace==rL.T.LOCAL&&(n.getDirectionToRef(o,o),(1!=n.scaling.x||1!=n.scaling.y||1!=n.scaling.z)&&o.normalize());let l=!1,h=!1;if((this._maxYaw!=Math.PI||this._minYaw!=-Math.PI)&&(l=!0),(this._maxPitch!=Math.PI||this._minPitch!=-Math.PI)&&(h=!0),l||h){let e=BoneLookController._TmpMats[2],r=BoneLookController._TmpMats[3];if(this.upAxisSpace==rL.T.BONE&&1==o.y&&a)a.getRotationMatrixToRef(rL.T.WORLD,this.mesh,e);else if(this.upAxisSpace!=rL.T.LOCAL||1!=o.y||a){let t=BoneLookController._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&rm.P.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),a?a.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);let i=rm.P.Cross(o,t);i.normalize(),t=rm.P.Cross(i,o),rm.y3.FromXYZAxesToRef(i,o,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(r);let s=null;if(h){let n=BoneLookController._TmpVecs[3];i.subtractToRef(t,n),rm.P.TransformCoordinatesToRef(n,r,n),s=Math.sqrt(n.x*n.x+n.z*n.z);let a=Math.atan2(n.y,s),o=a;a>this._maxPitch?(n.y=this._maxPitchTan*s,o=this._maxPitch):a<this._minPitch&&(n.y=this._minPitchTan*s,o=this._minPitch),a!=o&&(rm.P.TransformCoordinatesToRef(n,e,n),n.addInPlace(t),i=n)}if(l){let n=BoneLookController._TmpVecs[4];i.subtractToRef(t,n),rm.P.TransformCoordinatesToRef(n,r,n);let a=Math.atan2(n.x,n.z),o=this.useAbsoluteValueForYaw?Math.abs(a):a,l=a;if((o>this._maxYaw||o<this._minYaw)&&(null==s&&(s=Math.sqrt(n.x*n.x+n.z*n.z)),this._yawRange>Math.PI?this._isAngleBetween(a,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,l=this._maxYaw):this._isAngleBetween(a,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*s,n.x=this._minYawSin*s,l=this._minYaw):o>this._maxYaw?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,a<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):o<this._minYaw&&(n.z=this._minYawCos*s,n.x=this._minYawSin*s,a<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._minYaw)),this._slerping&&this._yawRange>Math.PI){let e=BoneLookController._TmpVecs[8];e.copyFrom(rL.RD.Z),this._transformYawPitch&&rm.P.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);let t=BoneLookController._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),rm.P.TransformCoordinatesToRef(e,t,e),rm.P.TransformCoordinatesToRef(e,r,e);let i=Math.atan2(e.x,e.z),o=this._getAngleBetween(i,a),h=this._getAngleBetween(i,this._midYawConstraint);if(o>h){null==s&&(s=Math.sqrt(n.x*n.x+n.z*n.z));let e=this._getAngleBetween(i,this._maxYaw),t=this._getAngleBetween(i,this._minYaw);l=t<e?i+.75*Math.PI:i-.75*Math.PI,n.z=Math.cos(l)*s,n.x=Math.sin(l)*s}}a!=l&&(rm.P.TransformCoordinatesToRef(n,e,n),n.addInPlace(t),i=n)}}let u=BoneLookController._TmpVecs[5],c=BoneLookController._TmpVecs[6],d=BoneLookController._TmpVecs[7],p=BoneLookController._TmpQuat;i.subtractToRef(t,u),u.normalize(),rm.P.CrossToRef(o,u,c),c.normalize(),rm.P.CrossToRef(u,c,d),d.normalize(),rm.y3.FromXYZAxesToRef(c,d,u,r),(0!==c.x||0!==c.y||0!==c.z)&&(0!==d.x||0!==d.y||0!==d.z)&&(0!==u.x||0!==u.y||0!==u.z)&&((this.adjustYaw||this.adjustPitch||this.adjustRoll)&&(rm.y3.RotationYawPitchRollToRef(this.adjustYaw,this.adjustPitch,this.adjustRoll,s),s.multiplyToRef(r,r)),this.slerpAmount<1?(this._slerping||this.bone.getRotationQuaternionToRef(rL.T.WORLD,this.mesh,this._boneQuat),this._transformYawPitch&&this._transformYawPitch.multiplyToRef(r,r),rm._f.FromRotationMatrixToRef(r,p),rm._f.SlerpToRef(this._boneQuat,p,this.slerpAmount,this._boneQuat),this.bone.setRotationQuaternion(this._boneQuat,rL.T.WORLD,this.mesh),this._slerping=!0):(this._transformYawPitch&&this._transformYawPitch.multiplyToRef(r,r),this.bone.setRotationMatrix(r,rL.T.WORLD,this.mesh),this._slerping=!1),this._updateLinkedTransformRotation())}_getAngleDiff(e,t){let i=t-e;return(i%=2*Math.PI)>Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI;let i=0;return(i=e<(t=t<0?t+2*Math.PI:t)?t-e:e-t)>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,t<(i=i<0?i+2*Math.PI:i)){if(e>t&&e<i)return!0}else if(e>i&&e<t)return!0;return!1}_updateLinkedTransformRotation(){let e=this.bone;e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new rm._f),e.getRotationQuaternionToRef(rL.T.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}};BoneLookController._TmpVecs=rB.B.BuildArray(10,rm.P.Zero),BoneLookController._TmpQuat=rm._f.Identity(),BoneLookController._TmpMats=rB.B.BuildArray(5,rm.y3.Identity);let skeleton_Skeleton=class skeleton_Skeleton{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=[],this._identity=rm.y3.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new rf.y$,this.bones=[],this._scene=i||rS.l.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;let r=this._scene.getEngine().getCaps();this._canUseTextureForBones=r.textureFloat&&r.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){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(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return -1}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=new AnimationRange(e,t,i);for(let r=0,s=this.bones.length;r<s;r++)this.bones[r].animations[0]&&this.bones[r].animations[0].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,r=this.bones.length;i<r;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}getAnimationRanges(){let e;let t=[];for(e in this._ranges)t.push(this._ranges[e]);return t}copyAnimationRange(e,t,i=!1){let r,s;if(this._ranges[t]||!e.getAnimationRange(t))return!1;let n=!0,a=this._getHighestAnimationFrame()+1,o={},l=e.bones;for(s=0,r=l.length;s<r;s++)o[l[s].name]=l[s];this.bones.length!==l.length&&(rT.Y.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${l.length}`),n=!1);let h=i&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(s=0,r=this.bones.length;s<r;s++){let e=this.bones[s].name,r=o[e];r?n=n&&this.bones[s].copyAnimationRange(r,t,a,i,h):(rT.Y.Warn("copyAnimationRange: not same rig, missing source bone "+e),n=!1)}let u=e.getAnimationRange(t);return u&&(this._ranges[t]=new AnimationRange(t,u.from+a,u.to+a)),n}returnToRest(){for(let e of this.bones)-1!==e._index&&e.returnToRest()}_getHighestAnimationFrame(){let e=0;for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){let i=this.bones[t].animations[0].getHighestFrame();e<i&&(e=i)}return e}beginAnimation(e,t,i,r){let s=this.getAnimationRange(e);return s?this._scene.beginAnimation(this,s.from,s.to,t,i,r):null}static MakeAnimationAdditive(e,t=0,i){let r=e.getAnimationRange(i);if(!r)return null;let s=e._scene.getAllAnimatablesByTarget(e),n=null;for(let e=0;e<s.length;e++){let t=s[e];if(t.fromFrame===(null==r?void 0:r.from)&&t.toFrame===(null==r?void 0:r.to)){n=t;break}}let a=e.getAnimatables();for(let e=0;e<a.length;e++){let r=a[e],s=r.animations;if(s)for(let e=0;e<s.length;e++)animation_Animation.MakeAnimationAdditive(s[e],t,i)}return n&&(n.isAdditive=!0),e}_markAsDirty(){this._isDirty=!0,this._absoluteTransformIsDirty=!0}_registerMeshWithPoseMatrix(e){this._meshesWithPoseMatrix.push(e)}_unregisterMeshWithPoseMatrix(e){let t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i<this.bones.length;i++){let r=this.bones[i];r._childUpdateId++;let s=r.getParent();if(s?r.getLocalMatrix().multiplyToRef(s.getFinalMatrix(),r.getFinalMatrix()):t?r.getLocalMatrix().multiplyToRef(t,r.getFinalMatrix()):r.getFinalMatrix().copyFrom(r.getLocalMatrix()),-1!==r._index){let t=null===r._index?i:r._index;r.getAbsoluteInverseBindMatrix().multiplyToArray(r.getFinalMatrix(),e,16*t)}}this._identity.copyToArray(e,16*this.bones.length)}prepare(e=!1){if(!e){let e=this.getScene().getRenderId();if(this._currentRenderId===e)return;this._currentRenderId=e}if(this._numBonesWithLinkedTransformNode>0){for(let e of this.bones)if(e._linkedTransformNode){let 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(let e of this._meshesWithPoseMatrix){let t=e.getPoseMatrix(),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){for(let i of(this._synchronizedWithMesh=e,this.bones))if(!i.getParent()){let e=i.getBindMatrix();e.multiplyToRef(t,rm.jp.Matrix[1]),i._updateAbsoluteBindMatrices(rm.jp.Matrix[1])}if(this.isUsingTextureForMatrices){let t=(this.bones.length+1)*4;e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=rawTexture_RawTexture.CreateRGBATexture(e._bonesTransformMatrices,(this.bones.length+1)*4,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=rawTexture_RawTexture.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables}clone(e,t){let i=new skeleton_Skeleton(e,t||e,this._scene);i.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let e=0;e<this.bones.length;e++){let t=this.bones[e],r=null,s=t.getParent();if(s){let e=this.bones.indexOf(s);r=i.bones[e]}let n=new Bone(t.name,i,r,t.getBindMatrix().clone(),t.getRestMatrix().clone());n._index=t._index,t._linkedTransformNode&&n.linkTransformNode(t._linkedTransformNode),rC.j.DeepCopy(t.animations,n.animations)}if(this._ranges)for(let e in i._ranges={},this._ranges){let t=this._ranges[e];t&&(i._ranges[e]=t.clone())}return this._isDirty=!0,i.prepare(!0),i}enableBlending(e=.01){this.bones.forEach(t=>{t.animations.forEach(t=>{t.enableBlending=!0,t.blendingSpeed=e})})}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){let 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;let 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;i<this.bones.length;i++){let r=this.bones[i],s=r.getParent(),n={parentBoneIndex:s?this.bones.indexOf(s):-1,index:r.getIndex(),name:r.name,id:r.id,matrix:r.getBindMatrix().toArray(),rest:r.getRestMatrix().toArray(),linkedTransformNodeId:null===(e=r.getTransformNode())||void 0===e?void 0:e.id};for(let e in t.bones.push(n),r.length&&(n.length=r.length),r.metadata&&(n.metadata=r.metadata),r.animations&&r.animations.length>0&&(n.animation=r.animations[0].serialize()),t.ranges=[],this._ranges){let i=this._ranges[e];if(!i)continue;let r={};r.name=e,r.from=i.from,r.to=i.to,t.ranges.push(r)}}return t}static Parse(e,t){let i;let r=new skeleton_Skeleton(e.name,e.id,t);for(e.dimensionsAtRest&&(r.dimensionsAtRest=rm.P.FromArray(e.dimensionsAtRest)),r.needInitialSkinMatrix=e.needInitialSkinMatrix,i=0;i<e.bones.length;i++){let t=e.bones[i],s=e.bones[i].index,n=null;t.parentBoneIndex>-1&&(n=r.bones[t.parentBoneIndex]);let a=t.rest?rm.y3.FromArray(t.rest):null,o=new Bone(t.name,r,n,rm.y3.FromArray(t.matrix),a,null,s);void 0!==t.id&&null!==t.id&&(o.id=t.id),t.length&&(o.length=t.length),t.metadata&&(o.metadata=t.metadata),t.animation&&o.animations.push(animation_Animation.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(r._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(i=0;i<e.ranges.length;i++){let t=e.ranges[i];r.createAnimationRange(t.name,t.from,t.to)}return r}computeAbsoluteMatrices(e=!1){(this._absoluteTransformIsDirty||e)&&(this.bones[0].computeAbsoluteMatrices(),this._absoluteTransformIsDirty=!1)}computeAbsoluteTransforms(e=!1){this.computeAbsoluteMatrices(e)}getPoseMatrix(){let e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){let e=[],t=Array(this.bones.length);for(let i=0;i<this.bones.length;i++)this._sortBones(i,e,t);this.bones=e}_sortBones(e,t,i){if(i[e])return;i[e]=!0;let r=this.bones[e];if(!r)return;void 0===r._index&&(r._index=e);let s=r.getParent();s&&this._sortBones(this.bones.indexOf(s),t,i),t.push(r)}setCurrentPoseAsRest(){this.bones.forEach(e=>{e.setCurrentPoseAsRest()})}};var sI=i(9185);let StorageBuffer=class StorageBuffer{constructor(e,t,i=3,r){this._engine=e,this._label=r,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t,this._label)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i){return this._engine.readFromStorageBuffer(this._buffer,e,t,i)}dispose(){let 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}};let sM=(()=>{let e=new Uint8Array(4),t=new Uint32Array(e.buffer);return!!((t[0]=1)&e[0])})();Object.defineProperty(rz.o.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(rz.o.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(rz.o.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),rz.o.prototype._rebuild=function(){var e,t;null===(e=this._buffer)||void 0===e||e._rebuild(),null===(t=this._alignedBuffer)||void 0===t||t._rebuild()},rz.o.prototype.dispose=function(){var e;this._ownsBuffer&&this._buffer.dispose(),null===(e=this._alignedBuffer)||void 0===e||e.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},rz.o.prototype._alignBuffer=function(){var e,t;let i,r;let s=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideMultiple4Bytes||this.byteStride%4==0||!s)return;let n=rz.o.GetTypeByteLength(this.type),a=this.byteStride+3&-4,o=a/n,l=this.totalVertices,h=l*a,u=h/n;if(Array.isArray(s)){let e=new Float32Array(s);i=new DataView(e.buffer,e.byteOffset,e.byteLength)}else i=s instanceof ArrayBuffer?new DataView(s,0,s.byteLength):new DataView(s.buffer,s.byteOffset,s.byteLength);r=this.type===rz.o.BYTE?new Int8Array(u):this.type===rz.o.UNSIGNED_BYTE?new Uint8Array(u):this.type===rz.o.SHORT?new Int16Array(u):this.type===rz.o.UNSIGNED_SHORT?new Uint16Array(u):this.type===rz.o.INT?new Int32Array(u):this.type===rz.o.UNSIGNED_INT?new Uint32Array(u):new Float32Array(u);let c=this.getSize(),d=this.byteOffset;for(let e=0;e<l;++e){for(let t=0;t<c;++t)switch(this.type){case rz.o.BYTE:r[e*o+t]=i.getInt8(d+t);break;case rz.o.UNSIGNED_BYTE:r[e*o+t]=i.getUint8(d+t);break;case rz.o.SHORT:r[e*o+t]=i.getInt16(d+2*t,sM);break;case rz.o.UNSIGNED_SHORT:r[e*o+t]=i.getUint16(d+2*t,sM);break;case rz.o.INT:r[e*o+t]=i.getInt32(d+4*t,sM);break;case rz.o.UNSIGNED_INT:r[e*o+t]=i.getUint32(d+4*t,sM);break;case rz.o.FLOAT:r[e*o+t]=i.getFloat32(d+4*t,sM)}d+=this.byteStride}null===(e=this._alignedBuffer)||void 0===e||e.dispose(),this._alignedBuffer=new rz.l(this.engine,r,!1,a,!1,this.getIsInstanced(),!0,this.instanceDivisor,(null!==(t=this._label)&&void 0!==t?t:"VertexBuffer")+"_aligned")};var sD=i(5294);let BaseCameraMouseWheelInput=class BaseCameraMouseWheelInput{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new rf.y$,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==r8.kD.POINTERWHEEL)return;let i=t.event,r=i.deltaMode===sD.G.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,r8.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,rH.gn)([(0,rb.qC)()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionX",void 0),(0,rH.gn)([(0,rb.qC)()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionY",void 0),(0,rH.gn)([(0,rb.qC)()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionZ",void 0);let BaseCameraPointersInput=class BaseCameraPointersInput{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement(),r=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{var a,o;let l=n.event,h="touch"===l.pointerType;if(n.type!==r8.kD.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;let u=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){let e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else if(n.type!==r8.kD.POINTERDOWN&&h&&(null===(a=this._pointA)||void 0===a?void 0:a.pointerId)!==l.pointerId&&(null===(o=this._pointB)||void 0===o?void 0:o.pointerId)!==l.pointerId)return;else if(n.type===r8.kD.POINTERDOWN&&(-1===this._currentActiveButton||h)){try{null==u||u.setPointerCapture(l.pointerId)}catch(e){}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())}else if(n.type===r8.kD.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(n.type===r8.kD.POINTERUP&&(this._currentActiveButton===l.button||h)){try{null==u||u.releasePointerCapture(l.pointerId)}catch(e){}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!==r||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(n.type===r8.kD.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&null===this._pointB){let 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){let e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;let t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,o={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,r,a,s,o),s=o,r=a}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,r8.kD.POINTERDOWN|r8.kD.POINTERUP|r8.kD.POINTERMOVE|r8.kD.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);let n=this.camera.getScene().getEngine().getHostWindow();n&&rW.w1.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){let e=this.camera.getScene().getEngine().getHostWindow();e&&rW.w1.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){let e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,r,s,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}};(0,rH.gn)([(0,rb.qC)()],BaseCameraPointersInput.prototype,"buttons",void 0);var sO={};let CameraInputsManager=class CameraInputsManager{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){let t=e.getSimpleName();if(this.attached[t]){rT.Y.Warn("camera input of type "+t+" already exists on camera");return}this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault)}remove(e){for(let t in this.attached){let i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(let t in this.attached){let i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){let t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement)for(let t in e=!rj.V.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e,this.attached)this.attached[t].attachControl(e)}detachElement(e=!1){for(let t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){for(let e in this.checkInputs=()=>{},this.attached){let 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){let t={};for(let e in this.attached){let i=this.attached[e],r=rb.p4.Serialize(i);t[i.getClassName()]=r}e.inputsmgr=t}parse(e){let t=e.inputsmgr;if(t)for(let e in this.clear(),t){let i=sO[e];if(i){let r=t[e],s=rb.p4.Parse(()=>new i,r,null);this.add(s)}}else for(let t in this.attached){let i=sO[this.attached[t].getClassName()];if(i){let r=rb.p4.Parse(()=>new i,e,null);this.remove(this.attached[t]),this.add(r)}}}};let Gamepad=class Gamepad{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,s=1,n=2,a=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=Gamepad.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=s,this._rightStickAxisX=n,this._rightStickAxisY=a,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(){}};Gamepad.GAMEPAD=0,Gamepad.GENERIC=1,Gamepad.XBOX=2,Gamepad.POSE_ENABLED=3,Gamepad.DUALSHOCK=4;let GenericPad=class GenericPad extends Gamepad{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new rf.y$,this.onButtonUpObservable=new rf.y$,this.type=Gamepad.GENERIC,this._buttons=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<this._buttons.length;e++)this._buttons[e]=this._setButtonValue(this.browserGamepad.buttons[e].value,this._buttons[e],e)}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear()}};let ArcRotateCameraGamepadInput=class ArcRotateCameraGamepadInput{constructor(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40,this._yAxisScale=1}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){let e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{e.type===Gamepad.POSE_ENABLED||this.gamepad&&e.type!==Gamepad.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Gamepad.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){let e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){let i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){let i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}let i=this.gamepad.leftStick;if(i&&0!=i.y){let e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}};(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraGamepadInput.prototype,"gamepadRotationSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraGamepadInput.prototype,"gamepadMoveSensibility",void 0),sO.ArcRotateCameraGamepadInput=ArcRotateCameraGamepadInput;var sN=i(7534);let ArcRotateCameraKeyboardMoveInput=class ArcRotateCameraKeyboardMoveInput{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=[]}attachControl(e){e=rW.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=>{let i=t.event;if(!i.metaKey){if(t.type===sN.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t];-1!==this.keysLeft.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:-1!==this.keysUp.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:-1!==this.keysRight.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:-1!==this.keysDown.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:-1!==this.keysReset.indexOf(i)&&e.useInputToRestoreState&&e.restoreState()}}}getClassName(){return"ArcRotateCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}};(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraKeyboardMoveInput.prototype,"keysUp",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraKeyboardMoveInput.prototype,"keysDown",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraKeyboardMoveInput.prototype,"keysLeft",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraKeyboardMoveInput.prototype,"keysRight",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraKeyboardMoveInput.prototype,"keysReset",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraKeyboardMoveInput.prototype,"panningSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraKeyboardMoveInput.prototype,"zoomingSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraKeyboardMoveInput.prototype,"useAltToZoom",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraKeyboardMoveInput.prototype,"angularSpeed",void 0),sO.ArcRotateCameraKeyboardMoveInput=ArcRotateCameraKeyboardMoveInput;let ArcRotateCameraMouseWheelInput=class ArcRotateCameraMouseWheelInput{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._viewOffset=new rm.P(0,0,0),this._globalOffset=new rm.P(0,0,0),this._inertialPanning=rm.P.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let i=.01*e*this.wheelDeltaPercentage*t;return e>0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage)}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==r8.kD.POINTERWHEEL)return;let i=t.event,r=0,s=i.deltaMode===sD.G.DOM_DELTA_LINE?40:1,n=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if((r=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius))>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+r;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=rE.R.Clamp(e,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else r=n/(40*this.wheelPrecision);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,r8.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;let e=this.camera,t=0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset;t&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){let e=this.camera,t=e.target.subtract(e.position);this._hitPlane=r2.J.FromPositionAndNormal(e.target,t)}_getPosition(){var e;let t=this.camera,i=t.getScene(),r=i.createPickingRay(i.pointerX,i.pointerY,rm.y3.Identity(),t,!1);(0!==t.targetScreenOffset.x||0!==t.targetScreenOffset.y)&&(this._viewOffset.set(t.targetScreenOffset.x,t.targetScreenOffset.y,0),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),this._globalOffset=rm.P.TransformNormal(this._viewOffset,t._cameraTransformMatrix),r.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=null!==(e=r.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),r.origin.addInPlace(r.direction.scaleInPlace(s))}_zoomToMouse(e){var t,i;let r=this.camera,s=1-r.inertia;if(r.lowerRadiusLimit){let i=null!==(t=r.lowerRadiusLimit)&&void 0!==t?t:0;r.radius-(r.inertialRadiusOffset+e)/s<i&&(e=(r.radius-i)*s-r.inertialRadiusOffset)}if(r.upperRadiusLimit){let t=null!==(i=r.upperRadiusLimit)&&void 0!==i?i:0;r.radius-(r.inertialRadiusOffset+e)/s>t&&(e=(r.radius-t)*s-r.inertialRadiusOffset)}let n=e/s,a=n/r.radius,o=this._getPosition(),l=rm.jp.Vector3[6];o.subtractToRef(r.target,l),l.scaleInPlace(a),l.scaleInPlace(s),this._inertialPanning.addInPlace(l),r.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)<rw.kn&&(e.x=0),Math.abs(e.y)<rw.kn&&(e.y=0),Math.abs(e.z)<rw.kn&&(e.z=0)}};(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraMouseWheelInput.prototype,"wheelPrecision",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraMouseWheelInput.prototype,"zoomToMouseLocation",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraMouseWheelInput.prototype,"wheelDeltaPercentage",void 0),sO.ArcRotateCameraMouseWheelInput=ArcRotateCameraMouseWheelInput;let ArcRotateCameraPointersInput=class ArcRotateCameraPointersInput extends BaseCameraPointersInput{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.pinchZoom=!0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this.pinchInwards=!0,this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(0!==this.panningSensibility&&e&&t){let i=t.x-e.x,r=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=r/this.panningSensibility}}_computePinchZoom(e,t){let i=this.camera.radius||ArcRotateCameraPointersInput.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,r,s,n){(0!==i||null!==s)&&(0!==r||null!==n)&&(this.multiTouchPanAndZoom?(this._computePinchZoom(i,r),this._computeMultiTouchPanning(s,n)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(r)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,n)):this.multiTouchPanning?this._computeMultiTouchPanning(s,n):this.pinchZoom&&this._computePinchZoom(i,r))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}};ArcRotateCameraPointersInput.MinimumRadiusForPinch=.001,(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"buttons",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"angularSensibilityX",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"angularSensibilityY",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"pinchPrecision",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"pinchDeltaPercentage",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"useNaturalPinchZoom",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"pinchZoom",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"panningSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"multiTouchPanning",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"multiTouchPanAndZoom",void 0),sO.ArcRotateCameraPointersInput=ArcRotateCameraPointersInput;let ArcRotateCameraInputsManager=class ArcRotateCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addMouseWheel(){return this.add(new ArcRotateCameraMouseWheelInput),this}addPointers(){return this.add(new ArcRotateCameraPointersInput),this}addKeyboard(){return this.add(new ArcRotateCameraKeyboardMoveInput),this}};ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation=function(){return this.add(new ArcRotateCameraVRDeviceOrientationInput),this};let ArcRotateCameraVRDeviceOrientationInput=class ArcRotateCameraVRDeviceOrientationInput{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);let 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):rW.w1.Warn("Permission not granted.")}).catch(e=>{rW.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"}};sO.ArcRotateCameraVRDeviceOrientationInput=ArcRotateCameraVRDeviceOrientationInput;let FlyCameraKeyboardInput=class FlyCameraKeyboardInput{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=[]}attachControl(e){e=rW.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=>{let i=t.event;if(t.type===sN.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=e._computeLocalCameraSpeed();-1!==this.keysForward.indexOf(i)?e._localDirection.copyFromFloats(0,0,r):-1!==this.keysBackward.indexOf(i)?e._localDirection.copyFromFloats(0,0,-r):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,r,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,-r,0):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(r,0,0):-1!==this.keysLeft.indexOf(i)&&e._localDirection.copyFromFloats(-r,0,0),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),rm.P.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}};(0,rH.gn)([(0,rb.qC)()],FlyCameraKeyboardInput.prototype,"keysForward",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCameraKeyboardInput.prototype,"keysBackward",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCameraKeyboardInput.prototype,"keysUp",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCameraKeyboardInput.prototype,"keysDown",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCameraKeyboardInput.prototype,"keysRight",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCameraKeyboardInput.prototype,"keysLeft",void 0),sO.FlyCameraKeyboardInput=FlyCameraKeyboardInput;let FlyCameraMouseInput=class FlyCameraMouseInput{constructor(){this.buttons=[0,1,2],this.buttonsYaw=[-1,0,1],this.buttonsPitch=[-1,0,1],this.buttonsRoll=[2],this.activeButton=-1,this.angularSensibility=1e3,this._previousPosition=null}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments),this._noPreventDefault=e,this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(e=>{this._pointerInput(e)},r8.kD.POINTERDOWN|r8.kD.POINTERUP|r8.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){let t=e.event,i=this.camera,r=i.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType||e.type!==r8.kD.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;let s=t.target;if(e.type===r8.kD.POINTERDOWN){try{null==s||s.setPointerCapture(t.pointerId)}catch(e){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),r.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===r8.kD.POINTERUP){try{null==s||s.releasePointerCapture(t.pointerId)}catch(e){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===r8.kD.POINTERMOVE){if(!this._previousPosition){r.isPointerLock&&this._onMouseMove(e.event);return}let i=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(i,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){let t=this.camera,i=t.getEngine();if(!i.isPointerLock)return;let r=e.movementX,s=e.movementY;this._rotateCamera(r,s),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){let i;let r=this.camera,s=r._calculateHandednessMultiplier();e*=s;let n=e/this.angularSensibility,a=t/this.angularSensibility,o=rm._f.RotationYawPitchRoll(r.rotation.y,r.rotation.x,r.rotation.z);if(this.buttonsPitch.some(e=>e===this.activeButton)&&(i=rm._f.RotationAxis(rL.RD.X,a),o.multiplyInPlace(i)),this.buttonsYaw.some(e=>e===this.activeButton)){i=rm._f.RotationAxis(rL.RD.Y,n),o.multiplyInPlace(i);let e=r.bankedTurnLimit+r._trackRoll;if(r.bankedTurn&&-e<r.rotation.z&&r.rotation.z<e){let e=-(r.bankedTurnMultiplier*n);i=rm._f.RotationAxis(rL.RD.Z,e),o.multiplyInPlace(i)}}this.buttonsRoll.some(e=>e===this.activeButton)&&(i=rm._f.RotationAxis(rL.RD.Z,-n),r._trackRoll-=n,o.multiplyInPlace(i)),o.toEulerAnglesToRef(r.rotation)}};(0,rH.gn)([(0,rb.qC)()],FlyCameraMouseInput.prototype,"buttons",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCameraMouseInput.prototype,"angularSensibility",void 0),sO.FlyCameraMouseInput=FlyCameraMouseInput;let FollowCameraKeyboardMoveInput=class FollowCameraKeyboardMoveInput{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=[]}attachControl(e){e=rW.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=>{let i=t.event;if(!i.metaKey){if(t.type===sN.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetIncr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetDecr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierAlt",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierCtrl",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierShift",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetIncr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetDecr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierAlt",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierCtrl",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierShift",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusIncr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusDecr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierAlt",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierCtrl",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierShift",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"heightSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"rotationSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"radiusSensibility",void 0),sO.FollowCameraKeyboardMoveInput=FollowCameraKeyboardMoveInput;let FollowCameraMouseWheelInput=class FollowCameraMouseWheelInput{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==r8.kD.POINTERWHEEL)return;let i=t.event,r=0,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?r=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=s*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,r8.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,rH.gn)([(0,rb.qC)()],FollowCameraMouseWheelInput.prototype,"axisControlRadius",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraMouseWheelInput.prototype,"axisControlHeight",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraMouseWheelInput.prototype,"axisControlRotation",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraMouseWheelInput.prototype,"wheelPrecision",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraMouseWheelInput.prototype,"wheelDeltaPercentage",void 0),sO.FollowCameraMouseWheelInput=FollowCameraMouseWheelInput;let FollowCameraPointersInput=class FollowCameraPointersInput extends BaseCameraPointersInput{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,s,n){if(0===i&&null===s||0===r&&null===n)return;let a=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(a*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=a*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=a*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=a*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=a),this.axisPinchControlHeight&&(this.camera.heightOffset+=a),this.axisPinchControlRadius&&(this.camera.radius-=a))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;let 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,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"angularSensibilityX",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"angularSensibilityY",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"pinchPrecision",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"pinchDeltaPercentage",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisXControlRadius",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisXControlHeight",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisXControlRotation",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisYControlRadius",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisYControlHeight",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisYControlRotation",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisPinchControlRadius",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisPinchControlHeight",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisPinchControlRotation",void 0),sO.FollowCameraPointersInput=FollowCameraPointersInput;let FreeCameraKeyboardMoveInput=class FreeCameraKeyboardMoveInput{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=[]}attachControl(e){e=rW.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=>{let i=t.event;if(!i.metaKey){if(t.type===sN.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=e._computeLocalCameraSpeed();-1!==this.keysLeft.indexOf(i)?e._localDirection.copyFromFloats(-r,0,0):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,0,r):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(r,0,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,0,-r):-1!==this.keysUpward.indexOf(i)?e._localDirection.copyFromFloats(0,r,0):-1!==this.keysDownward.indexOf(i)?e._localDirection.copyFromFloats(0,-r,0):-1!==this.keysRotateLeft.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):-1!==this.keysRotateRight.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):-1!==this.keysRotateUp.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):-1!==this.keysRotateDown.indexOf(i)&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),rm.P.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}getClassName(){return"FreeCameraKeyboardMoveInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}_getLocalRotation(){let e=this.camera._calculateHandednessMultiplier(),t=this.rotationSpeed*this._engine.getDeltaTime()/1e3*e;return t}};(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"keysUp",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"keysUpward",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"keysDown",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"keysDownward",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"keysLeft",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"keysRight",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"rotationSpeed",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"keysRotateLeft",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"keysRotateRight",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"keysRotateUp",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraKeyboardMoveInput.prototype,"keysRotateDown",void 0),sO.FreeCameraKeyboardMoveInput=FreeCameraKeyboardMoveInput;let FreeCameraMouseInput=class FreeCameraMouseInput{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new rf.y$,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=r=>{let s=r.event,n="touch"===s.pointerType;if(!this.touchEnabled&&n||r.type!==r8.kD.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;let a=s.target;if(r.type===r8.kD.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==a||a.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},!e&&(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===r8.kD.POINTERUP){if(n&&this._activePointerId!==s.pointerId||!n&&this._currentActiveButton!==s.button)return;try{null==a||a.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===r8.kD.POINTERMOVE&&(this._activePointerId===s.pointerId||!n)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){let t=this.camera._calculateHandednessMultiplier(),i=(s.clientX-this._previousPosition.x)*t,r=s.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=r/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:r}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;let r=this.camera._calculateHandednessMultiplier(),s=i.movementX*r;this.camera.cameraRotation.y+=s/this.angularSensibility;let n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,r8.kD.POINTERDOWN|r8.kD.POINTERUP|r8.kD.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}};(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseInput.prototype,"buttons",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseInput.prototype,"angularSensibility",void 0),sO.FreeCameraMouseInput=FreeCameraMouseInput,(b=tD||(tD={}))[b.MoveRelative=0]="MoveRelative",b[b.RotateRelative=1]="RotateRelative",b[b.MoveScene=2]="MoveScene";let FreeCameraMouseWheelInput=class FreeCameraMouseWheelInput extends BaseCameraMouseWheelInput{constructor(){super(...arguments),this._moveRelative=rm.P.Zero(),this._rotateRelative=rm.P.Zero(),this._moveScene=rm.P.Zero(),this._wheelXAction=tD.MoveRelative,this._wheelXActionCoordinate=rL.c7.X,this._wheelYAction=tD.MoveRelative,this._wheelYActionCoordinate=rL.c7.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){(null!==e||this._wheelXAction===tD.MoveRelative)&&(this._wheelXAction=tD.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==tD.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){(null!==e||this._wheelYAction===tD.MoveRelative)&&(this._wheelYAction=tD.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==tD.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){(null!==e||this._wheelZAction===tD.MoveRelative)&&(this._wheelZAction=tD.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==tD.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){(null!==e||this._wheelXAction===tD.RotateRelative)&&(this._wheelXAction=tD.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==tD.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){(null!==e||this._wheelYAction===tD.RotateRelative)&&(this._wheelYAction=tD.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==tD.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){(null!==e||this._wheelZAction===tD.RotateRelative)&&(this._wheelZAction=tD.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==tD.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){(null!==e||this._wheelXAction===tD.MoveScene)&&(this._wheelXAction=tD.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==tD.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){(null!==e||this._wheelYAction===tD.MoveScene)&&(this._wheelYAction=tD.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==tD.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){(null!==e||this._wheelZAction===tD.MoveScene)&&(this._wheelZAction=tD.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==tD.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);let e=rm.y3.Zero();this.camera.getViewMatrix().invertToRef(e);let t=rm.P.Zero();rm.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||null===t||null===i)return;let r=null;switch(t){case tD.MoveRelative:r=this._moveRelative;break;case tD.RotateRelative:r=this._rotateRelative;break;case tD.MoveScene:r=this._moveScene}switch(i){case rL.c7.X:r.set(e,0,0);break;case rL.c7.Y:r.set(0,e,0);break;case rL.c7.Z:r.set(0,0,e)}}};(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelXMoveRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelYMoveRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelZMoveRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelXRotateRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelYRotateRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelZRotateRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelXMoveScene",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelYMoveScene",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelZMoveScene",null),sO.FreeCameraMouseWheelInput=FreeCameraMouseWheelInput;let FreeCameraTouchInput=class FreeCameraTouchInput{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=[],this._isSafari=rW.w1.IsSafari()}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{let r=i.event,s="mouse"===r.pointerType||this._isSafari&&void 0===r.pointerType;if(this.allowMouse||!s){if(i.type===r8.kD.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),1!==this._pointerPressed.length)return;t={x:r.clientX,y:r.clientY}}else if(i.type===r8.kD.POINTERUP){e||r.preventDefault();let i=this._pointerPressed.indexOf(r.pointerId);if(-1===i||(this._pointerPressed.splice(i,1),0!=i))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===r8.kD.POINTERMOVE){if(e||r.preventDefault(),!t)return;let i=this._pointerPressed.indexOf(r.pointerId);if(0!=i)return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,r8.kD.POINTERDOWN|r8.kD.POINTERUP|r8.kD.POINTERMOVE),this._onLostFocus){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.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||0===this._offsetX&&0===this._offsetY)return;let e=this.camera,t=e._calculateHandednessMultiplier();e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility;let i=this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1;if(i)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{let t=e._computeLocalCameraSpeed(),i=new rm.P(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);rm.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(rm.P.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}};(0,rH.gn)([(0,rb.qC)()],FreeCameraTouchInput.prototype,"touchAngularSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraTouchInput.prototype,"touchMoveSensibility",void 0),sO.FreeCameraTouchInput=FreeCameraTouchInput;let FreeCameraInputsManager=class FreeCameraInputsManager extends CameraInputsManager{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new FreeCameraKeyboardMoveInput),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new FreeCameraMouseInput(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new FreeCameraMouseWheelInput,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new FreeCameraTouchInput),this}clear(){super.clear(),this._mouseInput=null}};FreeCameraInputsManager.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new FreeCameraDeviceOrientationInput,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};let FreeCameraDeviceOrientationInput=class FreeCameraDeviceOrientationInput{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let r=!1,eventHandler=()=>{window.removeEventListener("deviceorientation",eventHandler),r=!0,t()};e&&setTimeout(()=>{r||(window.removeEventListener("deviceorientation",eventHandler),i("WaitForOrientationChangeAsync timed out"))},e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"==e?window.addEventListener("deviceorientation",eventHandler):rW.w1.Warn("Permission not granted.")}).catch(e=>{rW.w1.Error(e)}):window.addEventListener("deviceorientation",eventHandler)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new rm._f,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new rf.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=-rW.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?rW.w1.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?rW.w1.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?rW.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 rm._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 rm._f),this._camera&&this._camera.onDisposeObservable.add(()=>{this._onDeviceOrientationChangedObservable.clear()})}attachControl(){let e=this.camera.getScene().getEngine().getHostWindow();if(e){let eventHandler=()=>{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?eventHandler():rW.w1.Warn("Permission not granted.")}).catch(e=>{rW.w1.Error(e)}):eventHandler()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(rm._f.RotationYawPitchRollToRef(rW.w1.ToRadians(this._alpha),rW.w1.ToRadians(this._beta),-rW.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"}};sO.FreeCameraDeviceOrientationInput=FreeCameraDeviceOrientationInput;let FreeCameraGamepadInput=class FreeCameraGamepadInput{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=rm.y3.Identity(),this._deltaTransform=rm.P.Zero(),this._vector3=rm.P.Zero(),this._vector2=rm.FM.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){let e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{e.type===Gamepad.POSE_ENABLED||this.gamepad&&e.type!==Gamepad.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Gamepad.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){let 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):rm.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);let r=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*r,0,-t.y*r),rm.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,rH.gn)([(0,rb.qC)()],FreeCameraGamepadInput.prototype,"gamepadAngularSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraGamepadInput.prototype,"gamepadMoveSensibility",void 0),sO.FreeCameraGamepadInput=FreeCameraGamepadInput;var sF=i(1186);(y=tO||(tO={}))[y.X=0]="X",y[y.Y=1]="Y",y[y.Z=2]="Z";let VirtualJoystick=class VirtualJoystick{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;let i=Object.assign(Object.assign({},VirtualJoystick._GetDefaultOptions()),t);if(e?this._leftJoystick=!0:this._leftJoystick=!1,VirtualJoystick._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=tO.X,this._axisTargetedByUpAndDown=tO.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new sF.x,this.deltaPosition=rm.P.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{VirtualJoystick._VJCanvasWidth=window.innerWidth,VirtualJoystick._VJCanvasHeight=window.innerHeight,VirtualJoystick.Canvas&&(VirtualJoystick.Canvas.width=VirtualJoystick._VJCanvasWidth,VirtualJoystick.Canvas.height=VirtualJoystick._VJCanvasHeight),VirtualJoystick._HalfWidth=VirtualJoystick._VJCanvasWidth/2},!VirtualJoystick.Canvas){window.addEventListener("resize",this._onResize,!1),VirtualJoystick.Canvas=document.createElement("canvas"),VirtualJoystick._VJCanvasWidth=window.innerWidth,VirtualJoystick._VJCanvasHeight=window.innerHeight,VirtualJoystick.Canvas.width=window.innerWidth,VirtualJoystick.Canvas.height=window.innerHeight,VirtualJoystick.Canvas.style.width="100%",VirtualJoystick.Canvas.style.height="100%",VirtualJoystick.Canvas.style.position="absolute",VirtualJoystick.Canvas.style.backgroundColor="transparent",VirtualJoystick.Canvas.style.top="0px",VirtualJoystick.Canvas.style.left="0px",VirtualJoystick.Canvas.style.zIndex="5",VirtualJoystick.Canvas.style.touchAction="none",VirtualJoystick.Canvas.setAttribute("touch-action","none");let e=VirtualJoystick.Canvas.getContext("2d");if(!e)throw Error("Unable to create canvas for virtual joystick");VirtualJoystick._VJCanvasContext=e,VirtualJoystick._VJCanvasContext.strokeStyle="#ffffff",VirtualJoystick._VJCanvasContext.lineWidth=2,document.body.appendChild(VirtualJoystick.Canvas)}VirtualJoystick._HalfWidth=VirtualJoystick.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&&VirtualJoystick._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new rm.FM(0,0),this._joystickPreviousPointerPos=new rm.FM(0,0),this._joystickPointerStartPos=new rm.FM(0,0),this._deltaJoystickVector=new rm.FM(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},VirtualJoystick.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("contextmenu",e=>{e.preventDefault()},!1),requestAnimationFrame(()=>{this._drawVirtualJoystick()})}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){e.preventDefault(),(!0===this._leftJoystick?e.clientX<VirtualJoystick._HalfWidth:e.clientX>VirtualJoystick._HalfWidth)&&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)):VirtualJoystick._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){let t=new rm.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),0<VirtualJoystick._AlwaysVisibleSticks&&(this._leftJoystick?this._joystickPointerPos.x=Math.min(VirtualJoystick._HalfWidth,this._joystickPointerPos.x):this._joystickPointerPos.x=Math.max(VirtualJoystick._HalfWidth,this._joystickPointerPos.x));let t=this.reverseLeftRight?-1:1,i=t*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case tO.X:this.deltaPosition.x=Math.min(1,Math.max(-1,i));break;case tO.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,i));break;case tO.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,i))}let r=this.reverseUpDown?1:-1,s=r*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case tO.X:this.deltaPosition.x=Math.min(1,Math.max(-1,s));break;case tO.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,s));break;case tO.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,s))}}else{let t=this._touches.get(e.pointerId.toString());t&&(t.x=e.clientX,t.y=e.clientY)}}_onPointerUp(e){if(this._joystickPointerId==e.pointerId)this._clearPreviousDraw(),this._joystickPointerId=-1,this.pressed=!1;else{let t=this._touches.get(e.pointerId.toString());t&&VirtualJoystick._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())}setJoystickColor(e){this._joystickColor=e}set containerSize(e){this._joystickContainerSize=e,this._clearContainerSize=~~(2.1*this._joystickContainerSize),this._clearContainerSizeOffset=~~(this._clearContainerSize/2)}get containerSize(){return this._joystickContainerSize}set puckSize(e){this._joystickPuckSize=e,this._clearPuckSize=~~(2.1*this._joystickPuckSize),this._clearPuckSizeOffset=~~(this._clearPuckSize/2)}get puckSize(){return this._joystickPuckSize}clearPosition(){this.alwaysVisible=!1,this._joystickPosition=null}set alwaysVisible(e){this._alwaysVisible!==e&&(e&&this._joystickPosition?(VirtualJoystick._AlwaysVisibleSticks++,this._alwaysVisible=!0):(VirtualJoystick._AlwaysVisibleSticks--,this._alwaysVisible=!1))}get alwaysVisible(){return this._alwaysVisible}setPosition(e,t){this._joystickPointerStartPos&&this._clearPreviousDraw(),this._joystickPosition=new rm.FM(e,t)}setActionOnTouch(e){this._action=e}setAxisForLeftRight(e){switch(e){case tO.X:case tO.Y:case tO.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=tO.X}}setAxisForUpDown(e){switch(e){case tO.X:case tO.Y:case tO.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=tO.Y}}_clearPreviousDraw(){let e=this._joystickPosition||this._joystickPointerStartPos;VirtualJoystick._VJCanvasContext.clearRect(e.x-this._clearContainerSizeOffset,e.y-this._clearContainerSizeOffset,this._clearContainerSize,this._clearContainerSize),VirtualJoystick._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x-this._clearPuckSizeOffset-1,this._joystickPreviousPointerPos.y-this._clearPuckSizeOffset-1,this._clearPuckSize+2,this._clearPuckSize+2)}setContainerImage(e){let t=new Image;t.src=e,t.onload=()=>this._containerImage=t}setPuckImage(e){let t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){let e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?VirtualJoystick._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.lineWidth=2,VirtualJoystick._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath(),VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.lineWidth=6,VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?VirtualJoystick._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.lineWidth=2,VirtualJoystick._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._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()):(VirtualJoystick._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.fillStyle="white",VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle="red",VirtualJoystick._VJCanvasContext.lineWidth=6,VirtualJoystick._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){VirtualJoystick.Canvas&&(VirtualJoystick.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(VirtualJoystick.Canvas),VirtualJoystick.Canvas=null),this._released=!0}};VirtualJoystick._GlobalJoystickIndex=0,VirtualJoystick._AlwaysVisibleSticks=0,FreeCameraInputsManager.prototype.addVirtualJoystick=function(){return this.add(new FreeCameraVirtualJoystickInput),this};let FreeCameraVirtualJoystickInput=class FreeCameraVirtualJoystickInput{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){let e=this.camera,t=50*e._computeLocalCameraSpeed(),i=rm.y3.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=rm.P.TransformCoordinates(new rm.P(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new VirtualJoystick(!0),this._leftjoystick.setAxisForUpDown(tO.Z),this._leftjoystick.setAxisForLeftRight(tO.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new VirtualJoystick(!1),this._rightjoystick.setAxisForUpDown(tO.X),this._rightjoystick.setAxisForLeftRight(tO.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"}};sO.FreeCameraVirtualJoystickInput=FreeCameraVirtualJoystickInput;let targetCamera_TargetCamera=class targetCamera_TargetCamera extends rj.V{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=rm.P.Zero(),this._tmpTargetVector=rm.P.Zero(),this.cameraDirection=new rm.P(0,0,0),this.cameraRotation=new rm.FM(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new rm._f,this.rotation=new rm.P(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=rm.P.Zero(),this._initialFocalDistance=1,this._viewMatrix=rm.y3.Zero(),this._camMatrix=rm.y3.Zero(),this._cameraTransformMatrix=rm.y3.Zero(),this._cameraRotationMatrix=rm.y3.Zero(),this._referencePoint=new rm.P(0,0,1),this._transformedReferencePoint=rm.P.Zero(),this._deferredPositionUpdate=new rm.P,this._deferredRotationQuaternionUpdate=new rm._f,this._deferredRotationUpdate=new rm.P,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=rm.P.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();let 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){let e=this.lockedTarget,t=e.computeWorldMatrix();t.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 rm.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new rm.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new rm._f(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();let 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;let 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(){let 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+=rw.kn),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),rm.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]);let 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&&rm._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){this.parent.getWorldMatrix().invertToRef(rm.jp.Matrix[0]),rm.P.TransformNormalToRef(this.cameraDirection,rm.jp.Matrix[0],rm.jp.Vector3[0]),this._deferredPositionUpdate.addInPlace(rm.jp.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){let e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint&&(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion)){let e=this._deferredRotationUpdate.lengthSquared();e&&(rm._f.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}t&&(Math.abs(this.cameraDirection.x)<this.speed*rw.kn&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<this.speed*rw.kn&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<this.speed*rw.kn&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<this.speed*rw.kn&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<this.speed*rw.kn&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):rm.y3.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return rm.P.TransformNormalToRef(this._defaultUp,this._cameraRotationMatrix,this.upVector),this}_getViewMatrix(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),rm.P.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?rL.RD.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(rm._f.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),rL.RD.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.ignoreParentScaling){if(this.parent){let r=this.parent.getWorldMatrix();rm.P.TransformCoordinatesToRef(e,r,this._globalPosition),rm.P.TransformCoordinatesToRef(t,r,this._tmpTargetVector),rm.P.TransformNormalToRef(i,r,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(i);this.getScene().useRightHandedSystem?rm.y3.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):rm.y3.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix);return}if(this.getScene().useRightHandedSystem?rm.y3.LookAtRHToRef(e,t,i,this._viewMatrix):rm.y3.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){let e=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(e,this._viewMatrix),this._viewMatrix.getTranslationToRef(this._globalPosition),this._viewMatrix.invert(),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e)}createRigCamera(e,t){if(this.cameraRigMode!==rj.V.RIG_MODE_NONE){let t=new targetCamera_TargetCamera(e,this.position.clone(),this.getScene());return t.isRigCamera=!0,t.rigParent=this,this.cameraRigMode===rj.V.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new rm._f),t._cameraRigParams={},t.rotationQuaternion=new rm._f),t.mode=this.mode,t.orthoLeft=this.orthoLeft,t.orthoRight=this.orthoRight,t.orthoTop=this.orthoTop,t.orthoBottom=this.orthoBottom,t}return null}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case rj.V.RIG_MODE_STEREOSCOPIC_INTERLACED:{let i=this.cameraRigMode===rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,r=this.cameraRigMode===rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*r,t);break}case rj.V.RIG_MODE_VR:e.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),t.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),t.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),t.position.copyFrom(this.position)}super._updateRigCameras()}_getRigCamPositionAndTarget(e,t){let i=this.getTarget();i.subtractToRef(this.position,targetCamera_TargetCamera._TargetFocalPoint),targetCamera_TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);let r=targetCamera_TargetCamera._TargetFocalPoint.addInPlace(this.position);rm.y3.TranslationToRef(-r.x,-r.y,-r.z,targetCamera_TargetCamera._TargetTransformMatrix),targetCamera_TargetCamera._TargetTransformMatrix.multiplyToRef(rm.y3.RotationAxis(t.upVector,e),targetCamera_TargetCamera._RigCamTransformMatrix),rm.y3.TranslationToRef(r.x,r.y,r.z,targetCamera_TargetCamera._TargetTransformMatrix),targetCamera_TargetCamera._RigCamTransformMatrix.multiplyToRef(targetCamera_TargetCamera._TargetTransformMatrix,targetCamera_TargetCamera._RigCamTransformMatrix),rm.P.TransformCoordinatesToRef(this.position,targetCamera_TargetCamera._RigCamTransformMatrix,t.position),t.setTarget(r)}getClassName(){return"TargetCamera"}};targetCamera_TargetCamera._RigCamTransformMatrix=new rm.y3,targetCamera_TargetCamera._TargetTransformMatrix=new rm.y3,targetCamera_TargetCamera._TargetFocalPoint=new rm.P,(0,rH.gn)([(0,rb.hd)()],targetCamera_TargetCamera.prototype,"rotation",void 0),(0,rH.gn)([(0,rb.qC)()],targetCamera_TargetCamera.prototype,"speed",void 0),(0,rH.gn)([(0,rb.RR)("lockedTargetId")],targetCamera_TargetCamera.prototype,"lockedTarget",void 0);let FreeCamera=class FreeCamera extends targetCamera_TargetCamera{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){let e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){let t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){let e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){let t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){let e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){let e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){let e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){let e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new rm.P(.5,1,.5),this.ellipsoidOffset=new rm.P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=rm.P.Zero(),this._diffPosition=rm.P.Zero(),this._newPosition=rm.P.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>rq.D.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new FreeCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=rW.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new rm.P(0,0,0),this.cameraRotation=new rm.FM(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?rm.P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=rm.P.Zero(),this._transformedDirection=rm.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,rH.gn)([(0,rb.hd)()],FreeCamera.prototype,"ellipsoid",void 0),(0,rH.gn)([(0,rb.hd)()],FreeCamera.prototype,"ellipsoidOffset",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCamera.prototype,"checkCollisions",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCamera.prototype,"applyGravity",void 0),ry.N.AddNodeConstructor("TouchCamera",(e,t)=>()=>new TouchCamera(e,rm.P.Zero(),t));let TouchCamera=class TouchCamera extends FreeCamera{get touchAngularSensibility(){let e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){let e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){let 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(){let e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}};ry.N.AddNodeConstructor("ArcRotateCamera",(e,t)=>()=>new ArcRotateCamera(e,0,0,1,rm.P.Zero(),t));let ArcRotateCamera=class ArcRotateCamera extends targetCamera_TargetCamera{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 rm.y3,this._upToYMatrix=new rm.y3,this._upVector=rm.P.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){rm.y3.RotationAlignToRef(rm.P.UpReadOnly,this._upVector,this._yToUpMatrix),rm.y3.RotationAlignToRef(this._upVector,rm.P.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){let e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){let t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){let e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){let t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){let e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){let t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){let e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){let t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){let e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){let e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){let t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){let e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){let 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 BouncingBehavior,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 FramingBehavior,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 AutoRotationBehavior,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,n,a=!0){super(e,rm.P.Zero(),n,a),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=rm.P.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=rm.FM.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new rm.y3,this.panningAxis=new rm.P(1,1,0),this._transformedDirection=new rm.P,this.mapPanning=!1,this.onMeshTargetChangedObservable=new rf.y$,this.checkCollisions=!1,this.collisionRadius=new rm.P(.5,.5,.5),this._previousPosition=rm.P.Zero(),this._collisionVelocity=rm.P.Zero(),this._newPosition=rm.P.Zero(),this._computationVector=rm.P.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);let r=Math.cos(this.alpha),s=Math.sin(this.alpha),n=Math.cos(this.beta),a=Math.sin(this.beta);0===a&&(a=1e-4);let o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*r*a,this.radius*n,this.radius*s*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=(l=l.clone()).negate()),this._computeViewMatrix(this._position,o,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=rm.P.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new ArcRotateCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new rm.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=rm.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){let e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}let 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,r=2){let s=arguments;t=rW.w1.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){let e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier(),i=this.inertialAlphaOffset*t;this.beta<=0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<rw.kn&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<rw.kn&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*rw.kn&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){let e=new rm.P(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.multiplyInPlace(this.panningAxis),rm.P.TransformNormalToRef(e,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){let e=this.upVector,t=rm.P.CrossToRef(this._transformedDirection,e,this._transformedDirection);rm.P.CrossToRef(e,t,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);if(!this._targetHost){if(this.panningDistanceLimit){this._transformedDirection.addInPlace(this._target);let e=rm.P.DistanceSquared(this._transformedDirection,this.panningOriginTarget);e<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)}else this._target.addInPlace(this._transformedDirection)}this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<this.speed*rw.kn&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<this.speed*rw.kn&&(this.inertialPanningY=0)}this._checkLimits(),super._checkInputs()}}_checkLimits(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),null!==this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(0!==this._upVector.x||1!==this._upVector.y||0!==this._upVector.z)&&rm.P.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);let 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);let t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,r=!1){var s;if(r=null!==(s=this.overrideCloneAlphaBetaRadius)&&void 0!==s?s:r,e.getBoundingInfo)t?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{let t=this._getTargetPosition();if(t&&!i&&t.equals(e))return;this._targetHost=null,this._target=e,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){let e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);0===r&&(r=1e-4),0===this.radius&&(this.radius=1e-4);let s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(0!==this._upVector.x||1!==this._upVector.y||0!==this._upVector.z)&&rm.P.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){let e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&r<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;let i=rV.Kj.MinMax(e),r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(void 0===e.min){let t=e||this.getScene().meshes;i=rV.Kj.MinMax(t),r=rm.P.Distance(i.min,i.max)}else i=e,r=e.distance;this._target=rV.Kj.Center(i),t||(this.maxZ=2*r)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case rj.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case rj.V.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}let r=new ArcRotateCamera(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case rj.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case rj.V.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){let r=rm.P.Distance(e,t),s=this.getScene().getEngine(),n=s.getAspectRatio(this),a=Math.tan(this.fov/2),o=a*n,l=.5*r*i;return Math.max(l*Math.sqrt(1+1/(o*o)),l*Math.sqrt(1+1/(a*a)))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}};(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"alpha",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"beta",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"radius",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"overrideCloneAlphaBetaRadius",void 0),(0,rH.gn)([(0,rb.hd)("target")],ArcRotateCamera.prototype,"_target",void 0),(0,rH.gn)([(0,rb.RR)("targetHost")],ArcRotateCamera.prototype,"_targetHost",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"inertialAlphaOffset",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"inertialBetaOffset",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"inertialRadiusOffset",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"lowerAlphaLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"upperAlphaLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"lowerBetaLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"upperBetaLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"lowerRadiusLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"upperRadiusLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"inertialPanningX",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"inertialPanningY",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"pinchToPanMaxDistance",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"panningDistanceLimit",void 0),(0,rH.gn)([(0,rb.hd)()],ArcRotateCamera.prototype,"panningOriginTarget",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"panningInertia",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"zoomToMouseLocation",null),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"zoomOnFactor",void 0),(0,rH.gn)([(0,rb.QC)()],ArcRotateCamera.prototype,"targetScreenOffset",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"allowUpsideDown",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"useInputToRestoreState",void 0),ry.N.AddNodeConstructor("DeviceOrientationCamera",(e,t)=>()=>new DeviceOrientationCamera(e,rm.P.Zero(),t));let DeviceOrientationCamera=class DeviceOrientationCamera extends FreeCamera{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new rm._f,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new rm._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 rm._f),rm._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=rL.RD.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new rm._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))}};let FlyCameraInputsManager=class FlyCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addKeyboard(){return this.add(new FlyCameraKeyboardInput),this}addMouse(){return this.add(new FlyCameraMouseInput),this}};let FlyCamera=class FlyCamera extends targetCamera_TargetCamera{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){let e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){let t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){let e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){let t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new rm.P(1,1,1),this.ellipsoidOffset=new rm.P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=rm.P.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=rm.P.Zero(),this._diffPosition=rm.P.Zero(),this._newPosition=rm.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()>rq.D.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new FlyCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=rW.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new rm.P(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?rm.P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=rm.P.Zero(),this._transformedDirection=rm.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){let t=this._trackRoll,i=this.rotation.z,r=t-i;Math.abs(r)>=.001&&(this.rotation.z+=r/e,.001>=Math.abs(t-this.rotation.z)&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}};(0,rH.gn)([(0,rb.hd)()],FlyCamera.prototype,"ellipsoid",void 0),(0,rH.gn)([(0,rb.hd)()],FlyCamera.prototype,"ellipsoidOffset",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCamera.prototype,"checkCollisions",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCamera.prototype,"applyGravity",void 0);let FollowCameraInputsManager=class FollowCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addKeyboard(){return this.add(new FollowCameraKeyboardMoveInput),this}addMouseWheel(){return this.add(new FollowCameraMouseWheelInput),this}addPointers(){return this.add(new FollowCameraPointersInput),this}addVRDeviceOrientation(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this}};ry.N.AddNodeConstructor("FollowCamera",(e,t)=>()=>new FollowCamera(e,rm.P.Zero(),t)),ry.N.AddNodeConstructor("ArcFollowCamera",(e,t)=>()=>new ArcFollowCamera(e,0,0,1,null,t));let FollowCamera=class FollowCamera extends targetCamera_TargetCamera{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new FollowCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;let t=rm.jp.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);let i=Math.atan2(t.m[8],t.m[10]),r=rW.w1.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),n=s.x+Math.sin(r)*this.radius,a=s.z+Math.cos(r)*this.radius,o=n-this.position.x,l=s.y+this.heightOffset-this.position.y,h=a-this.position.z,u=o*this.cameraAcceleration*2,c=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new rm.P(this.position.x+u,this.position.y+c,this.position.z+d),this.setTarget(s)}attachControl(e,t){t=rW.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.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffset<this.lowerHeightOffsetLimit&&(this.heightOffset=this.lowerHeightOffsetLimit),null!==this.upperHeightOffsetLimit&&this.heightOffset>this.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffset<this.lowerRotationOffsetLimit&&(this.rotationOffset=this.lowerRotationOffsetLimit),null!==this.upperRotationOffsetLimit&&this.rotationOffset>this.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}};(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"radius",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"lowerRadiusLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"upperRadiusLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"rotationOffset",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"lowerRotationOffsetLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"upperRotationOffsetLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"heightOffset",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"lowerHeightOffsetLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"upperHeightOffsetLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"cameraAcceleration",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"maxCameraSpeed",void 0),(0,rH.gn)([(0,rb.RR)("lockedTargetId")],FollowCamera.prototype,"lockedTarget",void 0);let ArcFollowCamera=class ArcFollowCamera extends targetCamera_TargetCamera{constructor(e,t,i,r,s,n){super(e,rm.P.Zero(),n),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=rm.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);let e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}};(P=tN||(tN={}))[P.A=0]="A",P[P.B=1]="B",P[P.X=2]="X",P[P.Y=3]="Y",P[P.LB=4]="LB",P[P.RB=5]="RB",P[P.Back=8]="Back",P[P.Start=9]="Start",P[P.LeftStick=10]="LeftStick",P[P.RightStick=11]="RightStick",(R=tF||(tF={}))[R.Up=12]="Up",R[R.Down=13]="Down",R[R.Left=14]="Left",R[R.Right=15]="Right";let Xbox360Pad=class Xbox360Pad extends Gamepad{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new rf.y$,this.onButtonUpObservable=new rf.y$,this.onPadDownObservable=new rf.y$,this.onPadUpObservable=new rf.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=Gamepad.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,tN.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,tN.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,tN.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,tN.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,tN.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,tN.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,tN.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,tN.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,tN.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,tN.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,tF.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,tF.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,tF.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,tF.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()}};(A=tB||(tB={}))[A.Cross=0]="Cross",A[A.Circle=1]="Circle",A[A.Square=2]="Square",A[A.Triangle=3]="Triangle",A[A.L1=4]="L1",A[A.R1=5]="R1",A[A.Share=8]="Share",A[A.Options=9]="Options",A[A.LeftStick=10]="LeftStick",A[A.RightStick=11]="RightStick",(I=tL||(tL={}))[I.Up=12]="Up",I[I.Down=13]="Down",I[I.Left=14]="Left",I[I.Right=15]="Right";let DualShockPad=class DualShockPad extends Gamepad{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 rf.y$,this.onButtonUpObservable=new rf.y$,this.onPadDownObservable=new rf.y$,this.onPadUpObservable=new rf.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=Gamepad.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,tB.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,tB.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,tB.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,tB.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,tB.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,tB.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,tB.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,tB.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,tB.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,tB.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,tL.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,tL.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,tL.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,tL.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()}};let GamepadManager=class GamepadManager{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new rf.y$,(0,rK.CG)()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new rf.y$(e=>{for(let t in this._babylonGamepads){let i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}}),this._onGamepadConnectedEvent=e=>{let t;let i=e.gamepad;i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected||(this._babylonGamepads[i.index]?((t=this._babylonGamepads[i.index]).browserGamepad=i,t._isConnected=!0):t=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(t),this._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=e=>{let t=e.gamepad;for(let e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){let t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport){if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){let 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=Gamepad.XBOX){for(let 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);let i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),r=-1!==e.id.search("Xbox One");return t=r||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Xbox360Pad(e.id,e.index,e,r):i?new DualShockPad(e.id,e.index,e):new GenericPad(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){for(let e in this._updateGamepadObjects(),this._babylonGamepads){let t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch(e){-1===this._loggedErrors.indexOf(t.index)&&(rW.w1.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&rq.D.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){let e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t<e.length;t++){let i=e[t];if(i){if(this._babylonGamepads[i.index])this._babylonGamepads[t].browserGamepad=i,this._babylonGamepads[t].isConnected||(this._babylonGamepads[t]._isConnected=!0,this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[t]));else{let e=this._addNewGamepad(i);this.onGamepadConnectedObservable.notifyObservers(e)}}}}};Object.defineProperty(rN.x.prototype,"gamepadManager",{get:function(){if(!this._gamepadManager){this._gamepadManager=new GamepadManager(this);let e=this._getComponent(rQ.l.NAME_GAMEPAD);e||(e=new GamepadSystemSceneComponent(this),this._addComponent(e))}return this._gamepadManager},enumerable:!0,configurable:!0}),FreeCameraInputsManager.prototype.addGamepad=function(){return this.add(new FreeCameraGamepadInput),this},ArcRotateCameraInputsManager.prototype.addGamepad=function(){return this.add(new ArcRotateCameraGamepadInput),this};let GamepadSystemSceneComponent=class GamepadSystemSceneComponent{constructor(e){this.name=rQ.l.NAME_GAMEPAD,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(rQ.l.STEP_BEFORECAMERAUPDATE_GAMEPAD,this,this._beforeCameraUpdate)}rebuild(){}dispose(){let e=this.scene._gamepadManager;e&&(e.dispose(),this.scene._gamepadManager=null)}_beforeCameraUpdate(){let e=this.scene._gamepadManager;e&&e._isMonitoring&&e._checkGamepadsStatus()}};ry.N.AddNodeConstructor("FreeCamera",(e,t)=>()=>new universalCamera_UniversalCamera(e,rm.P.Zero(),t));let universalCamera_UniversalCamera=class universalCamera_UniversalCamera extends TouchCamera{get gamepadAngularSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}};rj.V._CreateDefaultParsedCamera=(e,t)=>new universalCamera_UniversalCamera(e,rm.P.Zero(),t),ry.N.AddNodeConstructor("GamepadCamera",(e,t)=>()=>new GamepadCamera(e,rm.P.Zero(),t));let GamepadCamera=class GamepadCamera extends universalCamera_UniversalCamera{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}};let sB=`varying vec2 vUV;uniform samplerCube textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 uv=vUV*2.0-1.0; +#ifdef POSITIVEX +gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); +#endif +#ifdef NEGATIVEX +gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); +#endif +#ifdef POSITIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); +#endif +#ifdef NEGATIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); +#endif +#ifdef POSITIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); +#endif +#ifdef NEGATIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); +#endif +}`;s_.v.ShadersStore.passCubePixelShader=sB;let PassPostProcess=class PassPostProcess extends postProcess_PostProcess{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,n,a=0,o=!1){super(e,"pass",null,null,t,i,r,s,n,void 0,a,void 0,null,o)}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new PassPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}};(0,rv.H)("BABYLON.PassPostProcess",PassPostProcess),rq.D._RescalePostProcessFactory=e=>new PassPostProcess("rescale",1,null,2,e,!1,0);let sL=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`;s_.v.ShadersStore.anaglyphPixelShader=sL;let AnaglyphPostProcess=class AnaglyphPostProcess extends postProcess_PostProcess{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,s,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,s,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)})}};function setStereoscopicAnaglyphRigMode(e){e._rigCameras[0]._rigPostProcess=new PassPostProcess(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new AnaglyphPostProcess(e.name+"_anaglyph",1,e._rigCameras)}(0,rv.H)("BABYLON.AnaglyphPostProcess",AnaglyphPostProcess),ry.N.AddNodeConstructor("AnaglyphArcRotateCamera",(e,t,i)=>()=>new AnaglyphArcRotateCamera(e,0,0,1,rm.P.Zero(),i.interaxial_distance,t));let AnaglyphArcRotateCamera=class AnaglyphArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,n,a){super(e,t,i,r,s,a),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=n,this.setCameraRigMode(rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}};ry.N.AddNodeConstructor("AnaglyphFreeCamera",(e,t,i)=>()=>new AnaglyphFreeCamera(e,rm.P.Zero(),i.interaxial_distance,t));let AnaglyphFreeCamera=class AnaglyphFreeCamera extends FreeCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}};ry.N.AddNodeConstructor("AnaglyphGamepadCamera",(e,t,i)=>()=>new AnaglyphGamepadCamera(e,rm.P.Zero(),i.interaxial_distance,t));let AnaglyphGamepadCamera=class AnaglyphGamepadCamera extends GamepadCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}};ry.N.AddNodeConstructor("AnaglyphUniversalCamera",(e,t,i)=>()=>new AnaglyphUniversalCamera(e,rm.P.Zero(),i.interaxial_distance,t));let AnaglyphUniversalCamera=class AnaglyphUniversalCamera extends universalCamera_UniversalCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}};let sw=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; +#ifdef IS_STEREOSCOPIC_HORIZ +useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); +#else +#ifdef IS_STEREOSCOPIC_INTERLACED +float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); +#else +useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); +#endif +#endif +if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} +gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} +`;s_.v.ShadersStore.stereoscopicInterlacePixelShader=sw;let StereoscopicInterlacePostProcessI=class StereoscopicInterlacePostProcessI extends postProcess_PostProcess{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,s,n,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,n,a,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new rm.FM(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new rm.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 setStereoscopicRigMode(e){let t=e.cameraRigMode===rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,r=e.cameraRigMode===rj.V.RIG_MODE_STEREOSCOPIC_INTERLACED;r?(e._rigCameras[0]._rigPostProcess=new PassPostProcess(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new StereoscopicInterlacePostProcessI(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new sh.l(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new sh.l(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}ry.N.AddNodeConstructor("StereoscopicArcRotateCamera",(e,t,i)=>()=>new StereoscopicArcRotateCamera(e,0,0,1,rm.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicArcRotateCamera=class StereoscopicArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,n,a,o){super(e,t,i,r,s,o),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=a,this.setCameraRigMode(a?rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}};ry.N.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new StereoscopicFreeCamera(e,rm.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicFreeCamera=class StereoscopicFreeCamera extends FreeCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}};ry.N.AddNodeConstructor("StereoscopicGamepadCamera",(e,t,i)=>()=>new StereoscopicGamepadCamera(e,rm.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicGamepadCamera=class StereoscopicGamepadCamera extends GamepadCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}};ry.N.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new StereoscopicUniversalCamera(e,rm.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicUniversalCamera=class StereoscopicUniversalCamera extends universalCamera_UniversalCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}};ry.N.AddNodeConstructor("VirtualJoysticksCamera",(e,t)=>()=>new VirtualJoysticksCamera(e,rm.P.Zero(),t));let VirtualJoysticksCamera=class VirtualJoysticksCamera extends FreeCamera{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}};let VRCameraMetrics=class VRCameraMetrics{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(){let e=this.hScreenSize/4-this.lensSeparationDistance/2,t=4*e/this.hScreenSize;return rm.y3.Translation(t,0,0)}get rightHMatrix(){let e=this.hScreenSize/4-this.lensSeparationDistance/2,t=4*e/this.hScreenSize;return rm.y3.Translation(-t,0,0)}get leftPreViewMatrix(){return rm.y3.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return rm.y3.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){let e=new VRCameraMetrics;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}};let sU=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; +float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) +gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;s_.v.ShadersStore.vrDistortionCorrectionPixelShader=sU;let VRDistortionCorrectionPostProcess=class VRDistortionCorrectionPostProcess extends postProcess_PostProcess{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,texture_Texture.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new rm.FM(2,2/this.aspectRatio),this._scaleFactor=new rm.FM(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new rm.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])})}};let sV=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;s_.v.ShadersStore.vrMultiviewToSingleviewPixelShader=sV;let MultiviewRenderTarget=class MultiviewRenderTarget extends renderTargetTexture_RenderTargetTexture{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 createMultiviewUbo(e,t){let i=new rX.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}rq.D.prototype.createMultiviewRenderTargetTexture=function(e,t,i,r){let s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";let n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=s.createFramebuffer();let a=new r5.l(this,r5.S.Unknown,!0);return a.width=e,a.height=t,a.isMultiview=!0,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,e,t,2)),n._colorTextureArray=i,r||(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,r),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=r,a.isReady=!0,n.setTextures(a),n._depthStencilTexture=a,n},rq.D.prototype.bindMultiviewFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"},rq.D.prototype.bindSpaceWarpFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_ATTACHMENT,e._depthStencilTextureArray,0,0,2);else throw Error("Invalid Space Warp framebuffer")},rj.V.prototype._useMultiviewToSingleView=!1,rj.V.prototype._multiviewTexture=null,rj.V.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=e||this._multiviewTexture.getRenderHeight()!=t)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new MultiviewRenderTarget(this.getScene(),{width:e,height:t})):this._multiviewTexture=new MultiviewRenderTarget(this.getScene(),{width:e,height:t})};let sk=rN.x.prototype.createSceneUniformBuffer;rN.x.prototype._transformMatrixR=rm.y3.Zero(),rN.x.prototype._multiviewSceneUbo=null,rN.x.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=createMultiviewUbo(this.getEngine(),"scene_multiview")},rN.x.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?createMultiviewUbo(this.getEngine(),e):sk.bind(this)(e)},rN.x.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,rm.jp.Matrix[0]),sl.i.GetRightPlaneToRef(rm.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))},rN.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<e._rigCameras.length;t++){let i=this.getEngine();this._activeCamera=e._rigCameras[t],i.setViewport(this._activeCamera.viewport),this.postProcessManager&&(this.postProcessManager._prepareFrame(),this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate))}};let VRMultiviewToSingleviewPostProcess=class VRMultiviewToSingleviewPostProcess extends postProcess_PostProcess{getClassName(){return"VRMultiviewToSingleviewPostProcess"}constructor(e,t,i){super(e,"vrMultiviewToSingleview",["imageIndex"],["multiviewSampler"],i,t,texture_Texture.BILINEAR_SAMPLINGMODE);let r=null!=t?t:this.getCamera();this.onSizeChangedObservable.add(()=>{}),this.onApplyObservable.add(e=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",r._multiviewTexture)})}};function setVRRigMode(e,t){let i=t.vrCameraMetrics||VRCameraMetrics.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new sh.l(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new rm.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 sh.l(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new rm.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 VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(rT.Y.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}ry.N.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(e,t)=>()=>new VRDeviceOrientationArcRotateCamera(e,0,0,1,rm.P.Zero(),t));let VRDeviceOrientationArcRotateCamera=class VRDeviceOrientationArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,n,a=!0,o=VRCameraMetrics.GetDefault()){super(e,t,i,r,s,n),this._setRigMode=e=>setVRRigMode(this,e),o.compensateDistortion=a,this.setCameraRigMode(rj.V.RIG_MODE_VR,{vrCameraMetrics:o}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}};ry.N.AddNodeConstructor("VRDeviceOrientationFreeCamera",(e,t)=>()=>new VRDeviceOrientationFreeCamera(e,rm.P.Zero(),t));let VRDeviceOrientationFreeCamera=class VRDeviceOrientationFreeCamera extends DeviceOrientationCamera{constructor(e,t,i,r=!0,s=VRCameraMetrics.GetDefault()){super(e,t,i),this._setRigMode=e=>setVRRigMode(this,e),s.compensateDistortion=r,this.setCameraRigMode(rj.V.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}};ry.N.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(e,t)=>()=>new VRDeviceOrientationGamepadCamera(e,rm.P.Zero(),t));let VRDeviceOrientationGamepadCamera=class VRDeviceOrientationGamepadCamera extends VRDeviceOrientationFreeCamera{constructor(e,t,i,r=!0,s=VRCameraMetrics.GetDefault()){super(e,t,i,r,s),this._setRigMode=e=>setVRRigMode(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}};let PrePassConfiguration=class PrePassConfiguration{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());let s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}};var sG=i(4885);let MaterialFlags=class MaterialFlags{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,rq.D.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}};MaterialFlags._DiffuseTextureEnabled=!0,MaterialFlags._DetailTextureEnabled=!0,MaterialFlags._DecalMapEnabled=!0,MaterialFlags._AmbientTextureEnabled=!0,MaterialFlags._OpacityTextureEnabled=!0,MaterialFlags._ReflectionTextureEnabled=!0,MaterialFlags._EmissiveTextureEnabled=!0,MaterialFlags._SpecularTextureEnabled=!0,MaterialFlags._BumpTextureEnabled=!0,MaterialFlags._LightmapTextureEnabled=!0,MaterialFlags._RefractionTextureEnabled=!0,MaterialFlags._ColorGradingTextureEnabled=!0,MaterialFlags._FresnelEnabled=!0,MaterialFlags._ClearCoatTextureEnabled=!0,MaterialFlags._ClearCoatBumpTextureEnabled=!0,MaterialFlags._ClearCoatTintTextureEnabled=!0,MaterialFlags._SheenTextureEnabled=!0,MaterialFlags._AnisotropicTextureEnabled=!0,MaterialFlags._ThicknessTextureEnabled=!0,MaterialFlags._RefractionIntensityTextureEnabled=!0,MaterialFlags._TranslucencyIntensityTextureEnabled=!0,MaterialFlags._IridescenceTextureEnabled=!0;let sz=`#ifdef DECAL +uniform vec4 vDecalInfos; +#endif +`;s_.v.IncludesShadersStore.decalFragmentDeclaration=sz;let sW=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; +#ifdef SPECULARTERM +uniform vec4 vSpecularColor; +#endif +uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; +#ifdef DIFFUSE +uniform vec2 vDiffuseInfos; +#endif +#ifdef AMBIENT +uniform vec2 vAmbientInfos; +#endif +#ifdef OPACITY +uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#ifdef ALPHATEST +uniform float alphaCutOff; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) +uniform mat4 view; +#endif +#ifdef REFRACTION +uniform vec4 vRefractionInfos; +#ifndef REFRACTIONMAP_3D +uniform mat4 refractionMatrix; +#endif +#ifdef REFRACTIONFRESNEL +uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; +#endif +#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) +uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; +#endif +#endif +#if defined(SPECULAR) && defined(SPECULARTERM) +uniform vec2 vSpecularInfos; +#endif +#ifdef DIFFUSEFRESNEL +uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; +#endif +#ifdef OPACITYFRESNEL +uniform vec4 opacityParts; +#endif +#ifdef EMISSIVEFRESNEL +uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos; +#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) +uniform mat4 reflectionMatrix; +#endif +#ifndef REFLECTIONMAP_SKYBOX +#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; +#endif +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos; +#endif +#include<decalFragmentDeclaration> +#define ADDITIONAL_FRAGMENT_DECLARATION +`;s_.v.IncludesShadersStore.defaultFragmentDeclaration=sW;let sH=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; +#ifdef MULTIVIEW +mat4 viewProjectionR; +#endif +mat4 view;mat4 projection;vec4 vEyePosition;}; +`;s_.v.IncludesShadersStore.sceneUboDeclaration=sH;let sX=`#ifdef WEBGL2 +uniform mat4 world;uniform float visibility; +#else +layout(std140,column_major) uniform;uniform Mesh +{mat4 world;float visibility;}; +#endif +#define WORLD_UBO +`;s_.v.IncludesShadersStore.meshUboDeclaration=sX;let sY=`layout(std140,column_major) uniform;uniform Material +{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; +#define ADDITIONAL_UBO_DECLARATION +}; +#include<sceneUboDeclaration> +#include<meshUboDeclaration> +`;s_.v.IncludesShadersStore.defaultUboDeclaration=sY;let sj=`#ifdef PREPASS +#extension GL_EXT_draw_buffers : require +layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; +#ifdef PREPASS_DEPTH +varying highp vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; +#endif +#endif +`;s_.v.IncludesShadersStore.prePassDeclaration=sj;let sq=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +#extension GL_EXT_draw_buffers : require +layout(location=0) out vec2 depth; +layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; +#define MAX_DEPTH 99999.0 +highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; +#endif +`;s_.v.IncludesShadersStore.oitDeclaration=sq;let sK=`#ifdef MAINUV{X} +varying vec2 vMainUV{X}; +#endif +`;s_.v.IncludesShadersStore.mainUVVaryingDeclaration=sK;let s$=`const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; +const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; +#define saturate(x) clamp(x,0.0,1.0) +#define absEps(x) abs(x)+Epsilon +#define maxEps(x) max(x,Epsilon) +#define saturateEps(x) clamp(x,Epsilon,1.0) +mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( +vec3(i0.x,i1.x,i2.x), +vec3(i0.y,i1.y,i2.y), +vec3(i0.z,i1.z,i2.z) +);return outMatrix;} +mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), +b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), +b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} +#if USE_EXACT_SRGB_CONVERSIONS +vec3 toLinearSpaceExact(vec3 color) +{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); +#else +return +vec3( +color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, +color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, +color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); +#endif +} +vec3 toGammaSpaceExact(vec3 color) +{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); +#else +return +vec3( +color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, +color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, +color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); +#endif +} +#endif +float toLinearSpace(float color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; +#else +return pow(color,LinearEncodePowerApprox); +#endif +} +vec3 toLinearSpace(vec3 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toLinearSpaceExact(color); +#else +return pow(color,vec3(LinearEncodePowerApprox)); +#endif +} +vec4 toLinearSpace(vec4 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toLinearSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); +#endif +} +float toGammaSpace(float color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; +#else +return pow(color,GammaEncodePowerApprox); +#endif +} +vec3 toGammaSpace(vec3 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toGammaSpaceExact(color); +#else +return pow(color,vec3(GammaEncodePowerApprox)); +#endif +} +vec4 toGammaSpace(vec4 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toGammaSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); +#endif +} +float square(float value) +{return value*value;} +vec3 square(vec3 value) +{return value*value;} +float pow5(float value) {float sq=value*value;return sq*sq*value;} +float getLuminance(vec3 color) +{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} +float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} +float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} +const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); } +vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} +vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} +`;s_.v.IncludesShadersStore.helperFunctions=s$;let sQ=`#ifdef LIGHT{X} +uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; +#ifdef SPECULARTERM +uniform vec4 vLightSpecular{X}; +#else +vec4 vLightSpecular{X}=vec4(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DArrayShadow shadowSampler{X}; +#else +uniform highp sampler2DArray shadowSampler{X}; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] +( +vec3 ( 1.5,0.0,0.0 ), +vec3 ( 0.0,1.5,0.0 ), +vec3 ( 0.0,0.0,5.5 ), +vec3 ( 1.5,0.0,5.5 ), +vec3 ( 1.5,1.5,0.0 ), +vec3 ( 1.0,1.0,1.0 ), +vec3 ( 0.0,1.0,5.5 ), +vec3 ( 0.5,3.5,0.75 ) +);vec3 shadowDebug{X}; +#endif +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +int index{X}=-1; +#else +int index{X}=SHADOWCSMNUM_CASCADES{X}-1; +#endif +float diff{X}=0.; +#elif defined(SHADOWCUBE{X}) +uniform samplerCube shadowSampler{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowSampler{X}; +#else +uniform sampler2D shadowSampler{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; +#endif +#ifdef SPOTLIGHT{X} +uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; +#elif defined(POINTLIGHT{X}) +uniform vec4 vLightFalloff{X}; +#elif defined(HEMILIGHT{X}) +uniform vec3 vLightGround{X}; +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; +#endif +#endif +`;s_.v.IncludesShadersStore.lightFragmentDeclaration=sQ;let sZ=`#ifdef LIGHT{X} +uniform Light{X} +{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; +#ifdef SPOTLIGHT{X} +vec4 vLightDirection;vec4 vLightFalloff; +#elif defined(POINTLIGHT{X}) +vec4 vLightFalloff; +#elif defined(HEMILIGHT{X}) +vec3 vLightGround; +#endif +vec4 shadowsInfo;vec2 depthValues;} light{X}; +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DArrayShadow shadowSampler{X}; +#else +uniform highp sampler2DArray shadowSampler{X}; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] +( +vec3 ( 1.5,0.0,0.0 ), +vec3 ( 0.0,1.5,0.0 ), +vec3 ( 0.0,0.0,5.5 ), +vec3 ( 1.5,0.0,5.5 ), +vec3 ( 1.5,1.5,0.0 ), +vec3 ( 1.0,1.0,1.0 ), +vec3 ( 0.0,1.0,5.5 ), +vec3 ( 0.5,3.5,0.75 ) +);vec3 shadowDebug{X}; +#endif +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +int index{X}=-1; +#else +int index{X}=SHADOWCSMNUM_CASCADES{X}-1; +#endif +float diff{X}=0.; +#elif defined(SHADOWCUBE{X}) +uniform samplerCube shadowSampler{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowSampler{X}; +#else +uniform sampler2D shadowSampler{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`;s_.v.IncludesShadersStore.lightUboDeclaration=sZ;let sJ=`struct lightingInfo +{vec3 diffuse; +#ifdef SPECULARTERM +vec3 specular; +#endif +#ifdef NDOTL +float ndl; +#endif +};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) +{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} +else +{lightVectorW=normalize(-lightData.xyz);} +float ndl=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) +{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +result.diffuse=vec3(0.); +#ifdef SPECULARTERM +result.specular=vec3(0.); +#endif +#ifdef NDOTL +result.ndl=0.; +#endif +return result;} +lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=mix(groundColor,diffuseColor,ndl); +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; +#endif +return result;} +#define inline +vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;s_.v.IncludesShadersStore.lightsFragmentFunctions=sJ;let s0=`#ifdef SHADOWS +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +#ifndef SHADOWFLOAT +float unpack(vec4 color) +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} +#endif +float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) +{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} +#define inline +float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +float shadow=unpack(textureCube(shadowSampler,directionToLight)); +#else +float shadow=textureCube(shadowSampler,directionToLight).x; +#endif +return depth>shadow ? darkness : 1.0;} +#define inline +float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); +#ifndef SHADOWFLOAT +if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25; +#else +if (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25; +#endif +return min(1.0,visibility+darkness);} +#define inline +float computeShadowWithESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight)); +#else +float shadowMapSample=textureCube(shadowSampler,directionToLight).x; +#endif +float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;} +#define inline +float computeShadowWithCloseESMCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight)); +#else +float shadowMapSample=textureCube(shadowSampler,directionToLight).x; +#endif +float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;} +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define inline +float computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);vec3 uvLayer=vec3(uv.x,uv.y,layer);float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadow=unpack(texture2D(shadowSampler,uvLayer)); +#else +float shadow=texture2D(shadowSampler,uvLayer).x; +#endif +return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} +#endif +#define inline +float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} +#define inline +float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); +#ifndef SHADOWFLOAT +if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25; +#else +if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25; +#endif +return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +#ifdef IS_NDC_HALF_ZRANGE +#define ZINCLIP clipSpace.z +#else +#define ZINCLIP uvDepth.z +#endif +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define GREATEST_LESS_THAN_ONE 0.99999994 +/* disable_uniformity_analysis */ +#define inline +float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +const vec3 PoissonSamplers32[64]=vec3[64]( +vec3(0.06407013,0.05409927,0.), +vec3(0.7366577,0.5789394,0.), +vec3(-0.6270542,-0.5320278,0.), +vec3(-0.4096107,0.8411095,0.), +vec3(0.6849564,-0.4990818,0.), +vec3(-0.874181,-0.04579735,0.), +vec3(0.9989998,0.0009880066,0.), +vec3(-0.004920578,-0.9151649,0.), +vec3(0.1805763,0.9747483,0.), +vec3(-0.2138451,0.2635818,0.), +vec3(0.109845,0.3884785,0.), +vec3(0.06876755,-0.3581074,0.), +vec3(0.374073,-0.7661266,0.), +vec3(0.3079132,-0.1216763,0.), +vec3(-0.3794335,-0.8271583,0.), +vec3(-0.203878,-0.07715034,0.), +vec3(0.5912697,0.1469799,0.), +vec3(-0.88069,0.3031784,0.), +vec3(0.5040108,0.8283722,0.), +vec3(-0.5844124,0.5494877,0.), +vec3(0.6017799,-0.1726654,0.), +vec3(-0.5554981,0.1559997,0.), +vec3(-0.3016369,-0.3900928,0.), +vec3(-0.5550632,-0.1723762,0.), +vec3(0.925029,0.2995041,0.), +vec3(-0.2473137,0.5538505,0.), +vec3(0.9183037,-0.2862392,0.), +vec3(0.2469421,0.6718712,0.), +vec3(0.3916397,-0.4328209,0.), +vec3(-0.03576927,-0.6220032,0.), +vec3(-0.04661255,0.7995201,0.), +vec3(0.4402924,0.3640312,0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.) +);const vec3 PoissonSamplers64[64]=vec3[64]( +vec3(-0.613392,0.617481,0.), +vec3(0.170019,-0.040254,0.), +vec3(-0.299417,0.791925,0.), +vec3(0.645680,0.493210,0.), +vec3(-0.651784,0.717887,0.), +vec3(0.421003,0.027070,0.), +vec3(-0.817194,-0.271096,0.), +vec3(-0.705374,-0.668203,0.), +vec3(0.977050,-0.108615,0.), +vec3(0.063326,0.142369,0.), +vec3(0.203528,0.214331,0.), +vec3(-0.667531,0.326090,0.), +vec3(-0.098422,-0.295755,0.), +vec3(-0.885922,0.215369,0.), +vec3(0.566637,0.605213,0.), +vec3(0.039766,-0.396100,0.), +vec3(0.751946,0.453352,0.), +vec3(0.078707,-0.715323,0.), +vec3(-0.075838,-0.529344,0.), +vec3(0.724479,-0.580798,0.), +vec3(0.222999,-0.215125,0.), +vec3(-0.467574,-0.405438,0.), +vec3(-0.248268,-0.814753,0.), +vec3(0.354411,-0.887570,0.), +vec3(0.175817,0.382366,0.), +vec3(0.487472,-0.063082,0.), +vec3(-0.084078,0.898312,0.), +vec3(0.488876,-0.783441,0.), +vec3(0.470016,0.217933,0.), +vec3(-0.696890,-0.549791,0.), +vec3(-0.149693,0.605762,0.), +vec3(0.034211,0.979980,0.), +vec3(0.503098,-0.308878,0.), +vec3(-0.016205,-0.872921,0.), +vec3(0.385784,-0.393902,0.), +vec3(-0.146886,-0.859249,0.), +vec3(0.643361,0.164098,0.), +vec3(0.634388,-0.049471,0.), +vec3(-0.688894,0.007843,0.), +vec3(0.464034,-0.188818,0.), +vec3(-0.440840,0.137486,0.), +vec3(0.364483,0.511704,0.), +vec3(0.034028,0.325968,0.), +vec3(0.099094,-0.308023,0.), +vec3(0.693960,-0.366253,0.), +vec3(0.678884,-0.204688,0.), +vec3(0.001801,0.780328,0.), +vec3(0.145177,-0.898984,0.), +vec3(0.062655,-0.611866,0.), +vec3(0.315226,-0.604297,0.), +vec3(-0.780145,0.486251,0.), +vec3(-0.371868,0.882138,0.), +vec3(0.200476,0.494430,0.), +vec3(-0.494552,-0.711051,0.), +vec3(0.612476,0.705252,0.), +vec3(-0.578845,-0.768792,0.), +vec3(-0.772454,-0.090976,0.), +vec3(0.504440,0.372295,0.), +vec3(0.155736,0.065157,0.), +vec3(0.391522,0.849605,0.), +vec3(-0.620106,-0.328104,0.), +vec3(0.789239,-0.419965,0.), +vec3(-0.545396,0.538133,0.), +vec3(-0.178564,-0.596057,0.) +); +#define inline +float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}} +float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec4 offset=vec4(poissonSamplers[i],0.);offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);} +shadow/=float(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);if (numBlocker<1.0) {return 1.0;} +else +{return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}} +if (numBlocker<1.0) {return 1.0;} +else +{float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec3 offset=poissonSamplers[i];offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);shadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);} +shadow/=float(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}} +#define inline +float computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) +{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);} +#define inline +float computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) +{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);} +#define inline +float computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) +{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);} +#define inline +float computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} +#define inline +float computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} +#define inline +float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} +#endif +#endif +`;s_.v.IncludesShadersStore.shadowsFragmentFunctions=s0;let s1=`#ifdef _DEFINENAME_ +#if _DEFINENAME_DIRECTUV==1 +#define v_VARYINGNAME_UV vMainUV1 +#elif _DEFINENAME_DIRECTUV==2 +#define v_VARYINGNAME_UV vMainUV2 +#elif _DEFINENAME_DIRECTUV==3 +#define v_VARYINGNAME_UV vMainUV3 +#elif _DEFINENAME_DIRECTUV==4 +#define v_VARYINGNAME_UV vMainUV4 +#elif _DEFINENAME_DIRECTUV==5 +#define v_VARYINGNAME_UV vMainUV5 +#elif _DEFINENAME_DIRECTUV==6 +#define v_VARYINGNAME_UV vMainUV6 +#else +varying vec2 v_VARYINGNAME_UV; +#endif +uniform sampler2D _SAMPLERNAME_Sampler; +#endif +`;s_.v.IncludesShadersStore.samplerFragmentDeclaration=s1;let s2=`#ifdef FRESNEL +float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power) +{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} +#endif +`;s_.v.IncludesShadersStore.fresnelFunction=s2;let s3=`vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) +{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); } +vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) +{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); } +vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) +{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);} +vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix) +{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);} +vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) +{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));} +vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) +{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0)); +#ifdef INVERTCUBICMAP +coords.y*=-1.0; +#endif +return coords;} +vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition) +{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0)); +#ifdef INVERTCUBICMAP +coords.y*=-1.0; +#endif +return coords;} +vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix) +{return vec3(reflectionMatrix*(view*worldPos));} +vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix) +{return vec3(reflectionMatrix*vec4(positionW,1.));} +#ifdef REFLECTION +vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal) +{ +#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED +vec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction); +#endif +#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED +vec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction); +#endif +#ifdef REFLECTIONMAP_EQUIRECTANGULAR +return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_SPHERICAL +return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_PLANAR +return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_CUBIC +#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC +return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition); +#else +return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); +#endif +#endif +#ifdef REFLECTIONMAP_PROJECTION +return computeProjectionCoords(worldPos,view,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_SKYBOX +return computeSkyBoxCoords(vPositionUVW,reflectionMatrix); +#endif +#ifdef REFLECTIONMAP_EXPLICIT +return vec3(0,0,0); +#endif +} +#endif +`;s_.v.IncludesShadersStore.reflectionFunction=s3;let s4=`#ifdef EXPOSURE +uniform float exposureLinear; +#endif +#ifdef CONTRAST +uniform float contrast; +#endif +#if defined(VIGNETTE) || defined(DITHER) +uniform vec2 vInverseScreenSize; +#endif +#ifdef VIGNETTE +uniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2; +#endif +#ifdef COLORCURVES +uniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive; +#endif +#ifdef COLORGRADING +#ifdef COLORGRADING3D +uniform highp sampler3D txColorTransform; +#else +uniform sampler2D txColorTransform; +#endif +uniform vec4 colorTransformSettings; +#endif +#ifdef DITHER +uniform float ditherIntensity; +#endif +`;s_.v.IncludesShadersStore.imageProcessingDeclaration=s4;let s5=`#if defined(COLORGRADING) && !defined(COLORGRADING3D) +/** +* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL. +* sampler3dSetting.x=textureOffset (0.5/textureSize). +* sampler3dSetting.y=textureSize. +*/ +#define inline +vec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting) +{float sliceSize=2.0*sampler3dSetting.x; +#ifdef SAMPLER3DGREENDEPTH +float sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y; +#else +float sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y; +#endif +float sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger; +#ifdef SAMPLER3DGREENDEPTH +vec2 sliceUV=color.rb; +#else +vec2 sliceUV=color.rg; +#endif +sliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction); +#ifdef SAMPLER3DBGRMAP +color.rgb=result.rgb; +#else +color.rgb=result.bgr; +#endif +return color;} +#endif +#ifdef TONEMAPPING_ACES +const mat3 ACESInputMat=mat3( +vec3(0.59719,0.07600,0.02840), +vec3(0.35458,0.90834,0.13383), +vec3(0.04823,0.01566,0.83777) +);const mat3 ACESOutputMat=mat3( +vec3( 1.60475,-0.10208,-0.00327), +vec3(-0.53108, 1.10813,-0.07276), +vec3(-0.07367,-0.00605, 1.07602) +);vec3 RRTAndODTFit(vec3 v) +{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;} +vec3 ACESFitted(vec3 color) +{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;} +#endif +#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS +vec4 applyImageProcessing(vec4 result) { +#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART +#ifdef EXPOSURE +result.rgb*=exposureLinear; +#endif +#ifdef VIGNETTE +vec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb; +#ifdef VIGNETTEBLENDMODEMULTIPLY +vec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier; +#endif +#ifdef VIGNETTEBLENDMODEOPAQUE +result.rgb=mix(vignetteColor,result.rgb,vignette); +#endif +#endif +#ifdef TONEMAPPING +#ifdef TONEMAPPING_ACES +result.rgb=ACESFitted(result.rgb); +#else +const float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb); +#endif +#endif +result.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb); +#ifdef CONTRAST +vec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);} +#endif +#ifdef COLORGRADING +vec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy; +#ifdef COLORGRADING3D +vec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb; +#else +vec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb; +#endif +result.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www); +#endif +#ifdef COLORCURVES +float luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a); +#endif +#ifdef DITHER +float rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither)); +#endif +#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND +return result;}`;s_.v.IncludesShadersStore.imageProcessingFunctions=s5;let s6=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) +#if defined(TANGENT) && defined(NORMAL) +varying mat3 vTBN; +#endif +#ifdef OBJECTSPACE_NORMALMAP +uniform mat4 normalMatrix; +#if defined(WEBGL2) || defined(WEBGPU) +mat4 toNormalMatrix(mat4 wMatrix) +{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;} +#else +mat4 toNormalMatrix(mat4 m) +{float +a00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3], +a10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3], +a20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3], +a30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3], +b00=a00*a11-a01*a10, +b01=a00*a12-a02*a10, +b02=a00*a13-a03*a10, +b03=a01*a12-a02*a11, +b04=a01*a13-a03*a11, +b05=a02*a13-a03*a12, +b06=a20*a31-a21*a30, +b07=a20*a32-a22*a30, +b08=a20*a33-a23*a30, +b09=a21*a32-a22*a31, +b10=a21*a33-a23*a31, +b11=a22*a33-a23*a32, +det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4( +a11*b11-a12*b10+a13*b09, +a02*b10-a01*b11-a03*b09, +a31*b05-a32*b04+a33*b03, +a22*b04-a21*b05-a23*b03, +a12*b08-a10*b11-a13*b07, +a00*b11-a02*b08+a03*b07, +a32*b02-a30*b05-a33*b01, +a20*b05-a22*b02+a23*b01, +a10*b10-a11*b08+a13*b06, +a01*b08-a00*b10-a03*b06, +a30*b04-a31*b02+a33*b00, +a21*b02-a20*b04-a23*b00, +a11*b07-a10*b09-a12*b06, +a00*b09-a01*b07+a02*b06, +a31*b01-a30*b03-a32*b00, +a20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0], +mi[0][1],mi[1][1],mi[2][1],mi[3][1], +mi[0][2],mi[1][2],mi[2][2],mi[3][2], +mi[0][3],mi[1][3],mi[2][3],mi[3][3]);} +#endif +#endif +vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale) +{ +#ifdef NORMALXYSCALE +normal=normalize(normal*vec3(scale,scale,1.0)); +#endif +return normalize(cotangentFrame*normal);} +vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale) +{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);} +mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams) +{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);} +#endif +`;s_.v.IncludesShadersStore.bumpFragmentMainFunctions=s6;let s8=`#if defined(BUMP) +#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) +#endif +#if defined(DETAIL) +#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) +#endif +#if defined(BUMP) && defined(PARALLAX) +const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; i<iMaxSamples; i++) +{currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;if (!keepWorking) +{} +else if (currSampledHeight>currRayHeight) +{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} +else +{currRayHeight-=stepSize;vLastOffset=vCurrOffset; +#ifdef PARALLAX_RHS +vCurrOffset-=stepSize*vMaxOffset; +#else +vCurrOffset+=stepSize*vMaxOffset; +#endif +lastSampledHeight=currSampledHeight;}} +return vCurrOffset;} +vec2 parallaxOffset(vec3 viewDir,float heightScale) +{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height; +#ifdef PARALLAX_RHS +return texCoordOffset; +#else +return -texCoordOffset; +#endif +} +#endif +`;s_.v.IncludesShadersStore.bumpFragmentFunctions=s8;let s7=`#ifdef CLIPPLANE +varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +varying float fClipDistance6; +#endif +`;s_.v.IncludesShadersStore.clipPlaneFragmentDeclaration=s7;let s9=`#ifdef LOGARITHMICDEPTH +uniform float logarithmicDepthConstant;varying float vFragmentDepth; +#endif +`;s_.v.IncludesShadersStore.logDepthDeclaration=s9;let ne=`#ifdef FOG +#define FOGMODE_NONE 0. +#define FOGMODE_EXP 1. +#define FOGMODE_EXP2 2. +#define FOGMODE_LINEAR 3. +#define E 2.71828 +uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() +{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) +{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} +else if (FOGMODE_EXP==vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDensity);} +else if (FOGMODE_EXP2==vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} +return clamp(fogCoeff,0.0,1.0);} +#endif +`;s_.v.IncludesShadersStore.fogFragmentDeclaration=ne;let nt=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +if (false) {} +#endif +#ifdef CLIPPLANE +else if (fClipDistance>0.0) +{discard;} +#endif +#ifdef CLIPPLANE2 +else if (fClipDistance2>0.0) +{discard;} +#endif +#ifdef CLIPPLANE3 +else if (fClipDistance3>0.0) +{discard;} +#endif +#ifdef CLIPPLANE4 +else if (fClipDistance4>0.0) +{discard;} +#endif +#ifdef CLIPPLANE5 +else if (fClipDistance5>0.0) +{discard;} +#endif +#ifdef CLIPPLANE6 +else if (fClipDistance6>0.0) +{discard;} +#endif +`;s_.v.IncludesShadersStore.clipPlaneFragment=nt;let ni=`vec2 uvOffset=vec2(0.0,0.0); +#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) +#ifdef NORMALXYSCALE +float normalScale=1.0; +#elif defined(BUMP) +float normalScale=vBumpInfos.y; +#else +float normalScale=1.0; +#endif +#if defined(TANGENT) && defined(NORMAL) +mat3 TBN=vTBN; +#elif defined(BUMP) +vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); +#else +vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); +#endif +#elif defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +mat3 TBN=vTBN; +#else +vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); +#endif +#endif +#ifdef PARALLAX +mat3 invTBN=transposeMat3(TBN); +#ifdef PARALLAXOCCLUSION +uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); +#else +uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); +#endif +#endif +#ifdef DETAIL +vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); +#endif +#ifdef BUMP +#ifdef OBJECTSPACE_NORMALMAP +#define CUSTOM_FRAGMENT_BUMP_FRAGMENT +normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); +#elif !defined(DETAIL) +normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); +#else +vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; +#if DETAIL_NORMALBLENDMETHOD==0 +detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); +#elif DETAIL_NORMALBLENDMETHOD==1 +detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; +#endif +normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); +#endif +#elif defined(DETAIL) +detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); +#endif +`;s_.v.IncludesShadersStore.bumpFragment=ni;let nr=`#ifdef DECAL +#ifdef GAMMADECAL +decalColor.rgb=toLinearSpace(decalColor.rgb); +#endif +#ifdef DECAL_SMOOTHALPHA +decalColor.a*=decalColor.a; +#endif +surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); +#endif +`;s_.v.IncludesShadersStore.decalFragment=nr;let ns=`#ifdef DEPTHPREPASS +gl_FragColor=vec4(0.,0.,0.,1.0);return; +#endif +`;s_.v.IncludesShadersStore.depthPrePass=ns;let nn=`#ifdef LIGHT{X} +#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) +#else +#ifdef PBR +#ifdef SPOTLIGHT{X} +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(POINTLIGHT{X}) +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(HEMILIGHT{X}) +preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(DIRLIGHT{X}) +preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#endif +preInfo.NdotV=NdotV; +#ifdef SPOTLIGHT{X} +#ifdef LIGHT_FALLOFF_GLTF{X} +preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); +#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) +preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); +#elif defined(LIGHT_FALLOFF_STANDARD{X}) +preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); +#else +preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); +#endif +#elif defined(POINTLIGHT{X}) +#ifdef LIGHT_FALLOFF_GLTF{X} +preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); +#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) +preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); +#elif defined(LIGHT_FALLOFF_STANDARD{X}) +preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); +#else +preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); +#endif +#else +preInfo.attenuation=1.0; +#endif +#ifdef HEMILIGHT{X} +preInfo.roughness=roughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +#ifdef IRIDESCENCE +preInfo.iridescenceIntensity=iridescenceIntensity; +#endif +#ifdef HEMILIGHT{X} +info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); +#elif defined(SS_TRANSLUCENCY) +info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); +#else +info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); +#endif +#ifdef SPECULARTERM +#ifdef ANISOTROPIC +info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#else +info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#endif +#endif +#ifdef SHEEN +#ifdef SHEEN_LINKWITHALBEDO +preInfo.roughness=sheenOut.sheenIntensity; +#else +#ifdef HEMILIGHT{X} +preInfo.roughness=sheenOut.sheenRoughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +#endif +info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#endif +#ifdef CLEARCOAT +#ifdef HEMILIGHT{X} +preInfo.roughness=clearcoatOut.clearCoatRoughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); +#ifdef CLEARCOAT_TINT +absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; +#ifdef SPECULARTERM +info.specular*=absorption; +#endif +#endif +info.diffuse*=info.clearCoat.w; +#ifdef SPECULARTERM +info.specular*=info.clearCoat.w; +#endif +#ifdef SHEEN +info.sheen*=info.clearCoat.w; +#endif +#endif +#else +#ifdef SPOTLIGHT{X} +info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); +#elif defined(HEMILIGHT{X}) +info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); +#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) +info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); +#endif +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X}); +#endif +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) +{ +#ifdef SHADOWCSM_RIGHTHANDED{X} +diff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z; +#else +diff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z; +#endif +if (diff{X}>=0.) {index{X}=i;break;}} +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +if (index{X}>=0) +#endif +{ +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#else +shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#endif +#else +shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; +#endif +#ifndef SHADOWCSMNOBLEND{X} +float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) +{index{X}+=1;float nextShadow=0.; +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#else +nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#endif +#else +nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +shadow=mix(nextShadow,shadow,diffRatio); +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); +#endif +} +#endif +} +#elif defined(SHADOWCLOSEESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPOISSON{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#else +#if defined(SHADOWCUBE{X}) +shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#endif +#ifdef SHADOWONLY +#ifndef SHADOWINUSE +#define SHADOWINUSE +#endif +globalShadow+=shadow;shadowLightCount+=1.0; +#endif +#else +shadow=1.; +#endif +aggShadow+=shadow;numLights+=1.0; +#ifndef SHADOWONLY +#ifdef CUSTOMUSERLIGHTING +diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); +#ifdef SPECULARTERM +specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); +#endif +#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) +diffuseBase+=lightmapColor.rgb*shadow; +#ifdef SPECULARTERM +#ifndef LIGHTMAPNOSPECULAR{X} +specularBase+=info.specular*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef CLEARCOAT +#ifndef LIGHTMAPNOSPECULAR{X} +clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef SHEEN +#ifndef LIGHTMAPNOSPECULAR{X} +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#else +#ifdef SHADOWCSMDEBUG{X} +diffuseBase+=info.diffuse*shadowDebug{X}; +#else +diffuseBase+=info.diffuse*shadow; +#endif +#ifdef SPECULARTERM +specularBase+=info.specular*shadow; +#endif +#ifdef CLEARCOAT +clearCoatBase+=info.clearCoat.rgb*shadow; +#endif +#ifdef SHEEN +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#endif +#endif +`;s_.v.IncludesShadersStore.lightFragment=nn;let na=`#ifdef LOGARITHMICDEPTH +gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; +#endif +`;s_.v.IncludesShadersStore.logDepthFragment=na;let no=`#ifdef FOG +float fog=CalcFogFactor(); +#ifdef PBR +fog=toLinearSpace(fog); +#endif +color.rgb=mix(vFogColor,color.rgb,fog); +#endif +`;s_.v.IncludesShadersStore.fogFragment=no;let nl=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +float fragDepth=gl_FragCoord.z; +#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS +uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; +#endif +ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); +#ifdef USE_REVERSE_DEPTHBUFFER +float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; +#else +float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; +#endif +float alphaMultiplier=1.0-lastFrontColor.a; +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepth>nearestDepth || fragDepth<furthestDepth) { +#else +if (fragDepth<nearestDepth || fragDepth>furthestDepth) { +#endif +return;} +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepth<nearestDepth && fragDepth>furthestDepth) { +#else +if (fragDepth>nearestDepth && fragDepth<furthestDepth) { +#endif +depth.rg=vec2(-fragDepth,fragDepth);return;} +#endif +`;s_.v.IncludesShadersStore.oitFragment=nl;let nh=`#include<__decl__defaultFragment> +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +#include<prePassDeclaration>[SCENE_MRT_COUNT] +#include<oitDeclaration> +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include<mainUVVaryingDeclaration>[1..7] +#include<helperFunctions> +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include<lightsFragmentFunctions> +#include<shadowsFragmentFunctions> +#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) +#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef REFRACTION +#ifdef REFRACTIONMAP_3D +uniform samplerCube refractionCubeSampler; +#else +uniform sampler2D refraction2DSampler; +#endif +#endif +#if defined(SPECULARTERM) +#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) +#endif +#include<fresnelFunction> +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +uniform samplerCube reflectionCubeSampler; +#else +uniform sampler2D reflection2DSampler; +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include<reflectionFunction> +#endif +#include<imageProcessingDeclaration> +#include<imageProcessingFunctions> +#include<bumpFragmentMainFunctions> +#include<bumpFragmentFunctions> +#include<clipPlaneFragmentDeclaration> +#include<logDepthDeclaration> +#include<fogFragmentDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); +#endif +#include<bumpFragment> +#ifdef TWOSIDEDLIGHTING +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +#ifdef DIFFUSE +baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); +#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) +if (baseColor.a<alphaCutOff) +discard; +#endif +#ifdef ALPHAFROMDIFFUSE +alpha*=baseColor.a; +#endif +#define CUSTOM_FRAGMENT_UPDATE_ALPHA +baseColor.rgb*=vDiffuseInfos.y; +#endif +#if defined(DECAL) && !defined(DECAL_AFTER_DETAIL) +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#include<depthPrePass> +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor.rgb*=vColor.rgb; +#endif +#ifdef DETAIL +baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); +#endif +#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE +vec3 baseAmbientColor=vec3(1.,1.,1.); +#ifdef AMBIENT +baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; +#endif +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +#ifdef SPECULARTERM +float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; +#ifdef SPECULAR +vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; +#ifdef GLOSSINESS +glossiness=glossiness*specularMapColor.a; +#endif +#endif +#else +float glossiness=0.; +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +float shadow=1.;float aggShadow=0.;float numLights=0.; +#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +#include<lightFragment>[0..maxSimultaneousLights] +aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); +#ifdef REFRACTION +vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); +#ifdef REFRACTIONMAP_3D +#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); +#endif +#ifdef RGBDREFRACTION +refractionColor.rgb=fromRGBD(refractionColor); +#endif +#ifdef IS_REFRACTION_LINEAR +refractionColor.rgb=toGammaSpace(refractionColor.rgb); +#endif +refractionColor.rgb*=vRefractionInfos.x; +#endif +vec4 reflectionColor=vec4(0.,0.,0.,1.); +#ifdef REFLECTION +vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +vReflectionUVW.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +#ifdef ROUGHNESS +float bias=vReflectionInfos.y; +#ifdef SPECULARTERM +#ifdef SPECULAR +#ifdef GLOSSINESS +bias*=(1.0-specularMapColor.a); +#endif +#endif +#endif +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); +#else +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); +#endif +#else +vec2 coords=vReflectionUVW.xy; +#ifdef REFLECTIONMAP_PROJECTION +coords/=vReflectionUVW.z; +#endif +coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef IS_REFLECTION_LINEAR +reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#ifdef REFLECTIONFRESNEL +float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); +#ifdef REFLECTIONFRESNELFROMSPECULAR +#ifdef SPECULARTERM +reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#endif +#endif +#ifdef REFRACTIONFRESNEL +float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#ifdef OPACITYRGB +opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; +#else +alpha*=opacityMap.a*vOpacityInfos.y; +#endif +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef OPACITYFRESNEL +float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; +#endif +#ifdef ALPHATEST +#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS +if (alpha<alphaCutOff) +discard; +#endif +#ifndef ALPHABLEND +alpha=1.0; +#endif +#endif +vec3 emissiveColor=vEmissiveColor; +#ifdef EMISSIVE +emissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y; +#endif +#ifdef EMISSIVEFRESNEL +float emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb; +#endif +#ifdef DIFFUSEFRESNEL +float diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);diffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb; +#endif +#ifdef EMISSIVEASILLUMINATION +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb; +#else +#ifdef LINKEMISSIVEWITHDIFFUSE +vec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb; +#else +vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb; +#endif +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase*specularColor; +#ifdef SPECULAROVERALPHA +alpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.); +#endif +#else +vec3 finalSpecular=vec3(0.0); +#endif +#ifdef REFLECTIONOVERALPHA +alpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.); +#endif +#ifdef EMISSIVEASILLUMINATION +vec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha); +#else +vec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha); +#endif +#ifdef LIGHTMAP +#ifndef LIGHTMAPEXCLUDED +#ifdef USELIGHTMAPASSHADOWMAP +color.rgb*=lightmapColor.rgb; +#else +color.rgb+=lightmapColor.rgb; +#endif +#endif +#endif +#define CUSTOM_FRAGMENT_BEFORE_FOG +color.rgb=max(color.rgb,0.); +#include<logDepthFragment> +#include<fogFragment> +#ifdef IMAGEPROCESSINGPOSTPROCESS +color.rgb=toLinearSpace(color.rgb); +#else +#ifdef IMAGEPROCESSING +color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); +#endif +#endif +color.a*=visibility; +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_IRRADIANCE +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#if defined(SPECULARTERM) +#if defined(SPECULAR) +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; +#endif +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=color; +#endif +#include<oitFragment> +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} +#endif +#define CUSTOM_FRAGMENT_MAIN_END +} +`;s_.v.ShadersStore.defaultPixelShader=nh;let nu=`#ifdef DECAL +uniform vec4 vDecalInfos;uniform mat4 decalMatrix; +#endif +`;s_.v.IncludesShadersStore.decalVertexDeclaration=nu;let nc=`uniform mat4 viewProjection;uniform mat4 view; +#ifdef DIFFUSE +uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef AMBIENT +uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; +#endif +#ifdef OPACITY +uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; +#endif +#if defined(SPECULAR) && defined(SPECULARTERM) +uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; +#endif +#ifdef REFLECTION +uniform mat4 reflectionMatrix; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos;uniform mat4 detailMatrix; +#endif +#include<decalVertexDeclaration> +#define ADDITIONAL_VERTEX_DECLARATION +`;s_.v.IncludesShadersStore.defaultVertexDeclaration=nc;let nd=`#ifdef UV{X} +attribute vec2 uv{X}; +#endif +`;s_.v.IncludesShadersStore.uvAttributeDeclaration=nd;let np=`#if NUM_BONE_INFLUENCERS>0 +attribute vec4 matricesIndices;attribute vec4 matricesWeights; +#if NUM_BONE_INFLUENCERS>4 +attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; +#endif +#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#ifdef BONETEXTURE +uniform highp sampler2D boneSampler;uniform float boneTextureWidth; +#else +uniform mat4 mBones[BonesPerMesh]; +#ifdef BONES_VELOCITY_ENABLED +uniform mat4 mPreviousBones[BonesPerMesh]; +#endif +#endif +#ifdef BONETEXTURE +#define inline +mat4 readMatrixFromRawSampler(sampler2D smp,float index) +{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} +#endif +#endif +#endif +`;s_.v.IncludesShadersStore.bonesDeclaration=np;let n_=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; +#ifdef INSTANCES +attribute vec4 bakedVertexAnimationSettingsInstanced; +#endif +#define inline +mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) +{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} +#endif +`;s_.v.IncludesShadersStore.bakedVertexAnimationDeclaration=n_;let nf=`#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#ifdef INSTANCESCOLOR +attribute vec4 instanceColor; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; +#ifdef THIN_INSTANCES +uniform mat4 previousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +uniform mat4 previousWorld; +#endif +#endif +`;s_.v.IncludesShadersStore.instancesDeclaration=nf;let nm=`#ifdef PREPASS +#ifdef PREPASS_DEPTH +varying vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#endif +`;s_.v.IncludesShadersStore.prePassVertexDeclaration=nm;let ng=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +varying vec2 v_VARYINGNAME_UV; +#endif +`;s_.v.IncludesShadersStore.samplerVertexDeclaration=ng;let nv=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +varying mat3 vTBN; +#endif +#endif +`;s_.v.IncludesShadersStore.bumpVertexDeclaration=nv;let nx=`#ifdef CLIPPLANE +uniform vec4 vClipPlane;varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;varying float fClipDistance6; +#endif +`;s_.v.IncludesShadersStore.clipPlaneVertexDeclaration=nx;let nT=`#ifdef FOG +varying vec3 vFogDistance; +#endif +`;s_.v.IncludesShadersStore.fogVertexDeclaration=nT;let nS=`#ifdef LIGHT{X} +uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; +#ifdef SPECULARTERM +uniform vec4 vLightSpecular{X}; +#else +vec4 vLightSpecular{X}=vec4(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#elif defined(SHADOWCUBE{X}) +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; +#endif +uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; +#endif +#ifdef SPOTLIGHT{X} +uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; +#elif defined(POINTLIGHT{X}) +uniform vec4 vLightFalloff{X}; +#elif defined(HEMILIGHT{X}) +uniform vec3 vLightGround{X}; +#endif +#endif +`;s_.v.IncludesShadersStore.lightVxFragmentDeclaration=nS;let nC=`#ifdef LIGHT{X} +uniform Light{X} +{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; +#ifdef SPOTLIGHT{X} +vec4 vLightDirection;vec4 vLightFalloff; +#elif defined(POINTLIGHT{X}) +vec4 vLightFalloff; +#elif defined(HEMILIGHT{X}) +vec3 vLightGround; +#endif +vec4 shadowsInfo;vec2 depthValues;} light{X}; +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#elif defined(SHADOWCUBE{X}) +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`;s_.v.IncludesShadersStore.lightVxUboDeclaration=nC;let nE=`#ifdef MORPHTARGETS +uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; +#ifdef MORPHTARGETS_TEXTURE +uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) +{ +float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} +#endif +#endif +`;s_.v.IncludesShadersStore.morphTargetsVertexGlobalDeclaration=nE;let nb=`#ifdef MORPHTARGETS +#ifndef MORPHTARGETS_TEXTURE +attribute vec3 position{X}; +#ifdef MORPHTARGETS_NORMAL +attribute vec3 normal{X}; +#endif +#ifdef MORPHTARGETS_TANGENT +attribute vec3 tangent{X}; +#endif +#ifdef MORPHTARGETS_UV +attribute vec2 uv_{X}; +#endif +#endif +#endif +`;s_.v.IncludesShadersStore.morphTargetsVertexDeclaration=nb;let ny=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +float vertexID; +#endif +#endif +`;s_.v.IncludesShadersStore.morphTargetsVertexGlobal=ny;let nP=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];vertexID+=1.0; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}]; +#endif +#else +positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; +#endif +#endif +#endif +`;s_.v.IncludesShadersStore.morphTargetsVertex=nP;let nR=`#ifdef INSTANCES +mat4 finalWorld=mat4(world0,world1,world2,world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +finalWorld=world*finalWorld; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +mat4 finalWorld=world; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +mat4 finalPreviousWorld=previousWorld; +#endif +#endif +`;s_.v.IncludesShadersStore.instancesVertex=nR;let nA=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#if NUM_BONE_INFLUENCERS>0 +mat4 influence; +#ifdef BONETEXTURE +influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; +#endif +#else +influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#endif +`;s_.v.IncludesShadersStore.bonesVertex=nA;let nI=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +{ +#ifdef INSTANCES +#define BVASNAME bakedVertexAnimationSettingsInstanced +#else +#define BVASNAME bakedVertexAnimationSettings +#endif +float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; +#endif +finalWorld=finalWorld*VATInfluence;} +#endif +`;s_.v.IncludesShadersStore.bakedVertexAnimation=nI;let nM=`#ifdef PREPASS_DEPTH +vViewPos=(view*worldPos).rgb; +#endif +#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*worldPos; +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +`;s_.v.IncludesShadersStore.prePassVertex=nM;let nD=`#if !defined(UV{X}) && defined(MAINUV{X}) +vec2 uv{X}=vec2(0.,0.); +#endif +#ifdef MAINUV{X} +vMainUV{X}=uv{X}; +#endif +`;s_.v.IncludesShadersStore.uvVariableDeclaration=nD;let nO=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +if (v_INFONAME_==0.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} +#ifdef UV2 +else if (v_INFONAME_==1.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));} +#endif +#ifdef UV3 +else if (v_INFONAME_==2.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} +#endif +#ifdef UV4 +else if (v_INFONAME_==3.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} +#endif +#ifdef UV5 +else if (v_INFONAME_==4.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} +#endif +#ifdef UV6 +else if (v_INFONAME_==5.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} +#endif +#endif +`;s_.v.IncludesShadersStore.samplerVertexImplementation=nO;let nN=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); +#endif +#endif +`;s_.v.IncludesShadersStore.bumpVertex=nN;let nF=`#ifdef CLIPPLANE +fClipDistance=dot(worldPos,vClipPlane); +#endif +#ifdef CLIPPLANE2 +fClipDistance2=dot(worldPos,vClipPlane2); +#endif +#ifdef CLIPPLANE3 +fClipDistance3=dot(worldPos,vClipPlane3); +#endif +#ifdef CLIPPLANE4 +fClipDistance4=dot(worldPos,vClipPlane4); +#endif +#ifdef CLIPPLANE5 +fClipDistance5=dot(worldPos,vClipPlane5); +#endif +#ifdef CLIPPLANE6 +fClipDistance6=dot(worldPos,vClipPlane6); +#endif +`;s_.v.IncludesShadersStore.clipPlaneVertex=nF;let nB=`#ifdef FOG +vFogDistance=(view*worldPos).xyz; +#endif +`;s_.v.IncludesShadersStore.fogVertex=nB;let nL=`#ifdef SHADOWS +#if defined(SHADOWCSM{X}) +vPositionFromCamera{X}=view*worldPos;for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos; +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y; +#else +vDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y; +#endif +} +#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X}) +vPositionFromLight{X}=lightMatrix{X}*worldPos; +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#else +vDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; +#endif +#endif +#endif +`;s_.v.IncludesShadersStore.shadowsVertex=nL;let nw=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +vColor=vec4(1.0); +#ifdef VERTEXCOLOR +#ifdef VERTEXALPHA +vColor*=color; +#else +vColor.rgb*=color.rgb; +#endif +#endif +#ifdef INSTANCESCOLOR +vColor*=instanceColor; +#endif +#endif +`;s_.v.IncludesShadersStore.vertexColorMixing=nw;let nU=`#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +`;s_.v.IncludesShadersStore.pointCloudVertex=nU;let nV=`#ifdef LOGARITHMICDEPTH +vFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant; +#endif +`;s_.v.IncludesShadersStore.logDepthVertex=nV;let nk=`#include<__decl__defaultVertex> +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include<uvAttributeDeclaration>[2..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include<helperFunctions> +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<instancesDeclaration> +#include<prePassVertexDeclaration> +#include<mainUVVaryingDeclaration>[1..7] +#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) +#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#if defined(SPECULARTERM) +#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) +#endif +#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include<bumpVertexDeclaration> +#include<clipPlaneVertexDeclaration> +#include<fogVertexDeclaration> +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include<logDepthDeclaration> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include<instancesVertex> +#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +vPositionW=vec3(worldPos); +#include<prePassVertex> +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#include<uvVariableDeclaration>[2..7] +#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#if defined(SPECULARTERM) +#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) +#endif +#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#include<bumpVertex> +#include<clipPlaneVertex> +#include<fogVertex> +#include<shadowsVertex>[0..maxSimultaneousLights] +#include<vertexColorMixing> +#include<pointCloudVertex> +#include<logDepthVertex> +#define CUSTOM_VERTEX_MAIN_END +} +`;s_.v.ShadersStore.defaultVertexShader=nk;var nG=i(7790);let nz=RegExp("^([gimus]+)!");let MaterialPluginManager=class MaterialPluginManager{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e.name)return!1;if(this._material._uniformBufferLayoutBuilt)throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because this material has already been used for rendering! Please add plugins to materials before any rendering with this material occurs.`;let t=e.getClassName();MaterialPluginManager._MaterialPluginClassToMainDefine[t]||(MaterialPluginManager._MaterialPluginClassToMainDefine[t]="MATERIALPLUGIN_"+ ++MaterialPluginManager._MaterialPluginCounter),this._material._callbackPluginEventGeneric=(e,t)=>this._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort((e,t)=>e.priority-t.priority),this._codeInjectionPoints={};let i={};for(let e of(i[MaterialPluginManager._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0},this._plugins))e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.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;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null}_handlePluginEventIsReadyForSubMesh(e){let t=!0;for(let i of this._activePlugins)t=t&&i.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh);e.isReadyForSubMesh=t}_handlePluginEventPrepareDefinesBeforeAttributes(e){for(let t of this._activePlugins)t.prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)}_handlePluginEventPrepareDefines(e){for(let t of this._activePlugins)t.prepareDefines(e.defines,this._scene,e.mesh)}_handlePluginEventHardBindForSubMesh(e){for(let t of this._activePluginsForExtraEvents)t.hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventBindForSubMesh(e){for(let t of this._activePlugins)t.bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventHasRenderTargetTextures(e){let t=!1;for(let e of this._activePluginsForExtraEvents)if(t=e.hasRenderTargetTextures())break;e.hasRenderTargetTextures=t}_handlePluginEventFillRenderTargetTextures(e){for(let t of this._activePluginsForExtraEvents)t.fillRenderTargetTextures(e.renderTargets)}_handlePluginEvent(e,t){var i;switch(e){case sG.S.GetActiveTextures:for(let e of this._activePlugins)e.getActiveTextures(t.activeTextures);break;case sG.S.GetAnimatables:for(let e of this._activePlugins)e.getAnimatables(t.animatables);break;case sG.S.HasTexture:{let e=!1;for(let i of this._activePlugins)if(e=i.hasTexture(t.texture))break;t.hasTexture=e;break}case sG.S.Disposed:for(let e of this._plugins)e.dispose(t.forceDisposeTextures);break;case sG.S.GetDefineNames:t.defineNames=this._defineNamesFromPlugins;break;case sG.S.PrepareEffect:for(let e of this._activePlugins)t.fallbackRank=e.addFallbacks(t.defines,t.fallbacks,t.fallbackRank),e.getAttributes(t.attributes,this._scene,t.mesh);this._uniformList.length>0&&t.uniforms.push(...this._uniformList),this._samplerList.length>0&&t.samplers.push(...this._samplerList),this._uboList.length>0&&t.uniformBuffersNames.push(...this._uboList),t.customCode=this._injectCustomCode(t,t.customCode);break;case sG.S.PrepareUniformBuffer:for(let e of(this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[],this._plugins)){let r=e.getUniforms();if(r){if(r.ubo)for(let e of r.ubo){if(e.size&&e.type){let r=null!==(i=e.arraySize)&&void 0!==i?i:0;t.ubo.addUniform(e.name,e.size,r),this._uboDeclaration+=`${e.type} ${e.name}${r>0?`[${r}]`:""}; +`}this._uniformList.push(e.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\n")}e.getSamplers(this._samplerList),e.getUniformBuffersNames(this._uboList)}}}_collectPointNames(e,t){if(t)for(let i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var s,n;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));let a=null===(s=this._codeInjectionPoints)||void 0===s?void 0:s[i];if(!a)return r;let o=null;for(let t in a){let s="";for(let r of this._activePlugins){let a=null===(n=r.getCustomCode(i))||void 0===n?void 0:n[t];if(a){if(r.resolveIncludes){if(null===o){let t=sg.x.GLSL;o={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:s_.v.GetShadersRepository(t),includesShadersStore:s_.v.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}o.isFragment="fragment"===i,nG.L._ProcessIncludes(a,o,e=>a=e)}s+=a+"\n"}}if(s.length>0){if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{let i=nz.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}0>e.indexOf("g")&&(e+="g");let i=r,n=new RegExp(t,e),a=n.exec(i);for(;null!==a;){let e=s;for(let t=0;t<a.length;++t)e=e.replace("$"+t,a[t]);r=r.replace(a[0],e),a=n.exec(i)}}else{let e="#define "+t;r=r.replace(e,"\n"+s+"\n"+e)}}}return r}}};MaterialPluginManager._MaterialPluginClassToMainDefine={},MaterialPluginManager._MaterialPluginCounter=0,rS.l.OnEnginesDisposedObservable.add(()=>{UnregisterAllMaterialPlugins()});let nW=[],nH=null;function UnregisterAllMaterialPlugins(){nW.length=0,sr.F.OnEventObservable.remove(nH),nH=null}let MaterialPluginBase=class MaterialPluginBase{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,r,s=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new MaterialPluginManager(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(let t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;let 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){rb.p4.Clone(()=>e,this)}serialize(){return rb.p4.Serialize(this)}parse(e,t,i){rb.p4.Parse(()=>this,e,t,i)}};(0,rH.gn)([(0,rb.qC)()],MaterialPluginBase.prototype,"name",void 0),(0,rH.gn)([(0,rb.qC)()],MaterialPluginBase.prototype,"priority",void 0),(0,rH.gn)([(0,rb.qC)()],MaterialPluginBase.prototype,"resolveIncludes",void 0),(0,rH.gn)([(0,rb.qC)()],MaterialPluginBase.prototype,"registerForExtraEvents",void 0);let MaterialDetailMapDefines=class MaterialDetailMapDefines extends sn.H{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}};let material_detailMapConfiguration_DetailMapConfiguration=class material_detailMapConfiguration_DetailMapConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new MaterialDetailMapDefines,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=sr.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||!MaterialFlags.DetailTextureEnabled||!!this._texture.isReady()}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;let i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&MaterialFlags.DetailTextureEnabled&&this._isEnabled?(so.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;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||!this._texture||!MaterialFlags.DetailTextureEnabled||(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),so.G.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&MaterialFlags.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,rH.gn)([(0,rb.oU)("detailTexture"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"texture",void 0),(0,rH.gn)([(0,rb.qC)()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"diffuseBlendLevel",void 0),(0,rH.gn)([(0,rb.qC)()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"roughnessBlendLevel",void 0),(0,rH.gn)([(0,rb.qC)()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"bumpLevel",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"normalBlendMethod",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"isEnabled",void 0);var nX=i(6962);let nY={effect:null,subMesh:null};let StandardMaterialDefines=class StandardMaterialDefines extends sn.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.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!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.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){for(let t of["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"])this[t]=t===e}};let standardMaterial_StandardMaterial=class standardMaterial_StandardMaterial extends PushMaterial{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new rg.Wo(0,0,0),this.diffuseColor=new rg.Wo(1,1,1),this.specularColor=new rg.Wo(1,1,1),this.emissiveColor=new rg.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._applyDecalMapAfterDetailMap=!1,this._renderTargets=new sp.t(16),this._worldViewProjectionMatrix=rm.y3.Zero(),this._globalAmbientColor=new rg.Wo(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new material_detailMapConfiguration_DetailMapConfiguration(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new PrePassConfiguration,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),standardMaterial_StandardMaterial.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),standardMaterial_StandardMaterial.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!!standardMaterial_StandardMaterial.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||!!standardMaterial_StandardMaterial.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===sr.F.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==sr.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(sG.S.GetDefineNames,this._eventInfo),t.materialDefines=new StandardMaterialDefines(this._eventInfo.defineNames));let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();s._needNormals=so.G.PrepareDefinesForLights(r,e,s,!0,this._maxSimultaneousLights,this._disableLighting),so.G.PrepareDefinesForMultiview(r,s);let a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(so.G.PrepareDefinesForPrePass(r,s,this.canRenderToMRT&&!a),so.G.PrepareDefinesForOIT(r,s,a),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(r.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&&standardMaterial_StandardMaterial.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&standardMaterial_StandardMaterial.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===texture_Texture.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 texture_Texture.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case texture_Texture.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case texture_Texture.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case texture_Texture.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case texture_Texture.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case texture_Texture.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case texture_Texture.CUBIC_MODE:case texture_Texture.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&&standardMaterial_StandardMaterial.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&standardMaterial_StandardMaterial.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;so.G.PrepareDefinesForMergedUV(this._bumpTexture,s,"BUMP"),s.PARALLAX=this._useParallax,s.PARALLAX_RHS=r.useRightHandedSystem,s.PARALLAXOCCLUSION=this._useParallaxOcclusion,s.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else s.BUMP=!1,s.PARALLAX=!1,s.PARALLAX_RHS=!1,s.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&standardMaterial_StandardMaterial.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&&(standardMaterial_StandardMaterial.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),so.G.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s,this._applyDecalMapAfterDetailMap),so.G.PrepareDefinesForFrameBoundValues(r,n,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),so.G.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let o=!1;if(s.isDirty){let i=s._areLightsDisposed;s.markAsProcessed();let a=new EffectFallbacks;s.REFLECTION&&a.addFallback(0,"REFLECTION"),s.SPECULAR&&a.addFallback(0,"SPECULAR"),s.BUMP&&a.addFallback(0,"BUMP"),s.PARALLAX&&a.addFallback(1,"PARALLAX"),s.PARALLAX_RHS&&a.addFallback(1,"PARALLAX_RHS"),s.PARALLAXOCCLUSION&&a.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&a.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&a.addFallback(1,"FOG"),s.POINTSIZE&&a.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&a.addFallback(0,"LOGARITHMICDEPTH"),so.G.HandleFallbacksForShadows(s,a,this._maxSimultaneousLights),s.SPECULARTERM&&a.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&a.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&a.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&a.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&a.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&a.addFallback(4,"FRESNEL"),s.MULTIVIEW&&a.addFallback(0,"MULTIVIEW");let l=[rz.o.PositionKind];s.NORMAL&&l.push(rz.o.NormalKind),s.TANGENT&&l.push(rz.o.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(rz.o.ColorKind),so.G.PrepareAttributesForBones(l,e,s,a),so.G.PrepareAttributesForInstances(l,s),so.G.PrepareAttributesForMorphTargets(l,e,s),so.G.PrepareAttributesForBakedVertexAnimation(l,e,s);let h="default",u=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],c=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],p={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=a,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=u,this._eventInfo.attributes=l,this._eventInfo.samplers=c,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=p,this._callbackPluginEventGeneric(sG.S.PrepareEffect,this._eventInfo),PrePassConfiguration.AddUniforms(u),PrePassConfiguration.AddSamplers(c),sv.$&&(sv.$.PrepareUniforms(u,s),sv.$.PrepareSamplers(c,s)),so.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:d,samplers:c,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),(0,nX.qx)(u);let _={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,u,d,c,s,l,_));let f=s.toString(),m=t.effect,g=r.getEngine().createEffect(h,{attributes:l,uniformsNames:u,uniformBuffersNames:d,samplers:c,defines:f,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError,indexParameters:p,processFinalCode:_.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},n);if(this._eventInfo.customCode=void 0,g){if(this._onEffectCreatedObservable&&(nY.effect=g,nY.subMesh=t,this._onEffectCreatedObservable.notifyObservers(nY)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,s.markAsUnprocessed(),o=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!o,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let 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 r;let s=this.getScene(),n=i.materialDefines;if(!n)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let o=a._forceRebindOnNextCall||this._mustRebind(s,a,t.visibility);so.G.BindBonesParameters(t,a);let l=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!l.useUbo||!this.isFrozen||!l.isSync||a._forceRebindOnNextCall){if(standardMaterial_StandardMaterial.FresnelEnabled&&n.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new rg.Wo(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&standardMaterial_StandardMaterial.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),so.G.BindTextureMatrix(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),so.G.BindTextureMatrix(this._ambientTexture,l,"ambient")),this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),so.G.BindTextureMatrix(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&standardMaterial_StandardMaterial.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){let e=this._reflectionTexture;l.updateVector3("vReflectionPosition",e.boundingBoxPosition),l.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&standardMaterial_StandardMaterial.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),so.G.BindTextureMatrix(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),so.G.BindTextureMatrix(this._lightmapTexture,l,"lightmap")),this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),so.G.BindTextureMatrix(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&standardMaterial_StandardMaterial.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),so.G.BindTextureMatrix(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&standardMaterial_StandardMaterial.RefractionTextureEnabled){let e=1;if(!this._refractionTexture.isCube&&(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){let e=this._refractionTexture;l.updateVector3("vRefractionPosition",e.boundingBoxPosition),l.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),n.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",standardMaterial_StandardMaterial.EmissiveTextureEnabled?this.emissiveColor:rg.Wo.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&standardMaterial_StandardMaterial.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&standardMaterial_StandardMaterial.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&standardMaterial_StandardMaterial.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&standardMaterial_StandardMaterial.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&standardMaterial_StandardMaterial.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,nX.an)(a,this,s),this.bindEyePosition(a)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&so.G.BindLights(s,t,a,n,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==rN.x.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(a),so.G.BindFogParameters(s,t,a),n.NUM_MORPH_INFLUENCERS&&so.G.BindMorphTargetParameters(t,a),n.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(r=t.bakedVertexAnimationManager)||void 0===r||r.bind(a,n.INSTANCES)),this.useLogarithmicDepth&&so.G.BindLogDepth(n,a,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),l.update()}getAnimatables(){let 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(){let 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,r,s,n,a,o,l,h,u;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(n=this._reflectionTexture)||void 0===n||n.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._specularTexture)||void 0===o||o.dispose(),null===(l=this._bumpTexture)||void 0===l||l.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(u=this._refractionTexture)||void 0===u||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){let r=rb.p4.Clone(()=>new standardMaterial_StandardMaterial(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){let r=rb.p4.Parse(()=>new standardMaterial_StandardMaterial(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),sr.F._parsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return MaterialFlags.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){MaterialFlags.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return MaterialFlags.DetailTextureEnabled}static set DetailTextureEnabled(e){MaterialFlags.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return MaterialFlags.AmbientTextureEnabled}static set AmbientTextureEnabled(e){MaterialFlags.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return MaterialFlags.OpacityTextureEnabled}static set OpacityTextureEnabled(e){MaterialFlags.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return MaterialFlags.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){MaterialFlags.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return MaterialFlags.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){MaterialFlags.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return MaterialFlags.SpecularTextureEnabled}static set SpecularTextureEnabled(e){MaterialFlags.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return MaterialFlags.BumpTextureEnabled}static set BumpTextureEnabled(e){MaterialFlags.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return MaterialFlags.LightmapTextureEnabled}static set LightmapTextureEnabled(e){MaterialFlags.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return MaterialFlags.RefractionTextureEnabled}static set RefractionTextureEnabled(e){MaterialFlags.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return MaterialFlags.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){MaterialFlags.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return MaterialFlags.FresnelEnabled}static set FresnelEnabled(e){MaterialFlags.FresnelEnabled=e}};(0,rH.gn)([(0,rb.oU)("diffuseTexture")],standardMaterial_StandardMaterial.prototype,"_diffuseTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"diffuseTexture",void 0),(0,rH.gn)([(0,rb.oU)("ambientTexture")],standardMaterial_StandardMaterial.prototype,"_ambientTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"ambientTexture",void 0),(0,rH.gn)([(0,rb.oU)("opacityTexture")],standardMaterial_StandardMaterial.prototype,"_opacityTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"opacityTexture",void 0),(0,rH.gn)([(0,rb.oU)("reflectionTexture")],standardMaterial_StandardMaterial.prototype,"_reflectionTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"reflectionTexture",void 0),(0,rH.gn)([(0,rb.oU)("emissiveTexture")],standardMaterial_StandardMaterial.prototype,"_emissiveTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"emissiveTexture",void 0),(0,rH.gn)([(0,rb.oU)("specularTexture")],standardMaterial_StandardMaterial.prototype,"_specularTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"specularTexture",void 0),(0,rH.gn)([(0,rb.oU)("bumpTexture")],standardMaterial_StandardMaterial.prototype,"_bumpTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"bumpTexture",void 0),(0,rH.gn)([(0,rb.oU)("lightmapTexture")],standardMaterial_StandardMaterial.prototype,"_lightmapTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"lightmapTexture",void 0),(0,rH.gn)([(0,rb.oU)("refractionTexture")],standardMaterial_StandardMaterial.prototype,"_refractionTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"refractionTexture",void 0),(0,rH.gn)([(0,rb.n9)("ambient")],standardMaterial_StandardMaterial.prototype,"ambientColor",void 0),(0,rH.gn)([(0,rb.n9)("diffuse")],standardMaterial_StandardMaterial.prototype,"diffuseColor",void 0),(0,rH.gn)([(0,rb.n9)("specular")],standardMaterial_StandardMaterial.prototype,"specularColor",void 0),(0,rH.gn)([(0,rb.n9)("emissive")],standardMaterial_StandardMaterial.prototype,"emissiveColor",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"specularPower",void 0),(0,rH.gn)([(0,rb.qC)("useAlphaFromDiffuseTexture")],standardMaterial_StandardMaterial.prototype,"_useAlphaFromDiffuseTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"useAlphaFromDiffuseTexture",void 0),(0,rH.gn)([(0,rb.qC)("useEmissiveAsIllumination")],standardMaterial_StandardMaterial.prototype,"_useEmissiveAsIllumination",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useEmissiveAsIllumination",void 0),(0,rH.gn)([(0,rb.qC)("linkEmissiveWithDiffuse")],standardMaterial_StandardMaterial.prototype,"_linkEmissiveWithDiffuse",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"linkEmissiveWithDiffuse",void 0),(0,rH.gn)([(0,rb.qC)("useSpecularOverAlpha")],standardMaterial_StandardMaterial.prototype,"_useSpecularOverAlpha",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useSpecularOverAlpha",void 0),(0,rH.gn)([(0,rb.qC)("useReflectionOverAlpha")],standardMaterial_StandardMaterial.prototype,"_useReflectionOverAlpha",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useReflectionOverAlpha",void 0),(0,rH.gn)([(0,rb.qC)("disableLighting")],standardMaterial_StandardMaterial.prototype,"_disableLighting",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],standardMaterial_StandardMaterial.prototype,"disableLighting",void 0),(0,rH.gn)([(0,rb.qC)("useObjectSpaceNormalMap")],standardMaterial_StandardMaterial.prototype,"_useObjectSpaceNormalMap",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useObjectSpaceNormalMap",void 0),(0,rH.gn)([(0,rb.qC)("useParallax")],standardMaterial_StandardMaterial.prototype,"_useParallax",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useParallax",void 0),(0,rH.gn)([(0,rb.qC)("useParallaxOcclusion")],standardMaterial_StandardMaterial.prototype,"_useParallaxOcclusion",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useParallaxOcclusion",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"parallaxScaleBias",void 0),(0,rH.gn)([(0,rb.qC)("roughness")],standardMaterial_StandardMaterial.prototype,"_roughness",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"roughness",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"indexOfRefraction",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"invertRefractionY",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"alphaCutOff",void 0),(0,rH.gn)([(0,rb.qC)("useLightmapAsShadowmap")],standardMaterial_StandardMaterial.prototype,"_useLightmapAsShadowmap",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useLightmapAsShadowmap",void 0),(0,rH.gn)([(0,rb.qQ)("diffuseFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_diffuseFresnelParameters",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"diffuseFresnelParameters",void 0),(0,rH.gn)([(0,rb.qQ)("opacityFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_opacityFresnelParameters",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"opacityFresnelParameters",void 0),(0,rH.gn)([(0,rb.qQ)("reflectionFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_reflectionFresnelParameters",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"reflectionFresnelParameters",void 0),(0,rH.gn)([(0,rb.qQ)("refractionFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_refractionFresnelParameters",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"refractionFresnelParameters",void 0),(0,rH.gn)([(0,rb.qQ)("emissiveFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_emissiveFresnelParameters",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"emissiveFresnelParameters",void 0),(0,rH.gn)([(0,rb.qC)("useReflectionFresnelFromSpecular")],standardMaterial_StandardMaterial.prototype,"_useReflectionFresnelFromSpecular",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"useReflectionFresnelFromSpecular",void 0),(0,rH.gn)([(0,rb.qC)("useGlossinessFromSpecularMapAlpha")],standardMaterial_StandardMaterial.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useGlossinessFromSpecularMapAlpha",void 0),(0,rH.gn)([(0,rb.qC)("maxSimultaneousLights")],standardMaterial_StandardMaterial.prototype,"_maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],standardMaterial_StandardMaterial.prototype,"maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.qC)("invertNormalMapX")],standardMaterial_StandardMaterial.prototype,"_invertNormalMapX",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"invertNormalMapX",void 0),(0,rH.gn)([(0,rb.qC)("invertNormalMapY")],standardMaterial_StandardMaterial.prototype,"_invertNormalMapY",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"invertNormalMapY",void 0),(0,rH.gn)([(0,rb.qC)("twoSidedLighting")],standardMaterial_StandardMaterial.prototype,"_twoSidedLighting",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"twoSidedLighting",void 0),(0,rH.gn)([(0,rb.qC)("applyDecalMapAfterDetailMap")],standardMaterial_StandardMaterial.prototype,"_applyDecalMapAfterDetailMap",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],standardMaterial_StandardMaterial.prototype,"applyDecalMapAfterDetailMap",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"useLogarithmicDepth",null),(0,rv.H)("BABYLON.StandardMaterial",standardMaterial_StandardMaterial),rN.x.DefaultMaterialFactory=e=>new standardMaterial_StandardMaterial("default material",e),r6.B.prototype.createDynamicTexture=function(e,t,i,r){let s=new r5.l(this,r5.S.Dynamic);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?r6.B.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?r6.B.GetExponentOfTwo(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=r,this.updateTextureSamplingMode(r,s),this._internalTexturesCache.push(s),s},r6.B.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,n=!1,a=!1){if(!e)return;let o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);let u=this._getWebGLTextureType(e.type),c=this._getInternalFormat(s||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,c);o.texImage2D(l,0,d,c,u,t),e.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0};let DynamicTexture=class DynamicTexture extends texture_Texture{constructor(e,t,i=null,r=!1,s=3,n=5,a){super(null,i,!r,a,s,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=r;let o=this._getEngine();if(!o)return;t.getContext?(this._canvas=t,this._texture=o.createDynamicTexture(t.width,t.height,r,s)):(this._canvas=o.createCanvas(1,1),t.width||0===t.width?this._texture=o.createDynamicTexture(t.width,t.height,r,s):this._texture=o.createDynamicTexture(t,t,r,s));let 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){let t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){let i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(){let 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,r,s,n,a,o=!0){let l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null==t){let i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){let e=parseInt(r.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),o&&this.update(a)}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new DynamicTexture(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(){let e=this.getScene();e&&!e.isReady()&&rT.Y.Warn("The scene must be ready before serializing the dynamic texture");let t=super.serialize();return DynamicTexture._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()}};let WebXRLayerWrapper=class WebXRLayerWrapper{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){this.isFixedFoveationSupported&&(this.layer.fixedFoveation=Math.max(0,Math.min(1,e||0)))}constructor(e,t,i,r,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.createRenderTargetTextureProvider=s}};var nj=i(5342);let WebXRLayerRenderTargetTextureProvider=class WebXRLayerRenderTargetTextureProvider{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=[],this._engine=e.getEngine()}_createInternalTexture(e,t){let i=new r5.l(this._engine,r5.S.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new nj.B(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,s,n){if(!this._engine)throw Error("Engine is disposed");let a={width:e,height:t},o=n?new MultiviewRenderTarget(this._scene,a):new renderTargetTexture_RenderTargetTexture("XR renderTargetTexture",a,this._scene),l=o.renderTarget;if(l._samples=o.samples,(i||!r)&&(l._framebuffer=i),r){if(n)l._colorTextureArray=r;else{let e=this._createInternalTexture(a,r);l.setTexture(e,0),o._texture=e}}return s&&(n?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(a,s)),o.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(o.skipInitialClear=!0),this._renderTargetTextures.push(o),o}_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}};let WebXRWebGLLayerWrapper=class WebXRWebGLLayerWrapper extends WebXRLayerWrapper{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new WebXRWebGLLayerRenderTargetTextureProvider(e.scene,this)),this.layer=e}};let WebXRWebGLLayerRenderTargetTextureProvider=class WebXRWebGLLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{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){let i=this._layer.getViewport(t);if(!i)return!1;let r=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/s,e.width=i.width/r,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){let t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&r===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}};let WebXRManagedOutputCanvasOptions=class WebXRManagedOutputCanvasOptions{static GetDefaults(e){let t=new WebXRManagedOutputCanvasOptions;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}};let WebXRManagedOutputCanvas=class WebXRManagedOutputCanvas{constructor(e,t=WebXRManagedOutputCanvasOptions.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new rf.y$,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{let 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){let createLayer=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new WebXRWebGLLayerWrapper(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{rW.w1.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")}).then(()=>createLayer()):Promise.resolve(createLayer())}_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)}};let NativeXRLayerWrapper=class NativeXRLayerWrapper extends WebXRLayerWrapper{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new NativeXRLayerRenderTargetTextureProvider(e,this)),this.layer=e}};let NativeXRLayerRenderTargetTextureProvider=class NativeXRLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{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}}};let NativeXRRenderTarget=class NativeXRRenderTarget{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(){}};let WebXRSessionManager=class WebXRSessionManager{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new rf.y$,this.onXRReferenceSpaceChanged=new rf.y$,this.onXRSessionEnded=new rf.y$,this.onXRSessionInit=new rf.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(()=>{rT.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){let t=this.scene.getEngine();return this._xrNavigator.xr.native?new NativeXRRenderTarget(this):((e=e||WebXRManagedOutputCanvasOptions.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new WebXRManagedOutputCanvas(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 WebXRSessionManager.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),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=>(rT.Y.Error("XR.requestReferenceSpace failed for the following reason: "),rT.Y.Error(e),rT.Y.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(e=>{let t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)},e=>{throw rT.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 NativeXRLayerWrapper(e.baseLayer):new WebXRWebGLLayerWrapper(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);let t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(e=>Promise.resolve(void 0===e||e)).catch(e=>(rT.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){this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=Math.max(0,Math.min(1,e||0)))}get enabledFeatures(){var e,t;return null!==(t=null===(e=this.session)||void 0===e?void 0:e.enabledFeatures)&&void 0!==t?t:null}};(M=tw||(tw={}))[M.ENTERING_XR=0]="ENTERING_XR",M[M.EXITING_XR=1]="EXITING_XR",M[M.IN_XR=2]="IN_XR",M[M.NOT_IN_XR=3]="NOT_IN_XR",(D=tU||(tU={}))[D.NOT_TRACKING=0]="NOT_TRACKING",D[D.TRACKING_LOST=1]="TRACKING_LOST",D[D.TRACKING=2]="TRACKING",rV.Kj._GroundMeshParser=(e,t)=>GroundMesh.Parse(e,t);let GroundMesh=class GroundMesh extends rV.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),this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){let i=this.getWorldMatrix(),r=rm.jp.Matrix[5];i.invertToRef(r);let s=rm.jp.Vector3[8];if(rm.P.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return rm.P.TransformCoordinatesFromFloatsToRef(0,a,0,i,s),s.y}getNormalAtCoordinates(e,t){let i=new rm.P(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){let r=this.getWorldMatrix(),s=rm.jp.Matrix[5];r.invertToRef(s);let n=rm.jp.Vector3[8];if(rm.P.TransformCoordinatesFromFloatsToRef(e,0,t,s,n),e=n.x,t=n.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let a=this._getFacetAt(e,t);return rm.P.TransformNormalFromFloatsToRef(a.x,a.y,a.z,r,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){let i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i];return t<s.slope.x*e+s.slope.y?s.facet1:s.facet2}_initHeightQuads(){let e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=[];for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r={slope:rm.FM.Zero(),facet1:new rm.Lt(0,0,0,0),facet2:new rm.Lt(0,0,0,0)};this._heightQuads[i*e+t]=r}return this}_computeHeightQuads(){let e=this.getVerticesData(rz.o.PositionKind);if(!e)return this;let t=rm.jp.Vector3[3],i=rm.jp.Vector3[2],r=rm.jp.Vector3[1],s=rm.jp.Vector3[0],n=rm.jp.Vector3[4],a=rm.jp.Vector3[5],o=rm.jp.Vector3[6],l=rm.jp.Vector3[7],h=rm.jp.Vector3[8],u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=this._subdivisionsX,v=this._subdivisionsY;for(let x=0;x<v;x++)for(let v=0;v<g;v++){u=3*v,c=x*(g+1)*3,d=(x+1)*(g+1)*3,t.x=e[c+u],t.y=e[c+u+1],t.z=e[c+u+2],i.x=e[c+u+3],i.y=e[c+u+4],i.z=e[c+u+5],r.x=e[d+u],r.y=e[d+u+1],r.z=e[d+u+2],s.x=e[d+u+3],s.y=e[d+u+4],s.z=e[d+u+5],p=(s.z-t.z)/(s.x-t.x),_=t.z-p*t.x,i.subtractToRef(t,n),r.subtractToRef(t,a),s.subtractToRef(t,o),rm.P.CrossToRef(o,a,l),rm.P.CrossToRef(n,o,h),l.normalize(),h.normalize(),f=-(l.x*t.x+l.y*t.y+l.z*t.z),m=-(h.x*i.x+h.y*i.y+h.z*i.z);let T=this._heightQuads[x*g+v];T.slope.copyFromFloats(p,_),T.facet1.copyFromFloats(l.x,l.y,l.z,f),T.facet2.copyFromFloats(h.x,h.y,h.z,m)}return this}serialize(e){super.serialize(e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height}static Parse(e,t){let i=new GroundMesh(e.name,t);return i._subdivisionsX=e.subdivisionsX||1,i._subdivisionsY=e.subdivisionsY||1,i._minX=e.minX,i._maxX=e.maxX,i._minZ=e.minZ,i._maxZ=e.maxZ,i._width=e.width,i._height=e.height,i}};function CreateGroundVertexData(e){let t,i;let r=[],s=[],n=[],a=[],o=e.width||1,l=e.height||1,h=0|(e.subdivisionsX||e.subdivisions||1),u=0|(e.subdivisionsY||e.subdivisions||1);for(t=0;t<=u;t++)for(i=0;i<=h;i++){let e=new rm.P(i*o/h-o/2,0,(u-t)*l/u-l/2),r=new rm.P(0,1,0);s.push(e.x,e.y,e.z),n.push(r.x,r.y,r.z),a.push(i/h,r4.e.UseOpenGLOrientationForUV?t/u:1-t/u)}for(t=0;t<u;t++)for(i=0;i<h;i++)r.push(i+1+(t+1)*(h+1)),r.push(i+1+t*(h+1)),r.push(i+t*(h+1)),r.push(i+(t+1)*(h+1)),r.push(i+1+(t+1)*(h+1)),r.push(i+t*(h+1));let c=new se.x;return c.indices=r,c.positions=s,c.normals=n,c.uvs=a,c}function CreateTiledGroundVertexData(e){let t,i,r,s;let n=void 0!==e.xmin&&null!==e.xmin?e.xmin:-1,a=void 0!==e.zmin&&null!==e.zmin?e.zmin:-1,o=void 0!==e.xmax&&null!==e.xmax?e.xmax:1,l=void 0!==e.zmax&&null!==e.zmax?e.zmax:1,h=e.subdivisions||{w:1,h:1},u=e.precision||{w:1,h:1},c=[],d=[],p=[],_=[];h.h=h.h<1?1:h.h,h.w=h.w<1?1:h.w,u.w=u.w<1?1:u.w,u.h=u.h<1?1:u.h;let f={w:(o-n)/h.w,h:(l-a)/h.h};function applyTile(e,r,s,n){let a=d.length/3,o=u.w+1;for(t=0;t<u.h;t++)for(i=0;i<u.w;i++){let e=[a+i+t*o,a+(i+1)+t*o,a+(i+1)+(t+1)*o,a+i+(t+1)*o];c.push(e[1]),c.push(e[2]),c.push(e[3]),c.push(e[0]),c.push(e[1]),c.push(e[3])}let l=rm.P.Zero(),h=new rm.P(0,1,0);for(t=0;t<=u.h;t++)for(i=0,l.z=t*(n-r)/u.h+r;i<=u.w;i++)l.x=i*(s-e)/u.w+e,l.y=0,d.push(l.x,l.y,l.z),p.push(h.x,h.y,h.z),_.push(i/u.w,t/u.h)}for(r=0;r<h.h;r++)for(s=0;s<h.w;s++)applyTile(n+s*f.w,a+r*f.h,n+(s+1)*f.w,a+(r+1)*f.h);let m=new se.x;return m.indices=c,m.positions=d,m.normals=p,m.uvs=_,m}function CreateGroundFromHeightMapVertexData(e){let t,i;let r=[],s=[],n=[],a=[],o=e.colorFilter||new rg.Wo(.3,.59,.11),l=e.alphaFilter||0,h=!1;if(e.minHeight>e.maxHeight){h=!0;let t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(t=0;t<=e.subdivisions;t++)for(i=0;i<=e.subdivisions;i++){let r=new rm.P(i*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-t)*e.height/e.subdivisions-e.height/2),u=(r.x+e.width/2)/e.width*(e.bufferWidth-1)|0,c=(1-(r.z+e.height/2)/e.height)*(e.bufferHeight-1)|0,d=(u+c*e.bufferWidth)*4,p=e.buffer[d]/255,_=e.buffer[d+1]/255,f=e.buffer[d+2]/255,m=e.buffer[d+3]/255;h&&(p=1-p,_=1-_,f=1-f);let g=p*o.r+_*o.g+f*o.b;m>=l?r.y=e.minHeight+(e.maxHeight-e.minHeight)*g:r.y=e.minHeight-rw.kn,s.push(r.x,r.y,r.z),n.push(0,0,0),a.push(i/e.subdivisions,1-t/e.subdivisions)}for(t=0;t<e.subdivisions;t++)for(i=0;i<e.subdivisions;i++){let n=i+1+(t+1)*(e.subdivisions+1),a=i+1+t*(e.subdivisions+1),o=i+t*(e.subdivisions+1),l=i+(t+1)*(e.subdivisions+1),h=s[3*n+1]>=e.minHeight,u=s[3*a+1]>=e.minHeight,c=s[3*o+1]>=e.minHeight;h&&u&&c&&(r.push(n),r.push(a),r.push(o));let d=s[3*l+1]>=e.minHeight;d&&h&&c&&(r.push(l),r.push(n),r.push(o))}se.x.ComputeNormals(s,r,n);let u=new se.x;return u.indices=r,u.positions=s,u.normals=n,u.uvs=a,u}function CreateGround(e,t={},i){let r=new GroundMesh(e,i);r._setReady(!1),r._subdivisionsX=t.subdivisionsX||t.subdivisions||1,r._subdivisionsY=t.subdivisionsY||t.subdivisions||1,r._width=t.width||1,r._height=t.height||1,r._maxX=r._width/2,r._maxZ=r._height/2,r._minX=-r._maxX,r._minZ=-r._maxZ;let s=CreateGroundVertexData(t);return s.applyToMesh(r,t.updatable),r._setReady(!0),r}function CreateTiledGround(e,t,i=null){let r=new rV.Kj(e,i),s=CreateTiledGroundVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateGroundFromHeightMap(e,t,i={},r=null){let s=i.width||10,n=i.height||10,a=i.subdivisions||1,o=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new rg.Wo(.3,.59,.11),u=i.alphaFilter||0,c=i.updatable,d=i.onReady;r=r||rS.l.LastCreatedScene;let p=new GroundMesh(e,r);return p._subdivisionsX=a,p._subdivisionsY=a,p._width=s,p._height=n,p._maxX=p._width/2,p._maxZ=p._height/2,p._minX=-p._maxX,p._minZ=-p._maxZ,p._setReady(!1),rW.w1.LoadImage(t,e=>{let t=e.width,i=e.height;if(r.isDisposed)return;let _=null==r?void 0:r.getEngine().resizeImageBitmap(e,t,i),f=CreateGroundFromHeightMapVertexData({width:s,height:n,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:h,buffer:_,bufferWidth:t,bufferHeight:i,alphaFilter:u});f.applyToMesh(p,c),d&&d(p),p._setReady(!0)},()=>{},r.offlineProvider),p}function CreateTorusVertexData(e){let t=[],i=[],r=[],s=[],n=e.diameter||1,a=e.thickness||.5,o=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,h=o+1;for(let e=0;e<=o;e++){let l=e/o,u=e*Math.PI*2/o-Math.PI/2,c=rm.y3.Translation(n/2,0,0).multiply(rm.y3.RotationY(u));for(let n=0;n<=o;n++){let u=1-n/o,d=n*Math.PI*2/o+Math.PI,p=Math.cos(d),_=Math.sin(d),f=new rm.P(p,_,0),m=f.scale(a/2),g=new rm.FM(l,u);m=rm.P.TransformCoordinates(m,c),f=rm.P.TransformNormal(f,c),i.push(m.x,m.y,m.z),r.push(f.x,f.y,f.z),s.push(g.x,r4.e.UseOpenGLOrientationForUV?1-g.y:g.y);let v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}se.x._ComputeSides(l,i,t,r,s,e.frontUVs,e.backUVs);let u=new se.x;return u.indices=t,u.positions=i,u.normals=r,u.uvs=s,u}function CreateTorus(e,t={},i){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateTorusVertexData(t);return s.applyToMesh(r,t.updatable),r}se.x.CreateGround=CreateGroundVertexData,se.x.CreateTiledGround=CreateTiledGroundVertexData,se.x.CreateGroundFromHeightMap=CreateGroundFromHeightMapVertexData,rV.Kj.CreateGround=(e,t,i,r,s,n)=>CreateGround(e,{width:t,height:i,subdivisions:r,updatable:n},s),rV.Kj.CreateTiledGround=(e,t,i,r,s,n,a,o,l)=>CreateTiledGround(e,{xmin:t,zmin:i,xmax:r,zmax:s,subdivisions:n,precision:a,updatable:l},o),rV.Kj.CreateGroundFromHeightMap=(e,t,i,r,s,n,a,o,l,h,u)=>CreateGroundFromHeightMap(e,t,{width:i,height:r,subdivisions:s,minHeight:n,maxHeight:a,updatable:l,onReady:h,alphaFilter:u},o),se.x.CreateTorus=CreateTorusVertexData,rV.Kj.CreateTorus=(e,t,i,r,s,n,a)=>CreateTorus(e,{diameter:t,thickness:i,tessellation:r,sideOrientation:a,updatable:n},s);let VRExperienceHelperGazer=class VRExperienceHelperGazer{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=VRExperienceHelperGazer._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=CreateTorus("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;let t=new standardMaterial_StandardMaterial("targetMat",e);t.specularColor=rg.Wo.Black(),t.emissiveColor=new rg.Wo(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new ray_Ray(rm.P.Zero(),new rm.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()}};VRExperienceHelperGazer._IdCounter=0;let VRExperienceHelperCameraGazer=class VRExperienceHelperCameraGazer extends VRExperienceHelperGazer{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){let t=this._getCamera();return t?t.getForwardRay(e):new ray_Ray(rm.P.Zero(),rm.P.Forward())}};let VRExperienceHelper=class VRExperienceHelper{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new rf.y$,this.onAfterEnteringVRObservable=new rf.y$,this.onExitingVRObservable=new rf.y$,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new rm.P(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new rm.P(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new rg.Wo(.2,.2,1),this._pickedGazeColor=new rg.Wo(0,0,1),this.onNewMeshSelected=new rf.y$,this.onNewMeshPicked=new rf.y$,this.onBeforeCameraTeleport=new rf.y$,this.onAfterCameraTeleport=new rf.y$,this.onSelectedMeshUnselected=new rf.y$,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==Gamepad.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged(e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))}),e.rightStick&&e.onrightstickchanged(e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)}),e.type===Gamepad.XBOX&&(e.onbuttondown(e=>{this._interactionsEnabled&&e===tN.A&&this._cameraGazer._selectionPointerDown()}),e.onbuttonup(e=>{this._interactionsEnabled&&e===tN.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=rm.P.Zero(),this._workingQuaternion=rm._f.Identity(),this._workingMatrix=rm.y3.Identity(),rT.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();let i="getVRDisplays"in navigator;if(i||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new rm.P(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new DeviceOrientationCamera("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 targetCamera_TargetCamera&&this._scene.activeCamera.rotation)){let e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(rm._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?WebXRSessionManager.IsSessionSupportedAsync("immersive-vr").then(i=>{i?(rT.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 VRExperienceHelperCameraGazer(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(e=>{switch(e){case tw.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case tw.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case tw.IN_XR:this._hasEnteredVR=!0;break;case tw.NOT_IN_XR:this._hasEnteredVR=!1}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new VRExperienceHelperCameraGazer(()=>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=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",t=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); 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) }";t+=".babylonVRicon.vrdisplaypresenting { display: none; }";let i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode||this.enterVR()});let i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())},r8.kD.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new CircleEase,this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===r8.kD.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===r8.kD.POINTERUP&&this._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===tw.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){let e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr){this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){rT.Y.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=rm._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}exitVR(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){rT.Y.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr){this.xr.baseExperience.state===tw.IN_XR&&this.xr.pointerSelection.attach();return}this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>(!!this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t<this._floorMeshesCollection.length;t++)if(this._floorMeshesCollection[t].id===e.id)return!0;return!!this._floorMeshName&&e.name===this._floorMeshName}addFloorMesh(e){!this._floorMeshesCollection||this._floorMeshesCollection.indexOf(e)>-1||this._floorMeshesCollection.push(e)}removeFloorMesh(e){if(!this._floorMeshesCollection)return;let t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){let t=e.floorMeshes||[];if(!t.length){let i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr){t.forEach(e=>{this.xr.teleportation.addFloorMesh(e)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}if(!this.xrTestDone){let waitForXr=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(waitForXr),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(waitForXr);return}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);let t=new sv.$;t.vignetteColor=new rg.HE(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){(!this._teleportationRequestInitiated||t._teleportationRequestInitiated)&&(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)<this._padSensibilityDown&&(this._teleportActive&&this.teleportCamera(this._haloCenter),t._teleportationRequestInitiated=!1):e.y<-this._padSensibilityUp&&t._dpadPressed&&(t._activatePointer(),t._teleportationRequestInitiated=!0))}_checkRotate(e,t){!t._teleportationRequestInitiated&&(t._rotationLeftAsked?e.x>-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.x<this._padSensibilityDown&&(t._rotationRightAsked=!1):e.x>this._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=rm._f.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,rm._f.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),rm.P.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);let r=new ray_Ray(i,this._workingVector),s=this._scene.pickWithRay(r,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}}_createTeleportationCircles(){this._teleportationTarget=CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;let e=new DynamicTexture("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;let 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();let i=new standardMaterial_StandardMaterial("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;let r=CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);r.isPickable=!1,r.parent=this._teleportationTarget;let s=new animation_Animation("animationInnerCircle","position.y",30,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),s.setKeys(n);let a=new SineEase;a.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),s.setEasingFunction(a),r.animations=[],r.animations.push(s),this._scene.beginAnimation(r,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof FreeCamera))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];let t=rm._f.FromRotationMatrix(rm.y3.RotationY(Math.PI/4*this._rotationAngle)),i=new animation_Animation("animationRotation","rotationQuaternion",90,animation_Animation.ANIMATIONTYPE_QUATERNION,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];let s=new animation_Animation("animationPP","vignetteWeight",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),s.setKeys(n),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);let a=new animation_Animation("animationPP2","vignetteStretch",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:3,value:10}),o.push({frame:6,value:0}),a.setKeys(o),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){let t,i;if(!(this.currentVRCamera instanceof FreeCamera))return;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED){i=90;let e=rm.P.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];let r=new animation_Animation("animationCameraTeleportation","position",90,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];r.setKeys(s),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];let n=Math.round(i/2),a=new animation_Animation("animationPP","vignetteWeight",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:n,value:8}),o.push({frame:i,value:0}),a.setKeys(o),this._postProcessMove.animations.push(a);let l=new animation_Animation("animationPP2","vignetteStretch",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)}),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){if(!this.updateControllerLaserColor)return}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}};VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME=0,VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED=1;let intersectBoxAASphere=(e,t,i,r)=>!(e.x>i.x+r)&&!(i.x-r>t.x)&&!(e.y>i.y+r)&&!(i.y-r>t.y)&&!(e.z>i.z+r)&&!(i.z-r>t.z),nq=function(){let e={root:0,found:!1};return function(t,i,r,s){e.root=0,e.found=!1;let n=i*i-4*t*r;if(n<0)return e;let a=Math.sqrt(n),o=(-i-a)/(2*t),l=(-i+a)/(2*t);if(o>l){let e=l;l=o,o=e}return o>0&&o<s?(e.root=o,e.found=!0):l>0&&l<s&&(e.root=l,e.found=!0),e}}();let Collider=class Collider{constructor(){this._collisionPoint=rm.P.Zero(),this._planeIntersectionPoint=rm.P.Zero(),this._tempVector=rm.P.Zero(),this._tempVector2=rm.P.Zero(),this._tempVector3=rm.P.Zero(),this._tempVector4=rm.P.Zero(),this._edge=rm.P.Zero(),this._baseToVertex=rm.P.Zero(),this._destinationPoint=rm.P.Zero(),this._slidePlaneNormal=rm.P.Zero(),this._displacementVector=rm.P.Zero(),this._radius=rm.P.One(),this._retry=0,this._basePointWorld=rm.P.Zero(),this._velocityWorld=rm.P.Zero(),this._normalizedVelocity=rm.P.Zero(),this._collisionMask=-1}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}get slidePlaneNormal(){return this._slidePlaneNormal}_initialize(e,t,i){this._velocity=t,this._velocitySquaredLength=this._velocity.lengthSquared();let r=Math.sqrt(this._velocitySquaredLength);0===r||1===r?this._normalizedVelocity.copyFromFloats(t._x,t._y,t._z):t.scaleToRef(1/r,this._normalizedVelocity),this._basePoint=e,e.multiplyToRef(this._radius,this._basePointWorld),t.multiplyToRef(this._radius,this._velocityWorld),this._velocityWorldLength=this._velocityWorld.length(),this._epsilon=i,this.collisionFound=!1}_checkPointInTriangle(e,t,i,r,s){t.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),rm.P.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);let n=rm.P.Dot(this._tempVector4,s);return!(n<0)&&(r.subtractToRef(e,this._tempVector3),rm.P.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),!((n=rm.P.Dot(this._tempVector4,s))<0)&&(rm.P.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),(n=rm.P.Dot(this._tempVector4,s))>=0))}_canDoCollision(e,t,i,r){let s=rm.P.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+n+t)&&!!intersectBoxAASphere(i,r,this._basePointWorld,this._velocityWorldLength+n)}_testTriangle(e,t,i,r,s,n,a){let o;let l=!1;t||(t=[]),t[e]||(t[e]=new r2.J(0,0,0,0),t[e].copyFromPoints(i,r,s));let h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;let u=h.signedDistanceTo(this._basePoint),c=rm.P.Dot(h.normal,this._velocity);if(Collider.DoubleSidedCheck&&c>1e-4)return;if(0==c){if(Math.abs(u)>=1)return;l=!0,o=0}else{o=(-1-u)/c;let e=(1-u)/c;if(o>e){let t=e;e=o,o=t}if(o>1||e<0)return;o<0&&(o=0),o>1&&(o=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,p=1;if(!l&&(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(o,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,s,h.normal)&&(d=!0,p=o,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*rm.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,a=nq(e,t,n,p);a.found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),(a=nq(e,t=2*rm.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,p)).found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(s,this._tempVector),(a=nq(e,t=2*rm.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,p)).found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(s)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let o=this._edge.lengthSquared(),l=rm.P.Dot(this._edge,this._velocity),h=rm.P.Dot(this._edge,this._baseToVertex);if((a=nq(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rm.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=rm.P.Dot(this._edge,this._velocity),h=rm.P.Dot(this._edge,this._baseToVertex),(a=nq(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rm.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=rm.P.Dot(this._edge,this._velocity),h=rm.P.Dot(this._edge,this._baseToVertex),(a=nq(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rm.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(d){let e=p*p*this._velocitySquaredLength;(!this.collisionFound||e<this._nearestDistanceSquared)&&(a.collisionResponse&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this._nearestDistanceSquared=e,this._nearestDistance=Math.sqrt(e),this.collisionFound=!0),this.collidedMesh=a)}}_collide(e,t,i,r,s,n,a,o,l,h=!1){if(h){if(i&&0!==i.length)for(let n=r;n<s-2;n+=1){let r=i[n],s=i[n+1],h=i[n+2];if(4294967295===h){n+=2;continue}let u=t[r],c=t[s],d=t[h];u&&c&&d&&((l?1:0)^n%2?this._testTriangle(n,e,u,c,d,a,o):this._testTriangle(n,e,c,u,d,a,o))}else for(let i=0;i<t.length-2;i+=1){let r=t[i],s=t[i+1],n=t[i+2];r&&s&&n&&((l?1:0)^i%2?this._testTriangle(i,e,r,s,n,a,o):this._testTriangle(i,e,s,r,n,a,o))}}else if(i&&0!==i.length)for(let h=r;h<s;h+=3){let r=t[i[h]-n],s=t[i[h+1]-n],u=t[i[h+2]-n];l?this._testTriangle(h,e,r,s,u,a,o):this._testTriangle(h,e,u,s,r,a,o)}else for(let i=0;i<t.length;i+=3){let r=t[i],s=t[i+1],n=t[i+2];l?this._testTriangle(i,e,r,s,n,a,o):this._testTriangle(i,e,n,s,r,a,o)}}_getResponse(e,t){e.addToRef(t,this._destinationPoint),t.scaleInPlace(this._nearestDistance/t.length()),this._basePoint.addToRef(t,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this._epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(r2.J.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,t)}};Collider.DoubleSidedCheck=!1;let DefaultCollisionCoordinator=class DefaultCollisionCoordinator{constructor(){this._scaledPosition=rm.P.Zero(),this._scaledVelocity=rm.P.Zero(),this._finalPosition=rm.P.Zero()}getNewPosition(e,t,i,r,s,n,a){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,s),this._finalPosition.multiplyInPlace(i._radius),n(a,this._finalPosition,i.collidedMesh)}createCollider(){return new Collider}init(e){this._scene=e}_collideWithWorld(e,t,i,r,s,n=null){let a=10*rq.D.CollisionsEpsilon;if(i._retry>=r){s.copyFrom(e);return}let o=n?n.collisionMask:i.collisionMask;i._initialize(e,t,a);let l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;e<l.length;e++){let t=l[e];t.isEnabled()&&t.checkCollisions&&t.subMeshes&&t!==n&&(o&t.collisionGroup)!=0&&t._checkCollision(i)}if(!i.collisionFound){e.addToRef(t,s);return}if((0!==t.x||0!==t.y||0!==t.z)&&i._getResponse(e,t),t.length()<=a){s.copyFrom(e);return}i._retry++,this._collideWithWorld(e,t,i,r,s,n)}};rN.x.CollisionCoordinatorFactory=()=>new DefaultCollisionCoordinator,i(5790);let ComputeEffect=class ComputeEffect{constructor(e,t,i,r=""){var s,n;let a;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new rf.y$,this.onErrorObservable=new rf.y$,this.onBindObservable=new rf.y$,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=sg.x.WGSL,this.name=e,this._key=r,this._engine=i,this.uniqueId=ComputeEffect._UniqueIdSeed++,this.defines=null!==(s=t.defines)&&void 0!==s?s:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=null!==(n=t.entryPoint)&&void 0!==n?n:"main",this._shaderStore=s_.v.GetShadersStore(this._shaderLanguage),this._shaderRepository=s_.v.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=s_.v.GetIncludesShadersStore(this._shaderLanguage);let o=(0,rK.CG)()?this._engine.getHostDocument():null;e.computeSource?a="source:"+e.computeSource:e.computeElement?(a=o?o.getElementById(e.computeElement):null)||(a=e.computeElement):a=e.compute||e;let l={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=>{nG.L.Initialize(l),nG.L.PreProcess(i,l,r=>{this._rawComputeSourceCode=i,t.processFinalCode&&(r=t.processFinalCode(r));let s=nG.L.Finalize(r,"",l);this._useFinalCode(s.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){let 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){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let s;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){let t=(0,rK.v)(e);r(t);return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){let t=window.atob(e.substr(7));r(t);return}if(this._shaderStore[e+t+"Shader"]){r(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){r(this._shaderStore[e+i+"Shader"]);return}s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}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(){let e=this.defines,t=this._pipelineContext;this._isReady=!1;try{let 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(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t){let i=null;if(t&&e){let r=t.match(/COMPUTE SHADER ERROR: 0:(\d+?):/);if(r&&2===r.length){let t=parseInt(r[1]),s=e.split("\n",-1);s.length>=t&&(i=`Offending line [${t}] in compute code: ${s[t-1]}`)}}return[e,i]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,rT.Y.Error("Unable to compile compute effect:"),rT.Y.Error("Defines:\n"+this.defines),ComputeEffect.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&&(rT.Y.Error("Compute code:"),rT.Y.Error(t))),e&&rT.Y.Error(e)}rT.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){s_.v.GetShadersStore(sg.x.WGSL)[`${e}ComputeShader`]=t}};ComputeEffect._UniqueIdSeed=0,ComputeEffect.LogShaderCodeOnCompilationError=!0,(O=tV||(tV={}))[O.Texture=0]="Texture",O[O.StorageTexture=1]="StorageTexture",O[O.UniformBuffer=2]="UniformBuffer",O[O.StorageBuffer=3]="StorageBuffer",O[O.TextureWithoutSampler=4]="TextureWithoutSampler",O[O.Sampler=5]="Sampler",O[O.ExternalTexture=6]="ExternalTexture",r6.B.prototype.createComputeEffect=function(e,t){throw Error("createComputeEffect: This engine does not support compute shaders!")},r6.B.prototype.createComputePipelineContext=function(){throw Error("createComputePipelineContext: This engine does not support compute shaders!")},r6.B.prototype.createComputeContext=function(){},r6.B.prototype.computeDispatch=function(e,t,i,r,s,n,a){throw Error("computeDispatch: This engine does not support compute shaders!")},r6.B.prototype.areAllComputeEffectsReady=function(){return!0},r6.B.prototype.releaseComputeEffects=function(){},r6.B.prototype._prepareComputePipelineContext=function(e,t,i,r,s){},r6.B.prototype._rebuildComputeEffects=function(){},r6.B.prototype._executeWhenComputeStateIsCompiled=function(e,t){t()},r6.B.prototype._releaseComputeEffect=function(e){},r6.B.prototype._deleteComputePipelineContext=function(e){};var nK=i(7584);let ComputeShader=class ComputeShader{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,r={}){if(this._bindings={},this._samplers={},this._contextIsDirty=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=sa.K.UniqueId,!this._engine.getCaps().supportComputeShaders){rT.Y.Error("This engine does not support compute shaders!");return}if(!r.bindingsMapping){rT.Y.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!");return}this._context=t.createComputeContext(),this._shaderPath=i,this._options=Object.assign({bindingsMapping:{},defines:[]},r)}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){let r=this._bindings[e];this._bindings[e]={type:i?tV.Texture:tV.TextureWithoutSampler,object:t,indexInGroupEntries:null==r?void 0:r.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!r||r.object!==t||r.type!==this._bindings[e].type)}setStorageTexture(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tV.StorageTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setExternalTexture(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tV.ExternalTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setVideoTexture(e,t){return!!t.externalTexture&&(this.setExternalTexture(e,t.externalTexture),!0)}setUniformBuffer(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tV.UniformBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setStorageBuffer(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tV.StorageBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setTextureSampler(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:tV.Sampler,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}isReady(){let e=this._effect;for(let e in this._bindings){let t=this._bindings[e],i=t.type,r=t.object;switch(i){case tV.Texture:case tV.TextureWithoutSampler:case tV.StorageTexture:case tV.ExternalTexture:if(!r.isReady())return!1}}let t=[],i=this._shaderPath;if(this._options.defines)for(let e=0;e<this._options.defines.length;e++)t.push(this._options.defines[e]);let r=t.join("\n");return this._cachedDefines!==r&&(this._cachedDefines=r,e=this._engine.createComputeEffect(i,{defines:r,entryPoint:this._options.entryPoint,onCompiled:this.onCompiled,onError:this.onError}),this._effect=e),!!e.isReady()}dispatch(e,t,i){var r;if(!this.isReady())return!1;for(let e in this._bindings){let t=this._bindings[e];if(!this._options.bindingsMapping[e])throw Error("ComputeShader ('"+this.name+"'): No binding mapping has been provided for the property '"+e+"'");switch(t.type){case tV.Texture:{let i=this._samplers[e],s=t.object;i&&s._texture&&i.compareSampler(s._texture)||(this._samplers[e]=new nK.a().setParameters(s.wrapU,s.wrapV,s.wrapR,s.anisotropicFilteringLevel,s._texture.samplingMode,null===(r=s._texture)||void 0===r?void 0:r._comparisonFunction),this._contextIsDirty=!0);break}case tV.ExternalTexture:this._contextIsDirty=!0;break;case tV.UniformBuffer:{let e=t.object;e.getBuffer()!==t.buffer&&(t.buffer=e.getBuffer(),this._contextIsDirty=!0)}}}return this._contextIsDirty&&(this._contextIsDirty=!1,this._context.clear()),this._engine.computeDispatch(this._effect,this._context,this._bindings,e,t,i,this._options.bindingsMapping),!0}dispatchWhenReady(e,t,i,r=10){return new Promise(s=>{let check=()=>{this.dispatch(e,t,i)?s():setTimeout(check,r)};check()})}serialize(){let e=rb.p4.Serialize(this);for(let t in e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={},this._bindings){let i=this._bindings[t],r=i.object;switch(i.type){case tV.Texture:case tV.TextureWithoutSampler:case tV.StorageTexture:{let s=r.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type})}case tV.UniformBuffer:}}return e}static Parse(e,t,i){let r=rb.p4.Parse(()=>new ComputeShader(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(let s in e.textures){let n=e.bindings[s],a=texture_Texture.Parse(e.textures[s],t,i);n.type===tV.Texture?r.setTexture(s,a):n.type===tV.TextureWithoutSampler?r.setTexture(s,a,!1):r.setStorageTexture(s,a)}return r}};(0,rH.gn)([(0,rb.qC)()],ComputeShader.prototype,"name",void 0),(0,rv.H)("BABYLON.ComputeShader",ComputeShader);var n$=i(4347),nQ=i(5681),nZ=i(3592);let OctreeBlock=class OctreeBlock{constructor(e,t,i,r,s,n){this.entries=[],this._boundingVectors=[],this._capacity=i,this._depth=r,this._maxDepth=s,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.addEntry(e)}return}this._creationFunc(e,this),this.entries.length>this.capacity&&this._depth<this._maxDepth&&this.createInnerBlocks()}removeEntry(e){if(this.blocks){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.removeEntry(e)}return}let t=this.entries.indexOf(e);t>-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t<e.length;t++){let i=e[t];this.addEntry(i)}}select(e,t,i){if(n$.k.IsInFrustum(this._boundingVectors,e)){if(this.blocks){for(let r=0;r<this.blocks.length;r++){let s=this.blocks[r];s.select(e,t,i)}return}i?t.concat(this.entries):t.concatWithNoDuplicate(this.entries)}}intersects(e,t,i,r){if(n$.k.IntersectsSphere(this._minPoint,this._maxPoint,e,t)){if(this.blocks){for(let s=0;s<this.blocks.length;s++){let n=this.blocks[s];n.intersects(e,t,i,r)}return}r?i.concat(this.entries):i.concatWithNoDuplicate(this.entries)}}intersectsRay(e,t){if(e.intersectsBoxMinMax(this._minPoint,this._maxPoint)){if(this.blocks){for(let i=0;i<this.blocks.length;i++){let r=this.blocks[i];r.intersectsRay(e,t)}return}t.concatWithNoDuplicate(this.entries)}}createInnerBlocks(){OctreeBlock._CreateBlocks(this._minPoint,this._maxPoint,this.entries,this._capacity,this._depth,this._maxDepth,this,this._creationFunc),this.entries.splice(0)}static _CreateBlocks(e,t,i,r,s,n,a,o){a.blocks=[];let l=new rm.P((t.x-e.x)/2,(t.y-e.y)/2,(t.z-e.z)/2);for(let t=0;t<2;t++)for(let h=0;h<2;h++)for(let u=0;u<2;u++){let c=e.add(l.multiplyByFloats(t,h,u)),d=e.add(l.multiplyByFloats(t+1,h+1,u+1)),p=new OctreeBlock(c,d,r,s+1,n,o);p.addEntries(i),a.blocks.push(p)}}};let Octree=class Octree{constructor(e,t,i=2){this.maxDepth=i,this.dynamicContent=[],this._maxBlockCapacity=t||64,this._selectionContent=new sp.f(1024),this._creationFunc=e}update(e,t,i){OctreeBlock._CreateBlocks(e,t,i,this._maxBlockCapacity,0,this.maxDepth,this,this._creationFunc)}addMesh(e){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.addEntry(e)}}removeMesh(e){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.removeEntry(e)}}select(e,t){this._selectionContent.reset();for(let i=0;i<this.blocks.length;i++){let r=this.blocks[i];r.select(e,this._selectionContent,t)}return t?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}intersects(e,t,i){this._selectionContent.reset();for(let r=0;r<this.blocks.length;r++){let s=this.blocks[r];s.intersects(e,t,this._selectionContent,i)}return i?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}intersectsRay(e){this._selectionContent.reset();for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.intersectsRay(e,this._selectionContent)}return this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}};Octree.CreationFuncForMeshes=(e,t)=>{let i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Octree.CreationFuncForSubMeshes=(e,t)=>{let i=e.getBoundingInfo();i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},rN.x.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(rQ.l.NAME_OCTREE);i||(i=new OctreeSceneComponent(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Octree(Octree.CreationFuncForMeshes,e,t));let r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},Object.defineProperty(rN.x.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),rG.x.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){let i=this.getScene(),r=i._getComponent(rQ.l.NAME_OCTREE);r||(r=new OctreeSceneComponent(i),i._addComponent(r)),this._submeshesOctree||(this._submeshesOctree=new Octree(Octree.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);let s=this.getBoundingInfo(),n=s.boundingBox;return this._submeshesOctree.update(n.minimumWorld,n.maximumWorld,this.subMeshes),this._submeshesOctree};let OctreeSceneComponent=class OctreeSceneComponent{constructor(e){if(this.name=rQ.l.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new ray_Ray(rm.P.Zero(),new rm.P(1,1,1)),!(e=e||rS.l.LastCreatedScene))return;this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t)}register(){this.scene.onMeshRemovedObservable.add(e=>{let t=this.scene.selectionOctree;if(null!=t){let i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}}),this.scene.onMeshImportedObservable.add(e=>{let 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){let t=e._submeshesOctree.select(this.scene.frustumPlanes);return t}return this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForPicking){ray_Ray.TransformToRef(t,e.getWorldMatrix(),this._tempRay);let i=e._submeshesOctree.intersectsRay(this._tempRay);return i}return this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){let i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z),r=e._submeshesOctree.intersects(t._basePointWorld,i);return r}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}};function CreateCylinderVertexData(e){let t,i,r,s,n,a,o;let l=e.height||2,h=0===e.diameterTop?0:e.diameterTop||e.diameter||1,u=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;h=h||1e-5,u=u||1e-5;let c=0|(e.tessellation||24),d=0|(e.subdivisions||1),p=!!e.hasRings,_=!!e.enclose,f=0===e.cap?0:e.cap||rV.Kj.CAP_ALL,m=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,g=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,v=e.faceUV||[,,,],x=e.faceColors,T=2+(1+(1!==m&&_?2:0))*(p?d:1);for(t=0;t<T;t++)x&&void 0===x[t]&&(x[t]=new rg.HE(1,1,1,1));for(t=0;t<T;t++)v&&void 0===v[t]&&(v[t]=new rm.Lt(0,0,1,1));let S=[],C=[],E=[],b=[],y=[],P=2*Math.PI*m/c,R=(u-h)/2/l,A=rm.P.Zero(),I=rm.P.Zero(),M=rm.P.Zero(),D=rm.P.Zero(),O=rm.P.Zero(),N=rL.RD.Y,F=1,B=1,L=0,w=0;for(n=0;n<=d;n++)for(o=0,s=((r=n/d)*(h-u)+u)/2,F=p&&0!==n&&n!==d?2:1;o<F;o++){for(p&&(B+=o),_&&(B+=2*o),a=0;a<=c;a++)i=a*P,A.x=Math.cos(-i)*s,A.y=-l/2+r*l,A.z=Math.sin(-i)*s,0===h&&n===d?(I.x=E[E.length-(c+1)*3],I.y=E[E.length-(c+1)*3+1],I.z=E[E.length-(c+1)*3+2]):(I.x=A.x,I.z=A.z,I.y=Math.sqrt(I.x*I.x+I.z*I.z)*R,I.normalize()),0===a&&(M.copyFrom(A),D.copyFrom(I)),C.push(A.x,A.y,A.z),E.push(I.x,I.y,I.z),w=p?L!==B?v[B].y:v[B].w:v[B].y+(v[B].w-v[B].y)*r,b.push(v[B].x+(v[B].z-v[B].x)*a/c,r4.e.UseOpenGLOrientationForUV?1-w:w),x&&y.push(x[B].r,x[B].g,x[B].b,x[B].a);1!==m&&_&&(C.push(A.x,A.y,A.z),C.push(0,A.y,0),C.push(0,A.y,0),C.push(M.x,M.y,M.z),rm.P.CrossToRef(N,I,O),O.normalize(),E.push(O.x,O.y,O.z,O.x,O.y,O.z),rm.P.CrossToRef(D,N,O),O.normalize(),E.push(O.x,O.y,O.z,O.x,O.y,O.z),w=p?L!==B?v[B+1].y:v[B+1].w:v[B+1].y+(v[B+1].w-v[B+1].y)*r,b.push(v[B+1].x,r4.e.UseOpenGLOrientationForUV?1-w:w),b.push(v[B+1].z,r4.e.UseOpenGLOrientationForUV?1-w:w),w=p?L!==B?v[B+2].y:v[B+2].w:v[B+2].y+(v[B+2].w-v[B+2].y)*r,b.push(v[B+2].x,r4.e.UseOpenGLOrientationForUV?1-w:w),b.push(v[B+2].z,r4.e.UseOpenGLOrientationForUV?1-w:w),x&&(y.push(x[B+1].r,x[B+1].g,x[B+1].b,x[B+1].a),y.push(x[B+1].r,x[B+1].g,x[B+1].b,x[B+1].a),y.push(x[B+2].r,x[B+2].g,x[B+2].b,x[B+2].a),y.push(x[B+2].r,x[B+2].g,x[B+2].b,x[B+2].a))),L!==B&&(L=B)}let U=1!==m&&_?c+4:c;for(B=0,n=0;B<d;B++){let e=0,t=0,i=0,r=0;for(a=0;a<c;a++)e=n*(U+1)+a,t=(n+1)*(U+1)+a,i=n*(U+1)+(a+1),r=(n+1)*(U+1)+(a+1),S.push(e,t,i),S.push(r,i,t);1!==m&&_&&(S.push(e+2,t+2,i+2),S.push(r+2,i+2,t+2),S.push(e+4,t+4,i+4),S.push(r+4,i+4,t+4)),n=p?n+2:n+1}let createCylinderCap=e=>{let t,i,r;let s=e?h/2:u/2;if(0===s)return;let n=e?v[T-1]:v[0],a=null;x&&(a=e?x[T-1]:x[0]);let o=C.length/3,d=e?l/2:-l/2,p=new rm.P(0,d,0);C.push(p.x,p.y,p.z),E.push(0,e?1:-1,0);let _=n.y+(n.w-n.y)*.5;b.push(n.x+(n.z-n.x)*.5,r4.e.UseOpenGLOrientationForUV?1-_:_),a&&y.push(a.r,a.g,a.b,a.a);let f=new rm.FM(.5,.5);for(r=0;r<=c;r++){t=2*Math.PI*r*m/c;let o=Math.cos(-t),l=Math.sin(-t);i=new rm.P(o*s,d,l*s);let h=new rm.FM(o*f.x+.5,l*f.y+.5);C.push(i.x,i.y,i.z),E.push(0,e?1:-1,0);let u=n.y+(n.w-n.y)*h.y;b.push(n.x+(n.z-n.x)*h.x,r4.e.UseOpenGLOrientationForUV?1-u:u),a&&y.push(a.r,a.g,a.b,a.a)}for(r=0;r<c;r++)e?(S.push(o),S.push(o+(r+2)),S.push(o+(r+1))):(S.push(o),S.push(o+(r+1)),S.push(o+(r+2)))};(f===rV.Kj.CAP_START||f===rV.Kj.CAP_ALL)&&createCylinderCap(!1),(f===rV.Kj.CAP_END||f===rV.Kj.CAP_ALL)&&createCylinderCap(!0),se.x._ComputeSides(g,C,S,E,b,e.frontUVs,e.backUVs);let V=new se.x;return V.indices=S,V.positions=C,V.normals=E,V.uvs=b,x&&(V.colors=y),V}function cylinderBuilder_CreateCylinder(e,t={},i){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateCylinderVertexData(t);return s.applyToMesh(r,t.updatable),r}se.x.CreateCylinder=CreateCylinderVertexData,rV.Kj.CreateCylinder=(e,t,i,r,s,n,a,o,l)=>{void 0!==a&&a instanceof rN.x||(void 0!==a&&(l=o||rV.Kj.DEFAULTSIDE,o=a),a=n,n=1);let h={height:t,diameterTop:i,diameterBottom:r,tessellation:s,subdivisions:n,sideOrientation:l,updatable:o};return cylinderBuilder_CreateCylinder(e,h,a)},ry.N.AddNodeConstructor("Light_Type_3",(e,t)=>()=>new HemisphericLight(e,rm.P.Zero(),t));let HemisphericLight=class HemisphericLight extends light_Light{constructor(e,t,i){super(e,i),this.groundColor=new rg.Wo(0,0,0),this.direction=t||rm.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=rm.P.Normalize(e.subtract(rm.P.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){let i=rm.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){let i=rm.P.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=rm.y3.Identity()),this._worldMatrix}getTypeID(){return light_Light.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}};(0,rH.gn)([(0,rb.n9)()],HemisphericLight.prototype,"groundColor",void 0),(0,rH.gn)([(0,rb.hd)()],HemisphericLight.prototype,"direction",void 0);let utilityLayerRenderer_UtilityLayerRenderer=class utilityLayerRenderer_UtilityLayerRenderer{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 HemisphericLight("shared gizmo light",new rm.P(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=rg.Wo.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer?utilityLayerRenderer_UtilityLayerRenderer._CreateDefaultUtilityLayerFromScene(rS.l.LastCreatedScene):utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=new utilityLayerRenderer_UtilityLayerRenderer(e),utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=null}),utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer&&(utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=new utilityLayerRenderer_UtilityLayerRenderer(rS.l.LastCreatedScene),utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=null})),utilityLayerRenderer_UtilityLayerRenderer._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 rf.y$,this.utilityLayerScene=new rN.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||!this.pickingEnabled||!this.processAllEvents&&t.type!==r8.kD.POINTERMOVE&&t.type!==r8.kD.POINTERUP&&t.type!==r8.kD.POINTERDOWN&&t.type!==r8.kD.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;let i=t.event;if(e.isPointerCaptured(i.pointerId)){this._pointerCaptures[i.pointerId]=!1;return}let getNearPickDataForScene=i=>{let r=null;if(t.nearInteractionPickingInfo)r=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new r7.p;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)r=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),r=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return r},r=getNearPickDataForScene(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=r8.kD.POINTERDOWN){t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new r8.R5(t.type,t.event,r),t.type),t.type===r8.kD.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new r8.R5(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{let i=getNearPickDataForScene(e),s=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,s),t.skipOnPointerObservable=!0):t.type===r8.kD.POINTERDOWN?this._pointerCaptures[s.pointerId]=!0:(t.type===r8.kD.POINTERMOVE||t.type===r8.kD.POINTERUP)&&(this._lastPointerEvents[s.pointerId]&&(this.onPointerOutObservable.notifyObservers(s.pointerId),delete this._lastPointerEvents[s.pointerId]),this._notifyObservers(t,i,s)):!this._pointerCaptures[s.pointerId]&&(r.distance<i.distance||0===i.distance)?(this._notifyObservers(t,r,s),t.skipOnPointerObservable||(t.skipOnPointerObservable=r.distance>0)):!this._pointerCaptures[s.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,s),t.skipOnPointerObservable=!0):((t.type===r8.kD.POINTERMOVE||t.type===r8.kD.POINTERUP)&&this._lastPointerEvents[s.pointerId]&&(this.onPointerOutObservable.notifyObservers(s.pointerId),delete this._lastPointerEvents[s.pointerId]),this._notifyObservers(t,r,s))),t.type===r8.kD.POINTERUP&&this._pointerCaptures[s.pointerId]&&(this._pointerCaptures[s.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 r8.R5(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){let 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()}};utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=null,utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=null,(N=tk||(tk={}))[N.Origin=0]="Origin",N[N.Pivot=1]="Pivot",(F=tG||(tG={}))[F.World=0]="World",F[F.Local=1]="Local";let gizmo_Gizmo=class gizmo_Gizmo{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;let t=e==tG.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=utilityLayerRenderer_UtilityLayerRenderer.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=tk.Origin,this._updateScale=!0,this._coordinatesMode=tG.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=rm.y3.RotationY(Math.PI),this._rootMesh=new rV.Kj("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=rm._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==tk.Pivot&&e.getAbsolutePivotPoint){let t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{let t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new rm.P(0,0,0);this._rootMesh.position.copyFrom(i)}}if(this.updateGizmoRotationToMatchAttachedMesh){let t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName(),i=t?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,gizmo_Gizmo.PreserveScaling?i:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){let t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,rm.jp.Vector3[0]);let r=this.scaleRatio;if(t.mode==rj.V.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){let e=t.orthoTop-t.orthoBottom;r*=e}}else{let e=t.getScene().useRightHandedSystem?rm.P.RightHandedForwardReadOnly:rm.P.LeftHandedForwardReadOnly,i=t.getDirection(e);r*=rm.P.Dot(rm.jp.Vector3[0],i)}this._rootMesh.scaling.setAll(r),0>e._getWorldMatrixDeterminant()&&!gizmo_Gizmo.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_matrixChanged(){if(this._attachedNode){if(this._attachedNode._isCamera){let e,t;let i=this._attachedNode;if(i.parent){let t=rm.jp.Matrix[1];i.parent._worldMatrix.invertToRef(t),this._attachedNode._worldMatrix.multiplyToRef(t,rm.jp.Matrix[0]),e=rm.jp.Matrix[0]}else e=this._attachedNode._worldMatrix;i.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(e,rm.jp.Matrix[1]),t=rm.jp.Matrix[1]):t=e,t.decompose(rm.jp.Vector3[1],rm.jp.Quaternion[0],rm.jp.Vector3[0]);let r="FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName();if(r){let e=this._attachedNode;e.rotation=rm.jp.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(rm.jp.Quaternion[0]),e.rotationQuaternion.normalize())}i.position.copyFrom(rm.jp.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){let e=this._attachedNode;if(e.parent){let t=rm.jp.Matrix[0],i=rm.jp.Matrix[1];if(e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i),i.decompose(rm.jp.Vector3[0],rm.jp.Quaternion[0],e.position),rm.jp.Quaternion[0].normalize(),e.isUsingPivotMatrix()){let t=rm.jp.Quaternion[1];rm._f.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);let i=rm.jp.Matrix[2];rm.y3.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);let r=rm.jp.Matrix[2];t.toRotationMatrix(r);let s=e.getPivotMatrix(),n=rm.jp.Matrix[3];s.invertToRef(n),s.multiplyToRef(i,rm.jp.Matrix[4]),rm.jp.Matrix[4].multiplyToRef(r,rm.jp.Matrix[5]),rm.jp.Matrix[5].multiplyToRef(n,rm.jp.Matrix[6]),rm.jp.Matrix[6].getTranslationToRef(rm.jp.Vector3[1]),e.position.subtractInPlace(rm.jp.Vector3[1])}}else this._attachedNode._worldMatrix.decompose(rm.jp.Vector3[0],rm.jp.Quaternion[0],e.position,gizmo_Gizmo.PreserveScaling?e:void 0);rm.jp.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(rm.jp.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(rm.jp.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=rm.jp.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){let e=this._attachedNode,t=e.getParent();if(t){let i=rm.jp.Matrix[0],r=rm.jp.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r);let s=e.getLocalMatrix();s.copyFrom(r)}else{let t=e.getLocalMatrix();t.copyFrom(e.getFinalMatrix())}e.markAsDirty()}else{let e=this._attachedNode;if(e.getTypeID){let t=e.getTypeID();if(t===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT||t===light_Light.LIGHTTYPEID_SPOTLIGHT||t===light_Light.LIGHTTYPEID_POINTLIGHT){let t=e.parent;if(t){let i=rm.jp.Matrix[0],r=rm.jp.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,r),r.decompose(void 0,rm.jp.Quaternion[0],rm.jp.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,rm.jp.Quaternion[0],rm.jp.Vector3[0]);e.position=new rm.P(rm.jp.Vector3[0].x,rm.jp.Vector3[0].y,rm.jp.Vector3[0].z),e.direction&&(e.direction=new rm.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,r=e.utilityLayerScene.onPointerObservable.add(e=>{var r,s;if(e.pickInfo){if(e.type===r8.kD.POINTERMOVE){if(i)return;t.forEach(t=>{var i,r;if(t.colliderMeshes&&t.gizmoMeshes){let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,n=t.dragBehavior.enabled?s||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=n,e.color&&(e.color=n.diffuseColor)})}})}if(e.type===r8.kD.POINTERDOWN&&t.has(null===(r=e.pickInfo.pickedMesh)||void 0===r?void 0:r.parent)){i=!0;let r=t.get(null===(s=e.pickInfo.pickedMesh)||void 0===s?void 0:s.parent);r.active=!0,t.forEach(t=>{var i,r;let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,n=(s||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=n,e.color&&(e.color=n.diffuseColor)})})}e.type===r8.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)})})}});return r}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}};gizmo_Gizmo.PreserveScaling=!1,Object.defineProperty(rN.x.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new DebugLayer(this)),this._debugLayer},enumerable:!0,configurable:!0}),(B=tz||(tz={}))[B.Properties=0]="Properties",B[B.Debug=1]="Debug",B[B.Statistics=2]="Statistics",B[B.Tools=3]="Tools",B[B.Settings=4]="Settings";let DebugLayer=class DebugLayer{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new rf.y$),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new rf.y$),this._onSelectionChangedObservable)}constructor(e){if(this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||rS.l.LastCreatedScene,!this._scene)return;this._scene.onDisposeObservable.add(()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()})}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(let e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(let e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}let t=Object.assign(Object.assign({},DebugLayer.Config),e);this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise(t=>{if(void 0===this.BJSINSPECTOR){let i=e&&e.inspectorURL?e.inspectorURL:DebugLayer.InspectorURL;rW.w1.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}};function CreateBoxVertexData(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],i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[],s=[],n=e.width||e.size||1,a=e.height||e.size||1,o=e.depth||e.size||1,l=e.wrap||!1,h=void 0===e.topBaseAt?1:e.topBaseAt,u=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,u=(u+4)%4;let c=[2,0,3,1][h],d=[2,0,1,3][u],p=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],p=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,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]],r=[17,18,19,16],s=[22,23,20,21];for(;c>0;)e.unshift(e.pop()),r.unshift(r.pop()),c--;for(;d>0;)i.unshift(i.pop()),s.unshift(s.pop()),d--;e=e.flat(),i=i.flat(),p=p.concat(e).concat(i),t.push(r[0],r[2],r[3],r[0],r[1],r[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}let _=[n/2,a/2,o/2];s=p.reduce((e,t,i)=>e.concat(t*_[i%3]),[]);let f=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,m=e.faceUV||Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new rm.Lt(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new rg.HE(1,1,1,1));for(let e=0;e<6;e++)if(r.push(m[e].z,r4.e.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,r4.e.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,r4.e.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),r.push(m[e].z,r4.e.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);se.x._ComputeSides(f,s,t,i,r,e.frontUVs,e.backUVs);let x=new se.x;if(x.indices=t,x.positions=s,x.normals=i,x.uvs=r,g){let e=f===se.x.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function CreateSegmentedBoxVertexData(e){let t=e.width||e.size||1,i=e.height||e.size||1,r=e.depth||e.size||1,s=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),a=0|(e.depthSegments||e.segments||1),o=new rm.y3,l=new rm.y3,h=new rm.y3,u=CreateGroundVertexData({width:t,height:r,subdivisionsX:s,subdivisionsY:a});rm.y3.TranslationToRef(0,-i/2,0,l),rm.y3.RotationZToRef(Math.PI,o),o.multiplyToRef(l,h),u.transform(h);let c=CreateGroundVertexData({width:t,height:r,subdivisionsX:s,subdivisionsY:a});rm.y3.TranslationToRef(0,i/2,0,h),c.transform(h);let d=CreateGroundVertexData({width:i,height:r,subdivisionsX:n,subdivisionsY:a});rm.y3.TranslationToRef(-t/2,0,0,l),rm.y3.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,h),d.transform(h);let p=CreateGroundVertexData({width:i,height:r,subdivisionsX:n,subdivisionsY:a});rm.y3.TranslationToRef(t/2,0,0,l),rm.y3.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,h),p.transform(h);let _=CreateGroundVertexData({width:t,height:i,subdivisionsX:s,subdivisionsY:n});rm.y3.TranslationToRef(0,0,-r/2,l),rm.y3.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,h),_.transform(h);let f=CreateGroundVertexData({width:t,height:i,subdivisionsX:s,subdivisionsY:n});return rm.y3.TranslationToRef(0,0,r/2,l),rm.y3.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,h),f.transform(h),u.merge([c,p,d,_,f],!0),u}function boxBuilder_CreateBox(e,t={},i=null){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateBoxVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateSphereVertexData(e){let t=0|(e.segments||32),i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,a=e.slice&&e.slice<=0?1:e.slice||1,o=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new rm.P(i/2,r/2,s/2),u=2+t,c=2*u,d=[],p=[],_=[],f=[];for(let e=0;e<=u;e++){let t=e/u,i=t*Math.PI*a;for(let e=0;e<=c;e++){let r=e/c,s=r*Math.PI*2*n,a=rm.y3.RotationZ(-i),o=rm.y3.RotationY(s),l=rm.P.TransformCoordinates(rm.P.Up(),a),u=rm.P.TransformCoordinates(l,o),d=u.multiply(h),m=u.divide(h).normalize();p.push(d.x,d.y,d.z),_.push(m.x,m.y,m.z),f.push(r,r4.e.UseOpenGLOrientationForUV?1-t:t)}if(e>0){let t=p.length/3;for(let i=t-2*(c+1);i+c+2<t;i++)l?(e>1&&(d.push(i),d.push(i+1),d.push(i+c+1)),(e<u||a<1)&&(d.push(i+c+1),d.push(i+1),d.push(i+c+2))):(d.push(i),d.push(i+1),d.push(i+c+1),d.push(i+c+1),d.push(i+1),d.push(i+c+2))}}se.x._ComputeSides(o,p,d,_,f,e.frontUVs,e.backUVs);let m=new se.x;return m.indices=d,m.positions=p,m.normals=_,m.uvs=f,m}function sphereBuilder_CreateSphere(e,t={},i=null){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateSphereVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateCapsuleVertexData(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){let t,i;let r=0|Math.max(e.subdivisions?e.subdivisions:2,1),s=0|Math.max(e.tessellation?e.tessellation:16,3),n=Math.max(e.height?e.height:1,0),a=Math.max(e.radius?e.radius:.25,0),o=0|Math.max(e.capSubdivisions?e.capSubdivisions:6,1),l=Math.max(e.radiusTop?e.radiusTop:a,0),h=Math.max(e.radiusBottom?e.radiusBottom:a,0),u=n-(l+h),c=2*Math.PI,d=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:o,1),p=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:o,1),_=Math.acos((h-l)/n),f=[],m=[],g=[],v=[],x=0,T=[],S=.5*u,C=.5*Math.PI,E=rm.P.Zero(),b=rm.P.Zero(),y=Math.cos(_),P=Math.sin(_),R=new rm.FM(l*P,S+l*y).subtract(new rm.FM(h*P,-S+h*y)).length(),A=l*_+R+h*(C-_),I=0;for(i=0;i<=d;i++){let e=[],r=C-_*(i/d);I+=l*_/d;let n=Math.cos(r),a=Math.sin(r),o=n*l;for(t=0;t<=s;t++){let i=t/s,r=i*c+0,h=Math.sin(r),u=Math.cos(r);b.x=o*h,b.y=S+a*l,b.z=o*u,m.push(b.x,b.y,b.z),E.set(n*h,a,n*u),g.push(E.x,E.y,E.z),v.push(i,r4.e.UseOpenGLOrientationForUV?I/A:1-I/A),e.push(x),x++}T.push(e)}let M=n-l-h+y*l-y*h,D=P*(h-l)/M;for(i=1;i<=r;i++){let e=[];I+=R/r;let n=P*(i*(h-l)/r+l);for(t=0;t<=s;t++){let a=t/s,o=a*c+0,h=Math.sin(o),u=Math.cos(o);b.x=n*h,b.y=S+y*l-i*M/r,b.z=n*u,m.push(b.x,b.y,b.z),E.set(h,D,u).normalize(),g.push(E.x,E.y,E.z),v.push(a,r4.e.UseOpenGLOrientationForUV?I/A:1-I/A),e.push(x),x++}T.push(e)}for(i=1;i<=p;i++){let e=[],r=C-_-(Math.PI-_)*(i/p);I+=h*_/p;let n=Math.cos(r),a=Math.sin(r),o=n*h;for(t=0;t<=s;t++){let i=t/s,r=i*c+0,l=Math.sin(r),u=Math.cos(r);b.x=o*l,b.y=-S+a*h,b.z=o*u,m.push(b.x,b.y,b.z),E.set(n*l,a,n*u),g.push(E.x,E.y,E.z),v.push(i,r4.e.UseOpenGLOrientationForUV?I/A:1-I/A),e.push(x),x++}T.push(e)}for(t=0;t<s;t++)for(i=0;i<d+r+p;i++){let e=T[i][t],r=T[i+1][t],s=T[i+1][t+1],n=T[i][t+1];f.push(e),f.push(r),f.push(n),f.push(r),f.push(s),f.push(n)}if(f=f.reverse(),e.orientation&&!e.orientation.equals(rm.P.Up())){let t=new rm.y3;e.orientation.clone().scale(.5*Math.PI).cross(rm.P.Up()).toQuaternion().toRotationMatrix(t);let i=rm.P.Zero();for(let e=0;e<m.length;e+=3)i.set(m[e],m[e+1],m[e+2]),rm.P.TransformCoordinatesToRef(i.clone(),t,i),m[e]=i.x,m[e+1]=i.y,m[e+2]=i.z}let O=new se.x;return O.positions=m,O.normals=g,O.uvs=v,O.indices=f,O}function capsuleBuilder_CreateCapsule(e,t={orientation:rm.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},i=null){let r=new rV.Kj(e,i),s=CreateCapsuleVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateRibbonVertexData(e){let t,i,r,s,n,a,o,l,h,u,c,d=e.pathArray,p=e.closeArray||!1,_=e.closePath||!1,f=e.invertUV||!1,m=Math.floor(d[0].length/2),g=e.offset||m;g=g>m?m:Math.floor(g);let v=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,x=e.uvs,T=e.colors,S=[],C=[],E=[],b=[],y=[],P=[],R=[],A=[],I=[],M=[];if(d.length<2){let e=[],t=[];for(r=0;r<d[0].length-g;r++)e.push(d[0][r]),t.push(d[0][r+g]);d=[e,t]}let D=0,O=_?1:0;for(i=0,t=d[0].length;i<d.length;i++){for(R[i]=0,y[i]=[0],t=t<(a=(n=d[i]).length)?t:a,s=0;s<a;)S.push(n[s].x,n[s].y,n[s].z),s>0&&(o=n[s].subtract(n[s-1]).length()+R[i],y[i].push(o),R[i]=o),s++;_&&(s--,S.push(n[0].x,n[0].y,n[0].z),o=n[s].subtract(n[0]).length()+R[i],y[i].push(o),R[i]=o),I[i]=a+O,M[i]=D,D+=a+O}let N=null,F=null;for(r=0;r<t+O;r++){for(i=0,A[r]=0,P[r]=[0];i<d.length-1;i++)l=d[i],h=d[i+1],r===t?(N=l[0],F=h[0]):(N=l[r],F=h[r]),o=F.subtract(N).length()+A[r],P[r].push(o),A[r]=o;p&&F&&N&&(l=d[i],h=d[0],r===t&&(F=h[0]),o=F.subtract(N).length()+A[r],A[r]=o)}if(x)for(i=0;i<x.length;i++)b.push(x[i].x,r4.e.UseOpenGLOrientationForUV?1-x[i].y:x[i].y);else for(i=0;i<d.length;i++)for(r=0;r<t+O;r++)u=0!=R[i]?y[i][r]/R[i]:0,c=0!=A[r]?P[r][i]/A[r]:0,f?b.push(c,u):b.push(u,r4.e.UseOpenGLOrientationForUV?1-c:c);let B=0,L=I[i=0]-1,w=I[i+1]-1,U=L<w?L:w,V=M[1]-M[0],k=p?I.length:I.length-1;for(;B<=U&&i<k;)C.push(B,B+V,B+1),C.push(B+V+1,B+1,B+V),(B+=1)===U&&(++i==I.length-1?(V=M[0]-M[i],L=I[i]-1,w=I[0]-1):(V=M[i+1]-M[i],L=I[i]-1,w=I[i+1]-1),B=M[i],U=L<w?L+B:w+B);if(se.x.ComputeNormals(S,C,E),_){let e=0,t=0;for(i=0;i<d.length;i++)e=3*M[i],t=i+1<d.length?(M[i+1]-1)*3:E.length-3,E[e]=(E[e]+E[t])*.5,E[e+1]=(E[e+1]+E[t+1])*.5,E[e+2]=(E[e+2]+E[t+2])*.5,E[t]=E[e],E[t+1]=E[e+1],E[t+2]=E[e+2]}se.x._ComputeSides(v,S,C,E,b,e.frontUVs,e.backUVs);let G=null;if(T){G=new Float32Array(4*T.length);for(let e=0;e<T.length;e++)G[4*e]=T[e].r,G[4*e+1]=T[e].g,G[4*e+2]=T[e].b,G[4*e+3]=T[e].a}let z=new se.x,W=new Float32Array(S),H=new Float32Array(E),X=new Float32Array(b);return z.indices=C,z.positions=W,z.normals=H,z.uvs=X,G&&z.set(G,rz.o.ColorKind),_&&(z._idx=M),z}function CreateRibbon(e,t,i=null){let r=t.pathArray,s=t.closeArray,n=t.closePath,a=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),o=t.instance,l=t.updatable;if(o){let e=rm.jp.Vector3[0].setAll(Number.MAX_VALUE),i=rm.jp.Vector3[1].setAll(-Number.MAX_VALUE),s=o.getVerticesData(rz.o.PositionKind);if((t=>{let s=r[0].length,n=0,a=o._originalBuilderSideOrientation===rV.Kj.DOUBLESIDE?2:1;for(let l=1;l<=a;++l)for(let a=0;a<r.length;++a){let l=r[a],h=l.length;s=s<h?s:h;for(let r=0;r<s;++r){let s=l[r];t[n]=s.x,t[n+1]=s.y,t[n+2]=s.z,e.minimizeInPlaceFromFloats(s.x,s.y,s.z),i.maximizeInPlaceFromFloats(s.x,s.y,s.z),n+=3}if(o._creationDataStorage&&o._creationDataStorage.closePath){let e=l[0];t[n]=e.x,t[n+1]=e.y,t[n+2]=e.z,n+=3}}})(s),o.hasBoundingInfo?o.getBoundingInfo().reConstruct(e,i,o._worldMatrix):o.buildBoundingInfo(e,i,o._worldMatrix),o.updateVerticesData(rz.o.PositionKind,s,!1,!1),t.colors){let e=o.getVerticesData(rz.o.ColorKind);for(let i=0,r=0;i<t.colors.length;i++,r+=4){let s=t.colors[i];e[r]=s.r,e[r+1]=s.g,e[r+2]=s.b,e[r+3]=s.a}o.updateVerticesData(rz.o.ColorKind,e,!1,!1)}if(t.uvs){let e=o.getVerticesData(rz.o.UVKind);for(let i=0;i<t.uvs.length;i++)e[2*i]=t.uvs[i].x,e[2*i+1]=r4.e.UseOpenGLOrientationForUV?1-t.uvs[i].y:t.uvs[i].y;o.updateVerticesData(rz.o.UVKind,e,!1,!1)}if(!o.areNormalsFrozen||o.isFacetDataEnabled){let e=o.getIndices(),t=o.getVerticesData(rz.o.NormalKind),i=o.isFacetDataEnabled?o.getFacetDataParameters():null;if(se.x.ComputeNormals(s,e,t,i),o._creationDataStorage&&o._creationDataStorage.closePath){let e=0,i=0;for(let s=0;s<r.length;s++)e=3*o._creationDataStorage.idx[s],i=s+1<r.length?(o._creationDataStorage.idx[s+1]-1)*3:t.length-3,t[e]=(t[e]+t[i])*.5,t[e+1]=(t[e+1]+t[i+1])*.5,t[e+2]=(t[e+2]+t[i+2])*.5,t[i]=t[e],t[i+1]=t[e+1],t[i+2]=t[e+2]}o.areNormalsFrozen||o.updateVerticesData(rz.o.NormalKind,t,!1,!1)}return o}{let r=new rV.Kj(e,i);r._originalBuilderSideOrientation=a,r._creationDataStorage=new rV.gW;let o=CreateRibbonVertexData(t);return n&&(r._creationDataStorage.idx=o._idx),r._creationDataStorage.closePath=n,r._creationDataStorage.closeArray=s,o.applyToMesh(r,l),r}}function CreateDiscVertexData(e){let t=[],i=[],r=[],s=[],n=e.radius||.5,a=e.tessellation||64,o=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);let h=2*Math.PI*o,u=1===o?h/a:h/(a-1),c=0;for(let e=0;e<a;e++){let e=Math.cos(c),i=Math.sin(c),r=(e+1)/2,a=(1-i)/2;t.push(n*e,n*i,0),s.push(r,r4.e.UseOpenGLOrientationForUV?1-a:a),c+=u}1===o&&(t.push(t[3],t[4],t[5]),s.push(s[2],r4.e.UseOpenGLOrientationForUV?1-s[3]:s[3]));let d=t.length/3;for(let e=1;e<d-1;e++)i.push(e+1,0,e);se.x.ComputeNormals(t,i,r),se.x._ComputeSides(l,t,i,r,s,e.frontUVs,e.backUVs);let p=new se.x;return p.indices=i,p.positions=t,p.normals=r,p.uvs=s,p}function discBuilder_CreateDisc(e,t={},i=null){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateDiscVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateTiledPlaneVertexData(e){let t=e.pattern||rV.Kj.NO_FLIP,i=e.tileWidth||e.tileSize||1,r=e.tileHeight||e.tileSize||1,s=e.alignHorizontal||0,n=e.alignVertical||0,a=e.width||e.size||1,o=Math.floor(a/i),l=a-o*i,h=e.height||e.size||1,u=Math.floor(h/r),c=h-u*r,d=i*o/2,p=r*u/2,_=0,f=0,m=0,g=0,v=0,x=0;if(l>0||c>0){switch(m=-d,g=-p,v=d,x=p,s){case rV.Kj.CENTER:l/=2,m-=l,v+=l;break;case rV.Kj.LEFT:v+=l,_=-l/2;break;case rV.Kj.RIGHT:m-=l,_=l/2}switch(n){case rV.Kj.CENTER:c/=2,g-=c,x+=c;break;case rV.Kj.BOTTOM:x+=c,f=-c/2;break;case rV.Kj.TOP:g-=c,f=c/2}}let T=[],S=[],C=[];C[0]=[0,0,1,0,1,1,0,1],C[1]=[0,0,1,0,1,1,0,1],(t===rV.Kj.ROTATE_TILE||t===rV.Kj.ROTATE_ROW)&&(C[1]=[1,1,0,1,0,0,1,0]),(t===rV.Kj.FLIP_TILE||t===rV.Kj.FLIP_ROW)&&(C[1]=[1,0,0,0,0,1,1,1]),(t===rV.Kj.FLIP_N_ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_ROW)&&(C[1]=[0,1,1,1,1,0,0,0]);let E=[],b=[],y=[],P=0;for(let e=0;e<u;e++)for(let s=0;s<o;s++)T.push(-d+s*i+_,-p+e*r+f,0),T.push(-d+(s+1)*i+_,-p+e*r+f,0),T.push(-d+(s+1)*i+_,-p+(e+1)*r+f,0),T.push(-d+s*i+_,-p+(e+1)*r+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),E=t===rV.Kj.FLIP_TILE||t===rV.Kj.ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_TILE?E.concat(C[(s%2+e%2)%2]):t===rV.Kj.FLIP_ROW||t===rV.Kj.ROTATE_ROW||t===rV.Kj.FLIP_N_ROTATE_ROW?E.concat(C[e%2]):E.concat(C[0]),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1),P+=4;if(l>0||c>0){let e,a,h,C;let R=c>0&&(n===rV.Kj.CENTER||n===rV.Kj.TOP),A=c>0&&(n===rV.Kj.CENTER||n===rV.Kj.BOTTOM),I=l>0&&(s===rV.Kj.CENTER||s===rV.Kj.RIGHT),M=l>0&&(s===rV.Kj.CENTER||s===rV.Kj.LEFT),D=[];if(R&&I&&(T.push(m+_,g+f,0),T.push(-d+_,g+f,0),T.push(-d+_,g+c+f,0),T.push(m+_,g+c+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,h=1,C=1,D=[e=1-l/i,a=1-c/r,h,a,h,C,e,C],t===rV.Kj.ROTATE_ROW&&(D=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),t===rV.Kj.FLIP_ROW&&(D=[1-e,a,1-h,a,1-h,C,1-e,C]),t===rV.Kj.FLIP_N_ROTATE_ROW&&(D=[e,1-a,h,1-a,h,1-C,e,1-C]),E=E.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),R&&M&&(T.push(d+_,g+f,0),T.push(v+_,g+f,0),T.push(v+_,g+c+f,0),T.push(d+_,g+c+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,C=1,D=[e=0,a=1-c/r,h=l/i,a,h,C,e,C],(t===rV.Kj.ROTATE_ROW||t===rV.Kj.ROTATE_TILE&&o%2==0)&&(D=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_ROW||t===rV.Kj.FLIP_TILE&&o%2==0)&&(D=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_ROW||t===rV.Kj.FLIP_N_ROTATE_TILE&&o%2==0)&&(D=[e,1-a,h,1-a,h,1-C,e,1-C]),E=E.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),A&&I&&(T.push(m+_,p+f,0),T.push(-d+_,p+f,0),T.push(-d+_,x+f,0),T.push(m+_,x+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,a=0,h=1,D=[e=1-l/i,a,h,a,h,C=c/r,e,C],(t===rV.Kj.ROTATE_ROW&&u%2==1||t===rV.Kj.ROTATE_TILE&&u%1==0)&&(D=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_ROW&&u%2==1||t===rV.Kj.FLIP_TILE&&u%2==0)&&(D=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_ROW&&u%2==1||t===rV.Kj.FLIP_N_ROTATE_TILE&&u%2==0)&&(D=[e,1-a,h,1-a,h,1-C,e,1-C]),E=E.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),A&&M&&(T.push(d+_,p+f,0),T.push(v+_,p+f,0),T.push(v+_,x+f,0),T.push(d+_,x+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,D=[e=0,a=0,h=l/i,a,h,C=c/r,e,C],(t===rV.Kj.ROTATE_ROW&&u%2==1||t===rV.Kj.ROTATE_TILE&&(u+o)%2==1)&&(D=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_ROW&&u%2==1||t===rV.Kj.FLIP_TILE&&(u+o)%2==1)&&(D=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_ROW&&u%2==1||t===rV.Kj.FLIP_N_ROTATE_TILE&&(u+o)%2==1)&&(D=[e,1-a,h,1-a,h,1-C,e,1-C]),E=E.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),R){let s=[];e=0,a=1-c/r,h=1,C=1,s[0]=[e,a,h,a,h,C,e,C],s[1]=[e,a,h,a,h,C,e,C],(t===rV.Kj.ROTATE_TILE||t===rV.Kj.ROTATE_ROW)&&(s[1]=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_TILE||t===rV.Kj.FLIP_ROW)&&(s[1]=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-a,h,1-a,h,1-C,e,1-C]);for(let e=0;e<o;e++)T.push(-d+e*i+_,g+f,0),T.push(-d+(e+1)*i+_,g+f,0),T.push(-d+(e+1)*i+_,g+c+f,0),T.push(-d+e*i+_,g+c+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,E=t===rV.Kj.FLIP_TILE||t===rV.Kj.ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_TILE?E.concat(s[(e+1)%2]):t===rV.Kj.FLIP_ROW||t===rV.Kj.ROTATE_ROW||t===rV.Kj.FLIP_N_ROTATE_ROW?E.concat(s[1]):E.concat(s[0]),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(A){let s=[];e=0,a=0,h=1,C=c/r,s[0]=[e,a,h,a,h,C,e,C],s[1]=[e,a,h,a,h,C,e,C],(t===rV.Kj.ROTATE_TILE||t===rV.Kj.ROTATE_ROW)&&(s[1]=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_TILE||t===rV.Kj.FLIP_ROW)&&(s[1]=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-a,h,1-a,h,1-C,e,1-C]);for(let e=0;e<o;e++)T.push(-d+e*i+_,x-c+f,0),T.push(-d+(e+1)*i+_,x-c+f,0),T.push(-d+(e+1)*i+_,x+f,0),T.push(-d+e*i+_,x+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,E=t===rV.Kj.FLIP_TILE||t===rV.Kj.ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_TILE?E.concat(s[(e+u)%2]):t===rV.Kj.FLIP_ROW||t===rV.Kj.ROTATE_ROW||t===rV.Kj.FLIP_N_ROTATE_ROW?E.concat(s[u%2]):E.concat(s[0]),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(I){let s=[];e=1-l/i,a=0,h=1,C=1,s[0]=[e,a,h,a,h,C,e,C],s[1]=[e,a,h,a,h,C,e,C],(t===rV.Kj.ROTATE_TILE||t===rV.Kj.ROTATE_ROW)&&(s[1]=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_TILE||t===rV.Kj.FLIP_ROW)&&(s[1]=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-a,h,1-a,h,1-C,e,1-C]);for(let e=0;e<u;e++)T.push(m+_,-p+e*r+f,0),T.push(m+l+_,-p+e*r+f,0),T.push(m+l+_,-p+(e+1)*r+f,0),T.push(m+_,-p+(e+1)*r+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,E=t===rV.Kj.FLIP_TILE||t===rV.Kj.ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_TILE?E.concat(s[(e+1)%2]):t===rV.Kj.FLIP_ROW||t===rV.Kj.ROTATE_ROW||t===rV.Kj.FLIP_N_ROTATE_ROW?E.concat(s[e%2]):E.concat(s[0]),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(M){let i=[];e=0,a=0,h=l/r,C=1,i[0]=[e,a,h,a,h,C,e,C],i[1]=[e,a,h,a,h,C,e,C],(t===rV.Kj.ROTATE_TILE||t===rV.Kj.ROTATE_ROW)&&(i[1]=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_TILE||t===rV.Kj.FLIP_ROW)&&(i[1]=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_ROW)&&(i[1]=[e,1-a,h,1-a,h,1-C,e,1-C]);for(let e=0;e<u;e++)T.push(v-l+_,-p+e*r+f,0),T.push(v+_,-p+e*r+f,0),T.push(v+_,-p+(e+1)*r+f,0),T.push(v-l+_,-p+(e+1)*r+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,E=t===rV.Kj.FLIP_TILE||t===rV.Kj.ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_TILE?E.concat(i[(e+o)%2]):t===rV.Kj.FLIP_ROW||t===rV.Kj.ROTATE_ROW||t===rV.Kj.FLIP_N_ROTATE_ROW?E.concat(i[e%2]):E.concat(i[0]),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}}let R=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE;se.x._ComputeSides(R,T,y,S,E,e.frontUVs,e.backUVs);let A=new se.x;A.indices=y,A.positions=T,A.normals=S,A.uvs=E;let I=R===se.x.DOUBLESIDE?b.concat(b):b;return A.colors=I,A}function CreateTiledBoxVertexData(e){let t=e.faceUV||Array(6),i=e.faceColors,r=e.pattern||rV.Kj.NO_FLIP,s=e.width||e.size||1,n=e.height||e.size||1,a=e.depth||e.size||1,o=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,u=e.alignVertical||0,c=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new rm.Lt(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new rg.HE(1,1,1,1));let d=[];for(let e=0;e<2;e++)d[e]=CreateTiledPlaneVertexData({pattern:r,tileWidth:o,tileHeight:l,width:s,height:n,alignVertical:u,alignHorizontal:h,sideOrientation:c});for(let e=2;e<4;e++)d[e]=CreateTiledPlaneVertexData({pattern:r,tileWidth:o,tileHeight:l,width:a,height:n,alignVertical:u,alignHorizontal:h,sideOrientation:c});let p=u;u===rV.Kj.BOTTOM?p=rV.Kj.TOP:u===rV.Kj.TOP&&(p=rV.Kj.BOTTOM);for(let e=4;e<6;e++)d[e]=CreateTiledPlaneVertexData({pattern:r,tileWidth:o,tileHeight:l,width:s,height:a,alignVertical:p,alignHorizontal:h,sideOrientation:c});let _=[],f=[],m=[],g=[],v=[],x=[],T=[],S=[],C=0,E=0;for(let e=0;e<6;e++){let r=d[e].positions.length;x[e]=[],T[e]=[];for(let t=0;t<r/3;t++)x[e].push(new rm.P(d[e].positions[3*t],d[e].positions[3*t+1],d[e].positions[3*t+2])),T[e].push(new rm.P(d[e].normals[3*t],d[e].normals[3*t+1],d[e].normals[3*t+2]));C=d[e].uvs.length,S[e]=[];for(let i=0;i<C;i+=2)S[e][i]=t[e].x+(t[e].z-t[e].x)*d[e].uvs[i],S[e][i+1]=t[e].y+(t[e].w-t[e].y)*d[e].uvs[i+1],r4.e.UseOpenGLOrientationForUV&&(S[e][i+1]=1-S[e][i+1]);if(m=m.concat(S[e]),g=g.concat(d[e].indices.map(e=>e+E)),E+=x[e].length,i)for(let t=0;t<4;t++)v.push(i[e].r,i[e].g,i[e].b,i[e].a)}let b=new rm.P(0,0,a/2),y=rm.y3.RotationY(Math.PI);_=x[0].map(e=>rm.P.TransformNormal(e,y).add(b)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),f=T[0].map(e=>rm.P.TransformNormal(e,y)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),_=_.concat(x[1].map(e=>e.subtract(b)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[1].map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let P=new rm.P(s/2,0,0),R=rm.y3.RotationY(-Math.PI/2);_=_.concat(x[2].map(e=>rm.P.TransformNormal(e,R).add(P)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[2].map(e=>rm.P.TransformNormal(e,R)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let A=rm.y3.RotationY(Math.PI/2);_=_.concat(x[3].map(e=>rm.P.TransformNormal(e,A).subtract(P)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[3].map(e=>rm.P.TransformNormal(e,A)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let I=new rm.P(0,n/2,0),M=rm.y3.RotationX(Math.PI/2);_=_.concat(x[4].map(e=>rm.P.TransformNormal(e,M).add(I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[4].map(e=>rm.P.TransformNormal(e,M)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let D=rm.y3.RotationX(-Math.PI/2);_=_.concat(x[5].map(e=>rm.P.TransformNormal(e,D).subtract(I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[5].map(e=>rm.P.TransformNormal(e,D)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),se.x._ComputeSides(c,_,g,f,m);let O=new se.x;if(O.indices=g,O.positions=_,O.normals=f,O.uvs=m,i){let e=c===se.x.DOUBLESIDE?v.concat(v):v;O.colors=e}return O}function CreateTorusKnotVertexData(e){let t,i;let r=[],s=[],n=[],a=[],o=e.radius||2,l=e.tube||.5,h=e.radialSegments||32,u=e.tubularSegments||32,c=e.p||2,d=e.q||3,p=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,getPos=e=>{let t=d/c*e,i=Math.cos(t),r=o*Math.sin(t)*.5;return new rm.P(o*(2+i)*.5*Math.cos(e),o*(2+i)*Math.sin(e)*.5,r)};for(t=0;t<=h;t++){let e=t%h,r=e/h*2*c*Math.PI,n=getPos(r),o=getPos(r+.01),d=o.subtract(n),p=o.add(n),_=rm.P.Cross(d,p);for(p=rm.P.Cross(_,d),_.normalize(),p.normalize(),i=0;i<u;i++){let e=i%u,r=e/u*2*Math.PI,o=-l*Math.cos(r),c=l*Math.sin(r);s.push(n.x+o*p.x+c*_.x),s.push(n.y+o*p.y+c*_.y),s.push(n.z+o*p.z+c*_.z),a.push(t/h),a.push(r4.e.UseOpenGLOrientationForUV?1-i/u:i/u)}}for(t=0;t<h;t++)for(i=0;i<u;i++){let e=(i+1)%u,s=t*u+i,n=(t+1)*u+i,a=(t+1)*u+e,o=t*u+e;r.push(o),r.push(n),r.push(s),r.push(o),r.push(a),r.push(n)}se.x.ComputeNormals(s,r,n),se.x._ComputeSides(p,s,r,n,a,e.frontUVs,e.backUVs);let _=new se.x;return _.indices=r,_.positions=s,_.normals=n,_.uvs=a,_}function CreateTorusKnot(e,t={},i){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateTorusKnotVertexData(t);return s.applyToMesh(r,t.updatable),r}DebugLayer.InspectorURL=`${rW.w1._DefaultCdnUrl}/v${rq.D.Version}/inspector/babylon.inspector.bundle.js`,DebugLayer.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0},se.x.CreateBox=CreateBoxVertexData,rV.Kj.CreateBox=(e,t,i=null,r,s)=>boxBuilder_CreateBox(e,{size:t,sideOrientation:s,updatable:r},i),se.x.CreateSphere=CreateSphereVertexData,rV.Kj.CreateSphere=(e,t,i,r,s,n)=>sphereBuilder_CreateSphere(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:s},r),rV.Kj.CreateCapsule=(e,t,i)=>capsuleBuilder_CreateCapsule(e,t,i),se.x.CreateCapsule=CreateCapsuleVertexData,se.x.CreateRibbon=CreateRibbonVertexData,rV.Kj.CreateRibbon=(e,t,i=!1,r,s,n,a=!1,o,l)=>CreateRibbon(e,{pathArray:t,closeArray:i,closePath:r,offset:s,updatable:a,sideOrientation:o,instance:l},n),se.x.CreateDisc=CreateDiscVertexData,rV.Kj.CreateDisc=(e,t,i,r=null,s,n)=>discBuilder_CreateDisc(e,{radius:t,tessellation:i,sideOrientation:n,updatable:s},r),se.x.CreateTiledPlane=CreateTiledPlaneVertexData,se.x.CreateTiledBox=CreateTiledBoxVertexData,se.x.CreateTorusKnot=CreateTorusKnotVertexData,rV.Kj.CreateTorusKnot=(e,t,i,r,s,n,a,o,l,h)=>CreateTorusKnot(e,{radius:t,tube:i,radialSegments:r,tubularSegments:s,p:n,q:a,sideOrientation:h,updatable:l},o);let nJ={effect:null,subMesh:null};let shaderMaterial_ShaderMaterial=class shaderMaterial_ShaderMaterial extends PushMaterial{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new rm.y3,this._cachedWorldViewProjectionMatrix=new rm.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},r)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}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);let i=new Float32Array(16*t.length);for(let e=0;e<t.length;e++){let r=t[e];r.copyToArray(i,16*e)}return this._matrixArrays[e]=i,this}setMatrix3x3(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this}setMatrix2x2(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this}setArray2(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this}setArray3(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this}setArray4(e,t){return this._checkUniform(e),this._vectors4Arrays[e]=t,this}setUniformBuffer(e,t){return -1===this._options.uniformBuffers.indexOf(e)&&this._options.uniformBuffers.push(e),this._uniformBuffers[e]=t,this}setTextureSampler(e,t){return -1===this._options.samplerObjects.indexOf(e)&&this._options.samplerObjects.push(e),this._textureSamplers[e]=t,this}setStorageBuffer(e,t){return -1===this._options.storageBuffers.indexOf(e)&&this._options.storageBuffers.push(e),this._storageBuffers[e]=t,this}setDefine(e,t){let i=e.trimEnd()+" ",r=this.options.defines.findIndex(t=>t===e||t.startsWith(i));return r>=0&&this.options.defines.splice(r,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var r,s,n;let a=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){if(a){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{let e=this._drawWrapper.effect;if(e&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}}let o=this.getScene(),l=o.getEngine(),h=[],u=[],c=new EffectFallbacks,d=this._shaderPath,p=this._options.uniforms,_=this._options.uniformBuffers,f=this._options.samplers;l.getCaps().multiview&&o.activeCamera&&o.activeCamera.outputRenderTarget&&o.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,h.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let e=0;e<this._options.defines.length;e++){let t=0===this._options.defines[e].indexOf("#define")?this._options.defines[e]:`#define ${this._options.defines[e]}`;h.push(t)}for(let e=0;e<this._options.attributes.length;e++)u.push(this._options.attributes[e]);if(e&&e.isVerticesDataPresent(rz.o.ColorKind)&&(-1===u.indexOf(rz.o.ColorKind)&&u.push(rz.o.ColorKind),h.push("#define VERTEXCOLOR")),t&&(h.push("#define INSTANCES"),so.G.PushAttributesForInstances(u,this._materialHelperNeedsPreviousMatrices),(null==e?void 0:e.hasThinInstances)&&(h.push("#define THIN_INSTANCES"),e&&e.isVerticesDataPresent(rz.o.ColorInstanceKind)&&(u.push(rz.o.ColorInstanceKind),h.push("#define INSTANCESCOLOR")))),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){u.push(rz.o.MatricesIndicesKind),u.push(rz.o.MatricesWeightsKind),e.numBoneInfluencers>4&&(u.push(rz.o.MatricesIndicesExtraKind),u.push(rz.o.MatricesWeightsExtraKind));let t=e.skeleton;h.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),c.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(h.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")):(h.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else h.push("#define NUM_BONE_INFLUENCERS 0");let m=0,g=e?e.morphTargetManager:null;if(g){let e=g.supportsUVs&&-1!==h.indexOf("#define UV1"),t=g.supportsTangents&&-1!==h.indexOf("#define TANGENT"),i=g.supportsNormals&&-1!==h.indexOf("#define NORMAL");m=g.numInfluencers,e&&h.push("#define MORPHTARGETS_UV"),t&&h.push("#define MORPHTARGETS_TANGENT"),i&&h.push("#define MORPHTARGETS_NORMAL"),m>0&&h.push("#define MORPHTARGETS"),g.isUsingTextureForTargets&&(h.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")),h.push("#define NUM_MORPH_INFLUENCERS "+m);for(let r=0;r<m;r++)u.push(rz.o.PositionKind+r),i&&u.push(rz.o.NormalKind+r),t&&u.push(rz.o.TangentKind+r),e&&u.push(rz.o.UVKind+"_"+r);m>0&&((p=p.slice()).push("morphTargetInfluences"),p.push("morphTargetTextureInfo"),p.push("morphTargetTextureIndices"))}else h.push("#define NUM_MORPH_INFLUENCERS 0");if(e){let t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(h.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")),so.G.PrepareAttributesForBakedVertexAnimation(u,e,h)}for(let e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&h.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&((0,nX.qx)(p),(0,nX.lK)(this,o,h)),this.customShaderNameResolve&&(p=p.slice(),_=_.slice(),f=f.slice(),d=this.customShaderNameResolve(d,p,_,f,h,u));let v=a?i._getDrawWrapper():this._drawWrapper,x=null!==(r=null==v?void 0:v.effect)&&void 0!==r?r:null,T=null!==(s=null==v?void 0:v.defines)&&void 0!==s?s:null,S=h.join("\n"),C=x;return T!==S&&(C=l.createEffect(d,{attributes:u,uniformsNames:p,uniformBuffersNames:_,samplers:f,defines:S,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage},l),a?i.setEffect(C,S,this._materialContext):v&&v.setEffect(C,S),this._onEffectCreatedObservable&&(nJ.effect=C,nJ.subMesh=null!==(n=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==n?n:null,this._onEffectCreatedObservable.notifyObservers(nJ))),C._wasPreviouslyUsingInstances=!!t,!!(null==C?void 0:C.isReady())&&(x!==C&&o.resetCachedMaterial(),C._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){let i=this.getScene(),r=null!=t?t:this.getEffect();r&&(-1!==this._options.uniforms.indexOf("world")&&r.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var r;this.bind(e,t,null===(r=i._drawWrapperOverride)||void 0===r?void 0:r.effect,i)}bind(e,t,i,r){var s;let n=r&&this._storeEffectOnSubMeshes,a=null!=i?i:n?r.effect:this.getEffect();if(!a)return;this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);let o=this._options.uniformBuffers,l=!1;if(a&&o&&o.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let i=0;i<o.length;++i){let r=o[i];switch(r){case"Mesh":t&&(t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e));break;case"Scene":so.G.BindSceneUniformBuffer(a,this.getScene().getSceneUniformBuffer()),this.getScene().finalizeSceneUbo(),l=!0}}let h=t&&n?this._mustRebind(this.getScene(),a,t.visibility):this.getScene().getCachedMaterial()!==this;if(a&&h){let e;for(e in l||-1===this._options.uniforms.indexOf("view")||a.setMatrix("view",this.getScene().getViewMatrix()),l||-1===this._options.uniforms.indexOf("projection")||a.setMatrix("projection",this.getScene().getProjectionMatrix()),!l&&-1!==this._options.uniforms.indexOf("viewProjection")&&(a.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._multiview&&a.setMatrix("viewProjectionR",this.getScene()._transformMatrixR)),this.getScene().activeCamera&&-1!==this._options.uniforms.indexOf("cameraPosition")&&a.setVector3("cameraPosition",this.getScene().activeCamera.globalPosition),so.G.BindBonesParameters(t,a),(0,nX.an)(a,this,this.getScene()),this._textures)a.setTexture(e,this._textures[e]);for(e in this._textureArrays)a.setTextureArray(e,this._textureArrays[e]);for(e in this._externalTextures)a.setExternalTexture(e,this._externalTextures[e]);for(e in this._ints)a.setInt(e,this._ints[e]);for(e in this._uints)a.setUInt(e,this._uints[e]);for(e in this._floats)a.setFloat(e,this._floats[e]);for(e in this._floatsArrays)a.setArray(e,this._floatsArrays[e]);for(e in this._colors3)a.setColor3(e,this._colors3[e]);for(e in this._colors3Arrays)a.setArray3(e,this._colors3Arrays[e]);for(e in this._colors4){let t=this._colors4[e];a.setFloat4(e,t.r,t.g,t.b,t.a)}for(e in this._colors4Arrays)a.setArray4(e,this._colors4Arrays[e]);for(e in this._vectors2)a.setVector2(e,this._vectors2[e]);for(e in this._vectors3)a.setVector3(e,this._vectors3[e]);for(e in this._vectors4)a.setVector4(e,this._vectors4[e]);for(e in this._quaternions)a.setQuaternion(e,this._quaternions[e]);for(e in this._matrices)a.setMatrix(e,this._matrices[e]);for(e in this._matrixArrays)a.setMatrices(e,this._matrixArrays[e]);for(e in this._matrices3x3)a.setMatrix3x3(e,this._matrices3x3[e]);for(e in this._matrices2x2)a.setMatrix2x2(e,this._matrices2x2[e]);for(e in this._vectors2Arrays)a.setArray2(e,this._vectors2Arrays[e]);for(e in this._vectors3Arrays)a.setArray3(e,this._vectors3Arrays[e]);for(e in this._vectors4Arrays)a.setArray4(e,this._vectors4Arrays[e]);for(e in this._quaternionsArrays)a.setArray4(e,this._quaternionsArrays[e]);for(e in this._uniformBuffers){let t=this._uniformBuffers[e].getBuffer();t&&a.bindUniformBuffer(t,e)}for(e in this._textureSamplers)a.setTextureSampler(e,this._textureSamplers[e]);for(e in this._storageBuffers)a.setStorageBuffer(e,this._storageBuffers[e])}if(a&&t&&(h||!this.isFrozen)){let e=t.morphTargetManager;e&&e.numInfluencers>0&&so.G.BindMorphTargetParameters(t,a);let i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(a,!!a._wasPreviouslyUsingInstances))}this._afterBind(t,a)}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._textures)e.push(this._textures[t]);for(let t in this._textureArrays){let i=this._textureArrays[t];for(let t=0;t<i.length;t++)e.push(i[t])}return e}hasTexture(e){if(super.hasTexture(e))return!0;for(let t in this._textures)if(this._textures[t]===e)return!0;for(let t in this._textureArrays){let i=this._textureArrays[t];for(let t=0;t<i.length;t++)if(i[t]===e)return!0}return!1}clone(e){let t=rb.p4.Clone(()=>new shaderMaterial_ShaderMaterial(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);for(let i in 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=>{let t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))}),this.stencil.copyTo(t.stencil),this._textures)t.setTexture(i,this._textures[i]);for(let e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(let e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(let e in this._ints)t.setInt(e,this._ints[e]);for(let e in this._uints)t.setUInt(e,this._uints[e]);for(let e in this._floats)t.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(let e in this._colors3)t.setColor3(e,this._colors3[e]);for(let e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(let e in this._colors4)t.setColor4(e,this._colors4[e]);for(let e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(let e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(let e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(let e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(let e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(let e in this._matrices)t.setMatrix(e,this._matrices[e]);for(let e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(let e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(let e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(let e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(let e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(let e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(let e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(let e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(let e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){let t=this._textureArrays[e];for(let e=0;e<t.length;e++)t[e].dispose()}}this._textures={},super.dispose(e,t,i)}serialize(){let e;let t=rb.p4.Serialize(this);for(e in t.customType="BABYLON.ShaderMaterial",t.uniqueId=this.uniqueId,t.options=this._options,t.shaderPath=this._shaderPath,t.storeEffectOnSubMeshes=this._storeEffectOnSubMeshes,t.stencil=this.stencil.serialize(),t.textures={},this._textures)t.textures[e]=this._textures[e].serialize();for(e in t.textureArrays={},this._textureArrays){t.textureArrays[e]=[];let i=this._textureArrays[e];for(let r=0;r<i.length;r++)t.textureArrays[e].push(i[r].serialize())}for(e in t.ints={},this._ints)t.ints[e]=this._ints[e];for(e in t.uints={},this._uints)t.uints[e]=this._uints[e];for(e in t.floats={},this._floats)t.floats[e]=this._floats[e];for(e in t.FloatArrays={},this._floatsArrays)t.FloatArrays[e]=this._floatsArrays[e];for(e in t.colors3={},this._colors3)t.colors3[e]=this._colors3[e].asArray();for(e in t.colors3Arrays={},this._colors3Arrays)t.colors3Arrays[e]=this._colors3Arrays[e];for(e in t.colors4={},this._colors4)t.colors4[e]=this._colors4[e].asArray();for(e in t.colors4Arrays={},this._colors4Arrays)t.colors4Arrays[e]=this._colors4Arrays[e];for(e in t.vectors2={},this._vectors2)t.vectors2[e]=this._vectors2[e].asArray();for(e in t.vectors3={},this._vectors3)t.vectors3[e]=this._vectors3[e].asArray();for(e in t.vectors4={},this._vectors4)t.vectors4[e]=this._vectors4[e].asArray();for(e in t.quaternions={},this._quaternions)t.quaternions[e]=this._quaternions[e].asArray();for(e in t.matrices={},this._matrices)t.matrices[e]=this._matrices[e].asArray();for(e in t.matrixArray={},this._matrixArrays)t.matrixArray[e]=this._matrixArrays[e];for(e in t.matrices3x3={},this._matrices3x3)t.matrices3x3[e]=this._matrices3x3[e];for(e in t.matrices2x2={},this._matrices2x2)t.matrices2x2[e]=this._matrices2x2[e];for(e in t.vectors2Arrays={},this._vectors2Arrays)t.vectors2Arrays[e]=this._vectors2Arrays[e];for(e in t.vectors3Arrays={},this._vectors3Arrays)t.vectors3Arrays[e]=this._vectors3Arrays[e];for(e in t.vectors4Arrays={},this._vectors4Arrays)t.vectors4Arrays[e]=this._vectors4Arrays[e];for(e in t.quaternionsArrays={},this._quaternionsArrays)t.quaternionsArrays[e]=this._quaternionsArrays[e];return t}static Parse(e,t,i){let r;let s=rb.p4.Parse(()=>new shaderMaterial_ShaderMaterial(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,texture_Texture.Parse(e.textures[r],t,i));for(r in e.textureArrays){let n=e.textureArrays[r],a=[];for(let e=0;e<n.length;e++)a.push(texture_Texture.Parse(n[e],t,i));s.setTextureArray(r,a)}for(r in e.ints)s.setInt(r,e.ints[r]);for(r in e.uints)s.setUInt(r,e.uints[r]);for(r in e.floats)s.setFloat(r,e.floats[r]);for(r in e.floatsArrays)s.setFloats(r,e.floatsArrays[r]);for(r in e.colors3)s.setColor3(r,rg.Wo.FromArray(e.colors3[r]));for(r in e.colors3Arrays){let t=e.colors3Arrays[r].reduce((e,t,i)=>(i%3==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>rg.Wo.FromArray(e));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,rg.HE.FromArray(e.colors4[r]));for(r in e.colors4Arrays){let t=e.colors4Arrays[r].reduce((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>rg.HE.FromArray(e));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,rm.FM.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,rm.P.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,rm.Lt.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,rm._f.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,rm.y3.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,n)=>{let a=new rP.g;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let t=JSON.parse(a.responseText),n=this.Parse(t,i||rS.l.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the ShaderMaterial")}}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((r,s)=>{let n=new rP.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let s=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(s.shaderMaterial),o=this.Parse(a,t||rS.l.LastCreatedScene,i);o.snippetId=e,r(o)}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}};shaderMaterial_ShaderMaterial.SnippetUrl="https://snippet.babylonjs.com",shaderMaterial_ShaderMaterial.CreateFromSnippetAsync=shaderMaterial_ShaderMaterial.ParseFromSnippetAsync,(0,rv.H)("BABYLON.ShaderMaterial",shaderMaterial_ShaderMaterial);let n0=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +#define VERTEXCOLOR +varying vec4 vColor; +#else +uniform vec4 color; +#endif +#include<clipPlaneFragmentDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +gl_FragColor=vColor; +#else +gl_FragColor=color; +#endif +#define CUSTOM_FRAGMENT_MAIN_END +}`;s_.v.ShadersStore.colorPixelShader=n0;let n1=`attribute vec3 position; +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<clipPlaneVertexDeclaration> +#include<instancesDeclaration> +uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(position,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#include<clipPlaneVertex> +#include<vertexColorMixing> +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.colorVertexShader=n1,rV.Kj._LinesMeshParser=(e,t)=>LinesMesh.Parse(e,t);let LinesMesh=class LinesMesh extends rV.Kj{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,r=null,s,n,a,o){super(e,t,i,r,s),this.useVertexColor=n,this.useVertexAlpha=a,this.color=new rg.Wo(1,1,1),this.alpha=1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;let l={attributes:[rz.o.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===a?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(rz.o.ColorKind)):(l.uniforms.push("color"),this._color4=new rg.HE),o?this.material=o:(this.material=new shaderMaterial_ShaderMaterial("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=sr.F.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;let i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){let{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;let r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(sr.F.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(sr.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 LinesMesh(e,this.getScene(),t,this,i)}createInstance(e){let t=new InstancedLinesMesh(e,this);if(this.instancedBuffers)for(let e in t.instancedBuffers={},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){let i=new LinesMesh(e.name,t);return i.color=rg.Wo.FromArray(e.color),i.alpha=e.alpha,i}};let InstancedLinesMesh=class InstancedLinesMesh extends instancedMesh_InstancedMesh{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}};function CreateLineSystemVertexData(e){let t=[],i=[],r=e.lines,s=e.colors,n=[],a=0;for(let e=0;e<r.length;e++){let o=r[e];for(let r=0;r<o.length;r++){if(i.push(o[r].x,o[r].y,o[r].z),s){let t=s[e];n.push(t[r].r,t[r].g,t[r].b,t[r].a)}r>0&&(t.push(a-1),t.push(a)),a++}}let o=new se.x;return o.indices=t,o.positions=i,s&&(o.colors=n),o}function CreateDashedLinesVertexData(e){let t=e.dashSize||3,i=e.gapSize||1,r=e.dashNb||200,s=e.points,n=[],a=[],o=rm.P.Zero(),l=0,h=0,u=0,c=0,d=0,p=0,_=0;for(_=0;_<s.length-1;_++)s[_+1].subtractToRef(s[_],o),l+=o.length();for(_=0,c=t*(u=l/r)/(t+i);_<s.length-1;_++){s[_+1].subtractToRef(s[_],o),h=Math.floor(o.length()/u),o.normalize();for(let e=0;e<h;e++)d=u*e,n.push(s[_].x+d*o.x,s[_].y+d*o.y,s[_].z+d*o.z),n.push(s[_].x+(d+c)*o.x,s[_].y+(d+c)*o.y,s[_].z+(d+c)*o.z),a.push(p,p+1),p+=2}let f=new se.x;return f.positions=n,f.indices=a,f}function CreateLineSystem(e,t,i=null){let r=t.instance,s=t.lines,n=t.colors;if(r){let e,t;let i=r.getVerticesData(rz.o.PositionKind);n&&(e=r.getVerticesData(rz.o.ColorKind));let a=0,o=0;for(let r=0;r<s.length;r++){let l=s[r];for(let s=0;s<l.length;s++)i[a]=l[s].x,i[a+1]=l[s].y,i[a+2]=l[s].z,n&&e&&(t=n[r],e[o]=t[s].r,e[o+1]=t[s].g,e[o+2]=t[s].b,e[o+3]=t[s].a,o+=4),a+=3}return r.updateVerticesData(rz.o.PositionKind,i,!1,!1),n&&e&&r.updateVerticesData(rz.o.ColorKind,e,!1,!1),r}let a=new LinesMesh(e,i,null,void 0,void 0,!!n,t.useVertexAlpha,t.material),o=CreateLineSystemVertexData(t);return o.applyToMesh(a,t.updatable),a}function linesBuilder_CreateLines(e,t,i=null){let r=t.colors?[t.colors]:null,s=CreateLineSystem(e,{lines:[t.points],updatable:t.updatable,instance:t.instance,colors:r,useVertexAlpha:t.useVertexAlpha,material:t.material},i);return s}function CreateDashedLines(e,t,i=null){let r=t.points,s=t.instance,n=t.gapSize||1,a=t.dashSize||3;if(s)return(t.dashNb||t.dashSize||t.gapSize||t.useVertexAlpha||t.material)&&rT.Y.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."),s.updateMeshPositions(e=>{let t=rm.P.Zero(),i=e.length/6,n=0,a=0,o=0,l=0,h=0,u=0,c=0,d=0;for(c=0;c<r.length-1;c++)r[c+1].subtractToRef(r[c],t),n+=t.length();o=n/i;let p=s._creationDataStorage.dashSize,_=s._creationDataStorage.gapSize;for(c=0,l=p*o/(p+_);c<r.length-1;c++)for(r[c+1].subtractToRef(r[c],t),a=Math.floor(t.length()/o),t.normalize(),d=0;d<a&&u<e.length;)h=o*d,e[u]=r[c].x+h*t.x,e[u+1]=r[c].y+h*t.y,e[u+2]=r[c].z+h*t.z,e[u+3]=r[c].x+(h+l)*t.x,e[u+4]=r[c].y+(h+l)*t.y,e[u+5]=r[c].z+(h+l)*t.z,u+=6,d++;for(;u<e.length;)e[u]=r[c].x,e[u+1]=r[c].y,e[u+2]=r[c].z,u+=3},!1),s;let o=new LinesMesh(e,i,null,void 0,void 0,void 0,t.useVertexAlpha,t.material),l=CreateDashedLinesVertexData(t);return l.applyToMesh(o,t.updatable),o._creationDataStorage=new rV.gW,o._creationDataStorage.dashSize=a,o._creationDataStorage.gapSize=n,o}se.x.CreateLineSystem=CreateLineSystemVertexData,se.x.CreateDashedLines=CreateDashedLinesVertexData,rV.Kj.CreateLines=(e,t,i=null,r=!1,s=null)=>linesBuilder_CreateLines(e,{points:t,updatable:r,instance:s},i),rV.Kj.CreateDashedLines=(e,t,i,r,s,n=null,a,o)=>CreateDashedLines(e,{points:t,dashSize:i,gapSize:r,dashNb:s,updatable:a,instance:o},n);let IndexedVector2=class IndexedVector2 extends rm.FM{constructor(e,t){super(e.x,e.y),this.index=t}};let PolygonPoints=class PolygonPoints{constructor(){this.elements=[]}add(e){let t=[];return e.forEach(e=>{let i=new IndexedVector2(e,this.elements.length);t.push(i),this.elements.push(i)}),t}computeBounds(){let e=new rm.FM(this.elements[0].x,this.elements[0].y),t=new rm.FM(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.x<e.x?e.x=i.x:i.x>t.x&&(t.x=i.x),i.y<e.y?e.y=i.y:i.y>t.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}};let PolygonMeshBuilder=class PolygonMeshBuilder{_addToepoint(e){for(let t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){let s;this._points=new PolygonPoints,this._outlinepoints=new PolygonPoints,this._holes=[],this._epoints=[],this._eholes=[],this.bjsEarcut=r,this._name=e,this._scene=i||rS.l.LastCreatedScene,s=t instanceof math_path_Path2?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&rT.Y.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);let t=new PolygonPoints;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){let r=new rV.Kj(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(rz.o.PositionKind,s.positions,e),r.setVerticesData(rz.o.NormalKind,s.normals,e),r.setVerticesData(rz.o.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){let i=new se.x,r=[],s=[],n=[],a=this._points.computeBounds();this._points.elements.forEach(e=>{r.push(0,1,0),s.push(e.x,0,e.y),n.push((e.x-a.min.x)/a.width,(e.y-a.min.y)/a.height)});let o=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e<l.length;e++)o.push(l[e]);if(e>0){let i=s.length/3;this._points.elements.forEach(t=>{r.push(0,-1,0),s.push(t.x,-e,t.y),n.push(1-(t.x-a.min.x)/a.width,1-(t.y-a.min.y)/a.height)});let l=o.length;for(let e=0;e<l;e+=3){let t=o[e+0],r=o[e+1],s=o[e+2];o.push(s+i),o.push(r+i),o.push(t+i)}this._addSide(s,r,n,o,a,this._outlinepoints,e,!1,t),this._holes.forEach(i=>{this._addSide(s,r,n,o,a,i,e,!0,t)})}return i.indices=o,i.positions=s,i.normals=r,i.uvs=n,i}_addSide(e,t,i,r,s,n,a,o,l){let h=e.length/3,u=0;for(let c=0;c<n.elements.length;c++){let d=n.elements[c],p=n.elements[(c+1)%n.elements.length];e.push(d.x,0,d.y),e.push(d.x,-a,d.y),e.push(p.x,0,p.y),e.push(p.x,-a,p.y);let _=n.elements[(c+n.elements.length-1)%n.elements.length],f=n.elements[(c+2)%n.elements.length],m=new rm.P(-(p.y-d.y),0,p.x-d.x),g=new rm.P(-(d.y-_.y),0,d.x-_.x),v=new rm.P(-(f.y-p.y),0,f.x-p.x);o||(m=m.scale(-1),g=g.scale(-1),v=v.scale(-1));let x=m.normalizeToNew(),T=g.normalizeToNew(),S=v.normalizeToNew(),C=rm.P.Dot(T,x);T=C>l?C<rw.kn-1?new rm.P(d.x,0,d.y).subtract(new rm.P(p.x,0,p.y)).normalize():g.add(m).normalize():x;let E=rm.P.Dot(v,m);S=E>l?E<rw.kn-1?new rm.P(p.x,0,p.y).subtract(new rm.P(d.x,0,d.y)).normalize():v.add(m).normalize():x,i.push(u/s.width,0),i.push(u/s.width,1),u+=m.length(),i.push(u/s.width,0),i.push(u/s.width,1),t.push(T.x,T.y,T.z),t.push(T.x,T.y,T.z),t.push(S.x,S.y,S.z),t.push(S.x,S.y,S.z),o?(r.push(h),r.push(h+2),r.push(h+1),r.push(h+1),r.push(h+2),r.push(h+3)):(r.push(h),r.push(h+1),r.push(h+2),r.push(h+1),r.push(h+3),r.push(h+2)),h+=4}}};function CreatePolygonVertexData(e,t,i,r,s,n,a){let o=i||[,,,],l=[],h=a||!1;for(let e=0;e<3;e++)void 0===o[e]&&(o[e]=new rm.Lt(0,0,1,1)),r&&void 0===r[e]&&(r[e]=new rg.HE(1,1,1,1));let u=e.getVerticesData(rz.o.PositionKind),c=e.getVerticesData(rz.o.NormalKind),d=e.getVerticesData(rz.o.UVKind),p=e.getIndices(),_=u.length/9,f=0,m=0,g=0,v=0,x=[0];if(h)for(let e=_;e<u.length/3;e+=4)x.push(v+=Math.sqrt((m=u[3*(e+2)]-u[3*e])*m+(g=u[3*(e+2)+2]-u[3*e+2])*g));let T=0,S=0;for(let e=0;e<c.length;e+=3).001>Math.abs(c[e+1])&&(S=1),.001>Math.abs(c[e+1]-1)&&(S=0),.001>Math.abs(c[e+1]+1)&&(S=2),T=e/3,1===S?((f=T-_)%4<1.5?h?d[2*T]=o[S].x+(o[S].z-o[S].x)*x[Math.floor(f/4)]/v:d[2*T]=o[S].x:h?d[2*T]=o[S].x+(o[S].z-o[S].x)*x[Math.floor(f/4)+1]/v:d[2*T]=o[S].z,f%2==0?d[2*T+1]=r4.e.UseOpenGLOrientationForUV?1-o[S].w:o[S].w:d[2*T+1]=r4.e.UseOpenGLOrientationForUV?1-o[S].y:o[S].y):(d[2*T]=(1-d[2*T])*o[S].x+d[2*T]*o[S].z,d[2*T+1]=(1-d[2*T+1])*o[S].y+d[2*T+1]*o[S].w,r4.e.UseOpenGLOrientationForUV&&(d[2*T+1]=1-d[2*T+1])),r&&l.push(r[S].r,r[S].g,r[S].b,r[S].a);se.x._ComputeSides(t,u,p,c,d,s,n);let C=new se.x;if(C.indices=p,C.positions=u,C.normals=c,C.uvs=d,r){let e=t===se.x.DOUBLESIDE?l.concat(l):l;C.colors=e}return C}function CreatePolygon(e,t,i=null,r=earcut){t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation);let s=t.shape,n=t.holes||[],a=t.depth||0,o=t.smoothingThreshold||2,l=[],h=[];for(let e=0;e<s.length;e++)l[e]=new rm.FM(s[e].x,s[e].z);l[0].equalsWithEpsilon(l[l.length-1],1e-8)&&l.pop();let u=new PolygonMeshBuilder(e,l,i||rS.l.LastCreatedScene,r);for(let e=0;e<n.length;e++){h=[];for(let t=0;t<n[e].length;t++)h.push(new rm.FM(n[e][t].x,n[e][t].z));u.addHole(h)}let c=u.build(!1,a,o);c._originalBuilderSideOrientation=t.sideOrientation;let d=CreatePolygonVertexData(c,t.sideOrientation,t.faceUV,t.faceColors,t.frontUVs,t.backUVs,t.wrap);return d.applyToMesh(c,t.updatable),c}function ExtrudePolygon(e,t,i=null,r=earcut){return CreatePolygon(e,t,i,r)}function ExtrudeShape(e,t,i=null){let r=t.path,s=t.shape,n=t.scale||1,a=t.rotation||0,o=0===t.cap?0:t.cap||rV.Kj.NO_CAP,l=t.updatable,h=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),u=t.instance||null,c=t.invertUV||!1,d=t.closeShape||!1,p=t.closePath||!1;return _ExtrudeShapeGeneric(e,s,r,n,a,null,null,p,d,o,!1,i,!!l,h,u,c,t.frontUVs||null,t.backUVs||null,t.firstNormal||null,!!t.adjustFrame)}function ExtrudeShapeCustom(e,t,i=null){let r=t.path,s=t.shape,n=t.scaleFunction||(()=>1),a=t.rotationFunction||(()=>0),o=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||rV.Kj.NO_CAP,u=t.updatable,c=t.firstNormal||null,d=t.adjustFrame||!1,p=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),_=t.instance,f=t.invertUV||!1;return _ExtrudeShapeGeneric(e,s,r,null,null,n,a,o,l,h,!0,i,!!u,p,_||null,f,t.frontUVs||null,t.backUVs||null,c,d)}function _ExtrudeShapeGeneric(e,t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x){let T,S;let extrusionPathArray=(e,t,i,r,s,n,a,o,l,h,u)=>{let c=i.getTangents(),d=i.getNormals(),p=i.getBinormals(),_=i.getDistances();if(u){for(let e=0;e<c.length;e++)if(0==c[e].x&&0==c[e].y&&0==c[e].z&&c[e].copyFrom(c[e-1]),0==d[e].x&&0==d[e].y&&0==d[e].z&&d[e].copyFrom(d[e-1]),0==p[e].x&&0==p[e].y&&0==p[e].z&&p[e].copyFrom(p[e-1]),e>0){let t=c[e-1];0>rm.P.Dot(t,c[e])&&c[e].scaleInPlace(-1),t=d[e-1],0>rm.P.Dot(t,d[e])&&d[e].scaleInPlace(-1),t=p[e-1],0>rm.P.Dot(t,p[e])&&p[e].scaleInPlace(-1)}}let f=0,m=h&&o?o:()=>null!==n?n:0,g=h&&a?a:()=>null!==s?s:1,v=l===rV.Kj.NO_CAP||l===rV.Kj.CAP_END?0:2,x=rm.jp.Matrix[0];for(let i=0;i<t.length;i++){let s=[],n=m(i,_[i]),a=g(i,_[i]);rm.y3.RotationAxisToRef(c[i],f,x);for(let r=0;r<e.length;r++){let n=c[i].scale(e[r].z).add(d[i].scale(e[r].x)).add(p[i].scale(e[r].y)),o=rm.P.Zero();rm.P.TransformCoordinatesToRef(n,x,o),o.scaleInPlace(a).addInPlace(t[i]),s[r]=o}r[v]=s,f+=n,v++}let capPath=e=>{let t;let i=[],r=rm.P.Zero();for(t=0;t<e.length;t++)r.addInPlace(e[t]);for(r.scaleInPlace(1/e.length),t=0;t<e.length;t++)i.push(r);return i};switch(l){case rV.Kj.NO_CAP:break;case rV.Kj.CAP_START:r[0]=capPath(r[2]),r[1]=r[2];break;case rV.Kj.CAP_END:r[v]=r[v-1],r[v+1]=capPath(r[v-1]);break;case rV.Kj.CAP_ALL:r[0]=capPath(r[2]),r[1]=r[2],r[v]=r[v-1],r[v+1]=capPath(r[v-1])}return r};if(_){let e=_._creationDataStorage;return T=v?e.path3D.update(i,v):e.path3D.update(i),_=CreateRibbon("",{pathArray:S=extrusionPathArray(t,i,e.path3D,e.pathArray,r,s,n,a,e.cap,u,x),closeArray:!1,closePath:!1,offset:0,updatable:!1,sideOrientation:0,instance:_},c||void 0)}T=v?new Path3D(i,v):new Path3D(i),S=extrusionPathArray(t,i,T,[],r,s,n,a,h=h<0||h>3?0:h,u,x);let C=CreateRibbon(e,{pathArray:S,closeArray:o,closePath:l,updatable:d,sideOrientation:p,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},c);return C._creationDataStorage.pathArray=S,C._creationDataStorage.path3D=T,C._creationDataStorage.cap=h,C}function CreateLathe(e,t,i=null){let r,s;let n=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,a=void 0===t.closed||t.closed,o=t.shape,l=t.radius||1,h=t.tessellation||64,u=t.clip||0,c=t.updatable,d=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),p=t.cap||rV.Kj.NO_CAP,_=[],f=t.invertUV||!1,m=0,g=0,v=2*Math.PI/h*n;for(m=0;m<=h-u;m++){for(s=[],(p==rV.Kj.CAP_START||p==rV.Kj.CAP_ALL)&&(s.push(new rm.P(0,o[0].y,0)),s.push(new rm.P(Math.cos(m*v)*o[0].x*l,o[0].y,Math.sin(m*v)*o[0].x*l))),g=0;g<o.length;g++)r=new rm.P(Math.cos(m*v)*o[g].x*l,o[g].y,Math.sin(m*v)*o[g].x*l),s.push(r);(p==rV.Kj.CAP_END||p==rV.Kj.CAP_ALL)&&(s.push(new rm.P(Math.cos(m*v)*o[o.length-1].x*l,o[o.length-1].y,Math.sin(m*v)*o[o.length-1].x*l)),s.push(new rm.P(0,o[o.length-1].y,0))),_.push(s)}let x=CreateRibbon(e,{pathArray:_,closeArray:a,sideOrientation:d,updatable:c,invertUV:f,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return x}function CreateTube(e,t,i=null){let r,s;let n=t.path,a=t.instance,o=1;void 0!==t.radius?o=t.radius:a&&(o=a._creationDataStorage.radius);let l=t.tessellation||64,h=t.radiusFunction||null,u=t.cap||rV.Kj.NO_CAP,c=t.invertUV||!1,d=t.updatable,p=rV.Kj._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;let tubePathArray=(e,t,i,r,s,n,a,o)=>{let l,h,u,c;let d=t.getTangents(),p=t.getNormals(),_=t.getDistances(),f=2*Math.PI/s*o,m=n||(()=>r),g=rm.jp.Matrix[0],v=a===rV.Kj.NO_CAP||a===rV.Kj.CAP_END?0:2;for(let t=0;t<e.length;t++){h=m(t,_[t]),l=[],u=p[t];for(let i=0;i<s;i++)rm.y3.RotationAxisToRef(d[t],f*i,g),c=l[i]?l[i]:rm.P.Zero(),rm.P.TransformCoordinatesToRef(u,g,c),c.scaleInPlace(h).addInPlace(e[t]),l[i]=c;i[v]=l,v++}let capPath=(t,i)=>{let r=[];for(let s=0;s<t;s++)r.push(e[i]);return r};switch(a){case rV.Kj.NO_CAP:break;case rV.Kj.CAP_START:i[0]=capPath(s,0),i[1]=i[2].slice(0);break;case rV.Kj.CAP_END:i[v]=i[v-1].slice(0),i[v+1]=capPath(s,e.length-1);break;case rV.Kj.CAP_ALL:i[0]=capPath(s,0),i[1]=i[2].slice(0),i[v]=i[v-1].slice(0),i[v+1]=capPath(s,e.length-1)}return i};if(a){let e=a._creationDataStorage,i=t.arc||e.arc;return r=e.path3D.update(n),a=CreateRibbon("",{pathArray:s=tubePathArray(n,r,e.pathArray,o,e.tessellation,h,e.cap,i),instance:a}),e.path3D=r,e.pathArray=s,e.arc=i,e.radius=o,a}r=new Path3D(n),s=tubePathArray(n,r,[],o,l,h,u=u<0||u>3?0:u,t.arc);let _=CreateRibbon(e,{pathArray:s,closePath:!0,closeArray:!1,updatable:d,sideOrientation:p,invertUV:c,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return _._creationDataStorage.pathArray=s,_._creationDataStorage.path3D=r,_._creationDataStorage.tessellation=l,_._creationDataStorage.cap=u,_._creationDataStorage.arc=t.arc,_._creationDataStorage.radius=o,_}function CreatePolyhedronVertexData(e){let t,i,r,s,n,a;let o=[];o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]};let l=e.type&&(e.type<0||e.type>=o.length)?0:e.type||0,h=e.size,u=e.sizeX||h||1,c=e.sizeY||h||1,d=e.sizeZ||h||1,p=e.custom||o[l],_=p.face.length,f=e.faceUV||Array(_),m=e.faceColors,g=void 0===e.flat||e.flat,v=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,x=[],T=[],S=[],C=[],E=[],b=0,y=0,P=[],R=0,A=0;if(g)for(A=0;A<_;A++)m&&void 0===m[A]&&(m[A]=new rg.HE(1,1,1,1)),f&&void 0===f[A]&&(f[A]=new rm.Lt(0,0,1,1));if(g)for(A=0;A<_;A++){let e=p.face[A].length;for(R=0,s=.5*Math.tan((r=2*Math.PI/e)/2),n=.5;R<e;R++)x.push(p.vertex[p.face[A][R]][0]*u,p.vertex[p.face[A][R]][1]*c,p.vertex[p.face[A][R]][2]*d),P.push(b),b++,t=f[A].x+(f[A].z-f[A].x)*(.5+s),i=f[A].y+(f[A].w-f[A].y)*(n-.5),C.push(t,r4.e.UseOpenGLOrientationForUV?1-i:i),a=s*Math.cos(r)-n*Math.sin(r),n=s*Math.sin(r)+n*Math.cos(r),s=a,m&&E.push(m[A].r,m[A].g,m[A].b,m[A].a);for(R=0;R<e-2;R++)T.push(P[0+y],P[R+2+y],P[R+1+y]);y+=e}else{for(R=0;R<p.vertex.length;R++)x.push(p.vertex[R][0]*u,p.vertex[R][1]*c,p.vertex[R][2]*d),C.push(0,r4.e.UseOpenGLOrientationForUV?1:0);for(A=0;A<_;A++)for(R=0;R<p.face[A].length-2;R++)T.push(p.face[A][0],p.face[A][R+2],p.face[A][R+1])}se.x.ComputeNormals(x,T,S),se.x._ComputeSides(v,x,T,S,C,e.frontUVs,e.backUVs);let I=new se.x;return I.positions=x,I.indices=T,I.normals=S,I.uvs=C,m&&g&&(I.colors=E),I}function polyhedronBuilder_CreatePolyhedron(e,t={},i=null){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreatePolyhedronVertexData(t);return s.applyToMesh(r,t.updatable),r}se.x.CreatePolygon=CreatePolygonVertexData,rV.Kj.CreatePolygon=(e,t,i,r,s,n,a=earcut)=>CreatePolygon(e,{shape:t,holes:r,updatable:s,sideOrientation:n},i,a),rV.Kj.ExtrudePolygon=(e,t,i,r,s,n,a,o=earcut)=>ExtrudePolygon(e,{shape:t,holes:s,depth:i,updatable:n,sideOrientation:a},r,o),rV.Kj.ExtrudeShape=(e,t,i,r,s,n,a=null,o,l,h)=>{let u={shape:t,path:i,scale:r,rotation:s,cap:0===n?0:n||rV.Kj.NO_CAP,sideOrientation:l,instance:h,updatable:o};return ExtrudeShape(e,u,a)},rV.Kj.ExtrudeShapeCustom=(e,t,i,r,s,n,a,o,l,h,u,c)=>{let d={shape:t,path:i,scaleFunction:r,rotationFunction:s,ribbonCloseArray:n,ribbonClosePath:a,cap:0===o?0:o||rV.Kj.NO_CAP,sideOrientation:u,instance:c,updatable:h};return ExtrudeShapeCustom(e,d,l)},rV.Kj.CreateLathe=(e,t,i,r,s,n,a)=>CreateLathe(e,{shape:t,radius:i,tessellation:r,sideOrientation:a,updatable:n},s),rV.Kj.CreateTube=(e,t,i,r,s,n,a,o,l,h)=>CreateTube(e,{path:t,radius:i,tessellation:r,radiusFunction:s,arc:1,cap:n,updatable:o,sideOrientation:l,instance:h},a),se.x.CreatePolyhedron=CreatePolyhedronVertexData,rV.Kj.CreatePolyhedron=(e,t,i)=>polyhedronBuilder_CreatePolyhedron(e,t,i);let n2=new rm.P(1,0,0),n3=new rm.P(-1,0,0),n4=new rm.P(0,1,0),n5=new rm.P(0,-1,0),n6=new rm.P(0,0,1),n8=new rm.P(0,0,-1);let DecalVertex=class DecalVertex{constructor(e=rm.P.Zero(),t=rm.P.Up(),i=rm.FM.Zero(),r=0,s=0,n=null,a=null,o=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=n,this.localNormalOverride=a,this.matrixIndicesOverride=o,this.matrixWeightsOverride=l}clone(){var e,t,i,r;return new DecalVertex(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===(r=this.matrixWeightsOverride)||void 0===r?void 0:r.slice())}};function CreateDecal(e,t,i){var r,s,n,a;let o=!!t.skeleton,l=i.localMode||o,h=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,u=t.getIndices(),c=o?t.getPositionData(!0,!0):t.getVerticesData(rz.o.PositionKind),d=o?t.getNormalsData(!0,!0):t.getVerticesData(rz.o.NormalKind),p=l?o?t.getVerticesData(rz.o.PositionKind):c:null,_=l?o?t.getVerticesData(rz.o.NormalKind):d:null,f=t.getVerticesData(rz.o.UVKind),m=o?t.getVerticesData(rz.o.MatricesIndicesKind):null,g=o?t.getVerticesData(rz.o.MatricesWeightsKind):null,v=o?t.getVerticesData(rz.o.MatricesIndicesExtraKind):null,x=o?t.getVerticesData(rz.o.MatricesWeightsExtraKind):null,T=i.position||rm.P.Zero(),S=i.normal||rm.P.Up(),C=i.size||rm.P.One(),E=i.angle||0;if(!S){let e=new rm.P(0,0,1),i=t.getScene().activeCamera,r=rm.P.TransformCoordinates(e,i.getWorldMatrix());S=i.globalPosition.subtract(r)}let b=-Math.atan2(S.z,S.x)-Math.PI/2,y=Math.sqrt(S.x*S.x+S.z*S.z),P=Math.atan2(S.y,y),R=new se.x;R.indices=[],R.positions=[],R.normals=[],R.uvs=[],R.matricesIndices=o?[]:null,R.matricesWeights=o?[]:null,R.matricesIndicesExtra=v?[]:null,R.matricesWeightsExtra=x?[]:null;let A=0,extractDecalVector3=(e,t)=>{let r=new DecalVertex;if(!u||!c||!d)return r;let s=u[e];if(r.vertexIdx=3*s,r.vertexIdxForBones=4*s,r.position=new rm.P(c[3*s],c[3*s+1],c[3*s+2]),rm.P.TransformCoordinatesToRef(r.position,t,r.position),r.normal=new rm.P(d[3*s],d[3*s+1],d[3*s+2]),rm.P.TransformNormalToRef(r.normal,t,r.normal),i.captureUVS&&f){let e=f[2*s+1];r.uv=new rm.FM(f[2*s],r4.e.UseOpenGLOrientationForUV?1-e:e)}return r},I=[0,0,0,0],clip=(e,t)=>{if(0===e.length)return e;let i=.5*Math.abs(rm.P.Dot(C,t)),indexOf=(e,t,i,r)=>{for(let s=0;s<r;++s)if(e[i+s]===t)return i+s;return -1},clipVertices=(e,r)=>{var s,n,a,o,l,h,u,c,d,f,v,x,T,S,C,E;let b=rm.P.GetClipFactor(e.position,r.position,t,i),y=I,P=I;if(m&&g){let t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=null!==(s=e.matrixIndicesOverride)&&void 0!==s?s:m,l=null!==(n=e.matrixWeightsOverride)&&void 0!==n?n:g,h=r.matrixIndicesOverride?0:r.vertexIdxForBones,u=null!==(a=r.matrixIndicesOverride)&&void 0!==a?a:m,c=null!==(o=r.matrixWeightsOverride)&&void 0!==o?o:g;y=[0,0,0,0],P=[0,0,0,0];let d=0;for(let e=0;e<4;++e)if(l[t+e]>0){let r=indexOf(u,i[t+e],h,4);y[d]=i[t+e],P[d]=rE.R.Lerp(l[t+e],r>=0?c[r]:0,b),d++}for(let e=0;e<4&&d<4;++e){let r=u[h+e];-1===indexOf(i,r,t,4)&&(y[d]=r,P[d]=rE.R.Lerp(0,c[h+e],b),d++)}let p=P[0]+P[1]+P[2]+P[3];P[0]/=p,P[1]/=p,P[2]/=p,P[3]/=p}let R=e.localPositionOverride?e.localPositionOverride[0]:null!==(l=null==p?void 0:p[e.vertexIdx])&&void 0!==l?l:0,A=e.localPositionOverride?e.localPositionOverride[1]:null!==(h=null==p?void 0:p[e.vertexIdx+1])&&void 0!==h?h:0,M=e.localPositionOverride?e.localPositionOverride[2]:null!==(u=null==p?void 0:p[e.vertexIdx+2])&&void 0!==u?u:0,D=r.localPositionOverride?r.localPositionOverride[0]:null!==(c=null==p?void 0:p[r.vertexIdx])&&void 0!==c?c:0,O=r.localPositionOverride?r.localPositionOverride[1]:null!==(d=null==p?void 0:p[r.vertexIdx+1])&&void 0!==d?d:0,N=r.localPositionOverride?r.localPositionOverride[2]:null!==(f=null==p?void 0:p[r.vertexIdx+2])&&void 0!==f?f:0,F=e.localNormalOverride?e.localNormalOverride[0]:null!==(v=null==_?void 0:_[e.vertexIdx])&&void 0!==v?v:0,B=e.localNormalOverride?e.localNormalOverride[1]:null!==(x=null==_?void 0:_[e.vertexIdx+1])&&void 0!==x?x:0,L=e.localNormalOverride?e.localNormalOverride[2]:null!==(T=null==_?void 0:_[e.vertexIdx+2])&&void 0!==T?T:0,w=r.localNormalOverride?r.localNormalOverride[0]:null!==(S=null==_?void 0:_[r.vertexIdx])&&void 0!==S?S:0,U=r.localNormalOverride?r.localNormalOverride[1]:null!==(C=null==_?void 0:_[r.vertexIdx+1])&&void 0!==C?C:0,V=r.localNormalOverride?r.localNormalOverride[2]:null!==(E=null==_?void 0:_[r.vertexIdx+2])&&void 0!==E?E:0,k=F+(w-F)*b,G=B+(U-B)*b,z=L+(V-L)*b,W=Math.sqrt(k*k+G*G+z*z);return new DecalVertex(rm.P.Lerp(e.position,r.position,b),rm.P.Lerp(e.normal,r.normal,b).normalize(),rm.FM.Lerp(e.uv,r.uv,b),-1,-1,p?[R+(D-R)*b,A+(O-A)*b,M+(N-M)*b]:null,_?[k/W,G/W,z/W]:null,y,P)},r=null;e.length>3&&(r=[]);for(let s=0;s<e.length;s+=3){let n=null,a=null,o=null,l=null,h=rm.P.Dot(e[s].position,t)-i,u=rm.P.Dot(e[s+1].position,t)-i,c=rm.P.Dot(e[s+2].position,t)-i,d=h>0,p=u>0,_=c>0;switch((d?1:0)+(p?1:0)+(_?1:0)){case 0:e.length>3?(r.push(e[s]),r.push(e[s+1]),r.push(e[s+2])):r=e;break;case 1:if(r=null!=r?r:[],d&&(n=e[s+1],a=e[s+2],o=clipVertices(e[s],n),l=clipVertices(e[s],a)),p){n=e[s],a=e[s+2],o=clipVertices(e[s+1],n),l=clipVertices(e[s+1],a),r.push(o),r.push(a.clone()),r.push(n.clone()),r.push(a.clone()),r.push(o.clone()),r.push(l);break}_&&(n=e[s],a=e[s+1],o=clipVertices(e[s+2],n),l=clipVertices(e[s+2],a)),n&&a&&o&&l&&(r.push(n.clone()),r.push(a.clone()),r.push(o),r.push(l),r.push(o.clone()),r.push(a.clone()));break;case 2:r=null!=r?r:[],d||(a=clipVertices(n=e[s].clone(),e[s+1]),o=clipVertices(n,e[s+2]),r.push(n),r.push(a),r.push(o)),p||(a=clipVertices(n=e[s+1].clone(),e[s+2]),o=clipVertices(n,e[s]),r.push(n),r.push(a),r.push(o)),_||(a=clipVertices(n=e[s+2].clone(),e[s]),o=clipVertices(n,e[s+1]),r.push(n),r.push(a),r.push(o))}}return r},M=t instanceof rV.Kj?t:null,D=null==M?void 0:M._thinInstanceDataStorage.matrixData,O=(null==M?void 0:M.thinInstanceCount)||1,N=rm.jp.Matrix[0];N.copyFrom(rm.y3.IdentityReadOnly);for(let e=0;e<O;++e){if((null==M?void 0:M.hasThinInstances)&&D){let t=16*e;N.setRowFromFloats(0,D[t+0],D[t+1],D[t+2],D[t+3]),N.setRowFromFloats(1,D[t+4],D[t+5],D[t+6],D[t+7]),N.setRowFromFloats(2,D[t+8],D[t+9],D[t+10],D[t+11]),N.setRowFromFloats(3,D[t+12],D[t+13],D[t+14],D[t+15])}let r=rm.y3.RotationYawPitchRoll(b,P,E).multiply(rm.y3.Translation(T.x,T.y,T.z)),s=rm.y3.Invert(r),n=t.getWorldMatrix(),a=N.multiply(n).multiply(s),o=[,,,];for(let e=0;e<u.length;e+=3){let t=o;if(t[0]=extractDecalVector3(e,a),h&&l?(t[1]=extractDecalVector3(e+2,a),t[2]=extractDecalVector3(e+1,a)):(t[1]=extractDecalVector3(e+1,a),t[2]=extractDecalVector3(e+2,a)),!(i.cullBackFaces&&0>=-t[0].normal.z&&0>=-t[1].normal.z&&0>=-t[2].normal.z)&&(t=clip(t,n2))&&(t=clip(t,n3))&&(t=clip(t,n4))&&(t=clip(t,n5))&&(t=clip(t,n6))&&(t=clip(t,n8)))for(let e=0;e<t.length;e++){let r=t[e];if(R.indices.push(A),l?(r.localPositionOverride?(R.positions[3*A]=r.localPositionOverride[0],R.positions[3*A+1]=r.localPositionOverride[1],R.positions[3*A+2]=r.localPositionOverride[2]):p&&(R.positions[3*A]=p[r.vertexIdx],R.positions[3*A+1]=p[r.vertexIdx+1],R.positions[3*A+2]=p[r.vertexIdx+2]),r.localNormalOverride?(R.normals[3*A]=r.localNormalOverride[0],R.normals[3*A+1]=r.localNormalOverride[1],R.normals[3*A+2]=r.localNormalOverride[2]):_&&(R.normals[3*A]=_[r.vertexIdx],R.normals[3*A+1]=_[r.vertexIdx+1],R.normals[3*A+2]=_[r.vertexIdx+2])):(r.position.toArray(R.positions,3*A),r.normal.toArray(R.normals,3*A)),R.matricesIndices&&R.matricesWeights&&(r.matrixIndicesOverride?(R.matricesIndices[4*A]=r.matrixIndicesOverride[0],R.matricesIndices[4*A+1]=r.matrixIndicesOverride[1],R.matricesIndices[4*A+2]=r.matrixIndicesOverride[2],R.matricesIndices[4*A+3]=r.matrixIndicesOverride[3]):(m&&(R.matricesIndices[4*A]=m[r.vertexIdxForBones],R.matricesIndices[4*A+1]=m[r.vertexIdxForBones+1],R.matricesIndices[4*A+2]=m[r.vertexIdxForBones+2],R.matricesIndices[4*A+3]=m[r.vertexIdxForBones+3]),v&&R.matricesIndicesExtra&&(R.matricesIndicesExtra[4*A]=v[r.vertexIdxForBones],R.matricesIndicesExtra[4*A+1]=v[r.vertexIdxForBones+1],R.matricesIndicesExtra[4*A+2]=v[r.vertexIdxForBones+2],R.matricesIndicesExtra[4*A+3]=v[r.vertexIdxForBones+3])),r.matrixWeightsOverride?(R.matricesWeights[4*A]=r.matrixWeightsOverride[0],R.matricesWeights[4*A+1]=r.matrixWeightsOverride[1],R.matricesWeights[4*A+2]=r.matrixWeightsOverride[2],R.matricesWeights[4*A+3]=r.matrixWeightsOverride[3]):(g&&(R.matricesWeights[4*A]=g[r.vertexIdxForBones],R.matricesWeights[4*A+1]=g[r.vertexIdxForBones+1],R.matricesWeights[4*A+2]=g[r.vertexIdxForBones+2],R.matricesWeights[4*A+3]=g[r.vertexIdxForBones+3]),x&&R.matricesWeightsExtra&&(R.matricesWeightsExtra[4*A]=x[r.vertexIdxForBones],R.matricesWeightsExtra[4*A+1]=x[r.vertexIdxForBones+1],R.matricesWeightsExtra[4*A+2]=x[r.vertexIdxForBones+2],R.matricesWeightsExtra[4*A+3]=x[r.vertexIdxForBones+3]))),i.captureUVS)r.uv.toArray(R.uvs,2*A);else{R.uvs.push(.5+r.position.x/C.x);let e=.5+r.position.y/C.y;R.uvs.push(r4.e.UseOpenGLOrientationForUV?1-e:e)}A++}}}0===R.indices.length&&(R.indices=null),0===R.positions.length&&(R.positions=null),0===R.normals.length&&(R.normals=null),0===R.uvs.length&&(R.uvs=null),(null===(r=R.matricesIndices)||void 0===r?void 0:r.length)===0&&(R.matricesIndices=null),(null===(s=R.matricesWeights)||void 0===s?void 0:s.length)===0&&(R.matricesWeights=null),(null===(n=R.matricesIndicesExtra)||void 0===n?void 0:n.length)===0&&(R.matricesIndicesExtra=null),(null===(a=R.matricesWeightsExtra)||void 0===a?void 0:a.length)===0&&(R.matricesWeightsExtra=null);let F=new rV.Kj(e,t.getScene());return R.applyToMesh(F),l?(F.skeleton=t.skeleton,F.parent=t):(F.position=T.clone(),F.rotation=new rm.P(P,b,E)),F.computeWorldMatrix(!0),F.refreshBoundingInfo(!0,!0),F}rV.Kj.CreateDecal=(e,t,i,r,s,n)=>CreateDecal(e,t,{position:i,normal:r,size:s,angle:n}),rV.Kj._GoldbergMeshParser=(e,t)=>GoldbergMesh.Parse(e,t);let GoldbergMesh=class GoldbergMesh extends rV.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&&(rT.Y.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(rT.Y.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(rT.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 t=0;t<e.length;t++){let i=e[t][0],r=e[t][1],s=e[t][2];for(let e=i;e<r+1;e++)this.goldbergData.faceColors[e]=s}let t=[];for(let e=0;e<12;e++)for(let i=0;i<5;i++)t.push(this.goldbergData.faceColors[e].r,this.goldbergData.faceColors[e].g,this.goldbergData.faceColors[e].b,this.goldbergData.faceColors[e].a);for(let e=12;e<this.goldbergData.faceColors.length;e++)for(let i=0;i<6;i++)t.push(this.goldbergData.faceColors[e].r,this.goldbergData.faceColors[e].g,this.goldbergData.faceColors[e].b,this.goldbergData.faceColors[e].a);return t}setGoldbergFaceColors(e){let t=this._changeGoldbergFaceColors(e);this.setVerticesData(rz.o.ColorKind,t)}updateGoldbergFaceColors(e){let t=this._changeGoldbergFaceColors(e);this.updateVerticesData(rz.o.ColorKind,t)}_changeGoldbergFaceUVs(e){let t=this.getVerticesData(rz.o.UVKind);for(let i=0;i<e.length;i++){let r,s;let n=e[i][0],a=e[i][1],o=e[i][2],l=e[i][3],h=e[i][4],u=[],c=[];for(let e=0;e<5;e++)r=o.x+l*Math.cos(h+e*Math.PI/2.5),s=o.y+l*Math.sin(h+e*Math.PI/2.5),r<0&&(r=0),r>1&&(r=1),u.push(r,s);for(let e=0;e<6;e++)r=o.x+l*Math.cos(h+e*Math.PI/3),s=o.y+l*Math.sin(h+e*Math.PI/3),r<0&&(r=0),r>1&&(r=1),c.push(r,s);for(let e=n;e<Math.min(12,a+1);e++)for(let i=0;i<5;i++)t[10*e+2*i]=u[2*i],t[10*e+2*i+1]=u[2*i+1];for(let e=Math.max(12,n);e<a+1;e++)for(let i=0;i<6;i++)t[12*e-24+2*i]=c[2*i],t[12*e-23+2*i]=c[2*i+1]}return t}setGoldbergFaceUVs(e){let t=this._changeGoldbergFaceUVs(e);this.setVerticesData(rz.o.UVKind,t)}updateGoldbergFaceUVs(e){let t=this._changeGoldbergFaceUVs(e);this.updateVerticesData(rz.o.UVKind,t)}placeOnGoldbergFaceAt(e,t,i){let r=rm.P.RotationFromAxis(this.goldbergData.faceXaxis[t],this.goldbergData.faceYaxis[t],this.goldbergData.faceZaxis[t]);e.rotation=r,e.position=this.goldbergData.faceCenters[t].add(this.goldbergData.faceXaxis[t].scale(i.x)).add(this.goldbergData.faceYaxis[t].scale(i.y)).add(this.goldbergData.faceZaxis[t].scale(i.z))}serialize(e){super.serialize(e),e.type="GoldbergMesh";let t={};if(t.adjacentFaces=this.goldbergData.adjacentFaces,t.nbSharedFaces=this.goldbergData.nbSharedFaces,t.nbUnsharedFaces=this.goldbergData.nbUnsharedFaces,t.nbFaces=this.goldbergData.nbFaces,t.nbFacesAtPole=this.goldbergData.nbFacesAtPole,this.goldbergData.faceColors)for(let e of(t.faceColors=[],this.goldbergData.faceColors))t.faceColors.push(e.asArray());if(this.goldbergData.faceCenters)for(let e of(t.faceCenters=[],this.goldbergData.faceCenters))t.faceCenters.push(e.asArray());if(this.goldbergData.faceZaxis)for(let e of(t.faceZaxis=[],this.goldbergData.faceZaxis))t.faceZaxis.push(e.asArray());if(this.goldbergData.faceYaxis)for(let e of(t.faceYaxis=[],this.goldbergData.faceYaxis))t.faceYaxis.push(e.asArray());if(this.goldbergData.faceXaxis)for(let e of(t.faceXaxis=[],this.goldbergData.faceXaxis))t.faceXaxis.push(e.asArray());e.goldbergData=t}static Parse(e,t){let i=e.goldbergData;i.faceColors=i.faceColors.map(e=>rg.HE.FromArray(e)),i.faceCenters=i.faceCenters.map(e=>rm.P.FromArray(e)),i.faceZaxis=i.faceZaxis.map(e=>rm.P.FromArray(e)),i.faceXaxis=i.faceXaxis.map(e=>rm.P.FromArray(e)),i.faceYaxis=i.faceYaxis.map(e=>rm.P.FromArray(e));let r=new GoldbergMesh(e.name,t);return r.goldbergData=i,r}};let ShapePath=class ShapePath{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new math_path_Path2(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)}bezierCurveTo(e,t,i,r,s,n){this._currentPath.addBezierCurveTo(e,t,i,r,s,n,this._resolution)}extractHoles(){for(let e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){let 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 CreateShapePath(e,t,i,r,s,n){let a=n.glyphs[e]||n.glyphs["?"];if(!a)return null;let o=new ShapePath(s);if(a.o){let e=a.o.split(" ");for(let s=0,n=e.length;s<n;){let n=e[s++];switch(n){case"m":{let n=parseInt(e[s++])*t+i,a=parseInt(e[s++])*t+r;o.moveTo(n,a);break}case"l":{let n=parseInt(e[s++])*t+i,a=parseInt(e[s++])*t+r;o.lineTo(n,a);break}case"q":{let n=parseInt(e[s++])*t+i,a=parseInt(e[s++])*t+r,l=parseInt(e[s++])*t+i,h=parseInt(e[s++])*t+r;o.quadraticCurveTo(l,h,n,a);break}case"b":{let n=parseInt(e[s++])*t+i,a=parseInt(e[s++])*t+r,l=parseInt(e[s++])*t+i,h=parseInt(e[s++])*t+r,u=parseInt(e[s++])*t+i,c=parseInt(e[s++])*t+r;o.bezierCurveTo(l,h,u,c,n,a)}}}}return o.extractHoles(),{offsetX:a.ha*t,shapePath:o}}function CreateTextShapePaths(e,t,i,r){let s=Array.from(e),n=t/r.resolution,a=(r.boundingBox.yMax-r.boundingBox.yMin+r.underlineThickness)*n,o=[],l=0,h=0;for(let e=0;e<s.length;e++){let t=s[e];if("\n"===t)l=0,h-=a;else{let e=CreateShapePath(t,n,l,h,i,r);e&&(l+=e.offsetX,o.push(e.shapePath))}}return o}let SkeletonViewer=class SkeletonViewer{static CreateBoneWeightShader(e,t){var i,r,s,n,a,o;let l=e.skeleton,h=null!==(i=e.colorBase)&&void 0!==i?i:rg.Wo.Black(),u=null!==(r=e.colorZero)&&void 0!==r?r:rg.Wo.Blue(),c=null!==(s=e.colorQuarter)&&void 0!==s?s:rg.Wo.Green(),d=null!==(n=e.colorHalf)&&void 0!==n?n:rg.Wo.Yellow(),p=null!==(a=e.colorFull)&&void 0!==a?a:rg.Wo.Red(),_=null!==(o=e.targetBoneIndex)&&void 0!==o?o:0;ss.Q.ShadersStore["boneWeights:"+l.name+"VertexShader"]=`precision highp float; + + attribute vec3 position; + attribute vec2 uv; + + uniform mat4 view; + uniform mat4 projection; + uniform mat4 worldViewProjection; + + #include<bonesDeclaration> + #if NUM_BONE_INFLUENCERS == 0 + attribute vec4 matricesIndices; + attribute vec4 matricesWeights; + #endif + #include<bakedVertexAnimationDeclaration> + + #include<instancesDeclaration> + + varying vec3 vColor; + + uniform vec3 colorBase; + uniform vec3 colorZero; + uniform vec3 colorQuarter; + uniform vec3 colorHalf; + uniform vec3 colorFull; + + uniform float targetBoneIndex; + + void main() { + vec3 positionUpdated = position; + + #include<instancesVertex> + #include<bonesVertex> + #include<bakedVertexAnimation> + + vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); + + vec3 color = colorBase; + float totalWeight = 0.; + if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){ + totalWeight += matricesWeights[0]; + } + if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){ + totalWeight += matricesWeights[1]; + } + if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){ + totalWeight += matricesWeights[2]; + } + if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){ + totalWeight += matricesWeights[3]; + } + + color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight)); + color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight)); + color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight)); + color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight)); + vColor = color; + + gl_Position = projection * view * worldPos; + }`,ss.Q.ShadersStore["boneWeights:"+l.name+"FragmentShader"]=` + precision highp float; + varying vec3 vPosition; + + varying vec3 vColor; + + void main() { + vec4 color = vec4(vColor, 1.0); + gl_FragColor = color; + } + `;let f=new shaderMaterial_ShaderMaterial("boneWeight:"+l.name,t,{vertex:"boneWeights:"+l.name,fragment:"boneWeights:"+l.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return f.setColor3("colorBase",h),f.setColor3("colorZero",u),f.setColor3("colorQuarter",c),f.setColor3("colorHalf",d),f.setColor3("colorFull",p),f.setFloat("targetBoneIndex",_),f.getClassName=()=>"BoneWeightShader",f.transparencyMode=sr.F.MATERIAL_OPAQUE,f}static CreateSkeletonMapShader(e,t){var i;let r=e.skeleton,s=null!==(i=e.colorMap)&&void 0!==i?i:[{color:new rg.Wo(1,.38,.18),location:0},{color:new rg.Wo(.59,.18,1),location:.2},{color:new rg.Wo(.59,1,.18),location:.4},{color:new rg.Wo(1,.87,.17),location:.6},{color:new rg.Wo(1,.17,.42),location:.8},{color:new rg.Wo(.17,.68,1),location:1}],n=r.bones.length+1,a=SkeletonViewer._CreateBoneMapColorBuffer(n,s,t),o=new shaderMaterial_ShaderMaterial("boneWeights:"+r.name,t,{vertexSource:`precision highp float; + + attribute vec3 position; + attribute vec2 uv; + + uniform mat4 view; + uniform mat4 projection; + uniform mat4 worldViewProjection; + uniform float colorMap[`+4*r.bones.length+`]; + + #include<bonesDeclaration> + #if NUM_BONE_INFLUENCERS == 0 + attribute vec4 matricesIndices; + attribute vec4 matricesWeights; + #endif + #include<bakedVertexAnimationDeclaration> + #include<instancesDeclaration> + + varying vec3 vColor; + + void main() { + vec3 positionUpdated = position; + + #include<instancesVertex> + #include<bonesVertex> + #include<bakedVertexAnimation> + + vec3 color = vec3(0.); + bool first = true; + + for (int i = 0; i < 4; i++) { + int boneIdx = int(matricesIndices[i]); + float boneWgt = matricesWeights[i]; + + vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]); + + if (boneWgt > 0.) { + if (first) { + first = false; + color = c; + } else { + color = mix(color, c, boneWgt); + } + } + } + + vColor = color; + + vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); + + gl_Position = projection * view * worldPos; + }`,fragmentSource:` + precision highp float; + varying vec3 vColor; + + void main() { + vec4 color = vec4( vColor, 1.0 ); + gl_FragColor = color; + } + `},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",a),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=sr.F.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){let r=new DynamicTexture("temp",{width:e,height:1},i,!1),s=r.getContext(),n=s.createLinearGradient(0,0,e,0);t.forEach(e=>{n.addColorStop(e.location,e.color.toHexString())}),s.fillStyle=n,s.fillRect(0,0,e,1),r.update();let a=[],o=s.getImageData(0,0,e,1).data,l=1/255;for(let e=0;e<o.length;e++)a.push(o[e]*l);return r.dispose(),a}get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get isReady(){return this._ready}set ready(e){this._ready=e}get debugMesh(){return this._debugMesh}set debugMesh(e){this._debugMesh=e}get displayMode(){return this.options.displayMode||SkeletonViewer.DISPLAY_LINES}set displayMode(e){e>SkeletonViewer.DISPLAY_SPHERE_AND_SPURS&&(e=SkeletonViewer.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,s=3,n={}){var a,o,l,h,u,c,d,p,_,f,m,g,v,x;this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=s,this.options=n,this.color=rg.Wo.White(),this._debugLines=[],this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=null===(a=n.pauseAnimations)||void 0===a||a,n.returnToRest=null!==(o=n.returnToRest)&&void 0!==o&&o,n.displayMode=null!==(l=n.displayMode)&&void 0!==l?l:SkeletonViewer.DISPLAY_LINES,n.displayOptions=null!==(h=n.displayOptions)&&void 0!==h?h:{},n.displayOptions.midStep=null!==(u=n.displayOptions.midStep)&&void 0!==u?u:.235,n.displayOptions.midStepFactor=null!==(c=n.displayOptions.midStepFactor)&&void 0!==c?c:.155,n.displayOptions.sphereBaseSize=null!==(d=n.displayOptions.sphereBaseSize)&&void 0!==d?d:.15,n.displayOptions.sphereScaleUnit=null!==(p=n.displayOptions.sphereScaleUnit)&&void 0!==p?p:2,n.displayOptions.sphereFactor=null!==(_=n.displayOptions.sphereFactor)&&void 0!==_?_:.865,n.displayOptions.spurFollowsChild=null!==(f=n.displayOptions.spurFollowsChild)&&void 0!==f&&f,n.displayOptions.showLocalAxes=null!==(m=n.displayOptions.showLocalAxes)&&void 0!==m&&m,n.displayOptions.localAxesSize=null!==(g=n.displayOptions.localAxesSize)&&void 0!==g?g:.075,n.computeBonesUsingShaders=null===(v=n.computeBonesUsingShaders)||void 0===v||v,n.useAllBones=null===(x=n.useAllBones)||void 0===x||x;let T=t.getVerticesData(rz.o.MatricesIndicesKind),S=t.getVerticesData(rz.o.MatricesWeightsKind);if(this._boneIndices=new Set,!n.useAllBones&&T&&S)for(let e=0;e<T.length;++e){let t=T[e],i=S[e];0!==i&&this._boneIndices.add(t)}this._utilityLayer=new utilityLayerRenderer_UtilityLayerRenderer(this._scene,!1),this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!0;let C=this.options.displayMode||0;C>SkeletonViewer.DISPLAY_SPHERE_AND_SPURS&&(C=SkeletonViewer.DISPLAY_LINES),this.displayMode=C,this.update(),this._bindObs()}_bindObs(){this.displayMode===SkeletonViewer.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()}))}update(){switch(this.displayMode){case SkeletonViewer.DISPLAY_LINES:this._displayLinesUpdate();break;case SkeletonViewer.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,s=0,n=0){let a=rm.jp.Matrix[0],o=t.getParent();if(a.copyFrom(t.getLocalMatrix()),0!==r||0!==s||0!==n){let e=rm.jp.Matrix[1];rm.y3.IdentityToRef(e),e.setTranslationFromFloats(r,s,n),e.multiplyToRef(a,a)}o&&a.multiplyToRef(o.getAbsoluteMatrix(),a),a.multiplyToRef(i,a),e.x=a.m[12],e.y=a.m[13],e.z=a.m[14]}_getLinesForBonesWithLength(e,t){let i=e.length,r=this.mesh,s=r.position,n=0;for(let r=0;r<i;r++){let i=e[r],a=this._debugLines[n];-1!==i._index&&(this._boneIndices.has(i.getIndex())||this.options.useAllBones)&&(a||(a=[rm.P.Zero(),rm.P.Zero()],this._debugLines[n]=a),this._getBonePosition(a[0],i,t),this._getBonePosition(a[1],i,t,0,i.length,0),a[0].subtractInPlace(s),a[1].subtractInPlace(s),n++)}}_getLinesForBonesNoLength(e){let t=e.length,i=0,r=this.mesh,s=r.position;for(let n=t-1;n>=0;n--){let t=e[n],a=t.getParent();if(!a||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let o=this._debugLines[i];o||(o=[rm.P.Zero(),rm.P.Zero()],this._debugLines[i]=o),t.getAbsolutePositionToRef(r,o[0]),a.getAbsolutePositionToRef(r,o[1]),o[0].subtractInPlace(s),o[1].subtractInPlace(s),i++}}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){if(null===e||-1===e._index){t.copyFrom(rm.y3.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;let r=null===(t=this.utilityLayer)||void 0===t?void 0:t.utilityLayerScene,s=this.skeleton.bones,n=[],a=[],o=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,r.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let t=Number.NEGATIVE_INFINITY,l=this.options.displayOptions||{};for(let i=0;i<s.length;i++){let o=s[i];if(-1===o._index||!this._boneIndices.has(o.getIndex())&&!this.options.useAllBones)continue;let h=new rm.y3;this._getAbsoluteBindPoseToRef(o,h);let u=new rm.P;h.decompose(void 0,void 0,u),o.children.forEach(i=>{let s=new rm.y3;i.getLocalMatrix().multiplyToRef(h,s);let n=new rm.P;s.decompose(void 0,void 0,n);let c=rm.P.Distance(u,n);if(c>t&&(t=c),e)return;let d=n.clone().subtract(u.clone()),p=d.length(),_=d.normalize().scale(p),f=l.midStep||.165,m=l.midStepFactor||.215,g=_.scale(f),v=ExtrudeShapeCustom("skeletonViewer",{shape:[new rm.P(1,-1,0),new rm.P(1,1,0),new rm.P(-1,1,0),new rm.P(-1,-1,0),new rm.P(1,-1,0)],path:[rm.P.Zero(),g,_],scaleFunction:e=>{switch(e){case 0:case 2:break;case 1:return p*m}return 0},sideOrientation:rV.Kj.DEFAULTSIDE,updatable:!1},r),x=v.getTotalVertices(),T=[],S=[];for(let e=0;e<x;e++)T.push(1,0,0,0),l.spurFollowsChild&&e>9?S.push(i.getIndex(),0,0,0):S.push(o.getIndex(),0,0,0);v.position=u.clone(),v.setVerticesData(rz.o.MatricesWeightsKind,T,!1),v.setVerticesData(rz.o.MatricesIndicesKind,S,!1),v.convertToFlatShadedMesh(),a.push(v)});let c=l.sphereBaseSize||.2,d=sphereBuilder_CreateSphere("skeletonViewer",{segments:6,diameter:c,updatable:!0},r),p=d.getTotalVertices(),_=[],f=[];for(let e=0;e<p;e++)_.push(1,0,0,0),f.push(o.getIndex(),0,0,0);d.setVerticesData(rz.o.MatricesWeightsKind,_,!1),d.setVerticesData(rz.o.MatricesIndicesKind,f,!1),d.position=u.clone(),n.push([d,o])}let h=l.sphereScaleUnit||2,u=l.sphereFactor||.85,c=[];for(let e=0;e<n.length;e++){let[i,r]=n[e],s=1/(h/t),a=0,o=r;for(;o.getParent()&&-1!==o.getParent().getIndex();)a++,o=o.getParent();i.scaling.scaleInPlace(s*Math.pow(u,a)),c.push(i)}this.debugMesh=rV.Kj.MergeMeshes(c.concat(a),!0,!0),this.debugMesh&&(this.debugMesh.renderingGroupId=this.renderingGroupId,this.debugMesh.skeleton=this.skeleton,this.debugMesh.parent=this.mesh,this.debugMesh.computeBonesUsingShaders=null===(i=this.options.computeBonesUsingShaders)||void 0===i||i,this.debugMesh.alwaysSelectAsActiveMesh=!0);let d=this.utilityLayer._getSharedGizmoLight();d.intensity=.7,this._revert(o),this.ready=!0}catch(e){console.error(e),this._revert(o),this.dispose()}}_buildLocalAxes(){var e;this._localAxes&&this._localAxes.dispose(),this._localAxes=null;let t=this.options.displayOptions||{};if(!t.showLocalAxes)return;let i=this._utilityLayer.utilityLayerScene,r=t.localAxesSize||.075,s=[],n=[],a=new rg.HE(1,0,0,1),o=new rg.HE(0,1,0,1),l=new rg.HE(0,0,1,1),h=[],u=[];for(let e in this.skeleton.bones){let t=this.skeleton.bones[e];if(-1===t._index||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let i=new rm.y3,c=new rm.P;this._getAbsoluteBindPoseToRef(t,i),i.decompose(void 0,rm.jp.Quaternion[0],c);let d=new rm.y3;rm.jp.Quaternion[0].toRotationMatrix(d);let p=rm.P.TransformCoordinates(new rm.P(0+r,0,0),d),_=rm.P.TransformCoordinates(new rm.P(0,0+r,0),d),f=rm.P.TransformCoordinates(new rm.P(0,0,0+r),d),m=[c,c.add(p)],g=[c,c.add(_)],v=[c,c.add(f)],x=[m,g,v],T=[[a,a],[o,o],[l,l]];s.push(...x),n.push(...T);for(let e=0;e<6;e++)h.push(1,0,0,0),u.push(t.getIndex(),0,0,0)}this._localAxes=CreateLineSystem("localAxes",{lines:s,colors:n,updatable:!0},i),this._localAxes.setVerticesData(rz.o.MatricesWeightsKind,h,!1),this._localAxes.setVerticesData(rz.o.MatricesIndicesKind,u,!1),this._localAxes.skeleton=this.skeleton,this._localAxes.renderingGroupId=this.renderingGroupId+1,this._localAxes.parent=this.mesh,this._localAxes.computeBonesUsingShaders=null===(e=this.options.computeBonesUsingShaders)||void 0===e||e}_displayLinesUpdate(){if(!this._utilityLayer)return;this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh.getWorldMatrix());let e=this._utilityLayer.utilityLayerScene;e&&(this._debugMesh?CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},e):(this._debugMesh=CreateLineSystem("",{lines:this._debugLines,updatable:!0,instance:null},e),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.position.copyFrom(this.mesh.position),this._debugMesh.color=this.color)}changeDisplayMode(e){let t=!!this.isEnabled;this.displayMode!==e&&(this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this.displayMode=e,this.update(),this._bindObs(),this.isEnabled=t)}changeDisplayOptions(e,t){let i=!!this.isEnabled;this.options.displayOptions[e]=t,this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this.update(),this._bindObs(),this.isEnabled=i}dispose(){this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null),this.ready=!1}};SkeletonViewer.DISPLAY_LINES=0,SkeletonViewer.DISPLAY_SPHERES=1,SkeletonViewer.DISPLAY_SPHERE_AND_SPURS=2,i(6822),i(6327),i(8479);let Constants=class Constants{};Constants.ALPHA_DISABLE=0,Constants.ALPHA_ADD=1,Constants.ALPHA_COMBINE=2,Constants.ALPHA_SUBTRACT=3,Constants.ALPHA_MULTIPLY=4,Constants.ALPHA_MAXIMIZED=5,Constants.ALPHA_ONEONE=6,Constants.ALPHA_PREMULTIPLIED=7,Constants.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Constants.ALPHA_INTERPOLATE=9,Constants.ALPHA_SCREENMODE=10,Constants.ALPHA_ONEONE_ONEONE=11,Constants.ALPHA_ALPHATOCOLOR=12,Constants.ALPHA_REVERSEONEMINUS=13,Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,Constants.ALPHA_ONEONE_ONEZERO=15,Constants.ALPHA_EXCLUSION=16,Constants.ALPHA_LAYER_ACCUMULATE=17,Constants.ALPHA_EQUATION_ADD=0,Constants.ALPHA_EQUATION_SUBSTRACT=1,Constants.ALPHA_EQUATION_REVERSE_SUBTRACT=2,Constants.ALPHA_EQUATION_MAX=3,Constants.ALPHA_EQUATION_MIN=4,Constants.ALPHA_EQUATION_DARKEN=5,Constants.DELAYLOADSTATE_NONE=0,Constants.DELAYLOADSTATE_LOADED=1,Constants.DELAYLOADSTATE_LOADING=2,Constants.DELAYLOADSTATE_NOTLOADED=4,Constants.NEVER=512,Constants.ALWAYS=519,Constants.LESS=513,Constants.EQUAL=514,Constants.LEQUAL=515,Constants.GREATER=516,Constants.GEQUAL=518,Constants.NOTEQUAL=517,Constants.KEEP=7680,Constants.ZERO=0,Constants.REPLACE=7681,Constants.INCR=7682,Constants.DECR=7683,Constants.INVERT=5386,Constants.INCR_WRAP=34055,Constants.DECR_WRAP=34056,Constants.TEXTURE_CLAMP_ADDRESSMODE=0,Constants.TEXTURE_WRAP_ADDRESSMODE=1,Constants.TEXTURE_MIRROR_ADDRESSMODE=2,Constants.TEXTURE_CREATIONFLAG_STORAGE=1,Constants.TEXTUREFORMAT_ALPHA=0,Constants.TEXTUREFORMAT_LUMINANCE=1,Constants.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Constants.TEXTUREFORMAT_RGB=4,Constants.TEXTUREFORMAT_RGBA=5,Constants.TEXTUREFORMAT_RED=6,Constants.TEXTUREFORMAT_R=6,Constants.TEXTUREFORMAT_RG=7,Constants.TEXTUREFORMAT_RED_INTEGER=8,Constants.TEXTUREFORMAT_R_INTEGER=8,Constants.TEXTUREFORMAT_RG_INTEGER=9,Constants.TEXTUREFORMAT_RGB_INTEGER=10,Constants.TEXTUREFORMAT_RGBA_INTEGER=11,Constants.TEXTUREFORMAT_BGRA=12,Constants.TEXTUREFORMAT_DEPTH24_STENCIL8=13,Constants.TEXTUREFORMAT_DEPTH32_FLOAT=14,Constants.TEXTUREFORMAT_DEPTH16=15,Constants.TEXTUREFORMAT_DEPTH24=16,Constants.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,Constants.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,Constants.TEXTUREFORMAT_STENCIL8=19,Constants.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,Constants.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,Constants.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,Constants.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,Constants.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,Constants.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,Constants.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,Constants.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,Constants.TEXTURETYPE_UNSIGNED_BYTE=0,Constants.TEXTURETYPE_UNSIGNED_INT=0,Constants.TEXTURETYPE_FLOAT=1,Constants.TEXTURETYPE_HALF_FLOAT=2,Constants.TEXTURETYPE_BYTE=3,Constants.TEXTURETYPE_SHORT=4,Constants.TEXTURETYPE_UNSIGNED_SHORT=5,Constants.TEXTURETYPE_INT=6,Constants.TEXTURETYPE_UNSIGNED_INTEGER=7,Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Constants.TEXTURETYPE_UNSIGNED_INT_24_8=12,Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Constants.TEXTURETYPE_UNDEFINED=16,Constants.TEXTURE_2D=3553,Constants.TEXTURE_2D_ARRAY=35866,Constants.TEXTURE_CUBE_MAP=34067,Constants.TEXTURE_CUBE_MAP_ARRAY=3735928559,Constants.TEXTURE_3D=32879,Constants.TEXTURE_NEAREST_SAMPLINGMODE=1,Constants.TEXTURE_NEAREST_NEAREST=1,Constants.TEXTURE_BILINEAR_SAMPLINGMODE=2,Constants.TEXTURE_LINEAR_LINEAR=2,Constants.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Constants.TEXTURE_NEAREST_LINEAR=7,Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Constants.TEXTURE_LINEAR_NEAREST=12,Constants.TEXTURE_EXPLICIT_MODE=0,Constants.TEXTURE_SPHERICAL_MODE=1,Constants.TEXTURE_PLANAR_MODE=2,Constants.TEXTURE_CUBIC_MODE=3,Constants.TEXTURE_PROJECTION_MODE=4,Constants.TEXTURE_SKYBOX_MODE=5,Constants.TEXTURE_INVCUBIC_MODE=6,Constants.TEXTURE_EQUIRECTANGULAR_MODE=7,Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Constants.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,Constants.TEXTURE_FILTERING_QUALITY_HIGH=64,Constants.TEXTURE_FILTERING_QUALITY_MEDIUM=16,Constants.TEXTURE_FILTERING_QUALITY_LOW=8,Constants.SCALEMODE_FLOOR=1,Constants.SCALEMODE_NEAREST=2,Constants.SCALEMODE_CEILING=3,Constants.MATERIAL_TextureDirtyFlag=1,Constants.MATERIAL_LightDirtyFlag=2,Constants.MATERIAL_FresnelDirtyFlag=4,Constants.MATERIAL_AttributesDirtyFlag=8,Constants.MATERIAL_MiscDirtyFlag=16,Constants.MATERIAL_PrePassDirtyFlag=32,Constants.MATERIAL_AllDirtyFlag=63,Constants.MATERIAL_TriangleFillMode=0,Constants.MATERIAL_WireFrameFillMode=1,Constants.MATERIAL_PointFillMode=2,Constants.MATERIAL_PointListDrawMode=3,Constants.MATERIAL_LineListDrawMode=4,Constants.MATERIAL_LineLoopDrawMode=5,Constants.MATERIAL_LineStripDrawMode=6,Constants.MATERIAL_TriangleStripDrawMode=7,Constants.MATERIAL_TriangleFanDrawMode=8,Constants.MATERIAL_ClockWiseSideOrientation=0,Constants.MATERIAL_CounterClockWiseSideOrientation=1,Constants.ACTION_NothingTrigger=0,Constants.ACTION_OnPickTrigger=1,Constants.ACTION_OnLeftPickTrigger=2,Constants.ACTION_OnRightPickTrigger=3,Constants.ACTION_OnCenterPickTrigger=4,Constants.ACTION_OnPickDownTrigger=5,Constants.ACTION_OnDoublePickTrigger=6,Constants.ACTION_OnPickUpTrigger=7,Constants.ACTION_OnPickOutTrigger=16,Constants.ACTION_OnLongPressTrigger=8,Constants.ACTION_OnPointerOverTrigger=9,Constants.ACTION_OnPointerOutTrigger=10,Constants.ACTION_OnEveryFrameTrigger=11,Constants.ACTION_OnIntersectionEnterTrigger=12,Constants.ACTION_OnIntersectionExitTrigger=13,Constants.ACTION_OnKeyDownTrigger=14,Constants.ACTION_OnKeyUpTrigger=15,Constants.PARTICLES_BILLBOARDMODE_Y=2,Constants.PARTICLES_BILLBOARDMODE_ALL=7,Constants.PARTICLES_BILLBOARDMODE_STRETCHED=8,Constants.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,Constants.MESHES_CULLINGSTRATEGY_STANDARD=0,Constants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Constants.SCENELOADER_NO_LOGGING=0,Constants.SCENELOADER_MINIMAL_LOGGING=1,Constants.SCENELOADER_SUMMARY_LOGGING=2,Constants.SCENELOADER_DETAILED_LOGGING=3,Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,Constants.PREPASS_POSITION_TEXTURE_TYPE=1,Constants.PREPASS_VELOCITY_TEXTURE_TYPE=2,Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,Constants.PREPASS_COLOR_TEXTURE_TYPE=4,Constants.PREPASS_DEPTH_TEXTURE_TYPE=5,Constants.PREPASS_NORMAL_TEXTURE_TYPE=6,Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,Constants.BUFFER_CREATIONFLAG_READ=1,Constants.BUFFER_CREATIONFLAG_WRITE=2,Constants.BUFFER_CREATIONFLAG_READWRITE=3,Constants.BUFFER_CREATIONFLAG_UNIFORM=4,Constants.BUFFER_CREATIONFLAG_VERTEX=8,Constants.BUFFER_CREATIONFLAG_INDEX=16,Constants.BUFFER_CREATIONFLAG_STORAGE=32,Constants.RENDERPASS_MAIN=0,Constants.INPUT_ALT_KEY=18,Constants.INPUT_CTRL_KEY=17,Constants.INPUT_META_KEY1=91,Constants.INPUT_META_KEY2=92,Constants.INPUT_META_KEY3=93,Constants.INPUT_SHIFT_KEY=16,Constants.SNAPSHOTRENDERING_STANDARD=0,Constants.SNAPSHOTRENDERING_FAST=1,Constants.PERSPECTIVE_CAMERA=0,Constants.ORTHOGRAPHIC_CAMERA=1,Constants.FOVMODE_VERTICAL_FIXED=0,Constants.FOVMODE_HORIZONTAL_FIXED=1,Constants.RIG_MODE_NONE=0,Constants.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Constants.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Constants.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Constants.RIG_MODE_VR=20,Constants.RIG_MODE_CUSTOM=22,Constants.MAX_SUPPORTED_UV_SETS=6,Constants.GL_ALPHA_EQUATION_ADD=32774,Constants.GL_ALPHA_EQUATION_MIN=32775,Constants.GL_ALPHA_EQUATION_MAX=32776,Constants.GL_ALPHA_EQUATION_SUBTRACT=32778,Constants.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,Constants.GL_ALPHA_FUNCTION_SRC=768,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,Constants.GL_ALPHA_FUNCTION_SRC_ALPHA=770,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,Constants.GL_ALPHA_FUNCTION_DST_ALPHA=772,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,Constants.GL_ALPHA_FUNCTION_DST_COLOR=774,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,Constants.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,Constants.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,Constants.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,Constants.SnippetUrl="https://snippet.babylonjs.com",i(4548),i(6628),r6.B.prototype._debugPushGroup=function(e,t){},r6.B.prototype._debugPopGroup=function(e){},r6.B.prototype._debugInsertMarker=function(e,t){},r6.B.prototype._debugFlushPendingCommands=function(){};let _TimeToken=class _TimeToken{constructor(){this._timeElapsedQueryEnded=!1}};var n7=i(7263);let _OcclusionDataStorage=class _OcclusionDataStorage{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=rG.x.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=rG.x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}};rq.D.prototype.createQuery=function(){let e=this._gl.createQuery();if(!e)throw Error("Unable to create Occlusion Query");return e},rq.D.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},rq.D.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},rq.D.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},rq.D.prototype.beginOcclusionQuery=function(e,t){let i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},rq.D.prototype.endOcclusionQuery=function(e){let t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},rq.D.prototype._createTimeQuery=function(){let e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},rq.D.prototype._deleteTimeQuery=function(e){let t=this.getCaps().timerQuery;if(t.deleteQueryEXT){t.deleteQueryEXT(e);return}this.deleteQuery(e)},rq.D.prototype._getTimeQueryResult=function(e){let t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},rq.D.prototype._getTimeQueryAvailability=function(e){let t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},rq.D.prototype.startTimeQuery=function(){let e=this.getCaps(),t=e.timerQuery;if(!t)return null;let i=new _TimeToken;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery),this._currentNonTimestampToken=i}return i},rq.D.prototype.endTimeQuery=function(e){let t=this.getCaps(),i=t.timerQuery;if(!i||!e)return -1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return -1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return -1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}let r=this._gl.getParameter(i.GPU_DISJOINT_EXT),s=!1;if(e._endTimeQuery?s=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(s=this._getTimeQueryAvailability(e._timeElapsedQuery)),s&&!r){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return -1;let t=this._getTimeQueryResult(e._startTimeQuery),r=this._getTimeQueryResult(e._endTimeQuery);i=r-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return -1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return -1},rq.D.prototype._captureGPUFrameTime=!1,rq.D.prototype._gpuFrameTime=new n7.z,rq.D.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},rq.D.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add(()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(()=>{if(!this._gpuFrameTimeToken)return;let 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))},rq.D.prototype._getGlAlgorithmType=function(e){return e===rG.x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(rG.x.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(rG.x.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new _OcclusionDataStorage),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(rG.x.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(rG.x.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(rG.x.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(rG.x.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(rG.x.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),rG.x.prototype._checkOcclusionQuery=function(){let e=this._occlusionDataStorage;if(e.occlusionType===rG.x.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;let t=this.getEngine();if(!t.getCaps().supportOcclusionQuery||!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery){let i=t.isQueryResultAvailable(this._occlusionQuery);if(i){let 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!==rG.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==rG.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}}let i=this.getScene();if(i.getBoundingBoxRenderer){let r=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded},rq.D.prototype.createTransformFeedback=function(){let e=this._gl.createTransformFeedback();if(!e)throw Error("Unable to create Transform Feedback");return e},rq.D.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},rq.D.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},rq.D.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},rq.D.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},rq.D.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},rq.D.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},r6.B.prototype.createExternalTexture=function(e){return null},r6.B.prototype.setExternalTexture=function(e,t){throw Error("setExternalTexture: This engine does not support external textures!")},r6.B.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;let r=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);let t=e._workingCanvas.getContext("2d");if(!t)throw Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},r6.B.prototype.restoreSingleAttachment=function(){let e=this._gl;this.bindAttachments([e.BACK])},r6.B.prototype.restoreSingleAttachmentForRenderTarget=function(){let e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},r6.B.prototype.buildTextureLayout=function(e){let t=this._gl,i=[];for(let r=0;r<e.length;r++)e[r]?i.push(t["COLOR_ATTACHMENT"+r]):i.push(t.NONE);return i},r6.B.prototype.bindAttachments=function(e){let t=this._gl;t.drawBuffers(e)},r6.B.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t=!1,i){this._currentRenderTarget=null;let r=this._gl,s=e._attachments,n=s.length;if(e._MSAAFramebuffer){r.bindFramebuffer(r.READ_FRAMEBUFFER,e._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,e._framebuffer);for(let t=0;t<n;t++){let i=e.textures[t];for(let e=0;e<n;e++)s[e]=r.NONE;s[t]=r[this.webGLVersion>1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],r.readBuffer(s[t]),r.drawBuffers(s),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(let e=0;e<n;e++)s[e]=r[this.webGLVersion>1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];r.drawBuffers(s)}for(let i=0;i<n;i++){let s=e.textures[i];(null==s?void 0:s.generateMipMaps)&&!t&&!s.isCube&&(this._bindTextureDirectly(r.TEXTURE_2D,s,!0),r.generateMipmap(r.TEXTURE_2D),this._bindTextureDirectly(r.TEXTURE_2D,null))}i&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),i()),this._bindUnboundFramebuffer(null)},r6.B.prototype.createMultipleRenderTarget=function(e,t,i=!0){var r;let s=!1,n=!0,a=!1,o=!1,l=15,h=1,u=[],c=[],d=[],p=[],_=[],f=[],m=[],g=[],v=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(s=void 0!==t.generateMipMaps&&t.generateMipMaps,n=void 0===t.generateDepthBuffer||t.generateDepthBuffer,a=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,o=void 0!==t.generateDepthTexture&&t.generateDepthTexture,h=t.textureCount||1,t.types&&(u=t.types),t.samplingModes&&(c=t.samplingModes),t.useSRGBBuffers&&(d=t.useSRGBBuffers),t.formats&&(p=t.formats),t.targetTypes&&(_=t.targetTypes),t.faceIndex&&(f=t.faceIndex),t.layerIndex&&(m=t.layerIndex),t.layerCounts&&(g=t.layerCounts),this.webGLVersion>1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(l=t.depthTextureFormat));let x=this._gl,T=x.createFramebuffer();this._bindUnboundFramebuffer(T);let S=e.width||e,C=e.height||e,E=[],b=[],y=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),P=this._setupFramebufferDepthAttachments(!y&&a,!o&&n,S,C);v._framebuffer=T,v._depthStencilBuffer=P,v._generateDepthBuffer=!o&&n,v._generateStencilBuffer=!y&&a,v._attachments=b;for(let e=0;e<h;e++){let t=c[e]||3,i=u[e]||0,n=d[e]||!1,a=p[e]||5,o=_[e]||3553,l=null!==(r=g[e])&&void 0!==r?r:1;(1!==i||this._caps.textureFloatLinearFiltering)&&(2!==i||this._caps.textureHalfFloatLinearFiltering)||(t=1);let h=this._getSamplingParameters(t,s);1!==i||this._caps.textureFloat||(i=0,rT.Y.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),n=n&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU);let f=this.webGLVersion>1,m=x[f?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(b.push(m),-1===o)continue;let v=new r5.l(this,r5.S.MultiRenderTarget);E[e]=v,x.activeTexture(x["TEXTURE"+e]),x.bindTexture(o,v._hardwareTexture.underlyingResource),x.texParameteri(o,x.TEXTURE_MAG_FILTER,h.mag),x.texParameteri(o,x.TEXTURE_MIN_FILTER,h.min),x.texParameteri(o,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(o,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE);let T=this._getRGBABufferInternalSizedFormat(i,a,n),y=this._getInternalFormat(a),P=this._getWebGLTextureType(i);if(f&&(35866===o||32879===o))35866===o?v.is2DArray=!0:v.is3D=!0,v.baseDepth=v.depth=l,x.texImage3D(o,0,T,S,C,l,0,y,P,null);else if(34067===o){for(let e=0;e<6;e++)x.texImage2D(x.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,T,S,C,0,y,P,null);v.isCube=!0}else x.texImage2D(x.TEXTURE_2D,0,T,S,C,0,y,P,null);s&&x.generateMipmap(o),this._bindTextureDirectly(o,null),v.baseWidth=S,v.baseHeight=C,v.width=S,v.height=C,v.isReady=!0,v.samples=1,v.generateMipMaps=s,v.samplingMode=t,v.type=i,v._useSRGBBuffer=n,v.format=a,this._internalTexturesCache.push(v)}if(o&&this._caps.depthTextureExtension){let e=new r5.l(this,r5.S.Depth),t=5,i=x.DEPTH_COMPONENT16,r=x.DEPTH_COMPONENT,n=x.UNSIGNED_SHORT,a=x.DEPTH_ATTACHMENT;this.webGLVersion<2?i=x.DEPTH_COMPONENT:14===l?(t=1,n=x.FLOAT,i=x.DEPTH_COMPONENT32F):18===l?(t=0,n=x.FLOAT_32_UNSIGNED_INT_24_8_REV,i=x.DEPTH32F_STENCIL8,r=x.DEPTH_STENCIL,a=x.DEPTH_STENCIL_ATTACHMENT):16===l?(t=0,n=x.UNSIGNED_INT,i=x.DEPTH_COMPONENT24,a=x.DEPTH_ATTACHMENT):(13===l||17===l)&&(t=12,n=x.UNSIGNED_INT_24_8,i=x.DEPTH24_STENCIL8,r=x.DEPTH_STENCIL,a=x.DEPTH_STENCIL_ATTACHMENT),x.activeTexture(x.TEXTURE0),x.bindTexture(x.TEXTURE_2D,e._hardwareTexture.underlyingResource),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MAG_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MIN_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE),x.texImage2D(x.TEXTURE_2D,0,i,S,C,0,r,n,null),x.framebufferTexture2D(x.FRAMEBUFFER,a,x.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=S,e.baseHeight=C,e.width=S,e.height=C,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=l,e.type=t,E[h]=e,this._internalTexturesCache.push(e)}return v.setTextures(E),i&&x.drawBuffers(b),this._bindUnboundFramebuffer(null),v.setLayerAndFaceIndices(m,f),this.resetTextureCache(),v},r6.B.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let r=e._attachments.length;if(0===r)return 1;let s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);let n=!!e._depthStencilBuffer;if(n&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof s.renderbufferStorageMultisample){let n=s.createFramebuffer();if(!n)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);let a=[];for(let t=0;t<r;t++){let i=e.textures[t],r=i._hardwareTexture;r.releaseMSAARenderBuffers()}for(let i=0;i<r;i++){let r=e.textures[i],n=r._hardwareTexture,o=s[this.webGLVersion>1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(r.width,r.height,t,-1,this._getRGBAMultiSampleBufferFormat(r.type,r.format),o);if(!l)throw Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),r.samples=t,a.push(o)}i&&s.drawBuffers(a)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},r6.B.prototype._createDepthStencilCubeTexture=function(e,t,i){let r=new r5.l(this,r5.S.DepthStencil);if(r.isCube=!0,1===this.webGLVersion)return rT.Y.Error("Depth cube texture is not supported by WebGL 1."),r;let s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),n=this._gl;this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),i._depthStencilTexture=r,i._depthStencilTextureWithStencil=s.generateStencil;for(let t=0;t<6;t++)s.generateStencil?n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH24_STENCIL8,e,e,0,n.DEPTH_STENCIL,n.UNSIGNED_INT_24_8,null):n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH_COMPONENT24,e,e,0,n.DEPTH_COMPONENT,n.UNSIGNED_INT,null);return this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(r),r},r6.B.prototype._partialLoadFile=function(e,t,i,r,s=null){this._loadFile(e,e=>{i[t]=e,i._internalCount++,6===i._internalCount&&r(i)},void 0,void 0,!0,(e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)})},r6.B.prototype._cascadeLoadFiles=function(e,t,i,r=null){let s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,r)},r6.B.prototype._cascadeLoadImgs=function(e,t,i,r,s=null,n){let a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(r[o],o,a,e,t,i,s,n)},r6.B.prototype._partialLoadImg=function(e,t,i,r,s,n,a=null,o){let l=(0,rZ.f)();(0,rJ.r6)(e,e=>{i[t]=e,i._internalCount++,r&&r.removePendingData(l),6===i._internalCount&&n&&n(s,i)},(e,t)=>{r&&r.removePendingData(l),a&&a(e,t)},r?r.offlineProvider:null,o),r&&r.addPendingData(l)},r6.B.prototype._setCubeMapTextureParams=function(e,t,i){let r=this._gl;r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null)},r6.B.prototype.createCubeTextureBase=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d=null,p=null,_=!1){let f=c||new r5.l(this,r5.S.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!r,f._lodGenerationScale=h,f._lodGenerationOffset=u,f._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!r),f!==c&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=o,f._files=i);let m=e;this._transformTextureUrl&&!c&&(e=this._transformTextureUrl(e));let g=e.split("?")[0],v=g.lastIndexOf("."),x=o||(v>-1?g.substring(v).toLowerCase():""),T=null;for(let e of r6.B._TextureLoaders)if(e.canLoad(x)){T=e;break}if(T){let onloaddata=e=>{d&&d(f,e),T.loadCubeData(e,f,l,s,n)};i&&6===i.length?T.supportCascades?this._cascadeLoadFiles(t,e=>onloaddata(e.map(e=>new Uint8Array(e))),i,n):n?n("Textures type does not support cascades."):rT.Y.Warn("Texture loader does not support cascades."):this._loadFile(e,e=>onloaddata(new Uint8Array(e)),void 0,void 0,!0,(c,g)=>{e===m?n&&c&&n(c.status+" "+c.statusText,g):(rT.Y.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!r,s,n,a,o,l,h,u,f,d,p,_))})}else{if(!i)throw Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,f,(e,t)=>{p&&p(e,t)},i,n)}return this._internalTexturesCache.push(f),f},r6.B.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d,p=!1){let _=this._gl;return this.createCubeTextureBase(e,t,i,!!r,s,n,a,o,l,h,u,c,e=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),(e,t)=>{let i=this.needPOTTextures?r6.B.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=[_.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);let o=a?this._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA,l=a?this._getInternalFormat(a):_.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(l=o);for(let e=0;e<n.length;e++)if(t[e].width!==i||t[e].height!==i){if(this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext){rT.Y.Warn("Cannot create canvas to resize texture.");return}this._workingCanvas.width=i,this._workingCanvas.height=i,this._workingContext.drawImage(t[e],0,0,t[e].width,t[e].height,0,0,i,i),_.texImage2D(n[e],0,o,l,_.UNSIGNED_BYTE,this._workingCanvas)}else _.texImage2D(n[e],0,o,l,_.UNSIGNED_BYTE,t[e]);r||_.generateMipmap(_.TEXTURE_CUBE_MAP),this._setCubeMapTextureParams(e,!r),e.width=i,e.height=i,e.isReady=!0,a&&(e.format=a),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},!!p)},r6.B.prototype.setTextureSampler=function(e,t){throw Error("setTextureSampler: This engine does not support separate texture sampler objects!")},i(68);let n9=new rf.y$,ae=new rf.y$;Object.defineProperty(rq.D.prototype,"onBeforeViewRenderObservable",{get:function(){return n9}}),Object.defineProperty(rq.D.prototype,"onAfterViewRenderObservable",{get:function(){return ae}}),Object.defineProperty(rq.D.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){var t;this._inputElement!==e&&(this._inputElement=e,null===(t=this._onEngineViewChanged)||void 0===t||t.call(this))}}),rq.D.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},rq.D.prototype.registerView=function(e,t,i){for(let t of(this.views||(this.views=[]),this.views))if(t.target===e)return t;let r=this.getRenderingCanvas();r&&(e.width=r.width,e.height=r.height);let s={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(s),t&&t.onDisposeObservable.add(()=>{this.unRegisterView(e)}),s},rq.D.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(let t of this.views)if(t.target===e){let e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},rq.D.prototype._renderViewStep=function(e){let t=e.target,i=t.getContext("2d");if(!i)return!0;let r=this.getRenderingCanvas();n9.notifyObservers(e);let s=e.camera,n=null,a=null;if(s){if(!(a=s.getScene())||a.activeCameras&&a.activeCameras.length)return!0;this.activeView=e,n=a.activeCamera,a.activeCamera=s}if(e.customResize)e.customResize(t);else{let e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||r.width!==t.width||i!==t.height||r.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!!r.width&&!!r.height&&(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),n&&a&&(a.activeCamera=n),ae.notifyObservers(e),!0)},rq.D.prototype._renderViews=function(){let e;if(!this.views||0===this.views.length)return!1;let t=this.getRenderingCanvas();if(!t)return!1;for(let t of this.views){if(!t.enabled)continue;let i=t.target;if(i===this.inputElement){e=t;continue}if(!this._renderViewStep(t))return!1}return(!e||!!this._renderViewStep(e))&&(this.activeView=null,!0)};var at=i(9255);function transformTextureUrl(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(t=>e&&(e===t||e.match(RegExp("\\b"+t+"\\b","g")))))return e;let t=e.lastIndexOf("."),i=e.lastIndexOf("?"),r=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+r}r6.B.prototype.createStorageBuffer=function(e,t){throw Error("createStorageBuffer: Unsupported method in this engine!")},r6.B.prototype.updateStorageBuffer=function(e,t,i,r){},r6.B.prototype.readFromStorageBuffer=function(e,t,i,r){throw Error("readFromStorageBuffer: Unsupported method in this engine!")},r6.B.prototype.setStorageBuffer=function(e,t){throw Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(rq.D.prototype,"texturesSupported",{get:function(){let e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(rq.D.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),rq.D.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},rq.D.prototype.setTextureFormatToUse=function(e){let t=this.texturesSupported;for(let i=0,r=t.length;i<r;i++)for(let r=0,s=e.length;r<s;r++)if(t[i]===e[r].toLowerCase())return this._transformTextureUrl=transformTextureUrl.bind(this),this._textureFormatInUse=t[i];return this._textureFormatInUse="",this._transformTextureUrl=null,null};let NativeDataStream=class NativeDataStream{constructor(){let e=new ArrayBuffer(NativeDataStream.DEFAULT_BUFFER_SIZE);this._uint32s=new Uint32Array(e),this._int32s=new Int32Array(e),this._float32s=new Float32Array(e),this._length=NativeDataStream.DEFAULT_BUFFER_SIZE/4,this._position=0,this._nativeDataStream=new _native.NativeDataStream(()=>{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}};NativeDataStream.DEFAULT_BUFFER_SIZE=65536;let ai=[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))],ar=[()=>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],applySH3=(e,t)=>ai[e]*ar[e](t),as=[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];let SphericalHarmonics=class SphericalHarmonics{constructor(){this.preScaled=!1,this.l00=rm.P.Zero(),this.l1_1=rm.P.Zero(),this.l10=rm.P.Zero(),this.l11=rm.P.Zero(),this.l2_2=rm.P.Zero(),this.l2_1=rm.P.Zero(),this.l20=rm.P.Zero(),this.l21=rm.P.Zero(),this.l22=rm.P.Zero()}addLight(e,t,i){rm.jp.Vector3[0].set(t.r,t.g,t.b);let r=rm.jp.Vector3[0],s=rm.jp.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(applySH3(0,e),rm.jp.Vector3[2]),this.l00.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(1,e),rm.jp.Vector3[2]),this.l1_1.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(2,e),rm.jp.Vector3[2]),this.l10.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(3,e),rm.jp.Vector3[2]),this.l11.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(4,e),rm.jp.Vector3[2]),this.l2_2.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(5,e),rm.jp.Vector3[2]),this.l2_1.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(6,e),rm.jp.Vector3[2]),this.l20.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(7,e),rm.jp.Vector3[2]),this.l21.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(8,e),rm.jp.Vector3[2]),this.l22.addInPlace(rm.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(as[0]),this.l1_1.scaleInPlace(as[1]),this.l10.scaleInPlace(as[2]),this.l11.scaleInPlace(as[3]),this.l2_2.scaleInPlace(as[4]),this.l2_1.scaleInPlace(as[5]),this.l20.scaleInPlace(as[6]),this.l21.scaleInPlace(as[7]),this.l22.scaleInPlace(as[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(ai[0]),this.l1_1.scaleInPlace(ai[1]),this.l10.scaleInPlace(ai[2]),this.l11.scaleInPlace(ai[3]),this.l2_2.scaleInPlace(ai[4]),this.l2_1.scaleInPlace(ai[5]),this.l20.scaleInPlace(ai[6]),this.l21.scaleInPlace(ai[7]),this.l22.scaleInPlace(ai[8])}updateFromArray(e){return rm.P.FromArrayToRef(e[0],0,this.l00),rm.P.FromArrayToRef(e[1],0,this.l1_1),rm.P.FromArrayToRef(e[2],0,this.l10),rm.P.FromArrayToRef(e[3],0,this.l11),rm.P.FromArrayToRef(e[4],0,this.l2_2),rm.P.FromArrayToRef(e[5],0,this.l2_1),rm.P.FromArrayToRef(e[6],0,this.l20),rm.P.FromArrayToRef(e[7],0,this.l21),rm.P.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return rm.P.FromFloatsToRef(e[0],e[1],e[2],this.l00),rm.P.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),rm.P.FromFloatsToRef(e[6],e[7],e[8],this.l10),rm.P.FromFloatsToRef(e[9],e[10],e[11],this.l11),rm.P.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),rm.P.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),rm.P.FromFloatsToRef(e[18],e[19],e[20],this.l20),rm.P.FromFloatsToRef(e[21],e[22],e[23],this.l21),rm.P.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){let t=new SphericalHarmonics;return t.updateFromArray(e)}static FromPolynomial(e){let t=new SphericalHarmonics;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}};let SphericalPolynomial=class SphericalPolynomial{constructor(){this.x=rm.P.Zero(),this.y=rm.P.Zero(),this.z=rm.P.Zero(),this.xx=rm.P.Zero(),this.yy=rm.P.Zero(),this.zz=rm.P.Zero(),this.xy=rm.P.Zero(),this.yz=rm.P.Zero(),this.zx=rm.P.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=SphericalHarmonics.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){rm.jp.Vector3[0].copyFromFloats(e.r,e.g,e.b);let t=rm.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),rm.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),rm.jp.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(rm.jp.Vector3[0]).addInPlace(rm.jp.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(rm.jp.Vector3[0]).subtractInPlace(rm.jp.Vector3[1]),this.zz.copyFrom(e.l00),rm.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(rm.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){let t=new SphericalPolynomial;return t.updateFromHarmonics(e)}static FromArray(e){let t=new SphericalPolynomial;return rm.P.FromArrayToRef(e[0],0,t.x),rm.P.FromArrayToRef(e[1],0,t.y),rm.P.FromArrayToRef(e[2],0,t.z),rm.P.FromArrayToRef(e[3],0,t.xx),rm.P.FromArrayToRef(e[4],0,t.yy),rm.P.FromArrayToRef(e[5],0,t.zz),rm.P.FromArrayToRef(e[6],0,t.yz),rm.P.FromArrayToRef(e[7],0,t.zx),rm.P.FromArrayToRef(e[8],0,t.xy),t}};let an=`varying vec2 vUV;uniform sampler2D textureSampler; +#include<helperFunctions> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;function CreateResizedCopy(e,t,i,r=!0){let s=e.getScene(),n=s.getEngine(),a=new renderTargetTexture_RenderTargetTexture("resized"+e.name,{width:t,height:i},s,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);a.wrapU=e.wrapU,a.wrapV=e.wrapV,a.uOffset=e.uOffset,a.vOffset=e.vOffset,a.uScale=e.uScale,a.vScale=e.vScale,a.uAng=e.uAng,a.vAng=e.vAng,a.wAng=e.wAng,a.coordinatesIndex=e.coordinatesIndex,a.level=e.level,a.anisotropicFilteringLevel=e.anisotropicFilteringLevel,a._texture.isReady=!1,e.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.wrapV=texture_Texture.CLAMP_ADDRESSMODE;let o=new PassPostProcess("pass",1,null,r?texture_Texture.BILINEAR_SAMPLINGMODE:texture_Texture.NEAREST_SAMPLINGMODE,n,!1,0);return o.externalTextureSamplerBinding=!0,o.getEffect().executeWhenCompiled(()=>{o.onApply=function(t){t.setTexture("textureSampler",e)};let t=a.renderTarget;t&&(s.postProcessManager.directRender([o],t),n.unBindFramebuffer(t),a.disposeFramebufferObjects(),o.dispose(),a.getInternalTexture().isReady=!0)}),a}function ApplyPostProcess(e,t,i,r,s,n,a,o){let l=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,r=null!=r?r:t.type,n=null!=n?n:t.format,a=null!=a?a:t.width,o=null!=o?o:t.height,-1===r&&(r=0),new Promise(h=>{let u=new postProcess_PostProcess("postprocess",e,null,null,1,null,s,l,!1,void 0,r,void 0,null,!1,n);u.externalTextureSamplerBinding=!0;let c=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:r,format:n});u.getEffect().executeWhenCompiled(()=>{u.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([u],c,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),u&&u.dispose(),c._swapAndDie(t),t.type=r,t.format=5,t.isReady=!0,h(t)})})}function ToHalfFloat(e){r||(r=new Float32Array(1),s=new Int32Array(r.buffer)),r[0]=e;let t=s[0],i=t>>16&32768,n=t>>12&2047,a=t>>23&255;return a<103?i:a>142?(i|=31744,i|=(255==a?0:1)&&8388607&t):a<113?(n|=2048,i|=(n>>114-a)+(n>>113-a&1)):(i|=a-112<<10|n>>1,i+=1&n)}function FromHalfFloat(e){let t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*6103515625e-14*(r/1024):31==i?r?NaN:(t?-1:1)*(1/0):(t?-1:1)*Math.pow(2,i-15)*(1+r/1024)}s_.v.ShadersStore.rgbdDecodePixelShader=an;let ProcessAsync=async(e,t,i,r,s)=>{let n;let a=e.getScene(),o=a.getEngine();n=e.isCube?new postProcess_PostProcess("lodCube","lodCube",["lod","gamma"],null,1,null,texture_Texture.NEAREST_NEAREST_MIPNEAREST,o,!1,["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"][r]):new postProcess_PostProcess("lod","lod",["lod","gamma"],null,1,null,texture_Texture.NEAREST_NEAREST_MIPNEAREST,o),await new Promise(e=>{n.getEffect().executeWhenCompiled(()=>{e(0)})});let l=new renderTargetTexture_RenderTargetTexture("temp",{width:t,height:i},a,!1);n.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",s),t.setBool("gamma",e.gammaSpace)};let h=e.getInternalTexture();try{if(l.renderTarget&&h){let r=h.samplingMode;0!==s?e.updateSamplingMode(texture_Texture.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(texture_Texture.NEAREST_NEAREST),a.postProcessManager.directRender([n],l.renderTarget,!0),e.updateSamplingMode(r);let u=await o.readPixels(0,0,t,i),c=new Uint8Array(u.buffer,0,u.byteLength);return o.unBindFramebuffer(l.renderTarget),c}throw Error("Render to texture failed.")}finally{l.dispose(),n.dispose()}};async function GetTextureDataAsync(e,t,i,r=0,s=0){return!e.isReady()&&e._texture&&await new Promise((t,i)=>{if(null===e._texture){i(0);return}e._texture.onLoadedObservable.addOnce(()=>{t(0)})}),await ProcessAsync(e,t,i,r,s)}let aa={CreateResizedCopy,ApplyPostProcess,ToHalfFloat,FromHalfFloat,GetTextureDataAsync};let RGBDTextureTools=class RGBDTextureTools{static ExpandRGBDTexture(e){let t=e._texture;if(!t||!e.isRGBD)return;let i=t.getEngine(),r=i.getCaps(),s=t.isReady,n=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(n=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);let expandRGBDTexture=()=>{if(n){let r=new postProcess_PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);r.externalTextureSamplerBinding=!0;let s=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});r.getEffect().executeWhenCompiled(()=>{r.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([r],s,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),r&&r.dispose(),s._swapAndDie(t),t.isReady=!0})}};s?expandRGBDTexture():e.onLoadObservable.addOnce(expandRGBDTexture)}static EncodeTextureToRGBD(e,t,i=0){return ApplyPostProcess("rgbdEncode",e,t,i,1,5)}};let FileFaceOrientation=class FileFaceOrientation{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}};let CubeMapToSphericalPolynomialTools=class CubeMapToSphericalPolynomialTools{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;let i,r;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();let s=e.getSize().width,n=e.readPixels(0,void 0,void 0,!1),a=e.readPixels(1,void 0,void 0,!1);e.isRenderTarget?(i=e.readPixels(3,void 0,void 0,!1),r=e.readPixels(2,void 0,void 0,!1)):(i=e.readPixels(2,void 0,void 0,!1),r=e.readPixels(3,void 0,void 0,!1));let o=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,u=0;return(1==e.textureType||2==e.textureType)&&(u=1),new Promise(e=>{Promise.all([a,n,i,r,o,l]).then(([t,i,r,n,a,o])=>{let l={size:s,right:i,left:t,up:r,down:n,front:a,back:o,format:5,type:u,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){let t=new SphericalHarmonics,i=0,r=2/e.size,s=.5*r,n=s-1;for(let a=0;a<6;a++){let o=this._FileFaces[a],l=e[o.name],h=n,u=5===e.format?4:3;for(let a=0;a<e.size;a++){let c=n;for(let n=0;n<e.size;n++){let d=o.worldAxisForFileX.scale(c).add(o.worldAxisForFileY.scale(h)).add(o.worldAxisForNormal);d.normalize();let p=this._AreaElement(c-s,h-s)-this._AreaElement(c-s,h+s)-this._AreaElement(c+s,h-s)+this._AreaElement(c+s,h+s),_=l[a*e.size*u+n*u+0],f=l[a*e.size*u+n*u+1],m=l[a*e.size*u+n*u+2];isNaN(_)&&(_=0),isNaN(f)&&(f=0),isNaN(m)&&(m=0),0===e.type&&(_/=255,f/=255,m/=255),e.gammaSpace&&(_=Math.pow(rE.R.Clamp(_),rw.Nn),f=Math.pow(rE.R.Clamp(f),rw.Nn),m=Math.pow(rE.R.Clamp(m),rw.Nn));let g=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){let e=Math.max(_,f,m);if(e>g){let t=g/e;_*=t,f*=t,m*=t}}else _=rE.R.Clamp(_,0,g),f=rE.R.Clamp(f,0,g),m=rE.R.Clamp(m,0,g);let v=new rg.Wo(_,f,m);t.addLight(d,v,p),i+=p,c+=r}h+=r}}let a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),SphericalPolynomial.FromHarmonics(t)}};CubeMapToSphericalPolynomialTools._FileFaces=[new FileFaceOrientation("right",new rm.P(1,0,0),new rm.P(0,0,-1),new rm.P(0,-1,0)),new FileFaceOrientation("left",new rm.P(-1,0,0),new rm.P(0,0,1),new rm.P(0,-1,0)),new FileFaceOrientation("up",new rm.P(0,1,0),new rm.P(1,0,0),new rm.P(0,0,1)),new FileFaceOrientation("down",new rm.P(0,-1,0),new rm.P(1,0,0),new rm.P(0,0,-1)),new FileFaceOrientation("front",new rm.P(0,0,1),new rm.P(1,0,0),new rm.P(0,-1,0)),new FileFaceOrientation("back",new rm.P(0,0,-1),new rm.P(-1,0,0),new rm.P(0,-1,0))],CubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE=4096,CubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS=!1,baseTexture_BaseTexture.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(baseTexture_BaseTexture.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;this._texture.isReady&&!this._texture._sphericalPolynomialPromise&&(this._texture._sphericalPolynomialPromise=CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});let ao=`varying vec2 vUV;uniform sampler2D textureSampler; +#include<helperFunctions> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;s_.v.ShadersStore.rgbdEncodePixelShader=ao;let al="image/png",ah=[134,22,135,150,246,214,150,54];function GetEnvInfo(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=0;for(let e=0;e<ah.length;e++)if(t.getUint8(i++)!==ah[e])return rT.Y.Error("Not a babylon environment map"),null;let r="",s=0;for(;s=t.getUint8(i++);)r+=String.fromCharCode(s);let n=JSON.parse(r);return(n=normalizeEnvInfo(n)).specular&&(n.specular.specularDataPosition=i,n.specular.lodGenerationScale=n.specular.lodGenerationScale||.8),n}function normalizeEnvInfo(e){if(e.version>2)throw Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "2".`);return 2===e.version?e:e=Object.assign(Object.assign({},e),{version:2,imageType:al})}function CreateImageDataArrayBufferViews(e,t){t=normalizeEnvInfo(t);let i=t.specular,r=rE.R.Log2(t.width);if(r=Math.round(r)+1,i.mipmaps.length!==6*r)throw Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);let s=Array(r);for(let t=0;t<r;t++){s[t]=Array(6);for(let r=0;r<6;r++){let n=i.mipmaps[6*t+r];s[t][r]=new Uint8Array(e.buffer,e.byteOffset+i.specularDataPosition+n.position,n.length)}}return s}function UploadEnvLevelsAsync(e,t,i){i=normalizeEnvInfo(i);let r=i.specular;if(!r)return Promise.resolve();e._lodGenerationScale=r.lodGenerationScale;let s=CreateImageDataArrayBufferViews(t,i);return UploadLevelsAsync(e,s,i.imageType)}function _OnImageReadyAsync(e,t,i,r,s,n,a,o,l,h,u){return new Promise((c,d)=>{if(i){let i=t.createTexture(null,!0,!0,null,1,null,e=>{d(e)},e);r.getEffect().executeWhenCompiled(()=>{r.externalTextureSamplerBinding=!0,r.onApply=r=>{r._bindTexture("textureSampler",i),r.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([r],h,!0,n,a),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),c())})}else{if(t._uploadImageToTexture(u,e,n,a),o){let i=l[a];i&&t._uploadImageToTexture(i._texture,e,n,0)}c()}})}function UploadLevelsAsync(e,t,i=al){if(!rW.w1.IsExponentOfTwo(e.width))throw Error("Texture size must be a power of two");let r=rE.R.ILog2(e.width)+1,s=e.getEngine(),n=!1,a=!1,o=null,l=null,h=null,u=s.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,e),u.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?u.textureHalfFloatRender&&u.textureHalfFloatLinearFiltering?(n=!0,e.type=2):u.textureFloatRender&&u.textureFloatLinearFiltering&&(n=!0,e.type=1):n=!1:(n=!1,a=!0,h={}),n)o=new postProcess_PostProcess("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,a){let t=e._lodGenerationScale,i=e._lodGenerationOffset;for(let n=0;n<3;n++){let a=n/2,o=1-a,l=(r-1)*t+i,u=i+(l-i)*o,c=Math.round(Math.min(Math.max(u,0),l)),d=new r5.l(s,r5.S.Temp);d.isCube=!0,d.invertY=!0,d.generateMipMaps=!1,s.updateTextureSamplingMode(2,d);let p=new baseTexture_BaseTexture(null);switch(p._isCube=!0,p._texture=d,h[c]=p,n){case 0:e._lodTextureLow=p;break;case 1:e._lodTextureMid=p;break;case 2:e._lodTextureHigh=p}}}let c=[];for(let r=0;r<t.length;r++)for(let u=0;u<6;u++){let d;let p=t[r][u],_=new Blob([p],{type:i}),f=URL.createObjectURL(_);if("undefined"==typeof Image||s._features.forceBitmapOverHTMLImageElement)d=s.createImageBitmap(_,{premultiplyAlpha:"none"}).then(t=>_OnImageReadyAsync(t,s,n,o,f,u,r,a,h,l,e));else{let t=new Image;t.src=f,d=new Promise((i,c)=>{t.onload=()=>{_OnImageReadyAsync(t,s,n,o,f,u,r,a,h,l,e).then(()=>i()).catch(e=>{c(e)})},t.onerror=e=>{c(e)}})}c.push(d)}if(t.length<r){let i;let n=Math.pow(2,r-1-t.length),a=n*n*4;switch(e.type){case 0:i=new Uint8Array(a);break;case 2:i=new Uint16Array(a);break;case 1:i=new Float32Array(a)}for(let n=t.length;n<r;n++)for(let t=0;t<6;t++)s._uploadArrayBufferViewToTexture(e,i,t,n)}return Promise.all(c).then(()=>{l&&(s._releaseTexture(e),l._swapAndDie(e)),o&&o.dispose(),a&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))})}function UploadEnvSpherical(e,t){t=normalizeEnvInfo(t);let i=t.irradiance;if(!i)return;let r=new SphericalPolynomial;rm.P.FromArrayToRef(i.x,0,r.x),rm.P.FromArrayToRef(i.y,0,r.y),rm.P.FromArrayToRef(i.z,0,r.z),rm.P.FromArrayToRef(i.xx,0,r.xx),rm.P.FromArrayToRef(i.yy,0,r.yy),rm.P.FromArrayToRef(i.zz,0,r.zz),rm.P.FromArrayToRef(i.yz,0,r.yz),rm.P.FromArrayToRef(i.zx,0,r.zx),rm.P.FromArrayToRef(i.xy,0,r.xy),e._sphericalPolynomial=r}function ExtractBetweenMarkers(e,t,i,r){let s=r,n=0,a="";for(;s<i.length;){let r=i.charAt(s);if(a)r===a?'"'===a||"'"===a?"\\"!==i.charAt(s-1)&&(a=""):a="":"*/"===a&&"*"===r&&s+1<i.length&&("/"===i.charAt(s+1)&&(a=""),""===a&&s++);else switch(r){case e:n++;break;case t:n--;break;case'"':case"'":case"`":a=r;break;case"/":if(s+1<i.length){let e=i.charAt(s+1);"/"===e?a="\n":"*"===e&&(a="*/")}}if(s++,0===n)break}return 0===n?s-1:-1}function SkipWhitespaces(e,t){for(;t<e.length;){let i=e[t];if(" "!==i&&"\n"!==i&&"\r"!==i&&" "!==i&&"\n"!==i&&"\xa0"!==i)break;t++}return t}function IsIdentifierChar(e){let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function RemoveComments(e){let t=0,i="",r=!1,s=[];for(;t<e.length;){let n=e.charAt(t);if(i)n===i?'"'===i||"'"===i?("\\"!==e.charAt(t-1)&&(i=""),s.push(n)):(i="",r=!1):"*/"===i&&"*"===n&&t+1<e.length?("/"===e.charAt(t+1)&&(i=""),""===i&&(r=!1,t++)):r||s.push(n);else{switch(n){case'"':case"'":case"`":i=n;break;case"/":if(t+1<e.length){let s=e.charAt(t+1);"/"===s?(i="\n",r=!0):"*"===s&&(i="*/",r=!0)}}r||s.push(n)}t++}return s.join("")}function FindBackward(e,t,i){for(;t>=0&&e.charAt(t)!==i;)t--;return t}function EscapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}let ShaderCodeInliner=class ShaderCodeInliner{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<this._sourceCode.length;){let t=this._sourceCode.indexOf(this.inlineToken,e);if(t<0)break;let i=this._sourceCode.indexOf("(",t+this.inlineToken.length);if(i<0){this.debug&&console.warn(`Could not find the opening parenthesis after the token. startIndex=${e}`),e=t+this.inlineToken.length;continue}let r=ShaderCodeInliner._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(t+this.inlineToken.length,i));if(!r){this.debug&&console.warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(t+this.inlineToken.length,i)}`),e=t+this.inlineToken.length;continue}let[s,n]=[r[3],r[4]],a=ExtractBetweenMarkers("(",")",this._sourceCode,i);if(a<0){this.debug&&console.warn(`Could not extract the parameters the function '${n}' (type=${s}). funcParamsStartIndex=${i}`),e=t+this.inlineToken.length;continue}let o=this._sourceCode.substring(i+1,a),l=SkipWhitespaces(this._sourceCode,a+1);if(l===this._sourceCode.length){this.debug&&console.warn(`Could not extract the body of the function '${n}' (type=${s}). funcParamsEndIndex=${a}`),e=t+this.inlineToken.length;continue}let h=ExtractBetweenMarkers("{","}",this._sourceCode,l);if(h<0){this.debug&&console.warn(`Could not extract the body of the function '${n}' (type=${s}). funcBodyStartIndex=${l}`),e=t+this.inlineToken.length;continue}let u=this._sourceCode.substring(l,h+1),c=RemoveComments(o).split(","),d=[];for(let e=0;e<c.length;++e){let t=c[e].trim(),i=t.lastIndexOf(" ");i>=0&&d.push(t.substring(i+1))}"void"!==s&&d.push("return"),this._functionDescr.push({name:n,type:s,parameters:d,body:u,callIndex:0}),e=h+1;let p=t>0?this._sourceCode.substring(0,t):"",_=h+1<this._sourceCode.length-1?this._sourceCode.substring(h+1):"";this._sourceCode=p+_,e-=h+1-t}this.debug&&console.log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=`,this._functionDescr)}_processInlining(e=20){for(;e-- >=0&&this._replaceFunctionCallsByCode(););return this.debug&&console.log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(let t of this._functionDescr){let{name:i,type:r,parameters:s,body:n}=t,a=0;for(;a<this._sourceCode.length;){let o=this._sourceCode.indexOf(i,a);if(o<0)break;if(0===o||IsIdentifierChar(this._sourceCode.charAt(o-1))){a=o+i.length;continue}let l=SkipWhitespaces(this._sourceCode,o+i.length);if(l===this._sourceCode.length||"("!==this._sourceCode.charAt(l)){a=o+i.length;continue}let h=ExtractBetweenMarkers("(",")",this._sourceCode,l);if(h<0){this.debug&&console.warn(`Could not extract the parameters of the function call. Function '${i}' (type=${r}). callParamsStartIndex=${l}`),a=o+i.length;continue}let u=this._sourceCode.substring(l+1,h),splitParameterCall=e=>{let t=[],i=0,r=0;for(;i<e.length;){if("("===e.charAt(i)){let t=ExtractBetweenMarkers("(",")",e,i);if(t<0)return null;i=t}else","===e.charAt(i)&&(t.push(e.substring(r,i)),r=i+1);i++}return r<i&&t.push(e.substring(r,i)),t},c=splitParameterCall(RemoveComments(u));if(null===c){this.debug&&console.warn(`Invalid function call: can't extract the parameters of the function call. Function '${i}' (type=${r}). callParamsStartIndex=${l}, callParams=`+u),a=o+i.length;continue}let d=[];for(let e=0;e<c.length;++e){let t=c[e].trim();d.push(t)}let p="void"!==r?i+"_"+t.callIndex++:null;if(p&&d.push(p+" ="),d.length!==s.length){this.debug&&console.warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${i}' (type=${r}). function parameters=${s}, call parameters=${d}`),a=o+i.length;continue}a=h+1;let _=this._replaceNames(n,s,d),f=o>0?this._sourceCode.substring(0,o):"",m=h+1<this._sourceCode.length-1?this._sourceCode.substring(h+1):"";if(p){let e=FindBackward(this._sourceCode,o-1,"\n");f=this._sourceCode.substring(0,e+1);let t=this._sourceCode.substring(e+1,o);this._sourceCode=f+r+" "+p+";\n"+_+"\n"+t+p+m,this.debug&&console.log(`Replace function call by code. Function '${i}' (type=${r}). injectDeclarationIndex=${e}, call parameters=${d}`)}else this._sourceCode=f+_+m,a+=_.length-(h+1-o),this.debug&&console.log(`Replace function call by code. Function '${i}' (type=${r}). functionCallIndex=${o}, call parameters=${d}`);e=!0}}return e}_replaceNames(e,t,i){for(let r=0;r<t.length;++r){let s=RegExp(EscapeRegExp(t[r]),"g"),n=t[r].length,a=i[r];e=e.replace(s,(i,...s)=>{let o=s[0];return IsIdentifierChar(e.charAt(o-1))||IsIdentifierChar(e.charAt(o+n))?t[r]:a})}return e}};ShaderCodeInliner._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;var au=i(7666);let NativePipelineContext=class NativePipelineContext{get isAsync(){return this.isParallelCompiled}get isReady(){if(this.compilationError){let e=this.compilationError.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}_handlesSpectorRebuildCallback(e){throw Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this._engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);let u=this._engine.getUniforms(this,i);for(u.forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l<s.length;l++){let t=e.getUniform(s[l]);null==t&&(s.splice(l,1),l--)}s.forEach((e,t)=>{n[e]=t}),o.push(...h.getAttributes(this,a))}dispose(){this._uniforms={}}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n)return n=[t,i,r,s],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),n[3]!==s&&(n[3]=s,a=!0),a}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setUInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&!this._engine.setMatrices(this._uniforms[e],t.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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&!this._engine.setFloat2(this._uniforms[e],t.x,t.y)&&(this._valueCache[e]=null)}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setFloat2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&!this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)&&(this._valueCache[e]=null)}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setFloat3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setFloat4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&!this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)&&(this._valueCache[e]=null)}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(this._valueCache[e]=null)}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&!this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)&&(this._valueCache[e]=null)}};let NativeRenderTargetWrapper=class NativeRenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}};let NativeHardwareTexture=class NativeHardwareTexture{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}};function getNativeTextureFormat(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new si.LH(`Unsupported texture format or type: format ${e}, type ${t}.`,si.SM.UnsupportedTextureError)}function 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 Error(`Unsupported sampling mode: ${e}.`)}}function getNativeAddressMode(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 Error("Unexpected wrap mode: "+e+".")}}function getNativeStencilFunc(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 Error(`Unsupported stencil func mode: ${e}.`)}}function getNativeStencilOpFail(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 Error(`Unsupported stencil OpFail mode: ${e}.`)}}function getNativeStencilDepthFail(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 Error(`Unsupported stencil depthFail mode: ${e}.`)}}function getNativeStencilDepthPass(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 Error(`Unsupported stencil opPass mode: ${e}.`)}}function 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 Error(`Unsupported alpha mode: ${e}.`)}}function getNativeAttribType(e){switch(e){case rz.o.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case rz.o.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case rz.o.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case rz.o.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case rz.o.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw Error(`Unsupported attribute type: ${e}.`)}}let ac=new rf.y$;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{(e=t)&&ac.notifyObservers(e)}})}function AcquireNativeObjectAsync(){return new Promise(e=>{"undefined"==typeof _native?ac.addOnce(t=>e(t)):e(_native)})}async function RegisterNativeTypeAsync(e,t){(await AcquireNativeObjectAsync())[e]=t}let NativeDataBuffer=class NativeDataBuffer extends sI.h{};let CommandBufferEncoder=class CommandBufferEncoder{constructor(e){this._engine=e,this._pending=[],this._isCommandBufferScopeActive=!1,this._commandStream=NativeEngine._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw 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}};let NativeEngine=class NativeEngine extends rq.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 CommandBufferEncoder(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!==NativeEngine.PROTOCOL_VERSION)throw Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${NativeEngine.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:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1},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:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},rW.w1.Log("Babylon Native (v"+rq.D.Version+") launched"),rW.w1.LoadScript=function(e,t,i,r){rW.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 flat(){let e=isNaN(arguments[0])?1:Number(arguments[0]);return e?Array.prototype.reduce.call(this,function(t,i){return Array.isArray(i)?t.push.apply(t,flat.call(i,e-1)):t.push(i),t},[]):Array.prototype.slice.call(this)},writable:!0});let t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();let i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new au.C,this.onNewSceneAddedObservable.add(e=>{let 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 NativeDataStream}_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,r=!1){if(this.useReverseDepthBuffer)throw Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){let r=this._normalizeIndexData(e),s=new NativeDataBuffer;return s.references=1,s.is32Bits=4===r.BYTES_PER_ELEMENT,r.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,s.is32Bits,null!=t&&t)),s}createVertexBuffer(e,t,i){let r=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new NativeDataBuffer;return s.references=1,r.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,null!=t&&t)),s}_recordVertexArrayObject(e,t,i,r,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);let n=r.getAttributesNames();for(let i=0;i<n.length;i++){let a=r.getAttributeLocation(i);if(a>=0){let r=n[i],o=null;if(s&&(o=s[r]),o||(o=t[r]),o){let t=o.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,a,o.byteOffset,o.byteStride,o.getSize(),getNativeAttribType(o.type),o.normalized,o.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){let s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,r),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){return this._engine.getAttributes(e.nativeProgram,t)}drawElementsType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(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,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(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 NativePipelineContext(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,r,s,n,a,o){r?e.nativeProgram=this.createRawShaderProgram():e.nativeProgram=this.createShaderProgram(e,t,i,o)}isAsync(e){return!!(e.isAsync&&this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){if(!this.isAsync(e)){t();return}let i=e.onCompiled;i?e.onCompiled=()=>{i(),t()}:e.onCompiled=t}createRawShaderProgram(){throw Error("Not Supported")}createShaderProgram(e,t,i,r){if(e.nativeProgram)throw Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=new ShaderCodeInliner(t);s.processCode(),t=s.code;let n=new ShaderCodeInliner(i);n.processCode(),i=n.code,t=r6.B._ConcatenateShader(t,r),i=r6.B._ConcatenateShader(i,r);let onSuccess=()=>{var t;e.isCompiled=!0,null===(t=e.onCompiled)||void 0===t||t.call(e),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,onSuccess,t=>{e.compilationError=t});try{let r=e.nativeProgram=this._engine.createProgram(t,i);return onSuccess(),r}catch(t){let e=null==t?void 0:t.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}}inlineShaderCode(e){let t=new ShaderCodeInliner(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){e&&e.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){return this._engine.getUniforms(e.nativeProgram,t)}bindUniformBlock(e,t,i){throw Error("Not Implemented")}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.nativeProgram);let i=e.getSamplers();for(let t=0;t<i.length;t++){let r=e.getUniform(i[t]);r&&(this._boundUniforms[t]=r)}this._currentEffect=null}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._engine.getRenderWidth()}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._engine.getRenderHeight()}setViewport(e,t,i){this._cachedViewport=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.x),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.y),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.width),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.height),this._commandBufferEncoder.finishEncodingCommand()}enableScissor(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR),this._commandBufferEncoder.encodeCommandArgAsFloat32(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand()}disableScissor(){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.finishEncodingCommand()}setState(e,t=0,i,r=!1,s,n,a=0){var o,l;this._zOffset=t,this._zOffsetUnits=a,0!==this._zOffset&&rW.w1.Warn("zOffset is not supported in Native engine."),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(a),this._commandBufferEncoder.encodeCommandArgAsUInt32(null===(l=null!==(o=this.cullBackFaces)&&void 0!==o?o:s)||void 0===l||l?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.finishEncodingCommand()}getInputElementClientRect(){let e={bottom:this.getRenderHeight(),height:this.getRenderHeight(),left:0,right:this.getRenderWidth(),top:0,width:this.getRenderWidth(),x:0,y:0,toJSON:()=>{}};return e}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,getNativeStencilOpFail(this._stencilOpStencilFail),getNativeStencilDepthFail(this._stencilOpDepthFail),getNativeStencilDepthPass(this._stencilOpStencilDepthPass),getNativeStencilFunc(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,r,s,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,r){throw Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;let i=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,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,r,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,r=!1,s){if(void 0===r&&(r=!1),e&&e._hardwareTexture){let i=t.getCanvasTexture(),r=e._hardwareTexture.underlyingResource;this._engine.copyTexture(r,i),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){let r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){let c=new r5.l(this,r5.S.Raw);if(c.format=r,c.generateMipMaps=s,c.samplingMode=a,c.invertY=n,c.baseWidth=t,c.baseHeight=i,c.width=c.baseWidth,c.height=c.baseHeight,c._compression=o,c.type=l,c._useSRGBBuffer=this._getUseSRGBBuffer(u,!s),this.updateRawTexture(c,e,r,n,o,l,c._useSRGBBuffer),c._hardwareTexture){let e=c._hardwareTexture.underlyingResource,t=getNativeSamplingMode(a);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(c),c}createRawTexture2DArray(e,t,i,r,s,n,a,o,l=null,h=0){let u=new r5.l(this,r5.S.Raw2DArray);if(u.baseWidth=t,u.baseHeight=i,u.baseDepth=r,u.width=t,u.height=i,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=n,u.samplingMode=o,u.is2DArray=!0,u._hardwareTexture){let l=u._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,r,getNativeTextureFormat(s,h),n,a);let c=getNativeSamplingMode(o);this._setTextureSampling(l,c)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,r,s=null,n=0,a=!1){if(e){if(t&&e._hardwareTexture){let r=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(r,t,e.width,e.height,getNativeTextureFormat(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_=!1){e=e||"";let f="data:"===e.substr(0,5),m=f&&-1!==e.indexOf(";base64,"),g=l||new r5.l(this,r5.S.Url),v=e;!this._transformTextureUrl||m||l||o||(e=this._transformTextureUrl(e));let x=e.lastIndexOf("."),T=u||(x>-1?e.substring(x).toLowerCase():""),S=null;for(let e of rq.D._TextureLoaders)if(e.canLoad(T)){S=e;break}r&&r.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=s,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(g._buffer=o);let C=null;n&&!l&&(C=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);let onInternalError=(i,l)=>{r&&r.removePendingData(g),e===v?(C&&g.onLoadedObservable.remove(C),rS.l.UseFallbackTexture&&this.createTexture(rS.l.FallbackTexture,t,g.invertY,r,s,null,a,o,g),a&&a((i||"Unknown error")+(rS.l.UseFallbackTexture?" - Fallback texture was used":""),l)):(rT.Y.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,r,s,n,a,o,g,h,u,c,d))};if(S)throw Error("Loading textures from IInternalTextureLoader not yet implemented.");{let onload=e=>{if(!g._hardwareTexture){r&&r.removePendingData(g);return}let n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;let e=getNativeSamplingMode(s);this._setTextureSampling(n,e),r&&r.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>{throw Error("Could not load a native texture.")})};if(f&&o){if(o instanceof ArrayBuffer)onload(new Uint8Array(o));else if(ArrayBuffer.isView(o))onload(o);else if("string"==typeof o)onload(new Uint8Array(rW.w1.DecodeBase64(o)));else throw Error("Unsupported buffer type")}else m?onload(new Uint8Array(rW.w1.DecodeBase64(e))):this._loadFile(e,e=>onload(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{onInternalError("Unable to load "+(e&&e.responseURL,t))})}return g}wrapNativeTexture(e,t=!1,i=3){let r=new NativeHardwareTexture(e,this._engine),s=new r5.l(this,r5.S.Unknown,!0);return s._hardwareTexture=r,s.baseWidth=this._engine.getTextureWidth(e),s.baseHeight=this._engine.getTextureHeight(e),s.width=s.baseWidth,s.height=s.baseHeight,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){var r,s;let n=t.generateStencil||!1,a=t.samples||1,o=new r5.l(this,r5.S.DepthStencil),l=null!==(r=e.width)&&void 0!==r?r:e,h=null!==(s=e.height)&&void 0!==s?s:e,u=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,h,n,!0,a);return i._framebufferDepthStencil=u,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){let i=new Promise((t,i)=>{let r=this.createCanvasImage();r.onload=()=>{try{let e=this._engine.createImageBitmap(r);t(e)}catch(e){i(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{i(`Error loading image ${r.src} with exception: ${e}`)},r.src=e});return i}createImageBitmap(e,t){return new Promise((t,i)=>{if(Array.isArray(e)&&e.length){let i=this._engine.createImageBitmap(e[0]);if(i){t(i);return}}i("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d,p=!1){let _=c||new r5.l(this,r5.S.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!r,_._lodGenerationScale=h,_._lodGenerationOffset=u,_._useSRGBBuffer=this._getUseSRGBBuffer(p,!!r),this._doNotHandleContextLost||(_._extension=o,_._files=i);let f=e.lastIndexOf("."),m=o||(f>-1?e.substring(f).toLowerCase():"");if(".env"===m){let onloaddata=e=>{let t=GetEnvInfo(e);_.width=t.width,_.height=t.width,UploadEnvSpherical(_,t);let i=t.specular;if(!i)throw Error("Nothing else parsed so far");_._lodGenerationScale=i.lodGenerationScale;let r=CreateImageDataArrayBufferViews(e,t);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(texture_Texture.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,r,!1,_._useSRGBBuffer,()=>{_.isReady=!0,s&&s()},()=>{throw Error("Could not load a native cube texture.")})};if(i&&6===i.length)throw Error("Multi-file loading not allowed on env files.");this._loadFile(e,e=>onloaddata(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)})}else{if(!i||6!==i.length)throw Error("Cannot load cubemap because 6 files were not defined");let e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map(e=>rW.w1.LoadFileAsync(e).then(e=>new Uint8Array(e)))).then(e=>new Promise((t,i)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,e,!r,!0,_._useSRGBBuffer,t,i)})).then(()=>{_.isReady=!0,s&&s()},e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)})}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new NativeHardwareTexture(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){let r=new NativeRenderTargetWrapper(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=r5.S.Unknown){var s,n,a;let o;let l=!1,h=0,u=3,c=5,d=!1,p=1;void 0!==t&&"object"==typeof t?(l=!!t.generateMipMaps,h=void 0===t.type?0:t.type,u=void 0===t.samplingMode?3:t.samplingMode,c=void 0===t.format?5:t.format,d=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,p=null!==(s=t.samples)&&void 0!==s?s:1,o=t.label):l=!!t,d=this._getUseSRGBBuffer(d,!l),(1!==h||this._caps.textureFloatLinearFiltering)&&(2!==h||this._caps.textureHalfFloatLinearFiltering)||(u=1),1!==h||this._caps.textureFloat||(h=0,rT.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let _=new r5.l(this,r),f=null!==(n=e.width)&&void 0!==n?n:e,m=null!==(a=e.height)&&void 0!==a?a:e,g=e.layers||0;if(0!==g)throw Error("Texture layers are not supported in Babylon Native");let v=_._hardwareTexture.underlyingResource,x=getNativeTextureFormat(c,h);return this._engine.initializeTexture(v,f,m,l,x,!0,d,p),this._setTextureSampling(v,getNativeSamplingMode(u)),_._useSRGBBuffer=d,_.baseWidth=f,_.baseHeight=m,_.width=f,_.height=m,_.depth=g,_.isReady=!0,_.samples=p,_.generateMipMaps=l,_.samplingMode=u,_.type=h,_.format=c,_.label=o,this._internalTexturesCache.push(_),_}createRenderTargetTexture(e,t){var i,r,s,n;let a;let o=this._createHardwareRenderTargetWrapper(!1,!1,e),l=!0,h=!1,u=!1,c=1;void 0!==t&&"object"==typeof t&&(l=null===(i=t.generateDepthBuffer)||void 0===i||i,h=!!t.generateStencilBuffer,u=!!t.noColorAttachment,a=t.colorAttachment,c=null!==(r=t.samples)&&void 0!==r?r:1);let d=a||(u?null:this._createInternalTexture(e,t,!0,r5.S.RenderTarget)),p=null!==(s=e.width)&&void 0!==s?s:e,_=null!==(n=e.height)&&void 0!==n?n:e,f=this._engine.createFrameBuffer(d?d._hardwareTexture.underlyingResource:null,p,_,h,l,c);return o._framebuffer=f,o._generateDepthBuffer=l,o._generateStencilBuffer=h,o._samples=c,o.setTextures(d),o}updateRenderTargetTextureSampleCount(e,t){return rT.Y.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){let i=getNativeSamplingMode(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,s){if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||r)throw Error("Required width/height for frame buffers not yet supported in NativeEngine.");e._framebufferDepthStencil?this._bindUnboundFramebuffer(e._framebufferDepthStencil):this._bindUnboundFramebuffer(e._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){let r=this._normalizeIndexData(t);e.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(e.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i,r){let s=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(e.nativeVertexBuffer,s.buffer,s.byteOffset+(null!=i?i:0),null!=r?r:s.byteLength)}_setTexture(e,t,i=!1,r=!1){let s;let n=this._boundUniforms[e];if(!n)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;return s=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!!s&&!!s._hardwareTexture&&(this._setTextureWrapMode(s._hardwareTexture.underlyingResource,getNativeAddressMode(t.wrapU),getNativeAddressMode(t.wrapV),getNativeAddressMode(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(n,s._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){let t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){let i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){let 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 Error("Native Canvas plugin not available.");let i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");let e=new _native.Image;return e}updateTextureData(e,t,i,r,s,n,a=0,o=0,l=!1){throw Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,a=0){throw Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,r,s,n,a,o,l,h){var u,c,d,p;if(void 0!==r&&-1!==r)throw Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);return this._engine.readTexture(null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,null!=s?s:0,null!=l?l:0,null!=h?h:0,t,i,null!==(c=null==n?void 0:n.buffer)&&void 0!==c?c:null,null!==(d=null==n?void 0:n.byteOffset)&&void 0!==d?d:0,null!==(p=null==n?void 0:n.byteLength)&&void 0!==p?p:0).then(e=>(n||(n=new Uint8Array(e)),n))}};NativeEngine.PROTOCOL_VERSION=8,NativeEngine._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new ValidatedNativeDataStream:new NativeDataStream};let ValidatedNativeDataStream=class ValidatedNativeDataStream extends NativeDataStream{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)}};(L=tW||(tW={})).LowPower="low-power",L.HighPerformance="high-performance",(w=tH||(tH={})).DepthClipControl="depth-clip-control",w.Depth32FloatStencil8="depth32float-stencil8",w.TextureCompressionBC="texture-compression-bc",w.TextureCompressionETC2="texture-compression-etc2",w.TextureCompressionASTC="texture-compression-astc",w.TimestampQuery="timestamp-query",w.IndirectFirstInstance="indirect-first-instance",w.ShaderF16="shader-f16",w.RG11B10UFloatRenderable="rg11b10ufloat-renderable",w.BGRA8UnormStorage="bgra8unorm-storage",w.Float32Filterable="float32-filterable",(U=tX||(tX={})).Unmapped="unmapped",U.Pending="pending",U.Mapped="mapped",(V=tY||(tY={}))[V.MapRead=1]="MapRead",V[V.MapWrite=2]="MapWrite",V[V.CopySrc=4]="CopySrc",V[V.CopyDst=8]="CopyDst",V[V.Index=16]="Index",V[V.Vertex=32]="Vertex",V[V.Uniform=64]="Uniform",V[V.Storage=128]="Storage",V[V.Indirect=256]="Indirect",V[V.QueryResolve=512]="QueryResolve",(k=tj||(tj={}))[k.Read=1]="Read",k[k.Write=2]="Write",(G=tq||(tq={})).E1d="1d",G.E2d="2d",G.E3d="3d",(z=tK||(tK={}))[z.CopySrc=1]="CopySrc",z[z.CopyDst=2]="CopyDst",z[z.TextureBinding=4]="TextureBinding",z[z.StorageBinding=8]="StorageBinding",z[z.RenderAttachment=16]="RenderAttachment",(W=t$||(t$={})).E1d="1d",W.E2d="2d",W.E2dArray="2d-array",W.Cube="cube",W.CubeArray="cube-array",W.E3d="3d",(H=tQ||(tQ={})).All="all",H.StencilOnly="stencil-only",H.DepthOnly="depth-only",(X=tZ||(tZ={})).R8Unorm="r8unorm",X.R8Snorm="r8snorm",X.R8Uint="r8uint",X.R8Sint="r8sint",X.R16Uint="r16uint",X.R16Sint="r16sint",X.R16Float="r16float",X.RG8Unorm="rg8unorm",X.RG8Snorm="rg8snorm",X.RG8Uint="rg8uint",X.RG8Sint="rg8sint",X.R32Uint="r32uint",X.R32Sint="r32sint",X.R32Float="r32float",X.RG16Uint="rg16uint",X.RG16Sint="rg16sint",X.RG16Float="rg16float",X.RGBA8Unorm="rgba8unorm",X.RGBA8UnormSRGB="rgba8unorm-srgb",X.RGBA8Snorm="rgba8snorm",X.RGBA8Uint="rgba8uint",X.RGBA8Sint="rgba8sint",X.BGRA8Unorm="bgra8unorm",X.BGRA8UnormSRGB="bgra8unorm-srgb",X.RGB9E5UFloat="rgb9e5ufloat",X.RGB10A2UINT="rgb10a2uint",X.RGB10A2Unorm="rgb10a2unorm",X.RG11B10UFloat="rg11b10ufloat",X.RG32Uint="rg32uint",X.RG32Sint="rg32sint",X.RG32Float="rg32float",X.RGBA16Uint="rgba16uint",X.RGBA16Sint="rgba16sint",X.RGBA16Float="rgba16float",X.RGBA32Uint="rgba32uint",X.RGBA32Sint="rgba32sint",X.RGBA32Float="rgba32float",X.Stencil8="stencil8",X.Depth16Unorm="depth16unorm",X.Depth24Plus="depth24plus",X.Depth24PlusStencil8="depth24plus-stencil8",X.Depth32Float="depth32float",X.BC1RGBAUnorm="bc1-rgba-unorm",X.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",X.BC2RGBAUnorm="bc2-rgba-unorm",X.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",X.BC3RGBAUnorm="bc3-rgba-unorm",X.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",X.BC4RUnorm="bc4-r-unorm",X.BC4RSnorm="bc4-r-snorm",X.BC5RGUnorm="bc5-rg-unorm",X.BC5RGSnorm="bc5-rg-snorm",X.BC6HRGBUFloat="bc6h-rgb-ufloat",X.BC6HRGBFloat="bc6h-rgb-float",X.BC7RGBAUnorm="bc7-rgba-unorm",X.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",X.ETC2RGB8Unorm="etc2-rgb8unorm",X.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",X.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",X.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",X.ETC2RGBA8Unorm="etc2-rgba8unorm",X.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",X.EACR11Unorm="eac-r11unorm",X.EACR11Snorm="eac-r11snorm",X.EACRG11Unorm="eac-rg11unorm",X.EACRG11Snorm="eac-rg11snorm",X.ASTC4x4Unorm="astc-4x4-unorm",X.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",X.ASTC5x4Unorm="astc-5x4-unorm",X.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",X.ASTC5x5Unorm="astc-5x5-unorm",X.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",X.ASTC6x5Unorm="astc-6x5-unorm",X.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",X.ASTC6x6Unorm="astc-6x6-unorm",X.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",X.ASTC8x5Unorm="astc-8x5-unorm",X.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",X.ASTC8x6Unorm="astc-8x6-unorm",X.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",X.ASTC8x8Unorm="astc-8x8-unorm",X.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",X.ASTC10x5Unorm="astc-10x5-unorm",X.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",X.ASTC10x6Unorm="astc-10x6-unorm",X.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",X.ASTC10x8Unorm="astc-10x8-unorm",X.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",X.ASTC10x10Unorm="astc-10x10-unorm",X.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",X.ASTC12x10Unorm="astc-12x10-unorm",X.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",X.ASTC12x12Unorm="astc-12x12-unorm",X.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",X.Depth32FloatStencil8="depth32float-stencil8",(Y=tJ||(tJ={})).ClampToEdge="clamp-to-edge",Y.Repeat="repeat",Y.MirrorRepeat="mirror-repeat",(j=t0||(t0={})).Nearest="nearest",j.Linear="linear",(K=t1||(t1={})).Nearest="nearest",K.Linear="linear",($=t2||(t2={})).Never="never",$.Less="less",$.Equal="equal",$.LessEqual="less-equal",$.Greater="greater",$.NotEqual="not-equal",$.GreaterEqual="greater-equal",$.Always="always",(Q=t3||(t3={}))[Q.Vertex=1]="Vertex",Q[Q.Fragment=2]="Fragment",Q[Q.Compute=4]="Compute",(Z=t4||(t4={})).Uniform="uniform",Z.Storage="storage",Z.ReadOnlyStorage="read-only-storage",(J=t5||(t5={})).Filtering="filtering",J.NonFiltering="non-filtering",J.Comparison="comparison",(ee=t6||(t6={})).Float="float",ee.UnfilterableFloat="unfilterable-float",ee.Depth="depth",ee.Sint="sint",ee.Uint="uint",(t8||(t8={})).WriteOnly="write-only",(et=t7||(t7={})).Error="error",et.Warning="warning",et.Info="info",(ei=t9||(t9={})).Validation="validation",ei.Internal="internal",(ie||(ie={})).Auto="auto",(er=it||(it={})).PointList="point-list",er.LineList="line-list",er.LineStrip="line-strip",er.TriangleList="triangle-list",er.TriangleStrip="triangle-strip",(es=ii||(ii={})).CCW="ccw",es.CW="cw",(en=ir||(ir={})).None="none",en.Front="front",en.Back="back",(ea=is||(is={}))[ea.Red=1]="Red",ea[ea.Green=2]="Green",ea[ea.Blue=4]="Blue",ea[ea.Alpha=8]="Alpha",ea[ea.All=15]="All",(eo=ia||(ia={})).Zero="zero",eo.One="one",eo.Src="src",eo.OneMinusSrc="one-minus-src",eo.SrcAlpha="src-alpha",eo.OneMinusSrcAlpha="one-minus-src-alpha",eo.Dst="dst",eo.OneMinusDst="one-minus-dst",eo.DstAlpha="dst-alpha",eo.OneMinusDstAlpha="one-minus-dst-alpha",eo.SrcAlphaSaturated="src-alpha-saturated",eo.Constant="constant",eo.OneMinusConstant="one-minus-constant",(el=io||(io={})).Add="add",el.Subtract="subtract",el.ReverseSubtract="reverse-subtract",el.Min="min",el.Max="max",(eh=il||(il={})).Keep="keep",eh.Zero="zero",eh.Replace="replace",eh.Invert="invert",eh.IncrementClamp="increment-clamp",eh.DecrementClamp="decrement-clamp",eh.IncrementWrap="increment-wrap",eh.DecrementWrap="decrement-wrap",(eu=ih||(ih={})).Uint16="uint16",eu.Uint32="uint32",(ec=iu||(iu={})).Uint8x2="uint8x2",ec.Uint8x4="uint8x4",ec.Sint8x2="sint8x2",ec.Sint8x4="sint8x4",ec.Unorm8x2="unorm8x2",ec.Unorm8x4="unorm8x4",ec.Snorm8x2="snorm8x2",ec.Snorm8x4="snorm8x4",ec.Uint16x2="uint16x2",ec.Uint16x4="uint16x4",ec.Sint16x2="sint16x2",ec.Sint16x4="sint16x4",ec.Unorm16x2="unorm16x2",ec.Unorm16x4="unorm16x4",ec.Snorm16x2="snorm16x2",ec.Snorm16x4="snorm16x4",ec.Float16x2="float16x2",ec.Float16x4="float16x4",ec.Float32="float32",ec.Float32x2="float32x2",ec.Float32x3="float32x3",ec.Float32x4="float32x4",ec.Uint32="uint32",ec.Uint32x2="uint32x2",ec.Uint32x3="uint32x3",ec.Uint32x4="uint32x4",ec.Sint32="sint32",ec.Sint32x2="sint32x2",ec.Sint32x3="sint32x3",ec.Sint32x4="sint32x4",ec.UNORM10x10x10x2="unorm10-10-10-2",(ed=ic||(ic={})).Vertex="vertex",ed.Instance="instance",(ep=id||(id={})).Beginning="beginning",ep.End="end",(e_=ip||(ip={})).Beginning="beginning",e_.End="end",(ef=i_||(i_={})).Load="load",ef.Clear="clear",(em=im||(im={})).Store="store",em.Discard="discard",(eg=ig||(ig={})).Occlusion="occlusion",eg.Timestamp="timestamp",(ev=iv||(iv={})).Opaque="opaque",ev.Premultiplied="premultiplied",(ex=ix||(ix={})).Unknown="unknown",ex.Destroyed="destroyed",(eT=iT||(iT={})).Validation="validation",eT.OutOfMemory="out-of-memory",eT.Internal="internal";let WebGPUShaderProcessor=class WebGPUShaderProcessor{constructor(){this.shaderLanguage=sg.x.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let r=0;[e,t,r]=this._getArraySize(e,t,i);for(let t=0;t<this._webgpuProcessingContext.leftOverUniforms.length;t++)if(this._webgpuProcessingContext.leftOverUniforms[t].name===e)return;this._webgpuProcessingContext.leftOverUniforms.push({name:e,type:t,length:r})}_buildLeftOverUBO(){if(!this._webgpuProcessingContext.leftOverUniforms.length)return"";let e=WebGPUShaderProcessor.LeftOvertUBOName,t=this._webgpuProcessingContext.availableBuffers[e];return t||(t={binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[e]=t,this._addBufferBindingDescription(e,t,t4.Uniform,!0),this._addBufferBindingDescription(e,t,t4.Uniform,!1)),this._generateLeftOverUBOCode(e,t)}_collectBindingNames(){for(let e=0;e<this._webgpuProcessingContext.bindGroupLayoutEntries.length;e++){let t=this._webgpuProcessingContext.bindGroupLayoutEntries[e];if(void 0===t){this._webgpuProcessingContext.bindGroupLayoutEntries[e]=[];continue}for(let i=0;i<t.length;i++){let t=this._webgpuProcessingContext.bindGroupLayoutEntries[e][i],r=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][t.binding].name,s=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][t.binding].nameInArrayOfTexture;t&&(t.texture||t.externalTexture||t.storageTexture?this._webgpuProcessingContext.textureNames.push(s):t.sampler?this._webgpuProcessingContext.samplerNames.push(r):t.buffer&&this._webgpuProcessingContext.bufferNames.push(r))}}}_preCreateBindGroupEntries(){let e=this._webgpuProcessingContext.bindGroupEntries;for(let t=0;t<this._webgpuProcessingContext.bindGroupLayoutEntries.length;t++){let i=this._webgpuProcessingContext.bindGroupLayoutEntries[t],r=[];for(let e=0;e<i.length;e++){let i=this._webgpuProcessingContext.bindGroupLayoutEntries[t][e];i.sampler||i.texture||i.storageTexture||i.externalTexture?r.push({binding:i.binding,resource:void 0}):i.buffer&&r.push({binding:i.binding,resource:{buffer:void 0,offset:0,size:0}})}e[t]=r}}_addTextureBindingDescription(e,t,i,r,s,n){let{groupIndex:a,bindingIndex:o}=t.textures[i];if(this._webgpuProcessingContext.bindGroupLayoutEntries[a]||(this._webgpuProcessingContext.bindGroupLayoutEntries[a]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[a]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[a][o]){let n;n=null===r?this._webgpuProcessingContext.bindGroupLayoutEntries[a].push({binding:o,visibility:0,externalTexture:{}}):s?this._webgpuProcessingContext.bindGroupLayoutEntries[a].push({binding:o,visibility:0,storageTexture:{access:t8.WriteOnly,format:s,viewDimension:r}}):this._webgpuProcessingContext.bindGroupLayoutEntries[a].push({binding:o,visibility:0,texture:{sampleType:t.sampleType,viewDimension:r,multisampled:!1}});let l=t.isTextureArray?e+i:e;this._webgpuProcessingContext.bindGroupLayoutEntryInfo[a][o]={name:e,index:n-1,nameInArrayOfTexture:l}}o=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[a][o].index,n?this._webgpuProcessingContext.bindGroupLayoutEntries[a][o].visibility|=t3.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[a][o].visibility|=t3.Fragment}_addSamplerBindingDescription(e,t,i){let{groupIndex:r,bindingIndex:s}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[r]||(this._webgpuProcessingContext.bindGroupLayoutEntries[r]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][s]){let i=this._webgpuProcessingContext.bindGroupLayoutEntries[r].push({binding:s,visibility:0,sampler:{type:t.type}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][s]={name:e,index:i-1}}s=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][s].index,i?this._webgpuProcessingContext.bindGroupLayoutEntries[r][s].visibility|=t3.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[r][s].visibility|=t3.Fragment}_addBufferBindingDescription(e,t,i,r){let{groupIndex:s,bindingIndex:n}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[s]||(this._webgpuProcessingContext.bindGroupLayoutEntries[s]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][n]){let t=this._webgpuProcessingContext.bindGroupLayoutEntries[s].push({binding:n,visibility:0,buffer:{type:i}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][n]={name:e,index:t-1}}n=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][n].index,r?this._webgpuProcessingContext.bindGroupLayoutEntries[s][n].visibility|=t3.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[s][n].visibility|=t3.Fragment}_injectStartingAndEndingCode(e,t,i,r){let s=e.indexOf(t);if(s<0)return console.error('No "main" function found in shader code! Processing aborted.'),e;if(i){for(;s++<e.length&&"{"!=e.charAt(s););if(s<e.length){let t=e.substring(0,s+1),r=e.substring(s+1);e=t+i+r}}if(r){let t=e.lastIndexOf("}");e=e.substring(0,t)+(r+"\n}")}return e}};WebGPUShaderProcessor.AutoSamplerSuffix="Sampler",WebGPUShaderProcessor.LeftOvertUBOName="LeftOver",WebGPUShaderProcessor.InternalsUBOName="Internals",WebGPUShaderProcessor.UniformSizes={bool:1,int:1,float:1,vec2:2,ivec2:2,uvec2:2,vec3:3,ivec3:3,uvec3:3,vec4:4,ivec4:4,uvec4:4,mat2:4,mat3:12,mat4:16,i32:1,u32:1,f32:1,mat2x2:4,mat3x3:12,mat4x4:16},WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType={sampler2D:"sampler2D",sampler2DArray:"sampler2DArray",sampler2DShadow:"sampler2DShadow",sampler2DArrayShadow:"sampler2DArrayShadow",samplerCube:"samplerCube",sampler3D:"sampler3D"},WebGPUShaderProcessor._TextureTypeByWebGLSamplerType={sampler2D:"texture2D",sampler2DArray:"texture2DArray",sampler2DShadow:"texture2D",sampler2DArrayShadow:"texture2DArray",samplerCube:"textureCube",samplerCubeArray:"textureCubeArray",sampler3D:"texture3D"},WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType={textureCube:t$.Cube,textureCubeArray:t$.CubeArray,texture2D:t$.E2d,texture2DArray:t$.E2dArray,texture3D:t$.E3d},WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType={sampler2DShadow:"samplerShadow",sampler2DArrayShadow:"samplerShadow"},WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType={samplerShadow:!0,samplerArrayShadow:!0,sampler:!1};let WebGPUPipelineContext=class WebGPUPipelineContext{get isAsync(){return!1}get isReady(){return!!this.stages}constructor(e,t){this.bindGroupLayouts={},this._name="unnamed",this.shaderProcessingContext=e,this._leftOverUniformsByName={},this.engine=t,this.vertexBufferKindToType={}}_handlesSpectorRebuildCallback(){}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this.engine;e._fragmentSourceCode="",e._vertexSourceCode="";let u=this.shaderProcessingContext.availableTextures;for(l=0;l<s.length;l++){let e=s[l],t=u[s[l]];null==t||void 0==t?(s.splice(l,1),l--):n[e]=l}for(let e of h.getAttributes(this,a))o.push(e);this.buildUniformLayout();let c=[],d=[];for(l=0;l<a.length;l++){let e=o[l];e>=0&&(c.push(a[l]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=c,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){for(let e of(this.uniformBuffer=new rX.M(this.engine,void 0,void 0,"leftOver-"+this._name),this.shaderProcessingContext.leftOverUniforms)){let t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=WebGPUShaderProcessor.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,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,r,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,r,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,r,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){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}};let ad={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};let WebGPUShaderProcessingContext=class WebGPUShaderProcessingContext{static get KnownUBOs(){return WebGPUShaderProcessingContext._SimplifiedKnownBindings?WebGPUShaderProcessingContext._SimplifiedKnownUBOs:WebGPUShaderProcessingContext._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(){let e=WebGPUShaderProcessingContext.KnownUBOs,t=[];for(let i in e){let r=e[i].binding;-1!==r.groupIndex&&(void 0===t[r.groupIndex]?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;let r=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=ad[e])&&void 0!==i?i:1)*(t||1),r}getVaryingNextLocation(e,t=0){var i;let r=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=ad[e])&&void 0!==i?i:1)*(t||1),r}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.";let t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}};WebGPUShaderProcessingContext._SimplifiedKnownBindings=!0,WebGPUShaderProcessingContext._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}}},WebGPUShaderProcessingContext._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}}};let WebGPUShaderProcessorGLSL=class WebGPUShaderProcessorGLSL extends WebGPUShaderProcessor{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=sg.x.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0,s=e.indexOf("["),n=e.indexOf("]");if(s>0&&n>0){let t=e.substring(s+1,n);isNaN(r=+t)&&(r=+i[t.trim()]),e=e.substr(0,s)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){let i=`// Internals UBO +uniform ${WebGPUShaderProcessor.InternalsUBOName} { +float yFactor_; +float textureOutputHeight_; +}; +`,r=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){let i=t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/;return i.test(e)}varyingProcessor(e,t,i){var r;this._preProcessors=i;let 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,n=s.exec(e);if(null!==n){let s;let a=null!==(r=n[1])&&void 0!==r?r:"",o=n[2],l=n[3];t?(s=this._webgpuProcessingContext.availableVaryings[l],this._missingVaryings[s]="",void 0===s&&rT.Y.Warn(`Invalid fragment shader: The varying named "${l}" is not declared in the vertex shader! This declaration will be ignored.`)):(s=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(l,o,i)[2]),this._webgpuProcessingContext.availableVaryings[l]=s,this._missingVaryings[s]=`layout(location = ${s}) ${a} in ${o} ${l};`),e=e.replace(n[0],void 0===s?"":`layout(location = ${s}) ${a} ${t?"in":"out"} ${o} ${l};`)}return e}attributeProcessor(e,t){this._preProcessors=t;let i=this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,r=i.exec(e);if(null!==r){let i=r[1],s=r[2],n=this._webgpuProcessingContext.getAttributeNextLocation(i,this._getArraySize(s,i,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;let a=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==a){let t=`_int_${s}_`;e=e.replace(r[0],`layout(location = ${n}) in ${a<0?-1===a?"int":"ivec"+-a:1===a?"uint":"uvec"+a} ${t}; ${i} ${s} = ${i}(${t});`)}else e=e.replace(r[0],`layout(location = ${n}) in ${i} ${s};`)}return e}uniformProcessor(e,t,i){var r;this._preProcessors=i;let s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let n=s[1],a=s[2];if(0===n.indexOf("sampler")||1===n.indexOf("sampler")){let s=0;[a,n,s]=this._getArraySize(a,n,i);let o=this._webgpuProcessingContext.availableTextures[a];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:t6.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}let l=null!==(r=WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[n])&&void 0!==r?r:"sampler",h=!!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[l],u=h?t5.Comparison:t5.Filtering,c=a+WebGPUShaderProcessor.AutoSamplerSuffix,d=this._webgpuProcessingContext.availableSamplers[c];d||(d={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:u});let p="u"===n.charAt(0)?"u":"i"===n.charAt(0)?"i":"";p&&(n=n.substr(1));let _=h?t6.Depth:"u"===p?t6.Uint:"i"===p?t6.Sint:t6.Float;o.sampleType=_;let f=s>0,m=d.binding.groupIndex,g=d.binding.bindingIndex,v=WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[n],x=WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[n],T=WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[x];if(f){let t=[];t.push(`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${c};`),e=` +`;for(let i=0;i<s;++i){let r=o.textures[i].groupIndex,s=o.textures[i].bindingIndex;t.push(`layout(set = ${r}, binding = ${s}) uniform ${x} ${a}Texture${i};`),e+=`${i>0?"\n":""}#define ${a}${i} ${p}${v}(${a}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(a)}else s=1,e=`layout(set = ${m}, binding = ${g}) uniform ${l} ${c}; + layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${p}${x} ${a}Texture; + #define ${a} ${p}${v}(${a}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[a]=o,this._webgpuProcessingContext.availableSamplers[c]=d,this._addSamplerBindingDescription(c,d,!t);for(let e=0;e<s;++e)this._addTextureBindingDescription(a,o,e,T,null,!t)}else this._addUniformToLeftOverUBO(a,n,i),e=""}return e}uniformBufferProcessor(e,t){let i=/uniform\s+(\w+)/gm.exec(e);if(null!==i){let r=i[1],s=this._webgpuProcessingContext.availableBuffers[r];if(!s){let e=WebGPUShaderProcessingContext.KnownUBOs[r];s={binding:e&&-1!==e.binding.groupIndex?e.binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[r]=s}this._addBufferBindingDescription(r,s,t4.Uniform,!t),e=e.replace("uniform",`layout(set = ${s.binding.groupIndex}, binding = ${s.binding.bindingIndex}) uniform`)}return e}postProcessor(e,t,i,r,s){let 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){let t=e.indexOf("gl_FragCoord")>=0,i=` + glFragCoord_ = gl_FragCoord; + if (yFactor_ == 1.) { + glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; + } + `,r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){let t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",t?"vec4 glFragCoord_;\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");let i=-1!==t.indexOf("#define MULTIVIEW");if(i)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}if(!i){let t=e.lastIndexOf("}");e=e.substring(0,t)+"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){let i=RegExp(t+"\\s*\\[(.+)?\\]","gm"),r=i.exec(e);for(;null!==r;){let s=r[1],n=+s;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[s.trim()]),e=e.replace(r[0],t+n),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { + `;for(let e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}]; +`:i+=` ${e.type} ${e.name}; +`;return i+"};\n\n"}finalizeShaders(e,t){for(let i=0;i<this._textureArrayProcessing.length;++i){let r=this._textureArrayProcessing[i];e=this._applyTextureArrayProcessing(e,r),t=this._applyTextureArrayProcessing(t,r)}for(let e=0;e<this._missingVaryings.length;++e){let i=this._missingVaryings[e];i&&i.length>0&&(t=i+"\n"+t)}let i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}};let ap=`#if NUM_BONE_INFLUENCERS>0 +attribute matricesIndices : vec4<f32>;attribute matricesWeights : vec4<f32>; +#if NUM_BONE_INFLUENCERS>4 +attribute matricesIndicesExtra : vec4<f32>;attribute matricesWeightsExtra : vec4<f32>; +#endif +#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#ifdef BONETEXTURE +var boneSampler : texture_2d<f32>;uniform boneTextureWidth : f32; +#else +uniform mBones : array<mat4x4,BonesPerMesh>; +#ifdef BONES_VELOCITY_ENABLED +uniform mPreviousBones : array<mat4x4,BonesPerMesh>; +#endif +#endif +#ifdef BONETEXTURE +fn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4<f32> +{let offset=i32(index) *4; +let m0=textureLoad(smp,vec2<i32>(offset+0,0),0);let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);return mat4x4<f32>(m0,m1,m2,m3);} +#endif +#endif +#endif +`;s_.v.IncludesShadersStoreWGSL.bonesDeclaration=ap;let a_=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#if NUM_BONE_INFLUENCERS>0 +var influence : mat4x4<f32>; +#ifdef BONETEXTURE +influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; +#endif +#else +influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#endif +`;s_.v.IncludesShadersStoreWGSL.bonesVertex=a_;let af=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2<f32>;uniform bakedVertexAnimationSettings: vec4<f32>;var bakedVertexAnimationTexture : texture_2d<f32>; +#ifdef INSTANCES +attribute bakedVertexAnimationSettingsInstanced : vec4<f32>; +#endif +fn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32)->mat4x4<f32> +{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);return mat4x4<f32>(m0,m1,m2,m3);} +#endif +`;s_.v.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration=af;let am=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +{ +#ifdef INSTANCES +let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; +#else +let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; +#endif +let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4<f32>;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; +#endif +finalWorld=finalWorld*VATInfluence;} +#endif +`;s_.v.IncludesShadersStoreWGSL.bakedVertexAnimation=am;let ag=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +if (false) {} +#endif +#ifdef CLIPPLANE +else if (fragmentInputs.fClipDistance>0.0) +{discard;} +#endif +#ifdef CLIPPLANE2 +else if (fragmentInputs.fClipDistance2>0.0) +{discard;} +#endif +#ifdef CLIPPLANE3 +else if (fragmentInputs.fClipDistance3>0.0) +{discard;} +#endif +#ifdef CLIPPLANE4 +else if (fragmentInputs.fClipDistance4>0.0) +{discard;} +#endif +#ifdef CLIPPLANE5 +else if (fragmentInputs.fClipDistance5>0.0) +{discard;} +#endif +#ifdef CLIPPLANE6 +else if (fragmentInputs.fClipDistance6>0.0) +{discard;} +#endif +`;s_.v.IncludesShadersStoreWGSL.clipPlaneFragment=ag;let av=`#ifdef CLIPPLANE +varying fClipDistance: f32; +#endif +#ifdef CLIPPLANE2 +varying fClipDistance2: f32; +#endif +#ifdef CLIPPLANE3 +varying fClipDistance3: f32; +#endif +#ifdef CLIPPLANE4 +varying fClipDistance4: f32; +#endif +#ifdef CLIPPLANE5 +varying fClipDistance5: f32; +#endif +#ifdef CLIPPLANE6 +varying fClipDistance6: f32; +#endif +`;s_.v.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration=av;let ax=`#ifdef CLIPPLANE +vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); +#endif +#ifdef CLIPPLANE2 +vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); +#endif +#ifdef CLIPPLANE3 +vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); +#endif +#ifdef CLIPPLANE4 +vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); +#endif +#ifdef CLIPPLANE5 +vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); +#endif +#ifdef CLIPPLANE6 +vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); +#endif +`;s_.v.IncludesShadersStoreWGSL.clipPlaneVertex=ax;let aT=`#ifdef CLIPPLANE +uniform vClipPlane: vec4<f32>;varying fClipDistance: f32; +#endif +#ifdef CLIPPLANE2 +uniform vClipPlane2: vec4<f32>;varying fClipDistance2: f32; +#endif +#ifdef CLIPPLANE3 +uniform vClipPlane3: vec4<f32>;varying fClipDistance3: f32; +#endif +#ifdef CLIPPLANE4 +uniform vClipPlane4: vec4<f32>;varying fClipDistance4: f32; +#endif +#ifdef CLIPPLANE5 +uniform vClipPlane5: vec4<f32>;varying fClipDistance5: f32; +#endif +#ifdef CLIPPLANE6 +uniform vClipPlane6: vec4<f32>;varying fClipDistance6: f32; +#endif +`;s_.v.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration=aT;let aS=`#ifdef INSTANCES +attribute world0 : vec4<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>; +#ifdef INSTANCESCOLOR +attribute instanceColor : vec4<f32>; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform world : mat4x4<f32>; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +attribute previousWorld0 : vec4<f32>;attribute previousWorld1 : vec4<f32>;attribute previousWorld2 : vec4<f32>;attribute previousWorld3 : vec4<f32>; +#ifdef THIN_INSTANCES +uniform previousWorld : mat4x4<f32>; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform world : mat4x4<f32>; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +uniform previousWorld : mat4x4<f32>; +#endif +#endif +`;s_.v.IncludesShadersStoreWGSL.instancesDeclaration=aS;let aC=`#ifdef INSTANCES +var finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +var finalPreviousWorld=mat4x4<f32>(previousWorld0,previousWorld1,previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +#if !defined(WORLD_UBO) +finalWorld=uniforms.world*finalWorld; +#else +finalWorld=mesh.world*finalWorld; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +var finalWorld=uniforms.world; +#else +var finalWorld=mesh.world; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +var finalPreviousWorld=previousWorld; +#endif +#endif +`;s_.v.IncludesShadersStoreWGSL.instancesVertex=aC;let aE=`struct Mesh {world : mat4x4<f32>, +visibility : f32,};var<uniform> mesh : Mesh; +#define WORLD_UBO +`;s_.v.IncludesShadersStoreWGSL.meshUboDeclaration=aE;let ab=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#ifdef MORPHTARGETS_NORMAL +normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; +#endif +#else +positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; +#endif +#endif +#endif +`;s_.v.IncludesShadersStoreWGSL.morphTargetsVertex=ab;let ay=`#ifdef MORPHTARGETS +#ifndef MORPHTARGETS_TEXTURE +attribute position{X} : vec3<f32>; +#ifdef MORPHTARGETS_NORMAL +attribute normal{X} : vec3<f32>; +#endif +#ifdef MORPHTARGETS_TANGENT +attribute tangent{X} : vec3<f32>; +#endif +#ifdef MORPHTARGETS_UV +attribute uv_{X} : vec2<f32>; +#endif +#endif +#endif +`;s_.v.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration=ay;let aP=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +var vertexID : f32; +#endif +#endif +`;s_.v.IncludesShadersStoreWGSL.morphTargetsVertexGlobal=aP;let aR=`#ifdef MORPHTARGETS +uniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>; +#ifdef MORPHTARGETS_TEXTURE +uniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;uniform morphTargetTextureInfo : vec3<f32>;var morphTargets : texture_2d_array<f32>;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3<f32> +{ +let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2<f32>((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} +#endif +#endif +`;s_.v.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration=aR;let aA=`struct Scene {viewProjection : mat4x4<f32>, +#ifdef MULTIVIEW +viewProjectionR : mat4x4<f32>, +#endif +view : mat4x4<f32>, +projection : mat4x4<f32>, +vEyePosition : vec4<f32>,};var<uniform> scene : Scene; +`;s_.v.IncludesShadersStoreWGSL.sceneUboDeclaration=aA;let aI="fragmentOutputs.fragDepth",aM={texture_1d:t$.E1d,texture_2d:t$.E2d,texture_2d_array:t$.E2dArray,texture_3d:t$.E3d,texture_cube:t$.Cube,texture_cube_array:t$.CubeArray,texture_multisampled_2d:t$.E2d,texture_depth_2d:t$.E2d,texture_depth_2d_array:t$.E2dArray,texture_depth_cube:t$.Cube,texture_depth_cube_array:t$.CubeArray,texture_depth_multisampled_2d:t$.E2d,texture_storage_1d:t$.E1d,texture_storage_2d:t$.E2d,texture_storage_2d_array:t$.E2dArray,texture_storage_3d:t$.E3d,texture_external:null};let WebGPUShaderProcessorWGSL=class WebGPUShaderProcessorWGSL extends WebGPUShaderProcessor{constructor(){super(...arguments),this.shaderLanguage=sg.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 r=0,s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;let n=t.substring(e+1,s);for(isNaN(r=+n)&&(r=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${WebGPUShaderProcessor.InternalsUBOName} { + yFactor_: f32, + textureOutputHeight_: f32, +}; +var<uniform> internals : ${WebGPUShaderProcessor.InternalsUBOName}; +`+RemoveComments(e)}varyingProcessor(e,t,i){let r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==r){let s;let n=r[2],a=r[1];t?void 0===(s=this._webgpuProcessingContext.availableVaryings[a])&&rT.Y.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`):(s=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(a,n,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=s,this._varyingsWGSL.push(` @location(${s}) ${a} : ${n},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){let i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){let r=i[2],s=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;let a=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==a){let e=`_int_${s}_`;this._attributesInputWGSL.push(`@location(${n}) ${e} : ${a<0?-1===a?"i32":"vec"+-a+"<i32>":1===a?"u32":"vec"+a+"<u32>"},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = ${r}(vertexInputs_.${e});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${s} : ${r},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = vertexInputs_.${s};`);e=""}return e}uniformProcessor(e,t,i){let r=this.uniformRegexp.exec(e);if(null!==r){let t=r[2],s=r[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){let r=this.textureRegexp.exec(e);if(null!==r){let s=r[1],n=r[2],a=!!r[3],o=r[4],l=o.indexOf("storage")>0,h=r[6],u=l?h.substring(0,h.indexOf(",")).trim():null,c=a?this._getArraySize(s,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[s];if(d)c=d.textures.length;else{d={isTextureArray:c>0,isStorageTexture:l,textures:[],sampleType:t6.Float},c=c||1;for(let e=0;e<c;++e)d.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}this._webgpuProcessingContext.availableTextures[s]=d;let p=o.indexOf("depth")>0,_=aM[o],f=p?t6.Depth:"u32"===h?t6.Uint:"i32"===h?t6.Sint:t6.Float;if(d.sampleType=f,void 0===_)throw`Can't get the texture dimension corresponding to the texture function "${o}"!`;for(let i=0;i<c;++i){let{groupIndex:r,bindingIndex:n}=d.textures[i];0===i&&(e=`@group(${r}) @binding(${n}) ${e}`),this._addTextureBindingDescription(s,d,i,_,u,!t)}}return e}postProcessor(e){return e}finalizeShaders(e,t){let i=t.indexOf("fragmentInputs.position")>=0?` + if (internals.yFactor_ == 1.) { + fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; + } + `:"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);let r=this._buildLeftOverUBO();e=r+e,t=r+t,e=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._attributesInputWGSL.length>0&&(s+=this._attributesInputWGSL.join("\n")),s+="\n};\nvar<private> vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(s+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n"+this._attributesWGSL.join("\n")+"\n};\nvar<private> vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar<private> vertexOutputs : FragmentInputs;\n",e=s+n+e;let a=` + vertexInputs${this._hasNonFloatAttribute?"_":""} = input; +`;this._hasNonFloatAttribute&&(a+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n"+this._attributesConversionCodeWGSL.join("\n")+"\n");let o=` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; + return vertexOutputs;`;e=this._injectStartingAndEndingCode(e,"fn main",a,o),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar<private> fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4<f32>,\n",u=!1,c=0;for(;!u&&!((c=t.indexOf(aI,c))<0);){let e=c;for(u=!0;c>1&&"\n"!==t.charAt(c);){if("/"===t.charAt(c)&&"/"===t.charAt(c-1)){u=!1;break}c--}c=e+aI.length}return u&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar<private> fragmentOutputs : FragmentOutputs;\n",t=l+h+t,t=this._injectStartingAndEndingCode(t,"fn main"," fragmentInputs = input;\n "+i," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} { +`;for(let t of this._webgpuProcessingContext.leftOverUniforms){let s=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=WebGPUShaderProcessor.UniformSizes[s];if(t.length>0){if(n<=2){let n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} { + @size(16) + el: ${s}, + }`,this._stridedUniformArrays.push(t.name),r+=` @align(16) ${t.name} : array<${n}, ${t.length}>, +`}else r+=` ${t.name} : array<${t.type}, ${t.length}>, +`}else r+=` ${t.name} : ${t.type}, +`}return r+="};\n",r=`${i} +${r}@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var<uniform> uniforms : ${e}; +`}_processSamplers(e,t){let i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],n=r[2],a=s.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)===s.length-WebGPUShaderProcessor.AutoSamplerSuffix.length?s.substring(0,s.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)):null,o="sampler_comparison"===n?t5.Comparison:t5.Filtering;if(a){let e=this._webgpuProcessingContext.availableTextures[a];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:o},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);let h=e.substring(0,r.index),u=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,c=e.substring(r.index);e=h+u+c,i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){let i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],n=r[3],a=r[4],o=r[5],l=this._webgpuProcessingContext.availableBuffers[a];if(!l){let e;let t="uniform"===s?WebGPUShaderProcessingContext.KnownUBOs[o]:null;t?(a=o,-1===(e=t.binding).groupIndex&&(e=this._webgpuProcessingContext.getNextFreeUBOBinding())):e=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:e},this._webgpuProcessingContext.availableBuffers[a]=l}this._addBufferBindingDescription(a,this._webgpuProcessingContext.availableBuffers[a],"read_write"===n?t4.Storage:"storage"===s?t4.ReadOnlyStorage:t4.Uniform,t);let h=l.binding.groupIndex,u=l.binding.bindingIndex,c=e.substring(0,r.index),d=`@group(${h}) @binding(${u}) `,p=e.substring(r.index);e=c+d+p,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(let t of this._stridedUniformArrays)e=e.replace(RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}};let WebGPUHardwareTexture=class WebGPUHardwareTexture{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(let e of this._webgpuMSAATexture)null==e||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=tZ.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,s){this.createView({format:this.format,dimension:i?t$.Cube:t$.E2d,mipLevelCount:t?rE.R.ILog2(Math.max(r,s))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:tQ.All})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){let 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()}};let aD=` + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); + + layout(location = 0) out vec2 vTex; + + void main() { + vTex = tex[gl_VertexIndex]; + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,aO=` + layout(set = 0, binding = 0) uniform sampler imgSampler; + layout(set = 0, binding = 1) uniform texture2D img; + + layout(location = 0) in vec2 vTex; + layout(location = 0) out vec4 outColor; + + void main() { + outColor = texture(sampler2D(img, imgSampler), vTex); + } + `,aN=` + #extension GL_EXT_samplerless_texture_functions : enable + + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); + + layout(set = 0, binding = 0) uniform texture2D img; + + #ifdef INVERTY + layout(location = 0) out flat ivec2 vTextureSize; + #endif + + void main() { + #ifdef INVERTY + vTextureSize = textureSize(img, 0); + #endif + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,aF=` + #extension GL_EXT_samplerless_texture_functions : enable + + layout(set = 0, binding = 0) uniform texture2D img; + + #ifdef INVERTY + layout(location = 0) in flat ivec2 vTextureSize; + #endif + layout(location = 0) out vec4 outColor; + + void main() { + #ifdef INVERTY + vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0); + #else + vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color.rgb *= color.a; + #endif + outColor = color; + } + `,aB=` + #extension GL_EXT_samplerless_texture_functions : enable + + layout(set = 0, binding = 0) uniform texture2D img; + layout(set = 0, binding = 1) uniform Params { + float ofstX; + float ofstY; + float width; + float height; + }; + + #ifdef INVERTY + layout(location = 0) in flat ivec2 vTextureSize; + #endif + layout(location = 0) out vec4 outColor; + + void main() { + if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) { + discard; + } + if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) { + discard; + } + #ifdef INVERTY + vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0); + #else + vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color.rgb *= color.a; + #endif + outColor = color; + } + `,aL=` + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + + void main() { + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,aw=` + layout(set = 0, binding = 0) uniform Uniforms { + uniform vec4 color; + }; + + layout(location = 0) out vec4 outColor; + + void main() { + outColor = color; + } + `,aU=` + struct VertexOutput { + @builtin(position) Position : vec4<f32>, + @location(0) fragUV : vec2<f32> + } + + @vertex + fn main( + @builtin(vertex_index) VertexIndex : u32 + ) -> VertexOutput { + var pos = array<vec2<f32>, 4>( + vec2(-1.0, 1.0), + vec2( 1.0, 1.0), + vec2(-1.0, -1.0), + vec2( 1.0, -1.0) + ); + var tex = array<vec2<f32>, 4>( + vec2(0.0, 0.0), + vec2(1.0, 0.0), + vec2(0.0, 1.0), + vec2(1.0, 1.0) + ); + + var output: VertexOutput; + + output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0); + output.fragUV = tex[VertexIndex]; + + return output; + } + `,aV=` + @group(0) @binding(0) var videoSampler: sampler; + @group(0) @binding(1) var videoTexture: texture_external; + + @fragment + fn main( + @location(0) fragUV: vec2<f32> + ) -> @location(0) vec4<f32> { + return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); + } + `,ak=` + @group(0) @binding(0) var videoSampler: sampler; + @group(0) @binding(1) var videoTexture: texture_external; + + @fragment + fn main( + @location(0) fragUV: vec2<f32> + ) -> @location(0) vec4<f32> { + return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2<f32>(fragUV.x, 1.0 - fragUV.y)); + } + `;(eS=iS||(iS={}))[eS.MipMap=0]="MipMap",eS[eS.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",eS[eS.Clear=2]="Clear",eS[eS.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst",(eC=iC||(iC={}))[eC.DontInvertY=0]="DontInvertY",eC[eC.InvertY=1]="InvertY";let aG=[{vertex:aD,fragment:aO},{vertex:aN,fragment:aF},{vertex:aL,fragment:aw},{vertex:aN,fragment:aB}],az={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};let WebGPUTextureHelper=class WebGPUTextureHelper{static ComputeNumMipmapLevels(e,t){return rE.R.ILog2(Math.max(e,t))+1}constructor(e,t,i,r,s){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=r,-1!==s.indexOf(tH.RG11B10UFloatRenderable)){let e=Object.keys(az);az[tZ.RG11B10UFloat]=az[e[e.length-1]]+1}this._mipmapSampler=e.createSampler({minFilter:t0.Linear}),this._videoSampler=e.createSampler({minFilter:t0.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,tY.Uniform|tY.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(tZ.RGBA8Unorm),this._getVideoPipeline(tZ.RGBA8Unorm)}_getPipeline(e,t=iS.MipMap,i){let r=t===iS.MipMap?1:t===iS.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===iS.Clear?8:t===iS.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][r];if(!s){let n="#version 450\n";(t===iS.InvertYPremultiplyAlpha||t===iS.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let a=this._compiledShaders[r];if(!a){let e=this._glslang.compileGLSL(n+aG[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+aG[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));let s=this._device.createShaderModule({code:e}),o=this._device.createShaderModule({code:i});a=this._compiledShaders[r]=[s,o]}let o=this._device.createRenderPipeline({layout:ie.Auto,vertex:{module:a[0],entryPoint:"main"},fragment:{module:a[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:it.TriangleStrip,stripIndexFormat:ih.Uint16}});s=this._pipelines[e][r]=[o,o.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=iC.DontInvertY){let i=t===iC.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let t=this._videoCompiledShaders[i];if(!t){let e=this._device.createShaderModule({code:aU}),r=this._device.createShaderModule({code:0===i?aV:ak});t=this._videoCompiledShaders[i]=[e,r]}let s=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:ie.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:it.TriangleStrip,stripIndexFormat:ih.Uint16}});r=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return r}static _GetTextureTypeFromFormat(e){switch(e){case tZ.R8Unorm:case tZ.R8Snorm:case tZ.R8Uint:case tZ.R8Sint:case tZ.RG8Unorm:case tZ.RG8Snorm:case tZ.RG8Uint:case tZ.RG8Sint:case tZ.RGBA8Unorm:case tZ.RGBA8UnormSRGB:case tZ.RGBA8Snorm:case tZ.RGBA8Uint:case tZ.RGBA8Sint:case tZ.BGRA8Unorm:case tZ.BGRA8UnormSRGB:case tZ.RGB10A2UINT:case tZ.RGB10A2Unorm:case tZ.RGB9E5UFloat:case tZ.RG11B10UFloat:case tZ.Depth32FloatStencil8:case tZ.BC7RGBAUnorm:case tZ.BC7RGBAUnormSRGB:case tZ.BC6HRGBUFloat:case tZ.BC6HRGBFloat:case tZ.BC5RGUnorm:case tZ.BC5RGSnorm:case tZ.BC3RGBAUnorm:case tZ.BC3RGBAUnormSRGB:case tZ.BC2RGBAUnorm:case tZ.BC2RGBAUnormSRGB:case tZ.BC4RUnorm:case tZ.BC4RSnorm:case tZ.BC1RGBAUnorm:case tZ.BC1RGBAUnormSRGB:case tZ.ETC2RGB8Unorm:case tZ.ETC2RGB8UnormSRGB:case tZ.ETC2RGB8A1Unorm:case tZ.ETC2RGB8A1UnormSRGB:case tZ.ETC2RGBA8Unorm:case tZ.ETC2RGBA8UnormSRGB:case tZ.EACR11Unorm:case tZ.EACR11Snorm:case tZ.EACRG11Unorm:case tZ.EACRG11Snorm:case tZ.ASTC4x4Unorm:case tZ.ASTC4x4UnormSRGB:case tZ.ASTC5x4Unorm:case tZ.ASTC5x4UnormSRGB:case tZ.ASTC5x5Unorm:case tZ.ASTC5x5UnormSRGB:case tZ.ASTC6x5Unorm:case tZ.ASTC6x5UnormSRGB:case tZ.ASTC6x6Unorm:case tZ.ASTC6x6UnormSRGB:case tZ.ASTC8x5Unorm:case tZ.ASTC8x5UnormSRGB:case tZ.ASTC8x6Unorm:case tZ.ASTC8x6UnormSRGB:case tZ.ASTC8x8Unorm:case tZ.ASTC8x8UnormSRGB:case tZ.ASTC10x5Unorm:case tZ.ASTC10x5UnormSRGB:case tZ.ASTC10x6Unorm:case tZ.ASTC10x6UnormSRGB:case tZ.ASTC10x8Unorm:case tZ.ASTC10x8UnormSRGB:case tZ.ASTC10x10Unorm:case tZ.ASTC10x10UnormSRGB:case tZ.ASTC12x10Unorm:case tZ.ASTC12x10UnormSRGB:case tZ.ASTC12x12Unorm:case tZ.ASTC12x12UnormSRGB:break;case tZ.R16Uint:case tZ.R16Sint:case tZ.RG16Uint:case tZ.RG16Sint:case tZ.RGBA16Uint:case tZ.RGBA16Sint:case tZ.Depth16Unorm:return 5;case tZ.R16Float:case tZ.RG16Float:case tZ.RGBA16Float:return 2;case tZ.R32Uint:case tZ.R32Sint:case tZ.RG32Uint:case tZ.RG32Sint:case tZ.RGBA32Uint:case tZ.RGBA32Sint:return 7;case tZ.R32Float:case tZ.RG32Float:case tZ.RGBA32Float:case tZ.Depth32Float:return 1;case tZ.Stencil8:throw"No fixed size for Stencil8 format!";case tZ.Depth24Plus:throw"No fixed size for Depth24Plus format!";case tZ.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0}static _GetBlockInformationFromFormat(e){switch(e){case tZ.R8Unorm:case tZ.R8Snorm:case tZ.R8Uint:case tZ.R8Sint:return{width:1,height:1,length:1};case tZ.R16Uint:case tZ.R16Sint:case tZ.R16Float:case tZ.RG8Unorm:case tZ.RG8Snorm:case tZ.RG8Uint:case tZ.RG8Sint:return{width:1,height:1,length:2};case tZ.R32Uint:case tZ.R32Sint:case tZ.R32Float:case tZ.RG16Uint:case tZ.RG16Sint:case tZ.RG16Float:case tZ.RGBA8Unorm:case tZ.RGBA8UnormSRGB:case tZ.RGBA8Snorm:case tZ.RGBA8Uint:case tZ.RGBA8Sint:case tZ.BGRA8Unorm:case tZ.BGRA8UnormSRGB:case tZ.RGB9E5UFloat:case tZ.RGB10A2UINT:case tZ.RGB10A2Unorm:case tZ.RG11B10UFloat:break;case tZ.RG32Uint:case tZ.RG32Sint:case tZ.RG32Float:case tZ.RGBA16Uint:case tZ.RGBA16Sint:case tZ.RGBA16Float:return{width:1,height:1,length:8};case tZ.RGBA32Uint:case tZ.RGBA32Sint:case tZ.RGBA32Float:return{width:1,height:1,length:16};case tZ.Stencil8:throw"No fixed size for Stencil8 format!";case tZ.Depth16Unorm:return{width:1,height:1,length:2};case tZ.Depth24Plus:throw"No fixed size for Depth24Plus format!";case tZ.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case tZ.Depth32Float:break;case tZ.Depth32FloatStencil8:return{width:1,height:1,length:5};case tZ.BC7RGBAUnorm:case tZ.BC7RGBAUnormSRGB:case tZ.BC6HRGBUFloat:case tZ.BC6HRGBFloat:case tZ.BC5RGUnorm:case tZ.BC5RGSnorm:case tZ.BC3RGBAUnorm:case tZ.BC3RGBAUnormSRGB:case tZ.BC2RGBAUnorm:case tZ.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case tZ.BC4RUnorm:case tZ.BC4RSnorm:case tZ.BC1RGBAUnorm:case tZ.BC1RGBAUnormSRGB:case tZ.ETC2RGB8Unorm:case tZ.ETC2RGB8UnormSRGB:case tZ.ETC2RGB8A1Unorm:case tZ.ETC2RGB8A1UnormSRGB:case tZ.EACR11Unorm:case tZ.EACR11Snorm:return{width:4,height:4,length:8};case tZ.ETC2RGBA8Unorm:case tZ.ETC2RGBA8UnormSRGB:case tZ.EACRG11Unorm:case tZ.EACRG11Snorm:case tZ.ASTC4x4Unorm:case tZ.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case tZ.ASTC5x4Unorm:case tZ.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case tZ.ASTC5x5Unorm:case tZ.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case tZ.ASTC6x5Unorm:case tZ.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case tZ.ASTC6x6Unorm:case tZ.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case tZ.ASTC8x5Unorm:case tZ.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case tZ.ASTC8x6Unorm:case tZ.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case tZ.ASTC8x8Unorm:case tZ.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case tZ.ASTC10x5Unorm:case tZ.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case tZ.ASTC10x6Unorm:case tZ.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case tZ.ASTC10x8Unorm:case tZ.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case tZ.ASTC10x10Unorm:case tZ.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case tZ.ASTC12x10Unorm:case tZ.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case tZ.ASTC12x12Unorm:case tZ.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 tZ.BC7RGBAUnormSRGB:case tZ.BC7RGBAUnorm:case tZ.BC6HRGBFloat:case tZ.BC6HRGBUFloat:case tZ.BC5RGSnorm:case tZ.BC5RGUnorm:case tZ.BC4RSnorm:case tZ.BC4RUnorm:case tZ.BC3RGBAUnormSRGB:case tZ.BC3RGBAUnorm:case tZ.BC2RGBAUnormSRGB:case tZ.BC2RGBAUnorm:case tZ.BC1RGBAUnormSRGB:case tZ.BC1RGBAUnorm:case tZ.ETC2RGB8Unorm:case tZ.ETC2RGB8UnormSRGB:case tZ.ETC2RGB8A1Unorm:case tZ.ETC2RGB8A1UnormSRGB:case tZ.ETC2RGBA8Unorm:case tZ.ETC2RGBA8UnormSRGB:case tZ.EACR11Unorm:case tZ.EACR11Snorm:case tZ.EACRG11Unorm:case tZ.EACRG11Snorm:case tZ.ASTC4x4Unorm:case tZ.ASTC4x4UnormSRGB:case tZ.ASTC5x4Unorm:case tZ.ASTC5x4UnormSRGB:case tZ.ASTC5x5Unorm:case tZ.ASTC5x5UnormSRGB:case tZ.ASTC6x5Unorm:case tZ.ASTC6x5UnormSRGB:case tZ.ASTC6x6Unorm:case tZ.ASTC6x6UnormSRGB:case tZ.ASTC8x5Unorm:case tZ.ASTC8x5UnormSRGB:case tZ.ASTC8x6Unorm:case tZ.ASTC8x6UnormSRGB:case tZ.ASTC8x8Unorm:case tZ.ASTC8x8UnormSRGB:case tZ.ASTC10x5Unorm:case tZ.ASTC10x5UnormSRGB:case tZ.ASTC10x6Unorm:case tZ.ASTC10x6UnormSRGB:case tZ.ASTC10x8Unorm:case tZ.ASTC10x8UnormSRGB:case tZ.ASTC10x10Unorm:case tZ.ASTC10x10UnormSRGB:case tZ.ASTC12x10Unorm:case tZ.ASTC12x10UnormSRGB:case tZ.ASTC12x12Unorm:case tZ.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return tZ.Depth16Unorm;case 16:return tZ.Depth24Plus;case 13:return tZ.Depth24PlusStencil8;case 14:return tZ.Depth32Float;case 18:return tZ.Depth32FloatStencil8;case 19:return tZ.Stencil8;case 36492:return i?tZ.BC7RGBAUnormSRGB:tZ.BC7RGBAUnorm;case 36495:return tZ.BC6HRGBUFloat;case 36494:return tZ.BC6HRGBFloat;case 33779:return i?tZ.BC3RGBAUnormSRGB:tZ.BC3RGBAUnorm;case 33778:return i?tZ.BC2RGBAUnormSRGB:tZ.BC2RGBAUnorm;case 33777:case 33776:return i?tZ.BC1RGBAUnormSRGB:tZ.BC1RGBAUnorm;case 37808:return i?tZ.ASTC4x4UnormSRGB:tZ.ASTC4x4Unorm;case 36196:case 37492:return i?tZ.ETC2RGB8UnormSRGB:tZ.ETC2RGB8Unorm;case 37496:return i?tZ.ETC2RGBA8UnormSRGB:tZ.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return tZ.R8Snorm;case 7:return tZ.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return tZ.R8Sint;case 9:return tZ.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return tZ.RGBA8Sint;default:return tZ.RGBA8Snorm}case 0:switch(t){case 6:return tZ.R8Unorm;case 7:return tZ.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?tZ.RGBA8UnormSRGB:tZ.RGBA8Unorm;case 12:return i?tZ.BGRA8UnormSRGB:tZ.BGRA8Unorm;case 8:return tZ.R8Uint;case 9:return tZ.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return tZ.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 tZ.RGBA8Unorm}case 4:switch(t){case 8:return tZ.R16Sint;case 9:return tZ.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tZ.RGBA16Sint}case 5:switch(t){case 8:return tZ.R16Uint;case 9:return tZ.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tZ.RGBA16Uint}case 6:switch(t){case 8:return tZ.R32Sint;case 9:return tZ.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tZ.RGBA32Sint}case 7:switch(t){case 8:return tZ.R32Uint;case 9:return tZ.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tZ.RGBA32Uint}case 1:switch(t){case 6:return tZ.R32Float;case 7:return tZ.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return tZ.RGBA32Float}case 2:switch(t){case 6:return tZ.R16Float;case 7:return tZ.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return tZ.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return tZ.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 tZ.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 tZ.RGB10A2Unorm;case 11:return tZ.RGB10A2UINT}}return i?tZ.RGBA8UnormSRGB:tZ.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case tZ.R8Unorm:case tZ.R8Snorm:case tZ.R8Uint:case tZ.R8Sint:case tZ.BC4RUnorm:case tZ.BC4RSnorm:case tZ.R16Uint:case tZ.R16Sint:case tZ.Depth16Unorm:case tZ.R16Float:case tZ.R32Uint:case tZ.R32Sint:case tZ.R32Float:case tZ.Depth32Float:case tZ.Stencil8:case tZ.Depth24Plus:case tZ.EACR11Unorm:case tZ.EACR11Snorm:return 1;case tZ.RG8Unorm:case tZ.RG8Snorm:case tZ.RG8Uint:case tZ.RG8Sint:case tZ.Depth32FloatStencil8:case tZ.BC5RGUnorm:case tZ.BC5RGSnorm:case tZ.RG16Uint:case tZ.RG16Sint:case tZ.RG16Float:case tZ.RG32Uint:case tZ.RG32Sint:case tZ.RG32Float:case tZ.Depth24PlusStencil8:case tZ.EACRG11Unorm:case tZ.EACRG11Snorm:return 2;case tZ.RGB9E5UFloat:case tZ.RG11B10UFloat:case tZ.BC6HRGBUFloat:case tZ.BC6HRGBFloat:case tZ.ETC2RGB8Unorm:case tZ.ETC2RGB8UnormSRGB:return 3;case tZ.RGBA8Unorm:case tZ.RGBA8UnormSRGB:case tZ.RGBA8Snorm:case tZ.RGBA8Uint:case tZ.RGBA8Sint:case tZ.BGRA8Unorm:case tZ.BGRA8UnormSRGB:case tZ.RGB10A2UINT:case tZ.RGB10A2Unorm:case tZ.BC7RGBAUnorm:case tZ.BC7RGBAUnormSRGB:case tZ.BC3RGBAUnorm:case tZ.BC3RGBAUnormSRGB:case tZ.BC2RGBAUnorm:case tZ.BC2RGBAUnormSRGB:case tZ.BC1RGBAUnorm:case tZ.BC1RGBAUnormSRGB:case tZ.RGBA16Uint:case tZ.RGBA16Sint:case tZ.RGBA16Float:case tZ.RGBA32Uint:case tZ.RGBA32Sint:case tZ.RGBA32Float:case tZ.ETC2RGB8A1Unorm:case tZ.ETC2RGB8A1UnormSRGB:case tZ.ETC2RGBA8Unorm:case tZ.ETC2RGBA8UnormSRGB:case tZ.ASTC4x4Unorm:case tZ.ASTC4x4UnormSRGB:case tZ.ASTC5x4Unorm:case tZ.ASTC5x4UnormSRGB:case tZ.ASTC5x5Unorm:case tZ.ASTC5x5UnormSRGB:case tZ.ASTC6x5Unorm:case tZ.ASTC6x5UnormSRGB:case tZ.ASTC6x6Unorm:case tZ.ASTC6x6UnormSRGB:case tZ.ASTC8x5Unorm:case tZ.ASTC8x5UnormSRGB:case tZ.ASTC8x6Unorm:case tZ.ASTC8x6UnormSRGB:case tZ.ASTC8x8Unorm:case tZ.ASTC8x8UnormSRGB:case tZ.ASTC10x5Unorm:case tZ.ASTC10x5UnormSRGB:case tZ.ASTC10x6Unorm:case tZ.ASTC10x6UnormSRGB:case tZ.ASTC10x8Unorm:case tZ.ASTC10x8UnormSRGB:case tZ.ASTC10x10Unorm:case tZ.ASTC10x10UnormSRGB:case tZ.ASTC12x10Unorm:case tZ.ASTC12x10UnormSRGB:case tZ.ASTC12x12Unorm:case tZ.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case tZ.Stencil8:case tZ.Depth32FloatStencil8:case tZ.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case tZ.Depth32FloatStencil8:case tZ.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case tZ.Depth16Unorm:return tZ.Depth16Unorm;case tZ.Depth24Plus:case tZ.Depth24PlusStencil8:return tZ.Depth24Plus;case tZ.Depth32Float:case tZ.Depth32FloatStencil8:return tZ.Depth32Float}return e}copyVideoToTexture(e,t,i,r=!1,s){var n,a,o,l;let h=void 0===s,[u,c]=this._getVideoPipeline(i,r?iC.InvertY:iC.DontInvertY);h&&(s=this._device.createCommandEncoder({})),null===(a=(n=s).pushDebugGroup)||void 0===a||a.call(n,`copy video to texture - invertY=${r}`);let d=t._hardwareTexture,p={colorAttachments:[{view:d.underlyingResource.createView({format:i,dimension:t$.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:tQ.All}),loadOp:i_.Load,storeOp:im.Store}]},_=s.beginRenderPass(p),f={layout:c,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},m=this._device.createBindGroup(f);_.setPipeline(u),_.setBindGroup(0,m),_.draw(4,1,0,0),_.end(),null===(l=(o=s).popDebugGroup)||void 0===l||l.call(o),h&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,r,s=!1,n=!1,a=0,o=0,l=1,h=0,u=0,c=0,d=0,p,_){var f,m,g,v,x,T;let S;let C=0!==c,E=void 0===p,[b,y]=this._getPipeline(r,C?iS.InvertYPremultiplyAlphaWithOfst:iS.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:n});if(a=Math.max(a,0),E&&(p=this._device.createCommandEncoder({})),null===(m=(f=p).pushDebugGroup)||void 0===m||m.call(f,`internal process texture - invertY=${s} premultiplyAlpha=${n}`),WebGPUTextureHelper._IsHardwareTexture(e)?(S=e.underlyingResource,s&&!n&&1===l&&0===a||(e=void 0)):(S=e,e=void 0),!S)return;C&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,u,c,d]),0,16);let P=e,R=null!==(g=null==P?void 0:P._copyInvertYTempTexture)&&void 0!==g?g:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,p,tK.CopySrc|tK.RenderAttachment|tK.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),A=null!==(v=null==P?void 0:P._copyInvertYRenderPassDescr)&&void 0!==v?v:{colorAttachments:[{view:R.createView({format:r,dimension:t$.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:i_.Load,storeOp:im.Store}]},I=p.beginRenderPass(A),M=C?null==P?void 0:P._copyInvertYBindGroupWithOfst:null==P?void 0:P._copyInvertYBindGroup;if(!M){let e={layout:y,entries:[{binding:0,resource:S.createView({format:r,dimension:t$.E2d,baseMipLevel:o,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:a})}]};C&&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:S,mipLevel:o,origin:{x:0,y:0,z:a}},{width:t,height:i,depthOrArrayLayers:1}),P?(P._copyInvertYTempTexture=R,P._copyInvertYRenderPassDescr=A,C?P._copyInvertYBindGroupWithOfst=M:P._copyInvertYBindGroup=M):this._deferredReleaseTextures.push([R,null]),null===(T=(x=p).popDebugGroup)||void 0===T||T.call(x),E&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,r){var s,n,a,o;let l=void 0===r,[h,u]=this._getPipeline(t,iS.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});l&&(r=this._device.createCommandEncoder({})),null===(n=(s=r).pushDebugGroup)||void 0===n||n.call(s,"internal copy texture with invertY");let c=r.beginRenderPass(i),d=this._device.createBindGroup({layout:u,entries:[{binding:0,resource:e}]});c.setPipeline(h),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),null===(o=(a=r).popDebugGroup)||void 0===o||o.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,s=!1,n=!1,a=tZ.RGBA8Unorm,o=1,l,h=-1,u=0,c){o>1&&(o=4);let d=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:d},_=az[a]?tK.RenderAttachment:0,f=WebGPUTextureHelper.IsCompressedFormat(a),m=t?WebGPUTextureHelper.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:tK.CopySrc|tK.CopyDst|tK.TextureBinding;u|=t&&!f?tK.CopySrc|_:0,f||n||(u|=_|tK.CopyDst);let v=this._device.createTexture({label:`Texture${n?"3D":"2D"}_${c?c+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${a}_samples${o}`,size:p,dimension:n?tq.E3d:tq.E2d,format:a,usage:g|u,sampleCount:o,mipLevelCount:m});return WebGPUTextureHelper.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,a,0,0,r,s,0,0),t&&i&&this.generateMipmaps(v,a,m,0,l)),v}createCubeTexture(e,t=!1,i=!1,r=!1,s=!1,n=tZ.RGBA8Unorm,a=1,o,l=-1,h=0,u){a>1&&(a=4);let c=WebGPUTextureHelper.IsImageBitmapArray(e)?e[0].width:e.width,d=WebGPUTextureHelper.IsImageBitmapArray(e)?e[0].height:e.height,p=az[n]?tK.RenderAttachment:0,_=WebGPUTextureHelper.IsCompressedFormat(n),f=t?WebGPUTextureHelper.ComputeNumMipmapLevels(c,d):1,m=l>=0?l:tK.CopySrc|tK.CopyDst|tK.TextureBinding;h|=t&&!_?tK.CopySrc|p:0,_||(h|=p|tK.CopyDst);let g=this._device.createTexture({label:`TextureCube_${u?u+"_":""}${c}x${d}x6_${t?"wmips":"womips"}_${n}_samples${a}`,size:{width:c,height:d,depthOrArrayLayers:6},dimension:tq.E2d,format:n,usage:m|h,sampleCount:a,mipLevelCount:f});return WebGPUTextureHelper.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,c,d,n,r,s,0,0),t&&i&&this.generateCubeMipmaps(g,n,f,o)),g}generateCubeMipmaps(e,t,i,r){var s,n,a,o;let l=void 0===r;l&&(r=this._device.createCommandEncoder({})),null===(n=(s=r).pushDebugGroup)||void 0===n||n.call(s,`create cube mipmaps - ${i} levels`);for(let s=0;s<6;++s)this.generateMipmaps(e,t,i,s,r);null===(o=(a=r).popDebugGroup)||void 0===o||o.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,s){var n,a,o,l,h,u,c,d;let p;let _=void 0===s,[f,m]=this._getPipeline(t);if(r=Math.max(r,0),_&&(s=this._device.createCommandEncoder({})),null===(a=(n=s).pushDebugGroup)||void 0===a||a.call(n,`create mipmaps for face #${r} - ${i} levels`),WebGPUTextureHelper._IsHardwareTexture(e)?(p=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(p=e,e=void 0),!p)return;let g=e;for(let e=1;e<i;++e){let i=null!==(l=null===(o=null==g?void 0:g._mipmapGenRenderPassDescr[r])||void 0===o?void 0:o[e-1])&&void 0!==l?l:{colorAttachments:[{view:p.createView({format:t,dimension:t$.E2d,baseMipLevel:e,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:r}),loadOp:i_.Load,storeOp:im.Store}]};g&&(g._mipmapGenRenderPassDescr[r]=g._mipmapGenRenderPassDescr[r]||[],g._mipmapGenRenderPassDescr[r][e-1]=i);let n=s.beginRenderPass(i),a=null!==(u=null===(h=null==g?void 0:g._mipmapGenBindGroup[r])||void 0===h?void 0:h[e-1])&&void 0!==u?u:this._device.createBindGroup({layout:m,entries:[{binding:0,resource:this._mipmapSampler},{binding:1,resource:p.createView({format:t,dimension:t$.E2d,baseMipLevel:e-1,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:r})}]});g&&(g._mipmapGenBindGroup[r]=g._mipmapGenBindGroup[r]||[],g._mipmapGenBindGroup[r][e-1]=a),n.setPipeline(f),n.setBindGroup(0,a),n.draw(4,1,0,0),n.end()}null===(d=(c=s).popDebugGroup)||void 0===d||d.call(c),_&&(this._device.queue.submit([s.finish()]),s=null)}createGPUTextureForInternalTexture(e,t,i,r,s){let n;e._hardwareTexture||(e._hardwareTexture=new WebGPUHardwareTexture),void 0===t&&(t=e.width),void 0===i&&(i=e.height),void 0===r&&(r=e.depth);let a=e._hardwareTexture,o=((null!=s?s:0)&1)!=0;a.format=WebGPUTextureHelper.GetWebGPUTextureFormat(e.type,e.format,e._useSRGBBuffer),a.textureUsages=e._source===r5.S.RenderTarget||e.source===r5.S.MultiRenderTarget?tK.TextureBinding|tK.CopySrc|tK.RenderAttachment:e._source===r5.S.DepthStencil?tK.TextureBinding|tK.RenderAttachment:-1,a.textureAdditionalUsages=o?tK.StorageBinding:0;let l=e.generateMipMaps,h=r||1;if(n=null!==e._maxLodLevel?e._maxLodLevel:l?WebGPUTextureHelper.ComputeNumMipmapLevels(t,i):1,e.isCube){let r=this.createCubeTexture({width:t,height:i},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,a.format,1,this._commandEncoderForCreation,a.textureUsages,a.textureAdditionalUsages,e.label);a.set(r),a.createView({format:WebGPUTextureHelper.GetDepthFormatOnly(a.format),dimension:t$.Cube,mipLevelCount:n,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:6,aspect:WebGPUTextureHelper.HasDepthAndStencilAspects(a.format)?tQ.DepthOnly:tQ.All},o)}else{let r=this.createTexture({width:t,height:i,layers:h},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,e.is3D,a.format,1,this._commandEncoderForCreation,a.textureUsages,a.textureAdditionalUsages,e.label);a.set(r),a.createView({format:WebGPUTextureHelper.GetDepthFormatOnly(a.format),dimension:e.is2DArray?t$.E2dArray:e.is3D?tq.E3d:t$.E2d,mipLevelCount:n,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:e.is3D?1:h,aspect:WebGPUTextureHelper.HasDepthAndStencilAspects(a.format)?tQ.DepthOnly:tQ.All},o)}return e.width=e.baseWidth=t,e.height=e.baseHeight=i,e.depth=e.baseDepth=r,this.createMSAATexture(e,e.samples),a}createMSAATexture(e,t,i=!0,r=-1){let s=e._hardwareTexture;if(i&&(null==s||s.releaseMSAATexture()),!s||(null!=t?t:1)<=1)return;let n=e.width,a=e.height,o=this.createTexture({width:n,height:a,layers:1},!1,!1,!1,!1,!1,s.format,t,this._commandEncoderForCreation,tK.RenderAttachment,0,e.label?"MSAA"+e.label:void 0);s.setMSAATexture(o,r)}updateCubeTextures(e,t,i,r,s,n=!1,a=!1,o=0,l=0){let h=[0,3,1,4,2,5];for(let u=0;u<h.length;++u){let c=e[h[u]];this.updateTexture(c,t,i,r,1,s,u,0,n,a,o,l)}}updateTexture(e,t,i,r,s,n,a=0,o=0,l=!1,h=!1,u=0,c=0,d){let p=WebGPUTextureHelper._IsInternalTexture(t)?t._hardwareTexture.underlyingResource:t,_=WebGPUTextureHelper._GetBlockInformationFromFormat(n),f=WebGPUTextureHelper._IsInternalTexture(t)?t._hardwareTexture:t,m={texture:p,origin:{x:u,y:c,z:Math.max(a,0)},mipLevel:o,premultipliedAlpha:h},g={width:Math.ceil(i/_.width)*_.width,height:Math.ceil(r/_.height)*_.height,depthOrArrayLayers:s||1};if(void 0!==e.byteLength){let v=Math.ceil(i/_.width)*_.length,x=256*Math.ceil(v/256)===v;if(x){let t=this._device.createCommandEncoder({}),i=this._bufferManager.createRawBuffer(e.byteLength,tY.MapWrite|tY.CopySrc,!0,"TempBufferForUpdateTexture"+(p?"_"+p.label:"")),s=i.getMappedRange();new Uint8Array(s).set(e),i.unmap(),t.copyBufferToTexture({buffer:i,offset:0,bytesPerRow:v,rowsPerImage:r},m,g),this._device.queue.submit([t.finish()]),this._bufferManager.releaseBuffer(i)}else this._device.queue.writeTexture(m,e,{offset:0,bytesPerRow:v,rowsPerImage:r},g);if(l||h){if(WebGPUTextureHelper._IsInternalTexture(t)){let e=0===u&&0===c&&i===t.width&&r===t.height;this.invertYPreMultiplyAlpha(f,t.width,t.height,n,l,h,a,o,s||1,u,c,e?0:i,e?0:r,void 0,d)}else throw"updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!"}}else if(l){if(m.premultipliedAlpha=!1,WebGPUTextureHelper._IsInternalTexture(t)&&0===u&&0===c&&i===t.width&&r===t.height)this._device.queue.copyExternalImageToTexture({source:e},m,g),this.invertYPreMultiplyAlpha(f,i,r,n,l,h,a,o,s||1,0,0,0,0,void 0,d);else{let t=this._device.createCommandEncoder({}),u=this.createTexture({width:i,height:r,layers:1},!1,!1,!1,!1,!1,n,1,t,tK.CopySrc|tK.TextureBinding,void 0,"TempTextureForUpdateTexture");this._deferredReleaseTextures.push([u,null]),g.depthOrArrayLayers=1,this._device.queue.copyExternalImageToTexture({source:e},{texture:u},g),g.depthOrArrayLayers=s||1,this.invertYPreMultiplyAlpha(u,i,r,n,l,h,a,o,s||1,0,0,0,0,t,d),t.copyTextureToTexture({texture:u},m,g),this._device.queue.submit([t.finish()])}}else this._device.queue.copyExternalImageToTexture({source:e},m,g)}readPixels(e,t,i,r,s,n,a=0,o=0,l=null,h=!1){let u=WebGPUTextureHelper._GetBlockInformationFromFormat(n),c=Math.ceil(r/u.width)*u.length,d=256*Math.ceil(c/256),p=d*s,_=this._bufferManager.createRawBuffer(p,tY.MapRead|tY.CopyDst,void 0,"TempBufferForReadPixels"+(e.label?"_"+e.label:"")),f=this._device.createCommandEncoder({});return f.copyTextureToBuffer({texture:e,mipLevel:o,origin:{x:t,y:i,z:Math.max(a,0)}},{buffer:_,offset:0,bytesPerRow:d},{width:r,height:s,depthOrArrayLayers:1}),this._device.queue.submit([f.finish()]),this._bufferManager.readDataFromBuffer(_,p,r,s,c,d,WebGPUTextureHelper._GetTextureTypeFromFormat(n),0,l,!0,h)}releaseTexture(e){if(WebGPUTextureHelper._IsInternalTexture(e)){let t=e._hardwareTexture,i=e._irradianceTexture;this._deferredReleaseTextures.push([t,i])}else this._deferredReleaseTextures.push([e,null])}destroyDeferredTextures(){for(let e=0;e<this._deferredReleaseTextures.length;++e){let[t,i]=this._deferredReleaseTextures[e];t&&(WebGPUTextureHelper._IsHardwareTexture(t)?t.release():t.destroy()),null==i||i.dispose()}this._deferredReleaseTextures.length=0}};let WebGPUDataBuffer=class WebGPUDataBuffer extends sI.h{constructor(e,t=0){super(),this.capacity=t,this._buffer=e}get underlyingResource(){return this._buffer}};let WebGPUBufferManager=class WebGPUBufferManager{static _IsGPUBuffer(e){return void 0===e.underlyingResource}static _FlagsToString(e,t=""){let i=t;for(let t=0;t<=9;++t)e&1<<t&&(i&&(i+="_"),i+=tY[1<<t]);return i}constructor(e){this._deferredReleaseBuffers=[],this._device=e}createRawBuffer(e,t,i=!1,r){let s=void 0!==e.byteLength?e.byteLength+3&-4:e+3&-4,n={label:WebGPUBufferManager._FlagsToString(t,null!=r?r:"Buffer")+"_size"+s,mappedAtCreation:i,size:s,usage:t};return this._device.createBuffer(n)}createBuffer(e,t,i){let r=void 0!==e.byteLength,s=this.createRawBuffer(e,t,void 0,i),n=new WebGPUDataBuffer(s);return n.references=1,n.capacity=r?e.byteLength:e,r&&this.setSubData(n,0,e),n}setRawData(e,t,i,r,s){this._device.queue.writeBuffer(e,t,i.buffer,r,s)}setSubData(e,t,i,r=0,s=0){let n=e.underlyingResource;s=Math.min(s=s||i.byteLength,e.capacity-t);let a=i.byteOffset+r,o=a+s,l=s+3&-4;if(l!==s){let e=new Uint8Array(i.buffer.slice(a,o));(i=new Uint8Array(l)).set(e),r=0,a=0,o=l,s=l}let h=0;for(;o-(a+h)>15728640;)this._device.queue.writeBuffer(n,t+h,i.buffer,a+h,15728640),h+=15728640;this._device.queue.writeBuffer(n,t+h,i.buffer,a+h,s-h)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));let r=new Uint16Array(t);for(;e--;)i[e]=FromHalfFloat(r[e]);return i}readDataFromBuffer(e,t,i,r,s,n,a=0,o=0,l=null,h=!0,u=!1){let c=1===a?2:2===a?1:0;return new Promise((i,d)=>{e.mapAsync(tj.Read,o,t).then(()=>{let d=e.getMappedRange(o,t),p=l;if(u)p=null===p?(0,at.A)(a,t,!0,d):(0,at.A)(a,p.buffer,void 0,d);else if(null===p)switch(c){case 0:(p=new Uint8Array(t)).set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:(p=new Float32Array(t/4)).set(new Float32Array(d))}else switch(c){case 0:(p=new Uint8Array(p.buffer)).set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:(p=new Float32Array(p.buffer)).set(new Float32Array(d))}if(s!==n){1!==c||u||(s*=2,n*=2);let e=new Uint8Array(p.buffer),t=s,i=0;for(let a=1;a<r;++a){i=a*n;for(let r=0;r<s;++r)e[t++]=e[i++]}p=0===c||u?new Uint8Array(e.buffer,0,t):new Float32Array(e.buffer,0,t/4)}e.unmap(),h&&this.releaseBuffer(e),i(p)},e=>d(e))})}releaseBuffer(e){return WebGPUBufferManager._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e<this._deferredReleaseBuffers.length;++e)this._deferredReleaseBuffers[e].destroy();this._deferredReleaseBuffers.length=0}};let WebGPURenderPassWrapper=class WebGPURenderPassWrapper{constructor(){this.colorAttachmentGPUTextures=[],this.reset()}reset(e=!1){this.renderPass=null,e&&(this.renderPassDescriptor=null,this.colorAttachmentViewDescriptor=null,this.depthAttachmentViewDescriptor=null,this.colorAttachmentGPUTextures=[],this.depthTextureFormat=void 0)}};let aW=[0,0,3,7,0,2,6,2,4,1,5,3,1],aH=[0,64,32,96,16,80,48,112,8],aX=[0,128,128,0,0,0,0,128,0,0,0,0,128];let WebGPUCacheSampler=class WebGPUCacheSampler{constructor(e){this._samplers={},this._device=e,this.disabled=!1}static GetSamplerHashCode(e){var t,i,r;let s=e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,n=aW[e.samplingMode]+aH[(e._comparisonFunction||514)-512+1]+aX[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(r=e._cachedWrapR)&&void 0!==r?r:1)<<12)+((e.useMipMaps?1:0)<<14)+(s<<15);return n}static _GetSamplerFilterDescriptor(e,t){let i,r,s,n,a;let o=e.useMipMaps;switch(e.samplingMode){case 11:i=t0.Linear,r=t0.Linear,s=t0.Nearest,o||(n=a=0);break;case 3:case 3:i=t0.Linear,r=t0.Linear,o?s=t0.Linear:(s=t0.Nearest,n=a=0);break;case 8:i=t0.Nearest,r=t0.Nearest,o?s=t0.Linear:(s=t0.Nearest,n=a=0);break;case 4:i=t0.Nearest,r=t0.Nearest,s=t0.Nearest,o||(n=a=0);break;case 5:i=t0.Nearest,r=t0.Linear,s=t0.Nearest,o||(n=a=0);break;case 6:i=t0.Nearest,r=t0.Linear,o?s=t0.Linear:(s=t0.Nearest,n=a=0);break;case 7:i=t0.Nearest,r=t0.Linear,s=t0.Nearest,n=a=0;break;case 1:case 1:default:i=t0.Nearest,r=t0.Nearest,s=t0.Nearest,n=a=0;break;case 9:i=t0.Linear,r=t0.Nearest,s=t0.Nearest,o||(n=a=0);break;case 10:i=t0.Linear,r=t0.Nearest,o?s=t0.Linear:(s=t0.Nearest,n=a=0);break;case 2:case 2:i=t0.Linear,r=t0.Linear,s=t0.Nearest,n=a=0;break;case 12:i=t0.Linear,r=t0.Nearest,s=t0.Nearest,n=a=0}return t>1&&(0!==n||0!==a)&&s!==t0.Nearest?{magFilter:t0.Linear,minFilter:t0.Linear,mipmapFilter:t0.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:s,lodMinClamp:n,lodMaxClamp:a}}static _GetWrappingMode(e){switch(e){case 1:break;case 0:return tJ.ClampToEdge;case 2:return tJ.MirrorRepeat}return tJ.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e){let 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?WebGPUCacheSampler.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:i.anisotropyEnabled?t:1})}static GetCompareFunction(e){switch(e){case 519:return t2.Always;case 514:return t2.Equal;case 516:return t2.Greater;case 518:return t2.GreaterEqual;case 513:default:return t2.Less;case 515:return t2.LessEqual;case 512:return t2.Never;case 517:return t2.NotEqual}}getSampler(e,t=!1,i=0){if(this.disabled)return this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(e));t?i=0:0===i&&(i=WebGPUCacheSampler.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(e)),t||(this._samplers[i]=r)),r}};(eE=iE||(iE={}))[eE.StencilReadMask=0]="StencilReadMask",eE[eE.StencilWriteMask=1]="StencilWriteMask",eE[eE.DepthBias=2]="DepthBias",eE[eE.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",eE[eE.DepthStencilState=4]="DepthStencilState",eE[eE.MRTAttachments1=5]="MRTAttachments1",eE[eE.MRTAttachments2=6]="MRTAttachments2",eE[eE.RasterizationState=7]="RasterizationState",eE[eE.ColorStates=8]="ColorStates",eE[eE.ShaderStage=9]="ShaderStage",eE[eE.TextureStage=10]="TextureStage",eE[eE.VertexState=11]="VertexState",eE[eE.NumStates=12]="NumStates";let aY={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},aj={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},aq={[rz.o.PositionKind]:!0,[rz.o.NormalKind]:!0,[rz.o.TangentKind]:!0,[rz.o.UVKind]:!0,[rz.o.UV2Kind]:!0,[rz.o.UV3Kind]:!0,[rz.o.UV4Kind]:!0,[rz.o.UV5Kind]:!0,[rz.o.UV6Kind]:!0,[rz.o.ColorKind]:!0,[rz.o.ColorInstanceKind]:!0,[rz.o.MatricesIndicesKind]:!0,[rz.o.MatricesWeightsKind]:!0,[rz.o.MatricesIndicesExtraKind]:!0,[rz.o.MatricesWeightsExtraKind]:!0};let WebGPUCacheRenderPipeline=class WebGPUCacheRenderPipeline{static _IsSignedType(e){switch(e){case rz.o.BYTE:case rz.o.SHORT:case rz.o.INT:case rz.o.FLOAT:return!0;case rz.o.UNSIGNED_BYTE:case rz.o.UNSIGNED_SHORT:case rz.o.UNSIGNED_INT:return!1;default:throw Error(`Invalid type '${e}'`)}}constructor(e,t,i){this.mrtTextureCount=0,this._device=e,this._useTextureStage=i,this._states=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=[tZ.BGRA8Unorm],this.setColorFormat(tZ.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(tZ.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,r=0){if(i>1&&(i=4),this.disabled){let s=WebGPUCacheRenderPipeline._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,s,i),WebGPUCacheRenderPipeline.NumCacheMiss++,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,WebGPUCacheRenderPipeline.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return WebGPUCacheRenderPipeline.NumCacheHitWithHash++,this._parameter.pipeline;let s=WebGPUCacheRenderPipeline._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),WebGPUCacheRenderPipeline.NumCacheMiss++,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame=WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,s,n,a,o){this._depthWriteEnabled=a,this._depthTestEnabled=n,this._depthCompare=(null!=o?o:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[iE.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[iE.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=az[null!=e?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i<e.length;++i)0!==e[i]&&(t+=1<<i);this._mrtEnabledMask!==t&&(this._mrtEnabledMask=t,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.MRTAttachments1))}setMRT(e,t){var i,r;if((t=null!=t?t:e.length)>10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;let s=[0,0],n=0,a=0,o=0;for(let l=0;l<t;++l){let t=e[l],h=null==t?void 0:t._hardwareTexture;this._mrtFormats[o]=null!==(i=null==h?void 0:h.format)&&void 0!==i?i:this._webgpuColorFormat[0],s[n]+=az[null!==(r=this._mrtFormats[o])&&void 0!==r?r:""]<<a,a+=6,o++,a>=32&&(a=0,n++)}this._mrtFormats.length=o,(this._mrtAttachments1!==s[0]||this._mrtAttachments2!==s[1])&&(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[iE.MRTAttachments1]=s[0],this._states[iE.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.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:az[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:aj[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:aj[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:aj[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[iE.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[iE.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,s,n,a){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:519)-512,this._stencilFrontDepthFailOp=null===i?1:aj[i],this._stencilFrontPassOp=null===r?2:aj[r],this._stencilFrontFailOp=null===s?1:aj[s],this.setStencilReadMask(n),this.setStencilWriteMask(a)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return it.TriangleList;case 2:case 3:return it.PointList;case 1:case 4:return it.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return it.LineStrip;case 7:return it.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return io.Add;case 32778:return io.Subtract;case 32779:return io.ReverseSubtract;case 32775:return io.Min;case 32776:return io.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return ia.Zero;case 1:default:return ia.One;case 768:return ia.Src;case 769:return ia.OneMinusSrc;case 770:return ia.SrcAlpha;case 771:return ia.OneMinusSrcAlpha;case 772:return ia.DstAlpha;case 773:return ia.OneMinusDstAlpha;case 774:return ia.Dst;case 775:return ia.OneMinusDst;case 776:return ia.SrcAlphaSaturated;case 32769:case 32771:return ia.Constant;case 32770:case 32772:return ia.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:break;case 1:return t2.Less;case 2:return t2.Equal;case 3:return t2.LessEqual;case 4:return t2.Greater;case 5:return t2.NotEqual;case 6:return t2.GreaterEqual;case 7:return t2.Always}return t2.Never}static _GetStencilOpFunction(e){switch(e){case 0:return il.Zero;case 1:break;case 2:return il.Replace;case 3:return il.IncrementClamp;case 4:return il.DecrementClamp;case 5:return il.Invert;case 6:return il.IncrementWrap;case 7:return il.DecrementWrap}return il.Keep}static _GetVertexInputDescriptorFormat(e){let t=e.type,i=e.normalized,r=e.getSize();switch(t){case rz.o.BYTE:switch(r){case 1:case 2:return i?iu.Snorm8x2:iu.Sint8x2;case 3:case 4:return i?iu.Snorm8x4:iu.Sint8x4}break;case rz.o.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?iu.Unorm8x2:iu.Uint8x2;case 3:case 4:return i?iu.Unorm8x4:iu.Uint8x4}break;case rz.o.SHORT:switch(r){case 1:case 2:return i?iu.Snorm16x2:iu.Sint16x2;case 3:case 4:return i?iu.Snorm16x4:iu.Sint16x4}break;case rz.o.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?iu.Unorm16x2:iu.Uint16x2;case 3:case 4:return i?iu.Unorm16x4:iu.Uint16x4}break;case rz.o.INT:switch(r){case 1:return iu.Sint32;case 2:return iu.Sint32x2;case 3:return iu.Sint32x3;case 4:return iu.Sint32x4}break;case rz.o.UNSIGNED_INT:switch(r){case 1:return iu.Uint32;case 2:return iu.Uint32x2;case 3:return iu.Uint32x3;case 4:return iu.Uint32x4}break;case rz.o.FLOAT:switch(r){case 1:return iu.Float32;case 2:return iu.Float32x2;case 3:return iu.Float32x3;case 4:return iu.Float32x4}}throw Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[iE.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.ShaderStage))}_setRasterizationState(e,t){let i=this._frontFace,r=this._cullEnabled?this._cullFace:0,s=this._clampDepth?1:0,n=this._alphaToCoverageEnabled?1:0,a=i-1+(r<<1)+(s<<3)+(n<<4)+(e<<5)+(t<<8);this._rasterizationState!==a&&(this._rasterizationState=a,this._states[iE.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.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:aY[this._alphaBlendFuncParams[0]])<<0)+((null===this._alphaBlendFuncParams[1]?2:aY[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:aY[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:aY[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[iE.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.ColorStates))}_setDepthStencilState(){let 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[iE.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.DepthStencilState))}_setVertexState(e){var t,i;let r;let s=this._statesLength,n=iE.VertexState,a=e._pipelineContext,o=a.shaderProcessingContext.attributeNamesFromEffect,l=a.shaderProcessingContext.attributeLocationsFromEffect,h=0;for(let e=0;e<o.length;e++){let s=l[e],a=null!==(t=this._overrideVertexBuffers&&this._overrideVertexBuffers[o[e]])&&void 0!==t?t:this._vertexBuffers[o[e]];a||(a=this._emptyVertexBuffer);let u=null===(i=a.effectiveBuffer)||void 0===i?void 0:i.underlyingResource;if(void 0===a._validOffsetRange){let e=a.effectiveByteOffset,t=a.getSize(!0),i=a.effectiveByteStride;a._validOffsetRange=e+t<=this._kMaxVertexBufferStride&&0===i||0!==i&&e+t<=i}r&&r===u&&a._validOffsetRange||(this.vertexBuffers[h++]=a,r=a._validOffsetRange?u:null);let c=a.hashCode+(s<<7);this._isDirty=this._isDirty||this._states[n]!==c,this._states[n++]=c}this.vertexBuffers.length=h,this._statesLength=n,this._isDirty=this._isDirty||n!==s,this._isDirty&&(this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.VertexState))}_setTextureState(e){this._textureState!==e&&(this._textureState=e,this._states[iE.TextureStage]=this._textureState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.TextureStage))}_createPipelineLayout(e){if(this._useTextureStage)return this._createPipelineLayoutWithTextureStage(e);let t=[],i=e.shaderProcessingContext.bindGroupLayoutEntries;for(let e=0;e<i.length;e++){let r=i[e];t[e]=this._device.createBindGroupLayout({entries:r})}return e.bindGroupLayouts[0]=t,this._device.createPipelineLayout({bindGroupLayouts:t})}_createPipelineLayoutWithTextureStage(e){var t;let i=e.shaderProcessingContext,r=i.bindGroupLayoutEntries,s=1;for(let e=0;e<r.length;e++){let n=r[e];for(let a=0;a<n.length;a++){let n=r[e][a];if(n.texture){let a=i.bindGroupLayoutEntryInfo[e][n.binding].name,o=i.availableTextures[a],l=o.autoBindSampler?i.availableSamplers[a+WebGPUShaderProcessor.AutoSamplerSuffix]:null,h=o.sampleType,u=null!==(t=null==l?void 0:l.type)&&void 0!==t?t:t5.Filtering;if(this._textureState&s&&h!==t6.Depth&&(o.autoBindSampler&&(u=t5.NonFiltering),h=t6.UnfilterableFloat),n.texture.sampleType=h,l){let e=i.bindGroupLayoutEntryInfo[l.binding.groupIndex][l.binding.bindingIndex].index;r[l.binding.groupIndex][e].sampler.type=u}s<<=1}}}let n=[];for(let e=0;e<r.length;++e)n[e]=this._device.createBindGroupLayout({entries:r[e]});return e.bindGroupLayouts[this._textureState]=n,this._device.createPipelineLayout({bindGroupLayouts:n})}_getVertexInputDescriptor(e){var t,i;let r,s;let n=[],a=e._pipelineContext,o=a.shaderProcessingContext.attributeNamesFromEffect,l=a.shaderProcessingContext.attributeLocationsFromEffect;for(let e=0;e<o.length;e++){let a=l[e],h=null!==(t=this._overrideVertexBuffers&&this._overrideVertexBuffers[o[e]])&&void 0!==t?t:this._vertexBuffers[o[e]];h||(h=this._emptyVertexBuffer);let u=null===(i=h.effectiveBuffer)||void 0===i?void 0:i.underlyingResource,c=h.effectiveByteOffset,d=!h._validOffsetRange;if(!(r&&s&&r===u)||d){let e={arrayStride:h.effectiveByteStride,stepMode:h.getIsInstanced()?ic.Instance:ic.Vertex,attributes:[]};n.push(e),s=e.attributes,d&&(c=0,u=null)}s.push({shaderLocation:a,offset:c,format:WebGPUCacheRenderPipeline._GetVertexInputDescriptorFormat(h)}),r=u}return n}_processNonFloatVertexBuffers(e,t){let i=e.engine._getShaderProcessor(e.shaderProcessingContext.shaderLanguage),r=!1;for(let t in this._vertexBuffers){let s=this._vertexBuffers[t];if(!s||!aq[t])continue;let n=s.normalized?rz.o.FLOAT:s.type,a=e.vertexBufferKindToType[t];(n!==rz.o.FLOAT&&void 0===a||void 0!==a&&a!==n)&&(r=!0,e.vertexBufferKindToType[t]=n,n!==rz.o.FLOAT&&(i.vertexBufferKindToNumberOfComponents[t]=rz.o.DeduceStride(t),WebGPUCacheRenderPipeline._IsSignedType(n)&&(i.vertexBufferKindToNumberOfComponents[t]*=-1)))}r&&t._processShaderCode(i,!0)}_createRenderPipeline(e,t,i){var r,s,n;let a;let o=e._pipelineContext,l=this._getVertexInputDescriptor(e),h=this._createPipelineLayout(o),u=[],c=this._getAphaBlendState(),d=this._getColorBlendState();if(this._processNonFloatVertexBuffers(o,e),this._mrtAttachments1>0)for(let e=0;e<this._mrtFormats.length;++e){let t=this._mrtFormats[e];if(t){let i={format:t,writeMask:(this._mrtEnabledMask&1<<e)!=0?this._writeMask:0};c&&d&&(i.blend={alpha:c,color:d}),u.push(i)}else u.push(null)}else if(this._webgpuColorFormat[0]){let e={format:this._webgpuColorFormat[0],writeMask:this._writeMask};c&&d&&(e.blend={alpha:c,color:d}),u.push(e)}else u.push(null);let p={compare:WebGPUCacheRenderPipeline._GetCompareFunction(this._stencilEnabled?this._stencilFrontCompare:7),depthFailOp:WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontDepthFailOp:1),failOp:WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontFailOp:1),passOp:WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontPassOp:1)};(t===it.LineStrip||t===it.TriangleStrip)&&(a=!this._indexBuffer||this._indexBuffer.is32Bits?ih.Uint32:ih.Uint16);let _=!!this._webgpuDepthStencilFormat&&WebGPUTextureHelper.HasStencilAspect(this._webgpuDepthStencilFormat);return this._device.createRenderPipeline({label:`RenderPipeline_${null!==(s=null===(r=u[0])||void 0===r?void 0:r.format)&&void 0!==s?s:"nooutput"}_${null!==(n=this._webgpuDepthStencilFormat)&&void 0!==n?n:"nodepth"}_samples${i}_textureState${this._textureState}`,layout:h,vertex:{module:o.stages.vertexStage.module,entryPoint:o.stages.vertexStage.entryPoint,buffers:l},primitive:{topology:t,stripIndexFormat:a,frontFace:1===this._frontFace?ii.CCW:ii.CW,cullMode:this._cullEnabled?2===this._cullFace?ir.Front:ir.Back:ir.None},fragment:o.stages.fragmentStage?{module:o.stages.fragmentStage.module,entryPoint:o.stages.fragmentStage.entryPoint,targets:u}:void 0,multisample:{count:i},depthStencil:void 0===this._webgpuDepthStencilFormat?void 0:{depthWriteEnabled:this._depthWriteEnabled,depthCompare:this._depthTestEnabled?WebGPUCacheRenderPipeline._GetCompareFunction(this._depthCompare):t2.Always,format:this._webgpuDepthStencilFormat,stencilFront:this._stencilEnabled&&_?p:void 0,stencilBack:this._stencilEnabled&&_?p:void 0,stencilReadMask:this._stencilEnabled&&_?this._stencilReadMask:void 0,stencilWriteMask:this._stencilEnabled&&_?this._stencilWriteMask:void 0,depthBias:this._depthBias,depthBiasClamp:this._depthBiasClamp,depthBiasSlopeScale:this._depthBiasSlopeScale}})}};WebGPUCacheRenderPipeline.NumCacheHitWithoutHash=0,WebGPUCacheRenderPipeline.NumCacheHitWithHash=0,WebGPUCacheRenderPipeline.NumCacheMiss=0,WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame=0,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame=0;let NodeState=class NodeState{constructor(){this.values={}}count(){let e=0,t=this.pipeline?1:0;for(let i in this.values){let r=this.values[i],[s,n]=r.count();e+=s,t+=n,e++}return[e,t]}};let WebGPUCacheRenderPipelineTree=class WebGPUCacheRenderPipelineTree extends WebGPUCacheRenderPipeline{static GetNodeCounts(){let e=WebGPUCacheRenderPipelineTree._Cache.count();return{nodeCount:e[0],pipelineCount:e[1]}}static _GetPipelines(e,t,i,r){if(e.pipeline){let e=i.slice();e.length=r,t.push(e)}for(let s in e.values){let n=e.values[s];i[r]=parseInt(s),WebGPUCacheRenderPipelineTree._GetPipelines(n,t,i,r+1)}}static GetPipelines(){let e=[];return WebGPUCacheRenderPipelineTree._GetPipelines(WebGPUCacheRenderPipelineTree._Cache,e,[],0),e}constructor(e,t,i){super(e,t,i),this._nodeStack=[],this._nodeStack[0]=WebGPUCacheRenderPipelineTree._Cache}_getRenderPipeline(e){let t=this._nodeStack[this._stateDirtyLowestIndex];for(let e=this._stateDirtyLowestIndex;e<this._statesLength;++e){let i=t.values[this._states[e]];i||(i=new NodeState,t.values[this._states[e]]=i),t=i,this._nodeStack[e+1]=t}e.token=t,e.pipeline=t.pipeline}_setRenderPipeline(e){e.token.pipeline=e.pipeline}};WebGPUCacheRenderPipelineTree._Cache=new NodeState;var aK=i(5122);let WebGPUStencilStateComposer=class WebGPUStencilStateComposer extends aK.C{constructor(e){super(!1),this._cache=e,this.reset()}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._cache.setStencilCompare(e))}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._cache.setStencilReadMask(e))}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._cache.setStencilFailOp(e))}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._cache.setStencilDepthFailOp(e))}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._cache.setStencilPassOp(e))}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._cache.setStencilWriteMask(e))}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._cache.setStencilEnabled(e))}reset(){super.reset(),this._cache.resetStencilState()}apply(){var e;let t=null===(e=this.stencilMaterial)||void 0===e?void 0:e.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.enabled&&(this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask)}};var a$=i(7987);let WebGPUDepthCullingState=class WebGPUDepthCullingState extends a$.k{constructor(e){super(!1),this._cache=e,this.reset()}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0,this._cache.setDepthBiasSlopeScale(e))}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0,this._cache.setDepthBias(e))}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0,this._cache.setCullFace(null!=e?e:1))}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0,this._cache.setCullEnabled(!!e))}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0,this._cache.setDepthCompare(e))}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0,this._cache.setDepthWriteEnabled(e))}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0,this._cache.setDepthTestEnabled(e))}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0,this._cache.setFrontFace(null!=e?e:2))}reset(){super.reset(),this._cache.resetDepthCullingState()}apply(){}};let ExternalTexture=class ExternalTexture{static IsExternalTexture(e){return void 0!==e.underlyingResource}getClassName(){return"ExternalTexture"}get underlyingResource(){return this._video}constructor(e){this.useMipMaps=!1,this.type=16,this._video=e,this.uniqueId=r5.l._Counter++}isReady(){return this._video.readyState>=this._video.HAVE_CURRENT_DATA}dispose(){}};let WebGPUMaterialContext=class WebGPUMaterialContext{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatTextures(){return this._numFloatTextures>0}constructor(){this.uniqueId=WebGPUMaterialContext._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],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?WebGPUCacheSampler.GetSamplerHashCode(t):0;let s=r!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var i,r,s;let n=this.textures[e],a=-1;n?a=null!==(r=null===(i=n.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==r?r:-1:this.textures[e]=n={texture:t,isFloatTexture:!1,isExternalTexture:!1},n.isExternalTexture&&this._numExternalTextures--,n.isFloatTexture&&this._numFloatTextures--,t?(n.isFloatTexture=1===t.type,n.isExternalTexture=ExternalTexture.IsExternalTexture(t),n.isFloatTexture&&this._numFloatTextures++,n.isExternalTexture&&this._numExternalTextures++):(n.isFloatTexture=!1,n.isExternalTexture=!1),n.texture=t;let o=a!==(null!==(s=null==t?void 0:t.uniqueId)&&void 0!==s?s:-1);o&&this.updateId++,this.isDirty||(this.isDirty=o)}};WebGPUMaterialContext._Counter=0;let WebGPUDrawContext=class WebGPUDrawContext{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,tY.CopyDst|tY.Indirect|tY.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=WebGPUDrawContext._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}};WebGPUDrawContext._Counter=0;let WebGPUBindGroupCacheNode=class WebGPUBindGroupCacheNode{constructor(){this.values={}}};let WebGPUCacheBindGroups=class WebGPUCacheBindGroups{static get Statistics(){return{totalCreated:WebGPUCacheBindGroups.NumBindGroupsCreatedTotal,lastFrameCreated:WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame,lookupLastFrame:WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame,noLookupLastFrame:WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame=WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame,WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame=WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame,WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame=WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var r,s,n,a,o,l,h,u,c,d;let p;let _=WebGPUCacheBindGroups._Cache,f=this.disabled||i.forceBindGroupCreation;if(!f){if(!t.isDirty(i.updateId)&&!i.isDirty)return WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(let i of e.shaderProcessingContext.bufferNames){let e=null!==(s=null===(r=t.buffers[i])||void 0===r?void 0:r.uniqueId)&&void 0!==s?s:0,n=_.values[e];n||(n=new WebGPUBindGroupCacheNode,_.values[e]=n),_=n}for(let t of e.shaderProcessingContext.samplerNames){let e=null!==(a=null===(n=i.samplers[t])||void 0===n?void 0:n.hashCode)&&void 0!==a?a:0,r=_.values[e];r||(r=new WebGPUBindGroupCacheNode,_.values[e]=r),_=r}for(let t of e.shaderProcessingContext.textureNames){let e=null!==(h=null===(l=null===(o=i.textures[t])||void 0===o?void 0:o.texture)||void 0===l?void 0:l.uniqueId)&&void 0!==h?h:0,r=_.values[e];r||(r=new WebGPUBindGroupCacheNode,_.values[e]=r),_=r}p=_.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,p)return t.bindGroups=p,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame++,p;p=[],t.bindGroups=p,f||(_.bindGroups=p),WebGPUCacheBindGroups.NumBindGroupsCreatedTotal++,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame++;let m=e.bindGroupLayouts[i.textureState];for(let r=0;r<e.shaderProcessingContext.bindGroupLayoutEntries.length;r++){let s=e.shaderProcessingContext.bindGroupLayoutEntries[r],n=e.shaderProcessingContext.bindGroupEntries[r];for(let a=0;a<s.length;a++){let s=e.shaderProcessingContext.bindGroupLayoutEntries[r][a],o=e.shaderProcessingContext.bindGroupLayoutEntryInfo[r][s.binding],l=null!==(u=o.nameInArrayOfTexture)&&void 0!==u?u:o.name;if(s.sampler){let e=i.samplers[l];if(e){let t=e.sampler;if(!t){this._engine.dbgSanityChecks&&rT.Y.Error(`Trying to bind a null sampler! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=this._cacheSampler.getSampler(t,!1,e.hashCode)}else rT.Y.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(s.texture||s.storageTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){rT.Y.Error(`Trying to bind a null texture! entry=${JSON.stringify(s)}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||s.texture&&!t.view||s.storageTexture&&!t.viewForWriting)){rT.Y.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, isReady=${null===(c=e.texture)||void 0===c?void 0:c.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=s.storageTexture?t.viewForWriting:t.view}else rT.Y.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(s.externalTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){rT.Y.Error(`Trying to bind a null external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){rT.Y.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, isReady=${null===(d=e.texture)||void 0===d?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=this._device.importExternalTexture({source:t})}else rT.Y.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(s.buffer){let e=t.buffers[l];if(e){let t=e.underlyingResource;n[a].resource.buffer=t,n[a].resource.size=e.capacity}else rT.Y.Error(`Can't find buffer "${l}". entry=${JSON.stringify(s)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}let a=m[r];p[r]=this._device.createBindGroup({layout:a,entries:n})}return p}};WebGPUCacheBindGroups.NumBindGroupsCreatedTotal=0,WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame=0,WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame=0,WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame=0,WebGPUCacheBindGroups._Cache=new WebGPUBindGroupCacheNode,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame=0;let aQ=`uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0), +vec2(1.0,1.0), +vec2(-1.0,-1.0), +vec2(1.0,-1.0)}; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +gl_Position=vec4(pos[gl_VertexID],depthValue,1.0); +#define CUSTOM_VERTEX_MAIN_END +} +`;s_.v.ShadersStore.clearQuadVertexShader=aQ;let aZ=`uniform vec4 color;void main() {gl_FragColor=color;} +`;s_.v.ShadersStore.clearQuadPixelShader=aZ;let WebGPUClearQuad=class WebGPUClearQuad{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 WebGPUCacheRenderPipelineTree(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,r,s=1){var n,a;let o,l;let h=null,u=!!this._engine._currentRenderTarget;if(e)o=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t<this._cacheRenderPipeline.colorFormats.length;++t)this._keyTemp[e++]=az[null!==(n=this._cacheRenderPipeline.colorFormats[t])&&void 0!==n?n:""];let c=az[null!==(a=this._depthTextureFormat)&&void 0!==a?a:0];if(this._keyTemp[e]=(t?t.r+256*t.g+65536*t.b+16777216*t.a:0)+(i?4294967296:0)+(r?8589934592:0)+(this._engine.useReverseDepthBuffer?17179869184:0)+(u?34359738368:0)+(s>1?68719476736:0)+137438953472*c,l=this._keyTemp.join("_"),h=this._bundleCache[l])return h;o=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:s})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&WebGPUTextureHelper.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);let c=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),d=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),d.uniformBuffer.update();let p=u?this._engine._ubInvertY:this._engine._ubDontInvertY,_=d.uniformBuffer.getBuffer(),f=_.uniqueId+"-"+p.uniqueId,m=this._bindGroups[f];if(!m){let e=d.bindGroupLayouts[0];(m=this._bindGroups[f]=[]).push(this._device.createBindGroup({layout:e[0],entries:[]})),WebGPUShaderProcessingContext._SimplifiedKnownBindings||m.push(this._device.createBindGroup({layout:e[1],entries:[]})),m.push(this._device.createBindGroup({layout:e[WebGPUShaderProcessingContext._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:p.underlyingResource,size:p.capacity}},{binding:1,resource:{buffer:_.underlyingResource,size:_.capacity}}]}))}o.setPipeline(c);for(let e=0;e<m.length;++e)o.setBindGroup(e,m[e]);return o.draw(4,1,0,0),e||(h=o.finish(),this._bundleCache[l]=h),h}};let WebGPURenderItemViewport=class WebGPURenderItemViewport{constructor(e,t,i,r){this.x=Math.floor(e),this.y=Math.floor(t),this.w=Math.floor(i),this.h=Math.floor(r)}run(e){e.setViewport(this.x,this.y,this.w,this.h,0,1)}clone(){return new WebGPURenderItemViewport(this.x,this.y,this.w,this.h)}};let WebGPURenderItemScissor=class WebGPURenderItemScissor{constructor(e,t,i,r){this.x=e,this.y=t,this.w=i,this.h=r}run(e){e.setScissorRect(this.x,this.y,this.w,this.h)}clone(){return new WebGPURenderItemScissor(this.x,this.y,this.w,this.h)}};let WebGPURenderItemStencilRef=class WebGPURenderItemStencilRef{constructor(e){this.ref=e}run(e){e.setStencilReference(this.ref)}clone(){return new WebGPURenderItemStencilRef(this.ref)}};let WebGPURenderItemBlendColor=class WebGPURenderItemBlendColor{constructor(e){this.color=e}run(e){e.setBlendConstant(this.color)}clone(){return new WebGPURenderItemBlendColor(this.color)}};let WebGPURenderItemBeginOcclusionQuery=class WebGPURenderItemBeginOcclusionQuery{constructor(e){this.query=e}run(e){e.beginOcclusionQuery(this.query)}clone(){return new WebGPURenderItemBeginOcclusionQuery(this.query)}};let WebGPURenderItemEndOcclusionQuery=class WebGPURenderItemEndOcclusionQuery{constructor(){}run(e){e.endOcclusionQuery()}clone(){return new WebGPURenderItemEndOcclusionQuery}};let WebGPURenderItemBundles=class WebGPURenderItemBundles{constructor(){this.bundles=[]}run(e){e.executeBundles(this.bundles)}clone(){let e=new WebGPURenderItemBundles;return e.bundles=this.bundles,e}};let WebGPUBundleList=class WebGPUBundleList{constructor(e){this.numDrawCalls=0,this._device=e,this._list=Array(10),this._listLength=0}addBundle(e){if(!this._currentItemIsBundle){let e=new WebGPURenderItemBundles;this._list[this._listLength++]=e,this._currentBundleList=e.bundles,this._currentItemIsBundle=!0}e&&this._currentBundleList.push(e)}_finishBundle(){this._currentItemIsBundle&&this._bundleEncoder&&(this._currentBundleList.push(this._bundleEncoder.finish()),this._bundleEncoder=void 0,this._currentItemIsBundle=!1)}addItem(e){this._finishBundle(),this._list[this._listLength++]=e,this._currentItemIsBundle=!1}getBundleEncoder(e,t,i){return this._currentItemIsBundle||(this.addBundle(),this._bundleEncoder=this._device.createRenderBundleEncoder({colorFormats:e,depthStencilFormat:t,sampleCount:i})),this._bundleEncoder}close(){this._finishBundle()}run(e){this.close();for(let t=0;t<this._listLength;++t)this._list[t].run(e)}reset(){this._listLength=0,this._currentItemIsBundle=!1,this.numDrawCalls=0}clone(){this.close();let e=new WebGPUBundleList(this._device);e._list=Array(this._listLength),e._listLength=this._listLength,e.numDrawCalls=this.numDrawCalls;for(let t=0;t<this._listLength;++t)e._list[t]=this._list[t].clone();return e}};let WebGPUQuerySet=class WebGPUQuerySet{get querySet(){return this._querySet}constructor(e,t,i,r,s=!0,n){this._dstBuffers=[],this._device=i,this._bufferManager=r,this._count=e,this._canUseMultipleBuffers=s,this._querySet=i.createQuerySet({label:n,type:t,count:e}),this._queryBuffer=r.createRawBuffer(8*e,tY.QueryResolve|tY.CopySrc,void 0,"QueryBuffer"),s||this._dstBuffers.push(this._bufferManager.createRawBuffer(8*this._count,tY.MapRead|tY.CopyDst,void 0,"QueryBufferNoMultipleBuffers"))}_getBuffer(e,t){let i;if(!this._canUseMultipleBuffers&&0===this._dstBuffers.length)return null;let r=this._device.createCommandEncoder();return 0===this._dstBuffers.length?i=this._bufferManager.createRawBuffer(8*this._count,tY.MapRead|tY.CopyDst,void 0,"QueryBufferAdditionalBuffer"):(i=this._dstBuffers[this._dstBuffers.length-1],this._dstBuffers.length--),r.resolveQuerySet(this._querySet,e,t,this._queryBuffer,0),r.copyBufferToBuffer(this._queryBuffer,0,i,0,8*t),this._device.queue.submit([r.finish()]),i}async readValues(e=0,t=1){let i=this._getBuffer(e,t);if(null===i)return null;await i.mapAsync(tj.Read);let r=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,r}async readValue(e=0){let t=this._getBuffer(e,1);if(null===t)return null;await t.mapAsync(tj.Read);let i=new BigUint64Array(t.getMappedRange()),r=Number(i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r}async readTwoValuesAndSubtract(e=0){let t=this._getBuffer(e,2);if(null===t)return null;await t.mapAsync(tj.Read);let i=new BigUint64Array(t.getMappedRange()),r=Number(i[1]-i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e<this._dstBuffers.length;++e)this._bufferManager.releaseBuffer(this._dstBuffers[e])}};let WebGPUTimestampQuery=class WebGPUTimestampQuery{get gpuFrameTimeCounter(){return this._gpuFrameTimeCounter}constructor(e,t){this._enabled=!1,this._gpuFrameTimeCounter=new n7.z,this._measureDurationState=0,this._device=e,this._bufferManager=t}get enable(){return this._enabled}set enable(e){this._enabled!==e&&(this._enabled=e,this._measureDurationState=0,e?this._measureDuration=new WebGPUDurationMeasure(this._device,this._bufferManager):this._measureDuration.dispose())}startFrame(e){this._enabled&&0===this._measureDurationState&&(this._measureDuration.start(e),this._measureDurationState=1)}endFrame(e){1===this._measureDurationState&&(this._measureDurationState=2,this._measureDuration.stop(e).then(e=>{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0}))}};let WebGPUDurationMeasure=class WebGPUDurationMeasure{constructor(e,t){this._querySet=new WebGPUQuerySet(2,ig.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()}};let WebGPUOcclusionQuery=class WebGPUOcclusionQuery{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;let t=!1,i=this._engine._getCurrentRenderPassIndex();switch(i){case 0:t=void 0!==this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet;break;case 1:t=void 0!==this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet}return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,r=50,s=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(r)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();let e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e<this._lastBuffer.length}getQueryResult(e){var t,i;return Number(null!==(i=null===(t=this._lastBuffer)||void 0===t?void 0:t[e])&&void 0!==i?i:-1)}_retrieveQueryBuffer(){this._lastBuffer&&this._frameLastBuffer===this._engine.frameId||this._frameLastBuffer===this._engine.frameId||(this._frameLastBuffer=this._engine.frameId,this._querySet.readValues(0,this._currentTotalIndices).then(e=>{this._lastBuffer=e}))}_allocateNewIndices(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;t<e;++t)this._availableIndices.push(this._currentTotalIndices+t);this._currentTotalIndices+=e,this._querySet=new WebGPUQuerySet(this._currentTotalIndices,ig.Occlusion,this._device,this._bufferManager,!1,"QuerySet_OcclusionQuery_count_"+this._currentTotalIndices),this._frameQuerySetIsDirty=this._engine.frameId}_delayQuerySetDispose(){let e=this._querySet;e&&setTimeout(()=>e.dispose,1e3)}dispose(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0}};let WebGPUTintWASM=class WebGPUTintWASM{async initTwgsl(e){return WebGPUTintWASM._twgsl?void 0:(e=e||{},(e=Object.assign(Object.assign({},WebGPUTintWASM._TWgslDefaultOptions),e)).twgsl)?(WebGPUTintWASM._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await rW.w1.LoadBabylonScriptAsync(e.jsPath),self.twgsl)?(WebGPUTintWASM._twgsl=await self.twgsl(rW.w1.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available.")}convertSpirV2WGSL(e,t=!1){let i=WebGPUTintWASM._twgsl.convertSpirV2WGSL(e,WebGPUTintWASM.DisableUniformityAnalysis||t);return WebGPUTintWASM.ShowWGSLShaderCode&&(console.log(i),console.log("***********************************************")),WebGPUTintWASM.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}};WebGPUTintWASM._TWgslDefaultOptions={jsPath:`${rW.w1._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${rW.w1._DefaultCdnUrl}/twgsl/twgsl.wasm`},WebGPUTintWASM.ShowWGSLShaderCode=!1,WebGPUTintWASM.DisableUniformityAnalysis=!1,WebGPUTintWASM._twgsl=null;let WebGPUSnapshotRendering=class WebGPUSnapshotRendering{constructor(e,t,i,r){this._record=!1,this._play=!1,this._mainPassBundleList=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i,this._bundleListRenderTarget=r}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,r,s,n;if(this._play)null===(r=null===(i=t._bundleLists)||void 0===i?void 0:i[t._currentLayer])||void 0===r||r.run(e),1===this._mode&&this._engine._reportDrawCall(null===(n=null===(s=t._bundleLists)||void 0===s?void 0:s[t._currentLayer])||void 0===n?void 0:n.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<this._mainPassBundleList.length;++t)this._mainPassBundleList[t].run(e),1===this._mode&&this._engine._reportDrawCall(this._mainPassBundleList[t].numDrawCalls)}reset(){this.enabled=!1,this.enabled=!0}};let aJ=`attribute position: vec2<f32>;uniform scale: vec2<f32>;varying vUV: vec2<f32>;const madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +} +`;s_.v.ShadersStoreWGSL.postprocessVertexShader=aJ;let a0={label:"TextureView_SwapChain_ResolveTarget",dimension:tq.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},a1={label:"TextureView_SwapChain",dimension:tq.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},a2="/* disable_uniformity_analysis */",a3=new rg.HE;let webgpuEngine_WebGPUEngine=class webgpuEngine_WebGPUEngine extends rq.D{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return rT.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(){let e=this.name+this.version;return e}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={}){let i=new webgpuEngine_WebGPUEngine(e,t);return new Promise(e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>e(i))})}constructor(e,t={}){var i,r;if(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 WebGPURenderPassWrapper,this._rttRenderPassWrapper=new WebGPURenderPassWrapper,this._pendingDebugCommands=[],this._onAfterUnbindFrameBufferObservable=new rf.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!==(r=t.enableGPUDebugMarkers)&&void 0!==r&&r,rT.Y.Log(`Babylon.js v${rq.D.Version} - ${this.description} engine`),!navigator.gpu){rT.Y.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(e),this._shaderProcessor=new WebGPUShaderProcessorGLSL,this._shaderProcessorWGSL=new WebGPUShaderProcessorWGSL}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=webgpuEngine_WebGPUEngine.UseTWGSL?new WebGPUTintWASM: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 rT.Y.Error("Can not initialize twgsl!"),rT.Y.Error(e),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},e=>{throw rT.Y.Error("Can not initialize glslang!"),rT.Y.Error(e),Error("WebGPU initializations stopped.")}).then(e=>{var t,i,r;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});let s=null!==(i=this._options.deviceDescriptor)&&void 0!==i?i:{},n=null!==(r=null==s?void 0:s.requiredFeatures)&&void 0!==r?r:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(n){let e=[];for(let t of n)-1!==this._adapterSupportedExtensions.indexOf(t)&&e.push(t);s.requiredFeatures=e}if(this._options.setMaximumLimits&&!s.requiredLimits)for(let e in s.requiredLimits={},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 r=-1;this._device.addEventListener("uncapturederror",e=>{++r<this.numMaxUncapturedErrors?rT.Y.Warn(`WebGPU uncaptured error (${r+1}): ${e.error} - ${e.error.message}`):r++===this.numMaxUncapturedErrors&&rT.Y.Warn(`WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`)}),this._doNotHandleContextLost||null===(i=this._device.lost)||void 0===i||i.then(e=>{this._isDisposed||(this._contextWasLost=!0,rT.Y.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(()=>this.initAsync()))})},e=>{rT.Y.Error("Could not retrieve a WebGPU device."),rT.Y.Error(e)}).then(()=>{this._bufferManager=new WebGPUBufferManager(this._device),this._textureHelper=new WebGPUTextureHelper(this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new WebGPUCacheSampler(this._device),this._cacheBindGroups=new WebGPUCacheBindGroups(this._device,this._cacheSampler,this),this._timestampQuery=new WebGPUTimestampQuery(this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new WebGPUOcclusionQuery(this,this._device,this._bufferManager):void 0,this._bundleList=new WebGPUBundleList(this._device),this._bundleListRenderTarget=new WebGPUBundleList(this._device),this._snapshotRendering=new WebGPUSnapshotRendering(this,this._snapshotRenderingMode,this._bundleList,this._bundleListRenderTarget),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),tY.Uniform|tY.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),tY.Uniform|tY.CopyDst,"UBDontInvertY"),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._initializeLimits(),this._emptyVertexBuffer=new rz.o(this,[0],"",!1,!1,1,!1,0,1),this._cacheRenderPipeline=new WebGPUCacheRenderPipelineTree(this._device,this._emptyVertexBuffer,!this._caps.textureFloatLinearFiltering),this._depthCullingState=new WebGPUDepthCullingState(this._cacheRenderPipeline),this._stencilStateComposer=new WebGPUStencilStateComposer(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 WebGPUClearQuad(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=>{rT.Y.Error("Can not create WebGPU Device and/or context."),rT.Y.Error(e),console.trace&&console.trace()})}_initGlslang(e){return(e=e||{},(e=Object.assign(Object.assign({},webgpuEngine_WebGPUEngine._GLSLslangDefaultOptions),e)).glslang)?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?rW.w1.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(rW.w1.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(tH.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(tH.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(tH.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(tH.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(tH.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(tH.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,forceVertexBufferStrideMultiple4Bytes:!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 WebGPUHardwareTexture],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat}_initializeMainAttachments(){let e;if(!this._bufferManager)return;this.flushFramebuffer(!1),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};let t=new Float32Array([this.getRenderHeight(!0)]);if(this._bufferManager.setSubData(this._ubInvertY,4,t),this._bufferManager.setSubData(this._ubDontInvertY,4,t),this._options.antialias){let t={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:tq.E2d,format:this._options.swapChainFormat,usage:tK.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(t),e=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:tq.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new rg.HE(0,0,0,1),loadOp:i_.Clear,storeOp:im.Store}]}else e=[{view:void 0,clearValue:new rg.HE(0,0,0,1),loadOp:i_.Clear,storeOp:im.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?tZ.Depth24PlusStencil8:tZ.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);let i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:tq.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:tK.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);let r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:tq.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:i_.Clear,depthStoreOp:im.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?i_.Clear:void 0,stencilStoreOp:this.isStencilEnable?im.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:e,depthStencilAttachment:r}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:tK.RenderAttachment|tK.CopySrc,alphaMode:this.premultipliedAlpha?iv.Premultiplied:iv.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<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - setSize called -",e,t)),this._initializeMainAttachments(),this.snapshotRendering&&this.snapshotRenderingReset(),!0)}_getShaderProcessor(e){return e===sg.x.WGSL?this._shaderProcessorWGSL:this._shaderProcessor}_getShaderProcessingContext(e){return new WebGPUShaderProcessingContext(e)}applyStates(){this._stencilStateComposer.apply(),this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend)}wipeCaches(e){(!this.preventCacheWipeBetweenFrames||e)&&(this._forceEnableEffect=!0,this._currentIndexBuffer=null,this._currentOverrideVertexBuffers=null,this._cacheRenderPipeline.setBuffers(null,null,null),e&&(this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=515,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters),this._cacheRenderPipeline.setAlphaBlendEnabled(!1),this.setColorWrite(!0)),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}setColorWrite(e){this._colorWriteLocal=e,this._cacheRenderPipeline.setWriteMask(e?15:0)}getColorWrite(){return this._colorWriteLocal}_resetCurrentViewport(e){this._viewportsCurrent[e].x=0,this._viewportsCurrent[e].y=0,this._viewportsCurrent[e].w=0,this._viewportsCurrent[e].h=0}_mustUpdateViewport(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._viewportCached.x,r=this._viewportCached.y,s=this._viewportCached.z,n=this._viewportCached.w,a=this._viewportsCurrent[t].x!==i||this._viewportsCurrent[t].y!==r||this._viewportsCurrent[t].w!==s||this._viewportsCurrent[t].h!==n;return a&&(this._viewportsCurrent[t].x=this._viewportCached.x,this._viewportsCurrent[t].y=this._viewportCached.y,this._viewportsCurrent[t].w=this._viewportCached.z,this._viewportsCurrent[t].h=this._viewportCached.w),a}_applyViewport(e){let t=Math.floor(this._viewportCached.y),i=Math.floor(this._viewportCached.w);this._currentRenderTarget||(t=this.getRenderHeight(!0)-t-i),e.setViewport(Math.floor(this._viewportCached.x),t,Math.floor(this._viewportCached.z),i,0,1),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - viewport applied - (",this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w,") current pass is main pass="+(e===this._mainRenderPassWrapper.renderPass)))}_viewport(e,t,i,r){this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r}_resetCurrentScissor(e){this._scissorsCurrent[e].x=0,this._scissorsCurrent[e].y=0,this._scissorsCurrent[e].w=0,this._scissorsCurrent[e].h=0}_mustUpdateScissor(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._scissorCached.x,r=this._scissorCached.y,s=this._scissorCached.z,n=this._scissorCached.w,a=this._scissorsCurrent[t].x!==i||this._scissorsCurrent[t].y!==r||this._scissorsCurrent[t].w!==s||this._scissorsCurrent[t].h!==n;return a&&(this._scissorsCurrent[t].x=this._scissorCached.x,this._scissorsCurrent[t].y=this._scissorCached.y,this._scissorsCurrent[t].w=this._scissorCached.z,this._scissorsCurrent[t].h=this._scissorCached.w),a}_applyScissor(e){e.setScissorRect(this._scissorCached.x,this._currentRenderTarget?this._scissorCached.y:this.getRenderHeight()-this._scissorCached.w-this._scissorCached.y,this._scissorCached.z,this._scissorCached.w),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - scissor applied - (",this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w,") current pass is main pass="+(e===this._mainRenderPassWrapper.renderPass)))}_scissorIsActive(){return 0!==this._scissorCached.x||0!==this._scissorCached.y||0!==this._scissorCached.z||0!==this._scissorCached.w}enableScissor(e,t,i,r){this._scissorCached.x=e,this._scissorCached.y=t,this._scissorCached.z=i,this._scissorCached.w=r}disableScissor(){this._scissorCached.x=0,this._scissorCached.y=0,this._scissorCached.z=0,this._scissorCached.w=0,this._resetCurrentScissor(0),this._resetCurrentScissor(1)}_resetCurrentStencilRef(e){this._stencilRefsCurrent[e]=-1}_mustUpdateStencilRef(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._stencilStateComposer.funcRef!==this._stencilRefsCurrent[t];return i&&(this._stencilRefsCurrent[t]=this._stencilStateComposer.funcRef),i}_applyStencilRef(e){var t;e.setStencilReference(null!==(t=this._stencilStateComposer.funcRef)&&void 0!==t?t:0)}_resetCurrentColorBlend(e){this._blendColorsCurrent[e][0]=this._blendColorsCurrent[e][1]=this._blendColorsCurrent[e][2]=this._blendColorsCurrent[e][3]=null}_mustUpdateBlendColor(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._alphaState._blendConstants,r=i[0]!==this._blendColorsCurrent[t][0]||i[1]!==this._blendColorsCurrent[t][1]||i[2]!==this._blendColorsCurrent[t][2]||i[3]!==this._blendColorsCurrent[t][3];return r&&(this._blendColorsCurrent[t][0]=i[0],this._blendColorsCurrent[t][1]=i[1],this._blendColorsCurrent[t][2]=i[2],this._blendColorsCurrent[t][3]=i[3]),r}_applyBlendColor(e){e.setBlendConstant(this._alphaState._blendConstants)}clear(e,t,i,r=!1){e&&void 0===e.a&&(e.a=1);let s=this._scissorIsActive();this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - clear called - backBuffer=",t," depth=",i," stencil=",r," scissor is active=",s)),this._currentRenderTarget?s?(this._rttRenderPassWrapper.renderPass||this._startRenderTargetRenderPass(this._currentRenderTarget,!1,t?e:null,i,r),this.compatibilityMode?this._applyScissor(this._currentRenderPass):this._bundleListRenderTarget.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),this._clearFullQuad(t?e:null,i,r)):(this._currentRenderPass&&this._endRenderTargetRenderPass(),this._startRenderTargetRenderPass(this._currentRenderTarget,!0,t?e:null,i,r)):(this._mainRenderPassWrapper.renderPass&&s||this._startMainRenderPass(!s,t?e:null,i,r),s&&(this.compatibilityMode?this._applyScissor(this._currentRenderPass):this._bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),this._clearFullQuad(t?e:null,i,r)))}_clearFullQuad(e,t,i){var r,s,n;let a=this.compatibilityMode?this._getCurrentRenderPass():null,o=this._getCurrentRenderPassIndex(),l=0===o?this._bundleList:this._bundleListRenderTarget;this._clearQuad.setColorFormat(this._colorFormat),this._clearQuad.setDepthStencilFormat(this._depthTextureFormat),this._clearQuad.setMRTAttachments(null!==(r=this._cacheRenderPipeline.mrtAttachments)&&void 0!==r?r:[],null!==(s=this._cacheRenderPipeline.mrtTextureArray)&&void 0!==s?s:[],this._cacheRenderPipeline.mrtTextureCount),this.compatibilityMode?a.setStencilReference(this._clearStencilValue):l.addItem(new WebGPURenderItemStencilRef(this._clearStencilValue));let h=this._clearQuad.clear(a,e,t,i,this.currentSampleCount);this.compatibilityMode?this._applyStencilRef(a):(l.addBundle(h),l.addItem(new WebGPURenderItemStencilRef(null!==(n=this._stencilStateComposer.funcRef)&&void 0!==n?n:0)),this._reportDrawCall())}createVertexBuffer(e,t,i){let r;r=e instanceof Array?new Float32Array(e):e instanceof ArrayBuffer?new Uint8Array(e):e;let s=this._bufferManager.createBuffer(r,tY.Vertex|tY.CopyDst,i);return s}createDynamicVertexBuffer(e,t){return this.createVertexBuffer(e,void 0,t)}createIndexBuffer(e,t,i){let r,s=!0;e instanceof Uint32Array||e instanceof Int32Array?r=e:e instanceof Uint16Array?(r=e,s=!1):e.length>65535?r=new Uint32Array(e):(r=new Uint16Array(e),s=!1);let n=this._bufferManager.createBuffer(r,tY.Index|tY.CopyDst,i);return n.is32Bits=s,n}_createBuffer(e,t,i){let r;r=e instanceof Array?new Float32Array(e):e instanceof ArrayBuffer?new Uint8Array(e):e;let s=0;return 1&t&&(s|=tY.CopySrc),2&t&&(s|=tY.CopyDst),4&t&&(s|=tY.Uniform),8&t&&(s|=tY.Vertex),16&t&&(s|=tY.Index),32&t&&(s|=tY.Storage),this._bufferManager.createBuffer(r,s,i)}bindBuffersDirectly(){throw"Not implemented on WebGPU"}updateAndBindInstancesBuffer(){throw"Not implemented on WebGPU"}bindBuffers(e,t,i,r){this._currentIndexBuffer=t,this._currentOverrideVertexBuffers=null!=r?r:null,this._cacheRenderPipeline.setBuffers(e,t,this._currentOverrideVertexBuffers)}_releaseBuffer(e){return this._bufferManager.releaseBuffer(e)}createEffect(e,t,i,r,s,n,a,o,l,h=sg.x.GLSL){var u;let c=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,d=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,p=this._getGlobalDefines(),_=null!==(u=null!=s?s:t.defines)&&void 0!==u?u:"";p&&(_+="\n"+p);let f=c+"+"+d+"@"+_;if(this._compiledEffects[f]){let e=this._compiledEffects[f];return a&&e.isReady()&&a(e),e}let m=new ss.Q(e,t,i,r,this,s,n,a,o,l,f,h);return this._compiledEffects[f]=m,m}_compileRawShaderToSpirV(e,t){return this._glslang.compileGLSL(e,t)}_compileShaderToSpirV(e,t,i,r){return this._compileRawShaderToSpirV(r+(i?i+"\n":"")+e,t)}_getWGSLShader(e,t,i){return(i=i?"//"+i.split("\n").join("\n//")+"\n":"")+e}_createPipelineStageDescriptor(e,t,i,r,s){return this._tintWASM&&i===sg.x.GLSL&&(e=this._tintWASM.convertSpirV2WGSL(e,r),t=this._tintWASM.convertSpirV2WGSL(t,s)),{vertexStage:{module:this._device.createShaderModule({code:e}),entryPoint:"main"},fragmentStage:{module:this._device.createShaderModule({code:t}),entryPoint:"main"}}}_compileRawPipelineStageDescriptor(e,t,i){let r=e.indexOf(a2)>=0,s=t.indexOf(a2)>=0,n=i===sg.x.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,a=i===sg.x.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,a,i,r,s)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=e.indexOf(a2)>=0,n=t.indexOf(a2)>=0,a="#version 450\n",o=r===sg.x.GLSL?this._compileShaderToSpirV(e,"vertex",i,a):this._getWGSLShader(e,"vertex",i),l=r===sg.x.GLSL?this._compileShaderToSpirV(t,"fragment",i,a):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(o,l,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){let t=new ShaderCodeInliner(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new WebGPUPipelineContext(e,this)}createMaterialContext(){return new WebGPUMaterialContext}createDrawContext(){return new WebGPUDrawContext(this._bufferManager)}_preparePipelineContext(e,t,i,r,s,n,a,o){let l=e.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(o),console.log(t),console.log(i),console.log("***********************************************")),e.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:n},r?e.stages=this._compileRawPipelineStageDescriptor(t,i,l):e.stages=this._compilePipelineStageDescriptor(t,i,o,l)}getAttributes(e,t){let i=Array(t.length);for(let r=0;r<t.length;r++){let s=t[r],n=e.shaderProcessingContext.availableAttributes[s];void 0!==n&&(i[r]=n)}return i}enableEffect(e){if(!e)return;let t=!0;if(sm.q.IsWrapper(e)){if(e.effect&&(e.effect!==this._currentEffect||e.materialContext!==this._currentMaterialContext||e.drawContext!==this._currentDrawContext||this._forceEnableEffect)){if(t=e.effect!==this._currentEffect,this._currentEffect=e.effect,this._currentMaterialContext=e.materialContext,this._currentDrawContext=e.drawContext,this._counters.numEnableDrawWrapper++,!this._currentMaterialContext)throw console.error("drawWrapper=",e),"Invalid call to enableEffect: the materialContext property is empty!"}else{if(!e.effect&&this.dbgShowEmptyEnableEffectCalls)throw console.error("drawWrapper=",e),"Invalid call to enableEffect: the effect property is empty!";return}}else t=e!==this._currentEffect,this._currentEffect=e,this._currentMaterialContext=this._defaultMaterialContext,this._currentDrawContext=this._defaultDrawContext,this._counters.numEnableEffects++,this.dbgLogIfNotDrawWrapper&&rT.Y.Warn(`enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=${e.uniqueId}, effect.name=${e.name}, effect.name.vertex=${e.name.vertex}, effect.name.fragment=${e.name.fragment}`,10);this._stencilStateComposer.stencilMaterial=void 0,this._forceEnableEffect=!t&&!this._forceEnableEffect&&this._forceEnableEffect,t&&(this._currentEffect.onBind&&this._currentEffect.onBind(this._currentEffect),this._currentEffect._onBindObservable&&this._currentEffect._onBindObservable.notifyObservers(this._currentEffect))}_releaseEffect(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],this._deletePipelineContext(e.getPipelineContext()))}releaseEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}_deletePipelineContext(e){e&&e.dispose()}get needPOTTextures(){return!1}_createHardwareTexture(){return new WebGPUHardwareTexture}_releaseTexture(e){let t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),this._textureHelper.releaseTexture(e)}_getRGBABufferInternalSizedFormat(){return 5}updateTextureComparisonFunction(e,t){e._comparisonFunction=t}_createInternalTexture(e,t,i=!0,r=r5.S.Unknown){var s,n,a;let o={};void 0!==t&&"object"==typeof t?(o.generateMipMaps=t.generateMipMaps,o.type=void 0===t.type?0:t.type,o.samplingMode=void 0===t.samplingMode?3:t.samplingMode,o.format=void 0===t.format?5:t.format,o.samples=null!==(s=t.samples)&&void 0!==s?s:1,o.creationFlags=null!==(n=t.creationFlags)&&void 0!==n?n:0,o.useSRGBBuffer=null!==(a=t.useSRGBBuffer)&&void 0!==a&&a,o.label=t.label):(o.generateMipMaps=t,o.type=0,o.samplingMode=3,o.format=5,o.samples=1,o.creationFlags=0,o.useSRGBBuffer=!1),(1!==o.type||this._caps.textureFloatLinearFiltering)&&(2!==o.type||this._caps.textureHalfFloatLinearFiltering)||(o.samplingMode=1),1!==o.type||this._caps.textureFloat||(o.type=0,rT.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let l=new r5.l(this,r),h=e.width||e,u=e.height||e,c=e.layers||0;return l.baseWidth=h,l.baseHeight=u,l.width=h,l.height=u,l.depth=c,l.isReady=!0,l.samples=o.samples,l.generateMipMaps=!!o.generateMipMaps,l.samplingMode=o.samplingMode,l.type=o.type,l.format=o.format,l.is2DArray=c>0,l._cachedWrapU=0,l._cachedWrapV=0,l._useSRGBBuffer=o.useSRGBBuffer,l.label=o.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,h,u,c||1,o.creationFlags),l}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_){return this._createTextureBase(e,t,i,r,s,n,a,(e,t,i,r,s,n,a,o)=>{var l;if(e.baseWidth=r.width,e.baseHeight=r.height,e.width=r.width,e.height=r.height,e.format=-1!==e.format?e.format:null!=h?h:5,e.type=-1!==e.type?e.type:0,o(e.width,e.height,r,t,e,()=>{}),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)n||a||this._generateMipmaps(e,this._uploadEncoder);else{let t=this._textureHelper.createGPUTextureForInternalTexture(e,r.width,r.height,void 0,p);!WebGPUTextureHelper.IsImageBitmap(r)||(this._textureHelper.updateTexture(r,e,r.width,r.height,e.depth,t.format,0,0,s,!1,0,0),n||a||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()},()=>!1,o,l,h,u,c,d,_)}wrapWebGPUTexture(e){let t=new WebGPUHardwareTexture(e),i=new r5.l(this,r5.S.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;if(e.generateMipMaps){let i=null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource;i||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e,e.source===r5.S.RenderTarget||e.source===r5.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,r=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===r)return;let s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,s)}_setInternalTexture(e,t,i){if(i=null!=i?i:e,this._currentEffect){let r=this._currentEffect._pipelineContext,s=r.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){let e=i+WebGPUShaderProcessor.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let e=0;e<i.length;e++)this._setTexture(-1,i[e],!0,!1,r+e.toString(),r)}_setTexture(e,t,i=!1,r=!1,s="",n){if(n=null!=n?n:s,this._currentEffect){if(!t)return this._currentMaterialContext.setTexture(s,null),!1;if(t.video)t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let e=null;if((e=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture)&&!e.isMultiview){if(e.isCube&&e._cachedCoordinatesMode!==t.coordinatesMode){e._cachedCoordinatesMode=t.coordinatesMode;let i=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=i,t.wrapV=i}e._cachedWrapU=t.wrapU,e._cachedWrapV=t.wrapV,e.is3D&&(e._cachedWrapR=t.wrapR),this._setAnisotropicLevel(0,e,t.anisotropicFilteringLevel)}this._setInternalTexture(s,e,n)}else this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - _setTexture called with a null _currentEffect! texture=",t));return!0}_setAnisotropicLevel(e,t,i){t._cachedAnisotropicFilteringLevel!==i&&(t._cachedAnisotropicFilteringLevel=Math.min(i,this._caps.maxAnisotropy))}_bindTexture(e,t,i){void 0!==e&&this._setInternalTexture(i,t)}generateMipmaps(e){this._generateMipmaps(e,this._renderTargetEncoder)}_generateMipmaps(e,t){let i=e._hardwareTexture;if(!i)return;t=null!=t?t:this._currentRenderTarget&&!this._currentRenderPass?this._renderTargetEncoder:this._currentRenderPass?this._uploadEncoder:this._renderEncoder;let r=e._hardwareTexture.format,s=WebGPUTextureHelper.ComputeNumMipmapLevels(e.width,e.height);this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - generate mipmaps called - width=",e.width,"height=",e.height,"isCube=",e.isCube)),e.isCube?this._textureHelper.generateCubeMipmaps(i,r,s,t):this._textureHelper.generateMipmaps(i,r,s,0,t)}updateTextureData(e,t,i,r,s,n,a=0,o=0,l=!1){var h;let u=e._hardwareTexture;(null===(h=e._hardwareTexture)||void 0===h?void 0:h.underlyingResource)||(u=this._textureHelper.createGPUTextureForInternalTexture(e));let c=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(c,e,s,n,e.depth,u.format,a,o,e.invertY,!1,i,r),l&&this._generateMipmaps(e,this._renderTargetEncoder)}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,a=0){var o;let l=e._hardwareTexture;(null===(o=e._hardwareTexture)||void 0===o?void 0:o.underlyingResource)||(e.format=t,l=this._textureHelper.createGPUTextureForInternalTexture(e,i,r));let h=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);this._textureHelper.updateTexture(h,e,i,r,e.depth,l.format,n,a,!1,!1,0,0)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,n=!1){var a;let o=Math.round(Math.log(e.width)*Math.LOG2E),l=Math.round(Math.log(e.height)*Math.LOG2E),h=n?e.width:Math.pow(2,Math.max(o-r,0)),u=n?e.height:Math.pow(2,Math.max(l-r,0)),c=e._hardwareTexture;(null===(a=e._hardwareTexture)||void 0===a?void 0:a.underlyingResource)||(c=this._textureHelper.createGPUTextureForInternalTexture(e,h,u));let d=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(d,e,h,u,e.depth,c.format,i,r,e.invertY,!1,0,0)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){this._uploadDataToTextureDirectly(e,t,i,r)}_uploadImageToTexture(e,t,i=0,r=0){var s;let n=e._hardwareTexture;if((null===(s=e._hardwareTexture)||void 0===s?void 0:s.underlyingResource)||(n=this._textureHelper.createGPUTextureForInternalTexture(e)),t instanceof HTMLImageElement)throw"WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!";let a=Math.ceil(e.width/(1<<r)),o=Math.ceil(e.height/(1<<r));this._textureHelper.updateTexture(t,e,a,o,e.depth,n.format,i,r,e.invertY,!1,0,0)}readPixels(e,t,i,r,s=!0,n=!0){let a=this._rttRenderPassWrapper.renderPass?this._rttRenderPassWrapper:this._mainRenderPassWrapper,o=a.colorAttachmentGPUTextures[0];if(!o)return Promise.resolve(new Uint8Array(0));let l=o.underlyingResource,h=o.format;return l?(n&&this.flushFramebuffer(),this._textureHelper.readPixels(l,e,t,i,r,h)):Promise.resolve(new Uint8Array(0))}beginFrame(){super.beginFrame()}endFrame(){if(this._snapshotRendering.endFrame(this._mainRenderPassWrapper.renderPass),this._endMainRenderPass(),this._timestampQuery.endFrame(this._renderEncoder),this.flushFramebuffer(!1),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - counters")),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this._features._collectUbosUpdatedInFrame){if(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){let e=[];for(let t in rX.M._UpdatedUbosInFrame)e.push(t+":"+rX.M._UpdatedUbosInFrame[t]);console.log("frame #"+this._count+" - updated ubos -",e.join(", "))}rX.M._UpdatedUbosInFrame={}}this.countersLastFrame.numEnableEffects=this._counters.numEnableEffects,this.countersLastFrame.numEnableDrawWrapper=this._counters.numEnableDrawWrapper,this.countersLastFrame.numBundleCreationNonCompatMode=this._counters.numBundleCreationNonCompatMode,this.countersLastFrame.numBundleReuseNonCompatMode=this._counters.numBundleReuseNonCompatMode,this._counters.numEnableEffects=0,this._counters.numEnableDrawWrapper=0,this._counters.numBundleCreationNonCompatMode=0,this._counters.numBundleReuseNonCompatMode=0,this._cacheRenderPipeline.endFrame(),this._cacheBindGroups.endFrame(),this._pendingDebugCommands.length=0,super.endFrame(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),this._count<this.dbgVerboseLogsNumFrames&&console.log("%c frame #"+this._count+" - end","background: #ffff00"),this._count<this.dbgVerboseLogsNumFrames&&(this._count++,this._count!==this.dbgVerboseLogsNumFrames&&console.log("%c frame #"+this._count+" - begin","background: #ffff00")))}flushFramebuffer(e=!0){let t=!this._currentRenderPass,i=0;this._currentRenderPass&&this._currentRenderTarget&&(i|=1,this._endRenderTargetRenderPass()),this._mainRenderPassWrapper.renderPass&&(i|=2,this._endMainRenderPass()),this._commandBuffers[0]=this._uploadEncoder.finish(),this._commandBuffers[1]=this._renderTargetEncoder.finish(),this._commandBuffers[2]=this._renderEncoder.finish(),this._device.queue.submit(this._commandBuffers),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._timestampQuery.startFrame(this._uploadEncoder),this._textureHelper.setCommandEncoder(this._uploadEncoder),this._bundleList.reset(),this._bundleListRenderTarget.reset(),e&&(2&i&&this._startMainRenderPass(!1),1&i&&this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1),t&&this._currentRenderTarget&&(this._currentRenderPass=null))}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentRenderTarget}_startRenderTargetRenderPass(e,t,i,r,s){var n,a,o,l,h,u,c,d;let p=e._depthStencilTexture,_=null==p?void 0:p._hardwareTexture,f=null==_?void 0:_.underlyingResource,m=null==_?void 0:_.getMSAATexture(),g=null==f?void 0:f.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),v=null==m?void 0:m.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),x=!!_&&WebGPUTextureHelper.HasStencilAspect(_.format),T=[];this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual(),i&&(a3.r=255*i.r,a3.g=255*i.g,a3.b=255*i.b,a3.a=255*i.a);let S=t&&i,C=t&&r,E=t&&s;if(e._attachments&&e.isMulti){this._mrtAttachments&&0!==this._mrtAttachments.length||(this._mrtAttachments=e._defaultAttachments);for(let t=0;t<this._mrtAttachments.length;++t){let r=this._mrtAttachments[t],s=e.textures[t],h=null==s?void 0:s._hardwareTexture,u=null==h?void 0:h.underlyingResource;if(h&&u){let c=h.getMSAATexture(t),d=null!==(a=null===(n=e.layerIndices)||void 0===n?void 0:n[t])&&void 0!==a?a:0,p=null!==(l=null===(o=e.faceIndices)||void 0===o?void 0:o[t])&&void 0!==l?l:0,_=Object.assign(Object.assign({},this._rttRenderPassWrapper.colorAttachmentViewDescriptor),{format:h.format,baseArrayLayer:s.isCube?6*d+p:d}),f=Object.assign(Object.assign({},this._rttRenderPassWrapper.colorAttachmentViewDescriptor),{format:h.format,baseArrayLayer:0}),m=7===s.type||5===s.type,g=u.createView(_),v=null==c?void 0:c.createView(f);T.push({view:v||g,resolveTarget:c?g:void 0,clearValue:0!==r&&S?m?a3:i:void 0,loadOp:0!==r&&S?i_.Clear:i_.Load,storeOp:im.Store})}}this._cacheRenderPipeline.setMRT(e.textures,this._mrtAttachments.length),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)}else{let t=e.texture;if(t){let e=t._hardwareTexture,r=e.underlyingResource,s=e.getMSAATexture(),n=r.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),a=null==s?void 0:s.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),o=7===t.type||5===t.type;T.push({view:a||n,resolveTarget:s?n:void 0,clearValue:S?o?a3:i:void 0,loadOp:S?i_.Clear:i_.Load,storeOp:im.Store})}else T.push(null)}if(null===(h=this._debugPushGroup)||void 0===h||h.call(this,"render target pass",1),this._rttRenderPassWrapper.renderPassDescriptor={label:(null!==(u=e.label)&&void 0!==u?u:"RTT")+"RenderPass",colorAttachments:T,depthStencilAttachment:p&&f?{view:v||g,depthClearValue:C?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,depthLoadOp:C?i_.Clear:i_.Load,depthStoreOp:im.Store,stencilClearValue:e._depthStencilTextureWithStencil&&E?this._clearStencilValue:void 0,stencilLoadOp:x?e._depthStencilTextureWithStencil&&E?i_.Clear:i_.Load:void 0,stencilStoreOp:x?im.Store:void 0}:void 0,occlusionQuerySet:(null===(c=this._occlusionQuery)||void 0===c?void 0:c.hasQueries)?this._occlusionQuery.querySet:void 0},this._rttRenderPassWrapper.renderPass=this._renderTargetEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){let t=e.texture;console.log("frame #"+this._count+" - render target begin pass - internalTexture.uniqueId=",t.uniqueId,"width=",t.width,"height=",t.height,this._rttRenderPassWrapper.renderPassDescriptor)}this._currentRenderPass=this._rttRenderPassWrapper.renderPass,null===(d=this._debugFlushPendingCommands)||void 0===d||d.call(this),this._resetCurrentViewport(1),this._resetCurrentScissor(1),this._resetCurrentStencilRef(1),this._resetCurrentColorBlend(1),_&&WebGPUTextureHelper.HasStencilAspect(_.format)||(this._stencilStateComposer.enabled=!1)}_endRenderTargetRenderPass(){var e,t,i,r;if(this._currentRenderPass){let s=null===(e=this._currentRenderTarget.texture)||void 0===e?void 0:e._hardwareTexture;!s||this._snapshotRendering.endRenderTargetPass(this._currentRenderPass,s)||this.compatibilityMode||(this._bundleListRenderTarget.run(this._currentRenderPass),this._bundleListRenderTarget.reset()),this._currentRenderPass.end(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - render target end pass - internalTexture.uniqueId=",null===(i=null===(t=this._currentRenderTarget)||void 0===t?void 0:t.texture)||void 0===i?void 0:i.uniqueId)),null===(r=this._debugPopGroup)||void 0===r||r.call(this,1),this._resetCurrentViewport(1),this._viewport(0,0,0,0),this._resetCurrentScissor(1),this._resetCurrentStencilRef(1),this._resetCurrentColorBlend(1),this._currentRenderPass=null,this._rttRenderPassWrapper.reset()}}_getCurrentRenderPass(){return this._currentRenderTarget&&!this._currentRenderPass?this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1):this._currentRenderPass||this._startMainRenderPass(!1),this._currentRenderPass}_getCurrentRenderPassIndex(){return null===this._currentRenderPass?-1:this._currentRenderPass===this._mainRenderPassWrapper.renderPass?0:1}_startMainRenderPass(e,t,i,r){var s,n,a;this._mainRenderPassWrapper.renderPass&&this.flushFramebuffer(!1),this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();let o=e&&t,l=e&&i,h=e&&r;this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue=o?t:void 0,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp=o?i_.Clear:i_.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue=l?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp=l?i_.Clear:i_.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue=h?this._clearStencilValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp=this.isStencilEnable?h?i_.Clear:i_.Load:void 0,this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet=(null===(s=this._occlusionQuery)||void 0===s?void 0:s.hasQueries)?this._occlusionQuery.querySet:void 0;let u=this._context.getCurrentTexture();this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(u),this._options.antialias?(a0.format=u.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget=u.createView(a0)):(a1.format=u.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view=u.createView(a1)),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - main begin pass - texture width="+this._mainTextureExtends.width," height="+this._mainTextureExtends.height,this._mainRenderPassWrapper.renderPassDescriptor)),null===(n=this._debugPushGroup)||void 0===n||n.call(this,"main pass",0),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor),this._mainRenderPassWrapper.renderPass=this._currentRenderPass,null===(a=this._debugFlushPendingCommands)||void 0===a||a.call(this),this._resetCurrentViewport(0),this._resetCurrentScissor(0),this._resetCurrentStencilRef(0),this._resetCurrentColorBlend(0),this._isStencilEnable||(this._stencilStateComposer.enabled=!1)}_endMainRenderPass(){var e;null!==this._mainRenderPassWrapper.renderPass&&(this._snapshotRendering.endMainRenderPass(),this.compatibilityMode||this._snapshotRendering.play||(this._bundleList.run(this._mainRenderPassWrapper.renderPass),this._bundleList.reset()),this._mainRenderPassWrapper.renderPass.end(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - main end pass")),null===(e=this._debugPopGroup)||void 0===e||e.call(this,0),this._resetCurrentViewport(0),this._resetCurrentScissor(0),this._resetCurrentStencilRef(0),this._resetCurrentColorBlend(0),this._mainRenderPassWrapper.renderPass===this._currentRenderPass&&(this._currentRenderPass=null),this._mainRenderPassWrapper.reset(!1))}bindFramebuffer(e,t=0,i,r,s,n=0,a=0){var o,l;let h=null===(o=e.texture)||void 0===o?void 0:o._hardwareTexture;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,h&&(h._currentLayer=e.isCube?6*a+t:a),this._rttRenderPassWrapper.colorAttachmentGPUTextures[0]=h,this._rttRenderPassWrapper.depthTextureFormat=this._currentRenderTarget._depthStencilTexture?WebGPUTextureHelper.GetWebGPUTextureFormat(-1,this._currentRenderTarget._depthStencilTexture.format):void 0,this._setDepthTextureFormat(this._rttRenderPassWrapper),this._setColorFormat(this._rttRenderPassWrapper),this._rttRenderPassWrapper.colorAttachmentViewDescriptor={format:this._colorFormat,dimension:t$.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?6*a+t:a,baseMipLevel:n,arrayLayerCount:1,aspect:tQ.All},this._rttRenderPassWrapper.depthAttachmentViewDescriptor={format:this._depthTextureFormat,dimension:t$.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?6*a+t:a,baseMipLevel:0,arrayLayerCount:1,aspect:tQ.All},this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - bindFramebuffer called - internalTexture.uniqueId=",null===(l=e.texture)||void 0===l?void 0:l.uniqueId,"face=",t,"lodLevel=",n,"layer=",a,this._rttRenderPassWrapper.colorAttachmentViewDescriptor,this._rttRenderPassWrapper.depthAttachmentViewDescriptor)),this._currentRenderPass=null,this.snapshotRendering&&1===this.snapshotRenderingMode&&this._getCurrentRenderPass(),this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,r):(!i&&(i=e.width,n&&(i/=Math.pow(2,n))),!r&&(r=e.height,n&&(r/=Math.pow(2,n))),this._viewport(0,0,i,r)),this.wipeCaches()}unBindFramebuffer(e,t=!1,i){var r,s;let n=this._currentRenderTarget;this._currentRenderTarget=null,i&&i(),this._currentRenderTarget=n,this._currentRenderPass&&this._currentRenderPass!==this._mainRenderPassWrapper.renderPass&&this._endRenderTargetRenderPass(),(null===(r=e.texture)||void 0===r?void 0:r.generateMipMaps)&&!t&&!e.isCube&&this._generateMipmaps(e.texture),this._currentRenderTarget=null,this._onAfterUnbindFrameBufferObservable.notifyObservers(this),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - unBindFramebuffer called - internalTexture.uniqueId=",null===(s=e.texture)||void 0===s?void 0:s.uniqueId)),this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments),this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):(this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)),this._currentRenderPass&&this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_setColorFormat(e){var t,i;let r=null!==(i=null===(t=e.colorAttachmentGPUTextures[0])||void 0===t?void 0:t.format)&&void 0!==i?i:null;this._cacheRenderPipeline.setColorFormat(r),this._colorFormat!==r&&(this._colorFormat=r)}_setDepthTextureFormat(e){this._cacheRenderPipeline.setDepthStencilFormat(e.depthTextureFormat),this._depthTextureFormat!==e.depthTextureFormat&&(this._depthTextureFormat=e.depthTextureFormat)}setDitheringState(){}setRasterizerState(){}setState(e,t=0,i,r=!1,s,n,a=0){var o,l;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);let h=null===(l=null!==(o=this.cullBackFaces)&&void 0!==o?o:s)||void 0===l||l?1:2;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(a);let u=r?this._currentRenderTarget?1:2:this._currentRenderTarget?2:1;(this._depthCullingState.frontFace!==u||i)&&(this._depthCullingState.frontFace=u),this._stencilStateComposer.stencilMaterial=n}_applyRenderPassChanges(e,t){var i;let r=this._mustUpdateViewport(e),s=this._mustUpdateScissor(e),n=!!this._stencilStateComposer.enabled&&this._mustUpdateStencilRef(e),a=!!this._alphaState.alphaBlend&&this._mustUpdateBlendColor(e);t?(r&&t.addItem(new WebGPURenderItemViewport(this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w)),s&&t.addItem(new WebGPURenderItemScissor(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),n&&t.addItem(new WebGPURenderItemStencilRef(null!==(i=this._stencilStateComposer.funcRef)&&void 0!==i?i:0)),a&&t.addItem(new WebGPURenderItemBlendColor(this._alphaState._blendConstants.slice()))):(r&&this._applyViewport(e),s&&this._applyScissor(e),n&&this._applyStencilRef(e),a&&this._applyBlendColor(e))}_draw(e,t,i,r,s){var n;let a=this._getCurrentRenderPass(),o=this._getCurrentRenderPassIndex(),l=0===o?this._bundleList:this._bundleListRenderTarget;this.applyStates();let h=this._currentEffect._pipelineContext;if(this.bindUniformBufferBase(this._currentRenderTarget?this._ubInvertY:this._ubDontInvertY,0,WebGPUShaderProcessor.InternalsUBOName),h.uniformBuffer&&(h.uniformBuffer.update(),this.bindUniformBufferBase(h.uniformBuffer.getBuffer(),0,WebGPUShaderProcessor.LeftOvertUBOName)),this._snapshotRendering.play){this._reportDrawCall();return}!this.compatibilityMode&&(this._currentDrawContext.isDirty(this._currentMaterialContext.updateId)||this._currentMaterialContext.isDirty||this._currentMaterialContext.forceBindGroupCreation)&&(this._currentDrawContext.fastBundle=void 0);let u=!this.compatibilityMode&&this._currentDrawContext.fastBundle,c=a;if(u||this._snapshotRendering.record){if(this._applyRenderPassChanges(a,l),!this._snapshotRendering.record){this._counters.numBundleReuseNonCompatMode++,this._currentDrawContext.indirectDrawBuffer&&this._currentDrawContext.setIndirectData(r,s||1,i),l.addBundle(this._currentDrawContext.fastBundle),this._reportDrawCall();return}c=l.getBundleEncoder(this._cacheRenderPipeline.colorFormats,this._depthTextureFormat,this.currentSampleCount),l.numDrawCalls++}let d=0;if(!this._caps.textureFloatLinearFiltering&&this._currentMaterialContext.hasFloatTextures){let e=1;for(let t=0;t<h.shaderProcessingContext.textureNames.length;++t){let i=h.shaderProcessingContext.textureNames[t],r=null===(n=this._currentMaterialContext.textures[i])||void 0===n?void 0:n.texture;(null==r?void 0:r.type)===1&&(d|=e),e<<=1}}this._currentMaterialContext.textureState=d;let p=this._cacheRenderPipeline.getRenderPipeline(t,this._currentEffect,this.currentSampleCount,d),_=this._cacheBindGroups.getBindGroups(h,this._currentDrawContext,this._currentMaterialContext);this._snapshotRendering.record||(this._applyRenderPassChanges(a,this.compatibilityMode?null:l),this.compatibilityMode||(this._counters.numBundleCreationNonCompatMode++,c=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:this.currentSampleCount}))),c.setPipeline(p),this._currentIndexBuffer&&c.setIndexBuffer(this._currentIndexBuffer.underlyingResource,this._currentIndexBuffer.is32Bits?ih.Uint32:ih.Uint16,0);let f=this._cacheRenderPipeline.vertexBuffers;for(let e=0;e<f.length;e++){let t=f[e],i=t.effectiveBuffer;i&&c.setVertexBuffer(e,i.underlyingResource,t._validOffsetRange?0:t.byteOffset)}for(let e=0;e<_.length;e++)c.setBindGroup(e,_[e]);let m=!this.compatibilityMode&&!this._snapshotRendering.record;m&&this._currentDrawContext.indirectDrawBuffer?(this._currentDrawContext.setIndirectData(r,s||1,i),0===e?c.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer,0):c.drawIndirect(this._currentDrawContext.indirectDrawBuffer,0)):0===e?c.drawIndexed(r,s||1,i,0,0):c.draw(r,s||1,i,0),m&&(this._currentDrawContext.fastBundle=c.finish(),l.addBundle(this._currentDrawContext.fastBundle)),this._reportDrawCall()}drawElementsType(e,t,i,r=1){this._draw(0,e,t,i,r)}drawArraysType(e,t,i,r=1){this._currentIndexBuffer=null,this._draw(1,e,t,i,r)}dispose(){var e,t;this._isDisposed=!0,null===(e=this._mainTexture)||void 0===e||e.destroy(),null===(t=this._depthTexture)||void 0===t||t.destroy(),this._device.destroy(),super.dispose()}getRenderWidth(e=!1){var t,i;return!e&&this._currentRenderTarget?this._currentRenderTarget.width:null!==(i=null===(t=this._renderingCanvas)||void 0===t?void 0:t.width)&&void 0!==i?i:0}getRenderHeight(e=!1){var t,i;return!e&&this._currentRenderTarget?this._currentRenderTarget.height:null!==(i=null===(t=this._renderingCanvas)||void 0===t?void 0:t.height)&&void 0!==i?i:0}getError(){return 0}bindSamplers(){}_bindTextureDirectly(){return!1}areAllEffectsReady(){return!0}_executeWhenRenderingStateIsCompiled(e,t){t()}_isRenderingStateCompiled(){return!0}_getUnpackAlignement(){return 1}_unpackFlipY(){}_bindUnboundFramebuffer(){throw"_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead"}_getSamplingParameters(){throw"_getSamplingParameters is not available in WebGPU"}getUniforms(){return[]}setIntArray(){return!1}setIntArray2(){return!1}setIntArray3(){return!1}setIntArray4(){return!1}setArray(){return!1}setArray2(){return!1}setArray3(){return!1}setArray4(){return!1}setMatrices(){return!1}setMatrix3x3(){return!1}setMatrix2x2(){return!1}setFloat(){return!1}setFloat2(){return!1}setFloat3(){return!1}setFloat4(){return!1}};webgpuEngine_WebGPUEngine._GLSLslangDefaultOptions={jsPath:`${rW.w1._DefaultCdnUrl}/glslang/glslang.js`,wasmPath:`${rW.w1._DefaultCdnUrl}/glslang/glslang.wasm`},webgpuEngine_WebGPUEngine.UseTWGSL=!0,webgpuEngine_WebGPUEngine.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e&&(0===e&&!this._alphaState.alphaBlend||0!==e&&this._alphaState.alphaBlend)){if(!t){let t=0===e;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}return}switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0}t||(this.setDepthWrite(e===rq.D.ALPHA_DISABLE),this._cacheRenderPipeline.setDepthWriteEnabled(e===rq.D.ALPHA_DISABLE)),this._alphaMode=e,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)},webgpuEngine_WebGPUEngine.prototype.setAlphaEquation=function(e){rq.D.prototype.setAlphaEquation.call(this,e),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};let WebGPUComputeContext=class WebGPUComputeContext{getBindGroups(e,t,i){if(!i)throw Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(0===this._bindGroups.length){let r=this._bindGroupEntries.length>0;for(let t in e){let s=e[t],n=i[t],a=n.group,o=n.binding,l=s.type,h=s.object,u=s.indexInGroupEntries,c=this._bindGroupEntries[a];switch(c||(c=this._bindGroupEntries[a]=[]),l){case tV.Sampler:void 0!==u&&r?c[u].resource=this._cacheSampler.getSampler(h):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:this._cacheSampler.getSampler(h)}));break;case tV.Texture:case tV.TextureWithoutSampler:{let e=h._texture._hardwareTexture;void 0!==u&&r?(l===tV.Texture&&(c[u++].resource=this._cacheSampler.getSampler(h._texture)),c[u].resource=e.view):(s.indexInGroupEntries=c.length,l===tV.Texture&&c.push({binding:o-1,resource:this._cacheSampler.getSampler(h._texture)}),c.push({binding:o,resource:e.view}));break}case tV.StorageTexture:{let e=h._texture._hardwareTexture;(e.textureAdditionalUsages&tK.StorageBinding)==0&&rT.Y.Error(`computeDispatch: The texture (name=${h.name}, uniqueId=${h.uniqueId}) is not a storage texture!`,50),void 0!==u&&r?c[u].resource=e.viewForWriting:(s.indexInGroupEntries=c.length,c.push({binding:o,resource:e.viewForWriting}));break}case tV.ExternalTexture:{let e=h.underlyingResource;void 0!==u&&r?c[u].resource=this._device.importExternalTexture({source:e}):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:this._device.importExternalTexture({source:e})}));break}case tV.UniformBuffer:case tV.StorageBuffer:{let e=(tV.UniformBuffer,h),t=e.getBuffer(),i=t.underlyingResource;void 0!==u&&r?(c[u].resource.buffer=i,c[u].resource.size=t.capacity):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:{buffer:i,offset:0,size:t.capacity}}))}}}for(let e=0;e<this._bindGroupEntries.length;++e){let i=this._bindGroupEntries[e];if(!i){this._bindGroups[e]=void 0;continue}this._bindGroups[e]=this._device.createBindGroup({layout:t.getBindGroupLayout(e),entries:i})}this._bindGroups.length=this._bindGroupEntries.length}return this._bindGroups}constructor(e,t){this._device=e,this._cacheSampler=t,this.uniqueId=WebGPUComputeContext._Counter++,this._bindGroupEntries=[],this.clear()}clear(){this._bindGroups=[]}};WebGPUComputeContext._Counter=0;let WebGPUComputePipelineContext=class WebGPUComputePipelineContext{get isAsync(){return!1}get isReady(){return!!this.stage}constructor(e){this._name="unnamed",this.engine=e}_getComputeShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.compute}dispose(){}};webgpuEngine_WebGPUEngine.prototype.createComputeContext=function(){return new WebGPUComputeContext(this._device,this._cacheSampler)},webgpuEngine_WebGPUEngine.prototype.createComputeEffect=function(e,t){let i=e.computeElement||e.compute||e.computeToken||e.computeSource||e,r=i+"@"+t.defines;if(this._compiledComputeEffects[r]){let e=this._compiledComputeEffects[r];return t.onCompiled&&e.isReady()&&t.onCompiled(e),e}let s=new ComputeEffect(e,t,this,r);return this._compiledComputeEffects[r]=s,s},webgpuEngine_WebGPUEngine.prototype.createComputePipelineContext=function(){return new WebGPUComputePipelineContext(this)},webgpuEngine_WebGPUEngine.prototype.areAllComputeEffectsReady=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e];if(!t.isReady())return!1}return!0},webgpuEngine_WebGPUEngine.prototype.computeDispatch=function(e,t,i,r,s,n,a){if(this._currentRenderTarget){this._onAfterUnbindFrameBufferObservable.addOnce(()=>{this.computeDispatch(e,t,i,r,s,n,a)});return}let o=e._pipelineContext;o.computePipeline||(o.computePipeline=this._device.createComputePipeline({layout:ie.Auto,compute:o.stage}));let l=this._renderTargetEncoder,h=l.beginComputePass();h.setPipeline(o.computePipeline);let u=t.getBindGroups(i,o.computePipeline,a);for(let e=0;e<u.length;++e){let t=u[e];t&&h.setBindGroup(e,t)}h.dispatchWorkgroups(r,s,n),h.end()},webgpuEngine_WebGPUEngine.prototype.releaseComputeEffects=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},webgpuEngine_WebGPUEngine.prototype._prepareComputePipelineContext=function(e,t,i,r,s){this.dbgShowShaderCode&&(console.log(r),console.log(t)),e.sources={compute:t,rawCompute:i},e.stage=this._createComputePipelineStageDescriptor(t,r,s)},webgpuEngine_WebGPUEngine.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},webgpuEngine_WebGPUEngine.prototype._rebuildComputeEffects=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},webgpuEngine_WebGPUEngine.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},webgpuEngine_WebGPUEngine.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},webgpuEngine_WebGPUEngine.prototype._createDepthStencilCubeTexture=function(e,t){let i=new r5.l(this,r5.S.DepthStencil);i.isCube=!0;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1},t);return i.format=r.generateStencil?13:14,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},webgpuEngine_WebGPUEngine.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d=!1){return this.createCubeTextureBase(e,t,i,!!r,s,n,a,o,l,h,u,c,null,(e,t)=>{let i=t[0].width;this._setCubeMapTextureParams(e,!r),e.format=null!=a?a:-1;let n=this._textureHelper.createGPUTextureForInternalTexture(e,i,i);this._textureHelper.updateCubeTextures(t,n.underlyingResource,i,i,n.format,!1,!1,0,0),r||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},!!d)},webgpuEngine_WebGPUEngine.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},webgpuEngine_WebGPUEngine.prototype._debugPushGroup=function(e,t){if(this._options.enableGPUDebugMarkers){if(0===t||1===t){let i=0===t?this._renderEncoder:this._renderTargetEncoder;i.pushDebugGroup(e)}else this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e])}},webgpuEngine_WebGPUEngine.prototype._debugPopGroup=function(e){if(this._options.enableGPUDebugMarkers){if(0===e||1===e){let t=0===e?this._renderEncoder:this._renderTargetEncoder;t.popDebugGroup()}else this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null])}},webgpuEngine_WebGPUEngine.prototype._debugInsertMarker=function(e,t){if(this._options.enableGPUDebugMarkers){if(0===t||1===t){let i=0===t?this._renderEncoder:this._renderTargetEncoder;i.insertDebugMarker(e)}else this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e])}},webgpuEngine_WebGPUEngine.prototype._debugFlushPendingCommands=function(){for(let e=0;e<this._pendingDebugCommands.length;++e){let[t,i]=this._pendingDebugCommands[e];switch(t){case"push":this._debugPushGroup(i);break;case"pop":this._debugPopGroup();break;case"insert":this._debugInsertMarker(i)}}this._pendingDebugCommands.length=0},webgpuEngine_WebGPUEngine.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let r;r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._bufferManager.setSubData(e,i,r)},webgpuEngine_WebGPUEngine.prototype.updateDynamicVertexBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(e,i,s,0,r)},webgpuEngine_WebGPUEngine.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,n,a){var o;if(!e)return;let l=t.width,h=t.height,u=e._hardwareTexture;(null===(o=e._hardwareTexture)||void 0===o?void 0:o.underlyingResource)||(u=this._textureHelper.createGPUTextureForInternalTexture(e,l,h)),this._textureHelper.updateTexture(t,e,l,h,e.depth,u.format,0,0,i,r,0,0,a),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0};let WebGPUExternalTexture=class WebGPUExternalTexture extends ExternalTexture{constructor(e){super(e)}};function engine_rawTexture_convertRGBtoRGBATextureData(e,t,i,r){let s;let n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r<t;r++)for(let a=0;a<i;a++){let i=(a*t+r)*3,o=(a*t+r)*4;s[o+0]=e[i+0],s[o+1]=e[i+1],s[o+2]=e[i+2],s[o+3]=n}return s}ss.Q.prototype.setExternalTexture=function(e,t){this._engine.setExternalTexture(e,t)},webgpuEngine_WebGPUEngine.prototype.createExternalTexture=function(e){let t=new WebGPUExternalTexture(e);return t},webgpuEngine_WebGPUEngine.prototype.setExternalTexture=function(e,t){if(!t){this._currentMaterialContext.setTexture(e,null);return}this._setInternalTexture(e,t)},webgpuEngine_WebGPUEngine.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t=!1,i){i&&i();let r=e._attachments,s=r.length;this._currentRenderPass&&this._currentRenderPass!==this._mainRenderPassWrapper.renderPass&&this._endRenderTargetRenderPass();for(let i=0;i<s;i++){let r=e.textures[i];!r.generateMipMaps||t||r.isCube||this._generateMipmaps(r)}this._currentRenderTarget=null,this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments),this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)},webgpuEngine_WebGPUEngine.prototype.createMultipleRenderTarget=function(e,t,i){var r,s;let n=!1,a=!0,o=!1,l=!1,h=15,u=1,c=[],d=[],p=[],_=[],f=[],m=[],g=[],v=[],x=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(n=void 0!==t.generateMipMaps&&t.generateMipMaps,a=void 0===t.generateDepthBuffer||t.generateDepthBuffer,o=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,l=void 0!==t.generateDepthTexture&&t.generateDepthTexture,u=t.textureCount||1,h=null!==(r=t.depthTextureFormat)&&void 0!==r?r:15,t.types&&(c=t.types),t.samplingModes&&(d=t.samplingModes),t.useSRGBBuffers&&(p=t.useSRGBBuffers),t.formats&&(_=t.formats),t.targetTypes&&(f=t.targetTypes),t.faceIndex&&(m=t.faceIndex),t.layerIndex&&(g=t.layerIndex),t.layerCounts&&(v=t.layerCounts));let T=e.width||e,S=e.height||e,C=null;(a||o||l)&&(l||(h=a&&o?13:a?14:19),C=x.createDepthStencilTexture(0,!1,o,1,h));let E=[],b=[],y=[];x._generateDepthBuffer=a,x._generateStencilBuffer=o,x._attachments=b,x._defaultAttachments=y;for(let e=0;e<u;e++){let t=d[e]||3,r=c[e]||0,a=_[e]||5,o=(p[e]||!1)&&this._caps.supportSRGBBuffers,l=f[e]||3553,h=null!==(s=v[e])&&void 0!==s?s:1;if((1!==r||this._caps.textureFloatLinearFiltering)&&(2!==r||this._caps.textureHalfFloatLinearFiltering)||(t=1),1!==r||this._caps.textureFloat||(r=0,rT.Y.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),b.push(e+1),y.push(i?e+1:0===e?1:0),-1===l)continue;let u=new r5.l(this,r5.S.MultiRenderTarget);switch(E[e]=u,l){case 34067:u.isCube=!0;break;case 32879:u.is3D=!0,u.baseDepth=u.depth=h;break;case 35866:u.is2DArray=!0,u.baseDepth=u.depth=h}u.baseWidth=T,u.baseHeight=S,u.width=T,u.height=S,u.isReady=!0,u.samples=1,u.generateMipMaps=n,u.samplingMode=t,u.type=r,u._cachedWrapU=0,u._cachedWrapV=0,u._useSRGBBuffer=o,u.format=a,this._internalTexturesCache.push(u),this._textureHelper.createGPUTextureForInternalTexture(u)}return C&&(C.incrementReferences(),E[u]=C,this._internalTexturesCache.push(C)),x.setTextures(E),x.setLayerAndFaceIndices(g,m),x},webgpuEngine_WebGPUEngine.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(!e||!e.textures||e.textures[0].samples===t)return t;let i=e.textures.length;if(0===i)return 1;t=Math.min(t,this.getCaps().maxMSAASamples);for(let t=0;t<i;++t){let i=e.textures[t],r=i._hardwareTexture;null==r||r.releaseMSAATexture()}let r=e._depthStencilTexture===e.textures[i-1];for(let s=0;s<i;++s){let n=e.textures[s];this._textureHelper.createMSAATexture(n,t,!1,s===i-1&&r?0:s),n.samples=t}return e._depthStencilTexture&&!r&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),t},webgpuEngine_WebGPUEngine.prototype.bindAttachments=function(e){0!==e.length&&this._currentRenderTarget&&(this._mrtAttachments=e,this._currentRenderPass&&this._cacheRenderPipeline.setMRTAttachments(e))},webgpuEngine_WebGPUEngine.prototype.buildTextureLayout=function(e){let t=[];for(let i=0;i<e.length;i++)e[i]?t.push(i+1):t.push(0);return t},webgpuEngine_WebGPUEngine.prototype.restoreSingleAttachment=function(){},webgpuEngine_WebGPUEngine.prototype.restoreSingleAttachmentForRenderTarget=function(){},webgpuEngine_WebGPUEngine.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter},webgpuEngine_WebGPUEngine.prototype.captureGPUFrameTime=function(e){this._timestampQuery.enable=e&&!!this._caps.timerQuery},webgpuEngine_WebGPUEngine.prototype.createQuery=function(){return this._occlusionQuery.createQuery()},webgpuEngine_WebGPUEngine.prototype.deleteQuery=function(e){return this._occlusionQuery.deleteQuery(e),this},webgpuEngine_WebGPUEngine.prototype.isQueryResultAvailable=function(e){return this._occlusionQuery.isQueryResultAvailable(e)},webgpuEngine_WebGPUEngine.prototype.getQueryResult=function(e){return this._occlusionQuery.getQueryResult(e)},webgpuEngine_WebGPUEngine.prototype.beginOcclusionQuery=function(e,t){var i;if(this.compatibilityMode){if(this._occlusionQuery.canBeginQuery(t))return null===(i=this._currentRenderPass)||void 0===i||i.beginOcclusionQuery(t),!0}else{let e=this._getCurrentRenderPassIndex(),i=0===e?this._bundleList:this._bundleListRenderTarget;return i.addItem(new WebGPURenderItemBeginOcclusionQuery(t)),!0}return!1},webgpuEngine_WebGPUEngine.prototype.endOcclusionQuery=function(){var e;if(this.compatibilityMode)null===(e=this._currentRenderPass)||void 0===e||e.endOcclusionQuery();else{let e=this._getCurrentRenderPassIndex(),t=0===e?this._bundleList:this._bundleListRenderTarget;t.addItem(new WebGPURenderItemEndOcclusionQuery)}return this},webgpuEngine_WebGPUEngine.prototype.createRawTexture=function(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){let c=new r5.l(this,r5.S.Raw);return c.baseWidth=t,c.baseHeight=i,c.width=t,c.height=i,c.format=r,c.generateMipMaps=s,c.samplingMode=a,c.invertY=n,c._compression=o,c.type=l,c._useSRGBBuffer=u,this._doNotHandleContextLost||(c._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(c,t,i,void 0,h),this.updateRawTexture(c,e,r,n,o,l,u),this._internalTexturesCache.push(c),c},webgpuEngine_WebGPUEngine.prototype.updateRawTexture=function(e,t,i,r,s=null,n=0,a=!1){if(e){if(this._doNotHandleContextLost||(e._bufferView=t,e.invertY=r,e._compression=s,e._useSRGBBuffer=a),t){let s=e._hardwareTexture;4===i&&(t=engine_rawTexture_convertRGBtoRGBATextureData(t,e.width,e.height,n));let a=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(a,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0}},webgpuEngine_WebGPUEngine.prototype.createRawCubeTexture=function(e,t,i,r,s,n,a,o=null){let l=new r5.l(this,r5.S.CubeRaw);return 1!==r||this._caps.textureFloatLinearFiltering?2!==r||this._caps.textureHalfFloatLinearFiltering?1!==r||this._caps.textureFloatRender?2!==r||this._caps.colorBufferFloat||(s=!1,rT.Y.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(s=!1,rT.Y.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(s=!1,a=1,rT.Y.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(s=!1,a=1,rT.Y.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")),l.isCube=!0,l.format=4===i?5:i,l.type=r,l.generateMipMaps=s,l.width=t,l.height=t,l.samplingMode=a,this._doNotHandleContextLost||(l._bufferViewArray=e),l.invertY=n,l._compression=o,l._cachedWrapU=0,l._cachedWrapV=0,this._textureHelper.createGPUTextureForInternalTexture(l),e&&this.updateRawCubeTexture(l,e,i,r,n,o),l.isReady=!0,l},webgpuEngine_WebGPUEngine.prototype.updateRawCubeTexture=function(e,t,i,r,s,n=null){e._bufferViewArray=t,e.invertY=s,e._compression=n;let a=e._hardwareTexture,o=4===i,l=[];for(let i=0;i<t.length;++i){let s=t[i];o&&(s=engine_rawTexture_convertRGBtoRGBATextureData(t[i],e.width,e.height,r)),l.push(new Uint8Array(s.buffer,s.byteOffset,s.byteLength))}this._textureHelper.updateCubeTextures(l,a.underlyingResource,e.width,e.height,a.format,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0},webgpuEngine_WebGPUEngine.prototype.createRawCubeTextureFromUrl=function(e,t,i,r,s,n,a,o,l=null,h=null,u=3,c=!1){let d=this.createRawCubeTexture(null,i,r,s,!n,c,u,null);null==t||t.addPendingData(d),d.url=e,this._internalTexturesCache.push(d);let internalCallback=e=>{let i=d.width,n=a(e);if(!n)return;let h=[0,2,4,1,3,5];if(o){let e=4===r,t=o(n),a=d._hardwareTexture,l=[0,1,2,3,4,5];for(let r=0;r<t.length;r++){let n=i>>r,o=[];for(let i=0;i<6;i++){let a=t[r][l[i]];e&&(a=engine_rawTexture_convertRGBtoRGBATextureData(a,n,n,s)),o.push(new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}this._textureHelper.updateCubeTextures(o,a.underlyingResource,n,n,a.format,c,!1,0,0)}}else{let e=[];for(let t=0;t<6;t++)e.push(n[h[t]]);this.updateRawCubeTexture(d,e,r,s,c)}d.isReady=!0,null==t||t.removePendingData(d),l&&l()};return this._loadFile(e,e=>{internalCallback(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)}),d},webgpuEngine_WebGPUEngine.prototype.createRawTexture3D=function(e,t,i,r,s,n,a,o,l=null,h=0,u=0){let c=r5.S.Raw3D,d=new r5.l(this,c);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=n,d.samplingMode=o,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,u),this.updateRawTexture3D(d,e,s,a,l,h),this._internalTexturesCache.push(d),d},webgpuEngine_WebGPUEngine.prototype.updateRawTexture3D=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture,a=4===i;a&&(t=engine_rawTexture_convertRGBtoRGBATextureData(t,e.width,e.height,n));let o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},webgpuEngine_WebGPUEngine.prototype.createRawTexture2DArray=function(e,t,i,r,s,n,a,o,l=null,h=0,u=0){let c=r5.S.Raw2DArray,d=new r5.l(this,c);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=n,d.samplingMode=o,d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,r,u),this.updateRawTexture2DArray(d,e,s,a,l,h),this._internalTexturesCache.push(d),d},webgpuEngine_WebGPUEngine.prototype.updateRawTexture2DArray=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture,a=4===i;a&&(t=engine_rawTexture_convertRGBtoRGBATextureData(t,e.width,e.height,n));let o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},webgpuEngine_WebGPUEngine.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){let u=e._hardwareTexture;return a&&this.flushFramebuffer(),this._textureHelper.readPixels(u.underlyingResource,l,h,t,i,u.format,r,s,n,o)},webgpuEngine_WebGPUEngine.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};let WebGPURenderTargetWrapper=class WebGPURenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{};function IsExternalTexture(e){return!!e&&void 0!==e.underlyingResource}webgpuEngine_WebGPUEngine.prototype._createHardwareRenderTargetWrapper=function(e,t,i){let r=new WebGPURenderTargetWrapper(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},webgpuEngine_WebGPUEngine.prototype.createRenderTargetTexture=function(e,t){var i,r,s;let n=this._createHardwareRenderTargetWrapper(!1,!1,e),a={};void 0!==t&&"object"==typeof t?(a.generateMipMaps=t.generateMipMaps,a.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,a.generateStencilBuffer=a.generateDepthBuffer&&t.generateStencilBuffer,a.samplingMode=void 0===t.samplingMode?3:t.samplingMode,a.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,a.noColorAttachment=!!t.noColorAttachment,a.samples=t.samples,a.label=t.label):(a.generateMipMaps=t,a.generateDepthBuffer=!0,a.generateStencilBuffer=!1,a.samplingMode=3,a.creationFlags=0,a.noColorAttachment=!1);let o=a.noColorAttachment?null:this._createInternalTexture(e,t,!0,r5.S.RenderTarget);return n.label=null!==(r=a.label)&&void 0!==r?r:"RenderTargetWrapper",n._samples=null!==(s=a.samples)&&void 0!==s?s:1,n._generateDepthBuffer=a.generateDepthBuffer,n._generateStencilBuffer=!!a.generateStencilBuffer,n.setTextures(o),(n._generateDepthBuffer||n._generateStencilBuffer)&&n.createDepthStencilTexture(0,this._caps.textureFloatLinearFiltering&&(void 0===a.samplingMode||2===a.samplingMode||2===a.samplingMode||3===a.samplingMode||3===a.samplingMode||5===a.samplingMode||6===a.samplingMode||7===a.samplingMode||11===a.samplingMode),n._generateStencilBuffer,n.samples,a.generateStencilBuffer?13:14,a.label?a.label+"-DepthStencil":void 0),o&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!a.generateMipMaps&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o,void 0,void 0,void 0,a.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!a.generateMipMaps&&(o.generateMipMaps=!1)),n},webgpuEngine_WebGPUEngine.prototype._createDepthStencilTexture=function(e,t){let i=new r5.l(this,r5.S.DepthStencil);i.label=t.label;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14},t);return i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},webgpuEngine_WebGPUEngine.prototype._setupDepthStencilTexture=function(e,t,i,r,s,n=1){let a=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=1,e._comparisonFunction=s,e._cachedWrapU=0,e._cachedWrapV=0},webgpuEngine_WebGPUEngine.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},webgpuEngine_WebGPUEngine.prototype.createRenderTargetCubeTexture=function(e,t){var i;let r=this._createHardwareRenderTargetWrapper(!1,!0,e),s=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},t);s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,r.label=null!==(i=s.label)&&void 0!==i?i:"RenderTargetWrapper",r._generateDepthBuffer=s.generateDepthBuffer,r._generateStencilBuffer=s.generateStencilBuffer;let n=new r5.l(this,r5.S.RenderTarget);return n.width=e,n.height=e,n.depth=0,n.isReady=!0,n.isCube=!0,n.samples=s.samples,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),r.setTextures(n),(r._generateDepthBuffer||r._generateStencilBuffer)&&r.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,r._generateStencilBuffer,r.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(n.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(n),t&&t.createMipMaps&&!s.generateMipMaps&&(n.generateMipMaps=!1),r},ss.Q.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},webgpuEngine_WebGPUEngine.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},ss.Q.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},webgpuEngine_WebGPUEngine.prototype.createStorageBuffer=function(e,t,i){return this._createBuffer(e,32|t,i)},webgpuEngine_WebGPUEngine.prototype.updateStorageBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(e,i,s,0,r)},webgpuEngine_WebGPUEngine.prototype.readFromStorageBuffer=function(e,t,i,r){i=i||e.capacity;let s=this._bufferManager.createRawBuffer(i,tY.MapRead|tY.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderTargetEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,s,0,i),new Promise((e,t)=>{this.onEndFrameObservable.addOnce(()=>{s.mapAsync(tj.Read,0,i).then(()=>{let t=s.getMappedRange(0,i),n=r;if(void 0===n)(n=new Uint8Array(i)).set(new Uint8Array(t));else{let e=n.constructor;(n=new e(n.buffer)).set(new e(t))}s.unmap(),this._bufferManager.releaseBuffer(s),e(n)},e=>t(e))})})},webgpuEngine_WebGPUEngine.prototype.setStorageBuffer=function(e,t){var i,r;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(r=null==t?void 0:t.getBuffer())&&void 0!==r?r:null)},webgpuEngine_WebGPUEngine.prototype.createUniformBuffer=function(e,t){let i;i=e instanceof Array?new Float32Array(e):e;let r=this._bufferManager.createBuffer(i,tY.Uniform|tY.CopyDst,t);return r},webgpuEngine_WebGPUEngine.prototype.createDynamicUniformBuffer=function(e,t){return this.createUniformBuffer(e,t)},webgpuEngine_WebGPUEngine.prototype.updateUniformBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Float32Array?t:new Float32Array(t)).byteLength:s=t instanceof Float32Array?t:new Float32Array(t),this._bufferManager.setSubData(e,i,s,0,r)},webgpuEngine_WebGPUEngine.prototype.bindUniformBufferBase=function(e,t,i){this._currentDrawContext.setBuffer(i,e)},webgpuEngine_WebGPUEngine.prototype.bindUniformBlock=function(){},webgpuEngine_WebGPUEngine.prototype.updateVideoTexture=function(e,t,i){var r;if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;(null===(r=e._hardwareTexture)||void 0===r?void 0:r.underlyingResource)||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),IsExternalTexture(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0):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})},i(856);let ClipboardEventTypes=class ClipboardEventTypes{};ClipboardEventTypes.COPY=1,ClipboardEventTypes.CUT=2,ClipboardEventTypes.PASTE=3;let planeRotationGizmo_PlaneRotationGizmo=class planeRotationGizmo_PlaneRotationGizmo extends gizmo_Gizmo{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=rg.Wo.Gray(),i=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer,r=32,s=null,n=!1,a=1){var o;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new rf.y$,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new rm.P,this._parent=s,this._coloredMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new rg.Wo(.1,.1,.1)),this._hoverMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=rg.Wo.Yellow(),this._disableMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._disableMaterial.diffuseColor=rg.Wo.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new rV.Kj("",i.utilityLayerScene);let{rotationMesh:l,collider:h}=this._createGizmoMesh(this._gizmoMesh,a,r);this._rotationDisplayPlane=planeBuilder_CreatePlane("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),ss.Q.ShadersStore.rotationGizmoVertexShader=planeRotationGizmo_PlaneRotationGizmo._RotationGizmoVertexShader,ss.Q.ShadersStore.rotationGizmoFragmentShader=planeRotationGizmo_PlaneRotationGizmo._RotationGizmoFragmentShader,this._rotationShaderMaterial=new shaderMaterial_ShaderMaterial("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,gizmo_Gizmo.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new pointerDragBehavior_PointerDragBehavior({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);let u=new rm.P,c=new rm.y3,d=new rm.P,p=new rm.P;this.dragBehavior.onDragStartObservable.add(e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(c),rm.P.TransformCoordinatesToRef(e.dragPlanePoint,c,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});let _={snapDistance:0},f=0,m=new rm.y3,g=new rm._f;this.dragBehavior.onDragObservable.add(t=>{if(this.attachedNode){let r=new rm.P(1,1,1),s=new rm._f(0,0,0,1),n=new rm.P(0,0,0);this.attachedNode.getWorldMatrix().decompose(r,s,n);let a=Math.abs(Math.abs(r.x)-Math.abs(r.y))<=rw.kn&&Math.abs(Math.abs(r.x)-Math.abs(r.z))<=rw.kn;if(!a&&this.updateGizmoRotationToMatchAttachedMesh){rT.Y.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}s.normalize();let o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,l=t.dragPlanePoint.subtract(o).normalize(),h=u.subtract(o).normalize(),v=rm.P.Cross(l,h),x=rm.P.Dot(l,h),T=Math.atan2(v.length(),x)*this.sensitivity;d.copyFrom(e),p.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(c),p=rm.P.TransformCoordinates(d,c));let S=!1;if(i.utilityLayerScene.activeCamera){let e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();rm.P.Dot(e,p)>0&&(d.scaleInPlace(-1),p.scaleInPlace(-1),S=!0)}let C=rm.P.Dot(p,v)>0;C&&(T=-T),rm.jp.Vector3[0].set(T,0,0),this.dragBehavior.validateDrag(rm.jp.Vector3[0])||(T=0);let E=!1;if(0!=this.snapDistance){if(Math.abs(f+=T)>this.snapDistance){let e=Math.floor(Math.abs(f)/this.snapDistance);f<0&&(e*=-1),f%=this.snapDistance,T=this.snapDistance*e,E=!0}else T=0}let b=Math.sin(T/2);if(g.set(d.x*b,d.y*b,d.z*b,Math.cos(T/2)),m.determinant()>0){let e=new rm.P;g.toEulerAnglesToRef(e),rm._f.RotationYawPitchRollToRef(e.y,-e.x,-e.z,g)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(g,s),s.normalize(),rm.y3.ComposeToRef(r,s,n,this.attachedNode.getWorldMatrix());else{g.toRotationMatrix(rm.jp.Matrix[0]);let e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(rm.jp.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),E&&(_.snapDistance=T,this.onSnapObservable.notifyObservers(_)),this._angles.y+=T,this.angle+=S?-T:T,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});let v=i._getSharedGizmoLight();v.includedOnlyMeshes=v.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));let x={colliderMeshes:[h],gizmoMeshes:[l],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(o=this._parent)||void 0===o||o.addToAxisCache(this._gizmoMesh,x),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(e=>{var t;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle,this._isHovered=-1!=x.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh),!this._parent)){let e=x.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(x.gizmoMeshes,e)}}),this.dragBehavior.onEnabledObservable.add(e=>{this._setGizmoMeshMaterial(x.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){let r=CreateTorus("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;let s=CreateTorus("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(s,gizmo_Gizmo.PreserveScaling),e.addChild(r,gizmo_Gizmo.PreserveScaling),{rotationMesh:s,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}};planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle=9*Math.PI/20,planeRotationGizmo_PlaneRotationGizmo._RotationGizmoVertexShader=` + precision highp float; + attribute vec3 position; + attribute vec2 uv; + uniform mat4 worldViewProjection; + varying vec3 vPosition; + varying vec2 vUV; + void main(void) { + gl_Position = worldViewProjection * vec4(position, 1.0); + vUV = uv; + }`,planeRotationGizmo_PlaneRotationGizmo._RotationGizmoFragmentShader=` + precision highp float; + varying vec2 vUV; + varying vec3 vPosition; + uniform vec3 angles; + #define twopi 6.283185307 + void main(void) { + vec2 uv = vUV - vec2(0.5); + float angle = atan(uv.y, uv.x) + 3.141592; + float delta = gl_FrontFacing ? angles.y : -angles.y; + float begin = angles.x - delta * angles.z; + float start = (begin < (begin + delta)) ? begin : (begin + delta); + float end = (begin > (begin + delta)) ? begin : (begin + delta); + float len = sqrt(dot(uv,uv)); + float opacity = 1. - step(0.5, len); + + float base = abs(floor(start / twopi)) * twopi; + start += base; + end += base; + + float intensity = 0.; + for (int i = 0; i < 5; i++) + { + intensity += max(step(start, angle) - step(end, angle), 0.); + angle += twopi; + } + gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity; + }`;let ShadowLight=class ShadowLight extends light_Light{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=rm.P.Zero()),rm.P.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=rm.P.Zero()),rm.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=rm.P.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();let e=rm.P.Cross(this.direction,rL.RD.Y),t=rm.P.Cross(e,this.direction);return rm.P.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=rm.P.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?this._currentRenderId=this.getScene().getRenderId():(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=rm.y3.Identity()),rm.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,rH.gn)([(0,rb.hd)()],ShadowLight.prototype,"position",null),(0,rH.gn)([(0,rb.hd)()],ShadowLight.prototype,"direction",null),(0,rH.gn)([(0,rb.qC)()],ShadowLight.prototype,"shadowMinZ",null),(0,rH.gn)([(0,rb.qC)()],ShadowLight.prototype,"shadowMaxZ",null),ry.N.AddNodeConstructor("Light_Type_1",(e,t)=>()=>new DirectionalLight(e,rm.P.Zero(),t));let DirectionalLight=class DirectionalLight extends ShadowLight{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 light_Light.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){let t=this.getScene().activeCamera;t&&rm.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){let r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){let e=rm.P.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let r=Number.MAX_VALUE,s=-Number.MAX_VALUE;for(let n=0;n<i.length;n++){let a=i[n];if(!a)continue;let o=a.getBoundingInfo(),l=o.boundingBox;for(let i=0;i<l.vectorsWorld.length;i++)rm.P.TransformCoordinatesToRef(l.vectorsWorld[i],t,e),e.x<this._orthoLeft&&(this._orthoLeft=e.x),e.y<this._orthoBottom&&(this._orthoBottom=e.y),e.x>this._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.z<r&&(r=e.z),e.z>s&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=r,this._shadowMaxZ=s)}let s=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;rm.y3.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?o:a,l?a:o,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t):this._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):e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this}getDepthMinZ(e){let t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){let t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}};function CreateHemisphere(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);let r=sphereBuilder_CreateSphere("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=discBuilder_CreateDisc("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=r;let n=rV.Kj.MergeMeshes([s,r],!0);return n.name=e,n}(0,rH.gn)([(0,rb.qC)()],DirectionalLight.prototype,"shadowFrustumSize",null),(0,rH.gn)([(0,rb.qC)()],DirectionalLight.prototype,"shadowOrthoScale",null),(0,rH.gn)([(0,rb.qC)()],DirectionalLight.prototype,"autoUpdateExtends",void 0),(0,rH.gn)([(0,rb.qC)()],DirectionalLight.prototype,"autoCalcShadowZBounds",void 0),(0,rH.gn)([(0,rb.qC)("orthoLeft")],DirectionalLight.prototype,"_orthoLeft",void 0),(0,rH.gn)([(0,rb.qC)("orthoRight")],DirectionalLight.prototype,"_orthoRight",void 0),(0,rH.gn)([(0,rb.qC)("orthoTop")],DirectionalLight.prototype,"_orthoTop",void 0),(0,rH.gn)([(0,rb.qC)("orthoBottom")],DirectionalLight.prototype,"_orthoBottom",void 0),rV.Kj.CreateHemisphere=(e,t,i,r)=>CreateHemisphere(e,{segments:t,diameter:i},r),ry.N.AddNodeConstructor("Light_Type_2",(e,t)=>()=>new SpotLight(e,rm.P.Zero(),rm.P.Zero(),0,0,t));let SpotLight=class SpotLight extends ShadowLight{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()&&(SpotLight._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):SpotLight._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()})))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,r,s,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=rm.y3.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=rm.P.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=rm.P.Zero(),this._projectionTextureViewLightMatrix=rm.y3.Zero(),this._projectionTextureProjectionLightMatrix=rm.y3.Zero(),this._projectionTextureScalingMatrix=rm.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=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return light_Light.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;let s=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;rm.y3.PerspectiveFovLHToRef(s,1,o?a:n,o?n:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.direction,this._projectionTextureViewTargetVector),rm.y3.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;let e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);rm.y3.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof texture_Texture){let e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;rm.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=rm.P.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=rm.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()?rm.P.Normalize(this.transformedDirection):rm.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){let 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){let 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,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"angle",null),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"innerAngle",null),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"shadowAngleScale",null),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"exponent",void 0),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"projectionTextureLightNear",null),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"projectionTextureLightFar",null),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"projectionTextureUpDirection",null),(0,rH.gn)([(0,rb.oU)("projectedLightTexture")],SpotLight.prototype,"_projectionTexture",void 0);let LightGizmo=class LightGizmo extends gizmo_Gizmo{constructor(e=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer){super(e),this._cachedPosition=new rm.P,this._cachedForward=new rm.P(0,0,1),this._pointerObserver=null,this.onClickedObservable=new rf.y$,this._light=null,this.attachedMesh=new rG.x("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new rk.Y("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new standardMaterial_StandardMaterial("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new rg.Wo(.5,.5,.5),this._material.specularColor=new rg.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))},r8.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(),e instanceof HemisphericLight?this._lightMesh=LightGizmo._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof DirectionalLight?this._lightMesh=LightGizmo._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof SpotLight?this._lightMesh=LightGizmo._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=LightGizmo._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._lightMesh.parent=this._rootMesh;let t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new rm._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);let t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(rm.jp.Vector3[0]),e=rm.jp.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position){if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{let e=this.attachedMesh.position;this._light.position=new rm.P(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}}if(this._light.direction){let e=this._getMeshForward();rm.P.DistanceSquared(e,this._cachedForward)>1e-4?(this._light.direction=new rm.P(e.x,e.y,e.z),this._cachedForward.copyFrom(e)):rm.P.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){let t=new rV.Kj("hemisphereLight",e),i=CreateHemisphere(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;let r=this._CreateLightLines(3,e);return r.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){let t=new rV.Kj("pointLight",e),i=sphereBuilder_CreateSphere(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;let r=this._CreateLightLines(5,e);return r.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){let t=new rV.Kj("spotLight",e),i=sphereBuilder_CreateSphere(t.name,{segments:10,diameter:1},e);i.parent=t;let r=CreateHemisphere(t.name,{segments:10,diameter:2},e);r.parent=t,r.rotation.x=-Math.PI/2;let s=this._CreateLightLines(2,e);return s.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){let t=new rV.Kj("directionalLight",e),i=new rV.Kj(t.name,e);i.parent=t;let r=sphereBuilder_CreateSphere(t.name,{diameter:1.2,segments:10},e);r.parent=i;let s=cylinderBuilder_CreateCylinder(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=1.25;let a=s.clone(t.name);a.scaling.y=.5,a.position.x+=-1.25;let o=cylinderBuilder_CreateCylinder(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,(n=o.clone(t.name)).position.y=1.5,n.position.x+=1.25,(a=o.clone(t.name)).position.y=1.5,a.position.x+=-1.25,i.scaling.scaleInPlace(LightGizmo._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}};LightGizmo._Scale=.007,LightGizmo._CreateLightLines=(e,t)=>{let i=new rV.Kj("root",t);i.rotation.x=Math.PI/2;let r=new rV.Kj("linePivot",t);r.parent=i;let s=cylinderBuilder_CreateCylinder("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=r,e<2)return r;for(let e=0;e<4;e++){let t=r.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<5)return i;let n=r.clone("linePivotClone");return n.rotation.z=Math.PI,i};let CameraGizmo=class CameraGizmo extends gizmo_Gizmo{constructor(e=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer){super(e),this._pointerObserver=null,this.onClickedObservable=new rf.y$,this._camera=null,this._invProjection=new rm.y3,this._material=new standardMaterial_StandardMaterial("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new rg.Wo(.5,.5,.5),this._material.specularColor=new rg.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))},r8.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=CameraGizmo._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraLinesMesh=CameraGizmo._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;let 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){let t=new rV.Kj("rootCameraGizmo",e),i=new rV.Kj(t.name,e);i.parent=t;let r=boxBuilder_CreateBox(t.name,{width:1,height:.8,depth:.5},e);r.parent=i;let s=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;let n=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);n.parent=i,n.position.y=.5,n.position.x=.4,n.rotation.x=.5*Math.PI;let a=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return a.parent=i,a.position.y=0,a.position.x=.6,a.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(CameraGizmo._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e){let t=new rV.Kj("rootCameraGizmo",e),i=new rV.Kj(t.name,e);i.parent=t;for(let t=0;t<4;t+=2)for(let r=0;r<4;r+=2){let s=linesBuilder_CreateLines("lines",{points:[new rm.P(-1+r,-1+t,-1),new rm.P(-1+r,-1+t,1)]},e);s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=linesBuilder_CreateLines("lines",{points:[new rm.P(-1,-1+r,-1+t),new rm.P(1,-1+r,-1+t)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=linesBuilder_CreateLines("lines",{points:[new rm.P(-1+r,-1,-1+t),new rm.P(-1+r,1,-1+t)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1}return t}};CameraGizmo._Scale=.05,s_.v.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";let a4=`vec4 pack(float depth) +{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} +float unpack(vec4 color) +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;s_.v.IncludesShadersStore.packingFunctions=a4;let a5=`#ifdef DOF +factor=sampleCoC(sampleCoord{X}); +computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; +#else +blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; +#endif +`;s_.v.IncludesShadersStore.kernelBlurFragment=a5;let a6=`#ifdef DOF +factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_DEP_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; +#else +blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; +#endif +`;s_.v.IncludesShadersStore.kernelBlurFragment2=a6;let a8=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; +#ifdef DOF +uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } +#endif +#include<kernelBlurVaryingDeclaration>[0..varyingCount] +#ifdef PACKEDFLOAT +#include<packingFunctions> +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float computedWeight=0.0; +#ifdef PACKEDFLOAT +float blend=0.; +#else +vec4 blend=vec4(0.); +#endif +#ifdef DOF +float sumOfWeights=CENTER_WEIGHT; +float factor=0.0; +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; +#else +blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; +#endif +#endif +#include<kernelBlurFragment>[0..varyingCount] +#include<kernelBlurFragment2>[0..depCount] +#ifdef PACKEDFLOAT +gl_FragColor=pack(blend); +#else +gl_FragColor=blend; +#endif +#ifdef DOF +gl_FragColor/=sumOfWeights; +#endif +}`;s_.v.ShadersStore.kernelBlurPixelShader=a8,s_.v.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";let a7=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; +#include<kernelBlurVaryingDeclaration>[0..varyingCount] +const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +sampleCenter=(position*madd+madd); +#include<kernelBlurVertex>[0..varyingCount] +gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.kernelBlurVertexShader=a7;let BlurPostProcess=class BlurPostProcess extends postProcess_PostProcess{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,r,s,n=texture_Texture.BILINEAR_SAMPLINGMODE,a,o,l=0,h="",u=!1,c=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],r,s,n,a,o,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,c),this._blockCompilation=u,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,r,s,n){this._updateParameters(s,n)}_updateParameters(e,t){let i=this._kernel,r=(i-1)/2,s=[],n=[],a=0;for(let e=0;e<i;e++){let t=e/(i-1),o=this._gaussianWeight(2*t-1);s[e]=e-r,n[e]=o,a+=o}for(let e=0;e<n.length;e++)n[e]/=a;let o=[],l=[],h=[];for(let e=0;e<=r;e+=2){let t=Math.min(e+1,Math.floor(r)),i=e===t;if(i)h.push({o:s[e],w:n[e]});else{let i=t===r,a=n[e]+n[t]*(i?.5:1),o=s[e]+1/(1+n[e]/n[t]);0===o?(h.push({o:s[e],w:n[e]}),h.push({o:s[e+1],w:n[e+1]})):(h.push({o:o,w:a}),h.push({o:-o,w:a}))}}for(let e=0;e<h.length;e++)l[e]=h[e].o,o[e]=h[e].w;s=l,n=o;let u=this.getEngine().getCaps().maxVaryingVectors,c=Math.max(u,0)-1,d=Math.min(s.length,c),p="";p+=this._staticDefines,-1!=this._staticDefines.indexOf("DOF")&&(p+=`#define CENTER_WEIGHT ${this._glslFloat(n[d-1])} +`,d--);for(let e=0;e<d;e++)p+=`#define KERNEL_OFFSET${e} ${this._glslFloat(s[e])} +#define KERNEL_WEIGHT${e} ${this._glslFloat(n[e])} +`;let _=0;for(let e=c;e<s.length;e++)p+=`#define KERNEL_DEP_OFFSET${_} ${this._glslFloat(s[e])} +#define KERNEL_DEP_WEIGHT${_} ${this._glslFloat(n[e])} +`,_++;this.packedFloat&&(p+="#define PACKEDFLOAT 1"),this._blockCompilation=!1,super.updateEffect(p,null,null,{varyingCount:d,depCount:_},e,t)}_nearestBestKernel(e){let t=Math.round(e);for(let e of[t,t-1,t+1,t-2,t+2])if(e%2!=0&&Math.floor(e/2)%2==0&&e>0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){let t=1/3;return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(-(e*e/(2*t*t)))}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new BlurPostProcess(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}};(0,rH.gn)([(0,rb.qC)("kernel")],BlurPostProcess.prototype,"_kernel",void 0),(0,rH.gn)([(0,rb.qC)("packedFloat")],BlurPostProcess.prototype,"_packedFloat",void 0),(0,rH.gn)([(0,rb.QC)()],BlurPostProcess.prototype,"direction",void 0),(0,rv.H)("BABYLON.BlurPostProcess",BlurPostProcess);let MirrorTexture=class MirrorTexture extends renderTargetTexture_RenderTargetTexture{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(){let 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(){let e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,s=0,n=texture_Texture.BILINEAR_SAMPLINGMODE,a=!0){let o;if(super(e,t,i,r,!0,s,!1,n,a),this.mirrorPlane=new r2.J(0,1,0,1),this._transformMatrix=rm.y3.Zero(),this._mirrorMatrix=rm.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()});let l=i.getEngine();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()),rm.y3.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),o=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=rm.P.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=o})}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){let e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new BlurPostProcess("horizontal blur",new rm.FM(1,0),this._blurKernelX,this._blurRatio,null,texture_Texture.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 BlurPostProcess("vertical blur",new rm.FM(0,1),this._blurKernelY,this._blurRatio,null,texture_Texture.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(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new MirrorTexture(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;let e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();let t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}};texture_Texture._CreateMirror=(e,t,i,r)=>new MirrorTexture(e,t,i,r);let cubeTexture_CubeTexture=class cubeTexture_CubeTexture extends baseTexture_BaseTexture{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(rm.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 r="";return e.forEach(e=>r+=e),new cubeTexture_CubeTexture(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){let s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;let n=new cubeTexture_CubeTexture(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=s,n}constructor(e,t,i=null,r=!1,s=null,n=null,a=null,o=5,l=!1,h=null,u=!1,c=.8,d=0,p,_){var f;if(super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new rf.y$,this.boundingBoxPosition=rm.P.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new rm.y3,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this._format=o,this.isCube=!0,this._textureMatrix=rm.y3.Identity(),this._createPolynomials=u,this.coordinatesMode=texture_Texture.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=h,this._loaderOptions=p,this._useSRGBBuffer=_,this._lodScale=c,this._lodOffset=d,!e&&!s)return;this.updateURL(e,h,n,l,a,i,null===(f=this.getScene())||void 0===f?void 0:f.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,r=!1,s=null,n=null,a=!1,o=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);let l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),u=0===h.indexOf(".dds"),c=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(c?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(d||c||u||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let t=0;t<n.length;t++)this._files.push(e+n[t]);this._extensions=n}a?(this.delayLoadState=4,this._delayedOnLoad=i,this._delayedOnError=s):this._loadTexture(i,s)}delayLoad(e){4===this.delayLoadState&&(e&&(this._forcedExtension=e),this.delayLoadState=1,this._loadTexture(this._delayedOnLoad,this._delayedOnError))}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t,i;if(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))),this._textureMatrix=e,!(null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem)))return;let r=rm.jp.Vector3[0],s=rm.jp.Quaternion[0],n=rm.jp.Vector3[1];this._textureMatrix.decompose(r,s,n),s.z*=-1,s.w*=-1,rm.y3.ComposeToRef(r,s,n,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;let r=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);let onLoadProcessing=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},errorHandler=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),texture_Texture.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?rW.w1.SetImmediate(()=>onLoadProcessing()):this._texture.onLoadedObservable.add(()=>onLoadProcessing()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,r,this._lodScale,this._lodOffset,e,errorHandler,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,r,this._files,this._noMipmap,e,errorHandler,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){let r=rb.p4.Parse(()=>{var r;let s=!1;return e.prefiltered&&(s=e.prefiltered),new cubeTexture_CubeTexture(i+(null!==(r=e.url)&&void 0!==r?r:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=rm.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=rm.P.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t<e.animations.length;t++){let i=e.animations[t],s=(0,rv.q)("BABYLON.Animation");s&&r.animations.push(s.Parse(i))}return r}clone(){let e=0,t=rb.p4.Clone(()=>{let t=new cubeTexture_CubeTexture(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t},this);return t.uniqueId=e,t}};(0,rH.gn)([(0,rb.qC)()],cubeTexture_CubeTexture.prototype,"url",void 0),(0,rH.gn)([(0,rb.hd)()],cubeTexture_CubeTexture.prototype,"boundingBoxPosition",void 0),(0,rH.gn)([(0,rb.hd)()],cubeTexture_CubeTexture.prototype,"boundingBoxSize",null),(0,rH.gn)([(0,rb.qC)("rotationY")],cubeTexture_CubeTexture.prototype,"rotationY",null),(0,rH.gn)([(0,rb.qC)("files")],cubeTexture_CubeTexture.prototype,"_files",void 0),(0,rH.gn)([(0,rb.qC)("forcedExtension")],cubeTexture_CubeTexture.prototype,"_forcedExtension",void 0),(0,rH.gn)([(0,rb.qC)("extensions")],cubeTexture_CubeTexture.prototype,"_extensions",void 0),(0,rH.gn)([(0,rb.oQ)("textureMatrix")],cubeTexture_CubeTexture.prototype,"_textureMatrix",void 0),(0,rH.gn)([(0,rb.oQ)("textureMatrixRefraction")],cubeTexture_CubeTexture.prototype,"_textureMatrixRefraction",void 0),texture_Texture._CubeTextureParser=cubeTexture_CubeTexture.Parse,(0,rv.H)("BABYLON.CubeTexture",cubeTexture_CubeTexture);let a9=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +uniform vec4 vPrimaryColorShadow; +#endif +uniform float shadowLevel;uniform float alpha; +#ifdef DIFFUSE +uniform vec2 vDiffuseInfos; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; +#endif +#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) +uniform vec3 vBackgroundCenter; +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 vReflectionControl; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) +uniform mat4 view; +#endif +#ifdef PROJECTED_GROUND +uniform vec2 projectedGroundInfos; +#endif +`;s_.v.IncludesShadersStore.backgroundFragmentDeclaration=a9;let oe=`layout(std140,column_major) uniform;uniform Material +{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;}; +#include<sceneUboDeclaration> +`;s_.v.IncludesShadersStore.backgroundUboDeclaration=oe;let ot=`#ifdef TEXTURELODSUPPORT +#extension GL_EXT_shader_texture_lod : enable +#endif +precision highp float; +#include<__decl__backgroundFragment> +#include<helperFunctions> +varying vec3 vPositionW; +#ifdef MAINUV1 +varying vec2 vMainUV1; +#endif +#ifdef MAINUV2 +varying vec2 vMainUV2; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef DIFFUSE +#if DIFFUSEDIRECTUV==1 +#define vDiffuseUV vMainUV1 +#elif DIFFUSEDIRECTUV==2 +#define vDiffuseUV vMainUV2 +#else +varying vec2 vDiffuseUV; +#endif +uniform sampler2D diffuseSampler; +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +#define sampleReflection(s,c) textureCube(s,c) +uniform samplerCube reflectionSampler; +#ifdef TEXTURELODSUPPORT +#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#else +#define sampleReflection(s,c) texture2D(s,c) +uniform sampler2D reflectionSampler; +#ifdef TEXTURELODSUPPORT +#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include<reflectionFunction> +#endif +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE; +#endif +#ifndef SHADOWONLY +#define SHADOWONLY; +#endif +#include<imageProcessingDeclaration> +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include<lightsFragmentFunctions> +#include<shadowsFragmentFunctions> +#include<imageProcessingFunctions> +#include<clipPlaneFragmentDeclaration> +#include<fogFragmentDeclaration> +#ifdef REFLECTIONFRESNEL +#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) +{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#ifdef PROJECTED_GROUND +float diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; } +vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)<r*r) ? t : 1e6;} +float sphereIntersect(vec3 ro,vec3 rd,float ra) {float b=dot(ro,rd);float c=dot(ro,ro)-ra*ra;float h=b*b-c;if(h<0.0) { return -1.0; } +h=sqrt(h);return-b+h;} +vec3 project(vec3 viewDirectionW,vec3 eyePosition) {float radius=projectedGroundInfos.x;float height=projectedGroundInfos.y;vec3 camDir=-viewDirectionW;float skySphereDistance=sphereIntersect(eyePosition,camDir,radius);vec3 skySpherePositionW=eyePosition+camDir*skySphereDistance;vec3 p=normalize(skySpherePositionW);eyePosition.y-=height;float sIntersection=sphereIntersect(eyePosition,p,radius);vec3 h=vec3(0.0,-height,0.0);float dIntersection=diskIntersectWithBackFaceCulling(eyePosition,p,h,radius);p=(eyePosition+min(sIntersection,dIntersection)*p);return p;} +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(0.0,1.0,0.0); +#endif +float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.; +#include<lightFragment>[0..maxSimultaneousLights] +#ifdef SHADOWINUSE +globalShadow/=shadowLightCount; +#else +globalShadow=1.0; +#endif +#ifndef BACKMAT_SHADOWONLY +vec4 reflectionColor=vec4(1.,1.,1.,1.); +#ifdef REFLECTION +#ifdef PROJECTED_GROUND +vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.)); +#else +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords=reflectionVector; +#else +vec2 reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +#ifdef REFLECTIONBLUR +float reflectionLOD=vReflectionInfos.y; +#ifdef TEXTURELODSUPPORT +reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); +#else +float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( +sampleReflection(reflectionSamplerHigh,reflectionCoords), +reflectionSpecularMid, +lodReflectionNormalizedDoubled +);} else {reflectionColor=mix( +reflectionSpecularMid, +sampleReflection(reflectionSamplerLow,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#else +vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef GAMMAREFLECTION +reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); +#endif +#ifdef REFLECTIONBGR +reflectionColor.rgb=reflectionColor.bgr; +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#endif +vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; +#ifdef DIFFUSE +vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); +#ifdef GAMMADIFFUSE +diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); +#endif +diffuseMap.rgb*=vDiffuseInfos.y; +#ifdef DIFFUSEHASALPHA +finalAlpha*=diffuseMap.a; +#endif +diffuseColor=diffuseMap.rgb; +#endif +#ifdef REFLECTIONFRESNEL +vec3 colorBase=diffuseColor; +#else +vec3 colorBase=reflectionColor.rgb*diffuseColor; +#endif +colorBase=max(colorBase,0.0); +#ifdef USERGBCOLOR +vec3 finalColor=colorBase; +#else +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); +#else +vec3 mainColor=vPrimaryColor.rgb; +#endif +vec3 finalColor=colorBase*mainColor; +#endif +#ifdef REFLECTIONFRESNEL +vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; +#ifdef REFLECTIONFALLOFF +float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; +#endif +finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); +#endif +#ifdef OPACITYFRESNEL +float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; +#endif +#ifdef SHADOWINUSE +finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); +#endif +vec4 color=vec4(finalColor,finalAlpha); +#else +vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); +#endif +#include<fogFragment> +#ifdef IMAGEPROCESSINGPOSTPROCESS +#if !defined(SKIPFINALCOLORCLAMP) +color.rgb=clamp(color.rgb,0.,30.0); +#endif +#else +color=applyImageProcessing(color); +#endif +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#ifdef NOISE +color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); +#endif +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +} +`;s_.v.ShadersStore.backgroundPixelShader=ot;let oi=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; +#ifdef DIFFUSE +uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +`;s_.v.IncludesShadersStore.backgroundVertexDeclaration=oi;let or=`precision highp float; +#include<__decl__backgroundVertex> +#include<helperFunctions> +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<instancesDeclaration> +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef MAINUV1 +varying vec2 vMainUV1; +#endif +#ifdef MAINUV2 +varying vec2 vMainUV2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +varying vec2 vDiffuseUV; +#endif +#include<clipPlaneVertexDeclaration> +#include<fogVertexDeclaration> +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=position; +#endif +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} +#else +gl_Position=viewProjection*finalWorld*vec4(position,1.0); +#endif +vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normal); +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); +#ifdef EQUIRECTANGULAR_RELFECTION_FOV +mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} +#endif +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uv; +#endif +#ifdef MAINUV2 +vMainUV2=uv2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +if (vDiffuseInfos.x==0.) +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} +else +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} +#endif +#include<clipPlaneVertex> +#include<fogVertex> +#include<shadowsVertex>[0..maxSimultaneousLights] +#ifdef VERTEXCOLOR +vColor=color; +#endif +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;s_.v.ShadersStore.backgroundVertexShader=or;let BackgroundMaterialDefines=class BackgroundMaterialDefines extends sn.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.PROJECTED_GROUND=!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()}};let BackgroundMaterial=class BackgroundMaterial extends PushMaterial{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=BackgroundMaterial.StandardReflectance0*t,this.reflectionReflectance90=BackgroundMaterial.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=BackgroundMaterial.StandardReflectance0+(1-BackgroundMaterial.StandardReflectance0)*t,this.reflectionReflectance90=BackgroundMaterial.StandardReflectance90+(1-BackgroundMaterial.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()})))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=rg.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=rm.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._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new sp.t(16),this._reflectionControls=rm.Lt.Zero(),this._white=rg.Wo.White(),this._primaryShadowColor=rg.Wo.Black(),this._primaryHighlightColor=rg.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 BackgroundMaterialDefines);let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();if(so.G.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,so.G.PrepareDefinesForMultiview(r,s),s._areTexturesDirty){if(s._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;so.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;let e=this._reflectionTexture;if(e&&MaterialFlags.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===texture_Texture.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 texture_Texture.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case texture_Texture.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case texture_Texture.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case texture_Texture.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case texture_Texture.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case texture_Texture.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.CUBIC_MODE:case texture_Texture.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(s._areMiscDirty&&(s.REFLECTIONMAP_3D&&this._enableGroundProjection?(s.PROJECTED_GROUND=!0,s.REFLECTIONMAP_SKYBOX=!0):s.PROJECTED_GROUND=!1),so.G.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),so.G.PrepareDefinesForFrameBoundValues(r,n,this,s,i,null,t.getRenderingMesh().hasThinInstances),so.G.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&!r.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(rz.o.NormalKind)&&(e.createNormals(!0),rT.Y.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();let i=new EffectFallbacks;s.FOG&&i.addFallback(0,"FOG"),s.POINTSIZE&&i.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),so.G.HandleFallbacksForShadows(s,i,this._maxSimultaneousLights);let a=[rz.o.PositionKind];s.NORMAL&&a.push(rz.o.NormalKind),s.UV1&&a.push(rz.o.UVKind),s.UV2&&a.push(rz.o.UV2Kind),so.G.PrepareAttributesForBones(a,e,s,i),so.G.PrepareAttributesForInstances(a,s);let o=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos"];(0,nX.qx)(o);let l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];sv.$&&(sv.$.PrepareUniforms(o,s),sv.$.PrepareSamplers(l,s)),so.G.PrepareUniformsAndSamplersList({uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});let u=s.toString(),c=r.getEngine().createEffect("background",{attributes:a,uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:u,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},n);t.setEffect(c,s,this._materialContext),this.buildUniformLayout()}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.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.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.materialDefines;if(!s)return;let n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),so.G.BindBonesParameters(t,this._activeEffect);let a=this._mustRebind(r,n,t.visibility);if(a){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);let e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(r.texturesEnabled&&(this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),so.G.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&MaterialFlags.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&MaterialFlags.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),s.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),(0,nX.an)(this._activeEffect,this,r),r.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(a||!this.isFrozen)&&(r.lightsEnabled&&so.G.BindLights(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(n),so.G.BindFogParameters(r,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 rb.p4.Clone(()=>new BackgroundMaterial(e,this.getScene()),this)}serialize(){let e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return rb.p4.Parse(()=>new BackgroundMaterial(e.name,t),e,t,i)}};BackgroundMaterial.StandardReflectance0=.05,BackgroundMaterial.StandardReflectance90=.5,(0,rH.gn)([(0,rb.n9)()],BackgroundMaterial.prototype,"_primaryColor",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"primaryColor",void 0),(0,rH.gn)([(0,rb.n9)()],BackgroundMaterial.prototype,"__perceptualColor",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_primaryColorShadowLevel",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_primaryColorHighlightLevel",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"primaryColorHighlightLevel",null),(0,rH.gn)([(0,rb.oU)()],BackgroundMaterial.prototype,"_reflectionTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionTexture",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionBlur",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionBlur",void 0),(0,rH.gn)([(0,rb.oU)()],BackgroundMaterial.prototype,"_diffuseTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"diffuseTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"shadowLights",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_shadowLevel",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"shadowLevel",void 0),(0,rH.gn)([(0,rb.hd)()],BackgroundMaterial.prototype,"_sceneCenter",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"sceneCenter",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_opacityFresnel",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"opacityFresnel",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionFresnel",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionFresnel",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionFalloffDistance",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionFalloffDistance",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionAmount",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionAmount",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionReflectance0",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionReflectance0",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionReflectance90",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionReflectance90",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_useRGBColor",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"useRGBColor",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_enableNoise",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"enableNoise",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_shadowOnly",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"shadowOnly",void 0),(0,rH.gn)([(0,rb.rX)()],BackgroundMaterial.prototype,"_imageProcessingConfiguration",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],BackgroundMaterial.prototype,"enableGroundProjection",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"projectedGroundRadius",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"projectedGroundHeight",void 0),(0,rv.H)("BABYLON.BackgroundMaterial",BackgroundMaterial);let EnvironmentHelper=class EnvironmentHelper{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new rg.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 rg.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:rm.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({},EnvironmentHelper._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new rf.y$,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){let 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 rg.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 baseTexture_BaseTexture){this._scene.environmentTexture=this._options.environmentTexture;return}let e=cubeTexture_CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new rV.Kj("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;let 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};let r=this._scene.getWorldExtends(e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox),s=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof ArcRotateCamera&&this._scene.activeCamera.upperRadiusLimit&&(t=e=2*this._scene.activeCamera.upperRadiusLimit);let n=s.length();n>e&&(t=e=2*n),e*=1.1,t*=1.5,(i=r.min.add(s.scale(.5))).y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=planeBuilder_CreatePlane("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 BackgroundMaterial("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof baseTexture_BaseTexture){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new texture_Texture(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){let t=texture_Texture.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new MirrorTexture("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,texture_Texture.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new r2.J(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e<this._scene.meshes.length;e++){let t=this._scene.meshes[e];t!==this._ground&&t!==this._skybox&&t!==this._rootMesh&&this._groundMirror.renderList.push(t)}let i=this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions);this._groundMirror.clearColor=new rg.HE(i.r,i.g,i.b,1),this._groundMirror.adaptiveBlurKernel=this._options.groundMirrorBlurKernel}_setupMirrorInGroundMaterial(){this._groundMaterial&&(this._groundMaterial.reflectionTexture=this._groundMirror,this._groundMaterial.reflectionFresnel=!0,this._groundMaterial.reflectionAmount=this._options.groundMirrorAmount,this._groundMaterial.reflectionStandardFresnelWeight=this._options.groundMirrorFresnelWeight,this._groundMaterial.reflectionFalloffDistance=this._options.groundMirrorFallOffDistance)}_setupSkybox(e){(!this._skybox||this._skybox.isDisposed())&&(this._skybox=boxBuilder_CreateBox("BackgroundSkybox",{size:e.skyboxSize,sideOrientation:rV.Kj.BACKSIDE},this._scene),this._skybox.onDisposeObservable.add(()=>{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new BackgroundMaterial("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){if(this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof baseTexture_BaseTexture){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new cubeTexture_CubeTexture(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=texture_Texture.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)}};EnvironmentHelper._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",EnvironmentHelper._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",EnvironmentHelper._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";let TextureDome=class TextureDome extends rk.Y{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=TextureDome.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new rf.y$,this.onLoadObservable=new rf.y$,r=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=!!i.clickToPlay,i.autoPlay=void 0===i.autoPlay||!!i.autoPlay,i.loop=void 0===i.loop||!!i.loop,i.size=Math.abs(i.size)||(r.activeCamera?.48*r.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=sphereBuilder_CreateSphere(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:rV.Kj.BACKSIDE},r);let n=this._material=new BackgroundMaterial(e+"_material",r);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;let a=this._initTexture(t,r,i);if(this.texture=a,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=sphereBuilder_CreateSphere("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:rV.Kj.BACKSIDE},r),this._halfDomeMask.rotate(rL.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&&r.activeCamera){let e=r.activeCamera,t=rm.P.Forward(),i=rm.P.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(rm.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 TextureDome.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case TextureDome.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;let e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(i=>{let r=i.isRightCamera;this._crossEye&&(r=!r),r?this._texture.uOffset=e:this._texture.uOffset=t});break}case TextureDome.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)}};TextureDome.MODE_MONOSCOPIC=0,TextureDome.MODE_TOPBOTTOM=1,TextureDome.MODE_SIDEBYSIDE=2;let PhotoDome=class PhotoDome extends TextureDome{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 texture_Texture(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)})}};PhotoDome.MODE_MONOSCOPIC=TextureDome.MODE_MONOSCOPIC,PhotoDome.MODE_TOPBOTTOM=TextureDome.MODE_TOPBOTTOM,PhotoDome.MODE_SIDEBYSIDE=TextureDome.MODE_SIDEBYSIDE;let os=0,GetEnvironmentBRDFTexture=e=>{if(!e.environmentBRDFTexture){let t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;let i=e._blockEntityCollection;e._blockEntityCollection=!1;let r=texture_Texture.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+os++,e,!0,!1,texture_Texture.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;let s=e.getEngine().getLoadedTexturesCache(),n=s.indexOf(r.getInternalTexture());-1!==n&&s.splice(n,1),r.isRGBD=!0,r.wrapU=texture_Texture.CLAMP_ADDRESSMODE,r.wrapV=texture_Texture.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=r,e.useDelayedTextureLoading=t,RGBDTextureTools.ExpandRGBDTexture(r);let a=e.getEngine().onContextRestoredObservable.add(()=>{r.isRGBD=!0;let checkReady=()=>{r.isReady()?RGBDTextureTools.ExpandRGBDTexture(r):rW.w1.SetImmediate(checkReady)};checkReady()});e.onDisposeObservable.add(()=>{e.getEngine().onContextRestoredObservable.remove(a)})}return e.environmentBRDFTexture};let MaterialBRDFDefines=class MaterialBRDFDefines extends sn.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}};let pbrBRDFConfiguration_PBRBRDFConfiguration=class pbrBRDFConfiguration_PBRBRDFConfiguration extends MaterialPluginBase{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new MaterialBRDFDefines,t),this._useEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.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"}};pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useEnergyConservation",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSmithVisibilityHeightCorrelated",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSphericalHarmonics",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);let on=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; +#ifdef ALBEDO +uniform vec2 vAlbedoInfos; +#endif +#ifdef AMBIENT +uniform vec4 vAmbientInfos; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#ifdef OPACITY +uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos; +#endif +#ifdef REFLECTIVITY +uniform vec3 vReflectivityInfos; +#endif +#ifdef MICROSURFACEMAP +uniform vec2 vMicroSurfaceSamplerInfos; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) +uniform mat4 view; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos; +#ifdef REALTIME_FILTERING +uniform vec2 vReflectionFilteringInfo; +#endif +uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; +#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) +uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; +#endif +#ifdef CLEARCOAT +uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; +#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform vec4 vClearCoatInfos; +#endif +#ifdef CLEARCOAT_TEXTURE +uniform mat4 clearCoatMatrix; +#endif +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS +uniform mat4 clearCoatRoughnessMatrix; +#endif +#ifdef CLEARCOAT_BUMP +uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; +#endif +#ifdef CLEARCOAT_TINT +uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; +#ifdef CLEARCOAT_TINT_TEXTURE +uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; +#endif +#endif +#endif +#ifdef IRIDESCENCE +uniform vec4 vIridescenceParams; +#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) +uniform vec4 vIridescenceInfos; +#endif +#ifdef IRIDESCENCE_TEXTURE +uniform mat4 iridescenceMatrix; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +uniform mat4 iridescenceThicknessMatrix; +#endif +#endif +#ifdef ANISOTROPIC +uniform vec3 vAnisotropy; +#ifdef ANISOTROPIC_TEXTURE +uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; +#endif +#endif +#ifdef SHEEN +uniform vec4 vSheenColor; +#ifdef SHEEN_ROUGHNESS +uniform float vSheenRoughness; +#endif +#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) +uniform vec4 vSheenInfos; +#endif +#ifdef SHEEN_TEXTURE +uniform mat4 sheenMatrix; +#endif +#ifdef SHEEN_TEXTURE_ROUGHNESS +uniform mat4 sheenRoughnessMatrix; +#endif +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; +#ifdef REALTIME_FILTERING +uniform vec2 vRefractionFilteringInfo; +#endif +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; +#endif +uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity; +#endif +#ifdef PREPASS +#ifdef SS_SCATTERING +uniform float scatteringDiffusionProfile; +#endif +#endif +#if DEBUGMODE>0 +uniform vec2 vDebugMode; +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos; +#endif +#include<decalFragmentDeclaration> +#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; +#else +uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; +#endif +#endif +#define ADDITIONAL_FRAGMENT_DECLARATION +`;s_.v.IncludesShadersStore.pbrFragmentDeclaration=on;let oa=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; +#define ADDITIONAL_UBO_DECLARATION +}; +#include<sceneUboDeclaration> +#include<meshUboDeclaration> +`;s_.v.IncludesShadersStore.pbrUboDeclaration=oa;let oo=`varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#include<mainUVVaryingDeclaration>[1..7] +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +`;s_.v.IncludesShadersStore.pbrFragmentExtraDeclaration=oo;let ol=`#ifdef _DEFINENAME_ +#if _DEFINENAME_DIRECTUV==1 +#define v_VARYINGNAME_UV vMainUV1 +#elif _DEFINENAME_DIRECTUV==2 +#define v_VARYINGNAME_UV vMainUV2 +#elif _DEFINENAME_DIRECTUV==3 +#define v_VARYINGNAME_UV vMainUV3 +#elif _DEFINENAME_DIRECTUV==4 +#define v_VARYINGNAME_UV vMainUV4 +#elif _DEFINENAME_DIRECTUV==5 +#define v_VARYINGNAME_UV vMainUV5 +#elif _DEFINENAME_DIRECTUV==6 +#define v_VARYINGNAME_UV vMainUV6 +#else +varying vec2 v_VARYINGNAME_UV; +#endif +#endif +`;s_.v.IncludesShadersStore.samplerFragmentAlternateDeclaration=ol;let oh=`#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) +#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) +#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) +#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) +#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) +#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef CLEARCOAT +#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) +#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) +uniform sampler2D clearCoatRoughnessSampler; +#endif +#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) +#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) +#endif +#ifdef IRIDESCENCE +#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) +#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) +#endif +#ifdef SHEEN +#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) +#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) +uniform sampler2D sheenRoughnessSampler; +#endif +#endif +#ifdef ANISOTROPIC +#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +#define sampleReflection(s,c) textureCube(s,c) +uniform samplerCube reflectionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#ifdef USEIRRADIANCEMAP +uniform samplerCube irradianceSampler; +#endif +#else +#define sampleReflection(s,c) texture2D(s,c) +uniform sampler2D reflectionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; +#endif +#ifdef USEIRRADIANCEMAP +uniform sampler2D irradianceSampler; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#endif +#ifdef ENVIRONMENTBRDF +uniform sampler2D environmentBrdfSampler; +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +#ifdef SS_REFRACTIONMAP_3D +#define sampleRefraction(s,c) textureCube(s,c) +uniform samplerCube refractionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; +#endif +#else +#define sampleRefraction(s,c) texture2D(s,c) +uniform sampler2D refractionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; +#endif +#endif +#endif +#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) +#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) +#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) +#endif +`;s_.v.IncludesShadersStore.pbrFragmentSamplersDeclaration=oh;let ou=`bool testLightingForSSS(float diffusionProfile) +{return diffusionProfile<1.;}`;s_.v.IncludesShadersStore.subSurfaceScatteringFunctions=ou;let oc=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { +float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;s_.v.IncludesShadersStore.importanceSampling=oc;let od=`#define MINIMUMVARIANCE 0.0005 +float convertRoughnessToAverageSlope(float roughness) +{return square(roughness)+MINIMUMVARIANCE;} +float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} +vec2 getAARoughnessFactors(vec3 normalVector) { +#ifdef SPECULARAA +vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); +#else +return vec2(0.); +#endif +} +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_LEGACY +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} +#else +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} +#endif +#endif +#if defined(CLEARCOAT) || defined(SS_REFRACTION) +vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} +vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} +vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} +vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), +cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), +clearCoatIntensity);return clearCoatAbsorption;} +#endif +#ifdef MICROSURFACEAUTOMATIC +float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) +{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} +#endif +`;s_.v.IncludesShadersStore.pbrHelperFunctions=od;let op=`#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 ++ vSphericalL1_1*(normal.y) ++ vSphericalL10*(normal.z) ++ vSphericalL11*(normal.x) ++ vSphericalL2_2*(normal.y*normal.x) ++ vSphericalL2_1*(normal.y*normal.z) ++ vSphericalL20*((3.0*normal.z*normal.z)-1.0) ++ vSphericalL21*(normal.z*normal.x) ++ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} +#else +vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} +#endif +#endif +`;s_.v.IncludesShadersStore.harmonicsFunctions=op;let o_=`struct preLightingInfo +{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; +#ifdef IRIDESCENCE +float iridescenceIntensity; +#endif +};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; +#ifdef SPECULARTERM +result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); +#endif +return result;}`;s_.v.IncludesShadersStore.pbrDirectLightingSetupFunctions=o_;let of=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) +{return max(0.,1.0-length(lightOffset)/range);} +float computeDistanceLightFalloff_Physical(float lightDistanceSquared) +{return 1.0/maxEps(lightDistanceSquared);} +float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) +{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} +float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDistanceLightFalloff_Physical(lightDistanceSquared); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); +#else +return computeDistanceLightFalloff_Standard(lightOffset,range); +#endif +} +float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) +{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) +{falloff=max(0.,pow(cosAngle,exponent));} +return falloff;} +float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) +{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; +float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} +float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) +{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} +float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); +#else +return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); +#endif +}`;s_.v.IncludesShadersStore.pbrDirectLightingFalloffFunctions=of;let om=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} +#endif +#ifdef ENVIRONMENTBRDF +vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); +#ifdef ENVIRONMENTBRDF_RGBD +brdfLookup.rgb=fromRGBD(brdfLookup.rgba); +#endif +return brdfLookup.rgb;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; +#endif +return reflectance;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; +#endif +return reflectance;} +#endif +/* NOT USED +#if defined(SHEEN) && defined(SHEEN_SOFTER) +float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) +{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} +#endif +*/ +#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) +vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) +{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +/** +* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. +* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table +*/ +vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} +#endif +vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +#ifdef CLEARCOAT +vec3 getR0RemappedForClearCoat(vec3 f0) { +#ifdef CLEARCOAT_DEFAULTIOR +#ifdef MOBILE +return saturate(f0*(f0*0.526868+0.529324)-0.0482256); +#else +return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); +#endif +#else +vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); +#endif +} +#endif +#ifdef IRIDESCENCE +const mat3 XYZ_TO_REC709=mat3( +3.2404542,-0.9692660, 0.0556434, +-1.5371385, 1.8760108,-0.2040259, +-0.4985314, 0.0415560, 1.0572252 +);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} +vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} +float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} +vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} +vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} +float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR<outsideIOR) phi12=PI;float phi21=PI-phi12;vec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999)); +vec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);vec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));vec3 phi23=vec3(0.0);if (baseIOR[0]<iridescenceIOR) phi23[0]=PI;if (baseIOR[1]<iridescenceIOR) phi23[1]=PI;if (baseIOR[2]<iridescenceIOR) phi23[2]=PI;float opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;vec3 phi=vec3(phi21)+phi23;vec3 R123=clamp(R12*R23,1e-5,0.9999);vec3 r123=sqrt(R123);vec3 Rs=square(T121)*R23/(vec3(1.0)-R123);vec3 C0=R12+Rs;I=C0;vec3 Cm=Rs-T121;for (int m=1; m<=2; ++m) +{Cm*=r123;vec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);I+=Cm*Sm;} +return max(I,vec3(0.0));} +#endif +float normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG) +{float a2=square(alphaG);float d=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);} +#ifdef SHEEN +float normalDistributionFunction_CharlieSheen(float NdotH,float alphaG) +{float invR=1./alphaG;float cos2h=NdotH*NdotH;float sin2h=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);} +#endif +#ifdef ANISOTROPIC +float normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {float a2=alphaTB.x*alphaTB.y;vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);float v2=dot(v,v);float w2=a2/v2;return a2*w2*w2*RECIPROCAL_PI;} +#endif +#ifdef BRDF_V_HEIGHT_CORRELATED +float smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) { +#ifdef MOBILE +float GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL); +#else +float a2=alphaG*alphaG;float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL); +#endif +} +#else +float smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG) +{ +#ifdef MOBILE +return 1.0/(dot+alphaG+(1.0-alphaG)*dot )); +#else +float alphaSquared=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot)); +#endif +} +float smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG) +{float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;} +#endif +#ifdef ANISOTROPIC +float smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));float v=0.5/(lambdaV+lambdaL);return v;} +#endif +#ifdef CLEARCOAT +float visibility_Kelemen(float VdotH) {return 0.25/(VdotH*VdotH); } +#endif +#ifdef SHEEN +float visibility_Ashikhmin(float NdotL,float NdotV) +{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));} +/* NOT USED +#ifdef SHEEN_SOFTER +float l(float x,float alphaG) +{float oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);float a=mix(21.5473,25.3245,oneMinusAlphaSq);float b=mix(3.82987,3.32435,oneMinusAlphaSq);float c=mix(0.19823,0.16801,oneMinusAlphaSq);float d=mix(-1.97760,-1.27393,oneMinusAlphaSq);float e=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;} +float lambdaSheen(float cosTheta,float alphaG) +{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));} +float visibility_CharlieSheen(float NdotL,float NdotV,float alphaG) +{float G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);} +#endif +*/ +#endif +float diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;float fresnel = +(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) * +(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;} +#ifdef SS_TRANSLUCENCY +vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);} +float computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);} +#endif +`;s_.v.IncludesShadersStore.pbrBRDFFunctions=om;let og=`#ifdef NUM_SAMPLES +#if NUM_SAMPLES>0 +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +float radicalInverse_VdC(uint bits) +{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } +vec2 hammersley(uint i,uint N) +{return vec2(float(i)/float(N),radicalInverse_VdC(i));} +#else +float vanDerCorpus(int n,int base) +{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) +{if(n>0) +{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} +return result;} +vec2 hammersley(int i,int N) +{return vec2(float(i)/float(N),vanDerCorpus(i,2));} +#endif +float log4(float x) {return log2(x)/2.;} +const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; +#define inline +vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) +{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +for(uint i=0u; i<NUM_SAMPLES; ++i) +#else +for(int i=0; i<NUM_SAMPLES; ++i) +#endif +{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 Ls=hemisphereCosSample(Xi);Ls=normalize(Ls);vec3 Ns=vec3(0.,0.,1.);float NoL=dot(Ns,Ls);if (NoL>0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +result+=c;}} +result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} +#define inline +vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) +{vec3 n=normalize(inputN);if (alphaG==0.) {vec3 c=textureCube(inputTexture,n).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +for(uint i=0u; i<NUM_SAMPLES; ++i) +#else +for(int i=0; i<NUM_SAMPLES; ++i) +#endif +{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);float NoV=1.;float NoH=H.z;float NoH2=H.z*H.z;float NoL=2.*NoH2-1.;vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +result+=c*NoL;}} +result=result/weight;return result;}} +#endif +#endif +`;s_.v.IncludesShadersStore.hdrFilteringFunctions=og;let ov=`#define CLEARCOATREFLECTANCE90 1.0 +struct lightingInfo +{vec3 diffuse; +#ifdef SPECULARTERM +vec3 specular; +#endif +#ifdef CLEARCOAT +vec4 clearCoat; +#endif +#ifdef SHEEN +vec3 sheen; +#endif +};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { +#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) +float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; +#else +return roughness; +#endif +} +vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} +vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} +#define inline +vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} +#ifdef SS_TRANSLUCENCY +vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} +#endif +#ifdef SPECULARTERM +vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); +#ifdef BRDF_V_HEIGHT_CORRELATED +float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); +#else +float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); +#endif +vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef ANISOTROPIC +vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef CLEARCOAT +vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( +clearCoatTerm*info.attenuation*NccdotL*lightColor, +1.0-fresnel +);} +vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} +#endif +#ifdef SHEEN +vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER +float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); +#else */ +float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ +float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} +#endif +`;s_.v.IncludesShadersStore.pbrDirectLightingFunctions=ov;let ox=`#if defined(REFLECTION) || defined(SS_REFRACTION) +float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} +float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} +#endif +#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) +float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} +#endif +#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) +float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} +#endif +#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) +#define UNPACK_LOD(x) (1.0-x)*255.0 +float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} +#endif +`;s_.v.IncludesShadersStore.pbrIBLFunctions=ox;let oT=`struct albedoOpacityOutParams +{vec3 surfaceAlbedo;float alpha;}; +#define pbr_inline +void albedoOpacityBlock( +in vec4 vAlbedoColor, +#ifdef ALBEDO +in vec4 albedoTexture, +in vec2 albedoInfos, +#endif +#ifdef OPACITY +in vec4 opacityMap, +in vec2 vOpacityInfos, +#endif +#ifdef DETAIL +in vec4 detailColor, +in vec4 vDetailInfos, +#endif +#ifdef DECAL +in vec4 decalColor, +in vec4 vDecalInfos, +#endif +out albedoOpacityOutParams outParams +) +{vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; +#ifdef ALBEDO +#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) +alpha*=albedoTexture.a; +#endif +#ifdef GAMMAALBEDO +surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); +#else +surfaceAlbedo*=albedoTexture.rgb; +#endif +surfaceAlbedo*=albedoInfos.y; +#endif +#ifndef DECAL_AFTER_DETAIL +#include<decalFragment> +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +surfaceAlbedo*=vColor.rgb; +#endif +#ifdef DETAIL +float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; +#endif +#ifdef DECAL_AFTER_DETAIL +#include<decalFragment> +#endif +#define CUSTOM_FRAGMENT_UPDATE_ALBEDO +#ifdef OPACITY +#ifdef OPACITYRGB +alpha=getLuminance(opacityMap.rgb); +#else +alpha*=opacityMap.a; +#endif +alpha*=vOpacityInfos.y; +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) +#ifdef ALPHATEST +#if DEBUGMODE != 88 +if (alpha<ALPHATESTVALUE) +discard; +#endif +#ifndef ALPHABLEND +alpha=1.0; +#endif +#endif +#endif +outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;} +`;s_.v.IncludesShadersStore.pbrBlockAlbedoOpacity=oT;let oS=`struct reflectivityOutParams +{float microSurface;float roughness;vec3 surfaceReflectivityColor; +#ifdef METALLICWORKFLOW +vec3 surfaceAlbedo; +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +vec3 ambientOcclusionColor; +#endif +#if DEBUGMODE>0 +#ifdef METALLICWORKFLOW +vec2 metallicRoughness; +#ifdef REFLECTIVITY +vec4 surfaceMetallicColorMap; +#endif +#ifndef FROSTBITE_REFLECTANCE +vec3 metallicF0; +#endif +#else +#ifdef REFLECTIVITY +vec4 surfaceReflectivityColorMap; +#endif +#endif +#endif +}; +#define pbr_inline +void reflectivityBlock( +in vec4 vReflectivityColor, +#ifdef METALLICWORKFLOW +in vec3 surfaceAlbedo, +in vec4 metallicReflectanceFactors, +#endif +#ifdef REFLECTIVITY +in vec3 reflectivityInfos, +in vec4 surfaceMetallicOrReflectivityColorMap, +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +in vec3 ambientOcclusionColorIn, +#endif +#ifdef MICROSURFACEMAP +in vec4 microSurfaceTexel, +#endif +#ifdef DETAIL +in vec4 detailColor, +in vec4 vDetailInfos, +#endif +out reflectivityOutParams outParams +) +{float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +vec2 metallicRoughness=surfaceReflectivityColor.rg; +#ifdef REFLECTIVITY +#if DEBUGMODE>0 +outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef AOSTOREINMETALMAPRED +vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); +#endif +#ifdef METALLNESSSTOREINMETALMAPBLUE +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; +#else +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; +#endif +#ifdef ROUGHNESSSTOREINMETALMAPALPHA +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; +#else +#ifdef ROUGHNESSSTOREINMETALMAPGREEN +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; +#endif +#endif +#endif +#ifdef DETAIL +float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); +#endif +#ifdef MICROSURFACEMAP +metallicRoughness.g*=microSurfaceTexel.r; +#endif +#if DEBUGMODE>0 +outParams.metallicRoughness=metallicRoughness; +#endif +#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS +microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; +#ifdef FROSTBITE_REFLECTANCE +outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); +#else +vec3 metallicF0=metallicReflectanceFactors.rgb; +#if DEBUGMODE>0 +outParams.metallicF0=metallicF0; +#endif +outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); +#endif +#else +#ifdef REFLECTIVITY +surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; +#if DEBUGMODE>0 +outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef MICROSURFACEFROMREFLECTIVITYMAP +microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; +#else +#ifdef MICROSURFACEAUTOMATIC +microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); +#endif +#ifdef MICROSURFACEMAP +microSurface*=microSurfaceTexel.r; +#endif +#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE +#endif +#endif +#endif +microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;} +`;s_.v.IncludesShadersStore.pbrBlockReflectivity=oS;let oC=`struct ambientOcclusionOutParams +{vec3 ambientOcclusionColor; +#if DEBUGMODE>0 && defined(AMBIENT) +vec3 ambientOcclusionColorMap; +#endif +}; +#define pbr_inline +void ambientOcclusionBlock( +#ifdef AMBIENT +in vec3 ambientOcclusionColorMap_, +in vec4 vAmbientInfos, +#endif +out ambientOcclusionOutParams outParams +) +{vec3 ambientOcclusionColor=vec3(1.,1.,1.); +#ifdef AMBIENT +vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; +#ifdef AMBIENTINGRAYSCALE +ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); +#endif +ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); +#if DEBUGMODE>0 +outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; +#endif +#endif +outParams.ambientOcclusionColor=ambientOcclusionColor;} +`;s_.v.IncludesShadersStore.pbrBlockAmbientOcclusion=oC;let oE=`#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +struct alphaFresnelOutParams +{float alpha;}; +#define pbr_inline +void alphaFresnelBlock( +in vec3 normalW, +in vec3 viewDirectionW, +in float alpha, +in float microSurface, +out alphaFresnelOutParams outParams +) +{float opacityPerceptual=alpha; +#ifdef LINEARALPHAFRESNEL +float opacity0=opacityPerceptual; +#else +float opacity0=opacityPerceptual*opacityPerceptual; +#endif +float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; +#ifdef ALPHATEST +if (outParams.alpha<ALPHATESTVALUE) +discard; +#ifndef ALPHABLEND +outParams.alpha=1.0; +#endif +#endif +} +#endif +#endif +`;s_.v.IncludesShadersStore.pbrBlockAlphaFresnel=oE;let ob=`#ifdef ANISOTROPIC +struct anisotropicOutParams +{float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal; +#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE) +vec3 anisotropyMapData; +#endif +}; +#define pbr_inline +void anisotropicBlock( +in vec3 vAnisotropy, +in float roughness, +#ifdef ANISOTROPIC_TEXTURE +in vec3 anisotropyMapData, +#endif +in mat3 TBN, +in vec3 normalW, +in vec3 viewDirectionW, +out anisotropicOutParams outParams +) +{float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); +#ifdef ANISOTROPIC_TEXTURE +anisotropy*=anisotropyMapData.b; +#if DEBUGMODE>0 +outParams.anisotropyMapData=anisotropyMapData; +#endif +anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; +#ifdef ANISOTROPIC_LEGACY +anisotropyDirection.rg*=anisotropyMapData.rg; +#else +anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); +#endif +#endif +mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);} +#endif +`;s_.v.IncludesShadersStore.pbrBlockAnisotropic=ob;let oy=`#ifdef REFLECTION +struct reflectionOutParams +{vec4 environmentRadiance;vec3 environmentIrradiance; +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords; +#else +vec2 reflectionCoords; +#endif +#ifdef SS_TRANSLUCENCY +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +vec3 irradianceVector; +#endif +#endif +#endif +}; +#define pbr_inline +void createReflectionCoords( +in vec3 vPositionW, +in vec3 normalW, +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#ifdef REFLECTIONMAP_3D +out vec3 reflectionCoords +#else +out vec2 reflectionCoords +#endif +) +{ +#ifdef ANISOTROPIC +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); +#else +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +reflectionCoords=reflectionVector; +#else +reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +} +#define pbr_inline +#define inline +void sampleReflectionTexture( +in float alphaG, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +in float NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +in float roughness, +#endif +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +const vec3 reflectionCoords, +#else +in sampler2D reflectionSampler, +const vec2 reflectionCoords, +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +out vec4 environmentRadiance +) +{ +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); +#elif defined(LINEARSPECULARREFLECTION) +float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); +#else +float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); +#endif +#ifdef LODBASEDMICROSFURACE +reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; +#ifdef LODINREFLECTIONALPHA +float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); +#else +float requestedReflectionLOD=reflectionLOD; +#endif +#ifdef REALTIME_FILTERING +environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); +#else +environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); +#endif +#else +float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( +sampleReflection(reflectionSamplerHigh,reflectionCoords), +environmentMid, +lodReflectionNormalizedDoubled +);} else {environmentRadiance=mix( +environmentMid, +sampleReflection(reflectionSamplerLow,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#ifdef RGBDREFLECTION +environmentRadiance.rgb=fromRGBD(environmentRadiance); +#endif +#ifdef GAMMAREFLECTION +environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); +#endif +environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} +#define pbr_inline +#define inline +void reflectionBlock( +in vec3 vPositionW, +in vec3 normalW, +in float alphaG, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +in float NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +in float roughness, +#endif +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +#else +in sampler2D reflectionSampler, +#endif +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +in vec3 vEnvironmentIrradiance, +#endif +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +in mat4 reflectionMatrix, +#endif +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +in samplerCube irradianceSampler, +#else +in sampler2D irradianceSampler, +#endif +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +out reflectionOutParams outParams +) +{vec4 environmentRadiance=vec4(0.,0.,0.,0.); +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords=vec3(0.); +#else +vec2 reflectionCoords=vec2(0.); +#endif +createReflectionCoords( +vPositionW, +normalW, +#ifdef ANISOTROPIC +anisotropicOut, +#endif +reflectionCoords +);sampleReflectionTexture( +alphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +roughness, +#endif +#ifdef REFLECTIONMAP_3D +reflectionSampler, +reflectionCoords, +#else +reflectionSampler, +reflectionCoords, +#endif +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentRadiance +);vec3 environmentIrradiance=vec3(0.,0.,0.); +#ifdef USESPHERICALFROMREFLECTIONMAP +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +environmentIrradiance=vEnvironmentIrradiance; +#else +#ifdef ANISOTROPIC +vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; +#else +vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#if defined(REALTIME_FILTERING) +environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo); +#else +environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); +#endif +#ifdef SS_TRANSLUCENCY +outParams.irradianceVector=irradianceVector; +#endif +#endif +#elif defined(USEIRRADIANCEMAP) +vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; +#ifdef RGBDREFLECTION +environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); +#endif +#ifdef GAMMAREFLECTION +environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); +#endif +#endif +environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;} +#endif +`;s_.v.IncludesShadersStore.pbrBlockReflection=oy;let oP=`#ifdef SHEEN +struct sheenOutParams +{float sheenIntensity;vec3 sheenColor;float sheenRoughness; +#ifdef SHEEN_LINKWITHALBEDO +vec3 surfaceAlbedo; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +float sheenAlbedoScaling; +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +vec3 finalSheenRadianceScaled; +#endif +#if DEBUGMODE>0 +#ifdef SHEEN_TEXTURE +vec4 sheenMapData; +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +vec3 sheenEnvironmentReflectance; +#endif +#endif +}; +#define pbr_inline +#define inline +void sheenBlock( +in vec4 vSheenColor, +#ifdef SHEEN_ROUGHNESS +in float vSheenRoughness, +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +in vec4 sheenMapRoughnessData, +#endif +#endif +in float roughness, +#ifdef SHEEN_TEXTURE +in vec4 sheenMapData, +in float sheenMapLevel, +#endif +in float reflectance, +#ifdef SHEEN_LINKWITHALBEDO +in vec3 baseColor, +in vec3 surfaceAlbedo, +#endif +#ifdef ENVIRONMENTBRDF +in float NdotV, +in vec3 environmentBrdf, +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +in vec2 AARoughnessFactors, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +in vec4 vLightingIntensity, +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +in vec3 reflectionCoords, +#else +in sampler2D reflectionSampler, +in vec2 reflectionCoords, +#endif +in float NdotVUnclamped, +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +in float seo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +in float eho, +#endif +#endif +out sheenOutParams outParams +) +{float sheenIntensity=vSheenColor.a; +#ifdef SHEEN_TEXTURE +#if DEBUGMODE>0 +outParams.sheenMapData=sheenMapData; +#endif +#endif +#ifdef SHEEN_LINKWITHALBEDO +float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#else +vec3 sheenColor=vSheenColor.rgb; +#ifdef SHEEN_TEXTURE +#ifdef SHEEN_GAMMATEXTURE +sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); +#else +sheenColor.rgb*=sheenMapData.rgb; +#endif +sheenColor.rgb*=sheenMapLevel; +#endif +#ifdef SHEEN_ROUGHNESS +float sheenRoughness=vSheenRoughness; +#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE +#if defined(SHEEN_TEXTURE) +sheenRoughness*=sheenMapData.a; +#endif +#elif defined(SHEEN_TEXTURE_ROUGHNESS) +#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL +sheenRoughness*=sheenMapData.a; +#else +sheenRoughness*=sheenMapRoughnessData.a; +#endif +#endif +#else +float sheenRoughness=roughness; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#endif +#if !defined(SHEEN_ALBEDOSCALING) +sheenIntensity*=(1.-reflectance); +#endif +sheenColor*=sheenIntensity; +#endif +#ifdef ENVIRONMENTBRDF +/*#ifdef SHEEN_SOFTER +vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); +#else*/ +#ifdef SHEEN_ROUGHNESS +vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); +#else +vec3 environmentSheenBrdf=environmentBrdf; +#endif +/*#endif*/ +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); +#ifdef SPECULARAA +sheenAlphaG+=AARoughnessFactors.y; +#endif +vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( +sheenAlphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +sheenRoughness, +#endif +reflectionSampler, +reflectionCoords, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentSheenRadiance +);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +sheenEnvironmentReflectance*=seo; +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +sheenEnvironmentReflectance*=eho; +#endif +#if DEBUGMODE>0 +outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; +#endif +outParams.finalSheenRadianceScaled= +environmentSheenRadiance.rgb * +sheenEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; +#endif +outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;} +#endif +`;s_.v.IncludesShadersStore.pbrBlockSheen=oP;let oR=`struct clearcoatOutParams +{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; +#ifdef REFLECTION +vec3 finalClearCoatRadianceScaled; +#endif +#ifdef CLEARCOAT_TINT +vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; +#endif +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +vec3 energyConservationFactorClearCoat; +#endif +#if DEBUGMODE>0 +#ifdef CLEARCOAT_BUMP +mat3 TBNClearCoat; +#endif +#ifdef CLEARCOAT_TEXTURE +vec2 clearCoatMapData; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +vec4 clearCoatTintMapData; +#endif +#ifdef REFLECTION +vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; +#endif +float clearCoatNdotV; +#endif +}; +#ifdef CLEARCOAT +#define pbr_inline +#define inline +void clearcoatBlock( +in vec3 vPositionW, +in vec3 geometricNormalW, +in vec3 viewDirectionW, +in vec2 vClearCoatParams, +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +in vec4 clearCoatMapRoughnessData, +#endif +in vec3 specularEnvironmentR0, +#ifdef CLEARCOAT_TEXTURE +in vec2 clearCoatMapData, +#endif +#ifdef CLEARCOAT_TINT +in vec4 vClearCoatTintParams, +in float clearCoatColorAtDistance, +in vec4 vClearCoatRefractionParams, +#ifdef CLEARCOAT_TINT_TEXTURE +in vec4 clearCoatTintMapData, +#endif +#endif +#ifdef CLEARCOAT_BUMP +in vec2 vClearCoatBumpInfos, +in vec4 clearCoatBumpMapData, +in vec2 vClearCoatBumpUV, +#if defined(TANGENT) && defined(NORMAL) +in mat3 vTBN, +#else +in vec2 vClearCoatTangentSpaceParams, +#endif +#ifdef OBJECTSPACE_NORMALMAP +in mat4 normalMatrix, +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +in vec3 faceNormal, +#endif +#ifdef REFLECTION +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +in vec4 vLightingIntensity, +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +#else +in sampler2D reflectionSampler, +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +in float ambientMonochrome, +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +in float frontFacingMultiplier, +#endif +out clearcoatOutParams outParams +) +{float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE +clearCoatRoughness*=clearCoatMapData.y; +#endif +#if DEBUGMODE>0 +outParams.clearCoatMapData=clearCoatMapData; +#endif +#endif +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL +clearCoatRoughness*=clearCoatMapData.y; +#else +clearCoatRoughness*=clearCoatMapRoughnessData.y; +#endif +#endif +outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; +#ifdef CLEARCOAT_TINT +vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; +#ifdef CLEARCOAT_TINT_TEXTURE +#ifdef CLEARCOAT_TINT_GAMMATEXTURE +clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); +#else +clearCoatColor*=clearCoatTintMapData.rgb; +#endif +clearCoatThickness*=clearCoatTintMapData.a; +#if DEBUGMODE>0 +outParams.clearCoatTintMapData=clearCoatTintMapData; +#endif +#endif +outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; +#endif +#ifdef CLEARCOAT_REMAP_F0 +vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); +#else +vec3 specularEnvironmentR0Updated=specularEnvironmentR0; +#endif +outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; +#ifdef CLEARCOAT_BUMP +#ifdef NORMALXYSCALE +float clearCoatNormalScale=1.0; +#else +float clearCoatNormalScale=vClearCoatBumpInfos.y; +#endif +#if defined(TANGENT) && defined(NORMAL) +mat3 TBNClearCoat=vTBN; +#else +vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); +#endif +#if DEBUGMODE>0 +outParams.TBNClearCoat=TBNClearCoat; +#endif +#ifdef OBJECTSPACE_NORMALMAP +clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); +#else +clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; +#endif +outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); +#if DEBUGMODE>0 +outParams.clearCoatNdotV=clearCoatNdotV; +#endif +#ifdef CLEARCOAT_TINT +vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); +#endif +#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) +vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); +#endif +#if defined(REFLECTION) +float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); +#ifdef SPECULARAA +clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; +#endif +vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +clearCoatReflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +vec3 clearCoatReflectionCoords=clearCoatReflectionVector; +#else +vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +clearCoatReflectionCoords/=clearCoatReflectionVector.z; +#endif +clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; +#endif +sampleReflectionTexture( +clearCoatAlphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +clearCoatNdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +clearCoatRoughness, +#endif +reflectionSampler, +clearCoatReflectionCoords, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentClearCoatRadiance +); +#if DEBUGMODE>0 +outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; +#endif +#endif +#endif +#else +vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); +#endif +clearCoatEnvironmentReflectance*=clearCoatIntensity; +#if DEBUGMODE>0 +outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; +#endif +outParams.finalClearCoatRadianceScaled= +environmentClearCoatRadiance.rgb * +clearCoatEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(CLEARCOAT_TINT) +outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); +#endif +float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); +#endif +} +#endif +`;s_.v.IncludesShadersStore.pbrBlockClearcoat=oR;let oA=`struct iridescenceOutParams +{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; +#ifdef IRIDESCENCE +#define pbr_inline +#define inline +void iridescenceBlock( +in vec4 vIridescenceParams, +in float viewAngle, +in vec3 specularEnvironmentR0, +#ifdef IRIDESCENCE_TEXTURE +in vec2 iridescenceMapData, +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +in vec2 iridescenceThicknessMapData, +#endif +#ifdef CLEARCOAT +in float NdotVUnclamped, +#ifdef CLEARCOAT_TEXTURE +in vec2 clearCoatMapData, +#endif +#endif +out iridescenceOutParams outParams +) +{float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; +#ifdef IRIDESCENCE_TEXTURE +iridescenceIntensity*=iridescenceMapData.x; +#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE +iridescenceThicknessWeight=iridescenceMapData.g; +#endif +#endif +#if defined(IRIDESCENCE_THICKNESS_TEXTURE) +iridescenceThicknessWeight=iridescenceThicknessMapData.g; +#endif +float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; +#ifdef CLEARCOAT +float clearCoatIntensity=vClearCoatParams.x; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#endif +topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); +#endif +vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;} +#endif +`;s_.v.IncludesShadersStore.pbrBlockIridescence=oA;let oI=`struct subSurfaceOutParams +{vec3 specularEnvironmentReflectance; +#ifdef SS_REFRACTION +vec3 finalRefraction;vec3 surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +float alpha; +#endif +#ifdef REFLECTION +float refractionFactorForIrradiance; +#endif +#endif +#ifdef SS_TRANSLUCENCY +vec3 transmittance;float translucencyIntensity; +#ifdef REFLECTION +vec3 refractionIrradiance; +#endif +#endif +#if DEBUGMODE>0 +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec4 thicknessMap; +#endif +#ifdef SS_REFRACTION +vec4 environmentRefraction;vec3 refractionTransmittance; +#endif +#endif +}; +#ifdef SUBSURFACE +#define pbr_inline +#define inline +void subSurfaceBlock( +in vec3 vSubSurfaceIntensity, +in vec2 vThicknessParam, +in vec4 vTintColor, +in vec3 normalW, +in vec3 specularEnvironmentReflectance, +#ifdef SS_THICKNESSANDMASK_TEXTURE +in vec4 thicknessMap, +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +in vec4 refractionIntensityMap, +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +in vec4 translucencyIntensityMap, +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +in mat4 reflectionMatrix, +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +in vec3 irradianceVector_, +#endif +#if defined(REALTIME_FILTERING) +in samplerCube reflectionSampler, +in vec2 vReflectionFilteringInfo, +#endif +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +in samplerCube irradianceSampler, +#else +in sampler2D irradianceSampler, +#endif +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +in vec3 surfaceAlbedo, +#endif +#ifdef SS_REFRACTION +in vec3 vPositionW, +in vec3 viewDirectionW, +in mat4 view, +in vec4 vRefractionInfos, +in mat4 refractionMatrix, +in vec4 vRefractionMicrosurfaceInfos, +in vec4 vLightingIntensity, +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +in float alpha, +#endif +#ifdef SS_LODINREFRACTIONALPHA +in float NdotVUnclamped, +#endif +#ifdef SS_LINEARSPECULARREFRACTION +in float roughness, +#endif +in float alphaG, +#ifdef SS_REFRACTIONMAP_3D +in samplerCube refractionSampler, +#ifndef LODBASEDMICROSFURACE +in samplerCube refractionSamplerLow, +in samplerCube refractionSamplerHigh, +#endif +#else +in sampler2D refractionSampler, +#ifndef LODBASEDMICROSFURACE +in sampler2D refractionSamplerLow, +in sampler2D refractionSamplerHigh, +#endif +#endif +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#ifdef REALTIME_FILTERING +in vec2 vRefractionFilteringInfo, +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +in vec3 refractionPosition, +in vec3 refractionSize, +#endif +#endif +#ifdef SS_TRANSLUCENCY +in vec3 vDiffusionDistance, +#endif +out subSurfaceOutParams outParams +) +{outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; +#ifdef SS_REFRACTION +float refractionIntensity=vSubSurfaceIntensity.x; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; +#endif +#endif +#ifdef SS_TRANSLUCENCY +float translucencyIntensity=vSubSurfaceIntensity.y; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +#if defined(SS_USE_GLTF_TEXTURES) +float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; +#else +float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; +#endif +#if DEBUGMODE>0 +outParams.thicknessMap=thicknessMap; +#endif +#ifdef SS_MASK_FROM_THICKNESS_TEXTURE +#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE) +#if defined(SS_USE_GLTF_TEXTURES) +refractionIntensity*=thicknessMap.r; +#else +refractionIntensity*=thicknessMap.g; +#endif +#endif +#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE) +translucencyIntensity*=thicknessMap.b; +#endif +#endif +#else +float thickness=vThicknessParam.y; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +#ifdef SS_USE_GLTF_TEXTURES +refractionIntensity*=refractionIntensityMap.r; +#else +refractionIntensity*=refractionIntensityMap.g; +#endif +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +translucencyIntensity*=translucencyIntensityMap.b; +#endif +#ifdef SS_TRANSLUCENCY +thickness=maxEps(thickness);vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; +#endif +#ifdef SS_REFRACTION +vec4 environmentRefraction=vec4(0.,0.,0.,0.); +#ifdef ANISOTROPIC +vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y); +#else +vec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y); +#endif +#ifdef SS_REFRACTIONMAP_OPPOSITEZ +refractionVector.z*=-1.0; +#endif +#ifdef SS_REFRACTIONMAP_3D +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); +#else +#ifdef SS_USE_THICKNESS_AS_DEPTH +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); +#endif +vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; +#endif +#ifdef SS_HAS_THICKNESS +float ior=vRefractionInfos.y; +#else +float ior=vRefractionMicrosurfaceInfos.w; +#endif +#ifdef SS_LODINREFRACTIONALPHA +float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); +#elif defined(SS_LINEARSPECULARREFRACTION) +float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); +#else +float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); +#endif +#ifdef LODBASEDMICROSFURACE +refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; +#ifdef SS_LODINREFRACTIONALPHA +float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); +#else +float requestedRefractionLOD=refractionLOD; +#endif +#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) +environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); +#else +environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); +#endif +#else +float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( +sampleRefraction(refractionSamplerHigh,refractionCoords), +environmentRefractionMid, +lodRefractionNormalizedDoubled +);} else {environmentRefraction=mix( +environmentRefractionMid, +sampleRefraction(refractionSamplerLow,refractionCoords), +lodRefractionNormalizedDoubled-1.0 +);} +#endif +#ifdef SS_RGBDREFRACTION +environmentRefraction.rgb=fromRGBD(environmentRefraction); +#endif +#ifdef SS_GAMMAREFRACTION +environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); +#endif +environmentRefraction.rgb*=vRefractionInfos.x; +#endif +#ifdef SS_REFRACTION +vec3 refractionTransmittance=vec3(refractionIntensity); +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); +#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) +float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; +#else +vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); +#endif +#ifdef SS_ALBEDOFORREFRACTIONTINT +environmentRefraction.rgb*=surfaceAlbedo.rgb; +#endif +outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); +#ifdef REFLECTION +outParams.refractionFactorForIrradiance=(1.-refractionIntensity); +#endif +#ifdef UNUSED_MULTIPLEBOUNCES +vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); +#endif +refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; +#if DEBUGMODE>0 +outParams.refractionTransmittance=refractionTransmittance; +#endif +outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; +#if DEBUGMODE>0 +outParams.environmentRefraction=environmentRefraction; +#endif +#endif +#if defined(REFLECTION) && defined(SS_TRANSLUCENCY) +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) +vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#else +vec3 irradianceVector=irradianceVector_; +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) +#if defined(REALTIME_FILTERING) +vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo); +#else +vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); +#endif +#elif defined(USEIRRADIANCEMAP) +#ifdef REFLECTIONMAP_3D +vec3 irradianceCoords=irradianceVector; +#else +vec2 irradianceCoords=irradianceVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +irradianceCoords/=irradianceVector.z; +#endif +irradianceCoords.y=1.0-irradianceCoords.y; +#endif +vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); +#ifdef RGBDREFLECTION +refractionIrradiance.rgb=fromRGBD(refractionIrradiance); +#endif +#ifdef GAMMAREFLECTION +refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); +#endif +#else +vec4 refractionIrradiance=vec4(0.); +#endif +refractionIrradiance.rgb*=transmittance; +#ifdef SS_ALBEDOFORTRANSLUCENCYTINT +refractionIrradiance.rgb*=surfaceAlbedo.rgb; +#endif +outParams.refractionIrradiance=refractionIrradiance.rgb; +#endif +} +#endif +`;s_.v.IncludesShadersStore.pbrBlockSubSurface=oI;let oM=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; +#endif +vec3 geometricNormalW=normalW; +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; +#endif +`;s_.v.IncludesShadersStore.pbrBlockNormalGeometric=oM;let oD=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) +vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; +#if defined(TWOSIDEDLIGHTING) +faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; +#endif +normalW*=sign(dot(normalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +`;s_.v.IncludesShadersStore.pbrBlockNormalFinal=oD;let oO=`#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +#ifdef GAMMALIGHTMAP +lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +`;s_.v.IncludesShadersStore.pbrBlockLightmapInit=oO;let oN=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); +#ifdef SPECULARAA +alphaG+=AARoughnessFactors.y; +#endif +#if defined(ENVIRONMENTBRDF) +vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +#ifdef AMBIENTINGRAYSCALE +float ambientMonochrome=aoOut.ambientOcclusionColor.r; +#else +float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); +#endif +float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); +#endif +#endif +#endif +#endif +`;s_.v.IncludesShadersStore.pbrBlockGeometryInfo=oN;let oF=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); +#else +vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); +#endif +#ifdef ALPHAFRESNEL +float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; +#endif +`;s_.v.IncludesShadersStore.pbrBlockReflectance0=oF;let oB=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); +#ifdef RADIANCEOCCLUSION +specularEnvironmentReflectance*=seo; +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +specularEnvironmentReflectance*=eho; +#endif +#endif +#endif +#else +vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); +#endif +#ifdef CLEARCOAT +specularEnvironmentReflectance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +specularEnvironmentReflectance*=clearcoatOut.absorption; +#endif +#endif +`;s_.v.IncludesShadersStore.pbrBlockReflectance=oB;let oL=`vec3 diffuseBase=vec3(0.,0.,0.); +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +#ifdef CLEARCOAT +vec3 clearCoatBase=vec3(0.,0.,0.); +#endif +#ifdef SHEEN +vec3 sheenBase=vec3(0.,0.,0.); +#endif +preLightingInfo preInfo;lightingInfo info;float shadow=1.; +float aggShadow=0.;float numLights=0.; +#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +vec3 absorption=vec3(0.); +#endif +`;s_.v.IncludesShadersStore.pbrBlockDirectLighting=oL;let ow=`aggShadow=aggShadow/numLights; +#if defined(ENVIRONMENTBRDF) +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); +#endif +#endif +#ifndef METALLICWORKFLOW +#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION +surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; +#endif +#endif +#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) +surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; +#endif +#ifdef REFLECTION +vec3 finalIrradiance=reflectionOut.environmentIrradiance; +#if defined(CLEARCOAT) +finalIrradiance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +finalIrradiance*=clearcoatOut.absorption; +#endif +#endif +#if defined(SS_REFRACTION) +finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; +#endif +#if defined(SS_TRANSLUCENCY) +finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; +#endif +finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalSpecularScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalSpecularScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef REFLECTION +vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalRadianceScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalRadianceScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef SHEEN +vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; +#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef CLEARCOAT +vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; +#ifdef CLEARCOAT_TINT +subSurfaceOut.finalRefraction*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef ALPHABLEND +float luminanceOverAlpha=0.0; +#if defined(REFLECTION) && defined(RADIANCEOVERALPHA) +luminanceOverAlpha+=getLuminance(finalRadianceScaled); +#if defined(CLEARCOAT) +luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); +#endif +#endif +#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) +luminanceOverAlpha+=getLuminance(finalSpecularScaled); +#endif +#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) +luminanceOverAlpha+=getLuminance(finalClearCoatScaled); +#endif +#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) +alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); +#endif +#endif +`;s_.v.IncludesShadersStore.pbrBlockFinalLitComponents=ow;let oU=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; +#ifdef EMISSIVE +vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; +#ifdef GAMMAEMISSIVE +finalEmissive*=toLinearSpace(emissiveColorTex.rgb); +#else +finalEmissive*=emissiveColorTex.rgb; +#endif +finalEmissive*= vEmissiveInfos.y; +#endif +finalEmissive*=vLightingIntensity.y; +#ifdef AMBIENT +vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); +#else +vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; +#endif +finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; +`;s_.v.IncludesShadersStore.pbrBlockFinalUnlitComponents=oU;let oV=`vec4 finalColor=vec4( +#ifndef UNLIT +#ifdef REFLECTION +finalIrradiance + +#endif +#ifdef SPECULARTERM +finalSpecularScaled + +#endif +#ifdef SHEEN +finalSheenScaled + +#endif +#ifdef CLEARCOAT +finalClearCoatScaled + +#endif +#ifdef REFLECTION +finalRadianceScaled + +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled + +#endif +#ifdef CLEARCOAT +clearcoatOut.finalClearCoatRadianceScaled + +#endif +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction + +#endif +#endif +finalAmbient + +finalDiffuse, +alpha); +#ifdef LIGHTMAP +#ifndef LIGHTMAPEXCLUDED +#ifdef USELIGHTMAPASSHADOWMAP +finalColor.rgb*=lightmapColor.rgb; +#else +finalColor.rgb+=lightmapColor.rgb; +#endif +#endif +#endif +finalColor.rgb+=finalEmissive; +#define CUSTOM_FRAGMENT_BEFORE_FOG +finalColor=max(finalColor,0.0); +`;s_.v.IncludesShadersStore.pbrBlockFinalColorComposition=oV;let ok=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) +#if !defined(SKIPFINALCOLORCLAMP) +finalColor.rgb=clamp(finalColor.rgb,0.,30.0); +#endif +#else +finalColor=applyImageProcessing(finalColor); +#endif +finalColor.a*=visibility; +#ifdef PREMULTIPLYALPHA +finalColor.rgb*=finalColor.a; +#endif +`;s_.v.IncludesShadersStore.pbrBlockImageProcessing=ok;let oG=`#if DEBUGMODE>0 +if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { +#if DEBUGMODE==1 +gl_FragColor.rgb=vPositionW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==2 && defined(NORMAL) +gl_FragColor.rgb=vNormalW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) +gl_FragColor.rgb=TBN[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) +gl_FragColor.rgb=TBN[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==5 +gl_FragColor.rgb=normalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==6 && defined(MAINUV1) +gl_FragColor.rgb=vec3(vMainUV1,0.0); +#elif DEBUGMODE==7 && defined(MAINUV2) +gl_FragColor.rgb=vec3(vMainUV2,0.0); +#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==10 && defined(CLEARCOAT) +gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==11 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicNormal; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==12 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicTangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==13 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==20 && defined(ALBEDO) +gl_FragColor.rgb=albedoTexture.rgb; +#ifndef GAMMAALBEDO +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==21 && defined(AMBIENT) +gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; +#elif DEBUGMODE==22 && defined(OPACITY) +gl_FragColor.rgb=opacityMap.rgb; +#elif DEBUGMODE==23 && defined(EMISSIVE) +gl_FragColor.rgb=emissiveColorTex.rgb; +#ifndef GAMMAEMISSIVE +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==24 && defined(LIGHTMAP) +gl_FragColor.rgb=lightmapColor.rgb; +#ifndef GAMMALIGHTMAP +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; +#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); +#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; +#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) +gl_FragColor.rgb=sheenOut.sheenMapData.rgb; +#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) +gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; +#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) +gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; +#elif DEBUGMODE==32 && defined(BUMP) +gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; +#elif DEBUGMODE==40 && defined(SS_REFRACTION) +gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==41 && defined(REFLECTION) +gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) +gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==50 +gl_FragColor.rgb=diffuseBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==51 && defined(SPECULARTERM) +gl_FragColor.rgb=specularBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==52 && defined(CLEARCOAT) +gl_FragColor.rgb=clearCoatBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==53 && defined(SHEEN) +gl_FragColor.rgb=sheenBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==54 && defined(REFLECTION) +gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==60 +gl_FragColor.rgb=surfaceAlbedo.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==61 +gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==62 && defined(METALLICWORKFLOW) +gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); +#elif DEBUGMODE==71 && defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.metallicF0; +#elif DEBUGMODE==63 +gl_FragColor.rgb=vec3(roughness); +#elif DEBUGMODE==64 +gl_FragColor.rgb=vec3(alphaG); +#elif DEBUGMODE==65 +gl_FragColor.rgb=vec3(NdotV); +#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==67 && defined(CLEARCOAT) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); +#elif DEBUGMODE==68 && defined(CLEARCOAT) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); +#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) +gl_FragColor.rgb=subSurfaceOut.transmittance; +#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) +gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; +#elif DEBUGMODE==72 +gl_FragColor.rgb=vec3(microSurface); +#elif DEBUGMODE==73 +gl_FragColor.rgb=vAlbedoColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) +gl_FragColor.rgb=vReflectivityColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==75 +gl_FragColor.rgb=vEmissiveColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) +gl_FragColor.rgb=vec3(seo); +#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) +gl_FragColor.rgb=vec3(eho); +#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) +gl_FragColor.rgb=vec3(energyConservationFactor); +#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +gl_FragColor.rgb=specularEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) +gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==86 && defined(ALPHABLEND) +gl_FragColor.rgb=vec3(luminanceOverAlpha); +#elif DEBUGMODE==87 +gl_FragColor.rgb=vec3(alpha); +#elif DEBUGMODE==88 && defined(ALBEDO) +gl_FragColor.rgb=vec3(albedoTexture.a); +#else +float stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); +#endif +gl_FragColor.rgb*=vDebugMode.y; +#ifdef DEBUGMODE_NORMALIZE +gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; +#endif +#ifdef DEBUGMODE_GAMMA +gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); +#endif +gl_FragColor.a=1.0; +#ifdef PREPASS +gl_FragData[0]=toLinearSpace(gl_FragColor); +gl_FragData[1]=vec4(0.,0.,0.,0.); +#endif +#ifdef DEBUGMODE_FORCERETURN +return; +#endif +} +#endif +`;s_.v.IncludesShadersStore.pbrDebug=oG;let oz=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#extension GL_OES_standard_derivatives : enable +#endif +#ifdef LODBASEDMICROSFURACE +#extension GL_EXT_shader_texture_lod : enable +#endif +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include<prePassDeclaration>[SCENE_MRT_COUNT] +precision highp float; +#include<oitDeclaration> +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE +#endif +#include<__decl__pbrFragment> +#include<pbrFragmentExtraDeclaration> +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include<pbrFragmentSamplersDeclaration> +#include<imageProcessingDeclaration> +#include<clipPlaneFragmentDeclaration> +#include<logDepthDeclaration> +#include<fogFragmentDeclaration> +#include<helperFunctions> +#include<subSurfaceScatteringFunctions> +#include<importanceSampling> +#include<pbrHelperFunctions> +#include<imageProcessingFunctions> +#include<shadowsFragmentFunctions> +#include<harmonicsFunctions> +#include<pbrDirectLightingSetupFunctions> +#include<pbrDirectLightingFalloffFunctions> +#include<pbrBRDFFunctions> +#include<hdrFilteringFunctions> +#include<pbrDirectLightingFunctions> +#include<pbrIBLFunctions> +#include<bumpFragmentMainFunctions> +#include<bumpFragmentFunctions> +#ifdef REFLECTION +#include<reflectionFunction> +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +#include<pbrBlockAlbedoOpacity> +#include<pbrBlockReflectivity> +#include<pbrBlockAmbientOcclusion> +#include<pbrBlockAlphaFresnel> +#include<pbrBlockAnisotropic> +#include<pbrBlockReflection> +#include<pbrBlockSheen> +#include<pbrBlockClearcoat> +#include<pbrBlockIridescence> +#include<pbrBlockSubSurface> +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +#include<pbrBlockNormalGeometric> +#include<bumpFragment> +#include<pbrBlockNormalFinal> +albedoOpacityOutParams albedoOpacityOut; +#ifdef ALBEDO +vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#endif +#ifdef DECAL +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#endif +albedoOpacityBlock( +vAlbedoColor, +#ifdef ALBEDO +albedoTexture, +vAlbedoInfos, +#endif +#ifdef OPACITY +opacityMap, +vOpacityInfos, +#endif +#ifdef DETAIL +detailColor, +vDetailInfos, +#endif +#ifdef DECAL +decalColor, +vDecalInfos, +#endif +albedoOpacityOut +);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; +#define CUSTOM_FRAGMENT_UPDATE_ALPHA +#include<depthPrePass> +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +ambientOcclusionOutParams aoOut; +#ifdef AMBIENT +vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; +#endif +ambientOcclusionBlock( +#ifdef AMBIENT +ambientOcclusionColorMap, +vAmbientInfos, +#endif +aoOut +); +#include<pbrBlockLightmapInit> +#ifdef UNLIT +vec3 diffuseBase=vec3(1.,1.,1.); +#else +vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; +#if defined(REFLECTIVITY) +vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; +#ifndef METALLICWORKFLOW +#ifdef REFLECTIVITY_GAMMA +surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); +#endif +surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; +#endif +#endif +#if defined(MICROSURFACEMAP) +vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; +#endif +#ifdef METALLICWORKFLOW +vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; +#ifdef REFLECTANCE +vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); +#ifdef REFLECTANCE_GAMMA +reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); +#endif +metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; +#endif +#ifdef METALLIC_REFLECTANCE +vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); +#ifdef METALLIC_REFLECTANCE_GAMMA +metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); +#endif +#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY +metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; +#endif +metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; +#endif +#endif +reflectivityBlock( +vReflectivityColor, +#ifdef METALLICWORKFLOW +surfaceAlbedo, +metallicReflectanceFactors, +#endif +#ifdef REFLECTIVITY +vReflectivityInfos, +surfaceMetallicOrReflectivityColorMap, +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +aoOut.ambientOcclusionColor, +#endif +#ifdef MICROSURFACEMAP +microSurfaceTexel, +#endif +#ifdef DETAIL +detailColor, +vDetailInfos, +#endif +reflectivityOut +);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; +#ifdef METALLICWORKFLOW +surfaceAlbedo=reflectivityOut.surfaceAlbedo; +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; +#endif +#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +alphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock( +normalW, +viewDirectionW, +alpha, +microSurface, +alphaFresnelOut +);alpha=alphaFresnelOut.alpha; +#endif +#endif +#include<pbrBlockGeometryInfo> +#ifdef ANISOTROPIC +anisotropicOutParams anisotropicOut; +#ifdef ANISOTROPIC_TEXTURE +vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; +#endif +anisotropicBlock( +vAnisotropy, +roughness, +#ifdef ANISOTROPIC_TEXTURE +anisotropyMapData, +#endif +TBN, +normalW, +viewDirectionW, +anisotropicOut +); +#endif +#ifdef REFLECTION +reflectionOutParams reflectionOut; +#ifndef USE_CUSTOM_REFLECTION +reflectionBlock( +vPositionW, +normalW, +alphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#ifdef ANISOTROPIC +anisotropicOut, +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +roughness, +#endif +reflectionSampler, +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +vEnvironmentIrradiance, +#endif +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +reflectionMatrix, +#endif +#endif +#ifdef USEIRRADIANCEMAP +irradianceSampler, +#endif +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +reflectionOut +); +#else +#define CUSTOM_REFLECTION +#endif +#endif +#include<pbrBlockReflectance0> +#ifdef SHEEN +sheenOutParams sheenOut; +#ifdef SHEEN_TEXTURE +vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); +#endif +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; +#endif +sheenBlock( +vSheenColor, +#ifdef SHEEN_ROUGHNESS +vSheenRoughness, +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +sheenMapRoughnessData, +#endif +#endif +roughness, +#ifdef SHEEN_TEXTURE +sheenMapData, +vSheenInfos.y, +#endif +reflectance, +#ifdef SHEEN_LINKWITHALBEDO +baseColor, +surfaceAlbedo, +#endif +#ifdef ENVIRONMENTBRDF +NdotV, +environmentBrdf, +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +AARoughnessFactors, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +vLightingIntensity, +reflectionSampler, +reflectionOut.reflectionCoords, +NdotVUnclamped, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +seo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +eho, +#endif +#endif +sheenOut +); +#ifdef SHEEN_LINKWITHALBEDO +surfaceAlbedo=sheenOut.surfaceAlbedo; +#endif +#endif +#ifdef CLEARCOAT +#ifdef CLEARCOAT_TEXTURE +vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; +#endif +#endif +#ifdef IRIDESCENCE +iridescenceOutParams iridescenceOut; +#ifdef IRIDESCENCE_TEXTURE +vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; +#endif +iridescenceBlock( +vIridescenceParams, +NdotV, +specularEnvironmentR0, +#ifdef IRIDESCENCE_TEXTURE +iridescenceMapData, +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +iridescenceThicknessMapData, +#endif +#ifdef CLEARCOAT +NdotVUnclamped, +#ifdef CLEARCOAT_TEXTURE +clearCoatMapData, +#endif +#endif +iridescenceOut +);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; +#endif +clearcoatOutParams clearcoatOut; +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); +#endif +#ifdef CLEARCOAT_BUMP +vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); +#endif +clearcoatBlock( +vPositionW, +geometricNormalW, +viewDirectionW, +vClearCoatParams, +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +clearCoatMapRoughnessData, +#endif +specularEnvironmentR0, +#ifdef CLEARCOAT_TEXTURE +clearCoatMapData, +#endif +#ifdef CLEARCOAT_TINT +vClearCoatTintParams, +clearCoatColorAtDistance, +vClearCoatRefractionParams, +#ifdef CLEARCOAT_TINT_TEXTURE +clearCoatTintMapData, +#endif +#endif +#ifdef CLEARCOAT_BUMP +vClearCoatBumpInfos, +clearCoatBumpMapData, +vClearCoatBumpUV, +#if defined(TANGENT) && defined(NORMAL) +vTBN, +#else +vClearCoatTangentSpaceParams, +#endif +#ifdef OBJECTSPACE_NORMALMAP +normalMatrix, +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +faceNormal, +#endif +#ifdef REFLECTION +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +vLightingIntensity, +reflectionSampler, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +ambientMonochrome, +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +(gl_FrontFacing ? 1. : -1.), +#endif +clearcoatOut +); +#else +clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; +#endif +#include<pbrBlockReflectance> +subSurfaceOutParams subSurfaceOut; +#ifdef SUBSURFACE +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); +#endif +subSurfaceBlock( +vSubSurfaceIntensity, +vThicknessParam, +vTintColor, +normalW, +specularEnvironmentReflectance, +#ifdef SS_THICKNESSANDMASK_TEXTURE +thicknessMap, +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +refractionIntensityMap, +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +translucencyIntensityMap, +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +reflectionMatrix, +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +reflectionOut.irradianceVector, +#endif +#if defined(REALTIME_FILTERING) +reflectionSampler, +vReflectionFilteringInfo, +#endif +#endif +#ifdef USEIRRADIANCEMAP +irradianceSampler, +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +surfaceAlbedo, +#endif +#ifdef SS_REFRACTION +vPositionW, +viewDirectionW, +view, +vRefractionInfos, +refractionMatrix, +vRefractionMicrosurfaceInfos, +vLightingIntensity, +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha, +#endif +#ifdef SS_LODINREFRACTIONALPHA +NdotVUnclamped, +#endif +#ifdef SS_LINEARSPECULARREFRACTION +roughness, +#endif +alphaG, +refractionSampler, +#ifndef LODBASEDMICROSFURACE +refractionSamplerLow, +refractionSamplerHigh, +#endif +#ifdef ANISOTROPIC +anisotropicOut, +#endif +#ifdef REALTIME_FILTERING +vRefractionFilteringInfo, +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +vRefractionPosition, +vRefractionSize, +#endif +#endif +#ifdef SS_TRANSLUCENCY +vDiffusionDistance, +#endif +subSurfaceOut +); +#ifdef SS_REFRACTION +surfaceAlbedo=subSurfaceOut.surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha=subSurfaceOut.alpha; +#endif +#endif +#else +subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; +#endif +#include<pbrBlockDirectLighting> +#include<lightFragment>[0..maxSimultaneousLights] +#include<pbrBlockFinalLitComponents> +#endif +#include<pbrBlockFinalUnlitComponents> +#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION +#include<pbrBlockFinalColorComposition> +#include<logDepthFragment> +#include<fogFragment>(color,finalColor) +#include<pbrBlockImageProcessing> +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +vec3 sqAlbedo=sqrt(surfaceAlbedo); +#endif +#ifdef PREPASS_IRRADIANCE +vec3 irradiance=finalDiffuse; +#ifndef UNLIT +#ifdef REFLECTION +irradiance+=finalIrradiance; +#endif +#endif +#ifdef SS_SCATTERING +gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); +irradiance/=sqAlbedo; +#else +gl_FragData[0]=finalColor; +float scatteringDiffusionProfile=255.; +#endif +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); +#else +gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#ifndef UNLIT +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=finalColor; +#endif +#include<oitFragment> +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} +#endif +#include<pbrDebug> +#define CUSTOM_FRAGMENT_MAIN_END +} +`;s_.v.ShadersStore.pbrPixelShader=oz;let oW=`uniform mat4 view;uniform mat4 viewProjection; +#ifdef ALBEDO +uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; +#endif +#ifdef AMBIENT +uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; +#endif +#ifdef OPACITY +uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; +#endif +#ifdef REFLECTIVITY +uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; +#endif +#ifdef METALLIC_REFLECTANCE +uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; +#endif +#ifdef REFLECTANCE +uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; +#endif +#ifdef MICROSURFACEMAP +uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; +#endif +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform vec4 vClearCoatInfos; +#endif +#ifdef CLEARCOAT_TEXTURE +uniform mat4 clearCoatMatrix; +#endif +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS +uniform mat4 clearCoatRoughnessMatrix; +#endif +#ifdef CLEARCOAT_BUMP +uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; +#endif +#ifdef CLEARCOAT_TINT_TEXTURE +uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; +#endif +#endif +#ifdef IRIDESCENCE +#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) +uniform vec4 vIridescenceInfos; +#endif +#ifdef IRIDESCENCE_TEXTURE +uniform mat4 iridescenceMatrix; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +uniform mat4 iridescenceThicknessMatrix; +#endif +#endif +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_TEXTURE +uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; +#endif +#endif +#ifdef SHEEN +#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) +uniform vec4 vSheenInfos; +#endif +#ifdef SHEEN_TEXTURE +uniform mat4 sheenMatrix; +#endif +#ifdef SHEEN_TEXTURE_ROUGHNESS +uniform mat4 sheenRoughnessMatrix; +#endif +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; +#endif +#endif +#ifdef NORMAL +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; +#else +uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; +#endif +#endif +#endif +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos;uniform mat4 detailMatrix; +#endif +#include<decalVertexDeclaration> +#define ADDITIONAL_VERTEX_DECLARATION +`;s_.v.IncludesShadersStore.pbrVertexDeclaration=oW;let oH=`precision highp float; +#include<__decl__pbrVertex> +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include<uvAttributeDeclaration>[2..7] +#include<mainUVVaryingDeclaration>[1..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include<helperFunctions> +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<instancesDeclaration> +#include<prePassVertexDeclaration> +#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) +#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) +#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) +#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) +#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) +#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +#ifdef CLEARCOAT +#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) +#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) +#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) +#endif +#ifdef IRIDESCENCE +#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) +#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) +#endif +#ifdef SHEEN +#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) +#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#endif +#ifdef ANISOTROPIC +#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) +#endif +#ifdef SUBSURFACE +#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) +#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) +#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) +#endif +varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#include<harmonicsFunctions> +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include<bumpVertexDeclaration> +#include<clipPlaneVertexDeclaration> +#include<fogVertexDeclaration> +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include<logDepthDeclaration> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include<instancesVertex> +#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); +#include<prePassVertex> +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#if DEBUGMODE>0 +vClipSpacePosition=gl_Position; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#include<uvVariableDeclaration>[2..7] +#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#ifdef CLEARCOAT +#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) +#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) +#endif +#ifdef IRIDESCENCE +#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) +#endif +#ifdef SHEEN +#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z) +#endif +#ifdef ANISOTROPIC +#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) +#endif +#ifdef SUBSURFACE +#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) +#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) +#endif +#include<bumpVertex> +#include<clipPlaneVertex> +#include<fogVertex> +#include<shadowsVertex>[0..maxSimultaneousLights] +#include<vertexColorMixing> +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#include<logDepthVertex> +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.pbrVertexShader=oH;let MaterialClearCoatDefines=class MaterialClearCoatDefines extends sn.H{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}};let pbrClearCoatConfiguration_PBRClearCoatConfiguration=class pbrClearCoatConfiguration_PBRClearCoatConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new MaterialClearCoatDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,this.indexOfRefraction=pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=rg.Wo.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;let r=this._material._disableBumpMap;return!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.ClearCoatTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!MaterialFlags.ClearCoatTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())&&(!i.getCaps().standardDerivatives||!this._bumpTexture||!MaterialFlags.ClearCoatBumpTextureEnabled||!!r||!!this._bumpTexture.isReady())&&(!this._isTintEnabled||!this._tintTexture||!MaterialFlags.ClearCoatTintTextureEnabled||!!this._tintTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_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.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.ClearCoatTextureEnabled?so.G.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&MaterialFlags.ClearCoatTextureEnabled?so.G.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&MaterialFlags.ClearCoatBumpTextureEnabled?so.G.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=this._material._disableBumpMap,f=this._material._invertNormalMapX,m=this._material._invertNormalMapY,g=d.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!p||!e.isSync){g&&MaterialFlags.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),so.G.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&MaterialFlags.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&so.G.BindTextureMatrix(this._texture,e,"clearCoat"),!this._textureRoughness||g||d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE||so.G.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&MaterialFlags.ClearCoatTextureEnabled&&!_&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),so.G.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",f?1:-1,m?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",f?-1:1,m?-1:1)),this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),so.G.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);let r=1-this._indexOfRefraction,p=1+this._indexOfRefraction,v=Math.pow(-r/p,2),x=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",v,x,r,p),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&MaterialFlags.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!g&&!d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialFlags.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&MaterialFlags.ClearCoatBumpTextureEnabled&&!_&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||this._textureRoughness===e||this._bumpTexture===e||this._tintTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,r,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(r=this._bumpTexture)||void 0===r||r.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"}]}}};pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction=1.5,(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.qC)()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"roughness",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"indexOfRefraction",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"texture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"useRoughnessFromMainTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"textureRoughness",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"remapF0OnInterfaceChange",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"bumpTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"isTintEnabled",void 0),(0,rH.gn)([(0,rb.n9)()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintColor",void 0),(0,rH.gn)([(0,rb.qC)()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintColorAtDistance",void 0),(0,rH.gn)([(0,rb.qC)()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintThickness",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintTexture",void 0);let MaterialIridescenceDefines=class MaterialIridescenceDefines extends sn.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}};let pbrIridescenceConfiguration_PBRIridescenceConfiguration=class pbrIridescenceConfiguration_PBRIridescenceConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new MaterialIridescenceDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMinimumThickness,this.maximumThickness=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness,this.indexOfRefraction=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.IridescenceTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._thicknessTexture||!MaterialFlags.IridescenceTextureEnabled||!!this._thicknessTexture.isReadyOrNotBlocking())}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&&MaterialFlags.IridescenceTextureEnabled?so.G.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&MaterialFlags.IridescenceTextureEnabled?so.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,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&p&&e.isSync||(_&&MaterialFlags.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),so.G.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&MaterialFlags.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._thicknessTexture)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._thicknessTexture)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&so.G.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||_||d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||so.G.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&MaterialFlags.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!_&&!d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&MaterialFlags.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"}]}}};pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMinimumThickness=100,pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness=400,pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction=1.3,(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.qC)()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"minimumThickness",void 0),(0,rH.gn)([(0,rb.qC)()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"maximumThickness",void 0),(0,rH.gn)([(0,rb.qC)()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"indexOfRefraction",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"texture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"thicknessTexture",void 0);let MaterialAnisotropicDefines=class MaterialAnisotropicDefines extends sn.H{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}};let pbrAnisotropicConfiguration_PBRAnisotropicConfiguration=class pbrAnisotropicConfiguration_PBRAnisotropicConfiguration extends MaterialPluginBase{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 MaterialAnisotropicDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new rm.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||!MaterialFlags.AnisotropicTextureEnabled||!!this._texture.isReadyOrNotBlocking()}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(rz.o.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.AnisotropicTextureEnabled?so.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;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&MaterialFlags.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),so.G.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&MaterialFlags.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,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.QC)()],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"direction",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"texture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"legacy",void 0);let MaterialSheenDefines=class MaterialSheenDefines extends sn.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}};let pbrSheenConfiguration_PBRSheenConfiguration=class pbrSheenConfiguration_PBRSheenConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new MaterialSheenDefines,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=rg.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){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.SheenTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!MaterialFlags.SheenTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())}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&&MaterialFlags.SheenTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&MaterialFlags.SheenTextureEnabled?so.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,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=d.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&p&&e.isSync||(_&&MaterialFlags.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),so.G.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&MaterialFlags.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&so.G.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||_||d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||so.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&&MaterialFlags.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!_&&!d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialFlags.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,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"linkSheenWithAlbedo",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.n9)()],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"color",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"texture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"useRoughnessFromMainTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"roughness",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"textureRoughness",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"albedoScaling",void 0);let MaterialSubSurfaceDefines=class MaterialSubSurfaceDefines extends sn.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}};let pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration=class pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration extends MaterialPluginBase{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new MaterialSubSurfaceDefines,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=rg.Wo.White(),this.tintColorAtDistance=1,this.diffusionDistance=rg.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&&MaterialFlags.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;let e=this._getRefractionTexture(t);if(e&&MaterialFlags.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){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,e.SS_USE_GLTF_TEXTURES=!1;return}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;let i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,r=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(r||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&so.G.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&!s&&so.G.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&!s&&so.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){let i=this._getRefractionTexture(t);i&&MaterialFlags.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;r.getRenderingMesh().getWorldMatrix().decompose(rm.jp.Vector3[0]);let s=Math.max(Math.abs(rm.jp.Vector3[0].x),Math.abs(rm.jp.Vector3[0].y),Math.abs(rm.jp.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;let s=r.materialDefines,n=this._material.isFrozen,a=this._material.realTimeFiltering,o=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),so.G.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),so.G.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),so.G.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&MaterialFlags.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;!l.isCube&&l.depth&&(t=l.depth);let i=l.getSize().width,r=this.volumeIndexOfRefraction;e.updateFloat4("vRefractionInfos",l.level,1/r,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),a&&e.updateFloat2("vRefractionFilteringInfo",i,rE.R.Log2(i)),l.boundingBoxSize&&(e.updateVector3("vRefractionPosition",l.boundingBoxPosition),e.updateVector3("vRefractionSize",l.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&&MaterialFlags.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&MaterialFlags.RefractionTextureEnabled&&(o?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){MaterialFlags.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!MaterialFlags.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,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isRefractionEnabled",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isTranslucencyEnabled",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markScenePrePassDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isScatteringEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"_scatteringDiffusionProfileIndex",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionIntensity",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"translucencyIntensity",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useAlbedoToTintRefraction",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useAlbedoToTintTranslucency",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"thicknessTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"indexOfRefraction",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"_volumeIndexOfRefraction",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"volumeIndexOfRefraction",null),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"invertRefractionY",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"linkRefractionWithTransparency",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"minimumThickness",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"maximumThickness",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useThicknessAsDepth",void 0),(0,rH.gn)([(0,rb.n9)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"tintColor",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"tintColorAtDistance",void 0),(0,rH.gn)([(0,rb.n9)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"diffusionDistance",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useMaskFromThicknessTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionIntensityTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"translucencyIntensityTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useGltfStyleTextures",void 0);let oX={effect:null,subMesh:null};let PBRMaterialDefines=class PBRMaterialDefines extends sn.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.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!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.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}};let pbrBaseMaterial_PBRBaseMaterial=class pbrBaseMaterial_PBRBaseMaterial extends PushMaterial{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new rm.Lt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=pbrBaseMaterial_PBRBaseMaterial.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=rg.Wo.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new rg.Wo(0,0,0),this._albedoColor=new rg.Wo(1,1,1),this._reflectivityColor=new rg.Wo(1,1,1),this._reflectionColor=new rg.Wo(1,1,1),this._emissiveColor=new rg.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=pbrBaseMaterial_PBRBaseMaterial.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 sp.t(16),this._globalAmbientColor=new rg.Wo(0,0,0),this._useLogarithmicDepth=!1,this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new pbrBRDFConfiguration_PBRBRDFConfiguration(this),this.clearCoat=new pbrClearCoatConfiguration_PBRClearCoatConfiguration(this),this.iridescence=new pbrIridescenceConfiguration_PBRIridescenceConfiguration(this),this.anisotropy=new pbrAnisotropicConfiguration_PBRAnisotropicConfiguration(this),this.sheen=new pbrSheenConfiguration_PBRSheenConfiguration(this),this.subSurface=new pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration(this),this.detailMap=new material_detailMapConfiguration_DetailMapConfiguration(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),MaterialFlags.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this.getScene()),this.prePassConfiguration=new PrePassConfiguration}get hasRenderTargetTextures(){return!!MaterialFlags.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===pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE||this._transparencyMode===pbrBaseMaterial_PBRBaseMaterial.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||!e.disableAlphaBlending)&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var r;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(sG.S.GetDefineNames,this._eventInfo),t.materialDefines=new PBRMaterialDefines(this._eventInfo.defineNames));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=this.getScene(),a=n.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;let e=this._getReflectionTexture();if(e&&MaterialFlags.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&(null===(r=e.getInternalTexture())||void 0===r?void 0:r._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(MaterialFlags.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(a.getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&MaterialFlags.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;a.getCaps().standardDerivatives||e.isVerticesDataPresent(rz.o.NormalKind)||(e.createNormals(!0),rT.Y.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));let o=t.effect,l=s._areLightsDisposed,h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),u=!1;if(h){if(this._onEffectCreatedObservable&&(oX.effect=h,oX.subMesh=t,this._onEffectCreatedObservable.notifyObservers(oX)),this.allowShaderHotSwapping&&o&&!h.isReady()){if(h=o,s.markAsUnprocessed(),u=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,s,this._materialContext)}return!!(t.effect&&t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!u,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return null!=this._metallic||null!=this._roughness||!!this._metallicTexture}_prepareEffect(e,t,i=null,r=null,s=null,n=null,a){if(this._prepareDefines(e,t,s,n,a),!t.isDirty)return null;t.markAsProcessed();let o=this.getScene(),l=o.getEngine(),h=new EffectFallbacks,u=0;t.USESPHERICALINVERTEX&&h.addFallback(u++,"USESPHERICALINVERTEX"),t.FOG&&h.addFallback(u,"FOG"),t.SPECULARAA&&h.addFallback(u,"SPECULARAA"),t.POINTSIZE&&h.addFallback(u,"POINTSIZE"),t.LOGARITHMICDEPTH&&h.addFallback(u,"LOGARITHMICDEPTH"),t.PARALLAX&&h.addFallback(u,"PARALLAX"),t.PARALLAX_RHS&&h.addFallback(u,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&h.addFallback(u++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&h.addFallback(u++,"ENVIRONMENTBRDF"),t.TANGENT&&h.addFallback(u++,"TANGENT"),t.BUMP&&h.addFallback(u++,"BUMP"),u=so.G.HandleFallbacksForShadows(t,h,this._maxSimultaneousLights,u++),t.SPECULARTERM&&h.addFallback(u++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&h.addFallback(u++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&h.addFallback(u++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&h.addFallback(u++,"LIGHTMAP"),t.NORMAL&&h.addFallback(u++,"NORMAL"),t.AMBIENT&&h.addFallback(u++,"AMBIENT"),t.EMISSIVE&&h.addFallback(u++,"EMISSIVE"),t.VERTEXCOLOR&&h.addFallback(u++,"VERTEXCOLOR"),t.MORPHTARGETS&&h.addFallback(u++,"MORPHTARGETS"),t.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");let c=[rz.o.PositionKind];t.NORMAL&&c.push(rz.o.NormalKind),t.TANGENT&&c.push(rz.o.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(rz.o.ColorKind),t.INSTANCESCOLOR&&c.push(rz.o.ColorInstanceKind),so.G.PrepareAttributesForBones(c,e,t,h),so.G.PrepareAttributesForInstances(c,t),so.G.PrepareAttributesForMorphTargets(c,e,t),so.G.PrepareAttributesForBakedVertexAnimation(c,e,t);let d="pbr",p=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"],m={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=u,this._eventInfo.defines=t,this._eventInfo.uniforms=p,this._eventInfo.attributes=c,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(sG.S.PrepareEffect,this._eventInfo),PrePassConfiguration.AddUniforms(p),PrePassConfiguration.AddSamplers(_),(0,nX.qx)(p),sv.$&&(sv.$.PrepareUniforms(p,t),sv.$.PrepareSamplers(_,t)),so.G.PrepareUniformsAndSamplersList({uniformsNames:p,uniformBuffersNames:f,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});let g={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,p,f,_,t,c,g));let v=t.toString(),x=l.createEffect(d,{attributes:c,uniformsNames:p,uniformBuffersNames:f,samplers:_,defines:v,fallbacks:h,onCompiled:i,onError:r,indexParameters:m,processFinalCode:g.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},l);return this._eventInfo.customCode=void 0,x}_prepareDefines(e,t,i=null,r=null,s=!1){var n;let a=this.getScene(),o=a.getEngine();so.G.PrepareDefinesForLights(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,so.G.PrepareDefinesForMultiview(a,t);let l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(so.G.PrepareDefinesForPrePass(a,t,this.canRenderToMRT&&!l),so.G.PrepareDefinesForOIT(a,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(a.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&MaterialFlags.AmbientTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&MaterialFlags.OpacityTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;let e=this._getReflectionTexture();if(e&&MaterialFlags.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===texture_Texture.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 texture_Texture.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case texture_Texture.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case texture_Texture.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case texture_Texture.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case texture_Texture.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case texture_Texture.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.CUBIC_MODE:case texture_Texture.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==texture_Texture.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;if(this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled?(so.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&&MaterialFlags.EmissiveTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,MaterialFlags.SpecularTextureEnabled){if(this._metallicTexture?(so.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?(so.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){let e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(n=this._reflectanceTexture)||void 0===n?void 0:n._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(so.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)?(so.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?so.G.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap?(so.G.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=a.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&MaterialFlags.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===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(so.G.PrepareDefinesForMisc(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(rz.o.NormalKind),t.DEBUGMODE=this._debugMode),so.G.PrepareDefinesForFrameBoundValues(a,o,this,t,!!i,r,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),so.G.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){let r=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(sG.S.GetDefineNames,this._eventInfo);let s=new PBRMaterialDefines(this._eventInfo.defineNames),n=this._prepareEffect(e,s,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(oX.effect=n,oX.subMesh=null,this._onEffectCreatedObservable.notifyObservers(oX)),n.isReady()?t&&t(this):n.onCompileObservable.add(()=>{t&&t(this)})}buildUniformLayout(){let 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 r,s,n,a;let o=this.getScene(),l=i.materialDefines;if(!l)return;let h=i.effect;if(!h)return;this._activeEffect=h,t.getMeshUniformBuffer().bindToEffect(h,"Mesh"),t.transferToEffect(e);let u=o.getEngine();this._uniformBuffer.bindToEffect(h,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,o,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),l.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=h._forceRebindOnNextCall||this._mustRebind(o,h,t.visibility);so.G.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let d=null,p=this._uniformBuffer;if(c){if(this.bindViewProjection(h),d=this._getReflectionTexture(),!p.useUbo||!this.isFrozen||!p.isSync||h._forceRebindOnNextCall){if(o.texturesEnabled){if(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&(p.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),so.G.BindTextureMatrix(this._albedoTexture,p,"albedo")),this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&(p.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),so.G.BindTextureMatrix(this._ambientTexture,p,"ambient")),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&(p.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),so.G.BindTextureMatrix(this._opacityTexture,p,"opacity")),d&&MaterialFlags.ReflectionTextureEnabled){if(p.updateMatrix("reflectionMatrix",d.getReflectionTextureMatrix()),p.updateFloat2("vReflectionInfos",d.level,0),d.boundingBoxSize){let e=d;p.updateVector3("vReflectionPosition",e.boundingBoxPosition),p.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){let e=d.getSize().width;p.updateFloat2("vReflectionFilteringInfo",e,rE.R.Log2(e))}if(!l.USEIRRADIANCEMAP){let e=d.sphericalPolynomial;if(l.USESPHERICALFROMREFLECTIONMAP&&e){if(l.SPHERICAL_HARMONICS){let t=e.preScaledHarmonics;p.updateVector3("vSphericalL00",t.l00),p.updateVector3("vSphericalL1_1",t.l1_1),p.updateVector3("vSphericalL10",t.l10),p.updateVector3("vSphericalL11",t.l11),p.updateVector3("vSphericalL2_2",t.l2_2),p.updateVector3("vSphericalL2_1",t.l2_1),p.updateVector3("vSphericalL20",t.l20),p.updateVector3("vSphericalL21",t.l21),p.updateVector3("vSphericalL22",t.l22)}else p.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),p.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),p.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),p.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),p.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),p.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),p.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),p.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),p.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}}p.updateFloat3("vReflectionMicrosurfaceInfos",d.getSize().width,d.lodGenerationScale,d.lodGenerationOffset)}this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&(p.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),so.G.BindTextureMatrix(this._emissiveTexture,p,"emissive")),this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&(p.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),so.G.BindTextureMatrix(this._lightmapTexture,p,"lightmap")),MaterialFlags.SpecularTextureEnabled&&(this._metallicTexture?(p.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),so.G.BindTextureMatrix(this._metallicTexture,p,"reflectivity")):this._reflectivityTexture&&(p.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),so.G.BindTextureMatrix(this._reflectivityTexture,p,"reflectivity")),this._metallicReflectanceTexture&&(p.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),so.G.BindTextureMatrix(this._metallicReflectanceTexture,p,"metallicReflectance")),this._reflectanceTexture&&l.REFLECTANCE&&(p.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),so.G.BindTextureMatrix(this._reflectanceTexture,p,"reflectance")),this._microSurfaceTexture&&(p.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),so.G.BindTextureMatrix(this._microSurfaceTexture,p,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&(p.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),so.G.BindTextureMatrix(this._bumpTexture,p,"bump"),o._mirroredCameraPosition?p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&p.updateFloat("pointSize",this.pointSize),l.METALLICWORKFLOW){rg.zZ.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,rg.zZ.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,p.updateColor4("vReflectivityColor",rg.zZ.Color3[0],1);let e=null!==(s=null===(r=this.subSurface)||void 0===r?void 0:r._indexOfRefraction)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((e-1)/(e+1),2)*this._metallicF0Factor,rg.zZ.Color3[0]);let t=this._metallicF0Factor;p.updateColor4("vMetallicReflectanceFactors",rg.zZ.Color3[0],t)}else p.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);p.updateColor3("vEmissiveColor",MaterialFlags.EmissiveTextureEnabled?this._emissiveColor:rg.Wo.BlackReadOnly),p.updateColor3("vReflectionColor",this._reflectionColor),!l.SS_REFRACTION&&(null===(n=this.subSurface)||void 0===n?void 0:n._linkRefractionWithTransparency)?p.updateColor4("vAlbedoColor",this._albedoColor,1):p.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*o.environmentIntensity,this._lightingInfos.w=this._specularIntensity,p.updateVector4("vLightingIntensity",this._lightingInfos),o.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),p.updateColor3("vAmbientColor",this._globalAmbientColor),p.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}o.texturesEnabled&&(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&p.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&p.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&p.setTexture("opacitySampler",this._opacityTexture),d&&MaterialFlags.ReflectionTextureEnabled&&(l.LODBASEDMICROSFURACE?p.setTexture("reflectionSampler",d):(p.setTexture("reflectionSampler",d._lodTextureMid||d),p.setTexture("reflectionSamplerLow",d._lodTextureLow||d),p.setTexture("reflectionSamplerHigh",d._lodTextureHigh||d)),l.USEIRRADIANCEMAP&&p.setTexture("irradianceSampler",d.irradianceTexture)),l.ENVIRONMENTBRDF&&p.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&p.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&p.setTexture("lightmapSampler",this._lightmapTexture),MaterialFlags.SpecularTextureEnabled&&(this._metallicTexture?p.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&p.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&p.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&l.REFLECTANCE&&p.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&p.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&p.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(h),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,nX.an)(this._activeEffect,this,o),this.bindEyePosition(h)}else o.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(c||!this.isFrozen)&&(o.lightsEnabled&&!this._disableLighting&&so.G.BindLights(o,t,this._activeEffect,l,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==rN.x.FOGMODE_NONE||d||this.subSurface.refractionTexture||t.receiveShadows||l.PREPASS)&&this.bindView(h),so.G.BindFogParameters(o,t,this._activeEffect,!0),l.NUM_MORPH_INFLUENCERS&&so.G.BindMorphTargetParameters(t,this._activeEffect),l.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(a=t.bakedVertexAnimationManager)||void 0===a||a.bind(h,l.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),so.G.BindLogDepth(l,this._activeEffect,o)),this._afterBind(t,this._activeEffect),p.update()}getAnimatables(){let 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(){let 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;let t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,r,s,n,a,o,l,h,u,c,d,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(n=this._reflectionTexture)||void 0===n||n.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._metallicTexture)||void 0===o||o.dispose(),null===(l=this._reflectivityTexture)||void 0===l||l.dispose(),null===(h=this._bumpTexture)||void 0===h||h.dispose(),null===(u=this._lightmapTexture)||void 0===u||u.dispose(),null===(c=this._metallicReflectanceTexture)||void 0===c||c.dispose(),null===(d=this._reflectanceTexture)||void 0===d||d.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)}};pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE=sr.F.MATERIAL_OPAQUE,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST=sr.F.MATERIAL_ALPHATEST,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHABLEND=sr.F.MATERIAL_ALPHABLEND,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND=sr.F.MATERIAL_ALPHATESTANDBLEND,pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL=0,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF=1,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD=2,(0,rH.gn)([(0,rb.rX)()],pbrBaseMaterial_PBRBaseMaterial.prototype,"_imageProcessingConfiguration",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrBaseMaterial_PBRBaseMaterial.prototype,"debugMode",void 0),(0,rH.gn)([(0,rb.qC)()],pbrBaseMaterial_PBRBaseMaterial.prototype,"useLogarithmicDepth",null);let pbrMaterial_PBRMaterial=class pbrMaterial_PBRMaterial extends pbrBaseMaterial_PBRBaseMaterial{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===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF:this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.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=pbrMaterial_PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=rg.Wo.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new rg.Wo(0,0,0),this.albedoColor=new rg.Wo(1,1,1),this.reflectivityColor=new rg.Wo(1,1,1),this.reflectionColor=new rg.Wo(1,1,1),this.emissiveColor=new rg.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.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){let r=rb.p4.Clone(()=>new pbrMaterial_PBRMaterial(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){let r=rb.p4.Parse(()=>new pbrMaterial_PBRMaterial(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),sr.F._parsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};function FourCCToInt32(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function Int32ToFourCC(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}pbrMaterial_PBRMaterial.PBRMATERIAL_OPAQUE=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHATEST=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHABLEND=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHABLEND,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND,pbrMaterial_PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"directIntensity",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveIntensity",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"environmentIntensity",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"specularIntensity",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"disableBumpMap",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"albedoTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTextureStrength",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"opacityTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectionTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectivityTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallic",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"roughness",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicF0Factor",void 0),(0,rH.gn)([(0,rb.n9)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicReflectanceColor",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicReflectanceTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectanceTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"microSurfaceTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"bumpTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty",null)],pbrMaterial_PBRMaterial.prototype,"lightmapTexture",void 0),(0,rH.gn)([(0,rb.n9)("ambient"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientColor",void 0),(0,rH.gn)([(0,rb.n9)("albedo"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"albedoColor",void 0),(0,rH.gn)([(0,rb.n9)("reflectivity"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectivityColor",void 0),(0,rH.gn)([(0,rb.n9)("reflection"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectionColor",void 0),(0,rH.gn)([(0,rb.n9)("emissive"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveColor",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"microSurface",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useLightmapAsShadowmap",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"useAlphaFromAlbedoTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"forceAlphaTest",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"alphaCutOff",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useSpecularOverAlpha",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRoughnessFromMetallicTextureGreen",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useMetallnessFromMetallicTextureBlue",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAmbientInGrayScale",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),(0,rH.gn)([(0,rb.qC)()],pbrMaterial_PBRMaterial.prototype,"usePhysicalLightFalloff",null),(0,rH.gn)([(0,rb.qC)()],pbrMaterial_PBRMaterial.prototype,"useGLTFLightFalloff",null),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRadianceOverAlpha",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useObjectSpaceNormalMap",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useParallax",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useParallaxOcclusion",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"parallaxScaleBias",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],pbrMaterial_PBRMaterial.prototype,"disableLighting",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"forceIrradianceInFragment",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],pbrMaterial_PBRMaterial.prototype,"maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"invertNormalMapX",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"invertNormalMapY",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"twoSidedLighting",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAlphaFresnel",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useLinearAlphaFresnel",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"environmentBRDFTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"forceNormalForward",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"enableSpecularAntiAliasing",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useHorizonOcclusion",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRadianceOcclusion",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrMaterial_PBRMaterial.prototype,"unlit",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrMaterial_PBRMaterial.prototype,"applyDecalMapAfterDetailMap",void 0),(0,rv.H)("BABYLON.PBRMaterial",pbrMaterial_PBRMaterial);let oY=FourCCToInt32("DXT1"),oj=FourCCToInt32("DXT3"),oq=FourCCToInt32("DXT5"),oK=FourCCToInt32("DX10");let DDSTools=class DDSTools{static GetDDSInfo(e){let t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35),r=1;131072&t[2]&&(r=Math.max(1,t[7]));let s=t[21],n=s===oK?i[32]:0,a=0;switch(s){case 113:a=2;break;case 116:a=1;break;case oK:if(10===n){a=2;break}2===n&&(a=1)}return{width:t[4],height:t[3],mipmapCount:r,isFourCC:(4&t[20])==4,isRGB:(64&t[20])==64,isLuminance:(131072&t[20])==131072,isCube:(512&t[28])==512,isCompressed:s===oY||s===oj||s===oq,dxgiFormat:n,textureType:a}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,n){let a=new Float32Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;a[l]=FromHalfFloat(o[r]),a[l+1]=FromHalfFloat(o[r+1]),a[l+2]=FromHalfFloat(o[r+2]),DDSTools.StoreLODInAlphaChannel?a[l+3]=n:a[l+3]=FromHalfFloat(o[r+3]),l+=4}return a}static _GetHalfFloatRGBAArrayBuffer(e,t,i,r,s,n){if(DDSTools.StoreLODInAlphaChannel){let a=new Uint16Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;a[l]=o[r],a[l+1]=o[r+1],a[l+2]=o[r+2],a[l+3]=ToHalfFloat(n),l+=4}return a}return new Uint16Array(s,i,r)}static _GetFloatRGBAArrayBuffer(e,t,i,r,s,n){if(DDSTools.StoreLODInAlphaChannel){let a=new Float32Array(r),o=new Float32Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;a[l]=o[r],a[l+1]=o[r+1],a[l+2]=o[r+2],a[l+3]=n,l+=4}return a}return new Float32Array(s,i,r)}static _GetFloatAsHalfFloatRGBAArrayBuffer(e,t,i,r,s,n){let a=new Uint16Array(r),o=new Float32Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++)a[l]=ToHalfFloat(o[l]),a[l+1]=ToHalfFloat(o[l+1]),a[l+2]=ToHalfFloat(o[l+2]),DDSTools.StoreLODInAlphaChannel?a[l+3]=ToHalfFloat(n):a[l+3]=ToHalfFloat(o[l+3]),l+=4;return a}static _GetFloatAsUIntRGBAArrayBuffer(e,t,i,r,s,n){let a=new Uint8Array(r),o=new Float32Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;a[l]=255*rE.R.Clamp(o[r]),a[l+1]=255*rE.R.Clamp(o[r+1]),a[l+2]=255*rE.R.Clamp(o[r+2]),DDSTools.StoreLODInAlphaChannel?a[l+3]=n:a[l+3]=255*rE.R.Clamp(o[r+3]),l+=4}return a}static _GetHalfFloatAsUIntRGBAArrayBuffer(e,t,i,r,s,n){let a=new Uint8Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;a[l]=255*rE.R.Clamp(FromHalfFloat(o[r])),a[l+1]=255*rE.R.Clamp(FromHalfFloat(o[r+1])),a[l+2]=255*rE.R.Clamp(FromHalfFloat(o[r+2])),DDSTools.StoreLODInAlphaChannel?a[l+3]=n:a[l+3]=255*rE.R.Clamp(FromHalfFloat(o[r+3])),l+=4}return a}static _GetRGBAArrayBuffer(e,t,i,r,s,n,a,o,l){let h=new Uint8Array(r),u=new Uint8Array(s,i),c=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;h[c]=u[r+n],h[c+1]=u[r+a],h[c+2]=u[r+o],h[c+3]=u[r+l],c+=4}return h}static _ExtractLongWordOrder(e){return 0===e||255===e||-16777216===e?0:1+DDSTools._ExtractLongWordOrder(e>>8)}static _GetRGBArrayBuffer(e,t,i,r,s,n,a,o){let l=new Uint8Array(r),h=new Uint8Array(s,i),u=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*3;l[u]=h[r+n],l[u+1]=h[r+a],l[u+2]=h[r+o],u+=3}return l}static _GetLuminanceArrayBuffer(e,t,i,r,s){let n=new Uint8Array(r),a=new Uint8Array(s,i),o=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=t+i*e;n[o]=a[r],o++}return n}static UploadDDSLevels(e,t,i,r,s,n,a=-1,o,l=!0){let h,u,c,d=null;r.sphericalPolynomial&&(d=[]);let p=!!e.getCaps().s3tc;t.generateMipMaps=s;let _=new Int32Array(i.buffer,i.byteOffset,31),f,m,g,v=0,x,T=0,S=1;if(542327876!==_[0]){rT.Y.Error("Invalid magic number in DDS header");return}if(!r.isFourCC&&!r.isRGB&&!r.isLuminance){rT.Y.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");return}if(r.isCompressed&&!p){rT.Y.Error("Compressed textures are not supported on this platform.");return}let C=_[22];x=_[1]+4;let E=!1;if(r.isFourCC)switch(f=_[21]){case oY:S=8,T=33777;break;case oj:S=16,T=33778;break;case oq:S=16,T=33779;break;case 113:E=!0,C=64;break;case 116:E=!0,C=128;break;case oK:{x+=20;let e=!1;switch(r.dxgiFormat){case 10:E=!0,C=64,e=!0;break;case 2:E=!0,C=128,e=!0;break;case 88:r.isRGB=!0,r.isFourCC=!1,C=32,e=!0}if(e)break}default:console.error("Unsupported FourCC code:",Int32ToFourCC(f));return}let b=DDSTools._ExtractLongWordOrder(_[23]),y=DDSTools._ExtractLongWordOrder(_[24]),P=DDSTools._ExtractLongWordOrder(_[25]),R=DDSTools._ExtractLongWordOrder(_[26]);E&&(T=e._getRGBABufferInternalSizedFormat(r.textureType)),u=1,131072&_[2]&&!1!==s&&(u=Math.max(1,_[7]));let A=o||0,I=e.getCaps();for(let s=A;s<n;s++){for(c=0,m=_[4],g=_[3];c<u;++c){if(-1===a||a===c){let n=-1===a?c:0;if(!r.isCompressed&&r.isFourCC){t.format=5,v=m*g*4;let r=null;if(e._badOS||e._badDesktopOS||!I.textureHalfFloat&&!I.textureFloat)128===C?(r=DDSTools._GetFloatAsUIntRGBAArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,n),d&&0==n&&d.push(DDSTools._GetFloatRGBAArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,n))):64===C&&(r=DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,n),d&&0==n&&d.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,n))),t.type=0;else{let e;let s=I.textureFloat&&(l&&I.textureFloatLinearFiltering||!l),a=I.textureHalfFloat&&(l&&I.textureHalfFloatLinearFiltering||!l),o=(128===C||64===C&&!a)&&s?1:(64===C||128===C&&!s)&&a?2:0,h=null;if(128===C)switch(o){case 1:e=DDSTools._GetFloatRGBAArrayBuffer,h=null;break;case 2:e=DDSTools._GetFloatAsHalfFloatRGBAArrayBuffer,h=DDSTools._GetFloatRGBAArrayBuffer;break;case 0:e=DDSTools._GetFloatAsUIntRGBAArrayBuffer,h=DDSTools._GetFloatRGBAArrayBuffer}else switch(o){case 1:e=DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer,h=null;break;case 2:e=DDSTools._GetHalfFloatRGBAArrayBuffer,h=DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;break;case 0:e=DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer,h=DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer}t.type=o,r=e(m,g,i.byteOffset+x,v,i.buffer,n),d&&0==n&&d.push(h?h(m,g,i.byteOffset+x,v,i.buffer,n):r)}r&&e._uploadDataToTextureDirectly(t,r,s,n)}else if(r.isRGB)t.type=0,24===C?(t.format=4,v=m*g*3,h=DDSTools._GetRGBArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,b,y,P)):(t.format=5,v=m*g*4,h=DDSTools._GetRGBAArrayBuffer(m,g,i.byteOffset+x,v,i.buffer,b,y,P,R)),e._uploadDataToTextureDirectly(t,h,s,n);else if(r.isLuminance){let r=e._getUnpackAlignement(),a=m,o=Math.floor((m+r-1)/r)*r;v=o*(g-1)+a,h=DDSTools._GetLuminanceArrayBuffer(m,g,i.byteOffset+x,v,i.buffer),t.format=1,t.type=0,e._uploadDataToTextureDirectly(t,h,s,n)}else v=Math.max(4,m)/4*Math.max(4,g)/4*S,h=new Uint8Array(i.buffer,i.byteOffset+x,v),t.type=0,e._uploadCompressedDataToTextureDirectly(t,T,m,g,h,s,n)}x+=C?m*g*(C/8):v,m*=.5,g*=.5,m=Math.max(1,m),g=Math.max(1,g)}if(void 0!==o)break}d&&d.length>0?r.sphericalPolynomial=CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({size:_[4],right:d[0],left:d[1],up:d[2],down:d[3],front:d[4],back:d[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}};DDSTools.StoreLODInAlphaChannel=!1,r6.B.prototype.createPrefilteredCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!0){return this.createCubeTexture(e,t,null,!1,e=>{if(!e){s&&s(null);return}let n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new SphericalPolynomial,n._source=r5.S.CubePrefiltered,this.getCaps().textureLOD){s&&s(n);return}let a=this._gl,o=e.width;if(!o)return;let h=[];for(let s=0;s<3;s++){let l=s/2,u=1-l,c=rE.R.Log2(o)*i+r,d=r+(c-r)*u,p=Math.round(Math.min(Math.max(d,0),c)),_=new r5.l(this,r5.S.Temp);if(_.type=n.type,_.format=n.format,_.width=Math.pow(2,Math.max(rE.R.Log2(o)-p,0)),_.height=_.width,_.isCube=!0,_._cachedWrapU=0,_._cachedWrapV=0,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,_,!0),_.samplingMode=2,a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),e.isDDS){let t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),DDSTools.UploadDDSLevels(this,_,i,t,!0,6,p)}else rT.Y.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);let f=new baseTexture_BaseTexture(t);f._isCube=!0,f._texture=_,_.isReady=!0,h.push(f)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],s&&s(n)},n,a,o,l,i,r)};let _DDSTextureLoader=class _DDSTextureLoader{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,r){let s;let n=t.getEngine(),a=!1,o=1e3;if(Array.isArray(e))for(let i=0;i<e.length;i++){let r=e[i];s=DDSTools.GetDDSInfo(r),t.width=s.width,t.height=s.height,a=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,n._unpackFlipY(s.isCompressed),DDSTools.UploadDDSLevels(n,t,r,s,a,6,-1,i),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:n.generateMipMapsForCubemap(t)}else s=DDSTools.GetDDSInfo(e),t.width=s.width,t.height=s.height,i&&(s.sphericalPolynomial=new SphericalPolynomial),a=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,n._unpackFlipY(s.isCompressed),DDSTools.UploadDDSLevels(n,t,e,s,a,6),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:n.generateMipMapsForCubemap(t,!1);n._setCubeMapTextureParams(t,a,o),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:s,data:e,texture:t})}loadData(e,t,i){let r=DDSTools.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&r.width>>r.mipmapCount-1==1;i(r.width,r.height,s,r.isFourCC,()=>{DDSTools.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}};rq.D._TextureLoaders.push(new _DDSTextureLoader);let _ENVTextureLoader=class _ENVTextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let n=GetEnvInfo(e);if(n){t.width=n.width,t.height=n.width;try{UploadEnvSpherical(t,n),UploadEnvLevelsAsync(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},e=>{null==s||s("Can not upload environment levels",e)})}catch(e){null==s||s("Can not upload environment file",e)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}};rq.D._TextureLoaders.push(new _ENVTextureLoader);let KhronosTextureContainer=class KhronosTextureContainer{constructor(e,t){if(this.data=e,this.isInvalid=!1,!KhronosTextureContainer.IsValid(e)){this.isInvalid=!0,rT.Y.Error("texture missing KTX identifier");return}let i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=r.getUint32(0,!0),n=67305985===s;if(this.glType=r.getUint32(1*i,n),this.glTypeSize=r.getUint32(2*i,n),this.glFormat=r.getUint32(3*i,n),this.glInternalFormat=r.getUint32(4*i,n),this.glBaseInternalFormat=r.getUint32(5*i,n),this.pixelWidth=r.getUint32(6*i,n),this.pixelHeight=r.getUint32(7*i,n),this.pixelDepth=r.getUint32(8*i,n),this.numberOfArrayElements=r.getUint32(9*i,n),this.numberOfFaces=r.getUint32(10*i,n),this.numberOfMipmapLevels=r.getUint32(11*i,n),this.bytesOfKeyValueData=r.getUint32(12*i,n),0!==this.glType){rT.Y.Error("only compressed formats currently supported"),this.isInvalid=!0;return}if(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth){rT.Y.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(0!==this.numberOfArrayElements){rT.Y.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){rT.Y.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=KhronosTextureContainer.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case KhronosTextureContainer.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case KhronosTextureContainer.TEX_2D:case KhronosTextureContainer.COMPRESSED_3D:case KhronosTextureContainer.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=KhronosTextureContainer.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight,n=t?this.numberOfMipmapLevels:1;for(let t=0;t<n;t++){let n=new Int32Array(this.data.buffer,this.data.byteOffset+i,1)[0];i+=4;for(let a=0;a<this.numberOfFaces;a++){let o=new Uint8Array(this.data.buffer,this.data.byteOffset+i,n),l=e.getEngine();l._uploadCompressedDataToTextureDirectly(e,e.format,r,s,o,a,t),i+=n+(3-(n+3)%4)}r=Math.max(1,.5*r),s=Math.max(1,.5*s)}}static IsValid(e){if(e.byteLength>=12){let 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}};KhronosTextureContainer.HEADER_LEN=64,KhronosTextureContainer.COMPRESSED_2D=0,KhronosTextureContainer.COMPRESSED_3D=1,KhronosTextureContainer.TEX_2D=2,KhronosTextureContainer.TEX_3D=3;let WorkerPool=class WorkerPool{constructor(e){this._pendingActions=[],this._workerInfos=e.map(e=>({workerPromise:Promise.resolve(e),idle:!0}))}dispose(){for(let 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(let 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,()=>{let t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0})})}};let AutoReleaseWorkerPool=class AutoReleaseWorkerPool extends WorkerPool{constructor(e,t,i=AutoReleaseWorkerPool.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e)){if(this._workerInfos.length<this._maxWorkers){let t={workerPromise:this._createWorkerAsync(),idle:!1};this._workerInfos.push(t),this._execute(t,e)}else this._pendingActions.push(e)}}_execute(e,t){e.timeoutId&&(clearTimeout(e.timeoutId),delete e.timeoutId),super._execute(e,(i,r)=>{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(e=>{e.terminate()});let t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)},this._options.idleTimeElapsedBeforeRelease))})})}};function applyConfig(e){e.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}AutoReleaseWorkerPool.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},(eb=ib||(ib={}))[eb.ETC1S=0]="ETC1S",eb[eb.UASTC4x4=1]="UASTC4x4",(ey=iy||(iy={}))[ey.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",ey[ey.BC7_RGBA=1]="BC7_RGBA",ey[ey.BC3_RGBA=2]="BC3_RGBA",ey[ey.BC1_RGB=3]="BC1_RGB",ey[ey.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",ey[ey.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",ey[ey.ETC2_RGBA=6]="ETC2_RGBA",ey[ey.ETC1_RGB=7]="ETC1_RGB",ey[ey.RGBA32=8]="RGBA32",ey[ey.R8=9]="R8",ey[ey.RG8=10]="RG8",(eP=iP||(iP={}))[eP.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",eP[eP.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",eP[eP.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",eP[eP.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",eP[eP.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",eP[eP.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",eP[eP.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",eP[eP.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",eP[eP.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",eP[eP.RGBA8Format=32856]="RGBA8Format",eP[eP.R8Format=33321]="R8Format",eP[eP.RG8Format=33323]="RG8Format";let DefaultKTX2DecoderOptions=class DefaultKTX2DecoderOptions{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;let e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[iy.BC1_RGB,iy.BC3_RGBA],yes:{transcodeFormat:iy.RGBA32,engineFormat:iP.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}};let KhronosTextureContainer2=class KhronosTextureContainer2{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(KhronosTextureContainer2._WorkerPoolPromise||KhronosTextureContainer2._DecoderModulePromise)return;let t={jsDecoderModule:rW.w1.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:rW.w1.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?KhronosTextureContainer2._WorkerPoolPromise=new Promise(i=>{let r=`${applyConfig}(${workerFunc})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new AutoReleaseWorkerPool(e,()=>new Promise((e,i)=>{let r=new Worker(s),onError=e=>{r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),i(e)},onMessage=t=>{"init"===t.data.action&&(r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),e(r))};r.addEventListener("error",onError),r.addEventListener("message",onMessage),r.postMessage({action:"init",urls:t})})))}):"undefined"==typeof KTX2DECODER?KhronosTextureContainer2._DecoderModulePromise=rW.w1.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,applyConfig(t),new KTX2DECODER.KTX2Decoder)):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,KhronosTextureContainer2._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=KhronosTextureContainer2.DefaultNumWorkers){this._engine=e,KhronosTextureContainer2._Initialize(t)}uploadAsync(e,t,i){let r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(KhronosTextureContainer2._WorkerPoolPromise)return KhronosTextureContainer2._WorkerPoolPromise.then(r=>new Promise((n,a)=>{r.push((r,o)=>{let onError=e=>{r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),a(e),o()},onMessage=e=>{if("decoded"===e.data.action){if(r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){a({message:e})}else a({message:e.data.msg});o()}};r.addEventListener("error",onError),r.addEventListener("message",onMessage),r.postMessage({action:"setDefaultDecoderOptions",options:KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions()});let l=new Uint8Array(e.byteLength);l.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),r.postMessage({action:"decode",data:l,caps:s,options:i},[l.buffer])})}));if(KhronosTextureContainer2._DecoderModulePromise)return KhronosTextureContainer2._DecoderModulePromise.then(i=>(KhronosTextureContainer2.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((s,n)=>{i.decode(e,r).then(e=>{this._createTexture(e,t),s()}).catch(e=>{n({message:e})})})));throw Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let r=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,r=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i<e.mipmaps.length;++i){let s=e.mipmaps[i];if(!s||!s.data)throw Error("KTX2 container - could not transcode one of the image");r?(t.width=s.width,t.height=s.height,this._engine._uploadDataToTextureDirectly(t,s.data,0,i,void 0,!0)):this._engine._uploadCompressedDataToTextureDirectly(t,e.transcodedFormat,s.width,s.height,s.data,0,i)}t._extension=".ktx2",t.width=e.mipmaps[0].width,t.height=e.mipmaps[0].height,t.isReady=!0,this._engine._bindTextureDirectly(3553,null)}static IsValid(e){if(e.byteLength>=12){let 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 workerFunc(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{let i=t.data.urls;importScripts(i.jsDecoderModule),applyConfig(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=>{let t=[];for(let i=0;i<e.mipmaps.length;++i){let r=e.mipmaps[i];r&&r.data&&t.push(r.data.buffer)}postMessage({action:"decoded",success:!0,decodedData:e},t)}).catch(e=>{postMessage({action:"decoded",success:!1,msg:e})})}}}function mapSRGBToLinear(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}KhronosTextureContainer2.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},KhronosTextureContainer2.DefaultNumWorkers=KhronosTextureContainer2.GetDefaultNumWorkers(),KhronosTextureContainer2.DefaultDecoderOptions=new DefaultKTX2DecoderOptions;let _KTXTextureLoader=class _KTXTextureLoader{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;let s=t.getEngine(),n=new KhronosTextureContainer(e,6),a=n.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,s._setCubeMapTextureParams(t,a,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(KhronosTextureContainer.IsValid(e)){t._invertVScale=!t.invertY;let r=new KhronosTextureContainer(e,1),s=mapSRGBToLinear(r.glInternalFormat);s?(t.format=s,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=r.glInternalFormat,i(r.pixelWidth,r.pixelHeight,t.generateMipMaps,!0,()=>{r.uploadLevels(t,t.generateMipMaps)},r.isInvalid)}else if(KhronosTextureContainer2.IsValid(e)){let s=new KhronosTextureContainer2(t.getEngine());s.uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},e=>{rT.Y.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,()=>{},!0)})}else rT.Y.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0)}};rq.D._TextureLoaders.unshift(new _KTXTextureLoader);let WebXRCamera=class WebXRCamera extends FreeCamera{constructor(e,t,i){super(e,rm.P.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=rm._f.Identity(),this._referencedPosition=new rm.P,this._trackingState=tU.NOT_TRACKING,this.onXRCameraInitializedObservable=new rf.y$,this.onBeforeCameraTeleport=new rf.y$,this.onAfterCameraTeleport=new rf.y$,this.onTrackingStateChanged=new rf.y$,this.compensateOnFirstFrame=!0,this._rotate180=new rm._f(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new rm._f,this.cameraRigMode=rj.V.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add(()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame}),this._xrSessionManager.onXRFrameObservable.add(()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()},void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){let 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 sh.l(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new sh.l(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){if(!e||e===this)return;let i=e.computeWorldMatrix();i.decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,rm._f.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){let t=rm.jp.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();let i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),rm._f.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(tU.NOT_TRACKING);return}let t=e.emulatedPosition?tU.TRACKING_LOST:tU.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){let 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){let t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;let 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;let r=this.rigCameras[t];r.isLeftCamera||r.isRightCamera||("right"===e.eye?r._isRightCamera=!0:"left"!==e.eye||(r._isLeftCamera=!0));let s=e.transform.position,n=e.transform.orientation;r.parent=this.parent,r.position.set(s.x,s.y,s.z),r.rotationQuaternion.set(n.x,n.y,n.z,n.w),this._scene.useRightHandedSystem?r.rotationQuaternion.multiplyInPlace(this._rotate180):(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1),rm.y3.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,r._projectionMatrix),this._scene.useRightHandedSystem||r._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(r._projectionMatrix);let 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(r.viewport,e),r.outputRenderTarget=a||this._xrSessionManager.getRenderTargetTextureForView(e)),r.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.length<e;){let e=new targetCamera_TargetCamera("XR-RigCamera: "+this.rigCameras.length,rm.P.Zero(),this.getScene());e.minZ=.1,e.rotationQuaternion=new rm._f,e.updateUpVectorFromRotation=!0,e.isRigCamera=!0,e.rigParent=this,e.freezeProjectionMatrix(),this.rigCameras.push(e)}for(;this.rigCameras.length>e;){let e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){let e=rm.jp.Matrix[0],t=rm.jp.Matrix[1],i=rm.jp.Matrix[2];rm.y3.ComposeToRef(WebXRCamera._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),rm.y3.ComposeToRef(WebXRCamera._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);let r=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(r)}}};WebXRCamera._ScaleReadOnly=rm.P.One();let WebXRExperienceHelper=class WebXRExperienceHelper{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 rf.y$,this.onStateChangedObservable=new rf.y$,this.state=tw.NOT_IN_XR,this.sessionManager=new WebXRSessionManager(e),this.camera=new WebXRCamera("webxr",e,this.sessionManager),this.featuresManager=new WebXRFeaturesManager(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){let t=new WebXRExperienceHelper(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(e=>{throw t._setState(tw.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(),r={}){var s,n,a;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(tw.ENTERING_XR),"viewer"!==t&&"local"!==t&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),"immersive-ar"===e&&"unbounded"!==t&&rT.Y.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);let o=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(webXRFeaturesManager_WebXRFeatureName.LAYERS)||(l.baseLayer=o),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(n=null===(s=this._nonVRCamera)||void 0===s?void 0:s.inputs)||void 0===n?void 0:n.attachedToElement),null===(a=this._nonVRCamera)||void 0===a||a.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!==tw.EXITING_XR&&this._setState(tw.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(tw.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(tw.IN_XR)}),this.sessionManager}catch(e){throw console.log(e),console.log(e.message),this._setState(tw.NOT_IN_XR),e}}exitXRAsync(){return this.state!==tw.IN_XR?Promise.resolve():(this._setState(tw.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){let t=(null==e?void 0:e.fps)?e.fps:1e3,i=1/t*1e3,r=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,updateSpectatorCamera=()=>{if(this._spectatorCamera){let e=this.sessionManager.currentTimestamp-this._lastTimestamp;e>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[r].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[r].absoluteRotation))}};if(this._spectatorMode){if(r>=this.camera.rigCameras.length)throw Error("the preferred camera index is beyond the length of rig camera array.");let onStateChanged=()=>{this.state===tw.IN_XR?(this._spectatorCamera=new universalCamera_UniversalCamera("webxr-spectator",rm.P.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new rm._f,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(updateSpectatorCamera),this._scene.onAfterRenderCameraObservable.add(e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===tw.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera),this._scene.activeCameras=null)};this.onStateChangedObservable.add(onStateChanged),onStateChanged()}else this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera),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))}};let WebXRControllerComponent=class WebXRControllerComponent{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new rf.y$,this.onButtonStateChangedObservable=new rf.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()){let 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))}};WebXRControllerComponent.BUTTON_TYPE="button",WebXRControllerComponent.SQUEEZE_TYPE="squeeze",WebXRControllerComponent.THUMBSTICK_TYPE="thumbstick",WebXRControllerComponent.TOUCHPAD_TYPE="touchpad",WebXRControllerComponent.TRIGGER_TYPE="trigger";let WebXRAbstractMotionController=class WebXRAbstractMotionController{constructor(e,t,i,r,s=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=n,this._initComponent=e=>{if(!e)return;let t=this.layout.components[e],i=t.type,r=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new WebXRControllerComponent(e,i,r,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new rf.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(){let e=!this._getModelLoadingConstraints(),t=this._getGenericFilenameAndPath();return e?rT.Y.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,r)=>{let meshesLoaded=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){let e=this._controllerCache.filter(e=>e.filename===t.filename&&e.path===t.path);if(e[0]){e[0].meshes.forEach(e=>e.setEnabled(!0)),meshesLoaded(e[0].meshes);return}}sceneLoader_SceneLoader.ImportMesh("",t.path,t.filename,this.scene,e=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:e})),meshesLoaded(e)},null,(e,i)=>{rT.Y.Log(i),rT.Y.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(i)})})}updateFromXRFrame(e){this.getComponentIds().forEach(e=>this.getComponent(e).update(this.gamepadObject)),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren(e=>e.name===t,!1)[0]}_getImmediateChildByName(e,t){return e.getChildren(e=>e.name==t,!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh||!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;let r=i?.5*t+.5:t;rm._f.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),rm.P.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new rV.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=rm._f.FromEulerAngles(0,Math.PI,0)}};let WebXRGenericTriggerMotionController=class WebXRGenericTriggerMotionController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,o$[i],t,i),this.profileId=WebXRGenericTriggerMotionController.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new rV.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=rm._f.FromEulerAngles(0,Math.PI,0)}_updateModel(){}};WebXRGenericTriggerMotionController.ProfileId="generic-trigger";let o$={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"}};let WebXRProfiledMotionController=class WebXRProfiledMotionController extends WebXRAbstractMotionController{constructor(e,t,i,r,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=r,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach(e=>{this._touchDots[e].dispose()})}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){let e=sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb");return e||rT.Y.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach(i=>{let r=t.visualResponses[i];if("transform"===r.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{let s=t.type===WebXRControllerComponent.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===WebXRControllerComponent.TOUCHPAD_TYPE&&!this._touchDots[i]){let t=sphereBuilder_CreateSphere(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new standardMaterial_StandardMaterial(i+"mat",this.scene),t.material.diffuseColor=rg.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 rV.Kj(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i<e.length;i++){let r=e[i];r.isPickable=!1,r.parent||(t=r)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||this.rootMesh.rotate(rL.RD.Y,Math.PI,rL.T.WORLD)}_updateModel(e){this.disableAnimation||this.getComponentIds().forEach(e=>{let t=this.getComponent(e);if(!t.hasChanges)return;let i=this._buttonMeshMapping[e],r=this.layout.components[e];Object.keys(r.visualResponses).forEach(e=>{let s=r.visualResponses[e],n=t.value;if("xAxis"===s.componentProperty?n=t.axes.x:"yAxis"===s.componentProperty&&(n=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==s.componentProperty);else{let r=i.states[e].valueMesh;r&&(r.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}})})}};let oQ=[];let WebXRMotionControllerManager=class WebXRMotionControllerManager{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){let t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){let r=[];i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&r.push("oculus-touch-v2");let s=r.indexOf("windows-mixed-reality");if(-1!==s&&r.splice(s,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),!this.UseOnlineRepository)return this._LoadProfilesFromAvailableControllers(r,e,t);{let i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,r,e,t).catch(()=>s.call(this,r,e,t))}}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=rW.w1.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e.toString())),this._ProfilesList}static ClearControllerCache(){oQ.forEach(e=>{e.meshes.forEach(e=>{e.dispose(!1,!0)})}),oQ.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(t=>{for(let i=0;i<e.length;++i)if(e[i]&&t[e[i]])return e[i];throw Error(`neither controller ${e[0]} nor all fallbacks were found in the repository,`)}).then(e=>(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=rW.w1.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then(e=>JSON.parse(e))),this._ProfileLoadingPromises[e])).then(e=>new WebXRProfiledMotionController(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:oQ))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;r<e.length;++r){if(!e[r])continue;let s=this.FindFallbackWithProfileId(e[r]);for(let e=0;e<s.length;++e){let r=this._AvailableControllers[s[e]];if(r)return Promise.resolve(r(t,i))}}throw Error("no controller requested was found in the available controllers list")}};WebXRMotionControllerManager._AvailableControllers={},WebXRMotionControllerManager._Fallbacks={},WebXRMotionControllerManager._ProfileLoadingPromises={},WebXRMotionControllerManager.BaseRepositoryUrl="https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist",WebXRMotionControllerManager.PrioritizeOnlineRepository=!0,WebXRMotionControllerManager.UseOnlineRepository=!0,WebXRMotionControllerManager.DisableControllerCache=!0,WebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId,(e,t)=>new WebXRGenericTriggerMotionController(t,e.gamepad,e.handedness)),WebXRMotionControllerManager.DefaultFallbacks();let oZ=0;let WebXRInputSource=class WebXRInputSource{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new rm.P,this._disposed=!1,this.onDisposeObservable=new rf.y$,this.onMeshLoadedObservable=new rf.y$,this.onMotionControllerInitObservable=new rf.y$,this._uniqueId=`controller-${oZ++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new rG.x(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new rm._f,this.inputSource.gripSpace&&(this.grip=new rG.x(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new rm._f),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&WebXRMotionControllerManager.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())})},()=>{rW.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){let i=t&&this.grip?this.grip:this.pointer;rm.P.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){let r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){let e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z);let t=r.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){let r=e.getPose(this.inputSource.gripSpace,t);if(r){let e=r.transform.position,t=r.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)}};let WebXRInput=class WebXRInput{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new rf.y$,this.onControllerRemovedObservable=new rf.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&&(WebXRMotionControllerManager.BaseRepositoryUrl=this._options.customControllersRepositoryURL),WebXRMotionControllerManager.UseOnlineRepository=!this._options.disableOnlineControllerRepository,WebXRMotionControllerManager.UseOnlineRepository)try{WebXRMotionControllerManager.UpdateProfilesList().catch(()=>{WebXRMotionControllerManager.UseOnlineRepository=!1})}catch(e){WebXRMotionControllerManager.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){let i=this.controllers.map(e=>e.inputSource);for(let t of e)if(-1===i.indexOf(t)){let e=new WebXRInputSource(this.xrSessionManager.scene,t,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)}let r=[],s=[];this.controllers.forEach(e=>{-1===t.indexOf(e.inputSource)?r.push(e):s.push(e)}),this.controllers=r,s.forEach(e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()})}dispose(){this.controllers.forEach(e=>{e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),WebXRMotionControllerManager.ClearControllerCache()}};let WebXRControllerPointerSelection=class WebXRControllerPointerSelection extends WebXRAbstractFeature{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;let{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 ray_Ray(new rm.P,new rm.P),disabledByNearInteraction:!1,id:WebXRControllerPointerSelection._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 rm.P,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new rg.Wo(.9,.9,.9),this.laserPointerDefaultColor=new rg.Wo(.7,.7,.7),this.selectionMeshDefaultColor=new rg.Wo(.8,.8,.8),this.selectionMeshPickedColor=new rg.Wo(.3,.3,1),this._identityMatrix=rm.y3.Identity(),this._screenCoordinatesRef=rm.P.Zero(),this._viewportRef=new sh.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){let 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 ray_Ray(new rm.P,new rm.P),disabledByNearInteraction:!1,id:WebXRControllerPointerSelection._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){let t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null}_getPointerSelectionDisabledByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].disabledByNearInteraction;return!0}_setPointerSelectionDisabledByPointerId(e,t){let i=Object.keys(this._controllers);for(let r=0;r<i.length;++r)if(this._controllers[i[r]].id===e){this._controllers[i[r]].disabledByNearInteraction=t;return}}_onXRFrame(e){Object.keys(this._controllers).forEach(e=>{let t;let i=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||i.disabledByNearInteraction){i.selectionMesh.isVisible=!1,i.laserPointer.isVisible=!1,i.pick=null;return}if(i.laserPointer.isVisible=this.displayLaserPointer,i.xrController)t=i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay);else{if(!i.webXRCamera)return;t=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay)}if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&t){let e=this._xrSessionManager.scene,r=this._options.xrInput.xrCamera;!r||(r.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),rm.P.ProjectToRef(t,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,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));let s=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);r&&r.hit?s&&s.hit?r.distance<s.distance?i.pick=r:i.pick=s:i.pick=r:i.pick=s,i.pick&&i.xrController&&(i.pick.aimTransform=i.xrController.pointer,i.pick.gripTransform=i.xrController.grip||null);let n=i.pick;if(n&&n.pickedPoint&&n.hit){this._updatePointerDistance(i.laserPointer,n.distance),i.selectionMesh.position.copyFrom(n.pickedPoint),i.selectionMesh.scaling.x=Math.sqrt(n.distance),i.selectionMesh.scaling.y=Math.sqrt(n.distance),i.selectionMesh.scaling.z=Math.sqrt(n.distance);let e=this._convertNormalToDirectionOfRay(n.getNormal(!0),i.tmpRay);if(i.selectionMesh.position.copyFrom(n.pickedPoint),e){let t=rm.P.Cross(rL.RD.Y,e),r=rm.P.Cross(e,t);rm.P.RotationFromAxisToRef(r,e,t,i.selectionMesh.rotation),i.selectionMesh.position.addInPlace(e.scale(.001))}i.selectionMesh.isVisible=this.displaySelectionMesh,i.meshUnderPointer=n.pickedMesh}else i.selectionMesh.isVisible=!1,this._updatePointerDistance(i.laserPointer,1),i.meshUnderPointer=null})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene}_attachGazeMode(e){let t=this._controllers[e&&e.uniqueId||"camera"],i=this._options.timeToSelect||3e3,r=this._options.useUtilityLayer?this._utilityLayerScene:this._scene,s=new r7.p,n=CreateTorus("selection",{diameter:.0525,thickness:.015,tessellation:20},r);n.isVisible=!1,n.isPickable=!1,n.parent=t.selectionMesh;let a=0,o=!1,l={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit){if(this._pickingMoved(s,t.pick))o&&!this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),o=!1,a=0;else if(a>i/10&&(n.isVisible=!0),(a+=this._scene.getEngine().getDeltaTime())>=i)this._scene.simulatePointerDown(t.pick,l),o=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{let e=1-a/i;n.scaling.set(e,e,e)}}else o=!1,a=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}}),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&o&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()})}_attachScreenRayMode(e){let t=this._controllers[e.uniqueId],i=!1,r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),t.pick&&(!this._options.disablePointerUpOnTouchOut||!i)&&(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)})})}_attachTrackedPointerRayMode(e){let t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);let 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){let init=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(r=>{if(r.changes.pressed){let s=r.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?init(e.motionController):e.onMotionControllerInitObservable.add(init)}else{let selectStartListener=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)},selectEndListener=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:selectEndListener,selectstart:selectStartListener},this._xrSessionManager.session.addEventListener("selectstart",selectStartListener),this._xrSessionManager.session.addEventListener("selectend",selectEndListener)}}_convertNormalToDirectionOfRay(e,t){if(e){let i=Math.acos(rm.P.Dot(e,t.direction));i<Math.PI/2&&e.scaleInPlace(-1)}return e}_detachController(e){let t=this._controllers[e];if(t){if(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=>{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),!t.finalPointerUpTriggered&&t.pointerDownTriggered){let e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame(()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new r7.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){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){rW.w1.Warn("controller already detached.")}})}}_generateNewMeshPair(e){let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():cylinderBuilder_CreateCylinder("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;let r=new standardMaterial_StandardMaterial("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;let s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():CreateTorus("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;let n=new standardMaterial_StandardMaterial("targetMat",t);return n.specularColor=rg.Wo.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,s.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||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));let r=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance,s=this._tmpVectorForPickCompare.length();return s>r}_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}};WebXRControllerPointerSelection._IdCounter=200,WebXRControllerPointerSelection.Name=webXRFeaturesManager_WebXRFeatureName.POINTER_SELECTION,WebXRControllerPointerSelection.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name,(e,t)=>()=>new WebXRControllerPointerSelection(e,t),WebXRControllerPointerSelection.Version,!0);var oJ=i(1091);oJ.P.prototype._projectOnTrianglesToRef=function(e,t,i,r,s,n){let a=rm.jp.Vector3[0],o=rm.jp.Vector3[1],l=Infinity;for(let n=this.indexStart;n<this.indexStart+this.indexCount-(3-r);n+=r){let r=i[n],h=i[n+1],u=i[n+2];if(s&&4294967295===u){n+=2;continue}let c=t[r],d=t[h],p=t[u];if(!c||!d||!p)continue;let _=rm.P.ProjectOnTriangleToRef(e,c,d,p,o);_<l&&(a.copyFrom(o),l=_)}return n.copyFrom(a),l},oJ.P.prototype._projectOnUnIndexedTrianglesToRef=function(e,t,i,r){let s=rm.jp.Vector3[0],n=rm.jp.Vector3[1],a=Infinity;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=3){let r=t[i],o=t[i+1],l=t[i+2],h=rm.P.ProjectOnTriangleToRef(e,r,o,l,n);h<a&&(s.copyFrom(n),a=h)}return r.copyFrom(s),a},oJ.P.prototype.projectToRef=function(e,t,i,r){let s=this.getMaterial();if(!s)return -1;let n=3,a=!1;switch(s.fillMode){case 3:case 5:case 6:case 8:return -1;case 7:n=1,a=!0}return 4===s.fillMode?-1:!i.length&&this._mesh._unIndexed?this._projectOnUnIndexedTrianglesToRef(e,t,i,r):this._projectOnTrianglesToRef(e,t,i,n,a,r)},(eR=iR||(iR={}))[eR.DEHYDRATED=0]="DEHYDRATED",eR[eR.HOVER=1]="HOVER",eR[eR.TOUCH=2]="TOUCH",(eA=iA||(iA={}))[eA.DISABLED=0]="DISABLED",eA[eA.CENTERED_ON_CONTROLLER=1]="CENTERED_ON_CONTROLLER",eA[eA.CENTERED_IN_FRONT=2]="CENTERED_IN_FRONT";let WebXRNearInteraction=class WebXRNearInteraction extends WebXRAbstractFeature{constructor(e,t){super(e),this._options=t,this._tmpRay=new ray_Ray(new rm.P,new rm.P),this._attachController=e=>{if(this._controllers[e.uniqueId])return;let{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r,currentAnimationState:iR.DEHYDRATED,grabRay:new ray_Ray(new rm.P,new rm.P),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:WebXRNearInteraction._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 rg.Wo(.8,.8,.8),this.selectionMeshPickedColor=new rg.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=iA.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){let t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null}setFarInteractionFeature(e){this._farInteractionFeature=e}_nearPickPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearPickable}_nearGrabPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearGrabbable}_nearInteractionPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&(e.isNearPickable||e.isNearGrabbable)}_controllerAvailablePredicate(e,t){let i=e;for(;i;){if(i.reservedDataStore&&i.reservedDataStore.nearInteraction&&i.reservedDataStore.nearInteraction.excludedControllerId===t)return!1;i=i.parent}return!0}_handleTransitionAnimation(e,t){var i;if(e.currentAnimationState!==t&&this._options.nearInteractionControllerMode===iA.CENTERED_IN_FRONT&&(null===(i=e.xrController)||void 0===i||!i.inputSource.hand)){if(t>e.currentAnimationState)switch(e.currentAnimationState){case iR.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===iR.HOVER)break;case iR.HOVER:e.touchCollisionMeshFunction(!0),iR.TOUCH}else switch(e.currentAnimationState){case iR.TOUCH:if(e.touchCollisionMeshFunction(!1),t===iR.HOVER)break;case iR.HOVER:e.hydrateCollisionMeshFunction(!1),iR.DEHYDRATED}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var r;let s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(rm.jp.Vector3[0]),s.grabRay.direction.copyFrom(rm.jp.Vector3[0]),this._options.nearInteractionControllerMode!==iA.CENTERED_IN_FRONT||(null===(r=s.xrController)||void 0===r?void 0:r.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;let r=this._controllers[t],s=null===(i=r.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!r.xrController||!s&&(!this._options.nearInteractionControllerMode||!r.xrController.inputSource.gamepad)){r.pick=null;return}if(r.hoverInteraction=!1,r.nearInteraction=!1,!r.xrController)return;if(s){let i=s.get("index-finger-tip");if(i){let r=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(r&&r.transform){let e=this._scene.useRightHandedSystem?1:-1;rm.jp.Vector3[0].set(r.transform.position.x,r.transform.position.y,r.transform.position.z*e),rm.jp.Quaternion[0].set(r.transform.orientation.x,r.transform.orientation.y,r.transform.orientation.z*e,r.transform.orientation.w*e),this._processTouchPoint(t,rm.jp.Vector3[0],rm.jp.Quaternion[0])}}}else if(r.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==iA.DISABLED){let e=r.xrController.pointer;r.xrController.grip&&this._options.nearInteractionControllerMode===iA.CENTERED_ON_CONTROLLER&&(e=r.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}let accuratePickInfo=(e,t)=>t&&t.hit?e&&e.hit?t.distance<e.distance?t:e:t:e,populateNearInteractionInfo=e=>{let t=new r7.p,i=!1,r=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),r&&!i&&(t=e),t};if(!r.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,this._hoverRadius,this._utilityLayerScene,e=>this._nearInteractionPredicate(e)));let i=this._pickWithSphere(r,this._hoverRadius,this._scene,e=>this._nearInteractionPredicate(e)),n=accuratePickInfo(i,t);if(n&&n.hit&&(e=populateNearInteractionInfo(n)).hit&&(r.hoverInteraction=!0),r.hoverInteraction){let t=null,i=s?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,i,this._utilityLayerScene,e=>this._nearPickPredicate(e)));let n=this._pickWithSphere(r,i,this._scene,e=>this._nearPickPredicate(e)),a=accuratePickInfo(n,t),o=populateNearInteractionInfo(a);o.hit&&(e=o,r.nearInteraction=!0)}r.stalePick=r.pick,r.pick=e,r.pick&&r.pick.pickedPoint&&r.pick.hit?(r.meshUnderPointer=r.pick.pickedMesh,r.pickedPointVisualCue.position.copyFrom(r.pick.pickedPoint),r.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!0)):(r.meshUnderPointer=null,r.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!1))}let n=iR.DEHYDRATED;r.grabInteraction||r.nearInteraction?n=iR.TOUCH:r.hoverInteraction&&(n=iR.HOVER),this._handleTransitionAnimation(r,n)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,t=sphereBuilder_CreateSphere("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=rm._f.Identity();let i=new standardMaterial_StandardMaterial("targetMat",e);return i.specularColor=rg.Wo.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){let 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))});let grabCheck=r=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),r&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!r||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){let init=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(e=>{if(e.changes.pressed){let t=e.changes.pressed.current;grabCheck(t)}}):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(e=>{if(e.changes.pressed){let t=e.changes.pressed.current;grabCheck(t)}}))};e.motionController?init(e.motionController):e.onMotionControllerInitObservable.add(init)}else{let selectStartListener=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))},selectEndListener=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:selectEndListener,selectstart:selectStartListener},this._xrSessionManager.session.addEventListener("selectstart",selectStartListener),this._xrSessionManager.session.addEventListener("selectend",selectEndListener)}}_detachController(e){let 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=>{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{let e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new r7.p,e)}),delete this._controllers[e],this._attachedController===e)){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,t=sphereBuilder_CreateSphere("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:NodeMaterial.ParseFromSnippetAsync("8RUNKL#3",e).then(e=>{t.material=e});let i=new QuadraticEase;i.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);let r=new rm.P(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),s=this._controllerPickRadius*(4/3),n=new rm.P(s,s,s),a=this._controllerPickRadius*(7/6),o=new rm.P(a,a,a),l=.8*this._controllerPickRadius,h=new rm.P(l,l,l),u=1.5*this._controllerPickRadius,c=new rm.P(u,u,u),d=[{frame:0,value:r},{frame:10,value:c},{frame:18,value:n}],p=[{frame:0,value:n},{frame:10,value:h},{frame:18,value:r}],_=[{frame:0,value:rm.P.ZeroReadOnly},{frame:12,value:o},{frame:15,value:r}],f=[{frame:0,value:r},{frame:10,value:rm.P.ZeroReadOnly},{frame:15,value:rm.P.ZeroReadOnly}],m=new animation_Animation("touch","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),g=new animation_Animation("release","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),v=new animation_Animation("hydrate","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),x=new animation_Animation("dehydrate","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),x.setEasingFunction(i),m.setKeys(d),g.setKeys(p),v.setKeys(_),x.setKeys(f),{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{let r=i?m:g;e.beginDirectAnimation(t,[r],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{let r=i?v:x;i&&(t.isVisible=!0),e.beginDirectAnimation(t,[r],0,15,!1,1,()=>{i||(t.isVisible=!1)})}}}_pickWithSphere(e,t,i,r){let s=new r7.p;if(s.distance=Infinity,e.touchCollisionMesh&&e.xrController){let n=e.touchCollisionMesh.position,a=nZ.K.CreateFromCenterAndRadius(n,t);for(let t=0;t<i.meshes.length;t++){let n=i.meshes[t];if(!r(n)||!this._controllerAvailablePredicate(n,e.xrController.uniqueId))continue;let o=WebXRNearInteraction.PickMeshWithSphere(n,a);o&&o.hit&&o.distance<s.distance&&(s.hit=o.hit,s.pickedMesh=n,s.pickedPoint=o.pickedPoint,s.aimTransform=e.xrController.pointer,s.gripTransform=e.xrController.grip||null,s.originMesh=e.touchCollisionMesh,s.distance=o.distance)}}return s}static PickMeshWithSphere(e,t,i=!1){let r,s,n;let a=e.subMeshes,o=new r7.p,l=e.getBoundingInfo();if(!e._generatePointsArray()||!e.subMeshes||!l||!i&&!nZ.K.Intersects(l.boundingSphere,t))return o;let h=rm.jp.Vector3[0],u=rm.jp.Vector3[1],c=Infinity,d=rm.jp.Vector3[2],p=rm.jp.Matrix[0];p.copyFrom(e.getWorldMatrix()),p.invert(),rm.P.TransformCoordinatesToRef(t.center,p,d);for(let i=0;i<a.length;i++){let o=a[i];o.projectToRef(d,e._positions,e.getIndices(),u),rm.P.TransformCoordinatesToRef(u,e.getWorldMatrix(),u),r=rm.P.Distance(u,t.center),n=rm.P.Distance(u,e.getAbsolutePosition()),-1!==(s=rm.P.Distance(t.center,e.getAbsolutePosition()))&&-1!==n&&n>s&&(r=0,u.copyFrom(t.center)),-1!==r&&r<c&&(c=r,h.copyFrom(u))}return c<t.radius&&(o.hit=!0,o.distance=c,o.pickedMesh=e,o.pickedPoint=h.clone()),o}};WebXRNearInteraction._IdCounter=200,WebXRNearInteraction.Name=webXRFeaturesManager_WebXRFeatureName.NEAR_INTERACTION,WebXRNearInteraction.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRNearInteraction.Name,(e,t)=>()=>new WebXRNearInteraction(e,t),WebXRNearInteraction.Version,!0);let WebXREnterExitUIButton=class WebXREnterExitUIButton{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}};let WebXREnterExitUI=class WebXREnterExitUI{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new rf.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 rW.w1.Warn("WebXR can only be served over HTTPS"),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;";let e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor",r="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",s=".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("+r+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';let n=document.createElement("style");n.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(n);let a=document.createElement("button");a.className="babylonVRicon",a.title=`${e} - ${i}`,this._buttons.push(new WebXREnterExitUIButton(a,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",a.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}let 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;let i=this._buttons.map(t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode));e.onStateChangedObservable.add(e=>{e==tw.NOT_IN_XR&&this._updateButtons(null)});let r=await Promise.all(i);r.forEach((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):rW.w1.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){let r=new WebXREnterExitUI(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(this._helper.state==tw.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==tw.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(r){this._updateButtons(null);let t=this._buttons[e].element,i=t.title;t.title="Error entering XR session : "+i,t.classList.add("xr-error"),this.options.onError&&this.options.onError(r)}}dispose(){let 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 setAndStartTimer(e){var t;let i=0,r=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};let s=e.contextObservable.add(t=>{let n=Date.now();i=n-r;let a={startTime:r,currentTime:n,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(a),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(a)),i>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(a))},e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}(eI=iI||(iI={}))[eI.INIT=0]="INIT",eI[eI.STARTED=1]="STARTED",eI[eI.ENDED=2]="ENDED";let AdvancedTimer=class AdvancedTimer{constructor(e){var t,i;this.onEachCountObservable=new rf.y$,this.onTimerAbortedObservable=new rf.y$,this.onTimerEndedObservable=new rf.y$,this.onStateChangedObservable=new rf.y$,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{let t=Date.now();this._timer=t-this._startTime;let i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},r=this._breakOnNextTick||this._breakCondition(i);r||this._timer>=this._timeToEnd?this._stop(i,r):this.onEachCountObservable.notifyObservers(i)},this._setState(iI.INIT),this._contextObservable=e.contextObservable,this._observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{},this._breakCondition=null!==(i=e.breakCondition)&&void 0!==i?i:()=>!1,this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===iI.STARTED)throw Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(iI.STARTED)}stop(){this._state===iI.STARTED&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(iI.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}};let WebXRMotionControllerTeleportation=class WebXRMotionControllerTeleportation extends WebXRAbstractFeature{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){let 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 rg.HE(1,1,1,1),this._tmpRay=new ray_Ray(new rm.P,new rm.P),this._tmpVector=new rm.P,this._tmpQuaternion=new rm._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 rf.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}};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let initMotionController=()=>{if(e.motionController){let i=e.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){let 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;let r=this._options.timeToTeleport||3e3;setAndStartTimer({timeout:r,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,rm._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);let 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;let e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);rm._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?initMotionController():e.onMotionControllerInitObservable.addOnce(()=>{initMotionController()})}else this._xrSessionManager.scene.onPointerObservable.add(i=>{if(i.type===r8.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;let i=this._options.timeToTeleport||3e3;setAndStartTimer({timeout:i,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else i.type===r8.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 rg.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){let t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];let t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){let 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<this._snapToPositions.length;++i)if(this._snapToPositions[i].equals(e)){t=i;break}}return -1!==t&&(this._snapToPositions.splice(t,1),!0)}setSelectionFeature(e){this._selectionFeature=e}_onXRFrame(e){let t=this._xrSessionManager.currentFrame,i=this._xrSessionManager.scene;if(!this.attach||!t)return;let r=this._options.teleportationTargetMesh;if(this._currentTeleportationControllerId){if(!r)return;r.rotationQuaternion=r.rotationQuaternion||new rm._f;let e=this._controllers[this._currentTeleportationControllerId];if(e&&e.teleportationState.forward){rm._f.RotationYawPitchRollToRef(e.teleportationState.currentRotation+e.teleportationState.baseRotation,0,0,r.rotationQuaternion);let t=!1;if(e.xrController.getWorldPointerRayToRef(this._tmpRay),this.straightRayEnabled){let r=i.pickWithRay(this._tmpRay,e=>{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;let t=this._floorMeshes.indexOf(e);return -1!==t&&this._floorMeshes[t].absolutePosition.y<this._options.xrInput.xrCamera.globalPosition.y});if(r&&r.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(r.pickedMesh)){e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(r);return}r&&r.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(r),this._setTargetMeshVisibility(!0),this._showParabolicPath(r))}if(this.parabolicRayEnabled&&!t){let r=e.xrController.pointer.rotationQuaternion.toEulerAngles().x,s=this.parabolicCheckRadius*(1+(Math.PI/2-Math.abs(r)));this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(2*s),this._tmpVector),this._tmpVector.y=this._tmpRay.origin.y,this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(s)),this._tmpVector.subtractToRef(this._tmpRay.origin,this._tmpRay.direction),this._tmpRay.direction.normalize();let n=i.pickWithRay(this._tmpRay,e=>!!this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e)||-1!==this._floorMeshes.indexOf(e));if(n&&n.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(n.pickedMesh)){e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(n);return}n&&n.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(n),this._setTargetMeshVisibility(!0),this._showParabolicPath(n))}this._setTargetMeshVisibility(t)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{let i=new DynamicTexture("teleportationPlaneDynamicTexture",512,e,!0);i.hasAlpha=!0;let r=i.getContext();r.beginPath(),r.arc(256,256,200,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),i.update();let s=new standardMaterial_StandardMaterial("teleportationPlaneMaterial",e);s.diffuseTexture=i,t.material=s}let i=CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){let t=new animation_Animation("animationInnerCircle","position.y",30,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),t.setKeys(r);let s=new SineEase;s.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}let r=cylinderBuilder_CreateCylinder("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate(rL.RD.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{let t=new standardMaterial_StandardMaterial("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new rg.Wo(.3,.3,1):t.diffuseColor=new rg.Wo(.3,.3,1),t.alpha=.9,i.material=t,r.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){let t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){let s=t*t;this._snapToPositions.forEach(t=>{let n=rm.P.DistanceSquared(t,e);n<=s&&n<r&&(r=n,i=t)})}return i}_setTargetMeshPosition(e){let t=e.pickedPoint;if(!this._options.teleportationTargetMesh||!t)return;let i=this._findClosestSnapPointWithRadius(t);this._snappedToPoint=!!i,this.snapPointsOnly&&!this._snappedToPoint&&this._teleportationRingMaterial?this._teleportationRingMaterial.diffuseColor.set(1,.3,.3):this.snapPointsOnly&&this._snappedToPoint&&this._teleportationRingMaterial&&this._teleportationRingMaterial.diffuseColor.set(.3,.3,1),this._options.teleportationTargetMesh.position.copyFrom(i||t),this._options.teleportationTargetMesh.position.y+=.01,this.onTargetMeshPositionUpdatedObservable.notifyObservers(e)}_setTargetMeshVisibility(e,t){this._options.teleportationTargetMesh&&(this._options.teleportationTargetMesh.isVisible!==e||t)&&(this._options.teleportationTargetMesh.isVisible=e,this._options.teleportationTargetMesh.getChildren(void 0,!1).forEach(t=>{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;let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=Curve3.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,n=Array(26).fill(s||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=linesBuilder_CreateLines("teleportation path line",{points:r.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){let t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint)){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){let 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,rm._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)}}}};WebXRMotionControllerTeleportation.Name=webXRFeaturesManager_WebXRFeatureName.TELEPORTATION,WebXRMotionControllerTeleportation.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name,(e,t)=>()=>new WebXRMotionControllerTeleportation(e,t),WebXRMotionControllerTeleportation.Version,!0);let WebXRDefaultExperience=class WebXRDefaultExperience{constructor(){}static CreateAsync(e,t={}){let i=new WebXRDefaultExperience;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){let r=Object.assign({renderTarget:i.renderTarget},t.uiOptions||{});t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new WebXREnterExitUI(e,r)}return WebXRExperienceHelper.CreateAsync(e).then(e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new WebXRInput(e.sessionManager,e.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){let e=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.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(WebXRNearInteraction.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=>(rT.Y.Error("Error initializing XR"),rT.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 removeSource(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}rN.x.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;e<this.lights.length;e++)this.lights[e].dispose();0===this.lights.length&&new HemisphericLight("default light",rm.P.Up(),this)},rN.x.prototype.createDefaultCamera=function(e=!1,t=!1,i=!1){if(t&&this.activeCamera&&(this.activeCamera.dispose(),this.activeCamera=null),!this.activeCamera){let t;let r=this.getWorldExtends(e=>e.isVisible&&e.isEnabled()),s=r.max.subtract(r.min),n=r.min.add(s.scale(.5)),a=1.5*s.length();if(isFinite(a)||(a=1,n.copyFromFloats(0,0,0)),e){let e=new ArcRotateCamera("default camera",-(Math.PI/2),Math.PI/2,a,n,this);e.lowerRadiusLimit=.01*a,e.wheelPrecision=100/a,t=e}else{let e=new FreeCamera("default camera",new rm.P(n.x,n.y,-a),this);e.setTarget(n),t=e}t.minZ=.01*a,t.maxZ=1e3*a,t.speed=.2*a,this.activeCamera=t,i&&t.attachControl()}},rN.x.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},rN.x.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,r=0,s=!0){if(!e)return rT.Y.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);let n=boxBuilder_CreateBox("hdrSkyBox",{size:i},this);if(t){let t=new pbrMaterial_PBRMaterial("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=texture_Texture.SKYBOX_MODE),t.microSurface=1-r,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{let t=new standardMaterial_StandardMaterial("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=texture_Texture.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},rN.x.prototype.createDefaultEnvironment=function(e){return EnvironmentHelper?new EnvironmentHelper(e,this):null},rN.x.prototype.createDefaultVRExperience=function(e={}){return new VRExperienceHelper(this,e)},rN.x.prototype.createDefaultXRExperienceAsync=function(e={}){return WebXRDefaultExperience.CreateAsync(this,e).then(e=>e)};let VideoTexture=class VideoTexture extends texture_Texture{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new rf.y$),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):rT.Y.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if((null==e?void 0:e.name)==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}if(!this.video.muted){rT.Y.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,this.video.play().catch(e=>{this._processError(e)});return}}this._processError(e)})}constructor(e,t,i,r=!1,s=!1,n=texture_Texture.TRILINEAR_SAMPLINGMODE,a={},o,l=5){var h,u;super(null,i,!r,s),this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{var e;null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||rW.w1.IsExponentOfTwo(this.video.videoWidth)&&rW.w1.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=texture_Texture.WRAP_ADDRESSMODE,this.wrapV=texture_Texture.WRAP_ADDRESSMODE):(this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.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{let 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||this.video.readyState<this.video.HAVE_CURRENT_DATA||this._displayingPosterTexture)return;let e=this.getScene().getFrameId();this._frameId!==e&&(this._frameId=e,this._getEngine().updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:this.video,this._invertY))},this._settings=Object.assign({autoPlay:!0,loop:!0,autoUpdateTexture:!0},a),this._onError=o,this._generateMipMaps=r,this._initialSamplingMode=n,this.autoUpdateTexture=this._settings.autoUpdateTexture,this._currentSrc=t,this.name=e||this._getName(t),this.video=this._getVideo(t),this._externalTexture=null!==(u=null===(h=this._engine)||void 0===h?void 0:h.createExternalTexture(this.video))&&void 0!==u?u:null,!this._settings.independentVideoSource&&(this._settings.poster&&(this.video.poster=this._settings.poster),void 0!==this._settings.autoPlay&&(this.video.autoplay=this._settings.autoPlay),void 0!==this._settings.loop&&(this.video.loop=this._settings.loop),void 0!==this._settings.muted&&(this.video.muted=this._settings.muted),this.video.setAttribute("playsinline",""),this.video.addEventListener("paused",this._updateInternalTexture),this.video.addEventListener("seeked",this._updateInternalTexture),this.video.addEventListener("emptied",this._reset),this._settings.autoPlay&&this._handlePlay()),this._createInternalTextureOnEvent=this._settings.poster&&!this._settings.autoPlay?"play":"canplay",this.video.addEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._format=l;let c=this.video.readyState>=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&c?c&&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 rW.w1.SetCorsBehavior(e.currentSrc,e),e;let t=document.createElement("video");return"string"==typeof e?(rW.w1.SetCorsBehavior(e,t),t.src=e):(rW.w1.SetCorsBehavior(e[0],t),e.forEach(e=>{let i=document.createElement("source");i.src=e,t.appendChild(i)})),this.onDisposeObservable.addOnce(()=>{removeSource(t)}),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){!e||this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture())}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new VideoTexture(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,r=!0){let 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=>{let onPlaying=()=>{let i=new VideoTexture("video",s,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&i.onDisposeObservable.addOnce(()=>{s.remove()}),i.onDisposeObservable.addOnce(()=>{removeSource(s)}),t(i),s.removeEventListener("playing",onPlaying)};s.addEventListener("playing",onPlaying),s.play()})}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){let s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,s,t,r);return n.onDisposeObservable.addOnce(()=>{s.getTracks().forEach(e=>{e.stop()})}),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,s=!0){this.CreateFromWebCamAsync(e,i,r,s).then(function(e){t&&t(e)}).catch(function(e){rT.Y.Error(e.name)})}};(0,rH.gn)([(0,rb.qC)("settings")],VideoTexture.prototype,"_settings",void 0),(0,rH.gn)([(0,rb.qC)("src")],VideoTexture.prototype,"_currentSrc",void 0),(0,rH.gn)([(0,rb.qC)()],VideoTexture.prototype,"isVideo",void 0),texture_Texture._CreateVideoTexture=(e,t,i,r=!1,s=!1,n=texture_Texture.TRILINEAR_SAMPLINGMODE,a={},o,l=5)=>new VideoTexture(e,t,i,r,s,n,a,o,l),(0,rv.H)("BABYLON.VideoTexture",VideoTexture);let VideoDome=class VideoDome extends TextureDome{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){let r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new VideoTexture((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,texture_Texture.TRILINEAR_SAMPLINGMODE,r);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()},r8.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)}};VideoDome.MODE_MONOSCOPIC=TextureDome.MODE_MONOSCOPIC,VideoDome.MODE_TOPBOTTOM=TextureDome.MODE_TOPBOTTOM,VideoDome.MODE_SIDEBYSIDE=TextureDome.MODE_SIDEBYSIDE;let o0=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) +#include<helperFunctions> +#endif +#ifdef DIFFUSE +varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; +#endif +#ifdef OPACITY +varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; +#endif +#ifdef EMISSIVE +varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; +#endif +#ifdef VERTEXALPHA +varying vec4 vColor; +#endif +uniform vec4 glowColor;uniform float glowIntensity; +#include<clipPlaneFragmentDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include<clipPlaneFragment> +vec4 finalColor=glowColor; +#ifdef DIFFUSE +vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); +#ifdef DIFFUSE_ISLINEAR +albedoTexture=toGammaSpace(albedoTexture); +#endif +#ifdef GLOW +finalColor.a*=albedoTexture.a; +#endif +#ifdef HIGHLIGHT +finalColor.a=albedoTexture.a; +#endif +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); +#ifdef OPACITYRGB +finalColor.a*=getLuminance(opacityMap.rgb); +#else +finalColor.a*=opacityMap.a; +#endif +finalColor.a*=opacityIntensity; +#endif +#ifdef VERTEXALPHA +finalColor.a*=vColor.a; +#endif +#ifdef ALPHATEST +if (finalColor.a<ALPHATESTVALUE) +discard; +#endif +#ifdef EMISSIVE +vec4 emissive=texture2D(emissiveSampler,vUVEmissive); +#ifdef EMISSIVE_ISLINEAR +emissive=toGammaSpace(emissive); +#endif +gl_FragColor=emissive*finalColor*glowIntensity; +#else +gl_FragColor=finalColor*glowIntensity; +#endif +#ifdef HIGHLIGHT +gl_FragColor.a=glowColor.a; +#endif +}`;s_.v.ShadersStore.glowMapGenerationPixelShader=o0;let o1=`attribute vec3 position; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<clipPlaneVertexDeclaration> +#include<instancesDeclaration> +uniform mat4 viewProjection;varying vec4 vPosition; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef DIFFUSE +varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; +#endif +#ifdef OPACITY +varying vec2 vUVOpacity;uniform mat4 opacityMatrix; +#endif +#ifdef EMISSIVE +varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; +#endif +#ifdef VERTEXALPHA +attribute vec4 color;varying vec4 vColor; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef CUBEMAP +vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); +#else +vPosition=viewProjection*worldPos;gl_Position=vPosition; +#endif +#ifdef DIFFUSE +#ifdef DIFFUSEUV1 +vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef DIFFUSEUV2 +vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef OPACITY +#ifdef OPACITYUV1 +vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef OPACITYUV2 +vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef EMISSIVE +#ifdef EMISSIVEUV1 +vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef EMISSIVEUV2 +vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef VERTEXALPHA +vColor=color; +#endif +#include<clipPlaneVertex> +}`;s_.v.ShadersStore.glowMapGenerationVertexShader=o1;let EffectLayer=class EffectLayer{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i<e.length;++i){let r=e[i];t?this._materialForRendering[r.uniqueId]=[r,t]:delete this._materialForRendering[r.uniqueId]}else t?this._materialForRendering[e.uniqueId]=[e,t]:delete this._materialForRendering[e.uniqueId]}getEffectIntensity(e){var t;return null!==(t=this._effectIntensity[e.uniqueId])&&void 0!==t?t:1}setEffectIntensity(e,t){this._effectIntensity[e.uniqueId]=t}constructor(e,t){this._vertexBuffers={},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._shouldRender=!0,this._postProcesses=[],this._textures=[],this._emissiveTextureAndColor={texture:null,color:new rg.HE},this._effectIntensity={},this.neutralColor=new rg.HE,this.isEnabled=!0,this.disableBoundingBoxesFromEffectLayer=!1,this.onDisposeObservable=new rf.y$,this.onBeforeRenderMainTextureObservable=new rf.y$,this.onBeforeComposeObservable=new rf.y$,this.onBeforeRenderMeshToEffect=new rf.y$,this.onAfterRenderMeshToEffect=new rf.y$,this.onAfterComposeObservable=new rf.y$,this.onSizeChangedObservable=new rf.y$,this._materialForRendering={},this.name=e,this._scene=t||rS.l.LastCreatedScene,EffectLayer._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.effectLayers.push(this),this._mergeDrawWrapper=[],this._generateIndexBuffer(),this._generateVertexBuffer()}_numInternalDraws(){return 1}_init(e){this._effectLayerOptions=Object.assign({mainTextureRatio:.5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,generateStencilBuffer:!1},e),this._setMainTextureSize(),this._createMainTexture(),this._createTextureAndPostProcesses()}_generateIndexBuffer(){let e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._engine.createIndexBuffer(e)}_generateVertexBuffer(){let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1);let t=new rz.o(this._engine,e,rz.o.PositionKind,!1,!1,2);this._vertexBuffers[rz.o.PositionKind]=t}_setMainTextureSize(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?rq.D.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?rq.D.GetExponentOfTwo(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)}_createMainTexture(){for(let e in this._mainTexture=new renderTargetTexture_RenderTargetTexture("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,!1,!0,this._effectLayerOptions.mainTextureType,!1,texture_Texture.TRILINEAR_SAMPLINGMODE,!0,this._effectLayerOptions.generateStencilBuffer),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._materialForRendering){let[t,i]=this._materialForRendering[e];this._mainTexture.setMaterialForRendering(t,i)}if(this._mainTexture.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){let i=e.subMeshes[t],r=i.getMaterial(),s=i.getRenderingMesh();if(!r)continue;let n=s._getInstancesRenderList(i._id,!!i.getReplacementMesh()),a=n.hardwareInstancedRendering[i._id]||s.hasThinInstances;if(this._setEmissiveTextureAndColor(s,i,r),!this._isReady(i,a,this._emissiveTextureAndColor.texture))return!1}return!0},this._mainTexture.customRenderFunction=(e,t,i,r)=>{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);let n=this._scene.getEngine();if(r.length){for(n.setColorWrite(!1),s=0;s<r.length;s++)this._renderSubMesh(r.data[s]);n.setColorWrite(!0)}for(s=0;s<e.length;s++)this._renderSubMesh(e.data[s]);for(s=0;s<t.length;s++)this._renderSubMesh(t.data[s]);let a=n.getAlphaMode();for(s=0;s<i.length;s++)this._renderSubMesh(i.data[s],!0);n.setAlphaMode(a)},this._mainTexture.onClearObservable.add(e=>{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){let 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 r;let s=this._scene.getEngine(),n=e.getMesh(),a=null===(r=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[s.currentRenderPassId];if(a)return a.isReadyForSubMesh(n,e,t);let o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);let l=[],h=[rz.o.PositionKind],u=!1,c=!1;if(o){let e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(l.push("#define DIFFUSE"),n.isVerticesDataPresent(rz.o.UV2Kind)&&1===t.coordinatesIndex?(l.push("#define DIFFUSEUV2"),c=!0):n.isVerticesDataPresent(rz.o.UVKind)&&(l.push("#define DIFFUSEUV1"),u=!0),e&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));let r=o.opacityTexture;r&&(l.push("#define OPACITY"),n.isVerticesDataPresent(rz.o.UV2Kind)&&1===r.coordinatesIndex?(l.push("#define OPACITYUV2"),c=!0):n.isVerticesDataPresent(rz.o.UVKind)&&(l.push("#define OPACITYUV1"),u=!0))}i&&(l.push("#define EMISSIVE"),n.isVerticesDataPresent(rz.o.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),c=!0):n.isVerticesDataPresent(rz.o.UVKind)&&(l.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent(rz.o.ColorKind)&&n.hasVertexAlpha&&o.transparencyMode!==sr.F.MATERIAL_OPAQUE&&(h.push(rz.o.ColorKind),l.push("#define VERTEXALPHA")),u&&(h.push(rz.o.UVKind),l.push("#define UV1")),c&&(h.push(rz.o.UV2Kind),l.push("#define UV2"));let d=new EffectFallbacks;if(n.useBones&&n.computeBonesUsingShaders){h.push(rz.o.MatricesIndicesKind),h.push(rz.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(h.push(rz.o.MatricesIndicesExtraKind),h.push(rz.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);let e=n.skeleton;e&&e.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),n.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,n)}else l.push("#define NUM_BONE_INFLUENCERS 0");let p=n.morphTargetManager,_=0;p&&p.numInfluencers>0&&(l.push("#define MORPHTARGETS"),_=p.numInfluencers,l.push("#define NUM_MORPH_INFLUENCERS "+_),p.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),so.G.PrepareAttributesForMorphTargetsInfluencers(h,n,_)),t&&(l.push("#define INSTANCES"),so.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),(0,nX.lK)(o,this._scene,l),this._addCustomEffectDefines(l);let f=e._getDrawWrapper(void 0,!0),m=f.defines,g=l.join("\n");if(m!==g){let e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];(0,nX.qx)(e),f.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:_}),g)}return f.effect.isReady()}render(){for(let e=0;e<this._postProcesses.length;e++)if(!this._postProcesses[e].isReady())return;let e=this._scene.getEngine(),t=this._numInternalDraws(),i=!0;for(let e=0;e<t;++e){let t=this._mergeDrawWrapper[e];t||(t=this._mergeDrawWrapper[e]=new sm.q(this._engine)).setEffect(this._createMergeEffect()),i=i&&t.effect.isReady()}if(!i)return;this.onBeforeComposeObservable.notifyObservers(this);let r=e.getAlphaMode();for(let i=0;i<t;++i){let t=this._mergeDrawWrapper[i];e.enableEffect(t),e.setState(!1),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t.effect),e.setAlphaMode(this._effectLayerOptions.alphaBlendingMode),this._internalRender(t.effect,i)}e.setAlphaMode(r),this.onAfterComposeObservable.notifyObservers(this);let s=this._mainTexture.getSize();this._setMainTextureSize(),(s.width!==this._mainTextureDesiredSize.width||s.height!==this._mainTextureDesiredSize.height)&&0!==this._mainTextureDesiredSize.width&&0!==this._mainTextureDesiredSize.height&&(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses())}hasMesh(e){return -1===this.renderingGroupId||e.renderingGroupId===this.renderingGroupId}shouldRender(){return this.isEnabled&&this._shouldRender}_shouldRenderMesh(e){return!0}_canRenderMesh(e,t){return!t.needAlphaBlendingForMesh(e)}_shouldRenderEmissiveTextureForMesh(){return!0}_renderSubMesh(e,t=!1){var i,r;if(!this.shouldRender())return;let s=e.getMaterial(),n=e.getMesh(),a=e.getReplacementMesh(),o=e.getRenderingMesh(),l=e.getEffectiveMesh(),h=this._scene,u=h.getEngine();if(l._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!s||!this._canRenderMesh(o,s))return;let c=null!==(i=o.overrideMaterialSideOrientation)&&void 0!==i?i:s.sideOrientation,d=l._getWorldMatrixDeterminant();d<0&&(c=c===sr.F.ClockWiseSideOrientation?sr.F.CounterClockWiseSideOrientation:sr.F.ClockWiseSideOrientation);let p=c===sr.F.ClockWiseSideOrientation;u.setState(s.backFaceCulling,s.zOffset,void 0,p,s.cullBackFaces,void 0,s.zOffsetUnits);let _=o._getInstancesRenderList(e._id,!!a);if(_.mustReturn||!this._shouldRenderMesh(o))return;let f=_.hardwareInstancedRendering[e._id]||o.hasThinInstances;if(this._setEmissiveTextureAndColor(o,e,s),this.onBeforeRenderMeshToEffect.notifyObservers(n),this._useMeshMaterial(o))o.render(e,t,a||void 0);else if(this._isReady(e,f,this._emissiveTextureAndColor.texture)){let i=null===(r=l._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[u.currentRenderPassId],n=e._getDrawWrapper();if(!n&&i&&(n=i._getDrawWrapper()),!n)return;let a=n.effect;if(u.enableEffect(n),f||o._bind(e,a,s.fillMode),i?i.bindForSubMesh(l.getWorldMatrix(),l,e):(a.setMatrix("viewProjection",h.getTransformMatrix()),a.setMatrix("world",l.getWorldMatrix()),a.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!i){let e=s.needAlphaTesting(),i=s.getAlphaTestTexture(),r=i&&i.hasAlpha&&(s.useAlphaFromDiffuseTexture||s._useAlphaFromAlbedoTexture);if(i&&(e||r)){a.setTexture("diffuseSampler",i);let e=i.getTextureMatrix();e&&a.setMatrix("diffuseMatrix",e)}let n=s.opacityTexture;if(n){a.setTexture("opacitySampler",n),a.setFloat("opacityIntensity",n.level);let e=n.getTextureMatrix();e&&a.setMatrix("opacityMatrix",e)}if(this._emissiveTextureAndColor.texture&&(a.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),a.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),o.useBones&&o.computeBonesUsingShaders&&o.skeleton){let e=o.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(o);if(!t)return;a.setTexture("boneSampler",t),a.setFloat("boneTextureWidth",4*(e.bones.length+1))}else a.setMatrices("mBones",e.getTransformMatrices(o))}so.G.BindMorphTargetParameters(o,a),o.morphTargetManager&&o.morphTargetManager.isUsingTextureForTargets&&o.morphTargetManager._bind(a),t&&u.setAlphaMode(s.alphaMode),a.setFloat("glowIntensity",this.getEffectIntensity(o)),(0,nX.an)(a,s,h)}o._processRendering(l,e,a,s.fillMode,_,f,(e,t)=>a.setMatrix("world",t))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(n)}_useMeshMaterial(e){return!1}_rebuild(){let e=this._vertexBuffers[rz.o.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e<this._postProcesses.length;e++)this._postProcesses[e]&&this._postProcesses[e].dispose();this._postProcesses=[];for(let e=0;e<this._textures.length;e++)this._textures[e]&&this._textures[e].dispose();this._textures=[]}dispose(){let e=this._vertexBuffers[rz.o.PositionKind];for(let t of(e&&(e.dispose(),this._vertexBuffers[rz.o.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._mergeDrawWrapper))t.dispose();this._mergeDrawWrapper=[],this._disposeTextureAndPostProcesses();let t=this._scene.effectLayers.indexOf(this,0);t>-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){let r=rW.w1.Instantiate(e.customType);return r.Parse(e,t,i)}};EffectLayer._SceneComponentInitialization=e=>{throw(0,r$.S)("EffectLayerSceneComponent")},(0,rH.gn)([(0,rb.qC)()],EffectLayer.prototype,"name",void 0),(0,rH.gn)([(0,rb.XX)()],EffectLayer.prototype,"neutralColor",void 0),(0,rH.gn)([(0,rb.qC)()],EffectLayer.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.VE)()],EffectLayer.prototype,"camera",null),(0,rH.gn)([(0,rb.qC)()],EffectLayer.prototype,"renderingGroupId",null),(0,rH.gn)([(0,rb.qC)()],EffectLayer.prototype,"disableBoundingBoxesFromEffectLayer",void 0),rp.p.AddParser(rQ.l.NAME_EFFECTLAYER,(e,t,i,r)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let s=0;s<e.effectLayers.length;s++){let n=EffectLayer.Parse(e.effectLayers[s],t,r);i.effectLayers.push(n)}}}),rp.p.prototype.removeEffectLayer=function(e){let t=this.effectLayers.indexOf(e);return -1!==t&&this.effectLayers.splice(t,1),t},rp.p.prototype.addEffectLayer=function(e){this.effectLayers.push(e)};let EffectLayerSceneComponent=class EffectLayerSceneComponent{constructor(e){if(this.name=rQ.l.NAME_EFFECTLAYER,this._renderEffects=!1,this._needStencil=!1,this._previousStencilState=!1,this.scene=e||rS.l.LastCreatedScene,!this.scene)return;this._engine=this.scene.getEngine(),this.scene.effectLayers=[]}register(){this.scene._isReadyForMeshStage.registerStep(rQ.l.STEP_ISREADYFORMESH_EFFECTLAYER,this,this._isReadyForMesh),this.scene._cameraDrawRenderTargetStage.registerStep(rQ.l.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER,this,this._renderMainTexture),this.scene._beforeCameraDrawStage.registerStep(rQ.l.STEP_BEFORECAMERADRAW_EFFECTLAYER,this,this._setStencil),this.scene._afterRenderingGroupDrawStage.registerStep(rQ.l.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW,this,this._drawRenderingGroup),this.scene._afterCameraDrawStage.registerStep(rQ.l.STEP_AFTERCAMERADRAW_EFFECTLAYER,this,this._setStencilBack),this.scene._afterCameraDrawStage.registerStep(rQ.l.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW,this,this._drawCamera)}rebuild(){let e=this.scene.effectLayers;for(let t of e)t._rebuild()}serialize(e){e.effectLayers=[];let t=this.scene.effectLayers;for(let i of t)i.serialize&&e.effectLayers.push(i.serialize())}addFromContainer(e){e.effectLayers&&e.effectLayers.forEach(e=>{this.scene.addEffectLayer(e)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(e=>{this.scene.removeEffectLayer(e),t&&e.dispose()})}dispose(){let e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){let i=this._engine.currentRenderPassId,r=this.scene.effectLayers;for(let s of r){if(!s.hasMesh(e))continue;let r=s._mainTexture;for(let n of(this._engine.currentRenderPassId=r.renderPassId,e.subMeshes))if(!s.isReady(n,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1,i=this.scene.effectLayers;if(i&&i.length>0){for(let r of(this._previousStencilState=this._engine.getStencilBuffer(),i))if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===rj.V.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==rj.V.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();let e=r._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);let t=this.scene.effectLayers;for(let i=0;i<t.length;i++){let r=t[i];r.renderingGroupId===e&&r.shouldRender()&&r.render()}this._engine.setDepthBuffer(!0)}}_drawCamera(){this._renderEffects&&this._draw(-1)}_drawRenderingGroup(e){!this.scene._isInIntermediateRendering()&&this._renderEffects&&this._draw(e)}};EffectLayer._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_EFFECTLAYER);t||(t=new EffectLayerSceneComponent(e),e._addComponent(t))};let o2=`varying vec2 vUV;uniform sampler2D textureSampler; +#ifdef EMISSIVE +uniform sampler2D textureSampler2; +#endif +uniform float offset; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV); +#ifdef EMISSIVE +baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; +#else +baseColor.a=abs(offset-baseColor.a); +#ifdef STROKE +float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; +#endif +#endif +#if LDR +baseColor=clamp(baseColor,0.,1.0); +#endif +gl_FragColor=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`;s_.v.ShadersStore.glowMapMergePixelShader=o2;let o3=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.glowMapMergeVertexShader=o3,rp.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()===GlowLayer.EffectName)return this.effectLayers[i];return null};let GlowLayer=class GlowLayer extends EffectLayer{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;let 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 rg.HE(0,0,0,1),this._options=Object.assign({mainTextureRatio:GlowLayer.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType,generateStencilBuffer:this._options.generateStencilBuffer})}getEffectName(){return GlowLayer.EffectName}_createMergeEffect(){let e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[rz.o.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?rq.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?rq.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new renderTargetTexture_RenderTargetTexture("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;let r=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new renderTargetTexture_RenderTargetTexture("GlowLayerBlurRTT2",{width:r,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];let n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new BlurPostProcess("GlowLayerHBP1",new rm.FM(1,0),n,{width:e,height:t},null,texture_Texture.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 BlurPostProcess("GlowLayerVBP1",new rm.FM(0,1),n,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new BlurPostProcess("GlowLayerHBP2",new rm.FM(1,0),n,{width:r,height:s},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new BlurPostProcess("GlowLayerVBP2",new rm.FM(0,1),n,{width:r,height:s},null,texture_Texture.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(()=>{let e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);let 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){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;let 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);let t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(sr.F.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var r;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){let e=null!==(r=i.emissiveIntensity)&&void 0!==r?r:1;s*=e,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){let 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){let 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(){let e;let t=rb.p4.Serialize(this);if(t.customType="BABYLON.GlowLayer",t.includedMeshes=[],this._includedOnlyMeshes.length)for(e=0;e<this._includedOnlyMeshes.length;e++){let i=this._scene.getMeshByUniqueId(this._includedOnlyMeshes[e]);i&&t.includedMeshes.push(i.id)}if(t.excludedMeshes=[],this._excludedMeshes.length)for(e=0;e<this._excludedMeshes.length;e++){let i=this._scene.getMeshByUniqueId(this._excludedMeshes[e]);i&&t.excludedMeshes.push(i.id)}return t}static Parse(e,t,i){let r;let s=rb.p4.Parse(()=>new GlowLayer(e.name,t,e.options),e,t,i);for(r=0;r<e.excludedMeshes.length;r++){let i=t.getMeshById(e.excludedMeshes[r]);i&&s.addExcludedMesh(i)}for(r=0;r<e.includedMeshes.length;r++){let i=t.getMeshById(e.includedMeshes[r]);i&&s.addIncludedOnlyMesh(i)}return s}};GlowLayer.EffectName="GlowLayer",GlowLayer.DefaultBlurKernelSize=32,GlowLayer.DefaultTextureRatio=.5,(0,rH.gn)([(0,rb.qC)()],GlowLayer.prototype,"blurKernelSize",null),(0,rH.gn)([(0,rb.qC)()],GlowLayer.prototype,"intensity",null),(0,rH.gn)([(0,rb.qC)("options")],GlowLayer.prototype,"_options",void 0),(0,rv.H)("BABYLON.GlowLayer",GlowLayer);let o4=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color) +{return dot(color,vec3(0.2126,0.7152,0.0722));} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++) +{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;} +gl_FragColor=baseColor;}`;s_.v.ShadersStore.glowBlurPostProcessPixelShader=o4,rp.p.prototype.getHighlightLayerByName=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()===HighlightLayer.EffectName)return this.effectLayers[i];return null};let GlowBlurPostProcess=class GlowBlurPostProcess extends postProcess_PostProcess{constructor(e,t,i,r,s,n=texture_Texture.BILINEAR_SAMPLINGMODE,a,o){super(e,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,r,s,n,a,o),this.direction=t,this.kernel=i,this.onApplyObservable.add(e=>{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)})}};let HighlightLayer=class HighlightLayer extends EffectLayer{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 rf.y$,this.onAfterBlurObservable=new rf.y$,this._instanceGlowingMeshStencilReference=HighlightLayer.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=HighlightLayer.NeutralColor,this._engine.isStencilEnable||rT.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 HighlightLayer.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[rz.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?rq.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?rq.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new renderTargetTexture_RenderTargetTexture("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(texture_Texture.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new PassPostProcess("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new GlowBlurPostProcess("HighlightLayerHBP",new rm.FM(1,0),this._options.blurHorizontalSize,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new GlowBlurPostProcess("HighlightLayerVBP",new rm.FM(0,1),this._options.blurVerticalSize,1,null,texture_Texture.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 BlurPostProcess("HighlightLayerHBP",new rm.FM(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,texture_Texture.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 BlurPostProcess("HighlightLayerVBP",new rm.FM(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);let 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){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null,n=this._meshes[r.uniqueId];return n&&n.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);let 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(sr.F.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(sr.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){let r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];if(!t){let 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;let 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;let r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(e=>{this.isEnabled&&this._defaultStencilReference(e)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;let t=this._meshes[e.uniqueId];for(let i in t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1,this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(let e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){let t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(let e in this._meshes){let 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(let e in this._excludedMeshes){let 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(){let e=rb.p4.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(let t in this._meshes){let 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(let t in this._excludedMeshes){let i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){let r;let s=rb.p4.Parse(()=>new HighlightLayer(e.name,t,e.options),e,t,i);for(r=0;r<e.excludedMeshes.length;r++){let i=t.getMeshById(e.excludedMeshes[r]);i&&s.addExcludedMesh(i)}for(r=0;r<e.meshes.length;r++){let i=e.meshes[r],n=t.getMeshById(i.meshId);n&&s.addMesh(n,rg.Wo.FromArray(i.color),i.glowEmissiveOnly)}return s}};HighlightLayer.EffectName="HighlightLayer",HighlightLayer.NeutralColor=new rg.HE(0,0,0,0),HighlightLayer.GlowingMeshStencilReference=2,HighlightLayer.NormalMeshStencilReference=1,(0,rH.gn)([(0,rb.qC)()],HighlightLayer.prototype,"innerGlow",void 0),(0,rH.gn)([(0,rb.qC)()],HighlightLayer.prototype,"outerGlow",void 0),(0,rH.gn)([(0,rb.qC)()],HighlightLayer.prototype,"blurHorizontalSize",null),(0,rH.gn)([(0,rb.qC)()],HighlightLayer.prototype,"blurVerticalSize",null),(0,rH.gn)([(0,rb.qC)("options")],HighlightLayer.prototype,"_options",void 0),(0,rv.H)("BABYLON.HighlightLayer",HighlightLayer);let o5=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; +#include<helperFunctions> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV); +#ifdef LINEAR +baseColor.rgb=toGammaSpace(baseColor.rgb); +#endif +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +gl_FragColor=baseColor*color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;s_.v.ShadersStore.layerPixelShader=o5;let o6=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.layerVertexShader=o6;let LensFlare=class LensFlare{static AddFlare(e,t,i,r,s){return new LensFlare(e,t,i,r,s)}constructor(e,t,i,r,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new rg.Wo(1,1,1),this.texture=r?new texture_Texture(r,s.getScene(),!0):null,this._system=s;let n=s.scene.getEngine();this._drawWrapper=new sm.q(n),this._drawWrapper.effect=n.createEffect("lensFlare",[rz.o.PositionKind],["color","viewportMatrix"],["textureSampler"],""),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();let e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}};let o8=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;s_.v.ShadersStore.lensFlarePixelShader=o8;let o7=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.lensFlareVertexShader=o7;let LensFlareSystem=class LensFlareSystem{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||rS.l.LastCreatedScene,LensFlareSystem._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&(e.layerMask&i.activeCamera.layerMask)!=0;let r=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[rz.o.PositionKind]=new rz.o(r,s,rz.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){let 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=rm.P.Project(t,rm.y3.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=rm.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);let i=this._scene.useRightHandedSystem,r=t.z>0&&!i||t.z<0&&i;return!!r&&(this._positionX>e.x&&this._positionX<e.x+e.width&&this._positionY>e.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;let e=this.getEmitterPosition(),t=e.subtract(this._scene.activeCamera.globalPosition),i=t.length();t.normalize();let r=new ray_Ray(this._scene.activeCamera.globalPosition,t),s=this._scene.pickWithRay(r,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>i}render(){let e,t;if(!this._scene.activeCamera)return!1;let i=this._scene.getEngine(),r=this._scene.activeCamera.viewport,s=r.toGlobal(i.getRenderWidth(!0),i.getRenderHeight(!0));if(!this.computeEffectivePosition(s)||!this._isVisible())return!1;let n=(e=this._positionX<this.borderLimit+s.x?this.borderLimit+s.x-this._positionX:this._positionX>s.x+s.width-this.borderLimit?this._positionX-s.x-s.width+this.borderLimit:0)>(t=this._positionY<this.borderLimit+s.y?this.borderLimit+s.y-this._positionY:this._positionY>s.y+s.height-this.borderLimit?this._positionY-s.y-s.height+this.borderLimit:0)?e:t;(n-=this.viewportBorder)>this.borderLimit&&(n=this.borderLimit);let a=1-rE.R.Clamp(n/this.borderLimit,0,1);if(a<0)return!1;a>1&&(a=1),this.viewportBorder>0&&(s.x+=this.viewportBorder,s.y+=this.viewportBorder,s.width-=2*this.viewportBorder,s.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);let o=s.x+s.width/2,l=s.y+s.height/2,h=o-this._positionX,u=l-this._positionY;i.setState(!1),i.setDepthBuffer(!1);for(let e=0;e<this.lensFlares.length;e++){let t=this.lensFlares[e];if(!t._drawWrapper.effect.isReady()||t.texture&&!t.texture.isReady())continue;i.enableEffect(t._drawWrapper),i.bindBuffers(this._vertexBuffers,this._indexBuffer,t._drawWrapper.effect),i.setAlphaMode(t.alphaMode);let r=o-h*t.position,n=l-u*t.position,c=t.size,d=t.size*i.getAspectRatio(this._scene.activeCamera,!0),p=2*(r/(s.width+2*s.x))-1,_=1-2*(n/(s.height+2*s.y)),f=rm.y3.FromValues(c/2,0,0,0,0,d/2,0,0,0,0,1,0,p,_,0,1);t._drawWrapper.effect.setMatrix("viewportMatrix",f),t._drawWrapper.effect.setTexture("textureSampler",t.texture),t._drawWrapper.effect.setFloat4("color",t.color.r*a,t.color.g*a,t.color.b*a,1),i.drawElementsType(sr.F.TriangleFillMode,0,6)}return i.setDepthBuffer(!0),i.setAlphaMode(0),!0}rebuild(){var e;for(let t in this._createIndexBuffer(),this._vertexBuffers)null===(e=this._vertexBuffers[t])||void 0===e||e._rebuild()}dispose(){let e=this._vertexBuffers[rz.o.PositionKind];for(e&&(e.dispose(),this._vertexBuffers[rz.o.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);this.lensFlares.length;)this.lensFlares[0].dispose();let t=this._scene.lensFlareSystems.indexOf(this);this._scene.lensFlareSystems.splice(t,1)}static Parse(e,t,i){let r=t.getLastEntryById(e.emitterId),s=e.name||"lensFlareSystem#"+e.emitterId,n=new LensFlareSystem(s,r,t);n.id=e.id||s,n.borderLimit=e.borderLimit;for(let t=0;t<e.flares.length;t++){let r=e.flares[t];LensFlare.AddFlare(r.size,r.position,rg.Wo.FromArray(r.color),r.textureName?i+r.textureName:"",n)}return n}serialize(){let e={};e.id=this.id,e.name=this.name,e.emitterId=this.getEmitter().id,e.borderLimit=this.borderLimit,e.flares=[];for(let t=0;t<this.lensFlares.length;t++){let i=this.lensFlares[t];e.flares.push({size:i.size,position:i.position,color:i.color.asArray(),textureName:rW.w1.GetFilename(i.texture?i.texture.name:"")})}return e}};LensFlareSystem._SceneComponentInitialization=e=>{throw(0,r$.S)("LensFlareSystemSceneComponent")},rp.p.AddParser(rQ.l.NAME_LENSFLARESYSTEM,(e,t,i,r)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let s=0,n=e.lensFlareSystems.length;s<n;s++){let n=e.lensFlareSystems[s],a=LensFlareSystem.Parse(n,t,r);i.lensFlareSystems.push(a)}}}),rp.p.prototype.getLensFlareSystemByName=function(e){for(let t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].name===e)return this.lensFlareSystems[t];return null},rp.p.prototype.getLensFlareSystemById=function(e){for(let t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].id===e)return this.lensFlareSystems[t];return null},rp.p.prototype.getLensFlareSystemByID=function(e){return this.getLensFlareSystemById(e)},rp.p.prototype.removeLensFlareSystem=function(e){let t=this.lensFlareSystems.indexOf(e);return -1!==t&&this.lensFlareSystems.splice(t,1),t},rp.p.prototype.addLensFlareSystem=function(e){this.lensFlareSystems.push(e)};let LensFlareSystemSceneComponent=class LensFlareSystemSceneComponent{constructor(e){this.name=rQ.l.NAME_LENSFLARESYSTEM,this.scene=e,e.lensFlareSystems=[]}register(){this.scene._afterCameraDrawStage.registerStep(rQ.l.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM,this,this._draw)}rebuild(){for(let e=0;e<this.scene.lensFlareSystems.length;e++)this.scene.lensFlareSystems[e].rebuild()}addFromContainer(e){e.lensFlareSystems&&e.lensFlareSystems.forEach(e=>{this.scene.addLensFlareSystem(e)})}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach(e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()})}serialize(e){e.lensFlareSystems=[];let t=this.scene.lensFlareSystems;for(let i of t)e.lensFlareSystems.push(i.serialize())}dispose(){let e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){let t=this.scene.lensFlareSystems;for(let i of(rW.w1.StartPerformanceCounter("Lens flares",t.length>0),t))(e.layerMask&i.layerMask)!=0&&i.render();rW.w1.EndPerformanceCounter("Lens flares",t.length>0)}}};LensFlareSystem._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_LENSFLARESYSTEM);t||(t=new LensFlareSystemSceneComponent(e),e._addComponent(t))};let o9=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} +float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); +vec2 P2=floor(0.5*mod(_P,4.0)); +return 4.0*bayerDither2(P1)+bayerDither2(P2);} +float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); +vec2 P2=floor(0.5 *mod(_P,4.0)); +vec2 P4=floor(0.25*mod(_P,8.0)); +return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} +`;s_.v.IncludesShadersStore.bayerDitherFunctions=o9;let le=`#if SM_FLOAT==0 +#include<packingFunctions> +#endif +#if SM_SOFTTRANSPARENTSHADOW==1 +#include<bayerDitherFunctions> +uniform float softTransparentShadowSM; +#endif +varying float vDepthMetricSM; +#if SM_USEDISTANCE==1 +uniform vec3 lightDataSM;varying vec3 vPositionWSM; +#endif +uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying float zSM; +#endif +`;s_.v.IncludesShadersStore.shadowMapFragmentExtraDeclaration=le;let lt=`float depthSM=vDepthMetricSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +#if SM_USEDISTANCE==1 +depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#endif +#ifdef USE_REVERSE_DEPTHBUFFER +gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); +#else +gl_FragDepth=clamp(depthSM,0.0,1.0); +#endif +#elif SM_USEDISTANCE==1 +depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#if SM_ESM==1 +depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); +#endif +#if SM_FLOAT==1 +gl_FragColor=vec4(depthSM,1.0,1.0,1.0); +#else +gl_FragColor=pack(depthSM); +#endif +return;`;s_.v.IncludesShadersStore.shadowMapFragment=lt;let li=`#include<shadowMapFragmentExtraDeclaration> +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include<clipPlaneFragmentDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include<clipPlaneFragment> +#ifdef ALPHATEXTURE +float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; +#ifdef ALPHATESTVALUE +if (alphaFromAlphaTexture<ALPHATESTVALUE) +discard; +#endif +#endif +#if SM_SOFTTRANSPARENTSHADOW==1 +#ifdef ALPHATEXTURE +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alphaFromAlphaTexture) discard; +#else +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard; +#endif +#endif +#include<shadowMapFragment> +}`;s_.v.ShadersStore.shadowMapPixelShader=li;let lr=`uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; +`;s_.v.IncludesShadersStore.sceneVertexDeclaration=lr;let ls=`uniform mat4 world;uniform float visibility; +`;s_.v.IncludesShadersStore.meshVertexDeclaration=ls;let ln=`#include<sceneVertexDeclaration> +#include<meshVertexDeclaration> +`;s_.v.IncludesShadersStore.shadowMapVertexDeclaration=ln;let la=`layout(std140,column_major) uniform; +#include<sceneUboDeclaration> +#include<meshUboDeclaration> +`;s_.v.IncludesShadersStore.shadowMapUboDeclaration=la;let lo=`#if SM_NORMALBIAS==1 +uniform vec3 lightDataSM; +#endif +uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; +#if SM_USEDISTANCE==1 +varying vec3 vPositionWSM; +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying float zSM; +#endif +`;s_.v.IncludesShadersStore.shadowMapVertexExtraDeclaration=lo;let ll=`#if SM_NORMALBIAS==1 +#if SM_DIRECTIONINLIGHTDATA==1 +vec3 worldLightDirSM=normalize(-lightDataSM.xyz); +#else +vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); +#endif +float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; +#endif +`;s_.v.IncludesShadersStore.shadowMapVertexNormalBias=ll;let lh=`#if SM_USEDISTANCE==1 +vPositionWSM=worldPos.xyz; +#endif +#if SM_DEPTHTEXTURE==1 +#ifdef IS_NDC_HALF_ZRANGE +#define BIASFACTOR 0.5 +#else +#define BIASFACTOR 1.0 +#endif +#ifdef USE_REVERSE_DEPTHBUFFER +gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; +#else +gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; +#endif +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +zSM=gl_Position.z;gl_Position.z=0.0; +#elif SM_USEDISTANCE==0 +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#endif +`;s_.v.IncludesShadersStore.shadowMapVertexMetric=lh;let lu=`attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#endif +#include<helperFunctions> +#include<__decl__shadowMapVertex> +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#include<shadowMapVertexExtraDeclaration> +#include<clipPlaneVertexDeclaration> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normWorldSM=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vec3 vNormalW=normalize(normWorldSM*normalUpdated); +#endif +#endif +#include<shadowMapVertexNormalBias> +gl_Position=viewProjection*worldPos; +#include<shadowMapVertexMetric> +#ifdef ALPHATEXTURE +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#include<clipPlaneVertex> +}`;s_.v.ShadersStore.shadowMapVertexShader=lu;let lc=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) +for (int y=-OFFSET; y<=OFFSET; y++) +colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;s_.v.ShadersStore.depthBoxBlurPixelShader=lc;let ld=`#if SM_SOFTTRANSPARENTSHADOW==1 +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; +#endif +`;s_.v.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow=ld;let shadowGenerator_ShadowGenerator=class shadowGenerator_ShadowGenerator{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===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}if(e===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}if(e===shadowGenerator_ShadowGenerator.FILTER_PCF||e===shadowGenerator_ShadowGenerator.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===shadowGenerator_ShadowGenerator.FILTER_PCF||e===shadowGenerator_ShadowGenerator.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING}set usePoissonSampling(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_PCF}set usePercentageCloserFiltering(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_PCF);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCF)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.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===shadowGenerator_ShadowGenerator.FILTER_PCSS}set useContactHardeningShadow(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_PCSS);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCSS)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return shadowGenerator_ShadowGenerator.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(let t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;let i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(let t of e.getChildren())this.removeShadowCaster(t);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,r,s){this.onBeforeShadowMapRenderObservable=new rf.y$,this.onAfterShadowMapRenderObservable=new rf.y$,this.onBeforeShadowMapRenderMeshObservable=new rf.y$,this.onAfterShadowMapRenderMeshObservable=new rf.y$,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=shadowGenerator_ShadowGenerator.FILTER_NONE,this._filteringQuality=shadowGenerator_ShadowGenerator.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=rm.P.Zero(),this._viewMatrix=rm.y3.Zero(),this._projectionMatrix=rm.y3.Zero(),this._transformMatrix=rm.y3.Zero(),this._cachedPosition=new rm.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new rm.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=rm.y3.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=r?r:null,this._useRedTextureType=!!s;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),shadowGenerator_ShadowGenerator._SceneComponentInitialization(this._scene);let 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(){let e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new renderTargetTexture_RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new renderTargetTexture_RenderTargetTexture(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=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,r)=>this._renderForShadowMap(e,t,i,r),this._shadowMap.customIsReadyFunction=()=>!0;let 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===shadowGenerator_ShadowGenerator.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===shadowGenerator_ShadowGenerator.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){null===(t=e._debugPopGroup)||void 0===t||t.call(e,1);return}let r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))});let t=new rg.HE(0,0,0,0),i=new rg.HE(1,1,1,1);this._shadowMap.onClearObservable.add(e=>{this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let e=sT.$.MIN_RENDERINGGROUPS;e<sT.$.MAX_RENDERINGGROUPS;e++)this._shadowMap.setRenderingAutoClearDepthStencil(e,!1)}_initializeBlurRTTAndPostProcesses(){let e=this._scene.getEngine(),t=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new renderTargetTexture_RenderTargetTexture(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new BlurPostProcess(this._light.name+"KernelBlurX",new rm.FM(1,0),this.blurKernel,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=t,this._kernelBlurXPostprocess.height=t,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new BlurPostProcess(this._light.name+"KernelBlurY",new rm.FM(0,1),this.blurKernel,1,null,texture_Texture.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 postProcess_PostProcess(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,texture_Texture.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,r){let s;if(r.length)for(s=0;s<r.length;s++)this._renderSubMeshForShadowMap(r.data[s]);for(s=0;s<e.length;s++)this._renderSubMeshForShadowMap(e.data[s]);for(s=0;s<t.length;s++)this._renderSubMeshForShadowMap(t.data[s]);if(this._transparencyShadow)for(s=0;s<i.length;s++)this._renderSubMeshForShadowMap(i.data[s],!0);else for(s=0;s<i.length;s++)i.data[s].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}_bindCustomEffectForRenderSubMeshForShadowMap(e,t,i){t.setMatrix("viewProjection",this.getTransformMatrix())}_renderSubMeshForShadowMap(e,t=!1){var i,r;let s=e.getRenderingMesh(),n=e.getEffectiveMesh(),a=this._scene,o=a.getEngine(),l=e.getMaterial();if(n._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!l||0===e.verticesCount||e._renderId===a.getRenderId())return;let h=0>n._getWorldMatrixDeterminant(),u=null!==(i=s.overrideMaterialSideOrientation)&&void 0!==i?i:l.sideOrientation;h&&(u=0===u?1:0);let c=0===u;o.setState(l.backFaceCulling,void 0,void 0,c,l.cullBackFaces);let d=s._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;let p=o.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||s.hasThinInstances);if(!this.customAllowRendering||this.customAllowRendering(e)){if(this.isReady(e,p,t)){e._renderId=a.getRenderId();let i=l.shadowDepthWrapper,h=null!==(r=null==i?void 0:i.getEffect(e,this,o.currentRenderPassId))&&void 0!==r?r:e._getDrawWrapper(),u=sm.q.GetEffect(h);o.enableEffect(h),p||s._bind(e,u,l.fillMode),this.getTransformMatrix(),u.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?u.setVector3("lightDataSM",this._cachedDirection):u.setVector3("lightDataSM",this._cachedPosition);let c=this._getCamera();if(c&&u.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(c),this.getLight().getDepthMinZ(c)+this.getLight().getDepthMaxZ(c)),t&&this.enableSoftTransparentShadow&&u.setFloat("softTransparentShadowSM",n.visibility*l.alpha),i)e._setMainDrawWrapperOverride(h),i.standalone?i.baseMaterial.bindForSubMesh(n.getWorldMatrix(),s,e):l.bindForSubMesh(n.getWorldMatrix(),s,e),e._setMainDrawWrapperOverride(null);else{if(this._opacityTexture&&(u.setTexture("diffuseSampler",this._opacityTexture),u.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),s.useBones&&s.computeBonesUsingShaders&&s.skeleton){let e=s.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(s);if(!t)return;u.setTexture("boneSampler",t),u.setFloat("boneTextureWidth",4*(e.bones.length+1))}else u.setMatrices("mBones",e.getTransformMatrices(s))}so.G.BindMorphTargetParameters(s,u),s.morphTargetManager&&s.morphTargetManager.isUsingTextureForTargets&&s.morphTargetManager._bind(u),(0,nX.an)(u,l,a)}this._useUBO||i||this._bindCustomEffectForRenderSubMeshForShadowMap(e,u,n),so.G.BindSceneUniformBuffer(u,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();let _=n.getWorldMatrix();p&&(n.getMeshUniformBuffer().bindToEffect(u,"Mesh"),n.transferToEffect(_)),this.forceBackFacesOnly&&o.setState(!0,0,!1,!0,l.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(s),this.onBeforeShadowMapRenderObservable.notifyObservers(u),s._processRendering(n,e,u,l.fillMode,d,p,(e,t)=>{n===s||e?(n.getMeshUniformBuffer().bindToEffect(u,"Mesh"),n.transferToEffect(e?t:_)):(s.getMeshUniformBuffer().bindToEffect(u,"Mesh"),s.transferToEffect(t))}),this.forceBackFacesOnly&&o.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(u),this.onAfterShadowMapRenderMeshObservable.notifyObservers(s)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}}_applyFilterValues(){this._shadowMap&&(this.filter===shadowGenerator_ShadowGenerator.FILTER_NONE||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCSS?this._shadowMap.updateSamplingMode(texture_Texture.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){let i=Object.assign({useInstances:!1},t),r=this.getShadowMap();if(!r){e&&e(this);return}let s=r.renderList;if(!s){e&&e(this);return}let n=[];for(let e of s)n.push(...e.subMeshes);if(0===n.length){e&&e(this);return}let a=0,checkReady=()=>{var t,r;if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[a],i.useInstances,null!==(r=null===(t=n[a].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(n[a].getMesh()))&&void 0!==r&&r);)if(++a>=n.length){e&&e(this);return}setTimeout(checkReady,16)}};checkReady()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));let s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(rz.o.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var r;let s=e.getMaterial(),n=null==s?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;let a=[];if(this._prepareShadowDefines(e,t,a,i),n){if(!n.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{let i=e._getDrawWrapper(void 0,!0),n=i.effect,o=i.defines,l=[rz.o.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(rz.o.NormalKind)&&(l.push(rz.o.NormalKind),a.push("#define NORMAL"),h.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));let u=s.needAlphaTesting();if((u||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;let e=null!==(r=s.alphaCutOff)&&void 0!==r?r:shadowGenerator_ShadowGenerator.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),u&&a.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(rz.o.UVKind)&&(l.push(rz.o.UVKind),a.push("#define UV1")),h.isVerticesDataPresent(rz.o.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(l.push(rz.o.UV2Kind),a.push("#define UV2"))}let c=new EffectFallbacks;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(rz.o.MatricesIndicesKind),l.push(rz.o.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(rz.o.MatricesIndicesExtraKind),l.push(rz.o.MatricesWeightsExtraKind));let e=h.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");let d=h.morphTargetManager,p=0;if(d&&d.numInfluencers>0&&(a.push("#define MORPHTARGETS"),p=d.numInfluencers,a.push("#define NUM_MORPH_INFLUENCERS "+p),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),so.G.PrepareAttributesForMorphTargetsInfluencers(l,h,p)),(0,nX.lK)(s,this._scene,a),t&&(a.push("#define INSTANCES"),so.G.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(let e of this.customShaderOptions.defines)-1===a.indexOf(e)&&a.push(e);let _=a.join("\n");if(o!==_){o=_;let e="shadowMap",t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],r=["diffuseSampler","boneSampler","morphTargets"];if((0,nX.qx)(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(let e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(let e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(let e of this.customShaderOptions.samplers)-1===r.indexOf(e)&&r.push(e)}let s=this._scene.getEngine();n=s.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:["Scene","Mesh"],samplers:r,defines:_,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p}},s),i.setEffect(n,o)}if(!n.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){let i=this._scene,r=this._light;i.shadowsEnabled&&r.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let n=this.getShadowMap();n&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n.getSize().width,1/n.getSize().width,this.frustumEdgeFalloff,e)):this._filter===shadowGenerator_ShadowGenerator.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/n.getSize().width,this._contactHardeningLightSizeUVRatio*n.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/n.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e))}getTransformMatrix(){let 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),rm.P.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(rm.P.Dot(this._lightDirection,rm.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),rm.y3.LookAtLHToRef(t,t.add(this._lightDirection),rm.P.Up(),this._viewMatrix);let e=this.getShadowMap();if(e){let t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){let e=this._shadowMap;if(!e)return;let t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t)for(let e of(this._shadowMap.renderList||(this._shadowMap.renderList=[]),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(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){let e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){let[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;let 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 e=0;e<i.renderList.length;e++){let r=i.renderList[e];t.renderList.push(r.id)}return t}static Parse(e,t,i){let r=t.getLightById(e.lightId),s=void 0!==e.cameraId?t.getCameraById(e.cameraId):null,n=i?i(e.mapSize,r,s):new shadowGenerator_ShadowGenerator(e.mapSize,r,void 0,s),a=n.getShadowMap();for(let i=0;i<e.renderList.length;i++){let r=t.getMeshesById(e.renderList[i]);r.forEach(function(e){a&&(a.renderList||(a.renderList=[]),a.renderList.push(e))})}return void 0!==e.id&&(n.id=e.id),n.forceBackFacesOnly=!!e.forceBackFacesOnly,void 0!==e.darkness&&n.setDarkness(e.darkness),e.transparencyShadow&&n.setTransparencyShadow(!0),void 0!==e.frustumEdgeFalloff&&(n.frustumEdgeFalloff=e.frustumEdgeFalloff),void 0!==e.bias&&(n.bias=e.bias),void 0!==e.normalBias&&(n.normalBias=e.normalBias),e.usePercentageCloserFiltering?n.usePercentageCloserFiltering=!0:e.useContactHardeningShadow?n.useContactHardeningShadow=!0:e.usePoissonSampling?n.usePoissonSampling=!0:e.useExponentialShadowMap?n.useExponentialShadowMap=!0:e.useBlurExponentialShadowMap?n.useBlurExponentialShadowMap=!0:e.useCloseExponentialShadowMap?n.useCloseExponentialShadowMap=!0:e.useBlurCloseExponentialShadowMap?n.useBlurCloseExponentialShadowMap=!0:e.useVarianceShadowMap?n.useExponentialShadowMap=!0:e.useBlurVarianceShadowMap&&(n.useBlurExponentialShadowMap=!0),void 0!==e.contactHardeningLightSizeUVRatio&&(n.contactHardeningLightSizeUVRatio=e.contactHardeningLightSizeUVRatio),void 0!==e.filteringQuality&&(n.filteringQuality=e.filteringQuality),e.depthScale&&(n.depthScale=e.depthScale),e.blurScale&&(n.blurScale=e.blurScale),e.blurBoxOffset&&(n.blurBoxOffset=e.blurBoxOffset),e.useKernelBlur&&(n.useKernelBlur=e.useKernelBlur),e.blurKernel&&(n.blurKernel=e.blurKernel),n}};shadowGenerator_ShadowGenerator.CLASSNAME="ShadowGenerator",shadowGenerator_ShadowGenerator.FILTER_NONE=0,shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP=1,shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING=2,shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP=3,shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP=4,shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP=5,shadowGenerator_ShadowGenerator.FILTER_PCF=6,shadowGenerator_ShadowGenerator.FILTER_PCSS=7,shadowGenerator_ShadowGenerator.QUALITY_HIGH=0,shadowGenerator_ShadowGenerator.QUALITY_MEDIUM=1,shadowGenerator_ShadowGenerator.QUALITY_LOW=2,shadowGenerator_ShadowGenerator.DEFAULT_ALPHA_CUTOFF=.5,shadowGenerator_ShadowGenerator._SceneComponentInitialization=e=>{throw(0,r$.S)("ShadowGeneratorSceneComponent")};let lp=`#ifdef ALPHATEST +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include<clipPlaneFragmentDeclaration> +varying float vDepthMetric; +#ifdef PACKED +#include<packingFunctions> +#endif +#ifdef STORE_CAMERASPACE_Z +varying vec4 vViewPos; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include<clipPlaneFragment> +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +#ifdef STORE_CAMERASPACE_Z +#ifdef PACKED +gl_FragColor=pack(vViewPos.z); +#else +gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); +#endif +#else +#ifdef NONLINEARDEPTH +#ifdef PACKED +gl_FragColor=pack(gl_FragCoord.z); +#else +gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); +#endif +#else +#ifdef PACKED +gl_FragColor=pack(vDepthMetric); +#else +gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); +#endif +#endif +#endif +}`;s_.v.ShadersStore.depthPixelShader=lp;let l_=`attribute vec3 position; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<clipPlaneVertexDeclaration> +#include<instancesDeclaration> +uniform mat4 viewProjection;uniform vec2 depthValues; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#ifdef STORE_CAMERASPACE_Z +uniform mat4 view;varying vec4 vViewPos; +#endif +varying float vDepthMetric; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#include<clipPlaneVertex> +gl_Position=viewProjection*worldPos; +#ifdef STORE_CAMERASPACE_Z +vViewPos=view*worldPos; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); +#else +vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); +#endif +#endif +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +} +`;s_.v.ShadersStore.depthVertexShader=l_;let DepthRenderer=class DepthRenderer{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,s=texture_Texture.TRILINEAR_SAMPLINGMODE,n=!1,a){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new rg.HE(1,1,1,1):this.clearColor=new rg.HE(n?1e8:1,0,0,1),DepthRenderer._SceneComponentInitialization(this._scene);let o=e.getEngine();this._camera=i,s===texture_Texture.NEAREST_SAMPLINGMODE||(1!==t||o._caps.textureFloatLinearFiltering||(s=texture_Texture.NEAREST_SAMPLINGMODE),2!==t||o._caps.textureHalfFloatLinearFiltering||(s=texture_Texture.NEAREST_SAMPLINGMODE));let l=this.isPacked||!o._features.supportExtendedTextureFormats?5:6;this._depthMap=new renderTargetTexture_RenderTargetTexture(null!=a?a:"DepthRenderer",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,l),this._depthMap.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=texture_Texture.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=o._debugPushGroup)||void 0===e||e.call(o,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var e;null===(e=o._debugPopGroup)||void 0===e||e.call(o,1)}),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){let i=e.subMeshes[t],r=i.getRenderingMesh(),s=r._getInstancesRenderList(i._id,!!i.getReplacementMesh()),n=o.getCaps().instancedArrays&&(null!==s.visibleInstances[i._id]&&void 0!==s.visibleInstances[i._id]||r.hasThinInstances);if(!this.isReady(i,n))return!1}return!0};let renderSubMesh=e=>{var t,i;let r=e.getRenderingMesh(),s=e.getEffectiveMesh(),n=this._scene,a=n.getEngine(),o=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!o||s.infiniteDistance||o.disableDepthWrite||0===e.verticesCount||e._renderId===n.getRenderId())return;let l=0>s._getWorldMatrixDeterminant(),h=null!==(t=r.overrideMaterialSideOrientation)&&void 0!==t?t:o.sideOrientation;l&&(h=0===h?1:0);let u=0===h;a.setState(o.backFaceCulling,0,!1,u,this.reverseCulling?!o.cullBackFaces:o.cullBackFaces);let c=r._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(c.mustReturn)return;let d=a.getCaps().instancedArrays&&(null!==c.visibleInstances[e._id]&&void 0!==c.visibleInstances[e._id]||r.hasThinInstances),p=this._camera||n.activeCamera;if(this.isReady(e,d)&&p){let t,l;e._renderId=n.getRenderId();let h=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[a.currentRenderPassId],u=e._getDrawWrapper();!u&&h&&(u=h._getDrawWrapper());let _=p.mode===rj.V.ORTHOGRAPHIC_CAMERA;if(!u)return;let f=u.effect;if(a.enableEffect(u),d||r._bind(e,f,o.fillMode),h?h.bindForSubMesh(s.getWorldMatrix(),s,e):(f.setMatrix("viewProjection",n.getTransformMatrix()),f.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&f.setMatrix("view",n.getViewMatrix())),_?(t=!a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1,l=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1):(t=a.useReverseDepthBuffer&&a.isNDCHalfZRange?p.minZ:a.isNDCHalfZRange?0:p.minZ,l=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:p.maxZ),f.setFloat2("depthValues",t,t+l),!h){if(o.needAlphaTesting()){let e=o.getAlphaTestTexture();e&&(f.setTexture("diffuseSampler",e),f.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){let e=r.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(r);if(!t)return;f.setTexture("boneSampler",t),f.setFloat("boneTextureWidth",4*(e.bones.length+1))}else f.setMatrices("mBones",e.getTransformMatrices(r))}(0,nX.an)(f,o,n),so.G.BindMorphTargetParameters(r,f),r.morphTargetManager&&r.morphTargetManager.isUsingTextureForTargets&&r.morphTargetManager._bind(f)}r._processRendering(s,e,f,o.fillMode,c,d,(e,t)=>f.setMatrix("world",t))}};this._depthMap.customRenderFunction=(e,t,i,r)=>{let s;if(r.length)for(s=0;s<r.length;s++)renderSubMesh(r.data[s]);for(s=0;s<e.length;s++)renderSubMesh(e.data[s]);for(s=0;s<t.length;s++)renderSubMesh(t.data[s]);if(this.forceDepthWriteTransparentMeshes)for(s=0;s<i.length;s++)renderSubMesh(i.data[s]);else for(s=0;s<i.length;s++)i.data[s].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}}isReady(e,t){var i;let r=this._scene.getEngine(),s=e.getMesh(),n=s.getScene(),a=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[r.currentRenderPassId];if(a)return a.isReadyForSubMesh(s,e,t);let o=e.getMaterial();if(!o||o.disableDepthWrite)return!1;let l=[],h=[rz.o.PositionKind];if(o&&o.needAlphaTesting()&&o.getAlphaTestTexture()&&(l.push("#define ALPHATEST"),s.isVerticesDataPresent(rz.o.UVKind)&&(h.push(rz.o.UVKind),l.push("#define UV1")),s.isVerticesDataPresent(rz.o.UV2Kind)&&(h.push(rz.o.UV2Kind),l.push("#define UV2"))),s.useBones&&s.computeBonesUsingShaders){h.push(rz.o.MatricesIndicesKind),h.push(rz.o.MatricesWeightsKind),s.numBoneInfluencers>4&&(h.push(rz.o.MatricesIndicesExtraKind),h.push(rz.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));let t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");let u=s.morphTargetManager,c=0;u&&u.numInfluencers>0&&(c=u.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+c),u.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),so.G.PrepareAttributesForMorphTargetsInfluencers(h,s,c)),t&&(l.push("#define INSTANCES"),so.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,nX.lK)(o,n,l);let d=e._getDrawWrapper(void 0,!0),p=d.defines,_=l.join("\n");if(p!==_){let e=["world","mBones","boneTextureWidth","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,nX.qx)(e),d.setEffect(r.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),_)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){let e=[];for(let t in this._scene._depthRenderer){let i=this._scene._depthRenderer[t];i===this&&e.push(t)}if(e.length>0)for(let t of(this._depthMap.dispose(),e))delete this._scene._depthRenderer[t]}};DepthRenderer._SceneComponentInitialization=e=>{throw(0,r$.S)("DepthRendererSceneComponent")};let lf=`varying vec2 vUV;uniform sampler2D textureSampler; +#if defined(INITIAL) +uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); +#ifdef DEPTH_REDUX +float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); +#else +float maxz=max(max(max(f1,f2),f3),f4); +#endif +glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(MAIN) +uniform vec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(ONEBEFORELAST) +uniform ivec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(LAST) +void main(void) +{glFragColor=vec4(0.);if (true) { +discard;}} +#endif +`;s_.v.ShadersStore.minmaxReduxPixelShader=lf;let MinMaxReducer=class MinMaxReducer{constructor(e){this.onAfterReductionPerformed=new rf.y$,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new sx.O(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){var s,n,a,o;if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;let l=this._camera.getScene(),h=new postProcess_PostProcess("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,l.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);h.autoClear=!1,h.forceFullscreenViewport=r;let u=this._sourceTexture.getRenderWidth(),c=this._sourceTexture.getRenderHeight();h.onApply=(s=u,n=c,e=>{e.setTexture("sourceTexture",this._sourceTexture),e.setFloat2("texSize",s,n)}),this._reductionSteps.push(h);let d=1;for(;u>1||c>1;){u=Math.max(Math.round(u/2),1),c=Math.max(Math.round(c/2),1);let e=new postProcess_PostProcess("Reduction phase "+d,"minmaxRedux",["texSize"],null,{width:u,height:c},null,1,l.getEngine(),!1,"#define "+(1==u&&1==c?"LAST":1==u||1==c?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=r,e.onApply=(a=u,o=c,e=>{1==a||1==o?e.setInt2("texSize",a,o):e.setFloat2("texSize",a,o)}),this._reductionSteps.push(e),d++,1==u&&1==c){let func=(e,t,i)=>{let r=new Float32Array(4*e*t),s={min:0,max:0};return()=>{l.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,r,!1),s.min=r[0],s.max=r[1],this.onAfterReductionPerformed.notifyObservers(s)}};e.onAfterRenderObservable.add(func(u,c,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;let 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;e<this._reductionSteps.length;++e)this._reductionSteps[e].dispose();this._reductionSteps=null}this._postProcessManager&&e&&this._postProcessManager.dispose(),this._sourceTexture=null}};let DepthReducer=class DepthReducer extends MinMaxReducer{get depthRenderer(){return this._depthRenderer}constructor(e){super(e)}setDepthRenderer(e=null,t=2,i=!0){let r=this._camera.getScene();this._depthRenderer&&(delete r._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),null===e&&(r._depthRenderer||(r._depthRenderer={}),(e=this._depthRenderer=new DepthRenderer(r,t,this._camera,!1,1)).enabled=!1,this._depthRendererId="minmax"+this._camera.id,r._depthRenderer[this._depthRendererId]=e),super.setSourceTexture(e.getDepthMap(),!0,t,i)}setSourceTexture(e,t,i=2,r=!0){super.setSourceTexture(e,t,i,r)}activate(){this._depthRenderer&&(this._depthRenderer.enabled=!0),super.activate()}deactivate(){super.deactivate(),this._depthRenderer&&(this._depthRenderer.enabled=!1)}dispose(e=!0){if(super.dispose(e),this._depthRenderer&&e){let e=this._depthRenderer.getDepthMap().getScene();e&&delete e._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null}}};let lm=rm.P.Up(),lg=rm.P.Zero(),lv=new rm.P,lx=new rm.P,lT=new rm.y3;let CascadedShadowGenerator=class CascadedShadowGenerator extends shadowGenerator_ShadowGenerator{_validateFilter(e){return e===shadowGenerator_ShadowGenerator.FILTER_NONE||e===shadowGenerator_ShadowGenerator.FILTER_PCF||e===shadowGenerator_ShadowGenerator.FILTER_PCSS?e:(console.error('Unsupported filter "'+e+'"!'),shadowGenerator_ShadowGenerator.FILTER_NONE)}get numCascades(){return this._numCascades}set numCascades(e){(e=Math.min(Math.max(e,CascadedShadowGenerator.MIN_CASCADES_COUNT),CascadedShadowGenerator.MAX_CASCADES_COUNT))!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())}get freezeShadowCastersBoundingInfo(){return this._freezeShadowCastersBoundingInfo}set freezeShadowCastersBoundingInfo(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._freezeShadowCastersBoundingInfoObservable||e||(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(()=>this._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){let e=this._shadowMap.renderList;for(let t=0;t<e.length;t++){let i=e[t];if(!i)continue;let r=i.getBoundingInfo(),s=r.boundingBox;this._scbiMin.minimizeInPlace(s.minimumWorld),this._scbiMax.maximizeInPlace(s.maximumWorld)}let t=this._scene.meshes;for(let e=0;e<t.length;e++){let i=t[e];if(!i||!i.isVisible||!i.isEnabled||!i.receiveShadows)continue;let r=i.getBoundingInfo(),s=r.boundingBox;this._scbiMin.minimizeInPlace(s.minimumWorld),this._scbiMax.maximizeInPlace(s.maximumWorld)}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)}get shadowCastersBoundingInfo(){return this._shadowCastersBoundingInfo}set shadowCastersBoundingInfo(e){this._shadowCastersBoundingInfo=e}setMinMaxDistance(e,t){(this._minDistance!==e||this._maxDistance!==t)&&(e>t&&(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 CascadedShadowGenerator.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null}getCascadeMaxExtents(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null}get shadowMaxZ(){return this._getCamera()?this._shadowMaxZ:0}set shadowMaxZ(e){let t=this._getCamera();if(!t){this._shadowMaxZ=e;return}this._shadowMaxZ===e||e<t.minZ||e>t.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){let t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null}getCascadeProjectionMatrix(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null}getCascadeTransformMatrix(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null}setDepthRenderer(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)}get autoCalcDepthBounds(){return this._autoCalcDepthBounds}set autoCalcDepthBounds(e){let t=this._getCamera();if(t){if(this._autoCalcDepthBounds=e,!e){this._depthReducer&&this._depthReducer.deactivate(),this.setMinMaxDistance(0,1);return}this._depthReducer||(this._depthReducer=new DepthReducer(t),this._depthReducer.onAfterReductionPerformed.add(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(){let e=this._getCamera();if(!e)return;let t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,n=this._shadowMaxZ<i&&this._shadowMaxZ>=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,a=t+s*r,o=t+n*r,l=o-a,h=o/a;for(let e=0;e<this._cascades.length;++e){let i=(e+1)/this._numCascades,n=a*h**i,o=a+l*i,u=this._lambda*(n-o)+o;this._cascades[e].prevBreakDistance=0===e?s:this._cascades[e-1].breakDistance,this._cascades[e].breakDistance=(u-t)/r,this._viewSpaceFrustumsZ[e]=u,this._frustumLengths[e]=(this._cascades[e].breakDistance-this._cascades[e].prevBreakDistance)*r}this._breaksAreDirty=!1}_computeMatrices(){let e=this._scene,t=this._getCamera();if(!t)return;rm.P.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),1===Math.abs(rm.P.Dot(this._lightDirection,rm.P.Up()))&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);let i=e.getEngine().useReverseDepthBuffer;for(let t=0;t<this._numCascades;++t){this._computeFrustumInWorldSpace(t),this._computeCascadeFrustum(t),this._cascadeMaxExtents[t].subtractToRef(this._cascadeMinExtents[t],lv),this._frustumCenter[t].addToRef(this._lightDirection.scale(this._cascadeMinExtents[t].z),this._shadowCameraPos[t]),rm.y3.LookAtLHToRef(this._shadowCameraPos[t],this._frustumCenter[t],lm,this._viewMatrices[t]);let r=0,s=lv.z,n=this._shadowCastersBoundingInfo;n.update(this._viewMatrices[t]),s=Math.min(s,n.boundingBox.maximumWorld.z),r=this._depthClamp&&this.filter!==shadowGenerator_ShadowGenerator.FILTER_PCSS?Math.max(r,n.boundingBox.minimumWorld.z):Math.min(r,n.boundingBox.minimumWorld.z),rm.y3.OrthoOffCenterLHToRef(this._cascadeMinExtents[t].x,this._cascadeMaxExtents[t].x,this._cascadeMinExtents[t].y,this._cascadeMaxExtents[t].y,i?s:r,i?r:s,this._projectionMatrices[t],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[t].z=r,this._cascadeMaxExtents[t].z=s,this._viewMatrices[t].multiplyToRef(this._projectionMatrices[t],this._transformMatrices[t]),rm.P.TransformCoordinatesToRef(lg,this._transformMatrices[t],lv),lv.scaleInPlace(this._mapSize/2),lx.copyFromFloats(Math.round(lv.x),Math.round(lv.y),Math.round(lv.z)),lx.subtractInPlace(lv).scaleInPlace(2/this._mapSize),rm.y3.TranslationToRef(lx.x,lx.y,0,lT),this._projectionMatrices[t].multiplyToRef(lT,this._projectionMatrices[t]),this._viewMatrices[t].multiplyToRef(this._projectionMatrices[t],this._transformMatrices[t]),this._transformMatrices[t].copyToArray(this._transformMatricesAsArray,16*t)}}_computeFrustumInWorldSpace(e){let t=this._getCamera();if(!t)return;let i=this._cascades[e].prevBreakDistance,r=this._cascades[e].breakDistance,s=this._scene.getEngine().isNDCHalfZRange;t.getViewMatrix();let n=0===t.maxZ,a=t.maxZ;n&&(t.maxZ=this._shadowMaxZ,t.getProjectionMatrix(!0));let o=rm.y3.Invert(t.getTransformationMatrix());n&&(t.maxZ=a,t.getProjectionMatrix(!0));let l=this._scene.getEngine().useReverseDepthBuffer?4:0;for(let t=0;t<CascadedShadowGenerator._FrustumCornersNDCSpace.length;++t)lv.copyFrom(CascadedShadowGenerator._FrustumCornersNDCSpace[(t+l)%CascadedShadowGenerator._FrustumCornersNDCSpace.length]),s&&-1===lv.z&&(lv.z=0),rm.P.TransformCoordinatesToRef(lv,o,this._frustumCornersWorldSpace[e][t]);for(let t=0;t<CascadedShadowGenerator._FrustumCornersNDCSpace.length/2;++t)lv.copyFrom(this._frustumCornersWorldSpace[e][t+4]).subtractInPlace(this._frustumCornersWorldSpace[e][t]),lx.copyFrom(lv).scaleInPlace(i),lv.scaleInPlace(r),lv.addInPlace(this._frustumCornersWorldSpace[e][t]),this._frustumCornersWorldSpace[e][t+4].copyFrom(lv),this._frustumCornersWorldSpace[e][t].addInPlace(lx)}_computeCascadeFrustum(e){this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0);let t=this._getCamera();if(t){for(let t=0;t<this._frustumCornersWorldSpace[e].length;++t)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][t]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){let t=0;for(let i=0;i<this._frustumCornersWorldSpace[e].length;++i){let r=this._frustumCornersWorldSpace[e][i].subtractToRef(this._frustumCenter[e],lv).length();t=Math.max(t,r)}t=Math.ceil(16*t)/16,this._cascadeMaxExtents[e].copyFromFloats(t,t,t),this._cascadeMinExtents[e].copyFromFloats(-t,-t,-t)}else{let t=this._frustumCenter[e];this._frustumCenter[e].addToRef(this._lightDirection,lv),rm.y3.LookAtLHToRef(t,lv,lm,lT);for(let t=0;t<this._frustumCornersWorldSpace[e].length;++t)rm.P.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][t],lT,lv),this._cascadeMinExtents[e].minimizeInPlace(lv),this._cascadeMaxExtents[e].maximizeInPlace(lv)}}}_recreateSceneUBOs(){if(this._disposeSceneUBOs(),this._sceneUBOs)for(let e=0;e<this._numCascades;++e)this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${e})`))}static get IsSupported(){let e=rS.l.LastCreatedEngine;return!!e&&e._features.supportCSM}constructor(e,t,i,r,s=!0){if(!CascadedShadowGenerator.IsSupported){rT.Y.Error("CascadedShadowMap is not supported by the current engine.");return}super(e,t,i,r,s),this.usePercentageCloserFiltering=!0}_initializeGenerator(){var e,t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x;this.penumbraDarkness=null!==(e=this.penumbraDarkness)&&void 0!==e?e:1,this._numCascades=null!==(t=this._numCascades)&&void 0!==t?t:CascadedShadowGenerator.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=null!==(i=this.stabilizeCascades)&&void 0!==i&&i,this._freezeShadowCastersBoundingInfoObservable=null!==(r=this._freezeShadowCastersBoundingInfoObservable)&&void 0!==r?r:null,this.freezeShadowCastersBoundingInfo=null!==(s=this.freezeShadowCastersBoundingInfo)&&void 0!==s&&s,this._scbiMin=null!==(n=this._scbiMin)&&void 0!==n?n:new rm.P(0,0,0),this._scbiMax=null!==(a=this._scbiMax)&&void 0!==a?a:new rm.P(0,0,0),this._shadowCastersBoundingInfo=null!==(o=this._shadowCastersBoundingInfo)&&void 0!==o?o:new nQ.j(new rm.P(0,0,0),new rm.P(0,0,0)),this._breaksAreDirty=null===(l=this._breaksAreDirty)||void 0===l||l,this._minDistance=null!==(h=this._minDistance)&&void 0!==h?h:0,this._maxDistance=null!==(u=this._maxDistance)&&void 0!==u?u:1,this._currentLayer=null!==(c=this._currentLayer)&&void 0!==c?c:0,this._shadowMaxZ=null!==(_=null!==(d=this._shadowMaxZ)&&void 0!==d?d:null===(p=this._getCamera())||void 0===p?void 0:p.maxZ)&&void 0!==_?_:1e4,this._debug=null!==(f=this._debug)&&void 0!==f&&f,this._depthClamp=null===(m=this._depthClamp)||void 0===m||m,this._cascadeBlendPercentage=null!==(g=this._cascadeBlendPercentage)&&void 0!==g?g:.1,this._lambda=null!==(v=this._lambda)&&void 0!==v?v:.5,this._autoCalcDepthBounds=null!==(x=this._autoCalcDepthBounds)&&void 0!==x&&x,this._recreateSceneUBOs(),super._initializeGenerator()}_createTargetRenderTexture(){let e=this._scene.getEngine(),t={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new renderTargetTexture_RenderTargetTexture(this._light.name+"_CSMShadowMap",t,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(super._initializeShadowMap(),null===this._shadowMap)return;this._transformMatricesAsArray=new Float32Array(16*this._numCascades),this._viewSpaceFrustumsZ=Array(this._numCascades),this._frustumLengths=Array(this._numCascades),this._lightSizeUVCorrection=Array(2*this._numCascades),this._depthCorrection=Array(this._numCascades),this._cascades=[],this._viewMatrices=[],this._projectionMatrices=[],this._transformMatrices=[],this._cascadeMinExtents=[],this._cascadeMaxExtents=[],this._frustumCenter=[],this._shadowCameraPos=[],this._frustumCornersWorldSpace=[];for(let e=0;e<this._numCascades;++e){this._cascades[e]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[e]=rm.y3.Zero(),this._projectionMatrices[e]=rm.y3.Zero(),this._transformMatrices[e]=rm.y3.Zero(),this._cascadeMinExtents[e]=new rm.P,this._cascadeMaxExtents[e]=new rm.P,this._frustumCenter[e]=new rm.P,this._shadowCameraPos[e]=new rm.P,this._frustumCornersWorldSpace[e]=Array(CascadedShadowGenerator._FrustumCornersNDCSpace.length);for(let t=0;t<CascadedShadowGenerator._FrustumCornersNDCSpace.length;++t)this._frustumCornersWorldSpace[e][t]=new rm.P}let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.clear(),this._shadowMap.onBeforeRenderObservable.clear(),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===shadowGenerator_ShadowGenerator.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!==shadowGenerator_ShadowGenerator.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);let i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;let s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let n=this.getShadowMap();if(!n)return;let a=n.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===shadowGenerator_ShadowGenerator.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a,1/a,this.frustumEdgeFalloff,e);else if(this._filter===shadowGenerator_ShadowGenerator.FILTER_PCSS){for(let e=0;e<this._numCascades;++e)this._lightSizeUVCorrection[2*e+0]=0===e?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[e].x-this._cascadeMinExtents[e].x),this._lightSizeUVCorrection[2*e+1]=0===e?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[e].y-this._cascadeMinExtents[e].y),this._depthCorrection[e]=0===e?1:(this._cascadeMaxExtents[e].z-this._cascadeMinExtents[e].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);t.setDepthStencilTexture("shadowSampler"+e,n),t.setTexture("depthSampler"+e,n),t.setArray2("lightSizeUVCorrection"+e,this._lightSizeUVCorrection),t.setArray("depthCorrection"+e,this._depthCorrection),t.setFloat("penumbraDarkness"+e,this.penumbraDarkness),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a,this._contactHardeningLightSizeUVRatio*a,this.frustumEdgeFalloff,e)}else t.setTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a,1/a,this.frustumEdgeFalloff,e);i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}getTransformMatrix(){return this.getCascadeTransformMatrix(0)}dispose(){super.dispose(),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)}serialize(){let e=super.serialize(),t=this.getShadowMap();if(!t)return e;if(e.numCascades=this._numCascades,e.debug=this._debug,e.stabilizeCascades=this.stabilizeCascades,e.lambda=this._lambda,e.cascadeBlendPercentage=this.cascadeBlendPercentage,e.depthClamp=this._depthClamp,e.autoCalcDepthBounds=this.autoCalcDepthBounds,e.shadowMaxZ=this._shadowMaxZ,e.penumbraDarkness=this.penumbraDarkness,e.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,e.minDistance=this.minDistance,e.maxDistance=this.maxDistance,e.renderList=[],t.renderList)for(let i=0;i<t.renderList.length;i++){let r=t.renderList[i];e.renderList.push(r.id)}return e}static Parse(e,t){let i=shadowGenerator_ShadowGenerator.Parse(e,t,(e,t,i)=>new CascadedShadowGenerator(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}};CascadedShadowGenerator._FrustumCornersNDCSpace=[new rm.P(-1,1,-1),new rm.P(1,1,-1),new rm.P(1,-1,-1),new rm.P(-1,-1,-1),new rm.P(-1,1,1),new rm.P(1,1,1),new rm.P(1,-1,1),new rm.P(-1,-1,1)],CascadedShadowGenerator.CLASSNAME="CascadedShadowGenerator",CascadedShadowGenerator.DEFAULT_CASCADES_COUNT=4,CascadedShadowGenerator.MIN_CASCADES_COUNT=2,CascadedShadowGenerator.MAX_CASCADES_COUNT=4,CascadedShadowGenerator._SceneComponentInitialization=e=>{throw(0,r$.S)("ShadowGeneratorSceneComponent")},rp.p.AddParser(rQ.l.NAME_SHADOWGENERATOR,(e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,r=e.shadowGenerators.length;i<r;i++){let r=e.shadowGenerators[i];r.className===CascadedShadowGenerator.CLASSNAME?CascadedShadowGenerator.Parse(r,t):shadowGenerator_ShadowGenerator.Parse(r,t)}});let ShadowGeneratorSceneComponent=class ShadowGeneratorSceneComponent{constructor(e){this.name=rQ.l.NAME_SHADOWGENERATOR,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(rQ.l.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)}rebuild(){}serialize(e){e.shadowGenerators=[];let t=this.scene.lights;for(let i of t){let t=i.getShadowGenerators();if(t){let i=t.values();for(let t=i.next();!0!==t.done;t=i.next()){let i=t.value;e.shadowGenerators.push(i.serialize())}}}}addFromContainer(e){}removeFromContainer(e,t){}dispose(){}_gatherRenderTargets(e){let t=this.scene;if(this.scene.shadowsEnabled)for(let i=0;i<t.lights.length;i++){let r=t.lights[i],s=r.getShadowGenerators();if(r.isEnabled()&&r.shadowEnabled&&s){let i=s.values();for(let r=i.next();!0!==r.done;r=i.next()){let i=r.value,s=i.getShadowMap();-1!==t.textures.indexOf(s)&&e.push(s)}}}}};shadowGenerator_ShadowGenerator._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_SHADOWGENERATOR);t||(t=new ShadowGeneratorSceneComponent(e),e._addComponent(t))},ry.N.AddNodeConstructor("Light_Type_0",(e,t)=>()=>new PointLight(e,rm.P.Zero(),t));let PointLight=class PointLight extends ShadowLight{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){let t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){let e=t.value;e.recreateShadowMap()}}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return light_Light.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new rm.P(1,0,0);case 1:return new rm.P(-1,0,0);case 2:return new rm.P(0,-1,0);case 3:return new rm.P(0,1,0);case 4:return new rm.P(0,0,1);case 5:return new rm.P(0,0,-1)}return rm.P.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;let s=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;rm.y3.PerspectiveFovLHToRef(this.shadowAngle,1,a?n:s,a?s:n,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,rH.gn)([(0,rb.qC)()],PointLight.prototype,"shadowAngle",null);let DefaultLoadingScreen=class DefaultLoadingScreen{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{let 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";let e=`@-webkit-keyframes spin1 {\ + 0% { -webkit-transform: rotate(0deg);} + 100% { -webkit-transform: rotate(360deg);} + }\ + @keyframes spin1 {\ + 0% { transform: rotate(0deg);} + 100% { transform: rotate(360deg);} + }`;this._style.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(this._style);let t=!!window.SVGSVGElement,i=new Image;DefaultLoadingScreen.DefaultLogoUrl?i.src=DefaultLoadingScreen.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";let r=document.createElement("div");r.style.width="300px",r.style.gridColumn="1",r.style.gridRow="1",r.style.top="50%",r.style.left="50%",r.style.transform="translate(-50%, -50%)",r.style.position="absolute";let s=new Image;if(DefaultLoadingScreen.DefaultSpinnerUrl?s.src=DefaultLoadingScreen.DefaultSpinnerUrl:s.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!t){let e={w:16,h:18.5},t={w:30,h:30};i.style.width=`${e.w}vh`,i.style.height=`${e.h}vh`,i.style.left=`calc(50% - ${e.w/2}vh)`,i.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${t.w}vh`,s.style.height=`${t.h}vh`,s.style.left=`calc(50% - ${t.w/2}vh)`,s.style.top=`calc(50% - ${t.h/2}vh)`}r.appendChild(s),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)}))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}};DefaultLoadingScreen.DefaultLogoUrl="",DefaultLoadingScreen.DefaultSpinnerUrl="",rq.D.DefaultLoadingScreenFactory=e=>new DefaultLoadingScreen(e);var lS=i(1687),lC=i(5461);let PanoramaToCubeMapTools=class PanoramaToCubeMapTools{static ConvertPanoramaToCubemap(e,t,i,r,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";let n=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s),a=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s),o=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s),l=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s),h=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s),u=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s);return{front:n,back:a,left:o,right:l,up:h,down:u,size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,n=!1){let a=new ArrayBuffer(e*e*12),o=new Float32Array(a),l=n?Math.max(1,Math.round(r/4/e)):1,h=1/l,u=h*h,c=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),p=1/e,_=0;for(let n=0;n<e;n++)for(let a=0;a<l;a++){let a=t[0],f=t[2];for(let t=0;t<e;t++)for(let h=0;h<l;h++){let l=f.subtract(a).scale(_).add(a);l.normalize();let h=this.CalcProjectionSpherical(l,i,r,s);o[n*e*3+3*t+0]+=h.r*u,o[n*e*3+3*t+1]+=h.g*u,o[n*e*3+3*t+2]+=h.b*u,a=a.add(c),f=f.add(d)}_+=p*h}return o}static CalcProjectionSpherical(e,t,i,r){let s=Math.atan2(e.z,e.x),n=Math.acos(e.y);for(;s<-Math.PI;)s+=2*Math.PI;for(;s>Math.PI;)s-=2*Math.PI;let a=s/Math.PI,o=Math.round((a=.5*a+.5)*i);o<0?o=0:o>=i&&(o=i-1);let l=Math.round(n/Math.PI*r);l<0?l=0:l>=r&&(l=r-1);let h=r-l-1,u=t[h*i*3+3*o+0],c=t[h*i*3+3*o+1],d=t[h*i*3+3*o+2];return{r:u,g:c,b:d}}};PanoramaToCubeMapTools.FACE_LEFT=[new rm.P(-1,-1,-1),new rm.P(1,-1,-1),new rm.P(-1,1,-1),new rm.P(1,1,-1)],PanoramaToCubeMapTools.FACE_RIGHT=[new rm.P(1,-1,1),new rm.P(-1,-1,1),new rm.P(1,1,1),new rm.P(-1,1,1)],PanoramaToCubeMapTools.FACE_FRONT=[new rm.P(1,-1,-1),new rm.P(1,-1,1),new rm.P(1,1,-1),new rm.P(1,1,1)],PanoramaToCubeMapTools.FACE_BACK=[new rm.P(-1,-1,1),new rm.P(-1,-1,-1),new rm.P(-1,1,1),new rm.P(-1,1,-1)],PanoramaToCubeMapTools.FACE_DOWN=[new rm.P(1,1,-1),new rm.P(1,1,1),new rm.P(-1,1,-1),new rm.P(-1,1,1)],PanoramaToCubeMapTools.FACE_UP=[new rm.P(-1,-1,-1),new rm.P(-1,-1,1),new rm.P(1,-1,-1),new rm.P(1,-1,1)];let HDRTools=class HDRTools{static _Ldexp(e,t){return t>1023?898846567431158e293*e*Math.pow(2,t-1023):t<-1074?5e-324*e*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,r,s,n){s>0?(s=this._Ldexp(1,s-136),e[n+0]=t*s,e[n+1]=i*s,e[n+2]=r*s):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",r="";for(let s=t;s<e.length-t&&"\n"!=(r=String.fromCharCode(e[s]));s++)i+=r;return i}static RGBE_ReadHeader(e){let t=0,i=0,r=this._ReadStringLine(e,0);if("#"!=r[0]||"?"!=r[1])throw"Bad HDR Format.";let s=!1,n=!1,a=0;do a+=r.length+1,"FORMAT=32-bit_rle_rgbe"==(r=this._ReadStringLine(e,a))?n=!0:0==r.length&&(s=!0);while(!s);if(!n)throw"HDR Bad header format, unsupported FORMAT";a+=r.length+1,r=this._ReadStringLine(e,a);let o=/^-Y (.*) \+X (.*)$/g.exec(r);if(!o||o.length<3)throw"HDR Bad header format, no size";if(i=parseInt(o[2]),t=parseInt(o[1]),i<8||i>32767)throw"HDR Bad header format, unsupported size";return{height:t,width:i,dataPosition:a+=r.length+1}}static GetCubeMapTextureData(e,t,i=!1){let r=new Uint8Array(e),s=this.RGBE_ReadHeader(r),n=this.RGBE_ReadPixels(r,s),a=PanoramaToCubeMapTools.ConvertPanoramaToCubemap(n,s.width,s.height,t,i);return a}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i,r,s,n,a,o=t.height,l=t.width,h=t.dataPosition,u=0,c=0,d=0,p=new ArrayBuffer(4*l),_=new Uint8Array(p),f=new ArrayBuffer(t.width*t.height*12),m=new Float32Array(f);for(;o>0;){if(i=e[h++],r=e[h++],s=e[h++],n=e[h++],2!=i||2!=r||128&s||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((s<<8|n)!=l)throw"HDR Bad header format, wrong scan line width";for(d=0,u=0;d<4;d++)for(c=(d+1)*l;u<c;)if(i=e[h++],r=e[h++],i>128){if(0==(a=i-128)||a>c-u)throw"HDR Bad Format, bad scanline data (run)";for(;a-- >0;)_[u++]=r}else{if(0==(a=i)||a>c-u)throw"HDR Bad Format, bad scanline data (non-run)";if(_[u++]=r,--a>0)for(let t=0;t<a;t++)_[u++]=e[h++]}for(d=0;d<l;d++)i=_[d],r=_[d+l],s=_[d+2*l],n=_[d+3*l],this._Rgbe2float(m,i,r,s,n,(t.height-o)*l*3+3*d);o--}return m}static _RGBEReadPixelsNOTRLE(e,t){let i,r,s,n,a,o=t.height,l=t.width,h=t.dataPosition,u=new ArrayBuffer(t.width*t.height*12),c=new Float32Array(u);for(;o>0;){for(a=0;a<t.width;a++)i=e[h++],r=e[h++],s=e[h++],n=e[h++],this._Rgbe2float(c,i,r,s,n,(t.height-o)*l*3+3*a);o--}return c}};let lE=`attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +mat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.hdrFilteringVertexShader=lE;let lb=`#include<helperFunctions> +#include<importanceSampling> +#include<pbrBRDFFunctions> +#include<hdrFilteringFunctions> +uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`;s_.v.ShadersStore.hdrFilteringPixelShader=lb;let HDRFiltering=class HDRFiltering{constructor(e,t={}){this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}_createRenderTarget(e){let t=0;this._engine.getCaps().textureHalfFloatRender?t=2:this._engine.getCaps().textureFloatRender&&(t=1);let i=this._engine.createRenderTargetCubeTexture(e,{format:5,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(i.texture,0,0,0),this._engine.updateTextureSamplingMode(3,i.texture,!0),i}_prefilterInternal(e){let t=e.getSize().width,i=rE.R.ILog2(t)+1,r=this._effectWrapper.effect,s=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();let n=e.getInternalTexture();n&&this._engine.updateTextureSamplingMode(3,n,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let a=[[new rm.P(0,0,-1),new rm.P(0,-1,0),new rm.P(1,0,0)],[new rm.P(0,0,1),new rm.P(0,-1,0),new rm.P(-1,0,0)],[new rm.P(1,0,0),new rm.P(0,0,1),new rm.P(0,1,0)],[new rm.P(1,0,0),new rm.P(0,0,-1),new rm.P(0,-1,0)],[new rm.P(1,0,0),new rm.P(0,-1,0),new rm.P(0,0,1)],[new rm.P(-1,0,0),new rm.P(0,-1,0),new rm.P(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let e=0;e<6;e++){r.setVector3("up",a[e][0]),r.setVector3("right",a[e][1]),r.setVector3("front",a[e][2]);for(let n=0;n<i;n++){this._engine.bindFramebuffer(s,e,void 0,void 0,!0,n),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let i=Math.pow(2,(n-this._lodGenerationOffset)/this._lodGenerationScale)/t;0===n&&(i=0),r.setFloat("alphaG",i),this._effectRenderer.draw()}}this._effectRenderer.restoreStates(),this._engine.restoreDefaultFramebuffer(),this._engine._releaseTexture(e._texture);let o=s.texture.type,l=s.texture.format;return s._swapAndDie(e._texture),e._texture.type=o,e._texture.format=l,e.gammaSpace=!1,e.lodGenerationOffset=this._lodGenerationOffset,e.lodGenerationScale=this._lodGenerationScale,e._prefiltered=!0,e}_createEffect(e,t){let i=[];e.gammaSpace&&i.push("#define GAMMA_INPUT"),i.push("#define NUM_SAMPLES "+this.quality+"u");let r=new EffectWrapper({engine:this._engine,name:"hdrFiltering",vertexShader:"hdrFiltering",fragmentShader:"hdrFiltering",samplerNames:["inputTexture"],uniformNames:["vSampleDirections","vWeights","up","right","front","vFilteringInfo","hdrScale","alphaG"],useShaderStore:!0,defines:i,onCompiled:t});return r}isReady(e){return e.isReady()&&this._effectWrapper.effect.isReady()}prefilter(e,t=null){return this._engine._features.allowTexturePrefiltering?new Promise(i=>{this._effectRenderer=new EffectRenderer(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(rT.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."))}};let hdrCubeTexture_HDRCubeTexture=class hdrCubeTexture_HDRCubeTexture extends baseTexture_BaseTexture{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(rm.y3.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,s=!0,n=!1,a=!1,o=null,l=null,h=!1){var u;if(super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=rm.P.Zero(),this.onLoadObservable=new rf.y$,!e)return;this._coordinatesMode=texture_Texture.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=rm.y3.Identity(),this._prefilterOnLoad=a,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),o&&o()},this._onError=l,this.gammaSpace=n,this._noMipmap=r,this._size=i,this._supersample=h,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?rW.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(){let e=this._getEngine(),t=e.getCaps(),i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){let t=this._onLoad,i=new HDRFiltering(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;let t=HDRTools.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){let e=CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}let r=[],s=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));let a=t[hdrCubeTexture_HDRCubeTexture._FacesMapping[e]];if(this.gammaSpace||n||s){for(let e=0;e<this._size*this._size;e++)if(this.gammaSpace&&(a[3*e+0]=Math.pow(a[3*e+0],rw.zp),a[3*e+1]=Math.pow(a[3*e+1],rw.zp),a[3*e+2]=Math.pow(a[3*e+2],rw.zp)),n&&(n[3*e+0]=ToHalfFloat(a[3*e+0]),n[3*e+1]=ToHalfFloat(a[3*e+1]),n[3*e+2]=ToHalfFloat(a[3*e+2])),s){let t=Math.max(255*a[3*e+0],0),i=Math.max(255*a[3*e+1],0),r=Math.max(255*a[3*e+2],0),n=Math.max(Math.max(t,i),r);if(n>255){let e=255/n;t*=e,i*=e,r*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=r}}n?r.push(n):s?r.push(s):r.push(a)}return r},null,this._onLoad,this._onError)}clone(){let e=new hdrCubeTexture_HDRCubeTexture(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 r=null;return e.name&&!e.isRenderTarget&&((r=new hdrCubeTexture_HDRCubeTexture(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=rm.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=rm.P.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;let 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}};hdrCubeTexture_HDRCubeTexture._FacesMapping=["right","left","up","down","front","back"],(0,rv.H)("BABYLON.HDRCubeTexture",hdrCubeTexture_HDRCubeTexture);let MorphTarget=class MorphTarget{get influence(){return this._influence}set influence(e){if(this._influence===e)return;let t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new rf.y$,this._onDataLayoutChanged=new rf.y$,this._animationPropertiesOverride=null,this._scene=i||rS.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){let t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){let t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){let t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){let t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){let e=rb.p4.Clone(()=>new MorphTarget(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(){let 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())),rb.p4.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){let i=new MorphTarget(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t<e.animations.length;t++){let r=e.animations[t],s=(0,rv.q)("BABYLON.Animation");s&&i.animations.push(s.Parse(r))}e.autoAnimate&&t&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1)}return i}static FromMesh(e,t,i){t||(t=e.name);let r=new MorphTarget(t,i,e.getScene());return r.setPositions(e.getVerticesData(rz.o.PositionKind)),e.isVerticesDataPresent(rz.o.NormalKind)&&r.setNormals(e.getVerticesData(rz.o.NormalKind)),e.isVerticesDataPresent(rz.o.TangentKind)&&r.setTangents(e.getVerticesData(rz.o.TangentKind)),e.isVerticesDataPresent(rz.o.UVKind)&&r.setUVs(e.getVerticesData(rz.o.UVKind)),r}};(0,rH.gn)([(0,rb.qC)()],MorphTarget.prototype,"id",void 0);let RawTexture2DArray=class RawTexture2DArray extends texture_Texture{get depth(){return this._depth}constructor(e,t,i,r,s,n,a=!0,o=!1,l=texture_Texture.TRILINEAR_SAMPLINGMODE,h=0,u){super(null,n,!a,o),this.format=s,this._texture=n.getEngine().createRawTexture2DArray(e,t,i,r,s,a,o,l,null,h,u),this._depth=r,this.is2DArray=!0}update(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}static CreateRGBATexture(e,t,i,r,s,n=!0,a=!1,o=3,l=0){return new RawTexture2DArray(e,t,i,r,5,s,n,a,o,l)}};let morphTargetManager_MorphTargetManager=class morphTargetManager_MorphTargetManager{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null){if(this._targets=[],this._targetInfluenceChangedObservers=[],this._targetDataLayoutChangedObservers=[],this._activeTargets=new sp.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=[],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=rS.l.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();let 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 morphTargetManager_MorphTargetManager.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){let 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(){let e=new morphTargetManager_MorphTargetManager(this._scene);for(let t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){let e={};for(let t of(e.id=this.uniqueId,e.targets=[],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(let e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=morphTargetManager_MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;let r=e.getPositions();if(r){let e=r.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e){rT.Y.Error("Incompatible target. Targets must all have the same vertices count.");return}}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e<t;e++)this._influences[e]=this._tempInfluences[e];e&&this.synchronize()}synchronize(){if(this._scene&&!this.areUpdatesFrozen){if(this.isUsingTextureForTargets&&this._vertexCount){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride,this._textureHeight=1;let e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){let 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();let e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4),i=0;for(let r=0;r<e;r++){let e=this._targets[r],s=e.getPositions(),n=e.getNormals(),a=e.getUVs(),o=e.getTangents();if(!s){0===r&&rT.Y.Error("Invalid morph target. Target must have positions.");return}i=r*this._textureWidth*this._textureHeight*4;for(let e=0;e<this._vertexCount;e++)t[i]=s[3*e],t[i+1]=s[3*e+1],t[i+2]=s[3*e+2],i+=4,this._supportsNormals&&n&&(t[i]=n[3*e],t[i+1]=n[3*e+1],t[i+2]=n[3*e+2],i+=4),this._supportsUVs&&a&&(t[i]=a[2*e],t[i+1]=a[2*e+1],i+=4),this._supportsTangents&&o&&(t[i]=o[3*e],t[i+1]=o[3*e+1],t[i+2]=o[3*e+2],i+=4)}this._targetStoreTexture=RawTexture2DArray.CreateRGBATexture(t,this._textureWidth,this._textureHeight,e,this._scene,!1,!1,1,1)}}for(let e of this._scene.meshes)e.morphTargetManager===this&&e._syncGeometryWithMorphTargetManager()}}dispose(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this._scene){if(this._scene.removeMorphTargetManager(this),this._parentContainer){let e=this._parentContainer.morphTargetManagers.indexOf(this);e>-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(let e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){let i=new morphTargetManager_MorphTargetManager(t);for(let r of(i._uniqueId=e.id,e.targets))i.addTarget(MorphTarget.Parse(r,t));return i}};morphTargetManager_MorphTargetManager.EnableTextureStorage=!0,morphTargetManager_MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode=8;let PhysicsRaycastResult=class PhysicsRaycastResult{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=rm.P.Zero(),this._hitPointWorld=rm.P.Zero(),this._rayFromWorld=rm.P.Zero(),this._rayToWorld=rm.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=rm.P.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=rm.P.Zero(),t=rm.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,this.body=void 0,this.bodyIndex=void 0}};let PhysicsEngine=class PhysicsEngine{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,r$.S)("CannonJSPlugin")}constructor(e,t=PhysicsEngine.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new rm.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){let t=this._impostors.indexOf(e);if(t>-1){let i=this._impostors.splice(t,1);i.length&&this.getPhysicsPlugin().removePhysicsBody(e)}}addJoint(e,t,i){let r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){let r=this._joints.filter(function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e});r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach(e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t<this._impostors.length;++t)if(this._impostors[t].object===e)return this._impostors[t];return null}getImpostorWithPhysicsBody(e){for(let t=0;t<this._impostors.length;++t)if(this._impostors[t].physicsBody===e)return this._impostors[t];return null}raycast(e,t){return this._physicsPlugin.raycast(e,t)}raycastToRef(e,t,i){return this._physicsPlugin.raycastToRef(e,t,i)}};let CannonJSPlugin=class CannonJSPlugin{constructor(e=!0,t=10,i=CANNON){if(this._useDeltaForWorldStep=e,this.name="CannonJSPlugin",this._physicsMaterials=[],this._fixedTimeStep=1/60,this._physicsBodiesToRemoveAfterStep=[],this._firstFrame=!0,this._tmpQuaternion=new rm._f,this._minus90X=new rm._f(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new rm._f(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=rm.P.Zero(),this._tmpDeltaPosition=rm.P.Zero(),this._tmpUnityRotation=new rm._f,this.BJSCANNON=i,!this.isSupported()){rT.Y.Error("CannonJS is not available. Please make sure you included the js file.");return}this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=t,this._cannonRaycastResult=new this.BJSCANNON.RaycastResult,this._raycastResult=new PhysicsRaycastResult}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this._fixedTimeStep=e}getTimeStep(){return this._fixedTimeStep}executeStep(e,t){if(this._firstFrame)for(let e of(this._firstFrame=!1,t))e.type==physicsImpostor_PhysicsImpostor.HeightmapImpostor||e.type===physicsImpostor_PhysicsImpostor.PlaneImpostor||e.beforeStep();this.world.step(this._useDeltaForWorldStep?e:this._fixedTimeStep),this._removeMarkedPhysicsBodiesFromWorld()}_removeMarkedPhysicsBodiesFromWorld(){this._physicsBodiesToRemoveAfterStep.length>0&&(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){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,r)}applyForce(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){let t=this._createShape(e);if(!t){rT.Y.Warn("It was not possible to create a physics body for this object.");return}let i=e.physicsBody;i&&this.removePhysicsBody(e);let r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:r},n=e.getParam("nativeOptions");for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&(s[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(t){let r=i[t];e.physicsBody[t].set(r.x,r.y,r.z)}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}_processChildMeshes(e){let 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){let processMesh=t=>{if(!t.rotationQuaternion)return;let i=t.getPhysicsImpostor();if(i){let r=i.parent;if(r!==e&&t.parent){let r=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);i.physicsBody&&(this.removePhysicsBody(i),i.physicsBody=null),i.parent=e,i.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(i),new this.BJSCANNON.Vec3(r.x,r.y,r.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=i.getParam("mass")}}t.getChildMeshes(!0).filter(e=>!!e.physicsImpostor).forEach(processMesh)};t.filter(e=>!!e.physicsImpostor).forEach(processMesh)}}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){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,n={pivotA:s.mainPivot?new this.BJSCANNON.Vec3().set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?new this.BJSCANNON.Vec3().set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?new this.BJSCANNON.Vec3().set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?new this.BJSCANNON.Vec3().set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case PhysicsJoint.HingeJoint:case PhysicsJoint.Hinge2Joint:t=new this.BJSCANNON.HingeConstraint(i,r,n);break;case PhysicsJoint.DistanceJoint:t=new this.BJSCANNON.DistanceConstraint(i,r,s.maxDistance||2);break;case PhysicsJoint.SpringJoint:t=new this.BJSCANNON.Spring(i,r,{restLength:s.length,stiffness:s.stiffness,damping:s.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break;case PhysicsJoint.LockJoint:t=new this.BJSCANNON.LockConstraint(i,r,n);break;case PhysicsJoint.PointToPointJoint:case PhysicsJoint.BallAndSocketJoint:default:t=new this.BJSCANNON.PointToPointConstraint(i,n.pivotA,r,n.pivotB,n.maxForce)}t.collideConnected=!!s.collision,e.joint.physicsJoint=t,e.joint.type!==PhysicsJoint.SpringJoint?this.world.addConstraint(t):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){t.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==PhysicsJoint.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,s;for(r=0;r<this._physicsMaterials.length;r++)if((s=this._physicsMaterials[r]).friction===t&&s.restitution===i)return s;let n=new this.BJSCANNON.Material(e);return n.friction=t,n.restitution=i,this._physicsMaterials.push(n),n}_checkWithEpsilon(e){return e<rw.kn?rw.kn:e}_createShape(e){let t;let i=e.object,r=e.getObjectExtents();switch(e.type){case physicsImpostor_PhysicsImpostor.SphereImpostor:{let e=r.x,i=r.y,s=r.z;t=new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(e),this._checkWithEpsilon(i),this._checkWithEpsilon(s))/2);break}case physicsImpostor_PhysicsImpostor.CylinderImpostor:{let i=e.getParam("nativeOptions");i||(i={});let s=void 0!==i.radiusTop?i.radiusTop:this._checkWithEpsilon(r.x)/2,n=void 0!==i.radiusBottom?i.radiusBottom:this._checkWithEpsilon(r.x)/2,a=void 0!==i.height?i.height:this._checkWithEpsilon(r.y),o=void 0!==i.numSegments?i.numSegments:16;t=new this.BJSCANNON.Cylinder(s,n,a,o);let l=new this.BJSCANNON.Quaternion;l.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0),-Math.PI/2);let h=new this.BJSCANNON.Vec3(0,0,0);t.transformAllPoints(h,l);break}case physicsImpostor_PhysicsImpostor.BoxImpostor:{let e=r.scale(.5);t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(e.x),this._checkWithEpsilon(e.y),this._checkWithEpsilon(e.z)));break}case physicsImpostor_PhysicsImpostor.PlaneImpostor:rT.Y.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),t=new this.BJSCANNON.Plane;break;case physicsImpostor_PhysicsImpostor.MeshImpostor:{let r;let s=i.getVerticesData?i.getVerticesData(rz.o.PositionKind):[],n=i.getIndices?i.getIndices():[];if(!s){rT.Y.Warn("Tried to create a MeshImpostor for an object without vertices. This will fail.");return}let a=i.position.clone(),o=i.rotation&&i.rotation.clone(),l=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace();let h=i.computeWorldMatrix(!0),u=[];for(r=0;r<s.length;r+=3)rm.P.TransformCoordinates(rm.P.FromArray(s,r),h).toArray(u,r);rT.Y.Warn("MeshImpostor only collides against spheres."),t=new this.BJSCANNON.Trimesh(u,n),i.position.copyFrom(a),o&&i.rotation&&i.rotation.copyFrom(o),l&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(l);break}case physicsImpostor_PhysicsImpostor.HeightmapImpostor:{let r=i.position.clone(),s=i.rotation&&i.rotation.clone(),n=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace(),i.rotationQuaternion&&i.rotationQuaternion.multiplyInPlace(this._minus90X),t=this._createHeightmap(i),i.position.copyFrom(r),s&&i.rotation&&i.rotation.copyFrom(s),n&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(n),i.computeWorldMatrix(!0);break}case physicsImpostor_PhysicsImpostor.ParticleImpostor:t=new this.BJSCANNON.Particle;break;case physicsImpostor_PhysicsImpostor.NoImpostor:t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0))}return t}_createHeightmap(e,t){let i,r=e.getVerticesData(rz.o.PositionKind),s=e.computeWorldMatrix(!0),n=[];for(i=0;i<r.length;i+=3)rm.P.TransformCoordinates(rm.P.FromArray(r,i),s).toArray(n,i);r=n;let a=[],o=t||~~(Math.sqrt(r.length/3)-1),l=e.getBoundingInfo(),h=Math.min(l.boundingBox.extendSizeWorld.x,l.boundingBox.extendSizeWorld.y),u=l.boundingBox.extendSizeWorld.z,c=2*h/o;for(let e=0;e<r.length;e+=3){let t=Math.round(r[e+0]/c+o/2),i=Math.round(-((r[e+1]/c-o/2)*1)),s=-r[e+2]+u;a[t]||(a[t]=[]),a[t][i]||(a[t][i]=s),a[t][i]=Math.max(s,a[t][i])}for(let e=0;e<=o;++e){if(!a[e]){let t=1;for(;!a[(e+t)%o];)t++;a[e]=a[(e+t)%o].slice()}for(let t=0;t<=o;++t)if(!a[e][t]){let i,r=1;for(;void 0===i;)i=a[e][(t+r++)%o];a[e][t]=i}}let d=new this.BJSCANNON.Heightfield(a,{elementSize:c});return d.minY=u,d}_updatePhysicsBodyTransformation(e){let t=e.object;if(t.computeWorldMatrix&&t.computeWorldMatrix(!0),!t.getBoundingInfo())return;let i=e.getObjectCenter();this._tmpDeltaPosition.copyFrom(t.getAbsolutePivotPoint().subtract(i)),this._tmpDeltaPosition.divideInPlace(e.object.scaling),this._tmpPosition.copyFrom(i);let r=t.rotationQuaternion;if(r){if((e.type===physicsImpostor_PhysicsImpostor.PlaneImpostor||e.type===physicsImpostor_PhysicsImpostor.HeightmapImpostor)&&(r=r.multiply(this._minus90X),e.setDeltaRotation(this._plus90X)),e.type===physicsImpostor_PhysicsImpostor.HeightmapImpostor){let e=t.getBoundingInfo(),r=t.rotationQuaternion;t.rotationQuaternion=this._tmpUnityRotation,t.computeWorldMatrix(!0);let s=i.clone(),n=t.getPivotMatrix();n=n?n.clone():rm.y3.Identity();let a=rm.y3.Translation(e.boundingBox.extendSizeWorld.x,0,-e.boundingBox.extendSizeWorld.z);t.setPreTransformMatrix(a),t.computeWorldMatrix(!0),e=t.getBoundingInfo();let o=e.boundingBox.centerWorld.subtract(i).subtract(t.position).negate();this._tmpPosition.copyFromFloats(o.x,o.y-e.boundingBox.extendSizeWorld.y,o.z),this._tmpDeltaPosition.copyFrom(e.boundingBox.centerWorld.subtract(s)),this._tmpDeltaPosition.y+=e.boundingBox.extendSizeWorld.y,t.rotationQuaternion=r,t.setPreTransformMatrix(n),t.computeWorldMatrix(!0)}else e.type===physicsImpostor_PhysicsImpostor.MeshImpostor&&this._tmpDeltaPosition.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpDeltaPosition),e.physicsBody.position.set(this._tmpPosition.x,this._tmpPosition.y,this._tmpPosition.z),e.physicsBody.quaternion.set(r.x,r.y,r.z,r.w)}}setTransformationFromPhysicsBody(e){if(e.object.position.set(e.physicsBody.position.x,e.physicsBody.position.y,e.physicsBody.position.z),e.object.rotationQuaternion){let t=e.physicsBody.quaternion;e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}setPhysicsBodyTransformation(e,t,i){e.physicsBody.position.set(t.x,t.y,t.z),e.physicsBody.quaternion.set(i.x,i.y,i.z,i.w)}isSupported(){return void 0!==this.BJSCANNON}setLinearVelocity(e,t){e.physicsBody.velocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){let t=e.physicsBody.velocity;return t?new rm.P(t.x,t.y,t.z):null}getAngularVelocity(e){let t=e.physicsBody.angularVelocity;return t?new rm.P(t.x,t.y,t.z):null}setBodyMass(e,t){e.physicsBody.mass=t,e.physicsBody.updateMassProperties()}getBodyMass(e){return e.physicsBody.mass}getBodyFriction(e){return e.physicsBody.material.friction}setBodyFriction(e,t){e.physicsBody.material.friction=t}getBodyRestitution(e){return e.physicsBody.material.restitution}setBodyRestitution(e,t){e.physicsBody.material.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.wakeUp()}updateDistanceJoint(e,t){e.physicsJoint.distance=t}setMotor(e,t,i,r){!r&&(e.physicsJoint.enableMotor(),e.physicsJoint.setMotorSpeed(t),i&&this.setLimit(e,i))}setLimit(e,t,i){e.physicsJoint.motorEquation.maxForce=i,e.physicsJoint.motorEquation.minForce=void 0===t?-t:t}syncMeshWithImpostor(e,t){let 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.quaternion.x,e.rotationQuaternion.y=i.quaternion.y,e.rotationQuaternion.z=i.quaternion.z,e.rotationQuaternion.w=i.quaternion.w)}getRadius(e){let t=e.physicsBody.shapes[0];return t.boundingSphereRadius}getBoxSizeToRef(e,t){let i=e.physicsBody.shapes[0];t.x=2*i.halfExtents.x,t.y=2*i.halfExtents.y,t.z=2*i.halfExtents.z}dispose(){}_extendNamespace(){let e=new this.BJSCANNON.Vec3,t=this.BJSCANNON;this.BJSCANNON.World.prototype.step=function(i,r,s){if(s=s||10,0===(r=r||0))this.internalStep(i),this.time+=i;else{let n=Math.floor((this.time+r)/i)-Math.floor(this.time/i);n=Math.min(n,s)||1;let a=performance.now();for(let e=0;e!==n&&(this.internalStep(i),!(performance.now()-a>1e3*i));e++);this.time+=r;let o=this.time%i,l=o/i,h=this.bodies;for(let i=0;i!==h.length;i++){let r=h[i];r.type!==t.Body.STATIC&&r.sleepState!==t.Body.SLEEPING?(r.position.vsub(r.previousPosition,e),e.scale(l,e),r.position.vadd(e,r.interpolatedPosition)):(r.interpolatedPosition.set(r.position.x,r.position.y,r.position.z),r.interpolatedQuaternion.set(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.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))}};PhysicsEngine.DefaultPluginFactory=()=>new CannonJSPlugin;let OimoJSPlugin=class OimoJSPlugin{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=rm.P.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new PhysicsRaycastResult}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}let e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];if(!e||!t){i=i.next;continue}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}}applyImpulse(e,t,i){let r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){rT.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());return}if(e.isBodyInitRequired()){var t;let i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},r=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach(function(e){e.physicsImpostor&&r.push(e.physicsImpostor)});let checkWithEpsilon=e=>Math.max(e,rw.kn),s=new rm._f;r.forEach(t=>{if(!t.object.rotationQuaternion)return;let r=t.object.rotationQuaternion;s.copyFrom(r),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);let n=s.toEulerAngles(),a=t.getObjectExtents();if(t===e){let t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{let e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(57.29577951308232*n.x,57.29577951308232*n.y,57.29577951308232*n.z)}switch(t.object.rotationQuaternion.copyFrom(s),t.type){case physicsImpostor_PhysicsImpostor.ParticleImpostor:rT.Y.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case physicsImpostor_PhysicsImpostor.SphereImpostor:{let e=a.x,t=a.y,r=a.z,s=Math.max(checkWithEpsilon(e),checkWithEpsilon(t),checkWithEpsilon(r))/2;i.type.push("sphere"),i.size.push(s),i.size.push(s),i.size.push(s);break}case physicsImpostor_PhysicsImpostor.CylinderImpostor:{let e=checkWithEpsilon(a.x)/2,t=checkWithEpsilon(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case physicsImpostor_PhysicsImpostor.PlaneImpostor:case physicsImpostor_PhysicsImpostor.BoxImpostor:default:{let e=checkWithEpsilon(a.x),t=checkWithEpsilon(a.y),r=checkWithEpsilon(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(r)}}t.object.rotationQuaternion=r}),e.physicsBody=this.world.add(i),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){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,n=s.nativeParams||{},a={body1:i,body2:r,axe1:n.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:n.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:n.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:n.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:n.min,max:n.max,collision:n.collision||s.collision,spring:n.spring,world:this.world};switch(e.joint.type){case PhysicsJoint.BallAndSocketJoint:t="jointBall";break;case PhysicsJoint.SpringJoint:rT.Y.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead"),a.min=s.length||a.min,a.max=Math.max(a.min,a.max);case PhysicsJoint.DistanceJoint:t="jointDistance",a.max=s.maxDistance;break;case PhysicsJoint.PrismaticJoint:t="jointPrisme";break;case PhysicsJoint.SliderJoint:t="jointSlide";break;case PhysicsJoint.WheelJoint:t="jointWheel";break;case PhysicsJoint.HingeJoint:default:t="jointHinge"}a.type=t,e.joint.physicsJoint=this.world.add(a)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){rT.Y.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{let t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){let t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){let t=e.physicsBody.linearVelocity;return t?new rm.P(t.x,t.y,t.z):null}getAngularVelocity(e){let t=e.physicsBody.angularVelocity;return t?new rm.P(t.x,t.y,t.z):null}setBodyMass(e,t){let i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){void 0!==i?rT.Y.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,r){let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){let 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){let 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 rT.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){rT.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}};let AmmoJSPlugin=class AmmoJSPlugin{constructor(e=!0,t=Ammo,i=null){if(this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new rm._f,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new rm.P,this._tmpContactNormal=new rm.P,this._tmpVec3=new rm.P,this._tmpMatrix=new rm.y3,"function"==typeof t){rT.Y.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}if(this.bjsAMMO=t,!this.isSupported()){rT.Y.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint);let t=e.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 PhysicsRaycastResult,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i<i?(this.world.stepSimulation(e,0),e=0):(e-=i,this.world.stepSimulation(i,0)),t--}executeStep(e,t){for(let e of t)e.soft||e.beforeStep();for(let i of(this._stepSimulation(this._useDeltaForWorldStep?e:this._timeStep,this._maxSteps,this._fixedTimeStep),t))if(i.soft?this._afterSoftStep(i):i.afterStep(),i._onPhysicsCollideCallbacks.length>0&&this._isImpostorInContact(i))for(let e of i._onPhysicsCollideCallbacks)for(let 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===physicsImpostor_PhysicsImpostor.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){let t,i,r,s;let n=e.physicsBody.get_m_nodes(),a=n.size(),o=[];for(let e=0;e<a;e++)i=(t=n.at(e).get_m_x()).x(),r=t.y(),s=t.z(),o.push(new rm.P(i,r,s));let l=e.object,h=e.getParam("shape");e._isFromLine?e.object=linesBuilder_CreateLines("lines",{points:o,instance:l}):e.object=ExtrudeShape("ext",{shape:h,path:o,instance:l})}_softbodyOrClothStep(e){let t,i,r,s,n,a,o,l;let h=e.type===physicsImpostor_PhysicsImpostor.ClothImpostor?1:-1,u=e.object,c=u.getVerticesData(rz.o.PositionKind);c||(c=[]);let d=u.getVerticesData(rz.o.NormalKind);d||(d=[]);let p=c.length/3,_=e.physicsBody.get_m_nodes();for(let e=0;e<p;e++){r=(i=(t=_.at(e)).get_m_x()).x(),s=i.y(),n=i.z()*h;let u=t.get_m_n();a=u.x(),o=u.y(),l=u.z()*h,c[3*e]=r,c[3*e+1]=s,c[3*e+2]=n,d[3*e]=a,d[3*e+1]=o,d[3*e+2]=l}let f=new se.x;f.positions=c,f.normals=d,f.uvs=u.getVerticesData(rz.o.UVKind),f.colors=u.getVerticesData(rz.o.ColorKind),u&&u.getIndices&&(f.indices=u.getIndices()),f.applyToMesh(u)}applyImpulse(e,t,i){if(e.soft)rT.Y.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();let r=this._tmpAmmoVectorA,s=this._tmpAmmoVectorB;e.object&&e.object.getWorldMatrix&&i.subtractInPlace(e.object.getWorldMatrix().getTranslation()),r.setValue(i.x,i.y,i.z),s.setValue(t.x,t.y,t.z),e.physicsBody.applyImpulse(s,r)}}applyForce(e,t,i){if(e.soft)rT.Y.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();let r=this._tmpAmmoVectorA,s=this._tmpAmmoVectorB;if(e.object&&e.object.getWorldMatrix){let t=e.object.getWorldMatrix().getTranslation();r.setValue(i.x-t.x,i.y-t.y,i.z-t.z)}else r.setValue(i.x,i.y,i.z);s.setValue(t.x,t.y,t.z),e.physicsBody.applyForce(s,r)}}generatePhysicsBody(e){if(e._pluginData.toDispose=[],e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){let t=this._createShape(e),i=e.getParam("mass");if(e._pluginData.mass=i,e.soft)t.get_m_cfg().set_collisions(17),t.get_m_cfg().set_kDP(e.getParam("damping")),this.bjsAMMO.castObject(t,this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(e.getParam("margin")),t.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG),this.world.addSoftBody(t,1,-1),e.physicsBody=t,e._pluginData.toDispose.push(t),this.setBodyPressure(e,0),e.type===physicsImpostor_PhysicsImpostor.SoftbodyImpostor&&this.setBodyPressure(e,e.getParam("pressure")),this.setBodyStiffness(e,e.getParam("stiffness")),this.setBodyVelocityIterations(e,e.getParam("velocityIterations")),this.setBodyPositionIterations(e,e.getParam("positionIterations"));else{let r=new this.bjsAMMO.btVector3(0,0,0),s=new this.bjsAMMO.btTransform;e.object.computeWorldMatrix(!0),s.setIdentity(),0!==i&&t.calculateLocalInertia(i,r),this._tmpAmmoVectorA.setValue(e.object.position.x,e.object.position.y,e.object.position.z),this._tmpAmmoQuaternion.setValue(e.object.rotationQuaternion.x,e.object.rotationQuaternion.y,e.object.rotationQuaternion.z,e.object.rotationQuaternion.w),s.setOrigin(this._tmpAmmoVectorA),s.setRotation(this._tmpAmmoQuaternion);let n=new this.bjsAMMO.btDefaultMotionState(s),a=new this.bjsAMMO.btRigidBodyConstructionInfo(i,n,t,r),o=new this.bjsAMMO.btRigidBody(a);if(0===i&&(o.setCollisionFlags(o.getCollisionFlags()|AmmoJSPlugin._KINEMATIC_FLAG),o.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG)),e.type!=physicsImpostor_PhysicsImpostor.NoImpostor||t.getChildShape||o.setCollisionFlags(o.getCollisionFlags()|AmmoJSPlugin._DISABLE_COLLISION_FLAG),e.type!==physicsImpostor_PhysicsImpostor.MeshImpostor&&e.type!==physicsImpostor_PhysicsImpostor.NoImpostor){let t=e.object.getBoundingInfo();this._tmpVec3.copyFrom(e.object.getAbsolutePosition()),this._tmpVec3.subtractInPlace(t.boundingBox.centerWorld),this._tmpVec3.x/=e.object.scaling.x,this._tmpVec3.y/=e.object.scaling.y,this._tmpVec3.z/=e.object.scaling.z,e.setDeltaPosition(this._tmpVec3)}let l=e.getParam("group"),h=e.getParam("mask");l&&h?this.world.addRigidBody(o,l,h):this.world.addRigidBody(o),e.physicsBody=o,e._pluginData.toDispose=e._pluginData.toDispose.concat([o,a,n,s,r,t])}this.setBodyRestitution(e,e.getParam("restitution")),this.setBodyFriction(e,e.getParam("friction"))}}removePhysicsBody(e){this.world&&(e.soft?this.world.removeSoftBody(e.physicsBody):this.world.removeRigidBody(e.physicsBody),e._pluginData&&(e._pluginData.toDispose.forEach(e=>{this.bjsAMMO.destroy(e)}),e._pluginData.toDispose=[]))}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData;switch(s.mainPivot||(s.mainPivot=new rm.P(0,0,0)),s.connectedPivot||(s.connectedPivot=new rm.P(0,0,0)),e.joint.type){case PhysicsJoint.DistanceJoint:{let e=s.maxDistance;e&&(s.mainPivot=new rm.P(0,-e/2,0),s.connectedPivot=new rm.P(0,e/2,0)),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case PhysicsJoint.HingeJoint:{s.mainAxis||(s.mainAxis=new rm.P(0,0,0)),s.connectedAxis||(s.connectedAxis=new rm.P(0,0,0));let e=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),n=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);t=new this.bjsAMMO.btHingeConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),e,n);break}case PhysicsJoint.BallAndSocketJoint:t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:rT.Y.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z))}this.world.addConstraint(t,!e.joint.jointData.collision),e.joint.physicsJoint=t}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s,n=i.getIndices();n||(n=[]);let a=i.getVerticesData(rz.o.PositionKind);if(a||(a=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?rm._f.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):rm._f.Identity();let r=rm.y3.Compose(rm.P.One(),e,t.position);r.invertToRef(this._tmpMatrix);let n=i.computeWorldMatrix(!1);s=n.multiply(this._tmpMatrix)}else rm.y3.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),s=this._tmpMatrix;let o=n.length/3;for(let t=0;t<o;t++){let i=[];for(let e=0;e<3;e++){let r,o=new rm.P(a[3*n[3*t+e]+0],a[3*n[3*t+e]+1],a[3*n[3*t+e]+2]);o=rm.P.TransformCoordinates(o,s),(r=0==e?this._tmpAmmoVectorA:1==e?this._tmpAmmoVectorB:this._tmpAmmoVectorC).setValue(o.x,o.y,o.z),i.push(r)}e.addTriangle(i[0],i[1],i[2]),r++}i.getChildMeshes().forEach(i=>{r+=this._addMeshVerts(e,t,i)})}return r}_softVertexData(e){let t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(rz.o.PositionKind);i||(i=[]);let r=t.getVerticesData(rz.o.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);let s=[],n=[];for(let e=0;e<i.length;e+=3){let a=new rm.P(i[e],i[e+1],i[e+2]),o=new rm.P(r[e],r[e+1],r[e+2]);a=rm.P.TransformCoordinates(a,t.getWorldMatrix()),o=rm.P.TransformNormal(o,t.getWorldMatrix()),s.push(a.x,a.y,a.z),n.push(o.x,o.y,o.z)}let a=new se.x;return a.positions=s,a.normals=n,a.uvs=t.getVerticesData(rz.o.UVKind),a.colors=t.getVerticesData(rz.o.ColorKind),t&&t.getIndices&&(a.indices=t.getIndices()),a.applyToMesh(t),t.position=rm.P.Zero(),t.rotationQuaternion=null,t.rotation=rm.P.Zero(),t.computeWorldMatrix(!0),a}return se.x.ExtractFromMesh(t)}_createSoftbody(e){let t=e.object;if(t&&t.getIndices){let i=t.getIndices();i||(i=[]);let r=this._softVertexData(e),s=r.positions,n=r.normals;if(null===s||null===n)return new this.bjsAMMO.btCompoundShape;{let e;let r=[],a=[];for(let e=0;e<s.length;e+=3){let t=new rm.P(s[e],s[e+1],s[e+2]),i=new rm.P(n[e],n[e+1],n[e+2]);r.push(t.x,t.y,-t.z),a.push(i.x,i.y,-i.z)}let o=new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(),r,t.getIndices(),i.length/3,!0),l=s.length/3,h=o.get_m_nodes();for(let t=0;t<l;t++)(e=h.at(t).get_m_n()).setX(a[3*t]),e.setY(a[3*t+1]),e.setZ(a[3*t+2]);return o}}}_createCloth(e){let t=e.object;if(t&&t.getIndices){let i=t.getIndices();i||(i=[]);let r=this._softVertexData(e),s=r.positions,n=r.normals;if(null===s||null===n)return new this.bjsAMMO.btCompoundShape;{let t=s.length,i=Math.sqrt(t/3);e.segments=i;let r=i-1;this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[3*r],s[3*r+1],s[3*r+2]),this._tmpAmmoVectorD.setValue(s[t-3],s[t-2],s[t-1]),this._tmpAmmoVectorC.setValue(s[t-3-3*r],s[t-2-3*r],s[t-1-3*r]);let n=new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,this._tmpAmmoVectorC,this._tmpAmmoVectorD,i,i,e.getParam("fixedPoints"),!0);return n}}}_createRope(e){let t,i;let r=this._softVertexData(e),s=r.positions,n=r.normals;if(null===s||null===n)return new this.bjsAMMO.btCompoundShape;r.applyToMesh(e.object,!0),e._isFromLine=!0;let a=n.map(e=>e*e),o=a.reduce((e,t)=>e+t);if(0===o)i=(t=s.length)/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;let r=e.getParam("path"),s=e.getParam("shape");if(null===s)return rT.Y.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;i=(t=r.length)-1,this._tmpAmmoVectorA.setValue(r[0].x,r[0].y,r[0].z),this._tmpAmmoVectorB.setValue(r[t-1].x,r[t-1].y,r[t-1].z)}e.segments=i;let l=e.getParam("fixedPoints");l=l>3?3:l;let h=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,l);return h.get_m_cfg().set_collisions(17),h}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let n=i.getVerticesData(rz.o.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);let a=s.length/3;for(let t=0;t<a;t++){let a=[];for(let e=0;e<3;e++){let r,o=new rm.P(n[3*s[3*t+e]+0],n[3*s[3*t+e]+1],n[3*s[3*t+e]+2]);rm.y3.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),o=rm.P.TransformCoordinates(o,this._tmpMatrix),(r=0==e?this._tmpAmmoVectorA:1==e?this._tmpAmmoVectorB:this._tmpAmmoVectorC).setValue(o.x,o.y,o.z),a.push(r)}e.addPoint(a[0],!0),e.addPoint(a[1],!0),e.addPoint(a[2],!0),r++}i.getChildMeshes().forEach(i=>{r+=this._addHullVerts(e,t,i)})}return r}_createShape(e,t=!1){let i;let r=e.object,s=e.getObjectExtents();if(!t){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];i=new this.bjsAMMO.btCompoundShape;let r=0;if(t.forEach(e=>{let t=e.getPhysicsImpostor();if(t){if(t.type==physicsImpostor_PhysicsImpostor.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";let s=this._createShape(t),n=e.parent.getWorldMatrix().clone(),a=new rm.P;n.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),i.addChildShape(this._tmpAmmoTransform,s),t.dispose(),r++}}),r>0){if(e.type!=physicsImpostor_PhysicsImpostor.NoImpostor){let 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),i.addChildShape(this._tmpAmmoTransform,t))}return i}this.bjsAMMO.destroy(i),i=null}switch(e.type){case physicsImpostor_PhysicsImpostor.SphereImpostor:if(rE.R.WithinEpsilon(s.x,s.y,1e-4)&&rE.R.WithinEpsilon(s.x,s.z,1e-4))i=new this.bjsAMMO.btSphereShape(s.x/2);else{let e=[new this.bjsAMMO.btVector3(0,0,0)];(i=new this.bjsAMMO.btMultiSphereShape(e,[1],1)).setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case physicsImpostor_PhysicsImpostor.CapsuleImpostor:{let e=s.x/2;i=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case physicsImpostor_PhysicsImpostor.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case physicsImpostor_PhysicsImpostor.PlaneImpostor:case physicsImpostor_PhysicsImpostor.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case physicsImpostor_PhysicsImpostor.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)i=this.onCreateCustomMeshImpostor(e);else{let t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);let s=this._addMeshVerts(t,r,r);i=0==s?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case physicsImpostor_PhysicsImpostor.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)i=this.onCreateCustomConvexHullImpostor(e);else{let t=new this.bjsAMMO.btConvexHullShape,s=this._addHullVerts(t,r,r);0==s?(e._pluginData.toDispose.push(t),i=new this.bjsAMMO.btCompoundShape):i=t}break;case physicsImpostor_PhysicsImpostor.NoImpostor:i=new this.bjsAMMO.btSphereShape(s.x/2);break;case physicsImpostor_PhysicsImpostor.CustomImpostor:i=this._createCustom(e);break;case physicsImpostor_PhysicsImpostor.SoftbodyImpostor:i=this._createSoftbody(e);break;case physicsImpostor_PhysicsImpostor.ClothImpostor:i=this._createCloth(e);break;case physicsImpostor_PhysicsImpostor.RopeImpostor:i=this._createRope(e);break;default:rT.Y.Warn("The impostor type is not currently supported by the ammo plugin.")}return i}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){let r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>rw.kn||Math.abs(r.getOrigin().y()-t.y)>rw.kn||Math.abs(r.getOrigin().z()-t.z)>rw.kn||Math.abs(r.getRotation().x()-i.x)>rw.kn||Math.abs(r.getRotation().y()-i.y)>rw.kn||Math.abs(r.getRotation().z()-i.z)>rw.kn||Math.abs(r.getRotation().w()-i.w)>rw.kn){if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),0==e.mass){let t=e.physicsBody.getMotionState();t&&t.setWorldTransform(r)}else e.physicsBody.activate()}}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(!(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity()))return null;let i=new rm.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()))return null;let i=new rm.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:(rT.Y.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===physicsImpostor_PhysicsImpostor.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):rT.Y.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(rT.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):rT.Y.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(rT.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):rT.Y.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(rT.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):rT.Y.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,s=1,n=!1){let a=e.segments;e.physicsBody.appendAnchor(Math.round((a-1)*i)+a*(a-1-Math.round((a-1)*r)),t.physicsBody,n,s)}appendHook(e,t,i,r=1,s=!1){let n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,s,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){rT.Y.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){rT.Y.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){let i=t.physicsBody;i.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){let t=e.getObjectExtents();return t.x/2}getBoxSizeToRef(e,t){let 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);let r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}};AmmoJSPlugin._DISABLE_COLLISION_FLAG=4,AmmoJSPlugin._KINEMATIC_FLAG=2,AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG=4,rp.p.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return -1;let t=this.reflectionProbes.indexOf(e);return -1!==t&&this.reflectionProbes.splice(t,1),t},rp.p.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};let reflectionProbe_ReflectionProbe=class reflectionProbe_ReflectionProbe{constructor(e,t,i,r=!0,s=!1,n=!1){let a;if(this.name=e,this._viewMatrix=rm.y3.Identity(),this._target=rm.P.Zero(),this._add=rm.P.Zero(),this._invertYAxis=!1,this.position=rm.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=[]),this._scene.reflectionProbes.push(this);let o=0;if(s){let e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new renderTargetTexture_RenderTargetTexture(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;let l=i.getEngine().useReverseDepthBuffer;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);let t=i.useRightHandedSystem?rm.y3.LookAtRHToRef:rm.y3.LookAtLHToRef,r=i.useRightHandedSystem?rm.y3.PerspectiveFovRH:rm.y3.PerspectiveFovLH;t(this.position,this._target,rm.P.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=r(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,r;this._currentSceneUBO=i.getSceneUniformBuffer(),null===(r=(t=i.getEngine())._debugPushGroup)||void 0===r||r.call(t,`reflection probe generation for ${e}`,1),a=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var e,t;i.imageProcessingConfiguration.applyByPostProcess=a,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}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){let e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){let 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(let 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(){let e=rb.p4.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let i=0;i<t.reflectionProbes.length;i++){let s=t.reflectionProbes[i];if(s.name===e.name){r=s;break}}return(r=rb.p4.Parse(()=>r||new reflectionProbe_ReflectionProbe(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i)).cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}};(0,rH.gn)([(0,rb.RR)()],reflectionProbe_ReflectionProbe.prototype,"_attachedMesh",void 0),(0,rH.gn)([(0,rb.hd)()],reflectionProbe_ReflectionProbe.prototype,"position",void 0);let BabylonFileLoaderConfiguration=class BabylonFileLoaderConfiguration{};BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine=void 0;let ly={},lP={},parseMaterialByPredicate=(e,t,i,r)=>{if(!t.materials)return null;for(let s=0,n=t.materials.length;s<n;s++){let n=t.materials[s];if(e(n))return{parsedMaterial:n,material:sr.F.Parse(n,i,r)}}return null},isDescendantOf=(e,t,i)=>{for(let r in t)if(e.name===t[r])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},logOperation=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),loadDetailLevels=(e,t)=>{if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){let i=t._waitingData.lods.ids,r=t.isEnabled(!1);if(t._waitingData.lods.distances){let s=t._waitingData.lods.distances;if(s.length>=i.length){let n=s.length>i.length?s[s.length-1]:0;t.setEnabled(!1);for(let r=0;r<i.length;r++){let n=i[r],a=e.getMeshById(n);null!=a&&t.addLODLevel(s[r],a)}n>0&&t.addLODLevel(n,null),!0===r&&t.setEnabled(!0)}else rW.w1.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},findParent=(e,t,i)=>{if("number"!=typeof e){let r=i.getLastEntryById(e);if(r&&null!=t){let e=r.instances[parseInt(t)];return e}return r}let r=ly[e];if(r&&null!=t){let e=r.instances[parseInt(t)];return e}return r},findMaterial=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):lP[e],loadAssetContainer=(e,t,i,r,s=!1)=>{let n=new AssetContainer(e),a="importScene has failed JSON parse";try{let r,s;var o=JSON.parse(t);a="";let l=sceneLoader_SceneLoader.loggingLevel===sceneLoader_SceneLoader.DETAILED_LOGGING;if(void 0!==o.environmentTexture&&null!==o.environmentTexture){let t=void 0===o.isPBR||o.isPBR;if(o.environmentTextureType&&"BABYLON.HDRCubeTexture"===o.environmentTextureType){let r=o.environmentTextureSize?o.environmentTextureSize:128,s=new hdrCubeTexture_HDRCubeTexture((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,r,!0,!t,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(s.rotationY=o.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof o.environmentTexture){let t=cubeTexture_CubeTexture.Parse(o.environmentTexture,e,i);e.environmentTexture=t}else if(o.environmentTexture.endsWith(".env")){let t=new cubeTexture_CubeTexture((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}else{let t=cubeTexture_CubeTexture.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}if(!0===o.createDefaultSkybox){let i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,r=o.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,r)}n.environmentTexture=e.environmentTexture}if(void 0!==o.environmentIntensity&&null!==o.environmentIntensity&&(e.environmentIntensity=o.environmentIntensity),void 0!==o.lights&&null!==o.lights)for(r=0,s=o.lights.length;r<s;r++){let t=o.lights[r],i=light_Light.Parse(t,e);i&&(ly[t.uniqueId]=i,n.lights.push(i),i._parentContainer=n,a+=(0===r?"\n Lights:":"")+"\n "+i.toString(l))}if(void 0!==o.reflectionProbes&&null!==o.reflectionProbes)for(r=0,s=o.reflectionProbes.length;r<s;r++){let t=o.reflectionProbes[r],s=reflectionProbe_ReflectionProbe.Parse(t,e,i);s&&(n.reflectionProbes.push(s),s._parentContainer=n,a+=(0===r?"\n Reflection Probes:":"")+"\n "+s.toString(l))}if(void 0!==o.animations&&null!==o.animations)for(r=0,s=o.animations.length;r<s;r++){let t=o.animations[r],i=(0,rv.q)("BABYLON.Animation");if(i){let s=i.Parse(t);e.animations.push(s),n.animations.push(s),a+=(0===r?"\n Animations:":"")+"\n "+s.toString(l)}}if(void 0!==o.materials&&null!==o.materials)for(r=0,s=o.materials.length;r<s;r++){let t=o.materials[r],s=sr.F.Parse(t,e,i);if(s){lP[t.uniqueId||t.id]=s,n.materials.push(s),s._parentContainer=n,a+=(0===r?"\n Materials:":"")+"\n "+s.toString(l);let e=s.getActiveTextures();e.forEach(e=>{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})}}if(void 0!==o.multiMaterials&&null!==o.multiMaterials)for(r=0,s=o.multiMaterials.length;r<s;r++){let t=o.multiMaterials[r],i=lC.G.ParseMultiMaterial(t,e);lP[t.uniqueId||t.id]=i,n.multiMaterials.push(i),i._parentContainer=n,a+=(0===r?"\n MultiMaterials:":"")+"\n "+i.toString(l);let s=i.getActiveTextures();s.forEach(e=>{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})}if(void 0!==o.morphTargetManagers&&null!==o.morphTargetManagers)for(let t of o.morphTargetManagers){let i=morphTargetManager_MorphTargetManager.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==o.skeletons&&null!==o.skeletons)for(r=0,s=o.skeletons.length;r<s;r++){let t=o.skeletons[r],i=skeleton_Skeleton.Parse(t,e);n.skeletons.push(i),i._parentContainer=n,a+=(0===r?"\n Skeletons:":"")+"\n "+i.toString(l)}let h=o.geometries;if(null!=h){let t=[],a=h.vertexData;if(null!=a)for(r=0,s=a.length;r<s;r++){let s=a[r];t.push(lS.Z.Parse(s,e,i))}t.forEach(e=>{e&&(n.geometries.push(e),e._parentContainer=n)})}if(void 0!==o.transformNodes&&null!==o.transformNodes)for(r=0,s=o.transformNodes.length;r<s;r++){let t=o.transformNodes[r],s=rk.Y.Parse(t,e,i);ly[t.uniqueId]=s,n.transformNodes.push(s),s._parentContainer=n}if(void 0!==o.meshes&&null!==o.meshes)for(r=0,s=o.meshes.length;r<s;r++){let t=o.meshes[r],s=rV.Kj.Parse(t,e,i);if(ly[t.uniqueId]=s,n.meshes.push(s),s._parentContainer=n,s.hasInstances)for(let e of s.instances)n.meshes.push(e),e._parentContainer=n;a+=(0===r?"\n Meshes:":"")+"\n "+s.toString(l)}if(void 0!==o.cameras&&null!==o.cameras)for(r=0,s=o.cameras.length;r<s;r++){let t=o.cameras[r],i=rj.V.Parse(t,e);ly[t.uniqueId]=i,n.cameras.push(i),i._parentContainer=n,a+=(0===r?"\n Cameras:":"")+"\n "+i.toString(l)}if(void 0!==o.postProcesses&&null!==o.postProcesses)for(r=0,s=o.postProcesses.length;r<s;r++){let t=o.postProcesses[r],s=postProcess_PostProcess.Parse(t,e,i);s&&(n.postProcesses.push(s),s._parentContainer=n,a+=(0===r?"\nPostprocesses:":"")+"\n "+s.toString())}if(void 0!==o.animationGroups&&null!==o.animationGroups)for(r=0,s=o.animationGroups.length;r<s;r++){let t=o.animationGroups[r],i=AnimationGroup.Parse(t,e);n.animationGroups.push(i),i._parentContainer=n,a+=(0===r?"\n AnimationGroups:":"")+"\n "+i.toString(l)}for(r=0,s=e.cameras.length;r<s;r++){let t=e.cameras[r];null!==t._waitingParentId&&(t.parent=findParent(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,s=e.lights.length;r<s;r++){let t=e.lights[r];t&&null!==t._waitingParentId&&(t.parent=findParent(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,s=e.transformNodes.length;r<s;r++){let t=e.transformNodes[r];null!==t._waitingParentId&&(t.parent=findParent(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,s=e.meshes.length;r<s;r++){let t=e.meshes[r];null!==t._waitingParentId&&(t.parent=findParent(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null),t._waitingData.lods&&loadDetailLevels(e,t)}for(e.multiMaterials.forEach(t=>{t._waitingSubMaterialsUniqueIds.forEach(i=>{t.subMaterials.push(findMaterial(i,e))}),t._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(t=>{null!==t._waitingMaterialId&&(t.material=findMaterial(t._waitingMaterialId,e),t._waitingMaterialId=null)}),r=0,s=e.skeletons.length;r<s;r++){let t=e.skeletons[r];t._hasWaitingData&&(null!=t.bones&&t.bones.forEach(t=>{if(t._waitingTransformNodeId){let i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}}),t._hasWaitingData=null)}for(r=0,s=e.meshes.length;r<s;r++){let t=e.meshes[r];t._waitingData.freezeWorldMatrix?(t.freezeWorldMatrix(),t._waitingData.freezeWorldMatrix=null):t.computeWorldMatrix(!0)}for(r=0,s=e.lights.length;r<s;r++){let t=e.lights[r];if(t._excludedMeshesIds.length>0){for(let i=0;i<t._excludedMeshesIds.length;i++){let r=e.getMeshById(t._excludedMeshesIds[i]);r&&t.excludedMeshes.push(r)}t._excludedMeshesIds=[]}if(t._includedOnlyMeshesIds.length>0){for(let i=0;i<t._includedOnlyMeshesIds.length;i++){let r=e.getMeshById(t._includedOnlyMeshesIds[i]);r&&t.includedOnlyMeshes.push(r)}t._includedOnlyMeshesIds=[]}}for(e.geometries.forEach(e=>{e._loadedUniqueId=""}),rp.p.Parse(o,e,n,i),r=0,s=e.meshes.length;r<s;r++){let t=e.meshes[r];t._waitingData.actions&&(ActionManager.Parse(t._waitingData.actions,t,e),t._waitingData.actions=null)}void 0!==o.actions&&null!==o.actions&&ActionManager.Parse(o.actions,null,e)}catch(t){let e=logOperation("loadAssets",o?o.producer:"Unknown")+a;if(r)r(e,t);else throw rT.Y.Log(e),t}finally{ly={},lP={},s||n.removeAllFromScene(),null!==a&&sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.NO_LOGGING&&rT.Y.Log(logOperation("loadAssets",o?o.producer:"Unknown")+(sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.MINIMAL_LOGGING?a:""))}return n};sceneLoader_SceneLoader.RegisterPlugin({name:"babylon.js",extensions:".babylon",canDirectLoad:e=>-1!==e.indexOf("babylon"),importMesh:(e,t,i,r,s,n,a,o)=>{var l;let h="importMesh has failed JSON parse";try{var u=JSON.parse(i);h="";let o=sceneLoader_SceneLoader.loggingLevel===sceneLoader_SceneLoader.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;let c=[],d=new Map,p=[];if(void 0!==u.transformNodes&&null!==u.transformNodes)for(let e=0,i=u.transformNodes.length;e<i;e++){let i=u.transformNodes[e],s=rk.Y.Parse(i,t,r);p.push(s),d.set(s._waitingParsedUniqueId,s),s._waitingParsedUniqueId=null}if(void 0!==u.meshes&&null!==u.meshes){let i;let n=[],_=[],f=[],m=[];for(let i=0,l=u.meshes.length;i<l;i++){let l=u.meshes[i];if(null===e||isDescendantOf(l,e,c)){if(null!==e&&delete e[e.indexOf(l.name)],void 0!==l.geometryId&&null!==l.geometryId&&void 0!==u.geometries&&null!==u.geometries){let e=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach(i=>{!0!==e&&u.geometries[i]&&Array.isArray(u.geometries[i])&&u.geometries[i].forEach(s=>{s.id===l.geometryId&&("vertexData"===i&&lS.Z.Parse(s,t,r),e=!0)})}),!1===e&&rT.Y.Warn("Geometry not found for mesh "+l.id)}if(l.materialUniqueId||l.materialId){let e=l.materialUniqueId?f:_,i=-1!==e.indexOf(l.materialUniqueId||l.materialId);if(!1===i&&void 0!==u.multiMaterials&&null!==u.multiMaterials){let loadSubMaterial=(i,s)=>{e.push(i);let n=parseMaterialByPredicate(s,u,t,r);n&&n.material&&(lP[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,h+="\n Material "+n.material.toString(o))};for(let r=0,s=u.multiMaterials.length;r<s;r++){let s=u.multiMaterials[r];if(l.materialUniqueId&&s.uniqueId===l.materialUniqueId||s.id===l.materialId){s.materialsUniqueIds?s.materialsUniqueIds.forEach(e=>loadSubMaterial(e,t=>t.uniqueId===e)):s.materials.forEach(e=>loadSubMaterial(e,t=>t.id===e)),e.push(s.uniqueId||s.id);let r=lC.G.ParseMultiMaterial(s,t);lP[s.uniqueId||s.id]=r,r&&(i=!0,h+="\n Multi-Material "+r.toString(o));break}}}if(!1===i){e.push(l.materialUniqueId||l.materialId);let i=parseMaterialByPredicate(e=>l.materialUniqueId&&e.uniqueId===l.materialUniqueId||e.id===l.materialId,u,t,r);i&&i.material?(lP[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,h+="\n Material "+i.material.toString(o)):rT.Y.Warn("Material not found for mesh "+l.id)}}if(null!==l.skeletonId&&void 0!==l.skeletonId&&-1!==u.skeletonId&&void 0!==u.skeletons&&null!==u.skeletons){let e=n.indexOf(l.skeletonId)>-1;if(!e)for(let e=0,i=u.skeletons.length;e<i;e++){let i=u.skeletons[e];if(i.id===l.skeletonId){let e=skeleton_Skeleton.Parse(i,t);a.push(e),n.push(i.id),h+="\n Skeleton "+e.toString(o)}}}if(l.morphTargetManagerId>-1&&void 0!==u.morphTargetManagers&&null!==u.morphTargetManagers){let e=m.indexOf(l.morphTargetManagerId)>-1;if(!e)for(let e=0,i=u.morphTargetManagers.length;e<i;e++){let i=u.morphTargetManagers[e];if(i.id===l.morphTargetManagerId){let e=morphTargetManager_MorphTargetManager.Parse(i,t);m.push(e.uniqueId),h+="\nMorph target "+e.toString()}}}let i=rV.Kj.Parse(l,t,r);s.push(i),d.set(i._waitingParsedUniqueId,i),i._waitingParsedUniqueId=null,h+="\n Mesh "+i.toString(o)}}t.multiMaterials.forEach(e=>{e._waitingSubMaterialsUniqueIds.forEach(i=>{e.subMaterials.push(findMaterial(i,t))}),e._waitingSubMaterialsUniqueIds=[]}),t.meshes.forEach(e=>{null!==e._waitingMaterialId&&(e.material=findMaterial(e._waitingMaterialId,t),e._waitingMaterialId=null)});for(let e=0,i=t.transformNodes.length;e<i;e++){let i=t.transformNodes[e];if(null!==i._waitingParentId){let e=d.get(parseInt(i._waitingParentId))||null;null===e&&(e=t.getLastEntryById(i._waitingParentId));let r=e;i._waitingParentInstanceIndex&&(r=e.instances[parseInt(i._waitingParentInstanceIndex)],i._waitingParentInstanceIndex=null),i.parent=r,i._waitingParentId=null}}for(let e=0,r=t.meshes.length;e<r;e++){if((i=t.meshes[e])._waitingParentId){let e=d.get(parseInt(i._waitingParentId))||null;null===e&&(e=t.getLastEntryById(i._waitingParentId));let r=e;if(i._waitingParentInstanceIndex&&(r=e.instances[parseInt(i._waitingParentInstanceIndex)],i._waitingParentInstanceIndex=null),i.parent=r,(null===(l=i.parent)||void 0===l?void 0:l.getClassName())==="TransformNode"){let e=p.indexOf(i.parent);e>-1&&p.splice(e,1)}i._waitingParentId=null}i._waitingData.lods&&loadDetailLevels(t,i)}for(let e of p)e.dispose();for(let e=0,i=t.skeletons.length;e<i;e++){let i=t.skeletons[e];i._hasWaitingData&&(null!=i.bones&&i.bones.forEach(e=>{if(e._waitingTransformNodeId){let i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}}),i._hasWaitingData=null)}for(let e=0,r=t.meshes.length;e<r;e++)(i=t.meshes[e])._waitingData.freezeWorldMatrix?(i.freezeWorldMatrix(),i._waitingData.freezeWorldMatrix=null):i.computeWorldMatrix(!0)}if(void 0!==u.particleSystems&&null!==u.particleSystems){let e=rp.p.GetIndividualParser(rQ.l.NAME_PARTICLESYSTEM);if(e)for(let i=0,s=u.particleSystems.length;i<s;i++){let s=u.particleSystems[i];-1!==c.indexOf(s.emitterId)&&n.push(e(s,t,r))}}return t.geometries.forEach(e=>{e._loadedUniqueId=""}),!0}catch(t){let e=logOperation("importMesh",u?u.producer:"Unknown")+h;if(o)o(e,t);else throw rT.Y.Log(e),t}finally{null!==h&&sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.NO_LOGGING&&rT.Y.Log(logOperation("importMesh",u?u.producer:"Unknown")+(sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.MINIMAL_LOGGING?h:"")),lP={}}return!1},load:(e,t,i,r)=>{let s="importScene has failed JSON parse";try{var n=JSON.parse(t);if(s="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!sceneLoader_SceneLoader.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=rg.HE.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=rg.Wo.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=rm.P.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),n.fogMode&&0!==n.fogMode)switch(e.fogMode=n.fogMode,e.fogColor=rg.Wo.FromArray(n.fogColor),e.fogStart=n.fogStart,e.fogEnd=n.fogEnd,e.fogDensity=n.fogDensity,s+=" Fog mode for scene: ",e.fogMode){case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===CannonJSPlugin.name?t=new CannonJSPlugin(void 0,void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===OimoJSPlugin.name?t=new OimoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine):("ammo"===n.physicsEngine||n.physicsEngine===AmmoJSPlugin.name)&&(t=new AmmoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";let i=n.physicsGravity?rm.P.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled);let a=loadAssetContainer(e,t,i,r,!0);if(!a)return!1;return n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0}catch(t){let e=logOperation("importScene",n?n.producer:"Unknown")+s;if(r)r(e,t);else throw rT.Y.Log(e),t}finally{null!==s&&sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.NO_LOGGING&&rT.Y.Log(logOperation("importScene",n?n.producer:"Unknown")+(sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,r)=>{let s=loadAssetContainer(e,t,i,r);return s}}),i(9087);let FresnelParameters=class FresnelParameters{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,rq.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||rg.Wo.White(),this.rightColor=e.rightColor||rg.Wo.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){let e=new FresnelParameters;return rC.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 FresnelParameters({isEnabled:e.isEnabled,leftColor:rg.Wo.FromArray(e.leftColor),rightColor:rg.Wo.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}};rb.p4._FresnelParametersParser=FresnelParameters.Parse;let PBRBaseSimpleMaterial=class PBRBaseSimpleMaterial extends pbrBaseMaterial_PBRBaseMaterial{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 rg.Wo(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}};(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],PBRBaseSimpleMaterial.prototype,"maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],PBRBaseSimpleMaterial.prototype,"disableLighting",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],PBRBaseSimpleMaterial.prototype,"environmentTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"invertNormalMapX",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"invertNormalMapY",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],PBRBaseSimpleMaterial.prototype,"normalTexture",void 0),(0,rH.gn)([(0,rb.n9)("emissive"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"emissiveColor",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"emissiveTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],PBRBaseSimpleMaterial.prototype,"occlusionStrength",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],PBRBaseSimpleMaterial.prototype,"occlusionTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],PBRBaseSimpleMaterial.prototype,"alphaCutOff",void 0),(0,rH.gn)([(0,rb.qC)()],PBRBaseSimpleMaterial.prototype,"doubleSided",null),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty",null)],PBRBaseSimpleMaterial.prototype,"lightmapTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"useLightmapAsShadowmap",void 0);let PBRMetallicRoughnessMaterial=class PBRMetallicRoughnessMaterial extends PBRBaseSimpleMaterial{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){let t=rb.p4.Clone(()=>new PBRMetallicRoughnessMaterial(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(){let e=rb.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){let r=rb.p4.Parse(()=>new PBRMetallicRoughnessMaterial(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};(0,rH.gn)([(0,rb.n9)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],PBRMetallicRoughnessMaterial.prototype,"baseColor",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],PBRMetallicRoughnessMaterial.prototype,"baseTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRMetallicRoughnessMaterial.prototype,"metallic",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRMetallicRoughnessMaterial.prototype,"roughness",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],PBRMetallicRoughnessMaterial.prototype,"metallicRoughnessTexture",void 0),(0,rv.H)("BABYLON.PBRMetallicRoughnessMaterial",PBRMetallicRoughnessMaterial);let PBRSpecularGlossinessMaterial=class PBRSpecularGlossinessMaterial extends PBRBaseSimpleMaterial{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){let t=rb.p4.Clone(()=>new PBRSpecularGlossinessMaterial(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(){let e=rb.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){let r=rb.p4.Parse(()=>new PBRSpecularGlossinessMaterial(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};(0,rH.gn)([(0,rb.n9)("diffuse"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],PBRSpecularGlossinessMaterial.prototype,"diffuseColor",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],PBRSpecularGlossinessMaterial.prototype,"diffuseTexture",void 0),(0,rH.gn)([(0,rb.n9)("specular"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],PBRSpecularGlossinessMaterial.prototype,"specularColor",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_microSurface")],PBRSpecularGlossinessMaterial.prototype,"glossiness",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],PBRSpecularGlossinessMaterial.prototype,"specularGlossinessTexture",void 0),(0,rv.H)("BABYLON.PBRSpecularGlossinessMaterial",PBRSpecularGlossinessMaterial);let ColorGradingTexture=class ColorGradingTexture extends baseTexture_BaseTexture{constructor(e,t,i=null){if(super(t),!e)return;if(this._textureMatrix=rm.y3.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{let e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){let e;let t=this._getEngine();e=t._features.support3DTextures?t.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):t.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=e,this._texture.isReady=!1,this.isCube=!1,this.is3D=t._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;let callback=i=>{let r;if("string"!=typeof i)return;let s=null,n=null,a=i.split("\n"),o=0,l=0,h=0,u=0,c=0;for(let e=0;e<a.length;e++){if(r=a[e],!ColorGradingTexture._NoneEmptyLineRegex.test(r)||0===r.indexOf("#"))continue;let t=r.split(" ");if(0===o){o=t.length,s=new Uint8Array(o*o*o*4),n=new Float32Array(o*o*o*4);continue}if(0!=o){let e=Math.max(parseInt(t[0]),0),i=Math.max(parseInt(t[1]),0),r=Math.max(parseInt(t[2]),0);c=Math.max(r,c=Math.max(i,c=Math.max(e,c)));let s=(l+u*o+h*o*o)*4;n&&(n[s+0]=e,n[s+1]=i,n[s+2]=r),++h%o==0&&(h=0,++u%o==0&&(l++,u=0))}}if(n&&s)for(let e=0;e<n.length;e++)if(e>0&&(e+1)%4==0)s[e]=255;else{let t=n[e];s[e]=t/c*255}e.is3D?(e.updateSize(o,o,o),t.updateRawTexture3D(e,s,5,!1)):(e.updateSize(o*o,o),t.updateRawTexture(e,s,5,!1)),e.isReady=!0,this._triggerOnLoad()},i=this.getScene();return i?i._loadFile(this.url,callback):t._loadFile(this.url,callback),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){let e=new ColorGradingTexture(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 ColorGradingTexture(e.name,t)).name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}};ColorGradingTexture._NoneEmptyLineRegex=/\S+/,(0,rv.H)("BABYLON.ColorGradingTexture",ColorGradingTexture);let equiRectangularCubeTexture_EquiRectangularCubeTexture=class equiRectangularCubeTexture_EquiRectangularCubeTexture extends baseTexture_BaseTexture{constructor(e,t,i,r=!1,s=!0,n=null,a=null,o=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw Error("Image url is not set");this._coordinatesMode=texture_Texture.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=o,this._noMipmap=r,this.gammaSpace=s,this._onLoad=n,this._onError=a,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?rW.w1.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(()=>this._loadTexture(),this._onError)}_loadImage(e,t){let i=this.getScene();if(!i)return;let r=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,this._noMipmap,!1,3);r.generateMipMaps=!this._noMipmap,i.addPendingData(r),r.url=this.url,r.isReady=!1,i.getEngine()._internalTexturesCache.push(r),this._texture=r;let s=document.createElement("canvas");(0,rJ.r6)(this.url,t=>{this._width=t.width,this._height=t.height,s.width=this._width,s.height=this._height;let i=s.getContext("2d");i.drawImage(t,0,0);let r=i.getImageData(0,0,t.width,t.height);this._buffer=r.data.buffer,s.remove(),e()},(e,s)=>{i.removePendingData(r),t&&t(`${this.getClassName()} could not be loaded`,s)},i?i.offlineProvider:null)}_loadTexture(){let e=this.getScene();if(!e)return;let t=(()=>{let e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=PanoramaToCubeMapTools.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){let r=t[equiRectangularCubeTexture_EquiRectangularCubeTexture._FacesMapping[e]];i.push(r)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){let t=new DataView(e),i=new Float32Array(3*e.byteLength/4),r=0;for(let s=0;s<e.byteLength;s++)(s+1)%4!=0&&(i[r++]=t.getUint8(s)/255);return i}getClassName(){return"EquiRectangularCubeTexture"}clone(){let e=this.getScene();if(!e)return this;let t=new equiRectangularCubeTexture_EquiRectangularCubeTexture(this.url,e,this._size,this._noMipmap,this.gammaSpace);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t}};equiRectangularCubeTexture_EquiRectangularCubeTexture._FacesMapping=["right","left","up","down","front","back"];let HtmlElementTexture=class HtmlElementTexture extends baseTexture_BaseTexture{constructor(e,t,i){var r,s;if(super(i.scene||i.engine),this.onLoadObservable=new rf.y$,!t||!i.engine&&!i.scene)return;i=Object.assign(Object.assign({},HtmlElementTexture._DefaultOptions),i),this._generateMipMaps=i.generateMipMaps,this._samplingMode=i.samplingMode,this._textureMatrix=rm.y3.Identity(),this._format=i.format,this.name=e,this.element=t,this._isVideo=!!t.getVideoPlaybackQuality,this._externalTexture=this._isVideo&&null!==(s=null===(r=this._engine)||void 0===r?void 0:r.createExternalTexture(t))&&void 0!==s?s:null,this.anisotropicFilteringLevel=1,this._createInternalTexture()}_createInternalTexture(){let e=0,t=0;this._isVideo?(e=this.element.videoWidth,t=this.element.videoHeight):(e=this.element.width,t=this.element.height);let i=this._getEngine();i&&(this._texture=i.createDynamicTexture(e,t,this._generateMipMaps,this._samplingMode),this._texture.format=this._format),this.update()}getTextureMatrix(){return this._textureMatrix}update(e=null){let t=this._getEngine();if(null==this._texture||null==t)return;let i=this.isReady();if(this._isVideo){let i=this.element;if(i.readyState<i.HAVE_CURRENT_DATA)return;t.updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:i,null===e||e)}else{let i=this.element;t.updateDynamicTexture(this._texture,i,null===e||e,!1,this._format)}!i&&this.isReady()&&this.onLoadObservable.notifyObservers(this)}dispose(){this.onLoadObservable.clear(),super.dispose()}};function GetTGAHeader(e){let t=0,i={id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]};return i}function UploadContent(e,t){let i,r,s,n,a,o,l,h;if(t.length<19){rT.Y.Error("Unable to load TGA file - Not enough data to contain header");return}let u=18,c=GetTGAHeader(t);if(c.id_length+u>t.length){rT.Y.Error("Unable to load TGA file - Not enough data");return}u+=c.id_length;let d=!1,p=!1,_=!1;switch(c.image_type){case 9:d=!0;case 1:p=!0;break;case 10:d=!0;case 2:break;case 11:d=!0;case 3:_=!0}let f=c.pixel_size>>3,m=c.width*c.height*f;if(p&&(r=t.subarray(u,u+=c.colormap_length*(c.colormap_size>>3))),d){let e,r,s;i=new Uint8Array(m);let n=0,a=new Uint8Array(f);for(;u<m&&n<m;)if(r=(127&(e=t[u++]))+1,128&e){for(s=0;s<f;++s)a[s]=t[u++];for(s=0;s<r;++s)i.set(a,n+s*f);n+=f*r}else{for(r*=f,s=0;s<r;++s)i[n+s]=t[u++];n+=r}}else i=t.subarray(u,u+=p?c.width*c.height:m);switch((48&c.flags)>>4){default:case 2:s=0,a=1,h=c.width,n=0,o=1,l=c.height;break;case 0:s=0,a=1,h=c.width,n=c.height-1,o=-1,l=-1;break;case 3:s=c.width-1,a=-1,h=-1,n=0,o=1,l=c.height;break;case 1:s=c.width-1,a=-1,h=-1,n=c.height-1,o=-1,l=-1}let g="_getImageData"+(_?"Grey":"")+c.pixel_size+"bits",v=lR[g](c,r,i,n,o,l,s,a,h),x=e.getEngine();x._uploadDataToTextureDirectly(e,v)}function _getImageData8bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d++)c=i[d],f[(p+h*_)*4+3]=255,f[(p+h*_)*4+2]=t[3*c+0],f[(p+h*_)*4+1]=t[3*c+1],f[(p+h*_)*4+0]=t[3*c+2];return f}function _getImageData16bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d+=2){c=i[d+0]+(i[d+1]<<8);let e=((31744&c)>>10)*255/31|0,t=((992&c)>>5)*255/31|0,r=(31&c)*255/31|0;f[(p+h*_)*4+0]=e,f[(p+h*_)*4+1]=t,f[(p+h*_)*4+2]=r,f[(p+h*_)*4+3]=32768&c?0:255}return f}function _getImageData24bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=3)_[(d+h*p)*4+3]=255,_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+1]=i[c+1],_[(d+h*p)*4+0]=i[c+2];return _}function _getImageData32bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=4)_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+1]=i[c+1],_[(d+h*p)*4+0]=i[c+2],_[(d+h*p)*4+3]=i[c+3];return _}function _getImageDataGrey8bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d++)c=i[d],f[(p+h*_)*4+0]=c,f[(p+h*_)*4+1]=c,f[(p+h*_)*4+2]=c,f[(p+h*_)*4+3]=255;return f}function _getImageDataGrey16bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=2)_[(d+h*p)*4+0]=i[c+0],_[(d+h*p)*4+1]=i[c+0],_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+3]=i[c+1];return _}HtmlElementTexture._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};let lR={GetTGAHeader,UploadContent,_getImageData8bits,_getImageData16bits,_getImageData24bits,_getImageData32bits,_getImageDataGrey8bits,_getImageDataGrey16bits};let _TGATextureLoader=class _TGATextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=GetTGAHeader(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{UploadContent(t,r)})}};rq.D._TextureLoaders.push(new _TGATextureLoader);let _HDRTextureLoader=class _HDRTextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=HDRTools.RGBE_ReadHeader(r),n=HDRTools.RGBE_ReadPixels(r,s),a=s.width*s.height,o=new Float32Array(4*a);for(let e=0;e<a;e+=1)o[4*e]=n[3*e],o[4*e+1]=n[3*e+1],o[4*e+2]=n[3*e+2],o[4*e+3]=1;i(s.width,s.height,t.generateMipMaps,!1,()=>{let e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,o)})}};rq.D._TextureLoaders.push(new _HDRTextureLoader),(eM=iM||(iM={}))[eM.cTFETC1=0]="cTFETC1",eM[eM.cTFETC2=1]="cTFETC2",eM[eM.cTFBC1=2]="cTFBC1",eM[eM.cTFBC3=3]="cTFBC3",eM[eM.cTFBC4=4]="cTFBC4",eM[eM.cTFBC5=5]="cTFBC5",eM[eM.cTFBC7=6]="cTFBC7",eM[eM.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",eM[eM.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",eM[eM.cTFASTC_4x4=10]="cTFASTC_4x4",eM[eM.cTFATC_RGB=11]="cTFATC_RGB",eM[eM.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",eM[eM.cTFRGBA32=13]="cTFRGBA32",eM[eM.cTFRGB565=14]="cTFRGB565",eM[eM.cTFBGR565=15]="cTFBGR565",eM[eM.cTFRGBA4444=16]="cTFRGBA4444",eM[eM.cTFFXT1_RGB=17]="cTFFXT1_RGB",eM[eM.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",eM[eM.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",eM[eM.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",eM[eM.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11";let lA={JSModuleURL:`${rW.w1._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${rW.w1._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},lI=null,lM=null,lD=0,_CreateWorkerAsync=()=>(lI||(lI=new Promise((e,t)=>{lM?e(lM):rW.w1.LoadFileAsync(rW.w1.GetBabylonScriptURL(lA.WasmModuleURL)).then(i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");let r=URL.createObjectURL(new Blob([`(${basis_workerFunc})()`],{type:"application/javascript"}));lM=new Worker(r);let initHandler=i=>{"init"===i.data.action?(lM.removeEventListener("message",initHandler),e(lM)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};lM.addEventListener("message",initHandler),lM.postMessage({action:"init",url:rW.w1.GetBabylonScriptURL(lA.JSModuleURL),wasmBinary:i})}).catch(t)})),lI),TranscodeAsync=(e,t)=>{let i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise((e,r)=>{_CreateWorkerAsync().then(()=>{let s=lD++,messageHandler=t=>{"transcode"===t.data.action&&t.data.id===s&&(lM.removeEventListener("message",messageHandler),t.data.success?e(t.data):r("Transcode is not supported on this device"))};lM.addEventListener("message",messageHandler);let n=new Uint8Array(i.byteLength);n.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),lM.postMessage({action:"transcode",id:s,imageData:n,config:t,ignoreSupportedFormats:!1},[n.buffer])},e=>{r(e)})})},BindTexture=(e,t)=>{var i,r;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(r=t._gl)||void 0===r?void 0:r.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},LoadTextureFromTranscodeResult=(e,t)=>{let i=e.getEngine();for(let r=0;r<t.fileInfo.images.length;r++){let s=t.fileInfo.images[r].levels[0];if(e._invertVScale=e.invertY,-1===t.format||t.format===iM.cTFRGB565){if(e.type=10,e.format=4,i._features.basisNeedsPOT&&(rE.R.Log2(s.width)%1!=0||rE.R.Log2(s.height)%1!=0)){let t=new r5.l(i,r5.S.Temp);e._invertVScale=e.invertY,t.type=10,t.format=4,t.width=s.width+3&-4,t.height=s.height+3&-4,BindTexture(t,i),i._uploadDataToTextureDirectly(t,new Uint16Array(s.transcodedPixels.buffer),r,0,4,!0),i._rescaleTexture(t,e,i.scenes[0],i._getInternalFormat(4),()=>{i._releaseTexture(t),BindTexture(e,i)})}else e._invertVScale=!e.invertY,e.width=s.width+3&-4,e.height=s.height+3&-4,e.samplingMode=2,BindTexture(e,i),i._uploadDataToTextureDirectly(e,new Uint16Array(s.transcodedPixels.buffer),r,0,4,!0)}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[r].levels.length>1;let n=lO.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,BindTexture(e,i),t.fileInfo.images[r].levels.forEach((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,r,s)}),i._features.basisNeedsPOT&&(rE.R.Log2(e.width)%1!=0||rE.R.Log2(e.height)%1!=0)&&(rW.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=texture_Texture.CLAMP_ADDRESSMODE,e._cachedWrapV=texture_Texture.CLAMP_ADDRESSMODE)}}},lO={JSModuleURL:lA.JSModuleURL,WasmModuleURL:lA.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case iM.cTFETC1:i=36196;break;case iM.cTFBC1:i=33776;break;case iM.cTFBC4:i=33779;break;case iM.cTFASTC_4x4:i=37808;break;case iM.cTFETC2:i=37496;break;case iM.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync,LoadTextureFromTranscodeResult};function basis_workerFunc(){let e={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFRGB565:14},t=null;function GetSupportedTranscodeFormat(t,i){let r=null;return t.supportedCompressionFormats&&(r=t.supportedCompressionFormats.astc?e.cTFASTC_4x4:t.supportedCompressionFormats.bc7?e.cTFBC7:t.supportedCompressionFormats.s3tc?i.hasAlpha?e.cTFBC3:e.cTFBC1:t.supportedCompressionFormats.pvrtc?i.hasAlpha?e.cTFPVRTC1_4_RGBA:e.cTFPVRTC1_4_RGB:t.supportedCompressionFormats.etc2?e.cTFETC2:t.supportedCompressionFormats.etc1?e.cTFETC1:e.cTFRGB565),r}function GetFileInfo(e){let t=e.getHasAlpha(),i=e.getNumImages(),r=[];for(let t=0;t<i;t++){let i={levels:[]},s=e.getNumLevels(t);for(let r=0;r<s;r++){let s={width:e.getImageWidth(t,r),height:e.getImageHeight(t,r)};i.levels.push(s)}r.push(i)}return{hasAlpha:t,images:r}}function TranscodeLevel(e,t,i,r,s){let n=e.getImageTranscodedSizeInBytes(t,i,r),a=new Uint8Array(n);if(!e.transcodeImage(a,t,i,r,1,0))return null;if(s){let r=e.getImageWidth(t,i)+3&-4,s=e.getImageHeight(t,i)+3&-4;a=ConvertDxtToRgb565(a,0,r,s)}return a}function ConvertDxtToRgb565(e,t,i,r){let s=new Uint16Array(4),n=new Uint16Array(i*r),a=i/4,o=r/4;for(let r=0;r<o;r++)for(let o=0;o<a;o++){let l=t+8*(r*a+o);s[0]=e[l]|e[l+1]<<8,s[1]=e[l+2]|e[l+3]<<8,s[2]=(2*(31&s[0])+1*(31&s[1]))/3|(2*(2016&s[0])+1*(2016&s[1]))/3&2016|(2*(63488&s[0])+1*(63488&s[1]))/3&63488,s[3]=(2*(31&s[1])+1*(31&s[0]))/3|(2*(2016&s[1])+1*(2016&s[0]))/3&2016|(2*(63488&s[1])+1*(63488&s[0]))/3&63488;for(let t=0;t<4;t++){let a=e[l+4+t],h=(4*r+t)*i+4*o;n[h++]=s[3&a],n[h++]=s[a>>2&3],n[h++]=s[a>>4&3],n[h++]=s[a>>6&3]}}return n}onmessage=i=>{if("init"===i.data.action){if(!t){try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}t=BASIS({wasmBinary:i.data.wasmBinary})}null!==t&&t.then(e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})})}else if("transcode"===i.data.action){let t=i.data.config,r=i.data.imageData,s=new BASIS.BasisFile(r),n=GetFileInfo(s),a=i.data.ignoreSupportedFormats?null:GetSupportedTranscodeFormat(i.data.config,n),o=!1;null===a&&(o=!0,a=n.hasAlpha?e.cTFBC3:e.cTFBC1);let l=!0;s.startTranscoding()||(l=!1);let h=[];for(let e=0;e<n.images.length&&l;e++){let i=n.images[e];if(void 0===t.loadSingleImage||t.loadSingleImage===e){let r=i.levels.length;!1===t.loadMipmapLevels&&(r=1);for(let t=0;t<r;t++){let r=i.levels[t],n=TranscodeLevel(s,e,t,a,o);if(!n){l=!1;break}r.transcodedPixels=n,h.push(r.transcodedPixels.buffer)}}}s.close(),s.delete(),o&&(a=-1),l?postMessage({action:"transcode",success:l,id:i.data.id,fileInfo:n,format:a},h):postMessage({action:"transcode",success:l,id:i.data.id})}}}Object.defineProperty(lO,"JSModuleURL",{get:function(){return lA.JSModuleURL},set:function(e){lA.JSModuleURL=e}}),Object.defineProperty(lO,"WasmModuleURL",{get:function(){return lA.WasmModuleURL},set:function(e){lA.WasmModuleURL=e}});let _BasisTextureLoader=class _BasisTextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let n=t.getEngine().getCaps(),a={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};TranscodeAsync(e,a).then(e=>{let i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;LoadTextureFromTranscodeResult(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(e=>{rW.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){let r=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};TranscodeAsync(e,s).then(e=>{let r=e.fileInfo.images[0].levels[0],s=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(r.width,r.height,s,-1!==e.format,()=>{LoadTextureFromTranscodeResult(t,e)})}).catch(e=>{rW.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),rW.w1.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,()=>{},!0)})}};rq.D._TextureLoaders.push(new _BasisTextureLoader);let MultiRenderTarget=class MultiRenderTarget extends renderTargetTexture_RenderTargetTexture{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;t<this._textures.length;t++)this._textures[t].wrapU=e}set wrapV(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapV=e}constructor(e,t,i,r,s,n){let a=!!s&&!!s.generateMipMaps&&s.generateMipMaps,o=!!s&&!!s.generateDepthTexture&&s.generateDepthTexture,l=s&&s.depthTextureFormat?s.depthTextureFormat:15,h=!s||void 0===s.doNotChangeAspectRatio||s.doNotChangeAspectRatio,u=!!s&&!!s.drawOnlyOnFirstAttachmentByDefault&&s.drawOnlyOnFirstAttachmentByDefault;if(super(e,t,r,a,h,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0),!this.isSupported){this.dispose();return}this._textureNames=n;let c=[],d=[],p=[],_=[],f=[],m=[],g=[],v=[];this._initTypes(i,c,d,p,_,f,m,g,v,s);let x=!s||void 0===s.generateDepthBuffer||s.generateDepthBuffer,T=!!s&&void 0!==s.generateStencilBuffer&&s.generateStencilBuffer;this._multiRenderTargetOptions={samplingModes:d,generateMipMaps:a,generateDepthBuffer:x,generateStencilBuffer:T,generateDepthTexture:o,depthTextureFormat:l,types:c,textureCount:i,useSRGBBuffers:p,formats:_,targetTypes:f,faceIndex:m,layerIndex:g,layerCounts:v},this._count=i,this._drawOnlyOnFirstAttachmentByDefault=u,i>0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,r,s,n,a,o,l,h){for(let u=0;u<e;u++)h&&h.types&&void 0!==h.types[u]?t.push(h.types[u]):t.push(h&&h.defaultType?h.defaultType:0),h&&h.samplingModes&&void 0!==h.samplingModes[u]?i.push(h.samplingModes[u]):i.push(texture_Texture.BILINEAR_SAMPLINGMODE),h&&h.useSRGBBuffers&&void 0!==h.useSRGBBuffers[u]?r.push(h.useSRGBBuffers[u]):r.push(!1),h&&h.formats&&void 0!==h.formats[u]?s.push(h.formats[u]):s.push(5),h&&h.targetTypes&&void 0!==h.targetTypes[u]?n.push(h.targetTypes[u]):n.push(3553),h&&h.faceIndex&&void 0!==h.faceIndex[u]?a.push(h.faceIndex[u]):a.push(0),h&&h.layerIndex&&void 0!==h.layerIndex[u]?o.push(h.layerIndex[u]):o.push(0),h&&h.layerCounts&&void 0!==h.layerCounts[u]?l.push(h.layerCounts[u]):l.push(1)}_createInternaTextureIndexMapping(){let e={},t=[];if(!this._renderTarget)return t;let i=this._renderTarget.textures;for(let r=0;r<i.length;r++){let s=i[r];if(!s)continue;let n=e[s.uniqueId];void 0!==n?t[r]=n:e[s.uniqueId]=r}return t}_rebuild(e=!1,t){if(this._count<1)return;let i=this._createInternaTextureIndexMapping();this.releaseInternalTextures(),this._createInternalTextures(),e&&(this._releaseTextures(),this._createTextures(t));let r=this._renderTarget.textures;for(let e=0;e<r.length;e++){let t=this._textures[e];void 0!==i[e]&&this._renderTarget.setTexture(r[i[e]],e),t._texture=r[e],t._texture&&(t._noMipmap=!t._texture.useMipMaps,t._useSRGBBuffer=t._texture._useSRGBBuffer)}1!==this.samples&&this._renderTarget.setSamples(this.samples,!this._drawOnlyOnFirstAttachmentByDefault,!0)}_createInternalTextures(){this._renderTarget=this._getEngine().createMultipleRenderTarget(this._size,this._multiRenderTargetOptions,!this._drawOnlyOnFirstAttachmentByDefault),this._texture=this._renderTarget.texture}_releaseTextures(){if(this._textures)for(let e=0;e<this._textures.length;e++)this._textures[e]._texture=null,this._textures[e].dispose()}_createTextures(e){let t=this._renderTarget.textures;this._textures=[];for(let i=0;i<t.length;i++){let r=new texture_Texture(null,this.getScene());(null==e?void 0:e[i])&&(r.name=e[i]),r._texture=t[i],r._texture&&(r._noMipmap=!r._texture.useMipMaps,r._useSRGBBuffer=r._texture._useSRGBBuffer),this._textures.push(r)}}setInternalTexture(e,t,i=!0){var r,s;if(this.renderTarget&&(0===t&&(this._texture=e),this.renderTarget.setTexture(e,t,i),this.textures[t]||(this.textures[t]=new texture_Texture(null,this.getScene()),this.textures[t].name=null!==(s=null===(r=this._textureNames)||void 0===r?void 0:r[t])&&void 0!==s?s:this.textures[t].name),this.textures[t]._texture=e,this.textures[t]._noMipmap=!e.useMipMaps,this.textures[t]._useSRGBBuffer=e._useSRGBBuffer,this._count=this.renderTarget.textures?this.renderTarget.textures.length:0,this._multiRenderTargetOptions.types&&(this._multiRenderTargetOptions.types[t]=e.type),this._multiRenderTargetOptions.samplingModes&&(this._multiRenderTargetOptions.samplingModes[t]=e.samplingMode),this._multiRenderTargetOptions.useSRGBBuffers&&(this._multiRenderTargetOptions.useSRGBBuffers[t]=e._useSRGBBuffer),this._multiRenderTargetOptions.targetTypes&&-1!==this._multiRenderTargetOptions.targetTypes[t])){let i=0;i=e.is2DArray?35866:e.isCube?34067:e.is3D?32879:3553,this._multiRenderTargetOptions.targetTypes[t]=i}}setLayerAndFaceIndex(e,t=-1,i=-1){this.textures[e]&&this.renderTarget&&(this._multiRenderTargetOptions.layerIndex&&(this._multiRenderTargetOptions.layerIndex[e]=t),this._multiRenderTargetOptions.faceIndex&&(this._multiRenderTargetOptions.faceIndex[e]=i),this.renderTarget.setLayerAndFaceIndex(e,t,i))}setLayerAndFaceIndices(e,t){this.renderTarget&&(this._multiRenderTargetOptions.layerIndex=e,this._multiRenderTargetOptions.faceIndex=t,this.renderTarget.setLayerAndFaceIndices(e,t))}get samples(){return this._samples}set samples(e){this._renderTarget?this._samples=this._renderTarget.setSamples(e):this._samples=e}resize(e){this._processSizeParameter(e,!1),this._rebuild(void 0,this._textureNames)}updateCount(e,t,i){this._multiRenderTargetOptions.textureCount=e,this._count=e;let r=[],s=[],n=[],a=[],o=[],l=[],h=[],u=[];this._textureNames=i,this._initTypes(e,r,s,n,a,o,l,h,u,t),this._multiRenderTargetOptions.types=r,this._multiRenderTargetOptions.samplingModes=s,this._multiRenderTargetOptions.useSRGBBuffers=n,this._multiRenderTargetOptions.formats=a,this._multiRenderTargetOptions.targetTypes=o,this._multiRenderTargetOptions.faceIndex=l,this._multiRenderTargetOptions.layerIndex=h,this._multiRenderTargetOptions.layerCounts=u,this._rebuild(!0,i)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindMultiColorAttachmentFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;let 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}}};let TexturePackerFrame=class TexturePackerFrame{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}};let TexturePacker=class TexturePacker{constructor(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_,f,m;return this.name=e,this.meshes=t,this.scene=r,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!==(n=this.options.uvsIn)&&void 0!==n?n:rz.o.UVKind,this.options.uvsOut=null!==(a=this.options.uvsOut)&&void 0!==a?a:rz.o.UVKind,this.options.layout=null!==(o=this.options.layout)&&void 0!==o?o:TexturePacker.LAYOUT_STRIP,this.options.layout===TexturePacker.LAYOUT_COLNUM&&(this.options.colnum=null!==(l=this.options.colnum)&&void 0!==l?l:8),this.options.updateInputMeshes=null===(h=this.options.updateInputMeshes)||void 0===h||h,this.options.disposeSources=null===(u=this.options.disposeSources)||void 0===u||u,this._expecting=0,this.options.fillBlanks=null===(c=this.options.fillBlanks)||void 0===c||c,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(d=this.options.customFillColor)&&void 0!==d?d:"black"),this.options.frameSize=null!==(p=this.options.frameSize)&&void 0!==p?p: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!==(f=this.options.paddingMode)&&void 0!==f?f:TexturePacker.SUBUV_WRAP,this.options.paddingMode===TexturePacker.SUBUV_COLOR&&(this.options.paddingColor=null!==(m=this.options.paddingColor)&&void 0!==m?m:new rg.HE(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){let t=this._calculateSize(),i=new rm.FM(1,1).divide(t),r=0,s=this._expecting,n=this.meshes.length,a=Object.keys(this.sets);for(let e=0;e<a.length;e++){let i=a[e],r=new DynamicTexture(this.name+".TexturePack."+i+"Set",{width:t.x,height:t.y},this.scene,!0,texture_Texture.TRILINEAR_SAMPLINGMODE,rq.D.TEXTUREFORMAT_RGBA),s=r.getContext();s.fillStyle="rgba(0,0,0,0)",s.fillRect(0,0,t.x,t.y),r.update(!1),this.sets[i]=r}let o=this.options.frameSize||256,l=this._paddingValue,h=o+2*l,done=()=>{this._calculateMeshUVFrames(o,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i<n;i++){let n=this.meshes[i],u=n.material;for(let n=0;n<a.length;n++){let c=new DynamicTexture("temp",h,this.scene,!0),d=c.getContext(),p=this._getFrameOffset(i),updateDt=()=>{r++,c.update(!1);let i=d.getImageData(0,0,h,h),n=this.sets[_],a=n.getContext();if(a.putImageData(i,t.x*p.x,t.y*p.y),c.dispose(),n.update(!1),r==s){done(),e();return}},_=a[n]||"_blank";if(u&&null!==u[_]){let e=u[_],t=new Image;e instanceof DynamicTexture?t.src=e.getContext().canvas.toDataURL("image/png"):t.src=e.url,rW.w1.SetCorsBehavior(t.src,t),t.onload=()=>{d.fillStyle="rgba(0,0,0,0)",d.fillRect(0,0,h,h),c.update(!1),d.setTransform(1,0,0,-1,0,0);let 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++)d.drawImage(t,0,0,t.width,t.height,l+o*e[i],l+o*e[i+1]-h,o,o);break;case 1:for(let e=0;e<l;e++)d.drawImage(t,0,0,t.width,t.height,e+0*o,l-h,o,o),d.drawImage(t,0,0,t.width,t.height,2*l-e,l-h,o,o),d.drawImage(t,0,0,t.width,t.height,l,e-h,o,o),d.drawImage(t,0,0,t.width,t.height,l,2*l-e-h,o,o);d.drawImage(t,0,0,t.width,t.height,l+0*o,l+0*o-h,o,o);break;case 2:d.fillStyle=(this.options.paddingColor||rg.Wo.Black()).toHexString(),d.fillRect(0,0,h,-h),d.clearRect(l,l,o,o),d.drawImage(t,0,0,t.width,t.height,l+0*o,l+0*o-h,o,o)}d.setTransform(1,0,0,1,0,0),updateDt()}}else d.fillStyle="rgba(0,0,0,0)",this.options.fillBlanks&&(d.fillStyle=this.options.customFillColor),d.fillRect(0,0,h,h),updateDt()}}}_calculateSize(){let e=this.meshes.length||0,t=this.options.frameSize||0,i=this._paddingValue||0;switch(this.options.layout){case 0:return new rm.FM(t*e+2*i*e,t+2*i);case 1:{let r=Math.max(2,Math.ceil(Math.sqrt(e))),s=t*r+2*i*r;return new rm.FM(s,s)}case 2:{let r=this.options.colnum||1,s=Math.max(1,Math.ceil(e/r));return new rm.FM(t*r+2*i*r,t*s+2*i*s)}}return rm.FM.Zero()}_calculateMeshUVFrames(e,t,i,r,s){let n=this.meshes.length;for(let a=0;a<n;a++){let n=this.meshes[a],o=new rm.FM(e/i.x,e/i.y),l=r.clone().scale(t),h=this._getFrameOffset(a),u=h.add(l),c=new TexturePackerFrame(a,o,u);this.frames.push(c),s&&(this._updateMeshUV(n,a),this._updateTextureReferences(n))}}_getFrameOffset(e){let t,i,r;let s=this.meshes.length;switch(this.options.layout){case 0:return t=1/s,new rm.FM(e*t,0);case 1:{let n=Math.max(2,Math.ceil(Math.sqrt(s)));return i=Math.floor(e/n),r=e-i*n,t=1/n,new rm.FM(r*t,i*t)}case 2:{let n=this.options.colnum||1,a=Math.max(1,Math.ceil(s/n));return r=Math.floor(e/a),i=e-r*a,t=new rm.FM(1/n,1/a),new rm.FM(r*t.x,i*t.y)}}return rm.FM.Zero()}_updateMeshUV(e,t){let i=this.frames[t],r=e.getVerticesData(this.options.uvsIn||rz.o.UVKind),s=[],n=0;r.length&&(n=r.length||0);for(let e=0;e<n;e+=2)s.push(r[e]*i.scale.x+i.offset.x,r[e+1]*i.scale.y+i.offset.y);e.setVerticesData(this.options.uvsOut||rz.o.UVKind,s)}_updateTextureReferences(e,t=!1){let i=e.material,r=Object.keys(this.sets),_dispose=e=>{e.dispose&&e.dispose()};for(let e=0;e<r.length;e++){let s=r[e];if(t)null!==i[s]&&_dispose(i[s]),i[s]=this.sets[s];else{if(!i)return;null!==i[s]&&(_dispose(i[s]),i[s]=this.sets[s])}}}setMeshToFrame(e,t,i=!1){this._updateMeshUV(e,t),i&&this._updateTextureReferences(e,!0)}processAsync(){return new Promise((e,t)=>{try{if(0===this.meshes.length){e();return}let t=0,doneCheck=i=>{if(t++,this.options.map){for(let e=0;e<this.options.map.length;e++){let t=this.options.map[e],r=i[t];null!==r&&(this.sets[this.options.map[e]]||(this.sets[this.options.map[e]]=!0),this._expecting++)}t===this.meshes.length&&this._createFrames(e)}};for(let i=0;i<this.meshes.length;i++){let r=this.meshes[i],s=r.material;if(!s){if(++t===this.meshes.length)return this._createFrames(e);continue}s.forceCompilationAsync(r).then(()=>{doneCheck(s)})}}catch(e){return t(e)}})}dispose(){let e=Object.keys(this.sets);for(let t=0;t<e.length;t++){let i=e[t];this.sets[i].dispose()}}download(e="png",t=1){setTimeout(()=>{let i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;s<r.length;s++){let n=r[s],a=this.sets[n];i.sets[n]=a.getContext().canvas.toDataURL("image/"+e,t)}for(let e=0;e<s.length;e++){let t=s[e];i.options[t]=this.options[t]}for(let e=0;e<this.frames.length;e++){let t=this.frames[e];i.frames.push(t.scale.x,t.scale.y,t.offset.x,t.offset.y)}}catch(e){rT.Y.Warn("Unable to download: "+e);return}let n="data:text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(i,null,4)),a=document.createElement("a");a.setAttribute("href",n),a.setAttribute("download",this.name+"_texurePackage.json"),document.body.appendChild(a),a.click(),a.remove()},0)}updateFromJSON(e){try{let t=JSON.parse(e);this.name=t.name;let i=Object.keys(t.options);for(let e=0;e<i.length;e++)this.options[i[e]]=t.options[i[e]];for(let e=0;e<t.frames.length;e+=4){let i=new TexturePackerFrame(e/4,new rm.FM(t.frames[e],t.frames[e+1]),new rm.FM(t.frames[e+2],t.frames[e+3]));this.frames.push(i)}let r=Object.keys(t.sets);for(let e=0;e<r.length;e++){let i=new texture_Texture(t.sets[r[e]],this.scene,!1,!1);this.sets[r[e]]=i}}catch(e){rT.Y.Warn("Unable to update from JSON: "+e)}}};TexturePacker.LAYOUT_STRIP=0,TexturePacker.LAYOUT_POWER2=1,TexturePacker.LAYOUT_COLNUM=2,TexturePacker.SUBUV_WRAP=0,TexturePacker.SUBUV_EXTEND=1,TexturePacker.SUBUV_COLOR=2;let lN=`uniform float brightness;uniform float persistence;uniform float timeScale;varying vec2 vUV;vec2 hash22(vec2 p) +{p=p*mat2(127.1,311.7,269.5,183.3);p=-1.0+2.0*fract(sin(p)*43758.5453123);return sin(p*6.283+timeScale);} +float interpolationNoise(vec2 p) +{vec2 pi=floor(p);vec2 pf=p-pi;vec2 w=pf*pf*(3.-2.*pf);float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));float xm1=mix(f00,f10,w.x);float xm2=mix(f01,f11,w.x);float ym=mix(xm1,xm2,w.y); +return ym;} +float perlinNoise2D(float x,float y) +{float sum=0.0;float frequency=0.0;float amplitude=0.0;for(int i=0; i<OCTAVES; i++) +{frequency=pow(2.0,float(i));amplitude=pow(persistence,float(i));sum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;} +return sum;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float x=abs(vUV.x);float y=abs(vUV.y);float noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);gl_FragColor=vec4(noise,noise,noise,1.0);} +`;s_.v.ShadersStore.noisePixelShader=lN;let NoiseProceduralTexture=class NoiseProceduralTexture extends proceduralTexture_ProceduralTexture{constructor(e,t=256,i=rS.l.LastCreatedScene,r,s){super(e,t,"noise",i,r,s),this.time=0,this.brightness=.2,this.octaves=3,this.persistence=.8,this.animationSpeedFactor=1,this.autoClear=!1,this._updateShaderUniforms()}_updateShaderUniforms(){let e=this.getScene();e&&(this.time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this.time))}_getDefines(){return"#define OCTAVES "+(0|this.octaves)}render(e){this._updateShaderUniforms(),super.render(e)}serialize(){let e={};return e.customType="BABYLON.NoiseProceduralTexture",e.brightness=this.brightness,e.octaves=this.octaves,e.persistence=this.persistence,e.animationSpeedFactor=this.animationSpeedFactor,e.size=this.getSize().width,e.generateMipMaps=this._generateMipMaps,e.time=this.time,e}clone(){let e=this.getSize(),t=new NoiseProceduralTexture(this.name,e.width,this.getScene(),this._fallbackTexture?this._fallbackTexture:void 0,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t.brightness=this.brightness,t.octaves=this.octaves,t.persistence=this.persistence,t.animationSpeedFactor=this.animationSpeedFactor,t.time=this.time,t}static Parse(e,t){var i;let r=new NoiseProceduralTexture(e.name,e.size,t,void 0,e.generateMipMaps);return r.brightness=e.brightness,r.octaves=e.octaves,r.persistence=e.persistence,r.animationSpeedFactor=e.animationSpeedFactor,r.time=null!==(i=e.time)&&void 0!==i?i:0,r}};(0,rv.H)("BABYLON.NoiseProceduralTexture",NoiseProceduralTexture);let NodeMaterialConnectionPointCustomObject=class NodeMaterialConnectionPointCustomObject extends NodeMaterialConnectionPoint{constructor(e,t,i,r,s){super(e,t,i),this._blockType=r,this._blockName=s,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof NodeMaterialConnectionPointCustomObject&&e._blockName===this._blockName?tv.Compatible:tv.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}};let BonesBlock=class BonesBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Vertex),this.registerInput("matricesIndices",tm.Vector4),this.registerInput("matricesWeights",tm.Vector4),this.registerInput("matricesIndicesExtra",tm.Vector4,!0),this.registerInput("matricesWeightsExtra",tm.Vector4,!0),this.registerInput("world",tm.Matrix),this.registerOutput("output",tm.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesIndices"===e.name&&t(e));i||(i=new InputBlock("matricesIndices")).setAsAttribute("matricesIndices"),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesWeights"===e.name&&t(e));i||(i=new InputBlock("matricesWeights")).setAsAttribute("matricesWeights"),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(tC.World),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){so.G.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&so.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");let t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});let i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});let r=this._outputs[0],s=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 +`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName} * ${i}; +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName}; +`,e.compilationString+=`#endif +`,this}};(0,rv.H)("BABYLON.BonesBlock",BonesBlock);let InstancesBlock=class InstancesBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Vertex),this.registerInput("world0",tm.Vector4),this.registerInput("world1",tm.Vector4),this.registerInput("world2",tm.Vector4),this.registerInput("world3",tm.Vector4),this.registerInput("world",tm.Matrix,!0),this.registerOutput("output",tm.Matrix),this.registerOutput("instanceID",tm.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=()=>!0){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world0"===e.name&&t(e));i||(i=new InputBlock("world0")).setAsAttribute("world0"),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world1"===e.name&&t(e));i||(i=new InputBlock("world1")).setAsAttribute("world1"),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world2"===e.name&&t(e));i||(i=new InputBlock("world2")).setAsAttribute("world2"),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world3"===e.name&&t(e));i||(i=new InputBlock("world3")).setAsAttribute("world3"),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world"===e.name&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(tC.World),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,s){let n=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),n=!0),s&&!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)!==i.THIN_INSTANCES&&(i.setValue("THIN_INSTANCES",!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);let t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);let i=this._outputs[0],r=this._outputs[1],s=this.world0,n=this.world1,a=this.world2,o=this.world3;return e.compilationString+=`#ifdef INSTANCES +`,e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${n.associatedVariableName}, ${a.associatedVariableName}, ${o.associatedVariableName}); +`,e.compilationString+=`#ifdef THIN_INSTANCES +`,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName}; +`,e.compilationString+=`#endif +`,t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(r,e)+` = float(gl_InstanceID); +`:e.compilationString+=this._declareOutput(r,e)+` = 0.0; +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName}; +`,e.compilationString+=this._declareOutput(r,e)+` = 0.0; +`,e.compilationString+=`#endif +`,this}};(0,rv.H)("BABYLON.InstancesBlock",InstancesBlock);let MorphTargetsBlock=class MorphTargetsBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Vertex),this.registerInput("position",tm.Vector3),this.registerInput("normal",tm.Vector3),this.registerInput("tangent",tm.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(tm.Color4|tm.Vector4|tm.Vector3),this.registerInput("uv",tm.Vector2),this.registerOutput("positionOutput",tm.Vector3),this.registerOutput("normalOutput",tm.Vector3),this.registerOutput("tangentOutput",tm.Vector4),this.registerOutput("uvOutput",tm.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new InputBlock("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new InputBlock("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&t(e));i||(i=new InputBlock("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute("uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){let t=e.morphTargetManager;(null==t?void 0:t.isUsingTextureForTargets)&&t.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&so.G.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(so.G.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){let s=this.position,n=this.normal,a=this.tangent,o=this.uv,l=this.positionOutput,h=this.normalOutput,u=this.tangentOutput,c=this.uvOutput,d=r.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,_=p&&p.supportsNormals&&r.NORMAL,f=p&&p.supportsTangents&&r.TANGENT,m=p&&p.supportsUVs&&r.UV1,g="";(null==p?void 0:p.isUsingTextureForTargets)&&d>0&&(g+=`float vertexID; +`);for(let e=0;e<d;e++)g+=`#ifdef MORPHTARGETS +`,(null==p?void 0:p.isUsingTextureForTargets)?g+=`vertexID = float(gl_VertexID) * morphTargetTextureInfo.x; +${l.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID) - ${s.associatedVariableName}) * morphTargetInfluences[${e}]; +vertexID += 1.0; +`:g+=`${l.associatedVariableName} += (position${e} - ${s.associatedVariableName}) * morphTargetInfluences[${e}]; +`,_&&(g+=`#ifdef MORPHTARGETS_NORMAL +`,(null==p?void 0:p.isUsingTextureForTargets)?g+=`${h.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID) - ${n.associatedVariableName}) * morphTargetInfluences[${e}]; +vertexID += 1.0; +`:g+=`${h.associatedVariableName} += (normal${e} - ${n.associatedVariableName}) * morphTargetInfluences[${e}]; +`,g+=`#endif +`),m&&(g+=`#ifdef MORPHTARGETS_UV +`,(null==p?void 0:p.isUsingTextureForTargets)?g+=`${c.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID).xy - ${o.associatedVariableName}) * morphTargetInfluences[${e}]; +vertexID += 1.0; +`:g+=`${c.associatedVariableName}.xy += (uv_${e} - ${o.associatedVariableName}.xy) * morphTargetInfluences[${e}]; +`,g+=`#endif +`),f&&(g+=`#ifdef MORPHTARGETS_TANGENT +`,(null==p?void 0:p.isUsingTextureForTargets)?g+=`${u.associatedVariableName}.xyz += (readVector3FromRawSampler(${e}, vertexID) - ${a.associatedVariableName}.xyz) * morphTargetInfluences[${e}]; +`:g+=`${u.associatedVariableName}.xyz += (tangent${e} - ${a.associatedVariableName}.xyz) * morphTargetInfluences[${e}]; +`,a.type===tm.Vector4?g+=`${u.associatedVariableName}.w = ${a.associatedVariableName}.w; +`:g+=`${u.associatedVariableName}.w = 1.; +`,g+=`#endif +`),g+=`#endif +`;if(e.compilationString=e.compilationString.replace(this._repeatableContentAnchor,g),d>0)for(let t=0;t<d;t++)e.attributes.push(rz.o.PositionKind+t),_&&e.attributes.push(rz.o.NormalKind+t),f&&e.attributes.push(rz.o.TangentKind+t),m&&e.attributes.push(rz.o.UVKind+"_"+t)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);let t=this.position,i=this.normal,r=this.tangent,s=this.uv,n=this.positionOutput,a=this.normalOutput,o=this.tangentOutput,l=this.uvOutput,h=`//${this.name}`;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",h),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",h,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=`${this._declareOutput(n,e)} = ${t.associatedVariableName}; +`,e.compilationString+=`#ifdef NORMAL +`,e.compilationString+=`${this._declareOutput(a,e)} = ${i.associatedVariableName}; +`,e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(a,e)} = vec3(0., 0., 0.); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef TANGENT +`,e.compilationString+=`${this._declareOutput(o,e)} = ${r.associatedVariableName}; +`,e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(o,e)} = vec4(0., 0., 0., 0.); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef UV1 +`,e.compilationString+=`${this._declareOutput(l,e)} = ${s.associatedVariableName}; +`,e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(l,e)} = vec2(0., 0.); +`,e.compilationString+=`#endif +`,this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this}};(0,rv.H)("BABYLON.MorphTargetsBlock",MorphTargetsBlock);let LightInformationBlock=class LightInformationBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Vertex),this.registerInput("worldPosition",tm.Vector4,!1,tg.Vertex),this.registerOutput("direction",tm.Vector3),this.registerOutput("color",tm.Color3),this.registerOutput("intensity",tm.Float),this.registerOutput("shadowBias",tm.Float),this.registerOutput("shadowNormalBias",tm.Float),this.registerOutput("shadowDepthScale",tm.Float),this.registerOutput("shadowDepthRange",tm.Vector2)}getClassName(){return"LightInformationBlock"}get worldPosition(){return this._inputs[0]}get direction(){return this._outputs[0]}get color(){return this._outputs[1]}get intensity(){return this._outputs[2]}get shadowBias(){return this._outputs[3]}get shadowNormalBias(){return this._outputs[4]}get shadowDepthScale(){return this._outputs[5]}get shadowDepthRange(){return this._outputs[6]}bind(e,t,i){if(!i)return;this.light&&this.light.isDisposed()&&(this.light=null);let r=this.light,s=t.getScene();if(!r&&s.lights.length&&(r=this.light=s.lights[0],this._forcePrepareDefines=!0),!r||!r.isEnabled){e.setFloat3(this._lightDataUniformName,0,0,0),e.setFloat4(this._lightColorUniformName,0,0,0,0);return}r.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,r.diffuse,r.intensity);let n=r.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(n?e.setFloat3(this._lightShadowUniformName,n.bias,n.normalBias,n.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange){if(n&&s.activeCamera){let t=r;e.setFloat2(this._lightShadowExtraUniformName,t.getDepthMinZ(s.activeCamera),t.getDepthMinZ(s.activeCamera)+t.getDepthMaxZ(s.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}}prepareDefines(e,t,i){if(!i._areLightsDirty&&!this._forcePrepareDefines)return;this._forcePrepareDefines=!1;let r=this.light;i.setValue(this._lightTypeDefineName,!!r&&r instanceof PointLight,!0)}_buildBlock(e){super._buildBlock(e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);let t=this.direction,i=this.color,r=this.intensity,s=this.shadowBias,n=this.shadowNormalBias,a=this.shadowDepthScale,o=this.shadowDepthRange;return this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightShadowUniformName=e._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=e._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE"),e._emitUniformFromString(this._lightDataUniformName,"vec3"),e._emitUniformFromString(this._lightColorUniformName,"vec4"),e.compilationString+=`#ifdef ${this._lightTypeDefineName} +`,e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName}); +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(t,e)+` = ${this._lightDataUniformName}; +`,e.compilationString+=`#endif +`,e.compilationString+=this._declareOutput(i,e)+` = ${this._lightColorUniformName}.rgb; +`,e.compilationString+=this._declareOutput(r,e)+` = ${this._lightColorUniformName}.a; +`,(s.hasEndpoints||n.hasEndpoints||a.hasEndpoints)&&(e._emitUniformFromString(this._lightShadowUniformName,"vec3"),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${this._lightShadowUniformName}.x; +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${this._lightShadowUniformName}.y; +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${this._lightShadowUniformName}.z; +`)),o.hasEndpoints&&(e._emitUniformFromString(this._lightShadowExtraUniformName,"vec2"),e.compilationString+=this._declareOutput(o,e)+` = ${this._lightShadowUniformName}; +`),this}serialize(){let e=super.serialize();return 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))}};(0,rv.H)("BABYLON.LightInformationBlock",LightInformationBlock);let ImageProcessingBlock=class ImageProcessingBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.convertInputToLinearSpace=!0,this.registerInput("color",tm.AutoDetect),this.registerOutput("output",tm.Color4),this.registerOutput("rgb",tm.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Color4|tm.Vector3|tm.Vector4)}getClassName(){return"ImageProcessingBlock"}get color(){return this._inputs[0]}get output(){return this._outputs[0]}get rgb(){return this._outputs[1]}initialize(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")}isReady(e,t,i){return!i._areImageProcessingDirty||!t.imageProcessingConfiguration||!!t.imageProcessingConfiguration.isReady()}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_buildBlock(e){var t;super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity");let i=this.color,r=this._outputs[0],s=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("imageProcessingDeclaration",s),e._emitFunctionFromInclude("imageProcessingFunctions",s),(null===(t=i.connectedPoint)||void 0===t?void 0:t.isConnected)&&(i.connectedPoint.type===tm.Color4||i.connectedPoint.type===tm.Vector4?e.compilationString+=`${this._declareOutput(r,e)} = ${i.associatedVariableName}; +`:e.compilationString+=`${this._declareOutput(r,e)} = vec4(${i.associatedVariableName}, 1.0); +`,e.compilationString+=`#ifdef IMAGEPROCESSINGPOSTPROCESS +`,this.convertInputToLinearSpace&&(e.compilationString+=`${r.associatedVariableName}.rgb = toLinearSpace(${i.associatedVariableName}.rgb); +`),e.compilationString+=`#else +`,e.compilationString+=`#ifdef IMAGEPROCESSING +`,this.convertInputToLinearSpace&&(e.compilationString+=`${r.associatedVariableName}.rgb = toLinearSpace(${i.associatedVariableName}.rgb); +`),e.compilationString+=`${r.associatedVariableName} = applyImageProcessing(${r.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#endif +`,this.rgb.hasEndpoints&&(e.compilationString+=this._declareOutput(this.rgb,e)+` = ${this.output.associatedVariableName}.xyz; +`)),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace}; +`}serialize(){let e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.convertInputToLinearSpace=null===(r=e.convertInputToLinearSpace)||void 0===r||r}};(0,rH.gn)([editableInPropertyPage("Convert input to linear space",tT.Boolean,"ADVANCED")],ImageProcessingBlock.prototype,"convertInputToLinearSpace",void 0),(0,rv.H)("BABYLON.ImageProcessingBlock",ImageProcessingBlock);let TBNBlock=class TBNBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment,!0),this.registerInput("normal",tm.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(tm.Color4|tm.Vector4|tm.Vector3),this.registerInput("tangent",tm.Vector4,!1),this.registerInput("world",tm.Matrix,!1),this.registerOutput("TBN",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("TBN",this,tx.Output,TBNBlock,"TBNBlock")),this.registerOutput("row0",tm.Vector3,tg.Fragment),this.registerOutput("row1",tm.Vector3,tg.Fragment),this.registerOutput("row2",tm.Vector3,tg.Fragment)}getClassName(){return"TBNBlock"}initialize(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")}get normal(){return this._inputs[0]}get tangent(){return this._inputs[1]}get world(){return this._inputs[2]}get TBN(){return this._outputs[0]}get row0(){return this._outputs[1]}get row1(){return this._outputs[2]}get row2(){return this._outputs[3]}get target(){return tg.Fragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.isSystemValue&&e.systemValue===tC.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(tC.World),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new InputBlock("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&e.type===tm.Vector4&&t(e));i||(i=new InputBlock("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var r,s,n,a;let o=this.normal,l=this.tangent,h=o.isConnected;(null===(r=o.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(s=o.connectInputBlock)||void 0===s?void 0:s.name)&&(h=!1);let u=l.isConnected;(null===(n=l.connectInputBlock)||void 0===n?void 0:n.isAttribute)&&!e.isVerticesDataPresent(null===(a=l.connectInputBlock)||void 0===a?void 0:a.name)&&(u=!1);let c=h&&u;i.setValue("TBNBLOCK",c,!0)}_buildBlock(e){super._buildBlock(e);let t=this.normal,i=this.tangent,r=this.world,s=this.TBN,n=this.row0,a=this.row1,o=this.row2;return e.target===tg.Fragment&&(e.compilationString+=` + // ${this.name} + vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz; + vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz); + vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; + mat3 ${s.associatedVariableName} = mat3(${r.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); + `,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]); +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]); +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]); +`),e.sharedData.blocksWithDefines.push(this)),this}};(0,rv.H)("BABYLON.TBNBlock",TBNBlock);let PerturbNormalBlock=class PerturbNormalBlock extends NodeMaterialBlock{constructor(e){super(e,tg.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",tm.Vector4,!1),this.registerInput("worldNormal",tm.Vector4,!1),this.registerInput("worldTangent",tm.Vector4,!0),this.registerInput("uv",tm.Vector2,!1),this.registerInput("normalMapColor",tm.Color3,!1),this.registerInput("strength",tm.Float,!1),this.registerInput("viewDirection",tm.Vector3,!0),this.registerInput("parallaxScale",tm.Float,!0),this.registerInput("parallaxHeight",tm.Float,!0),this.registerInput("TBN",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("TBN",this,tx.Input,TBNBlock,"TBNBlock")),this.registerInput("world",tm.Matrix,!0),this.registerOutput("output",tm.Vector4),this.registerOutput("uvOffset",tm.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){let r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute(),i.output.connectTo(this.uv)}if(!this.strength.isConnected){let e=new InputBlock("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`,i=this.uv,r=this.worldPosition,s=this.worldNormal,n=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 a=null;this.normalMapColor.connectedPoint&&(a=this.normalMapColor.connectedPoint._ownerBlock.samplerName);let o=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&a||!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?` +#if !defined(NORMALXYSCALE) +1.0/ +#endif +${e._emitFloat(this.strength.connectInputBlock.value)}`:` +#if !defined(NORMALXYSCALE) +1.0/ +#endif +${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let u={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},c=this.TBN;c.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${c.associatedVariableName}; + #endif + `:n.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +`,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[u,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include<samplerFragmentDeclaration>\(_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\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_"}]});let d=o&&a?`texture2D(${a}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${d}`},{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, ${d}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o&&this.useParallaxOcclusion?a:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${o?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:r.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:o?this.viewDirection.associatedVariableName:"vec3(0.)"},u]}),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX}; +`+`${this._codeVariableName}.invertY = ${this.invertY}; +${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion}; +${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap}; +`}serialize(){let 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,rH.gn)([editableInPropertyPage("Invert X axis",tT.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"invertX",void 0),(0,rH.gn)([editableInPropertyPage("Invert Y axis",tT.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"invertY",void 0),(0,rH.gn)([editableInPropertyPage("Use parallax occlusion",tT.Boolean)],PerturbNormalBlock.prototype,"useParallaxOcclusion",void 0),(0,rH.gn)([editableInPropertyPage("Object Space Mode",tT.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"useObjectSpaceNormalMap",void 0),(0,rv.H)("BABYLON.PerturbNormalBlock",PerturbNormalBlock);let DiscardBlock=class DiscardBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment,!0),this.registerInput("value",tm.Float,!0),this.registerInput("cutoff",tm.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard; +`,this}};(0,rv.H)("BABYLON.DiscardBlock",DiscardBlock);let FrontFacingBlock=class FrontFacingBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerOutput("output",tm.Float,tg.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===tg.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = gl_FrontFacing ? 1.0 : 0.0; +`,this}};(0,rv.H)("BABYLON.FrontFacingBlock",FrontFacingBlock);let DerivativeBlock=class DerivativeBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerInput("input",tm.AutoDetect,!1),this.registerOutput("dx",tm.BasedOnInput),this.registerOutput("dy",tm.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);let 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}); +`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName}); +`),this}};(0,rv.H)("BABYLON.DerivativeBlock",DerivativeBlock);let FragCoordBlock=class FragCoordBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerOutput("xy",tm.Vector2,tg.Fragment),this.registerOutput("xyz",tm.Vector3,tg.Fragment),this.registerOutput("xyzw",tm.Vector4,tg.Fragment),this.registerOutput("x",tm.Float,tg.Fragment),this.registerOutput("y",tm.Float,tg.Fragment),this.registerOutput("z",tm.Float,tg.Fragment),this.registerOutput("w",tm.Float,tg.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(let i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name}; +`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===tg.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}};(0,rv.H)("BABYLON.FragCoordBlock",FragCoordBlock);let ScreenSizeBlock=class ScreenSizeBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerOutput("xy",tm.Vector2,tg.Fragment),this.registerOutput("x",tm.Float,tg.Fragment),this.registerOutput("y",tm.Float,tg.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){let t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; +`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===tg.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,rv.H)("BABYLON.ScreenSizeBlock",ScreenSizeBlock);let ScreenSpaceBlock=class ScreenSpaceBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerInput("vector",tm.AutoDetect),this.registerInput("worldViewProjection",tm.Matrix),this.registerOutput("output",tm.Vector2),this.registerOutput("x",tm.Float),this.registerOutput("y",tm.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.WorldViewProjection&&t(e));i||(i=new InputBlock("worldViewProjection")).setAsSystemValue(tC.WorldViewProjection),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;let r=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case tm.Vector3:e.compilationString+=`vec4 ${s} = ${r} * vec4(${t.associatedVariableName}, 1.0); +`;break;case tm.Vector4:e.compilationString+=`vec4 ${s} = ${r} * ${t.associatedVariableName}; +`}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; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y; +`),this}};(0,rv.H)("BABYLON.ScreenSpaceBlock",ScreenSpaceBlock);let TwirlBlock=class TwirlBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerInput("input",tm.Vector2),this.registerInput("strength",tm.Float),this.registerInput("center",tm.Vector2),this.registerInput("offset",tm.Vector2),this.registerOutput("output",tm.Vector2),this.registerOutput("x",tm.Float),this.registerOutput("y",tm.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){let e=new InputBlock("center");e.value=new rm.FM(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){let e=new InputBlock("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){let e=new InputBlock("offset");e.value=new rm.FM(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);let t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` + vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; + float ${i} = ${this.strength.associatedVariableName} * length(${t}); + float ${r} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; + float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; + vec2 ${n} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); + `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${n}; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${n}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${n}.y; +`),this}};(0,rv.H)("BABYLON.TwirlBlock",TwirlBlock);let HeightToNormalBlock=class HeightToNormalBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",tm.Float),this.registerInput("worldPosition",tm.Vector3),this.registerInput("worldNormal",tm.Vector3),this.registerInput("worldTangent",tm.AutoDetect,!0),this.registerOutput("output",tm.Vector4),this.registerOutput("xyz",tm.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.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);let t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`);let i=this.generateInWorldSpace?"":` + vec3 biTangent = cross(normal, tangent); + mat3 TBN = mat3(tangent, biTangent, normal); + `,r=this.generateInWorldSpace?"":` + result = TBN * result; + result = result * vec3(0.5) + vec3(0.5); + `,s=` + vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { + ${i} + ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""} + ${this.automaticNormalizationNormal?"normal = normalize(normal);":""} + vec3 worlddX = dFdx(position); + vec3 worlddY = dFdy(position); + vec3 crossX = cross(normal, worlddX); + vec3 crossY = cross(normal, worlddY); + float d = abs(dot(crossY, worlddX)); + vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); + inToNormal.y *= -1.0; + vec3 result = normalize((d * normal) - inToNormal); + ${r} + return vec4(result, 0.); + }`;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}); +`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; +`),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace}; +${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal}; +${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent}; +`}serialize(){let 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,rH.gn)([editableInPropertyPage("Generate in world space instead of tangent space",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"generateInWorldSpace",void 0),(0,rH.gn)([editableInPropertyPage("Force normalization for the worldNormal input",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"automaticNormalizationNormal",void 0),(0,rH.gn)([editableInPropertyPage("Force normalization for the worldTangent input",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"automaticNormalizationTangent",void 0),(0,rv.H)("BABYLON.HeightToNormalBlock",HeightToNormalBlock);let FragDepthBlock=class FragDepthBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment,!0),this.registerInput("depth",tm.Float,!0),this.registerInput("worldPos",tm.Vector4,!0),this.registerInput("viewProjection",tm.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName}; +`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=` + vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; + float v = p.z / p.w; + #ifndef IS_NDC_HALF_ZRANGE + v = v * 0.5 + 0.5; + #endif + gl_FragDepth = v; + + `:console.warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}};(0,rv.H)("BABYLON.FragDepthBlock",FragDepthBlock);let ShadowMapBlock=class ShadowMapBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerInput("worldPosition",tm.Vector4,!1),this.registerInput("viewProjection",tm.Matrix,!1),this.registerInput("worldNormal",tm.AutoDetect,!0),this.registerOutput("depth",tm.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.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);let 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}; +`,e.compilationString+=`vec3 vPositionWSM; +`,e.compilationString+=`float vDepthMetricSM = 0.0; +`,e.compilationString+=`float zSM; +`,this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos; +`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+=` + #if SM_DEPTHTEXTURE == 1 + #ifdef IS_NDC_HALF_ZRANGE + gl_FragDepth = (clipPos.z / clipPos.w); + #else + gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5; + #endif + #endif + `,e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.); +`,this}};(0,rv.H)("BABYLON.ShadowMapBlock",ShadowMapBlock);let PrePassOutputBlock=class PrePassOutputBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment,!0),this.registerInput("viewDepth",tm.Float,!0),this.registerInput("worldPosition",tm.AutoDetect,!0),this.registerInput("viewNormal",tm.AutoDetect,!0),this.registerInput("reflectivity",tm.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(tm.Vector3|tm.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(tm.Vector3|tm.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(tm.Vector3|tm.Vector4|tm.Color3|tm.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);let t=this.worldPosition,i=this.viewNormal,r=this.viewDepth,s=this.reflectivity;e.sharedData.blocksWithDefines.push(this);let n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`#ifdef PREPASS_DEPTH\r +`,r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${r.associatedVariableName}, 0.0, 0.0, 1.0);\r +`:e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_POSITION\r +`,t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===tm.Vector4?t.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_NORMAL\r +`,i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===tm.Vector4?i.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r +`,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${s.associatedVariableName}.rgb, ${s.connectedPoint.type===tm.Vector4?s.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#endif\r +`,this}};(0,rv.H)("BABYLON.PrePassOutputBlock",PrePassOutputBlock);let FogBlock=class FogBlock extends NodeMaterialBlock{constructor(e){super(e,tg.VertexAndFragment,!1),this.registerInput("worldPosition",tm.Vector4,!1,tg.Vertex),this.registerInput("view",tm.Matrix,!1,tg.Vertex),this.registerInput("input",tm.AutoDetect,!1,tg.Fragment),this.registerInput("fogColor",tm.AutoDetect,!1,tg.Fragment),this.registerOutput("output",tm.Color3,tg.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(tC.View),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.FogColor&&t(e));i||(i=new InputBlock("fogColor",void 0,tm.Color3)).setAsSystemValue(tC.FogColor),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){let r=e.getScene();i.setValue("FOG",t.fogEnabled&&so.G.GetFogState(e,r))}bind(e,t,i){if(!i)return;let r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===tg.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)"}]});let t=e._getFreeVariableName("fog"),i=this.input,r=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");let s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+=`#ifdef FOG +`,e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters}); +`,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${r.associatedVariableName}.rgb; +`,e.compilationString+=`#else +${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb; +`,e.compilationString+=`#endif +`}else{let 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; +`}return this}};(0,rv.H)("BABYLON.FogBlock",FogBlock);let LightBlock=class LightBlock extends NodeMaterialBlock{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?tg.Fragment:tg.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tg.Fragment:tg.Vertex}constructor(e){super(e,tg.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",tm.Vector4,!1,tg.Vertex),this.registerInput("worldNormal",tm.Vector4,!1,tg.Fragment),this.registerInput("cameraPosition",tm.Vector3,!1,tg.Fragment),this.registerInput("glossiness",tm.Float,!0,tg.Fragment),this.registerInput("glossPower",tm.Float,!0,tg.Fragment),this.registerInput("diffuseColor",tm.Color3,!0,tg.Fragment),this.registerInput("specularColor",tm.Color3,!0,tg.Fragment),this.registerInput("view",tm.Matrix,!0),this.registerOutput("diffuseOutput",tm.Color3,tg.Fragment),this.registerOutput("specularOutput",tm.Color3,tg.Fragment),this.registerOutput("shadow",tm.Float,tg.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(tC.CameraPosition),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;let r=e.getScene();if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};so.G.PrepareDefinesForLight(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else so.G.PrepareDefinesForLights(r,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s<t.maxSimultaneousLights&&i["LIGHT"+s];s++){let t=e.uniforms.indexOf("vLightData"+s)>=0;so.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}bind(e,t,i){if(!i)return;let r=i.getScene();this.light?so.G.BindLight(this.light,this._lightId,r,e,!0):so.G.BindLights(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){let 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));let r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${t.associatedVariableName}; +`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==tg.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);let t=`//${this.name}`,i=this.worldPosition,r=i.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${r}; +`,t),e.compilationString+=`${r} = ${i.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):r="v_"+r+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),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} - ${r}); +`),e.compilationString+=`lightingInfo info; +`,e.compilationString+=`float shadow = 1.; +`,e.compilationString+=`float aggShadow = 0.; +`,e.compilationString+=`float numLights = 0.; +`,e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; +`,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.); +`,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.); +`,e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz; +`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),0===this._lightId&&(e.compilationString+=`aggShadow = aggShadow / numLights; +`);let s=this.diffuseOutput,n=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; +`,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""}; +`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = aggShadow; +`),this}serialize(){let 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,rH.gn)([editableInPropertyPage("Generate only fragment code",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:LightBlock._OnGenerateOnlyFragmentCodeChanged}})],LightBlock.prototype,"generateOnlyFragmentCode",void 0),(0,rv.H)("BABYLON.LightBlock",LightBlock);let ImageSourceBlock=class ImageSourceBlock extends NodeMaterialBlock{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rS.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,tg.VertexAndFragment),this.registerOutput("source",tm.Object,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,tx.Output,ImageSourceBlock,"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===tg.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}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let 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&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};(0,rv.H)("BABYLON.ImageSourceBlock",ImageSourceBlock);let TextureBlock=class TextureBlock extends NodeMaterialBlock{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;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rS.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 _IsPrePassTextureBlock(e){return(null==e?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return TextureBlock._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!TextureBlock._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rS.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)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rS.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?tg.Fragment:tg.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",tm.AutoDetect,!1,tg.VertexAndFragment),this.registerInput("source",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,tx.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerInput("layer",tm.Float,!0),this.registerInput("lod",tm.Float,!0),this.registerOutput("rgba",tm.Color4,tg.Neutral),this.registerOutput("rgb",tm.Color3,tg.Neutral),this.registerOutput("r",tm.Float,tg.Neutral),this.registerOutput("g",tm.Float,tg.Neutral),this.registerOutput("b",tm.Float,tg.Neutral),this.registerOutput("a",tm.Float,tg.Neutral),this.registerOutput("level",tm.Float,tg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector2|tm.Vector3|tm.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 tg.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return tg.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===tg.Fragment)return tg.Fragment;if(e.target===tg.Vertex)break;if(e.target===tg.Neutral||e.target===tg.VertexAndFragment){let t=e.ownerBlock;if(t.target===tg.Fragment)return tg.Fragment;for(let i of(e=null,t.inputs))if(i.connectedPoint){e=i.connectedPoint;break}}}return tg.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){if(e.mode===tb.PostProcess){let i=e.getBlockByPredicate(e=>"uv"===e.name&&t(e));i&&i.connectTo(this)}else{let i=e.mode===tb.Particle?"particle_uv":"uv",r=e.getInputBlockByPredicate(e=>e.isAttribute&&e.name===i&&t(e));r||(r=new InputBlock("uv")).setAsAttribute(i),r.output.connectTo(this.uv)}}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix){this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0));return}let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),void 0==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==tg.Fragment}_injectVertexCode(e){let 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} +`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0)); +`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) +`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,e.compilationString+=`#endif +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}_getUVW(e){var t,i,r;let s=e,n=null!==(r=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==r&&r;if(n){let t=this.layer.isConnected?this.layer.associatedVariableName:"0";s=`vec3(${e}, ${t})`}return s}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){let t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName} +`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix}); +`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) +`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix}); +`,e.compilationString+=`#endif +`}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tg.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix}); +`;return}this._generateTextureLookup(e)}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} + ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); + #endif + `),e.compilationString+=`#ifdef ${this._gammaDefineName} + ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); + #endif + `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tg.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s}; +`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,r,s;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===tg.Vertex||this._fragmentOnly||e.target===tg.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===tg.Fragment||this._isMixed&&e.target===tg.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!==tg.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((null===(s=null===(r=this._texture)||void 0===r?void 0:r._texture)||void 0===s?void 0:s.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));let n=`//${this.name}`;for(let t of(e._emitFunctionFromInclude("helperFunctions",n),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; +`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let 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&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};(0,rv.H)("BABYLON.TextureBlock",TextureBlock);let ReflectionTextureBaseBlock=class ReflectionTextureBaseBlock extends NodeMaterialBlock{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rS.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?tg.Fragment:tg.VertexAndFragment)}constructor(e){super(e,tg.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new InputBlock("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(tC.World),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(tC.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this._getTexture();r&&r.getTextureMatrix&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===r.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===r.coordinatesMode,!0),i.setValue(this._defineCubicName,3===r.coordinatesMode||6===r.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===r.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===r.coordinatesMode,!0),i.setValue(this._definePlanarName,2===r.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===r.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===r.coordinatesMode,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){let r=this._getTexture();i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize&&(e.setVector3(this._reflectionPositionName,r.boundingBoxPosition),e.setVector3(this._reflectionSizeName,r.boundingBoxSize)))}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===tg.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");let i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName}; +`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName} +${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; +#endif +`),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) +${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0))); +#endif +`),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName} +`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; +`,e._samplerDeclaration+=`#else +`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; +`,e._samplerDeclaration+=`#endif +`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,r=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);let s=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,a=`${this._positionUVWName}`,o=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=` + #ifdef ${this._defineMirroredEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n}); + #endif + + #ifdef ${this._defineEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n}); + #endif + + #ifdef ${this._defineEquirectangularName} + vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + + #ifdef ${this._defineSphericalName} + vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s}); + #endif + + #ifdef ${this._definePlanarName} + vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + + #ifdef ${this._defineCubicName} + #ifdef ${this._defineLocalCubicName} + vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${o}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); + #else + vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + #endif + + #ifdef ${this._defineProjectionName} + vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s}); + #endif + + #ifdef ${this._defineSkyboxName} + vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${a}, ${s}); + #endif + + #ifdef ${this._defineExplicitName} + vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); + #endif +`;return r||(h+=`#ifdef ${this._defineOppositeZ} + ${this._reflectionVectorName}.z *= -1.0; + #endif +`),i||(h+=` + #ifdef ${this._define3DName} + vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName}; + #else + vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy; + #ifdef ${this._defineProjectionName} + ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; + #endif + ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; + #endif +`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i="vec"+(0===t.length?"4":t.length-1),r=`${i} ${this._reflectionColorName}; + #ifdef ${this._define3DName} +`;return e?r+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t}; +`:r+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t}; +`,r+=` + #else +`,e?r+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t}; +`:r+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t}; +`,r+=`#endif +`}writeOutputs(e,t){let i="";if(e.target===tg.Fragment)for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; +`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){let t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"}); +`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null); +`;return e+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`}serialize(){let 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&&!NodeMaterial.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=cubeTexture_CubeTexture.Parse(e.texture,t,i):this.texture=texture_Texture.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}};(0,rH.gn)([editableInPropertyPage("Generate only fragment code",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:ReflectionTextureBaseBlock._OnGenerateOnlyFragmentCodeChanged}})],ReflectionTextureBaseBlock.prototype,"generateOnlyFragmentCode",void 0),(0,rv.H)("BABYLON.ReflectionTextureBaseBlock",ReflectionTextureBaseBlock);let ReflectionTextureBlock=class ReflectionTextureBlock extends ReflectionTextureBaseBlock{_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?tg.Fragment:tg.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tg.Fragment:tg.Vertex}constructor(e){super(e),this.registerInput("position",tm.AutoDetect,!1,tg.Vertex),this.registerInput("worldPosition",tm.Vector4,!1,tg.Vertex),this.registerInput("worldNormal",tm.Vector4,!1,tg.Fragment),this.registerInput("world",tm.Matrix,!1,tg.Vertex),this.registerInput("cameraPosition",tm.Vector3,!1,tg.Fragment),this.registerInput("view",tm.Matrix,!1,tg.Fragment),this.registerOutput("rgb",tm.Color3,tg.Fragment),this.registerOutput("rgba",tm.Color4,tg.Fragment),this.registerOutput("r",tm.Float,tg.Fragment),this.registerOutput("g",tm.Float,tg.Fragment),this.registerOutput("b",tm.Float,tg.Fragment),this.registerOutput("a",tm.Float,tg.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=()=>!0){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(tC.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==tg.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);let t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName}); +`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}};(0,rv.H)("BABYLON.ReflectionTextureBlock",ReflectionTextureBlock);let SceneDepthBlock=class SceneDepthBlock extends NodeMaterialBlock{constructor(e){super(e,tg.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",tm.AutoDetect,!1,tg.VertexAndFragment),this.registerOutput("depth",tm.Float,tg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector2|tm.Vector3|tm.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?tg.VertexAndFragment:tg.Fragment}_getTexture(e){let t=e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ);return t.getDepthMap()}bind(e,t){let i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput){let i=t.connectedPoint.ownerBlock;i.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===tm.Vector3?"3":t.type===tm.Vector4?"4":"2"))}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tg.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); +`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tg.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.bindableBlocks.indexOf(this)&&e.sharedData.bindableBlocks.push(this),e.target!==tg.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(this._outputs.some(e=>e.isConnectedInFragmentShader)){for(let t of(e._emit2DSampler(this._samplerName),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){let 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,rH.gn)([editableInPropertyPage("Use non linear depth",tT.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],SceneDepthBlock.prototype,"useNonLinearDepth",void 0),(0,rH.gn)([editableInPropertyPage("Store Camera space Z",tT.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],SceneDepthBlock.prototype,"storeCameraSpaceZ",void 0),(0,rH.gn)([editableInPropertyPage("Force 32 bits float",tT.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>null==e?void 0:e.disableDepthRenderer()}})],SceneDepthBlock.prototype,"force32itsFloat",void 0),(0,rv.H)("BABYLON.SceneDepthBlock",SceneDepthBlock);let ClipPlanesBlock=class ClipPlanesBlock extends NodeMaterialBlock{constructor(e){super(e,tg.VertexAndFragment,!0),this.registerInput("worldPosition",tm.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 tg.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var r,s,n,a,o,l;let h=e.getScene(),u=null!==(r=t.clipPlane)&&void 0!==r?!!r:!!h.clipPlane,c=null!==(s=t.clipPlane2)&&void 0!==s?!!s:!!h.clipPlane2,d=null!==(n=t.clipPlane3)&&void 0!==n?!!n:!!h.clipPlane3,p=null!==(a=t.clipPlane4)&&void 0!==a?!!a:!!h.clipPlane4,_=null!==(o=t.clipPlane5)&&void 0!==o?!!o:!!h.clipPlane5,f=null!==(l=t.clipPlane6)&&void 0!==l?!!l:!!h.clipPlane6;i.setValue("CLIPPLANE",u,!0),i.setValue("CLIPPLANE2",c,!0),i.setValue("CLIPPLANE3",d,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",_,!0),i.setValue("CLIPPLANE6",f,!0)}bind(e,t,i){if(!i)return;let r=i.getScene();(0,nX.an)(e,t,r)}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;if(e.target!==tg.Fragment){let i=this.worldPosition;e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),e._emitUniformFromString("vClipPlane6","vec4");return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}};(0,rv.H)("BABYLON.ClipPlanesBlock",ClipPlanesBlock);let PrePassTextureBlock=class PrePassTextureBlock extends NodeMaterialBlock{get texture(){return null}set texture(e){}constructor(e,t=tg.VertexAndFragment){super(e,t,!1),this.registerOutput("position",tm.Object,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("position",this,tx.Output,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("depth",tm.Object,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("depth",this,tx.Output,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("normal",tm.Object,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("normal",this,tx.Output,ImageSourceBlock,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==tg.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){let i=t.getScene(),r=i.enablePrePassRenderer();if(!r)return;let s=r.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[r.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[r.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[r.getIndex(6)]))}};(0,rv.H)("BABYLON.PrePassTextureBlock",PrePassTextureBlock);let NodeMaterialTeleportInBlock=class NodeMaterialTeleportInBlock extends NodeMaterialBlock{get endpoints(){return this._endpoints}constructor(e){super(e,tg.Neutral),this._endpoints=[],this.registerInput("input",tm.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some(e=>e.output.isConnectedInFragmentShader)}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){for(let e of(super.dispose(),this._endpoints))this.detachFromEndpoint(e);this._endpoints=[]}};(0,rv.H)("BABYLON.NodeMaterialTeleportInBlock",NodeMaterialTeleportInBlock);let NodeMaterialTeleportOutBlock=class NodeMaterialTeleportOutBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",tm.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){(this._target&e)==0&&(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName}; +`)}clone(e,t=""){let i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); +`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}};(0,rv.H)("BABYLON.NodeMaterialTeleportOutBlock",NodeMaterialTeleportOutBlock);let AddBlock=class AddBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(tm.Float),this._inputs[1].acceptedConnectionPointTypes.push(tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName}; +`,this}};(0,rv.H)("BABYLON.AddBlock",AddBlock);let ScaleBlock=class ScaleBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.AutoDetect),this.registerInput("factor",tm.Float),this.registerOutput("output",tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName}; +`,this}};(0,rv.H)("BABYLON.ScaleBlock",ScaleBlock);let ClampBlock=class ClampBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",tm.AutoDetect),this.registerOutput("output",tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)}); +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; +`+`${this._codeVariableName}.maximum = ${this.maximum}; +`}serialize(){let 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,rH.gn)([editableInPropertyPage("Minimum",tT.Float)],ClampBlock.prototype,"minimum",void 0),(0,rH.gn)([editableInPropertyPage("Maximum",tT.Float)],ClampBlock.prototype,"maximum",void 0),(0,rv.H)("BABYLON.ClampBlock",ClampBlock);let CrossBlock=class CrossBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tm.Vector2),this._inputs[1].excludedConnectionPointTypes.push(tm.Float),this._inputs[1].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz); +`,this}};(0,rv.H)("BABYLON.CrossBlock",CrossBlock);let CustomBlock=class CustomBlock extends NodeMaterialBlock{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)}),this._outputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)}),e._emitFunction(i,t,""),this._outputs.forEach(t=>{e.compilationString+=this._declareOutput(t,e)+";\n"}),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach((t,i)=>{var s,n,a;i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=null!==(a=null===(n=null===(s=t.connectedPoint)||void 0===s?void 0:s.ownerBlock)||void 0===n?void 0:n.samplerName)&&void 0!==a?a:t.associatedVariableName:e.compilationString+=t.associatedVariableName,r=!0}),this._outputs.forEach((t,i)=>{(i>0||r)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName}),e.compilationString+=");\n",this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.options = ${JSON.stringify(this._options)}; +`}serialize(){let 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,r;this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=tg[e.target],null===(t=e.inParameters)||void 0===t||t.forEach((e,t)=>{let i=tm[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject(e.name,this,tx.Input,ImageSourceBlock,"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,tm[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===(r=e.inLinkedConnectionTypes)||void 0===r||r.forEach(e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t<this._inputs.length;t++)if(this._inputs[t].name===e)return[this._inputs[t],t];return null}};(0,rv.H)("BABYLON.CustomBlock",CustomBlock);let DotBlock=class DotBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tm.Float),this._inputs[1].excludedConnectionPointTypes.push(tm.Matrix)}getClassName(){return"DotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = dot(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.DotBlock",DotBlock);let NormalizeBlock=class NormalizeBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix)}getClassName(){return"NormalizeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${i.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.NormalizeBlock",NormalizeBlock);let ColorMergerBlock=class ColorMergerBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.rSwizzle="r",this.gSwizzle="g",this.bSwizzle="b",this.aSwizzle="a",this.registerInput("rgb ",tm.Color3,!0),this.registerInput("r",tm.Float,!0),this.registerInput("g",tm.Float,!0),this.registerInput("b",tm.Float,!0),this.registerInput("a",tm.Float,!0),this.registerOutput("rgba",tm.Color4),this.registerOutput("rgb",tm.Color3)}getClassName(){return"ColorMergerBlock"}get rgbIn(){return this._inputs[0]}get r(){return this._inputs[1]}get g(){return this._inputs[2]}get b(){return this._inputs[3]}get a(){return this._inputs[4]}get rgba(){return this._outputs[0]}get rgbOut(){return this._outputs[1]}get rgb(){return this.rgbOut}_inputRename(e){return"rgb "===e?"rgbIn":e}_buildSwizzle(e){let t=this.rSwizzle+this.gSwizzle+this.bSwizzle+this.aSwizzle;return"."+t.substr(0,e)}_buildBlock(e){super._buildBlock(e);let t=this.r,i=this.g,r=this.b,s=this.a,n=this.rgbIn,a=this._outputs[0],o=this._outputs[1];return n.isConnected?(a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec4(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${n.associatedVariableName}${this._buildSwizzle(3)}; +`)):(a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; +`)),this}serialize(){let e=super.serialize();return e.rSwizzle=this.rSwizzle,e.gSwizzle=this.gSwizzle,e.bSwizzle=this.bSwizzle,e.aSwizzle=this.aSwizzle,e}_deserialize(e,t,i){var r,s,n,a;super._deserialize(e,t,i),this.rSwizzle=null!==(r=e.rSwizzle)&&void 0!==r?r:"r",this.gSwizzle=null!==(s=e.gSwizzle)&&void 0!==s?s:"g",this.bSwizzle=null!==(n=e.bSwizzle)&&void 0!==n?n:"b",this.aSwizzle=null!==(a=e.aSwizzle)&&void 0!==a?a:"a"}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.rSwizzle = "${this.rSwizzle}"; +${this._codeVariableName}.gSwizzle = "${this.gSwizzle}"; +${this._codeVariableName}.bSwizzle = "${this.bSwizzle}"; +${this._codeVariableName}.aSwizzle = "${this.aSwizzle}"; +`}};(0,rv.H)("BABYLON.ColorMergerBlock",ColorMergerBlock);let VectorSplitterBlock=class VectorSplitterBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("xyzw",tm.Vector4,!0),this.registerInput("xyz ",tm.Vector3,!0),this.registerInput("xy ",tm.Vector2,!0),this.registerOutput("xyz",tm.Vector3),this.registerOutput("xy",tm.Vector2),this.registerOutput("zw",tm.Vector2),this.registerOutput("x",tm.Float),this.registerOutput("y",tm.Float),this.registerOutput("z",tm.Float),this.registerOutput("w",tm.Float),this.inputsAreExclusive=!0}getClassName(){return"VectorSplitterBlock"}get xyzw(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get xyzOut(){return this._outputs[0]}get xyOut(){return this._outputs[1]}get zw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get w(){return this._outputs[6]}_inputRename(e){switch(e){case"xy ":return"xyIn";case"xyz ":return"xyzIn";default:return e}}_outputRename(e){switch(e){case"xy":return"xyOut";case"xyz":return"xyzOut";default:return e}}_buildBlock(e){super._buildBlock(e);let t=this.xyzw.isConnected?this.xyzw:this.xyzIn.isConnected?this.xyzIn:this.xyIn,i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],n=this._outputs[3],a=this._outputs[4],o=this._outputs[5],l=this._outputs[6];return i.hasEndpoints&&(t===this.xyIn?e.compilationString+=this._declareOutput(i,e)+` = vec3(${t.associatedVariableName}, 0.0); +`:e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.xyz; +`),s.hasEndpoints&&this.xyzw.isConnected&&(e.compilationString+=this._declareOutput(s,e)+` = ${this.xyzw.associatedVariableName}.zw; +`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.xy; +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.x; +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.y; +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.z; +`),l.hasEndpoints&&(e.compilationString+=this._declareOutput(l,e)+` = ${t.associatedVariableName}.w; +`),this}};(0,rv.H)("BABYLON.VectorSplitterBlock",VectorSplitterBlock);let LerpBlock=class LerpBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerInput("gradient",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(tm.Float)}getClassName(){return"LerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.LerpBlock",LerpBlock);let DivideBlock=class DivideBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(tm.Float),this._inputs[1].acceptedConnectionPointTypes.push(tm.Float)}getClassName(){return"DivideBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} / ${this.right.associatedVariableName}; +`,this}};(0,rv.H)("BABYLON.DivideBlock",DivideBlock);let SubtractBlock=class SubtractBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(tm.Float),this._inputs[1].acceptedConnectionPointTypes.push(tm.Float)}getClassName(){return"SubtractBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} - ${this.right.associatedVariableName}; +`,this}};(0,rv.H)("BABYLON.SubtractBlock",SubtractBlock);let StepBlock=class StepBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.Float),this.registerInput("edge",tm.Float),this.registerOutput("output",tm.Float)}getClassName(){return"StepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = step(${this.edge.associatedVariableName}, ${this.value.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.StepBlock",StepBlock);let OneMinusBlock=class OneMinusBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[0].excludedConnectionPointTypes.push(tm.Matrix)}getClassName(){return"OneMinusBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = 1. - ${this.input.associatedVariableName}; +`,this}};(0,rv.H)("BABYLON.OneMinusBlock",OneMinusBlock),(0,rv.H)("BABYLON.OppositeBlock",OneMinusBlock);let ViewDirectionBlock=class ViewDirectionBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("worldPosition",tm.Vector4),this.registerInput("cameraPosition",tm.Vector3),this.registerOutput("output",tm.Vector3)}getClassName(){return"ViewDirectionBlock"}get worldPosition(){return this._inputs[0]}get cameraPosition(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(tC.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz); +`,this}};(0,rv.H)("BABYLON.ViewDirectionBlock",ViewDirectionBlock);let FresnelBlock=class FresnelBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("worldNormal",tm.Vector4),this.registerInput("viewDirection",tm.Vector3),this.registerInput("bias",tm.Float),this.registerInput("power",tm.Float),this.registerOutput("fresnel",tm.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){let t=new ViewDirectionBlock("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){let e=new InputBlock("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){let e=new InputBlock("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);let 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}); +`,this}};(0,rv.H)("BABYLON.FresnelBlock",FresnelBlock);let MaxBlock=class MaxBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.MaxBlock",MaxBlock);let MinBlock=class MinBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.MinBlock",MinBlock);let DistanceBlock=class DistanceBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tm.Float),this._inputs[1].excludedConnectionPointTypes.push(tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.DistanceBlock",DistanceBlock);let LengthBlock=class LengthBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerOutput("output",tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.LengthBlock",LengthBlock);let NegateBlock=class NegateBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerOutput("output",tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName}; +`,this}};(0,rv.H)("BABYLON.NegateBlock",NegateBlock);let PowBlock=class PowBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerInput("power",tm.AutoDetect),this.registerOutput("output",tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.PowBlock",PowBlock);let RandomNumberBlock=class RandomNumberBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("seed",tm.AutoDetect),this.registerOutput("output",tm.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector2|tm.Vector3|tm.Vector4|tm.Color3|tm.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy); +`,this}};(0,rv.H)("BABYLON.RandomNumberBlock",RandomNumberBlock);let ArcTan2Block=class ArcTan2Block extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("x",tm.Float),this.registerInput("y",tm.Float),this.registerOutput("output",tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.ArcTan2Block",ArcTan2Block);let SmoothStepBlock=class SmoothStepBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerInput("edge0",tm.Float),this.registerInput("edge1",tm.Float),this.registerOutput("output",tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.SmoothStepBlock",SmoothStepBlock);let ReciprocalBlock=class ReciprocalBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.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);let t=this._outputs[0];return this.input.type===tm.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); +`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName}; +`,this}};(0,rv.H)("BABYLON.ReciprocalBlock",ReciprocalBlock);let ReplaceColorBlock=class ReplaceColorBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerInput("reference",tm.AutoDetect),this.registerInput("distance",tm.Float),this.registerInput("replacement",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tm.Float),this._inputs[1].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[3].excludedConnectionPointTypes.push(tm.Float),this._inputs[3].excludedConnectionPointTypes.push(tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+`; +`,e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) { +`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName}; +`,e.compilationString+=`} else { +`,e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName}; +`,e.compilationString+=`} +`,this}};(0,rv.H)("BABYLON.ReplaceColorBlock",ReplaceColorBlock);let PosterizeBlock=class PosterizeBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerInput("steps",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tm.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);let 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}); +`,this}};(0,rv.H)("BABYLON.PosterizeBlock",PosterizeBlock),(eD=iD||(iD={}))[eD.SawTooth=0]="SawTooth",eD[eD.Square=1]="Square",eD[eD.Triangle=2]="Triangle";let WaveBlock=class WaveBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.kind=iD.SawTooth,this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];switch(this.kind){case iD.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); +`;break;case iD.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); +`;break;case iD.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0; +`}return this}serialize(){let e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}};(0,rv.H)("BABYLON.WaveBlock",WaveBlock);let GradientBlockColorStep=class GradientBlockColorStep{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}};let GradientBlock=class GradientBlock extends NodeMaterialBlock{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,tg.Neutral),this.colorSteps=[new GradientBlockColorStep(0,rg.Wo.Black()),new GradientBlockColorStep(1,rg.Wo.White())],this.onValueChangedObservable=new rf.y$,this.registerInput("gradient",tm.AutoDetect),this.registerOutput("output",tm.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Float|tm.Vector2|tm.Vector3|tm.Vector4|tm.Color3|tm.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){let t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=this._declareOutput(t,e)+` = vec3(0., 0., 0.); +`;return}let i=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)}; +`,e.compilationString+=`float ${r}; +`;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==tm.Float&&(s+=".x");for(let t=1;t<this.colorSteps.length;t++){let n=this.colorSteps[t],a=this.colorSteps[t-1];e.compilationString+=`${r} = clamp((${s} - ${e._emitFloat(a.step)}) / (${e._emitFloat(n.step)} - ${e._emitFloat(a.step)}), 0.0, 1.0) * step(${e._emitFloat(t)}, ${e._emitFloat(this.colorSteps.length-1)}); +`,e.compilationString+=`${i} = mix(${i}, ${this._writeColorConstant(t)}, ${r}); +`}return e.compilationString+=this._declareOutput(t,e)+` = ${i}; +`,this}serialize(){let e=super.serialize();for(let t of(e.colorSteps=[],this.colorSteps))e.colorSteps.push({step:t.step,color:{r:t.color.r,g:t.color.g,b:t.color.b}});return e}_deserialize(e,t,i){for(let r of(super._deserialize(e,t,i),this.colorSteps.length=0,e.colorSteps))this.colorSteps.push(new GradientBlockColorStep(r.step,new rg.Wo(r.color.r,r.color.g,r.color.b)))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();for(let t of(e+=`${this._codeVariableName}.colorSteps = []; +`,this.colorSteps))e+=`${this._codeVariableName}.colorSteps.push(new BABYLON.GradientBlockColorStep(${t.step}, new BABYLON.Color3(${t.color.r}, ${t.color.g}, ${t.color.b}))); +`;return e}};(0,rv.H)("BABYLON.GradientBlock",GradientBlock);let NLerpBlock=class NLerpBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerInput("gradient",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(tm.Float)}getClassName(){return"NLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName})); +`,this}};(0,rv.H)("BABYLON.NLerpBlock",NLerpBlock);let WorleyNoise3DBlock=class WorleyNoise3DBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.manhattanDistance=!1,this.registerInput("seed",tm.Vector3),this.registerInput("jitter",tm.Float),this.registerOutput("output",tm.Vector2),this.registerOutput("x",tm.Float),this.registerOutput("y",tm.Float)}getClassName(){return"WorleyNoise3DBlock"}get seed(){return this._inputs[0]}get jitter(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected||!this.output.hasEndpoints&&!this.x.hasEndpoints&&!this.y.hasEndpoints)return;let t=`vec3 permute(vec3 x){ +`;t+=` return mod((34.0 * x + 1.0) * x, 289.0); +} + +vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){ + return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z); +} + +vec2 worley(vec3 P, float jitter, bool manhattanDistance){ + float K = 0.142857142857; // 1/7 + float Ko = 0.428571428571; // 1/2-K/2 + float K2 = 0.020408163265306; // 1/(7*7) + float Kz = 0.166666666667; // 1/6 + float Kzo = 0.416666666667; // 1/2-1/6*2 + + vec3 Pi = mod(floor(P), 289.0); + vec3 Pf = fract(P) - 0.5; + + vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0); + vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0); + vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0); + + vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0)); + vec3 p1 = permute(p + Pi.y - 1.0); + vec3 p2 = permute(p + Pi.y); + vec3 p3 = permute(p + Pi.y + 1.0); + + vec3 p11 = permute(p1 + Pi.z - 1.0); + vec3 p12 = permute(p1 + Pi.z); + vec3 p13 = permute(p1 + Pi.z + 1.0); + + vec3 p21 = permute(p2 + Pi.z - 1.0); + vec3 p22 = permute(p2 + Pi.z); + vec3 p23 = permute(p2 + Pi.z + 1.0); + + vec3 p31 = permute(p3 + Pi.z - 1.0); + vec3 p32 = permute(p3 + Pi.z); + vec3 p33 = permute(p3 + Pi.z + 1.0); + + vec3 ox11 = fract(p11*K) - Ko; + vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko; + vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed + + vec3 ox12 = fract(p12*K) - Ko; + vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko; + vec3 oz12 = floor(p12*K2)*Kz - Kzo; + + vec3 ox13 = fract(p13*K) - Ko; + vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko; + vec3 oz13 = floor(p13*K2)*Kz - Kzo; + + vec3 ox21 = fract(p21*K) - Ko; + vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko; + vec3 oz21 = floor(p21*K2)*Kz - Kzo; + + vec3 ox22 = fract(p22*K) - Ko; + vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko; + vec3 oz22 = floor(p22*K2)*Kz - Kzo; + + vec3 ox23 = fract(p23*K) - Ko; + vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko; + vec3 oz23 = floor(p23*K2)*Kz - Kzo; + + vec3 ox31 = fract(p31*K) - Ko; + vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko; + vec3 oz31 = floor(p31*K2)*Kz - Kzo; + + vec3 ox32 = fract(p32*K) - Ko; + vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko; + vec3 oz32 = floor(p32*K2)*Kz - Kzo; + + vec3 ox33 = fract(p33*K) - Ko; + vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko; + vec3 oz33 = floor(p33*K2)*Kz - Kzo; + + vec3 dx11 = Pfx + jitter*ox11; + vec3 dy11 = Pfy.x + jitter*oy11; + vec3 dz11 = Pfz.x + jitter*oz11; + + vec3 dx12 = Pfx + jitter*ox12; + vec3 dy12 = Pfy.x + jitter*oy12; + vec3 dz12 = Pfz.y + jitter*oz12; + + vec3 dx13 = Pfx + jitter*ox13; + vec3 dy13 = Pfy.x + jitter*oy13; + vec3 dz13 = Pfz.z + jitter*oz13; + + vec3 dx21 = Pfx + jitter*ox21; + vec3 dy21 = Pfy.y + jitter*oy21; + vec3 dz21 = Pfz.x + jitter*oz21; + + vec3 dx22 = Pfx + jitter*ox22; + vec3 dy22 = Pfy.y + jitter*oy22; + vec3 dz22 = Pfz.y + jitter*oz22; + + vec3 dx23 = Pfx + jitter*ox23; + vec3 dy23 = Pfy.y + jitter*oy23; + vec3 dz23 = Pfz.z + jitter*oz23; + + vec3 dx31 = Pfx + jitter*ox31; + vec3 dy31 = Pfy.z + jitter*oy31; + vec3 dz31 = Pfz.x + jitter*oz31; + + vec3 dx32 = Pfx + jitter*ox32; + vec3 dy32 = Pfy.z + jitter*oy32; + vec3 dz32 = Pfz.y + jitter*oz32; + + vec3 dx33 = Pfx + jitter*ox33; + vec3 dy33 = Pfy.z + jitter*oy33; + vec3 dz33 = Pfz.z + jitter*oz33; + + vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance); + vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance); + vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance); + vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance); + vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance); + vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance); + vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance); + vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance); + vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance); + + vec3 d1a = min(d11, d12); + d12 = max(d11, d12); + d11 = min(d1a, d13); // Smallest now not in d12 or d13 + d13 = max(d1a, d13); + d12 = min(d12, d13); // 2nd smallest now not in d13 + vec3 d2a = min(d21, d22); + d22 = max(d21, d22); + d21 = min(d2a, d23); // Smallest now not in d22 or d23 + d23 = max(d2a, d23); + d22 = min(d22, d23); // 2nd smallest now not in d23 + vec3 d3a = min(d31, d32); + d32 = max(d31, d32); + d31 = min(d3a, d33); // Smallest now not in d32 or d33 + d33 = max(d3a, d33); + d32 = min(d32, d33); // 2nd smallest now not in d33 + vec3 da = min(d11, d21); + d21 = max(d11, d21); + d11 = min(da, d31); // Smallest now in d11 + d31 = max(da, d31); // 2nd smallest now not in d31 + d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx; + d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest + d12 = min(d12, d21); // 2nd smallest now not in d21 + d12 = min(d12, d22); // nor in d22 + d12 = min(d12, d31); // nor in d31 + d12 = min(d12, d32); // nor in d32 + d11.yz = min(d11.yz,d12.xy); // nor in d12.yz + d11.y = min(d11.y,d12.z); // Only two more to go + d11.y = min(d11.y,d11.z); // Done! (Phew!) + return sqrt(d11.xy); // F1, F2 +} + +`,e._emitFunction("worley3D",t,"// Worley3D");let i=e._getFreeVariableName("worleyTemp");return e.compilationString+=`vec2 ${i} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance}); +`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${i}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${i}.y; +`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance}; +`;return e}serialize(){let e=super.serialize();return e.manhattanDistance=this.manhattanDistance,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.manhattanDistance=e.manhattanDistance}};(0,rH.gn)([editableInPropertyPage("Use Manhattan Distance",tT.Boolean,"PROPERTIES",{notifiers:{update:!1}})],WorleyNoise3DBlock.prototype,"manhattanDistance",void 0),(0,rv.H)("BABYLON.WorleyNoise3DBlock",WorleyNoise3DBlock);let SimplexPerlin3DBlock=class SimplexPerlin3DBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("seed",tm.Vector3),this.registerOutput("output",tm.Float)}getClassName(){return"SimplexPerlin3DBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;let t=`const float SKEWFACTOR = 1.0/3.0; +`;return t+=`const float UNSKEWFACTOR = 1.0/6.0; +const float SIMPLEX_CORNER_POS = 0.5; +const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485; +float SimplexPerlin3D( vec3 P ){ + P.x = P == vec3(0., 0., 0.) ? 0.00001 : P.x; + P *= SIMPLEX_TETRAHADRON_HEIGHT; + vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) ); vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) ); + vec3 g = step(x0.yzx, x0.xyz); + vec3 l = 1.0 - g; + vec3 Pi_1 = min( g.xyz, l.zxy ); + vec3 Pi_2 = max( g.xyz, l.zxy ); + vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR; + vec3 x2 = x0 - Pi_2 + SKEWFACTOR; + vec3 x3 = x0 - SIMPLEX_CORNER_POS; + vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x ); + vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y ); + vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z ); + Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0; + vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 ); + vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy; + Pt *= Pt; + vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) ); + Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w ); + const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 ); + const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 ); + vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) ); + vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) ); + Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods; + Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods; + vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999; + vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999; + vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999; + 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 ); + const float FINAL_NORMALIZATION = 37.837227241611314102871574478976; + vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z; + kernel_weights = max(0.5 - kernel_weights, 0.0); + kernel_weights = kernel_weights*kernel_weights*kernel_weights; + return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION; +} +`,e._emitFunction("SimplexPerlin3D",t,"// SimplexPerlin3D"),e.compilationString+=this._declareOutput(this._outputs[0],e)+` = SimplexPerlin3D(${this.seed.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.SimplexPerlin3DBlock",SimplexPerlin3DBlock);let NormalBlendBlock=class NormalBlendBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("normalMap0",tm.AutoDetect),this.registerInput("normalMap1",tm.AutoDetect),this.registerOutput("output",tm.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Color4|tm.Vector3|tm.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Color4|tm.Vector3|tm.Vector4)}getClassName(){return"NormalBlendBlock"}get normalMap0(){return this._inputs[0]}get normalMap1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0],r=this._inputs[1],s=e._getFreeVariableName("stepR"),n=e._getFreeVariableName("stepG");return e.compilationString+=`float ${s} = step(0.5, ${i.associatedVariableName}.r); +`,e.compilationString+=`float ${n} = step(0.5, ${i.associatedVariableName}.g); +`,e.compilationString+=this._declareOutput(t,e)+`; +`,e.compilationString+=`${t.associatedVariableName}.r = (1.0 - ${s}) * ${i.associatedVariableName}.r * ${r.associatedVariableName}.r * 2.0 + ${s} * (1.0 - (1.0 - ${i.associatedVariableName}.r) * (1.0 - ${r.associatedVariableName}.r) * 2.0); +`,e.compilationString+=`${t.associatedVariableName}.g = (1.0 - ${n}) * ${i.associatedVariableName}.g * ${r.associatedVariableName}.g * 2.0 + ${n} * (1.0 - (1.0 - ${i.associatedVariableName}.g) * (1.0 - ${r.associatedVariableName}.g) * 2.0); +`,e.compilationString+=`${t.associatedVariableName}.b = ${i.associatedVariableName}.b * ${r.associatedVariableName}.b; +`,this}};(0,rv.H)("BABYLON.NormalBlendBlock",NormalBlendBlock);let Rotate2dBlock=class Rotate2dBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.Vector2),this.registerInput("angle",tm.Float),this.registerOutput("output",tm.Vector2)}getClassName(){return"Rotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new InputBlock("angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.angle,r=this.input;return e.compilationString+=this._declareOutput(t,e)+` = vec2(cos(${i.associatedVariableName}) * ${r.associatedVariableName}.x - sin(${i.associatedVariableName}) * ${r.associatedVariableName}.y, sin(${i.associatedVariableName}) * ${r.associatedVariableName}.x + cos(${i.associatedVariableName}) * ${r.associatedVariableName}.y); +`,this}};(0,rv.H)("BABYLON.Rotate2dBlock",Rotate2dBlock);let ReflectBlock=class ReflectBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("incident",tm.AutoDetect),this.registerInput("normal",tm.AutoDetect),this.registerOutput("output",tm.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector3|tm.Vector4|tm.Color3|tm.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(tm.Vector3|tm.Vector4|tm.Color3|tm.Color4)}getClassName(){return"ReflectBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz); +`,this}};(0,rv.H)("BABYLON.ReflectBlock",ReflectBlock);let RefractBlock=class RefractBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("incident",tm.AutoDetect),this.registerInput("normal",tm.AutoDetect),this.registerInput("ior",tm.Float),this.registerOutput("output",tm.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector3|tm.Vector4|tm.Color3|tm.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(tm.Vector3|tm.Vector4|tm.Color3|tm.Color4)}getClassName(){return"RefractBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get ior(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.RefractBlock",RefractBlock);let DesaturateBlock=class DesaturateBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("color",tm.Color3),this.registerInput("level",tm.Float),this.registerOutput("output",tm.Color3)}getClassName(){return"DesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.color,r=i.associatedVariableName,s=e._getFreeVariableName("colorMin"),n=e._getFreeVariableName("colorMax"),a=e._getFreeVariableName("colorMerge");return e.compilationString+=`float ${s} = min(min(${r}.x, ${r}.y), ${r}.z); +`,e.compilationString+=`float ${n} = max(max(${r}.x, ${r}.y), ${r}.z); +`,e.compilationString+=`float ${a} = 0.5 * (${s} + ${n}); +`,e.compilationString+=this._declareOutput(t,e)+` = mix(${r}, vec3(${a}, ${a}, ${a}), ${this.level.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.DesaturateBlock",DesaturateBlock);let SheenBlock=class SheenBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.albedoScaling=!1,this.linkSheenWithAlbedo=!1,this._isUnique=!0,this.registerInput("intensity",tm.Float,!0,tg.Fragment),this.registerInput("color",tm.Color3,!0,tg.Fragment),this.registerInput("roughness",tm.Float,!0,tg.Fragment),this.registerOutput("sheen",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("sheen",this,tx.Output,SheenBlock,"SheenBlock"))}initialize(e){e._excludeVariableName("sheenOut"),e._excludeVariableName("sheenMapData"),e._excludeVariableName("vSheenColor"),e._excludeVariableName("vSheenRoughness")}getClassName(){return"SheenBlock"}get intensity(){return this._inputs[0]}get color(){return this._inputs[1]}get roughness(){return this._inputs[2]}get sheen(){return this._outputs[0]}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("SHEEN",!0),i.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("SHEEN_LINKWITHALBEDO",this.linkSheenWithAlbedo,!0),i.setValue("SHEEN_ROUGHNESS",this.roughness.isConnected,!0),i.setValue("SHEEN_ALBEDOSCALING",this.albedoScaling,!0)}getCode(e){let t=this.color.isConnected?this.color.associatedVariableName:"vec3(1.)",i=this.intensity.isConnected?this.intensity.associatedVariableName:"1.",r=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return`#ifdef SHEEN + sheenOutParams sheenOut; + + vec4 vSheenColor = vec4(${t}, ${i}); + + sheenBlock( + vSheenColor, + #ifdef SHEEN_ROUGHNESS + ${r}, + #endif + roughness, + #ifdef SHEEN_TEXTURE + vec4(0.), + 1.0, + #endif + reflectance, + #ifdef SHEEN_LINKWITHALBEDO + baseColor, + surfaceAlbedo, + #endif + #ifdef ENVIRONMENTBRDF + NdotV, + environmentBrdf, + #endif + #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) + AARoughnessFactors, + ${null==e?void 0:e._vReflectionMicrosurfaceInfosName}, + ${null==e?void 0:e._vReflectionInfosName}, + ${null==e?void 0:e.reflectionColor}, + vLightingIntensity, + #ifdef ${null==e?void 0:e._define3DName} + ${null==e?void 0:e._cubeSamplerName}, + #else + ${null==e?void 0:e._2DSamplerName}, + #endif + reflectionOut.reflectionCoords, + NdotVUnclamped, + #ifndef LODBASEDMICROSFURACE + #ifdef ${null==e?void 0:e._define3DName} + ${null==e?void 0:e._cubeSamplerName}, + ${null==e?void 0:e._cubeSamplerName}, + #else + ${null==e?void 0:e._2DSamplerName}, + ${null==e?void 0:e._2DSamplerName}, + #endif + #endif + #if !defined(${null==e?void 0:e._defineSkyboxName}) && defined(RADIANCEOCCLUSION) + seo, + #endif + #if !defined(${null==e?void 0:e._defineSkyboxName}) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(${null==e?void 0:e._define3DName}) + eho, + #endif + #endif + sheenOut + ); + + #ifdef SHEEN_LINKWITHALBEDO + surfaceAlbedo = sheenOut.surfaceAlbedo; + #endif + #endif +`}_buildBlock(e){return e.target===tg.Fragment&&e.sharedData.blocksWithDefines.push(this),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.albedoScaling = ${this.albedoScaling}; +${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo}; +`}serialize(){let e=super.serialize();return e.albedoScaling=this.albedoScaling,e.linkSheenWithAlbedo=this.linkSheenWithAlbedo,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.albedoScaling=e.albedoScaling,this.linkSheenWithAlbedo=e.linkSheenWithAlbedo}};(0,rH.gn)([editableInPropertyPage("Albedo scaling",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],SheenBlock.prototype,"albedoScaling",void 0),(0,rH.gn)([editableInPropertyPage("Link sheen with albedo",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],SheenBlock.prototype,"linkSheenWithAlbedo",void 0),(0,rv.H)("BABYLON.SheenBlock",SheenBlock);let AnisotropyBlock=class AnisotropyBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._tangentCorrectionFactorName="",this._isUnique=!0,this.registerInput("intensity",tm.Float,!0,tg.Fragment),this.registerInput("direction",tm.Vector2,!0,tg.Fragment),this.registerInput("uv",tm.Vector2,!0),this.registerInput("worldTangent",tm.Vector4,!0),this.registerInput("TBN",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("TBN",this,tx.Input,TBNBlock,"TBNBlock")),this.registerInput("roughness",tm.Float,!0,tg.Fragment),this.registerOutput("anisotropy",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("anisotropy",this,tx.Output,AnisotropyBlock,"AnisotropyBlock"))}initialize(e){e._excludeVariableName("anisotropicOut"),e._excludeVariableName("TBN")}getClassName(){return"AnisotropyBlock"}get intensity(){return this._inputs[0]}get direction(){return this._inputs[1]}get uv(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get TBN(){return this._inputs[4]}get roughness(){return this._inputs[5]}get anisotropy(){return this._outputs[0]}_generateTBNSpace(e){let t="",i=`//${this.name}`,r=this.uv,s=this.worldPositionConnectionPoint,n=this.worldNormalConnectionPoint,a=this.worldTangent;r.isConnected||console.error("You must connect the 'uv' input of the Anisotropy block!"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let o={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},l=this.TBN;return l.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${l.associatedVariableName}; + #endif + `:a.isConnected&&(t+=`vec3 tbnNormal = normalize(${n.associatedVariableName}.xyz); +vec3 tbnTangent = normalize(${a.associatedVariableName}.xyz); +vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),t+=` + #if defined(${a.isConnected?"TANGENT":"IGNORE"}) && defined(NORMAL) + mat3 TBN = vTBN; + #else + mat3 TBN = cotangent_frame(${n.associatedVariableName+".xyz"}, ${"v_"+s.associatedVariableName+".xyz"}, ${r.isConnected?r.associatedVariableName:"vec2(0.)"}, vec2(1., 1.)); + #endif +`,e._emitFunctionFromInclude("bumpFragmentMainFunctions",i,{replaceStrings:[o]}),t}getCode(e,t=!1){let i="";t&&(i+=this._generateTBNSpace(e));let r=this.intensity.isConnected?this.intensity.associatedVariableName:"1.0",s=this.direction.isConnected?this.direction.associatedVariableName:"vec2(1., 0.)",n=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return i+`anisotropicOutParams anisotropicOut; + anisotropicBlock( + vec3(${s}, ${r}), + ${n}, + #ifdef ANISOTROPIC_TEXTURE + vec3(0.), + #endif + TBN, + normalW, + viewDirectionW, + anisotropicOut + ); +`}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("ANISOTROPIC",!0),i.setValue("ANISOTROPIC_TEXTURE",!1,!0),i.setValue("ANISOTROPIC_LEGACY",!this.roughness.isConnected)}bind(e,t,i){super.bind(e,t,i),i&&e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1)}_buildBlock(e){return e.target===tg.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}};(0,rv.H)("BABYLON.AnisotropyBlock",AnisotropyBlock);let ReflectionBlock=class ReflectionBlock extends ReflectionTextureBaseBlock{_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._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?tg.Fragment:tg.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",tm.AutoDetect,!1,tg.Vertex),this.registerInput("world",tm.Matrix,!1,tg.Vertex),this.registerInput("color",tm.Color3,!0,tg.Fragment),this.registerOutput("reflection",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("reflection",this,tx.Output,ReflectionBlock,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4)}getClassName(){return"ReflectionBlock"}get position(){return this._inputs[0]}get worldPosition(){return this.worldPositionConnectionPoint}get worldNormal(){return this.worldNormalConnectionPoint}get world(){return this._inputs[1]}get cameraPosition(){return this.cameraPositionConnectionPoint}get view(){return this.viewConnectionPoint}get color(){return this._inputs[2]}get reflection(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}get reflectionColor(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("REFLECTION",s,!0),s&&(i.setValue(this._defineLODReflectionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!r.invertZ:r.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",r.gammaSpace,!0),i.setValue("RGBDREFLECTION",r.isRGBD,!0),r&&r.coordinatesMode!==texture_Texture.SKYBOX_MODE&&r.isCube&&(i.setValue("USESPHERICALFROMREFLECTIONMAP",!0),i.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?i.setValue("USESPHERICALINVERTEX",!1):i.setValue("USESPHERICALINVERTEX",!0)))}bind(e,t,i,r){super.bind(e,t,i);let s=this._getTexture();if(!s||!r)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s);let n=s.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,n,s.lodGenerationScale,s.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,n,rE.R.Log2(n));let a=r.materialDefines,o=s.sphericalPolynomial;if(a.USESPHERICALFROMREFLECTIONMAP&&o){if(a.SPHERICAL_HARMONICS){let t=o.preScaledHarmonics;e.setVector3("vSphericalL00",t.l00),e.setVector3("vSphericalL1_1",t.l1_1),e.setVector3("vSphericalL10",t.l10),e.setVector3("vSphericalL11",t.l11),e.setVector3("vSphericalL2_2",t.l2_2),e.setVector3("vSphericalL2_1",t.l2_1),e.setVector3("vSphericalL20",t.l20),e.setVector3("vSphericalL21",t.l21),e.setVector3("vSphericalL22",t.l22)}else e.setFloat3("vSphericalX",o.x.x,o.x.y,o.x.z),e.setFloat3("vSphericalY",o.y.x,o.y.y,o.y.z),e.setFloat3("vSphericalZ",o.z.x,o.z.y,o.z.z),e.setFloat3("vSphericalXX_ZZ",o.xx.x-o.zz.x,o.xx.y-o.zz.y,o.xx.z-o.zz.z),e.setFloat3("vSphericalYY_ZZ",o.yy.x-o.zz.x,o.yy.y-o.zz.y,o.yy.z-o.zz.z),e.setFloat3("vSphericalZZ",o.zz.x,o.zz.y,o.zz.z),e.setFloat3("vSphericalXY",o.xy.x,o.xy.y,o.xy.z),e.setFloat3("vSphericalYZ",o.yz.x,o.yz.y,o.yz.z),e.setFloat3("vSphericalZX",o.zx.x,o.zx.y,o.zx.z)}}handleVertexSide(e){let t=super.handleVertexSide(e);e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});let i=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,"vec3","defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX","vec3","SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) + vec3 ${i} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; + #ifdef ${this._defineOppositeZ} + ${i}.z *= -1.0; + #endif + ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${i}); + #endif +`}getCode(e,t){let i="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection",` + #ifdef ${this._define3DName} + #define sampleReflection(s, c) textureCube(s, c) + #else + #define sampleReflection(s, c) texture2D(s, c) + #endif +`,`//${this.name}`),e._emitFunction("sampleReflectionLod",` + #ifdef ${this._define3DName} + #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l) + #else + #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l) + #endif +`,`//${this.name}`);let r=` + vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) { + ${this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0,!0)} + return ${this._reflectionVectorName}; + } +`;return e._emitFunction("computeReflectionCoordsPBR",r,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,"vec3"),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,"vec2"),i+=`#ifdef REFLECTION + vec2 ${this._vReflectionInfosName} = vec2(1., 0.); + + reflectionOutParams reflectionOut; + + reflectionBlock( + ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName}.xyz, + ${t}, + alphaG, + ${this._vReflectionMicrosurfaceInfosName}, + ${this._vReflectionInfosName}, + ${this.reflectionColor}, + #ifdef ANISOTROPIC + anisotropicOut, + #endif + #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName}) + NdotVUnclamped, + #endif + #ifdef ${this._defineLinearSpecularReflection} + roughness, + #endif + #ifdef ${this._define3DName} + ${this._cubeSamplerName}, + #else + ${this._2DSamplerName}, + #endif + #if defined(NORMAL) && defined(USESPHERICALINVERTEX) + ${this._vEnvironmentIrradianceName}, + #endif + #ifdef USESPHERICALFROMREFLECTIONMAP + #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) + ${this._reflectionMatrixName}, + #endif + #endif + #ifdef USEIRRADIANCEMAP + irradianceSampler, // ** not handled ** + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${this._define3DName} + ${this._cubeSamplerName}, + ${this._cubeSamplerName}, + #else + ${this._2DSamplerName}, + ${this._2DSamplerName}, + #endif + #endif + #ifdef REALTIME_FILTERING + ${this._vReflectionFilteringInfoName}, + #endif + reflectionOut + ); + #endif +`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==tg.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace}; +`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics}; +${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment}; +`}serialize(){var e,t;let i=super.serialize();return i.useSphericalHarmonics=this.useSphericalHarmonics,i.forceIrradianceInFragment=this.forceIrradianceInFragment,i.gammaSpace=null===(t=null===(e=this.texture)||void 0===e?void 0:e.gammaSpace)||void 0===t||t,i}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}};(0,rH.gn)([editableInPropertyPage("Spherical Harmonics",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],ReflectionBlock.prototype,"useSphericalHarmonics",void 0),(0,rH.gn)([editableInPropertyPage("Force irradiance in fragment",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],ReflectionBlock.prototype,"forceIrradianceInFragment",void 0),(0,rv.H)("BABYLON.ReflectionBlock",ReflectionBlock);let ClearCoatBlock=class ClearCoatBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",tm.Float,!1,tg.Fragment),this.registerInput("roughness",tm.Float,!0,tg.Fragment),this.registerInput("indexOfRefraction",tm.Float,!0,tg.Fragment),this.registerInput("normalMapColor",tm.Color3,!0,tg.Fragment),this.registerInput("uv",tm.Vector2,!0,tg.Fragment),this.registerInput("tintColor",tm.Color3,!0,tg.Fragment),this.registerInput("tintAtDistance",tm.Float,!0,tg.Fragment),this.registerInput("tintThickness",tm.Float,!0,tg.Fragment),this.registerInput("worldTangent",tm.Vector4,!0),this.registerInput("worldNormal",tm.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(tm.Color4|tm.Vector4|tm.Vector3),this.registerInput("TBN",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("TBN",this,tx.Input,TBNBlock,"TBNBlock")),this.registerOutput("clearcoat",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("clearcoat",this,tx.Output,ClearCoatBlock,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new InputBlock("ClearCoat intensity",tg.Fragment,tm.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var r,s;super.bind(e,t,i);let n=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,a=1-n,o=1+n,l=Math.pow(-a/o,2);e.setFloat4("vClearCoatRefractionParams",l,1/n,a,o);let h=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,u=(null==h?void 0:h.perturbedNormal.isConnected)?h.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",(null==u?void 0:u.invertX)?1:-1,(null==u?void 0:u.invertY)?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",(null==u?void 0:u.invertX)?-1:1,(null==u?void 0:u.invertY)?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1)}_generateTBNSpace(e,t,i){let r="",s=`//${this.name}`,n=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let a={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},o=this.TBN;return o.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${o.associatedVariableName}; + #endif + `:n.isConnected&&(r+=`vec3 tbnNormal = normalize(${i}.xyz); +vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); +vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[a]}),r}static GetCode(e,t,i,r,s,n,a){let o="",l=(null==t?void 0:t.intensity.isConnected)?t.intensity.associatedVariableName:"1.",h=(null==t?void 0:t.roughness.isConnected)?t.roughness.associatedVariableName:"0.",u=(null==t?void 0:t.normalMapColor.isConnected)?t.normalMapColor.associatedVariableName:"vec3(0.)",c=(null==t?void 0:t.uv.isConnected)?t.uv.associatedVariableName:"vec2(0.)",d=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",p=(null==t?void 0:t.tintThickness.isConnected)?t.tintThickness.associatedVariableName:"1.",_=(null==t?void 0:t.tintAtDistance.isConnected)?t.tintAtDistance.associatedVariableName:"1.";if(t){e._emitUniformFromString("vClearCoatRefractionParams","vec4"),e._emitUniformFromString("vClearCoatTangentSpaceParams","vec2");let i=t.worldNormal;o+=`vec3 vGeometricNormaClearCoatW = ${i.isConnected?"normalize("+i.associatedVariableName+".xyz)":"geometricNormalW"}; +`}else o+=`vec3 vGeometricNormaClearCoatW = geometricNormalW; +`;return s&&t&&(o+=t._generateTBNSpace(e,r,a),n=t.worldTangent.isConnected),o+=`clearcoatOutParams clearcoatOut; + + #ifdef CLEARCOAT + vec2 vClearCoatParams = vec2(${l}, ${h}); + vec4 vClearCoatTintParams = vec4(${d}, ${p}); + + clearcoatBlock( + ${r}.xyz, + vGeometricNormaClearCoatW, + viewDirectionW, + vClearCoatParams, + specularEnvironmentR0, + #ifdef CLEARCOAT_TEXTURE + vec2(0.), + #endif + #ifdef CLEARCOAT_TINT + vClearCoatTintParams, + ${_}, + vClearCoatRefractionParams, + #ifdef CLEARCOAT_TINT_TEXTURE + vec4(0.), + #endif + #endif + #ifdef CLEARCOAT_BUMP + vec2(0., 1.), + vec4(${u}, 0.), + ${c}, + #if defined(${n?"TANGENT":"IGNORE"}) && defined(NORMAL) + vTBN, + #else + vClearCoatTangentSpaceParams, + #endif + #ifdef OBJECTSPACE_NORMALMAP + normalMatrix, + #endif + #endif + #if defined(FORCENORMALFORWARD) && defined(NORMAL) + faceNormal, + #endif + #ifdef REFLECTION + ${null==i?void 0:i._vReflectionMicrosurfaceInfosName}, + ${null==i?void 0:i._vReflectionInfosName}, + ${null==i?void 0:i.reflectionColor}, + vLightingIntensity, + #ifdef ${null==i?void 0:i._define3DName} + ${null==i?void 0:i._cubeSamplerName}, + #else + ${null==i?void 0:i._2DSamplerName}, + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${null==i?void 0:i._define3DName} + ${null==i?void 0:i._cubeSamplerName}, + ${null==i?void 0:i._cubeSamplerName}, + #else + ${null==i?void 0:i._2DSamplerName}, + ${null==i?void 0:i._2DSamplerName}, + #endif + #endif + #endif + #if defined(ENVIRONMENTBRDF) && !defined(${null==i?void 0:i._defineSkyboxName}) + #ifdef RADIANCEOCCLUSION + ambientMonochrome, + #endif + #endif + #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) + (gl_FrontFacing ? 1. : -1.), + #endif + clearcoatOut + ); + #else + clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0; + #endif +`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===tg.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange}; +`}serialize(){let e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.remapF0OnInterfaceChange=null===(r=e.remapF0OnInterfaceChange)||void 0===r||r}};(0,rH.gn)([editableInPropertyPage("Remap F0 on interface change",tT.Boolean,"ADVANCED")],ClearCoatBlock.prototype,"remapF0OnInterfaceChange",void 0),(0,rv.H)("BABYLON.ClearCoatBlock",ClearCoatBlock);let IridescenceBlock=class IridescenceBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._isUnique=!0,this.registerInput("intensity",tm.Float,!0,tg.Fragment),this.registerInput("indexOfRefraction",tm.Float,!0,tg.Fragment),this.registerInput("thickness",tm.Float,!0,tg.Fragment),this.registerOutput("iridescence",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("iridescence",this,tx.Output,IridescenceBlock,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new InputBlock("Iridescence intensity",tg.Fragment,tm.Float);e.value=1,e.output.connectTo(this.intensity);let t=new InputBlock("Iridescence ior",tg.Fragment,tm.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);let i=new InputBlock("Iridescence thickness",tg.Fragment,tm.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e){let t=(null==e?void 0:e.intensity.isConnected)?e.intensity.associatedVariableName:"1.",i=(null==e?void 0:e.indexOfRefraction.isConnected)?e.indexOfRefraction.associatedVariableName:pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction,r=(null==e?void 0:e.thickness.isConnected)?e.thickness.associatedVariableName:pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness;return`iridescenceOutParams iridescenceOut; + + #ifdef IRIDESCENCE + iridescenceBlock( + vec4(${t}, ${i}, 1., ${r}), + NdotV, + specularEnvironmentR0, + #ifdef CLEARCOAT + NdotVUnclamped, + #endif + iridescenceOut + ); + + float iridescenceIntensity = iridescenceOut.iridescenceIntensity; + specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; + #endif +`}_buildBlock(e){return e.target===tg.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){let e=super.serialize();return e}_deserialize(e,t,i){super._deserialize(e,t,i)}};(0,rv.H)("BABYLON.IridescenceBlock",IridescenceBlock);let RefractionBlock=class RefractionBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",tm.Float,!1,tg.Fragment),this.registerInput("tintAtDistance",tm.Float,!0,tg.Fragment),this.registerInput("volumeIndexOfRefraction",tm.Float,!0,tg.Fragment),this.registerOutput("refraction",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("refraction",this,tx.Output,RefractionBlock,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e,t=()=>!0){if(!this.intensity.isConnected){let e=new InputBlock("Refraction intensity",tg.Fragment,tm.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(tC.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){var r,s,n,a;super.bind(e,t,i);let o=this._getTexture();if(!o)return;o.isCube?e.setTexture(this._cubeSamplerName,o):e.setTexture(this._2DSamplerName,o),e.setMatrix(this._refractionMatrixName,o.getRefractionTextureMatrix());let l=1;!o.isCube&&o.depth&&(l=o.depth);let h=null!==(a=null!==(s=null===(r=this.volumeIndexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:null===(n=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==a?a:1.5;e.setFloat4(this._vRefractionInfosName,o.level,1/h,l,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,o.getSize().width,o.lodGenerationScale,o.lodGenerationOffset,1/h);let u=o.getSize().width;e.setFloat2(this._vRefractionFilteringInfoName,u,rE.R.Log2(u)),o.boundingBoxSize&&(e.setVector3("vRefractionPosition",o.boundingBoxPosition),e.setVector3("vRefractionSize",o.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} +`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; +`,e._samplerDeclaration+=`#else +`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; +`,e._samplerDeclaration+=`#endif +`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",` + #ifdef ${this._define3DName} + #define sampleRefraction(s, c) textureCube(s, c) + #else + #define sampleRefraction(s, c) texture2D(s, c) + #endif +`,`//${this.name}`),e._emitFunction("sampleRefractionLod",` + #ifdef ${this._define3DName} + #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) + #else + #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) + #endif +`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"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}"); +`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}"); +`)+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency}; +${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY}; +${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth}; +`}serialize(){let 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=cubeTexture_CubeTexture.Parse(e.texture,t,i):this.texture=texture_Texture.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}};(0,rH.gn)([editableInPropertyPage("Link refraction to transparency",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"linkRefractionWithTransparency",void 0),(0,rH.gn)([editableInPropertyPage("Invert refraction Y",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"invertRefractionY",void 0),(0,rH.gn)([editableInPropertyPage("Use thickness as depth",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"useThicknessAsDepth",void 0),(0,rv.H)("BABYLON.RefractionBlock",RefractionBlock);let SubSurfaceBlock=class SubSurfaceBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._isUnique=!0,this.registerInput("thickness",tm.Float,!1,tg.Fragment),this.registerInput("tintColor",tm.Color3,!0,tg.Fragment),this.registerInput("translucencyIntensity",tm.Float,!0,tg.Fragment),this.registerInput("translucencyDiffusionDist",tm.Color3,!0,tg.Fragment),this.registerInput("refraction",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("refraction",this,tx.Input,RefractionBlock,"RefractionBlock")),this.registerOutput("subsurface",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("subsurface",this,tx.Output,SubSurfaceBlock,"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){let e=new InputBlock("SubSurface thickness",tg.Fragment,tm.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0)}static GetCode(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x;let T=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",S=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",C=(null==t?void 0:t.translucencyIntensity.isConnected)?null==t?void 0:t.translucencyIntensity.associatedVariableName:"1.",E=(null==t?void 0:t.translucencyDiffusionDist.isConnected)?null==t?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",b=(null==t?void 0:t.refraction.isConnected)?null===(s=null==t?void 0:t.refraction.connectedPoint)||void 0===s?void 0:s.ownerBlock:null,y=(null==b?void 0:b.tintAtDistance.isConnected)?b.tintAtDistance.associatedVariableName:"1.",P=(null==b?void 0:b.intensity.isConnected)?b.intensity.associatedVariableName:"1.",R=(null==b?void 0:b.view.isConnected)?b.view.associatedVariableName:"";return""+(null!==(n=null==b?void 0:b.getCode(e))&&void 0!==n?n:"")+`subSurfaceOutParams subSurfaceOut; + + #ifdef SUBSURFACE + vec2 vThicknessParam = vec2(0., ${T}); + vec4 vTintColor = vec4(${S}, ${y}); + vec3 vSubSurfaceIntensity = vec3(${P}, ${C}, 0.); + + subSurfaceBlock( + vSubSurfaceIntensity, + vThicknessParam, + vTintColor, + normalW, + specularEnvironmentReflectance, + #ifdef SS_THICKNESSANDMASK_TEXTURE + vec4(0.), + #endif + #ifdef REFLECTION + #ifdef SS_TRANSLUCENCY + ${null==i?void 0:i._reflectionMatrixName}, + #ifdef USESPHERICALFROMREFLECTIONMAP + #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) + reflectionOut.irradianceVector, + #endif + #if defined(REALTIME_FILTERING) + ${null==i?void 0:i._cubeSamplerName}, + ${null==i?void 0:i._vReflectionFilteringInfoName}, + #endif + #endif + #ifdef USEIRRADIANCEMAP + irradianceSampler, + #endif + #endif + #endif + #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) + surfaceAlbedo, + #endif + #ifdef SS_REFRACTION + ${r}.xyz, + viewDirectionW, + ${R}, + ${null!==(a=null==b?void 0:b._vRefractionInfosName)&&void 0!==a?a:""}, + ${null!==(o=null==b?void 0:b._refractionMatrixName)&&void 0!==o?o:""}, + ${null!==(l=null==b?void 0:b._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:""}, + vLightingIntensity, + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha, + #endif + #ifdef ${null!==(h=null==b?void 0:b._defineLODRefractionAlpha)&&void 0!==h?h:"IGNORE"} + NdotVUnclamped, + #endif + #ifdef ${null!==(u=null==b?void 0:b._defineLinearSpecularRefraction)&&void 0!==u?u:"IGNORE"} + roughness, + #endif + alphaG, + #ifdef ${null!==(c=null==b?void 0:b._define3DName)&&void 0!==c?c:"IGNORE"} + ${null!==(d=null==b?void 0:b._cubeSamplerName)&&void 0!==d?d:""}, + #else + ${null!==(p=null==b?void 0:b._2DSamplerName)&&void 0!==p?p:""}, + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${null!==(_=null==b?void 0:b._define3DName)&&void 0!==_?_:"IGNORE"} + ${null!==(f=null==b?void 0:b._cubeSamplerName)&&void 0!==f?f:""}, + ${null!==(m=null==b?void 0:b._cubeSamplerName)&&void 0!==m?m:""}, + #else + ${null!==(g=null==b?void 0:b._2DSamplerName)&&void 0!==g?g:""}, + ${null!==(v=null==b?void 0:b._2DSamplerName)&&void 0!==v?v:""}, + #endif + #endif + #ifdef ANISOTROPIC + anisotropicOut, + #endif + #ifdef REALTIME_FILTERING + ${null!==(x=null==b?void 0:b._vRefractionFilteringInfoName)&&void 0!==x?x:""}, + #endif + #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC + vRefractionPosition, + vRefractionSize, + #endif + #endif + #ifdef SS_TRANSLUCENCY + ${E}, + #endif + subSurfaceOut + ); + + #ifdef SS_REFRACTION + surfaceAlbedo = subSurfaceOut.surfaceAlbedo; + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha = subSurfaceOut.alpha; + #endif + #endif + #else + subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; + #endif +`}_buildBlock(e){return e.target===tg.Fragment&&e.sharedData.blocksWithDefines.push(this),this}};(0,rv.H)("BABYLON.SubSurfaceBlock",SubSurfaceBlock);let lF={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};let PBRMetallicRoughnessBlock=class PBRMetallicRoughnessBlock extends NodeMaterialBlock{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?tg.Fragment:tg.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tg.Fragment:tg.Vertex}constructor(e){super(e,tg.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=rg.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",tm.Vector4,!1,tg.Vertex),this.registerInput("worldNormal",tm.Vector4,!1,tg.Fragment),this.registerInput("view",tm.Matrix,!1),this.registerInput("cameraPosition",tm.Vector3,!1,tg.Fragment),this.registerInput("perturbedNormal",tm.Vector4,!0,tg.Fragment),this.registerInput("baseColor",tm.Color3,!0,tg.Fragment),this.registerInput("metallic",tm.Float,!1,tg.Fragment),this.registerInput("roughness",tm.Float,!1,tg.Fragment),this.registerInput("ambientOcc",tm.Float,!0,tg.Fragment),this.registerInput("opacity",tm.Float,!0,tg.Fragment),this.registerInput("indexOfRefraction",tm.Float,!0,tg.Fragment),this.registerInput("ambientColor",tm.Color3,!0,tg.Fragment),this.registerInput("reflection",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("reflection",this,tx.Input,ReflectionBlock,"ReflectionBlock")),this.registerInput("clearcoat",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("clearcoat",this,tx.Input,ClearCoatBlock,"ClearCoatBlock")),this.registerInput("sheen",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("sheen",this,tx.Input,SheenBlock,"SheenBlock")),this.registerInput("subsurface",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("subsurface",this,tx.Input,SubSurfaceBlock,"SubSurfaceBlock")),this.registerInput("anisotropy",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("anisotropy",this,tx.Input,AnisotropyBlock,"AnisotropyBlock")),this.registerInput("iridescence",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("iridescence",this,tx.Input,IridescenceBlock,"IridescenceBlock")),this.registerOutput("ambientClr",tm.Color3,tg.Fragment),this.registerOutput("diffuseDir",tm.Color3,tg.Fragment),this.registerOutput("specularDir",tm.Color3,tg.Fragment),this.registerOutput("clearcoatDir",tm.Color3,tg.Fragment),this.registerOutput("sheenDir",tm.Color3,tg.Fragment),this.registerOutput("diffuseInd",tm.Color3,tg.Fragment),this.registerOutput("specularInd",tm.Color3,tg.Fragment),this.registerOutput("clearcoatInd",tm.Color3,tg.Fragment),this.registerOutput("sheenInd",tm.Color3,tg.Fragment),this.registerOutput("refraction",tm.Color3,tg.Fragment),this.registerOutput("lighting",tm.Color3,tg.Fragment),this.registerOutput("shadow",tm.Float,tg.Fragment),this.registerOutput("alpha",tm.Float,tg.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(tC.CameraPosition),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(tC.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));let r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",0>r.indexOf(".")?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);let s=e.getScene(),n=s.getEngine();if(n._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&&MaterialFlags.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){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};so.G.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else so.G.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,so.G.PrepareDefinesForMultiview(s,i)}}updateUniformsAndSamples(e,t,i,r){for(let s=0;s<t.maxSimultaneousLights&&i["LIGHT"+s];s++){let t=e.uniforms.indexOf("vLightData"+s)>=0;so.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}isReady(e,t,i){return(!this._environmentBRDFTexture||!!this._environmentBRDFTexture.isReady())&&(!i._areImageProcessingDirty||!t.imageProcessingConfiguration||!!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var r,s;if(!i)return;let n=i.getScene();this.light?so.G.BindLight(this.light,this._lightId,n,e,!0):so.G.BindLights(n,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);let a=this._scene.ambientColor;a&&e.setColor3("ambientFromScene",a);let o=n.useRightHandedSystem===(null!=n._mirroredCameraPosition);e.setFloat(this._invertNormalName,o?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);let l=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((l-1)/(l+1),2)*this._metallicF0Factor,rg.zZ.Color3[0]);let h=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,rg.zZ.Color3[0],h),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;let r=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));let n="v_"+r.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${r.associatedVariableName}; +`);let a=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;a&&(a.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==a?void 0:a.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 +`,e._injectAtEnd+=`vClipSpacePosition = gl_Position; +`,e._injectAtEnd+=`#endif +`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:r.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${r.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e=`albedoOpacityOutParams albedoOpacityOut; +`,t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+`albedoOpacityBlock( + vec4(${t}, 1.), + #ifdef ALBEDO + vec4(1.), + vec2(1., 1.), + #endif + #ifdef OPACITY + vec4(${i}), + vec2(1., 1.), + #endif + albedoOpacityOut + ); + + vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; + float alpha = albedoOpacityOut.alpha; +`}_getAmbientOcclusionCode(){let e=`ambientOcclusionOutParams aoOut; +`,t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+`ambientOcclusionBlock( + #ifdef AMBIENT + vec3(${t}), + vec4(0., 1.0, 1.0, 0.), + #endif + aoOut + ); +`}_getReflectivityCode(e){let t=`reflectivityOutParams reflectivityOut; +`;return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo; + + reflectivityBlock( + vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.), + #ifdef METALLICWORKFLOW + surfaceAlbedo, + ${this._vMetallicReflectanceFactorsName}, + #endif + #ifdef REFLECTIVITY + vec3(0., 0., 1.), + vec4(1.), + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + aoOut.ambientOcclusionColor, + #endif + #ifdef MICROSURFACEMAP + microSurfaceTexel, <== not handled! + #endif + reflectivityOut + ); + + float microSurface = reflectivityOut.microSurface; + float roughness = reflectivityOut.roughness; + + #ifdef METALLICWORKFLOW + surfaceAlbedo = reflectivityOut.surfaceAlbedo; + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; + #endif +`}_buildBlock(e){var t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x,T,S,C,E,b,y,P,R,A,I,M,D,O,N,F,B,L,w,U,V,k,G;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this._scene));let 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!==tg.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);let W=`//${this.name}`,H=this.perturbedNormal,X=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(X=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${X}; +`,W),e.compilationString+=`${X} = ${this.worldPosition.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 +`,e.compilationString+=`vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0); +`,e.compilationString+=`#endif +`):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),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}); +`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${X}.xyz); +`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz; +`,e.compilationString+=`vec3 normalW = ${H.isConnected?"normalize("+H.associatedVariableName+".xyz)":"geometricNormalW"}; +`,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 + vec3 diffuseBase = vec3(1., 1., 1.); + #else +`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(r=null==z?void 0:z._defineSkyboxName)&&void 0!==r?r:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==z?void 0:z._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"}]});let Y=this.anisotropy.isConnected?null===(n=this.anisotropy.connectedPoint)||void 0===n?void 0:n.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!==(a=null==z?void 0:z._define3DName)&&void 0!==a?a:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(o=null==z?void 0:z._defineOppositeZ)&&void 0!==o?o:"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!==(u=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==u?u:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(c=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==c?c:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(d=null==z?void 0:z._vReflectionFilteringInfoName)&&void 0!==d?d:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",W,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});let 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!==(_=null==z?void 0:z._define3DName)&&void 0!==_?_:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(f=null==z?void 0:z._defineSkyboxName)&&void 0!==f?f:"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"}]});let K=this.iridescence.isConnected?null===(v=this.iridescence.connectedPoint)||void 0===v?void 0:v.ownerBlock:null;e.compilationString+=IridescenceBlock.GetCode(K),e._emitFunctionFromInclude("pbrBlockIridescence",W,{replaceStrings:[]});let $=this.clearcoat.isConnected?null===(x=this.clearcoat.connectedPoint)||void 0===x?void 0:x.ownerBlock:null,Q=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Z=this.perturbedNormal.isConnected&&(null===(S=(null===(T=this.perturbedNormal.connectedPoint)||void 0===T?void 0:T.ownerBlock).worldTangent)||void 0===S?void 0:S.isConnected),J=this.anisotropy.isConnected&&(null===(C=this.anisotropy.connectedPoint)||void 0===C?void 0:C.ownerBlock).worldTangent.isConnected,ee=Z||!this.perturbedNormal.isConnected&&J;e.compilationString+=ClearCoatBlock.GetCode(e,$,z,X,Q,ee,this.worldNormal.associatedVariableName),Q&&(ee=null!==(E=null==$?void 0:$.worldTangent.isConnected)&&void 0!==E&&E),e._emitFunctionFromInclude("pbrBlockClearcoat",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(b=null==z?void 0:z._define3DName)&&void 0!==b?b:"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!==(P=null==z?void 0:z._defineProjectionName)&&void 0!==P?P:"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!==(A=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==A?A:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(I=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==I?I:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:ee?"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!==(D=null==z?void 0:z._define3DName)&&void 0!==D?D:"REFLECTIONMAP_3D"}]});let et=this.subsurface.isConnected?null===(O=this.subsurface.connectedPoint)||void 0===O?void 0:O.ownerBlock:null,ei=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;ei&&(ei.viewConnectionPoint=this.view,ei.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=SubSurfaceBlock.GetCode(e,et,z,X),e._emitFunctionFromInclude("pbrBlockSubSurface",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(B=null==z?void 0:z._define3DName)&&void 0!==B?B:"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!==(w=null==z?void 0:z._defineProjectionName)&&void 0!==w?w:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:null!==(U=null==ei?void 0:ei._define3DName)&&void 0!==U?U:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(V=null==ei?void 0:ei._defineLODRefractionAlpha)&&void 0!==V?V:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(k=null==ei?void 0:ei._defineLinearSpecularRefraction)&&void 0!==k?k:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(G=null==ei?void 0:ei._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()},{search:/vPositionW/g,replace:X+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{repeatKey:"maxSimultaneousLights",replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",W),e.compilationString+=`#endif +`;let er=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",es=pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();for(let t of(-1===es.indexOf(".")&&(es+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",W,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:er+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:es}]}),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.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]}),this._outputs))if(t.hasEndpoints){let i=lF[t.name];if(i){let[r,s]=i;s&&(e.compilationString+=`#if ${s} +`),e.compilationString+=`${this._declareOutput(t,e)} = ${r}; +`,s&&(e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(t,e)} = vec3(0.); +`,e.compilationString+=`#endif +`)}else console.error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lightFalloff = ${this.lightFalloff}; +${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest}; +${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff}; +${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending}; +${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha}; +${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha}; +${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing}; +${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering}; +${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality}; +${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation}; +${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion}; +${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion}; +${this._codeVariableName}.unlit = ${this.unlit}; +${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward}; +${this._codeVariableName}.debugMode = ${this.debugMode}; +${this._codeVariableName}.debugLimit = ${this.debugLimit}; +${this._codeVariableName}.debugFactor = ${this.debugFactor}; +`}serialize(){let 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 r,s;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=null!==(r=e.lightFalloff)&&void 0!==r?r: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,rH.gn)([editableInPropertyPage("Direct lights",tT.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"directIntensity",void 0),(0,rH.gn)([editableInPropertyPage("Environment lights",tT.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"environmentIntensity",void 0),(0,rH.gn)([editableInPropertyPage("Specular highlights",tT.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"specularIntensity",void 0),(0,rH.gn)([editableInPropertyPage("Light falloff",tT.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF},{label:"Standard",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD}]})],PBRMetallicRoughnessBlock.prototype,"lightFalloff",void 0),(0,rH.gn)([editableInPropertyPage("Alpha Testing",tT.Boolean,"OPACITY")],PBRMetallicRoughnessBlock.prototype,"useAlphaTest",void 0),(0,rH.gn)([editableInPropertyPage("Alpha CutOff",tT.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"alphaTestCutoff",void 0),(0,rH.gn)([editableInPropertyPage("Alpha blending",tT.Boolean,"OPACITY")],PBRMetallicRoughnessBlock.prototype,"useAlphaBlending",void 0),(0,rH.gn)([editableInPropertyPage("Radiance over alpha",tT.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useRadianceOverAlpha",void 0),(0,rH.gn)([editableInPropertyPage("Specular over alpha",tT.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useSpecularOverAlpha",void 0),(0,rH.gn)([editableInPropertyPage("Specular anti-aliasing",tT.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"enableSpecularAntiAliasing",void 0),(0,rH.gn)([editableInPropertyPage("Realtime filtering",tT.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"realTimeFiltering",void 0),(0,rH.gn)([editableInPropertyPage("Realtime filtering quality",tT.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],PBRMetallicRoughnessBlock.prototype,"realTimeFilteringQuality",void 0),(0,rH.gn)([editableInPropertyPage("Energy Conservation",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useEnergyConservation",void 0),(0,rH.gn)([editableInPropertyPage("Radiance occlusion",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useRadianceOcclusion",void 0),(0,rH.gn)([editableInPropertyPage("Horizon occlusion",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useHorizonOcclusion",void 0),(0,rH.gn)([editableInPropertyPage("Unlit",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"unlit",void 0),(0,rH.gn)([editableInPropertyPage("Force normal forward",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"forceNormalForward",void 0),(0,rH.gn)([editableInPropertyPage("Generate only fragment code",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:PBRMetallicRoughnessBlock._OnGenerateOnlyFragmentCodeChanged}})],PBRMetallicRoughnessBlock.prototype,"generateOnlyFragmentCode",void 0),(0,rH.gn)([editableInPropertyPage("Debug mode",tT.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}]})],PBRMetallicRoughnessBlock.prototype,"debugMode",void 0),(0,rH.gn)([editableInPropertyPage("Split position",tT.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"debugLimit",void 0),(0,rH.gn)([editableInPropertyPage("Output factor",tT.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"debugFactor",void 0),(0,rv.H)("BABYLON.PBRMetallicRoughnessBlock",PBRMetallicRoughnessBlock);let ModBlock=class ModBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.ModBlock",ModBlock);let MatrixBuilderBlock=class MatrixBuilderBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("row0",tm.Vector4),this.registerInput("row1",tm.Vector4),this.registerInput("row2",tm.Vector4),this.registerInput("row3",tm.Vector4),this.registerOutput("output",tm.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){let e=new InputBlock("row0");e.value=new rm.Lt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){let e=new InputBlock("row1");e.value=new rm.Lt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){let e=new InputBlock("row2");e.value=new rm.Lt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){let e=new InputBlock("row3");e.value=new rm.Lt(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.row0,r=this.row1,s=this.row2,n=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${r.associatedVariableName}, ${s.associatedVariableName}, ${n.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.MatrixBuilder",MatrixBuilderBlock),(eO=iO||(iO={}))[eO.Equal=0]="Equal",eO[eO.NotEqual=1]="NotEqual",eO[eO.LessThan=2]="LessThan",eO[eO.GreaterThan=3]="GreaterThan",eO[eO.LessOrEqual=4]="LessOrEqual",eO[eO.GreaterOrEqual=5]="GreaterOrEqual",eO[eO.Xor=6]="Xor",eO[eO.Or=7]="Or",eO[eO.And=8]="And";let ConditionalBlock=class ConditionalBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.condition=iO.LessThan,this.registerInput("a",tm.Float),this.registerInput("b",tm.Float),this.registerInput("true",tm.AutoDetect,!0),this.registerInput("false",tm.AutoDetect,!0),this.registerOutput("output",tm.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=tm.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);let t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case iO.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iO.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iO.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iO.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iO.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iO.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iO.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${r}; +`;break;case iO.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${r}; +`;break;case iO.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${r}; +`}return this}serialize(){let e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${iO[this.condition]}; +`;return e}};(0,rv.H)("BABYLON.ConditionalBlock",ConditionalBlock);let CloudBlock=class CloudBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.octaves=6,this.registerInput("seed",tm.AutoDetect),this.registerInput("chaos",tm.AutoDetect,!0),this.registerInput("offsetX",tm.Float,!0),this.registerInput("offsetY",tm.Float,!0),this.registerInput("offsetZ",tm.Float,!0),this.registerOutput("output",tm.Float),this._inputs[0].acceptedConnectionPointTypes.push(tm.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(tm.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||!this._outputs[0].hasEndpoints)return;let r=` + + float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } + + // Based on Morgan McGuire @morgan3d + // https://www.shadertoy.com/view/4dS3Wd + float cloudNoise(in vec2 x, in vec2 chaos) { + vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); + + vec2 i = floor(x); + vec2 f = fract(x); + + float n = dot(i, step); + + vec2 u = f * f * (3.0 - 2.0 * f); + return mix( + mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), + mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), + u.y + ); + } + + float cloudNoise(in vec3 x, in vec3 chaos) { + vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); + + vec3 i = floor(x); + vec3 f = fract(x); + + float n = dot(i, step); + + vec3 u = f * f * (3.0 - 2.0 * f); + return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), + mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), + mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), + mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); + }`,s=` + float fbm(in vec2 st, in vec2 chaos) { + // Initial values + float value = 0.0; + float amplitude = .5; + float frequency = 0.; + + // Loop of octaves + for (int i = 0; i < OCTAVES; i++) { + value += amplitude * cloudNoise(st, chaos); + st *= 2.0; + amplitude *= 0.5; + } + return value; + } + + float fbm(in vec3 x, in vec3 chaos) { + // Initial values + float value = 0.0; + float amplitude = 0.5; + for (int i = 0; i < OCTAVES; ++i) { + value += amplitude * cloudNoise(x, chaos); + x = x * 2.0; + amplitude *= 0.5; + } + return value; + }`,n=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",r,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,s.replace(/fbm/gi,n).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");let a=e._getFreeVariableName("st"),o=(null===(t=this.seed.connectedPoint)||void 0===t?void 0:t.type)===tm.Vector2?"vec2":"vec3";e.compilationString+=`${o} ${a} = ${this.seed.associatedVariableName}; +`,this.offsetX.isConnected&&(e.compilationString+=`${a}.x += 0.1 * ${this.offsetX.associatedVariableName}; +`),this.offsetY.isConnected&&(e.compilationString+=`${a}.y += 0.1 * ${this.offsetY.associatedVariableName}; +`),this.offsetZ.isConnected&&"vec3"===o&&(e.compilationString+=`${a}.z += 0.1 * ${this.offsetZ.associatedVariableName}; +`);let l="";return l=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===tm.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${n}(${a}, ${l}); +`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves}; +`;return e}serialize(){let e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}};(0,rH.gn)([editableInPropertyPage("Octaves",tT.Int)],CloudBlock.prototype,"octaves",void 0),(0,rv.H)("BABYLON.CloudBlock",CloudBlock);let VoronoiNoiseBlock=class VoronoiNoiseBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("seed",tm.Vector2),this.registerInput("offset",tm.Float),this.registerInput("density",tm.Float),this.registerOutput("output",tm.Float),this.registerOutput("cells",tm.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t=`vec2 voronoiRandom(vec2 seed, float offset){ + mat2 m = mat2(15.27, 47.63, 99.41, 89.98); + vec2 uv = fract(sin(m * seed) * 46839.32); + return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5); + } + `;e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ + vec2 g = floor(seed * density); + vec2 f = fract(seed * density); + float t = 8.0; + vec3 res = vec3(8.0, 0.0, 0.0); + + for(int y=-1; y<=1; y++) + { + for(int x=-1; x<=1; x++) + { + vec2 lattice = vec2(x,y); + vec2 randomOffset = voronoiRandom(lattice + g, offset); + float d = distance(lattice + randomOffset, f); + if(d < res.x) + { + res = vec3(d, randomOffset.x, randomOffset.y); + outValue = res.x; + cells = res.y; + } + } + } + } + `,e._emitFunction("voronoi",t,"// Voronoi");let i=e._getFreeVariableName("tempOutput"),r=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0; +`,e.compilationString+=`float ${r} = 0.0; +`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${r}); +`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; +`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${r}; +`),this}};(0,rv.H)("BABYLON.VoronoiNoiseBlock",VoronoiNoiseBlock);let ElbowBlock=class ElbowBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.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(){let e=this._inputs[0];if(e.isConnected){let t=e.connectedPoint.ownerBlock;if(t.target!==tg.VertexAndFragment)return t.target;if(e.connectedPoint.target!==tg.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){(this._target&e)==0&&(this._target=e)}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName}; +`,this}};(0,rv.H)("BABYLON.ElbowBlock",ElbowBlock);let TriPlanarBlock=class TriPlanarBlock extends NodeMaterialBlock{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;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rS.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(){let 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)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rS.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)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rS.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,tg.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",tm.AutoDetect,!1),this.registerInput("normal",tm.AutoDetect,!1),this.registerInput("sharpness",tm.Float,!0),this.registerInput("source",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,tx.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerInput("sourceY",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("sourceY",this,tx.Input,ImageSourceBlock,"ImageSourceBlock")),t||this.registerInput("sourceZ",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("sourceZ",this,tx.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("rgba",tm.Color4,tg.Neutral),this.registerOutput("rgb",tm.Color3,tg.Neutral),this.registerOutput("r",tm.Float,tg.Neutral),this.registerOutput("g",tm.Float,tg.Neutral),this.registerOutput("b",tm.Float,tg.Neutral),this.registerOutput("a",tm.Float,tg.Neutral),this.registerOutput("level",tm.Float,tg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.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;let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){var t,i;let r=this.samplerName,s=null!==(t=this.samplerYName)&&void 0!==t?t:r,n=null!==(i=this.samplerZName)&&void 0!==i?i:r,a=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",o=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),u=e._getFreeVariableName("w"),c=e._getFreeVariableName("n"),d=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),_=e._getFreeVariableName("uvz");e.compilationString+=` + vec3 ${c} = ${this.normal.associatedVariableName}.xyz; + + vec2 ${d} = ${this.position.associatedVariableName}.yz; + vec2 ${p} = ${this.position.associatedVariableName}.zx; + vec2 ${_} = ${this.position.associatedVariableName}.xy; + `,this.projectAsCube&&(e.compilationString+=` + ${d}.xy = ${d}.yx; + + if (${c}.x >= 0.0) { + ${d}.x = -${d}.x; + } + if (${c}.y < 0.0) { + ${p}.y = -${p}.y; + } + if (${c}.z < 0.0) { + ${_}.x = -${_}.x; + } + `),e.compilationString+=` + vec4 ${o} = texture2D(${r}, ${d}); + vec4 ${l} = texture2D(${s}, ${p}); + vec4 ${h} = texture2D(${n}, ${_}); + + // blend weights + vec3 ${u} = pow(abs(${c}), vec3(${a})); + + // blend and return + vec4 ${this._tempTextureRead} = (${o}*${u}.x + ${l}*${u}.y + ${h}*${u}.z) / (${u}.x + ${u}.y + ${u}.z); + `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} + ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); + #endif + `),e.compilationString+=`#ifdef ${this._gammaDefineName} + ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); + #endif + `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r}; +`,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);let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e),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}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; +${this._codeVariableName}.projectAsCube = ${this.projectAsCube}; +`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let 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&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};(0,rH.gn)([editableInPropertyPage("Project as cube",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],TriPlanarBlock.prototype,"projectAsCube",void 0),(0,rv.H)("BABYLON.TriPlanarBlock",TriPlanarBlock);let BiPlanarBlock=class BiPlanarBlock extends TriPlanarBlock{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;let i=this.samplerName,r=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("dpdx"),a=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),u=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+=` + // grab coord derivatives for texturing + vec3 ${n} = dFdx(${this.position.associatedVariableName}.xyz); + vec3 ${a} = dFdy(${this.position.associatedVariableName}.xyz); + vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz); + + // determine major axis (in x; yz are following axis) + ivec3 ${l} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) : + (${o}.y>${o}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine minor axis (in x; yz are following axis) + ivec3 ${h} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) : + (${o}.y<${o}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine median axis (in x; yz are following axis) + ivec3 ${u} = ivec3(3) - ${h} - ${l}; + + // project+fetch + vec4 ${c} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), + vec2(${n}[${l}.y],${n}[${l}.z]), + vec2(${a}[${l}.y],${a}[${l}.z]) ); + vec4 ${d} = textureGrad( ${r}, vec2( ${this.position.associatedVariableName}[${u}.y], ${this.position.associatedVariableName}[${u}.z]), + vec2(${n}[${u}.y],${n}[${u}.z]), + vec2(${a}[${u}.y],${a}[${u}.z]) ); + + // blend factors + vec2 ${p} = vec2(${o}[${l}.x],${o}[${u}.x]); + // make local support + ${p} = clamp( (${p}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); + // shape transition + ${p} = pow( ${p}, vec2(${s}/8.0) ); + // blend and return + vec4 ${this._tempTextureRead} = (${c}*${p}.x + ${d}*${p}.y) / (${p}.x + ${p}.y); + `}};(0,rv.H)("BABYLON.BiPlanarBlock",BiPlanarBlock);let MatrixDeterminantBlock=class MatrixDeterminantBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.Matrix),this.registerOutput("output",tm.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.MatrixDeterminantBlock",MatrixDeterminantBlock);let MatrixTransposeBlock=class MatrixTransposeBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.Matrix),this.registerOutput("output",tm.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName}); +`,this}};(0,rv.H)("BABYLON.MatrixTransposeBlock",MatrixTransposeBlock),(eN=iN||(iN={}))[eN.None=0]="None",eN[eN.Normal=1]="Normal",eN[eN.Tangent=2]="Tangent",eN[eN.VertexColor=3]="VertexColor",eN[eN.UV1=4]="UV1",eN[eN.UV2=5]="UV2",eN[eN.UV3=6]="UV3",eN[eN.UV4=7]="UV4",eN[eN.UV5=8]="UV5",eN[eN.UV6=9]="UV6";let MeshAttributeExistsBlock=class MeshAttributeExistsBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.attributeType=iN.None,this.registerInput("input",tm.AutoDetect),this.registerInput("fallback",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(e=>{var t;if(this.attributeType)return;let i=e.ownerBlock;if(i instanceof InputBlock&&i.isAttribute)switch(i.name){case"color":this.attributeType=iN.VertexColor;break;case"normal":this.attributeType=iN.Normal;break;case"tangent":this.attributeType=iN.Tangent;break;case"uv":this.attributeType=iN.UV1;break;case"uv2":this.attributeType=iN.UV2;break;case"uv3":this.attributeType=iN.UV3;break;case"uv4":this.attributeType=iN.UV4;break;case"uv5":this.attributeType=iN.UV5;break;case"uv6":this.attributeType=iN.UV6}else if(i instanceof MorphTargetsBlock)switch(null===(t=this.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":this.attributeType=iN.Normal;break;case"tangentOutput":this.attributeType=iN.Tangent;break;case"uvOutput":this.attributeType=iN.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 iN.VertexColor:t="VERTEXCOLOR_NME";break;case iN.Normal:t="NORMAL";break;case iN.Tangent:t="TANGENT";break;case iN.UV1:t="UV1";break;case iN.UV2:t="UV2";break;case iN.UV3:t="UV3";break;case iN.UV4:t="UV4";break;case iN.UV5:t="UV5";break;case iN.UV6:t="UV6"}let i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t} +`),e.compilationString+=`${i} = ${this.input.associatedVariableName}; +`,t&&(e.compilationString+=`#else +`,e.compilationString+=`${i} = ${this.fallback.associatedVariableName}; +`,e.compilationString+=`#endif +`),this}serialize(){let e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.attributeType=null!==(r=e.attributeType)&&void 0!==r?r:iN.None}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.attributeType = ${this.attributeType}; +`}};(0,rH.gn)([editableInPropertyPage("Attribute lookup",tT.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:iN.None},{label:"Normal",value:iN.Normal},{label:"Tangent",value:iN.Tangent},{label:"Vertex Color",value:iN.VertexColor},{label:"UV1",value:iN.UV1},{label:"UV2",value:iN.UV2},{label:"UV3",value:iN.UV3},{label:"UV4",value:iN.UV4},{label:"UV5",value:iN.UV5},{label:"UV6",value:iN.UV6}]})],MeshAttributeExistsBlock.prototype,"attributeType",void 0),(0,rv.H)("BABYLON.MeshAttributeExistsBlock",MeshAttributeExistsBlock),(eF=iF||(iF={}))[eF.EaseInSine=0]="EaseInSine",eF[eF.EaseOutSine=1]="EaseOutSine",eF[eF.EaseInOutSine=2]="EaseInOutSine",eF[eF.EaseInQuad=3]="EaseInQuad",eF[eF.EaseOutQuad=4]="EaseOutQuad",eF[eF.EaseInOutQuad=5]="EaseInOutQuad",eF[eF.EaseInCubic=6]="EaseInCubic",eF[eF.EaseOutCubic=7]="EaseOutCubic",eF[eF.EaseInOutCubic=8]="EaseInOutCubic",eF[eF.EaseInQuart=9]="EaseInQuart",eF[eF.EaseOutQuart=10]="EaseOutQuart",eF[eF.EaseInOutQuart=11]="EaseInOutQuart",eF[eF.EaseInQuint=12]="EaseInQuint",eF[eF.EaseOutQuint=13]="EaseOutQuint",eF[eF.EaseInOutQuint=14]="EaseInOutQuint",eF[eF.EaseInExpo=15]="EaseInExpo",eF[eF.EaseOutExpo=16]="EaseOutExpo",eF[eF.EaseInOutExpo=17]="EaseInOutExpo",eF[eF.EaseInCirc=18]="EaseInCirc",eF[eF.EaseOutCirc=19]="EaseOutCirc",eF[eF.EaseInOutCirc=20]="EaseInOutCirc",eF[eF.EaseInBack=21]="EaseInBack",eF[eF.EaseOutBack=22]="EaseOutBack",eF[eF.EaseInOutBack=23]="EaseInOutBack",eF[eF.EaseInElastic=24]="EaseInElastic",eF[eF.EaseOutElastic=25]="EaseOutElastic",eF[eF.EaseInOutElastic=26]="EaseInOutElastic";let CurveBlock=class CurveBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.type=iF.EaseInOutSine,this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tm.Object),this._inputs[0].excludedConnectionPointTypes.push(tm.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);let i=parseInt(t.replace("vec","")),r=` + vec${i} ret = vec${i}(0.0); + `;for(let t=1;t<=i;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+"return ret;\n"}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="",r="",s="";switch(this.input.type){case tm.Float:s="float";break;case tm.Vector2:s="vec2";break;case tm.Vector3:case tm.Color3:s="vec3";break;case tm.Vector4:case tm.Color4:s="vec4"}switch(r=iF[this.type]+"_"+s,this.type){case iF.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case iF.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case iF.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case iF.EaseInQuad:i="return v * v";break;case iF.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case iF.EaseInOutQuad:i=this._duplicateVector("VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0",s);break;case iF.EaseInCubic:i="return v * v * v";break;case iF.EaseOutCubic:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",s);break;case iF.EaseInOutCubic:i=this._duplicateVector("VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0",s);break;case iF.EaseInQuart:i="return v * v * v * v";break;case iF.EaseOutQuart:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",s);break;case iF.EaseInOutQuart:i=this._duplicateVector("VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0",s);break;case iF.EaseInQuint:i="return v * v * v * v * v";break;case iF.EaseOutQuint:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",s);break;case iF.EaseInOutQuint:i=this._duplicateVector("VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0",s);break;case iF.EaseInExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)",s);break;case iF.EaseOutExpo:i=this._duplicateVector("VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)",s);break;case iF.EaseInOutExpo:i=this._duplicateVector("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",s);break;case iF.EaseInCirc:i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",s);break;case iF.EaseOutCirc:i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",s);break;case iF.EaseInOutCirc:i=this._duplicateVector("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",s);break;case iF.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case iF.EaseOutBack:i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",s);break;case iF.EaseInOutBack:i=this._duplicateVector("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",s);break;case iF.EaseInElastic:i=this._duplicateVector("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))",s);break;case iF.EaseOutElastic:i=this._duplicateVector("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",s);break;case iF.EaseInOutElastic:i=this._duplicateVector("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",s)}return e._emitFunction(r,`${s} ${r}(${s} v) {${i};} +`,""),e.compilationString+=this._declareOutput(t,e)+` = ${r}(${this.input.associatedVariableName}); +`,this}serialize(){let e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${iF[this.type]}; +`;return e}};(0,rv.H)("BABYLON.CurveBlock",CurveBlock);let DecalMapDefines=class DecalMapDefines extends sn.H{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}};let DecalMapConfiguration=class DecalMapConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new DecalMapDefines,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,r){let s=r.getMesh().decalMap;return!this._isEnabled||null==s||!s.texture||!MaterialFlags.DecalMapEnabled||!t.texturesEnabled||s.isReady()}prepareDefines(e,t,i){let r=i.decalMap;if(this._isEnabled&&(null==r?void 0:r.texture)&&MaterialFlags.DecalMapEnabled&&t.texturesEnabled){let t=!e.DECAL||e.GAMMADECAL!==r.texture.gammaSpace;t&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=r.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,so.G.PrepareDefinesForMergedUV(r.texture,e,"DECAL")}else{let t=e.DECAL;t&&e.markAsTexturesDirty(),e.DECAL=!1}}hardBindForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;if(!this._isEnabled||!(null==s?void 0:s.texture)||!MaterialFlags.DecalMapEnabled||!t.texturesEnabled)return;let n=this._material.isFrozen,a=s.texture;e.useUbo&&n&&e.isSync||(e.updateFloat4("vDecalInfos",a.coordinatesIndex,0,0,0),so.G.BindTextureMatrix(a,e,"decal")),e.setTexture("decalSampler",a)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}};(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],DecalMapConfiguration.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],DecalMapConfiguration.prototype,"smoothAlpha",void 0),(0,rv.H)("BABYLON.DecalMapConfiguration",DecalMapConfiguration),(eB=iB||(iB={}))[eB.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",eB[eB.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",eB[eB.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE",(eL=iL||(iL={}))[eL.COLOR_MODE_SET=0]="COLOR_MODE_SET",eL[eL.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",eL[eL.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY",(ew=iw||(iw={}))[ew.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",ew[ew.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE";let greasedLineMaterialDefaults_GreasedLineMaterialDefaults=class greasedLineMaterialDefaults_GreasedLineMaterialDefaults{};greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR=rg.Wo.White(),greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED=1,greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH=.1;let greasedLineTools_GreasedLineTools=class greasedLineTools_GreasedLineTools{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 rm.P){let t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push(r.x,r.y,r.z)}return[t]}if(e.length>0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof rm.P){let 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){let t=[];return e.forEach(e=>{t.push(Array.from(e))}),t}return[]}static OmitZeroLengthPredicate(e,t,i){let r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),0===r.length?null:r}static OmitDuplicatesPredicate(e,t,i,r){let s=[];return greasedLineTools_GreasedLineTools._SearchInPoints(e,t,r)||s.push([e,t]),greasedLineTools_GreasedLineTools._SearchInPoints(t,i,r)||s.push([t,i]),greasedLineTools_GreasedLineTools._SearchInPoints(i,e,r)||s.push([i,e]),0===s.length?null:s}static _SearchInPoints(e,t,i){var r,s,n;for(let a of i)for(let i=0;i<a.length;i++)if((null===(r=a[i])||void 0===r?void 0:r.equals(e))&&((null===(s=a[i+1])||void 0===s?void 0:s.equals(t))||(null===(n=a[i-1])||void 0===n?void 0:n.equals(t))))return!0;return!1}static MeshesToLines(e,t){let i=[];return e.forEach((e,r)=>{let s=e.getVerticesData(rz.o.PositionKind),n=e.getIndices();if(s&&n)for(let a=0,o=0;a<n.length;a++){let l=3*n[o++],h=3*n[o++],u=3*n[o++],c=new rm.P(s[l],s[l+1],s[l+2]),d=new rm.P(s[h],s[h+1],s[h+2]),p=new rm.P(s[u],s[u+1],s[u+2]);if(t){let o=t(c,d,p,i,a,l,e,r,s,n);if(o)for(let e of o)i.push(e)}else i.push([c,d],[d,p],[p,c])}}),i}static ToVector3Array(e){if(Array.isArray(e[0])){let t=[];for(let i of e){let e=[];for(let t=0;t<i.length;t+=3)e.push(new rm.P(i[t],i[t+1],i[t+2]));t.push(e)}return t}let t=[];for(let i=0;i<e.length;i+=3)t.push(new rm.P(e[i],e[i+1],e[i+2]));return t}static ToNumberArray(e){return e.flatMap(e=>[e.x,e.y,e.z])}static GetPointsCountInfo(e){let t=Array(e.length),i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){let t;if(0===e.length)return 0;t="number"==typeof e[0]?greasedLineTools_GreasedLineTools.ToVector3Array(e):e;let i=rm.jp.Vector3[0],r=0;for(let e=0;e<t.length-1;e++){let s=t[e],n=t[e+1];r+=n.subtractToRef(s,i).length()}return r}static SegmentizeSegmentByCount(e,t,i){let r=[],s=t.subtract(e),n=rm.jp.Vector3[0];n.setAll(i);let a=rm.jp.Vector3[1];s.divideToRef(n,a);let o=e.clone();r.push(o);for(let e=0;e<i;e++)r.push((o=o.clone()).addInPlace(a));return r}static SegmentizeLineBySegmentLength(e,t){let i=e[0]instanceof rm.P?greasedLineTools_GreasedLineTools.GetLineSegments(e):"number"==typeof e[0]?greasedLineTools_GreasedLineTools.GetLineSegments(greasedLineTools_GreasedLineTools.ToVector3Array(e)):e,r=[];return i.forEach(e=>{if(e.length>t){let i=greasedLineTools_GreasedLineTools.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t));i.forEach(e=>{r.push(e)})}else r.push(e.point1),r.push(e.point2)}),r}static SegmentizeLineBySegmentCount(e,t){let i="number"==typeof e[0]?greasedLineTools_GreasedLineTools.ToVector3Array(e):e,r=greasedLineTools_GreasedLineTools.GetLineLength(i)/t;return greasedLineTools_GreasedLineTools.SegmentizeLineBySegmentLength(i,r)}static GetLineSegments(e){let t=[];for(let i=0;i<e.length-1;i++){let r=e[i],s=e[i+1],n=s.subtract(r).length();t.push({point1:r,point2:s,length:n})}return t}static GetMinMaxSegmentLength(e){let t=greasedLineTools_GreasedLineTools.GetLineSegments(e),i=t.sort(e=>e.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){let s=t*i,n=0,a=0,o=e.length;for(let t=0;t<o;t++){if(s<=n+e[t].length){a=t;break}n+=e[t].length}let l=(s-n)/e[a].length;return e[a].point2.subtractToRef(e[a].point1,rm.jp.Vector3[0]),rm.jp.Vector3[1]=rm.jp.Vector3[0].multiplyByFloats(l,l,l),r||rm.jp.Vector3[1].addInPlace(e[a].point1),rm.jp.Vector3[1].clone()}static GetCircleLinePoints(e,t,i=0,r=e,s=2*Math.PI/t){let n=[];for(let a=0;a<=t;a++)n.push(new rm.P(Math.cos(a*s)*e,Math.sin(a*s)*r,i));return n}static GetBezierLinePoints(e,t,i,r){return Curve3.CreateQuadraticBezier(e,t,i,r).getPoints().flatMap(e=>[e.x,e.y,e.z])}static GetArrowCap(e,t,i,r,s,n=0,a=0){let o=[e.clone(),e.add(t.multiplyByFloats(i,i,i))];return{points:o,widths:[r,s,n,a]}}static GetPointsFromText(e,t,i,r,s=0,n=!0){let a=[],o=CreateTextShapePaths(e,t,i,r);for(let e of o){for(let t of e.paths){let e=[],i=t.getPoints();for(let t of i)e.push(t.x,t.y,s);a.push(e)}if(n)for(let t of e.holes){let e=[],i=t.getPoints();for(let t of i)e.push(t.x,t.y,s);a.push(e)}}return a}static Color3toRGBAUint8(e){let t=new Uint8Array(4*e.length);for(let i=0,r=0;i<e.length;i++)t[r++]=255*e[i].r,t[r++]=255*e[i].g,t[r++]=255*e[i].b,t[r++]=255;return t}static CreateColorsTexture(e,t,i,r){let s=greasedLineTools_GreasedLineTools.Color3toRGBAUint8(t),n=new rawTexture_RawTexture(s,t.length,1,rq.D.TEXTUREFORMAT_RGBA,r,!1,!0,i);return n.name=e,n}static PrepareEmptyColorsTexture(e){if(!greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture){let t=new Uint8Array(4);greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture=new rawTexture_RawTexture(t,1,1,rq.D.TEXTUREFORMAT_RGBA,e,!1,!1,rawTexture_RawTexture.NEAREST_NEAREST),greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture.name="grlEmptyColorsTexture"}}static DisposeEmptyColorsTexture(){var e;null===(e=greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture)||void 0===e||e.dispose(),greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}};let MaterialGreasedLineDefines=class MaterialGreasedLineDefines extends sn.H{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1,this.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=!1,this.GREASED_LINE_CAMERA_FACING=!0}};let greasedLinePluginMaterial_GreasedLinePluginMaterial=class greasedLinePluginMaterial_GreasedLinePluginMaterial extends MaterialPluginBase{constructor(e,t,i){var r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x;i=i||{color:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR};let T=new MaterialGreasedLineDefines;T.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,T.GREASED_LINE_SIZE_ATTENUATION=null!==(r=i.sizeAttenuation)&&void 0!==r&&r,T.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===iw.COLOR_DISTRIBUTION_TYPE_LINE,T.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(null!=t?t:e.getScene()).useRightHandedSystem,T.GREASED_LINE_CAMERA_FACING=null===(s=i.cameraFacing)||void 0===s||s,super(e,greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME,200,T),this.colorsTexture=null,this._scene=null!=t?t:e.getScene(),this._engine=this._scene.getEngine(),this._cameraFacing=null===(n=i.cameraFacing)||void 0===n||n,this.visibility=null!==(a=i.visibility)&&void 0!==a?a:1,this.useDash=null!==(o=i.useDash)&&void 0!==o&&o,this.dashRatio=null!==(l=i.dashRatio)&&void 0!==l?l:.5,this.dashOffset=null!==(h=i.dashOffset)&&void 0!==h?h:0,this.width=i.width?i.width:i.sizeAttenuation?greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH,this._sizeAttenuation=null!==(u=i.sizeAttenuation)&&void 0!==u&&u,this.colorMode=null!==(c=i.colorMode)&&void 0!==c?c:iL.COLOR_MODE_SET,this._color=null!==(d=i.color)&&void 0!==d?d:null,this.useColors=null!==(p=i.useColors)&&void 0!==p&&p,this._colorsDistributionType=null!==(_=i.colorDistributionType)&&void 0!==_?_:iw.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=null!==(f=i.colorsSampling)&&void 0!==f?f:rawTexture_RawTexture.NEAREST_NEAREST,this._colors=null!==(m=i.colors)&&void 0!==m?m:null,this.dashCount=null!==(g=i.dashCount)&&void 0!==g?g:1,this.resolution=null!==(v=i.resolution)&&void 0!==v?v:new rm.FM(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=null!==(x=this._color)&&void 0!==x?x:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR,greasedLineTools_GreasedLineTools.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add(()=>{greasedLineTools_GreasedLineTools.DisposeEmptyColorsTexture()}),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){let e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?` + uniform vec4 grl_aspect_resolution_lineWidth; + uniform mat4 grl_projection; + `:"",fragment:` + uniform vec4 grl_dashOptions; + uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; + uniform vec3 grl_singleColor; + `}}get isEnabled(){return!0}bindForSubMesh(e){var t;if(this._cameraFacing){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}else throw Error("GreasedLinePluginMaterial requires an active camera.");let i=rm.jp.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}let i=rm.jp.Vector4[0];i.x=greasedLineTools_GreasedLineTools.BooleanToNumber(this.useDash),i.y=this._dashArray,i.z=this.dashOffset,i.w=this.dashRatio,e.updateVector4("grl_dashOptions",i);let r=rm.jp.Vector4[1];r.x=this.colorMode,r.y=this.visibility,r.z=this.colorsTexture?this.colorsTexture.getSize().width:0,r.w=greasedLineTools_GreasedLineTools.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",r),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",null!==(t=this.colorsTexture)&&void 0!==t?t:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===iw.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){let e={CUSTOM_VERTEX_DEFINITIONS:` + attribute float grl_widths; + attribute vec3 grl_offsets; + attribute float grl_colorPointers; + + varying float grlCounters; + varying float grlColorPointer; + + #ifdef GREASED_LINE_CAMERA_FACING + attribute vec4 grl_previousAndSide; + attribute vec4 grl_nextAndCounters; + + vec2 grlFix( vec4 i, float aspect ) { + vec2 res = i.xy / i.w; + res.x *= aspect; + return res; + } + #else + attribute vec3 grl_slopes; + attribute float grl_counters; + #endif + `,CUSTOM_VERTEX_UPDATE_POSITION:` + #ifdef GREASED_LINE_CAMERA_FACING + vec3 grlPositionOffset = grl_offsets; + positionUpdated += grlPositionOffset; + #else + positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths); + #endif + `,CUSTOM_VERTEX_MAIN_END:` + grlColorPointer = grl_colorPointers; + + #ifdef GREASED_LINE_CAMERA_FACING + + float grlAspect = grl_aspect_resolution_lineWidth.x; + float grlBaseWidth = grl_aspect_resolution_lineWidth.w; + + + vec3 grlPrevious = grl_previousAndSide.xyz; + float grlSide = grl_previousAndSide.w; + + vec3 grlNext = grl_nextAndCounters.xyz; + grlCounters = grl_nextAndCounters.w; + + mat4 grlMatrix = viewProjection * finalWorld; + vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 ); + vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 ); + vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 ); + + vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect ); + vec2 grlPrevP = grlFix( grlPrevPos, grlAspect ); + vec2 grlNextP = grlFix( grlNextPos, grlAspect ); + + float grlWidth = grlBaseWidth * grl_widths; + + vec2 grlDir; + if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP ); + else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP ); + else { + vec2 grlDir1 = normalize( grlCurrentP - grlPrevP ); + vec2 grlDir2 = normalize( grlNextP - grlCurrentP ); + grlDir = normalize( grlDir1 + grlDir2 ); + } + vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. ); + #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM + grlNormal.xy *= -.5 * grlWidth; + #else + grlNormal.xy *= .5 * grlWidth; + #endif + + grlNormal *= grl_projection; + + #ifdef GREASED_LINE_SIZE_ATTENUATION + grlNormal.xy *= grlFinalPosition.w; + grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy; + #endif + + grlFinalPosition.xy += grlNormal.xy * grlSide; + gl_Position = grlFinalPosition; + + vPositionW = vec3(grlFinalPosition); + #else + grlCounters = grl_counters; + #endif + `};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:` + varying float grlCounters; + varying float grlColorPointer; + uniform sampler2D grl_colors; + `,CUSTOM_FRAGMENT_MAIN_END:` + float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; + float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; + float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; + float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; + + float grlUseDash = grl_dashOptions.x; + float grlDashArray = grl_dashOptions.y; + float grlDashOffset = grl_dashOptions.z; + float grlDashRatio = grl_dashOptions.w; + + gl_FragColor.a *= step(grlCounters, grlVisibility); + if( gl_FragColor.a == 0. ) discard; + + if(grlUseDash == 1.){ + gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); + if (gl_FragColor.a == 0.) discard; + } + + #ifdef GREASED_LINE_HAS_COLOR + if (grlColorMode == ${iL.COLOR_MODE_SET}.) { + gl_FragColor.rgb = grl_singleColor; + } else if (grlColorMode == ${iL.COLOR_MODE_ADD}.) { + gl_FragColor.rgb += grl_singleColor; + } else if (grlColorMode == ${iL.COLOR_MODE_MULTIPLY}.) { + gl_FragColor.rgb *= grl_singleColor; + } + #else + if (grlUseColors == 1.) { + #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE + vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); + #else + vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.); + #endif + if (grlColorMode == ${iL.COLOR_MODE_SET}.) { + gl_FragColor = grlColor; + } else if (grlColorMode == ${iL.COLOR_MODE_ADD}.) { + gl_FragColor += grlColor; + } else if (grlColorMode == ${iL.COLOR_MODE_MULTIPLY}.) { + gl_FragColor *= grlColor; + } + } + #endif + + `}:null}dispose(){var e;null===(e=this.colorsTexture)||void 0===e||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,n,a;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(n=this.colorsTexture)||void 0===n||n.dispose();return}if(!t||i){if(this.colorsTexture&&o===e.length&&!i){let t=greasedLineTools_GreasedLineTools.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else null===(a=this.colorsTexture)||void 0===a||a.dispose(),this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,t||this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r;super.parse(e,t,i);let s=e.greasedLineMaterialOptions;null===(r=this.colorsTexture)||void 0===r||r.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):greasedLineTools_GreasedLineTools.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var t;null===(t=e.colorsTexture)||void 0===t||t.dispose(),this._colors&&(e.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${e._material.name}-colors-texture`,this._colors,e.colorsSampling,this._scene)),e.setColor(this.color,!0),e.colorsDistributionType=this.colorsDistributionType,e.colorsSampling=this.colorsSampling,e.colorMode=this.colorMode,e.useColors=this.useColors,e.visibility=this.visibility,e.useDash=this.useDash,e.dashCount=this.dashCount,e.dashRatio=this.dashRatio,e.dashOffset=this.dashOffset,e.width=this.width,e.sizeAttenuation=this.sizeAttenuation,e.resolution=this.resolution,e.markAllDefinesAsDirty()}};greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",(0,rv.H)(`BABYLON.${greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}`,greasedLinePluginMaterial_GreasedLinePluginMaterial);let lB=`precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} +if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { +textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} +if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}} +`;s_.v.ShadersStore.greasedLinePixelShader=lB;let lL=`precision highp float; +#include<instancesDeclaration> +attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer; +#ifdef GREASED_LINE_CAMERA_FACING +attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} +#else +attribute vec3 grl_slopes;attribute float grl_counters; +#endif +void main() { +#include<instancesVertex> +grlColorPointer=grl_colorPointers; +#ifdef GREASED_LINE_CAMERA_FACING +float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=viewProjection*finalWorld ;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );} +vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); +#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM +grlNormal.xy*=-.5*grlWidth; +#else +grlNormal.xy*=.5*grlWidth; +#endif +grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} +grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition; +#else +grlCounters=grl_counters;vec4 grlFinalPosition=worldViewProjection*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition; +#endif +} +`;s_.v.ShadersStore.greasedLineVertexShader=lL;let greasedLineSimpleMaterial_GreasedLineSimpleMaterial=class greasedLineSimpleMaterial_GreasedLineSimpleMaterial extends shaderMaterial_ShaderMaterial{constructor(e,t,i){var r,s,n,a,o,l,h,u,c,d,p,_,f,m;let g=[`COLOR_DISTRIBUTION_TYPE_LINE ${iw.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${iw.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${iL.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${iL.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${iL.COLOR_MODE_MULTIPLY}.`],v=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&g.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(g.push("GREASED_LINE_CAMERA_FACING"),v.push("grl_previousAndSide","grl_nextAndCounters")):(v.push("grl_slopes"),v.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:v,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:g}),this._color=rg.Wo.White(),this._colorsDistributionType=iw.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR};let x=t.getEngine();this.visibility=null!==(r=i.visibility)&&void 0!==r?r:1,this.useDash=null!==(s=i.useDash)&&void 0!==s&&s,this.dashRatio=null!==(n=i.dashRatio)&&void 0!==n?n:.5,this.dashOffset=null!==(a=i.dashOffset)&&void 0!==a?a:0,this.dashCount=null!==(o=i.dashCount)&&void 0!==o?o:1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH,this.sizeAttenuation=null!==(l=i.sizeAttenuation)&&void 0!==l&&l,this.color=null!==(h=i.color)&&void 0!==h?h:rg.Wo.White(),this.useColors=null!==(u=i.useColors)&&void 0!==u&&u,this.colorsDistributionType=null!==(c=i.colorDistributionType)&&void 0!==c?c:iw.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=null!==(d=i.colorsSampling)&&void 0!==d?d:rawTexture_RawTexture.NEAREST_NEAREST,this.colorMode=null!==(p=i.colorMode)&&void 0!==p?p:iL.COLOR_MODE_SET,this._colors=null!==(_=i.colors)&&void 0!==_?_:null,this._cameraFacing=null===(f=i.cameraFacing)||void 0===f||f,this.resolution=null!==(m=i.resolution)&&void 0!==m?m:new rm.FM(x.getRenderWidth(),x.getRenderHeight()),i.colorsTexture&&(this.colorsTexture=i.colorsTexture),this._colors&&this.setColors(this._colors),x.onDisposeObservable.add(()=>{greasedLineTools_GreasedLineTools.DisposeEmptyColorsTexture()})}dispose(){var e;null===(e=this._colorsTexture)||void 0===e||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new rm.FM(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,n,a;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(n=this._colorsTexture)||void 0===n||n.dispose();return}if(!t||i){if(this._colorsTexture&&o===e.length&&!i){let t=greasedLineTools_GreasedLineTools.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else null===(a=this._colorsTexture)||void 0===a||a.dispose(),this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}}get colorsTexture(){var e;return null!==(e=this._colorsTexture)&&void 0!==e?e:null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=null!=e?e:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r,s;let n=e.greasedLineMaterialOptions;null===(r=this._colorsTexture)||void 0===r||r.dispose(),n.color&&(this.color=n.color),n.colorDistributionType&&(this.colorsDistributionType=n.colorDistributionType),n.colorsSampling&&(this.colorsSampling=n.colorsSampling),n.colorMode&&(this.colorMode=n.colorMode),n.useColors&&(this.useColors=n.useColors),n.visibility&&(this.visibility=n.visibility),n.useDash&&(this.useDash=n.useDash),n.dashCount&&(this.dashCount=n.dashCount),n.dashRatio&&(this.dashRatio=n.dashRatio),n.dashOffset&&(this.dashOffset=n.dashOffset),n.width&&(this.width=n.width),n.sizeAttenuation&&(this.sizeAttenuation=n.sizeAttenuation),n.resolution&&(this.resolution=n.resolution),n.colors?this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`,n.colors,this.colorsSampling,this.getScene()):greasedLineTools_GreasedLineTools.PrepareEmptyColorsTexture(t),this._cameraFacing=null===(s=n.cameraFacing)||void 0===s||s,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}};let lw=`#if defined(DBG_ENABLED) +attribute float dbg_initialPass; +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; +#endif`,lU=`#if defined(DBG_ENABLED) +float dbg_vertexIndex = mod(float(gl_VertexID), 3.); +if (dbg_vertexIndex == 0.0) { + dbg_vBarycentric = vec3(1.,0.,0.); +} +else if (dbg_vertexIndex == 1.0) { + dbg_vBarycentric = vec3(0.,1.,0.); +} +else { + dbg_vBarycentric = vec3(0.,0.,1.); +} + +dbg_vVertexWorldPos = vPositionW; +dbg_vPass = dbg_initialPass; +#endif`,lV=`#if defined(DBG_ENABLED) +uniform vec3 dbg_shadedDiffuseColor; +uniform vec4 dbg_shadedSpecularColorPower; +uniform vec3 dbg_thicknessRadiusScale; + +#if DBG_MODE == 2 || DBG_MODE == 3 + uniform vec3 dbg_vertexColor; +#endif + +#if DBG_MODE == 1 + uniform vec3 dbg_wireframeTrianglesColor; +#elif DBG_MODE == 3 + uniform vec3 dbg_wireframeVerticesColor; +#elif DBG_MODE == 4 || DBG_MODE == 5 + uniform vec3 dbg_uvPrimaryColor; + uniform vec3 dbg_uvSecondaryColor; +#elif DBG_MODE == 7 + uniform vec3 dbg_materialColor; +#endif +#endif`,lk=`#if defined(DBG_ENABLED) +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; + +#if !defined(DBG_MULTIPLY) + vec3 dbg_applyShading(vec3 color) { + vec3 N = vNormalW.xyz; + vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); + vec3 H = normalize(L + L); + float LdotN = clamp(dot(L,N), 0., 1.); + float HdotN = clamp(dot(H,N), 0., 1.); + float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); + color *= (LdotN / PI); + color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); + return color; + } +#endif + +#if DBG_MODE == 1 || DBG_MODE == 3 + float dbg_edgeFactor() { + vec3 d = fwidth(dbg_vBarycentric); + vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); + return min(min(a3.x, a3.y), a3.z); + } +#endif + +#if DBG_MODE == 2 || DBG_MODE == 3 + float dbg_cornerFactor() { + vec3 worldPos = vPositionW; + float dist = length(worldPos - dbg_vVertexWorldPos); + float camDist = length(worldPos - vEyePosition.xyz); + float d = sqrt(camDist) * .001; + return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); + } +#endif + +#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) + float dbg_checkerboardFactor(vec2 uv) { + vec2 f = fract(uv * dbg_thicknessRadiusScale.z); + f -= .5; + return (f.x * f.y) > 0. ? 1. : 0.; + } +#endif +#endif`,lG=`#if defined(DBG_ENABLED) +vec3 dbg_color = vec3(1.); +#if DBG_MODE == 1 + dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); +#elif DBG_MODE == 2 || DBG_MODE == 3 + float dbg_cornerFactor = dbg_cornerFactor(); + if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; + dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); + #if DBG_MODE == 3 + dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); + #endif +#elif DBG_MODE == 4 && defined(UV1) + dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); +#elif DBG_MODE == 5 && defined(UV2) + dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); +#elif DBG_MODE == 6 && defined(VERTEXCOLOR) + dbg_color = vColor.rgb; +#elif DBG_MODE == 7 + dbg_color = dbg_materialColor; +#endif + +#if defined(DBG_MULTIPLY) + gl_FragColor *= vec4(dbg_color, 1.); +#else + #if DBG_MODE != 6 + gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); + #else + gl_FragColor = vec4(dbg_color, 1.); + #endif +#endif +#endif`,lz=[new rg.Wo(.98,.26,.38),new rg.Wo(.47,.75,.3),new rg.Wo(0,.26,.77),new rg.Wo(.97,.6,.76),new rg.Wo(.19,.63,.78),new rg.Wo(.98,.8,.6),new rg.Wo(.65,.43,.15),new rg.Wo(.15,.47,.22),new rg.Wo(.67,.71,.86),new rg.Wo(.09,.46,.56),new rg.Wo(.8,.98,.02),new rg.Wo(.39,.29,.13),new rg.Wo(.53,.63,.06),new rg.Wo(.95,.96,.41),new rg.Wo(1,.72,.94),new rg.Wo(.63,.08,.31),new rg.Wo(.66,.96,.95),new rg.Wo(.22,.14,.19),new rg.Wo(.14,.65,.59),new rg.Wo(.93,1,.68),new rg.Wo(.93,.14,.44),new rg.Wo(.47,.86,.67),new rg.Wo(.85,.07,.78),new rg.Wo(.53,.64,.98),new rg.Wo(.43,.37,.56),new rg.Wo(.71,.65,.25),new rg.Wo(.66,.19,.01),new rg.Wo(.94,.53,.12),new rg.Wo(.41,.44,.44),new rg.Wo(.24,.71,.96),new rg.Wo(.57,.28,.56),new rg.Wo(.44,.98,.42)];(eU=iU||(iU={}))[eU.NONE=0]="NONE",eU[eU.TRIANGLES=1]="TRIANGLES",eU[eU.VERTICES=2]="VERTICES",eU[eU.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",eU[eU.UV0=4]="UV0",eU[eU.UV1=5]="UV1",eU[eU.VERTEXCOLORS=6]="VERTEXCOLORS",eU[eU.MATERIALIDS=7]="MATERIALIDS";let MeshDebugDefines=class MeshDebugDefines extends sn.H{constructor(){super(...arguments),this.DBG_MODE=iU.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}};let MeshDebugPluginMaterial=class MeshDebugPluginMaterial extends MaterialPluginBase{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){var i,r,s,n,a,o,l,h,u,c,d,p,_;let f=new MeshDebugDefines;f.DBG_MODE=null!==(i=t.mode)&&void 0!==i?i:f.DBG_MODE,f.DBG_MULTIPLY=null!==(r=t.multiply)&&void 0!==r?r:f.DBG_MULTIPLY,super(e,"MeshDebug",200,f,!0,!0),this._mode=f.DBG_MODE,this._multiply=f.DBG_MULTIPLY,this.shadedDiffuseColor=null!==(s=t.shadedDiffuseColor)&&void 0!==s?s:new rg.Wo(1,1,1),this.shadedSpecularColor=null!==(n=t.shadedSpecularColor)&&void 0!==n?n:new rg.Wo(.8,.8,.8),this.shadedSpecularPower=null!==(a=t.shadedSpecularPower)&&void 0!==a?a:10,this.wireframeThickness=null!==(o=t.wireframeThickness)&&void 0!==o?o:.7,this.wireframeTrianglesColor=null!==(l=t.wireframeTrianglesColor)&&void 0!==l?l:new rg.Wo(0,0,0),this.wireframeVerticesColor=null!==(h=t.wireframeVerticesColor)&&void 0!==h?h:new rg.Wo(.8,.8,.8),this.vertexColor=null!==(u=t.vertexColor)&&void 0!==u?u:new rg.Wo(0,0,0),this.vertexRadius=null!==(c=t.vertexRadius)&&void 0!==c?c:1.2,this.uvScale=null!==(d=t.uvScale)&&void 0!==d?d:20,this.uvPrimaryColor=null!==(p=t.uvPrimaryColor)&&void 0!==p?p:new rg.Wo(1,1,1),this.uvSecondaryColor=null!==(_=t.uvSecondaryColor)&&void 0!==_?_:new rg.Wo(.5,.5,.5),this._materialColor=MeshDebugPluginMaterial.MaterialColors[MeshDebugPluginMaterial._PluginCount++%MeshDebugPluginMaterial.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().webGLVersion){rT.Y.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=iU.VERTICES&&this._mode!=iU.TRIANGLES&&this._mode!=iU.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||rT.Y.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:lV}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:lw,CUSTOM_VERTEX_MAIN_END:lU}:{CUSTOM_FRAGMENT_DEFINITIONS:lk,CUSTOM_FRAGMENT_MAIN_END:lG}}static Reset(){this._PluginCount=0,this.MaterialColors=lz}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let rollback=()=>{};if(0==e.getTotalIndices())return rollback;if(t){let t=e.getVerticesDataKinds(),i=e.getIndices(),r={};for(let i of t)r[i]=e.getVerticesData(i);rollback=function(){for(let s of(e.setIndices(i),t)){let t=e.getVertexBuffer(s).getStrideSize();e.setVerticesData(s,r[s],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let i=Array.from(e.getIndices()),r=[];for(let e=0;e<i.length;e+=3)r.push(i[e+1],i[e+2],i[e+0]);e.setIndices(i.concat(r)),e.convertToUnIndexedMesh(),e.isUnIndexed=!1,i=Array.from(e.getIndices());let s=[];for(let e=i.length/2;e<i.length;e+=3)s.push(i[e+1],i[e+2],i[e+0]);e.setIndices(i.concat(s));let n=e.getTotalVertices(),a=n/2,o=Array(n).fill(1,0,a).fill(0,a,n);return e.setVerticesData("dbg_initialPass",o,!1,1),rollback}};MeshDebugPluginMaterial._PluginCount=0,MeshDebugPluginMaterial.MaterialColors=lz,(0,rH.gn)([(0,rb.n9)()],MeshDebugPluginMaterial.prototype,"_materialColor",void 0),(0,rH.gn)([(0,rb.qC)()],MeshDebugPluginMaterial.prototype,"_isEnabled",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllDefinesAsDirty")],MeshDebugPluginMaterial.prototype,"mode",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllDefinesAsDirty")],MeshDebugPluginMaterial.prototype,"multiply",void 0),(0,rH.gn)([(0,rb.n9)()],MeshDebugPluginMaterial.prototype,"shadedDiffuseColor",void 0),(0,rH.gn)([(0,rb.n9)()],MeshDebugPluginMaterial.prototype,"shadedSpecularColor",void 0),(0,rH.gn)([(0,rb.qC)()],MeshDebugPluginMaterial.prototype,"shadedSpecularPower",void 0),(0,rH.gn)([(0,rb.qC)()],MeshDebugPluginMaterial.prototype,"wireframeThickness",void 0),(0,rH.gn)([(0,rb.n9)()],MeshDebugPluginMaterial.prototype,"wireframeTrianglesColor",void 0),(0,rH.gn)([(0,rb.n9)()],MeshDebugPluginMaterial.prototype,"wireframeVerticesColor",void 0),(0,rH.gn)([(0,rb.n9)()],MeshDebugPluginMaterial.prototype,"vertexColor",void 0),(0,rH.gn)([(0,rb.qC)()],MeshDebugPluginMaterial.prototype,"vertexRadius",void 0),(0,rH.gn)([(0,rb.qC)()],MeshDebugPluginMaterial.prototype,"uvScale",void 0),(0,rH.gn)([(0,rb.n9)()],MeshDebugPluginMaterial.prototype,"uvPrimaryColor",void 0),(0,rH.gn)([(0,rb.n9)()],MeshDebugPluginMaterial.prototype,"uvSecondaryColor",void 0),(0,rv.H)("BABYLON.MeshDebugPluginMaterial",MeshDebugPluginMaterial),Object.defineProperty(standardMaterial_StandardMaterial.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new DecalMapConfiguration(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(pbrBaseMaterial_PBRBaseMaterial.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new DecalMapConfiguration(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(rG.x.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});var lW=i(7383);function createDecoderAsync(e){return new Promise(t=>{DracoDecoderModule({wasmBinary:e}).then(e=>{t({module:e})})})}function decodeMesh(e,t,i,r,s){let n=null,a=null,o=null;try{let l;n=new e.Decoder,(a=new e.DecoderBuffer).Init(t,t.byteLength);let h=n.GetEncodedGeometryType(a);switch(h){case e.TRIANGULAR_MESH:{let t=new e.Mesh;if(!(l=n.DecodeBufferToMesh(a,t)).ok()||0===t.ptr)throw Error(l.error_msg());let i=t.num_faces(),s=3*i,h=4*s,u=e._malloc(h);try{n.GetTrianglesUInt32Array(t,h,u);let i=new Uint32Array(s);i.set(new Uint32Array(e.HEAPF32.buffer,u,s)),r(i)}finally{e._free(u)}o=t;break}case e.POINT_CLOUD:{let t=new e.PointCloud;if(!(l=n.DecodeBufferToPointCloud(a,t)).ok()||!t.ptr)throw Error(l.error_msg());o=t;break}default:throw Error(`Invalid geometry type ${h}`)}let u=o.num_points(),processAttribute=(t,i,r,n)=>{let a=n.data_type(),o=n.num_components(),l=n.normalized(),h=n.byte_stride(),c=n.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}},p=d[a];if(!p)throw Error(`Invalid data type ${a}`);let _=u*o,f=_*p.typedArrayConstructor.BYTES_PER_ELEMENT,m=e._malloc(f);try{t.GetAttributeDataArrayForAllPoints(i,n,a,f,m);let e=new p.typedArrayConstructor(p.heap.buffer,m,_);s(r,e.slice(),o,c,h,l)}finally{e._free(m)}};if(i)for(let e in i){let t=i[e],r=n.GetAttributeByUniqueId(o,t);processAttribute(n,o,e,r)}else{let t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(let e in t){let i=n.GetAttributeId(o,t[e]);if(-1!==i){let t=n.GetAttribute(o,i);processAttribute(n,o,e,t)}}}return u}finally{o&&e.destroy(o),a&&e.destroy(a),n&&e.destroy(n)}}function worker(){let e;onmessage=t=>{let i=t.data;switch(i.id){case"init":{let t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw Error("Draco decoder module is not available");e.then(e=>{let t=decodeMesh(e,i.dataView,i.attributes,e=>{postMessage({id:"indices",data:e},[e.buffer])},(e,t,i,r,s,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:r,byteStride:s,normalized:n},[t.buffer])});postMessage({id:"decodeMeshDone",totalVertices:t})})}}}let DracoCompression=class DracoCompression{static get DecoderAvailable(){let e=DracoCompression.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 DracoCompression._Default||(DracoCompression._Default=new DracoCompression),DracoCompression._Default}constructor(e=DracoCompression.DefaultNumWorkers){let t=DracoCompression.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:rW.w1.GetBabylonScriptURL(t.wasmUrl,!0),wasmBinaryPromise:rW.w1.LoadFileAsync(rW.w1.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:rW.w1.GetBabylonScriptURL(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then(t=>{let r=`${decodeMesh}(${worker})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));return new AutoReleaseWorkerPool(e,()=>new Promise((e,r)=>{let n=new Worker(s),onError=e=>{n.removeEventListener("error",onError),n.removeEventListener("message",onMessage),r(e)},onMessage=t=>{"initDone"===t.data.id&&(n.removeEventListener("error",onError),n.removeEventListener("message",onMessage),e(n))};n.addEventListener("error",onError),n.addEventListener("message",onMessage),n.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))}):this._decoderModulePromise=i.wasmBinaryPromise.then(e=>{if(!i.url)throw Error("Draco decoder module is not available");return rW.w1.LoadBabylonScriptAsync(i.url).then(()=>createDecoderAsync(e))})}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){let r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),applyGltfNormalizedOverride=(e,t)=>i&&void 0!==i[e]?(t!==i[e]&&rT.Y.Warn(`Normalized flag from Draco data (${t}) does not match normalized flag from glTF accessor (${i[e]}). Using flag from glTF accessor.`),i[e]):t;if(this._workerPoolPromise)return this._workerPoolPromise.then(e=>new Promise((i,s)=>{e.push((e,n)=>{let a=null,o=[],onError=t=>{e.removeEventListener("error",onError),e.removeEventListener("message",onMessage),s(t),n()},onMessage=t=>{let r=t.data;switch(r.id){case"decodeMeshDone":e.removeEventListener("error",onError),e.removeEventListener("message",onMessage),i({indices:a,attributes:o,totalVertices:r.totalVertices}),n();break;case"indices":a=r.data;break;case"attribute":o.push({kind:r.kind,data:r.data,size:r.size,byteOffset:r.byteOffset,byteStride:r.byteStride,normalized:applyGltfNormalizedOverride(r.kind,r.normalized)})}};e.addEventListener("error",onError),e.addEventListener("message",onMessage);let l=r.slice();e.postMessage({id:"decodeMesh",dataView:l,attributes:t},[l.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(e=>{let i=null,s=[],n=decodeMesh(e.module,r,t,e=>{i=e},(e,t,i,r,n,a)=>{s.push({kind:e,data:t,size:i,byteOffset:r,byteStride:n,normalized:a})});return{indices:i,attributes:s,totalVertices:n}});throw Error("Draco decoder module is not available")}decodeMeshToGeometryAsync(e,t,i,r){return this._decodeMeshAsync(i,r).then(i=>{let r=new lS.Z(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new rz.o(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}_decodeMeshToGeometryForGltfAsync(e,t,i,r,s){return this._decodeMeshAsync(i,r,s).then(i=>{let r=new lS.Z(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new rz.o(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}decodeMeshAsync(e,t){return this._decodeMeshAsync(e,t).then(e=>{let t=new se.x;for(let i of(e.indices&&(t.indices=e.indices),e.attributes)){let r=rz.o.GetFloatData(i.data,i.size,rz.o.GetDataType(i.data),i.byteOffset,i.byteStride,i.normalized,e.totalVertices);t.set(r,i.kind)}return t})}};DracoCompression.Configuration={decoder:{wasmUrl:`${rW.w1._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${rW.w1._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${rW.w1._DefaultCdnUrl}/draco_decoder_gltf.js`}},DracoCompression.DefaultNumWorkers=DracoCompression.GetDefaultNumWorkers(),DracoCompression._Default=null;let MeshoptCompression=class MeshoptCompression{static get Default(){return MeshoptCompression._Default||(MeshoptCompression._Default=new MeshoptCompression),MeshoptCompression._Default}constructor(){let e=MeshoptCompression.Configuration.decoder;this._decoderModulePromise=rW.w1.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,s){return this._decoderModulePromise.then(()=>{let n=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(n,t,i,e,r,s),n})}};MeshoptCompression.Configuration={decoder:{url:`${rW.w1._DefaultCdnUrl}/meshopt_decoder.js`}},MeshoptCompression._Default=null;let lH=0;let Vertex=class Vertex{constructor(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}clone(){var e,t;return new Vertex(this.pos.clone(),this.normal.clone(),null===(e=this.uv)||void 0===e?void 0:e.clone(),null===(t=this.vertColor)||void 0===t?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new Vertex(rm.P.Lerp(this.pos,e.pos,t),rm.P.Lerp(this.normal,e.normal,t),this.uv&&e.uv?rm.FM.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?rg.HE.Lerp(this.vertColor,e.vertColor,t):void 0)}};let csg_Plane=class csg_Plane{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){let r=i.subtract(e),s=t.subtract(e);if(0===r.lengthSquared()||0===s.lengthSquared())return null;let n=rm.P.Normalize(rm.P.Cross(r,s));return new csg_Plane(n,rm.P.Dot(n,e))}clone(){return new csg_Plane(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,s){let n,a;let o=0,l=[];for(n=0;n<e.vertices.length;n++){a=rm.P.Dot(this.normal,e.vertices[n].pos)-this.w;let t=a<-csg_Plane.EPSILON?2:a>csg_Plane.EPSILON?1:0;o|=t,l.push(t)}switch(o){case 0:(rm.P.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:s.push(e);break;case 3:{let t;let i=[],o=[];for(n=0;n<e.vertices.length;n++){let t=(n+1)%e.vertices.length,r=l[n],s=l[t],h=e.vertices[n],u=e.vertices[t];if(2!==r&&i.push(h),1!==r&&o.push(2!==r?h.clone():h),(r|s)==3){a=(this.w-rm.P.Dot(this.normal,h.pos))/rm.P.Dot(this.normal,u.pos.subtract(h.pos));let e=h.interpolate(u,a);i.push(e),o.push(e.clone())}}i.length>=3&&(t=new csg_Polygon(i,e.shared)).plane&&r.push(t),o.length>=3&&(t=new csg_Polygon(o,e.shared)).plane&&s.push(t)}}}};csg_Plane.EPSILON=1e-5;let csg_Polygon=class csg_Polygon{constructor(e,t){this.vertices=e,this.shared=t,this.plane=csg_Plane.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){let e=this.vertices.map(e=>e.clone());return new csg_Polygon(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}};let csg_Node=class csg_Node{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=[],e&&this.build(e)}clone(){let e=new csg_Node;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map(e=>e.clone()),e}invert(){for(let e=0;e<this._polygons.length;e++)this._polygons[e].flip();this._plane&&this._plane.flip(),this._front&&this._front.invert(),this._back&&this._back.invert();let e=this._front;this._front=this._back,this._back=e}clipPolygons(e){if(!this._plane)return e.slice();let t=[],i=[];for(let r=0;r<e.length;r++)this._plane.splitPolygon(e[r],t,i,t,i);return this._front&&(t=this._front.clipPolygons(t)),i=this._back?this._back.clipPolygons(i):[],t.concat(i)}clipTo(e){this._polygons=e.clipPolygons(this._polygons),this._front&&this._front.clipTo(e),this._back&&this._back.clipTo(e)}allPolygons(){let e=this._polygons.slice();return this._front&&(e=e.concat(this._front.allPolygons())),this._back&&(e=e.concat(this._back.allPolygons())),e}build(e){if(!e.length)return;this._plane||(this._plane=e[0].plane.clone());let t=[],i=[];for(let r=0;r<e.length;r++)this._plane.splitPolygon(e[r],this._polygons,this._polygons,t,i);t.length&&(this._front||(this._front=new csg_Node),this._front.build(t)),i.length&&(this._back||(this._back=new csg_Node),this._back.build(i))}};let CSG=class CSG{constructor(){this._polygons=[]}static FromVertexData(e){let t,i,r;let s=[],n=e.indices,a=e.positions,o=e.normals,l=e.uvs,h=e.colors;if(!n||!a)throw"BABYLON.CSG: VertexData must at least contain positions and indices";for(let e=0;e<n.length;e+=3){r=[];for(let i=0;i<3;i++){let s=e+i,u=n[s],c=o?rm.P.FromArray(o,3*u):rm.P.Zero(),d=l?rm.FM.FromArray(l,2*u):void 0,p=h?rg.HE.FromArray(h,4*u):void 0,_=rm.P.FromArray(a,3*u);t=new Vertex(_,c,d,p),r.push(t)}(i=new csg_Polygon(r,{subMeshId:0,meshId:lH,materialIndex:0})).plane&&s.push(i)}let u=CSG._FromPolygons(s);return u.matrix=rm.y3.Identity(),u.position=rm.P.Zero(),u.rotation=rm.P.Zero(),u.scaling=rm.P.One(),u.rotationQuaternion=rm._f.Identity(),lH++,u}static FromMesh(e,t=!1){let i,r,s,n,a;let o=[],l,h,u,c=null,d,p=!1;if(e instanceof rV.Kj)e.computeWorldMatrix(!0),l=e.getWorldMatrix(),h=e.position.clone(),u=e.rotation.clone(),e.rotationQuaternion&&(c=e.rotationQuaternion.clone()),d=e.scaling.clone(),e.material&&t&&(p=0===e.material.sideOrientation);else throw"BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh";let _=e.getIndices(),f=e.getVerticesData(rz.o.PositionKind),m=e.getVerticesData(rz.o.NormalKind),g=e.getVerticesData(rz.o.UVKind),v=e.getVerticesData(rz.o.ColorKind),x=e.subMeshes;for(let e=0,t=x.length;e<t;e++)for(let t=x[e].indexStart,h=x[e].indexCount+x[e].indexStart;t<h;t+=3){a=[];for(let e=0;e<3;e++){let n=0===e?t+e:p?t+3-e:t+e,o=new rm.P(m[3*_[n]],m[3*_[n]+1],m[3*_[n]+2]);g&&(r=new rm.FM(g[2*_[n]],g[2*_[n]+1])),v&&(s=new rg.HE(v[4*_[n]],v[4*_[n]+1],v[4*_[n]+2],v[4*_[n]+3]));let h=new rm.P(f[3*_[n]],f[3*_[n]+1],f[3*_[n]+2]);i=new Vertex(rm.P.TransformCoordinates(h,l),rm.P.TransformNormal(o,l),r,s),a.push(i)}(n=new csg_Polygon(a,{subMeshId:e,meshId:lH,materialIndex:x[e].materialIndex})).plane&&o.push(n)}let T=CSG._FromPolygons(o);return T.matrix=t?rm.y3.Identity():l,T.position=t?rm.P.Zero():h,T.rotation=t?rm.P.Zero():u,T.scaling=t?rm.P.One():d,T.rotationQuaternion=t&&c?rm._f.Identity():c,lH++,T}static _FromPolygons(e){let t=new CSG;return t._polygons=e,t}clone(){let e=new CSG;return e._polygons=this._polygons.map(e=>e.clone()),e.copyTransformAttributes(this),e}union(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){let e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map(e=>{e.flip()})}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){let i;let r=this.matrix.clone();r.invert();let s=this._polygons,n=[],a=[],o=[],l=null,h=null,u=rm.P.Zero(),c=rm.P.Zero(),d=rm.FM.Zero(),p=new rg.HE(0,0,0,0),_=[0,0,0],f={};for(let m=0,g=s.length;m<g;m++){let g=s[m];e&&e(g);for(let e=2,s=g.vertices.length;e<s;e++){_[0]=0,_[1]=e-1,_[2]=e;for(let e=0;e<3;e++){u.copyFrom(g.vertices[_[e]].pos),c.copyFrom(g.vertices[_[e]].normal),g.vertices[_[e]].uv&&(l||(l=[]),d.copyFrom(g.vertices[_[e]].uv)),g.vertices[_[e]].vertColor&&(h||(h=[]),p.copyFrom(g.vertices[_[e]].vertColor));let s=rm.P.TransformCoordinates(u,r),m=rm.P.TransformNormal(c,r);i=f[s.x+","+s.y+","+s.z];let v=!1;l&&!(l[2*i]===d.x||l[2*i+1]===d.y)&&(v=!0);let x=!1;h&&!(h[4*i]===p.r||h[4*i+1]===p.g||h[4*i+2]===p.b||h[4*i+3]===p.a)&&(x=!0),(!(void 0!==i&&o[3*i]===m.x&&o[3*i+1]===m.y&&o[3*i+2]===m.z)||v||x)&&(n.push(s.x,s.y,s.z),l&&l.push(d.x,d.y),o.push(c.x,c.y,c.z),h&&h.push(p.r,p.g,p.b,p.a),i=f[s.x+","+s.y+","+s.z]=n.length/3-1),a.push(i),t&&t()}}}let m=new se.x;return m.positions=n,m.normals=o,l&&(m.uvs=l),h&&(m.colors=h),m.indices=a,m}buildMeshGeometry(e,t,i){let r;let s=new rV.Kj(e,t),n=this._polygons,a=0,o={};i&&n.sort((e,t)=>e.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId);let l=this.toVertexData(e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:Infinity,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),r=o[e.shared.meshId][e.shared.subMeshId]},()=>{r.indexStart=Math.min(a,r.indexStart),r.indexEnd=Math.max(a,r.indexEnd),a++});if(l.applyToMesh(s),i){let e=0,t;for(let i in s.subMeshes=[],o){for(let n in t=-1,o[i])r=o[i][n],oJ.P.CreateFromIndices(r.materialIndex+e,r.indexStart,r.indexEnd-r.indexStart+1,s),t=Math.max(r.materialIndex,t);e+=++t}}return s}toMesh(e,t=null,i,r){let s=this.buildMeshGeometry(e,i,r);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}};let lX=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<instancesDeclaration> +void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vNormalW=normalize(normWorldSM*normalUpdated); +#endif +vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);} +`;s_.v.ShadersStore.meshUVSpaceRendererVertexShader=lX;let lY=`precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} +gl_FragColor=texture2D(textureSampler,vDecalTC);} +`;s_.v.ShadersStore.meshUVSpaceRendererPixelShader=lY,rV.Kj._TrailMeshParser=(e,t)=>TrailMesh.Parse(e,t);let TrailMesh=class TrailMesh extends rV.Kj{constructor(e,t,i,r=1,s=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=n,this._generator=t,this.diameter=r,this._length=s,this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=rm.P.Zero(),this._sectionNormalVectors[e]=rm.P.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){let e=new se.x,t=[],i=[],r=[],s=rm.P.Zero();s=this._generator instanceof rG.x&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.position;let n=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<this._sectionPolygonPointsCount;e++)t.push(s.x+Math.cos(e*n)*this.diameter,s.y+Math.sin(e*n)*this.diameter,s.z);for(let e=1;e<=this._length;e++){for(let e=0;e<this._sectionPolygonPointsCount;e++)t.push(s.x+Math.cos(e*n)*this.diameter,s.y+Math.sin(e*n)*this.diameter,s.z);let e=t.length/3-2*this._sectionPolygonPointsCount;for(let t=0;t<this._sectionPolygonPointsCount-1;t++)r.push(e+t,e+t+this._sectionPolygonPointsCount,e+t+this._sectionPolygonPointsCount+1),r.push(e+t,e+t+this._sectionPolygonPointsCount+1,e+t+1);r.push(e+this._sectionPolygonPointsCount-1,e+this._sectionPolygonPointsCount-1+this._sectionPolygonPointsCount,e+this._sectionPolygonPointsCount),r.push(e+this._sectionPolygonPointsCount-1,e+this._sectionPolygonPointsCount,e)}se.x.ComputeNormals(t,r,i),e.positions=t,e.normals=i,e.indices=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add(()=>{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){let e=this.getVerticesData(rz.o.PositionKind),t=this.getVerticesData(rz.o.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let i=3*this._sectionPolygonPointsCount;i<e.length;i++)e[i-3*this._sectionPolygonPointsCount]=e[i]-t[i]/this._length*this.diameter;for(let e=3*this._sectionPolygonPointsCount;e<t.length;e++)t[e-3*this._sectionPolygonPointsCount]=t[e];let r=e.length-3*this._sectionPolygonPointsCount,s=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<this._sectionPolygonPointsCount;e++)this._sectionVectors[e].copyFromFloats(Math.cos(e*s)*this.diameter,Math.sin(e*s)*this.diameter,0),this._sectionNormalVectors[e].copyFromFloats(Math.cos(e*s),Math.sin(e*s),0),rm.P.TransformCoordinatesToRef(this._sectionVectors[e],i,this._sectionVectors[e]),rm.P.TransformNormalToRef(this._sectionNormalVectors[e],i,this._sectionNormalVectors[e]);for(let i=0;i<this._sectionPolygonPointsCount;i++)e[r+3*i]=this._sectionVectors[i].x,e[r+3*i+1]=this._sectionVectors[i].y,e[r+3*i+2]=this._sectionVectors[i].z,t[r+3*i]=this._sectionNormalVectors[i].x,t[r+3*i+1]=this._sectionNormalVectors[i].y,t[r+3*i+2]=this._sectionNormalVectors[i].z;this.updateVerticesData(rz.o.PositionKind,e,!0,!1),this.updateVerticesData(rz.o.NormalKind,t,!0,!1)}}clone(e="",t){return new TrailMesh(e,void 0===t?this._generator:t,this.getScene(),this.diameter,this._length,this._autoStart)}serialize(e){super.serialize(e),e.generatorId=this._generator.id}static Parse(e,t){var i,r;let s=null!==(i=t.getLastMeshById(e.generatorId))&&void 0!==i?i:t.getLastTransformNodeById(e.generatorId);if(!s)throw Error("TrailMesh: generator not found with ID "+e.generatorId);return new TrailMesh(e.name,s,t,null!==(r=e.diameter)&&void 0!==r?r:e._diameter,e._length,e._autoStart)}};let SimplificationQueue=class SimplificationQueue{constructor(){this.running=!1,this._simplificationArray=[]}addTask(e){this._simplificationArray.push(e)}executeNext(){let e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1}runSimplification(e){if(e.parallelProcessing)e.settings.forEach(t=>{let i=this._getSimplifier(e);i.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{let t=this._getSimplifier(e),runDecimation=(i,r)=>{t.simplify(i,t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,r()})};rW.$g.Run(e.settings.length,t=>{runDecimation(e.settings[t.index],()=>{t.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){return e.simplificationType,iV.QUADRATIC,new QuadraticErrorSimplification(e.mesh)}};(eV=iV||(iV={}))[eV.QUADRATIC=0]="QUADRATIC";let DecimationTriangle=class DecimationTriangle{constructor(e){this._vertices=e,this.error=[,,,,],this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}};let DecimationVertex=class DecimationVertex{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new QuadraticMatrix,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}};let QuadraticMatrix=class QuadraticMatrix{constructor(e){this.data=Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,s,n,a,o,l){let h=this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[r]*this.data[o]+this.data[t]*this.data[n]*this.data[a]-this.data[i]*this.data[s]*this.data[a]-this.data[e]*this.data[n]*this.data[o]-this.data[t]*this.data[r]*this.data[l];return h}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){let t=new QuadraticMatrix;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}};let Reference=class Reference{constructor(e,t){this.vertexId=e,this.triangleId=t}};let QuadraticErrorSimplification=class QuadraticErrorSimplification{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=rw.kn}simplify(e,t){this._initDecimatedMesh(),rW.$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){let r=~~(this._triangles.length*e.quality),s=0,n=this._triangles.length,iterationFunction=(e,t)=>{setTimeout(()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e<this._triangles.length;++e)this._triangles[e].isDirty=!1;let i=1e-9*Math.pow(e+3,this.aggressiveness);rW.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=~~((this._triangles.length/2+e)%this._triangles.length),r=this._triangles[t];if(r&&!(r.error[3]>i)&&!r.deleted&&!r.isDirty){for(let e=0;e<3;++e)if(r.error[e]<i){let t=[],i=[],n=r._vertices[e],a=r._vertices[(e+1)%3];if(n.isBorder||a.isBorder)continue;let o=rm.P.Zero();this._calculateError(n,a,o);let l=[];if(this._isFlipped(n,a,o,t,l)||this._isFlipped(a,n,o,i,l)||0>t.indexOf(!0)||0>i.indexOf(!0))continue;let h=[];if(l.forEach(e=>{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))}),h.length%2!=0)continue;n.q=a.q.add(n.q),n.updatePosition(o);let u=this._references.length;s=this._updateTriangles(n,n,t,s),s=this._updateTriangles(n,a,i,s);let c=this._references.length-u;if(c<=n.triangleCount){if(c)for(let e=0;e<c;e++)this._references[n.triangleStart+e]=this._references[u+e]}else n.triangleStart=u;n.triangleCount=c;break}}},t,()=>n-s<=r)},0)};rW.$g.Run(this.decimationIterations,e=>{n-s<=r?e.breakLoop():iterationFunction(e.index,()=>{e.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];let r=this._mesh.getVerticesData(rz.o.PositionKind),s=this._mesh.getIndices(),n=this._mesh.subMeshes[e],findInVertices=e=>{if(i){for(let t=0;t<this._vertices.length;++t)if(this._vertices[t].position.equalsWithEpsilon(e,1e-4))return this._vertices[t]}return null},a=[],o=n.verticesCount;rW.$g.SyncAsyncForLoop(o,this.syncIterations/4>>0,e=>{if(!r)return;let t=e+n.verticesStart,i=rm.P.FromArray(r,3*t),s=findInVertices(i)||new DecimationVertex(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),a.push(s.id)},()=>{rW.$g.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,e=>{if(!s)return;let t=n.indexStart/3+e,i=3*t,r=s[i+0],o=s[i+1],l=s[i+2],h=this._vertices[a[r-n.verticesStart]],u=this._vertices[a[o-n.verticesStart]],c=this._vertices[a[l-n.verticesStart]],d=new DecimationTriangle([h,u,c]);d.originalOffset=i,this._triangles.push(d)},()=>{this._init(t)})})}_init(e){rW.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];t.normal=rm.P.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-rm.P.Dot(t.normal,t._vertices[0].position)))},()=>{rW.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])},()=>{e()})})}_reconstructMesh(e){let t,i,r;let s=[];for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleCount=0;for(t=0;t<this._triangles.length;++t)if(!this._triangles[t].deleted){for(r=0,i=this._triangles[t];r<3;++r)i._vertices[r].triangleCount=1;s.push(i)}let n=this._reconstructedMesh.getVerticesData(rz.o.PositionKind)||[],a=this._reconstructedMesh.getVerticesData(rz.o.NormalKind)||[],o=this._reconstructedMesh.getVerticesData(rz.o.UVKind)||[],l=this._reconstructedMesh.getVerticesData(rz.o.ColorKind)||[],h=this._mesh.getVerticesData(rz.o.NormalKind),u=this._mesh.getVerticesData(rz.o.UVKind),c=this._mesh.getVerticesData(rz.o.ColorKind),d=0;for(t=0;t<this._vertices.length;++t){let e=this._vertices[t];e.id=d,e.triangleCount&&e.originalOffsets.forEach(t=>{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(a.push(h[3*t]),a.push(h[3*t+1]),a.push(h[3*t+2])),u&&u.length&&(o.push(u[2*t]),o.push(u[2*t+1])),c&&c.length&&(l.push(c[4*t]),l.push(c[4*t+1]),l.push(c[4*t+2]),l.push(c[4*t+3])),++d})}let p=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];let m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(t=0;t<s.length;++t)i=s[t],[0,1,2].forEach(e=>{let t=g[i.originalOffset+e],r=i._vertices[e].originalOffsets.indexOf(t);r<0&&(r=0),m.push(i._vertices[e].id+r+_)});this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(rz.o.PositionKind,n),a.length>0&&this._reconstructedMesh.setVerticesData(rz.o.NormalKind,a),o.length>0&&this._reconstructedMesh.setVerticesData(rz.o.UVKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(rz.o.ColorKind,l);let v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach(e=>{oJ.P.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())}),oJ.P.AddToMesh(v.materialIndex,_,d,p,3*s.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new rV.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,r,s){for(let n=0;n<e.triangleCount;++n){let a=this._triangles[this._references[e.triangleStart+n].triangleId];if(a.deleted)continue;let o=this._references[e.triangleStart+n].vertexId,l=a._vertices[(o+1)%3],h=a._vertices[(o+2)%3];if(l===t||h===t){r[n]=!0,s.push(a);continue}let u=l.position.subtract(i);u=u.normalize();let c=h.position.subtract(i);if(c=c.normalize(),Math.abs(rm.P.Dot(u,c))>.999)return!0;let d=rm.P.Cross(u,c).normalize();if(r[n]=!1,.2>rm.P.Dot(d,a.normal))return!0}return!1}_updateTriangles(e,t,i,r){let s=r;for(let r=0;r<t.triangleCount;++r){let n=this._references[t.triangleStart+r],a=this._triangles[n.triangleId];if(!a.deleted){if(i[r]&&a.deletePending){a.deleted=!0,s++;continue}a._vertices[n.vertexId]=e,a.isDirty=!0,a.error[0]=this._calculateError(a._vertices[0],a._vertices[1])+a.borderFactor/2,a.error[1]=this._calculateError(a._vertices[1],a._vertices[2])+a.borderFactor/2,a.error[2]=this._calculateError(a._vertices[2],a._vertices[0])+a.borderFactor/2,a.error[3]=Math.min(a.error[0],a.error[1],a.error[2]),this._references.push(n)}}return s}_identifyBorder(){for(let e=0;e<this._vertices.length;++e){let t;let i=[],r=[],s=this._vertices[e];for(t=0;t<s.triangleCount;++t){let e=this._triangles[this._references[s.triangleStart+t].triangleId];for(let t=0;t<3;t++){let s=0,n=e._vertices[t];for(;s<i.length&&r[s]!==n.id;)++s;s===i.length?(i.push(1),r.push(n.id)):i[s]++}}for(t=0;t<i.length;++t)1===i[t]?this._vertices[r[t]].isBorder=!0:this._vertices[r[t]].isBorder=!1}}_updateMesh(e=!1){let t,i,r,s;if(!e){let e=[];for(t=0;t<this._triangles.length;++t)this._triangles[t].deleted||e.push(this._triangles[t]);this._triangles=e}for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleCount=0,this._vertices[t].triangleStart=0;for(t=0;t<this._triangles.length;++t)for(r=0,i=this._triangles[t];r<3;++r)s=i._vertices[r],s.triangleCount++;let n=0;for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleStart=n,n+=this._vertices[t].triangleCount,this._vertices[t].triangleCount=0;let a=Array(3*this._triangles.length);for(t=0;t<this._triangles.length;++t)for(r=0,i=this._triangles[t];r<3;++r)a[(s=i._vertices[r]).triangleStart+s.triangleCount]=new Reference(r,t),s.triangleCount++;this._references=a,e&&this._identifyBorder()}_vertexError(e,t){let i=t.x,r=t.y,s=t.z;return e.data[0]*i*i+2*e.data[1]*i*r+2*e.data[2]*i*s+2*e.data[3]*i+e.data[4]*r*r+2*e.data[5]*r*s+2*e.data[6]*r+e.data[7]*s*s+2*e.data[8]*s+e.data[9]}_calculateError(e,t,i){let r=e.q.add(t.q),s=e.isBorder&&t.isBorder,n=0,a=r.det(0,1,2,1,4,5,2,5,7);if(0===a||s){let s=e.position.add(t.position).divide(new rm.P(2,2,2)),a=this._vertexError(r,e.position),o=this._vertexError(r,t.position),l=this._vertexError(r,s);(n=Math.min(a,o,l))===a?i&&i.copyFrom(e.position):n===o?i&&i.copyFrom(t.position):i&&i.copyFrom(s)}else i||(i=rm.P.Zero()),i.x=-1/a*r.det(1,2,3,4,5,6,5,7,8),i.y=1/a*r.det(0,2,3,1,5,6,2,7,8),i.z=-1/a*r.det(0,1,3,1,4,6,2,5,8),n=this._vertexError(r,i);return n}};Object.defineProperty(rN.x.prototype,"simplificationQueue",{get:function(){if(!this._simplificationQueue){this._simplificationQueue=new SimplificationQueue;let e=this._getComponent(rQ.l.NAME_SIMPLIFICATIONQUEUE);e||(e=new SimplicationQueueSceneComponent(this),this._addComponent(e))}return this._simplificationQueue},set:function(e){this._simplificationQueue=e},enumerable:!0,configurable:!0}),rV.Kj.prototype.simplify=function(e,t=!0,i=iV.QUADRATIC,r){return this.getScene().simplificationQueue.addTask({settings:e,parallelProcessing:t,mesh:this,simplificationType:i,successCallback:r}),this};let SimplicationQueueSceneComponent=class SimplicationQueueSceneComponent{constructor(e){this.name=rQ.l.NAME_SIMPLIFICATIONQUEUE,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(rQ.l.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE,this,this._beforeCameraUpdate)}rebuild(){}dispose(){}_beforeCameraUpdate(){this.scene._simplificationQueue&&!this.scene._simplificationQueue.running&&this.scene._simplificationQueue.executeNext()}};i(4926),(ek=ik||(ik={}))[ek.POINTS_MODE_POINTS=0]="POINTS_MODE_POINTS",ek[ek.POINTS_MODE_PATHS=1]="POINTS_MODE_PATHS",(eG=iG||(iG={}))[eG.FACES_MODE_SINGLE_SIDED=0]="FACES_MODE_SINGLE_SIDED",eG[eG.FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING=1]="FACES_MODE_SINGLE_SIDED_NO_BACKFACE_CULLING",eG[eG.FACES_MODE_DOUBLE_SIDED=2]="FACES_MODE_DOUBLE_SIDED",(ez=iz||(iz={}))[ez.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT=0]="AUTO_DIRECTIONS_FROM_FIRST_SEGMENT",ez[ez.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS=1]="AUTO_DIRECTIONS_FROM_ALL_SEGMENTS",ez[ez.AUTO_DIRECTIONS_ENHANCED=2]="AUTO_DIRECTIONS_ENHANCED",ez[ez.AUTO_DIRECTIONS_NONE=99]="AUTO_DIRECTIONS_NONE";let GreasedLineBaseMesh=class GreasedLineBaseMesh extends rV.Kj{constructor(e,t,i){var r,s,n,a;super(e,t,null,null,!1,!1),this.name=e,this._options=i,this._lazy=!1,this._updatable=!1,this._engine=t.getEngine(),this._lazy=null!==(r=i.lazy)&&void 0!==r&&r,this._updatable=null!==(s=i.updatable)&&void 0!==s&&s,this._vertexPositions=[],this._indices=[],this._uvs=[],this._points=[],this._colorPointers=null!==(n=i.colorPointers)&&void 0!==n?n:[],this._widths=null!==(a=i.widths)&&void 0!==a?a:Array(i.points.length).fill(1)}getClassName(){return"GreasedLineMesh"}_updateWidthsWithValue(e){let t=0;for(let e of this._points)t+=e.length;let i=t/3*2-this._widths.length;for(let t=0;t<i;t++)this._widths.push(e)}updateLazy(){var e,t;this._setPoints(this._points),this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(null===(e=this._options.ribbonOptions)||void 0===e?void 0:e.smoothShading),this.refreshBoundingInfo(),null===(t=this.greasedLineMaterial)||void 0===t||t.updateLazy()}addPoints(e,t){for(let t of e)this._points.push(t);this._lazy||this.setPoints(this._points,t)}dispose(){super.dispose()}isLazy(){return this._lazy}get offsets(){return this._offsets}set offsets(e){this._offsets=e,this._offsetsBuffer?this._offsetsBuffer.update(e):this._createOffsetsBuffer(e)}get widths(){return this._widths}set widths(e){this._widths=e,!this._lazy&&this._widthsBuffer&&this._widthsBuffer.update(e)}get colorPointers(){return this._colorPointers}set colorPointers(e){this._colorPointers=e,!this._lazy&&this._colorPointersBuffer&&this._colorPointersBuffer.update(e)}get greasedLineMaterial(){var e,t;if(this.material&&this.material instanceof greasedLineSimpleMaterial_GreasedLineSimpleMaterial)return this.material;let i=null===(t=null===(e=this.material)||void 0===e?void 0:e.pluginManager)||void 0===t?void 0:t.getPlugin(greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME);if(i)return i}get points(){let e=[];return rC.j.DeepCopy(this._points,e),e}setPoints(e,t){this._points=e,this._updateWidths(),(null==t?void 0:t.colorPointers)||this._updateColorPointers(),this._setPoints(e,t)}_initGreasedLine(){this._vertexPositions=[],this._indices=[],this._uvs=[]}_createLineOptions(){let e={points:this._points,colorPointers:this._colorPointers,lazy:this._lazy,updatable:this._updatable,uvs:this._uvs,widths:this._widths,ribbonOptions:this._options.ribbonOptions};return e}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions()}_createVertexBuffers(e=!1){let t=new se.x;return t.positions=this._vertexPositions,t.indices=this._indices,t.uvs=this._uvs,e&&(t.normals=[],se.x.ComputeNormals(this._vertexPositions,this._indices,t.normals)),t.applyToMesh(this,this._options.updatable),t}_createOffsetsBuffer(e){let t=this._scene.getEngine(),i=new rz.l(t,e,this._updatable,3);this.setVerticesBuffer(i.createVertexBuffer("grl_offsets",0,3)),this._offsetsBuffer=i}};rV.Kj._GreasedLineMeshParser=(e,t)=>greasedLineMesh_GreasedLineMesh.Parse(e,t);let greasedLineMesh_GreasedLineMesh=class greasedLineMesh_GreasedLineMesh extends GreasedLineBaseMesh{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(greasedLineTools_GreasedLineTools.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach(t=>{for(let i=0;i<t.length;i+=3)this._colorPointers.push(e),this._colorPointers.push(e++)})}_updateWidths(){super._updateWidthsWithValue(0)}_setPoints(e){this._points=e,this._options.points=e,this._initGreasedLine();let t=0;e.forEach(e=>{var i;let r=[],s=[],n=[],a=greasedLineTools_GreasedLineTools.GetLineLength(e);for(let i=0,o=0;o<e.length;i++,o+=3){let l=e.slice(0,o+3),h=greasedLineTools_GreasedLineTools.GetLineLength(l),u=h/a;if(s.push(e[o],e[o+1],e[o+2]),s.push(e[o],e[o+1],e[o+2]),r.push(u),r.push(u),o<e.length-3){let e=2*i+t;n.push(e,e+1,e+2),n.push(e+2,e+1,e+3)}}t+=e.length/3*2;let o=[],l=[],h=[],u=[];for(let e of(this._preprocess(s,o,l,h,u),s))this._vertexPositions.push(e);for(let e of n)this._indices.push(e);for(let e=0;e<h.length;e++)this._previousAndSide.push(o[3*e],o[3*e+1],o[3*e+2],h[e]),this._nextAndCounters.push(l[3*e],l[3*e+1],l[3*e+2],r[e]);for(let e of u=null!==(i=this._options.uvs)&&void 0!==i?i:u)this._uvs.push(e)}),this._lazy||(this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(),this.refreshBoundingInfo())}clone(e=`${this.name}-cloned`,t){let i=this._createLineOptions(),r={};rC.j.DeepCopy(i,r,["instance"],void 0,!0);let s=new greasedLineMesh_GreasedLineMesh(e,this._scene,r);return t&&(s.parent=t),s.material=this.material,s}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions()}static Parse(e,t){let i=e.lineOptions,r=e.name,s=new greasedLineMesh_GreasedLineMesh(r,t,i);return s}_initGreasedLine(){super._initGreasedLine(),this._previousAndSide=[],this._nextAndCounters=[]}intersects(e,t,i,r=!1,s,n=!1){let a=new r7.p,o=this.findAllIntersections(e,t,i,r,s,n,!0);if((null==o?void 0:o.length)===1){let t=o[0];a.hit=!0,a.distance=t.distance,a.ray=e,a.pickedMesh=this,a.pickedPoint=t.point}return a}findAllIntersections(e,t,i,r=!1,s,n=!1,a=!1){var o,l;if(r&&!n&&!1===e.intersectsSphere(this._boundingSphere,this.intersectionThreshold))return;let h=this.getIndices(),u=this.getVerticesData(rz.o.PositionKind),c=this._widths,d=null!==(l=null===(o=this.greasedLineMaterial)||void 0===o?void 0:o.width)&&void 0!==l?l:1,p=[];if(h&&u&&c){let t=0,i=0;for(t=0,i=h.length-1;t<i;t+=3){let i=h[t],r=h[t+1];greasedLineMesh_GreasedLineMesh._V_START.fromArray(u,3*i),greasedLineMesh_GreasedLineMesh._V_END.fromArray(u,3*r),this._offsets&&(greasedLineMesh_GreasedLineMesh._V_OFFSET_START.fromArray(this._offsets,3*i),greasedLineMesh_GreasedLineMesh._V_OFFSET_END.fromArray(this._offsets,3*r),greasedLineMesh_GreasedLineMesh._V_START.addInPlace(greasedLineMesh_GreasedLineMesh._V_OFFSET_START),greasedLineMesh_GreasedLineMesh._V_END.addInPlace(greasedLineMesh_GreasedLineMesh._V_OFFSET_END));let s=Math.floor(t/3),n=void 0!==c[s]?c[s]:1,o=this.intersectionThreshold*(d*n)/2,l=e.intersectionSegment(greasedLineMesh_GreasedLineMesh._V_START,greasedLineMesh_GreasedLineMesh._V_END,o);if(-1!==l&&(p.push({distance:l,point:e.direction.normalize().multiplyByFloats(l,l,l).add(e.origin)}),a))return p}t=i}return p}get _boundingSphere(){return this.getBoundingInfo().boundingSphere}static _CompareV3(e,t,i){let r=6*e,s=6*t;return i[r]===i[s]&&i[r+1]===i[s+1]&&i[r+2]===i[s+2]}static _CopyV3(e,t){let i=6*e;return[t[i],t[i+1],t[i+2]]}_preprocess(e,t,i,r,s){let n=e.length/6,a=[];a=greasedLineMesh_GreasedLineMesh._CompareV3(0,n-1,e)?greasedLineMesh_GreasedLineMesh._CopyV3(n-2,e):greasedLineMesh_GreasedLineMesh._CopyV3(0,e),t.push(a[0],a[1],a[2]),t.push(a[0],a[1],a[2]);for(let o=0;o<n;o++)r.push(1),r.push(-1),this._options.uvs||(s.push(o/(n-1),0),s.push(o/(n-1),1)),o<n-1&&(a=greasedLineMesh_GreasedLineMesh._CopyV3(o,e),t.push(a[0],a[1],a[2]),t.push(a[0],a[1],a[2])),o>0&&(a=greasedLineMesh_GreasedLineMesh._CopyV3(o,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]));return a=greasedLineMesh_GreasedLineMesh._CompareV3(n-1,0,e)?greasedLineMesh_GreasedLineMesh._CopyV3(1,e):greasedLineMesh_GreasedLineMesh._CopyV3(n-1,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]),{previous:t,next:i,uvs:s,side:r}}_createVertexBuffers(){let e=super._createVertexBuffers(),t=this._scene.getEngine(),i=new rz.l(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));let r=new rz.l(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(r.createVertexBuffer("grl_nextAndCounters",0,4));let s=new rz.l(t,this._widths,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s;let n=new rz.l(t,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(n.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=n,e}};greasedLineMesh_GreasedLineMesh._V_START=new rm.P,greasedLineMesh_GreasedLineMesh._V_END=new rm.P,greasedLineMesh_GreasedLineMesh._V_OFFSET_START=new rm.P,greasedLineMesh_GreasedLineMesh._V_OFFSET_END=new rm.P,rV.Kj._GreasedLineRibbonMeshParser=(e,t)=>greasedLineRibbonMesh_GreasedLineRibbonMesh.Parse(e,t);let greasedLineRibbonMesh_GreasedLineRibbonMesh=class greasedLineRibbonMesh_GreasedLineRibbonMesh extends GreasedLineBaseMesh{constructor(e,t,i,r){var s;if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=null!==(s=i.widths)&&void 0!==s?s:[],this._ribbonWidths=[],this._pathsOptions=null!=r?r:[],i.points&&this.addPoints(greasedLineTools_GreasedLineTools.ConvertPoints(i.points),i,!!r)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t<this._pathsOptions.length;t++){let{options:i,pathCount:r}=this._pathsOptions[t],s=this._points[t];if(i.ribbonOptions.pointsMode===ik.POINTS_MODE_POINTS)for(let t=0;t<r;t++)for(let t=0;t<s.length;t+=3)this._colorPointers.push(e),this._colorPointers.push(e++);else for(let t=0;t<s.length;t+=3){for(let t=0;t<r;t++)this._colorPointers.push(e);e++}}}_updateWidths(){super._updateWidthsWithValue(1)}_setPoints(e,t){var i,r;let s;if(!this._options.ribbonOptions)throw"No 'GreasedLineMeshOptions.ribbonOptions' provided.";this._points=e,this._options.points=e,this._initGreasedLine();let n=0;for(let t=0,a=0;t<this._pathsOptions.length;t++){let{options:o,pathCount:l}=this._pathsOptions[t],h=e.slice(a,a+l);if(a+=l,(null===(i=o.ribbonOptions)||void 0===i?void 0:i.pointsMode)===ik.POINTS_MODE_PATHS)n=this._preprocess(greasedLineTools_GreasedLineTools.ToVector3Array(h),n,o);else{if((null===(r=o.ribbonOptions)||void 0===r?void 0:r.directionsAutoMode)===iz.AUTO_DIRECTIONS_NONE){if(!o.ribbonOptions.directions)throw"In GreasedLineRibbonAutoDirectionMode.AUTO_DIRECTIONS_NONE 'GreasedLineMeshOptions.ribbonOptions.directions' must be defined.";s=greasedLineRibbonMesh_GreasedLineRibbonMesh._GetDirectionPlanesFromDirectionsOption(h.length,o.ribbonOptions.directions)}h.forEach((e,t)=>{let i=greasedLineRibbonMesh_GreasedLineRibbonMesh._ConvertToRibbonPath(e,o.ribbonOptions,this._scene.useRightHandedSystem,s?s[t]:s);n=this._preprocess(i,n,o)})}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:Array(e).fill(t)}static _CreateRibbonVertexData(e,t){var i,r,s;let n=e.length;if(n<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";let a=[],o=[],l=e[0];for(let t=0;t<l.length;t++)for(let i=0;i<e.length;i++){let r=e[i][t];a.push(r.x,r.y,r.z)}let h=[1,0,n],u=(null===(i=t.ribbonOptions)||void 0===i?void 0:i.facesMode)===iG.FACES_MODE_DOUBLE_SIDED,c=(null===(s=t.ribbonOptions)||void 0===s?void 0:s.pointsMode)===ik.POINTS_MODE_PATHS&&t.ribbonOptions.closePath;if(n>2)for(let e=0;e<l.length-1;e++){h[0]=1+n*e,h[1]=n*e,h[2]=(e+1)*n;for(let e=0;e<(n-1)*2;e++)e%2!=0&&(h[2]+=1),e%2==0&&e>0&&(h[0]+=1,h[1]+=1),o.push(h[1]+(e%2!=0?n:0),h[0],h[2]),u&&o.push(h[0],h[1]+(e%2!=0?n:0),h[2])}else for(let e=0;e<a.length/3-3;e+=2)o.push(e,e+1,e+2),o.push(e+2,e+1,e+3),u&&(o.push(e+1,e,e+2),o.push(e+1,e+2,e+3));if(c){let e=n*(l.length-1);for(let t=0;t<n-1;t++)o.push(e,t+1,t),o.push(e+1,t+1,e),u&&(o.push(t,t+1,e),o.push(e,t+1,e+1)),e++}return{positions:a,indices:o}}_preprocess(e,t,i){var r,s,n,a;this._paths=e;let o=greasedLineRibbonMesh_GreasedLineRibbonMesh._CreateRibbonVertexData(e,i),l=o.positions;if(!this._options.widths)throw"No 'GreasedLineMeshOptions.widths' table is specified.";for(let e of l)this._vertexPositions.push(e);let h=e;if((null===(r=i.ribbonOptions)||void 0===r?void 0:r.pointsMode)===ik.POINTS_MODE_PATHS&&i.ribbonOptions.closePath){h=[];for(let t=0;t<e.length;t++){let i=e[t].slice();i.push(e[t][0].clone()),h.push(i)}}this._calculateSegmentLengths(h);let u=h.length,c=Array(u).fill(0);for(let e=0;e<h[0].length;e++){let t=0;for(let i=0;i<u;i++){let r=c[i]+this._vSegmentLengths[i][e]/this._vTotalLengths[i];this._counters.push(r),this._uvs.push(r,t),c[i]=r,t+=this._uSegmentLengths[e][i]/this._uTotalLengths[e]}}for(let e=0,t=0;e<h[0].length;e++){let i=this._uSegmentLengths[e][0]/2,r=this._uSegmentLengths[e][u-1]/2;this._ribbonWidths.push(((null!==(s=this._widths[t++])&&void 0!==s?s:1)-1)*i);for(let e=0;e<u-2;e++)this._ribbonWidths.push(0);this._ribbonWidths.push(((null!==(n=this._widths[t++])&&void 0!==n?n:1)-1)*r)}let d=(null===(a=i.ribbonOptions)||void 0===a?void 0:a.pointsMode)===ik.POINTS_MODE_PATHS?Array(h[0].length*h.length*6).fill(0):greasedLineRibbonMesh_GreasedLineRibbonMesh._CalculateSlopes(h);for(let e of d)this._slopes.push(e);if(o.indices)for(let e=0;e<o.indices.length;e++)this._indices.push(o.indices[e]+t);return t+=l.length/3}static _ConvertToRibbonPath(e,t,i,r){if(t.pointsMode===ik.POINTS_MODE_POINTS&&!t.width)throw"'GreasedLineMeshOptions.ribbonOptiosn.width' must be specified in GreasedLineRibbonPointsMode.POINTS_MODE_POINTS.";let s=[],n=[];if(t.pointsMode===ik.POINTS_MODE_POINTS){let a=t.width/2,o=greasedLineTools_GreasedLineTools.ToVector3Array(e),l=null,h=null;t.directionsAutoMode===iz.AUTO_DIRECTIONS_FROM_FIRST_SEGMENT&&(r=greasedLineRibbonMesh_GreasedLineRibbonMesh._GetDirectionFromPoints(o[0],o[1],null));for(let e=0;e<o.length-(r?0:1);e++){let u=o[e],c=o[e+1];if(r)l=r;else if(t.directionsAutoMode===iz.AUTO_DIRECTIONS_FROM_ALL_SEGMENTS)l=greasedLineRibbonMesh_GreasedLineRibbonMesh._GetDirectionFromPoints(u,c,l);else{let e=c.subtract(u);e.applyRotationQuaternionInPlace(e.x>e.y&&e.x>e.z?i?greasedLineRibbonMesh_GreasedLineRibbonMesh._RightHandedForwardReadOnlyQuaternion:greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftHandedForwardReadOnlyQuaternion:greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(a,a,a),s.push(u.add(h)),n.push(u.subtract(h))}r||(s.push(o[o.length-1].add(h)),n.push(o[o.length-1].subtract(h)))}return[s,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&(null==i?void 0:i.x)!==1?e.y===t.y?greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XZ:e.z===t.z?greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XY:greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XZ:greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){let i=this._createLineOptions(),r={},s=[];rC.j.DeepCopy(this._pathsOptions,s,void 0,void 0,!0),rC.j.DeepCopy(i,r,["instance"],void 0,!0);let n=new greasedLineRibbonMesh_GreasedLineRibbonMesh(e,this._scene,r,s);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){let i=e.lineOptions,r=e.name,s=e.pathOptions,n=new greasedLineRibbonMesh_GreasedLineRibbonMesh(r,t,i,s);return n}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){let t=e.length;this._vSegmentLengths=Array(t),this._vTotalLengths=Array(t);let i=0;for(let r=0;r<t;r++){let t=e[r];this._vSegmentLengths[r]=[0],i=0;for(let e=0;e<t.length-1;e++){let s=Math.abs(t[e].subtract(t[e+1]).lengthSquared());i+=s,this._vSegmentLengths[r].push(s)}this._vTotalLengths[r]=i}let r=e[0].length;this._uSegmentLengths=Array(r).fill([]),this._uTotalLengths=Array(r).fill([]);let s=new rm.P;for(let n=0;n<r;n++){i=0;for(let r=1;r<t;r++){e[r][n].subtractToRef(e[r-1][n],s);let t=s.length();i+=t,this._uSegmentLengths[n].push(t)}this._uTotalLengths[n]=i}}static _CalculateSlopes(e){let t=e[0],i=2===e.length?e[1]:e[e.length-1],r=[],s=new rm.P;for(let n=0;n<t.length;n++)for(let a=0;a<e.length;a++)0===a||a===e.length-1?(t[n].subtract(i[n]).normalizeToRef(s),r.push(s.x,s.y,s.z),r.push(-s.x,-s.y,-s.z)):r.push(0,0,0,0,0,0);return r}_createVertexBuffers(){var e,t;this._uvs=null!==(e=this._options.uvs)&&void 0!==e?e:this._uvs;let i=super._createVertexBuffers(null===(t=this._options.ribbonOptions)||void 0===t?void 0:t.smoothShading),r=new rz.l(this._engine,this._counters,this._updatable,1);this.setVerticesBuffer(r.createVertexBuffer("grl_counters",0,1));let s=new rz.l(this._engine,this._colorPointers,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_colorPointers",0,1));let n=new rz.l(this._engine,this._slopes,this._updatable,3);this.setVerticesBuffer(n.createVertexBuffer("grl_slopes",0,3));let a=new rz.l(this._engine,this._ribbonWidths,this._updatable,1);return this.setVerticesBuffer(a.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=a,i}};greasedLineRibbonMesh_GreasedLineRibbonMesh.DEFAULT_WIDTH=.1,greasedLineRibbonMesh_GreasedLineRibbonMesh._RightHandedForwardReadOnlyQuaternion=rm._f.RotationAxis(rm.P.RightHandedForwardReadOnly,Math.PI/2),greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftHandedForwardReadOnlyQuaternion=rm._f.RotationAxis(rm.P.LeftHandedForwardReadOnly,Math.PI/2),greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftReadOnlyQuaternion=rm._f.RotationAxis(rm.P.LeftReadOnly,Math.PI/2),greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XY=rm.P.LeftHandedForwardReadOnly,greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XZ=rm.P.UpReadOnly,greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_YZ=rm.P.LeftReadOnly,(eW=iW||(iW={}))[eW.COLOR_DISTRIBUTION_NONE=0]="COLOR_DISTRIBUTION_NONE",eW[eW.COLOR_DISTRIBUTION_REPEAT=1]="COLOR_DISTRIBUTION_REPEAT",eW[eW.COLOR_DISTRIBUTION_EVEN=2]="COLOR_DISTRIBUTION_EVEN",eW[eW.COLOR_DISTRIBUTION_START=3]="COLOR_DISTRIBUTION_START",eW[eW.COLOR_DISTRIBUTION_END=4]="COLOR_DISTRIBUTION_END",eW[eW.COLOR_DISTRIBUTION_START_END=5]="COLOR_DISTRIBUTION_START_END",(eH=iH||(iH={}))[eH.WIDTH_DISTRIBUTION_NONE=0]="WIDTH_DISTRIBUTION_NONE",eH[eH.WIDTH_DISTRIBUTION_REPEAT=1]="WIDTH_DISTRIBUTION_REPEAT",eH[eH.WIDTH_DISTRIBUTION_EVEN=2]="WIDTH_DISTRIBUTION_EVEN",eH[eH.WIDTH_DISTRIBUTION_START=3]="WIDTH_DISTRIBUTION_START",eH[eH.WIDTH_DISTRIBUTION_END=4]="WIDTH_DISTRIBUTION_END",eH[eH.WIDTH_DISTRIBUTION_START_END=5]="WIDTH_DISTRIBUTION_START_END",i(998),rV.Kj.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return rT.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);let i=this._thinInstanceDataStorage.instancesCount;if(Array.isArray(e))for(let i=0;i<e.length;++i)this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e[i],i===e.length-1&&t);else this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e,t);return i},rV.Kj.prototype.thinInstanceAddSelf=function(e=!0){return this.thinInstanceAdd(rm.y3.IdentityReadOnly,e)},rV.Kj.prototype.thinInstanceRegisterAttribute=function(e,t){e===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind),this.removeVerticesData(e),this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.strides[e]=t,this._userThinInstanceBuffersStorage.sizes[e]=t*Math.max(32,this._thinInstanceDataStorage.instancesCount),this._userThinInstanceBuffersStorage.data[e]=new Float32Array(this._userThinInstanceBuffersStorage.sizes[e]),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new rz.o(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!0,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])},rV.Kj.prototype.thinInstanceSetMatrixAt=function(e,t,i=!0){if(!this._thinInstanceDataStorage.matrixData||e>=this._thinInstanceDataStorage.instancesCount)return!1;let r=this._thinInstanceDataStorage.matrixData;return t.copyToArray(r,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},rV.Kj.prototype.thinInstanceSetAttributeAt=function(e,t,i,r=!0){return e===rz.o.ColorKind&&(e=rz.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]),r&&this.thinInstanceBufferUpdated(e),!0)},Object.defineProperty(rV.Kj.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;let r=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData,s=r?r.length/16:0;e<=s&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),rV.Kj.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind);let r=new rz.l(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(r.createVertexBuffer(e+t,4*t,4));return r},rV.Kj.prototype.thinInstanceSetBuffer=function(e,t,i=0,r=!1){var s,n,a;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,r),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(null===(n=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===n||n.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,r))):(e===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind),null===t?(null===(a=this._userThinInstanceBuffersStorage)||void 0===a?void 0:a.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 rz.o(this.getEngine(),t,e,!r,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},rV.Kj.prototype.thinInstanceBufferUpdated=function(e){var t,i,r;"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===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},rV.Kj.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var r;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},rV.Kj.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];let e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;t<this._thinInstanceDataStorage.instancesCount;++t)this._thinInstanceDataStorage.worldMatrices[t]=rm.y3.FromArray(e,16*t)}return this._thinInstanceDataStorage.worldMatrices},rV.Kj.prototype.thinInstanceRefreshBoundingInfo=function(e=!1,t=!1,i=!1){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return;let r=this._thinInstanceDataStorage.boundingVectors;if(e||!this.rawBoundingInfo){r.length=0,this.refreshBoundingInfo(t,i);let e=this.getBoundingInfo();this.rawBoundingInfo=new nQ.j(e.minimum,e.maximum)}let s=this.getBoundingInfo(),n=this._thinInstanceDataStorage.matrixData;if(0===r.length)for(let e=0;e<s.boundingBox.vectors.length;++e)r.push(s.boundingBox.vectors[e].clone());rm.jp.Vector3[0].setAll(Number.POSITIVE_INFINITY),rm.jp.Vector3[1].setAll(Number.NEGATIVE_INFINITY);for(let e=0;e<this._thinInstanceDataStorage.instancesCount;++e){rm.y3.FromArrayToRef(n,16*e,rm.jp.Matrix[0]);for(let e=0;e<r.length;++e)rm.P.TransformCoordinatesToRef(r[e],rm.jp.Matrix[0],rm.jp.Vector3[2]),rm.jp.Vector3[0].minimizeInPlace(rm.jp.Vector3[2]),rm.jp.Vector3[1].maximizeInPlace(rm.jp.Vector3[2])}s.reConstruct(rm.jp.Vector3[0],rm.jp.Vector3[1]),this._updateBoundingInfo()},rV.Kj.prototype._thinInstanceUpdateBufferSize=function(e,t=1){var i,r,s;e===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind);let n="matrix"===e;if(!n&&(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.strides[e]))return;let a=n?16:this._userThinInstanceBuffersStorage.strides[e],o=n?this._thinInstanceDataStorage.matrixBufferSize:this._userThinInstanceBuffersStorage.sizes[e],l=n?this._thinInstanceDataStorage.matrixData:this._userThinInstanceBuffersStorage.data[e],h=(this._thinInstanceDataStorage.instancesCount+t)*a,u=o;for(;u<h;)u*=2;if(!l||o!=u){if(l){let e=new Float32Array(u);e.set(l,0),l=e}else l=new Float32Array(u);n?(null===(i=this._thinInstanceDataStorage.matrixBuffer)||void 0===i||i.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",l,!1),this._thinInstanceDataStorage.matrixData=l,this._thinInstanceDataStorage.matrixBufferSize=u,this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&(null===(r=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===r||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",l,!1))):(null===(s=this._userThinInstanceBuffersStorage.vertexBuffers[e])||void 0===s||s.dispose(),this._userThinInstanceBuffersStorage.data[e]=l,this._userThinInstanceBuffersStorage.sizes[e]=u,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new rz.o(this.getEngine(),l,e,!0,!1,a,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))}},rV.Kj.prototype._thinInstanceInitializeUserStorage=function(){this._userThinInstanceBuffersStorage||(this._userThinInstanceBuffersStorage={data:{},sizes:{},vertexBuffers:{},strides:{}})},rV.Kj.prototype._disposeThinInstanceSpecificData=function(){var e;(null===(e=this._thinInstanceDataStorage)||void 0===e?void 0:e.matrixBuffer)&&(this._thinInstanceDataStorage.matrixBuffer.dispose(),this._thinInstanceDataStorage.matrixBuffer=null)},(eX=iX||(iX={}))[eX.Int=1]="Int",eX[eX.Float=2]="Float",eX[eX.Vector2=4]="Vector2",eX[eX.Vector3=8]="Vector3",eX[eX.Vector4=16]="Vector4",eX[eX.Matrix=32]="Matrix",eX[eX.Geometry=64]="Geometry",eX[eX.Texture=128]="Texture",eX[eX.AutoDetect=1024]="AutoDetect",eX[eX.BasedOnInput=2048]="BasedOnInput",eX[eX.Undefined=4096]="Undefined",eX[eX.All=4095]="All",(eY=iY||(iY={}))[eY.Compatible=0]="Compatible",eY[eY.TypeIncompatible=1]="TypeIncompatible",eY[eY.HierarchyIssue=2]="HierarchyIssue",(ej=ij||(ij={}))[ej.Input=0]="Input",ej[ej.Output=1]="Output";let NodeGeometryConnectionPoint=class NodeGeometryConnectionPoint{get direction(){return this._direction}get type(){if(this._type===iX.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===iX.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map(e=>e.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}getConnectedValue(e){var t,i,r;return this.isConnected?(null===(t=this._connectedPoint)||void 0===t?void 0:t._storedFunction)?null===(i=this._connectedPoint)||void 0===i?void 0:i._storedFunction(e):null===(r=this._connectedPoint)||void 0===r?void 0:r._storedValue:this.value}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=[],this._type=iX.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new rf.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===iY.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==iX.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?iY.Compatible:iY.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return iY.TypeIncompatible;let r=i,s=t;return(this.direction===ij.Input&&(r=t,s=i),r.isAnAncestorOf(s))?iY.HierarchyIssue:iY.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t<iX.All;)e&t||this.excludedConnectionPointTypes.push(t),t<<=1}serialize(e=!0){let t={};return t.name=this.name,t.displayName=this.displayName,void 0!==this.value&&null!==this.value&&(this.value.asArray?(t.valueType="BABYLON."+this.value.getClassName(),t.value=this.value.asArray()):(t.valueType="number",t.value=this.value)),e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name),t}dispose(){this.onConnectionObservable.clear()}};let NodeGeometryBlock=class NodeGeometryBlock{get buildExecutionTime(){return this._buildExecutionTime}get inputs(){return this._inputs}get outputs(){return this._outputs}get name(){return this._name}set name(e){this._name=e}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isDebug(){return this._isDebug}get isUnique(){return this._isUnique}getClassName(){return"NodeGeometryBlock"}_inputRename(e){return e}_outputRename(e){return e}isAnAncestorOf(e){for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock.isAnAncestorOfType(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(let t of this._outputs)if(t.hasEndpoints)for(let i of t.endpoints){let t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}constructor(e){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this._buildExecutionTime=0,this.onBuildObservable=new rf.y$,this._inputs=[],this._outputs=[],this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=sa.K.UniqueId}registerInput(e,t,i=!1,r,s,n){let a=new NodeGeometryConnectionPoint(e,this,ij.Input);return a.type=t,a.isOptional=i,a.defaultValue=r,a.value=r,a.valueMin=s,a.valueMax=n,this._inputs.push(a),this}registerOutput(e,t,i){return(i=null!=i?i:new NodeGeometryConnectionPoint(e,this,ij.Output)).type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}build(e){if(this._buildId===e.buildId)return!0;if(this._outputs.length>0&&!this._outputs.some(e=>e.hasEndpoints)&&!this.isDebug)return!1;for(let t of(this._buildId=e.buildId,this._inputs)){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}let i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&console.log(`Building ${this.name} [${this.getClassName()}]`);let t=rF.F.Now;for(let i of(this._buildBlock(e),this._buildExecutionTime=rF.F.Now-t,this._outputs))for(let t of i.endpoints){let i=t.ownerBlock;i&&i.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}serialize(){let e={};for(let t of(e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.inputs=[],e.outputs=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach(e=>{let t=this.inputs.find(t=>t.name===e.name);if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value)){if("number"===e.valueType)t.value=e.value;else{let i=(0,rv.q)(e.valueType);i&&(t.value=i.FromArray(e.value))}}}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleOnFrame = ${this.visibleOnFrame}; +`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); +`}return t}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` +// ${this.getClassName()} +`;for(let i of(this.comments&&(r+=`// ${this.comments} +`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); +`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint,n=s.ownerBlock;-1===t.indexOf(n)&&(r+=n._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){let e=this.serialize(),t=(0,rv.q)(e.customType);if(t){let i=new t;return i._deserialize(e),i}return null}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose();this.onBuildObservable.clear()}};(0,rH.gn)([(0,rb.qC)("comment")],NodeGeometryBlock.prototype,"comments",void 0);let GeometryOutputBlock=class GeometryOutputBlock extends NodeGeometryBlock{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",iX.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}};(0,rv.H)("BABYLON.GeometryOutputBlock",GeometryOutputBlock),(eq=iq||(iq={}))[eq.None=0]="None",eq[eq.Positions=1]="Positions",eq[eq.Normals=2]="Normals",eq[eq.Tangents=3]="Tangents",eq[eq.UV=4]="UV",eq[eq.UV2=5]="UV2",eq[eq.UV3=6]="UV3",eq[eq.UV4=7]="UV4",eq[eq.UV5=8]="UV5",eq[eq.UV6=9]="UV6",eq[eq.Colors=10]="Colors",eq[eq.VertexID=11]="VertexID",eq[eq.FaceID=12]="FaceID",eq[eq.GeometryID=13]="GeometryID",eq[eq.CollectionID=14]="CollectionID",eq[eq.LoopID=15]="LoopID",eq[eq.InstanceID=16]="InstanceID";let NodeGeometryBuildState=class NodeGeometryBuildState{constructor(){this._rotationMatrix=new rm.y3,this._scalingMatrix=new rm.y3,this._positionMatrix=new rm.y3,this._scalingRotationMatrix=new rm.y3,this._transformMatrix=new rm.y3,this._tempVector3=new rm.P,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;let i=this.executionContext.getExecutionIndex();switch(e){case iq.Positions:if(this.executionContext.getOverridePositionsContextualValue)return this.executionContext.getOverridePositionsContextualValue();if(!this.geometryContext||!this.geometryContext.positions)return rm.P.Zero();return rm.P.FromArray(this.geometryContext.positions,3*i);case iq.Normals:if(this.executionContext.getOverrideNormalsContextualValue)return this.executionContext.getOverrideNormalsContextualValue();if(!this.geometryContext||!this.geometryContext.normals)return rm.P.Zero();return rm.P.FromArray(this.geometryContext.normals,3*i);case iq.Colors:if(!this.geometryContext||!this.geometryContext.colors)return rm.Lt.Zero();return rm.Lt.FromArray(this.geometryContext.colors,4*i);case iq.Tangents:if(!this.geometryContext||!this.geometryContext.tangents)return rm.Lt.Zero();return rm.Lt.FromArray(this.geometryContext.tangents,4*i);case iq.UV:if(this.executionContext.getOverrideUVs1ContextualValue)return this.executionContext.getOverrideUVs1ContextualValue();if(!this.geometryContext||!this.geometryContext.uvs)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs,2*i);case iq.UV2:if(!this.geometryContext||!this.geometryContext.uvs2)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs2,2*i);case iq.UV3:if(!this.geometryContext||!this.geometryContext.uvs3)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs3,2*i);case iq.UV4:if(!this.geometryContext||!this.geometryContext.uvs4)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs4,2*i);case iq.UV5:if(!this.geometryContext||!this.geometryContext.uvs5)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs5,2*i);case iq.UV6:if(!this.geometryContext||!this.geometryContext.uvs6)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs6,2*i);case iq.VertexID:return i;case iq.FaceID:return this.executionContext.getExecutionFaceIndex();case iq.LoopID:return this.executionContext.getExecutionLoopIndex();case iq.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case iq.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case iq.CollectionID:if(!this.geometryContext||!this.geometryContext.metadata)return 0;return this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){let i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case iX.Vector2:return new rm.FM(i,i);case iX.Vector3:return new rm.P(i,i,i);case iX.Vector4:return new rm.Lt(i,i,i,i)}return null}adaptInput(e,t,i){var r;if(!e.isConnected)return e.value||i;let s=e.getConnectedValue(this);if((null===(r=e._connectedPoint)||void 0===r?void 0:r.type)===t)return s;switch(t){case iX.Vector2:return new rm.FM(s,s);case iX.Vector3:return new rm.P(s,s,s);case iX.Vector4:return new rm.Lt(s,s,s,s)}return null}emitErrors(){let e="";for(let t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. +`;for(let t of this.noContextualData)e+=`Contextual input ${iq[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block). +`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,r,s){rm.y3.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),rm.y3.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),rm.y3.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;t<e.positions.length;t+=3)this._tempVector3.fromArray(e.positions,t),rm.P.TransformCoordinatesToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.positions,t),e.normals&&(this._tempVector3.fromArray(e.normals,t),rm.P.TransformNormalToRef(this._tempVector3,this._scalingRotationMatrix,this._tempVector3),this._tempVector3.toArray(e.normals,t));s.push(e)}_instantiateWithMatrix(e,t,i){for(let i=0;i<e.positions.length;i+=3)this._tempVector3.fromArray(e.positions,i),rm.P.TransformCoordinatesToRef(this._tempVector3,t,this._tempVector3),this._tempVector3.toArray(e.positions,i),e.normals&&(this._tempVector3.fromArray(e.normals,i),rm.P.TransformNormalToRef(this._tempVector3,t,this._tempVector3),this._tempVector3.toArray(e.normals,i));i.push(e)}_instantiateWithPositionAndMatrix(e,t,i,r){rm.y3.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),i.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;t<e.positions.length;t+=3)this._tempVector3.fromArray(e.positions,t),rm.P.TransformCoordinatesToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.positions,t),e.normals&&(this._tempVector3.fromArray(e.normals,t),rm.P.TransformNormalToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.normals,t));r.push(e)}};let GeometryInputBlock=class GeometryInputBlock extends NodeGeometryBlock{get type(){if(this._type===iX.AutoDetect&&null!=this.value){if(!isNaN(this.value))return this._type=iX.Float,this._type;switch(this.value.getClassName()){case"Vector2":this._type=iX.Vector2;break;case"Vector3":this._type=iX.Vector3;break;case"Vector4":this._type=iX.Vector4;break;case"Matrix":this._type=iX.Matrix}}return this._type}get isContextual(){return this._contextualSource!==iq.None}get contextualValue(){return this._contextualSource}set contextualValue(e){switch(this._contextualSource=e,e){case iq.Positions:case iq.Normals:this._type=iX.Vector3;break;case iq.Colors:case iq.Tangents:this._type=iX.Vector4;break;case iq.UV:case iq.UV2:case iq.UV3:case iq.UV4:case iq.UV5:case iq.UV6:this._type=iX.Vector2;break;case iq.VertexID:case iq.GeometryID:case iq.CollectionID:case iq.FaceID:case iq.LoopID:case iq.InstanceID:this._type=iX.Int}this.output&&(this.output.type=this._type)}constructor(e,t=iX.AutoDetect){super(e),this._type=iX.Undefined,this._contextualSource=iq.None,this.min=0,this.max=0,this.groupInInspector="",this.onValueChangedObservable=new rf.y$,this._type=t,this._isInput=!0,this.setDefaultValue(),this.registerOutput("output",t)}get value(){return this._storedValue}set value(e){this.type===iX.Float&&this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e)),this._storedValue=e,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e}getClassName(){return"GeometryInputBlock"}get output(){return this._outputs[0]}setDefaultValue(){switch(this.contextualValue=iq.None,this.type){case iX.Int:case iX.Float:this.value=0;break;case iX.Vector2:this.value=rm.FM.Zero();break;case iX.Vector3:this.value=rm.P.Zero();break;case iX.Vector4:this.value=rm.Lt.Zero();break;case iX.Matrix:this.value=rm.y3.Identity()}}_buildBlock(e){super._buildBlock(e),this.isContextual?(this.output._storedValue=null,this.output._storedFunction=e=>e.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${iq[this._contextualSource]}; +`;let t=[],i="";switch(this.type){case iX.Float:case iX.Int:i=`${this.value}`;break;case iX.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case iX.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case iX.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),(this.type===iX.Float||this.type===iX.Int)&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){let e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=(0,rv.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}};(0,rv.H)("BABYLON.GeometryInputBlock",GeometryInputBlock);let BoxBlock=class BoxBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",iX.Float,!0,1),this.registerInput("width",iX.Float,!0,0),this.registerInput("height",iX.Float,!0,0),this.registerInput("depth",iX.Float,!0,0),this.registerInput("subdivisions",iX.Int,!0,1),this.registerInput("subdivisionsX",iX.Int,!0,0),this.registerInput("subdivisionsY",iX.Int,!0,0),this.registerInput("subdivisionsZ",iX.Int,!0,0),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){let e=new GeometryInputBlock("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){let e=new GeometryInputBlock("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){let t={},func=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);let i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),r&&(t.widthSegments=r),s&&(t.heightSegments=s),n&&(t.depthSegments=n),CreateSegmentedBoxVertexData(t)};if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],BoxBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.BoxBlock",BoxBlock);let NodeGeometry=class NodeGeometry{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=NodeGeometry._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new rf.y$,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){rW.w1.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise(t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){let i=e&&e.editorURL?e.editorURL:NodeGeometry.EditorURL;rW.w1.LoadBabylonScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){let t=Object.assign({nodeGeometry:this},e);this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";let r=rF.F.Now;this._initializeBlock(this.outputBlock,i);let s=new NodeGeometryBuildState;s.buildId=this._buildId,s.verbose=e,this.outputBlock.build(s),t&&(this._buildId=NodeGeometry._BuildIdGenerator++),this._buildExecutionTime=rF.F.Now-r,s.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=s.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;let i=new rV.Kj(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){for(let i of(e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();let i={};for(let t of e.blocks){let e=(0,rv.q)(t.customType);if(e){let r=new e;r._deserialize(t),i[t.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;if(t){let r=i[t];r.attachToEndpoint(e)}}for(let r=0;r<e.blocks.length;r++){let s=e.blocks[r],n=i[s.id];!n||n.inputs.length&&s.inputs.some(e=>e.targetConnectionName)&&!t||this._restoreConnections(n,e,i)}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){let r=e.locations||e.editorData.locations;for(let e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);let s=[];for(let e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let n=i[s.id];if(n){for(let a of s.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===r.name){let e=n.getInputByName(a.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i);continue}}}}generateCode(){let e=[],t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); +`;for(let s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));return this.outputBlock&&(e=[],r+="// Connections\n"+this.outputBlock._dumpCodeForOutputConnections(e)+"// Output nodes\n"+`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; +`+`nodeGeometry.build(); +`),r}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}setToDefault(){this.clear(),this.editorData=null;let e=new BoxBlock("Box");e.autoConfigure();let t=new GeometryOutputBlock("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){let t=this.serialize(),i=rb.p4.Clone(()=>new NodeGeometry(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){let t=e?{}:rb.p4.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];for(let r of(e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[],i))t.blocks.push(r.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){let t=new NodeGeometry(e);return t.setToDefault(),t.build(),t}static Parse(e){let t=rb.p4.Parse(()=>new NodeGeometry(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(NodeGeometry.CreateDefault("blank")):new Promise((r,s)=>{let n=new rP.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let a=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(a.nodeGeometry);t||(t=rb.p4.Parse(()=>new NodeGeometry(e),o,null)),t.parseSerializedObject(o),t.snippetId=e;try{i||t.build(),r(t)}catch(e){s(e)}}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}};NodeGeometry._BuildIdGenerator=0,NodeGeometry.EditorURL=`${rW.w1._DefaultCdnUrl}/v${rq.D.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,NodeGeometry.SnippetUrl="https://snippet.babylonjs.com",(0,rH.gn)([(0,rb.qC)()],NodeGeometry.prototype,"name",void 0),(0,rH.gn)([(0,rb.qC)("comment")],NodeGeometry.prototype,"comment",void 0);let GeometryOptimizeBlock=class GeometryOptimizeBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=rw.kn,this.registerInput("geometry",iX.Geometry),this.registerOutput("output",iX.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e),i=[],r={};for(let e=0;e<t.positions.length;e+=3){let s=t.positions[e],n=t.positions[e+1],a=t.positions[e+2],o=!1;for(let t=0;t<i.length;t+=3)if(rE.R.WithinEpsilon(s,i[t],this.epsilon)&&rE.R.WithinEpsilon(n,i[t+1],this.epsilon)&&rE.R.WithinEpsilon(a,i[t+2],this.epsilon)){r[e/3]=t/3,o=!0;continue}o||(r[e/3]=i.length/3,i.push(s,n,a))}let s=new se.x;return s.positions=i,s.indices=t.indices.map(e=>r[e]),s};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`+`${this._codeVariableName}.epsilon = ${this.epsilon}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryOptimizeBlock.prototype,"evaluateContext",void 0),(0,rH.gn)([editableInPropertyPage("Epsilon",tT.Float,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryOptimizeBlock.prototype,"epsilon",void 0),(0,rv.H)("BABYLON.GeometryOptimizeBlock",GeometryOptimizeBlock);let PlaneBlock=class PlaneBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",iX.Float,!0,1),this.registerInput("width",iX.Float,!0,0),this.registerInput("height",iX.Float,!0,0),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){let e=new GeometryInputBlock("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){let t={},func=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),CreatePlaneVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],PlaneBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.PlaneBlock",PlaneBlock);let MeshBlock=class MeshBlock extends NodeGeometryBlock{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",iX.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}let e=se.x.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;t<e.indices.length;t+=3){let i=e.indices[t];e.indices[t]=e.indices[t+2],e.indices[t+2]=i}this.geometry._storedFunction=()=>e.clone()}serialize(){let e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=se.x.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=se.x.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}};(0,rH.gn)([editableInPropertyPage("Serialize cached data",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],MeshBlock.prototype,"serializedCachedData",void 0),(0,rv.H)("BABYLON.MeshBlock",MeshBlock);let IcoSphereBlock=class IcoSphereBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",iX.Float,!0,1),this.registerInput("radiusX",iX.Float,!0,0),this.registerInput("radiusY",iX.Float,!0,0),this.registerInput("radiusZ",iX.Float,!0,0),this.registerInput("subdivisions",iX.Int,!0,4),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),CreateIcoSphereVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],IcoSphereBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.IcoSphereBlock",IcoSphereBlock);let SphereBlock=class SphereBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",iX.Int,!0,32),this.registerInput("diameter",iX.Float,!0,1),this.registerInput("diameterX",iX.Float,!0,0),this.registerInput("diameterY",iX.Float,!0,0),this.registerInput("diameterZ",iX.Float,!0,0),this.registerInput("arc",iX.Float,!0,1),this.registerInput("slice",iX.Float,!0,1),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},func=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),CreateSphereVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SphereBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.SphereBlock",SphereBlock);let GridBlock=class GridBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",iX.Float,!0,1),this.registerInput("height",iX.Float,!0,1),this.registerInput("subdivisions",iX.Int,!0,1),this.registerInput("subdivisionsX",iX.Int,!0,0),this.registerInput("subdivisionsY",iX.Int,!0,0),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},func=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),CreateGroundVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GridBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.GridBlock",GridBlock);let TorusBlock=class TorusBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",iX.Float,!0,1),this.registerInput("thickness",iX.Float,!0,.5),this.registerInput("tessellation",iX.Int,!0,16),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},func=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),CreateTorusVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],TorusBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.TorusBlock",TorusBlock);let CylinderBlock=class CylinderBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",iX.Float,!0,25),this.registerInput("diameter",iX.Float,!0,1),this.registerInput("diameterTop",iX.Float,!0,-1),this.registerInput("diameterBottom",iX.Float,!0,-1),this.registerInput("subdivisions",iX.Int,!0,1),this.registerInput("tessellation",iX.Int,!0,24),this.registerInput("arc",iX.Float,!0,1),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},func=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),CreateCylinderVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CylinderBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.CylinderBlock",CylinderBlock);let CapsuleBlock=class CapsuleBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",iX.Float,!0,1),this.registerInput("radius",iX.Float,!0,.25),this.registerInput("tessellation",iX.Int,!0,16),this.registerInput("subdivisions",iX.Int,!0,2),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),CreateCapsuleVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CapsuleBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.CapsuleBlock",CapsuleBlock);let DiscBlock=class DiscBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",iX.Float,!0,.5),this.registerInput("tessellation",iX.Int,!0,64),this.registerInput("arc",iX.Float,!0,1),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),CreateDiscVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],DiscBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.DiscBlock",DiscBlock);let NullBlock=class NullBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}};(0,rv.H)("BABYLON.NullBlock",NullBlock);let SetPositionsBlock=class SetPositionsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("positions",iX.Vector3),this.registerOutput("output",iX.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.positions.getConnectedValue(e);t&&t.toArray(this._vertexData.positions,3*this._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetPositionsBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.SetPositionsBlock",SetPositionsBlock);let SetNormalsBlock=class SetNormalsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("normals",iX.Vector3),this.registerOutput("output",iX.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetNormalsBlock"}get geometry(){return this._inputs[0]}get normals(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.normals.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.normals||(this._vertexData.normals=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.normals.getConnectedValue(e);t&&t.toArray(this._vertexData.normals,3*this._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetNormalsBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.SetNormalsBlock",SetNormalsBlock);let SetUVsBlock=class SetUVsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.textureCoordinateIndex=0,this.registerInput("geometry",iX.Geometry),this.registerInput("uvs",iX.Vector2),this.registerOutput("output",iX.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetUVsBlock"}get geometry(){return this._inputs[0]}get uvs(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.uvs.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}let t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<i;this._currentIndex++){let i=this.uvs.getConnectedValue(e);i&&i.toArray(t,2*this._currentIndex)}switch(this.textureCoordinateIndex){case 0:this._vertexData.uvs=t;break;case 1:this._vertexData.uvs2=t;break;case 2:this._vertexData.uvs3=t;break;case 3:this._vertexData.uvs4=t;break;case 4:this._vertexData.uvs5=t;break;case 5:this._vertexData.uvs6=t}return e.restoreGeometryContext(),e.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.textureCoordinateIndex}; +`+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.textureCoordinateIndex=this.textureCoordinateIndex,e}_deserialize(e){super._deserialize(e),this.textureCoordinateIndex=e.textureCoordinateIndex,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetUVsBlock.prototype,"evaluateContext",void 0),(0,rH.gn)([editableInPropertyPage("Texture coordinates index",tT.List,"ADVANCED",{notifiers:{update:!0},options:[{label:"UV1",value:0},{label:"UV2",value:1},{label:"UV3",value:2},{label:"UV4",value:3},{label:"UV5",value:4},{label:"UV6",value:5}]})],SetUVsBlock.prototype,"textureCoordinateIndex",void 0),(0,rv.H)("BABYLON.SetUVsBlock",SetUVsBlock);let SetColorsBlock=class SetColorsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("colors",iX.Vector4),this.registerOutput("output",iX.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetColorsBlock"}get geometry(){return this._inputs[0]}get colors(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.colors.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.colors||(this._vertexData.colors=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.colors.getConnectedValue(e);t&&t.toArray(this._vertexData.colors,4*this._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetColorsBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.SetColorsBlock",SetColorsBlock);let SetTangentsBlock=class SetTangentsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("tangents",iX.Vector4),this.registerOutput("output",iX.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetTangentsBlock"}get geometry(){return this._inputs[0]}get tangents(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.tangents.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.tangents||(this._vertexData.tangents=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.tangents.getConnectedValue(e);t&&t.toArray(this._vertexData.tangents,4*this._currentIndex)}return e.restoreGeometryContext(),e.restoreExecutionContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetTangentsBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.SetTangentsBlock",SetTangentsBlock),(eK=iK||(iK={}))[eK.Add=0]="Add",eK[eK.Subtract=1]="Subtract",eK[eK.Multiply=2]="Multiply",eK[eK.Divide=3]="Divide",eK[eK.Max=4]="Max",eK[eK.Min=5]="Min";let MathBlock=class MathBlock extends NodeGeometryBlock{constructor(e){super(e),this.operation=iK.Add,this.registerInput("left",iX.AutoDetect),this.registerInput("right",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture),this._inputs[1].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[1].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[1].excludedConnectionPointTypes.push(iX.Texture),this._inputs[1].acceptedConnectionPointTypes.push(iX.Float),this._linkConnectionTypes(0,1)}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;let t=this.left,i=this.right;if(!t.isConnected||!i.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let r=t.type===iX.Float||t.type===iX.Int;switch(this.operation){case iK.Add:e=r?e=>t.getConnectedValue(e)+i.getConnectedValue(e):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case iK.Subtract:e=r?e=>t.getConnectedValue(e)-i.getConnectedValue(e):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case iK.Multiply:e=r?e=>t.getConnectedValue(e)*i.getConnectedValue(e):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case iK.Divide:e=r?e=>t.getConnectedValue(e)/i.getConnectedValue(e):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case iK.Min:if(r)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case iX.Vector2:e=e=>rm.FM.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iX.Vector3:e=e=>rm.P.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iX.Vector4:e=e=>rm.Lt.Minimize(t.getConnectedValue(e),e.adapt(i,t.type))}break;case iK.Max:if(r)e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case iX.Vector2:e=e=>rm.FM.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iX.Vector3:e=e=>rm.P.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iX.Vector4:e=e=>rm.Lt.Maximize(t.getConnectedValue(e),e.adapt(i,t.type))}}this.output._storedFunction=i=>t.type===iX.Int?0|e(i):e(i)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${iK[this.operation]}; +`;return e}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}};(0,rH.gn)([editableInPropertyPage("Operation",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:iK.Add},{label:"Subtract",value:iK.Subtract},{label:"Multiply",value:iK.Multiply},{label:"Divide",value:iK.Divide},{label:"Max",value:iK.Max},{label:"Min",value:iK.Min}]})],MathBlock.prototype,"operation",void 0),(0,rv.H)("BABYLON.MathBlock",MathBlock);let MapRangeBlock=class MapRangeBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("value",iX.AutoDetect),this.registerInput("fromMin",iX.Float,!0,0),this.registerInput("fromMax",iX.Float,!0,1),this.registerInput("toMin",iX.Float,!0,0),this.registerInput("toMax",iX.Float,!0,1),this.registerOutput("output",iX.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iX.Vector2),this._inputs[0].excludedConnectionPointTypes.push(iX.Vector3),this._inputs[0].excludedConnectionPointTypes.push(iX.Vector4),this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.output._storedFunction=e=>{let t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),n=this.toMax.getConnectedValue(e),a=(t-i)/(r-i)*(n-s)+s;return this.output.type===iX.Int?Math.floor(a):a}}};(0,rv.H)("BABYLON.MapRangeBlock",MapRangeBlock),(e$=i$||(i$={}))[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";let ConditionBlock=class ConditionBlock extends NodeGeometryBlock{constructor(e){super(e),this.test=i$.Equal,this.registerInput("left",iX.Float),this.registerInput("right",iX.Float,!0,0),this.registerInput("ifTrue",iX.AutoDetect,!0,1),this.registerInput("ifFalse",iX.AutoDetect,!0,0),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=iX.Float,this._inputs[0].acceptedConnectionPointTypes.push(iX.Int),this._inputs[1].acceptedConnectionPointTypes.push(iX.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e),r=!1;switch(this.test){case i$.Equal:r=rE.R.WithinEpsilon(t,i,rw.kn);break;case i$.NotEqual:r=t!==i;break;case i$.LessThan:r=t<i;break;case i$.GreaterThan:r=t>i;break;case i$.LessOrEqual:r=t<=i;break;case i$.GreaterOrEqual:r=t>=i;break;case i$.Xor:r=!!t&&!i||!t&&!!i;break;case i$.Or:r=!!t||!!i;break;case i$.And:r=!!t&&!!i}return r};this.output._storedFunction=e=>func(e)?this.ifTrue.getConnectedValue(e):this.ifFalse.getConnectedValue(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${i$[this.test]}; +`;return e}serialize(){let e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}};(0,rH.gn)([editableInPropertyPage("Test",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:i$.Equal},{label:"NotEqual",value:i$.NotEqual},{label:"LessThan",value:i$.LessThan},{label:"GreaterThan",value:i$.GreaterThan},{label:"LessOrEqual",value:i$.LessOrEqual},{label:"GreaterOrEqual",value:i$.GreaterOrEqual},{label:"Xor",value:i$.Xor},{label:"Or",value:i$.Or},{label:"And",value:i$.And}]})],ConditionBlock.prototype,"test",void 0),(0,rv.H)("BABYLON.ConditionBlock",ConditionBlock),(eQ=iQ||(iQ={}))[eQ.None=0]="None",eQ[eQ.LoopID=1]="LoopID",eQ[eQ.InstanceID=2]="InstanceID";let RandomBlock=class RandomBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentLockId=-1,this.lockMode=iQ.None,this.registerInput("min",iX.AutoDetect),this.registerInput("max",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture),this._inputs[1].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[1].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[1].excludedConnectionPointTypes.push(iX.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){let e=new GeometryInputBlock("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){let e=new GeometryInputBlock("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case iX.Int:case iX.Float:e=e=>{let t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case iX.Vector2:e=e=>{let t=this.min.getConnectedValue(e)||rm.FM.Zero(),i=this.max.getConnectedValue(e)||rm.FM.Zero();return new rm.FM(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case iX.Vector3:e=e=>{let t=this.min.getConnectedValue(e)||rm.P.Zero(),i=this.max.getConnectedValue(e)||rm.P.Zero();return new rm.P(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case iX.Vector4:e=e=>{let t=this.min.getConnectedValue(e)||rm.Lt.Zero(),i=this.max.getConnectedValue(e)||rm.Lt.Zero();return new rm.Lt(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==iQ.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case iQ.InstanceID:i=t.getContextualValue(iq.InstanceID,!0)||0;break;case iQ.LoopID:i=t.getContextualValue(iq.LoopID,!0)||0}return this._currentLockId!==i&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${iQ[this.lockMode]}; +`;return e}serialize(){let e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}};(0,rH.gn)([editableInPropertyPage("LockMode",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:iQ.None},{label:"LoopID",value:iQ.LoopID},{label:"InstanceID",value:iQ.InstanceID}]})],RandomBlock.prototype,"lockMode",void 0),(0,rv.H)("BABYLON.RandomBlock",RandomBlock);let NoiseBlock=class NoiseBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("offset",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scale",iX.Float,!0,1),this.registerInput("octaves",iX.Float,!0,2,0,16),this.registerInput("roughness",iX.Float,!0,.5,0,1),this.registerOutput("output",iX.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,r){let s=15&e,n=s<8?t:i,a=12===s||14==s?t:r,o=s<4?i:a;return this._negateIf(n,s&n)+this._negateIf(o,2&s)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<<t|e>>32-t}_hash(e,t,i){let r,s,n;return r=s=n=3735928584,n+=i,s+=t,r+=e,n^=s,n-=this._hashBitRotate(s,14),r^=n,r-=this._hashBitRotate(n,11),s^=r,s-=this._hashBitRotate(r,25),n^=s,n-=this._hashBitRotate(s,16),r^=n,r-=this._hashBitRotate(n,4),s^=r,s-=this._hashBitRotate(r,14),n^=s,n-=this._hashBitRotate(s,24)}_mix(e,t,i,r,s,n,a,o,l,h,u){let c=1-l,d=1-h;return(1-u)*(d*(e*c+t*l)+h*(i*c+r*l))+u*(d*(s*c+n*l)+h*(a*c+o*l))}_perlinNoise(e){let t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),r=(0|e.z)-(e.z<0?1:0),s=e.x-t,n=e.y-i,a=e.z-r,o=this._fade(s),l=this._fade(n),h=this._fade(a);return this._mix(this._noiseGrad(this._hash(t,i,r),s,n,a),this._noiseGrad(this._hash(t+1,i,r),s-1,n,a),this._noiseGrad(this._hash(t,i+1,r),s,n-1,a),this._noiseGrad(this._hash(t+1,i+1,r),s-1,n-1,a),this._noiseGrad(this._hash(t,i,r+1),s,n,a-1),this._noiseGrad(this._hash(t+1,i,r+1),s-1,n,a-1),this._noiseGrad(this._hash(t,i+1,r+1),s,n-1,a-1),this._noiseGrad(this._hash(t+1,i+1,r+1),s-1,n-1,a-1),o,l,h)}_perlinSigned(e){return .982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,s){let n=new rm.P(i.x*s+r.x,i.y*s+r.y,i.z*s+r.z),a=1,o=1,l=0,h=0;e=rE.R.Clamp(e,0,15);let u=0|e;for(let e=0;e<=u;e++){let e=this._perlin(n.scale(a));h+=e*o,l+=o,o*=rE.R.Clamp(t,0,1),a*=2}let c=e-Math.floor(e);if(0==c)return h/l;let d=this._perlin(n.scale(a)),p=h+d*o;return(1-c)*(h/=l)+c*(p/=l+o)}_buildBlock(){this.output._storedFunction=e=>{let t=e.getContextualValue(iq.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,r,t,s,n)}}};(0,rv.H)("BABYLON.NoiseBlock",NoiseBlock);let MergeGeometryBlock=class MergeGeometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",iX.Geometry),this.registerInput("geometry1",iX.Geometry,!0),this.registerInput("geometry2",iX.Geometry,!0),this.registerInput("geometry3",iX.Geometry,!0),this.registerInput("geometry4",iX.Geometry,!0),this.registerOutput("output",iX.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{let t=this.geometry0.getConnectedValue(e),i=[];if(this.geometry1.isConnected){let t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){let t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){let t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){let t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],MergeGeometryBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.MergeGeometryBlock",MergeGeometryBlock);let GeometryCollectionBlock=class GeometryCollectionBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",iX.Geometry,!0),this.registerInput("geometry1",iX.Geometry,!0),this.registerInput("geometry2",iX.Geometry,!0),this.registerInput("geometry3",iX.Geometry,!0),this.registerInput("geometry4",iX.Geometry,!0),this.registerInput("geometry5",iX.Geometry,!0),this.registerInput("geometry6",iX.Geometry,!0),this.registerInput("geometry7",iX.Geometry,!0),this.registerInput("geometry8",iX.Geometry,!0),this.registerInput("geometry9",iX.Geometry,!0),this.registerOutput("output",iX.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){let s=e.getConnectedValue(t);s&&(s.metadata=s.metadata||{},s.metadata.collectionId=i,r.push(s))}}_buildBlock(e){let func=e=>{let t=[];return(this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length)?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryCollectionBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.GeometryCollectionBlock",GeometryCollectionBlock);let GeometryElbowBlock=class GeometryElbowBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("input",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}};(0,rv.H)("BABYLON.GeometryElbowBlock",GeometryElbowBlock);let ComputeNormalsBlock=class ComputeNormalsBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",iX.Geometry),this.registerOutput("output",iX.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),se.x.ComputeNormals(t.positions,t.indices,t.normals),t}}};(0,rv.H)("BABYLON.ComputeNormalsBlock",ComputeNormalsBlock);let VectorConverterBlock=class VectorConverterBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("xyzw ",iX.Vector4,!0),this.registerInput("xyz ",iX.Vector3,!0),this.registerInput("xy ",iX.Vector2,!0),this.registerInput("zw ",iX.Vector2,!0),this.registerInput("x ",iX.Float,!0),this.registerInput("y ",iX.Float,!0),this.registerInput("z ",iX.Float,!0),this.registerInput("w ",iX.Float,!0),this.registerOutput("xyzw",iX.Vector4),this.registerOutput("xyz",iX.Vector3),this.registerOutput("xy",iX.Vector2),this.registerOutput("zw",iX.Vector2),this.registerOutput("x",iX.Float),this.registerOutput("y",iX.Float),this.registerOutput("z",iX.Float),this.registerOutput("w",iX.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);let t=this.xIn,i=this.yIn,r=this.zIn,s=this.wIn,n=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,u=this.xyzOut,c=this.xyOut,d=this.zwOut,p=this.xOut,_=this.yOut,f=this.zOut,m=this.wOut,getData=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,u=0,c=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(u=i.getConnectedValue(e)),r.isConnected&&(c=r.getConnectedValue(e)),s.isConnected&&(d=s.getConnectedValue(e)),n.isConnected){let t=n.getConnectedValue(e);t&&(h=t.x,u=t.y)}if(a.isConnected){let t=a.getConnectedValue(e);t&&(c=t.x,d=t.y)}if(o.isConnected){let t=o.getConnectedValue(e);t&&(h=t.x,u=t.y,c=t.z)}return new rm.Lt(h,u,c,d)};h._storedFunction=e=>getData(e),u._storedFunction=e=>{let t=getData(e);return new rm.P(t.x,t.y,t.z)},c._storedFunction=e=>{let t=getData(e);return new rm.FM(t.x,t.y)},d._storedFunction=e=>{let t=getData(e);return new rm.FM(t.z,t.w)},p._storedFunction=e=>getData(e).x,_._storedFunction=e=>getData(e).y,f._storedFunction=e=>getData(e).z,m._storedFunction=e=>getData(e).w}};(0,rv.H)("BABYLON.VectorConverterBlock",VectorConverterBlock);let NormalizeVectorBlock=class NormalizeVectorBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("input",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iX.Float),this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),this.output._storedFunction=null,!this.input.isConnected){this.output._storedValue=null;return}this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize()}};(0,rv.H)("BABYLON.NormalizeVectorBlock",NormalizeVectorBlock);let SetMaterialIDBlock=class SetMaterialIDBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("id",iX.Int,!0,0),this.registerOutput("output",iX.Geometry),this.id.acceptedConnectionPointTypes.push(iX.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;let i=new se.D;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetMaterialIDBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.SetMaterialIDBlock",SetMaterialIDBlock),(eZ=iZ||(iZ={}))[eZ.Cos=0]="Cos",eZ[eZ.Sin=1]="Sin",eZ[eZ.Abs=2]="Abs",eZ[eZ.Exp=3]="Exp",eZ[eZ.Round=4]="Round",eZ[eZ.Floor=5]="Floor",eZ[eZ.Ceiling=6]="Ceiling",eZ[eZ.Sqrt=7]="Sqrt",eZ[eZ.Log=8]="Log",eZ[eZ.Tan=9]="Tan",eZ[eZ.ArcTan=10]="ArcTan",eZ[eZ.ArcCos=11]="ArcCos",eZ[eZ.ArcSin=12]="ArcSin",eZ[eZ.Sign=13]="Sign",eZ[eZ.Negate=14]="Negate",eZ[eZ.OneMinus=15]="OneMinus",eZ[eZ.Reciprocal=16]="Reciprocal",eZ[eZ.ToDegrees=17]="ToDegrees",eZ[eZ.ToRadians=18]="ToRadians";let GeometryTrigonometryBlock=class GeometryTrigonometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.operation=iZ.Cos,this.registerInput("input",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case iZ.Cos:t=e=>Math.cos(e);break;case iZ.Sin:t=e=>Math.sin(e);break;case iZ.Abs:t=e=>Math.abs(e);break;case iZ.Exp:t=e=>Math.exp(e);break;case iZ.Round:t=e=>Math.round(e);break;case iZ.Floor:t=e=>Math.floor(e);break;case iZ.Ceiling:t=e=>Math.ceil(e);break;case iZ.Sqrt:t=e=>Math.sqrt(e);break;case iZ.Log:t=e=>Math.log(e);break;case iZ.Tan:t=e=>Math.tan(e);break;case iZ.ArcTan:t=e=>Math.atan(e);break;case iZ.ArcCos:t=e=>Math.acos(e);break;case iZ.ArcSin:t=e=>Math.asin(e);break;case iZ.Sign:t=e=>Math.sign(e);break;case iZ.Negate:t=e=>-e;break;case iZ.OneMinus:t=e=>1-e;break;case iZ.Reciprocal:t=e=>1/e;break;case iZ.ToRadians:t=e=>e*Math.PI/180;break;case iZ.ToDegrees:t=e=>180*e/Math.PI}if(!t){this.input._storedFunction=null,this.input._storedValue=null;return}switch(this.input.type){case iX.Int:case iX.Float:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return t(i)};break;case iX.Vector2:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rm.FM(t(i.x),t(i.y))};break;case iX.Vector3:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rm.P(t(i.x),t(i.y),t(i.z))};break;case iX.Vector4:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rm.Lt(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${iZ[this.operation]}; +`;return e}};(0,rH.gn)([editableInPropertyPage("Operation",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:iZ.Cos},{label:"Sin",value:iZ.Sin},{label:"Abs",value:iZ.Abs},{label:"Exp",value:iZ.Exp},{label:"Round",value:iZ.Round},{label:"Floor",value:iZ.Floor},{label:"Ceiling",value:iZ.Ceiling},{label:"Sqrt",value:iZ.Sqrt},{label:"Log",value:iZ.Log},{label:"Tan",value:iZ.Tan},{label:"ArcTan",value:iZ.ArcTan},{label:"ArcCos",value:iZ.ArcCos},{label:"ArcSin",value:iZ.ArcSin},{label:"Sign",value:iZ.Sign},{label:"Negate",value:iZ.Negate},{label:"OneMinus",value:iZ.OneMinus},{label:"Reciprocal",value:iZ.Reciprocal},{label:"ToDegrees",value:iZ.ToDegrees},{label:"ToRadians",value:iZ.ToRadians}]})],GeometryTrigonometryBlock.prototype,"operation",void 0),(0,rv.H)("BABYLON.GeometryTrigonometryBlock",GeometryTrigonometryBlock);let GeometryTransformBlock=class GeometryTransformBlock extends NodeGeometryBlock{constructor(e){super(e),this._rotationMatrix=new rm.y3,this._scalingMatrix=new rm.y3,this._translationMatrix=new rm.y3,this._scalingRotationMatrix=new rm.y3,this._transformMatrix=new rm.y3,this.evaluateContext=!0,this.registerInput("value",iX.AutoDetect),this.registerInput("matrix",iX.Matrix,!0),this.registerInput("translation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("rotation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scaling",iX.Vector3,!0,rm.P.One()),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iX.Float),this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t;let i=this.value.getConnectedValue(e);if(!i)return null;if(this.matrix.isConnected)t=this.matrix.getConnectedValue(e);else{let i=this.scaling.getConnectedValue(e),r=this.rotation.getConnectedValue(e),s=this.translation.getConnectedValue(e);rm.y3.ScalingToRef(i.x,i.y,i.z,this._scalingMatrix),rm.y3.RotationYawPitchRollToRef(r.y,r.x,r.z,this._rotationMatrix),rm.y3.TranslationToRef(s.x,s.y,s.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),t=this._transformMatrix}switch(this.value.type){case iX.Geometry:{let e=i.clone();return e.transform(t),e}case iX.Vector2:return rm.FM.Transform(i,t);case iX.Vector3:return rm.P.TransformCoordinates(i,t);case iX.Vector4:return rm.Lt.TransformCoordinates(i,t)}return null};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryTransformBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.GeometryTransformBlock",GeometryTransformBlock);let RotationXBlock=class RotationXBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",iX.Float,!1,0),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rm.y3.RotationX(this.angle.getConnectedValue(e))}};(0,rv.H)("BABYLON.RotationXBlock",RotationXBlock);let RotationYBlock=class RotationYBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",iX.Float,!1,0),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rm.y3.RotationY(this.angle.getConnectedValue(e))}};(0,rv.H)("BABYLON.RotationYBlock",RotationYBlock);let RotationZBlock=class RotationZBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",iX.Float,!1,0),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rm.y3.RotationZ(this.angle.getConnectedValue(e))}};(0,rv.H)("BABYLON.RotationZBlock",RotationZBlock);let ScalingBlock=class ScalingBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("scale",iX.Vector3,!1,rm.P.One()),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){let e=new GeometryInputBlock("Scale");e.value=new rm.P(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.scale.getConnectedValue(e);return rm.y3.Scaling(t.x,t.y,t.z)}}};(0,rv.H)("BABYLON.ScalingBlock",ScalingBlock);let AlignBlock=class AlignBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("source",iX.Vector3,!0,rm.P.Up()),this.registerInput("target",iX.Vector3,!0,rm.P.Left()),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),r=new rm.y3;return t.normalize(),i.normalize(),rm.y3.RotationAlignToRef(t,i,r,!0),r}}};(0,rv.H)("BABYLON.AlignBlock",AlignBlock);let TranslationBlock=class TranslationBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("translation",iX.Vector3,!1,rm.P.Zero()),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){let e=new GeometryInputBlock("Translation");e.value=new rm.P(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.translation.getConnectedValue(e);return rm.y3.Translation(t.x,t.y,t.z)}}};(0,rv.H)("BABYLON.TranslationBlock",TranslationBlock);let InstantiateOnVerticesBlock=class InstantiateOnVerticesBlock extends NodeGeometryBlock{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("instance",iX.Geometry,!0),this.registerInput("density",iX.Float,!0,1,0,1),this.registerInput("matrix",iX.Matrix,!0),this.registerInput("rotation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scaling",iX.Vector3,!0,rm.P.One()),this.scaling.acceptedConnectionPointTypes.push(iX.Float),this.registerOutput("output",iX.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3,i=[],r=new rm.P,s=[],n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let e=n[3*this._currentIndex],t=n[3*this._currentIndex+1],i=n[3*this._currentIndex+2],r=!1;for(let n=0;n<s.length;n+=3)if(Math.abs(s[n]-e)<rw.kn&&Math.abs(s[n+1]-t)<rw.kn&&Math.abs(s[n+2]-i)<rw.kn){r=!0;break}r||(this._indexTranslation[s.length/3]=this._currentIndex,s.push(e,t,i))}t=(n=s).length/3}else this._indexTranslation=null;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.instance.getConnectedValue(e);if(!t||!t.positions||0===t.positions.length)continue;let s=this.density.getConnectedValue(e);if(s<1&&Math.random()>s)continue;r.fromArray(n,3*this._currentIndex);let a=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(a,r,t,i)}else{let t=e.adaptInput(this.scaling,iX.Vector3,rm.P.OneReadOnly),s=this.rotation.getConnectedValue(e)||rm.P.ZeroReadOnly;e._instantiate(a,r,s,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"}; +`+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnVerticesBlock.prototype,"evaluateContext",void 0),(0,rH.gn)([editableInPropertyPage("Remove duplicated positions",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],InstantiateOnVerticesBlock.prototype,"removeDuplicatedPositions",void 0),(0,rv.H)("BABYLON.InstantiateOnVerticesBlock",InstantiateOnVerticesBlock);let InstantiateOnFacesBlock=class InstantiateOnFacesBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentPosition=new rm.P,this._currentUV=new rm.FM,this._vertex0=new rm.P,this._vertex1=new rm.P,this._vertex2=new rm.P,this._tempVector0=new rm.P,this._tempVector1=new rm.P,this._uv0=new rm.FM,this._uv1=new rm.FM,this._uv2=new rm.FM,this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("instance",iX.Geometry,!0),this.registerInput("count",iX.Int,!0,256),this.registerInput("matrix",iX.Matrix,!0),this.registerInput("rotation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scaling",iX.Vector3,!0,rm.P.One()),this.scaling.acceptedConnectionPointTypes.push(iX.Float),this.registerOutput("output",iX.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),rm.P.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=this._vertexData.indices.length/3,s=i/r,n=0,a=[],o=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex<r;this._currentFaceIndex++){n+=s;let r=(0|n)-o;if(r<1)continue;let l=this._vertexData.indices[3*this._currentFaceIndex],h=this._vertexData.indices[3*this._currentFaceIndex+1],u=this._vertexData.indices[3*this._currentFaceIndex+2];this._vertex0.fromArray(this._vertexData.positions,3*l),this._vertex1.fromArray(this._vertexData.positions,3*h),this._vertex2.fromArray(this._vertexData.positions,3*u),this._vertexData.uvs&&(this._uv0.fromArray(this._vertexData.uvs,2*l),this._uv1.fromArray(this._vertexData.uvs,2*h),this._uv2.fromArray(this._vertexData.uvs,2*u));for(let l=0;l<r&&!(o>=i);l++){let i=Math.random(),r=Math.random();if(i>r){let e=i;i=r,r=e}let l=i,h=r-i,u=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+u*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+u*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+u*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+u*this._uv2.x,l*this._uv0.y+h*this._uv1.y+u*this._uv2.y),!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length){n-=s;continue}let c=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,a)}else{let t=e.adaptInput(this.scaling,iX.Vector3,rm.P.OneReadOnly),i=this.rotation.getConnectedValue(e)||rm.P.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,a)}o++,this._currentLoopIndex++}}if(a.length){if(1===a.length)this._vertexData=a[0];else{let e=a.splice(0,1)[0];this._vertexData=e.merge(a,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnFacesBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.InstantiateOnFacesBlock",InstantiateOnFacesBlock);let InstantiateOnVolumeBlock=class InstantiateOnVolumeBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentPosition=new rm.P,this._vertex0=new rm.P,this._vertex1=new rm.P,this._vertex2=new rm.P,this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("instance",iX.Geometry,!0),this.registerInput("count",iX.Int,!0,256),this.registerInput("matrix",iX.Matrix,!0),this.registerInput("rotation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scaling",iX.Vector3,!0,rm.P.One()),this.scaling.acceptedConnectionPointTypes.push(iX.Float),this.registerOutput("output",iX.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=[],s=(0,lW.k)(this._vertexData.positions,0,this._vertexData.positions.length/3),n=s.minimum,a=s.maximum,o=new rm.P(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let s=0;s<i;s++){this._currentPosition.set(Math.random()*(a.x-n.x)+n.x,Math.random()*(a.y-n.y)+n.y,Math.random()*(a.z-n.z)+n.z);let i=new ray_Ray(this._currentPosition,o),h=0;for(let e=0;e<l;e++){this._vertex0.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*e]),this._vertex1.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*e+1]),this._vertex2.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*e+2]);let t=i.intersectsTriangle(this._vertex0,this._vertex1,this._vertex2);t&&t.distance>0&&h++}if(h%2==0){s--;continue}if(!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length)continue;let u=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,r)}else{let t=e.adaptInput(this.scaling,iX.Vector3,rm.P.OneReadOnly),i=this.rotation.getConnectedValue(e)||rm.P.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,r)}this._currentLoopIndex++}if(r.length){if(1===r.length)this._vertexData=r[0];else{let e=r.splice(0,1)[0];this._vertexData=e.merge(r,!0,!1,!0,!0)}}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnVolumeBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.InstantiateOnVolumeBlock",InstantiateOnVolumeBlock);let InstantiateBaseBlock=class InstantiateBaseBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",iX.Geometry,!0),this.registerInput("count",iX.Int,!0,1),this.registerOutput("output",iX.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateBaseBlock.prototype,"evaluateContext",void 0);let InstantiateBlock=class InstantiateBlock extends InstantiateBaseBlock{constructor(e){super(e),this.registerInput("matrix",iX.Matrix,!0),this.registerInput("position",iX.Vector3,!0,rm.P.Zero()),this.registerInput("rotation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scaling",iX.Vector3,!0,rm.P.One()),this.scaling.acceptedConnectionPointTypes.push(iX.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){let func=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.instance.getConnectedValue(e);if(!t||!t.positions||0===t.positions.length)continue;let r=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithMatrix(r,t,i)}else{let t=this.position.getConnectedValue(e)||rm.P.ZeroReadOnly,s=e.adaptInput(this.scaling,iX.Vector3,rm.P.OneReadOnly),n=this.rotation.getConnectedValue(e)||rm.P.ZeroReadOnly;e._instantiate(r,t,n,s,i)}}if(i.length){if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}};(0,rv.H)("BABYLON.InstantiateBlock",InstantiateBlock);let InstantiateLinearBlock=class InstantiateLinearBlock extends InstantiateBaseBlock{constructor(e){super(e),this.registerInput("direction",iX.Vector3,!0,new rm.P(1,0,0)),this.registerInput("rotation",iX.Vector3,!0,new rm.P(0,0,0)),this.registerInput("scaling",iX.Vector3,!0,new rm.P(0,0,0)),this.scaling.acceptedConnectionPointTypes.push(iX.Float)}getClassName(){return"InstantiateLinearBlock"}get direction(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}_buildBlock(e){let func=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=rm.y3.Identity(),s=rm.P.Zero(),n=rm.P.Zero(),a=rm.P.Zero();for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.instance.getConnectedValue(e);if(!t||!t.positions||0===t.positions.length)continue;let o=t.clone(),l=this.direction.getConnectedValue(e),h=this.rotation.getConnectedValue(e),u=e.adaptInput(this.scaling,iX.Vector3,rm.P.OneReadOnly);s.copyFrom(l.clone().scale(this._currentIndex)),n.copyFrom(h.clone().scale(this._currentIndex)),a.copyFrom(u.clone().scale(this._currentIndex)),a.addInPlaceFromFloats(1,1,1),rm.y3.ComposeToRef(a,rm._f.FromEulerAngles(n.x,n.y,n.z),s,r),e._instantiateWithMatrix(o,r,i)}if(i.length){if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}};(0,rv.H)("BABYLON.InstantiateLinearBlock",InstantiateLinearBlock);let InstantiateRadialBlock=class InstantiateRadialBlock extends InstantiateBaseBlock{constructor(e){super(e),this.registerInput("radius",iX.Int,!0,0,0),this.registerInput("angleStart",iX.Float,!0,0),this.registerInput("angleEnd",iX.Float,!0,2*Math.PI),this.registerInput("transform",iX.Vector3,!0,new rm.P(0,0,0)),this.registerInput("rotation",iX.Vector3,!0,new rm.P(0,0,0)),this.registerInput("scaling",iX.Vector3,!0,new rm.P(0,0,0)),this.scaling.acceptedConnectionPointTypes.push(iX.Float)}getClassName(){return"InstantiateRadialBlock"}get radius(){return this._inputs[2]}get angleStart(){return this._inputs[3]}get angleEnd(){return this._inputs[4]}get transform(){return this._inputs[5]}get rotation(){return this._inputs[6]}get scaling(){return this._inputs[7]}_buildBlock(e){let func=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=rm.y3.Identity(),s=rm.y3.Identity(),n=rm.y3.Identity(),a=rm.P.Zero(),o=rm.P.Zero(),l=rm.P.Zero();for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let h=this.instance.getConnectedValue(e);if(!h||!h.positions||0===h.positions.length)continue;let u=h.clone(),c=this.radius.getConnectedValue(e),d=this.angleStart.getConnectedValue(e),p=this.angleEnd.getConnectedValue(e),_=this.transform.getConnectedValue(e),f=this.rotation.getConnectedValue(e),m=e.adaptInput(this.scaling,iX.Vector3,rm.P.OneReadOnly),g=p-d,v=g/t,x=d+v*this._currentIndex,T=rm._f.FromEulerAngles(0,x,0);a.copyFrom(_.clone().scale(this._currentIndex)),o.copyFrom(f.clone().scale(this._currentIndex)),l.copyFrom(m.clone().scale(this._currentIndex)),l.addInPlaceFromFloats(1,1,1),rm.y3.RotationYawPitchRollToRef(o.y,o.x,o.z,r),s.setTranslationFromFloats(0,0,c),rm.y3.ComposeToRef(l,T,a,n),r.multiplyToRef(s,s),s.multiplyToRef(n,n),e._instantiateWithMatrix(u,n,i)}if(i.length){if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}};(0,rv.H)("BABYLON.InstantiateRadialBlock",InstantiateRadialBlock);let IntFloatConverterBlock=class IntFloatConverterBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("float ",iX.Float,!0),this.registerInput("int ",iX.Int,!0),this.registerOutput("float",iX.Float),this.registerOutput("int",iX.Int)}getClassName(){return"IntFloatConverterBlock"}get floatIn(){return this._inputs[0]}get intIn(){return this._inputs[1]}get floatOut(){return this._outputs[0]}get intOut(){return this._outputs[1]}_inputRename(e){return"float "===e?"floatIn":"int "===e?"intIn":e}_buildBlock(){this.floatOut._storedFunction=e=>this.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}};(0,rv.H)("BABYLON.IntFloatConverterBlock",IntFloatConverterBlock);let DebugBlock=class DebugBlock extends NodeGeometryBlock{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.log=[];let func=e=>{let t=this.input.getConnectedValue(e);return null==t?this.log.push("null"):this.log.push(t.toString()),t};this.output.isConnected?this.output._storedFunction=func:this.output._storedValue=func(e)}};(0,rv.H)("BABYLON.DebugBlock",DebugBlock);let GeometryInfoBlock=class GeometryInfoBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",iX.Geometry),this.registerOutput("output",iX.Geometry),this.registerOutput("id",iX.Int),this.registerOutput("collectionId",iX.Int),this.registerOutput("verticesCount",iX.Int),this.registerOutput("facesCount",iX.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected){this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,this.output._storedFunction=null;return}this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}};(0,rv.H)("BABYLON.GeometryInfoBlock",GeometryInfoBlock),(eJ=iJ||(iJ={}))[eJ.Spherical=0]="Spherical",eJ[eJ.Cylindrical=1]="Cylindrical",eJ[eJ.Cubic=2]="Cubic";let MappingBlock=class MappingBlock extends NodeGeometryBlock{constructor(e){super(e),this.mapping=iJ.Spherical,this.registerInput("position",iX.Vector3),this.registerInput("normal",iX.Vector3),this.registerInput("center",iX.Vector3,!0,rm.P.Zero()),this.registerOutput("uv",iX.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected){this.uv._storedFunction=null,this.uv._storedValue=null;return}let e=rm.P.Zero(),func=t=>{let i=this.position.getConnectedValue(t)||rm.P.Zero(),r=this.normal.getConnectedValue(t)||rm.P.Zero(),s=this.center.getConnectedValue(t),n=rm.FM.Zero();switch(this.mapping){case iJ.Spherical:{i.subtractToRef(s,e);let t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,(0!==e.x||0!==e.z)&&(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case iJ.Cylindrical:{i.subtractToRef(s,e);let t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case iJ.Cubic:{let e=Math.abs(r.x),t=Math.abs(r.y),a=Math.abs(r.z),o=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),l=0,h=0;e>=t&&e>=a?(l=i.y/o-s.y,h=i.z/o-s.z):t>=e&&t>=a?(l=i.x/o-s.x,h=i.z/o-s.z):(l=i.x/o-s.x,h=i.y/o-s.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>func(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${iJ[this.mapping]}; +`;return e}serialize(){let e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}};(0,rH.gn)([editableInPropertyPage("Mapping",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:iJ.Spherical},{label:"Cylindrical",value:iJ.Cylindrical},{label:"Cubic",value:iJ.Cubic}]})],MappingBlock.prototype,"mapping",void 0),(0,rv.H)("BABYLON.MappingBlock",MappingBlock);let MatrixComposeBlock=class MatrixComposeBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("matrix0",iX.Matrix),this.registerInput("matrix1",iX.Matrix),this.registerOutput("output",iX.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;let t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}};(0,rv.H)("BABYLON.MatrixComposeBlock",MatrixComposeBlock);let TeleportInBlock=class TeleportInBlock extends NodeGeometryBlock{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",iX.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(let t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(let t of this.endpoints){let i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(let e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}};(0,rv.H)("BABYLON.TeleportInBlock",TeleportInBlock);let TeleportOutBlock=class TeleportOutBlock extends NodeGeometryBlock{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",iX.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){let e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); +`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}};(0,rv.H)("BABYLON.TeleportOutBlock",TeleportOutBlock);let GeometryTextureBlock=class GeometryTextureBlock extends NodeGeometryBlock{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",iX.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{let r=new Image,s=document.createElement("canvas"),n=s.getContext("2d");r.onload=()=>{s.width=r.width,s.height=r.height,n.drawImage(r,0,0);let e=n.getImageData(0,0,r.width,r.height),i=e.data,a=new Float32Array(i.length);for(let e=0;e<i.length;e++)a[e]=i[e]/255;this._data=a,this._width=r.width,this._height=r.height,t()},r.onerror=()=>{this._data=null,i()},r.src=e})}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise((t,i)=>{if(!e.isReady()){e.onLoadObservable.addOnce(()=>this.extractFromTextureAsync(e).then(t).catch(i));return}let r=e.getSize();aa.GetTextureDataAsync(e,r.width,r.height).then(async e=>{let i=new Float32Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/255;this._data=i,this._width=r.width,this._height=r.height,t()}).catch(i)})}_buildBlock(){if(!this._data){this.texture._storedValue=null;return}let e={data:this._data,width:this._width,height:this._height};this.texture._storedValue=e}serialize(){let e=super.serialize();return e.width=this._width,e.height=this._height,e.serializedCachedData=this.serializedCachedData,this._data&&this.serializedCachedData&&(e.data=Array.from(this._data)),e}_deserialize(e){super._deserialize(e),this._width=e.width,this._height=e.height,e.data?(this._data=new Float32Array(e.data),this.serializedCachedData=!0):this.serializedCachedData=!!e.serializedCachedData}};(0,rH.gn)([editableInPropertyPage("Serialize cached data",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryTextureBlock.prototype,"serializedCachedData",void 0),(0,rv.H)("BABYLON.GeometryTextureBlock",GeometryTextureBlock);let GeometryTextureFetchBlock=class GeometryTextureFetchBlock extends NodeGeometryBlock{constructor(e){super(e),this.clampCoordinates=!0,this.registerInput("texture",iX.Texture),this.registerInput("coordinates",iX.Vector2),this.registerOutput("rgba",iX.Vector4),this.registerOutput("rgb",iX.Vector3),this.registerOutput("r",iX.Float),this.registerOutput("g",iX.Float),this.registerOutput("b",iX.Float),this.registerOutput("a",iX.Float)}getClassName(){return"GeometryTextureFetchBlock"}get texture(){return this.inputs[0]}get coordinates(){return this.inputs[1]}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]}_repeatClamp(e){return e>=0?e%1:1-Math.abs(e)%1}_buildBlock(){let func=e=>{let t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;let i=this.coordinates.getConnectedValue(e);if(!i)return null;let r=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),s=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(r*(t.width-1)),a=Math.floor(s*(t.height-1)),o=n+t.width*a;return rm.Lt.FromArray(t.data,4*o)};this.rgba._storedFunction=e=>func(e),this.rgb._storedFunction=e=>{let t=func(e);return t?t.toVector3():null},this.r._storedFunction=e=>{let t=func(e);return t?t.x:null},this.g._storedFunction=e=>{let t=func(e);return t?t.y:null},this.b._storedFunction=e=>{let t=func(e);return t?t.z:null},this.a._storedFunction=e=>{let t=func(e);return t?t.w:null}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates}; +`;return e}serialize(){let e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}};(0,rH.gn)([editableInPropertyPage("Clamp Coordinates",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryTextureFetchBlock.prototype,"clampCoordinates",void 0),(0,rv.H)("BABYLON.GeometryTextureFetchBlock",GeometryTextureFetchBlock);let BoundingBlock=class BoundingBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",iX.Geometry),this.registerOutput("min",iX.Vector3),this.registerOutput("max",iX.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);if(!t)return null;let i=(0,lW.k)(t.positions,0,t.positions.length/3);return i.minimum},this.max._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);if(!t)return null;let i=(0,lW.k)(t.positions,0,t.positions.length/3);return i.maximum}}};(0,rv.H)("BABYLON.BoundingBlock",BoundingBlock),(e0=i0||(i0={}))[e0.Intersect=0]="Intersect",e0[e0.Subtract=1]="Subtract",e0[e0.Union=2]="Union";let BooleanGeometryBlock=class BooleanGeometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.operation=i0.Intersect,this.registerInput("geometry0",iX.Geometry),this.registerInput("geometry1",iX.Geometry),this.registerOutput("output",iX.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{let t;let i=this.geometry0.getConnectedValue(e),r=this.geometry1.getConnectedValue(e);if(!i||!r)return null;let s=i.positions.length/3;!i.normals&&r.normals&&(i.normals=Array(i.positions.length)),!r.normals&&i.normals&&(r.normals=Array(r.positions.length)),!i.uvs&&r.uvs&&(i.uvs=Array(2*s)),!r.uvs&&i.uvs&&(r.uvs=Array(2*s)),!i.colors&&r.colors&&(i.colors=Array(4*s)),!r.colors&&i.colors&&(r.colors=Array(4*s));let n=CSG.FromVertexData(i),a=CSG.FromVertexData(r);switch(this.operation){case i0.Intersect:t=n.intersect(a);break;case i0.Subtract:t=n.subtract(a);break;case i0.Union:t=n.union(a)}return t.toVertexData()};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`+`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${i0[this.operation]}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],BooleanGeometryBlock.prototype,"evaluateContext",void 0),(0,rH.gn)([editableInPropertyPage("Operation",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:i0.Intersect},{label:"Subtract",value:i0.Subtract},{label:"Union",value:i0.Union}]})],BooleanGeometryBlock.prototype,"operation",void 0),(0,rv.H)("BABYLON.BooleanGeometryBlock",BooleanGeometryBlock),rq.D.OfflineProviderFactory=(e,t,i=!1)=>new Database(e,t,i);let Database=class Database{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=Database._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,Database.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,rW.w1.SetImmediate(()=>{t(!0)})):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){let noManifestFile=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},createManifestURL=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){let e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`},t=!1,i=createManifestURL(),r=new rP.g;navigator.onLine&&(t=!0,i=i+(null==i.match(/\?/)?"?":"&")+Date.now()),r.open("GET",i),r.addEventListener("load",()=>{if(200===r.status||Database._ValidateXHRData(r,1))try{let t=JSON.parse(r.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&Database._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){noManifestFile()}else noManifestFile()},!1),r.addEventListener("error",()=>{if(t){t=!1;let e=createManifestURL();r.open("GET",e),r.send()}else noManifestFile()},!1);try{r.send()}catch(t){rT.Y.Error("Error on XHR send request."),e(!1)}}open(e,t){let handleError=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline)){if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;let t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{handleError()},t.onblocked=()=>{rT.Y.Error("IDB request blocked. Please reload the page."),handleError()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){rT.Y.Error("Error while creating object stores. Exception: "+e.message),handleError()}}}}else this._isSupported=!1,t&&t()}loadImage(e,t){let i=Database._ReturnFullUrlLocation(e),saveAndLoadImage=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?saveAndLoadImage():this._loadImageFromDBAsync(i,t,saveAndLoadImage)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let r;let s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;r&&"function"==typeof URL?(s=URL.createObjectURL(r.data),t.onerror=()=>{rT.Y.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};let n=s.objectStore("textures").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{rT.Y.Error("Error loading texture "+e+" from DB."),t.src=e}}else rT.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){let generateBlobUrl=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(Database._IsUASupportingBlobStorage){let r=new rP.g;r.open("GET",e),r.responseType="blob",r.addEventListener("load",()=>{if(200===r.status&&this._db){i=r.response;let s=this._db.transaction(["textures"],"readwrite");s.onabort=e=>{try{let t=e.target,i=t.error;i&&"QuotaExceededError"===i.name&&(this._hasReachedQuota=!0)}catch(e){}generateBlobUrl()},s.oncomplete=()=>{generateBlobUrl()};let n={textureUrl:e,data:i};try{let e=s.objectStore("textures").put(n);e.onsuccess=()=>{},e.onerror=()=>{generateBlobUrl()}}catch(i){25===i.code&&(Database._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),r.addEventListener("error",()=>{rT.Y.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),r.send()}else t.src=e}else rT.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 r;try{let s=this._db.transaction(["versions"]);s.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};let n=s.objectStore("versions").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{rT.Y.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){rT.Y.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else rT.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{let i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};let r={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(r);s.onsuccess=()=>{},s.onerror=()=>{rT.Y.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){rT.Y.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,r,s){let n=Database._ReturnFullUrlLocation(e),saveAndLoadFile=()=>{this._saveFileAsync(n,t,i,s,r)};this._checkVersionFromDB(n,e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,s,r):this._loadFileAsync(n,t,saveAndLoadFile):r&&r()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let r,s;r=-1!==e.indexOf(".babylon")?"scenes":"textures";let n=this._db.transaction([r]);n.oncomplete=()=>{s?t(s.data):i()},n.onabort=()=>{i()};let a=n.objectStore(r).get(e);a.onsuccess=e=>{s=e.target.result},a.onerror=()=>{rT.Y.Error("Error loading file "+e+" from DB."),i()}}else rT.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,s){if(this._isSupported){let n,a;n=-1!==e.indexOf(".babylon")?"scenes":"textures";let o=new rP.g;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(200===o.status||o.status<400&&Database._ValidateXHRData(o,r?6:1)){if(a=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){let i;let r=this._db.transaction([n],"readwrite");r.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},r.oncomplete=()=>{t(a)},i="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{let e=r.objectStore(n).put(i);e.onsuccess=()=>{},e.onerror=()=>{rT.Y.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a)}else o.status>=400&&s?s(o):t()},!1),o.addEventListener("error",()=>{rT.Y.Error("error on XHR request."),s&&s()},!1),o.send()}else rT.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){let i=GetTGAHeader(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){let t=new Uint8Array(e.response,0,3);if(68===t[0]&&68===t[1]&&83===t[2])return!0}}catch(e){}return!1}};Database._IsUASupportingBlobStorage=!0,Database.IDBStorageEnabled=!1,Database._ParseURL=e=>{let t=document.createElement("a");t.href=e;let i=e.substring(0,e.lastIndexOf("#")),r=e.substring(i.lastIndexOf("/")+1,e.length),s=e.substring(0,e.indexOf(r,0));return s},Database._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?Database._ParseURL(window.location.href)+e:e;let UniformBufferEffectCommonAccessor=class UniformBufferEffectCommonAccessor{_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))}};let lj=`#version 300 es +void main() {discard;} +`;s_.v.ShadersStore.gpuUpdateParticlesPixelShader=lj;let lq=`#version 300 es +#define PI 3.14159 +uniform float currentCount;uniform float timeDelta;uniform float stopFactor; +#ifndef LOCAL +uniform mat4 emitterWM; +#endif +uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; +#ifndef COLORGRADIENTS +uniform vec4 color1;uniform vec4 color2; +#endif +uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; +#ifdef BOXEMITTER +uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; +#endif +#ifdef POINTEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#endif +#ifdef HEMISPHERICEMITTER +uniform float radius;uniform float radiusRange;uniform float directionRandomizer; +#endif +#ifdef SPHEREEMITTER +uniform float radius;uniform float radiusRange; +#ifdef DIRECTEDSPHEREEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +#ifdef CYLINDEREMITTER +uniform float radius;uniform float height;uniform float radiusRange; +#ifdef DIRECTEDCYLINDEREMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +#ifdef CONEEMITTER +uniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer; +#endif +in vec3 position; +#ifdef CUSTOMEMITTER +in vec3 initialPosition; +#endif +in float age;in float life;in vec4 seed;in vec3 size; +#ifndef COLORGRADIENTS +in vec4 color; +#endif +in vec3 direction; +#ifndef BILLBOARD +in vec3 initialDirection; +#endif +#ifdef ANGULARSPEEDGRADIENTS +in float angle; +#else +in vec2 angle; +#endif +#ifdef ANIMATESHEET +in float cellIndex; +#ifdef ANIMATESHEETRANDOMSTART +in float cellStartOffset; +#endif +#endif +#ifdef NOISE +in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; +#endif +out vec3 outPosition; +#ifdef CUSTOMEMITTER +out vec3 outInitialPosition; +#endif +out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; +#ifndef COLORGRADIENTS +out vec4 outColor; +#endif +out vec3 outDirection; +#ifndef BILLBOARD +out vec3 outInitialDirection; +#endif +#ifdef ANGULARSPEEDGRADIENTS +out float outAngle; +#else +out vec2 outAngle; +#endif +#ifdef ANIMATESHEET +out float outCellIndex; +#ifdef ANIMATESHEETRANDOMSTART +out float outCellStartOffset; +#endif +#endif +#ifdef NOISE +out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; +#endif +#ifdef SIZEGRADIENTS +uniform sampler2D sizeGradientSampler; +#endif +#ifdef ANGULARSPEEDGRADIENTS +uniform sampler2D angularSpeedGradientSampler; +#endif +#ifdef VELOCITYGRADIENTS +uniform sampler2D velocityGradientSampler; +#endif +#ifdef LIMITVELOCITYGRADIENTS +uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; +#endif +#ifdef DRAGGRADIENTS +uniform sampler2D dragGradientSampler; +#endif +#ifdef NOISE +uniform vec3 noiseStrength;uniform sampler2D noiseSampler; +#endif +#ifdef ANIMATESHEET +uniform vec4 cellInfos; +#endif +vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} +vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} +void main() {float newAge=age+timeDelta; +if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; +#ifdef SIZEGRADIENTS +outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; +#else +outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; +#endif +outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; +#ifndef COLORGRADIENTS +outColor=color1+(color2-color1)*randoms.b; +#endif +#ifndef ANGULARSPEEDGRADIENTS +outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; +#else +outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; +#endif +#ifdef POINTEMITTER +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; +#elif defined(BOXEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; +#elif defined(HEMISPHERICEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; +#elif defined(SPHEREEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); +#ifdef DIRECTEDSPHEREEMITTER +newDirection=normalize(direction1+(direction2-direction1)*randoms3); +#else +newDirection=normalize(newPosition+directionRandomizer*randoms3); +#endif +#elif defined(CYLINDEREMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); +#ifdef DIRECTEDCYLINDEREMITTER +newDirection=direction1+(direction2-direction1)*randoms3; +#else +angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); +#endif +#elif defined(CONEEMITTER) +vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; +#ifdef CONEEMITTERSPAWNPOINT +float h=0.0001; +#else +float h=randoms2.y*height.y;h=1.-h*h; +#endif +float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); +if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); } +#elif defined(CUSTOMEMITTER) +newPosition=initialPosition;outInitialPosition=initialPosition; +#else +newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); +#endif +float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; +#ifdef LOCAL +outPosition=newPosition; +#else +outPosition=(emitterWM*vec4(newPosition,1.)).xyz; +#endif +#ifdef CUSTOMEMITTER +outDirection=direction; +#ifndef BILLBOARD +outInitialDirection=direction; +#endif +#else +#ifdef LOCAL +vec3 initial=newDirection; +#else +vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; +#endif +outDirection=initial*power; +#ifndef BILLBOARD +outInitialDirection=initial; +#endif +#endif +#ifdef ANIMATESHEET +outCellIndex=cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +outCellStartOffset=randoms.a*outLife; +#endif +#endif +#ifdef NOISE +outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; +#endif +} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; +#ifdef VELOCITYGRADIENTS +directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; +#endif +#ifdef DRAGGRADIENTS +directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; +#endif +#if defined(CUSTOMEMITTER) +outPosition=position+(direction-position)*ageGradient; +outInitialPosition=initialPosition; +#else +outPosition=position+direction*directionScale; +#endif +outLife=life;outSeed=seed; +#ifndef COLORGRADIENTS +outColor=color; +#endif +#ifdef SIZEGRADIENTS +outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; +#else +outSize=size; +#endif +#ifndef BILLBOARD +outInitialDirection=initialDirection; +#endif +#ifdef CUSTOMEMITTER +outDirection=direction; +#else +vec3 updatedDirection=direction+gravity*timeDelta; +#ifdef LIMITVELOCITYGRADIENTS +float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} +#endif +outDirection=updatedDirection; +#ifdef NOISE +float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; +#endif +#endif +#ifdef ANGULARSPEEDGRADIENTS +float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; +#else +outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); +#endif +#ifdef ANIMATESHEET +float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; +#else +float cellStartOffset=0.; +#endif +float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} +else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} +outCellIndex=float(int(cellInfos.x+ratio*dist)); +#endif +}}`;s_.v.ShadersStore.gpuUpdateParticlesVertexShader=lq;let WebGL2ParticleSystem=class WebGL2ParticleSystem{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e,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 CustomParticleEmitter&&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 ss.Q("gpuUpdateParticles",this._updateEffectOptions,this._engine),new UniformBufferEffectCommonAccessor(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){let e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw 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);let r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e<this._updateVAO.length;e++)this._engine.releaseVertexArrayObject(this._updateVAO[e]);this._updateVAO.length=0;for(let e=0;e<this._renderVAO.length;e++)this._engine.releaseVertexArrayObject(this._renderVAO[e]);this._renderVAO.length=0}_createUpdateVAO(e){let t={};t.position=e.createVertexBuffer("position",0,3);let i=3;t.age=e.createVertexBuffer("age",i,1),i+=1,t.size=e.createVertexBuffer("size",i,3),i+=3,t.life=e.createVertexBuffer("life",i,1),i+=1,t.seed=e.createVertexBuffer("seed",i,4),i+=4,t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._parent.particleEmitterType instanceof CustomParticleEmitter&&(t.initialPosition=e.createVertexBuffer("initialPosition",i,3),i+=3),this._parent._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),this._parent._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._parent.noiseTexture&&(t.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",i,3),i+=3,t.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",i,3),i+=3),this._parent._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._parent._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1,this._parent.spriteRandomStartCell&&(t.cellStartOffset=e.createVertexBuffer("cellStartOffset",i,1),i+=1));let r=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),r}};(0,rv.H)("BABYLON.WebGL2ParticleSystem",WebGL2ParticleSystem);let lK=`struct Particle {position : vec3<f32>, +age : f32, +size : vec3<f32>, +life : f32, +seed : vec4<f32>, +direction : vec3<f32>, +dummy0: f32, +#ifdef CUSTOMEMITTER +initialPosition : vec3<f32>, +dummy1: f32, +#endif +#ifndef COLORGRADIENTS +color : vec4<f32>, +#endif +#ifndef BILLBOARD +initialDirection : vec3<f32>, +dummy2: f32, +#endif +#ifdef NOISE +noiseCoordinates1 : vec3<f32>, +dummy3: f32, +noiseCoordinates2 : vec3<f32>, +dummy4: f32, +#endif +#ifdef ANGULARSPEEDGRADIENTS +angle : f32, +#else +angle : vec2<f32>, +#endif +#ifdef ANIMATESHEET +cellIndex : f32, +#ifdef ANIMATESHEETRANDOMSTART +cellStartOffset : f32, +#endif +#endif +};struct Particles {particles : array<Particle>,};struct SimParams {currentCount : f32, +timeDelta : f32, +stopFactor : f32, +randomTextureSize: i32, +lifeTime : vec2<f32>, +emitPower : vec2<f32>, +#ifndef COLORGRADIENTS +color1 : vec4<f32>, +color2 : vec4<f32>, +#endif +sizeRange : vec2<f32>, +scaleRange : vec4<f32>, +angleRange : vec4<f32>, +gravity : vec3<f32>, +#ifdef LIMITVELOCITYGRADIENTS +limitVelocityDamping : f32, +#endif +#ifdef ANIMATESHEET +cellInfos : vec4<f32>, +#endif +#ifdef NOISE +noiseStrength : vec3<f32>, +#endif +#ifndef LOCAL +emitterWM : mat4x4<f32>, +#endif +#ifdef BOXEMITTER +direction1 : vec3<f32>, +direction2 : vec3<f32>, +minEmitBox : vec3<f32>, +maxEmitBox : vec3<f32>, +#endif +#ifdef CONEEMITTER +radius : vec2<f32>, +coneAngle : f32, +height : vec2<f32>, +directionRandomizer : f32, +#endif +#ifdef CYLINDEREMITTER +radius : f32, +height : f32, +radiusRange : f32, +#ifdef DIRECTEDCYLINDEREMITTER +direction1 : vec3<f32>, +direction2 : vec3<f32>, +#else +directionRandomizer : f32, +#endif +#endif +#ifdef HEMISPHERICEMITTER +radius : f32, +radiusRange : f32, +directionRandomizer : f32, +#endif +#ifdef POINTEMITTER +direction1 : vec3<f32>, +direction2 : vec3<f32>, +#endif +#ifdef SPHEREEMITTER +radius : f32, +radiusRange : f32, +#ifdef DIRECTEDSPHEREEMITTER +direction1 : vec3<f32>, +direction2 : vec3<f32>, +#else +directionRandomizer : f32, +#endif +#endif +};@binding(0) @group(0) var<uniform> params : SimParams;@binding(1) @group(0) var<storage,read> particlesIn : Particles;@binding(2) @group(0) var<storage,read_write> particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d<f32>;@binding(4) @group(0) var randomTexture2 : texture_2d<f32>; +#ifdef SIZEGRADIENTS +@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d<f32>; +#endif +#ifdef ANGULARSPEEDGRADIENTS +@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d<f32>; +#endif +#ifdef VELOCITYGRADIENTS +@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d<f32>; +#endif +#ifdef LIMITVELOCITYGRADIENTS +@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d<f32>; +#endif +#ifdef DRAGGRADIENTS +@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d<f32>; +#endif +#ifdef NOISE +@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d<f32>; +#endif +fn getRandomVec3(offset : f32,vertexID : f32)->vec3<f32> {return textureLoad(randomTexture2,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} +fn getRandomVec4(offset : f32,vertexID : f32)->vec4<f32> {return textureLoad(randomTexture,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3<u32>) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} +let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4<f32>=particlesIn.particles[index].seed;let direction : vec3<f32>=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3<f32>;var newDirection : vec3<f32>;let randoms : vec4<f32>=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; +#ifdef SIZEGRADIENTS +sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(0.,0.),0.).r; +#else +sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; +#endif +particlesOut.particles[index].size=vec3<f32>( +sizex, +params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, +params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); +#ifndef COLORGRADIENTS +particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; +#endif +#ifndef ANGULARSPEEDGRADIENTS +particlesOut.particles[index].angle=vec2<f32>( +params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, +params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); +#else +particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; +#endif +#if defined(POINTEMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=vec3<f32>(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#elif defined(BOXEMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#elif defined(HEMISPHERICEMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); +#elif defined(SPHEREEMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,randY,randZ); +#ifdef DIRECTEDSPHEREEMITTER +newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); +#else +newDirection=normalize(newPosition+params.directionRandomizer*randoms3); +#endif +#elif defined(CYLINDEREMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3<f32>(xPos,yPos,zPos); +#ifdef DIRECTEDCYLINDEREMITTER +newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#else +angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3<f32>(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); +#endif +#elif defined(CONEEMITTER) +let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; +#ifdef CONEEMITTERSPAWNPOINT +let h : f32=0.0001; +#else +var h : f32=randoms2.y*params.height.y;h=1.-h*h; +#endif +var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3<f32>(randX,randY,randZ); +if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3<f32>(0.,1.0,0.);} else {let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } +#elif defined(CUSTOMEMITTER) +newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; +#else +newPosition=vec3<f32>(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3<f32>(0.5,0.5,0.5)); +#endif +let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; +#ifdef LOCAL +particlesOut.particles[index].position=newPosition; +#else +particlesOut.particles[index].position=(params.emitterWM*vec4<f32>(newPosition,1.)).xyz; +#endif +#ifdef CUSTOMEMITTER +particlesOut.particles[index].direction=direction; +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=direction; +#endif +#else +#ifdef LOCAL +let initial : vec3<f32>=newDirection; +#else +let initial : vec3<f32>=(params.emitterWM*vec4<f32>(newDirection,0.)).xyz; +#endif +particlesOut.particles[index].direction=initial*power; +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=initial; +#endif +#endif +#ifdef ANIMATESHEET +particlesOut.particles[index].cellIndex=params.cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +particlesOut.particles[index].cellStartOffset=randoms.a*outLife; +#endif +#endif +#ifdef NOISE +particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; +#endif +} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; +#ifdef VELOCITYGRADIENTS +directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r; +#endif +#ifdef DRAGGRADIENTS +directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2<f32>(ageGradient,0.),0.).r); +#endif +let position : vec3<f32>=particlesIn.particles[index].position; +#if defined(CUSTOMEMITTER) +particlesOut.particles[index].position=position+(direction-position)*ageGradient; +particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; +#else +particlesOut.particles[index].position=position+direction*directionScale; +#endif +particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; +#ifndef COLORGRADIENTS +particlesOut.particles[index].color=particlesIn.particles[index].color; +#endif +#ifdef SIZEGRADIENTS +particlesOut.particles[index].size=vec3<f32>( +textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(ageGradient,0.),0.).r, +particlesIn.particles[index].size.yz); +#else +particlesOut.particles[index].size=particlesIn.particles[index].size; +#endif +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; +#endif +#ifdef CUSTOMEMITTER +particlesOut.particles[index].direction=direction; +#else +var updatedDirection : vec3<f32>=direction+params.gravity*timeDelta; +#ifdef LIMITVELOCITYGRADIENTS +let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} +#endif +particlesOut.particles[index].direction=updatedDirection; +#ifdef NOISE +let noiseCoordinates1 : vec3<f32>=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3<f32>=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.x,noiseCoordinates1.y)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.z,noiseCoordinates2.x)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates2.y,noiseCoordinates2.z)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let force : vec3<f32>=vec3<f32>(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; +#endif +#endif +#ifdef ANGULARSPEEDGRADIENTS +let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2<f32>(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; +#else +let angle : vec2<f32>=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2<f32>(angle.x+angle.y*timeDelta,angle.y); +#endif +#ifdef ANIMATESHEET +var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; +#else +let cellStartOffset : f32=0.; +#endif +var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} +else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} +particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); +#endif +}} +`;s_.v.ShadersStoreWGSL.gpuUpdateParticlesComputeShader=lK;let ComputeShaderParticleSystem=class ComputeShaderParticleSystem{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}contextLost(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateComputeShader)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){var t;let i={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new ComputeShader("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split("\n")}),null===(t=this._simParamsComputeShader)||void 0===t||t.dispose(),this._simParamsComputeShader=new rX.M(this._engine),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new UniformBufferEffectCommonAccessor(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){let t=new StorageBuffer(this._engine,4*e.length,11);return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)}preUpdateParticleBuffer(){}updateParticleBuffer(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[1^e]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let e=0;e<this._bufferComputeShader.length;++e)this._bufferComputeShader[e].dispose();this._bufferComputeShader.length=0,null===(e=this._simParamsComputeShader)||void 0===e||e.dispose(),this._simParamsComputeShader=null,this._updateComputeShader=null}releaseVertexBuffers(){this._renderVertexBuffers.length=0}};(0,rv.H)("BABYLON.ComputeShaderParticleSystem",ComputeShaderParticleSystem);let ColorGradient=class ColorGradient{constructor(e,t,i){this.gradient=e,this.color1=t,this.color2=i}getColorToRef(e){if(!this.color2){e.copyFrom(this.color1);return}rg.HE.LerpToRef(this.color1,this.color2,Math.random(),e)}};let Color3Gradient=class Color3Gradient{constructor(e,t){this.gradient=e,this.color=t}};let FactorGradient=class FactorGradient{constructor(e,t,i){this.gradient=e,this.factor1=t,this.factor2=i}getFactor(){return void 0===this.factor2||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()}};let GradientHelper=class GradientHelper{static GetCurrentGradient(e,t,i){if(t[0].gradient>e){i(t[0],t[0],1);return}for(let r=0;r<t.length-1;r++){let s=t[r],n=t[r+1];if(e>=s.gradient&&e<=n.gradient){let t=(e-s.gradient)/(n.gradient-s.gradient);i(s,n,t);return}}let r=t.length-1;i(t[r],t[r],1)}};let Particle=class Particle{constructor(e){if(this.particleSystem=e,this.position=rm.P.Zero(),this.direction=rm.P.Zero(),this.color=new rg.HE(0,0,0,0),this.colorStep=new rg.HE(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new rm.FM(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new rg.HE(0,0,0,0),this._currentColor2=new rg.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=Particle._Count++,!this.particleSystem.isAnimationSheetEnabled)return;this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e,t=this.age,i=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===i?(i=1,t=this._randomCellOffset):t+=this._randomCellOffset);let r=this._initialEndSpriteCellID-this._initialStartSpriteCellID;e=this._initialSpriteCellLoop?rE.R.Clamp(t*i%this.lifeTime/this.lifeTime):rE.R.Clamp(t*i/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+e*r|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){let t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){let e=rm.jp.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else{let t=e.particleSystem.emitter;t.copyFrom(this.position)}this.direction.scaleToRef(e.inheritedVelocityAmount/2,rm.jp.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(rm.jp.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=Particle._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 rm.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()))}};Particle._Count=0,(e1=i1||(i1={}))[e1.ATTACHED=0]="ATTACHED",e1[e1.END=1]="END";let SubEmitter=class SubEmitter{constructor(e){if(this.particleSystem=e,this.type=i1.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){let t=(0,rv.q)("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(e){if(e instanceof rm.P)e=e.clone();else if(-1!==e.getClassName().indexOf("Mesh")){let t=(0,rv.q)("BABYLON.Mesh");(e=new t("",e.getScene())).isVisible=!1}}else e=new rm.P;let t=new SubEmitter(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){let t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw(0,r$.S)("ParseParticle")}static Parse(e,t,i){let r=e.particleSystem,s=new SubEmitter(SubEmitter._ParseParticleSystem(r,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}};let l$=`#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; +#include<clipPlaneFragmentDeclaration> +#include<imageProcessingDeclaration> +#include<logDepthDeclaration> +#include<helperFunctions> +#include<imageProcessingFunctions> +#ifdef RAMPGRADIENT +varying vec4 remapRanges;uniform sampler2D rampSampler; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; +#ifdef RAMPGRADIENT +float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); +#endif +#ifdef BLENDMULTIPLYMODE +float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); +#endif +#include<logDepthFragment> +#ifdef IMAGEPROCESSINGPOSTPROCESS +baseColor.rgb=toLinearSpace(baseColor.rgb); +#else +#ifdef IMAGEPROCESSING +baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); +#endif +#endif +gl_FragColor=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`;s_.v.ShadersStore.particlesPixelShader=l$;let lQ=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; +#ifdef ANIMATESHEET +attribute float cellIndex; +#endif +#ifndef BILLBOARD +attribute vec3 direction; +#endif +#ifdef BILLBOARDSTRETCHED +attribute vec3 direction; +#endif +#ifdef RAMPGRADIENT +attribute vec4 remapData; +#endif +attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; +#ifdef ANIMATESHEET +uniform vec3 particlesInfos; +#endif +varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; +#ifdef RAMPGRADIENT +varying vec4 remapRanges; +#endif +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform mat4 invView; +#endif +#include<clipPlaneVertexDeclaration> +#include<logDepthDeclaration> +#ifdef BILLBOARD +uniform vec3 eyePosition; +#endif +vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} +#ifdef BILLBOARDSTRETCHED +vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); +#ifdef BILLBOARDSTRETCHED_LOCAL +vec3 row1=direction; +#else +vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); +#endif +mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; +#ifdef BILLBOARD +vec3 rotatedCorner; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; +#else +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; +#endif +#ifdef RAMPGRADIENT +remapRanges=remapData; +#endif +gl_Position=projection*vec4(viewPos,1.0); +#else +vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); +#endif +vColor=color; +#ifdef ANIMATESHEET +float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; +#else +vUV=offset; +#endif +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include<clipPlaneVertex> +#include<logDepthVertex> +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.particlesVertexShader=lQ;let particleSystem_ParticleSystem=class particleSystem_ParticleSystem extends BaseParticleSystem{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 sm.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 rf.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,s=!1,n=.01){super(e),this._emitterInverseWorldMatrix=rm.y3.Identity(),this._inheritedVelocityOffset=new rm.P,this.onDisposeObservable=new rf.y$,this.onStoppedObservable=new rf.y$,this._particles=[],this._stockParticles=[],this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new rg.HE(0,0,0,0),this._colorDiff=new rg.HE(0,0,0,0),this._scaledDirection=rm.P.Zero(),this._scaledGravity=rm.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=>{let 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())._reset():e=new Particle(this),this._subEmitters&&this._subEmitters.length>0){let t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(t=>{if(t.type===i1.ATTACHED){let i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}})}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;let t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach(t=>{if(t.type===i1.END){let i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}})},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=rm.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||rS.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 sm.q(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new BoxParticleEmitter;let a=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=>{a=e}));let r=e===this._particles;for(let t=0;t<e.length;t++){let s=e[t],n=this._scaledUpdateSpeed,o=s.age;if(s.age+=n,s.age>s.lifeTime){let e=s.age-o,t=s.lifeTime-o;n=t*n/e,s.age=s.lifeTime}let l=s.age/s.lifeTime;this._colorGradients&&this._colorGradients.length>0?GradientHelper.GetCurrentGradient(l,this._colorGradients,(e,t,i)=>{e!==s._currentColorGradient&&(s._currentColor1.copyFrom(s._currentColor2),t.getColorToRef(s._currentColor2),s._currentColorGradient=e),rg.HE.LerpToRef(s._currentColor1,s._currentColor2,i,s.color)}):(s.colorStep.scaleToRef(n,this._scaledColorStep),s.color.addInPlace(this._scaledColorStep),s.color.a<0&&(s.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._angularSpeedGradients,(e,t,i)=>{e!==s._currentAngularSpeedGradient&&(s._currentAngularSpeed1=s._currentAngularSpeed2,s._currentAngularSpeed2=t.getFactor(),s._currentAngularSpeedGradient=e),s.angularSpeed=rE.R.Lerp(s._currentAngularSpeed1,s._currentAngularSpeed2,i)}),s.angle+=s.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._velocityGradients,(e,t,i)=>{e!==s._currentVelocityGradient&&(s._currentVelocity1=s._currentVelocity2,s._currentVelocity2=t.getFactor(),s._currentVelocityGradient=e),h*=rE.R.Lerp(s._currentVelocity1,s._currentVelocity2,i)}),s.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._limitVelocityGradients,(e,t,i)=>{e!==s._currentLimitVelocityGradient&&(s._currentLimitVelocity1=s._currentLimitVelocity2,s._currentLimitVelocity2=t.getFactor(),s._currentLimitVelocityGradient=e);let r=rE.R.Lerp(s._currentLimitVelocity1,s._currentLimitVelocity2,i),n=s.direction.length();n>r&&s.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._dragGradients,(e,t,i)=>{e!==s._currentDragGradient&&(s._currentDrag1=s._currentDrag2,s._currentDrag2=t.getFactor(),s._currentDragGradient=e);let r=rE.R.Lerp(s._currentDrag1,s._currentDrag2,i);this._scaledDirection.scaleInPlace(1-r)}),this.isLocal&&s._localPosition?(s._localPosition.addInPlace(this._scaledDirection),rm.P.TransformCoordinatesToRef(s._localPosition,this._emitterWorldMatrix,s.position)):s.position.addInPlace(this._scaledDirection),a&&i&&s._randomNoiseCoordinates1){let e=this._fetchR(s._randomNoiseCoordinates1.x,s._randomNoiseCoordinates1.y,i.width,i.height,a),t=this._fetchR(s._randomNoiseCoordinates1.z,s._randomNoiseCoordinates2.x,i.width,i.height,a),r=this._fetchR(s._randomNoiseCoordinates2.y,s._randomNoiseCoordinates2.z,i.width,i.height,a),o=rm.jp.Vector3[0],l=rm.jp.Vector3[1];o.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*t-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),o.scaleToRef(n,l),s.direction.addInPlace(l)}if(this.gravity.scaleToRef(n,this._scaledGravity),s.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._sizeGradients,(e,t,i)=>{e!==s._currentSizeGradient&&(s._currentSize1=s._currentSize2,s._currentSize2=t.getFactor(),s._currentSizeGradient=e),s.size=rE.R.Lerp(s._currentSize1,s._currentSize2,i)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._colorRemapGradients,(e,t,i)=>{let r=rE.R.Lerp(e.factor1,t.factor1,i),n=rE.R.Lerp(e.factor2,t.factor2,i);s.remapData.x=r,s.remapData.y=n-r}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._alphaRemapGradients,(e,t,i)=>{let r=rE.R.Lerp(e.factor1,t.factor1,i),n=rE.R.Lerp(e.factor2,t.factor2,i);s.remapData.z=r,s.remapData.w=n-r})),this._isAnimationSheetEnabled&&s.updateCellIndex(),s._inheritParticleInfoToSubEmitters(),s.age>=s.lifeTime){this._emitFromParticle(s),s._attachedSubEmitters&&(s._attachedSubEmitters.forEach(e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()}),s._attachedSubEmitters=null),this.recycleParticle(s),r&&t--;continue}}}}_addFactorGradient(e,t,i,r){let s=new FactorGradient(t,i,r);e.push(s),e.sort((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(let r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;let e=new Uint8Array(4*this._rawTextureWidth),t=rg.zZ.Color3[0];for(let i=0;i<this._rawTextureWidth;i++){let r=i/this._rawTextureWidth;GradientHelper.GetCurrentGradient(r,this._rampGradients,(r,s,n)=>{rg.Wo.LerpToRef(r.color,s.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255})}this._rampGradientsTexture=rawTexture_RawTexture.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.gradient<t.gradient?-1:e.gradient>t.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);let i=new Color3Gradient(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=[]);let r=new ColorGradient(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(let i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(let e of this._drawWrappers)if(e)for(let t of e)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,s){e=.5*Math.abs(e)+.5,t=.5*Math.abs(t)+.5;let n=e*i%i|0,a=t*r%r|0;return s[(n+a*i)*4]/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(){let e;this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);let t=this._engine,i=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*i),this._vertexBuffer=new rz.l(t,this._vertexData,!0,i);let r=0,s=this._vertexBuffer.createVertexBuffer(rz.o.PositionKind,r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[rz.o.PositionKind]=s,r+=3;let n=this._vertexBuffer.createVertexBuffer(rz.o.ColorKind,r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[rz.o.ColorKind]=n,r+=4;let a=this._vertexBuffer.createVertexBuffer("angle",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=a,r+=1;let o=this._vertexBuffer.createVertexBuffer("size",r,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,r+=2,this._isAnimationSheetEnabled){let e=this._vertexBuffer.createVertexBuffer("cellIndex",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,r+=1}if(!this._isBillboardBased||this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED||this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL){let e=this._vertexBuffer.createVertexBuffer("direction",r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,r+=3}if(this._useRampGradients){let e=this._vertexBuffer.createVertexBuffer("remapData",r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,r+=4}if(this._useInstancing){let i=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new rz.l(t,i,!1,2),e=this._spriteBuffer.createVertexBuffer("offset",0,2)}else e=this._vertexBuffer.createVertexBuffer("offset",r,2,this._vertexBufferSize,this._useInstancing),r+=2;this._vertexBuffers.offset=e,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));return}let e=[],t=[],i=0;for(let r=0;r<this._capacity;r++)e.push(i),e.push(i+1),e.push(i+2),e.push(i),e.push(i+2),e.push(i+3),t.push(i,i+1,i+1,i+2,i+2,i+3,i+3,i,i,i+3),i+=4;this._indexBuffer=this._engine.createIndexBuffer(e),this._linesIndexBuffer=this._engine.createIndexBuffer(t)}getCapacity(){return this._capacity}isAlive(){return this._alive}isStarted(){return this._started}_prepareSubEmitterInternalArray(){this._subEmitters=[],this.subEmitters&&this.subEmitters.forEach(e=>{e instanceof particleSystem_ParticleSystem?this._subEmitters.push([new SubEmitter(e)]):e instanceof SubEmitter?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);return}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[]),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){(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);let e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce(()=>{setTimeout(()=>{for(let t=0;t<this.preWarmCycles;t++)this.animate(!0),e.render()})});else for(let e=0;e<this.preWarmCycles;e++)this.animate(!0)}this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&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,r){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED||this.billboardMode===particleSystem_ParticleSystem.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&&(rm.P.TransformNormalToRef(e,this._emitterWorldMatrix,rm.jp.Vector3[0]),e=rm.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&&(rm.P.TransformNormalToRef(e,this._emitterWorldMatrix,rm.jp.Vector3[0]),e=rm.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===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=r)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;let e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){let t;if(this._alive=this._particles.length>0,this.emitter.position){let e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{let e=this.emitter;this._emitterWorldMatrix=rm.y3.Translation(e.x,e.y,e.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i<e&&this._particles.length!==this._capacity;i++){if(t=this._createParticle(),this._particles.push(t),this.targetStopDuration&&this._lifeTimeGradients&&this._lifeTimeGradients.length>0){let e=rE.R.Clamp(this._actualFrame/this.targetStopDuration);GradientHelper.GetCurrentGradient(e,this._lifeTimeGradients,(i,r)=>{let s=i.getFactor(),n=r.getFactor(),a=(e-i.gradient)/(r.gradient-i.gradient);t.lifeTime=rE.R.Lerp(s,n,a)})}else t.lifeTime=rE.R.RandomRange(this.minLifeTime,this.maxLifeTime);let e=rE.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(),rm.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=rE.R.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(rE.R.RandomRange(this.minScaleX,this.maxScaleX),rE.R.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){let e=this._actualFrame/this.targetStopDuration;GradientHelper.GetCurrentGradient(e,this._startSizeGradients,(e,i,r)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);let s=rE.R.Lerp(this._currentStartSize1,this._currentStartSize2,r);t.scale.scaleInPlace(s)})}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=rE.R.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=rE.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{let e=rE.R.RandomRange(0,1);rg.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 rm.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 rm.P(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new rm.P(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){let r=[rz.o.PositionKind,rz.o.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1){let i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return(0,nX.qx)(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&(0,nX.lK)(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===particleSystem_ParticleSystem.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case particleSystem_ParticleSystem.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED:case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case particleSystem_ParticleSystem.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(...particleSystem_ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...particleSystem_ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(sv.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),sv.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0,s=this._drawWrappers[r];s||(s=this._drawWrappers[r]=[]);let n=s[e];n||((n=new sm.q(this._engine)).drawContext&&(n.drawContext.useInstancing=this._useInstancing),s[e]=n);let a=i.join("\n");if(n.defines!==a){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,a),a)}return n}animate(e=!1){var t;let i;if(this._started){if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}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){let t=this._actualFrame/this.targetStopDuration;GradientHelper.GetCurrentGradient(t,this._emitRateGradients,(t,i,r)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=rE.R.Lerp(this._currentEmitRate1,this._currentEmitRate2,r)})}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<this._particles.length;t++){let i=this._particles[t];this._appendParticleVertices(e,i),e+=this._useInstancing?1:4}this._vertexBuffer&&this._vertexBuffer.updateDirectly(this._vertexData,0,this._particles.length)}0===this.manualEmitCount&&this.disposeOnStop&&this.stop()}}_appendParticleVertices(e,t){this._appendParticleVertex(e++,t,0,0),this._useInstancing||(this._appendParticleVertex(e++,t,1,0),this._appendParticleVertex(e++,t,1,1),this._appendParticleVertex(e++,t,0,1))}rebuild(){var e,t;for(let i in this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._createIndexBuffer(),null===(e=this._spriteBuffer)||void 0===e||e._rebuild(),null===(t=this._vertexBuffer)||void 0===t||t._rebuild(),this._vertexBuffers)this._vertexBuffers[i]._rebuild();this.resetDrawCache()}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_ADD).effect.isReady())return!1;return!0}_render(e){var t,i,r,s,n,a,o,l;let h=this._getWrapper(e),u=h.effect,c=this._engine;c.enableEffect(h);let d=null!==(t=this.defaultViewMatrix)&&void 0!==t?t:this._scene.getViewMatrix();if(u.setTexture("diffuseSampler",this.particleTexture),u.setMatrix("view",d),u.setMatrix("projection",null!==(i=this.defaultProjectionMatrix)&&void 0!==i?i:this._scene.getProjectionMatrix()),this._isAnimationSheetEnabled&&this.particleTexture){let e=this.particleTexture.getBaseSize();u.setFloat3("particlesInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,this.spriteCellWidth/e.width)}if(u.setVector2("translationPivot",this.translationPivot),u.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._isBillboardBased&&this._scene){let e=this._scene.activeCamera;u.setVector3("eyePosition",e.globalPosition)}this._rampGradientsTexture&&(this._rampGradients&&this._rampGradients.length||(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),u.setTexture("rampSampler",this._rampGradientsTexture));let p=u.defines;switch(this._scene&&(0,nX.an)(u,this,this._scene),p.indexOf("#define BILLBOARDMODE_ALL")>=0&&(d.invertToRef(rm.jp.Matrix[0]),u.setMatrix("invView",rm.jp.Matrix[0])),void 0!==this._vertexArrayObject?(null===(r=this._scene)||void 0===r?void 0:r.forceWireframe)?c.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,u):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,u)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?c.bindBuffers(this._vertexBuffers,(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)?this._linesIndexBuffer:this._indexBuffer,u):c.bindBuffers(this._vertexBuffers,(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._linesIndexBufferUseInstancing:null,u),this.useLogarithmicDepth&&this._scene&&so.G.BindLogDepth(p,u,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(u),e){case particleSystem_ParticleSystem.BLENDMODE_ADD:c.setAlphaMode(1);break;case particleSystem_ParticleSystem.BLENDMODE_ONEONE:c.setAlphaMode(6);break;case particleSystem_ParticleSystem.BLENDMODE_STANDARD:c.setAlphaMode(2);break;case particleSystem_ParticleSystem.BLENDMODE_MULTIPLY:c.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(u),this._useInstancing?(null===(o=this._scene)||void 0===o?void 0:o.forceWireframe)?c.drawElementsType(6,0,10,this._particles.length):c.drawArraysType(7,0,4,this._particles.length):(null===(l=this._scene)||void 0===l?void 0:l.forceWireframe)?c.drawElementsType(1,0,10*this._particles.length):c.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;let e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD?this._render(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY)+this._render(particleSystem_ParticleSystem.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._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let e=0;e<this._subEmitters.length;e++)for(let t of this._subEmitters[e])t.dispose();this._subEmitters=[],this.subEmitters=[]}if(this._disposeEmitterOnDispose&&this.emitter&&this.emitter.dispose&&this.emitter.dispose(!0),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){let e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){let r=Object.assign({},this._customWrappers),s=null,n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){s=this.customShader;let e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);r[0]?r[0].effect=t:this.setCustomEffect(t,0)}let a=this.serialize(i),o=particleSystem_ParticleSystem.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,this.preventAutoStart||o.start(),o}serialize(e=!1){let t={};if(particleSystem_ParticleSystem._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters)for(let i of(t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray(),this._subEmitters)){let r=[];for(let t of i)r.push(t.serialize(e));t.subEmitters.push(r)}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){let i=t.emitter;e.emitterId=i.id}else{let 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,rb.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;let r=t.getColorGradients();if(r)for(let t of(e.colorGradients=[],r)){let i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}let s=t.getRampGradients();if(s){for(let t of(e.rampGradients=[],s)){let i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}let n=t.getColorRemapGradients();if(n)for(let t of(e.colorRemapGradients=[],n)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}let a=t.getAlphaRemapGradients();if(a)for(let t of(e.alphaRemapGradients=[],a)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}let o=t.getSizeGradients();if(o)for(let t of(e.sizeGradients=[],o)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}let l=t.getAngularSpeedGradients();if(l)for(let t of(e.angularSpeedGradients=[],l)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}let h=t.getVelocityGradients();if(h)for(let t of(e.velocityGradients=[],h)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}let u=t.getDragGradients();if(u)for(let t of(e.dragGradients=[],u)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}let c=t.getEmitRateGradients();if(c)for(let t of(e.emitRateGradients=[],c)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}let d=t.getStartSizeGradients();if(d)for(let t of(e.startSizeGradients=[],d)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}let p=t.getLifeTimeGradients();if(p)for(let t of(e.lifeTimeGradients=[],p)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}let _=t.getLimitVelocityGradients();if(_){for(let t of(e.limitVelocityGradients=[],_)){let 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,r){var s,n,a;let o,l;o=i instanceof r6.B?null:i;let h=(0,rv.q)("BABYLON.Texture");if(h&&o&&(e.texture?t.particleTexture=h.Parse(e.texture,o,r):e.textureName&&(t.particleTexture=new h(r+e.textureName,o,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&o?t.emitter=o.getLastMeshById(e.emitterId):t.emitter=rm.P.FromArray(e.emitter):t.emitter=rm.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;i<e.animations.length;i++){let r=e.animations[i],s=(0,rv.q)("BABYLON.Animation");s&&t.animations.push(s.Parse(r))}t.beginAnimationOnStart=e.beginAnimationOnStart,t.beginAnimationFrom=e.beginAnimationFrom,t.beginAnimationTo=e.beginAnimationTo,t.beginAnimationLoop=e.beginAnimationLoop}if(e.autoAnimate&&o&&o.beginAnimation(t,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),t.startDelay=0|e.startDelay,t.minAngularSpeed=e.minAngularSpeed,t.maxAngularSpeed=e.maxAngularSpeed,t.minSize=e.minSize,t.maxSize=e.maxSize,e.minScaleX&&(t.minScaleX=e.minScaleX,t.maxScaleX=e.maxScaleX,t.minScaleY=e.minScaleY,t.maxScaleY=e.maxScaleY),void 0!==e.preWarmCycles&&(t.preWarmCycles=e.preWarmCycles,t.preWarmStepOffset=e.preWarmStepOffset),void 0!==e.minInitialRotation&&(t.minInitialRotation=e.minInitialRotation,t.maxInitialRotation=e.maxInitialRotation),t.minLifeTime=e.minLifeTime,t.maxLifeTime=e.maxLifeTime,t.minEmitPower=e.minEmitPower,t.maxEmitPower=e.maxEmitPower,t.emitRate=e.emitRate,t.gravity=rm.P.FromArray(e.gravity),e.noiseStrength&&(t.noiseStrength=rm.P.FromArray(e.noiseStrength)),t.color1=rg.HE.FromArray(e.color1),t.color2=rg.HE.FromArray(e.color2),t.colorDead=rg.HE.FromArray(e.colorDead),t.updateSpeed=e.updateSpeed,t.targetStopDuration=e.targetStopDuration,t.blendMode=e.blendMode,e.colorGradients)for(let i of e.colorGradients)t.addColorGradient(i.gradient,rg.HE.FromArray(i.color1),i.color2?rg.HE.FromArray(i.color2):void 0);if(e.rampGradients){for(let i of e.rampGradients)t.addRampGradient(i.gradient,rg.Wo.FromArray(i.color));t.useRampGradients=e.useRampGradients}if(e.colorRemapGradients)for(let i of e.colorRemapGradients)t.addColorRemapGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.alphaRemapGradients)for(let i of e.alphaRemapGradients)t.addAlphaRemapGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.sizeGradients)for(let i of e.sizeGradients)t.addSizeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.angularSpeedGradients)for(let i of e.angularSpeedGradients)t.addAngularSpeedGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.velocityGradients)for(let i of e.velocityGradients)t.addVelocityGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.dragGradients)for(let i of e.dragGradients)t.addDragGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.emitRateGradients)for(let i of e.emitRateGradients)t.addEmitRateGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.startSizeGradients)for(let i of e.startSizeGradients)t.addStartSizeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.lifeTimeGradients)for(let i of e.lifeTimeGradients)t.addLifeTimeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.limitVelocityGradients){for(let i of e.limitVelocityGradients)t.addLimitVelocityGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);t.limitVelocityDamping=e.limitVelocityDamping}if(e.noiseTexture&&o){let i=(0,rv.q)("BABYLON.ProceduralTexture");t.noiseTexture=i.Parse(e.noiseTexture,o,r)}if(e.particleEmitterType){switch(e.particleEmitterType.type){case"SphereParticleEmitter":l=new SphereParticleEmitter;break;case"SphereDirectedParticleEmitter":l=new SphereDirectedParticleEmitter;break;case"ConeEmitter":case"ConeParticleEmitter":l=new ConeParticleEmitter;break;case"CylinderParticleEmitter":l=new CylinderParticleEmitter;break;case"CylinderDirectedParticleEmitter":l=new CylinderDirectedParticleEmitter;break;case"HemisphericParticleEmitter":l=new HemisphericParticleEmitter;break;case"PointParticleEmitter":l=new PointParticleEmitter;break;case"MeshParticleEmitter":l=new MeshParticleEmitter;break;default:l=new BoxParticleEmitter}l.parse(e.particleEmitterType,o)}else(l=new BoxParticleEmitter).parse(e,o);t.particleEmitterType=l,t.startSpriteCellID=e.startSpriteCellID,t.endSpriteCellID=e.endSpriteCellID,t.spriteCellLoop=null===(s=e.spriteCellLoop)||void 0===s||s,t.spriteCellWidth=e.spriteCellWidth,t.spriteCellHeight=e.spriteCellHeight,t.spriteCellChangeSpeed=e.spriteCellChangeSpeed,t.spriteRandomStartCell=e.spriteRandomStartCell,t.disposeOnStop=null!==(n=e.disposeOnStop)&&void 0!==n&&n,t.manualEmitCount=null!==(a=e.manualEmitCount)&&void 0!==a?a:-1}static Parse(e,t,i,r=!1,s){let n;let a=e.name,o=null,l=null;if(n=t instanceof r6.B?t:t.getEngine(),e.customShader&&n.createEffectForParticles){l=e.customShader;let t=l.shaderOptions.defines.length>0?l.shaderOptions.defines.join("\n"):"";o=n.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,t)}let h=new particleSystem_ParticleSystem(a,s||e.capacity,t,o,e.isAnimationSheetEnabled);if(h.customShader=l,h._rootUrl=i,e.id&&(h.id=e.id),e.subEmitters)for(let r of(h.subEmitters=[],e.subEmitters)){let e=[];for(let s of r)e.push(SubEmitter.Parse(s,t,i));h.subEmitters.push(e)}return particleSystem_ParticleSystem._Parse(e,h,t,i),e.textureMask&&(h.textureMask=rg.HE.FromArray(e.textureMask)),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),r||h.preventAutoStart||h.start(),h}};particleSystem_ParticleSystem.BILLBOARDMODE_Y=2,particleSystem_ParticleSystem.BILLBOARDMODE_ALL=7,particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED=8,particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL=9,SubEmitter._ParseParticleSystem=particleSystem_ParticleSystem.Parse;let lZ=`#ifdef CLIPPLANE +in float fClipDistance; +#endif +#ifdef CLIPPLANE2 +in float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +in float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +in float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +in float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +in float fClipDistance6; +#endif +`;s_.v.IncludesShadersStore.clipPlaneFragmentDeclaration2=lZ;let lJ=`precision highp float; +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; +#include<clipPlaneFragmentDeclaration2> +#include<imageProcessingDeclaration> +#include<logDepthDeclaration> +#include<helperFunctions> +#include<imageProcessingFunctions> +void main() { +#include<clipPlaneFragment> +vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; +#ifdef BLENDMULTIPLYMODE +float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); +#endif +#include<logDepthFragment> +#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); +#else +#ifdef IMAGEPROCESSING +gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); +#endif +#endif +} +`;s_.v.ShadersStore.gpuRenderParticlesPixelShader=lJ;let l0=`#ifdef CLIPPLANE +uniform vec4 vClipPlane;out float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;out float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;out float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;out float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;out float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;out float fClipDistance6; +#endif +`;s_.v.IncludesShadersStore.clipPlaneVertexDeclaration2=l0;let l1=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; +#ifdef LOCAL +uniform mat4 emitterWM; +#endif +attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; +#ifndef BILLBOARD +attribute vec3 initialDirection; +#endif +#ifdef BILLBOARDSTRETCHED +attribute vec3 direction; +#endif +attribute float angle; +#ifdef ANIMATESHEET +attribute float cellIndex; +#endif +attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform mat4 invView; +#endif +#include<clipPlaneVertexDeclaration2> +#include<logDepthDeclaration> +#ifdef COLORGRADIENTS +uniform sampler2D colorGradientSampler; +#else +uniform vec4 colorDead;attribute vec4 color; +#endif +#ifdef ANIMATESHEET +uniform vec3 sheetInfos; +#endif +#ifdef BILLBOARD +uniform vec3 eyePosition; +#endif +vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; +#ifdef LOCAL +return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; +#else +return (position+worldOffset)+alignedCorner; +#endif +} +#ifdef BILLBOARDSTRETCHED +vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; +#ifdef LOCAL +return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; +#else +return (position+worldOffset)+alignedCorner; +#endif +} +#endif +void main() { +#ifdef ANIMATESHEET +float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; +#else +vUV=uv; +#endif +float ratio=age/life; +#ifdef COLORGRADIENTS +vColor=texture2D(colorGradientSampler,vec2(ratio,0)); +#else +vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); +#endif +vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; +#ifdef BILLBOARD +vec4 rotatedCorner;rotatedCorner.w=0.; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); +#else +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; +#ifdef LOCAL +vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; +#else +vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; +#endif +vPositionW=(invView*viewPosition).xyz; +#endif +#else +vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); +#endif +gl_Position=projection*viewPosition; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include<clipPlaneVertex> +#include<logDepthVertex> +}`;s_.v.ShadersStore.gpuRenderParticlesVertexShader=l1;let GPUParticleSystem=class GPUParticleSystem extends BaseParticleSystem{static get IsSupported(){if(!rS.l.LastCreatedEngine)return!1;let e=rS.l.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]))}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t,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 sm.q(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new rf.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=[]);let i=new ColorGradient(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.gradient<t.gradient?-1:e.gradient>t.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(let t in this._drawWrappers){let i=this._drawWrappers[t];null===(e=i.drawContext)||void 0===e||e.reset()}}_addFactorGradient(e,t,i){let r=new FactorGradient(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){e&&(i&&e.sort((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0),this[t]&&(this[t].dispose(),this[t]=null))}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this.onDisposeObservable=new rf.y$,this.onStoppedObservable=new rf.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=rm.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||rS.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!(0,rv.q)("BABYLON.ComputeShaderParticleSystem"))throw Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,rv.q)("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!(0,rv.q)("BABYLON.WebGL2ParticleSystem"))throw Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,rv.q)("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new sm.q(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new sm.q(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=null!=t?t:{}).randomTextureSize||delete t.randomTextureSize;let n=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),a=t;isFinite(a)&&(n.capacity=a),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new BoxParticleEmitter;let o=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize),l=[];for(let e=0;e<o;++e)l.push(Math.random()),l.push(Math.random()),l.push(Math.random()),l.push(Math.random());this._randomTexture=new rawTexture_RawTexture(new Float32Array(l),o,1,5,i,!1,!1,1,1),this._randomTexture.name="GPUParticleSystem_random1",this._randomTexture.wrapU=1,this._randomTexture.wrapV=1,l=[];for(let e=0;e<o;++e)l.push(Math.random()),l.push(Math.random()),l.push(Math.random()),l.push(Math.random());this._randomTexture2=new rawTexture_RawTexture(new Float32Array(l),o,1,5,i,!1,!1,1,1),this._randomTexture2.name="GPUParticleSystem_random2",this._randomTexture2.wrapU=1,this._randomTexture2.wrapV=1,this._randomTextureSize=o}_reset(){this._releaseBuffers()}_createVertexBuffers(e,t,i){let r={};r.position=t.createVertexBuffer("position",0,3,this._attributesStrideSize,!0);let s=3;r.age=t.createVertexBuffer("age",s,1,this._attributesStrideSize,!0),s+=1,r.size=t.createVertexBuffer("size",s,3,this._attributesStrideSize,!0),s+=3,r.life=t.createVertexBuffer("life",s,1,this._attributesStrideSize,!0),s+=5,this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED&&(r.direction=t.createVertexBuffer("direction",s,3,this._attributesStrideSize,!0)),s+=3,this._platform.alignDataInBuffer&&(s+=1),this.particleEmitterType instanceof CustomParticleEmitter&&(s+=3,this._platform.alignDataInBuffer&&(s+=1)),this._colorGradientsTexture||(r.color=t.createVertexBuffer("color",s,4,this._attributesStrideSize,!0),s+=4),!this._isBillboardBased&&(r.initialDirection=t.createVertexBuffer("initialDirection",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1)),this.noiseTexture&&(r.noiseCoordinates1=t.createVertexBuffer("noiseCoordinates1",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1),r.noiseCoordinates2=t.createVertexBuffer("noiseCoordinates2",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1)),r.angle=t.createVertexBuffer("angle",s,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?s++:s+=2,this._isAnimationSheetEnabled&&(r.cellIndex=t.createVertexBuffer("cellIndex",s,1,this._attributesStrideSize,!0),s+=1,this.spriteRandomStartCell&&(r.cellStartOffset=t.createVertexBuffer("cellStartOffset",s,1,this._attributesStrideSize,!0),s+=1)),r.offset=i.createVertexBuffer("offset",0,2),r.uv=i.createVertexBuffer("uv",2,2),this._renderVertexBuffers.push(r),this._platform.createVertexBuffers(e,r),this.resetDrawCache()}_initialize(e=!1){if(this._buffer0&&!e)return;let t=this._engine,i=[];this._attributesStrideSize=21,this._targetIndex=0,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1),this.particleEmitterType instanceof CustomParticleEmitter&&(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),!this.isBillboardBased&&(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1,this.spriteRandomStartCell&&(this._attributesStrideSize+=1)),this.noiseTexture&&(this._attributesStrideSize+=6,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=2)),this._platform.alignDataInBuffer&&(this._attributesStrideSize+=3-(this._attributesStrideSize+3&3));let r=this.particleEmitterType instanceof CustomParticleEmitter,s=rm.jp.Vector3[0],n=0;for(let e=0;e<this._capacity;e++)if(i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),r?(this.particleEmitterType.particleDestinationGenerator(e,null,s),i.push(s.x),i.push(s.y),i.push(s.z)):(i.push(0),i.push(0),i.push(0)),this._platform.alignDataInBuffer&&i.push(0),n+=16,r&&(this.particleEmitterType.particlePositionGenerator(e,null,s),i.push(s.x),i.push(s.y),i.push(s.z),this._platform.alignDataInBuffer&&i.push(0),n+=4),this._colorGradientsTexture||(i.push(0),i.push(0),i.push(0),i.push(0),n+=4),this.isBillboardBased||(i.push(0),i.push(0),i.push(0),this._platform.alignDataInBuffer&&i.push(0),n+=4),this.noiseTexture&&(i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),n+=8),i.push(0),n+=1,this._angularSpeedGradientsTexture||(i.push(0),n+=1),this._isAnimationSheetEnabled&&(i.push(0),n+=1,this.spriteRandomStartCell&&(i.push(0),n+=1)),this._platform.alignDataInBuffer){let e=3-(n+3&3);for(n+=e;e-- >0;)i.push(0)}let a=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),o=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new rz.l(t,o,!1,this._attributesStrideSize),this._buffer1=new rz.l(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new rz.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){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||((r=new sm.q(this._engine)).drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);let s=i.join("\n");if(r.defines!==s){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){let s=[rz.o.PositionKind,"age","life","size","angle"];return e||s.push(rz.o.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),r&&s.push("direction"),s.push("offset",rz.o.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1){let i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return(0,nX.qx)(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&(0,nX.lK)(this,this._scene,e),t===particleSystem_ParticleSystem.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 particleSystem_ParticleSystem.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case particleSystem_ParticleSystem.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(...GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED)),e.push(...GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(sv.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),sv.$.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){let i=this[t];if(!e||!e.length||i)return;let r=new Float32Array(this._rawTextureWidth);for(let t=0;t<this._rawTextureWidth;t++){let i=t/this._rawTextureWidth;GradientHelper.GetCurrentGradient(i,e,(e,i,s)=>{r[t]=rE.R.Lerp(e.factor1,i.factor1,s)})}this[t]=rawTexture_RawTexture.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;let e=new Uint8Array(4*this._rawTextureWidth),t=rg.zZ.Color4[0];for(let i=0;i<this._rawTextureWidth;i++){let r=i/this._rawTextureWidth;GradientHelper.GetCurrentGradient(r,this._colorGradients,(r,s,n)=>{rg.HE.LerpToRef(r.color1,s.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a})}this._colorGradientsTexture=rawTexture_RawTexture.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,r,s,n,a;let o=this._getWrapper(e),l=o.effect;this._engine.enableEffect(o);let h=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||rm.y3.IdentityReadOnly;if(l.setMatrix("view",h),l.setMatrix("projection",null!==(r=this.defaultProjectionMatrix)&&void 0!==r?r:this._scene.getProjectionMatrix()),l.setTexture("diffuseSampler",this.particleTexture),l.setVector2("translationPivot",this.translationPivot),l.setVector3("worldOffset",this.worldOffset),this.isLocal&&l.setMatrix("emitterWM",t),this._colorGradientsTexture?l.setTexture("colorGradientSampler",this._colorGradientsTexture):l.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){let e=this.particleTexture.getBaseSize();l.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){let e=this._scene.activeCamera;l.setVector3("eyePosition",e.globalPosition)}let u=l.defines;if(this._scene&&(0,nX.an)(l,this,this._scene),u.indexOf("#define BILLBOARDMODE_ALL")>=0){let e=h.clone();e.invert(),l.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&so.G.BindLogDepth(u,l,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(l),e){case particleSystem_ParticleSystem.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case particleSystem_ParticleSystem.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case particleSystem_ParticleSystem.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case particleSystem_ParticleSystem.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,l,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(l),(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect())return;if(!e){if(this.emitter.position){let t=this.emitter;e=t.getWorldMatrix()}else{let t=this.emitter;e=rm.jp.Matrix[0],rm.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);let t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){let i;if(!this._started||!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e<this.preWarmCycles;e++)this.animate(!0),this.render(!0,!0);this._preWarmDone=!0}if(this._currentRenderId===this._scene.getRenderId()&&(!this._scene.activeCamera||this._scene.activeCamera&&this._currentRenderingCameraUniqueId===this._scene.activeCamera.uniqueId))return 0;this._currentRenderId=this._scene.getRenderId(),this._scene.activeCamera&&(this._currentRenderingCameraUniqueId=this._scene.activeCamera.uniqueId)}if(this._initialize(),this._accumulatedCount+=this.emitRate*this._timeDelta,this._accumulatedCount>1){let e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;if(this.emitter.position){let e=this.emitter;i=e.getWorldMatrix()}else{let e=this.emitter;i=rm.jp.Matrix[0],rm.y3.TranslationToRef(e.x,e.y,e.z,i)}let r=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),s=this.blendMode===particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD?this._render(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY,i)+this._render(particleSystem_ParticleSystem.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){let checkUpdateEffect=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?this._initialize(!0):setTimeout(checkUpdateEffect,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),checkUpdateEffect()}_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(let e in this._drawWrappers){let t=this._drawWrappers[e];t.dispose()}if(this._drawWrappers={},this._scene){let e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e<this._renderVertexBuffers.length;++e){let t=this._renderVertexBuffers[e];for(let e in t)t[e].dispose()}this._renderVertexBuffers=[],this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._limitVelocityGradientsTexture&&(this._limitVelocityGradientsTexture.dispose(),this._limitVelocityGradientsTexture=null),this._dragGradientsTexture&&(this._dragGradientsTexture.dispose(),this._dragGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onStoppedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}clone(e,t,i=!1){let r=Object.assign({},this._customWrappers),s=null,n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){s=this.customShader;let e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"";r[0]=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}let a=this.serialize(i),o=GPUParticleSystem.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,o}serialize(e=!1){let t={};return particleSystem_ParticleSystem._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,s){let n;let a=e.name;n=t instanceof r6.B?t:t.getEngine();let o=new GPUParticleSystem(a,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(o._rootUrl=i,e.customShader&&n.createEffectForParticles){let t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",r=n.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,o);o.setCustomEffect(r,0),o.customShader=t}return e.id&&(o.id=e.id),e.activeParticleCount&&(o.activeParticleCount=e.activeParticleCount),particleSystem_ParticleSystem._Parse(e,o,t,i),e.preventAutoStart&&(o.preventAutoStart=e.preventAutoStart),r||o.preventAutoStart||o.start(),o}};let ParticleSystemSet=class ParticleSystemSet{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){for(let t of(this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1),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};let r=sphereBuilder_CreateSphere("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;let s=new standardMaterial_StandardMaterial("emitterSphereMaterial",i);for(let t of(s.emissiveColor=e.color,r.material=s,this.systems))t.emitter=r;this._emitterNode=r}start(e){for(let t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(let e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){let t={};for(let i of(t.systems=[],this.systems))t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){let s=new ParticleSystemSet,n=this.BaseAssetsUrl+"/textures/";for(let a of(t=t||rS.l.LastCreatedScene,e.systems))s.systems.push(i?GPUParticleSystem.Parse(a,t,n,!0,r):particleSystem_ParticleSystem.Parse(a,t,n,!0,r));if(e.emitter){let i=e.emitter.options;"Sphere"===e.emitter.kind&&s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:rg.Wo.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}};ParticleSystemSet.BaseAssetsUrl="https://assets.babylonjs.com/particles";let ParticleHelper=class ParticleHelper{static CreateDefault(e,t=500,i,r=!1){let s;return(s=r?new GPUParticleSystem("default system",{capacity:t},i):new particleSystem_ParticleSystem("default system",t,i)).emitter=e,s.particleTexture=new texture_Texture("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new rg.HE(1,1,1,1),s.color2=new rg.HE(1,1,1,1),s.colorDead=new rg.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,r){t||(t=rS.l.LastCreatedScene);let s={};return t.addPendingData(s),new Promise((n,a)=>{if(i&&!GPUParticleSystem.IsSupported)return t.removePendingData(s),a("Particle system with GPU is not supported.");rW.w1.LoadFile(`${ParticleHelper.BaseAssetsUrl}/systems/${e}.json`,e=>{t.removePendingData(s);let a=JSON.parse(e.toString());return n(ParticleSystemSet.Parse(a,t,i,r))},void 0,void 0,void 0,()=>(t.removePendingData(s),a(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){let t=new ParticleSystemSet;for(let i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,s="",n){return new Promise((a,o)=>{let l=new rP.g;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let t;let o=JSON.parse(l.responseText);t=r?GPUParticleSystem.Parse(o,i,s,!1,n):particleSystem_ParticleSystem.Parse(o,i,s,!1,n),e&&(t.name=e),a(t)}else o("Unable to load the particle system")}}),l.open("GET",t),l.send()})}static ParseFromSnippetAsync(e,t,i=!1,r="",s){if("_BLANK"===e){let e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise((n,a)=>{let o=new rP.g;o.addEventListener("readystatechange",()=>{if(4==o.readyState){if(200==o.status){let a;let l=JSON.parse(JSON.parse(o.responseText).jsonPayload),h=JSON.parse(l.particleSystem);(a=i?GPUParticleSystem.Parse(h,t,r,!1,s):particleSystem_ParticleSystem.Parse(h,t,r,!1,s)).snippetId=e,n(a)}else a("Unable to load the snippet "+e)}}),o.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),o.send()})}};ParticleHelper.BaseAssetsUrl=ParticleSystemSet.BaseAssetsUrl,ParticleHelper.SnippetUrl="https://snippet.babylonjs.com",ParticleHelper.CreateFromSnippetAsync=ParticleHelper.ParseFromSnippetAsync,rp.p.AddParser(rQ.l.NAME_PARTICLESYSTEM,(e,t,i,r)=>{let s=rp.p.GetIndividualParser(rQ.l.NAME_PARTICLESYSTEM);if(s&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,a=e.particleSystems.length;n<a;n++){let a=e.particleSystems[n];i.particleSystems.push(s(a,t,r))}}),rp.p.AddIndividualParser(rQ.l.NAME_PARTICLESYSTEM,(e,t,i)=>{if(e.activeParticleCount){let r=GPUParticleSystem.Parse(e,t,i);return r}{let r=particleSystem_ParticleSystem.Parse(e,t,i);return r}}),rq.D.prototype.createEffectForParticles=function(e,t=[],i=[],r="",s,n,a,o){var l;let h=[],u=[],c=[];return o?o.fillUniformsAttributesAndSamplerNames(u,h,c):(h=particleSystem_ParticleSystem._GetAttributeNamesOrOptions(),u=particleSystem_ParticleSystem._GetEffectCreationOptions()),-1===r.indexOf(" BILLBOARD")&&(r+="\n#define BILLBOARD\n"),(null==o?void 0:o.isAnimationSheetEnabled)&&-1===r.indexOf(" ANIMATESHEET")&&(r+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==o?void 0:o.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},h,u.concat(t),c.concat(i),r,s,n,a)},rV.Kj.prototype.getEmittedParticleSystems=function(){let e=[];for(let t=0;t<this.getScene().particleSystems.length;t++){let i=this.getScene().particleSystems[t];i.emitter===this&&e.push(i)}return e},rV.Kj.prototype.getHierarchyEmittedParticleSystems=function(){let e=[],t=this.getDescendants();t.push(this);for(let i=0;i<this.getScene().particleSystems.length;i++){let r=this.getScene().particleSystems[i],s=r.emitter;s.position&&-1!==t.indexOf(s)&&e.push(r)}return e},(e2=i2||(i2={}))[e2.Color=2]="Color",e2[e2.UV=1]="UV",e2[e2.Random=0]="Random",e2[e2.Stated=3]="Stated",Object.defineProperty(rG.x.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0}),rG.x.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},rG.x.prototype.applyImpulse=function(e,t){return this.physicsImpostor&&this.physicsImpostor.applyImpulse(e,t),this},rG.x.prototype.setPhysicsLinkWith=function(e,t,i,r){return this.physicsImpostor&&e.physicsImpostor&&this.physicsImpostor.createJoint(e.physicsImpostor,PhysicsJoint.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:r}),this};let physicsEngine_PhysicsEngine=class physicsEngine_PhysicsEngine{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,r$.S)("")}constructor(e,t=physicsEngine_PhysicsEngine.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new rm.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){let t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){let r=new PhysicsRaycastResult;return this._physicsPlugin.raycast(e,t,r,i),r}};(e3=i3||(i3={}))[e3.FREE=0]="FREE",e3[e3.LIMITED=1]="LIMITED",e3[e3.LOCKED=2]="LOCKED",(e4=i4||(i4={}))[e4.LINEAR_X=0]="LINEAR_X",e4[e4.LINEAR_Y=1]="LINEAR_Y",e4[e4.LINEAR_Z=2]="LINEAR_Z",e4[e4.ANGULAR_X=3]="ANGULAR_X",e4[e4.ANGULAR_Y=4]="ANGULAR_Y",e4[e4.ANGULAR_Z=5]="ANGULAR_Z",e4[e4.LINEAR_DISTANCE=6]="LINEAR_DISTANCE",(e5=i5||(i5={}))[e5.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e5[e5.DISTANCE=2]="DISTANCE",e5[e5.HINGE=3]="HINGE",e5[e5.SLIDER=4]="SLIDER",e5[e5.LOCK=5]="LOCK",e5[e5.PRISMATIC=6]="PRISMATIC",e5[e5.SIX_DOF=7]="SIX_DOF",(e6=i6||(i6={}))[e6.SPHERE=0]="SPHERE",e6[e6.CAPSULE=1]="CAPSULE",e6[e6.CYLINDER=2]="CYLINDER",e6[e6.BOX=3]="BOX",e6[e6.CONVEX_HULL=4]="CONVEX_HULL",e6[e6.CONTAINER=5]="CONTAINER",e6[e6.MESH=6]="MESH",e6[e6.HEIGHTFIELD=7]="HEIGHTFIELD",(e8=i8||(i8={}))[e8.NONE=0]="NONE",e8[e8.VELOCITY=1]="VELOCITY",e8[e8.POSITION=2]="POSITION",(e7=i7||(i7={})).COLLISION_STARTED="COLLISION_STARTED",e7.COLLISION_CONTINUED="COLLISION_CONTINUED",e7.COLLISION_FINISHED="COLLISION_FINISHED",e7.TRIGGER_ENTERED="TRIGGER_ENTERED",e7.TRIGGER_EXITED="TRIGGER_EXITED",(e9=i9||(i9={}))[e9.STATIC=0]="STATIC",e9[e9.ANIMATED=1]="ANIMATED",e9[e9.DYNAMIC=2]="DYNAMIC",(te=re||(re={}))[te.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",te[te.MINIMUM=1]="MINIMUM",te[te.MAXIMUM=2]="MAXIMUM",te[te.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",te[te.MULTIPLY=4]="MULTIPLY",rN.x.prototype.getPhysicsEngine=function(){return this._physicsEngine},rN.x.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(rQ.l.NAME_PHYSICSENGINE);i||(i=new PhysicsEngineSceneComponent(this),this._addComponent(i));try{if(t&&(null==t?void 0:t.getPluginVersion())!==1){if((null==t?void 0:t.getPluginVersion())===2)this._physicsEngine=new physicsEngine_PhysicsEngine(e,t);else throw Error("Unsupported Physics plugin version.")}else this._physicsEngine=new PhysicsEngine(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return rT.Y.Error(e.message),!1}},rN.x.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},rN.x.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},rN.x.prototype.deleteCompoundImpostor=function(e){let t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},rN.x.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){let 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)}};let PhysicsEngineSceneComponent=class PhysicsEngineSceneComponent{constructor(e){this.name=rQ.l.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new rf.y$,this.scene.onAfterPhysicsObservable=new rf.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(rk.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}),rk.Y.prototype.getPhysicsBody=function(){return this.physicsBody},rk.Y.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this};let HelperTools=class HelperTools{static GetContactPointToRef(e,t,i,r,s){let n=e.getScene().getPhysicsEngine(),a=null==n?void 0:n.getPluginVersion();if(1===a){let s=new ray_Ray(t,i),n=s.intersectsMesh(e);if(n.hit&&n.pickedPoint)return r.copyFrom(n.pickedPoint),!0}else if(2===a)return e.physicsBody.getObjectCenterWorldToRef(r,s),!0;return!1}static HasAppliedForces(e,t){var i,r,s;return e.getMotionType(t)===i9.STATIC||(null!==(r=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==r?r:0)===0||(null===(s=e.transformNode)||void 0===s?void 0:s.getTotalVertices())===0}static IsInsideCylinder(e,t,i,r){let s=rm.jp.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=r}};let PhysicsUpdraftEvent=class PhysicsUpdraftEvent{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=rm.P.Zero(),this._originDirection=rm.P.Zero(),this._cylinderPosition=rm.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new PhysicsUpdraftEventOptions),this._options),this._origin.addToRef(new rm.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new rm.P(0,this._options.height,0),this._originTop),this._options.updraftMode===ri.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout(()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)},0))}_getHitData(e,t){let i;i=this._options.updraftMode===ri.Perpendicular?this._originDirection:e.subtract(this._originTop);let r=rm.P.Distance(this._origin,e),s=-1*this._options.strength,n=i.multiplyByFloats(s,s,s);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(HelperTools.HasAppliedForces(e))return!1;let r=e.getObjectCenterWorld(i);return!!HelperTools.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){let e=PhysicsUpdraftEvent._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=cylinderBuilder_CreateCylinder("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))}};PhysicsUpdraftEvent._HitData={force:new rm.P,contactPoint:new rm.P,distanceFromOrigin:0};let PhysicsVortexEvent=class PhysicsVortexEvent{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=rm.P.Zero(),this._cylinderPosition=rm.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new PhysicsVortexEventOptions),this._options),this._origin.addToRef(new rm.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new rm.P(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout(()=>{this._dataFetched||this._cylinder.dispose()},0))}_getHitData(e,t,i){let r,s,n;let a=PhysicsVortexEvent.originOnPlane;a.set(this._origin.x,t.y,this._origin.z);let o=rm.jp.Vector3[0];t.subtractToRef(a,o);let l=rm.jp.Vector3[1],h=HelperTools.GetContactPointToRef(e,a,o,l,i.instanceIndex);if(!h)return!1;let u=rm.P.Distance(l,a),c=u/this._options.radius,d=rm.jp.Vector3[2];if(l.normalizeToRef(d),c>this._options.centripetalForceThreshold&&d.negateInPlace(),c>this._options.centripetalForceThreshold)r=d.x*this._options.centripetalForceMultiplier,s=d.y*this._options.updraftForceMultiplier,n=d.z*this._options.centripetalForceMultiplier;else{let e=rm.P.Cross(a,t).normalize();r=(e.x+d.x)*this._options.centrifugalForceMultiplier,s=this._originTop.y*this._options.updraftForceMultiplier,n=(e.z+d.z)*this._options.centrifugalForceMultiplier}let p=rm.jp.Vector3[3];return p.set(r,s,n),p.scaleInPlace(this._options.strength),i.force.copyFrom(p),i.contactPoint.copyFrom(t),i.distanceFromOrigin=c,!0}_getBodyHitData(e,t,i){if(HelperTools.HasAppliedForces(e,i))return!1;let r=e.transformNode,s=e.getObjectCenterWorld(i);return!!HelperTools.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,s,t))}_getImpostorHitData(e,t){if(0===e.mass||"Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){let e=PhysicsVortexEvent.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=cylinderBuilder_CreateCylinder("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)}};PhysicsVortexEvent.originOnPlane=rm.P.Zero(),PhysicsVortexEvent.hitData={force:new rm.P,contactPoint:new rm.P,distanceFromOrigin:0};let PhysicsUpdraftEventOptions=class PhysicsUpdraftEventOptions{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=ri.Center}};let PhysicsVortexEventOptions=class PhysicsVortexEventOptions{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}};(tt=rt||(rt={}))[tt.Constant=0]="Constant",tt[tt.Linear=1]="Linear",(ti=ri||(ri={}))[ti.Center=0]="Center",ti[ti.Perpendicular=1]="Perpendicular";let l2=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); +vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;s_.v.ShadersStore.blackAndWhitePixelShader=l2;let BlackAndWhitePostProcess=class BlackAndWhitePostProcess extends postProcess_PostProcess{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,r,s,n){super(e,"blackAndWhite",["degree"],null,t,i,r,s,n),this.degree=1,this.onApplyObservable.add(e=>{e.setFloat("degree",this.degree)})}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new BlackAndWhitePostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],BlackAndWhitePostProcess.prototype,"degree",void 0),(0,rv.H)("BABYLON.BlackAndWhitePostProcess",BlackAndWhitePostProcess);let postProcessRenderEffect_PostProcessRenderEffect=class postProcessRenderEffect_PostProcessRenderEffect{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(let e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){let t=this._postProcesses[e];for(let e=0;e<t.length;e++)if(!t[e].isSupported)return!1}return!0}_update(){}_attachCameras(e){let t;let i=rW.w1.MakeArray(e||this._cameras);if(i)for(let e=0;e<i.length;e++){let r=i[e];if(!r)continue;let s=r.name;if(t=this._singleInstance?0:s,!this._postProcesses[t]){let e=this._getPostProcesses();e&&(this._postProcesses[t]=Array.isArray(e)?e:[e])}this._indicesForCamera[s]||(this._indicesForCamera[s]=[]),this._postProcesses[t].forEach(e=>{let t=r.attachPostProcess(e);this._indicesForCamera[s].push(t)}),this._cameras[s]||(this._cameras[s]=r)}}_detachCameras(e){let t=rW.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){let i=t[e],r=i.name,s=this._postProcesses[this._singleInstance?0:r];s&&s.forEach(e=>{i.detachPostProcess(e)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){let t=rW.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){let i=t[e],r=i.name,s=this._singleInstance?0:r;for(let n=0;n<this._indicesForCamera[r].length;n++){let a=this._indicesForCamera[r][n],o=i._postProcesses[a];null==o&&t[e].attachPostProcess(this._postProcesses[s][n],a)}}}_disable(e){let t=rW.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){let i=t[e],r=i.name;this._postProcesses[this._singleInstance?0:r].forEach(e=>{i.detachPostProcess(e)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}};let l3=`#include<helperFunctions> +varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;s_.v.ShadersStore.extractHighlightsPixelShader=l3;let ExtractHighlightsPostProcess=class ExtractHighlightsPostProcess extends postProcess_PostProcess{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,r,s,n,null,a,void 0,null,o),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,rw.zp)),e.setFloat("exposure",this._exposure)})}};(0,rH.gn)([(0,rb.qC)()],ExtractHighlightsPostProcess.prototype,"threshold",void 0),(0,rv.H)("BABYLON.ExtractHighlightsPostProcess",ExtractHighlightsPostProcess);let l4=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } +`;s_.v.ShadersStore.bloomMergePixelShader=l4;let BloomMergePostProcess=class BloomMergePostProcess extends postProcess_PostProcess{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,s,n,a,o,l,h=0,u=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,n,a,o,l,null,h,void 0,null,!0),this.weight=1,this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)}),u||this.updateEffect()}};(0,rH.gn)([(0,rb.qC)()],BloomMergePostProcess.prototype,"weight",void 0),(0,rv.H)("BABYLON.BloomMergePostProcess",BloomMergePostProcess);let BloomEffect=class BloomEffect extends postProcessRenderEffect_PostProcessRenderEffect{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,r,s=0,n=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new ExtractHighlightsPostProcess("highlights",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,n),this._blurX=new BlurPostProcess("horizontal blur",new rm.FM(1,0),10,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new BlurPostProcess("vertical blur",new rm.FM(0,1),10,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new BloomMergePostProcess("bloomMerge",this._downscale,this._blurY,i,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){for(let e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0}};let l5=`uniform sampler2D textureSampler; +uniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);} +float radius2=centered_screen_pos.x*centered_screen_pos.x ++ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec4 original=texture2D(textureSampler,vUV);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);original.r=texture2D(textureSampler,ref_coords_r).r;original.g=texture2D(textureSampler,ref_coords_g).g;original.b=texture2D(textureSampler,ref_coords_b).b;original.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);gl_FragColor=original;}`;s_.v.ShadersStore.chromaticAberrationPixelShader=l5;let ChromaticAberrationPostProcess=class ChromaticAberrationPostProcess extends postProcess_PostProcess{getClassName(){return"ChromaticAberrationPostProcess"}constructor(e,t,i,r,s,n,a,o,l=0,h=!1){super(e,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],r,s,n,a,o,null,l,void 0,null,h),this.aberrationAmount=30,this.radialIntensity=0,this.direction=new rm.FM(.707,.707),this.centerPosition=new rm.FM(.5,.5),this.screenWidth=t,this.screenHeight=i,this.onApplyObservable.add(e=>{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,r){return rb.p4.Parse(()=>new ChromaticAberrationPostProcess(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"aberrationAmount",void 0),(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"radialIntensity",void 0),(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"direction",void 0),(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"centerPosition",void 0),(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"screenWidth",void 0),(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"screenHeight",void 0),(0,rv.H)("BABYLON.ChromaticAberrationPostProcess",ChromaticAberrationPostProcess);let l6=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float depth=texture2D(depthSampler,vUV).r; +#define CUSTOM_COC_DEPTH +float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; +#define CUSTOM_COC_PIXELDISTANCE +float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} +`;s_.v.ShadersStore.circleOfConfusionPixelShader=l6;let CircleOfConfusionPostProcess=class CircleOfConfusionPostProcess extends postProcess_PostProcess{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,r,s,n,a,null,o,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){rT.Y.Warn("No depth texture set on CircleOfConfusionPostProcess");return}e.setTexture("depthSampler",this._depthTexture);let t=this.lensSize/this.fStop,i=t*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",i);let r=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",r.minZ,r.maxZ-r.minZ)})}set depthTexture(e){this._depthTexture=e}};(0,rH.gn)([(0,rb.qC)()],CircleOfConfusionPostProcess.prototype,"lensSize",void 0),(0,rH.gn)([(0,rb.qC)()],CircleOfConfusionPostProcess.prototype,"fStop",void 0),(0,rH.gn)([(0,rb.qC)()],CircleOfConfusionPostProcess.prototype,"focusDistance",void 0),(0,rH.gn)([(0,rb.qC)()],CircleOfConfusionPostProcess.prototype,"focalLength",void 0),(0,rv.H)("BABYLON.CircleOfConfusionPostProcess",CircleOfConfusionPostProcess);let l8=`uniform sampler2D textureSampler; +uniform sampler2D colorTable; +varying vec2 vUV;const float SLICE_COUNT=16.0; +vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; +float slicePixelSize=sliceSize/width; +float sliceInnerSize=slicePixelSize*(width-1.0); +float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;s_.v.ShadersStore.colorCorrectionPixelShader=l8;let ColorCorrectionPostProcess=class ColorCorrectionPostProcess extends postProcess_PostProcess{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,s,n,a){super(e,"colorCorrection",null,["colorTable"],i,r,s,n,a);let o=(null==r?void 0:r.getScene())||null;this._colorTableTexture=new texture_Texture(t,o,!0,!1,texture_Texture.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new ColorCorrectionPostProcess(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],ColorCorrectionPostProcess.prototype,"colorTableUrl",void 0),(0,rv.H)("BABYLON.ColorCorrectionPostProcess",ColorCorrectionPostProcess);let l7=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = +texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + +texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + +texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + +texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + +texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + +texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + +texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + +texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + +texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = +kernel[0] + +kernel[1] + +kernel[2] + +kernel[3] + +kernel[4] + +kernel[5] + +kernel[6] + +kernel[7] + +kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} +gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;s_.v.ShadersStore.convolutionPixelShader=l7;let ConvolutionPostProcess=class ConvolutionPostProcess extends postProcess_PostProcess{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,s,n,a,o=0){super(e,"convolution",["kernel","screenSize"],null,i,r,s,n,a,null,o),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new ConvolutionPostProcess(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,r)}};ConvolutionPostProcess.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],ConvolutionPostProcess.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],ConvolutionPostProcess.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],ConvolutionPostProcess.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],ConvolutionPostProcess.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],ConvolutionPostProcess.GaussianKernel=[0,1,0,1,1,1,0,1,0],(0,rH.gn)([(0,rb.qC)()],ConvolutionPostProcess.prototype,"kernel",void 0),(0,rv.H)("BABYLON.ConvolutionPostProcess",ConvolutionPostProcess);let DepthOfFieldBlurPostProcess=class DepthOfFieldBlurPostProcess extends BlurPostProcess{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,s,n,a,o=null,l=texture_Texture.BILINEAR_SAMPLINGMODE,h,u,c=0,d=!1,p=5){super(e,i,r,s,n,2,h,u,c,`#define DOF 1 +`,d,p),this.direction=i,this.externalTextureSamplerBinding=!!o,this.onApplyObservable.add(e=>{null!=o&&e.setTextureFromPostProcess("textureSampler",o),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",a)})}};(0,rH.gn)([(0,rb.qC)()],DepthOfFieldBlurPostProcess.prototype,"direction",void 0),(0,rv.H)("BABYLON.DepthOfFieldBlurPostProcess",DepthOfFieldBlurPostProcess);let l9=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; +#if BLUR_LEVEL>0 +uniform sampler2D blurStep1; +#endif +#if BLUR_LEVEL>1 +uniform sampler2D blurStep2; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; +#if BLUR_LEVEL==0 +vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); +#endif +#if BLUR_LEVEL==1 +if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} +#endif +#if BLUR_LEVEL==2 +if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} +#endif +} +`;s_.v.ShadersStore.depthOfFieldMergePixelShader=l9;let DepthOfFieldMergePostProcess=class DepthOfFieldMergePostProcess extends postProcess_PostProcess{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,s,n,a,o,l,h=0,u=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,n,a,o,l,null,h,void 0,null,!0),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(r.length-i-1),t)})}),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,r,s,n){e||(e="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,r,s,n)}};(tr=rr||(rr={}))[tr.Low=0]="Low",tr[tr.Medium=1]="Medium",tr[tr.High=2]="High";let DepthOfFieldEffect=class DepthOfFieldEffect extends postProcessRenderEffect_PostProcessRenderEffect{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=rr.Low,r=0,s=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];let n=e.getEngine(),a=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new CircleOfConfusionPostProcess("circleOfConfusion",t,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,n,!1,r,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let o=1,l=15;switch(i){case rr.High:o=3,l=51;break;case rr.Medium:o=2,l=31;break;default:l=15,o=1}let h=l/Math.pow(2,o-1),u=1;for(let t=0;t<o;t++){let i=new DepthOfFieldBlurPostProcess("vertical blur",e,new rm.FM(0,1),h,u,null,this._circleOfConfusion,0==t?this._circleOfConfusion:null,texture_Texture.BILINEAR_SAMPLINGMODE,n,!1,r,s,0==t?a:5);i.autoClear=!1,u=.75/Math.pow(2,t);let o=new DepthOfFieldBlurPostProcess("horizontal blur",e,new rm.FM(1,0),h,u,null,this._circleOfConfusion,null,texture_Texture.BILINEAR_SAMPLINGMODE,n,!1,r,s);o.autoClear=!1,this._depthOfFieldBlurY.push(i),this._depthOfFieldBlurX.push(o)}this._effects=[this._circleOfConfusion];for(let e=0;e<this._depthOfFieldBlurX.length;e++)this._effects.push(this._depthOfFieldBlurY[e]),this._effects.push(this._depthOfFieldBlurX[e]);this._dofMerge=new DepthOfFieldMergePostProcess("dofMerge",this._circleOfConfusion,this._circleOfConfusion,this._depthOfFieldBlurX,u,null,texture_Texture.BILINEAR_SAMPLINGMODE,n,!1,r,s),this._dofMerge.autoClear=!1,this._effects.push(this._dofMerge)}getClassName(){return"DepthOfFieldEffect"}set depthTexture(e){this._circleOfConfusion.depthTexture=e}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){for(let e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0}};let he=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(passSampler,vUV);}`;s_.v.ShadersStore.displayPassPixelShader=he;let DisplayPassPostProcess=class DisplayPassPostProcess extends postProcess_PostProcess{getClassName(){return"DisplayPassPostProcess"}constructor(e,t,i,r,s,n){super(e,"displayPass",["passSampler"],["passSampler"],t,i,r,s,n)}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new DisplayPassPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rv.H)("BABYLON.DisplayPassPostProcess",DisplayPassPostProcess);let ht=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;s_.v.ShadersStore.filterPixelShader=ht;let FilterPostProcess=class FilterPostProcess extends postProcess_PostProcess{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,s,n,a){super(e,"filter",["kernelMatrix"],null,i,r,s,n,a),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new FilterPostProcess(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.oQ)()],FilterPostProcess.prototype,"kernelMatrix",void 0),(0,rv.H)("BABYLON.FilterPostProcess",FilterPostProcess);let hi=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); +#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) +void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); +#ifndef MALI +if(range<rangeMaxClamped) +{gl_FragColor=rgbyM;return;} +#endif +float lumaNW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNW,0.0));float lumaSE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSE,0.0));float lumaNE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNE,0.0));float lumaSW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSW,0.0));float lumaNS=lumaN+lumaS;float lumaWE=lumaW+lumaE;float subpixRcpRange=1.0/range;float subpixNSWE=lumaNS+lumaWE;float edgeHorz1=(-2.0*lumaM)+lumaNS;float edgeVert1=(-2.0*lumaM)+lumaWE;float lumaNESE=lumaNE+lumaSE;float lumaNWNE=lumaNW+lumaNE;float edgeHorz2=(-2.0*lumaE)+lumaNESE;float edgeVert2=(-2.0*lumaN)+lumaNWNE;float lumaNWSW=lumaNW+lumaSW;float lumaSWSE=lumaSW+lumaSE;float edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);float edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);float edgeHorz3=(-2.0*lumaW)+lumaNWSW;float edgeVert3=(-2.0*lumaS)+lumaSWSE;float edgeHorz=abs(edgeHorz3)+edgeHorz4;float edgeVert=abs(edgeVert3)+edgeVert4;float subpixNWSWNESE=lumaNWSW+lumaNESE;float lengthSign=texelSize.x;bool horzSpan=edgeHorz>=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) +{lumaN=lumaW;} +if (!horzSpan) +{lumaS=lumaE;} +if (horzSpan) +{lengthSign=texelSize.y;} +float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) +{lengthSign=-lengthSign;} +float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) +{posB.x+=lengthSign*0.5;} +if (horzSpan) +{posB.y+=lengthSign*0.5;} +vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) +{lumaNN=lumaSS;} +float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) +{posN.x-=offNP.x*3.0;} +if (!doneN) +{posN.y-=offNP.y*3.0;} +bool doneNP=(!doneN) || (!doneP);if (!doneP) +{posP.x+=offNP.x*3.0;} +if (!doneP) +{posP.y+=offNP.y*3.0;} +if (doneNP) +{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} +float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) +{dstN=posM.y-posN.y;} +if (!horzSpan) +{dstP=posP.y-posM.y;} +bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN<dstP;float dst=min(dstN,dstP);bool goodSpan=directionN ? goodSpanN : goodSpanP;float subpixG=subpixF*subpixF;float pixelOffset=(dst*(-spanLengthRcp))+0.5;float subpixH=subpixG*fxaaQualitySubpix;float pixelOffsetGood=goodSpan ? pixelOffset : 0.0;float pixelOffsetSubpix=max(pixelOffsetGood,subpixH);if (!horzSpan) +{posM.x+=pixelOffsetSubpix*lengthSign;} +if (horzSpan) +{posM.y+=pixelOffsetSubpix*lengthSign;} +#ifdef MALI +if(range<rangeMaxClamped) +{gl_FragColor=rgbyM;} +else +{gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);} +#else +gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0); +#endif +}`;s_.v.ShadersStore.fxaaPixelShader=hi;let hr=`attribute vec2 position;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.fxaaVertexShader=hr;let FxaaPostProcess=class FxaaPostProcess extends postProcess_PostProcess{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,r,s,n,a=0){super(e,"fxaa",["texelSize"],null,t,i,r||texture_Texture.BILINEAR_SAMPLINGMODE,s,n,null,a,"fxaa",void 0,!0);let o=this._getDefines();this.updateEffect(o),this.onApplyObservable.add(e=>{let t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)})}_getDefines(){let e=this.getEngine();if(!e)return null;let t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new FxaaPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rv.H)("BABYLON.FxaaPostProcess",FxaaPostProcess);let hs=`#include<helperFunctions> +uniform sampler2D textureSampler; +uniform float intensity;uniform float animatedSeed;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`;s_.v.ShadersStore.grainPixelShader=hs;let GrainPostProcess=class GrainPostProcess extends postProcess_PostProcess{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,s,n,null,a,void 0,null,o),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,r){return rb.p4.Parse(()=>new GrainPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],GrainPostProcess.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.qC)()],GrainPostProcess.prototype,"animated",void 0),(0,rv.H)("BABYLON.GrainPostProcess",GrainPostProcess);let hn=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;s_.v.ShadersStore.highlightsPixelShader=hn;let ha=`varying vec2 vUV;uniform sampler2D textureSampler; +#include<imageProcessingDeclaration> +#include<helperFunctions> +#include<imageProcessingFunctions> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 result=texture2D(textureSampler,vUV); +#ifdef IMAGEPROCESSING +#ifndef FROMLINEARSPACE +result.rgb=toLinearSpace(result.rgb); +#endif +result=applyImageProcessing(result); +#else +#ifdef FROMLINEARSPACE +result=applyImageProcessing(result); +#endif +#endif +gl_FragColor=result;}`;s_.v.ShadersStore.imageProcessingPixelShader=ha;let ImageProcessingPostProcess=class ImageProcessingPostProcess extends postProcess_PostProcess{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,t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){let i=t.scenes;e=i[i.length-1]}else e=rS.l.LastCreatedScene;e?this._imageProcessingConfiguration=e.imageProcessingConfiguration:this._imageProcessingConfiguration=new sv.$}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get isSupported(){let e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,s,n,a=0,o){super(e,"imageProcessing",[],[],t,i,r,s,n,null,a,"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},o?(o.applyByPostProcess=!0,this._attachImageProcessingConfiguration(o,!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(let t in this._defines)this._defines[t]&&(e+=`#define ${t}; +`);let t=["textureSampler"],i=["scale"];sv.$&&(sv.$.PrepareSamplers(t,this._defines),sv.$.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,rH.gn)([(0,rb.qC)()],ImageProcessingPostProcess.prototype,"_fromLinearSpace",void 0);let ho=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +layout(location=0) out vec4 glFragData[{X}]; +#endif +`;s_.v.IncludesShadersStore.mrtFragmentDeclaration=ho;let hl=`#extension GL_EXT_draw_buffers : require +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +precision highp float; +#ifdef BUMP +varying mat4 vWorldView;varying vec3 vNormalW; +#else +varying vec3 vNormalV; +#endif +varying vec4 vViewPos; +#if defined(POSITION) || defined(BUMP) +varying vec3 vPositionW; +#endif +#ifdef VELOCITY +varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#ifdef NEED_UV +varying vec2 vUV; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#if defined(REFLECTIVITY) +#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; +#endif +#ifdef ALBEDOTEXTURE +varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; +#endif +#ifdef REFLECTIVITYCOLOR +uniform vec3 reflectivityColor; +#endif +#ifdef ALBEDOCOLOR +uniform vec3 albedoColor; +#endif +#ifdef METALLIC +uniform float metallic; +#endif +#if defined(ROUGHNESS) || defined(GLOSSINESS) +uniform float glossiness; +#endif +#endif +#if defined(ALPHATEST) && defined(NEED_UV) +uniform sampler2D diffuseSampler; +#endif +#include<clipPlaneFragmentDeclaration> +#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT] +#include<bumpFragmentMainFunctions> +#include<bumpFragmentFunctions> +#include<helperFunctions> +void main() { +#include<clipPlaneFragment> +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +vec3 normalOutput; +#ifdef BUMP +vec3 normalW=normalize(vNormalW); +#include<bumpFragment> +#ifdef NORMAL_WORLDSPACE +normalOutput=normalW; +#else +normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); +#endif +#else +normalOutput=normalize(vNormalV); +#endif +#ifdef PREPASS +#ifdef PREPASS_DEPTH +gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); +#endif +#ifdef PREPASS_NORMAL +gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); +#endif +#else +gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); +#endif +#ifdef POSITION +gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); +#endif +#ifdef VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); +#endif +#ifdef REFLECTIVITY +vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); +#ifdef METALLICWORKFLOW +float metal=1.0;float roughness=1.0; +#ifdef ORMTEXTURE +metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; +#endif +#ifdef METALLIC +metal*=metallic; +#endif +#ifdef ROUGHNESS +roughness*=(1.0-glossiness); +#endif +reflectivity.a-=roughness;vec3 color=vec3(1.0); +#ifdef ALBEDOTEXTURE +color=texture2D(albedoSampler,vAlbedoUV).rgb; +#ifdef GAMMAALBEDO +color=toLinearSpace(color); +#endif +#endif +#ifdef ALBEDOCOLOR +color*=albedoColor.xyz; +#endif +reflectivity.rgb=mix(vec3(0.04),color,metal); +#else +#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +reflectivity=texture2D(reflectivitySampler,vReflectivityUV); +#ifdef GAMMAREFLECTIVITYTEXTURE +reflectivity.rgb=toLinearSpace(reflectivity.rgb); +#endif +#else +#ifdef REFLECTIVITYCOLOR +reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; +#endif +#endif +#ifdef GLOSSINESSS +reflectivity.a*=glossiness; +#endif +#endif +gl_FragData[REFLECTIVITY_INDEX]=reflectivity; +#endif +} +`;s_.v.ShadersStore.geometryPixelShader=hl,s_.v.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";let hh=`#include<sceneUboDeclaration> +`;s_.v.IncludesShadersStore.geometryUboDeclaration=hh;let hu=`precision highp float; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<instancesDeclaration> +#include<__decl__geometryVertex> +#include<clipPlaneVertexDeclaration> +attribute vec3 position;attribute vec3 normal; +#ifdef NEED_UV +varying vec2 vUV; +#ifdef ALPHATEST +uniform mat4 diffuseMatrix; +#endif +#ifdef BUMP +uniform mat4 bumpMatrix;varying vec2 vBumpUV; +#endif +#ifdef REFLECTIVITY +uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#ifdef BUMP +varying mat4 vWorldView; +#endif +#ifdef BUMP +varying vec3 vNormalW; +#else +varying vec3 vNormalV; +#endif +varying vec4 vViewPos; +#if defined(POSITION) || defined(BUMP) +varying vec3 vPositionW; +#endif +#ifdef VELOCITY +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position;vec3 normalUpdated=normal; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); +#ifdef BUMP +vWorldView=view*finalWorld;vNormalW=normalUpdated; +#else +#ifdef NORMAL_WORLDSPACE +vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0))); +#else +vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); +#endif +#endif +vViewPos=view*worldPos; +#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +#if defined(POSITION) || defined(BUMP) +vPositionW=worldPos.xyz/worldPos.w; +#endif +gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#include<clipPlaneVertex> +#ifdef NEED_UV +#ifdef UV1 +#if defined(ALPHATEST) && defined(ALPHATEST_UV1) +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#else +vUV=uv; +#endif +#ifdef BUMP_UV1 +vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef REFLECTIVITY_UV1 +vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef ALBEDO_UV1 +vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#endif +#ifdef UV2 +#if defined(ALPHATEST) && defined(ALPHATEST_UV2) +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#else +vUV=uv2; +#endif +#ifdef BUMP_UV2 +vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); +#endif +#ifdef REFLECTIVITY_UV2 +vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); +#endif +#ifdef ALBEDO_UV2 +vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#endif +#include<bumpVertex> +} +`;s_.v.ShadersStore.geometryVertexShader=hu;let hc=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,nX.qx)(hc);let GeometryBufferRenderer=class GeometryBufferRenderer{_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===GeometryBufferRenderer.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===GeometryBufferRenderer.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===GeometryBufferRenderer.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 GeometryBufferRenderer.POSITION_TEXTURE_TYPE:return this._positionIndex;case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case GeometryBufferRenderer.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case GeometryBufferRenderer.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return -1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return this._ratio}constructor(e,t=1,i=15){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new rg.HE(0,0,0,0),this._clearDepthColor=new rg.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,GeometryBufferRenderer._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){let i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;let r=[],s=[rz.o.PositionKind,rz.o.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&MaterialFlags.BumpTextureEnabled&&(r.push("#define BUMP"),r.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&r.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&r.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&r.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&r.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}e&&(r.push("#define NEED_UV"),n.isVerticesDataPresent(rz.o.UVKind)&&(s.push(rz.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(rz.o.UV2Kind)&&(s.push(rz.o.UV2Kind),r.push("#define UV2")))}this._linkedWithPrePass&&(r.push("#define PREPASS"),-1!==this._depthIndex&&(r.push("#define DEPTH_INDEX "+this._depthIndex),r.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(r.push("#define NORMAL_INDEX "+this._normalIndex),r.push("#define PREPASS_NORMAL"))),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),n.useBones&&n.computeBonesUsingShaders?(s.push(rz.o.MatricesIndicesKind),s.push(rz.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(rz.o.MatricesIndicesExtraKind),s.push(rz.o.MatricesWeightsExtraKind)),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");let a=n.morphTargetManager,o=0;a&&a.numInfluencers>0&&(o=a.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+o),a.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),so.G.PrepareAttributesForMorphTargetsInfluencers(s,n,o)),t&&(r.push("#define INSTANCES"),so.G.PushAttributesForInstances(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):r.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),(0,nX.lK)(i,this._scene,r);let l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),u=h.defines,c=r.join("\n");return u!==c&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:hc,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets"],defines:c,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:o}},l),c),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){if(this._resizeObserver){let e=this._scene.getEngine();e.onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null}this.getGBuffer().dispose()}_assignRenderTargetIndices(){let e=[],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(){let e=this._scene.getEngine(),[t,i]=this._assignRenderTargetIndices(),r=0;if(e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2),this._multiRenderTarget=new MultiRenderTarget("gBuffer",{width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio},t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:r,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;let s=[!0],n=[!1],a=[!0];for(let e=1;e<t;++e)s.push(!0),a.push(!1),n.push(!0);let o=e.buildTextureLayout(s),l=e.buildTextureLayout(n),h=e.buildTextureLayout(a);this._multiRenderTarget.onClearObservable.add(e=>{e.bindAttachments(this.useSpecificClearForDepthTexture?l:o),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(h),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(o)}),this._resizeObserver=e.onResizeObservable.add(()=>{this._multiRenderTarget&&this._multiRenderTarget.resize({width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio})});let renderSubMesh=e=>{let t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:rm.y3.Identity(),viewProjection:r.getTransformMatrix()},t.skeleton)){let e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}let a=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;let o=s.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,o)){let h;let u=e._getDrawWrapper();if(!u)return;let c=u.effect;s.enableEffect(u),o||t._bind(e,c,n.fillMode),this._useUbo?(so.G.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("view",r.getViewMatrix()));let d=t._instanceDataStorage;if(!d.isFrozen&&(n.backFaceCulling||null!==t.overrideMaterialSideOrientation)){let e=i._getWorldMatrixDeterminant();null===(h=t.overrideMaterialSideOrientation)&&(h=n.sideOrientation),e<0&&(h=h===sr.F.ClockWiseSideOrientation?sr.F.CounterClockWiseSideOrientation:sr.F.ClockWiseSideOrientation)}else h=d.sideOrientation;if(n._preBind(u,h),n.needAlphaTesting()){let e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}n.bumpTexture&&r.getEngine().getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),(0,nX.an)(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&(c.setMatrices("mBones",t.skeleton.getTransformMatrices(t)),this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])),so.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)),o&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,a,o,(e,t)=>{e||c.setMatrix("world",t)})}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,r)=>{if((r||0===i)&&t.subMeshes)for(let i=0;i<t.subMeshes.length;++i){let r=t.subMeshes[i],s=r.getMaterial(),n=r.getRenderingMesh();if(!s)continue;let a=n._getInstancesRenderList(r._id,!!r.getReplacementMesh()),o=e.getCaps().instancedArrays&&(null!==a.visibleInstances[r._id]||n.hasThinInstances);if(!this.isReady(r,o))return!1}return!0},this._multiRenderTarget.customRenderFunction=(t,i,r,s)=>{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),n=0;n<s.length;n++)renderSubMesh(s.data[n]);e.setColorWrite(!0)}for(n=0;n<t.length;n++)renderSubMesh(t.data[n]);for(e.setDepthWrite(!1),n=0;n<i.length;n++)renderSubMesh(i.data[n]);if(this.renderTransparentMeshes)for(n=0;n<r.length;n++)renderSubMesh(r.data[n]);e.setDepthWrite(!0)}}_copyBonesTransformationMatrices(e,t){for(let i=0;i<e.length;i++)t[i]=e[i];return t}};GeometryBufferRenderer.DEPTH_TEXTURE_TYPE=0,GeometryBufferRenderer.NORMAL_TEXTURE_TYPE=1,GeometryBufferRenderer.POSITION_TEXTURE_TYPE=2,GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE=3,GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE=4,GeometryBufferRenderer._SceneComponentInitialization=e=>{throw(0,r$.S)("GeometryBufferRendererSceneComponent")};let MotionBlurConfiguration=class MotionBlurConfiguration{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}};Object.defineProperty(rN.x.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),rN.x.prototype.enableGeometryBufferRenderer=function(e=1,t=15){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new GeometryBufferRenderer(this,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},rN.x.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};let GeometryBufferRendererSceneComponent=class GeometryBufferRendererSceneComponent{constructor(e){this.name=rQ.l.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(rQ.l.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}};GeometryBufferRenderer._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_GEOMETRYBUFFERRENDERER);t||(t=new GeometryBufferRendererSceneComponent(e),e._addComponent(t))};let hd=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; +#ifdef OBJECT_BASED +uniform sampler2D velocitySampler; +#else +uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#ifdef GEOMETRY_SUPPORTED +#ifdef OBJECT_BASED +vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) +{if (i>=samplesCount) +break;vec2 offset=vUV+velocity*(hlim+float(i)); +#if defined(WEBGPU) +result+=texture2DLodEXT(textureSampler,offset,0.0); +#else +result+=texture2D(textureSampler,offset); +#endif +} +gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; +#else +vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; +vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) {if (i>=nSamples) +break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); +#if defined(WEBGPU) +result+=texture2DLodEXT(textureSampler,offset1,0.0); +#else +result+=texture2D(textureSampler,offset1); +#endif +} +gl_FragColor=result/float(nSamples); +#endif +#else +gl_FragColor=texture2D(textureSampler,vUV); +#endif +} +`;s_.v.ShadersStore.motionBlurPixelShader=hd;let MotionBlurPostProcess=class MotionBlurPostProcess extends postProcess_PostProcess{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,s,n,a,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",o,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new MotionBlurConfiguration)),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}let 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 rT.Y.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=rm.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 rm.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){let t=rm.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 rm.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){let e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new MotionBlurPostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],MotionBlurPostProcess.prototype,"motionStrength",void 0),(0,rH.gn)([(0,rb.qC)()],MotionBlurPostProcess.prototype,"motionBlurSamples",null),(0,rH.gn)([(0,rb.qC)()],MotionBlurPostProcess.prototype,"isObjectBased",null),(0,rv.H)("BABYLON.MotionBlurPostProcess",MotionBlurPostProcess),s_.v.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";let RefractionPostProcess=class RefractionPostProcess extends postProcess_PostProcess{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,s,n,a,o,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,a,o,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add(e=>{this._refTexture=this._refTexture||new texture_Texture(t,e.getScene())}),this.onApplyObservable.add(e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new RefractionPostProcess(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],RefractionPostProcess.prototype,"color",void 0),(0,rH.gn)([(0,rb.qC)()],RefractionPostProcess.prototype,"depth",void 0),(0,rH.gn)([(0,rb.qC)()],RefractionPostProcess.prototype,"colorLevel",void 0),(0,rH.gn)([(0,rb.qC)()],RefractionPostProcess.prototype,"refractionTextureUrl",void 0),(0,rv.H)("BABYLON.RefractionPostProcess",RefractionPostProcess);let hp=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + +texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + +texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + +texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - +color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;s_.v.ShadersStore.sharpenPixelShader=hp;let SharpenPostProcess=class SharpenPostProcess extends postProcess_PostProcess{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,s,n,null,a,void 0,null,o),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,r){return rb.p4.Parse(()=>new SharpenPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],SharpenPostProcess.prototype,"colorAmount",void 0),(0,rH.gn)([(0,rb.qC)()],SharpenPostProcess.prototype,"edgeAmount",void 0),(0,rv.H)("BABYLON.SharpenPostProcess",SharpenPostProcess);let postProcessRenderPipeline_PostProcessRenderPipeline=class postProcessRenderPipeline_PostProcessRenderPipeline{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=[],this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(let 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){let i=this._renderEffects[e];i&&i._enable(rW.w1.MakeArray(t||this._cameras))}_disableEffect(e,t){let i=this._renderEffects[e];i&&i._disable(rW.w1.MakeArray(t||this._cameras))}_attachCameras(e,t){let i;let r=rW.w1.MakeArray(e||this._cameras);if(!r)return;let s=[];for(i=0;i<r.length;i++){let e=r[i];e&&(-1===this._cameras.indexOf(e)?this._cameras.push(e):t&&s.push(i))}for(i=0;i<s.length;i++)r.splice(s[i],1);for(let e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._attachCameras(r)}_detachCameras(e){let t=rW.w1.MakeArray(e||this._cameras);if(t){for(let e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._detachCameras(t);for(let e=0;e<t.length;e++)this._cameras.splice(this._cameras.indexOf(t[e]),1)}}_update(){for(let e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._update();for(let e=0;e<this._cameras.length;e++){if(!this._cameras[e])continue;let t=this._cameras[e].name;this._renderEffectsForIsolatedPass[t]&&this._renderEffectsForIsolatedPass[t]._update()}}_reset(){this._renderEffects={},this._renderEffectsForIsolatedPass=[]}_enableMSAAOnFirstPostProcess(e){if(!this._engine._features.supportMSAA)return!1;let t=Object.keys(this._renderEffects);if(t.length>0){let i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){let e=Object.keys(this._renderEffects);for(let t of e){let e=this._renderEffects[t].getPostProcesses();if(e)for(let t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}};(0,rH.gn)([(0,rb.qC)()],postProcessRenderPipeline_PostProcessRenderPipeline.prototype,"_name",void 0);let PostProcessRenderPipelineManager=class PostProcessRenderPipelineManager{constructor(){this._renderPipelines={}}get supportedPipelines(){let e=[];for(let t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){let 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){let r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){let i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t._rebuild()}}dispose(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.dispose()}}};Object.defineProperty(rN.x.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(rQ.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new PostProcessRenderPipelineManagerSceneComponent(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new PostProcessRenderPipelineManager}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});let PostProcessRenderPipelineManagerSceneComponent=class PostProcessRenderPipelineManagerSceneComponent{constructor(e){this.name=rQ.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(rQ.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()}};let DefaultRenderingPipeline=class DefaultRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{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(){let e=this.bloom;this.bloom=new BloomEffect(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;t<this._cameras.length;t++)e.disposeEffects(this._cameras[t])}get depthOfFieldEnabled(){return this._depthOfFieldEnabled}set depthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get depthOfFieldBlurLevel(){return this._depthOfFieldBlurLevel}set depthOfFieldBlurLevel(e){if(this._depthOfFieldBlurLevel===e)return;this._depthOfFieldBlurLevel=e;let t=this.depthOfField;this.depthOfField=new DepthOfFieldEffect(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!1),this.depthOfField.focalLength=t.focalLength,this.depthOfField.focusDistance=t.focusDistance,this.depthOfField.fStop=t.fStop,this.depthOfField.lensSize=t.lensSize;for(let e=0;e<this._cameras.length;e++)t.disposeEffects(this._cameras[e]);this._buildPipeline()}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}set imageProcessingEnabled(e){this._imageProcessingEnabled!==e&&(this._scene.imageProcessingConfiguration.isEnabled=e)}get imageProcessingEnabled(){return this._imageProcessingEnabled}set glowLayerEnabled(e){e&&!this._glowLayer?this._glowLayer=new GlowLayer("",this._scene):!e&&this._glowLayer&&(this._glowLayer.dispose(),this._glowLayer=null)}get glowLayerEnabled(){return null!=this._glowLayer}get glowLayer(){return this._glowLayer}set chromaticAberrationEnabled(e){this._chromaticAberrationEnabled!==e&&(this._chromaticAberrationEnabled=e,this._buildPipeline())}get chromaticAberrationEnabled(){return this._chromaticAberrationEnabled}set grainEnabled(e){this._grainEnabled!==e&&(this._grainEnabled=e,this._buildPipeline())}get grainEnabled(){return this._grainEnabled}constructor(e="",t=!0,i=rS.l.LastCreatedScene,r,s=!0){super(i.getEngine(),e),this._camerasToBeAttached=[],this.SharpenPostProcessId="SharpenPostProcessEffect",this.ImageProcessingPostProcessId="ImageProcessingPostProcessEffect",this.FxaaPostProcessId="FxaaPostProcessEffect",this.ChromaticAberrationPostProcessId="ChromaticAberrationPostProcessEffect",this.GrainPostProcessId="GrainPostProcessEffect",this._glowLayer=null,this.animations=[],this._imageProcessingConfigurationObserver=null,this._sharpenEnabled=!1,this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._depthOfFieldBlurLevel=rr.Low,this._fxaaEnabled=!1,this._imageProcessingEnabled=!0,this._bloomScale=.5,this._chromaticAberrationEnabled=!1,this._grainEnabled=!1,this._buildAllowed=!0,this.onBuildObservable=new rf.y$,this._resizeObserver=null,this._hardwareScaleLevel=1,this._bloomKernel=64,this._bloomWeight=.15,this._bloomThreshold=.9,this._samples=1,this._hasCleared=!1,this._prevPostProcess=null,this._prevPrevPostProcess=null,this._depthOfFieldSceneObserver=null,this._activeCameraChangedObserver=null,this._activeCamerasChangedObserver=null,this._cameras=r||i.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._buildAllowed=s,this._scene=i;let n=this._scene.getEngine().getCaps();this._hdr=t&&(n.textureHalfFloatRender||n.textureFloatRender),this._hdr?n.textureHalfFloatRender?this._defaultPipelineTextureType=2:n.textureFloatRender&&(this._defaultPipelineTextureType=1):this._defaultPipelineTextureType=0,i.postProcessRenderPipelineManager.addPipeline(this);let a=this._scene.getEngine();this.sharpen=new SharpenPostProcess("sharpen",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._sharpenEffect=new postProcessRenderEffect_PostProcessRenderEffect(a,this.SharpenPostProcessId,()=>this.sharpen,!0),this.depthOfField=new DepthOfFieldEffect(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 BloomEffect(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new ChromaticAberrationPostProcess("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,texture_Texture.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new postProcessRenderEffect_PostProcessRenderEffect(a,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new GrainPostProcess("Grain",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new postProcessRenderEffect_PostProcessRenderEffect(a,this.GrainPostProcessId,()=>this.grain,!0);let o=!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,o?rW.w1.SetImmediate(()=>{this._buildPipeline()}):this._buildPipeline())}),this._buildPipeline(),o=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){let 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;let 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(let e of this._cameras){let t=this._scene.enableDepthRenderer(e);t.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);let 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 ImageProcessingPostProcess("imageProcessing",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(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 FxaaPostProcess("fxaa",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e,this.FxaaPostProcessId,()=>this.fxaa,!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add(()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)})),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add(()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)})),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&rT.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;t<this._cameras.length;t++){let i=this._cameras[t];this.imageProcessing&&this.imageProcessing.dispose(i),this.fxaa&&this.fxaa.dispose(i),e&&(this.sharpen&&this.sharpen.dispose(i),this.depthOfField&&(this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver),this.depthOfField.disposeEffects(i)),this.bloom&&this.bloom.disposeEffects(i),this.chromaticAberration&&this.chromaticAberration.dispose(i),this.grain&&this.grain.dispose(i),this._glowLayer&&this._glowLayer.dispose())}this.imageProcessing=null,this.fxaa=null,e&&(this.sharpen=null,this._sharpenEffect=null,this.depthOfField=null,this.bloom=null,this.chromaticAberration=null,this._chromaticAberrationEffect=null,this.grain=null,this._grainEffect=null,this._glowLayer=null)}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){let t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._buildAllowed=!1,this.onBuildObservable.clear(),this._disposePostProcesses(!0),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._scene._postProcessRenderPipelineManager.removePipeline(this.name),this._scene.autoClear=!0,this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver),this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver),this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver),super.dispose()}serialize(){let e=rb.p4.Serialize(this);return e.customType="DefaultRenderingPipeline",e}static Parse(e,t,i){return rb.p4.Parse(()=>new DefaultRenderingPipeline(e._name,e._name._hdr,t),e,t,i)}};(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"sharpenEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"bloomKernel",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"_bloomWeight",void 0),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"_bloomThreshold",void 0),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"_hdr",void 0),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"bloomWeight",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"bloomThreshold",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"bloomScale",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"bloomEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"depthOfFieldEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"depthOfFieldBlurLevel",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"fxaaEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"samples",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"imageProcessingEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"glowLayerEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"chromaticAberrationEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"grainEnabled",null),(0,rv.H)("BABYLON.DefaultRenderingPipeline",DefaultRenderingPipeline);let h_=`uniform sampler2D textureSampler; +uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } +else { lum_threshold=0.5+0.44*threshold; } +luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} +float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); +#ifdef PENTAGON +blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); +#else +blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); +#endif +blurred/=39.0;gl_FragColor=blurred;}`;s_.v.ShadersStore.lensHighlightsPixelShader=h_;let hf=`uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; +uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; +#define PI 3.14159265 +#define TWOPI 6.28318530 +#define inverse_focal_length 0.1 +vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) +{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} +vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } +vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} +float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} +float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} +vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} +if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} +col/=total_weight; +if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} +return col;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); +vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); +float depth=texture2D(depthSampler,distorted_coords).r; +float distance=near+(far-near)*depth; +vec4 color=texture2D(textureSampler,vUV); +float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } +float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} +float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} +else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} +if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} +if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} +`;s_.v.ShadersStore.depthOfFieldPixelShader=hf;let SSAO2Configuration=class SSAO2Configuration{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}};let hm=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSAO +float scales[16]=float[16]( +0.1, +0.11406250000000001, +0.131640625, +0.15625, +0.187890625, +0.2265625, +0.272265625, +0.325, +0.384765625, +0.4515625, +0.525390625, +0.60625, +0.694140625, +0.7890625, +0.891015625, +1.0 +);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() +{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=depth/abs(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i<SAMPLES; ++i) {vec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];samplePosition=samplePosition*correctedRadius+origin;vec4 offset=vec4(samplePosition,1.0);offset=projection*offset;offset.xyz/=offset.w;offset.xy=offset.xy*0.5+0.5;if (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {continue;} +float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} +occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} +#endif +#ifdef BLUR +uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; +#ifndef BLUR_BYPASS +uniform sampler2D depthSampler; +#ifdef BLUR_LEGACY +#define inline +float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} +#endif +#endif +void main() +{float result=0.0; +#ifdef BLUR_BYPASS +result=textureLod(textureSampler,vUV,0.0).r; +#else +#ifdef BLUR_H +vec2 step=vec2(1.0/outSize,0.0); +#else +vec2 step=vec2(0.0,1.0/outSize); +#endif +#ifdef BLUR_LEGACY +result=blur13Bilateral(textureSampler,vUV,step); +#else +float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i<samples; i+=2) +{vec2 samplePos=vUV+step*(float(i)+0.5);float sampleDepth=abs(textureLod(depthSampler,samplePos,0.0).r);float falloff=smoothstep(0.0, +float(samples), +float(samples)-abs(float(i))*soften);float minDivider=tolerance*0.5+0.003;float weight=falloff/( minDivider+abs(compareDepth-sampleDepth));result+=textureLod(textureSampler,samplePos,0.0).r*weight;weightSum+=weight;} +result/=weightSum; +#endif +#endif +gl_FragColor.rgb=vec3(result);gl_FragColor.a=1.0;} +#endif +`;s_.v.ShadersStore.ssao2PixelShader=hm;let hg=`uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);vec4 sceneColor=texture2D(originalColor,vUV);gl_FragColor=sceneColor*ssaoColor; +#define CUSTOM_FRAGMENT_MAIN_END +} +`;s_.v.ShadersStore.ssaoCombinePixelShader=hg;let SSAO2RenderingPipeline=class SSAO2RenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{set epsilon(e){this._epsilon=e,this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO())}get epsilon(){return this._epsilon}set samples(e){this._samples=e,this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO()),this._sampleSphere=this._generateHemisphere()}get samples(){return this._samples}set textureSamples(e){this._textureSamples=e,this._prePassRenderer?this._prePassRenderer.samples=e:this._originalColorPostProcess.samples=e}get textureSamples(){return this._textureSamples}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}set bypassBlur(e){let t=this._getDefinesForBlur(this.expensiveBlur,e),i=this._getSamplersForBlur(e);this._blurHPostProcess.updateEffect(t.h,null,i),this._blurVPostProcess.updateEffect(t.v,null,i),this._bypassBlur=e}get bypassBlur(){return this._bypassBlur}set expensiveBlur(e){let t=this._getDefinesForBlur(e,this._bypassBlur);this._blurHPostProcess.updateEffect(t.h),this._blurVPostProcess.updateEffect(t.v),this._expensiveBlur=e}get expensiveBlur(){return this._expensiveBlur}static get IsSupported(){let e=rS.l.LastCreatedEngine;return!!e&&e._features.supportSSAO2}get scene(){return this._scene}constructor(e,t,i,r,s=!1,n=0){var a,o;if(super(t.getEngine(),e),this.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",this.SSAORenderEffect="SSAORenderEffect",this.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",this.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",this.SSAOCombineRenderEffect="SSAOCombineRenderEffect",this.totalStrength=1,this.maxZ=100,this.minZAspect=.2,this._epsilon=.02,this._samples=8,this._textureSamples=1,this._forceGeometryBuffer=!1,this.radius=2,this.base=0,this._bypassBlur=!1,this._expensiveBlur=!0,this.bilateralSamples=16,this.bilateralSoften=0,this.bilateralTolerance=0,this._bits=new Uint32Array(1),this._scene=t,this._ratio=i,this._textureType=n,this._forceGeometryBuffer=s,!this.isSupported){rT.Y.Error("The current engine does not support SSAO 2.");return}let l=this._ratio.ssaoRatio||i,h=this._ratio.blurRatio||i;this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),(null===(a=t.geometryBufferRenderer)||void 0===a?void 0:a.generateNormalsInWorldSpace)&&console.error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!")):(t.enablePrePassRenderer(),(null===(o=t.prePassRenderer)||void 0===o?void 0:o.generateNormalsInWorldSpace)&&console.error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!")),this._createRandomTexture(),this._originalColorPostProcess=new PassPostProcess("SSAOOriginalSceneColor",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),void 0,this._textureType),this._originalColorPostProcess.samples=this.textureSamples,this._createSSAOPostProcess(1,n),this._createBlurPostProcess(l,h,this._textureType),this._createSSAOCombinePostProcess(h,this._textureType),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOOriginalSceneColorEffect,()=>this._originalColorPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e<this._scene.cameras.length;e++){let t=this._scene.cameras[e];this._originalColorPostProcess.dispose(t),this._ssaoPostProcess.dispose(t),this._blurHPostProcess.dispose(t),this._blurVPostProcess.dispose(t),this._ssaoCombinePostProcess.dispose(t)}this._randomTexture.dispose(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),super.dispose()}_rebuild(){super._rebuild()}_getSamplersForBlur(e){return e?["textureSampler"]:["textureSampler","depthSampler"]}_getDefinesForBlur(e,t){let i="#define BLUR\n";return t&&(i+="#define BLUR_BYPASS\n"),e||(i+="#define BLUR_LEGACY\n"),{h:i+"#define BLUR_H\n",v:i}}_createBlurPostProcess(e,t,i){let r=this._getDefinesForBlur(this.expensiveBlur,this.bypassBlur),s=this._getSamplersForBlur(this.bypassBlur);this._blurHPostProcess=this._createBlurFilter("BlurH",s,e,r.h,i,!0),this._blurVPostProcess=this._createBlurFilter("BlurV",s,t,r.v,i,!1)}_createBlurFilter(e,t,i,r,s,n){let a=new postProcess_PostProcess(e,"ssao2",["outSize","samples","soften","tolerance"],t,i,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,r,s);return a.onApply=e=>{if(!this._scene.activeCamera)return;let t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},a.samples=this.textureSamples,a}_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,23283064365386963e-26*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){let i=2*t*Math.PI,r=1-.85*e,s=Math.sqrt(1-r*r);return new rm.P(Math.cos(i)*s,Math.sin(i)*s,r)}_generateHemisphere(){let e;let t=this.samples,i=[],r=0;for(;r<t;){if(t<16)e=this._hemisphereSample_uniform(Math.random(),Math.random());else{let i=this._hammersley(r,t);e=this._hemisphereSample_uniform(i[0],i[1])}i.push(e.x,e.y,e.z),r++}return i}_getDefinesForSSAO(){let e=`#define SSAO +#define SAMPLES ${this.samples} +#define EPSILON ${this.epsilon.toFixed(4)}`;return e}_createSSAOPostProcess(e,t){this._sampleSphere=this._generateHemisphere();let i=this._getDefinesForSSAO();this._ssaoPostProcess=new postProcess_PostProcess("ssao2","ssao2",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","base","range","projection","near","texelSize","xViewport","yViewport","maxZ","minZAspect","depthProjection"],["randomSampler","depthSampler","normalSampler"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i,t),this._ssaoPostProcess.onApply=e=>{var t,i,r,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===rj.V.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",SSAO2RenderingPipeline.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{let n=this._scene.getEngine().getRenderWidth()/2,a=this._scene.getEngine().getRenderHeight()/2,o=null!==(t=this._scene.activeCamera.orthoLeft)&&void 0!==t?t:-n,l=null!==(i=this._scene.activeCamera.orthoRight)&&void 0!==i?i:n,h=null!==(r=this._scene.activeCamera.orthoBottom)&&void 0!==r?r:-a,u=null!==(s=this._scene.activeCamera.orthoTop)&&void 0!==s?s:a;e.setMatrix3x3("depthProjection",SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",(l-o)*.5),e.setFloat("yViewport",(u-h)*.5)}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 SSAO2Configuration)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new postProcess_PostProcess("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{let t=this._scene.activeCamera.viewport;e.setVector4("viewport",rm.jp.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){let e=new Uint8Array(65536),t=rm.FM.Zero();for(let i=0;i<e.length;)t.set(rE.R.RandomRange(0,1),rE.R.RandomRange(0,1)).normalize().scaleInPlace(255),e[i++]=Math.floor(t.x),e[i++]=Math.floor(t.y),e[i++]=0,e[i++]=255;let i=rawTexture_RawTexture.CreateRGBATexture(e,128,128,this._scene,!1,!1,2);i.name="SSAORandomTexture",i.wrapU=texture_Texture.WRAP_ADDRESSMODE,i.wrapV=texture_Texture.WRAP_ADDRESSMODE,this._randomTexture=i}serialize(){let e=rb.p4.Serialize(this);return e.customType="SSAO2RenderingPipeline",e}static Parse(e,t,i){return rb.p4.Parse(()=>new SSAO2RenderingPipeline(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}};SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"totalStrength",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"maxZ",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"minZAspect",void 0),(0,rH.gn)([(0,rb.qC)("epsilon")],SSAO2RenderingPipeline.prototype,"_epsilon",void 0),(0,rH.gn)([(0,rb.qC)("samples")],SSAO2RenderingPipeline.prototype,"_samples",void 0),(0,rH.gn)([(0,rb.qC)("textureSamples")],SSAO2RenderingPipeline.prototype,"_textureSamples",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"_forceGeometryBuffer",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"_ratio",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"_textureType",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"radius",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"base",void 0),(0,rH.gn)([(0,rb.qC)("bypassBlur")],SSAO2RenderingPipeline.prototype,"_bypassBlur",void 0),(0,rH.gn)([(0,rb.qC)("expensiveBlur")],SSAO2RenderingPipeline.prototype,"_expensiveBlur",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"bilateralSamples",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"bilateralSoften",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"bilateralTolerance",void 0),(0,rv.H)("BABYLON.SSAO2RenderingPipeline",SSAO2RenderingPipeline);let hv=`uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSAO +uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) +{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} +void main() +{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; i<SAMPLES; i++) +{ray=radiusDepth*reflect(sampleSphere[i],random);hemiRay=position+sign(dot(ray,normal))*ray;occlusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;difference=depth-occlusionDepth;occlusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));} +float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor.r=result;gl_FragColor.g=result;gl_FragColor.b=result;gl_FragColor.a=1.0;} +#endif +`;s_.v.ShadersStore.ssaoPixelShader=hv;let SSAORenderingPipeline=class SSAORenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{get scene(){return this._scene}constructor(e,t,i,r){super(t.getEngine(),e),this.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",this.SSAORenderEffect="SSAORenderEffect",this.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",this.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",this.SSAOCombineRenderEffect="SSAOCombineRenderEffect",this.totalStrength=1,this.radius=1e-4,this.area=.0075,this.fallOff=1e-6,this.base=.5,this._firstUpdate=!0,this._scene=t,this._createRandomTexture();let s=i.ssaoRatio||i,n=i.combineRatio||i;this._originalColorPostProcess=new PassPostProcess("SSAOOriginalSceneColor",n,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1),this._createSSAOPostProcess(s),this._createBlurPostProcess(s),this._createSSAOCombinePostProcess(n),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOOriginalSceneColorEffect,()=>this._originalColorPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){for(let i of(super._attachCameras(e,t),this._cameras))this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e<this._scene.cameras.length;e++){let t=this._scene.cameras[e];this._originalColorPostProcess.dispose(t),this._ssaoPostProcess.dispose(t),this._blurHPostProcess.dispose(t),this._blurVPostProcess.dispose(t),this._ssaoCombinePostProcess.dispose(t)}this._randomTexture.dispose(),e&&this._scene.disableDepthRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),super.dispose()}_createBlurPostProcess(e){this._blurHPostProcess=new BlurPostProcess("BlurH",new rm.FM(1,0),16,e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,0),this._blurVPostProcess=new BlurPostProcess("BlurV",new rm.FM(0,1),16,e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,0),this._blurHPostProcess.onActivateObservable.add(()=>{let e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e}),this._blurVPostProcess.onActivateObservable.add(()=>{let e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e})}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){let 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 postProcess_PostProcess("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,texture_Texture.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 postProcess_PostProcess("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",rm.jp.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){let e=new Uint8Array(1048576);for(let t=0;t<e.length;)e[t++]=Math.floor(255*Math.max(0,rE.R.RandomRange(-1,1))),e[t++]=Math.floor(255*Math.max(0,rE.R.RandomRange(-1,1))),e[t++]=Math.floor(255*Math.max(0,rE.R.RandomRange(-1,1))),e[t++]=255;let t=rawTexture_RawTexture.CreateRGBATexture(e,512,512,this._scene,!1,!1,2);t.name="SSAORandomTexture",t.wrapU=texture_Texture.WRAP_ADDRESSMODE,t.wrapV=texture_Texture.WRAP_ADDRESSMODE,this._randomTexture=t}};(0,rH.gn)([(0,rb.qC)()],SSAORenderingPipeline.prototype,"totalStrength",void 0),(0,rH.gn)([(0,rb.qC)()],SSAORenderingPipeline.prototype,"radius",void 0),(0,rH.gn)([(0,rb.qC)()],SSAORenderingPipeline.prototype,"area",void 0),(0,rH.gn)([(0,rb.qC)()],SSAORenderingPipeline.prototype,"fallOff",void 0),(0,rH.gn)([(0,rb.qC)()],SSAORenderingPipeline.prototype,"base",void 0);let ScreenSpaceReflectionsConfiguration=class ScreenSpaceReflectionsConfiguration{constructor(){this.enabled=!1,this.name="screenSpaceReflections",this.texturesRequired=[6,3,1]}};let hx=`uniform sampler2D textureSampler; +#ifdef SSR_SUPPORTED +uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler; +#endif +uniform mat4 view;uniform mat4 projection;uniform float stepSize;uniform float strength;uniform float threshold;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;varying vec2 vUV; +#ifdef SSR_SUPPORTED +struct ReflectionInfo {vec3 color;vec4 coords;};/** +* According to specular,see https: +*/ +vec3 fresnelSchlick(float cosTheta,vec3 F0) +{return F0+(1.0-F0)*pow(1.0-cosTheta,5.0);} +/** +* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit +* by sampling multiple reflection pixels. +*/ +ReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord) +{ReflectionInfo info;info.color=vec3(0.0);vec4 projectedCoord;float sampledDepth;for(int i=0; i<SMOOTH_STEPS; i++) +{projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z;dir*=0.5;if(depth>0.0) +hitCoord-=dir;else +hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} +projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} +/** +* Tests the given world position (hitCoord) according to the given reflection vector (dir) +* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). +*/ +ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) +{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i<REFLECTION_SAMPLES; i++) +{hitCoord+=dir;projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z; +#ifdef RIGHT_HANDED_SCENE +depth*=-1.0; +#endif +if(((depth-dir.z)<threshold) && depth<=0.0) +{ +#ifdef ENABLE_SMOOTH_REFLECTIONS +return smoothReflectionInfo(dir,hitCoord); +#else +info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info; +#endif +}} +info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info;} +vec3 hash(vec3 a) +{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} +#endif +void main() +{ +#ifdef SSR_SUPPORTED +vec4 albedoFull=texture2D(textureSampler,vUV);vec3 albedo=albedoFull.rgb;float spec=texture2D(reflectivitySampler,vUV).r;if (spec==0.0) {gl_FragColor=albedoFull;return;} +vec3 normal=(texture2D(normalSampler,vUV)).xyz;vec3 position=(view*texture2D(positionSampler,vUV)).xyz;vec3 reflected=normalize(reflect(normalize(position),normalize(normal)));float roughness=1.0-texture2D(reflectivitySampler,vUV).a;vec3 jitt=mix(vec3(0.0),hash(position),roughness)*roughnessFactor;ReflectionInfo info=getReflectionInfo(jitt+reflected,position);vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-info.coords.xy));float screenEdgefactor=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);vec3 F0=vec3(0.04);F0 =mix(F0,albedo,spec);vec3 fresnel=fresnelSchlick(max(dot(normalize(normal),normalize(position)),0.0),F0); +#ifdef RIGHT_HANDED_SCENE +reflected.z*=-1.0; +#endif +float reflectionMultiplier=clamp(pow(spec*strength,reflectionSpecularFalloffExponent)*screenEdgefactor*reflected.z,0.0,0.9);float albedoMultiplier=1.0-reflectionMultiplier;vec3 SSR=info.color*fresnel;gl_FragColor=vec4((albedo*albedoMultiplier)+(SSR*reflectionMultiplier),albedoFull.a); +#else +gl_FragColor=texture2D(textureSampler,vUV); +#endif +} +`;s_.v.ShadersStore.screenSpaceReflectionPixelShader=hx;let ScreenSpaceReflectionPostProcess=class ScreenSpaceReflectionPostProcess extends postProcess_PostProcess{get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"ScreenSpaceReflectionPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1,h=!1){if(super(e,"screenSpaceReflection",["projection","view","threshold","reflectionSpecularFalloffExponent","strength","stepSize","roughnessFactor"],["textureSampler","normalSampler","positionSampler","reflectivitySampler"],i,r,s,n,a,"#define SSR_SUPPORTED\n#define REFLECTION_SAMPLES 64\n#define SMOOTH_STEPS 5\n",o,void 0,null,l),this.threshold=1.2,this.strength=1,this.reflectionSpecularFalloffExponent=3,this.step=1,this.roughnessFactor=.2,this._forceGeometryBuffer=!1,this._enableSmoothReflections=!1,this._reflectionSamples=64,this._smoothSteps=5,this._forceGeometryBuffer=h,this._forceGeometryBuffer){let e=t.enableGeometryBufferRenderer();e&&e.isSupported&&(e.enablePosition=!0,e.enableReflectivity=!0,e.generateNormalsInWorldSpace&&console.error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"))}else{let e=t.enablePrePassRenderer();null==e||e.markAsDirty(),(null==e?void 0:e.generateNormalsInWorldSpace)&&console.error("ScreenSpaceReflectionPostProcess does not support generateNormalsInWorldSpace=true for the prepass renderer!"),this._prePassEffectConfiguration=new ScreenSpaceReflectionsConfiguration}this._updateEffectDefines(),this.onApply=e=>{let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(!r&&!i)return;if(i){let t=i.getTextureIndex(GeometryBufferRenderer.POSITION_TEXTURE_TYPE),r=i.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[r])}else if(r){let t=r.getIndex(1),i=r.getIndex(3),s=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[s]),e.setTexture("positionSampler",r.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",r.getRenderTarget().textures[i])}let s=t.activeCamera;if(!s)return;let n=s.getViewMatrix(!0),a=s.getProjectionMatrix(!0);e.setMatrix("projection",a),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){let 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,r){return rb.p4.Parse(()=>new ScreenSpaceReflectionPostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"threshold",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"strength",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"reflectionSpecularFalloffExponent",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"step",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"roughnessFactor",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"enableSmoothReflections",null),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"reflectionSamples",null),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"smoothSteps",null),(0,rv.H)("BABYLON.ScreenSpaceReflectionPostProcess",ScreenSpaceReflectionPostProcess);let hT=`uniform sampler2D textureSampler;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +#if defined(PASS_POST_PROCESS) +void main(void) +{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} +#endif +#if defined(DOWN_SAMPLE_X4) +uniform vec2 dsOffsets[16];void main(void) +{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} +#endif +#if defined(BRIGHT_PASS) +uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) +{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminance<brightThreshold) {average=vec4(0.0,0.0,0.0,1.0);} +gl_FragColor=average;} +#endif +#if defined(TEXTURE_ADDER) +uniform sampler2D otherSampler;uniform sampler2D lensSampler;uniform float exposure;void main(void) +{vec3 colour=texture2D(textureSampler,vUV).rgb;colour*=exposure;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;colour+=colour*texture2D(lensSampler,vUV).rgb;vec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);gl_FragColor=finalColor;} +#endif +#if defined(VLS) +#define PI 3.1415926535897932384626433832795 +uniform mat4 shadowViewProjection;uniform mat4 lightWorld;uniform vec3 cameraPosition;uniform vec3 sunDirection;uniform vec3 sunColor;uniform vec2 depthValues;uniform float scatteringCoefficient;uniform float scatteringPower;uniform sampler2D shadowMapSampler;uniform sampler2D positionSampler;float computeScattering(float lightDotView) +{float result=1.0-scatteringCoefficient*scatteringCoefficient;result/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));return result;} +void main(void) +{vec3 worldPos=texture2D(positionSampler,vUV).rgb;vec3 startPosition=cameraPosition;vec3 rayVector=worldPos-startPosition;float rayLength=length(rayVector);vec3 rayDirection=rayVector/rayLength;float stepLength=rayLength/NB_STEPS;vec3 stepL=rayDirection*stepLength;vec3 currentPosition=startPosition;vec3 accumFog=vec3(0.0);for (int i=0; i<int(NB_STEPS); i++) +{vec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);float depthMetric= (worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depthMetric,0.0,1.0);worldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;worldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);float shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;if (shadowMapValue>shadowPixelDepth) +accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} +accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} +#endif +#if defined(VLSMERGE) +uniform sampler2D originalSampler;void main(void) +{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} +#endif +#if defined(LUMINANCE) +uniform vec2 lumOffsets[4];void main() +{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) +{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); +#ifdef WEIGHTED_AVERAGE +float GreyValue=dot(color.rgb,weight); +#endif +#ifdef BRIGHTNESS +float GreyValue=max(color.r,max(color.g,color.b)); +#endif +#ifdef HSL_COMPONENT +float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); +#endif +#ifdef MAGNITUDE +float GreyValue=length(color.rgb); +#endif +maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} +average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} +#endif +#if defined(LUMINANCE_DOWN_SAMPLE) +uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; +#ifdef FINAL_DOWN_SAMPLER +#include<packingFunctions> +#endif +void main() +{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) +{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} +average/=9.0; +#ifdef FINAL_DOWN_SAMPLER +gl_FragColor=pack(average); +#else +gl_FragColor=vec4(average,average,0.0,1.0); +#endif +} +#endif +#if defined(HDR) +uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() +{vec4 color=texture2D(textureAdderSampler,vUV); +#ifndef AUTO_EXPOSURE +vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; +#endif +gl_FragColor=color;} +#endif +#if defined(LENS_FLARE) +#define GHOSTS 3 +uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) +{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} +float noise(in vec2 p) +{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), +hash(i+vec2(1.0,0.0)),u.x), +mix(hash(i+vec2(0.0,1.0)), +hash(i+vec2(1.0,1.0)),u.x),u.y);} +float fbm(vec2 p) +{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} +vec3 pattern(vec2 uv) +{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} +float luminance(vec3 color) +{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} +vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) +{return vec4( +texture2D(tex,texcoord+direction*distortion.r).r, +texture2D(tex,texcoord+direction*distortion.g).g, +texture2D(tex,texcoord+direction*distortion.b).b, +1.0 +);} +void main(void) +{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i<GHOSTS; ++i) +{vec2 offset=fract(uv+ghostDir*ghostIndice);float weight=length(vec2(0.5)-offset)/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;ghostIndice+=1.0;} +vec2 haloVec=normalize(ghostDir)*haloWidth;float weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;result*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));gl_FragColor=result;} +#endif +#if defined(LENS_FLARE_COMPOSE) +uniform sampler2D otherSampler;uniform sampler2D lensDirtSampler;uniform sampler2D lensStarSampler;uniform mat4 lensStarMatrix;void main(void) +{vec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;vec4 lensMod=texture2D(lensDirtSampler,vUV);lensMod+=texture2D(lensStarSampler,vUV/*lensFlareCoords*/);vec4 result=texture2D(textureSampler,vUV)*lensMod;gl_FragColor=texture2D(otherSampler,vUV)+result;} +#endif +#if defined(DEPTH_OF_FIELD) +uniform sampler2D otherSampler;uniform sampler2D depthSampler;uniform float distance;void main(void) +{vec4 sharp=texture2D(otherSampler,vUV);vec4 blur=texture2D(textureSampler,vUV);float dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);float factor=0.0;if (dist<0.05) +factor=1.0;else if (dist<0.1) +factor=20.0*(0.1-dist);else if (dist<0.5) +factor=0.0;else +factor=2.0*(dist-0.5);factor=clamp(factor,0.0,0.90);gl_FragColor=mix(sharp,blur,factor);} +#endif +#if defined(MOTION_BLUR) +uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform vec2 screenSize;uniform float motionScale;uniform float motionStrength;uniform sampler2D depthSampler;void main(void) +{vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=cpos*inverseViewProjection;vec4 ppos=cpos*prevViewProjection;ppos.xyz/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {if (i>=nSamples) +break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} +gl_FragColor=result/float(nSamples);} +#endif +`;s_.v.ShadersStore.standardPixelShader=hT;let StandardRenderingPipeline=class StandardRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{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){let 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){let 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){let e=this._scene.enableGeometryBufferRenderer();if(!e){rT.Y.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");return}}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){let 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 ScreenSpaceReflectionPostProcess("HDRPass",t,e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new postProcess_PostProcess("HDRPass","standard",[],[],e,null,texture_Texture.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 postProcessRenderEffect_PostProcessRenderEffect(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 postProcess_PostProcess("HDRDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new postProcess_PostProcess("HDRVLSFinal","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new postProcess_PostProcess("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new postProcess_PostProcess("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(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 FxaaPostProcess("fxaa",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&rT.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){let i=Array(32);this.downSampleX4PostProcess=new postProcess_PostProcess("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0,r=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/r),i[t+1]=(n+.5)*(1/s),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){let i=Array(8);this.brightPassPostProcess=new postProcess_PostProcess("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{let t=1/this.brightPassPostProcess.width,r=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*r,i[2]=.5*t,i[3]=.5*r,i[4]=-.5*t,i[5]=-.5*r,i[6]=.5*t,i[7]=-.5*r,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){let s=e.getEngine(),n=new BlurPostProcess("HDRBlurH_"+i,new rm.FM(1,0),this[r],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),a=new BlurPostProcess("HDRBlurV_"+i,new rm.FM(0,1),this[r],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add(()=>{let e=n.width/s.getRenderWidth();n.kernel=this[r]*e}),a.onActivateObservable.add(()=>{let e=a.height/s.getRenderHeight();a.kernel=this.horizontalBlur?64*e:this[r]*e}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBlurH"+i,()=>n,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBlurV"+i,()=>a,!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(a)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new postProcess_PostProcess("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,texture_Texture.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 postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){let i=e.enableGeometryBufferRenderer();i.enablePosition=!0;let r=i.getGBuffer();this.volumetricLightPostProcess=new postProcess_PostProcess("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));let s=rm.FM.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){let t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new postProcess_PostProcess("HDRVLSMerge","standard",[],["originalSampler"],t,null,texture_Texture.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 postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,StandardRenderingPipeline.LuminanceSteps);this.luminancePostProcess=new postProcess_PostProcess("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);let r=[];this.luminancePostProcess.onApply=e=>{let t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;r[0]=-.5*t,r[1]=.5*i,r[2]=.5*t,r[3]=.5*i,r[4]=-.5*t,r[5]=-.5*i,r[6]=.5*t,r[7]=-.5*i,e.setArray2("lumOffsets",r)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let r=StandardRenderingPipeline.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let s="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(s+="#define FINAL_DOWN_SAMPLER");let n=new postProcess_PostProcess("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,t);this.luminanceDownSamplePostProcesses.push(n)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((t,i)=>{let r=Array(18);t.onApply=e=>{if(!s)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)r[n]=e/s.width,r[n+1]=t/s.height,n+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{let t=e.getEngine().readPixels(0,0,1,1),i=new rm.Lt(6030862941101084e-23,1/65025,1/255,1);t.then(e=>{let 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 postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLuminanceDownSample"+i,()=>t,!0))})}_createHdrPostProcess(e,t){let i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new postProcess_PostProcess("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let r=1,s=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{let e=(n-s)/1e3;this._hdrCurrentLuminance<r+this.hdrDecreaseRate*e?r+=this.hdrDecreaseRate*e:this._hdrCurrentLuminance>r-this.hdrIncreaseRate*e?r-=this.hdrIncreaseRate*e:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=rE.R.Clamp(r,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),n=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new postProcess_PostProcess("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new postProcess_PostProcess("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));let i=new rm.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)};let r=rm.y3.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=rm.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);let t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2),n=rm.P.Dot(t.toVector3(),new rm.P(1,0,0))+rm.P.Dot(i.toVector3(),new rm.P(0,0,1));n*=4;let a=rm.y3.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),o=s.multiply(a).multiply(r);e.setMatrix("lensStarMatrix",o),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new postProcess_PostProcess("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,texture_Texture.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 postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){let i=new MotionBlurPostProcess("HDRMotionBlur",e,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new postProcess_PostProcess("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,r=rm.y3.Identity(),s=rm.y3.Identity(),n=rm.y3.Identity(),a=rm.FM.Zero();this.motionBlurPostProcess.onApply=t=>{(n=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",r),r=n,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 postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRMotionBlur",()=>this.motionBlurPostProcess,!0))}_getDepthTexture(){if(this._scene.getEngine().getCaps().drawBuffersExtension){let e=this._scene.enableGeometryBufferRenderer();return e.getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;e<this._cameras.length;e++){let t=this._cameras[e];this.originalPostProcess&&this.originalPostProcess.dispose(t),this.screenSpaceReflectionPostProcess&&this.screenSpaceReflectionPostProcess.dispose(t),this.downSampleX4PostProcess&&this.downSampleX4PostProcess.dispose(t),this.brightPassPostProcess&&this.brightPassPostProcess.dispose(t),this.textureAdderPostProcess&&this.textureAdderPostProcess.dispose(t),this.volumetricLightPostProcess&&this.volumetricLightPostProcess.dispose(t),this.volumetricLightSmoothXPostProcess&&this.volumetricLightSmoothXPostProcess.dispose(t),this.volumetricLightSmoothYPostProcess&&this.volumetricLightSmoothYPostProcess.dispose(t),this.volumetricLightMergePostProces&&this.volumetricLightMergePostProces.dispose(t),this.volumetricLightFinalPostProcess&&this.volumetricLightFinalPostProcess.dispose(t),this.lensFlarePostProcess&&this.lensFlarePostProcess.dispose(t),this.lensFlareComposePostProcess&&this.lensFlareComposePostProcess.dispose(t);for(let e=0;e<this.luminanceDownSamplePostProcesses.length;e++)this.luminanceDownSamplePostProcesses[e].dispose(t);this.luminancePostProcess&&this.luminancePostProcess.dispose(t),this.hdrPostProcess&&this.hdrPostProcess.dispose(t),this.hdrFinalPostProcess&&this.hdrFinalPostProcess.dispose(t),this.depthOfFieldPostProcess&&this.depthOfFieldPostProcess.dispose(t),this.motionBlurPostProcess&&this.motionBlurPostProcess.dispose(t),this.fxaaPostProcess&&this.fxaaPostProcess.dispose(t);for(let e=0;e<this.blurHPostProcesses.length;e++)this.blurHPostProcesses[e].dispose(t);for(let e=0;e<this.blurVPostProcesses.length;e++)this.blurVPostProcesses[e].dispose(t)}this.originalPostProcess=null,this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.textureAdderPostProcess=null,this.textureAdderFinalPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.luminancePostProcess=null,this.hdrPostProcess=null,this.hdrFinalPostProcess=null,this.depthOfFieldPostProcess=null,this.motionBlurPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.luminanceDownSamplePostProcesses.length=0,this.blurHPostProcesses.length=0,this.blurVPostProcesses.length=0}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}serialize(){let e=rb.p4.Serialize(this);return this.sourceLight&&(e.sourceLightId=this.sourceLight.id),this.screenSpaceReflectionPostProcess&&(e.screenSpaceReflectionPostProcess=rb.p4.Serialize(this.screenSpaceReflectionPostProcess)),e.customType="StandardRenderingPipeline",e}static Parse(e,t,i){let r=rb.p4.Parse(()=>new StandardRenderingPipeline(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&rb.p4.Parse(()=>r.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),r}};StandardRenderingPipeline.LuminanceSteps=6,(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"brightThreshold",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"blurWidth",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"horizontalBlur",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"exposure",null),(0,rH.gn)([(0,rb.oU)("lensTexture")],StandardRenderingPipeline.prototype,"lensTexture",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"volumetricLightCoefficient",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"volumetricLightPower",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"volumetricLightBlurScale",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"hdrMinimumLuminance",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"hdrDecreaseRate",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"hdrIncreaseRate",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"hdrAutoExposure",null),(0,rH.gn)([(0,rb.oU)("lensColorTexture")],StandardRenderingPipeline.prototype,"lensColorTexture",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"lensFlareStrength",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"lensFlareGhostDispersal",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"lensFlareHaloWidth",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"lensFlareDistortionStrength",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"lensFlareBlurWidth",void 0),(0,rH.gn)([(0,rb.oU)("lensStarTexture")],StandardRenderingPipeline.prototype,"lensStarTexture",void 0),(0,rH.gn)([(0,rb.oU)("lensFlareDirtTexture")],StandardRenderingPipeline.prototype,"lensFlareDirtTexture",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"depthOfFieldDistance",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"depthOfFieldBlurWidth",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"motionStrength",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"objectBasedMotionBlur",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"_ratio",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"BloomEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"DepthOfFieldEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"LensFlareEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"HDREnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"VLSEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"MotionBlurEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"fxaaEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"screenSpaceReflectionsEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"volumetricLightStepsCount",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"motionBlurSamples",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"samples",null),(0,rv.H)("BABYLON.StandardRenderingPipeline",StandardRenderingPipeline);let ScreenSpaceReflections2Configuration=class ScreenSpaceReflections2Configuration{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}};let hS=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } +/** +param csOrigin Camera-space ray origin,which must be +within the view volume and must have z>0.01 and project within the valid screen rectangle +param csDirection Unit length camera-space ray direction +param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates +(**not** [-1,+1] normalized device coordinates). +param csZBuffer The camera-space Z buffer +param csZBufferSize Dimensions of csZBuffer +param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer +param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value +for clipping rays headed towards the camera +param stride Step in horizontal or vertical pixels between samples. This is a float +because integer math is slow on GPUs,but should be set to an integer>=1 +param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units +to conceal banding artifacts,plus the stride ray offset. +param maxSteps Maximum number of iterations. Higher gives better images but may be slow +param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss +param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. +1 is a reasonable value,depending on the scene you may need to set this value to 2 +param hitPixel Pixel coordinates of the first intersection with the scene +param numIterations number of iterations performed +param csHitPoint Camera space location of the ray hit +*/ +#define inline +bool traceScreenSpaceRay1( +vec3 csOrigin, +vec3 csDirection, +mat4 projectToPixelMatrix, +sampler2D csZBuffer, +vec2 csZBufferSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +sampler2D csZBackBuffer, +float csZBackSizeFactor, +#endif +float csZThickness, +float nearPlaneZ, +float stride, +float jitterFraction, +float maxSteps, +float maxRayTraceDistance, +float selfCollisionNumSkip, +out vec2 startPixel, +out vec2 hitPixel, +out vec3 csHitPoint, +out float numIterations +#ifdef SSRAYTRACE_DEBUG +,out vec3 debugColor +#endif +) +{ +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; +#else +float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)<nearPlaneZ ? (nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; +#endif +vec3 csEndPoint=csOrigin+csDirection*rayLength;hitPixel=vec2(-1.0,-1.0);vec4 H0=projectToPixelMatrix*vec4(csOrigin,1.0);vec4 H1=projectToPixelMatrix*vec4(csEndPoint,1.0);float k0=1.0/H0.w;float k1=1.0/H1.w;vec3 Q0=csOrigin*k0;vec3 Q1=csEndPoint*k1;vec2 P0=H0.xy*k0;vec2 P1=H1.xy*k1; +#ifdef SSRAYTRACE_CLIP_TO_FRUSTUM +float xMax=csZBufferSize.x-0.5,xMin=0.5,yMax=csZBufferSize.y-0.5,yMin=0.5;float alpha=0.0;if ((P1.y>yMax) || (P1.y<yMin)) {alpha=(P1.y-((P1.y>yMax) ? yMax : yMin))/(P1.y-P0.y);} +if ((P1.x>xMax) || (P1.x<xMin)) {alpha=max(alpha,(P1.x-((P1.x>xMax) ? xMax : xMin))/(P1.x-P0.x));} +P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); +#endif +P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)<abs(delta.y)) { +permute=true;delta=delta.yx;P0=P0.yx;P1=P1.yx; } +float stepDirection=sign(delta.x);float invdx=stepDirection/delta.x;vec2 dP=vec2(stepDirection,delta.y*invdx);vec3 dQ=(Q1-Q0)*invdx;float dk=(k1-k0)*invdx;float zMin=min(csEndPoint.z,csOrigin.z);float zMax=max(csEndPoint.z,csOrigin.z);dP*=stride; dQ*=stride; dk*=stride;P0+=dP*jitterFraction; Q0+=dQ*jitterFraction; k0+=dk*jitterFraction;vec4 pqk=vec4(P0,Q0.z,k0);vec4 dPQK=vec4(dP,dQ.z,dk);startPixel=permute ? P0.yx : P0.xy;float prevZMaxEstimate=csOrigin.z;float rayZMin=prevZMaxEstimate,rayZMax=prevZMaxEstimate;float sceneZMax=rayZMax+1e4;float end=P1.x*stepDirection;bool hit=false;float stepCount;for (stepCount=0.0;stepCount<=selfCollisionNumSkip || +(pqk.x*stepDirection)<=end && +stepCount<maxSteps && +!hit && +sceneZMax != 0.0; +pqk+=dPQK,++stepCount) +{hitPixel=permute ? pqk.yx : pqk.xy;rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;if (rayZMin>rayZMax) { +float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} +sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); +#else +hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); +#endif +#else +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); +#else +hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); +#endif +#endif +} +pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} +#ifdef SSRAYTRACE_ENABLE_REFINEMENT +if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || +(refinementStepCount<=stride*1.4) && +(rayZMax<sceneZMax) && (sceneZMax != 0.0);pqk+=dPQK,refinementStepCount+=1.0) +{rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;rayZMax=max(rayZMax,rayZMin);hitPixel=permute ? pqk.yx : pqk.xy;sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;} +pqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;} +#endif +Q0.xy+=dQ.xy*stepCount;Q0.z=pqk.z;csHitPoint=Q0/pqk.w;numIterations=stepCount+1.0; +#ifdef SSRAYTRACE_DEBUG +if (((pqk.x+dPQK.x)*stepDirection)>end) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} +#endif +return hit;} +/** +texCoord: in the [0,1] range +depth: depth in view space (range [znear,zfar]]) +*/ +vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +ndc.z=-projection[2].z-projection[3].z/depth; +#else +ndc.z=projection[2].z+projection[3].z/depth; +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +`;s_.v.IncludesShadersStore.screenSpaceRayTrace=hS;let hC=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSR_SUPPORTED +uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +uniform sampler2D backDepthSampler;uniform float backSizeFactor; +#endif +#ifdef SSR_USE_ENVIRONMENT_CUBE +uniform samplerCube envCubeSampler; +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; +#include<helperFunctions> +#include<pbrBRDFFunctions> +#include<screenSpaceRayTrace> +vec3 hash(vec3 a) +{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} +float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; +#ifdef SSR_ATTENUATE_SCREEN_BORDERS +vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE +attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS +attenuation*=1.0-(numIterations/maxSteps); +#endif +#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION +vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; +#endif +return attenuation;} +#endif +void main() +{ +#ifdef SSR_SUPPORTED +vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { +#ifdef SSR_USE_BLUR +gl_FragColor=vec4(0.); +#else +gl_FragColor=colorFull; +#endif +return;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpace(color); +#endif +vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; +float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal); +#ifdef SSR_USE_ENVIRONMENT_CUBE +vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); +#endif +#ifdef SSR_INVERTCUBICMAP +wReflectedVector.y*=-1.0; +#endif +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +wReflectedVector.z*=-1.0; +#endif +vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; +#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE +envColor=toLinearSpace(envColor); +#endif +#else +vec3 envColor=color; +#endif +float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; +#ifdef SSRAYTRACE_DEBUG +vec3 debugColor; +#endif +#ifdef SSR_ATTENUATE_FACING_CAMERA +reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); +#endif +if (reflectionAttenuation>0.0) { +#ifdef SSR_USE_BLUR +vec3 jitt=vec3(0.); +#else +float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; +#endif +vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); +rayHasHit=traceScreenSpaceRay1( +csPosition, +normalize(csReflectedVector+jitt), +projectionPixel, +depthSampler, +texSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +backDepthSampler, +backSizeFactor, +#endif +thickness, +nearPlaneZ, +stepSize, +jitter, +maxSteps, +maxDistance, +selfCollisionNumSkip, +startPixel, +hitPixel, +hitPoint, +numIterations +#ifdef SSRAYTRACE_DEBUG +,debugColor +#endif +);} +#ifdef SSRAYTRACE_DEBUG +gl_FragColor=vec4(debugColor,1.);return; +#endif +vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; +#ifdef SSR_INPUT_IS_GAMMA_SPACE +reflectedColor=toLinearSpace(reflectedColor); +#endif +reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} +#ifndef SSR_BLEND_WITH_FRESNEL +SSR*=fresnel; +#endif +#ifdef SSR_USE_BLUR +float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; +float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} +gl_FragColor=vec4(SSR,blur_radius/255.0); +#else +#ifdef SSR_BLEND_WITH_FRESNEL +vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#else +vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#endif +vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpace(finalColor); +#endif +gl_FragColor=vec4(finalColor,colorFull.a); +#endif +#else +gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); +#endif +} +`;s_.v.ShadersStore.screenSpaceReflection2PixelShader=hC;let hE=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) +{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} +void main() +{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} +float blurRadius=colorFull.a*255.0; +vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} +`;s_.v.ShadersStore.screenSpaceReflection2BlurPixelShader=hE;let hb=`uniform sampler2D textureSampler; +uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; +#include<helperFunctions> +#ifdef SSR_BLEND_WITH_FRESNEL +#include<pbrBRDFFunctions> +#include<screenSpaceRayTrace> +uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler; +#endif +void main() +{ +#ifdef SSRAYTRACE_DEBUG +gl_FragColor=texture2D(textureSampler,vUV); +#else +vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpace(color); +#endif +#ifdef SSR_BLEND_WITH_FRESNEL +vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#else +vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#endif +vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpace(finalColor); +#endif +gl_FragColor=vec4(finalColor,color.a); +#endif +} +`;s_.v.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader=hb;let hy=rm.y3.Compose(new rm.P(.5,.5,.5),rm._f.Identity(),new rm.P(.5,.5,.5)),hP=rm.y3.Compose(new rm.P(.5,.5,1),rm._f.Identity(),new rm.P(.5,.5,0));let SSRRenderingPipeline=class SSRRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{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;let 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(){let e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!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=r,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){let e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0,e.generateNormalsInWorldSpace&&console.error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"))}else{let e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty(),e.generateNormalsInWorldSpace&&console.error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!"))}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){let 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;let i=this._scene.getEngine(),r=this._prePassRenderer,s={width:i.getRenderWidth(),height:i.getRenderHeight()};if(r&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){let e=r.getRenderTarget();e&&e.textures&&(s=e.textures[r.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;let 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){this._isDirty=!0;return}this._isDirty=!1;let 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){let t=null===(e=this._cameras)||void 0===e?void 0:e[0];t&&(this._depthRendererCamera=t,this._depthRenderer=new DepthRenderer(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 postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRCombineRenderEffect,()=>this._blurCombinerPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;let e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==r)&&this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){let 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,r;for(let s=0;s<this._cameras.length;s++){let n=this._cameras[s];null===(e=this._ssrPostProcess)||void 0===e||e.dispose(n),null===(t=this._blurPostProcessX)||void 0===t||t.dispose(n),null===(i=this._blurPostProcessY)||void 0===i||i.dispose(n),null===(r=this._blurCombinerPostProcess)||void 0===r||r.dispose(n)}this._ssrPostProcess=null,this._blurPostProcessX=null,this._blurPostProcessY=null,this._blurCombinerPostProcess=null}_createSSRPostProcess(){this._ssrPostProcess=new postProcess_PostProcess("ssr","screenSpaceReflection2",["projection","invProjectionMatrix","view","invView","thickness","reflectionSpecularFalloffExponent","strength","stepSize","maxSteps","roughnessFactor","projectionPixel","nearPlaneZ","maxDistance","selfCollisionNumSkip","vReflectionPosition","vReflectionSize","backSizeFactor","reflectivityThreshold"],["textureSampler","normalSampler","reflectivitySampler","depthSampler","envCubeSampler","backDepthSampler"],1,null,this._textureType,this._scene.getEngine(),!1,"",this._textureType),this._updateEffectDefines(),this._ssrPostProcess.onApply=e=>{this._resizeDepthRenderer();let t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){let i=t.getTextureIndex(GeometryBufferRenderer.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){let t=i.getIndex(5),r=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[r])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));let r=this._scene.activeCamera;if(!r)return;let s=r.getViewMatrix(!0),n=r.getProjectionMatrix(!0);n.invertToRef(rm.jp.Matrix[0]),s.invertToRef(rm.jp.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",s),e.setMatrix("invView",rm.jp.Matrix[1]),e.setMatrix("invProjectionMatrix",rm.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",r.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);let a=this._getTextureSize();rm.y3.ScalingToRef(a.width,a.height,1,rm.jp.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?hP:hy,rm.jp.Matrix[3]),rm.jp.Matrix[3].multiplyToRef(rm.jp.Matrix[2],rm.jp.Matrix[4]),e.setMatrix("projectionPixel",rm.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 ScreenSpaceReflections2Configuration)}_createBlurAndCombinerPostProcesses(){let e=this._scene.getEngine();this._blurPostProcessX=new postProcess_PostProcess("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;let r=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/r,0)}),this._blurPostProcessY=new postProcess_PostProcess("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;let r=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/r)});let t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"],r="";this._debug&&(r+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(r+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(r+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(r+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(r+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new postProcess_PostProcess("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,r,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(e=>{var t;let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(r||i){if(r&&(null===(t=this._scene.activeCamera)||void 0===t?void 0:t._getFirstPostProcess())===this._ssrPostProcess){let t=r.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[r.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(i){let t=i.getTextureIndex(GeometryBufferRenderer.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(r){let t=r.getIndex(3);if(e.setTexture("reflectivitySampler",r.getRenderTarget().textures[t]),this.useFresnel){let t=r.getIndex(5),i=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[i]),e.setTexture("depthSampler",r.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();i.invertToRef(rm.jp.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",rm.jp.Matrix[0])}}}})}serialize(){let e=rb.p4.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return rb.p4.Parse(()=>new SSRRenderingPipeline(e._name,t,e._ratio),e,t,i)}};(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"samples",null),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"maxDistance",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"step",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"thickness",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"strength",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"reflectionSpecularFalloffExponent",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"maxSteps",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"roughnessFactor",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"selfCollisionNumSkip",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"_reflectivityThreshold",void 0),(0,rH.gn)([(0,rb.qC)("_ssrDownsample")],SSRRenderingPipeline.prototype,"_ssrDownsample",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"ssrDownsample",null),(0,rH.gn)([(0,rb.qC)("blurDispersionStrength")],SSRRenderingPipeline.prototype,"_blurDispersionStrength",void 0),(0,rH.gn)([(0,rb.qC)("blurDownsample")],SSRRenderingPipeline.prototype,"_blurDownsample",void 0),(0,rH.gn)([(0,rb.qC)("enableSmoothReflections")],SSRRenderingPipeline.prototype,"_enableSmoothReflections",void 0),(0,rH.gn)([(0,rb.qC)("environmentTexture")],SSRRenderingPipeline.prototype,"_environmentTexture",void 0),(0,rH.gn)([(0,rb.qC)("environmentTextureIsProbe")],SSRRenderingPipeline.prototype,"_environmentTextureIsProbe",void 0),(0,rH.gn)([(0,rb.qC)("attenuateScreenBorders")],SSRRenderingPipeline.prototype,"_attenuateScreenBorders",void 0),(0,rH.gn)([(0,rb.qC)("attenuateIntersectionDistance")],SSRRenderingPipeline.prototype,"_attenuateIntersectionDistance",void 0),(0,rH.gn)([(0,rb.qC)("attenuateIntersectionIterations")],SSRRenderingPipeline.prototype,"_attenuateIntersectionIterations",void 0),(0,rH.gn)([(0,rb.qC)("attenuateFacingCamera")],SSRRenderingPipeline.prototype,"_attenuateFacingCamera",void 0),(0,rH.gn)([(0,rb.qC)("attenuateBackfaceReflection")],SSRRenderingPipeline.prototype,"_attenuateBackfaceReflection",void 0),(0,rH.gn)([(0,rb.qC)("clipToFrustum")],SSRRenderingPipeline.prototype,"_clipToFrustum",void 0),(0,rH.gn)([(0,rb.qC)("useFresnel")],SSRRenderingPipeline.prototype,"_useFresnel",void 0),(0,rH.gn)([(0,rb.qC)("enableAutomaticThicknessComputation")],SSRRenderingPipeline.prototype,"_enableAutomaticThicknessComputation",void 0),(0,rH.gn)([(0,rb.qC)("backfaceDepthTextureDownsample")],SSRRenderingPipeline.prototype,"_backfaceDepthTextureDownsample",void 0),(0,rH.gn)([(0,rb.qC)("backfaceForceDepthWriteTransparentMeshes")],SSRRenderingPipeline.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),(0,rH.gn)([(0,rb.qC)("isEnabled")],SSRRenderingPipeline.prototype,"_isEnabled",void 0),(0,rH.gn)([(0,rb.qC)("inputTextureColorIsInGammaSpace")],SSRRenderingPipeline.prototype,"_inputTextureColorIsInGammaSpace",void 0),(0,rH.gn)([(0,rb.qC)("generateOutputInGammaSpace")],SSRRenderingPipeline.prototype,"_generateOutputInGammaSpace",void 0),(0,rH.gn)([(0,rb.qC)("debug")],SSRRenderingPipeline.prototype,"_debug",void 0),(0,rv.H)("BABYLON.SSRRenderingPipeline",SSRRenderingPipeline);let hR=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; +#if defined(HABLE_TONEMAPPING) +const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2; +#endif +float Luminance(vec3 c) +{return dot(c,vec3(0.22,0.707,0.071));} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 colour=texture2D(textureSampler,vUV).rgb; +#if defined(REINHARD_TONEMAPPING) +float lum=Luminance(colour.rgb); +float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); +colour*=scale/lum; +#elif defined(HABLE_TONEMAPPING) +colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; +#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) +colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; +#elif defined(PHOTOGRAPHIC_TONEMAPPING) +colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); +#endif +gl_FragColor=vec4(colour.rgb,1.0);}`;s_.v.ShadersStore.tonemapPixelShader=hR,(ts=rs||(rs={}))[ts.Hable=0]="Hable",ts[ts.Reinhard=1]="Reinhard",ts[ts.HejiDawson=2]="HejiDawson",ts[ts.Photographic=3]="Photographic";let hA=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i<NUM_SAMPLES; i++) {tc-=deltaTexCoord;vec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;dataSample*=illuminationDecay*weight;color+=dataSample;illuminationDecay*=decay;} +vec4 realColor=texture2D(textureSampler,vUV);gl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4))); +#define CUSTOM_FRAGMENT_MAIN_END +} +`;s_.v.ShadersStore.volumetricLightScatteringPixelShader=hA;let hI=`attribute vec3 position; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<instancesDeclaration> +uniform mat4 viewProjection;uniform vec2 depthValues; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +} +`;s_.v.ShadersStore.volumetricLightScatteringPassVertexShader=hI;let hM=`#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV; +#endif +#if defined(ALPHATEST) +uniform sampler2D diffuseSampler; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#if defined(ALPHATEST) +vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) +discard; +#endif +gl_FragColor=vec4(0.0,0.0,0.0,1.0);} +`;s_.v.ShadersStore.volumetricLightScatteringPassPixelShader=hM;let VolumetricLightScatteringPostProcess=class VolumetricLightScatteringPostProcess extends postProcess_PostProcess{get useDiffuseColor(){return rT.Y.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){rT.Y.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,r,s=100,n=texture_Texture.BILINEAR_SAMPLINGMODE,a,o,l){var h,u;super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,n,a,o,"#define NUM_SAMPLES "+s),this._screenCoordinates=rm.FM.Zero(),this.customMeshPosition=rm.P.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,a=(l=null!==(u=null!==(h=null==i?void 0:i.getScene())&&void 0!==h?h:l)&&void 0!==u?u:this._scene).getEngine(),this._viewPort=new sh.l(0,0,1,1).toGlobal(a.getRenderWidth(),a.getRenderHeight()),this.mesh=null!=r?r:VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh",l),this._createPass(l,t.passRatio||t),this.onActivate=e=>{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add(e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;let r=e.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);let s=null===(i=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(r,e,t);let n=[],a=[rz.o.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(rz.o.UVKind)&&(a.push(rz.o.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(rz.o.UV2Kind)&&(a.push(rz.o.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(a.push(rz.o.MatricesIndicesKind),a.push(rz.o.MatricesWeightsKind),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"),t&&(n.push("#define INSTANCES"),so.G.PushAttributesForInstances(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));let l=e._getDrawWrapper(void 0,!0),h=l.defines,u=n.join("\n");return h!==u&&l.setEffect(r.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:r.numBoneInfluencers}),u),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){let 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){let i;let r=e.getEngine();this._volumetricLightScatteringRTT=new renderTargetTexture_RenderTargetTexture("volumetricLightScatteringMap",{width:r.getRenderWidth()*t,height:r.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;let s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);let renderSubMesh=e=>{var t;let i=e.getRenderingMesh(),r=e.getEffectiveMesh();if(this._meshExcluded(i))return;r._internalAbstractMeshDataInfo._isActiveIntermediate=!1;let s=e.getMaterial();if(!s)return;let n=i.getScene(),a=n.getEngine();a.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);let o=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;let l=a.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||i.hasThinInstances);if(this._isReady(e,l)){let h=null===(t=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[a.currentRenderPassId],u=e._getDrawWrapper();if(i!==this.mesh||u||(u=s._getDrawWrapper()),!u)return;let c=u.effect;if(a.enableEffect(u),l||i._bind(e,c,s.fillMode),i===this.mesh)s.bind(r.getWorldMatrix(),i);else if(h)h.bindForSubMesh(r.getWorldMatrix(),r,e);else{if(c.setMatrix("viewProjection",n.getTransformMatrix()),s&&s.needAlphaTesting()){let e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&c.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}l&&i.hasThinInstances&&c.setMatrix("world",r.getWorldMatrix()),i._processRendering(r,e,c,sr.F.TriangleFillMode,o,l,(e,t)=>{e||c.setMatrix("world",t)})}},n=new rg.HE(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{i=e.clearColor,e.clearColor=n}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=i}),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){let i=e.subMeshes[t],s=i.getMaterial(),n=i.getRenderingMesh();if(!s)continue;let a=n._getInstancesRenderList(i._id,!!i.getReplacementMesh()),o=r.getCaps().instancedArrays&&(null!==a.visibleInstances[i._id]||n.hasThinInstances);if(!this._isReady(i,o))return!1}return!0},this._volumetricLightScatteringRTT.customRenderFunction=(t,i,r,s)=>{let n;let a=e.getEngine();if(s.length){for(a.setColorWrite(!1),n=0;n<s.length;n++)renderSubMesh(s.data[n]);a.setColorWrite(!0)}for(n=0;n<t.length;n++)renderSubMesh(t.data[n]);for(n=0;n<i.length;n++)renderSubMesh(i.data[n]);if(r.length){for(n=0;n<r.length;n++){let t=r.data[n],i=t.getBoundingInfo();i&&e.activeCamera&&(t._alphaIndex=t.getMesh().alphaIndex,t._distanceToCamera=i.boundingSphere.centerWorld.subtract(e.activeCamera.position).length())}let t=r.data.slice(0,r.length);for(t.sort((e,t)=>e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0),a.setAlphaMode(2),n=0;n<t.length;n++)renderSubMesh(t[n]);a.setAlphaMode(0)}}}_updateMeshScreenCoordinates(e){let t;let i=e.getTransformMatrix();t=this.useCustomMeshPosition?this.customMeshPosition:this.attachedNode?this.attachedNode.position:this.mesh.parent?this.mesh.getAbsolutePosition():this.mesh.position;let r=rm.P.Project(t,rm.y3.Identity(),i,this._viewPort);this._screenCoordinates.x=r.x/this._viewPort.width,this._screenCoordinates.y=r.y/this._viewPort.height,this.invert&&(this._screenCoordinates.y=1-this._screenCoordinates.y)}static CreateDefaultMesh(e,t){let i=planeBuilder_CreatePlane(e,{size:1},t);i.billboardMode=rG.x.BILLBOARDMODE_ALL;let r=new standardMaterial_StandardMaterial(e+"Material",t);return r.emissiveColor=new rg.Wo(1,1,1),i.material=r,i}};(0,rH.gn)([(0,rb.hd)()],VolumetricLightScatteringPostProcess.prototype,"customMeshPosition",void 0),(0,rH.gn)([(0,rb.qC)()],VolumetricLightScatteringPostProcess.prototype,"useCustomMeshPosition",void 0),(0,rH.gn)([(0,rb.qC)()],VolumetricLightScatteringPostProcess.prototype,"invert",void 0),(0,rH.gn)([(0,rb.RR)()],VolumetricLightScatteringPostProcess.prototype,"mesh",void 0),(0,rH.gn)([(0,rb.qC)()],VolumetricLightScatteringPostProcess.prototype,"excludedMeshes",void 0),(0,rH.gn)([(0,rb.qC)()],VolumetricLightScatteringPostProcess.prototype,"includedMeshes",void 0),(0,rH.gn)([(0,rb.qC)()],VolumetricLightScatteringPostProcess.prototype,"exposure",void 0),(0,rH.gn)([(0,rb.qC)()],VolumetricLightScatteringPostProcess.prototype,"decay",void 0),(0,rH.gn)([(0,rb.qC)()],VolumetricLightScatteringPostProcess.prototype,"weight",void 0),(0,rH.gn)([(0,rb.qC)()],VolumetricLightScatteringPostProcess.prototype,"density",void 0),(0,rv.H)("BABYLON.VolumetricLightScatteringPostProcess",VolumetricLightScatteringPostProcess);let hD=`precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform float curvature_ridge;uniform float curvature_valley; +#ifndef CURVATURE_OFFSET +#define CURVATURE_OFFSET 1 +#endif +float curvature_soft_clamp(float curvature,float control) +{if (curvature<0.5/control) +return curvature*(1.0-curvature*control);return 0.25/control;} +float calculate_curvature(ivec2 texel,float ridge,float valley) +{vec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;vec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;vec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;vec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;float normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));if (normal_diff<0.0) +return -2.0*curvature_soft_clamp(-normal_diff,valley);return 2.0*curvature_soft_clamp(normal_diff,ridge);} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ivec2 texel=ivec2(gl_FragCoord.xy);vec4 baseColor=texture2D(textureSampler,vUV);float curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);baseColor.rgb*=curvature+1.0;gl_FragColor=baseColor;}`;s_.v.ShadersStore.screenSpaceCurvaturePixelShader=hD;let ScreenSpaceCurvaturePostProcess=class ScreenSpaceCurvaturePostProcess extends postProcess_PostProcess{getClassName(){return"ScreenSpaceCurvaturePostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1){super(e,"screenSpaceCurvature",["curvature_ridge","curvature_valley"],["textureSampler","normalSampler"],i,r,s,n,a,void 0,o,void 0,null,l),this.ridge=1,this.valley=1,this._geometryBufferRenderer=t.enableGeometryBufferRenderer(),this._geometryBufferRenderer?(this._geometryBufferRenderer.generateNormalsInWorldSpace&&console.error("ScreenSpaceCurvaturePostProcess does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"),this.onApply=e=>{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));let t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):rT.Y.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){let e=rS.l.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new ScreenSpaceCurvaturePostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],ScreenSpaceCurvaturePostProcess.prototype,"ridge",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceCurvaturePostProcess.prototype,"valley",void 0),(0,rv.H)("BABYLON.ScreenSpaceCurvaturePostProcess",ScreenSpaceCurvaturePostProcess);let hO=`uniform vec4 color; +`;s_.v.IncludesShadersStore.boundingBoxRendererFragmentDeclaration=hO;let hN=`#ifdef WEBGL2 +uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +#else +layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; +#endif +`;s_.v.IncludesShadersStore.boundingBoxRendererUboDeclaration=hN;let hF=`#include<__decl__boundingBoxRendererFragment> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;s_.v.ShadersStore.boundingBoxRendererPixelShader=hF;let hB=`uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +`;s_.v.IncludesShadersStore.boundingBoxRendererVertexDeclaration=hB;let hL=`attribute vec3 position; +#include<__decl__boundingBoxRendererVertex> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec4 worldPos=world*vec4(position,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;s_.v.ShadersStore.boundingBoxRendererVertexShader=hL,Object.defineProperty(rN.x.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),rN.x.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new BoundingBoxRenderer(this)),this._boundingBoxRenderer},Object.defineProperty(rG.x.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});let BoundingBoxRenderer=class BoundingBoxRenderer{constructor(e){this.name=rQ.l.NAME_BOUNDINGBOXRENDERER,this.frontColor=new rg.Wo(1,1,1),this.backColor=new rg.Wo(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new rf.y$,this.onAfterBoxRenderingObservable=new rf.y$,this.onResourcesReadyObservable=new rf.y$,this.enabled=!0,this.renderList=new sp.t(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new rX.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new rX.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(rQ.l.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(rQ.l.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(rQ.l.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(rQ.l.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){let i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){let t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new shaderMaterial_ShaderMaterial("colorShader",this.scene,"boundingBoxRenderer",{attributes:[rz.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new shaderMaterial_ShaderMaterial("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[rz.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};let e=this.scene.getEngine(),t=CreateBoxVertexData({size:1});this._vertexBuffers[rz.o.PositionKind]=new rz.o(e,t.positions,rz.o.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){let 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(){let e=this._vertexBuffers[rz.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(0===this.renderList.length||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;let r=this.scene.getEngine();r.setDepthWrite(!1);let s=this.scene.getTransformMatrix();for(let n=0;n<this.renderList.length;n++){let a=this.renderList.data[n];if(a._tag!==e)continue;this._createWrappersForBoundingBox(a),this.onBeforeBoxRenderingObservable.notifyObservers(a);let o=a.minimum,l=a.maximum,h=l.subtract(o),u=o.add(h.scale(.5)),c=rm.y3.Scaling(h.x,h.y,h.z).multiply(rm.y3.Translation(u.x,u.y,u.z)).multiply(a.getWorldMatrix()),d=r.useReverseDepthBuffer;if(this.showBackLines){let e=null!==(t=a._drawWrapperBack)&&void 0!==t?t:this._colorShader._getDrawWrapper();this._colorShader._preBind(e),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),d?r.setDepthFunctionToLessOrEqual():r.setDepthFunctionToGreaterOrEqual(),this._uniformBufferBack.bindToEffect(e.effect,"BoundingBoxRenderer"),this._uniformBufferBack.updateColor4("color",this.backColor,1),this._uniformBufferBack.updateMatrix("world",c),this._uniformBufferBack.updateMatrix("viewProjection",s),this._uniformBufferBack.update(),r.drawElementsType(sr.F.LineListDrawMode,0,24)}let p=null!==(i=a._drawWrapperFront)&&void 0!==i?i:this._colorShader._getDrawWrapper();this._colorShader._preBind(p),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),d?r.setDepthFunctionToGreater():r.setDepthFunctionToLess(),this._uniformBufferFront.bindToEffect(p.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateColor4("color",this.frontColor,1),this._uniformBufferFront.updateMatrix("world",c),this._uniformBufferFront.updateMatrix("viewProjection",s),this._uniformBufferFront.update(),r.drawElementsType(sr.F.LineListDrawMode,0,24),this.onAfterBoxRenderingObservable.notifyObservers(a)}this._colorShader.unbind(),r.setDepthFunctionToLessOrEqual(),r.setDepthWrite(!0)}_createWrappersForBoundingBox(e){if(!e._drawWrapperFront){let t=this.scene.getEngine();e._drawWrapperFront=new sm.q(t),e._drawWrapperBack=new sm.q(t),e._drawWrapperFront.setEffect(this._colorShader.getEffect()),e._drawWrapperBack.setEffect(this._colorShader.getEffect())}}renderOcclusionBoundingBox(e){let t=this.scene.getEngine();void 0===this._renderPassIdForOcclusionQuery&&(this._renderPassIdForOcclusionQuery=t.createRenderPassId("Render pass for occlusion query"));let i=t.currentRenderPassId;t.currentRenderPassId=this._renderPassIdForOcclusionQuery,this._prepareResources();let r=e.subMeshes[0];if(!this._colorShaderForOcclusionQuery.isReady(e,void 0,r)||!e.hasBoundingInfo){t.currentRenderPassId=i;return}this._fillIndexBuffer||(this._fillIndexBuffer=t.createIndexBuffer(this._fillIndexData));let s=t.useReverseDepthBuffer;t.setDepthWrite(!1),t.setColorWrite(!1);let n=e.getBoundingInfo().boundingBox,a=n.minimum,o=n.maximum,l=o.subtract(a),h=a.add(l.scale(.5)),u=rm.y3.Scaling(l.x,l.y,l.z).multiply(rm.y3.Translation(h.x,h.y,h.z)).multiply(n.getWorldMatrix()),c=r._drawWrapper;this._colorShaderForOcclusionQuery._preBind(c),t.bindBuffers(this._vertexBuffers,this._fillIndexBuffer,c.effect),s?t.setDepthFunctionToGreater():t.setDepthFunctionToLess(),this.scene.resetCachedMaterial(),this._uniformBufferFront.bindToEffect(c.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateMatrix("world",u),this._uniformBufferFront.updateMatrix("viewProjection",this.scene.getTransformMatrix()),this._uniformBufferFront.update(),t.drawElementsType(sr.F.TriangleFillMode,0,36),this._colorShaderForOcclusionQuery.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0),t.setColorWrite(!0),t.currentRenderPassId=i}dispose(){if(void 0!==this._renderPassIdForOcclusionQuery&&(this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery),this._renderPassIdForOcclusionQuery=void 0),!this._colorShader)return;this.onBeforeBoxRenderingObservable.clear(),this.onAfterBoxRenderingObservable.clear(),this.onResourcesReadyObservable.clear(),this.renderList.dispose(),this._colorShader.dispose(),this._colorShaderForOcclusionQuery.dispose(),this._uniformBufferFront.dispose(),this._uniformBufferBack.dispose();let e=this._vertexBuffers[rz.o.PositionKind];e&&(e.dispose(),this._vertexBuffers[rz.o.PositionKind]=null),this.scene.getEngine()._releaseBuffer(this._indexBuffer),this._fillIndexBuffer&&(this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer),this._fillIndexBuffer=null)}};rN.x.prototype.enableDepthRenderer=function(e,t=!1,i=!1,r=3,s=!1){if(!(e=e||this.activeCamera))throw"No camera available to enable depth renderer";if(this._depthRenderer||(this._depthRenderer={}),!this._depthRenderer[e.id]){let n=!!this.getEngine().getCaps().textureFloatRender,a=0;a=!this.getEngine().getCaps().textureHalfFloatRender||i&&n?n?1:0:2,this._depthRenderer[e.id]=new DepthRenderer(this,a,e,t,r,s)}return this._depthRenderer[e.id]},rN.x.prototype.disableDepthRenderer=function(e){(e=e||this.activeCamera)&&this._depthRenderer&&this._depthRenderer[e.id]&&this._depthRenderer[e.id].dispose()};let DepthRendererSceneComponent=class DepthRendererSceneComponent{constructor(e){this.name=rQ.l.NAME_DEPTHRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(rQ.l.STEP_GATHERRENDERTARGETS_DEPTHRENDERER,this,this._gatherRenderTargets),this.scene._gatherActiveCameraRenderTargetsStage.registerStep(rQ.l.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER,this,this._gatherActiveCameraRenderTargets)}rebuild(){}dispose(){for(let e in this.scene._depthRenderer)this.scene._depthRenderer[e].dispose()}_gatherRenderTargets(e){if(this.scene._depthRenderer)for(let t in this.scene._depthRenderer){let i=this.scene._depthRenderer[t];i.enabled&&!i.useOnlyInActiveCamera&&e.push(i.getDepthMap())}}_gatherActiveCameraRenderTargets(e){if(this.scene._depthRenderer)for(let t in this.scene._depthRenderer){let i=this.scene._depthRenderer[t];i.enabled&&i.useOnlyInActiveCamera&&this.scene.activeCamera.id===t&&e.push(i.getDepthMap())}}};DepthRenderer._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_DEPTHRENDERER);t||(t=new DepthRendererSceneComponent(e),e._addComponent(t))};let hw=`precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( +frontColor.rgb+alphaMultiplier*backColor.rgb, +frontColor.a+backColor.a +);}`;s_.v.ShadersStore.oitFinalPixelShader=hw;let hU=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { +discard;}}`;s_.v.ShadersStore.oitBackBlendPixelShader=hU;let DepthPeelingEffectConfiguration=class DepthPeelingEffectConfiguration{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}};let DepthPeelingRenderer=class DepthPeelingRenderer{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){let 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 sp.t(10),this._excludedSubMeshes=new sp.t(10),this._excludedMeshes=[],this._colorCache=[new rg.HE(DepthPeelingRenderer._DEPTH_CLEAR_VALUE,DepthPeelingRenderer._DEPTH_CLEAR_VALUE,0,0),new rg.HE(-DepthPeelingRenderer._MIN_DEPTH,DepthPeelingRenderer._MAX_DEPTH,0,0),new rg.HE(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){rT.Y.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let e=0;e<this._layoutCacheFormat.length;++e)this._layoutCache[e]=this._engine.buildTextureLayout(this._layoutCacheFormat[e]);this._renderPassIds=[],this.useRenderPasses=!1,this._prePassEffectConfiguration=new DepthPeelingEffectConfiguration,this._createTextures(),this._createEffects()}_createRenderPassIds(){if(this._releaseRenderPassIds(),this._useRenderPasses)for(let e=0;e<this._passCount+1;++e)this._renderPassIds[e]||(this._renderPassIds[e]=this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${e}`))}_releaseRenderPassIds(){for(let e=0;e<this._renderPassIds.length;++e)this._engine.releaseRenderPassId(this._renderPassIds[e]);this._renderPassIds=[]}_createTextures(){let e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()};this._depthMrts=[new MultiRenderTarget("depthPeelingDepth0",e,3,this._scene),new MultiRenderTarget("depthPeelingDepth1",e,3,this._scene)],this._colorMrts=[new MultiRenderTarget("depthPeelingColor0",e,2,this._scene,{generateDepthBuffer:!1}),new MultiRenderTarget("depthPeelingColor1",e,2,this._scene,{generateDepthBuffer:!1})],this._blendBackMrt=new MultiRenderTarget("depthPeelingBack",e,1,this._scene,{generateDepthBuffer:!1}),this._outputRT=new renderTargetTexture_RenderTargetTexture("depthPeelingOutput",e,this._scene,!1);let t=[{format:7,samplingMode:1,type:this._engine.getCaps().textureFloatLinearFiltering?1:2,label:"DepthPeelingRenderer-DepthTexture"},{format:5,samplingMode:1,type:2,label:"DepthPeelingRenderer-ColorTexture"}];for(let i=0;i<2;i++){let r=this._engine._createInternalTexture(e,t[0],!1),s=this._engine._createInternalTexture(e,t[1],!1),n=this._engine._createInternalTexture(e,t[1],!1);this._depthMrts[i].setInternalTexture(r,0),this._depthMrts[i].setInternalTexture(s,1),this._depthMrts[i].setInternalTexture(n,2),this._colorMrts[i].setInternalTexture(s,0),this._colorMrts[i].setInternalTexture(n,1),this._thinTextures.push(new thinTexture_ThinTexture(r),new thinTexture_ThinTexture(s),new thinTexture_ThinTexture(n))}}_disposeTextures(){for(let e=0;e<this._thinTextures.length;e++)6!==e&&this._thinTextures[e].dispose();for(let e=0;e<2;e++)this._depthMrts[e].dispose(!0),this._colorMrts[e].dispose(!0),this._blendBackMrt.dispose(!0);this._outputRT.dispose(),this._thinTextures=[],this._colorMrts=[],this._depthMrts=[]}_updateTextures(){return(this._depthMrts[0].getSize().width!==this._engine.getRenderWidth()||this._depthMrts[0].getSize().height!==this._engine.getRenderHeight())&&(this._disposeTextures(),this._createTextures()),this._updateTextureReferences()}_updateTextureReferences(){var e;let t=this._scene.prePassRenderer;if(!t)return!1;let i=t.getIndex(4),r=(null===(e=t.defaultRT.textures)||void 0===e?void 0:e.length)?t.defaultRT.textures[i].getInternalTexture():null;return!!r&&(this._blendBackTexture!==r&&(this._blendBackTexture=r,this._blendBackMrt.setInternalTexture(this._blendBackTexture,0),this._thinTextures[6]&&this._thinTextures[6].dispose(),this._thinTextures[6]=new thinTexture_ThinTexture(this._blendBackTexture),t.defaultRT.renderTarget._shareDepth(this._depthMrts[0].renderTarget)),!0)}_createEffects(){this._blendBackEffectWrapper=new EffectWrapper({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._blendBackEffectWrapperPingPong=new EffectWrapper({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._finalEffectWrapper=new EffectWrapper({fragmentShader:"oitFinal",useShaderStore:!0,engine:this._engine,samplerNames:["uFrontColor","uBackColor"],uniformNames:[]}),this._effectRenderer=new EffectRenderer(this._engine)}setPrePassRenderer(e){e.addEffectConfiguration(this._prePassEffectConfiguration)}bind(e){e.setTexture("oitDepthSampler",this._thinTextures[3*this._currentPingPongState]),e.setTexture("oitFrontColorSampler",this._thinTextures[3*this._currentPingPongState+1])}_renderSubMeshes(e){let t;this._useRenderPasses&&(t={});for(let i=0;i<e.length;i++){let r;let s=e.data[i].getMaterial(),n=!0,a=!1,o=e.data[i],l=!1;if(this._useRenderPasses&&(l=!(r=o._getDrawWrapper())),s&&(n=s.allowShaderHotSwapping,a=s.backFaceCulling,s.allowShaderHotSwapping=!1,s.backFaceCulling=!1),o.render(!1),l&&(r=o._getDrawWrapper()).materialContext){let e=t[r.materialContext.uniqueId];e||(e=t[r.materialContext.uniqueId]=this._engine.createMaterialContext()),o._getDrawWrapper().materialContext=e}s&&(s.allowShaderHotSwapping=n,s.backFaceCulling=a)}}_finalCompose(e){var t;let i=null===(t=this._scene.prePassRenderer)||void 0===t?void 0:t.setCustomOutput(this._outputRT);i?this._engine.bindFramebuffer(this._outputRT.renderTarget):this._engine.restoreDefaultFramebuffer(),this._engine.setAlphaMode(0),this._engine.applyStates(),this._engine.enableEffect(this._finalEffectWrapper._drawWrapper),this._finalEffectWrapper.effect.setTexture("uFrontColor",this._thinTextures[3*e+1]),this._finalEffectWrapper.effect.setTexture("uBackColor",this._thinTextures[6]),this._effectRenderer.render(this._finalEffectWrapper)}render(e){if(this._candidateSubMeshes.length=0,this._excludedSubMeshes.length=0,!this._blendBackEffectWrapper.effect.isReady()||!this._blendBackEffectWrapperPingPong.effect.isReady()||!this._finalEffectWrapper.effect.isReady()||!this._updateTextures())return this._excludedSubMeshes;this._scene.activeCamera&&this._engine.setViewport(this._scene.activeCamera.viewport);for(let t=0;t<e.length;t++){let i=e.data[t],r=i.getMaterial(),s=r&&i.getRenderingMesh()._getRenderingFillMode(r.fillMode);r&&(s===sr.F.TriangleFanDrawMode||s===sr.F.TriangleFillMode||s===sr.F.TriangleStripDrawMode)&&-1===this._excludedMeshes.indexOf(i.getMesh().uniqueId)?this._candidateSubMeshes.push(i):this._excludedSubMeshes.push(i)}if(!this._candidateSubMeshes.length)return this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._finalCompose(1),this._excludedSubMeshes;let t=this._engine.currentRenderPassId;this._scene.prePassRenderer._enabled=!1,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[0]),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[1],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaMode(11),this._engine.setAlphaEquation(3),this._engine.depthCullingState.depthMask=!1,this._engine.depthCullingState.depthTest=!0,this._engine.applyStates(),this._currentPingPongState=1,this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._scene.resetCachedMaterial();let i=0,r=0;for(let e=0;e<this._passCount;e++){r=1-(i=e%2),this._currentPingPongState=i,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[e+1]),this._scene.activeCamera&&this._engine.setViewport(this._scene.activeCamera.viewport),this._engine.bindFramebuffer(this._depthMrts[r].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[r].renderTarget),this._engine.bindFramebuffer(this._colorMrts[r].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[r].renderTarget),this._engine.bindFramebuffer(this._depthMrts[r].renderTarget),this._engine.bindAttachments(this._layoutCache[2]),this._engine.setAlphaMode(11),this._engine.setAlphaEquation(3),this._engine.depthCullingState.depthTest=!1,this._engine.applyStates(),this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[r].renderTarget),this._scene.resetCachedMaterial(),this._engine.bindFramebuffer(this._blendBackMrt.renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaEquation(0),this._engine.setAlphaMode(17),this._engine.applyStates();let t=0!==r&&this._useRenderPasses?this._blendBackEffectWrapperPingPong:this._blendBackEffectWrapper;this._engine.enableEffect(t._drawWrapper),t.effect.setTexture("uBackColor",this._thinTextures[3*r+2]),this._effectRenderer.render(t),this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget)}return this._engine.currentRenderPassId=t,this._finalCompose(r),this._scene.prePassRenderer._enabled=!0,this._engine.depthCullingState.depthMask=!0,this._engine.depthCullingState.depthTest=!0,this._excludedSubMeshes}dispose(){this._disposeTextures(),this._blendBackEffectWrapper.dispose(),this._finalEffectWrapper.dispose(),this._effectRenderer.dispose(),this._releaseRenderPassIds()}};DepthPeelingRenderer._DEPTH_CLEAR_VALUE=-99999,DepthPeelingRenderer._MIN_DEPTH=0,DepthPeelingRenderer._MAX_DEPTH=1,Object.defineProperty(rN.x.prototype,"depthPeelingRenderer",{get:function(){if(!this._depthPeelingRenderer){let e=this._getComponent(rQ.l.NAME_DEPTHPEELINGRENDERER);e||(e=new DepthPeelingSceneComponent(this),this._addComponent(e))}return this._depthPeelingRenderer},set:function(e){this._depthPeelingRenderer=e},enumerable:!0,configurable:!0}),Object.defineProperty(rN.x.prototype,"useOrderIndependentTransparency",{get:function(){return this._useOrderIndependentTransparency},set:function(e){var t;this._useOrderIndependentTransparency!==e&&(this._useOrderIndependentTransparency=e,this.markAllMaterialsAsDirty(63),null===(t=this.prePassRenderer)||void 0===t||t.markAsDirty())},enumerable:!0,configurable:!0});let DepthPeelingSceneComponent=class DepthPeelingSceneComponent{constructor(e){this.name=rQ.l.NAME_DEPTHPEELINGRENDERER,this.scene=e,e.depthPeelingRenderer=new DepthPeelingRenderer(e)}register(){}rebuild(){}dispose(){var e;null===(e=this.scene.depthPeelingRenderer)||void 0===e||e.dispose(),this.scene.depthPeelingRenderer=null}};let hV=`#include<clipPlaneFragmentDeclaration> +uniform vec4 color; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;s_.v.ShadersStore.linePixelShader=hV;let hk=`#include<instancesDeclaration> +#include<clipPlaneVertexDeclaration> +attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include<instancesVertex> +mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=finalWorld*vec4(position,1.0); +#include<clipPlaneVertex> +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.lineVertexShader=hk,rG.x.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},rG.x.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new EdgesRenderer(this,e,t,!0,i),this},Object.defineProperty(rG.x.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),LinesMesh.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new LineEdgesRenderer(this,e,t),this},InstancedLinesMesh.prototype.enableEdgesRendering=function(e=.95,t=!1){return LinesMesh.prototype.enableEdgesRendering.apply(this,arguments),this};let FaceAdjacencies=class FaceAdjacencies{constructor(){this.edges=[],this.edgesConnectedCount=0}};let EdgesRenderer=class EdgesRenderer{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){let t=new shaderMaterial_ShaderMaterial("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,r=!0,s){var n;this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=[],this._linesNormals=[],this._linesIndices=[],this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new sp.t(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=null!=s?s:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new sm.q(e.getEngine())),this._prepareRessources(),r&&(null===(n=null==s?void 0:s.useAlternateEdgeFinder)||void 0===n||n?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=EdgesRenderer._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[rz.o.PositionKind];e&&e._rebuild(),(e=this._buffers[rz.o.NormalKind])&&e._rebuild();let t=this._source.getScene(),i=t.getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[rz.o.PositionKind];t&&(t.dispose(),this._buffers[rz.o.PositionKind]=null),(t=this._buffers[rz.o.NormalKind])&&(t.dispose(),this._buffers[rz.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,r,s){return e===i&&t===r||e===r&&t===i?0:e===r&&t===s||e===s&&t===r?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,s){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)?1:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)?2:-1}_checkEdge(e,t,i,r,s){let n;if(void 0===t)n=!0;else{let r=rm.P.Dot(i[e],i[t]);n=r<this._epsilon}n&&this.createLine(r,s,this._linesPositions.length/3)}createLine(e,t,i){this._linesPositions.push(e.x,e.y,e.z,e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z),this._linesNormals.push(t.x,t.y,t.z,-1,t.x,t.y,t.z,1,e.x,e.y,e.z,-1,e.x,e.y,e.z,1),this._linesIndices.push(i,i+1,i+2,i,i+2,i+3)}_tessellateTriangle(e,t,i,r){let makePointList=(e,t,i)=>{i>=0&&t.push(i);for(let i=0;i<e.length;++i)t.push(e[i][0])},s=0;e[1].length>=e[0].length&&e[1].length>=e[2].length?s=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(s=2);for(let t=0;t<3;++t)t===s?e[t].sort((e,t)=>e[1]<t[1]?-1:e[1]>t[1]?1:0):e[t].sort((e,t)=>e[1]>t[1]?-1:e[1]<t[1]?1:0);let n=[],a=[];makePointList(e[s],n,-1);let o=n.length;for(let n=s+2;n>=s+1;--n)makePointList(e[n%3],a,n!==s+2?r[i[t+(n+1)%3]]:-1);let l=a.length;i.push(r[i[t+s]],n[0],a[0]),i.push(r[i[t+(s+1)%3]],a[l-1],n[o-1]);let h=o<=l,u=h?o:l,c=h?l:o,d=h?o-1:l-1,p=h?0:1,_=o+l-2,f=0,m=0,g=h?n:a,v=h?a:n,x=0;for(;_-- >0;){let e;p?i.push(g[f],v[m]):i.push(v[m],g[f]),(x+=u)>=c&&f<d?(e=g[++f],x-=c):e=v[++m],i.push(e)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3}_generateEdgesLinesAlternate(){var e,t,i,r,s,n,a,o,l,h;let u=this._source.getVerticesData(rz.o.PositionKind),c=this._source.getIndices();if(!c||!u)return;Array.isArray(c)||(c=Array.from(c));let d=null===(t=null===(e=this._options)||void 0===e?void 0:e.useFastVertexMerger)||void 0===t||t,p=d?Math.round(-Math.log(null!==(r=null===(i=this._options)||void 0===i?void 0:i.epsilonVertexMerge)&&void 0!==r?r:1e-6)/Math.log(10)):null!==(n=null===(s=this._options)||void 0===s?void 0:s.epsilonVertexMerge)&&void 0!==n?n:1e-6,_=[],f=[];if(d){let e={};for(let t=0;t<u.length;t+=3){let i=u[t+0],r=u[t+1],s=u[t+2],n=i.toFixed(p)+"|"+r.toFixed(p)+"|"+s.toFixed(p);if(void 0!==e[n])_.push(e[n]);else{let i=t/3;e[n]=i,_.push(i),f.push(i)}}}else for(let e=0;e<u.length;e+=3){let t=u[e+0],i=u[e+1],r=u[e+2],s=!1;for(let n=0;n<e&&!s;n+=3){let e=u[n+0],a=u[n+1],o=u[n+2];if(Math.abs(t-e)<p&&Math.abs(i-a)<p&&Math.abs(r-o)<p){_.push(n/3),s=!0;break}}s||(_.push(e/3),f.push(e/3))}if(null===(a=this._options)||void 0===a?void 0:a.applyTessellation){let e=null!==(l=null===(o=this._options)||void 0===o?void 0:o.epsilonVertexAligned)&&void 0!==l?l:1e-6,t=[];for(let i=0;i<c.length;i+=3){let r;for(let s=0;s<3;++s){let n=_[c[i+s]],a=_[c[i+(s+1)%3]],o=_[c[i+(s+2)%3]];if(n===a)continue;let l=u[3*n+0],h=u[3*n+1],d=u[3*n+2],p=u[3*a+0],m=u[3*a+1],g=u[3*a+2],v=Math.sqrt((p-l)*(p-l)+(m-h)*(m-h)+(g-d)*(g-d));for(let c=0;c<f.length-1;c++){let _=f[c];if(_===n||_===a||_===o)continue;let x=u[3*_+0],T=u[3*_+1],S=u[3*_+2],C=Math.sqrt((x-l)*(x-l)+(T-h)*(T-h)+(S-d)*(S-d)),E=Math.sqrt((x-p)*(x-p)+(T-m)*(T-m)+(S-g)*(S-g));Math.abs(C+E-v)<e&&(r||(r={index:i,edgesPoints:[[],[],[]]},t.push(r)),r.edgesPoints[s].push([_,C]))}}}for(let e=0;e<t.length;++e){let i=t[e];this._tessellateTriangle(i.edgesPoints,i.index,c,_)}t.length=0}let m={};for(let e=0;e<c.length;e+=3){let t;for(let i=0;i<3;++i){let r=_[c[e+i]],s=_[c[e+(i+1)%3]],n=_[c[e+(i+2)%3]];if(r===s||(r===n||s===n)&&(null===(h=this._options)||void 0===h?void 0:h.removeDegeneratedTriangles))continue;if(rm.jp.Vector3[0].copyFromFloats(u[3*r+0],u[3*r+1],u[3*r+2]),rm.jp.Vector3[1].copyFromFloats(u[3*s+0],u[3*s+1],u[3*s+2]),rm.jp.Vector3[2].copyFromFloats(u[3*n+0],u[3*n+1],u[3*n+2]),t||(rm.jp.Vector3[1].subtractToRef(rm.jp.Vector3[0],rm.jp.Vector3[3]),rm.jp.Vector3[2].subtractToRef(rm.jp.Vector3[1],rm.jp.Vector3[4]),(t=rm.P.Cross(rm.jp.Vector3[3],rm.jp.Vector3[4])).normalize()),r>s){let e=r;r=s,s=e}let a=r+"_"+s,o=m[a];if(o){if(!o.done){let e=rm.P.Dot(t,o.normal);e<this._epsilon&&this.createLine(rm.jp.Vector3[0],rm.jp.Vector3[1],this._linesPositions.length/3),o.done=!0}}else m[a]={normal:t,done:!1,index:e,i:i}}}for(let e in m){let t=m[e];if(!t.done){let e=_[c[t.index+t.i]],i=_[c[t.index+(t.i+1)%3]];rm.jp.Vector3[0].copyFromFloats(u[3*e+0],u[3*e+1],u[3*e+2]),rm.jp.Vector3[1].copyFromFloats(u[3*i+0],u[3*i+1],u[3*i+2]),this.createLine(rm.jp.Vector3[0],rm.jp.Vector3[1],this._linesPositions.length/3)}}let g=this._source.getScene().getEngine();this._buffers[rz.o.PositionKind]=new rz.o(g,this._linesPositions,rz.o.PositionKind,!1),this._buffers[rz.o.NormalKind]=new rz.o(g,this._linesNormals,rz.o.NormalKind,!1,!1,4),this._buffersForInstances[rz.o.PositionKind]=this._buffers[rz.o.PositionKind],this._buffersForInstances[rz.o.NormalKind]=this._buffers[rz.o.NormalKind],this._ib=g.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}_generateEdgesLines(){let e,t;let i=this._source.getVerticesData(rz.o.PositionKind),r=this._source.getIndices();if(!r||!i)return;let s=[],n=[];for(e=0;e<r.length;e+=3){t=new FaceAdjacencies;let a=r[e],o=r[e+1],l=r[e+2];t.p0=new rm.P(i[3*a],i[3*a+1],i[3*a+2]),t.p1=new rm.P(i[3*o],i[3*o+1],i[3*o+2]),t.p2=new rm.P(i[3*l],i[3*l+1],i[3*l+2]);let h=rm.P.Cross(t.p1.subtract(t.p0),t.p2.subtract(t.p1));h.normalize(),n.push(h),s.push(t)}for(e=0;e<s.length;e++){t=s[e];for(let i=e+1;i<s.length;i++){let n=s[i];if(3===t.edgesConnectedCount)break;if(3===n.edgesConnectedCount)continue;let a=r[3*i],o=r[3*i+1],l=r[3*i+2];for(let s=0;s<3;s++){let h=0;if(void 0===t.edges[s]){switch(s){case 0:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(t.p0,t.p1,n.p0,n.p1,n.p2):this._processEdgeForAdjacencies(r[3*e],r[3*e+1],a,o,l);break;case 1:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(t.p1,t.p2,n.p0,n.p1,n.p2):this._processEdgeForAdjacencies(r[3*e+1],r[3*e+2],a,o,l);break;case 2:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(t.p2,t.p0,n.p0,n.p1,n.p2):this._processEdgeForAdjacencies(r[3*e+2],r[3*e],a,o,l)}if(-1!==h&&(t.edges[s]=i,n.edges[h]=e,t.edgesConnectedCount++,n.edgesConnectedCount++,3===t.edgesConnectedCount))break}}}}for(e=0;e<s.length;e++){let t=s[e];this._checkEdge(e,t.edges[0],n,t.p0,t.p1),this._checkEdge(e,t.edges[1],n,t.p1,t.p2),this._checkEdge(e,t.edges[2],n,t.p2,t.p0)}let a=this._source.getScene().getEngine();this._buffers[rz.o.PositionKind]=new rz.o(a,this._linesPositions,rz.o.PositionKind,!1),this._buffers[rz.o.NormalKind]=new rz.o(a,this._linesNormals,rz.o.NormalKind,!1,!1,4),this._buffersForInstances[rz.o.PositionKind]=this._buffers[rz.o.PositionKind],this._buffersForInstances[rz.o.NormalKind]=this._buffers[rz.o.NormalKind],this._ib=a.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}isReady(){return this._lineShader.isReady(this._source,this._source.hasInstances&&this.customInstances.length>0||this._source.hasThinInstances)}render(){let e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}let i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances,s=0;if(r){if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){let e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!e.isFrozen){let t=0;for(let i=0;i<s;++i)this.customInstances.data[i].copyToArray(e.instancesData,t),t+=16;e.instancesBuffer.updateDirectly(e.instancesData,0,s)}}else s=this._source.thinInstanceCount}let n=e.getEngine();this._lineShader._preBind(),1!==this._source.edgesColor.a?n.setAlphaMode(2):n.setAlphaMode(0),n.bindBuffers(r?this._buffersForInstances:this._buffers,this._ib,this._lineShader.getEffect()),e.resetCachedMaterial(),this._lineShader.setColor4("color",this._source.edgesColor),e.activeCamera.mode===rj.V.ORTHOGRAPHIC_CAMERA?this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForOrthographic):this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForPerspective),this._lineShader.setFloat("aspectRatio",n.getAspectRatio(e.activeCamera)),this._lineShader.bind(this._source.getWorldMatrix()),n.drawElementsType(sr.F.TriangleFillMode,0,this._indicesCount,s),this._lineShader.unbind(),r&&n.unbindInstanceAttributes(),this._source.getScene()._activeMeshesFrozen||this.customInstances.reset(),this._lineShader._setDrawWrapper(t)}};let LineEdgesRenderer=class LineEdgesRenderer extends EdgesRenderer{constructor(e,t=.95,i=!1){super(e,t,i,!1),this._generateEdgesLines()}_generateEdgesLines(){let e=this._source.getVerticesData(rz.o.PositionKind),t=this._source.getIndices();if(!t||!e)return;let i=rm.jp.Vector3[0],r=rm.jp.Vector3[1],s=t.length-1;for(let n=0,a=0;n<s;n+=2,a+=4)rm.P.FromArrayToRef(e,3*t[n],i),rm.P.FromArrayToRef(e,3*t[n+1],r),this.createLine(i,r,a);let n=this._source.getScene().getEngine();this._buffers[rz.o.PositionKind]=new rz.o(n,this._linesPositions,rz.o.PositionKind,!1),this._buffers[rz.o.NormalKind]=new rz.o(n,this._linesNormals,rz.o.NormalKind,!1,!1,4),this._ib=n.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}};let PrePassRenderTarget=class PrePassRenderTarget extends MultiRenderTarget{constructor(e,t,i,r,s,n){super(e,i,r,s,n),this._beforeCompositionPostProcesses=[],this._internalTextureDirty=!1,this.enabled=!1,this.renderTargetTexture=null,this.renderTargetTexture=t}_createCompositionEffect(){this.imageProcessingPostProcess=new ImageProcessingPostProcess("prePassComposition",1,null,void 0,this._engine),this.imageProcessingPostProcess._updateParameters()}_checkSize(){let e=this._engine.getRenderWidth(!0),t=this._engine.getRenderHeight(!0),i=this.getRenderWidth(),r=this.getRenderHeight();(i!==e||r!==t)&&(this.resize({width:e,height:t}),this._internalTextureDirty=!0)}updateCount(e,t,i){super.updateCount(e,t,i),this._internalTextureDirty=!0}_resetPostProcessChain(){this._beforeCompositionPostProcesses.length=0}dispose(){let e=this._scene;if(super.dispose(),e&&e.prePassRenderer){let t=e.prePassRenderer.renderTargets.indexOf(this);-1!==t&&e.prePassRenderer.renderTargets.splice(t,1)}this.imageProcessingPostProcess&&this.imageProcessingPostProcess.dispose(),this.renderTargetTexture&&(this.renderTargetTexture._prePassRenderTarget=null),this._outputPostProcess&&(this._outputPostProcess.autoClear=!0,this._outputPostProcess.restoreDefaultInputTexture())}};let PrePassRenderer=class PrePassRenderer{get generateNormalsInWorldSpace(){return this._generateNormalsInWorldSpace}set generateNormalsInWorldSpace(e){this._generateNormalsInWorldSpace!==e&&(this._generateNormalsInWorldSpace=e,this._markAllMaterialsAsPrePassDirty())}getIndex(e){return this._textureIndices[e]}get samples(){return this.defaultRT.samples}set samples(e){this.defaultRT.samples=e}get useSpecificClearForDepthTexture(){return this._useSpecificClearForDepthTexture}set useSpecificClearForDepthTexture(e){this._useSpecificClearForDepthTexture!==e&&(this._useSpecificClearForDepthTexture=e,this._isDirty=!0)}getRenderTarget(){return this._currentTarget}_setRenderTarget(e){var t,i;e?this._currentTarget=e:(this._currentTarget=this.defaultRT,this._engine.currentRenderPassId=null!==(i=null===(t=this._scene.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==i?i:this._currentTarget.renderPassId)}get currentRTisSceneRT(){return this._currentTarget===this.defaultRT}_refreshGeometryBufferRendererLink(){if(this.doNotUseGeometryRendererFallback)this._geometryBuffer&&this._geometryBuffer._unlinkPrePassRenderer(),this._geometryBuffer=null,this._scene.disableGeometryBufferRenderer();else{if(this._geometryBuffer=this._scene.enableGeometryBufferRenderer(),!this._geometryBuffer){this.doNotUseGeometryRendererFallback=!0;return}this._geometryBuffer._linkPrePassRenderer(this)}}get enabled(){return this._enabled}constructor(e){this.excludedSkinnedMesh=[],this.excludedMaterials=[],this.mrtCount=0,this._mrtTypes=[],this._mrtFormats=[],this._mrtLayout=[],this._mrtNames=[],this._textureIndices=[],this._generateNormalsInWorldSpace=!1,this._useSpecificClearForDepthTexture=!1,this._isDirty=!0,this._effectConfigurations=[],this.doNotUseGeometryRendererFallback=!0,this.renderTargets=[],this._clearColor=new rg.HE(0,0,0,0),this._clearDepthColor=new rg.HE(1e8,0,0,1),this._enabled=!1,this._needsCompositionForThisPass=!1,this.disableGammaTransform=!1,this._scene=e,this._engine=e.getEngine();let t=0;if(this._engine._caps.textureFloat&&this._engine._caps.textureFloatLinearFiltering?t=1:this._engine._caps.textureHalfFloat&&this._engine._caps.textureHalfFloatLinearFiltering&&(t=2),1!==t)for(let e=0;e<PrePassRenderer.TextureFormats.length;++e)1===PrePassRenderer.TextureFormats[e].type&&(PrePassRenderer.TextureFormats[5].type=t);PrePassRenderer._SceneComponentInitialization(this._scene),this.defaultRT=this._createRenderTarget("sceneprePassRT",null),this._currentTarget=this.defaultRT}_createRenderTarget(e,t){let i=new PrePassRenderTarget(e,t,{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},0,this._scene,{generateMipMaps:!1,generateStencilBuffer:this._engine.isStencilEnable,defaultType:0,types:[],drawOnlyOnFirstAttachmentByDefault:!0});return this.renderTargets.push(i),this._enabled&&this._update(),i}get isSupported(){return this._scene.getEngine().getCaps().drawBuffersExtension}bindAttachmentsForEffect(e,t){let i=t.getMaterial(),r=i&&i.isPrePassCapable,s=i&&-1!==this.excludedMaterials.indexOf(i);this.enabled&&this._currentTarget.enabled&&(e._multiTarget&&r&&!s?this._engine.bindAttachments(this._multiRenderAttachments):(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment(),this._geometryBuffer&&this.currentRTisSceneRT&&!s&&this._geometryBuffer.renderList.push(t.getRenderingMesh())))}_reinitializeAttachments(){let e=[],t=[!1],i=[!1],r=[!0];for(let s=0;s<this.mrtCount;s++)e.push(!0),s>0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;e<PrePassRenderer.TextureFormats.length;e++)this._textureIndices[PrePassRenderer.TextureFormats[e].purpose]=-1;this._textureIndices[4]=0,this._mrtLayout=[4],this._mrtTypes=[PrePassRenderer.TextureFormats[4].type],this._mrtFormats=[PrePassRenderer.TextureFormats[4].format],this._mrtNames=[PrePassRenderer.TextureFormats[4].name],this.mrtCount=1}_updateGeometryBufferLayout(){if(this._refreshGeometryBufferRendererLink(),this._geometryBuffer){this._geometryBuffer._resetLayout();let e=[];for(let t=0;t<this._mrtLayout.length;t++)e.push(!1);this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture());let t=[{prePassConstant:5,geometryBufferConstant:GeometryBufferRenderer.DEPTH_TEXTURE_TYPE},{prePassConstant:6,geometryBufferConstant:GeometryBufferRenderer.NORMAL_TEXTURE_TYPE},{prePassConstant:1,geometryBufferConstant:GeometryBufferRenderer.POSITION_TEXTURE_TYPE},{prePassConstant:3,geometryBufferConstant:GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE},{prePassConstant:2,geometryBufferConstant:GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE}];for(let i=0;i<t.length;i++){let r=this._mrtLayout.indexOf(t[i].prePassConstant);-1!==r&&(this._geometryBuffer._forceTextureType(t[i].geometryBufferConstant,r),e[r]=!0)}this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(e))}}restoreAttachments(){this.enabled&&this._currentTarget.enabled&&this._defaultAttachments&&(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment())}_beforeDraw(e,t,i){this._isDirty&&this._update(),this._enabled&&this._currentTarget.enabled&&(this._geometryBuffer&&(this._geometryBuffer.renderList=[]),this._setupOutputForThisPass(this._currentTarget,e))}_prepareFrame(e,t,i){e.renderTargetTexture?e.renderTargetTexture._prepareFrame(this._scene,t,i,e.renderTargetTexture.useCameraPostProcesses):this._postProcessesSourceForThisPass.length?this._scene.postProcessManager._prepareFrame():this._engine.restoreDefaultFramebuffer()}setCustomOutput(e){let t=this._postProcessesSourceForThisPass[0];return!!t&&(t.inputTexture=e.renderTarget,!0)}_renderPostProcesses(e,t){var i;let r=this._postProcessesSourceForThisPass[0],s=r?r.inputTexture:e.renderTargetTexture?e.renderTargetTexture.renderTarget:null,n=this._currentTarget._beforeCompositionPostProcesses;this._needsCompositionForThisPass&&(n=n.concat([this._currentTarget.imageProcessingPostProcess])),n.length&&(this._scene.postProcessManager._prepareFrame(null===(i=this._currentTarget.renderTarget)||void 0===i?void 0:i.texture,n),this._scene.postProcessManager.directRender(n,s,!1,t))}_afterDraw(e,t){this._enabled&&this._currentTarget.enabled&&(this._prepareFrame(this._currentTarget,e,t),this._renderPostProcesses(this._currentTarget,e))}_clear(){this._enabled&&this._currentTarget.enabled&&(this._bindFrameBuffer(),this._engine.bindAttachments(this._clearAttachments),this._engine.clear(this._clearColor,!0,!1,!1),this._useSpecificClearForDepthTexture&&(this._engine.bindAttachments(this._clearDepthAttachments),this._engine.clear(this._clearDepthColor,!0,!1,!1)),this._engine.bindAttachments(this._defaultAttachments))}_bindFrameBuffer(){if(this._enabled&&this._currentTarget.enabled){this._currentTarget._checkSize();let e=this._currentTarget.renderTarget;e&&this._engine.bindFramebuffer(e)}}_setEnabled(e){this._enabled=e}_setRenderTargetEnabled(e,t){e.enabled=t,t||this._unlinkInternalTexture(e)}addEffectConfiguration(e){for(let t=0;t<this._effectConfigurations.length;t++)if(this._effectConfigurations[t].name===e.name)return this._effectConfigurations[t];return this._effectConfigurations.push(e),e}getEffectConfiguration(e){for(let t=0;t<this._effectConfigurations.length;t++)if(this._effectConfigurations[t].name===e)return this._effectConfigurations[t];return null}_enable(){let e=this.mrtCount;for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled&&this._enableTextures(this._effectConfigurations[e].texturesRequired);for(let t=0;t<this.renderTargets.length;t++){(this.mrtCount!==e||this.renderTargets[t].count!==this.mrtCount)&&this.renderTargets[t].updateCount(this.mrtCount,{types:this._mrtTypes,formats:this._mrtFormats},this._mrtNames.concat("prePass_DepthBuffer")),this.renderTargets[t]._resetPostProcessChain();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled&&(!this._effectConfigurations[e].postProcess&&this._effectConfigurations[e].createPostProcess&&this._effectConfigurations[e].createPostProcess(),this._effectConfigurations[e].postProcess&&this.renderTargets[t]._beforeCompositionPostProcesses.push(this._effectConfigurations[e].postProcess))}this._reinitializeAttachments(),this._setEnabled(!0),this._updateGeometryBufferLayout()}_disable(){this._setEnabled(!1);for(let e=0;e<this.renderTargets.length;e++)this._setRenderTargetEnabled(this.renderTargets[e],!1);this._resetLayout();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled=!1}_getPostProcessesSource(e,t){if(t)return t._postProcesses;if(!e.renderTargetTexture)return this._scene.activeCamera?this._scene.activeCamera._postProcesses:[];if(e.renderTargetTexture.useCameraPostProcesses){let t=e.renderTargetTexture.activeCamera?e.renderTargetTexture.activeCamera:this._scene.activeCamera;return t?t._postProcesses:[]}return e.renderTargetTexture.postProcesses?e.renderTargetTexture.postProcesses:[]}_setupOutputForThisPass(e,t){let i=t&&this._scene.activeCameras&&!!this._scene.activeCameras.length&&0!==this._scene.activeCameras.indexOf(t);this._postProcessesSourceForThisPass=this._getPostProcessesSource(e,t),this._postProcessesSourceForThisPass=this._postProcessesSourceForThisPass.filter(e=>null!=e),this._scene.autoClear=!0;let r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;let s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0],a=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?a=n:this._needsCompositionForThisPass?a=e.imageProcessingPostProcess:s&&(a=s),this._bindFrameBuffer(),this._linkInternalTexture(e,a)}_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;e<this._effectConfigurations.length;e++)if(this._effectConfigurations[e].enabled&&this._effectConfigurations[e].needsImageProcessing)return!0;return!1}_hasImageProcessing(e){var t;let i=!1;if(e){for(let r=0;r<e.length;r++)if((null===(t=e[r])||void 0===t?void 0:t.getClassName())==="ImageProcessingPostProcess"){i=!0;break}}return i}_getFirstPostProcess(e){for(let t=0;t<e.length;t++)if(null!==e[t])return e[t];return null}markAsDirty(){this._isDirty=!0}_enableTextures(e){this._scene.needsPreviousWorldMatrices=!1;for(let t=0;t<e.length;t++){let i=e[t];-1===this._textureIndices[i]&&(this._textureIndices[i]=this._mrtLayout.length,this._mrtLayout.push(i),this._mrtTypes.push(PrePassRenderer.TextureFormats[i].type),this._mrtFormats.push(PrePassRenderer.TextureFormats[i].format),this._mrtNames.push(PrePassRenderer.TextureFormats[i].name),this.mrtCount++),2===i&&(this._scene.needsPreviousWorldMatrices=!0)}}update(){this._isDirty&&this._update()}_update(){let e;this._disable();let t=!1;this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._scene._depthPeelingRenderer&&this._scene.useOrderIndependentTransparency&&(this._scene._depthPeelingRenderer.setPrePassRenderer(this),t=!0);for(let e=0;e<this._scene.materials.length;e++)this._scene.materials[e].setPrePassRenderer(this)&&(t=!0);t&&this._setRenderTargetEnabled(this.defaultRT,!0);for(let i=0;i<this.renderTargets.length;i++){if(this.renderTargets[i].renderTargetTexture)e=this._getPostProcessesSource(this.renderTargets[i]);else{let t=this._scene.activeCamera;if(!t)continue;e=t._postProcesses}if(e&&(e=e.filter(e=>null!=e))){for(let r=0;r<e.length;r++)e[r].setPrePassRenderer(this)&&(this._setRenderTargetEnabled(this.renderTargets[i],!0),t=!0);this._hasImageProcessing(e)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!0)}}this._markAllMaterialsAsPrePassDirty(),this._isDirty=!1,t&&this._enable()}_markAllMaterialsAsPrePassDirty(){let e=this._scene.materials;for(let t=0;t<e.length;t++)e[t].markAsDirty(sr.F.PrePassDirtyFlag)}dispose(){for(let e=this.renderTargets.length-1;e>=0;e--)this.renderTargets[e].dispose();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].dispose&&this._effectConfigurations[e].dispose()}};PrePassRenderer._SceneComponentInitialization=e=>{throw(0,r$.S)("PrePassRendererSceneComponent")},PrePassRenderer.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(rN.x.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),rN.x.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new PrePassRenderer(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,rT.Y.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},rN.x.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};let PrePassRendererSceneComponent=class PrePassRendererSceneComponent{constructor(e){this.name=rQ.l.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(rQ.l.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(rQ.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(rQ.l.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(rQ.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(rQ.l.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(rQ.l.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(rQ.l.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(rQ.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,r){if(!r)return;let s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){let t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}};PrePassRenderer._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_PREPASSRENDERER);t||(t=new PrePassRendererSceneComponent(e),e._addComponent(t))};let hG=`#define rcp(x) 1./x +#define GOLDEN_RATIO 1.618033988749895 +#define TWO_PI 6.2831855 +vec2 Golden2dSeq(int i,float n) +{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} +vec2 SampleDiskGolden(int i,int sampleCount) +{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;s_.v.IncludesShadersStore.fibonacci=hG,s_.v.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";let hz=`#include<fibonacci> +#include<helperFunctions> +#include<subSurfaceScatteringFunctions> +#include<diffusionProfile> +varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; +#define rcp(x) 1./x +#define Sq(x) x*x +#define SSS_BILATERAL_FILTER true +vec3 EvalBurleyDiffusionProfile(float r,vec3 S) +{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); +vec3 expSum=exp_13*(1.+exp_13*exp_13); +return (S*rcp(8.*PI))*expSum; } +vec2 SampleBurleyDiffusionProfile(float u,float rcpS) +{u=1.-u; +float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); +float p=(g*n)*n; +float c=1.+p+n; +float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); +float x=(3./LOG2_E)*log2(c)-d; +float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; +return vec2(r,rcpPdf);} +vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) +{ +#ifndef SSS_BILATERAL_FILTER +z=0.; +#endif +float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; +#if SSS_CLAMP_ARTIFACT +return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); +#else +return EvalBurleyDiffusionProfile(r,S)*area; +#endif +} +void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, +float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) +{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; +float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; +vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; +float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) +{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} +else +{}} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) +{centerDepth=texture2D(depthSampler,vUV).r;} +if (!passedStencilTest) { +gl_FragColor=inputColor;return;} +float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; +vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; +float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) +{ +#ifdef DEBUG_SSS_SAMPLES +vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; +#endif +gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} +#ifdef DEBUG_SSS_SAMPLES +vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; +#endif +float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); +vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i<n; i++) +{EvaluateSample(i,n,S,d,centerPosVS,mmPerUnit,pixelsPerMm, +phase,totalIrradiance,totalWeight);} +totalWeight=max(totalWeight,HALF_MIN);gl_FragColor=vec4(inputColor.rgb+albedo*max(totalIrradiance/totalWeight,vec3(0.0)),1.);}`;s_.v.ShadersStore.subSurfaceScatteringPixelShader=hz;let SubSurfaceScatteringPostProcess=class SubSurfaceScatteringPostProcess extends postProcess_PostProcess{getClassName(){return"SubSurfaceScatteringPostProcess"}constructor(e,t,i,r=null,s,n,a,o=0){super(e,"subSurfaceScattering",["texelSize","viewportSize","metersPerUnit"],["diffusionS","diffusionD","filterRadii","irradianceSampler","depthSampler","albedoSampler"],i,r,s||texture_Texture.BILINEAR_SAMPLINGMODE,n,a,null,o,"postprocess",void 0,!0),this._scene=t,this.updateEffect(),this.onApplyObservable.add(e=>{if(!t.prePassRenderer||!t.subSurfaceConfiguration){rT.Y.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}let 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)})}};let SubSurfaceConfiguration=class SubSurfaceConfiguration{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=rQ.l.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new rg.Wo(1,1,1)),this._scene=e,SubSurfaceConfiguration._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return rT.Y.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t<this._ssDiffusionS.length/3;t++)if(this._ssDiffusionS[3*t]===e.r&&this._ssDiffusionS[3*t+1]===e.g&&this._ssDiffusionS[3*t+2]===e.b)return t;return this._ssDiffusionS.push(e.r,e.b,e.g),this._ssDiffusionD.push(Math.max(Math.max(e.r,e.b),e.g)),this._ssFilterRadii.push(this.getDiffusionProfileParameters(e)),this.ssDiffusionProfileColors.push(e),this._ssDiffusionD.length-1}createPostProcess(){return this.postProcess=new SubSurfaceScatteringPostProcess("subSurfaceScattering",this._scene,1,null,void 0,this._scene.getEngine()),this.postProcess.autoClear=!1,this.postProcess}clearAllDiffusionProfiles(){this._ssDiffusionD=[],this._ssDiffusionS=[],this._ssFilterRadii=[],this.ssDiffusionProfileColors=[]}dispose(){this.clearAllDiffusionProfiles(),this.postProcess&&this.postProcess.dispose()}getDiffusionProfileParameters(e){let t=Math.max(e.r,e.g,e.b);return this._sampleBurleyDiffusionProfile(.997,t)}_sampleBurleyDiffusionProfile(e,t){e=1-e;let i=1+4*e*(2*e+Math.sqrt(1+4*e*e)),r=Math.pow(i,-1/3),s=3*Math.log((1+i*r*r+r)/(4*e));return s*t}};SubSurfaceConfiguration._SceneComponentInitialization=e=>{throw(0,r$.S)("SubSurfaceSceneComponent")},rp.p.AddParser(rQ.l.NAME_SUBSURFACE,(e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,r=e.ssDiffusionProfileColors.length;i<r;i++){let r=e.ssDiffusionProfileColors[i];t.subSurfaceConfiguration.addDiffusionProfile(new rg.Wo(r.r,r.g,r.b))}}),Object.defineProperty(rN.x.prototype,"subSurfaceConfiguration",{get:function(){return this._subSurfaceConfiguration},set:function(e){e&&this.enablePrePassRenderer()&&(this._subSurfaceConfiguration=e)},enumerable:!0,configurable:!0}),rN.x.prototype.enableSubSurfaceForPrePass=function(){if(this._subSurfaceConfiguration)return this._subSurfaceConfiguration;let e=this.enablePrePassRenderer();return e?(this._subSurfaceConfiguration=new SubSurfaceConfiguration(this),e.addEffectConfiguration(this._subSurfaceConfiguration),this._subSurfaceConfiguration):null},rN.x.prototype.disableSubSurfaceForPrePass=function(){this._subSurfaceConfiguration&&(this._subSurfaceConfiguration.dispose(),this._subSurfaceConfiguration=null)};let SubSurfaceSceneComponent=class SubSurfaceSceneComponent{constructor(e){this.name=rQ.l.NAME_PREPASSRENDERER,this.scene=e}register(){}serialize(e){if(!this.scene.subSurfaceConfiguration)return;let t=this.scene.subSurfaceConfiguration.ssDiffusionProfileColors;e.ssDiffusionProfileColors=[];for(let i=0;i<t.length;i++)e.ssDiffusionProfileColors.push({r:t[i].r,g:t[i].g,b:t[i].b})}addFromContainer(){}removeFromContainer(){this.scene.prePassRenderer&&this.scene.subSurfaceConfiguration&&this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles()}rebuild(){}dispose(){}};SubSurfaceConfiguration._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_SUBSURFACE);t||(t=new SubSurfaceSceneComponent(e),e._addComponent(t))};let hW=`#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform vec4 color; +#ifdef ALPHATEST +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include<clipPlaneFragmentDeclaration> +#include<logDepthDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include<clipPlaneFragment> +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +#include<logDepthFragment> +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;s_.v.ShadersStore.outlinePixelShader=hW;let hH=`attribute vec3 position;attribute vec3 normal; +#include<bonesDeclaration> +#include<bakedVertexAnimationDeclaration> +#include<morphTargetsVertexGlobalDeclaration> +#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] +#include<clipPlaneVertexDeclaration> +uniform float offset; +#include<instancesDeclaration> +uniform mat4 viewProjection; +#ifdef ALPHATEST +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#include<logDepthDeclaration> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position;vec3 normalUpdated=normal; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include<morphTargetsVertexGlobal> +#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] +vec3 offsetPosition=positionUpdated+(normalUpdated*offset); +#include<instancesVertex> +#include<bonesVertex> +#include<bakedVertexAnimation> +vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; +#ifdef ALPHATEST +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#include<clipPlaneVertex> +#include<logDepthVertex> +} +`;s_.v.ShadersStore.outlineVertexShader=hH,rN.x.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new OutlineRenderer(this)),this._outlineRenderer},Object.defineProperty(rV.Kj.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(rV.Kj.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});let OutlineRenderer=class OutlineRenderer{constructor(e){this.name=rQ.l.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(rQ.l.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(rQ.l.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e<this._passIdForDrawWrapper.length;++e)this._engine.releaseRenderPassId(this._passIdForDrawWrapper[e])}render(e,t,i=!1,r){r=null!=r?r:this._passIdForDrawWrapper[0];let s=this.scene,n=s.getEngine(),a=n.getCaps().instancedArrays&&(null!==t.visibleInstances[e._id]&&void 0!==t.visibleInstances[e._id]||e.getRenderingMesh().hasThinInstances);if(!this.isReady(e,a,r))return;let o=e.getMesh(),l=o._internalAbstractMeshDataInfo._actAsRegularMesh?o:null,h=e.getRenderingMesh(),u=l||h,c=e.getMaterial();if(!c||!s.activeCamera)return;let d=e._getDrawWrapper(r),p=sm.q.GetEffect(d);if(n.enableEffect(d),c.useLogarithmicDepth&&p.setFloat("logarithmicDepthConstant",2/(Math.log(s.activeCamera.maxZ+1)/Math.LN2)),p.setFloat("offset",i?0:h.outlineWidth),p.setColor4("color",i?h.overlayColor:h.outlineColor,i?h.overlayAlpha:c.alpha),p.setMatrix("viewProjection",s.getTransformMatrix()),p.setMatrix("world",u.getWorldMatrix()),h.useBones&&h.computeBonesUsingShaders&&h.skeleton&&p.setMatrices("mBones",h.skeleton.getTransformMatrices(h)),h.morphTargetManager&&h.morphTargetManager.isUsingTextureForTargets&&h.morphTargetManager._bind(p),so.G.BindMorphTargetParameters(h,p),a||h._bind(e,p,c.fillMode),c&&c.needAlphaTesting()){let e=c.getAlphaTestTexture();e&&(p.setTexture("diffuseSampler",e),p.setMatrix("diffuseMatrix",e.getTextureMatrix()))}(0,nX.an)(p,c,s),n.setZOffset(-this.zOffset),n.setZOffsetUnits(-this.zOffsetUnits),h._processRendering(u,e,p,c.fillMode,t,a,(e,t)=>{p.setMatrix("world",t)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];let r=[],s=[rz.o.PositionKind,rz.o.NormalKind],n=e.getMesh(),a=e.getMaterial();if(!a)return!1;let o=n.getScene();a.needAlphaTesting()&&(r.push("#define ALPHATEST"),n.isVerticesDataPresent(rz.o.UVKind)&&(s.push(rz.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(rz.o.UV2Kind)&&(s.push(rz.o.UV2Kind),r.push("#define UV2"))),a.useLogarithmicDepth&&r.push("#define LOGARITHMICDEPTH"),(0,nX.lK)(a,o,r),n.useBones&&n.computeBonesUsingShaders?(s.push(rz.o.MatricesIndicesKind),s.push(rz.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(rz.o.MatricesIndicesExtraKind),s.push(rz.o.MatricesWeightsExtraKind)),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");let l=n.morphTargetManager,h=0;l&&l.numInfluencers>0&&(h=l.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),so.G.PrepareAttributesForMorphTargetsInfluencers(s,n,h)),t&&(r.push("#define INSTANCES"),so.G.PushAttributesForInstances(s),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));let u=e._getDrawWrapper(i,!0),c=u.defines,d=r.join("\n");if(c!==d){let e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,nX.qx)(e),u.setEffect(this.scene.getEngine().createEffect("outline",s,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return u.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){let r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(OutlineRenderer._StencilReference),this._engine.setStencilFunctionReference(OutlineRenderer._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){let e=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}};OutlineRenderer._StencilReference=4,i(7254);let FluidRenderingObject=class FluidRenderingObject{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 rf.y$,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){let 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 EffectWrapper({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new EffectWrapper({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;let e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){let e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;let 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(){let e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;let 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()}};let FluidRenderingObjectParticleSystem=class FluidRenderingObjectParticleSystem extends FluidRenderingObject{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}};let FluidRenderingTextures=class FluidRenderingTextures{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){let 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,r,s,n,a=1,o=6,l=1,h=6,u=!1,c=null,d=!0,p=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 rf.y$,this._name=e,this._scene=t,this._camera=c,this._engine=t.getEngine(),this._width=i,this._height=r,this._blurTextureSizeX=s,this._blurTextureSizeY=n,this._textureType=a,this._textureFormat=o,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=u,this._generateDepthBuffer=d,this._samples=p,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==n,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){let[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}`});let e=this._rt.texture;e.incrementReferences(),this._texture=new texture_Texture(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,r,s,n=!1){let a=this._scene.getEngine(),o=new rm.FM(Math.floor(this._blurTextureSizeX/r),Math.floor(this._blurTextureSizeY/r)),l=1===t&&a.getCaps().textureFloatLinearFiltering||2===t&&a.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:o.x,height:o.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${s}`}),u=h.texture;u.incrementReferences();let c=new texture_Texture(null,this._scene);if(c.name="rttBlurred"+s,c._texture=u,c.wrapU=texture_Texture.CLAMP_ADDRESSMODE,c.wrapV=texture_Texture.CLAMP_ADDRESSMODE,c.anisotropicFilteringLevel=1,n){let r=new postProcess_PostProcess("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),r.onSizeChangedObservable.add(()=>{r._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(r);let s=new postProcess_PostProcess("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=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s),r.autoClear=!1,s.autoClear=!1;let n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?s:r;return[h,c,n]}{let r=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],s=new postProcess_PostProcess("BilateralBlurX","fluidRenderingBilateralBlur",r,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=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s);let n=new postProcess_PostProcess("BilateralBlurY","fluidRenderingBilateralBlur",r,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.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++}),n.onSizeChangedObservable.add(()=>{n._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(n),s.autoClear=!1,n.autoClear=!1;let o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?n:s;return[h,c,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,r;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===(r=this._textureBlurred)||void 0===r||r.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}};(tn=rn||(rn={}))[tn.DepthTexture=0]="DepthTexture",tn[tn.DepthBlurredTexture=1]="DepthBlurredTexture",tn[tn.ThicknessTexture=2]="ThicknessTexture",tn[tn.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",tn[tn.DiffuseTexture=4]="DiffuseTexture",tn[tn.Normals=5]="Normals",tn[tn.DiffuseRendering=6]="DiffuseRendering";let FluidRenderingTargetRenderer=class FluidRenderingTargetRenderer{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 rg.Wo(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new rm.P(-2,-1,1).normalize(),this._debugFeature=rn.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 rf.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 rm.y3,this._depthClearColor=new rg.HE(1e6,1e6,1e6,1),this._thicknessClearColor=new rg.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;let r=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 FluidRenderingTextures("Depth",this._scene,r,s,r,s,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){let 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 FluidRenderingTextures("Diffuse",this._scene,e,i,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}let n=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),a=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new FluidRenderingTextures("Thickness",this._scene,n,a,n,a,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;let t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],r=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;let n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new rm.FM(1/n.getSize().width,1/n.getSize().height);if(this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap){let t=null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture;t&&(r.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT"))}this._diffuseRenderTarget?(r.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(r.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),r.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),r.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===rn.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===rn.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),r.push("debugSampler"),(this._debugFeature===rn.DepthTexture||this._debugFeature===rn.DepthBlurredTexture)&&s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new postProcess_PostProcess("FluidRendering","fluidRenderingRender",i,r,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,r,s,n,o,l,h,u,c,d,p,_,f,m,g,v,x,T,S,C,E,b,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!==(n=null===(s=this._depthRenderTarget.textureBlur)||void 0===s?void 0:s.getInternalTexture())&&void 0!==n?n:null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(r=null===(i=this._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==r?r:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(u=null===(h=this._diffuseRenderTarget.textureBlur)||void 0===h?void 0:h.getInternalTexture())&&void 0!==u?u: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!==(c=this._bgDepthTexture)&&void 0!==c?c:null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(f=null===(_=this._thicknessRenderTarget.textureBlur)||void 0===_?void 0:_.getInternalTexture())&&void 0!==f?f:null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(p=null===(d=this._thicknessRenderTarget.texture)||void 0===d?void 0:d.getInternalTexture())&&void 0!==p?p:null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){let 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 rn.DepthTexture:i=this._depthRenderTarget.texture;break;case rn.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case rn.ThicknessTexture:i=null!==(x=null===(v=this._thicknessRenderTarget)||void 0===v?void 0:v.texture)&&void 0!==x?x:null;break;case rn.ThicknessBlurredTexture:i=(null===(T=this._thicknessRenderTarget)||void 0===T?void 0:T.enableBlur)?null!==(C=null===(S=this._thicknessRenderTarget)||void 0===S?void 0:S.textureBlur)&&void 0!==C?C:null:null!==(b=null===(E=this._thicknessRenderTarget)||void 0===E?void 0:E.texture)&&void 0!==b?b:null;break;case rn.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==rn.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,r,s,n,a;if(this._needInitialization||!e.isReady())return;let o=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===(r=this._thicknessRenderTarget)||void 0===r?void 0:r.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===(n=this._diffuseRenderTarget)||void 0===n||n.applyBlurPostProcesses(),null===(a=this._thicknessRenderTarget)||void 0===a||a.applyBlurPostProcesses(),o&&this._engine.bindFramebuffer(o)}dispose(e=!1){var t,i,r,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===(r=this._thicknessRenderTarget)||void 0===r||r.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}};let FluidRenderingObjectCustomParticles=class FluidRenderingObjectCustomParticles extends FluidRenderingObject{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(let t in e){let i;let r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1}this._vertexBuffers[t]=new rz.o(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new EffectWrapper({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 rz.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(){let e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;let 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;for(let t in super.dispose(),null===(e=this._diffuseEffectWrapper)||void 0===e||e.dispose(),this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}};let hX=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; +#include<helperFunctions> +void main(void) +{vec4 color=texture2D(textureSampler,vUV); +#ifdef DEPTH_TEXTURE +gl_FragDepth=color.r; +#else +if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} +gl_FragColor=color; +#endif +} +`;s_.v.ShadersStore.copyTextureToTexturePixelShader=hX,(ta=ra||(ra={}))[ta.None=0]="None",ta[ta.ToLinearSpace=1]="ToLinearSpace",ta[ta.ToGammaSpace=2]="ToGammaSpace";let CopyTextureToTexture=class CopyTextureToTexture{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new EffectRenderer(e),this._effectWrapper=new EffectWrapper({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=ra.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;let r=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&r&&(this._engine.depthCullingState.depthFunc=r),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}};let FluidRenderingDepthTextureCopy=class FluidRenderingDepthTextureCopy{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new CopyTextureToTexture(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil")}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}};let hY=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +#ifdef FLUIDRENDERING_VELOCITY +attribute vec3 velocity;varying float velocityNorm; +#endif +void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; +#ifdef FLUIDRENDERING_VELOCITY +velocityNorm=length(velocity); +#endif +} +`;s_.v.ShadersStore.fluidRenderingParticleDepthVertexShader=hY;let hj=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +#ifdef FLUIDRENDERING_VELOCITY +varying float velocityNorm; +#endif +void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); +#ifndef FLUIDRENDERING_RHS +normal.z=-normal.z; +#endif +vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; +#ifdef WEBGPU +gl_FragDepth=clipSpacePos.z/clipSpacePos.w; +#else +gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; +#endif +#ifdef FLUIDRENDERING_RHS +realViewPos.z=-realViewPos.z; +#endif +#ifdef FLUIDRENDERING_VELOCITY +glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); +#else +glFragColor=vec4(realViewPos.z,0.,0.,1.); +#endif +} +`;s_.v.ShadersStore.fluidRenderingParticleDepthPixelShader=hj;let hq=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} +`;s_.v.ShadersStore.fluidRenderingParticleThicknessVertexShader=hq;let hK=`uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} +`;s_.v.ShadersStore.fluidRenderingParticleThicknessPixelShader=hK;let h$=`attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} +`;s_.v.ShadersStore.fluidRenderingParticleDiffuseVertexShader=h$;let hQ=`uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} +`;s_.v.ShadersStore.fluidRenderingParticleDiffusePixelShader=hQ;let hZ=`uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} +int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} +glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} +`;s_.v.ShadersStore.fluidRenderingBilateralBlurPixelShader=hZ;let hJ=`uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} +float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} +sum/=wsum;glFragColor=vec4(sum.rgb,1.);} +`;s_.v.ShadersStore.fluidRenderingStandardBlurPixelShader=hJ;let h0=`/* disable_uniformity_analysis */ +#define IOR 1.333 +#define ETA 1.0/IOR +#define F0 0.02 +uniform sampler2D textureSampler;uniform sampler2D depthSampler; +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +uniform sampler2D diffuseSampler; +#else +uniform vec3 diffuseColor; +#endif +#ifdef FLUIDRENDERING_FIXED_THICKNESS +uniform float thickness;uniform sampler2D bgDepthSampler; +#else +uniform float minimumThickness;uniform sampler2D thicknessSampler; +#endif +#ifdef FLUIDRENDERING_ENVIRONMENT +uniform samplerCube reflectionSampler; +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +uniform sampler2D debugSampler; +#endif +uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; +#ifdef FLUIDRENDERING_RHS +ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; +#else +ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} +void main(void) {vec2 texCoord=vUV; +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +vec4 color=texture2D(debugSampler,texCoord); +#ifdef FLUIDRENDERING_DEBUG_DEPTH +glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} +#else +glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} +#endif +return; +#endif +vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; +#ifndef FLUIDRENDERING_FIXED_THICKNESS +float thickness=texture2D(thicknessSampler,texCoord).x; +#else +float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; +#endif +vec4 backColor=texture2D(textureSampler,texCoord); +#ifndef FLUIDRENDERING_FIXED_THICKNESS +if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { +#else +if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { +#endif +glFragColor=backColor;return;} +vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} +vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} +vec3 normal=normalize(cross(ddy,ddx)); +#ifdef FLUIDRENDERING_RHS +normal=-normal; +#endif +#ifndef WEBGPU +if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) +glFragColor=vec4(normal*0.5+0.5,1.0);return; +#endif +vec3 rayDir=normalize(viewPos); +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; +#endif +vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); +#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING +float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; +#endif +vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); +vec3 refractionColor=transmitted.rgb*transmittance; +#ifdef FLUIDRENDERING_ENVIRONMENT +vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; +#else +vec3 finalColor=refractionColor+specular; +#endif +#ifdef FLUIDRENDERING_VELOCITY +float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); +#endif +glFragColor=vec4(finalColor,transmitted.a);} +`;function IsParticleSystemObject(e){return!!e.particleSystem}s_.v.ShadersStore.fluidRenderingRenderPixelShader=h0,Object.defineProperty(rN.x.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),rN.x.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new FluidRenderer(this)),this._fluidRenderer},rN.x.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};let FluidRendererSceneComponent=class FluidRendererSceneComponent{constructor(e){this.name=rQ.l.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(rQ.l.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(rQ.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()}};let FluidRenderer=class FluidRenderer{static _SceneComponentInitialization(e){let t=e._getComponent(rQ.l.NAME_FLUIDRENDERER);t||(t=new FluidRendererSceneComponent(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,FluidRenderer._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add(()=>{this._initialize()})}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){let t=this._getParticleSystemIndex(e);return -1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){let s=new FluidRenderingObjectParticleSystem(this._scene,e);s.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new FluidRenderingTargetRenderer(this._scene,r),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==t&&(i.generateDiffuseTexture=t);let n={object:s,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,r,s){let n=new FluidRenderingObjectCustomParticles(this._scene,e,t);n.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),r||(r=new FluidRenderingTargetRenderer(this._scene,s),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==i&&(r.generateDiffuseTexture=i);let a={object:n,targetRenderer:r};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}removeRenderObject(e,t=!0){let 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.priority<t.object.priority?-1:e.object.priority>t.object.priority?1:0)}_removeUnusedTargetRenderers(){let e={};for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t].targetRenderer;e[this.targetRenderers.indexOf(i)]=!0}let t=!1,i=[];for(let r=0;r<this.targetRenderers.length;++r)e[r]?i.push(this.targetRenderers[r]):(this.targetRenderers[r].dispose(),t=!0);return t&&(this.targetRenderers.length=0,this.targetRenderers.push(...i)),t}_getParticleSystemIndex(e){for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t].object;if(IsParticleSystemObject(i)&&i.particleSystem===e)return t}return -1}_initialize(){for(let e=0;e<this.targetRenderers.length;++e)this.targetRenderers[e].dispose();let e=new Map;for(let t=0;t<this.targetRenderers.length;++t){let i=this.targetRenderers[t];if(i._initialize(),i.camera&&i._renderPostProcess){let r=e.get(i.camera);r||(r=[[],{}],e.set(i.camera,r)),r[0].push(i),i.camera.attachPostProcess(i._renderPostProcess,t)}}let t=e.keys();for(let i=t.next();!0!==i.done;i=t.next()){let t=i.value,r=e.get(t),s=t._getFirstPostProcess();if(!s)continue;let[n,a]=r;s.onSizeChangedObservable.add(()=>{var e;for(let t of(s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`),n)){let i=null===(e=t._thicknessRenderTarget)||void 0===e?void 0:e.renderTarget,r=null==i?void 0:i.texture;if(i&&r){let e=r.width+"_"+r.height,t=a[e];t||(t=a[e]=new FluidRenderingDepthTextureCopy(this._engine,r.width,r.height)),t.depthRTWrapper._shareDepth(i)}}})}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){let t=i.value,r=this._cameras.get(t),s=r[1],n=e.get(t);if(n)for(let e in s)n[1][e]||s[e].dispose();else for(let e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){let e=new Map;for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t],r=e.get(i.targetRenderer);void 0===r&&(r=0),e.set(i.targetRenderer,Math.max(r,i.object.particleSize))}e.forEach((e,t)=>{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)})}_setUseVelocityForRenderObject(){for(let e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(let e of this.targetRenderers)if(e.needInitialization){this._initialize();return}}_render(e){var t;for(let t=0;t<this.targetRenderers.length;++t)e&&this.targetRenderers[t].camera!==e||this.targetRenderers[t]._clearTargets();let i=this._cameras.keys();for(let r=i.next();!0!==r.done;r=i.next()){let i=r.value,s=this._cameras.get(i);if(e&&i!==e)continue;let n=i._getFirstPostProcess();if(!n)continue;let a=null===(t=n.inputTexture)||void 0===t?void 0:t.depthStencilTexture;if(a){let[e,t]=s;for(let t of e)t._bgDepthTexture=a;for(let e in t)t[e].copy(a)}}for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t];e&&i.targetRenderer.camera!==e||i.targetRenderer._render(i.object)}}dispose(){this._engine.onResizeObservable.remove(this._onEngineResizeObserver),this._onEngineResizeObserver=null;for(let e=0;e<this.renderObjects.length;++e)this.renderObjects[e].object.dispose();for(let e=0;e<this.targetRenderers.length;++e)this.targetRenderers[e].dispose();this._cameras.forEach(e=>{let t=e[1];for(let e in t)t[e].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}};let ThinSprite=class ThinSprite{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,e<t?this._direction=1:(this._direction=-1,this._toIndex=e,this._fromIndex=t),this.cellIndex=e,this._time=0}stopAnimation(){this._animationStarted=!1}_animate(e){this._animationStarted&&(this._time+=e,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex<this._fromIndex)&&(this._loopAnimation?this.cellIndex=this._direction>0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}};let Sprite=class Sprite extends ThinSprite{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=[],this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new rf.y$,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new rg.HE(1,1,1,1),this.position=rm.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,r,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1);this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}serialize(){let e={};return e.name=this.name,e.position=this.position.asArray(),e.color=this.color.asArray(),e.width=this.width,e.height=this.height,e.angle=this.angle,e.cellIndex=this.cellIndex,e.cellRef=this.cellRef,e.invertU=this.invertU,e.invertV=this.invertV,e.disposeWhenFinishedAnimating=this.disposeWhenFinishedAnimating,e.isPickable=this.isPickable,e.isVisible=this.isVisible,e.useAlphaForPicking=this.useAlphaForPicking,e.animationStarted=this.animationStarted,e.fromIndex=this.fromIndex,e.toIndex=this.toIndex,e.loopAnimation=this.loopAnimation,e.delay=this.delay,e}static Parse(e,t){let i=new Sprite(e.name,t);return i.position=rm.P.FromArray(e.position),i.color=rg.HE.FromArray(e.color),i.width=e.width,i.height=e.height,i.angle=e.angle,i.cellIndex=e.cellIndex,i.cellRef=e.cellRef,i.invertU=e.invertU,i.invertV=e.invertV,i.disposeWhenFinishedAnimating=e.disposeWhenFinishedAnimating,i.isPickable=e.isPickable,i.isVisible=e.isVisible,i.useAlphaForPicking=e.useAlphaForPicking,i._fromIndex=e.fromIndex,i._toIndex=e.toIndex,i._loopAnimation=e.loopAnimation,i._delay=e.delay,e.animationStarted&&i.playAnimation(i.fromIndex,i.toIndex,i.loopAnimation,i.delay),i}};rN.x.prototype._internalPickSprites=function(e,t,i,r){if(!r7.p)return null;let s=null;if(!r){if(!this.activeCamera)return null;r=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let n=0;n<this.spriteManagers.length;n++){let a=this.spriteManagers[n];if(!a.isPickable)continue;let o=a.intersects(e,r,t,i);if(o&&o.hit&&(i||null==s||!(o.distance>=s.distance))&&(s=o,i))break}return s||new r7.p},rN.x.prototype._internalMultiPickSprites=function(e,t,i){if(!r7.p)return null;let r=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s<this.spriteManagers.length;s++){let n=this.spriteManagers[s];if(!n.isPickable)continue;let a=n.multiIntersects(e,i,t);null!==a&&(r=r.concat(a))}return r},rN.x.prototype.pickSprite=function(e,t,i,r,s){if(!this._tempSpritePickingRay)return null;this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,s);let n=this._internalPickSprites(this._tempSpritePickingRay,i,r,s);return n&&(n.ray=this.createPickingRayInCameraSpace(e,t,s)),n},rN.x.prototype.pickSpriteWithRay=function(e,t,i,r){if(!this._tempSpritePickingRay)return null;if(!r){if(!this.activeCamera)return null;r=this.activeCamera}ray_Ray.TransformToRef(e,r.getViewMatrix(),this._tempSpritePickingRay);let s=this._internalPickSprites(this._tempSpritePickingRay,t,i,r);return s&&(s.ray=e),s},rN.x.prototype.multiPickSprite=function(e,t,i,r){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,r),this._internalMultiPickSprites(this._tempSpritePickingRay,i,r)},rN.x.prototype.multiPickSpriteWithRay=function(e,t,i){if(!this._tempSpritePickingRay)return null;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}return ray_Ray.TransformToRef(e,i.getViewMatrix(),this._tempSpritePickingRay),this._internalMultiPickSprites(this._tempSpritePickingRay,t,i)},rN.x.prototype.setPointerOverSprite=function(e){this._pointerOverSprite!==e&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(10,rx.V.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=e,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(9,rx.V.CreateNewFromSprite(this._pointerOverSprite,this)))},rN.x.prototype.getPointerOverSprite=function(){return this._pointerOverSprite};let SpriteSceneComponent=class SpriteSceneComponent{constructor(e){this.name=rQ.l.NAME_SPRITE,this.scene=e,this.scene.spriteManagers=[],this.scene._tempSpritePickingRay=ray_Ray?ray_Ray.Zero():null,this.scene.onBeforeSpritesRenderingObservable=new rf.y$,this.scene.onAfterSpritesRenderingObservable=new rf.y$,this._spritePredicate=e=>!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(rQ.l.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(rQ.l.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(rQ.l.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();let e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,s){let n=this.scene.pickSprite(t,i,this._spritePredicate,r,s);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,r,s){let n=this.scene;return r?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&s&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,r){let s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,rx.V.CreateNewFromSprite(i.pickedSprite,s,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,rx.V.CreateNewFromSprite(i.pickedSprite,s,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,rx.V.CreateNewFromSprite(i.pickedSprite,s,r))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,rx.V.CreateNewFromSprite(i.pickedSprite,s,r))}return i}_pointerUp(e,t,i,r,s){let n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){let i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,rx.V.CreateNewFromSprite(i.pickedSprite,n,r)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,rx.V.CreateNewFromSprite(i.pickedSprite,n,r)),s&&i.pickedSprite.actionManager.processTrigger(6,rx.V.CreateNewFromSprite(i.pickedSprite,n,r)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,rx.V.CreateNewFromSprite(n._pickedDownSprite,n,r)))}return i}};let h1=`#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); +#endif +`;s_.v.IncludesShadersStore.imageProcessingCompatibility=h1;let h2=`uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; +#include<fogFragmentDeclaration> +#define CUSTOM_FRAGMENT_DEFINITIONS +#ifdef PIXEL_PERFECT +vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} +#endif +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#ifdef PIXEL_PERFECT +vec2 uv=uvPixelPerfect(vUV); +#else +vec2 uv=vUV; +#endif +vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) +{if (color.a<0.95) +discard;} +color*=vColor; +#include<fogFragment> +gl_FragColor=color; +#include<imageProcessingCompatibility> +#define CUSTOM_FRAGMENT_MAIN_END +}`;s_.v.ShadersStore.spritesPixelShader=h2;let h3=`attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; +#include<fogVertexDeclaration> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; +vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); +vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; +#ifdef FOG +vFogDistance=viewPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.spritesVertexShader=h3;let SpriteRenderer=class SpriteRenderer{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,r=null){let s;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=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new rz.l(e,this._vertexData,!0,this._vertexBufferSize);let n=this._buffer.createVertexBuffer(rz.o.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),a=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing),o=6;if(this._useInstancing){let t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new rz.l(e,t,!1,2),s=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else s=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;let l=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer(rz.o.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[rz.o.PositionKind]=n,this._vertexBuffers.options=a,this._vertexBuffers.offsets=s,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[rz.o.ColorKind]=u,this._createEffects()}_createEffects(){var e,t,i,r;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===(r=this._drawWrapperFogDepth)||void 0===r||r.dispose(),this._drawWrapperBase=new sm.q(this._engine),this._drawWrapperFog=new sm.q(this._engine),this._drawWrapperDepth=new sm.q(this._engine,!1),this._drawWrapperFogDepth=new sm.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);let s=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[rz.o.PositionKind,"options","offsets","inverts","cellInfo",rz.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",[rz.o.PositionKind,"options","offsets","inverts","cellInfo",rz.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,r,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let n=this._drawWrapperBase,a=this._drawWrapperDepth,o=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(n=this._drawWrapperFog,a=this._drawWrapperFogDepth,o=!0);let l=n.effect;if(!l.isReady())return;let h=this._engine,u=!!(this._scene&&this._scene.useRightHandedSystem),c=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length),p=0,_=!0;for(let i=0;i<d;i++){let r=e[i];r&&r.isVisible&&(_=!1,r._animate(t),this._appendSpriteVertex(p++,r,0,0,c,u,s),this._useInstancing||(this._appendSpriteVertex(p++,r,1,0,c,u,s),this._appendSpriteVertex(p++,r,1,1,c,u,s),this._appendSpriteVertex(p++,r,0,1,c,u,s)))}if(_)return;this._buffer.update(this._vertexData);let f=!!h.depthCullingState.cull,m=h.depthCullingState.zOffset,g=h.depthCullingState.zOffsetUnits;if(h.setState(f,m,!1,!1,void 0,void 0,g),h.enableEffect(n),l.setTexture("diffuseSampler",this.texture),l.setMatrix("view",i),l.setMatrix("projection",r),o){let e=this._scene;l.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),l.setColor3("vFogColor",e.fogColor)}this._useVAO?(this._vertexArrayObject||(this._vertexArrayObject=h.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,l)),h.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):h.bindBuffers(this._vertexBuffers,this._indexBuffer,l),h.depthCullingState.depthFunc=h.useReverseDepthBuffer?518:515,this.disableDepthWrite||(l.setBool("alphaTest",!0),h.setColorWrite(!1),h.enableEffect(a),this._useInstancing?h.drawArraysType(7,0,4,p):h.drawElementsType(0,0,p/4*6),h.enableEffect(n),h.setColorWrite(!0),l.setBool("alphaTest",!1)),h.setAlphaMode(this.blendMode),this._useInstancing?h.drawArraysType(7,0,4,p):h.drawElementsType(0,0,p/4*6),this.autoResetAlpha&&h.setAlphaMode(0),u&&this._scene.getEngine().setState(f,m,!1,!0,void 0,void 0,g),h.unbindInstanceAttributes()}_appendSpriteVertex(e,t,i,r,s,n,a){let o=e*this._vertexBufferSize;if(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon),a)a(t,s);else{t.cellIndex||(t.cellIndex=0);let e=s.width/this.cellWidth,i=t.cellIndex/e>>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[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._useInstancing?o-=2:(this._vertexData[o+6]=i,this._vertexData[o+7]=r),n?this._vertexData[o+8]=t.invertU?0:1:this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0,this._vertexData[o+10]=t._xOffset,this._vertexData[o+11]=t._yOffset,this._vertexData[o+12]=t._xSize/s.width,this._vertexData[o+13]=t._ySize/s.height,this._vertexData[o+14]=t.color.r,this._vertexData[o+15]=t.color.g,this._vertexData[o+16]=t.color.b,this._vertexData[o+17]=t.color.a}_buildIndexBuffer(){let e=[],t=0;for(let i=0;i<this._capacity;i++)e.push(t),e.push(t+1),e.push(t+2),e.push(t),e.push(t+2),e.push(t+3),t+=4;this._indexBuffer=this._engine.createIndexBuffer(e)}rebuild(){var e;for(let e in this._indexBuffer&&this._buildIndexBuffer(),this._useVAO&&(this._vertexArrayObject=void 0),this._buffer._rebuild(),this._vertexBuffers){let t=this._vertexBuffers[e];t._rebuild()}null===(e=this._spriteBuffer)||void 0===e||e._rebuild()}dispose(){this._buffer&&(this._buffer.dispose(),this._buffer=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),this.texture&&(this.texture.dispose(),this.texture=null),this._drawWrapperBase.dispose(),this._drawWrapperFog.dispose(),this._drawWrapperDepth.dispose(),this._drawWrapperFogDepth.dispose()}};let spriteManager_SpriteManager=class spriteManager_SpriteManager{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get children(){return this.sprites}get scene(){return this._scene}get capacity(){return this._spriteRenderer.capacity}get texture(){return this._spriteRenderer.texture}set texture(e){e.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._spriteRenderer.texture=e,this._textureContent=null}get cellWidth(){return this._spriteRenderer.cellWidth}set cellWidth(e){this._spriteRenderer.cellWidth=e}get cellHeight(){return this._spriteRenderer.cellHeight}set cellHeight(e){this._spriteRenderer.cellHeight=e}get fogEnabled(){return this._spriteRenderer.fogEnabled}set fogEnabled(e){this._spriteRenderer.fogEnabled=e}get blendMode(){return this._spriteRenderer.blendMode}set blendMode(e){this._spriteRenderer.blendMode=e}get disableDepthWrite(){return this._disableDepthWrite}set disableDepthWrite(e){this._disableDepthWrite=e,this._spriteRenderer.disableDepthWrite=e}get pixelPerfect(){return this._spriteRenderer.pixelPerfect}set pixelPerfect(e){this._spriteRenderer.pixelPerfect=e,e&&3!==this.texture.samplingMode&&this.texture.updateSamplingMode(3)}constructor(e,t,i,r,s,n=.01,a=texture_Texture.TRILINEAR_SAMPLINGMODE,o=!1,l=null){this.name=e,this.sprites=[],this.renderingGroupId=0,this.layerMask=268435455,this.isPickable=!1,this.metadata=null,this._wasDispatched=!1,this.onDisposeObservable=new rf.y$,this._disableDepthWrite=!1,this._packedAndReady=!1,this._customUpdate=(e,t)=>{e.cellRef||(e.cellIndex=0);let 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=rS.l.LastCreatedScene),s._getComponent(rQ.l.NAME_SPRITE)||s._addComponent(new SpriteSceneComponent(s)),this._fromPacked=o,this._scene=s;let h=this._scene.getEngine();if(this._spriteRenderer=new SpriteRenderer(h,i,n,s),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else if(void 0!==r)this.cellWidth=r,this.cellHeight=r;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new texture_Texture(t,s,!0,!1,a)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if((e="string"==typeof t?JSON.parse(t):t).frames.length){let t={};for(let i=0;i<e.frames.length;i++){let r=e.frames[i];if("string"!=typeof Object.keys(r)[0])throw Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter.");let s=r[Object.keys(r)[0]];t[s]=r}e.frames=t}let i=Reflect.ownKeys(e.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=e.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,Error("Invalid JSON from string. Spritesheet managed with constant cell size.")}else{let t;let i=/\./g;do t=i.lastIndex,i.test(e);while(i.lastIndex>0);let r=e.substring(0,t-1)+".json";rW.w1.LoadFile(r,e=>{try{let t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,Error("Invalid JSON format. Please check documentation for format specifications.")}},void 0,void 0,!1,()=>{rT.Y.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1})}}_checkTextureAlpha(e,t,i,r,s){if(!e.useAlphaForPicking||!this.texture)return!0;let n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));let a=rm.jp.Vector3[0];a.copyFrom(t.direction),a.normalize(),a.scaleInPlace(i),a.addInPlace(t.origin);let o=(a.x-r.x)/(s.x-r.x),l=1-(a.y-r.y)/(s.y-r.y),h=e._xOffset*n.width+o*e._xSize|0,u=e._yOffset*n.height+l*e._ySize|0,c=this._textureContent[(h+u*n.width)*4+3];return c>.5}intersects(e,t,i,r){let s=Math.min(this.capacity,this.sprites.length),n=rm.P.Zero(),a=rm.P.Zero(),o=Number.MAX_VALUE,l=null,h=rm.jp.Vector3[0],u=rm.jp.Vector3[1],c=t.getViewMatrix(),d=e,p=e;for(let t=0;t<s;t++){let s=this.sprites[t];if(s){if(i){if(!i(s))continue}else if(!s.isPickable)continue;if(rm.P.TransformCoordinatesToRef(s.position,c,u),s.angle?(rm.y3.TranslationToRef(-u.x,-u.y,0,rm.jp.Matrix[1]),rm.y3.TranslationToRef(u.x,u.y,0,rm.jp.Matrix[2]),rm.y3.RotationZToRef(-s.angle,rm.jp.Matrix[3]),rm.jp.Matrix[1].multiplyToRef(rm.jp.Matrix[3],rm.jp.Matrix[4]),rm.jp.Matrix[4].multiplyToRef(rm.jp.Matrix[2],rm.jp.Matrix[0]),d=e.clone(),rm.P.TransformCoordinatesToRef(e.origin,rm.jp.Matrix[0],d.origin),rm.P.TransformNormalToRef(e.direction,rm.jp.Matrix[0],d.direction)):d=e,n.copyFromFloats(u.x-s.width/2,u.y-s.height/2,u.z),a.copyFromFloats(u.x+s.width/2,u.y+s.height/2,u.z),d.intersectsBoxMinMax(n,a)){let e=rm.P.Distance(u,d.origin);if(o>e){if(!this._checkTextureAlpha(s,d,e,n,a))continue;if(p=d,o=e,l=s,r)break}}}}if(l){let e=new r7.p;c.invertToRef(rm.jp.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=o;let t=rm.jp.Vector3[2];return t.copyFrom(p.direction),t.normalize(),t.scaleInPlace(o),p.origin.addToRef(t,h),e.pickedPoint=rm.P.TransformCoordinates(h,rm.jp.Matrix[0]),e}return null}multiIntersects(e,t,i){let r;let s=Math.min(this.capacity,this.sprites.length),n=rm.P.Zero(),a=rm.P.Zero(),o=[],l=rm.jp.Vector3[0].copyFromFloats(0,0,0),h=rm.jp.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix();for(let t=0;t<s;t++){let s=this.sprites[t];if(s){if(i){if(!i(s))continue}else if(!s.isPickable)continue;if(rm.P.TransformCoordinatesToRef(s.position,u,h),n.copyFromFloats(h.x-s.width/2,h.y-s.height/2,h.z),a.copyFromFloats(h.x+s.width/2,h.y+s.height/2,h.z),e.intersectsBoxMinMax(n,a)){if(r=rm.P.Distance(h,e.origin),!this._checkTextureAlpha(s,e,r,n,a))continue;let t=new r7.p;o.push(t),u.invertToRef(rm.jp.Matrix[0]),t.hit=!0,t.pickedSprite=s,t.distance=r;let i=rm.jp.Vector3[2];i.copyFrom(e.direction),i.normalize(),i.scaleInPlace(r),e.origin.addToRef(i,l),t.pickedPoint=rm.P.TransformCoordinates(l,rm.jp.Matrix[0])}}}return o}render(){if(this._fromPacked&&(!this._packedAndReady||!this._spriteMap||!this._cellData))return;let e=this._scene.getEngine(),t=e.getDeltaTime();this._packedAndReady?this._spriteRenderer.render(this.sprites,t,this._scene.getViewMatrix(),this._scene.getProjectionMatrix(),this._customUpdate):this._spriteRenderer.render(this.sprites,t,this._scene.getViewMatrix(),this._scene.getProjectionMatrix())}rebuild(){var e;null===(e=this._spriteRenderer)||void 0===e||e.rebuild()}dispose(){if(this._spriteRenderer&&(this._spriteRenderer.dispose(),this._spriteRenderer=null),this._textureContent=null,this._scene.spriteManagers){let e=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(e,1)}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null}serialize(e=!1){let t={};for(let i of(t.name=this.name,t.capacity=this.capacity,t.cellWidth=this.cellWidth,t.cellHeight=this.cellHeight,t.fogEnabled=this.fogEnabled,t.blendMode=this.blendMode,t.disableDepthWrite=this.disableDepthWrite,t.pixelPerfect=this.pixelPerfect,this.texture&&(e?t.texture=this.texture.serialize():(t.textureUrl=this.texture.name,t.invertY=this.texture._invertY)),t.sprites=[],this.sprites))t.sprites.push(i.serialize());return t.metadata=this.metadata,t}static Parse(e,t,i){let r=new spriteManager_SpriteManager(e.name,"",e.capacity,{width:e.cellWidth,height:e.cellHeight},t);for(let s of(void 0!==e.fogEnabled&&(r.fogEnabled=e.fogEnabled),void 0!==e.blendMode&&(r.blendMode=e.blendMode),void 0!==e.disableDepthWrite&&(r.disableDepthWrite=e.disableDepthWrite),void 0!==e.pixelPerfect&&(r.pixelPerfect=e.pixelPerfect),void 0!==e.metadata&&(r.metadata=e.metadata),e.texture?r.texture=texture_Texture.Parse(e.texture,t,i):e.textureName&&(r.texture=new texture_Texture(i+e.textureUrl,t,!1,void 0===e.invertY||e.invertY)),e.sprites))Sprite.Parse(s,r);return r}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,n)=>{let a=new rP.g;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let t=JSON.parse(a.responseText),n=spriteManager_SpriteManager.Parse(t,i||rS.l.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the sprite manager")}}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new spriteManager_SpriteManager("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((r,s)=>{let n=new rP.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let s=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(s.spriteManager),o=spriteManager_SpriteManager.Parse(a,t||rS.l.LastCreatedScene,i);o.snippetId=e,r(o)}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}};spriteManager_SpriteManager.SnippetUrl="https://snippet.babylonjs.com",spriteManager_SpriteManager.CreateFromSnippetAsync=spriteManager_SpriteManager.ParseFromSnippetAsync;let h4=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4( +texture2D(frameMap,vec2(fX,0.),0.), +texture2D(frameMap,vec2(fX,fdStep*1.),0.), +texture2D(frameMap,vec2(fX,fdStep*2.),0.), +vec4(0.) +);} +void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV); +#ifdef FLIPU +tileUV.y=1.0-tileUV.y; +#endif +vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i<LAYERS; i++) {float frameID; +#define LAYER_ID_SWITCH +vec4 animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,0.),0.);if(animationData.y>0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; f<MAX_ANIMATION_FRAMES; f++){if(animationData.y>mt){frameID=animationData.x;break;} +animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}} +mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;} +vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} +color.xyz*=colorMul;gl_FragColor=color;}`;s_.v.ShadersStore.spriteMapPixelShader=h4;let h5=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; +gl_Position=worldViewProjection*p;}`;s_.v.ShadersStore.spriteMapVertexShader=h5,i(3609),i(6807),i(1146),(to=ro||(ro={}))[to.INIT=0]="INIT",to[to.RUNNING=1]="RUNNING",to[to.DONE=2]="DONE",to[to.ERROR=3]="ERROR",i(320),rf.y$.prototype.notifyObserversWithPromise=async function(e,t=-1,i,r,s){let n=Promise.resolve(e);if(!this.observers.length)return n;let a=this._eventState;return a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.userInfo=s,this.observers.forEach(i=>{!a.skipNextObservers&&!i._willBeUnregistered&&i.mask&t&&(n=i.scope?n.then(t=>(a.lastReturnValue=t,i.callback.apply(i.scope,[e,a]))):n.then(t=>(a.lastReturnValue=t,i.callback(e,a))),i.unregisterOnNextCall&&this._deferUnregister(i))}),await n,e},i(8786);let SceneOptimization=class SceneOptimization{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}};let MergeMeshesOptimization=class MergeMeshesOptimization extends SceneOptimization{constructor(){super(...arguments),this._canBeMerged=e=>e instanceof rV.Kj&&!e.isDisposed()&&!!e.isVisible&&!!e.isEnabled()&&!(e.instances.length>0)&&!e.skeleton&&!e.hasLODLevels&&0!==e.getTotalVertices()}static get UpdateSelectionTree(){return MergeMeshesOptimization._UpdateSelectionTree}static set UpdateSelectionTree(e){MergeMeshesOptimization._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){let r=e.meshes.slice(0),s=r.length;for(let e=0;e<s;e++){let t=[],i=r[e];if(this._canBeMerged(i)){t.push(i);for(let n=e+1;n<s;n++){let e=r[n];this._canBeMerged(e)&&e.material===i.material&&e.checkCollisions===i.checkCollisions&&(t.push(e),s--,r.splice(n,1),n--)}t.length<2||rV.Kj.MergeMeshes(t,void 0,!0)}}return e.createOrUpdateSelectionOctree&&(void 0!=i?i&&e.createOrUpdateSelectionOctree():MergeMeshesOptimization.UpdateSelectionTree&&e.createOrUpdateSelectionOctree()),!0}};MergeMeshesOptimization._UpdateSelectionTree=!1;let h6=[],SerializeGeometry=(e,t)=>{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),h6[e.id]=!0)},SerializeMesh=(e,t)=>{let i={},r=e._geometry;return r&&!e.getScene().getGeometryById(r.id)&&SerializeGeometry(r,t.geometries),e.serialize&&e.serialize(i),i},FinalizeSingleNode=(e,t)=>{if(e._isMesh){if(1===e.delayLoadState||0===e.delayLoadState){let serializeMaterial=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 lC.G){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some(t=>t.id===e.material.id))for(let i of(t.multiMaterials.push(e.material.serialize()),e.material.subMaterials))i&&serializeMaterial(i)}else serializeMaterial(e.material)}else e.material||serializeMaterial(e.getScene().defaultMaterial);let i=e._geometry;i&&(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=[]),SerializeGeometry(i,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(SerializeMesh(e,t))}}else"TransformNode"===e.getClassName()?t.transformNodes.push(e.serialize()):-1!==e.getClassName().indexOf("Camera")?t.cameras.push(e.serialize()):-1!==e.getClassName().indexOf("Light")&&t.lights.push(e.serialize())};let sceneSerializer_SceneSerializer=class sceneSerializer_SceneSerializer{static ClearCache(){h6=[]}static Serialize(e){return sceneSerializer_SceneSerializer._Serialize(e)}static _Serialize(e,t=!0){let i,r,s;let n={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&texture_Texture.ForceSerializeBuffers&&console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),sceneSerializer_SceneSerializer.ClearCache(),n.useDelayedTextureLoading=e.useDelayedTextureLoading,n.autoClear=e.autoClear,n.clearColor=e.clearColor.asArray(),n.ambientColor=e.ambientColor.asArray(),n.gravity=e.gravity.asArray(),n.collisionsEnabled=e.collisionsEnabled,n.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(n.fogMode=e.fogMode,n.fogColor=e.fogColor.asArray(),n.fogStart=e.fogStart,n.fogEnd=e.fogEnd,n.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){let t=e.getPhysicsEngine();t&&(n.physicsEnabled=!0,n.physicsGravity=t.gravity.asArray(),n.physicsEngine=t.getPhysicsPluginName())}for(let t of(e.metadata&&(n.metadata=e.metadata),n.morphTargetManagers=[],e.meshes)){let e=t.morphTargetManager;e&&n.morphTargetManagers.push(e.serialize())}for(i=0,n.lights=[];i<e.lights.length;i++)(r=e.lights[i]).doNotSerialize||n.lights.push(r.serialize());for(i=0,n.cameras=[];i<e.cameras.length;i++){let t=e.cameras[i];t.doNotSerialize||n.cameras.push(t.serialize())}if(e.activeCamera&&(n.activeCameraID=e.activeCamera.id),rb.p4.AppendSerializedAnimations(e,n),e.animationGroups&&e.animationGroups.length>0){n.animationGroups=[];for(let t=0;t<e.animationGroups.length;t++){let i=e.animationGroups[t];n.animationGroups.push(i.serialize())}}if(e.reflectionProbes&&e.reflectionProbes.length>0)for(i=0,n.reflectionProbes=[];i<e.reflectionProbes.length;i++){let t=e.reflectionProbes[i];n.reflectionProbes.push(t.serialize())}for(i=0,n.materials=[],n.multiMaterials=[];i<e.materials.length;i++)(s=e.materials[i]).doNotSerialize||n.materials.push(s.serialize());for(i=0,n.multiMaterials=[];i<e.multiMaterials.length;i++){let t=e.multiMaterials[i];n.multiMaterials.push(t.serialize())}for(e.environmentTexture&&(e.environmentTexture._files?n.environmentTexture=e.environmentTexture.serialize():(n.environmentTexture=e.environmentTexture.name,n.environmentTextureRotationY=e.environmentTexture.rotationY)),n.environmentIntensity=e.environmentIntensity,n.skeletons=[],i=0;i<e.skeletons.length;i++){let t=e.skeletons[i];t.doNotSerialize||n.skeletons.push(t.serialize())}for(i=0,n.transformNodes=[];i<e.transformNodes.length;i++)e.transformNodes[i].doNotSerialize||n.transformNodes.push(e.transformNodes[i].serialize());n.geometries={},n.geometries.boxes=[],n.geometries.spheres=[],n.geometries.cylinders=[],n.geometries.toruses=[],n.geometries.grounds=[],n.geometries.planes=[],n.geometries.torusKnots=[],n.geometries.vertexData=[],h6=[];let a=e.getGeometries();for(i=0;i<a.length;i++){let e=a[i];e.isReady()&&SerializeGeometry(e,n.geometries)}for(i=0,n.meshes=[];i<e.meshes.length;i++){let t=e.meshes[i];t instanceof rV.Kj&&!t.doNotSerialize&&(1===t.delayLoadState||0===t.delayLoadState)&&n.meshes.push(SerializeMesh(t,n))}for(i=0,n.particleSystems=[];i<e.particleSystems.length;i++)n.particleSystems.push(e.particleSystems[i].serialize(!1));for(i=0,n.postProcesses=[];i<e.postProcesses.length;i++)n.postProcesses.push(e.postProcesses[i].serialize());for(let t of(e.actionManager&&(n.actions=e.actionManager.serialize("scene")),e._serializableComponents))t.serialize(n);return n}static SerializeAsync(e){let t=sceneSerializer_SceneSerializer._Serialize(e,!1),i=[];return this._CollectPromises(t,i),Promise.all(i).then(()=>t)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;i<e.length;++i){let r=e[i];r instanceof Promise?t.push(r.then(t=>e[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object){for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];r instanceof Promise?t.push(r.then(t=>e[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}}static SerializeMesh(e,t=!1,i=!1){let r={};if(r.meshes=[],r.transformNodes=[],r.cameras=[],r.lights=[],sceneSerializer_SceneSerializer.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let r=0;r<e.length;++r)i&&e[r].getDescendants().forEach(t=>{0>e.indexOf(t)&&!t.doNotSerialize&&e.push(t)}),t&&e[r].parent&&0>e.indexOf(e[r].parent)&&!e[r].parent.doNotSerialize&&e.push(e[r].parent);return e.forEach(e=>{FinalizeSingleNode(e,r)}),r}};let VideoRecorder=class VideoRecorder{static IsSupported(e){let t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!VideoRecorder.IsSupported(e))throw"Your browser does not support recording so far.";let 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({},VideoRecorder._DefaultOptions),t);let r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(let e of this._options.audioTracks)r.addTrack(e);this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._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)this._reject(e.error);else throw new e.error}_handleStop(){this.stopRecording();let e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&rW.w1.Download(e,this._fileName)}};VideoRecorder._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let h8=null;function CreateScreenshot(e,t,i,r,s="image/png",n=!1,a){let{height:o,width:l}=_GetScreenshotSize(e,t,i);if(!(o&&l)){rT.Y.Error("Invalid 'size' parameter !");return}h8||(h8=document.createElement("canvas")),h8.width=l,h8.height=o;let h=h8.getContext("2d"),u=e.getRenderWidth()/e.getRenderHeight(),c=l,d=c/u;d>o&&(c=(d=o)*u);let p=Math.max(0,l-c)/2,_=Math.max(0,o-d)/2,f=t.getScene();f.activeCamera!==t?CreateScreenshotUsingRenderTarget(e,t,i,e=>{if(n){let t=new Blob([e]);rW.w1.DownloadBlob(t),r&&r("")}else r&&r(e)},s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,a):e.onEndFrameObservable.addOnce(()=>{let t=e.getRenderingCanvas();h&&t&&h.drawImage(t,p,_,c,d),h8&&(n?(rW.w1.EncodeScreenshotCanvasData(h8,void 0,s,void 0,a),r&&r("")):rW.w1.EncodeScreenshotCanvasData(h8,r,s,void 0,a))})}function CreateScreenshotAsync(e,t,i,r="image/png",s){return new Promise((n,a)=>{CreateScreenshot(e,t,i,e=>{void 0!==e?n(e):a(Error("Data is undefined"))},r,void 0,s)})}function CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",n=1,a=!1,o,l=!1,h=!1,u=!0,c,d){let{height:p,width:_,finalWidth:f,finalHeight:m}=_GetScreenshotSize(e,t,i);if(!(p&&_)){rT.Y.Error("Invalid 'size' parameter !");return}let g={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(_,p);let v=t.getScene(),x=new renderTargetTexture_RenderTargetTexture("screenShot",{width:_,height:p},v,!1,!1,0,!1,texture_Texture.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);x.renderList=v.meshes.slice(),x.samples=n,x.renderSprites=l,x.activeCamera=t,x.forceLayerMaskCheck=u,null==d||d(x);let renderWhenReady=()=>{x.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce(()=>{f===_&&m===p?x.readPixels(void 0,void 0,void 0,!1).then(e=>{dumpTools_DumpTools.DumpData(_,p,e,r,s,o,!0,void 0,c),x.dispose()}):ApplyPostProcess("pass",x.getInternalTexture(),v,void 0,void 0,void 0,f,m).then(t=>{e._readTexturePixels(t,f,m,-1,0,null,!0,!1,0,0).then(e=>{dumpTools_DumpTools.DumpData(f,m,e,r,s,o,!0,void 0,c),t.dispose()})})}),x.render(!0),v.incrementRenderId(),v.resetCachedMaterial(),e.setSize(g.width,g.height),t.getProjectionMatrix(!0),v.render()):setTimeout(renderWhenReady,16)},renderToTexture=()=>{v.incrementRenderId(),v.resetCachedMaterial(),renderWhenReady()};if(a){let e=new FxaaPostProcess("antialiasing",1,v.activeCamera);x.addPostProcess(e),e.getEffect().isReady()?renderToTexture():e.getEffect().onCompiled=()=>{renderToTexture()}}else renderToTexture()}function CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,n=!1,a,o=!1,l=!1,h=!0,u){return new Promise((c,d)=>{CreateScreenshotUsingRenderTarget(e,t,i,e=>{void 0!==e?c(e):d(Error("Data is undefined"))},r,s,n,a,o,l,h,u)})}function _GetScreenshotSize(e,t,i){let r=0,s=0,n=0,a=0;if("object"==typeof i){let o=i.precision?Math.abs(i.precision):1;i.width&&i.height?(r=i.height*o,s=i.width*o):i.width&&!i.height?r=Math.round((s=i.width*o)/e.getAspectRatio(t)):i.height&&!i.width?s=Math.round((r=i.height*o)*e.getAspectRatio(t)):r=Math.round((s=Math.round(e.getRenderWidth()*o))/e.getAspectRatio(t)),i.finalWidth&&i.finalHeight?(a=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?a=Math.round((n=i.finalWidth)/e.getAspectRatio(t)):i.finalHeight&&!i.finalWidth?n=Math.round((a=i.finalHeight)*e.getAspectRatio(t)):(n=s,a=r)}else isNaN(i)||(r=i,s=i,n=i,a=i);return s&&(s=Math.floor(s)),r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),a&&(a=Math.floor(a)),{height:0|r,width:0|s,finalWidth:0|n,finalHeight:0|a}}rW.w1.CreateScreenshot=CreateScreenshot,rW.w1.CreateScreenshotAsync=CreateScreenshotAsync,rW.w1.CreateScreenshotUsingRenderTarget=CreateScreenshotUsingRenderTarget,rW.w1.CreateScreenshotUsingRenderTargetAsync=CreateScreenshotUsingRenderTargetAsync,(tl=rl||(rl={}))[tl.Checkbox=0]="Checkbox",tl[tl.Slider=1]="Slider",tl[tl.Vector3=2]="Vector3",tl[tl.Quaternion=3]="Quaternion",tl[tl.Color3=4]="Color3",tl[tl.String=5]="String",tl[tl.Button=6]="Button",tl[tl.Options=7]="Options",tl[tl.Tab=8]="Tab",tl[tl.FileButton=9]="FileButton",tl[tl.Vector2=10]="Vector2",i(9983);let DataStorage=class DataStorage{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(t){let e={};return{getItem:t=>{let i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){let i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){let 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){let i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}};DataStorage._Storage=DataStorage._GetStorage(),function(e){let Alphabet=class Alphabet{serialize(){let e={},t=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){let t=JSON.parse(e),i=new Alphabet(t.characters);return i._insertionCosts=t.insertionCosts,i._deletionCosts=t.deletionCosts,i._substitutionCosts=t.substitutionCosts,i}constructor(e,t=null,i=null,r=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,r=null!=r?r:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=Array(e.length),this._deletionCosts=Array(e.length),this._substitutionCosts=Array(e.length);for(let n=0;n<e.length;++n){s=e[n],this._characterToIdx.set(s,n),this._insertionCosts[n]=t(s),this._deletionCosts[n]=i(s),this._substitutionCosts[n]=Array(e.length);for(let t=n;t<e.length;++t)this._substitutionCosts[n][t]=r(s,e[t])}}getCharacterIdx(e){return this._characterToIdx.get(e)}getInsertionCost(e){return this._insertionCosts[e]}getDeletionCost(e){return this._deletionCosts[e]}getSubstitutionCost(e,t){return this._substitutionCosts[Math.min(e,t)][Math.max(e,t)]}};e.Alphabet=Alphabet;let Sequence=class Sequence{serialize(){return JSON.stringify(this._characters)}static Deserialize(e,t){let i=new Sequence([],t);return i._characters=JSON.parse(e),i}constructor(e,t){if(e.length>Sequence._MAX_SEQUENCE_LENGTH)throw Error("Sequences longer than "+Sequence._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map(e=>this._alphabet.getCharacterIdx(e))}distance(e){return Sequence._Distance(this,e)}static _Distance(e,t){let i=e._alphabet;if(i!==t._alphabet)throw Error("Cannot Levenshtein compare Sequences built from different alphabets.");let r=e._characters,s=t._characters,n=r.length,a=s.length,o=Sequence._CostMatrix;o[0][0]=0;for(let e=0;e<n;++e)o[e+1][0]=o[e][0]+i.getInsertionCost(r[e]);for(let e=0;e<a;++e)o[0][e+1]=o[0][e]+i.getInsertionCost(s[e]);for(let e=0;e<n;++e)for(let t=0;t<a;++t)Sequence._InsertionCost=o[e+1][t]+i.getInsertionCost(s[t]),Sequence._DeletionCost=o[e][t+1]+i.getDeletionCost(r[e]),Sequence._SubstitutionCost=o[e][t]+i.getSubstitutionCost(r[e],s[t]),o[e+1][t+1]=Math.min(Sequence._InsertionCost,Sequence._DeletionCost,Sequence._SubstitutionCost);return o[n][a]}};Sequence._MAX_SEQUENCE_LENGTH=256,Sequence._CostMatrix=[...Array(Sequence._MAX_SEQUENCE_LENGTH+1)].map(()=>Array(Sequence._MAX_SEQUENCE_LENGTH+1)),e.Sequence=Sequence}(rh||(rh={}));let Trajectory=class Trajectory{serialize(){return JSON.stringify(this)}static Deserialize(e){let t=JSON.parse(e),i=new Trajectory(t._segmentLength);return i._points=t._points.map(e=>new rm.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{let getT=()=>this._segmentLength/rm.P.Distance(this._points[t-1],e);for(let i=getT();i<=1;i=getT()){let r=this._points[t-1].scale(1-i);e.scaleAndAddToRef(i,r),this._points.push(r),++t}}}resampleAtTargetResolution(e){let t=new Trajectory(this.getLength()/e);return this._points.forEach(e=>{t.add(e)}),t}tokenize(e){let t=[],i=new rm.P;for(let r=2;r<this._points.length;++r)Trajectory._TransformSegmentDirToRef(this._points[r-2],this._points[r-1],this._points[r],i)&&t.push(Trajectory._TokenizeSegment(i,e));return t}static _TransformSegmentDirToRef(e,t,i,r){return t.subtractToRef(e,Trajectory._ForwardDir),Trajectory._ForwardDir.normalize(),t.scaleToRef(-1,Trajectory._InverseFromVec),Trajectory._InverseFromVec.normalize(),!(Math.abs(rm.P.Dot(Trajectory._ForwardDir,Trajectory._InverseFromVec))>.98)&&(rm.P.CrossToRef(Trajectory._ForwardDir,Trajectory._InverseFromVec,Trajectory._UpDir),Trajectory._UpDir.normalize(),rm.y3.LookAtLHToRef(e,t,Trajectory._UpDir,Trajectory._LookMatrix),i.subtractToRef(t,Trajectory._FromToVec),Trajectory._FromToVec.normalize(),rm.P.TransformNormalToRef(Trajectory._FromToVec,Trajectory._LookMatrix,r),!0)}static _TokenizeSegment(e,t){Trajectory._BestMatch=0,Trajectory._Score=rm.P.Dot(e,t[0]),Trajectory._BestScore=Trajectory._Score;for(let i=1;i<t.length;++i)Trajectory._Score=rm.P.Dot(e,t[i]),Trajectory._Score>Trajectory._BestScore&&(Trajectory._BestMatch=i,Trajectory._BestScore=Trajectory._Score);return Trajectory._BestMatch}};Trajectory._ForwardDir=new rm.P,Trajectory._InverseFromVec=new rm.P,Trajectory._UpDir=new rm.P,Trajectory._FromToVec=new rm.P,Trajectory._LookMatrix=new rm.y3;let TrajectoryDescriptor=class TrajectoryDescriptor{serialize(){return JSON.stringify(this._sequences.map(e=>e.serialize()))}static Deserialize(e,t){let i=new TrajectoryDescriptor;return i._sequences=JSON.parse(e).map(e=>rh.Sequence.Deserialize(e,t)),i}static CreateFromTrajectory(e,t,i){return TrajectoryDescriptor.CreateFromTokenizationPyramid(TrajectoryDescriptor._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){let i=new TrajectoryDescriptor;return i._sequences=e.map(e=>new rh.Sequence(e,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION){let r=[];for(let s=i;s>4;s=Math.floor(s/2))r.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return r}distance(e){let t=0;for(let i=0;i<this._sequences.length;++i)t+=Math.pow(2,i)*this._sequences[i].distance(e._sequences[i]);return t}};TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION=32;let TrajectoryClass=class TrajectoryClass{serialize(){let e={};return e.descriptors=this._descriptors.map(e=>e.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){let i=JSON.parse(e),r=new TrajectoryClass;return r._descriptors=i.descriptors.map(e=>TrajectoryDescriptor.Deserialize(e,t)),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map(t=>t.distance(e)))}_refreshDescription(){let e;this._centroidIdx=-1;let t=this._descriptors.map(t=>(e=0,this._descriptors.forEach(i=>{e+=t.distance(i)}),e));for(let e=0;e<t.length;++e)(this._centroidIdx<0||t[e]<t[this._centroidIdx])&&(this._centroidIdx=e);this._averageDistance=0,this._descriptors.forEach(e=>{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])}),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,TrajectoryClass._MIN_AVERAGE_DISTANCE))}};TrajectoryClass._MIN_AVERAGE_DISTANCE=1;let Reflector=class Reflector{constructor(e,t,i){this._scene=e,rT.Y.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{let t=e.data;if(t.startsWith(Reflector._SERVER_PREFIX)){let e=t.substr(Reflector._SERVER_PREFIX.length);rT.Y.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),this._handleServerMessage(e);return}rT.Y.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{rT.Y.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&sceneSerializer_SceneSerializer.SerializeAsync(this._scene).then(e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)})}_handleClientMessage(){}};Reflector._SERVER_PREFIX="$$";let DynamicFloat32Array=class DynamicFloat32Array{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(){let e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}};let h7="timestamp",h9="numPoints",ue=/\r/g;let PerformanceViewerCollector=class PerformanceViewerCollector{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{let e=rF.F.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength,r=0;if(i>0){let e=this.datasets.startingIndices.at(i-1);r=e+this.datasets.data.at(e+PerformanceViewerCollector.NumberOfPointsOffset)+PerformanceViewerCollector.SliceDataOffset}if(this.datasets.startingIndices.push(r),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())}),this.datasetObservable.hasObservers()){let i=[e,t];for(let e=0;e<t;e++)i.push(this.datasets.data.at(r+PerformanceViewerCollector.SliceDataOffset+e));this.datasetObservable.notifyObservers(i)}},this.datasets={ids:[],data:new DynamicFloat32Array(1800),startingIndices:new DynamicFloat32Array(1800)},this._strategies=new Map,this._datasetMeta=new Map,this._eventRestoreSet=new Set,this._customEventObservable=new rf.y$,this.datasetObservable=new rf.y$,this.metadataObservable=new rf.y$(e=>e.callback(this._datasetMeta,new rf.he(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var r;return this._strategies.has(e)&&!t?void 0:(this._strategies.has(e)&&t&&(null===(r=this._strategies.get(e))||void 0===r||r.dispose(),this._strategies.delete(e)),this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,r=0,s=t.onAfterRenderObservable.add(()=>{r=i,i=0}),n=this._customEventObservable.add(t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)});return{id:e,getData:()=>r,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(n)}}},category:i}),{name:e})}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach(e=>{this.registerEvent(e,!0)})}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:r}of e){let e=t(this._scene);if(this._strategies.has(e.id)){e.dispose();continue}this.datasets.ids.push(e.id),i&&(i=i.replace(RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:r}),this._strategies.set(e.id,e)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);let i="#";for(let e=0;e<24;e+=8){let r=t>>e&255;i+=("0"+r.toString(16)).substr(-2)}return i}getCurrentSlice(){let e=rF.F.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasetObservable.hasObservers()&&i.push(t.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){let r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new DynamicFloat32Array(1800),this.datasets.ids.length=0,this.datasets.startingIndices=new DynamicFloat32Array(1800),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){let i=e.replace(ue,"").split("\n").map(e=>e.split(",").filter(e=>e.length>0)).filter(e=>e.length>0),r=PerformanceViewerCollector.NumberOfPointsOffset;if(i.length<2)return!1;let s={ids:[],data:new DynamicFloat32Array(1800),startingIndices:new DynamicFloat32Array(1800)},[n,...a]=i;if(n.length<2||n[0]!==h7||n[r]!==h9)return!1;let o=new Map;for(let e=PerformanceViewerCollector.SliceDataOffset;e<n.length;e++){let[t,i]=n[e].split("@");s.ids.push(t),o.set(t,i)}let l=0;for(let e of a){if(e.length<2)return!1;let t=parseFloat(e[0]),i=parseInt(e[r]);if(isNaN(i)||isNaN(t)||(s.data.push(t),s.data.push(i),i+PerformanceViewerCollector.SliceDataOffset!==e.length))return!1;for(let t=PerformanceViewerCollector.SliceDataOffset;t<e.length;t++){let i=parseFloat(e[t]);if(isNaN(i))return!1;s.data.push(i)}s.startingIndices.push(l),l+=e.length}if(this.datasets.ids=s.ids,this.datasets.data=s.data,this.datasets.startingIndices=s.startingIndices,t||this._datasetMeta.clear(),this._strategies.forEach(e=>e.dispose()),this._strategies.clear(),!t)for(let e of this.datasets.ids){let t=o.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${h7},${h9}`;for(let t=0;t<this.datasets.ids.length;t++)if(e+=`,${this.datasets.ids[t]}`,this._datasetMeta){let i=this._datasetMeta.get(this.datasets.ids[t]);(null==i?void 0:i.category)&&(e+=`@${i.category}`)}e+="\n";for(let t=0;t<this.datasets.startingIndices.itemLength;t++){let i=this.datasets.startingIndices.at(t),r=this.datasets.data.at(i),s=this.datasets.data.at(i+PerformanceViewerCollector.NumberOfPointsOffset);e+=`${r},${s}`;for(let t=0;t<s;t++)e+=`,${this.datasets.data.at(i+PerformanceViewerCollector.SliceDataOffset+t)}`;for(let t=0;t<this.datasets.ids.length-s;t++)e+=",";e+="\n"}let t=`${new Date().toISOString()}-perfdata.csv`;rW.w1.Download(new Blob([e],{type:"text/csv"}),t)}start(e){e?void 0===this._startingTimestamp&&(this._startingTimestamp=rF.F.Now):(this.datasets.data=new DynamicFloat32Array(1800),this.datasets.startingIndices=new DynamicFloat32Array(1800),this._startingTimestamp=rF.F.Now),this._scene.onAfterRenderObservable.add(this._collectDataAtFrame),this._restoreStringEvents(),this._isStarted=!0}stop(){this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame),this._isStarted=!1}get isStarted(){return this._isStarted}dispose(){this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame),this._datasetMeta.clear(),this._strategies.forEach(e=>{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}};rN.x.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new PerformanceViewerCollector(this)),this._perfCollector};var ut=i(7521);function CreateObservableScheduler(e){let t=[],i=[],r=[],s=e.add(()=>{let e=t.length;for(let s=0;s<e;s++)(0,ut.WP)(t.shift(),i.shift(),r.shift())});return{scheduler:(e,s,n)=>{t.push(e),i.push(s),r.push(n)},dispose:()=>{e.remove(s)}}}rf.y$.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){let e=CreateObservableScheduler(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return(0,ut.sM)(e,this._coroutineScheduler)},rf.y$.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};let ui=`#ifdef GL_ES +precision highp float; +#endif +#define M_PI 3.1415926535897932384626433832795 +varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3( +- sin( longitude )*sin( latitude ), +cos( latitude ), +- cos( longitude )*sin( latitude ) +);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;s_.v.ShadersStore.equirectangularPanoramaPixelShader=ui;let WebXRHitTestLegacy=class WebXRHitTestLegacy extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this._direction=new rm.P(0,0,-1),this._mat=new rm.y3,this._onSelectEnabled=!1,this._origin=new rm.P(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new rf.y$,this._onHitTestResults=e=>{let t=e.map(e=>{let t=rm.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&&WebXRHitTestLegacy.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",rW.w1.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then(e=>{let t=r||(e=>!!e.hitMatrix);return e.filter(t)})}static XRHitTestWithSelectEvent(e,t){let i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);let r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;rm.y3.FromArrayToRef(t.transform.matrix,0,this._mat),rm.P.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),rm.P.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();let 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});WebXRHitTestLegacy.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}};WebXRHitTestLegacy.Name=webXRFeaturesManager_WebXRFeatureName.HIT_TEST,WebXRHitTestLegacy.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRHitTestLegacy.Name,(e,t)=>()=>new WebXRHitTestLegacy(e,t),WebXRHitTestLegacy.Version,!1);let ur=0;let WebXRAnchorSystem=class WebXRAnchorSystem extends WebXRAbstractFeature{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 rf.y$,this.onAnchorRemovedObservable=new rf.y$,this.onAnchorUpdatedObservable=new rf.y$,this._tmpVector=new rm.P,this._tmpQuaternion=new rm._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 rm.P,i=new rm._f){this._populateTmpTransformation(t,i);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(e.xrHitResult.createAnchor)try{let t=await e.xrHitResult.createAnchor(r);return new Promise((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:r,resolve:e,reject:i})})}catch(e){throw Error(e)}else throw this.detach(),Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new rm._f,i=!1){this._populateTmpTransformation(e,t);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:r,resolve:e,reject:t})})}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){let e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;let t=e.trackedAnchors;if(t){let i=this._trackedAnchors.filter(e=>!t.has(e.xrAnchor)).map(e=>{let t=this._trackedAnchors.indexOf(e);return t}),r=0;i.forEach(e=>{let t=this._trackedAnchors.splice(e-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),r++}),t.forEach(t=>{if(this._lastFrameDetected.has(t)){let i=this._findIndexInAnchorArray(t),r=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,r,e),r.attachedNode&&(r.attachedNode.rotationQuaternion=r.attachedNode.rotationQuaternion||new rm._f,r.transformationMatrix.decompose(r.attachedNode.scaling,r.attachedNode.rotationQuaternion,r.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(r)}catch(e){rW.w1.Warn("Anchor could not be updated")}}else{let i={id:ur++,xrAnchor:t,remove:()=>t.delete()},r=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(r),this.onAnchorAddedObservable.notifyObservers(r);let s=this._futureAnchors.filter(e=>e.nativeAnchor===t),n=s[0];n&&(n.resolve(r),n.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<this._trackedAnchors.length;++t)if(this._trackedAnchors[t].xrAnchor===e)return t;return -1}_updateAnchorWithXRFrame(e,t,i){let r=i.getPose(e.anchorSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new rm.y3;rm.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}async _createAnchorAtTransformation(e,t){var i;if(t.createAnchor)try{return t.createAnchor(e,null!==(i=this._referenceSpaceForFrameAnchors)&&void 0!==i?i:this._xrSessionManager.referenceSpace)}catch(e){throw Error(e)}else throw this.detach(),Error("Anchors are not enabled in your browser")}};WebXRAnchorSystem.Name=webXRFeaturesManager_WebXRFeatureName.ANCHOR_SYSTEM,WebXRAnchorSystem.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRAnchorSystem.Name,(e,t)=>()=>new WebXRAnchorSystem(e,t),WebXRAnchorSystem.Version);let us=0;let WebXRPlaneDetector=class WebXRPlaneDetector extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new rf.y$,this.onPlaneRemovedObservable=new rf.y$,this.onPlaneUpdatedObservable=new rf.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;){let e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){var t;if(!this.attached||!this._enabled||!e)return;let i=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(i){for(let e=0;e<this._detectedPlanes.length;e++){let t=this._detectedPlanes[e];i.has(t.xrPlane)||(this._detectedPlanes.splice(e--,1),this.onPlaneRemovedObservable.notifyObservers(t))}i.forEach(t=>{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._findIndexInPlaneArray(t),r=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,r,e),this.onPlaneUpdatedObservable.notifyObservers(r)}}else{let i={id:us++,xrPlane:t,polygonDefinition:[]},r=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(r),this.onPlaneAddedObservable.notifyObservers(r)}}),this._lastFrameDetected=i}}_init(){let internalInit=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};if(this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),!this._xrSessionManager.session.updateWorldTrackingState){internalInit();return}this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),internalInit()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map(e=>{let t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new rm.P(e.x,e.y,e.z*t)});let r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new rm.y3;rm.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t<this._detectedPlanes.length;++t)if(this._detectedPlanes[t].xrPlane===e)return t;return -1}};WebXRPlaneDetector.Name=webXRFeaturesManager_WebXRFeatureName.PLANE_DETECTION,WebXRPlaneDetector.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRPlaneDetector.Name,(e,t)=>()=>new WebXRPlaneDetector(e,t),WebXRPlaneDetector.Version);let WebXRBackgroundRemover=class WebXRBackgroundRemover extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new rf.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){let t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper){if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){let i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){let i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{let i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(t=>t.setEnabled(e)),this.onBackgroundStateChangedObservable.notifyObservers(e)}};WebXRBackgroundRemover.Name=webXRFeaturesManager_WebXRFeatureName.BACKGROUND_REMOVER,WebXRBackgroundRemover.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRBackgroundRemover.Name,(e,t)=>()=>new WebXRBackgroundRemover(e,t),WebXRBackgroundRemover.Version,!0);let WebXRControllerPhysics=class WebXRControllerPhysics extends WebXRAbstractFeature{_createPhysicsImpostor(e){let t=this._options.physicsProperties.impostorType||physicsImpostor_PhysicsImpostor.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=sphereBuilder_CreateSphere("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new rm._f;let s=e.grip||e.pointer;r.position.copyFrom(s.position),r.rotationQuaternion.copyFrom(s.rotationQuaternion);let n=new physicsImpostor_PhysicsImpostor(r,t,Object.assign({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||rT.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(()=>{let i=new physicsImpostor_PhysicsImpostor(t.rootMesh,physicsImpostor_PhysicsImpostor.MeshImpostor,Object.assign({mass:0},this._options.physicsProperties)),r=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:r.position.clone(),oldRotation:r.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new rm._f,this._tmpVector=new rm.P,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach(e=>{let 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){let e=this._options.headsetImpostorParams||{impostorType:physicsImpostor_PhysicsImpostor.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=sphereBuilder_CreateSphere("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 rm._f,this._headsetMesh.isVisible=!1,this._headsetImpostor=new physicsImpostor_PhysicsImpostor(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){let 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){let 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){let 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;let r=this._controllers[e],s=r.xrController.grip||r.xrController.pointer,n=r.oldPos||r.impostorMesh.position;if(null===(t=r.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){let e=r.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setLinearVelocity(this._tmpVector)}else s.position.subtractToRef(n,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),r.impostor.setLinearVelocity(this._tmpVector);n.copyFrom(s.position),this._debugMode&&console.log(this._tmpVector,"linear");let a=r.oldRotation||r.impostorMesh.rotationQuaternion;if(null===(i=r.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){let e=r.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setAngularVelocity(this._tmpVector)}else if(!a.equalsWithEpsilon(s.rotationQuaternion)){a.conjugateInPlace().multiplyToRef(s.rotationQuaternion,this._tmpQuaternion);let 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{let t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}r.impostor.setAngularVelocity(this._tmpVector)}a.copyFrom(s.rotationQuaternion),this._debugMode&&console.log(this._tmpVector,this._tmpQuaternion,"angular")})}_detachController(e){let t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}};WebXRControllerPhysics.Name=webXRFeaturesManager_WebXRFeatureName.PHYSICS_CONTROLLERS,WebXRControllerPhysics.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPhysics.Name,(e,t)=>()=>new WebXRControllerPhysics(e,t),WebXRControllerPhysics.Version,!0);let WebXRHitTest=class WebXRHitTest extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new rm.y3,this._tmpPos=new rm.P,this._tmpQuat=new rm._f,this._initHitTestSource=e=>{if(!e)return;let t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};if(this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),!i.space){rW.w1.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(i).then(e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new rf.y$,this.paused=!1,this.xrNativeFeatureName="hit-test",rW.w1.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach()||!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){let 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){let t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}if(this._transientXrHitTestSource){let t=e.getHitTestResultsForTransientInput(this._transientXrHitTestSource);t.forEach(e=>{this._processWebXRHitTestResult(e.results,e.inputSource)})}}}_processWebXRHitTestResult(e,t){let i=[];e.forEach(e=>{let r=e.getPose(this._xrSessionManager.referenceSpace);if(!r)return;let s=r.transform.position,n=r.transform.orientation;this._tmpPos.set(s.x,s.y,s.z),this._tmpQuat.set(n.x,n.y,n.z,n.w),rm.y3.FromFloat32ArrayToRefScaled(r.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());let 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)}};WebXRHitTest.Name=webXRFeaturesManager_WebXRFeatureName.HIT_TEST,WebXRHitTest.Version=2,WebXRFeaturesManager.AddWebXRFeature(WebXRHitTest.Name,(e,t)=>()=>new WebXRHitTest(e,t),WebXRHitTest.Version,!1);let WebXRFeaturePointSystem=class WebXRFeaturePointSystem extends WebXRAbstractFeature{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new rf.y$,this.onFeaturePointsUpdatedObservable=new rf.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;let t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw Error("Received malformed feature point cloud of length: "+t.length);let e=t.length/5,i=[],r=[];for(let s=0;s<e;s++){let e=5*s,n=t[e+4];this._featurePointCloud[n]?i.push(n):(this._featurePointCloud[n]={position:new rm.P,confidenceValue:0},r.push(n)),this._featurePointCloud[n].position.x=t[e],this._featurePointCloud[n].position.y=t[e+1],this._featurePointCloud[n].position.z=t[e+2],this._featurePointCloud[n].confidenceValue=t[e+3]}r.length>0&&this.onFeaturePointsAddedObservable.notifyObservers(r),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}};WebXRFeaturePointSystem.Name=webXRFeaturesManager_WebXRFeatureName.FEATURE_POINTS,WebXRFeaturePointSystem.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRFeaturePointSystem.Name,e=>()=>new WebXRFeaturePointSystem(e),WebXRFeaturePointSystem.Version);let un=0;let WebXRMeshDetector=class WebXRMeshDetector extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new rf.y$,this.onMeshRemovedObservable=new rf.y$,this.onMeshUpdatedObservable=new rf.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;let i=null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes;if(i){let t=new Set;this._detectedMeshes.forEach((e,r)=>{i.has(r)||t.add(r)}),t.forEach(e=>{let 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){let i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{let i={id:un++,xrMesh:t},r=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,r),this.onMeshAddedObservable.notifyObservers(r)}})}}catch(e){console.log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){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<e.positions.length;i+=3)t.positions[i]=e.positions[i],t.positions[i+1]=e.positions[i+1],t.positions[i+2]=-1*e.positions[i+2];if(e.normals){t.normals=new Float32Array(e.normals.length);for(let i=0;i<e.normals.length;i+=3)t.normals[i]=e.normals[i],t.normals[i+1]=e.normals[i+1],t.normals[i+2]=-1*e.normals[i+2]}}t.indices=e.indices;let r=i.getPose(e.meshSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new rm.y3;rm.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}}return t}};WebXRMeshDetector.Name=webXRFeaturesManager_WebXRFeatureName.MESH_DETECTION,WebXRMeshDetector.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRMeshDetector.Name,(e,t)=>()=>new WebXRMeshDetector(e,t),WebXRMeshDetector.Version,!1),(th=ru||(ru={}))[th.NotReceived=0]="NotReceived",th[th.Waiting=1]="Waiting",th[th.Received=2]="Received";let WebXRImageTracking=class WebXRImageTracking extends WebXRAbstractFeature{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new rf.y$,this.onTrackableImageFoundObservable=new rf.y$,this.onTrackedImageUpdatedObservable=new rf.y$,this._trackableScoreStatus=ru.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{};let e=this.options.images.map(e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src));try{let t=await Promise.all(e);return this._originalTrackingRequest=t.map((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch(e){return rW.w1.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===ru.Waiting)return;if(this._trackableScoreStatus===ru.NotReceived){this._checkScoresAsync();return}let t=e.getImageTrackingResults();for(let i of t){let t=!1,r=i.index,s=this._trackedImages[r];if(!s)continue;s.xrTrackingResult=i,s.realWorldWidth!==i.measuredWidthInMeters&&(s.realWorldWidth=i.measuredWidthInMeters,t=!0);let n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){let e=s.transformationMatrix;rm.y3.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}let a=i.trackingState,o="emulated"===a;s.emulated!==o&&(s.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==ru.NotReceived)return;this._trackableScoreStatus=ru.Waiting;let e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||0===e.length){this._trackableScoreStatus=ru.NotReceived;return}for(let t=0;t<e.length;++t)if("untrackable"==e[t])this.onUntrackableImageFoundObservable.notifyObservers(t);else{let e=this._originalTrackingRequest[t].image,i={id:t,originalBitmap:e,transformationMatrix:new rm.y3,ratio:e.width/e.height};this._trackedImages[t]=i,this.onTrackableImageFoundObservable.notifyObservers(i)}this._trackableScoreStatus=e.length>0?ru.Received:ru.NotReceived}};WebXRImageTracking.Name=webXRFeaturesManager_WebXRFeatureName.IMAGE_TRACKING,WebXRImageTracking.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRImageTracking.Name,(e,t)=>()=>new WebXRImageTracking(e,t),WebXRImageTracking.Version,!1);let WebXRDomOverlay=class WebXRDomOverlay extends WebXRAbstractFeature{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",rW.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 rW.w1.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){let e=document.querySelector(this.options.element);if(null===e)return rW.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}}}};WebXRDomOverlay.Name=webXRFeaturesManager_WebXRFeatureName.DOM_OVERLAY,WebXRDomOverlay.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRDomOverlay.Name,(e,t)=>()=>new WebXRDomOverlay(e,t),WebXRDomOverlay.Version,!1);let WebXRControllerMovement=class WebXRControllerMovement extends WebXRAbstractFeature{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,r,s,n,a,o;if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new rm._f,this._tmpRotationMatrix=rm.y3.Identity(),this._tmpTranslationDirection=new rm.P,this._tmpMovementTranslation=new rm.P,this._tempCacheQuaternion=new rm._f,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let initController=()=>{if(e.motionController)for(let i of this._currentRegistrationConfigurations){let r=null;if(i.allowedComponentTypes)for(let t of i.allowedComponentTypes){let i=e.motionController.getComponentOfType(t);if(null!==i){r=i;break}}if(i.mainComponentOnly){let t=e.motionController.getMainComponent();if(null===t)continue;r=t}if("function"==typeof i.componentSelectionPredicate&&(r=i.componentSelectionPredicate(e)),r&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness||null===r)continue;let s={registrationConfiguration:i,component:r};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=r.onAxisValueChangedObservable.add(e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in i&&(s.onButtonChangedObserver=r.onButtonStateChangedObservable.add(()=>{r.changes.pressed&&i.buttonChangedhandler(r.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};e.motionController?initController():e.onMotionControllerInitObservable.addOnce(()=>{initController()})}},!t||void 0===t.xrInput){rW.w1.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=WebXRControllerMovement.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(i=t.movementOrientationFollowsViewerPose)||void 0===i||i,movementSpeed:null!==(r=t.movementSpeed)&&void 0!==r?r:1,movementThreshold:null!==(s=t.movementThreshold)&&void 0!==s?s:.25,rotationEnabled:null===(n=t.rotationEnabled)||void 0===n||n,rotationSpeed:null!==(a=t.rotationSpeed)&&void 0!==a?a:1,rotationThreshold:null!==(o=t.rotationThreshold)&&void 0!==o?o:.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){let e=this._xrSessionManager.scene.getEngine().getDeltaTime(),t=.001*e*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=t,rm._f.RotationYawPitchRollToRef(t,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(rm._f.RotationYawPitchRollToRef(3*t,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(rm.y3.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),rm.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){let t=this._controllers[e];if(t){for(let e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}};WebXRControllerMovement.Name=webXRFeaturesManager_WebXRFeatureName.MOVEMENT,WebXRControllerMovement.REGISTRATIONS={default:[{allowedComponentTypes:[WebXRControllerComponent.THUMBSTICK_TYPE,WebXRControllerComponent.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:[WebXRControllerComponent.THUMBSTICK_TYPE,WebXRControllerComponent.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}}]},WebXRControllerMovement.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerMovement.Name,(e,t)=>()=>new WebXRControllerMovement(e,t),WebXRControllerMovement.Version,!0);let WebXRLightEstimation=class WebXRLightEstimation extends WebXRAbstractFeature{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=rm.P.Up().negateInPlace(),this._lightColor=rg.Wo.White(),this._intensity=1,this._sphericalHarmonics=new SphericalHarmonics,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new rf.y$,this._updateReflectionCubeMap=()=>{var e;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){let e=Date.now();if(e-this._cubeMapPollTime<this.options.cubeMapPollInterval)return;this._cubeMapPollTime=e}let t=this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe);if(t&&this._reflectionCubeMap){if(this._reflectionCubeMap._texture)null===(e=this._reflectionCubeMap._texture._hardwareTexture)||void 0===e||e.set(t),this._reflectionCubeMap._texture.getEngine().resetTextureCache();else{let e=new r5.l(this._xrSessionManager.scene.getEngine(),r5.S.Unknown);e.isCube=!0,e.invertY=!1,e._useSRGBBuffer="srgba8"===this.options.reflectionFormat,e.format=5,e.generateMipMaps=!0,e.type="srgba8"!==this.options.reflectionFormat?2:0,e.samplingMode=3,e.width=this._reflectionCubeMapTextureSize,e.height=this._reflectionCubeMapTextureSize,e._cachedWrapU=1,e._cachedWrapV=1,e._hardwareTexture=new nj.B(t,this._getCanvasContext()),this._reflectionCubeMap._texture=e}this._reflectionCubeMap._texture.isReady=!0,this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap)}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new DirectionalLight("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new rm.P(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=rY.m.FALLOFF_GLTF),rW.w1.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){let e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){var e;if(!super.attach())return!1;let t=null!==(e=this.options.reflectionFormat)&&void 0!==e?e:this._xrSessionManager.session.preferredReflectionFormat||"srgba8";return this.options.reflectionFormat=t,this._xrSessionManager.session.requestLightProbe({reflectionFormat:t}).then(e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(!this._reflectionCubeMap&&(this._reflectionCubeMap=new baseTexture_BaseTexture(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(){let 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){let e=Date.now();if(e-this._lightEstimationPollTime<this.options.lightEstimationPollInterval)return;this._lightEstimationPollTime=e}if(this._xrLightEstimate=e.getLightEstimate(this._xrLightProbe),this._xrLightEstimate){this._intensity=Math.max(1,this._xrLightEstimate.primaryLightIntensity.x,this._xrLightEstimate.primaryLightIntensity.y,this._xrLightEstimate.primaryLightIntensity.z);let e=this._xrSessionManager.scene.useRightHandedSystem?1:-1;this.options.disableVectorReuse&&(this._lightDirection=new rm.P,this._lightColor=new rg.Wo,this.directionalLight&&(this.directionalLight.direction=this._lightDirection,this.directionalLight.diffuse=this._lightColor)),this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x,this._xrLightEstimate.primaryLightDirection.y,this._xrLightEstimate.primaryLightDirection.z*e),this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x/this._intensity,this._xrLightEstimate.primaryLightIntensity.y/this._intensity,this._xrLightEstimate.primaryLightIntensity.z/this._intensity),this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients),this._reflectionCubeMap&&!this.options.disableSphericalPolynomial&&(this._reflectionCubeMap.sphericalPolynomial=this._reflectionCubeMap.sphericalPolynomial||new SphericalPolynomial,null===(t=this._reflectionCubeMap.sphericalPolynomial)||void 0===t||t.updateFromHarmonics(this._sphericalHarmonics)),this._lightDirection.negateInPlace(),this.directionalLight&&(this.directionalLight.direction.copyFrom(this._lightDirection),this.directionalLight.intensity=Math.min(this._intensity,1),this.directionalLight.diffuse.copyFrom(this._lightColor))}}}};WebXRLightEstimation.Name=webXRFeaturesManager_WebXRFeatureName.LIGHT_ESTIMATION,WebXRLightEstimation.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRLightEstimation.Name,(e,t)=>()=>new WebXRLightEstimation(e,t),WebXRLightEstimation.Version,!1);let WebXREyeTracking=class WebXREyeTracking extends WebXRAbstractFeature{constructor(e){super(e),this.onEyeTrackingStartedObservable=new rf.y$,this.onEyeTrackingEndedObservable=new rf.y$,this.onEyeTrackingFrameUpdateObservable=new rf.y$,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new ray_Ray(rm.P.Zero(),rm.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){let 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);let e=t.transform.orientation;rm.jp.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?rm.P.RightHandedForwardReadOnly.rotateByQuaternionToRef(rm.jp.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,rm.jp.Quaternion[0].z*=-1,rm.jp.Quaternion[0].w*=-1,rm.P.LeftHandedForwardReadOnly.rotateByQuaternionToRef(rm.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))}};WebXREyeTracking.Name=webXRFeaturesManager_WebXRFeatureName.EYE_TRACKING,WebXREyeTracking.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXREyeTracking.Name,e=>()=>new WebXREyeTracking(e),WebXREyeTracking.Version,!1);let CircleBuffer=class CircleBuffer{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i<e;++i)this._samples.push(t?t():rm.FM.Zero())}get length(){return this._samples.length}push(e,t){this._idx=(this._idx+this._samples.length-1)%this._samples.length,this.at(0).copyFromFloats(e,t)}at(e){if(e>=this._samples.length)throw Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}};let FirstStepDetector=class FirstStepDetector{constructor(){this._samples=new CircleBuffer(20),this._entropy=0,this.onFirstStepDetected=new rf.y$}update(e,t,i,r){let s,n;this._samples.push(e,t);let a=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=rm.FM.Distance(a,this._samples.at(1)),this._entropy>this._entropyThreshold)return;for(s=this._samePointCheckStartIdx;s<this._samples.length&&!(rm.FM.DistanceSquared(a,this._samples.at(s))<this._samePointSquaredDistanceThreshold);++s);if(s===this._samples.length)return;let o=-1,l=0;for(let e,t=1;t<s;++t)(e=rm.FM.DistanceSquared(a,this._samples.at(t)))>o&&(l=t,o=e);if(o<this._apexSquaredDistanceThreshold)return;let h=this._samples.at(l),u=h.subtract(a);u.normalize();let c=rm.jp.Vector2[0],d=0;for(let e=1;e<s;++e)this._samples.at(e).subtractToRef(a,c),n=rm.FM.Dot(u,c),d+=c.lengthSquared()-n*n;if(d>s*this._squaredProjectionDistanceThreshold)return;let p=rm.jp.Vector3[0];p.set(i,r,0);let _=rm.jp.Vector3[1];_.set(u.x,u.y,0);let f=rm.P.Cross(p,_).z>0,m=a.clone(),g=a.clone();h.subtractToRef(a,u),f?(u.scaleAndAddToRef(this._axisToApexShrinkFactor,m),u.scaleAndAddToRef(this._axisToApexExtendFactor,g)):(u.scaleAndAddToRef(this._axisToApexExtendFactor,m),u.scaleAndAddToRef(this._axisToApexShrinkFactor,g)),this.onFirstStepDetected.notifyObservers({leftApex:m,rightApex:g,currentPosition:a,currentStepDirection:f?"right":"left"})}reset(){for(let e=0;e<this._samples.length;++e)this._samples.at(e).copyFromFloats(0,0)}get _samePointCheckStartIdx(){return Math.floor(this._samples.length/3)}get _samePointSquaredDistanceThreshold(){return 9e-4}get _apexSquaredDistanceThreshold(){return .0081}get _squaredProjectionDistanceThreshold(){return 9e-4}get _axisToApexShrinkFactor(){return .8}get _axisToApexExtendFactor(){return -1.6}get _entropyDecayFactor(){return .93}get _entropyThreshold(){return .4}};let WalkingTracker=class WalkingTracker{constructor(e,t,i,r){this._leftApex=new rm.FM,this._rightApex=new rm.FM,this._currentPosition=new rm.FM,this._axis=new rm.FM,this._axisLength=-1,this._forward=new rm.FM,this._steppingLeft=!1,this._t=-1,this._maxT=-1,this._maxTPosition=new rm.FM,this._vitality=0,this.onMovement=new rf.y$,this.onFootfall=new rf.y$,this._reset(e,t,i,"left"===r)}_reset(e,t,i,r){this._leftApex.copyFrom(e),this._rightApex.copyFrom(t),this._steppingLeft=r,this._steppingLeft?(this._leftApex.subtractToRef(this._rightApex,this._axis),this._forward.copyFromFloats(-this._axis.y,this._axis.x)):(this._rightApex.subtractToRef(this._leftApex,this._axis),this._forward.copyFromFloats(this._axis.y,-this._axis.x)),this._axisLength=this._axis.length(),this._forward.scaleInPlace(1/this._axisLength),this._updateTAndVitality(i.x,i.y),this._maxT=this._t,this._maxTPosition.copyFrom(i),this._vitality=1}_updateTAndVitality(e,t){this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._currentPosition.subtractInPlace(this._rightApex):this._currentPosition.subtractInPlace(this._leftApex);let i=this._t,r=rm.FM.Dot(this._currentPosition,this._axis);this._t=r/(this._axisLength*this._axisLength);let s=this._currentPosition.lengthSquared()-r/this._axisLength*(r/this._axisLength);this._vitality*=.92-100*Math.max(s-.0016,0)+Math.max(this._t-i,0)}update(e,t){if(this._vitality<this._vitalityThreshold)return!1;let i=this._t;return this._updateTAndVitality(e,t),this._t>this._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitality<this._vitalityThreshold)&&(this._t>i&&(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}};let Walker=class Walker{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new FirstStepDetector,this._walker=null,this._movement=new rm.FM,this._millisecondsSinceLastUpdate=Walker._MillisecondsPerUpdate,this.movementThisFrame=rm.P.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(e=>{this._walker||(this._walker=new WalkingTracker(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>=Walker._MillisecondsPerUpdate){if(this._millisecondsSinceLastUpdate-=Walker._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker){let t=this._walker.update(e.x,e.z);t||(this._walker=null)}this._movement.scaleInPlace(.85)}this.movementThisFrame.set(this._movement.x,0,this._movement.y)}};let WebXRWalkingLocomotion=class WebXRWalkingLocomotion extends WebXRAbstractFeature{static get Name(){return webXRFeaturesManager_WebXRFeatureName.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 rm.P,this._forward=new rm.P,this._position=new rm.P,this._movement=new rm.P,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&rT.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 Walker(this._sessionManager.scene.getEngine()),!0)}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){let t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;let i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||rm.P.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}};WebXRFeaturesManager.AddWebXRFeature(WebXRWalkingLocomotion.Name,(e,t)=>()=>new WebXRWalkingLocomotion(e,t),WebXRWalkingLocomotion.Version,!1);let WebXRCompositionLayerWrapper=class WebXRCompositionLayerWrapper extends WebXRLayerWrapper{constructor(e,t,i,r,s,n){super(e,t,i,r,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=s,this.createRTTProvider=n}};let WebXRCompositionLayerRenderTargetTextureProvider=class WebXRCompositionLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{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,r,s,n;let a=this._lastSubImages.get(t),o="left"==t?0:1,l=null!==(i=e.colorTextureWidth)&&void 0!==i?i:e.textureWidth,h=null!==(r=e.colorTextureHeight)&&void 0!==r?r:e.textureHeight;if(!this._renderTargetTextures[o]||(null==a?void 0:a.textureWidth)!==l||(null==a?void 0:a.textureHeight)!==h){let t;let i=null!==(s=e.depthStencilTextureWidth)&&void 0!==s?s:l,r=null!==(n=e.depthStencilTextureHeight)&&void 0!==n?n:h;(l===i||h===r)&&(t=e.depthStencilTexture),this._renderTargetTextures[o]=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[o]}_getSubImageForEye(e){let t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){let t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}_setViewportForSubImage(e,t){var i,r;let s=null!==(i=t.colorTextureWidth)&&void 0!==i?i:t.textureWidth,n=null!==(r=t.colorTextureWidth)&&void 0!==r?r:t.textureHeight,a=t.viewport;e.x=a.x/s,e.y=a.y/n,e.width=a.width/s,e.height=a.height/n}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}};let WebXRProjectionLayerWrapper=class WebXRProjectionLayerWrapper extends WebXRCompositionLayerWrapper{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,e=>new WebXRProjectionLayerRenderTargetTextureProvider(e,i,this)),this.layer=e}};let WebXRProjectionLayerRenderTargetTextureProvider=class WebXRProjectionLayerRenderTargetTextureProvider extends WebXRCompositionLayerRenderTargetTextureProvider{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){let t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}};let ua={},uo={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};let WebXRLayers=class WebXRLayers extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;let t=Object.assign({},uo),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=ua){let t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new WebXRWebGLLayerWrapper(t)}createProjectionLayer(e=uo,t=!1){if(t&&"texture-array"!==e.textureType)throw 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 Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.");let i=this._xrWebGLBinding.createProjectionLayer(e);return new WebXRProjectionLayerWrapper(i,t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;let 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){}};WebXRLayers.Name=webXRFeaturesManager_WebXRFeatureName.LAYERS,WebXRLayers.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRLayers.Name,(e,t)=>()=>new WebXRLayers(e,t),WebXRLayers.Version,!1);let WebXRDepthSensing=class WebXRDepthSensing extends WebXRAbstractFeature{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;let i=this._xrSessionManager.scene.getEngine(),r=new r5.l(i,r5.S.Unknown);return r.isCube=!1,r.invertY=!1,r._useSRGBBuffer=!1,r.format="ushort"===this.depthDataFormat?2:5,r.generateMipMaps=!1,r.type="ushort"===this.depthDataFormat?5:1,r.samplingMode=7,r.width=null!==(e=this.width)&&void 0!==e?e:0,r.height=null!==(t=this.height)&&void 0!==t?t:0,r._cachedWrapU=1,r._cachedWrapV=1,r._hardwareTexture=new nj.B(this._cachedWebGLTexture,i._gl),r}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 rf.y$,this.xrNativeFeatureName="depth-sensing",rW.w1.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){if(!super.attach(e))return!1;let t=null==this._xrSessionManager.session.depthDataFormat||null==this._xrSessionManager.session.depthUsage;return!t&&(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){let t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(let t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:rW.w1.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{data:s,width:n,height:a,rawValueToMeters:o,getDepthInMeters:l}=r;switch(this._width=n,this._height=a,this._rawValueToMeters=o,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=rawTexture_RawTexture.CreateRTexture(null,n,a,this._xrSessionManager.scene,!1,!0,texture_Texture.NEAREST_SAMPLINGMODE,rq.D.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map(e=>e*o));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map(e=>e*o))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{texture:s,width:n,height:a}=r;this._width=n,this._height=a,this._cachedWebGLTexture=s;let o=this._xrSessionManager.scene,l=o.getEngine(),h=l.wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=rawTexture_RawTexture.CreateRTexture(null,n,a,o,!1,!0,texture_Texture.NEAREST_SAMPLINGMODE,"ushort"===i?rq.D.TEXTURETYPE_UNSIGNED_BYTE:rq.D.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=h}getXRSessionInitExtension(){let 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){let e=this.options.usagePreference.map(e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),t=this.options.dataFormatPreference.map(e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:e,dataFormatPreference:t}})}else i({})})}};WebXRDepthSensing.Name=webXRFeaturesManager_WebXRFeatureName.DEPTH_SENSING,WebXRDepthSensing.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRDepthSensing.Name,(e,t)=>()=>new WebXRDepthSensing(e,t),WebXRDepthSensing.Version,!1);let ul=`precision highp float; +#define CUSTOM_FRAGMENT_BEGIN +varying vec4 clipPos;varying vec4 previousClipPos; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; +#define CUSTOM_FRAGMENT_MAIN_END +}`;s_.v.ShadersStore.velocityPixelShader=ul;let uh=`#define CUSTOM_VERTEX_BEGIN +#define VELOCITY +attribute vec3 position; +#include<instancesDeclaration> +uniform mat4 viewProjection;uniform mat4 previousViewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; +#endif +varying vec4 clipPos;varying vec4 previousClipPos; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#include<instancesVertex> +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} +#elif +clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;s_.v.ShadersStore.velocityVertexShader=uh;let XRSpaceWarpRenderTarget=class XRSpaceWarpRenderTarget extends renderTargetTexture_RenderTargetTexture{constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[rm.y3.Identity(),rm.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 shaderMaterial_ShaderMaterial("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;let 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}};let WebXRSpaceWarpRenderTargetTextureProvider=class WebXRSpaceWarpRenderTargetTextureProvider{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){let t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw Error('For Space Warp, the base layer type should "XRProjectionLayer".');let i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,s){if(!this._engine)throw Error("Engine is disposed");let n=new XRSpaceWarpRenderTarget(r,s,this._scene,{width:e,height:t}),a=n.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=r,a._depthStencilTextureArray=s,n.disableRescaling(),n.renderListPredicate=()=>!0,n}_getRenderTargetForSubImage(e,t){let i=this._lastSubImages.get(t),r=this._renderTargetTextures.get(t.eye),s=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return r&&(null==i?void 0:i.textureWidth)===s&&(null==i?void 0:i.textureHeight)==n||(r=this._createRenderTargetTexture(s,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:n}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){let i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){let t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){let t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}};let WebXRSpaceWarp=class WebXRSpaceWarp extends WebXRAbstractFeature{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[webXRFeaturesManager_WebXRFeatureName.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new WebXRSpaceWarpRenderTargetTextureProvider(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add(()=>this._onAfterRender()),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;let i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}};WebXRSpaceWarp.Name=webXRFeaturesManager_WebXRFeatureName.SPACE_WARP,WebXRSpaceWarp.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRSpaceWarp.Name,e=>()=>new WebXRSpaceWarp(e),WebXRSpaceWarp.Version,!1);let WebXRGenericHandController=class WebXRGenericHandController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,uu[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(){}};WebXRMotionControllerManager.RegisterController("generic-hand-select-grasp",(e,t)=>new WebXRGenericHandController(t,e.gamepad,e.handedness));let uu={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"}};let WebXRMicrosoftMixedRealityController=class WebXRMicrosoftMixedRealityController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,uc["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?WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME:WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME;let t=WebXRMicrosoftMixedRealityController.MODEL_BASE_URL+"default/";return{filename:e,path:t}}_getModelLoadingConstraints(){let e=sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb");return e||rT.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){let i=this._mapping.buttons[e],r=i.rootNodeName;if(!r){rT.Y.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);return}let s=this._getChildByName(this.rootMesh,r);if(!s){rT.Y.Warn("Missing button mesh with name: "+r);return}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){let t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add(e=>{this._lerpTransform(i,e.value)},void 0,!0)}else rT.Y.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(e=>{let t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach(i=>{if(!this.rootMesh)return;let r=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,r.rootNodeName);if(!s){rT.Y.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?t&&t.onAxisValueChangedObservable.add(e=>{let t="x-axis"===i?e.x:e.y;this._lerpTransform(r,t,!0)},void 0,!0):rT.Y.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){let t;this.rootMesh=new rV.Kj(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i<e.length;i++){let r=e[i];r.isPickable=!1,r.parent||(t=r)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=rm._f.FromEulerAngles(0,Math.PI,0))}_updateModel(){}};WebXRMicrosoftMixedRealityController.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME="left.glb",WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME="right.glb",WebXRMotionControllerManager.RegisterController("windows-mixed-reality",(e,t)=>new WebXRMicrosoftMixedRealityController(t,e.gamepad,e.handedness));let uc={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"}};let WebXROculusTouchMotionController=class WebXROculusTouchMotionController extends WebXRAbstractMotionController{constructor(e,t,i,r=!1,s=!1){super(e,ud[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";e="left"===this.handedness?WebXROculusTouchMotionController.MODEL_LEFT_FILENAME:WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME;let t=this._isQuest()?WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL:WebXROculusTouchMotionController.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){let t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach(e=>{let r=e&&this.getComponent(e);r&&r.onButtonStateChangedObservable.add(r=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-(.2*r.value),this._modelRootNode.getChildren()[3].position.y=-(.005*r.value),this._modelRootNode.getChildren()[3].position.z=-(.005*r.value));return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*r.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(r.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(r.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new rV.Kj(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=rm._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}};WebXROculusTouchMotionController.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",WebXROculusTouchMotionController.MODEL_LEFT_FILENAME="left.babylon",WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME="right.babylon",WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",WebXRMotionControllerManager.RegisterController("oculus-touch",(e,t)=>new WebXROculusTouchMotionController(t,e.gamepad,e.handedness)),WebXRMotionControllerManager.RegisterController("oculus-touch-legacy",(e,t)=>new WebXROculusTouchMotionController(t,e.gamepad,e.handedness,!0));let ud={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"}};let WebXRHTCViveMotionController=class WebXRHTCViveMotionController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,up[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){let e=WebXRHTCViveMotionController.MODEL_FILENAME,t=WebXRHTCViveMotionController.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add(t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-(.15*t.value);return;case"xr-standard-touchpad":case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new rV.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=rm._f.FromEulerAngles(0,Math.PI,0))}_updateModel(){}};WebXRHTCViveMotionController.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",WebXRHTCViveMotionController.MODEL_FILENAME="wand.babylon",WebXRMotionControllerManager.RegisterController("htc-vive",(e,t)=>new WebXRHTCViveMotionController(t,e.gamepad,e.handedness));let up={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"}};let NativeXRFrame=class NativeXRFrame{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 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 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;let i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];let r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw Error("This function is not available in Babylon Native")}};RegisterNativeTypeAsync("NativeXRFrame",NativeXRFrame),(tu=rc||(rc={}))[tu.Input=0]="Input",tu[tu.Output=1]="Output";let FlowGraphConnection=class FlowGraphConnection{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=(0,rZ.f)(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){for(let t of(e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName(),this._connectedPoint))e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){let i=rW.w1.Instantiate(e.className),r=new i(e.name,e._connectionType,t);return r.deserialize(e),r}};let RichType=class RichType{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new RichType(e.typeName,e.defaultValue)}};let u_=new RichType("any",void 0),uf=new RichType("string",""),um=new RichType("number",0),ug=new RichType("boolean",!1),uv=new RichType("Vector2",rm.FM.Zero()),ux=new RichType("Vector3",rm.P.Zero()),uT=new RichType("Vector4",rm.Lt.Zero()),uS=new RichType("Matrix",rm.y3.Identity()),uC=new RichType("Color3",rg.Wo.Black()),uE=new RichType("Color4",new rg.HE(0,0,0,0)),ub=new RichType("Quaternion",rm._f.Identity());function getRichTypeFromValue(e){switch(typeof e){case"string":return uf;case"number":return um;case"boolean":return ug;case"object":if(e instanceof rm.FM)return uv;if(e instanceof rm.P)return ux;if(e instanceof rm.Lt)return uT;if(e instanceof rg.Wo)return uC;else if(e instanceof rg.HE)return uE;else if(e instanceof rm._f)return ub;else return u_;default:return u_}}let FlowGraphDataConnection=class FlowGraphDataConnection extends FlowGraphConnection{constructor(e,t,i,r){super(e,t,i),this.richType=r}_isSingularConnection(){return this.connectionType===rc.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===rc.Output?(this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){let i=FlowGraphConnection.Parse(e,t);return i.richType=RichType.Parse(e.richType),i}};(0,rv.H)("FGDataConnection",FlowGraphDataConnection);let FlowGraphBlock=class FlowGraphBlock{constructor(e){this.config=e,this.uniqueId=(0,rZ.f)(),this.configure()}configure(){var e,t;this.name=null!==(t=null===(e=this.config)||void 0===e?void 0:e.name)&&void 0!==t?t:this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}_registerDataInput(e,t){let i=new FlowGraphDataConnection(e,rc.Input,this,t);return this.dataInputs.push(i),i}_registerDataOutput(e,t){let i=new FlowGraphDataConnection(e,rc.Output,this,t);return this.dataOutputs.push(i),i}serialize(e={}){for(let t of(e.uniqueId=this.uniqueId,e.config=this.config,e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName(),this.dataInputs)){let i={};t.serialize(i),e.dataInputs.push(i)}for(let t of this.dataOutputs){let i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e){let t=rW.w1.Instantiate(e.className),i=new t(e.config);i.uniqueId=e.uniqueId;for(let t=0;t<e.dataInputs.length;t++)i.dataInputs[t].deserialize(e.dataInputs[t]);for(let t=0;t<e.dataOutputs.length;t++)i.dataOutputs[t].deserialize(e.dataOutputs[t]);if(i instanceof FlowGraphExecutionBlock){for(let t=0;t<e.signalInputs.length;t++)i.signalInputs[t].deserialize(e.signalInputs[t]);for(let t=0;t<e.signalOutputs.length;t++)i.signalOutputs[t].deserialize(e.signalOutputs[t])}return i}};let FlowGraphSignalConnection=class FlowGraphSignalConnection extends FlowGraphConnection{_isSingularConnection(){return this.connectionType===rc.Output}_activateSignal(e){var t;this.connectionType===rc.Input?(this._ownerBlock._execute(e,this),e._increaseExecutionId()):null===(t=this._connectedPoint[0])||void 0===t||t._activateSignal(e)}};(0,rv.H)("FlowGraphSignalConnection",FlowGraphSignalConnection);let FlowGraphExecutionBlock=class FlowGraphExecutionBlock extends FlowGraphBlock{constructor(e){super(e),this.onStart=this._registerSignalInput("onStart")}configure(){super.configure(),this.signalInputs=[],this.signalOutputs=[]}_registerSignalInput(e){let t=new FlowGraphSignalConnection(e,rc.Input,this);return this.signalInputs.push(t),t}_registerSignalOutput(e){let t=new FlowGraphSignalConnection(e,rc.Output,this);return this.signalOutputs.push(t),t}serialize(e={}){for(let t of(super.serialize(e),e.signalInputs=[],e.signalOutputs=[],this.signalInputs)){let i={};t.serialize(i),e.signalInputs.push(i)}for(let t of this.signalOutputs){let i={};t.serialize(i),e.signalOutputs.push(i)}}getClassName(){return"FGExecutionBlock"}static Parse(e={}){let t=super.Parse(e);for(let i=0;i<e.signalInputs.length;i++)t.signalInputs[i].deserialize(e.signalInputs[i]);for(let i=0;i<e.signalOutputs.length;i++)t.signalOutputs[i].deserialize(e.signalOutputs[i]);return t}};let FlowGraphAsyncExecutionBlock=class FlowGraphAsyncExecutionBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.onDone=this._registerSignalOutput("onDone")}_startPendingTasks(e){this._preparePendingTasks(e),e._addPendingBlock(this)}};let FlowGraphEventBlock=class FlowGraphEventBlock extends FlowGraphAsyncExecutionBlock{_execute(e){this.onDone._activateSignal(e)}};function isMeshClassName(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function defaultValueSerializationFunction(e,t,i){(null==t?void 0:t.getClassName)&&isMeshClassName(null==t?void 0:t.getClassName())?i[e]={name:t.name,className:t.getClassName()}:i[e]=t}function defaultValueParseFunction(e,t,i){let r=t[e],s=null==r?void 0:r.className;return isMeshClassName(s)?i.getMeshByName(r.name):r}let FlowGraphContext=class FlowGraphContext{constructor(e){this.uniqueId=(0,rZ.f)(),this._userVariables=new Map,this._executionVariables=new Map,this._connectionValues=new Map,this._pendingBlocks=[],this._executionId=0,this._configuration=e}hasVariable(e){return this._userVariables.has(e)}setVariable(e,t){this._userVariables.set(e,t)}getVariable(e){return this._userVariables.get(e)}_getUniqueIdPrefixedName(e,t){return`${e.uniqueId}_${t}`}_setExecutionVariable(e,t,i){this._executionVariables.set(this._getUniqueIdPrefixedName(e,t),i)}_getExecutionVariable(e,t,i){return this._hasExecutionVariable(e,t)?this._executionVariables.get(this._getUniqueIdPrefixedName(e,t)):i}_deleteExecutionVariable(e,t){this._executionVariables.delete(this._getUniqueIdPrefixedName(e,t))}_hasExecutionVariable(e,t){return this._executionVariables.has(this._getUniqueIdPrefixedName(e,t))}_hasConnectionValue(e){return this._connectionValues.has(e.uniqueId)}_setConnectionValue(e,t){this._connectionValues.set(e.uniqueId,t)}_getConnectionValue(e){return this._connectionValues.get(e.uniqueId)}get configuration(){return this._configuration}_addPendingBlock(e){this._pendingBlocks.push(e)}_removePendingBlock(e){let t=this._pendingBlocks.indexOf(e);-1!==t&&this._pendingBlocks.splice(t,1)}_clearPendingBlocks(){for(let e of this._pendingBlocks)e._cancelPendingTasks(this);this._pendingBlocks.length=0}_increaseExecutionId(){this._executionId++}get executionId(){return this._executionId}serialize(e={},t=defaultValueSerializationFunction){e.uniqueId=this.uniqueId,e._userVariables={},this._userVariables.forEach((i,r)=>{t(r,i,e._userVariables)}),e._connectionValues={},this._connectionValues.forEach((i,r)=>{t(r,i,e._connectionValues)})}getClassName(){return"FGContext"}static Parse(e={},t,i=defaultValueParseFunction){let r=t.createContext();for(let t in r.uniqueId=e.uniqueId,e._userVariables){let s=i(t,e._userVariables,r._configuration.scene);r._userVariables.set(t,s)}for(let t in e._connectionValues){let s=i(t,e._connectionValues,r._configuration.scene);r._connectionValues.set(t,s)}return r}};(0,rH.gn)([(0,rb.qC)()],FlowGraphContext.prototype,"uniqueId",void 0);let FlowGraphVariableDefinitions=class FlowGraphVariableDefinitions{constructor(){this._definitions=new Map}defineVariable(e,t){this._definitions.set(e,t)}generateContext(e){let t=new FlowGraphContext(e);return this._definitions.forEach((e,i)=>{t.setVariable(i,e)}),t}serialize(e){this._definitions.forEach((t,i)=>{e[i]=t})}deserialize(e){for(let t in this._definitions.clear(),e)this._definitions.set(t,e[t])}};(tc=rd||(rd={}))[tc.Stopped=0]="Stopped",tc[tc.Started=1]="Started";let FlowGraph=class FlowGraph{constructor(e){this.variableDefinitions=new FlowGraphVariableDefinitions,this._eventBlocks=[],this._executionContexts=[],this.state=rd.Stopped,this._scene=e.scene,this._eventCoordinator=e.eventCoordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){let e=this.variableDefinitions.generateContext({scene:this._scene,eventCoordinator:this._eventCoordinator});return this._executionContexts.push(e),e}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==rd.Started)for(let e of(this.state=rd.Started,0===this._executionContexts.length&&this.createContext(),this._executionContexts))for(let t of this._eventBlocks)t._startPendingTasks(e)}dispose(){if(this.state!==rd.Stopped){for(let e of(this.state=rd.Stopped,this._executionContexts))e._clearPendingBlocks();this._executionContexts.length=0,this._eventBlocks.length=0,this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null}}visitAllBlocks(e){let t=[],i=new Set;for(let e of this._eventBlocks)t.push(e),i.add(e.uniqueId);for(;t.length>0;){let r=t.pop();for(let s of(e(r),r.dataInputs))for(let e of s._connectedPoint)i.has(e._ownerBlock.uniqueId)||(t.push(e._ownerBlock),i.add(e._ownerBlock.uniqueId));if(r instanceof FlowGraphExecutionBlock)for(let e of r.signalOutputs)for(let r of e._connectedPoint)i.has(r._ownerBlock.uniqueId)||(t.push(r._ownerBlock),i.add(r._ownerBlock.uniqueId))}}serialize(e={},t){for(let i of(e.variableDefinitions={},this.variableDefinitions.serialize(e.variableDefinitions),e.allBlocks=[],this.visitAllBlocks(t=>{let i={};t.serialize(i),e.allBlocks.push(i)}),e.executionContexts=[],this._executionContexts)){let r={};i.serialize(r,t),e.executionContexts.push(r)}}static GetDataOutConnectionByUniqueId(e,t){for(let i of e)for(let e of i.dataOutputs)if(e.uniqueId===t)return e;throw Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(let i of e)if(i instanceof FlowGraphExecutionBlock){for(let e of i.signalInputs)if(e.uniqueId===t)return e}throw Error("Could not find signal in connection with unique id "+t)}static Parse(e,t,i){let r=t.createGraph();r.variableDefinitions.deserialize(e.variableDefinitions);let s=[];for(let t of e.allBlocks){let e=FlowGraphBlock.Parse(t);s.push(e),e instanceof FlowGraphEventBlock&&r.addEventBlock(e)}for(let e of s){for(let t of e.dataInputs)for(let e of t.connectedPointIds){let i=FlowGraph.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof FlowGraphExecutionBlock)for(let t of e.signalOutputs)for(let e of t.connectedPointIds){let i=FlowGraph.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(let t of e.executionContexts)FlowGraphContext.Parse(t,r,i);return r}};let FlowGraphEventCoordinator=class FlowGraphEventCoordinator{constructor(){this._customEventsMap=new Map}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new rf.y$,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){let i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}};let FlowGraphCoordinator=class FlowGraphCoordinator{constructor(e){var t;this._config=e,this._flowGraphs=[],this.eventCoordinator=new FlowGraphEventCoordinator,this._config.scene.onDisposeObservable.add(()=>{this.dispose()});let i=null!==(t=FlowGraphCoordinator.SceneCoordinators.get(this._config.scene))&&void 0!==t?t:[];i.push(this)}createGraph(){let e=new FlowGraph({scene:this._config.scene,eventCoordinator:this.eventCoordinator});return this._flowGraphs.push(e),e}removeGraph(e){let t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach(e=>e.start())}dispose(){var e;this._flowGraphs.forEach(e=>e.dispose()),this._flowGraphs.length=0;let t=null!==(e=FlowGraphCoordinator.SceneCoordinators.get(this._config.scene))&&void 0!==e?e:[],i=t.indexOf(this);-1!==i&&t.splice(i,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach(i=>{let r={};i.serialize(r,t),e._flowGraphs.push(r)})}static Parse(e,t,i){var r;let s=new FlowGraphCoordinator({scene:t});return null===(r=e._flowGraphs)||void 0===r||r.forEach(e=>{FlowGraph.Parse(e,s,i)}),s}};FlowGraphCoordinator.SceneCoordinators=new Map;let FlowGraphWithOnDoneExecutionBlock=class FlowGraphWithOnDoneExecutionBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.onDone=this._registerSignalOutput("onDone")}};let FlowGraphLogBlock=class FlowGraphLogBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.message=this._registerDataInput("message",u_)}_execute(e){let t=this.message.getValue(e);console.log(t),this.onDone._activateSignal(e)}getClassName(){return"FGLogBlock"}};(0,rv.H)("FGLogBlock",FlowGraphLogBlock);let FlowGraphSetVariableBlock=class FlowGraphSetVariableBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.variableName=this._registerDataInput("variableName",uf),this.input=this._registerDataInput("input",u_)}_execute(e){let t=this.variableName.getValue(e),i=this.input.getValue(e);e.setVariable(t,i),this.onDone._activateSignal(e)}getClassName(){return"FGSetVariableBlock"}};(0,rv.H)("FGSetVariableBlock",FlowGraphSetVariableBlock);let FlowGraphSetPropertyBlock=class FlowGraphSetPropertyBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.target=this._registerDataInput("target",u_),this.property=this._registerDataInput("property",uf),this.value=this._registerDataInput("value",u_)}_setProperty(e,t,i){let r=t.split("."),s=e;for(let e=0;e<r.length-1;e++)s=s[r[e]];s[r[r.length-1]]=i}_execute(e){let t=this.target.getValue(e),i=this.property.getValue(e),r=this.value.getValue(e);if(t&&i&&r)this._setProperty(t,i,r);else throw Error("Invalid target, property or value.");this.onDone._activateSignal(e)}getClassName(){return"FGSetPropertyBlock"}};(0,rv.H)("FGSetPropertyBlock",FlowGraphSetPropertyBlock);let FlowGraphSendCustomEventBlock=class FlowGraphSendCustomEventBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.eventId=this._registerDataInput("eventId",uf),this.eventData=this._registerDataInput("eventData",u_)}_execute(e){let t=this.eventId.getValue(e),i=this.eventData.getValue(e);e.configuration.eventCoordinator.notifyCustomEvent(t,i),this.onDone._activateSignal(e)}getClassName(){return"FGSendCustomEventBlock"}};(0,rv.H)("FGSendCustomEventBlock",FlowGraphSendCustomEventBlock);let FlowGraphBranchBlock=class FlowGraphBranchBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.condition=this._registerDataInput("condition",ug),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}};(0,rv.H)("FGBranchBlock",FlowGraphBranchBlock);let FlowGraphDoNBlock=class FlowGraphDoNBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.reset=this._registerSignalInput("reset"),this.maxNumberOfExecutions=this._registerDataInput("numberOfExecutions",um),this.currentCount=this._registerDataOutput("currentCount",um)}_execute(e,t){if(t===this.reset)this.currentCount.setValue(0,e);else{let t=this.currentCount.getValue(e);t<this.maxNumberOfExecutions.getValue(e)&&(this.currentCount.setValue(t+1,e),this.onDone._activateSignal(e))}}getClassName(){return"FGDoNBlock"}};(0,rv.H)("FGDoNBlock",FlowGraphDoNBlock);let FlowGraphForLoopBlock=class FlowGraphForLoopBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.startIndex=this._registerDataInput("startIndex",um),this.endIndex=this._registerDataInput("endIndex",um),this.step=this._registerDataInput("step",um),this.index=this._registerDataOutput("index",um),this.onLoop=this._registerSignalOutput("onLoop"),this.onDone=this._registerSignalOutput("onDone")}_executeLoop(e){let t=e._getExecutionVariable(this,"index"),i=e._getExecutionVariable(this,"endIndex");if(t<i){this.index.setValue(t,e),this.onLoop._activateSignal(e);let i=e._getExecutionVariable(this,"step",1);t+=i,e._setExecutionVariable(this,"index",t),this._executeLoop(e)}else this.onDone._activateSignal(e)}_execute(e){let t=this.startIndex.getValue(e),i=this.endIndex.getValue(e),r=this.step.getValue(e);e._setExecutionVariable(this,"index",t),e._setExecutionVariable(this,"endIndex",i),e._setExecutionVariable(this,"step",r),this._executeLoop(e)}getClassName(){return"FGForLoopBlock"}};(0,rv.H)("FGForLoopBlock",FlowGraphForLoopBlock);let FlowGraphThrottleBlock=class FlowGraphThrottleBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.reset=this._registerSignalInput("reset"),this.duration=this._registerDataInput("duration",um),this.timeRemaining=this._registerDataOutput("timeRemaining",um)}_execute(e,t){let i=e._getExecutionVariable(this,"lastExecutedTime"),r=this.duration.getValue(e),s=Date.now();if(t===this.reset||void 0===i||s-i>r)this.timeRemaining.setValue(0,e),this.onDone._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",s);else{let t=r-(s-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}};(0,rv.H)("FGThrottleBlock",FlowGraphThrottleBlock);let FlowGraphTimerBlock=class FlowGraphTimerBlock extends FlowGraphAsyncExecutionBlock{constructor(e){super(e),this.timeout=this._registerDataInput("timeout",um),this.onTimerDone=this._registerSignalOutput("onTimerDone")}_preparePendingTasks(e){let t=this.timeout.getValue(e);if(void 0!==t&&t>=0){let i=e._getExecutionVariable(this,"runningTimers")||[],r=e.configuration.scene,s=new AdvancedTimer({timeout:t,contextObservable:r.onBeforeRenderObservable,onEnded:()=>this._onEnded(s,e)});s.start(),i.push(s),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.onDone._activateSignal(e)}_onEnded(e,t){let i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);-1!==r?i.splice(r,1):rW.w1.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.onTimerDone._activateSignal(t)}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"runningTimers")||[];for(let e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return"FGTimerBlock"}};(0,rv.H)("FGTimerBlock",FlowGraphTimerBlock);let FlowGraphMultiGateBlock=class FlowGraphMultiGateBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this._registerDataOutput("currentIndex",um)}configure(){super.configure(),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e<this.config.numberOutputFlows;e++)this.outFlows.push(this._registerSignalOutput(`out${e}`))}_getUnusedIndexes(e){let t=this._cachedUnusedIndexes;if(t.length=0,e._hasExecutionVariable(this,"unusedIndexes")){let i=e._getExecutionVariable(this,"unusedIndexes");for(let e=0;e<i.length;e++)t.push(i[e])}else for(let e=0;e<this.config.numberOutputFlows;e++)t.push(e);return t}_getNextOutput(e,t){if(!this.config.isRandom)return e+1;{let e=Math.floor(Math.random()*t.length);return t[e]}}_execute(e,t){var i;let r=null!==(i=e._getExecutionVariable(this,"currentIndex"))&&void 0!==i?i:this.config.startIndex-1,s=this._getUnusedIndexes(e);if(t===this.reset){e._deleteExecutionVariable(this,"currentIndex"),e._deleteExecutionVariable(this,"unusedIndexes");return}let n=this._getNextOutput(r,s);if(n>=this.config.numberOutputFlows&&this.config.loop)n=0;else if(n>=this.config.numberOutputFlows&&!this.config.loop)return;if(0===(s=s.filter(e=>e!==n)).length)for(let e=0;e<this.config.numberOutputFlows;e++)s.push(e);e._setExecutionVariable(this,"unusedIndexes",s),e._setExecutionVariable(this,"currentIndex",n),this.currentIndex.setValue(n,e),this.outFlows[n]._activateSignal(e)}getClassName(){return"FGMultiGateBlock"}};(0,rv.H)("FGMultiGateBlock",FlowGraphMultiGateBlock);let FlowGraphSwitchBlock=class FlowGraphSwitchBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.config=e,this.selection=this._registerDataInput("selection",u_)}configure(){super.configure(),this.outputFlows=[];for(let e=0;e<=this.config.cases.length;e++)this.outputFlows.push(this._registerSignalOutput(`out${e}`))}_execute(e,t){let i=this.selection.getValue(e);for(let t=0;t<this.config.cases.length;t++)if(i===this.config.cases[t]){this.outputFlows[t]._activateSignal(e);return}this.outputFlows[this.outputFlows.length-1]._activateSignal(e)}getClassName(){return"FGSwitchBlock"}};(0,rv.H)("FGSwitchBlock",FlowGraphSwitchBlock);let FlowGraphWaitAllBlock=class FlowGraphWaitAllBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.config=e,this.inFlows=[],this._cachedActivationState=[],this.reset=this._registerSignalInput("reset")}configure(){for(let e=1;e<this.config.numberInputFlows;e++)this.inFlows.push(this._registerSignalInput(`in${e}`))}_getCurrentActivationState(e){let t=this._cachedActivationState;if(t.length=0,e._hasExecutionVariable(this,"activationState")){let i=e._getExecutionVariable(this,"activationState");for(let e=0;e<i.length;e++)t.push(i[e])}else for(let e=0;e<this.config.numberInputFlows;e++)t.push(!1);return t}_execute(e,t){let i=this._getCurrentActivationState(e);if(t===this.reset)for(let e=0;e<this.config.numberInputFlows;e++)i[e]=!1;else if(t===this.onStart)i[0]=!0;else{let e=this.inFlows.indexOf(t);e>=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(e=>e)){this.onDone._activateSignal(e);for(let e=0;e<this.config.numberInputFlows;e++)i[e]=!1}}getClassName(){return"FGWaitAllBlock"}};(0,rv.H)("FGWaitAllBlock",FlowGraphWaitAllBlock);let FlowGraphCounterBlock=class FlowGraphCounterBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.count=this._registerDataOutput("count",um),this.reset=this._registerSignalInput("reset")}_execute(e,t){var i;if(t===this.reset){e._setExecutionVariable(this,"count",0),this.count.setValue(0,e);return}let r=(null!==(i=e._getExecutionVariable(this,"count"))&&void 0!==i?i:0)+1;e._setExecutionVariable(this,"count",r),this.count.setValue(r,e),this.onDone._activateSignal(e)}getClassName(){return"FGCounterBlock"}};(0,rv.H)("FGCounterBlock",FlowGraphCounterBlock);let FlowGraphWhileLoopBlock=class FlowGraphWhileLoopBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.config=e,this.condition=this._registerDataInput("condition",ug),this.loopBody=this._registerSignalOutput("loopBody")}_execute(e,t){var i;let r=this.condition.getValue(e);for((null===(i=this.config)||void 0===i?void 0:i.isDo)&&!r&&this.loopBody._activateSignal(e);r;)this.loopBody._activateSignal(e),r=this.condition.getValue(e);this.onDone._activateSignal(e)}getClassName(){return"FGWhileLoopBlock"}};(0,rv.H)("FGWhileLoopBlock",FlowGraphWhileLoopBlock);let FlowGraphDebounceBlock=class FlowGraphDebounceBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.count=this._registerDataInput("count",um),this.reset=this._registerSignalInput("reset"),this.currentCount=this._registerDataOutput("currentCount",um)}_execute(e,t){if(t===this.reset){e._setExecutionVariable(this,"debounceCount",0);return}let i=this.count.getValue(e),r=e._getExecutionVariable(this,"debounceCount",0),s=r+1;this.currentCount.setValue(s,e),e._setExecutionVariable(this,"debounceCount",s),s>=i&&(this.onDone._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}};(0,rv.H)("FGDebounceBlock",FlowGraphDebounceBlock);let FlowGraphFlipFlopBlock=class FlowGraphFlipFlopBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this._registerDataOutput("isOn",ug)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}};(0,rv.H)("FGFlipFlopBlock",FlowGraphFlipFlopBlock);let FlowGraphPlayAnimationBlock=class FlowGraphPlayAnimationBlock extends FlowGraphAsyncExecutionBlock{constructor(e){super(e),this.target=this._registerDataInput("target",u_),this.animation=this._registerDataInput("animation",u_),this.speed=this._registerDataInput("speed",um),this.loop=this._registerDataInput("loop",ug),this.from=this._registerDataInput("from",um),this.to=this._registerDataInput("to",um),this.onAnimationEnd=this._registerSignalOutput("onAnimationEnd"),this.runningAnimatable=this._registerDataOutput("runningAnimatable",u_)}_preparePendingTasks(e){var t;let i=this.target.getValue(e),r=this.animation.getValue(e);if(!i||!r)throw Error("Cannot play animation without target or animation");let s=null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[],n=this.runningAnimatable.getValue(e);if(n&&n.paused)n.restart();else{let t=e.configuration.scene,n=t.beginDirectAnimation(i,[r],this.from.getValue(e),this.to.getValue(e),this.loop.getValue(e),this.speed.getValue(e),()=>this._onAnimationEnd(n,e));this.runningAnimatable.setValue(n,e),s.push(n)}e._setExecutionVariable(this,"runningAnimatables",s)}_execute(e){this._startPendingTasks(e),this.onDone._activateSignal(e)}_onAnimationEnd(e,t){var i;let r=null!==(i=t._getExecutionVariable(this,"runningAnimatables"))&&void 0!==i?i:[],s=r.indexOf(e);-1!==s&&r.splice(s,1),t._removePendingBlock(this),this.onAnimationEnd._activateSignal(t)}_cancelPendingTasks(e){var t;let i=null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[];for(let e of i)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return"FGPlayAnimationBlock"}};(0,rv.H)("FGPlayAnimationBlock",FlowGraphPlayAnimationBlock);let FlowGraphStopAnimationBlock=class FlowGraphStopAnimationBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.animationToStop=this._registerDataInput("animationToStop",u_)}_execute(e){let t=this.animationToStop.getValue(e);t.stop(),this.onDone._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}};(0,rv.H)("FGStopAnimationBlock",FlowGraphStopAnimationBlock);let FlowGraphPauseAnimationBlock=class FlowGraphPauseAnimationBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.animationToPause=this._registerDataInput("animationToPause",u_)}_execute(e){let t=this.animationToPause.getValue(e);t.pause(),this.onDone._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}};(0,rv.H)("FGPauseAnimationBlock",FlowGraphPauseAnimationBlock);let FlowGraphPlayAudioBlock=class FlowGraphPlayAudioBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.audio=this._registerDataInput("audio",u_)}_execute(e,t){let i=this.audio.getValue(e);i instanceof Sound&&i.play(),this.onDone._activateSignal(e)}getClassName(){return"FGPlayAudioBlock"}};(0,rv.H)("FGPlayAudioBlock",FlowGraphPlayAudioBlock);let FlowGraphStopAudioBlock=class FlowGraphStopAudioBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.audio=this._registerDataInput("audio",u_)}_execute(e,t){let i=this.audio.getValue(e);i instanceof Sound&&i.stop()}getClassName(){return"FGStopAudioBlock"}};(0,rv.H)("FGStopAudioBlock",FlowGraphStopAudioBlock);let FlowGraphConditionalDataBlock=class FlowGraphConditionalDataBlock extends FlowGraphBlock{constructor(e){super(e),this.condition=this._registerDataInput("condition",ug),this.trueValue=this._registerDataInput("trueValue",u_),this.falseValue=this._registerDataInput("falseValue",u_),this.output=this._registerDataOutput("output",u_)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}};(0,rv.H)("FGConditionalDataBlock",FlowGraphConditionalDataBlock);let FlowGraphGetVariableBlock=class FlowGraphGetVariableBlock extends FlowGraphBlock{constructor(e){super(e),this.variableName=this._registerDataInput("variableName",uf),this.output=this._registerDataOutput("output",u_)}_updateOutputs(e){let t=this.variableName.getValue(e);e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return"FGGetVariableBlock"}};(0,rv.H)("FGGetVariableBlock",FlowGraphGetVariableBlock);let FlowGraphCoordinateTransformBlock=class FlowGraphCoordinateTransformBlock extends FlowGraphBlock{constructor(e){super(e),this.sourceSystem=this._registerDataInput("sourceSystem",u_),this.destinationSystem=this._registerDataInput("destinationSystem",u_),this.inputCoordinates=this._registerDataInput("inputCoordinates",ux),this.outputCoordinates=this._registerDataOutput("outputCoordinates",ux)}_updateOutputs(e){let t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),s=t.getWorldMatrix(),n=i.getWorldMatrix(),a=rm.jp.Matrix[0].copyFrom(n);a.invert();let o=rm.jp.Matrix[1];a.multiplyToRef(s,o);let l=this.outputCoordinates.getValue(e);rm.P.TransformCoordinatesToRef(r,o,l)}getClassName(){return"FGCoordinateTransformBlock"}};(0,rv.H)("FGCoordinateTransformBlock",FlowGraphCoordinateTransformBlock);let FlowGraphConstantBlock=class FlowGraphConstantBlock extends FlowGraphBlock{constructor(e){super(e),this.config=e,this.output=this._registerDataOutput("output",getRichTypeFromValue(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}};(0,rv.H)("FGConstantBlock",FlowGraphConstantBlock);let uy="cachedOperationValue",uP="cachedExecutionId";let FlowGraphCachedOperationBlock=class FlowGraphCachedOperationBlock extends FlowGraphBlock{constructor(e,t){super(t),this.output=this._registerDataOutput("output",e)}_updateOutputs(e){let t=e._getExecutionVariable(this,uP),i=e._getExecutionVariable(this,uy);if(void 0!==i&&t===e.executionId)this.output.setValue(i,e);else{let t=this._doOperation(e);e._setExecutionVariable(this,uy,t),e._setExecutionVariable(this,uP,e.executionId),this.output.setValue(t,e)}}};let FlowGraphBinaryOperationBlock=class FlowGraphBinaryOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r,s,n){super(i,n),this._operation=r,this._className=s,this.leftInput=this._registerDataInput("leftInput",e),this.rightInput=this._registerDataInput("rightInput",t)}_doOperation(e){return this._operation(this.leftInput.getValue(e),this.rightInput.getValue(e))}getClassName(){return this._className}};let FlowGraphUnaryOperationBlock=class FlowGraphUnaryOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r,s){super(t,s),this._operation=i,this._className=r,this.input=this._registerDataInput("input",e)}_doOperation(e){return this._operation(this.input.getValue(e))}getClassName(){return this._className}};let uR="FGBitwise",uA="AndBlock",uI="OrBlock",uM="XorBlock",uD="NotBlock",uO="LeftShiftBlock",uN="RightShiftBlock",uF="CountLeadingZerosBlock",uB="CountTrailingZerosBlock";let FlowGraphBitwiseAndBlock=class FlowGraphBitwiseAndBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e&t,`${uR}${uA}`,e)}};(0,rv.H)(`${uR}${uA}`,FlowGraphBitwiseAndBlock);let FlowGraphBitwiseOrBlock=class FlowGraphBitwiseOrBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e|t,`${uR}${uI}`,e)}};(0,rv.H)(`${uR}${uI}`,FlowGraphBitwiseOrBlock);let FlowGraphBitwiseXorBlock=class FlowGraphBitwiseXorBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e^t,`${uR}${uM}`,e)}};(0,rv.H)(`${uR}${uM}`,FlowGraphBitwiseXorBlock);let FlowGraphBitwiseNotBlock=class FlowGraphBitwiseNotBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>~e,`${uR}${uD}`,e)}};(0,rv.H)(`${uR}${uD}`,FlowGraphBitwiseNotBlock);let FlowGraphBitwiseLeftShiftBlock=class FlowGraphBitwiseLeftShiftBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e<<t,`${uR}${uO}`,e)}};(0,rv.H)(`${uR}${uO}`,FlowGraphBitwiseLeftShiftBlock);let FlowGraphBitwiseRightShiftBlock=class FlowGraphBitwiseRightShiftBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e>>t,`${uR}${uN}`,e)}};(0,rv.H)(`${uR}${uN}`,FlowGraphBitwiseRightShiftBlock);let FlowGraphCountLeadingZerosBlock=class FlowGraphCountLeadingZerosBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.clz32(e),`${uR}${uF}`,e)}};(0,rv.H)(`${uR}${uF}`,FlowGraphCountLeadingZerosBlock);let FlowGraphCountTrailingZerosBlock=class FlowGraphCountTrailingZerosBlock extends FlowGraphUnaryOperationBlock{_ctrz(e){return 0==(e>>>=0)?32:31-Math.clz32(e&=-e)}constructor(e){super(um,um,e=>this._ctrz(e),`${uR}${uB}`,e)}};(0,rv.H)(`${uR}${uB}`,FlowGraphCountTrailingZerosBlock);let uL="FGLogic",uw="AndBlock",uU="OrBlock",uV="NotBlock";let FlowGraphLogicAndBlock=class FlowGraphLogicAndBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(ug,ug,ug,(e,t)=>e&&t,`${uL}${uw}`,e)}};(0,rv.H)(`${uL}${uw}`,FlowGraphLogicAndBlock);let FlowGraphLogicOrBlock=class FlowGraphLogicOrBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(ug,ug,ug,(e,t)=>e||t,`${uL}${uU}`,e)}};(0,rv.H)(`${uL}${uU}`,FlowGraphLogicOrBlock);let FlowGraphLogicNotBlock=class FlowGraphLogicNotBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(ug,ug,e=>!e,`${uL}${uV}`,e)}};(0,rv.H)(`${uL}${uV}`,FlowGraphLogicNotBlock);let FlowGraphConstantOperationBlock=class FlowGraphConstantOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r){super(e,r),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}};let uk="FGAddNumberBlock";let FlowGraphAddNumberBlock=class FlowGraphAddNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e+t,uk,e)}};(0,rv.H)(uk,FlowGraphAddNumberBlock);let uG="FGSubtractNumberBlock";let FlowGraphSubtractNumberBlock=class FlowGraphSubtractNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e-t,uG,e)}};(0,rv.H)(uG,FlowGraphSubtractNumberBlock);let uz="FGMultiplyNumberBlock";let FlowGraphMultiplyNumberBlock=class FlowGraphMultiplyNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e*t,uz,e)}};(0,rv.H)(uz,FlowGraphMultiplyNumberBlock);let uW="FGDivideNumberBlock";let FlowGraphDivideNumberBlock=class FlowGraphDivideNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e/t,uW,e)}};(0,rv.H)(uW,FlowGraphDivideNumberBlock);let uH="FGModNumberBlock";let FlowGraphModNumberBlock=class FlowGraphModNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e%t,uH,e)}};(0,rv.H)(uH,FlowGraphModNumberBlock);let uX="FGPowNumberBlock";let FlowGraphPowNumberBlock=class FlowGraphPowNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>Math.pow(e,t),uX,e)}};(0,rv.H)(uX,FlowGraphPowNumberBlock);let uY="FGIsNaNNumberBlock";let FlowGraphIsNaNNumberBlock=class FlowGraphIsNaNNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,ug,e=>isNaN(e),uY,e)}};(0,rv.H)(uY,FlowGraphIsNaNNumberBlock);let uj="FGIsInfinityNumberBlock";let FlowGraphIsInfinityNumberBlock=class FlowGraphIsInfinityNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,ug,e=>!isFinite(e),uj,e)}};(0,rv.H)(uj,FlowGraphIsInfinityNumberBlock);let uq="FGSqrtNumberBlock";let FlowGraphSqrtNumberBlock=class FlowGraphSqrtNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.sqrt(e),uq,e)}};(0,rv.H)(uq,FlowGraphSqrtNumberBlock);let uK="FGAbsNumberBlock";let FlowGraphAbsNumberBlock=class FlowGraphAbsNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.abs(e),uK,e)}};(0,rv.H)(uK,FlowGraphAbsNumberBlock);let u$="FGNegateNumberBlock";let FlowGraphNegateNumberBlock=class FlowGraphNegateNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>-e,u$,e)}};(0,rv.H)(u$,FlowGraphNegateNumberBlock);let uQ="FGFloorNumberBlock";let FlowGraphFloorNumberBlock=class FlowGraphFloorNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.floor(e),uQ,e)}};(0,rv.H)(uQ,FlowGraphFloorNumberBlock);let uZ="FGCeilNumberBlock";let FlowGraphCeilNumberBlock=class FlowGraphCeilNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.ceil(e),uZ,e)}};(0,rv.H)(uZ,FlowGraphCeilNumberBlock);let uJ="FGRoundNumberBlock";let FlowGraphRoundNumberBlock=class FlowGraphRoundNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>Math.round(e/Math.pow(10,t))/Math.pow(10,t),uJ,e)}};(0,rv.H)(uJ,FlowGraphRoundNumberBlock);let u0="FGTruncNumberBlock";let FlowGraphTruncNumberBlock=class FlowGraphTruncNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.trunc(e),u0,e)}};(0,rv.H)(u0,FlowGraphTruncNumberBlock);let u1="FGExpNumberBlock";let FlowGraphExpNumberBlock=class FlowGraphExpNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.exp(e),u1,e)}};(0,rv.H)(u1,FlowGraphExpNumberBlock);let u2="FGLog10NumberBlock";let FlowGraphLog10NumberBlock=class FlowGraphLog10NumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.log10(e),u2,e)}};(0,rv.H)(u2,FlowGraphLog10NumberBlock);let u3="FGLogNumberBlock";let FlowGraphLogNumberBlock=class FlowGraphLogNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.log(e),u3,e)}};(0,rv.H)(u3,FlowGraphLogNumberBlock);let u4="FGLnNumberBlock";let FlowGraphLnNumberBlock=class FlowGraphLnNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.log(e)/Math.LN2,u4,e)}};(0,rv.H)(u4,FlowGraphLnNumberBlock);let u5="FGSineNumberBlock";let FlowGraphSinNumberBlock=class FlowGraphSinNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.sin(e),u5,e)}};(0,rv.H)(u5,FlowGraphSinNumberBlock);let u6="FGCosNumberBlock";let FlowGraphCosNumberBlock=class FlowGraphCosNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.cos(e),u6,e)}};(0,rv.H)(u6,FlowGraphCosNumberBlock);let u8="FGTanNumberBlock";let FlowGraphTanNumberBlock=class FlowGraphTanNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.tan(e),u8,e)}};(0,rv.H)(u8,FlowGraphTanNumberBlock);let u7="FGASineNumberBlock";let FlowGraphASinNumberBlock=class FlowGraphASinNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.asin(e),u7,e)}};(0,rv.H)(u7,FlowGraphASinNumberBlock);let u9="FGACosNumberBlock";let FlowGraphACosNumberBlock=class FlowGraphACosNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.acos(e),u9,e)}};(0,rv.H)(u9,FlowGraphACosNumberBlock);let ce="FGATanNumberBlock";let FlowGraphATanNumberBlock=class FlowGraphATanNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.atan(e),ce,e)}};(0,rv.H)(ce,FlowGraphATanNumberBlock);let ct="FGENumberBlock";let FlowGraphENumberBlock=class FlowGraphENumberBlock extends FlowGraphConstantOperationBlock{constructor(e){super(um,()=>Math.E,ct,e)}};(0,rv.H)(ct,FlowGraphENumberBlock);let ci="FGPiNumberBlock";let FlowGraphPiNumberBlock=class FlowGraphPiNumberBlock extends FlowGraphConstantOperationBlock{constructor(e){super(um,()=>Math.PI,ci,e)}};(0,rv.H)(ci,FlowGraphPiNumberBlock);let cr="FGATan2NumberBlock";let FlowGraphATan2NumberBlock=class FlowGraphATan2NumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>Math.atan2(e,t),cr,e)}};(0,rv.H)(cr,FlowGraphATan2NumberBlock);let cs="FGRandomNumberBlock";let FlowGraphRandomNumberBlock=class FlowGraphRandomNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e+Math.random()*(t-e),cs,e)}};(0,rv.H)(cs,FlowGraphRandomNumberBlock);let cn="FGMinNumberBlock";let FlowGraphMinNumberBlock=class FlowGraphMinNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>Math.min(e,t),cn,e)}};(0,rv.H)(cn,FlowGraphMinNumberBlock);let ca="FGMaxNumberBlock";let FlowGraphMaxNumberBlock=class FlowGraphMaxNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>Math.max(e,t),ca,e)}};(0,rv.H)(ca,FlowGraphMaxNumberBlock);let co="FGEqualsNumberBlock";let FlowGraphEqualsNumberBlock=class FlowGraphEqualsNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,ug,(e,t)=>e===t,co,e)}};(0,rv.H)(co,FlowGraphEqualsNumberBlock);let cl="FGGreaterThanNumberBlock";let FlowGraphGreaterThanNumberBlock=class FlowGraphGreaterThanNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,ug,(e,t)=>e>t,cl,e)}};(0,rv.H)(cl,FlowGraphGreaterThanNumberBlock);let ch="FGGreaterThanOrEqualsNumberBlock";let FlowGraphGreaterThanOrEqualsNumberBlock=class FlowGraphGreaterThanOrEqualsNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,ug,(e,t)=>e>=t,ch,e)}};(0,rv.H)(ch,FlowGraphGreaterThanOrEqualsNumberBlock);let cu="FGLessThanNumberBlock";let FlowGraphLessThanNumberBlock=class FlowGraphLessThanNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,ug,(e,t)=>e<t,cu,e)}};(0,rv.H)(cu,FlowGraphLessThanNumberBlock);let cc="FGLessThanOrEqualsNumberBlock";let FlowGraphLessThanOrEqualsNumberBlock=class FlowGraphLessThanOrEqualsNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,ug,(e,t)=>e<=t,cc,e)}};(0,rv.H)(cc,FlowGraphLessThanOrEqualsNumberBlock);let cd="FGMixNumberBlock";let FlowGraphMixNumberBlock=class FlowGraphMixNumberBlock extends FlowGraphBlock{constructor(e){super(e),this.leftInput=this._registerDataInput("leftInput",um),this.rightInput=this._registerDataInput("rightInput",um),this.alphaInput=this._registerDataInput("alphaInput",um),this.resultOutput=this._registerDataOutput("resultOutput",um)}_updateOutputs(e){let t=this.leftInput.getValue(e),i=this.rightInput.getValue(e),r=this.alphaInput.getValue(e);this.resultOutput.setValue(t+(i-t)*r,e)}getClassName(){return cd}};(0,rv.H)(cd,FlowGraphMixNumberBlock);let cp="FGAddVector2Block";let FlowGraphAddVector2Block=class FlowGraphAddVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uv,uv,uv,(e,t)=>e.add(t),cp,e)}};(0,rv.H)(cp,FlowGraphAddVector2Block);let c_="FGSubtractVector2Block";let FlowGraphSubtractVector2Block=class FlowGraphSubtractVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uv,uv,uv,(e,t)=>e.subtract(t),c_,e)}};(0,rv.H)(c_,FlowGraphSubtractVector2Block);let cf="FGMultiplyVector2Block";let FlowGraphMultiplyVector2Block=class FlowGraphMultiplyVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uv,uv,uv,(e,t)=>e.multiply(t),cf,e)}};(0,rv.H)(cf,FlowGraphMultiplyVector2Block);let cm="FGDivideVector2Block";let FlowGraphDivideVector2Block=class FlowGraphDivideVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uv,uv,uv,(e,t)=>e.divide(t),cm,e)}};(0,rv.H)(cm,FlowGraphDivideVector2Block);let cg="FGScaleVector2Block";let FlowGraphScaleVector2Block=class FlowGraphScaleVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uv,um,uv,(e,t)=>e.scale(t),cg,e)}};(0,rv.H)(cg,FlowGraphScaleVector2Block);let cv="FGLengthVector2Block";let FlowGraphLengthVector2Block=class FlowGraphLengthVector2Block extends FlowGraphUnaryOperationBlock{constructor(e){super(uv,um,e=>e.length(),cv,e)}};(0,rv.H)(cv,FlowGraphLengthVector2Block);let cx="FGNormalizeVector2Block";let FlowGraphNormalizeVector2Block=class FlowGraphNormalizeVector2Block extends FlowGraphUnaryOperationBlock{constructor(e){super(uv,uv,e=>{let t=e.clone();return t.normalize(),t},cx,e)}};(0,rv.H)(cx,FlowGraphNormalizeVector2Block);let FlowGraphCreateVector2Block=class FlowGraphCreateVector2Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=rm.FM.Zero(),this.x=this._registerDataInput("x",um),this.y=this._registerDataInput("y",um),this.vector=this._registerDataOutput("vector",uv)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this.vector.setValue(this._cachedVector,e)}};(0,rv.H)("FGCreateVector2Block",FlowGraphCreateVector2Block);let FlowGraphSplitVector2Block=class FlowGraphSplitVector2Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",uv),this.x=this._registerDataOutput("x",um),this.y=this._registerDataOutput("y",um)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e)}};(0,rv.H)("FGSplitVector2Block",FlowGraphSplitVector2Block);let FlowGraphRotate2dVector2Block=class FlowGraphRotate2dVector2Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=rm.FM.Zero(),this.input=this._registerDataInput("input",uv),this.angle=this._registerDataInput("angle",um),this.output=this._registerDataOutput("output",uv)}_updateOutputs(e){let t=this.input.getValue(e),i=this.angle.getValue(e);this._cachedVector.x=t.x*Math.cos(i)-t.y*Math.sin(i),this._cachedVector.y=t.x*Math.sin(i)+t.y*Math.cos(i),this.output.setValue(this._cachedVector,e)}};(0,rv.H)("FGRotate2dVector2Block",FlowGraphRotate2dVector2Block);let cT="FGAddVector3Block";let FlowGraphAddVector3Block=class FlowGraphAddVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,ux,(e,t)=>e.add(t),cT,e)}};(0,rv.H)(cT,FlowGraphAddVector3Block);let cS="FGSubtractVector3Block";let FlowGraphSubtractVector3Block=class FlowGraphSubtractVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,ux,(e,t)=>e.subtract(t),cS,e)}};(0,rv.H)(cS,FlowGraphSubtractVector3Block);let cC="FGMultiplyVector3Block";let FlowGraphMultiplyVector3Block=class FlowGraphMultiplyVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,ux,(e,t)=>e.multiply(t),cC,e)}};(0,rv.H)(cC,FlowGraphMultiplyVector3Block);let cE="FGDivideVector3Block";let FlowGraphDivideVector3Block=class FlowGraphDivideVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,ux,(e,t)=>e.divide(t),cE,e)}};(0,rv.H)(cE,FlowGraphDivideVector3Block);let cb="FGScaleVector3Block";let FlowGraphScaleVector3Block=class FlowGraphScaleVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,um,ux,(e,t)=>e.scale(t),cb,e)}};(0,rv.H)(cb,FlowGraphScaleVector3Block);let cy="FGLengthVector3Block";let FlowGraphLengthVector3Block=class FlowGraphLengthVector3Block extends FlowGraphUnaryOperationBlock{constructor(e){super(ux,um,e=>e.length(),cy,e)}};(0,rv.H)(cy,FlowGraphLengthVector3Block);let cP="FGNormalizeVector3Block";let FlowGraphNormalizeVector3Block=class FlowGraphNormalizeVector3Block extends FlowGraphUnaryOperationBlock{constructor(e){super(ux,ux,e=>e.normalizeToNew(),cP,e)}};(0,rv.H)(cP,FlowGraphNormalizeVector3Block);let cR="FGDotVector3Block";let FlowGraphDotVector3Block=class FlowGraphDotVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,um,(e,t)=>rm.P.Dot(e,t),cR,e)}};(0,rv.H)(cR,FlowGraphDotVector3Block);let cA="FGCrossVector3Block";let FlowGraphCrossVector3Block=class FlowGraphCrossVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,ux,(e,t)=>rm.P.Cross(e,t),cA,e)}};(0,rv.H)(cA,FlowGraphCrossVector3Block);let cI="FGCreateVector3Block";let FlowGraphCreateVector3Block=class FlowGraphCreateVector3Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=rm.P.Zero(),this.x=this._registerDataInput("x",um),this.y=this._registerDataInput("y",um),this.z=this._registerDataInput("y",um),this.vector=this._registerDataOutput("vector",ux)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this._cachedVector.z=this.z.getValue(e),this.vector.setValue(this._cachedVector,e)}getClassName(){return cI}};(0,rv.H)(cI,FlowGraphCreateVector3Block);let cM="FGSplitVector3Block";let FlowGraphSplitVector3Block=class FlowGraphSplitVector3Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",ux),this.x=this._registerDataOutput("x",um),this.y=this._registerDataOutput("y",um),this.z=this._registerDataOutput("z",um)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e),this.z.setValue(t.z,e)}getClassName(){return cM}};(0,rv.H)(cM,FlowGraphSplitVector3Block);let cD="FGRotateVector3Block";let FlowGraphRotate3dVector3Block=class FlowGraphRotate3dVector3Block extends FlowGraphBlock{constructor(e){super(e),this._cachedQuaternion=new rm._f,this.input=this._registerDataInput("input",ux),this.angle=this._registerDataInput("angle",um),this.output=this._registerDataOutput("output",ux)}_updateOutputs(e){let t=rm._f.RotationAxisToRef(this.axis.getValue(e),this.angle.getValue(e),this._cachedQuaternion),i=this.input.getValue(e),r=this.output.getValue(e);i.applyRotationQuaternionToRef(t,r)}getClassName(){return cD}};(0,rv.H)(cD,FlowGraphRotate3dVector3Block);let cO="FGTransformVector3Block";let FlowGraphTransformVector3Block=class FlowGraphTransformVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,ux,ux,(e,t)=>rm.P.TransformCoordinatesToRef(t,e,this._cachedResult),cO,e),this._cachedResult=rm.P.Zero()}};(0,rv.H)(cO,FlowGraphTransformVector3Block);let cN="FGAddVector4Block";let FlowGraphAddVector4Block=class FlowGraphAddVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uT,uT,uT,(e,t)=>e.add(t),cN,e)}};(0,rv.H)(cN,FlowGraphAddVector4Block);let cF="FGSubtractVector4Block";let FlowGraphSubtractVector4Block=class FlowGraphSubtractVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uT,uT,uT,(e,t)=>e.subtract(t),cF,e)}};(0,rv.H)(cF,FlowGraphSubtractVector4Block);let cB="FGMultiplyVector4Block";let FlowGraphMultiplyVector4Block=class FlowGraphMultiplyVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uT,uT,uT,(e,t)=>e.multiply(t),cB,e)}};(0,rv.H)(cB,FlowGraphMultiplyVector4Block);let cL="FGDivideVector4Block";let FlowGraphDivideVector4Block=class FlowGraphDivideVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uT,uT,uT,(e,t)=>e.divide(t),cL,e)}};(0,rv.H)(cL,FlowGraphDivideVector4Block);let cw="FGScaleVector4Block";let FlowGraphScaleVector4Block=class FlowGraphScaleVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uT,um,uT,(e,t)=>e.scale(t),cw,e)}};(0,rv.H)(cw,FlowGraphScaleVector4Block);let cU="FGLengthVector4Block";let FlowGraphLengthVector4Block=class FlowGraphLengthVector4Block extends FlowGraphUnaryOperationBlock{constructor(e){super(uT,um,e=>e.length(),cU,e)}};(0,rv.H)(cU,FlowGraphLengthVector4Block);let cV="FGNormalizeVector4Block";let FlowGraphNormalizeVector4Block=class FlowGraphNormalizeVector4Block extends FlowGraphUnaryOperationBlock{constructor(e){super(uT,uT,e=>{let t=e.clone();return t.normalize(),t},cV,e)}getClassName(){return cV}};(0,rv.H)(cV,FlowGraphNormalizeVector4Block);let ck="FGCreateVector4Block";let FlowGraphCreateVector4Block=class FlowGraphCreateVector4Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=rm.Lt.Zero(),this.x=this._registerDataInput("x",um),this.y=this._registerDataInput("y",um),this.z=this._registerDataInput("y",um),this.w=this._registerDataInput("w",um),this.vector=this._registerDataOutput("vector",uT)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this._cachedVector.z=this.z.getValue(e),this._cachedVector.w=this.w.getValue(e),this.vector.setValue(this._cachedVector,e)}getClassName(){return ck}};(0,rv.H)(ck,FlowGraphCreateVector4Block);let cG="FGSplitVector4Block";let FlowGraphSplitVector4Block=class FlowGraphSplitVector4Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",uT),this.x=this._registerDataOutput("x",um),this.y=this._registerDataOutput("y",um),this.z=this._registerDataOutput("z",um),this.w=this._registerDataOutput("w",um)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e),this.z.setValue(t.z,e),this.w.setValue(t.w,e)}getClassName(){return cG}};(0,rv.H)(cG,FlowGraphSplitVector4Block);let cz="FGAddMatrixBlock";let FlowGraphAddMatrixBlock=class FlowGraphAddMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,uS,uS,(e,t)=>e.addToRef(t,this._cachedMatrix),cz,e),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cz,FlowGraphAddMatrixBlock);let cW="FGAddMatrixAndNumberBlock";let FlowGraphAddMatrixAndNumberBlock=class FlowGraphAddMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,um,uS,(e,t)=>{for(let i=0;i<e.m.length;i++)this._cachedArray[i]=e.m[i]+t;return rm.y3.FromArrayToRef(this._cachedArray,0,this._cachedMatrix)},cW,e),this._cachedArray=new Float32Array(16),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cW,FlowGraphAddMatrixAndNumberBlock);let cH="FGSubtractMatrixBlock";let FlowGraphSubtractMatrixBlock=class FlowGraphSubtractMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,uS,uS,(e,t)=>e.addToRef(t.scaleToRef(-1,rm.jp.Matrix[0]),this._cachedMatrix),cH,e),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cH,FlowGraphSubtractMatrixBlock);let cX="FGSubtractMatrixAndNumberBlock";let FlowGraphSubtractMatrixAndNumberBlock=class FlowGraphSubtractMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,um,uS,(e,t)=>{for(let i=0;i<e.m.length;i++)this._cachedArray[i]=e.m[i]-t;return rm.y3.FromArrayToRef(this._cachedArray,0,this._cachedMatrix)},cX,e),this._cachedArray=new Float32Array(16),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cX,FlowGraphSubtractMatrixAndNumberBlock);let cY="FGMultiplyMatrixBlock";let FlowGraphMultiplyMatrixBlock=class FlowGraphMultiplyMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,uS,uS,(e,t)=>e.multiplyToRef(t,this._cachedMatrix),cY,e),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cY,FlowGraphMultiplyMatrixBlock);let cj="FGDivideMatrixBlock";let FlowGraphDivideMatrixBlock=class FlowGraphDivideMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,uS,uS,(e,t)=>e.multiplyToRef(t.invertToRef(rm.jp.Matrix[0]),this._cachedResultMatrix),cj,e),this._cachedResultMatrix=rm.y3.Zero()}};(0,rv.H)(cj,FlowGraphDivideMatrixBlock);let cq="FGDivideMatrixAndNumberBlock";let FlowGraphDivideMatrixAndNumberBlock=class FlowGraphDivideMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,um,uS,(e,t)=>{for(let i=0;i<e.m.length;i++)this._cachedArray[i]=e.m[i]/t;return rm.y3.FromArrayToRef(this._cachedArray,0,this._cachedMatrix)},cq,e),this._cachedArray=new Float32Array(16),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cq,FlowGraphDivideMatrixAndNumberBlock);let cK="FGScaleMatrixBlock";let FlowGraphScaleMatrixBlock=class FlowGraphScaleMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,um,uS,(e,t)=>e.scaleToRef(t,this._cachedMatrix),cK,e),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cK,FlowGraphScaleMatrixBlock);let c$="FGClampMatrixBlock";let FlowGraphClampMatrixBlock=class FlowGraphClampMatrixBlock extends FlowGraphBlock{constructor(e){super(e),this._cachedArray=new Float32Array(16),this._cachedMatrix=rm.y3.Identity(),this.input=this._registerDataInput("input",uS),this.min=this._registerDataInput("min",um),this.max=this._registerDataInput("max",um),this.output=this._registerDataOutput("output",uS)}_updateOutputs(e){let t=this.input.getValue(e),i=this.min.getValue(e),r=this.max.getValue(e);for(let e=0;e<t.m.length;e++)this._cachedArray[e]=Math.min(Math.max(t.m[e],i),r);rm.y3.FromArrayToRef(this._cachedArray,0,this._cachedMatrix),this.output.setValue(this._cachedMatrix,e)}getClassName(){return c$}};(0,rv.H)(c$,FlowGraphClampMatrixBlock);let cQ="FGDecomposeMatrixBlock";let FlowGraphDecomposeMatrixBlock=class FlowGraphDecomposeMatrixBlock extends FlowGraphBlock{constructor(e){super(e),this._cachedTranslation=new rm.P,this._cachedRotation=new rm._f,this._cachedScale=new rm.P,this.input=this._registerDataInput("input",uS),this.translation=this._registerDataOutput("translation",ux),this.rotation=this._registerDataOutput("rotation",ub),this.scale=this._registerDataOutput("scale",ux)}_updateOutputs(e){let t=this.input.getValue(e);t.decompose(this._cachedScale,this._cachedRotation,this._cachedTranslation),this.translation.setValue(this._cachedTranslation,e),this.rotation.setValue(this._cachedRotation,e),this.scale.setValue(this._cachedScale,e)}getClassName(){return cQ}};(0,rv.H)(cQ,FlowGraphDecomposeMatrixBlock);let cZ="FGComposeMatrixBlock";let FlowGraphComposeMatrixBlock=class FlowGraphComposeMatrixBlock extends FlowGraphBlock{constructor(e){super(e),this._cachedMatrix=new rm.y3,this.output=this._registerDataOutput("input",uS),this.translation=this._registerDataInput("translation",ux),this.rotation=this._registerDataInput("rotation",ub),this.scale=this._registerDataInput("scale",ux)}_updateOutputs(e){let t=this.translation.getValue(e),i=this.rotation.getValue(e),r=this.scale.getValue(e);rm.y3.ComposeToRef(r,i,t,this._cachedMatrix),this.output.setValue(this._cachedMatrix,e)}getClassName(){return cZ}};(0,rv.H)(cZ,FlowGraphComposeMatrixBlock);let cJ="FGQuaternionToRotationMatrixBlock";let FlowGraphQuaternionToRotationMatrixBlock=class FlowGraphQuaternionToRotationMatrixBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(ub,uS,e=>rm.y3.FromQuaternionToRef(e,this._cachedMatrix),cJ,e),this._cachedMatrix=new rm.y3}};(0,rv.H)(cJ,FlowGraphQuaternionToRotationMatrixBlock);let c0="FGGetTransformationMatrixBlock";let FlowGraphGetTransformationMatrixBlock=class FlowGraphGetTransformationMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(u_,u_,uS,(e,t)=>{let i=e.getWorldMatrix(),r=t.getWorldMatrix(),s=r.invertToRef(rm.jp.Matrix[0]),n=s.multiplyToRef(i,this._cachedResult);return n},c0,e),this._cachedResult=rm.y3.Zero()}};(0,rv.H)(c0,FlowGraphGetTransformationMatrixBlock);let FlowGraphMeshPickEventBlock=class FlowGraphMeshPickEventBlock extends FlowGraphEventBlock{constructor(e){super(e),this.config=e}configure(){super.configure(),this._meshVariableName=this.config.meshVariableName}_preparePendingTasks(e){let t=e._getExecutionVariable(this,"meshPickObserver");if(!t){let i=e.getVariable(this._meshVariableName);t=i.getScene().onPointerObservable.add(t=>{var r;t.type===r8.kD.POINTERPICK&&(null===(r=t.pickInfo)||void 0===r?void 0:r.pickedMesh)===i&&this._execute(e)});let r=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",r)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){let t=e.getVariable(this._meshVariableName),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return"FGMeshPickEventBlock"}};(0,rv.H)("FGMeshPickEventBlock",FlowGraphMeshPickEventBlock);let FlowGraphSceneReadyEventBlock=class FlowGraphSceneReadyEventBlock extends FlowGraphEventBlock{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){let t=e.configuration.scene,i=t.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",i)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneReadyObserver"),i=e.configuration.scene;i.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return"FGSceneReadyEventBlock"}};(0,rv.H)("FGSceneReadyEventBlock",FlowGraphSceneReadyEventBlock);let FlowGraphReceiveCustomEventBlock=class FlowGraphReceiveCustomEventBlock extends FlowGraphEventBlock{constructor(e){super(e),this.config=e,this.eventData=this._registerDataOutput("eventData",u_)}_preparePendingTasks(e){let t=e.configuration.eventCoordinator.getCustomEventObservable(this.config.eventId);this._eventObserver=t.add(t=>{this.eventData.setValue(t,e),this._execute(e)})}_cancelPendingTasks(e){let t=e.configuration.eventCoordinator.getCustomEventObservable(this.config.eventId);t?t.remove(this._eventObserver):rW.w1.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this.config.eventId}`)}getClassName(){return"FGReceiveCustomEventBlock"}};(0,rv.H)("FGReceiveCustomEventBlock",FlowGraphReceiveCustomEventBlock);let FlowGraphSceneTickEventBlock=class FlowGraphSceneTickEventBlock extends FlowGraphEventBlock{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneBeforeRender")){let t=e.configuration.scene,i=t.onBeforeRenderObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",i)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneBeforeRender"),i=e.configuration.scene;i.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return"FGSceneTickEventBlock"}};(0,rv.H)("FGSceneTickEventBlock",FlowGraphSceneTickEventBlock)},208:function(e,t,i){i.d(t,{N:function(){return Node}});var r=i(9956),s=i(78),n=i(1760),a=i(4800),o=i(6030),l=i(6131);let _InternalNodeDataInfo=class _InternalNodeDataInfo{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new a.y$,this._onClonedObservable=new a.y$}};let Node=class Node{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){let s=this._NodeConstructors[e];return s?s(t,i,r):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;let t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){let 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=[]),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){let 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 _InternalNodeDataInfo,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new a.y$,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=s.y3.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new a.y$,this._onDisposeObserver=null,this._behaviors=[],this.name=e,this.id=e,this._scene=t||o.l.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){let i=this._behaviors.indexOf(e);return -1!==i||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{e.attach(this)}):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){let 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(let 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 r=0;r<this._children.length;r++){let s=this._children[r];(!i||i(s))&&e.push(s),t||s._getDescendants(e,!1,i)}}getDescendants(e,t){let i=[];return this._getDescendants(i,e,t),i}getChildMeshes(e,t){let i=[];return this._getDescendants(i,e,e=>(!t||t(e))&&void 0!==e.cullingStrategy),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;t<this.animations.length;t++){let i=this.animations[t];if(i.name===e)return i}return null}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=Node._AnimationRangeFactory(e,t,i);for(let r=0,s=this.animations.length;r<s;r++)this.animations[r]&&this.animations[r].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,r=this.animations.length;i<r;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(e,t,i){let r=n.p4.Clone(()=>new Node(e,this.getScene()),this);if(t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;i<t.length;i++){let s=t[i];s.clone(e+"."+s.name,r)}}return r}getAnimationRanges(){let e;let t=[];for(e in this._ranges)t.push(this._ranges[e]);return t}beginAnimation(e,t,i,r){let s=this.getAnimationRange(e);return s?this._scene.beginAnimation(this,s.from,s.to,t,i,r):null}serializeAnimationRanges(){let e=[];for(let t in this._ranges){let i=this._ranges[t];if(!i)continue;let r={};r.name=t,r.from=i.from,r.to=i.to,e.push(r)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=s.y3.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){let i=this.getDescendants(!0);for(let r of i)r.dispose(e,t)}for(let e of(this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear(),this._behaviors))e.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,i){if(t.ranges)for(let i=0;i<t.ranges.length;i++){let r=t.ranges[i];e.createAnimationRange(r.name,r.from,r.to)}}getHierarchyBoundingVectors(e=!0,t=null){let i,r;if(this.getScene().incrementRenderId(),this.computeWorldMatrix(!0),this.getBoundingInfo&&this.subMeshes){let e=this.getBoundingInfo();i=e.boundingBox.minimumWorld.clone(),r=e.boundingBox.maximumWorld.clone()}else i=new s.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new s.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){let e=this.getDescendants(!1);for(let n of e){if(n.computeWorldMatrix(!0),t&&!t(n)||!n.getBoundingInfo||0===n.getTotalVertices())continue;let e=n.getBoundingInfo(),a=e.boundingBox,o=a.minimumWorld,l=a.maximumWorld;s.P.CheckExtends(o,i,r),s.P.CheckExtends(l,i,r)}}return{min:i,max:r}}};Node._AnimationRangeFactory=(e,t,i)=>{throw(0,l.S)("AnimationRange")},Node._NodeConstructors={},(0,r.gn)([(0,n.qC)()],Node.prototype,"name",void 0),(0,r.gn)([(0,n.qC)()],Node.prototype,"id",void 0),(0,r.gn)([(0,n.qC)()],Node.prototype,"uniqueId",void 0),(0,r.gn)([(0,n.qC)()],Node.prototype,"state",void 0),(0,r.gn)([(0,n.qC)()],Node.prototype,"metadata",void 0)},7609:function(e,t,i){i.d(t,{H:function(){return Stage},l:function(){return SceneComponentConstants}});let SceneComponentConstants=class SceneComponentConstants{};SceneComponentConstants.NAME_EFFECTLAYER="EffectLayer",SceneComponentConstants.NAME_LAYER="Layer",SceneComponentConstants.NAME_LENSFLARESYSTEM="LensFlareSystem",SceneComponentConstants.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",SceneComponentConstants.NAME_PARTICLESYSTEM="ParticleSystem",SceneComponentConstants.NAME_GAMEPAD="Gamepad",SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",SceneComponentConstants.NAME_PREPASSRENDERER="PrePassRenderer",SceneComponentConstants.NAME_DEPTHRENDERER="DepthRenderer",SceneComponentConstants.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",SceneComponentConstants.NAME_SPRITE="Sprite",SceneComponentConstants.NAME_SUBSURFACE="SubSurface",SceneComponentConstants.NAME_OUTLINERENDERER="Outline",SceneComponentConstants.NAME_PROCEDURALTEXTURE="ProceduralTexture",SceneComponentConstants.NAME_SHADOWGENERATOR="ShadowGenerator",SceneComponentConstants.NAME_OCTREE="Octree",SceneComponentConstants.NAME_PHYSICSENGINE="PhysicsEngine",SceneComponentConstants.NAME_AUDIO="Audio",SceneComponentConstants.NAME_FLUIDRENDERER="FluidRenderer",SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER=0,SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS=0,SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER=2,SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER=1,SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS=0,SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE=1,SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS=0,SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE=1,SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,SceneComponentConstants.STEP_BEFORECLEAR_PREPASS=1,SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER=1,SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS=0,SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER=4,SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,SceneComponentConstants.STEP_AFTERRENDER_AUDIO=0,SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,SceneComponentConstants.STEP_POINTERMOVE_SPRITE=0,SceneComponentConstants.STEP_POINTERDOWN_SPRITE=0,SceneComponentConstants.STEP_POINTERUP_SPRITE=0;let Stage=class Stage extends Array{constructor(e){super(...e)}static Create(){return Object.create(Stage.prototype)}registerStep(e,t,i){let r=0;for(;r<this.length;r++){let t=this[r];if(e<t.index)break}this.splice(r,0,{index:e,component:t,action:i.bind(t)})}clear(){this.length=0}}},9956:function(e,t,i){i.d(t,{gn:function(){return __decorate}});function __decorate(e,t,i,r){var s,n=arguments.length,a=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,r);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(a=(n<3?s(a):n>3?s(t,i,a):s(t,i))||a);return n>3&&a&&Object.defineProperty(t,i,a),a}}}]); \ No newline at end of file diff --git a/.next/static/chunks/1f3d3139-f107a678ff6361e9.js b/.next/static/chunks/1f3d3139-f107a678ff6361e9.js new file mode 100644 index 0000000..bbda3dd --- /dev/null +++ b/.next/static/chunks/1f3d3139-f107a678ff6361e9.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[105],{3249:function(e,t,s){s.d(t,{Kj:function(){return Mesh},gW:function(){return _CreationDataStorage}});var i=s(4800),r=s(5132),a=s(3189),n=s(1803),o=s(7521),h=s(555),l=s(6540),d=s(78),c=s(2983),u=s(208),f=s(1295),g=s(2696),_=s(1687),m=s(7042),M=s(1091),I=s(2515),p=s(5461),v=s(2697),D=s(1760),y=s(9626),b=s(3048),S=s(6131),x=s(7609),B=s(4926);let _CreationDataStorage=class _CreationDataStorage{};let _InstanceDataStorage=class _InstanceDataStorage{constructor(){this.visibleInstances={},this.batchCache=new _InstancesBatch,this.batchCacheReplacementModeInFrozenMode=new _InstancesBatch,this.instancesBufferSize=2048}};let _InstancesBatch=class _InstancesBatch{constructor(){this.mustReturn=!1,this.visibleInstances=[],this.renderSelf=[],this.hardwareInstancedRendering=[]}};let _ThinInstanceDataStorage=class _ThinInstanceDataStorage{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}};let _InternalMeshDataInfo=class _InternalMeshDataInfo{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=[],this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}};let Mesh=class Mesh extends m.x{static _GetDefaultSideOrientation(e){return e||Mesh.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(f.o.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(f.o.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new i.y$),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new i.y$),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new i.y$),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new i.y$),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new i.y$),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){var e;return(null!==(e=this._thinInstanceDataStorage.instancesCount)&&void 0!==e?e:0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,s=null,r=null,o,h=!0){if(super(e,t),this._internalMeshDataInfo=new _InternalMeshDataInfo,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new _InstanceDataStorage,this._thinInstanceDataStorage=new _ThinInstanceDataStorage,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=Mesh.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,s)=>{e&&s&&(this._uniformBuffer?this.transferToEffect(t):s.bindOnlyWorldMatrix(t))},r){if(r._geometry&&r._geometry.applyToMesh(this),a.j.DeepCopy(r,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=r,t.useClonedMeshMap&&(r._internalMeshDataInfo.meshMap||(r._internalMeshDataInfo.meshMap={}),r._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=r._originalBuilderSideOrientation,this._creationDataStorage=r._creationDataStorage,r._ranges){let e=r._ranges;for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(r.metadata&&r.metadata.clone?this.metadata=r.metadata.clone():this.metadata=r.metadata,this._internalMetadata=r._internalMetadata,n.$&&n.$.HasTags(r)&&n.$.AddTagsTo(this,n.$.GetTags(r,!0)),this.setEnabled(r.isEnabled(!1)),this.parent=r.parent,this.setPivotMatrix(r.getPivotMatrix()),this.id=e+"."+r.id,this.material=r.material,!o){let t=r.getDescendants(!0);for(let s=0;s<t.length;s++){let i=t[s];i.clone&&i.clone(e+"."+i.name,this)}}if(r.morphTargetManager&&(this.morphTargetManager=r.morphTargetManager),t.getPhysicsEngine){let e=t.getPhysicsEngine();if(h&&e){if(1===e.getPluginVersion()){let t=e.getImpostorForPhysicsObject(r);t&&(this.physicsImpostor=t.clone(this))}else 2===e.getPluginVersion()&&r.physicsBody&&r.physicsBody.clone(this)}}for(let e=0;e<t.particleSystems.length;e++){let s=t.particleSystems[e];s.emitter===r&&s.clone(s.name,this)}this.skeleton=r.skeleton,this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}null!==s&&(this.parent=s),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=e=>{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new i.y$(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,s){let i=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));for(let r of(i.parent=e||this.parent,i.position=this.position.clone(),i.scaling=this.scaling.clone(),this.rotationQuaternion?i.rotationQuaternion=this.rotationQuaternion.clone():i.rotation=this.rotation.clone(),s&&s(this,i),this.getChildTransformNodes(!0)))"InstancedMesh"===r.getClassName()&&"Mesh"===i.getClassName()&&r.sourceMesh===this?r.instantiateHierarchy(i,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:i},s):r.instantiateHierarchy(i,t,s);return i}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices()+", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let s=0;s<this.animations.length;s++)t+=", animation[0]: "+this.animations[s].toString(e);if(e){if(this._geometry){let e=this.getIndices(),s=this.getVerticesData(f.o.PositionKind);s&&e&&(t+=", flat shading: "+(s.length/3===e.length?"YES":"NO"))}else t+=", flat shading: UNKNOWN"}return t}_unBindEffect(){for(let e of(super._unBindEffect(),this.instances))e._unBindEffect()}get hasLODLevels(){return this._internalMeshDataInfo._LODLevels.length>0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){let e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,s)=>t.distanceOrScreenCoverage<s.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>s.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return y.Y.Warn("You cannot use a mesh as LOD level twice"),this;let s=new B.g(e,t);return this._internalMeshDataInfo._LODLevels.push(s),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){let t=this._internalMeshDataInfo;for(let s=0;s<t._LODLevels.length;s++){let i=t._LODLevels[s];if(i.distanceOrScreenCoverage===e)return i.mesh}return null}removeLODLevel(e){let t=this._internalMeshDataInfo;for(let s=0;s<t._LODLevels.length;s++)t._LODLevels[s].mesh===e&&(t._LODLevels.splice(s,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){let s=this._internalMeshDataInfo;if(!s._LODLevels||0===s._LODLevels.length)return this;let i=t||this.getBoundingInfo().boundingSphere,r=e.mode===h.V.ORTHOGRAPHIC_CAMERA?e.minZ:i.centerWorld.subtract(e.globalPosition).length(),a=r,n=1;if(s._useLODScreenCoverage){let t=e.screenArea,s=i.radiusWorld*e.minZ/r;a=(s=s*s*Math.PI)/t,n=-1}if(n*s._LODLevels[s._LODLevels.length-1].distanceOrScreenCoverage>n*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let e=0;e<s._LODLevels.length;e++){let t=s._LODLevels[e];if(n*t.distanceOrScreenCoverage<n*a){if(t.mesh){if(4===t.mesh.delayLoadState)return t.mesh._checkDelayState(),this;if(2===t.mesh.delayLoadState)return this;t.mesh._preActivate(),t.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,t.mesh),t.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return null===this._geometry||void 0===this._geometry?0:this._geometry.getTotalVertices()}getVerticesData(e,t,s,i){var r,a;if(!this._geometry)return null;let n=i?void 0:null===(a=null===(r=this._userInstancedBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])||void 0===a?void 0:a.getFloatData(this.instances.length+1,s||t&&1!==this._geometry.meshes.length);return n||(n=this._geometry.getVerticesData(e,t,s)),n}getVertexBuffer(e,t){var s,i;return this._geometry?null!==(i=t?void 0:null===(s=this._userInstancedBuffersStorage)||void 0===s?void 0:s.vertexBuffers[e])&&void 0!==i?i:this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){var s;return this._geometry?!t&&(null===(s=this._userInstancedBuffersStorage)||void 0===s?void 0:s.vertexBuffers[e])!==void 0||this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}isVertexBufferUpdatable(e,t){var s;if(!this._geometry)return!!this._delayInfo&&-1!==this._delayInfo.indexOf(e);if(!t){let t=null===(s=this._userInstancedBuffersStorage)||void 0===s?void 0:s.vertexBuffers[e];if(t)return t.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){let e=[];return this._delayInfo&&this._delayInfo.forEach(function(t){e.push(t)}),e}let t=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(let e in this._userInstancedBuffersStorage.vertexBuffers)-1===t.indexOf(e)&&t.push(e);return t}getTotalIndices(){return this._geometry?this._geometry.getTotalIndices():0}getIndices(e,t){return this._geometry?this._geometry.getIndices(e,t):[]}get isBlocked(){return null!==this._masterMesh&&void 0!==this._masterMesh}isReady(e=!1,t=!1){var s,i,r,a,n,o,h;if(2===this.delayLoadState||!super.isReady(e))return!1;if(!this.subMeshes||0===this.subMeshes.length||!e)return!0;let l=this.getEngine(),d=this.getScene(),c=t||l.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();let u=this.material||d.defaultMaterial;if(u){if(u._storeEffectOnSubMeshes)for(let e of this.subMeshes){let t=e.getMaterial();if(t){if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,c))return!1}else if(!t.isReady(this,c))return!1}}else if(!u.isReady(this,c))return!1}let f=l.currentRenderPassId;for(let e of this.lightSources){let t=e.getShadowGenerators();if(!t)continue;let d=t.values();for(let e=d.next();!0!==e.done;e=d.next()){let t=e.value;if(t&&(!(null===(s=t.getShadowMap())||void 0===s?void 0:s.renderList)||(null===(i=t.getShadowMap())||void 0===i?void 0:i.renderList)&&(null===(a=null===(r=t.getShadowMap())||void 0===r?void 0:r.renderList)||void 0===a?void 0:a.indexOf(this))!==-1)){let e=t.getShadowMap(),s=null!==(n=e.renderPassIds)&&void 0!==n?n:[l.currentRenderPassId];for(let e=0;e<s.length;++e)for(let i of(l.currentRenderPassId=s[e],this.subMeshes))if(!t.isReady(i,c,null!==(h=null===(o=i.getMaterial())||void 0===o?void 0:o.needAlphaBlendingForMesh(this))&&void 0!==h&&h))return l.currentRenderPassId=f,!1;l.currentRenderPassId=f}}}for(let e of this._internalMeshDataInfo._LODLevels)if(e.mesh&&!e.mesh.isReady(c))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_preActivate(){let e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t||(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null),this}_preActivateForIntermediateRendering(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(void 0!==this._instanceDataStorage.previousRenderId&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=t,this._instanceDataStorage.visibleInstances[t]=[]),this._instanceDataStorage.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let s=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getPositionData(e,t),s),this}_createGlobalSubMesh(e){let t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){let s=this.getIndices();if(!s)return null;let i=s.length,r=!1;if(e)r=!0;else for(let e of this.subMeshes)if(e.indexStart+e.indexCount>i||e.verticesStart+e.verticesCount>t){r=!0;break}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new M.P(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;let t=this.getTotalIndices(),s=t/e|0,i=0;for(;s%3!=0;)s++;this.releaseSubMeshes();for(let r=0;r<e&&!(i>=t);r++)M.P.CreateFromIndices(0,i,r===e-1?t-i:s,this,void 0,!1),i+=s;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,s=!1,i){if(this._geometry)this._geometry.setVerticesData(e,t,s,i);else{let i=new g.x;i.set(t,e);let r=this.getScene();new _.Z(_.Z.RandomId(),r,i,s,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){let s=this.getVertexBuffer(e);s&&s.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=_.Z.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,s,i){return this._geometry&&(i?(this.makeGeometryUnique(),this.updateVerticesData(e,t,s,!1)):this._geometry.updateVerticesData(e,t,s)),this}updateMeshPositions(e,t=!0){let s=this.getVerticesData(f.o.PositionKind);if(!s)return this;if(e(s),this.updateVerticesData(f.o.PositionKind,s,!1,!1),t){let e=this.getIndices(),t=this.getVerticesData(f.o.NormalKind);if(!t)return this;g.x.ComputeNormals(s,e,t),this.updateVerticesData(f.o.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry||1===this._geometry.meshes.length)return this;let e=this._geometry,t=this._geometry.copy(_.Z.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndices(e,t=null,s=!1){if(this._geometry)this._geometry.setIndices(e,t,s);else{let t=new g.x;t.indices=e;let i=this.getScene();new _.Z(_.Z.RandomId(),i,t,s,this)}return this}updateIndices(e,t,s=!1){return this._geometry&&this._geometry.updateIndices(e,t,s),this}toLeftHanded(){return this._geometry&&this._geometry.toLeftHanded(),this}_bind(e,t,s,i=!0){let r;if(!this._geometry)return this;let a=this.getScene().getEngine();if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)r=null;else switch(this._getRenderingFillMode(s)){case I.F.PointFillMode:r=null;break;case I.F.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),a);break;default:case I.F.TriangleFillMode:r=this._geometry.getIndexBuffer()}return i&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,r,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,r),this}_draw(e,t,s){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);let i=this.getScene(),r=i.getEngine();return this._unIndexed||t==I.F.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||s):t==I.F.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||s):r.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||s),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}let s=this.getScene(),i=s._isInIntermediateRendering(),r=i?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=this._instanceDataStorage.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){let t=this._instanceDataStorage.visibleInstances,r=s.getRenderId(),n=i?t.intermediateDefaultRenderId:t.defaultRenderId;a.visibleInstances[e]=t[r],!a.visibleInstances[e]&&n&&(a.visibleInstances[e]=t[n])}return a.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==a.visibleInstances[e]&&void 0!==a.visibleInstances[e],this._instanceDataStorage.previousBatch=a,a}_renderWithInstances(e,t,s,i,r){var a;let n=s.visibleInstances[e._id],o=n?n.length:0,h=this._instanceDataStorage,l=h.instancesBufferSize,c=h.instancesBuffer,u=h.instancesPreviousBuffer,g=64*(o+1);for(;h.instancesBufferSize<g;)h.instancesBufferSize*=2;h.instancesData&&l==h.instancesBufferSize||(h.instancesData=new Float32Array(h.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!h.instancesPreviousData||l!=h.instancesBufferSize)&&(h.instancesPreviousData=new Float32Array(h.instancesBufferSize/4));let _=0,m=0,M=s.renderSelf[e._id],I=!c||l!==h.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!h.instancesPreviousBuffer;if(this._instanceDataStorage.manualUpdate||h.isFrozen&&!I)m=(M?1:0)+o;else{let t=this.getWorldMatrix();if(M&&(this._scene.needsPreviousWorldMatrices&&(h.masterMeshPreviousWorldMatrix?(h.masterMeshPreviousWorldMatrix.copyToArray(h.instancesPreviousData,_),h.masterMeshPreviousWorldMatrix.copyFrom(t)):(h.masterMeshPreviousWorldMatrix=t.clone(),h.masterMeshPreviousWorldMatrix.copyToArray(h.instancesPreviousData,_))),t.copyToArray(h.instancesData,_),_+=16,m++),n){if(Mesh.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&(null===(a=e.getMaterial())||void 0===a?void 0:a.needAlphaBlendingForMesh(e.getRenderingMesh()))){let e=this._scene.activeCamera.globalPosition;for(let t=0;t<n.length;t++){let s=n[t];s._distanceToCamera=d.P.Distance(s.getBoundingInfo().boundingSphere.centerWorld,e)}n.sort((e,t)=>e._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera<t._distanceToCamera?1:0)}for(let e=0;e<n.length;e++){let t=n[e],s=t.getWorldMatrix();s.copyToArray(h.instancesData,_),this._scene.needsPreviousWorldMatrices&&(t._previousWorldMatrix?(t._previousWorldMatrix.copyToArray(h.instancesPreviousData,_),t._previousWorldMatrix.copyFrom(s)):(t._previousWorldMatrix=s.clone(),t._previousWorldMatrix.copyToArray(h.instancesPreviousData,_))),_+=16,m++}}}return I?(c&&c.dispose(),u&&u.dispose(),c=new f.l(r,h.instancesData,!0,16,!1,!0),h.instancesBuffer=c,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=c.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=c.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=c.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=c.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(u=new f.l(r,h.instancesPreviousData,!0,16,!1,!0),h.instancesPreviousBuffer=u,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=u.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=u.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=u.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=u.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&(c.updateDirectly(h.instancesData,0,m),this._scene.needsPreviousWorldMatrices&&(!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.previousManualUpdate)&&u.updateDirectly(h.instancesPreviousData,0,m)),this._processInstancedBuffers(n,M),this.getScene()._activeIndices.addCount(e.indexCount*m,!1),r._currentDrawContext&&(r._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,m),this._scene.needsPreviousWorldMatrices&&!I&&this._instanceDataStorage.manualUpdate&&(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&!this._instanceDataStorage.previousManualUpdate&&u.updateDirectly(h.instancesData,0,m),r.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,s,i){var r,a;let n=null!==(a=null===(r=this._thinInstanceDataStorage)||void 0===r?void 0:r.instancesCount)&&void 0!==a?a:0;this.getScene()._activeIndices.addCount(e.indexCount*n,!1),i._currentDrawContext&&(i._currentDrawContext.useInstancing=!0),this._bind(e,s,t),this._draw(e,t,n),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,n):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),i.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,s,i,r,a,n,o){let h=this.getScene(),l=h.getEngine();if(i=this._getRenderingFillMode(i),a&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,i,s,l),this;if(a)this._renderWithInstances(t,i,r,s,l);else{l._currentDrawContext&&(l._currentDrawContext.useInstancing=!1);let s=0;r.renderSelf[t._id]&&(n&&n(!1,e.getWorldMatrix(),o),s++,this._draw(t,i,this._instanceDataStorage.overridenInstanceCount));let a=r.visibleInstances[t._id];if(a){let e=a.length;s+=e;for(let s=0;s<e;s++){let e=a[s],r=e.getWorldMatrix();n&&n(!0,r,o),this._draw(t,i)}}h._activeIndices.addCount(t.indexCount*s,!1)}return this}_rebuild(e=!1){if(this._instanceDataStorage.instancesBuffer&&(e&&this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),this._userInstancedBuffersStorage){for(let t in this._userInstancedBuffersStorage.vertexBuffers){let s=this._userInstancedBuffersStorage.vertexBuffers[t];s&&(e&&s.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(e)}_freeze(){if(this.subMeshes){for(let e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}}_unFreeze(){this._instanceDataStorage.isFrozen=!1,this._instanceDataStorage.previousBatch=null}renderWithRenderPassId(e,t,s,i,r=!0){let a=this._scene.getEngine(),n=a.currentRenderPassId;if(void 0!==e&&(a.currentRenderPassId=e),i)(!r||r&&i.isInFrustum(this._scene._frustumPlanes))&&this.render(i,!!t,s);else for(let e=0;e<this.subMeshes.length;e++){let i=this.subMeshes[e];(!r||r&&i.isInFrustum(this._scene._frustumPlanes))&&this.render(i,!!t,s)}return void 0!==e&&(a.currentRenderPassId=n),this}render(e,t,s){var i,r,a,n,o;let h,d;let c=this.getScene();this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1;let u=null!==(r=null===(i=c.activeCameras)||void 0===i?void 0:i.length)&&void 0!==r?r:0,f=u>1&&c.activeCamera===c.activeCameras[0]||u<=1;if(f&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;let g=this._getInstancesRenderList(e._id,!!s);if(g.mustReturn||!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let _=c.getEngine(),m=0,M=null;this.ignoreCameraMaxZ&&c.activeCamera&&!c._isInIntermediateRendering()&&(m=c.activeCamera.maxZ,M=c.activeCamera,c.activeCamera.maxZ=0,c.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);let p=e.getRenderingMesh(),v=g.hardwareInstancedRendering[e._id]||p.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,D=this._instanceDataStorage,y=e.getMaterial();if(!y)return M&&(M.maxZ=m,c.updateTransformMatrix(!0)),this;if(D.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===y){if(y._storeEffectOnSubMeshes&&!(null===(a=e.effect)||void 0===a?void 0:a._wasPreviouslyReady)||!y._storeEffectOnSubMeshes&&!(null===(n=y.getEffect())||void 0===n?void 0:n._wasPreviouslyReady))return M&&(M.maxZ=m,c.updateTransformMatrix(!0)),this}else{if(y._storeEffectOnSubMeshes){if(!y.isReadyForSubMesh(this,e,v))return M&&(M.maxZ=m,c.updateTransformMatrix(!0)),this}else if(!y.isReady(this,v))return M&&(M.maxZ=m,c.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=y}t&&_.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),h=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();let b=null!==(o=null==h?void 0:h.effect)&&void 0!==o?o:null;for(let t of c._beforeRenderingMeshStage)t.action(this,e,g,b);if(!h||!b)return M&&(M.maxZ=m,c.updateTransformMatrix(!0)),this;let S=s||this;if(!D.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||null!==this.overrideMaterialSideOrientation)){let e=S._getWorldMatrixDeterminant();null==(d=this.overrideMaterialSideOrientation)&&(d=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(d=d===I.F.ClockWiseSideOrientation?I.F.CounterClockWiseSideOrientation:I.F.ClockWiseSideOrientation),D.sideOrientation=d}else d=D.sideOrientation;let x=this._internalMeshDataInfo._effectiveMaterial._preBind(h,d);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&_.setDepthWrite(!0);let B=this._internalMeshDataInfo._effectiveMaterial,P=B.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),v||this._bind(e,b,P,!1);let A=S.getWorldMatrix();for(let t of(B._storeEffectOnSubMeshes?B.bindForSubMesh(A,this,e):B.bind(A,this),!B.backFaceCulling&&B.separateCullingPass&&(_.setState(!0,B.zOffset,!1,!x,B.cullBackFaces,B.stencil,B.zOffsetUnits),this._processRendering(this,e,b,P,g,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),_.setState(!0,B.zOffset,!1,x,B.cullBackFaces,B.stencil,B.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,b,P,g,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind(),c._afterRenderingMeshStage))t.action(this,e,g,b);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),M&&(M.maxZ=m,c.updateTransformMatrix(!0)),c.performancePriority!==l.a.Aggressive||D.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(f.o.MatricesWeightsKind)&&(this.isVerticesDataPresent(f.o.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){let e=this.getVerticesData(f.o.MatricesWeightsKind),t=e.length;for(let s=0;s<t;s+=4){let t=e[s]+e[s+1]+e[s+2]+e[s+3];if(0===t)e[s]=1;else{let i=1/t;e[s]*=i,e[s+1]*=i,e[s+2]*=i,e[s+3]*=i}}this.setVerticesData(f.o.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){let e=this.getVerticesData(f.o.MatricesWeightsExtraKind),t=this.getVerticesData(f.o.MatricesWeightsKind),s=t.length;for(let i=0;i<s;i+=4){let s=t[i]+t[i+1]+t[i+2]+t[i+3];if(0===(s+=e[i]+e[i+1]+e[i+2]+e[i+3]))t[i]=1;else{let r=1/s;t[i]*=r,t[i+1]*=r,t[i+2]*=r,t[i+3]*=r,e[i]*=r,e[i+1]*=r,e[i+2]*=r,e[i+3]*=r}}this.setVerticesData(f.o.MatricesWeightsKind,t),this.setVerticesData(f.o.MatricesWeightsKind,e)}validateSkinning(){let e=this.getVerticesData(f.o.MatricesWeightsExtraKind),t=this.getVerticesData(f.o.MatricesWeightsKind);if(null===t||null==this.skeleton)return{skinned:!1,valid:!0,report:"not skinned"};let s=t.length,i=0,r=0,a=0,n=0,o=null===e?4:8,h=[];for(let e=0;e<=o;e++)h[e]=0;for(let l=0;l<s;l+=4){let s=t[l],d=s,c=0===d?0:1;for(let r=1;r<o;r++){let a=r<4?t[l+r]:e[l+r-4];a>s&&i++,0!==a&&c++,d+=a,s=a}if(h[c]++,c>a&&(a=c),0===d)r++;else{let s=1/d,i=0;for(let r=0;r<o;r++)r<4?i+=Math.abs(t[l+r]-t[l+r]*s):i+=Math.abs(e[l+r-4]-e[l+r-4]*s);i>.001&&n++}}let l=this.skeleton.bones.length,d=this.getVerticesData(f.o.MatricesIndicesKind),c=this.getVerticesData(f.o.MatricesIndicesExtraKind),u=0;for(let e=0;e<s;e+=4)for(let t=0;t<o;t++){let s=t<4?d[e+t]:c[e+t-4];(s>=l||s<0)&&u++}let g="Number of Weights = "+s/4+"\nMaximum influences = "+a+"\nMissing Weights = "+r+"\nNot Sorted = "+i+"\nNot Normalized = "+n+"\nWeightCounts = ["+h+"]\nNumber of bones = "+l+"\nBad Bone Indices = "+u;return{skinned:!0,valid:0===r&&0===n&&0===u,report:g}}_checkDelayState(){let e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);let t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return r.w1.LoadFile(this.delayLoadingFile,t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach(e=>{e.refreshBoundingInfo(),e._syncSubMeshes()}),this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return!!(2!==this.delayLoadState&&super.isInFrustum(e))&&(this._checkDelayState(),!0)}setMaterialById(e){let t;let s=this.getScene().materials;for(t=s.length-1;t>-1;t--)if(s[t].id===e)return this.material=s[t],this;let i=this.getScene().multiMaterials;for(t=i.length-1;t>-1;t--)if(i[t].id===e){this.material=i[t];break}return this}getAnimatables(){let e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){let t;if(!this.isVerticesDataPresent(f.o.PositionKind))return this;let s=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(f.o.PositionKind),r=d.P.Zero();for(t=0;t<i.length;t+=3)d.P.TransformCoordinatesFromFloatsToRef(i[t],i[t+1],i[t+2],e,r).toArray(i,t);if(this.setVerticesData(f.o.PositionKind,i,this.getVertexBuffer(f.o.PositionKind).isUpdatable()),this.isVerticesDataPresent(f.o.NormalKind)){for(t=0,i=this.getVerticesData(f.o.NormalKind);t<i.length;t+=3)d.P.TransformNormalFromFloatsToRef(i[t],i[t+1],i[t+2],e,r).normalize().toArray(i,t);this.setVerticesData(f.o.NormalKind,i,this.getVertexBuffer(f.o.NormalKind).isUpdatable())}return 0>e.determinant()&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=s,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions?this._internalAbstractMeshDataInfo._positions:this._geometry?this._geometry._positions:null}_resetPointsArrayCache(){return this._geometry&&this._geometry._resetPointsArrayCache(),this}_generatePointsArray(){return!!this._geometry&&this._geometry._generatePointsArray()}clone(e="",t=null,s,i=!0){return new Mesh(e,this.getScene(),t,this,s,i)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);let s=this._internalMeshDataInfo;if(s._onBeforeDrawObservable&&s._onBeforeDrawObservable.clear(),s._onBeforeBindObservable&&s._onBeforeBindObservable.clear(),s._onBeforeRenderObservable&&s._onBeforeRenderObservable.clear(),s._onAfterRenderObservable&&s._onAfterRenderObservable.clear(),s._onBetweenPassObservable&&s._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(s.meshMap)for(let e in s.meshMap){let t=s.meshMap[e];t&&(t._internalMeshDataInfo._source=null,s.meshMap[e]=void 0)}s._source&&s._source._internalMeshDataInfo.meshMap&&(s._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{let e=this.getScene().meshes;for(let t of e)t._internalMeshDataInfo&&t._internalMeshDataInfo._source&&t._internalMeshDataInfo._source===this&&(t._internalMeshDataInfo._source=null)}s._source=null,this._instanceDataStorage.visibleInstances={},this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,s,i,a,n,o=!1){let h=this.getScene();return r.w1.LoadImage(e,e=>{let r=e.width,h=e.height,l=this.getEngine().createCanvas(r,h),d=l.getContext("2d");d.drawImage(e,0,0);let c=d.getImageData(0,0,r,h).data;this.applyDisplacementMapFromBuffer(c,r,h,t,s,a,n,o),i&&i(this)},()=>{},h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,s,i,r,a,n,o=!1){if(!this.isVerticesDataPresent(f.o.PositionKind)||!this.isVerticesDataPresent(f.o.NormalKind)||!this.isVerticesDataPresent(f.o.UVKind))return y.Y.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;let h=this.getVerticesData(f.o.PositionKind,!0,!0),l=this.getVerticesData(f.o.NormalKind),c=this.getVerticesData(f.o.UVKind),u=d.P.Zero(),_=d.P.Zero(),m=d.FM.Zero();a=a||d.FM.Zero(),n=n||new d.FM(1,1);for(let o=0;o<h.length;o+=3){d.P.FromArrayToRef(h,o,u),d.P.FromArrayToRef(l,o,_),d.FM.FromArrayToRef(c,o/3*2,m);let f=Math.abs(m.x*n.x+a.x%1)*(t-1)%t|0,g=Math.abs(m.y*n.y+a.y%1)*(s-1)%s|0,M=(f+g*t)*4,I=e[M]/255,p=e[M+1]/255,v=e[M+2]/255,D=.3*I+.59*p+.11*v;_.normalize(),_.scaleInPlace(i+(r-i)*D),(u=u.add(_)).toArray(h,o)}return g.x.ComputeNormals(h,this.getIndices(),l),o?(this.setVerticesData(f.o.PositionKind,h),this.setVerticesData(f.o.NormalKind,l),this.setVerticesData(f.o.UVKind,c)):(this.updateVerticesData(f.o.PositionKind,h),this.updateVerticesData(f.o.NormalKind,l)),this}_getFlattenedNormals(e,t){let s=new Float32Array(3*e.length),i=0,r=this.overrideMaterialSideOrientation===(this._scene.useRightHandedSystem?1:0);for(let a=0;a<e.length;a+=3){let n=d.P.FromArray(t,3*e[a]),o=d.P.FromArray(t,3*e[a+1]),h=d.P.FromArray(t,3*e[a+2]),l=n.subtract(o),c=h.subtract(o),u=d.P.Normalize(d.P.Cross(l,c));r&&u.scaleInPlace(-1);for(let e=0;e<3;e++)s[i++]=u.x,s[i++]=u.y,s[i++]=u.z}return s}_convertToUnIndexedMesh(e=!1){let t=this.getVerticesDataKinds(),s=this.getIndices(),i={},separateVertices=(e,t)=>{let i=new Float32Array(s.length*t),r=0;for(let a=0;a<s.length;a++)for(let n=0;n<t;n++)i[r++]=e[s[a]*t+n];return i},r=this.geometry?this.subMeshes.slice(0):[];for(let e of t)i[e]=this.getVerticesData(e);for(let r of t){let t=this.getVertexBuffer(r),a=t.getStrideSize();if(e&&r===f.o.NormalKind){let e=this._getFlattenedNormals(s,i[f.o.PositionKind]);this.setVerticesData(f.o.NormalKind,e,t.isUpdatable(),a)}else this.setVerticesData(r,separateVertices(i[r],a),t.isUpdatable(),a)}if(this.morphTargetManager){for(let t=0;t<this.morphTargetManager.numTargets;t++){let i=this.morphTargetManager.getTarget(t),r=i.getPositions();i.setPositions(separateVertices(r,3));let a=i.getNormals();a&&i.setNormals(e?this._getFlattenedNormals(s,r):separateVertices(a,3));let n=i.getTangents();n&&i.setTangents(separateVertices(n,3));let o=i.getUVs();o&&i.setUVs(separateVertices(o,2))}this.morphTargetManager.synchronize()}for(let e=0;e<s.length;e++)s[e]=e;for(let e of(this.setIndices(s),this._unIndexed=!0,this.releaseSubMeshes(),r))M.P.AddToMesh(e.materialIndex,e.indexStart,e.indexCount,e.indexStart,e.indexCount,this);return this.synchronizeInstances(),this}convertToFlatShadedMesh(){return this._convertToUnIndexedMesh(!0)}convertToUnIndexedMesh(){return this._convertToUnIndexedMesh()}flipFaces(e=!1){let t;let s=g.x.ExtractFromMesh(this);if(e&&this.isVerticesDataPresent(f.o.NormalKind)&&s.normals)for(t=0;t<s.normals.length;t++)s.normals[t]*=-1;if(s.indices){let e;for(t=0;t<s.indices.length;t+=3)e=s.indices[t+1],s.indices[t+1]=s.indices[t+2],s.indices[t+2]=e}return s.applyToMesh(this,this.isVertexBufferUpdatable(f.o.PositionKind)),this}increaseVertices(e=1){let t=g.x.ExtractFromMesh(this),s=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,i=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,r=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,a=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(s&&i){let n,o,h,l,c;t.indices=s,t.positions=i,r&&(t.uvs=r),a&&(t.normals=a);let u=e+1,g=[];for(let e=0;e<u+1;e++)g[e]=[];let _=new d.P(0,0,0),m=new d.P(0,0,0),M=new d.FM(0,0),I=[],p=[],v=[],D=i.length;r&&(l=r.length),a&&(c=a.length);for(let e=0;e<s.length;e+=3){p[0]=s[e],p[1]=s[e+1],p[2]=s[e+2];for(let e=0;e<3;e++)if(n=p[e],o=p[(e+1)%3],void 0===v[n]&&void 0===v[o]?(v[n]=[],v[o]=[]):(void 0===v[n]&&(v[n]=[]),void 0===v[o]&&(v[o]=[])),void 0===v[n][o]&&void 0===v[o][n]){v[n][o]=[],_.x=(i[3*o]-i[3*n])/u,_.y=(i[3*o+1]-i[3*n+1])/u,_.z=(i[3*o+2]-i[3*n+2])/u,a&&(m.x=(a[3*o]-a[3*n])/u,m.y=(a[3*o+1]-a[3*n+1])/u,m.z=(a[3*o+2]-a[3*n+2])/u),r&&(M.x=(r[2*o]-r[2*n])/u,M.y=(r[2*o+1]-r[2*n+1])/u),v[n][o].push(n);for(let e=1;e<u;e++)v[n][o].push(i.length/3),i[D++]=i[3*n]+e*_.x,i[D++]=i[3*n+1]+e*_.y,i[D++]=i[3*n+2]+e*_.z,a&&(a[c++]=a[3*n]+e*m.x,a[c++]=a[3*n+1]+e*m.y,a[c++]=a[3*n+2]+e*m.z),r&&(r[l++]=r[2*n]+e*M.x,r[l++]=r[2*n+1]+e*M.y);v[n][o].push(o),v[o][n]=[],h=v[n][o].length;for(let e=0;e<h;e++)v[o][n][e]=v[n][o][h-1-e]}g[0][0]=s[e],g[1][0]=v[s[e]][s[e+1]][1],g[1][1]=v[s[e]][s[e+2]][1];for(let t=2;t<u;t++){g[t][0]=v[s[e]][s[e+1]][t],g[t][t]=v[s[e]][s[e+2]][t],_.x=(i[3*g[t][t]]-i[3*g[t][0]])/t,_.y=(i[3*g[t][t]+1]-i[3*g[t][0]+1])/t,_.z=(i[3*g[t][t]+2]-i[3*g[t][0]+2])/t,a&&(m.x=(a[3*g[t][t]]-a[3*g[t][0]])/t,m.y=(a[3*g[t][t]+1]-a[3*g[t][0]+1])/t,m.z=(a[3*g[t][t]+2]-a[3*g[t][0]+2])/t),r&&(M.x=(r[2*g[t][t]]-r[2*g[t][0]])/t,M.y=(r[2*g[t][t]+1]-r[2*g[t][0]+1])/t);for(let e=1;e<t;e++)g[t][e]=i.length/3,i[D++]=i[3*g[t][0]]+e*_.x,i[D++]=i[3*g[t][0]+1]+e*_.y,i[D++]=i[3*g[t][0]+2]+e*_.z,a&&(a[c++]=a[3*g[t][0]]+e*m.x,a[c++]=a[3*g[t][0]+1]+e*m.y,a[c++]=a[3*g[t][0]+2]+e*m.z),r&&(r[l++]=r[2*g[t][0]]+e*M.x,r[l++]=r[2*g[t][0]+1]+e*M.y)}g[u]=v[s[e+1]][s[e+2]],I.push(g[0][0],g[1][0],g[1][1]);for(let e=1;e<u;e++){let t;for(t=0;t<e;t++)I.push(g[e][t],g[e+1][t],g[e+1][t+1]),I.push(g[e][t],g[e+1][t+1],g[e][t+1]);I.push(g[e][t],g[e+1][t],g[e+1][t+1])}}t.indices=I,t.applyToMesh(this,this.isVertexBufferUpdatable(f.o.PositionKind))}else y.Y.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions")}forceSharedVertices(){let e=g.x.ExtractFromMesh(this),t=e.uvs,s=e.indices,i=e.positions,r=e.colors,a=e.matricesIndices,n=e.matricesWeights,o=e.matricesIndicesExtra,h=e.matricesWeightsExtra;if(void 0===s||void 0===i||null===s||null===i)y.Y.Warn("VertexData contains empty entries");else{let l,d;let c=[],u=[],_=[],m=[],M=[],I=[],p=[],v=[],D=[],y=0,b={};for(let e=0;e<s.length;e+=3){d=[s[e],s[e+1],s[e+2]],D=[];for(let e=0;e<3;e++){D[e]="";for(let t=0;t<3;t++)1e-8>Math.abs(i[3*d[e]+t])&&(i[3*d[e]+t]=0),D[e]+=i[3*d[e]+t]+"|"}if(!(D[0]==D[1]||D[0]==D[2]||D[1]==D[2]))for(let e=0;e<3;e++){if(void 0===(l=b[D[e]])){b[D[e]]=y,l=y++;for(let t=0;t<3;t++)c.push(i[3*d[e]+t]);if(null!=r)for(let t=0;t<4;t++)m.push(r[4*d[e]+t]);if(null!=t)for(let s=0;s<2;s++)_.push(t[2*d[e]+s]);if(null!=a)for(let t=0;t<4;t++)M.push(a[4*d[e]+t]);if(null!=n)for(let t=0;t<4;t++)I.push(n[4*d[e]+t]);if(null!=o)for(let t=0;t<4;t++)p.push(o[4*d[e]+t]);if(null!=h)for(let t=0;t<4;t++)v.push(h[4*d[e]+t])}u.push(l)}}let S=[];g.x.ComputeNormals(c,u,S),e.positions=c,e.indices=u,e.normals=S,null!=t&&(e.uvs=_),null!=r&&(e.colors=m),null!=a&&(e.matricesIndices=M),null!=n&&(e.matricesWeights=I),null!=o&&(e.matricesIndicesExtra=p),null!=n&&(e.matricesWeightsExtra=v),e.applyToMesh(this,this.isVertexBufferUpdatable(f.o.PositionKind))}}static _instancedMeshFactory(e,t){throw(0,S.S)("InstancedMesh")}static _PhysicsImpostorParser(e,t,s){throw(0,S.S)("PhysicsImpostor")}createInstance(e){return Mesh._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e<this.instances.length;e++){let t=this.instances[e];t._syncSubMeshes()}return this}optimizeIndices(e){let t=this.getIndices(),s=this.getVerticesData(f.o.PositionKind);if(!s||!t)return this;let i=[];for(let e=0;e<s.length;e+=3)i.push(d.P.FromArray(s,e));let a=[];return r.$g.SyncAsyncForLoop(i.length,40,e=>{let t=i.length-1-e,s=i[t];for(let e=0;e<t;++e){let r=i[e];if(s.equals(r)){a[t]=e;break}}},()=>{for(let e=0;e<t.length;++e)t[e]=a[t[e]]||t[e];let s=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=s,e&&e(this)}),this}serialize(e={}){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),n.$&&n.$.HasTags(this)&&(e.tags=n.$.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.checkCollisions=this.checkCollisions,e.isBlocker=this.isBlocker,e.overrideMaterialSideOrientation=this.overrideMaterialSideOrientation,this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;let t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(let t=0;t<this.subMeshes.length;t++){let s=this.subMeshes[t];e.subMeshes.push({materialIndex:s.materialIndex,verticesStart:s.verticesStart,verticesCount:s.verticesCount,indexStart:s.indexStart,indexCount:s.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(x.l.NAME_PHYSICSENGINE)){let t=this.getPhysicsImpostor();t&&(e.physicsMass=t.getParam("mass"),e.physicsFriction=t.getParam("friction"),e.physicsRestitution=t.getParam("mass"),e.physicsImpostor=t.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(let t=0;t<this.instances.length;t++){let s=this.instances[t];if(s.doNotSerialize)continue;let i={name:s.name,id:s.id,isEnabled:s.isEnabled(!1),isVisible:s.isVisible,isPickable:s.isPickable,checkCollisions:s.checkCollisions,position:s.position.asArray(),scaling:s.scaling.asArray()};if(s.parent&&s.parent._serializeAsParent(i),s.rotationQuaternion?i.rotationQuaternion=s.rotationQuaternion.asArray():s.rotation&&(i.rotation=s.rotation.asArray()),this.getScene()._getComponent(x.l.NAME_PHYSICSENGINE)){let e=s.getPhysicsImpostor();e&&(i.physicsMass=e.getParam("mass"),i.physicsFriction=e.getParam("friction"),i.physicsRestitution=e.getParam("mass"),i.physicsImpostor=e.type)}s.metadata&&(i.metadata=s.metadata),s.actionManager&&(i.actions=s.actionManager.serialize(s.name)),e.instances.push(i),D.p4.AppendSerializedAnimations(s,i),i.ranges=s.serializeAnimationRanges()}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){let t={data:{},sizes:{},strides:{}};for(let e in this._userThinInstanceBuffersStorage.data)t.data[e]=Array.from(this._userThinInstanceBuffersStorage.data[e]),t.sizes[e]=this._userThinInstanceBuffersStorage.sizes[e],t.strides[e]=this._userThinInstanceBuffersStorage.strides[e];e.thinInstances.userThinInstance=t}return D.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e}_syncGeometryWithMorphTargetManager(){if(!this.geometry)return;this._markSubMeshesAsAttributesDirty();let e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices()){y.Y.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),this.morphTargetManager=null;return}if(e.isUsingTextureForTargets)return;for(let t=0;t<e.numInfluencers;t++){let s=e.getActiveTarget(t),i=s.getPositions();if(!i){y.Y.Error("Invalid morph target. Target must have positions.");return}this.geometry.setVerticesData(f.o.PositionKind+t,i,!1,3);let r=s.getNormals();r&&this.geometry.setVerticesData(f.o.NormalKind+t,r,!1,3);let a=s.getTangents();a&&this.geometry.setVerticesData(f.o.TangentKind+t,a,!1,3);let n=s.getUVs();n&&this.geometry.setVerticesData(f.o.UVKind+"_"+t,n,!1,2)}}else{let e=0;for(;this.geometry.isVerticesDataPresent(f.o.PositionKind+e);)this.geometry.removeVerticesData(f.o.PositionKind+e),this.geometry.isVerticesDataPresent(f.o.NormalKind+e)&&this.geometry.removeVerticesData(f.o.NormalKind+e),this.geometry.isVerticesDataPresent(f.o.TangentKind+e)&&this.geometry.removeVerticesData(f.o.TangentKind+e),this.geometry.isVerticesDataPresent(f.o.UVKind+e)&&this.geometry.removeVerticesData(f.o.UVKind+"_"+e),e++}}static Parse(e,t,s){let i;if((i=e.type&&"LinesMesh"===e.type?Mesh._LinesMeshParser(e,t):e.type&&"GroundMesh"===e.type?Mesh._GroundMeshParser(e,t):e.type&&"GoldbergMesh"===e.type?Mesh._GoldbergMeshParser(e,t):e.type&&"GreasedLineMesh"===e.type?Mesh._GreasedLineMeshParser(e,t):e.type&&"TrailMesh"===e.type?Mesh._TrailMeshParser(e,t):new Mesh(e.name,t)).id=e.id,i._waitingParsedUniqueId=e.uniqueId,n.$&&n.$.AddTagsTo(i,e.tags),i.position=d.P.FromArray(e.position),void 0!==e.metadata&&(i.metadata=e.metadata),e.rotationQuaternion?i.rotationQuaternion=d._f.FromArray(e.rotationQuaternion):e.rotation&&(i.rotation=d.P.FromArray(e.rotation)),i.scaling=d.P.FromArray(e.scaling),e.localMatrix?i.setPreTransformMatrix(d.y3.FromArray(e.localMatrix)):e.pivotMatrix&&i.setPivotMatrix(d.y3.FromArray(e.pivotMatrix)),i.setEnabled(e.isEnabled),i.isVisible=e.isVisible,i.infiniteDistance=e.infiniteDistance,i.showBoundingBox=e.showBoundingBox,i.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,void 0!==e.applyFog&&(i.applyFog=e.applyFog),void 0!==e.pickable&&(i.isPickable=e.pickable),void 0!==e.alphaIndex&&(i.alphaIndex=e.alphaIndex),i.receiveShadows=e.receiveShadows,void 0!==e.billboardMode&&(i.billboardMode=e.billboardMode),void 0!==e.visibility&&(i.visibility=e.visibility),i.checkCollisions=e.checkCollisions,void 0!==e.overrideMaterialSideOrientation&&(i.overrideMaterialSideOrientation=e.overrideMaterialSideOrientation),void 0!==e.isBlocker&&(i.isBlocker=e.isBlocker),i._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(i._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),void 0!==e.parentId&&(i._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(i._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.actions&&(i._waitingData.actions=e.actions),void 0!==e.overlayAlpha&&(i.overlayAlpha=e.overlayAlpha),void 0!==e.overlayColor&&(i.overlayColor=c.Wo.FromArray(e.overlayColor)),void 0!==e.renderOverlay&&(i.renderOverlay=e.renderOverlay),i.isUnIndexed=!!e.isUnIndexed,i.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(i.delayLoadState=4,i.delayLoadingFile=s+e.delayLoadingFile,i.buildBoundingInfo(d.P.FromArray(e.boundingBoxMinimum),d.P.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(i._binaryInfo=e._binaryInfo),i._delayInfo=[],e.hasUVs&&i._delayInfo.push(f.o.UVKind),e.hasUVs2&&i._delayInfo.push(f.o.UV2Kind),e.hasUVs3&&i._delayInfo.push(f.o.UV3Kind),e.hasUVs4&&i._delayInfo.push(f.o.UV4Kind),e.hasUVs5&&i._delayInfo.push(f.o.UV5Kind),e.hasUVs6&&i._delayInfo.push(f.o.UV6Kind),e.hasColors&&i._delayInfo.push(f.o.ColorKind),e.hasMatricesIndices&&i._delayInfo.push(f.o.MatricesIndicesKind),e.hasMatricesWeights&&i._delayInfo.push(f.o.MatricesWeightsKind),i._delayLoadingFunction=_.Z._ImportGeometry,v.Z.ForceFullSceneLoadingForIncremental&&i._checkDelayState()):_.Z._ImportGeometry(e,i),e.materialUniqueId?i._waitingMaterialId=e.materialUniqueId:e.materialId&&(i._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(i.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(i.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(i.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t<e.animations.length;t++){let s=e.animations[t],r=(0,b.q)("BABYLON.Animation");r&&i.animations.push(r.Parse(s))}u.N.ParseAnimationRanges(i,e,t)}if(e.autoAnimate&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?i.layerMask=Math.abs(parseInt(e.layerMask)):i.layerMask=268435455,e.physicsImpostor&&Mesh._PhysicsImpostorParser(t,i,e),e.lodMeshIds&&(i._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let s=0;s<e.instances.length;s++){let r=e.instances[s],a=i.createInstance(r.name);if(r.id&&(a.id=r.id),n.$&&(r.tags?n.$.AddTagsTo(a,r.tags):n.$.AddTagsTo(a,e.tags)),a.position=d.P.FromArray(r.position),void 0!==r.metadata&&(a.metadata=r.metadata),void 0!==r.parentId&&(a._waitingParentId=r.parentId),void 0!==r.parentInstanceIndex&&(a._waitingParentInstanceIndex=r.parentInstanceIndex),void 0!==r.isEnabled&&null!==r.isEnabled&&a.setEnabled(r.isEnabled),void 0!==r.isVisible&&null!==r.isVisible&&(a.isVisible=r.isVisible),void 0!==r.isPickable&&null!==r.isPickable&&(a.isPickable=r.isPickable),r.rotationQuaternion?a.rotationQuaternion=d._f.FromArray(r.rotationQuaternion):r.rotation&&(a.rotation=d.P.FromArray(r.rotation)),a.scaling=d.P.FromArray(r.scaling),void 0!=r.checkCollisions&&null!=r.checkCollisions&&(a.checkCollisions=r.checkCollisions),void 0!=r.pickable&&null!=r.pickable&&(a.isPickable=r.pickable),void 0!=r.showBoundingBox&&null!=r.showBoundingBox&&(a.showBoundingBox=r.showBoundingBox),void 0!=r.showSubMeshesBoundingBox&&null!=r.showSubMeshesBoundingBox&&(a.showSubMeshesBoundingBox=r.showSubMeshesBoundingBox),void 0!=r.alphaIndex&&null!=r.showSubMeshesBoundingBox&&(a.alphaIndex=r.alphaIndex),r.physicsImpostor&&Mesh._PhysicsImpostorParser(t,a,r),void 0!==r.actions&&(a._waitingData.actions=r.actions),r.animations){for(let e=0;e<r.animations.length;e++){let t=r.animations[e],s=(0,b.q)("BABYLON.Animation");s&&a.animations.push(s.Parse(t))}u.N.ParseAnimationRanges(a,r,t),r.autoAnimate&&t.beginAnimation(a,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1)}}if(e.thinInstances){let t=e.thinInstances;if(i.thinInstanceEnablePicking=!!t.enablePicking,t.matrixData?(i.thinInstanceSetBuffer("matrix",new Float32Array(t.matrixData),16,!1),i._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,i._thinInstanceDataStorage.instancesCount=t.instancesCount):i._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,e.thinInstances.userThinInstance){let t=e.thinInstances.userThinInstance;for(let e in t.data)i.thinInstanceSetBuffer(e,new Float32Array(t.data[e]),t.strides[e],!1),i._userThinInstanceBuffersStorage.sizes[e]=t.sizes[e]}}return i}setPositionsForCPUSkinning(){let e=this._internalMeshDataInfo;if(!e._sourcePositions){let t=this.getVerticesData(f.o.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(f.o.PositionKind)||this.setVerticesData(f.o.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){let e=this._internalMeshDataInfo;if(!e._sourceNormals){let t=this.getVerticesData(f.o.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(f.o.NormalKind)||this.setVerticesData(f.o.NormalKind,t,!0)}return e._sourceNormals}applySkeleton(e){let t;if(!this.geometry||this.geometry._softwareSkinningFrameId==this.getScene().getFrameId()||(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(f.o.PositionKind)||!this.isVerticesDataPresent(f.o.MatricesIndicesKind)||!this.isVerticesDataPresent(f.o.MatricesWeightsKind)))return this;let s=this.isVerticesDataPresent(f.o.NormalKind),i=this._internalMeshDataInfo;if(!i._sourcePositions){let e=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=e}s&&!i._sourceNormals&&this.setNormalsForCPUSkinning();let r=this.getVerticesData(f.o.PositionKind);if(!r)return this;r instanceof Float32Array||(r=new Float32Array(r));let a=this.getVerticesData(f.o.NormalKind);if(s){if(!a)return this;a instanceof Float32Array||(a=new Float32Array(a))}let n=this.getVerticesData(f.o.MatricesIndicesKind),o=this.getVerticesData(f.o.MatricesWeightsKind);if(!o||!n)return this;let h=this.numBoneInfluencers>4,l=h?this.getVerticesData(f.o.MatricesIndicesExtraKind):null,c=h?this.getVerticesData(f.o.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),g=d.P.Zero(),_=new d.y3,m=new d.y3,M=0;for(let e=0;e<r.length;e+=3,M+=4){let f;for(t=0;t<4;t++)(f=o[M+t])>0&&(d.y3.FromFloat32ArrayToRefScaled(u,Math.floor(16*n[M+t]),f,m),_.addToSelf(m));if(h)for(t=0;t<4;t++)(f=c[M+t])>0&&(d.y3.FromFloat32ArrayToRefScaled(u,Math.floor(16*l[M+t]),f,m),_.addToSelf(m));d.P.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],_,g),g.toArray(r,e),s&&(d.P.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],_,g),g.toArray(a,e)),_.reset()}return this.updateVerticesData(f.o.PositionKind,r),s&&this.updateVerticesData(f.o.NormalKind,a),this}static MinMax(e){let t=null,s=null;return(e.forEach(function(e){let i=e.getBoundingInfo(),r=i.boundingBox;t&&s?(t.minimizeInPlace(r.minimumWorld),s.maximizeInPlace(r.maximumWorld)):(t=r.minimumWorld,s=r.maximumWorld)}),t&&s)?{min:t,max:s}:{min:d.P.Zero(),max:d.P.Zero()}}static Center(e){let t=e instanceof Array?Mesh.MinMax(e):e;return d.P.Center(t.min,t.max)}static MergeMeshes(e,t=!0,s,i,r,a){return(0,o.s3)(Mesh._MergeMeshesCoroutine(e,t,s,i,r,a,!1))}static MergeMeshesAsync(e,t=!0,s,i,r,a){return(0,o.sM)(Mesh._MergeMeshesCoroutine(e,t,s,i,r,a,!0),(0,o.KO)())}static*_MergeMeshesCoroutine(e,t=!0,s,i,r,a,n){let o;if(0===(e=e.filter(Boolean)).length)return null;if(!s){let t=0;for(o=0;o<e.length;o++)if((t+=e[o].getTotalVertices())>=65536)return y.Y.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}a&&(r=!1);let h=[],l=[],d=[],c=e[0].overrideMaterialSideOrientation;for(o=0;o<e.length;o++){let t=e[o];if(t.isAnInstance)return y.Y.Warn("Cannot merge instance meshes."),null;if(c!==t.overrideMaterialSideOrientation)return y.Y.Warn("Cannot merge meshes with different overrideMaterialSideOrientation values."),null;if(r&&d.push(t.getTotalIndices()),a){if(t.material){let e=t.material;if(e instanceof p.G){for(let t=0;t<e.subMaterials.length;t++)0>h.indexOf(e.subMaterials[t])&&h.push(e.subMaterials[t]);for(let s=0;s<t.subMeshes.length;s++)l.push(h.indexOf(e.subMaterials[t.subMeshes[s].materialIndex])),d.push(t.subMeshes[s].indexCount)}else{0>h.indexOf(e)&&h.push(e);for(let s=0;s<t.subMeshes.length;s++)l.push(h.indexOf(e)),d.push(t.subMeshes[s].indexCount)}}else for(let e=0;e<t.subMeshes.length;e++)l.push(0),d.push(t.subMeshes[e].indexCount)}}let u=e[0],getVertexDataFromMesh=e=>{let t=e.computeWorldMatrix(!0),s=g.x.ExtractFromMesh(e,!1,!1);return{vertexData:s,transform:t}},{vertexData:f,transform:_}=getVertexDataFromMesh(u);n&&(yield);let m=Array(e.length-1);for(let t=1;t<e.length;t++)m[t-1]=getVertexDataFromMesh(e[t]),n&&(yield);let I=f._mergeCoroutine(_,m,s,n,!t),v=I.next();for(;!v.done;)n&&(yield),v=I.next();let D=v.value;i||(i=new Mesh(u.name+"_merged",u.getScene()));let b=D._applyToCoroutine(i,void 0,n),S=b.next();for(;!S.done;)n&&(yield),S=b.next();if(i.checkCollisions=u.checkCollisions,i.overrideMaterialSideOrientation=u.overrideMaterialSideOrientation,t)for(o=0;o<e.length;o++)e[o].dispose();if(r||a){i.releaseSubMeshes(),o=0;let e=0;for(;o<d.length;)M.P.CreateFromIndices(0,e,d[o],i,void 0,!1),e+=d[o],o++;for(let e of i.subMeshes)e.refreshBoundingInfo();i.computeWorldMatrix(!0)}if(a){let e=new p.G(u.name+"_merged",u.getScene());e.subMaterials=h;for(let e=0;e<i.subMeshes.length;e++)i.subMeshes[e].materialIndex=l[e];i.material=e}else i.material=u.material;return i}addInstance(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)}removeInstance(e){let t=e._indexInSourceMeshInstanceArray;if(-1!=t){if(t!==this.instances.length-1){let e=this.instances[this.instances.length-1];this.instances[t]=e,e._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}}_shouldConvertRHS(){return this.overrideMaterialSideOrientation===I.F.CounterClockWiseSideOrientation}_getRenderingFillMode(e){var t;let s=this.getScene();return s.forcePointsCloud?I.F.PointFillMode:s.forceWireframe?I.F.WireFrameFillMode:null!==(t=this.overrideRenderingFillMode)&&void 0!==t?t:e}setMaterialByID(e){return this.setMaterialById(e)}static CreateRibbon(e,t,s,i,r,a,n,o,h){throw Error("Import MeshBuilder to populate this function")}static CreateDisc(e,t,s,i,r,a){throw Error("Import MeshBuilder to populate this function")}static CreateBox(e,t,s,i,r){throw Error("Import MeshBuilder to populate this function")}static CreateSphere(e,t,s,i,r,a){throw Error("Import MeshBuilder to populate this function")}static CreateHemisphere(e,t,s,i){throw Error("Import MeshBuilder to populate this function")}static CreateCylinder(e,t,s,i,r,a,n,o,h){throw Error("Import MeshBuilder to populate this function")}static CreateTorus(e,t,s,i,r,a,n){throw Error("Import MeshBuilder to populate this function")}static CreateTorusKnot(e,t,s,i,r,a,n,o,h,l){throw Error("Import MeshBuilder to populate this function")}static CreateLines(e,t,s,i,r){throw Error("Import MeshBuilder to populate this function")}static CreateDashedLines(e,t,s,i,r,a,n,o){throw Error("Import MeshBuilder to populate this function")}static CreatePolygon(e,t,s,i,r,a,n){throw Error("Import MeshBuilder to populate this function")}static ExtrudePolygon(e,t,s,i,r,a,n,o){throw Error("Import MeshBuilder to populate this function")}static ExtrudeShape(e,t,s,i,r,a,n,o,h,l){throw Error("Import MeshBuilder to populate this function")}static ExtrudeShapeCustom(e,t,s,i,r,a,n,o,h,l,d,c){throw Error("Import MeshBuilder to populate this function")}static CreateLathe(e,t,s,i,r,a,n){throw Error("Import MeshBuilder to populate this function")}static CreatePlane(e,t,s,i,r){throw Error("Import MeshBuilder to populate this function")}static CreateGround(e,t,s,i,r,a){throw Error("Import MeshBuilder to populate this function")}static CreateTiledGround(e,t,s,i,r,a,n,o,h){throw Error("Import MeshBuilder to populate this function")}static CreateGroundFromHeightMap(e,t,s,i,r,a,n,o,h,l,d){throw Error("Import MeshBuilder to populate this function")}static CreateTube(e,t,s,i,r,a,n,o,h,l){throw Error("Import MeshBuilder to populate this function")}static CreatePolyhedron(e,t,s){throw Error("Import MeshBuilder to populate this function")}static CreateIcoSphere(e,t,s){throw Error("Import MeshBuilder to populate this function")}static CreateDecal(e,t,s,i,r,a){throw Error("Import MeshBuilder to populate this function")}static CreateCapsule(e,t,s){throw Error("Import MeshBuilder to populate this function")}static ExtendToGoldberg(e){throw Error("Import MeshBuilder to populate this function")}};Mesh.FRONTSIDE=g.x.FRONTSIDE,Mesh.BACKSIDE=g.x.BACKSIDE,Mesh.DOUBLESIDE=g.x.DOUBLESIDE,Mesh.DEFAULTSIDE=g.x.DEFAULTSIDE,Mesh.NO_CAP=0,Mesh.CAP_START=1,Mesh.CAP_END=2,Mesh.CAP_ALL=3,Mesh.NO_FLIP=0,Mesh.FLIP_TILE=1,Mesh.ROTATE_TILE=2,Mesh.FLIP_ROW=3,Mesh.ROTATE_ROW=4,Mesh.FLIP_N_ROTATE_TILE=5,Mesh.FLIP_N_ROTATE_ROW=6,Mesh.CENTER=0,Mesh.LEFT=1,Mesh.RIGHT=2,Mesh.TOP=3,Mesh.BOTTOM=4,Mesh.INSTANCEDMESH_SORT_TRANSPARENT=!1,Mesh._GroundMeshParser=(e,t)=>{throw(0,S.S)("GroundMesh")},Mesh._GoldbergMeshParser=(e,t)=>{throw(0,S.S)("GoldbergMesh")},Mesh._LinesMeshParser=(e,t)=>{throw(0,S.S)("LinesMesh")},Mesh._GreasedLineMeshParser=(e,t)=>{throw(0,S.S)("GreasedLineMesh")},Mesh._GreasedLineRibbonMeshParser=(e,t)=>{throw(0,S.S)("GreasedLineRibbonMesh")},Mesh._TrailMeshParser=(e,t)=>{throw(0,S.S)("TrailMesh")},(0,b.H)("BABYLON.Mesh",Mesh)}}]); \ No newline at end of file diff --git a/.next/static/chunks/23-fb41cbadaf19fac2.js b/.next/static/chunks/23-fb41cbadaf19fac2.js deleted file mode 100644 index aff9b47..0000000 --- a/.next/static/chunks/23-fb41cbadaf19fac2.js +++ /dev/null @@ -1,11400 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[23],{1301:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let r=i(6927);i(6006);let s=r._(i(1937));function n(e){return{default:(null==e?void 0:e.default)||e}}function a(e,t){let i=s.default,r={loading:e=>{let{error:t,isLoading:i,pastDelay:r}=e;return null}};"function"==typeof e&&(r.loader=e),Object.assign(r,t);let a=r.loader;return i({...r,loader:()=>null!=a?a().then(n):Promise.resolve(n(()=>null))})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7069:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{suspense:function(){return s},NoSSR:function(){return n}}),i(6927),i(6006);let r=i(4722);function s(){let e=Error(r.NEXT_DYNAMIC_NO_SSR_CODE);throw e.digest=r.NEXT_DYNAMIC_NO_SSR_CODE,e}function n(e){let{children:t}=e;return t}},1937:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let r=i(6927),s=r._(i(6006)),n=i(7069),a=function(e){let t=Object.assign({loader:null,loading:null,ssr:!0},e);function i(e){let i=t.loading,r=s.default.createElement(i,{isLoading:!0,pastDelay:!0,error:null}),a=t.ssr?s.default.Fragment:n.NoSSR,o=t.lazy;return s.default.createElement(s.default.Suspense,{fallback:r},s.default.createElement(a,null,s.default.createElement(o,e)))}return t.lazy=s.default.lazy(t.loader),i.displayName="LoadableComponent",i}},3177:function(e,t,i){/** - * @license React - * react-jsx-runtime.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var r=i(6006),s=Symbol.for("react.element"),n=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,o=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function h(e,t,i){var r,n={},h=null,u=null;for(r in void 0!==i&&(h=""+i),void 0!==t.key&&(h=""+t.key),void 0!==t.ref&&(u=t.ref),t)a.call(t,r)&&!l.hasOwnProperty(r)&&(n[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===n[r]&&(n[r]=t[r]);return{$$typeof:s,type:e,key:h,ref:u,props:n,_owner:o.current}}t.Fragment=n,t.jsx=h,t.jsxs=h},9268:function(e,t,i){e.exports=i(3177)},2511:function(e,t,i){i.d(t,{O:function(){return r}});class r{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(let e in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(let e in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,e)){let t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(let t in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,t)){let i=parseInt(t);if(i===e)return!0}return!1}}r.Triggers={}},9326:function(e,t,i){i.d(t,{V:function(){return r}});class r{constructor(e,t,i,r,s,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=n}static CreateNew(e,t,i){let s=e.getScene();return new r(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new r(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new r(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new r(e,t.x,t.y,null,i,s)}}},7620:function(e,t,i){i.d(t,{l:function(){return s},o:function(){return n}});var r=i(6430);class s{constructor(e,t,i,s=0,n=!1,a=!1,o=!1,l){this._isAlreadyOwned=!1,e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=a,this._divisor=l||1,t instanceof r.h?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=o?s:s*Float32Array.BYTES_PER_ELEMENT,n||this.create()}createVertexBuffer(e,t,i,r,s,a=!1,o){let l=a?t:t*Float32Array.BYTES_PER_ELEMENT,h=r?a?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new n(this._engine,this,e,this._updatable,!0,h,void 0===s?this._instanced:s,l,i,void 0,void 0,!0,this._divisor||o)}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,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),0===t&&void 0===i?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null,this._data=null)}}class n{get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){let t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}constructor(e,t,i,r,a,o,l,h,u,c,d=!1,p=!1,_=1,f=!1){if(t instanceof s?(this._buffer=t,this._ownsBuffer=f):(this._buffer=new s(e,t,r,o,a,l,p),this._ownsBuffer=!0),this.uniqueId=n._Counter++,this._kind=i,void 0==c){let e=this.getData();this.type=n.FLOAT,e instanceof Int8Array?this.type=n.BYTE:e instanceof Uint8Array?this.type=n.UNSIGNED_BYTE:e instanceof Int16Array?this.type=n.SHORT:e instanceof Uint16Array?this.type=n.UNSIGNED_SHORT:e instanceof Int32Array?this.type=n.INT:e instanceof Uint32Array&&(this.type=n.UNSIGNED_INT)}else this.type=c;let m=n.GetTypeByteLength(this.type);p?(this._size=u||(o?o/m:n.DeduceStride(i)),this.byteStride=o||this._buffer.byteStride||this._size*m,this.byteOffset=h||0):(this._size=u||o||n.DeduceStride(i),this.byteStride=o?o*m:this._buffer.byteStride||this._size*m,this.byteOffset=(h||0)*m),this.normalized=d,this._instanced=void 0!==l&&l,this._instanceDivisor=l?_: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){let i=this.getData();if(!i)return null;let r=this.getSize()*n.GetTypeByteLength(this.type),s=e*this.getSize();if(this.type!==n.FLOAT||this.byteStride!==r){let 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){let 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){let t=new Float32Array(s),r=new Float32Array(i.buffer,e,s);return t.set(r),t}let r=e%4;return r&&(e=Math.max(0,e-r)),new Float32Array(i.buffer,e,s)}}return t?i.slice():i}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/n.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/n.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*n.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){n.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}static DeduceStride(e){switch(e){case n.UVKind:case n.UV2Kind:case n.UV3Kind:case n.UV4Kind:case n.UV5Kind:case n.UV6Kind:return 2;case n.NormalKind:case n.PositionKind:return 3;case n.ColorKind:case n.MatricesIndicesKind:case n.MatricesIndicesExtraKind:case n.MatricesWeightsKind:case n.MatricesWeightsExtraKind:case n.TangentKind:return 4;default:throw Error("Invalid kind '"+e+"'")}}static GetTypeByteLength(e){switch(e){case n.BYTE:case n.UNSIGNED_BYTE:return 1;case n.SHORT:case n.UNSIGNED_SHORT:return 2;case n.INT:case n.UNSIGNED_INT:case n.FLOAT:return 4;default:throw Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,r,s,a,o,l){if(e instanceof Array){let s=t/4,n=i/4;for(let t=0;t<a;t+=r){for(let i=0;i<r;i++)l(e[s+i],t+i);s+=n}}else{let h=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),u=n.GetTypeByteLength(s);for(let e=0;e<a;e+=r){let a=t;for(let t=0;t<r;t++){let i=n._GetFloatValue(h,s,a,o);l(i,e+t),a+=u}t+=i}}}static _GetFloatValue(e,t,i,r){switch(t){case n.BYTE:{let t=e.getInt8(i);return r&&(t=Math.max(t/127,-1)),t}case n.UNSIGNED_BYTE:{let t=e.getUint8(i);return r&&(t/=255),t}case n.SHORT:{let t=e.getInt16(i,!0);return r&&(t=Math.max(t/32767,-1)),t}case n.UNSIGNED_SHORT:{let t=e.getUint16(i,!0);return r&&(t/=65535),t}case n.INT:return e.getInt32(i,!0);case n.UNSIGNED_INT:return e.getUint32(i,!0);case n.FLOAT:return e.getFloat32(i,!0);default:throw Error(`Invalid component type ${t}`)}}}n._Counter=0,n.BYTE=5120,n.UNSIGNED_BYTE=5121,n.SHORT=5122,n.UNSIGNED_SHORT=5123,n.INT=5124,n.UNSIGNED_INT=5125,n.FLOAT=5126,n.PositionKind="position",n.NormalKind="normal",n.TangentKind="tangent",n.UVKind="uv",n.UV2Kind="uv2",n.UV3Kind="uv3",n.UV4Kind="uv4",n.UV5Kind="uv5",n.UV6Kind="uv6",n.ColorKind="color",n.ColorInstanceKind="instanceColor",n.MatricesIndicesKind="matricesIndices",n.MatricesWeightsKind="matricesWeights",n.MatricesIndicesExtraKind="matricesIndicesExtra",n.MatricesWeightsExtraKind="matricesWeightsExtra"},6430:function(e,t,i){i.d(t,{h:function(){return r}});class r{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=r._Counter++}}r._Counter=0},7419:function(e,t,i){i.d(t,{V:function(){return f}});var r=i(6851),s=i(6816),n=i(1945),a=i(3636),o=i(6702),l=i(1823),h=i(9747),u=i(7694),c=i(9678),d=i(4620),p=i(5831),_=i(9320);class f extends h.N{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,r;let s=0,n=0;if(this.mode===f.PERSPECTIVE_CAMERA)this.fovMode===f.FOVMODE_VERTICAL_FIXED?(n=2*this.minZ*Math.tan(this.fov/2),s=this.getEngine().getAspectRatio(this)*n):n=(s=2*this.minZ*Math.tan(this.fov/2))/this.getEngine().getAspectRatio(this);else{let a=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;s=(null!==(e=this.orthoRight)&&void 0!==e?e:a)-(null!==(t=this.orthoLeft)&&void 0!==t?t:-a),n=(null!==(i=this.orthoTop)&&void 0!==i?i:o)-(null!==(r=this.orthoBottom)&&void 0!==r?r:-o)}return s*n}set orthoLeft(e){for(let t of(this._orthoLeft=e,this._rigCameras))t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){for(let t of(this._orthoRight=e,this._rigCameras))t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){for(let t of(this._orthoBottom=e,this._rigCameras))t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){for(let t of(this._orthoTop=e,this._rigCameras))t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){for(let t of(this._mode=e,this._rigCameras))t.mode=e}get mode(){return this._mode}constructor(e,t,i,r=!0){super(e,i),this._position=l.P.Zero(),this._upVector=l.P.Up(),this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=f.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new p.l(0,0,1,1),this.layerMask=268435455,this.fovMode=f.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=f.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new o.y$,this.onProjectionMatrixChangedObservable=new o.y$,this.onAfterCheckInputsObservable=new o.y$,this.onRestoreStateObservable=new o.y$,this.isRigCamera=!1,this._rigCameras=[],this._webvrViewMatrix=l.y3.Identity(),this._skipRendering=!1,this._projectionMatrix=new l.y3,this._postProcesses=[],this._activeMeshes=new n.t(256),this._globalPosition=l.P.Zero(),this._computedViewMatrix=l.y3.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=l.y3.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=l._f.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}applyVerticalCorrection(){let e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return -1!==this._activeMeshes.indexOf(e)}isReady(e=!1){if(e){for(let e of this._postProcesses)if(e&&!e.isReady())return!1}return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new l.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new l.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return!!super._isSynchronized()&&this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent()}_isSynchronizedProjectionMatrix(){if(!(this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ))return!1;let e=this.getEngine();return this.mode===f.PERSPECTIVE_CAMERA?this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===e.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===e.getRenderWidth()&&this._cache.renderHeight===e.getRenderHeight()}attachControl(e,t){}detachControl(e){}update(){this._checkInputs(),this.cameraRigMode!==f.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(null!==this._postProcesses[e])return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){let e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let e=0,t=this._rigCameras.length;e<t;e++){let t=this._rigCameras[e],i=t._rigPostProcess;if(i){let e="pass"===i.getEffectName();e&&(t.isIntermediate=0===this._postProcesses.length),t._postProcesses=this._postProcesses.slice(0).concat(i),i.markTextureDirty()}else t._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(u.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){let 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,r,s,n,a,o,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;let u=this.getEngine(),c=this.getScene(),d=u.useReverseDepthBuffer;if(this.mode===f.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=u.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),(c.useRightHandedSystem?l.y3.PerspectiveFovRHToRef:l.y3.PerspectiveFovLHToRef)(this.fov,u.getAspectRatio(this),d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===f.FOVMODE_VERTICAL_FIXED,u.isNDCHalfZRange,this.projectionPlaneTilt,d);else{let e=u.getRenderWidth()/2,p=u.getRenderHeight()/2;c.useRightHandedSystem?l.y3.OrthoOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(r=this.orthoBottom)&&void 0!==r?r:-p,null!==(s=this.orthoTop)&&void 0!==s?s:p,d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,u.isNDCHalfZRange):l.y3.OrthoOffCenterLHToRef(null!==(n=this.orthoLeft)&&void 0!==n?n:-e,null!==(a=this.orthoRight)&&void 0!==a?a:e,null!==(o=this.orthoBottom)&&void 0!==o?o:-p,null!==(h=this.orthoTop)&&void 0!==h?h:p,d?this.maxZ:this.minZ,d?this.minZ:this.maxZ,this._projectionMatrix,u.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=u.getRenderWidth(),this._cache.renderHeight=u.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?_.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=_.i.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),!t||!(this.rigCameras.length>0))return e.isInFrustum(this._frustumPlanes);{let t=!1;return this.rigCameras.forEach(i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)}),t}}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,d.S)("Ray")}getForwardRayToRef(e,t=100,i,r){throw(0,d.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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){let 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!==f.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){let 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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=a.w1.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==f.RIG_MODE_NONE){let e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);let 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=a.w1.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===f.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){let e=s.p4.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),s.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){let i=s.p4.Clone(f.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return i.name=e,i.parent=t,this.onClonedObservable.notifyObservers(i),i}getDirection(e){let t=l.P.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){l.P.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,i,r=0,s=!0){let n=h.N.Construct(e,t,i,{interaxial_distance:r,isStereoscopicSideBySide:s});return n||(()=>f._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){let i=e.type,r=f.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),n=s.p4.Parse(r,e,t);if(void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),n.inputs&&(n.inputs.parse(e),n._setupInputs()),e.upVector&&(n.upVector=l.P.FromArray(e.upVector)),n.setPosition&&(n.position.copyFromFloats(0,0,0),n.setPosition(l.P.FromArray(e.position))),e.target&&n.setTarget&&n.setTarget(l.P.FromArray(e.target)),e.cameraRigMode){let t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};n.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t<e.animations.length;t++){let i=e.animations[t],r=(0,c.q)("BABYLON.Animation");r&&n.animations.push(r.Parse(i))}h.N.ParseAnimationRanges(n,e,t)}return e.autoAnimate&&t.beginAnimation(n,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&n.setEnabled(e.isEnabled),n}}f._CreateDefaultParsedCamera=(e,t)=>{throw(0,d.S)("UniversalCamera")},f.PERSPECTIVE_CAMERA=0,f.ORTHOGRAPHIC_CAMERA=1,f.FOVMODE_VERTICAL_FIXED=0,f.FOVMODE_HORIZONTAL_FIXED=1,f.RIG_MODE_NONE=0,f.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,f.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,f.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,f.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,f.RIG_MODE_STEREOSCOPIC_INTERLACED=14,f.RIG_MODE_VR=20,f.RIG_MODE_WEBVR=21,f.RIG_MODE_CUSTOM=22,f.ForceAttachControlToAlwaysPreventDefault=!1,(0,r.gn)([(0,s.hd)("position")],f.prototype,"_position",void 0),(0,r.gn)([(0,s.hd)("upVector")],f.prototype,"_upVector",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"orthoLeft",null),(0,r.gn)([(0,s.qC)()],f.prototype,"orthoRight",null),(0,r.gn)([(0,s.qC)()],f.prototype,"orthoBottom",null),(0,r.gn)([(0,s.qC)()],f.prototype,"orthoTop",null),(0,r.gn)([(0,s.qC)()],f.prototype,"fov",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"projectionPlaneTilt",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"minZ",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"maxZ",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"inertia",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"mode",null),(0,r.gn)([(0,s.qC)()],f.prototype,"layerMask",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"fovMode",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"cameraRigMode",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"interaxialDistance",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"isStereoscopicSideBySide",void 0)},7796:function(e,t,i){i.d(t,{c:function(){return r}});class r{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}},3927:function(e,t,i){i.d(t,{a:function(){return s}});var r=i(1823);class s{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new r.P(0,0,0),this._diffPositionForCollisions=new r.P(0,0,0),this._collisionResponse=!0}}},9657:function(e,t,i){i.d(t,{p:function(){return n}});var r=i(1823),s=i(7620);class n{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){let i;if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(s.o.NormalKind))return null;let n=this.pickedMesh.getIndices();(null==n?void 0:n.length)===0&&(n=null);let a=r.jp.Vector3[0],o=r.jp.Vector3[1],l=r.jp.Vector3[2];if(t){let e=this.pickedMesh.getVerticesData(s.o.NormalKind),t=n?r.P.FromArrayToRef(e,3*n[3*this.faceId],a):a.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),h=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+1],o):o.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),u=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]);t=t.scale(this.bu),h=h.scale(this.bv),u=u.scale(1-this.bu-this.bv),i=new r.P(t.x+h.x+u.x,t.y+h.y+u.y,t.z+h.z+u.z)}else{let e=this.pickedMesh.getVerticesData(s.o.PositionKind),t=n?r.P.FromArrayToRef(e,3*n[3*this.faceId],a):a.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),h=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+1],o):o.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),u=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]),c=t.subtract(h),d=u.subtract(h);i=r.P.Cross(c,d)}let h=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(r.jp.Matrix[0].copyFrom(i),(i=r.jp.Matrix[0]).setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(r.jp.Matrix[1]),i=r.jp.Matrix[1]),r.P.TransformNormalToRef(t,i,t)};if(e&&h(this.pickedMesh,i),this.ray){let t=r.jp.Vector3[0].copyFrom(i);e||h(this.pickedMesh,t),r.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;let t=this.pickedMesh.getIndices();if(!t)return null;let i=this.pickedMesh.getVerticesData(e);if(!i)return null;let n=r.FM.FromArray(i,2*t[3*this.faceId]),a=r.FM.FromArray(i,2*t[3*this.faceId+1]),o=r.FM.FromArray(i,2*t[3*this.faceId+2]);return n=n.scale(this.bu),a=a.scale(this.bv),o=o.scale(1-this.bu-this.bv),new r.FM(n.x+a.x+o.x,n.y+a.y+o.y)}}},4870:function(e,t,i){i.d(t,{e:function(){return r}});class r{}r.UseOpenGLOrientationForUV=!1},9687:function(e,t,i){i.d(t,{k:function(){return a}});var r=i(4046),s=i(1823),n=i(156);class a{constructor(e,t,i){this.vectors=r.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=r.B.BuildArray(3,s.P.Zero),this.vectorsWorld=r.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){let r=e.x,n=e.y,a=e.z,o=t.x,l=t.y,h=t.z,u=this.vectors;this.minimum.copyFromFloats(r,n,a),this.maximum.copyFromFloats(o,l,h),u[0].copyFromFloats(r,n,a),u[1].copyFromFloats(o,l,h),u[2].copyFromFloats(o,n,a),u[3].copyFromFloats(r,l,a),u[4].copyFromFloats(r,n,h),u[5].copyFromFloats(o,l,a),u[6].copyFromFloats(r,l,h),u[7].copyFromFloats(o,n,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){let t=a._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);let s=r*e,n=i.scaleInPlace(.5*s),o=this.center.subtractToRef(n,t[1]),l=this.center.addToRef(n,t[2]);return this.reConstruct(o,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){let t=this.minimumWorld,i=this.maximumWorld,r=this.directions,n=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)n[e].copyFrom(a[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let r=0;r<8;++r){let o=n[r];s.P.TransformCoordinatesToRef(a[r],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}s.P.FromArrayToRef(e.m,0,r[0]),s.P.FromArrayToRef(e.m,4,r[1]),s.P.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return a.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return a.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){let t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,a=t.z,o=i.x,l=i.y,h=i.z,u=e.x,c=e.y,d=e.z,p=-n.kn;return!(o-u<p)&&!(p>u-r)&&!(l-c<p)&&!(p>c-s)&&!(h-d<p)&&!(p>d-a)}intersectsSphere(e){return a.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){let i=this.minimumWorld,r=this.maximumWorld,s=i.x,n=i.y,a=i.z,o=r.x,l=r.y,h=r.z,u=e.x,c=e.y,d=e.z,p=t.x,_=t.y,f=t.z;return!(o<u)&&!(s>p)&&!(l<c)&&!(n>_)&&!(h<d)&&!(a>f)}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,r){let n=a._TmpVector3[0];s.P.ClampToRef(i,e,t,n);let o=s.P.DistanceSquared(i,n);return o<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){let r=t[i];for(let t=0;t<8;++t)if(0>r.dotCoordinate(e[t]))return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0,s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){r=!1;break}if(r)return!1}return!0}}a._TmpVector3=r.B.BuildArray(3,s.P.Zero)},6886:function(e,t,i){i.d(t,{j:function(){return c}});var r=i(4046),s=i(1823),n=i(9687),a=i(416);let o={min:0,max:0},l={min:0,max:0},h=(e,t,i)=>{let r=s.P.Dot(t.centerWorld,e),n=Math.abs(s.P.Dot(t.directions[0],e))*t.extendSize.x,a=Math.abs(s.P.Dot(t.directions[1],e))*t.extendSize.y,o=Math.abs(s.P.Dot(t.directions[2],e))*t.extendSize.z,l=n+a+o;i.min=r-l,i.max=r+l},u=(e,t,i)=>(h(e,t,o),h(e,i,l),!(o.min>l.max||l.min>o.max));class c{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new n.k(e,t,i),this.boundingSphere=new a.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){let i=c._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=c._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){let 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){let t=s.jp.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);let 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){return!!((2===t||3===t)&&this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(1===t||3===t||this.boundingBox.isInFrustum(e))}get diagonalLength(){let e=this.boundingBox,t=e.maximumWorld.subtractToRef(e.minimumWorld,c._TmpVector3[0]);return t.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(!a.K.Intersects(this.boundingSphere,e.boundingSphere)||!n.k.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;let i=this.boundingBox,r=e.boundingBox;return!!(u(i.directions[0],i,r)&&u(i.directions[1],i,r)&&u(i.directions[2],i,r)&&u(r.directions[0],i,r)&&u(r.directions[1],i,r)&&u(r.directions[2],i,r)&&u(s.P.Cross(i.directions[0],r.directions[0]),i,r)&&u(s.P.Cross(i.directions[0],r.directions[1]),i,r)&&u(s.P.Cross(i.directions[0],r.directions[2]),i,r)&&u(s.P.Cross(i.directions[1],r.directions[0]),i,r)&&u(s.P.Cross(i.directions[1],r.directions[1]),i,r)&&u(s.P.Cross(i.directions[1],r.directions[2]),i,r)&&u(s.P.Cross(i.directions[2],r.directions[0]),i,r)&&u(s.P.Cross(i.directions[2],r.directions[1]),i,r)&&u(s.P.Cross(i.directions[2],r.directions[2]),i,r))}}c._TmpVector3=r.B.BuildArray(2,s.P.Zero)},416:function(e,t,i){i.d(t,{K:function(){return n}});var r=i(4046),s=i(1823);class n{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);let r=s.P.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*r,this._update(i||s.y3.IdentityReadOnly)}scale(e){let t=this.radius*e,i=n._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),a=this.center.addToRef(r,i[2]);return this.reConstruct(s,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{s.P.TransformCoordinatesToRef(this.center,e,this.centerWorld);let t=n._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){let t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){let t=this.centerWorld;for(let i=0;i<6;i++)if(0>e[i].dotCoordinate(t))return!1;return!0}intersectsPoint(e){let t=s.P.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){let i=s.P.DistanceSquared(e.centerWorld,t.centerWorld),r=e.radiusWorld+t.radiusWorld;return!(r*r<i)}static CreateFromCenterAndRadius(e,t,i){this._TmpVector3[0].copyFrom(e),this._TmpVector3[1].copyFromFloats(0,0,t),this._TmpVector3[2].copyFrom(e),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);let r=new n(this._TmpVector3[0],this._TmpVector3[2]);return i?r._worldMatrix=i:r._worldMatrix=s.y3.Identity(),r}}n._TmpVector3=r.B.BuildArray(3,s.P.Zero)},485:function(e,t,i){var r,s,n,a,o,l,h,u,c,d,p,_,f,m;i.d(t,{FP:function(){return n},Fz:function(){return s},Yi:function(){return r}}),(u=r||(r={}))[u.Generic=0]="Generic",u[u.Keyboard=1]="Keyboard",u[u.Mouse=2]="Mouse",u[u.Touch=3]="Touch",u[u.DualShock=4]="DualShock",u[u.Xbox=5]="Xbox",u[u.Switch=6]="Switch",u[u.DualSense=7]="DualSense",(c=s||(s={}))[c.Horizontal=0]="Horizontal",c[c.Vertical=1]="Vertical",c[c.LeftClick=2]="LeftClick",c[c.MiddleClick=3]="MiddleClick",c[c.RightClick=4]="RightClick",c[c.BrowserBack=5]="BrowserBack",c[c.BrowserForward=6]="BrowserForward",c[c.MouseWheelX=7]="MouseWheelX",c[c.MouseWheelY=8]="MouseWheelY",c[c.MouseWheelZ=9]="MouseWheelZ",c[c.Move=12]="Move",(d=n||(n={}))[d.Horizontal=0]="Horizontal",d[d.Vertical=1]="Vertical",d[d.LeftClick=2]="LeftClick",d[d.MiddleClick=3]="MiddleClick",d[d.RightClick=4]="RightClick",d[d.BrowserBack=5]="BrowserBack",d[d.BrowserForward=6]="BrowserForward",d[d.MouseWheelX=7]="MouseWheelX",d[d.MouseWheelY=8]="MouseWheelY",d[d.MouseWheelZ=9]="MouseWheelZ",d[d.DeltaHorizontal=10]="DeltaHorizontal",d[d.DeltaVertical=11]="DeltaVertical",(p=a||(a={}))[p.Cross=0]="Cross",p[p.Circle=1]="Circle",p[p.Square=2]="Square",p[p.Triangle=3]="Triangle",p[p.L1=4]="L1",p[p.R1=5]="R1",p[p.L2=6]="L2",p[p.R2=7]="R2",p[p.Share=8]="Share",p[p.Options=9]="Options",p[p.L3=10]="L3",p[p.R3=11]="R3",p[p.DPadUp=12]="DPadUp",p[p.DPadDown=13]="DPadDown",p[p.DPadLeft=14]="DPadLeft",p[p.DPadRight=15]="DPadRight",p[p.Home=16]="Home",p[p.TouchPad=17]="TouchPad",p[p.LStickXAxis=18]="LStickXAxis",p[p.LStickYAxis=19]="LStickYAxis",p[p.RStickXAxis=20]="RStickXAxis",p[p.RStickYAxis=21]="RStickYAxis",(_=o||(o={}))[_.Cross=0]="Cross",_[_.Circle=1]="Circle",_[_.Square=2]="Square",_[_.Triangle=3]="Triangle",_[_.L1=4]="L1",_[_.R1=5]="R1",_[_.L2=6]="L2",_[_.R2=7]="R2",_[_.Create=8]="Create",_[_.Options=9]="Options",_[_.L3=10]="L3",_[_.R3=11]="R3",_[_.DPadUp=12]="DPadUp",_[_.DPadDown=13]="DPadDown",_[_.DPadLeft=14]="DPadLeft",_[_.DPadRight=15]="DPadRight",_[_.Home=16]="Home",_[_.TouchPad=17]="TouchPad",_[_.LStickXAxis=18]="LStickXAxis",_[_.LStickYAxis=19]="LStickYAxis",_[_.RStickXAxis=20]="RStickXAxis",_[_.RStickYAxis=21]="RStickYAxis",(f=l||(l={}))[f.A=0]="A",f[f.B=1]="B",f[f.X=2]="X",f[f.Y=3]="Y",f[f.LB=4]="LB",f[f.RB=5]="RB",f[f.LT=6]="LT",f[f.RT=7]="RT",f[f.Back=8]="Back",f[f.Start=9]="Start",f[f.LS=10]="LS",f[f.RS=11]="RS",f[f.DPadUp=12]="DPadUp",f[f.DPadDown=13]="DPadDown",f[f.DPadLeft=14]="DPadLeft",f[f.DPadRight=15]="DPadRight",f[f.Home=16]="Home",f[f.LStickXAxis=17]="LStickXAxis",f[f.LStickYAxis=18]="LStickYAxis",f[f.RStickXAxis=19]="RStickXAxis",f[f.RStickYAxis=20]="RStickYAxis",(m=h||(h={}))[m.B=0]="B",m[m.A=1]="A",m[m.Y=2]="Y",m[m.X=3]="X",m[m.L=4]="L",m[m.R=5]="R",m[m.ZL=6]="ZL",m[m.ZR=7]="ZR",m[m.Minus=8]="Minus",m[m.Plus=9]="Plus",m[m.LS=10]="LS",m[m.RS=11]="RS",m[m.DPadUp=12]="DPadUp",m[m.DPadDown=13]="DPadDown",m[m.DPadLeft=14]="DPadLeft",m[m.DPadRight=15]="DPadRight",m[m.Home=16]="Home",m[m.Capture=17]="Capture",m[m.LStickXAxis=18]="LStickXAxis",m[m.LStickYAxis=19]="LStickYAxis",m[m.RStickXAxis=20]="RStickXAxis",m[m.RStickYAxis=21]="RStickYAxis"},6692:function(e,t,i){i.d(t,{p:function(){return s}});var r=i(6702);class s{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new r.y$,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}},4949:function(e,t,i){i.d(t,{U:function(){return _}});var r=i(485),s=i(6702),n=i(3184);class a{static CreateDeviceEvent(e,t,i,s,n,a,o){switch(e){case r.Yi.Keyboard:return this._CreateKeyboardEvent(i,s,n,a);case r.Yi.Mouse:if(i===r.Fz.MouseWheelX||i===r.Fz.MouseWheelY||i===r.Fz.MouseWheelZ)return this._CreateWheelEvent(e,t,i,s,n,a);case r.Yi.Touch:return this._CreatePointerEvent(e,t,i,s,n,a,o);default:throw`Unable to generate event for device ${r.Yi[e]}`}}static _CreatePointerEvent(e,t,i,s,n,a,o){let l;let h=this._CreateMouseEvent(e,t,i,s,n,a);return e===r.Yi.Mouse?(h.deviceType=r.Yi.Mouse,h.pointerId=1,h.pointerType="mouse"):(h.deviceType=r.Yi.Touch,h.pointerId=null!=o?o:t,h.pointerType="touch"),l=0+n.pollInput(e,t,r.Fz.LeftClick)+2*n.pollInput(e,t,r.Fz.RightClick)+4*n.pollInput(e,t,r.Fz.MiddleClick),h.buttons=l,i===r.Fz.Move?h.type="pointermove":i>=r.Fz.LeftClick&&i<=r.Fz.RightClick&&(h.type=1===s?"pointerdown":"pointerup",h.button=i-2),h}static _CreateWheelEvent(e,t,i,s,a,o){let l=this._CreateMouseEvent(e,t,i,s,a,o);switch(l.pointerId=1,l.type="wheel",l.deltaMode=n.G.DOM_DELTA_PIXEL,l.deltaX=0,l.deltaY=0,l.deltaZ=0,i){case r.Fz.MouseWheelX:l.deltaX=s;break;case r.Fz.MouseWheelY:l.deltaY=s;break;case r.Fz.MouseWheelZ:l.deltaZ=s}return l}static _CreateMouseEvent(e,t,i,s,n,a){let o=this._CreateEvent(a),l=n.pollInput(e,t,r.Fz.Horizontal),h=n.pollInput(e,t,r.Fz.Vertical);return a?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-a.getBoundingClientRect().x,o.offsetY=o.movementY-a.getBoundingClientRect().y):(o.movementX=n.pollInput(e,t,r.FP.DeltaHorizontal),o.movementY=n.pollInput(e,t,r.FP.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,n),o.clientX=l,o.clientY=h,o.x=l,o.y=h,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){let n=this._CreateEvent(s);return this._CheckNonCharacterKeys(n,i),n.deviceType=r.Yi.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=1===t?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n}static _CheckNonCharacterKeys(e,t){let i=t.isDeviceAvailable(r.Yi.Keyboard),s=i&&1===t.pollInput(r.Yi.Keyboard,0,18),n=i&&1===t.pollInput(r.Yi.Keyboard,0,17),a=i&&(1===t.pollInput(r.Yi.Keyboard,0,91)||1===t.pollInput(r.Yi.Keyboard,0,92)||1===t.pollInput(r.Yi.Keyboard,0,93)),o=i&&1===t.pollInput(r.Yi.Keyboard,0,16);e.altKey=s,e.ctrlKey=n,e.metaKey=a,e.shiftKey=o}static _CreateEvent(e){let t={};return t.preventDefault=()=>{},t.target=e,t}}class o{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(e,t,r,s)=>{let n=a.CreateDeviceEvent(e,t,r,s,this);i(e,t,n)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===r.Yi.Mouse||e===r.Yi.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}var l=i(216),h=i(3636);let u=Object.keys(r.Fz).length/2;class c{constructor(e,t,i,r){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=(0,l.up)()&&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=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){let s=this._inputs[e][t];if(!s)throw`Unable to find device ${r.Yi[e]}`;e>=r.Yi.DualShock&&e<=r.Yi.DualSense&&this._updateDevice(e,t,i);let n=s[i];if(void 0===n)throw`Unable to find input ${i} for device ${r.Yi[e]} in slot ${t}`;return i===r.Fz.Move&&h.w1.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){let e=this===null||void 0===this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(let e of this._inputs)if(e)for(let t in e){let i=+t,r=e[i];if(r)for(let e=0;e<r.length;e++)r[e]=0}}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=-1!==this._elementToAttachTo.tabIndex?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}}_disableEvents(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){let e=navigator.getGamepads();for(let t of e)t&&this._addGamePad(t)}"function"==typeof matchMedia&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(r.Yi.Mouse,0,0,0)}_addGamePad(e){let t=this._getGamepadDeviceType(e.id),i=e.index;this._gamepads=this._gamepads||Array(e.index+1),this._registerDevice(t,i,e.buttons.length+e.axes.length),this._gamepads[i]=t}_addPointerDevice(e,t,i,r){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,u);let s=this._inputs[e][t];s[0]=i,s[1]=r}_registerDevice(e,t,i){if(void 0===t)throw`Unable to register device ${r.Yi[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){let r=Array(i);r.fill(0),this._inputs[e][t]=r,this._onDeviceConnected(e,t)}}_unregisterDevice(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))}_handleKeyActions(){this._keyboardDownEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.Yi.Keyboard,0,255));let t=this._inputs[r.Yi.Keyboard][0];t&&(t[e.keyCode]=1,e.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&!this._metaKeys.includes(e.keyCode)&&this._metaKeys.push(e.keyCode),this._onInputChanged(r.Yi.Keyboard,0,e))},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.Yi.Keyboard,0,255));let t=this._inputs[r.Yi.Keyboard][0];if(t){if(t[e.keyCode]=0,e.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(let e of this._metaKeys){let i=a.CreateDeviceEvent(r.Yi.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(r.Yi.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(r.Yi.Keyboard,0,e)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){let e=this._inputs[r.Yi.Keyboard][0];for(let t=0;t<e.length;t++)if(0!==e[t]){e[t]=0;let i=a.CreateDeviceEvent(r.Yi.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(r.Yi.Keyboard,0,i)}this._usingMacOS&&this._metaKeys.splice(0,this._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)}_handlePointerActions(){this._maxTouchPoints=(0,l.up)()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=Array(this._maxTouchPoints));for(let e=0;e<this._maxTouchPoints;e++)this._activeTouchIds[e]=-1;this._pointerMoveEvent=e=>{let t=this._getPointerType(e),i=t===r.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===r.Yi.Touch&&-1===i){let r=this._activeTouchIds.indexOf(-1);if(r>=0)i=r,this._activeTouchIds[r]=e.pointerId,this._onDeviceConnected(t,i);else{h.w1.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);let s=this._inputs[t][i];s&&(e.inputIndex=r.Fz.Move,s[r.Fz.Horizontal]=e.clientX,s[r.Fz.Vertical]=e.clientY,t===r.Yi.Touch&&0===s[r.Fz.LeftClick]&&(s[r.Fz.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,e),this._usingSafari||-1===e.button||(e.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,e)))},this._pointerDownEvent=e=>{let t=this._getPointerType(e),i=t===r.Yi.Mouse?0:e.pointerId;if(t===r.Yi.Touch){let t=this._activeTouchIds.indexOf(-1);if(t>=0)i=t,this._activeTouchIds[t]=e.pointerId;else{h.w1.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===r.Yi.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);let s=this._inputs[t][i];if(s){let n=s[r.Fz.Horizontal],a=s[r.Fz.Vertical];if(t===r.Yi.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[r.Fz.Horizontal]=e.clientX,s[r.Fz.Vertical]=e.clientY,s[e.button+2]=1,e.inputIndex=e.button+2,this._onInputChanged(t,i,e),(n!==e.clientX||a!==e.clientY)&&(e.inputIndex=r.Fz.Move,this._onInputChanged(t,i,e))}},this._pointerUpEvent=e=>{var t,i,s,n,a;let o=this._getPointerType(e),l=o===r.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(o===r.Yi.Touch){if(-1===l)return;this._activeTouchIds[l]=-1}let h=null===(t=this._inputs[o])||void 0===t?void 0:t[l];if(h&&0!==h[e.button+2]){let t=h[r.Fz.Horizontal],u=h[r.Fz.Vertical];h[r.Fz.Horizontal]=e.clientX,h[r.Fz.Vertical]=e.clientY,h[e.button+2]=0,void 0===e.pointerId&&(e.pointerId=this._mouseId),(t!==e.clientX||u!==e.clientY)&&(e.inputIndex=r.Fz.Move,this._onInputChanged(o,l,e)),e.inputIndex=e.button+2,o===r.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===(a=(n=this._elementToAttachTo).hasPointerCapture)||void 0===a?void 0:a.call(n,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(o,l,e),o===r.Yi.Touch&&this._onDeviceDisconnected(o,l)}},this._pointerCancelEvent=e=>{var t,i,s,n;if("mouse"===e.pointerType){let e=this._inputs[r.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=r.Fz.LeftClick;t<=r.Fz.BrowserForward;t++)if(1===e[t]){e[t]=0;let i=a.CreateDeviceEvent(r.Yi.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(r.Yi.Mouse,0,i)}}else{let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;(null===(n=(s=this._elementToAttachTo).hasPointerCapture)||void 0===n?void 0:n.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[r.Yi.Touch][t][r.Fz.LeftClick]=0;let i=a.CreateDeviceEvent(r.Yi.Touch,t,r.Fz.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(r.Yi.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(r.Yi.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1,t=function(){};try{let i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{var e,t,i,s,n;if(this.isDeviceAvailable(r.Yi.Mouse)){let i=this._inputs[r.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=r.Fz.LeftClick;e<=r.Fz.BrowserForward;e++)if(1===i[e]){i[e]=0;let t=a.CreateDeviceEvent(r.Yi.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(r.Yi.Mouse,0,t)}}if(this.isDeviceAvailable(r.Yi.Touch)){let e=this._inputs[r.Yi.Touch];for(let t=0;t<this._activeTouchIds.length;t++){let o=this._activeTouchIds[t];if((null===(s=(i=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(i,o))&&this._elementToAttachTo.releasePointerCapture(o),-1!==o&&(null===(n=e[t])||void 0===n?void 0:n[r.Fz.LeftClick])===1){e[t][r.Fz.LeftClick]=0;let i=a.CreateDeviceEvent(r.Yi.Touch,t,r.Fz.LeftClick,0,this,this._elementToAttachTo,o);this._onInputChanged(r.Yi.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(r.Yi.Touch,t)}}}},this._pointerWheelEvent=e=>{let t=r.Yi.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,u));let i=this._inputs[t][0];i&&(i[r.Fz.MouseWheelX]=e.deltaX||0,i[r.Fz.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[r.Fz.MouseWheelZ]=e.deltaZ||0,void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[r.Fz.MouseWheelX]&&(e.inputIndex=r.Fz.MouseWheelX,this._onInputChanged(t,0,e)),0!==i[r.Fz.MouseWheelY]&&(e.inputIndex=r.Fz.MouseWheelY,this._onInputChanged(t,0,e)),0!==i[r.Fz.MouseWheelZ]&&(e.inputIndex=r.Fz.MouseWheelZ,this._onInputChanged(t,0,e)))},this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(r.Yi.Mouse)){let e=this._inputs[r.Yi.Mouse][0];e[r.Fz.MouseWheelX]=0,e[r.Fz.MouseWheelY]=0,e[r.Fz.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){let 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){let r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){let s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return -1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?r.Yi.DualSense:r.Yi.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?r.Yi.Xbox:-1!==e.indexOf("057e")?r.Yi.Switch:r.Yi.Generic}_getPointerType(e){let t=r.Yi.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=r.Yi.Touch),t}}var d=i(6692);class p{constructor(e){this._registeredManagers=[],this._refCount=0,this.registerManager=e=>{for(let t=0;t<this._devices.length;t++){let i=this._devices[t];for(let r in i){let i=+r;e._addDevice(new d.p(this._deviceInputSystem,t,i))}}this._registeredManagers.push(e)},this.unregisterManager=e=>{let t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};let t=Object.keys(r.Yi).length/2;this._devices=Array(t);let i=(e,t)=>{for(let i of(this._devices[e]||(this._devices[e]=[]),this._devices[e][t]||(this._devices[e][t]=t),this._registeredManagers)){let r=new d.p(this._deviceInputSystem,e,t);i._addDevice(r)}},s=(e,t)=>{var i;for(let r of((null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t],this._registeredManagers))r._removeDevice(e,t)},n=(e,t,i)=>{if(i)for(let r of this._registeredManagers)r._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new o(i,s,n):this._deviceInputSystem=new c(e,i,s,n)}dispose(){this._deviceInputSystem.dispose()}}class _{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){let t=Object.keys(r.Yi).length/2;this._devices=Array(t),this._firstDevice=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(let t of this._devices)if(t)for(let 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]=[]),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,r;let s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(r=this._devices[e])||void 0===r?void 0:r[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;null===(s=null===(r=this._devices[e])||void 0===r?void 0:r[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case r.Yi.Keyboard:case r.Yi.Mouse:this._firstDevice[e]=0;break;case r.Yi.Touch:case r.Yi.DualSense:case r.Yi.DualShock:case r.Yi.Xbox:case r.Yi.Switch:case r.Yi.Generic:{delete this._firstDevice[e];let t=this._devices[e];if(t){for(let i=0;i<t.length;i++)if(t[i]){this._firstDevice[e]=i;break}}}}}}},1851:function(e,t,i){var r=i(4826);r.B.prototype.setAlphaConstants=function(e,t,i,r){this._alphaState.setAlphaBlendConstants(e,t,i,r)},r.B.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e){if(!t){let t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e},r.B.prototype.getAlphaMode=function(){return this._alphaMode},r.B.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},r.B.prototype.getAlphaEquation=function(){return this._alphaEquation}},8066:function(e,t,i){var r=i(4826);r.B.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let r;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},r.B.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0);let s=t.byteLength||t.length;void 0===r||r>=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,r):new Uint8Array(t.buffer,t.byteOffset+i,r),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()}},1300:function(e,t,i){i.d(t,{A:function(){return s}});var r=i(4826);function s(e,t,i=!1,r){switch(e){case 3:{let e=(ArrayBuffer,new Int8Array(t));return r&&e.set(new Int8Array(r)),e}case 0:{let e=(ArrayBuffer,new Uint8Array(t));return r&&e.set(new Uint8Array(r)),e}case 4:{let e=new Int16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Int16Array(r)),e}case 5:case 8:case 9:case 10:case 2:{let e=new Uint16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Uint16Array(r)),e}case 6:{let e=new Int32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Int32Array(r)),e}case 7:case 11:case 12:case 13:case 14:case 15:{let e=new Uint32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Uint32Array(r)),e}case 1:{let e=new Float32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Float32Array(r)),e}}let s=(ArrayBuffer,new Uint8Array(t));return r&&s.set(new Uint8Array(r)),s}r.B.prototype._readTexturePixelsSync=function(e,t,i,r=-1,n=0,a=null,o=!0,l=!1,h=0,u=0){var c,d;let p=this._gl;if(!p)throw Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){let e=p.createFramebuffer();if(!e)throw Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}p.bindFramebuffer(p.FRAMEBUFFER,this._dummyFramebuffer),r>-1?p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_CUBE_MAP_POSITIVE_X+r,null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,n):p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,null===(d=e._hardwareTexture)||void 0===d?void 0:d.underlyingResource,n);let _=void 0!==e.type?this._getWebGLTextureType(e.type):p.UNSIGNED_BYTE;return l?a||(a=s(e.type,4*t*i)):_===p.UNSIGNED_BYTE?(a||(a=new Uint8Array(4*t*i)),_=p.UNSIGNED_BYTE):(a||(a=new Float32Array(4*t*i)),_=p.FLOAT),o&&this.flushFramebuffer(),p.readPixels(h,u,t,i,p.RGBA,_,a),p.bindFramebuffer(p.FRAMEBUFFER,this._currentFramebuffer),a},r.B.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,r,s,n,a,o,l,h))}},54:function(e,t,i){var r=i(4826),s=i(4696);r.B.prototype.createUniformBuffer=function(e){let t=this._gl.createBuffer();if(!t)throw Error("Unable to create uniform buffer");let 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},r.B.prototype.createDynamicUniformBuffer=function(e){let t=this._gl.createBuffer();if(!t)throw Error("Unable to create dynamic uniform buffer");let 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},r.B.prototype.updateUniformBuffer=function(e,t,i,r){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this.bindUniformBuffer(null)},r.B.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},r.B.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},r.B.prototype.bindUniformBlock=function(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);4294967295!==s&&this._gl.uniformBlockBinding(r,s,i)}},76:function(e,t,i){i.d(t,{L:function(){return S}});class r{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,r,s,n,a,o,l;let h="";if(this.line){let u=this.line,c=t.processor;if(c){c.lineProcessor&&(u=c.lineProcessor(u,t.isFragment,t.processingContext));let h=null!==(r=null===(i=t.processor)||void 0===i?void 0:i.attributeKeywordName)&&void 0!==r?r:"attribute",d=t.isFragment&&(null===(s=t.processor)||void 0===s?void 0:s.varyingFragmentKeywordName)?null===(n=t.processor)||void 0===n?void 0:n.varyingFragmentKeywordName:!t.isFragment&&(null===(a=t.processor)||void 0===a?void 0:a.varyingVertexKeywordName)?null===(o=t.processor)||void 0===o?void 0:o.varyingVertexKeywordName:"varying";!t.isFragment&&c.attributeProcessor&&this.line.startsWith(h)?u=c.attributeProcessor(this.line,e,t.processingContext):c.varyingProcessor&&((null===(l=c.varyingCheck)||void 0===l?void 0:l.call(c,this.line,t.isFragment))||!c.varyingCheck&&this.line.startsWith(d))?u=c.varyingProcessor(this.line,t.isFragment,e,t.processingContext):c.uniformProcessor&&c.uniformRegexp&&c.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&c.uniformBufferRegexp&&c.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):c.textureProcessor&&c.textureRegexp&&c.textureRegexp.test(this.line)?u=c.textureProcessor(this.line,t.isFragment,e,t.processingContext):(c.uniformProcessor||c.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?c.uniformProcessor&&(u=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&(u=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,c.endOfUniformBufferProcessor&&(u=c.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}h+=u+"\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<this._lines.length-1}set lines(e){for(let t of(this._lines.length=0,e)){if(!t||"\r"===t)continue;if("#"===t[0]){this._lines.push(t);continue}let e=t.trim();if(!e)continue;if(e.startsWith("//")){this._lines.push(t);continue}let i=e.indexOf(";");if(-1===i)this._lines.push(e);else if(i===e.length-1)e.length>1&&this._lines.push(e);else{let e=t.split(";");for(let t=0;t<e.length;t++){let i=e[t];i&&(i=i.trim())&&this._lines.push(i+(t!==e.length-1?";":""))}}}}}class n extends r{process(e,t){for(let i=0;i<this.children.length;i++){let r=this.children[i];if(r.isValid(e))return r.process(e,t)}return""}}class a extends r{isValid(e){return this.testExpression.isTrue(e)}}class o{isTrue(e){return!0}static postfixToInfix(e){let t=[];for(let i of e)if(void 0===o._OperatorPriority[i])t.push(i);else{let e=t[t.length-1],r=t[t.length-2];t.length-=2,t.push(`(${r}${i}${e})`)}return t[t.length-1]}static infixToPostfix(e){let t=o._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!e.includes("&&")&&!e.includes("||")&&!e.includes(")")&&!e.includes("("))return[e];let i=[],r=-1,s=()=>{""!==(u=u.trim())&&(i.push(u),u="")},n=e=>{r<o._Stack.length-1&&(o._Stack[++r]=e)},a=()=>o._Stack[r],l=()=>-1===r?"!!INVALID EXPRESSION!!":o._Stack[r--],h=0,u="";for(;h<e.length;){let t=e.charAt(h),c=h<e.length-1?e.substr(h,2):"";if("("===t)u="",n(t);else if(")"===t){for(s();-1!==r&&"("!==a();)i.push(l());l()}else if(o._OperatorPriority[c]>1){for(s();-1!==r&&o._OperatorPriority[a()]>=o._OperatorPriority[c];)i.push(l());n(c),h++}else u+=t;h++}for(s();-1!==r;)"("===a()?l():i.push(l());return o._InfixToPostfixCache.size>=o.InfixToPostfixCacheLimitSize&&o.ClearCache(),o._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){let e=Array.from(o._InfixToPostfixCache.entries()).sort((e,t)=>e[1].accessTime-t[1].accessTime);for(let t=0;t<o.InfixToPostfixCacheCleanupSize;t++)o._InfixToPostfixCache.delete(e[t][0])}}o.InfixToPostfixCacheLimitSize=5e4,o.InfixToPostfixCacheCleanupSize=25e3,o._InfixToPostfixCache=new Map,o._OperatorPriority={")":0,"(":1,"||":2,"&&":3},o._Stack=["","","","","","","","","","","","","","","","","","","",""];class l extends o{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=void 0!==e[this.define];return this.not&&(t=!t),t}}class h extends o{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class u extends o{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class c extends o{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}isTrue(e){let t=e[this.define];void 0===t&&(t=this.define);let i=!1,r=parseInt(t),s=parseInt(this.testValue);switch(this.operand){case">":i=r>s;break;case"<":i=r<s;break;case"<=":i=r<=s;break;case">=":i=r>=s;break;case"==":i=r===s;break;case"!=":i=r!==s}return i}}var d=i(4620),p=i(3587);let _=/defined\s*?\((.+?)\)/g,f=/defined\s*?\[(.+?)\]/g,m=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,g=/__decl__/,v=/light\{X\}.(\w*)/g,T=/\{X\}/g,x=[];class S{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,r){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));let s=this._ProcessShaderConversion(e,t,r);i(s,e)})}static PreProcess(e,t,i,r){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));let s=this._ApplyPreProcessing(e,t,r);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;let r=t.shouldUseHighPrecisionShader;return -1===e.indexOf("precision highp float")?e=r?"precision highp float;\n"+e:"precision mediump float;\n"+e:r||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){let t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new l(t[1].trim(),"!"===e[0]);let i="",r=0;for(i of["==","!=",">=","<=","<",">"])if((r=e.indexOf(i))>-1)break;if(-1===r)return new l(e);let s=e.substring(0,r).trim(),n=e.substring(r+i.length).trim();return new c(s,i,n)}static _BuildSubExpression(e){e=e.replace(_,"defined[$1]");let t=o.infixToPostfix(e),i=[];for(let e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],r=i[i.length-2];i.length-=2;let s="&&"==e?new u:new h;"string"==typeof t&&(t=t.replace(f,"defined($1)")),"string"==typeof r&&(r=r.replace(f,"defined($1)")),s.leftOperand="string"==typeof r?this._ExtractOperation(r):r,s.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(s)}let r=i[i.length-1];return"string"==typeof r&&(r=r.replace(f,"defined($1)")),"string"==typeof r?this._ExtractOperation(r):r}static _BuildExpression(e,t){let i=new a,r=e.substring(0,t),s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),"#ifdef"===r?i.testExpression=new l(s):"#ifndef"===r?i.testExpression=new l(s,!0):i.testExpression=this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let s=e.currentLine;for(;this._MoveCursor(e,i);){s=e.currentLine;let n=s.substring(0,5).toLowerCase();if("#else"===n){let i=new r;t.children.push(i),this._MoveCursor(e,i);return}if("#elif"===n){let e=this._BuildExpression(s,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;let i=e.currentLine;if(i.indexOf("#")>=0){let r=S._MoveCursorRegex.exec(i);if(r&&r.length){let s=r[0];switch(s){case"#ifdef":{let r=new n;t.children.push(r);let s=this._BuildExpression(i,6);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{let r=new n;t.children.push(r);let s=this._BuildExpression(i,7);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#if":{let r=new n,s=this._BuildExpression(i,3);t.children.push(r),r.children.push(s),this._MoveCursorWithinIf(e,r,s)}}continue}}let s=new r;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){let e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){let n=new r,a=new s;return a.lineIndex=-1,a.lines=e.split("\n"),this._MoveCursor(a,n),n.process(t,i)}static _PreparePreProcessors(e,t){var i;let r=e.defines,s={};for(let e of r){let t=e.replace("#define","").replace(";","").trim(),i=t.split(" ");s[i[0]]=i.length>1?i[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 r=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===p.x.GLSL&&-1!==r.indexOf("#version 3")&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;let s=t.defines,n=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,s,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,n,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ApplyPreProcessing(e,t,i){var r,s;let n=e,a=t.defines,o=this._PreparePreProcessors(t,i);return(null===(r=t.processor)||void 0===r?void 0:r.preProcessor)&&(n=t.processor.preProcessor(n,a,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,o,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(n=t.processor.postProcessor(n,a,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ProcessIncludes(e,t,i){let r;for(x.length=0;null!==(r=m.exec(e));)x.push(r);let s=String(e),n=[e],a=!1;for(let e of x){let r=e[1];if(-1!==r.indexOf("__decl__")&&(r=r.replace(g,""),t.supportsUniformBuffers&&(r=r.replace("Vertex","Ubo").replace("Fragment","Ubo")),r+="Declaration"),t.includesShadersStore[r]){let i=t.includesShadersStore[r];if(e[2]){let t=e[3].split(",");for(let e=0;e<t.length;e+=2){let r=RegExp(t[e],"g"),s=t[e+1];i=i.replace(r,s)}}if(e[4]){let r=e[5];if(-1!==r.indexOf("..")){let e=r.split(".."),s=parseInt(e[0]),n=parseInt(e[1]),a=i.slice(0);i="",isNaN(n)&&(n=t.indexParameters[e[1]]);for(let e=s;e<n;e++)t.supportsUniformBuffers||(a=a.replace(v,(e,t)=>t+"{X}")),i+=a.replace(T,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(v,(e,t)=>t+"{X}")),i=i.replace(T,r)}let s=[];for(let t of n){let r=t.split(e[0]);for(let e=0;e<r.length-1;e++)s.push(r[e]),s.push(i);s.push(r[r.length-1])}n=s,a=a||i.indexOf("#include<")>=0||i.indexOf("#include <")>=0}else{let e=t.shadersRepository+"ShadersInclude/"+r+".fx";S._FileToolsLoadFile(e,e=>{t.includesShadersStore[r]=e,this._ProcessIncludes(n.join(""),t,i)});return}}x.length=0,s=n.join(""),a?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,r,s,n){throw(0,d.S)("FileTools")}}S._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/},6983:function(e,t,i){i.d(t,{C:function(){return n}});var r=i(3587);let s=/(flat\s)?\s*varying\s*.*/;class n{constructor(){this.shaderLanguage=r.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){let r=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){let t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(r||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else{let i=-1!==t.indexOf("#define MULTIVIEW");if(i)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}return e}}},9123:function(e,t,i){i.d(t,{B:function(){return r}});class r{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw 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(let e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},5342:function(e,t,i){i.d(t,{y:function(){return r}});class r{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this.engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);let u=this.engine.getUniforms(this,i);for(u.forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l<s.length;l++){let t=e.getUniform(s[l]);null==t&&(s.splice(l,1),l--)}for(let e of(s.forEach((e,t)=>{n[e]=t}),h.getAttributes(this,a)))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||2!==r.length)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,r,s],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),n[3]!==s&&(n[3]=s,a=!0),a}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setUInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&!this.engine.setMatrices(this._uniforms[e],t.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){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&!this.engine.setFloat2(this._uniforms[e],t.x,t.y)&&(this._valueCache[e]=null)}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setFloat2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&!this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)&&(this._valueCache[e]=null)}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setFloat3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setFloat4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&!this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)&&(this._valueCache[e]=null)}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(this._valueCache[e]=null)}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&!this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)&&(this._valueCache[e]=null)}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}},5310:function(e,t,i){i.d(t,{f:function(){return s}});var r=i(3587);class s{constructor(){this.shaderLanguage=r.x.GLSL}postProcessor(e,t,i,r,s){return s.getCaps().drawBuffersExtension||(e=e.replace(/#extension.+GL_EXT_draw_buffers.+(enable|require)/g,"")),e}}},3700:function(e,t,i){i.d(t,{D:function(){return _}});var r=i(6702),s=i(6452),n=i(216),a=i(3914),o=i(4620),l=i(4826),h=i(2241),u=i(6339),c=i(4696),d=i(7694),p=i(9123);i(1851),i(1300),i(8066);class _ extends l.B{static get NpmPackage(){return l.B.NpmPackage}static get Version(){return l.B.Version}static get Instances(){return a.l.Instances}static get LastCreatedEngine(){return a.l.LastCreatedEngine}static get LastCreatedScene(){return a.l.LastCreatedScene}_createImageBitmapFromSource(e,t){let i=new Promise((i,r)=>{let s=new Image;s.onload=()=>{s.decode().then(()=>{this.createImageBitmap(s,t).then(e=>{i(e)})})},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=e});return i}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){let r=this.createCanvas(t,i),s=r.getContext("2d");if(!s)throw Error("Unable to get 2d context for resizeImageBitmap");s.drawImage(e,0,0);let n=s.getImageData(0,0,t,i).data;return n}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i<_.Instances.length;i++){let r=_.Instances[i];for(let i=0;i<r.scenes.length;i++)r.scenes[i].markAllMaterialsAsDirty(e,t)}}static DefaultLoadingScreenFactory(e){throw(0,o.S)("LoadingScreen")}get _supportsHardwareTextureRescaling(){return!!_._RescalePostProcessFactory}get performanceMonitor(){return this._performanceMonitor}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}getInputElement(){return this._renderingCanvas}constructor(e,t,i,s=!1){if(super(e,t,i,s),this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.scenes=[],this._virtualScenes=[],this.onNewSceneAddedObservable=new r.y$,this.postProcesses=[],this.isPointerLock=!1,this.onResizeObservable=new r.y$,this.onCanvasBlurObservable=new r.y$,this.onCanvasFocusObservable=new r.y$,this.onCanvasPointerOutObservable=new r.y$,this.onBeginFrameObservable=new r.y$,this.customAnimationFrameRequester=null,this.onEndFrameObservable=new r.y$,this.onBeforeShaderCompilationObservable=new r.y$,this.onAfterShaderCompilationObservable=new r.y$,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this._fps=60,this._deltaTime=0,this._drawCalls=new u.z,this.canvasTabIndex=1,this.disablePerformanceMonitorInBackground=!1,this._performanceMonitor=new h.A,this._compatibilityMode=!0,this.currentRenderPassId=0,this._renderPassNames=["main"],_.Instances.push(this),!e)return;this._features.supportRenderPasses=!0,i=this._creationOptions,e.getContext&&(this._sharedInit(e),this._connectVREvents()),this._prepareVRComponent(),i.autoEnableWebVR&&this.initWebVR()}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),this._onCanvasFocus=()=>{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)};let 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(),!_.audioEngine&&this._creationOptions.audioEngine&&_.AudioEngineFactory&&(_.audioEngine=_.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),(0,n.n5)()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&_._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!==_.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){let 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){let 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,r){let s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){let s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){let e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}initWebVR(){throw(0,o.S)("WebVRCamera")}_prepareVRComponent(){}_connectVREvents(e,t){}_submitVRFrame(){}disableVR(){}isVRPresenting(){return!1}_requestVRFrame(){}_loadFileAsync(e,t,i){return new Promise((r,s)=>{this._loadFile(e,e=>{r(e)},void 0,t,i,(e,t)=>{s(t)})})}getVertexShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))}setTextureFromPostProcess(e,t,i){var r;let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(r=null==s?void 0:s.texture)&&void 0!==r?r:null,i)}setTextureFromPostProcessOutput(e,t,i){var r,s;this._bindTexture(e,null!==(s=null===(r=null==t?void 0:t._outputTexture)||void 0===r?void 0:r.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(let e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(let e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++){let t=this._activeRenderLoops[e];t()}}_cancelFrame(){if(this._renderingQueueLaunched&&this.customAnimationFrameRequester){this._renderingQueueLaunched=!1;let{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}else super._cancelFrame()}_renderLoop(){if(!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0?this.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&&_._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&_._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&_._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){_._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||!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e<this.scenes.length;e++){let t=this.scenes[e];for(let e=0;e<t.cameras.length;e++){let i=t.cameras[e];i._currentRenderId=0}}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0}_deletePipelineContext(e){e&&e.program&&e.transformFeedback&&(this.deleteTransformFeedback(e.transformFeedback),e.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,r,s,n=null){s=s||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);let a=super.createShaderProgram(e,t,i,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),a}_createShaderProgram(e,t,i,r,s=null){let n=r.createProgram();if(e.program=n,!n)throw Error("Unable to create program");if(r.attachShader(n,t),r.attachShader(n,i),this.webGLVersion>1&&s){let t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,s),e.transformFeedback=t}return r.linkProgram(n),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach(t=>{t.postProcesses.forEach(t=>{t._outputTexture===e&&(t._outputTexture=null)}),t.cameras.forEach(t=>{t._postProcesses.forEach(t=>{t&&t._outputTexture===e&&(t._outputTexture=null)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){let t=++_._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t<this.scenes.length;++t){let i=this.scenes[t];for(let t=0;t<i.meshes.length;++t){let r=i.meshes[t];if(r.subMeshes)for(let t=0;t<r.subMeshes.length;++t){let i=r.subMeshes[t];i._removeDrawWrapper(e)}}}}_rescaleTexture(e,t,i,r,s){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);let n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&_._RescalePostProcessFactory&&(this._rescalePostProcess=_._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled(()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=i;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,r,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),s&&s()}))}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){let r=new p.B(e,this._gl),n=new s.l(this,s.S.Unknown,!0);return n._hardwareTexture=r,n.isReady=!0,n.useMipMaps=t,this.updateTextureSamplingMode(i,n),n}_uploadImageToTexture(e,t,i=0,r=0){let s=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,r,o,a,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion){d.Y.Error("WebGL 1 does not support texture comparison.");return}let 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){let t=this._gl.createBuffer();if(!t)throw Error("Unable to create instance buffer");let i=new c.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){let r=this._gl;return new Promise((s,n)=>{let a=()=>{let o=r.clientWaitSync(e,t,0);if(o==r.WAIT_FAILED){n();return}if(o==r.TIMEOUT_EXPIRED){setTimeout(a,i);return}s()};a()})}_readPixelsAsync(e,t,i,r,s,n,a){if(this._webGLVersion<2)throw Error("_readPixelsAsync only work on WebGL2+");let o=this._gl,l=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,i,r,s,n,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);let h=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(o.flush(),this._clientWaitAsync(h,0,10).then(()=>(o.deleteSync(h),o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(l),a))):null}dispose(){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===a.l.Instances.length&&_.audioEngine&&(_.audioEngine.dispose(),_.audioEngine=null),this.disableVR();let 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,n.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();let t=a.l.Instances.indexOf(this);t>=0&&a.l.Instances.splice(t,1),_.Instances.length||a.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,n.CG)())return;let e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!(0,n.CG)())return;let e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=_.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){let t=e.requestPointerLock();t instanceof Promise?t.then(()=>{e.focus()}).catch(()=>{}):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){let t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){let e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){let t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);let i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";let r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);let s=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:s,height:n,descent:n-s}}}_.ALPHA_DISABLE=0,_.ALPHA_ADD=1,_.ALPHA_COMBINE=2,_.ALPHA_SUBTRACT=3,_.ALPHA_MULTIPLY=4,_.ALPHA_MAXIMIZED=5,_.ALPHA_ONEONE=6,_.ALPHA_PREMULTIPLIED=7,_.ALPHA_PREMULTIPLIED_PORTERDUFF=8,_.ALPHA_INTERPOLATE=9,_.ALPHA_SCREENMODE=10,_.DELAYLOADSTATE_NONE=0,_.DELAYLOADSTATE_LOADED=1,_.DELAYLOADSTATE_LOADING=2,_.DELAYLOADSTATE_NOTLOADED=4,_.NEVER=512,_.ALWAYS=519,_.LESS=513,_.EQUAL=514,_.LEQUAL=515,_.GREATER=516,_.GEQUAL=518,_.NOTEQUAL=517,_.KEEP=7680,_.REPLACE=7681,_.INCR=7682,_.DECR=7683,_.INVERT=5386,_.INCR_WRAP=34055,_.DECR_WRAP=34056,_.TEXTURE_CLAMP_ADDRESSMODE=0,_.TEXTURE_WRAP_ADDRESSMODE=1,_.TEXTURE_MIRROR_ADDRESSMODE=2,_.TEXTUREFORMAT_ALPHA=0,_.TEXTUREFORMAT_LUMINANCE=1,_.TEXTUREFORMAT_LUMINANCE_ALPHA=2,_.TEXTUREFORMAT_RGB=4,_.TEXTUREFORMAT_RGBA=5,_.TEXTUREFORMAT_RED=6,_.TEXTUREFORMAT_R=6,_.TEXTUREFORMAT_RG=7,_.TEXTUREFORMAT_RED_INTEGER=8,_.TEXTUREFORMAT_R_INTEGER=8,_.TEXTUREFORMAT_RG_INTEGER=9,_.TEXTUREFORMAT_RGB_INTEGER=10,_.TEXTUREFORMAT_RGBA_INTEGER=11,_.TEXTURETYPE_UNSIGNED_BYTE=0,_.TEXTURETYPE_UNSIGNED_INT=0,_.TEXTURETYPE_FLOAT=1,_.TEXTURETYPE_HALF_FLOAT=2,_.TEXTURETYPE_BYTE=3,_.TEXTURETYPE_SHORT=4,_.TEXTURETYPE_UNSIGNED_SHORT=5,_.TEXTURETYPE_INT=6,_.TEXTURETYPE_UNSIGNED_INTEGER=7,_.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,_.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,_.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,_.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,_.TEXTURETYPE_UNSIGNED_INT_24_8=12,_.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,_.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,_.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,_.TEXTURE_NEAREST_SAMPLINGMODE=1,_.TEXTURE_BILINEAR_SAMPLINGMODE=2,_.TEXTURE_TRILINEAR_SAMPLINGMODE=3,_.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,_.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,_.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,_.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,_.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,_.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,_.TEXTURE_NEAREST_LINEAR=7,_.TEXTURE_NEAREST_NEAREST=1,_.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,_.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,_.TEXTURE_LINEAR_LINEAR=2,_.TEXTURE_LINEAR_NEAREST=12,_.TEXTURE_EXPLICIT_MODE=0,_.TEXTURE_SPHERICAL_MODE=1,_.TEXTURE_PLANAR_MODE=2,_.TEXTURE_CUBIC_MODE=3,_.TEXTURE_PROJECTION_MODE=4,_.TEXTURE_SKYBOX_MODE=5,_.TEXTURE_INVCUBIC_MODE=6,_.TEXTURE_EQUIRECTANGULAR_MODE=7,_.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,_.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,_.SCALEMODE_FLOOR=1,_.SCALEMODE_NEAREST=2,_.SCALEMODE_CEILING=3,_._RescalePostProcessFactory=null,_._RenderPassIdCounter=0},3914:function(e,t,i){i.d(t,{l:function(){return s}});var r=i(6702);class s{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}s.Instances=[],s.OnEnginesDisposedObservable=new r.y$,s._LastCreatedScene=null,s.UseFallbackTexture=!0,s.FallbackTexture=""},4499:function(e,t,i){i.d(t,{Z:function(){return r}});class r{static SetMatrixPrecision(e){if(r.MatrixTrackPrecisionChange=!1,e&&!r.MatrixUse64Bits&&r.MatrixTrackedMatrices)for(let e=0;e<r.MatrixTrackedMatrices.length;++e){let t=r.MatrixTrackedMatrices[e],i=t._m;t._m=Array(16);for(let e=0;e<16;++e)t._m[e]=i[e]}r.MatrixUse64Bits=e,r.MatrixCurrentType=r.MatrixUse64Bits?Array:Float32Array,r.MatrixTrackedMatrices=null}}r.MatrixUse64Bits=!1,r.MatrixTrackPrecisionChange=!0,r.MatrixCurrentType=Float32Array,r.MatrixTrackedMatrices=[]},7005:function(e,t,i){i.d(t,{v:function(){return s}});var r=i(3587);class s{static GetShadersRepository(e=r.x.GLSL){return e===r.x.GLSL?s.ShadersRepository:s.ShadersRepositoryWGSL}static GetShadersStore(e=r.x.GLSL){return e===r.x.GLSL?s.ShadersStore:s.ShadersStoreWGSL}static GetIncludesShadersStore(e=r.x.GLSL){return e===r.x.GLSL?s.IncludesShadersStore:s.IncludesShadersStoreWGSL}}s.ShadersRepository="src/Shaders/",s.ShadersStore={},s.IncludesShadersStore={},s.ShadersRepositoryWGSL="src/ShadersWGSL/",s.ShadersStoreWGSL={},s.IncludesShadersStoreWGSL={}},3184:function(e,t,i){var r,s;i.d(t,{G:function(){return n}}),(s=r||(r={}))[s.PointerMove=0]="PointerMove",s[s.PointerDown=1]="PointerDown",s[s.PointerUp=2]="PointerUp";class n{}n.DOM_DELTA_PIXEL=0,n.DOM_DELTA_LINE=1,n.DOM_DELTA_PAGE=2},3968:function(e,t,i){i.d(t,{NG:function(){return s},OG:function(){return r},WZ:function(){return n}});class r{}r.KEYDOWN=1,r.KEYUP=2;class s{constructor(e,t){this.type=e,this.event=t}}class n extends s{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}},7792:function(e,t,i){i.d(t,{FV:function(){return a},R5:function(){return o},kD:function(){return s}});var r=i(1823);class s{}s.POINTERDOWN=1,s.POINTERUP=2,s.POINTERMOVE=4,s.POINTERWHEEL=8,s.POINTERPICK=16,s.POINTERTAP=32,s.POINTERDOUBLETAP=64;class n{constructor(e,t){this.type=e,this.event=t}}class a extends n{constructor(e,t,i,s){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new r.FM(i,s)}}class o extends n{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,r=null){super(e,t),this._pickInfo=i,this._inputManager=r}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}},9334:function(e,t,i){i.d(t,{M:function(){return r}});class r{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}},8033:function(e,t,i){i.d(t,{$:function(){return p}});var r=i(7792),s=i(2511),n=i(9657),a=i(1823),o=i(9326),l=i(3968),h=i(485),u=i(4949),c=i(3914);class d{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}}class p{constructor(e){if(this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new a.FM(0,0),this._previousStartingPointerPosition=new a.FM(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||c.l.LastCreatedScene,!this._scene)return}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new a.FM(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){let t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){let i;let s=this._scene,n=s.getEngine(),a=n.getInputElement();for(let i of(a&&(a.tabIndex=n.canvasTabIndex,s.doNotHandleCursors||(a.style.cursor=s.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,s),s._pointerMoveStage)){e=e||this._pickMove(t);let r=null!=e&&!!e.pickedMesh;e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,r,a)}let o=t.inputIndex>=h.Fz.MouseWheelX&&t.inputIndex<=h.Fz.MouseWheelZ?r.kD.POINTERWHEEL:r.kD.POINTERMOVE;s.onPointerMove&&(e=e||this._pickMove(t),s.onPointerMove(t,e,o)),e?(i=new r.R5(o,t,e),this._setRayOnPointerInfo(e,t)):(i=new r.R5(o,t,null,this),this._movePointerInfo=i),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(i,o)}_setRayOnPointerInfo(e,t){let i=this._scene;e&&i._pickingAvailable&&!e.ray&&(e.ray=i.createPickingRay(t.offsetX,t.offsetY,a.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){let s=this._scene,n=new r.FV(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(n.originalPickingInfo=e,n.ray=e.ray,e.originMesh&&(n.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(n,i),!!n.skipOnPointerObservable}_pickMove(e){let 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){let r=i.getEngine(),s=r.getInputElement();if(null==e?void 0:e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){let e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){let i=new PointerEvent("pointermove",t);i.inputIndex=h.Fz.Move,this._checkPrePointerObservable(e,i,r.kD.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){let i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,r.kD.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){let i;let s=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;let i=e.pickedMesh._getActionManagerForTrigger();if(i){if(i.hasPickTriggers)switch(i.processTrigger(5,o.V.CreateNew(e.pickedMesh,t,e)),t.button){case 0:i.processTrigger(2,o.V.CreateNew(e.pickedMesh,t,e));break;case 1:i.processTrigger(4,o.V.CreateNew(e.pickedMesh,t,e));break;case 2:i.processTrigger(3,o.V.CreateNew(e.pickedMesh,t,e))}i.hasSpecificTrigger(8)&&window.setTimeout(()=>{let e=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh,!1,s.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&i&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>p.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,i.processTrigger(8,o.V.CreateNew(e.pickedMesh,t)))},p.LongPressDelay)}}else for(let i of s._pointerDownStage)e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let n=r.kD.POINTERDOWN;e?(s.onPointerDown&&s.onPointerDown(t,e,n),i=new r.R5(n,t,e),this._setRayOnPointerInfo(e,t)):i=new r.R5(n,t,null,this),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(i,n)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){let s=new PointerEvent("pointerup",t);s.inputIndex=h.Fz.Move;let n=new d;i?n.doubleClick=!0:n.singleClick=!0,this._checkPrePointerObservable(e,s,r.kD.POINTERUP)||this._processPointerUp(e,s,n)}_processPointerUp(e,t,i){let 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)){let i=r.kD.POINTERPICK,n=new r.R5(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,i)}let n=e.pickedMesh._getActionManagerForTrigger();if(n&&!i.ignore){n.processTrigger(7,o.V.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&n.processTrigger(1,o.V.CreateNew(e.pickedMesh,t,e));let r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,o.V.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(let r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){let e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,o.V.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){let n=new r.R5(r.kD.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,r.kD.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,r.kD.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=r.kD.POINTERTAP:i.doubleClick&&(n=r.kD.POINTERDOUBLETAP),n){let i=new r.R5(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(i,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,a=null){let c=this._scene,_=c.getEngine();a||(a=_.getInputElement()),this._alreadyAttached&&this.detachControl(),a&&(this._alreadyAttachedTo=a),this._deviceSourceManager=new u.U(_),this._initActionManager=e=>{if(!this._meshPickProceed){let t=!c.skipPointerUpPicking&&(0!==c._registeredActions||this._checkForPicking()||c.onPointerUp)?c.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,c.pointerUpPredicate,c.pointerUpFastCheck,c.cameraToUseForPointers):null;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])){let t=this._delayedClicks[e].evt,i=r.kD.POINTERTAP,s=new r.R5(i,t,this._currentPickResult);c.onPointerObservable.hasObservers()&&c.onPointerObservable.hasSpecificMask(i)&&c.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,n)=>{var a,o;let l=new d;this._currentPickResult=null;let h=null,u=e.hasSpecificMask(r.kD.POINTERPICK)||t.hasSpecificMask(r.kD.POINTERPICK)||e.hasSpecificMask(r.kD.POINTERTAP)||t.hasSpecificMask(r.kD.POINTERTAP)||e.hasSpecificMask(r.kD.POINTERDOUBLETAP)||t.hasSpecificMask(r.kD.POINTERDOUBLETAP);!u&&s.O&&(h=this._initActionManager(h,l))&&(u=h.hasPickTriggers);let c=!1;if(u){let u=i.button;if(l.hasSwiped=this._isPointerSwiping(),!l.hasSwiped){let d=!p.ExclusiveDoubleClickMode;if(!d&&(d=!e.hasSpecificMask(r.kD.POINTERDOUBLETAP)&&!t.hasSpecificMask(r.kD.POINTERDOUBLETAP))&&!s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l))&&(d=!h.hasSpecificTrigger(6)),d)(Date.now()-this._previousStartingPointerTime>p.DoubleClickDelay||u!==this._previousButtonPressed)&&(l.singleClick=!0,n(l,this._currentPickResult),c=!0);else{let e={evt:i,clickInfo:l,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,u,l,n),p.DoubleClickDelay)};this._delayedClicks[u]=e}let _=e.hasSpecificMask(r.kD.POINTERDOUBLETAP)||t.hasSpecificMask(r.kD.POINTERDOUBLETAP);!_&&s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l))&&(_=h.hasSpecificTrigger(6)),_&&(u===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<p.DoubleClickDelay&&!this._doubleClickOccured?(l.hasSwiped||this._isPointerSwiping()?(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=u,p.ExclusiveDoubleClickMode?(this._delayedClicks[u]&&(clearTimeout(null===(o=this._delayedClicks[u])||void 0===o?void 0:o.timeoutId),this._delayedClicks[u]=null),n(l,this._previousPickResult)):n(l,this._currentPickResult)):(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,l.doubleClick=!0,l.ignore=!1,p.ExclusiveDoubleClickMode&&this._delayedClicks[u]&&(clearTimeout(null===(a=this._delayedClicks[u])||void 0===a?void 0:a.timeoutId),this._delayedClicks[u]=null),n(l,this._currentPickResult)),c=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=u))}}c||n(l,this._currentPickResult)},this._onPointerMove=e=>{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),_.isPointerLock&&_._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=h.Fz.MouseWheelX&&e.inputIndex<=h.Fz.MouseWheelZ?r.kD.POINTERWHEEL:r.kD.POINTERMOVE)||!c.cameraToUseForPointers&&!c.activeCamera)return;if(c.skipPointerMovePicking){this._processPointerMove(new n.p,e);return}c.pointerMovePredicate||(c.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||c.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0));let t=c._registeredActions>0||c.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;let i;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,p.ExclusiveDoubleClickMode){for(let i=0;i<this._delayedClicks.length;i++)if(this._delayedClicks[i]){if(e.button===i)clearTimeout(null===(t=this._delayedClicks[i])||void 0===t?void 0:t.timeoutId);else{let e=this._delayedClicks[i].clickInfo;this._doubleClickOccured=!1,e.singleClick=!0,e.ignore=!1;let t=this._delayedClicks[i].evt,s=r.kD.POINTERTAP,n=new r.R5(s,t,this._currentPickResult);c.onPointerObservable.hasObservers()&&c.onPointerObservable.hasSpecificMask(s)&&c.onPointerObservable.notifyObservers(n,s),this._delayedClicks[i]=null}}}this._updatePointerPosition(e),-1===this._swipeButtonPressed&&(this._swipeButtonPressed=e.button),c.preventDefaultOnPointerDown&&a&&(e.preventDefault(),a.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),!this._checkPrePointerObservable(null,e,r.kD.POINTERDOWN)&&(c.cameraToUseForPointers||c.activeCamera)&&(this._pointerCaptures[e.pointerId]=!0,c.pointerDownPredicate||(c.pointerDownPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0)),this._pickedDownMesh=null,i=!c.skipPointerDownPicking&&(0!==c._registeredActions||this._checkForPicking()||c.onPointerDown)?c.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,c.pointerDownPredicate,c.pointerDownFastCheck,c.cameraToUseForPointers):new n.p,this._processPointerDown(i,e))},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),c.preventDefaultOnPointerUp&&a&&(e.preventDefault(),a.focus()),this._initClickEvent(c.onPrePointerObservable,c.onPointerObservable,e,(t,i)=>{if(c.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,r.kD.POINTERUP)){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1);return}!t.hasSwiped&&(t.singleClick&&c.onPrePointerObservable.hasSpecificMask(r.kD.POINTERTAP)&&this._checkPrePointerObservable(null,e,r.kD.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&c.onPrePointerObservable.hasSpecificMask(r.kD.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,r.kD.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[e.pointerId]){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(c.cameraToUseForPointers||c.activeCamera)&&(c.pointerUpPredicate||(c.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0)),!this._meshPickProceed&&(s.O&&s.O.HasTriggers||this._checkForPicking()||c.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._onKeyDown=e=>{let t=l.OG.KEYDOWN;if(c.onPreKeyboardObservable.hasObservers()){let i=new l.WZ(t,e);if(c.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(c.onKeyboardObservable.hasObservers()){let i=new l.NG(t,e);c.onKeyboardObservable.notifyObservers(i,t)}c.actionManager&&c.actionManager.processTrigger(14,o.V.CreateNewFromScene(c,e))},this._onKeyUp=e=>{let t=l.OG.KEYUP;if(c.onPreKeyboardObservable.hasObservers()){let i=new l.WZ(t,e);if(c.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(c.onKeyboardObservable.hasObservers()){let i=new l.NG(t,e);c.onKeyboardObservable.notifyObservers(i,t)}c.actionManager&&c.actionManager.processTrigger(15,o.V.CreateNewFromScene(c,e))},this._deviceSourceManager.onDeviceConnectedObservable.add(r=>{r.deviceType===h.Yi.Mouse?r.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===r.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===r.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))}):r.deviceType===h.Yi.Touch?r.onInputChangedObservable.add(s=>{s.inputIndex===h.Fz.LeftClick&&(t&&1===r.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===r.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===h.Fz.Move&&this._onPointerMove(s)}):r.deviceType===h.Yi.Keyboard&&r.onInputChangedObservable.add(e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,r){let s;if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;let n=this._meshUnderPointerId[t];n&&(s=n._getActionManagerForTrigger(10))&&s.processTrigger(10,o.V.CreateNew(n,r,{pointerId:t})),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,(s=e._getActionManagerForTrigger(9))&&s.processTrigger(9,o.V.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){for(let t in this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null),this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}p.DragMovementThreshold=10,p.LongPressDelay=500,p.DoubleClickDelay=300,p.ExclusiveDoubleClickMode=!1},8463:function(e,t,i){i.d(t,{m:function(){return r}});class r{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}r.FALLOFF_DEFAULT=0,r.FALLOFF_PHYSICAL=1,r.FALLOFF_GLTF=2,r.FALLOFF_STANDARD=3,r.LIGHTMAP_DEFAULT=0,r.LIGHTMAP_SPECULAR=1,r.LIGHTMAP_SHADOWSONLY=2,r.INTENSITYMODE_AUTOMATIC=0,r.INTENSITYMODE_LUMINOUSPOWER=1,r.INTENSITYMODE_LUMINOUSINTENSITY=2,r.INTENSITYMODE_ILLUMINANCE=3,r.INTENSITYMODE_LUMINANCE=4,r.LIGHTTYPEID_POINTLIGHT=0,r.LIGHTTYPEID_DIRECTIONALLIGHT=1,r.LIGHTTYPEID_SPOTLIGHT=2,r.LIGHTTYPEID_HEMISPHERICLIGHT=3},199:function(e,t,i){i.d(t,{Z:function(){return r}});class r{static get ForceFullSceneLoadingForIncremental(){return r._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){r._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return r._ShowLoadingScreen}static set ShowLoadingScreen(e){r._ShowLoadingScreen=e}static get loggingLevel(){return r._LoggingLevel}static set loggingLevel(e){r._LoggingLevel=e}static get CleanBoneMatrixWeights(){return r._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){r._CleanBoneMatrixWeights=e}}r._ForceFullSceneLoadingForIncremental=!1,r._ShowLoadingScreen=!0,r._CleanBoneMatrixWeights=!1,r._LoggingLevel=0},6452:function(e,t,i){i.d(t,{S:function(){return s},l:function(){return o}});var r,s,n=i(6702),a=i(7955);(r=s||(s={}))[r.Unknown=0]="Unknown",r[r.Url=1]="Url",r[r.Temp=2]="Temp",r[r.Raw=3]="Raw",r[r.Dynamic=4]="Dynamic",r[r.RenderTarget=5]="RenderTarget",r[r.MultiRenderTarget=6]="MultiRenderTarget",r[r.Cube=7]="Cube",r[r.CubeRaw=8]="CubeRaw",r[r.CubePrefiltered=9]="CubePrefiltered",r[r.Raw3D=10]="Raw3D",r[r.Raw2DArray=11]="Raw2DArray",r[r.DepthStencil=12]="DepthStencil",r[r.CubeRawRGBD=13]="CubeRawRGBD",r[r.Depth=14]="Depth";class o extends a.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 n.y$,this.onErrorObservable=new n.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=s.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;let t;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){let e=this.onRebuildCallback(this),t=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};e.isAsync?e.proxy.then(t):t(e.proxy);return}switch(this.source){case s.Temp:break;case s.Url: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);return;case s.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))._swapAndDie(this,!1),this.isReady=!0;break;case s.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))._swapAndDie(this,!1),this.isReady=!0;break;case s.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))._swapAndDie(this,!1),this.isReady=!0;break;case s.Dynamic:(t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode))._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case s.Cube: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);return;case s.CubeRaw:(t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this,!1),this.isReady=!0;break;case s.CubeRawRGBD:return;case s.CubePrefiltered:(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))._sphericalPolynomial=this._sphericalPolynomial;return}}_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);let r=this._engine.getLoadedTexturesCache(),s=r.indexOf(this);-1!==s&&r.splice(s,1),-1===(s=r.indexOf(e))&&r.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}}o._Counter=0},7955:function(e,t,i){i.d(t,{a:function(){return r}});class r{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,r=1,s=2,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=s,this._comparisonFunction=n,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}},7138:function(e,t,i){function r(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function s(e,t,i){var r,s,n,a,o,l;let h=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),u=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),c=!!(null!==(n=e.clipPlane3)&&void 0!==n?n:t.clipPlane3),d=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),p=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),_=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);h&&i.push("#define CLIPPLANE"),u&&i.push("#define CLIPPLANE2"),c&&i.push("#define CLIPPLANE3"),d&&i.push("#define CLIPPLANE4"),p&&i.push("#define CLIPPLANE5"),_&&i.push("#define CLIPPLANE6")}function n(e,t,i){var r,s,n,a,o,l;let h=!1,u=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),c=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),d=!!(null!==(n=e.clipPlane3)&&void 0!==n?n:t.clipPlane3),p=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),_=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==u&&(i.CLIPPLANE=u,h=!0),i.CLIPPLANE2!==c&&(i.CLIPPLANE2=c,h=!0),i.CLIPPLANE3!==d&&(i.CLIPPLANE3=d,h=!0),i.CLIPPLANE4!==p&&(i.CLIPPLANE4=p,h=!0),i.CLIPPLANE5!==_&&(i.CLIPPLANE5=_,h=!0),i.CLIPPLANE6!==f&&(i.CLIPPLANE6=f,h=!0),h}function a(e,t,i){var r,s,n,a,l,h;let u=null!==(r=t.clipPlane)&&void 0!==r?r:i.clipPlane;o(e,"vClipPlane",u),o(e,"vClipPlane2",u=null!==(s=t.clipPlane2)&&void 0!==s?s:i.clipPlane2),o(e,"vClipPlane3",u=null!==(n=t.clipPlane3)&&void 0!==n?n:i.clipPlane3),o(e,"vClipPlane4",u=null!==(a=t.clipPlane4)&&void 0!==a?a:i.clipPlane4),o(e,"vClipPlane5",u=null!==(l=t.clipPlane5)&&void 0!==l?l:i.clipPlane5),o(e,"vClipPlane6",u=null!==(h=t.clipPlane6)&&void 0!==h?h:i.clipPlane6)}function o(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}i.d(t,{AN:function(){return n},an:function(){return a},lK:function(){return s},qx:function(){return r}})},2117:function(e,t,i){i.d(t,{U:function(){return a}});var r=i(6851),s=i(6816),n=i(6762);class a{constructor(){this._dirty=!0,this._tempColor=new n.HE(0,0,0,0),this._globalCurve=new n.HE(0,0,0,0),this._highlightsCurve=new n.HE(0,0,0,0),this._midtonesCurve=new n.HE(0,0,0,0),this._shadowsCurve=new n.HE(0,0,0,0),this._positiveCurve=new n.HE(0,0,0,0),this._negativeCurve=new n.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",r="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}static PrepareUniforms(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}_getColorGradingDataToRef(e,t,i,r,s){null!=e&&(e=a._Clamp(e,0,360),t=a._Clamp(t,-100,100),i=a._Clamp(i,-100,100),r=a._Clamp(r,-100,100),t=.5*a._ApplyColorGradingSliderNonlinear(t),r=a._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),a._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){let t=Math.abs(e/=100);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100}static _FromHSBToRef(e,t,i,r){let s=a._Clamp(e,0,360),n=a._Clamp(t/100,0,1),o=a._Clamp(i/100,0,1);if(0===n)r.r=o,r.g=o,r.b=o;else{s/=60;let e=Math.floor(s),t=s-e,i=o*(1-n),a=o*(1-n*t),l=o*(1-n*(1-t));switch(e){case 0:r.r=o,r.g=l,r.b=i;break;case 1:r.r=a,r.g=o,r.b=i;break;case 2:r.r=i,r.g=o,r.b=l;break;case 3:r.r=i,r.g=a,r.b=o;break;case 4:r.r=l,r.g=i,r.b=o;break;default:r.r=o,r.g=i,r.b=a}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return s.p4.Clone(()=>new a,this)}serialize(){return s.p4.Serialize(this)}static Parse(e){return s.p4.Parse(()=>new a,e,null,null)}}(0,r.gn)([(0,s.qC)()],a.prototype,"_globalHue",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_globalDensity",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_globalSaturation",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_globalExposure",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_highlightsHue",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_highlightsDensity",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_highlightsSaturation",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_highlightsExposure",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_midtonesHue",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_midtonesDensity",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_midtonesSaturation",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_midtonesExposure",void 0),s.p4._ColorCurvesParser=a.Parse},1470:function(e,t,i){i.d(t,{q:function(){return r}});class r{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 r;this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(r=this.drawContext)||void 0===r||r.reset())}dispose(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()}}},4213:function(e,t,i){i.d(t,{Q:function(){return h}});var r=i(6702),s=i(216),n=i(7694),a=i(76),o=i(7005),l=i(3587);class h{static get ShadersRepository(){return o.v.ShadersRepository}static set ShadersRepository(e){o.v.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new r.y$),this._onBindObservable}constructor(e,t,i,n=null,u,c=null,d=null,p=null,_=null,f,m="",g=l.x.GLSL){var v,T,x;let S,E,C;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new r.y$,this.onErrorObservable=new r.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 b=null;if(t.attributes){if(this._engine=i,this._attributesNames=t.attributes,this._uniformsNames=t.uniformsNames.concat(t.samplers),this._samplerList=t.samplers.slice(),this.defines=t.defines,this.onError=t.onError,this.onCompiled=t.onCompiled,this._fallbacks=t.fallbacks,this._indexParameters=t.indexParameters,this._transformFeedbackVaryings=t.transformFeedbackVaryings||null,this._multiTarget=!!t.multiTarget,this._shaderLanguage=null!==(v=t.shaderLanguage)&&void 0!==v?v:l.x.GLSL,t.uniformBuffersNames){this._uniformBuffersNamesList=t.uniformBuffersNames.slice();for(let e=0;e<t.uniformBuffersNames.length;e++)this._uniformBuffersNames[t.uniformBuffersNames[e]]=e}b=null!==(T=t.processFinalCode)&&void 0!==T?T:null,C=null!==(x=t.processCodeAfterIncludes)&&void 0!==x?x:void 0}else this._engine=u,this.defines=null==c?"":c,this._uniformsNames=i.concat(n),this._samplerList=n?n.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=g,this.onError=_,this.onCompiled=p,this._indexParameters=f,this._fallbacks=d;this._attributeLocationByName={},this.uniqueId=h._UniqueIdSeed++;let y=(0,s.CG)()?this._engine.getHostDocument():null;e.vertexSource?S="source:"+e.vertexSource:e.vertexElement?(S=y?y.getElementById(e.vertexElement):null)||(S=e.vertexElement):S=e.vertex||e,e.fragmentSource?E="source:"+e.fragmentSource:e.fragmentElement?(E=y?y.getElementById(e.fragmentElement):null)||(E=e.fragmentElement):E=e.fragment||e,this._processingContext=this._engine._getShaderProcessingContext(this._shaderLanguage);let A={defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:o.v.GetShadersRepository(this._shaderLanguage),includesShadersStore:o.v.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:C},R=[void 0,void 0],P=()=>{if(R[0]&&R[1]){A.isFragment=!0;let[t,i]=R;a.L.Process(i,A,(i,r)=>{this._fragmentSourceCodeBeforeMigration=r,b&&(i=b("fragment",i));let s=a.L.Finalize(t,i,A);A=null,this._useFinalCode(s.vertexCode,s.fragmentCode,e)},this._engine)}};this._loadShader(S,"Vertex","",e=>{a.L.Initialize(A),a.L.Process(e,A,(t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,b&&(t=b("vertex",t)),R[0]=t,P()},this._engine)}),this._loadShader(E,"Fragment","Pixel",e=>{this._rawFragmentSourceCode=e,R[1]=e,P()})}_useFinalCode(e,t,i){if(i){let r=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:"+r+"\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){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let n;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){let t=(0,s.v)(e);r(t);return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){let t=window.atob(e.substr(7));r(t);return}let a=o.v.GetShadersStore(this._shaderLanguage);if(a[e+t+"Shader"]){r(a[e+t+"Shader"]);return}if(i&&a[e+i+"Shader"]){r(a[e+i+"Shader"]);return}n="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:o.v.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",r)}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,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{r&&r(t)},this.onCompiled=()=>{let e=this.getEngine().scenes;if(e)for(let t=0;t<e.length;t++)e[t].markAllMaterialsAsDirty(63);this._pipelineContext._handlesSpectorRebuildCallback(i)},this._fallbacks=null,this._prepareEffect()}_prepareEffect(){let e=this._attributesNames,t=this.defines,i=this._pipelineContext;this._isReady=!1;try{let r=this._engine;this._pipelineContext=r.createPipelineContext(this._processingContext),this._pipelineContext._name=this._key;let s=this._rebuildProgram.bind(this);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?r._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,s,null,this._transformFeedbackVaryings,this._key):r._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,s,t,this._transformFeedbackVaryings,this._key),r._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{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<e.length;t++){let i=e[t];this._attributeLocationByName[i]=this._attributes[t]}r.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh(),i&&this.getEngine()._deletePipelineContext(i)}),this._pipelineContext.isAsync&&this._checkIsReady(i)}catch(e){this._processCompilationErrors(e,i)}}_getShaderCodeAndErrorLine(e,t,i){let r=null;if(t&&e){let s=t.match(i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/);if(s&&2===s.length){let t=parseInt(s[1]),n=e.split("\n",-1);n.length>=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i,r,s;this._compilationError=e.message;let a=this._attributesNames,o=this._fallbacks;if(n.Y.Error("Unable to compile effect:"),n.Y.Error("Uniforms: "+this._uniformsNames.map(function(e){return" "+e})),n.Y.Error("Attributes: "+a.map(function(e){return" "+e})),n.Y.Error("Defines:\n"+this.defines),h.LogShaderCodeOnCompilationError){let e=null,t=null,a=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([a,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),a&&(n.Y.Error("Vertex code:"),n.Y.Error(a))),(null===(r=this._pipelineContext)||void 0===r?void 0:r._getFragmentShaderCode())&&([a,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),a&&(n.Y.Error("Fragment code:"),n.Y.Error(a))),e&&n.Y.Error(e),t&&n.Y.Error(t)}n.Y.Error("Error: "+this._compilationError);let l=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,l()),o?(this._pipelineContext=null,o.hasMoreFallbacks?(this._allFallbacksProcessed=!1,n.Y.Error("Trying next fallback."),this.defines=o.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){let i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){let r=this._samplerList.indexOf(e);for(let e=1;e<t.length;e++){let t=i+(e-1).toString();this._samplerList.splice(r+e,0,t)}let s=0;for(let e of this._samplerList)this._samplers[e]=s,s+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}setTextureFromPostProcess(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)}setTextureFromPostProcessOutput(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)}bindUniformBuffer(e,t){let i=this._uniformBuffersNames[t];void 0===i||h._BaseCache[i]===e&&this._engine._features.useUBOBindingCache||(h._BaseCache[i]=e,this._engine.bindUniformBufferBase(e,i,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setInt3(e,t,i,r){return this._pipelineContext.setInt3(e,t,i,r),this}setInt4(e,t,i,r,s){return this._pipelineContext.setInt4(e,t,i,r,s),this}setIntArray(e,t){return this._pipelineContext.setIntArray(e,t),this}setIntArray2(e,t){return this._pipelineContext.setIntArray2(e,t),this}setIntArray3(e,t){return this._pipelineContext.setIntArray3(e,t),this}setIntArray4(e,t){return this._pipelineContext.setIntArray4(e,t),this}setUInt(e,t){return this._pipelineContext.setInt(e,t),this}setUInt2(e,t,i){return this._pipelineContext.setInt2(e,t,i),this}setUInt3(e,t,i,r){return this._pipelineContext.setInt3(e,t,i,r),this}setUInt4(e,t,i,r,s){return this._pipelineContext.setInt4(e,t,i,r,s),this}setUIntArray(e,t){return this._pipelineContext.setUIntArray(e,t),this}setUIntArray2(e,t){return this._pipelineContext.setUIntArray2(e,t),this}setUIntArray3(e,t){return this._pipelineContext.setUIntArray3(e,t),this}setUIntArray4(e,t){return this._pipelineContext.setUIntArray4(e,t),this}setFloatArray(e,t){return this._pipelineContext.setArray(e,t),this}setFloatArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setFloatArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setFloatArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setArray(e,t){return this._pipelineContext.setArray(e,t),this}setArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setMatrices(e,t){return this._pipelineContext.setMatrices(e,t),this}setMatrix(e,t){return this._pipelineContext.setMatrix(e,t),this}setMatrix3x3(e,t){return this._pipelineContext.setMatrix3x3(e,t),this}setMatrix2x2(e,t){return this._pipelineContext.setMatrix2x2(e,t),this}setFloat(e,t){return this._pipelineContext.setFloat(e,t),this}setBool(e,t){return this._pipelineContext.setInt(e,t?1:0),this}setVector2(e,t){return this._pipelineContext.setVector2(e,t),this}setFloat2(e,t,i){return this._pipelineContext.setFloat2(e,t,i),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,i,r){return this._pipelineContext.setFloat3(e,t,i,r),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,i,r,s){return this._pipelineContext.setFloat4(e,t,i,r,s),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,i){return this._pipelineContext.setColor4(e,t,i),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseEffect(this),this._isDisposed=!0}static RegisterShader(e,t,i,r=l.x.GLSL){t&&(o.v.GetShadersStore(r)[`${e}PixelShader`]=t),i&&(o.v.GetShadersStore(r)[`${e}VertexShader`]=i)}static ResetCache(){h._BaseCache={}}}h.LogShaderCodeOnCompilationError=!0,h._UniqueIdSeed=0,h._BaseCache={},h.ShadersStore=o.v.ShadersStore,h.IncludesShadersStore=o.v.IncludesShadersStore},9290:function(e,t,i){i.d(t,{$:function(){return c},b:function(){return u}});var r=i(6851),s=i(6816),n=i(6702),a=i(3636),o=i(6762),l=i(9241),h=i(2117);class u extends l.H{constructor(){super(),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.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class c{constructor(){this.colorCurves=new h.U,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=c.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new o.HE(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=c.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new n.y$}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}static PrepareUniforms(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&h.U.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===c._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType===c.TONEMAPPING_ACES)?e.TONEMAPPING_ACES=!0:e.TONEMAPPING_ACES=!1,e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&h.U.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){let i=1/e.getEngine().getRenderWidth(),r=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){let s=null!=t?t:r/i,n=Math.tan(.5*this.vignetteCameraFov),o=n*s,l=Math.sqrt(o*n);o=a.w1.Mix(o,l,this.vignetteStretch),n=a.w1.Mix(n,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*this.vignetteCenterX,-n*this.vignetteCenterY);let h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);let t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return s.p4.Clone(()=>new c,this)}serialize(){return s.p4.Serialize(this)}static Parse(e){let t=s.p4.Parse(()=>new c,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}}c.TONEMAPPING_STANDARD=0,c.TONEMAPPING_ACES=1,c._VIGNETTEMODE_MULTIPLY=0,c._VIGNETTEMODE_OPAQUE=1,(0,r.gn)([(0,s.N$)()],c.prototype,"colorCurves",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_colorCurvesEnabled",void 0),(0,r.gn)([(0,s.oU)("colorGradingTexture")],c.prototype,"_colorGradingTexture",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_colorGradingEnabled",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_colorGradingWithGreenDepth",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_colorGradingBGR",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_exposure",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_toneMappingEnabled",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_toneMappingType",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_contrast",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"vignetteStretch",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"vignetteCenterX",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"vignetteCenterY",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"vignetteWeight",void 0),(0,r.gn)([(0,s.XX)()],c.prototype,"vignetteColor",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"vignetteCameraFov",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_vignetteBlendMode",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_vignetteEnabled",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_ditheringEnabled",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_ditheringIntensity",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_skipFinalColorClamp",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_applyByPostProcess",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_isEnabled",void 0),s.p4._ImageProcessingConfigurationParser=c.Parse},1870:function(e,t,i){i.d(t,{F:function(){return g}});var r=i(6851),s=i(6816),n=i(3636),a=i(6702),o=i(3914),l=i(1813),h=i(1378),u=i(7694),c=i(2321),d=i(8461),p=i(1470);class _{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,r.gn)([(0,s.qC)()],_.prototype,"func",null),(0,r.gn)([(0,s.qC)()],_.prototype,"funcRef",null),(0,r.gn)([(0,s.qC)()],_.prototype,"funcMask",null),(0,r.gn)([(0,s.qC)()],_.prototype,"opStencilFail",null),(0,r.gn)([(0,s.qC)()],_.prototype,"opDepthFail",null),(0,r.gn)([(0,s.qC)()],_.prototype,"opStencilDepthPass",null),(0,r.gn)([(0,s.qC)()],_.prototype,"mask",null),(0,r.gn)([(0,s.qC)()],_.prototype,"enabled",null);var f=i(6438),m=i(3511);class g{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;let 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 a.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 a.y$),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new a.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 a.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 _,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=()=>void 0,this._callbackPluginEventIsReadyForSubMesh=()=>void 0,this._callbackPluginEventPrepareDefines=()=>void 0,this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>void 0,this._callbackPluginEventHardBindForSubMesh=()=>void 0,this._callbackPluginEventBindForSubMesh=()=>void 0,this._callbackPluginEventHasRenderTargetTextures=()=>void 0,this._callbackPluginEventFillRenderTargetTextures=()=>void 0,this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;let r=t||o.l.LastCreatedScene;if(!r)return;this._scene=r,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||n.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){let t="Name: "+this.name;return t}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){let r=t.materialDefines;return!!r&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}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){let t=this.getScene().meshes;for(let i of t)if(i.subMeshes)for(let 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){let i=this._scene.getEngine(),r=null==t?this.sideOrientation:t,s=r===g.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){let e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(m.S.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){let r=i.effect;r&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1)}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,d.G.BindSceneUniformBuffer(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){let e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){let e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){let e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){if(this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction){let e=this._scene.getEngine();e.setDepthFunction(this._cachedDepthFunctionState)}if(this.disableDepthWrite){let e=this._scene.getEngine();e.setDepthWrite(this._cachedDepthWriteState)}if(this.disableColorWrite){let e=this._scene.getEngine();e.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){let i={};if(this._serializePlugins(i),g._parsePlugins(i,e,this._scene,t),this.pluginManager)for(let t of this.pluginManager._plugins){let i=e.pluginManager.getPlugin(t.name);t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){let e=[];for(let t in this.meshMap){let i=this.meshMap[t];i&&e.push(i)}return e}{let e=this._scene.meshes;return e.filter(e=>e.material===this)}}forceCompilation(e,t,i,r){let s=Object.assign({clipPlane:!1,useInstances:!1},i),n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;let o=()=>{if(!this._scene||!this._scene.getEngine())return;let i=n.clipPlane;if(s.clipPlane&&(n.clipPlane=new c.J(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){let 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()?n=t.effect.getCompilationError():(i=!1,setTimeout(o,16)))}i&&(this.allowShaderHotSwapping=a,n&&r&&r(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);s.clipPlane&&(n.clipPlane=i)};o()}forceCompilationAsync(e,t){return new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,e=>{r(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(){let e=this.getScene().meshes;for(let t of e)if(t.subMeshes)for(let e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let t=this.getScene().meshes;for(let i of t)if(i.subMeshes){for(let t of i.subMeshes)if(t.getMaterial(!1)===this)for(let 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;let 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!==f.a.BackwardCompatible){this.checkReadyOnlyOnce=!0;let e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){let r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(m.S.Disposed,this._eventInfo),this._parentContainer){let e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i){if(this.meshMap)for(let t in this.meshMap){let i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{let t=r.meshes;for(let 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){let i=e.geometry;if(this._storeEffectOnSubMeshes)for(let r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose();else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){let 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(let 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 u.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";let r=n.w1.Instantiate(e.customType),s=r.Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _parsePlugins(e,t,i,r){var s;if(e.plugins)for(let a in e.plugins){let o=e.plugins[a],l=null===(s=t.pluginManager)||void 0===s?void 0:s.getPlugin(o.name);if(!l){let e=n.w1.Instantiate("BABYLON."+a);e&&(l=new e(t))}null==l||l.parse(o,i,r)}}}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 a.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(let t of g._DirtyCallbackArray)t(e)},(0,r.gn)([(0,s.qC)()],g.prototype,"id",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"uniqueId",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"name",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"metadata",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"checkReadyOnEveryCall",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"checkReadyOnlyOnce",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"state",void 0),(0,r.gn)([(0,s.qC)("alpha")],g.prototype,"_alpha",void 0),(0,r.gn)([(0,s.qC)("backFaceCulling")],g.prototype,"_backFaceCulling",void 0),(0,r.gn)([(0,s.qC)("cullBackFaces")],g.prototype,"_cullBackFaces",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"sideOrientation",void 0),(0,r.gn)([(0,s.qC)("alphaMode")],g.prototype,"_alphaMode",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"_needDepthPrePass",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"disableDepthWrite",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"disableColorWrite",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"forceDepthWrite",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"depthFunction",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"separateCullingPass",void 0),(0,r.gn)([(0,s.qC)("fogEnabled")],g.prototype,"_fogEnabled",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"pointSize",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"zOffset",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"zOffsetUnits",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"pointsCloud",null),(0,r.gn)([(0,s.qC)()],g.prototype,"fillMode",null),(0,r.gn)([(0,s.qC)()],g.prototype,"transparencyMode",null)},9241:function(e,t,i){i.d(t,{H:function(){return r}});class r{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(let 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(){for(let e of(this._keys.length=0,Object.keys(this)))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(let e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;t<this._keys.length;t++){let i=this._keys[t];if(this[i]!==e[i])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){let i=this._keys[t];e[i]=this[i]}}reset(){this._keys.forEach(e=>this._setDefaultValue(e))}_setDefaultValue(e){var t,i,r,s,n;let a=null!==(r=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==r?r:typeof this[e],o=null===(n=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===n?void 0:n.default;switch(a){case"number":this[e]=null!=o?o:0;break;case"string":this[e]=null!=o?o:"";break;default:this[e]=null!=o&&o}}toString(){let e="";for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=this[i],s=typeof r;switch(s){case"number":case"string":e+="#define "+i+" "+r+"\n";break;default:r&&(e+="#define "+i+"\n")}}return e}}},8461:function(e,t,i){i.d(t,{G:function(){return c}});var r=i(7694),s=i(7419),n=i(6438),a=i(3914),o=i(7620),l=i(8463),h=i(6762),u=i(7138);class c{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}static BindTextureMatrix(e,t,i){let r=e.getTextureMatrix();t.updateMatrix(i+"Matrix",r)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==n.x.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,r,s,n,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=r,a.FOG=s&&this.GetFogState(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=o)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){let r=t.CAMERA_ORTHOGRAPHIC?1:0,n=t.CAMERA_PERSPECTIVE?1:0,a=e.activeCamera.mode===s.V.ORTHOGRAPHIC_CAMERA?1:0,o=e.activeCamera.mode===s.V.PERSPECTIVE_CAMERA?1:0;(r^a||n^o)&&(t.CAMERA_ORTHOGRAPHIC=1===a,t.CAMERA_PERSPECTIVE=1===o,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,r,s,n=null,a=!1){let o=c.PrepareDefinesForCamera(e,r);!1!==n&&(o=(0,u.AN)(i,e,r)),!t.getColorWrite()!==r.DEPTHPREPASS&&(r.DEPTHPREPASS=!r.DEPTHPREPASS,o=!0),r.INSTANCES!==s&&(r.INSTANCES=s,o=!0),r.THIN_INSTANCES!==a&&(r.THIN_INSTANCES=a,o=!0),o&&r.markAsUnprocessed()}static PrepareDefinesForBones(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;let i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;let r=e.getScene().prePassRenderer;if(r&&r.enabled){let i=-1===r.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(e,t){let i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,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){let i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!i&&!!i.isEnabled}static PrepareDefinesForAttributes(e,t,i,r,s=!1,n=!0,a=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(o.o.NormalKind),t._needNormals&&e.isVerticesDataPresent(o.o.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){let i=e.useVertexColors&&e.isVerticesDataPresent(o.o.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent(o.o.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),r&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),a&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){let i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){let r=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(r!==t.ORDER_INDEPENDENT_TRANSPARENCY||s!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){let r=t.PREPASS;if(!t._arePrePassDirty)return;let 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;i<s.length;i++){let r=e.prePassRenderer.getIndex(s[i].type);-1!==r?(t[s[i].define]=!0,t[s[i].index]=r):t[s[i].define]=!1}}else{t.PREPASS=!1;for(let e=0;e<s.length;e++)t[s[e].define]=!1}t.PREPASS!=r&&(t.markAsUnprocessed(),t.markAsImageProcessingDirty())}static PrepareDefinesForLight(e,t,i,r,s,n,a){var o;switch(a.needNormals=!0,void 0===s["LIGHT"+r]&&(a.needRebuild=!0),s["LIGHT"+r]=!0,s["SPOTLIGHT"+r]=!1,s["HEMILIGHT"+r]=!1,s["POINTLIGHT"+r]=!1,s["DIRLIGHT"+r]=!1,i.prepareLightSpecificDefines(s,r),s["LIGHT_FALLOFF_PHYSICAL"+r]=!1,s["LIGHT_FALLOFF_GLTF"+r]=!1,s["LIGHT_FALLOFF_STANDARD"+r]=!1,i.falloffType){case l.m.FALLOFF_GLTF:s["LIGHT_FALLOFF_GLTF"+r]=!0;break;case l.m.FALLOFF_PHYSICAL:s["LIGHT_FALLOFF_PHYSICAL"+r]=!0;break;case l.m.FALLOFF_STANDARD:s["LIGHT_FALLOFF_STANDARD"+r]=!0}if(n&&!i.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),s["SHADOW"+r]=!1,s["SHADOWCSM"+r]=!1,s["SHADOWCSMDEBUG"+r]=!1,s["SHADOWCSMNUM_CASCADES"+r]=!1,s["SHADOWCSMUSESHADOWMAXZ"+r]=!1,s["SHADOWCSMNOBLEND"+r]=!1,s["SHADOWCSM_RIGHTHANDED"+r]=!1,s["SHADOWPCF"+r]=!1,s["SHADOWPCSS"+r]=!1,s["SHADOWPOISSON"+r]=!1,s["SHADOWESM"+r]=!1,s["SHADOWCLOSEESM"+r]=!1,s["SHADOWCUBE"+r]=!1,s["SHADOWLOWQUALITY"+r]=!1,s["SHADOWMEDIUMQUALITY"+r]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&i.shadowEnabled){let t=null!==(o=i.getShadowGenerator(e.activeCamera))&&void 0!==o?o:i.getShadowGenerator();if(t){let e=t.getShadowMap();e&&e.renderList&&e.renderList.length>0&&(a.shadowEnabled=!0,t.prepareDefines(s,r))}}i.lightmapMode!=l.m.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+r]=!0,s["LIGHTMAPNOSPECULAR"+r]=i.lightmapMode==l.m.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+r]=!1,s["LIGHTMAPNOSPECULAR"+r]=!1)}static PrepareDefinesForLights(e,t,i,r,s=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let a=0,o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n){for(let n of t.lightSources)if(this.PrepareDefinesForLight(e,t,n,a,i,r,o),++a===s)break}i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e<s;e++)void 0!==i["LIGHT"+e]&&(i["LIGHT"+e]=!1,i["HEMILIGHT"+e]=!1,i["POINTLIGHT"+e]=!1,i["DIRLIGHT"+e]=!1,i["SPOTLIGHT"+e]=!1,i["SHADOW"+e]=!1,i["SHADOWCSM"+e]=!1,i["SHADOWCSMDEBUG"+e]=!1,i["SHADOWCSMNUM_CASCADES"+e]=!1,i["SHADOWCSMUSESHADOWMAXZ"+e]=!1,i["SHADOWCSMNOBLEND"+e]=!1,i["SHADOWCSM_RIGHTHANDED"+e]=!1,i["SHADOWPCF"+e]=!1,i["SHADOWPCSS"+e]=!1,i["SHADOWPOISSON"+e]=!1,i["SHADOWESM"+e]=!1,i["SHADOWCLOSEESM"+e]=!1,i["SHADOWCUBE"+e]=!1,i["SHADOWLOWQUALITY"+e]=!1,i["SHADOWMEDIUMQUALITY"+e]=!1);let l=e.getEngine().getCaps();return void 0===i.SHADOWFLOAT&&(o.needRebuild=!0),i.SHADOWFLOAT=o.shadowEnabled&&(l.textureFloatRender&&l.textureFloatLinearFiltering||l.textureHalfFloatRender&&l.textureHalfFloatLinearFiltering),i.LIGHTMAPEXCLUDED=o.lightmapMode,o.needRebuild&&i.rebuild(),o.needNormals}static PrepareUniformsAndSamplersForLight(e,t,i,r,s=null,n=!1){s&&s.push("Light"+e),!n&&(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),i.push("shadowSampler"+e),i.push("depthSampler"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),r&&(i.push("projectionLightSampler"+e),t.push("textureProjectionMatrix"+e)))}static PrepareUniformsAndSamplersList(e,t,i,r=4){let s;let n=null;e.uniformsNames?(s=e.uniformsNames,n=e.uniformBuffersNames,t=e.samplers,i=e.defines,r=e.maxSimultaneousLights||0):(s=e,t||(t=[]));for(let e=0;e<r&&i["LIGHT"+e];e++)this.PrepareUniformsAndSamplersForLight(e,s,t,i["PROJECTEDLIGHTTEXTURE"+e],n);i.NUM_MORPH_INFLUENCERS&&s.push("morphTargetInfluences"),i.BAKED_VERTEX_ANIMATION_TEXTURE&&(s.push("bakedVertexAnimationSettings"),s.push("bakedVertexAnimationTextureSizeInverted"),s.push("bakedVertexAnimationTime"),t.push("bakedVertexAnimationTexture"))}static HandleFallbacksForShadows(e,t,i=4,r=0){let s=0;for(let n=0;n<i&&e["LIGHT"+n];n++)n>0&&(s=r+n,t.addFallback(s,"LIGHT"+n)),!e.SHADOWS&&(e["SHADOW"+n]&&t.addFallback(r,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(r,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(r,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(r,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(r,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(r,"SHADOWCLOSEESM"+n));return s++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){let s=i.NUM_MORPH_INFLUENCERS;if(s>0&&a.l.LastCreatedEngine){let n=a.l.LastCreatedEngine.getCaps().maxVertexAttribs,l=t.morphTargetManager;if(null==l?void 0:l.isUsingTextureForTargets)return;let h=l&&l.supportsNormals&&i.NORMAL,u=l&&l.supportsTangents&&i.TANGENT,c=l&&l.supportsUVs&&i.UV1;for(let i=0;i<s;i++)e.push(o.o.PositionKind+i),h&&e.push(o.o.NormalKind+i),u&&e.push(o.o.TangentKind+i),c&&e.push(o.o.UVKind+"_"+i),e.length>n&&r.Y.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){let r=i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES;r&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,r){i.NUM_BONE_INFLUENCERS>0&&(r.addCPUSkinningFallback(0,t),e.push(o.o.MatricesIndicesKind),e.push(o.o.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(o.o.MatricesIndicesExtraKind),e.push(o.o.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(o.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,r,s,n=!0){e._bindLight(t,i,r,s,n)}static BindLights(e,t,i,r,s=4){let n=Math.min(t.lightSources.length,s);for(let s=0;s<n;s++){let n=t.lightSources[s];this.BindLight(n,s,e,i,"boolean"==typeof r?r:r.SPECULARTERM,t.receiveShadows)}}static BindFogParameters(e,t,i,r=!1){e.fogEnabled&&t.applyFog&&e.fogMode!==n.x.FOGMODE_NONE&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),r?(e.fogColor.toLinearSpaceToRef(this._TempFogColor,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",this._TempFogColor)):i.setColor3("vFogColor",e.fogColor))}static BindBonesParameters(e,t,i){if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){let r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){let i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{let s=r.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]),c._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){let 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){let e=i.activeCamera;e.mode===s.V.ORTHOGRAPHIC_CAMERA&&r.Y.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}}c._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},c._TempFogColor=h.Wo.Black()},3511:function(e,t,i){var r,s;i.d(t,{S:function(){return r}}),(s=r||(r={}))[s.Created=1]="Created",s[s.Disposed=2]="Disposed",s[s.GetDefineNames=4]="GetDefineNames",s[s.PrepareUniformBuffer=8]="PrepareUniformBuffer",s[s.IsReadyForSubMesh=16]="IsReadyForSubMesh",s[s.PrepareDefines=32]="PrepareDefines",s[s.BindForSubMesh=64]="BindForSubMesh",s[s.PrepareEffect=128]="PrepareEffect",s[s.GetAnimatables=256]="GetAnimatables",s[s.GetActiveTextures=512]="GetActiveTextures",s[s.HasTexture=1024]="HasTexture",s[s.FillRenderTargetTextures=2048]="FillRenderTargetTextures",s[s.HasRenderTargetTextures=4096]="HasRenderTargetTextures",s[s.HardBindForSubMesh=8192]="HardBindForSubMesh"},5816:function(e,t,i){i.d(t,{G:function(){return a}});var r=i(1870),s=i(8772),n=i(9678);class a extends r.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=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._markAllSubMeshesAsTexturesDirty(),s}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i<this.subMaterials.length;i++)if(null===(t=this.subMaterials[i])||void 0===t?void 0:t.hasTexture(e))return!0;return!1}getClassName(){return"MultiMaterial"}isReadyForSubMesh(e,t,i){for(let r=0;r<this.subMaterials.length;r++){let s=this.subMaterials[r];if(s){if(s._storeEffectOnSubMeshes){if(!s.isReadyForSubMesh(e,t,i))return!1;continue}if(!s.isReady(e))return!1}}return!0}clone(e,t){let i=new a(e,this.getScene());for(let r=0;r<this.subMaterials.length;r++){let s=null,n=this.subMaterials[r];s=t&&n?n.clone(e+"-"+n.name):this.subMaterials[r],i.subMaterials.push(s)}return i}serialize(){let e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,s.$&&(e.tags=s.$.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){let i=this.subMaterials[t];i?(e.materialsUniqueIds.push(i.uniqueId),e.materials.push(i.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,i){let r=this.getScene();if(!r)return;if(i)for(let i=0;i<this.subMaterials.length;i++){let r=this.subMaterials[i];r&&r.dispose(e,t)}let s=r.multiMaterials.indexOf(this);s>=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){let i=new a(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,n.H)("BABYLON.MultiMaterial",a)},3587:function(e,t,i){var r,s;i.d(t,{x:function(){return r}}),(s=r||(r={}))[s.GLSL=0]="GLSL",s[s.WGSL=1]="WGSL"},1378:function(e,t,i){i.d(t,{M:function(){return n}});var r=i(7694),s=i(3636);i(54);class n{constructor(e,t,i,r,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=r?r:"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){let e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;let i=this._uniformLocationPointer-e;for(let e=0;e<i;e++)this._data.push(0)}}addUniform(e,t,i=0){let r;if(!this._noUBO&&void 0===this._uniformLocations[e]){if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t)t*=i;else{let e=4-t;t=t*i+e*i}r=[];for(let e=0;e<t;e++)r.push(0)}else{if(t instanceof Array)t=(r=t).length;else{r=[];for(let e=0;e<t;e++)r.push(0)}this._fillAlignment(t)}this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(let e=0;e<t;e++)this._data.push(r[e]);this._needSync=!0}}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.toArray()))}addFloat2(e,t,i){let r=[t,i];this.addUniform(e,r)}addFloat3(e,t,i,r){let s=[t,i,r];this.addUniform(e,s)}addColor3(e,t){let i=[t.r,t.g,t.b];this.addUniform(e,i)}addColor4(e,t,i){let r=[t.r,t.g,t.b,i];this.addUniform(e,r)}addVector3(e,t){let i=[t.x,t.y,t.z];this.addUniform(e,i)}addMatrix3x3(e){this.addUniform(e,12)}addMatrix2x2(e){this.addUniform(e,8)}create(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)}_rebuild(){!this._noUBO&&this._bufferData&&(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData):this._buffer=this._engine.createUniformBuffer(this._bufferData),this._engine._features.trackUbosInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}_copyBuffer(e,t){for(let i=0;i<e.length;++i)t[i]=e[i]}update(){if(!this._noUBO){if(this.bindUniformBuffer(),!this._buffer){this.create();return}if(!this._dynamic&&!this._needSync){this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}if(this._buffers&&this._buffers.length>1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(n._UpdatedUbosInFrame[this._name]||(n._UpdatedUbosInFrame[this._name]=0),n._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()}_checkNewFrame(){this._engine._features.trackUbosInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let n=this._uniformLocations[e];if(void 0===n){if(this._buffer){r.Y.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),n=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e<i;e++)this._bufferData[n+e]=t[e];else{let e=!1;for(let r=0;r<i;r++)(16!==i||this._engine._features.uniformBufferHardCheckMatrix)&&this._bufferData[n+r]===s.w1.FloatRound(t[r])||(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[n+r]=t[r]);this._needSync=this._needSync||e}}updateUniformArray(e,t,i){this._checkNewFrame();let n=this._uniformLocations[e];if(void 0===n){r.Y.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.");return}this._buffer||this.create();let a=this._uniformArraySizes[e];if(this._dynamic)for(let e=0;e<i;e++)this._bufferData[n+e]=t[e];else{let e=!1,r=0,o=0;for(let l=0;l<i;l++)if(this._bufferData[n+4*o+r]!==s.w1.FloatRound(t[l])&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[n+4*o+r]=t[l]),++r===a.strideSize){for(;r<4;r++)this._bufferData[n+4*o+r]=0;r=0,o++}this._needSync=this._needSync||e}}_cacheMatrix(e,t){this._checkNewFrame();let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_updateMatrix3x3ForUniform(e,t){for(let e=0;e<3;e++)n._TempBuffer[4*e]=t[3*e],n._TempBuffer[4*e+1]=t[3*e+1],n._TempBuffer[4*e+2]=t[3*e+2],n._TempBuffer[4*e+3]=0;this.updateUniform(e,n._TempBuffer,12)}_updateMatrix3x3ForEffect(e,t){this._currentEffect.setMatrix3x3(e,t)}_updateMatrix2x2ForEffect(e,t){this._currentEffect.setMatrix2x2(e,t)}_updateMatrix2x2ForUniform(e,t){for(let e=0;e<2;e++)n._TempBuffer[4*e]=t[2*e],n._TempBuffer[4*e+1]=t[2*e+1],n._TempBuffer[4*e+2]=0,n._TempBuffer[4*e+3]=0;this.updateUniform(e,n._TempBuffer,8)}_updateFloatForEffect(e,t){this._currentEffect.setFloat(e,t)}_updateFloatForUniform(e,t){n._TempBuffer[0]=t,this.updateUniform(e,n._TempBuffer,1)}_updateFloat2ForEffect(e,t,i,r=""){this._currentEffect.setFloat2(e+r,t,i)}_updateFloat2ForUniform(e,t,i){n._TempBuffer[0]=t,n._TempBuffer[1]=i,this.updateUniform(e,n._TempBuffer,2)}_updateFloat3ForEffect(e,t,i,r,s=""){this._currentEffect.setFloat3(e+s,t,i,r)}_updateFloat3ForUniform(e,t,i,r){n._TempBuffer[0]=t,n._TempBuffer[1]=i,n._TempBuffer[2]=r,this.updateUniform(e,n._TempBuffer,3)}_updateFloat4ForEffect(e,t,i,r,s,n=""){this._currentEffect.setFloat4(e+n,t,i,r,s)}_updateFloat4ForUniform(e,t,i,r,s){n._TempBuffer[0]=t,n._TempBuffer[1]=i,n._TempBuffer[2]=r,n._TempBuffer[3]=s,this.updateUniform(e,n._TempBuffer,4)}_updateFloatArrayForEffect(e,t){this._currentEffect.setFloatArray(e,t)}_updateFloatArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateArrayForEffect(e,t){this._currentEffect.setArray(e,t)}_updateArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateIntArrayForEffect(e,t){this._currentEffect.setIntArray(e,t)}_updateIntArrayForUniform(e,t){n._TempBufferInt32View.set(t),this.updateUniformArray(e,n._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){n._TempBufferUInt32View.set(t),this.updateUniformArray(e,n._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.toArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){n._TempBuffer[0]=t.x,n._TempBuffer[1]=t.y,n._TempBuffer[2]=t.z,this.updateUniform(e,n._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){n._TempBuffer[0]=t.x,n._TempBuffer[1]=t.y,n._TempBuffer[2]=t.z,n._TempBuffer[3]=t.w,this.updateUniform(e,n._TempBuffer,4)}_updateColor3ForEffect(e,t,i=""){this._currentEffect.setColor3(e+i,t)}_updateColor3ForUniform(e,t){n._TempBuffer[0]=t.r,n._TempBuffer[1]=t.g,n._TempBuffer[2]=t.b,this.updateUniform(e,n._TempBuffer,3)}_updateColor4ForEffect(e,t,i,r=""){this._currentEffect.setColor4(e+r,t,i)}_updateDirectColor4ForEffect(e,t,i=""){this._currentEffect.setDirectColor4(e+i,t)}_updateColor4ForUniform(e,t,i){n._TempBuffer[0]=t.r,n._TempBuffer[1]=t.g,n._TempBuffer[2]=t.b,n._TempBuffer[3]=i,this.updateUniform(e,n._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){n._TempBuffer[0]=t.r,n._TempBuffer[1]=t.g,n._TempBuffer[2]=t.b,n._TempBuffer[3]=t.a,this.updateUniform(e,n._TempBuffer,4)}_updateIntForEffect(e,t,i=""){this._currentEffect.setInt(e+i,t)}_updateIntForUniform(e,t){n._TempBufferInt32View[0]=t,this.updateUniform(e,n._TempBuffer,1)}_updateInt2ForEffect(e,t,i,r=""){this._currentEffect.setInt2(e+r,t,i)}_updateInt2ForUniform(e,t,i){n._TempBufferInt32View[0]=t,n._TempBufferInt32View[1]=i,this.updateUniform(e,n._TempBuffer,2)}_updateInt3ForEffect(e,t,i,r,s=""){this._currentEffect.setInt3(e+s,t,i,r)}_updateInt3ForUniform(e,t,i,r){n._TempBufferInt32View[0]=t,n._TempBufferInt32View[1]=i,n._TempBufferInt32View[2]=r,this.updateUniform(e,n._TempBuffer,3)}_updateInt4ForEffect(e,t,i,r,s,n=""){this._currentEffect.setInt4(e+n,t,i,r,s)}_updateInt4ForUniform(e,t,i,r,s){n._TempBufferInt32View[0]=t,n._TempBufferInt32View[1]=i,n._TempBufferInt32View[2]=r,n._TempBufferInt32View[3]=s,this.updateUniform(e,n._TempBuffer,4)}_updateUIntForEffect(e,t,i=""){this._currentEffect.setUInt(e+i,t)}_updateUIntForUniform(e,t){n._TempBufferUInt32View[0]=t,this.updateUniform(e,n._TempBuffer,1)}_updateUInt2ForEffect(e,t,i,r=""){this._currentEffect.setUInt2(e+r,t,i)}_updateUInt2ForUniform(e,t,i){n._TempBufferUInt32View[0]=t,n._TempBufferUInt32View[1]=i,this.updateUniform(e,n._TempBuffer,2)}_updateUInt3ForEffect(e,t,i,r,s=""){this._currentEffect.setUInt3(e+s,t,i,r)}_updateUInt3ForUniform(e,t,i,r){n._TempBufferUInt32View[0]=t,n._TempBufferUInt32View[1]=i,n._TempBufferUInt32View[2]=r,this.updateUniform(e,n._TempBuffer,3)}_updateUInt4ForEffect(e,t,i,r,s,n=""){this._currentEffect.setUInt4(e+n,t,i,r,s)}_updateUInt4ForUniform(e,t,i,r,s){n._TempBufferUInt32View[0]=t,n._TempBufferUInt32View[1]=i,n._TempBufferUInt32View[2]=r,n._TempBufferUInt32View[3]=s,this.updateUniform(e,n._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t){let i=this._buffers[t];if(i[0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,!0}return!1}dispose(){if(this._noUBO)return;let e=this._engine._uniformBuffers,t=e.indexOf(this);if(-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._features.trackUbosInFrame&&this._buffers)for(let e=0;e<this._buffers.length;++e){let t=this._buffers[e][0];this._engine._releaseBuffer(t)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}}n._UpdatedUbosInFrame={},n._MAX_UNIFORM_SIZE=256,n._TempBuffer=new Float32Array(n._MAX_UNIFORM_SIZE),n._TempBufferInt32View=new Int32Array(n._TempBuffer.buffer),n._TempBufferUInt32View=new Uint32Array(n._TempBuffer.buffer)},5980:function(e,t,i){i.d(t,{RD:function(){return l},T:function(){return n},c7:function(){return a}});var r,s,n,a,o=i(1823);(r=n||(n={}))[r.LOCAL=0]="LOCAL",r[r.WORLD=1]="WORLD",r[r.BONE=2]="BONE";class l{}l.X=new o.P(1,0,0),l.Y=new o.P(0,1,0),l.Z=new o.P(0,0,1),(s=a||(a={}))[s.X=0]="X",s[s.Y=1]="Y",s[s.Z=2]="Z"},6762:function(e,t,i){i.d(t,{HE:function(){return d},Wo:function(){return c},zZ:function(){return p}});var r=i(5526),s=i(156),n=i(4046),a=i(9678);function o(e){return Math.pow(e,s.Nn)}function l(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function h(e){return Math.pow(e,s.zp)}function u(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}class c{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return 397*(e=397*e^(255*this.g|0))^(255*this.b|0)}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return c.FromArrayToRef(e,t,this),this}toColor4(e=1){return new d(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return .3*this.r+.59*this.g+.11*this.b}multiply(e){return new c(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}scale(e){return new c(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this}clampToRef(e=0,t=1,i){return i.r=r.R.Clamp(this.r,e,t),i.g=r.R.Clamp(this.g,e,t),i.b=r.R.Clamp(this.b,e,t),this}add(e){return new c(this.r+e.r,this.g+e.g,this.b+e.b)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this}subtract(e){return new c(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,this}clone(){return new c(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}toHexString(){let e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+r.R.ToHex(e)+r.R.ToHex(t)+r.R.ToHex(i)}toHSV(){let e=new c;return this.toHSVToRef(e),e}toHSVToRef(e){let t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),n=Math.min(t,i,r),a=0,o=0,l=s-n;0!==s&&(o=l/s),s!=n&&(s==t?(a=(i-r)/l,i<r&&(a+=6)):s==i?a=(r-t)/l+2:s==r&&(a=(t-i)/l+4),a*=60),e.r=a,e.g=o,e.b=s}toLinearSpace(e=!1){let t=new c;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=o(this.r),e.g=o(this.g),e.b=o(this.b)),this}toGammaSpace(e=!1){let t=new c;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=u(this.r),e.g=u(this.g),e.b=u(this.b)):(e.r=h(this.r),e.g=h(this.g),e.b=h(this.b)),this}static HSVtoRGBToRef(e,t,i,r){let s=i*t,n=e/60,a=s*(1-Math.abs(n%2-1)),o=0,l=0,h=0;n>=0&&n<=1?(o=s,l=a):n>=1&&n<=2?(o=a,l=s):n>=2&&n<=3?(l=s,h=a):n>=3&&n<=4?(l=a,h=s):n>=4&&n<=5?(o=a,h=s):n>=5&&n<=6&&(o=s,h=a);let u=i-s;r.set(o+u,l+u,h+u)}static FromHSV(e,t,i){let r=new c(0,0,0);return c.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new c(0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16);return c.FromInts(t,i,r)}static FromArray(e,t=0){return new c(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 c(e/255,t/255,i/255)}static Lerp(e,t,i){let r=new c(0,0,0);return c.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n,d=e.r*o+i.r*l+t.r*h+r.r*u,p=e.g*o+i.g*l+t.g*h+r.g*u,_=e.b*o+i.b*l+t.b*h+r.b*u;return new c(d,p,_)}static Hermite1stDerivative(e,t,i,r,s){let n=c.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;n.r=(a-s)*6*e.r+(3*a-4*s+1)*t.r+(-a+s)*6*i.r+(3*a-2*s)*r.r,n.g=(a-s)*6*e.g+(3*a-4*s+1)*t.g+(-a+s)*6*i.g+(3*a-2*s)*r.g,n.b=(a-s)*6*e.b+(3*a-4*s+1)*t.b+(-a+s)*6*i.b+(3*a-2*s)*r.b}static Red(){return new c(1,0,0)}static Green(){return new c(0,1,0)}static Blue(){return new c(0,0,1)}static Black(){return new c(0,0,0)}static get BlackReadOnly(){return c._BlackReadOnly}static White(){return new c(1,1,1)}static Purple(){return new c(.5,0,.5)}static Magenta(){return new c(1,0,1)}static Yellow(){return new c(1,1,0)}static Gray(){return new c(.5,.5,.5)}static Teal(){return new c(0,1,1)}static Random(){return new c(Math.random(),Math.random(),Math.random())}}c._BlackReadOnly=c.Black();class d{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}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 d.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 d(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new d(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,this}scale(e){return new d(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,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=r.R.Clamp(this.r,e,t),i.g=r.R.Clamp(this.g,e,t),i.b=r.R.Clamp(this.b,e,t),i.a=r.R.Clamp(this.a,e,t),this}multiply(e){return new d(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}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 397*(e=397*(e=397*e^(255*this.g|0))^(255*this.b|0))^(255*this.a|0)}clone(){return new d(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,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}toHexString(e=!1){let t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+r.R.ToHex(t)+r.R.ToHex(i)+r.R.ToHex(s);let n=Math.round(255*this.a);return"#"+r.R.ToHex(t)+r.R.ToHex(i)+r.R.ToHex(s)+r.R.ToHex(n)}toLinearSpace(e=!1){let t=new d;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=l(this.r),e.g=l(this.g),e.b=l(this.b)):(e.r=o(this.r),e.g=o(this.g),e.b=o(this.b)),e.a=this.a,this}toGammaSpace(e=!1){let t=new d;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=u(this.r),e.g=u(this.g),e.b=u(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 d(0,0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return d.FromInts(t,i,r,s)}static Lerp(e,t,i){let r=new d(0,0,0,0);return d.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n,c=e.r*o+i.r*l+t.r*h+r.r*u,p=e.g*o+i.g*l+t.g*h+r.g*u,_=e.b*o+i.b*l+t.b*h+r.b*u,f=e.a*o+i.a*l+t.a*h+r.a*u;return new d(c,p,_,f)}static Hermite1stDerivative(e,t,i,r,s){let n=new d;return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;n.r=(a-s)*6*e.r+(3*a-4*s+1)*t.r+(-a+s)*6*i.r+(3*a-2*s)*r.r,n.g=(a-s)*6*e.g+(3*a-4*s+1)*t.g+(-a+s)*6*i.g+(3*a-2*s)*r.g,n.b=(a-s)*6*e.b+(3*a-4*s+1)*t.b+(-a+s)*6*i.b+(3*a-2*s)*r.b,n.a=(a-s)*6*e.a+(3*a-4*s+1)*t.a+(-a+s)*6*i.a+(3*a-2*s)*r.a}static FromColor3(e,t=1){return new d(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new d(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new d(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===3*t){let t=[];for(let i=0;i<e.length;i+=3){let r=i/3*4;t[r]=e[i],t[r+1]=e[i+1],t[r+2]=e[i+2],t[r+3]=1}return t}return e}}class p{}p.Color3=n.B.BuildArray(3,c.Black),p.Color4=n.B.BuildArray(3,()=>new d(0,0,0,0)),(0,a.H)("BABYLON.Color3",c),(0,a.H)("BABYLON.Color4",d)},156:function(e,t,i){i.d(t,{Nn:function(){return s},Q_:function(){return n},kn:function(){return a},zp:function(){return r}});let r=1/2.2,s=2.2,n=(1+Math.sqrt(5))/2,a=.001},9320:function(e,t,i){i.d(t,{i:function(){return s}});var r=i(2321);class s{static GetPlanes(e){let t=[];for(let e=0;e<6;e++)t.push(new r.J(0,0,0,0));return s.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){let 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){let 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){let 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){let 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){let 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){let 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(0>t[i].dotCoordinate(e))return!1;return!0}}},4316:function(e,t,i){i.d(t,{k:function(){return l},y:function(){return o}});var r=i(6851),s=i(1823),n=i(6816);class a{static extractMinAndMaxIndexed(e,t,i,r,s,n){for(let a=i;a<i+r;a++){let i=3*t[a],r=e[i],o=e[i+1],l=e[i+2];s.minimizeInPlaceFromFloats(r,o,l),n.maximizeInPlaceFromFloats(r,o,l)}}static extractMinAndMax(e,t,i,r,s,n){for(let a=t,o=t*r;a<t+i;a++,o+=r){let t=e[o],i=e[o+1],r=e[o+2];s.minimizeInPlaceFromFloats(t,i,r),n.maximizeInPlaceFromFloats(t,i,r)}}}function o(e,t,i,r,n=null){let o=new s.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),l=new s.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return a.extractMinAndMaxIndexed(e,t,i,r,o,l),n&&(o.x-=o.x*n.x+n.y,o.y-=o.y*n.x+n.y,o.z-=o.z*n.x+n.y,l.x+=l.x*n.x+n.y,l.y+=l.y*n.x+n.y,l.z+=l.z*n.x+n.y),{minimum:o,maximum:l}}function l(e,t,i,r=null,n){let o=new s.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),l=new s.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return n||(n=3),a.extractMinAndMax(e,t,i,n,o,l),r&&(o.x-=o.x*r.x+r.y,o.y-=o.y*r.x+r.y,o.z-=o.z*r.x+r.y,l.x+=l.x*r.x+r.y,l.y+=l.y*r.x+r.y,l.z+=l.z*r.x+r.y),{minimum:o,maximum:l}}(0,r.gn)([n.G6.filter((...[e,t])=>!Array.isArray(e)&&!Array.isArray(t))],a,"extractMinAndMaxIndexed",null),(0,r.gn)([n.G6.filter((...[e])=>!Array.isArray(e))],a,"extractMinAndMax",null)},2321:function(e,t,i){i.d(t,{J:function(){return s}});var r=i(1823);class s{constructor(e,t,i,s){this.normal=new r.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(){return 397*this.normal.getHashCode()^(0|this.d)}normalize(){let e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),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){let t=s._TmpMatrix;e.invertToRef(t);let i=t.m,r=this.normal.x,n=this.normal.y,a=this.normal.z,o=this.d,l=r*i[0]+n*i[1]+a*i[2]+o*i[3],h=r*i[4]+n*i[5]+a*i[6]+o*i[7],u=r*i[8]+n*i[9]+a*i[10]+o*i[11],c=r*i[12]+n*i[13]+a*i[14]+o*i[15];return new s(l,h,u,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){let r;let s=t.x-e.x,n=t.y-e.y,a=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,u=n*h-a*l,c=a*o-s*h,d=s*l-n*o,p=Math.sqrt(u*u+c*c+d*d);return r=0!==p?1/p:0,this.normal.x=u*r,this.normal.y=c*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){let i=r.P.Dot(this.normal,e);return i<=t}signedDistanceTo(e){return r.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){let r=new s(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){let 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){let s=-(t.x*e.x+t.y*e.y+t.z*e.z);return r.P.Dot(i,t)+s}}s._TmpMatrix=r.y3.Identity()},5526:function(e,t,i){i.d(t,{R:function(){return r}});class r{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){let 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=r.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){let i=r.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=r.Clamp(i);return t*(s=-2*s*s*s+3*s*s)+e*(1-s)}static MoveTowards(e,t,i){return Math.abs(t-e)<=i?t:e+r.Sign(t-e)*i}static MoveTowardsAngle(e,t,i){let s=r.DeltaAngle(e,t),n=0;return-i<s&&s<i?n=t:(t=e+s,n=r.MoveTowards(e,t,i)),n}static Lerp(e,t,i){return e+(t-e)*i}static LerpAngle(e,t,i){let s=r.Repeat(t-e,360);return s>180&&(s-=360),e+s*r.Clamp(i)}static InverseLerp(e,t,i){return e!=t?r.Clamp((i-e)/(t-e)):0}static Hermite(e,t,i,r,s){let n=s*s,a=s*n;return e*(2*a-3*n+1)+i*(-2*a+3*n)+t*(a-2*n+s)+r*(a-n)}static Hermite1stDerivative(e,t,i,r,s){let n=s*s;return(n-s)*6*e+(3*n-4*s+1)*t+(-n+s)*6*i+(3*n-2*s)*r}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-=r.TwoPi*Math.floor((e+Math.PI)/r.TwoPi)}static HCF(e,t){let i=e%t;return 0===i?t:r.HCF(t,i)}}r.TwoPi=2*Math.PI},5831:function(e,t,i){i.d(t,{l:function(){return r}});class r{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new r(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new r(this.x,this.y,this.width,this.height)}}},4696:function(e,t,i){i.d(t,{M:function(){return s}});var r=i(6430);class s extends r.h{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},1572:function(e,t,i){i.d(t,{x:function(){return E}});var r=i(6702),s=i(6438),n=i(1823),a=i(3700),o=i(7620),l=i(3795),h=i(2469),u=i(9657),c=i(6886),d=i(1378),p=i(3927),_=i(4620),f=i(4316),m=i(6762),g=i(156),v=i(5980),T=i(9678);class x{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=n.P.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class S{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new x,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 E 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;let 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){let 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 S,this._waitingMaterialId=null,this.cullingStrategy=E.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new r.y$,this.onCollisionPositionChangeObservable=new r.y$,this.onMaterialChangedObservable=new r.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 n.P(.5,1,.5),this.ellipsoidOffset=new n.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=[],this._unIndexed=!1,this._lightSources=[],this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new r.y$,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>a.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 d.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){let 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);let i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode]+", 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){return this.actionManager&&(t||this.actionManager.isRecursive)&&(!e||this.actionManager.hasSpecificTrigger(e))?this.actionManager: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(let e of this.subMeshes)e._rebuild()}_resyncLightSources(){for(let e of(this._lightSources.length=0,this.getScene().lights))e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){let t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(let e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){let i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(let t of this.subMeshes)for(let i=0;i<t._drawWrappers.length;++i){let r=t._drawWrappers[i];r&&r.defines&&r.defines.markAllAsDirty&&e(r.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty(t=>t.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(let t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,r){return this}updateVerticesData(e,t,i,r){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){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 c.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(o.o.MatricesIndicesKind)&&this.isVerticesDataPresent(o.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){let r=new n.y3,s=this.rotationQuaternion?this.rotationQuaternion:n._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z);s.toRotationMatrix(r);let a=n.P.Zero(),o=this.definedFacingForward?-1:1;return n.P.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,r,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){let r=this.definedFacingForward?1:-1;return new n.P(e*r,t,i*r)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){let i=(0,f.k)(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new c.j(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t<this.subMeshes.length;t++)this.subMeshes[t].refreshBoundingInfo(e);this._updateBoundingInfo()}_getData(e=!1,t=!1,i,r=o.o.PositionKind){if((i=null!=i?i:this.getVerticesData(r).slice())&&t&&this.morphTargetManager){let e=0,t=0;for(let s=0;s<i.length;s++){for(let e=0;e<this.morphTargetManager.numTargets;e++){let t=this.morphTargetManager.getTarget(e),r=t.influence;if(r>0){let e=t.getPositions();e&&(i[s]+=(e[s]-i[s])*r)}}if(e++,r===o.o.PositionKind&&this._positions&&3===e){e=0;let r=3*t;this._positions[t++].copyFromFloats(i[r],i[r+1],i[r+2])}}}if(i&&e&&this.skeleton){let e=this.getVerticesData(o.o.MatricesIndicesKind),t=this.getVerticesData(o.o.MatricesWeightsKind);if(t&&e){let s=this.numBoneInfluencers>4,a=s?this.getVerticesData(o.o.MatricesIndicesExtraKind):null,l=s?this.getVerticesData(o.o.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this),u=n.jp.Vector3[0],c=n.jp.Matrix[0],d=n.jp.Matrix[1],p=0;for(let _=0;_<i.length;_+=3,p+=4){let f,m;for(c.reset(),f=0;f<4;f++)(m=t[p+f])>0&&(n.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*e[p+f]),m,d),c.addToSelf(d));if(s)for(f=0;f<4;f++)(m=l[p+f])>0&&(n.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*a[p+f]),m,d),c.addToSelf(d));r===o.o.NormalKind?n.P.TransformNormalFromFloatsToRef(i[_],i[_+1],i[_+2],c,u):n.P.TransformCoordinatesFromFloatsToRef(i[_],i[_+1],i[_+2],c,u),u.toArray(i,_),r===o.o.PositionKind&&this._positions&&this._positions[_/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,o.o.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,o.o.PositionKind)}_getPositionData(e,t){var i;let r=this.getVerticesData(o.o.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),r&&(e&&this.skeleton||t&&this.morphTargetManager)){if(r=r.slice(),this._generatePointsArray(),this._positions){let e=this._positions;this._internalAbstractMeshDataInfo._positions=Array(e.length);for(let t=0;t<e.length;t++)this._internalAbstractMeshDataInfo._positions[t]=(null===(i=e[t])||void 0===i?void 0:i.clone())||new n.P}return this.getPositionData(e,t,r)}return r}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new c.j(n.P.Zero(),n.P.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;let t=this.subMeshes.length;for(let i=0;i<t;i++){let r=this.subMeshes[i];(t>1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){let r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(let i of this.getChildMeshes())if(i.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){let t=this.getAbsolutePosition();t.addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);let i=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=i.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];let i=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let s=i;s<r;s++)e._lastColliderWorldVertices.push(n.P.TransformCoordinates(this._positions[s],t))}return i._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),(null===(r=e.getMaterial())||void 0===r?void 0:r.fillMode)===7),this}_processCollisionsForSubMeshes(e,t){let i=this._scene.getCollidingSubMeshCandidates(this,e),r=i.length;for(let s=0;s<r;s++){let n=i.data[s];(!(r>1)||n._checkCollision(e))&&this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;let t=n.jp.Matrix[0],i=n.jp.Matrix[1];return n.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,r=!1,s,a=!1){let o=new u.p,l=this.getClassName(),h="InstancedLinesMesh"===l||"LinesMesh"===l||"GreasedLineMesh"===l?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(c.boundingSphere,h)||!e.intersectsBox(c.boundingBox,h)))return o;if(r)return o.hit=!a,o.pickedMesh=a?null:this,o.distance=a?0:n.P.Distance(e.origin,c.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let d=null,p=this._scene.getIntersectingSubMeshCandidates(this,e),_=p.length,f=!1;for(let e=0;e<_;e++){let t=p.data[e],i=t.getMaterial();if(i&&(7==i.fillMode||0==i.fillMode||1==i.fillMode||2==i.fillMode||4==i.fillMode)){f=!0;break}}if(!f)return o.hit=!0,o.pickedMesh=this,o.distance=n.P.Distance(e.origin,c.boundingSphere.center),o.subMeshId=-1,o;for(let r=0;r<_;r++){let s=p.data[r];if(_>1&&!s.canIntersects(e))continue;let n=s.intersects(e,this._positions,this.getIndices(),t,i);if(n&&(t||!d||n.distance<d.distance)&&((d=n).subMeshId=r,t))break}if(d){let t=null!=s?s:this.getWorldMatrix(),i=n.jp.Vector3[0],r=n.jp.Vector3[1];n.P.TransformCoordinatesToRef(e.origin,t,i),e.direction.scaleToRef(d.distance,r);let a=n.P.TransformNormal(r,t),l=a.addInPlace(i);o.hit=!0,o.distance=n.P.Distance(i,l),o.pickedPoint=l,o.pickedMesh=this,o.bu=d.bu||0,o.bv=d.bv||0,o.subMeshFaceId=d.faceId,o.faceId=d.faceId+p.data[d.subMeshId].indexStart/(-1!==this.getClassName().indexOf("LinesMesh")?2:3),o.subMeshId=d.subMeshId}return o}clone(e,t,i){return null}releaseSubMeshes(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=[];return this}dispose(e,t=!1){let i;for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this.getScene().freeActiveMeshes(),this.getScene().freeRenderingGroups(),void 0!==this.actionManager&&null!==this.actionManager&&(this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i<this._intersectionsInProgress.length;i++){let e=this._intersectionsInProgress[i],t=e._intersectionsInProgress.indexOf(this);e._intersectionsInProgress.splice(t,1)}this._intersectionsInProgress.length=0;let r=this.getScene().lights;r.forEach(e=>{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),-1!==(t=e.excludedMeshes.indexOf(this))&&e.excludedMeshes.splice(t,1);let i=e.getShadowGenerators();if(i){let e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){let e=i.value,r=e.getShadowMap();r&&r.renderList&&-1!==(t=r.renderList.indexOf(this))&&r.renderList.splice(t,1)}}}),("InstancedMesh"!==this.getClassName()||"InstancedLinesMesh"!==this.getClassName())&&this.releaseSubMeshes();let s=this.getScene().getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,s.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),s.wipeCaches(),this.getScene().removeMesh(this),this._parentContainer){let e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i<this.getScene().particleSystems.length;i++)this.getScene().particleSystems[i].emitter===this&&(this.getScene().particleSystems[i].dispose(),i--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}_initFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=[]),e.facetPositions||(e.facetPositions=[]),e.facetPartitioning||(e.facetPartitioning=[]),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=n.P.Zero(),e.facetPositions[t]=n.P.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();let t=this.getVerticesData(o.o.PositionKind),i=this.getIndices(),r=this.getVerticesData(o.o.NormalKind),s=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,i instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(i);else if(i instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(i);else{let t=!1;for(let e=0;e<i.length;e++)if(i[e]>65535){t=!0;break}t?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){let t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:n.P.Zero()}e.depthSortedFacets=[];for(let t=0;t<e.facetNb;t++){let i={ind:3*t,sqDistance:0};e.depthSortedFacets.push(i)}e.invertedMatrix=n.y3.Identity(),e.facetDepthSortOrigin=n.P.Zero()}e.bbSize.x=s.maximum.x-s.minimum.x>g.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 a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),n.P.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&l.x.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);let t=e.depthSortedIndices.length/3|0;for(let r=0;r<t;r++){let t=e.depthSortedFacets[r].ind;e.depthSortedIndices[3*r]=i[t],e.depthSortedIndices[3*r+1]=i[t+1],e.depthSortedIndices[3*r+2]=i[t+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this}getFacetLocalNormals(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals}getFacetLocalPositions(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions}getFacetLocalPartitioning(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning}getFacetPosition(e){let t=n.P.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){let i=this.getFacetLocalPositions()[e],r=this.getWorldMatrix();return n.P.TransformCoordinatesToRef(i,r,t),this}getFacetNormal(e){let t=n.P.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){let i=this.getFacetLocalNormals()[e];return n.P.TransformNormalToRef(i,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,i){let r=this.getBoundingInfo(),s=this._internalAbstractMeshDataInfo._facetData,n=Math.floor((e-r.minimum.x*s.partitioningBBoxRatio)*s.subDiv.X*s.partitioningBBoxRatio/s.bbSize.x),a=Math.floor((t-r.minimum.y*s.partitioningBBoxRatio)*s.subDiv.Y*s.partitioningBBoxRatio/s.bbSize.y),o=Math.floor((i-r.minimum.z*s.partitioningBBoxRatio)*s.subDiv.Z*s.partitioningBBoxRatio/s.bbSize.z);return n<0||n>s.subDiv.max||a<0||a>s.subDiv.max||o<0||o>s.subDiv.max?null:s.facetPartitioning[n+s.subDiv.max*a+s.subDiv.max*s.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,a=!0){let o=this.getWorldMatrix(),l=n.jp.Matrix[5];o.invertToRef(l);let h=n.jp.Vector3[8];n.P.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);let u=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,r,s,a);return r&&n.P.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),u}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,n=!0){let a,o,l,h=null,u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=0,v=this.getFacetLocalPositions(),T=this.getFacetLocalNormals(),x=this.getFacetsAtLocalCoordinates(e,t,i);if(!x)return null;let S=Number.MAX_VALUE,E=S;for(let C=0;C<x.length;C++)o=T[a=x[C]],p=(e-(l=v[a]).x)*o.x+(t-l.y)*o.y+(i-l.z)*o.z,(!s||s&&n&&p>=0||s&&!n&&p<=0)&&(p=o.x*l.x+o.y*l.y+o.z*l.z,_=-(o.x*e+o.y*t+o.z*i-p)/(o.x*o.x+o.y*o.y+o.z*o.z),f=e+o.x*_,m=t+o.y*_,g=i+o.z*_,(E=(u=f-e)*u+(c=m-t)*c+(d=g-i)*d)<S&&(S=E,h=a,r&&(r.x=f,r.y=m,r.z=g)));return h}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){let e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=[],e.facetNormals=[],e.facetPartitioning=[],e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,i=!1){return this}createNormals(e){let t;let i=this.getVerticesData(o.o.PositionKind),r=this.getIndices();return t=this.isVerticesDataPresent(o.o.NormalKind)?this.getVerticesData(o.o.NormalKind):[],l.x.ComputeNormals(i,r,t,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(o.o.NormalKind,t,e),this}alignWithNormal(e,t){t||(t=v.RD.Y);let i=n.jp.Vector3[0],r=n.jp.Vector3[1];return n.P.CrossToRef(t,e,r),n.P.CrossToRef(e,r,i),this.rotationQuaternion?n._f.RotationQuaternionFromAxisToRef(i,e,r,this.rotationQuaternion):n.P.RotationFromAxisToRef(i,e,r,this.rotation),this}_checkOcclusionQuery(){return!1}disableEdgesRendering(){throw(0,_.S)("EdgesRenderer")}enableEdgesRendering(e,t,i){throw(0,_.S)("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter(e=>e.emitter===this)}}E.OCCLUSION_TYPE_NONE=0,E.OCCLUSION_TYPE_OPTIMISTIC=1,E.OCCLUSION_TYPE_STRICT=2,E.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,E.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,E.CULLINGSTRATEGY_STANDARD=0,E.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,E.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,E.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,(0,T.H)("BABYLON.AbstractMesh",E)},1397:function(e,t,i){i.d(t,{Z:function(){return f}});var r=i(1823),s=i(6762),n=i(3795),a=i(7620),o=i(1813),l=i(199),h=i(6886),u=i(3636),c=i(8772),d=i(4316),p=i(3914),_=i(4870);class f{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){let t=new f(f.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null){if(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)return;this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0}_rebuild(){for(let e in this._vertexArrayObjects&&(this._vertexArrayObjects={}),0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),this._vertexBuffers){let t=this._vertexBuffers[e];t._rebuild()}}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,r){i&&Array.isArray(t)&&(t=new Float32Array(t));let s=new a.o(this._engine,t,e,i,0===this._meshes.length,r);this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){let r=e.getKind();this._vertexBuffers[r]&&i&&this._vertexBuffers[r].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[r]=e;let s=this._meshes,n=s.length;if(r===a.o.PositionKind){let i=e.getData();null!=t?this._totalVertices=t:null!=i&&(this._totalVertices=i.length/(e.type===a.o.BYTE?e.byteStride:e.byteStride/4)),this._updateExtend(i),this._resetPointsArrayCache();for(let e=0;e<n;e++){let t=s[e];t.buildBoundingInfo(this._extend.minimum,this._extend.maximum),t._createGlobalSubMesh(t.isUnIndexed),t.computeWorldMatrix(!0),t.synchronizeInstances()}}this._notifyUpdate(r)}updateVerticesDataDirectly(e,t,i,r=!1){let s=this.getVertexBuffer(e);s&&(s.updateDirectly(t,i,r),this._notifyUpdate(e))}updateVerticesData(e,t,i=!1){let r=this.getVertexBuffer(e);r&&(r.update(t),e===a.o.PositionKind&&this._updateBoundingInfo(i,t),this._notifyUpdate(e))}_updateBoundingInfo(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e){let e=this._meshes;for(let t of e){t.hasBoundingInfo?t.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):t.buildBoundingInfo(this._extend.minimum,this._extend.maximum);let e=t.subMeshes;for(let t of e)t.refreshBoundingInfo()}}}_bind(e,t,i,r){if(!e)return;void 0===t&&(t=this._indexBuffer);let s=this.getVertexBuffers();if(!s)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!r){this._engine.bindBuffers(s,t,e,i);return}let n=r||this._vertexArrayObjects;n[e.key]||(n[e.key]=this._engine.recordVertexArrayObject(s,t,e,i)),this._engine.bindVertexArrayObject(n[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,i){let r=this.getVertexBuffer(e);return r?r.getFloatData(this._totalVertices,i||t&&1!==this._meshes.length):null}isVertexBufferUpdatable(e){let t=this._vertexBuffers[e];return!!t&&t.isUpdatable()}getVertexBuffer(e){return this.isReady()?this._vertexBuffers[e]:null}getVertexBuffers(){return this.isReady()?this._vertexBuffers:null}isVerticesDataPresent(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}getVerticesDataKinds(){let e;let t=[];if(!this._vertexBuffers&&this._delayInfo)for(e in this._delayInfo)t.push(e);else for(e in this._vertexBuffers)t.push(e);return t}updateIndices(e,t,i=!1){if(this._indexBuffer){if(this._indexBufferIsUpdatable){let r=e.length!==this._indices.length;if(i||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),r)for(let e of this._meshes)e._createGlobalSubMesh(!0)}else this.setIndices(e,null,!0)}}setIndices(e,t=null,i=!1){for(let r of(this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i)),void 0!=t&&(this._totalVertices=t),this._meshes))r._createGlobalSubMesh(!0),r.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;let i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){let i=this._meshes,r=i.indexOf(e);-1!==r&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;let t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();let i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(a.o.PositionKind)))return;this._extend=(0,d.k)(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){let t=this._meshes.length;for(let i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===a.o.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){for(let t of(this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects(),this._meshes))t._markSubMeshesAsAttributesDirty()}load(e,t){if(2!==this.delayLoadState){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);let r=this._meshes,s=r.length;for(let e=0;e<s;e++)this._applyToMesh(r[e]);t&&t()},void 0,!0))}toLeftHanded(){let e=this.getIndices(!1);if(null!=e&&e.length>0){for(let t=0;t<e.length;t+=3){let i=e[t+0];e[t+0]=e[t+2],e[t+2]=i}this.setIndices(e)}let t=this.getVerticesData(a.o.PositionKind,!1);if(null!=t&&t.length>0){for(let e=0;e<t.length;e+=3)t[e+2]=-t[e+2];this.setVerticesData(a.o.PositionKind,t,!1)}let i=this.getVerticesData(a.o.NormalKind,!1);if(null!=i&&i.length>0){for(let e=0;e<i.length;e+=3)i[e+2]=-i[e+2];this.setVerticesData(a.o.NormalKind,i,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;let e=this.getVerticesData(a.o.PositionKind);if(!e||0===e.length)return!1;for(let t=3*this._positionsCache.length,i=this._positionsCache.length;t<e.length;t+=3,++i)this._positionsCache[i]=r.P.FromArray(e,t);for(let t=0,i=0;t<e.length;t+=3,++i)this._positionsCache[i].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0}isDisposed(){return this._isDisposed}_disposeVertexArrayObjects(){if(this._vertexArrayObjects){for(let e in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);this._vertexArrayObjects={};let e=this._meshes,t=e.length;for(let i=0;i<t;i++)e[i]._invalidateInstanceVertexArrayObject()}}dispose(){let e;let t=this._meshes,i=t.length;for(e=0;e<i;e++)this.releaseForMesh(t[e]);for(let e in this._meshes.length=0,this._disposeVertexArrayObjects(),this._vertexBuffers)this._vertexBuffers[e].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=0,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){let e=this._parentContainer.geometries.indexOf(this);e>-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){let t;let i=new n.x;i.indices=[];let r=this.getIndices();if(r)for(let e=0;e<r.length;e++)i.indices.push(r[e]);let s=!1,a=!1;for(t in this._vertexBuffers){let e=this.getVerticesData(t);if(e&&(e instanceof Float32Array?i.set(new Float32Array(e),t):i.set(e.slice(0),t),!a)){let e=this.getVertexBuffer(t);e&&(a=!(s=e.isUpdatable()))}}let o=new f(e,this._scene,i,s);for(t in o.delayLoadState=this.delayLoadState,o.delayLoadingFile=this.delayLoadingFile,o._delayLoadingFunction=this._delayLoadingFunction,this._delayInfo)o._delayInfo=o._delayInfo||[],o._delayInfo.push(t);return o._boundingInfo=new h.j(this._extend.minimum,this._extend.maximum),o}serialize(){let e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,c.$&&c.$.HasTags(this)&&(e.tags=c.$.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){for(let e in this._indices=[],this._resetPointsArrayCache(),this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){let e=this.serialize();return this.isVerticesDataPresent(a.o.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(a.o.PositionKind)),this.isVertexBufferUpdatable(a.o.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(a.o.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(a.o.NormalKind)),this.isVertexBufferUpdatable(a.o.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(a.o.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(a.o.TangentKind)),this.isVertexBufferUpdatable(a.o.TangentKind)&&(e.tangents._updatable=!0)),this.isVerticesDataPresent(a.o.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(a.o.UVKind)),this.isVertexBufferUpdatable(a.o.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(a.o.UV2Kind)&&(e.uv2s=this._toNumberArray(this.getVerticesData(a.o.UV2Kind)),this.isVertexBufferUpdatable(a.o.UV2Kind)&&(e.uv2s._updatable=!0)),this.isVerticesDataPresent(a.o.UV3Kind)&&(e.uv3s=this._toNumberArray(this.getVerticesData(a.o.UV3Kind)),this.isVertexBufferUpdatable(a.o.UV3Kind)&&(e.uv3s._updatable=!0)),this.isVerticesDataPresent(a.o.UV4Kind)&&(e.uv4s=this._toNumberArray(this.getVerticesData(a.o.UV4Kind)),this.isVertexBufferUpdatable(a.o.UV4Kind)&&(e.uv4s._updatable=!0)),this.isVerticesDataPresent(a.o.UV5Kind)&&(e.uv5s=this._toNumberArray(this.getVerticesData(a.o.UV5Kind)),this.isVertexBufferUpdatable(a.o.UV5Kind)&&(e.uv5s._updatable=!0)),this.isVerticesDataPresent(a.o.UV6Kind)&&(e.uv6s=this._toNumberArray(this.getVerticesData(a.o.UV6Kind)),this.isVertexBufferUpdatable(a.o.UV6Kind)&&(e.uv6s._updatable=!0)),this.isVerticesDataPresent(a.o.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(a.o.ColorKind)),this.isVertexBufferUpdatable(a.o.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(a.o.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(a.o.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(a.o.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(a.o.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(a.o.MatricesWeightsKind)),this.isVertexBufferUpdatable(a.o.MatricesWeightsKind)&&(e.matricesWeights._updatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){let i=e._geometry;return i?i.copy(t):null}static RandomId(){return u.w1.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i<t.geometries.length;i++)if(t.geometries[i]._loadedUniqueId===e)return t.geometries[i];return null}static _ImportGeometry(e,t){let i=t.getScene(),r=e.geometryUniqueId,n=e.geometryId;if(r||n){let e=r?this._GetGeometryByLoadedUniqueId(r,i):i.getGeometryById(n);e&&e.applyToMesh(t)}else if(e instanceof ArrayBuffer){let i=t._binaryInfo;if(i.positionsAttrDesc&&i.positionsAttrDesc.count>0){let r=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(a.o.PositionKind,r,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){let r=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(a.o.NormalKind,r,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){let r=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(a.o.TangentKind,r,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){let r=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UVKind,r,!1)}if(i.uvs2AttrDesc&&i.uvs2AttrDesc.count>0){let r=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UV2Kind,r,!1)}if(i.uvs3AttrDesc&&i.uvs3AttrDesc.count>0){let r=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UV3Kind,r,!1)}if(i.uvs4AttrDesc&&i.uvs4AttrDesc.count>0){let r=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UV4Kind,r,!1)}if(i.uvs5AttrDesc&&i.uvs5AttrDesc.count>0){let r=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UV5Kind,r,!1)}if(i.uvs6AttrDesc&&i.uvs6AttrDesc.count>0){let r=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e<r.length;e+=2)r[e]=1-r[e];t.setVerticesData(a.o.UV6Kind,r,!1)}if(i.colorsAttrDesc&&i.colorsAttrDesc.count>0){let r=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(a.o.ColorKind,r,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e<r.length;e++){let t=r[e];s.push(255&t),s.push((65280&t)>>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(a.o.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e<r.length;e++){let t=r[e];s.push(255&t),s.push((65280&t)>>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(a.o.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){let r=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(a.o.MatricesWeightsKind,r,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){let r=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(r,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){let r=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e<i.subMeshesAttrDesc.count;e++){let i=r[5*e+0],s=r[5*e+1],n=r[5*e+2],a=r[5*e+3],l=r[5*e+4];o.P.AddToMesh(i,s,n,a,l,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(a.o.PositionKind,e.positions,e.positions._updatable),t.setVerticesData(a.o.NormalKind,e.normals,e.normals._updatable),e.tangents&&t.setVerticesData(a.o.TangentKind,e.tangents,e.tangents._updatable),e.uvs&&t.setVerticesData(a.o.UVKind,e.uvs,e.uvs._updatable),e.uvs2&&t.setVerticesData(a.o.UV2Kind,e.uvs2,e.uvs2._updatable),e.uvs3&&t.setVerticesData(a.o.UV3Kind,e.uvs3,e.uvs3._updatable),e.uvs4&&t.setVerticesData(a.o.UV4Kind,e.uvs4,e.uvs4._updatable),e.uvs5&&t.setVerticesData(a.o.UV5Kind,e.uvs5,e.uvs5._updatable),e.uvs6&&t.setVerticesData(a.o.UV6Kind,e.uvs6,e.uvs6._updatable),e.colors&&t.setVerticesData(a.o.ColorKind,s.HE.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices){if(e.matricesIndices._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(a.o.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable);else{let i=[];for(let t=0;t<e.matricesIndices.length;t++){let r=e.matricesIndices[t];i.push(255&r),i.push((65280&r)>>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(a.o.MatricesIndicesKind,i,e.matricesIndices._updatable)}}if(e.matricesIndicesExtra){if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(a.o.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{let i=[];for(let t=0;t<e.matricesIndicesExtra.length;t++){let r=e.matricesIndicesExtra[t];i.push(255&r),i.push((65280&r)>>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(a.o.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}}e.matricesWeights&&(f._CleanMatricesWeights(e,t),t.setVerticesData(a.o.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(a.o.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i<e.subMeshes.length;i++){let r=e.subMeshes[i];o.P.AddToMesh(r.materialIndex,r.verticesStart,r.verticesCount,r.indexStart,r.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),i.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){if(!l.Z.CleanBoneMatrixWeights)return;let i=0;if(!(e.skeletonId>-1))return;{let r=t.getScene().getLastSkeletonById(e.skeletonId);if(!r)return;i=r.bones.length}let r=t.getVerticesData(a.o.MatricesIndicesKind),s=t.getVerticesData(a.o.MatricesIndicesExtraKind),n=e.matricesWeights,o=e.matricesWeightsExtra,h=e.numBoneInfluencer,u=n.length;for(let e=0;e<u;e+=4){let t=0,a=-1;for(let i=0;i<4;i++){let r=n[e+i];t+=r,r<.001&&a<0&&(a=i)}if(o)for(let i=0;i<4;i++){let r=o[e+i];t+=r,r<.001&&a<0&&(a=i+4)}if((a<0||a>h-1)&&(a=h-1),t>.001){let i=1/t;for(let t=0;t<4;t++)n[e+t]*=i;if(o)for(let t=0;t<4;t++)o[e+t]*=i}else a>=4?(o[e+a-4]=1-t,s[e+a-4]=i):(n[e+a]=1-t,r[e+a]=i)}t.setVerticesData(a.o.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(a.o.MatricesIndicesExtraKind,s)}static Parse(e,t,i){let s=new f(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,c.$&&c.$.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new h.j(r.P.FromArray(e.boundingBoxMinimum),r.P.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(a.o.UVKind),e.hasUVs2&&s._delayInfo.push(a.o.UV2Kind),e.hasUVs3&&s._delayInfo.push(a.o.UV3Kind),e.hasUVs4&&s._delayInfo.push(a.o.UV4Kind),e.hasUVs5&&s._delayInfo.push(a.o.UV5Kind),e.hasUVs6&&s._delayInfo.push(a.o.UV6Kind),e.hasColors&&s._delayInfo.push(a.o.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(a.o.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(a.o.MatricesWeightsKind),s._delayLoadingFunction=n.x.ImportVertexData):n.x.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}},3795:function(e,t,i){i.d(t,{D:function(){return p},x:function(){return _}});var r=i(6851),s=i(1823),n=i(7620),a=i(4620),o=i(6762),l=i(7694),h=i(6816),u=i(9357),c=i(8150),d=i(1813);class p{}class _{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=(0,u.vp)(this._applyToCoroutine.bind(this)),this.uniqueId=_._UniqueIDGenerator,_._UniqueIDGenerator++}set(e,t){switch(e.length||l.Y.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case n.o.PositionKind:this.positions=e;break;case n.o.NormalKind:this.normals=e;break;case n.o.TangentKind:this.tangents=e;break;case n.o.UVKind:this.uvs=e;break;case n.o.UV2Kind:this.uvs2=e;break;case n.o.UV3Kind:this.uvs3=e;break;case n.o.UV4Kind:this.uvs4=e;break;case n.o.UV5Kind:this.uvs5=e;break;case n.o.UV6Kind:this.uvs6=e;break;case n.o.ColorKind:this.colors=e;break;case n.o.MatricesIndicesKind:this.matricesIndices=e;break;case n.o.MatricesWeightsKind:this.matricesWeights=e;break;case n.o.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case n.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){if(this.positions&&(e.setVerticesData(n.o.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(n.o.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(n.o.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(n.o.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(n.o.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(n.o.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(n.o.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(n.o.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(n.o.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(n.o.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(n.o.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(n.o.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1)for(let t of(e.subMeshes=[],this.materialInfos))new d.P(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,e);return this}_update(e,t,i){return this.positions&&e.updateVerticesData(n.o.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(n.o.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(n.o.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(n.o.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(n.o.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(n.o.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(n.o.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(n.o.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(n.o.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(n.o.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(n.o.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(n.o.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){let n=s.jp.Vector3[0],a=s.jp.Vector3[1];for(let o=i;o<i+r;o+=3)s.P.FromArrayToRef(e,o,n),s.P.TransformCoordinatesToRef(n,t,a),e[o]=a.x,e[o+1]=a.y,e[o+2]=a.z}static _TransformVector3Normals(e,t,i=0,r=e.length){let n=s.jp.Vector3[0],a=s.jp.Vector3[1];for(let o=i;o<i+r;o+=3)s.P.FromArrayToRef(e,o,n),s.P.TransformNormalToRef(n,t,a),e[o]=a.x,e[o+1]=a.y,e[o+2]=a.z}static _TransformVector4Normals(e,t,i=0,r=e.length){let n=s.jp.Vector4[0],a=s.jp.Vector4[1];for(let o=i;o<i+r;o+=4)s.Lt.FromArrayToRef(e,o,n),s.Lt.TransformNormalToRef(n,t,a),e[o]=a.x,e[o+1]=a.y,e[o+2]=a.z,e[o+3]=a.w}static _FlipFaces(e,t=0,i=e.length){for(let r=t;r<t+i;r+=3){let t=e[r+1];e[r+1]=e[r+2],e[r+2]=t}}transform(e){let t=0>e.determinant();return this.positions&&_._TransformVector3Coordinates(this.positions,e),this.normals&&_._TransformVector3Normals(this.normals,e),this.tangents&&_._TransformVector4Normals(this.tangents,e),t&&this.indices&&_._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];let e=[];for(let t of this.materialInfos){let i=new _;if(this.positions&&(i.positions=this.positions.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.normals&&(i.normals=this.normals.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.tangents&&(i.tangents=this.tangents.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.colors&&(i.colors=this.colors.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.uvs&&(i.uvs=this.uvs.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs2&&(i.uvs2=this.uvs2.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs3&&(i.uvs3=this.uvs3.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs4&&(i.uvs4=this.uvs4.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs5&&(i.uvs5=this.uvs5.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs6&&(i.uvs6=this.uvs6.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.indices){i.indices=[];for(let e=t.indexStart;e<t.indexStart+t.indexCount;e++)i.indices.push(this.indices[e]-t.verticesStart)}let r=new p;r.indexStart=0,r.indexCount=i.indices?i.indices.length:0,r.materialIndex=t.materialIndex,r.verticesStart=0,r.verticesCount=(i.positions?i.positions.length:0)/3,i.materialInfos=[r],e.push(i)}return e}merge(e,t=!1,i=!1,r=!1,s=!1){let n=Array.isArray(e)?e.map(e=>({vertexData:e})):[{vertexData:e}];return(0,u.s3)(this._mergeCoroutine(void 0,n,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,a=!1,o=!1){var l,h,u,c;this._validate();let d=t.map(e=>e.vertexData),f=this;for(let e of d)if(e){if(e._validate(),o)!this.normals!=!e.normals&&(this.normals?e.normals=Array.from(this.normals):this.normals=Array.from(e.normals)),!this.tangents!=!e.tangents&&(this.tangents?e.tangents=Array.from(this.tangents):this.tangents=Array.from(e.tangents)),!this.uvs!=!e.uvs&&(this.uvs?e.uvs=Array.from(this.uvs):this.uvs=Array.from(e.uvs)),!this.uvs2!=!e.uvs2&&(this.uvs2?e.uvs2=Array.from(this.uvs2):this.uvs2=Array.from(e.uvs2)),!this.uvs3!=!e.uvs3&&(this.uvs3?e.uvs3=Array.from(this.uvs3):this.uvs3=Array.from(e.uvs3)),!this.uvs4!=!e.uvs4&&(this.uvs4?e.uvs4=Array.from(this.uvs4):this.uvs4=Array.from(e.uvs4)),!this.uvs5!=!e.uvs5&&(this.uvs5?e.uvs5=Array.from(this.uvs5):this.uvs5=Array.from(e.uvs5)),!this.uvs6!=!e.uvs6&&(this.uvs6?e.uvs6=Array.from(this.uvs6):this.uvs6=Array.from(e.uvs6)),!this.colors!=!e.colors&&(this.colors?e.colors=Array.from(this.colors):this.colors=Array.from(e.colors)),!this.matricesIndices!=!e.matricesIndices&&(this.matricesIndices?e.matricesIndices=Array.from(this.matricesIndices):this.matricesIndices=Array.from(e.matricesIndices)),!this.matricesWeights!=!e.matricesWeights&&(this.matricesWeights?e.matricesWeights=Array.from(this.matricesWeights):this.matricesWeights=Array.from(e.matricesWeights)),!this.matricesIndicesExtra!=!e.matricesIndicesExtra&&(this.matricesIndicesExtra?e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra):this.matricesIndicesExtra=Array.from(e.matricesIndicesExtra)),!this.matricesWeightsExtra!=!e.matricesWeightsExtra&&(this.matricesWeightsExtra?e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra):this.matricesWeightsExtra=Array.from(e.matricesWeightsExtra));else if(!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let i=0,r=0,s=0,n=[],a=null,o=[];for(let t of this.splitBasedOnMaterialID())o.push({vertexData:t,transform:e});for(let e of t)for(let t of e.vertexData.splitBasedOnMaterialID())o.push({vertexData:t,transform:e.transform});for(let e of(o.sort((e,t)=>{let i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,r=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>r?1:i===r?0:-1}),o)){let t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,a&&a.materialIndex===i)a.indexCount+=t.indices.length,a.verticesCount+=t.positions.length/3;else{let e=new p;e.materialIndex=i,e.indexStart=r,e.indexCount=t.indices.length,e.verticesStart=s,e.verticesCount=t.positions.length/3,n.push(e),a=e}r+=t.indices.length,s+=t.positions.length/3}let l=o.splice(0,1)[0];f=l.vertexData,e=l.transform,d=o.map(e=>e.vertexData),t=o,this.materialInfos=n}let m=d.reduce((e,t)=>{var i,r;return e+(null!==(r=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==r?r:0)},null!==(h=null===(l=f.indices)||void 0===l?void 0:l.length)&&void 0!==h?h:0),g=s||d.some(e=>e.indices===f.indices),v=g?null===(u=f.indices)||void 0===u?void 0:u.slice():f.indices;if(m>0){let s=null!==(c=null==v?void 0:v.length)&&void 0!==c?c:0;if(v||(v=Array(m)),v.length!==m){if(Array.isArray(v))v.length=m;else{let e=i||v instanceof Uint32Array?new Uint32Array(m):new Uint16Array(m);e.set(v),v=e}e&&0>e.determinant()&&_._FlipFaces(v,0,s)}let n=f.positions?f.positions.length/3:0;for(let{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t<e.indices.length;t++)v[s+t]=e.indices[t]+n;i&&0>i.determinant()&&_._FlipFaces(v,s,e.indices.length),n+=e.positions.length/3,s+=e.indices.length,r&&(yield)}}return this.indices=v,this.positions=_._MergeElement(n.o.PositionKind,f.positions,e,t.map(e=>[e.vertexData.positions,e.transform])),r&&(yield),f.normals&&(this.normals=_._MergeElement(n.o.NormalKind,f.normals,e,t.map(e=>[e.vertexData.normals,e.transform])),r&&(yield)),f.tangents&&(this.tangents=_._MergeElement(n.o.TangentKind,f.tangents,e,t.map(e=>[e.vertexData.tangents,e.transform])),r&&(yield)),f.uvs&&(this.uvs=_._MergeElement(n.o.UVKind,f.uvs,e,t.map(e=>[e.vertexData.uvs,e.transform])),r&&(yield)),f.uvs2&&(this.uvs2=_._MergeElement(n.o.UV2Kind,f.uvs2,e,t.map(e=>[e.vertexData.uvs2,e.transform])),r&&(yield)),f.uvs3&&(this.uvs3=_._MergeElement(n.o.UV3Kind,f.uvs3,e,t.map(e=>[e.vertexData.uvs3,e.transform])),r&&(yield)),f.uvs4&&(this.uvs4=_._MergeElement(n.o.UV4Kind,f.uvs4,e,t.map(e=>[e.vertexData.uvs4,e.transform])),r&&(yield)),f.uvs5&&(this.uvs5=_._MergeElement(n.o.UV5Kind,f.uvs5,e,t.map(e=>[e.vertexData.uvs5,e.transform])),r&&(yield)),f.uvs6&&(this.uvs6=_._MergeElement(n.o.UV6Kind,f.uvs6,e,t.map(e=>[e.vertexData.uvs6,e.transform])),r&&(yield)),f.colors&&(this.colors=_._MergeElement(n.o.ColorKind,f.colors,e,t.map(e=>[e.vertexData.colors,e.transform])),r&&(yield)),f.matricesIndices&&(this.matricesIndices=_._MergeElement(n.o.MatricesIndicesKind,f.matricesIndices,e,t.map(e=>[e.vertexData.matricesIndices,e.transform])),r&&(yield)),f.matricesWeights&&(this.matricesWeights=_._MergeElement(n.o.MatricesWeightsKind,f.matricesWeights,e,t.map(e=>[e.vertexData.matricesWeights,e.transform])),r&&(yield)),f.matricesIndicesExtra&&(this.matricesIndicesExtra=_._MergeElement(n.o.MatricesIndicesExtraKind,f.matricesIndicesExtra,e,t.map(e=>[e.vertexData.matricesIndicesExtra,e.transform])),r&&(yield)),f.matricesWeightsExtra&&(this.matricesWeightsExtra=_._MergeElement(n.o.MatricesWeightsExtraKind,f.matricesWeightsExtra,e,t.map(e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,r){let s=r.filter(e=>null!==e[0]&&void 0!==e[0]);if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));let a=s.reduce((e,t)=>e+t[0].length,t.length),o=e===n.o.PositionKind?_._TransformVector3Coordinates:e===n.o.NormalKind?_._TransformVector3Normals:e===n.o.TangentKind?_._TransformVector4Normals:()=>{};if(t instanceof Float32Array){let e=new Float32Array(a);e.set(t),i&&o(e,i,0,t.length);let r=t.length;for(let[t,i]of s)e.set(t,r),i&&o(e,i,r,t.length),r+=t.length;return e}{let e=Array(a);for(let i=0;i<t.length;i++)e[i]=t[i];i&&o(e,i,0,t.length);let r=t.length;for(let[t,i]of s){for(let i=0;i<t.length;i++)e[r+i]=t[i];i&&o(e,i,r,t.length),r+=t.length}return e}}_validate(){if(!this.positions)throw new c.LH("Positions are required",c.SM.MeshInvalidPositionsError);let e=(e,t)=>{let i=n.o.DeduceStride(e);if(t.length%i!=0)throw Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(n.o.PositionKind,this.positions),i=(i,r)=>{let s=e(i,r);if(s!==t)throw Error("The "+i+"s element count ("+s+") does not match the positions count ("+t+")")};this.normals&&i(n.o.NormalKind,this.normals),this.tangents&&i(n.o.TangentKind,this.tangents),this.uvs&&i(n.o.UVKind,this.uvs),this.uvs2&&i(n.o.UV2Kind,this.uvs2),this.uvs3&&i(n.o.UV3Kind,this.uvs3),this.uvs4&&i(n.o.UV4Kind,this.uvs4),this.uvs5&&i(n.o.UV5Kind,this.uvs5),this.uvs6&&i(n.o.UV6Kind,this.uvs6),this.colors&&i(n.o.ColorKind,this.colors),this.matricesIndices&&i(n.o.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(n.o.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){let e=this.serialize();return _.Parse(e)}serialize(){let e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors)),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos)for(let t of(e.materialInfos=[],this.materialInfos)){let i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}return e}static ExtractFromMesh(e,t,i){return _._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return _._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){let r=new _;return e.isVerticesDataPresent(n.o.PositionKind)&&(r.positions=e.getVerticesData(n.o.PositionKind,t,i)),e.isVerticesDataPresent(n.o.NormalKind)&&(r.normals=e.getVerticesData(n.o.NormalKind,t,i)),e.isVerticesDataPresent(n.o.TangentKind)&&(r.tangents=e.getVerticesData(n.o.TangentKind,t,i)),e.isVerticesDataPresent(n.o.UVKind)&&(r.uvs=e.getVerticesData(n.o.UVKind,t,i)),e.isVerticesDataPresent(n.o.UV2Kind)&&(r.uvs2=e.getVerticesData(n.o.UV2Kind,t,i)),e.isVerticesDataPresent(n.o.UV3Kind)&&(r.uvs3=e.getVerticesData(n.o.UV3Kind,t,i)),e.isVerticesDataPresent(n.o.UV4Kind)&&(r.uvs4=e.getVerticesData(n.o.UV4Kind,t,i)),e.isVerticesDataPresent(n.o.UV5Kind)&&(r.uvs5=e.getVerticesData(n.o.UV5Kind,t,i)),e.isVerticesDataPresent(n.o.UV6Kind)&&(r.uvs6=e.getVerticesData(n.o.UV6Kind,t,i)),e.isVerticesDataPresent(n.o.ColorKind)&&(r.colors=e.getVerticesData(n.o.ColorKind,t,i)),e.isVerticesDataPresent(n.o.MatricesIndicesKind)&&(r.matricesIndices=e.getVerticesData(n.o.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(n.o.MatricesWeightsKind)&&(r.matricesWeights=e.getVerticesData(n.o.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(n.o.MatricesIndicesExtraKind)&&(r.matricesIndicesExtra=e.getVerticesData(n.o.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(n.o.MatricesWeightsExtraKind)&&(r.matricesWeightsExtra=e.getVerticesData(n.o.MatricesWeightsExtraKind,t,i)),r.indices=e.getIndices(t,i),r}static CreateRibbon(e){throw(0,a.S)("ribbonBuilder")}static CreateBox(e){throw(0,a.S)("boxBuilder")}static CreateTiledBox(e){throw(0,a.S)("tiledBoxBuilder")}static CreateTiledPlane(e){throw(0,a.S)("tiledPlaneBuilder")}static CreateSphere(e){throw(0,a.S)("sphereBuilder")}static CreateCylinder(e){throw(0,a.S)("cylinderBuilder")}static CreateTorus(e){throw(0,a.S)("torusBuilder")}static CreateLineSystem(e){throw(0,a.S)("linesBuilder")}static CreateDashedLines(e){throw(0,a.S)("linesBuilder")}static CreateGround(e){throw(0,a.S)("groundBuilder")}static CreateTiledGround(e){throw(0,a.S)("groundBuilder")}static CreateGroundFromHeightMap(e){throw(0,a.S)("groundBuilder")}static CreatePlane(e){throw(0,a.S)("planeBuilder")}static CreateDisc(e){throw(0,a.S)("discBuilder")}static CreatePolygon(e,t,i,r,s,n,o){throw(0,a.S)("polygonBuilder")}static CreateIcoSphere(e){throw(0,a.S)("icoSphereBuilder")}static CreatePolyhedron(e){throw(0,a.S)("polyhedronBuilder")}static CreateCapsule(e={orientation:s.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw(0,a.S)("capsuleBuilder")}static CreateTorusKnot(e){throw(0,a.S)("torusKnotBuilder")}static ComputeNormals(e,t,i,r){let n=0,a=0,o=0,l=0,h=0,u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=0,v=0,T=0,x=0,S=0,E=0,C=0,b=0,y=!1,A=!1,R=!1,P=!1,I=1,M=0,D=null;r&&(y=!!r.facetNormals,A=!!r.facetPositions,R=!!r.facetPartitioning,I=!0===r.useRightHandedSystem?-1:1,M=r.ratio||0,P=!!r.depthSort,D=r.distanceTo,P&&void 0===D&&(D=s.P.Zero()));let O=0,N=0,F=0,L=0;for(R&&r&&r.bbSize&&(O=r.subDiv.X*M/r.bbSize.x,N=r.subDiv.Y*M/r.bbSize.y,F=r.subDiv.Z*M/r.bbSize.z,L=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0),n=0;n<e.length;n++)i[n]=0;let w=t.length/3|0;for(n=0;n<w;n++){if(g=(m=3*t[3*n])+1,v=m+2,x=(T=3*t[3*n+1])+1,S=T+2,C=(E=3*t[3*n+2])+1,b=E+2,a=e[m]-e[T],o=e[g]-e[x],l=e[v]-e[S],h=e[E]-e[T],u=e[C]-e[x],f=0===(f=Math.sqrt((d=I*(o*(c=e[b]-e[S])-l*u))*d+(p=I*(l*h-a*c))*p+(_=I*(a*u-o*h))*_))?1:f,d/=f,p/=f,_/=f,y&&r&&(r.facetNormals[n].x=d,r.facetNormals[n].y=p,r.facetNormals[n].z=_),A&&r&&(r.facetPositions[n].x=(e[m]+e[T]+e[E])/3,r.facetPositions[n].y=(e[g]+e[x]+e[C])/3,r.facetPositions[n].z=(e[v]+e[S]+e[b])/3),R&&r){let t=Math.floor((r.facetPositions[n].x-r.bInfo.minimum.x*M)*O),i=Math.floor((r.facetPositions[n].y-r.bInfo.minimum.y*M)*N),s=Math.floor((r.facetPositions[n].z-r.bInfo.minimum.z*M)*F),a=Math.floor((e[m]-r.bInfo.minimum.x*M)*O),o=Math.floor((e[g]-r.bInfo.minimum.y*M)*N),l=Math.floor((e[v]-r.bInfo.minimum.z*M)*F),h=Math.floor((e[T]-r.bInfo.minimum.x*M)*O),u=Math.floor((e[x]-r.bInfo.minimum.y*M)*N),c=Math.floor((e[S]-r.bInfo.minimum.z*M)*F),d=Math.floor((e[E]-r.bInfo.minimum.x*M)*O),p=Math.floor((e[C]-r.bInfo.minimum.y*M)*N),_=Math.floor((e[b]-r.bInfo.minimum.z*M)*F),f=a+r.subDiv.max*o+L*l,y=h+r.subDiv.max*u+L*c,A=d+r.subDiv.max*p+L*_,R=t+r.subDiv.max*i+L*s;r.facetPartitioning[R]=r.facetPartitioning[R]?r.facetPartitioning[R]:[],r.facetPartitioning[f]=r.facetPartitioning[f]?r.facetPartitioning[f]:[],r.facetPartitioning[y]=r.facetPartitioning[y]?r.facetPartitioning[y]:[],r.facetPartitioning[A]=r.facetPartitioning[A]?r.facetPartitioning[A]:[],r.facetPartitioning[f].push(n),y!=f&&r.facetPartitioning[y].push(n),A==y||A==f||r.facetPartitioning[A].push(n),R==f||R==y||R==A||r.facetPartitioning[R].push(n)}if(P&&r&&r.facetPositions){let e=r.depthSortedFacets[n];e.ind=3*n,e.sqDistance=s.P.DistanceSquared(r.facetPositions[n],D)}i[m]+=d,i[g]+=p,i[v]+=_,i[T]+=d,i[x]+=p,i[S]+=_,i[E]+=d,i[C]+=p,i[b]+=_}for(n=0;n<i.length/3;n++)d=i[3*n],p=i[3*n+1],_=i[3*n+2],f=0===(f=Math.sqrt(d*d+p*p+_*_))?1:f,d/=f,p/=f,_/=f,i[3*n]=d,i[3*n+1]=p,i[3*n+2]=_}static _ComputeSides(e,t,i,r,n,a,o){let l,h;let u=i.length,c=r.length;switch(e=e||_.DEFAULTSIDE){case _.FRONTSIDE:break;case _.BACKSIDE:for(l=0;l<u;l+=3){let e=i[l];i[l]=i[l+2],i[l+2]=e}for(h=0;h<c;h++)r[h]=-r[h];break;case _.DOUBLESIDE:{let e=t.length,d=e/3;for(let i=0;i<e;i++)t[e+i]=t[i];for(l=0;l<u;l+=3)i[l+u]=i[l+2]+d,i[l+1+u]=i[l+1]+d,i[l+2+u]=i[l]+d;for(h=0;h<c;h++)r[c+h]=-r[h];let p=n.length,_=0;for(_=0;_<p;_++)n[_+p]=n[_];for(l=0,a=a||new s.Lt(0,0,1,1),o=o||new s.Lt(0,0,1,1),_=0;l<p/2;l++)n[_]=a.x+(a.z-a.x)*n[_],n[_+1]=a.y+(a.w-a.y)*n[_+1],n[_+p]=o.x+(o.z-o.x)*n[_+p],n[_+p+1]=o.y+(o.w-o.y)*n[_+p+1],_+=2}}}static Parse(e){let t=new _,i=e.positions;i&&t.set(i,n.o.PositionKind);let r=e.normals;r&&t.set(r,n.o.NormalKind);let s=e.tangents;s&&t.set(s,n.o.TangentKind);let a=e.uvs;a&&t.set(a,n.o.UVKind);let l=e.uvs2;l&&t.set(l,n.o.UV2Kind);let h=e.uvs3;h&&t.set(h,n.o.UV3Kind);let u=e.uvs4;u&&t.set(u,n.o.UV4Kind);let c=e.uvs5;c&&t.set(c,n.o.UV5Kind);let d=e.uvs6;d&&t.set(d,n.o.UV6Kind);let f=e.colors;f&&t.set(o.HE.CheckColors4(f,i.length/3),n.o.ColorKind);let m=e.matricesIndices;m&&t.set(m,n.o.MatricesIndicesKind);let g=e.matricesWeights;g&&t.set(g,n.o.MatricesWeightsKind);let v=e.indices;v&&(t.indices=v);let T=e.materialInfos;if(T)for(let e of(t.materialInfos=[],T)){let i=new p;i.indexCount=e.indexCount,i.indexStart=e.indexStart,i.verticesCount=e.verticesCount,i.verticesStart=e.verticesStart,i.materialIndex=e.materialIndex,t.materialInfos.push(i)}return t}static ImportVertexData(e,t){let i=_.Parse(e);t.setAllVerticesData(i,e.updatable)}}_.FRONTSIDE=0,_.BACKSIDE=1,_.DOUBLESIDE=2,_.DEFAULTSIDE=0,_._UniqueIDGenerator=0,(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],_,"_TransformVector3Coordinates",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],_,"_TransformVector3Normals",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],_,"_TransformVector4Normals",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],_,"_FlipFaces",null)},8675:function(e,t,i){i.d(t,{g:function(){return r}});class r{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}},1813:function(e,t,i){i.d(t,{P:function(){return l}});var r=i(7620),s=i(7796),n=i(6886),a=i(4316),o=i(1470);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;let i=null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0);i.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 o.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,r=!0){let s=this._drawWrapper;s.setEffect(e,t,r),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e){this._removeDrawWrapper(e);return}for(let e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,n,a,o=!0){return new l(e,t,i,r,s,n,a,o)}constructor(e,t,i,r,s,n,a,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=a||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,o&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal?this._mesh.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(){let e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var t;let 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)){let 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){let t;if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(r.o.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;let i=this._renderingMesh.getIndices();if(0===this.indexStart&&this.indexCount===i.length){let e=this._renderingMesh.getBoundingInfo();t={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else t=(0,a.y)(e,i,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(t.minimum,t.maximum):this._boundingInfo=new n.j(t.minimum,t.maximum),this}_checkCollision(e){let t=this.getBoundingInfo();return t._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){let t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){let 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){let i=[];for(let t=this.indexStart;t<this.indexStart+this.indexCount;t+=3)i.push(e[t],e[t+1],e[t+1],e[t+2],e[t+2],e[t]);this._linesIndexBuffer=t.createIndexBuffer(i),this._linesIndexCount=i.length}return this._linesIndexBuffer}canIntersects(e){let t=this.getBoundingInfo();return!!t&&e.intersectsBox(t.boundingBox)}intersects(e,t,i,r,s){let n=this.getMaterial();if(!n)return null;let a=3,o=!1;switch(n.fillMode){case 3:case 5:case 6:case 8:return null;case 7:a=1,o=!0}return 4===n.fillMode?i.length?this._intersectLines(e,t,i,this._mesh.intersectionThreshold,r):this._intersectUnIndexedLines(e,t,i,this._mesh.intersectionThreshold,r):!i.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,i,r,s):this._intersectTriangles(e,t,i,a,o,r,s)}_intersectLines(e,t,i,r,n){let a=null;for(let o=this.indexStart;o<this.indexStart+this.indexCount;o+=2){let l=t[i[o]],h=t[i[o+1]],u=e.intersectionSegment(l,h,r);if(!(u<0)&&(n||!a||u<a.distance)&&((a=new s.c(null,null,u)).faceId=o/2,n))break}return a}_intersectUnIndexedLines(e,t,i,r,n){let a=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=2){let o=t[i],l=t[i+1],h=e.intersectionSegment(o,l,r);if(!(h<0)&&(n||!a||h<a.distance)&&((a=new s.c(null,null,h)).faceId=i/2,n))break}return a}_intersectTriangles(e,t,i,r,s,n,a){let o=null,l=-1;for(let h=this.indexStart;h<this.indexStart+this.indexCount-(3-r);h+=r){l++;let r=i[h],u=i[h+1],c=i[h+2];if(s&&4294967295===c){h+=2;continue}let d=t[r],p=t[u],_=t[c];if(!d||!p||!_||a&&!a(d,p,_,e,r,u,c))continue;let f=e.intersectsTriangle(d,p,_);if(f){if(f.distance<0)continue;if((n||!o||f.distance<o.distance)&&((o=f).faceId=l,n))break}}return o}_intersectUnIndexedTriangles(e,t,i,r,s){let n=null;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=3){let a=t[i],o=t[i+1],l=t[i+2];if(s&&!s(a,o,l,e,-1,-1,-1))continue;let h=e.intersectsTriangle(a,o,l);if(h){if(h.distance<0)continue;if((r||!n||h.distance<n.distance)&&((n=h).faceId=i/3,r))break}}return n}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){let i=new l(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){let e=this.getBoundingInfo();if(!e)return i;i._boundingInfo=new n.j(e.minimum,e.maximum)}return i}dispose(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);let e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1),this.resetDrawCache()}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,i,r,s,n=!0){let a=Number.MAX_VALUE,o=-Number.MAX_VALUE,h=s||r,u=h.getIndices();for(let e=t;e<t+i;e++){let t=u[e];t<a&&(a=t),t>o&&(o=t)}return new l(e,a,o-a+1,t,i,r,s,n)}}},2469:function(e,t,i){i.d(t,{Y:function(){return u}});var r=i(6851),s=i(6816),n=i(6702),a=i(1823),o=i(9747),l=i(5980);let h=a.y3.Compose(a.P.One(),a._f.FromEulerAngles(0,Math.PI,0),a.P.Zero());class u extends o.N{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&u.BILLBOARDMODE_USE_POSITION)!=0,this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==u.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 a.P(0,0,1),this._up=new a.P(0,1,0),this._right=new a.P(1,0,0),this._position=a.P.Zero(),this._rotation=a.P.Zero(),this._rotationQuaternion=null,this._scaling=a.P.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=u.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=a.y3.Zero(),this._usePivotMatrix=!1,this._absolutePosition=a.P.Zero(),this._absoluteScaling=a.P.Zero(),this._absoluteRotationQuaternion=a._f.Identity(),this._pivotMatrix=a.y3.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new n.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 a.P.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return a.P.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return a.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=a.y3.Identity()),this._poseMatrix}_isSynchronized(){let e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===u.BILLBOARDMODE_NONE&&!e.pivotMatrixUpdated&&!this._infiniteDistance&&!this._position._isDirty&&!this._scaling._isDirty&&(!this._rotationQuaternion||!this._rotationQuaternion._isDirty)&&!this._rotation._isDirty}_initCache(){super._initCache();let 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=a.y3.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);for(let e of(r&&i&&i(this,r),this.getChildTransformNodes(!0)))e.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||a._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){let t,i,r;if(!e)return this;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){let e=a.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),a.P.TransformCoordinatesFromFloatsToRef(t,i,r,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=a.P.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();let e=a.jp.Matrix[0];return this._localMatrix.invertToRef(e),a.P.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=a.P.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=l.T.LOCAL){let n=u._LookAtVectorCache,o=s===l.T.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,r),s===l.T.WORLD&&this.parent){if(this.rotationQuaternion){let e=a.jp.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);let t=a.jp.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{let e=a.jp.Quaternion[0];a._f.FromEulerVectorToRef(this.rotation,e);let t=a.jp.Matrix[0];e.toRotationMatrix(t);let i=a.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){let t=a.P.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return a.P.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){let s=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?a._f.RotationYawPitchRollToRef(s+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=l.T.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);let i=this.getWorldMatrix();if(t==l.T.WORLD){let t=a.jp.Matrix[0];i.invertToRef(t),e=a.P.TransformCoordinates(e,t)}return this.setPivotMatrix(a.y3.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){let e=a.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(){let e=a.P.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),a.P.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(let t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;let r=a.jp.Quaternion[0],s=a.jp.Vector3[0],n=a.jp.Vector3[1],o=a.jp.Matrix[1];a.y3.IdentityToRef(o);let l=a.jp.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=u._TmpRotation,a._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),a.y3.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(n,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(a.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(!0),0>e.getFinalMatrix().determinant()&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(0>this.parent.getWorldMatrix().determinant()&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==l.T.LOCAL){if(this.parent){let t=a.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(t),e=a.P.TransformNormal(e,t)}(r=a._f.RotationAxisToRef(e,t,u._RotationAxisCache)).multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=a._f.RotationAxisToRef(e,t,u._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=a._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));let r=a.jp.Vector3[0],s=a.jp.Vector3[1],n=a.jp.Vector3[2],o=a.jp.Quaternion[0],l=a.jp.Matrix[0],h=a.jp.Matrix[1],u=a.jp.Matrix[2],c=a.jp.Matrix[3];return e.subtractToRef(this.position,r),a.y3.TranslationToRef(r.x,r.y,r.z,l),a.y3.TranslationToRef(-r.x,-r.y,-r.z,h),a.y3.RotationAxisToRef(t,i,u),h.multiplyToRef(u,c),c.multiplyToRef(l,c),c.decompose(s,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){let r=e.scale(t);if(i&&i!==l.T.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(r));else{let e=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=a.jp.Quaternion[1],a._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));let s=a.jp.Quaternion[0];return a._f.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==u.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){let i;if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;let r=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===r||this.isSynchronized()))return this._currentRenderId=r,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();let s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=r,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;let n=this._getEffectiveParent(),o=u._TmpScaling,l=this._position;if(this._infiniteDistance&&!this.parent&&t){let e=t.getWorldMatrix(),i=new a.P(e.m[12],e.m[13],e.m[14]);(l=u._TmpTranslation).copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(o.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion){if(this._rotationQuaternion._isDirty=!1,i=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion){let e=this.rotation.lengthSquared();e&&(this._rotationQuaternion.multiplyInPlace(a._f.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else i=u._TmpRotation,a._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,i);if(this._usePivotMatrix){let e=a.jp.Matrix[1];a.y3.ScalingToRef(o.x,o.y,o.z,e);let t=a.jp.Matrix[0];i.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,a.jp.Matrix[4]),a.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 a.y3.ComposeToRef(o,i,l,this._localMatrix);if(n&&n.getWorldMatrix){if(e&&n.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),a.jp.Matrix[7])}else a.jp.Matrix[7].copyFrom(n.getWorldMatrix());let e=a.jp.Vector3[5],t=a.jp.Vector3[6],i=a.jp.Quaternion[0];a.jp.Matrix[7].decompose(t,i,e),a.y3.ScalingToRef(t.x,t.y,t.z,a.jp.Matrix[7]),a.jp.Matrix[7].setTranslation(e),u.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(a.jp.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),a.jp.Matrix[6]),a.jp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(n.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){let e=a.jp.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),a.jp.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&a.jp.Matrix[1].multiplyToRef(h,a.jp.Matrix[1]),a.jp.Matrix[1].setTranslationFromFloats(0,0,0),a.jp.Matrix[1].invertToRef(a.jp.Matrix[0]),(this.billboardMode&u.BILLBOARDMODE_ALL)!==u.BILLBOARDMODE_ALL){a.jp.Matrix[0].decompose(void 0,a.jp.Quaternion[0],void 0);let e=a.jp.Vector3[1];a.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&u.BILLBOARDMODE_X)!==u.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&u.BILLBOARDMODE_Y)!==u.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&u.BILLBOARDMODE_Z)!==u.BILLBOARDMODE_Z&&(e.z=0),a.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,a.jp.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(a.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(a.jp.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){let e=a.jp.Vector3[0];this._worldMatrix.getTranslationToRef(e);let i=t.globalPosition;this._worldMatrix.invertToRef(a.jp.Matrix[1]);let r=a.jp.Vector3[1];a.P.TransformCoordinatesToRef(i,a.jp.Matrix[1],r),r.normalize();let s=-Math.atan2(r.z,r.x)+Math.PI/2,n=Math.sqrt(r.x*r.x+r.z*r.z),o=-Math.atan2(r.y,n);if(a._f.RotationYawPitchRollToRef(s,o,0,a.jp.Quaternion[0]),(this.billboardMode&u.BILLBOARDMODE_ALL)!==u.BILLBOARDMODE_ALL){let e=a.jp.Vector3[1];a.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&u.BILLBOARDMODE_X)!==u.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&u.BILLBOARDMODE_Y)!==u.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&u.BILLBOARDMODE_Z)!==u.BILLBOARDMODE_Z&&(e.z=0),a.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,a.jp.Matrix[0])}else a.y3.FromQuaternionToRef(a.jp.Quaternion[0],a.jp.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(a.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(a.jp.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):n&&n._nonUniformScaling?this._updateNonUniformScalingState(n._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=a.y3.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){let e=this.getChildren();for(let t=0;t<e.length;++t){let i=e[t];if(i){i.computeWorldMatrix();let e=a.jp.Matrix[0];i._localMatrix.multiplyToRef(this._localMatrix,e);let t=a.jp.Quaternion[0];e.decompose(i.scaling,t,i.position),i.rotationQuaternion?i.rotationQuaternion.copyFrom(t):t.toEulerAnglesToRef(i.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=a._f.Identity()),this._worldMatrix=a.y3.Identity()}_afterComputeWorldMatrix(){}registerAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this}unregisterAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this}getPositionInCameraSpace(e=null){return e||(e=this.getScene().activeCamera),a.P.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(e,t,i){let r=s.p4.Clone(()=>new u(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;i<t.length;i++){let s=t[i];s.clone&&s.clone(e+"."+s.name,r)}}return r}serialize(e){let t=s.p4.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),t}static Parse(e,t,i){let r=s.p4.Parse(()=>new u(e.name,t),e,t,i);return e.localMatrix?r.setPreTransformMatrix(a.y3.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(a.y3.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r}getChildTransformNodes(e,t){let i=[];return this._getDescendants(i,e,e=>(!t||t(e))&&e instanceof u),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){let e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){let e=this.getChildTransformNodes(!0);for(let t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));let n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),o=Math.max(a.x,a.y,a.z);return 0===o||(this.scaling.scaleInPlace(1/o),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r))),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}u.BILLBOARDMODE_NONE=0,u.BILLBOARDMODE_X=1,u.BILLBOARDMODE_Y=2,u.BILLBOARDMODE_Z=4,u.BILLBOARDMODE_ALL=7,u.BILLBOARDMODE_USE_POSITION=128,u.BillboardUseParentOrientation=!1,u._TmpRotation=a._f.Zero(),u._TmpScaling=a.P.Zero(),u._TmpTranslation=a.P.Zero(),u._LookAtVectorCache=new a.P(0,0,0),u._RotationAxisCache=new a._f,(0,r.gn)([(0,s.hd)("position")],u.prototype,"_position",void 0),(0,r.gn)([(0,s.hd)("rotation")],u.prototype,"_rotation",void 0),(0,r.gn)([(0,s.mv)("rotationQuaternion")],u.prototype,"_rotationQuaternion",void 0),(0,r.gn)([(0,s.hd)("scaling")],u.prototype,"_scaling",void 0),(0,r.gn)([(0,s.qC)("billboardMode")],u.prototype,"_billboardMode",void 0),(0,r.gn)([(0,s.qC)()],u.prototype,"scalingDeterminant",void 0),(0,r.gn)([(0,s.qC)("infiniteDistance")],u.prototype,"_infiniteDistance",void 0),(0,r.gn)([(0,s.qC)()],u.prototype,"ignoreNonUniformScaling",void 0),(0,r.gn)([(0,s.qC)()],u.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0)},2703:function(e,t,i){i.d(t,{q:function(){return r}});class r{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,e=>(e=e.slice(1,e.length-1),r._HandleParenthesisContent(e,t))):r._HandleParenthesisContent(e,t))||"false"!==e&&r.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);let s=e.split("||");for(let e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let n=r._SimplifyNegation(s[e].trim()),a=n.split("&&");if(a.length>1)for(let e=0;e<a.length;++e){let s=r._SimplifyNegation(a[e].trim());if(!(i="true"!==s&&"false"!==s?"!"===s[0]?!t(s.substring(1)):t(s):"true"===s)){n="false";break}}if(i||"true"===n){i=!0;break}i="true"!==n&&"false"!==n?"!"===n[0]?!t(n.substring(1)):t(n):"true"===n}return i?"true":"false"}static _SimplifyNegation(e){return"!true"===(e=(e=e.replace(/^[\s!]+/,e=>(e=e.replace(/[\s]/g,()=>"")).length%2?"!":"")).trim())?e="false":"!false"===e&&(e="true"),e}}},4046:function(e,t,i){i.d(t,{B:function(){return r},M:function(){return n}});class r{static BuildArray(e,t){let i=[];for(let r=0;r<e;++r)i.push(t());return i}static BuildTuple(e,t){return r.BuildArray(e,t)}}let s=["push","splice","pop","shift","unshift"];function n(e,t){let i=s.map(i=>(function(e,t,i){let r=e[t];if("function"!=typeof r)return null;let s=function(){let r=e.length,n=s.previous.apply(e,arguments);return i(t,r),n};return r.next=s,s.previous=r,e[t]=s,()=>{let i=s.previous;if(!i)return;let r=s.next;r?(i.next=r,r.previous=i):(i.next=void 0,e[t]=i),s.next=void 0,s.previous=void 0}})(e,i,t));return()=>{i.forEach(e=>{null==e||e()})}}},9357:function(e,t,i){function r(e,t,i){try{let r=e.next();r.done?t(r):r.value?r.value.then(()=>{r.value=void 0,t(r)},i):t(r)}catch(e){i(e)}}function s(e=25){let t;return(i,s,n)=>{let a=performance.now();void 0===t||a-t>e?(t=a,setTimeout(()=>{r(i,s,n)},0)):r(i,s,n)}}function n(e,t,i,r,s){let n=()=>{let a;let o=e=>{e.done?i(e.value):void 0===a?a=!0:n()};do a=void 0,s&&s.aborted?r(Error("Aborted")):t(e,o,r),void 0===a&&(a=!1);while(a)};n()}function a(e,t){let i;return n(e,r,e=>i=e,e=>{throw e},t),i}function o(e,t,i){return new Promise((r,s)=>{n(e,t,r,s,i)})}function l(e,t){return(...i)=>a(e(...i),t)}i.d(t,{KO:function(){return s},WP:function(){return r},s3:function(){return a},sM:function(){return o},vp:function(){return l}})},6816:function(e,t,i){i.d(t,{G6:function(){return R},N$:function(){return x},QC:function(){return g},RR:function(){return T},VE:function(){return y},XX:function(){return S},hd:function(){return v},mv:function(){return C},n9:function(){return f},oQ:function(){return b},oU:function(){return _},p4:function(){return A},qC:function(){return p},qQ:function(){return m},rX:function(){return E},wz:function(){return d}});var r=i(8772),s=i(1823),n=i(4620),a=i(6762);let o={},l={},h=function(e,t,i,s={}){let n=e();r.$&&r.$.HasTags(t)&&r.$.AddTagsTo(n,r.$.GetTags(t,!0));let a=u(n),o={};for(let e in a){let r=a[e],l=t[e],h=r.type;if(null!=l&&("uniqueId"!==e||A.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:n[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&o[l.uniqueId]?n[e]=o[l.uniqueId]:(n[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=n[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:n[e]=i?l:l.clone()}}return n};function u(e){let t=e.getClassName();if(l[t])return l[t];l[t]={};let i=l[t],r=e,s=t;for(;s;){let e;let t=o[s];for(let e in t)i[e]=t[e];let n=!1;do{if(!(e=Object.getPrototypeOf(r)).getClassName){n=!0;break}if(e.getClassName()!==s)break;r=e}while(e);if(n)break;s=e.getClassName(),r=e}return i}function c(e,t){return(i,r)=>{let s=function(e){let t=e.getClassName();return o[t]||(o[t]={}),o[t]}(i);s[r]||(s[r]={type:e,sourceName:t})}}function d(e,t=null){return function(e,t=null){return(i,r)=>{let s=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]===t||(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function p(e){return c(0,e)}function _(e){return c(1,e)}function f(e){return c(2,e)}function m(e){return c(3,e)}function g(e){return c(4,e)}function v(e){return c(5,e)}function T(e){return c(6,e)}function x(e){return c(7,e)}function S(e){return c(8,e)}function E(e){return c(9,e)}function C(e){return c(10,e)}function b(e){return c(12,e)}function y(e){return c(11,e)}class A{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i<e.animations.length;i++){let r=e.animations[i];t.animations.push(r.serialize())}}}static Serialize(e,t){t||(t={}),r.$&&(t.tags=r.$.GetTags(e));let i=u(e);for(let r in i){let s=i[r],n=s.sourceName||r,a=s.type,o=e[r];if(null!=o&&("uniqueId"!==r||A.AllowLoadingUniqueId))switch(a){case 0:t[n]=o;break;case 1:case 3:case 7:case 9:t[n]=o.serialize();break;case 2:case 4:case 5:case 8:case 10:case 12:t[n]=o.asArray();break;case 6:case 11:t[n]=o.id}}return t}static ParseProperties(e,t,i,r){r||(r="");let n=u(t);for(let o in n){let l=n[o],h=e[l.sourceName||o],u=l.type;if(null!=h&&("uniqueId"!==o||A.AllowLoadingUniqueId))switch(u){case 0:t[o]=h;break;case 1:i&&(t[o]=A._TextureParser(h,i,r));break;case 2:t[o]=a.Wo.FromArray(h);break;case 3:t[o]=A._FresnelParametersParser(h);break;case 4:t[o]=s.FM.FromArray(h);break;case 5:t[o]=s.P.FromArray(h);break;case 6:i&&(t[o]=i.getLastMeshById(h));break;case 7:t[o]=A._ColorCurvesParser(h);break;case 8:t[o]=a.HE.FromArray(h);break;case 9:t[o]=A._ImageProcessingConfigurationParser(h);break;case 10:t[o]=s._f.FromArray(h);break;case 11:i&&(t[o]=i.getCameraById(h));break;case 12:t[o]=s.y3.FromArray(h)}}}static Parse(e,t,i,s=null){let n=e();return r.$&&r.$.AddTagsTo(n,t.tags),A.ParseProperties(t,n,i,s),n}static Clone(e,t,i={}){return h(e,t,!1,i)}static Instanciate(e,t){return h(e,t,!0)}}function R(e,t,i,r){let s=i.value;i.value=(...i)=>{let n=s;if("undefined"!=typeof _native&&_native[t]){let e=_native[t];n=r?(...t)=>r(...t)?e(...t):s(...t):e}return e[t]=n,n(...i)}}A.AllowLoadingUniqueId=!1,A._ImageProcessingConfigurationParser=e=>{throw(0,n.S)("ImageProcessingConfiguration")},A._FresnelParametersParser=e=>{throw(0,n.S)("FresnelParameters")},A._ColorCurvesParser=e=>{throw(0,n.S)("ColorCurves")},A._TextureParser=(e,t,i)=>{throw(0,n.S)("Texture")},R.filter=function(e){return(t,i,r)=>R(t,i,r,e)}},5754:function(e,t,i){i.d(t,{j:function(){return n}});var r=i(7694);let s=(e,t)=>!e||e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&("SubMesh"===e.getClassName()||"PhysicsBody"===e.getClassName())?e.clone(t):e.clone?e.clone():Array.isArray(e)?e.slice():null;class n{static DeepCopy(e,t,i,n){let a=function(e){let t=[];do Object.getOwnPropertyNames(e).forEach(function(e){-1===t.indexOf(e)&&t.push(e)});while(e=Object.getPrototypeOf(e));return t}(e);for(let o of a){if("_"===o[0]&&(!n||-1===n.indexOf(o))||o.endsWith("Observable")||i&&-1!==i.indexOf(o))continue;let a=e[o],l=typeof a;if("function"!==l)try{if("object"===l){if(a instanceof Uint8Array)t[o]=Uint8Array.from(a);else if(a instanceof Array){if(t[o]=[],a.length>0){if("object"==typeof a[0])for(let e=0;e<a.length;e++){let i=s(a[e],t);-1===t[o].indexOf(i)&&t[o].push(i)}else t[o]=a.slice(0)}}else t[o]=s(a,t)}else t[o]=a}catch(e){r.Y.Warn(e.message)}}}}},4620:function(e,t,i){i.d(t,{S:function(){return r}});function r(e){return`${e} needs to be imported before as it contains a side-effect required by your code.`}},216:function(e,t,i){function r(){return"undefined"!=typeof window}function s(){return"undefined"!=typeof navigator}function n(){return"undefined"!=typeof document}function a(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}i.d(t,{CG:function(){return r},n5:function(){return n},up:function(){return s},v:function(){return a}})},8150:function(e,t,i){i.d(t,{GU:function(){return r},LH:function(){return n},SM:function(){return s}});class r extends Error{}r._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));let s={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class n extends r{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",r._setPrototypeOf(this,n.prototype)}}},41:function(e,t,i){let r;i.d(t,{$K:function(){return M},$M:function(){return E},FV:function(){return A},Ip:function(){return b},VL:function(){return P},r6:function(){return C},rN:function(){return x},vP:function(){return y}});var s=i(3105),n=i(216),a=i(6702),o=i(4129),l=i(3367),h=i(8150),u=i(4250),c=i(76),d=i(4826),p=i(3914),_=i(7694),f=i(265);let m=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class g extends h.LH{constructor(e,t){super(e,h.SM.LoadFileError),this.name="LoadFileError",h.GU._setPrototypeOf(this,g.prototype),t instanceof s.g?this.request=t:this.file=t}}class v extends h.LH{constructor(e,t){super(e,h.SM.RequestFileError),this.request=t,this.name="RequestFileError",h.GU._setPrototypeOf(this,v.prototype)}}class T extends h.LH{constructor(e,t){super(e,h.SM.ReadFileError),this.file=t,this.name="ReadFileError",h.GU._setPrototypeOf(this,T.prototype)}}let x={DefaultRetryStrategy:l.b.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e},S=e=>e=e.replace(/#/gm,"%23"),E=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&x.CorsBehavior){if("string"==typeof x.CorsBehavior||x.CorsBehavior instanceof String)t.crossOrigin=x.CorsBehavior;else{let i=x.CorsBehavior(e);i&&(t.crossOrigin=i)}}},C=(e,t,i,r,s="",n)=>{var a;let l;let h=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(l=URL.createObjectURL(new Blob([e],{type:s})),h=!0):l=`data:${s};base64,`+(0,u.Gh)(e):e instanceof Blob?(l=URL.createObjectURL(e),h=!0):(l=S(e),l=x.PreprocessUrl(e));let c=p.l.LastCreatedEngine,d=t=>{if(i){let r=l||e.toString();i(`Error while trying to load image: ${0===r.indexOf("http")||r.length<=128?r:r.slice(0,128)+"..."}`,t)}};if("undefined"==typeof Image||null!==(a=null==c?void 0:c._features.forceBitmapOverHTMLImageElement)&&void 0!==a&&a)return y(l,r=>{c.createImageBitmap(new Blob([r],{type:s}),Object.assign({premultiplyAlpha:"none"},n)).then(e=>{t(e),h&&URL.revokeObjectURL(l)}).catch(t=>{i&&i("Error while trying to load image: "+e,t)})},void 0,r||void 0,!0,(e,t)=>{d(t)}),null;let _=new Image;E(l,_);let f=[],m=()=>{f.forEach(e=>{e.target.removeEventListener(e.name,e.handler)}),f.length=0};f.push({target:_,name:"load",handler:()=>{m(),t(_),h&&_.src&&URL.revokeObjectURL(_.src)}}),f.push({target:_,name:"error",handler:e=>{m(),d(e),h&&_.src&&URL.revokeObjectURL(_.src)}}),f.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==_.src)return;m();let t=Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);p.l.UseFallbackTexture=!1,d(t),h&&_.src&&URL.revokeObjectURL(_.src),_.src=""}}),f.forEach(e=>{e.target.addEventListener(e.name,e.handler)});let g="blob:"===l.substring(0,5),v="data:"===l.substring(0,5),T=()=>{g||v?_.src=l:y(l,(e,t,i)=>{let r=!s&&i?i:s,n=new Blob([e],{type:r}),a=URL.createObjectURL(n);h=!0,_.src=a},void 0,r||void 0,!0,(e,t)=>{d(t)})};if(!g&&!v&&r&&r.enableTexturesOffline)r.open(()=>{r&&r.loadImage(l,_)},T);else{if(-1!==l.indexOf("file:")){let 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(i){t=URL.createObjectURL(o.X.FilesToLoad[e])}_.src=t,h=!0}catch(e){_.src=""}return _}}T()}return _},b=(e,t,i,r,s)=>{let n=new FileReader,o={onCompleteObservable:new a.y$,abort:()=>n.abort()};return n.onloadend=()=>o.onCompleteObservable.notifyObservers(o),s&&(n.onerror=()=>{s(new T(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),r?n.readAsArrayBuffer(e):n.readAsText(e),o},y=(e,t,i,r,s,n,l)=>{if(e.name)return b(e,t,i,s,n?e=>{n(void 0,e)}:void 0);if(-1!==e.indexOf("file:")){let r=decodeURIComponent(e.substring(5).toLowerCase());0===r.indexOf("./")&&(r=r.substring(2));let a=o.X.FilesToLoad[r];if(a)return b(a,t,i,s,n?e=>n(void 0,new g(e.message,e.file)):void 0)}let{match:h,type:u}=I(e);if(h){let i={onCompleteObservable:new a.y$,abort:()=>()=>{}};try{let i=s?M(e):D(e);t(i,void 0,u)}catch(e){n?n(void 0,e):_.Y.Error(e.message||"Failed to parse the Data URL")}return f.Q.SetImmediate(()=>{i.onCompleteObservable.notifyObservers(i)}),i}return A(e,(e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))},i,r,s,n?e=>{n(e.request,new g(e.message,e.request))}:void 0,l)},A=(e,t,i,r,o,l,h)=>{e=S(e),e=x.PreprocessUrl(e);let u=x.BaseUrl+e,c=!1,d={onCompleteObservable:new a.y$,abort:()=>c=!0},p=()=>{let e,r=new s.g,a=null,p=()=>{r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",f))},f=()=>{p(),d.onCompleteObservable.notifyObservers(d),d.onCompleteObservable.clear(),i=void 0,e=null,f=null,l=void 0,h=void 0,t=void 0};d.abort=()=>{c=!0,f&&f(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==a&&(clearTimeout(a),a=null),r=null};let m=e=>{let t=e.message||"Unknown error";l&&r?l(new v(t,r)):_.Y.Error(t)},g=d=>{if(r){if(r.open("GET",u),h)try{h(r)}catch(e){m(e);return}o&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),f&&r.addEventListener("loadend",f),e=()=>{if(!c&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status&&(!(0,n.CG)()||R())){try{t&&t(o?r.response:r.responseText,r)}catch(e){m(e)}return}let i=x.DefaultRetryStrategy;if(i){let e=i(u,r,d);if(-1!==e){p(),r=new s.g,a=setTimeout(()=>g(d+1),e);return}}let h=new v("Error status: "+r.status+" "+r.statusText+" - Unable to load "+u,r);l&&l(h)}},r.addEventListener("readystatechange",e),r.send()}};g(0)};if(r&&r.enableSceneOffline){let s=e=>{e&&e.status>400?l&&l(e):p()};r.open(()=>{r&&r.loadFile(x.BaseUrl+e,e=>{!c&&t&&t(e),d.onCompleteObservable.notifyObservers(d)},i?e=>{!c&&i&&i(e)}:void 0,s,o)},s)}else p();return d},R=()=>"undefined"!=typeof location&&"file:"===location.protocol,P=e=>m.test(e),I=e=>{let t=m.exec(e);if(null===t||0===t.length)return{match:!1,type:""};{let e=t[0].replace("data:","").replace("base64,","");return{match:!0,type:e}}};function M(e){return(0,u.HQ)(e.split(",")[1])}let D=e=>(0,u.rP)(e.split(",")[1]);d.B._FileToolsLoadImage=C,d.B._FileToolsLoadFile=y,c.L._FileToolsLoadFile=y,Object.defineProperty(r={DecodeBase64UrlToBinary:M,DecodeBase64UrlToString:D,DefaultRetryStrategy:x.DefaultRetryStrategy,BaseUrl:x.BaseUrl,CorsBehavior:x.CorsBehavior,PreprocessUrl:x.PreprocessUrl,IsBase64DataUrl:P,IsFileURL:R,LoadFile:y,LoadImage:C,ReadFile:b,RequestFile:A,SetCorsBehavior:E},"DefaultRetryStrategy",{get:function(){return x.DefaultRetryStrategy},set:function(e){x.DefaultRetryStrategy=e}}),Object.defineProperty(r,"BaseUrl",{get:function(){return x.BaseUrl},set:function(e){x.BaseUrl=e}}),Object.defineProperty(r,"PreprocessUrl",{get:function(){return x.PreprocessUrl},set:function(e){x.PreprocessUrl=e}}),Object.defineProperty(r,"CorsBehavior",{get:function(){return x.CorsBehavior},set:function(e){x.CorsBehavior=e}})},4129:function(e,t,i){i.d(t,{X:function(){return r}});class r{}r.FilesToLoad={}},4871:function(e,t,i){i.d(t,{f:function(){return r}});function r(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}},16:function(e,t,i){i.d(t,{K:function(){return n}});var r=i(7694),s=i(9678);class n{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];let t=(0,s.q)(e);if(t)return t;r.Y.Warn(e+" not found, you may have missed an import.");let i=e.split("."),n=window||this;for(let e=0,t=i.length;e<t;e++)n=n[i[e]];return"function"!=typeof n?null:n}}n.RegisteredExternalClasses={}},7694:function(e,t,i){i.d(t,{Y:function(){return r}});class r{static _CheckLimit(e,t){let i=r._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},r._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var i;let s=r._LogLimitOutputs[e];if(!s||!r.MessageLimitReached)return;let n=this._Levels[t];s.current===s.limit&&r[n.name](r.MessageLimitReached.replace(/%LIMIT%/g,""+s.limit).replace(/%TYPE%/g,null!==(i=n.name)&&void 0!==i?i:""))}static _AddLogEntry(e){r._LogCache=e+r._LogCache,r.OnNewCacheEntry&&r.OnNewCacheEntry(e)}static _FormatMessage(e){let t=e=>e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){if(void 0!==i&&!r._CheckLimit(t,i))return;let s=r._FormatMessage(t),n=this._Levels[e];n.logFunc&&n.logFunc("BJS - "+s);let a=`<div style='color:${n.color}'>${s}</div><br>`;r._AddLogEntry(a),r._GenerateLimitMessage(t,e)}static get LogCache(){return r._LogCache}static ClearLogCache(){r._LogCache="",r._LogLimitOutputs={},r.errorsCount=0}static set LogLevels(e){r.Log=r._LogDisabled,r.Warn=r._LogDisabled,r.Error=r._LogDisabled,[r.MessageLogLevel,r.WarningLogLevel,r.ErrorLogLevel].forEach(t=>{if((e&t)===t){let e=this._Levels[t];r[e.name]=r._LogEnabled.bind(r,t)}})}}r.NoneLogLevel=0,r.MessageLogLevel=1,r.WarningLogLevel=2,r.ErrorLogLevel=4,r.AllLogLevel=7,r.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",r._LogCache="",r._LogLimitOutputs={},r._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],r.errorsCount=0,r.Log=r._LogEnabled.bind(r,r.MessageLogLevel),r.Warn=r._LogEnabled.bind(r,r.WarningLogLevel),r.Error=r._LogEnabled.bind(r,r.ErrorLogLevel)},6702:function(e,t,i){i.d(t,{he:function(){return r},y$:function(){return n}});class r{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}}class s{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class n{static FromPromise(e,t){let i=new n;return e.then(e=>{i.notifyObservers(e)}).catch(e=>{if(t)t.notifyObservers(e);else throw e}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=[],this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new r(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,n=!1){if(!e)return null;let a=new s(e,t,r);return a.unregisterOnNextCall=n,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(a,this._lastNotifiedValue),a._remove=()=>{this.remove(a)},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){if(!e)return!1;e._remove=null;let t=this._observers.indexOf(e);return -1!==t&&(this._deferUnregister(e),!0)}removeCallback(e,t){for(let i=0;i<this._observers.length;i++){let r=this._observers[i];if(!r._willBeUnregistered&&r.callback===e&&(!t||t===r.scope))return this._deferUnregister(r),!0}return!1}_deferUnregister(e){e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout(()=>{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;let i=this._observers.indexOf(e);return -1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;let n=this._eventState;for(let a of(n.mask=t,n.target=i,n.currentTarget=r,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=s,this._observers))if(!a._willBeUnregistered&&(a.mask&t&&(a.unregisterOnNextCall&&this._deferUnregister(a),a.scope?n.lastReturnValue=a.callback.apply(a.scope,[e,n]):n.lastReturnValue=a.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;let r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){let 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(){let e=new n;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(let t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}},6339:function(e,t,i){i.d(t,{z:function(){return s}});var r=i(8257);class s{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){s.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){s.Enabled&&(this._startMonitoringTime=r.F.Now)}endMonitoring(e=!0){if(!s.Enabled)return;e&&this.fetchNewFrame();let t=r.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;let e=r.F.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}s.Enabled=!0},2241:function(e,t,i){i.d(t,{A:function(){return s}});var r=i(8257);class s{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new n(e)}sampleFrame(e=r.F.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){let 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(){let 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 n{constructor(e){this._samples=Array(e),this.reset()}add(e){let t;if(this.isSaturated()){let 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;let 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){let t=this._samples.length;return(e%t+t)%t}}},8257:function(e,t,i){i.d(t,{F:function(){return s}});var r=i(216);class s{static get Now(){return(0,r.CG)()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},3367:function(e,t,i){i.d(t,{b:function(){return r}});class r{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>0!==r.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}},1945:function(e,t,i){i.d(t,{f:function(){return s},t:function(){return r}});class r{constructor(e){this.length=0,this.data=Array(e),this._id=r._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){let t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return -1!==this.indexOf(e)}}r._GlobalId=0;class s extends r{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t<e.length;t++){let i=(e.data||e)[t];this.pushNoDuplicate(i)}}}}},4346:function(e,t,i){i.d(t,{x:function(){return r}});class r{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach((e,t)=>this.add(e,t))}get(e){let 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))&&this.add(e,i),i}getOrAdd(e,t){let 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){let 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(let t in this._data){let i=this._data[t];e(t,i)}}first(e){for(let t in this._data){let i=this._data[t],r=e(t,i);if(r)return r}return null}}},4250:function(e,t,i){i.d(t,{Gh:function(){return r},HQ:function(){return n},rP:function(){return s}});let r=e=>{let t,i,r,s,n,a,o;let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",u=0,c=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;u<c.length;)t=c[u++],i=u<c.length?c[u++]:Number.NaN,r=u<c.length?c[u++]:Number.NaN,s=t>>2,n=(3&t)<<4|i>>4,a=(15&i)<<2|r>>6,o=63&r,isNaN(i)?a=o=64:isNaN(r)&&(o=64),h+=l.charAt(s)+l.charAt(n)+l.charAt(a)+l.charAt(o);return h},s=e=>atob(e),n=e=>{let t=s(e),i=t.length,r=new Uint8Array(new ArrayBuffer(i));for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r.buffer}},8772:function(e,t,i){i.d(t,{$:function(){return s}});var r=i(2703);class s{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>s.HasTags(e),e.addTags=t=>s.AddTagsTo(e,t),e.removeTags=t=>s.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>s.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;let t=e._tags;for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(!t)return e._tags;{let t=[];for(let i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}}static AddTagsTo(e,t){if(!t||"string"!=typeof t)return;let i=t.split(" ");i.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;let i=t.split(" ");for(let t in i)s._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?s.HasTags(e):r.q.Eval(t,t=>s.HasTags(e)&&e._tags[t]))}}},265:function(e,t,i){i.d(t,{Q:function(){return s}});var r=i(216);class s{static SetImmediate(e){(0,r.CG)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}},3636:function(e,t,i){i.d(t,{$g:function(){return m},w1:function(){return f}});var r=i(6702),s=i(216),n=i(7694),a=i(5754),o=i(8257),l=i(4620),h=i(3105),u=i(3914),c=i(41),d=i(265),p=i(16),_=i(4871);class f{static get BaseUrl(){return c.rN.BaseUrl}static set BaseUrl(e){c.rN.BaseUrl=e}static get DefaultRetryStrategy(){return c.rN.DefaultRetryStrategy}static set DefaultRetryStrategy(e){c.rN.DefaultRetryStrategy=e}static get CorsBehavior(){return c.rN.CorsBehavior}static set CorsBehavior(e){c.rN.CorsBehavior=e}static get UseFallbackTexture(){return u.l.UseFallbackTexture}static set UseFallbackTexture(e){u.l.UseFallbackTexture=e}static get RegisteredExternalClasses(){return p.K.RegisteredExternalClasses}static set RegisteredExternalClasses(e){p.K.RegisteredExternalClasses=e}static get fallbackTexture(){return u.l.FallbackTexture}static set fallbackTexture(e){u.l.FallbackTexture=e}static FetchToRef(e,t,i,r,s,n){let a=((Math.abs(e)*i%i|0)+(Math.abs(t)*r%r|0)*i)*4;n.r=s[a]/255,n.g=s[a+1]/255,n.b=s[a+2]/255,n.a=s[a+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return p.K.Instantiate(e)}static SetImmediate(e){d.Q.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do t*=2;while(t<e);return t===e}static FloatRound(e){return Math.fround?Math.fround(e):(f._TmpFloatArray[0]=e,f._TmpFloatArray[0])}static GetFilename(e){let t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){let i=e.lastIndexOf("/");return i<0?t?e:"":e.substring(0,i+1)}static ToDegrees(e){return 180*e/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,i=.9){let r=this.ToRadians(e),s=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-i)*Math.sin(s)+i*Math.sin(r),(1-i)*Math.cos(s)+i*Math.cos(r)))}static MakeArray(e,t){return!0!==t&&(void 0===e||null==e)?null:Array.isArray(e)?e:[e]}static GetPointerPrefix(e){let t="pointer";return(0,s.CG)()&&!window.PointerEvent&&(t="mouse"),!e._badDesktopOS||e._badOS||document&&"ontouchend"in document||(t="mouse"),t}static SetCorsBehavior(e,t){(0,c.$M)(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static CleanUrl(e){return e=e.replace(/#/gm,"%23")}static get PreprocessUrl(){return c.rN.PreprocessUrl}static set PreprocessUrl(e){c.rN.PreprocessUrl=e}static LoadImage(e,t,i,r,s,n){return(0,c.r6)(e,t,i,r,s,n)}static LoadFile(e,t,i,r,s,n){return(0,c.vP)(e,t,i,r,s,n)}static LoadFileAsync(e,t=!0){return new Promise((i,r)=>{(0,c.vP)(e,e=>{i(e)},void 0,void 0,t,(e,t)=>{r(t)})})}static LoadScript(e,t,i,r){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){null==i||i(`Unable to load script '${e}' in worker`,t)}return}if(!(0,s.CG)()){null==i||i(`Cannot load script '${e}' outside of a window or a worker`);return}let n=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),r&&(a.id=r),a.onload=()=>{t&&t()},a.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},n.appendChild(a)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(e,t)=>{i(t||Error(e))})})}static ReadFileAsDataURL(e,t,i){let s=new FileReader,n={onCompleteObservable:new r.y$,abort:()=>s.abort()};return s.onloadend=()=>{n.onCompleteObservable.notifyObservers(n)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),n}static ReadFile(e,t,i,r,s){return(0,c.Ip)(e,t,i,r,s)}static FileAsURL(e){let t=new Blob([e]),i=window.URL,r=i.createObjectURL(t);return r}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){a.j.DeepCopy(e,t,i,r)}static IsEmpty(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){let r=t[i];e.addEventListener(r.name,r.handler,!1);try{window.parent&&window.parent.addEventListener(r.name,r.handler,!1)}catch(e){}}}static UnregisterTopRootEvents(e,t){for(let i=0;i<t.length;i++){let r=t[i];e.removeEventListener(r.name,r.handler);try{e.parent&&e.parent.removeEventListener(r.name,r.handler)}catch(e){}}}static async DumpFramebuffer(e,t,i,r,s="image/png",n,a){throw(0,l.S)("DumpTools")}static DumpData(e,t,i,r,s="image/png",n,a=!1,o=!1,h){throw(0,l.S)("DumpTools")}static DumpDataAsync(e,t,i,r="image/png",s,n=!1,a=!1,o){throw(0,l.S)("DumpTools")}static _IsOffScreenCanvas(e){return void 0!==e.convertToBlob}static ToBlob(e,t,i="image/png",r){f._IsOffScreenCanvas(e)||e.toBlob||(e.toBlob=function(e,t,i){setTimeout(()=>{let r=atob(this.toDataURL(t,i).split(",")[1]),s=r.length,n=new Uint8Array(s);for(let e=0;e<s;e++)n[e]=r.charCodeAt(e);e(new Blob([n]))})}),f._IsOffScreenCanvas(e)?e.convertToBlob({type:i,quality:r}).then(e=>t(e)):e.toBlob(function(e){t(e)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){let e=new Date,i=(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2);t="screenshot_"+i+".png"}f.Download(e,t)}else if(e&&"undefined"!=typeof URL){let t=URL.createObjectURL(e),i=window.open("");if(!i)return;let r=i.document.createElement("img");r.onload=function(){URL.revokeObjectURL(t)},r.src=t,i.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if("string"!=typeof r&&t){if(t){if(f._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(e=>{let i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{let e=i.result;t(e)}});return}let r=e.toDataURL(i,s);t(r)}}else this.ToBlob(e,function(e){e&&f.DownloadBlob(e,r),t&&t("")},i,s)}static Download(e,t){if("undefined"==typeof URL)return;let i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,r,s="image/png",n=!1,a){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",s){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",n=1,a=!1,o,h=!1,u=!1,c=!0,d){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,n=!1,a,o=!1,h=!1,u=!0,c){throw(0,l.S)("ScreenshotTools")}static RandomId(){return(0,_.f)()}static IsBase64(e){return(0,c.VL)(e)}static DecodeBase64(e){return(0,c.$K)(e)}static get errorsCount(){return n.Y.errorsCount}static Log(e){n.Y.Log(e)}static Warn(e){n.Y.Warn(e)}static Error(e){n.Y.Error(e)}static get LogCache(){return n.Y.LogCache}static ClearLogCache(){n.Y.ClearLogCache()}static set LogLevels(e){n.Y.LogLevels=e}static set PerformanceLogLevel(e){if((e&f.PerformanceUserMarkLogLevel)===f.PerformanceUserMarkLogLevel){f.StartPerformanceCounter=f._StartUserMark,f.EndPerformanceCounter=f._EndUserMark;return}if((e&f.PerformanceConsoleLogLevel)===f.PerformanceConsoleLogLevel){f.StartPerformanceCounter=f._StartPerformanceConsole,f.EndPerformanceCounter=f._EndPerformanceConsole;return}f.StartPerformanceCounter=f._StartPerformanceCounterDisabled,f.EndPerformanceCounter=f._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!f._Performance){if(!(0,s.CG)())return;f._Performance=window.performance}t&&f._Performance.mark&&f._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&f._Performance.mark&&(f._Performance.mark(e+"-End"),f._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(f._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(f._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return o.F.Now}static GetClassName(e,t=!1){let i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__}i||(i=typeof e)}return i}static First(e,t){for(let i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return!!(0,s.up)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}f.UseCustomRequestHeaders=!1,f.CustomRequestHeaders=h.g.CustomRequestHeaders,f._TmpFloatArray=new Float32Array(1),f.GetDOMTextContent=s.v,f.GetAbsoluteUrl="object"==typeof document?e=>{let t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},f.NoneLogLevel=n.Y.NoneLogLevel,f.MessageLogLevel=n.Y.MessageLogLevel,f.WarningLogLevel=n.Y.WarningLogLevel,f.ErrorLogLevel=n.Y.ErrorLogLevel,f.AllLogLevel=n.Y.AllLogLevel,f.IsWindowObjectExist=s.CG,f.PerformanceNoneLogLevel=0,f.PerformanceUserMarkLogLevel=1,f.PerformanceConsoleLogLevel=2,f.StartPerformanceCounter=f._StartPerformanceCounterDisabled,f.EndPerformanceCounter=f._EndPerformanceCounterDisabled;class m{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,i,r=0){let s=new m(e,t,i,r);return s.executeNext(),s}static SyncAsyncForLoop(e,t,i,r,s,n=0){return m.Run(Math.ceil(e/t),r=>{s&&s()?r.breakLoop():setTimeout(()=>{for(let n=0;n<t;++n){let a=r.index*t+n;if(a>=e)break;if(i(a),s&&s()){r.breakLoop();break}}r.executeNext()},n)},r)}}u.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"},9678:function(e,t,i){i.d(t,{H:function(){return s},q:function(){return n}});let r={};function s(e,t){r[e]=t}function n(e){return r[e]}},2853:function(e,t,i){i.d(t,{K:function(){return r}});class r{static get UniqueId(){let e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}r._UniqueIdCounter=1},3105:function(e,t,i){i.d(t,{g:function(){return r}});class r{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(let e in r.CustomRequestHeaders){let t=r.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return r.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){r.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(let e of r.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(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)}}r.CustomRequestHeaders={},r.CustomRequestModifiers=[],r.SkipRequestModificationForBabylonCDN=!0},1970:function(e,t,i){i.d(t,{O:function(){return s}});var r=i(7620);class s{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[r.o.PositionKind])return;let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[r.o.PositionKind]=new r.o(this._scene.getEngine(),e,r.o.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){let 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(){let e=this._vertexBuffers[r.o.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){let i=this._scene.activeCamera;return!!(i&&(t=t||i._postProcesses.filter(e=>null!=e))&&0!==t.length&&this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!=t),!0)}directRender(e,t=null,i=!1,r=0,s=0,n=!1){var a;let o=this._scene.getEngine();for(let l=0;l<e.length;l++){l<e.length-1?e[l+1].activate(this._scene.activeCamera,null==t?void 0:t.texture):(t?o.bindFramebuffer(t,r,void 0,void 0,i,s):n||o.restoreDefaultFramebuffer(),null===(a=o._debugInsertMarker)||void 0===a||a.call(o,`post process ${e[l].name} output`));let h=e[l],u=h.apply();u&&(h.onBeforeRenderObservable.notifyObservers(u),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,u),o.drawElementsType(0,0,6),h.onAfterRenderObservable.notifyObservers(u))}o.setDepthBuffer(!0),o.setDepthWrite(!0)}_finalizeFrame(e,t,i,r,s=!1){var n;let a=this._scene.activeCamera;if(!a||0===(r=r||a._postProcesses.filter(e=>null!=e)).length||!this._scene.postProcessesEnabled)return;let o=this._scene.getEngine();for(let l=0,h=r.length;l<h;l++){let u=r[l];if(l<h-1?u._outputTexture=r[l+1].activate(a,null==t?void 0:t.texture):(t?(o.bindFramebuffer(t,i,void 0,void 0,s),u._outputTexture=t):(o.restoreDefaultFramebuffer(),u._outputTexture=null),null===(n=o._debugInsertMarker)||void 0===n||n.call(o,`post process ${r[l].name} output`)),e)break;let c=u.apply();c&&(u.onBeforeRenderObservable.notifyObservers(c),this._prepareBuffers(),o.bindBuffers(this._vertexBuffers,this._indexBuffer,c),o.drawElementsType(0,0,6),u.onAfterRenderObservable.notifyObservers(c))}o.setDepthBuffer(!0),o.setDepthWrite(!0),o.setAlphaMode(0)}dispose(){let e=this._vertexBuffers[r.o.PositionKind];e&&(e.dispose(),this._vertexBuffers[r.o.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}},9623:function(e,t,i){i.d(t,{S:function(){return n}});var r=i(1945),s=i(1823);class n{set opaqueSortCompareFn(e){e?this._opaqueSortCompareFn=e:this._opaqueSortCompareFn=n.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){e?this._alphaTestSortCompareFn=e:this._alphaTestSortCompareFn=n.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=n.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,s=null,n=null){this.index=e,this._opaqueSubMeshes=new r.t(256),this._transparentSubMeshes=new r.t(256),this._alphaTestSubMeshes=new r.t(256),this._depthOnlySubMeshes=new r.t(256),this._particleSystems=new r.t(256),this._spriteManagers=new r.t(256),this._empty=!0,this._edgesRenderers=new r.f(16),this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=s,this.transparentSortCompareFn=n}render(e,t,i,r){if(e){e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);return}let s=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(s.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),s.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);let n=s.getStencilBuffer();if(s.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(r),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency){if(s.setStencilBuffer(n),this._scene.useOrderIndependentTransparency){let e=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);e.length&&this._renderTransparent(e)}else this._renderTransparent(this._transparentSubMeshes);s.setAlphaMode(0)}if(s.setStencilBuffer(!1),this._edgesRenderers.length){for(let e=0;e<this._edgesRenderers.length;e++)this._edgesRenderers.data[e].render();s.setAlphaMode(0)}s.setStencilBuffer(n)}_renderOpaqueSorted(e){return n._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1)}_renderAlphaTestSorted(e){return n._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)}_renderTransparentSorted(e){return n._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0)}static _RenderSorted(e,t,i,r){let a,o=0,l=i?i.globalPosition:n._ZeroVector;if(r)for(;o<e.length;o++)(a=e.data[o])._alphaIndex=a.getMesh().alphaIndex,a._distanceToCamera=s.P.Distance(a.getBoundingInfo().boundingSphere.centerWorld,l);let h=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&h.sort(t);let u=h[0].getMesh().getScene();for(o=0;o<h.length;o++)if(a=h[o],!u._activeMeshesFrozenButKeepClipping||a.isInFrustum(u._frustumPlanes)){if(r){let e=a.getMaterial();if(e&&e.needDepthPrePass){let t=e.getScene().getEngine();t.setColorWrite(!1),t.setAlphaMode(0),a.render(!1),t.setColorWrite(!0)}}a.render(r)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:n.backToFrontSortCompare(e,t)}static backToFrontSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0}static PainterSortCompare(e,t){let i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t._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;let t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i<this._particleSystems.length;i++){let r=this._particleSystems.data[i];if(0===(t&&t.layerMask&r.layerMask))continue;let s=r.emitter;s.position&&e&&-1===e.indexOf(s)||this._scene._activeParticles.addCount(r.render(),!1)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}_renderSprites(){if(!this._scene.spritesEnabled||0===this._spriteManagers.length)return;let e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(let t=0;t<this._spriteManagers.length;t++){let i=this._spriteManagers.data[t];0!==(e&&e.layerMask&i.layerMask)&&i.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}}n._ZeroVector=s.P.Zero()},7077:function(e,t,i){i.d(t,{$:function(){return n}});var r=i(9623);class s{}class n{get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){if(e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,!this._maintainStateBetweenFrames)){for(let e of this._scene.meshes)if(e.subMeshes)for(let t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(let e of this._scene.spriteManagers)e._wasDispatched=!1;for(let e of this._scene.particleSystems)e._wasDispatched=!1}}constructor(e){this._useSceneAutoClearSetup=!1,this._renderingGroups=[],this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new s,this._maintainStateBetweenFrames=!1,this._scene=e;for(let e=n.MIN_RENDERINGGROUPS;e<n.MAX_RENDERINGGROUPS;e++)this._autoClearDepthStencil[e]={autoClear:!0,depth:!0,stencil:!0}}getRenderingGroup(e){let t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]}_clearDepthStencilBuffer(e=!0,t=!0){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)}render(e,t,i,r){let s=this._renderingGroupInfo;if(s.scene=this._scene,s.camera=this._scene.activeCamera,this._scene.spriteManagers&&r)for(let e=0;e<this._scene.spriteManagers.length;e++){let t=this._scene.spriteManagers[e];this.dispatchSprites(t)}for(let a=n.MIN_RENDERINGGROUPS;a<n.MAX_RENDERINGGROUPS;a++){this._depthStencilBufferAlreadyCleaned=a===n.MIN_RENDERINGGROUPS;let o=this._renderingGroups[a];if(!o||o._empty)continue;let l=Math.pow(2,a);if(s.renderingGroupId=a,this._scene.onBeforeRenderingGroupObservable.notifyObservers(s,l),n.AUTOCLEAR){let e=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(a):this._autoClearDepthStencil[a];e&&e.autoClear&&this._clearDepthStencilBuffer(e.depth,e.stencil)}for(let e of this._scene._beforeRenderingGroupDrawStage)e.action(a);for(let s of(o.render(e,r,i,t),this._scene._afterRenderingGroupDrawStage))s.action(a);this._scene.onAfterRenderingGroupObservable.notifyObservers(s,l)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=n.MIN_RENDERINGGROUPS;e<n.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=n.MIN_RENDERINGGROUPS;e<n.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.prepareSprites()}}dispose(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null}freeRenderingGroups(){for(let e=n.MIN_RENDERINGGROUPS;e<n.MAX_RENDERINGGROUPS;e++){let t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){void 0===this._renderingGroups[e]&&(this._renderingGroups[e]=new r.S(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))}dispatchSprites(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))}dispatchParticles(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,i))}setRenderingOrder(e,t=null,i=null,r=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=i,this._customTransparentSortCompareFn[e]=r,this._renderingGroups[e]){let t=this._renderingGroups[e];t.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],t.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],t.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:i,stencil:r}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}}n.MAX_RENDERINGGROUPS=4,n.MIN_RENDERINGGROUPS=0,n.AUTOCLEAR=!0},7339:function(e,t,i){i.d(t,{Q:function(){return r}});class r{constructor(){this._blendFunctionParameters=[,,,,],this._blendEquationParameters=[,,],this._blendConstants=[,,,,],this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,r){(this._blendConstants[0]!==e||this._blendConstants[1]!==t||this._blendConstants[2]!==i||this._blendConstants[3]!==r)&&(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=r,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,r){(this._blendFunctionParameters[0]!==e||this._blendFunctionParameters[1]!==t||this._blendFunctionParameters[2]!==i||this._blendFunctionParameters[3]!==r)&&(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=i,this._blendFunctionParameters[3]=r,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){(this._blendEquationParameters[0]!==e||this._blendEquationParameters[1]!==t)&&(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}},3430:function(e,t,i){i.d(t,{k:function(){return r}});class r{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}},2267:function(e,t,i){i.d(t,{s:function(){return r}});class r{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=r.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=r.KEEP,this.opDepthFail=r.KEEP,this.opStencilDepthPass=r.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}r.ALWAYS=519,r.KEEP=7680,r.REPLACE=7681},3076:function(e,t,i){i.d(t,{C:function(){return r}});class r{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){var e;this.stencilMaterial=void 0,null===(e=this.stencilGlobal)||void 0===e||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var t;if(!e)return;let i=!this.useStencilGlobalOnly&&!!(null===(t=this.stencilMaterial)||void 0===t?void 0:t.enabled);this.enabled=i?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=i?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=i?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=i?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=i?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=i?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=i?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=i?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}},2725:function(e,t,i){i.d(t,{p:function(){return r}});class r{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,r){for(let s in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,s)&&this._BabylonFileParsers[s](e,t,i,r)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=(e=(e=(e=e.concat(this.meshes)).concat(this.lights)).concat(this.cameras)).concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}}r._BabylonFileParsers={},r._IndividualBabylonFileParsers={}},870:function(e,t,i){let r,s;i.d(t,{YfP:function(){return aA},HEv:function(){return rs.HE},Dso:function(){return np},xsS:function(){return rI.x},xeF:function(){return nd.x},vGS:function(){return no.v},w1W:function(){return rZ.w1},Pa4:function(){return rr.P},fWK:function(){return cG}});var n,a,o,l,h,u,c,d,p,_,f,m,g,v,T,x,S,E,C,b,y,A,R,P,I,M,D,O,N,F,L,w,B,U,V,k,G,z,W,H,X,Y,j,q,K,$,Q,Z,J,ee,et,ei,er,es,en,ea,eo,el,eh,eu,ec,ed,ep,e_,ef,em,eg,ev,eT,ex,eS,eE,eC,eb,ey,eA,eR,eP,eI,eM,eD,eO,eN,eF,eL,ew,eB,eU,eV,ek,eG,ez,eW,eH,eX,eY,ej,eq,eK,e$,eQ,eZ,eJ,e0,e1,e2,e3,e4,e5,e6,e8,e7,e9,te,tt,ti,tr,ts,tn,ta,to,tl,th,tu,tc,td,tp,t_,tf,tm,tg,tv,tT,tx,tS,tE,tC,tb,ty,tA,tR,tP,tI,tM,tD,tO,tN,tF,tL,tw,tB,tU,tV,tk,tG,tz,tW,tH,tX,tY,tj,tq,tK,t$,tQ,tZ,tJ,t0,t1,t2,t3,t4,t5,t6,t8,t7,t9,ie,it,ii,ir,is,ia,io,il,ih,iu,ic,id,ip,i_,im,ig,iv,iT,ix,iS,iE,iC,ib,iy,iA,iR,iP,iI,iM,iD,iO,iN,iF,iL,iw,iB,iU,iV,ik,iG,iz,iW,iH,iX,iY,ij,iq,iK,i$,iQ,iZ,iJ,i0,i1,i2,i3,i4,i5,i6,i8,i7,i9,re=i(2725),rt=i(2511),ri=i(6702),rr=i(1823),rs=i(6762),rn=i(9678);class ra{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new ri.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(){let e=this._condition;if(!e)return!0;let t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){let t=this._evaluateConditionForCurrentFrame();t&&(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){let i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){let e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}ra._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof rr.FM?e.x+", "+e.y:e instanceof rr.P?e.x+", "+e.y+", "+e.z:e instanceof rs.Wo?e.r+", "+e.g+", "+e.b:e instanceof rs.HE?e.r+", "+e.g+", "+e.b+", "+e.a:e,ra._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,rn.H)("BABYLON.Action",ra);var ro=i(9326);class rl{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 rh extends rl{static get IsEqual(){return rh._IsEqual}static get IsDifferent(){return rh._IsDifferent}static get IsGreater(){return rh._IsGreater}static get IsLesser(){return rh._IsLesser}constructor(e,t,i,r,s=rh.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case rh.IsGreater:return this._effectiveTarget[this._property]>this.value;case rh.IsLesser:return this._effectiveTarget[this._property]<this.value;case rh.IsEqual:case rh.IsDifferent:{let e;return e=this.value.equals?this.value.equals(this._effectiveTarget[this._property]):this.value===this._effectiveTarget[this._property],this.operator===rh.IsEqual?e:!e}}return!1}serialize(){return this._serialize({name:"ValueCondition",properties:[ra._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ra._SerializeValueAsString(this.value)},{name:"operator",value:rh.GetOperatorName(this.operator)}]})}static GetOperatorName(e){switch(e){case rh._IsEqual:return"IsEqual";case rh._IsDifferent:return"IsDifferent";case rh._IsGreater:return"IsGreater";case rh._IsLesser:return"IsLesser";default:return""}}}rh._IsEqual=0,rh._IsDifferent=1,rh._IsGreater=2,rh._IsLesser=3,(0,rn.H)("BABYLON.ValueCondition",rh),(0,rn.H)("BABYLON.PredicateCondition",class extends rl{constructor(e,t){super(e),this.predicate=t}isValid(){return this.predicate()}}),(0,rn.H)("BABYLON.StateCondition",class extends rl{constructor(e,t,i){super(e),this.value=i,this._target=t}isValid(){return this._target.state===this.value}serialize(){return this._serialize({name:"StateCondition",properties:[ra._GetTargetProperty(this._target),{name:"value",value:this.value}]})}});var ru=i(7694);class rc extends ra{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class rd extends ra{constructor(e,t,i,r){super(e,r),this._target=t,this._parent=i}_prepare(){}execute(){if(this._target.parent===this._parent)return;let e=this._parent.getWorldMatrix().clone();e.invert(),this._target.position=rr.P.TransformCoordinates(this._target.position,e),this._target.parent=this._parent}serialize(e){return super._serialize({name:"SetParentAction",properties:[ra._GetTargetProperty(this._target),ra._GetTargetProperty(this._parent)]},e)}}(0,rn.H)("BABYLON.SetParentAction",rd),(0,rn.H)("BABYLON.ExecuteCodeAction",class extends ra{constructor(e,t,i){super(e,i),this.func=t}execute(e){this.func(e)}}),(0,rn.H)("BABYLON.DoNothingAction",rc),(0,rn.H)("BABYLON.StopAnimationAction",class extends ra{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){let e=this._actionManager.getScene();e.stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[ra._GetTargetProperty(this._target)]},e)}}),(0,rn.H)("BABYLON.PlayAnimationAction",class extends ra{constructor(e,t,i,r,s,n){super(e,n),this.from=i,this.to=r,this.loop=s,this._target=t}_prepare(){}execute(){let e=this._actionManager.getScene();e.beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[ra._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:ra._SerializeValueAsString(this.loop)||!1}]},e)}}),(0,rn.H)("BABYLON.IncrementValueAction",class extends ra{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&ru.Y.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[ra._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ra._SerializeValueAsString(this.value)}]},e)}}),(0,rn.H)("BABYLON.SetValueAction",class extends ra{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[ra._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ra._SerializeValueAsString(this.value)}]},e)}}),(0,rn.H)("BABYLON.SetStateAction",class extends ra{constructor(e,t,i,r){super(e,r),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[ra._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}),(0,rn.H)("BABYLON.SetParentAction",rd),(0,rn.H)("BABYLON.SwitchBooleanAction",class extends ra{constructor(e,t,i,r){super(e,r),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[ra._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}),(0,rn.H)("BABYLON.CombineAction",class extends ra{constructor(e,t,i,r=!0){super(e,i),this.children=t,this.enableChildrenConditions=r}_prepare(){for(let e=0;e<this.children.length;e++)this.children[e]._actionManager=this._actionManager,this.children[e]._prepare()}execute(e){for(let t of this.children)(!this.enableChildrenConditions||t._evaluateConditionForCurrentFrame())&&t.execute(e)}serialize(e){let t=super._serialize({name:"CombineAction",properties:[],combine:[]},e);for(let e=0;e<this.children.length;e++)t.combine.push(this.children[e].serialize(null));return t}});var rp=i(3914),r_=i(5754);class rf extends rt.O{constructor(e){if(super(),!(e=e||rp.l.LastCreatedScene))return;this._scene=e,e.actionManagers.push(this)}dispose(){let e=this._scene.actionManagers.indexOf(this);for(let e=0;e<this.actions.length;e++){let t=this.actions[e];rf.Triggers[t.trigger]--,0===rf.Triggers[t.trigger]&&delete rf.Triggers[t.trigger]}this.actions.length=0,e>-1&&this._scene.actionManagers.splice(e,1);let t=this._scene.meshes.find(e=>e.actionManager===this);t&&(t.actionManager=null)}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t<this.actions.length;t++){let i=this.actions[t];if(e.indexOf(i.trigger)>-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i<this.actions.length;i++){let r=this.actions[i];if(e==r.trigger||t==r.trigger)return!0}return!1}hasSpecificTrigger(e,t){for(let i=0;i<this.actions.length;i++){let r=this.actions[i];if(r.trigger===e&&(!t||t(r.getTriggerParameter())))return!0}return!1}get hasPointerTriggers(){for(let e=0;e<this.actions.length;e++){let t=this.actions[e];if(t.trigger>=rf.OnPickTrigger&&t.trigger<=rf.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e<this.actions.length;e++){let t=this.actions[e];if(t.trigger>=rf.OnPickTrigger&&t.trigger<=rf.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===rf.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(ru.Y.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,rf.Triggers[e.trigger]?rf.Triggers[e.trigger]++:rf.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){let t=this.actions.indexOf(e);return -1!==t&&(this.actions.splice(t,1),rf.Triggers[e.trigger]-=1,0===rf.Triggers[e.trigger]&&delete rf.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i<this.actions.length;i++){let r=this.actions[i];if(r.trigger===e){if(t&&(e===rf.OnKeyUpTrigger||e===rf.OnKeyDownTrigger)){let e=r.getTriggerParameter();if("function"==typeof e){if(!e(t))continue}else if(e&&e!==t.sourceEvent.keyCode){if(!e.toLowerCase)continue;let i=e.toLowerCase();if(i!==t.sourceEvent.key){let e=t.sourceEvent.charCode?t.sourceEvent.charCode:t.sourceEvent.keyCode,r=String.fromCharCode(e).toLowerCase();if(r!==i)continue}}}r._executeCurrent(t)}}}_getEffectiveTarget(e,t){let i=t.split(".");for(let t=0;t<i.length-1;t++)e=e[i[t]];return e}_getProperty(e){let t=e.split(".");return t[t.length-1]}serialize(e){let t={children:[],name:e,type:3,properties:[]};for(let e=0;e<this.actions.length;e++){let i={type:0,children:[],name:rf.GetTriggerName(this.actions[e].trigger),properties:[]},r=this.actions[e].triggerOptions;if(r&&"number"!=typeof r){if(r.parameter instanceof Node)i.properties.push(ra._GetTargetProperty(r.parameter));else if("object"==typeof r.parameter){let e={};r_.j.DeepCopy(r.parameter,e,["mesh"]),r.parameter&&r.parameter.mesh&&(e._meshId=r.parameter.mesh.id),i.properties.push({name:"parameter",targetType:null,value:e})}else i.properties.push({name:"parameter",targetType:null,value:r.parameter})}this.actions[e].serialize(i),t.children.push(i)}return t}static Parse(e,t,i){let r=new rf(i);null===t?i.actionManager=r:t.actionManager=r;let s=(e,t)=>{let i=(0,rn.q)("BABYLON."+e);return i&&new i(...t)},n=(e,t,i,r)=>{if(null===r){let e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}let s=r.split("."),n=t.split(",");for(let e=0;e<s.length;e++)i=i[s[e]];if("boolean"==typeof i)return"true"===n[0];if("string"==typeof i)return n[0];let a=[];for(let e=0;e<n.length;e++)a.push(parseFloat(n[e]));return i instanceof rr.P?rr.P.FromArray(a):i instanceof rr.Lt?rr.Lt.FromArray(a):i instanceof rs.Wo?rs.Wo.FromArray(a):i instanceof rs.HE?rs.HE.FromArray(a):parseFloat(n[0])},a=(e,t,o,l,h=null)=>{if(e.detached)return;let u=[],c=null,d=null,p=e.combine&&e.combine.length>0;if(2===e.type?u.push(r):u.push(t),p){let t=[];for(let i=0;i<e.combine.length;i++)a(e.combine[i],rf.NothingTrigger,o,l,t);u.push(t)}else for(let t=0;t<e.properties.length;t++){let r=e.properties[t].value,s=e.properties[t].name,a=e.properties[t].targetType;"target"===s?r=c="SceneProperties"===a?i:"MaterialProperties"===a?i.getMaterialByName(r):i.getNodeByName(r):"parent"===s?r=i.getNodeByName(r):"sound"===s?i.getSoundByName&&(r=i.getSoundByName(r)):"propertyPath"!==s?r=2===e.type&&"operator"===s?rh[r]:n(s,r,c,"value"===s?d:null):d=r,u.push(r)}if(null===h?u.push(o):u.push(null),"InterpolateValueAction"===e.name){let e=u[u.length-2];u[u.length-1]=e,u[u.length-2]=o}let _=s(e.name,u);if(_ instanceof rl&&null!==o){let e=new rc(t,o);l?l.then(e):r.registerAction(e),l=e}null===h?_ instanceof rl?(o=_,_=l):(o=null,l?l.then(_):r.registerAction(_)):h.push(_);for(let i=0;i<e.children.length;i++)a(e.children[i],t,o,_,null)};for(let t=0;t<e.children.length;t++){let r;let s=e.children[t];if(s.properties.length>0){let e=s.properties[0].value,t=null===s.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),r={trigger:rf[s.name],parameter:t}}else r=rf[s.name];for(let e=0;e<s.children.length;e++)s.detached||a(s.children[e],r,null,null)}}static GetTriggerName(e){switch(e){case 0:return"NothingTrigger";case 1:return"OnPickTrigger";case 2:return"OnLeftPickTrigger";case 3:return"OnRightPickTrigger";case 4:return"OnCenterPickTrigger";case 5:return"OnPickDownTrigger";case 6:return"OnDoublePickTrigger";case 7:return"OnPickUpTrigger";case 8:return"OnLongPressTrigger";case 9:return"OnPointerOverTrigger";case 10:return"OnPointerOutTrigger";case 11:return"OnEveryFrameTrigger";case 12:return"OnIntersectionEnterTrigger";case 13:return"OnIntersectionExitTrigger";case 14:return"OnKeyDownTrigger";case 15:return"OnKeyUpTrigger";case 16:return"OnPickOutTrigger";default:return""}}}rf.NothingTrigger=0,rf.OnPickTrigger=1,rf.OnLeftPickTrigger=2,rf.OnRightPickTrigger=3,rf.OnCenterPickTrigger=4,rf.OnPickDownTrigger=5,rf.OnDoublePickTrigger=6,rf.OnPickUpTrigger=7,rf.OnPickOutTrigger=16,rf.OnLongPressTrigger=8,rf.OnPointerOverTrigger=9,rf.OnPointerOutTrigger=10,rf.OnEveryFrameTrigger=11,rf.OnIntersectionEnterTrigger=12,rf.OnIntersectionExitTrigger=13,rf.OnKeyDownTrigger=14,rf.OnKeyUpTrigger=15,(0,rn.H)("BABYLON.PlaySoundAction",class extends ra{constructor(e,t,i){super(e,i),this._sound=t}_prepare(){}execute(){void 0!==this._sound&&this._sound.play()}serialize(e){return super._serialize({name:"PlaySoundAction",properties:[{name:"sound",value:this._sound.name}]},e)}}),(0,rn.H)("BABYLON.StopSoundAction",class extends ra{constructor(e,t,i){super(e,i),this._sound=t}_prepare(){}execute(){void 0!==this._sound&&this._sound.stop()}serialize(e){return super._serialize({name:"StopSoundAction",properties:[{name:"sound",value:this._sound.name}]},e)}});var rm=i(5526),rg=i(6816);(n=tn||(tn={}))[n.NONE=0]="NONE",n[n.STEP=1]="STEP";class rv{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new rv(this.name,this.from,this.to)}}var rT=i(9747);class rx{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){return 397*(0|this.width)^(0|this.height)}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new rx(this.width*e,this.height*t)}clone(){return new rx(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new rx(0,0)}add(e){let t=new rx(this.width+e.width,this.height+e.height);return t}subtract(e){let t=new rx(this.width-e.width,this.height-e.height);return t}static Lerp(e,t,i){let r=e.width+(t.width-e.width)*i,s=e.height+(t.height-e.height)*i;return new rx(r,s)}}var rS=i(3105);class rE{static _PrepareAnimation(e,t,i,r,s,n,a,o){let l;if(!isNaN(parseFloat(s))&&isFinite(s)?l=rE.ANIMATIONTYPE_FLOAT:s instanceof rr._f?l=rE.ANIMATIONTYPE_QUATERNION:s instanceof rr.P?l=rE.ANIMATIONTYPE_VECTOR3:s instanceof rr.FM?l=rE.ANIMATIONTYPE_VECTOR2:s instanceof rs.Wo?l=rE.ANIMATIONTYPE_COLOR3:s instanceof rs.HE?l=rE.ANIMATIONTYPE_COLOR4:s instanceof rx&&(l=rE.ANIMATIONTYPE_SIZE),void 0==l)return null;let h=new rE(e,t,i,l,a),u=[{frame:0,value:s},{frame:r,value:n}];return h.setKeys(u),void 0!==o&&h.setEasingFunction(o),h}static CreateAnimation(e,t,i,r){let s=new rE(e+"Animation",e,i,t,rE.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,n,a,o,l,h,u){let c=rE._PrepareAnimation(e,i,r,s,n,a,o,l);return c&&(t.getScene&&(u=t.getScene()),u)?u.beginDirectAnimation(t,[c],0,s,1===c.loopMode,1,h):null}static CreateAndStartHierarchyAnimation(e,t,i,r,s,n,a,o,l,h,u){let c=rE._PrepareAnimation(e,r,s,n,a,o,l,h);if(!c)return null;let d=t.getScene();return d.beginDirectHierarchyAnimation(t,i,[c],0,n,1===c.loopMode,1,u)}static CreateMergeAndStartAnimation(e,t,i,r,s,n,a,o,l,h){let u=rE._PrepareAnimation(e,i,r,s,n,a,o,l);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,s,1===u.loopMode,1,h)):null}static MakeAnimationAdditive(e,t=0,i,r=!1,s){let n=e;if(r&&((n=e.clone()).name=s||n.name),!n._keys.length)return n;t=t>=0?t:0;let a=0,o=n._keys[0],l=n._keys.length-1,h=n._keys[l],u={referenceValue:o.value,referencePosition:rr.jp.Vector3[0],referenceQuaternion:rr.jp.Quaternion[0],referenceScaling:rr.jp.Vector3[1],keyPosition:rr.jp.Vector3[2],keyQuaternion:rr.jp.Quaternion[1],keyScaling:rr.jp.Vector3[3]},c=!1,d=o.frame,p=h.frame;if(i){let e=n.getRange(i);e&&(d=e.from,p=e.to)}let _=o.frame===d,f=h.frame===p;if(1===n._keys.length){let e=n._getKeyValue(n._keys[0]);u.referenceValue=e.clone?e.clone():e,c=!0}else if(t<=o.frame){let e=n._getKeyValue(o.value);u.referenceValue=e.clone?e.clone():e,c=!0}else if(t>=h.frame){let e=n._getKeyValue(h.value);u.referenceValue=e.clone?e.clone():e,c=!0}let m=0;for(;!c||!_||!f&&m<n._keys.length-1;){let e=n._keys[m],i=n._keys[m+1];if(!c&&t>=e.frame&&t<=i.frame){let r;if(t===e.frame)r=n._getKeyValue(e.value);else if(t===i.frame)r=n._getKeyValue(i.value);else{let e={key:m,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};r=n._interpolate(t,e)}u.referenceValue=r.clone?r.clone():r,c=!0}if(!_&&d>=e.frame&&d<=i.frame){if(d===e.frame)a=m;else if(d===i.frame)a=m+1;else{let e={key:m,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=n._interpolate(d,e),i={frame:d,value:t.clone?t.clone():t};n._keys.splice(m+1,0,i),a=m+1}_=!0}if(!f&&p>=e.frame&&p<=i.frame){if(p===e.frame)l=m;else if(p===i.frame)l=m+1;else{let e={key:m,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=n._interpolate(p,e),i={frame:p,value:t.clone?t.clone():t};n._keys.splice(m+1,0,i),l=m+1}f=!0}m++}for(n.dataType===rE.ANIMATIONTYPE_QUATERNION?u.referenceValue.normalize().conjugateInPlace():n.dataType===rE.ANIMATIONTYPE_MATRIX&&(u.referenceValue.decompose(u.referenceScaling,u.referenceQuaternion,u.referencePosition),u.referenceQuaternion.normalize().conjugateInPlace()),m=a;m<=l;m++){let e=n._keys[m];if(!m||n.dataType===rE.ANIMATIONTYPE_FLOAT||e.value!==o.value)switch(n.dataType){case rE.ANIMATIONTYPE_MATRIX:e.value.decompose(u.keyScaling,u.keyQuaternion,u.keyPosition),u.keyPosition.subtractInPlace(u.referencePosition),u.keyScaling.divideInPlace(u.referenceScaling),u.referenceQuaternion.multiplyToRef(u.keyQuaternion,u.keyQuaternion),rr.y3.ComposeToRef(u.keyScaling,u.keyQuaternion,u.keyPosition,e.value);break;case rE.ANIMATIONTYPE_QUATERNION:u.referenceValue.multiplyToRef(e.value,e.value);break;case rE.ANIMATIONTYPE_VECTOR2:case rE.ANIMATIONTYPE_VECTOR3:case rE.ANIMATIONTYPE_COLOR3:case rE.ANIMATIONTYPE_COLOR4:e.value.subtractToRef(u.referenceValue,e.value);break;case rE.ANIMATIONTYPE_SIZE:e.value.width-=u.referenceValue.width,e.value.height-=u.referenceValue.height;break;default:e.value-=u.referenceValue}}return n}static TransitionTo(e,t,i,r,s,n,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;let l=s*(a/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);let h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=o,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(let e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=[],this._events=[],this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=void 0===s?rE.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=rE._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType]+", nKeys: "+(this._keys?this._keys.length:"none")+", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((e,t)=>e.frame-t.frame)}removeEvents(e){for(let t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)}getEvents(){return this._events}createRange(e,t,i){this._ranges[e]||(this._ranges[e]=new rv(e,t,i))}deleteRange(e,t=!0){let i=this._ranges[e];if(i){if(t){let e=i.from,t=i.to;for(let i=this._keys.length-1;i>=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t<i;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e}getEasingFunction(){return this._easingFunction}setEasingFunction(e){this._easingFunction=e}floatInterpolateFunction(e,t,i){return rm.R.Lerp(e,t,i)}floatInterpolateFunctionWithTangents(e,t,i,r,s){return rm.R.Hermite(e,t,i,r,s)}quaternionInterpolateFunction(e,t,i){return rr._f.Slerp(e,t,i)}quaternionInterpolateFunctionWithTangents(e,t,i,r,s){return rr._f.Hermite(e,t,i,r,s).normalize()}vector3InterpolateFunction(e,t,i){return rr.P.Lerp(e,t,i)}vector3InterpolateFunctionWithTangents(e,t,i,r,s){return rr.P.Hermite(e,t,i,r,s)}vector2InterpolateFunction(e,t,i){return rr.FM.Lerp(e,t,i)}vector2InterpolateFunctionWithTangents(e,t,i,r,s){return rr.FM.Hermite(e,t,i,r,s)}sizeInterpolateFunction(e,t,i){return rx.Lerp(e,t,i)}color3InterpolateFunction(e,t,i){return rs.Wo.Lerp(e,t,i)}color3InterpolateFunctionWithTangents(e,t,i,r,s){return rs.Wo.Hermite(e,t,i,r,s)}color4InterpolateFunction(e,t,i){return rs.HE.Lerp(e,t,i)}color4InterpolateFunctionWithTangents(e,t,i,r,s){return rs.HE.Hermite(e,t,i,r,s)}_getKeyValue(e){return"function"==typeof e?e():e}evaluate(e){return this._interpolate(e,{key:0,repeatCount:0,loopMode:rE.ANIMATIONLOOPMODE_CONSTANT})}_interpolate(e,t){if(t.loopMode===rE.ANIMATIONLOOPMODE_CONSTANT&&t.repeatCount>0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;let i=this._keys,r=i.length,s=t.key;for(;s>=0&&e<i[s].frame;)--s;for(;s+1<=r-1&&e>=i[s+1].frame;)++s;if(t.key=s,s<0)return this._getKeyValue(i[0].value);if(s+1>r-1)return this._getKeyValue(i[r-1].value);let n=i[s],a=i[s+1],o=this._getKeyValue(n.value),l=this._getKeyValue(a.value);if(n.interpolation===tn.STEP)return a.frame>e?o:l;let h=void 0!==n.outTangent&&void 0!==a.inTangent,u=a.frame-n.frame,c=(e-n.frame)/u,d=this.getEasingFunction();switch(null!==d&&(c=d.ease(c)),this.dataType){case rE.ANIMATIONTYPE_FLOAT:{let e=h?this.floatInterpolateFunctionWithTangents(o,n.outTangent*u,l,a.inTangent*u,c):this.floatInterpolateFunction(o,l,c);switch(t.loopMode){case rE.ANIMATIONLOOPMODE_CYCLE:case rE.ANIMATIONLOOPMODE_CONSTANT:case rE.ANIMATIONLOOPMODE_YOYO:return e;case rE.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+e}break}case rE.ANIMATIONTYPE_QUATERNION:{let e=h?this.quaternionInterpolateFunctionWithTangents(o,n.outTangent.scale(u),l,a.inTangent.scale(u),c):this.quaternionInterpolateFunction(o,l,c);switch(t.loopMode){case rE.ANIMATIONLOOPMODE_CYCLE:case rE.ANIMATIONLOOPMODE_CONSTANT:case rE.ANIMATIONLOOPMODE_YOYO:break;case rE.ANIMATIONLOOPMODE_RELATIVE:return e.addInPlace(t.offsetValue.scale(t.repeatCount))}return e}case rE.ANIMATIONTYPE_VECTOR3:{let e=h?this.vector3InterpolateFunctionWithTangents(o,n.outTangent.scale(u),l,a.inTangent.scale(u),c):this.vector3InterpolateFunction(o,l,c);switch(t.loopMode){case rE.ANIMATIONLOOPMODE_CYCLE:case rE.ANIMATIONLOOPMODE_CONSTANT:case rE.ANIMATIONLOOPMODE_YOYO:return e;case rE.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case rE.ANIMATIONTYPE_VECTOR2:{let e=h?this.vector2InterpolateFunctionWithTangents(o,n.outTangent.scale(u),l,a.inTangent.scale(u),c):this.vector2InterpolateFunction(o,l,c);switch(t.loopMode){case rE.ANIMATIONLOOPMODE_CYCLE:case rE.ANIMATIONLOOPMODE_CONSTANT:case rE.ANIMATIONLOOPMODE_YOYO:return e;case rE.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case rE.ANIMATIONTYPE_SIZE:switch(t.loopMode){case rE.ANIMATIONLOOPMODE_CYCLE:case rE.ANIMATIONLOOPMODE_CONSTANT:case rE.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(o,l,c);case rE.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(o,l,c).add(t.offsetValue.scale(t.repeatCount))}break;case rE.ANIMATIONTYPE_COLOR3:{let e=h?this.color3InterpolateFunctionWithTangents(o,n.outTangent.scale(u),l,a.inTangent.scale(u),c):this.color3InterpolateFunction(o,l,c);switch(t.loopMode){case rE.ANIMATIONLOOPMODE_CYCLE:case rE.ANIMATIONLOOPMODE_CONSTANT:case rE.ANIMATIONLOOPMODE_YOYO:return e;case rE.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case rE.ANIMATIONTYPE_COLOR4:{let e=h?this.color4InterpolateFunctionWithTangents(o,n.outTangent.scale(u),l,a.inTangent.scale(u),c):this.color4InterpolateFunction(o,l,c);switch(t.loopMode){case rE.ANIMATIONLOOPMODE_CYCLE:case rE.ANIMATIONLOOPMODE_CONSTANT:case rE.ANIMATIONLOOPMODE_YOYO:return e;case rE.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case rE.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case rE.ANIMATIONLOOPMODE_CYCLE:case rE.ANIMATIONLOOPMODE_CONSTANT:case rE.ANIMATIONLOOPMODE_YOYO:if(rE.AllowMatricesInterpolation)return this.matrixInterpolateFunction(o,l,c,t.workValue);return o;case rE.ANIMATIONLOOPMODE_RELATIVE:return o}}return 0}matrixInterpolateFunction(e,t,i,r){return rE.AllowMatrixDecomposeForInterpolation?r?(rr.y3.DecomposeLerpToRef(e,t,i,r),r):rr.y3.DecomposeLerp(e,t,i):r?(rr.y3.LerpToRef(e,t,i,r),r):rr.y3.Lerp(e,t,i)}clone(){let e=new rE(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)for(let t in e._ranges={},this._ranges){let i=this._ranges[t];i&&(e._ranges[t]=i.clone())}return e}setKeys(e){this._keys=e.slice(0)}serialize(){let 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;let t=this.dataType;e.keys=[];let i=this.getKeys();for(let r=0;r<i.length;r++){let s=i[r],n={};switch(n.frame=s.frame,t){case rE.ANIMATIONTYPE_FLOAT:n.values=[s.value],void 0!==s.inTangent&&n.values.push(s.inTangent),void 0!==s.outTangent&&(void 0===s.inTangent&&n.values.push(void 0),n.values.push(s.outTangent)),void 0!==s.interpolation&&(void 0===s.inTangent&&n.values.push(void 0),void 0===s.outTangent&&n.values.push(void 0),n.values.push(s.interpolation));break;case rE.ANIMATIONTYPE_QUATERNION:case rE.ANIMATIONTYPE_MATRIX:case rE.ANIMATIONTYPE_VECTOR3:case rE.ANIMATIONTYPE_COLOR3:case rE.ANIMATIONTYPE_COLOR4:n.values=s.value.asArray(),void 0!=s.inTangent&&n.values.push(s.inTangent.asArray()),void 0!=s.outTangent&&(void 0===s.inTangent&&n.values.push(void 0),n.values.push(s.outTangent.asArray())),void 0!==s.interpolation&&(void 0===s.inTangent&&n.values.push(void 0),void 0===s.outTangent&&n.values.push(void 0),n.values.push(s.interpolation))}e.keys.push(n)}for(let t in e.ranges=[],this._ranges){let i=this._ranges[t];if(!i)continue;let r={};r.name=t,r.from=i.from,r.to=i.to,e.ranges.push(r)}return e}static _UniversalLerp(e,t,i){let r=e.constructor;return r.Lerp?r.Lerp(e,t,i):r.Slerp?r.Slerp(e,t,i):e.toFixed?e*(1-i)+i*t:t}static Parse(e){let t,i;let r=new rE(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior),s=e.dataType,n=[];for(e.enableBlending&&(r.enableBlending=e.enableBlending),e.blendingSpeed&&(r.blendingSpeed=e.blendingSpeed),i=0;i<e.keys.length;i++){let r,a,o;let l=e.keys[i];switch(s){case rE.ANIMATIONTYPE_FLOAT:t=l.values[0],l.values.length>=2&&(r=l.values[1]),l.values.length>=3&&(a=l.values[2]),l.values.length>=4&&(o=l.values[3]);break;case rE.ANIMATIONTYPE_QUATERNION:if(t=rr._f.FromArray(l.values),l.values.length>=8){let e=rr._f.FromArray(l.values.slice(4,8));e.equals(rr._f.Zero())||(r=e)}if(l.values.length>=12){let e=rr._f.FromArray(l.values.slice(8,12));e.equals(rr._f.Zero())||(a=e)}l.values.length>=13&&(o=l.values[12]);break;case rE.ANIMATIONTYPE_MATRIX:t=rr.y3.FromArray(l.values),l.values.length>=17&&(o=l.values[16]);break;case rE.ANIMATIONTYPE_COLOR3:t=rs.Wo.FromArray(l.values),l.values[3]&&(r=rs.Wo.FromArray(l.values[3])),l.values[4]&&(a=rs.Wo.FromArray(l.values[4])),l.values[5]&&(o=l.values[5]);break;case rE.ANIMATIONTYPE_COLOR4:t=rs.HE.FromArray(l.values),l.values[4]&&(r=rs.HE.FromArray(l.values[4])),l.values[5]&&(a=rs.HE.FromArray(l.values[5])),l.values[6]&&(o=rs.HE.FromArray(l.values[6]));break;case rE.ANIMATIONTYPE_VECTOR3:default:t=rr.P.FromArray(l.values),l.values[3]&&(r=rr.P.FromArray(l.values[3])),l.values[4]&&(a=rr.P.FromArray(l.values[4])),l.values[5]&&(o=l.values[5])}let h={};h.frame=l.frame,h.value=t,void 0!=r&&(h.inTangent=r),void 0!=a&&(h.outTangent=a),void 0!=o&&(h.interpolation=o),n.push(h)}if(r.setKeys(n),e.ranges)for(i=0;i<e.ranges.length;i++)t=e.ranges[i],r.createRange(t.name,t.from,t.to);return r}static AppendSerializedAnimations(e,t){rg.p4.AppendSerializedAnimations(e,t)}static ParseFromFileAsync(e,t){return new Promise((i,r)=>{let s=new rS.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){let e=[];for(let i of t)e.push(this.Parse(i));i(e)}else{let r=this.Parse(t);e&&(r.name=e),i(r)}}else r("Unable to load the animation")}}),s.open("GET",t),s.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{let r=new rS.g;r.addEventListener("readystatechange",()=>{if(4==r.readyState){if(200==r.status){let i=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(i.animations){let r=JSON.parse(i.animations),s=[];for(let t of r.animations){let i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{let r=JSON.parse(i.animation),s=this.Parse(r);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)}}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}}rE._UniqueIdGenerator=0,rE.AllowMatricesInterpolation=!1,rE.AllowMatrixDecomposeForInterpolation=!0,rE.SnippetUrl="https://snippet.babylonjs.com",rE.ANIMATIONTYPE_FLOAT=0,rE.ANIMATIONTYPE_VECTOR3=1,rE.ANIMATIONTYPE_QUATERNION=2,rE.ANIMATIONTYPE_MATRIX=3,rE.ANIMATIONTYPE_COLOR3=4,rE.ANIMATIONTYPE_COLOR4=7,rE.ANIMATIONTYPE_VECTOR2=5,rE.ANIMATIONTYPE_SIZE=6,rE.ANIMATIONLOOPMODE_RELATIVE=0,rE.ANIMATIONLOOPMODE_CYCLE=1,rE.ANIMATIONLOOPMODE_CONSTANT=2,rE.ANIMATIONLOOPMODE_YOYO=4,rE.CreateFromSnippetAsync=rE.ParseFromSnippetAsync,(0,rn.H)("BABYLON.Animation",rE),rT.N._AnimationRangeFactory=(e,t,i)=>new rv(e,t,i),(0,rn.H)("BABYLON.InterpolateValueAction",class extends ra{constructor(e,t,i,r,s=1e3,n,a,o){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new ri.y$,this.propertyPath=i,this.value=r,this.duration=s,this.stopOtherAnimations=a,this.onInterpolationDone=o,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){let e;let t=this._actionManager.getScene(),i=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)e=rE.ANIMATIONTYPE_FLOAT;else if(this.value instanceof rs.Wo)e=rE.ANIMATIONTYPE_COLOR3;else if(this.value instanceof rr.P)e=rE.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof rr.y3)e=rE.ANIMATIONTYPE_MATRIX;else if(this.value instanceof rr._f)e=rE.ANIMATIONTYPE_QUATERNION;else{ru.Y.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}let r=new rE("InterpolateValueAction",this._property,100*(1e3/this.duration),e,rE.ANIMATIONLOOPMODE_CONSTANT);r.setKeys(i),this.stopOtherAnimations&&t.stopAnimation(this._effectiveTarget),t.beginDirectAnimation(this._effectiveTarget,[r],0,100,!1,1,()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()})}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[ra._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:ra._SerializeValueAsString(this.value)},{name:"duration",value:ra._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:ra._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}});let rC=Object.freeze(new rr._f(0,0,0,0)),rb=Object.freeze(rr.P.Zero()),ry=Object.freeze(rr.FM.Zero()),rA=Object.freeze(rx.Zero()),rR=Object.freeze(rs.Wo.Black());class rP{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,r){if(this._events=[],this._currentFrame=0,this._originalValue=[],this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===rE.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=rr.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){let e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(let 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];let 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){let i=this._animation.targetPropertyPath;if(i.length>1){let r=e[i[0]];for(let e=1;e<i.length-1;e++)r=r[i[e]];this._targetPath=i[i.length-1],this._activeTargets[t]=r}else this._targetPath=i[0],this._activeTargets[t]=e}get animation(){return this._animation}reset(e=!1){if(e){if(this._target instanceof Array){let e=0;for(let t of this._target)void 0!==this._originalValue[e]&&this._setValue(t,this._activeTargets[e],this._originalValue[e],-1,e),e++}else void 0!==this._originalValue[0]&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0)}this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(let e=0;e<this._events.length;e++)this._events[e].isDone=!1}isStopped(){return this._stopped}dispose(){let e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;i<this._target.length;i++){let r=this._target[i];this._setValue(r,this._activeTargets[i],e,t,i)}return}this._setValue(this._target,this._directTarget,e,t,0)}_getOriginalValues(e=0){let t;let i=this._activeTargets[e];(t=i.getRestPose&&"_matrix"===this._targetPath?i.getRestPose():i[this._targetPath])&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t}_setValue(e,t,i,r,s){if(this._currentActiveTarget=t,this._weight=r,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){let e=t[this._targetPath];e.clone?this._originalBlendValue=e.clone():this._originalBlendValue=e}this._originalBlendValue.m?rE.AllowMatrixDecomposeForInterpolation?this._currentValue?rr.y3.DecomposeLerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=rr.y3.DecomposeLerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue?rr.y3.LerpToRef(this._originalBlendValue,i,this._blendingFactor,this._currentValue):this._currentValue=rr.y3.Lerp(this._originalBlendValue,i,this._blendingFactor):this._currentValue=rE._UniversalLerp(this._originalBlendValue,i,this._blendingFactor);let r=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=r}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(i):this._currentValue=i:(null==i?void 0:i.clone)?this._currentValue=i.clone():this._currentValue=i;-1!==r?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[s]):t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)}_getCorrectLoopMode(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode}goToFrame(e){let t=this._animation.getKeys();e<t[0].frame?e=t[0].frame:e>t[t.length-1].frame&&(e=t[t.length-1].frame);let i=this._events;if(i.length)for(let t=0;t<i.length;t++)i[t].onlyOnce||(i[t].isDone=i[t].frame<e);this._currentFrame=e;let r=this._animation._interpolate(e,this._animationState);this.setValue(r,-1)}_prepareForSpeedRatioChange(e){let t=this._previousElapsedTime*(this._animation.framePerSecond*e)/1e3;this._absoluteFrameOffset=this._previousAbsoluteFrame-t}animate(e,t,i,r,s,n=-1){let a,o;let l=this._animation,h=l.targetPropertyPath;if(!h||h.length<1)return this._stopped=!0,!1;let u=!0;(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(i<this._minFrame||i>this._maxFrame)&&(i=this._maxFrame);let c=i-t,d=e*(l.framePerSecond*s)/1e3+this._absoluteFrameOffset,p=0;if(r&&this._animationState.loopMode===rE.ANIMATIONLOOPMODE_YOYO){let e=(d-t)/c;d=Math.abs(Math.sin(e*Math.PI))*c+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&d>=c)u=!1,p=l._getKeyValue(this._maxValue);else if(!r&&t>=i&&d<=c)u=!1,p=l._getKeyValue(this._minValue);else if(this._animationState.loopMode!==rE.ANIMATIONLOOPMODE_CYCLE){let e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=rE.ANIMATIONLOOPMODE_CYCLE;let r=l._interpolate(t,this._animationState),s=l._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),l.dataType){case rE.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=s-r;break;case rE.ANIMATIONTYPE_QUATERNION:case rE.ANIMATIONTYPE_VECTOR3:case rE.ANIMATIONTYPE_VECTOR2:case rE.ANIMATIONTYPE_SIZE:case rE.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=s.subtract(r)}this._highLimitsCache[e]=s}p=this._highLimitsCache[e],a=this._offsetsCache[e]}if(void 0===a)switch(l.dataType){case rE.ANIMATIONTYPE_FLOAT:a=0;break;case rE.ANIMATIONTYPE_QUATERNION:a=rC;break;case rE.ANIMATIONTYPE_VECTOR3:a=rb;break;case rE.ANIMATIONTYPE_VECTOR2:a=ry;break;case rE.ANIMATIONTYPE_SIZE:a=rA;break;case rE.ANIMATIONTYPE_COLOR3:a=rR}if(this._host&&this._host.syncRoot){let e=this._host.syncRoot,i=(e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame);o=t+c*i}else o=d>0&&t>i||d<0&&t<i?u&&0!==c?i+d%c:t:u&&0!==c?t+d%c:i;let _=this._events;if(s>0&&this.currentFrame>o||s<0&&this.currentFrame<o){this._onLoop();for(let e=0;e<_.length;e++)_[e].onlyOnce||(_[e].isDone=!1);this._animationState.key=s>0?0:l.getKeys().length-1}this._currentFrame=o,this._animationState.repeatCount=0===c?0:d/c>>0,this._animationState.highLimitValue=p,this._animationState.offsetValue=a;let f=l._interpolate(o,this._animationState);if(this.setValue(f,n),_.length){for(let e=0;e<_.length;e++)if(c>0&&o>=_[e].frame&&_[e].frame>=t||c<0&&o<=_[e].frame&&_[e].frame<=t){let t=_[e];t.isDone||(t.onlyOnce&&(_.splice(e,1),e--),t.isDone=!0,t.action(o))}}return u||(this._stopped=!0),u}}var rI=i(6438),rM=i(8257),rD=i(4046),rO=i(5980);class rN extends rT.N{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,r=null,s=null,n=null,a=null){var o;super(e,t.getScene()),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=null!==(o=null==r?void 0:r.clone())&&void 0!==o?o:rr.y3.Identity(),this._restMatrix=null!=s?s:this._localMatrix.clone(),this._bindMatrix=null!=n?n:this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new rr.y3,this._absoluteBindMatrix=new rr.y3,this._absoluteInverseBindMatrix=new rr.y3,this._finalMatrix=new rr.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){let 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){let t=rr.jp.Vector3[0],i=rr.jp.Quaternion[0],r=rr.jp.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:rr._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=rr.P.Zero(),this._localRotation=rr._f.Zero(),this._localPosition=rr.P.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,rr.y3.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e<this.children.length;e++)this.children[e]._updateAbsoluteBindMatrices();this._scalingDeterminant=0>this._absoluteBindMatrix.determinant()?-1:1}markAsDirty(){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this}_markAsDirtyAndCompose(){this.markAsDirty(),this._needToCompose=!0}_markAsDirtyAndDecompose(){this.markAsDirty(),this._needToDecompose=!0}_updatePosition(e,t=rO.T.LOCAL,i,r=!0){let s=this.getLocalMatrix();if(t==rO.T.LOCAL)r?(s.addAtIndex(12,e.x),s.addAtIndex(13,e.y),s.addAtIndex(14,e.z)):s.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let n=rN._TmpMats[0],a=rN._TmpVecs[0];this.parent?i&&t?(n.copyFrom(this.parent.getAbsoluteMatrix()),n.multiplyToRef(t,n)):n.copyFrom(this.parent.getAbsoluteMatrix()):rr.y3.IdentityToRef(n),r&&n.setTranslationFromFloats(0,0,0),n.invert(),rr.P.TransformCoordinatesToRef(e,n,a),r?(s.addAtIndex(12,a.x),s.addAtIndex(13,a.y),s.addAtIndex(14,a.z)):s.setTranslationFromFloats(a.x,a.y,a.z)}this._markAsDirtyAndDecompose()}translate(e,t=rO.T.LOCAL,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=rO.T.LOCAL,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,rO.T.WORLD,t)}scale(e,t,i,r=!1){let s=this.getLocalMatrix(),n=rN._TmpMats[0];for(let r of(rr.y3.ScalingToRef(e,t,i,n),n.multiplyToRef(s,s),n.invert(),this.children)){let s=r.getLocalMatrix();s.multiplyToRef(n,s),s.multiplyAtIndex(12,e),s.multiplyAtIndex(13,t),s.multiplyAtIndex(14,i),r._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),r)for(let s of this.children)s.scale(e,t,i,r)}setScale(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()}getScale(){return this._decompose(),this._localScaling}getScaleToRef(e){this._decompose(),e.copyFrom(this._localScaling)}setYawPitchRoll(e,t,i,r=rO.T.LOCAL,s){if(r===rO.T.LOCAL){let n=rN._TmpQuat;rr._f.RotationYawPitchRollToRef(e,t,i,n),this.setRotationQuaternion(n,r,s);return}let n=rN._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(n,s))return;let a=rN._TmpMats[1];rr.y3.RotationYawPitchRollToRef(e,t,i,a),n.multiplyToRef(a,a),this._rotateWithMatrix(a,r,s)}rotate(e,t,i=rO.T.LOCAL,r){let s=rN._TmpMats[0];s.setTranslationFromFloats(0,0,0),rr.y3.RotationAxisToRef(e,t,s),this._rotateWithMatrix(s,i,r)}setAxisAngle(e,t,i=rO.T.LOCAL,r){if(i===rO.T.LOCAL){let s=rN._TmpQuat;rr._f.RotationAxisToRef(e,t,s),this.setRotationQuaternion(s,i,r);return}let s=rN._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,r))return;let n=rN._TmpMats[1];rr.y3.RotationAxisToRef(e,t,n),s.multiplyToRef(n,n),this._rotateWithMatrix(n,i,r)}setRotation(e,t=rO.T.LOCAL,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=rO.T.LOCAL,i){if(t===rO.T.LOCAL){this._decompose(),this._localRotation.copyFrom(e),this._markAsDirtyAndCompose();return}let r=rN._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=rN._TmpMats[1];rr.y3.FromQuaternionToRef(e,s),r.multiplyToRef(s,s),this._rotateWithMatrix(s,t,i)}setRotationMatrix(e,t=rO.T.LOCAL,i){if(t===rO.T.LOCAL){let r=rN._TmpQuat;rr._f.FromRotationMatrixToRef(e,r),this.setRotationQuaternion(r,t,i);return}let r=rN._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=rN._TmpMats[1];s.copyFrom(e),r.multiplyToRef(e,s),this._rotateWithMatrix(s,t,i)}_rotateWithMatrix(e,t=rO.T.LOCAL,i){let r=this.getLocalMatrix(),s=r.m[12],n=r.m[13],a=r.m[14],o=this.getParent(),l=rN._TmpMats[3],h=rN._TmpMats[4];o&&t==rO.T.WORLD?(i?(l.copyFrom(i.getWorldMatrix()),o.getAbsoluteMatrix().multiplyToRef(l,l)):l.copyFrom(o.getAbsoluteMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):t==rO.T.WORLD&&i?(l.copyFrom(i.getWorldMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):r.multiplyToRef(e,r),r.setTranslationFromFloats(s,n,a),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){let i=rN._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),rr.y3.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):rr.y3.IdentityToRef(i),e.invert(),!isNaN(e.m[0])&&(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=rO.T.LOCAL,t=null){let i=rr.P.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=rO.T.LOCAL,t,i){if(e==rO.T.LOCAL){let e=this.getLocalMatrix();i.x=e.m[12],i.y=e.m[13],i.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let r=rN._TmpMats[0];t&&e?(r.copyFrom(this.getAbsoluteMatrix()),r.multiplyToRef(e,r)):r=this.getAbsoluteMatrix(),i.x=r.m[12],i.y=r.m[13],i.z=r.m[14]}}getAbsolutePosition(e=null){let t=rr.P.Zero();return this.getPositionToRef(rO.T.WORLD,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(rO.T.WORLD,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);let e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}let e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].computeAbsoluteMatrices()}computeAbsoluteTransforms(){this.computeAbsoluteMatrices()}getDirection(e,t=null){let i=rr.P.Zero();return this.getDirectionToRef(e,t,i),i}getDirectionToRef(e,t=null,i){let r=null;t&&(r=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let s=rN._TmpMats[0];s.copyFrom(this.getAbsoluteMatrix()),t&&r&&s.multiplyToRef(r,s),rr.P.TransformNormalToRef(e,s,i),i.normalize()}getRotation(e=rO.T.LOCAL,t=null){let i=rr.P.Zero();return this.getRotationToRef(e,t,i),i}getRotationToRef(e=rO.T.LOCAL,t=null,i){let r=rN._TmpQuat;this.getRotationQuaternionToRef(e,t,r),r.toEulerAnglesToRef(i)}getRotationQuaternion(e=rO.T.LOCAL,t=null){let i=rr._f.Identity();return this.getRotationQuaternionToRef(e,t,i),i}getRotationQuaternionToRef(e=rO.T.LOCAL,t=null,i){if(e==rO.T.LOCAL)this._decompose(),i.copyFrom(this._localRotation);else{let e=rN._TmpMats[0],r=this.getAbsoluteMatrix();t?r.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(r),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.decompose(void 0,i,void 0)}}getRotationMatrix(e=rO.T.LOCAL,t){let i=rr.y3.Identity();return this.getRotationMatrixToRef(e,t,i),i}getRotationMatrixToRef(e=rO.T.LOCAL,t,i){if(e==rO.T.LOCAL)this.getLocalMatrix().getRotationMatrixToRef(i);else{let e=rN._TmpMats[0],r=this.getAbsoluteMatrix();t?r.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(r),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.getRotationMatrixToRef(i)}}getAbsolutePositionFromLocal(e,t=null){let i=rr.P.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,i),i}getAbsolutePositionFromLocalToRef(e,t=null,i){let r=null;t&&(r=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let s=rN._TmpMats[0];s.copyFrom(this.getAbsoluteMatrix()),t&&r&&s.multiplyToRef(r,s),rr.P.TransformCoordinatesToRef(e,s,i)}getLocalPositionFromAbsolute(e,t=null){let i=rr.P.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,i),i}getLocalPositionFromAbsoluteToRef(e,t=null,i){let r=null;t&&(r=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let s=rN._TmpMats[0];s.copyFrom(this.getAbsoluteMatrix()),t&&r&&s.multiplyToRef(r,s),s.invert(),rr.P.TransformCoordinatesToRef(e,s,i)}setCurrentPoseAsRest(){this.setRestMatrix(this.getLocalMatrix())}}rN._TmpVecs=rD.B.BuildArray(2,rr.P.Zero),rN._TmpQuat=rr._f.Identity(),rN._TmpMats=rD.B.BuildArray(5,rr.y3.Identity);class rF{get syncRoot(){return this._syncRoot}get masterFrame(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){if(-1===e){this._weight=-1;return}this._weight=Math.min(Math.max(e,0),1)}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t<this._runtimeAnimations.length;t++){let i=this._runtimeAnimations[t];i._prepareForSpeedRatioChange(e)}this._speedRatio=e,null!==this._goToFrame&&this.goToFrame(this._goToFrame)}constructor(e,t,i=0,r=100,s=!1,n=1,a,o,l,h=!1,u=0){this.target=t,this.fromFrame=i,this.toFrame=r,this.loopAnimation=s,this.onAnimationEnd=a,this.onAnimationLoop=l,this.isAdditive=h,this.playOrder=u,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=[],this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this._frameToSyncFromJump=null,this._goToFrame=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new ri.y$,this.onAnimationLoopObservable=new ri.y$,this._scene=e,o&&this.appendAnimations(t,o),this._speedRatio=n,e._activeAnimatables.push(this)}syncWith(e){if(this._syncRoot=e,e){let e=this._scene._activeAnimatables.indexOf(this);e>-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i<t.length;i++){let r=t[i],s=new rP(e,r,this._scene,this);s._onLoop=()=>{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i].animation;return null}getRuntimeAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)if(t[i].animation.targetProperty===e)return t[i];return null}reset(){let e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null}enableBlending(e){let t=this._runtimeAnimations;for(let i=0;i<t.length;i++)t[i].animation.enableBlending=!0,t[i].animation.blendingSpeed=e}disableBlending(){let e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].animation.enableBlending=!1}goToFrame(e){var t;let i=this._runtimeAnimations;if(i[0]){let r=i[0].animation.framePerSecond;this._frameToSyncFromJump=null!==(t=this._frameToSyncFromJump)&&void 0!==t?t:i[0].currentFrame;let s=0===this.speedRatio?0:(e-this._frameToSyncFromJump)/r*1e3/this.speedRatio;this._manualJumpDelay=-s}for(let t=0;t<i.length;t++)i[t].goToFrame(e);this._goToFrame=e}get paused(){return this._paused}pause(){this._paused||(this._paused=!0)}restart(){this._paused=!1}_raiseOnAnimationEnd(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)}stop(e,t,i=!1){if(e||t){let r=this._scene._activeAnimatables.indexOf(this);if(r>-1){let s=this._runtimeAnimations;for(let i=s.length-1;i>=0;i--){let r=s[i];(!e||r.animation.name==e)&&(!t||t(r.target))&&(r.dispose(),s.splice(i,1))}0==s.length&&(i||this._scene._activeAnimatables.splice(r,1),this._raiseOnAnimationEnd())}}else{let e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);let t=this._runtimeAnimations;for(let e=0;e<t.length;e++)t[e].dispose();this._runtimeAnimations.length=0,this._raiseOnAnimationEnd()}}}waitAsync(){return new Promise(e=>{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){let t;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 i=!1,r=this._runtimeAnimations;for(t=0;t<r.length;t++){let s=r[t],n=s.animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);i=i||n}if(this.animationStarted=i,!i){if(this.disposeOnEnd)for(t=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(t,1),t=0;t<r.length;t++)r[t].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return i}}rI.x.prototype._animate=function(){if(!this.animationsEnabled)return;let e=rM.F.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;let t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;let i=this._animationTime;for(let e=0;e<t.length;e++){let r=t[e];!r._animate(i)&&r.disposeOnEnd&&e--}this._processLateAnimationBindings()},rI.x.prototype.sortActiveAnimatables=function(){this._activeAnimatables.sort((e,t)=>e.playOrder-t.playOrder)},rI.x.prototype.beginWeightedAnimation=function(e,t,i,r=1,s,n=1,a,o,l,h,u=!1){let c=this.beginAnimation(e,t,i,s,n,a,o,!1,l,h,u);return c.weight=r,c},rI.x.prototype.beginAnimation=function(e,t,i,r,s=1,n,a,o=!0,l,h,u=!1){t>i&&s>0&&(s*=-1),o&&this.stopAnimation(e,void 0,l),a||(a=new rF(this,e,t,i,r,s,n,void 0,h,u));let c=!l||l(e);if(e.animations&&c&&a.appendAnimations(e,e.animations),e.getAnimatables){let u=e.getAnimatables();for(let e=0;e<u.length;e++)this.beginAnimation(u[e],t,i,r,s,n,a,o,l,h)}return a.reset(),a},rI.x.prototype.beginHierarchyAnimation=function(e,t,i,r,s,n=1,a,o,l=!0,h,u,c=!1){let d=e.getDescendants(t),p=[];for(let t of(p.push(this.beginAnimation(e,i,r,s,n,a,o,l,h,void 0,c)),d))p.push(this.beginAnimation(t,i,r,s,n,a,o,l,h,void 0,c));return p},rI.x.prototype.beginDirectAnimation=function(e,t,i,r,s,n,a,o,l=!1){if(void 0===n&&(n=1),i>r&&n>0)n*=-1;else if(r>i&&n<0){let e=r;r=i,i=e}let h=new rF(this,e,i,r,s,n,a,t,o,l);return h},rI.x.prototype.beginDirectHierarchyAnimation=function(e,t,i,r,s,n,a,o,l,h=!1){let u=e.getDescendants(t),c=[];for(let t of(c.push(this.beginDirectAnimation(e,i,r,s,n,a,o,l,h)),u))c.push(this.beginDirectAnimation(t,i,r,s,n,a,o,l,h));return c},rI.x.prototype.getAnimatableByTarget=function(e){for(let t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},rI.x.prototype.getAllAnimatablesByTarget=function(e){let t=[];for(let i=0;i<this._activeAnimatables.length;i++)this._activeAnimatables[i].target===e&&t.push(this._activeAnimatables[i]);return t},rI.x.prototype.stopAnimation=function(e,t,i){let r=this.getAllAnimatablesByTarget(e);for(let e of r)e.stop(t,i)},rI.x.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(let e=0;e<this._activeAnimatables.length;e++)this._activeAnimatables[e].stop(void 0,void 0,!0);this._activeAnimatables.length=0}for(let e of this.animationGroups)e.stop()},rI.x.prototype._registerTargetForLateAnimationBinding=function(e,t){let i=e.target;this._registeredForLateAnimationBindings.pushNoDuplicate(i),i._lateAnimationHolders||(i._lateAnimationHolders={}),i._lateAnimationHolders[e.targetPath]||(i._lateAnimationHolders[e.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:t}),e.isAdditive?(i._lateAnimationHolders[e.targetPath].additiveAnimations.push(e),i._lateAnimationHolders[e.targetPath].totalAdditiveWeight+=e.weight):(i._lateAnimationHolders[e.targetPath].animations.push(e),i._lateAnimationHolders[e.targetPath].totalWeight+=e.weight)},rI.x.prototype._processLateAnimationBindingsForMatrices=function(e){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return e.originalValue;let t=1,i=rr.jp.Vector3[0],r=rr.jp.Vector3[1],s=rr.jp.Quaternion[0],n=0,a=e.animations[0],o=e.originalValue,l=1,h=!1;if(e.totalWeight<1)l=1-e.totalWeight,o.decompose(r,s,i);else{if(n=1,t=e.totalWeight,1==(l=a.weight/t)){if(!e.totalAdditiveWeight)return a.currentValue;h=!0}a.currentValue.decompose(r,s,i)}if(!h){r.scaleInPlace(l),i.scaleInPlace(l),s.scaleInPlace(l);for(let a=n;a<e.animations.length;a++){let n=e.animations[a];if(0===n.weight)continue;l=n.weight/t;let o=rr.jp.Vector3[2],h=rr.jp.Vector3[3],u=rr.jp.Quaternion[1];n.currentValue.decompose(h,u,o),h.scaleAndAddToRef(l,r),u.scaleAndAddToRef(rr._f.Dot(s,u)>0?l:-l,s),o.scaleAndAddToRef(l,i)}s.normalize()}for(let t=0;t<e.additiveAnimations.length;t++){let n=e.additiveAnimations[t];if(0===n.weight)continue;let a=rr.jp.Vector3[2],o=rr.jp.Vector3[3],l=rr.jp.Quaternion[1];n.currentValue.decompose(o,l,a),o.multiplyToRef(r,o),rr.P.LerpToRef(r,o,n.weight,r),s.multiplyToRef(l,l),rr._f.SlerpToRef(s,l,n.weight,s),a.scaleAndAddToRef(n.weight,i)}let u=a?a._animationState.workValue:rr.jp.Matrix[0].clone();return rr.y3.ComposeToRef(r,s,i,u),u},rI.x.prototype._processLateAnimationBindingsForQuaternions=function(e,t){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return t;let i=e.animations[0],r=e.originalValue,s=t;if(0===e.totalWeight&&e.totalAdditiveWeight>0)s.copyFrom(r);else if(1===e.animations.length){if(rr._f.SlerpToRef(r,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,n,a=1;if(e.totalWeight<1){let t=1-e.totalWeight;n=[],(i=[]).push(r),n.push(t)}else{if(2===e.animations.length&&(rr._f.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],a=e.totalWeight}for(let t=0;t<e.animations.length;t++){let r=e.animations[t];i.push(r.currentValue),n.push(r.weight/a)}let o=0;for(let e=0;e<i.length;){if(!e){rr._f.SlerpToRef(i[e],i[e+1],n[e+1]/(n[e]+n[e+1]),t),s=t,o=n[e]+n[e+1],e+=2;continue}o+=n[e],rr._f.SlerpToRef(s,i[e],n[e]/o,s),e++}}for(let t=0;t<e.additiveAnimations.length;t++){let i=e.additiveAnimations[t];0!==i.weight&&(s.multiplyToRef(i.currentValue,rr.jp.Quaternion[0]),rr._f.SlerpToRef(s,rr.jp.Quaternion[0],i.weight,s))}return s},rI.x.prototype._processLateAnimationBindings=function(){if(this._registeredForLateAnimationBindings.length){for(let e=0;e<this._registeredForLateAnimationBindings.length;e++){let t=this._registeredForLateAnimationBindings.data[e];for(let e in t._lateAnimationHolders){let i=t._lateAnimationHolders[e],r=i.animations[0],s=i.originalValue;if(null==s)continue;let n=rE.AllowMatrixDecomposeForInterpolation&&s.m,a=t[e];if(n)a=this._processLateAnimationBindingsForMatrices(i);else{let e=void 0!==s.w;if(e)a=this._processLateAnimationBindingsForQuaternions(i,a||rr._f.Identity());else{let e=0,t=1;if(i.totalWeight<1)a=r&&s.scale?s.scale(1-i.totalWeight):r?s*(1-i.totalWeight):s.clone?s.clone():s;else if(r){t=i.totalWeight;let s=r.weight/t;a=1!==s?r.currentValue.scale?r.currentValue.scale(s):r.currentValue*s:r.currentValue,e=1}for(let r=e;r<i.animations.length;r++){let e=i.animations[r],s=e.weight/t;s&&(e.currentValue.scaleAndAddToRef?e.currentValue.scaleAndAddToRef(s,a):a+=e.currentValue*s)}for(let e=0;e<i.additiveAnimations.length;e++){let t=i.additiveAnimations[e],r=t.weight;r&&(t.currentValue.scaleAndAddToRef?t.currentValue.scaleAndAddToRef(r,a):a+=t.currentValue*r)}}}t[e]=a}t._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}},rN.prototype.copyAnimationRange=function(e,t,i,r=!1,s=null){let n,a,o;0===this.animations.length&&(this.animations.push(new rE(this.name,"_matrix",e.animations[0].framePerSecond,rE.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));let l=e.animations[0].getRange(t);if(!l)return!1;let h=l.from,u=l.to,c=e.animations[0].getKeys(),d=e.length,p=e.getParent(),_=this.getParent(),f=r&&p&&d&&this.length&&d!==this.length,m=f&&_&&p?_.length/p.length:1,g=r&&!_&&s&&(1!==s.x||1!==s.y||1!==s.z),v=this.animations[0].getKeys();for(let e=0,t=c.length;e<t;e++)(n=c[e]).frame>=h&&n.frame<=u&&(r?(o=n.value.clone(),f?(a=o.getTranslation(),o.setTranslation(a.scaleInPlace(m))):g&&s?(a=o.getTranslation(),o.setTranslation(a.multiplyInPlace(s))):o=n.value):o=n.value,v.push({frame:n.frame+i,value:o}));return this.animations[0].createRange(t,h+i,u+i),!0};var rL=i(156);(a=ta||(ta={}))[a.CW=0]="CW",a[a.CCW=1]="CCW";class rw{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){let i=t.subtract(e),r=Math.atan2(i.y,i.x);return new rw(r)}static FromRadians(e){return new rw(e)}static FromDegrees(e){return new rw(e*Math.PI/180)}}class rB{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;let r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,n=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new rr.FM((s*(t.y-i.y)-n*(e.y-t.y))/a,((e.x-t.x)*n-(t.x-i.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=rw.BetweenTwoPoints(this.centerPoint,this.startPoint);let o=this.startAngle.degrees(),l=rw.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=rw.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-o>180&&(l-=360),l-o<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-o<0?ta.CW:ta.CCW,this.angle=rw.FromDegrees(this.orientation===ta.CW?o-h:h-o)}}class rU{constructor(e,t){this._points=[],this._length=0,this.closed=!1,this._points.push(new rr.FM(e,t))}addLineTo(e,t){if(this.closed)return this;let i=new rr.FM(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;let n=this._points[this._points.length-1],a=new rr.FM(e,t),o=new rr.FM(i,r),l=new rB(n,a,o),h=l.angle.radians()/s;l.orientation===ta.CW&&(h*=-1);let u=l.startAngle.radians()+h;for(let e=0;e<s;e++){let e=Math.cos(u)*l.radius+l.centerPoint.x,t=Math.sin(u)*l.radius+l.centerPoint.y;this.addLineTo(e,t),u+=h}return this}addQuadraticCurveTo(e,t,i,r,s=36){if(this.closed)return this;let n=this._points[this._points.length-1];for(let a=0;a<=s;a++){let o=a/s,l=(1-o)*(1-o)*n.x+2*o*(1-o)*e+o*o*i,h=(1-o)*(1-o)*n.y+2*o*(1-o)*t+o*o*r;this.addLineTo(l,h)}return this}addBezierCurveTo(e,t,i,r,s,n,a=36){if(this.closed)return this;let o=this._points[this._points.length-1];for(let l=0;l<=a;l++){let h=l/a,u=(1-h)*(1-h)*(1-h)*o.x+3*h*(1-h)*(1-h)*e+3*h*h*(1-h)*i+h*h*h*s,c=(1-h)*(1-h)*(1-h)*o.y+3*h*(1-h)*(1-h)*t+3*h*h*(1-h)*r+h*h*h*n;this.addLineTo(u,c)}return this}isPointInside(e){let t=!1,i=this._points.length;for(let r=i-1,s=0;s<i;r=s++){let i=this._points[r],n=this._points[s],a=n.x-i.x,o=n.y-i.y;if(Math.abs(o)>Number.EPSILON){if(o<0&&(i=this._points[s],a=-a,n=this._points[r],o=-o),e.y<i.y||e.y>n.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{let r=o*(e.x-i.x)-a*(e.y-i.y);if(0===r)return!0;if(r<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){let t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){let e=this._points.length,t=0;for(let i=e-1,r=0;r<e;i=r++)t+=this._points[i].x*this._points[r].y-this._points[r].x*this._points[i].y;return .5*t}getPoints(){return this._points}getPointAtLengthPosition(e){if(e<0||e>1)return rr.FM.Zero();let t=e*this.length(),i=0;for(let e=0;e<this._points.length;e++){let r=(e+1)%this._points.length,s=this._points[e],n=this._points[r],a=n.subtract(s),o=a.length()+i;if(t>=i&&t<=o){let e=a.normalize(),r=t-i;return new rr.FM(s.x+e.x*r,s.y+e.y*r)}i=o}return rr.FM.Zero()}static StartingAt(e,t){return new rU(e,t)}}class rV{constructor(e,t=null,i,r=!1){this.path=e,this._curve=[],this._distances=[],this._tangents=[],this._normals=[],this._binormals=[],this._pointAtData={id:0,point:rr.P.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:rr.y3.Identity()};for(let t=0;t<e.length;t++)this._curve[t]=e[t].clone();this._raw=i||!1,this._alignTangentsWithPath=r,this._compute(t,r)}getCurve(){return this._curve}getPoints(){return this._curve}length(){return this._distances[this._distances.length-1]}getTangents(){return this._tangents}getNormals(){return this._normals}getBinormals(){return this._binormals}getDistances(){return this._distances}getPointAt(e){return this._updatePointAtData(e).point}getTangentAt(e,t=!1){return this._updatePointAtData(e,t),t?rr.P.TransformCoordinates(rr.P.Forward(),this._pointAtData.interpolationMatrix):this._tangents[this._pointAtData.previousPointArrayIndex]}getNormalAt(e,t=!1){return this._updatePointAtData(e,t),t?rr.P.TransformCoordinates(rr.P.Right(),this._pointAtData.interpolationMatrix):this._normals[this._pointAtData.previousPointArrayIndex]}getBinormalAt(e,t=!1){return this._updatePointAtData(e,t),t?rr.P.TransformCoordinates(rr.P.UpReadOnly,this._pointAtData.interpolationMatrix):this._binormals[this._pointAtData.previousPointArrayIndex]}getDistanceAt(e){return this.length()*e}getPreviousPointIndexAt(e){return this._updatePointAtData(e),this._pointAtData.previousPointArrayIndex}getSubPositionAt(e){return this._updatePointAtData(e),this._pointAtData.subPosition}getClosestPositionTo(e){let t=Number.MAX_VALUE,i=0;for(let r=0;r<this._curve.length-1;r++){let s=this._curve[r+0],n=this._curve[r+1].subtract(s).normalize(),a=this._distances[r+1]-this._distances[r+0],o=Math.min(Math.max(rr.P.Dot(n,e.subtract(s).normalize()),0)*rr.P.Distance(s,e)/a,1),l=rr.P.Distance(s.add(n.scale(o*a)),e);l<t&&(t=l,i=(this._distances[r+0]+a*o)/this.length())}return i}slice(e=0,t=1){if(e<0&&(e=1- -1*e%1),t<0&&(t=1- -1*t%1),e>t){let i=e;e=t,t=i}let i=this.getCurve(),r=this.getPointAt(e),s=this.getPreviousPointIndexAt(e),n=this.getPointAt(t),a=this.getPreviousPointIndexAt(t)+1,o=[];return 0!==e&&(s++,o.push(r)),o.push(...i.slice(s,a)),(1!==t||1===e)&&o.push(n),new rV(o,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;t<e.length;t++)this._curve[t].x=e[t].x,this._curve[t].y=e[t].y,this._curve[t].z=e[t].z;return this._compute(t,i),this}_compute(e,t=!1){let i,r,s,n,a;let o=this._curve.length;if(o<2)return;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[o-1]=this._curve[o-1].subtract(this._curve[o-2]),this._raw||this._tangents[o-1].normalize();let l=this._tangents[0],h=this._normalVector(l,e);this._normals[0]=h,this._raw||this._normals[0].normalize(),this._binormals[0]=rr.P.Cross(l,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(let e=1;e<o;e++)i=this._getLastNonNullVector(e),e<o-1&&(r=this._getFirstNonNullVector(e),this._tangents[e]=t?r:i.add(r),this._tangents[e].normalize()),this._distances[e]=this._distances[e-1]+this._curve[e].subtract(this._curve[e-1]).length(),s=this._tangents[e],a=this._binormals[e-1],this._normals[e]=rr.P.Cross(a,s),this._raw||(0===this._normals[e].length()?(n=this._normals[e-1],this._normals[e]=n.clone()):this._normals[e].normalize()),this._binormals[e]=rr.P.Cross(s,this._normals[e]),this._raw||this._binormals[e].normalize();this._pointAtData.id=NaN}_getFirstNonNullVector(e){let t=1,i=this._curve[e+t].subtract(this._curve[e]);for(;0===i.length()&&e+t+1<this._curve.length;)t++,i=this._curve[e+t].subtract(this._curve[e]);return i}_getLastNonNullVector(e){let t=1,i=this._curve[e].subtract(this._curve[e-t]);for(;0===i.length()&&e>t+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i;let r=e.length();if(0===r&&(r=1),null==t){let t;t=rm.R.WithinEpsilon(Math.abs(e.y)/r,1,rL.kn)?rm.R.WithinEpsilon(Math.abs(e.x)/r,1,rL.kn)?rm.R.WithinEpsilon(Math.abs(e.z)/r,1,rL.kn)?rr.P.Zero():new rr.P(0,0,1):new rr.P(1,0,0):new rr.P(0,-1,0),i=rr.P.Cross(e,t)}else i=rr.P.Cross(e,t),rr.P.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){let i;if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;let r=this.getPoints();if(e<=0)return this._setPointAtData(0,0,r[0],0,t);if(e>=1)return this._setPointAtData(1,1,r[r.length-1],r.length-1,t);let s=r[0],n=0,a=e*this.length();for(let o=1;o<r.length;o++){i=r[o];let l=rr.P.Distance(s,i);if((n+=l)===a)return this._setPointAtData(e,1,i,o,t);if(n>a){let r=n-a,h=r/l,u=s.subtract(i),c=i.add(u.scaleInPlace(h));return this._setPointAtData(e,1-h,c,o-1,t)}s=i}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=rr.y3.Identity();let e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){let t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),n=this._tangents[t].clone(),a=this._normals[t].clone(),o=this._binormals[t].clone(),l=rr._f.RotationQuaternionFromAxis(r,s,i),h=rr._f.RotationQuaternionFromAxis(a,o,n),u=rr._f.Slerp(l,h,this._pointAtData.subPosition);u.toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class rk{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;let s=[],n=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;for(let a=0;a<=r;a++)s.push(new rr.P(n(a/r,e.x,t.x,i.x),n(a/r,e.y,t.y,i.y),n(a/r,e.z,t.z,i.z)));return new rk(s)}static CreateCubicBezier(e,t,i,r,s){s=s>3?s:4;let n=[],a=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s;for(let o=0;o<=s;o++)n.push(new rr.P(a(o/s,e.x,t.x,i.x,r.x),a(o/s,e.y,t.y,i.y,r.y),a(o/s,e.z,t.z,i.z,r.z)));return new rk(n)}static CreateHermiteSpline(e,t,i,r,s){let n=[],a=1/s;for(let o=0;o<=s;o++)n.push(rr.P.Hermite(e,t,i,r,o*a));return new rk(n)}static CreateCatmullRomSpline(e,t,i){let r=[],s=1/t,n=0;if(i){let i=e.length;for(let a=0;a<i;a++){n=0;for(let o=0;o<t;o++)r.push(rr.P.CatmullRom(e[a%i],e[(a+1)%i],e[(a+2)%i],e[(a+3)%i],n)),n+=s}r.push(r[0])}else{let i=[];i.push(e[0].clone()),Array.prototype.push.apply(i,e),i.push(e[e.length-1].clone());let a=0;for(;a<i.length-3;a++){n=0;for(let e=0;e<t;e++)r.push(rr.P.CatmullRom(i[a],i[a+1],i[a+2],i[a+3],n)),n+=s}a--,r.push(rr.P.CatmullRom(i[a],i[a+1],i[a+2],i[a+3],n))}return new rk(r)}static ArcThru3Points(e,t,i,r=32,s=!1,n=!1){let a=[],o=t.subtract(e),l=i.subtract(t),h=e.subtract(i),u=rr.P.Cross(o,l),c=u.length();if(c<1e-8)return new rk(a);let d=o.lengthSquared(),p=l.lengthSquared(),_=h.lengthSquared(),f=u.lengthSquared(),m=o.length(),g=l.length(),v=h.length(),T=.5*m*g*v/c,x=rr.P.Dot(o,h),S=rr.P.Dot(o,l),E=rr.P.Dot(l,h),C=e.scale(-.5*p*x/f).add(t.scale(-.5*_*S/f)).add(i.scale(-.5*d*E/f)),b=e.subtract(C),y=b.normalize(),A=rr.P.Cross(u,y).normalize();if(n){let t=2*Math.PI/r;for(let e=0;e<=2*Math.PI;e+=t)a.push(C.add(y.scale(T*Math.cos(e)).add(A.scale(T*Math.sin(e)))));a.push(e)}else{let t=1/r,n=0,o=rr.P.Zero();do o=C.add(y.scale(T*Math.cos(n)).add(A.scale(T*Math.sin(n)))),a.push(o),n+=t;while(!o.equalsWithEpsilon(i,T*t*1.1));a.push(i),s&&a.push(e)}return new rk(a)}constructor(e){this._length=0,this._points=e,this._length=this._computeLength(e)}getPoints(){return this._points}length(){return this._length}continue(e){let t=this._points[this._points.length-1],i=this._points.slice(),r=e.getPoints();for(let e=1;e<r.length;e++)i.push(r[e].subtract(r[0]).add(t));let s=new rk(i);return s}_computeLength(e){let t=0;for(let i=1;i<e.length;i++)t+=e[i].subtract(e[i-1]).length();return t}}class rG{constructor(){this._easingMode=rG.EASINGMODE_EASEIN}setEasingMode(e){this._easingMode=Math.min(Math.max(e,0),2)}getEasingMode(){return this._easingMode}easeInCore(e){throw Error("You must implement this method")}ease(e){switch(this._easingMode){case rG.EASINGMODE_EASEIN:return this.easeInCore(e);case rG.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?(1-this.easeInCore((1-e)*2))*.5+.5:.5*this.easeInCore(2*e)}}rG.EASINGMODE_EASEIN=0,rG.EASINGMODE_EASEOUT=1,rG.EASINGMODE_EASEINOUT=2;class rz extends rG{easeInCore(e){return 1-Math.sqrt(1-(e=Math.max(0,Math.min(1,e)))*e)}}class rW extends rG{easeInCore(e){return e*e}}class rH extends rG{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}var rX=i(8772);class rY{getClassName(){return"TargetedAnimation"}serialize(){let e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class rj{syncWithMask(){if(this.mask)for(let e=0;e<this._animatables.length;++e){let t=this._animatables[e];this.mask.retainsTarget(t.target.name)?t.paused&&t.restart():t.paused||t.pause()}}removeUnmaskedAnimations(){if(this.mask){for(let e=0;e<this._animatables.length;++e){let t=this._animatables[e];!this.mask.retainsTarget(t.target.name)&&(t.stop(),this._animatables.splice(e,1),--e)}for(let e=0;e<this._targetedAnimations.length;e++){let t=this._targetedAnimations[e];!this.mask.retainsTarget(t.target.name)&&(this._targetedAnimations.splice(e,1),--e)}}}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;e<this._animatables.length;e++){let t=this._animatables[e];t.speedRatio=this._speedRatio}}}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.loopAnimation=this._loopAnimation}}}get isAdditive(){return this._isAdditive}set isAdditive(e){if(this._isAdditive!==e){this._isAdditive=e;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.isAdditive=this._isAdditive}}}get weight(){return this._weight}set weight(e){this._weight!==e&&(this._weight=e,this.setWeightForAllAnimatables(this._weight))}get targetedAnimations(){return this._targetedAnimations}get animatables(){return this._animatables}get children(){return this._targetedAnimations}get playOrder(){return this._playOrder}set playOrder(e){if(this._playOrder!==e&&(this._playOrder=e,this._animatables.length>0)){for(let e=0;e<this._animatables.length;e++)this._animatables[e].playOrder=this._playOrder;this._scene.sortActiveAnimatables()}}enableBlending(e){for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=!0,this._targetedAnimations[t].animation.blendingSpeed=e}disableBlending(){for(let e=0;e<this._targetedAnimations.length;++e)this._targetedAnimations[e].animation.enableBlending=!1}static MergeAnimationGroups(e,t=!0,i=!1,r){if(0===e.length)return null;r=null!=r?r:e[0].weight;let s=Number.MAX_VALUE,n=Number.MIN_VALUE;if(i)for(let t of e)t.from<s&&(s=t.from),t.to>n&&(n=t.to);let a=new rj(e[0].name+"_merged",e[0]._scene,r);for(let r of e){for(let e of(i&&r.normalize(s,n),r.targetedAnimations))a.addTargetedAnimation(e.animation,e.target);t&&r.dispose()}return a}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=[],this._animatables=[],this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._parentContainer=null,this.onAnimationEndObservable=new ri.y$,this.onAnimationLoopObservable=new ri.y$,this.onAnimationGroupLoopObservable=new ri.y$,this.onAnimationGroupEndObservable=new ri.y$,this.onAnimationGroupPauseObservable=new ri.y$,this.onAnimationGroupPlayObservable=new ri.y$,this.metadata=null,this._animationLoopFlags=[],this._scene=t||rp.l.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){let i=new rY;i.animation=e,i.target=t;let r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to<r[r.length-1].frame&&(this._to=r[r.length-1].frame),this._targetedAnimations.push(i),i}removeTargetedAnimation(e){for(let t=this._targetedAnimations.length-1;t>-1;t--){let i=this._targetedAnimations[t];i.animation===e&&this._targetedAnimations.splice(t,1)}}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;i<this._targetedAnimations.length;i++){let r=this._targetedAnimations[i],s=r.animation.getKeys(),n=s[0],a=s[s.length-1];if(n.frame>e){let t={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};s.splice(0,0,t)}if(a.frame<t){let e={frame:t,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};s.push(e)}}return this._from=e,this._to=t,this}_processLoop(e,t,i){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount!==this._targetedAnimations.length||(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n<this._targetedAnimations.length;n++){let a=this._targetedAnimations[n],o=this._scene.beginDirectAnimation(a.target,[a.animation],void 0!==i?i:this._from,void 0!==r?r:this._to,e,t,void 0,void 0,void 0!==s?s:this._isAdditive);o.weight=this._weight,o.playOrder=this._playOrder,o.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(a),this._checkAnimationGroupEnded(o)},this._processLoop(o,a,n),this._animatables.push(o)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.pause()}return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length===this._targetedAnimations.length?(void 0!==e&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this._isPaused=!1,this}reset(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(),this;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.reset()}return this}restart(){if(!this._isStarted)return this;for(let e=0;e<this._animatables.length;e++){let t=this._animatables[e];t.restart()}return this.onAnimationGroupPlayObservable.notifyObservers(this),this}stop(){if(!this._isStarted)return this;let e=this._animatables.slice();for(let t=0;t<e.length;t++)e[t].stop(void 0,void 0,!0);let t=0;for(let e=0;e<this._scene._activeAnimatables.length;e++){let i=this._scene._activeAnimatables[e];i._runtimeAnimations.length>0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.weight=e}return this}syncAllAnimationsWith(e){for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.syncWith(e)}return this}goToFrame(e){if(!this._isStarted)return this;for(let t=0;t<this._animatables.length;t++){let i=this._animatables[t];i.goToFrame(e)}return this}dispose(){this._targetedAnimations.length=0,this._animatables.length=0;let e=this._scene.animationGroups.indexOf(this);if(e>-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){let 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){let 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){let r=new rj(e||this.name,this._scene);for(let e of this._targetedAnimations)r.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return r}serialize(){let e={};e.name=this.name,e.from=this.from,e.to=this.to,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){let i=this.targetedAnimations[t];e.targetedAnimations[t]=i.serialize()}return rX.$&&rX.$.HasTags(this)&&(e.tags=rX.$.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t){let i=new rj(e.name,t);for(let r=0;r<e.targetedAnimations.length;r++){let s=e.targetedAnimations[r],n=rE.Parse(s.animation),a=s.targetId;if("influence"===s.animation.property){let e=t.getMorphTargetById(a);e&&i.addTargetedAnimation(n,e)}else{let e=t.getNodeById(a);null!=e&&i.addTargetedAnimation(n,e)}}return null!==e.from&&null!==e.to&&i.normalize(e.from,e.to),rX.$&&rX.$.AddTagsTo(i,e.tags),void 0!==e.metadata&&(i.metadata=e.metadata),i}static MakeAnimationAdditive(e,t=0,i,r=!1,s){let n=e;r&&(n=e.clone(s||n.name));let a=n.targetedAnimations;for(let e=0;e<a.length;e++){let r=a[e];rE.MakeAnimationAdditive(r.animation,t,i)}return n.isAdditive=!0,n}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from+", to: "+this._to+", isStarted: "+this._isStarted+", speedRatio: "+this._speedRatio+", targetedAnimations length: "+this._targetedAnimations.length+", animatables length: "+this._animatables),t}}(o=to||(to={}))[o.Include=0]="Include",o[o.Exclude=1]="Exclude";var rq=i(7104),rK=i(2469),r$=i(1572),rQ=i(7620),rZ=i(3636);rq.Kj._instancedMeshFactory=(e,t)=>{let i=new rJ(e,t);if(t.instancedBuffers)for(let e in i.instancedBuffers={},t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e];return i};class rJ extends r$.x{constructor(e,t){for(let i of(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(),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&&rZ.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&&rZ.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&&rZ.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&&rZ.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&&ru.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,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i=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||ru.Y.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){let i=this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0;if(i)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!==rK.Y.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new rr.y3);let e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,rr.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(rr.jp.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;let t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){let t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this}_generatePointsArray(){return this._sourceMesh._generatePointsArray()}_updateBoundingInfo(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}clone(e,t=null,i,r){let s=(r||this._sourceMesh).createInstance(e);if(r_.j.DeepCopy(this,s,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo"],[]),this.refreshBoundingInfo(),t&&(s.parent=t),!i)for(let e=0;e<this.getScene().meshes.length;e++){let t=this.getScene().meshes[e];t.parent===this&&t.clone(t.name,s)}return s.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(s),s}dispose(e,t=!1){this._sourceMesh.removeInstance(this),super.dispose(e,t)}_serializeAsParent(e){super._serializeAsParent(e),e.parentId=this._sourceMesh.uniqueId,e.parentInstanceIndex=this._indexInSourceMeshInstanceArray}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);for(let e of(r&&i&&i(this,r),this.getChildTransformNodes(!0)))e.instantiateHierarchy(r,t,i);return r}}rq.Kj.prototype.registerInstancedBuffer=function(e,t){var i,r;if(null===(r=null===(i=this._userInstancedBuffersStorage)||void 0===i?void 0:i.vertexBuffers[e])||void 0===r||r.dispose(),!this.instancedBuffers){for(let e of(this.instancedBuffers={},this.instances))e.instancedBuffers={};this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0})}for(let i of(this.instancedBuffers[e]=null,this._userInstancedBuffersStorage.strides[e]=t,this._userInstancedBuffersStorage.sizes[e]=32*t,this._userInstancedBuffersStorage.data[e]=new Float32Array(this._userInstancedBuffersStorage.sizes[e]),this._userInstancedBuffersStorage.vertexBuffers[e]=new rQ.o(this.getEngine(),this._userInstancedBuffersStorage.data[e],e,!0,!1,t,!0),this.instances))i.instancedBuffers[e]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()},rq.Kj.prototype._processInstancedBuffers=function(e,t){let i=e?e.length:0;for(let r in this.instancedBuffers){let s=this._userInstancedBuffersStorage.sizes[r],n=this._userInstancedBuffersStorage.strides[r],a=(i+1)*n;for(;s<a;)s*=2;this._userInstancedBuffersStorage.data[r].length!=s&&(this._userInstancedBuffersStorage.data[r]=new Float32Array(s),this._userInstancedBuffersStorage.sizes[r]=s,this._userInstancedBuffersStorage.vertexBuffers[r]&&(this._userInstancedBuffersStorage.vertexBuffers[r].dispose(),this._userInstancedBuffersStorage.vertexBuffers[r]=null));let o=this._userInstancedBuffersStorage.data[r],l=0;if(t){let e=this.instancedBuffers[r];e.toArray?e.toArray(o,l):e.copyToArray?e.copyToArray(o,l):o[l]=e,l+=n}for(let t=0;t<i;t++){let i=e[t],s=i.instancedBuffers[r];s.toArray?s.toArray(o,l):s.copyToArray?s.copyToArray(o,l):o[l]=s,l+=n}this._userInstancedBuffersStorage.vertexBuffers[r]?this._userInstancedBuffersStorage.vertexBuffers[r].updateDirectly(o,0):(this._userInstancedBuffersStorage.vertexBuffers[r]=new rQ.o(this.getEngine(),this._userInstancedBuffersStorage.data[r],r,!0,!1,n,!0),this._invalidateInstanceVertexArrayObject())}},rq.Kj.prototype._invalidateInstanceVertexArrayObject=function(){if(this._userInstancedBuffersStorage&&void 0!==this._userInstancedBuffersStorage.vertexArrayObjects){for(let e in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[e]);this._userInstancedBuffersStorage.vertexArrayObjects={}}},rq.Kj.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(let e in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[e]&&this._userInstancedBuffersStorage.vertexBuffers[e].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}};var r0=i(6851),r1=i(1378),r2=i(8463);class r3 extends rT.N{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}constructor(e,t){super(e,t),this.diffuse=new rs.Wo(1,1,1),this.specular=new rs.Wo(1,1,1),this.falloffType=r3.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=r3.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=[],this._includedOnlyMeshesIds=[],this._isLight=!0,this.getScene().addLight(this),this._uniformBuffer=new r1.M(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,r,s=!0){var n;let a=e.toString(),o=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+a),this._renderId!==t.getRenderId()||this._lastUseSpecular!==r||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=r;let e=this.getScaledIntensity();this.transferToEffect(i,a),this.diffuse.scaleToRef(e,rs.zZ.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",rs.zZ.Color3[0],this.range,a),r&&(this.specular.scaleToRef(e,rs.zZ.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",rs.zZ.Color3[1],this.radius,a)),o=!0}if(this.transferTexturesToEffect(i,a),t.shadowsEnabled&&this.shadowEnabled&&s){let e=null!==(n=this.getShadowGenerator(t.activeCamera))&&void 0!==n?n:this.getShadowGenerator();e&&(e.bindShadowLight(a,i),o=!0)}o?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(let i=0;i<this.animations.length;i++)t+=", animation[0]: "+this.animations[i].toString(e);return t}_syncParentEnabledState(){super._syncParentEnabledState(),this.isDisposed()||this._resyncMeshes()}setEnabled(e){super.setEnabled(e),this._resyncMeshes()}getShadowGenerator(e=null){var t;return null===this._shadowGenerators?null:null!==(t=this._shadowGenerators.get(e))&&void 0!==t?t:null}getShadowGenerators(){return this._shadowGenerators}getAbsolutePosition(){return rr.P.Zero()}canAffectMesh(e){return!e||(!this.includedOnlyMeshes||!(this.includedOnlyMeshes.length>0)||-1!==this.includedOnlyMeshes.indexOf(e))&&(!this.excludedMeshes||!(this.excludedMeshes.length>0)||-1===this.excludedMeshes.indexOf(e))&&(0===this.includeOnlyWithLayerMask||(this.includeOnlyWithLayerMask&e.layerMask)!=0)&&(0===this.excludeWithLayerMask||!(this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){let e=t.value;e.dispose()}this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){let e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(let e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){let i=r3.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;let r=rg.p4.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){let e=rg.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)})),rg.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){let r=rT.N.Construct("Light_Type_"+e,t,i);return r||null}static Parse(e,t){let i=r3.GetConstructorFromName(e.type,e.name,t);if(!i)return null;let r=rg.p4.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(r.falloffType=e.falloffType),void 0!==e.lightmapMode&&(r.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t<e.animations.length;t++){let i=e.animations[t],s=(0,rn.q)("BABYLON.Animation");s&&r.animations.push(s.Parse(i))}rT.N.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&r.setEnabled(e.isEnabled),r}_hookArrayForExcluded(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);for(let e of i)e._resyncLightSource(this);return r};let i=e.splice;for(let t of(e.splice=(t,r)=>{let s=i.apply(e,[t,r]);for(let e of s)e._resyncLightSource(this);return s},e))t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._resyncMeshes(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(let e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(let e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0,t=this.getTypeID(),i=this.intensityMode;switch(i===r3.INTENSITYMODE_AUTOMATIC&&(i=t===r3.LIGHTTYPEID_DIRECTIONALLIGHT?r3.INTENSITYMODE_ILLUMINANCE:r3.INTENSITYMODE_LUMINOUSINTENSITY),t){case r3.LIGHTTYPEID_POINTLIGHT:case r3.LIGHTTYPEID_SPOTLIGHT:switch(i){case r3.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case r3.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case r3.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case r3.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case r3.INTENSITYMODE_ILLUMINANCE:e=1;break;case r3.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001);let i=2*Math.PI*(1-Math.cos(t));e=i}}break;case r3.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){let e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}r3.FALLOFF_DEFAULT=r2.m.FALLOFF_DEFAULT,r3.FALLOFF_PHYSICAL=r2.m.FALLOFF_PHYSICAL,r3.FALLOFF_GLTF=r2.m.FALLOFF_GLTF,r3.FALLOFF_STANDARD=r2.m.FALLOFF_STANDARD,r3.LIGHTMAP_DEFAULT=r2.m.LIGHTMAP_DEFAULT,r3.LIGHTMAP_SPECULAR=r2.m.LIGHTMAP_SPECULAR,r3.LIGHTMAP_SHADOWSONLY=r2.m.LIGHTMAP_SHADOWSONLY,r3.INTENSITYMODE_AUTOMATIC=r2.m.INTENSITYMODE_AUTOMATIC,r3.INTENSITYMODE_LUMINOUSPOWER=r2.m.INTENSITYMODE_LUMINOUSPOWER,r3.INTENSITYMODE_LUMINOUSINTENSITY=r2.m.INTENSITYMODE_LUMINOUSINTENSITY,r3.INTENSITYMODE_ILLUMINANCE=r2.m.INTENSITYMODE_ILLUMINANCE,r3.INTENSITYMODE_LUMINANCE=r2.m.INTENSITYMODE_LUMINANCE,r3.LIGHTTYPEID_POINTLIGHT=r2.m.LIGHTTYPEID_POINTLIGHT,r3.LIGHTTYPEID_DIRECTIONALLIGHT=r2.m.LIGHTTYPEID_DIRECTIONALLIGHT,r3.LIGHTTYPEID_SPOTLIGHT=r2.m.LIGHTTYPEID_SPOTLIGHT,r3.LIGHTTYPEID_HEMISPHERICLIGHT=r2.m.LIGHTTYPEID_HEMISPHERICLIGHT,(0,r0.gn)([(0,rg.n9)()],r3.prototype,"diffuse",void 0),(0,r0.gn)([(0,rg.n9)()],r3.prototype,"specular",void 0),(0,r0.gn)([(0,rg.qC)()],r3.prototype,"falloffType",void 0),(0,r0.gn)([(0,rg.qC)()],r3.prototype,"intensity",void 0),(0,r0.gn)([(0,rg.qC)()],r3.prototype,"range",null),(0,r0.gn)([(0,rg.qC)()],r3.prototype,"intensityMode",null),(0,r0.gn)([(0,rg.qC)()],r3.prototype,"radius",null),(0,r0.gn)([(0,rg.qC)()],r3.prototype,"_renderPriority",void 0),(0,r0.gn)([(0,rg.wz)("_reorderLightsInScene")],r3.prototype,"renderPriority",void 0),(0,r0.gn)([(0,rg.qC)("shadowEnabled")],r3.prototype,"_shadowEnabled",void 0),(0,r0.gn)([(0,rg.qC)("excludeWithLayerMask")],r3.prototype,"_excludeWithLayerMask",void 0),(0,r0.gn)([(0,rg.qC)("includeOnlyWithLayerMask")],r3.prototype,"_includeOnlyWithLayerMask",void 0),(0,r0.gn)([(0,rg.qC)("lightmapMode")],r3.prototype,"_lightmapMode",void 0);var r4=i(7419);class r5 extends re.p{}class r6{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 r8 extends re.p{constructor(e){if(super(),this._wasAddedToScene=!1,!(e=e||rp.l.LastCreatedScene))return;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(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of this.particleSystems)e.rebuild();for(let e of this.textures)e._rebuild()})}_topologicalSort(e){let t=new Map;for(let i of e)t.set(i.uniqueId,i);let i={dependsOn:new Map,dependedBy:new Map};for(let t of e){let e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(let r of e){let e=r.uniqueId,s=i.dependsOn.get(e);if(r instanceof rJ){let n=r.sourceMesh;t.has(n.uniqueId)&&(s.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}let n=i.dependedBy.get(e);for(let s of r.getDescendants()){let r=s.uniqueId;if(t.has(r)){n.add(r);let t=i.dependsOn.get(r);t.add(e)}}}let r=[],s=[];for(let r of e){let e=r.uniqueId;0===i.dependsOn.get(e).size&&(s.push(r),t.delete(e))}for(;s.length>0;){let e=s.shift();r.push(e);let n=i.dependedBy.get(e.uniqueId);for(let r of Array.from(n.values())){let n=i.dependsOn.get(r);n.delete(e.uniqueId),0===n.size&&t.get(r)&&(s.push(t.get(r)),t.delete(r))}}return t.size>0&&(console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(e=>console.error(e.name))),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId)))for(let s of(e.push(i),t.add(i.uniqueId),i.getDescendants(!0)))this._addNodeAndDescendantsToList(e,t,s,r)}_isNodeInContainer(e){return e instanceof rq.Kj&&-1!==this.meshes.indexOf(e)||e instanceof rK.Y&&-1!==this.transformNodes.indexOf(e)||e instanceof r3&&-1!==this.lights.indexOf(e)||e instanceof r4.V&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(let e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return ru.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return ru.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return ru.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return ru.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||rZ.w1.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");let r={},s={},n=new r6,a=[],o=[],l=Object.assign({doNotInstantiate:!0},i),h=(t,i)=>{if(r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof rq.Kj&&i.morphTargetManager){let e=t.morphTargetManager;i.morphTargetManager=e.clone();for(let t=0;t<e.numTargets;t++){let n=e.getTarget(t),a=i.morphTargetManager.getTarget(t);r[n.uniqueId]=a.uniqueId,s[a.uniqueId]=a}}},u=[],c=new Set;for(let e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(u,c,e,l.predicate);for(let e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(u,c,e,l.predicate);let d=this._topologicalSort(u),p=(i,a)=>{if(h(i,a),i.parent){let e=r[i.parent.uniqueId],t=s[e];t?a.parent=t:a.parent=i.parent}if(a.position&&i.position&&a.position.copyFrom(i.position),a.rotationQuaternion&&i.rotationQuaternion&&a.rotationQuaternion.copyFrom(i.rotationQuaternion),a.rotation&&i.rotation&&a.rotation.copyFrom(i.rotation),a.scaling&&i.scaling&&a.scaling.copyFrom(i.scaling),a.material&&a.material){if(t){let t=i.material;if(-1===o.indexOf(t)){let i=t.clone(e?e(t.name):"Clone of "+t.name);if(o.push(t),r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,"MultiMaterial"===t.getClassName()){for(let n of t.subMaterials)n&&(i=n.clone(e?e(n.name):"Clone of "+n.name),o.push(n),r[n.uniqueId]=i.uniqueId,s[i.uniqueId]=i);t.subMaterials=t.subMaterials.map(e=>e&&s[r[e.uniqueId]])}}"InstancedMesh"!==a.getClassName()&&(a.material=s[r[t.uniqueId]])}else"MultiMaterial"===a.material.getClassName()?-1===this.scene.multiMaterials.indexOf(a.material)&&this.scene.addMultiMaterial(a.material):-1===this.scene.materials.indexOf(a.material)&&this.scene.addMaterial(a.material)}null===a.parent&&n.rootNodes.push(a)};return d.forEach(e=>{if("InstancedMesh"===e.getClassName()){let t=e.sourceMesh,i=r[t.uniqueId],n="number"==typeof i?s[i]:t,a=n.createInstance(e.name);p(e,a)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);let i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw Error(`Could not clone or instantiate node on Asset Container ${e.name}`);p(e,i)}}),this.skeletons.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name);for(let e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){let t=s[r[e.uniqueId]];if(!t||t.isAnInstance||(t.skeleton=i,-1!==a.indexOf(i)))continue;for(let e of(a.push(i),i.bones))e._linkedTransformNode&&(e._linkedTransformNode=s[r[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)}),this.animationGroups.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name,e=>{let t=s[r[e.uniqueId]];return t||e});n.animationGroups.push(i)}),n}addAllToScene(){if(!this._wasAddedToScene){for(let e of(this._isValidHierarchy()||rZ.w1.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture),this.scene._serializableComponents))e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){let t=[];for(let i of(this.cameras.forEach(i=>{(!e||e(i))&&(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{(!e||e(i))&&(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{(!e||e(i))&&(this.scene.addMesh(i),t.push(i))}),this.skeletons.forEach(t=>{(!e||e(t))&&this.scene.addSkeleton(t)}),this.animations.forEach(t=>{(!e||e(t))&&this.scene.addAnimation(t)}),this.animationGroups.forEach(t=>{(!e||e(t))&&this.scene.addAnimationGroup(t)}),this.multiMaterials.forEach(t=>{(!e||e(t))&&this.scene.addMultiMaterial(t)}),this.materials.forEach(t=>{(!e||e(t))&&this.scene.addMaterial(t)}),this.morphTargetManagers.forEach(t=>{(!e||e(t))&&this.scene.addMorphTargetManager(t)}),this.geometries.forEach(t=>{(!e||e(t))&&this.scene.addGeometry(t)}),this.transformNodes.forEach(i=>{(!e||e(i))&&(this.scene.addTransformNode(i),t.push(i))}),this.actionManagers.forEach(t=>{(!e||e(t))&&this.scene.addActionManager(t)}),this.textures.forEach(t=>{(!e||e(t))&&this.scene.addTexture(t)}),this.reflectionProbes.forEach(t=>{(!e||e(t))&&this.scene.addReflectionProbe(t)}),t))i.parent&&-1===this.scene.getNodes().indexOf(i.parent)&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){for(let e of(this._isValidHierarchy()||rZ.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),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(){for(let e of(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),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(let r of e){let e=!0;if(i){for(let t of i)if(r===t){e=!1;break}}e&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){for(let t in this._wasAddedToScene=!1,void 0===e&&(e=new r5),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(){let e=new rq.Kj("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=rp.l.LastCreatedScene,t,i=null){if(!e)return ru.Y.Error("No scene available to merge animations to"),[];let r=i||(t=>{let i=null,r=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(r){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i}),s=this.getNodes();s.forEach(e=>{let t=r(e);if(null!==t){for(let i of e.animations){let e=t.animations.filter(e=>e.targetProperty===i.targetProperty);for(let i of e){let e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}});let n=[];return this.animationGroups.slice().forEach(e=>{n.push(e.clone(e.name,r)),e.animatables.forEach(e=>{e.stop()})}),t.forEach(t=>{let i=r(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))}),n}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}),this.transformNodes.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}),this.lights.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}),this.cameras.forEach(e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})}}var r7=i(3700),r9=i(216);r7.D.AudioEngineFactory=(e,t,i)=>new se(e,t,i);class se{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new ri.y$,this.onAudioLockedObservable=new ri.y$,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,r9.CG)())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);let r=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{r&&r.canPlayType&&(r.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||r.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{r&&r.canPlayType&&r.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if((null===(e=this._audioContext)||void 0===e?void 0:e.state)==="running"){this._hideMuteButton();return}this._tryToRun?null===(t=this._audioContext)||void 0===t||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return(null===(e=this._audioContext)||void 0===e?void 0:e.resume)?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,ru.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";let e=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",t=document.createElement("style");t.appendChild(document.createTextNode(".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); 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) }")),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",()=>{this._triggerRunningState()},!0),this._muteButton.addEventListener("click",()=>{this.unlock()},!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}var st=i(4620);class si{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=r7.D.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){let e=this.isPaused?0:r7.D.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;let t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,s){var n,a,o,l,h;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 ri.y$,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=rr.P.Zero(),this._localDirection=new rr.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||rp.l.LastCreatedScene))return;if(this._scene=i,si._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(e,t,i,r,s)=>t<i?e*(1-t/i):0,s&&(this.autoplay=s.autoplay||!1,this._loop=s.loop||!1,void 0!==s.volume&&(this._volume=s.volume),this._spatialSound=null!==(n=s.spatialSound)&&void 0!==n&&n,this.maxDistance=null!==(a=s.maxDistance)&&void 0!==a?a:100,this.useCustomAttenuation=null!==(o=s.useCustomAttenuation)&&void 0!==o&&o,this.rolloffFactor=s.rolloffFactor||1,this.refDistance=s.refDistance||1,this.distanceModel=s.distanceModel||"linear",this._playbackRate=s.playbackRate||1,this._streaming=null!==(l=s.streaming)&&void 0!==l&&l,this._length=s.length,this._offset=s.offset),(null===(h=r7.D.audioEngine)||void 0===h?void 0:h.canUseWebAudio)&&r7.D.audioEngine.audioContext){this._soundGain=r7.D.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this._spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.addSound(this);let e=!0;if(t)try{"string"==typeof t?this._urlType="String":t instanceof ArrayBuffer?this._urlType="ArrayBuffer":t instanceof HTMLMediaElement?this._urlType="MediaElement":t instanceof MediaStream?this._urlType="MediaStream":t instanceof AudioBuffer?this._urlType="AudioBuffer":Array.isArray(t)&&(this._urlType="Array");let i=[],r=!1;switch(this._urlType){case"MediaElement":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=r7.D.audioEngine.audioContext.createMediaElementSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=r7.D.audioEngine.audioContext.createMediaStreamSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":t.byteLength>0&&(r=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e<i.length;e++){let t=i[e];if(r=s&&s.skipCodecCheck||-1!==t.indexOf(".mp3",t.length-4)&&r7.D.audioEngine.isMP3supported||-1!==t.indexOf(".ogg",t.length-4)&&r7.D.audioEngine.isOGGsupported||-1!==t.indexOf(".wav",t.length-4)||-1!==t.indexOf(".m4a",t.length-4)||-1!==t.indexOf(".mp4",t.length-4)||-1!==t.indexOf("blob:")){this._streaming?(this._htmlAudioElement=new Audio(t),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,rZ.w1.SetCorsBehavior(t,this._htmlAudioElement),this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",()=>{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()}),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,e=>{this._soundLoaded(e)},void 0,!0,!0,e=>{e&&ru.Y.Error("XHR "+e.status+" error on: "+t+"."),ru.Y.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:e=!1}e?!r&&(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):ru.Y.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){ru.Y.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),r7.D.audioEngine&&!r7.D.audioEngine.WarnedWebAudioUnsupported&&(ru.Y.Error("Web Audio is not supported by your browser."),r7.D.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(null===(e=r7.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),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){var t;(null===(t=r7.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=r7.D.audioEngine)||void 0===t?void 0:t.audioContext)&&r7.D.audioEngine.audioContext.decodeAudioData(e,e=>{this._audioBufferLoaded(e)},e=>{ru.Y.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)})}setAudioBuffer(e){var t;(null===(t=r7.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,r,s,n,a,o,l,h,u,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!==(r=e.useCustomAttenuation)&&void 0!==r?r:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(n=e.refDistance)&&void 0!==n?n:this.refDistance,this.distanceModel=null!==(a=e.distanceModel)&&void 0!==a?a:this.distanceModel,this._playbackRate=null!==(o=e.playbackRate)&&void 0!==o?o:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this.spatialSound=null!==(h=e.spatialSound)&&void 0!==h?h:this._spatialSound,this._setOffset(null!==(u=e.offset)&&void 0!==u?u: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=r7.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&r7.D.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:r7.D.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,null===(e=this._soundPanner)||void 0===e||e.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){var e;(null===(e=r7.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=r7.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){if(t<e){ru.Y.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=e,this._coneOuterAngle=t,this._coneOuterGain=i,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){var t;if(e!=this._coneInnerAngle){if(this._coneOuterAngle<e){ru.Y.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneInnerAngle=e,(null===(t=r7.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){var t;if(e!=this._coneOuterAngle){if(e<this._coneInnerAngle){ru.Y.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");return}this._coneOuterAngle=e,(null===(t=r7.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}}setPosition(e){var t;!e.equals(this._position)&&(this._position.copyFrom(e),(null===(t=r7.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z))}setLocalDirectionToMesh(e){var t;this._localDirection=e,(null===(t=r7.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()}_updateDirection(){if(!this._connectedTransformNode||!this._soundPanner)return;let e=this._connectedTransformNode.getWorldMatrix(),t=rr.P.TransformNormal(this._localDirection,e);t.normalize(),this._soundPanner.orientationX.value=t.x,this._soundPanner.orientationY.value=t.y,this._soundPanner.orientationZ.value=t.z}updateDistanceFromListener(){var e;if((null===(e=r7.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){let e=this._scene.audioListenerPositionProvider?this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length():this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,e,this.maxDistance,this.refDistance,this.rolloffFactor)}}setAttenuationFunction(e){this._customAttenuationFunction=e}play(e,t,i){var r,s,n,a;if(this._isReadyToPlay&&this._scene.audioEnabled&&(null===(r=r7.D.audioEngine)||void 0===r?void 0:r.audioContext))try{this._clearTimeoutsAndObservers();let r=e?(null===(s=r7.D.audioEngine)||void 0===s?void 0:s.audioContext.currentTime)+e:null===(n=r7.D.audioEngine)||void 0===n?void 0:n.audioContext.currentTime;if((!this._soundSource||!this._streamingSource)&&this._spatialSound&&this._soundPanner&&(isNaN(this._position.x)||isNaN(this._position.y)||isNaN(this._position.z)||(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=r7.D.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=()=>{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){let e=()=>{var t,i;if(null===(t=r7.D.audioEngine)||void 0===t?void 0:t.unlocked){let t=this._htmlAudioElement.play();void 0!==t&&t.catch(()=>{var t,i;null===(t=r7.D.audioEngine)||void 0===t||t.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(i=r7.D.audioEngine)||void 0===i?void 0:i.onAudioUnlockedObservable.addOnce(()=>{e()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(i=r7.D.audioEngine)||void 0===i?void 0:i.onAudioUnlockedObservable.addOnce(()=>{e()}))};e()}}else{let s=()=>{var s,n,a,o;if(null===(s=r7.D.audioEngine)||void 0===s?void 0:s.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){let e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=null===(n=r7.D.audioEngine)||void 0===n?void 0:n.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},r=e?(null===(a=r7.D.audioEngine)||void 0===a?void 0:a.audioContext.currentTime)+e:r7.D.audioEngine.audioContext.currentTime;let s=((this.isPaused?this.currentTime:0)+(null!==(o=this._offset)&&void 0!==o?o:0))%this._soundSource.buffer.duration;this._soundSource.start(r,s,this.loop?void 0:i)}}};(null===(a=r7.D.audioEngine)||void 0===a?void 0:a.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var e;(null===(e=r7.D.audioEngine)||void 0===e?void 0:e.audioContext.state)==="suspended"?(r7.D.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=r7.D.audioEngine.onAudioUnlockedObservable.addOnce(()=>{s()}))):s()},500):s()}this._startTime=r,this.isPlaying=!0,this.isPaused=!1}catch(e){ru.Y.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){var t;if(this.isPlaying){if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((null===(t=r7.D.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){let t=e?r7.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=()=>void 0),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1}else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=r7.D.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>void 0,this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=r7.D.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=r7.D.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&r7.D.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(r7.D.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,r7.D.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,r7.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){let t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=r7.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{let e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new si(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){let 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,r){let s,n;let a=e.name;s=e.url?i+e.url:i+a;let o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};if(r){let e=()=>{r._isReadyToPlay?(n._audioBuffer=r.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play(0,n._offset,n._length)):setTimeout(e,300)};n=new si(a,new ArrayBuffer(0),t,null,o),e()}else n=new si(a,s,t,()=>{t.removePendingData(n)},o),t.addPendingData(n);if(e.position){let t=rr.P.FromArray(e.position);n.setPosition(t)}if(e.isDirectional&&(n.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){let t=rr.P.FromArray(e.localDirectionToMesh);n.setLocalDirectionToMesh(t)}if(e.connectedMeshId){let i=t.getMeshById(e.connectedMeshId);i&&n.attachToMesh(i)}return e.metadata&&(n.metadata=e.metadata),n}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(null===(e=r7.D.audioEngine)||void 0===e||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}si._SceneComponentInitialization=e=>{throw(0,st.S)("AudioSceneComponent")};class sr{constructor(e,t={}){if(this.id=-1,this._isInitialized=!1,!(e=e||rp.l.LastCreatedScene))return;this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}_initializeSoundTrackAudioGraph(){var e;(null===(e=r7.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&r7.D.audioEngine.audioContext&&(this._outputAudioNode=r7.D.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(r7.D.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(r7.D.audioEngine&&r7.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=r7.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){let t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){var t;(null===(t=r7.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(null===(e=r7.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToHRTF()}switchPanningModelToEqualPower(){var e;if(null===(e=r7.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e<this.soundCollection.length;e++)this.soundCollection[e].switchPanningModelToEqualPower()}connectToAnalyser(e){var t;this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser=e,(null===(t=r7.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.disconnect(),this._connectedAnalyser.connectAudioNodes(this._outputAudioNode,r7.D.audioEngine.masterGain))}}var ss=i(176);re.p.AddParser(ss.l.NAME_AUDIO,(e,t,i,r)=>{var s;let n;let a=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,l=e.sounds.length;o<l;o++){let l=e.sounds[o];(null===(s=r7.D.audioEngine)||void 0===s?void 0:s.canUseWebAudio)?(l.url||(l.url=l.name),a[l.url]?i.sounds.push(si.Parse(l,t,r,a[l.url])):(n=si.Parse(l,t,r),a[l.url]=n,i.sounds.push(n))):i.sounds.push(new si(l.name,null,t))}a=[]}),Object.defineProperty(rI.x.prototype,"mainSoundTrack",{get:function(){let e=this._getComponent(ss.l.NAME_AUDIO);return e||(e=new sn(this),this._addComponent(e)),this._mainSoundTrack||(this._mainSoundTrack=new sr(this,{mainTrack:!0})),this._mainSoundTrack},enumerable:!0,configurable:!0}),rI.x.prototype.getSoundByName=function(e){let t;for(t=0;t<this.mainSoundTrack.soundCollection.length;t++)if(this.mainSoundTrack.soundCollection[t].name===e)return this.mainSoundTrack.soundCollection[t];if(this.soundTracks){for(let i=0;i<this.soundTracks.length;i++)for(t=0;t<this.soundTracks[i].soundCollection.length;t++)if(this.soundTracks[i].soundCollection[t].name===e)return this.soundTracks[i].soundCollection[t]}return null},Object.defineProperty(rI.x.prototype,"audioEnabled",{get:function(){let e=this._getComponent(ss.l.NAME_AUDIO);return e||(e=new sn(this),this._addComponent(e)),e.audioEnabled},set:function(e){let t=this._getComponent(ss.l.NAME_AUDIO);t||(t=new sn(this),this._addComponent(t)),e?t.enableAudio():t.disableAudio()},enumerable:!0,configurable:!0}),Object.defineProperty(rI.x.prototype,"headphone",{get:function(){let e=this._getComponent(ss.l.NAME_AUDIO);return e||(e=new sn(this),this._addComponent(e)),e.headphone},set:function(e){let t=this._getComponent(ss.l.NAME_AUDIO);t||(t=new sn(this),this._addComponent(t)),e?t.switchAudioModeForHeadphones():t.switchAudioModeForNormalSpeakers()},enumerable:!0,configurable:!0}),Object.defineProperty(rI.x.prototype,"audioListenerPositionProvider",{get:function(){let e=this._getComponent(ss.l.NAME_AUDIO);return e||(e=new sn(this),this._addComponent(e)),e.audioListenerPositionProvider},set:function(e){let t=this._getComponent(ss.l.NAME_AUDIO);if(t||(t=new sn(this),this._addComponent(t)),e&&"function"!=typeof e)throw Error("The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3");t.audioListenerPositionProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(rI.x.prototype,"audioListenerRotationProvider",{get:function(){let e=this._getComponent(ss.l.NAME_AUDIO);return e||(e=new sn(this),this._addComponent(e)),e.audioListenerRotationProvider},set:function(e){let t=this._getComponent(ss.l.NAME_AUDIO);if(t||(t=new sn(this),this._addComponent(t)),e&&"function"!=typeof e)throw Error("The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3");t.audioListenerRotationProvider=e},enumerable:!0,configurable:!0}),Object.defineProperty(rI.x.prototype,"audioPositioningRefreshRate",{get:function(){let e=this._getComponent(ss.l.NAME_AUDIO);return e||(e=new sn(this),this._addComponent(e)),e.audioPositioningRefreshRate},set:function(e){let t=this._getComponent(ss.l.NAME_AUDIO);t||(t=new sn(this),this._addComponent(t)),t.audioPositioningRefreshRate=e},enumerable:!0,configurable:!0});class sn{get audioEnabled(){return this._audioEnabled}get headphone(){return this._headphone}constructor(e){if(this.name=ss.l.NAME_AUDIO,this._audioEnabled=!0,this._headphone=!1,this.audioPositioningRefreshRate=500,this.audioListenerPositionProvider=null,this.audioListenerRotationProvider=null,this._cachedCameraDirection=new rr.P,this._cachedCameraPosition=new rr.P,this._lastCheck=0,this._invertMatrixTemp=new rr.y3,this._cameraDirectionTemp=new rr.P,!(e=e||rp.l.LastCreatedScene))return;this.scene=e,e.soundTracks=[],e.sounds=[]}register(){this.scene._afterRenderStage.registerStep(ss.l.STEP_AFTERRENDER_AUDIO,this,this._afterRender)}rebuild(){}serialize(e){if(e.sounds=[],this.scene.soundTracks)for(let t=0;t<this.scene.soundTracks.length;t++){let i=this.scene.soundTracks[t];for(let t=0;t<i.soundCollection.length;t++)e.sounds.push(i.soundCollection[t].serialize())}}addFromContainer(e){e.sounds&&e.sounds.forEach(e=>{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(){let e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].dispose()}disableAudio(){let e;let t=this.scene;for(this._audioEnabled=!1,r7.D.audioEngine&&r7.D.audioEngine.audioContext&&r7.D.audioEngine.audioContext.suspend(),e=0;e<t.mainSoundTrack.soundCollection.length;e++)t.mainSoundTrack.soundCollection[e].pause();if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(let i=0;i<t.soundTracks[e].soundCollection.length;i++)t.soundTracks[e].soundCollection[i].pause()}enableAudio(){let e;let t=this.scene;for(this._audioEnabled=!0,r7.D.audioEngine&&r7.D.audioEngine.audioContext&&r7.D.audioEngine.audioContext.resume(),e=0;e<t.mainSoundTrack.soundCollection.length;e++)t.mainSoundTrack.soundCollection[e].isPaused&&t.mainSoundTrack.soundCollection[e].play();if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(let i=0;i<t.soundTracks[e].soundCollection.length;i++)t.soundTracks[e].soundCollection[i].isPaused&&t.soundTracks[e].soundCollection[i].play()}switchAudioModeForHeadphones(){let e=this.scene;if(this._headphone=!0,e.mainSoundTrack.switchPanningModelToHRTF(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToHRTF()}switchAudioModeForNormalSpeakers(){let e=this.scene;if(this._headphone=!1,e.mainSoundTrack.switchPanningModelToEqualPower(),e.soundTracks)for(let t=0;t<e.soundTracks.length;t++)e.soundTracks[t].switchPanningModelToEqualPower()}_afterRender(){let e=rM.F.Now;if(this._lastCheck&&e-this._lastCheck<this.audioPositioningRefreshRate)return;this._lastCheck=e;let t=this.scene;if(!this._audioEnabled||!t._mainSoundTrack||!t.soundTracks||0===t._mainSoundTrack.soundCollection.length&&1===t.soundTracks.length)return;let i=r7.D.audioEngine;if(i&&i.audioContext){let e,r=t.activeCamera;if(t.activeCameras&&t.activeCameras.length>0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){let e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){let e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),rr.P.TransformNormalToRef(sn._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e<t.mainSoundTrack.soundCollection.length;e++){let i=t.mainSoundTrack.soundCollection[e];i.useCustomAttenuation&&i.updateDistanceFromListener()}if(t.soundTracks)for(e=0;e<t.soundTracks.length;e++)for(let i=0;i<t.soundTracks[e].soundCollection.length;i++){let r=t.soundTracks[e].soundCollection[i];r.useCustomAttenuation&&r.updateDistanceFromListener()}}}}sn._CameraDirection=new rr.P(0,0,-1),si._SceneComponentInitialization=e=>{let t=e._getComponent(ss.l.NAME_AUDIO);t||(t=new sn(e),e._addComponent(t))};class sa{constructor(e){if(this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,!(e=e||rp.l.LastCreatedScene))return;this._scene=e,this.animationParameters=new rr.Lt(0,0,0,30)}_markSubMeshesAsAttributesDirty(){for(let e of this._scene.meshes)e.bakedVertexAnimationManager===this&&e._markSubMeshesAsAttributesDirty()}bind(e,t=!1){if(!this._texture||!this._isEnabled)return;let i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}clone(){let e=new sa(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,r=30){this.animationParameters=new rr.Lt(e,t,i,r)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){rg.p4.Clone(()=>e,this)}serialize(){return rg.p4.Serialize(this)}parse(e,t,i){rg.p4.Parse(()=>this,e,t,i)}}(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markSubMeshesAsAttributesDirty")],sa.prototype,"texture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markSubMeshesAsAttributesDirty")],sa.prototype,"isEnabled",void 0),(0,r0.gn)([(0,rg.qC)()],sa.prototype,"animationParameters",void 0),(0,r0.gn)([(0,rg.qC)()],sa.prototype,"time",void 0);var so=i(4871),sl=i(41);class sh{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(null==e?void 0:e._shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=rx.Zero(),this._cachedBaseSize=rx.Zero(),this._initialSamplingMode=2,this._texture=sh._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;this._texture._size&&(this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size)}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 su extends sh{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,so.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=su.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new ri.y$,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?su._IsScene(e)?this._scene=e:this._engine=e:this._scene=rp.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 rr.y3.IdentityReadOnly}getReflectionTextureMatrix(){return rr.y3.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,n){let a=this._getEngine();if(!a)return null;let o=a._getUseSRGBBuffer(!!s,t),l=a.getLoadedTexturesCache();for(let a=0;a<l.length;a++){let h=l[a];if((void 0===s||o===h._useSRGBBuffer)&&(void 0===r||r===h.invertY)&&h.url===e&&!t===h.generateMipMaps&&(!i||i===h.samplingMode)&&(void 0===n||n===h.isCube))return h.incrementReferences(),h}return null}_rebuild(){}clone(){return null}get textureType(){return this._texture&&void 0!==this._texture.type?this._texture.type:0}get textureFormat(){return this._texture&&void 0!==this._texture.format?this._texture.format:5}_markAllSubMeshesAsTexturesDirty(){let e=this.getScene();e&&e.markAllMaterialsAsDirty(1)}readPixels(e=0,t=0,i=null,r=!0,s=!1,n=0,a=0,o=Number.MAX_VALUE,l=Number.MAX_VALUE){if(!this._texture)return null;let h=this._getEngine();if(!h)return null;let u=this.getSize(),c=u.width,d=u.height;0!==t&&(c/=Math.pow(2,t),d/=Math.pow(2,t),c=Math.round(c),d=Math.round(d)),o=Math.min(c,o),l=Math.min(d,l);try{if(this._texture.isCube)return h._readTexturePixels(this._texture,o,l,e,t,i,r,s,n,a);return h._readTexturePixels(this._texture,o,l,-1,t,i,r,s,n,a)}catch(e){return null}}_readPixelsSync(e=0,t=0,i=null,r=!0,s=!1){if(!this._texture)return null;let n=this.getSize(),a=n.width,o=n.height,l=this._getEngine();if(!l)return null;0!=t&&(a/=Math.pow(2,t),o/=Math.pow(2,t),a=Math.round(a),o=Math.round(o));try{if(this._texture.isCube)return l._readTexturePixelsSync(this._texture,a,o,e,t,i,r,s);return l._readTexturePixelsSync(this._texture,a,o,-1,t,i,r,s)}catch(e){return null}}get _lodTextureHigh(){return this._texture?this._texture._lodTextureHigh:null}get _lodTextureMid(){return this._texture?this._texture._lodTextureMid:null}get _lodTextureLow(){return this._texture?this._texture._lodTextureLow:null}dispose(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);let e=this._scene.textures.indexOf(this);if(e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){let 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;let t=rg.p4.Serialize(this);return rg.p4.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0===i){t();return}for(let r=0;r<e.length;r++){let s=e[r];if(s.isReady())0==--i&&t();else{let e=s.onLoadObservable;e?e.addOnce(()=>{0==--i&&t()}):0==--i&&t()}}}static _IsScene(e){return"Scene"===e.getClassName()}}su.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,(0,r0.gn)([(0,rg.qC)()],su.prototype,"uniqueId",void 0),(0,r0.gn)([(0,rg.qC)()],su.prototype,"name",void 0),(0,r0.gn)([(0,rg.qC)()],su.prototype,"metadata",void 0),(0,r0.gn)([(0,rg.qC)("hasAlpha")],su.prototype,"_hasAlpha",void 0),(0,r0.gn)([(0,rg.qC)("getAlphaFromRGB")],su.prototype,"_getAlphaFromRGB",void 0),(0,r0.gn)([(0,rg.qC)()],su.prototype,"level",void 0),(0,r0.gn)([(0,rg.qC)("coordinatesIndex")],su.prototype,"_coordinatesIndex",void 0),(0,r0.gn)([(0,rg.qC)()],su.prototype,"optimizeUVAllocation",void 0),(0,r0.gn)([(0,rg.qC)("coordinatesMode")],su.prototype,"_coordinatesMode",void 0),(0,r0.gn)([(0,rg.qC)()],su.prototype,"wrapU",null),(0,r0.gn)([(0,rg.qC)()],su.prototype,"wrapV",null),(0,r0.gn)([(0,rg.qC)()],su.prototype,"wrapR",void 0),(0,r0.gn)([(0,rg.qC)()],su.prototype,"anisotropicFilteringLevel",void 0),(0,r0.gn)([(0,rg.qC)()],su.prototype,"isCube",null),(0,r0.gn)([(0,rg.qC)()],su.prototype,"is3D",null),(0,r0.gn)([(0,rg.qC)()],su.prototype,"is2DArray",null),(0,r0.gn)([(0,rg.qC)()],su.prototype,"gammaSpace",null),(0,r0.gn)([(0,rg.qC)()],su.prototype,"invertZ",void 0),(0,r0.gn)([(0,rg.qC)()],su.prototype,"lodLevelInAlpha",void 0),(0,r0.gn)([(0,rg.qC)()],su.prototype,"lodGenerationOffset",null),(0,r0.gn)([(0,rg.qC)()],su.prototype,"lodGenerationScale",null),(0,r0.gn)([(0,rg.qC)()],su.prototype,"linearSpecularLOD",null),(0,r0.gn)([(0,rg.oU)()],su.prototype,"irradianceTexture",null),(0,r0.gn)([(0,rg.qC)()],su.prototype,"isRenderTarget",void 0);var sc=i(265),sd=i(16),sp=i(2321),s_=i(4250);function sf(e,t,i=!1){let r=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT,i=new Uint8Array(t);for(;--t>=0;){let r=e[t];r<0?r=0:r>1&&(r=1),i[t]=255*r}e=i}let n=document.createElement("canvas");n.width=r,n.height=s;let a=n.getContext("2d");if(!a)return null;let o=a.createImageData(r,s),l=o.data;if(l.set(e),a.putImageData(o,0,0),i){let e=document.createElement("canvas");e.width=r,e.height=s;let t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}async function sm(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=await e.readPixels(t,i);return s?sf(s,e.getSize(),r.invertY):null}var sg=i(4870);class sv extends su{get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,r,s=sv.TRILINEAR_SAMPLINGMODE,n=null,a=null,o=null,l=!1,h,u,c,d,p){var _,f,m,g,v,T,x,S,E;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 ri.y$,this._isBlocking=!0,this.name=e||"",this.url=e;let b=!1,y=null;"object"==typeof i&&null!==i?(C=null!==(_=i.noMipmap)&&void 0!==_&&_,r=null!==(f=i.invertY)&&void 0!==f?f:!sg.e.UseOpenGLOrientationForUV,s=null!==(m=i.samplingMode)&&void 0!==m?m:sv.TRILINEAR_SAMPLINGMODE,n=null!==(g=i.onLoad)&&void 0!==g?g:null,a=null!==(v=i.onError)&&void 0!==v?v:null,o=null!==(T=i.buffer)&&void 0!==T?T:null,l=null!==(x=i.deleteBuffer)&&void 0!==x&&x,h=i.format,u=i.mimeType,c=i.loaderOptions,d=i.creationFlags,b=null!==(S=i.useSRGBBuffer)&&void 0!==S&&S,y=null!==(E=i.internalTexture)&&void 0!==E?E:null):C=!!i,this._noMipmap=C,this._invertY=void 0===r?!sg.e.UseOpenGLOrientationForUV:r,this._initialSamplingMode=s,this._buffer=o,this._deleteBuffer=l,this._mimeType=u,this._loaderOptions=c,this._creationFlags=d,this._useSRGBBuffer=b,this._forcedExtension=p,h&&(this._format=h);let A=this.getScene(),R=this._getEngine();if(!R)return;R.onBeforeTextureInitObservable.notifyObservers(this);let P=()=>{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),n&&n(),!this.isBlocking&&A&&A.resetCachedMaterial()},I=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),sv.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!y){this._delayedOnLoad=P,this._delayedOnError=I;return}if(this._texture=null!=y?y:this._getFromCache(this.url,C,s,this._invertY,b),this._texture){if(this._texture.isReady)sc.Q.SetImmediate(()=>P());else{let e=this._texture.onLoadedObservable.add(P);this._texture.onErrorObservable.add(t=>{var i;I(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)})}}else if(A&&A.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=P,this._delayedOnError=I;else{try{this._texture=R.createTexture(this.url,C,this._invertY,A,s,P,I,this._buffer,void 0,this._format,this._forcedExtension,u,c,d,b)}catch(e){throw I("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,r){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=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;let 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?sc.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,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,rr.P.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}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=rr.y3.Zero(),this._rowGenerationMatrix=new rr.y3,this._t0=rr.P.Zero(),this._t1=rr.P.Zero(),this._t2=rr.P.Zero()),rr.y3.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(rr.y3.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,rr.jp.Matrix[0]),rr.y3.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,rr.jp.Matrix[1]),rr.y3.ScalingToRef(this._cachedUScale,this._cachedVScale,0,rr.jp.Matrix[2]),rr.y3.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,rr.jp.Matrix[3]),rr.jp.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rr.jp.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rr.jp.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rr.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),rr.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));let t=this.getScene();return t&&this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){let e=this.getScene();if(!e||this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode&&(this.coordinatesMode!==sv.PROJECTION_MODE||this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag))return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=rr.y3.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=rr.y3.Zero());let 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 sv.PLANAR_MODE:rr.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 sv.PROJECTION_MODE:{rr.y3.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);let t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:rr.y3.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,e=>-1!==e.getActiveTextures().indexOf(this)),this._cachedReflectionTextureMatrix}clone(){let 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 rg.p4.Clone(()=>new sv(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;let i=this.name;!sv.SerializeBuffers&&this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");let r=super.serialize(sv._SerializeInternalTextureUniqueId);return r?((sv.SerializeBuffers||sv.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(r.base64String=this._buffer,r.name=r.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?r.base64String="data:image/png;base64,"+(0,s_.Gh)(this._buffer):(sv.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(r.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=e._readPixelsSync(t,i);return s?sf(s,e.getSize(),r.invertY):null}(this):sm(this))),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r._creationFlags=this._creationFlags,r._useSRGBBuffer=this._useSRGBBuffer,sv._SerializeInternalTextureUniqueId&&(r.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),this.name=i,r):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){let r;if(e.customType){let r=sd.K.Instantiate(e.customType),s=r.Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return sv._CubeTextureParser(e,t,i);let s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;if(s){let i=t.getEngine().getLoadedTexturesCache();for(let t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}let n=t=>{var i;if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){let i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i<e.animations.length;i++){let r=e.animations[i],s=(0,rn.q)("BABYLON.Animation");s&&t.animations.push(s.Parse(r))}s&&!r&&(null===(i=null==t?void 0:t._texture)||void 0===i||i._setUniqueId(e.internalTextureUniqueId))},a=rg.p4.Parse(()=>{var s,a,o;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){let i=sv._CreateMirror(e.name,e.renderTargetSize,t,l);return i._waitingRenderList=e.renderList,i.mirrorPlane=sp.J.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i<t.reflectionProbes.length;i++){let r=t.reflectionProbes[i];if(r.name===e.name)return r.cubeTexture}}else(i=sv._CreateRenderTargetTexture(e.name,e.renderTargetSize,t,l,null!==(s=e._creationFlags)&&void 0!==s?s:0))._waitingRenderList=e.renderList;return n(i),i}{let s;if(e.base64String&&!r)(s=sv.CreateFromBase64String(e.base64String,e.base64String,t,!l,e.invertY,e.samplingMode,()=>{n(s)},null!==(a=e._creationFlags)&&void 0!==a?a:0,null!==(o=e._useSRGBBuffer)&&void 0!==o&&o)).name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||sv.UseSerializedUrlIfAny)&&(a=e.url);let o={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(s)},internalTexture:r};s=new sv(a,t,o)}return s}},e,t);return a}static CreateFromBase64String(e,t,i,r,s,n=sv.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=5,h){return new sv("data:"+t,i,r,s,n,a,o,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,r=!1,s,n=!0,a=sv.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new sv(e,i,s,n,a,o,l,t,r,h,void 0,void 0,u)}}sv.SerializeBuffers=!0,sv.ForceSerializeBuffers=!1,sv.OnTextureLoadErrorObservable=new ri.y$,sv._SerializeInternalTextureUniqueId=!1,sv._CubeTextureParser=(e,t,i)=>{throw(0,st.S)("CubeTexture")},sv._CreateMirror=(e,t,i,r)=>{throw(0,st.S)("MirrorTexture")},sv._CreateRenderTargetTexture=(e,t,i,r,s)=>{throw(0,st.S)("RenderTargetTexture")},sv.NEAREST_SAMPLINGMODE=1,sv.NEAREST_NEAREST_MIPLINEAR=8,sv.BILINEAR_SAMPLINGMODE=2,sv.LINEAR_LINEAR_MIPNEAREST=11,sv.TRILINEAR_SAMPLINGMODE=3,sv.LINEAR_LINEAR_MIPLINEAR=3,sv.NEAREST_NEAREST_MIPNEAREST=4,sv.NEAREST_LINEAR_MIPNEAREST=5,sv.NEAREST_LINEAR_MIPLINEAR=6,sv.NEAREST_LINEAR=7,sv.NEAREST_NEAREST=1,sv.LINEAR_NEAREST_MIPNEAREST=9,sv.LINEAR_NEAREST_MIPLINEAR=10,sv.LINEAR_LINEAR=2,sv.LINEAR_NEAREST=12,sv.EXPLICIT_MODE=0,sv.SPHERICAL_MODE=1,sv.PLANAR_MODE=2,sv.CUBIC_MODE=3,sv.PROJECTION_MODE=4,sv.SKYBOX_MODE=5,sv.INVCUBIC_MODE=6,sv.EQUIRECTANGULAR_MODE=7,sv.FIXED_EQUIRECTANGULAR_MODE=8,sv.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,sv.CLAMP_ADDRESSMODE=0,sv.WRAP_ADDRESSMODE=1,sv.MIRROR_ADDRESSMODE=2,sv.UseSerializedUrlIfAny=!1,(0,r0.gn)([(0,rg.qC)()],sv.prototype,"url",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"uOffset",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"vOffset",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"uScale",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"vScale",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"uAng",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"vAng",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"wAng",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"uRotationCenter",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"vRotationCenter",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"wRotationCenter",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"homogeneousRotationInUVTransform",void 0),(0,r0.gn)([(0,rg.qC)()],sv.prototype,"isBlocking",null),(0,rn.H)("BABYLON.Texture",sv),rg.p4._TextureParser=sv.Parse;var sT=i(6452),sx=i(4826);function sS(e,t,i,r){let s;let n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r<t;r++)for(let a=0;a<i;a++){let i=(a*t+r)*3,o=(a*t+r)*4;s[o+0]=e[i+0],s[o+1]=e[i+1],s[o+2]=e[i+2],s[o+3]=n}return s}function sE(e){return function(t,i,r,s,n,a,o,l,h=null,u=0){let c=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,d=e?sT.S.Raw3D:sT.S.Raw2DArray,p=new sT.l(this,d);p.baseWidth=i,p.baseHeight=r,p.baseDepth=s,p.width=i,p.height=r,p.depth=s,p.format=n,p.type=u,p.generateMipMaps=a,p.samplingMode=l,e?p.is3D=!0:p.is2DArray=!0,this._doNotHandleContextLost||(p._bufferView=t),e?this.updateRawTexture3D(p,t,n,o,h,u):this.updateRawTexture2DArray(p,t,n,o,h,u),this._bindTextureDirectly(c,p,!0);let _=this._getSamplingParameters(l,a);return this._gl.texParameteri(c,this._gl.TEXTURE_MAG_FILTER,_.mag),this._gl.texParameteri(c,this._gl.TEXTURE_MIN_FILTER,_.min),a&&this._gl.generateMipmap(c),this._bindTextureDirectly(c,null),this._internalTexturesCache.push(p),p}}function sC(e){return function(t,i,r,s,n=null,a=0){let o=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,l=this._getWebGLTextureType(a),h=this._getInternalFormat(r),u=this._getRGBABufferInternalSizedFormat(a,r);this._bindTextureDirectly(o,t,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(t._bufferView=i,t.format=r,t.invertY=s,t._compression=n),t.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),n&&i?this._gl.compressedTexImage3D(o,0,this.getCaps().s3tc[n],t.width,t.height,t.depth,0,i):this._gl.texImage3D(o,0,u,t.width,t.height,t.depth,0,h,l,i),t.generateMipMaps&&this._gl.generateMipmap(o),this._bindTextureDirectly(o,null),t.isReady=!0}}sx.B.prototype.updateRawTexture=function(e,t,i,r,s=null,n=0,a=!1){if(!e)return;let o=this._getRGBABufferInternalSizedFormat(n,i,a),l=this._getInternalFormat(i),h=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=n,e.invertY=r,e._compression=s),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},sx.B.prototype.createRawTexture=function(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){let c=new sT.l(this,sT.S.Raw);c.baseWidth=t,c.baseHeight=i,c.width=t,c.height=i,c.format=r,c.generateMipMaps=s,c.samplingMode=a,c.invertY=n,c._compression=o,c.type=l,c._useSRGBBuffer=this._getUseSRGBBuffer(u,!s),this._doNotHandleContextLost||(c._bufferView=e),this.updateRawTexture(c,e,r,n,o,l,c._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,c,!0);let d=this._getSamplingParameters(a,s);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(c),c},sx.B.prototype.createRawCubeTexture=function(e,t,i,r,s,n,a,o=null){let l=this._gl,h=new sT.l(this,sT.S.CubeRaw);h.isCube=!0,h.format=i,h.type=r,this._doNotHandleContextLost||(h._bufferViewArray=e);let u=this._getWebGLTextureType(r),c=this._getInternalFormat(i);c===l.RGB&&(c=l.RGBA),u!==l.FLOAT||this._caps.textureFloatLinearFiltering?u!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?u!==l.FLOAT||this._caps.textureFloatRender?u!==l.HALF_FLOAT||this._caps.colorBufferFloat||(s=!1,ru.Y.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(s=!1,ru.Y.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(s=!1,a=1,ru.Y.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(s=!1,a=1,ru.Y.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")),h.width=t,h.height=t,h.invertY=n,h._compression=o;let d=!this.needPOTTextures||rZ.w1.IsExponentOfTwo(h.width)&&rZ.w1.IsExponentOfTwo(h.height);if(d||(s=!1),e)this.updateRawCubeTexture(h,e,i,r,n,o);else{let e=this._getRGBABufferInternalSizedFormat(r);this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let t=0;t<6;t++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this.getCaps().s3tc[o],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,e,h.width,h.height,0,c,u,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);let p=this._getSamplingParameters(a,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,p.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,p.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=s,h.samplingMode=a,h.isReady=!0,h},sx.B.prototype.updateRawCubeTexture=function(e,t,i,r,s,n=null,a=0){e._bufferViewArray=t,e.format=i,e.type=r,e.invertY=s,e._compression=n;let o=this._gl,l=this._getWebGLTextureType(r),h=this._getInternalFormat(i),u=this._getRGBABufferInternalSizedFormat(r),c=!1;h===o.RGB&&(h=o.RGBA,c=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===s||!!s),e.width%4!=0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let s=t[i];n?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,this.getCaps().s3tc[n],e.width,e.height,0,s):(c&&(s=sS(s,e.width,e.height,r)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,u,e.width,e.height,0,h,l,s))}let d=!this.needPOTTextures||rZ.w1.IsExponentOfTwo(e.width)&&rZ.w1.IsExponentOfTwo(e.height);d&&e.generateMipMaps&&0===a&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},sx.B.prototype.createRawCubeTextureFromUrl=function(e,t,i,r,s,n,a,o,l=null,h=null,u=3,c=!1){let d=this._gl,p=this.createRawCubeTexture(null,i,r,s,!n,c,u,null);null==t||t.addPendingData(p),p.url=e,p.isReady=!1,this._internalTexturesCache.push(p);let _=e=>{let i=p.width,n=a(e);if(n){if(o){let e=this._getWebGLTextureType(s),t=this._getInternalFormat(r),a=this._getRGBABufferInternalSizedFormat(s),l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);let h=o(n);for(let r=0;r<h.length;r++){let n=i>>r;for(let i=0;i<6;i++){let o=h[r][i];l&&(o=sS(o,n,n,s)),d.texImage2D(i,r,a,n,n,0,t,e,o)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(p,n,r,s,c);p.isReady=!0,null==t||t.removePendingData(p),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,e=>{_(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},sx.B.prototype.createRawTexture2DArray=sE(!1),sx.B.prototype.createRawTexture3D=sE(!0),sx.B.prototype.updateRawTexture2DArray=sC(!1),sx.B.prototype.updateRawTexture3D=sC(!0);class sb extends sv{constructor(e,t,i,r,s,n=!0,a=!1,o=3,l=0,h,u){if(super(null,s,!n,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=r,!this._engine)return;this._engine._caps.textureFloatLinearFiltering||1!==l||(o=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(o=1),this._texture=this._engine.createRawTexture(e,t,i,r,n,a,o,null,l,null!=h?h:0,null!=u&&u),this.wrapU=sv.CLAMP_ADDRESSMODE,this.wrapV=sv.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,r,s=!0,n=!1,a=3){return new sb(e,t,i,1,r,s,n,a)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,n=!1,a=3){return new sb(e,t,i,2,r,s,n,a)}static CreateAlphaTexture(e,t,i,r,s=!0,n=!1,a=3){return new sb(e,t,i,0,r,s,n,a)}static CreateRGBTexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=0,h=!1){return new sb(e,t,i,4,r,s,n,a,o,l,h)}static CreateRGBATexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=0,h=!1){return new sb(e,t,i,5,r,s,n,a,o,l,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=!1){return new sb(e,t,i,5,r,s,n,a,o,1,l)}static CreateRTexture(e,t,i,r,s=!0,n=!1,a=sv.TRILINEAR_SAMPLINGMODE,o=1){return new sb(e,t,i,6,r,s,n,a,o)}static CreateRStorageTexture(e,t,i,r,s=!0,n=!1,a=sv.TRILINEAR_SAMPLINGMODE,o=1){return new sb(e,t,i,6,r,s,n,a,o,1)}}var sy=i(7792);class sA{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;let t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===sy.kD.POINTERDOWN){this._isPointerDown=!0;return}e.type===sy.kD.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;let e=rM.F.Now,t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();let i=e-this._lastInteractionTime-this._idleRotationWaitTime,r=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*r,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))})}detach(){if(!this._attachedCamera)return;let 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:rM.F.Now}_reachTargetAlpha(){return!!this._attachedCamera&&!!this.targetAlpha&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)<rL.kn}_userIsZooming(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset}_shouldAnimationStopForInteraction(){if(!this._attachedCamera)return!1;let e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()}_applyUserInteraction(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=rM.F.Now)}_userIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}class sR{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=[]}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;let t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(e=>{if(!e)return;e.computeWorldMatrix(!0);let 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||(sR.EasingFunction.setEasingMode(sR.EasingMode),this._radiusBounceTransition=rE.CreateAnimation("radius",rE.ANIMATIONTYPE_FLOAT,60,sR.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;let t=rE.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()}}sR.EasingFunction=new class extends rG{constructor(e=1){super(),this.amplitude=e}easeInCore(e){let t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}(.3),sR.EasingMode=rG.EASINGMODE_EASEOUT;class sP{constructor(){this.onTargetFramingAnimationEndObservable=new ri.y$,this._mode=sP.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=[],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;let t=this._attachedCamera.getScene();sP.EasingFunction.setEasingMode(sP.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===sy.kD.POINTERDOWN){this._isPointerDown=!0;return}e.type===sy.kD.POINTERUP&&(this._isPointerDown=!1)}),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;let 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);let r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){let r=new rr.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new rr.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t<e.length;t++){let i=e[t].getHierarchyBoundingVectors(!0);rr.P.CheckExtends(i.min,r,s),rr.P.CheckExtends(i.max,r,s)}this.zoomOnBoundingInfo(r,s,t,i)}zoomOnBoundingInfo(e,t,i=!1,r=null){let s;if(!this._attachedCamera)return!1;let n=e.y,a=t.y,o=n+(a-n)*this._positionScale,l=t.subtract(e).scale(.5);if(i)s=new rr.P(0,o,0);else{let t=e.add(l);s=new rr.P(t.x,o,t.z)}this._vectorTransition||(this._vectorTransition=rE.CreateAnimation("target",rE.ANIMATIONTYPE_VECTOR3,60,sP.EasingFunction)),this._betaIsAnimating=!0;let h=rE.TransitionTo("target",s,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);h&&this._animatables.push(h);let u=0;if(this._mode===sP.FitFrustumSidesMode){let i=this._calculateLowerRadiusFromModelBoundingSphere(e,t);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=l.length()+this._attachedCamera.minZ),u=i}else this._mode===sP.IgnoreBoundsSizeMode&&(u=this._calculateLowerRadiusFromModelBoundingSphere(e,t),this.autoCorrectCameraLimitsAndSensibility&&null===this._attachedCamera.lowerRadiusLimit&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){let i=t.subtract(e).length();this._attachedCamera.panningSensibility=5e3/i,this._attachedCamera.wheelPrecision=100/u}return this._radiusTransition||(this._radiusTransition=rE.CreateAnimation("radius",rE.ANIMATIONTYPE_FLOAT,60,sP.EasingFunction)),(h=rE.TransitionTo("radius",u,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,()=>{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}))&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){let i=t.subtract(e),r=i.length(),s=this._getFrustumSlope(),n=.5*r*this._radiusScale,a=n*Math.sqrt(1+1/(s.x*s.x)),o=n*Math.sqrt(1+1/(s.y*s.y)),l=Math.max(a,o),h=this._attachedCamera;return h?(h.lowerRadiusLimit&&this._mode===sP.IgnoreBoundsSizeMode&&(l=l<h.lowerRadiusLimit?h.lowerRadiusLimit:l),h.upperRadiusLimit&&(l=l>h.upperRadiusLimit?h.upperRadiusLimit:l),l):0}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;let e=rM.F.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>.5*Math.PI&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=rE.CreateAnimation("beta",rE.ANIMATIONTYPE_FLOAT,60,sP.EasingFunction));let e=rE.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});e&&this._animatables.push(e)}}_getFrustumSlope(){let e=this._attachedCamera;if(!e)return rr.FM.Zero();let t=e.getScene().getEngine(),i=t.getAspectRatio(e),r=Math.tan(e.fov/2),s=r*i;return new rr.FM(s,r)}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=rM.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)}}sP.EasingFunction=new class extends rG{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)}},sP.EasingMode=rG.EASINGMODE_EASEINOUT,sP.IgnoreBoundsSizeMode=0,sP.FitFrustumSidesMode=1;var sI=i(9657),sM=i(7796);class sD{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new sD(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){let r,s,n,a;let o=sD._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),l=sD._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i),h=0,u=Number.MAX_VALUE;if(1e-7>Math.abs(this.direction.x)){if(this.origin.x<o.x||this.origin.x>l.x)return!1}else if(r=1/this.direction.x,s=(o.x-this.origin.x)*r,(n=(l.x-this.origin.x)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;if(1e-7>Math.abs(this.direction.y)){if(this.origin.y<o.y||this.origin.y>l.y)return!1}else if(r=1/this.direction.y,s=(o.y-this.origin.y)*r,(n=(l.y-this.origin.y)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;if(1e-7>Math.abs(this.direction.z)){if(this.origin.z<o.z||this.origin.z>l.z)return!1}else if(r=1/this.direction.z,s=(o.z-this.origin.z)*r,(n=(l.z-this.origin.z)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){let i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,n=i*i+r*r+s*s,a=e.radius+t,o=a*a;if(n<=o)return!0;let l=i*this.direction.x+r*this.direction.y+s*this.direction.z;return!(l<0)&&n-l*l<=o}intersectsTriangle(e,t,i){let r=sD._TmpVector3[0],s=sD._TmpVector3[1],n=sD._TmpVector3[2],a=sD._TmpVector3[3],o=sD._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),rr.P.CrossToRef(this.direction,s,n);let l=rr.P.Dot(r,n);if(0===l)return null;let h=1/l;this.origin.subtractToRef(e,a);let u=rr.P.Dot(a,n)*h;if(u<0||u>1)return null;rr.P.CrossToRef(a,r,o);let c=rr.P.Dot(this.direction,o)*h;if(c<0||u+c>1)return null;let d=rr.P.Dot(s,o)*h;return d>this.length?null:new sM.c(1-u-c,u,d)}intersectsPlane(e){let t;let i=rr.P.Dot(e.normal,this.direction);if(999999997475243e-21>Math.abs(i))return null;{let r=rr.P.Dot(e.normal,this.origin);return(t=(-e.d-r)/i)<0?t<-.000000999999997475243?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{let e=(this.origin.y-t)/this.direction.y;if(e>0)return null;return new rr.P(this.origin.x+-(this.direction.x*e),t,this.origin.z+-(this.direction.z*e))}case"x":{let e=(this.origin.x-t)/this.direction.x;if(e>0)return null;return new rr.P(t,this.origin.y+-(this.direction.y*e),this.origin.z+-(this.direction.z*e))}case"z":{let e=(this.origin.z-t)/this.direction.z;if(e>0)return null;return new rr.P(this.origin.x+-(this.direction.x*e),this.origin.y+-(this.direction.y*e),t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,n=!1){let a=rr.jp.Matrix[0];return e.getWorldMatrix().invertToRef(a),this._tmpRay?sD.TransformToRef(this,a,this._tmpRay):this._tmpRay=sD.Transform(this,a),e.intersects(this._tmpRay,t,i,r,s,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;r<e.length;r++){let s=this.intersectsMesh(e[r],t);s.hit&&i.push(s)}return i.sort(this._comparePickingInfo),i}_comparePickingInfo(e,t){return e.distance<t.distance?-1:e.distance>t.distance?1:0}intersectionSegment(e,t,i){let r=this.origin,s=rr.jp.Vector3[0],n=rr.jp.Vector3[1],a=rr.jp.Vector3[2],o=rr.jp.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(sD._Rayl,a),r.addToRef(a,n),e.subtractToRef(r,o);let l=rr.P.Dot(s,s),h=rr.P.Dot(s,a),u=rr.P.Dot(a,a),c=rr.P.Dot(s,o),d=rr.P.Dot(a,o),p=l*u-h*h,_,f=p,m,g=p;p<sD._Smallnum?(_=0,f=1,m=d,g=u):(_=h*d-u*c,m=l*d-h*c,_<0?(_=0,m=d,g=u):_>f&&(_=f,m=d+h,g=u)),m<0?(m=0,0>-c?_=0:-c>l?_=f:(_=-c,f=l)):m>g&&(m=g,-c+h<0?_=0:-c+h>l?_=f:(_=-c+h,f=l));let v=Math.abs(_)<sD._Smallnum?0:_/f,T=Math.abs(m)<sD._Smallnum?0:m/g,x=rr.jp.Vector3[4];a.scaleToRef(T,x);let S=rr.jp.Vector3[5];s.scaleToRef(v,S),S.addInPlace(o);let E=rr.jp.Vector3[6];S.subtractToRef(x,E);let C=T>0&&T<=this.length&&E.lengthSquared()<i*i;return C?S.length():-1}update(e,t,i,r,s,n,a,o=!1){if(o){sD._RayDistant||(sD._RayDistant=sD.Zero()),sD._RayDistant.unprojectRayToRef(e,t,i,r,rr.y3.IdentityReadOnly,n,a);let o=rr.jp.Matrix[0];s.invertToRef(o),sD.TransformToRef(sD._RayDistant,o,this)}else this.unprojectRayToRef(e,t,i,r,s,n,a);return this}static Zero(){return new sD(rr.P.Zero(),rr.P.Zero())}static CreateNew(e,t,i,r,s,n,a){let o=sD.Zero();return o.update(e,t,i,r,s,n,a)}static CreateNewFromTo(e,t,i=rr.y3.IdentityReadOnly){let r=t.subtract(e),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),sD.Transform(new sD(e,r,s),i)}static Transform(e,t){let i=new sD(new rr.P(0,0,0),new rr.P(0,0,0));return sD.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){rr.P.TransformCoordinatesToRef(e.origin,t,i.origin),rr.P.TransformNormalToRef(e.direction,t,i.direction),i.length=e.length;let r=i.direction,s=r.length();if(!(0===s||1===s)){let e=1/s;r.x*=e,r.y*=e,r.z*=e,i.length*=s}}unprojectRayToRef(e,t,i,r,s,n,a){let o=rr.jp.Matrix[0];s.multiplyToRef(n,o),o.multiplyToRef(a,o),o.invert();let l=rp.l.LastCreatedEngine,h=rr.jp.Vector3[0];h.x=e/i*2-1,h.y=-(t/r*2-1),h.z=(null==l?void 0:l.useReverseDepthBuffer)?1:(null==l?void 0:l.isNDCHalfZRange)?0:-1;let u=rr.jp.Vector3[1].copyFromFloats(h.x,h.y,1-1e-8),c=rr.jp.Vector3[2],d=rr.jp.Vector3[3];rr.P._UnprojectFromInvertedMatrixToRef(h,o,c),rr.P._UnprojectFromInvertedMatrixToRef(u,o,d),this.origin.copyFrom(c),d.subtractToRef(c,this.direction),this.direction.normalize()}}sD._TmpVector3=rD.B.BuildArray(6,rr.P.Zero),sD._RayDistant=sD.Zero(),sD._Smallnum=1e-8,sD._Rayl=1e9,rI.x.prototype.createPickingRay=function(e,t,i,r,s=!1){let n=sD.Zero();return this.createPickingRayToRef(e,t,i,n,r,s),n},rI.x.prototype.createPickingRayToRef=function(e,t,i,r,s,n=!1,a=!1){let o=this.getEngine();if(!s){if(!this.activeCamera)return this;s=this.activeCamera}let l=s.viewport,h=l.toGlobal(o.getRenderWidth(),o.getRenderHeight());return e=e/o.getHardwareScalingLevel()-h.x,t=t/o.getHardwareScalingLevel()-(o.getRenderHeight()-h.y-h.height),r.update(e,t,h.width,h.height,i||rr.y3.IdentityReadOnly,n?rr.y3.IdentityReadOnly:s.getViewMatrix(),s.getProjectionMatrix(),a),this},rI.x.prototype.createPickingRayInCameraSpace=function(e,t,i){let r=sD.Zero();return this.createPickingRayInCameraSpaceToRef(e,t,r,i),r},rI.x.prototype.createPickingRayInCameraSpaceToRef=function(e,t,i,r){if(!sI.p)return this;let s=this.getEngine();if(!r){if(!this.activeCamera)throw Error("Active camera not set");r=this.activeCamera}let n=r.viewport,a=n.toGlobal(s.getRenderWidth(),s.getRenderHeight()),o=rr.y3.Identity();return e=e/s.getHardwareScalingLevel()-a.x,t=t/s.getHardwareScalingLevel()-(s.getRenderHeight()-a.y-a.height),i.update(e,t,a.width,a.height,o,o,r.getProjectionMatrix()),this},rI.x.prototype._internalPickForMesh=function(e,t,i,r,s,n,a,o){let l=t(r,i.enableDistantPicking),h=i.intersects(l,s,a,n,r,o);return h&&h.hit&&(s||null==e||!(h.distance>=e.distance))?h:null},rI.x.prototype._internalPick=function(e,t,i,r,s){let n=null,a=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l<this.meshes.length;l++){let h=this.meshes[l];if(t){if(!t(h))continue}else if(!h.isEnabled()||!h.isVisible||!h.isPickable)continue;let u=a&&h.isWorldMatrixCameraDependent(),c=h.computeWorldMatrix(u,o);if(h.hasThinInstances&&h.thinInstanceEnablePicking){let t=this._internalPickForMesh(n,e,h,c,!0,!0,s);if(t){if(r)return t;let a=rr.jp.Matrix[1],o=h.thinInstanceGetWorldMatrices();for(let t=0;t<o.length;t++){let l=o[t];l.multiplyToRef(c,a);let u=this._internalPickForMesh(n,e,h,a,i,r,s,!0);if(u&&((n=u).thinInstanceIndex=t,i))return n}}}else{let t=this._internalPickForMesh(n,e,h,c,i,r,s);if(t&&(n=t,i))return n}}return n||new sI.p},rI.x.prototype._internalMultiPick=function(e,t,i){if(!sI.p)return null;let r=[],s=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let a=0;a<this.meshes.length;a++){let o=this.meshes[a];if(t){if(!t(o))continue}else if(!o.isEnabled()||!o.isVisible||!o.isPickable)continue;let l=s&&o.isWorldMatrixCameraDependent(),h=o.computeWorldMatrix(l,n);if(o.hasThinInstances&&o.thinInstanceEnablePicking){let t=this._internalPickForMesh(null,e,o,h,!0,!0,i);if(t){let t=rr.jp.Matrix[1],s=o.thinInstanceGetWorldMatrices();for(let n=0;n<s.length;n++){let a=s[n];a.multiplyToRef(h,t);let l=this._internalPickForMesh(null,e,o,t,!1,!1,i,!0);l&&(l.thinInstanceIndex=n,r.push(l))}}}else{let t=this._internalPickForMesh(null,e,o,h,!1,!1,i);t&&r.push(t)}}return r},rI.x.prototype.pickWithBoundingInfo=function(e,t,i,r,s){if(!sI.p)return null;let n=this._internalPick(i=>(this._tempPickingRay||(this._tempPickingRay=sD.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null),this._tempPickingRay),i,r,!0);return n&&(n.ray=this.createPickingRay(e,t,rr.y3.Identity(),s||null)),n},Object.defineProperty(rI.x.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),rI.x.prototype.pick=function(e,t,i,r,s,n,a=!1){let o=this._internalPick((i,r)=>(this._tempPickingRay||(this._tempPickingRay=sD.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null,!1,r),this._tempPickingRay),i,r,!1,n);return o&&(o.ray=this.createPickingRay(e,t,rr.y3.Identity(),s||null)),o},rI.x.prototype.pickWithRay=function(e,t,i,r){let s=this._internalPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=rr.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=sD.Zero()),sD.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i,!1,r);return s&&(s.ray=e),s},rI.x.prototype.multiPick=function(e,t,i,r,s){return this._internalMultiPick(i=>this.createPickingRay(e,t,i,r||null),i,s)},rI.x.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=rr.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=sD.Zero()),sD.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i)},r4.V.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new sD(rr.P.Zero(),rr.P.Zero(),e),e,t,i)},r4.V.prototype.getForwardRayToRef=function(e,t=100,i,r){return i||(i=this.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(this.position),rr.jp.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),rr.P.TransformNormalToRef(rr.jp.Vector3[2],i,rr.jp.Vector3[3]),rr.P.NormalizeToRef(rr.jp.Vector3[3],e.direction),e};class sO{static _RemoveAndStorePivotPoint(e){e&&0===sO._PivotCached&&(e.getPivotPointToRef(sO._OldPivotPoint),sO._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,sO._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(rr.y3.IdentityReadOnly),sO._OldPivotPoint.subtractToRef(e.getPivotPoint(),sO._PivotTranslation),sO._PivotTmpVector.copyFromFloats(1,1,1),sO._PivotTmpVector.subtractInPlace(e.scaling),sO._PivotTmpVector.multiplyInPlace(sO._PivotTranslation),e.position.addInPlace(sO._PivotTmpVector))),sO._PivotCached++}static _RestorePivotPoint(e){e&&!sO._OldPivotPoint.equalsToFloats(0,0,0)&&1===sO._PivotCached&&(e.setPivotPoint(sO._OldPivotPoint),e._postMultiplyPivotMatrix=sO._PivotPostMultiplyPivotMatrix,sO._PivotTmpVector.copyFromFloats(1,1,1),sO._PivotTmpVector.subtractInPlace(e.scaling),sO._PivotTmpVector.multiplyInPlace(sO._PivotTranslation),e.position.subtractInPlace(sO._PivotTmpVector)),this._PivotCached--}}sO._PivotCached=0,sO._OldPivotPoint=new rr.P,sO._PivotTranslation=new rr.P,sO._PivotTmpVector=new rr.P,sO._PivotPostMultiplyPivotMatrix=!1;var sN=i(3795);function sF(e){let t=[],i=[],r=[],s=[],n=e.width||e.size||1,a=e.height||e.size||1,o=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE,l=n/2,h=a/2;i.push(-l,-h,0),r.push(0,0,-1),s.push(0,sg.e.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),r.push(0,0,-1),s.push(1,sg.e.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),r.push(0,0,-1),s.push(1,sg.e.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),r.push(0,0,-1),s.push(0,sg.e.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),sN.x._ComputeSides(o,i,t,r,s,e.frontUVs,e.backUVs);let u=new sN.x;return u.indices=t,u.positions=i,u.normals=r,u.uvs=s,u}function sL(e,t={},i=null){let r=new rq.Kj(e,i);t.sideOrientation=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=sF(t);return s.applyToMesh(r,t.updatable),t.sourcePlane&&(r.translate(t.sourcePlane.normal,-t.sourcePlane.d),r.setDirection(t.sourcePlane.normal.scale(-1))),r}sN.x.CreatePlane=sF,rq.Kj.CreatePlane=(e,t,i,r,s)=>sL(e,{size:t,width:t,height:t,sideOrientation:s,updatable:r},i);class sw{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 ri.y$,this.onDragStartObservable=new ri.y$,this.onDragEndObservable=new ri.y$,this.onEnabledObservable=new ri.y$,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new rr.P(0,0,0),this._alternatePickedPoint=new rr.P(0,0,0),this._worldDragAxis=new rr.P(0,0,0),this._targetPosition=new rr.P(0,0,0),this._attachedToElement=!1,this._startDragRay=new sD(new rr.P,new rr.P),this._lastPointerRay={},this._dragDelta=new rr.P,this._pointA=new rr.P(0,0,0),this._pointC=new rr.P(0,0,0),this._localAxis=new rr.P(0,0,0),this._lookAt=new rr.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,sw._PlaneScene||(this._debugMode?sw._PlaneScene=this._scene:(sw._PlaneScene=new rI.x(this._scene.getEngine(),{virtual:!0}),sw._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{sw._PlaneScene.dispose(),sw._PlaneScene=null}))),this._dragPlane=sL("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:rq.Kj.DOUBLESIDE},sw._PlaneScene),this.lastDragPosition=new rr.P(0,0,0);let i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(e=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(e.type==sy.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==sy.kD.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==e.event.pointerId&&(this._activeDragButton===e.event.button||-1===this._activeDragButton)&&this.releaseDrag();else if(e.type==sy.kD.POINTERMOVE){let t=e.event.pointerId;if(this.currentDraggingPointerId===sw._AnyMouseId&&t!==sw._AnyMouseId){let i=e.event,r="mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent;r&&(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 sD(new rr.P,new rr.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))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let e=!1;sO._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),sO._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()){let 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=sw._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===sw._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;sO._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);let r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),sO._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;let t=this._pickWithRayOnDragPlane(e);if(t){sO._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?rr.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=rr.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),sO._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(rr.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)return null;{this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*rr.P.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);let t=rr.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}}let i=sw._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?rr.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(rr.P.Dot(this._localAxis,this._pointC))>.999?Math.abs(rr.P.Dot(rr.P.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(rr.P.Right()):this._lookAt.copyFrom(rr.P.UpReadOnly):(rr.P.CrossToRef(this._localAxis,this._pointC,this._lookAt),rr.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?rr.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()}}sw._AnyMouseId=-2;class sB{}sB.ANCHOR_SYSTEM="xr-anchor-system",sB.BACKGROUND_REMOVER="xr-background-remover",sB.HIT_TEST="xr-hit-test",sB.MESH_DETECTION="xr-mesh-detection",sB.PHYSICS_CONTROLLERS="xr-physics-controller",sB.PLANE_DETECTION="xr-plane-detection",sB.POINTER_SELECTION="xr-controller-pointer-selection",sB.TELEPORTATION="xr-controller-teleportation",sB.FEATURE_POINTS="xr-feature-points",sB.HAND_TRACKING="xr-hand-tracking",sB.IMAGE_TRACKING="xr-image-tracking",sB.NEAR_INTERACTION="xr-near-interaction",sB.DOM_OVERLAY="xr-dom-overlay",sB.MOVEMENT="xr-controller-movement",sB.LIGHT_ESTIMATION="xr-light-estimation",sB.EYE_TRACKING="xr-eye-tracking",sB.WALKING_LOCOMOTION="xr-walking-locomotion",sB.LAYERS="xr-layers",sB.DEPTH_SENSING="xr-depth-sensing",sB.SPACE_WARP="xr-space-warp";class sU{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)})}),this._xrSessionManager.onXRSessionEnded.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)})})}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){let s=this._AvailableFeatures[e][t];if(!s)throw Error("feature not found");return s(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){let t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){let t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){let t="string"==typeof e?e:e.Name,i=this._features[t];return!!i&&!!i.enabled&&(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0)}dispose(){this.getEnabledFeatures().forEach(e=>{this.disableFeature(e)})}enableFeature(e,t="latest",i={},r=!0,s=!0){let n="string"==typeof e?e:e.Name,a=0;if("string"==typeof t){if(!t)throw Error(`Error in provided version - ${n} (${t})`);if(-1===(a="stable"===t?sU.GetStableVersionOfFeature(n):"latest"===t?sU.GetLatestVersionOfFeature(n):+t)||isNaN(a))throw Error(`feature not found - ${n} (${t})`)}else a=t;let o=sU._ConflictingFeatures[n];if(void 0!==o&&-1!==this.getEnabledFeatures().indexOf(o))throw Error(`Feature ${n} cannot be enabled while ${o} is enabled.`);let l=this._features[n],h=sU.ConstructFeature(n,a,this._xrSessionManager,i);if(!h)throw Error(`feature not found - ${n}`);l&&this.disableFeature(n);let u=h();if(u.dependsOn){let e=u.dependsOn.every(e=>!!this._features[e]);if(!e)throw Error(`Dependant features missing. Make sure the following features are enabled - ${u.dependsOn.join(", ")}`)}if(u.isCompatible())return this._features[n]={featureImplementation:u,enabled:!0,version:a,required:s},r?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(!s)return rZ.w1.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),u;throw Error("required feature not compatible")}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){let t=this.getEnabledFeatures();for(let i of t){let t=this._features[i],r=t.featureImplementation.xrNativeFeatureName;if(r&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(r)&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(r)&&e.optionalFeatures.push(r))),t.featureImplementation.getXRSessionInitExtension){let i=await t.featureImplementation.getXRSessionInitExtension();e=Object.assign(Object.assign({},e),i)}}return e}}sU._AvailableFeatures={},sU._ConflictingFeatures={[sB.TELEPORTATION]:sB.MOVEMENT,[sB.MOVEMENT]:sB.TELEPORTATION};class sV{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 sk{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)}}sk.DistanceJoint=0,sk.HingeJoint=1,sk.BallAndSocketJoint=2,sk.WheelJoint=3,sk.SliderJoint=4,sk.PrismaticJoint=5,sk.UniversalJoint=6,sk.Hinge2Joint=sk.WheelJoint,sk.PointToPointJoint=8,sk.SpringJoint=9,sk.LockJoint=10,rq.Kj._PhysicsImpostorParser=function(e,t,i){return new sG(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class sG{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;let e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){if(this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=[],this._onAfterPhysicsStepCallbacks=[],this._onPhysicsCollideCallbacks=[],this._deltaPosition=rr.P.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new rr._f,this._tmpQuat2=new rr._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 rr._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,sG._TmpVecs[0]),this.object.translate(sG._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||!this._physicsEngine)return;let 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){ru.Y.Error("No object was provided. A physics object is obligatory");return}if(this.object.parent&&0!==i.mass&&ru.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)return;this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=rr._f.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new rr._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&&ru.Y.Warn("You must affect impostors to children before affecting impostor to parent.")):ru.Y.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){if(this.object.parent instanceof r$.x){let e=this.object.parent;return e.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)return sG.DEFAULT_OBJECT_SIZE;{let e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=sG.IDENTITY_QUATERNION;let i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);let r=this.object.getBoundingInfo(),s=r.boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}}getObjectCenter(){if(!this.object.getBoundingInfo)return this.object.position;{let e=this.object.getBoundingInfo();return e.boundingBox.centerWorld}}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):rr.P.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):rr.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){let t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):ru.Y.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){let t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):ru.Y.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e],r=-1,s=this._onPhysicsCollideCallbacks.some((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){let t=e.otherImpostors.every(e=>i.indexOf(e)>-1);return t&&(r=s),t}return!1});s?this._onPhysicsCollideCallbacks.splice(r,1):ru.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):rr._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){let r=new sk(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,s){if(!this._physicsEngine)return this;let n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor&&this._physicsEngine&&n.appendAnchor(this,e,t,i,r,s),this}addHook(e,t,i,r){if(!this._physicsEngine)return this;let s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor&&this._physicsEngine&&s.appendHook(this,e,t,i,r),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 sG(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 rr._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,r,s){let n=sG._TmpVecs[0],a=this.object;if(a.rotationQuaternion){if(s){let i=sG._TmpQuat;a.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,rO.T.WORLD,t)}else e.setRotationQuaternion(a.rotationQuaternion,rO.T.WORLD,t)}n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==r&&(r=i.length()),n.x*=r,n.y*=r,n.z*=r),e.getParent()?(n.addInPlace(a.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(a.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,r,s,n){let a=this.object;if(a.rotationQuaternion){if(s){let i=sG._TmpQuat;e.getRotationQuaternionToRef(rO.T.WORLD,t,i),i.multiplyToRef(s,a.rotationQuaternion)}else e.getRotationQuaternionToRef(rO.T.WORLD,t,a.rotationQuaternion)}let o=sG._TmpVecs[0],l=sG._TmpVecs[1];n||((n=sG._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,o),null==r&&i&&(r=i.length()),null!=r&&(o.x+=l.x*r,o.y+=l.y*r,o.z+=l.z*r),a.setAbsolutePosition(o)}}sG.DEFAULT_OBJECT_SIZE=new rr.P(1,1,1),sG.IDENTITY_QUATERNION=rr._f.Identity(),sG._TmpVecs=rD.B.BuildArray(3,rr.P.Zero),sG._TmpQuat=rr._f.Identity(),sG.NoImpostor=0,sG.SphereImpostor=1,sG.BoxImpostor=2,sG.PlaneImpostor=3,sG.MeshImpostor=4,sG.CapsuleImpostor=6,sG.CylinderImpostor=7,sG.ParticleImpostor=8,sG.HeightmapImpostor=9,sG.ConvexHullImpostor=10,sG.CustomImpostor=100,sG.RopeImpostor=101,sG.ClothImpostor=102,sG.SoftbodyImpostor=103;var sz=i(199),sW=i(8150);(l=tl||(tl={}))[l.Clean=0]="Clean",l[l.Stop=1]="Stop",l[l.Sync=2]="Sync",l[l.NoSync=3]="NoSync";class sH{static get ForceFullSceneLoadingForIncremental(){return sz.Z.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){sz.Z.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return sz.Z.ShowLoadingScreen}static set ShowLoadingScreen(e){sz.Z.ShowLoadingScreen=e}static get loggingLevel(){return sz.Z.loggingLevel}static set loggingLevel(e){sz.Z.loggingLevel=e}static get CleanBoneMatrixWeights(){return sz.Z.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){sz.Z.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return sH._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){let t=sH._RegisteredPlugins[e];return t||(ru.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"),sH.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(let t in sH._RegisteredPlugins){let i=sH._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return sH._RegisteredPlugins[t]}return sH.GetDefaultPlugin()}static _GetPluginForFilename(e){let t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));let i=e.lastIndexOf("."),r=e.substring(i,e.length).toLowerCase();return sH._GetPluginForExtension(r)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let r=e.rawData?"binary data":e.url,s="Unable to load from "+r;return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,r,s,n,a,o){let l;let h=sH._GetDirectLoad(e.url);if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";let u=a?sH._GetPluginForExtension(a):h?sH._GetPluginForDirectLoad(e.url):sH._GetPluginForFilename(e.url);if(e.rawData&&!u.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";if(!(l=void 0!==u.plugin.createPlugin?u.plugin.createPlugin():u.plugin))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(sH.OnPluginActivatedObservable.notifyObservers(l),h&&(l.canDirectLoad&&l.canDirectLoad(e.url)||!(0,sl.VL)(e.url))){if(l.directLoad){let e=l.directLoad(t,h);e.then?e.then(e=>{i(l,e)}).catch(e=>{s("Error in directLoad of _loadData: "+e,e)}):i(l,e)}else i(l,h);return l}let c=u.isBinary,d=(e,r)=>{if(t.isDisposed){s("Scene has been disposed");return}i(l,e,r)},p=null,_=!1,f=l.onDisposeObservable;f&&f.add(()=>{_=!0,p&&(p.abort(),p=null),n()});let m=()=>{if(_)return;let i=(e,t)=>{s(null==e?void 0:e.statusText,t)};if(!l.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=l.loadFile?l.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,r,c,i,o):t._loadFile(e.file||e.url,d,r,!0,c,i)},g=t.getEngine(),v=g.enableOfflineSupport;if(v){let i=!1;for(let r of t.disableOfflineSupportExceptionRules)if(r.test(e.url)){i=!0;break}v=!i}return v&&r7.D.OfflineProviderFactory?t.offlineProvider=r7.D.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),l}static _GetFileInfo(e,t){let i,r;let s=null,n=null;if(t){if(t.name)i=`file:${t.name}`,r=t.name,s=t;else if(ArrayBuffer.isView(t))i="",r="arrayBuffer",n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,r="";else{if("/"===t.substr(0,1))return rZ.w1.Error("Wrong sceneFilename parameter"),null;i=e+t,r=t}}else i=e,r=rZ.w1.GetFilename(e),e=rZ.w1.GetFolderPath(e);return{url:i,rootUrl:e,name:r,file:s,rawData:n}}static GetPluginForExtension(e){return sH._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!sH._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){let t=e.extensions;sH._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{let t=e.extensions;Object.keys(t).forEach(i=>{sH._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",r=rp.l.LastCreatedScene,s=null,n=null,a=null,o=null,l=""){if(!r)return ru.Y.Error("No scene available to import mesh to"),null;let h=sH._GetFileInfo(t,i);if(!h)return null;let u={};r.addPendingData(u);let c=()=>{r.removePendingData(u)},d=(e,t)=>{let i=sH._FormatErrorMessage(h,e,t);a?a(r,i,new sW.LH(i,sW.SM.SceneLoaderError,t)):ru.Y.Error(i),c()},p=n?e=>{try{n(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,_=(e,t,i,n,a,o,l)=>{if(r.importedMeshesFiles.push(h.url),s)try{s(e,t,i,n,a,o,l)}catch(e){d("Error in onSuccess callback: "+e,e)}r.removePendingData(u)};return sH._LoadData(h,r,(t,i,s)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,s)),t.importMesh){let s=[],n=[],a=[];t.importMesh(e,r,i,h.rootUrl,s,n,a,d)&&(r.loadingPluginName=t.name,_(s,n,a,[],[],[],[]))}else t.importMeshAsync(e,r,i,h.rootUrl,p,h.name).then(e=>{r.loadingPluginName=t.name,_(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)}).catch(e=>{d(e.message,e)})},p,d,c,o,l)}static ImportMeshAsync(e,t,i="",r=rp.l.LastCreatedScene,s=null,n=null,a=""){return new Promise((o,l)=>{sH.ImportMesh(e,t,i,r,(e,t,i,r,s,n,a)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:r,transformNodes:s,geometries:n,lights:a})},s,(e,t,i)=>{l(i||Error(t))},n,a)})}static Load(e,t="",i=rp.l.LastCreatedEngine,r=null,s=null,n=null,a=null,o=""){return i?sH.Append(e,t,new rI.x(i),r,s,n,a,o):(rZ.w1.Error("No engine available"),null)}static LoadAsync(e,t="",i=rp.l.LastCreatedEngine,r=null,s=null,n=""){return new Promise((a,o)=>{sH.Load(e,t,i,e=>{a(e)},r,(e,t,i)=>{o(i||Error(t))},s,n)})}static Append(e,t="",i=rp.l.LastCreatedScene,r=null,s=null,n=null,a=null,o=""){if(!i)return ru.Y.Error("No scene available to append to"),null;let l=sH._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let u=()=>{i.removePendingData(h)};sH.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));let c=(e,t)=>{let r=sH._FormatErrorMessage(l,e,t);n?n(i,r,new sW.LH(r,sW.SM.SceneLoaderError,t)):ru.Y.Error(r),u()},d=s?e=>{try{s(e)}catch(e){c("Error in onProgress callback",e)}}:void 0,p=()=>{if(r)try{r(i)}catch(e){c("Error in onSuccess callback",e)}i.removePendingData(h)};return sH._LoadData(l,i,(e,t)=>{e.load?!e.load(i,t,l.rootUrl,c)||(i.loadingPluginName=e.name,p()):e.loadAsync(i,t,l.rootUrl,d,l.name).then(()=>{i.loadingPluginName=e.name,p()}).catch(e=>{c(e.message,e)})},d,c,u,a,o)}static AppendAsync(e,t="",i=rp.l.LastCreatedScene,r=null,s=null,n=""){return new Promise((a,o)=>{sH.Append(e,t,i,e=>{a(e)},r,(e,t,i)=>{o(i||Error(t))},s,n)})}static LoadAssetContainer(e,t="",i=rp.l.LastCreatedScene,r=null,s=null,n=null,a=null,o=""){if(!i)return ru.Y.Error("No scene available to load asset container to"),null;let l=sH._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let u=()=>{i.removePendingData(h)},c=(e,t)=>{let r=sH._FormatErrorMessage(l,e,t);n?n(i,r,new sW.LH(r,sW.SM.SceneLoaderError,t)):ru.Y.Error(r),u()},d=s?e=>{try{s(e)}catch(e){c("Error in onProgress callback",e)}}:void 0,p=e=>{if(r)try{r(e)}catch(e){c("Error in onSuccess callback",e)}i.removePendingData(h)};return sH._LoadData(l,i,(e,t)=>{if(e.loadAssetContainer){let r=e.loadAssetContainer(i,t,l.rootUrl,c);r&&(r.populateRootNodes(),i.loadingPluginName=e.name,p(r))}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,d,l.name).then(t=>{t.populateRootNodes(),i.loadingPluginName=e.name,p(t)}).catch(e=>{c(e.message,e)}):c("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},d,c,u,a,o)}static LoadAssetContainerAsync(e,t="",i=rp.l.LastCreatedScene,r=null,s=null){return new Promise((n,a)=>{sH.LoadAssetContainer(e,t,i,e=>{n(e)},r,(e,t,i)=>{a(i||Error(t))},s)})}static ImportAnimations(e,t="",i=rp.l.LastCreatedScene,r=!0,s=tl.Clean,n=null,a=null,o=null,l=null,h=null){if(!i){ru.Y.Error("No scene available to load animations to");return}if(r){for(let e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(e=>{e.dispose()});let e=i.getNodes();e.forEach(e=>{e.animations&&(e.animations=[])})}else switch(s){case tl.Clean:i.animationGroups.slice().forEach(e=>{e.dispose()});break;case tl.Stop:i.animationGroups.forEach(e=>{e.stop()});break;case tl.Sync:i.animationGroups.forEach(e=>{e.reset(),e.restart()});break;case tl.NoSync:break;default:ru.Y.Error("Unknown animation group loading mode value '"+s+"'");return}let u=i.animatables.length;this.LoadAssetContainer(e,t,i,e=>{e.mergeAnimationsTo(i,i.animatables.slice(u),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)},o,l,h)}static ImportAnimationsAsync(e,t="",i=rp.l.LastCreatedScene,r=!0,s=tl.Clean,n=null,a=null,o=null,l=null,h=null){return new Promise((a,l)=>{sH.ImportAnimations(e,t,i,r,s,n,e=>{a(e)},o,(e,t,i)=>{l(i||Error(t))},h)})}}sH.NO_LOGGING=0,sH.MINIMAL_LOGGING=1,sH.SUMMARY_LOGGING=2,sH.DETAILED_LOGGING=3,sH.OnPluginActivatedObservable=new ri.y$,sH._RegisteredPlugins={},sH._ShowingLoadingScreen=!1;var sX=i(1870);class sY extends sX.F{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new rr.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){let 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)}}(h=th||(th={}))[h.Float=1]="Float",h[h.Int=2]="Int",h[h.Vector2=4]="Vector2",h[h.Vector3=8]="Vector3",h[h.Vector4=16]="Vector4",h[h.Color3=32]="Color3",h[h.Color4=64]="Color4",h[h.Matrix=128]="Matrix",h[h.Object=256]="Object",h[h.AutoDetect=1024]="AutoDetect",h[h.BasedOnInput=2048]="BasedOnInput",h[h.All=4095]="All",(u=tu||(tu={}))[u.Vertex=1]="Vertex",u[u.Fragment=2]="Fragment",u[u.Neutral=4]="Neutral",u[u.VertexAndFragment=3]="VertexAndFragment";var sj=i(4213);class sq{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],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){let t=e.sharedData.emitComments,i=this.target===tu.Fragment;this.compilationString=` -${t?"//Entry point\n":""}void main(void) { -${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` -${t?"//Constants\n":""}${this._constantDeclaration} -${this.compilationString}`);let r="";for(let e in this.functions)r+=this.functions[e]+` -`;for(let e in this.compilationString=` -${r} -${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString} -${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString} -${this._injectAtEnd}`),this.compilationString=`${this.compilationString} -}`,this.sharedData.varyingDeclaration&&(this.compilationString=` -${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration} -${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=` -${t?"//Samplers\n":""}${this._samplerDeclaration} -${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=` -${t?"//Uniforms\n":""}${this._uniformDeclaration} -${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=` -${t?"//Attributes\n":""}${this._attributeDeclaration} -${this.compilationString}`),this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,this.extensions){let t=this.extensions[e];this.compilationString=` -${t} -${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){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2D ${e}; -`,this.samplers.push(e))}_emit2DArraySampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2DArray ${e}; -`,this.samplers.push(e))}_getGLType(e){switch(e){case th.Float:return"float";case th.Int:return"int";case th.Vector2:return"vec2";case th.Color3:case th.Vector3:return"vec3";case th.Color4:case th.Vector4:return"vec4";case th.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i} -${t} -#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+` -`+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] -`;let r=sj.Q.IncludesShadersStore[e]+"\n";if(this.sharedData.emitComments&&(r=t+` -`+r),!i)return r;if(i.replaceStrings)for(let e=0;e<i.replaceStrings.length;e++){let t=i.replaceStrings[e];r=r.replace(t.search,t.replace)}return r}_emitFunctionFromInclude(e,t,i,r=""){let s=e+r;if(!this.functions[s]){if(!i||!i.removeAttributes&&!i.removeUniforms&&!i.removeVaryings&&!i.removeIfDef&&!i.replaceStrings){i&&i.repeatKey?this.functions[s]=`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] -`:this.functions[s]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""} -`,this.sharedData.emitComments&&(this.functions[s]=t+` -`+this.functions[s]);return}if(this.functions[s]=sj.Q.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+` -`+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;e<i.replaceStrings.length;e++){let t=i.replaceStrings[e];this.functions[s]=this.functions[s].replace(t.search,t.replace)}}}_registerTempVariable(e){return -1===this.sharedData.temps.indexOf(e)&&(this.sharedData.temps.push(e),!0)}_emitVaryingFromString(e,t,i="",r=!1){return -1===this.sharedData.varyings.indexOf(e)&&(this.sharedData.varyings.push(e),i&&(i.startsWith("defined(")?this.sharedData.varyingDeclaration+=`#if ${i} -`:this.sharedData.varyingDeclaration+=`${r?"#ifndef":"#ifdef"} ${i} -`),this.sharedData.varyingDeclaration+=`varying ${t} ${e}; -`,i&&(this.sharedData.varyingDeclaration+=`#endif -`),!0)}_emitUniformFromString(e,t,i="",r=!1){-1===this.uniforms.indexOf(e)&&(this.uniforms.push(e),i&&(i.startsWith("defined(")?this._uniformDeclaration+=`#if ${i} -`:this._uniformDeclaration+=`${r?"#ifndef":"#ifdef"} ${i} -`),this._uniformDeclaration+=`uniform ${t} ${e}; -`,i&&(this._uniformDeclaration+=`#endif -`))}_emitFloat(e){return e.toString()===e.toFixed(0)?`${e}.0`:e.toString()}}class sK{constructor(){this.temps=[],this.varyings=[],this.varyingDeclaration="",this.inputBlocks=[],this.textureBlocks=[],this.bindableBlocks=[],this.forcedBindableBlocks=[],this.blocksWithFallbacks=[],this.blocksWithDefines=[],this.repeatableContentBlocks=[],this.dynamicUniformBlocks=[],this.blockingBlocks=[],this.animatedInputs=[],this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:[]},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}emitErrors(){let e="";for(let t of(this.checks.emitVertex||this.allowEmptyVertexProgram||(e+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\n"),this.checks.emitFragment||(e+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\n"),this.checks.notConnectedNonOptionalInputs))e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. -`;if(e)throw"Build of NodeMaterial failed:\n"+e}}var s$=i(9241);(c=tc||(tc={}))[c.Compatible=0]="Compatible",c[c.TypeIncompatible=1]="TypeIncompatible",c[c.TargetIncompatible=2]="TargetIncompatible",c[c.HierarchyIssue=3]="HierarchyIssue",(d=td||(td={}))[d.Input=0]="Input",d[d.Output=1]="Output";class sQ{static AreEquivalentTypes(e,t){switch(e){case th.Vector3:if(t===th.Color3)return!0;break;case th.Vector4:if(t===th.Color4)return!0;break;case th.Color3:if(t===th.Vector3)return!0;break;case th.Color4:if(t===th.Vector4)return!0}return!1}get direction(){return this._direction}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===th.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===th.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get target(){return this._prioritizeVertex&&this._ownerBlock&&this._target===tu.VertexAndFragment?this._ownerBlock.target===tu.Fragment?tu.Fragment:tu.Vertex:this._target}set target(e){this._target=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get isConnectedToInputBlock(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map(e=>e.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tu.Vertex||(e.ownerBlock.target===tu.Neutral||e.ownerBlock.target===tu.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===tu.Vertex)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tu.Vertex||e.target===tu.Vertex||(e.ownerBlock.target===tu.Neutral||e.ownerBlock.target===tu.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===tu.Fragment)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tu.Fragment||(e.ownerBlock.target===tu.Neutral||e.ownerBlock.target===tu.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=[],this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=th.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new ri.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=tu.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===tc.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(t.target===tu.Fragment){if(i.target===tu.Vertex)return tc.TargetIncompatible;for(let e of i.outputs)if(e.ownerBlock.target!=tu.Neutral&&e.isConnectedInVertexShader)return tc.TargetIncompatible}if(this.type!==e.type&&e.innerType!==th.AutoDetect)return sQ.AreEquivalentTypes(this.type,e.type)?tc.Compatible:e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&sQ.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?tc.Compatible:tc.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return tc.TypeIncompatible;let r=i,s=t;return(this.direction===td.Input&&(r=t,s=i),r.isAnAncestorOf(s))?tc.HierarchyIssue:tc.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){let 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<th.All;)e&t||this.excludedConnectionPointTypes.push(t),t<<=1}serialize(e=!0){let t={};return t.name=this.name,t.displayName=this.displayName,e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name,t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),(this.isExposedOnFrame||this.exposedPortPosition>=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}}var sZ=i(2853);class sJ{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){(this._target&e)==0&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}constructor(e,t=tu.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=[],this._outputs=[],this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===tu.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=sZ.K.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===tu.Neutral}initialize(e){}bind(e,t,i,r){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){let t=e.connectedPoint;return t?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return -1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some(e=>e.isConnectedInFragmentShader)}registerInput(e,t,i=!1,r,s){return(s=null!=s?s:new sQ(e,this,td.Input)).type=t,s.isOptional=i,r&&(s.target=r),this._inputs.push(s),this}registerOutput(e,t,i,r){return(r=null!=r?r:new sQ(e,this,td.Output)).type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(let t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===th.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(let t of this._outputs)if(!e||!e.target||e.target===tu.Neutral||(e.target&t.target)!=0)return t;return null}getSiblingOutput(e){let t=this._outputs.indexOf(e);return -1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){let s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),r=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,s){}autoConfigure(e){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput))&&this.target!==tu.Vertex&&!!((this.target===tu.VertexAndFragment||this.target===tu.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);let s=null!=t._vertexState,n=e._buildTarget===tu.Vertex&&e.target!==tu.VertexAndFragment;if(s&&((e.target&e._buildTarget)==0||(e.target&i.target)==0||this.target!==tu.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){let e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName}; -`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){for(let t of["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"])if(e===t)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(let t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(let i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==tu.Neutral&&((i.target&this.target)==0||(i.target&e.target)==0))continue;let r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log(`${e.target===tu.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case tu.Vertex:e.sharedData.checks.emitVertex=!0;break;case tu.Fragment:e.sharedData.checks.emitFragment=!0}for(let i of(!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=` -//${this.name} -`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target,this._outputs))if((i.target&e.target)!=0)for(let r of i.endpoints){let i=r.ownerBlock;i&&(i.target&e.target)!=0&&-1!==t.indexOf(i)&&this._processBuild(i,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector}; -${e}.visibleOnFrame = ${this.visibleOnFrame}; -${e}.target = ${this.target}; -`}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` -// ${this.getClassName()} -`;for(let i of(this.comments&&(r+=`// ${this.comments} -`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); -`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint,n=s.ownerBlock;-1===t.indexOf(n)&&(r+=n._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); -`}return t}clone(e,t=""){let i=this.serialize(),r=(0,rn.q)(i.customType);if(r){let s=new r;return s._deserialize(i,e,t),s}return null}serialize(){let e={};for(let t of(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=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var r;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(r=e.target)&&void 0!==r?r:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let 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(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose()}}class s0 extends sJ{constructor(e){super(e,tu.Neutral),this.complementW=1,this.complementZ=0,this.target=tu.Vertex,this.registerInput("vector",th.AutoDetect),this.registerInput("transform",th.Matrix),this.registerOutput("output",th.Vector4),this.registerOutput("xyz",th.Vector3),this._inputs[0].onConnectionObservable.add(e=>{if(e.ownerBlock.isInput){let 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);let t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){let r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),e.sharedData.blocksWithDefines.push(this);let s=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${s} = mat3(${i.associatedVariableName}); -`,e.compilationString+=`#ifdef NONUNIFORMSCALING -`,e.compilationString+=`${s} = transposeMat3(inverseMat3(${s})); -`,e.compilationString+=`#endif -`,t.connectedPoint.type){case th.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); -`;break;case th.Vector3:case th.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); -`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); -`}}else{let r=i.associatedVariableName;switch(t.connectedPoint.type){case th.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); -`;break;case th.Vector3:case th.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); -`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * ${t.associatedVariableName}; -`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; -`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){let 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(){return super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ}; -`+`${this._codeVariableName}.complementW = ${this.complementW}; -`}}(0,rn.H)("BABYLON.TransformBlock",s0);class s1 extends sJ{constructor(e){super(e,tu.Vertex,!0),this.registerInput("vector",th.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e){for(let t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);let t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName}; -`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w; -`,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant; -`),this}}function s2(e,t=tp.Boolean,i="PROPERTIES",r){return(s,n)=>{let a=s._propStore;a||(a=[],s._propStore=a),a.push({propertyName:n,displayName:e,type:t,groupName:i,options:null!=r?r:{}})}}(0,rn.H)("BABYLON.VertexOutputBlock",s1),(p=tp||(tp={}))[p.Boolean=0]="Boolean",p[p.Float=1]="Float",p[p.Int=2]="Int",p[p.Vector2=3]="Vector2",p[p.List=4]="List";var s3=i(8461);class s4 extends sJ{constructor(e){super(e,tu.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",th.Color4,!0),this.registerInput("rgb",th.AutoDetect,!0),this.registerInput("a",th.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Vector3|th.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&&s3.G.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);let t=this.rgba,i=this.rgb,r=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||r.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");let s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)r.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${r.associatedVariableName}); -`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName}; -`;else if(i.connectedPoint){let t="1.0";r.connectedPoint&&(t=r.associatedVariableName),i.connectedPoint.type===th.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t}); -`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t}); -`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName} -`,e.compilationString+=`gl_FragColor = toLinearSpace(gl_FragColor); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef ${this._gammaDefineName} -`,e.compilationString+=`gl_FragColor = toGammaSpace(gl_FragColor); -`,e.compilationString+=`#endif -`,this.useLogarithmicDepth&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5; -`),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; -${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; -${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth}; -`}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(r=e.useLogarithmicDepth)&&void 0!==r&&r}}(0,r0.gn)([s2("Convert to gamma space",tp.Boolean,"PROPERTIES",{notifiers:{update:!0}})],s4.prototype,"convertToGammaSpace",void 0),(0,r0.gn)([s2("Convert to linear space",tp.Boolean,"PROPERTIES",{notifiers:{update:!0}})],s4.prototype,"convertToLinearSpace",void 0),(0,r0.gn)([s2("Use logarithmic depth",tp.Boolean,"PROPERTIES")],s4.prototype,"useLogarithmicDepth",void 0),(0,rn.H)("BABYLON.FragmentOutputBlock",s4),(_=t_||(t_={}))[_.Uniform=0]="Uniform",_[_.Attribute=1]="Attribute",_[_.Varying=2]="Varying",_[_.Undefined=3]="Undefined",(f=tf||(tf={}))[f.World=1]="World",f[f.View=2]="View",f[f.Projection=3]="Projection",f[f.ViewProjection=4]="ViewProjection",f[f.WorldView=5]="WorldView",f[f.WorldViewProjection=6]="WorldViewProjection",f[f.CameraPosition=7]="CameraPosition",f[f.FogColor=8]="FogColor",f[f.DeltaTime=9]="DeltaTime",f[f.CameraParameters=10]="CameraParameters",f[f.MaterialAlpha=11]="MaterialAlpha";var s5=i(9320),s6=i(5831);(m=tm||(tm={}))[m.None=0]="None",m[m.Time=1]="Time",m[m.RealTime=2]="RealTime";let s8={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},s7={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},s9={particle_texturemask:!0};class ne extends sJ{get type(){if(this._type===th.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=th.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=th.Vector2,this._type;case"Vector3":return this._type=th.Vector3,this._type;case"Vector4":return this._type=th.Vector4,this._type;case"Color3":return this._type=th.Color3,this._type;case"Color4":return this._type=th.Color4,this._type;case"Matrix":return this._type=th.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=th.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=th.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=th.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=th.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case tf.World:case tf.WorldView:case tf.WorldViewProjection:case tf.View:case tf.ViewProjection:case tf.Projection:this._type=th.Matrix;break;case tf.CameraPosition:this._type=th.Vector3;break;case tf.FogColor:this._type=th.Color3;break;case tf.DeltaTime:case tf.MaterialAlpha:this._type=th.Float;break;case tf.CameraParameters:this._type=th.Vector4}}return this._type}constructor(e,t=tu.Vertex,i=th.AutoDetect){super(e,t,!1),this._mode=t_.Undefined,this._animationType=tm.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new ri.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=t_.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===th.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=t_.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=t_.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===t_.Undefined}get isUniform(){return this._mode===t_.Uniform}set isUniform(e){this._mode=e?t_.Uniform:t_.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===t_.Attribute}set isAttribute(e){this._mode=e?t_.Attribute:t_.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===t_.Varying}set isVarying(e){this._mode=e?t_.Varying:t_.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=t_.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case tm.Time:this.type===th.Float&&(this.value+=.01*e.getAnimationRatio());break;case tm.RealTime:this.type===th.Float&&(this.value=(rM.F.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)} -`:`#ifdef ${e} -`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case th.Float:this.value=0;break;case th.Vector2:this.value=rr.FM.Zero();break;case th.Vector3:this.value=rr.P.Zero();break;case th.Vector4:this.value=rr.Lt.Zero();break;case th.Color3:this.value=rs.Wo.White();break;case th.Color4:this.value=new rs.HE(1,1,1,1);break;case th.Matrix:this.value=rr.y3.Identity()}}_emitConstant(e){switch(this.type){case th.Float:return`${e._emitFloat(this.value)}`;case th.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case th.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case th.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case th.Color3:return rs.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&rs.zZ.Color3[0].toGammaSpaceToRef(rs.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rs.zZ.Color3[0].toLinearSpaceToRef(rs.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${rs.zZ.Color3[0].r}, ${rs.zZ.Color3[0].g}, ${rs.zZ.Color3[0].b})`;case th.Color4:return rs.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&rs.zZ.Color4[0].toGammaSpaceToRef(rs.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rs.zZ.Color4[0].toLinearSpaceToRef(rs.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${rs.zZ.Color4[0].r}, ${rs.zZ.Color4[0].g}, ${rs.zZ.Color4[0].b}, ${rs.zZ.Color4[0].a})`}return""}get _noContextSwitch(){return s7[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;e.constants.push(this.associatedVariableName),e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)}; -`;return}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}; -`,t&&(e._uniformDeclaration+=`#endif -`);let i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case tf.WorldView:i.needWorldViewMatrix=!0;break;case tf.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==tm.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=null!==(i=s8[this.name])&&void 0!==i?i:this.name,this.target===tu.Vertex&&e._vertexState){s7[this.name]?s9[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);return}if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),s7[this.name]?s9[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}; -`,t&&(e._attributeDeclaration+=`#endif -`))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;let s=this.associatedVariableName;switch(this._systemValue){case tf.World:e.setMatrix(s,t);break;case tf.WorldView:e.setMatrix(s,i);break;case tf.WorldViewProjection:e.setMatrix(s,r)}}_transmit(e,t,i){if(this.isAttribute)return;let r=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case tf.World:case tf.WorldView:case tf.WorldViewProjection:break;case tf.View:e.setMatrix(r,t.getViewMatrix());break;case tf.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case tf.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case tf.CameraPosition:t.bindEyePosition(e,r,!0);break;case tf.FogColor:e.setColor3(r,t.fogColor);break;case tf.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case tf.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case tf.MaterialAlpha:e.setFloat(r,i.alpha)}return}let s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case th.Float:e.setFloat(r,s);break;case th.Int:e.setInt(r,s);break;case th.Color3:rs.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&rs.zZ.Color3[0].toGammaSpaceToRef(rs.zZ.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rs.zZ.Color3[0].toLinearSpaceToRef(rs.zZ.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,rs.zZ.Color3[0]);break;case th.Color4:rs.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&rs.zZ.Color4[0].toGammaSpaceToRef(rs.zZ.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rs.zZ.Color4[0].toLinearSpaceToRef(rs.zZ.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,rs.zZ.Color4[0]);break;case th.Vector2:e.setVector2(r,s);break;case th.Vector3:e.setVector3(r,s);break;case th.Vector4:e.setVector4(r,s);break;case th.Matrix:e.setMatrix(r,s)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}"); -`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${tf[this._systemValue]}); -`;if(this.isUniform){let t=[],i="";switch(this.type){case th.Float:i=`${this.value}`;break;case th.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case th.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case th.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case th.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case th.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 th.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===th.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${tm[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){let 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===t_.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===t_.Attribute&&e.type===th.Vector3&&(this._type=th.Vector4),e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=(0,rn.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}}(0,rn.H)("BABYLON.InputBlock",ne);class nt extends sJ{constructor(e){super(e,tu.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",th.AutoDetect,!1,tu.VertexAndFragment),this.registerOutput("rgba",th.Color4,tu.Neutral),this.registerOutput("rgb",th.Color3,tu.Neutral),this.registerOutput("r",th.Float,tu.Neutral),this.registerOutput("g",th.Float,tu.Neutral),this.registerOutput("b",th.Float,tu.Neutral),this.registerOutput("a",th.Float,tu.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Vector2|th.Vector3|th.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?tu.VertexAndFragment:tu.Fragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput){let i=t.connectedPoint.ownerBlock;i.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; -`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tu.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); -`;return}if(this.uv.ownerBlock.target===tu.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); -`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); -`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tu.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}if(this.uv.ownerBlock.target===tu.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,e.compilationString+=`#ifdef ${this._linearDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef ${this._gammaDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.blockingBlocks.indexOf(this)&&e.sharedData.blockingBlocks.push(this),0>e.sharedData.textureBlocks.indexOf(this)&&e.sharedData.textureBlocks.push(this),0>e.sharedData.blocksWithDefines.indexOf(this)&&e.sharedData.blocksWithDefines.push(this),e.target!==tu.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e),this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let 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=sv.Parse(e.texture,t,i))}}(0,rn.H)("BABYLON.CurrentScreenBlock",nt);class ni extends sJ{constructor(e){super(e,tu.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",th.AutoDetect,!1,tu.VertexAndFragment),this.registerOutput("rgba",th.Color4,tu.Neutral),this.registerOutput("rgb",th.Color3,tu.Neutral),this.registerOutput("r",th.Float,tu.Neutral),this.registerOutput("g",th.Float,tu.Neutral),this.registerOutput("b",th.Float,tu.Neutral),this.registerOutput("a",th.Float,tu.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Vector2|th.Vector3|th.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 ne("uv")).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}; -`,e.compilationString+=`#ifdef ${this._linearDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef ${this._gammaDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`}_buildBlock(e){if(super._buildBlock(e),e.target===tu.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");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName}); -`,this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let 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=sv.Parse(e.texture,t,i))}}(0,rn.H)("BABYLON.ParticleTextureBlock",ni);class nr extends sJ{constructor(e){super(e,tu.Fragment),this._isUnique=!0,this.registerInput("color",th.Color4,!1,tu.Fragment),this.registerOutput("rampColor",th.Color4,tu.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!==tu.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=` - #ifdef RAMPGRADIENT - vec4 baseColor = ${this.color.associatedVariableName}; - float alpha = ${this.color.associatedVariableName}.a; - - float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); - - vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.)); - baseColor.rgb *= rampColor.rgb; - - // Remapped alpha - float finalAlpha = baseColor.a; - baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0); - - ${this._declareOutput(this.rampColor,e)} = baseColor; - #else - ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName}; - #endif - `,this}}(0,rn.H)("BABYLON.ParticleRampGradientBlock",nr);class ns extends sJ{constructor(e){super(e,tu.Fragment),this._isUnique=!0,this.registerInput("color",th.Color4,!1,tu.Fragment),this.registerInput("alphaTexture",th.Float,!1,tu.Fragment),this.registerInput("alphaColor",th.Float,!1,tu.Fragment),this.registerOutput("blendColor",th.Color4,tu.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!==tu.Vertex)return e.compilationString+=` - #ifdef BLENDMULTIPLYMODE - ${this._declareOutput(this.blendColor,e)}; - float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; - ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha); - ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a; - #else - ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName}; - #endif - `,this}}(0,rn.H)("BABYLON.ParticleBlendMultiplyBlock",ns);class nn{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=[]),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;let i=this._mesh.getScene();for(let e=0;e<i.meshes.length;e++){let r=i.meshes[e];if(!r.material){!this._mesh.material&&r.computeBonesUsingShaders&&r.numBoneInfluencers>0&&(r.computeBonesUsingShaders=!1);continue}if(r.computeBonesUsingShaders&&0!==r.numBoneInfluencers){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes)for(let e of r.subMeshes){let i=e.effect;if(i===t){r.computeBonesUsingShaders=!1;break}}}}}else{let t=this._defines[this._currentRank];if(t)for(let i=0;i<t.length;i++)e=e.replace("#define "+t[i],"");this._currentRank++}return e}}var na=i(1945),no=i(7005);let nl=`attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.postprocessVertexShader=nl;class nh{get depthStencilTexture(){return this._depthStencilTexture}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get 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;let r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,n){var a;return null===(a=this._depthStencilTexture)||void 0===a||a.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:n},this),this._depthStencilTexture}_shareDepth(e){this._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,r,s,n,a,o;let l=null;if(this._isMulti){let i=this.textures;if(i&&i.length>0){let r=!1,s=i.length,n=i[i.length-1]._source;(n===sT.S.Depth||n===sT.S.DepthStencil)&&(r=!0,s--);let a=[],o=[],h=[],u=[],c=[],d=[],p=[],_={};for(let r=0;r<s;++r){let s=i[r];a.push(s.samplingMode),o.push(s.type),h.push(s.format);let n=_[s.uniqueId];void 0!==n?(u.push(-1),p.push(0)):(_[s.uniqueId]=r,s.is2DArray?(u.push(35866),p.push(s.depth)):s.isCube?(u.push(34067),p.push(0)):s.is3D?(u.push(32879),p.push(s.depth)):(u.push(3553),p.push(0))),this._faceIndices&&c.push(null!==(e=this._faceIndices[r])&&void 0!==e?e:0),this._layerIndices&&d.push(null!==(t=this._layerIndices[r])&&void 0!==t?t:0)}let f={samplingModes:a,generateMipMaps:i[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:r,types:o,formats:h,textureCount:s,targetTypes:u,faceIndex:c,layerIndex:d,layerCounts:p},m={width:this.width,height:this.height};l=this._engine.createMultipleRenderTarget(m,f);for(let e=0;e<s;++e){if(-1!==u[e])continue;let t=_[i[e].uniqueId];l.setTexture(l.textures[t],e)}}}else{let e={};if(e.generateDepthBuffer=this._generateDepthBuffer,e.generateMipMaps=null!==(r=null===(i=this.texture)||void 0===i?void 0:i.generateMipMaps)&&void 0!==r&&r,e.generateStencilBuffer=this._generateStencilBuffer,e.samplingMode=null===(s=this.texture)||void 0===s?void 0:s.samplingMode,e.type=null===(n=this.texture)||void 0===n?void 0:n.type,e.format=null===(a=this.texture)||void 0===a?void 0:a.format,this.isCube)l=this._engine.createRenderTargetCubeTexture(this.width,e);else{let t={width:this.width,height:this.height,layers:this.is2DArray?null===(o=this.texture)||void 0===o?void 0:o.depth:void 0};l=this._engine.createRenderTargetTexture(t,e)}l.texture.isReady=!0}return l}_swapRenderTargetWrapper(e){if(this._textures&&e._textures)for(let t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null}_rebuild(){let e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){let t=this._depthStencilTexture.samplingMode;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,2===t||3===t||11===t,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let t=0;t<(null===(e=this._textures)||void 0===e?void 0:e.length);++t)this._textures[t].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 nu extends nh{constructor(e,t,i,r,s){super(e,t,i,r),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)).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);let t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=this._depthStencilBuffer,this._engine._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var s,n,a,o;if(!e._hardwareTexture)return;let l=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(l),this._engine.webGLVersion>1){let l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(n=null!=i?i:null===(s=this.layerIndices)||void 0===s?void 0:s[t])&&void 0!==n?n:0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=null!==(o=null!=i?i:null===(a=this.faceIndices)||void 0===a?void 0:a[t])&&void 0!==o?o:0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{let s=this._context,n=s["COLOR_ATTACHMENT"+t+"_WEBGL"],a=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,n,a,e._hardwareTexture.underlyingResource,r)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,r;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;let s=null!==(r=null===(i=this._attachments)||void 0===i?void 0:i.length)&&void 0!==r?r:this.textures.length;for(let e=0;e<s;e++){let t=this.textures[e];t&&(t.is2DArray||t.is3D?this._bindTextureRenderTarget(t,e,this.layerIndices[e]):t.isCube?this._bindTextureRenderTarget(t,e,this.faceIndices[e]):this._bindTextureRenderTarget(t,e))}}setLayerAndFaceIndex(e=0,t,i){if(super.setLayerAndFaceIndex(e,t,i),!this.textures||!this.layerIndices||!this.faceIndices)return;let r=this.textures[e];r.is2DArray||r.is3D?this._bindTextureRenderTarget(this.textures[e],e,this.layerIndices[e]):r.isCube&&this._bindTextureRenderTarget(this.textures[e],e,this.faceIndices[e])}dispose(e=this._disposeOnlyFramebuffers){let t=this._context;!e&&(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(t.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(t.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(t.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),super.dispose(e)}}sx.B.prototype._createHardwareRenderTargetWrapper=function(e,t,i){let r=new nu(e,t,i,this,this._gl);return this._renderTargetWrapperCache.push(r),r},sx.B.prototype.createRenderTargetTexture=function(e,t){var i,r;let s;let n=this._createHardwareRenderTargetWrapper(!1,!1,e),a=!0,o=!1,l=!1,h=1;void 0!==t&&"object"==typeof t&&(a=null===(i=t.generateDepthBuffer)||void 0===i||i,o=!!t.generateStencilBuffer,l=!!t.noColorAttachment,s=t.colorAttachment,h=null!==(r=t.samples)&&void 0!==r?r:1);let u=s||(l?null:this._createInternalTexture(e,t,!0,sT.S.RenderTarget)),c=e.width||e,d=e.height||e,p=this._currentFramebuffer,_=this._gl,f=_.createFramebuffer();return this._bindUnboundFramebuffer(f),n._depthStencilBuffer=this._setupFramebufferDepthAttachments(o,a,c,d),u&&!u.is2DArray&&_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,u._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(p),n._framebuffer=f,n._generateDepthBuffer=a,n._generateStencilBuffer=o,n.setTextures(u),this.updateRenderTargetTextureSampleCount(n,h),n},sx.B.prototype.createDepthStencilTexture=function(e,t,i){if(!t.isCube)return this._createDepthStencilTexture(e,t,i);{let r=e.width||e;return this._createDepthStencilCubeTexture(r,t,i)}},sx.B.prototype._createDepthStencilTexture=function(e,t,i){let r=this._gl,s=e.layers||0,n=0!==s?r.TEXTURE_2D_ARRAY:r.TEXTURE_2D,a=new sT.l(this,sT.S.DepthStencil);if(!this._caps.depthTextureExtension)return ru.Y.Error("Depth texture is not supported by your browser or hardware."),a;let o=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t);if(this._bindTextureDirectly(n,a,!0),this._setupDepthStencilTexture(a,e,o.generateStencil,0!==o.comparisonFunction&&o.bilinearFiltering,o.comparisonFunction,o.samples),void 0!==o.depthTextureFormat){if(15!==o.depthTextureFormat&&16!==o.depthTextureFormat&&17!==o.depthTextureFormat&&13!==o.depthTextureFormat&&14!==o.depthTextureFormat&&18!==o.depthTextureFormat)return ru.Y.Error("Depth texture format is not supported."),a;a.format=o.depthTextureFormat}else a.format=o.generateStencil?13:16;let l=17===a.format||13===a.format||18===a.format;i._depthStencilTexture=a,i._depthStencilTextureWithStencil=l;let h=r.UNSIGNED_INT;15===a.format?h=r.UNSIGNED_SHORT:17===a.format||13===a.format?h=r.UNSIGNED_INT_24_8:14===a.format?h=r.FLOAT:18===a.format&&(h=r.FLOAT_32_UNSIGNED_INT_24_8_REV);let u=l?r.DEPTH_STENCIL:r.DEPTH_COMPONENT,c=u;if(this.webGLVersion>1&&(15===a.format?c=r.DEPTH_COMPONENT16:16===a.format?c=r.DEPTH_COMPONENT24:17===a.format||13===a.format?c=r.DEPTH24_STENCIL8:14===a.format?c=r.DEPTH_COMPONENT32F:18===a.format&&(c=r.DEPTH32F_STENCIL8)),a.is2DArray?r.texImage3D(n,0,c,a.width,a.height,s,0,u,h,null):r.texImage2D(n,0,c,a.width,a.height,0,u,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(a),i._depthStencilBuffer){let e=this._currentFramebuffer;this._bindUnboundFramebuffer(i._framebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),r.deleteRenderbuffer(i._depthStencilBuffer),i._depthStencilBuffer=null}return a},sx.B.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let 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);let r=e.texture._hardwareTexture;if(r.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){let s=i.createFramebuffer();if(!s)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);let n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBAMultiSampleBufferFormat(e.texture.type),i.COLOR_ATTACHMENT0,!1);if(!n)throw Error("Unable to create multi sampled framebuffer");r.addMSAARenderBuffer(n)}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 nc=i(1470),nd=i(3587);class np{static RegisterShaderCodeProcessing(e,t){if(!t){delete np._CustomShaderCodeProcessing[null!=e?e:""];return}np._CustomShaderCodeProcessing[null!=e?e:""]=t}static _GetShaderCodeProcessing(e){var t;return null!==(t=np._CustomShaderCodeProcessing[e])&&void 0!==t?t:np._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,r,s,n,a=1,o,l,h=null,u=0,c="postprocess",d,p=!1,_=5,f=nd.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=[],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 na.t(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new rr.FM(1,1),this._texelSize=rr.FM.Zero(),this.onActivateObservable=new ri.y$,this.onSizeChangedObservable=new ri.y$,this.onApplyObservable=new ri.y$,this.onBeforeRenderObservable=new ri.y$,this.onAfterRenderObservable=new ri.y$,this.name=e,null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):o&&(this._engine=o,this._engine.postProcesses.push(this)),this._options=s,this.renderTargetSamplingMode=a||1,this._reusable=l||!1,this._textureType=u,this._textureFormat=_,this._shaderLanguage=f,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=c,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=d,this._drawWrapper=new nc.q(this._engine),p||this.updateEffect(h)}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 na.t(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,n,a,o){var l,h;let u=np._GetShaderCodeProcessing(this.name);if(null==u?void 0:u.defineCustomBindings){let r=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];r.push(...this._parameters);let s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=u.defineCustomBindings(this.name,e,r,s),t=r,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=a?a:this._vertexUrl,fragment:null!=o?o: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!=n?n:null,indexParameters:r||this._indexParameters,processCodeAfterIncludes:(null==u?void 0:u.processCodeAfterIncludes)?(e,t)=>u.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:(null==u?void 0:u.processFinalCode)?(e,t)=>u.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 r=0;r<this._textureCache.length;r++)if(this._textureCache[r].texture.width===e.width&&this._textureCache[r].texture.height===e.height&&this._textureCache[r].postProcessChannel===i&&this._textureCache[r].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[r].texture.samples===t.samples)return this._textureCache[r].texture;let r=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:r,postProcessChannel:i,lastUsedRenderId:-1}),r}_flushTextureCache(){let e=this._renderId;for(let t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i<this._textures.length;i++)if(this._textures.data[i]===this._textureCache[t].texture){e=!0;break}e||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}_resize(e,t,i,r,s){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let n=null;for(let e=0;e<i._postProcesses.length;e++)if(null!==i._postProcesses[e]){n=i._postProcesses[e];break}let a={width:this.width,height:this.height},o={generateMipMaps:r,generateDepthBuffer:s||n===this,generateStencilBuffer:(s||n===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(a,o,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(a,o,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}activate(e,t=null,i){var r,s;let n;e=e||this._camera;let a=e.getScene(),o=a.getEngine(),l=o.getCaps().maxTextureSize,h=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,u=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0,c=e.parent;c&&(c.leftCamera==e||c.rightCamera==e)&&(h/=2);let d=this._options.width||h,p=this._options.height||u,_=7!==this.renderTargetSamplingMode&&1!==this.renderTargetSamplingMode&&2!==this.renderTargetSamplingMode;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){let e=o.currentViewport;e&&(d*=e.width,p*=e.height)}(_||this.alwaysForcePOT)&&(this._options.width||(d=o.needPOTTextures?r7.D.GetExponentOfTwo(d,l,this.scaleMode):d),this._options.height||(p=o.needPOTTextures?r7.D.GetExponentOfTwo(p,l,this.scaleMode):p)),(this.width!==d||this.height!==p)&&this._resize(d,p,e,_,i),this._textures.forEach(e=>{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)}),this._flushTextureCache(),this._renderId++}if(this._shareOutputWithPostProcess)n=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)n=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let e;n=this.inputTexture;for(let t=0;t<this._textureCache.length;t++)if(this._textureCache[t].texture===n){e=this._textureCache[t];break}e&&(e.lastUsedRenderId=this._renderId)}return this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(h/d,u/p),this._engine.bindFramebuffer(n,0,h,u,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(n,0,void 0,void 0,this.forceFullscreenViewport)),null===(s=(r=this._engine)._debugInsertMarker)||void 0===s||s.call(r,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:a.clearColor,a._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),n}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){var e,t;return null!==(t=null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}apply(){var e,t,i;let r;return(null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())?(this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),r=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",null==r?void 0:r.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),null===(i=null===(t=np._GetShaderCodeProcessing(this.name))||void 0===t?void 0:t.bindCustomBindings)||void 0===i||i.call(t,this.name,this._drawWrapper.effect),this._drawWrapper.effect):null}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&-1!==(t=this._scene.postProcesses.indexOf(this))&&this._scene.postProcesses.splice(t,1),this._parentContainer){let e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(-1!==(t=this._engine.postProcesses.indexOf(this))&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),0===(t=e._postProcesses.indexOf(this))&&e._postProcesses.length>0){let e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){let e=rg.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(){let e=this.serialize();e._engine=this._engine,e.cameraId=null;let t=np.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){let r=(0,rn.q)(e.customType);if(!r||!r._Parse)return null;let s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new np(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,r)}}np._CustomShaderCodeProcessing={},(0,r0.gn)([(0,rg.qC)()],np.prototype,"uniqueId",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"name",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"width",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"height",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"renderTargetSamplingMode",void 0),(0,r0.gn)([(0,rg.XX)()],np.prototype,"clearColor",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"autoClear",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"forceAutoClearInAlphaMode",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"alphaMode",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"alphaConstants",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"enablePixelPerfectMode",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"forceFullscreenViewport",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"scaleMode",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"alwaysForcePOT",void 0),(0,r0.gn)([(0,rg.qC)("samples")],np.prototype,"_samples",void 0),(0,r0.gn)([(0,rg.qC)()],np.prototype,"adaptScaleToCurrentViewport",void 0),(0,rn.H)("BABYLON.PostProcess",np);class n_ extends sJ{constructor(e){super(e,tu.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",th.Vector4,!0),this.registerInput("xyz ",th.Vector3,!0),this.registerInput("xy ",th.Vector2,!0),this.registerInput("zw ",th.Vector2,!0),this.registerInput("x",th.Float,!0),this.registerInput("y",th.Float,!0),this.registerInput("z",th.Float,!0),this.registerInput("w",th.Float,!0),this.registerOutput("xyzw",th.Vector4),this.registerOutput("xyz",th.Vector3),this.registerOutput("xy",th.Vector2),this.registerOutput("zw",th.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){let t=this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle;return"."+t.substr(0,e)}_buildBlock(e){super._buildBlock(e);let t=this.x,i=this.y,r=this.z,s=this.w,n=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],u=this._outputs[1],c=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; -`)):o.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${o.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(3)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; -`)):n.isConnected?(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${a.associatedVariableName})${this._buildSwizzle(4)}; -`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)}; -`),d.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)}; -`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)}; -`)):(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${a.associatedVariableName})${this._buildSwizzle(4)}; -`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)}; -`),d.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)}; -`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)}; -`)),this}serialize(){let 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 r,s,n,a;super._deserialize(e,t,i),this.xSwizzle=null!==(r=e.xSwizzle)&&void 0!==r?r:"x",this.ySwizzle=null!==(s=e.ySwizzle)&&void 0!==s?s:"y",this.zSwizzle=null!==(n=e.zSwizzle)&&void 0!==n?n:"z",this.wSwizzle=null!==(a=e.wSwizzle)&&void 0!==a?a:"w"}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}"; -${this._codeVariableName}.ySwizzle = "${this.ySwizzle}"; -${this._codeVariableName}.zSwizzle = "${this.zSwizzle}"; -${this._codeVariableName}.wSwizzle = "${this.wSwizzle}"; -`}}(0,rn.H)("BABYLON.VectorMergerBlock",n_);class nf extends sJ{constructor(e){super(e,tu.Neutral),this.sourceRange=new rr.FM(-1,1),this.targetRange=new rr.FM(0,1),this.registerInput("input",th.AutoDetect),this.registerInput("sourceMin",th.Float,!0),this.registerInput("sourceMax",th.Float,!0),this.registerInput("targetMin",th.Float,!0),this.registerInput("targetMax",th.Float,!0),this.registerOutput("output",th.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);let t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${s}) / (${r} - ${i}); -`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y}); -`+`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y}); -`}serialize(){let 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=rr.FM.FromArray(e.sourceRange),this.targetRange=rr.FM.FromArray(e.targetRange)}}(0,r0.gn)([s2("From",tp.Vector2)],nf.prototype,"sourceRange",void 0),(0,r0.gn)([s2("To",tp.Vector2)],nf.prototype,"targetRange",void 0),(0,rn.H)("BABYLON.RemapBlock",nf);class nm extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(th.Float),this._inputs[1].acceptedConnectionPointTypes.push(th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName}; -`,this}}(0,rn.H)("BABYLON.MultiplyBlock",nm),(g=tg||(tg={}))[g.Material=0]="Material",g[g.PostProcess=1]="PostProcess",g[g.Particle=2]="Particle",g[g.ProceduralTexture=3]="ProceduralTexture";var ng=i(9290);class nv{constructor(){this.direction1=new rr.P(0,1,0),this.direction2=new rr.P(0,1,0),this.minEmitBox=new rr.P(-.5,-.5,-.5),this.maxEmitBox=new rr.P(.5,.5,.5)}startDirectionFunction(e,t,i,r){let s=rm.R.RandomRange(this.direction1.x,this.direction2.x),n=rm.R.RandomRange(this.direction1.y,this.direction2.y),a=rm.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.x=s,t.y=n,t.z=a;return}rr.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){let s=rm.R.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),n=rm.R.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=rm.R.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(r){t.x=s,t.y=n,t.z=a;return}rr.P.TransformCoordinatesFromFloatsToRef(s,n,a,e,t)}clone(){let e=new nv;return r_.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(){let 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){rr.P.FromArrayToRef(e.direction1,0,this.direction1),rr.P.FromArrayToRef(e.direction2,0,this.direction2),rr.P.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),rr.P.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class nT{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?rr.jp.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),rr.jp.Vector3[0]).normalize();let s=rm.R.RandomRange(0,this.directionRandomizer),n=rm.R.RandomRange(0,this.directionRandomizer),a=rm.R.RandomRange(0,this.directionRandomizer);t.x=rr.jp.Vector3[0].x+s,t.y=rr.jp.Vector3[0].y+n,t.z=rr.jp.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,r){let s;let n=rm.R.RandomRange(0,2*Math.PI);s=this.emitFromSpawnPointOnly?1e-4:1-(s=rm.R.RandomRange(0,this.heightRange))*s;let a=this._radius-rm.R.RandomRange(0,this._radius*this.radiusRange);a*=s;let o=a*Math.sin(n),l=a*Math.cos(n),h=s*this._height;if(r){t.x=o,t.y=h,t.z=l;return}rr.P.TransformCoordinatesFromFloatsToRef(o,h,l,e,t)}clone(){let e=new nT(this._radius,this._angle,this.directionRandomizer);return r_.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(){let 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 nx{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=rr.P.Zero()}startDirectionFunction(e,t,i,r,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),rr.P.TransformNormalToRef(this._tempVector,s,this._tempVector);let n=rm.R.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),a=Math.atan2(this._tempVector.x,this._tempVector.z);if(a+=rm.R.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),r){t.copyFrom(this._tempVector);return}rr.P.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){let s=rm.R.RandomRange(-this.height/2,this.height/2),n=rm.R.RandomRange(0,2*Math.PI),a=rm.R.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),o=Math.sqrt(a)*this.radius,l=o*Math.cos(n),h=o*Math.sin(n);if(r){t.copyFromFloats(l,s,h);return}rr.P.TransformCoordinatesFromFloatsToRef(l,s,h,e,t)}clone(){let e=new nx(this.radius,this.directionRandomizer);return r_.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(){let 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 nS extends nx{constructor(e=1,t=1,i=1,r=new rr.P(0,1,0),s=new rr.P(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=s}startDirectionFunction(e,t){let i=rm.R.RandomRange(this.direction1.x,this.direction2.x),r=rm.R.RandomRange(this.direction1.y,this.direction2.y),s=rm.R.RandomRange(this.direction1.z,this.direction2.z);rr.P.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new nS(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return r_.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(){let 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 nE{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),n=rm.R.RandomRange(0,this.directionRandomizer),a=rm.R.RandomRange(0,this.directionRandomizer),o=rm.R.RandomRange(0,this.directionRandomizer);if(s.x+=n,s.y+=a,s.z+=o,s.normalize(),r){t.copyFrom(s);return}rr.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-rm.R.RandomRange(0,this.radius*this.radiusRange),n=rm.R.RandomRange(0,1),a=rm.R.RandomRange(0,2*Math.PI),o=Math.acos(2*n-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),u=s*Math.sin(a)*Math.sin(o);if(r){t.copyFromFloats(l,Math.abs(h),u);return}rr.P.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),u,e,t)}clone(){let e=new nE(this.radius,this.directionRandomizer);return r_.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(){let 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 nC{constructor(){this.direction1=new rr.P(0,1,0),this.direction2=new rr.P(0,1,0)}startDirectionFunction(e,t,i,r){let s=rm.R.RandomRange(this.direction1.x,this.direction2.x),n=rm.R.RandomRange(this.direction1.y,this.direction2.y),a=rm.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,n,a);return}rr.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){if(r){t.copyFromFloats(0,0,0);return}rr.P.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){let e=new nC;return r_.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(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){rr.P.FromArrayToRef(e.direction1,0,this.direction1),rr.P.FromArrayToRef(e.direction2,0,this.direction2)}}class nb{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),n=rm.R.RandomRange(0,this.directionRandomizer),a=rm.R.RandomRange(0,this.directionRandomizer),o=rm.R.RandomRange(0,this.directionRandomizer);if(s.x+=n,s.y+=a,s.z+=o,s.normalize(),r){t.copyFrom(s);return}rr.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-rm.R.RandomRange(0,this.radius*this.radiusRange),n=rm.R.RandomRange(0,1),a=rm.R.RandomRange(0,2*Math.PI),o=Math.acos(2*n-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),u=s*Math.sin(a)*Math.sin(o);if(r){t.copyFromFloats(l,h,u);return}rr.P.TransformCoordinatesFromFloatsToRef(l,h,u,e,t)}clone(){let e=new nb(this.radius,this.directionRandomizer);return r_.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(){let 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 ny extends nb{constructor(e=1,t=new rr.P(0,1,0),i=new rr.P(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){let i=rm.R.RandomRange(this.direction1.x,this.direction2.x),r=rm.R.RandomRange(this.direction1.y,this.direction2.y),s=rm.R.RandomRange(this.direction1.z,this.direction2.z);rr.P.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new ny(this.radius,this.direction1,this.direction2);return r_.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(){let 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 nA{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){let s=rr.jp.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);let e=rr.jp.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);if(r){t.copyFrom(s);return}rr.P.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,r){let s=rr.jp.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),r){t.copyFrom(s);return}rr.P.TransformCoordinatesToRef(s,e,t)}clone(){let e=new nA;return r_.j.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e}parse(e){}}class nR{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(rQ.o.PositionKind),this._normals=e.getVerticesData(rQ.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=rr.P.Zero(),this._mesh=null,this.direction1=new rr.P(0,1,0),this.direction2=new rr.P(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals){rr.P.TransformNormalToRef(this._storedNormal,e,t);return}let s=rm.R.RandomRange(this.direction1.x,this.direction2.x),n=rm.R.RandomRange(this.direction1.y,this.direction2.y),a=rm.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,n,a);return}rr.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;let s=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),a=Math.random()*(1-n),o=1-n-a,l=this._indices[s],h=this._indices[s+1],u=this._indices[s+2],c=rr.jp.Vector3[0],d=rr.jp.Vector3[1],p=rr.jp.Vector3[2],_=rr.jp.Vector3[3];rr.P.FromArrayToRef(this._positions,3*l,c),rr.P.FromArrayToRef(this._positions,3*h,d),rr.P.FromArrayToRef(this._positions,3*u,p),_.x=n*c.x+a*d.x+o*p.x,_.y=n*c.y+a*d.y+o*p.y,_.z=n*c.z+a*d.z+o*p.z,r?t.copyFromFloats(_.x,_.y,_.z):rr.P.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(rr.P.FromArrayToRef(this._normals,3*l,c),rr.P.FromArrayToRef(this._normals,3*h,d),rr.P.FromArrayToRef(this._normals,3*u,p),this._storedNormal.x=n*c.x+a*d.x+o*p.x,this._storedNormal.y=n*c.y+a*d.y+o*p.y,this._storedNormal.z=n*c.z+a*d.z+o*p.z)}clone(){let e=new nR(this.mesh);return r_.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;let 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){rr.P.FromArrayToRef(e.direction1,0,this.direction1),rr.P.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}i(8066);class nP{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:rr.P.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:rr.P.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:rr.P.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:rr.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 r=0;for(let i of t){if(i.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=rr.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 rr.P(10,10,10),this.onAnimationEnd=null,this.blendMode=nP.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 rr.FM(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new rr.P(0,0,0),this._useLogarithmicDepth=!1,this.gravity=rr.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 rs.HE(1,1,1,1),this.color2=new rs.HE(1,1,1,1),this.colorDead=new rs.HE(0,0,0,1),this.textureMask=new rs.HE(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new ng.b,this.id=e,this.name=e}createPointEmitter(e,t){let i=new nC;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){let i=new nE(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){let i=new nb(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new rr.P(0,1,0),i=new rr.P(0,1,0)){let r=new ny(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){let s=new nx(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new rr.P(0,1,0),s=new rr.P(0,1,0)){let n=new nS(e,t,i,r,s);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){let i=new nT(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,r){let s=new nv;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}}nP.BLENDMODE_ONEONE=0,nP.BLENDMODE_STANDARD=1,nP.BLENDMODE_ADD=2,nP.BLENDMODE_MULTIPLY=3,nP.BLENDMODE_MULTIPLYADD=4;class nI extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("rgba",th.Color4,!0),this.registerInput("rgb ",th.Color3,!0),this.registerOutput("rgb",th.Color3),this.registerOutput("r",th.Float),this.registerOutput("g",th.Float),this.registerOutput("b",th.Float),this.registerOutput("a",th.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);let t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;let i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],n=this._outputs[3],a=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb; -`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.r; -`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g; -`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.b; -`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.a; -`),this}}(0,rn.H)("BABYLON.ColorSplitterBlock",nI);var nM=i(1970),nD=i(7077);sx.B.prototype.createRenderTargetCubeTexture=function(e,t){let i=this._createHardwareRenderTargetWrapper(!1,!0,e),r=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},t);r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1);let s=this._gl,n=new sT.l(this,sT.S.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,n,!0);let a=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);1!==r.type||this._caps.textureFloat||(r.type=0,ru.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,a.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,a.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let t=0;t<6;t++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);let o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n.format=r.format,this._internalTexturesCache.push(n),i.setTextures(n),i};let nO={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class nN{constructor(e,t=nO){var i,r;this._fullscreenViewport=new s6.l(0,0,1,1);let s=null!==(i=t.positions)&&void 0!==i?i:nO.positions,n=null!==(r=t.indices)&&void 0!==r?r:nO.indices;this.engine=e,this._vertexBuffers={[rQ.o.PositionKind]:new rQ.o(e,s,rQ.o.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{for(let t in this._indexBuffer=e.createIndexBuffer(n),this._vertexBuffers){let e=this._vertexBuffers[t];e._rebuild()}})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();let 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(){let e=this._vertexBuffers[rQ.o.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[rQ.o.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class nF{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new ri.y$;let 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)}));let r=e.defines?e.defines.join("\n"):"";this._drawWrapper=new nc.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,r,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new sj.Q(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,r,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()}}let nL="passPixelShader",nw=`varying vec2 vUV;uniform sampler2D textureSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);}`;no.v.ShadersStore[nL]=nw;let nB={name:nL,shader:nw};class nU{static _CreateDumpRenderer(){if(!nU._DumpToolsEngine){let e=new OffscreenCanvas(100,100),t=null,i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{t=new sx.B(e,!1,i)}catch(r){e=document.createElement("canvas"),t=new sx.B(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;let r=new nN(t),s=new nF({engine:t,name:nB.name,fragmentShader:nB.shader,samplerNames:["textureSampler"]});nU._DumpToolsEngine={canvas:e,engine:t,renderer:r,wrapper:s}}return nU._DumpToolsEngine}static async DumpFramebuffer(e,t,i,r,s="image/png",n,a){let o=await i.readPixels(0,0,e,t),l=new Uint8Array(o.buffer);nU.DumpData(e,t,l,r,s,n,!0,void 0,a)}static DumpDataAsync(e,t,i,r="image/png",s,n=!1,a=!1,o){return new Promise(l=>{nU.DumpData(e,t,i,e=>l(e),r,s,n,a,o)})}static DumpData(e,t,i,r,s="image/png",n,a=!1,o=!1,l){let h=nU._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){let e=new Uint8Array(i.length),t=i.length;for(;t--;){let r=i[t];e[t]=Math.round(255*rm.R.Clamp(r))}i=e}let u=h.engine.createRawTexture(i,e,t,5,!1,!a,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",u),h.renderer.draw(),o?rZ.w1.ToBlob(h.canvas,e=>{let t=new FileReader;t.onload=e=>{let t=e.target.result;r&&r(t)},t.readAsArrayBuffer(e)},s,l):rZ.w1.EncodeScreenshotCanvasData(h.canvas,r,s,n,l),u.dispose()}static Dispose(){nU._DumpToolsEngine&&(nU._DumpToolsEngine.wrapper.dispose(),nU._DumpToolsEngine.renderer.dispose(),nU._DumpToolsEngine.engine.dispose()),nU._DumpToolsEngine=null}}rZ.w1.DumpData=nU.DumpData,rZ.w1.DumpDataAsync=nU.DumpDataAsync,rZ.w1.DumpFramebuffer=nU.DumpFramebuffer;class nV extends sv{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=(0,rD.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 e=0;e<i.length;++e)for(let r=0;r<this._renderPassIds.length;++r)i[e].setMaterialForRenderPass(this._renderPassIds[r],void 0!==t?Array.isArray(t)?t[r]:t:void 0)}get isMulti(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e.isMulti)&&void 0!==t&&t}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e._depthStencilTexture)&&void 0!==t?t:null}constructor(e,t,i,r=!1,s=!0,n=0,a=!1,o=sv.TRILINEAR_SAMPLINGMODE,l=!0,h=!1,u=!1,c=5,d=!1,p,_,f=!1,m=!1){var g,v,T,x,S,E;let C;if("object"==typeof r){let e=r;r=!!e.generateMipMaps,s=null===(g=e.doNotChangeAspectRatio)||void 0===g||g,n=null!==(v=e.type)&&void 0!==v?v:0,a=!!e.isCube,o=null!==(T=e.samplingMode)&&void 0!==T?T:sv.TRILINEAR_SAMPLINGMODE,l=null===(x=e.generateDepthBuffer)||void 0===x||x,h=!!e.generateStencilBuffer,u=!!e.isMulti,c=null!==(S=e.format)&&void 0!==S?S:5,d=!!e.delayAllocation,p=e.samples,_=e.creationFlags,f=!!e.noColorAttachment,m=!!e.useSRGBBuffer,C=e.colorAttachment}if(super(null,i,!r,void 0,o,void 0,void 0,void 0,void 0,c),this._unObserveRenderList=null,this._renderListHasChanged=(e,t)=>{var i;let r=this._renderList?this._renderList.length:0;(0===t&&r>0||0===r)&&(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 ri.y$,this.onAfterUnbindObservable=new ri.y$,this.onBeforeRenderObservable=new ri.y$,this.onAfterRenderObservable=new ri.y$,this.onClearObservable=new ri.y$,this.onResizeObservable=new ri.y$,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=rr.P.Zero(),!(i=this.getScene()))return;let b=this.getScene().getEngine();if(this._coordinatesMode=sv.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=a,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=b.onResizeObservable.add(()=>{}),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=s,this._renderingManager=new nD.$(i),this._renderingManager._useSceneAutoClearSetup=!0,u)return;this._renderTargetOptions={generateMipMaps:r,type:n,format:null!==(E=this._format)&&void 0!==E?E:void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:p,creationFlags:_,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:C,label:this.name},this.samplingMode===sv.NEAREST_SAMPLINGMODE&&(this.wrapU=sv.CLAMP_ADDRESSMODE,this.wrapV=sv.CLAMP_ADDRESSMODE),d||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=sv.INVCUBIC_MODE,this._textureMatrix=rr.y3.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0===p||(this.samples=p))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14){var n;null===(n=this._renderTarget)||void 0===n||n.createDepthStencilTexture(e,t,i,r,s)}_releaseRenderPassId(){if(this._scene){let e=this._scene.getEngine();for(let t=0;t<this._renderPassIds.length;++t)e.releaseRenderPassId(this._renderPassIds[t])}this._renderPassIds=[]}_createRenderPassId(){this._releaseRenderPassId();let e=this._scene.getEngine(),t=this._isCubeData?6:this.getRenderLayers()||1;for(let i=0;i<t;++i)this._renderPassIds[i]=e.createRenderPassId(`RenderTargetTexture - ${this.name}#${i}`)}_processSizeParameter(e,t=!0){if(e.ratio){this._sizeRatio=e.ratio;let t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e;t&&this._createRenderPassId()}get samples(){var e,t;return null!==(t=null===(e=this._renderTarget)||void 0===e?void 0:e.samples)&&void 0!==t?t:this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}addPostProcess(e){if(!this._postProcessManager){let e=this.getScene();if(!e)return;this._postProcessManager=new nM.O(e),this._postProcesses=[]}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(let e of this._postProcesses)e.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;let t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return -1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){let e=this._size.layers;return e||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){let t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var t;let i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;let r=this.getScene();r&&(this._processSizeParameter(e,!1),i?this._renderTarget=r.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=r.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 r;let s=this.getScene();if(!s)return i;let n=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let e=0;e<this._waitingRenderList.length;e++){let t=this._waitingRenderList[e],i=s.getMeshById(t);i&&this.renderList.push(i)}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];let e=this.getScene();if(!e)return i;let t=e.meshes;for(let e=0;e<t.length;e++){let i=t[e];this.renderListPredicate(i)&&this.renderList.push(i)}}let a=n.currentRenderPassId;this.onBeforeBindObservable.notifyObservers(this);let o=null!==(r=this.activeCamera)&&void 0!==r?r:s.activeCamera,l=s.activeCamera;o&&(o!==s.activeCamera&&(s.setTransformMatrix(o.getViewMatrix(),o.getProjectionMatrix(!0)),s.activeCamera=o),n.setViewport(o.rigParent?o.rigParent.viewport:o.viewport,this.getRenderWidth(),this.getRenderHeight())),this._defaultRenderListPrepared=!1;let h=i;if(i){s.getViewMatrix()||s.updateTransformMatrix();let e=this.is2DArray?this.getRenderLayers():this.isCube?6:1;for(let t=0;t<e&&h;t++){let e=null,r=this.renderList?this.renderList:s.getActiveMeshes().data,a=this.renderList?this.renderList.length:s.getActiveMeshes().length;n.currentRenderPassId=this._renderPassIds[t],this.onBeforeRenderObservable.notifyObservers(t),this.getCustomRenderList&&(e=this.getCustomRenderList(t,r,a)),e||(e=r),this._doNotChangeAspectRatio||s.updateTransformMatrix(!0);for(let t=0;t<e.length&&h;++t){let r=e[t];if(r.isEnabled()&&!r.isBlocked&&r.isVisible&&r.subMeshes){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(r,this.refreshRate,i)){h=!1;continue}}else if(!r.isReady(!0)){h=!1;continue}}}this.onAfterRenderObservable.notifyObservers(t),(this.is2DArray||this.isCube)&&(s.incrementRenderId(),s.resetCachedMaterial())}}else if(this.is2DArray&&!this.isMulti)for(let i=0;i<this.getRenderLayers();i++)this._renderToTarget(0,e,t,i,o),s.incrementRenderId(),s.resetCachedMaterial();else if(this.isCube&&!this.isMulti)for(let i=0;i<6;i++)this._renderToTarget(i,e,t,void 0,o),s.incrementRenderId(),s.resetCachedMaterial();else this._renderToTarget(0,e,t,void 0,o);return this.onAfterUnbindObservable.notifyObservers(this),n.currentRenderPassId=a,l&&(s.activeCamera=l,(s.getEngine().scenes.length>1||this.activeCamera&&this.activeCamera!==s.activeCamera)&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),n.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){let i=e*t,r=r7.D.NearestPOT(i+16384/(128+i));return Math.min(r7.D.FloorPOT(e),r)}_prepareRenderingManager(e,t,i,r){let s=this.getScene();if(!s)return;this._renderingManager.reset();let n=s.getRenderId();for(let a=0;a<t;a++){let t=e[a];if(t&&!t.isBlocked){let e;if(this.customIsReadyFunction){if(!this.customIsReadyFunction(t,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!t.isReady(0===this.refreshRate)){this.resetRefreshCounter();continue}if(!t._internalAbstractMeshDataInfo._currentLODIsUpToDate&&s.activeCamera&&(t._internalAbstractMeshDataInfo._currentLOD=s.customLODSelector?s.customLODSelector(t,this.activeCamera||s.activeCamera):t.getLOD(this.activeCamera||s.activeCamera),t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0),!t._internalAbstractMeshDataInfo._currentLOD)continue;let a=t._internalAbstractMeshDataInfo._currentLOD;if(a._preActivateForIntermediateRendering(n),e=!!r&&!!i&&(t.layerMask&i.layerMask)==0,t.isEnabled()&&t.isVisible&&t.subMeshes&&!e&&(a!==t&&a._activate(n,!0),t._activate(n,!0)&&t.subMeshes.length)){t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(a=t):a._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,a._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(let e=0;e<a.subMeshes.length;e++){let t=a.subMeshes[e];this._renderingManager.dispatch(t,a)}}}}for(let e=0;e<s.particleSystems.length;e++){let t=s.particleSystems[e],i=t.emitter;t.isStarted()&&i&&(!i.position||i.isEnabled())&&this._renderingManager.dispatchParticles(t)}}_bindFrameBuffer(e=0,t=0){let i=this.getScene();if(!i)return;let r=i.getEngine();this._renderTarget&&r.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):r&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0,s=null){var n,a,o,l,h,u;let c=this.getScene();if(!c)return;let d=c.getEngine();null===(n=d._debugPushGroup)||void 0===n||n.call(d,`render to face #${e} layer #${r}`,1),this._prepareFrame(c,e,r,t),this.is2DArray?(d.currentRenderPassId=this._renderPassIds[r],this.onBeforeRenderObservable.notifyObservers(r)):(d.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));let p=d.snapshotRendering&&1===d.snapshotRenderingMode;if(p)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||c.clearColor,!0,!0,!0);else{let n=null,u=this.renderList?this.renderList:c.getActiveMeshes().data,p=this.renderList?this.renderList.length:c.getActiveMeshes().length;for(let t of(this.getCustomRenderList&&(n=this.getCustomRenderList(this.is2DArray?r:e,u,p)),n?this._prepareRenderingManager(n,n.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(u,p,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),n=u),c._beforeRenderTargetClearStage))t.action(this,e,r);for(let t of(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||c.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||c.updateTransformMatrix(!0),c._beforeRenderTargetDrawStage))t.action(this,e,r);for(let t of(this._renderingManager.render(this.customRenderFunction,n,this.renderParticles,this.renderSprites),c._afterRenderTargetDrawStage))t.action(this,e,r);let _=null!==(o=null===(a=this._texture)||void 0===a?void 0:a.generateMipMaps)&&void 0!==o&&o;for(let i of(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&&c.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e),c._afterRenderTargetPostProcessStage))i.action(this,e,r);this._texture&&(this._texture.generateMipMaps=_),this._doNotChangeAspectRatio||c.updateTransformMatrix(!0),i&&nU.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),d)}this._unbindFrameBuffer(d,e),this._texture&&this.isCube&&5===e&&d.generateMipMapsForCubemap(this._texture),null===(u=d._debugPopGroup)||void 0===u||u.call(d,1)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){let e=this.getSize(),t=new nV(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;let e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t<this.renderList.length;t++)e.renderList.push(this.renderList[t].id);return e}disposeFramebufferObjects(){var e;null===(e=this._renderTarget)||void 0===e||e.dispose(!0)}releaseInternalTexture(){var e;null===(e=this._renderTarget)||void 0===e||e.releaseTextures(),this._texture=null}dispose(){var e;this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._releaseRenderPassId(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;let t=this.getScene();if(!t)return;let i=t.customRenderTargets.indexOf(this);for(let e of(i>=0&&t.customRenderTargets.splice(i,1),t.cameras))(i=e.customRenderTargets.indexOf(this))>=0&&e.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===nV.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=nV.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}nV.REFRESHRATE_RENDER_ONCE=0,nV.REFRESHRATE_RENDER_ONEVERYFRAME=1,nV.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,sv._CreateRenderTargetTexture=(e,t,i,r,s)=>new nV(e,t,i,r);class nk{constructor(e){this.name=ss.l.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(ss.l.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){rZ.w1.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e<this.scene.proceduralTextures.length;e++){let t=this.scene.proceduralTextures[e];t._shouldRender()&&t.render()}rZ.w1.EndPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0)}}}let nG=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.proceduralVertexShader=nG;class nz extends sv{constructor(e,t,i,r,s=null,n=!0,a=!1,o=0){super(null,r,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new ri.y$,this.onBeforeGenerationObservable=new ri.y$,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=[],this._samplers=[],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 l=(r=this.getScene()||rp.l.LastCreatedScene)._getComponent(ss.l.NAME_PROCEDURALTEXTURE);l||(l=new nk(r),r._addComponent(l)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=o,this._generateMipMaps=n,this._drawWrapper=new nc.q(this._fullEngine),this.setFragment(i),this._fallbackTexture=s;let h=this._createRtWrapper(a,t,n,o);this._texture=h.texture;let u=[];u.push(1,1),u.push(-1,1),u.push(-1,-1),u.push(1,-1),this._vertexBuffers[rQ.o.PositionKind]=new rQ.o(this._fullEngine,u,rQ.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r}),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(){let 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(){let e=this._vertexBuffers[rQ.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===nV.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=nV.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose()}_getDefines(){return""}isReady(){let e;let t=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;let i=this._getDefines();return!!(this._drawWrapper.effect&&i===this._cachedDefines&&this._drawWrapper.effect.isReady())||(e=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=t.createEffect(e,[rQ.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;let i=this._texture.isCube;this._rtWrapper.dispose();let r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return -1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;let r=this.getScene();if(!r)return;let s=this._fullEngine;if(s.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),s.setState(!1),!this.nodeMaterialSource){for(let e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(let e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(let e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(let e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(let e in this._colors4){let t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(let e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(let 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);let n=s.currentViewport;if(this.isCube)for(let e=0;e<6;e++)s.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(sX.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(r.clearColor,!0,!1,!1),s.drawElementsType(sX.F.TriangleFillMode,0,6);s.unBindFramebuffer(this._rtWrapper,this.isCube),n&&s.setViewport(n),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(){let e=this.getSize(),t=new nz(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(){let e=this.getScene();if(!e)return;let t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);let i=this._vertexBuffers[rQ.o.PositionKind];i&&(i.dispose(),this._vertexBuffers[rQ.o.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}(0,r0.gn)([(0,rg.qC)()],nz.prototype,"isEnabled",void 0),(0,r0.gn)([(0,rg.qC)()],nz.prototype,"autoClear",void 0),(0,r0.gn)([(0,rg.qC)()],nz.prototype,"_generateMipMaps",void 0),(0,r0.gn)([(0,rg.qC)()],nz.prototype,"_size",void 0),(0,r0.gn)([(0,rg.qC)()],nz.prototype,"refreshRate",null),(0,rn.H)("BABYLON.ProceduralTexture",nz),(v=tv||(tv={}))[v.Cos=0]="Cos",v[v.Sin=1]="Sin",v[v.Abs=2]="Abs",v[v.Exp=3]="Exp",v[v.Exp2=4]="Exp2",v[v.Round=5]="Round",v[v.Floor=6]="Floor",v[v.Ceiling=7]="Ceiling",v[v.Sqrt=8]="Sqrt",v[v.Log=9]="Log",v[v.Tan=10]="Tan",v[v.ArcTan=11]="ArcTan",v[v.ArcCos=12]="ArcCos",v[v.ArcSin=13]="ArcSin",v[v.Fract=14]="Fract",v[v.Sign=15]="Sign",v[v.Radians=16]="Radians",v[v.Degrees=17]="Degrees";class nW extends sJ{constructor(e){super(e,tu.Neutral),this.operation=tv.Cos,this.registerInput("input",th.AutoDetect),this.registerOutput("output",th.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);let t=this._outputs[0],i="";switch(this.operation){case tv.Cos:i="cos";break;case tv.Sin:i="sin";break;case tv.Abs:i="abs";break;case tv.Exp:i="exp";break;case tv.Exp2:i="exp2";break;case tv.Round:i="round";break;case tv.Floor:i="floor";break;case tv.Ceiling:i="ceil";break;case tv.Sqrt:i="sqrt";break;case tv.Log:i="log";break;case tv.Tan:i="tan";break;case tv.ArcTan:i="atan";break;case tv.ArcCos:i="acos";break;case tv.ArcSin:i="asin";break;case tv.Fract:i="fract";break;case tv.Sign:i="sign";break;case tv.Radians:i="radians";break;case tv.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName}); -`,this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${tv[this.operation]}; -`;return e}}(0,rn.H)("BABYLON.TrigonometryBlock",nW);let nH={effect:null,subMesh:null};class nX extends s$.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 nY extends sY{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||rp.l.LastCreatedScene),this._buildId=nY._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new rr.y3,this._cachedWorldViewProjectionMatrix=new rr.y3,this._optimizers=[],this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new ri.y$,this._vertexOutputNodes=[],this._fragmentOutputNodes=[],this.attachedBlocks=[],this._mode=tg.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),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){rZ.w1.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(let t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){let t=this._optimizers.indexOf(e);if(!(t>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){let t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return(e.target&tu.Vertex)!=0&&this._addVertexOutputNode(e),(e.target&tu.Fragment)!=0&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||((e.target&tu.Vertex)!=0&&this._removeVertexOutputNode(e),(e.target&tu.Fragment)!=0&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=tu.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){let 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=tu.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){let t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){e.target===tu.VertexAndFragment?i.push(e):t.target===tu.Fragment&&e.target===tu.Vertex&&e._preparationId!==this._buildId&&i.push(e),this._initializeBlock(e,t,i,r)}_initializeBlock(e,t,i,r=!0){if(e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){let t=e.getClassName();for(let 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(let s of e.inputs){s.associatedVariableName="";let n=s.connectedPoint;if(n){let s=n.ownerBlock;s!==e&&this._processInitializeOnLink(s,t,i,r)}}for(let s of(e.isTeleportOut&&e.entryPoint&&this._processInitializeOnLink(e.entryPoint,t,i,r),e.outputs))s.associatedVariableName=""}_resetDualBlocks(e,t){for(let i of(e.target===tu.VertexAndFragment&&(e.buildId=t),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._resetDualBlocks(e.entryPoint,t)}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;let r=this.getScene().getEngine(),s=this._mode===tg.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 sq,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=tu.Vertex,this._fragmentCompilationState=new sq,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=tu.Fragment,this._sharedData=new sK,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;let n=[],a=[];for(let e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,a,i);for(let e of this._fragmentOutputNodes)a.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);for(let e of(this.optimize(),n))e.build(this._vertexCompilationState,n);for(let e of(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,a))this._resetDualBlocks(e,this._buildId-1);for(let e of a)e.build(this._fragmentCompilationState,a);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=nY._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);let o=this.getScene().meshes;for(let e of o)if(e.subMeshes)for(let t of e.subMeshes){if(t.getMaterial()!==this||!t.materialDefines)continue;let e=t.materialDefines;e.markAllAsDirty(),e.reset()}}optimize(){for(let e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){let i=t.NORMAL,r=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(rQ.o.NormalKind),t.TANGENT=e.isVerticesDataPresent(rQ.o.TangentKind);let n=e.useVertexColors&&e.isVerticesDataPresent(rQ.o.ColorKind);t.VERTEXCOLOR_NME=n;let a=!1;for(let i=1;i<=6;++i){let r=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),a=a||t["UV"+i]!==r}(i!==t.NORMAL||r!==t.TANGENT||s!==t.VERTEXCOLOR_NME||a)&&t.markAsAttributesDirty()}createPostProcess(e,t=1,i=1,r,s,n=0,a=5){return this.mode!==tg.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,s,n,a)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,s,n,a=0,o=5){let l=this.name+this._buildId,h=new nX,u=new r$.x(l+"PostProcess",this.getScene()),c=this._buildId;return this._processDefines(u,h),sj.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 np(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,s,n,h.toString(),a,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,o),e.nodeMaterialSource=this,e.onApplyObservable.add(t=>{c!==this._buildId&&(delete sj.Q.ShadersStore[l+"VertexShader"],delete sj.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),c=this._buildId);let i=this._processDefines(u,h);i&&(sj.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),sc.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!==tg.ProceduralTexture)return console.log("Incompatible material mode"),null;let i=this.name+this._buildId,r=new nz(i,e,null,t),s=new r$.x(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};let n=new nX,a=this._processDefines(s,n);sj.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[rQ.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),null==a?void 0:a.fallbacks,void 0);r.nodeMaterialSource=this,r._setEffect(o);let l=this._buildId;return r.onBeforeGenerationObservable.add(()=>{l!==this._buildId&&(delete sj.Q.ShadersStore[i+"VertexShader"],delete sj.Q.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);let e=this._processDefines(s,n);e&&(sj.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),sc.Q.SetImmediate(()=>{o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[rQ.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),null==e?void 0:e.fallbacks,void 0),r._setEffect(o)})),this._checkInternals(o)}),r}_createEffectForParticles(e,t,i,r,s,n,a,o=""){let l=this.name+this._buildId+"_"+t;n||(n=new nX),a||(a=this.getScene().getMeshByName(this.name+"Particle"))||((a=new r$.x(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId,u=[],c=o;if(!s){let o=this._processDefines(a,n);sj.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(u,t),c=u.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+c,null==o?void 0:o.fallbacks,i,r,e),e.setCustomEffect(s,t)}s.onBindObservable.add(s=>{h!==this._buildId&&(delete sj.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),u.length=0,e.fillDefines(u,t);let d=u.join("\n");d!==c&&(n.markAllAsDirty(),c=d);let p=this._processDefines(a,n);if(p){sj.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+c,null==p?void 0:p.fallbacks,i,r,e),e.setCustomEffect(s,t),this._createEffectForParticles(e,t,i,r,s,n,a,o);return}this._checkInternals(s)})}_checkInternals(e){if(this._sharedData.animatedInputs){let e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(let t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(let t of this._sharedData.bindableBlocks)t.bind(e,this);for(let t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){if(this.mode!==tg.Particle){console.log("Incompatible material mode");return}this._createEffectForParticles(e,nP.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,nP.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==tg.Material){console.log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,r){let s=null,n=this.getScene();if(s3.G.PrepareDefinesForCamera(n,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(r=>{r.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(s=>{s.prepareDefines(e,this,t,i,r)}),t.isDirty){let 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)});let r=[];this._sharedData.dynamicUniformBlocks.forEach(e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,r)});let n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(e=>{let t=n.indexOf(e);-1===t&&n.push(e)});let a=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(e=>{let t=a.indexOf(e);-1===t&&a.push(e)});let o=new nn;this._sharedData.blocksWithFallbacks.forEach(t=>{t.provideFallbacks(e,o)}),s={lightDisposed:i,uniformBuffers:r,mergedUniforms:n,mergedSamplers:a,fallbacks:o}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;let r=this.getScene();if(this._sharedData.animatedInputs){let e=r.getFrameId();if(this._animationFrame!==e){for(let e of this._sharedData.animatedInputs)e.animate(r);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new nX);let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();if(this._prepareDefinesForAttributes(e,s),this._sharedData.blockingBlocks.some(t=>!t.isReady(e,this,s,i)))return!1;let a=this._processDefines(e,s,i,t);if(a){let e=t.effect,i=s.toString(),o=n.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},n);if(o){if(this._onEffectCreatedObservable&&(nH.effect=o,nH.subMesh=t,this._onEffectCreatedObservable.notifyObservers(nH)),this.allowShaderHotSwapping&&e&&!o.isReady()){if(o=e,s.markAsUnprocessed(),a.lightDisposed)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(o,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader -${this._vertexCompilationState.compilationString} - -// Fragment shader -${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){let t=this.getScene();if(!this._activeEffect)return;let i=this._sharedData.hints;for(let r of(i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),this._sharedData.inputBlocks))r._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);let n=this._mustRebind(r,s,t.visibility),a=this._sharedData;if(n){for(let e of a.bindableBlocks)e.bind(s,this,t,i);for(let e of a.forcedBindableBlocks)e.bind(s,this,t,i);for(let e of a.inputBlocks)e._transmit(s,r,this)}else if(!this.isFrozen)for(let e of a.forcedBindableBlocks)e.bind(s,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){let 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(){let e=[];for(let t of this.attachedBlocks)nY._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(let t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(let e of this.getTextureBlocks().filter(e=>e.texture).map(e=>e.texture))e.dispose();for(let e of this.attachedBlocks)e.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){let 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){let i=e&&e.editorURL?e.editorURL:nY.EditorURL;rZ.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;let e=new ne("Position");e.setAsAttribute("position");let t=new ne("World");t.setAsSystemValue(tf.World);let i=new s0("WorldPos");e.connectTo(i),t.connectTo(i);let r=new ne("ViewProjection");r.setAsSystemValue(tf.ViewProjection);let s=new s0("WorldPos * ViewProjectionTransform");i.connectTo(s),r.connectTo(s);let n=new s1("VertexOutput");s.connectTo(n);let a=new ne("color");a.value=new rs.HE(.8,.8,.8,1);let o=new s4("FragmentOutput");a.connectTo(o),this.addOutputNode(n),this.addOutputNode(o),this._mode=tg.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;let e=new ne("Position");e.setAsAttribute("position2d");let t=new ne("Constant1");t.isConstant=!0,t.value=1;let i=new n_("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new s1("VertexOutput");i.connectTo(r);let s=new ne("Scale");s.visibleInInspector=!0,s.value=new rr.FM(1,1);let n=new nf("uv0");e.connectTo(n);let a=new nm("UV scale");n.connectTo(a),s.connectTo(a);let o=new nt("CurrentScreen");a.connectTo(o),o.texture=new sv("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());let l=new s4("FragmentOutput");o.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=tg.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;let e=new ne("Position");e.setAsAttribute("position2d");let t=new ne("Constant1");t.isConstant=!0,t.value=1;let i=new n_("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new s1("VertexOutput");i.connectTo(r);let s=new ne("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=tm.Time,s.isConstant=!1;let n=new ne("Color3");n.value=new rs.Wo(1,1,1),n.isConstant=!1;let a=new s4("FragmentOutput"),o=new n_("VectorMerger");o.visibleInInspector=!1;let l=new nW("Cos");l.operation=tv.Cos,e.connectTo(o),s.output.connectTo(l.input),l.output.connectTo(o.z),o.xyzOut.connectTo(a.rgb),this.addOutputNode(r),this.addOutputNode(a),this._mode=tg.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;let e=new ne("uv");e.setAsAttribute("particle_uv");let t=new ni("ParticleTexture");e.connectTo(t);let i=new ne("Color");i.setAsAttribute("particle_color");let r=new nm("Texture * Color");t.connectTo(r),i.connectTo(r);let s=new nr("ParticleRampGradient");r.connectTo(s);let n=new nI("ColorSplitter");i.connectTo(n);let a=new ns("ParticleBlendMultiply");s.connectTo(a),t.connectTo(a,{output:"a"}),n.connectTo(a,{output:"a"});let o=new s4("FragmentOutput");a.connectTo(o),this.addOutputNode(o),this._mode=tg.Particle}async loadAsync(e,t=""){return nY.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}generateCode(){let e=[],t=[],i=["const","var","let"];for(let e of this._vertexOutputNodes)this._gatherBlocks(e,t);let r=[];for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,r);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); -`;for(let r of(s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${tg[this.mode]}; -`,t))r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(let t of r)t.isInput&&-1===e.indexOf(t)&&(s+=t._dumpCode(i,e));for(let t of(e=[],s+="\n// Connections\n",this._vertexOutputNodes))s+=t._dumpCodeForOutputConnections(e);for(let t of this._fragmentOutputNodes)s+=t._dumpCodeForOutputConnections(e);for(let e of(s+="\n// Output nodes\n",this._vertexOutputNodes))s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); -`;for(let e of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); -`;return s+`nodeMaterial.build(); -`}serialize(e){let t=e?{}:rg.p4.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{for(let e of(t.customType="BABYLON.NodeMaterial",t.outputNodes=[],this._vertexOutputNodes))this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}for(let e of(t.blocks=[],i))t.blocks.push(e.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let n=i[s.id];if(n){for(let a of s.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===r.name){let e=n.getInputByName(a.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){var r;i||this.clear();let s={};for(let i of e.blocks){let e=(0,rn.q)(i.customType);if(e){let r=new e;r._deserialize(i,this.getScene(),t),s[i.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e,i=t._tempEntryPointUniqueId;if(i){let e=s[i];e.attachToEndpoint(t)}}for(let t=0;t<e.blocks.length;t++){let r=e.blocks[t],n=s[r.id];n&&(!n.inputs.length||i)&&this._restoreConnections(n,e,s)}if(e.outputNodes)for(let t of e.outputNodes)this.addOutputNode(s[t]);if(e.locations||e.editorData&&e.editorData.locations){let t=e.locations||e.editorData.locations;for(let e of t)s[e.blockId]&&(e.blockId=s[e.blockId].uniqueId);i&&this.editorData&&this.editorData.locations&&t.concat(this.editorData.locations),e.locations?this.editorData={locations:t}:(this.editorData=e.editorData,this.editorData.locations=t);let r=[];for(let e in s)r[e]=s[e].uniqueId;this.editorData.map=r}this.comment=e.comment,void 0!==e.forceAlphaBlending&&(this.forceAlphaBlending=e.forceAlphaBlending),i||(this._mode=null!==(r=e.mode)&&void 0!==r?r:tg.Material)}loadFromSerialization(e,t="",i=!1){this.parseSerializedObject(e,t,i)}clone(e,t=!1){let i=this.serialize(),r=rg.p4.Clone(()=>new nY(e,this.getScene(),this.options),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}static Parse(e,t,i=""){let r=rg.p4.Parse(()=>new nY(e.name,t),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,r="",s=!1,n){let a=null!=n?n:new nY(e,i),o=await i._loadFileAsync(t),l=JSON.parse(o);return a.parseSerializedObject(l,r),s||a.build(),a}static ParseFromSnippetAsync(e,t=rp.l.LastCreatedScene,i="",r,s=!1){return"_BLANK"===e?Promise.resolve(nY.CreateDefault("blank",t)):new Promise((n,a)=>{let o=new rS.g;o.addEventListener("readystatechange",()=>{if(4==o.readyState){if(200==o.status){let l=JSON.parse(JSON.parse(o.responseText).jsonPayload),h=JSON.parse(l.nodeMaterial);r||((r=rg.p4.Parse(()=>new nY(e,t),h,t,i)).uniqueId=t.getUniqueId()),r.parseSerializedObject(h),r.snippetId=e;try{s||r.build(),n(r)}catch(e){a(e)}}else a("Unable to load the snippet "+e)}}),o.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),o.send()})}static CreateDefault(e,t){let i=new nY(e,t);return i.setToDefault(),i.build(),i}}function nj(e){let t;let i=e.sideOrientation||sN.x.DEFAULTSIDE,r=e.radius||1,s=void 0===e.flat||e.flat,n=0|(e.subdivisions||4),a=e.radiusX||r,o=e.radiusY||r,l=e.radiusZ||r,h=(1+Math.sqrt(5))/2,u=[-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],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],d=[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],_=138/1024,f=239/1024,m=60/1024,g=26/1024,v=-40/1024,T=20/1024,x=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],S=[],E=[],C=[],b=[],y=0,A=[,,,],R=[,,,];for(t=0;t<3;t++)A[t]=rr.P.Zero(),R[t]=rr.FM.Zero();for(let e=0;e<20;e++){for(t=0;t<3;t++){let i=c[3*e+t];A[t].copyFromFloats(u[3*d[i]],u[3*d[i]+1],u[3*d[i]+2]),A[t].normalize(),R[t].copyFromFloats(p[2*i]*_+m+x[e]*v,p[2*i+1]*f+g+x[e]*T)}let i=(e,t,i,r)=>{let h;let u=rr.P.Lerp(A[0],A[2],t/n),c=rr.P.Lerp(A[1],A[2],t/n),d=n===t?A[2]:rr.P.Lerp(u,c,e/(n-t));if(d.normalize(),s){let e=rr.P.Lerp(A[0],A[2],r/n),t=rr.P.Lerp(A[1],A[2],r/n);h=rr.P.Lerp(e,t,i/(n-r))}else h=new rr.P(d.x,d.y,d.z);h.x/=a,h.y/=o,h.z/=l,h.normalize();let p=rr.FM.Lerp(R[0],R[2],t/n),_=rr.FM.Lerp(R[1],R[2],t/n),f=n===t?R[2]:rr.FM.Lerp(p,_,e/(n-t));E.push(d.x*a,d.y*o,d.z*l),C.push(h.x,h.y,h.z),b.push(f.x,sg.e.UseOpenGLOrientationForUV?1-f.y:f.y),S.push(y),y++};for(let e=0;e<n;e++)for(let t=0;t+e<n;t++)i(t,e,t+1/3,e+1/3),i(t+1,e,t+1/3,e+1/3),i(t,e+1,t+1/3,e+1/3),t+e+1<n&&(i(t+1,e,t+2/3,e+2/3),i(t+1,e+1,t+2/3,e+2/3),i(t,e+1,t+2/3,e+2/3))}sN.x._ComputeSides(i,E,S,C,b,e.frontUVs,e.backUVs);let P=new sN.x;return P.indices=S,P.positions=E,P.normals=C,P.uvs=b,P}function nq(e,t={},i=null){let r=new rq.Kj(e,i);t.sideOrientation=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=nj(t);return s.applyToMesh(r,t.updatable),r}nY._BuildIdGenerator=0,nY.EditorURL=`https://unpkg.com/babylonjs-node-editor@${r7.D.Version}/babylon.nodeEditor.js`,nY.SnippetUrl="https://snippet.babylonjs.com",nY.IgnoreTexturesAtLoadTime=!1,(0,r0.gn)([(0,rg.qC)()],nY.prototype,"ignoreAlpha",void 0),(0,r0.gn)([(0,rg.qC)()],nY.prototype,"maxSimultaneousLights",void 0),(0,r0.gn)([(0,rg.qC)("mode")],nY.prototype,"_mode",void 0),(0,r0.gn)([(0,rg.qC)("comment")],nY.prototype,"comment",void 0),(0,r0.gn)([(0,rg.qC)()],nY.prototype,"forceAlphaBlending",void 0),(0,rn.H)("BABYLON.NodeMaterial",nY),sN.x.CreateIcoSphere=nj,rq.Kj.CreateIcoSphere=(e,t,i)=>nq(e,t,i),(T=tT||(tT={})).WRIST="wrist",T.THUMB="thumb",T.INDEX="index",T.MIDDLE="middle",T.RING="ring",T.LITTLE="little",(x=tx||(tx={})).WRIST="wrist",x.THUMB_METACARPAL="thumb-metacarpal",x.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",x.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",x.THUMB_TIP="thumb-tip",x.INDEX_FINGER_METACARPAL="index-finger-metacarpal",x.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",x.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",x.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",x.INDEX_FINGER_TIP="index-finger-tip",x.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",x.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",x.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",x.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",x.MIDDLE_FINGER_TIP="middle-finger-tip",x.RING_FINGER_METACARPAL="ring-finger-metacarpal",x.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",x.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",x.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",x.RING_FINGER_TIP="ring-finger-tip",x.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",x.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",x.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",x.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",x.PINKY_FINGER_TIP="pinky-finger-tip";let nK=[tx.WRIST,tx.THUMB_METACARPAL,tx.THUMB_PHALANX_PROXIMAL,tx.THUMB_PHALANX_DISTAL,tx.THUMB_TIP,tx.INDEX_FINGER_METACARPAL,tx.INDEX_FINGER_PHALANX_PROXIMAL,tx.INDEX_FINGER_PHALANX_INTERMEDIATE,tx.INDEX_FINGER_PHALANX_DISTAL,tx.INDEX_FINGER_TIP,tx.MIDDLE_FINGER_METACARPAL,tx.MIDDLE_FINGER_PHALANX_PROXIMAL,tx.MIDDLE_FINGER_PHALANX_INTERMEDIATE,tx.MIDDLE_FINGER_PHALANX_DISTAL,tx.MIDDLE_FINGER_TIP,tx.RING_FINGER_METACARPAL,tx.RING_FINGER_PHALANX_PROXIMAL,tx.RING_FINGER_PHALANX_INTERMEDIATE,tx.RING_FINGER_PHALANX_DISTAL,tx.RING_FINGER_TIP,tx.PINKY_FINGER_METACARPAL,tx.PINKY_FINGER_PHALANX_PROXIMAL,tx.PINKY_FINGER_PHALANX_INTERMEDIATE,tx.PINKY_FINGER_PHALANX_DISTAL,tx.PINKY_FINGER_TIP],n$={[tT.WRIST]:[tx.WRIST],[tT.THUMB]:[tx.THUMB_METACARPAL,tx.THUMB_PHALANX_PROXIMAL,tx.THUMB_PHALANX_DISTAL,tx.THUMB_TIP],[tT.INDEX]:[tx.INDEX_FINGER_METACARPAL,tx.INDEX_FINGER_PHALANX_PROXIMAL,tx.INDEX_FINGER_PHALANX_INTERMEDIATE,tx.INDEX_FINGER_PHALANX_DISTAL,tx.INDEX_FINGER_TIP],[tT.MIDDLE]:[tx.MIDDLE_FINGER_METACARPAL,tx.MIDDLE_FINGER_PHALANX_PROXIMAL,tx.MIDDLE_FINGER_PHALANX_INTERMEDIATE,tx.MIDDLE_FINGER_PHALANX_DISTAL,tx.MIDDLE_FINGER_TIP],[tT.RING]:[tx.RING_FINGER_METACARPAL,tx.RING_FINGER_PHALANX_PROXIMAL,tx.RING_FINGER_PHALANX_INTERMEDIATE,tx.RING_FINGER_PHALANX_DISTAL,tx.RING_FINGER_TIP],[tT.LITTLE]:[tx.PINKY_FINGER_METACARPAL,tx.PINKY_FINGER_PHALANX_PROXIMAL,tx.PINKY_FINGER_PHALANX_INTERMEDIATE,tx.PINKY_FINGER_PHALANX_DISTAL,tx.PINKY_FINGER_TIP]};class nQ{get handMesh(){return this._handMesh}getHandPartMeshes(e){return n$[e].map(e=>this._jointMeshes[nK.indexOf(e)])}getJointMesh(e){return this._jointMeshes[nK.indexOf(e)]}constructor(e,t,i,r,s=!1,n=!1,a=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=s,this._jointsInvisible=n,this._jointScaleFactor=a,this._jointTransforms=Array(nK.length),this._jointTransformMatrices=new Float32Array(16*nK.length),this._tempJointMatrix=new rr.y3,this._jointRadii=new Float32Array(nK.length),this._scene=t[0].getScene();for(let e=0;e<this._jointTransforms.length;e++){let i=this._jointTransforms[e]=new rK.Y(nK[e],this._scene);i.rotationQuaternion=new rr._f,t[e].rotationQuaternion=new rr._f}i&&this.setHandMesh(i,r),this.xrController.motionController&&(this.xrController.motionController.rootMesh?this.xrController.motionController.rootMesh.setEnabled(!1):this.xrController.motionController.onModelLoadedObservable.add(e=>{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){let e=this._handMesh.skeleton;nK.forEach((i,r)=>{let s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[r])})}}updateFromXRFrame(e,t){let i=this.xrController.inputSource.hand;if(!i)return;let r=nK.map(e=>i[e]||i.get(e)),s=!1;if(e.fillPoses&&e.fillJointRadii)s=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){s=!0;for(let i=0;i<r.length;i++){let n=e.getJointPose(r[i],t);if(n)this._jointTransformMatrices.set(n.transform.matrix,16*i),this._jointRadii[i]=n.radius||.008;else{s=!1;break}}}s&&(nK.forEach((e,t)=>{let i=this._jointTransforms[t];rr.y3.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);let r=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(r),!this._scene.useRightHandedSystem&&(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}}class nZ extends sV{static _GenerateTrackedJointMeshes(e){let t={};return["left","right"].map(i=>{var r,s,n,a,o;let l=[],h=(null===(r=e.jointMeshes)||void 0===r?void 0:r.sourceMesh)||nq("jointParent",nZ._ICOSPHERE_PARAMS);h.isVisible=!!(null===(s=e.jointMeshes)||void 0===s?void 0:s.keepOriginalVisible);for(let t=0;t<nK.length;++t){let r=h.createInstance(`${i}-handJoint-${t}`);if(null===(n=e.jointMeshes)||void 0===n?void 0:n.onHandJointMeshGenerated){let s=e.jointMeshes.onHandJointMeshGenerated(r,t,i);s&&s!==r&&(r.dispose(),r=s)}if(r.isPickable=!1,null===(a=e.jointMeshes)||void 0===a?void 0:a.enablePhysics){let t=(null===(o=e.jointMeshes)||void 0===o?void 0:o.physicsProps)||{};r.scaling.setAll(.02);let i=void 0!==t.impostorType?t.impostorType:sG.SphereImpostor;r.physicsImpostor=new sG(r,i,Object.assign({mass:0},t))}r.rotationQuaternion=new rr._f,r.isVisible=!1,l.push(r)}t[i]=l}),{left:t.left,right:t.right}}static _GenerateDefaultHandMeshesAsync(e,t){return new Promise(async i=>{var r,s,n,a,o;let l={};(null===(s=null===(r=nZ._RightHandGLB)||void 0===r?void 0:r.meshes[1])||void 0===s?void 0:s.isDisposed())&&(nZ._RightHandGLB=null),(null===(a=null===(n=nZ._LeftHandGLB)||void 0===n?void 0:n.meshes[1])||void 0===a?void 0:a.isDisposed())&&(nZ._LeftHandGLB=null);let h=!!(nZ._RightHandGLB&&nZ._LeftHandGLB),u=await Promise.all([nZ._RightHandGLB||sH.ImportMeshAsync("",nZ.DEFAULT_HAND_MODEL_BASE_URL,nZ.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),nZ._LeftHandGLB||sH.ImportMeshAsync("",nZ.DEFAULT_HAND_MODEL_BASE_URL,nZ.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);nZ._RightHandGLB=u[0],nZ._LeftHandGLB=u[1];let c=new nY("handShader",e,{emitComments:!1});await c.loadAsync(nZ.DEFAULT_HAND_MODEL_SHADER_URL),c.needDepthPrePass=!0,c.transparencyMode=sX.F.MATERIAL_ALPHABLEND,c.alphaMode=2,c.build(!1);let d=Object.assign({base:rs.Wo.FromInts(116,63,203),fresnel:rs.Wo.FromInts(149,102,229),fingerColor:rs.Wo.FromInts(177,130,255),tipFresnel:rs.Wo.FromInts(220,200,255)},null===(o=null==t?void 0:t.handMeshes)||void 0===o?void 0:o.customColors),p={base:c.getBlockByName("baseColor"),fresnel:c.getBlockByName("fresnelColor"),fingerColor:c.getBlockByName("fingerColor"),tipFresnel:c.getBlockByName("tipFresnelColor")};p.base.value=d.base,p.fresnel.value=d.fresnel,p.fingerColor.value=d.fingerColor,p.tipFresnel.value=d.tipFresnel,["left","right"].forEach(t=>{let i="left"==t?nZ._LeftHandGLB:nZ._RightHandGLB;if(!i)throw Error("Could not load hand model");let r=i.meshes[1];r._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,r.material=c.clone(`${t}HandShaderClone`,!0),r.isVisible=!1,l[t]=r,h||e.useRightHandedSystem||i.meshes[1].rotate(rO.RD.Y,Math.PI)}),c.dispose(),i({left:l.left,right:l.right})})}static _GenerateDefaultHandMeshRigMapping(e){let t="right"==e?"R":"L";return{[tx.WRIST]:`wrist_${t}`,[tx.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[tx.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[tx.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[tx.THUMB_TIP]:`thumb_tip_${t}`,[tx.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[tx.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[tx.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[tx.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[tx.INDEX_FINGER_TIP]:`index_tip_${t}`,[tx.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[tx.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[tx.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[tx.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[tx.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[tx.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[tx.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[tx.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[tx.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[tx.RING_FINGER_TIP]:`ring_tip_${t}`,[tx.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[tx.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[tx.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[tx.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[tx.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 ri.y$,this.onHandRemovedObservable=new ri.y$,this._attachHand=e=>{var t,i,r;if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;let s=e.inputSource.handedness,n=new nQ(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===(r=this.options.jointMeshes)||void 0===r?void 0:r.scaleFactor);this._attachedHands[e.uniqueId]=n,this._trackingHands[s]=n,this.onHandAddedObservable.notifyObservers(n)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";let 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||{};let e={},r={};[[i.rigMapping.left,e],[i.rigMapping.right,r]].forEach(e=>{let t=e[0],i=e[1];t.forEach((e,t)=>{i[nK[t]]=e})}),t.handMeshes.customRigMappings={left:e,right:r}}}attach(){var e,t,i,r;return!!super.attach()&&(this._handResources={jointMeshes:nZ._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===(r=this.options.handMeshes)||void 0===r?void 0:r.disableDefaultMeshes)||nZ._GenerateDefaultHandMeshesAsync(rp.l.LastCreatedScene,this.options).then(e=>{var t,i;this._handResources.handMeshes=e,this._handResources.rigMappings={left:nZ._GenerateDefaultHandMeshRigMapping("left"),right:nZ._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;let i=this.getHandByControllerId(e);if(i){let r="left"==i.xrController.inputSource.handedness?"left":"right";(null===(t=this._trackingHands[r])||void 0===t?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[r]=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(),nZ._RightHandGLB=null,nZ._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(e=>e.dispose()),this._handResources.jointMeshes.right.forEach(e=>e.dispose()))}}nZ.Name=sB.HAND_TRACKING,nZ.Version=1,nZ.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",nZ.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",nZ.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",nZ.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",nZ._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},nZ._RightHandGLB=null,nZ._LeftHandGLB=null,sU.AddWebXRFeature(nZ.Name,(e,t)=>()=>new nZ(e,t),nZ.Version,!1),(S=tS||(tS={}))[S.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",S[S.RADIAL_SIDE=1]="RADIAL_SIDE",S[S.ULNAR_SIDE=2]="ULNAR_SIDE",S[S.BELOW_WRIST=3]="BELOW_WRIST",(E=tE||(tE={}))[E.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",E[E.HAND_ROTATION=1]="HAND_ROTATION",(C=tC||(tC={}))[C.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",C[C.PALM_UP=1]="PALM_UP",C[C.GAZE_FOCUS=2]="GAZE_FOCUS",C[C.PALM_AND_GAZE=3]="PALM_AND_GAZE";class nJ{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=rr.P.Zero(),this.poleTargetPosition=rr.P.Zero(),this.poleTargetLocalOffset=rr.P.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=rr._f.Identity(),this._bone1Mat=rr.y3.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=rr.P.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;let r=t.getParent();if(!r){this._notEnoughInformation=!0,ru.Y.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=r,0===this._bone2.children.length&&!this._bone2.length){this._notEnoughInformation=!0,ru.Y.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");return}this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();let 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){let 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);let t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone2Length=rr.P.Distance(t,i),this._bone1Length=rr.P.Distance(i,r)}else{e.computeWorldMatrix(!0);let t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;let i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone1Length=rr.P.Distance(i,r)}this._bone1.getRotationMatrixToRef(rO.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||void 0==e)&&(e=Math.PI),this._maxAngle=e;let 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;let e=this.targetPosition,t=this.poleTargetPosition,i=nJ._TmpMats[0],r=nJ._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&rr.P.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);let s=nJ._TmpVecs[0],n=nJ._TmpVecs[1],a=nJ._TmpVecs[2],o=nJ._TmpVecs[3],l=nJ._TmpVecs[4],h=nJ._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(s,o),o.normalize(),rr.P.CrossToRef(o,l,n),n.normalize(),rr.P.CrossToRef(o,n,a),a.normalize(),rr.y3.FromXYZAxesToRef(a,o,n,i);let u=this._bone1Length,c=this._bone2Length,d=rr.P.Distance(s,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let p=(c*c+d*d-u*u)/(2*c*d),_=(d*d+u*u-c*c)/(2*d*u);p>1&&(p=1),_>1&&(_=1),p<-1&&(p=-1),_<-1&&(_=-1);let f=Math.acos(p),m=Math.acos(_),g=-f-m;if(this._rightHandedSystem)rr.y3.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),rr.y3.RotationAxisToRef(this._bendAxis,m,r),r.multiplyToRef(i,i);else{let e=nJ._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,rr.y3.RotationAxisToRef(e,-m,r),r.multiplyToRef(i,i)}this.poleAngle&&(rr.y3.RotationAxisToRef(o,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||rr._f.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),rr._f.FromRotationMatrixToRef(i,h),rr._f.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,rO.T.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,rO.T.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,rO.T.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new rr._f),e.getRotationQuaternionToRef(rO.T.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}nJ._TmpVecs=[rr.P.Zero(),rr.P.Zero(),rr.P.Zero(),rr.P.Zero(),rr.P.Zero(),rr.P.Zero()],nJ._TmpQuat=rr._f.Identity(),nJ._TmpMats=[rr.y3.Identity(),rr.y3.Identity()];class n0{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=rr.P.Up(),this.upAxisSpace=rO.T.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=rr._f.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=rr.P.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),null!=r.maxYaw?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,null!=r.minYaw?this.minYaw=r.minYaw:this.minYaw=-Math.PI,null!=r.maxPitch?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,null!=r.minPitch?this.minPitch=r.minPitch:this.minPitch=-Math.PI,null!=r.slerpAmount&&(this.slerpAmount=r.slerpAmount),null!=r.upAxis&&(this.upAxis=r.upAxis),null!=r.upAxisSpace&&(this.upAxisSpace=r.upAxisSpace),null!=r.yawAxis||null!=r.pitchAxis){let e=rO.RD.Y,t=rO.RD.X;null!=r.yawAxis&&(e=r.yawAxis.clone()).normalize(),null!=r.pitchAxis&&(t=r.pitchAxis.clone()).normalize();let i=rr.P.Cross(t,e);this._transformYawPitch=rr.y3.Identity(),rr.y3.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==r.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=rO.T.BONE||(this.upAxisSpace=rO.T.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped){this._firstFrameSkipped=!0;return}let e=this.bone,t=n0._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target,r=n0._TmpMats[0],s=n0._TmpMats[1],n=this.mesh,a=e.getParent(),o=n0._TmpVecs[1];o.copyFrom(this.upAxis),this.upAxisSpace==rO.T.BONE&&a?(this._transformYawPitch&&rr.P.TransformCoordinatesToRef(o,this._transformYawPitchInv,o),a.getDirectionToRef(o,this.mesh,o)):this.upAxisSpace==rO.T.LOCAL&&(n.getDirectionToRef(o,o),(1!=n.scaling.x||1!=n.scaling.y||1!=n.scaling.z)&&o.normalize());let l=!1,h=!1;if((this._maxYaw!=Math.PI||this._minYaw!=-Math.PI)&&(l=!0),(this._maxPitch!=Math.PI||this._minPitch!=-Math.PI)&&(h=!0),l||h){let e=n0._TmpMats[2],r=n0._TmpMats[3];if(this.upAxisSpace==rO.T.BONE&&1==o.y&&a)a.getRotationMatrixToRef(rO.T.WORLD,this.mesh,e);else if(this.upAxisSpace!=rO.T.LOCAL||1!=o.y||a){let t=n0._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&rr.P.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),a?a.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);let i=rr.P.Cross(o,t);i.normalize(),t=rr.P.Cross(i,o),rr.y3.FromXYZAxesToRef(i,o,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(r);let s=null;if(h){let n=n0._TmpVecs[3];i.subtractToRef(t,n),rr.P.TransformCoordinatesToRef(n,r,n),s=Math.sqrt(n.x*n.x+n.z*n.z);let a=Math.atan2(n.y,s),o=a;a>this._maxPitch?(n.y=this._maxPitchTan*s,o=this._maxPitch):a<this._minPitch&&(n.y=this._minPitchTan*s,o=this._minPitch),a!=o&&(rr.P.TransformCoordinatesToRef(n,e,n),n.addInPlace(t),i=n)}if(l){let n=n0._TmpVecs[4];i.subtractToRef(t,n),rr.P.TransformCoordinatesToRef(n,r,n);let a=Math.atan2(n.x,n.z),o=this.useAbsoluteValueForYaw?Math.abs(a):a,l=a;if((o>this._maxYaw||o<this._minYaw)&&(null==s&&(s=Math.sqrt(n.x*n.x+n.z*n.z)),this._yawRange>Math.PI?this._isAngleBetween(a,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,l=this._maxYaw):this._isAngleBetween(a,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*s,n.x=this._minYawSin*s,l=this._minYaw):o>this._maxYaw?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,a<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):o<this._minYaw&&(n.z=this._minYawCos*s,n.x=this._minYawSin*s,a<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._minYaw)),this._slerping&&this._yawRange>Math.PI){let e=n0._TmpVecs[8];e.copyFrom(rO.RD.Z),this._transformYawPitch&&rr.P.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);let t=n0._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),rr.P.TransformCoordinatesToRef(e,t,e),rr.P.TransformCoordinatesToRef(e,r,e);let i=Math.atan2(e.x,e.z),o=this._getAngleBetween(i,a),h=this._getAngleBetween(i,this._midYawConstraint);if(o>h){null==s&&(s=Math.sqrt(n.x*n.x+n.z*n.z));let e=this._getAngleBetween(i,this._maxYaw),t=this._getAngleBetween(i,this._minYaw);t<e?(l=i+.75*Math.PI,n.z=Math.cos(l)*s,n.x=Math.sin(l)*s):(l=i-.75*Math.PI,n.z=Math.cos(l)*s,n.x=Math.sin(l)*s)}}a!=l&&(rr.P.TransformCoordinatesToRef(n,e,n),n.addInPlace(t),i=n)}}let u=n0._TmpVecs[5],c=n0._TmpVecs[6],d=n0._TmpVecs[7],p=n0._TmpQuat;i.subtractToRef(t,u),u.normalize(),rr.P.CrossToRef(o,u,c),c.normalize(),rr.P.CrossToRef(u,c,d),d.normalize(),rr.y3.FromXYZAxesToRef(c,d,u,r),(0!==c.x||0!==c.y||0!==c.z)&&(0!==d.x||0!==d.y||0!==d.z)&&(0!==u.x||0!==u.y||0!==u.z)&&((this.adjustYaw||this.adjustPitch||this.adjustRoll)&&(rr.y3.RotationYawPitchRollToRef(this.adjustYaw,this.adjustPitch,this.adjustRoll,s),s.multiplyToRef(r,r)),this.slerpAmount<1?(this._slerping||this.bone.getRotationQuaternionToRef(rO.T.WORLD,this.mesh,this._boneQuat),this._transformYawPitch&&this._transformYawPitch.multiplyToRef(r,r),rr._f.FromRotationMatrixToRef(r,p),rr._f.SlerpToRef(this._boneQuat,p,this.slerpAmount,this._boneQuat),this.bone.setRotationQuaternion(this._boneQuat,rO.T.WORLD,this.mesh),this._slerping=!0):(this._transformYawPitch&&this._transformYawPitch.multiplyToRef(r,r),this.bone.setRotationMatrix(r,rO.T.WORLD,this.mesh),this._slerping=!1),this._updateLinkedTransformRotation())}_getAngleDiff(e,t){let i=t-e;return(i%=2*Math.PI)>Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI;let i=0;return(i=e<(t=t<0?t+2*Math.PI:t)?t-e:e-t)>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,t<(i=i<0?i+2*Math.PI:i)){if(e>t&&e<i)return!0}else if(e>i&&e<t)return!0;return!1}_updateLinkedTransformRotation(){let e=this.bone;e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new rr._f),e.getRotationQuaternionToRef(rO.T.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}n0._TmpVecs=rD.B.BuildArray(10,rr.P.Zero),n0._TmpQuat=rr._f.Identity(),n0._TmpMats=rD.B.BuildArray(5,rr.y3.Identity);class n1{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=[],this._identity=rr.y3.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new ri.y$,this.bones=[],this._scene=i||rp.l.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;let r=this._scene.getEngine().getCaps();this._canUseTextureForBones=r.textureFloat&&r.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){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(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].name===e)return t;return -1}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=new rv(e,t,i);for(let r=0,s=this.bones.length;r<s;r++)this.bones[r].animations[0]&&this.bones[r].animations[0].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,r=this.bones.length;i<r;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}getAnimationRanges(){let e;let t=[];for(e in this._ranges)t.push(this._ranges[e]);return t}copyAnimationRange(e,t,i=!1){let r,s;if(this._ranges[t]||!e.getAnimationRange(t))return!1;let n=!0,a=this._getHighestAnimationFrame()+1,o={},l=e.bones;for(s=0,r=l.length;s<r;s++)o[l[s].name]=l[s];this.bones.length!==l.length&&(ru.Y.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${l.length}`),n=!1);let h=i&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(s=0,r=this.bones.length;s<r;s++){let e=this.bones[s].name,r=o[e];r?n=n&&this.bones[s].copyAnimationRange(r,t,a,i,h):(ru.Y.Warn("copyAnimationRange: not same rig, missing source bone "+e),n=!1)}let u=e.getAnimationRange(t);return u&&(this._ranges[t]=new rv(t,u.from+a,u.to+a)),n}returnToRest(){for(let e of this.bones)-1!==e._index&&e.returnToRest()}_getHighestAnimationFrame(){let e=0;for(let t=0,i=this.bones.length;t<i;t++)if(this.bones[t].animations[0]){let i=this.bones[t].animations[0].getHighestFrame();e<i&&(e=i)}return e}beginAnimation(e,t,i,r){let s=this.getAnimationRange(e);return s?this._scene.beginAnimation(this,s.from,s.to,t,i,r):null}static MakeAnimationAdditive(e,t=0,i){let r=e.getAnimationRange(i);if(!r)return null;let s=e._scene.getAllAnimatablesByTarget(e),n=null;for(let e=0;e<s.length;e++){let t=s[e];if(t.fromFrame===(null==r?void 0:r.from)&&t.toFrame===(null==r?void 0:r.to)){n=t;break}}let a=e.getAnimatables();for(let e=0;e<a.length;e++){let r=a[e],s=r.animations;if(s)for(let e=0;e<s.length;e++)rE.MakeAnimationAdditive(s[e],t,i)}return n&&(n.isAdditive=!0),e}_markAsDirty(){this._isDirty=!0,this._absoluteTransformIsDirty=!0}_registerMeshWithPoseMatrix(e){this._meshesWithPoseMatrix.push(e)}_unregisterMeshWithPoseMatrix(e){let t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i<this.bones.length;i++){let r=this.bones[i];r._childUpdateId++;let s=r.getParent();if(s?r.getLocalMatrix().multiplyToRef(s.getFinalMatrix(),r.getFinalMatrix()):t?r.getLocalMatrix().multiplyToRef(t,r.getFinalMatrix()):r.getFinalMatrix().copyFrom(r.getLocalMatrix()),-1!==r._index){let t=null===r._index?i:r._index;r.getAbsoluteInverseBindMatrix().multiplyToArray(r.getFinalMatrix(),e,16*t)}}this._identity.copyToArray(e,16*this.bones.length)}prepare(e=!1){if(!e){let e=this.getScene().getRenderId();if(this._currentRenderId===e)return;this._currentRenderId=e}if(this._numBonesWithLinkedTransformNode>0){for(let e of this.bones)if(e._linkedTransformNode){let 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(let e of this._meshesWithPoseMatrix){let t=e.getPoseMatrix(),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){for(let i of(this._synchronizedWithMesh=e,this.bones))if(!i.getParent()){let e=i.getBindMatrix();e.multiplyToRef(t,rr.jp.Matrix[1]),i._updateAbsoluteBindMatrices(rr.jp.Matrix[1])}if(this.isUsingTextureForMatrices){let t=(this.bones.length+1)*4;e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=sb.CreateRGBATexture(e._bonesTransformMatrices,(this.bones.length+1)*4,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=sb.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables}clone(e,t){let i=new n1(e,t||e,this._scene);i.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let e=0;e<this.bones.length;e++){let t=this.bones[e],r=null,s=t.getParent();if(s){let e=this.bones.indexOf(s);r=i.bones[e]}let n=new rN(t.name,i,r,t.getBindMatrix().clone(),t.getRestMatrix().clone());n._index=t._index,t._linkedTransformNode&&n.linkTransformNode(t._linkedTransformNode),r_.j.DeepCopy(t.animations,n.animations)}if(this._ranges)for(let e in i._ranges={},this._ranges){let t=this._ranges[e];t&&(i._ranges[e]=t.clone())}return this._isDirty=!0,i.prepare(!0),i}enableBlending(e=.01){this.bones.forEach(t=>{t.animations.forEach(t=>{t.enableBlending=!0,t.blendingSpeed=e})})}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){let 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;let 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;i<this.bones.length;i++){let r=this.bones[i],s=r.getParent(),n={parentBoneIndex:s?this.bones.indexOf(s):-1,index:r.getIndex(),name:r.name,id:r.id,matrix:r.getBindMatrix().toArray(),rest:r.getRestMatrix().toArray(),linkedTransformNodeId:null===(e=r.getTransformNode())||void 0===e?void 0:e.id};for(let e in t.bones.push(n),r.length&&(n.length=r.length),r.metadata&&(n.metadata=r.metadata),r.animations&&r.animations.length>0&&(n.animation=r.animations[0].serialize()),t.ranges=[],this._ranges){let i=this._ranges[e];if(!i)continue;let r={};r.name=e,r.from=i.from,r.to=i.to,t.ranges.push(r)}}return t}static Parse(e,t){let i;let r=new n1(e.name,e.id,t);for(e.dimensionsAtRest&&(r.dimensionsAtRest=rr.P.FromArray(e.dimensionsAtRest)),r.needInitialSkinMatrix=e.needInitialSkinMatrix,i=0;i<e.bones.length;i++){let t=e.bones[i],s=e.bones[i].index,n=null;t.parentBoneIndex>-1&&(n=r.bones[t.parentBoneIndex]);let a=t.rest?rr.y3.FromArray(t.rest):null,o=new rN(t.name,r,n,rr.y3.FromArray(t.matrix),a,null,s);void 0!==t.id&&null!==t.id&&(o.id=t.id),t.length&&(o.length=t.length),t.metadata&&(o.metadata=t.metadata),t.animation&&o.animations.push(rE.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(r._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(i=0;i<e.ranges.length;i++){let t=e.ranges[i];r.createAnimationRange(t.name,t.from,t.to)}return r}computeAbsoluteMatrices(e=!1){(this._absoluteTransformIsDirty||e)&&(this.bones[0].computeAbsoluteMatrices(),this._absoluteTransformIsDirty=!1)}computeAbsoluteTransforms(e=!1){this.computeAbsoluteMatrices(e)}getPoseMatrix(){let e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){let e=[],t=Array(this.bones.length);for(let i=0;i<this.bones.length;i++)this._sortBones(i,e,t);this.bones=e}_sortBones(e,t,i){if(i[e])return;i[e]=!0;let r=this.bones[e];if(!r)return;void 0===r._index&&(r._index=e);let s=r.getParent();s&&this._sortBones(this.bones.indexOf(s),t,i),t.push(r)}setCurrentPoseAsRest(){this.bones.forEach(e=>{e.setCurrentPoseAsRest()})}}var n2=i(6430);class n3{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(){let 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 n4=i(3184);class n5{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new ri.y$,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=rZ.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==sy.kD.POINTERWHEEL)return;let i=t.event,r=i.deltaMode===n4.G.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,sy.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,r0.gn)([(0,rg.qC)()],n5.prototype,"wheelPrecisionX",void 0),(0,r0.gn)([(0,rg.qC)()],n5.prototype,"wheelPrecisionY",void 0),(0,r0.gn)([(0,rg.qC)()],n5.prototype,"wheelPrecisionZ",void 0);class n6{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=rZ.w1.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement(),r=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{var a,o;let l=n.event,h="touch"===l.pointerType;if(t.isInVRExclusivePointerMode||n.type!==sy.kD.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;let u=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){let e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else if(n.type!==sy.kD.POINTERDOWN&&h&&(null===(a=this._pointA)||void 0===a?void 0:a.pointerId)!==l.pointerId&&(null===(o=this._pointB)||void 0===o?void 0:o.pointerId)!==l.pointerId)return;else if(n.type===sy.kD.POINTERDOWN&&(-1===this._currentActiveButton||h)){try{null==u||u.setPointerCapture(l.pointerId)}catch(e){}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())}else if(n.type===sy.kD.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(n.type===sy.kD.POINTERUP&&(this._currentActiveButton===l.button||h)){try{null==u||u.releasePointerCapture(l.pointerId)}catch(e){}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!==r||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(n.type===sy.kD.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&null===this._pointB){let 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){let e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;let t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,o={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,r,a,s,o),s=o,r=a}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,sy.kD.POINTERDOWN|sy.kD.POINTERUP|sy.kD.POINTERMOVE|sy.kD.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=this.onContextMenu.bind(this),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);let n=this.camera.getScene().getEngine().getHostWindow();n&&rZ.w1.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){let e=this.camera.getScene().getEngine().getHostWindow();e&&rZ.w1.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){let e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,r,s,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}(0,r0.gn)([(0,rg.qC)()],n6.prototype,"buttons",void 0);var n8={};class n7{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){let t=e.getSimpleName();if(this.attached[t]){ru.Y.Warn("camera input of type "+t+" already exists on camera");return}this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault)}remove(e){for(let t in this.attached){let i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(let t in this.attached){let i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){let t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement)for(let t in e=!r4.V.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e,this.attached)this.attached[t].attachControl(e)}detachElement(e=!1){for(let t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){for(let e in this.checkInputs=()=>{},this.attached){let 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){let t={};for(let e in this.attached){let i=this.attached[e],r=rg.p4.Serialize(i);t[i.getClassName()]=r}e.inputsmgr=t}parse(e){let t=e.inputsmgr;if(t)for(let e in this.clear(),t){let i=n8[e];if(i){let r=t[e],s=rg.p4.Parse(()=>new i,r,null);this.add(s)}}else for(let t in this.attached){let i=n8[this.attached[t].getClassName()];if(i){let r=rg.p4.Parse(()=>new i,e,null);this.remove(this.attached[t]),this.add(r)}}}}class n9{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,s=1,n=2,a=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=n9.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=s,this._rightStickAxisX=n,this._rightStickAxisY=a,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(){}}n9.GAMEPAD=0,n9.GENERIC=1,n9.XBOX=2,n9.POSE_ENABLED=3,n9.DUALSHOCK=4;class ae extends n9{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new ri.y$,this.onButtonUpObservable=new ri.y$,this.type=n9.GENERIC,this._buttons=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<this._buttons.length;e++)this._buttons[e]=this._setButtonValue(this.browserGamepad.buttons[e].value,this._buttons[e],e)}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear()}}class at{constructor(){this.gamepadRotationSensibility=80,this.gamepadMoveSensibility=40,this._yAxisScale=1}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){let e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{e.type===n9.POSE_ENABLED||this.gamepad&&e.type!==n9.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(n9.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){let e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){let i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){let i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}let i=this.gamepad.leftStick;if(i&&0!=i.y){let e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}(0,r0.gn)([(0,rg.qC)()],at.prototype,"gamepadRotationSensibility",void 0),(0,r0.gn)([(0,rg.qC)()],at.prototype,"gamepadMoveSensibility",void 0),n8.ArcRotateCameraGamepadInput=at;var ai=i(3968);class ar{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=[]}attachControl(e){e=rZ.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=>{let i=t.event;if(!i.metaKey){if(t.type===ai.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t];-1!==this.keysLeft.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:-1!==this.keysUp.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:-1!==this.keysRight.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:-1!==this.keysDown.indexOf(i)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:-1!==this.keysReset.indexOf(i)&&e.useInputToRestoreState&&e.restoreState()}}}getClassName(){return"ArcRotateCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}}(0,r0.gn)([(0,rg.qC)()],ar.prototype,"keysUp",void 0),(0,r0.gn)([(0,rg.qC)()],ar.prototype,"keysDown",void 0),(0,r0.gn)([(0,rg.qC)()],ar.prototype,"keysLeft",void 0),(0,r0.gn)([(0,rg.qC)()],ar.prototype,"keysRight",void 0),(0,r0.gn)([(0,rg.qC)()],ar.prototype,"keysReset",void 0),(0,r0.gn)([(0,rg.qC)()],ar.prototype,"panningSensibility",void 0),(0,r0.gn)([(0,rg.qC)()],ar.prototype,"zoomingSensibility",void 0),(0,r0.gn)([(0,rg.qC)()],ar.prototype,"useAltToZoom",void 0),(0,r0.gn)([(0,rg.qC)()],ar.prototype,"angularSpeed",void 0),n8.ArcRotateCameraKeyboardMoveInput=ar;class as{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._inertialPanning=rr.P.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let i=.01*e*this.wheelDeltaPercentage*t;return e>0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage)}attachControl(e){e=rZ.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==sy.kD.POINTERWHEEL)return;let i=t.event,r=0,s=i.deltaMode===n4.G.DOM_DELTA_LINE?40:1,n=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if((r=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius))>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+r;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=rm.R.Clamp(e,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else r=n/(40*this.wheelPrecision);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,sy.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;let e=this.camera,t=0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset;t&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){let e=this.camera,t=e.target.subtract(e.position);this._hitPlane=sp.J.FromPositionAndNormal(e.target,t)}_getPosition(){var e;let t=this.camera,i=t.getScene(),r=i.createPickingRay(i.pointerX,i.pointerY,rr.y3.Identity(),t,!1);r.origin.x-=t.targetScreenOffset.x,r.origin.y-=t.targetScreenOffset.y;let s=0;return this._hitPlane&&(s=null!==(e=r.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),r.origin.addInPlace(r.direction.scaleInPlace(s))}_zoomToMouse(e){var t,i;let r=this.camera,s=1-r.inertia;if(r.lowerRadiusLimit){let i=null!==(t=r.lowerRadiusLimit)&&void 0!==t?t:0;r.radius-(r.inertialRadiusOffset+e)/s<i&&(e=(r.radius-i)*s-r.inertialRadiusOffset)}if(r.upperRadiusLimit){let t=null!==(i=r.upperRadiusLimit)&&void 0!==i?i:0;r.radius-(r.inertialRadiusOffset+e)/s>t&&(e=(r.radius-t)*s-r.inertialRadiusOffset)}let n=e/s,a=n/r.radius,o=this._getPosition(),l=rr.jp.Vector3[6];o.subtractToRef(r.target,l),l.scaleInPlace(a),l.scaleInPlace(s),this._inertialPanning.addInPlace(l),r.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)<rL.kn&&(e.x=0),Math.abs(e.y)<rL.kn&&(e.y=0),Math.abs(e.z)<rL.kn&&(e.z=0)}}(0,r0.gn)([(0,rg.qC)()],as.prototype,"wheelPrecision",void 0),(0,r0.gn)([(0,rg.qC)()],as.prototype,"zoomToMouseLocation",void 0),(0,r0.gn)([(0,rg.qC)()],as.prototype,"wheelDeltaPercentage",void 0),n8.ArcRotateCameraMouseWheelInput=as;class an extends n6{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.pinchZoom=!0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this.pinchInwards=!0,this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(0!==this.panningSensibility&&e&&t){let i=t.x-e.x,r=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=r/this.panningSensibility}}_computePinchZoom(e,t){let i=this.camera.radius||an.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,r,s,n){(0!==i||null!==s)&&(0!==r||null!==n)&&(this.multiTouchPanAndZoom?(this._computePinchZoom(i,r),this._computeMultiTouchPanning(s,n)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(r)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,n)):this.multiTouchPanning?this._computeMultiTouchPanning(s,n):this.pinchZoom&&this._computePinchZoom(i,r))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}an.MinimumRadiusForPinch=.001,(0,r0.gn)([(0,rg.qC)()],an.prototype,"buttons",void 0),(0,r0.gn)([(0,rg.qC)()],an.prototype,"angularSensibilityX",void 0),(0,r0.gn)([(0,rg.qC)()],an.prototype,"angularSensibilityY",void 0),(0,r0.gn)([(0,rg.qC)()],an.prototype,"pinchPrecision",void 0),(0,r0.gn)([(0,rg.qC)()],an.prototype,"pinchDeltaPercentage",void 0),(0,r0.gn)([(0,rg.qC)()],an.prototype,"useNaturalPinchZoom",void 0),(0,r0.gn)([(0,rg.qC)()],an.prototype,"pinchZoom",void 0),(0,r0.gn)([(0,rg.qC)()],an.prototype,"panningSensibility",void 0),(0,r0.gn)([(0,rg.qC)()],an.prototype,"multiTouchPanning",void 0),(0,r0.gn)([(0,rg.qC)()],an.prototype,"multiTouchPanAndZoom",void 0),n8.ArcRotateCameraPointersInput=an;class aa extends n7{constructor(e){super(e)}addMouseWheel(){return this.add(new as),this}addPointers(){return this.add(new an),this}addKeyboard(){return this.add(new ar),this}}aa.prototype.addVRDeviceOrientation=function(){return this.add(new ao),this};class ao{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=rZ.w1.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);let 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):rZ.w1.Warn("Permission not granted.")}).catch(e=>{rZ.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"}}n8.ArcRotateCameraVRDeviceOrientationInput=ao;class al{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=[]}attachControl(e){e=rZ.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=>{let i=t.event;if(t.type===ai.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=e._computeLocalCameraSpeed();-1!==this.keysForward.indexOf(i)?e._localDirection.copyFromFloats(0,0,r):-1!==this.keysBackward.indexOf(i)?e._localDirection.copyFromFloats(0,0,-r):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,r,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,-r,0):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(r,0,0):-1!==this.keysLeft.indexOf(i)&&e._localDirection.copyFromFloats(-r,0,0),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),rr.P.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}}(0,r0.gn)([(0,rg.qC)()],al.prototype,"keysForward",void 0),(0,r0.gn)([(0,rg.qC)()],al.prototype,"keysBackward",void 0),(0,r0.gn)([(0,rg.qC)()],al.prototype,"keysUp",void 0),(0,r0.gn)([(0,rg.qC)()],al.prototype,"keysDown",void 0),(0,r0.gn)([(0,rg.qC)()],al.prototype,"keysRight",void 0),(0,r0.gn)([(0,rg.qC)()],al.prototype,"keysLeft",void 0),n8.FlyCameraKeyboardInput=al;class ah{constructor(){this.buttons=[0,1,2],this.buttonsYaw=[-1,0,1],this.buttonsPitch=[-1,0,1],this.buttonsRoll=[2],this.activeButton=-1,this.angularSensibility=1e3,this._previousPosition=null}attachControl(e){e=rZ.w1.BackCompatCameraNoPreventDefault(arguments),this._noPreventDefault=e,this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(e=>{this._pointerInput(e)},sy.kD.POINTERDOWN|sy.kD.POINTERUP|sy.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){let t=e.event,i=this.camera,r=i.getEngine();if(r.isInVRExclusivePointerMode||!this.touchEnabled&&"touch"===t.pointerType||e.type!==sy.kD.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;let s=t.target;if(e.type===sy.kD.POINTERDOWN){try{null==s||s.setPointerCapture(t.pointerId)}catch(e){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),r.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===sy.kD.POINTERUP){try{null==s||s.releasePointerCapture(t.pointerId)}catch(e){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===sy.kD.POINTERMOVE){if(!this._previousPosition){r.isPointerLock&&this._onMouseMove(e.event);return}let i=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(i,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){let t=this.camera,i=t.getEngine();if(!i.isPointerLock||i.isInVRExclusivePointerMode)return;let r=e.movementX,s=e.movementY;this._rotateCamera(r,s),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){let i;let r=this.camera,s=this.camera.getScene();s.useRightHandedSystem&&(e*=-1),r.parent&&0>r.parent._getWorldMatrixDeterminant()&&(e*=-1);let n=e/this.angularSensibility,a=t/this.angularSensibility,o=rr._f.RotationYawPitchRoll(r.rotation.y,r.rotation.x,r.rotation.z);if(this.buttonsPitch.some(e=>e===this.activeButton)&&(i=rr._f.RotationAxis(rO.RD.X,a),o.multiplyInPlace(i)),this.buttonsYaw.some(e=>e===this.activeButton)){i=rr._f.RotationAxis(rO.RD.Y,n),o.multiplyInPlace(i);let e=r.bankedTurnLimit+r._trackRoll;if(r.bankedTurn&&-e<r.rotation.z&&r.rotation.z<e){let e=-(r.bankedTurnMultiplier*n);i=rr._f.RotationAxis(rO.RD.Z,e),o.multiplyInPlace(i)}}this.buttonsRoll.some(e=>e===this.activeButton)&&(i=rr._f.RotationAxis(rO.RD.Z,-n),r._trackRoll-=n,o.multiplyInPlace(i)),o.toEulerAnglesToRef(r.rotation)}}(0,r0.gn)([(0,rg.qC)()],ah.prototype,"buttons",void 0),(0,r0.gn)([(0,rg.qC)()],ah.prototype,"angularSensibility",void 0),n8.FlyCameraMouseInput=ah;class au{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=[]}attachControl(e){e=rZ.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=>{let i=t.event;if(!i.metaKey){if(t.type===ai.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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,r0.gn)([(0,rg.qC)()],au.prototype,"keysHeightOffsetIncr",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysHeightOffsetDecr",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysHeightOffsetModifierAlt",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysHeightOffsetModifierCtrl",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysHeightOffsetModifierShift",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysRotationOffsetIncr",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysRotationOffsetDecr",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysRotationOffsetModifierAlt",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysRotationOffsetModifierCtrl",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysRotationOffsetModifierShift",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysRadiusIncr",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysRadiusDecr",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysRadiusModifierAlt",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysRadiusModifierCtrl",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"keysRadiusModifierShift",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"heightSensibility",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"rotationSensibility",void 0),(0,r0.gn)([(0,rg.qC)()],au.prototype,"radiusSensibility",void 0),n8.FollowCameraKeyboardMoveInput=au;class ac{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=rZ.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==sy.kD.POINTERWHEEL)return;let i=t.event,r=0,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?r=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=s*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,sy.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,r0.gn)([(0,rg.qC)()],ac.prototype,"axisControlRadius",void 0),(0,r0.gn)([(0,rg.qC)()],ac.prototype,"axisControlHeight",void 0),(0,r0.gn)([(0,rg.qC)()],ac.prototype,"axisControlRotation",void 0),(0,r0.gn)([(0,rg.qC)()],ac.prototype,"wheelPrecision",void 0),(0,r0.gn)([(0,rg.qC)()],ac.prototype,"wheelDeltaPercentage",void 0),n8.FollowCameraMouseWheelInput=ac;class ad extends n6{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,s,n){if(0===i&&null===s||0===r&&null===n)return;let a=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(a*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=a*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=a*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=a*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=a),this.axisPinchControlHeight&&(this.camera.heightOffset+=a),this.axisPinchControlRadius&&(this.camera.radius-=a))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;let 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,r0.gn)([(0,rg.qC)()],ad.prototype,"angularSensibilityX",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"angularSensibilityY",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"pinchPrecision",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"pinchDeltaPercentage",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"axisXControlRadius",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"axisXControlHeight",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"axisXControlRotation",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"axisYControlRadius",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"axisYControlHeight",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"axisYControlRotation",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"axisPinchControlRadius",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"axisPinchControlHeight",void 0),(0,r0.gn)([(0,rg.qC)()],ad.prototype,"axisPinchControlRotation",void 0),n8.FollowCameraPointersInput=ad;class ap{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=[]}attachControl(e){e=rZ.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=>{let i=t.event;if(!i.metaKey){if(t.type===ai.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)){let t=this._keys.indexOf(i.keyCode);-1===t&&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)){let 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){let e=this.camera;for(let t=0;t<this._keys.length;t++){let i=this._keys[t],r=e._computeLocalCameraSpeed();-1!==this.keysLeft.indexOf(i)?e._localDirection.copyFromFloats(-r,0,0):-1!==this.keysUp.indexOf(i)?e._localDirection.copyFromFloats(0,0,r):-1!==this.keysRight.indexOf(i)?e._localDirection.copyFromFloats(r,0,0):-1!==this.keysDown.indexOf(i)?e._localDirection.copyFromFloats(0,0,-r):-1!==this.keysUpward.indexOf(i)?e._localDirection.copyFromFloats(0,r,0):-1!==this.keysDownward.indexOf(i)?e._localDirection.copyFromFloats(0,-r,0):-1!==this.keysRotateLeft.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):-1!==this.keysRotateRight.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):-1!==this.keysRotateUp.indexOf(i)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):-1!==this.keysRotateDown.indexOf(i)&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),rr.P.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}getClassName(){return"FreeCameraKeyboardMoveInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}_getLocalRotation(){let e=this.rotationSpeed*this._engine.getDeltaTime()/1e3;return this.camera.getScene().useRightHandedSystem&&(e*=-1),this.camera.parent&&0>this.camera.parent._getWorldMatrixDeterminant()&&(e*=-1),e}}(0,r0.gn)([(0,rg.qC)()],ap.prototype,"keysUp",void 0),(0,r0.gn)([(0,rg.qC)()],ap.prototype,"keysUpward",void 0),(0,r0.gn)([(0,rg.qC)()],ap.prototype,"keysDown",void 0),(0,r0.gn)([(0,rg.qC)()],ap.prototype,"keysDownward",void 0),(0,r0.gn)([(0,rg.qC)()],ap.prototype,"keysLeft",void 0),(0,r0.gn)([(0,rg.qC)()],ap.prototype,"keysRight",void 0),(0,r0.gn)([(0,rg.qC)()],ap.prototype,"rotationSpeed",void 0),(0,r0.gn)([(0,rg.qC)()],ap.prototype,"keysRotateLeft",void 0),(0,r0.gn)([(0,rg.qC)()],ap.prototype,"keysRotateRight",void 0),(0,r0.gn)([(0,rg.qC)()],ap.prototype,"keysRotateUp",void 0),(0,r0.gn)([(0,rg.qC)()],ap.prototype,"keysRotateDown",void 0),n8.FreeCameraKeyboardMoveInput=ap;class a_{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new ri.y$,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=rZ.w1.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=r=>{let s=r.event,n="touch"===s.pointerType;if(t.isInVRExclusivePointerMode||!this.touchEnabled&&n||r.type!==sy.kD.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;let a=s.target;if(r.type===sy.kD.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==a||a.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},!e&&(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===sy.kD.POINTERUP){if(n&&this._activePointerId!==s.pointerId||!n&&this._currentActiveButton!==s.button)return;try{null==a||a.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===sy.kD.POINTERMOVE&&(this._activePointerId===s.pointerId||!n)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){let t=s.clientX-this._previousPosition.x,i=s.clientY-this._previousPosition.y;this.camera.getScene().useRightHandedSystem&&(t*=-1),this.camera.parent&&0>this.camera.parent._getWorldMatrixDeterminant()&&(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||t.isInVRExclusivePointerMode)return;let r=i.movementX;this.camera.getScene().useRightHandedSystem&&(r*=-1),this.camera.parent&&0>this.camera.parent._getWorldMatrixDeterminant()&&(r*=-1),this.camera.cameraRotation.y+=r/this.angularSensibility;let 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,sy.kD.POINTERDOWN|sy.kD.POINTERUP|sy.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){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}(0,r0.gn)([(0,rg.qC)()],a_.prototype,"buttons",void 0),(0,r0.gn)([(0,rg.qC)()],a_.prototype,"angularSensibility",void 0),n8.FreeCameraMouseInput=a_,(b=tb||(tb={}))[b.MoveRelative=0]="MoveRelative",b[b.RotateRelative=1]="RotateRelative",b[b.MoveScene=2]="MoveScene";class af extends n5{constructor(){super(...arguments),this._moveRelative=rr.P.Zero(),this._rotateRelative=rr.P.Zero(),this._moveScene=rr.P.Zero(),this._wheelXAction=tb.MoveRelative,this._wheelXActionCoordinate=rO.c7.X,this._wheelYAction=tb.MoveRelative,this._wheelYActionCoordinate=rO.c7.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){(null!==e||this._wheelXAction===tb.MoveRelative)&&(this._wheelXAction=tb.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==tb.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){(null!==e||this._wheelYAction===tb.MoveRelative)&&(this._wheelYAction=tb.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==tb.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){(null!==e||this._wheelZAction===tb.MoveRelative)&&(this._wheelZAction=tb.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==tb.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){(null!==e||this._wheelXAction===tb.RotateRelative)&&(this._wheelXAction=tb.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==tb.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){(null!==e||this._wheelYAction===tb.RotateRelative)&&(this._wheelYAction=tb.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==tb.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){(null!==e||this._wheelZAction===tb.RotateRelative)&&(this._wheelZAction=tb.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==tb.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){(null!==e||this._wheelXAction===tb.MoveScene)&&(this._wheelXAction=tb.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==tb.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){(null!==e||this._wheelYAction===tb.MoveScene)&&(this._wheelYAction=tb.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==tb.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){(null!==e||this._wheelZAction===tb.MoveScene)&&(this._wheelZAction=tb.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==tb.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);let e=rr.y3.Zero();this.camera.getViewMatrix().invertToRef(e);let t=rr.P.Zero();rr.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||null===t||null===i)return;let r=null;switch(t){case tb.MoveRelative:r=this._moveRelative;break;case tb.RotateRelative:r=this._rotateRelative;break;case tb.MoveScene:r=this._moveScene}switch(i){case rO.c7.X:r.set(e,0,0);break;case rO.c7.Y:r.set(0,e,0);break;case rO.c7.Z:r.set(0,0,e)}}}(0,r0.gn)([(0,rg.qC)()],af.prototype,"wheelXMoveRelative",null),(0,r0.gn)([(0,rg.qC)()],af.prototype,"wheelYMoveRelative",null),(0,r0.gn)([(0,rg.qC)()],af.prototype,"wheelZMoveRelative",null),(0,r0.gn)([(0,rg.qC)()],af.prototype,"wheelXRotateRelative",null),(0,r0.gn)([(0,rg.qC)()],af.prototype,"wheelYRotateRelative",null),(0,r0.gn)([(0,rg.qC)()],af.prototype,"wheelZRotateRelative",null),(0,r0.gn)([(0,rg.qC)()],af.prototype,"wheelXMoveScene",null),(0,r0.gn)([(0,rg.qC)()],af.prototype,"wheelYMoveScene",null),(0,r0.gn)([(0,rg.qC)()],af.prototype,"wheelZMoveScene",null),n8.FreeCameraMouseWheelInput=af;class am{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=[],this._isSafari=rZ.w1.IsSafari()}attachControl(e){e=rZ.w1.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{let r=i.event,s="mouse"===r.pointerType||this._isSafari&&void 0===r.pointerType;if(this.allowMouse||!s){if(i.type===sy.kD.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),1!==this._pointerPressed.length)return;t={x:r.clientX,y:r.clientY}}else if(i.type===sy.kD.POINTERUP){e||r.preventDefault();let i=this._pointerPressed.indexOf(r.pointerId);if(-1===i||(this._pointerPressed.splice(i,1),0!=i))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===sy.kD.POINTERMOVE){if(e||r.preventDefault(),!t)return;let i=this._pointerPressed.indexOf(r.pointerId);if(0!=i)return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,sy.kD.POINTERDOWN|sy.kD.POINTERUP|sy.kD.POINTERMOVE),this._onLostFocus){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.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||0===this._offsetX&&0===this._offsetY)return;let e=this.camera;e.cameraRotation.y=this._offsetX/this.touchAngularSensibility;let t=this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1;if(t)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{let t=e._computeLocalCameraSpeed(),i=new rr.P(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);rr.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(rr.P.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}(0,r0.gn)([(0,rg.qC)()],am.prototype,"touchAngularSensibility",void 0),(0,r0.gn)([(0,rg.qC)()],am.prototype,"touchMoveSensibility",void 0),n8.FreeCameraTouchInput=am;class ag extends n7{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new ap),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new a_(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new af,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new am),this}clear(){super.clear(),this._mouseInput=null}}ag.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new av,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class av{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let r=!1,s=()=>{window.removeEventListener("deviceorientation",s),r=!0,t()};e&&setTimeout(()=>{r||(window.removeEventListener("deviceorientation",s),i("WaitForOrientationChangeAsync timed out"))},e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"==e?window.addEventListener("deviceorientation",s):rZ.w1.Warn("Permission not granted.")}).catch(e=>{rZ.w1.Error(e)}):window.addEventListener("deviceorientation",s)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new rr._f,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new ri.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=-rZ.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?rZ.w1.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?rZ.w1.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?rZ.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 rr._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 rr._f),this._camera&&this._camera.onDisposeObservable.add(()=>{this._onDeviceOrientationChangedObservable.clear()})}attachControl(){let e=this.camera.getScene().getEngine().getHostWindow();if(e){let 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():rZ.w1.Warn("Permission not granted.")}).catch(e=>{rZ.w1.Error(e)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(rr._f.RotationYawPitchRollToRef(rZ.w1.ToRadians(this._alpha),rZ.w1.ToRadians(this._beta),-rZ.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"}}n8.FreeCameraDeviceOrientationInput=av;class aT{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=rr.y3.Identity(),this._deltaTransform=rr.P.Zero(),this._vector3=rr.P.Zero(),this._vector2=rr.FM.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){let e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{e.type===n9.POSE_ENABLED||this.gamepad&&e.type!==n9.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(n9.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){let 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):rr.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);let r=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*r,0,-t.y*r),rr.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,r0.gn)([(0,rg.qC)()],aT.prototype,"gamepadAngularSensibility",void 0),(0,r0.gn)([(0,rg.qC)()],aT.prototype,"gamepadMoveSensibility",void 0),n8.FreeCameraGamepadInput=aT;var ax=i(4346);(y=ty||(ty={}))[y.X=0]="X",y[y.Y=1]="Y",y[y.Z=2]="Z";class aS{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;let i=Object.assign(Object.assign({},aS._GetDefaultOptions()),t);if(e?this._leftJoystick=!0:this._leftJoystick=!1,aS._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=ty.X,this._axisTargetedByUpAndDown=ty.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new ax.x,this.deltaPosition=rr.P.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{aS._VJCanvasWidth=window.innerWidth,aS._VJCanvasHeight=window.innerHeight,aS.Canvas&&(aS.Canvas.width=aS._VJCanvasWidth,aS.Canvas.height=aS._VJCanvasHeight),aS._HalfWidth=aS._VJCanvasWidth/2},!aS.Canvas){window.addEventListener("resize",this._onResize,!1),aS.Canvas=document.createElement("canvas"),aS._VJCanvasWidth=window.innerWidth,aS._VJCanvasHeight=window.innerHeight,aS.Canvas.width=window.innerWidth,aS.Canvas.height=window.innerHeight,aS.Canvas.style.width="100%",aS.Canvas.style.height="100%",aS.Canvas.style.position="absolute",aS.Canvas.style.backgroundColor="transparent",aS.Canvas.style.top="0px",aS.Canvas.style.left="0px",aS.Canvas.style.zIndex="5",aS.Canvas.style.touchAction="none",aS.Canvas.setAttribute("touch-action","none");let e=aS.Canvas.getContext("2d");if(!e)throw Error("Unable to create canvas for virtual joystick");aS._VJCanvasContext=e,aS._VJCanvasContext.strokeStyle="#ffffff",aS._VJCanvasContext.lineWidth=2,document.body.appendChild(aS.Canvas)}aS._HalfWidth=aS.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&&aS._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new rr.FM(0,0),this._joystickPreviousPointerPos=new rr.FM(0,0),this._joystickPointerStartPos=new rr.FM(0,0),this._deltaJoystickVector=new rr.FM(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},aS.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),aS.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),aS.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),aS.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),aS.Canvas.addEventListener("contextmenu",e=>{e.preventDefault()},!1),requestAnimationFrame(()=>{this._drawVirtualJoystick()})}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){e.preventDefault(),(!0===this._leftJoystick?e.clientX<aS._HalfWidth:e.clientX>aS._HalfWidth)&&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)):aS._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){let t=new rr.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),0<aS._AlwaysVisibleSticks&&(this._leftJoystick?this._joystickPointerPos.x=Math.min(aS._HalfWidth,this._joystickPointerPos.x):this._joystickPointerPos.x=Math.max(aS._HalfWidth,this._joystickPointerPos.x));let t=this.reverseLeftRight?-1:1,i=t*this._deltaJoystickVector.x/this._inversedSensibility;switch(this._axisTargetedByLeftAndRight){case ty.X:this.deltaPosition.x=Math.min(1,Math.max(-1,i));break;case ty.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,i));break;case ty.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,i))}let r=this.reverseUpDown?1:-1,s=r*this._deltaJoystickVector.y/this._inversedSensibility;switch(this._axisTargetedByUpAndDown){case ty.X:this.deltaPosition.x=Math.min(1,Math.max(-1,s));break;case ty.Y:this.deltaPosition.y=Math.min(1,Math.max(-1,s));break;case ty.Z:this.deltaPosition.z=Math.min(1,Math.max(-1,s))}}else{let t=this._touches.get(e.pointerId.toString());t&&(t.x=e.clientX,t.y=e.clientY)}}_onPointerUp(e){if(this._joystickPointerId==e.pointerId)this._clearPreviousDraw(),this._joystickPointerId=-1,this.pressed=!1;else{let t=this._touches.get(e.pointerId.toString());t&&aS._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88)}this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this._touches.remove(e.pointerId.toString())}setJoystickColor(e){this._joystickColor=e}set containerSize(e){this._joystickContainerSize=e,this._clearContainerSize=~~(2.1*this._joystickContainerSize),this._clearContainerSizeOffset=~~(this._clearContainerSize/2)}get containerSize(){return this._joystickContainerSize}set puckSize(e){this._joystickPuckSize=e,this._clearPuckSize=~~(2.1*this._joystickPuckSize),this._clearPuckSizeOffset=~~(this._clearPuckSize/2)}get puckSize(){return this._joystickPuckSize}clearPosition(){this.alwaysVisible=!1,this._joystickPosition=null}set alwaysVisible(e){this._alwaysVisible!==e&&(e&&this._joystickPosition?(aS._AlwaysVisibleSticks++,this._alwaysVisible=!0):(aS._AlwaysVisibleSticks--,this._alwaysVisible=!1))}get alwaysVisible(){return this._alwaysVisible}setPosition(e,t){this._joystickPointerStartPos&&this._clearPreviousDraw(),this._joystickPosition=new rr.FM(e,t)}setActionOnTouch(e){this._action=e}setAxisForLeftRight(e){switch(e){case ty.X:case ty.Y:case ty.Z:this._axisTargetedByLeftAndRight=e;break;default:this._axisTargetedByLeftAndRight=ty.X}}setAxisForUpDown(e){switch(e){case ty.X:case ty.Y:case ty.Z:this._axisTargetedByUpAndDown=e;break;default:this._axisTargetedByUpAndDown=ty.Y}}_clearPreviousDraw(){let e=this._joystickPosition||this._joystickPointerStartPos;aS._VJCanvasContext.clearRect(e.x-this._clearContainerSizeOffset,e.y-this._clearContainerSizeOffset,this._clearContainerSize,this._clearContainerSize),aS._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x-this._clearPuckSizeOffset-1,this._joystickPreviousPointerPos.y-this._clearPuckSizeOffset-1,this._clearPuckSize+2,this._clearPuckSize+2)}setContainerImage(e){let t=new Image;t.src=e,t.onload=()=>this._containerImage=t}setPuckImage(e){let t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){let e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?aS._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(aS._VJCanvasContext.beginPath(),aS._VJCanvasContext.strokeStyle=this._joystickColor,aS._VJCanvasContext.lineWidth=2,aS._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),aS._VJCanvasContext.stroke(),aS._VJCanvasContext.closePath(),aS._VJCanvasContext.beginPath(),aS._VJCanvasContext.lineWidth=6,aS._VJCanvasContext.strokeStyle=this._joystickColor,aS._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),aS._VJCanvasContext.stroke(),aS._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?aS._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(aS._VJCanvasContext.beginPath(),aS._VJCanvasContext.strokeStyle=this._joystickColor,aS._VJCanvasContext.lineWidth=2,aS._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),aS._VJCanvasContext.stroke(),aS._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()):(aS._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),aS._VJCanvasContext.beginPath(),aS._VJCanvasContext.fillStyle="white",aS._VJCanvasContext.beginPath(),aS._VJCanvasContext.strokeStyle="red",aS._VJCanvasContext.lineWidth=6,aS._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),aS._VJCanvasContext.stroke(),aS._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){aS.Canvas&&(aS.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),aS.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),aS.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),aS.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(aS.Canvas),aS.Canvas=null),this._released=!0}}aS._GlobalJoystickIndex=0,aS._AlwaysVisibleSticks=0,ag.prototype.addVirtualJoystick=function(){return this.add(new aE),this};class aE{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){let e=this.camera,t=50*e._computeLocalCameraSpeed(),i=rr.y3.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=rr.P.TransformCoordinates(new rr.P(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new aS(!0),this._leftjoystick.setAxisForUpDown(ty.Z),this._leftjoystick.setAxisForLeftRight(ty.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new aS(!1),this._rightjoystick.setAxisForUpDown(ty.X),this._rightjoystick.setAxisForLeftRight(ty.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"}}n8.FreeCameraVirtualJoystickInput=aE;class aC extends r4.V{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=rr.P.Zero(),this._tmpTargetVector=rr.P.Zero(),this.cameraDirection=new rr.P(0,0,0),this.cameraRotation=new rr.FM(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new rr._f,this.rotation=new rr.P(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=rr.P.Zero(),this._initialFocalDistance=1,this._viewMatrix=rr.y3.Zero(),this._camMatrix=rr.y3.Zero(),this._cameraTransformMatrix=rr.y3.Zero(),this._cameraRotationMatrix=rr.y3.Zero(),this._referencePoint=new rr.P(0,0,1),this._transformedReferencePoint=rr.P.Zero(),this._deferredPositionUpdate=new rr.P,this._deferredRotationQuaternionUpdate=new rr._f,this._deferredRotationUpdate=new rr.P,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=rr.P.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();let 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){let e=this.lockedTarget,t=e.computeWorldMatrix();t.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 rr.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new rr.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new rr._f(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();let 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;let 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(){let 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+=rL.kn),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),rr.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]);let 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&&rr._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){this.parent.getWorldMatrix().invertToRef(rr.jp.Matrix[0]),rr.P.TransformNormalToRef(this.cameraDirection,rr.jp.Matrix[0],rr.jp.Vector3[0]),this._deferredPositionUpdate.addInPlace(rr.jp.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){let e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint&&(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion)){let e=this._deferredRotationUpdate.lengthSquared();e&&(rr._f.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}t&&(Math.abs(this.cameraDirection.x)<this.speed*rL.kn&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<this.speed*rL.kn&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<this.speed*rL.kn&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<this.speed*rL.kn&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<this.speed*rL.kn&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):rr.y3.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return rr.P.TransformNormalToRef(this._defaultUp,this._cameraRotationMatrix,this.upVector),this}_getViewMatrix(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),rr.P.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?rO.RD.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(rr._f.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),rO.RD.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.ignoreParentScaling){if(this.parent){let r=this.parent.getWorldMatrix();rr.P.TransformCoordinatesToRef(e,r,this._globalPosition),rr.P.TransformCoordinatesToRef(t,r,this._tmpTargetVector),rr.P.TransformNormalToRef(i,r,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(i);this.getScene().useRightHandedSystem?rr.y3.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):rr.y3.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix);return}if(this.getScene().useRightHandedSystem?rr.y3.LookAtRHToRef(e,t,i,this._viewMatrix):rr.y3.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){let e=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(e,this._viewMatrix),this._viewMatrix.getTranslationToRef(this._globalPosition),this._viewMatrix.invert(),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e)}createRigCamera(e,t){if(this.cameraRigMode!==r4.V.RIG_MODE_NONE){let t=new aC(e,this.position.clone(),this.getScene());return t.isRigCamera=!0,t.rigParent=this,(this.cameraRigMode===r4.V.RIG_MODE_VR||this.cameraRigMode===r4.V.RIG_MODE_WEBVR)&&(this.rotationQuaternion||(this.rotationQuaternion=new rr._f),t._cameraRigParams={},t.rotationQuaternion=new rr._f),t.mode=this.mode,t.orthoLeft=this.orthoLeft,t.orthoRight=this.orthoRight,t.orthoTop=this.orthoTop,t.orthoBottom=this.orthoBottom,t}return null}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case r4.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case r4.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case r4.V.RIG_MODE_STEREOSCOPIC_INTERLACED:{let i=this.cameraRigMode===r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,r=this.cameraRigMode===r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*r,t);break}case r4.V.RIG_MODE_VR:e.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),t.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),t.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),t.position.copyFrom(this.position)}super._updateRigCameras()}_getRigCamPositionAndTarget(e,t){let i=this.getTarget();i.subtractToRef(this.position,aC._TargetFocalPoint),aC._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);let r=aC._TargetFocalPoint.addInPlace(this.position);rr.y3.TranslationToRef(-r.x,-r.y,-r.z,aC._TargetTransformMatrix),aC._TargetTransformMatrix.multiplyToRef(rr.y3.RotationAxis(t.upVector,e),aC._RigCamTransformMatrix),rr.y3.TranslationToRef(r.x,r.y,r.z,aC._TargetTransformMatrix),aC._RigCamTransformMatrix.multiplyToRef(aC._TargetTransformMatrix,aC._RigCamTransformMatrix),rr.P.TransformCoordinatesToRef(this.position,aC._RigCamTransformMatrix,t.position),t.setTarget(r)}getClassName(){return"TargetCamera"}}aC._RigCamTransformMatrix=new rr.y3,aC._TargetTransformMatrix=new rr.y3,aC._TargetFocalPoint=new rr.P,(0,r0.gn)([(0,rg.hd)()],aC.prototype,"rotation",void 0),(0,r0.gn)([(0,rg.qC)()],aC.prototype,"speed",void 0),(0,r0.gn)([(0,rg.RR)("lockedTargetId")],aC.prototype,"lockedTarget",void 0);class ab extends aC{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){let e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){let t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){let e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){let t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){let e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){let e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){let e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){let e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new rr.P(.5,1,.5),this.ellipsoidOffset=new rr.P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=rr.P.Zero(),this._diffPosition=rr.P.Zero(),this._newPosition=rr.P.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>r7.D.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new ag(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=rZ.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new rr.P(0,0,0),this.cameraRotation=new rr.FM(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?rr.P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=rr.P.Zero(),this._transformedDirection=rr.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,r0.gn)([(0,rg.hd)()],ab.prototype,"ellipsoid",void 0),(0,r0.gn)([(0,rg.hd)()],ab.prototype,"ellipsoidOffset",void 0),(0,r0.gn)([(0,rg.qC)()],ab.prototype,"checkCollisions",void 0),(0,r0.gn)([(0,rg.qC)()],ab.prototype,"applyGravity",void 0),rT.N.AddNodeConstructor("TouchCamera",(e,t)=>()=>new ay(e,rr.P.Zero(),t));class ay extends ab{get touchAngularSensibility(){let e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){let e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){let 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(){let e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}rT.N.AddNodeConstructor("ArcRotateCamera",(e,t)=>()=>new aA(e,0,0,1,rr.P.Zero(),t));class aA extends aC{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 rr.y3,this._upToYMatrix=new rr.y3,this._upVector=rr.P.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){rr.y3.RotationAlignToRef(rr.P.UpReadOnly,this._upVector,this._yToUpMatrix),rr.y3.RotationAlignToRef(this._upVector,rr.P.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){let e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){let t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){let e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){let t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){let e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){let t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){let e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){let t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){let e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){let e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){let t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){let e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){let 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 sR,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 sP,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 sA,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,n,a=!0){super(e,rr.P.Zero(),n,a),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=rr.P.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=rr.FM.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new rr.y3,this.panningAxis=new rr.P(1,1,0),this._transformedDirection=new rr.P,this.mapPanning=!1,this.onMeshTargetChangedObservable=new ri.y$,this.checkCollisions=!1,this.collisionRadius=new rr.P(.5,.5,.5),this._previousPosition=rr.P.Zero(),this._collisionVelocity=rr.P.Zero(),this._newPosition=rr.P.Zero(),this._computationVector=rr.P.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);let r=Math.cos(this.alpha),s=Math.sin(this.alpha),n=Math.cos(this.beta),a=Math.sin(this.beta);0===a&&(a=1e-4);let o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*r*a,this.radius*n,this.radius*s*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=(l=l.clone()).negate()),this._computeViewMatrix(this._position,o,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=rr.P.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new aa(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new rr.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=rr.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){let e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}let 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,r=2){let s=arguments;t=rZ.w1.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){let e=this.invertRotation?-1:1,t=this.inertialAlphaOffset;this.beta<=0&&(t*=-1),this.getScene().useRightHandedSystem&&(t*=-1),this.parent&&0>this.parent._getWorldMatrixDeterminant()&&(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)<rL.kn&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<rL.kn&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*rL.kn&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){let e=new rr.P(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.multiplyInPlace(this.panningAxis),rr.P.TransformNormalToRef(e,this._cameraTransformMatrix,this._transformedDirection),(this.mapPanning||!this.panningAxis.y)&&(this._transformedDirection.y=0),!this._targetHost){if(this.panningDistanceLimit){this._transformedDirection.addInPlace(this._target);let e=rr.P.DistanceSquared(this._transformedDirection,this.panningOriginTarget);e<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)}else this._target.addInPlace(this._transformedDirection)}this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<this.speed*rL.kn&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<this.speed*rL.kn&&(this.inertialPanningY=0)}this._checkLimits(),super._checkInputs()}}_checkLimits(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),null!==this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(0!==this._upVector.x||1!==this._upVector.y||0!==this._upVector.z)&&rr.P.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);let 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);let t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,r=!1){var s;if(r=null!==(s=this.overrideCloneAlphaBetaRadius)&&void 0!==s?s:r,e.getBoundingInfo)t?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{let t=this._getTargetPosition();if(t&&!i&&t.equals(e))return;this._targetHost=null,this._target=e,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){let e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);0===r&&(r=1e-4),0===this.radius&&(this.radius=1e-4);let s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(0!==this._upVector.x||1!==this._upVector.y||0!==this._upVector.z)&&rr.P.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){let e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&r<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;let i=rq.Kj.MinMax(e),r=rr.P.Distance(i.min,i.max);this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(void 0===e.min){let t=e||this.getScene().meshes;i=rq.Kj.MinMax(t),r=rr.P.Distance(i.min,i.max)}else i=e,r=e.distance;this._target=rq.Kj.Center(i),t||(this.maxZ=2*r)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case r4.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case r4.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case r4.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case r4.V.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}let r=new aA(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case r4.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case r4.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case r4.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case r4.V.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case r4.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,r0.gn)([(0,rg.qC)()],aA.prototype,"alpha",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"beta",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"radius",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"overrideCloneAlphaBetaRadius",void 0),(0,r0.gn)([(0,rg.hd)("target")],aA.prototype,"_target",void 0),(0,r0.gn)([(0,rg.RR)("targetHost")],aA.prototype,"_targetHost",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"inertialAlphaOffset",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"inertialBetaOffset",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"inertialRadiusOffset",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"lowerAlphaLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"upperAlphaLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"lowerBetaLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"upperBetaLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"lowerRadiusLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"upperRadiusLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"inertialPanningX",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"inertialPanningY",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"pinchToPanMaxDistance",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"panningDistanceLimit",void 0),(0,r0.gn)([(0,rg.hd)()],aA.prototype,"panningOriginTarget",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"panningInertia",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"zoomToMouseLocation",null),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"zoomOnFactor",void 0),(0,r0.gn)([(0,rg.QC)()],aA.prototype,"targetScreenOffset",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"allowUpsideDown",void 0),(0,r0.gn)([(0,rg.qC)()],aA.prototype,"useInputToRestoreState",void 0),rT.N.AddNodeConstructor("DeviceOrientationCamera",(e,t)=>()=>new aR(e,rr.P.Zero(),t));class aR extends ab{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new rr._f,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new rr._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 rr._f),rr._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=rO.RD.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new rr._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 aP extends n7{constructor(e){super(e)}addKeyboard(){return this.add(new al),this}addMouse(){return this.add(new ah),this}}class aI extends aC{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){let e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){let t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){let e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){let t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new rr.P(1,1,1),this.ellipsoidOffset=new rr.P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=rr.P.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=rr.P.Zero(),this._diffPosition=rr.P.Zero(),this._newPosition=rr.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()>r7.D.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new aP(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=rZ.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new rr.P(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?rr.P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=rr.P.Zero(),this._transformedDirection=rr.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){let t=this._trackRoll,i=this.rotation.z,r=t-i;Math.abs(r)>=.001&&(this.rotation.z+=r/e,.001>=Math.abs(t-this.rotation.z)&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}(0,r0.gn)([(0,rg.hd)()],aI.prototype,"ellipsoid",void 0),(0,r0.gn)([(0,rg.hd)()],aI.prototype,"ellipsoidOffset",void 0),(0,r0.gn)([(0,rg.qC)()],aI.prototype,"checkCollisions",void 0),(0,r0.gn)([(0,rg.qC)()],aI.prototype,"applyGravity",void 0);class aM extends n7{constructor(e){super(e)}addKeyboard(){return this.add(new au),this}addMouseWheel(){return this.add(new ac),this}addPointers(){return this.add(new ad),this}addVRDeviceOrientation(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}rT.N.AddNodeConstructor("FollowCamera",(e,t)=>()=>new aD(e,rr.P.Zero(),t)),rT.N.AddNodeConstructor("ArcFollowCamera",(e,t)=>()=>new aO(e,0,0,1,null,t));class aD extends aC{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new aM(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;let t=rr.jp.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);let i=Math.atan2(t.m[8],t.m[10]),r=rZ.w1.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),n=s.x+Math.sin(r)*this.radius,a=s.z+Math.cos(r)*this.radius,o=n-this.position.x,l=s.y+this.heightOffset-this.position.y,h=a-this.position.z,u=o*this.cameraAcceleration*2,c=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new rr.P(this.position.x+u,this.position.y+c,this.position.z+d),this.setTarget(s)}attachControl(e,t){t=rZ.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.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffset<this.lowerHeightOffsetLimit&&(this.heightOffset=this.lowerHeightOffsetLimit),null!==this.upperHeightOffsetLimit&&this.heightOffset>this.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffset<this.lowerRotationOffsetLimit&&(this.rotationOffset=this.lowerRotationOffsetLimit),null!==this.upperRotationOffsetLimit&&this.rotationOffset>this.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}(0,r0.gn)([(0,rg.qC)()],aD.prototype,"radius",void 0),(0,r0.gn)([(0,rg.qC)()],aD.prototype,"lowerRadiusLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aD.prototype,"upperRadiusLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aD.prototype,"rotationOffset",void 0),(0,r0.gn)([(0,rg.qC)()],aD.prototype,"lowerRotationOffsetLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aD.prototype,"upperRotationOffsetLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aD.prototype,"heightOffset",void 0),(0,r0.gn)([(0,rg.qC)()],aD.prototype,"lowerHeightOffsetLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aD.prototype,"upperHeightOffsetLimit",void 0),(0,r0.gn)([(0,rg.qC)()],aD.prototype,"cameraAcceleration",void 0),(0,r0.gn)([(0,rg.qC)()],aD.prototype,"maxCameraSpeed",void 0),(0,r0.gn)([(0,rg.RR)("lockedTargetId")],aD.prototype,"lockedTarget",void 0);class aO extends aC{constructor(e,t,i,r,s,n){super(e,rr.P.Zero(),n),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=rr.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);let e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}(A=tA||(tA={}))[A.VIVE=0]="VIVE",A[A.OCULUS=1]="OCULUS",A[A.WINDOWS=2]="WINDOWS",A[A.GEAR_VR=3]="GEAR_VR",A[A.DAYDREAM=4]="DAYDREAM",A[A.GENERIC=5]="GENERIC";class aN{static InitiateController(e){for(let 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."}}aN._ControllerFactories=[],aN._DefaultControllerFactory=null;class aF extends n9{_disableTrackPosition(e){this._trackPosition&&(this._calculatedPosition.copyFrom(e),this._trackPosition=!1)}constructor(e){super(e.id,e.index,e),this.isXR=!1,this._deviceRoomPosition=rr.P.Zero(),this._deviceRoomRotationQuaternion=new rr._f,this.devicePosition=rr.P.Zero(),this.deviceRotationQuaternion=new rr._f,this.deviceScaleFactor=1,this._trackPosition=!0,this._maxRotationDistFromHeadset=Math.PI/5,this._draggedRoomRotation=0,this._leftHandSystemQuaternion=new rr._f,this._deviceToWorld=rr.y3.Identity(),this._pointingPoseNode=null,this._workingMatrix=rr.y3.Identity(),this._meshAttachedObservable=new ri.y$,this.type=n9.POSE_ENABLED,this.controllerType=tA.GENERIC,this.position=rr.P.Zero(),this.rotationQuaternion=new rr._f,this._calculatedPosition=rr.P.Zero(),this._calculatedRotation=new rr._f,rr._f.RotationYawPitchRollToRef(Math.PI,0,0,this._leftHandSystemQuaternion)}update(){super.update(),this._updatePoseAndMesh()}_updatePoseAndMesh(){if(this.isXR)return;let e=this.browserGamepad.pose;if(this.updateFromDevice(e),!this._trackPosition&&rp.l.LastCreatedScene&&rp.l.LastCreatedScene.activeCamera&&rp.l.LastCreatedScene.activeCamera.devicePosition){let e=rp.l.LastCreatedScene.activeCamera;if(e._computeDevicePosition(),this._deviceToWorld.setTranslation(e.devicePosition),e.deviceRotationQuaternion){e._deviceRoomRotationQuaternion.toEulerAnglesToRef(rr.jp.Vector3[0]);let t=Math.atan2(Math.sin(rr.jp.Vector3[0].y-this._draggedRoomRotation),Math.cos(rr.jp.Vector3[0].y-this._draggedRoomRotation));if(Math.abs(t)>this._maxRotationDistFromHeadset){let e=t-(t<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=e;let i=Math.sin(-e),r=Math.cos(-e);this._calculatedPosition.x=this._calculatedPosition.x*r-this._calculatedPosition.z*i,this._calculatedPosition.z=this._calculatedPosition.x*i+this._calculatedPosition.z*r}}}rr.P.TransformCoordinatesToRef(this._calculatedPosition,this._deviceToWorld,this.devicePosition),this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),rr._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));let 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 rr._f),!this.isXR&&(this._updatePoseAndMesh(),this._pointingPoseNode)){let e=[],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 sD(rr.P.Zero(),new rr.P(0,0,1),e);let t=this._pointingPoseNode?this._pointingPoseNode.getWorldMatrix():this.mesh.getWorldMatrix(),i=t.getTranslation(),r=new rr.P(0,0,-1),s=rr.P.TransformNormal(r,t),n=rr.P.Normalize(s);return new sD(i,n,e)}}aF.POINTING_POSE="POINTING_POSE",(R=tR||(tR={}))[R.A=0]="A",R[R.B=1]="B",R[R.X=2]="X",R[R.Y=3]="Y",R[R.LB=4]="LB",R[R.RB=5]="RB",R[R.Back=8]="Back",R[R.Start=9]="Start",R[R.LeftStick=10]="LeftStick",R[R.RightStick=11]="RightStick",(P=tP||(tP={}))[P.Up=12]="Up",P[P.Down=13]="Down",P[P.Left=14]="Left",P[P.Right=15]="Right";class aL extends n9{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new ri.y$,this.onButtonUpObservable=new ri.y$,this.onPadDownObservable=new ri.y$,this.onPadUpObservable=new ri.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=n9.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,tR.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,tR.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,tR.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,tR.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,tR.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,tR.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,tR.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,tR.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,tR.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,tR.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,tP.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,tP.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,tP.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,tP.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()}}(I=tI||(tI={}))[I.Cross=0]="Cross",I[I.Circle=1]="Circle",I[I.Square=2]="Square",I[I.Triangle=3]="Triangle",I[I.L1=4]="L1",I[I.R1=5]="R1",I[I.Share=8]="Share",I[I.Options=9]="Options",I[I.LeftStick=10]="LeftStick",I[I.RightStick=11]="RightStick",(M=tM||(tM={}))[M.Up=12]="Up",M[M.Down=13]="Down",M[M.Left=14]="Left",M[M.Right=15]="Right";class aw extends n9{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 ri.y$,this.onButtonUpObservable=new ri.y$,this.onPadDownObservable=new ri.y$,this.onPadUpObservable=new ri.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=n9.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,tI.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,tI.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,tI.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,tI.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,tI.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,tI.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,tI.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,tI.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,tI.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,tI.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,tM.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,tM.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,tM.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,tM.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 aB{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new ri.y$,(0,r9.CG)()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new ri.y$(e=>{for(let t in this._babylonGamepads){let i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}}),this._onGamepadConnectedEvent=e=>{let t;let i=e.gamepad;i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected||(this._babylonGamepads[i.index]?((t=this._babylonGamepads[i.index]).browserGamepad=i,t._isConnected=!0):t=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(t),this._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=e=>{let t=e.gamepad;for(let e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){let t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport){if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){let 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=n9.XBOX){for(let 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);let i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),r=-1!==e.id.search("Xbox One");return t=r||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new aL(e.id,e.index,e,r):i?new aw(e.id,e.index,e):e.pose?aN.InitiateController(e):new ae(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){for(let e in this._updateGamepadObjects(),this._babylonGamepads){let t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch(e){-1===this._loggedErrors.indexOf(t.index)&&(rZ.w1.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&r7.D.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){let e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t<e.length;t++){let i=e[t];if(i){if(this._babylonGamepads[i.index])this._babylonGamepads[t].browserGamepad=i,this._babylonGamepads[t].isConnected||(this._babylonGamepads[t]._isConnected=!0,this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[t]));else{let e=this._addNewGamepad(i);this.onGamepadConnectedObservable.notifyObservers(e)}}}}}Object.defineProperty(rI.x.prototype,"gamepadManager",{get:function(){if(!this._gamepadManager){this._gamepadManager=new aB(this);let e=this._getComponent(ss.l.NAME_GAMEPAD);e||(e=new aU(this),this._addComponent(e))}return this._gamepadManager},enumerable:!0,configurable:!0}),ag.prototype.addGamepad=function(){return this.add(new aT),this},aa.prototype.addGamepad=function(){return this.add(new at),this};class aU{constructor(e){this.name=ss.l.NAME_GAMEPAD,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(ss.l.STEP_BEFORECAMERAUPDATE_GAMEPAD,this,this._beforeCameraUpdate)}rebuild(){}dispose(){let e=this.scene._gamepadManager;e&&(e.dispose(),this.scene._gamepadManager=null)}_beforeCameraUpdate(){let e=this.scene._gamepadManager;e&&e._isMonitoring&&e._checkGamepadsStatus()}}rT.N.AddNodeConstructor("FreeCamera",(e,t)=>()=>new aV(e,rr.P.Zero(),t));class aV extends ay{get gamepadAngularSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}r4.V._CreateDefaultParsedCamera=(e,t)=>new aV(e,rr.P.Zero(),t),rT.N.AddNodeConstructor("GamepadCamera",(e,t)=>()=>new ak(e,rr.P.Zero(),t));class ak extends aV{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}let aG=`varying vec2 vUV;uniform samplerCube textureSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 uv=vUV*2.0-1.0; -#ifdef POSITIVEX -gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); -#endif -#ifdef NEGATIVEX -gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); -#endif -#ifdef POSITIVEY -gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); -#endif -#ifdef NEGATIVEY -gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); -#endif -#ifdef POSITIVEZ -gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); -#endif -#ifdef NEGATIVEZ -gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); -#endif -}`;no.v.ShadersStore.passCubePixelShader=aG;class az extends np{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,n,a=0,o=!1){super(e,"pass",null,null,t,i,r,s,n,void 0,a,void 0,null,o)}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new az(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}}(0,rn.H)("BABYLON.PassPostProcess",az),r7.D._RescalePostProcessFactory=e=>new az("rescale",1,null,2,e,!1,0);let aW=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`;no.v.ShadersStore.anaglyphPixelShader=aW;class aH extends np{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,s,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,s,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)})}}function aX(e){e._rigCameras[0]._rigPostProcess=new az(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new aH(e.name+"_anaglyph",1,e._rigCameras)}(0,rn.H)("BABYLON.AnaglyphPostProcess",aH),rT.N.AddNodeConstructor("AnaglyphArcRotateCamera",(e,t,i)=>()=>new aY(e,0,0,1,rr.P.Zero(),i.interaxial_distance,t));class aY extends aA{constructor(e,t,i,r,s,n,a){super(e,t,i,r,s,a),this._setRigMode=aX.bind(null,this),this.interaxialDistance=n,this.setCameraRigMode(r4.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}rT.N.AddNodeConstructor("AnaglyphFreeCamera",(e,t,i)=>()=>new aj(e,rr.P.Zero(),i.interaxial_distance,t));class aj extends ab{constructor(e,t,i,r){super(e,t,r),this._setRigMode=aX.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(r4.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}rT.N.AddNodeConstructor("AnaglyphGamepadCamera",(e,t,i)=>()=>new aq(e,rr.P.Zero(),i.interaxial_distance,t));class aq extends ak{constructor(e,t,i,r){super(e,t,r),this._setRigMode=aX.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(r4.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}rT.N.AddNodeConstructor("AnaglyphUniversalCamera",(e,t,i)=>()=>new aK(e,rr.P.Zero(),i.interaxial_distance,t));class aK extends aV{constructor(e,t,i,r){super(e,t,r),this._setRigMode=aX.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(r4.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}let a$=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; -#ifdef IS_STEREOSCOPIC_HORIZ -useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); -#else -#ifdef IS_STEREOSCOPIC_INTERLACED -float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); -#else -useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); -#endif -#endif -if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} -gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} -`;no.v.ShadersStore.stereoscopicInterlacePixelShader=a$;class aQ extends np{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,s,n,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,n,a,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new rr.FM(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new rr.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 aZ(e){let t=e.cameraRigMode===r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,r=e.cameraRigMode===r4.V.RIG_MODE_STEREOSCOPIC_INTERLACED;r?(e._rigCameras[0]._rigPostProcess=new az(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new aQ(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new s6.l(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new s6.l(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}rT.N.AddNodeConstructor("StereoscopicArcRotateCamera",(e,t,i)=>()=>new aJ(e,0,0,1,rr.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class aJ extends aA{constructor(e,t,i,r,s,n,a,o){super(e,t,i,r,s,o),this._setRigMode=aZ.bind(null,this),this.interaxialDistance=n,this.isStereoscopicSideBySide=a,this.setCameraRigMode(a?r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:r4.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}rT.N.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new a0(e,rr.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class a0 extends ab{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=aZ.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:r4.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}rT.N.AddNodeConstructor("StereoscopicGamepadCamera",(e,t,i)=>()=>new a1(e,rr.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class a1 extends ak{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=aZ.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:r4.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}rT.N.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new a2(e,rr.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class a2 extends aV{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=aZ.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?r4.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:r4.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}rT.N.AddNodeConstructor("VirtualJoysticksCamera",(e,t)=>()=>new a3(e,rr.P.Zero(),t));class a3 extends ab{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class a4{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(){let e=this.hScreenSize/4-this.lensSeparationDistance/2,t=4*e/this.hScreenSize;return rr.y3.Translation(t,0,0)}get rightHMatrix(){let e=this.hScreenSize/4-this.lensSeparationDistance/2,t=4*e/this.hScreenSize;return rr.y3.Translation(-t,0,0)}get leftPreViewMatrix(){return rr.y3.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return rr.y3.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){let e=new a4;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}}let a5=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; -float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) -gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;no.v.ShadersStore.vrDistortionCorrectionPixelShader=a5;class a6 extends np{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,sv.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new rr.FM(2,2/this.aspectRatio),this._scaleFactor=new rr.FM(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new rr.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])})}}let a8=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;no.v.ShadersStore.vrMultiviewToSingleviewPixelShader=a8;class a7 extends nV{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 a9(e,t){let i=new r1.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}r7.D.prototype.createMultiviewRenderTargetTexture=function(e,t,i,r){let s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";let n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=s.createFramebuffer();let a=new sT.l(this,sT.S.Unknown,!0);return a.width=e,a.height=t,a.isMultiview=!0,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,e,t,2)),n._colorTextureArray=i,r||(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,r),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=r,a.isReady=!0,n.setTextures(a),n._depthStencilTexture=a,n},r7.D.prototype.bindMultiviewFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"},r7.D.prototype.bindSpaceWarpFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_ATTACHMENT,e._depthStencilTextureArray,0,0,2);else throw Error("Invalid Space Warp framebuffer")},r4.V.prototype._useMultiviewToSingleView=!1,r4.V.prototype._multiviewTexture=null,r4.V.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=e||this._multiviewTexture.getRenderHeight()!=t)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new a7(this.getScene(),{width:e,height:t})):this._multiviewTexture=new a7(this.getScene(),{width:e,height:t})};let oe=rI.x.prototype.createSceneUniformBuffer;rI.x.prototype._transformMatrixR=rr.y3.Zero(),rI.x.prototype._multiviewSceneUbo=null,rI.x.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=a9(this.getEngine(),"scene_multiview")},rI.x.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?a9(this.getEngine(),e):oe.bind(this)(e)},rI.x.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,rr.jp.Matrix[0]),s5.i.GetRightPlaneToRef(rr.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))},rI.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<e._rigCameras.length;t++){let i=this.getEngine();this._activeCamera=e._rigCameras[t],i.setViewport(this._activeCamera.viewport),this.postProcessManager&&(this.postProcessManager._prepareFrame(),this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate))}};class ot extends np{getClassName(){return"VRMultiviewToSingleviewPostProcess"}constructor(e,t,i){super(e,"vrMultiviewToSingleview",["imageIndex"],["multiviewSampler"],i,t,sv.BILINEAR_SAMPLINGMODE);let r=null!=t?t:this.getCamera();this.onSizeChangedObservable.add(()=>{}),this.onApplyObservable.add(e=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",r._multiviewTexture)})}}function oi(e,t){let i=t.vrCameraMetrics||a4.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new s6.l(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new rr.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 s6.l(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new rr.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 ot("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(ru.Y.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new a6("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new a6("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}rT.N.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(e,t)=>()=>new or(e,0,0,1,rr.P.Zero(),t));class or extends aA{constructor(e,t,i,r,s,n,a=!0,o=a4.GetDefault()){super(e,t,i,r,s,n),this._setRigMode=oi.bind(null,this),o.compensateDistortion=a,this.setCameraRigMode(r4.V.RIG_MODE_VR,{vrCameraMetrics:o}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}rT.N.AddNodeConstructor("VRDeviceOrientationFreeCamera",(e,t)=>()=>new os(e,rr.P.Zero(),t));class os extends aR{constructor(e,t,i,r=!0,s=a4.GetDefault()){super(e,t,i),this._setRigMode=oi.bind(null,this),s.compensateDistortion=r,this.setCameraRigMode(r4.V.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}}rT.N.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(e,t)=>()=>new on(e,rr.P.Zero(),t));class on extends os{constructor(e,t,i,r=!0,s=a4.GetDefault()){super(e,t,i,r,s),this._setRigMode=oi.bind(null,this),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}rT.N.AddNodeConstructor("Light_Type_3",(e,t)=>()=>new oa(e,rr.P.Zero(),t));class oa extends r3{constructor(e,t,i){super(e,i),this.groundColor=new rs.Wo(0,0,0),this.direction=t||rr.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=rr.P.Normalize(e.subtract(rr.P.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){let i=rr.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){let i=rr.P.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=rr.y3.Identity()),this._worldMatrix}getTypeID(){return r3.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}function oo(e,t){if(t.vrDisplay){let i=t.vrDisplay.getEyeParameters("left"),r=t.vrDisplay.getEyeParameters("right");e._rigCameras[0].viewport=new s6.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 rr.y3,e._rigCameras[0].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[0].parent=e,e._rigCameras[0]._getViewMatrix=e._getWebVRViewMatrix,e._rigCameras[1].viewport=new s6.l(.5,0,.5,1),e._rigCameras[1].setCameraRigParameter("eyeParameters",r),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 rr.y3,e._rigCameras[1].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[1].parent=e,e._rigCameras[1]._getViewMatrix=e._getWebVRViewMatrix}}(0,r0.gn)([(0,rg.n9)()],oa.prototype,"groundColor",void 0),(0,r0.gn)([(0,rg.hd)()],oa.prototype,"direction",void 0),Object.defineProperty(r7.D.prototype,"isInVRExclusivePointerMode",{get:function(){return this._vrExclusivePointerMode},enumerable:!0,configurable:!0}),r7.D.prototype._prepareVRComponent=function(){this._vrSupported=!1,this._vrExclusivePointerMode=!1,this.onVRDisplayChangedObservable=new ri.y$,this.onVRRequestPresentComplete=new ri.y$,this.onVRRequestPresentStart=new ri.y$},r7.D.prototype.isVRDevicePresent=function(){return!!this._vrDisplay},r7.D.prototype.getVRDevice=function(){return this._vrDisplay},r7.D.prototype.initWebVR=function(){return this.initWebVRAsync(),this.onVRDisplayChangedObservable},r7.D.prototype.initWebVRAsync=function(){let e=()=>{let 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=r7.D.QueueNewFrame(this._boundRenderFunction),e()},this._onVrDisplayPresentChange=()=>{this._vrExclusivePointerMode=this._vrDisplay&&this._vrDisplay.isPresenting};let 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},r7.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}))})},r7.D.prototype.enableVR=function(e){if(this._vrDisplay&&!this._vrDisplay.isPresenting){this.onVRRequestPresentStart.notifyObservers(this);let t={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:t},t)]).then(()=>{this.onVRRequestPresentComplete.notifyObservers(!0),this._onVRFullScreenTriggered()}).catch(()=>{this.onVRRequestPresentComplete.notifyObservers(!1)})}},r7.D.prototype._onVRFullScreenTriggered=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting){this._oldSize=new rx(this.getRenderWidth(),this.getRenderHeight()),this._oldHardwareScaleFactor=this.getHardwareScalingLevel();let 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)},r7.D.prototype.disableVR=function(){this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.exitPresent().then(()=>this._onVRFullScreenTriggered()).catch(()=>this._onVRFullScreenTriggered()),(0,r9.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))},r7.D.prototype._connectVREvents=function(e,t){if(this._onVRDisplayPointerRestricted=()=>{e&&e.requestPointerLock()},this._onVRDisplayPointerUnrestricted=()=>{if(!t){let e=this.getHostWindow();e.document&&e.document.exitPointerLock&&e.document.exitPointerLock();return}t.exitPointerLock&&t.exitPointerLock()},(0,r9.CG)()){let e=this.getHostWindow();e.addEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted,!1),e.addEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted,!1)}},r7.D.prototype._submitVRFrame=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting)try{this._vrDisplay.submitFrame()}catch(e){rZ.w1.Warn("webVR submitFrame has had an unexpected failure: "+e)}},r7.D.prototype.isVRPresenting=function(){return this._vrDisplay&&this._vrDisplay.isPresenting},r7.D.prototype._requestVRFrame=function(){this._frameHandler=r7.D.QueueNewFrame(this._boundRenderFunction,this._vrDisplay)},rT.N.AddNodeConstructor("WebVRFreeCamera",(e,t)=>()=>new ol(e,rr.P.Zero(),t)),rT.N.AddNodeConstructor("WebVRGamepadCamera",(e,t)=>()=>new ol(e,rr.P.Zero(),t));class ol extends ab{constructor(e,t,i,r={}){super(e,t,i),this._webVROptions=r,this._vrDevice=null,this.rawPose=null,this._specsVersion="1.1",this._attached=!1,this._descendants=[],this._deviceRoomPosition=rr.P.Zero(),this._deviceRoomRotationQuaternion=rr._f.Identity(),this._standingMatrix=null,this.devicePosition=rr.P.Zero(),this.deviceRotationQuaternion=rr._f.Identity(),this.deviceScaleFactor=1,this._deviceToWorld=rr.y3.Identity(),this._worldToDevice=rr.y3.Identity(),this.controllers=[],this.onControllersAttachedObservable=new ri.y$,this.onControllerMeshLoadedObservable=new ri.y$,this.onPoseUpdatedFromDeviceObservable=new ri.y$,this._poseSet=!1,this.rigParenting=!0,this._defaultHeight=void 0,this._setRigMode=oo.bind(null,this),this._detachIfAttached=()=>{let e=this.getEngine().getVRDevice();e&&!e.isPresenting&&this.detachControl()},this._workingVector=rr.P.Zero(),this._oneVector=rr.P.One(),this._workingMatrix=rr.y3.Identity(),this._tmpMatrix=new rr.y3,this._cache.position=rr.P.Zero(),r.defaultHeight&&(this._defaultHeight=r.defaultHeight,this.position.y=this._defaultHeight),this.minZ=.1,5==arguments.length&&(this._webVROptions=arguments[4]),void 0==this._webVROptions.trackPosition&&(this._webVROptions.trackPosition=!0),void 0==this._webVROptions.controllerMeshes&&(this._webVROptions.controllerMeshes=!0),void 0==this._webVROptions.defaultLightingOnControllers&&(this._webVROptions.defaultLightingOnControllers=!0),this.rotationQuaternion=new rr._f,this._webVROptions&&this._webVROptions.positionScale&&(this.deviceScaleFactor=this._webVROptions.positionScale);let 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(r4.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),r.useMultiview&&(this.getScene().getEngine().getCaps().multiview?(this._useMultiviewToSingleView=!0,this._rigPostProcess=new ot("VRMultiviewToSingleview",this,1)):(ru.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=>{let 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 rr.y3,rr.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(let 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=rZ.w1.BackCompatCameraNoPreventDefault(arguments),super.attachControl(e),this._attached=!0,e=!r4.V.ForceAttachControlToAlwaysPreventDefault&&e,this._vrDevice&&this.getEngine().enableVR(this._webVROptions);let 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(){let 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&&(rr.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),rr.P.TransformCoordinatesToRef(this._deviceRoomPosition,this._workingMatrix,this._workingVector),this.devicePosition.subtractToRef(this._workingVector,this._workingVector),rr.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(){rr.P.TransformCoordinatesToRef(this._deviceRoomPosition,this._deviceToWorld,this.devicePosition)}update(){this._computeDevicePosition(),rr.y3.FromQuaternionToRef(this._deviceRoomRotationQuaternion,this._workingMatrix),this._workingMatrix.multiplyToRef(this._deviceToWorld,this._workingMatrix),rr._f.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this._poseSet&&this.onPoseUpdatedFromDeviceObservable.notifyObservers(null),super.update()}_getViewMatrix(){return rr.y3.Identity()}_getWebVRViewMatrix(){let e=this._cameraRigParams.parentCamera;e._updateCache();let t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return rr.y3.FromArrayToRef(t,0,this._webvrViewMatrix),this.getScene().useRightHandedSystem||this._webvrViewMatrix.toggleModelMatrixHandInPlace(),this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix),rr.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||rr.y3.Identity(),this._webvrViewMatrix.invertToRef(this._workingMatrix),this._workingMatrix.multiplyToRef(e.getWorldMatrix(),this._workingMatrix),this._workingMatrix.getTranslationToRef(this._globalPosition),this._markSyncedWithParent(),this._webvrViewMatrix}_getWebVRProjectionMatrix(){let e=this.parent;e._vrDevice.depthNear=e.minZ,e._vrDevice.depthFar=e.maxZ;let t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return rr.y3.FromArrayToRef(t,0,this._projectionMatrix),this.getScene().useRightHandedSystem||this._projectionMatrix.toggleProjectionMatrixHandInPlace(),this._projectionMatrix}initControllers(){this.controllers.length=0;let e=this.getScene().gamepadManager;this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{if(e.type===n9.POSE_ENABLED){e.defaultModel&&e.defaultModel.setEnabled(!1),"right"===e.hand&&(this._rightController=null),"left"===e.hand&&(this._leftController=null);let t=this.controllers.indexOf(e);-1!==t&&this.controllers.splice(t,1)}}),this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{if(e.type===n9.POSE_ENABLED&&(this._webVROptions.trackPosition||(e._disableTrackPosition(new rr.P("left"==e.hand?-.15:.15,-.5,.25)),this._updateCacheWhenTrackingDisabledObserver||(this._updateCacheWhenTrackingDisabledObserver=this._scene.onBeforeRenderObservable.add(()=>{this._updateCache()}))),e.deviceScaleFactor=this.deviceScaleFactor,e._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(e._deviceToWorld),this._webVROptions.controllerMeshes&&(e.defaultModel?e.defaultModel.setEnabled(!0):e.initControllerMesh(this.getScene(),t=>{if(t.scaling.scaleInPlace(this.deviceScaleFactor),this.onControllerMeshLoadedObservable.notifyObservers(e),this._webVROptions.defaultLightingOnControllers){this._lightOnControllers||(this._lightOnControllers=new oa("vrControllersLight",new rr.P(0,1,0),this.getScene()));let e=function(t,i){let r=t.getChildren();r&&0!==r.length&&r.forEach(t=>{i.includedOnlyMeshes.push(t),e(t,i)})};this._lightOnControllers.includedOnlyMeshes.push(t),e(t,this._lightOnControllers)}})),e.attachToPoseControlledCamera(this),-1===this.controllers.indexOf(e))){this.controllers.push(e);let t=!1;for(let e=0;e<this.controllers.length;e++)this.controllers[e].controllerType===tA.VIVE&&(t?this.controllers[e].hand="right":(t=!0,this.controllers[e].hand="left"));this.controllers.length>=2&&this.onControllersAttachedObservable.notifyObservers(this.controllers)}})}}class oh extends aF{onButtonStateChange(e){this._onButtonStateChange=e}get defaultModel(){return this._defaultModel}constructor(e){super(e),this.onTriggerStateChangedObservable=new ri.y$,this.onMainButtonStateChangedObservable=new ri.y$,this.onSecondaryButtonStateChangedObservable=new ri.y$,this.onPadStateChangedObservable=new ri.y$,this.onPadValuesChangedObservable=new ri.y$,this.pad={x:0,y:0},this._changes={pressChanged:!1,touchChanged:!1,valueChanged:!1,changed:!1},this._buttons=Array(e.buttons.length),this.hand=e.hand}update(){super.update();for(let e=0;e<this._buttons.length;e++)this._setButtonValue(this.browserGamepad.buttons[e],this._buttons[e],e);(this.leftStick.x!==this.pad.x||this.leftStick.y!==this.pad.y)&&(this.pad.x=this.leftStick.x,this.pad.y=this.leftStick.y,this.onPadValuesChangedObservable.notifyObservers(this.pad))}_setButtonValue(e,t,i){if(e||(e={pressed:!1,touched:!1,value:0}),!t){this._buttons[i]={pressed:e.pressed,touched:e.touched,value:e.value};return}this._checkChanges(e,t),this._changes.changed&&(this._onButtonStateChange&&this._onButtonStateChange(this.index,i,e),this._handleButtonChange(i,e,this._changes)),this._buttons[i].pressed=e.pressed,this._buttons[i].touched=e.touched,this._buttons[i].value=e.value<1e-8?0:e.value}_checkChanges(e,t){return this._changes.pressChanged=e.pressed!==t.pressed,this._changes.touchChanged=e.touched!==t.touched,this._changes.valueChanged=e.value!==t.value,this._changes.changed=this._changes.pressChanged||this._changes.touchChanged||this._changes.valueChanged,this._changes}dispose(){super.dispose(),this._defaultModel=null,this.onTriggerStateChangedObservable.clear(),this.onMainButtonStateChangedObservable.clear(),this.onSecondaryButtonStateChangedObservable.clear(),this.onPadStateChangedObservable.clear(),this.onPadValuesChangedObservable.clear()}}class ou{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());let s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}}var oc=i(3511);class od{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,r7.D.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,r7.D.MarkAllMaterialsAsDirty(1))}}od._DiffuseTextureEnabled=!0,od._DetailTextureEnabled=!0,od._DecalMapEnabled=!0,od._AmbientTextureEnabled=!0,od._OpacityTextureEnabled=!0,od._ReflectionTextureEnabled=!0,od._EmissiveTextureEnabled=!0,od._SpecularTextureEnabled=!0,od._BumpTextureEnabled=!0,od._LightmapTextureEnabled=!0,od._RefractionTextureEnabled=!0,od._ColorGradingTextureEnabled=!0,od._FresnelEnabled=!0,od._ClearCoatTextureEnabled=!0,od._ClearCoatBumpTextureEnabled=!0,od._ClearCoatTintTextureEnabled=!0,od._SheenTextureEnabled=!0,od._AnisotropicTextureEnabled=!0,od._ThicknessTextureEnabled=!0,od._RefractionIntensityTextureEnabled=!0,od._TranslucencyIntensityTextureEnabled=!0,od._IridescenceTextureEnabled=!0;let op=`#ifdef DECAL -uniform vec4 vDecalInfos; -#endif -`;no.v.IncludesShadersStore.decalFragmentDeclaration=op;let o_=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; -#ifdef SPECULARTERM -uniform vec4 vSpecularColor; -#endif -uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; -#ifdef DIFFUSE -uniform vec2 vDiffuseInfos; -#endif -#ifdef AMBIENT -uniform vec2 vAmbientInfos; -#endif -#ifdef OPACITY -uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#ifdef ALPHATEST -uniform float alphaCutOff; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) -uniform mat4 view; -#endif -#ifdef REFRACTION -uniform vec4 vRefractionInfos; -#ifndef REFRACTIONMAP_3D -uniform mat4 refractionMatrix; -#endif -#ifdef REFRACTIONFRESNEL -uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; -#endif -#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) -uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; -#endif -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) -uniform vec2 vSpecularInfos; -#endif -#ifdef DIFFUSEFRESNEL -uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; -#endif -#ifdef OPACITYFRESNEL -uniform vec4 opacityParts; -#endif -#ifdef EMISSIVEFRESNEL -uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos; -#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) -uniform mat4 reflectionMatrix; -#endif -#ifndef REFLECTIONMAP_SKYBOX -#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -#ifdef REFLECTIONFRESNEL -uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; -#endif -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos; -#endif -#include<decalFragmentDeclaration> -#define ADDITIONAL_FRAGMENT_DECLARATION -`;no.v.IncludesShadersStore.defaultFragmentDeclaration=o_;let of=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; -#ifdef MULTIVIEW -mat4 viewProjectionR; -#endif -mat4 view;mat4 projection;vec4 vEyePosition;}; -`;no.v.IncludesShadersStore.sceneUboDeclaration=of;let om=`#ifdef WEBGL2 -uniform mat4 world;uniform float visibility; -#else -layout(std140,column_major) uniform;uniform Mesh -{mat4 world;float visibility;}; -#endif -#define WORLD_UBO -`;no.v.IncludesShadersStore.meshUboDeclaration=om;let og=`layout(std140,column_major) uniform;uniform Material -{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; -#define ADDITIONAL_UBO_DECLARATION -}; -#include<sceneUboDeclaration> -#include<meshUboDeclaration> -`;no.v.IncludesShadersStore.defaultUboDeclaration=og;let ov=`#ifdef PREPASS -#extension GL_EXT_draw_buffers : require -layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; -#ifdef PREPASS_DEPTH -varying highp vec3 vViewPos; -#endif -#ifdef PREPASS_VELOCITY -varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; -#endif -#endif -`;no.v.IncludesShadersStore.prePassDeclaration=ov;let oT=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY -#extension GL_EXT_draw_buffers : require -layout(location=0) out vec2 depth; -layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; -#define MAX_DEPTH 99999.0 -highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; -#endif -`;no.v.IncludesShadersStore.oitDeclaration=oT;let ox=`#ifdef MAINUV{X} -varying vec2 vMainUV{X}; -#endif -`;no.v.IncludesShadersStore.mainUVVaryingDeclaration=ox;let oS=`const float PI=3.1415926535897932384626433832795;const float HALF_MIN=5.96046448e-08; -const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; -#define saturate(x) clamp(x,0.0,1.0) -#define absEps(x) abs(x)+Epsilon -#define maxEps(x) max(x,Epsilon) -#define saturateEps(x) clamp(x,Epsilon,1.0) -mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( -vec3(i0.x,i1.x,i2.x), -vec3(i0.y,i1.y,i2.y), -vec3(i0.z,i1.z,i2.z) -);return outMatrix;} -mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), -b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), -b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} -#if USE_EXACT_SRGB_CONVERSIONS -vec3 toLinearSpaceExact(vec3 color) -{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); -#else -return -vec3( -color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, -color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, -color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); -#endif -} -vec3 toGammaSpaceExact(vec3 color) -{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); -#else -return -vec3( -color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, -color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, -color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); -#endif -} -#endif -float toLinearSpace(float color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; -#else -return pow(color,LinearEncodePowerApprox); -#endif -} -vec3 toLinearSpace(vec3 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return toLinearSpaceExact(color); -#else -return pow(color,vec3(LinearEncodePowerApprox)); -#endif -} -vec4 toLinearSpace(vec4 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return vec4(toLinearSpaceExact(color.rgb),color.a); -#else -return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); -#endif -} -float toGammaSpace(float color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; -#else -return pow(color,GammaEncodePowerApprox); -#endif -} -vec3 toGammaSpace(vec3 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return toGammaSpaceExact(color); -#else -return pow(color,vec3(GammaEncodePowerApprox)); -#endif -} -vec4 toGammaSpace(vec4 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return vec4(toGammaSpaceExact(color.rgb),color.a); -#else -return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); -#endif -} -float square(float value) -{return value*value;} -vec3 square(vec3 value) -{return value*value;} -float pow5(float value) {float sq=value*value;return sq*sq*value;} -float getLuminance(vec3 color) -{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} -float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} -float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} -const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); } -vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} -vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} -`;no.v.IncludesShadersStore.helperFunctions=oS;let oE=`#ifdef LIGHT{X} -uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; -#ifdef SPECULARTERM -uniform vec4 vLightSpecular{X}; -#else -vec4 vLightSpecular{X}=vec4(0.); -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DArrayShadow shadowSampler{X}; -#else -uniform highp sampler2DArray shadowSampler{X}; -#endif -#ifdef SHADOWCSMDEBUG{X} -const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] -( -vec3 ( 1.5,0.0,0.0 ), -vec3 ( 0.0,1.5,0.0 ), -vec3 ( 0.0,0.0,5.5 ), -vec3 ( 1.5,0.0,5.5 ), -vec3 ( 1.5,1.5,0.0 ), -vec3 ( 1.0,1.0,1.0 ), -vec3 ( 0.0,1.0,5.5 ), -vec3 ( 0.5,3.5,0.75 ) -);vec3 shadowDebug{X}; -#endif -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -int index{X}=-1; -#else -int index{X}=SHADOWCSMNUM_CASCADES{X}-1; -#endif -float diff{X}=0.; -#elif defined(SHADOWCUBE{X}) -uniform samplerCube shadowSampler{X}; -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DShadow shadowSampler{X}; -#else -uniform sampler2D shadowSampler{X}; -#endif -uniform mat4 lightMatrix{X}; -#endif -uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; -#endif -#ifdef SPOTLIGHT{X} -uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; -#elif defined(POINTLIGHT{X}) -uniform vec4 vLightFalloff{X}; -#elif defined(HEMILIGHT{X}) -uniform vec3 vLightGround{X}; -#endif -#ifdef PROJECTEDLIGHTTEXTURE{X} -uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; -#endif -#endif -`;no.v.IncludesShadersStore.lightFragmentDeclaration=oE;let oC=`#ifdef LIGHT{X} -uniform Light{X} -{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; -#ifdef SPOTLIGHT{X} -vec4 vLightDirection;vec4 vLightFalloff; -#elif defined(POINTLIGHT{X}) -vec4 vLightFalloff; -#elif defined(HEMILIGHT{X}) -vec3 vLightGround; -#endif -vec4 shadowsInfo;vec2 depthValues;} light{X}; -#ifdef PROJECTEDLIGHTTEXTURE{X} -uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DArrayShadow shadowSampler{X}; -#else -uniform highp sampler2DArray shadowSampler{X}; -#endif -#ifdef SHADOWCSMDEBUG{X} -const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] -( -vec3 ( 1.5,0.0,0.0 ), -vec3 ( 0.0,1.5,0.0 ), -vec3 ( 0.0,0.0,5.5 ), -vec3 ( 1.5,0.0,5.5 ), -vec3 ( 1.5,1.5,0.0 ), -vec3 ( 1.0,1.0,1.0 ), -vec3 ( 0.0,1.0,5.5 ), -vec3 ( 0.5,3.5,0.75 ) -);vec3 shadowDebug{X}; -#endif -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -int index{X}=-1; -#else -int index{X}=SHADOWCSMNUM_CASCADES{X}-1; -#endif -float diff{X}=0.; -#elif defined(SHADOWCUBE{X}) -uniform samplerCube shadowSampler{X}; -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DShadow shadowSampler{X}; -#else -uniform sampler2D shadowSampler{X}; -#endif -uniform mat4 lightMatrix{X}; -#endif -#endif -#endif -`;no.v.IncludesShadersStore.lightUboDeclaration=oC;let ob=`struct lightingInfo -{vec3 diffuse; -#ifdef SPECULARTERM -vec3 specular; -#endif -#ifdef NDOTL -float ndl; -#endif -};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) -{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} -else -{lightVectorW=normalize(-lightData.xyz);} -float ndl=max(0.,dot(vNormal,lightVectorW)); -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=ndl*diffuseColor*attenuation; -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; -#endif -return result;} -lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) -{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW)); -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=ndl*diffuseColor*attenuation; -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; -#endif -return result;} -result.diffuse=vec3(0.); -#ifdef SPECULARTERM -result.specular=vec3(0.); -#endif -#ifdef NDOTL -result.ndl=0.; -#endif -return result;} -lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=mix(groundColor,diffuseColor,ndl); -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; -#endif -return result;} -#define inline -vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;no.v.IncludesShadersStore.lightsFragmentFunctions=ob;let oy=`#ifdef SHADOWS -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -#ifndef SHADOWFLOAT -float unpack(vec4 color) -{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} -#endif -float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) -{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} -#define inline -float computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) -{vec3 directionToLight=vPositionW-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; -#ifndef SHADOWFLOAT -float shadow=unpack(textureCube(shadowSampler,directionToLight)); -#else -float shadow=textureCube(shadowSampler,directionToLight).x; -#endif -return depth>shadow ? darkness : 1.0;} -#define inline -float computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) -{vec3 directionToLight=vPositionW-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); -#ifndef SHADOWFLOAT -if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25; -#else -if (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;if (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25; -#endif -return min(1.0,visibility+darkness);} -#define inline -float computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues) -{vec3 directionToLight=vPositionW-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight)); -#else -float shadowMapSample=textureCube(shadowSampler,directionToLight).x; -#endif -float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); -return esm;} -#define inline -float computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues) -{vec3 directionToLight=vPositionW-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(textureCube(shadowSampler,directionToLight)); -#else -float shadowMapSample=textureCube(shadowSampler,directionToLight).x; -#endif -float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;} -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define inline -float computeShadowCSM(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray shadowSampler,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);vec3 uvLayer=vec3(uv.x,uv.y,layer);float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadow=unpack(texture2D(shadowSampler,uvLayer)); -#else -float shadow=texture2D(shadowSampler,uvLayer).x; -#endif -return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} -#endif -#define inline -float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} -#define inline -float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); -#ifndef SHADOWFLOAT -if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.))<shadowPixelDepth) visibility-=0.25;if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.))<shadowPixelDepth) visibility-=0.25; -#else -if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[1]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[2]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25;if (TEXTUREFUNC(shadowSampler,uv+poissonDisk[3]*mapSize,0.).x<shadowPixelDepth) visibility-=0.25; -#endif -return computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} -#ifdef IS_NDC_HALF_ZRANGE -#define ZINCLIP clipSpace.z -#else -#define ZINCLIP uvDepth.z -#endif -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define GREATEST_LESS_THAN_ONE 0.99999994 -#define inline -float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -const vec3 PoissonSamplers32[64]=vec3[64]( -vec3(0.06407013,0.05409927,0.), -vec3(0.7366577,0.5789394,0.), -vec3(-0.6270542,-0.5320278,0.), -vec3(-0.4096107,0.8411095,0.), -vec3(0.6849564,-0.4990818,0.), -vec3(-0.874181,-0.04579735,0.), -vec3(0.9989998,0.0009880066,0.), -vec3(-0.004920578,-0.9151649,0.), -vec3(0.1805763,0.9747483,0.), -vec3(-0.2138451,0.2635818,0.), -vec3(0.109845,0.3884785,0.), -vec3(0.06876755,-0.3581074,0.), -vec3(0.374073,-0.7661266,0.), -vec3(0.3079132,-0.1216763,0.), -vec3(-0.3794335,-0.8271583,0.), -vec3(-0.203878,-0.07715034,0.), -vec3(0.5912697,0.1469799,0.), -vec3(-0.88069,0.3031784,0.), -vec3(0.5040108,0.8283722,0.), -vec3(-0.5844124,0.5494877,0.), -vec3(0.6017799,-0.1726654,0.), -vec3(-0.5554981,0.1559997,0.), -vec3(-0.3016369,-0.3900928,0.), -vec3(-0.5550632,-0.1723762,0.), -vec3(0.925029,0.2995041,0.), -vec3(-0.2473137,0.5538505,0.), -vec3(0.9183037,-0.2862392,0.), -vec3(0.2469421,0.6718712,0.), -vec3(0.3916397,-0.4328209,0.), -vec3(-0.03576927,-0.6220032,0.), -vec3(-0.04661255,0.7995201,0.), -vec3(0.4402924,0.3640312,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.), -vec3(0.,0.,0.) -);const vec3 PoissonSamplers64[64]=vec3[64]( -vec3(-0.613392,0.617481,0.), -vec3(0.170019,-0.040254,0.), -vec3(-0.299417,0.791925,0.), -vec3(0.645680,0.493210,0.), -vec3(-0.651784,0.717887,0.), -vec3(0.421003,0.027070,0.), -vec3(-0.817194,-0.271096,0.), -vec3(-0.705374,-0.668203,0.), -vec3(0.977050,-0.108615,0.), -vec3(0.063326,0.142369,0.), -vec3(0.203528,0.214331,0.), -vec3(-0.667531,0.326090,0.), -vec3(-0.098422,-0.295755,0.), -vec3(-0.885922,0.215369,0.), -vec3(0.566637,0.605213,0.), -vec3(0.039766,-0.396100,0.), -vec3(0.751946,0.453352,0.), -vec3(0.078707,-0.715323,0.), -vec3(-0.075838,-0.529344,0.), -vec3(0.724479,-0.580798,0.), -vec3(0.222999,-0.215125,0.), -vec3(-0.467574,-0.405438,0.), -vec3(-0.248268,-0.814753,0.), -vec3(0.354411,-0.887570,0.), -vec3(0.175817,0.382366,0.), -vec3(0.487472,-0.063082,0.), -vec3(-0.084078,0.898312,0.), -vec3(0.488876,-0.783441,0.), -vec3(0.470016,0.217933,0.), -vec3(-0.696890,-0.549791,0.), -vec3(-0.149693,0.605762,0.), -vec3(0.034211,0.979980,0.), -vec3(0.503098,-0.308878,0.), -vec3(-0.016205,-0.872921,0.), -vec3(0.385784,-0.393902,0.), -vec3(-0.146886,-0.859249,0.), -vec3(0.643361,0.164098,0.), -vec3(0.634388,-0.049471,0.), -vec3(-0.688894,0.007843,0.), -vec3(0.464034,-0.188818,0.), -vec3(-0.440840,0.137486,0.), -vec3(0.364483,0.511704,0.), -vec3(0.034028,0.325968,0.), -vec3(0.099094,-0.308023,0.), -vec3(0.693960,-0.366253,0.), -vec3(0.678884,-0.204688,0.), -vec3(0.001801,0.780328,0.), -vec3(0.145177,-0.898984,0.), -vec3(0.062655,-0.611866,0.), -vec3(0.315226,-0.604297,0.), -vec3(-0.780145,0.486251,0.), -vec3(-0.371868,0.882138,0.), -vec3(0.200476,0.494430,0.), -vec3(-0.494552,-0.711051,0.), -vec3(0.612476,0.705252,0.), -vec3(-0.578845,-0.768792,0.), -vec3(-0.772454,-0.090976,0.), -vec3(0.504440,0.372295,0.), -vec3(0.155736,0.065157,0.), -vec3(0.391522,0.849605,0.), -vec3(-0.620106,-0.328104,0.), -vec3(0.789239,-0.419965,0.), -vec3(-0.545396,0.538133,0.), -vec3(-0.178564,-0.596057,0.) -); -#define inline -float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=texture2D(depthSampler,vec3(uvDepth.xy+(lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse*PoissonSamplers32[i].xy),layer)).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}} -float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)*depthCorrection+AAOffset);vec4 filterRadius=vec4(penumbraRatio*lightSizeUV*lightSizeUVCorrection*shadowMapSizeInverse,0.,0.);float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec4 offset=vec4(poissonSamplers[i],0.);offset=vec4(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.,0.);shadow+=texture2D(shadowSampler,uvDepthLayer+offset*filterRadius);} -shadow/=float(pcfTapCount);shadow=mix(shadow,1.,min((depthMetric-avgBlockerDepth)*depthCorrection*penumbraDarkness,1.));shadow=mix(darkness,1.,shadow);if (numBlocker<1.0) {return 1.0;} -else -{return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i<searchTapCount; i ++) {blockerDepth=TEXTUREFUNC(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy),0.).r;if (blockerDepth<depthMetric) {sumBlockerDepth+=blockerDepth;numBlocker++;}} -if (numBlocker<1.0) {return 1.0;} -else -{float avgBlockerDepth=sumBlockerDepth/numBlocker;float AAOffset=shadowMapSizeInverse*10.;float penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);float filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;float random=getRand(vPositionFromLight.xy);float rotationAngle=random*3.1415926;vec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));float shadow=0.;for (int i=0; i<pcfTapCount; i++) {vec3 offset=poissonSamplers[i];offset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);shadow+=TEXTUREFUNC(shadowSampler,uvDepth+offset*filterRadius,0.);} -shadow/=float(pcfTapCount);shadow=mix(shadow,1.,depthMetric-avgBlockerDepth);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}} -#define inline -float computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) -{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);} -#define inline -float computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) -{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);} -#define inline -float computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,highp sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff) -{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);} -#define inline -float computeShadowWithCSMPCSS16(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) -{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} -#define inline -float computeShadowWithCSMPCSS32(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) -{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} -#define inline -float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) -{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} -#endif -#endif -`;no.v.IncludesShadersStore.shadowsFragmentFunctions=oy;let oA=`#ifdef _DEFINENAME_ -#if _DEFINENAME_DIRECTUV==1 -#define v_VARYINGNAME_UV vMainUV1 -#elif _DEFINENAME_DIRECTUV==2 -#define v_VARYINGNAME_UV vMainUV2 -#elif _DEFINENAME_DIRECTUV==3 -#define v_VARYINGNAME_UV vMainUV3 -#elif _DEFINENAME_DIRECTUV==4 -#define v_VARYINGNAME_UV vMainUV4 -#elif _DEFINENAME_DIRECTUV==5 -#define v_VARYINGNAME_UV vMainUV5 -#elif _DEFINENAME_DIRECTUV==6 -#define v_VARYINGNAME_UV vMainUV6 -#else -varying vec2 v_VARYINGNAME_UV; -#endif -uniform sampler2D _SAMPLERNAME_Sampler; -#endif -`;no.v.IncludesShadersStore.samplerFragmentDeclaration=oA;let oR=`#ifdef FRESNEL -float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power) -{float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} -#endif -`;no.v.IncludesShadersStore.fresnelFunction=oR;let oP=`vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) -{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); } -vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) -{float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); } -vec3 computeEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) -{vec3 cameraToVertex=normalize(worldPos.xyz-eyePosition);vec3 r=normalize(reflect(cameraToVertex,worldNormal));r=vec3(reflectionMatrix*vec4(r,0));float lon=atan(r.z,r.x);float lat=acos(r.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0);} -vec3 computeSphericalCoords(vec4 worldPos,vec3 worldNormal,mat4 view,mat4 reflectionMatrix) -{vec3 viewDir=normalize(vec3(view*worldPos));vec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));vec3 r=reflect(viewDir,viewNormal);r=vec3(reflectionMatrix*vec4(r,0));r.z=r.z-1.0;float m=2.0*length(r);return vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);} -vec3 computePlanarCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) -{vec3 viewDir=worldPos.xyz-eyePosition;vec3 coords=normalize(reflect(viewDir,worldNormal));return vec3(reflectionMatrix*vec4(coords,1));} -vec3 computeCubicCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix) -{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=vec3(reflectionMatrix*vec4(coords,0)); -#ifdef INVERTCUBICMAP -coords.y*=-1.0; -#endif -return coords;} -vec3 computeCubicLocalCoords(vec4 worldPos,vec3 worldNormal,vec3 eyePosition,mat4 reflectionMatrix,vec3 reflectionSize,vec3 reflectionPosition) -{vec3 viewDir=normalize(worldPos.xyz-eyePosition);vec3 coords=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=vec3(reflectionMatrix*vec4(coords,0)); -#ifdef INVERTCUBICMAP -coords.y*=-1.0; -#endif -return coords;} -vec3 computeProjectionCoords(vec4 worldPos,mat4 view,mat4 reflectionMatrix) -{return vec3(reflectionMatrix*(view*worldPos));} -vec3 computeSkyBoxCoords(vec3 positionW,mat4 reflectionMatrix) -{return vec3(reflectionMatrix*vec4(positionW,1.));} -#ifdef REFLECTION -vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal) -{ -#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED -vec3 direction=normalize(vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction); -#endif -#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED -vec3 direction=normalize(vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction); -#endif -#ifdef REFLECTIONMAP_EQUIRECTANGULAR -return computeEquirectangularCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); -#endif -#ifdef REFLECTIONMAP_SPHERICAL -return computeSphericalCoords(worldPos,worldNormal,view,reflectionMatrix); -#endif -#ifdef REFLECTIONMAP_PLANAR -return computePlanarCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); -#endif -#ifdef REFLECTIONMAP_CUBIC -#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC -return computeCubicLocalCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix,vReflectionSize,vReflectionPosition); -#else -return computeCubicCoords(worldPos,worldNormal,vEyePosition.xyz,reflectionMatrix); -#endif -#endif -#ifdef REFLECTIONMAP_PROJECTION -return computeProjectionCoords(worldPos,view,reflectionMatrix); -#endif -#ifdef REFLECTIONMAP_SKYBOX -return computeSkyBoxCoords(vPositionUVW,reflectionMatrix); -#endif -#ifdef REFLECTIONMAP_EXPLICIT -return vec3(0,0,0); -#endif -} -#endif -`;no.v.IncludesShadersStore.reflectionFunction=oP;let oI=`#ifdef EXPOSURE -uniform float exposureLinear; -#endif -#ifdef CONTRAST -uniform float contrast; -#endif -#if defined(VIGNETTE) || defined(DITHER) -uniform vec2 vInverseScreenSize; -#endif -#ifdef VIGNETTE -uniform vec4 vignetteSettings1;uniform vec4 vignetteSettings2; -#endif -#ifdef COLORCURVES -uniform vec4 vCameraColorCurveNegative;uniform vec4 vCameraColorCurveNeutral;uniform vec4 vCameraColorCurvePositive; -#endif -#ifdef COLORGRADING -#ifdef COLORGRADING3D -uniform highp sampler3D txColorTransform; -#else -uniform sampler2D txColorTransform; -#endif -uniform vec4 colorTransformSettings; -#endif -#ifdef DITHER -uniform float ditherIntensity; -#endif -`;no.v.IncludesShadersStore.imageProcessingDeclaration=oI;let oM=`#if defined(COLORGRADING) && !defined(COLORGRADING3D) -/** -* Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL. -* sampler3dSetting.x=textureOffset (0.5/textureSize). -* sampler3dSetting.y=textureSize. -*/ -#define inline -vec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting) -{float sliceSize=2.0*sampler3dSetting.x; -#ifdef SAMPLER3DGREENDEPTH -float sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y; -#else -float sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y; -#endif -float sliceInteger=floor(sliceContinuous);float sliceFraction=sliceContinuous-sliceInteger; -#ifdef SAMPLER3DGREENDEPTH -vec2 sliceUV=color.rb; -#else -vec2 sliceUV=color.rg; -#endif -sliceUV.x*=sliceSize;sliceUV.x+=sliceInteger*sliceSize;sliceUV=saturate(sliceUV);vec4 slice0Color=texture2D(colorTransform,sliceUV);sliceUV.x+=sliceSize;sliceUV=saturate(sliceUV);vec4 slice1Color=texture2D(colorTransform,sliceUV);vec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction); -#ifdef SAMPLER3DBGRMAP -color.rgb=result.rgb; -#else -color.rgb=result.bgr; -#endif -return color;} -#endif -#ifdef TONEMAPPING_ACES -const mat3 ACESInputMat=mat3( -vec3(0.59719,0.07600,0.02840), -vec3(0.35458,0.90834,0.13383), -vec3(0.04823,0.01566,0.83777) -);const mat3 ACESOutputMat=mat3( -vec3( 1.60475,-0.10208,-0.00327), -vec3(-0.53108, 1.10813,-0.07276), -vec3(-0.07367,-0.00605, 1.07602) -);vec3 RRTAndODTFit(vec3 v) -{vec3 a=v*(v+0.0245786)-0.000090537;vec3 b=v*(0.983729*v+0.4329510)+0.238081;return a/b;} -vec3 ACESFitted(vec3 color) -{color=ACESInputMat*color;color=RRTAndODTFit(color);color=ACESOutputMat*color;color=saturate(color);return color;} -#endif -#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS -vec4 applyImageProcessing(vec4 result) { -#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART -#ifdef EXPOSURE -result.rgb*=exposureLinear; -#endif -#ifdef VIGNETTE -vec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;vec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);float vignetteTerm=dot(vignetteXY1,vignetteXY1);float vignette=pow(vignetteTerm,vignetteSettings2.w);vec3 vignetteColor=vignetteSettings2.rgb; -#ifdef VIGNETTEBLENDMODEMULTIPLY -vec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);result.rgb*=vignetteColorMultiplier; -#endif -#ifdef VIGNETTEBLENDMODEOPAQUE -result.rgb=mix(vignetteColor,result.rgb,vignette); -#endif -#endif -#ifdef TONEMAPPING -#ifdef TONEMAPPING_ACES -result.rgb=ACESFitted(result.rgb); -#else -const float tonemappingCalibration=1.590579;result.rgb=1.0-exp2(-tonemappingCalibration*result.rgb); -#endif -#endif -result.rgb=toGammaSpace(result.rgb);result.rgb=saturate(result.rgb); -#ifdef CONTRAST -vec3 resultHighContrast=result.rgb*result.rgb*(3.0-2.0*result.rgb);if (contrast<1.0) {result.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);} else {result.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);} -#endif -#ifdef COLORGRADING -vec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy; -#ifdef COLORGRADING3D -vec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb; -#else -vec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb; -#endif -result.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www); -#endif -#ifdef COLORCURVES -float luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));vec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;result.rgb*=colorCurve.rgb;result.rgb=mix(vec3(luma),result.rgb,colorCurve.a); -#endif -#ifdef DITHER -float rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither)); -#endif -#define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND -return result;}`;no.v.IncludesShadersStore.imageProcessingFunctions=oM;let oD=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) -#if defined(TANGENT) && defined(NORMAL) -varying mat3 vTBN; -#endif -#ifdef OBJECTSPACE_NORMALMAP -uniform mat4 normalMatrix; -#if defined(WEBGL2) || defined(WEBGPU) -mat4 toNormalMatrix(mat4 wMatrix) -{mat4 ret=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]=vec4(0.,0.,0.,1.);return ret;} -#else -mat4 toNormalMatrix(mat4 m) -{float -a00=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3], -a10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3], -a20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3], -a30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3], -b00=a00*a11-a01*a10, -b01=a00*a12-a02*a10, -b02=a00*a13-a03*a10, -b03=a01*a12-a02*a11, -b04=a01*a13-a03*a11, -b05=a02*a13-a03*a12, -b06=a20*a31-a21*a30, -b07=a20*a32-a22*a30, -b08=a20*a33-a23*a30, -b09=a21*a32-a22*a31, -b10=a21*a33-a23*a31, -b11=a22*a33-a23*a32, -det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;mat4 mi=mat4( -a11*b11-a12*b10+a13*b09, -a02*b10-a01*b11-a03*b09, -a31*b05-a32*b04+a33*b03, -a22*b04-a21*b05-a23*b03, -a12*b08-a10*b11-a13*b07, -a00*b11-a02*b08+a03*b07, -a32*b02-a30*b05-a33*b01, -a20*b05-a22*b02+a23*b01, -a10*b10-a11*b08+a13*b06, -a01*b08-a00*b10-a03*b06, -a30*b04-a31*b02+a33*b00, -a21*b02-a20*b04-a23*b00, -a11*b07-a10*b09-a12*b06, -a00*b09-a01*b07+a02*b06, -a31*b01-a30*b03-a32*b00, -a20*b03-a21*b01+a22*b00)/det;return mat4(mi[0][0],mi[1][0],mi[2][0],mi[3][0], -mi[0][1],mi[1][1],mi[2][1],mi[3][1], -mi[0][2],mi[1][2],mi[2][2],mi[3][2], -mi[0][3],mi[1][3],mi[2][3],mi[3][3]);} -#endif -#endif -vec3 perturbNormalBase(mat3 cotangentFrame,vec3 normal,float scale) -{ -#ifdef NORMALXYSCALE -normal=normalize(normal*vec3(scale,scale,1.0)); -#endif -return normalize(cotangentFrame*normal);} -vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale) -{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);} -mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams) -{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);} -#endif -`;no.v.IncludesShadersStore.bumpFragmentMainFunctions=oD;let oO=`#if defined(BUMP) -#include<samplerFragmentDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) -#endif -#if defined(DETAIL) -#include<samplerFragmentDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) -#endif -#if defined(BUMP) && defined(PARALLAX) -const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; i<iMaxSamples; i++) -{currSampledHeight=texture2D(bumpSampler,texCoord+vCurrOffset).w;if (!keepWorking) -{} -else if (currSampledHeight>currRayHeight) -{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} -else -{currRayHeight-=stepSize;vLastOffset=vCurrOffset;vCurrOffset+=stepSize*vMaxOffset;lastSampledHeight=currSampledHeight;}} -return vCurrOffset;} -vec2 parallaxOffset(vec3 viewDir,float heightScale) -{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height;return -texCoordOffset;} -#endif -`;no.v.IncludesShadersStore.bumpFragmentFunctions=oO;let oN=`#ifdef CLIPPLANE -varying float fClipDistance; -#endif -#ifdef CLIPPLANE2 -varying float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -varying float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -varying float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -varying float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -varying float fClipDistance6; -#endif -`;no.v.IncludesShadersStore.clipPlaneFragmentDeclaration=oN;let oF=`#ifdef LOGARITHMICDEPTH -uniform float logarithmicDepthConstant;varying float vFragmentDepth; -#endif -`;no.v.IncludesShadersStore.logDepthDeclaration=oF;let oL=`#ifdef FOG -#define FOGMODE_NONE 0. -#define FOGMODE_EXP 1. -#define FOGMODE_EXP2 2. -#define FOGMODE_LINEAR 3. -#define E 2.71828 -uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() -{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) -{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} -else if (FOGMODE_EXP==vFogInfos.x) -{fogCoeff=1.0/pow(E,fogDistance*fogDensity);} -else if (FOGMODE_EXP2==vFogInfos.x) -{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} -return clamp(fogCoeff,0.0,1.0);} -#endif -`;no.v.IncludesShadersStore.fogFragmentDeclaration=oL;let ow=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -if (false) {} -#endif -#ifdef CLIPPLANE -else if (fClipDistance>0.0) -{discard;} -#endif -#ifdef CLIPPLANE2 -else if (fClipDistance2>0.0) -{discard;} -#endif -#ifdef CLIPPLANE3 -else if (fClipDistance3>0.0) -{discard;} -#endif -#ifdef CLIPPLANE4 -else if (fClipDistance4>0.0) -{discard;} -#endif -#ifdef CLIPPLANE5 -else if (fClipDistance5>0.0) -{discard;} -#endif -#ifdef CLIPPLANE6 -else if (fClipDistance6>0.0) -{discard;} -#endif -`;no.v.IncludesShadersStore.clipPlaneFragment=ow;let oB=`vec2 uvOffset=vec2(0.0,0.0); -#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) -#ifdef NORMALXYSCALE -float normalScale=1.0; -#elif defined(BUMP) -float normalScale=vBumpInfos.y; -#else -float normalScale=1.0; -#endif -#if defined(TANGENT) && defined(NORMAL) -mat3 TBN=vTBN; -#elif defined(BUMP) -vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); -#else -vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); -#endif -#elif defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -mat3 TBN=vTBN; -#else -vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); -#endif -#endif -#ifdef PARALLAX -mat3 invTBN=transposeMat3(TBN); -#ifdef PARALLAXOCCLUSION -uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); -#else -uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); -#endif -#endif -#ifdef DETAIL -vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); -#endif -#ifdef BUMP -#ifdef OBJECTSPACE_NORMALMAP -#define CUSTOM_FRAGMENT_BUMP_FRAGMENT -normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); -#elif !defined(DETAIL) -normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); -#else -vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; -#if DETAIL_NORMALBLENDMETHOD==0 -detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); -#elif DETAIL_NORMALBLENDMETHOD==1 -detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; -#endif -normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); -#endif -#elif defined(DETAIL) -detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); -#endif -`;no.v.IncludesShadersStore.bumpFragment=oB;let oU=`#ifdef DECAL -#ifdef GAMMADECAL -decalColor.rgb=toLinearSpace(decalColor.rgb); -#endif -#ifdef DECAL_SMOOTHALPHA -decalColor.a*=decalColor.a; -#endif -surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); -#endif -`;no.v.IncludesShadersStore.decalFragment=oU;let oV=`#ifdef DEPTHPREPASS -gl_FragColor=vec4(0.,0.,0.,1.0);return; -#endif -`;no.v.IncludesShadersStore.depthPrePass=oV;let ok=`#ifdef LIGHT{X} -#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) -#else -#ifdef PBR -#ifdef SPOTLIGHT{X} -preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(POINTLIGHT{X}) -preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(HEMILIGHT{X}) -preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(DIRLIGHT{X}) -preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#endif -preInfo.NdotV=NdotV; -#ifdef SPOTLIGHT{X} -#ifdef LIGHT_FALLOFF_GLTF{X} -preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); -#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) -preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); -#elif defined(LIGHT_FALLOFF_STANDARD{X}) -preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); -#else -preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); -#endif -#elif defined(POINTLIGHT{X}) -#ifdef LIGHT_FALLOFF_GLTF{X} -preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); -#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) -preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); -#elif defined(LIGHT_FALLOFF_STANDARD{X}) -preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); -#else -preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); -#endif -#else -preInfo.attenuation=1.0; -#endif -#ifdef HEMILIGHT{X} -preInfo.roughness=roughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -#ifdef IRIDESCENCE -preInfo.iridescenceIntensity=iridescenceIntensity; -#endif -#ifdef HEMILIGHT{X} -info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); -#elif defined(SS_TRANSLUCENCY) -info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); -#else -info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); -#endif -#ifdef SPECULARTERM -#ifdef ANISOTROPIC -info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#else -info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#endif -#endif -#ifdef SHEEN -#ifdef SHEEN_LINKWITHALBEDO -preInfo.roughness=sheenOut.sheenIntensity; -#else -#ifdef HEMILIGHT{X} -preInfo.roughness=sheenOut.sheenRoughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -#endif -info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#endif -#ifdef CLEARCOAT -#ifdef HEMILIGHT{X} -preInfo.roughness=clearcoatOut.clearCoatRoughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); -#ifdef CLEARCOAT_TINT -absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; -#ifdef SPECULARTERM -info.specular*=absorption; -#endif -#endif -info.diffuse*=info.clearCoat.w; -#ifdef SPECULARTERM -info.specular*=info.clearCoat.w; -#endif -#ifdef SHEEN -info.sheen*=info.clearCoat.w; -#endif -#endif -#else -#ifdef SPOTLIGHT{X} -info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); -#elif defined(HEMILIGHT{X}) -info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); -#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) -info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); -#endif -#endif -#ifdef PROJECTEDLIGHTTEXTURE{X} -info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X}); -#endif -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) -{ -#ifdef SHADOWCSM_RIGHTHANDED{X} -diff{X}=viewFrustumZ{X}[i]+vPositionFromCamera{X}.z; -#else -diff{X}=viewFrustumZ{X}[i]-vPositionFromCamera{X}.z; -#endif -if (diff{X}>=0.) {index{X}=i;break;}} -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -if (index{X}>=0) -#endif -{ -#if defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#else -shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#endif -#else -shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#ifdef SHADOWCSMDEBUG{X} -shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; -#endif -#ifndef SHADOWCSMNOBLEND{X} -float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) -{index{X}+=1;float nextShadow=0.; -#if defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#elif defined(SHADOWMEDIUMQUALITY{X}) -nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#else -nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#endif -#else -nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -shadow=mix(nextShadow,shadow,diffRatio); -#ifdef SHADOWCSMDEBUG{X} -shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); -#endif -} -#endif -} -#elif defined(SHADOWCLOSEESM{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); -#else -shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWESM{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); -#else -shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPOISSON{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); -#else -shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#else -#if defined(SHADOWCUBE{X}) -shadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues); -#else -shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#endif -#ifdef SHADOWONLY -#ifndef SHADOWINUSE -#define SHADOWINUSE -#endif -globalShadow+=shadow;shadowLightCount+=1.0; -#endif -#else -shadow=1.; -#endif -#ifndef SHADOWONLY -#ifdef CUSTOMUSERLIGHTING -diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); -#ifdef SPECULARTERM -specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); -#endif -#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) -diffuseBase+=lightmapColor.rgb*shadow; -#ifdef SPECULARTERM -#ifndef LIGHTMAPNOSPECULAR{X} -specularBase+=info.specular*shadow*lightmapColor.rgb; -#endif -#endif -#ifdef CLEARCOAT -#ifndef LIGHTMAPNOSPECULAR{X} -clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; -#endif -#endif -#ifdef SHEEN -#ifndef LIGHTMAPNOSPECULAR{X} -sheenBase+=info.sheen.rgb*shadow; -#endif -#endif -#else -#ifdef SHADOWCSMDEBUG{X} -diffuseBase+=info.diffuse*shadowDebug{X}; -#else -diffuseBase+=info.diffuse*shadow; -#endif -#ifdef SPECULARTERM -specularBase+=info.specular*shadow; -#endif -#ifdef CLEARCOAT -clearCoatBase+=info.clearCoat.rgb*shadow; -#endif -#ifdef SHEEN -sheenBase+=info.sheen.rgb*shadow; -#endif -#endif -#endif -#endif -`;no.v.IncludesShadersStore.lightFragment=ok;let oG=`#ifdef LOGARITHMICDEPTH -gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; -#endif -`;no.v.IncludesShadersStore.logDepthFragment=oG;let oz=`#ifdef FOG -float fog=CalcFogFactor(); -#ifdef PBR -fog=toLinearSpace(fog); -#endif -color.rgb=mix(vFogColor,color.rgb,fog); -#endif -`;no.v.IncludesShadersStore.fogFragment=oz;let oW=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY -float fragDepth=gl_FragCoord.z; -#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS -uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; -#endif -ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); -#ifdef USE_REVERSE_DEPTHBUFFER -float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; -#else -float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; -#endif -float alphaMultiplier=1.0-lastFrontColor.a; -#ifdef USE_REVERSE_DEPTHBUFFER -if (fragDepth>nearestDepth || fragDepth<furthestDepth) { -#else -if (fragDepth<nearestDepth || fragDepth>furthestDepth) { -#endif -return;} -#ifdef USE_REVERSE_DEPTHBUFFER -if (fragDepth<nearestDepth && fragDepth>furthestDepth) { -#else -if (fragDepth>nearestDepth && fragDepth<furthestDepth) { -#endif -depth.rg=vec2(-fragDepth,fragDepth);return;} -#endif -`;no.v.IncludesShadersStore.oitFragment=oW;let oH=`#include<__decl__defaultFragment> -#if defined(BUMP) || !defined(NORMAL) -#extension GL_OES_standard_derivatives : enable -#endif -#include<prePassDeclaration>[SCENE_MRT_COUNT] -#include<oitDeclaration> -#define CUSTOM_FRAGMENT_BEGIN -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -#define RECIPROCAL_PI2 0.15915494 -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include<mainUVVaryingDeclaration>[1..7] -#include<helperFunctions> -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include<lightsFragmentFunctions> -#include<shadowsFragmentFunctions> -#include<samplerFragmentDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) -#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) -#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) -#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) -#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) -#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) -#ifdef REFRACTION -#ifdef REFRACTIONMAP_3D -uniform samplerCube refractionCubeSampler; -#else -uniform sampler2D refraction2DSampler; -#endif -#endif -#if defined(SPECULARTERM) -#include<samplerFragmentDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) -#endif -#include<fresnelFunction> -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -uniform samplerCube reflectionCubeSampler; -#else -uniform sampler2D reflection2DSampler; -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#include<reflectionFunction> -#endif -#include<imageProcessingDeclaration> -#include<imageProcessingFunctions> -#include<bumpFragmentMainFunctions> -#include<bumpFragmentFunctions> -#include<clipPlaneFragmentDeclaration> -#include<logDepthDeclaration> -#include<fogFragmentDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); -#endif -#include<bumpFragment> -#ifdef TWOSIDEDLIGHTING -normalW=gl_FrontFacing ? normalW : -normalW; -#endif -#ifdef DIFFUSE -baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); -#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) -if (baseColor.a<alphaCutOff) -discard; -#endif -#ifdef ALPHAFROMDIFFUSE -alpha*=baseColor.a; -#endif -#define CUSTOM_FRAGMENT_UPDATE_ALPHA -baseColor.rgb*=vDiffuseInfos.y; -#endif -#if defined(DECAL) && !defined(DECAL_AFTER_DETAIL) -vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); -#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) -#endif -#include<depthPrePass> -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -baseColor.rgb*=vColor.rgb; -#endif -#ifdef DETAIL -baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); -#endif -#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) -vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); -#include<decalFragment>(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) -#endif -#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE -vec3 baseAmbientColor=vec3(1.,1.,1.); -#ifdef AMBIENT -baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; -#endif -#define CUSTOM_FRAGMENT_BEFORE_LIGHTS -#ifdef SPECULARTERM -float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; -#ifdef SPECULAR -vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; -#ifdef GLOSSINESS -glossiness=glossiness*specularMapColor.a; -#endif -#endif -#else -float glossiness=0.; -#endif -vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; -#ifdef SPECULARTERM -vec3 specularBase=vec3(0.,0.,0.); -#endif -float shadow=1.; -#ifdef LIGHTMAP -vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); -#ifdef RGBDLIGHTMAP -lightmapColor.rgb=fromRGBD(lightmapColor); -#endif -lightmapColor.rgb*=vLightmapInfos.y; -#endif -#include<lightFragment>[0..maxSimultaneousLights] -vec4 refractionColor=vec4(0.,0.,0.,1.); -#ifdef REFRACTION -vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); -#ifdef REFRACTIONMAP_3D -#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC -refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); -#endif -refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} -#else -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); -#endif -#ifdef RGBDREFRACTION -refractionColor.rgb=fromRGBD(refractionColor); -#endif -#ifdef IS_REFRACTION_LINEAR -refractionColor.rgb=toGammaSpace(refractionColor.rgb); -#endif -refractionColor.rgb*=vRefractionInfos.x; -#endif -vec4 reflectionColor=vec4(0.,0.,0.,1.); -#ifdef REFLECTION -vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#ifdef REFLECTIONMAP_OPPOSITEZ -vReflectionUVW.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -#ifdef ROUGHNESS -float bias=vReflectionInfos.y; -#ifdef SPECULARTERM -#ifdef SPECULAR -#ifdef GLOSSINESS -bias*=(1.0-specularMapColor.a); -#endif -#endif -#endif -reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); -#else -reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); -#endif -#else -vec2 coords=vReflectionUVW.xy; -#ifdef REFLECTIONMAP_PROJECTION -coords/=vReflectionUVW.z; -#endif -coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); -#endif -#ifdef RGBDREFLECTION -reflectionColor.rgb=fromRGBD(reflectionColor); -#endif -#ifdef IS_REFLECTION_LINEAR -reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); -#endif -reflectionColor.rgb*=vReflectionInfos.x; -#ifdef REFLECTIONFRESNEL -float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); -#ifdef REFLECTIONFRESNELFROMSPECULAR -#ifdef SPECULARTERM -reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#else -reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#endif -#else -reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#endif -#endif -#endif -#ifdef REFRACTIONFRESNEL -float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); -#ifdef OPACITYRGB -opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; -#else -alpha*=opacityMap.a*vOpacityInfos.y; -#endif -#endif -#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) -alpha*=vColor.a; -#endif -#ifdef OPACITYFRESNEL -float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; -#endif -#ifdef ALPHATEST -#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS -if (alpha<alphaCutOff) -discard; -#endif -#ifndef ALPHABLEND -alpha=1.0; -#endif -#endif -vec3 emissiveColor=vEmissiveColor; -#ifdef EMISSIVE -emissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y; -#endif -#ifdef EMISSIVEFRESNEL -float emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);emissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb; -#endif -#ifdef DIFFUSEFRESNEL -float diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);diffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb; -#endif -#ifdef EMISSIVEASILLUMINATION -vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb; -#else -#ifdef LINKEMISSIVEWITHDIFFUSE -vec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb; -#else -vec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb; -#endif -#endif -#ifdef SPECULARTERM -vec3 finalSpecular=specularBase*specularColor; -#ifdef SPECULAROVERALPHA -alpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.); -#endif -#else -vec3 finalSpecular=vec3(0.0); -#endif -#ifdef REFLECTIONOVERALPHA -alpha=clamp(alpha+dot(reflectionColor.rgb,vec3(0.3,0.59,0.11)),0.,1.); -#endif -#ifdef EMISSIVEASILLUMINATION -vec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+emissiveColor+refractionColor.rgb,0.0,1.0),alpha); -#else -vec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor.rgb+refractionColor.rgb,alpha); -#endif -#ifdef LIGHTMAP -#ifndef LIGHTMAPEXCLUDED -#ifdef USELIGHTMAPASSHADOWMAP -color.rgb*=lightmapColor.rgb; -#else -color.rgb+=lightmapColor.rgb; -#endif -#endif -#endif -#define CUSTOM_FRAGMENT_BEFORE_FOG -color.rgb=max(color.rgb,0.); -#include<logDepthFragment> -#include<fogFragment> -#ifdef IMAGEPROCESSINGPOSTPROCESS -color.rgb=toLinearSpace(color.rgb); -#else -#ifdef IMAGEPROCESSING -color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); -#endif -#endif -color.a*=visibility; -#ifdef PREMULTIPLYALPHA -color.rgb*=color.a; -#endif -#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR -#ifdef PREPASS -float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; -#ifdef PREPASS_POSITION -gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); -#endif -#ifdef PREPASS_VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_IRRADIANCE -gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_DEPTH -gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_NORMAL -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); -#endif -#ifdef PREPASS_ALBEDO_SQRT -gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_REFLECTIVITY -#if defined(SPECULARTERM) -#if defined(SPECULAR) -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; -#endif -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; -#endif -#endif -#endif -#if !defined(PREPASS) || defined(WEBGL2) -gl_FragColor=color; -#endif -#include<oitFragment> -#if ORDER_INDEPENDENT_TRANSPARENCY -if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} -#endif -#define CUSTOM_FRAGMENT_MAIN_END -} -`;no.v.ShadersStore.defaultPixelShader=oH;let oX=`#ifdef DECAL -uniform vec4 vDecalInfos;uniform mat4 decalMatrix; -#endif -`;no.v.IncludesShadersStore.decalVertexDeclaration=oX;let oY=`uniform mat4 viewProjection;uniform mat4 view; -#ifdef DIFFUSE -uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; -#endif -#ifdef AMBIENT -uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; -#endif -#ifdef OPACITY -uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) -uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; -#endif -#ifdef REFLECTION -uniform mat4 reflectionMatrix; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos;uniform mat4 detailMatrix; -#endif -#include<decalVertexDeclaration> -#define ADDITIONAL_VERTEX_DECLARATION -`;no.v.IncludesShadersStore.defaultVertexDeclaration=oY;let oj=`#ifdef UV{X} -attribute vec2 uv{X}; -#endif -`;no.v.IncludesShadersStore.uvAttributeDeclaration=oj;let oq=`#if NUM_BONE_INFLUENCERS>0 -attribute vec4 matricesIndices;attribute vec4 matricesWeights; -#if NUM_BONE_INFLUENCERS>4 -attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; -#endif -#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#ifdef BONETEXTURE -uniform sampler2D boneSampler;uniform float boneTextureWidth; -#else -uniform mat4 mBones[BonesPerMesh]; -#ifdef BONES_VELOCITY_ENABLED -uniform mat4 mPreviousBones[BonesPerMesh]; -#endif -#endif -#ifdef BONETEXTURE -#define inline -mat4 readMatrixFromRawSampler(sampler2D smp,float index) -{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} -#endif -#endif -#endif -`;no.v.IncludesShadersStore.bonesDeclaration=oq;let oK=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; -#ifdef INSTANCES -attribute vec4 bakedVertexAnimationSettingsInstanced; -#endif -#define inline -mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) -{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} -#endif -`;no.v.IncludesShadersStore.bakedVertexAnimationDeclaration=oK;let o$=`#ifdef INSTANCES -attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; -#ifdef INSTANCESCOLOR -attribute vec4 instanceColor; -#endif -#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) -uniform mat4 world; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; -#ifdef THIN_INSTANCES -uniform mat4 previousWorld; -#endif -#endif -#else -#if !defined(WORLD_UBO) -uniform mat4 world; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -uniform mat4 previousWorld; -#endif -#endif -`;no.v.IncludesShadersStore.instancesDeclaration=o$;let oQ=`#ifdef PREPASS -#ifdef PREPASS_DEPTH -varying vec3 vViewPos; -#endif -#ifdef PREPASS_VELOCITY -uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#endif -`;no.v.IncludesShadersStore.prePassVertexDeclaration=oQ;let oZ=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 -varying vec2 v_VARYINGNAME_UV; -#endif -`;no.v.IncludesShadersStore.samplerVertexDeclaration=oZ;let oJ=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -varying mat3 vTBN; -#endif -#endif -`;no.v.IncludesShadersStore.bumpVertexDeclaration=oJ;let o0=`#ifdef CLIPPLANE -uniform vec4 vClipPlane;varying float fClipDistance; -#endif -#ifdef CLIPPLANE2 -uniform vec4 vClipPlane2;varying float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -uniform vec4 vClipPlane3;varying float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -uniform vec4 vClipPlane4;varying float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -uniform vec4 vClipPlane5;varying float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -uniform vec4 vClipPlane6;varying float fClipDistance6; -#endif -`;no.v.IncludesShadersStore.clipPlaneVertexDeclaration=o0;let o1=`#ifdef FOG -varying vec3 vFogDistance; -#endif -`;no.v.IncludesShadersStore.fogVertexDeclaration=o1;let o2=`#ifdef LIGHT{X} -uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; -#ifdef SPECULARTERM -uniform vec4 vLightSpecular{X}; -#else -vec4 vLightSpecular{X}=vec4(0.); -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#elif defined(SHADOWCUBE{X}) -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; -#endif -uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; -#endif -#ifdef SPOTLIGHT{X} -uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; -#elif defined(POINTLIGHT{X}) -uniform vec4 vLightFalloff{X}; -#elif defined(HEMILIGHT{X}) -uniform vec3 vLightGround{X}; -#endif -#endif -`;no.v.IncludesShadersStore.lightVxFragmentDeclaration=o2;let o3=`#ifdef LIGHT{X} -uniform Light{X} -{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; -#ifdef SPOTLIGHT{X} -vec4 vLightDirection;vec4 vLightFalloff; -#elif defined(POINTLIGHT{X}) -vec4 vLightFalloff; -#elif defined(HEMILIGHT{X}) -vec3 vLightGround; -#endif -vec4 shadowsInfo;vec2 depthValues;} light{X}; -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#elif defined(SHADOWCUBE{X}) -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; -#endif -#endif -#endif -`;no.v.IncludesShadersStore.lightVxUboDeclaration=o3;let o4=`#ifdef MORPHTARGETS -uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; -#ifdef MORPHTARGETS_TEXTURE -precision mediump sampler2DArray; -uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) -{ -float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} -#endif -#endif -`;no.v.IncludesShadersStore.morphTargetsVertexGlobalDeclaration=o4;let o5=`#ifdef MORPHTARGETS -#ifndef MORPHTARGETS_TEXTURE -attribute vec3 position{X}; -#ifdef MORPHTARGETS_NORMAL -attribute vec3 normal{X}; -#endif -#ifdef MORPHTARGETS_TANGENT -attribute vec3 tangent{X}; -#endif -#ifdef MORPHTARGETS_UV -attribute vec2 uv_{X}; -#endif -#endif -#endif -`;no.v.IncludesShadersStore.morphTargetsVertexDeclaration=o5;let o6=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -float vertexID; -#endif -#endif -`;no.v.IncludesShadersStore.morphTargetsVertexGlobal=o6;let o8=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];vertexID+=1.0; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];vertexID+=1.0; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];vertexID+=1.0; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}]; -#endif -#else -positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; -#endif -#endif -#endif -`;no.v.IncludesShadersStore.morphTargetsVertex=o8;let o7=`#ifdef INSTANCES -mat4 finalWorld=mat4(world0,world1,world2,world3); -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); -#endif -#ifdef THIN_INSTANCES -finalWorld=world*finalWorld; -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -finalPreviousWorld=previousWorld*finalPreviousWorld; -#endif -#endif -#else -mat4 finalWorld=world; -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -mat4 finalPreviousWorld=previousWorld; -#endif -#endif -`;no.v.IncludesShadersStore.instancesVertex=o7;let o9=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#if NUM_BONE_INFLUENCERS>0 -mat4 influence; -#ifdef BONETEXTURE -influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; -#endif -#else -influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -#endif -finalWorld=finalWorld*influence; -#endif -#endif -`;no.v.IncludesShadersStore.bonesVertex=o9;let le=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -{ -#ifdef INSTANCES -#define BVASNAME bakedVertexAnimationSettingsInstanced -#else -#define BVASNAME bakedVertexAnimationSettings -#endif -float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; -#endif -finalWorld=finalWorld*VATInfluence;} -#endif -`;no.v.IncludesShadersStore.bakedVertexAnimation=le;let lt=`#ifdef PREPASS_DEPTH -vViewPos=(view*worldPos).rgb; -#endif -#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*worldPos; -#if NUM_BONE_INFLUENCERS>0 -mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); -#else -vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#endif -`;no.v.IncludesShadersStore.prePassVertex=lt;let li=`#if !defined(UV{X}) && defined(MAINUV{X}) -vec2 uv{X}=vec2(0.,0.); -#endif -#ifdef MAINUV{X} -vMainUV{X}=uv{X}; -#endif -`;no.v.IncludesShadersStore.uvVariableDeclaration=li;let lr=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 -if (v_INFONAME_==0.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} -#ifdef UV2 -else if (v_INFONAME_==1.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));} -#endif -#ifdef UV3 -else if (v_INFONAME_==2.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} -#endif -#ifdef UV4 -else if (v_INFONAME_==3.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} -#endif -#ifdef UV5 -else if (v_INFONAME_==4.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} -#endif -#ifdef UV6 -else if (v_INFONAME_==5.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} -#endif -#endif -`;no.v.IncludesShadersStore.samplerVertexImplementation=lr;let ls=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); -#endif -#endif -`;no.v.IncludesShadersStore.bumpVertex=ls;let ln=`#ifdef CLIPPLANE -fClipDistance=dot(worldPos,vClipPlane); -#endif -#ifdef CLIPPLANE2 -fClipDistance2=dot(worldPos,vClipPlane2); -#endif -#ifdef CLIPPLANE3 -fClipDistance3=dot(worldPos,vClipPlane3); -#endif -#ifdef CLIPPLANE4 -fClipDistance4=dot(worldPos,vClipPlane4); -#endif -#ifdef CLIPPLANE5 -fClipDistance5=dot(worldPos,vClipPlane5); -#endif -#ifdef CLIPPLANE6 -fClipDistance6=dot(worldPos,vClipPlane6); -#endif -`;no.v.IncludesShadersStore.clipPlaneVertex=ln;let la=`#ifdef FOG -vFogDistance=(view*worldPos).xyz; -#endif -`;no.v.IncludesShadersStore.fogVertex=la;let lo=`#ifdef SHADOWS -#if defined(SHADOWCSM{X}) -vPositionFromCamera{X}=view*worldPos;for (int i=0; i<SHADOWCSMNUM_CASCADES{X}; i++) {vPositionFromLight{X}[i]=lightMatrix{X}[i]*worldPos; -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetric{X}[i]=(-vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y; -#else -vDepthMetric{X}[i]=(vPositionFromLight{X}[i].z+light{X}.depthValues.x)/light{X}.depthValues.y; -#endif -} -#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X}) -vPositionFromLight{X}=lightMatrix{X}*worldPos; -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetric{X}=(-vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; -#else -vDepthMetric{X}=(vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; -#endif -#endif -#endif -`;no.v.IncludesShadersStore.shadowsVertex=lo;let ll=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -vColor=vec4(1.0); -#ifdef VERTEXCOLOR -#ifdef VERTEXALPHA -vColor*=color; -#else -vColor.rgb*=color.rgb; -#endif -#endif -#ifdef INSTANCESCOLOR -vColor*=instanceColor; -#endif -#endif -`;no.v.IncludesShadersStore.vertexColorMixing=ll;let lh=`#if defined(POINTSIZE) && !defined(WEBGPU) -gl_PointSize=pointSize; -#endif -`;no.v.IncludesShadersStore.pointCloudVertex=lh;let lu=`#ifdef LOGARITHMICDEPTH -vFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant; -#endif -`;no.v.IncludesShadersStore.logDepthVertex=lu;let lc=`#include<__decl__defaultVertex> -#define CUSTOM_VERTEX_BEGIN -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#ifdef TANGENT -attribute vec4 tangent; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#include<uvAttributeDeclaration>[2..7] -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include<helperFunctions> -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<instancesDeclaration> -#include<prePassVertexDeclaration> -#include<mainUVVaryingDeclaration>[1..7] -#include<samplerVertexDeclaration>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) -#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) -#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) -#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) -#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) -#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) -#if defined(SPECULARTERM) -#include<samplerVertexDeclaration>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) -#endif -#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) -#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include<bumpVertexDeclaration> -#include<clipPlaneVertexDeclaration> -#include<fogVertexDeclaration> -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#include<logDepthDeclaration> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#ifdef TANGENT -vec4 tangentUpdated=tangent; -#endif -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=positionUpdated; -#endif -#define CUSTOM_VERTEX_UPDATE_POSITION -#define CUSTOM_VERTEX_UPDATE_NORMAL -#include<instancesVertex> -#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normalUpdated); -#endif -#endif -#define CUSTOM_VERTEX_UPDATE_WORLDPOS -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -vPositionW=vec3(worldPos); -#include<prePassVertex> -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); -#endif -#ifndef UV1 -vec2 uvUpdated=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uvUpdated; -#endif -#include<uvVariableDeclaration>[2..7] -#include<samplerVertexImplementation>(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) -#if defined(SPECULARTERM) -#include<samplerVertexImplementation>(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) -#endif -#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) -#include<bumpVertex> -#include<clipPlaneVertex> -#include<fogVertex> -#include<shadowsVertex>[0..maxSimultaneousLights] -#include<vertexColorMixing> -#include<pointCloudVertex> -#include<logDepthVertex> -#define CUSTOM_VERTEX_MAIN_END -} -`;no.v.ShadersStore.defaultVertexShader=lc;var ld=i(76);let lp=RegExp("^([gimus]+)!");class l_{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e.name)return!1;if(this._material._uniformBufferLayoutBuilt)throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because this material has already been used for rendering! Please add plugins to materials before any rendering with this material occurs.`;let t=e.getClassName();l_._MaterialPluginClassToMainDefine[t]||(l_._MaterialPluginClassToMainDefine[t]="MATERIALPLUGIN_"+ ++l_._MaterialPluginCounter),this._material._callbackPluginEventGeneric=this._handlePluginEvent.bind(this),this._plugins.push(e),this._plugins.sort((e,t)=>e.priority-t.priority),this._codeInjectionPoints={};let i={};for(let e of(i[l_._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0},this._plugins))e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.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;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null}_handlePluginEventIsReadyForSubMesh(e){let t=!0;for(let i of this._activePlugins)t=t&&i.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh);e.isReadyForSubMesh=t}_handlePluginEventPrepareDefinesBeforeAttributes(e){for(let t of this._activePlugins)t.prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)}_handlePluginEventPrepareDefines(e){for(let t of this._activePlugins)t.prepareDefines(e.defines,this._scene,e.mesh)}_handlePluginEventHardBindForSubMesh(e){for(let t of this._activePluginsForExtraEvents)t.hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventBindForSubMesh(e){for(let t of this._activePlugins)t.bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventHasRenderTargetTextures(e){let t=!1;for(let e of this._activePluginsForExtraEvents)if(t=e.hasRenderTargetTextures())break;e.hasRenderTargetTextures=t}_handlePluginEventFillRenderTargetTextures(e){for(let t of this._activePluginsForExtraEvents)t.fillRenderTargetTextures(e.renderTargets)}_handlePluginEvent(e,t){var i;switch(e){case oc.S.GetActiveTextures:for(let e of this._activePlugins)e.getActiveTextures(t.activeTextures);break;case oc.S.GetAnimatables:for(let e of this._activePlugins)e.getAnimatables(t.animatables);break;case oc.S.HasTexture:{let e=!1;for(let i of this._activePlugins)if(e=i.hasTexture(t.texture))break;t.hasTexture=e;break}case oc.S.Disposed:for(let e of this._plugins)e.dispose(t.forceDisposeTextures);break;case oc.S.GetDefineNames:t.defineNames=this._defineNamesFromPlugins;break;case oc.S.PrepareEffect:for(let e of this._activePlugins)t.fallbackRank=e.addFallbacks(t.defines,t.fallbacks,t.fallbackRank),e.getAttributes(t.attributes,this._scene,t.mesh);this._uniformList.length>0&&t.uniforms.push(...this._uniformList),this._samplerList.length>0&&t.samplers.push(...this._samplerList),this._uboList.length>0&&t.uniformBuffersNames.push(...this._uboList),t.customCode=this._injectCustomCode(t,t.customCode);break;case oc.S.PrepareUniformBuffer:for(let e of(this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[],this._plugins)){let r=e.getUniforms();if(r){if(r.ubo)for(let e of r.ubo){if(e.size&&e.type){let r=null!==(i=e.arraySize)&&void 0!==i?i:0;t.ubo.addUniform(e.name,e.size,r),this._uboDeclaration+=`${e.type} ${e.name}${r>0?`[${r}]`:""}; -`}this._uniformList.push(e.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\n")}e.getSamplers(this._samplerList),e.getUniformBuffersNames(this._uboList)}}}_collectPointNames(e,t){if(t)for(let i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var s,n;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));let a=null===(s=this._codeInjectionPoints)||void 0===s?void 0:s[i];if(!a)return r;let o=null;for(let t in a){let s="";for(let r of this._activePlugins){let a=null===(n=r.getCustomCode(i))||void 0===n?void 0:n[t];if(a){if(r.resolveIncludes){if(null===o){let t=nd.x.GLSL;o={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:no.v.GetShadersRepository(t),includesShadersStore:no.v.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}o.isFragment="fragment"===i,ld.L._ProcessIncludes(a,o,e=>a=e)}s+=a+"\n"}}if(s.length>0){if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{let i=lp.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}0>e.indexOf("g")&&(e+="g");let i=r,n=new RegExp(t,e),a=n.exec(i);for(;null!==a;){let e=s;for(let t=0;t<a.length;++t)e=e.replace("$"+t,a[t]);r=r.replace(a[0],e),a=n.exec(i)}}else{let e="#define "+t;r=r.replace(e,"\n"+s+"\n"+e)}}}return r}}}l_._MaterialPluginClassToMainDefine={},l_._MaterialPluginCounter=0,rp.l.OnEnginesDisposedObservable.add(()=>{lf.length=0,sX.F.OnEventObservable.remove(lm),lm=null});let lf=[],lm=null;class lg{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,r,s=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new l_(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(let t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;let 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){rg.p4.Clone(()=>e,this)}serialize(){return rg.p4.Serialize(this)}parse(e,t,i){rg.p4.Parse(()=>this,e,t,i)}}(0,r0.gn)([(0,rg.qC)()],lg.prototype,"name",void 0),(0,r0.gn)([(0,rg.qC)()],lg.prototype,"priority",void 0),(0,r0.gn)([(0,rg.qC)()],lg.prototype,"resolveIncludes",void 0),(0,r0.gn)([(0,rg.qC)()],lg.prototype,"registerForExtraEvents",void 0);class lv extends s$.H{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class lT extends lg{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new lv,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=sX.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||!od.DetailTextureEnabled||!!this._texture.isReady()}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;let i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&od.DetailTextureEnabled&&this._isEnabled?(s3.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;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||!this._texture||!od.DetailTextureEnabled||(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),s3.G.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&od.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,r0.gn)([(0,rg.oU)("detailTexture"),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lT.prototype,"texture",void 0),(0,r0.gn)([(0,rg.qC)()],lT.prototype,"diffuseBlendLevel",void 0),(0,r0.gn)([(0,rg.qC)()],lT.prototype,"roughnessBlendLevel",void 0),(0,r0.gn)([(0,rg.qC)()],lT.prototype,"bumpLevel",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lT.prototype,"normalBlendMethod",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lT.prototype,"isEnabled",void 0);var lx=i(7138);let lS={effect:null,subMesh:null};class lE extends s$.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.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){for(let t of["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"])this[t]=t===e}}class lC extends sY{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new rs.Wo(0,0,0),this.diffuseColor=new rs.Wo(1,1,1),this.specularColor=new rs.Wo(1,1,1),this.emissiveColor=new rs.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._applyDecalMapAfterDetailMap=!1,this._renderTargets=new na.t(16),this._worldViewProjectionMatrix=rr.y3.Zero(),this._globalAmbientColor=new rs.Wo(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new lT(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new ou,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),lC.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),lC.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!!lC.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||!!lC.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===sX.F.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==sX.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(oc.S.GetDefineNames,this._eventInfo),t.materialDefines=new lE(this._eventInfo.defineNames));let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();s._needNormals=s3.G.PrepareDefinesForLights(r,e,s,!0,this._maxSimultaneousLights,this._disableLighting),s3.G.PrepareDefinesForMultiview(r,s);let a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(s3.G.PrepareDefinesForPrePass(r,s,this.canRenderToMRT&&!a),s3.G.PrepareDefinesForOIT(r,s,a),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(r.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&&lC.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;s3.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&lC.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;s3.G.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&lC.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;s3.G.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&lC.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===sv.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 sv.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case sv.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case sv.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case sv.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case sv.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case sv.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case sv.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case sv.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case sv.CUBIC_MODE:case sv.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&&lC.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;s3.G.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&lC.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;s3.G.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&lC.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;s3.G.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&lC.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;s3.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&&lC.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&&(lC.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),s3.G.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s,this._applyDecalMapAfterDetailMap),s3.G.PrepareDefinesForFrameBoundValues(r,n,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),s3.G.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let o=!1;if(s.isDirty){let i=s._areLightsDisposed;s.markAsProcessed();let a=new nn;s.REFLECTION&&a.addFallback(0,"REFLECTION"),s.SPECULAR&&a.addFallback(0,"SPECULAR"),s.BUMP&&a.addFallback(0,"BUMP"),s.PARALLAX&&a.addFallback(1,"PARALLAX"),s.PARALLAXOCCLUSION&&a.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&a.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&a.addFallback(1,"FOG"),s.POINTSIZE&&a.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&a.addFallback(0,"LOGARITHMICDEPTH"),s3.G.HandleFallbacksForShadows(s,a,this._maxSimultaneousLights),s.SPECULARTERM&&a.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&a.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&a.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&a.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&a.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&a.addFallback(4,"FRESNEL"),s.MULTIVIEW&&a.addFallback(0,"MULTIVIEW");let l=[rQ.o.PositionKind];s.NORMAL&&l.push(rQ.o.NormalKind),s.TANGENT&&l.push(rQ.o.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(rQ.o.ColorKind),s3.G.PrepareAttributesForBones(l,e,s,a),s3.G.PrepareAttributesForInstances(l,s),s3.G.PrepareAttributesForMorphTargets(l,e,s),s3.G.PrepareAttributesForBakedVertexAnimation(l,e,s);let h="default",u=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],c=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],p={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=a,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=u,this._eventInfo.attributes=l,this._eventInfo.samplers=c,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=p,this._callbackPluginEventGeneric(oc.S.PrepareEffect,this._eventInfo),ou.AddUniforms(u),ou.AddSamplers(c),ng.$&&(ng.$.PrepareUniforms(u,s),ng.$.PrepareSamplers(c,s)),s3.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:d,samplers:c,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),(0,lx.qx)(u);let _={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,u,d,c,s,l,_));let f=s.toString(),m=t.effect,g=r.getEngine().createEffect(h,{attributes:l,uniformsNames:u,uniformBuffersNames:d,samplers:c,defines:f,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError,indexParameters:p,processFinalCode:_.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},n);if(this._eventInfo.customCode=void 0,g){if(this._onEffectCreatedObservable&&(lS.effect=g,lS.subMesh=t,this._onEffectCreatedObservable.notifyObservers(lS)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,s.markAsUnprocessed(),o=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!o,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let 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 r;let s=this.getScene(),n=i.materialDefines;if(!n)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let o=a._forceRebindOnNextCall||this._mustRebind(s,a,t.visibility);s3.G.BindBonesParameters(t,a);let l=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!l.useUbo||!this.isFrozen||!l.isSync||a._forceRebindOnNextCall){if(lC.FresnelEnabled&&n.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new rs.Wo(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&lC.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),s3.G.BindTextureMatrix(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&lC.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),s3.G.BindTextureMatrix(this._ambientTexture,l,"ambient")),this._opacityTexture&&lC.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),s3.G.BindTextureMatrix(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&lC.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){let e=this._reflectionTexture;l.updateVector3("vReflectionPosition",e.boundingBoxPosition),l.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&lC.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),s3.G.BindTextureMatrix(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&lC.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),s3.G.BindTextureMatrix(this._lightmapTexture,l,"lightmap")),this._specularTexture&&lC.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),s3.G.BindTextureMatrix(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&lC.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),s3.G.BindTextureMatrix(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&lC.RefractionTextureEnabled){let e=1;if(!this._refractionTexture.isCube&&(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){let e=this._refractionTexture;l.updateVector3("vRefractionPosition",e.boundingBoxPosition),l.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),n.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",lC.EmissiveTextureEnabled?this.emissiveColor:rs.Wo.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&lC.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&lC.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&lC.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&lC.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&lC.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&lC.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&lC.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&lC.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&lC.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,lx.an)(a,this,s),this.bindEyePosition(a)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&s3.G.BindLights(s,t,a,n,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==rI.x.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(a),s3.G.BindFogParameters(s,t,a),n.NUM_MORPH_INFLUENCERS&&s3.G.BindMorphTargetParameters(t,a),n.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(r=t.bakedVertexAnimationManager)||void 0===r||r.bind(a,n.INSTANCES)),this.useLogarithmicDepth&&s3.G.BindLogDepth(n,a,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),l.update()}getAnimatables(){let 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(){let 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,r,s,n,a,o,l,h,u;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(n=this._reflectionTexture)||void 0===n||n.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._specularTexture)||void 0===o||o.dispose(),null===(l=this._bumpTexture)||void 0===l||l.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(u=this._refractionTexture)||void 0===u||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){let r=rg.p4.Clone(()=>new lC(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){let r=rg.p4.Parse(()=>new lC(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),sX.F._parsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return od.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){od.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return od.DetailTextureEnabled}static set DetailTextureEnabled(e){od.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return od.AmbientTextureEnabled}static set AmbientTextureEnabled(e){od.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return od.OpacityTextureEnabled}static set OpacityTextureEnabled(e){od.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return od.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){od.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return od.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){od.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return od.SpecularTextureEnabled}static set SpecularTextureEnabled(e){od.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return od.BumpTextureEnabled}static set BumpTextureEnabled(e){od.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return od.LightmapTextureEnabled}static set LightmapTextureEnabled(e){od.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return od.RefractionTextureEnabled}static set RefractionTextureEnabled(e){od.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return od.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){od.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return od.FresnelEnabled}static set FresnelEnabled(e){od.FresnelEnabled=e}}(0,r0.gn)([(0,rg.oU)("diffuseTexture")],lC.prototype,"_diffuseTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],lC.prototype,"diffuseTexture",void 0),(0,r0.gn)([(0,rg.oU)("ambientTexture")],lC.prototype,"_ambientTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"ambientTexture",void 0),(0,r0.gn)([(0,rg.oU)("opacityTexture")],lC.prototype,"_opacityTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],lC.prototype,"opacityTexture",void 0),(0,r0.gn)([(0,rg.oU)("reflectionTexture")],lC.prototype,"_reflectionTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"reflectionTexture",void 0),(0,r0.gn)([(0,rg.oU)("emissiveTexture")],lC.prototype,"_emissiveTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"emissiveTexture",void 0),(0,r0.gn)([(0,rg.oU)("specularTexture")],lC.prototype,"_specularTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"specularTexture",void 0),(0,r0.gn)([(0,rg.oU)("bumpTexture")],lC.prototype,"_bumpTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"bumpTexture",void 0),(0,r0.gn)([(0,rg.oU)("lightmapTexture")],lC.prototype,"_lightmapTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"lightmapTexture",void 0),(0,r0.gn)([(0,rg.oU)("refractionTexture")],lC.prototype,"_refractionTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"refractionTexture",void 0),(0,r0.gn)([(0,rg.n9)("ambient")],lC.prototype,"ambientColor",void 0),(0,r0.gn)([(0,rg.n9)("diffuse")],lC.prototype,"diffuseColor",void 0),(0,r0.gn)([(0,rg.n9)("specular")],lC.prototype,"specularColor",void 0),(0,r0.gn)([(0,rg.n9)("emissive")],lC.prototype,"emissiveColor",void 0),(0,r0.gn)([(0,rg.qC)()],lC.prototype,"specularPower",void 0),(0,r0.gn)([(0,rg.qC)("useAlphaFromDiffuseTexture")],lC.prototype,"_useAlphaFromDiffuseTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],lC.prototype,"useAlphaFromDiffuseTexture",void 0),(0,r0.gn)([(0,rg.qC)("useEmissiveAsIllumination")],lC.prototype,"_useEmissiveAsIllumination",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"useEmissiveAsIllumination",void 0),(0,r0.gn)([(0,rg.qC)("linkEmissiveWithDiffuse")],lC.prototype,"_linkEmissiveWithDiffuse",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"linkEmissiveWithDiffuse",void 0),(0,r0.gn)([(0,rg.qC)("useSpecularOverAlpha")],lC.prototype,"_useSpecularOverAlpha",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"useSpecularOverAlpha",void 0),(0,r0.gn)([(0,rg.qC)("useReflectionOverAlpha")],lC.prototype,"_useReflectionOverAlpha",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"useReflectionOverAlpha",void 0),(0,r0.gn)([(0,rg.qC)("disableLighting")],lC.prototype,"_disableLighting",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsLightsDirty")],lC.prototype,"disableLighting",void 0),(0,r0.gn)([(0,rg.qC)("useObjectSpaceNormalMap")],lC.prototype,"_useObjectSpaceNormalMap",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"useObjectSpaceNormalMap",void 0),(0,r0.gn)([(0,rg.qC)("useParallax")],lC.prototype,"_useParallax",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"useParallax",void 0),(0,r0.gn)([(0,rg.qC)("useParallaxOcclusion")],lC.prototype,"_useParallaxOcclusion",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"useParallaxOcclusion",void 0),(0,r0.gn)([(0,rg.qC)()],lC.prototype,"parallaxScaleBias",void 0),(0,r0.gn)([(0,rg.qC)("roughness")],lC.prototype,"_roughness",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"roughness",void 0),(0,r0.gn)([(0,rg.qC)()],lC.prototype,"indexOfRefraction",void 0),(0,r0.gn)([(0,rg.qC)()],lC.prototype,"invertRefractionY",void 0),(0,r0.gn)([(0,rg.qC)()],lC.prototype,"alphaCutOff",void 0),(0,r0.gn)([(0,rg.qC)("useLightmapAsShadowmap")],lC.prototype,"_useLightmapAsShadowmap",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"useLightmapAsShadowmap",void 0),(0,r0.gn)([(0,rg.qQ)("diffuseFresnelParameters")],lC.prototype,"_diffuseFresnelParameters",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsFresnelDirty")],lC.prototype,"diffuseFresnelParameters",void 0),(0,r0.gn)([(0,rg.qQ)("opacityFresnelParameters")],lC.prototype,"_opacityFresnelParameters",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsFresnelAndMiscDirty")],lC.prototype,"opacityFresnelParameters",void 0),(0,r0.gn)([(0,rg.qQ)("reflectionFresnelParameters")],lC.prototype,"_reflectionFresnelParameters",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsFresnelDirty")],lC.prototype,"reflectionFresnelParameters",void 0),(0,r0.gn)([(0,rg.qQ)("refractionFresnelParameters")],lC.prototype,"_refractionFresnelParameters",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsFresnelDirty")],lC.prototype,"refractionFresnelParameters",void 0),(0,r0.gn)([(0,rg.qQ)("emissiveFresnelParameters")],lC.prototype,"_emissiveFresnelParameters",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsFresnelDirty")],lC.prototype,"emissiveFresnelParameters",void 0),(0,r0.gn)([(0,rg.qC)("useReflectionFresnelFromSpecular")],lC.prototype,"_useReflectionFresnelFromSpecular",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsFresnelDirty")],lC.prototype,"useReflectionFresnelFromSpecular",void 0),(0,r0.gn)([(0,rg.qC)("useGlossinessFromSpecularMapAlpha")],lC.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"useGlossinessFromSpecularMapAlpha",void 0),(0,r0.gn)([(0,rg.qC)("maxSimultaneousLights")],lC.prototype,"_maxSimultaneousLights",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsLightsDirty")],lC.prototype,"maxSimultaneousLights",void 0),(0,r0.gn)([(0,rg.qC)("invertNormalMapX")],lC.prototype,"_invertNormalMapX",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"invertNormalMapX",void 0),(0,r0.gn)([(0,rg.qC)("invertNormalMapY")],lC.prototype,"_invertNormalMapY",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"invertNormalMapY",void 0),(0,r0.gn)([(0,rg.qC)("twoSidedLighting")],lC.prototype,"_twoSidedLighting",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],lC.prototype,"twoSidedLighting",void 0),(0,r0.gn)([(0,rg.qC)("applyDecalMapAfterDetailMap")],lC.prototype,"_applyDecalMapAfterDetailMap",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsMiscDirty")],lC.prototype,"applyDecalMapAfterDetailMap",void 0),(0,r0.gn)([(0,rg.qC)()],lC.prototype,"useLogarithmicDepth",null),(0,rn.H)("BABYLON.StandardMaterial",lC),rI.x.DefaultMaterialFactory=e=>new lC("default material",e),sx.B.prototype.createDynamicTexture=function(e,t,i,r){let s=new sT.l(this,sT.S.Dynamic);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?sx.B.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?sx.B.GetExponentOfTwo(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=r,this.updateTextureSamplingMode(r,s),this._internalTexturesCache.push(s),s},sx.B.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,n=!1,a=!1){if(!e)return;let o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);let u=this._getWebGLTextureType(e.type),c=this._getInternalFormat(s||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,c);o.texImage2D(l,0,d,c,u,t),e.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0};class lb extends sv{constructor(e,t,i=null,r=!1,s=3,n=5,a){super(null,i,!r,a,s,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=sv.CLAMP_ADDRESSMODE,this.wrapV=sv.CLAMP_ADDRESSMODE,this._generateMipMaps=r;let o=this._getEngine();if(!o)return;t.getContext?(this._canvas=t,this._texture=o.createDynamicTexture(t.width,t.height,r,s)):(this._canvas=o.createCanvas(1,1),t.width||0===t.width?this._texture=o.createDynamicTexture(t.width,t.height,r,s):this._texture=o.createDynamicTexture(t,t,r,s));let 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){let t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){let i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(){let 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,r,s,n,a,o=!0){let l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null==t){let i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){let e=parseInt(r.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),o&&this.update(a)}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new lb(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(){let e=this.getScene();e&&!e.isReady()&&ru.Y.Warn("The scene must be ready before serializing the dynamic texture");let t=super.serialize();return lb._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()}}let ly=`varying vec2 vUV;uniform sampler2D textureSampler; -#include<imageProcessingDeclaration> -#include<helperFunctions> -#include<imageProcessingFunctions> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 result=texture2D(textureSampler,vUV); -#ifdef IMAGEPROCESSING -#ifndef FROMLINEARSPACE -result.rgb=toLinearSpace(result.rgb); -#endif -result=applyImageProcessing(result); -#else -#ifdef FROMLINEARSPACE -result=applyImageProcessing(result); -#endif -#endif -gl_FragColor=result;}`;no.v.ShadersStore.imageProcessingPixelShader=ly;class lA extends np{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,t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){let i=t.scenes;e=i[i.length-1]}else e=rp.l.LastCreatedScene;e?this._imageProcessingConfiguration=e.imageProcessingConfiguration:this._imageProcessingConfiguration=new ng.$}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get isSupported(){let e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,s,n,a=0,o){super(e,"imageProcessing",[],[],t,i,r,s,n,null,a,"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},o?(o.applyByPostProcess=!0,this._attachImageProcessingConfiguration(o,!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(let t in this._defines)this._defines[t]&&(e+=`#define ${t}; -`);let t=["textureSampler"],i=["scale"];ng.$&&(ng.$.PrepareSamplers(t,this._defines),ng.$.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,r0.gn)([(0,rg.qC)()],lA.prototype,"_fromLinearSpace",void 0);class lR{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){this.isFixedFoveationSupported&&(this.layer.fixedFoveation=Math.max(0,Math.min(1,e||0)))}constructor(e,t,i,r,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.createRenderTargetTextureProvider=s}}var lP=i(9123);class lI{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=[],this._engine=e.getEngine()}_createInternalTexture(e,t){let i=new sT.l(this._engine,sT.S.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new lP.B(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,s,n){if(!this._engine)throw Error("Engine is disposed");let a={width:e,height:t},o=n?new a7(this._scene,a):new nV("XR renderTargetTexture",a,this._scene),l=o.renderTarget;if(l._samples=o.samples,(i||!r)&&(l._framebuffer=i),r){if(n)l._colorTextureArray=r;else{let e=this._createInternalTexture(a,r);l.setTexture(e,0),o._texture=e}}return s&&(n?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(a,s)),o.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(o.skipInitialClear=!0),this._renderTargetTextures.push(o),o}_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 lM extends lR{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new lD(e.scene,this)),this.layer=e}}class lD extends lI{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){let i=this._layer.getViewport(t);if(!i)return!1;let r=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/s,e.width=i.width/r,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){let t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&r===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class lO{static GetDefaults(e){let t=new lO;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 lN{constructor(e,t=lO.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new ri.y$,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{let 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){let t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new lM(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{rZ.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 lF extends lR{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new lL(e,this)),this.layer=e}}class lL extends lI{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 lw{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 lB{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new ri.y$,this.onXRReferenceSpaceChanged=new ri.y$,this.onXRSessionEnded=new ri.y$,this.onXRSessionInit=new ri.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(()=>{ru.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){let t=this.scene.getEngine();return this._xrNavigator.xr.native?new lw(this):((e=e||lO.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new lN(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 lB.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=>(ru.Y.Error("XR.requestReferenceSpace failed for the following reason: "),ru.Y.Error(e),ru.Y.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(e=>{let t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)},e=>{throw ru.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 lF(e.baseLayer):new lM(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);let t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(e=>Promise.resolve(void 0===e||e)).catch(e=>(ru.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){this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=Math.max(0,Math.min(1,e||0)))}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 lU(e){let t,i,r,s,n,a,o;let l=e.height||2,h=0===e.diameterTop?0:e.diameterTop||e.diameter||1,u=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;h=h||1e-5,u=u||1e-5;let c=0|(e.tessellation||24),d=0|(e.subdivisions||1),p=!!e.hasRings,_=!!e.enclose,f=0===e.cap?0:e.cap||rq.Kj.CAP_ALL,m=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,g=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE,v=e.faceUV||[,,,],T=e.faceColors,x=2+(1+(1!==m&&_?2:0))*(p?d:1);for(t=0;t<x;t++)T&&void 0===T[t]&&(T[t]=new rs.HE(1,1,1,1));for(t=0;t<x;t++)v&&void 0===v[t]&&(v[t]=new rr.Lt(0,0,1,1));let S=[],E=[],C=[],b=[],y=[],A=2*Math.PI*m/c,R=(u-h)/2/l,P=rr.P.Zero(),I=rr.P.Zero(),M=rr.P.Zero(),D=rr.P.Zero(),O=rr.P.Zero(),N=rO.RD.Y,F=1,L=1,w=0,B=0;for(n=0;n<=d;n++)for(o=0,s=((r=n/d)*(h-u)+u)/2,F=p&&0!==n&&n!==d?2:1;o<F;o++){for(p&&(L+=o),_&&(L+=2*o),a=0;a<=c;a++)i=a*A,P.x=Math.cos(-i)*s,P.y=-l/2+r*l,P.z=Math.sin(-i)*s,0===h&&n===d?(I.x=C[C.length-(c+1)*3],I.y=C[C.length-(c+1)*3+1],I.z=C[C.length-(c+1)*3+2]):(I.x=P.x,I.z=P.z,I.y=Math.sqrt(I.x*I.x+I.z*I.z)*R,I.normalize()),0===a&&(M.copyFrom(P),D.copyFrom(I)),E.push(P.x,P.y,P.z),C.push(I.x,I.y,I.z),B=p?w!==L?v[L].y:v[L].w:v[L].y+(v[L].w-v[L].y)*r,b.push(v[L].x+(v[L].z-v[L].x)*a/c,sg.e.UseOpenGLOrientationForUV?1-B:B),T&&y.push(T[L].r,T[L].g,T[L].b,T[L].a);1!==m&&_&&(E.push(P.x,P.y,P.z),E.push(0,P.y,0),E.push(0,P.y,0),E.push(M.x,M.y,M.z),rr.P.CrossToRef(N,I,O),O.normalize(),C.push(O.x,O.y,O.z,O.x,O.y,O.z),rr.P.CrossToRef(D,N,O),O.normalize(),C.push(O.x,O.y,O.z,O.x,O.y,O.z),B=p?w!==L?v[L+1].y:v[L+1].w:v[L+1].y+(v[L+1].w-v[L+1].y)*r,b.push(v[L+1].x,sg.e.UseOpenGLOrientationForUV?1-B:B),b.push(v[L+1].z,sg.e.UseOpenGLOrientationForUV?1-B:B),B=p?w!==L?v[L+2].y:v[L+2].w:v[L+2].y+(v[L+2].w-v[L+2].y)*r,b.push(v[L+2].x,sg.e.UseOpenGLOrientationForUV?1-B:B),b.push(v[L+2].z,sg.e.UseOpenGLOrientationForUV?1-B:B),T&&(y.push(T[L+1].r,T[L+1].g,T[L+1].b,T[L+1].a),y.push(T[L+1].r,T[L+1].g,T[L+1].b,T[L+1].a),y.push(T[L+2].r,T[L+2].g,T[L+2].b,T[L+2].a),y.push(T[L+2].r,T[L+2].g,T[L+2].b,T[L+2].a))),w!==L&&(w=L)}let U=1!==m&&_?c+4:c;for(L=0,n=0;L<d;L++){let e=0,t=0,i=0,r=0;for(a=0;a<c;a++)e=n*(U+1)+a,t=(n+1)*(U+1)+a,i=n*(U+1)+(a+1),r=(n+1)*(U+1)+(a+1),S.push(e,t,i),S.push(r,i,t);1!==m&&_&&(S.push(e+2,t+2,i+2),S.push(r+2,i+2,t+2),S.push(e+4,t+4,i+4),S.push(r+4,i+4,t+4)),n=p?n+2:n+1}let V=e=>{let t,i,r;let s=e?h/2:u/2;if(0===s)return;let n=e?v[x-1]:v[0],a=null;T&&(a=e?T[x-1]:T[0]);let o=E.length/3,d=e?l/2:-l/2,p=new rr.P(0,d,0);E.push(p.x,p.y,p.z),C.push(0,e?1:-1,0);let _=n.y+(n.w-n.y)*.5;b.push(n.x+(n.z-n.x)*.5,sg.e.UseOpenGLOrientationForUV?1-_:_),a&&y.push(a.r,a.g,a.b,a.a);let f=new rr.FM(.5,.5);for(r=0;r<=c;r++){t=2*Math.PI*r*m/c;let o=Math.cos(-t),l=Math.sin(-t);i=new rr.P(o*s,d,l*s);let h=new rr.FM(o*f.x+.5,l*f.y+.5);E.push(i.x,i.y,i.z),C.push(0,e?1:-1,0);let u=n.y+(n.w-n.y)*h.y;b.push(n.x+(n.z-n.x)*h.x,sg.e.UseOpenGLOrientationForUV?1-u:u),a&&y.push(a.r,a.g,a.b,a.a)}for(r=0;r<c;r++)e?(S.push(o),S.push(o+(r+2)),S.push(o+(r+1))):(S.push(o),S.push(o+(r+1)),S.push(o+(r+2)))};(f===rq.Kj.CAP_START||f===rq.Kj.CAP_ALL)&&V(!1),(f===rq.Kj.CAP_END||f===rq.Kj.CAP_ALL)&&V(!0),sN.x._ComputeSides(g,E,S,C,b,e.frontUVs,e.backUVs);let k=new sN.x;return k.indices=S,k.positions=E,k.normals=C,k.uvs=b,T&&(k.colors=y),k}function lV(e,t={},i){let r=new rq.Kj(e,i);t.sideOrientation=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=lU(t);return s.applyToMesh(r,t.updatable),r}function lk(e){let t=[],i=[],r=[],s=[],n=e.diameter||1,a=e.thickness||.5,o=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE,h=o+1;for(let e=0;e<=o;e++){let l=e/o,u=e*Math.PI*2/o-Math.PI/2,c=rr.y3.Translation(n/2,0,0).multiply(rr.y3.RotationY(u));for(let n=0;n<=o;n++){let u=1-n/o,d=n*Math.PI*2/o+Math.PI,p=Math.cos(d),_=Math.sin(d),f=new rr.P(p,_,0),m=f.scale(a/2),g=new rr.FM(l,u);m=rr.P.TransformCoordinates(m,c),f=rr.P.TransformNormal(f,c),i.push(m.x,m.y,m.z),r.push(f.x,f.y,f.z),s.push(g.x,sg.e.UseOpenGLOrientationForUV?1-g.y:g.y);let v=(e+1)%h,T=(n+1)%h;t.push(e*h+n),t.push(e*h+T),t.push(v*h+n),t.push(e*h+T),t.push(v*h+T),t.push(v*h+n)}}sN.x._ComputeSides(l,i,t,r,s,e.frontUVs,e.backUVs);let u=new sN.x;return u.indices=t,u.positions=i,u.normals=r,u.uvs=s,u}function lG(e,t={},i){let r=new rq.Kj(e,i);t.sideOrientation=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=lk(t);return s.applyToMesh(r,t.updatable),r}(D=tD||(tD={}))[D.ENTERING_XR=0]="ENTERING_XR",D[D.EXITING_XR=1]="EXITING_XR",D[D.IN_XR=2]="IN_XR",D[D.NOT_IN_XR=3]="NOT_IN_XR",(O=tO||(tO={}))[O.NOT_TRACKING=0]="NOT_TRACKING",O[O.TRACKING_LOST=1]="TRACKING_LOST",O[O.TRACKING=2]="TRACKING",sN.x.CreateCylinder=lU,rq.Kj.CreateCylinder=(e,t,i,r,s,n,a,o,l)=>{void 0!==a&&a instanceof rI.x||(void 0!==a&&(l=o||rq.Kj.DEFAULTSIDE,o=a),a=n,n=1);let h={height:t,diameterTop:i,diameterBottom:r,tessellation:s,subdivisions:n,sideOrientation:l,updatable:o};return lV(e,h,a)},sN.x.CreateTorus=lk,rq.Kj.CreateTorus=(e,t,i,r,s,n,a)=>lG(e,{diameter:t,thickness:i,tessellation:r,sideOrientation:a,updatable:n},s),rq.Kj._GroundMeshParser=(e,t)=>lz.Parse(e,t);class lz extends rq.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),this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){let i=this.getWorldMatrix(),r=rr.jp.Matrix[5];i.invertToRef(r);let s=rr.jp.Vector3[8];if(rr.P.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return rr.P.TransformCoordinatesFromFloatsToRef(0,a,0,i,s),s.y}getNormalAtCoordinates(e,t){let i=new rr.P(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){let r=this.getWorldMatrix(),s=rr.jp.Matrix[5];r.invertToRef(s);let n=rr.jp.Vector3[8];if(rr.P.TransformCoordinatesFromFloatsToRef(e,0,t,s,n),e=n.x,t=n.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let a=this._getFacetAt(e,t);return rr.P.TransformNormalFromFloatsToRef(a.x,a.y,a.z,r,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){let i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i];return t<s.slope.x*e+s.slope.y?s.facet1:s.facet2}_initHeightQuads(){let e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=[];for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r={slope:rr.FM.Zero(),facet1:new rr.Lt(0,0,0,0),facet2:new rr.Lt(0,0,0,0)};this._heightQuads[i*e+t]=r}return this}_computeHeightQuads(){let e=this.getVerticesData(rQ.o.PositionKind);if(!e)return this;let t=rr.jp.Vector3[3],i=rr.jp.Vector3[2],r=rr.jp.Vector3[1],s=rr.jp.Vector3[0],n=rr.jp.Vector3[4],a=rr.jp.Vector3[5],o=rr.jp.Vector3[6],l=rr.jp.Vector3[7],h=rr.jp.Vector3[8],u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=this._subdivisionsX,v=this._subdivisionsY;for(let T=0;T<v;T++)for(let v=0;v<g;v++){u=3*v,c=T*(g+1)*3,d=(T+1)*(g+1)*3,t.x=e[c+u],t.y=e[c+u+1],t.z=e[c+u+2],i.x=e[c+u+3],i.y=e[c+u+4],i.z=e[c+u+5],r.x=e[d+u],r.y=e[d+u+1],r.z=e[d+u+2],s.x=e[d+u+3],s.y=e[d+u+4],s.z=e[d+u+5],p=(s.z-t.z)/(s.x-t.x),_=t.z-p*t.x,i.subtractToRef(t,n),r.subtractToRef(t,a),s.subtractToRef(t,o),rr.P.CrossToRef(o,a,l),rr.P.CrossToRef(n,o,h),l.normalize(),h.normalize(),f=-(l.x*t.x+l.y*t.y+l.z*t.z),m=-(h.x*i.x+h.y*i.y+h.z*i.z);let x=this._heightQuads[T*g+v];x.slope.copyFromFloats(p,_),x.facet1.copyFromFloats(l.x,l.y,l.z,f),x.facet2.copyFromFloats(h.x,h.y,h.z,m)}return this}serialize(e){super.serialize(e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height}static Parse(e,t){let i=new lz(e.name,t);return i._subdivisionsX=e.subdivisionsX||1,i._subdivisionsY=e.subdivisionsY||1,i._minX=e.minX,i._maxX=e.maxX,i._minZ=e.minZ,i._maxZ=e.maxZ,i._width=e.width,i._height=e.height,i}}function lW(e){let t,i;let r=[],s=[],n=[],a=[],o=e.width||1,l=e.height||1,h=0|(e.subdivisionsX||e.subdivisions||1),u=0|(e.subdivisionsY||e.subdivisions||1);for(t=0;t<=u;t++)for(i=0;i<=h;i++){let e=new rr.P(i*o/h-o/2,0,(u-t)*l/u-l/2),r=new rr.P(0,1,0);s.push(e.x,e.y,e.z),n.push(r.x,r.y,r.z),a.push(i/h,sg.e.UseOpenGLOrientationForUV?t/u:1-t/u)}for(t=0;t<u;t++)for(i=0;i<h;i++)r.push(i+1+(t+1)*(h+1)),r.push(i+1+t*(h+1)),r.push(i+t*(h+1)),r.push(i+(t+1)*(h+1)),r.push(i+1+(t+1)*(h+1)),r.push(i+t*(h+1));let c=new sN.x;return c.indices=r,c.positions=s,c.normals=n,c.uvs=a,c}function lH(e){let t,i,r,s;let n=void 0!==e.xmin&&null!==e.xmin?e.xmin:-1,a=void 0!==e.zmin&&null!==e.zmin?e.zmin:-1,o=void 0!==e.xmax&&null!==e.xmax?e.xmax:1,l=void 0!==e.zmax&&null!==e.zmax?e.zmax:1,h=e.subdivisions||{w:1,h:1},u=e.precision||{w:1,h:1},c=[],d=[],p=[],_=[];h.h=h.h<1?1:h.h,h.w=h.w<1?1:h.w,u.w=u.w<1?1:u.w,u.h=u.h<1?1:u.h;let f={w:(o-n)/h.w,h:(l-a)/h.h};for(r=0;r<h.h;r++)for(s=0;s<h.w;s++)!function(e,r,s,n){let a=d.length/3,o=u.w+1;for(t=0;t<u.h;t++)for(i=0;i<u.w;i++){let e=[a+i+t*o,a+(i+1)+t*o,a+(i+1)+(t+1)*o,a+i+(t+1)*o];c.push(e[1]),c.push(e[2]),c.push(e[3]),c.push(e[0]),c.push(e[1]),c.push(e[3])}let l=rr.P.Zero(),h=new rr.P(0,1,0);for(t=0;t<=u.h;t++)for(i=0,l.z=t*(n-r)/u.h+r;i<=u.w;i++)l.x=i*(s-e)/u.w+e,l.y=0,d.push(l.x,l.y,l.z),p.push(h.x,h.y,h.z),_.push(i/u.w,t/u.h)}(n+s*f.w,a+r*f.h,n+(s+1)*f.w,a+(r+1)*f.h);let m=new sN.x;return m.indices=c,m.positions=d,m.normals=p,m.uvs=_,m}function lX(e){let t,i;let r=[],s=[],n=[],a=[],o=e.colorFilter||new rs.Wo(.3,.59,.11),l=e.alphaFilter||0,h=!1;if(e.minHeight>e.maxHeight){h=!0;let t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(t=0;t<=e.subdivisions;t++)for(i=0;i<=e.subdivisions;i++){let r=new rr.P(i*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-t)*e.height/e.subdivisions-e.height/2),u=(r.x+e.width/2)/e.width*(e.bufferWidth-1)|0,c=(1-(r.z+e.height/2)/e.height)*(e.bufferHeight-1)|0,d=(u+c*e.bufferWidth)*4,p=e.buffer[d]/255,_=e.buffer[d+1]/255,f=e.buffer[d+2]/255,m=e.buffer[d+3]/255;h&&(p=1-p,_=1-_,f=1-f);let g=p*o.r+_*o.g+f*o.b;m>=l?r.y=e.minHeight+(e.maxHeight-e.minHeight)*g:r.y=e.minHeight-rL.kn,s.push(r.x,r.y,r.z),n.push(0,0,0),a.push(i/e.subdivisions,1-t/e.subdivisions)}for(t=0;t<e.subdivisions;t++)for(i=0;i<e.subdivisions;i++){let n=i+1+(t+1)*(e.subdivisions+1),a=i+1+t*(e.subdivisions+1),o=i+t*(e.subdivisions+1),l=i+(t+1)*(e.subdivisions+1),h=s[3*n+1]>=e.minHeight,u=s[3*a+1]>=e.minHeight,c=s[3*o+1]>=e.minHeight;h&&u&&c&&(r.push(n),r.push(a),r.push(o));let d=s[3*l+1]>=e.minHeight;d&&h&&c&&(r.push(l),r.push(n),r.push(o))}sN.x.ComputeNormals(s,r,n);let u=new sN.x;return u.indices=r,u.positions=s,u.normals=n,u.uvs=a,u}function lY(e,t={},i){let r=new lz(e,i);r._setReady(!1),r._subdivisionsX=t.subdivisionsX||t.subdivisions||1,r._subdivisionsY=t.subdivisionsY||t.subdivisions||1,r._width=t.width||1,r._height=t.height||1,r._maxX=r._width/2,r._maxZ=r._height/2,r._minX=-r._maxX,r._minZ=-r._maxZ;let s=lW(t);return s.applyToMesh(r,t.updatable),r._setReady(!0),r}sN.x.CreateGround=lW,sN.x.CreateTiledGround=lH,sN.x.CreateGroundFromHeightMap=lX,rq.Kj.CreateGround=(e,t,i,r,s,n)=>lY(e,{width:t,height:i,subdivisions:r,updatable:n},s),rq.Kj.CreateTiledGround=(e,t,i,r,s,n,a,o,l)=>(function(e,t,i=null){let r=new rq.Kj(e,i),s=lH(t);return s.applyToMesh(r,t.updatable),r})(e,{xmin:t,zmin:i,xmax:r,zmax:s,subdivisions:n,precision:a,updatable:l},o),rq.Kj.CreateGroundFromHeightMap=(e,t,i,r,s,n,a,o,l,h,u)=>(function(e,t,i={},r=null){let s=i.width||10,n=i.height||10,a=i.subdivisions||1,o=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new rs.Wo(.3,.59,.11),u=i.alphaFilter||0,c=i.updatable,d=i.onReady;r=r||rp.l.LastCreatedScene;let p=new lz(e,r);return p._subdivisionsX=a,p._subdivisionsY=a,p._width=s,p._height=n,p._maxX=p._width/2,p._maxZ=p._height/2,p._minX=-p._maxX,p._minZ=-p._maxZ,p._setReady(!1),rZ.w1.LoadImage(t,e=>{let t=e.width,i=e.height;if(r.isDisposed)return;let _=null==r?void 0:r.getEngine().resizeImageBitmap(e,t,i),f=lX({width:s,height:n,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:h,buffer:_,bufferWidth:t,bufferHeight:i,alphaFilter:u});f.applyToMesh(p,c),d&&d(p),p._setReady(!0)},()=>{},r.offlineProvider),p})(e,t,{width:i,height:r,subdivisions:s,minHeight:n,maxHeight:a,updatable:l,onReady:h,alphaFilter:u},o);class lj{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=lj._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=lG("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;let t=new lC("targetMat",e);t.specularColor=rs.Wo.Black(),t.emissiveColor=new rs.Wo(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new sD(rr.P.Zero(),new rr.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()}}lj._IdCounter=0;class lq extends lj{constructor(e,t,i){super(t,i),this.webVRController=e,this._laserPointer=lV("laserPointer",{updatable:!1,height:1,diameterTop:.004,diameterBottom:2e-4,tessellation:20,subdivisions:1},t);let r=new lC("laserPointerMat",t);if(r.emissiveColor=new rs.Wo(.7,.7,.7),r.alpha=.6,this._laserPointer.material=r,this._laserPointer.rotation.x=Math.PI/2,this._laserPointer.position.z=-.5,this._laserPointer.isVisible=!1,this._laserPointer.isPickable=!1,!e.mesh){let i=new rq.Kj("preloadControllerMesh",t),r=new rq.Kj(aF.POINTING_POSE,t);r.rotation.x=-.7,i.addChild(r),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){let t=e=>{e.isPickable=!1,e.getChildMeshes().forEach(e=>{t(e)})};t(e);let i=e.getChildren(void 0,!1),r=e;this.webVRController._pointingPoseNode=null;for(let e=0;e<i.length;e++)if(i[e].name&&i[e].name.indexOf(aF.POINTING_POSE)>=0){r=i[e],this.webVRController._pointingPoseNode=r;break}this._laserPointer.parent=r}_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 lK extends lj{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){let t=this._getCamera();return t?t.getForwardRay(e):new sD(rr.P.Zero(),rr.P.Forward())}}class l${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(){let e=this._cameraGazer._teleportationRequestInitiated||null!==this._leftController&&this._leftController._teleportationRequestInitiated||null!==this._rightController&&this._rightController._teleportationRequestInitiated;return e}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 ri.y$,this.onAfterEnteringVRObservable=new ri.y$,this.onExitingVRObservable=new ri.y$,this.onControllerMeshLoadedObservable=new ri.y$,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=l$.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new rr.P(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new rr.P(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._leftController=null,this._rightController=null,this._gazeColor=new rs.Wo(.7,.7,.7),this._laserColor=new rs.Wo(.7,.7,.7),this._pickedLaserColor=new rs.Wo(.2,.2,1),this._pickedGazeColor=new rs.Wo(0,0,1),this.onNewMeshSelected=new ri.y$,this.onMeshSelectedWithController=new ri.y$,this.onNewMeshPicked=new ri.y$,this.onBeforeCameraTeleport=new ri.y$,this.onAfterCameraTeleport=new ri.y$,this.onSelectedMeshUnselected=new ri.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!==n9.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===n9.XBOX&&(e.onbuttondown(e=>{this._interactionsEnabled&&e===tR.A&&this._cameraGazer._selectionPointerDown()}),e.onbuttonup(e=>{this._interactionsEnabled&&e===tR.A&&this._cameraGazer._selectionPointerUp()}));else{let t=new lq(e,this._scene,this._cameraGazer._gazeTracker);"right"===e.hand||this._leftController&&this._leftController.webVRController!=e?this._rightController=t:this._leftController=t,this._tryEnableInteractionOnController(t)}},this._tryEnableInteractionOnController=e=>{this._interactionsRequested&&!e._interactionsEnabled&&this._enableInteractionOnController(e),this._teleportationRequested&&!e._teleportationEnabled&&this._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=e=>{e instanceof oh&&("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=rr.P.Zero(),this._workingQuaternion=rr._f.Identity(),this._workingMatrix=rr.y3.Identity(),ru.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();let i="getVRDisplays"in navigator;if(i||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 rr.P(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new aR("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 aC&&this._scene.activeCamera.rotation)){let e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(rr._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?lB.IsSessionSupportedAsync("immersive-vr").then(i=>{i?(ru.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 lK(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(e=>{switch(e){case tD.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case tD.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case tD.IN_XR:this._hasEnteredVR=!0;break;case tD.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=a4.GetDefault()),t.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new os("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new ol("WebVRHelper",this._position,this._scene,t),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new lK(()=>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=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",t=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); 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) }";t+=".babylonVRicon.vrdisplaypresenting { display: none; }";let i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode?this._scene.getEngine().disableVR():this.enterVR()});let 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())},sy.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 rz,this._circleEase.setEasingMode(rG.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===sy.kD.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===sy.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(e){ru.Y.Warn("Error in your custom logic onControllerMeshLoaded: "+e)}}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===tD.IN_XR||this._webVRpresenting||this._fullscreenVRpresenting}_onVrDisplayPresentChange(){let e=this._scene.getEngine().getVRDevice();if(e){let t=this._webVRpresenting;this._webVRpresenting=e.isPresenting,t&&!this._webVRpresenting&&this.exitVR()}else ru.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){let 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);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){ru.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=rr._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this.webVRCamera){let e=this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y,t=rr._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y,i=this.webVRCamera.rotationQuaternion.toEulerAngles().y;this.webVRCamera.rotationQuaternion=rr._f.FromEulerAngles(0,i+(t-e),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();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){ru.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;let e=this._scene.getEngine();e._onVrDisplayPresentChange&&e._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){this.xr.baseExperience.state===tD.IN_XR&&this.xr.pointerSelection.attach();return}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<this._floorMeshesCollection.length;t++)if(this._floorMeshesCollection[t].id===e.id)return!0;return!!this._floorMeshName&&e.name===this._floorMeshName}addFloorMesh(e){!this._floorMeshesCollection||this._floorMeshesCollection.indexOf(e)>-1||this._floorMeshesCollection.push(e)}removeFloorMesh(e){if(!this._floorMeshesCollection)return;let 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)){let t=e.floorMeshes||[];if(!t.length){let i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr){t.forEach(e=>{this.xr.teleportation.addFloorMesh(e)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}if(!this.xrTestDone){let t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(t);return}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction),null!=this._leftController&&this._enableTeleportationOnController(this._leftController),null!=this._rightController&&this._enableTeleportationOnController(this._rightController);let t=new ng.$;t.vignetteColor=new rs.HE(0,0,0,0),t.vignetteEnabled=!0,this._postProcessMove=new lA("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){let t=e.webVRController.mesh;t&&(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.value<this._padSensibilityDown&&i._selectionPointerUp():t.value>this._padSensibilityUp&&i._selectionPointerDown()}))}_checkTeleportWithRay(e,t){(!this._teleportationRequestInitiated||t._teleportationRequestInitiated)&&(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)<this._padSensibilityDown&&(this._teleportActive&&this.teleportCamera(this._haloCenter),t._teleportationRequestInitiated=!1):e.y<-this._padSensibilityUp&&t._dpadPressed&&(t._activatePointer(),t._teleportationRequestInitiated=!0))}_checkRotate(e,t){!t._teleportationRequestInitiated&&(t._rotationLeftAsked?e.x>-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.x<this._padSensibilityDown&&(t._rotationRightAsked=!1):e.x>this._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=rr._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,rr._f.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),rr.P.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);let r=new sD(i,this._workingVector),s=this._scene.pickWithRay(r,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}}_enableTeleportationOnController(e){let t=e.webVRController.mesh;t&&(e._interactionsEnabled||this._enableInteractionOnController(e),e._interactionsEnabled=!0,e._teleportationEnabled=!0,e.webVRController.controllerType===tA.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=lY("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;let e=new lb("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;let 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();let i=new lC("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;let r=lG("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);r.isPickable=!1,r.parent=this._teleportationTarget;let s=new rE("animationInnerCircle","position.y",30,rE.ANIMATIONTYPE_FLOAT,rE.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),s.setKeys(n);let a=new rH;a.setEasingMode(rG.EASINGMODE_EASEINOUT),s.setEasingFunction(a),r.animations=[],r.animations.push(s),this._scene.beginAnimation(r,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 ab))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];let t=rr._f.FromRotationMatrix(rr.y3.RotationY(Math.PI/4*this._rotationAngle)),i=new rE("animationRotation","rotationQuaternion",90,rE.ANIMATIONTYPE_QUATERNION,rE.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];let s=new rE("animationPP","vignetteWeight",90,rE.ANIMATIONTYPE_FLOAT,rE.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),s.setKeys(n),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);let a=new rE("animationPP2","vignetteStretch",90,rE.ANIMATIONTYPE_FLOAT,rE.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:3,value:10}),o.push({frame:6,value:0}),a.setKeys(o),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));let r=this._convertNormalToDirectionOfRay(e.getNormal(!0,!1),i);if(r){let e=rr.P.Cross(rO.RD.Y,r),t=rr.P.Cross(r,e);rr.P.RotationFromAxisToRef(t,r,e,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}}teleportCamera(e){let t,i;if(!(this.currentVRCamera instanceof ab))return;if(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),this._teleportationMode==l$.TELEPORTATIONMODE_CONSTANTSPEED){i=90;let e=rr.P.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];let r=new rE("animationCameraTeleportation","position",90,rE.ANIMATIONTYPE_VECTOR3,rE.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];r.setKeys(s),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];let n=Math.round(i/2),a=new rE("animationPP","vignetteWeight",90,rE.ANIMATIONTYPE_FLOAT,rE.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:n,value:8}),o.push({frame:i,value:0}),a.setKeys(o),this._postProcessMove.animations.push(a);let l=new rE("animationPP2","vignetteStretch",90,rE.ANIMATIONTYPE_FLOAT,rE.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._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){let i=Math.acos(rr.P.Dot(e,t.direction));i<Math.PI/2&&e.scaleInPlace(-1)}return e}_castRayAndSelectObject(e){if(!(this.currentVRCamera instanceof ab))return;let t=e._getForwardRay(this._rayLength),i=this._scene.pickWithRay(t,this._raySelectionPredicate);if(i&&this._scene.simulatePointerMove(i,{pointerId:e._id}),e._currentHit=i,i&&i.pickedPoint){if(this._displayGaze){let r=1;e._gazeTracker.isVisible=!0,e._isActionableMesh&&(r=3),this.updateGazeTrackerScale&&(e._gazeTracker.scaling.x=i.distance*r,e._gazeTracker.scaling.y=i.distance*r,e._gazeTracker.scaling.z=i.distance*r);let s=this._convertNormalToDirectionOfRay(i.getNormal(),t);if(s){let t=rr.P.Cross(rO.RD.Y,s),i=rr.P.Cross(s,t);rr.P.RotationFromAxisToRef(i,s,t,e._gazeTracker.rotation)}e._gazeTracker.position.copyFrom(i.pickedPoint),e._gazeTracker.position.x<0?e._gazeTracker.position.x+=.002:e._gazeTracker.position.x-=.002,e._gazeTracker.position.y<0?e._gazeTracker.position.y+=.002:e._gazeTracker.position.y-=.002,e._gazeTracker.position.z<0?e._gazeTracker.position.z+=.002:e._gazeTracker.position.z-=.002}e._updatePointerDistance(i.distance)}else e._updatePointerDistance(),e._gazeTracker.isVisible=!1;if(i&&i.pickedMesh){if(this._teleportationInitialized&&this._isTeleportationFloor(i.pickedMesh)&&i.pickedPoint){e._currentMeshSelected&&!this._isTeleportationFloor(e._currentMeshSelected)&&this._notifySelectedMeshUnselected(e._currentMeshSelected),e._currentMeshSelected=null,e._teleportationRequestInitiated&&this._moveTeleportationSelectorTo(i,e,t);return}if(i.pickedMesh!==e._currentMeshSelected){if(this.meshSelectionPredicate(i.pickedMesh)){this.onNewMeshPicked.notifyObservers(i),e._currentMeshSelected=i.pickedMesh,i.pickedMesh.isPickable&&i.pickedMesh.actionManager?(this.changeGazeColor(this._pickedGazeColor),this.changeLaserColor(this._pickedLaserColor),e._isActionableMesh=!0):(this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor),e._isActionableMesh=!1);try{this.onNewMeshSelected.notifyObservers(i.pickedMesh),e.webVRController&&this.onMeshSelectedWithController.notifyObservers({mesh:i.pickedMesh,controller:e.webVRController})}catch(e){ru.Y.Warn("Error while raising onNewMeshSelected or onMeshSelectedWithController: "+e)}}else this._notifySelectedMeshUnselected(e._currentMeshSelected),e._currentMeshSelected=null,this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor)}}else this._notifySelectedMeshUnselected(e._currentMeshSelected),e._currentMeshSelected=null,this.changeGazeColor(this._gazeColor),this.changeLaserColor(this._laserColor)}_notifySelectedMeshUnselected(e){e&&this.onSelectedMeshUnselected.notifyObservers(e)}setLaserColor(e,t=this._pickedLaserColor){this._laserColor=e,this._pickedLaserColor=t}setLaserLightingState(e=!0){this._leftController&&this._leftController._setLaserPointerLightingDisabled(!e),this._rightController&&this._rightController._setLaserPointerLightingDisabled(!e)}setGazeColor(e,t=this._pickedGazeColor){this._gazeColor=e,this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor&&(this._leftController&&this._leftController._setLaserPointerColor(e),this._rightController&&this._rightController._setLaserPointerColor(e))}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e,this._leftController&&(this._leftController._gazeTracker.material.emissiveColor=e),this._rightController&&(this._rightController._gazeTracker.material.emissiveColor=e))}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._webVRCamera&&this._webVRCamera.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._leftController&&this._leftController.dispose(),this._rightController&&this._rightController.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChangedBind),this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart),this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}l$.TELEPORTATIONMODE_CONSTANTTIME=0,l$.TELEPORTATIONMODE_CONSTANTSPEED=1;let lQ=(e,t,i,r)=>!(e.x>i.x+r)&&!(i.x-r>t.x)&&!(e.y>i.y+r)&&!(i.y-r>t.y)&&!(e.z>i.z+r)&&!(i.z-r>t.z),lZ=function(){let e={root:0,found:!1};return function(t,i,r,s){e.root=0,e.found=!1;let n=i*i-4*t*r;if(n<0)return e;let a=Math.sqrt(n),o=(-i-a)/(2*t),l=(-i+a)/(2*t);if(o>l){let e=l;l=o,o=e}return o>0&&o<s?(e.root=o,e.found=!0,e):(l>0&&l<s&&(e.root=l,e.found=!0),e)}}();class lJ{constructor(){this._collisionPoint=rr.P.Zero(),this._planeIntersectionPoint=rr.P.Zero(),this._tempVector=rr.P.Zero(),this._tempVector2=rr.P.Zero(),this._tempVector3=rr.P.Zero(),this._tempVector4=rr.P.Zero(),this._edge=rr.P.Zero(),this._baseToVertex=rr.P.Zero(),this._destinationPoint=rr.P.Zero(),this._slidePlaneNormal=rr.P.Zero(),this._displacementVector=rr.P.Zero(),this._radius=rr.P.One(),this._retry=0,this._basePointWorld=rr.P.Zero(),this._velocityWorld=rr.P.Zero(),this._normalizedVelocity=rr.P.Zero(),this._collisionMask=-1}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}get slidePlaneNormal(){return this._slidePlaneNormal}_initialize(e,t,i){this._velocity=t,this._velocitySquaredLength=this._velocity.lengthSquared();let r=Math.sqrt(this._velocitySquaredLength);0===r||1===r?this._normalizedVelocity.copyFromFloats(t._x,t._y,t._z):t.scaleToRef(1/r,this._normalizedVelocity),this._basePoint=e,e.multiplyToRef(this._radius,this._basePointWorld),t.multiplyToRef(this._radius,this._velocityWorld),this._velocityWorldLength=this._velocityWorld.length(),this._epsilon=i,this.collisionFound=!1}_checkPointInTriangle(e,t,i,r,s){t.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),rr.P.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);let n=rr.P.Dot(this._tempVector4,s);return!(n<0)&&(r.subtractToRef(e,this._tempVector3),rr.P.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),!((n=rr.P.Dot(this._tempVector4,s))<0)&&(rr.P.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),(n=rr.P.Dot(this._tempVector4,s))>=0))}_canDoCollision(e,t,i,r){let s=rr.P.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+n+t)&&!!lQ(i,r,this._basePointWorld,this._velocityWorldLength+n)}_testTriangle(e,t,i,r,s,n,a){let o;let l=!1;t||(t=[]),t[e]||(t[e]=new sp.J(0,0,0,0),t[e].copyFromPoints(i,r,s));let h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;let u=h.signedDistanceTo(this._basePoint),c=rr.P.Dot(h.normal,this._velocity);if(lJ.DoubleSidedCheck&&c>1e-4)return;if(0==c){if(Math.abs(u)>=1)return;l=!0,o=0}else{o=(-1-u)/c;let e=(1-u)/c;if(o>e){let t=e;e=o,o=t}if(o>1||e<0)return;o<0&&(o=0),o>1&&(o=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,p=1;if(!l&&(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(o,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,s,h.normal)&&(d=!0,p=o,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*rr.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,a=lZ(e,t,n,p);a.found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),(a=lZ(e,t=2*rr.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,p)).found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(s,this._tempVector),(a=lZ(e,t=2*rr.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,p)).found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(s)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let o=this._edge.lengthSquared(),l=rr.P.Dot(this._edge,this._velocity),h=rr.P.Dot(this._edge,this._baseToVertex);if((a=lZ(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rr.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=rr.P.Dot(this._edge,this._velocity),h=rr.P.Dot(this._edge,this._baseToVertex),(a=lZ(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rr.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=rr.P.Dot(this._edge,this._velocity),h=rr.P.Dot(this._edge,this._baseToVertex),(a=lZ(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rr.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(d){let e=p*p*this._velocitySquaredLength;(!this.collisionFound||e<this._nearestDistanceSquared)&&(a.collisionResponse&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this._nearestDistanceSquared=e,this._nearestDistance=Math.sqrt(e),this.collisionFound=!0),this.collidedMesh=a)}}_collide(e,t,i,r,s,n,a,o,l,h=!1){if(h){if(i&&0!==i.length)for(let n=r;n<s-2;n+=1){let r=i[n],s=i[n+1],h=i[n+2];if(4294967295===h){n+=2;continue}let u=t[r],c=t[s],d=t[h];u&&c&&d&&((l?1:0)^n%2?this._testTriangle(n,e,u,c,d,a,o):this._testTriangle(n,e,c,u,d,a,o))}else for(let i=0;i<t.length-2;i+=1){let r=t[i],s=t[i+1],n=t[i+2];r&&s&&n&&((l?1:0)^i%2?this._testTriangle(i,e,r,s,n,a,o):this._testTriangle(i,e,s,r,n,a,o))}}else if(i&&0!==i.length)for(let h=r;h<s;h+=3){let r=t[i[h]-n],s=t[i[h+1]-n],u=t[i[h+2]-n];l?this._testTriangle(h,e,r,s,u,a,o):this._testTriangle(h,e,u,s,r,a,o)}else for(let i=0;i<t.length;i+=3){let r=t[i],s=t[i+1],n=t[i+2];l?this._testTriangle(i,e,r,s,n,a,o):this._testTriangle(i,e,n,s,r,a,o)}}_getResponse(e,t){e.addToRef(t,this._destinationPoint),t.scaleInPlace(this._nearestDistance/t.length()),this._basePoint.addToRef(t,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this._epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(sp.J.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,t)}}lJ.DoubleSidedCheck=!1;class l0{constructor(){this._scaledPosition=rr.P.Zero(),this._scaledVelocity=rr.P.Zero(),this._finalPosition=rr.P.Zero()}getNewPosition(e,t,i,r,s,n,a){e.divideToRef(i._radius,this._scaledPosition),t.divideToRef(i._radius,this._scaledVelocity),i.collidedMesh=null,i._retry=0,i._initialVelocity=this._scaledVelocity,i._initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,r,this._finalPosition,s),this._finalPosition.multiplyInPlace(i._radius),n(a,this._finalPosition,i.collidedMesh)}createCollider(){return new lJ}init(e){this._scene=e}_collideWithWorld(e,t,i,r,s,n=null){let a=10*r7.D.CollisionsEpsilon;if(i._retry>=r){s.copyFrom(e);return}let o=n?n.collisionMask:i.collisionMask;i._initialize(e,t,a);let l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;e<l.length;e++){let t=l[e];t.isEnabled()&&t.checkCollisions&&t.subMeshes&&t!==n&&(o&t.collisionGroup)!=0&&t._checkCollision(i)}if(!i.collisionFound){e.addToRef(t,s);return}if((0!==t.x||0!==t.y||0!==t.z)&&i._getResponse(e,t),t.length()<=a){s.copyFrom(e);return}i._retry++,this._collideWithWorld(e,t,i,r,s,n)}}rI.x.CollisionCoordinatorFactory=()=>new l0,i(3927);class l1{constructor(e,t,i,r=""){var s,n;let a;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new ri.y$,this.onErrorObservable=new ri.y$,this.onBindObservable=new ri.y$,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=nd.x.WGSL,this.name=e,this._key=r,this._engine=i,this.uniqueId=l1._UniqueIdSeed++,this.defines=null!==(s=t.defines)&&void 0!==s?s:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=null!==(n=t.entryPoint)&&void 0!==n?n:"main",this._shaderStore=no.v.GetShadersStore(this._shaderLanguage),this._shaderRepository=no.v.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=no.v.GetIncludesShadersStore(this._shaderLanguage);let o=(0,r9.CG)()?this._engine.getHostDocument():null;e.computeSource?a="source:"+e.computeSource:e.computeElement?(a=o?o.getElementById(e.computeElement):null)||(a=e.computeElement):a=e.compute||e;let l={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=>{ld.L.Initialize(l),ld.L.PreProcess(i,l,r=>{this._rawComputeSourceCode=i,t.processFinalCode&&(r=t.processFinalCode(r));let s=ld.L.Finalize(r,"",l);this._useFinalCode(s.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){let 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){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&setTimeout(()=>{this._checkIsReady(null)},16)}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let s;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){let t=(0,r9.v)(e);r(t);return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){let t=window.atob(e.substr(7));r(t);return}if(this._shaderStore[e+t+"Shader"]){r(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){r(this._shaderStore[e+i+"Shader"]);return}s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}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(){let e=this.defines,t=this._pipelineContext;this._isReady=!1;try{let 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(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t){let i=null;if(t&&e){let r=t.match(/COMPUTE SHADER ERROR: 0:(\d+?):/);if(r&&2===r.length){let t=parseInt(r[1]),s=e.split("\n",-1);s.length>=t&&(i=`Offending line [${t}] in compute code: ${s[t-1]}`)}}return[e,i]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,ru.Y.Error("Unable to compile compute effect:"),ru.Y.Error("Defines:\n"+this.defines),l1.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&&(ru.Y.Error("Compute code:"),ru.Y.Error(t))),e&&ru.Y.Error(e)}ru.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){no.v.GetShadersStore(nd.x.WGSL)[`${e}ComputeShader`]=t}}l1._UniqueIdSeed=0,l1.LogShaderCodeOnCompilationError=!0,(N=tN||(tN={}))[N.Texture=0]="Texture",N[N.StorageTexture=1]="StorageTexture",N[N.UniformBuffer=2]="UniformBuffer",N[N.StorageBuffer=3]="StorageBuffer",N[N.TextureWithoutSampler=4]="TextureWithoutSampler",N[N.Sampler=5]="Sampler",sx.B.prototype.createComputeEffect=function(e,t){throw Error("createComputeEffect: This engine does not support compute shaders!")},sx.B.prototype.createComputePipelineContext=function(){throw Error("createComputePipelineContext: This engine does not support compute shaders!")},sx.B.prototype.createComputeContext=function(){},sx.B.prototype.computeDispatch=function(e,t,i,r,s,n,a){throw Error("computeDispatch: This engine does not support compute shaders!")},sx.B.prototype.areAllComputeEffectsReady=function(){return!0},sx.B.prototype.releaseComputeEffects=function(){},sx.B.prototype._prepareComputePipelineContext=function(e,t,i,r,s){},sx.B.prototype._rebuildComputeEffects=function(){},sx.B.prototype._executeWhenComputeStateIsCompiled=function(e,t){t()},sx.B.prototype._releaseComputeEffect=function(e){},sx.B.prototype._deleteComputePipelineContext=function(e){};var l2=i(7955);class l3{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,r={}){if(this._bindings={},this._samplers={},this._contextIsDirty=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=sZ.K.UniqueId,!this._engine.getCaps().supportComputeShaders){ru.Y.Error("This engine does not support compute shaders!");return}if(!r.bindingsMapping){ru.Y.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!");return}this._context=t.createComputeContext(),this._shaderPath=i,this._options=Object.assign({bindingsMapping:{},defines:[]},r)}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){let r=this._bindings[e];this._bindings[e]={type:i?tN.Texture:tN.TextureWithoutSampler,object:t,indexInGroupEntries:null==r?void 0:r.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!r||r.object!==t||r.type!==this._bindings[e].type)}setStorageTexture(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tN.StorageTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setUniformBuffer(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tN.UniformBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setStorageBuffer(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tN.StorageBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setTextureSampler(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:tN.Sampler,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}isReady(){let e=this._effect;for(let e in this._bindings){let t=this._bindings[e],i=t.type,r=t.object;switch(i){case tN.Texture:case tN.TextureWithoutSampler:case tN.StorageTexture:if(!r.isReady())return!1}}let t=[],i=this._shaderPath;if(this._options.defines)for(let e=0;e<this._options.defines.length;e++)t.push(this._options.defines[e]);let r=t.join("\n");return this._cachedDefines!==r&&(this._cachedDefines=r,e=this._engine.createComputeEffect(i,{defines:r,entryPoint:this._options.entryPoint,onCompiled:this.onCompiled,onError:this.onError}),this._effect=e),!!e.isReady()}dispatch(e,t,i){var r;if(!this.isReady())return!1;for(let e in this._bindings){let t=this._bindings[e];if(!this._options.bindingsMapping[e])throw Error("ComputeShader ('"+this.name+"'): No binding mapping has been provided for the property '"+e+"'");switch(t.type){case tN.Texture:{let i=this._samplers[e],s=t.object;i&&s._texture&&i.compareSampler(s._texture)||(this._samplers[e]=new l2.a().setParameters(s.wrapU,s.wrapV,s.wrapR,s.anisotropicFilteringLevel,s._texture.samplingMode,null===(r=s._texture)||void 0===r?void 0:r._comparisonFunction),this._contextIsDirty=!0);break}case tN.UniformBuffer:{let e=t.object;e.getBuffer()!==t.buffer&&(t.buffer=e.getBuffer(),this._contextIsDirty=!0)}}}return this._contextIsDirty&&(this._contextIsDirty=!1,this._context.clear()),this._engine.computeDispatch(this._effect,this._context,this._bindings,e,t,i,this._options.bindingsMapping),!0}dispatchWhenReady(e,t,i,r=10){return new Promise(s=>{let n=()=>{this.dispatch(e,t,i)?s():setTimeout(n,r)};n()})}serialize(){let e=rg.p4.Serialize(this);for(let t in e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={},this._bindings){let i=this._bindings[t],r=i.object;switch(i.type){case tN.Texture:case tN.TextureWithoutSampler:case tN.StorageTexture:{let s=r.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type})}case tN.UniformBuffer:}}return e}static Parse(e,t,i){let r=rg.p4.Parse(()=>new l3(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(let s in e.textures){let n=e.bindings[s],a=sv.Parse(e.textures[s],t,i);n.type===tN.Texture?r.setTexture(s,a):n.type===tN.TextureWithoutSampler?r.setTexture(s,a,!1):r.setStorageTexture(s,a)}return r}}(0,r0.gn)([(0,rg.qC)()],l3.prototype,"name",void 0),(0,rn.H)("BABYLON.ComputeShader",l3);var l4=i(9687),l5=i(6886),l6=i(416);class l8{constructor(e,t,i,r,s,n){this.entries=[],this._boundingVectors=[],this._capacity=i,this._depth=r,this._maxDepth=s,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.addEntry(e)}return}this._creationFunc(e,this),this.entries.length>this.capacity&&this._depth<this._maxDepth&&this.createInnerBlocks()}removeEntry(e){if(this.blocks){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.removeEntry(e)}return}let t=this.entries.indexOf(e);t>-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t<e.length;t++){let i=e[t];this.addEntry(i)}}select(e,t,i){if(l4.k.IsInFrustum(this._boundingVectors,e)){if(this.blocks){for(let r=0;r<this.blocks.length;r++){let s=this.blocks[r];s.select(e,t,i)}return}i?t.concat(this.entries):t.concatWithNoDuplicate(this.entries)}}intersects(e,t,i,r){if(l4.k.IntersectsSphere(this._minPoint,this._maxPoint,e,t)){if(this.blocks){for(let s=0;s<this.blocks.length;s++){let n=this.blocks[s];n.intersects(e,t,i,r)}return}r?i.concat(this.entries):i.concatWithNoDuplicate(this.entries)}}intersectsRay(e,t){if(e.intersectsBoxMinMax(this._minPoint,this._maxPoint)){if(this.blocks){for(let i=0;i<this.blocks.length;i++){let r=this.blocks[i];r.intersectsRay(e,t)}return}t.concatWithNoDuplicate(this.entries)}}createInnerBlocks(){l8._CreateBlocks(this._minPoint,this._maxPoint,this.entries,this._capacity,this._depth,this._maxDepth,this,this._creationFunc),this.entries.splice(0)}static _CreateBlocks(e,t,i,r,s,n,a,o){a.blocks=[];let l=new rr.P((t.x-e.x)/2,(t.y-e.y)/2,(t.z-e.z)/2);for(let t=0;t<2;t++)for(let h=0;h<2;h++)for(let u=0;u<2;u++){let c=e.add(l.multiplyByFloats(t,h,u)),d=e.add(l.multiplyByFloats(t+1,h+1,u+1)),p=new l8(c,d,r,s+1,n,o);p.addEntries(i),a.blocks.push(p)}}}class l7{constructor(e,t,i=2){this.maxDepth=i,this.dynamicContent=[],this._maxBlockCapacity=t||64,this._selectionContent=new na.f(1024),this._creationFunc=e}update(e,t,i){l8._CreateBlocks(e,t,i,this._maxBlockCapacity,0,this.maxDepth,this,this._creationFunc)}addMesh(e){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.addEntry(e)}}removeMesh(e){for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.removeEntry(e)}}select(e,t){this._selectionContent.reset();for(let i=0;i<this.blocks.length;i++){let r=this.blocks[i];r.select(e,this._selectionContent,t)}return t?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}intersects(e,t,i){this._selectionContent.reset();for(let r=0;r<this.blocks.length;r++){let s=this.blocks[r];s.intersects(e,t,this._selectionContent,i)}return i?this._selectionContent.concat(this.dynamicContent):this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}intersectsRay(e){this._selectionContent.reset();for(let t=0;t<this.blocks.length;t++){let i=this.blocks[t];i.intersectsRay(e,this._selectionContent)}return this._selectionContent.concatWithNoDuplicate(this.dynamicContent),this._selectionContent}}l7.CreationFuncForMeshes=(e,t)=>{let i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},l7.CreationFuncForSubMeshes=(e,t)=>{let i=e.getBoundingInfo();i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},rI.x.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(ss.l.NAME_OCTREE);i||(i=new l9(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new l7(l7.CreationFuncForMeshes,e,t));let r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},Object.defineProperty(rI.x.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),r$.x.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){let i=this.getScene(),r=i._getComponent(ss.l.NAME_OCTREE);r||(r=new l9(i),i._addComponent(r)),this._submeshesOctree||(this._submeshesOctree=new l7(l7.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);let s=this.getBoundingInfo(),n=s.boundingBox;return this._submeshesOctree.update(n.minimumWorld,n.maximumWorld,this.subMeshes),this._submeshesOctree};class l9{constructor(e){if(this.name=ss.l.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new sD(rr.P.Zero(),new rr.P(1,1,1)),!(e=e||rp.l.LastCreatedScene))return;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=>{let t=this.scene.selectionOctree;if(null!=t){let i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}}),this.scene.onMeshImportedObservable.add(e=>{let 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){let t=e._submeshesOctree.select(this.scene.frustumPlanes);return t}return this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForPicking){sD.TransformToRef(t,e.getWorldMatrix(),this._tempRay);let i=e._submeshesOctree.intersectsRay(this._tempRay);return i}return this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){let i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z),r=e._submeshesOctree.intersects(t._basePointWorld,i);return r}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}class he{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 oa("shared gizmo light",new rr.P(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=rs.Wo.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==he._DefaultUtilityLayer?he._CreateDefaultUtilityLayerFromScene(rp.l.LastCreatedScene):he._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return he._DefaultUtilityLayer=new he(e),he._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{he._DefaultUtilityLayer=null}),he._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==he._DefaultKeepDepthUtilityLayer&&(he._DefaultKeepDepthUtilityLayer=new he(rp.l.LastCreatedScene),he._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,he._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{he._DefaultKeepDepthUtilityLayer=null})),he._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 ri.y$,this.utilityLayerScene=new rI.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||!this.pickingEnabled||!this.processAllEvents&&t.type!==sy.kD.POINTERMOVE&&t.type!==sy.kD.POINTERUP&&t.type!==sy.kD.POINTERDOWN&&t.type!==sy.kD.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;let i=t.event;if(e.isPointerCaptured(i.pointerId)){this._pointerCaptures[i.pointerId]=!1;return}let r=i=>{let r=null;if(t.nearInteractionPickingInfo)r=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new sI.p;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)r=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),r=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return r},s=r(this.utilityLayerScene);if(!t.ray&&s&&(t.ray=s.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=sy.kD.POINTERDOWN){t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new sy.R5(t.type,t.event,s),t.type),t.type===sy.kD.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)s&&s.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new sy.R5(t.type,t.event,s),t.type),t.skipOnPointerObservable=!0);else{let i=r(e),n=t.event;i&&s&&(0===s.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===sy.kD.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:(t.type===sy.kD.POINTERMOVE||t.type===sy.kD.POINTERUP)&&(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(s.distance<i.distance||0===i.distance)?(this._notifyObservers(t,s,n),t.skipOnPointerObservable||(t.skipOnPointerObservable=s.distance>0)):!this._pointerCaptures[n.pointerId]&&s.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):((t.type===sy.kD.POINTERMOVE||t.type===sy.kD.POINTERUP)&&this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,s,n))),t.type===sy.kD.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add(e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(()=>{this.dispose()}),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new sy.R5(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){let 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()}}he._DefaultUtilityLayer=null,he._DefaultKeepDepthUtilityLayer=null,(F=tF||(tF={}))[F.Origin=0]="Origin",F[F.Pivot=1]="Pivot",(L=tL||(tL={}))[L.World=0]="World",L[L.Local=1]="Local";class ht{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;let t=e==tL.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=he.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=tF.Origin,this._updateScale=!0,this._coordinatesMode=tL.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=rr.y3.RotationY(Math.PI),this._rootMesh=new rq.Kj("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=rr._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==tF.Pivot&&e.getAbsolutePivotPoint){let t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{let t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new rr.P(0,0,0);this._rootMesh.position.copyFrom(i)}}if(this.updateGizmoRotationToMatchAttachedMesh){let t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName(),i=t?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,ht.PreserveScaling?i:void 0)}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){let t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;t.devicePosition&&(i=t.devicePosition),this._rootMesh.position.subtractToRef(i,rr.jp.Vector3[0]);let r=this.scaleRatio;if(t.mode==r4.V.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){let e=t.orthoTop-t.orthoBottom;r*=e}}else{let e=t.getScene().useRightHandedSystem?rr.P.RightHandedForwardReadOnly:rr.P.LeftHandedForwardReadOnly,i=t.getDirection(e);r*=rr.P.Dot(rr.jp.Vector3[0],i)}this._rootMesh.scaling.setAll(r),0>e._getWorldMatrixDeterminant()&&!ht.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_handlePivot(){let e=this._attachedNode;e.isUsingPivotMatrix&&e.isUsingPivotMatrix()&&e.position&&e.getWorldMatrix().setTranslation(e.position)}_matrixChanged(){if(this._attachedNode){if(this._attachedNode._isCamera){let e,t;let i=this._attachedNode;if(i.parent){let t=rr.jp.Matrix[1];i.parent._worldMatrix.invertToRef(t),this._attachedNode._worldMatrix.multiplyToRef(t,rr.jp.Matrix[0]),e=rr.jp.Matrix[0]}else e=this._attachedNode._worldMatrix;i.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(e,rr.jp.Matrix[1]),t=rr.jp.Matrix[1]):t=e,t.decompose(rr.jp.Vector3[1],rr.jp.Quaternion[0],rr.jp.Vector3[0]);let r="FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName();if(r){let e=this._attachedNode;e.rotation=rr.jp.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(rr.jp.Quaternion[0]),e.rotationQuaternion.normalize())}i.position.copyFrom(rr.jp.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){let e=this._attachedNode;if(e.parent){let t=rr.jp.Matrix[0],i=rr.jp.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i),i.decompose(rr.jp.Vector3[0],rr.jp.Quaternion[0],e.position,ht.PreserveScaling?e:void 0)}else this._attachedNode._worldMatrix.decompose(rr.jp.Vector3[0],rr.jp.Quaternion[0],e.position,ht.PreserveScaling?e:void 0);rr.jp.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(rr.jp.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(rr.jp.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=rr.jp.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){let e=this._attachedNode,t=e.getParent();if(t){let i=rr.jp.Matrix[0],r=rr.jp.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r);let s=e.getLocalMatrix();s.copyFrom(r)}else{let t=e.getLocalMatrix();t.copyFrom(e.getFinalMatrix())}e.markAsDirty()}else{let e=this._attachedNode;if(e.getTypeID){let t=e.getTypeID();if(t===r3.LIGHTTYPEID_DIRECTIONALLIGHT||t===r3.LIGHTTYPEID_SPOTLIGHT||t===r3.LIGHTTYPEID_POINTLIGHT){let t=e.parent;if(t){let i=rr.jp.Matrix[0],r=rr.jp.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,r),r.decompose(void 0,rr.jp.Quaternion[0],rr.jp.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,rr.jp.Quaternion[0],rr.jp.Vector3[0]);e.position=new rr.P(rr.jp.Vector3[0].x,rr.jp.Vector3[0].y,rr.jp.Vector3[0].z),e.direction&&(e.direction=new rr.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,r=e.utilityLayerScene.onPointerObservable.add(e=>{var r,s;if(e.pickInfo){if(e.type===sy.kD.POINTERMOVE){if(i)return;t.forEach(t=>{var i,r;if(t.colliderMeshes&&t.gizmoMeshes){let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,n=t.dragBehavior.enabled?s||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=n,e.color&&(e.color=n.diffuseColor)})}})}if(e.type===sy.kD.POINTERDOWN&&t.has(null===(r=e.pickInfo.pickedMesh)||void 0===r?void 0:r.parent)){i=!0;let r=t.get(null===(s=e.pickInfo.pickedMesh)||void 0===s?void 0:s.parent);r.active=!0,t.forEach(t=>{var i,r;let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,n=(s||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=n,e.color&&(e.color=n.diffuseColor)})})}e.type===sy.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)})})}});return r}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}ht.PreserveScaling=!1,Object.defineProperty(rI.x.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new hi(this)),this._debugLayer},enumerable:!0,configurable:!0}),(w=tw||(tw={}))[w.Properties=0]="Properties",w[w.Debug=1]="Debug",w[w.Statistics=2]="Statistics",w[w.Tools=3]="Tools",w[w.Settings=4]="Settings";class hi{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new ri.y$),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new ri.y$),this._onSelectionChangedObservable)}constructor(e){if(this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||rp.l.LastCreatedScene,!this._scene)return;this._scene.onDisposeObservable.add(()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()})}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(let e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(let e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}let 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){let i=e&&e.inspectorURL?e.inspectorURL:hi.InspectorURL;rZ.w1.LoadScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}function hr(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],i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[],s=[],n=e.width||e.size||1,a=e.height||e.size||1,o=e.depth||e.size||1,l=e.wrap||!1,h=void 0===e.topBaseAt?1:e.topBaseAt,u=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,u=(u+4)%4;let c=[2,0,3,1][h],d=[2,0,1,3][u],p=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],p=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,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]],r=[17,18,19,16],s=[22,23,20,21];for(;c>0;)e.unshift(e.pop()),r.unshift(r.pop()),c--;for(;d>0;)i.unshift(i.pop()),s.unshift(s.pop()),d--;e=e.flat(),i=i.flat(),p=p.concat(e).concat(i),t.push(r[0],r[2],r[3],r[0],r[1],r[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}let _=[n/2,a/2,o/2];s=p.reduce((e,t,i)=>e.concat(t*_[i%3]),[]);let f=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE,m=e.faceUV||Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new rr.Lt(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new rs.HE(1,1,1,1));for(let e=0;e<6;e++)if(r.push(m[e].z,sg.e.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,sg.e.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,sg.e.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),r.push(m[e].z,sg.e.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);sN.x._ComputeSides(f,s,t,i,r,e.frontUVs,e.backUVs);let T=new sN.x;if(T.indices=t,T.positions=s,T.normals=i,T.uvs=r,g){let e=f===sN.x.DOUBLESIDE?v.concat(v):v;T.colors=e}return T}function hs(e,t={},i=null){let r=new rq.Kj(e,i);t.sideOrientation=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=hr(t);return s.applyToMesh(r,t.updatable),r}function hn(e){let t=0|(e.segments||32),i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,a=e.slice&&e.slice<=0?1:e.slice||1,o=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new rr.P(i/2,r/2,s/2),u=2+t,c=2*u,d=[],p=[],_=[],f=[];for(let e=0;e<=u;e++){let t=e/u,i=t*Math.PI*a;for(let e=0;e<=c;e++){let r=e/c,s=r*Math.PI*2*n,a=rr.y3.RotationZ(-i),o=rr.y3.RotationY(s),l=rr.P.TransformCoordinates(rr.P.Up(),a),u=rr.P.TransformCoordinates(l,o),d=u.multiply(h),m=u.divide(h).normalize();p.push(d.x,d.y,d.z),_.push(m.x,m.y,m.z),f.push(r,sg.e.UseOpenGLOrientationForUV?1-t:t)}if(e>0){let t=p.length/3;for(let i=t-2*(c+1);i+c+2<t;i++)l?(e>1&&(d.push(i),d.push(i+1),d.push(i+c+1)),(e<u||a<1)&&(d.push(i+c+1),d.push(i+1),d.push(i+c+2))):(d.push(i),d.push(i+1),d.push(i+c+1),d.push(i+c+1),d.push(i+1),d.push(i+c+2))}}sN.x._ComputeSides(o,p,d,_,f,e.frontUVs,e.backUVs);let m=new sN.x;return m.indices=d,m.positions=p,m.normals=_,m.uvs=f,m}function ha(e,t={},i=null){let r=new rq.Kj(e,i);t.sideOrientation=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=hn(t);return s.applyToMesh(r,t.updatable),r}function ho(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){let t,i;let r=0|Math.max(e.subdivisions?e.subdivisions:2,1),s=0|Math.max(e.tessellation?e.tessellation:16,3),n=Math.max(e.height?e.height:1,0),a=Math.max(e.radius?e.radius:.25,0),o=0|Math.max(e.capSubdivisions?e.capSubdivisions:6,1),l=Math.max(e.radiusTop?e.radiusTop:a,0),h=Math.max(e.radiusBottom?e.radiusBottom:a,0),u=n-(l+h),c=2*Math.PI,d=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:o,1),p=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:o,1),_=Math.acos((h-l)/n),f=[],m=[],g=[],v=[],T=0,x=[],S=.5*u,E=.5*Math.PI,C=rr.P.Zero(),b=rr.P.Zero(),y=Math.cos(_),A=Math.sin(_),R=new rr.FM(l*A,S+l*y).subtract(new rr.FM(h*A,-S+h*y)).length(),P=l*_+R+h*(E-_),I=0;for(i=0;i<=d;i++){let e=[],r=E-_*(i/d);I+=l*_/d;let n=Math.cos(r),a=Math.sin(r),o=n*l;for(t=0;t<=s;t++){let i=t/s,r=i*c+0,h=Math.sin(r),u=Math.cos(r);b.x=o*h,b.y=S+a*l,b.z=o*u,m.push(b.x,b.y,b.z),C.set(n*h,a,n*u),g.push(C.x,C.y,C.z),v.push(i,sg.e.UseOpenGLOrientationForUV?I/P:1-I/P),e.push(T),T++}x.push(e)}let M=n-l-h+y*l-y*h,D=A*(h-l)/M;for(i=1;i<=r;i++){let e=[];I+=R/r;let n=A*(i*(h-l)/r+l);for(t=0;t<=s;t++){let a=t/s,o=a*c+0,h=Math.sin(o),u=Math.cos(o);b.x=n*h,b.y=S+y*l-i*M/r,b.z=n*u,m.push(b.x,b.y,b.z),C.set(h,D,u).normalize(),g.push(C.x,C.y,C.z),v.push(a,sg.e.UseOpenGLOrientationForUV?I/P:1-I/P),e.push(T),T++}x.push(e)}for(i=1;i<=p;i++){let e=[],r=E-_-(Math.PI-_)*(i/p);I+=h*_/p;let n=Math.cos(r),a=Math.sin(r),o=n*h;for(t=0;t<=s;t++){let i=t/s,r=i*c+0,l=Math.sin(r),u=Math.cos(r);b.x=o*l,b.y=-S+a*h,b.z=o*u,m.push(b.x,b.y,b.z),C.set(n*l,a,n*u),g.push(C.x,C.y,C.z),v.push(i,sg.e.UseOpenGLOrientationForUV?I/P:1-I/P),e.push(T),T++}x.push(e)}for(t=0;t<s;t++)for(i=0;i<d+r+p;i++){let e=x[i][t],r=x[i+1][t],s=x[i+1][t+1],n=x[i][t+1];f.push(e),f.push(r),f.push(n),f.push(r),f.push(s),f.push(n)}if(f=f.reverse(),e.orientation&&!e.orientation.equals(rr.P.Up())){let t=new rr.y3;e.orientation.clone().scale(.5*Math.PI).cross(rr.P.Up()).toQuaternion().toRotationMatrix(t);let i=rr.P.Zero();for(let e=0;e<m.length;e+=3)i.set(m[e],m[e+1],m[e+2]),rr.P.TransformCoordinatesToRef(i.clone(),t,i),m[e]=i.x,m[e+1]=i.y,m[e+2]=i.z}let O=new sN.x;return O.positions=m,O.normals=g,O.uvs=v,O.indices=f,O}function hl(e){let t,i,r,s,n,a,o,l,h,u,c,d=e.pathArray,p=e.closeArray||!1,_=e.closePath||!1,f=e.invertUV||!1,m=Math.floor(d[0].length/2),g=e.offset||m;g=g>m?m:Math.floor(g);let v=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE,T=e.uvs,x=e.colors,S=[],E=[],C=[],b=[],y=[],A=[],R=[],P=[],I=[],M=[];if(d.length<2){let e=[],t=[];for(r=0;r<d[0].length-g;r++)e.push(d[0][r]),t.push(d[0][r+g]);d=[e,t]}let D=0,O=_?1:0;for(i=0,t=d[0].length;i<d.length;i++){for(R[i]=0,y[i]=[0],t=t<(a=(n=d[i]).length)?t:a,s=0;s<a;)S.push(n[s].x,n[s].y,n[s].z),s>0&&(o=n[s].subtract(n[s-1]).length()+R[i],y[i].push(o),R[i]=o),s++;_&&(s--,S.push(n[0].x,n[0].y,n[0].z),o=n[s].subtract(n[0]).length()+R[i],y[i].push(o),R[i]=o),I[i]=a+O,M[i]=D,D+=a+O}let N=null,F=null;for(r=0;r<t+O;r++){for(i=0,P[r]=0,A[r]=[0];i<d.length-1;i++)l=d[i],h=d[i+1],r===t?(N=l[0],F=h[0]):(N=l[r],F=h[r]),o=F.subtract(N).length()+P[r],A[r].push(o),P[r]=o;p&&F&&N&&(l=d[i],h=d[0],r===t&&(F=h[0]),o=F.subtract(N).length()+P[r],P[r]=o)}if(T)for(i=0;i<T.length;i++)b.push(T[i].x,sg.e.UseOpenGLOrientationForUV?1-T[i].y:T[i].y);else for(i=0;i<d.length;i++)for(r=0;r<t+O;r++)u=0!=R[i]?y[i][r]/R[i]:0,c=0!=P[r]?A[r][i]/P[r]:0,f?b.push(c,u):b.push(u,sg.e.UseOpenGLOrientationForUV?1-c:c);let L=0,w=I[i=0]-1,B=I[i+1]-1,U=w<B?w:B,V=M[1]-M[0],k=p?I.length:I.length-1;for(;L<=U&&i<k;)E.push(L,L+V,L+1),E.push(L+V+1,L+1,L+V),(L+=1)===U&&(++i==I.length-1?(V=M[0]-M[i],w=I[i]-1,B=I[0]-1):(V=M[i+1]-M[i],w=I[i]-1,B=I[i+1]-1),L=M[i],U=w<B?w+L:B+L);if(sN.x.ComputeNormals(S,E,C),_){let e=0,t=0;for(i=0;i<d.length;i++)e=3*M[i],t=i+1<d.length?(M[i+1]-1)*3:C.length-3,C[e]=(C[e]+C[t])*.5,C[e+1]=(C[e+1]+C[t+1])*.5,C[e+2]=(C[e+2]+C[t+2])*.5,C[t]=C[e],C[t+1]=C[e+1],C[t+2]=C[e+2]}sN.x._ComputeSides(v,S,E,C,b,e.frontUVs,e.backUVs);let G=null;if(x){G=new Float32Array(4*x.length);for(let e=0;e<x.length;e++)G[4*e]=x[e].r,G[4*e+1]=x[e].g,G[4*e+2]=x[e].b,G[4*e+3]=x[e].a}let z=new sN.x,W=new Float32Array(S),H=new Float32Array(C),X=new Float32Array(b);return z.indices=E,z.positions=W,z.normals=H,z.uvs=X,G&&z.set(G,rQ.o.ColorKind),_&&(z._idx=M),z}function hh(e,t,i=null){let r=t.pathArray,s=t.closeArray,n=t.closePath,a=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),o=t.instance,l=t.updatable;if(o){let e=rr.jp.Vector3[0].setAll(Number.MAX_VALUE),i=rr.jp.Vector3[1].setAll(-Number.MAX_VALUE),s=o.getVerticesData(rQ.o.PositionKind);if((t=>{let s=r[0].length,n=0,a=o._originalBuilderSideOrientation===rq.Kj.DOUBLESIDE?2:1;for(let l=1;l<=a;++l)for(let a=0;a<r.length;++a){let l=r[a],h=l.length;s=s<h?s:h;for(let r=0;r<s;++r){let s=l[r];t[n]=s.x,t[n+1]=s.y,t[n+2]=s.z,e.minimizeInPlaceFromFloats(s.x,s.y,s.z),i.maximizeInPlaceFromFloats(s.x,s.y,s.z),n+=3}if(o._creationDataStorage&&o._creationDataStorage.closePath){let e=l[0];t[n]=e.x,t[n+1]=e.y,t[n+2]=e.z,n+=3}}})(s),o.hasBoundingInfo?o.getBoundingInfo().reConstruct(e,i,o._worldMatrix):o.buildBoundingInfo(e,i,o._worldMatrix),o.updateVerticesData(rQ.o.PositionKind,s,!1,!1),t.colors){let e=o.getVerticesData(rQ.o.ColorKind);for(let i=0,r=0;i<t.colors.length;i++,r+=4){let s=t.colors[i];e[r]=s.r,e[r+1]=s.g,e[r+2]=s.b,e[r+3]=s.a}o.updateVerticesData(rQ.o.ColorKind,e,!1,!1)}if(t.uvs){let e=o.getVerticesData(rQ.o.UVKind);for(let i=0;i<t.uvs.length;i++)e[2*i]=t.uvs[i].x,e[2*i+1]=sg.e.UseOpenGLOrientationForUV?1-t.uvs[i].y:t.uvs[i].y;o.updateVerticesData(rQ.o.UVKind,e,!1,!1)}if(!o.areNormalsFrozen||o.isFacetDataEnabled){let e=o.getIndices(),t=o.getVerticesData(rQ.o.NormalKind),i=o.isFacetDataEnabled?o.getFacetDataParameters():null;if(sN.x.ComputeNormals(s,e,t,i),o._creationDataStorage&&o._creationDataStorage.closePath){let e=0,i=0;for(let s=0;s<r.length;s++)e=3*o._creationDataStorage.idx[s],i=s+1<r.length?(o._creationDataStorage.idx[s+1]-1)*3:t.length-3,t[e]=(t[e]+t[i])*.5,t[e+1]=(t[e+1]+t[i+1])*.5,t[e+2]=(t[e+2]+t[i+2])*.5,t[i]=t[e],t[i+1]=t[e+1],t[i+2]=t[e+2]}o.areNormalsFrozen||o.updateVerticesData(rQ.o.NormalKind,t,!1,!1)}return o}{let r=new rq.Kj(e,i);r._originalBuilderSideOrientation=a,r._creationDataStorage=new rq.gW;let o=hl(t);return n&&(r._creationDataStorage.idx=o._idx),r._creationDataStorage.closePath=n,r._creationDataStorage.closeArray=s,o.applyToMesh(r,l),r}}function hu(e){let t=[],i=[],r=[],s=[],n=e.radius||.5,a=e.tessellation||64,o=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);let h=2*Math.PI*o,u=1===o?h/a:h/(a-1),c=0;for(let e=0;e<a;e++){let e=Math.cos(c),i=Math.sin(c),r=(e+1)/2,a=(1-i)/2;t.push(n*e,n*i,0),s.push(r,sg.e.UseOpenGLOrientationForUV?1-a:a),c+=u}1===o&&(t.push(t[3],t[4],t[5]),s.push(s[2],sg.e.UseOpenGLOrientationForUV?1-s[3]:s[3]));let d=t.length/3;for(let e=1;e<d-1;e++)i.push(e+1,0,e);sN.x.ComputeNormals(t,i,r),sN.x._ComputeSides(l,t,i,r,s,e.frontUVs,e.backUVs);let p=new sN.x;return p.indices=i,p.positions=t,p.normals=r,p.uvs=s,p}function hc(e,t={},i=null){let r=new rq.Kj(e,i);t.sideOrientation=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=hu(t);return s.applyToMesh(r,t.updatable),r}function hd(e){let t=e.pattern||rq.Kj.NO_FLIP,i=e.tileWidth||e.tileSize||1,r=e.tileHeight||e.tileSize||1,s=e.alignHorizontal||0,n=e.alignVertical||0,a=e.width||e.size||1,o=Math.floor(a/i),l=a-o*i,h=e.height||e.size||1,u=Math.floor(h/r),c=h-u*r,d=i*o/2,p=r*u/2,_=0,f=0,m=0,g=0,v=0,T=0;if(l>0||c>0){switch(m=-d,g=-p,v=d,T=p,s){case rq.Kj.CENTER:l/=2,m-=l,v+=l;break;case rq.Kj.LEFT:v+=l,_=-l/2;break;case rq.Kj.RIGHT:m-=l,_=l/2}switch(n){case rq.Kj.CENTER:c/=2,g-=c,T+=c;break;case rq.Kj.BOTTOM:T+=c,f=-c/2;break;case rq.Kj.TOP:g-=c,f=c/2}}let x=[],S=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],(t===rq.Kj.ROTATE_TILE||t===rq.Kj.ROTATE_ROW)&&(E[1]=[1,1,0,1,0,0,1,0]),(t===rq.Kj.FLIP_TILE||t===rq.Kj.FLIP_ROW)&&(E[1]=[1,0,0,0,0,1,1,1]),(t===rq.Kj.FLIP_N_ROTATE_TILE||t===rq.Kj.FLIP_N_ROTATE_ROW)&&(E[1]=[0,1,1,1,1,0,0,0]);let C=[],b=[],y=[],A=0;for(let e=0;e<u;e++)for(let s=0;s<o;s++)x.push(-d+s*i+_,-p+e*r+f,0),x.push(-d+(s+1)*i+_,-p+e*r+f,0),x.push(-d+(s+1)*i+_,-p+(e+1)*r+f,0),x.push(-d+s*i+_,-p+(e+1)*r+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),C=t===rq.Kj.FLIP_TILE||t===rq.Kj.ROTATE_TILE||t===rq.Kj.FLIP_N_ROTATE_TILE?C.concat(E[(s%2+e%2)%2]):t===rq.Kj.FLIP_ROW||t===rq.Kj.ROTATE_ROW||t===rq.Kj.FLIP_N_ROTATE_ROW?C.concat(E[e%2]):C.concat(E[0]),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1),A+=4;if(l>0||c>0){let e,a,h,E;let R=c>0&&(n===rq.Kj.CENTER||n===rq.Kj.TOP),P=c>0&&(n===rq.Kj.CENTER||n===rq.Kj.BOTTOM),I=l>0&&(s===rq.Kj.CENTER||s===rq.Kj.RIGHT),M=l>0&&(s===rq.Kj.CENTER||s===rq.Kj.LEFT),D=[];if(R&&I&&(x.push(m+_,g+f,0),x.push(-d+_,g+f,0),x.push(-d+_,g+c+f,0),x.push(m+_,g+c+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,h=1,E=1,D=[e=1-l/i,a=1-c/r,h,a,h,E,e,E],t===rq.Kj.ROTATE_ROW&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),t===rq.Kj.FLIP_ROW&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),t===rq.Kj.FLIP_N_ROTATE_ROW&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),C=C.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),R&&M&&(x.push(d+_,g+f,0),x.push(v+_,g+f,0),x.push(v+_,g+c+f,0),x.push(d+_,g+c+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,E=1,D=[e=0,a=1-c/r,h=l/i,a,h,E,e,E],(t===rq.Kj.ROTATE_ROW||t===rq.Kj.ROTATE_TILE&&o%2==0)&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===rq.Kj.FLIP_ROW||t===rq.Kj.FLIP_TILE&&o%2==0)&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===rq.Kj.FLIP_N_ROTATE_ROW||t===rq.Kj.FLIP_N_ROTATE_TILE&&o%2==0)&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),C=C.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),P&&I&&(x.push(m+_,p+f,0),x.push(-d+_,p+f,0),x.push(-d+_,T+f,0),x.push(m+_,T+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,a=0,h=1,D=[e=1-l/i,a,h,a,h,E=c/r,e,E],(t===rq.Kj.ROTATE_ROW&&u%2==1||t===rq.Kj.ROTATE_TILE&&u%1==0)&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===rq.Kj.FLIP_ROW&&u%2==1||t===rq.Kj.FLIP_TILE&&u%2==0)&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===rq.Kj.FLIP_N_ROTATE_ROW&&u%2==1||t===rq.Kj.FLIP_N_ROTATE_TILE&&u%2==0)&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),C=C.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),P&&M&&(x.push(d+_,p+f,0),x.push(v+_,p+f,0),x.push(v+_,T+f,0),x.push(d+_,T+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,D=[e=0,a=0,h=l/i,a,h,E=c/r,e,E],(t===rq.Kj.ROTATE_ROW&&u%2==1||t===rq.Kj.ROTATE_TILE&&(u+o)%2==1)&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===rq.Kj.FLIP_ROW&&u%2==1||t===rq.Kj.FLIP_TILE&&(u+o)%2==1)&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===rq.Kj.FLIP_N_ROTATE_ROW&&u%2==1||t===rq.Kj.FLIP_N_ROTATE_TILE&&(u+o)%2==1)&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),C=C.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),R){let s=[];e=0,a=1-c/r,h=1,E=1,s[0]=[e,a,h,a,h,E,e,E],s[1]=[e,a,h,a,h,E,e,E],(t===rq.Kj.ROTATE_TILE||t===rq.Kj.ROTATE_ROW)&&(s[1]=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===rq.Kj.FLIP_TILE||t===rq.Kj.FLIP_ROW)&&(s[1]=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===rq.Kj.FLIP_N_ROTATE_TILE||t===rq.Kj.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-a,h,1-a,h,1-E,e,1-E]);for(let e=0;e<o;e++)x.push(-d+e*i+_,g+f,0),x.push(-d+(e+1)*i+_,g+f,0),x.push(-d+(e+1)*i+_,g+c+f,0),x.push(-d+e*i+_,g+c+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,C=t===rq.Kj.FLIP_TILE||t===rq.Kj.ROTATE_TILE||t===rq.Kj.FLIP_N_ROTATE_TILE?C.concat(s[(e+1)%2]):t===rq.Kj.FLIP_ROW||t===rq.Kj.ROTATE_ROW||t===rq.Kj.FLIP_N_ROTATE_ROW?C.concat(s[1]):C.concat(s[0]),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(P){let s=[];e=0,a=0,h=1,E=c/r,s[0]=[e,a,h,a,h,E,e,E],s[1]=[e,a,h,a,h,E,e,E],(t===rq.Kj.ROTATE_TILE||t===rq.Kj.ROTATE_ROW)&&(s[1]=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===rq.Kj.FLIP_TILE||t===rq.Kj.FLIP_ROW)&&(s[1]=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===rq.Kj.FLIP_N_ROTATE_TILE||t===rq.Kj.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-a,h,1-a,h,1-E,e,1-E]);for(let e=0;e<o;e++)x.push(-d+e*i+_,T-c+f,0),x.push(-d+(e+1)*i+_,T-c+f,0),x.push(-d+(e+1)*i+_,T+f,0),x.push(-d+e*i+_,T+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,C=t===rq.Kj.FLIP_TILE||t===rq.Kj.ROTATE_TILE||t===rq.Kj.FLIP_N_ROTATE_TILE?C.concat(s[(e+u)%2]):t===rq.Kj.FLIP_ROW||t===rq.Kj.ROTATE_ROW||t===rq.Kj.FLIP_N_ROTATE_ROW?C.concat(s[u%2]):C.concat(s[0]),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(I){let s=[];e=1-l/i,a=0,h=1,E=1,s[0]=[e,a,h,a,h,E,e,E],s[1]=[e,a,h,a,h,E,e,E],(t===rq.Kj.ROTATE_TILE||t===rq.Kj.ROTATE_ROW)&&(s[1]=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===rq.Kj.FLIP_TILE||t===rq.Kj.FLIP_ROW)&&(s[1]=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===rq.Kj.FLIP_N_ROTATE_TILE||t===rq.Kj.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-a,h,1-a,h,1-E,e,1-E]);for(let e=0;e<u;e++)x.push(m+_,-p+e*r+f,0),x.push(m+l+_,-p+e*r+f,0),x.push(m+l+_,-p+(e+1)*r+f,0),x.push(m+_,-p+(e+1)*r+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,C=t===rq.Kj.FLIP_TILE||t===rq.Kj.ROTATE_TILE||t===rq.Kj.FLIP_N_ROTATE_TILE?C.concat(s[(e+1)%2]):t===rq.Kj.FLIP_ROW||t===rq.Kj.ROTATE_ROW||t===rq.Kj.FLIP_N_ROTATE_ROW?C.concat(s[e%2]):C.concat(s[0]),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}if(M){let i=[];e=0,a=0,h=l/r,E=1,i[0]=[e,a,h,a,h,E,e,E],i[1]=[e,a,h,a,h,E,e,E],(t===rq.Kj.ROTATE_TILE||t===rq.Kj.ROTATE_ROW)&&(i[1]=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===rq.Kj.FLIP_TILE||t===rq.Kj.FLIP_ROW)&&(i[1]=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===rq.Kj.FLIP_N_ROTATE_TILE||t===rq.Kj.FLIP_N_ROTATE_ROW)&&(i[1]=[e,1-a,h,1-a,h,1-E,e,1-E]);for(let e=0;e<u;e++)x.push(v-l+_,-p+e*r+f,0),x.push(v+_,-p+e*r+f,0),x.push(v+_,-p+(e+1)*r+f,0),x.push(v-l+_,-p+(e+1)*r+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,C=t===rq.Kj.FLIP_TILE||t===rq.Kj.ROTATE_TILE||t===rq.Kj.FLIP_N_ROTATE_TILE?C.concat(i[(e+o)%2]):t===rq.Kj.FLIP_ROW||t===rq.Kj.ROTATE_ROW||t===rq.Kj.FLIP_N_ROTATE_ROW?C.concat(i[e%2]):C.concat(i[0]),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)}}let R=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE;sN.x._ComputeSides(R,x,y,S,C,e.frontUVs,e.backUVs);let P=new sN.x;P.indices=y,P.positions=x,P.normals=S,P.uvs=C;let I=R===sN.x.DOUBLESIDE?b.concat(b):b;return P.colors=I,P}function hp(e){let t,i;let r=[],s=[],n=[],a=[],o=e.radius||2,l=e.tube||.5,h=e.radialSegments||32,u=e.tubularSegments||32,c=e.p||2,d=e.q||3,p=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE,_=e=>{let t=d/c*e,i=Math.cos(t),r=o*Math.sin(t)*.5;return new rr.P(o*(2+i)*.5*Math.cos(e),o*(2+i)*Math.sin(e)*.5,r)};for(t=0;t<=h;t++){let e=t%h,r=e/h*2*c*Math.PI,n=_(r),o=_(r+.01),d=o.subtract(n),p=o.add(n),f=rr.P.Cross(d,p);for(p=rr.P.Cross(f,d),f.normalize(),p.normalize(),i=0;i<u;i++){let e=i%u,r=e/u*2*Math.PI,o=-l*Math.cos(r),c=l*Math.sin(r);s.push(n.x+o*p.x+c*f.x),s.push(n.y+o*p.y+c*f.y),s.push(n.z+o*p.z+c*f.z),a.push(t/h),a.push(sg.e.UseOpenGLOrientationForUV?1-i/u:i/u)}}for(t=0;t<h;t++)for(i=0;i<u;i++){let e=(i+1)%u,s=t*u+i,n=(t+1)*u+i,a=(t+1)*u+e,o=t*u+e;r.push(o),r.push(n),r.push(s),r.push(o),r.push(a),r.push(n)}sN.x.ComputeNormals(s,r,n),sN.x._ComputeSides(p,s,r,n,a,e.frontUVs,e.backUVs);let f=new sN.x;return f.indices=r,f.positions=s,f.normals=n,f.uvs=a,f}hi.InspectorURL=`https://unpkg.com/babylonjs-inspector@${r7.D.Version}/babylon.inspector.bundle.js`,sN.x.CreateBox=hr,rq.Kj.CreateBox=(e,t,i=null,r,s)=>hs(e,{size:t,sideOrientation:s,updatable:r},i),sN.x.CreateSphere=hn,rq.Kj.CreateSphere=(e,t,i,r,s,n)=>ha(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:s},r),rq.Kj.CreateCapsule=(e,t,i)=>(function(e,t={orientation:rr.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},i=null){let r=new rq.Kj(e,i),s=ho(t);return s.applyToMesh(r,t.updatable),r})(e,t,i),sN.x.CreateCapsule=ho,sN.x.CreateRibbon=hl,rq.Kj.CreateRibbon=(e,t,i=!1,r,s,n,a=!1,o,l)=>hh(e,{pathArray:t,closeArray:i,closePath:r,offset:s,updatable:a,sideOrientation:o,instance:l},n),sN.x.CreateDisc=hu,rq.Kj.CreateDisc=(e,t,i,r=null,s,n)=>hc(e,{radius:t,tessellation:i,sideOrientation:n,updatable:s},r),sN.x.CreateTiledPlane=hd,sN.x.CreateTiledBox=function(e){let t=e.faceUV||Array(6),i=e.faceColors,r=e.pattern||rq.Kj.NO_FLIP,s=e.width||e.size||1,n=e.height||e.size||1,a=e.depth||e.size||1,o=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,u=e.alignVertical||0,c=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new rr.Lt(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new rs.HE(1,1,1,1));let d=[];for(let e=0;e<2;e++)d[e]=hd({pattern:r,tileWidth:o,tileHeight:l,width:s,height:n,alignVertical:u,alignHorizontal:h,sideOrientation:c});for(let e=2;e<4;e++)d[e]=hd({pattern:r,tileWidth:o,tileHeight:l,width:a,height:n,alignVertical:u,alignHorizontal:h,sideOrientation:c});let p=u;u===rq.Kj.BOTTOM?p=rq.Kj.TOP:u===rq.Kj.TOP&&(p=rq.Kj.BOTTOM);for(let e=4;e<6;e++)d[e]=hd({pattern:r,tileWidth:o,tileHeight:l,width:s,height:a,alignVertical:p,alignHorizontal:h,sideOrientation:c});let _=[],f=[],m=[],g=[],v=[],T=[],x=[],S=[],E=0,C=0;for(let e=0;e<6;e++){let r=d[e].positions.length;T[e]=[],x[e]=[];for(let t=0;t<r/3;t++)T[e].push(new rr.P(d[e].positions[3*t],d[e].positions[3*t+1],d[e].positions[3*t+2])),x[e].push(new rr.P(d[e].normals[3*t],d[e].normals[3*t+1],d[e].normals[3*t+2]));E=d[e].uvs.length,S[e]=[];for(let i=0;i<E;i+=2)S[e][i]=t[e].x+(t[e].z-t[e].x)*d[e].uvs[i],S[e][i+1]=t[e].y+(t[e].w-t[e].y)*d[e].uvs[i+1],sg.e.UseOpenGLOrientationForUV&&(S[e][i+1]=1-S[e][i+1]);if(m=m.concat(S[e]),g=g.concat(d[e].indices.map(e=>e+C)),C+=T[e].length,i)for(let t=0;t<4;t++)v.push(i[e].r,i[e].g,i[e].b,i[e].a)}let b=new rr.P(0,0,a/2),y=rr.y3.RotationY(Math.PI);_=T[0].map(e=>rr.P.TransformNormal(e,y).add(b)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),f=x[0].map(e=>rr.P.TransformNormal(e,y)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),_=_.concat(T[1].map(e=>e.subtract(b)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(x[1].map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let A=new rr.P(s/2,0,0),R=rr.y3.RotationY(-Math.PI/2);_=_.concat(T[2].map(e=>rr.P.TransformNormal(e,R).add(A)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(x[2].map(e=>rr.P.TransformNormal(e,R)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let P=rr.y3.RotationY(Math.PI/2);_=_.concat(T[3].map(e=>rr.P.TransformNormal(e,P).subtract(A)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(x[3].map(e=>rr.P.TransformNormal(e,P)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let I=new rr.P(0,n/2,0),M=rr.y3.RotationX(Math.PI/2);_=_.concat(T[4].map(e=>rr.P.TransformNormal(e,M).add(I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(x[4].map(e=>rr.P.TransformNormal(e,M)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let D=rr.y3.RotationX(-Math.PI/2);_=_.concat(T[5].map(e=>rr.P.TransformNormal(e,D).subtract(I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(x[5].map(e=>rr.P.TransformNormal(e,D)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),sN.x._ComputeSides(c,_,g,f,m);let O=new sN.x;if(O.indices=g,O.positions=_,O.normals=f,O.uvs=m,i){let e=c===sN.x.DOUBLESIDE?v.concat(v):v;O.colors=e}return O},sN.x.CreateTorusKnot=hp,rq.Kj.CreateTorusKnot=(e,t,i,r,s,n,a,o,l,h)=>(function(e,t={},i){let r=new rq.Kj(e,i);t.sideOrientation=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=hp(t);return s.applyToMesh(r,t.updatable),r})(e,{radius:t,tube:i,radialSegments:r,tubularSegments:s,p:n,q:a,sideOrientation:h,updatable:l},o);let h_={effect:null,subMesh:null};class hf extends sY{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new rr.y3,this._cachedWorldViewProjectionMatrix=new rr.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},r)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}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);let i=new Float32Array(16*t.length);for(let e=0;e<t.length;e++){let r=t[e];r.copyToArray(i,16*e)}return this._matrixArrays[e]=i,this}setMatrix3x3(e,t){return this._checkUniform(e),this._matrices3x3[e]=t,this}setMatrix2x2(e,t){return this._checkUniform(e),this._matrices2x2[e]=t,this}setArray2(e,t){return this._checkUniform(e),this._vectors2Arrays[e]=t,this}setArray3(e,t){return this._checkUniform(e),this._vectors3Arrays[e]=t,this}setArray4(e,t){return this._checkUniform(e),this._vectors4Arrays[e]=t,this}setUniformBuffer(e,t){return -1===this._options.uniformBuffers.indexOf(e)&&this._options.uniformBuffers.push(e),this._uniformBuffers[e]=t,this}setTextureSampler(e,t){return -1===this._options.samplerObjects.indexOf(e)&&this._options.samplerObjects.push(e),this._textureSamplers[e]=t,this}setStorageBuffer(e,t){return -1===this._options.storageBuffers.indexOf(e)&&this._options.storageBuffers.push(e),this._storageBuffers[e]=t,this}setDefine(e,t){let i=e.trimEnd()+" ",r=this.options.defines.findIndex(t=>t===e||t.startsWith(i));return r>=0&&this.options.defines.splice(r,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var r,s,n;let a=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){if(a){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{let e=this._drawWrapper.effect;if(e&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}}let o=this.getScene(),l=o.getEngine(),h=[],u=[],c=new nn,d=this._shaderPath,p=this._options.uniforms,_=this._options.uniformBuffers,f=this._options.samplers;l.getCaps().multiview&&o.activeCamera&&o.activeCamera.outputRenderTarget&&o.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,h.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let e=0;e<this._options.defines.length;e++){let t=0===this._options.defines[e].indexOf("#define")?this._options.defines[e]:`#define ${this._options.defines[e]}`;h.push(t)}for(let e=0;e<this._options.attributes.length;e++)u.push(this._options.attributes[e]);if(e&&e.isVerticesDataPresent(rQ.o.ColorKind)&&(u.push(rQ.o.ColorKind),h.push("#define VERTEXCOLOR")),t&&(h.push("#define INSTANCES"),s3.G.PushAttributesForInstances(u,this._materialHelperNeedsPreviousMatrices),(null==e?void 0:e.hasThinInstances)&&(h.push("#define THIN_INSTANCES"),e&&e.isVerticesDataPresent(rQ.o.ColorInstanceKind)&&(u.push(rQ.o.ColorInstanceKind),h.push("#define INSTANCESCOLOR")))),e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton){u.push(rQ.o.MatricesIndicesKind),u.push(rQ.o.MatricesWeightsKind),e.numBoneInfluencers>4&&(u.push(rQ.o.MatricesIndicesExtraKind),u.push(rQ.o.MatricesWeightsExtraKind));let t=e.skeleton;h.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),c.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(h.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")):(h.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else h.push("#define NUM_BONE_INFLUENCERS 0");let m=0,g=e?e.morphTargetManager:null;if(g){let e=g.supportsUVs&&-1!==h.indexOf("#define UV1"),t=g.supportsTangents&&-1!==h.indexOf("#define TANGENT"),i=g.supportsNormals&&-1!==h.indexOf("#define NORMAL");m=g.numInfluencers,e&&h.push("#define MORPHTARGETS_UV"),t&&h.push("#define MORPHTARGETS_TANGENT"),i&&h.push("#define MORPHTARGETS_NORMAL"),m>0&&h.push("#define MORPHTARGETS"),g.isUsingTextureForTargets&&(h.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")),h.push("#define NUM_MORPH_INFLUENCERS "+m);for(let r=0;r<m;r++)u.push(rQ.o.PositionKind+r),i&&u.push(rQ.o.NormalKind+r),t&&u.push(rQ.o.TangentKind+r),e&&u.push(rQ.o.UVKind+"_"+r);m>0&&((p=p.slice()).push("morphTargetInfluences"),p.push("morphTargetTextureInfo"),p.push("morphTargetTextureIndices"))}else h.push("#define NUM_MORPH_INFLUENCERS 0");if(e){let t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(h.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")),s3.G.PrepareAttributesForBakedVertexAnimation(u,e,h)}for(let e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&h.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&((0,lx.qx)(p),(0,lx.lK)(this,o,h)),this.customShaderNameResolve&&(p=p.slice(),_=_.slice(),f=f.slice(),d=this.customShaderNameResolve(d,p,_,f,h,u));let v=a?i._getDrawWrapper():this._drawWrapper,T=null!==(r=null==v?void 0:v.effect)&&void 0!==r?r:null,x=null!==(s=null==v?void 0:v.defines)&&void 0!==s?s:null,S=h.join("\n"),E=T;return x!==S&&(E=l.createEffect(d,{attributes:u,uniformsNames:p,uniformBuffersNames:_,samplers:f,defines:S,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage},l),a?i.setEffect(E,S,this._materialContext):v&&v.setEffect(E,S),this._onEffectCreatedObservable&&(h_.effect=E,h_.subMesh=null!==(n=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==n?n:null,this._onEffectCreatedObservable.notifyObservers(h_))),E._wasPreviouslyUsingInstances=!!t,!!(null==E?void 0:E.isReady())&&(T!==E&&o.resetCachedMaterial(),E._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){let i=this.getScene(),r=null!=t?t:this.getEffect();r&&(-1!==this._options.uniforms.indexOf("world")&&r.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var r;this.bind(e,t,null===(r=i._drawWrapperOverride)||void 0===r?void 0:r.effect,i)}bind(e,t,i,r){var s;let n=r&&this._storeEffectOnSubMeshes,a=null!=i?i:n?r.effect:this.getEffect();if(!a)return;this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);let o=this._options.uniformBuffers,l=!1;if(a&&o&&o.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let i=0;i<o.length;++i){let r=o[i];switch(r){case"Mesh":t&&(t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e));break;case"Scene":s3.G.BindSceneUniformBuffer(a,this.getScene().getSceneUniformBuffer()),this.getScene().finalizeSceneUbo(),l=!0}}let h=t&&n?this._mustRebind(this.getScene(),a,t.visibility):this.getScene().getCachedMaterial()!==this;if(a&&h){let e;for(e in l||-1===this._options.uniforms.indexOf("view")||a.setMatrix("view",this.getScene().getViewMatrix()),l||-1===this._options.uniforms.indexOf("projection")||a.setMatrix("projection",this.getScene().getProjectionMatrix()),!l&&-1!==this._options.uniforms.indexOf("viewProjection")&&(a.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._multiview&&a.setMatrix("viewProjectionR",this.getScene()._transformMatrixR)),this.getScene().activeCamera&&-1!==this._options.uniforms.indexOf("cameraPosition")&&a.setVector3("cameraPosition",this.getScene().activeCamera.globalPosition),s3.G.BindBonesParameters(t,a),(0,lx.an)(a,this,this.getScene()),this._textures)a.setTexture(e,this._textures[e]);for(e in this._textureArrays)a.setTextureArray(e,this._textureArrays[e]);for(e in this._externalTextures)a.setExternalTexture(e,this._externalTextures[e]);for(e in this._ints)a.setInt(e,this._ints[e]);for(e in this._uints)a.setUInt(e,this._uints[e]);for(e in this._floats)a.setFloat(e,this._floats[e]);for(e in this._floatsArrays)a.setArray(e,this._floatsArrays[e]);for(e in this._colors3)a.setColor3(e,this._colors3[e]);for(e in this._colors3Arrays)a.setArray3(e,this._colors3Arrays[e]);for(e in this._colors4){let t=this._colors4[e];a.setFloat4(e,t.r,t.g,t.b,t.a)}for(e in this._colors4Arrays)a.setArray4(e,this._colors4Arrays[e]);for(e in this._vectors2)a.setVector2(e,this._vectors2[e]);for(e in this._vectors3)a.setVector3(e,this._vectors3[e]);for(e in this._vectors4)a.setVector4(e,this._vectors4[e]);for(e in this._quaternions)a.setQuaternion(e,this._quaternions[e]);for(e in this._matrices)a.setMatrix(e,this._matrices[e]);for(e in this._matrixArrays)a.setMatrices(e,this._matrixArrays[e]);for(e in this._matrices3x3)a.setMatrix3x3(e,this._matrices3x3[e]);for(e in this._matrices2x2)a.setMatrix2x2(e,this._matrices2x2[e]);for(e in this._vectors2Arrays)a.setArray2(e,this._vectors2Arrays[e]);for(e in this._vectors3Arrays)a.setArray3(e,this._vectors3Arrays[e]);for(e in this._vectors4Arrays)a.setArray4(e,this._vectors4Arrays[e]);for(e in this._quaternionsArrays)a.setArray4(e,this._quaternionsArrays[e]);for(e in this._uniformBuffers){let t=this._uniformBuffers[e].getBuffer();t&&a.bindUniformBuffer(t,e)}for(e in this._textureSamplers)a.setTextureSampler(e,this._textureSamplers[e]);for(e in this._storageBuffers)a.setStorageBuffer(e,this._storageBuffers[e])}if(a&&t&&(h||!this.isFrozen)){let e=t.morphTargetManager;e&&e.numInfluencers>0&&s3.G.BindMorphTargetParameters(t,a);let i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(a,!!a._wasPreviouslyUsingInstances))}this._afterBind(t,a)}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._textures)e.push(this._textures[t]);for(let t in this._textureArrays){let i=this._textureArrays[t];for(let t=0;t<i.length;t++)e.push(i[t])}return e}hasTexture(e){if(super.hasTexture(e))return!0;for(let t in this._textures)if(this._textures[t]===e)return!0;for(let t in this._textureArrays){let i=this._textureArrays[t];for(let t=0;t<i.length;t++)if(i[t]===e)return!0}return!1}clone(e){let t=rg.p4.Clone(()=>new hf(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);for(let i in 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=>{let t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))}),this.stencil.copyTo(t.stencil),this._textures)t.setTexture(i,this._textures[i]);for(let e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(let e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(let e in this._ints)t.setInt(e,this._ints[e]);for(let e in this._uints)t.setUInt(e,this._uints[e]);for(let e in this._floats)t.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(let e in this._colors3)t.setColor3(e,this._colors3[e]);for(let e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(let e in this._colors4)t.setColor4(e,this._colors4[e]);for(let e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(let e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(let e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(let e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(let e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(let e in this._matrices)t.setMatrix(e,this._matrices[e]);for(let e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(let e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(let e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(let e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(let e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(let e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(let e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(let e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(let e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){let t=this._textureArrays[e];for(let e=0;e<t.length;e++)t[e].dispose()}}this._textures={},super.dispose(e,t,i)}serialize(){let e;let t=rg.p4.Serialize(this);for(e in t.customType="BABYLON.ShaderMaterial",t.uniqueId=this.uniqueId,t.options=this._options,t.shaderPath=this._shaderPath,t.storeEffectOnSubMeshes=this._storeEffectOnSubMeshes,t.stencil=this.stencil.serialize(),t.textures={},this._textures)t.textures[e]=this._textures[e].serialize();for(e in t.textureArrays={},this._textureArrays){t.textureArrays[e]=[];let i=this._textureArrays[e];for(let r=0;r<i.length;r++)t.textureArrays[e].push(i[r].serialize())}for(e in t.ints={},this._ints)t.ints[e]=this._ints[e];for(e in t.uints={},this._uints)t.uints[e]=this._uints[e];for(e in t.floats={},this._floats)t.floats[e]=this._floats[e];for(e in t.FloatArrays={},this._floatsArrays)t.FloatArrays[e]=this._floatsArrays[e];for(e in t.colors3={},this._colors3)t.colors3[e]=this._colors3[e].asArray();for(e in t.colors3Arrays={},this._colors3Arrays)t.colors3Arrays[e]=this._colors3Arrays[e];for(e in t.colors4={},this._colors4)t.colors4[e]=this._colors4[e].asArray();for(e in t.colors4Arrays={},this._colors4Arrays)t.colors4Arrays[e]=this._colors4Arrays[e];for(e in t.vectors2={},this._vectors2)t.vectors2[e]=this._vectors2[e].asArray();for(e in t.vectors3={},this._vectors3)t.vectors3[e]=this._vectors3[e].asArray();for(e in t.vectors4={},this._vectors4)t.vectors4[e]=this._vectors4[e].asArray();for(e in t.quaternions={},this._quaternions)t.quaternions[e]=this._quaternions[e].asArray();for(e in t.matrices={},this._matrices)t.matrices[e]=this._matrices[e].asArray();for(e in t.matrixArray={},this._matrixArrays)t.matrixArray[e]=this._matrixArrays[e];for(e in t.matrices3x3={},this._matrices3x3)t.matrices3x3[e]=this._matrices3x3[e];for(e in t.matrices2x2={},this._matrices2x2)t.matrices2x2[e]=this._matrices2x2[e];for(e in t.vectors2Arrays={},this._vectors2Arrays)t.vectors2Arrays[e]=this._vectors2Arrays[e];for(e in t.vectors3Arrays={},this._vectors3Arrays)t.vectors3Arrays[e]=this._vectors3Arrays[e];for(e in t.vectors4Arrays={},this._vectors4Arrays)t.vectors4Arrays[e]=this._vectors4Arrays[e];for(e in t.quaternionsArrays={},this._quaternionsArrays)t.quaternionsArrays[e]=this._quaternionsArrays[e];return t}static Parse(e,t,i){let r;let s=rg.p4.Parse(()=>new hf(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,sv.Parse(e.textures[r],t,i));for(r in e.textureArrays){let n=e.textureArrays[r],a=[];for(let e=0;e<n.length;e++)a.push(sv.Parse(n[e],t,i));s.setTextureArray(r,a)}for(r in e.ints)s.setInt(r,e.ints[r]);for(r in e.uints)s.setUInt(r,e.uints[r]);for(r in e.floats)s.setFloat(r,e.floats[r]);for(r in e.floatsArrays)s.setFloats(r,e.floatsArrays[r]);for(r in e.colors3)s.setColor3(r,rs.Wo.FromArray(e.colors3[r]));for(r in e.colors3Arrays){let t=e.colors3Arrays[r].reduce((e,t,i)=>(i%3==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>rs.Wo.FromArray(e));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,rs.HE.FromArray(e.colors4[r]));for(r in e.colors4Arrays){let t=e.colors4Arrays[r].reduce((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>rs.HE.FromArray(e));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,rr.FM.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,rr.P.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,rr.Lt.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,rr._f.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,rr.y3.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,n)=>{let a=new rS.g;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let t=JSON.parse(a.responseText),n=this.Parse(t,i||rp.l.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the ShaderMaterial")}}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((r,s)=>{let n=new rS.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let s=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(s.shaderMaterial),o=this.Parse(a,t||rp.l.LastCreatedScene,i);o.snippetId=e,r(o)}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}hf.SnippetUrl="https://snippet.babylonjs.com",hf.CreateFromSnippetAsync=hf.ParseFromSnippetAsync,(0,rn.H)("BABYLON.ShaderMaterial",hf);let hm=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -#define VERTEXCOLOR -varying vec4 vColor; -#else -uniform vec4 color; -#endif -#include<clipPlaneFragmentDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -gl_FragColor=vColor; -#else -gl_FragColor=color; -#endif -#define CUSTOM_FRAGMENT_MAIN_END -}`;no.v.ShadersStore.colorPixelShader=hm;let hg=`attribute vec3 position; -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<clipPlaneVertexDeclaration> -#include<instancesDeclaration> -uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(position,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#include<clipPlaneVertex> -#include<vertexColorMixing> -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.colorVertexShader=hg,rq.Kj._LinesMeshParser=(e,t)=>hv.Parse(e,t);class hv extends rq.Kj{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,r=null,s,n,a,o){super(e,t,i,r,s),this.useVertexColor=n,this.useVertexAlpha=a,this.color=new rs.Wo(1,1,1),this.alpha=1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;let l={attributes:[rQ.o.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===a?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(rQ.o.ColorKind)):(l.uniforms.push("color"),this._color4=new rs.HE),o?this.material=o:(this.material=new hf("colorShader",this.getScene(),"color",l,!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=sX.F.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;let 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)){let{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;let r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(sX.F.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(sX.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 hv(e,this.getScene(),t,this,i)}createInstance(e){let t=new hT(e,this);if(this.instancedBuffers)for(let e in t.instancedBuffers={},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){let i=new hv(e.name,t);return i.color=rs.Wo.FromArray(e.color),i.alpha=e.alpha,i}}class hT extends rJ{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function hx(e){let t=[],i=[],r=e.lines,s=e.colors,n=[],a=0;for(let e=0;e<r.length;e++){let o=r[e];for(let r=0;r<o.length;r++){if(i.push(o[r].x,o[r].y,o[r].z),s){let t=s[e];n.push(t[r].r,t[r].g,t[r].b,t[r].a)}r>0&&(t.push(a-1),t.push(a)),a++}}let o=new sN.x;return o.indices=t,o.positions=i,s&&(o.colors=n),o}function hS(e){let t=e.dashSize||3,i=e.gapSize||1,r=e.dashNb||200,s=e.points,n=[],a=[],o=rr.P.Zero(),l=0,h=0,u=0,c=0,d=0,p=0,_=0;for(_=0;_<s.length-1;_++)s[_+1].subtractToRef(s[_],o),l+=o.length();for(_=0,c=t*(u=l/r)/(t+i);_<s.length-1;_++){s[_+1].subtractToRef(s[_],o),h=Math.floor(o.length()/u),o.normalize();for(let e=0;e<h;e++)d=u*e,n.push(s[_].x+d*o.x,s[_].y+d*o.y,s[_].z+d*o.z),n.push(s[_].x+(d+c)*o.x,s[_].y+(d+c)*o.y,s[_].z+(d+c)*o.z),a.push(p,p+1),p+=2}let f=new sN.x;return f.positions=n,f.indices=a,f}function hE(e,t,i=null){let r=t.instance,s=t.lines,n=t.colors;if(r){let e,t;let i=r.getVerticesData(rQ.o.PositionKind);n&&(e=r.getVerticesData(rQ.o.ColorKind));let a=0,o=0;for(let r=0;r<s.length;r++){let l=s[r];for(let s=0;s<l.length;s++)i[a]=l[s].x,i[a+1]=l[s].y,i[a+2]=l[s].z,n&&e&&(t=n[r],e[o]=t[s].r,e[o+1]=t[s].g,e[o+2]=t[s].b,e[o+3]=t[s].a,o+=4),a+=3}return r.updateVerticesData(rQ.o.PositionKind,i,!1,!1),n&&e&&r.updateVerticesData(rQ.o.ColorKind,e,!1,!1),r}let a=new hv(e,i,null,void 0,void 0,!!n,t.useVertexAlpha,t.material),o=hx(t);return o.applyToMesh(a,t.updatable),a}function hC(e,t,i=null){let r=t.colors?[t.colors]:null,s=hE(e,{lines:[t.points],updatable:t.updatable,instance:t.instance,colors:r,useVertexAlpha:t.useVertexAlpha,material:t.material},i);return s}sN.x.CreateLineSystem=hx,sN.x.CreateDashedLines=hS,rq.Kj.CreateLines=(e,t,i=null,r=!1,s=null)=>hC(e,{points:t,updatable:r,instance:s},i),rq.Kj.CreateDashedLines=(e,t,i,r,s,n=null,a,o)=>(function(e,t,i=null){let r=t.points,s=t.instance,n=t.gapSize||1,a=t.dashSize||3;if(s)return(t.dashNb||t.dashSize||t.gapSize||t.useVertexAlpha||t.material)&&ru.Y.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."),s.updateMeshPositions(e=>{let t=rr.P.Zero(),i=e.length/6,n=0,a=0,o=0,l=0,h=0,u=0,c=0,d=0;for(c=0;c<r.length-1;c++)r[c+1].subtractToRef(r[c],t),n+=t.length();o=n/i;let p=s._creationDataStorage.dashSize,_=s._creationDataStorage.gapSize;for(c=0,l=p*o/(p+_);c<r.length-1;c++)for(r[c+1].subtractToRef(r[c],t),a=Math.floor(t.length()/o),t.normalize(),d=0;d<a&&u<e.length;)h=o*d,e[u]=r[c].x+h*t.x,e[u+1]=r[c].y+h*t.y,e[u+2]=r[c].z+h*t.z,e[u+3]=r[c].x+(h+l)*t.x,e[u+4]=r[c].y+(h+l)*t.y,e[u+5]=r[c].z+(h+l)*t.z,u+=6,d++;for(;u<e.length;)e[u]=r[c].x,e[u+1]=r[c].y,e[u+2]=r[c].z,u+=3},!1),s;let o=new hv(e,i,null,void 0,void 0,void 0,t.useVertexAlpha,t.material),l=hS(t);return l.applyToMesh(o,t.updatable),o._creationDataStorage=new rq.gW,o._creationDataStorage.dashSize=a,o._creationDataStorage.gapSize=n,o})(e,{points:t,dashSize:i,gapSize:r,dashNb:s,updatable:a,instance:o},n);class hb extends rr.FM{constructor(e,t){super(e.x,e.y),this.index=t}}class hy{constructor(){this.elements=[]}add(e){let t=[];return e.forEach(e=>{let i=new hb(e,this.elements.length);t.push(i),this.elements.push(i)}),t}computeBounds(){let e=new rr.FM(this.elements[0].x,this.elements[0].y),t=new rr.FM(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.x<e.x?e.x=i.x:i.x>t.x&&(t.x=i.x),i.y<e.y?e.y=i.y:i.y>t.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class hA{_addToepoint(e){for(let t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){let s;this._points=new hy,this._outlinepoints=new hy,this._holes=[],this._epoints=[],this._eholes=[],this.bjsEarcut=r,this._name=e,this._scene=i||rp.l.LastCreatedScene,s=t instanceof rU?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&ru.Y.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);let t=new hy;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){let r=new rq.Kj(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(rQ.o.PositionKind,s.positions,e),r.setVerticesData(rQ.o.NormalKind,s.normals,e),r.setVerticesData(rQ.o.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){let i=new sN.x,r=[],s=[],n=[],a=this._points.computeBounds();this._points.elements.forEach(e=>{r.push(0,1,0),s.push(e.x,0,e.y),n.push((e.x-a.min.x)/a.width,(e.y-a.min.y)/a.height)});let o=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e<l.length;e++)o.push(l[e]);if(e>0){let i=s.length/3;this._points.elements.forEach(t=>{r.push(0,-1,0),s.push(t.x,-e,t.y),n.push(1-(t.x-a.min.x)/a.width,1-(t.y-a.min.y)/a.height)});let l=o.length;for(let e=0;e<l;e+=3){let t=o[e+0],r=o[e+1],s=o[e+2];o.push(s+i),o.push(r+i),o.push(t+i)}this._addSide(s,r,n,o,a,this._outlinepoints,e,!1,t),this._holes.forEach(i=>{this._addSide(s,r,n,o,a,i,e,!0,t)})}return i.indices=o,i.positions=s,i.normals=r,i.uvs=n,i}_addSide(e,t,i,r,s,n,a,o,l){let h=e.length/3,u=0;for(let c=0;c<n.elements.length;c++){let d=n.elements[c],p=n.elements[(c+1)%n.elements.length];e.push(d.x,0,d.y),e.push(d.x,-a,d.y),e.push(p.x,0,p.y),e.push(p.x,-a,p.y);let _=n.elements[(c+n.elements.length-1)%n.elements.length],f=n.elements[(c+2)%n.elements.length],m=new rr.P(-(p.y-d.y),0,p.x-d.x),g=new rr.P(-(d.y-_.y),0,d.x-_.x),v=new rr.P(-(f.y-p.y),0,f.x-p.x);o||(m=m.scale(-1),g=g.scale(-1),v=v.scale(-1));let T=m.normalizeToNew(),x=g.normalizeToNew(),S=v.normalizeToNew(),E=rr.P.Dot(x,T);x=E>l?E<rL.kn-1?new rr.P(d.x,0,d.y).subtract(new rr.P(p.x,0,p.y)).normalize():g.add(m).normalize():T;let C=rr.P.Dot(v,m);S=C>l?C<rL.kn-1?new rr.P(p.x,0,p.y).subtract(new rr.P(d.x,0,d.y)).normalize():v.add(m).normalize():T,i.push(u/s.width,0),i.push(u/s.width,1),u+=m.length(),i.push(u/s.width,0),i.push(u/s.width,1),t.push(x.x,x.y,x.z),t.push(x.x,x.y,x.z),t.push(S.x,S.y,S.z),t.push(S.x,S.y,S.z),o?(r.push(h),r.push(h+2),r.push(h+1),r.push(h+1),r.push(h+2),r.push(h+3)):(r.push(h),r.push(h+1),r.push(h+2),r.push(h+1),r.push(h+3),r.push(h+2)),h+=4}}}function hR(e,t,i,r,s,n,a){let o=i||[,,,],l=[],h=a||!1;for(let e=0;e<3;e++)void 0===o[e]&&(o[e]=new rr.Lt(0,0,1,1)),r&&void 0===r[e]&&(r[e]=new rs.HE(1,1,1,1));let u=e.getVerticesData(rQ.o.PositionKind),c=e.getVerticesData(rQ.o.NormalKind),d=e.getVerticesData(rQ.o.UVKind),p=e.getIndices(),_=u.length/9,f=0,m=0,g=0,v=0,T=[0];if(h)for(let e=_;e<u.length/3;e+=4)T.push(v+=Math.sqrt((m=u[3*(e+2)]-u[3*e])*m+(g=u[3*(e+2)+2]-u[3*e+2])*g));let x=0,S=0;for(let e=0;e<c.length;e+=3).001>Math.abs(c[e+1])&&(S=1),.001>Math.abs(c[e+1]-1)&&(S=0),.001>Math.abs(c[e+1]+1)&&(S=2),x=e/3,1===S?((f=x-_)%4<1.5?h?d[2*x]=o[S].x+(o[S].z-o[S].x)*T[Math.floor(f/4)]/v:d[2*x]=o[S].x:h?d[2*x]=o[S].x+(o[S].z-o[S].x)*T[Math.floor(f/4)+1]/v:d[2*x]=o[S].z,f%2==0?d[2*x+1]=sg.e.UseOpenGLOrientationForUV?1-o[S].w:o[S].w:d[2*x+1]=sg.e.UseOpenGLOrientationForUV?1-o[S].y:o[S].y):(d[2*x]=(1-d[2*x])*o[S].x+d[2*x]*o[S].z,d[2*x+1]=(1-d[2*x+1])*o[S].y+d[2*x+1]*o[S].w,sg.e.UseOpenGLOrientationForUV&&(d[2*x+1]=1-d[2*x+1])),r&&l.push(r[S].r,r[S].g,r[S].b,r[S].a);sN.x._ComputeSides(t,u,p,c,d,s,n);let E=new sN.x;if(E.indices=p,E.positions=u,E.normals=c,E.uvs=d,r){let e=t===sN.x.DOUBLESIDE?l.concat(l):l;E.colors=e}return E}function hP(e,t,i=null,r=earcut){t.sideOrientation=rq.Kj._GetDefaultSideOrientation(t.sideOrientation);let s=t.shape,n=t.holes||[],a=t.depth||0,o=t.smoothingThreshold||2,l=[],h=[];for(let e=0;e<s.length;e++)l[e]=new rr.FM(s[e].x,s[e].z);l[0].equalsWithEpsilon(l[l.length-1],1e-8)&&l.pop();let u=new hA(e,l,i||rp.l.LastCreatedScene,r);for(let e=0;e<n.length;e++){h=[];for(let t=0;t<n[e].length;t++)h.push(new rr.FM(n[e][t].x,n[e][t].z));u.addHole(h)}let c=u.build(!1,a,o);c._originalBuilderSideOrientation=t.sideOrientation;let d=hR(c,t.sideOrientation,t.faceUV,t.faceColors,t.frontUVs,t.backUVs,t.wrap);return d.applyToMesh(c,t.updatable),c}function hI(e,t,i=null){let r=t.path,s=t.shape,n=t.scale||1,a=t.rotation||0,o=0===t.cap?0:t.cap||rq.Kj.NO_CAP,l=t.updatable,h=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),u=t.instance||null,c=t.invertUV||!1,d=t.closeShape||!1,p=t.closePath||!1;return hD(e,s,r,n,a,null,null,p,d,o,!1,i,!!l,h,u,c,t.frontUVs||null,t.backUVs||null,t.firstNormal||null,!!t.adjustFrame)}function hM(e,t,i=null){let r=t.path,s=t.shape,n=t.scaleFunction||(()=>1),a=t.rotationFunction||(()=>0),o=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||rq.Kj.NO_CAP,u=t.updatable,c=t.firstNormal||null,d=t.adjustFrame||!1,p=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),_=t.instance,f=t.invertUV||!1;return hD(e,s,r,null,null,n,a,o,l,h,!0,i,!!u,p,_||null,f,t.frontUVs||null,t.backUVs||null,c,d)}function hD(e,t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,T){let x,S;let E=(e,t,i,r,s,n,a,o,l,h,u)=>{let c=i.getTangents(),d=i.getNormals(),p=i.getBinormals(),_=i.getDistances();if(u){for(let e=0;e<c.length;e++)if(0==c[e].x&&0==c[e].y&&0==c[e].z&&c[e].copyFrom(c[e-1]),0==d[e].x&&0==d[e].y&&0==d[e].z&&d[e].copyFrom(d[e-1]),0==p[e].x&&0==p[e].y&&0==p[e].z&&p[e].copyFrom(p[e-1]),e>0){let t=c[e-1];0>rr.P.Dot(t,c[e])&&c[e].scaleInPlace(-1),t=d[e-1],0>rr.P.Dot(t,d[e])&&d[e].scaleInPlace(-1),t=p[e-1],0>rr.P.Dot(t,p[e])&&p[e].scaleInPlace(-1)}}let f=0,m=h&&o?o:()=>null!==n?n:0,g=h&&a?a:()=>null!==s?s:1,v=l===rq.Kj.NO_CAP||l===rq.Kj.CAP_END?0:2,T=rr.jp.Matrix[0];for(let i=0;i<t.length;i++){let s=[],n=m(i,_[i]),a=g(i,_[i]);rr.y3.RotationAxisToRef(c[i],f,T);for(let r=0;r<e.length;r++){let n=c[i].scale(e[r].z).add(d[i].scale(e[r].x)).add(p[i].scale(e[r].y)),o=rr.P.Zero();rr.P.TransformCoordinatesToRef(n,T,o),o.scaleInPlace(a).addInPlace(t[i]),s[r]=o}r[v]=s,f+=n,v++}let x=e=>{let t;let i=[],r=rr.P.Zero();for(t=0;t<e.length;t++)r.addInPlace(e[t]);for(r.scaleInPlace(1/e.length),t=0;t<e.length;t++)i.push(r);return i};switch(l){case rq.Kj.NO_CAP:break;case rq.Kj.CAP_START:r[0]=x(r[2]),r[1]=r[2];break;case rq.Kj.CAP_END:r[v]=r[v-1],r[v+1]=x(r[v-1]);break;case rq.Kj.CAP_ALL:r[0]=x(r[2]),r[1]=r[2],r[v]=r[v-1],r[v+1]=x(r[v-1])}return r};if(_){let e=_._creationDataStorage;return x=v?e.path3D.update(i,v):e.path3D.update(i),_=hh("",{pathArray:S=E(t,i,e.path3D,e.pathArray,r,s,n,a,e.cap,u,T),closeArray:!1,closePath:!1,offset:0,updatable:!1,sideOrientation:0,instance:_},c||void 0)}x=v?new rV(i,v):new rV(i),S=E(t,i,x,[],r,s,n,a,h=h<0||h>3?0:h,u,T);let C=hh(e,{pathArray:S,closeArray:o,closePath:l,updatable:d,sideOrientation:p,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},c);return C._creationDataStorage.pathArray=S,C._creationDataStorage.path3D=x,C._creationDataStorage.cap=h,C}function hO(e){let t,i,r,s,n,a;let o=[];o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]},o[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]]};let l=e.type&&(e.type<0||e.type>=o.length)?0:e.type||0,h=e.size,u=e.sizeX||h||1,c=e.sizeY||h||1,d=e.sizeZ||h||1,p=e.custom||o[l],_=p.face.length,f=e.faceUV||Array(_),m=e.faceColors,g=void 0===e.flat||e.flat,v=0===e.sideOrientation?0:e.sideOrientation||sN.x.DEFAULTSIDE,T=[],x=[],S=[],E=[],C=[],b=0,y=0,A=[],R=0,P=0;if(g)for(P=0;P<_;P++)m&&void 0===m[P]&&(m[P]=new rs.HE(1,1,1,1)),f&&void 0===f[P]&&(f[P]=new rr.Lt(0,0,1,1));if(g)for(P=0;P<_;P++){let e=p.face[P].length;for(R=0,s=.5*Math.tan((r=2*Math.PI/e)/2),n=.5;R<e;R++)T.push(p.vertex[p.face[P][R]][0]*u,p.vertex[p.face[P][R]][1]*c,p.vertex[p.face[P][R]][2]*d),A.push(b),b++,t=f[P].x+(f[P].z-f[P].x)*(.5+s),i=f[P].y+(f[P].w-f[P].y)*(n-.5),E.push(t,sg.e.UseOpenGLOrientationForUV?1-i:i),a=s*Math.cos(r)-n*Math.sin(r),n=s*Math.sin(r)+n*Math.cos(r),s=a,m&&C.push(m[P].r,m[P].g,m[P].b,m[P].a);for(R=0;R<e-2;R++)x.push(A[0+y],A[R+2+y],A[R+1+y]);y+=e}else{for(R=0;R<p.vertex.length;R++)T.push(p.vertex[R][0]*u,p.vertex[R][1]*c,p.vertex[R][2]*d),E.push(0,sg.e.UseOpenGLOrientationForUV?1:0);for(P=0;P<_;P++)for(R=0;R<p.face[P].length-2;R++)x.push(p.face[P][0],p.face[P][R+2],p.face[P][R+1])}sN.x.ComputeNormals(T,x,S),sN.x._ComputeSides(v,T,x,S,E,e.frontUVs,e.backUVs);let I=new sN.x;return I.positions=T,I.indices=x,I.normals=S,I.uvs=E,m&&g&&(I.colors=C),I}sN.x.CreatePolygon=hR,rq.Kj.CreatePolygon=(e,t,i,r,s,n,a=earcut)=>hP(e,{shape:t,holes:r,updatable:s,sideOrientation:n},i,a),rq.Kj.ExtrudePolygon=(e,t,i,r,s,n,a,o=earcut)=>(function(e,t,i=null,r=earcut){return hP(e,t,i,r)})(e,{shape:t,holes:s,depth:i,updatable:n,sideOrientation:a},r,o),rq.Kj.ExtrudeShape=(e,t,i,r,s,n,a=null,o,l,h)=>{let u={shape:t,path:i,scale:r,rotation:s,cap:0===n?0:n||rq.Kj.NO_CAP,sideOrientation:l,instance:h,updatable:o};return hI(e,u,a)},rq.Kj.ExtrudeShapeCustom=(e,t,i,r,s,n,a,o,l,h,u,c)=>{let d={shape:t,path:i,scaleFunction:r,rotationFunction:s,ribbonCloseArray:n,ribbonClosePath:a,cap:0===o?0:o||rq.Kj.NO_CAP,sideOrientation:u,instance:c,updatable:h};return hM(e,d,l)},rq.Kj.CreateLathe=(e,t,i,r,s,n,a)=>(function(e,t,i=null){let r,s;let n=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,a=void 0===t.closed||t.closed,o=t.shape,l=t.radius||1,h=t.tessellation||64,u=t.clip||0,c=t.updatable,d=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),p=t.cap||rq.Kj.NO_CAP,_=[],f=t.invertUV||!1,m=0,g=0,v=2*Math.PI/h*n;for(m=0;m<=h-u;m++){for(s=[],(p==rq.Kj.CAP_START||p==rq.Kj.CAP_ALL)&&(s.push(new rr.P(0,o[0].y,0)),s.push(new rr.P(Math.cos(m*v)*o[0].x*l,o[0].y,Math.sin(m*v)*o[0].x*l))),g=0;g<o.length;g++)r=new rr.P(Math.cos(m*v)*o[g].x*l,o[g].y,Math.sin(m*v)*o[g].x*l),s.push(r);(p==rq.Kj.CAP_END||p==rq.Kj.CAP_ALL)&&(s.push(new rr.P(Math.cos(m*v)*o[o.length-1].x*l,o[o.length-1].y,Math.sin(m*v)*o[o.length-1].x*l)),s.push(new rr.P(0,o[o.length-1].y,0))),_.push(s)}let T=hh(e,{pathArray:_,closeArray:a,sideOrientation:d,updatable:c,invertUV:f,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return T})(e,{shape:t,radius:i,tessellation:r,sideOrientation:a,updatable:n},s),rq.Kj.CreateTube=(e,t,i,r,s,n,a,o,l,h)=>(function(e,t,i=null){let r,s;let n=t.path,a=t.instance,o=1;void 0!==t.radius?o=t.radius:a&&(o=a._creationDataStorage.radius);let l=t.tessellation||64,h=t.radiusFunction||null,u=t.cap||rq.Kj.NO_CAP,c=t.invertUV||!1,d=t.updatable,p=rq.Kj._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;let _=(e,t,i,r,s,n,a,o)=>{let l,h,u,c;let d=t.getTangents(),p=t.getNormals(),_=t.getDistances(),f=2*Math.PI/s*o,m=n||(()=>r),g=rr.jp.Matrix[0],v=a===rq.Kj.NO_CAP||a===rq.Kj.CAP_END?0:2;for(let t=0;t<e.length;t++){h=m(t,_[t]),l=[],u=p[t];for(let i=0;i<s;i++)rr.y3.RotationAxisToRef(d[t],f*i,g),c=l[i]?l[i]:rr.P.Zero(),rr.P.TransformCoordinatesToRef(u,g,c),c.scaleInPlace(h).addInPlace(e[t]),l[i]=c;i[v]=l,v++}let T=(t,i)=>{let r=[];for(let s=0;s<t;s++)r.push(e[i]);return r};switch(a){case rq.Kj.NO_CAP:break;case rq.Kj.CAP_START:i[0]=T(s,0),i[1]=i[2].slice(0);break;case rq.Kj.CAP_END:i[v]=i[v-1].slice(0),i[v+1]=T(s,e.length-1);break;case rq.Kj.CAP_ALL:i[0]=T(s,0),i[1]=i[2].slice(0),i[v]=i[v-1].slice(0),i[v+1]=T(s,e.length-1)}return i};if(a){let e=a._creationDataStorage,i=t.arc||e.arc;return r=e.path3D.update(n),a=hh("",{pathArray:s=_(n,r,e.pathArray,o,e.tessellation,h,e.cap,i),instance:a}),e.path3D=r,e.pathArray=s,e.arc=i,e.radius=o,a}r=new rV(n),s=_(n,r,[],o,l,h,u=u<0||u>3?0:u,t.arc);let f=hh(e,{pathArray:s,closePath:!0,closeArray:!1,updatable:d,sideOrientation:p,invertUV:c,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return f._creationDataStorage.pathArray=s,f._creationDataStorage.path3D=r,f._creationDataStorage.tessellation=l,f._creationDataStorage.cap=u,f._creationDataStorage.arc=t.arc,f._creationDataStorage.radius=o,f})(e,{path:t,radius:i,tessellation:r,radiusFunction:s,arc:1,cap:n,updatable:o,sideOrientation:l,instance:h},a),sN.x.CreatePolyhedron=hO,rq.Kj.CreatePolyhedron=(e,t,i)=>(function(e,t={},i=null){let r=new rq.Kj(e,i);t.sideOrientation=rq.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=hO(t);return s.applyToMesh(r,t.updatable),r})(e,t,i);let hN=new rr.P(1,0,0),hF=new rr.P(-1,0,0),hL=new rr.P(0,1,0),hw=new rr.P(0,-1,0),hB=new rr.P(0,0,1),hU=new rr.P(0,0,-1);class hV{constructor(e=rr.P.Zero(),t=rr.P.Up(),i=rr.FM.Zero(),r=0,s=0,n=null,a=null,o=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=n,this.localNormalOverride=a,this.matrixIndicesOverride=o,this.matrixWeightsOverride=l}clone(){var e,t,i,r;return new hV(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===(r=this.matrixWeightsOverride)||void 0===r?void 0:r.slice())}}rq.Kj.CreateDecal=(e,t,i,r,s,n)=>(function(e,t,i){var r,s,n,a;let o=!!t.skeleton,l=i.localMode||o,h=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,u=t.getIndices(),c=o?t.getPositionData(!0,!0):t.getVerticesData(rQ.o.PositionKind),d=o?t.getNormalsData(!0,!0):t.getVerticesData(rQ.o.NormalKind),p=l?o?t.getVerticesData(rQ.o.PositionKind):c:null,_=l?o?t.getVerticesData(rQ.o.NormalKind):d:null,f=t.getVerticesData(rQ.o.UVKind),m=o?t.getVerticesData(rQ.o.MatricesIndicesKind):null,g=o?t.getVerticesData(rQ.o.MatricesWeightsKind):null,v=o?t.getVerticesData(rQ.o.MatricesIndicesExtraKind):null,T=o?t.getVerticesData(rQ.o.MatricesWeightsExtraKind):null,x=i.position||rr.P.Zero(),S=i.normal||rr.P.Up(),E=i.size||rr.P.One(),C=i.angle||0;if(!S){let e=new rr.P(0,0,1),i=t.getScene().activeCamera,r=rr.P.TransformCoordinates(e,i.getWorldMatrix());S=i.globalPosition.subtract(r)}let b=-Math.atan2(S.z,S.x)-Math.PI/2,y=Math.sqrt(S.x*S.x+S.z*S.z),A=Math.atan2(S.y,y),R=new sN.x;R.indices=[],R.positions=[],R.normals=[],R.uvs=[],R.matricesIndices=o?[]:null,R.matricesWeights=o?[]:null,R.matricesIndicesExtra=v?[]:null,R.matricesWeightsExtra=T?[]:null;let P=0,I=(e,t)=>{let r=new hV;if(!u||!c||!d)return r;let s=u[e];if(r.vertexIdx=3*s,r.vertexIdxForBones=4*s,r.position=new rr.P(c[3*s],c[3*s+1],c[3*s+2]),rr.P.TransformCoordinatesToRef(r.position,t,r.position),r.normal=new rr.P(d[3*s],d[3*s+1],d[3*s+2]),rr.P.TransformNormalToRef(r.normal,t,r.normal),i.captureUVS&&f){let e=f[2*s+1];r.uv=new rr.FM(f[2*s],sg.e.UseOpenGLOrientationForUV?1-e:e)}return r},M=[0,0,0,0],D=(e,t)=>{if(0===e.length)return e;let i=.5*Math.abs(rr.P.Dot(E,t)),r=(e,t,i,r)=>{for(let s=0;s<r;++s)if(e[i+s]===t)return i+s;return -1},s=(e,s)=>{var n,a,o,l,h,u,c,d,f,v,T,x,S,E,C,b;let y=rr.P.GetClipFactor(e.position,s.position,t,i),A=M,R=M;if(m&&g){let t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=null!==(n=e.matrixIndicesOverride)&&void 0!==n?n:m,h=null!==(a=e.matrixWeightsOverride)&&void 0!==a?a:g,u=s.matrixIndicesOverride?0:s.vertexIdxForBones,c=null!==(o=s.matrixIndicesOverride)&&void 0!==o?o:m,d=null!==(l=s.matrixWeightsOverride)&&void 0!==l?l:g;A=[0,0,0,0],R=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(h[t+e]>0){let s=r(c,i[t+e],u,4);A[p]=i[t+e],R[p]=rm.R.Lerp(h[t+e],s>=0?d[s]:0,y),p++}for(let e=0;e<4&&p<4;++e){let s=c[u+e];-1===r(i,s,t,4)&&(A[p]=s,R[p]=rm.R.Lerp(0,d[u+e],y),p++)}let _=R[0]+R[1]+R[2]+R[3];R[0]/=_,R[1]/=_,R[2]/=_,R[3]/=_}let P=e.localPositionOverride?e.localPositionOverride[0]:null!==(h=null==p?void 0:p[e.vertexIdx])&&void 0!==h?h:0,I=e.localPositionOverride?e.localPositionOverride[1]:null!==(u=null==p?void 0:p[e.vertexIdx+1])&&void 0!==u?u:0,D=e.localPositionOverride?e.localPositionOverride[2]:null!==(c=null==p?void 0:p[e.vertexIdx+2])&&void 0!==c?c:0,O=s.localPositionOverride?s.localPositionOverride[0]:null!==(d=null==p?void 0:p[s.vertexIdx])&&void 0!==d?d:0,N=s.localPositionOverride?s.localPositionOverride[1]:null!==(f=null==p?void 0:p[s.vertexIdx+1])&&void 0!==f?f:0,F=s.localPositionOverride?s.localPositionOverride[2]:null!==(v=null==p?void 0:p[s.vertexIdx+2])&&void 0!==v?v:0,L=e.localNormalOverride?e.localNormalOverride[0]:null!==(T=null==_?void 0:_[e.vertexIdx])&&void 0!==T?T:0,w=e.localNormalOverride?e.localNormalOverride[1]:null!==(x=null==_?void 0:_[e.vertexIdx+1])&&void 0!==x?x:0,B=e.localNormalOverride?e.localNormalOverride[2]:null!==(S=null==_?void 0:_[e.vertexIdx+2])&&void 0!==S?S:0,U=s.localNormalOverride?s.localNormalOverride[0]:null!==(E=null==_?void 0:_[s.vertexIdx])&&void 0!==E?E:0,V=s.localNormalOverride?s.localNormalOverride[1]:null!==(C=null==_?void 0:_[s.vertexIdx+1])&&void 0!==C?C:0,k=s.localNormalOverride?s.localNormalOverride[2]:null!==(b=null==_?void 0:_[s.vertexIdx+2])&&void 0!==b?b:0,G=L+(U-L)*y,z=w+(V-w)*y,W=B+(k-B)*y,H=Math.sqrt(G*G+z*z+W*W);return new hV(rr.P.Lerp(e.position,s.position,y),rr.P.Lerp(e.normal,s.normal,y).normalize(),rr.FM.Lerp(e.uv,s.uv,y),-1,-1,p?[P+(O-P)*y,I+(N-I)*y,D+(F-D)*y]:null,_?[G/H,z/H,W/H]:null,A,R)},n=null;e.length>3&&(n=[]);for(let r=0;r<e.length;r+=3){let a=null,o=null,l=null,h=null,u=rr.P.Dot(e[r].position,t)-i,c=rr.P.Dot(e[r+1].position,t)-i,d=rr.P.Dot(e[r+2].position,t)-i,p=u>0,_=c>0,f=d>0;switch((p?1:0)+(_?1:0)+(f?1:0)){case 0:e.length>3?(n.push(e[r]),n.push(e[r+1]),n.push(e[r+2])):n=e;break;case 1:if(n=null!=n?n:[],p&&(a=e[r+1],o=e[r+2],l=s(e[r],a),h=s(e[r],o)),_){a=e[r],o=e[r+2],l=s(e[r+1],a),h=s(e[r+1],o),n.push(l),n.push(o.clone()),n.push(a.clone()),n.push(o.clone()),n.push(l.clone()),n.push(h);break}f&&(a=e[r],o=e[r+1],l=s(e[r+2],a),h=s(e[r+2],o)),a&&o&&l&&h&&(n.push(a.clone()),n.push(o.clone()),n.push(l),n.push(h),n.push(l.clone()),n.push(o.clone()));break;case 2:n=null!=n?n:[],p||(o=s(a=e[r].clone(),e[r+1]),l=s(a,e[r+2]),n.push(a),n.push(o),n.push(l)),_||(o=s(a=e[r+1].clone(),e[r+2]),l=s(a,e[r]),n.push(a),n.push(o),n.push(l)),f||(o=s(a=e[r+2].clone(),e[r]),l=s(a,e[r+1]),n.push(a),n.push(o),n.push(l))}}return n},O=t instanceof rq.Kj?t:null,N=null==O?void 0:O._thinInstanceDataStorage.matrixData,F=(null==O?void 0:O.thinInstanceCount)||1,L=rr.jp.Matrix[0];L.copyFrom(rr.y3.IdentityReadOnly);for(let e=0;e<F;++e){if((null==O?void 0:O.hasThinInstances)&&N){let t=16*e;L.setRowFromFloats(0,N[t+0],N[t+1],N[t+2],N[t+3]),L.setRowFromFloats(1,N[t+4],N[t+5],N[t+6],N[t+7]),L.setRowFromFloats(2,N[t+8],N[t+9],N[t+10],N[t+11]),L.setRowFromFloats(3,N[t+12],N[t+13],N[t+14],N[t+15])}let r=rr.y3.RotationYawPitchRoll(b,A,C).multiply(rr.y3.Translation(x.x,x.y,x.z)),s=rr.y3.Invert(r),n=t.getWorldMatrix(),a=L.multiply(n).multiply(s),o=[,,,];for(let e=0;e<u.length;e+=3){let t=o;if(t[0]=I(e,a),h&&l?(t[1]=I(e+2,a),t[2]=I(e+1,a)):(t[1]=I(e+1,a),t[2]=I(e+2,a)),!(i.cullBackFaces&&0>=-t[0].normal.z&&0>=-t[1].normal.z&&0>=-t[2].normal.z)&&(t=D(t,hN))&&(t=D(t,hF))&&(t=D(t,hL))&&(t=D(t,hw))&&(t=D(t,hB))&&(t=D(t,hU)))for(let e=0;e<t.length;e++){let r=t[e];if(R.indices.push(P),l?(r.localPositionOverride?(R.positions[3*P]=r.localPositionOverride[0],R.positions[3*P+1]=r.localPositionOverride[1],R.positions[3*P+2]=r.localPositionOverride[2]):p&&(R.positions[3*P]=p[r.vertexIdx],R.positions[3*P+1]=p[r.vertexIdx+1],R.positions[3*P+2]=p[r.vertexIdx+2]),r.localNormalOverride?(R.normals[3*P]=r.localNormalOverride[0],R.normals[3*P+1]=r.localNormalOverride[1],R.normals[3*P+2]=r.localNormalOverride[2]):_&&(R.normals[3*P]=_[r.vertexIdx],R.normals[3*P+1]=_[r.vertexIdx+1],R.normals[3*P+2]=_[r.vertexIdx+2])):(r.position.toArray(R.positions,3*P),r.normal.toArray(R.normals,3*P)),R.matricesIndices&&R.matricesWeights&&(r.matrixIndicesOverride?(R.matricesIndices[4*P]=r.matrixIndicesOverride[0],R.matricesIndices[4*P+1]=r.matrixIndicesOverride[1],R.matricesIndices[4*P+2]=r.matrixIndicesOverride[2],R.matricesIndices[4*P+3]=r.matrixIndicesOverride[3]):(m&&(R.matricesIndices[4*P]=m[r.vertexIdxForBones],R.matricesIndices[4*P+1]=m[r.vertexIdxForBones+1],R.matricesIndices[4*P+2]=m[r.vertexIdxForBones+2],R.matricesIndices[4*P+3]=m[r.vertexIdxForBones+3]),v&&R.matricesIndicesExtra&&(R.matricesIndicesExtra[4*P]=v[r.vertexIdxForBones],R.matricesIndicesExtra[4*P+1]=v[r.vertexIdxForBones+1],R.matricesIndicesExtra[4*P+2]=v[r.vertexIdxForBones+2],R.matricesIndicesExtra[4*P+3]=v[r.vertexIdxForBones+3])),r.matrixWeightsOverride?(R.matricesWeights[4*P]=r.matrixWeightsOverride[0],R.matricesWeights[4*P+1]=r.matrixWeightsOverride[1],R.matricesWeights[4*P+2]=r.matrixWeightsOverride[2],R.matricesWeights[4*P+3]=r.matrixWeightsOverride[3]):(g&&(R.matricesWeights[4*P]=g[r.vertexIdxForBones],R.matricesWeights[4*P+1]=g[r.vertexIdxForBones+1],R.matricesWeights[4*P+2]=g[r.vertexIdxForBones+2],R.matricesWeights[4*P+3]=g[r.vertexIdxForBones+3]),T&&R.matricesWeightsExtra&&(R.matricesWeightsExtra[4*P]=T[r.vertexIdxForBones],R.matricesWeightsExtra[4*P+1]=T[r.vertexIdxForBones+1],R.matricesWeightsExtra[4*P+2]=T[r.vertexIdxForBones+2],R.matricesWeightsExtra[4*P+3]=T[r.vertexIdxForBones+3]))),i.captureUVS)r.uv.toArray(R.uvs,2*P);else{R.uvs.push(.5+r.position.x/E.x);let e=.5+r.position.y/E.y;R.uvs.push(sg.e.UseOpenGLOrientationForUV?1-e:e)}P++}}}0===R.indices.length&&(R.indices=null),0===R.positions.length&&(R.positions=null),0===R.normals.length&&(R.normals=null),0===R.uvs.length&&(R.uvs=null),(null===(r=R.matricesIndices)||void 0===r?void 0:r.length)===0&&(R.matricesIndices=null),(null===(s=R.matricesWeights)||void 0===s?void 0:s.length)===0&&(R.matricesWeights=null),(null===(n=R.matricesIndicesExtra)||void 0===n?void 0:n.length)===0&&(R.matricesIndicesExtra=null),(null===(a=R.matricesWeightsExtra)||void 0===a?void 0:a.length)===0&&(R.matricesWeightsExtra=null);let w=new rq.Kj(e,t.getScene());return R.applyToMesh(w),l?(w.skeleton=t.skeleton,w.parent=t):(w.position=x.clone(),w.rotation=new rr.P(A,b,C)),w.computeWorldMatrix(!0),w.refreshBoundingInfo(!0,!0),w})(e,t,{position:i,normal:r,size:s,angle:n}),rq.Kj._GoldbergMeshParser=(e,t)=>hk.Parse(e,t);class hk extends rq.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&&(ru.Y.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(ru.Y.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(ru.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 t=0;t<e.length;t++){let i=e[t][0],r=e[t][1],s=e[t][2];for(let e=i;e<r+1;e++)this.goldbergData.faceColors[e]=s}let t=[];for(let e=0;e<12;e++)for(let i=0;i<5;i++)t.push(this.goldbergData.faceColors[e].r,this.goldbergData.faceColors[e].g,this.goldbergData.faceColors[e].b,this.goldbergData.faceColors[e].a);for(let e=12;e<this.goldbergData.faceColors.length;e++)for(let i=0;i<6;i++)t.push(this.goldbergData.faceColors[e].r,this.goldbergData.faceColors[e].g,this.goldbergData.faceColors[e].b,this.goldbergData.faceColors[e].a);return t}setGoldbergFaceColors(e){let t=this._changeGoldbergFaceColors(e);this.setVerticesData(rQ.o.ColorKind,t)}updateGoldbergFaceColors(e){let t=this._changeGoldbergFaceColors(e);this.updateVerticesData(rQ.o.ColorKind,t)}_changeGoldbergFaceUVs(e){let t=this.getVerticesData(rQ.o.UVKind);for(let i=0;i<e.length;i++){let r,s;let n=e[i][0],a=e[i][1],o=e[i][2],l=e[i][3],h=e[i][4],u=[],c=[];for(let e=0;e<5;e++)r=o.x+l*Math.cos(h+e*Math.PI/2.5),s=o.y+l*Math.sin(h+e*Math.PI/2.5),r<0&&(r=0),r>1&&(r=1),u.push(r,s);for(let e=0;e<6;e++)r=o.x+l*Math.cos(h+e*Math.PI/3),s=o.y+l*Math.sin(h+e*Math.PI/3),r<0&&(r=0),r>1&&(r=1),c.push(r,s);for(let e=n;e<Math.min(12,a+1);e++)for(let i=0;i<5;i++)t[10*e+2*i]=u[2*i],t[10*e+2*i+1]=u[2*i+1];for(let e=Math.max(12,n);e<a+1;e++)for(let i=0;i<6;i++)t[12*e-24+2*i]=c[2*i],t[12*e-23+2*i]=c[2*i+1]}return t}setGoldbergFaceUVs(e){let t=this._changeGoldbergFaceUVs(e);this.setVerticesData(rQ.o.UVKind,t)}updateGoldbergFaceUVs(e){let t=this._changeGoldbergFaceUVs(e);this.updateVerticesData(rQ.o.UVKind,t)}placeOnGoldbergFaceAt(e,t,i){let r=rr.P.RotationFromAxis(this.goldbergData.faceXaxis[t],this.goldbergData.faceYaxis[t],this.goldbergData.faceZaxis[t]);e.rotation=r,e.position=this.goldbergData.faceCenters[t].add(this.goldbergData.faceXaxis[t].scale(i.x)).add(this.goldbergData.faceYaxis[t].scale(i.y)).add(this.goldbergData.faceZaxis[t].scale(i.z))}serialize(e){super.serialize(e),e.type="GoldbergMesh";let t={};if(t.adjacentFaces=this.goldbergData.adjacentFaces,t.nbSharedFaces=this.goldbergData.nbSharedFaces,t.nbUnsharedFaces=this.goldbergData.nbUnsharedFaces,t.nbFaces=this.goldbergData.nbFaces,t.nbFacesAtPole=this.goldbergData.nbFacesAtPole,this.goldbergData.faceColors)for(let e of(t.faceColors=[],this.goldbergData.faceColors))t.faceColors.push(e.asArray());if(this.goldbergData.faceCenters)for(let e of(t.faceCenters=[],this.goldbergData.faceCenters))t.faceCenters.push(e.asArray());if(this.goldbergData.faceZaxis)for(let e of(t.faceZaxis=[],this.goldbergData.faceZaxis))t.faceZaxis.push(e.asArray());if(this.goldbergData.faceYaxis)for(let e of(t.faceYaxis=[],this.goldbergData.faceYaxis))t.faceYaxis.push(e.asArray());if(this.goldbergData.faceXaxis)for(let e of(t.faceXaxis=[],this.goldbergData.faceXaxis))t.faceXaxis.push(e.asArray());e.goldbergData=t}static Parse(e,t){let i=e.goldbergData;i.faceColors=i.faceColors.map(e=>rs.HE.FromArray(e)),i.faceCenters=i.faceCenters.map(e=>rr.P.FromArray(e)),i.faceZaxis=i.faceZaxis.map(e=>rr.P.FromArray(e)),i.faceXaxis=i.faceXaxis.map(e=>rr.P.FromArray(e)),i.faceYaxis=i.faceYaxis.map(e=>rr.P.FromArray(e));let r=new hk(e.name,t);return r.goldbergData=i,r}}class hG{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new rU(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)}bezierCurveTo(e,t,i,r,s,n){this._currentPath.addBezierCurveTo(e,t,i,r,s,n,this._resolution)}extractHoles(){for(let e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){let e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}class hz{static CreateBoneWeightShader(e,t){var i,r,s,n,a,o;let l=e.skeleton,h=null!==(i=e.colorBase)&&void 0!==i?i:rs.Wo.Black(),u=null!==(r=e.colorZero)&&void 0!==r?r:rs.Wo.Blue(),c=null!==(s=e.colorQuarter)&&void 0!==s?s:rs.Wo.Green(),d=null!==(n=e.colorHalf)&&void 0!==n?n:rs.Wo.Yellow(),p=null!==(a=e.colorFull)&&void 0!==a?a:rs.Wo.Red(),_=null!==(o=e.targetBoneIndex)&&void 0!==o?o:0;sj.Q.ShadersStore["boneWeights:"+l.name+"VertexShader"]=`precision highp float; - - attribute vec3 position; - attribute vec2 uv; - - uniform mat4 view; - uniform mat4 projection; - uniform mat4 worldViewProjection; - - #include<bonesDeclaration> - #if NUM_BONE_INFLUENCERS == 0 - attribute vec4 matricesIndices; - attribute vec4 matricesWeights; - #endif - #include<bakedVertexAnimationDeclaration> - - #include<instancesDeclaration> - - varying vec3 vColor; - - uniform vec3 colorBase; - uniform vec3 colorZero; - uniform vec3 colorQuarter; - uniform vec3 colorHalf; - uniform vec3 colorFull; - - uniform float targetBoneIndex; - - void main() { - vec3 positionUpdated = position; - - #include<instancesVertex> - #include<bonesVertex> - #include<bakedVertexAnimation> - - vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); - - vec3 color = colorBase; - float totalWeight = 0.; - if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){ - totalWeight += matricesWeights[0]; - } - if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){ - totalWeight += matricesWeights[1]; - } - if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){ - totalWeight += matricesWeights[2]; - } - if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){ - totalWeight += matricesWeights[3]; - } - - color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight)); - color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight)); - color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight)); - color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight)); - vColor = color; - - gl_Position = projection * view * worldPos; - }`,sj.Q.ShadersStore["boneWeights:"+l.name+"FragmentShader"]=` - precision highp float; - varying vec3 vPosition; - - varying vec3 vColor; - - void main() { - vec4 color = vec4(vColor, 1.0); - gl_FragColor = color; - } - `;let f=new hf("boneWeight:"+l.name,t,{vertex:"boneWeights:"+l.name,fragment:"boneWeights:"+l.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return f.setColor3("colorBase",h),f.setColor3("colorZero",u),f.setColor3("colorQuarter",c),f.setColor3("colorHalf",d),f.setColor3("colorFull",p),f.setFloat("targetBoneIndex",_),f.getClassName=()=>"BoneWeightShader",f.transparencyMode=sX.F.MATERIAL_OPAQUE,f}static CreateSkeletonMapShader(e,t){var i;let r=e.skeleton,s=null!==(i=e.colorMap)&&void 0!==i?i:[{color:new rs.Wo(1,.38,.18),location:0},{color:new rs.Wo(.59,.18,1),location:.2},{color:new rs.Wo(.59,1,.18),location:.4},{color:new rs.Wo(1,.87,.17),location:.6},{color:new rs.Wo(1,.17,.42),location:.8},{color:new rs.Wo(.17,.68,1),location:1}],n=r.bones.length+1,a=hz._CreateBoneMapColorBuffer(n,s,t),o=new hf("boneWeights:"+r.name,t,{vertexSource:`precision highp float; - - attribute vec3 position; - attribute vec2 uv; - - uniform mat4 view; - uniform mat4 projection; - uniform mat4 worldViewProjection; - uniform float colorMap[`+4*r.bones.length+`]; - - #include<bonesDeclaration> - #if NUM_BONE_INFLUENCERS == 0 - attribute vec4 matricesIndices; - attribute vec4 matricesWeights; - #endif - #include<bakedVertexAnimationDeclaration> - #include<instancesDeclaration> - - varying vec3 vColor; - - void main() { - vec3 positionUpdated = position; - - #include<instancesVertex> - #include<bonesVertex> - #include<bakedVertexAnimation> - - vec3 color = vec3(0.); - bool first = true; - - for (int i = 0; i < 4; i++) { - int boneIdx = int(matricesIndices[i]); - float boneWgt = matricesWeights[i]; - - vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]); - - if (boneWgt > 0.) { - if (first) { - first = false; - color = c; - } else { - color = mix(color, c, boneWgt); - } - } - } - - vColor = color; - - vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); - - gl_Position = projection * view * worldPos; - }`,fragmentSource:` - precision highp float; - varying vec3 vColor; - - void main() { - vec4 color = vec4( vColor, 1.0 ); - gl_FragColor = color; - } - `},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",a),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=sX.F.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){let r=new lb("temp",{width:e,height:1},i,!1),s=r.getContext(),n=s.createLinearGradient(0,0,e,0);t.forEach(e=>{n.addColorStop(e.location,e.color.toHexString())}),s.fillStyle=n,s.fillRect(0,0,e,1),r.update();let a=[],o=s.getImageData(0,0,e,1).data,l=1/255;for(let e=0;e<o.length;e++)a.push(o[e]*l);return r.dispose(),a}get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get isReady(){return this._ready}set ready(e){this._ready=e}get debugMesh(){return this._debugMesh}set debugMesh(e){this._debugMesh=e}get displayMode(){return this.options.displayMode||hz.DISPLAY_LINES}set displayMode(e){e>hz.DISPLAY_SPHERE_AND_SPURS&&(e=hz.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,s=3,n={}){var a,o,l,h,u,c,d,p,_,f,m,g,v,T;this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=s,this.options=n,this.color=rs.Wo.White(),this._debugLines=[],this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=null===(a=n.pauseAnimations)||void 0===a||a,n.returnToRest=null!==(o=n.returnToRest)&&void 0!==o&&o,n.displayMode=null!==(l=n.displayMode)&&void 0!==l?l:hz.DISPLAY_LINES,n.displayOptions=null!==(h=n.displayOptions)&&void 0!==h?h:{},n.displayOptions.midStep=null!==(u=n.displayOptions.midStep)&&void 0!==u?u:.235,n.displayOptions.midStepFactor=null!==(c=n.displayOptions.midStepFactor)&&void 0!==c?c:.155,n.displayOptions.sphereBaseSize=null!==(d=n.displayOptions.sphereBaseSize)&&void 0!==d?d:.15,n.displayOptions.sphereScaleUnit=null!==(p=n.displayOptions.sphereScaleUnit)&&void 0!==p?p:2,n.displayOptions.sphereFactor=null!==(_=n.displayOptions.sphereFactor)&&void 0!==_?_:.865,n.displayOptions.spurFollowsChild=null!==(f=n.displayOptions.spurFollowsChild)&&void 0!==f&&f,n.displayOptions.showLocalAxes=null!==(m=n.displayOptions.showLocalAxes)&&void 0!==m&&m,n.displayOptions.localAxesSize=null!==(g=n.displayOptions.localAxesSize)&&void 0!==g?g:.075,n.computeBonesUsingShaders=null===(v=n.computeBonesUsingShaders)||void 0===v||v,n.useAllBones=null===(T=n.useAllBones)||void 0===T||T;let x=t.getVerticesData(rQ.o.MatricesIndicesKind),S=t.getVerticesData(rQ.o.MatricesWeightsKind);if(this._boneIndices=new Set,!n.useAllBones&&x&&S)for(let e=0;e<x.length;++e){let t=x[e],i=S[e];0!==i&&this._boneIndices.add(t)}this._utilityLayer=new he(this._scene,!1),this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!0;let E=this.options.displayMode||0;E>hz.DISPLAY_SPHERE_AND_SPURS&&(E=hz.DISPLAY_LINES),this.displayMode=E,this.update(),this._bindObs()}_bindObs(){this.displayMode===hz.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()}))}update(){switch(this.displayMode){case hz.DISPLAY_LINES:this._displayLinesUpdate();break;case hz.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case hz.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,s=0,n=0){let a=rr.jp.Matrix[0],o=t.getParent();if(a.copyFrom(t.getLocalMatrix()),0!==r||0!==s||0!==n){let e=rr.jp.Matrix[1];rr.y3.IdentityToRef(e),e.setTranslationFromFloats(r,s,n),e.multiplyToRef(a,a)}o&&a.multiplyToRef(o.getAbsoluteMatrix(),a),a.multiplyToRef(i,a),e.x=a.m[12],e.y=a.m[13],e.z=a.m[14]}_getLinesForBonesWithLength(e,t){let i=e.length,r=this.mesh,s=r.position,n=0;for(let r=0;r<i;r++){let i=e[r],a=this._debugLines[n];-1!==i._index&&(this._boneIndices.has(i.getIndex())||this.options.useAllBones)&&(a||(a=[rr.P.Zero(),rr.P.Zero()],this._debugLines[n]=a),this._getBonePosition(a[0],i,t),this._getBonePosition(a[1],i,t,0,i.length,0),a[0].subtractInPlace(s),a[1].subtractInPlace(s),n++)}}_getLinesForBonesNoLength(e){let t=e.length,i=0,r=this.mesh,s=r.position;for(let n=t-1;n>=0;n--){let t=e[n],a=t.getParent();if(!a||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let o=this._debugLines[i];o||(o=[rr.P.Zero(),rr.P.Zero()],this._debugLines[i]=o),t.getAbsolutePositionToRef(r,o[0]),a.getAbsolutePositionToRef(r,o[1]),o[0].subtractInPlace(s),o[1].subtractInPlace(s),i++}}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){if(null===e||-1===e._index){t.copyFrom(rr.y3.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;let r=null===(t=this.utilityLayer)||void 0===t?void 0:t.utilityLayerScene,s=this.skeleton.bones,n=[],a=[],o=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,r.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let t=Number.NEGATIVE_INFINITY,l=this.options.displayOptions||{};for(let i=0;i<s.length;i++){let o=s[i];if(-1===o._index||!this._boneIndices.has(o.getIndex())&&!this.options.useAllBones)continue;let h=new rr.y3;this._getAbsoluteBindPoseToRef(o,h);let u=new rr.P;h.decompose(void 0,void 0,u),o.children.forEach(i=>{let s=new rr.y3;i.getLocalMatrix().multiplyToRef(h,s);let n=new rr.P;s.decompose(void 0,void 0,n);let c=rr.P.Distance(u,n);if(c>t&&(t=c),e)return;let d=n.clone().subtract(u.clone()),p=d.length(),_=d.normalize().scale(p),f=l.midStep||.165,m=l.midStepFactor||.215,g=_.scale(f),v=hM("skeletonViewer",{shape:[new rr.P(1,-1,0),new rr.P(1,1,0),new rr.P(-1,1,0),new rr.P(-1,-1,0),new rr.P(1,-1,0)],path:[rr.P.Zero(),g,_],scaleFunction:e=>{switch(e){case 0:case 2:break;case 1:return p*m}return 0},sideOrientation:rq.Kj.DEFAULTSIDE,updatable:!1},r),T=v.getTotalVertices(),x=[],S=[];for(let e=0;e<T;e++)x.push(1,0,0,0),l.spurFollowsChild&&e>9?S.push(i.getIndex(),0,0,0):S.push(o.getIndex(),0,0,0);v.position=u.clone(),v.setVerticesData(rQ.o.MatricesWeightsKind,x,!1),v.setVerticesData(rQ.o.MatricesIndicesKind,S,!1),v.convertToFlatShadedMesh(),a.push(v)});let c=l.sphereBaseSize||.2,d=ha("skeletonViewer",{segments:6,diameter:c,updatable:!0},r),p=d.getTotalVertices(),_=[],f=[];for(let e=0;e<p;e++)_.push(1,0,0,0),f.push(o.getIndex(),0,0,0);d.setVerticesData(rQ.o.MatricesWeightsKind,_,!1),d.setVerticesData(rQ.o.MatricesIndicesKind,f,!1),d.position=u.clone(),n.push([d,o])}let h=l.sphereScaleUnit||2,u=l.sphereFactor||.85,c=[];for(let e=0;e<n.length;e++){let[i,r]=n[e],s=1/(h/t),a=0,o=r;for(;o.getParent()&&-1!==o.getParent().getIndex();)a++,o=o.getParent();i.scaling.scaleInPlace(s*Math.pow(u,a)),c.push(i)}this.debugMesh=rq.Kj.MergeMeshes(c.concat(a),!0,!0),this.debugMesh&&(this.debugMesh.renderingGroupId=this.renderingGroupId,this.debugMesh.skeleton=this.skeleton,this.debugMesh.parent=this.mesh,this.debugMesh.computeBonesUsingShaders=null===(i=this.options.computeBonesUsingShaders)||void 0===i||i,this.debugMesh.alwaysSelectAsActiveMesh=!0);let d=this.utilityLayer._getSharedGizmoLight();d.intensity=.7,this._revert(o),this.ready=!0}catch(e){console.error(e),this._revert(o),this.dispose()}}_buildLocalAxes(){var e;this._localAxes&&this._localAxes.dispose(),this._localAxes=null;let t=this.options.displayOptions||{};if(!t.showLocalAxes)return;let i=this._utilityLayer.utilityLayerScene,r=t.localAxesSize||.075,s=[],n=[],a=new rs.HE(1,0,0,1),o=new rs.HE(0,1,0,1),l=new rs.HE(0,0,1,1),h=[],u=[];for(let e in this.skeleton.bones){let t=this.skeleton.bones[e];if(-1===t._index||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let i=new rr.y3,c=new rr.P;this._getAbsoluteBindPoseToRef(t,i),i.decompose(void 0,rr.jp.Quaternion[0],c);let d=new rr.y3;rr.jp.Quaternion[0].toRotationMatrix(d);let p=rr.P.TransformCoordinates(new rr.P(0+r,0,0),d),_=rr.P.TransformCoordinates(new rr.P(0,0+r,0),d),f=rr.P.TransformCoordinates(new rr.P(0,0,0+r),d),m=[c,c.add(p)],g=[c,c.add(_)],v=[c,c.add(f)],T=[m,g,v],x=[[a,a],[o,o],[l,l]];s.push(...T),n.push(...x);for(let e=0;e<6;e++)h.push(1,0,0,0),u.push(t.getIndex(),0,0,0)}this._localAxes=hE("localAxes",{lines:s,colors:n,updatable:!0},i),this._localAxes.setVerticesData(rQ.o.MatricesWeightsKind,h,!1),this._localAxes.setVerticesData(rQ.o.MatricesIndicesKind,u,!1),this._localAxes.skeleton=this.skeleton,this._localAxes.renderingGroupId=this.renderingGroupId+1,this._localAxes.parent=this.mesh,this._localAxes.computeBonesUsingShaders=null===(e=this.options.computeBonesUsingShaders)||void 0===e||e}_displayLinesUpdate(){if(!this._utilityLayer)return;this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices(),void 0===this.skeleton.bones[0].length?this._getLinesForBonesNoLength(this.skeleton.bones):this._getLinesForBonesWithLength(this.skeleton.bones,this.mesh.getWorldMatrix());let e=this._utilityLayer.utilityLayerScene;e&&(this._debugMesh?hE("",{lines:this._debugLines,updatable:!0,instance:this._debugMesh},e):(this._debugMesh=hE("",{lines:this._debugLines,updatable:!0,instance:null},e),this._debugMesh.renderingGroupId=this.renderingGroupId),this._debugMesh.position.copyFrom(this.mesh.position),this._debugMesh.color=this.color)}changeDisplayMode(e){let t=!!this.isEnabled;this.displayMode!==e&&(this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this.displayMode=e,this.update(),this._bindObs(),this.isEnabled=t)}changeDisplayOptions(e,t){let i=!!this.isEnabled;this.options.displayOptions[e]=t,this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this.update(),this._bindObs(),this.isEnabled=i}dispose(){this.isEnabled=!1,this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null),this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null),this.ready=!1}}hz.DISPLAY_LINES=0,hz.DISPLAY_SPHERES=1,hz.DISPLAY_SPHERE_AND_SPURS=2,i(485),i(6692),i(4949);class hW{}hW.ALPHA_DISABLE=0,hW.ALPHA_ADD=1,hW.ALPHA_COMBINE=2,hW.ALPHA_SUBTRACT=3,hW.ALPHA_MULTIPLY=4,hW.ALPHA_MAXIMIZED=5,hW.ALPHA_ONEONE=6,hW.ALPHA_PREMULTIPLIED=7,hW.ALPHA_PREMULTIPLIED_PORTERDUFF=8,hW.ALPHA_INTERPOLATE=9,hW.ALPHA_SCREENMODE=10,hW.ALPHA_ONEONE_ONEONE=11,hW.ALPHA_ALPHATOCOLOR=12,hW.ALPHA_REVERSEONEMINUS=13,hW.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,hW.ALPHA_ONEONE_ONEZERO=15,hW.ALPHA_EXCLUSION=16,hW.ALPHA_LAYER_ACCUMULATE=17,hW.ALPHA_EQUATION_ADD=0,hW.ALPHA_EQUATION_SUBSTRACT=1,hW.ALPHA_EQUATION_REVERSE_SUBTRACT=2,hW.ALPHA_EQUATION_MAX=3,hW.ALPHA_EQUATION_MIN=4,hW.ALPHA_EQUATION_DARKEN=5,hW.DELAYLOADSTATE_NONE=0,hW.DELAYLOADSTATE_LOADED=1,hW.DELAYLOADSTATE_LOADING=2,hW.DELAYLOADSTATE_NOTLOADED=4,hW.NEVER=512,hW.ALWAYS=519,hW.LESS=513,hW.EQUAL=514,hW.LEQUAL=515,hW.GREATER=516,hW.GEQUAL=518,hW.NOTEQUAL=517,hW.KEEP=7680,hW.ZERO=0,hW.REPLACE=7681,hW.INCR=7682,hW.DECR=7683,hW.INVERT=5386,hW.INCR_WRAP=34055,hW.DECR_WRAP=34056,hW.TEXTURE_CLAMP_ADDRESSMODE=0,hW.TEXTURE_WRAP_ADDRESSMODE=1,hW.TEXTURE_MIRROR_ADDRESSMODE=2,hW.TEXTURE_CREATIONFLAG_STORAGE=1,hW.TEXTUREFORMAT_ALPHA=0,hW.TEXTUREFORMAT_LUMINANCE=1,hW.TEXTUREFORMAT_LUMINANCE_ALPHA=2,hW.TEXTUREFORMAT_RGB=4,hW.TEXTUREFORMAT_RGBA=5,hW.TEXTUREFORMAT_RED=6,hW.TEXTUREFORMAT_R=6,hW.TEXTUREFORMAT_RG=7,hW.TEXTUREFORMAT_RED_INTEGER=8,hW.TEXTUREFORMAT_R_INTEGER=8,hW.TEXTUREFORMAT_RG_INTEGER=9,hW.TEXTUREFORMAT_RGB_INTEGER=10,hW.TEXTUREFORMAT_RGBA_INTEGER=11,hW.TEXTUREFORMAT_BGRA=12,hW.TEXTUREFORMAT_DEPTH24_STENCIL8=13,hW.TEXTUREFORMAT_DEPTH32_FLOAT=14,hW.TEXTUREFORMAT_DEPTH16=15,hW.TEXTUREFORMAT_DEPTH24=16,hW.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,hW.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,hW.TEXTUREFORMAT_STENCIL8=19,hW.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,hW.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,hW.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,hW.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,hW.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,hW.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,hW.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,hW.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,hW.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,hW.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,hW.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,hW.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,hW.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,hW.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,hW.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,hW.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,hW.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,hW.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,hW.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,hW.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,hW.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,hW.TEXTURETYPE_UNSIGNED_BYTE=0,hW.TEXTURETYPE_UNSIGNED_INT=0,hW.TEXTURETYPE_FLOAT=1,hW.TEXTURETYPE_HALF_FLOAT=2,hW.TEXTURETYPE_BYTE=3,hW.TEXTURETYPE_SHORT=4,hW.TEXTURETYPE_UNSIGNED_SHORT=5,hW.TEXTURETYPE_INT=6,hW.TEXTURETYPE_UNSIGNED_INTEGER=7,hW.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,hW.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,hW.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,hW.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,hW.TEXTURETYPE_UNSIGNED_INT_24_8=12,hW.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,hW.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,hW.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,hW.TEXTURETYPE_UNDEFINED=16,hW.TEXTURE_2D=3553,hW.TEXTURE_2D_ARRAY=35866,hW.TEXTURE_CUBE_MAP=34067,hW.TEXTURE_CUBE_MAP_ARRAY=3735928559,hW.TEXTURE_3D=32879,hW.TEXTURE_NEAREST_SAMPLINGMODE=1,hW.TEXTURE_NEAREST_NEAREST=1,hW.TEXTURE_BILINEAR_SAMPLINGMODE=2,hW.TEXTURE_LINEAR_LINEAR=2,hW.TEXTURE_TRILINEAR_SAMPLINGMODE=3,hW.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,hW.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,hW.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,hW.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,hW.TEXTURE_NEAREST_LINEAR=7,hW.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,hW.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,hW.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,hW.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,hW.TEXTURE_LINEAR_NEAREST=12,hW.TEXTURE_EXPLICIT_MODE=0,hW.TEXTURE_SPHERICAL_MODE=1,hW.TEXTURE_PLANAR_MODE=2,hW.TEXTURE_CUBIC_MODE=3,hW.TEXTURE_PROJECTION_MODE=4,hW.TEXTURE_SKYBOX_MODE=5,hW.TEXTURE_INVCUBIC_MODE=6,hW.TEXTURE_EQUIRECTANGULAR_MODE=7,hW.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,hW.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,hW.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,hW.TEXTURE_FILTERING_QUALITY_HIGH=64,hW.TEXTURE_FILTERING_QUALITY_MEDIUM=16,hW.TEXTURE_FILTERING_QUALITY_LOW=8,hW.SCALEMODE_FLOOR=1,hW.SCALEMODE_NEAREST=2,hW.SCALEMODE_CEILING=3,hW.MATERIAL_TextureDirtyFlag=1,hW.MATERIAL_LightDirtyFlag=2,hW.MATERIAL_FresnelDirtyFlag=4,hW.MATERIAL_AttributesDirtyFlag=8,hW.MATERIAL_MiscDirtyFlag=16,hW.MATERIAL_PrePassDirtyFlag=32,hW.MATERIAL_AllDirtyFlag=63,hW.MATERIAL_TriangleFillMode=0,hW.MATERIAL_WireFrameFillMode=1,hW.MATERIAL_PointFillMode=2,hW.MATERIAL_PointListDrawMode=3,hW.MATERIAL_LineListDrawMode=4,hW.MATERIAL_LineLoopDrawMode=5,hW.MATERIAL_LineStripDrawMode=6,hW.MATERIAL_TriangleStripDrawMode=7,hW.MATERIAL_TriangleFanDrawMode=8,hW.MATERIAL_ClockWiseSideOrientation=0,hW.MATERIAL_CounterClockWiseSideOrientation=1,hW.ACTION_NothingTrigger=0,hW.ACTION_OnPickTrigger=1,hW.ACTION_OnLeftPickTrigger=2,hW.ACTION_OnRightPickTrigger=3,hW.ACTION_OnCenterPickTrigger=4,hW.ACTION_OnPickDownTrigger=5,hW.ACTION_OnDoublePickTrigger=6,hW.ACTION_OnPickUpTrigger=7,hW.ACTION_OnPickOutTrigger=16,hW.ACTION_OnLongPressTrigger=8,hW.ACTION_OnPointerOverTrigger=9,hW.ACTION_OnPointerOutTrigger=10,hW.ACTION_OnEveryFrameTrigger=11,hW.ACTION_OnIntersectionEnterTrigger=12,hW.ACTION_OnIntersectionExitTrigger=13,hW.ACTION_OnKeyDownTrigger=14,hW.ACTION_OnKeyUpTrigger=15,hW.PARTICLES_BILLBOARDMODE_Y=2,hW.PARTICLES_BILLBOARDMODE_ALL=7,hW.PARTICLES_BILLBOARDMODE_STRETCHED=8,hW.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,hW.MESHES_CULLINGSTRATEGY_STANDARD=0,hW.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,hW.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,hW.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,hW.SCENELOADER_NO_LOGGING=0,hW.SCENELOADER_MINIMAL_LOGGING=1,hW.SCENELOADER_SUMMARY_LOGGING=2,hW.SCENELOADER_DETAILED_LOGGING=3,hW.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,hW.PREPASS_POSITION_TEXTURE_TYPE=1,hW.PREPASS_VELOCITY_TEXTURE_TYPE=2,hW.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,hW.PREPASS_COLOR_TEXTURE_TYPE=4,hW.PREPASS_DEPTH_TEXTURE_TYPE=5,hW.PREPASS_NORMAL_TEXTURE_TYPE=6,hW.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,hW.BUFFER_CREATIONFLAG_READ=1,hW.BUFFER_CREATIONFLAG_WRITE=2,hW.BUFFER_CREATIONFLAG_READWRITE=3,hW.BUFFER_CREATIONFLAG_UNIFORM=4,hW.BUFFER_CREATIONFLAG_VERTEX=8,hW.BUFFER_CREATIONFLAG_INDEX=16,hW.BUFFER_CREATIONFLAG_STORAGE=32,hW.RENDERPASS_MAIN=0,hW.INPUT_ALT_KEY=18,hW.INPUT_CTRL_KEY=17,hW.INPUT_META_KEY1=91,hW.INPUT_META_KEY2=92,hW.INPUT_META_KEY3=93,hW.INPUT_SHIFT_KEY=16,hW.SNAPSHOTRENDERING_STANDARD=0,hW.SNAPSHOTRENDERING_FAST=1,hW.PERSPECTIVE_CAMERA=0,hW.ORTHOGRAPHIC_CAMERA=1,hW.FOVMODE_VERTICAL_FIXED=0,hW.FOVMODE_HORIZONTAL_FIXED=1,hW.RIG_MODE_NONE=0,hW.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,hW.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,hW.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,hW.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,hW.RIG_MODE_STEREOSCOPIC_INTERLACED=14,hW.RIG_MODE_VR=20,hW.RIG_MODE_WEBVR=21,hW.RIG_MODE_CUSTOM=22,hW.MAX_SUPPORTED_UV_SETS=6,hW.GL_ALPHA_EQUATION_ADD=32774,hW.GL_ALPHA_EQUATION_MIN=32775,hW.GL_ALPHA_EQUATION_MAX=32776,hW.GL_ALPHA_EQUATION_SUBTRACT=32778,hW.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,hW.GL_ALPHA_FUNCTION_SRC=768,hW.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,hW.GL_ALPHA_FUNCTION_SRC_ALPHA=770,hW.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,hW.GL_ALPHA_FUNCTION_DST_ALPHA=772,hW.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,hW.GL_ALPHA_FUNCTION_DST_COLOR=774,hW.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,hW.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,hW.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,hW.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,hW.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,hW.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,hW.SnippetUrl="https://snippet.babylonjs.com",i(4499),i(1851),sx.B.prototype._debugPushGroup=function(e,t){},sx.B.prototype._debugPopGroup=function(e){},sx.B.prototype._debugInsertMarker=function(e,t){},sx.B.prototype._debugFlushPendingCommands=function(){};class hH{constructor(){this._timeElapsedQueryEnded=!1}}var hX=i(6339);class hY{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=r$.x.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=r$.x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}r7.D.prototype.createQuery=function(){let e=this._gl.createQuery();if(!e)throw Error("Unable to create Occlusion Query");return e},r7.D.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},r7.D.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},r7.D.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},r7.D.prototype.beginOcclusionQuery=function(e,t){let i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},r7.D.prototype.endOcclusionQuery=function(e){let t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},r7.D.prototype._createTimeQuery=function(){let e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},r7.D.prototype._deleteTimeQuery=function(e){let t=this.getCaps().timerQuery;if(t.deleteQueryEXT){t.deleteQueryEXT(e);return}this.deleteQuery(e)},r7.D.prototype._getTimeQueryResult=function(e){let t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},r7.D.prototype._getTimeQueryAvailability=function(e){let t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},r7.D.prototype.startTimeQuery=function(){let e=this.getCaps(),t=e.timerQuery;if(!t)return null;let i=new hH;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery),this._currentNonTimestampToken=i}return i},r7.D.prototype.endTimeQuery=function(e){let t=this.getCaps(),i=t.timerQuery;if(!i||!e)return -1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return -1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return -1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}let r=this._gl.getParameter(i.GPU_DISJOINT_EXT),s=!1;if(e._endTimeQuery?s=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(s=this._getTimeQueryAvailability(e._timeElapsedQuery)),s&&!r){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return -1;let t=this._getTimeQueryResult(e._startTimeQuery),r=this._getTimeQueryResult(e._endTimeQuery);i=r-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return -1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return -1},r7.D.prototype._captureGPUFrameTime=!1,r7.D.prototype._gpuFrameTime=new hX.z,r7.D.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},r7.D.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add(()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(()=>{if(!this._gpuFrameTimeToken)return;let 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))},r7.D.prototype._getGlAlgorithmType=function(e){return e===r$.x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(r$.x.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(r$.x.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new hY),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(r$.x.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(r$.x.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(r$.x.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(r$.x.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(r$.x.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),r$.x.prototype._checkOcclusionQuery=function(){let e=this._occlusionDataStorage;if(e.occlusionType===r$.x.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;let t=this.getEngine();if(!t.getCaps().supportOcclusionQuery||!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery){let i=t.isQueryResultAvailable(this._occlusionQuery);if(i){let 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!==r$.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==r$.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}}let i=this.getScene();if(i.getBoundingBoxRenderer){let r=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded},r7.D.prototype.createTransformFeedback=function(){let e=this._gl.createTransformFeedback();if(!e)throw Error("Unable to create Transform Feedback");return e},r7.D.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},r7.D.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},r7.D.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},r7.D.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},r7.D.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},r7.D.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},sx.B.prototype.createExternalTexture=function(e){return null},sx.B.prototype.setExternalTexture=function(e,t){throw Error("setExternalTexture: This engine does not support external textures!")},sx.B.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;let r=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);let t=e._workingCanvas.getContext("2d");if(!t)throw Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},sx.B.prototype.restoreSingleAttachment=function(){let e=this._gl;this.bindAttachments([e.BACK])},sx.B.prototype.restoreSingleAttachmentForRenderTarget=function(){let e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},sx.B.prototype.buildTextureLayout=function(e){let t=this._gl,i=[];for(let r=0;r<e.length;r++)e[r]?i.push(t["COLOR_ATTACHMENT"+r]):i.push(t.NONE);return i},sx.B.prototype.bindAttachments=function(e){let t=this._gl;t.drawBuffers(e)},sx.B.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t=!1,i){this._currentRenderTarget=null;let r=this._gl,s=e._attachments,n=s.length;if(e._MSAAFramebuffer){r.bindFramebuffer(r.READ_FRAMEBUFFER,e._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,e._framebuffer);for(let t=0;t<n;t++){let i=e.textures[t];for(let e=0;e<n;e++)s[e]=r.NONE;s[t]=r[this.webGLVersion>1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],r.readBuffer(s[t]),r.drawBuffers(s),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(let e=0;e<n;e++)s[e]=r[this.webGLVersion>1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];r.drawBuffers(s)}for(let i=0;i<n;i++){let s=e.textures[i];(null==s?void 0:s.generateMipMaps)&&!t&&!s.isCube&&(this._bindTextureDirectly(r.TEXTURE_2D,s,!0),r.generateMipmap(r.TEXTURE_2D),this._bindTextureDirectly(r.TEXTURE_2D,null))}i&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),i()),this._bindUnboundFramebuffer(null)},sx.B.prototype.createMultipleRenderTarget=function(e,t,i=!0){var r;let s=!1,n=!0,a=!1,o=!1,l=15,h=1,u=[],c=[],d=[],p=[],_=[],f=[],m=[],g=[],v=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(s=void 0!==t.generateMipMaps&&t.generateMipMaps,n=void 0===t.generateDepthBuffer||t.generateDepthBuffer,a=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,o=void 0!==t.generateDepthTexture&&t.generateDepthTexture,h=t.textureCount||1,t.types&&(u=t.types),t.samplingModes&&(c=t.samplingModes),t.useSRGBBuffers&&(d=t.useSRGBBuffers),t.formats&&(p=t.formats),t.targetTypes&&(_=t.targetTypes),t.faceIndex&&(f=t.faceIndex),t.layerIndex&&(m=t.layerIndex),t.layerCounts&&(g=t.layerCounts),this.webGLVersion>1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(l=t.depthTextureFormat));let T=this._gl,x=T.createFramebuffer();this._bindUnboundFramebuffer(x);let S=e.width||e,E=e.height||e,C=[],b=[],y=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),A=this._setupFramebufferDepthAttachments(!y&&a,!o&&n,S,E);v._framebuffer=x,v._depthStencilBuffer=A,v._generateDepthBuffer=!o&&n,v._generateStencilBuffer=!y&&a,v._attachments=b;for(let e=0;e<h;e++){let t=c[e]||3,i=u[e]||0,n=d[e]||!1,a=p[e]||5,o=_[e]||3553,l=null!==(r=g[e])&&void 0!==r?r:1;(1!==i||this._caps.textureFloatLinearFiltering)&&(2!==i||this._caps.textureHalfFloatLinearFiltering)||(t=1);let h=this._getSamplingParameters(t,s);1!==i||this._caps.textureFloat||(i=0,ru.Y.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),n=n&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU);let f=this.webGLVersion>1,m=T[f?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(b.push(m),-1===o)continue;let v=new sT.l(this,sT.S.MultiRenderTarget);C[e]=v,T.activeTexture(T["TEXTURE"+e]),T.bindTexture(o,v._hardwareTexture.underlyingResource),T.texParameteri(o,T.TEXTURE_MAG_FILTER,h.mag),T.texParameteri(o,T.TEXTURE_MIN_FILTER,h.min),T.texParameteri(o,T.TEXTURE_WRAP_S,T.CLAMP_TO_EDGE),T.texParameteri(o,T.TEXTURE_WRAP_T,T.CLAMP_TO_EDGE);let x=this._getRGBABufferInternalSizedFormat(i,a,n),y=this._getInternalFormat(a),A=this._getWebGLTextureType(i);if(f&&(35866===o||32879===o))35866===o?v.is2DArray=!0:v.is3D=!0,v.baseDepth=v.depth=l,T.texImage3D(o,0,x,S,E,l,0,y,A,null);else if(34067===o){for(let e=0;e<6;e++)T.texImage2D(T.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,x,S,E,0,y,A,null);v.isCube=!0}else T.texImage2D(T.TEXTURE_2D,0,x,S,E,0,y,A,null);s&&T.generateMipmap(o),this._bindTextureDirectly(o,null),v.baseWidth=S,v.baseHeight=E,v.width=S,v.height=E,v.isReady=!0,v.samples=1,v.generateMipMaps=s,v.samplingMode=t,v.type=i,v._useSRGBBuffer=n,v.format=a,this._internalTexturesCache.push(v)}if(o&&this._caps.depthTextureExtension){let e=new sT.l(this,sT.S.Depth),t=5,i=T.DEPTH_COMPONENT16,r=T.DEPTH_COMPONENT,n=T.UNSIGNED_SHORT,a=T.DEPTH_ATTACHMENT;this.webGLVersion<2?i=T.DEPTH_COMPONENT:14===l?(t=1,n=T.FLOAT,i=T.DEPTH_COMPONENT32F):18===l?(t=0,n=T.FLOAT_32_UNSIGNED_INT_24_8_REV,i=T.DEPTH32F_STENCIL8,r=T.DEPTH_STENCIL,a=T.DEPTH_STENCIL_ATTACHMENT):16===l?(t=0,n=T.UNSIGNED_INT,i=T.DEPTH_COMPONENT24,a=T.DEPTH_ATTACHMENT):(13===l||17===l)&&(t=12,n=T.UNSIGNED_INT_24_8,i=T.DEPTH24_STENCIL8,r=T.DEPTH_STENCIL,a=T.DEPTH_STENCIL_ATTACHMENT),T.activeTexture(T.TEXTURE0),T.bindTexture(T.TEXTURE_2D,e._hardwareTexture.underlyingResource),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_MAG_FILTER,T.NEAREST),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_MIN_FILTER,T.NEAREST),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_WRAP_S,T.CLAMP_TO_EDGE),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_WRAP_T,T.CLAMP_TO_EDGE),T.texImage2D(T.TEXTURE_2D,0,i,S,E,0,r,n,null),T.framebufferTexture2D(T.FRAMEBUFFER,a,T.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=S,e.baseHeight=E,e.width=S,e.height=E,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 v.setTextures(C),i&&T.drawBuffers(b),this._bindUnboundFramebuffer(null),v.setLayerAndFaceIndices(m,f),this.resetTextureCache(),v},sx.B.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let r=e._attachments.length;if(0===r)return 1;let s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);let n=!!e._depthStencilBuffer;if(n&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof s.renderbufferStorageMultisample){let n=s.createFramebuffer();if(!n)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);let a=[];for(let t=0;t<r;t++){let i=e.textures[t],r=i._hardwareTexture;r.releaseMSAARenderBuffers()}for(let i=0;i<r;i++){let r=e.textures[i],n=r._hardwareTexture,o=s[this.webGLVersion>1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(r.width,r.height,t,-1,this._getRGBAMultiSampleBufferFormat(r.type,r.format),o);if(!l)throw Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),r.samples=t,a.push(o)}i&&s.drawBuffers(a)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},sx.B.prototype._createDepthStencilCubeTexture=function(e,t,i){let r=new sT.l(this,sT.S.DepthStencil);if(r.isCube=!0,1===this.webGLVersion)return ru.Y.Error("Depth cube texture is not supported by WebGL 1."),r;let s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),n=this._gl;this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),i._depthStencilTexture=r,i._depthStencilTextureWithStencil=s.generateStencil;for(let t=0;t<6;t++)s.generateStencil?n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH24_STENCIL8,e,e,0,n.DEPTH_STENCIL,n.UNSIGNED_INT_24_8,null):n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH_COMPONENT24,e,e,0,n.DEPTH_COMPONENT,n.UNSIGNED_INT,null);return this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(r),r},sx.B.prototype._partialLoadFile=function(e,t,i,r,s=null){this._loadFile(e,e=>{i[t]=e,i._internalCount++,6===i._internalCount&&r(i)},void 0,void 0,!0,(e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)})},sx.B.prototype._cascadeLoadFiles=function(e,t,i,r=null){let s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,r)},sx.B.prototype._cascadeLoadImgs=function(e,t,i,r,s=null,n){let a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(r[o],o,a,e,t,i,s,n)},sx.B.prototype._partialLoadImg=function(e,t,i,r,s,n,a=null,o){let l=(0,so.f)();(0,sl.r6)(e,e=>{i[t]=e,i._internalCount++,r&&r.removePendingData(l),6===i._internalCount&&n&&n(s,i)},(e,t)=>{r&&r.removePendingData(l),a&&a(e,t)},r?r.offlineProvider:null,o),r&&r.addPendingData(l)},sx.B.prototype._setCubeMapTextureParams=function(e,t,i){let r=this._gl;r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null)},sx.B.prototype.createCubeTextureBase=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d=null,p=null,_=!1){let f=c||new sT.l(this,sT.S.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!r,f._lodGenerationScale=h,f._lodGenerationOffset=u,f._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!r),f!==c&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=o,f._files=i);let m=e;this._transformTextureUrl&&!c&&(e=this._transformTextureUrl(e));let g=e.split("?")[0],v=g.lastIndexOf("."),T=o||(v>-1?g.substring(v).toLowerCase():""),x=null;for(let e of sx.B._TextureLoaders)if(e.canLoad(T)){x=e;break}if(x){let c=e=>{d&&d(f,e),x.loadCubeData(e,f,l,s,n)};i&&6===i.length?x.supportCascades?this._cascadeLoadFiles(t,e=>c(e.map(e=>new Uint8Array(e))),i,n):n?n("Textures type does not support cascades."):ru.Y.Warn("Texture loader does not support cascades."):this._loadFile(e,e=>c(new Uint8Array(e)),void 0,void 0,!0,(c,g)=>{e===m?n&&c&&n(c.status+" "+c.statusText,g):(ru.Y.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!r,s,n,a,o,l,h,u,f,d,p,_))})}else{if(!i)throw Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,f,(e,t)=>{p&&p(e,t)},i,n)}return this._internalTexturesCache.push(f),f},sx.B.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d,p=!1){let _=this._gl;return this.createCubeTextureBase(e,t,i,!!r,s,n,a,o,l,h,u,c,e=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),(e,t)=>{let i=this.needPOTTextures?sx.B.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=[_.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);let o=a?this._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA,l=a?this._getInternalFormat(a):_.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(l=o);for(let e=0;e<n.length;e++)if(t[e].width!==i||t[e].height!==i){if(this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext){ru.Y.Warn("Cannot create canvas to resize texture.");return}this._workingCanvas.width=i,this._workingCanvas.height=i,this._workingContext.drawImage(t[e],0,0,t[e].width,t[e].height,0,0,i,i),_.texImage2D(n[e],0,o,l,_.UNSIGNED_BYTE,this._workingCanvas)}else _.texImage2D(n[e],0,o,l,_.UNSIGNED_BYTE,t[e]);r||_.generateMipmap(_.TEXTURE_CUBE_MAP),this._setCubeMapTextureParams(e,!r),e.width=i,e.height=i,e.isReady=!0,a&&(e.format=a),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},!!p)},sx.B.prototype.setTextureSampler=function(e,t){throw Error("setTextureSampler: This engine does not support separate texture sampler objects!")},i(54);let hj=new ri.y$,hq=new ri.y$;Object.defineProperty(r7.D.prototype,"onBeforeViewRenderObservable",{get:function(){return hj}}),Object.defineProperty(r7.D.prototype,"onAfterViewRenderObservable",{get:function(){return hq}}),Object.defineProperty(r7.D.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){var t;this._inputElement!==e&&(this._inputElement=e,null===(t=this._onEngineViewChanged)||void 0===t||t.call(this))}}),r7.D.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},r7.D.prototype.registerView=function(e,t,i){for(let t of(this.views||(this.views=[]),this.views))if(t.target===e)return t;let r=this.getRenderingCanvas();r&&(e.width=r.width,e.height=r.height);let s={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(s),t&&t.onDisposeObservable.add(()=>{this.unRegisterView(e)}),s},r7.D.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(let t of this.views)if(t.target===e){let e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},r7.D.prototype._renderViewStep=function(e){let t=e.target,i=t.getContext("2d");if(!i)return!0;let r=this.getRenderingCanvas();hj.notifyObservers(e);let s=e.camera,n=null,a=null;if(s){if(!(a=s.getScene())||a.activeCameras&&a.activeCameras.length)return!0;this.activeView=e,n=a.activeCamera,a.activeCamera=s}if(e.customResize)e.customResize(t);else{let e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||r.width!==t.width||i!==t.height||r.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!!r.width&&!!r.height&&(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),n&&a&&(a.activeCamera=n),hq.notifyObservers(e),!0)},r7.D.prototype._renderViews=function(){let e;if(!this.views||0===this.views.length)return!1;let t=this.getRenderingCanvas();if(!t)return!1;for(let t of this.views){if(!t.enabled)continue;let i=t.target;if(i===this.inputElement){e=t;continue}if(!this._renderViewStep(t))return!1}return(!e||!!this._renderViewStep(e))&&(this.activeView=null,!0)};var hK=i(1300);function h$(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(t=>e&&(e===t||e.match(RegExp("\\b"+t+"\\b","g")))))return e;let t=e.lastIndexOf("."),i=e.lastIndexOf("?"),r=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+r}sx.B.prototype.createStorageBuffer=function(e,t){throw Error("createStorageBuffer: Unsupported method in this engine!")},sx.B.prototype.updateStorageBuffer=function(e,t,i,r){},sx.B.prototype.readFromStorageBuffer=function(e,t,i,r){throw Error("readFromStorageBuffer: Unsupported method in this engine!")},sx.B.prototype.setStorageBuffer=function(e,t){throw Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(r7.D.prototype,"texturesSupported",{get:function(){let e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(r7.D.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),r7.D.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},r7.D.prototype.setTextureFormatToUse=function(e){let t=this.texturesSupported;for(let i=0,r=t.length;i<r;i++)for(let r=0,s=e.length;r<s;r++)if(t[i]===e[r].toLowerCase())return this._transformTextureUrl=h$.bind(this),this._textureFormatInUse=t[i];return this._textureFormatInUse="",this._transformTextureUrl=null,null};class hQ{constructor(){let e=new ArrayBuffer(hQ.DEFAULT_BUFFER_SIZE);this._uint32s=new Uint32Array(e),this._int32s=new Int32Array(e),this._float32s=new Float32Array(e),this._length=hQ.DEFAULT_BUFFER_SIZE/4,this._position=0,this._nativeDataStream=new _native.NativeDataStream(()=>{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}}hQ.DEFAULT_BUFFER_SIZE=65536;let hZ=[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))],hJ=[()=>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],h0=(e,t)=>hZ[e]*hJ[e](t),h1=[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 h2{constructor(){this.preScaled=!1,this.l00=rr.P.Zero(),this.l1_1=rr.P.Zero(),this.l10=rr.P.Zero(),this.l11=rr.P.Zero(),this.l2_2=rr.P.Zero(),this.l2_1=rr.P.Zero(),this.l20=rr.P.Zero(),this.l21=rr.P.Zero(),this.l22=rr.P.Zero()}addLight(e,t,i){rr.jp.Vector3[0].set(t.r,t.g,t.b);let r=rr.jp.Vector3[0],s=rr.jp.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(h0(0,e),rr.jp.Vector3[2]),this.l00.addInPlace(rr.jp.Vector3[2]),s.scaleToRef(h0(1,e),rr.jp.Vector3[2]),this.l1_1.addInPlace(rr.jp.Vector3[2]),s.scaleToRef(h0(2,e),rr.jp.Vector3[2]),this.l10.addInPlace(rr.jp.Vector3[2]),s.scaleToRef(h0(3,e),rr.jp.Vector3[2]),this.l11.addInPlace(rr.jp.Vector3[2]),s.scaleToRef(h0(4,e),rr.jp.Vector3[2]),this.l2_2.addInPlace(rr.jp.Vector3[2]),s.scaleToRef(h0(5,e),rr.jp.Vector3[2]),this.l2_1.addInPlace(rr.jp.Vector3[2]),s.scaleToRef(h0(6,e),rr.jp.Vector3[2]),this.l20.addInPlace(rr.jp.Vector3[2]),s.scaleToRef(h0(7,e),rr.jp.Vector3[2]),this.l21.addInPlace(rr.jp.Vector3[2]),s.scaleToRef(h0(8,e),rr.jp.Vector3[2]),this.l22.addInPlace(rr.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(h1[0]),this.l1_1.scaleInPlace(h1[1]),this.l10.scaleInPlace(h1[2]),this.l11.scaleInPlace(h1[3]),this.l2_2.scaleInPlace(h1[4]),this.l2_1.scaleInPlace(h1[5]),this.l20.scaleInPlace(h1[6]),this.l21.scaleInPlace(h1[7]),this.l22.scaleInPlace(h1[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(hZ[0]),this.l1_1.scaleInPlace(hZ[1]),this.l10.scaleInPlace(hZ[2]),this.l11.scaleInPlace(hZ[3]),this.l2_2.scaleInPlace(hZ[4]),this.l2_1.scaleInPlace(hZ[5]),this.l20.scaleInPlace(hZ[6]),this.l21.scaleInPlace(hZ[7]),this.l22.scaleInPlace(hZ[8])}updateFromArray(e){return rr.P.FromArrayToRef(e[0],0,this.l00),rr.P.FromArrayToRef(e[1],0,this.l1_1),rr.P.FromArrayToRef(e[2],0,this.l10),rr.P.FromArrayToRef(e[3],0,this.l11),rr.P.FromArrayToRef(e[4],0,this.l2_2),rr.P.FromArrayToRef(e[5],0,this.l2_1),rr.P.FromArrayToRef(e[6],0,this.l20),rr.P.FromArrayToRef(e[7],0,this.l21),rr.P.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return rr.P.FromFloatsToRef(e[0],e[1],e[2],this.l00),rr.P.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),rr.P.FromFloatsToRef(e[6],e[7],e[8],this.l10),rr.P.FromFloatsToRef(e[9],e[10],e[11],this.l11),rr.P.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),rr.P.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),rr.P.FromFloatsToRef(e[18],e[19],e[20],this.l20),rr.P.FromFloatsToRef(e[21],e[22],e[23],this.l21),rr.P.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){let t=new h2;return t.updateFromArray(e)}static FromPolynomial(e){let t=new h2;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 h3{constructor(){this.x=rr.P.Zero(),this.y=rr.P.Zero(),this.z=rr.P.Zero(),this.xx=rr.P.Zero(),this.yy=rr.P.Zero(),this.zz=rr.P.Zero(),this.xy=rr.P.Zero(),this.yz=rr.P.Zero(),this.zx=rr.P.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=h2.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){rr.jp.Vector3[0].copyFromFloats(e.r,e.g,e.b);let t=rr.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),rr.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),rr.jp.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(rr.jp.Vector3[0]).addInPlace(rr.jp.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(rr.jp.Vector3[0]).subtractInPlace(rr.jp.Vector3[1]),this.zz.copyFrom(e.l00),rr.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(rr.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){let t=new h3;return t.updateFromHarmonics(e)}static FromArray(e){let t=new h3;return rr.P.FromArrayToRef(e[0],0,t.x),rr.P.FromArrayToRef(e[1],0,t.y),rr.P.FromArrayToRef(e[2],0,t.z),rr.P.FromArrayToRef(e[3],0,t.xx),rr.P.FromArrayToRef(e[4],0,t.yy),rr.P.FromArrayToRef(e[5],0,t.zz),rr.P.FromArrayToRef(e[6],0,t.yz),rr.P.FromArrayToRef(e[7],0,t.zx),rr.P.FromArrayToRef(e[8],0,t.xy),t}}let h4=`varying vec2 vUV;uniform sampler2D textureSampler; -#include<helperFunctions> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;function h5(e,t,i,r,s,n,a,o){let l=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,r=null!=r?r:t.type,n=null!=n?n:t.format,a=null!=a?a:t.width,o=null!=o?o:t.height,-1===r&&(r=0),new Promise(h=>{let u=new np("postprocess",e,null,null,1,null,s,l,!1,void 0,r,void 0,null,!1,n);u.externalTextureSamplerBinding=!0;let c=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:r,format:n});u.getEffect().executeWhenCompiled(()=>{u.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([u],c,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),u&&u.dispose(),c._swapAndDie(t),t.type=r,t.format=5,t.isReady=!0,h(t)})})}function h6(e){r||(r=new Float32Array(1),s=new Int32Array(r.buffer)),r[0]=e;let t=s[0],i=t>>16&32768,n=t>>12&2047,a=t>>23&255;return a<103?i:a>142?(i|=31744,i|=(255==a?0:1)&&8388607&t):a<113?(n|=2048,i|=(n>>114-a)+(n>>113-a&1)):(i|=a-112<<10|n>>1,i+=1&n)}function h8(e){let t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*6103515625e-14*(r/1024):31==i?r?NaN:(t?-1:1)*(1/0):(t?-1:1)*Math.pow(2,i-15)*(1+r/1024)}no.v.ShadersStore.rgbdDecodePixelShader=h4;class h7{static ExpandRGBDTexture(e){let t=e._texture;if(!t||!e.isRGBD)return;let i=t.getEngine(),r=i.getCaps(),s=t.isReady,n=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(n=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);let a=()=>{if(n){let r=new np("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);r.externalTextureSamplerBinding=!0;let s=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});r.getEffect().executeWhenCompiled(()=>{r.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([r],s,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),r&&r.dispose(),s._swapAndDie(t),t.isReady=!0})}};s?a():e.onLoadObservable.addOnce(a)}static EncodeTextureToRGBD(e,t,i=0){return h5("rgbdEncode",e,t,i,1,5)}}class h9{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}}class ue{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;let i,r;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();let s=e.getSize().width,n=e.readPixels(0,void 0,void 0,!1),a=e.readPixels(1,void 0,void 0,!1);e.isRenderTarget?(i=e.readPixels(3,void 0,void 0,!1),r=e.readPixels(2,void 0,void 0,!1)):(i=e.readPixels(2,void 0,void 0,!1),r=e.readPixels(3,void 0,void 0,!1));let o=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,u=0;return(1==e.textureType||2==e.textureType)&&(u=1),new Promise(e=>{Promise.all([a,n,i,r,o,l]).then(([t,i,r,n,a,o])=>{let l={size:s,right:i,left:t,up:r,down:n,front:a,back:o,format:5,type:u,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){let t=new h2,i=0,r=2/e.size,s=.5*r,n=s-1;for(let a=0;a<6;a++){let o=this._FileFaces[a],l=e[o.name],h=n,u=5===e.format?4:3;for(let a=0;a<e.size;a++){let c=n;for(let n=0;n<e.size;n++){let d=o.worldAxisForFileX.scale(c).add(o.worldAxisForFileY.scale(h)).add(o.worldAxisForNormal);d.normalize();let p=this._AreaElement(c-s,h-s)-this._AreaElement(c-s,h+s)-this._AreaElement(c+s,h-s)+this._AreaElement(c+s,h+s),_=l[a*e.size*u+n*u+0],f=l[a*e.size*u+n*u+1],m=l[a*e.size*u+n*u+2];isNaN(_)&&(_=0),isNaN(f)&&(f=0),isNaN(m)&&(m=0),0===e.type&&(_/=255,f/=255,m/=255),e.gammaSpace&&(_=Math.pow(rm.R.Clamp(_),rL.Nn),f=Math.pow(rm.R.Clamp(f),rL.Nn),m=Math.pow(rm.R.Clamp(m),rL.Nn));let g=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){let e=Math.max(_,f,m);if(e>g){let t=g/e;_*=t,f*=t,m*=t}}else _=rm.R.Clamp(_,0,g),f=rm.R.Clamp(f,0,g),m=rm.R.Clamp(m,0,g);let v=new rs.Wo(_,f,m);t.addLight(d,v,p),i+=p,c+=r}h+=r}}let a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),h3.FromHarmonics(t)}}ue._FileFaces=[new h9("right",new rr.P(1,0,0),new rr.P(0,0,-1),new rr.P(0,-1,0)),new h9("left",new rr.P(-1,0,0),new rr.P(0,0,1),new rr.P(0,-1,0)),new h9("up",new rr.P(0,1,0),new rr.P(1,0,0),new rr.P(0,0,1)),new h9("down",new rr.P(0,-1,0),new rr.P(1,0,0),new rr.P(0,0,-1)),new h9("front",new rr.P(0,0,1),new rr.P(1,0,0),new rr.P(0,-1,0)),new h9("back",new rr.P(0,0,-1),new rr.P(-1,0,0),new rr.P(0,-1,0))],ue.MAX_HDRI_VALUE=4096,ue.PRESERVE_CLAMPED_COLORS=!1,su.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(su.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;this._texture.isReady&&!this._texture._sphericalPolynomialPromise&&(this._texture._sphericalPolynomialPromise=ue.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});let ut=`varying vec2 vUV;uniform sampler2D textureSampler; -#include<helperFunctions> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;no.v.ShadersStore.rgbdEncodePixelShader=ut;let ui="image/png",ur=[134,22,135,150,246,214,150,54];function us(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=0;for(let e=0;e<ur.length;e++)if(t.getUint8(i++)!==ur[e])return ru.Y.Error("Not a babylon environment map"),null;let r="",s=0;for(;s=t.getUint8(i++);)r+=String.fromCharCode(s);let n=JSON.parse(r);return(n=un(n)).specular&&(n.specular.specularDataPosition=i,n.specular.lodGenerationScale=n.specular.lodGenerationScale||.8),n}function un(e){if(e.version>2)throw Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "2".`);return 2===e.version?e:e=Object.assign(Object.assign({},e),{version:2,imageType:ui})}function ua(e,t){t=un(t);let i=t.specular,r=rm.R.Log2(t.width);if(r=Math.round(r)+1,i.mipmaps.length!==6*r)throw Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);let s=Array(r);for(let t=0;t<r;t++){s[t]=Array(6);for(let r=0;r<6;r++){let n=i.mipmaps[6*t+r];s[t][r]=new Uint8Array(e.buffer,e.byteOffset+i.specularDataPosition+n.position,n.length)}}return s}function uo(e,t,i,r,s,n,a,o,l,h,u){return new Promise((c,d)=>{if(i){let i=t.createTexture(null,!0,!0,null,1,null,e=>{d(e)},e);r.getEffect().executeWhenCompiled(()=>{r.externalTextureSamplerBinding=!0,r.onApply=r=>{r._bindTexture("textureSampler",i),r.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([r],h,!0,n,a),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),c())})}else{if(t._uploadImageToTexture(u,e,n,a),o){let i=l[a];i&&t._uploadImageToTexture(i._texture,e,n,0)}c()}})}function ul(e,t){t=un(t);let i=t.irradiance;if(!i)return;let r=new h3;rr.P.FromArrayToRef(i.x,0,r.x),rr.P.FromArrayToRef(i.y,0,r.y),rr.P.FromArrayToRef(i.z,0,r.z),rr.P.FromArrayToRef(i.xx,0,r.xx),rr.P.FromArrayToRef(i.yy,0,r.yy),rr.P.FromArrayToRef(i.zz,0,r.zz),rr.P.FromArrayToRef(i.yz,0,r.yz),rr.P.FromArrayToRef(i.zx,0,r.zx),rr.P.FromArrayToRef(i.xy,0,r.xy),e._sphericalPolynomial=r}function uh(e,t,i,r){let s=r,n=0,a="";for(;s<i.length;){let r=i.charAt(s);if(a)r===a?'"'===a||"'"===a?"\\"!==i.charAt(s-1)&&(a=""):a="":"*/"===a&&"*"===r&&s+1<i.length&&("/"===i.charAt(s+1)&&(a=""),""===a&&s++);else switch(r){case e:n++;break;case t:n--;break;case'"':case"'":case"`":a=r;break;case"/":if(s+1<i.length){let e=i.charAt(s+1);"/"===e?a="\n":"*"===e&&(a="*/")}}if(s++,0===n)break}return 0===n?s-1:-1}function uu(e,t){for(;t<e.length;){let i=e[t];if(" "!==i&&"\n"!==i&&"\r"!==i&&" "!==i&&"\n"!==i&&"\xa0"!==i)break;t++}return t}function uc(e){let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function ud(e){let t=0,i="",r=!1,s=[];for(;t<e.length;){let n=e.charAt(t);if(i)n===i?'"'===i||"'"===i?("\\"!==e.charAt(t-1)&&(i=""),s.push(n)):(i="",r=!1):"*/"===i&&"*"===n&&t+1<e.length?("/"===e.charAt(t+1)&&(i=""),""===i&&(r=!1,t++)):r||s.push(n);else{switch(n){case'"':case"'":case"`":i=n;break;case"/":if(t+1<e.length){let s=e.charAt(t+1);"/"===s?(i="\n",r=!0):"*"===s&&(i="*/",r=!0)}}r||s.push(n)}t++}return s.join("")}class up{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<this._sourceCode.length;){let t=this._sourceCode.indexOf(this.inlineToken,e);if(t<0)break;let i=this._sourceCode.indexOf("(",t+this.inlineToken.length);if(i<0){this.debug&&console.warn(`Could not find the opening parenthesis after the token. startIndex=${e}`),e=t+this.inlineToken.length;continue}let r=up._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(t+this.inlineToken.length,i));if(!r){this.debug&&console.warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(t+this.inlineToken.length,i)}`),e=t+this.inlineToken.length;continue}let[s,n]=[r[3],r[4]],a=uh("(",")",this._sourceCode,i);if(a<0){this.debug&&console.warn(`Could not extract the parameters the function '${n}' (type=${s}). funcParamsStartIndex=${i}`),e=t+this.inlineToken.length;continue}let o=this._sourceCode.substring(i+1,a),l=uu(this._sourceCode,a+1);if(l===this._sourceCode.length){this.debug&&console.warn(`Could not extract the body of the function '${n}' (type=${s}). funcParamsEndIndex=${a}`),e=t+this.inlineToken.length;continue}let h=uh("{","}",this._sourceCode,l);if(h<0){this.debug&&console.warn(`Could not extract the body of the function '${n}' (type=${s}). funcBodyStartIndex=${l}`),e=t+this.inlineToken.length;continue}let u=this._sourceCode.substring(l,h+1),c=ud(o).split(","),d=[];for(let e=0;e<c.length;++e){let t=c[e].trim(),i=t.lastIndexOf(" ");i>=0&&d.push(t.substring(i+1))}"void"!==s&&d.push("return"),this._functionDescr.push({name:n,type:s,parameters:d,body:u,callIndex:0}),e=h+1;let p=t>0?this._sourceCode.substring(0,t):"",_=h+1<this._sourceCode.length-1?this._sourceCode.substring(h+1):"";this._sourceCode=p+_,e-=h+1-t}this.debug&&console.log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=`,this._functionDescr)}_processInlining(e=20){for(;e-- >=0&&this._replaceFunctionCallsByCode(););return this.debug&&console.log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(let t of this._functionDescr){let{name:i,type:r,parameters:s,body:n}=t,a=0;for(;a<this._sourceCode.length;){let o=this._sourceCode.indexOf(i,a);if(o<0)break;if(0===o||uc(this._sourceCode.charAt(o-1))){a=o+i.length;continue}let l=uu(this._sourceCode,o+i.length);if(l===this._sourceCode.length||"("!==this._sourceCode.charAt(l)){a=o+i.length;continue}let h=uh("(",")",this._sourceCode,l);if(h<0){this.debug&&console.warn(`Could not extract the parameters of the function call. Function '${i}' (type=${r}). callParamsStartIndex=${l}`),a=o+i.length;continue}let u=this._sourceCode.substring(l+1,h),c=e=>{let t=[],i=0,r=0;for(;i<e.length;){if("("===e.charAt(i)){let t=uh("(",")",e,i);if(t<0)return null;i=t}else","===e.charAt(i)&&(t.push(e.substring(r,i)),r=i+1);i++}return r<i&&t.push(e.substring(r,i)),t},d=c(ud(u));if(null===d){this.debug&&console.warn(`Invalid function call: can't extract the parameters of the function call. Function '${i}' (type=${r}). callParamsStartIndex=${l}, callParams=`+u),a=o+i.length;continue}let p=[];for(let e=0;e<d.length;++e){let t=d[e].trim();p.push(t)}let _="void"!==r?i+"_"+t.callIndex++:null;if(_&&p.push(_+" ="),p.length!==s.length){this.debug&&console.warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${i}' (type=${r}). function parameters=${s}, call parameters=${p}`),a=o+i.length;continue}a=h+1;let f=this._replaceNames(n,s,p),m=o>0?this._sourceCode.substring(0,o):"",g=h+1<this._sourceCode.length-1?this._sourceCode.substring(h+1):"";if(_){let e=function(e,t,i){for(;t>=0&&"\n"!==e.charAt(t);)t--;return t}(this._sourceCode,o-1,0);m=this._sourceCode.substring(0,e+1);let t=this._sourceCode.substring(e+1,o);this._sourceCode=m+r+" "+_+";\n"+f+"\n"+t+_+g,this.debug&&console.log(`Replace function call by code. Function '${i}' (type=${r}). injectDeclarationIndex=${e}, call parameters=${p}`)}else this._sourceCode=m+f+g,a+=f.length-(h+1-o),this.debug&&console.log(`Replace function call by code. Function '${i}' (type=${r}). functionCallIndex=${o}, call parameters=${p}`);e=!0}}return e}_replaceNames(e,t,i){for(let r=0;r<t.length;++r){let s=RegExp(t[r].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),n=t[r].length,a=i[r];e=e.replace(s,(i,...s)=>{let o=s[0];return uc(e.charAt(o-1))||uc(e.charAt(o+n))?t[r]:a})}return e}}up._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;var u_=i(6983);class uf{get isAsync(){return this.isParallelCompiled}get isReady(){if(this.compilationError){let e=this.compilationError.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}_handlesSpectorRebuildCallback(e){throw Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this._engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);let u=this._engine.getUniforms(this,i);for(u.forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l<s.length;l++){let t=e.getUniform(s[l]);null==t&&(s.splice(l,1),l--)}s.forEach((e,t)=>{n[e]=t}),o.push(...h.getAttributes(this,a))}dispose(){this._uniforms={}}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n)return n=[t,i,r,s],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),n[3]!==s&&(n[3]=s,a=!0),a}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setUInt4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&!this._engine.setMatrices(this._uniforms[e],t.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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&!this._engine.setFloat2(this._uniforms[e],t.x,t.y)&&(this._valueCache[e]=null)}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setFloat2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&!this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)&&(this._valueCache[e]=null)}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setFloat3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&!this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)&&(this._valueCache[e]=null)}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setFloat4(this._uniforms[e],t,i,r,s)&&(this._valueCache[e]=null)}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&!this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)&&(this._valueCache[e]=null)}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(this._valueCache[e]=null)}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&!this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)&&(this._valueCache[e]=null)}}class um extends nh{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class ug{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()}}let uv=new ri.y$;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{(e=t)&&uv.notifyObservers(e)}})}async function uT(e,t){(await new Promise(e=>{"undefined"==typeof _native?uv.addOnce(t=>e(t)):e(_native)}))[e]=t}class ux extends n2.h{}class uS{constructor(e){this._engine=e,this._pending=[],this._isCommandBufferScopeActive=!1,this._commandStream=uE._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw 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 uE extends r7.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 uS(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!==uE.PROTOCOL_VERSION)throw Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${uE.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:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1},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},rZ.w1.Log("Babylon Native (v"+r7.D.Version+") launched"),rZ.w1.LoadScript=function(e,t,i,r){rZ.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(){let t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,function(i,r){return Array.isArray(r)?i.push.apply(i,e.call(r,t-1)):i.push(r),i},[]):Array.prototype.slice.call(this)},writable:!0});let t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();let i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new u_.C,this.onNewSceneAddedObservable.add(e=>{let 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 hQ}_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,r=!1){if(this.useReverseDepthBuffer)throw Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t){let i=this._normalizeIndexData(e),r=new ux;return r.references=1,r.is32Bits=4===i.BYTES_PER_ELEMENT,i.byteLength&&(r.nativeIndexBuffer=this._engine.createIndexBuffer(i.buffer,i.byteOffset,i.byteLength,r.is32Bits,null!=t&&t)),r}createVertexBuffer(e,t){let i=ArrayBuffer.isView(e)?e:new Float32Array(e),r=new ux;return r.references=1,i.byteLength&&(r.nativeVertexBuffer=this._engine.createVertexBuffer(i.buffer,i.byteOffset,i.byteLength,null!=t&&t)),r}_recordVertexArrayObject(e,t,i,r,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);let n=r.getAttributesNames();for(let i=0;i<n.length;i++){let a=r.getAttributeLocation(i);if(a>=0){let r=n[i],o=null;if(s&&(o=s[r]),o||(o=t[r]),o){let t=o.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,a,o.byteOffset,o.byteStride,o.getSize(),this._getNativeAttribType(o.type),o.normalized,o.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){let s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,r),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){return this._engine.getAttributes(e.nativeProgram,t)}drawElementsType(e,t,i,r){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,r){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 uf(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,r,s,n,a,o){r?e.nativeProgram=this.createRawShaderProgram():e.nativeProgram=this.createShaderProgram(e,t,i,o)}isAsync(e){return!!(e.isAsync&&this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){if(!this.isAsync(e)){t();return}let i=e.onCompiled;i?e.onCompiled=()=>{i(),t()}:e.onCompiled=t}createRawShaderProgram(){throw Error("Not Supported")}createShaderProgram(e,t,i,r){if(e.nativeProgram)throw Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=new up(t);s.processCode(),t=s.code;let n=new up(i);n.processCode(),i=n.code,t=sx.B._ConcatenateShader(t,r),i=sx.B._ConcatenateShader(i,r);let a=()=>{var t;e.isCompiled=!0,null===(t=e.onCompiled)||void 0===t||t.call(e),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,a,t=>{e.compilationError=t});try{let r=e.nativeProgram=this._engine.createProgram(t,i);return a(),r}catch(t){let e=null==t?void 0:t.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}}inlineShaderCode(e){let t=new up(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){e&&e.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){return this._engine.getUniforms(e.nativeProgram,t)}bindUniformBlock(e,t,i){throw Error("Not Implemented")}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.nativeProgram);let i=e.getSamplers();for(let t=0;t<i.length;t++){let r=e.getUniform(i[t]);r&&(this._boundUniforms[t]=r)}this._currentEffect=null}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._engine.getRenderWidth()}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._engine.getRenderHeight()}setViewport(e,t,i){this._cachedViewport=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.x),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.y),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.width),this._commandBufferEncoder.encodeCommandArgAsFloat32(e.height),this._commandBufferEncoder.finishEncodingCommand()}enableScissor(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR),this._commandBufferEncoder.encodeCommandArgAsFloat32(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand()}disableScissor(){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.encodeCommandArgAsFloat32(0),this._commandBufferEncoder.finishEncodingCommand()}setState(e,t=0,i,r=!1,s,n,a=0){var o,l;this._zOffset=t,this._zOffsetUnits=a,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(a),this._commandBufferEncoder.encodeCommandArgAsUInt32(null===(l=null!==(o=this.cullBackFaces)&&void 0!==o?o:s)||void 0===l||l?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.finishEncodingCommand()}getInputElementClientRect(){let e={bottom:this.getRenderHeight(),height:this.getRenderHeight(),left:0,right:this.getRenderWidth(),top:0,width:this.getRenderWidth(),x:0,y:0,toJSON:()=>{}};return e}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,r,s,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,r){throw Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;let 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,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,r,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,r=!1,s){if(void 0===r&&(r=!1),e&&e._hardwareTexture){let i=t.getCanvasTexture(),r=e._hardwareTexture.underlyingResource;this._engine.copyTexture(r,i),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){let r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){let c=new sT.l(this,sT.S.Raw);if(c.format=r,c.generateMipMaps=s,c.samplingMode=a,c.invertY=n,c.baseWidth=t,c.baseHeight=i,c.width=c.baseWidth,c.height=c.baseHeight,c._compression=o,c.type=l,c._useSRGBBuffer=this._getUseSRGBBuffer(u,!s),this.updateRawTexture(c,e,r,n,o,l,c._useSRGBBuffer),c._hardwareTexture){let e=c._hardwareTexture.underlyingResource,t=this._getNativeSamplingMode(a);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(c),c}createRawTexture2DArray(e,t,i,r,s,n,a,o,l=null,h=0){let u=new sT.l(this,sT.S.Raw2DArray);if(u.baseWidth=t,u.baseHeight=i,u.baseDepth=r,u.width=t,u.height=i,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=n,u.samplingMode=o,u.is2DArray=!0,u._hardwareTexture){let l=u._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,r,this._getNativeTextureFormat(s,h),n,a);let c=this._getNativeSamplingMode(o);this._setTextureSampling(l,c)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,r,s=null,n=0,a=!1){if(e){if(t&&e._hardwareTexture){let r=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(r,t,e.width,e.height,this._getNativeTextureFormat(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_=!1){e=e||"";let f="data:"===e.substr(0,5),m=f&&-1!==e.indexOf(";base64,"),g=l||new sT.l(this,sT.S.Url),v=e;!this._transformTextureUrl||m||l||o||(e=this._transformTextureUrl(e));let T=e.lastIndexOf("."),x=u||(T>-1?e.substring(T).toLowerCase():""),S=null;for(let e of r7.D._TextureLoaders)if(e.canLoad(x)){S=e;break}r&&r.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=s,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(g._buffer=o);let E=null;n&&!l&&(E=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);let C=(i,l)=>{r&&r.removePendingData(g),e===v?(E&&g.onLoadedObservable.remove(E),rp.l.UseFallbackTexture&&this.createTexture(rp.l.FallbackTexture,t,g.invertY,r,s,null,a,o,g),a&&a((i||"Unknown error")+(rp.l.UseFallbackTexture?" - Fallback texture was used":""),l)):(ru.Y.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,r,s,n,a,o,g,h,u,c,d))};if(S)throw Error("Loading textures from IInternalTextureLoader not yet implemented.");{let n=e=>{if(!g._hardwareTexture){r&&r.removePendingData(g);return}let n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;let e=this._getNativeSamplingMode(s);this._setTextureSampling(n,e),r&&r.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>{throw Error("Could not load a native texture.")})};if(f&&o){if(o instanceof ArrayBuffer)n(new Uint8Array(o));else if(ArrayBuffer.isView(o))n(o);else if("string"==typeof o)n(new Uint8Array(rZ.w1.DecodeBase64(o)));else throw Error("Unsupported buffer type")}else m?n(new Uint8Array(rZ.w1.DecodeBase64(e))):this._loadFile(e,e=>n(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{C("Unable to load "+(e&&e.responseURL,t))})}return g}wrapNativeTexture(e,t=!1,i=3){let r=new ug(e,this._engine),s=new sT.l(this,sT.S.Unknown,!0);return s._hardwareTexture=r,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){var r,s;let n=t.generateStencil||!1,a=t.samples||1,o=new sT.l(this,sT.S.DepthStencil),l=null!==(r=e.width)&&void 0!==r?r:e,h=null!==(s=e.height)&&void 0!==s?s:e,u=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,h,n,!0,a);return i._framebufferDepthStencil=u,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){let i=new Promise((t,i)=>{let r=this.createCanvasImage();r.onload=()=>{try{let e=this._engine.createImageBitmap(r);t(e)}catch(e){i(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{i(`Error loading image ${r.src} with exception: ${e}`)},r.src=e});return i}createImageBitmap(e,t){return new Promise((t,i)=>{if(Array.isArray(e)&&e.length){let i=this._engine.createImageBitmap(e[0]);if(i){t(i);return}}i("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d,p=!1){let _=c||new sT.l(this,sT.S.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!r,_._lodGenerationScale=h,_._lodGenerationOffset=u,_._useSRGBBuffer=this._getUseSRGBBuffer(p,!!r),this._doNotHandleContextLost||(_._extension=o,_._files=i);let f=e.lastIndexOf("."),m=o||(f>-1?e.substring(f).toLowerCase():"");if(".env"===m){let t=e=>{let t=us(e);_.width=t.width,_.height=t.width,ul(_,t);let i=t.specular;if(!i)throw Error("Nothing else parsed so far");_._lodGenerationScale=i.lodGenerationScale;let r=ua(e,t);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(sv.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,r,!1,_._useSRGBBuffer,()=>{_.isReady=!0,s&&s()},()=>{throw Error("Could not load a native cube texture.")})};if(i&&6===i.length)throw Error("Multi-file loading not allowed on env files.");this._loadFile(e,e=>t(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)})}else{if(!i||6!==i.length)throw Error("Cannot load cubemap because 6 files were not defined");let e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map(e=>rZ.w1.LoadFileAsync(e).then(e=>new Uint8Array(e)))).then(e=>new Promise((t,i)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,e,!r,!0,_._useSRGBBuffer,t,i)})).then(()=>{_.isReady=!0,s&&s()},e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)})}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new ug(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){let r=new um(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=sT.S.Unknown){var s,n,a;let o;let l=!1,h=0,u=3,c=5,d=!1,p=1;void 0!==t&&"object"==typeof t?(l=!!t.generateMipMaps,h=void 0===t.type?0:t.type,u=void 0===t.samplingMode?3:t.samplingMode,c=void 0===t.format?5:t.format,d=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,p=null!==(s=t.samples)&&void 0!==s?s:1,o=t.label):l=!!t,d=this._getUseSRGBBuffer(d,!l),(1!==h||this._caps.textureFloatLinearFiltering)&&(2!==h||this._caps.textureHalfFloatLinearFiltering)||(u=1),1!==h||this._caps.textureFloat||(h=0,ru.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let _=new sT.l(this,r),f=null!==(n=e.width)&&void 0!==n?n:e,m=null!==(a=e.height)&&void 0!==a?a:e,g=e.layers||0;if(0!==g)throw Error("Texture layers are not supported in Babylon Native");let v=_._hardwareTexture.underlyingResource,T=this._getNativeTextureFormat(c,h);return this._engine.initializeTexture(v,f,m,l,T,!0,d,p),this._setTextureSampling(v,this._getNativeSamplingMode(u)),_._useSRGBBuffer=d,_.baseWidth=f,_.baseHeight=m,_.width=f,_.height=m,_.depth=g,_.isReady=!0,_.samples=p,_.generateMipMaps=l,_.samplingMode=u,_.type=h,_.format=c,_.label=o,this._internalTexturesCache.push(_),_}createRenderTargetTexture(e,t){var i,r,s,n;let a;let o=this._createHardwareRenderTargetWrapper(!1,!1,e),l=!0,h=!1,u=!1,c=1;void 0!==t&&"object"==typeof t&&(l=null===(i=t.generateDepthBuffer)||void 0===i||i,h=!!t.generateStencilBuffer,u=!!t.noColorAttachment,a=t.colorAttachment,c=null!==(r=t.samples)&&void 0!==r?r:1);let d=a||(u?null:this._createInternalTexture(e,t,!0,sT.S.RenderTarget)),p=null!==(s=e.width)&&void 0!==s?s:e,_=null!==(n=e.height)&&void 0!==n?n:e,f=this._engine.createFrameBuffer(d?d._hardwareTexture.underlyingResource:null,p,_,h,l,c);return o._framebuffer=f,o._generateDepthBuffer=l,o._generateStencilBuffer=h,o._samples=c,o.setTextures(d),o}updateRenderTargetTextureSampleCount(e,t){return ru.Y.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){let i=this._getNativeSamplingMode(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,s){if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||r)throw Error("Required width/height for frame buffers not yet supported in NativeEngine.");e._framebufferDepthStencil?this._bindUnboundFramebuffer(e._framebufferDepthStencil):this._bindUnboundFramebuffer(e._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){let r=this._normalizeIndexData(t);e.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(e.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i,r){let s=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(e.nativeVertexBuffer,s.buffer,s.byteOffset+(null!=i?i:0),null!=r?r:s.byteLength)}_setTexture(e,t,i=!1,r=!1){let s;let n=this._boundUniforms[e];if(!n)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;return s=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!!s&&!!s._hardwareTexture&&(this._setTextureWrapMode(s._hardwareTexture.underlyingResource,this._getAddressMode(t.wrapU),this._getAddressMode(t.wrapV),this._getAddressMode(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(n,s._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){let 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 Error("Unexpected wrap mode: "+e+".")}}_bindTexture(e,t){let i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){let 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 Error("Native Canvas plugin not available.");let i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");let e=new _native.Image;return e}updateTextureData(e,t,i,r,s,n,a=0,o=0,l=!1){throw Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,a=0){throw Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw 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 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 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 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 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 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 sW.LH(`Unsupported texture format or type: format ${e}, type ${t}.`,sW.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 Error(`Unsupported alpha mode: ${e}.`)}}_getNativeAttribType(e){switch(e){case rQ.o.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case rQ.o.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case rQ.o.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case rQ.o.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case rQ.o.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw Error(`Unsupported attribute type: ${e}.`)}}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,r,s,n,a,o,l,h){var u,c,d,p;if(void 0!==r&&-1!==r)throw Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);return this._engine.readTexture(null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,null!=s?s:0,null!=l?l:0,null!=h?h:0,t,i,null!==(c=null==n?void 0:n.buffer)&&void 0!==c?c:null,null!==(d=null==n?void 0:n.byteOffset)&&void 0!==d?d:0,null!==(p=null==n?void 0:n.byteLength)&&void 0!==p?p:0).then(e=>(n||(n=new Uint8Array(e)),n))}}uE.PROTOCOL_VERSION=8,uE._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new uC:new hQ};class uC extends hQ{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)}}(B=tB||(tB={})).LowPower="low-power",B.HighPerformance="high-performance",(U=tU||(tU={})).DepthClipControl="depth-clip-control",U.Depth32FloatStencil8="depth32float-stencil8",U.TextureCompressionBC="texture-compression-bc",U.TextureCompressionETC2="texture-compression-etc2",U.TextureCompressionASTC="texture-compression-astc",U.TimestampQuery="timestamp-query",U.IndirectFirstInstance="indirect-first-instance",U.ShaderF16="shader-f16",U.RG11B10UFloatRenderable="rg11b10ufloat-renderable",U.BGRA8UnormStorage="bgra8unorm-storage",U.Float32Filterable="float32-filterable",(V=tV||(tV={})).Unmapped="unmapped",V.Pending="pending",V.Mapped="mapped",(k=tk||(tk={}))[k.MapRead=1]="MapRead",k[k.MapWrite=2]="MapWrite",k[k.CopySrc=4]="CopySrc",k[k.CopyDst=8]="CopyDst",k[k.Index=16]="Index",k[k.Vertex=32]="Vertex",k[k.Uniform=64]="Uniform",k[k.Storage=128]="Storage",k[k.Indirect=256]="Indirect",k[k.QueryResolve=512]="QueryResolve",(G=tG||(tG={}))[G.Read=1]="Read",G[G.Write=2]="Write",(z=tz||(tz={})).E1d="1d",z.E2d="2d",z.E3d="3d",(W=tW||(tW={}))[W.CopySrc=1]="CopySrc",W[W.CopyDst=2]="CopyDst",W[W.TextureBinding=4]="TextureBinding",W[W.StorageBinding=8]="StorageBinding",W[W.RenderAttachment=16]="RenderAttachment",(H=tH||(tH={})).E1d="1d",H.E2d="2d",H.E2dArray="2d-array",H.Cube="cube",H.CubeArray="cube-array",H.E3d="3d",(X=tX||(tX={})).All="all",X.StencilOnly="stencil-only",X.DepthOnly="depth-only",(Y=tY||(tY={})).R8Unorm="r8unorm",Y.R8Snorm="r8snorm",Y.R8Uint="r8uint",Y.R8Sint="r8sint",Y.R16Uint="r16uint",Y.R16Sint="r16sint",Y.R16Float="r16float",Y.RG8Unorm="rg8unorm",Y.RG8Snorm="rg8snorm",Y.RG8Uint="rg8uint",Y.RG8Sint="rg8sint",Y.R32Uint="r32uint",Y.R32Sint="r32sint",Y.R32Float="r32float",Y.RG16Uint="rg16uint",Y.RG16Sint="rg16sint",Y.RG16Float="rg16float",Y.RGBA8Unorm="rgba8unorm",Y.RGBA8UnormSRGB="rgba8unorm-srgb",Y.RGBA8Snorm="rgba8snorm",Y.RGBA8Uint="rgba8uint",Y.RGBA8Sint="rgba8sint",Y.BGRA8Unorm="bgra8unorm",Y.BGRA8UnormSRGB="bgra8unorm-srgb",Y.RGB9E5UFloat="rgb9e5ufloat",Y.RGB10A2Unorm="rgb10a2unorm",Y.RG11B10UFloat="rg11b10ufloat",Y.RG32Uint="rg32uint",Y.RG32Sint="rg32sint",Y.RG32Float="rg32float",Y.RGBA16Uint="rgba16uint",Y.RGBA16Sint="rgba16sint",Y.RGBA16Float="rgba16float",Y.RGBA32Uint="rgba32uint",Y.RGBA32Sint="rgba32sint",Y.RGBA32Float="rgba32float",Y.Stencil8="stencil8",Y.Depth16Unorm="depth16unorm",Y.Depth24Plus="depth24plus",Y.Depth24PlusStencil8="depth24plus-stencil8",Y.Depth32Float="depth32float",Y.BC1RGBAUnorm="bc1-rgba-unorm",Y.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",Y.BC2RGBAUnorm="bc2-rgba-unorm",Y.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",Y.BC3RGBAUnorm="bc3-rgba-unorm",Y.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",Y.BC4RUnorm="bc4-r-unorm",Y.BC4RSnorm="bc4-r-snorm",Y.BC5RGUnorm="bc5-rg-unorm",Y.BC5RGSnorm="bc5-rg-snorm",Y.BC6HRGBUFloat="bc6h-rgb-ufloat",Y.BC6HRGBFloat="bc6h-rgb-float",Y.BC7RGBAUnorm="bc7-rgba-unorm",Y.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",Y.ETC2RGB8Unorm="etc2-rgb8unorm",Y.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",Y.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",Y.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",Y.ETC2RGBA8Unorm="etc2-rgba8unorm",Y.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",Y.EACR11Unorm="eac-r11unorm",Y.EACR11Snorm="eac-r11snorm",Y.EACRG11Unorm="eac-rg11unorm",Y.EACRG11Snorm="eac-rg11snorm",Y.ASTC4x4Unorm="astc-4x4-unorm",Y.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",Y.ASTC5x4Unorm="astc-5x4-unorm",Y.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",Y.ASTC5x5Unorm="astc-5x5-unorm",Y.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",Y.ASTC6x5Unorm="astc-6x5-unorm",Y.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",Y.ASTC6x6Unorm="astc-6x6-unorm",Y.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",Y.ASTC8x5Unorm="astc-8x5-unorm",Y.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",Y.ASTC8x6Unorm="astc-8x6-unorm",Y.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",Y.ASTC8x8Unorm="astc-8x8-unorm",Y.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",Y.ASTC10x5Unorm="astc-10x5-unorm",Y.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",Y.ASTC10x6Unorm="astc-10x6-unorm",Y.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",Y.ASTC10x8Unorm="astc-10x8-unorm",Y.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",Y.ASTC10x10Unorm="astc-10x10-unorm",Y.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",Y.ASTC12x10Unorm="astc-12x10-unorm",Y.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",Y.ASTC12x12Unorm="astc-12x12-unorm",Y.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",Y.Depth24UnormStencil8="depth24unorm-stencil8",Y.Depth32FloatStencil8="depth32float-stencil8",(j=tj||(tj={})).ClampToEdge="clamp-to-edge",j.Repeat="repeat",j.MirrorRepeat="mirror-repeat",(q=tq||(tq={})).Nearest="nearest",q.Linear="linear",(K=tK||(tK={})).Nearest="nearest",K.Linear="linear",($=t$||(t$={})).Never="never",$.Less="less",$.Equal="equal",$.LessEqual="less-equal",$.Greater="greater",$.NotEqual="not-equal",$.GreaterEqual="greater-equal",$.Always="always",(Q=tQ||(tQ={}))[Q.Vertex=1]="Vertex",Q[Q.Fragment=2]="Fragment",Q[Q.Compute=4]="Compute",(Z=tZ||(tZ={})).Uniform="uniform",Z.Storage="storage",Z.ReadOnlyStorage="read-only-storage",(J=tJ||(tJ={})).Filtering="filtering",J.NonFiltering="non-filtering",J.Comparison="comparison",(ee=t0||(t0={})).Float="float",ee.UnfilterableFloat="unfilterable-float",ee.Depth="depth",ee.Sint="sint",ee.Uint="uint",(t1||(t1={})).WriteOnly="write-only",(et=t2||(t2={})).Error="error",et.Warning="warning",et.Info="info",(ei=t3||(t3={})).Validation="validation",ei.Internal="internal",(t4||(t4={})).Auto="auto",(er=t5||(t5={})).PointList="point-list",er.LineList="line-list",er.LineStrip="line-strip",er.TriangleList="triangle-list",er.TriangleStrip="triangle-strip",(es=t6||(t6={})).CCW="ccw",es.CW="cw",(en=t8||(t8={})).None="none",en.Front="front",en.Back="back",(ea=t7||(t7={}))[ea.Red=1]="Red",ea[ea.Green=2]="Green",ea[ea.Blue=4]="Blue",ea[ea.Alpha=8]="Alpha",ea[ea.All=15]="All",(eo=t9||(t9={})).Zero="zero",eo.One="one",eo.Src="src",eo.OneMinusSrc="one-minus-src",eo.SrcAlpha="src-alpha",eo.OneMinusSrcAlpha="one-minus-src-alpha",eo.Dst="dst",eo.OneMinusDst="one-minus-dst",eo.DstAlpha="dst-alpha",eo.OneMinusDstAlpha="one-minus-dst-alpha",eo.SrcAlphaSaturated="src-alpha-saturated",eo.Constant="constant",eo.OneMinusConstant="one-minus-constant",(el=ie||(ie={})).Add="add",el.Subtract="subtract",el.ReverseSubtract="reverse-subtract",el.Min="min",el.Max="max",(eh=it||(it={})).Keep="keep",eh.Zero="zero",eh.Replace="replace",eh.Invert="invert",eh.IncrementClamp="increment-clamp",eh.DecrementClamp="decrement-clamp",eh.IncrementWrap="increment-wrap",eh.DecrementWrap="decrement-wrap",(eu=ii||(ii={})).Uint16="uint16",eu.Uint32="uint32",(ec=ir||(ir={})).Uint8x2="uint8x2",ec.Uint8x4="uint8x4",ec.Sint8x2="sint8x2",ec.Sint8x4="sint8x4",ec.Unorm8x2="unorm8x2",ec.Unorm8x4="unorm8x4",ec.Snorm8x2="snorm8x2",ec.Snorm8x4="snorm8x4",ec.Uint16x2="uint16x2",ec.Uint16x4="uint16x4",ec.Sint16x2="sint16x2",ec.Sint16x4="sint16x4",ec.Unorm16x2="unorm16x2",ec.Unorm16x4="unorm16x4",ec.Snorm16x2="snorm16x2",ec.Snorm16x4="snorm16x4",ec.Float16x2="float16x2",ec.Float16x4="float16x4",ec.Float32="float32",ec.Float32x2="float32x2",ec.Float32x3="float32x3",ec.Float32x4="float32x4",ec.Uint32="uint32",ec.Uint32x2="uint32x2",ec.Uint32x3="uint32x3",ec.Uint32x4="uint32x4",ec.Sint32="sint32",ec.Sint32x2="sint32x2",ec.Sint32x3="sint32x3",ec.Sint32x4="sint32x4",(ed=is||(is={})).Vertex="vertex",ed.Instance="instance",(ep=ia||(ia={})).Beginning="beginning",ep.End="end",(e_=io||(io={})).Beginning="beginning",e_.End="end",(ef=il||(il={})).Load="load",ef.Clear="clear",(em=ih||(ih={})).Store="store",em.Discard="discard",(eg=iu||(iu={})).Occlusion="occlusion",eg.Timestamp="timestamp",(ev=ic||(ic={})).Opaque="opaque",ev.Premultiplied="premultiplied",(eT=id||(id={})).Unknown="unknown",eT.Destroyed="destroyed",(ex=ip||(ip={})).Validation="validation",ex.OutOfMemory="out-of-memory",ex.Internal="internal";class ub{constructor(){this.shaderLanguage=nd.x.GLSL}_addUniformToLeftOverUBO(e,t,i){let r=0;[e,t,r]=this._getArraySize(e,t,i);for(let t=0;t<this._webgpuProcessingContext.leftOverUniforms.length;t++)if(this._webgpuProcessingContext.leftOverUniforms[t].name===e)return;this._webgpuProcessingContext.leftOverUniforms.push({name:e,type:t,length:r})}_buildLeftOverUBO(){if(!this._webgpuProcessingContext.leftOverUniforms.length)return"";let e=ub.LeftOvertUBOName,t=this._webgpuProcessingContext.availableBuffers[e];return t||(t={binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[e]=t,this._addBufferBindingDescription(e,t,tZ.Uniform,!0),this._addBufferBindingDescription(e,t,tZ.Uniform,!1)),this._generateLeftOverUBOCode(e,t)}_collectBindingNames(){for(let e=0;e<this._webgpuProcessingContext.bindGroupLayoutEntries.length;e++){let t=this._webgpuProcessingContext.bindGroupLayoutEntries[e];if(void 0===t){this._webgpuProcessingContext.bindGroupLayoutEntries[e]=[];continue}for(let i=0;i<t.length;i++){let t=this._webgpuProcessingContext.bindGroupLayoutEntries[e][i],r=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][t.binding].name,s=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[e][t.binding].nameInArrayOfTexture;t&&(t.texture||t.externalTexture||t.storageTexture?this._webgpuProcessingContext.textureNames.push(s):t.sampler?this._webgpuProcessingContext.samplerNames.push(r):t.buffer&&this._webgpuProcessingContext.bufferNames.push(r))}}}_preCreateBindGroupEntries(){let e=this._webgpuProcessingContext.bindGroupEntries;for(let t=0;t<this._webgpuProcessingContext.bindGroupLayoutEntries.length;t++){let i=this._webgpuProcessingContext.bindGroupLayoutEntries[t],r=[];for(let e=0;e<i.length;e++){let i=this._webgpuProcessingContext.bindGroupLayoutEntries[t][e];i.sampler||i.texture||i.storageTexture||i.externalTexture?r.push({binding:i.binding,resource:void 0}):i.buffer&&r.push({binding:i.binding,resource:{buffer:void 0,offset:0,size:0}})}e[t]=r}}_addTextureBindingDescription(e,t,i,r,s,n){let{groupIndex:a,bindingIndex:o}=t.textures[i];if(this._webgpuProcessingContext.bindGroupLayoutEntries[a]||(this._webgpuProcessingContext.bindGroupLayoutEntries[a]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[a]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[a][o]){let n;n=null===r?this._webgpuProcessingContext.bindGroupLayoutEntries[a].push({binding:o,visibility:0,externalTexture:{}}):s?this._webgpuProcessingContext.bindGroupLayoutEntries[a].push({binding:o,visibility:0,storageTexture:{access:t1.WriteOnly,format:s,viewDimension:r}}):this._webgpuProcessingContext.bindGroupLayoutEntries[a].push({binding:o,visibility:0,texture:{sampleType:t.sampleType,viewDimension:r,multisampled:!1}});let l=t.isTextureArray?e+i:e;this._webgpuProcessingContext.bindGroupLayoutEntryInfo[a][o]={name:e,index:n-1,nameInArrayOfTexture:l}}o=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[a][o].index,n?this._webgpuProcessingContext.bindGroupLayoutEntries[a][o].visibility|=tQ.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[a][o].visibility|=tQ.Fragment}_addSamplerBindingDescription(e,t,i){let{groupIndex:r,bindingIndex:s}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[r]||(this._webgpuProcessingContext.bindGroupLayoutEntries[r]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][s]){let i=this._webgpuProcessingContext.bindGroupLayoutEntries[r].push({binding:s,visibility:0,sampler:{type:t.type}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][s]={name:e,index:i-1}}s=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[r][s].index,i?this._webgpuProcessingContext.bindGroupLayoutEntries[r][s].visibility|=tQ.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[r][s].visibility|=tQ.Fragment}_addBufferBindingDescription(e,t,i,r){let{groupIndex:s,bindingIndex:n}=t.binding;if(this._webgpuProcessingContext.bindGroupLayoutEntries[s]||(this._webgpuProcessingContext.bindGroupLayoutEntries[s]=[],this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s]=[]),!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][n]){let t=this._webgpuProcessingContext.bindGroupLayoutEntries[s].push({binding:n,visibility:0,buffer:{type:i}});this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][n]={name:e,index:t-1}}n=this._webgpuProcessingContext.bindGroupLayoutEntryInfo[s][n].index,r?this._webgpuProcessingContext.bindGroupLayoutEntries[s][n].visibility|=tQ.Vertex:this._webgpuProcessingContext.bindGroupLayoutEntries[s][n].visibility|=tQ.Fragment}_injectStartingAndEndingCode(e,t,i,r){let s=e.indexOf(t);if(s<0)return console.error('No "main" function found in shader code! Processing aborted.'),e;if(i){for(;s++<e.length&&"{"!=e.charAt(s););if(s<e.length){let t=e.substring(0,s+1),r=e.substring(s+1);e=t+i+r}}if(r){let t=e.lastIndexOf("}");e=e.substring(0,t)+(r+"\n}")}return e}}ub.AutoSamplerSuffix="Sampler",ub.LeftOvertUBOName="LeftOver",ub.InternalsUBOName="Internals",ub.UniformSizes={bool:1,int:1,float:1,vec2:2,ivec2:2,uvec2:2,vec3:3,ivec3:3,uvec3:3,vec4:4,ivec4:4,uvec4:4,mat2:4,mat3:12,mat4:16,i32:1,u32:1,f32:1,mat2x2:4,mat3x3:12,mat4x4:16},ub._SamplerFunctionByWebGLSamplerType={sampler2D:"sampler2D",sampler2DArray:"sampler2DArray",sampler2DShadow:"sampler2DShadow",sampler2DArrayShadow:"sampler2DArrayShadow",samplerCube:"samplerCube",sampler3D:"sampler3D"},ub._TextureTypeByWebGLSamplerType={sampler2D:"texture2D",sampler2DArray:"texture2DArray",sampler2DShadow:"texture2D",sampler2DArrayShadow:"texture2DArray",samplerCube:"textureCube",samplerCubeArray:"textureCubeArray",sampler3D:"texture3D"},ub._GpuTextureViewDimensionByWebGPUTextureType={textureCube:tH.Cube,textureCubeArray:tH.CubeArray,texture2D:tH.E2d,texture2DArray:tH.E2dArray,texture3D:tH.E3d},ub._SamplerTypeByWebGLSamplerType={sampler2DShadow:"samplerShadow",sampler2DArrayShadow:"samplerShadow"},ub._IsComparisonSamplerByWebGPUSamplerType={samplerShadow:!0,samplerArrayShadow:!0,sampler:!1};class uy{get isAsync(){return!1}get isReady(){return!!this.stages}constructor(e,t){this.bindGroupLayouts={},this._name="unnamed",this.shaderProcessingContext=e,this._leftOverUniformsByName={},this.engine=t}_handlesSpectorRebuildCallback(){}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this.engine;e._fragmentSourceCode="",e._vertexSourceCode="";let u=this.shaderProcessingContext.availableTextures;for(l=0;l<s.length;l++){let e=s[l],t=u[s[l]];null==t||void 0==t?(s.splice(l,1),l--):n[e]=l}for(let e of h.getAttributes(this,a))o.push(e);this.buildUniformLayout();let c=[],d=[];for(l=0;l<a.length;l++){let e=o[l];e>=0&&(c.push(a[l]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=c,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){for(let e of(this.uniformBuffer=new r1.M(this.engine,void 0,void 0,"leftOver-"+this._name),this.shaderProcessingContext.leftOverUniforms)){let t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=ub.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,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,r,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,r,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,r,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){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}}let uA={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class uR{static get KnownUBOs(){return uR._SimplifiedKnownBindings?uR._SimplifiedKnownUBOs:uR._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(){let e=uR.KnownUBOs,t=[];for(let i in e){let r=e[i].binding;-1!==r.groupIndex&&(void 0===t[r.groupIndex]?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;let r=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=uA[e])&&void 0!==i?i:1)*(t||1),r}getVaryingNextLocation(e,t=0){var i;let r=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=uA[e])&&void 0!==i?i:1)*(t||1),r}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.";let t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}uR._SimplifiedKnownBindings=!0,uR._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}}},uR._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 uP extends ub{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=nd.x.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0,s=e.indexOf("["),n=e.indexOf("]");if(s>0&&n>0){let t=e.substring(s+1,n);isNaN(r=+t)&&(r=+i[t.trim()]),e=e.substr(0,s)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){let i=`// Internals UBO -uniform ${ub.InternalsUBOName} { -float yFactor_; -float textureOutputHeight_; -}; -`,r=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){let i=t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/;return i.test(e)}varyingProcessor(e,t,i){var r;this._preProcessors=i;let 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,n=s.exec(e);if(null!==n){let s;let a=null!==(r=n[1])&&void 0!==r?r:"",o=n[2],l=n[3];t?(s=this._webgpuProcessingContext.availableVaryings[l],this._missingVaryings[s]="",void 0===s&&ru.Y.Warn(`Invalid fragment shader: The varying named "${l}" is not declared in the vertex shader! This declaration will be ignored.`)):(s=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(l,o,i)[2]),this._webgpuProcessingContext.availableVaryings[l]=s,this._missingVaryings[s]=`layout(location = ${s}) ${a} in ${o} ${l};`),e=e.replace(n[0],void 0===s?"":`layout(location = ${s}) ${a} ${t?"in":"out"} ${o} ${l};`)}return e}attributeProcessor(e,t){this._preProcessors=t;let i=this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,r=i.exec(e);if(null!==r){let i=r[1],s=r[2],n=this._webgpuProcessingContext.getAttributeNextLocation(i,this._getArraySize(s,i,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s,e=e.replace(r[0],`layout(location = ${n}) in ${i} ${s};`)}return e}uniformProcessor(e,t,i){var r;this._preProcessors=i;let s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let n=s[1],a=s[2];if(0===n.indexOf("sampler")||1===n.indexOf("sampler")){let s=0;[a,n,s]=this._getArraySize(a,n,i);let o=this._webgpuProcessingContext.availableTextures[a];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:t0.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}let l=null!==(r=ub._SamplerTypeByWebGLSamplerType[n])&&void 0!==r?r:"sampler",h=!!ub._IsComparisonSamplerByWebGPUSamplerType[l],u=h?tJ.Comparison:tJ.Filtering,c=a+ub.AutoSamplerSuffix,d=this._webgpuProcessingContext.availableSamplers[c];d||(d={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:u});let p="u"===n.charAt(0)?"u":"i"===n.charAt(0)?"i":"";p&&(n=n.substr(1));let _=h?t0.Depth:"u"===p?t0.Uint:"i"===p?t0.Sint:t0.Float;o.sampleType=_;let f=s>0,m=d.binding.groupIndex,g=d.binding.bindingIndex,v=ub._SamplerFunctionByWebGLSamplerType[n],T=ub._TextureTypeByWebGLSamplerType[n],x=ub._GpuTextureViewDimensionByWebGPUTextureType[T];if(f){let t=[];t.push(`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${c};`),e=` -`;for(let i=0;i<s;++i){let r=o.textures[i].groupIndex,s=o.textures[i].bindingIndex;t.push(`layout(set = ${r}, binding = ${s}) uniform ${T} ${a}Texture${i};`),e+=`${i>0?"\n":""}#define ${a}${i} ${p}${v}(${a}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(a)}else s=1,e=`layout(set = ${m}, binding = ${g}) uniform ${l} ${c}; - layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${p}${T} ${a}Texture; - #define ${a} ${p}${v}(${a}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[a]=o,this._webgpuProcessingContext.availableSamplers[c]=d,this._addSamplerBindingDescription(c,d,!t);for(let e=0;e<s;++e)this._addTextureBindingDescription(a,o,e,x,null,!t)}else this._addUniformToLeftOverUBO(a,n,i),e=""}return e}uniformBufferProcessor(e,t){let i=/uniform\s+(\w+)/gm.exec(e);if(null!==i){let r=i[1],s=this._webgpuProcessingContext.availableBuffers[r];if(!s){let e=uR.KnownUBOs[r];s={binding:e&&-1!==e.binding.groupIndex?e.binding:this._webgpuProcessingContext.getNextFreeUBOBinding()},this._webgpuProcessingContext.availableBuffers[r]=s}this._addBufferBindingDescription(r,s,tZ.Uniform,!t),e=e.replace("uniform",`layout(set = ${s.binding.groupIndex}, binding = ${s.binding.bindingIndex}) uniform`)}return e}postProcessor(e,t,i,r,s){let 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){let t=e.indexOf("gl_FragCoord")>=0,i=` - glFragCoord_ = gl_FragCoord; - if (yFactor_ == 1.) { - glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; - } - `,r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){let t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",t?"vec4 glFragCoord_;\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");let i=-1!==t.indexOf("#define MULTIVIEW");if(i)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}if(!i){let t=e.lastIndexOf("}");e=e.substring(0,t)+"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){let i=RegExp(t+"\\s*\\[(.+)?\\]","gm"),r=i.exec(e);for(;null!==r;){let s=r[1],n=+s;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[s.trim()]),e=e.replace(r[0],t+n),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { - `;for(let e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}]; -`:i+=` ${e.type} ${e.name}; -`;return i+"};\n\n"}finalizeShaders(e,t){for(let i=0;i<this._textureArrayProcessing.length;++i){let r=this._textureArrayProcessing[i];e=this._applyTextureArrayProcessing(e,r),t=this._applyTextureArrayProcessing(t,r)}for(let e=0;e<this._missingVaryings.length;++e){let i=this._missingVaryings[e];i&&i.length>0&&(t=i+"\n"+t)}let i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,{vertexCode:e,fragmentCode:t}}}let uI=`#if NUM_BONE_INFLUENCERS>0 -attribute matricesIndices : vec4<f32>;attribute matricesWeights : vec4<f32>; -#if NUM_BONE_INFLUENCERS>4 -attribute matricesIndicesExtra : vec4<f32>;attribute matricesWeightsExtra : vec4<f32>; -#endif -#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#ifdef BONETEXTURE -var boneSampler : texture_2d<f32>;uniform boneTextureWidth : f32; -#else -uniform mBones : array<mat4x4,BonesPerMesh>; -#ifdef BONES_VELOCITY_ENABLED -uniform mPreviousBones : array<mat4x4,BonesPerMesh>; -#endif -#endif -#ifdef BONETEXTURE -fn readMatrixFromRawSampler(smp : texture_2d<f32>,index : f32)->mat4x4<f32> -{let offset=i32(index) *4; -let m0=textureLoad(smp,vec2<i32>(offset+0,0),0);let m1=textureLoad(smp,vec2<i32>(offset+1,0),0);let m2=textureLoad(smp,vec2<i32>(offset+2,0),0);let m3=textureLoad(smp,vec2<i32>(offset+3,0),0);return mat4x4<f32>(m0,m1,m2,m3);} -#endif -#endif -#endif -`;no.v.IncludesShadersStoreWGSL.bonesDeclaration=uI;let uM=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#if NUM_BONE_INFLUENCERS>0 -var influence : mat4x4<f32>; -#ifdef BONETEXTURE -influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; -#endif -#else -influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; -#endif -#endif -finalWorld=finalWorld*influence; -#endif -#endif -`;no.v.IncludesShadersStoreWGSL.bonesVertex=uM;let uD=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2<f32>;uniform bakedVertexAnimationSettings: vec4<f32>;var bakedVertexAnimationTexture : texture_2d<f32>; -#ifdef INSTANCES -attribute bakedVertexAnimationSettingsInstanced : vec4<f32>; -#endif -fn readMatrixFromRawSamplerVAT(smp : texture_2d<f32>,index : f32,frame : f32)->mat4x4<f32> -{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2<i32>(offset+0,frameUV),0);let m1=textureLoad(smp,vec2<i32>(offset+1,frameUV),0);let m2=textureLoad(smp,vec2<i32>(offset+2,frameUV),0);let m3=textureLoad(smp,vec2<i32>(offset+3,frameUV),0);return mat4x4<f32>(m0,m1,m2,m3);} -#endif -`;no.v.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration=uD;let uO=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -{ -#ifdef INSTANCES -let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; -#else -let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; -#endif -let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4<f32>;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; -#endif -finalWorld=finalWorld*VATInfluence;} -#endif -`;no.v.IncludesShadersStoreWGSL.bakedVertexAnimation=uO;let uN=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -if (false) {} -#endif -#ifdef CLIPPLANE -else if (fragmentInputs.fClipDistance>0.0) -{discard;} -#endif -#ifdef CLIPPLANE2 -else if (fragmentInputs.fClipDistance2>0.0) -{discard;} -#endif -#ifdef CLIPPLANE3 -else if (fragmentInputs.fClipDistance3>0.0) -{discard;} -#endif -#ifdef CLIPPLANE4 -else if (fragmentInputs.fClipDistance4>0.0) -{discard;} -#endif -#ifdef CLIPPLANE5 -else if (fragmentInputs.fClipDistance5>0.0) -{discard;} -#endif -#ifdef CLIPPLANE6 -else if (fragmentInputs.fClipDistance6>0.0) -{discard;} -#endif -`;no.v.IncludesShadersStoreWGSL.clipPlaneFragment=uN;let uF=`#ifdef CLIPPLANE -varying fClipDistance: f32; -#endif -#ifdef CLIPPLANE2 -varying fClipDistance2: f32; -#endif -#ifdef CLIPPLANE3 -varying fClipDistance3: f32; -#endif -#ifdef CLIPPLANE4 -varying fClipDistance4: f32; -#endif -#ifdef CLIPPLANE5 -varying fClipDistance5: f32; -#endif -#ifdef CLIPPLANE6 -varying fClipDistance6: f32; -#endif -`;no.v.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration=uF;let uL=`#ifdef CLIPPLANE -vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); -#endif -#ifdef CLIPPLANE2 -vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); -#endif -#ifdef CLIPPLANE3 -vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); -#endif -#ifdef CLIPPLANE4 -vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); -#endif -#ifdef CLIPPLANE5 -vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); -#endif -#ifdef CLIPPLANE6 -vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); -#endif -`;no.v.IncludesShadersStoreWGSL.clipPlaneVertex=uL;let uw=`#ifdef CLIPPLANE -uniform vClipPlane: vec4<f32>;varying fClipDistance: f32; -#endif -#ifdef CLIPPLANE2 -uniform vClipPlane2: vec4<f32>;varying fClipDistance2: f32; -#endif -#ifdef CLIPPLANE3 -uniform vClipPlane3: vec4<f32>;varying fClipDistance3: f32; -#endif -#ifdef CLIPPLANE4 -uniform vClipPlane4: vec4<f32>;varying fClipDistance4: f32; -#endif -#ifdef CLIPPLANE5 -uniform vClipPlane5: vec4<f32>;varying fClipDistance5: f32; -#endif -#ifdef CLIPPLANE6 -uniform vClipPlane6: vec4<f32>;varying fClipDistance6: f32; -#endif -`;no.v.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration=uw;let uB=`#ifdef INSTANCES -attribute world0 : vec4<f32>;attribute world1 : vec4<f32>;attribute world2 : vec4<f32>;attribute world3 : vec4<f32>; -#ifdef INSTANCESCOLOR -attribute instanceColor : vec4<f32>; -#endif -#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) -uniform world : mat4x4<f32>; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -attribute previousWorld0 : vec4<f32>;attribute previousWorld1 : vec4<f32>;attribute previousWorld2 : vec4<f32>;attribute previousWorld3 : vec4<f32>; -#ifdef THIN_INSTANCES -uniform previousWorld : mat4x4<f32>; -#endif -#endif -#else -#if !defined(WORLD_UBO) -uniform world : mat4x4<f32>; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -uniform previousWorld : mat4x4<f32>; -#endif -#endif -`;no.v.IncludesShadersStoreWGSL.instancesDeclaration=uB;let uU=`#ifdef INSTANCES -var finalWorld=mat4x4<f32>(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -var finalPreviousWorld=mat4x4<f32>(previousWorld0,previousWorld1,previousWorld2,previousWorld3); -#endif -#ifdef THIN_INSTANCES -#if !defined(WORLD_UBO) -finalWorld=uniforms.world*finalWorld; -#else -finalWorld=mesh.world*finalWorld; -#endif -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -finalPreviousWorld=previousWorld*finalPreviousWorld; -#endif -#endif -#else -#if !defined(WORLD_UBO) -var finalWorld=uniforms.world; -#else -var finalWorld=mesh.world; -#endif -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -var finalPreviousWorld=previousWorld; -#endif -#endif -`;no.v.IncludesShadersStoreWGSL.instancesVertex=uU;let uV=`struct Mesh {world : mat4x4<f32>, -visibility : f32,};var<uniform> mesh : Mesh; -#define WORLD_UBO -`;no.v.IncludesShadersStoreWGSL.meshUboDeclaration=uV;let uk=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#ifdef MORPHTARGETS_NORMAL -normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; -#endif -#else -positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; -#endif -#endif -#endif -`;no.v.IncludesShadersStoreWGSL.morphTargetsVertex=uk;let uG=`#ifdef MORPHTARGETS -#ifndef MORPHTARGETS_TEXTURE -attribute position{X} : vec3<f32>; -#ifdef MORPHTARGETS_NORMAL -attribute normal{X} : vec3<f32>; -#endif -#ifdef MORPHTARGETS_TANGENT -attribute tangent{X} : vec3<f32>; -#endif -#ifdef MORPHTARGETS_UV -attribute uv_{X} : vec2<f32>; -#endif -#endif -#endif -`;no.v.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration=uG;let uz=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -var vertexID : f32; -#endif -#endif -`;no.v.IncludesShadersStoreWGSL.morphTargetsVertexGlobal=uz;let uW=`#ifdef MORPHTARGETS -uniform morphTargetInfluences : array<f32,NUM_MORPH_INFLUENCERS>; -#ifdef MORPHTARGETS_TEXTURE -uniform morphTargetTextureIndices : array<f32,NUM_MORPH_INFLUENCERS>;uniform morphTargetTextureInfo : vec3<f32>;var morphTargets : texture_2d_array<f32>;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3<f32> -{ -let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2<f32>((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} -#endif -#endif -`;no.v.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration=uW;let uH=`struct Scene {viewProjection : mat4x4<f32>, -#ifdef MULTIVIEW -viewProjectionR : mat4x4<f32>, -#endif -view : mat4x4<f32>, -projection : mat4x4<f32>, -vEyePosition : vec4<f32>,};var<uniform> scene : Scene; -`;no.v.IncludesShadersStoreWGSL.sceneUboDeclaration=uH;let uX="fragmentOutputs.fragDepth",uY={texture_1d:tH.E1d,texture_2d:tH.E2d,texture_2d_array:tH.E2dArray,texture_3d:tH.E3d,texture_cube:tH.Cube,texture_cube_array:tH.CubeArray,texture_multisampled_2d:tH.E2d,texture_depth_2d:tH.E2d,texture_depth_2d_array:tH.E2dArray,texture_depth_cube:tH.Cube,texture_depth_cube_array:tH.CubeArray,texture_depth_multisampled_2d:tH.E2d,texture_storage_1d:tH.E1d,texture_storage_2d:tH.E2d,texture_storage_2d_array:tH.E2dArray,texture_storage_3d:tH.E3d,texture_external:null};class uj extends ub{constructor(){super(...arguments),this.shaderLanguage=nd.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 r=0,s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;let n=t.substring(e+1,s);for(isNaN(r=+n)&&(r=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesWGSL=[],this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${ub.InternalsUBOName} { - yFactor_: f32, - textureOutputHeight_: f32, -}; -var<uniform> internals : ${ub.InternalsUBOName}; -`+ud(e)}varyingProcessor(e,t,i){let r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==r){let s;let n=r[2],a=r[1];t?void 0===(s=this._webgpuProcessingContext.availableVaryings[a])&&ru.Y.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`):(s=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(a,n,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=s,this._varyingsWGSL.push(` @location(${s}) ${a} : ${n},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){let i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){let r=i[2],s=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s,this._attributesWGSL.push(`@location(${n}) ${s} : ${r},`),e=""}return e}uniformProcessor(e,t,i){let r=this.uniformRegexp.exec(e);if(null!==r){let t=r[2],s=r[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){let r=this.textureRegexp.exec(e);if(null!==r){let s=r[1],n=r[2],a=!!r[3],o=r[4],l=o.indexOf("storage")>0,h=r[6],u=l?h.substring(0,h.indexOf(",")).trim():null,c=a?this._getArraySize(s,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[s];if(d)c=d.textures.length;else{d={isTextureArray:c>0,isStorageTexture:l,textures:[],sampleType:t0.Float},c=c||1;for(let e=0;e<c;++e)d.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}this._webgpuProcessingContext.availableTextures[s]=d;let p=o.indexOf("depth")>0,_=uY[o],f=p?t0.Depth:"u32"===h?t0.Uint:"i32"===h?t0.Sint:t0.Float;if(d.sampleType=f,void 0===_)throw`Can't get the texture dimension corresponding to the texture function "${o}"!`;for(let i=0;i<c;++i){let{groupIndex:r,bindingIndex:n}=d.textures[i];0===i&&(e=`@group(${r}) @binding(${n}) ${e}`),this._addTextureBindingDescription(s,d,i,_,u,!t)}}return e}postProcessor(e){return e}finalizeShaders(e,t){let i=t.indexOf("fragmentInputs.position")>=0?` - if (internals.yFactor_ == 1.) { - fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; - } - `:"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);let r=this._buildLeftOverUBO();e=r+e,t=r+t,e=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<private> vertexInputs : VertexInputs;\n";let n="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar<private> vertexOutputs : FragmentInputs;\n",e=s+n+e;let a=` - vertexInputs = input; -`,o=` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; - return vertexOutputs;`;e=this._injectStartingAndEndingCode(e,"fn main",a,o),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4<f32>,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar<private> fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4<f32>,\n",u=!1,c=0;for(;!u&&!((c=t.indexOf(uX,c))<0);){let e=c;for(u=!0;c>1&&"\n"!==t.charAt(c);){if("/"===t.charAt(c)&&"/"===t.charAt(c-1)){u=!1;break}c--}c=e+uX.length}return u&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar<private> fragmentOutputs : FragmentOutputs;\n",t=l+h+t,t=this._injectStartingAndEndingCode(t,"fn main"," fragmentInputs = input;\n "+i," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} { -`;for(let t of this._webgpuProcessingContext.leftOverUniforms){let s=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=ub.UniformSizes[s];if(t.length>0){if(n<=2){let n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} { - @size(16) - el: ${s}, - }`,this._stridedUniformArrays.push(t.name),r+=` @align(16) ${t.name} : array<${n}, ${t.length}>, -`}else r+=` ${t.name} : array<${t.type}, ${t.length}>, -`}else r+=` ${t.name} : ${t.type}, -`}return r+="};\n",r=`${i} -${r}@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var<uniform> uniforms : ${e}; -`}_processSamplers(e,t){let i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],n=r[2],a=s.indexOf(ub.AutoSamplerSuffix)===s.length-ub.AutoSamplerSuffix.length?s.substring(0,s.indexOf(ub.AutoSamplerSuffix)):null,o="sampler_comparison"===n?tJ.Comparison:tJ.Filtering;if(a){let e=this._webgpuProcessingContext.availableTextures[a];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:o},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);let h=e.substring(0,r.index),u=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,c=e.substring(r.index);e=h+u+c,i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){let i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],n=r[3],a=r[4],o=r[5],l=this._webgpuProcessingContext.availableBuffers[a];if(!l){let e;let t="uniform"===s?uR.KnownUBOs[o]:null;t?(a=o,-1===(e=t.binding).groupIndex&&(e=this._webgpuProcessingContext.getNextFreeUBOBinding())):e=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:e},this._webgpuProcessingContext.availableBuffers[a]=l}this._addBufferBindingDescription(a,this._webgpuProcessingContext.availableBuffers[a],"read_write"===n?tZ.Storage:"storage"===s?tZ.ReadOnlyStorage:tZ.Uniform,t);let h=l.binding.groupIndex,u=l.binding.bindingIndex,c=e.substring(0,r.index),d=`@group(${h}) @binding(${u}) `,p=e.substring(r.index);e=c+d+p,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(let t of this._stridedUniformArrays)e=e.replace(RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}}class uq{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(let e of this._webgpuMSAATexture)null==e||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=tY.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,s){this.createView({format:this.format,dimension:i?tH.Cube:tH.E2d,mipLevelCount:t?rm.R.ILog2(Math.max(r,s))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:tX.All})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){let 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()}}let uK=` - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); - - layout(location = 0) out vec2 vTex; - - void main() { - vTex = tex[gl_VertexIndex]; - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `,u$=` - layout(set = 0, binding = 0) uniform sampler imgSampler; - layout(set = 0, binding = 1) uniform texture2D img; - - layout(location = 0) in vec2 vTex; - layout(location = 0) out vec4 outColor; - - void main() { - outColor = texture(sampler2D(img, imgSampler), vTex); - } - `,uQ=` - #extension GL_EXT_samplerless_texture_functions : enable - - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); - - layout(set = 0, binding = 0) uniform texture2D img; - - #ifdef INVERTY - layout(location = 0) out flat ivec2 vTextureSize; - #endif - - void main() { - #ifdef INVERTY - vTextureSize = textureSize(img, 0); - #endif - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `,uZ=` - #extension GL_EXT_samplerless_texture_functions : enable - - layout(set = 0, binding = 0) uniform texture2D img; - - #ifdef INVERTY - layout(location = 0) in flat ivec2 vTextureSize; - #endif - layout(location = 0) out vec4 outColor; - - void main() { - #ifdef INVERTY - vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0); - #else - vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); - #endif - #ifdef PREMULTIPLYALPHA - color.rgb *= color.a; - #endif - outColor = color; - } - `,uJ=` - #extension GL_EXT_samplerless_texture_functions : enable - - layout(set = 0, binding = 0) uniform texture2D img; - layout(set = 0, binding = 1) uniform Params { - float ofstX; - float ofstY; - float width; - float height; - }; - - #ifdef INVERTY - layout(location = 0) in flat ivec2 vTextureSize; - #endif - layout(location = 0) out vec4 outColor; - - void main() { - if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) { - discard; - } - if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) { - discard; - } - #ifdef INVERTY - vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0); - #else - vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); - #endif - #ifdef PREMULTIPLYALPHA - color.rgb *= color.a; - #endif - outColor = color; - } - `,u0=` - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - - void main() { - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `,u1=` - layout(set = 0, binding = 0) uniform Uniforms { - uniform vec4 color; - }; - - layout(location = 0) out vec4 outColor; - - void main() { - outColor = color; - } - `,u2=` - struct VertexOutput { - @builtin(position) Position : vec4<f32>, - @location(0) fragUV : vec2<f32> - } - - @vertex - fn main( - @builtin(vertex_index) VertexIndex : u32 - ) -> VertexOutput { - var pos = array<vec2<f32>, 4>( - vec2(-1.0, 1.0), - vec2( 1.0, 1.0), - vec2(-1.0, -1.0), - vec2( 1.0, -1.0) - ); - var tex = array<vec2<f32>, 4>( - vec2(0.0, 0.0), - vec2(1.0, 0.0), - vec2(0.0, 1.0), - vec2(1.0, 1.0) - ); - - var output: VertexOutput; - - output.Position = vec4<f32>(pos[VertexIndex], 0.0, 1.0); - output.fragUV = tex[VertexIndex]; - - return output; - } - `,u3=` - @group(0) @binding(0) var videoSampler: sampler; - @group(0) @binding(1) var videoTexture: texture_external; - - @fragment - fn main( - @location(0) fragUV: vec2<f32> - ) -> @location(0) vec4<f32> { - return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); - } - `,u4=` - @group(0) @binding(0) var videoSampler: sampler; - @group(0) @binding(1) var videoTexture: texture_external; - - @fragment - fn main( - @location(0) fragUV: vec2<f32> - ) -> @location(0) vec4<f32> { - return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2<f32>(fragUV.x, 1.0 - fragUV.y)); - } - `;(eS=i_||(i_={}))[eS.MipMap=0]="MipMap",eS[eS.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",eS[eS.Clear=2]="Clear",eS[eS.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst",(eE=im||(im={}))[eE.DontInvertY=0]="DontInvertY",eE[eE.InvertY=1]="InvertY";let u5=[{vertex:uK,fragment:u$},{vertex:uQ,fragment:uZ},{vertex:u0,fragment:u1},{vertex:uQ,fragment:uJ}],u6={"":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 u8{static ComputeNumMipmapLevels(e,t){return rm.R.ILog2(Math.max(e,t))+1}constructor(e,t,i,r,s){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=r,-1!==s.indexOf(tU.RG11B10UFloatRenderable)){let e=Object.keys(u6);u6[tY.RG11B10UFloat]=u6[e[e.length-1]]+1}this._mipmapSampler=e.createSampler({minFilter:tq.Linear}),this._videoSampler=e.createSampler({minFilter:tq.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,tk.Uniform|tk.CopyDst).underlyingResource,this._getPipeline(tY.RGBA8Unorm),this._getVideoPipeline(tY.RGBA8Unorm)}_getPipeline(e,t=i_.MipMap,i){let r=t===i_.MipMap?1:t===i_.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===i_.Clear?8:t===i_.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][r];if(!s){let n="#version 450\n";(t===i_.InvertYPremultiplyAlpha||t===i_.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let a=this._compiledShaders[r];if(!a){let e=this._glslang.compileGLSL(n+u5[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+u5[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));let s=this._device.createShaderModule({code:e}),o=this._device.createShaderModule({code:i});a=this._compiledShaders[r]=[s,o]}let o=this._device.createRenderPipeline({layout:t4.Auto,vertex:{module:a[0],entryPoint:"main"},fragment:{module:a[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:t5.TriangleStrip,stripIndexFormat:ii.Uint16}});s=this._pipelines[e][r]=[o,o.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=im.DontInvertY){let i=t===im.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let t=this._videoCompiledShaders[i];if(!t){let e=this._device.createShaderModule({code:u2}),r=this._device.createShaderModule({code:0===i?u3:u4});t=this._videoCompiledShaders[i]=[e,r]}let s=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:t4.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:t5.TriangleStrip,stripIndexFormat:ii.Uint16}});r=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return r}static _GetTextureTypeFromFormat(e){switch(e){case tY.R8Unorm:case tY.R8Snorm:case tY.R8Uint:case tY.R8Sint:case tY.RG8Unorm:case tY.RG8Snorm:case tY.RG8Uint:case tY.RG8Sint:case tY.RGBA8Unorm:case tY.RGBA8UnormSRGB:case tY.RGBA8Snorm:case tY.RGBA8Uint:case tY.RGBA8Sint:case tY.BGRA8Unorm:case tY.BGRA8UnormSRGB:case tY.RGB10A2Unorm:case tY.RGB9E5UFloat:case tY.RG11B10UFloat:case tY.Depth24UnormStencil8:case tY.Depth32FloatStencil8:case tY.BC7RGBAUnorm:case tY.BC7RGBAUnormSRGB:case tY.BC6HRGBUFloat:case tY.BC6HRGBFloat:case tY.BC5RGUnorm:case tY.BC5RGSnorm:case tY.BC3RGBAUnorm:case tY.BC3RGBAUnormSRGB:case tY.BC2RGBAUnorm:case tY.BC2RGBAUnormSRGB:case tY.BC4RUnorm:case tY.BC4RSnorm:case tY.BC1RGBAUnorm:case tY.BC1RGBAUnormSRGB:case tY.ETC2RGB8Unorm:case tY.ETC2RGB8UnormSRGB:case tY.ETC2RGB8A1Unorm:case tY.ETC2RGB8A1UnormSRGB:case tY.ETC2RGBA8Unorm:case tY.ETC2RGBA8UnormSRGB:case tY.EACR11Unorm:case tY.EACR11Snorm:case tY.EACRG11Unorm:case tY.EACRG11Snorm:case tY.ASTC4x4Unorm:case tY.ASTC4x4UnormSRGB:case tY.ASTC5x4Unorm:case tY.ASTC5x4UnormSRGB:case tY.ASTC5x5Unorm:case tY.ASTC5x5UnormSRGB:case tY.ASTC6x5Unorm:case tY.ASTC6x5UnormSRGB:case tY.ASTC6x6Unorm:case tY.ASTC6x6UnormSRGB:case tY.ASTC8x5Unorm:case tY.ASTC8x5UnormSRGB:case tY.ASTC8x6Unorm:case tY.ASTC8x6UnormSRGB:case tY.ASTC8x8Unorm:case tY.ASTC8x8UnormSRGB:case tY.ASTC10x5Unorm:case tY.ASTC10x5UnormSRGB:case tY.ASTC10x6Unorm:case tY.ASTC10x6UnormSRGB:case tY.ASTC10x8Unorm:case tY.ASTC10x8UnormSRGB:case tY.ASTC10x10Unorm:case tY.ASTC10x10UnormSRGB:case tY.ASTC12x10Unorm:case tY.ASTC12x10UnormSRGB:case tY.ASTC12x12Unorm:case tY.ASTC12x12UnormSRGB:break;case tY.R16Uint:case tY.R16Sint:case tY.RG16Uint:case tY.RG16Sint:case tY.RGBA16Uint:case tY.RGBA16Sint:case tY.Depth16Unorm:return 5;case tY.R16Float:case tY.RG16Float:case tY.RGBA16Float:return 2;case tY.R32Uint:case tY.R32Sint:case tY.RG32Uint:case tY.RG32Sint:case tY.RGBA32Uint:case tY.RGBA32Sint:return 7;case tY.R32Float:case tY.RG32Float:case tY.RGBA32Float:case tY.Depth32Float:return 1;case tY.Stencil8:throw"No fixed size for Stencil8 format!";case tY.Depth24Plus:throw"No fixed size for Depth24Plus format!";case tY.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0}static _GetBlockInformationFromFormat(e){switch(e){case tY.R8Unorm:case tY.R8Snorm:case tY.R8Uint:case tY.R8Sint:return{width:1,height:1,length:1};case tY.R16Uint:case tY.R16Sint:case tY.R16Float:case tY.RG8Unorm:case tY.RG8Snorm:case tY.RG8Uint:case tY.RG8Sint:return{width:1,height:1,length:2};case tY.R32Uint:case tY.R32Sint:case tY.R32Float:case tY.RG16Uint:case tY.RG16Sint:case tY.RG16Float:case tY.RGBA8Unorm:case tY.RGBA8UnormSRGB:case tY.RGBA8Snorm:case tY.RGBA8Uint:case tY.RGBA8Sint:case tY.BGRA8Unorm:case tY.BGRA8UnormSRGB:case tY.RGB9E5UFloat:case tY.RGB10A2Unorm:case tY.RG11B10UFloat:break;case tY.RG32Uint:case tY.RG32Sint:case tY.RG32Float:case tY.RGBA16Uint:case tY.RGBA16Sint:case tY.RGBA16Float:return{width:1,height:1,length:8};case tY.RGBA32Uint:case tY.RGBA32Sint:case tY.RGBA32Float:return{width:1,height:1,length:16};case tY.Stencil8:throw"No fixed size for Stencil8 format!";case tY.Depth16Unorm:return{width:1,height:1,length:2};case tY.Depth24Plus:throw"No fixed size for Depth24Plus format!";case tY.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case tY.Depth32Float:case tY.Depth24UnormStencil8:break;case tY.Depth32FloatStencil8:return{width:1,height:1,length:5};case tY.BC7RGBAUnorm:case tY.BC7RGBAUnormSRGB:case tY.BC6HRGBUFloat:case tY.BC6HRGBFloat:case tY.BC5RGUnorm:case tY.BC5RGSnorm:case tY.BC3RGBAUnorm:case tY.BC3RGBAUnormSRGB:case tY.BC2RGBAUnorm:case tY.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case tY.BC4RUnorm:case tY.BC4RSnorm:case tY.BC1RGBAUnorm:case tY.BC1RGBAUnormSRGB:case tY.ETC2RGB8Unorm:case tY.ETC2RGB8UnormSRGB:case tY.ETC2RGB8A1Unorm:case tY.ETC2RGB8A1UnormSRGB:case tY.EACR11Unorm:case tY.EACR11Snorm:return{width:4,height:4,length:8};case tY.ETC2RGBA8Unorm:case tY.ETC2RGBA8UnormSRGB:case tY.EACRG11Unorm:case tY.EACRG11Snorm:case tY.ASTC4x4Unorm:case tY.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case tY.ASTC5x4Unorm:case tY.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case tY.ASTC5x5Unorm:case tY.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case tY.ASTC6x5Unorm:case tY.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case tY.ASTC6x6Unorm:case tY.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case tY.ASTC8x5Unorm:case tY.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case tY.ASTC8x6Unorm:case tY.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case tY.ASTC8x8Unorm:case tY.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case tY.ASTC10x5Unorm:case tY.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case tY.ASTC10x6Unorm:case tY.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case tY.ASTC10x8Unorm:case tY.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case tY.ASTC10x10Unorm:case tY.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case tY.ASTC12x10Unorm:case tY.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case tY.ASTC12x12Unorm:case tY.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 tY.BC7RGBAUnormSRGB:case tY.BC7RGBAUnorm:case tY.BC6HRGBFloat:case tY.BC6HRGBUFloat:case tY.BC5RGSnorm:case tY.BC5RGUnorm:case tY.BC4RSnorm:case tY.BC4RUnorm:case tY.BC3RGBAUnormSRGB:case tY.BC3RGBAUnorm:case tY.BC2RGBAUnormSRGB:case tY.BC2RGBAUnorm:case tY.BC1RGBAUnormSRGB:case tY.BC1RGBAUnorm:case tY.ETC2RGB8Unorm:case tY.ETC2RGB8UnormSRGB:case tY.ETC2RGB8A1Unorm:case tY.ETC2RGB8A1UnormSRGB:case tY.ETC2RGBA8Unorm:case tY.ETC2RGBA8UnormSRGB:case tY.EACR11Unorm:case tY.EACR11Snorm:case tY.EACRG11Unorm:case tY.EACRG11Snorm:case tY.ASTC4x4Unorm:case tY.ASTC4x4UnormSRGB:case tY.ASTC5x4Unorm:case tY.ASTC5x4UnormSRGB:case tY.ASTC5x5Unorm:case tY.ASTC5x5UnormSRGB:case tY.ASTC6x5Unorm:case tY.ASTC6x5UnormSRGB:case tY.ASTC6x6Unorm:case tY.ASTC6x6UnormSRGB:case tY.ASTC8x5Unorm:case tY.ASTC8x5UnormSRGB:case tY.ASTC8x6Unorm:case tY.ASTC8x6UnormSRGB:case tY.ASTC8x8Unorm:case tY.ASTC8x8UnormSRGB:case tY.ASTC10x5Unorm:case tY.ASTC10x5UnormSRGB:case tY.ASTC10x6Unorm:case tY.ASTC10x6UnormSRGB:case tY.ASTC10x8Unorm:case tY.ASTC10x8UnormSRGB:case tY.ASTC10x10Unorm:case tY.ASTC10x10UnormSRGB:case tY.ASTC12x10Unorm:case tY.ASTC12x10UnormSRGB:case tY.ASTC12x12Unorm:case tY.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return tY.Depth16Unorm;case 16:return tY.Depth24Plus;case 13:return tY.Depth24PlusStencil8;case 14:return tY.Depth32Float;case 17:return tY.Depth24UnormStencil8;case 18:return tY.Depth32FloatStencil8;case 19:return tY.Stencil8;case 36492:return i?tY.BC7RGBAUnormSRGB:tY.BC7RGBAUnorm;case 36495:return tY.BC6HRGBUFloat;case 36494:return tY.BC6HRGBFloat;case 33779:return i?tY.BC3RGBAUnormSRGB:tY.BC3RGBAUnorm;case 33778:return i?tY.BC2RGBAUnormSRGB:tY.BC2RGBAUnorm;case 33777:case 33776:return i?tY.BC1RGBAUnormSRGB:tY.BC1RGBAUnorm;case 37808:return i?tY.ASTC4x4UnormSRGB:tY.ASTC4x4Unorm;case 36196:case 37492:return i?tY.ETC2RGB8UnormSRGB:tY.ETC2RGB8Unorm;case 37496:return i?tY.ETC2RGBA8UnormSRGB:tY.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return tY.R8Snorm;case 7:return tY.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return tY.R8Sint;case 9:return tY.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return tY.RGBA8Sint;default:return tY.RGBA8Snorm}case 0:switch(t){case 6:return tY.R8Unorm;case 7:return tY.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?tY.RGBA8UnormSRGB:tY.RGBA8Unorm;case 12:return i?tY.BGRA8UnormSRGB:tY.BGRA8Unorm;case 8:return tY.R8Uint;case 9:return tY.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return tY.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 tY.RGBA8Unorm}case 4:switch(t){case 8:return tY.R16Sint;case 9:return tY.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tY.RGBA16Sint}case 5:switch(t){case 8:return tY.R16Uint;case 9:return tY.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tY.RGBA16Uint}case 6:switch(t){case 8:return tY.R32Sint;case 9:return tY.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tY.RGBA32Sint}case 7:switch(t){case 8:return tY.R32Uint;case 9:return tY.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tY.RGBA32Uint}case 1:switch(t){case 6:return tY.R32Float;case 7:return tY.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return tY.RGBA32Float}case 2:switch(t){case 6:return tY.R16Float;case 7:return tY.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return tY.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return tY.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 tY.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 tY.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?tY.RGBA8UnormSRGB:tY.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case tY.R8Unorm:case tY.R8Snorm:case tY.R8Uint:case tY.R8Sint:case tY.BC4RUnorm:case tY.BC4RSnorm:case tY.R16Uint:case tY.R16Sint:case tY.Depth16Unorm:case tY.R16Float:case tY.R32Uint:case tY.R32Sint:case tY.R32Float:case tY.Depth32Float:case tY.Stencil8:case tY.Depth24Plus:case tY.EACR11Unorm:case tY.EACR11Snorm:return 1;case tY.RG8Unorm:case tY.RG8Snorm:case tY.RG8Uint:case tY.RG8Sint:case tY.Depth24UnormStencil8:case tY.Depth32FloatStencil8:case tY.BC5RGUnorm:case tY.BC5RGSnorm:case tY.RG16Uint:case tY.RG16Sint:case tY.RG16Float:case tY.RG32Uint:case tY.RG32Sint:case tY.RG32Float:case tY.Depth24PlusStencil8:case tY.EACRG11Unorm:case tY.EACRG11Snorm:return 2;case tY.RGB9E5UFloat:case tY.RG11B10UFloat:case tY.BC6HRGBUFloat:case tY.BC6HRGBFloat:case tY.ETC2RGB8Unorm:case tY.ETC2RGB8UnormSRGB:return 3;case tY.RGBA8Unorm:case tY.RGBA8UnormSRGB:case tY.RGBA8Snorm:case tY.RGBA8Uint:case tY.RGBA8Sint:case tY.BGRA8Unorm:case tY.BGRA8UnormSRGB:case tY.RGB10A2Unorm:case tY.BC7RGBAUnorm:case tY.BC7RGBAUnormSRGB:case tY.BC3RGBAUnorm:case tY.BC3RGBAUnormSRGB:case tY.BC2RGBAUnorm:case tY.BC2RGBAUnormSRGB:case tY.BC1RGBAUnorm:case tY.BC1RGBAUnormSRGB:case tY.RGBA16Uint:case tY.RGBA16Sint:case tY.RGBA16Float:case tY.RGBA32Uint:case tY.RGBA32Sint:case tY.RGBA32Float:case tY.ETC2RGB8A1Unorm:case tY.ETC2RGB8A1UnormSRGB:case tY.ETC2RGBA8Unorm:case tY.ETC2RGBA8UnormSRGB:case tY.ASTC4x4Unorm:case tY.ASTC4x4UnormSRGB:case tY.ASTC5x4Unorm:case tY.ASTC5x4UnormSRGB:case tY.ASTC5x5Unorm:case tY.ASTC5x5UnormSRGB:case tY.ASTC6x5Unorm:case tY.ASTC6x5UnormSRGB:case tY.ASTC6x6Unorm:case tY.ASTC6x6UnormSRGB:case tY.ASTC8x5Unorm:case tY.ASTC8x5UnormSRGB:case tY.ASTC8x6Unorm:case tY.ASTC8x6UnormSRGB:case tY.ASTC8x8Unorm:case tY.ASTC8x8UnormSRGB:case tY.ASTC10x5Unorm:case tY.ASTC10x5UnormSRGB:case tY.ASTC10x6Unorm:case tY.ASTC10x6UnormSRGB:case tY.ASTC10x8Unorm:case tY.ASTC10x8UnormSRGB:case tY.ASTC10x10Unorm:case tY.ASTC10x10UnormSRGB:case tY.ASTC12x10Unorm:case tY.ASTC12x10UnormSRGB:case tY.ASTC12x12Unorm:case tY.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case tY.Stencil8:case tY.Depth24UnormStencil8:case tY.Depth32FloatStencil8:case tY.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case tY.Depth24UnormStencil8:case tY.Depth32FloatStencil8:case tY.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case tY.Depth16Unorm:return tY.Depth16Unorm;case tY.Depth24Plus:case tY.Depth24PlusStencil8:case tY.Depth24UnormStencil8:return tY.Depth24Plus;case tY.Depth32Float:case tY.Depth32FloatStencil8:return tY.Depth32Float}return e}copyVideoToTexture(e,t,i,r=!1,s){var n,a,o,l;let h=void 0===s,[u,c]=this._getVideoPipeline(i,r?im.InvertY:im.DontInvertY);h&&(s=this._device.createCommandEncoder({})),null===(a=(n=s).pushDebugGroup)||void 0===a||a.call(n,`copy video to texture - invertY=${r}`);let d=t._hardwareTexture,p={colorAttachments:[{view:d.underlyingResource.createView({format:i,dimension:tH.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:tX.All}),loadOp:il.Load,storeOp:ih.Store}]},_=s.beginRenderPass(p),f={layout:c,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},m=this._device.createBindGroup(f);_.setPipeline(u),_.setBindGroup(0,m),_.draw(4,1,0,0),_.end(),null===(l=(o=s).popDebugGroup)||void 0===l||l.call(o),h&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,r,s=!1,n=!1,a=0,o=0,l=1,h=0,u=0,c=0,d=0,p,_){var f,m,g,v,T,x;let S;let E=0!==c,C=void 0===p,[b,y]=this._getPipeline(r,E?i_.InvertYPremultiplyAlphaWithOfst:i_.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:n});if(a=Math.max(a,0),C&&(p=this._device.createCommandEncoder({})),null===(m=(f=p).pushDebugGroup)||void 0===m||m.call(f,`internal process texture - invertY=${s} premultiplyAlpha=${n}`),u8._IsHardwareTexture(e)?(S=e.underlyingResource,s&&!n&&1===l&&0===a||(e=void 0)):(S=e,e=void 0),!S)return;E&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,u,c,d]),0,16);let 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,r,1,p,tW.CopySrc|tW.RenderAttachment|tW.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),P=null!==(v=null==A?void 0:A._copyInvertYRenderPassDescr)&&void 0!==v?v:{colorAttachments:[{view:R.createView({format:r,dimension:tH.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:il.Load,storeOp:ih.Store}]},I=p.beginRenderPass(P),M=E?null==A?void 0:A._copyInvertYBindGroupWithOfst:null==A?void 0:A._copyInvertYBindGroup;if(!M){let e={layout:y,entries:[{binding:0,resource:S.createView({format:r,dimension:tH.E2d,baseMipLevel:o,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:a})}]};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:S,mipLevel:o,origin:{x:0,y:0,z:a}},{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===(x=(T=p).popDebugGroup)||void 0===x||x.call(T),C&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,r){var s,n,a,o;let l=void 0===r,[h,u]=this._getPipeline(t,i_.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});l&&(r=this._device.createCommandEncoder({})),null===(n=(s=r).pushDebugGroup)||void 0===n||n.call(s,"internal copy texture with invertY");let c=r.beginRenderPass(i),d=this._device.createBindGroup({layout:u,entries:[{binding:0,resource:e}]});c.setPipeline(h),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),null===(o=(a=r).popDebugGroup)||void 0===o||o.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,s=!1,n=!1,a=tY.RGBA8Unorm,o=1,l,h=-1,u=0,c){o>1&&(o=4);let d=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:d},_=u6[a]?tW.RenderAttachment:0,f=u8.IsCompressedFormat(a),m=t?u8.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:tW.CopySrc|tW.CopyDst|tW.TextureBinding;u|=t&&!f?tW.CopySrc|_:0,f||n||(u|=_|tW.CopyDst);let v=this._device.createTexture({label:`Texture${n?"3D":"2D"}_${c?c+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${a}_samples${o}`,size:p,dimension:n?tz.E3d:tz.E2d,format:a,usage:g|u,sampleCount:o,mipLevelCount:m});return u8.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,a,0,0,r,s,0,0),t&&i&&this.generateMipmaps(v,a,m,0,l)),v}createCubeTexture(e,t=!1,i=!1,r=!1,s=!1,n=tY.RGBA8Unorm,a=1,o,l=-1,h=0,u){a>1&&(a=4);let c=u8.IsImageBitmapArray(e)?e[0].width:e.width,d=u8.IsImageBitmapArray(e)?e[0].height:e.height,p=u6[n]?tW.RenderAttachment:0,_=u8.IsCompressedFormat(n),f=t?u8.ComputeNumMipmapLevels(c,d):1,m=l>=0?l:tW.CopySrc|tW.CopyDst|tW.TextureBinding;h|=t&&!_?tW.CopySrc|p:0,_||(h|=p|tW.CopyDst);let g=this._device.createTexture({label:`TextureCube_${u?u+"_":""}${c}x${d}x6_${t?"wmips":"womips"}_${n}_samples${a}`,size:{width:c,height:d,depthOrArrayLayers:6},dimension:tz.E2d,format:n,usage:m|h,sampleCount:a,mipLevelCount:f});return u8.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,c,d,n,r,s,0,0),t&&i&&this.generateCubeMipmaps(g,n,f,o)),g}generateCubeMipmaps(e,t,i,r){var s,n,a,o;let l=void 0===r;l&&(r=this._device.createCommandEncoder({})),null===(n=(s=r).pushDebugGroup)||void 0===n||n.call(s,`create cube mipmaps - ${i} levels`);for(let s=0;s<6;++s)this.generateMipmaps(e,t,i,s,r);null===(o=(a=r).popDebugGroup)||void 0===o||o.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,s){var n,a,o,l,h,u,c,d;let p;let _=void 0===s,[f,m]=this._getPipeline(t);if(r=Math.max(r,0),_&&(s=this._device.createCommandEncoder({})),null===(a=(n=s).pushDebugGroup)||void 0===a||a.call(n,`create mipmaps for face #${r} - ${i} levels`),u8._IsHardwareTexture(e)?(p=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(p=e,e=void 0),!p)return;let g=e;for(let e=1;e<i;++e){let i=null!==(l=null===(o=null==g?void 0:g._mipmapGenRenderPassDescr[r])||void 0===o?void 0:o[e-1])&&void 0!==l?l:{colorAttachments:[{view:p.createView({format:t,dimension:tH.E2d,baseMipLevel:e,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:r}),loadOp:il.Load,storeOp:ih.Store}]};g&&(g._mipmapGenRenderPassDescr[r]=g._mipmapGenRenderPassDescr[r]||[],g._mipmapGenRenderPassDescr[r][e-1]=i);let n=s.beginRenderPass(i),a=null!==(u=null===(h=null==g?void 0:g._mipmapGenBindGroup[r])||void 0===h?void 0:h[e-1])&&void 0!==u?u:this._device.createBindGroup({layout:m,entries:[{binding:0,resource:this._mipmapSampler},{binding:1,resource:p.createView({format:t,dimension:tH.E2d,baseMipLevel:e-1,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:r})}]});g&&(g._mipmapGenBindGroup[r]=g._mipmapGenBindGroup[r]||[],g._mipmapGenBindGroup[r][e-1]=a),n.setPipeline(f),n.setBindGroup(0,a),n.draw(4,1,0,0),n.end()}null===(d=(c=s).popDebugGroup)||void 0===d||d.call(c),_&&(this._device.queue.submit([s.finish()]),s=null)}createGPUTextureForInternalTexture(e,t,i,r,s){let n;e._hardwareTexture||(e._hardwareTexture=new uq),void 0===t&&(t=e.width),void 0===i&&(i=e.height),void 0===r&&(r=e.depth);let a=e._hardwareTexture,o=((null!=s?s:0)&1)!=0;a.format=u8.GetWebGPUTextureFormat(e.type,e.format,e._useSRGBBuffer),a.textureUsages=e._source===sT.S.RenderTarget||e.source===sT.S.MultiRenderTarget?tW.TextureBinding|tW.CopySrc|tW.RenderAttachment:e._source===sT.S.DepthStencil?tW.TextureBinding|tW.RenderAttachment:-1,a.textureAdditionalUsages=o?tW.StorageBinding:0;let l=e.generateMipMaps,h=r||1;if(n=null!==e._maxLodLevel?e._maxLodLevel:l?u8.ComputeNumMipmapLevels(t,i):1,e.isCube){let r=this.createCubeTexture({width:t,height:i},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,a.format,1,this._commandEncoderForCreation,a.textureUsages,a.textureAdditionalUsages,e.label);a.set(r),a.createView({format:u8.GetDepthFormatOnly(a.format),dimension:tH.Cube,mipLevelCount:n,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:6,aspect:u8.HasDepthAndStencilAspects(a.format)?tX.DepthOnly:tX.All},o)}else{let r=this.createTexture({width:t,height:i,layers:h},e.generateMipMaps,e.generateMipMaps,e.invertY,!1,e.is3D,a.format,1,this._commandEncoderForCreation,a.textureUsages,a.textureAdditionalUsages,e.label);a.set(r),a.createView({format:u8.GetDepthFormatOnly(a.format),dimension:e.is2DArray?tH.E2dArray:e.is3D?tz.E3d:tH.E2d,mipLevelCount:n,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:e.is3D?1:h,aspect:u8.HasDepthAndStencilAspects(a.format)?tX.DepthOnly:tX.All},o)}return e.width=e.baseWidth=t,e.height=e.baseHeight=i,e.depth=e.baseDepth=r,this.createMSAATexture(e,e.samples),a}createMSAATexture(e,t,i=!0,r=-1){let s=e._hardwareTexture;if(i&&(null==s||s.releaseMSAATexture()),!s||(null!=t?t:1)<=1)return;let n=e.width,a=e.height,o=this.createTexture({width:n,height:a,layers:1},!1,!1,!1,!1,!1,s.format,t,this._commandEncoderForCreation,tW.RenderAttachment,0,e.label?"MSAA"+e.label:void 0);s.setMSAATexture(o,r)}updateCubeTextures(e,t,i,r,s,n=!1,a=!1,o=0,l=0){let h=[0,3,1,4,2,5];for(let u=0;u<h.length;++u){let c=e[h[u]];this.updateTexture(c,t,i,r,1,s,u,0,n,a,o,l)}}updateTexture(e,t,i,r,s,n,a=0,o=0,l=!1,h=!1,u=0,c=0,d){let p=u8._IsInternalTexture(t)?t._hardwareTexture.underlyingResource:t,_=u8._GetBlockInformationFromFormat(n),f=u8._IsInternalTexture(t)?t._hardwareTexture:t,m={texture:p,origin:{x:u,y:c,z:Math.max(a,0)},mipLevel:o,premultipliedAlpha:h},g={width:Math.ceil(i/_.width)*_.width,height:Math.ceil(r/_.height)*_.height,depthOrArrayLayers:s||1};if(void 0!==e.byteLength){let p=Math.ceil(i/_.width)*_.length,v=256*Math.ceil(p/256)===p;if(v){let t=this._device.createCommandEncoder({}),i=this._bufferManager.createRawBuffer(e.byteLength,tk.MapWrite|tk.CopySrc,!0),s=i.getMappedRange();new Uint8Array(s).set(e),i.unmap(),t.copyBufferToTexture({buffer:i,offset:0,bytesPerRow:p,rowsPerImage:r},m,g),this._device.queue.submit([t.finish()]),this._bufferManager.releaseBuffer(i)}else this._device.queue.writeTexture(m,e,{offset:0,bytesPerRow:p,rowsPerImage:r},g);if(l||h){if(u8._IsInternalTexture(t)){let e=0===u&&0===c&&i===t.width&&r===t.height;this.invertYPreMultiplyAlpha(f,t.width,t.height,n,l,h,a,o,s||1,u,c,e?0:i,e?0:r,void 0,d)}else throw"updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!"}}else if(l){if(m.premultipliedAlpha=!1,u8._IsInternalTexture(t)&&0===u&&0===c&&i===t.width&&r===t.height)this._device.queue.copyExternalImageToTexture({source:e},m,g),this.invertYPreMultiplyAlpha(f,i,r,n,l,h,a,o,s||1,0,0,0,0,void 0,d);else{let t=this._device.createCommandEncoder({}),u=this.createTexture({width:i,height:r,layers:1},!1,!1,!1,!1,!1,n,1,t,tW.CopySrc|tW.TextureBinding,void 0,"TempTextureForUpdateTexture");this._deferredReleaseTextures.push([u,null]),g.depthOrArrayLayers=1,this._device.queue.copyExternalImageToTexture({source:e},{texture:u},g),g.depthOrArrayLayers=s||1,this.invertYPreMultiplyAlpha(u,i,r,n,l,h,a,o,s||1,0,0,0,0,t,d),t.copyTextureToTexture({texture:u},m,g),this._device.queue.submit([t.finish()])}}else this._device.queue.copyExternalImageToTexture({source:e},m,g)}readPixels(e,t,i,r,s,n,a=0,o=0,l=null,h=!1){let u=u8._GetBlockInformationFromFormat(n),c=Math.ceil(r/u.width)*u.length,d=256*Math.ceil(c/256),p=d*s,_=this._bufferManager.createRawBuffer(p,tk.MapRead|tk.CopyDst),f=this._device.createCommandEncoder({});return f.copyTextureToBuffer({texture:e,mipLevel:o,origin:{x:t,y:i,z:Math.max(a,0)}},{buffer:_,offset:0,bytesPerRow:d},{width:r,height:s,depthOrArrayLayers:1}),this._device.queue.submit([f.finish()]),this._bufferManager.readDataFromBuffer(_,p,r,s,c,d,u8._GetTextureTypeFromFormat(n),0,l,!0,h)}releaseTexture(e){if(u8._IsInternalTexture(e)){let t=e._hardwareTexture,i=e._irradianceTexture;this._deferredReleaseTextures.push([t,i])}else this._deferredReleaseTextures.push([e,null])}destroyDeferredTextures(){for(let e=0;e<this._deferredReleaseTextures.length;++e){let[t,i]=this._deferredReleaseTextures[e];t&&(u8._IsHardwareTexture(t)?t.release():t.destroy()),null==i||i.dispose()}this._deferredReleaseTextures.length=0}}class u7 extends n2.h{constructor(e,t=0){super(),this.capacity=t,this._buffer=e}get underlyingResource(){return this._buffer}}class u9{static _IsGPUBuffer(e){return void 0===e.underlyingResource}constructor(e){this._deferredReleaseBuffers=[],this._device=e}createRawBuffer(e,t,i=!1){let r=void 0!==e.byteLength?e.byteLength+3&-4:e+3&-4;return this._device.createBuffer({mappedAtCreation:i,size:r,usage:t})}createBuffer(e,t){let i=void 0!==e.byteLength,r=this.createRawBuffer(e,t),s=new u7(r);return s.references=1,s.capacity=i?e.byteLength:e,i&&this.setSubData(s,0,e),s}setRawData(e,t,i,r,s){this._device.queue.writeBuffer(e,t,i.buffer,r,s)}setSubData(e,t,i,r=0,s=0){let n=e.underlyingResource;s=Math.min(s=s||i.byteLength,e.capacity-t);let a=i.byteOffset+r,o=a+s,l=s+3&-4;if(l!==s){let e=new Uint8Array(i.buffer.slice(a,o));(i=new Uint8Array(l)).set(e),r=0,a=0,o=l,s=l}let h=0;for(;o-(a+h)>15728640;)this._device.queue.writeBuffer(n,t+h,i.buffer,a+h,15728640),h+=15728640;this._device.queue.writeBuffer(n,t+h,i.buffer,a+h,s-h)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));let r=new Uint16Array(t);for(;e--;)i[e]=h8(r[e]);return i}readDataFromBuffer(e,t,i,r,s,n,a=0,o=0,l=null,h=!0,u=!1){let c=1===a?2:2===a?1:0;return new Promise((i,d)=>{e.mapAsync(tG.Read,o,t).then(()=>{let d=e.getMappedRange(o,t),p=l;if(u)p=null===p?(0,hK.A)(a,t,!0,d):(0,hK.A)(a,p.buffer,void 0,d);else if(null===p)switch(c){case 0:(p=new Uint8Array(t)).set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:(p=new Float32Array(t/4)).set(new Float32Array(d))}else switch(c){case 0:(p=new Uint8Array(p.buffer)).set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:(p=new Float32Array(p.buffer)).set(new Float32Array(d))}if(s!==n){1!==c||u||(s*=2,n*=2);let e=new Uint8Array(p.buffer),t=s,i=0;for(let a=1;a<r;++a){i=a*n;for(let r=0;r<s;++r)e[t++]=e[i++]}p=0===c||u?new Uint8Array(e.buffer,0,t):new Float32Array(e.buffer,0,t/4)}e.unmap(),h&&this.releaseBuffer(e),i(p)},e=>d(e))})}releaseBuffer(e){return u9._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e<this._deferredReleaseBuffers.length;++e)this._deferredReleaseBuffers[e].destroy();this._deferredReleaseBuffers.length=0}}class ce{constructor(){this.colorAttachmentGPUTextures=[],this.reset()}reset(e=!1){this.renderPass=null,e&&(this.renderPassDescriptor=null,this.colorAttachmentViewDescriptor=null,this.depthAttachmentViewDescriptor=null,this.colorAttachmentGPUTextures=[],this.depthTextureFormat=void 0)}}let ct=[0,0,3,7,0,2,6,2,4,1,5,3,1],ci=[0,64,32,96,16,80,48,112,8],cr=[0,128,128,0,0,0,0,128,0,0,0,0,128];class cs{constructor(e){this._samplers={},this._device=e,this.disabled=!1}static GetSamplerHashCode(e){var t,i,r;let s=e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,n=ct[e.samplingMode]+ci[(e._comparisonFunction||514)-512+1]+cr[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(r=e._cachedWrapR)&&void 0!==r?r:1)<<12)+((e.useMipMaps?1:0)<<14)+(s<<15);return n}static _GetSamplerFilterDescriptor(e,t){let i,r,s,n,a;let o=e.useMipMaps;switch(e.samplingMode){case 11:i=tq.Linear,r=tq.Linear,s=tq.Nearest,o||(n=a=0);break;case 3:case 3:i=tq.Linear,r=tq.Linear,o?s=tq.Linear:(s=tq.Nearest,n=a=0);break;case 8:i=tq.Nearest,r=tq.Nearest,o?s=tq.Linear:(s=tq.Nearest,n=a=0);break;case 4:i=tq.Nearest,r=tq.Nearest,s=tq.Nearest,o||(n=a=0);break;case 5:i=tq.Nearest,r=tq.Linear,s=tq.Nearest,o||(n=a=0);break;case 6:i=tq.Nearest,r=tq.Linear,o?s=tq.Linear:(s=tq.Nearest,n=a=0);break;case 7:i=tq.Nearest,r=tq.Linear,s=tq.Nearest,n=a=0;break;case 1:case 1:default:i=tq.Nearest,r=tq.Nearest,s=tq.Nearest,n=a=0;break;case 9:i=tq.Linear,r=tq.Nearest,s=tq.Nearest,o||(n=a=0);break;case 10:i=tq.Linear,r=tq.Nearest,o?s=tq.Linear:(s=tq.Nearest,n=a=0);break;case 2:case 2:i=tq.Linear,r=tq.Linear,s=tq.Nearest,n=a=0;break;case 12:i=tq.Linear,r=tq.Nearest,s=tq.Nearest,n=a=0}return t>1&&(0!==n||0!==a)?{magFilter:tq.Linear,minFilter:tq.Linear,mipmapFilter:tq.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:s,lodMinClamp:n,lodMaxClamp:a}}static _GetWrappingMode(e){switch(e){case 1:break;case 0:return tj.ClampToEdge;case 2:return tj.MirrorRepeat}return tj.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e){let 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?cs.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:i.anisotropyEnabled?t:1})}static GetCompareFunction(e){switch(e){case 519:return t$.Always;case 514:return t$.Equal;case 516:return t$.Greater;case 518:return t$.GreaterEqual;case 513:default:return t$.Less;case 515:return t$.LessEqual;case 512:return t$.Never;case 517:return t$.NotEqual}}getSampler(e,t=!1,i=0){if(this.disabled)return this._device.createSampler(cs._GetSamplerDescriptor(e));t?i=0:0===i&&(i=cs.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(cs._GetSamplerDescriptor(e)),t||(this._samplers[i]=r)),r}}(eC=ig||(ig={}))[eC.StencilReadMask=0]="StencilReadMask",eC[eC.StencilWriteMask=1]="StencilWriteMask",eC[eC.DepthBias=2]="DepthBias",eC[eC.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",eC[eC.DepthStencilState=4]="DepthStencilState",eC[eC.MRTAttachments1=5]="MRTAttachments1",eC[eC.MRTAttachments2=6]="MRTAttachments2",eC[eC.RasterizationState=7]="RasterizationState",eC[eC.ColorStates=8]="ColorStates",eC[eC.ShaderStage=9]="ShaderStage",eC[eC.TextureStage=10]="TextureStage",eC[eC.VertexState=11]="VertexState",eC[eC.NumStates=12]="NumStates";let cn={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},ca={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class co{constructor(e,t,i){this.mrtTextureCount=0,this._device=e,this._useTextureStage=i,this._states=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=[tY.BGRA8Unorm],this.setColorFormat(tY.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(tY.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,r=0){if(i>1&&(i=4),this.disabled){let s=co._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,s,i),co.NumCacheMiss++,co._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,co.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return co.NumCacheHitWithHash++,this._parameter.pipeline;let s=co._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),co.NumCacheMiss++,co._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){co.NumPipelineCreationLastFrame=co._NumPipelineCreationCurrentFrame,co._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,s,n,a,o){this._depthWriteEnabled=a,this._depthTestEnabled=n,this._depthCompare=(null!=o?o:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[ig.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[ig.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=u6[null!=e?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i<e.length;++i)0!==e[i]&&(t+=1<<i);this._mrtEnabledMask!==t&&(this._mrtEnabledMask=t,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.MRTAttachments1))}setMRT(e,t){var i,r;if((t=null!=t?t:e.length)>10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;let s=[0,0],n=0,a=0,o=0;for(let l=0;l<t;++l){let t=e[l],h=null==t?void 0:t._hardwareTexture;this._mrtFormats[o]=null!==(i=null==h?void 0:h.format)&&void 0!==i?i:this._webgpuColorFormat[0],s[n]+=u6[null!==(r=this._mrtFormats[o])&&void 0!==r?r:""]<<a,a+=6,o++,a>=32&&(a=0,n++)}this._mrtFormats.length=o,(this._mrtAttachments1!==s[0]||this._mrtAttachments2!==s[1])&&(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[ig.MRTAttachments1]=s[0],this._states[ig.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.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:u6[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:ca[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:ca[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:ca[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[ig.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[ig.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,s,n,a){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:519)-512,this._stencilFrontDepthFailOp=null===i?1:ca[i],this._stencilFrontPassOp=null===r?2:ca[r],this._stencilFrontFailOp=null===s?1:ca[s],this.setStencilReadMask(n),this.setStencilWriteMask(a)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return t5.TriangleList;case 2:case 3:return t5.PointList;case 1:case 4:return t5.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return t5.LineStrip;case 7:return t5.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return ie.Add;case 32778:return ie.Subtract;case 32779:return ie.ReverseSubtract;case 32775:return ie.Min;case 32776:return ie.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return t9.Zero;case 1:default:return t9.One;case 768:return t9.Src;case 769:return t9.OneMinusSrc;case 770:return t9.SrcAlpha;case 771:return t9.OneMinusSrcAlpha;case 772:return t9.DstAlpha;case 773:return t9.OneMinusDstAlpha;case 774:return t9.Dst;case 775:return t9.OneMinusDst;case 776:return t9.SrcAlphaSaturated;case 32769:case 32771:return t9.Constant;case 32770:case 32772:return t9.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:break;case 1:return t$.Less;case 2:return t$.Equal;case 3:return t$.LessEqual;case 4:return t$.Greater;case 5:return t$.NotEqual;case 6:return t$.GreaterEqual;case 7:return t$.Always}return t$.Never}static _GetStencilOpFunction(e){switch(e){case 0:return it.Zero;case 1:break;case 2:return it.Replace;case 3:return it.IncrementClamp;case 4:return it.DecrementClamp;case 5:return it.Invert;case 6:return it.IncrementWrap;case 7:return it.DecrementWrap}return it.Keep}static _GetVertexInputDescriptorFormat(e){let t=e.type,i=e.normalized,r=e.getSize();switch(t){case rQ.o.BYTE:switch(r){case 1:case 2:return i?ir.Snorm8x2:ir.Sint8x2;case 3:case 4:return i?ir.Snorm8x4:ir.Sint8x4}break;case rQ.o.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?ir.Unorm8x2:ir.Uint8x2;case 3:case 4:return i?ir.Unorm8x4:ir.Uint8x4}break;case rQ.o.SHORT:switch(r){case 1:case 2:return i?ir.Snorm16x2:ir.Sint16x2;case 3:case 4:return i?ir.Snorm16x4:ir.Sint16x4}break;case rQ.o.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?ir.Unorm16x2:ir.Uint16x2;case 3:case 4:return i?ir.Unorm16x4:ir.Uint16x4}break;case rQ.o.INT:switch(r){case 1:return ir.Sint32;case 2:return ir.Sint32x2;case 3:return ir.Sint32x3;case 4:return ir.Sint32x4}break;case rQ.o.UNSIGNED_INT:switch(r){case 1:return ir.Uint32;case 2:return ir.Uint32x2;case 3:return ir.Uint32x3;case 4:return ir.Uint32x4}break;case rQ.o.FLOAT:switch(r){case 1:return ir.Float32;case 2:return ir.Float32x2;case 3:return ir.Float32x3;case 4:return ir.Float32x4}}throw Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:co._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:co._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:co._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:co._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:co._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:co._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[ig.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.ShaderStage))}_setRasterizationState(e,t){let i=this._frontFace,r=this._cullEnabled?this._cullFace:0,s=this._clampDepth?1:0,n=this._alphaToCoverageEnabled?1:0,a=i-1+(r<<1)+(s<<3)+(n<<4)+(e<<5)+(t<<8);this._rasterizationState!==a&&(this._rasterizationState=a,this._states[ig.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.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:cn[this._alphaBlendFuncParams[0]])<<0)+((null===this._alphaBlendFuncParams[1]?2:cn[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:cn[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:cn[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[ig.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.ColorStates))}_setDepthStencilState(){let 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[ig.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.DepthStencilState))}_setVertexState(e){var t,i;let r;let s=this._statesLength,n=ig.VertexState,a=e._pipelineContext,o=a.shaderProcessingContext.attributeNamesFromEffect,l=a.shaderProcessingContext.attributeLocationsFromEffect,h=0;for(let e=0;e<o.length;e++){let s=l[e],a=null!==(t=this._overrideVertexBuffers&&this._overrideVertexBuffers[o[e]])&&void 0!==t?t:this._vertexBuffers[o[e]];a||(a=this._emptyVertexBuffer);let u=null===(i=a.getBuffer())||void 0===i?void 0:i.underlyingResource;if(void 0===a._validOffsetRange){let e=a.byteOffset,t=a.getSize(!0),i=a.byteStride;a._validOffsetRange=e<=this._kMaxVertexBufferStride-t&&(0===i||e+t<=i)}r&&r===u&&a._validOffsetRange||(this.vertexBuffers[h++]=a,r=a._validOffsetRange?u:null);let c=a.hashCode+(s<<7);this._isDirty=this._isDirty||this._states[n]!==c,this._states[n++]=c}this.vertexBuffers.length=h,this._statesLength=n,this._isDirty=this._isDirty||n!==s,this._isDirty&&(this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.VertexState))}_setTextureState(e){this._textureState!==e&&(this._textureState=e,this._states[ig.TextureStage]=this._textureState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ig.TextureStage))}_createPipelineLayout(e){if(this._useTextureStage)return this._createPipelineLayoutWithTextureStage(e);let t=[],i=e.shaderProcessingContext.bindGroupLayoutEntries;for(let e=0;e<i.length;e++){let r=i[e];t[e]=this._device.createBindGroupLayout({entries:r})}return e.bindGroupLayouts[0]=t,this._device.createPipelineLayout({bindGroupLayouts:t})}_createPipelineLayoutWithTextureStage(e){var t;let i=e.shaderProcessingContext,r=i.bindGroupLayoutEntries,s=1;for(let e=0;e<r.length;e++){let n=r[e];for(let a=0;a<n.length;a++){let n=r[e][a];if(n.texture){let a=i.bindGroupLayoutEntryInfo[e][n.binding].name,o=i.availableTextures[a],l=o.autoBindSampler?i.availableSamplers[a+ub.AutoSamplerSuffix]:null,h=o.sampleType,u=null!==(t=null==l?void 0:l.type)&&void 0!==t?t:tJ.Filtering;if(this._textureState&s&&h!==t0.Depth&&(o.autoBindSampler&&(u=tJ.NonFiltering),h=t0.UnfilterableFloat),n.texture.sampleType=h,l){let e=i.bindGroupLayoutEntryInfo[l.binding.groupIndex][l.binding.bindingIndex].index;r[l.binding.groupIndex][e].sampler.type=u}s<<=1}}}let n=[];for(let e=0;e<r.length;++e)n[e]=this._device.createBindGroupLayout({entries:r[e]});return e.bindGroupLayouts[this._textureState]=n,this._device.createPipelineLayout({bindGroupLayouts:n})}_getVertexInputDescriptor(e){var t,i;let r,s;let n=[],a=e._pipelineContext,o=a.shaderProcessingContext.attributeNamesFromEffect,l=a.shaderProcessingContext.attributeLocationsFromEffect;for(let e=0;e<o.length;e++){let a=l[e],h=null!==(t=this._overrideVertexBuffers&&this._overrideVertexBuffers[o[e]])&&void 0!==t?t:this._vertexBuffers[o[e]];h||(h=this._emptyVertexBuffer);let u=null===(i=h.getBuffer())||void 0===i?void 0:i.underlyingResource,c=h.byteOffset,d=!h._validOffsetRange;if(!(r&&s&&r===u)||d){let e={arrayStride:h.byteStride,stepMode:h.getIsInstanced()?is.Instance:is.Vertex,attributes:[]};n.push(e),s=e.attributes,d&&(c=0,u=null)}s.push({shaderLocation:a,offset:c,format:co._GetVertexInputDescriptorFormat(h)}),r=u}return n}_createRenderPipeline(e,t,i){var r,s,n;let a;let o=e._pipelineContext,l=this._getVertexInputDescriptor(e),h=this._createPipelineLayout(o),u=[],c=this._getAphaBlendState(),d=this._getColorBlendState();if(this._mrtAttachments1>0)for(let e=0;e<this._mrtFormats.length;++e){let t=this._mrtFormats[e];if(t){let i={format:t,writeMask:(this._mrtEnabledMask&1<<e)!=0?this._writeMask:0};c&&d&&(i.blend={alpha:c,color:d}),u.push(i)}else u.push(null)}else if(this._webgpuColorFormat[0]){let e={format:this._webgpuColorFormat[0],writeMask:this._writeMask};c&&d&&(e.blend={alpha:c,color:d}),u.push(e)}else u.push(null);let p={compare:co._GetCompareFunction(this._stencilEnabled?this._stencilFrontCompare:7),depthFailOp:co._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontDepthFailOp:1),failOp:co._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontFailOp:1),passOp:co._GetStencilOpFunction(this._stencilEnabled?this._stencilFrontPassOp:1)};(t===t5.LineStrip||t===t5.TriangleStrip)&&(a=!this._indexBuffer||this._indexBuffer.is32Bits?ii.Uint32:ii.Uint16);let _=!!this._webgpuDepthStencilFormat&&u8.HasStencilAspect(this._webgpuDepthStencilFormat);return this._device.createRenderPipeline({label:`RenderPipeline_${null!==(s=null===(r=u[0])||void 0===r?void 0:r.format)&&void 0!==s?s:"nooutput"}_${null!==(n=this._webgpuDepthStencilFormat)&&void 0!==n?n:"nodepth"}_samples${i}_textureState${this._textureState}`,layout:h,vertex:{module:o.stages.vertexStage.module,entryPoint:o.stages.vertexStage.entryPoint,buffers:l},primitive:{topology:t,stripIndexFormat:a,frontFace:1===this._frontFace?t6.CCW:t6.CW,cullMode:this._cullEnabled?2===this._cullFace?t8.Front:t8.Back:t8.None},fragment:o.stages.fragmentStage?{module:o.stages.fragmentStage.module,entryPoint:o.stages.fragmentStage.entryPoint,targets:u}:void 0,multisample:{count:i},depthStencil:void 0===this._webgpuDepthStencilFormat?void 0:{depthWriteEnabled:this._depthWriteEnabled,depthCompare:this._depthTestEnabled?co._GetCompareFunction(this._depthCompare):t$.Always,format:this._webgpuDepthStencilFormat,stencilFront:this._stencilEnabled&&_?p:void 0,stencilBack:this._stencilEnabled&&_?p:void 0,stencilReadMask:this._stencilEnabled&&_?this._stencilReadMask:void 0,stencilWriteMask:this._stencilEnabled&&_?this._stencilWriteMask:void 0,depthBias:this._depthBias,depthBiasClamp:this._depthBiasClamp,depthBiasSlopeScale:this._depthBiasSlopeScale}})}}co.NumCacheHitWithoutHash=0,co.NumCacheHitWithHash=0,co.NumCacheMiss=0,co.NumPipelineCreationLastFrame=0,co._NumPipelineCreationCurrentFrame=0;class cl{constructor(){this.values={}}count(){let e=0,t=this.pipeline?1:0;for(let i in this.values){let r=this.values[i],[s,n]=r.count();e+=s,t+=n,e++}return[e,t]}}class ch extends co{static GetNodeCounts(){let e=ch._Cache.count();return{nodeCount:e[0],pipelineCount:e[1]}}static _GetPipelines(e,t,i,r){if(e.pipeline){let e=i.slice();e.length=r,t.push(e)}for(let s in e.values){let n=e.values[s];i[r]=parseInt(s),ch._GetPipelines(n,t,i,r+1)}}static GetPipelines(){let e=[];return ch._GetPipelines(ch._Cache,e,[],0),e}constructor(e,t,i){super(e,t,i),this._nodeStack=[],this._nodeStack[0]=ch._Cache}_getRenderPipeline(e){let t=this._nodeStack[this._stateDirtyLowestIndex];for(let e=this._stateDirtyLowestIndex;e<this._statesLength;++e){let i=t.values[this._states[e]];i||(i=new cl,t.values[this._states[e]]=i),t=i,this._nodeStack[e+1]=t}e.token=t,e.pipeline=t.pipeline}_setRenderPipeline(e){e.token.pipeline=e.pipeline}}ch._Cache=new cl;var cu=i(3076);class cc extends cu.C{constructor(e){super(!1),this._cache=e,this.reset()}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._cache.setStencilCompare(e))}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._cache.setStencilReadMask(e))}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._cache.setStencilFailOp(e))}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._cache.setStencilDepthFailOp(e))}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._cache.setStencilPassOp(e))}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._cache.setStencilWriteMask(e))}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._cache.setStencilEnabled(e))}reset(){super.reset(),this._cache.resetStencilState()}apply(){var e;let t=null===(e=this.stencilMaterial)||void 0===e?void 0:e.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.enabled&&(this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask)}}var cd=i(3430);class cp extends cd.k{constructor(e){super(!1),this._cache=e,this.reset()}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0,this._cache.setDepthBiasSlopeScale(e))}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0,this._cache.setDepthBias(e))}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0,this._cache.setCullFace(null!=e?e:1))}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0,this._cache.setCullEnabled(!!e))}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0,this._cache.setDepthCompare(e))}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0,this._cache.setDepthWriteEnabled(e))}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0,this._cache.setDepthTestEnabled(e))}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0,this._cache.setFrontFace(null!=e?e:2))}reset(){super.reset(),this._cache.resetDepthCullingState()}apply(){}}class c_{static IsExternalTexture(e){return void 0!==e.underlyingResource}getClassName(){return"ExternalTexture"}get underlyingResource(){return this._video}constructor(e){this.useMipMaps=!1,this.type=16,this._video=e,this.uniqueId=sT.l._Counter++}isReady(){return this._video.readyState>=this._video.HAVE_CURRENT_DATA}dispose(){}}class cf{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatTextures(){return this._numFloatTextures>0}constructor(){this.uniqueId=cf._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],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?cs.GetSamplerHashCode(t):0;let s=r!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var i,r,s;let n=this.textures[e],a=-1;n?a=null!==(r=null===(i=n.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==r?r:-1:this.textures[e]=n={texture:t,isFloatTexture:!1,isExternalTexture:!1},n.isExternalTexture&&this._numExternalTextures--,n.isFloatTexture&&this._numFloatTextures--,t?(n.isFloatTexture=1===t.type,n.isExternalTexture=c_.IsExternalTexture(t),n.isFloatTexture&&this._numFloatTextures++,n.isExternalTexture&&this._numExternalTextures++):(n.isFloatTexture=!1,n.isExternalTexture=!1),n.texture=t;let o=a!==(null!==(s=null==t?void 0:t.uniqueId)&&void 0!==s?s:-1);o&&this.updateId++,this.isDirty||(this.isDirty=o)}}cf._Counter=0;class cm{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,tk.CopyDst|tk.Indirect|tk.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=cm._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}}cm._Counter=0;class cg{constructor(){this.values={}}}class cv{static get Statistics(){return{totalCreated:cv.NumBindGroupsCreatedTotal,lastFrameCreated:cv.NumBindGroupsCreatedLastFrame,lookupLastFrame:cv.NumBindGroupsLookupLastFrame,noLookupLastFrame:cv.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){cv.NumBindGroupsCreatedLastFrame=cv._NumBindGroupsCreatedCurrentFrame,cv.NumBindGroupsLookupLastFrame=cv._NumBindGroupsLookupCurrentFrame,cv.NumBindGroupsNoLookupLastFrame=cv._NumBindGroupsNoLookupCurrentFrame,cv._NumBindGroupsCreatedCurrentFrame=0,cv._NumBindGroupsLookupCurrentFrame=0,cv._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var r,s,n,a,o,l,h,u,c,d;let p;let _=cv._Cache,f=this.disabled||i.forceBindGroupCreation;if(!f){if(!t.isDirty(i.updateId)&&!i.isDirty)return cv._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(let i of e.shaderProcessingContext.bufferNames){let e=null!==(s=null===(r=t.buffers[i])||void 0===r?void 0:r.uniqueId)&&void 0!==s?s:0,n=_.values[e];n||(n=new cg,_.values[e]=n),_=n}for(let t of e.shaderProcessingContext.samplerNames){let e=null!==(a=null===(n=i.samplers[t])||void 0===n?void 0:n.hashCode)&&void 0!==a?a:0,r=_.values[e];r||(r=new cg,_.values[e]=r),_=r}for(let t of e.shaderProcessingContext.textureNames){let e=null!==(h=null===(l=null===(o=i.textures[t])||void 0===o?void 0:o.texture)||void 0===l?void 0:l.uniqueId)&&void 0!==h?h:0,r=_.values[e];r||(r=new cg,_.values[e]=r),_=r}p=_.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,p)return t.bindGroups=p,cv._NumBindGroupsLookupCurrentFrame++,p;p=[],t.bindGroups=p,f||(_.bindGroups=p),cv.NumBindGroupsCreatedTotal++,cv._NumBindGroupsCreatedCurrentFrame++;let m=e.bindGroupLayouts[i.textureState];for(let r=0;r<e.shaderProcessingContext.bindGroupLayoutEntries.length;r++){let s=e.shaderProcessingContext.bindGroupLayoutEntries[r],n=e.shaderProcessingContext.bindGroupEntries[r];for(let a=0;a<s.length;a++){let s=e.shaderProcessingContext.bindGroupLayoutEntries[r][a],o=e.shaderProcessingContext.bindGroupLayoutEntryInfo[r][s.binding],l=null!==(u=o.nameInArrayOfTexture)&&void 0!==u?u:o.name;if(s.sampler){let e=i.samplers[l];if(e){let t=e.sampler;if(!t){this._engine.dbgSanityChecks&&ru.Y.Error(`Trying to bind a null sampler! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=this._cacheSampler.getSampler(t,!1,e.hashCode)}else ru.Y.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(s.texture||s.storageTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){ru.Y.Error(`Trying to bind a null texture! entry=${JSON.stringify(s)}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||s.texture&&!t.view||s.storageTexture&&!t.viewForWriting)){ru.Y.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, isReady=${null===(c=e.texture)||void 0===c?void 0:c.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=s.storageTexture?t.viewForWriting:t.view}else ru.Y.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(s.externalTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){ru.Y.Error(`Trying to bind a null external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){ru.Y.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"<no dump>":t)}, isReady=${null===(d=e.texture)||void 0===d?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=this._device.importExternalTexture({source:t})}else ru.Y.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"<no dump>":t)}`,50)}else if(s.buffer){let e=t.buffers[l];if(e){let t=e.underlyingResource;n[a].resource.buffer=t,n[a].resource.size=e.capacity}else ru.Y.Error(`Can't find buffer "${l}". entry=${JSON.stringify(s)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}let a=m[r];p[r]=this._device.createBindGroup({layout:a,entries:n})}return p}}cv.NumBindGroupsCreatedTotal=0,cv.NumBindGroupsCreatedLastFrame=0,cv.NumBindGroupsLookupLastFrame=0,cv.NumBindGroupsNoLookupLastFrame=0,cv._Cache=new cg,cv._NumBindGroupsCreatedCurrentFrame=0,cv._NumBindGroupsLookupCurrentFrame=0,cv._NumBindGroupsNoLookupCurrentFrame=0;let cT=`uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0), -vec2(1.0,1.0), -vec2(-1.0,-1.0), -vec2(1.0,-1.0)}; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -gl_Position=vec4(pos[gl_VertexID],depthValue,1.0); -#define CUSTOM_VERTEX_MAIN_END -} -`;no.v.ShadersStore.clearQuadVertexShader=cT;let cx=`uniform vec4 color;void main() {gl_FragColor=color;} -`;no.v.ShadersStore.clearQuadPixelShader=cx;class cS{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 ch(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,r,s=1){var n,a;let o,l;let h=null,u=!!this._engine._currentRenderTarget;if(e)o=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t<this._cacheRenderPipeline.colorFormats.length;++t)this._keyTemp[e++]=u6[null!==(n=this._cacheRenderPipeline.colorFormats[t])&&void 0!==n?n:""];let c=u6[null!==(a=this._depthTextureFormat)&&void 0!==a?a:0];if(this._keyTemp[e]=(t?t.r+256*t.g+65536*t.b+16777216*t.a:0)+(i?4294967296:0)+(r?8589934592:0)+(this._engine.useReverseDepthBuffer?17179869184:0)+(u?34359738368:0)+(s>1?68719476736:0)+137438953472*c,l=this._keyTemp.join("_"),h=this._bundleCache[l])return h;o=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:s})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&u8.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);let c=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),d=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),d.uniformBuffer.update();let p=u?this._engine._ubInvertY:this._engine._ubDontInvertY,_=d.uniformBuffer.getBuffer(),f=_.uniqueId+"-"+p.uniqueId,m=this._bindGroups[f];if(!m){let e=d.bindGroupLayouts[0];(m=this._bindGroups[f]=[]).push(this._device.createBindGroup({layout:e[0],entries:[]})),uR._SimplifiedKnownBindings||m.push(this._device.createBindGroup({layout:e[1],entries:[]})),m.push(this._device.createBindGroup({layout:e[uR._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:p.underlyingResource,size:p.capacity}},{binding:1,resource:{buffer:_.underlyingResource,size:_.capacity}}]}))}o.setPipeline(c);for(let e=0;e<m.length;++e)o.setBindGroup(e,m[e]);return o.draw(4,1,0,0),e||(h=o.finish(),this._bundleCache[l]=h),h}}class cE{constructor(e,t,i,r){this.x=Math.floor(e),this.y=Math.floor(t),this.w=Math.floor(i),this.h=Math.floor(r)}run(e){e.setViewport(this.x,this.y,this.w,this.h,0,1)}clone(){return new cE(this.x,this.y,this.w,this.h)}}class cC{constructor(e,t,i,r){this.x=e,this.y=t,this.w=i,this.h=r}run(e){e.setScissorRect(this.x,this.y,this.w,this.h)}clone(){return new cC(this.x,this.y,this.w,this.h)}}class cb{constructor(e){this.ref=e}run(e){e.setStencilReference(this.ref)}clone(){return new cb(this.ref)}}class cy{constructor(e){this.color=e}run(e){e.setBlendConstant(this.color)}clone(){return new cy(this.color)}}class cA{constructor(e){this.query=e}run(e){e.beginOcclusionQuery(this.query)}clone(){return new cA(this.query)}}class cR{constructor(){}run(e){e.endOcclusionQuery()}clone(){return new cR}}class cP{constructor(){this.bundles=[]}run(e){e.executeBundles(this.bundles)}clone(){let e=new cP;return e.bundles=this.bundles,e}}class cI{constructor(e){this.numDrawCalls=0,this._device=e,this._list=Array(10),this._listLength=0}addBundle(e){if(!this._currentItemIsBundle){let e=new cP;this._list[this._listLength++]=e,this._currentBundleList=e.bundles,this._currentItemIsBundle=!0}e&&this._currentBundleList.push(e)}_finishBundle(){this._currentItemIsBundle&&this._bundleEncoder&&(this._currentBundleList.push(this._bundleEncoder.finish()),this._bundleEncoder=void 0,this._currentItemIsBundle=!1)}addItem(e){this._finishBundle(),this._list[this._listLength++]=e,this._currentItemIsBundle=!1}getBundleEncoder(e,t,i){return this._currentItemIsBundle||(this.addBundle(),this._bundleEncoder=this._device.createRenderBundleEncoder({colorFormats:e,depthStencilFormat:t,sampleCount:i})),this._bundleEncoder}close(){this._finishBundle()}run(e){this.close();for(let t=0;t<this._listLength;++t)this._list[t].run(e)}reset(){this._listLength=0,this._currentItemIsBundle=!1,this.numDrawCalls=0}clone(){this.close();let e=new cI(this._device);e._list=Array(this._listLength),e._listLength=this._listLength,e.numDrawCalls=this.numDrawCalls;for(let t=0;t<this._listLength;++t)e._list[t]=this._list[t].clone();return e}}class cM{get querySet(){return this._querySet}constructor(e,t,i,r,s=!0){this._dstBuffers=[],this._device=i,this._bufferManager=r,this._count=e,this._canUseMultipleBuffers=s,this._querySet=i.createQuerySet({type:t,count:e}),this._queryBuffer=r.createRawBuffer(8*e,tk.QueryResolve|tk.CopySrc),s||this._dstBuffers.push(this._bufferManager.createRawBuffer(8*this._count,tk.MapRead|tk.CopyDst))}_getBuffer(e,t){let i;if(!this._canUseMultipleBuffers&&0===this._dstBuffers.length)return null;let r=this._device.createCommandEncoder();return 0===this._dstBuffers.length?i=this._bufferManager.createRawBuffer(8*this._count,tk.MapRead|tk.CopyDst):(i=this._dstBuffers[this._dstBuffers.length-1],this._dstBuffers.length--),r.resolveQuerySet(this._querySet,e,t,this._queryBuffer,0),r.copyBufferToBuffer(this._queryBuffer,0,i,0,8*t),this._device.queue.submit([r.finish()]),i}async readValues(e=0,t=1){let i=this._getBuffer(e,t);if(null===i)return null;await i.mapAsync(tG.Read);let r=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,r}async readValue(e=0){let t=this._getBuffer(e,1);if(null===t)return null;await t.mapAsync(tG.Read);let i=new BigUint64Array(t.getMappedRange()),r=Number(i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r}async readTwoValuesAndSubtract(e=0){let t=this._getBuffer(e,2);if(null===t)return null;await t.mapAsync(tG.Read);let i=new BigUint64Array(t.getMappedRange()),r=Number(i[1]-i[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,r}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e<this._dstBuffers.length;++e)this._bufferManager.releaseBuffer(this._dstBuffers[e])}}class cD{get gpuFrameTimeCounter(){return this._gpuFrameTimeCounter}constructor(e,t){this._enabled=!1,this._gpuFrameTimeCounter=new hX.z,this._measureDurationState=0,this._device=e,this._bufferManager=t}get enable(){return this._enabled}set enable(e){this._enabled!==e&&(this._enabled=e,this._measureDurationState=0,e?this._measureDuration=new cO(this._device,this._bufferManager):this._measureDuration.dispose())}startFrame(e){this._enabled&&0===this._measureDurationState&&(this._measureDuration.start(e),this._measureDurationState=1)}endFrame(e){1===this._measureDurationState&&(this._measureDurationState=2,this._measureDuration.stop(e).then(e=>{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0}))}}class cO{constructor(e,t){this._querySet=new cM(2,iu.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 cN{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}get canBeginQuery(){let e=this._engine._getCurrentRenderPassIndex();switch(e){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,r=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(r)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();let 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.length}getQueryResult(e){var t,i;return Number(null!==(i=null===(t=this._lastBuffer)||void 0===t?void 0:t[e])&&void 0!==i?i:-1)}_retrieveQueryBuffer(){this._lastBuffer&&this._frameLastBuffer===this._engine.frameId||this._frameLastBuffer===this._engine.frameId||(this._frameLastBuffer=this._engine.frameId,this._querySet.readValues(0,this._currentTotalIndices).then(e=>{this._lastBuffer=e}))}_allocateNewIndices(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;t<e;++t)this._availableIndices.push(this._currentTotalIndices+t);this._currentTotalIndices+=e,this._querySet=new cM(this._currentTotalIndices,iu.Occlusion,this._device,this._bufferManager,!1)}_delayQuerySetDispose(){let e=this._querySet;e&&setTimeout(()=>e.dispose,1e3)}dispose(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0}}class cF{async initTwgsl(e){return cF._twgsl?void 0:(e=e||{},(e=Object.assign(Object.assign({},cF._TWgslDefaultOptions),e)).twgsl)?(cF._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&((0,r9.CG)()?await rZ.w1.LoadScriptAsync(e.jsPath):importScripts(e.jsPath)),self.twgsl)?(cF._twgsl=await self.twgsl(e.wasmPath),Promise.resolve()):Promise.reject("twgsl is not available.")}convertSpirV2WGSL(e,t=!1){let i=cF._twgsl.convertSpirV2WGSL(e);return cF.ShowWGSLShaderCode&&(console.log(i),console.log("***********************************************")),cF.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}cF._TWgslDefaultOptions={jsPath:"https://preview.babylonjs.com/twgsl/twgsl.js",wasmPath:"https://preview.babylonjs.com/twgsl/twgsl.wasm"},cF.ShowWGSLShaderCode=!1,cF.DisableUniformityAnalysis=!1,cF._twgsl=null;class cL{constructor(e,t,i,r){this._record=!1,this._play=!1,this._mainPassBundleList=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i,this._bundleListRenderTarget=r}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,r,s,n;if(this._play)null===(r=null===(i=t._bundleLists)||void 0===i?void 0:i[t._currentLayer])||void 0===r||r.run(e),1===this._mode&&this._engine._reportDrawCall(null===(n=null===(s=t._bundleLists)||void 0===s?void 0:s[t._currentLayer])||void 0===n?void 0:n.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<this._mainPassBundleList.length;++t)this._mainPassBundleList[t].run(e),1===this._mode&&this._engine._reportDrawCall(this._mainPassBundleList[t].numDrawCalls)}reset(){this.enabled=!1,this.enabled=!0}}let cw=`attribute position: vec2<f32>;uniform scale: vec2<f32>;varying vUV: vec2<f32>;const madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -@vertex -fn main(input : VertexInputs)->FragmentInputs { -#define CUSTOM_VERTEX_MAIN_BEGIN -vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -} -`;no.v.ShadersStoreWGSL.postprocessVertexShader=cw;let cB={label:"TextureView_SwapChain_ResolveTarget",dimension:tz.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},cU={label:"TextureView_SwapChain",dimension:tz.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},cV="/* disable_uniformity_analysis */",ck=new rs.HE;class cG extends r7.D{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return ru.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(){let e=this.name+this.version;return e}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={}){let i=new cG(e,t);return new Promise(e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>e(i))})}constructor(e,t={}){var i,r;if(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 ce,this._rttRenderPassWrapper=new ce,this._pendingDebugCommands=[],this._onAfterUnbindFrameBufferObservable=new ri.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!==(r=t.enableGPUDebugMarkers)&&void 0!==r&&r,ru.Y.Log(`Babylon.js v${r7.D.Version} - ${this.description} engine`),!navigator.gpu){ru.Y.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(e),this._shaderProcessor=new uP,this._shaderProcessorWGSL=new uj}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=cG.UseTWGSL?new cF: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 ru.Y.Error("Can not initialize twgsl!"),ru.Y.Error(e),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},e=>{throw ru.Y.Error("Can not initialize glslang!"),ru.Y.Error(e),Error("WebGPU initializations stopped.")}).then(e=>{var t,i,r;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});let s=null!==(i=this._options.deviceDescriptor)&&void 0!==i?i:{},n=null!==(r=null==s?void 0:s.requiredFeatures)&&void 0!==r?r:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(n){let e=[];for(let t of n)-1!==this._adapterSupportedExtensions.indexOf(t)&&e.push(t);s.requiredFeatures=e}if(this._options.setMaximumLimits&&!s.requiredLimits)for(let e in s.requiredLimits={},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 r=-1;this._device.addEventListener("uncapturederror",e=>{++r<this.numMaxUncapturedErrors?ru.Y.Warn(`WebGPU uncaptured error (${r+1}): ${e.error} - ${e.error.message}`):r++===this.numMaxUncapturedErrors&&ru.Y.Warn(`WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`)}),this._doNotHandleContextLost||null===(i=this._device.lost)||void 0===i||i.then(e=>{this._isDisposed||(this._contextWasLost=!0,ru.Y.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(this.initAsync.bind(this)))})},e=>{ru.Y.Error("Could not retrieve a WebGPU device."),ru.Y.Error(e)}).then(()=>{this._bufferManager=new u9(this._device),this._textureHelper=new u8(this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new cs(this._device),this._cacheBindGroups=new cv(this._device,this._cacheSampler,this),this._timestampQuery=new cD(this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new cN(this,this._device,this._bufferManager):void 0,this._bundleList=new cI(this._device),this._bundleListRenderTarget=new cI(this._device),this._snapshotRendering=new cL(this,this._snapshotRenderingMode,this._bundleList,this._bundleListRenderTarget),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),tk.Uniform|tk.CopyDst),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),tk.Uniform|tk.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 rQ.o(this,[0],"",!1,!1,1,!1,0,1),this._initializeLimits(),this._cacheRenderPipeline=new ch(this._device,this._emptyVertexBuffer,!this._caps.textureFloatLinearFiltering),this._depthCullingState=new cp(this._cacheRenderPipeline),this._stencilStateComposer=new cc(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 cS(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=>{ru.Y.Error("Can not create WebGPU Device and/or context."),ru.Y.Error(e),console.trace&&console.trace()})}_initGlslang(e){return(e=e||{},(e=Object.assign(Object.assign({},cG._GLSLslangDefaultOptions),e)).glslang)?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?(0,r9.CG)()?rZ.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(tU.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(tU.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(tU.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(tU.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(tU.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(tU.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 uq],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat}_initializeMainAttachments(){let e;if(!this._bufferManager)return;this.flushFramebuffer(!1),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};let t=new Float32Array([this.getRenderHeight(!0)]);if(this._bufferManager.setSubData(this._ubInvertY,4,t),this._bufferManager.setSubData(this._ubDontInvertY,4,t),this._options.antialias){let t={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:tz.E2d,format:this._options.swapChainFormat,usage:tW.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(t),e=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:tz.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new rs.HE(0,0,0,1),loadOp:il.Clear,storeOp:ih.Store}]}else e=[{view:void 0,clearValue:new rs.HE(0,0,0,1),loadOp:il.Clear,storeOp:ih.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?tY.Depth24PlusStencil8:tY.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);let i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:tz.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:tW.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);let r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:tz.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:il.Clear,depthStoreOp:ih.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?il.Clear:void 0,stencilStoreOp:this.isStencilEnable?ih.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={colorAttachments:e,depthStencilAttachment:r}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:tW.RenderAttachment|tW.CopySrc,alphaMode:this.premultipliedAlpha?ic.Premultiplied:ic.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<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - setSize called -",e,t)),this._initializeMainAttachments(),this.snapshotRendering&&this.snapshotRenderingReset(),!0)}_getShaderProcessor(e){return e===nd.x.WGSL?this._shaderProcessorWGSL:this._shaderProcessor}_getShaderProcessingContext(e){return new uR(e)}applyStates(){this._stencilStateComposer.apply(),this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend)}wipeCaches(e){(!this.preventCacheWipeBetweenFrames||e)&&(this._forceEnableEffect=!0,this._currentIndexBuffer=null,this._currentOverrideVertexBuffers=null,this._cacheRenderPipeline.setBuffers(null,null,null),e&&(this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=515,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters),this._cacheRenderPipeline.setAlphaBlendEnabled(!1),this.setColorWrite(!0)),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}setColorWrite(e){this._colorWriteLocal=e,this._cacheRenderPipeline.setWriteMask(e?15:0)}getColorWrite(){return this._colorWriteLocal}_resetCurrentViewport(e){this._viewportsCurrent[e].x=0,this._viewportsCurrent[e].y=0,this._viewportsCurrent[e].w=0,this._viewportsCurrent[e].h=0}_mustUpdateViewport(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._viewportCached.x,r=this._viewportCached.y,s=this._viewportCached.z,n=this._viewportCached.w,a=this._viewportsCurrent[t].x!==i||this._viewportsCurrent[t].y!==r||this._viewportsCurrent[t].w!==s||this._viewportsCurrent[t].h!==n;return a&&(this._viewportsCurrent[t].x=this._viewportCached.x,this._viewportsCurrent[t].y=this._viewportCached.y,this._viewportsCurrent[t].w=this._viewportCached.z,this._viewportsCurrent[t].h=this._viewportCached.w),a}_applyViewport(e){let t=Math.floor(this._viewportCached.y),i=Math.floor(this._viewportCached.w);this._currentRenderTarget||(t=this.getRenderHeight(!0)-t-i),e.setViewport(Math.floor(this._viewportCached.x),t,Math.floor(this._viewportCached.z),i,0,1),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - viewport applied - (",this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w,") current pass is main pass="+(e===this._mainRenderPassWrapper.renderPass)))}_viewport(e,t,i,r){this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r}_resetCurrentScissor(e){this._scissorsCurrent[e].x=0,this._scissorsCurrent[e].y=0,this._scissorsCurrent[e].w=0,this._scissorsCurrent[e].h=0}_mustUpdateScissor(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._scissorCached.x,r=this._scissorCached.y,s=this._scissorCached.z,n=this._scissorCached.w,a=this._scissorsCurrent[t].x!==i||this._scissorsCurrent[t].y!==r||this._scissorsCurrent[t].w!==s||this._scissorsCurrent[t].h!==n;return a&&(this._scissorsCurrent[t].x=this._scissorCached.x,this._scissorsCurrent[t].y=this._scissorCached.y,this._scissorsCurrent[t].w=this._scissorCached.z,this._scissorsCurrent[t].h=this._scissorCached.w),a}_applyScissor(e){e.setScissorRect(this._scissorCached.x,this._currentRenderTarget?this._scissorCached.y:this.getRenderHeight()-this._scissorCached.w-this._scissorCached.y,this._scissorCached.z,this._scissorCached.w),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - scissor applied - (",this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w,") current pass is main pass="+(e===this._mainRenderPassWrapper.renderPass)))}_scissorIsActive(){return 0!==this._scissorCached.x||0!==this._scissorCached.y||0!==this._scissorCached.z||0!==this._scissorCached.w}enableScissor(e,t,i,r){this._scissorCached.x=e,this._scissorCached.y=t,this._scissorCached.z=i,this._scissorCached.w=r}disableScissor(){this._scissorCached.x=0,this._scissorCached.y=0,this._scissorCached.z=0,this._scissorCached.w=0,this._resetCurrentScissor(0),this._resetCurrentScissor(1)}_resetCurrentStencilRef(e){this._stencilRefsCurrent[e]=-1}_mustUpdateStencilRef(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._stencilStateComposer.funcRef!==this._stencilRefsCurrent[t];return i&&(this._stencilRefsCurrent[t]=this._stencilStateComposer.funcRef),i}_applyStencilRef(e){var t;e.setStencilReference(null!==(t=this._stencilStateComposer.funcRef)&&void 0!==t?t:0)}_resetCurrentColorBlend(e){this._blendColorsCurrent[e][0]=this._blendColorsCurrent[e][1]=this._blendColorsCurrent[e][2]=this._blendColorsCurrent[e][3]=null}_mustUpdateBlendColor(e){let t=e===this._mainRenderPassWrapper.renderPass?0:1,i=this._alphaState._blendConstants,r=i[0]!==this._blendColorsCurrent[t][0]||i[1]!==this._blendColorsCurrent[t][1]||i[2]!==this._blendColorsCurrent[t][2]||i[3]!==this._blendColorsCurrent[t][3];return r&&(this._blendColorsCurrent[t][0]=i[0],this._blendColorsCurrent[t][1]=i[1],this._blendColorsCurrent[t][2]=i[2],this._blendColorsCurrent[t][3]=i[3]),r}_applyBlendColor(e){e.setBlendConstant(this._alphaState._blendConstants)}clear(e,t,i,r=!1){e&&void 0===e.a&&(e.a=1);let s=this._scissorIsActive();this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - clear called - backBuffer=",t," depth=",i," stencil=",r," scissor is active=",s)),this._currentRenderTarget?s?(this._rttRenderPassWrapper.renderPass||this._startRenderTargetRenderPass(this._currentRenderTarget,!1,t?e:null,i,r),this.compatibilityMode?this._applyScissor(this._currentRenderPass):this._bundleListRenderTarget.addItem(new cC(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),this._clearFullQuad(t?e:null,i,r)):(this._currentRenderPass&&this._endRenderTargetRenderPass(),this._startRenderTargetRenderPass(this._currentRenderTarget,!0,t?e:null,i,r)):(this._mainRenderPassWrapper.renderPass&&s||this._startMainRenderPass(!s,t?e:null,i,r),s&&(this.compatibilityMode?this._applyScissor(this._currentRenderPass):this._bundleList.addItem(new cC(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),this._clearFullQuad(t?e:null,i,r)))}_clearFullQuad(e,t,i){var r,s,n;let a=this.compatibilityMode?this._getCurrentRenderPass():null,o=this._getCurrentRenderPassIndex(),l=0===o?this._bundleList:this._bundleListRenderTarget;this._clearQuad.setColorFormat(this._colorFormat),this._clearQuad.setDepthStencilFormat(this._depthTextureFormat),this._clearQuad.setMRTAttachments(null!==(r=this._cacheRenderPipeline.mrtAttachments)&&void 0!==r?r:[],null!==(s=this._cacheRenderPipeline.mrtTextureArray)&&void 0!==s?s:[],this._cacheRenderPipeline.mrtTextureCount),this.compatibilityMode?a.setStencilReference(this._clearStencilValue):l.addItem(new cb(this._clearStencilValue));let h=this._clearQuad.clear(a,e,t,i,this.currentSampleCount);this.compatibilityMode?this._applyStencilRef(a):(l.addBundle(h),l.addItem(new cb(null!==(n=this._stencilStateComposer.funcRef)&&void 0!==n?n:0)),this._reportDrawCall())}createVertexBuffer(e){let t;t=e instanceof Array?new Float32Array(e):e instanceof ArrayBuffer?new Uint8Array(e):e;let i=this._bufferManager.createBuffer(t,tk.Vertex|tk.CopyDst);return i}createDynamicVertexBuffer(e){return this.createVertexBuffer(e)}createIndexBuffer(e){let t,i=!0;e instanceof Uint32Array||e instanceof Int32Array?t=e:e instanceof Uint16Array?(t=e,i=!1):e.length>65535?t=new Uint32Array(e):(t=new Uint16Array(e),i=!1);let r=this._bufferManager.createBuffer(t,tk.Index|tk.CopyDst);return r.is32Bits=i,r}_createBuffer(e,t){let i;i=e instanceof Array?new Float32Array(e):e instanceof ArrayBuffer?new Uint8Array(e):e;let r=0;return 1&t&&(r|=tk.CopySrc),2&t&&(r|=tk.CopyDst),4&t&&(r|=tk.Uniform),8&t&&(r|=tk.Vertex),16&t&&(r|=tk.Index),32&t&&(r|=tk.Storage),this._bufferManager.createBuffer(i,r)}bindBuffersDirectly(){throw"Not implemented on WebGPU"}updateAndBindInstancesBuffer(){throw"Not implemented on WebGPU"}bindBuffers(e,t,i,r){this._currentIndexBuffer=t,this._currentOverrideVertexBuffers=null!=r?r:null,this._cacheRenderPipeline.setBuffers(e,t,this._currentOverrideVertexBuffers)}_releaseBuffer(e){return this._bufferManager.releaseBuffer(e)}createEffect(e,t,i,r,s,n,a,o,l,h=nd.x.GLSL){var u;let c=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,d=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,p=this._getGlobalDefines(),_=null!==(u=null!=s?s:t.defines)&&void 0!==u?u:"";p&&(_+="\n"+p);let f=c+"+"+d+"@"+_;if(this._compiledEffects[f]){let e=this._compiledEffects[f];return a&&e.isReady()&&a(e),e}let m=new sj.Q(e,t,i,r,this,s,n,a,o,l,f,h);return this._compiledEffects[f]=m,m}_compileRawShaderToSpirV(e,t){return this._glslang.compileGLSL(e,t)}_compileShaderToSpirV(e,t,i,r){return this._compileRawShaderToSpirV(r+(i?i+"\n":"")+e,t)}_getWGSLShader(e,t,i){return(i=i?"//"+i.split("\n").join("\n//")+"\n":"")+e}_createPipelineStageDescriptor(e,t,i,r,s){return this._tintWASM&&i===nd.x.GLSL&&(e=this._tintWASM.convertSpirV2WGSL(e,r),t=this._tintWASM.convertSpirV2WGSL(t,s)),{vertexStage:{module:this._device.createShaderModule({code:e}),entryPoint:"main"},fragmentStage:{module:this._device.createShaderModule({code:t}),entryPoint:"main"}}}_compileRawPipelineStageDescriptor(e,t,i){let r=e.indexOf(cV)>=0,s=t.indexOf(cV)>=0,n=i===nd.x.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,a=i===nd.x.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,a,i,r,s)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=e.indexOf(cV)>=0,n=t.indexOf(cV)>=0,a="#version 450\n",o=r===nd.x.GLSL?this._compileShaderToSpirV(e,"vertex",i,a):this._getWGSLShader(e,"vertex",i),l=r===nd.x.GLSL?this._compileShaderToSpirV(t,"fragment",i,a):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(o,l,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){let t=new up(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new uy(e,this)}createMaterialContext(){return new cf}createDrawContext(){return new cm(this._bufferManager)}_preparePipelineContext(e,t,i,r,s,n,a,o){let l=e.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(o),console.log(t),console.log(i),console.log("***********************************************")),e.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:n},r?e.stages=this._compileRawPipelineStageDescriptor(t,i,l):e.stages=this._compilePipelineStageDescriptor(t,i,o,l)}getAttributes(e,t){let i=Array(t.length);for(let r=0;r<t.length;r++){let s=t[r],n=e.shaderProcessingContext.availableAttributes[s];void 0!==n&&(i[r]=n)}return i}enableEffect(e){if(!e)return;let t=!0;if(nc.q.IsWrapper(e)){if(e.effect&&(e.effect!==this._currentEffect||e.materialContext!==this._currentMaterialContext||e.drawContext!==this._currentDrawContext||this._forceEnableEffect)){if(t=e.effect!==this._currentEffect,this._currentEffect=e.effect,this._currentMaterialContext=e.materialContext,this._currentDrawContext=e.drawContext,this._counters.numEnableDrawWrapper++,!this._currentMaterialContext)throw console.error("drawWrapper=",e),"Invalid call to enableEffect: the materialContext property is empty!"}else{if(!e.effect&&this.dbgShowEmptyEnableEffectCalls)throw console.error("drawWrapper=",e),"Invalid call to enableEffect: the effect property is empty!";return}}else t=e!==this._currentEffect,this._currentEffect=e,this._currentMaterialContext=this._defaultMaterialContext,this._currentDrawContext=this._defaultDrawContext,this._counters.numEnableEffects++,this.dbgLogIfNotDrawWrapper&&ru.Y.Warn(`enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=${e.uniqueId}, effect.name=${e.name}, effect.name.vertex=${e.name.vertex}, effect.name.fragment=${e.name.fragment}`,10);this._stencilStateComposer.stencilMaterial=void 0,this._forceEnableEffect=!t&&!this._forceEnableEffect&&this._forceEnableEffect,t&&(this._currentEffect.onBind&&this._currentEffect.onBind(this._currentEffect),this._currentEffect._onBindObservable&&this._currentEffect._onBindObservable.notifyObservers(this._currentEffect))}_releaseEffect(e){this._compiledEffects[e._key]&&(delete this._compiledEffects[e._key],this._deletePipelineContext(e.getPipelineContext()))}releaseEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}_deletePipelineContext(e){e&&e.dispose()}get needPOTTextures(){return!1}_createHardwareTexture(){return new uq}_releaseTexture(e){let t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),this._textureHelper.releaseTexture(e)}_getRGBABufferInternalSizedFormat(){return 5}updateTextureComparisonFunction(e,t){e._comparisonFunction=t}_createInternalTexture(e,t,i=!0,r=sT.S.Unknown){var s,n,a;let o={};void 0!==t&&"object"==typeof t?(o.generateMipMaps=t.generateMipMaps,o.type=void 0===t.type?0:t.type,o.samplingMode=void 0===t.samplingMode?3:t.samplingMode,o.format=void 0===t.format?5:t.format,o.samples=null!==(s=t.samples)&&void 0!==s?s:1,o.creationFlags=null!==(n=t.creationFlags)&&void 0!==n?n:0,o.useSRGBBuffer=null!==(a=t.useSRGBBuffer)&&void 0!==a&&a,o.label=t.label):(o.generateMipMaps=t,o.type=0,o.samplingMode=3,o.format=5,o.samples=1,o.creationFlags=0,o.useSRGBBuffer=!1),(1!==o.type||this._caps.textureFloatLinearFiltering)&&(2!==o.type||this._caps.textureHalfFloatLinearFiltering)||(o.samplingMode=1),1!==o.type||this._caps.textureFloat||(o.type=0,ru.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let l=new sT.l(this,r),h=e.width||e,u=e.height||e,c=e.layers||0;return l.baseWidth=h,l.baseHeight=u,l.width=h,l.height=u,l.depth=c,l.isReady=!0,l.samples=o.samples,l.generateMipMaps=!!o.generateMipMaps,l.samplingMode=o.samplingMode,l.type=o.type,l.format=o.format,l.is2DArray=c>0,l._cachedWrapU=0,l._cachedWrapV=0,l._useSRGBBuffer=o.useSRGBBuffer,l.label=o.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,h,u,c||1,o.creationFlags),l}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_){return this._createTextureBase(e,t,i,r,s,n,a,(e,t,i,r,s,n,a,o)=>{var l;if(e.baseWidth=r.width,e.baseHeight=r.height,e.width=r.width,e.height=r.height,e.format=null!=h?h:-1,o(e.width,e.height,r,t,e,()=>{}),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)n||a||this._generateMipmaps(e,this._uploadEncoder);else{let t=this._textureHelper.createGPUTextureForInternalTexture(e,r.width,r.height,void 0,p);!u8.IsImageBitmap(r)||(this._textureHelper.updateTexture(r,e,r.width,r.height,e.depth,t.format,0,0,s,!1,0,0),n||a||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()},()=>!1,o,l,h,u,c,d,_)}wrapWebGPUTexture(e){let t=new uq(e),i=new sT.l(this,sT.S.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;if(e.generateMipMaps){let i=null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource;i||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e,e.source===sT.S.RenderTarget||e.source===sT.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,r=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===r)return;let s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,s)}_setInternalTexture(e,t,i){if(i=null!=i?i:e,this._currentEffect){let r=this._currentEffect._pipelineContext,s=r.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){let e=i+ub.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let e=0;e<i.length;e++)this._setTexture(-1,i[e],!0,!1,r+e.toString(),r)}_setTexture(e,t,i=!1,r=!1,s="",n){if(n=null!=n?n:s,this._currentEffect){if(!t)return this._currentMaterialContext.setTexture(s,null),!1;if(t.video)t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let e=null;if((e=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture)&&!e.isMultiview){if(e.isCube&&e._cachedCoordinatesMode!==t.coordinatesMode){e._cachedCoordinatesMode=t.coordinatesMode;let i=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=i,t.wrapV=i}e._cachedWrapU=t.wrapU,e._cachedWrapV=t.wrapV,e.is3D&&(e._cachedWrapR=t.wrapR),this._setAnisotropicLevel(0,e,t.anisotropicFilteringLevel)}this._setInternalTexture(s,e,n)}else this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - _setTexture called with a null _currentEffect! texture=",t));return!0}_setAnisotropicLevel(e,t,i){t._cachedAnisotropicFilteringLevel!==i&&(t._cachedAnisotropicFilteringLevel=Math.min(i,this._caps.maxAnisotropy))}_bindTexture(e,t,i){void 0!==e&&this._setInternalTexture(i,t)}generateMipmaps(e){this._generateMipmaps(e,this._renderTargetEncoder)}_generateMipmaps(e,t){let i=e._hardwareTexture;if(!i)return;t=null!=t?t:this._currentRenderTarget&&!this._currentRenderPass?this._renderTargetEncoder:this._currentRenderPass?this._uploadEncoder:this._renderEncoder;let r=e._hardwareTexture.format,s=u8.ComputeNumMipmapLevels(e.width,e.height);this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - generate mipmaps called - width=",e.width,"height=",e.height,"isCube=",e.isCube)),e.isCube?this._textureHelper.generateCubeMipmaps(i,r,s,t):this._textureHelper.generateMipmaps(i,r,s,0,t)}updateTextureData(e,t,i,r,s,n,a=0,o=0,l=!1){var h;let u=e._hardwareTexture;(null===(h=e._hardwareTexture)||void 0===h?void 0:h.underlyingResource)||(u=this._textureHelper.createGPUTextureForInternalTexture(e));let c=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(c,e,s,n,e.depth,u.format,a,o,e.invertY,!1,i,r),l&&this._generateMipmaps(e,this._renderTargetEncoder)}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,a=0){var o;let l=e._hardwareTexture;(null===(o=e._hardwareTexture)||void 0===o?void 0:o.underlyingResource)||(e.format=t,l=this._textureHelper.createGPUTextureForInternalTexture(e,i,r));let h=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);this._textureHelper.updateTexture(h,e,i,r,e.depth,l.format,n,a,!1,!1,0,0)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,n=!1){var a;let o=Math.round(Math.log(e.width)*Math.LOG2E),l=Math.round(Math.log(e.height)*Math.LOG2E),h=n?e.width:Math.pow(2,Math.max(o-r,0)),u=n?e.height:Math.pow(2,Math.max(l-r,0)),c=e._hardwareTexture;(null===(a=e._hardwareTexture)||void 0===a?void 0:a.underlyingResource)||(c=this._textureHelper.createGPUTextureForInternalTexture(e,h,u));let d=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(d,e,h,u,e.depth,c.format,i,r,e.invertY,!1,0,0)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){this._uploadDataToTextureDirectly(e,t,i,r)}_uploadImageToTexture(e,t,i=0,r=0){var s;let n=e._hardwareTexture;if((null===(s=e._hardwareTexture)||void 0===s?void 0:s.underlyingResource)||(n=this._textureHelper.createGPUTextureForInternalTexture(e)),t instanceof HTMLImageElement)throw"WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!";let a=Math.ceil(e.width/(1<<r)),o=Math.ceil(e.height/(1<<r));this._textureHelper.updateTexture(t,e,a,o,e.depth,n.format,i,r,e.invertY,!1,0,0)}readPixels(e,t,i,r,s=!0,n=!0){let a=this._rttRenderPassWrapper.renderPass?this._rttRenderPassWrapper:this._mainRenderPassWrapper,o=a.colorAttachmentGPUTextures[0];if(!o)return Promise.resolve(new Uint8Array(0));let l=o.underlyingResource,h=o.format;return l?(n&&this.flushFramebuffer(),this._textureHelper.readPixels(l,e,t,i,r,h)):Promise.resolve(new Uint8Array(0))}beginFrame(){super.beginFrame()}endFrame(){if(this._snapshotRendering.endFrame(this._mainRenderPassWrapper.renderPass),this._endMainRenderPass(),this._timestampQuery.endFrame(this._renderEncoder),this.flushFramebuffer(!1),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - counters")),this._textureHelper.destroyDeferredTextures(),this._bufferManager.destroyDeferredBuffers(),this._features._collectUbosUpdatedInFrame){if(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){let e=[];for(let t in r1.M._UpdatedUbosInFrame)e.push(t+":"+r1.M._UpdatedUbosInFrame[t]);console.log("frame #"+this._count+" - updated ubos -",e.join(", "))}r1.M._UpdatedUbosInFrame={}}this.countersLastFrame.numEnableEffects=this._counters.numEnableEffects,this.countersLastFrame.numEnableDrawWrapper=this._counters.numEnableDrawWrapper,this.countersLastFrame.numBundleCreationNonCompatMode=this._counters.numBundleCreationNonCompatMode,this.countersLastFrame.numBundleReuseNonCompatMode=this._counters.numBundleReuseNonCompatMode,this._counters.numEnableEffects=0,this._counters.numEnableDrawWrapper=0,this._counters.numBundleCreationNonCompatMode=0,this._counters.numBundleReuseNonCompatMode=0,this._cacheRenderPipeline.endFrame(),this._cacheBindGroups.endFrame(),this._pendingDebugCommands.length=0,super.endFrame(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),this._count<this.dbgVerboseLogsNumFrames&&console.log("%c frame #"+this._count+" - end","background: #ffff00"),this._count<this.dbgVerboseLogsNumFrames&&(this._count++,this._count!==this.dbgVerboseLogsNumFrames&&console.log("%c frame #"+this._count+" - begin","background: #ffff00")))}flushFramebuffer(e=!0){let t=!this._currentRenderPass,i=0;this._currentRenderPass&&this._currentRenderTarget&&(i|=1,this._endRenderTargetRenderPass()),this._mainRenderPassWrapper.renderPass&&(i|=2,this._endMainRenderPass()),this._commandBuffers[0]=this._uploadEncoder.finish(),this._commandBuffers[1]=this._renderTargetEncoder.finish(),this._commandBuffers[2]=this._renderEncoder.finish(),this._device.queue.submit(this._commandBuffers),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._timestampQuery.startFrame(this._uploadEncoder),this._textureHelper.setCommandEncoder(this._uploadEncoder),this._bundleList.reset(),this._bundleListRenderTarget.reset(),e&&(2&i&&this._startMainRenderPass(!1),1&i&&this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1),t&&this._currentRenderTarget&&(this._currentRenderPass=null))}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentRenderTarget}_startRenderTargetRenderPass(e,t,i,r,s){var n,a,o,l,h,u,c;let d=e._depthStencilTexture,p=null==d?void 0:d._hardwareTexture,_=null==p?void 0:p.underlyingResource,f=null==p?void 0:p.getMSAATexture(),m=null==_?void 0:_.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),g=null==f?void 0:f.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor),v=!!p&&u8.HasStencilAspect(p.format),T=[];this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual(),i&&(ck.r=255*i.r,ck.g=255*i.g,ck.b=255*i.b,ck.a=255*i.a);let x=t&&i,S=t&&r,E=t&&s;if(e._attachments&&e.isMulti){this._mrtAttachments&&0!==this._mrtAttachments.length||(this._mrtAttachments=e._defaultAttachments);for(let t=0;t<this._mrtAttachments.length;++t){let r=this._mrtAttachments[t],s=e.textures[t],h=null==s?void 0:s._hardwareTexture,u=null==h?void 0:h.underlyingResource;if(h&&u){let c=h.getMSAATexture(t),d=null!==(a=null===(n=e.layerIndices)||void 0===n?void 0:n[t])&&void 0!==a?a:0,p=null!==(l=null===(o=e.faceIndices)||void 0===o?void 0:o[t])&&void 0!==l?l:0,_=Object.assign(Object.assign({},this._rttRenderPassWrapper.colorAttachmentViewDescriptor),{format:h.format,baseArrayLayer:s.isCube?6*d+p:d}),f=Object.assign(Object.assign({},this._rttRenderPassWrapper.colorAttachmentViewDescriptor),{format:h.format,baseArrayLayer:0}),m=7===s.type||5===s.type,g=u.createView(_),v=null==c?void 0:c.createView(f);T.push({view:v||g,resolveTarget:c?g:void 0,clearValue:0!==r&&x?m?ck:i:void 0,loadOp:0!==r&&x?il.Clear:il.Load,storeOp:ih.Store})}}this._cacheRenderPipeline.setMRT(e.textures,this._mrtAttachments.length),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments)}else{let t=e.texture;if(t){let e=t._hardwareTexture,r=e.underlyingResource,s=e.getMSAATexture(),n=r.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),a=null==s?void 0:s.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor),o=7===t.type||5===t.type;T.push({view:a||n,resolveTarget:s?n:void 0,clearValue:x?o?ck:i:void 0,loadOp:x?il.Clear:il.Load,storeOp:ih.Store})}else T.push(null)}if(null===(h=this._debugPushGroup)||void 0===h||h.call(this,"render target pass",1),this._rttRenderPassWrapper.renderPassDescriptor={colorAttachments:T,depthStencilAttachment:d&&_?{view:g||m,depthClearValue:S?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,depthLoadOp:S?il.Clear:il.Load,depthStoreOp:ih.Store,stencilClearValue:e._depthStencilTextureWithStencil&&E?this._clearStencilValue:void 0,stencilLoadOp:v?e._depthStencilTextureWithStencil&&E?il.Clear:il.Load:void 0,stencilStoreOp:v?ih.Store:void 0}:void 0,occlusionQuerySet:(null===(u=this._occlusionQuery)||void 0===u?void 0:u.hasQueries)?this._occlusionQuery.querySet:void 0},this._rttRenderPassWrapper.renderPass=this._renderTargetEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),!this._count||this._count<this.dbgVerboseLogsNumFrames)){let t=e.texture;console.log("frame #"+this._count+" - render target begin pass - internalTexture.uniqueId=",t.uniqueId,"width=",t.width,"height=",t.height,this._rttRenderPassWrapper.renderPassDescriptor)}this._currentRenderPass=this._rttRenderPassWrapper.renderPass,null===(c=this._debugFlushPendingCommands)||void 0===c||c.call(this),this._resetCurrentViewport(1),this._resetCurrentScissor(1),this._resetCurrentStencilRef(1),this._resetCurrentColorBlend(1),p&&u8.HasStencilAspect(p.format)||(this._stencilStateComposer.enabled=!1)}_endRenderTargetRenderPass(){var e,t,i,r;if(this._currentRenderPass){let s=null===(e=this._currentRenderTarget.texture)||void 0===e?void 0:e._hardwareTexture;!s||this._snapshotRendering.endRenderTargetPass(this._currentRenderPass,s)||this.compatibilityMode||(this._bundleListRenderTarget.run(this._currentRenderPass),this._bundleListRenderTarget.reset()),this._currentRenderPass.end(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - render target end pass - internalTexture.uniqueId=",null===(i=null===(t=this._currentRenderTarget)||void 0===t?void 0:t.texture)||void 0===i?void 0:i.uniqueId)),null===(r=this._debugPopGroup)||void 0===r||r.call(this,1),this._resetCurrentViewport(1),this._viewport(0,0,0,0),this._resetCurrentScissor(1),this._resetCurrentStencilRef(1),this._resetCurrentColorBlend(1),this._currentRenderPass=null,this._rttRenderPassWrapper.reset()}}_getCurrentRenderPass(){return this._currentRenderTarget&&!this._currentRenderPass?this._startRenderTargetRenderPass(this._currentRenderTarget,!1,null,!1,!1):this._currentRenderPass||this._startMainRenderPass(!1),this._currentRenderPass}_getCurrentRenderPassIndex(){return null===this._currentRenderPass?-1:this._currentRenderPass===this._mainRenderPassWrapper.renderPass?0:1}_startMainRenderPass(e,t,i,r){var s,n,a;this._mainRenderPassWrapper.renderPass&&this.flushFramebuffer(!1),this.useReverseDepthBuffer&&this.setDepthFunctionToGreaterOrEqual();let o=e&&t,l=e&&i,h=e&&r;this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue=o?t:void 0,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp=o?il.Clear:il.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue=l?this.useReverseDepthBuffer?this._clearReverseDepthValue:this._clearDepthValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp=l?il.Clear:il.Load,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue=h?this._clearStencilValue:void 0,this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp=this.isStencilEnable?h?il.Clear:il.Load:void 0,this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet=(null===(s=this._occlusionQuery)||void 0===s?void 0:s.hasQueries)?this._occlusionQuery.querySet:void 0;let u=this._context.getCurrentTexture();this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(u),this._options.antialias?(cB.format=u.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget=u.createView(cB)):(cU.format=u.format,this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view=u.createView(cU)),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - main begin pass - texture width="+this._mainTextureExtends.width," height="+this._mainTextureExtends.height,this._mainRenderPassWrapper.renderPassDescriptor)),null===(n=this._debugPushGroup)||void 0===n||n.call(this,"main pass",0),this._currentRenderPass=this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor),this._mainRenderPassWrapper.renderPass=this._currentRenderPass,null===(a=this._debugFlushPendingCommands)||void 0===a||a.call(this),this._resetCurrentViewport(0),this._resetCurrentScissor(0),this._resetCurrentStencilRef(0),this._resetCurrentColorBlend(0),this._isStencilEnable||(this._stencilStateComposer.enabled=!1)}_endMainRenderPass(){var e;null!==this._mainRenderPassWrapper.renderPass&&(this._snapshotRendering.endMainRenderPass(),this.compatibilityMode||this._snapshotRendering.play||(this._bundleList.run(this._mainRenderPassWrapper.renderPass),this._bundleList.reset()),this._mainRenderPassWrapper.renderPass.end(),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - main end pass")),null===(e=this._debugPopGroup)||void 0===e||e.call(this,0),this._resetCurrentViewport(0),this._resetCurrentScissor(0),this._resetCurrentStencilRef(0),this._resetCurrentColorBlend(0),this._mainRenderPassWrapper.renderPass===this._currentRenderPass&&(this._currentRenderPass=null),this._mainRenderPassWrapper.reset(!1))}bindFramebuffer(e,t=0,i,r,s,n=0,a=0){var o,l;let h=null===(o=e.texture)||void 0===o?void 0:o._hardwareTexture;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,h&&(h._currentLayer=e.isCube?6*a+t:a),this._rttRenderPassWrapper.colorAttachmentGPUTextures[0]=h,this._rttRenderPassWrapper.depthTextureFormat=this._currentRenderTarget._depthStencilTexture?u8.GetWebGPUTextureFormat(-1,this._currentRenderTarget._depthStencilTexture.format):void 0,this._setDepthTextureFormat(this._rttRenderPassWrapper),this._setColorFormat(this._rttRenderPassWrapper),this._rttRenderPassWrapper.colorAttachmentViewDescriptor={format:this._colorFormat,dimension:tH.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?6*a+t:a,baseMipLevel:n,arrayLayerCount:1,aspect:tX.All},this._rttRenderPassWrapper.depthAttachmentViewDescriptor={format:this._depthTextureFormat,dimension:tH.E2d,mipLevelCount:1,baseArrayLayer:e.isCube?6*a+t:a,baseMipLevel:0,arrayLayerCount:1,aspect:tX.All},this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - bindFramebuffer called - internalTexture.uniqueId=",null===(l=e.texture)||void 0===l?void 0:l.uniqueId,"face=",t,"lodLevel=",n,"layer=",a,this._rttRenderPassWrapper.colorAttachmentViewDescriptor,this._rttRenderPassWrapper.depthAttachmentViewDescriptor)),this._currentRenderPass=null,this.snapshotRendering&&1===this.snapshotRenderingMode&&this._getCurrentRenderPass(),this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,r):(!i&&(i=e.width,n&&(i/=Math.pow(2,n))),!r&&(r=e.height,n&&(r/=Math.pow(2,n))),this._viewport(0,0,i,r)),this.wipeCaches()}unBindFramebuffer(e,t=!1,i){var r,s;let n=this._currentRenderTarget;this._currentRenderTarget=null,i&&i(),this._currentRenderTarget=n,this._currentRenderPass&&this._currentRenderPass!==this._mainRenderPassWrapper.renderPass&&this._endRenderTargetRenderPass(),(null===(r=e.texture)||void 0===r?void 0:r.generateMipMaps)&&!t&&!e.isCube&&this._generateMipmaps(e.texture),this._currentRenderTarget=null,this._onAfterUnbindFrameBufferObservable.notifyObservers(this),this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count<this.dbgVerboseLogsNumFrames)&&console.log("frame #"+this._count+" - unBindFramebuffer called - internalTexture.uniqueId=",null===(s=e.texture)||void 0===s?void 0:s.uniqueId)),this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments),this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):(this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)),this._currentRenderPass&&this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_setColorFormat(e){var t,i;let r=null!==(i=null===(t=e.colorAttachmentGPUTextures[0])||void 0===t?void 0:t.format)&&void 0!==i?i:null;this._cacheRenderPipeline.setColorFormat(r),this._colorFormat!==r&&(this._colorFormat=r)}_setDepthTextureFormat(e){this._cacheRenderPipeline.setDepthStencilFormat(e.depthTextureFormat),this._depthTextureFormat!==e.depthTextureFormat&&(this._depthTextureFormat=e.depthTextureFormat)}setDitheringState(){}setRasterizerState(){}setState(e,t=0,i,r=!1,s,n,a=0){var o,l;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);let h=null===(l=null!==(o=this.cullBackFaces)&&void 0!==o?o:s)||void 0===l||l?1:2;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(a);let u=r?this._currentRenderTarget?1:2:this._currentRenderTarget?2:1;(this._depthCullingState.frontFace!==u||i)&&(this._depthCullingState.frontFace=u),this._stencilStateComposer.stencilMaterial=n}_applyRenderPassChanges(e,t){var i;let r=this._mustUpdateViewport(e),s=this._mustUpdateScissor(e),n=!!this._stencilStateComposer.enabled&&this._mustUpdateStencilRef(e),a=!!this._alphaState.alphaBlend&&this._mustUpdateBlendColor(e);t?(r&&t.addItem(new cE(this._viewportCached.x,this._viewportCached.y,this._viewportCached.z,this._viewportCached.w)),s&&t.addItem(new cC(this._scissorCached.x,this._scissorCached.y,this._scissorCached.z,this._scissorCached.w)),n&&t.addItem(new cb(null!==(i=this._stencilStateComposer.funcRef)&&void 0!==i?i:0)),a&&t.addItem(new cy(this._alphaState._blendConstants.slice()))):(r&&this._applyViewport(e),s&&this._applyScissor(e),n&&this._applyStencilRef(e),a&&this._applyBlendColor(e))}_draw(e,t,i,r,s){var n;let a=this._getCurrentRenderPass(),o=this._getCurrentRenderPassIndex(),l=0===o?this._bundleList:this._bundleListRenderTarget;this.applyStates();let h=this._currentEffect._pipelineContext;if(this.bindUniformBufferBase(this._currentRenderTarget?this._ubInvertY:this._ubDontInvertY,0,ub.InternalsUBOName),h.uniformBuffer&&(h.uniformBuffer.update(),this.bindUniformBufferBase(h.uniformBuffer.getBuffer(),0,ub.LeftOvertUBOName)),this._snapshotRendering.play){this._reportDrawCall();return}!this.compatibilityMode&&(this._currentDrawContext.isDirty(this._currentMaterialContext.updateId)||this._currentMaterialContext.isDirty||this._currentMaterialContext.forceBindGroupCreation)&&(this._currentDrawContext.fastBundle=void 0);let u=!this.compatibilityMode&&this._currentDrawContext.fastBundle,c=a;if(u||this._snapshotRendering.record){if(this._applyRenderPassChanges(a,l),!this._snapshotRendering.record){this._counters.numBundleReuseNonCompatMode++,this._currentDrawContext.indirectDrawBuffer&&this._currentDrawContext.setIndirectData(r,s||1,i),l.addBundle(this._currentDrawContext.fastBundle),this._reportDrawCall();return}c=l.getBundleEncoder(this._cacheRenderPipeline.colorFormats,this._depthTextureFormat,this.currentSampleCount),l.numDrawCalls++}let d=0;if(!this._caps.textureFloatLinearFiltering&&this._currentMaterialContext.hasFloatTextures){let e=1;for(let t=0;t<h.shaderProcessingContext.textureNames.length;++t){let i=h.shaderProcessingContext.textureNames[t],r=null===(n=this._currentMaterialContext.textures[i])||void 0===n?void 0:n.texture;(null==r?void 0:r.type)===1&&(d|=e),e<<=1}}this._currentMaterialContext.textureState=d;let p=this._cacheRenderPipeline.getRenderPipeline(t,this._currentEffect,this.currentSampleCount,d),_=this._cacheBindGroups.getBindGroups(h,this._currentDrawContext,this._currentMaterialContext);this._snapshotRendering.record||(this._applyRenderPassChanges(a,this.compatibilityMode?null:l),this.compatibilityMode||(this._counters.numBundleCreationNonCompatMode++,c=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:this.currentSampleCount}))),c.setPipeline(p),this._currentIndexBuffer&&c.setIndexBuffer(this._currentIndexBuffer.underlyingResource,this._currentIndexBuffer.is32Bits?ii.Uint32:ii.Uint16,0);let f=this._cacheRenderPipeline.vertexBuffers;for(let e=0;e<f.length;e++){let t=f[e],i=t.getBuffer();i&&c.setVertexBuffer(e,i.underlyingResource,t._validOffsetRange?0:t.byteOffset)}for(let e=0;e<_.length;e++)c.setBindGroup(e,_[e]);let m=!this.compatibilityMode&&!this._snapshotRendering.record;m&&this._currentDrawContext.indirectDrawBuffer?(this._currentDrawContext.setIndirectData(r,s||1,i),0===e?c.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer,0):c.drawIndirect(this._currentDrawContext.indirectDrawBuffer,0)):0===e?c.drawIndexed(r,s||1,i,0,0):c.draw(r,s||1,i,0),m&&(this._currentDrawContext.fastBundle=c.finish(),l.addBundle(this._currentDrawContext.fastBundle)),this._reportDrawCall()}drawElementsType(e,t,i,r=1){this._draw(0,e,t,i,r)}drawArraysType(e,t,i,r=1){this._currentIndexBuffer=null,this._draw(1,e,t,i,r)}dispose(){var e,t;this._isDisposed=!0,null===(e=this._mainTexture)||void 0===e||e.destroy(),null===(t=this._depthTexture)||void 0===t||t.destroy(),this._device.destroy(),super.dispose()}getRenderWidth(e=!1){var t,i;return!e&&this._currentRenderTarget?this._currentRenderTarget.width:null!==(i=null===(t=this._renderingCanvas)||void 0===t?void 0:t.width)&&void 0!==i?i:0}getRenderHeight(e=!1){var t,i;return!e&&this._currentRenderTarget?this._currentRenderTarget.height:null!==(i=null===(t=this._renderingCanvas)||void 0===t?void 0:t.height)&&void 0!==i?i:0}getError(){return 0}bindSamplers(){}_bindTextureDirectly(){return!1}areAllEffectsReady(){return!0}_executeWhenRenderingStateIsCompiled(e,t){t()}_isRenderingStateCompiled(){return!0}_getUnpackAlignement(){return 1}_unpackFlipY(){}_bindUnboundFramebuffer(){throw"_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead"}_getSamplingParameters(){throw"_getSamplingParameters is not available in WebGPU"}getUniforms(){return[]}setIntArray(){return!1}setIntArray2(){return!1}setIntArray3(){return!1}setIntArray4(){return!1}setArray(){return!1}setArray2(){return!1}setArray3(){return!1}setArray4(){return!1}setMatrices(){return!1}setMatrix3x3(){return!1}setMatrix2x2(){return!1}setFloat(){return!1}setFloat2(){return!1}setFloat3(){return!1}setFloat4(){return!1}}cG._GLSLslangDefaultOptions={jsPath:"https://preview.babylonjs.com/glslang/glslang.js",wasmPath:"https://preview.babylonjs.com/glslang/glslang.wasm"},cG.UseTWGSL=!0,cG.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e&&(0===e&&!this._alphaState.alphaBlend||0!==e&&this._alphaState.alphaBlend)){if(!t){let t=0===e;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}return}switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0}t||(this.setDepthWrite(e===r7.D.ALPHA_DISABLE),this._cacheRenderPipeline.setDepthWriteEnabled(e===r7.D.ALPHA_DISABLE)),this._alphaMode=e,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)},cG.prototype.setAlphaEquation=function(e){r7.D.prototype.setAlphaEquation.call(this,e),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};class cz{getBindGroups(e,t,i){if(!i)throw Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(0===this._bindGroups.length){let r=this._bindGroupEntries.length>0;for(let t in e){let s=e[t],n=i[t],a=n.group,o=n.binding,l=s.type,h=s.object,u=s.indexInGroupEntries,c=this._bindGroupEntries[a];switch(c||(c=this._bindGroupEntries[a]=[]),l){case tN.Sampler:void 0!==u&&r?c[u].resource=this._cacheSampler.getSampler(h):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:this._cacheSampler.getSampler(h)}));break;case tN.Texture:case tN.TextureWithoutSampler:{let e=h._texture._hardwareTexture;void 0!==u&&r?(l===tN.Texture&&(c[u++].resource=this._cacheSampler.getSampler(h._texture)),c[u].resource=e.view):(s.indexInGroupEntries=c.length,l===tN.Texture&&c.push({binding:o-1,resource:this._cacheSampler.getSampler(h._texture)}),c.push({binding:o,resource:e.view}));break}case tN.StorageTexture:{let e=h._texture._hardwareTexture;(e.textureAdditionalUsages&tW.StorageBinding)==0&&ru.Y.Error(`computeDispatch: The texture (name=${h.name}, uniqueId=${h.uniqueId}) is not a storage texture!`,50),void 0!==u&&r?c[u].resource=e.viewForWriting:(s.indexInGroupEntries=c.length,c.push({binding:o,resource:e.viewForWriting}));break}case tN.UniformBuffer:case tN.StorageBuffer:{let e=(tN.UniformBuffer,h),t=e.getBuffer(),i=t.underlyingResource;void 0!==u&&r?(c[u].resource.buffer=i,c[u].resource.size=t.capacity):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:{buffer:i,offset:0,size:t.capacity}}))}}}for(let e=0;e<this._bindGroupEntries.length;++e){let i=this._bindGroupEntries[e];if(!i){this._bindGroups[e]=void 0;continue}this._bindGroups[e]=this._device.createBindGroup({layout:t.getBindGroupLayout(e),entries:i})}this._bindGroups.length=this._bindGroupEntries.length}return this._bindGroups}constructor(e,t){this._device=e,this._cacheSampler=t,this.uniqueId=cz._Counter++,this._bindGroupEntries=[],this.clear()}clear(){this._bindGroups=[]}}cz._Counter=0;class cW{get isAsync(){return!1}get isReady(){return!!this.stage}constructor(e){this._name="unnamed",this.engine=e}_getComputeShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.compute}dispose(){}}cG.prototype.createComputeContext=function(){return new cz(this._device,this._cacheSampler)},cG.prototype.createComputeEffect=function(e,t){let i=e.computeElement||e.compute||e.computeToken||e.computeSource||e,r=i+"@"+t.defines;if(this._compiledComputeEffects[r]){let e=this._compiledComputeEffects[r];return t.onCompiled&&e.isReady()&&t.onCompiled(e),e}let s=new l1(e,t,this,r);return this._compiledComputeEffects[r]=s,s},cG.prototype.createComputePipelineContext=function(){return new cW(this)},cG.prototype.areAllComputeEffectsReady=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e];if(!t.isReady())return!1}return!0},cG.prototype.computeDispatch=function(e,t,i,r,s,n,a){if(this._currentRenderTarget){this._onAfterUnbindFrameBufferObservable.addOnce(()=>{this.computeDispatch(e,t,i,r,s,n,a)});return}let o=e._pipelineContext;o.computePipeline||(o.computePipeline=this._device.createComputePipeline({layout:t4.Auto,compute:o.stage}));let l=this._renderTargetEncoder,h=l.beginComputePass();h.setPipeline(o.computePipeline);let u=t.getBindGroups(i,o.computePipeline,a);for(let e=0;e<u.length;++e){let t=u[e];t&&h.setBindGroup(e,t)}h.dispatchWorkgroups(r,s,n),h.end()},cG.prototype.releaseComputeEffects=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},cG.prototype._prepareComputePipelineContext=function(e,t,i,r,s){this.dbgShowShaderCode&&(console.log(r),console.log(t)),e.sources={compute:t,rawCompute:i},e.stage=this._createComputePipelineStageDescriptor(t,r,s)},cG.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},cG.prototype._rebuildComputeEffects=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},cG.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},cG.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},cG.prototype._createDepthStencilCubeTexture=function(e,t){let i=new sT.l(this,sT.S.DepthStencil);i.isCube=!0;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1},t);return i.format=r.generateStencil?13:14,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},cG.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d=!1){return this.createCubeTextureBase(e,t,i,!!r,s,n,a,o,l,h,u,c,null,(e,t)=>{let i=t[0].width;this._setCubeMapTextureParams(e,!r),e.format=null!=a?a:-1;let n=this._textureHelper.createGPUTextureForInternalTexture(e,i,i);this._textureHelper.updateCubeTextures(t,n.underlyingResource,i,i,n.format,!1,!1,0,0),r||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},!!d)},cG.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},cG.prototype._debugPushGroup=function(e,t){if(this._options.enableGPUDebugMarkers){if(0===t||1===t){let i=0===t?this._renderEncoder:this._renderTargetEncoder;i.pushDebugGroup(e)}else this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e])}},cG.prototype._debugPopGroup=function(e){if(this._options.enableGPUDebugMarkers){if(0===e||1===e){let t=0===e?this._renderEncoder:this._renderTargetEncoder;t.popDebugGroup()}else this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null])}},cG.prototype._debugInsertMarker=function(e,t){if(this._options.enableGPUDebugMarkers){if(0===t||1===t){let i=0===t?this._renderEncoder:this._renderTargetEncoder;i.insertDebugMarker(e)}else this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e])}},cG.prototype._debugFlushPendingCommands=function(){for(let e=0;e<this._pendingDebugCommands.length;++e){let[t,i]=this._pendingDebugCommands[e];switch(t){case"push":this._debugPushGroup(i);break;case"pop":this._debugPopGroup();break;case"insert":this._debugInsertMarker(i)}}this._pendingDebugCommands.length=0},cG.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let r;r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._bufferManager.setSubData(e,i,r)},cG.prototype.updateDynamicVertexBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(e,i,s,0,r)},cG.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,n,a){var o;if(!e)return;let l=t.width,h=t.height,u=e._hardwareTexture;(null===(o=e._hardwareTexture)||void 0===o?void 0:o.underlyingResource)||(u=this._textureHelper.createGPUTextureForInternalTexture(e,l,h)),this._textureHelper.updateTexture(t,e,l,h,e.depth,u.format,0,0,i,r,0,0,a),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0};class cH extends c_{constructor(e){super(e)}}function cX(e,t,i,r){let s;let n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r<t;r++)for(let a=0;a<i;a++){let i=(a*t+r)*3,o=(a*t+r)*4;s[o+0]=e[i+0],s[o+1]=e[i+1],s[o+2]=e[i+2],s[o+3]=n}return s}sj.Q.prototype.setExternalTexture=function(e,t){this._engine.setExternalTexture(e,t)},cG.prototype.createExternalTexture=function(e){let t=new cH(e);return t},cG.prototype.setExternalTexture=function(e,t){if(!t){this._currentMaterialContext.setTexture(e,null);return}this._setInternalTexture(e,t)},cG.prototype.unBindMultiColorAttachmentFramebuffer=function(e,t=!1,i){i&&i();let r=e._attachments,s=r.length;this._currentRenderPass&&this._currentRenderPass!==this._mainRenderPassWrapper.renderPass&&this._endRenderTargetRenderPass();for(let i=0;i<s;i++){let r=e.textures[i];!r.generateMipMaps||t||r.isCube||this._generateMipmaps(r)}this._currentRenderTarget=null,this._mrtAttachments=[],this._cacheRenderPipeline.setMRT([]),this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments),this._currentRenderPass=this._mainRenderPassWrapper.renderPass,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper)},cG.prototype.createMultipleRenderTarget=function(e,t,i){var r,s;let n=!1,a=!0,o=!1,l=!1,h=15,u=1,c=[],d=[],p=[],_=[],f=[],m=[],g=[],v=[],T=this._createHardwareRenderTargetWrapper(!0,!1,e);void 0!==t&&(n=void 0!==t.generateMipMaps&&t.generateMipMaps,a=void 0===t.generateDepthBuffer||t.generateDepthBuffer,o=void 0!==t.generateStencilBuffer&&t.generateStencilBuffer,l=void 0!==t.generateDepthTexture&&t.generateDepthTexture,u=t.textureCount||1,h=null!==(r=t.depthTextureFormat)&&void 0!==r?r:15,t.types&&(c=t.types),t.samplingModes&&(d=t.samplingModes),t.useSRGBBuffers&&(p=t.useSRGBBuffers),t.formats&&(_=t.formats),t.targetTypes&&(f=t.targetTypes),t.faceIndex&&(m=t.faceIndex),t.layerIndex&&(g=t.layerIndex),t.layerCounts&&(v=t.layerCounts));let x=e.width||e,S=e.height||e,E=null;(a||o||l)&&(l||(h=a&&o?13:a?14:19),E=T.createDepthStencilTexture(0,!1,o,1,h));let C=[],b=[],y=[];T._generateDepthBuffer=a,T._generateStencilBuffer=o,T._attachments=b,T._defaultAttachments=y;for(let e=0;e<u;e++){let t=d[e]||3,r=c[e]||0,a=_[e]||5,o=(p[e]||!1)&&this._caps.supportSRGBBuffers,l=f[e]||3553,h=null!==(s=v[e])&&void 0!==s?s:1;if((1!==r||this._caps.textureFloatLinearFiltering)&&(2!==r||this._caps.textureHalfFloatLinearFiltering)||(t=1),1!==r||this._caps.textureFloat||(r=0,ru.Y.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")),b.push(e+1),y.push(i?e+1:0===e?1:0),-1===l)continue;let u=new sT.l(this,sT.S.MultiRenderTarget);switch(C[e]=u,l){case 34067:u.isCube=!0;break;case 32879:u.is3D=!0,u.baseDepth=u.depth=h;break;case 35866:u.is2DArray=!0,u.baseDepth=u.depth=h}u.baseWidth=x,u.baseHeight=S,u.width=x,u.height=S,u.isReady=!0,u.samples=1,u.generateMipMaps=n,u.samplingMode=t,u.type=r,u._cachedWrapU=0,u._cachedWrapV=0,u._useSRGBBuffer=o,u.format=a,this._internalTexturesCache.push(u),this._textureHelper.createGPUTextureForInternalTexture(u)}return E&&(E.incrementReferences(),C[u]=E,this._internalTexturesCache.push(E)),T.setTextures(C),T.setLayerAndFaceIndices(g,m),T},cG.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t){if(!e||!e.textures||e.textures[0].samples===t)return t;let i=e.textures.length;if(0===i)return 1;t=Math.min(t,this.getCaps().maxMSAASamples);for(let t=0;t<i;++t){let i=e.textures[t],r=i._hardwareTexture;null==r||r.releaseMSAATexture()}let r=e._depthStencilTexture===e.textures[i-1];for(let s=0;s<i;++s){let n=e.textures[s];this._textureHelper.createMSAATexture(n,t,!1,s===i-1&&r?0:s),n.samples=t}return e._depthStencilTexture&&!r&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),t},cG.prototype.bindAttachments=function(e){0!==e.length&&this._currentRenderTarget&&(this._mrtAttachments=e,this._currentRenderPass&&this._cacheRenderPipeline.setMRTAttachments(e))},cG.prototype.buildTextureLayout=function(e){let t=[];for(let i=0;i<e.length;i++)e[i]?t.push(i+1):t.push(0);return t},cG.prototype.restoreSingleAttachment=function(){},cG.prototype.restoreSingleAttachmentForRenderTarget=function(){},cG.prototype.getGPUFrameTimeCounter=function(){return this._timestampQuery.gpuFrameTimeCounter},cG.prototype.captureGPUFrameTime=function(e){this._timestampQuery.enable=e&&!!this._caps.timerQuery},cG.prototype.createQuery=function(){return this._occlusionQuery.createQuery()},cG.prototype.deleteQuery=function(e){return this._occlusionQuery.deleteQuery(e),this},cG.prototype.isQueryResultAvailable=function(e){return this._occlusionQuery.isQueryResultAvailable(e)},cG.prototype.getQueryResult=function(e){return this._occlusionQuery.getQueryResult(e)},cG.prototype.beginOcclusionQuery=function(e,t){var i;if(this.compatibilityMode){if(this._occlusionQuery.canBeginQuery)return null===(i=this._currentRenderPass)||void 0===i||i.beginOcclusionQuery(t),!0}else{let e=this._getCurrentRenderPassIndex(),i=0===e?this._bundleList:this._bundleListRenderTarget;return i.addItem(new cA(t)),!0}return!1},cG.prototype.endOcclusionQuery=function(){var e;if(this.compatibilityMode)null===(e=this._currentRenderPass)||void 0===e||e.endOcclusionQuery();else{let e=this._getCurrentRenderPassIndex(),t=0===e?this._bundleList:this._bundleListRenderTarget;t.addItem(new cR)}return this},cG.prototype.createRawTexture=function(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){let c=new sT.l(this,sT.S.Raw);return c.baseWidth=t,c.baseHeight=i,c.width=t,c.height=i,c.format=r,c.generateMipMaps=s,c.samplingMode=a,c.invertY=n,c._compression=o,c.type=l,c._useSRGBBuffer=u,this._doNotHandleContextLost||(c._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(c,t,i,void 0,h),this.updateRawTexture(c,e,r,n,o,l,u),this._internalTexturesCache.push(c),c},cG.prototype.updateRawTexture=function(e,t,i,r,s=null,n=0,a=!1){if(e){if(this._doNotHandleContextLost||(e._bufferView=t,e.invertY=r,e._compression=s,e._useSRGBBuffer=a),t){let s=e._hardwareTexture;4===i&&(t=cX(t,e.width,e.height,n));let a=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(a,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0}},cG.prototype.createRawCubeTexture=function(e,t,i,r,s,n,a,o=null){let l=new sT.l(this,sT.S.CubeRaw);return 1!==r||this._caps.textureFloatLinearFiltering?2!==r||this._caps.textureHalfFloatLinearFiltering?1!==r||this._caps.textureFloatRender?2!==r||this._caps.colorBufferFloat||(s=!1,ru.Y.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(s=!1,ru.Y.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(s=!1,a=1,ru.Y.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(s=!1,a=1,ru.Y.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")),l.isCube=!0,l.format=4===i?5:i,l.type=r,l.generateMipMaps=s,l.width=t,l.height=t,l.samplingMode=a,this._doNotHandleContextLost||(l._bufferViewArray=e),l.invertY=n,l._compression=o,l._cachedWrapU=0,l._cachedWrapV=0,this._textureHelper.createGPUTextureForInternalTexture(l),e&&this.updateRawCubeTexture(l,e,i,r,n,o),l.isReady=!0,l},cG.prototype.updateRawCubeTexture=function(e,t,i,r,s,n=null){e._bufferViewArray=t,e.invertY=s,e._compression=n;let a=e._hardwareTexture,o=4===i,l=[];for(let i=0;i<t.length;++i){let s=t[i];o&&(s=cX(t[i],e.width,e.height,r)),l.push(new Uint8Array(s.buffer,s.byteOffset,s.byteLength))}this._textureHelper.updateCubeTextures(l,a.underlyingResource,e.width,e.height,a.format,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0},cG.prototype.createRawCubeTextureFromUrl=function(e,t,i,r,s,n,a,o,l=null,h=null,u=3,c=!1){let d=this.createRawCubeTexture(null,i,r,s,!n,c,u,null);null==t||t.addPendingData(d),d.url=e,this._internalTexturesCache.push(d);let p=e=>{let i=d.width,n=a(e);if(!n)return;let h=[0,2,4,1,3,5];if(o){let e=4===r,t=o(n),a=d._hardwareTexture,l=[0,1,2,3,4,5];for(let r=0;r<t.length;r++){let n=i>>r,o=[];for(let i=0;i<6;i++){let a=t[r][l[i]];e&&(a=cX(a,n,n,s)),o.push(new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}this._textureHelper.updateCubeTextures(o,a.underlyingResource,n,n,a.format,c,!1,0,0)}}else{let e=[];for(let t=0;t<6;t++)e.push(n[h[t]]);this.updateRawCubeTexture(d,e,r,s,c)}d.isReady=!0,null==t||t.removePendingData(d),l&&l()};return this._loadFile(e,e=>{p(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)}),d},cG.prototype.createRawTexture3D=function(e,t,i,r,s,n,a,o,l=null,h=0,u=0){let c=sT.S.Raw3D,d=new sT.l(this,c);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=n,d.samplingMode=o,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,u),this.updateRawTexture3D(d,e,s,a,l,h),this._internalTexturesCache.push(d),d},cG.prototype.updateRawTexture3D=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture;4===i&&(t=cX(t,e.width,e.height,n));let a=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(a,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},cG.prototype.createRawTexture2DArray=function(e,t,i,r,s,n,a,o,l=null,h=0,u=0){let c=sT.S.Raw2DArray,d=new sT.l(this,c);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=n,d.samplingMode=o,d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,r,u),this.updateRawTexture2DArray(d,e,s,a,l,h),this._internalTexturesCache.push(d),d},cG.prototype.updateRawTexture2DArray=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture;4===i&&(t=cX(t,e.width,e.height,n));let a=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(a,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},cG.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){let u=e._hardwareTexture;return a&&this.flushFramebuffer(),this._textureHelper.readPixels(u.underlyingResource,l,h,t,i,u.format,r,s,n,o)},cG.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class cY extends nh{}cG.prototype._createHardwareRenderTargetWrapper=function(e,t,i){let r=new cY(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},cG.prototype.createRenderTargetTexture=function(e,t){var i,r;let s=this._createHardwareRenderTargetWrapper(!1,!1,e),n={};void 0!==t&&"object"==typeof t?(n.generateMipMaps=t.generateMipMaps,n.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,n.generateStencilBuffer=n.generateDepthBuffer&&t.generateStencilBuffer,n.samplingMode=void 0===t.samplingMode?3:t.samplingMode,n.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,n.noColorAttachment=!!t.noColorAttachment,n.samples=t.samples,n.label=t.label):(n.generateMipMaps=t,n.generateDepthBuffer=!0,n.generateStencilBuffer=!1,n.samplingMode=3,n.creationFlags=0,n.noColorAttachment=!1);let a=n.noColorAttachment?null:this._createInternalTexture(e,t,!0,sT.S.RenderTarget);return s._samples=null!==(r=n.samples)&&void 0!==r?r:1,s._generateDepthBuffer=n.generateDepthBuffer,s._generateStencilBuffer=!!n.generateStencilBuffer,s.setTextures(a),(s._generateDepthBuffer||s._generateStencilBuffer)&&s.createDepthStencilTexture(0,this._caps.textureFloatLinearFiltering&&(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),s._generateStencilBuffer,s.samples,n.generateStencilBuffer?13:14,n.label?n.label+"-DepthStencil":void 0),a&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!n.generateMipMaps&&(a.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(a,void 0,void 0,void 0,n.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!n.generateMipMaps&&(a.generateMipMaps=!1)),s},cG.prototype._createDepthStencilTexture=function(e,t){let i=new sT.l(this,sT.S.DepthStencil);i.label=t.label;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14},t);return i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},cG.prototype._setupDepthStencilTexture=function(e,t,i,r,s,n=1){let a=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=1,e._comparisonFunction=s,e._cachedWrapU=0,e._cachedWrapV=0},cG.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},cG.prototype.createRenderTargetCubeTexture=function(e,t){let i=this._createHardwareRenderTargetWrapper(!1,!0,e),r=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},t);r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer;let s=new sT.l(this,sT.S.RenderTarget);return s.width=e,s.height=e,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=r.samples,s.generateMipMaps=r.generateMipMaps,s.samplingMode=r.samplingMode,s.type=r.type,s.format=r.format,this._internalTexturesCache.push(s),i.setTextures(s),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===r.samplingMode||2===r.samplingMode||2===r.samplingMode||3===r.samplingMode||3===r.samplingMode||5===r.samplingMode||6===r.samplingMode||7===r.samplingMode||11===r.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!r.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),t&&t.createMipMaps&&!r.generateMipMaps&&(s.generateMipMaps=!1),i},sj.Q.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},cG.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},sj.Q.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},cG.prototype.createStorageBuffer=function(e,t){return this._createBuffer(e,32|t)},cG.prototype.updateStorageBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(e,i,s,0,r)},cG.prototype.readFromStorageBuffer=function(e,t,i,r){i=i||e.capacity;let s=this._bufferManager.createRawBuffer(i,tk.MapRead|tk.CopyDst);return this._renderTargetEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,s,0,i),new Promise((e,t)=>{this.onEndFrameObservable.addOnce(()=>{s.mapAsync(tG.Read,0,i).then(()=>{let t=s.getMappedRange(0,i),n=r;if(void 0===n)(n=new Uint8Array(i)).set(new Uint8Array(t));else{let e=n.constructor;(n=new e(n.buffer)).set(new e(t))}s.unmap(),this._bufferManager.releaseBuffer(s),e(n)},e=>t(e))})})},cG.prototype.setStorageBuffer=function(e,t){var i,r;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(r=null==t?void 0:t.getBuffer())&&void 0!==r?r:null)},cG.prototype.createUniformBuffer=function(e){let t;t=e instanceof Array?new Float32Array(e):e;let i=this._bufferManager.createBuffer(t,tk.Uniform|tk.CopyDst);return i},cG.prototype.createDynamicUniformBuffer=function(e){return this.createUniformBuffer(e)},cG.prototype.updateUniformBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Float32Array?t:new Float32Array(t)).byteLength:s=t instanceof Float32Array?t:new Float32Array(t),this._bufferManager.setSubData(e,i,s,0,r)},cG.prototype.bindUniformBufferBase=function(e,t,i){this._currentDrawContext.setBuffer(i,e)},cG.prototype.bindUniformBlock=function(){},cG.prototype.updateVideoTexture=function(e,t,i){var r;if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;((null===(r=e._hardwareTexture)||void 0===r?void 0:r.underlyingResource)||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),t&&void 0!==t.underlyingResource)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0):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})},i(5342);class cj{}cj.COPY=1,cj.CUT=2,cj.PASTE=3;class cq extends oh{constructor(e){super(e),this.controllerType=tA.DAYDREAM}initControllerMesh(e,t){sH.ImportMesh("",cq.MODEL_BASE_URL,cq.MODEL_FILENAME,e,e=>{this._defaultModel=e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)})}_handleButtonChange(e,t){if(0===e){let e=this.onTriggerStateChangedObservable;e&&e.notifyObservers(t)}else ru.Y.Warn(`Unrecognized Daydream button index: ${e}`)}}cq.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",cq.MODEL_FILENAME="generic.babylon",cq.GAMEPAD_ID_PREFIX="Daydream",aN._ControllerFactories.push({canCreate:e=>0===e.id.indexOf(cq.GAMEPAD_ID_PREFIX),create:e=>new cq(e)});class cK extends oh{constructor(e){super(e),this._buttonIndexToObservableNameMap=["onPadStateChangedObservable","onTriggerStateChangedObservable"],this.controllerType=tA.GEAR_VR,this._calculatedPosition=new rr.P("left"==this.hand?-.15:.15,-.5,.25),this._disableTrackPosition(this._calculatedPosition)}initControllerMesh(e,t){sH.ImportMesh("",cK.MODEL_BASE_URL,cK.MODEL_FILENAME,e,i=>{let r=new rq.Kj("",e);i[1].parent=r,i[1].position.z=-.15,this._defaultModel=r,this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)})}_handleButtonChange(e,t){if(e<this._buttonIndexToObservableNameMap.length){let i=this._buttonIndexToObservableNameMap[e],r=this[i];r&&r.notifyObservers(t)}}}cK.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",cK.MODEL_FILENAME="generic.babylon",cK.GAMEPAD_ID_PREFIX="Gear VR",aN._ControllerFactories.push({canCreate:e=>0===e.id.indexOf(cK.GAMEPAD_ID_PREFIX)||-1!==e.id.indexOf("Oculus Go")||-1!==e.id.indexOf("Vive Focus"),create:e=>new cK(e)});class c$ extends oh{constructor(e){super(e)}initControllerMesh(e,t){sH.ImportMesh("",c$.MODEL_BASE_URL,c$.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)}}c$.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",c$.MODEL_FILENAME="generic.babylon",aN._DefaultControllerFactory=e=>new c$(e);class cQ extends oh{constructor(e){super(e),this.onSecondaryTriggerStateChangedObservable=new ri.y$,this.onThumbRestChangedObservable=new ri.y$,this.controllerType=tA.OCULUS}initControllerMesh(e,t){let i;i="left"===this.hand?cQ.MODEL_LEFT_FILENAME:cQ.MODEL_RIGHT_FILENAME,sH.ImportMesh("",cQ._IsQuest?cQ.QUEST_MODEL_BASE_URL:cQ.MODEL_BASE_URL,i,e,e=>{this._defaultModel=cQ._IsQuest?e[0]:e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)})}get onAButtonStateChangedObservable(){if("right"===this.hand)return this.onMainButtonStateChangedObservable;throw Error("No A button on left hand")}get onBButtonStateChangedObservable(){if("right"===this.hand)return this.onSecondaryButtonStateChangedObservable;throw Error("No B button on left hand")}get onXButtonStateChangedObservable(){if("left"===this.hand)return this.onMainButtonStateChangedObservable;throw Error("No X button on right hand")}get onYButtonStateChangedObservable(){if("left"===this.hand)return this.onSecondaryButtonStateChangedObservable;throw Error("No Y button on right hand")}_handleButtonChange(e,t){let i="right"===this.hand?-1:1;switch(e){case 0:this.onPadStateChangedObservable.notifyObservers(t);return;case 1:!cQ._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[3].rotation.x=-(.2*t.value),this._defaultModel.getChildren()[3].position.y=-(.005*t.value),this._defaultModel.getChildren()[3].position.z=-(.005*t.value)),this.onTriggerStateChangedObservable.notifyObservers(t);return;case 2:!cQ._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[4].position.x=i*t.value*.0035),this.onSecondaryTriggerStateChangedObservable.notifyObservers(t);return;case 3:!cQ._IsQuest&&this._defaultModel&&(t.pressed?this._defaultModel.getChildren()[1].position.y=-.001:this._defaultModel.getChildren()[1].position.y=0),this.onMainButtonStateChangedObservable.notifyObservers(t);return;case 4:!cQ._IsQuest&&this._defaultModel&&(t.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),this.onSecondaryButtonStateChangedObservable.notifyObservers(t);return;case 5:this.onThumbRestChangedObservable.notifyObservers(t);return}}}cQ.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",cQ.MODEL_LEFT_FILENAME="left.babylon",cQ.MODEL_RIGHT_FILENAME="right.babylon",cQ.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",cQ._IsQuest=!1,aN._ControllerFactories.push({canCreate:e=>(rp.l.LastCreatedEngine&&rp.l.LastCreatedEngine._vrDisplay&&"Oculus Quest"===rp.l.LastCreatedEngine._vrDisplay.displayName&&(cQ._IsQuest=!0),-1!==e.id.indexOf("Oculus Touch")),create:e=>new cQ(e)});class cZ extends oh{constructor(e){super(e),this.controllerType=tA.VIVE,this._invertLeftStickY=!0}initControllerMesh(e,t){sH.ImportMesh("",cZ.MODEL_BASE_URL,cZ.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){switch(e){case 0:this.onPadStateChangedObservable.notifyObservers(t);return;case 1:this._defaultModel&&(this._defaultModel.getChildren()[6].rotation.x=-(.15*t.value)),this.onTriggerStateChangedObservable.notifyObservers(t);return;case 2:this.onMainButtonStateChangedObservable.notifyObservers(t);return;case 3:this._defaultModel&&(t.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),this.onSecondaryButtonStateChangedObservable.notifyObservers(t);return}}}cZ.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",cZ.MODEL_FILENAME="wand.babylon",aN._ControllerFactories.push({canCreate:e=>-1!==e.id.toLowerCase().indexOf("openvr"),create:e=>new cZ(e)});class cJ{constructor(){this.buttonMeshes={},this.axisMeshes={}}}class c0 extends oh{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:aF.POINTING_POSE},this.onTrackpadChangedObservable=new ri.y$,this.onTrackpadValuesChangedObservable=new ri.y$,this.trackpad={x:0,y:0},this.controllerType=tA.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._mapping.axisMeshNames.length;e++)this._lerpAxisTransform(e,this.browserGamepad.axes[e])}_handleButtonChange(e,t){let i=this._mapping.buttons[e];if(!i)return;this._updateTrackpad();let r=this[this._mapping.buttonObservableNames[i]];r&&r.notifyObservers(t),this._lerpButtonTransform(i,t.value)}_lerpButtonTransform(e,t){if(!this._loadedMeshInfo)return;let i=this._loadedMeshInfo.buttonMeshes[e];i&&i.unpressed.rotationQuaternion&&i.pressed.rotationQuaternion&&i.value.rotationQuaternion&&(rr._f.SlerpToRef(i.unpressed.rotationQuaternion,i.pressed.rotationQuaternion,t,i.value.rotationQuaternion),rr.P.LerpToRef(i.unpressed.position,i.pressed.position,t,i.value.position))}_lerpAxisTransform(e,t){if(!this._loadedMeshInfo)return;let i=this._loadedMeshInfo.axisMeshes[e];if(!i||!i.min.rotationQuaternion||!i.max.rotationQuaternion||!i.value.rotationQuaternion)return;let r=.5*t+.5;rr._f.SlerpToRef(i.min.rotationQuaternion,i.max.rotationQuaternion,r,i.value.rotationQuaternion),rr.P.LerpToRef(i.min.position,i.max.position,r,i.value.position)}initControllerMesh(e,t,i=!1){let r,s;if(sH.IsPluginForExtensionAvailable(".glb")){let e="default";if(this.id&&!i){let t=this.id.match(c0.GAMEPAD_ID_PATTERN);e=t&&t[0]||e}s="left"===this.hand?c0.MODEL_LEFT_FILENAME:c0.MODEL_RIGHT_FILENAME,r=c0.MODEL_BASE_URL+e+"/"}else ru.Y.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models"),r=c$.MODEL_BASE_URL,s=c$.MODEL_FILENAME;sH.ImportMesh("",r,s,e,i=>{this._loadedMeshInfo=this._processModel(e,i),this._loadedMeshInfo&&(this._defaultModel=this._loadedMeshInfo.rootNode,this.attachToMesh(this._defaultModel),t&&t(this._defaultModel))},null,(e,n)=>{ru.Y.Log(n),ru.Y.Warn("Failed to retrieve controller model from the remote server: "+r+s),i||this.initControllerMesh(e,t,!0)})}_processModel(e,t){let i=null,r=new rq.Kj(this.id+" "+this.hand,e),s=null;for(let e=0;e<t.length;e++){let i=t[e];if(!i.parent){i.isPickable=!1,s=i;break}}return s?(s.setParent(r),i=this._createMeshInfo(r)):ru.Y.Warn("Could not find root node in model file."),i}_createMeshInfo(e){let t;let i=new cJ;for(t=0,i.rootNode=e,i.buttonMeshes={},i.axisMeshes={};t<this._mapping.buttons.length;t++){let n=this._mapping.buttonMeshNames[this._mapping.buttons[t]];if(!n){ru.Y.Log("Skipping unknown button at index: "+t+" with mapped name: "+this._mapping.buttons[t]);continue}let a=r(e,n);if(!a){ru.Y.Warn("Missing button mesh with name: "+n);continue}let o={index:t,value:s(a,"VALUE"),pressed:s(a,"PRESSED"),unpressed:s(a,"UNPRESSED")};o.value&&o.pressed&&o.unpressed?i.buttonMeshes[this._mapping.buttons[t]]=o:ru.Y.Warn("Missing button submesh under mesh with name: "+n+"(VALUE: "+!!o.value+", PRESSED: "+!!o.pressed+", UNPRESSED:"+!!o.unpressed+")")}for(t=0;t<this._mapping.axisMeshNames.length;t++){let n=this._mapping.axisMeshNames[t];if(!n){ru.Y.Log("Skipping unknown axis at index: "+t);continue}let a=r(e,n);if(!a){ru.Y.Warn("Missing axis mesh with name: "+n);continue}let o={index:t,value:s(a,"VALUE"),min:s(a,"MIN"),max:s(a,"MAX")};o.value&&o.min&&o.max?i.axisMeshes[t]=o:ru.Y.Warn("Missing axis submesh under mesh with name: "+n+"(VALUE: "+!!o.value+", MIN: "+!!o.min+", MAX:"+!!o.max+")")}return i.pointingPoseNode=r(e,this._mapping.pointingPoseMeshName),i.pointingPoseNode?this._pointingPoseNode=i.pointingPoseNode:ru.Y.Warn("Missing pointing pose mesh with name: "+this._mapping.pointingPoseMeshName),i;function r(e,t){return e.getChildren(e=>e.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);let t=this._loadedMeshInfo.pointingPoseNode.getWorldMatrix(),i=t.getTranslation(),r=new rr.P(0,0,-1),s=rr.P.TransformNormal(r,t),n=rr.P.Normalize(s);return new sD(i,n,e)}dispose(){super.dispose(),this.onTrackpadChangedObservable.clear(),this.onTrackpadValuesChangedObservable.clear()}}c0.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",c0.MODEL_LEFT_FILENAME="left.glb",c0.MODEL_RIGHT_FILENAME="right.glb",c0.GAMEPAD_ID_PREFIX="Spatial Controller (Spatial Interaction Source) ",c0.GAMEPAD_ID_PATTERN=/([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/,aN._ControllerFactories.push({canCreate:e=>0===e.id.indexOf(c0.GAMEPAD_ID_PREFIX),create:e=>new c0(e)});class c1 extends ht{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=rs.Wo.Gray(),i=he.DefaultUtilityLayer,r=32,s=null,n=!1,a=1){var o;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new ri.y$,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new rr.P,this._parent=s,this._coloredMaterial=new lC("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new rs.Wo(.1,.1,.1)),this._hoverMaterial=new lC("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=rs.Wo.Yellow(),this._disableMaterial=new lC("",i.utilityLayerScene),this._disableMaterial.diffuseColor=rs.Wo.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new rq.Kj("",i.utilityLayerScene);let{rotationMesh:l,collider:h}=this._createGizmoMesh(this._gizmoMesh,a,r);this._rotationDisplayPlane=sL("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),sj.Q.ShadersStore.rotationGizmoVertexShader=c1._RotationGizmoVertexShader,sj.Q.ShadersStore.rotationGizmoFragmentShader=c1._RotationGizmoFragmentShader,this._rotationShaderMaterial=new hf("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,ht.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new sw({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=c1.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);let u=new rr.P,c=new rr.y3,d=new rr.P,p=new rr.P;this.dragBehavior.onDragStartObservable.add(e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(c),rr.P.TransformCoordinatesToRef(e.dragPlanePoint,c,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});let _={snapDistance:0},f=0,m=new rr.y3,g=new rr._f;this.dragBehavior.onDragObservable.add(t=>{if(this.attachedNode){let r=new rr.P(1,1,1),s=new rr._f(0,0,0,1),n=new rr.P(0,0,0);this._handlePivot(),this.attachedNode.getWorldMatrix().decompose(r,s,n);let a=Math.abs(Math.abs(r.x)-Math.abs(r.y))<=rL.kn&&Math.abs(Math.abs(r.x)-Math.abs(r.z))<=rL.kn;if(!a&&this.updateGizmoRotationToMatchAttachedMesh){ru.Y.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}s.normalize();let o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,l=t.dragPlanePoint.subtract(o).normalize(),h=u.subtract(o).normalize(),v=rr.P.Cross(l,h),T=rr.P.Dot(l,h),x=Math.atan2(v.length(),T)*this.sensitivity;d.copyFrom(e),p.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(c),p=rr.P.TransformCoordinates(d,c));let S=!1;if(i.utilityLayerScene.activeCamera){let e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();rr.P.Dot(e,p)>0&&(d.scaleInPlace(-1),p.scaleInPlace(-1),S=!0)}let E=rr.P.Dot(p,v)>0;E&&(x=-x);let C=!1;if(0!=this.snapDistance){if(Math.abs(f+=x)>this.snapDistance){let e=Math.floor(Math.abs(f)/this.snapDistance);f<0&&(e*=-1),f%=this.snapDistance,x=this.snapDistance*e,C=!0}else x=0}let b=Math.sin(x/2);if(g.set(d.x*b,d.y*b,d.z*b,Math.cos(x/2)),m.determinant()>0){let e=new rr.P;g.toEulerAnglesToRef(e),rr._f.RotationYawPitchRollToRef(e.y,-e.x,-e.z,g)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(g,s),rr.y3.ComposeToRef(r,s,n,this.attachedNode.getWorldMatrix());else{g.toRotationMatrix(rr.jp.Matrix[0]);let e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(rr.jp.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),C&&(_.snapDistance=x,this.onSnapObservable.notifyObservers(_)),this._angles.y+=x,this.angle+=S?-x:x,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});let v=i._getSharedGizmoLight();v.includedOnlyMeshes=v.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));let T={colliderMeshes:[h],gizmoMeshes:[l],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(o=this._parent)||void 0===o||o.addToAxisCache(this._gizmoMesh,T),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(e=>{var t;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=c1.MaxDragAngle,this._isHovered=-1!=T.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh),!this._parent)){let e=T.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(T.gizmoMeshes,e)}}),this.dragBehavior.onEnabledObservable.add(e=>{this._setGizmoMeshMaterial(T.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){let r=lG("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;let s=lG("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(s,ht.PreserveScaling),e.addChild(r,ht.PreserveScaling),{rotationMesh:s,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}}c1.MaxDragAngle=9*Math.PI/20,c1._RotationGizmoVertexShader=` - precision highp float; - attribute vec3 position; - attribute vec2 uv; - uniform mat4 worldViewProjection; - varying vec3 vPosition; - varying vec2 vUV; - void main(void) { - gl_Position = worldViewProjection * vec4(position, 1.0); - vUV = uv; - }`,c1._RotationGizmoFragmentShader=` - precision highp float; - varying vec2 vUV; - varying vec3 vPosition; - uniform vec3 angles; - #define twopi 6.283185307 - void main(void) { - vec2 uv = vUV - vec2(0.5); - float angle = atan(uv.y, uv.x) + 3.141592; - float delta = gl_FrontFacing ? angles.y : -angles.y; - float begin = angles.x - delta * angles.z; - float start = (begin < (begin + delta)) ? begin : (begin + delta); - float end = (begin > (begin + delta)) ? begin : (begin + delta); - float len = sqrt(dot(uv,uv)); - float opacity = 1. - step(0.5, len); - - float base = abs(floor(start / twopi)) * twopi; - start += base; - end += base; - - float intensity = 0.; - for (int i = 0; i < 5; i++) - { - intensity += max(step(start, angle) - step(end, angle), 0.); - angle += twopi; - } - gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity; - }`;class c2 extends r3{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=rr.P.Zero()),rr.P.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=rr.P.Zero()),rr.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=rr.P.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();let e=rr.P.Cross(this.direction,rO.RD.Y),t=rr.P.Cross(e,this.direction);return rr.P.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=rr.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=rr.y3.Identity()),rr.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,r0.gn)([(0,rg.hd)()],c2.prototype,"position",null),(0,r0.gn)([(0,rg.hd)()],c2.prototype,"direction",null),(0,r0.gn)([(0,rg.qC)()],c2.prototype,"shadowMinZ",null),(0,r0.gn)([(0,rg.qC)()],c2.prototype,"shadowMaxZ",null),rT.N.AddNodeConstructor("Light_Type_1",(e,t)=>()=>new c3(e,rr.P.Zero(),t));class c3 extends c2{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 r3.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){let t=this.getScene().activeCamera;t&&rr.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){let r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){let e=rr.P.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;let r=Number.MAX_VALUE,s=Number.MIN_VALUE;for(let n=0;n<i.length;n++){let a=i[n];if(!a)continue;let o=a.getBoundingInfo(),l=o.boundingBox;for(let i=0;i<l.vectorsWorld.length;i++)rr.P.TransformCoordinatesToRef(l.vectorsWorld[i],t,e),e.x<this._orthoLeft&&(this._orthoLeft=e.x),e.y<this._orthoBottom&&(this._orthoBottom=e.y),e.x>this._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.z<r&&(r=e.z),e.z>s&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=r,this._shadowMaxZ=s)}let s=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;rr.y3.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?o:a,l?a:o,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){let t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){let t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function c4(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);let r=ha("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=hc("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=r;let n=rq.Kj.MergeMeshes([s,r],!0);return n.name=e,n}(0,r0.gn)([(0,rg.qC)()],c3.prototype,"shadowFrustumSize",null),(0,r0.gn)([(0,rg.qC)()],c3.prototype,"shadowOrthoScale",null),(0,r0.gn)([(0,rg.qC)()],c3.prototype,"autoUpdateExtends",void 0),(0,r0.gn)([(0,rg.qC)()],c3.prototype,"autoCalcShadowZBounds",void 0),(0,r0.gn)([(0,rg.qC)("orthoLeft")],c3.prototype,"_orthoLeft",void 0),(0,r0.gn)([(0,rg.qC)("orthoRight")],c3.prototype,"_orthoRight",void 0),(0,r0.gn)([(0,rg.qC)("orthoTop")],c3.prototype,"_orthoTop",void 0),(0,r0.gn)([(0,rg.qC)("orthoBottom")],c3.prototype,"_orthoBottom",void 0),rq.Kj.CreateHemisphere=(e,t,i,r)=>c4(e,{segments:t,diameter:i},r),rT.N.AddNodeConstructor("Light_Type_2",(e,t)=>()=>new c5(e,rr.P.Zero(),rr.P.Zero(),0,0,t));class c5 extends c2{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()&&(c5._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):c5._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()})))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,r,s,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=rr.y3.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=rr.P.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=rr.P.Zero(),this._projectionTextureViewLightMatrix=rr.y3.Zero(),this._projectionTextureProjectionLightMatrix=rr.y3.Zero(),this._projectionTextureScalingMatrix=rr.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=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return r3.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;let s=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;rr.y3.PerspectiveFovLHToRef(s,1,o?a:n,o?n:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.direction,this._projectionTextureViewTargetVector),rr.y3.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;let e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);rr.y3.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof sv){let e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;rr.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=rr.P.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=rr.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()?rr.P.Normalize(this.transformedDirection):rr.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){let 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){let 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,r0.gn)([(0,rg.qC)()],c5.prototype,"angle",null),(0,r0.gn)([(0,rg.qC)()],c5.prototype,"innerAngle",null),(0,r0.gn)([(0,rg.qC)()],c5.prototype,"shadowAngleScale",null),(0,r0.gn)([(0,rg.qC)()],c5.prototype,"exponent",void 0),(0,r0.gn)([(0,rg.qC)()],c5.prototype,"projectionTextureLightNear",null),(0,r0.gn)([(0,rg.qC)()],c5.prototype,"projectionTextureLightFar",null),(0,r0.gn)([(0,rg.qC)()],c5.prototype,"projectionTextureUpDirection",null),(0,r0.gn)([(0,rg.oU)("projectedLightTexture")],c5.prototype,"_projectionTexture",void 0);class c6 extends ht{constructor(e=he.DefaultUtilityLayer){super(e),this._cachedPosition=new rr.P,this._cachedForward=new rr.P(0,0,1),this._pointerObserver=null,this.onClickedObservable=new ri.y$,this._light=null,this.attachedMesh=new r$.x("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new rK.Y("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new lC("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new rs.Wo(.5,.5,.5),this._material.specularColor=new rs.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))},sy.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(),e instanceof oa?this._lightMesh=c6._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof c3?this._lightMesh=c6._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof c5?this._lightMesh=c6._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=c6._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._lightMesh.parent=this._rootMesh;let t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new rr._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);let t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(rr.jp.Vector3[0]),e=rr.jp.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position){if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{let e=this.attachedMesh.position;this._light.position=new rr.P(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}}if(this._light.direction){let e=this._getMeshForward();rr.P.DistanceSquared(e,this._cachedForward)>1e-4?(this._light.direction=new rr.P(e.x,e.y,e.z),this._cachedForward.copyFrom(e)):rr.P.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){let t=new rq.Kj("hemisphereLight",e),i=c4(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;let r=this._CreateLightLines(3,e);return r.parent=t,t.scaling.scaleInPlace(c6._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){let t=new rq.Kj("pointLight",e),i=ha(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;let r=this._CreateLightLines(5,e);return r.parent=t,t.scaling.scaleInPlace(c6._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){let t=new rq.Kj("spotLight",e),i=ha(t.name,{segments:10,diameter:1},e);i.parent=t;let r=c4(t.name,{segments:10,diameter:2},e);r.parent=t,r.rotation.x=-Math.PI/2;let s=this._CreateLightLines(2,e);return s.parent=t,t.scaling.scaleInPlace(c6._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){let t=new rq.Kj("directionalLight",e),i=new rq.Kj(t.name,e);i.parent=t;let r=ha(t.name,{diameter:1.2,segments:10},e);r.parent=i;let s=lV(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=1.25;let a=s.clone(t.name);a.scaling.y=.5,a.position.x+=-1.25;let o=lV(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,(n=o.clone(t.name)).position.y=1.5,n.position.x+=1.25,(a=o.clone(t.name)).position.y=1.5,a.position.x+=-1.25,i.scaling.scaleInPlace(c6._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}c6._Scale=.007,c6._CreateLightLines=(e,t)=>{let i=new rq.Kj("root",t);i.rotation.x=Math.PI/2;let r=new rq.Kj("linePivot",t);r.parent=i;let s=lV("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=r,e<2)return r;for(let e=0;e<4;e++){let t=r.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<5)return i;let n=r.clone("linePivotClone");return n.rotation.z=Math.PI,i};class c8 extends ht{constructor(e=he.DefaultUtilityLayer){super(e),this._pointerObserver=null,this.onClickedObservable=new ri.y$,this._camera=null,this._invProjection=new rr.y3,this._material=new lC("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new rs.Wo(.5,.5,.5),this._material.specularColor=new rs.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))},sy.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=c8._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraLinesMesh=c8._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;let 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){let t=new rq.Kj("rootCameraGizmo",e),i=new rq.Kj(t.name,e);i.parent=t;let r=hs(t.name,{width:1,height:.8,depth:.5},e);r.parent=i;let s=lV(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;let n=lV(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);n.parent=i,n.position.y=.5,n.position.x=.4,n.rotation.x=.5*Math.PI;let a=lV(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return a.parent=i,a.position.y=0,a.position.x=.6,a.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(c8._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e){let t=new rq.Kj("rootCameraGizmo",e),i=new rq.Kj(t.name,e);i.parent=t;for(let t=0;t<4;t+=2)for(let r=0;r<4;r+=2){let s=hC("lines",{points:[new rr.P(-1+r,-1+t,-1),new rr.P(-1+r,-1+t,1)]},e);s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=hC("lines",{points:[new rr.P(-1,-1+r,-1+t),new rr.P(1,-1+r,-1+t)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=hC("lines",{points:[new rr.P(-1+r,-1,-1+t),new rr.P(-1+r,1,-1+t)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1}return t}}c8._Scale=.05,no.v.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";let c7=`vec4 pack(float depth) -{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} -float unpack(vec4 color) -{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;no.v.IncludesShadersStore.packingFunctions=c7;let c9=`#ifdef DOF -factor=sampleCoC(sampleCoord{X}); -computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; -#else -computedWeight=KERNEL_WEIGHT{X}; -#endif -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; -#else -blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; -#endif -`;no.v.IncludesShadersStore.kernelBlurFragment=c9;let de=`#ifdef DOF -factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; -#else -computedWeight=KERNEL_DEP_WEIGHT{X}; -#endif -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; -#else -blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; -#endif -`;no.v.IncludesShadersStore.kernelBlurFragment2=de;let dt=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; -#ifdef DOF -uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } -#endif -#include<kernelBlurVaryingDeclaration>[0..varyingCount] -#ifdef PACKEDFLOAT -#include<packingFunctions> -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float computedWeight=0.0; -#ifdef PACKEDFLOAT -float blend=0.; -#else -vec4 blend=vec4(0.); -#endif -#ifdef DOF -float sumOfWeights=CENTER_WEIGHT; -float factor=0.0; -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; -#else -blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; -#endif -#endif -#include<kernelBlurFragment>[0..varyingCount] -#include<kernelBlurFragment2>[0..depCount] -#ifdef PACKEDFLOAT -gl_FragColor=pack(blend); -#else -gl_FragColor=blend; -#endif -#ifdef DOF -gl_FragColor/=sumOfWeights; -#endif -}`;no.v.ShadersStore.kernelBlurPixelShader=dt,no.v.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";let di=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; -#include<kernelBlurVaryingDeclaration>[0..varyingCount] -const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -sampleCenter=(position*madd+madd); -#include<kernelBlurVertex>[0..varyingCount] -gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.kernelBlurVertexShader=di;class dr extends np{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,r,s,n=sv.BILINEAR_SAMPLINGMODE,a,o,l=0,h="",u=!1,c=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],r,s,n,a,o,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,c),this._blockCompilation=u,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,r,s,n){this._updateParameters(s,n)}_updateParameters(e,t){let i=this._kernel,r=(i-1)/2,s=[],n=[],a=0;for(let e=0;e<i;e++){let t=e/(i-1),o=this._gaussianWeight(2*t-1);s[e]=e-r,n[e]=o,a+=o}for(let e=0;e<n.length;e++)n[e]/=a;let o=[],l=[],h=[];for(let e=0;e<=r;e+=2){let t=Math.min(e+1,Math.floor(r)),i=e===t;if(i)h.push({o:s[e],w:n[e]});else{let i=t===r,a=n[e]+n[t]*(i?.5:1),o=s[e]+1/(1+n[e]/n[t]);0===o?(h.push({o:s[e],w:n[e]}),h.push({o:s[e+1],w:n[e+1]})):(h.push({o:o,w:a}),h.push({o:-o,w:a}))}}for(let e=0;e<h.length;e++)l[e]=h[e].o,o[e]=h[e].w;s=l,n=o;let u=this.getEngine().getCaps().maxVaryingVectors,c=Math.max(u,0)-1,d=Math.min(s.length,c),p="";p+=this._staticDefines,-1!=this._staticDefines.indexOf("DOF")&&(p+=`#define CENTER_WEIGHT ${this._glslFloat(n[d-1])} -`,d--);for(let e=0;e<d;e++)p+=`#define KERNEL_OFFSET${e} ${this._glslFloat(s[e])} -#define KERNEL_WEIGHT${e} ${this._glslFloat(n[e])} -`;let _=0;for(let e=c;e<s.length;e++)p+=`#define KERNEL_DEP_OFFSET${_} ${this._glslFloat(s[e])} -#define KERNEL_DEP_WEIGHT${_} ${this._glslFloat(n[e])} -`,_++;this.packedFloat&&(p+="#define PACKEDFLOAT 1"),this._blockCompilation=!1,super.updateEffect(p,null,null,{varyingCount:d,depCount:_},e,t)}_nearestBestKernel(e){let t=Math.round(e);for(let e of[t,t-1,t+1,t-2,t+2])if(e%2!=0&&Math.floor(e/2)%2==0&&e>0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){let t=1/3;return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(-(e*e/(2*t*t)))}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new dr(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}}(0,r0.gn)([(0,rg.qC)("kernel")],dr.prototype,"_kernel",void 0),(0,r0.gn)([(0,rg.qC)("packedFloat")],dr.prototype,"_packedFloat",void 0),(0,r0.gn)([(0,rg.QC)()],dr.prototype,"direction",void 0),(0,rn.H)("BABYLON.BlurPostProcess",dr);class ds extends nV{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(){let 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(){let e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,s=0,n=sv.BILINEAR_SAMPLINGMODE,a=!0){let o;if(super(e,t,i,r,!0,s,!1,n,a),this.mirrorPlane=new sp.J(0,1,0,1),this._transformMatrix=rr.y3.Zero(),this._mirrorMatrix=rr.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()});let l=i.getEngine();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()),rr.y3.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),o=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=rr.P.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=o})}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){let e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new dr("horizontal blur",new rr.FM(1,0),this._blurKernelX,this._blurRatio,null,sv.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 dr("vertical blur",new rr.FM(0,1),this._blurKernelY,this._blurRatio,null,sv.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(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new ds(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;let e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();let t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}}sv._CreateMirror=(e,t,i,r)=>new ds(e,t,i,r);class dn extends su{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(rr.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 r="";return e.forEach(e=>r+=e),new dn(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){let s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;let n=new dn(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=s,n}constructor(e,t,i=null,r=!1,s=null,n=null,a=null,o=5,l=!1,h=null,u=!1,c=.8,d=0,p,_){var f;if(super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new ri.y$,this.boundingBoxPosition=rr.P.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new rr.y3,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this._format=o,this.isCube=!0,this._textureMatrix=rr.y3.Identity(),this._createPolynomials=u,this.coordinatesMode=sv.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=h,this._loaderOptions=p,this._useSRGBBuffer=_,this._lodScale=c,this._lodOffset=d,!e&&!s)return;this.updateURL(e,h,n,l,a,i,null===(f=this.getScene())||void 0===f?void 0:f.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,r=!1,s=null,n=null,a=!1,o=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);let l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),u=0===h.indexOf(".dds"),c=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(c?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(d||c||u||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let t=0;t<n.length;t++)this._files.push(e+n[t]);this._extensions=n}a?(this.delayLoadState=4,this._delayedOnLoad=i,this._delayedOnError=s):this._loadTexture(i,s)}delayLoad(e){4===this.delayLoadState&&(e&&(this._forcedExtension=e),this.delayLoadState=1,this._loadTexture(this._delayedOnLoad,this._delayedOnError))}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t,i;if(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))),this._textureMatrix=e,!(null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem)))return;let r=rr.jp.Vector3[0],s=rr.jp.Quaternion[0],n=rr.jp.Vector3[1];this._textureMatrix.decompose(r,s,n),s.z*=-1,s.w*=-1,rr.y3.ComposeToRef(r,s,n,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;let r=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);let n=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},a=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),sv.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?rZ.w1.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(()=>n()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,r,this._lodScale,this._lodOffset,e,a,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,r,this._files,this._noMipmap,e,a,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){let r=rg.p4.Parse(()=>{var r;let s=!1;return e.prefiltered&&(s=e.prefiltered),new dn(i+(null!==(r=e.url)&&void 0!==r?r:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=rr.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=rr.P.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t<e.animations.length;t++){let i=e.animations[t],s=(0,rn.q)("BABYLON.Animation");s&&r.animations.push(s.Parse(i))}return r}clone(){let e=0,t=rg.p4.Clone(()=>{let t=new dn(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t},this);return t.uniqueId=e,t}}(0,r0.gn)([(0,rg.qC)()],dn.prototype,"url",void 0),(0,r0.gn)([(0,rg.hd)()],dn.prototype,"boundingBoxPosition",void 0),(0,r0.gn)([(0,rg.hd)()],dn.prototype,"boundingBoxSize",null),(0,r0.gn)([(0,rg.qC)("rotationY")],dn.prototype,"rotationY",null),(0,r0.gn)([(0,rg.qC)("files")],dn.prototype,"_files",void 0),(0,r0.gn)([(0,rg.qC)("forcedExtension")],dn.prototype,"_forcedExtension",void 0),(0,r0.gn)([(0,rg.qC)("extensions")],dn.prototype,"_extensions",void 0),(0,r0.gn)([(0,rg.oQ)("textureMatrix")],dn.prototype,"_textureMatrix",void 0),(0,r0.gn)([(0,rg.oQ)("textureMatrixRefraction")],dn.prototype,"_textureMatrixRefraction",void 0),sv._CubeTextureParser=dn.Parse,(0,rn.H)("BABYLON.CubeTexture",dn);let da=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; -#ifdef USEHIGHLIGHTANDSHADOWCOLORS -uniform vec4 vPrimaryColorShadow; -#endif -uniform float shadowLevel;uniform float alpha; -#ifdef DIFFUSE -uniform vec2 vDiffuseInfos; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; -#endif -#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) -uniform vec3 vBackgroundCenter; -#endif -#ifdef REFLECTIONFRESNEL -uniform vec4 vReflectionControl; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) -uniform mat4 view; -#endif -`;no.v.IncludesShadersStore.backgroundFragmentDeclaration=da;let dl=`layout(std140,column_major) uniform;uniform Material -{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha; -#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) -uniform vec3 vBackgroundCenter; -#endif -#ifdef REFLECTIONFRESNEL -uniform vec4 vReflectionControl; -#endif -}; -#include<sceneUboDeclaration> -`;no.v.IncludesShadersStore.backgroundUboDeclaration=dl;let dh=`#ifdef TEXTURELODSUPPORT -#extension GL_EXT_shader_texture_lod : enable -#endif -precision highp float; -#include<__decl__backgroundFragment> -#include<helperFunctions> -#define RECIPROCAL_PI2 0.15915494 -varying vec3 vPositionW; -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef DIFFUSE -#if DIFFUSEDIRECTUV==1 -#define vDiffuseUV vMainUV1 -#elif DIFFUSEDIRECTUV==2 -#define vDiffuseUV vMainUV2 -#else -varying vec2 vDiffuseUV; -#endif -uniform sampler2D diffuseSampler; -#endif -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -#define sampleReflection(s,c) textureCube(s,c) -uniform samplerCube reflectionSampler; -#ifdef TEXTURELODSUPPORT -#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#else -#define sampleReflection(s,c) texture2D(s,c) -uniform sampler2D reflectionSampler; -#ifdef TEXTURELODSUPPORT -#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#include<reflectionFunction> -#endif -#ifndef FROMLINEARSPACE -#define FROMLINEARSPACE; -#endif -#ifndef SHADOWONLY -#define SHADOWONLY; -#endif -#include<imageProcessingDeclaration> -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include<lightsFragmentFunctions> -#include<shadowsFragmentFunctions> -#include<imageProcessingFunctions> -#include<clipPlaneFragmentDeclaration> -#include<fogFragmentDeclaration> -#ifdef REFLECTIONFRESNEL -#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 -vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) -{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=vec3(0.0,1.0,0.0); -#endif -float shadow=1.;float globalShadow=0.;float shadowLightCount=0.; -#include<lightFragment>[0..maxSimultaneousLights] -#ifdef SHADOWINUSE -globalShadow/=shadowLightCount; -#else -globalShadow=1.0; -#endif -#ifndef BACKMAT_SHADOWONLY -vec4 reflectionColor=vec4(1.,1.,1.,1.); -#ifdef REFLECTION -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords=reflectionVector; -#else -vec2 reflectionCoords=reflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -reflectionCoords/=reflectionVector.z; -#endif -reflectionCoords.y=1.0-reflectionCoords.y; -#endif -#ifdef REFLECTIONBLUR -float reflectionLOD=vReflectionInfos.y; -#ifdef TEXTURELODSUPPORT -reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); -#else -float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( -sampleReflection(reflectionSamplerHigh,reflectionCoords), -reflectionSpecularMid, -lodReflectionNormalizedDoubled -);} else {reflectionColor=mix( -reflectionSpecularMid, -sampleReflection(reflectionSamplerLow,reflectionCoords), -lodReflectionNormalizedDoubled-1.0 -);} -#endif -#else -vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; -#endif -#ifdef RGBDREFLECTION -reflectionColor.rgb=fromRGBD(reflectionColor); -#endif -#ifdef GAMMAREFLECTION -reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); -#endif -#ifdef REFLECTIONBGR -reflectionColor.rgb=reflectionColor.bgr; -#endif -reflectionColor.rgb*=vReflectionInfos.x; -#endif -vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; -#ifdef DIFFUSE -vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); -#ifdef GAMMADIFFUSE -diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); -#endif -diffuseMap.rgb*=vDiffuseInfos.y; -#ifdef DIFFUSEHASALPHA -finalAlpha*=diffuseMap.a; -#endif -diffuseColor=diffuseMap.rgb; -#endif -#ifdef REFLECTIONFRESNEL -vec3 colorBase=diffuseColor; -#else -vec3 colorBase=reflectionColor.rgb*diffuseColor; -#endif -colorBase=max(colorBase,0.0); -#ifdef USERGBCOLOR -vec3 finalColor=colorBase; -#else -#ifdef USEHIGHLIGHTANDSHADOWCOLORS -vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); -#else -vec3 mainColor=vPrimaryColor.rgb; -#endif -vec3 finalColor=colorBase*mainColor; -#endif -#ifdef REFLECTIONFRESNEL -vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; -#ifdef REFLECTIONFALLOFF -float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; -#endif -finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); -#endif -#ifdef OPACITYFRESNEL -float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; -#endif -#ifdef SHADOWINUSE -finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); -#endif -vec4 color=vec4(finalColor,finalAlpha); -#else -vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); -#endif -#include<fogFragment> -#ifdef IMAGEPROCESSINGPOSTPROCESS -#if !defined(SKIPFINALCOLORCLAMP) -color.rgb=clamp(color.rgb,0.,30.0); -#endif -#else -color=applyImageProcessing(color); -#endif -#ifdef PREMULTIPLYALPHA -color.rgb*=color.a; -#endif -#ifdef NOISE -color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); -#endif -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -} -`;no.v.ShadersStore.backgroundPixelShader=dh;let du=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; -#ifdef DIFFUSE -uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -`;no.v.IncludesShadersStore.backgroundVertexDeclaration=du;let dc=`precision highp float; -#include<__decl__backgroundVertex> -#include<helperFunctions> -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<instancesDeclaration> -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 -varying vec2 vDiffuseUV; -#endif -#include<clipPlaneVertexDeclaration> -#include<fogVertexDeclaration> -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=position; -#endif -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} -#else -gl_Position=viewProjection*finalWorld*vec4(position,1.0); -#endif -vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normal); -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); -#ifdef EQUIRECTANGULAR_RELFECTION_FOV -mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} -#endif -#endif -#ifndef UV1 -vec2 uv=vec2(0.,0.); -#endif -#ifndef UV2 -vec2 uv2=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uv; -#endif -#ifdef MAINUV2 -vMainUV2=uv2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 -if (vDiffuseInfos.x==0.) -{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} -else -{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} -#endif -#include<clipPlaneVertex> -#include<fogVertex> -#include<shadowsVertex>[0..maxSimultaneousLights] -#ifdef VERTEXCOLOR -vColor=color; -#endif -#if defined(POINTSIZE) && !defined(WEBGPU) -gl_PointSize=pointSize; -#endif -#define CUSTOM_VERTEX_MAIN_END -} -`;no.v.ShadersStore.backgroundVertexShader=dc;class dd extends s$.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 dp extends sY{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=dp.StandardReflectance0*t,this.reflectionReflectance90=dp.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=dp.StandardReflectance0+(1-dp.StandardReflectance0)*t,this.reflectionReflectance90=dp.StandardReflectance90+(1-dp.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()})))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=rs.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=rr.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 na.t(16),this._reflectionControls=rr.Lt.Zero(),this._white=rs.Wo.White(),this._primaryShadowColor=rs.Wo.Black(),this._primaryHighlightColor=rs.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 dd);let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();if(s3.G.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,s3.G.PrepareDefinesForMultiview(r,s),s._areTexturesDirty){if(s._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&od.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;s3.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;let e=this._reflectionTexture;if(e&&od.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===sv.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 sv.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case sv.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case sv.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case sv.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case sv.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case sv.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case sv.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case sv.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case sv.CUBIC_MODE:case sv.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(s3.G.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),s3.G.PrepareDefinesForFrameBoundValues(r,n,this,s,i,null,t.getRenderingMesh().hasThinInstances),s3.G.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&!r.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(rQ.o.NormalKind)&&(e.createNormals(!0),ru.Y.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();let i=new nn;s.FOG&&i.addFallback(0,"FOG"),s.POINTSIZE&&i.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),s3.G.HandleFallbacksForShadows(s,i,this._maxSimultaneousLights);let a=[rQ.o.PositionKind];s.NORMAL&&a.push(rQ.o.NormalKind),s.UV1&&a.push(rQ.o.UVKind),s.UV2&&a.push(rQ.o.UV2Kind),s3.G.PrepareAttributesForBones(a,e,s,i),s3.G.PrepareAttributesForInstances(a,s);let o=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"];(0,lx.qx)(o);let l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];ng.$&&(ng.$.PrepareUniforms(o,s),ng.$.PrepareSamplers(l,s)),s3.G.PrepareUniformsAndSamplersList({uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});let u=s.toString(),c=r.getEngine().createEffect("background",{attributes:a,uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:u,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},n);t.setEffect(c,s,this._materialContext),this.buildUniformLayout()}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.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){let r=this.getScene(),s=i.materialDefines;if(!s)return;let n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),s3.G.BindBonesParameters(t,this._activeEffect);let a=this._mustRebind(r,n,t.visibility);if(a){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);let e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(r.texturesEnabled&&(this._diffuseTexture&&od.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),s3.G.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&od.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&od.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&od.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,lx.an)(this._activeEffect,this,r),r.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(a||!this.isFrozen)&&(r.lightsEnabled&&s3.G.BindLights(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(n),s3.G.BindFogParameters(r,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 rg.p4.Clone(()=>new dp(e,this.getScene()),this)}serialize(){let e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return rg.p4.Parse(()=>new dp(e.name,t),e,t,i)}}dp.StandardReflectance0=.05,dp.StandardReflectance90=.5,(0,r0.gn)([(0,rg.n9)()],dp.prototype,"_primaryColor",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsLightsDirty")],dp.prototype,"primaryColor",void 0),(0,r0.gn)([(0,rg.n9)()],dp.prototype,"__perceptualColor",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_primaryColorShadowLevel",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_primaryColorHighlightLevel",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsLightsDirty")],dp.prototype,"primaryColorHighlightLevel",null),(0,r0.gn)([(0,rg.oU)()],dp.prototype,"_reflectionTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"reflectionTexture",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_reflectionBlur",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"reflectionBlur",void 0),(0,r0.gn)([(0,rg.oU)()],dp.prototype,"_diffuseTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"diffuseTexture",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"shadowLights",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_shadowLevel",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"shadowLevel",void 0),(0,r0.gn)([(0,rg.hd)()],dp.prototype,"_sceneCenter",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"sceneCenter",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_opacityFresnel",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"opacityFresnel",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_reflectionFresnel",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"reflectionFresnel",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_reflectionFalloffDistance",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"reflectionFalloffDistance",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_reflectionAmount",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"reflectionAmount",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_reflectionReflectance0",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"reflectionReflectance0",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_reflectionReflectance90",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"reflectionReflectance90",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_useRGBColor",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"useRGBColor",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_enableNoise",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"enableNoise",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_maxSimultaneousLights",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],dp.prototype,"maxSimultaneousLights",void 0),(0,r0.gn)([(0,rg.qC)()],dp.prototype,"_shadowOnly",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsLightsDirty")],dp.prototype,"shadowOnly",void 0),(0,r0.gn)([(0,rg.rX)()],dp.prototype,"_imageProcessingConfiguration",void 0),(0,rn.H)("BABYLON.BackgroundMaterial",dp);class d_{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new rs.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 rs.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:rr.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({},d_._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new ri.y$,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){let 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 rs.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 su){this._scene.environmentTexture=this._options.environmentTexture;return}let e=dn.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new rq.Kj("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;let 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};let r=this._scene.getWorldExtends(e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox),s=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof aA&&this._scene.activeCamera.upperRadiusLimit&&(t=e=2*this._scene.activeCamera.upperRadiusLimit);let n=s.length();n>e&&(t=e=2*n),e*=1.1,t*=1.5,(i=r.min.add(s.scale(.5))).y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=sL("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 dp("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof su){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new sv(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){let t=sv.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new ds("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,sv.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new sp.J(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e<this._scene.meshes.length;e++){let t=this._scene.meshes[e];t!==this._ground&&t!==this._skybox&&t!==this._rootMesh&&this._groundMirror.renderList.push(t)}let i=this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions);this._groundMirror.clearColor=new rs.HE(i.r,i.g,i.b,1),this._groundMirror.adaptiveBlurKernel=this._options.groundMirrorBlurKernel}_setupMirrorInGroundMaterial(){this._groundMaterial&&(this._groundMaterial.reflectionTexture=this._groundMirror,this._groundMaterial.reflectionFresnel=!0,this._groundMaterial.reflectionAmount=this._options.groundMirrorAmount,this._groundMaterial.reflectionStandardFresnelWeight=this._options.groundMirrorFresnelWeight,this._groundMaterial.reflectionFalloffDistance=this._options.groundMirrorFallOffDistance)}_setupSkybox(e){(!this._skybox||this._skybox.isDisposed())&&(this._skybox=hs("BackgroundSkybox",{size:e.skyboxSize,sideOrientation:rq.Kj.BACKSIDE},this._scene),this._skybox.onDisposeObservable.add(()=>{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new dp("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){if(this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof su){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new dn(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=sv.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)}}d_._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",d_._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",d_._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class df extends rK.Y{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=sv.CLAMP_ADDRESSMODE,this._texture.wrapV=sv.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=sv.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=sv.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=df.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new ri.y$,this.onLoadObservable=new ri.y$,r=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=!!i.clickToPlay,i.autoPlay=void 0===i.autoPlay||!!i.autoPlay,i.loop=void 0===i.loop||!!i.loop,i.size=Math.abs(i.size)||(r.activeCamera?.48*r.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=ha(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:rq.Kj.BACKSIDE},r);let n=this._material=new dp(e+"_material",r);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;let a=this._initTexture(t,r,i);if(this.texture=a,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=ha("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:rq.Kj.BACKSIDE},r),this._halfDomeMask.rotate(rO.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&&r.activeCamera){let e=r.activeCamera,t=rr.P.Forward(),i=rr.P.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(rr.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 df.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case df.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;let e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(i=>{let r=i.isRightCamera;this._crossEye&&(r=!r),r?this._texture.uOffset=e:this._texture.uOffset=t});break}case df.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)}}df.MODE_MONOSCOPIC=0,df.MODE_TOPBOTTOM=1,df.MODE_SIDEBYSIDE=2;class dm extends df{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 sv(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)})}}dm.MODE_MONOSCOPIC=df.MODE_MONOSCOPIC,dm.MODE_TOPBOTTOM=df.MODE_TOPBOTTOM,dm.MODE_SIDEBYSIDE=df.MODE_SIDEBYSIDE;let dg=0,dv=e=>{if(!e.environmentBRDFTexture){let t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;let i=e._blockEntityCollection;e._blockEntityCollection=!1;let r=sv.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+dg++,e,!0,!1,sv.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;let s=e.getEngine().getLoadedTexturesCache(),n=s.indexOf(r.getInternalTexture());-1!==n&&s.splice(n,1),r.isRGBD=!0,r.wrapU=sv.CLAMP_ADDRESSMODE,r.wrapV=sv.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=r,e.useDelayedTextureLoading=t,h7.ExpandRGBDTexture(r);let a=e.getEngine().onContextRestoredObservable.add(()=>{r.isRGBD=!0;let e=()=>{r.isReady()?h7.ExpandRGBDTexture(r):rZ.w1.SetImmediate(e)};e()});e.onDisposeObservable.add(()=>{e.getEngine().onContextRestoredObservable.remove(a)})}return e.environmentBRDFTexture};class dT extends s$.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 dx extends lg{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new dT,t),this._useEnergyConservation=dx.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=dx.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=dx.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=dx.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=dx.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=dx.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=dx.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=dx.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"}}dx.DEFAULT_USE_ENERGY_CONSERVATION=!0,dx.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,dx.DEFAULT_USE_SPHERICAL_HARMONICS=!0,dx.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsMiscDirty")],dx.prototype,"useEnergyConservation",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsMiscDirty")],dx.prototype,"useSmithVisibilityHeightCorrelated",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsMiscDirty")],dx.prototype,"useSphericalHarmonics",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsMiscDirty")],dx.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);let dS=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; -#ifdef ALBEDO -uniform vec2 vAlbedoInfos; -#endif -#ifdef AMBIENT -uniform vec4 vAmbientInfos; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#ifdef OPACITY -uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos; -#endif -#ifdef REFLECTIVITY -uniform vec3 vReflectivityInfos; -#endif -#ifdef MICROSURFACEMAP -uniform vec2 vMicroSurfaceSamplerInfos; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) -uniform mat4 view; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos; -#ifdef REALTIME_FILTERING -uniform vec2 vReflectionFilteringInfo; -#endif -uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; -#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) -uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; -#endif -#ifdef CLEARCOAT -uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; -#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) -uniform vec4 vClearCoatInfos; -#endif -#ifdef CLEARCOAT_TEXTURE -uniform mat4 clearCoatMatrix; -#endif -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS -uniform mat4 clearCoatRoughnessMatrix; -#endif -#ifdef CLEARCOAT_BUMP -uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; -#endif -#ifdef CLEARCOAT_TINT -uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; -#ifdef CLEARCOAT_TINT_TEXTURE -uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; -#endif -#endif -#endif -#ifdef IRIDESCENCE -uniform vec4 vIridescenceParams; -#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) -uniform vec4 vIridescenceInfos; -#endif -#ifdef IRIDESCENCE_TEXTURE -uniform mat4 iridescenceMatrix; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -uniform mat4 iridescenceThicknessMatrix; -#endif -#endif -#ifdef ANISOTROPIC -uniform vec3 vAnisotropy; -#ifdef ANISOTROPIC_TEXTURE -uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; -#endif -#endif -#ifdef SHEEN -uniform vec4 vSheenColor; -#ifdef SHEEN_ROUGHNESS -uniform float vSheenRoughness; -#endif -#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) -uniform vec4 vSheenInfos; -#endif -#ifdef SHEEN_TEXTURE -uniform mat4 sheenMatrix; -#endif -#ifdef SHEEN_TEXTURE_ROUGHNESS -uniform mat4 sheenRoughnessMatrix; -#endif -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; -#ifdef REALTIME_FILTERING -uniform vec2 vRefractionFilteringInfo; -#endif -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; -#endif -uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity; -#endif -#ifdef PREPASS -#ifdef SS_SCATTERING -uniform float scatteringDiffusionProfile; -#endif -#endif -#if DEBUGMODE>0 -uniform vec2 vDebugMode; -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos; -#endif -#include<decalFragmentDeclaration> -#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; -#else -uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; -#endif -#endif -#define ADDITIONAL_FRAGMENT_DECLARATION -`;no.v.IncludesShadersStore.pbrFragmentDeclaration=dS;let dE=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; -#define ADDITIONAL_UBO_DECLARATION -}; -#include<sceneUboDeclaration> -#include<meshUboDeclaration> -`;no.v.IncludesShadersStore.pbrUboDeclaration=dE;let dC=`varying vec3 vPositionW; -#if DEBUGMODE>0 -varying vec4 vClipSpacePosition; -#endif -#include<mainUVVaryingDeclaration>[1..7] -#ifdef NORMAL -varying vec3 vNormalW; -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -varying vec3 vEnvironmentIrradiance; -#endif -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -`;no.v.IncludesShadersStore.pbrFragmentExtraDeclaration=dC;let db=`#ifdef _DEFINENAME_ -#if _DEFINENAME_DIRECTUV==1 -#define v_VARYINGNAME_UV vMainUV1 -#elif _DEFINENAME_DIRECTUV==2 -#define v_VARYINGNAME_UV vMainUV2 -#elif _DEFINENAME_DIRECTUV==3 -#define v_VARYINGNAME_UV vMainUV3 -#elif _DEFINENAME_DIRECTUV==4 -#define v_VARYINGNAME_UV vMainUV4 -#elif _DEFINENAME_DIRECTUV==5 -#define v_VARYINGNAME_UV vMainUV5 -#elif _DEFINENAME_DIRECTUV==6 -#define v_VARYINGNAME_UV vMainUV6 -#else -varying vec2 v_VARYINGNAME_UV; -#endif -#endif -`;no.v.IncludesShadersStore.samplerFragmentAlternateDeclaration=db;let dy=`#include<samplerFragmentDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) -#include<samplerFragmentDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) -#include<samplerFragmentDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) -#include<samplerFragmentDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) -#include<samplerFragmentDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) -#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) -#include<samplerFragmentDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) -#include<samplerFragmentDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) -#include<samplerFragmentDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) -#include<samplerFragmentDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) -#ifdef CLEARCOAT -#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) -#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) -uniform sampler2D clearCoatRoughnessSampler; -#endif -#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) -#include<samplerFragmentDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) -#endif -#ifdef IRIDESCENCE -#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) -#include<samplerFragmentDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) -#endif -#ifdef SHEEN -#include<samplerFragmentDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) -#include<samplerFragmentAlternateDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) -#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) -uniform sampler2D sheenRoughnessSampler; -#endif -#endif -#ifdef ANISOTROPIC -#include<samplerFragmentDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) -#endif -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -#define sampleReflection(s,c) textureCube(s,c) -uniform samplerCube reflectionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#ifdef USEIRRADIANCEMAP -uniform samplerCube irradianceSampler; -#endif -#else -#define sampleReflection(s,c) texture2D(s,c) -uniform sampler2D reflectionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; -#endif -#ifdef USEIRRADIANCEMAP -uniform sampler2D irradianceSampler; -#endif -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#endif -#ifdef ENVIRONMENTBRDF -uniform sampler2D environmentBrdfSampler; -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -#ifdef SS_REFRACTIONMAP_3D -#define sampleRefraction(s,c) textureCube(s,c) -uniform samplerCube refractionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; -#endif -#else -#define sampleRefraction(s,c) texture2D(s,c) -uniform sampler2D refractionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; -#endif -#endif -#endif -#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) -#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) -#include<samplerFragmentDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) -#endif -`;no.v.IncludesShadersStore.pbrFragmentSamplersDeclaration=dy;let dA=`bool testLightingForSSS(float diffusionProfile) -{return diffusionProfile<1.;}`;no.v.IncludesShadersStore.subSurfaceScatteringFunctions=dA;let dR=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} -vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} -vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { -float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;no.v.IncludesShadersStore.importanceSampling=dR;let dP=`#define RECIPROCAL_PI2 0.15915494 -#define RECIPROCAL_PI 0.31830988618 -#define MINIMUMVARIANCE 0.0005 -float convertRoughnessToAverageSlope(float roughness) -{return square(roughness)+MINIMUMVARIANCE;} -float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} -vec2 getAARoughnessFactors(vec3 normalVector) { -#ifdef SPECULARAA -vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); -#else -return vec2(0.); -#endif -} -#ifdef ANISOTROPIC -#ifdef ANISOTROPIC_LEGACY -vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} -vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} -#else -vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} -vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} -#endif -#endif -#if defined(CLEARCOAT) || defined(SS_REFRACTION) -vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} -vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} -vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} -vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), -cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), -clearCoatIntensity);return clearCoatAbsorption;} -#endif -#ifdef MICROSURFACEAUTOMATIC -float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) -{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} -#endif -`;no.v.IncludesShadersStore.pbrHelperFunctions=dP;let dI=`#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 -+ vSphericalL1_1*(normal.y) -+ vSphericalL10*(normal.z) -+ vSphericalL11*(normal.x) -+ vSphericalL2_2*(normal.y*normal.x) -+ vSphericalL2_1*(normal.y*normal.z) -+ vSphericalL20*((3.0*normal.z*normal.z)-1.0) -+ vSphericalL21*(normal.z*normal.x) -+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} -#else -vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} -#endif -#endif -`;no.v.IncludesShadersStore.harmonicsFunctions=dI;let dM=`struct preLightingInfo -{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; -#ifdef IRIDESCENCE -float iridescenceIntensity; -#endif -};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} -preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} -preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; -#ifdef SPECULARTERM -result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); -#endif -return result;}`;no.v.IncludesShadersStore.pbrDirectLightingSetupFunctions=dM;let dD=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) -{return max(0.,1.0-length(lightOffset)/range);} -float computeDistanceLightFalloff_Physical(float lightDistanceSquared) -{return 1.0/maxEps(lightDistanceSquared);} -float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) -{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} -float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) -{ -#ifdef USEPHYSICALLIGHTFALLOFF -return computeDistanceLightFalloff_Physical(lightDistanceSquared); -#elif defined(USEGLTFLIGHTFALLOFF) -return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); -#else -return computeDistanceLightFalloff_Standard(lightOffset,range); -#endif -} -float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) -{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) -{falloff=max(0.,pow(cosAngle,exponent));} -return falloff;} -float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) -{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; -float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} -float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) -{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} -float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) -{ -#ifdef USEPHYSICALLIGHTFALLOFF -return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); -#elif defined(USEGLTFLIGHTFALLOFF) -return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); -#else -return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); -#endif -}`;no.v.IncludesShadersStore.pbrDirectLightingFalloffFunctions=dD;let dO=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 -#ifdef MS_BRDF_ENERGY_CONSERVATION -vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} -#endif -#ifdef ENVIRONMENTBRDF -vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); -#ifdef ENVIRONMENTBRDF_RGBD -brdfLookup.rgb=fromRGBD(brdfLookup.rgba); -#endif -return brdfLookup.rgb;} -vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { -#ifdef BRDF_V_HEIGHT_CORRELATED -vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; -#else -vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; -#endif -return reflectance;} -vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { -#ifdef BRDF_V_HEIGHT_CORRELATED -vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); -#else -vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; -#endif -return reflectance;} -#endif -/* NOT USED -#if defined(SHEEN) && defined(SHEEN_SOFTER) -float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) -{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} -#endif -*/ -#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) -vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) -{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) -/** -* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. -* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table -*/ -vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} -#endif -vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) -{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} -float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) -{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} -#ifdef CLEARCOAT -vec3 getR0RemappedForClearCoat(vec3 f0) { -#ifdef CLEARCOAT_DEFAULTIOR -#ifdef MOBILE -return saturate(f0*(f0*0.526868+0.529324)-0.0482256); -#else -return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); -#endif -#else -vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); -#endif -} -#endif -#ifdef IRIDESCENCE -const mat3 XYZ_TO_REC709=mat3( -3.2404542,-0.9692660, 0.0556434, --1.5371385, 1.8760108,-0.2040259, --0.4985314, 0.0415560, 1.0572252 -);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} -vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} -float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} -vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} -vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} -float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR<outsideIOR) phi12=PI;float phi21=PI-phi12;vec3 baseIOR=getIORTfromAirToSurfaceR0(clamp(baseF0,0.0,0.9999)); -vec3 R1=getR0fromIORs(baseIOR,iridescenceIOR);vec3 R23=fresnelSchlickGGX(cosTheta2,R1,vec3(1.));vec3 phi23=vec3(0.0);if (baseIOR[0]<iridescenceIOR) phi23[0]=PI;if (baseIOR[1]<iridescenceIOR) phi23[1]=PI;if (baseIOR[2]<iridescenceIOR) phi23[2]=PI;float opd=2.0*iridescenceIOR*thinFilmThickness*cosTheta2;vec3 phi=vec3(phi21)+phi23;vec3 R123=clamp(R12*R23,1e-5,0.9999);vec3 r123=sqrt(R123);vec3 Rs=square(T121)*R23/(vec3(1.0)-R123);vec3 C0=R12+Rs;I=C0;vec3 Cm=Rs-T121;for (int m=1; m<=2; ++m) -{Cm*=r123;vec3 Sm=2.0*evalSensitivity(float(m)*opd,float(m)*phi);I+=Cm*Sm;} -return max(I,vec3(0.0));} -#endif -float normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG) -{float a2=square(alphaG);float d=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);} -#ifdef SHEEN -float normalDistributionFunction_CharlieSheen(float NdotH,float alphaG) -{float invR=1./alphaG;float cos2h=NdotH*NdotH;float sin2h=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);} -#endif -#ifdef ANISOTROPIC -float normalDistributionFunction_BurleyGGX_Anisotropic(float NdotH,float TdotH,float BdotH,const vec2 alphaTB) {float a2=alphaTB.x*alphaTB.y;vec3 v=vec3(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);float v2=dot(v,v);float w2=a2/v2;return a2*w2*w2*RECIPROCAL_PI;} -#endif -#ifdef BRDF_V_HEIGHT_CORRELATED -float smithVisibility_GGXCorrelated(float NdotL,float NdotV,float alphaG) { -#ifdef MOBILE -float GGXV=NdotL*(NdotV*(1.0-alphaG)+alphaG);float GGXL=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL); -#else -float a2=alphaG*alphaG;float GGXV=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);float GGXL=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL); -#endif -} -#else -float smithVisibilityG1_TrowbridgeReitzGGXFast(float dot,float alphaG) -{ -#ifdef MOBILE -return 1.0/(dot+alphaG+(1.0-alphaG)*dot )); -#else -float alphaSquared=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot)); -#endif -} -float smithVisibility_TrowbridgeReitzGGXFast(float NdotL,float NdotV,float alphaG) -{float visibility=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;} -#endif -#ifdef ANISOTROPIC -float smithVisibility_GGXCorrelated_Anisotropic(float NdotL,float NdotV,float TdotV,float BdotV,float TdotL,float BdotL,const vec2 alphaTB) {float lambdaV=NdotL*length(vec3(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));float lambdaL=NdotV*length(vec3(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));float v=0.5/(lambdaV+lambdaL);return v;} -#endif -#ifdef CLEARCOAT -float visibility_Kelemen(float VdotH) {return 0.25/(VdotH*VdotH); } -#endif -#ifdef SHEEN -float visibility_Ashikhmin(float NdotL,float NdotV) -{return 1./(4.*(NdotL+NdotV-NdotL*NdotV));} -/* NOT USED -#ifdef SHEEN_SOFTER -float l(float x,float alphaG) -{float oneMinusAlphaSq=(1.0-alphaG)*(1.0-alphaG);float a=mix(21.5473,25.3245,oneMinusAlphaSq);float b=mix(3.82987,3.32435,oneMinusAlphaSq);float c=mix(0.19823,0.16801,oneMinusAlphaSq);float d=mix(-1.97760,-1.27393,oneMinusAlphaSq);float e=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;} -float lambdaSheen(float cosTheta,float alphaG) -{return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));} -float visibility_CharlieSheen(float NdotL,float NdotV,float alphaG) -{float G=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);} -#endif -*/ -#endif -float diffuseBRDF_Burley(float NdotL,float NdotV,float VdotH,float roughness) {float diffuseFresnelNV=pow5(saturateEps(1.0-NdotL));float diffuseFresnelNL=pow5(saturateEps(1.0-NdotV));float diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;float fresnel = -(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) * -(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;} -#ifdef SS_TRANSLUCENCY -vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);} -float computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);} -#endif -`;no.v.IncludesShadersStore.pbrBRDFFunctions=dO;let dN=`#ifdef NUM_SAMPLES -#if NUM_SAMPLES>0 -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -float radicalInverse_VdC(uint bits) -{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } -vec2 hammersley(uint i,uint N) -{return vec2(float(i)/float(N),radicalInverse_VdC(i));} -#else -float vanDerCorpus(int n,int base) -{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) -{if(n>0) -{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} -return result;} -vec2 hammersley(int i,int N) -{return vec2(float(i)/float(N),vanDerCorpus(i,2));} -#endif -float log4(float x) {return log2(x)/2.;} -const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; -#define inline -vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) -{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -for(uint i=0u; i<NUM_SAMPLES; ++i) -#else -for(int i=0; i<NUM_SAMPLES; ++i) -#endif -{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 Ls=hemisphereCosSample(Xi);Ls=normalize(Ls);vec3 Ns=vec3(0.,0.,1.);float NoL=dot(Ns,Ls);if (NoL>0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -result+=c;}} -result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} -#define inline -vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) -{vec3 n=normalize(inputN);if (alphaG==0.) {vec3 c=textureCube(inputTexture,n).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -for(uint i=0u; i<NUM_SAMPLES; ++i) -#else -for(int i=0; i<NUM_SAMPLES; ++i) -#endif -{vec2 Xi=hammersley(i,NUM_SAMPLES);vec3 H=hemisphereImportanceSampleDggx(Xi,alphaG);float NoV=1.;float NoH=H.z;float NoH2=H.z*H.z;float NoL=2.*NoH2-1.;vec3 L=vec3(2.*NoH*H.x,2.*NoH*H.y,NoL);L=normalize(L);if (NoL>0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -result+=c*NoL;}} -result=result/weight;return result;}} -#endif -#endif -`;no.v.IncludesShadersStore.hdrFilteringFunctions=dN;let dF=`#define CLEARCOATREFLECTANCE90 1.0 -struct lightingInfo -{vec3 diffuse; -#ifdef SPECULARTERM -vec3 specular; -#endif -#ifdef CLEARCOAT -vec4 clearCoat; -#endif -#ifdef SHEEN -vec3 sheen; -#endif -};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { -#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) -float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; -#else -return roughness; -#endif -} -vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} -vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} -#define inline -vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} -#ifdef SS_TRANSLUCENCY -vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} -#endif -#ifdef SPECULARTERM -vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); -#ifdef IRIDESCENCE -fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); -#endif -float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); -#ifdef BRDF_V_HEIGHT_CORRELATED -float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); -#else -float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); -#endif -vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} -#endif -#ifdef ANISOTROPIC -vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); -#ifdef IRIDESCENCE -fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); -#endif -float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} -#endif -#ifdef CLEARCOAT -vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( -clearCoatTerm*info.attenuation*NccdotL*lightColor, -1.0-fresnel -);} -vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} -#endif -#ifdef SHEEN -vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER -float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); -#else */ -float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ -float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} -#endif -`;no.v.IncludesShadersStore.pbrDirectLightingFunctions=dF;let dL=`#if defined(REFLECTION) || defined(SS_REFRACTION) -float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} -float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} -#endif -#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) -float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} -#endif -#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) -float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} -#endif -#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) -#define UNPACK_LOD(x) (1.0-x)*255.0 -float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} -#endif -`;no.v.IncludesShadersStore.pbrIBLFunctions=dL;let dw=`struct albedoOpacityOutParams -{vec3 surfaceAlbedo;float alpha;}; -#define pbr_inline -void albedoOpacityBlock( -in vec4 vAlbedoColor, -#ifdef ALBEDO -in vec4 albedoTexture, -in vec2 albedoInfos, -#endif -#ifdef OPACITY -in vec4 opacityMap, -in vec2 vOpacityInfos, -#endif -#ifdef DETAIL -in vec4 detailColor, -in vec4 vDetailInfos, -#endif -#ifdef DECAL -in vec4 decalColor, -in vec4 vDecalInfos, -#endif -out albedoOpacityOutParams outParams -) -{vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; -#ifdef ALBEDO -#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) -alpha*=albedoTexture.a; -#endif -#ifdef GAMMAALBEDO -surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); -#else -surfaceAlbedo*=albedoTexture.rgb; -#endif -surfaceAlbedo*=albedoInfos.y; -#endif -#ifndef DECAL_AFTER_DETAIL -#include<decalFragment> -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -surfaceAlbedo*=vColor.rgb; -#endif -#ifdef DETAIL -float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; -#endif -#ifdef DECAL_AFTER_DETAIL -#include<decalFragment> -#endif -#define CUSTOM_FRAGMENT_UPDATE_ALBEDO -#ifdef OPACITY -#ifdef OPACITYRGB -alpha=getLuminance(opacityMap.rgb); -#else -alpha*=opacityMap.a; -#endif -alpha*=vOpacityInfos.y; -#endif -#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) -alpha*=vColor.a; -#endif -#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) -#ifdef ALPHATEST -#if DEBUGMODE != 88 -if (alpha<ALPHATESTVALUE) -discard; -#endif -#ifndef ALPHABLEND -alpha=1.0; -#endif -#endif -#endif -outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;} -`;no.v.IncludesShadersStore.pbrBlockAlbedoOpacity=dw;let dB=`struct reflectivityOutParams -{float microSurface;float roughness;vec3 surfaceReflectivityColor; -#ifdef METALLICWORKFLOW -vec3 surfaceAlbedo; -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -vec3 ambientOcclusionColor; -#endif -#if DEBUGMODE>0 -#ifdef METALLICWORKFLOW -vec2 metallicRoughness; -#ifdef REFLECTIVITY -vec4 surfaceMetallicColorMap; -#endif -#ifndef FROSTBITE_REFLECTANCE -vec3 metallicF0; -#endif -#else -#ifdef REFLECTIVITY -vec4 surfaceReflectivityColorMap; -#endif -#endif -#endif -}; -#define pbr_inline -void reflectivityBlock( -in vec4 vReflectivityColor, -#ifdef METALLICWORKFLOW -in vec3 surfaceAlbedo, -in vec4 metallicReflectanceFactors, -#endif -#ifdef REFLECTIVITY -in vec3 reflectivityInfos, -in vec4 surfaceMetallicOrReflectivityColorMap, -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -in vec3 ambientOcclusionColorIn, -#endif -#ifdef MICROSURFACEMAP -in vec4 microSurfaceTexel, -#endif -#ifdef DETAIL -in vec4 detailColor, -in vec4 vDetailInfos, -#endif -out reflectivityOutParams outParams -) -{float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; -#ifdef METALLICWORKFLOW -vec2 metallicRoughness=surfaceReflectivityColor.rg; -#ifdef REFLECTIVITY -#if DEBUGMODE>0 -outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; -#endif -#ifdef AOSTOREINMETALMAPRED -vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); -#endif -#ifdef METALLNESSSTOREINMETALMAPBLUE -metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; -#else -metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; -#endif -#ifdef ROUGHNESSSTOREINMETALMAPALPHA -metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; -#else -#ifdef ROUGHNESSSTOREINMETALMAPGREEN -metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; -#endif -#endif -#endif -#ifdef DETAIL -float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); -#endif -#ifdef MICROSURFACEMAP -metallicRoughness.g*=microSurfaceTexel.r; -#endif -#if DEBUGMODE>0 -outParams.metallicRoughness=metallicRoughness; -#endif -#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS -microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; -#ifdef FROSTBITE_REFLECTANCE -outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); -#else -vec3 metallicF0=metallicReflectanceFactors.rgb; -#if DEBUGMODE>0 -outParams.metallicF0=metallicF0; -#endif -outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); -#endif -#else -#ifdef REFLECTIVITY -surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; -#if DEBUGMODE>0 -outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; -#endif -#ifdef MICROSURFACEFROMREFLECTIVITYMAP -microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; -#else -#ifdef MICROSURFACEAUTOMATIC -microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); -#endif -#ifdef MICROSURFACEMAP -microSurface*=microSurfaceTexel.r; -#endif -#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE -#endif -#endif -#endif -microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;} -`;no.v.IncludesShadersStore.pbrBlockReflectivity=dB;let dU=`struct ambientOcclusionOutParams -{vec3 ambientOcclusionColor; -#if DEBUGMODE>0 && defined(AMBIENT) -vec3 ambientOcclusionColorMap; -#endif -}; -#define pbr_inline -void ambientOcclusionBlock( -#ifdef AMBIENT -in vec3 ambientOcclusionColorMap_, -in vec4 vAmbientInfos, -#endif -out ambientOcclusionOutParams outParams -) -{vec3 ambientOcclusionColor=vec3(1.,1.,1.); -#ifdef AMBIENT -vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; -#ifdef AMBIENTINGRAYSCALE -ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); -#endif -ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); -#if DEBUGMODE>0 -outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; -#endif -#endif -outParams.ambientOcclusionColor=ambientOcclusionColor;} -`;no.v.IncludesShadersStore.pbrBlockAmbientOcclusion=dU;let dV=`#ifdef ALPHAFRESNEL -#if defined(ALPHATEST) || defined(ALPHABLEND) -struct alphaFresnelOutParams -{float alpha;}; -#define pbr_inline -void alphaFresnelBlock( -in vec3 normalW, -in vec3 viewDirectionW, -in float alpha, -in float microSurface, -out alphaFresnelOutParams outParams -) -{float opacityPerceptual=alpha; -#ifdef LINEARALPHAFRESNEL -float opacity0=opacityPerceptual; -#else -float opacity0=opacityPerceptual*opacityPerceptual; -#endif -float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; -#ifdef ALPHATEST -if (outParams.alpha<ALPHATESTVALUE) -discard; -#ifndef ALPHABLEND -outParams.alpha=1.0; -#endif -#endif -} -#endif -#endif -`;no.v.IncludesShadersStore.pbrBlockAlphaFresnel=dV;let dk=`#ifdef ANISOTROPIC -struct anisotropicOutParams -{float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal; -#if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE) -vec3 anisotropyMapData; -#endif -}; -#define pbr_inline -void anisotropicBlock( -in vec3 vAnisotropy, -in float roughness, -#ifdef ANISOTROPIC_TEXTURE -in vec3 anisotropyMapData, -#endif -in mat3 TBN, -in vec3 normalW, -in vec3 viewDirectionW, -out anisotropicOutParams outParams -) -{float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); -#ifdef ANISOTROPIC_TEXTURE -anisotropy*=anisotropyMapData.b; -#if DEBUGMODE>0 -outParams.anisotropyMapData=anisotropyMapData; -#endif -anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; -#ifdef ANISOTROPIC_LEGACY -anisotropyDirection.rg*=anisotropyMapData.rg; -#else -anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); -#endif -#endif -mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);} -#endif -`;no.v.IncludesShadersStore.pbrBlockAnisotropic=dk;let dG=`#ifdef REFLECTION -struct reflectionOutParams -{vec4 environmentRadiance;vec3 environmentIrradiance; -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords; -#else -vec2 reflectionCoords; -#endif -#ifdef SS_TRANSLUCENCY -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -vec3 irradianceVector; -#endif -#endif -#endif -}; -#define pbr_inline -void createReflectionCoords( -in vec3 vPositionW, -in vec3 normalW, -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#ifdef REFLECTIONMAP_3D -out vec3 reflectionCoords -#else -out vec2 reflectionCoords -#endif -) -{ -#ifdef ANISOTROPIC -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); -#else -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#endif -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -reflectionCoords=reflectionVector; -#else -reflectionCoords=reflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -reflectionCoords/=reflectionVector.z; -#endif -reflectionCoords.y=1.0-reflectionCoords.y; -#endif -} -#define pbr_inline -#define inline -void sampleReflectionTexture( -in float alphaG, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -in float NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -in float roughness, -#endif -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -const vec3 reflectionCoords, -#else -in sampler2D reflectionSampler, -const vec2 reflectionCoords, -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -out vec4 environmentRadiance -) -{ -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); -#elif defined(LINEARSPECULARREFLECTION) -float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); -#else -float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); -#endif -#ifdef LODBASEDMICROSFURACE -reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; -#ifdef LODINREFLECTIONALPHA -float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); -#else -float requestedReflectionLOD=reflectionLOD; -#endif -#ifdef REALTIME_FILTERING -environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); -#else -environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); -#endif -#else -float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( -sampleReflection(reflectionSamplerHigh,reflectionCoords), -environmentMid, -lodReflectionNormalizedDoubled -);} else {environmentRadiance=mix( -environmentMid, -sampleReflection(reflectionSamplerLow,reflectionCoords), -lodReflectionNormalizedDoubled-1.0 -);} -#endif -#ifdef RGBDREFLECTION -environmentRadiance.rgb=fromRGBD(environmentRadiance); -#endif -#ifdef GAMMAREFLECTION -environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); -#endif -environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} -#define pbr_inline -#define inline -void reflectionBlock( -in vec3 vPositionW, -in vec3 normalW, -in float alphaG, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -in float NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -in float roughness, -#endif -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -#else -in sampler2D reflectionSampler, -#endif -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -in vec3 vEnvironmentIrradiance, -#endif -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -in mat4 reflectionMatrix, -#endif -#endif -#ifdef USEIRRADIANCEMAP -#ifdef REFLECTIONMAP_3D -in samplerCube irradianceSampler, -#else -in sampler2D irradianceSampler, -#endif -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -out reflectionOutParams outParams -) -{vec4 environmentRadiance=vec4(0.,0.,0.,0.); -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords=vec3(0.); -#else -vec2 reflectionCoords=vec2(0.); -#endif -createReflectionCoords( -vPositionW, -normalW, -#ifdef ANISOTROPIC -anisotropicOut, -#endif -reflectionCoords -);sampleReflectionTexture( -alphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -roughness, -#endif -#ifdef REFLECTIONMAP_3D -reflectionSampler, -reflectionCoords, -#else -reflectionSampler, -reflectionCoords, -#endif -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentRadiance -);vec3 environmentIrradiance=vec3(0.,0.,0.); -#ifdef USESPHERICALFROMREFLECTIONMAP -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -environmentIrradiance=vEnvironmentIrradiance; -#else -#ifdef ANISOTROPIC -vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; -#else -vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; -#endif -#ifdef REFLECTIONMAP_OPPOSITEZ -irradianceVector.z*=-1.0; -#endif -#ifdef INVERTCUBICMAP -irradianceVector.y*=-1.0; -#endif -#if defined(REALTIME_FILTERING) -environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo); -#else -environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); -#endif -#ifdef SS_TRANSLUCENCY -outParams.irradianceVector=irradianceVector; -#endif -#endif -#elif defined(USEIRRADIANCEMAP) -vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; -#ifdef RGBDREFLECTION -environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); -#endif -#ifdef GAMMAREFLECTION -environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); -#endif -#endif -environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;} -#endif -`;no.v.IncludesShadersStore.pbrBlockReflection=dG;let dz=`#ifdef SHEEN -struct sheenOutParams -{float sheenIntensity;vec3 sheenColor;float sheenRoughness; -#ifdef SHEEN_LINKWITHALBEDO -vec3 surfaceAlbedo; -#endif -#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -float sheenAlbedoScaling; -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -vec3 finalSheenRadianceScaled; -#endif -#if DEBUGMODE>0 -#ifdef SHEEN_TEXTURE -vec4 sheenMapData; -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -vec3 sheenEnvironmentReflectance; -#endif -#endif -}; -#define pbr_inline -#define inline -void sheenBlock( -in vec4 vSheenColor, -#ifdef SHEEN_ROUGHNESS -in float vSheenRoughness, -#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -in vec4 sheenMapRoughnessData, -#endif -#endif -in float roughness, -#ifdef SHEEN_TEXTURE -in vec4 sheenMapData, -in float sheenMapLevel, -#endif -in float reflectance, -#ifdef SHEEN_LINKWITHALBEDO -in vec3 baseColor, -in vec3 surfaceAlbedo, -#endif -#ifdef ENVIRONMENTBRDF -in float NdotV, -in vec3 environmentBrdf, -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -in vec2 AARoughnessFactors, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -in vec4 vLightingIntensity, -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -in vec3 reflectionCoords, -#else -in sampler2D reflectionSampler, -in vec2 reflectionCoords, -#endif -in float NdotVUnclamped, -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -in float seo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -in float eho, -#endif -#endif -out sheenOutParams outParams -) -{float sheenIntensity=vSheenColor.a; -#ifdef SHEEN_TEXTURE -#if DEBUGMODE>0 -outParams.sheenMapData=sheenMapData; -#endif -#endif -#ifdef SHEEN_LINKWITHALBEDO -float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; -#ifdef SHEEN_TEXTURE -sheenIntensity*=sheenMapData.a; -#endif -#else -vec3 sheenColor=vSheenColor.rgb; -#ifdef SHEEN_TEXTURE -#ifdef SHEEN_GAMMATEXTURE -sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); -#else -sheenColor.rgb*=sheenMapData.rgb; -#endif -sheenColor.rgb*=sheenMapLevel; -#endif -#ifdef SHEEN_ROUGHNESS -float sheenRoughness=vSheenRoughness; -#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE -#if defined(SHEEN_TEXTURE) -sheenRoughness*=sheenMapData.a; -#endif -#elif defined(SHEEN_TEXTURE_ROUGHNESS) -#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL -sheenRoughness*=sheenMapData.a; -#else -sheenRoughness*=sheenMapRoughnessData.a; -#endif -#endif -#else -float sheenRoughness=roughness; -#ifdef SHEEN_TEXTURE -sheenIntensity*=sheenMapData.a; -#endif -#endif -#if !defined(SHEEN_ALBEDOSCALING) -sheenIntensity*=(1.-reflectance); -#endif -sheenColor*=sheenIntensity; -#endif -#ifdef ENVIRONMENTBRDF -/*#ifdef SHEEN_SOFTER -vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); -#else*/ -#ifdef SHEEN_ROUGHNESS -vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); -#else -vec3 environmentSheenBrdf=environmentBrdf; -#endif -/*#endif*/ -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); -#ifdef SPECULARAA -sheenAlphaG+=AARoughnessFactors.y; -#endif -vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( -sheenAlphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -sheenRoughness, -#endif -reflectionSampler, -reflectionCoords, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentSheenRadiance -);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -sheenEnvironmentReflectance*=seo; -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -sheenEnvironmentReflectance*=eho; -#endif -#if DEBUGMODE>0 -outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; -#endif -outParams.finalSheenRadianceScaled= -environmentSheenRadiance.rgb * -sheenEnvironmentReflectance * -vLightingIntensity.z; -#endif -#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; -#endif -outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;} -#endif -`;no.v.IncludesShadersStore.pbrBlockSheen=dz;let dW=`struct clearcoatOutParams -{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; -#ifdef REFLECTION -vec3 finalClearCoatRadianceScaled; -#endif -#ifdef CLEARCOAT_TINT -vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; -#endif -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -vec3 energyConservationFactorClearCoat; -#endif -#if DEBUGMODE>0 -#ifdef CLEARCOAT_BUMP -mat3 TBNClearCoat; -#endif -#ifdef CLEARCOAT_TEXTURE -vec2 clearCoatMapData; -#endif -#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -vec4 clearCoatTintMapData; -#endif -#ifdef REFLECTION -vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; -#endif -float clearCoatNdotV; -#endif -}; -#ifdef CLEARCOAT -#define pbr_inline -#define inline -void clearcoatBlock( -in vec3 vPositionW, -in vec3 geometricNormalW, -in vec3 viewDirectionW, -in vec2 vClearCoatParams, -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -in vec4 clearCoatMapRoughnessData, -#endif -in vec3 specularEnvironmentR0, -#ifdef CLEARCOAT_TEXTURE -in vec2 clearCoatMapData, -#endif -#ifdef CLEARCOAT_TINT -in vec4 vClearCoatTintParams, -in float clearCoatColorAtDistance, -in vec4 vClearCoatRefractionParams, -#ifdef CLEARCOAT_TINT_TEXTURE -in vec4 clearCoatTintMapData, -#endif -#endif -#ifdef CLEARCOAT_BUMP -in vec2 vClearCoatBumpInfos, -in vec4 clearCoatBumpMapData, -in vec2 vClearCoatBumpUV, -#if defined(TANGENT) && defined(NORMAL) -in mat3 vTBN, -#else -in vec2 vClearCoatTangentSpaceParams, -#endif -#ifdef OBJECTSPACE_NORMALMAP -in mat4 normalMatrix, -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -in vec3 faceNormal, -#endif -#ifdef REFLECTION -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -in vec4 vLightingIntensity, -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -#else -in sampler2D reflectionSampler, -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -in float ambientMonochrome, -#endif -#endif -#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) -in float frontFacingMultiplier, -#endif -out clearcoatOutParams outParams -) -{float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; -#ifdef CLEARCOAT_TEXTURE -clearCoatIntensity*=clearCoatMapData.x; -#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE -clearCoatRoughness*=clearCoatMapData.y; -#endif -#if DEBUGMODE>0 -outParams.clearCoatMapData=clearCoatMapData; -#endif -#endif -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL -clearCoatRoughness*=clearCoatMapData.y; -#else -clearCoatRoughness*=clearCoatMapRoughnessData.y; -#endif -#endif -outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; -#ifdef CLEARCOAT_TINT -vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; -#ifdef CLEARCOAT_TINT_TEXTURE -#ifdef CLEARCOAT_TINT_GAMMATEXTURE -clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); -#else -clearCoatColor*=clearCoatTintMapData.rgb; -#endif -clearCoatThickness*=clearCoatTintMapData.a; -#if DEBUGMODE>0 -outParams.clearCoatTintMapData=clearCoatTintMapData; -#endif -#endif -outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; -#endif -#ifdef CLEARCOAT_REMAP_F0 -vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); -#else -vec3 specularEnvironmentR0Updated=specularEnvironmentR0; -#endif -outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; -#ifdef CLEARCOAT_BUMP -#ifdef NORMALXYSCALE -float clearCoatNormalScale=1.0; -#else -float clearCoatNormalScale=vClearCoatBumpInfos.y; -#endif -#if defined(TANGENT) && defined(NORMAL) -mat3 TBNClearCoat=vTBN; -#else -vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); -#endif -#if DEBUGMODE>0 -outParams.TBNClearCoat=TBNClearCoat; -#endif -#ifdef OBJECTSPACE_NORMALMAP -clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); -#else -clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); -#endif -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; -#endif -outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); -#if DEBUGMODE>0 -outParams.clearCoatNdotV=clearCoatNdotV; -#endif -#ifdef CLEARCOAT_TINT -vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); -#endif -#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) -vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); -#endif -#if defined(REFLECTION) -float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); -#ifdef SPECULARAA -clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; -#endif -vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); -#ifdef REFLECTIONMAP_OPPOSITEZ -clearCoatReflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -vec3 clearCoatReflectionCoords=clearCoatReflectionVector; -#else -vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -clearCoatReflectionCoords/=clearCoatReflectionVector.z; -#endif -clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; -#endif -sampleReflectionTexture( -clearCoatAlphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -clearCoatNdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -clearCoatRoughness, -#endif -reflectionSampler, -clearCoatReflectionCoords, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentClearCoatRadiance -); -#if DEBUGMODE>0 -outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; -#endif -#endif -#endif -#else -vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); -#endif -clearCoatEnvironmentReflectance*=clearCoatIntensity; -#if DEBUGMODE>0 -outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; -#endif -outParams.finalClearCoatRadianceScaled= -environmentClearCoatRadiance.rgb * -clearCoatEnvironmentReflectance * -vLightingIntensity.z; -#endif -#if defined(CLEARCOAT_TINT) -outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); -#endif -float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); -#endif -} -#endif -`;no.v.IncludesShadersStore.pbrBlockClearcoat=dW;let dH=`struct iridescenceOutParams -{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; -#ifdef IRIDESCENCE -#define pbr_inline -#define inline -void iridescenceBlock( -in vec4 vIridescenceParams, -in float viewAngle, -in vec3 specularEnvironmentR0, -#ifdef IRIDESCENCE_TEXTURE -in vec2 iridescenceMapData, -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -in vec2 iridescenceThicknessMapData, -#endif -#ifdef CLEARCOAT -in float NdotVUnclamped, -#ifdef CLEARCOAT_TEXTURE -in vec2 clearCoatMapData, -#endif -#endif -out iridescenceOutParams outParams -) -{float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; -#ifdef IRIDESCENCE_TEXTURE -iridescenceIntensity*=iridescenceMapData.x; -#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE -iridescenceThicknessWeight=iridescenceMapData.g; -#endif -#endif -#if defined(IRIDESCENCE_THICKNESS_TEXTURE) -iridescenceThicknessWeight=iridescenceThicknessMapData.g; -#endif -float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; -#ifdef CLEARCOAT -float clearCoatIntensity=vClearCoatParams.x; -#ifdef CLEARCOAT_TEXTURE -clearCoatIntensity*=clearCoatMapData.x; -#endif -topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); -#endif -vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;} -#endif -`;no.v.IncludesShadersStore.pbrBlockIridescence=dH;let dX=`struct subSurfaceOutParams -{vec3 specularEnvironmentReflectance; -#ifdef SS_REFRACTION -vec3 finalRefraction;vec3 surfaceAlbedo; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -float alpha; -#endif -#ifdef REFLECTION -float refractionFactorForIrradiance; -#endif -#endif -#ifdef SS_TRANSLUCENCY -vec3 transmittance;float translucencyIntensity; -#ifdef REFLECTION -vec3 refractionIrradiance; -#endif -#endif -#if DEBUGMODE>0 -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec4 thicknessMap; -#endif -#ifdef SS_REFRACTION -vec4 environmentRefraction;vec3 refractionTransmittance; -#endif -#endif -}; -#ifdef SUBSURFACE -#define pbr_inline -#define inline -void subSurfaceBlock( -in vec3 vSubSurfaceIntensity, -in vec2 vThicknessParam, -in vec4 vTintColor, -in vec3 normalW, -in vec3 specularEnvironmentReflectance, -#ifdef SS_THICKNESSANDMASK_TEXTURE -in vec4 thicknessMap, -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -in vec4 refractionIntensityMap, -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -in vec4 translucencyIntensityMap, -#endif -#ifdef REFLECTION -#ifdef SS_TRANSLUCENCY -in mat4 reflectionMatrix, -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -in vec3 irradianceVector_, -#endif -#if defined(REALTIME_FILTERING) -in samplerCube reflectionSampler, -in vec2 vReflectionFilteringInfo, -#endif -#endif -#ifdef USEIRRADIANCEMAP -#ifdef REFLECTIONMAP_3D -in samplerCube irradianceSampler, -#else -in sampler2D irradianceSampler, -#endif -#endif -#endif -#endif -#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) -in vec3 surfaceAlbedo, -#endif -#ifdef SS_REFRACTION -in vec3 vPositionW, -in vec3 viewDirectionW, -in mat4 view, -in vec4 vRefractionInfos, -in mat4 refractionMatrix, -in vec4 vRefractionMicrosurfaceInfos, -in vec4 vLightingIntensity, -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -in float alpha, -#endif -#ifdef SS_LODINREFRACTIONALPHA -in float NdotVUnclamped, -#endif -#ifdef SS_LINEARSPECULARREFRACTION -in float roughness, -#endif -in float alphaG, -#ifdef SS_REFRACTIONMAP_3D -in samplerCube refractionSampler, -#ifndef LODBASEDMICROSFURACE -in samplerCube refractionSamplerLow, -in samplerCube refractionSamplerHigh, -#endif -#else -in sampler2D refractionSampler, -#ifndef LODBASEDMICROSFURACE -in sampler2D refractionSamplerLow, -in sampler2D refractionSamplerHigh, -#endif -#endif -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#ifdef REALTIME_FILTERING -in vec2 vRefractionFilteringInfo, -#endif -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -in vec3 refractionPosition, -in vec3 refractionSize, -#endif -#endif -#ifdef SS_TRANSLUCENCY -in vec3 vDiffusionDistance, -#endif -out subSurfaceOutParams outParams -) -{outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; -#ifdef SS_REFRACTION -float refractionIntensity=vSubSurfaceIntensity.x; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; -#endif -#endif -#ifdef SS_TRANSLUCENCY -float translucencyIntensity=vSubSurfaceIntensity.y; -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -#if defined(SS_USE_GLTF_TEXTURES) -float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; -#else -float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; -#endif -#if DEBUGMODE>0 -outParams.thicknessMap=thicknessMap; -#endif -#ifdef SS_MASK_FROM_THICKNESS_TEXTURE -#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE) -#if defined(SS_USE_GLTF_TEXTURES) -refractionIntensity*=thicknessMap.r; -#else -refractionIntensity*=thicknessMap.g; -#endif -#endif -#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE) -translucencyIntensity*=thicknessMap.b; -#endif -#endif -#else -float thickness=vThicknessParam.y; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -#ifdef SS_USE_GLTF_TEXTURES -refractionIntensity*=refractionIntensityMap.r; -#else -refractionIntensity*=refractionIntensityMap.g; -#endif -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -translucencyIntensity*=translucencyIntensityMap.b; -#endif -#ifdef SS_TRANSLUCENCY -thickness=maxEps(thickness);vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; -#endif -#ifdef SS_REFRACTION -vec4 environmentRefraction=vec4(0.,0.,0.,0.); -#ifdef ANISOTROPIC -vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y); -#else -vec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y); -#endif -#ifdef SS_REFRACTIONMAP_OPPOSITEZ -refractionVector.z*=-1.0; -#endif -#ifdef SS_REFRACTIONMAP_3D -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); -#endif -refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); -#else -#ifdef SS_USE_THICKNESS_AS_DEPTH -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); -#else -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); -#endif -vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; -#endif -#ifdef SS_HAS_THICKNESS -float ior=vRefractionInfos.y; -#else -float ior=vRefractionMicrosurfaceInfos.w; -#endif -#ifdef SS_LODINREFRACTIONALPHA -float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); -#elif defined(SS_LINEARSPECULARREFRACTION) -float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); -#else -float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); -#endif -#ifdef LODBASEDMICROSFURACE -refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; -#ifdef SS_LODINREFRACTIONALPHA -float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); -#else -float requestedRefractionLOD=refractionLOD; -#endif -#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) -environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); -#else -environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); -#endif -#else -float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( -sampleRefraction(refractionSamplerHigh,refractionCoords), -environmentRefractionMid, -lodRefractionNormalizedDoubled -);} else {environmentRefraction=mix( -environmentRefractionMid, -sampleRefraction(refractionSamplerLow,refractionCoords), -lodRefractionNormalizedDoubled-1.0 -);} -#endif -#ifdef SS_RGBDREFRACTION -environmentRefraction.rgb=fromRGBD(environmentRefraction); -#endif -#ifdef SS_GAMMAREFRACTION -environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); -#endif -environmentRefraction.rgb*=vRefractionInfos.x; -#endif -#ifdef SS_REFRACTION -vec3 refractionTransmittance=vec3(refractionIntensity); -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); -#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) -float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; -#else -vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); -#endif -#ifdef SS_ALBEDOFORREFRACTIONTINT -environmentRefraction.rgb*=surfaceAlbedo.rgb; -#endif -outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); -#ifdef REFLECTION -outParams.refractionFactorForIrradiance=(1.-refractionIntensity); -#endif -#ifdef UNUSED_MULTIPLEBOUNCES -vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); -#endif -refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; -#if DEBUGMODE>0 -outParams.refractionTransmittance=refractionTransmittance; -#endif -outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; -#if DEBUGMODE>0 -outParams.environmentRefraction=environmentRefraction; -#endif -#endif -#if defined(REFLECTION) && defined(SS_TRANSLUCENCY) -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) -vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; -#ifdef REFLECTIONMAP_OPPOSITEZ -irradianceVector.z*=-1.0; -#endif -#ifdef INVERTCUBICMAP -irradianceVector.y*=-1.0; -#endif -#else -vec3 irradianceVector=irradianceVector_; -#endif -#if defined(USESPHERICALFROMREFLECTIONMAP) -#if defined(REALTIME_FILTERING) -vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo); -#else -vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); -#endif -#elif defined(USEIRRADIANCEMAP) -#ifdef REFLECTIONMAP_3D -vec3 irradianceCoords=irradianceVector; -#else -vec2 irradianceCoords=irradianceVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -irradianceCoords/=irradianceVector.z; -#endif -irradianceCoords.y=1.0-irradianceCoords.y; -#endif -vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); -#ifdef RGBDREFLECTION -refractionIrradiance.rgb=fromRGBD(refractionIrradiance); -#endif -#ifdef GAMMAREFLECTION -refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); -#endif -#else -vec4 refractionIrradiance=vec4(0.); -#endif -refractionIrradiance.rgb*=transmittance; -#ifdef SS_ALBEDOFORTRANSLUCENCYTINT -refractionIrradiance.rgb*=surfaceAlbedo.rgb; -#endif -outParams.refractionIrradiance=refractionIrradiance.rgb; -#endif -} -#endif -`;no.v.IncludesShadersStore.pbrBlockSubSurface=dX;let dY=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; -#endif -vec3 geometricNormalW=normalW; -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; -#endif -`;no.v.IncludesShadersStore.pbrBlockNormalGeometric=dY;let dj=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) -vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; -#if defined(TWOSIDEDLIGHTING) -faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; -#endif -normalW*=sign(dot(normalW,faceNormal)); -#endif -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -normalW=gl_FrontFacing ? normalW : -normalW; -#endif -`;no.v.IncludesShadersStore.pbrBlockNormalFinal=dj;let dq=`#ifdef LIGHTMAP -vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); -#ifdef RGBDLIGHTMAP -lightmapColor.rgb=fromRGBD(lightmapColor); -#endif -#ifdef GAMMALIGHTMAP -lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); -#endif -lightmapColor.rgb*=vLightmapInfos.y; -#endif -`;no.v.IncludesShadersStore.pbrBlockLightmapInit=dq;let dK=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); -#ifdef SPECULARAA -alphaG+=AARoughnessFactors.y; -#endif -#if defined(ENVIRONMENTBRDF) -vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -#ifdef AMBIENTINGRAYSCALE -float ambientMonochrome=aoOut.ambientOcclusionColor.r; -#else -float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); -#endif -float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); -#endif -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); -#endif -#endif -#endif -#endif -`;no.v.IncludesShadersStore.pbrBlockGeometryInfo=dK;let d$=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; -#ifdef METALLICWORKFLOW -vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); -#else -vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); -#endif -#ifdef ALPHAFRESNEL -float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; -#endif -`;no.v.IncludesShadersStore.pbrBlockReflectance0=d$;let dQ=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); -#ifdef RADIANCEOCCLUSION -specularEnvironmentReflectance*=seo; -#endif -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -specularEnvironmentReflectance*=eho; -#endif -#endif -#endif -#else -vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); -#endif -#ifdef CLEARCOAT -specularEnvironmentReflectance*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -specularEnvironmentReflectance*=clearcoatOut.absorption; -#endif -#endif -`;no.v.IncludesShadersStore.pbrBlockReflectance=dQ;let dZ=`vec3 diffuseBase=vec3(0.,0.,0.); -#ifdef SPECULARTERM -vec3 specularBase=vec3(0.,0.,0.); -#endif -#ifdef CLEARCOAT -vec3 clearCoatBase=vec3(0.,0.,0.); -#endif -#ifdef SHEEN -vec3 sheenBase=vec3(0.,0.,0.); -#endif -preLightingInfo preInfo;lightingInfo info;float shadow=1.; -#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) -vec3 absorption=vec3(0.); -#endif -`;no.v.IncludesShadersStore.pbrBlockDirectLighting=dZ;let dJ=`#if defined(ENVIRONMENTBRDF) -#ifdef MS_BRDF_ENERGY_CONSERVATION -vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); -#endif -#endif -#ifndef METALLICWORKFLOW -#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION -surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; -#endif -#endif -#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) -surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; -#endif -#ifdef REFLECTION -vec3 finalIrradiance=reflectionOut.environmentIrradiance; -#if defined(CLEARCOAT) -finalIrradiance*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -finalIrradiance*=clearcoatOut.absorption; -#endif -#endif -#if defined(SS_REFRACTION) -finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; -#endif -#if defined(SS_TRANSLUCENCY) -finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; -#endif -finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; -#endif -#ifdef SPECULARTERM -vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalSpecularScaled*=energyConservationFactor; -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -finalSpecularScaled*=sheenOut.sheenAlbedoScaling; -#endif -#endif -#ifdef REFLECTION -vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalRadianceScaled*=energyConservationFactor; -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -finalRadianceScaled*=sheenOut.sheenAlbedoScaling; -#endif -#endif -#ifdef SHEEN -vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; -#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) -sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; -#endif -#endif -#endif -#ifdef CLEARCOAT -vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; -#endif -#ifdef SS_REFRACTION -subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; -#ifdef CLEARCOAT_TINT -subSurfaceOut.finalRefraction*=clearcoatOut.absorption; -#endif -#endif -#endif -#ifdef ALPHABLEND -float luminanceOverAlpha=0.0; -#if defined(REFLECTION) && defined(RADIANCEOVERALPHA) -luminanceOverAlpha+=getLuminance(finalRadianceScaled); -#if defined(CLEARCOAT) -luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); -#endif -#endif -#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) -luminanceOverAlpha+=getLuminance(finalSpecularScaled); -#endif -#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) -luminanceOverAlpha+=getLuminance(finalClearCoatScaled); -#endif -#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) -alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); -#endif -#endif -`;no.v.IncludesShadersStore.pbrBlockFinalLitComponents=dJ;let d0=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; -#ifdef EMISSIVE -vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; -#ifdef GAMMAEMISSIVE -finalEmissive*=toLinearSpace(emissiveColorTex.rgb); -#else -finalEmissive*=emissiveColorTex.rgb; -#endif -finalEmissive*= vEmissiveInfos.y; -#endif -finalEmissive*=vLightingIntensity.y; -#ifdef AMBIENT -vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); -#else -vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; -#endif -finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; -`;no.v.IncludesShadersStore.pbrBlockFinalUnlitComponents=d0;let d1=`vec4 finalColor=vec4( -#ifndef UNLIT -#ifdef REFLECTION -finalIrradiance + -#endif -#ifdef SPECULARTERM -finalSpecularScaled + -#endif -#ifdef SHEEN -finalSheenScaled + -#endif -#ifdef CLEARCOAT -finalClearCoatScaled + -#endif -#ifdef REFLECTION -finalRadianceScaled + -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) -sheenOut.finalSheenRadianceScaled + -#endif -#ifdef CLEARCOAT -clearcoatOut.finalClearCoatRadianceScaled + -#endif -#endif -#ifdef SS_REFRACTION -subSurfaceOut.finalRefraction + -#endif -#endif -finalAmbient + -finalDiffuse, -alpha); -#ifdef LIGHTMAP -#ifndef LIGHTMAPEXCLUDED -#ifdef USELIGHTMAPASSHADOWMAP -finalColor.rgb*=lightmapColor.rgb; -#else -finalColor.rgb+=lightmapColor.rgb; -#endif -#endif -#endif -finalColor.rgb+=finalEmissive; -#define CUSTOM_FRAGMENT_BEFORE_FOG -finalColor=max(finalColor,0.0); -`;no.v.IncludesShadersStore.pbrBlockFinalColorComposition=d1;let d2=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) -#if !defined(SKIPFINALCOLORCLAMP) -finalColor.rgb=clamp(finalColor.rgb,0.,30.0); -#endif -#else -finalColor=applyImageProcessing(finalColor); -#endif -finalColor.a*=visibility; -#ifdef PREMULTIPLYALPHA -finalColor.rgb*=finalColor.a; -#endif -`;no.v.IncludesShadersStore.pbrBlockImageProcessing=d2;let d3=`#if DEBUGMODE>0 -if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { -#if DEBUGMODE==1 -gl_FragColor.rgb=vPositionW.rgb; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==2 && defined(NORMAL) -gl_FragColor.rgb=vNormalW.rgb; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) -gl_FragColor.rgb=TBN[0]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) -gl_FragColor.rgb=TBN[1]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==5 -gl_FragColor.rgb=normalW; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==6 && defined(MAINUV1) -gl_FragColor.rgb=vec3(vMainUV1,0.0); -#elif DEBUGMODE==7 && defined(MAINUV2) -gl_FragColor.rgb=vec3(vMainUV2,0.0); -#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) -gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) -gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==10 && defined(CLEARCOAT) -gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==11 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicNormal; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==12 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicTangent; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==13 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==20 && defined(ALBEDO) -gl_FragColor.rgb=albedoTexture.rgb; -#ifndef GAMMAALBEDO -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==21 && defined(AMBIENT) -gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; -#elif DEBUGMODE==22 && defined(OPACITY) -gl_FragColor.rgb=opacityMap.rgb; -#elif DEBUGMODE==23 && defined(EMISSIVE) -gl_FragColor.rgb=emissiveColorTex.rgb; -#ifndef GAMMAEMISSIVE -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==24 && defined(LIGHTMAP) -gl_FragColor.rgb=lightmapColor.rgb; -#ifndef GAMMALIGHTMAP -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; -#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); -#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; -#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) -gl_FragColor.rgb=sheenOut.sheenMapData.rgb; -#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) -gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; -#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) -gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; -#elif DEBUGMODE==32 && defined(BUMP) -gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; -#elif DEBUGMODE==40 && defined(SS_REFRACTION) -gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==41 && defined(REFLECTION) -gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; -#ifndef GAMMAREFLECTION -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) -gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==50 -gl_FragColor.rgb=diffuseBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==51 && defined(SPECULARTERM) -gl_FragColor.rgb=specularBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==52 && defined(CLEARCOAT) -gl_FragColor.rgb=clearCoatBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==53 && defined(SHEEN) -gl_FragColor.rgb=sheenBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==54 && defined(REFLECTION) -gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; -#ifndef GAMMAREFLECTION -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==60 -gl_FragColor.rgb=surfaceAlbedo.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==61 -gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==62 && defined(METALLICWORKFLOW) -gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); -#elif DEBUGMODE==71 && defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.metallicF0; -#elif DEBUGMODE==63 -gl_FragColor.rgb=vec3(roughness); -#elif DEBUGMODE==64 -gl_FragColor.rgb=vec3(alphaG); -#elif DEBUGMODE==65 -gl_FragColor.rgb=vec3(NdotV); -#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) -gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==67 && defined(CLEARCOAT) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); -#elif DEBUGMODE==68 && defined(CLEARCOAT) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); -#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) -gl_FragColor.rgb=subSurfaceOut.transmittance; -#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) -gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; -#elif DEBUGMODE==72 -gl_FragColor.rgb=vec3(microSurface); -#elif DEBUGMODE==73 -gl_FragColor.rgb=vAlbedoColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) -gl_FragColor.rgb=vReflectivityColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==75 -gl_FragColor.rgb=vEmissiveColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) -gl_FragColor.rgb=vec3(seo); -#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) -gl_FragColor.rgb=vec3(eho); -#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) -gl_FragColor.rgb=vec3(energyConservationFactor); -#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -gl_FragColor.rgb=specularEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) -gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==86 && defined(ALPHABLEND) -gl_FragColor.rgb=vec3(luminanceOverAlpha); -#elif DEBUGMODE==87 -gl_FragColor.rgb=vec3(alpha); -#elif DEBUGMODE==88 && defined(ALBEDO) -gl_FragColor.rgb=vec3(albedoTexture.a); -#else -float stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); -#endif -gl_FragColor.rgb*=vDebugMode.y; -#ifdef DEBUGMODE_NORMALIZE -gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; -#endif -#ifdef DEBUGMODE_GAMMA -gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); -#endif -gl_FragColor.a=1.0; -#ifdef PREPASS -gl_FragData[0]=toLinearSpace(gl_FragColor); -gl_FragData[1]=vec4(0.,0.,0.,0.); -#endif -} -#endif -`;no.v.IncludesShadersStore.pbrDebug=d3;let d4=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#extension GL_OES_standard_derivatives : enable -#endif -#ifdef LODBASEDMICROSFURACE -#extension GL_EXT_shader_texture_lod : enable -#endif -#define CUSTOM_FRAGMENT_BEGIN -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -#include<prePassDeclaration>[SCENE_MRT_COUNT] -precision highp float; -#include<oitDeclaration> -#ifndef FROMLINEARSPACE -#define FROMLINEARSPACE -#endif -#include<__decl__pbrFragment> -#include<pbrFragmentExtraDeclaration> -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include<pbrFragmentSamplersDeclaration> -#include<imageProcessingDeclaration> -#include<clipPlaneFragmentDeclaration> -#include<logDepthDeclaration> -#include<fogFragmentDeclaration> -#include<helperFunctions> -#include<subSurfaceScatteringFunctions> -#include<importanceSampling> -#include<pbrHelperFunctions> -#include<imageProcessingFunctions> -#include<shadowsFragmentFunctions> -#include<harmonicsFunctions> -#include<pbrDirectLightingSetupFunctions> -#include<pbrDirectLightingFalloffFunctions> -#include<pbrBRDFFunctions> -#include<hdrFilteringFunctions> -#include<pbrDirectLightingFunctions> -#include<pbrIBLFunctions> -#include<bumpFragmentMainFunctions> -#include<bumpFragmentFunctions> -#ifdef REFLECTION -#include<reflectionFunction> -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -#include<pbrBlockAlbedoOpacity> -#include<pbrBlockReflectivity> -#include<pbrBlockAmbientOcclusion> -#include<pbrBlockAlphaFresnel> -#include<pbrBlockAnisotropic> -#include<pbrBlockReflection> -#include<pbrBlockSheen> -#include<pbrBlockClearcoat> -#include<pbrBlockIridescence> -#include<pbrBlockSubSurface> -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -#include<pbrBlockNormalGeometric> -#include<bumpFragment> -#include<pbrBlockNormalFinal> -albedoOpacityOutParams albedoOpacityOut; -#ifdef ALBEDO -vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); -#endif -#ifdef DECAL -vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); -#endif -albedoOpacityBlock( -vAlbedoColor, -#ifdef ALBEDO -albedoTexture, -vAlbedoInfos, -#endif -#ifdef OPACITY -opacityMap, -vOpacityInfos, -#endif -#ifdef DETAIL -detailColor, -vDetailInfos, -#endif -#ifdef DECAL -decalColor, -vDecalInfos, -#endif -albedoOpacityOut -);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; -#define CUSTOM_FRAGMENT_UPDATE_ALPHA -#include<depthPrePass> -#define CUSTOM_FRAGMENT_BEFORE_LIGHTS -ambientOcclusionOutParams aoOut; -#ifdef AMBIENT -vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; -#endif -ambientOcclusionBlock( -#ifdef AMBIENT -ambientOcclusionColorMap, -vAmbientInfos, -#endif -aoOut -); -#include<pbrBlockLightmapInit> -#ifdef UNLIT -vec3 diffuseBase=vec3(1.,1.,1.); -#else -vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; -#if defined(REFLECTIVITY) -vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; -#ifndef METALLICWORKFLOW -#ifdef REFLECTIVITY_GAMMA -surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); -#endif -surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; -#endif -#endif -#if defined(MICROSURFACEMAP) -vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; -#endif -#ifdef METALLICWORKFLOW -vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; -#ifdef REFLECTANCE -vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); -#ifdef REFLECTANCE_GAMMA -reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); -#endif -metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; -#endif -#ifdef METALLIC_REFLECTANCE -vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); -#ifdef METALLIC_REFLECTANCE_GAMMA -metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); -#endif -#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY -metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; -#endif -metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; -#endif -#endif -reflectivityBlock( -vReflectivityColor, -#ifdef METALLICWORKFLOW -surfaceAlbedo, -metallicReflectanceFactors, -#endif -#ifdef REFLECTIVITY -vReflectivityInfos, -surfaceMetallicOrReflectivityColorMap, -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -aoOut.ambientOcclusionColor, -#endif -#ifdef MICROSURFACEMAP -microSurfaceTexel, -#endif -#ifdef DETAIL -detailColor, -vDetailInfos, -#endif -reflectivityOut -);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; -#ifdef METALLICWORKFLOW -surfaceAlbedo=reflectivityOut.surfaceAlbedo; -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; -#endif -#ifdef ALPHAFRESNEL -#if defined(ALPHATEST) || defined(ALPHABLEND) -alphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock( -normalW, -viewDirectionW, -alpha, -microSurface, -alphaFresnelOut -);alpha=alphaFresnelOut.alpha; -#endif -#endif -#include<pbrBlockGeometryInfo> -#ifdef ANISOTROPIC -anisotropicOutParams anisotropicOut; -#ifdef ANISOTROPIC_TEXTURE -vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; -#endif -anisotropicBlock( -vAnisotropy, -roughness, -#ifdef ANISOTROPIC_TEXTURE -anisotropyMapData, -#endif -TBN, -normalW, -viewDirectionW, -anisotropicOut -); -#endif -#ifdef REFLECTION -reflectionOutParams reflectionOut; -#ifndef USE_CUSTOM_REFLECTION -reflectionBlock( -vPositionW, -normalW, -alphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#ifdef ANISOTROPIC -anisotropicOut, -#endif -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -roughness, -#endif -reflectionSampler, -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -vEnvironmentIrradiance, -#endif -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -reflectionMatrix, -#endif -#endif -#ifdef USEIRRADIANCEMAP -irradianceSampler, -#endif -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -reflectionOut -); -#else -#define CUSTOM_REFLECTION -#endif -#endif -#include<pbrBlockReflectance0> -#ifdef SHEEN -sheenOutParams sheenOut; -#ifdef SHEEN_TEXTURE -vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); -#endif -#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; -#endif -sheenBlock( -vSheenColor, -#ifdef SHEEN_ROUGHNESS -vSheenRoughness, -#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -sheenMapRoughnessData, -#endif -#endif -roughness, -#ifdef SHEEN_TEXTURE -sheenMapData, -vSheenInfos.y, -#endif -reflectance, -#ifdef SHEEN_LINKWITHALBEDO -baseColor, -surfaceAlbedo, -#endif -#ifdef ENVIRONMENTBRDF -NdotV, -environmentBrdf, -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -AARoughnessFactors, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -vLightingIntensity, -reflectionSampler, -reflectionOut.reflectionCoords, -NdotVUnclamped, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -seo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -eho, -#endif -#endif -sheenOut -); -#ifdef SHEEN_LINKWITHALBEDO -surfaceAlbedo=sheenOut.surfaceAlbedo; -#endif -#endif -#ifdef CLEARCOAT -#ifdef CLEARCOAT_TEXTURE -vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; -#endif -#endif -#ifdef IRIDESCENCE -iridescenceOutParams iridescenceOut; -#ifdef IRIDESCENCE_TEXTURE -vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; -#endif -iridescenceBlock( -vIridescenceParams, -NdotV, -specularEnvironmentR0, -#ifdef IRIDESCENCE_TEXTURE -iridescenceMapData, -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -iridescenceThicknessMapData, -#endif -#ifdef CLEARCOAT -NdotVUnclamped, -#ifdef CLEARCOAT_TEXTURE -clearCoatMapData, -#endif -#endif -iridescenceOut -);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; -#endif -clearcoatOutParams clearcoatOut; -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; -#endif -#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); -#endif -#ifdef CLEARCOAT_BUMP -vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); -#endif -clearcoatBlock( -vPositionW, -geometricNormalW, -viewDirectionW, -vClearCoatParams, -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -clearCoatMapRoughnessData, -#endif -specularEnvironmentR0, -#ifdef CLEARCOAT_TEXTURE -clearCoatMapData, -#endif -#ifdef CLEARCOAT_TINT -vClearCoatTintParams, -clearCoatColorAtDistance, -vClearCoatRefractionParams, -#ifdef CLEARCOAT_TINT_TEXTURE -clearCoatTintMapData, -#endif -#endif -#ifdef CLEARCOAT_BUMP -vClearCoatBumpInfos, -clearCoatBumpMapData, -vClearCoatBumpUV, -#if defined(TANGENT) && defined(NORMAL) -vTBN, -#else -vClearCoatTangentSpaceParams, -#endif -#ifdef OBJECTSPACE_NORMALMAP -normalMatrix, -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -faceNormal, -#endif -#ifdef REFLECTION -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -vLightingIntensity, -reflectionSampler, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -ambientMonochrome, -#endif -#endif -#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) -(gl_FrontFacing ? 1. : -1.), -#endif -clearcoatOut -); -#else -clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; -#endif -#include<pbrBlockReflectance> -subSurfaceOutParams subSurfaceOut; -#ifdef SUBSURFACE -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); -#endif -subSurfaceBlock( -vSubSurfaceIntensity, -vThicknessParam, -vTintColor, -normalW, -specularEnvironmentReflectance, -#ifdef SS_THICKNESSANDMASK_TEXTURE -thicknessMap, -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -refractionIntensityMap, -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -translucencyIntensityMap, -#endif -#ifdef REFLECTION -#ifdef SS_TRANSLUCENCY -reflectionMatrix, -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -reflectionOut.irradianceVector, -#endif -#if defined(REALTIME_FILTERING) -reflectionSampler, -vReflectionFilteringInfo, -#endif -#endif -#ifdef USEIRRADIANCEMAP -irradianceSampler, -#endif -#endif -#endif -#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) -surfaceAlbedo, -#endif -#ifdef SS_REFRACTION -vPositionW, -viewDirectionW, -view, -vRefractionInfos, -refractionMatrix, -vRefractionMicrosurfaceInfos, -vLightingIntensity, -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -alpha, -#endif -#ifdef SS_LODINREFRACTIONALPHA -NdotVUnclamped, -#endif -#ifdef SS_LINEARSPECULARREFRACTION -roughness, -#endif -alphaG, -refractionSampler, -#ifndef LODBASEDMICROSFURACE -refractionSamplerLow, -refractionSamplerHigh, -#endif -#ifdef ANISOTROPIC -anisotropicOut, -#endif -#ifdef REALTIME_FILTERING -vRefractionFilteringInfo, -#endif -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -vRefractionPosition, -vRefractionSize, -#endif -#endif -#ifdef SS_TRANSLUCENCY -vDiffusionDistance, -#endif -subSurfaceOut -); -#ifdef SS_REFRACTION -surfaceAlbedo=subSurfaceOut.surfaceAlbedo; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -alpha=subSurfaceOut.alpha; -#endif -#endif -#else -subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; -#endif -#include<pbrBlockDirectLighting> -#include<lightFragment>[0..maxSimultaneousLights] -#include<pbrBlockFinalLitComponents> -#endif -#include<pbrBlockFinalUnlitComponents> -#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION -#include<pbrBlockFinalColorComposition> -#include<logDepthFragment> -#include<fogFragment>(color,finalColor) -#include<pbrBlockImageProcessing> -#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR -#ifdef PREPASS -float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; -#ifdef PREPASS_POSITION -gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); -#endif -#ifdef PREPASS_VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_ALBEDO_SQRT -vec3 sqAlbedo=sqrt(surfaceAlbedo); -#endif -#ifdef PREPASS_IRRADIANCE -vec3 irradiance=finalDiffuse; -#ifndef UNLIT -#ifdef REFLECTION -irradiance+=finalIrradiance; -#endif -#endif -#ifdef SS_SCATTERING -gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); -irradiance/=sqAlbedo; -#else -gl_FragData[0]=finalColor; -float scatteringDiffusionProfile=255.; -#endif -gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); -#else -gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); -#endif -#ifdef PREPASS_DEPTH -gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_NORMAL -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); -#endif -#ifdef PREPASS_ALBEDO_SQRT -gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); -#endif -#ifdef PREPASS_REFLECTIVITY -#ifndef UNLIT -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; -#endif -#endif -#endif -#if !defined(PREPASS) || defined(WEBGL2) -gl_FragColor=finalColor; -#endif -#include<oitFragment> -#if ORDER_INDEPENDENT_TRANSPARENCY -if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} -#endif -#include<pbrDebug> -#define CUSTOM_FRAGMENT_MAIN_END -} -`;no.v.ShadersStore.pbrPixelShader=d4;let d5=`uniform mat4 view;uniform mat4 viewProjection; -#ifdef ALBEDO -uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; -#endif -#ifdef AMBIENT -uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; -#endif -#ifdef OPACITY -uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; -#endif -#ifdef REFLECTIVITY -uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; -#endif -#ifdef METALLIC_REFLECTANCE -uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; -#endif -#ifdef REFLECTANCE -uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; -#endif -#ifdef MICROSURFACEMAP -uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; -#endif -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) -uniform vec4 vClearCoatInfos; -#endif -#ifdef CLEARCOAT_TEXTURE -uniform mat4 clearCoatMatrix; -#endif -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS -uniform mat4 clearCoatRoughnessMatrix; -#endif -#ifdef CLEARCOAT_BUMP -uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; -#endif -#ifdef CLEARCOAT_TINT_TEXTURE -uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; -#endif -#endif -#ifdef IRIDESCENCE -#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) -uniform vec4 vIridescenceInfos; -#endif -#ifdef IRIDESCENCE_TEXTURE -uniform mat4 iridescenceMatrix; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -uniform mat4 iridescenceThicknessMatrix; -#endif -#endif -#ifdef ANISOTROPIC -#ifdef ANISOTROPIC_TEXTURE -uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; -#endif -#endif -#ifdef SHEEN -#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) -uniform vec4 vSheenInfos; -#endif -#ifdef SHEEN_TEXTURE -uniform mat4 sheenMatrix; -#endif -#ifdef SHEEN_TEXTURE_ROUGHNESS -uniform mat4 sheenRoughnessMatrix; -#endif -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; -#endif -#endif -#ifdef NORMAL -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; -#else -uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; -#endif -#endif -#endif -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos;uniform mat4 detailMatrix; -#endif -#include<decalVertexDeclaration> -#define ADDITIONAL_VERTEX_DECLARATION -`;no.v.IncludesShadersStore.pbrVertexDeclaration=d5;let d6=`precision highp float; -#include<__decl__pbrVertex> -#define CUSTOM_VERTEX_BEGIN -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#ifdef TANGENT -attribute vec4 tangent; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#include<uvAttributeDeclaration>[2..7] -#include<mainUVVaryingDeclaration>[1..7] -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include<helperFunctions> -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<instancesDeclaration> -#include<prePassVertexDeclaration> -#include<samplerVertexDeclaration>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) -#include<samplerVertexDeclaration>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) -#include<samplerVertexDeclaration>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) -#include<samplerVertexDeclaration>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) -#include<samplerVertexDeclaration>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) -#include<samplerVertexDeclaration>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) -#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) -#include<samplerVertexDeclaration>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) -#include<samplerVertexDeclaration>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) -#include<samplerVertexDeclaration>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) -#include<samplerVertexDeclaration>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) -#include<samplerVertexDeclaration>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) -#ifdef CLEARCOAT -#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) -#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) -#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) -#include<samplerVertexDeclaration>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) -#endif -#ifdef IRIDESCENCE -#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) -#include<samplerVertexDeclaration>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) -#endif -#ifdef SHEEN -#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) -#include<samplerVertexDeclaration>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) -#endif -#ifdef ANISOTROPIC -#include<samplerVertexDeclaration>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) -#endif -#ifdef SUBSURFACE -#include<samplerVertexDeclaration>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) -#include<samplerVertexDeclaration>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) -#include<samplerVertexDeclaration>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) -#endif -varying vec3 vPositionW; -#if DEBUGMODE>0 -varying vec4 vClipSpacePosition; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -varying vec3 vEnvironmentIrradiance; -#include<harmonicsFunctions> -#endif -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include<bumpVertexDeclaration> -#include<clipPlaneVertexDeclaration> -#include<fogVertexDeclaration> -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#include<logDepthDeclaration> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#ifdef TANGENT -vec4 tangentUpdated=tangent; -#endif -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=positionUpdated; -#endif -#define CUSTOM_VERTEX_UPDATE_POSITION -#define CUSTOM_VERTEX_UPDATE_NORMAL -#include<instancesVertex> -#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); -#include<prePassVertex> -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normalUpdated); -#endif -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); -#endif -#endif -#define CUSTOM_VERTEX_UPDATE_WORLDPOS -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#if DEBUGMODE>0 -vClipSpacePosition=gl_Position; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); -#endif -#ifndef UV1 -vec2 uvUpdated=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uvUpdated; -#endif -#include<uvVariableDeclaration>[2..7] -#include<samplerVertexImplementation>(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) -#ifdef CLEARCOAT -#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) -#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) -#endif -#ifdef IRIDESCENCE -#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) -#endif -#ifdef SHEEN -#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z) -#endif -#ifdef ANISOTROPIC -#include<samplerVertexImplementation>(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) -#endif -#ifdef SUBSURFACE -#include<samplerVertexImplementation>(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) -#include<samplerVertexImplementation>(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) -#endif -#include<bumpVertex> -#include<clipPlaneVertex> -#include<fogVertex> -#include<shadowsVertex>[0..maxSimultaneousLights] -#include<vertexColorMixing> -#if defined(POINTSIZE) && !defined(WEBGPU) -gl_PointSize=pointSize; -#endif -#include<logDepthVertex> -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.pbrVertexShader=d6;class d8 extends s$.H{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}}class d7 extends lg{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new d8,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=d7._DefaultIndexOfRefraction,this.indexOfRefraction=d7._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=rs.Wo.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;let r=this._material._disableBumpMap;return!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!od.ClearCoatTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!od.ClearCoatTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())&&(!i.getCaps().standardDerivatives||!this._bumpTexture||!od.ClearCoatBumpTextureEnabled||!!r||!!this._bumpTexture.isReady())&&(!this._isTintEnabled||!this._tintTexture||!od.ClearCoatTintTextureEnabled||!!this._tintTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_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.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&od.ClearCoatTextureEnabled?s3.G.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&od.ClearCoatTextureEnabled?s3.G.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&od.ClearCoatBumpTextureEnabled?s3.G.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===d7._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&od.ClearCoatTintTextureEnabled?(s3.G.PrepareDefinesForMergedUV(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=this._material._disableBumpMap,f=this._material._invertNormalMapX,m=this._material._invertNormalMapY,g=d.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!p||!e.isSync){g&&od.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),s3.G.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&od.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&s3.G.BindTextureMatrix(this._texture,e,"clearCoat"),!this._textureRoughness||g||d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE||s3.G.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&od.ClearCoatTextureEnabled&&!_&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),s3.G.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",f?1:-1,m?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",f?-1:1,m?-1:1)),this._tintTexture&&od.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),s3.G.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);let r=1-this._indexOfRefraction,p=1+this._indexOfRefraction,v=Math.pow(-r/p,2),T=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",v,T,r,p),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&od.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!g&&!d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&od.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&od.ClearCoatBumpTextureEnabled&&!_&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&od.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||this._textureRoughness===e||this._bumpTexture===e||this._tintTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,r,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(r=this._bumpTexture)||void 0===r||r.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"}]}}}d7._DefaultIndexOfRefraction=1.5,(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],d7.prototype,"isEnabled",void 0),(0,r0.gn)([(0,rg.qC)()],d7.prototype,"intensity",void 0),(0,r0.gn)([(0,rg.qC)()],d7.prototype,"roughness",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],d7.prototype,"indexOfRefraction",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],d7.prototype,"texture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],d7.prototype,"useRoughnessFromMainTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],d7.prototype,"textureRoughness",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],d7.prototype,"remapF0OnInterfaceChange",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],d7.prototype,"bumpTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],d7.prototype,"isTintEnabled",void 0),(0,r0.gn)([(0,rg.n9)()],d7.prototype,"tintColor",void 0),(0,r0.gn)([(0,rg.qC)()],d7.prototype,"tintColorAtDistance",void 0),(0,r0.gn)([(0,rg.qC)()],d7.prototype,"tintThickness",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],d7.prototype,"tintTexture",void 0);class d9 extends s$.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 pe extends lg{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new d9,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=pe._DefaultMinimumThickness,this.maximumThickness=pe._DefaultMaximumThickness,this.indexOfRefraction=pe._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!od.IridescenceTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._thicknessTexture||!od.IridescenceTextureEnabled||!!this._thicknessTexture.isReadyOrNotBlocking())}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&&od.IridescenceTextureEnabled?s3.G.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&od.IridescenceTextureEnabled?s3.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,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&p&&e.isSync||(_&&od.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),s3.G.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&od.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._thicknessTexture)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._thicknessTexture)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&s3.G.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||_||d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||s3.G.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&od.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!_&&!d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&od.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"}]}}}pe._DefaultMinimumThickness=100,pe._DefaultMaximumThickness=400,pe._DefaultIndexOfRefraction=1.3,(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pe.prototype,"isEnabled",void 0),(0,r0.gn)([(0,rg.qC)()],pe.prototype,"intensity",void 0),(0,r0.gn)([(0,rg.qC)()],pe.prototype,"minimumThickness",void 0),(0,r0.gn)([(0,rg.qC)()],pe.prototype,"maximumThickness",void 0),(0,r0.gn)([(0,rg.qC)()],pe.prototype,"indexOfRefraction",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pe.prototype,"texture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pe.prototype,"thicknessTexture",void 0);class pt extends s$.H{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class pi extends lg{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 pt,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new rr.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||!od.AnisotropicTextureEnabled||!!this._texture.isReadyOrNotBlocking()}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(rQ.o.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&od.AnisotropicTextureEnabled?s3.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;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&od.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),s3.G.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&od.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,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pi.prototype,"isEnabled",void 0),(0,r0.gn)([(0,rg.qC)()],pi.prototype,"intensity",void 0),(0,r0.gn)([(0,rg.QC)()],pi.prototype,"direction",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pi.prototype,"texture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsMiscDirty")],pi.prototype,"legacy",void 0);class pr extends s$.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 ps extends lg{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new pr,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=rs.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){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!od.SheenTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!od.SheenTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())}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&&od.SheenTextureEnabled?(s3.G.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&od.SheenTextureEnabled?s3.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,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=d.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&p&&e.isSync||(_&&od.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),s3.G.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&od.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&s3.G.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||_||d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||s3.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&&od.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!_&&!d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&od.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,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],ps.prototype,"isEnabled",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],ps.prototype,"linkSheenWithAlbedo",void 0),(0,r0.gn)([(0,rg.qC)()],ps.prototype,"intensity",void 0),(0,r0.gn)([(0,rg.n9)()],ps.prototype,"color",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],ps.prototype,"texture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],ps.prototype,"useRoughnessFromMainTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],ps.prototype,"roughness",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],ps.prototype,"textureRoughness",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],ps.prototype,"albedoScaling",void 0);class pn extends s$.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 pa extends lg{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new pn,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=rs.Wo.White(),this.tintColorAtDistance=1,this.diffusionDistance=rs.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&&od.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;let e=this._getRefractionTexture(t);if(e&&od.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){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,e.SS_USE_GLTF_TEXTURES=!1;return}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;let i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,r=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(r||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&od.ThicknessTextureEnabled&&s3.G.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&od.RefractionIntensityTextureEnabled&&!s&&s3.G.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&od.TranslucencyIntensityTextureEnabled&&!s&&s3.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){let i=this._getRefractionTexture(t);i&&od.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;r.getRenderingMesh().getWorldMatrix().decompose(rr.jp.Vector3[0]);let s=Math.max(Math.abs(rr.jp.Vector3[0].x),Math.abs(rr.jp.Vector3[0].y),Math.abs(rr.jp.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;let s=r.materialDefines,n=this._material.isFrozen,a=this._material.realTimeFiltering,o=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&od.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),s3.G.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&od.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),s3.G.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&od.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),s3.G.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&od.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;!l.isCube&&l.depth&&(t=l.depth);let i=l.getSize().width,r=this.volumeIndexOfRefraction;e.updateFloat4("vRefractionInfos",l.level,1/r,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),a&&e.updateFloat2("vRefractionFilteringInfo",i,rm.R.Log2(i)),l.boundingBoxSize&&(e.updateVector3("vRefractionPosition",l.boundingBoxPosition),e.updateVector3("vRefractionSize",l.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&&od.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&od.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&od.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&od.RefractionTextureEnabled&&(o?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){od.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!od.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,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"isRefractionEnabled",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"isTranslucencyEnabled",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markScenePrePassDirty")],pa.prototype,"isScatteringEnabled",void 0),(0,r0.gn)([(0,rg.qC)()],pa.prototype,"_scatteringDiffusionProfileIndex",void 0),(0,r0.gn)([(0,rg.qC)()],pa.prototype,"refractionIntensity",void 0),(0,r0.gn)([(0,rg.qC)()],pa.prototype,"translucencyIntensity",void 0),(0,r0.gn)([(0,rg.qC)()],pa.prototype,"useAlbedoToTintRefraction",void 0),(0,r0.gn)([(0,rg.qC)()],pa.prototype,"useAlbedoToTintTranslucency",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"thicknessTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"refractionTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"indexOfRefraction",void 0),(0,r0.gn)([(0,rg.qC)()],pa.prototype,"_volumeIndexOfRefraction",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"volumeIndexOfRefraction",null),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"invertRefractionY",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"linkRefractionWithTransparency",void 0),(0,r0.gn)([(0,rg.qC)()],pa.prototype,"minimumThickness",void 0),(0,r0.gn)([(0,rg.qC)()],pa.prototype,"maximumThickness",void 0),(0,r0.gn)([(0,rg.qC)()],pa.prototype,"useThicknessAsDepth",void 0),(0,r0.gn)([(0,rg.n9)()],pa.prototype,"tintColor",void 0),(0,r0.gn)([(0,rg.qC)()],pa.prototype,"tintColorAtDistance",void 0),(0,r0.gn)([(0,rg.n9)()],pa.prototype,"diffusionDistance",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"useMaskFromThicknessTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"refractionIntensityTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"translucencyIntensityTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pa.prototype,"useGltfStyleTextures",void 0);let po={effect:null,subMesh:null};class pl extends s$.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.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class ph extends sY{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new rr.Lt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=ph.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=rs.Wo.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new rs.Wo(0,0,0),this._albedoColor=new rs.Wo(1,1,1),this._reflectivityColor=new rs.Wo(1,1,1),this._reflectionColor=new rs.Wo(1,1,1),this._emissiveColor=new rs.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=ph.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 na.t(16),this._globalAmbientColor=new rs.Wo(0,0,0),this._useLogarithmicDepth=!1,this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new dx(this),this.clearCoat=new d7(this),this.iridescence=new pe(this),this.anisotropy=new pi(this),this.sheen=new ps(this),this.subSurface=new pa(this),this.detailMap=new lT(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),od.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=dv(this.getScene()),this.prePassConfiguration=new ou}get hasRenderTargetTextures(){return!!od.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===ph.PBRMATERIAL_OPAQUE||this._transparencyMode===ph.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||!e.disableAlphaBlending)&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===ph.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==ph.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var r;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(oc.S.GetDefineNames,this._eventInfo),t.materialDefines=new pl(this._eventInfo.defineNames));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=this.getScene(),a=n.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&od.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&od.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&od.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;let e=this._getReflectionTexture();if(e&&od.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&(null===(r=e.getInternalTexture())||void 0===r?void 0:r._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&od.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&od.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(od.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(a.getCaps().standardDerivatives&&this._bumpTexture&&od.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&od.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;a.getCaps().standardDerivatives||e.isVerticesDataPresent(rQ.o.NormalKind)||(e.createNormals(!0),ru.Y.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));let o=t.effect,l=s._areLightsDisposed,h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),u=!1;if(h){if(this._onEffectCreatedObservable&&(po.effect=h,po.subMesh=t,this._onEffectCreatedObservable.notifyObservers(po)),this.allowShaderHotSwapping&&o&&!h.isReady()){if(h=o,s.markAsUnprocessed(),u=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,s,this._materialContext)}return!!(t.effect&&t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!u,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return null!=this._metallic||null!=this._roughness||!!this._metallicTexture}_prepareEffect(e,t,i=null,r=null,s=null,n=null,a){if(this._prepareDefines(e,t,s,n,a),!t.isDirty)return null;t.markAsProcessed();let o=this.getScene(),l=o.getEngine(),h=new nn,u=0;t.USESPHERICALINVERTEX&&h.addFallback(u++,"USESPHERICALINVERTEX"),t.FOG&&h.addFallback(u,"FOG"),t.SPECULARAA&&h.addFallback(u,"SPECULARAA"),t.POINTSIZE&&h.addFallback(u,"POINTSIZE"),t.LOGARITHMICDEPTH&&h.addFallback(u,"LOGARITHMICDEPTH"),t.PARALLAX&&h.addFallback(u,"PARALLAX"),t.PARALLAXOCCLUSION&&h.addFallback(u++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&h.addFallback(u++,"ENVIRONMENTBRDF"),t.TANGENT&&h.addFallback(u++,"TANGENT"),t.BUMP&&h.addFallback(u++,"BUMP"),u=s3.G.HandleFallbacksForShadows(t,h,this._maxSimultaneousLights,u++),t.SPECULARTERM&&h.addFallback(u++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&h.addFallback(u++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&h.addFallback(u++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&h.addFallback(u++,"LIGHTMAP"),t.NORMAL&&h.addFallback(u++,"NORMAL"),t.AMBIENT&&h.addFallback(u++,"AMBIENT"),t.EMISSIVE&&h.addFallback(u++,"EMISSIVE"),t.VERTEXCOLOR&&h.addFallback(u++,"VERTEXCOLOR"),t.MORPHTARGETS&&h.addFallback(u++,"MORPHTARGETS"),t.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");let c=[rQ.o.PositionKind];t.NORMAL&&c.push(rQ.o.NormalKind),t.TANGENT&&c.push(rQ.o.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(rQ.o.ColorKind),t.INSTANCESCOLOR&&c.push(rQ.o.ColorInstanceKind),s3.G.PrepareAttributesForBones(c,e,t,h),s3.G.PrepareAttributesForInstances(c,t),s3.G.PrepareAttributesForMorphTargets(c,e,t),s3.G.PrepareAttributesForBakedVertexAnimation(c,e,t);let d="pbr",p=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"],m={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=u,this._eventInfo.defines=t,this._eventInfo.uniforms=p,this._eventInfo.attributes=c,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(oc.S.PrepareEffect,this._eventInfo),ou.AddUniforms(p),ou.AddSamplers(_),(0,lx.qx)(p),ng.$&&(ng.$.PrepareUniforms(p,t),ng.$.PrepareSamplers(_,t)),s3.G.PrepareUniformsAndSamplersList({uniformsNames:p,uniformBuffersNames:f,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});let g={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,p,f,_,t,c,g));let v=t.toString(),T=l.createEffect(d,{attributes:c,uniformsNames:p,uniformBuffersNames:f,samplers:_,defines:v,fallbacks:h,onCompiled:i,onError:r,indexParameters:m,processFinalCode:g.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},l);return this._eventInfo.customCode=void 0,T}_prepareDefines(e,t,i=null,r=null,s=!1){var n;let a=this.getScene(),o=a.getEngine();s3.G.PrepareDefinesForLights(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,s3.G.PrepareDefinesForMultiview(a,t);let l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(s3.G.PrepareDefinesForPrePass(a,t,this.canRenderToMRT&&!l),s3.G.PrepareDefinesForOIT(a,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(a.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&od.DiffuseTextureEnabled?(s3.G.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&od.AmbientTextureEnabled?(s3.G.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&od.OpacityTextureEnabled?(s3.G.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;let e=this._getReflectionTexture();if(e&&od.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===sv.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 sv.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case sv.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case sv.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case sv.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case sv.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case sv.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case sv.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case sv.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case sv.CUBIC_MODE:case sv.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==sv.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;if(this._lightmapTexture&&od.LightmapTextureEnabled?(s3.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&&od.EmissiveTextureEnabled?(s3.G.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,od.SpecularTextureEnabled){if(this._metallicTexture?(s3.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?(s3.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){let e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(n=this._reflectanceTexture)||void 0===n?void 0:n._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(s3.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)?(s3.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?s3.G.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&od.BumpTextureEnabled&&!this._disableBumpMap?(s3.G.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&od.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&&od.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===ph.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===ph.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(s3.G.PrepareDefinesForMisc(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(rQ.o.NormalKind),t.DEBUGMODE=this._debugMode),s3.G.PrepareDefinesForFrameBoundValues(a,o,this,t,!!i,r,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),s3.G.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==ph.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){let r=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(oc.S.GetDefineNames,this._eventInfo);let s=new pl(this._eventInfo.defineNames),n=this._prepareEffect(e,s,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(po.effect=n,po.subMesh=null,this._onEffectCreatedObservable.notifyObservers(po)),n.isReady()?t&&t(this):n.onCompileObservable.add(()=>{t&&t(this)})}buildUniformLayout(){let 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 r,s,n,a;let o=this.getScene(),l=i.materialDefines;if(!l)return;let h=i.effect;if(!h)return;this._activeEffect=h,t.getMeshUniformBuffer().bindToEffect(h,"Mesh"),t.transferToEffect(e);let u=o.getEngine();this._uniformBuffer.bindToEffect(h,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,o,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),l.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=h._forceRebindOnNextCall||this._mustRebind(o,h,t.visibility);s3.G.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let d=null,p=this._uniformBuffer;if(c){if(this.bindViewProjection(h),d=this._getReflectionTexture(),!p.useUbo||!this.isFrozen||!p.isSync||h._forceRebindOnNextCall){if(o.texturesEnabled){if(this._albedoTexture&&od.DiffuseTextureEnabled&&(p.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),s3.G.BindTextureMatrix(this._albedoTexture,p,"albedo")),this._ambientTexture&&od.AmbientTextureEnabled&&(p.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),s3.G.BindTextureMatrix(this._ambientTexture,p,"ambient")),this._opacityTexture&&od.OpacityTextureEnabled&&(p.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),s3.G.BindTextureMatrix(this._opacityTexture,p,"opacity")),d&&od.ReflectionTextureEnabled){if(p.updateMatrix("reflectionMatrix",d.getReflectionTextureMatrix()),p.updateFloat2("vReflectionInfos",d.level,0),d.boundingBoxSize){let e=d;p.updateVector3("vReflectionPosition",e.boundingBoxPosition),p.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){let e=d.getSize().width;p.updateFloat2("vReflectionFilteringInfo",e,rm.R.Log2(e))}if(!l.USEIRRADIANCEMAP){let e=d.sphericalPolynomial;if(l.USESPHERICALFROMREFLECTIONMAP&&e){if(l.SPHERICAL_HARMONICS){let t=e.preScaledHarmonics;p.updateVector3("vSphericalL00",t.l00),p.updateVector3("vSphericalL1_1",t.l1_1),p.updateVector3("vSphericalL10",t.l10),p.updateVector3("vSphericalL11",t.l11),p.updateVector3("vSphericalL2_2",t.l2_2),p.updateVector3("vSphericalL2_1",t.l2_1),p.updateVector3("vSphericalL20",t.l20),p.updateVector3("vSphericalL21",t.l21),p.updateVector3("vSphericalL22",t.l22)}else p.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),p.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),p.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),p.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),p.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),p.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),p.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),p.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),p.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}}p.updateFloat3("vReflectionMicrosurfaceInfos",d.getSize().width,d.lodGenerationScale,d.lodGenerationOffset)}this._emissiveTexture&&od.EmissiveTextureEnabled&&(p.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),s3.G.BindTextureMatrix(this._emissiveTexture,p,"emissive")),this._lightmapTexture&&od.LightmapTextureEnabled&&(p.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),s3.G.BindTextureMatrix(this._lightmapTexture,p,"lightmap")),od.SpecularTextureEnabled&&(this._metallicTexture?(p.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),s3.G.BindTextureMatrix(this._metallicTexture,p,"reflectivity")):this._reflectivityTexture&&(p.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),s3.G.BindTextureMatrix(this._reflectivityTexture,p,"reflectivity")),this._metallicReflectanceTexture&&(p.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),s3.G.BindTextureMatrix(this._metallicReflectanceTexture,p,"metallicReflectance")),this._reflectanceTexture&&l.REFLECTANCE&&(p.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),s3.G.BindTextureMatrix(this._reflectanceTexture,p,"reflectance")),this._microSurfaceTexture&&(p.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),s3.G.BindTextureMatrix(this._microSurfaceTexture,p,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&od.BumpTextureEnabled&&!this._disableBumpMap&&(p.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),s3.G.BindTextureMatrix(this._bumpTexture,p,"bump"),o._mirroredCameraPosition?p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&p.updateFloat("pointSize",this.pointSize),l.METALLICWORKFLOW){rs.zZ.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,rs.zZ.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,p.updateColor4("vReflectivityColor",rs.zZ.Color3[0],1);let e=null!==(s=null===(r=this.subSurface)||void 0===r?void 0:r._indexOfRefraction)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((e-1)/(e+1),2)*this._metallicF0Factor,rs.zZ.Color3[0]);let t=this._metallicF0Factor;p.updateColor4("vMetallicReflectanceFactors",rs.zZ.Color3[0],t)}else p.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);p.updateColor3("vEmissiveColor",od.EmissiveTextureEnabled?this._emissiveColor:rs.Wo.BlackReadOnly),p.updateColor3("vReflectionColor",this._reflectionColor),!l.SS_REFRACTION&&(null===(n=this.subSurface)||void 0===n?void 0:n._linkRefractionWithTransparency)?p.updateColor4("vAlbedoColor",this._albedoColor,1):p.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*o.environmentIntensity,this._lightingInfos.w=this._specularIntensity,p.updateVector4("vLightingIntensity",this._lightingInfos),o.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),p.updateColor3("vAmbientColor",this._globalAmbientColor),p.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}o.texturesEnabled&&(this._albedoTexture&&od.DiffuseTextureEnabled&&p.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&od.AmbientTextureEnabled&&p.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&od.OpacityTextureEnabled&&p.setTexture("opacitySampler",this._opacityTexture),d&&od.ReflectionTextureEnabled&&(l.LODBASEDMICROSFURACE?p.setTexture("reflectionSampler",d):(p.setTexture("reflectionSampler",d._lodTextureMid||d),p.setTexture("reflectionSamplerLow",d._lodTextureLow||d),p.setTexture("reflectionSamplerHigh",d._lodTextureHigh||d)),l.USEIRRADIANCEMAP&&p.setTexture("irradianceSampler",d.irradianceTexture)),l.ENVIRONMENTBRDF&&p.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&od.EmissiveTextureEnabled&&p.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&od.LightmapTextureEnabled&&p.setTexture("lightmapSampler",this._lightmapTexture),od.SpecularTextureEnabled&&(this._metallicTexture?p.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&p.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&p.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&l.REFLECTANCE&&p.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&p.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&od.BumpTextureEnabled&&!this._disableBumpMap&&p.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(h),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,lx.an)(this._activeEffect,this,o),this.bindEyePosition(h)}else o.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(c||!this.isFrozen)&&(o.lightsEnabled&&!this._disableLighting&&s3.G.BindLights(o,t,this._activeEffect,l,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==rI.x.FOGMODE_NONE||d||t.receiveShadows||l.PREPASS)&&this.bindView(h),s3.G.BindFogParameters(o,t,this._activeEffect,!0),l.NUM_MORPH_INFLUENCERS&&s3.G.BindMorphTargetParameters(t,this._activeEffect),l.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(a=t.bakedVertexAnimationManager)||void 0===a||a.bind(h,l.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),s3.G.BindLogDepth(l,this._activeEffect,o)),this._afterBind(t,this._activeEffect),p.update()}getAnimatables(){let 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(){let 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;let t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,r,s,n,a,o,l,h,u,c,d,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(n=this._reflectionTexture)||void 0===n||n.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._metallicTexture)||void 0===o||o.dispose(),null===(l=this._reflectivityTexture)||void 0===l||l.dispose(),null===(h=this._bumpTexture)||void 0===h||h.dispose(),null===(u=this._lightmapTexture)||void 0===u||u.dispose(),null===(c=this._metallicReflectanceTexture)||void 0===c||c.dispose(),null===(d=this._reflectanceTexture)||void 0===d||d.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)}}ph.PBRMATERIAL_OPAQUE=sX.F.MATERIAL_OPAQUE,ph.PBRMATERIAL_ALPHATEST=sX.F.MATERIAL_ALPHATEST,ph.PBRMATERIAL_ALPHABLEND=sX.F.MATERIAL_ALPHABLEND,ph.PBRMATERIAL_ALPHATESTANDBLEND=sX.F.MATERIAL_ALPHATESTANDBLEND,ph.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,ph.LIGHTFALLOFF_PHYSICAL=0,ph.LIGHTFALLOFF_GLTF=1,ph.LIGHTFALLOFF_STANDARD=2,(0,r0.gn)([(0,rg.rX)()],ph.prototype,"_imageProcessingConfiguration",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsMiscDirty")],ph.prototype,"debugMode",void 0),(0,r0.gn)([(0,rg.qC)()],ph.prototype,"useLogarithmicDepth",null);class pu extends ph{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===ph.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=ph.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=ph.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===ph.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=ph.LIGHTFALLOFF_GLTF:this._lightFalloff=ph.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=pu.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=rs.Wo.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new rs.Wo(0,0,0),this.albedoColor=new rs.Wo(1,1,1),this.reflectivityColor=new rs.Wo(1,1,1),this.reflectionColor=new rs.Wo(1,1,1),this.emissiveColor=new rs.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.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=dv(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){let r=rg.p4.Clone(()=>new pu(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){let r=rg.p4.Parse(()=>new pu(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),sX.F._parsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}function pc(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}pu.PBRMATERIAL_OPAQUE=ph.PBRMATERIAL_OPAQUE,pu.PBRMATERIAL_ALPHATEST=ph.PBRMATERIAL_ALPHATEST,pu.PBRMATERIAL_ALPHABLEND=ph.PBRMATERIAL_ALPHABLEND,pu.PBRMATERIAL_ALPHATESTANDBLEND=ph.PBRMATERIAL_ALPHATESTANDBLEND,pu.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=ph.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"directIntensity",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"emissiveIntensity",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"environmentIntensity",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"specularIntensity",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"disableBumpMap",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"albedoTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"ambientTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"ambientTextureStrength",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pu.prototype,"opacityTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"reflectionTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"emissiveTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"reflectivityTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"metallicTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"metallic",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"roughness",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"metallicF0Factor",void 0),(0,r0.gn)([(0,rg.n9)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"metallicReflectanceColor",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"metallicReflectanceTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"reflectanceTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"microSurfaceTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"bumpTexture",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty",null)],pu.prototype,"lightmapTexture",void 0),(0,r0.gn)([(0,rg.n9)("ambient"),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"ambientColor",void 0),(0,r0.gn)([(0,rg.n9)("albedo"),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"albedoColor",void 0),(0,r0.gn)([(0,rg.n9)("reflectivity"),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"reflectivityColor",void 0),(0,r0.gn)([(0,rg.n9)("reflection"),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"reflectionColor",void 0),(0,r0.gn)([(0,rg.n9)("emissive"),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"emissiveColor",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"microSurface",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useLightmapAsShadowmap",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pu.prototype,"useAlphaFromAlbedoTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pu.prototype,"forceAlphaTest",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pu.prototype,"alphaCutOff",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useSpecularOverAlpha",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useRoughnessFromMetallicTextureGreen",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useMetallnessFromMetallicTextureBlue",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useAmbientInGrayScale",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),(0,r0.gn)([(0,rg.qC)()],pu.prototype,"usePhysicalLightFalloff",null),(0,r0.gn)([(0,rg.qC)()],pu.prototype,"useGLTFLightFalloff",null),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useRadianceOverAlpha",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useObjectSpaceNormalMap",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useParallax",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useParallaxOcclusion",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"parallaxScaleBias",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsLightsDirty")],pu.prototype,"disableLighting",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"forceIrradianceInFragment",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsLightsDirty")],pu.prototype,"maxSimultaneousLights",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"invertNormalMapX",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"invertNormalMapY",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"twoSidedLighting",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useAlphaFresnel",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useLinearAlphaFresnel",void 0),(0,r0.gn)([(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"environmentBRDFTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"forceNormalForward",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"enableSpecularAntiAliasing",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useHorizonOcclusion",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],pu.prototype,"useRadianceOcclusion",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsMiscDirty")],pu.prototype,"unlit",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsMiscDirty")],pu.prototype,"applyDecalMapAfterDetailMap",void 0),(0,rn.H)("BABYLON.PBRMaterial",pu);let pd=pc("DXT1"),pp=pc("DXT3"),p_=pc("DXT5"),pf=pc("DX10");class pm{static GetDDSInfo(e){let t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35),r=1;131072&t[2]&&(r=Math.max(1,t[7]));let s=t[21],n=s===pf?i[32]:0,a=0;switch(s){case 113:a=2;break;case 116:a=1;break;case pf:if(10===n){a=2;break}2===n&&(a=1)}return{width:t[4],height:t[3],mipmapCount:r,isFourCC:(4&t[20])==4,isRGB:(64&t[20])==64,isLuminance:(131072&t[20])==131072,isCube:(512&t[28])==512,isCompressed:s===pd||s===pp||s===p_,dxgiFormat:n,textureType:a}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,n){let a=new Float32Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;a[l]=h8(o[r]),a[l+1]=h8(o[r+1]),a[l+2]=h8(o[r+2]),pm.StoreLODInAlphaChannel?a[l+3]=n:a[l+3]=h8(o[r+3]),l+=4}return a}static _GetHalfFloatRGBAArrayBuffer(e,t,i,r,s,n){if(pm.StoreLODInAlphaChannel){let a=new Uint16Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;a[l]=o[r],a[l+1]=o[r+1],a[l+2]=o[r+2],a[l+3]=h6(n),l+=4}return a}return new Uint16Array(s,i,r)}static _GetFloatRGBAArrayBuffer(e,t,i,r,s,n){if(pm.StoreLODInAlphaChannel){let a=new Float32Array(r),o=new Float32Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;a[l]=o[r],a[l+1]=o[r+1],a[l+2]=o[r+2],a[l+3]=n,l+=4}return a}return new Float32Array(s,i,r)}static _GetFloatAsHalfFloatRGBAArrayBuffer(e,t,i,r,s,n){let a=new Uint16Array(r),o=new Float32Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++)a[l]=h6(o[l]),a[l+1]=h6(o[l+1]),a[l+2]=h6(o[l+2]),pm.StoreLODInAlphaChannel?a[l+3]=h6(n):a[l+3]=h6(o[l+3]),l+=4;return a}static _GetFloatAsUIntRGBAArrayBuffer(e,t,i,r,s,n){let a=new Uint8Array(r),o=new Float32Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;a[l]=255*rm.R.Clamp(o[r]),a[l+1]=255*rm.R.Clamp(o[r+1]),a[l+2]=255*rm.R.Clamp(o[r+2]),pm.StoreLODInAlphaChannel?a[l+3]=n:a[l+3]=255*rm.R.Clamp(o[r+3]),l+=4}return a}static _GetHalfFloatAsUIntRGBAArrayBuffer(e,t,i,r,s,n){let a=new Uint8Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;a[l]=255*rm.R.Clamp(h8(o[r])),a[l+1]=255*rm.R.Clamp(h8(o[r+1])),a[l+2]=255*rm.R.Clamp(h8(o[r+2])),pm.StoreLODInAlphaChannel?a[l+3]=n:a[l+3]=255*rm.R.Clamp(h8(o[r+3])),l+=4}return a}static _GetRGBAArrayBuffer(e,t,i,r,s,n,a,o,l){let h=new Uint8Array(r),u=new Uint8Array(s,i),c=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*4;h[c]=u[r+n],h[c+1]=u[r+a],h[c+2]=u[r+o],h[c+3]=u[r+l],c+=4}return h}static _ExtractLongWordOrder(e){return 0===e||255===e||-16777216===e?0:1+pm._ExtractLongWordOrder(e>>8)}static _GetRGBArrayBuffer(e,t,i,r,s,n,a,o){let l=new Uint8Array(r),h=new Uint8Array(s,i),u=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=(t+i*e)*3;l[u]=h[r+n],l[u+1]=h[r+a],l[u+2]=h[r+o],u+=3}return l}static _GetLuminanceArrayBuffer(e,t,i,r,s){let n=new Uint8Array(r),a=new Uint8Array(s,i),o=0;for(let i=0;i<t;i++)for(let t=0;t<e;t++){let r=t+i*e;n[o]=a[r],o++}return n}static UploadDDSLevels(e,t,i,r,s,n,a=-1,o,l=!0){let h,u,c,d=null;r.sphericalPolynomial&&(d=[]);let p=!!e.getCaps().s3tc;t.generateMipMaps=s;let _=new Int32Array(i.buffer,i.byteOffset,31),f,m,g,v=0,T,x=0,S=1;if(542327876!==_[0]){ru.Y.Error("Invalid magic number in DDS header");return}if(!r.isFourCC&&!r.isRGB&&!r.isLuminance){ru.Y.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");return}if(r.isCompressed&&!p){ru.Y.Error("Compressed textures are not supported on this platform.");return}let E=_[22];T=_[1]+4;let C=!1;if(r.isFourCC)switch(f=_[21]){case pd:S=8,x=33777;break;case pp:S=16,x=33778;break;case p_:S=16,x=33779;break;case 113:C=!0,E=64;break;case 116:C=!0,E=128;break;case pf:{T+=20;let e=!1;switch(r.dxgiFormat){case 10:C=!0,E=64,e=!0;break;case 2:C=!0,E=128,e=!0;break;case 88:r.isRGB=!0,r.isFourCC=!1,E=32,e=!0}if(e)break}default:console.error("Unsupported FourCC code:",String.fromCharCode(255&f,f>>8&255,f>>16&255,f>>24&255));return}let b=pm._ExtractLongWordOrder(_[23]),y=pm._ExtractLongWordOrder(_[24]),A=pm._ExtractLongWordOrder(_[25]),R=pm._ExtractLongWordOrder(_[26]);C&&(x=e._getRGBABufferInternalSizedFormat(r.textureType)),u=1,131072&_[2]&&!1!==s&&(u=Math.max(1,_[7]));let P=o||0,I=e.getCaps();for(let s=P;s<n;s++){for(c=0,m=_[4],g=_[3];c<u;++c){if(-1===a||a===c){let n=-1===a?c:0;if(!r.isCompressed&&r.isFourCC){t.format=5,v=m*g*4;let r=null;if(e._badOS||e._badDesktopOS||!I.textureHalfFloat&&!I.textureFloat)128===E?(r=pm._GetFloatAsUIntRGBAArrayBuffer(m,g,i.byteOffset+T,v,i.buffer,n),d&&0==n&&d.push(pm._GetFloatRGBAArrayBuffer(m,g,i.byteOffset+T,v,i.buffer,n))):64===E&&(r=pm._GetHalfFloatAsUIntRGBAArrayBuffer(m,g,i.byteOffset+T,v,i.buffer,n),d&&0==n&&d.push(pm._GetHalfFloatAsFloatRGBAArrayBuffer(m,g,i.byteOffset+T,v,i.buffer,n))),t.type=0;else{let e;let s=I.textureFloat&&(l&&I.textureFloatLinearFiltering||!l),a=I.textureHalfFloat&&(l&&I.textureHalfFloatLinearFiltering||!l),o=(128===E||64===E&&!a)&&s?1:(64===E||128===E&&!s)&&a?2:0,h=null;if(128===E)switch(o){case 1:e=pm._GetFloatRGBAArrayBuffer,h=null;break;case 2:e=pm._GetFloatAsHalfFloatRGBAArrayBuffer,h=pm._GetFloatRGBAArrayBuffer;break;case 0:e=pm._GetFloatAsUIntRGBAArrayBuffer,h=pm._GetFloatRGBAArrayBuffer}else switch(o){case 1:e=pm._GetHalfFloatAsFloatRGBAArrayBuffer,h=null;break;case 2:e=pm._GetHalfFloatRGBAArrayBuffer,h=pm._GetHalfFloatAsFloatRGBAArrayBuffer;break;case 0:e=pm._GetHalfFloatAsUIntRGBAArrayBuffer,h=pm._GetHalfFloatAsFloatRGBAArrayBuffer}t.type=o,r=e(m,g,i.byteOffset+T,v,i.buffer,n),d&&0==n&&d.push(h?h(m,g,i.byteOffset+T,v,i.buffer,n):r)}r&&e._uploadDataToTextureDirectly(t,r,s,n)}else if(r.isRGB)t.type=0,24===E?(t.format=4,v=m*g*3,h=pm._GetRGBArrayBuffer(m,g,i.byteOffset+T,v,i.buffer,b,y,A),e._uploadDataToTextureDirectly(t,h,s,n)):(t.format=5,v=m*g*4,h=pm._GetRGBAArrayBuffer(m,g,i.byteOffset+T,v,i.buffer,b,y,A,R),e._uploadDataToTextureDirectly(t,h,s,n));else if(r.isLuminance){let r=e._getUnpackAlignement(),a=m,o=Math.floor((m+r-1)/r)*r;v=o*(g-1)+a,h=pm._GetLuminanceArrayBuffer(m,g,i.byteOffset+T,v,i.buffer),t.format=1,t.type=0,e._uploadDataToTextureDirectly(t,h,s,n)}else v=Math.max(4,m)/4*Math.max(4,g)/4*S,h=new Uint8Array(i.buffer,i.byteOffset+T,v),t.type=0,e._uploadCompressedDataToTextureDirectly(t,x,m,g,h,s,n)}T+=E?m*g*(E/8):v,m*=.5,g*=.5,m=Math.max(1,m),g=Math.max(1,g)}if(void 0!==o)break}d&&d.length>0?r.sphericalPolynomial=ue.ConvertCubeMapToSphericalPolynomial({size:_[4],right:d[0],left:d[1],up:d[2],down:d[3],front:d[4],back:d[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}}pm.StoreLODInAlphaChannel=!1,sx.B.prototype.createPrefilteredCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!0){return this.createCubeTexture(e,t,null,!1,e=>{if(!e){s&&s(null);return}let n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new h3,n._source=sT.S.CubePrefiltered,this.getCaps().textureLOD){s&&s(n);return}let a=this._gl,o=e.width;if(!o)return;let h=[];for(let s=0;s<3;s++){let l=s/2,u=1-l,c=rm.R.Log2(o)*i+r,d=r+(c-r)*u,p=Math.round(Math.min(Math.max(d,0),c)),_=new sT.l(this,sT.S.Temp);if(_.type=n.type,_.format=n.format,_.width=Math.pow(2,Math.max(rm.R.Log2(o)-p,0)),_.height=_.width,_.isCube=!0,_._cachedWrapU=0,_._cachedWrapV=0,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,_,!0),_.samplingMode=2,a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),e.isDDS){let t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),pm.UploadDDSLevels(this,_,i,t,!0,6,p)}else ru.Y.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);let f=new su(t);f._isCube=!0,f._texture=_,_.isReady=!0,h.push(f)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],s&&s(n)},n,a,o,l,i,r)},r7.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,r){let s;let n=t.getEngine(),a=!1,o=1e3;if(Array.isArray(e))for(let i=0;i<e.length;i++){let r=e[i];s=pm.GetDDSInfo(r),t.width=s.width,t.height=s.height,a=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,n._unpackFlipY(s.isCompressed),pm.UploadDDSLevels(n,t,r,s,a,6,-1,i),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:n.generateMipMapsForCubemap(t)}else s=pm.GetDDSInfo(e),t.width=s.width,t.height=s.height,i&&(s.sphericalPolynomial=new h3),a=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,n._unpackFlipY(s.isCompressed),pm.UploadDDSLevels(n,t,e,s,a,6),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:n.generateMipMapsForCubemap(t,!1);n._setCubeMapTextureParams(t,a,o),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:s,data:e,texture:t})}loadData(e,t,i){let r=pm.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&r.width>>r.mipmapCount-1==1;i(r.width,r.height,s,r.isFourCC,()=>{pm.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}}),r7.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let n=us(e);if(n){t.width=n.width,t.height=n.width;try{ul(t,n),(function(e,t,i){i=un(i);let r=i.specular;if(!r)return Promise.resolve();e._lodGenerationScale=r.lodGenerationScale;let s=ua(t,i);return function(e,t,i=ui){if(!rZ.w1.IsExponentOfTwo(e.width))throw Error("Texture size must be a power of two");let r=rm.R.ILog2(e.width)+1,s=e.getEngine(),n=!1,a=!1,o=null,l=null,h=null,u=s.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,e),u.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?u.textureHalfFloatRender&&u.textureHalfFloatLinearFiltering?(n=!0,e.type=2):u.textureFloatRender&&u.textureFloatLinearFiltering&&(n=!0,e.type=1):n=!1:(n=!1,a=!0,h={}),n)o=new np("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,a){let t=e._lodGenerationScale,i=e._lodGenerationOffset;for(let n=0;n<3;n++){let a=n/2,o=1-a,l=(r-1)*t+i,u=i+(l-i)*o,c=Math.round(Math.min(Math.max(u,0),l)),d=new sT.l(s,sT.S.Temp);d.isCube=!0,d.invertY=!0,d.generateMipMaps=!1,s.updateTextureSamplingMode(2,d);let p=new su(null);switch(p._isCube=!0,p._texture=d,h[c]=p,n){case 0:e._lodTextureLow=p;break;case 1:e._lodTextureMid=p;break;case 2:e._lodTextureHigh=p}}}let c=[];for(let r=0;r<t.length;r++)for(let u=0;u<6;u++){let d;let p=t[r][u],_=new Blob([p],{type:i}),f=URL.createObjectURL(_);if("undefined"==typeof Image||s._features.forceBitmapOverHTMLImageElement)d=s.createImageBitmap(_,{premultiplyAlpha:"none"}).then(t=>uo(t,s,n,o,f,u,r,a,h,l,e));else{let t=new Image;t.src=f,d=new Promise((i,c)=>{t.onload=()=>{uo(t,s,n,o,f,u,r,a,h,l,e).then(()=>i()).catch(e=>{c(e)})},t.onerror=e=>{c(e)}})}c.push(d)}if(t.length<r){let i;let n=Math.pow(2,r-1-t.length),a=n*n*4;switch(e.type){case 0:i=new Uint8Array(a);break;case 2:i=new Uint16Array(a);break;case 1:i=new Float32Array(a)}for(let n=t.length;n<r;n++)for(let t=0;t<6;t++)s._uploadArrayBufferViewToTexture(e,i,t,n)}return Promise.all(c).then(()=>{l&&(s._releaseTexture(e),l._swapAndDie(e)),o&&o.dispose(),a&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))})}(e,s,i.imageType)})(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},e=>{null==s||s("Can not upload environment levels",e)})}catch(e){null==s||s("Can not upload environment file",e)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}});class pg{constructor(e,t){if(this.data=e,this.isInvalid=!1,!pg.IsValid(e)){this.isInvalid=!0,ru.Y.Error("texture missing KTX identifier");return}let i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=r.getUint32(0,!0),n=67305985===s;if(this.glType=r.getUint32(1*i,n),this.glTypeSize=r.getUint32(2*i,n),this.glFormat=r.getUint32(3*i,n),this.glInternalFormat=r.getUint32(4*i,n),this.glBaseInternalFormat=r.getUint32(5*i,n),this.pixelWidth=r.getUint32(6*i,n),this.pixelHeight=r.getUint32(7*i,n),this.pixelDepth=r.getUint32(8*i,n),this.numberOfArrayElements=r.getUint32(9*i,n),this.numberOfFaces=r.getUint32(10*i,n),this.numberOfMipmapLevels=r.getUint32(11*i,n),this.bytesOfKeyValueData=r.getUint32(12*i,n),0!==this.glType){ru.Y.Error("only compressed formats currently supported"),this.isInvalid=!0;return}if(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth){ru.Y.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(0!==this.numberOfArrayElements){ru.Y.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){ru.Y.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=pg.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case pg.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case pg.TEX_2D:case pg.COMPRESSED_3D:case pg.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=pg.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight,n=t?this.numberOfMipmapLevels:1;for(let t=0;t<n;t++){let n=new Int32Array(this.data.buffer,this.data.byteOffset+i,1)[0];i+=4;for(let a=0;a<this.numberOfFaces;a++){let o=new Uint8Array(this.data.buffer,this.data.byteOffset+i,n),l=e.getEngine();l._uploadCompressedDataToTextureDirectly(e,e.format,r,s,o,a,t),i+=n+(3-(n+3)%4)}r=Math.max(1,.5*r),s=Math.max(1,.5*s)}}static IsValid(e){if(e.byteLength>=12){let 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}}pg.HEADER_LEN=64,pg.COMPRESSED_2D=0,pg.COMPRESSED_3D=1,pg.TEX_2D=2,pg.TEX_3D=3;class pv{constructor(e){this._pendingActions=[],this._workerInfos=e.map(e=>({workerPromise:Promise.resolve(e),idle:!0}))}dispose(){for(let 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(let 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,()=>{let t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0})})}}class pT extends pv{constructor(e,t,i=pT.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e)){if(this._workerInfos.length<this._maxWorkers){let t={workerPromise:this._createWorkerAsync(),idle:!1};this._workerInfos.push(t),this._execute(t,e)}else this._pendingActions.push(e)}}_execute(e,t){e.timeoutId&&(clearTimeout(e.timeoutId),delete e.timeoutId),super._execute(e,(i,r)=>{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(e=>{e.terminate()});let t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)},this._options.idleTimeElapsedBeforeRelease))})})}}function px(e){return e?rZ.w1.GetAbsoluteUrl(e):null}function pS(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)}pT.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},(eb=iv||(iv={}))[eb.ETC1S=0]="ETC1S",eb[eb.UASTC4x4=1]="UASTC4x4",(ey=iT||(iT={}))[ey.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",ey[ey.BC7_RGBA=1]="BC7_RGBA",ey[ey.BC3_RGBA=2]="BC3_RGBA",ey[ey.BC1_RGB=3]="BC1_RGB",ey[ey.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",ey[ey.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",ey[ey.ETC2_RGBA=6]="ETC2_RGBA",ey[ey.ETC1_RGB=7]="ETC1_RGB",ey[ey.RGBA32=8]="RGBA32",ey[ey.R8=9]="R8",ey[ey.RG8=10]="RG8",(eA=ix||(ix={}))[eA.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",eA[eA.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",eA[eA.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",eA[eA.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",eA[eA.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",eA[eA.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",eA[eA.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",eA[eA.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",eA[eA.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",eA[eA.RGBA8Format=32856]="RGBA8Format",eA[eA.R8Format=33321]="R8Format",eA[eA.RG8Format=33323]="RG8Format";class pE{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(pE._WorkerPoolPromise||pE._DecoderModulePromise)return;let t={jsDecoderModule:rZ.w1.GetAbsoluteUrl(this.URLConfig.jsDecoderModule),wasmUASTCToASTC:px(this.URLConfig.wasmUASTCToASTC),wasmUASTCToBC7:px(this.URLConfig.wasmUASTCToBC7),wasmUASTCToRGBA_UNORM:px(this.URLConfig.wasmUASTCToRGBA_UNORM),wasmUASTCToRGBA_SRGB:px(this.URLConfig.wasmUASTCToRGBA_SRGB),wasmUASTCToR8_UNORM:px(this.URLConfig.wasmUASTCToR8_UNORM),wasmUASTCToRG8_UNORM:px(this.URLConfig.wasmUASTCToRG8_UNORM),jsMSCTranscoder:px(this.URLConfig.jsMSCTranscoder),wasmMSCTranscoder:px(this.URLConfig.wasmMSCTranscoder),wasmZSTDDecoder:px(this.URLConfig.wasmZSTDDecoder)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?pE._WorkerPoolPromise=new Promise(i=>{let r=`${pS}(${pC})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new pT(e,()=>new Promise((e,i)=>{let r=new Worker(s),n=e=>{r.removeEventListener("error",n),r.removeEventListener("message",a),i(e)},a=t=>{"init"===t.data.action&&(r.removeEventListener("error",n),r.removeEventListener("message",a),e(r))};r.addEventListener("error",n),r.addEventListener("message",a),r.postMessage({action:"init",urls:t})})))}):"undefined"==typeof KTX2DECODER?pE._DecoderModulePromise=rZ.w1.LoadScriptAsync(t.jsDecoderModule).then(()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,pS(t),new KTX2DECODER.KTX2Decoder)):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,pE._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=pE.DefaultNumWorkers){this._engine=e,pE._Initialize(t)}uploadAsync(e,t,i){let r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(pE._WorkerPoolPromise)return pE._WorkerPoolPromise.then(r=>new Promise((n,a)=>{r.push((r,o)=>{let l=e=>{r.removeEventListener("error",l),r.removeEventListener("message",h),a(e),o()},h=e=>{if("decoded"===e.data.action){if(r.removeEventListener("error",l),r.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){a({message:e})}else a({message:e.data.msg});o()}};r.addEventListener("error",l),r.addEventListener("message",h),r.postMessage({action:"setDefaultDecoderOptions",options:pE.DefaultDecoderOptions._getKTX2DecoderOptions()});let u=new Uint8Array(e.byteLength);u.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),r.postMessage({action:"decode",data:u,caps:s,options:i},[u.buffer])})}));if(pE._DecoderModulePromise)return pE._DecoderModulePromise.then(i=>(pE.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=pE.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((s,n)=>{i.decode(e,r).then(e=>{this._createTexture(e,t),s()}).catch(e=>{n({message:e})})})));throw Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let r=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,r=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i<e.mipmaps.length;++i){let s=e.mipmaps[i];if(!s||!s.data)throw Error("KTX2 container - could not transcode one of the image");r?(t.width=s.width,t.height=s.height,this._engine._uploadDataToTextureDirectly(t,s.data,0,i,void 0,!0)):this._engine._uploadCompressedDataToTextureDirectly(t,e.transcodedFormat,s.width,s.height,s.data,0,i)}t._extension=".ktx2",t.width=e.mipmaps[0].width,t.height=e.mipmaps[0].height,t.isReady=!0,this._engine._bindTextureDirectly(3553,null)}static IsValid(e){if(e.byteLength>=12){let 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 pC(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{let i=t.data.urls;importScripts(i.jsDecoderModule),pS(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=>{let t=[];for(let i=0;i<e.mipmaps.length;++i){let r=e.mipmaps[i];r&&r.data&&t.push(r.data.buffer)}postMessage({action:"decoded",success:!0,decodedData:e},t)}).catch(e=>{postMessage({action:"decoded",success:!1,msg:e})})}}}pE.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},pE.DefaultNumWorkers=pE.GetDefaultNumWorkers(),pE.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;let e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[iT.BC1_RGB,iT.BC3_RGBA],yes:{transcodeFormat:iT.RGBA32,engineFormat:ix.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}},r7.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,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;let s=t.getEngine(),n=new pg(e,6),a=n.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,s._setCubeMapTextureParams(t,a,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(pg.IsValid(e)){t._invertVScale=!t.invertY;let r=new pg(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}(r.glInternalFormat);s?(t.format=s,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=r.glInternalFormat,i(r.pixelWidth,r.pixelHeight,t.generateMipMaps,!0,()=>{r.uploadLevels(t,t.generateMipMaps)},r.isInvalid)}else if(pE.IsValid(e)){let s=new pE(t.getEngine());s.uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},e=>{ru.Y.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,()=>{},!0)})}else ru.Y.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0)}});class pb extends ab{constructor(e,t,i){super(e,rr.P.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=rr._f.Identity(),this._referencedPosition=new rr.P,this._trackingState=tO.NOT_TRACKING,this.onBeforeCameraTeleport=new ri.y$,this.onAfterCameraTeleport=new ri.y$,this.onTrackingStateChanged=new ri.y$,this.compensateOnFirstFrame=!0,this._rotate180=new rr._f(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new rr._f,this.cameraRigMode=r4.V.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add(()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame}),this._xrSessionManager.onXRFrameObservable.add(()=>{this._firstFrame&&this._updateFromXRSession(),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()},void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){let 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 s6.l(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new s6.l(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){if(!e||e===this)return;let i=e.computeWorldMatrix();i.decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,rr._f.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){let t=rr.jp.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();let i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),rr._f.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(tO.NOT_TRACKING);return}let t=e.emulatedPosition?tO.TRACKING_LOST:tO.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){let 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){let t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;let 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;let r=this.rigCameras[t];r.isLeftCamera||r.isRightCamera||("right"===e.eye?r._isRightCamera=!0:"left"!==e.eye||(r._isLeftCamera=!0));let s=e.transform.position,n=e.transform.orientation;r.parent=this.parent,r.position.set(s.x,s.y,s.z),r.rotationQuaternion.set(n.x,n.y,n.z,n.w),this._scene.useRightHandedSystem?r.rotationQuaternion.multiplyInPlace(this._rotate180):(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1),rr.y3.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,r._projectionMatrix),this._scene.useRightHandedSystem||r._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(r._projectionMatrix);let 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(r.viewport,e),r.outputRenderTarget=a||this._xrSessionManager.getRenderTargetTextureForView(e)),r.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.length<e;){let e=new aC("XR-RigCamera: "+this.rigCameras.length,rr.P.Zero(),this.getScene());e.minZ=.1,e.rotationQuaternion=new rr._f,e.updateUpVectorFromRotation=!0,e.isRigCamera=!0,e.rigParent=this,e.freezeProjectionMatrix(),this.rigCameras.push(e)}for(;this.rigCameras.length>e;){let e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){let e=rr.jp.Matrix[0],t=rr.jp.Matrix[1],i=rr.jp.Matrix[2];rr.y3.ComposeToRef(pb._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),rr.y3.ComposeToRef(pb._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);let r=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(r)}}}pb._ScaleReadOnly=rr.P.One();class py{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 ri.y$,this.onStateChangedObservable=new ri.y$,this.state=tD.NOT_IN_XR,this.sessionManager=new lB(e),this.camera=new pb("webxr",e,this.sessionManager),this.featuresManager=new sU(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){let t=new py(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(e=>{throw t._setState(tD.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(),r={}){var s,n,a;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(tD.ENTERING_XR),"viewer"!==t&&"local"!==t&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),"immersive-ar"===e&&"unbounded"!==t&&ru.Y.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);let o=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(sB.LAYERS)||(l.baseLayer=o),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(n=null===(s=this._nonVRCamera)||void 0===s?void 0:s.inputs)||void 0===n?void 0:n.attachedToElement),null===(a=this._nonVRCamera)||void 0===a||a.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!==tD.EXITING_XR&&this._setState(tD.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(tD.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(tD.IN_XR)}),this.sessionManager}catch(e){throw console.log(e),console.log(e.message),this._setState(tD.NOT_IN_XR),e}}exitXRAsync(){return this.state!==tD.IN_XR?Promise.resolve():(this._setState(tD.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){let t=(null==e?void 0:e.fps)?e.fps:1e3,i=1/t*1e3,r=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,s=()=>{if(this._spectatorCamera){let e=this.sessionManager.currentTimestamp-this._lastTimestamp;e>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[r].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[r].absoluteRotation))}};if(this._spectatorMode){if(r>=this.camera.rigCameras.length)throw Error("the preferred camera index is beyond the length of rig camera array.");let e=()=>{this.state===tD.IN_XR?(this._spectatorCamera=new aV("webxr-spectator",rr.P.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new rr._f,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(s),this._scene.onAfterRenderCameraObservable.add(e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===tD.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class pA{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new ri.y$,this.onButtonStateChangedObservable=new ri.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()){let 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))}}pA.BUTTON_TYPE="button",pA.SQUEEZE_TYPE="squeeze",pA.THUMBSTICK_TYPE="thumbstick",pA.TOUCHPAD_TYPE="touchpad",pA.TRIGGER_TYPE="trigger";class pR{constructor(e,t,i,r,s=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=n,this._initComponent=e=>{if(!e)return;let t=this.layout.components[e],i=t.type,r=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new pA(e,i,r,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new ri.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(){let e=!this._getModelLoadingConstraints(),t=this._getGenericFilenameAndPath();return e?ru.Y.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,r)=>{let s=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){let e=this._controllerCache.filter(e=>e.filename===t.filename&&e.path===t.path);if(e[0]){e[0].meshes.forEach(e=>e.setEnabled(!0)),s(e[0].meshes);return}}sH.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)=>{ru.Y.Log(i),ru.Y.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(i)})})}updateFromXRFrame(e){this.getComponentIds().forEach(e=>this.getComponent(e).update(this.gamepadObject)),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren(e=>e.name===t,!1)[0]}_getImmediateChildByName(e,t){return e.getChildren(e=>e.name==t,!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh||!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;let r=i?.5*t+.5:t;rr._f.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),rr.P.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new rq.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=rr._f.FromEulerAngles(0,Math.PI,0)}}class pP extends pR{constructor(e,t,i){super(e,pI[i],t,i),this.profileId=pP.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new rq.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=rr._f.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}pP.ProfileId="generic-trigger";let pI={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 pM extends pR{constructor(e,t,i,r,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=r,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach(e=>{this._touchDots[e].dispose()})}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){let e=sH.IsPluginForExtensionAvailable(".glb");return e||ru.Y.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach(i=>{let r=t.visualResponses[i];if("transform"===r.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{let s=t.type===pA.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===pA.TOUCHPAD_TYPE&&!this._touchDots[i]){let t=ha(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new lC(i+"mat",this.scene),t.material.diffuseColor=rs.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 rq.Kj(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i<e.length;i++){let r=e[i];r.isPickable=!1,r.parent||(t=r)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||this.rootMesh.rotate(rO.RD.Y,Math.PI,rO.T.WORLD)}_updateModel(e){this.disableAnimation||this.getComponentIds().forEach(e=>{let t=this.getComponent(e);if(!t.hasChanges)return;let i=this._buttonMeshMapping[e],r=this.layout.components[e];Object.keys(r.visualResponses).forEach(e=>{let s=r.visualResponses[e],n=t.value;if("xAxis"===s.componentProperty?n=t.axes.x:"yAxis"===s.componentProperty&&(n=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==s.componentProperty);else{let r=i.states[e].valueMesh;r&&(r.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}})})}}let pD=[];class pO{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){let t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){let r=[];i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&r.push("oculus-touch-v2");let s=r.indexOf("windows-mixed-reality");if(-1!==s&&r.splice(s,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),!this.UseOnlineRepository)return this._LoadProfilesFromAvailableControllers(r,e,t);{let i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,r,e,t).catch(()=>s.call(this,r,e,t))}}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=rZ.w1.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e.toString())),this._ProfilesList}static ClearControllerCache(){pD.forEach(e=>{e.meshes.forEach(e=>{e.dispose(!1,!0)})}),pD.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(t=>{for(let i=0;i<e.length;++i)if(e[i]&&t[e[i]])return e[i];throw Error(`neither controller ${e[0]} nor all fallbacks were found in the repository,`)}).then(e=>(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=rZ.w1.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then(e=>JSON.parse(e))),this._ProfileLoadingPromises[e])).then(e=>new pM(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:pD))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;r<e.length;++r){if(!e[r])continue;let s=this.FindFallbackWithProfileId(e[r]);for(let e=0;e<s.length;++e){let r=this._AvailableControllers[s[e]];if(r)return Promise.resolve(r(t,i))}}throw Error("no controller requested was found in the available controllers list")}}pO._AvailableControllers={},pO._Fallbacks={},pO._ProfileLoadingPromises={},pO.BaseRepositoryUrl="https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist",pO.PrioritizeOnlineRepository=!0,pO.UseOnlineRepository=!0,pO.DisableControllerCache=!0,pO.RegisterController(pP.ProfileId,(e,t)=>new pP(t,e.gamepad,e.handedness)),pO.DefaultFallbacks();let pN=0;class pF{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new rr.P,this._disposed=!1,this.onDisposeObservable=new ri.y$,this.onMeshLoadedObservable=new ri.y$,this.onMotionControllerInitObservable=new ri.y$,this._uniqueId=`controller-${pN++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new r$.x(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new rr._f,this.inputSource.gripSpace&&(this.grip=new r$.x(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new rr._f),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&pO.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())})},()=>{rZ.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){let i=t&&this.grip?this.grip:this.pointer;rr.P.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){let r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){let e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z);let t=r.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){let r=e.getPose(this.inputSource.gripSpace,t);if(r){let e=r.transform.position,t=r.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 pL{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new ri.y$,this.onControllerRemovedObservable=new ri.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&&(pO.BaseRepositoryUrl=this._options.customControllersRepositoryURL),pO.UseOnlineRepository=!this._options.disableOnlineControllerRepository,pO.UseOnlineRepository)try{pO.UpdateProfilesList().catch(()=>{pO.UseOnlineRepository=!1})}catch(e){pO.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){let i=this.controllers.map(e=>e.inputSource);for(let t of e)if(-1===i.indexOf(t)){let e=new pF(this.xrSessionManager.scene,t,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)}let r=[],s=[];this.controllers.forEach(e=>{-1===t.indexOf(e.inputSource)?r.push(e):s.push(e)}),this.controllers=r,s.forEach(e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()})}dispose(){this.controllers.forEach(e=>{e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),pO.ClearControllerCache()}}class pw extends sV{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;let{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 sD(new rr.P,new rr.P),disabledByNearInteraction:!1,id:pw._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 rr.P,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new rs.Wo(.9,.9,.9),this.laserPointerDefaultColor=new rs.Wo(.7,.7,.7),this.selectionMeshDefaultColor=new rs.Wo(.8,.8,.8),this.selectionMeshPickedColor=new rs.Wo(.3,.3,1),this._identityMatrix=rr.y3.Identity(),this._screenCoordinatesRef=rr.P.Zero(),this._viewportRef=new s6.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){let 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 sD(new rr.P,new rr.P),disabledByNearInteraction:!1,id:pw._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){let t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null}_getPointerSelectionDisabledByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].disabledByNearInteraction;return!0}_setPointerSelectionDisabledByPointerId(e,t){let i=Object.keys(this._controllers);for(let r=0;r<i.length;++r)if(this._controllers[i[r]].id===e){this._controllers[i[r]].disabledByNearInteraction=t;return}}_onXRFrame(e){Object.keys(this._controllers).forEach(e=>{let t;let i=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||i.disabledByNearInteraction){i.selectionMesh.isVisible=!1,i.laserPointer.isVisible=!1,i.pick=null;return}if(i.laserPointer.isVisible=this.displayLaserPointer,i.xrController)t=i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay);else{if(!i.webXRCamera)return;t=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay)}if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&t){let e=this._xrSessionManager.scene,r=this._options.xrInput.xrCamera;!r||(r.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),rr.P.ProjectToRef(t,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,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));let s=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);r&&r.hit?s&&s.hit?r.distance<s.distance?i.pick=r:i.pick=s:i.pick=r:i.pick=s,i.pick&&i.xrController&&(i.pick.aimTransform=i.xrController.pointer,i.pick.gripTransform=i.xrController.grip||null);let n=i.pick;if(n&&n.pickedPoint&&n.hit){this._updatePointerDistance(i.laserPointer,n.distance),i.selectionMesh.position.copyFrom(n.pickedPoint),i.selectionMesh.scaling.x=Math.sqrt(n.distance),i.selectionMesh.scaling.y=Math.sqrt(n.distance),i.selectionMesh.scaling.z=Math.sqrt(n.distance);let e=this._convertNormalToDirectionOfRay(n.getNormal(!0),i.tmpRay);if(i.selectionMesh.position.copyFrom(n.pickedPoint),e){let t=rr.P.Cross(rO.RD.Y,e),r=rr.P.Cross(e,t);rr.P.RotationFromAxisToRef(r,e,t,i.selectionMesh.rotation),i.selectionMesh.position.addInPlace(e.scale(.001))}i.selectionMesh.isVisible=this.displaySelectionMesh,i.meshUnderPointer=n.pickedMesh}else i.selectionMesh.isVisible=!1,this._updatePointerDistance(i.laserPointer,1),i.meshUnderPointer=null})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||he.DefaultUtilityLayer.utilityLayerScene}_attachGazeMode(e){let t=this._controllers[e&&e.uniqueId||"camera"],i=this._options.timeToSelect||3e3,r=this._options.useUtilityLayer?this._utilityLayerScene:this._scene,s=new sI.p,n=lG("selection",{diameter:.0525,thickness:.015,tessellation:20},r);n.isVisible=!1,n.isPickable=!1,n.parent=t.selectionMesh;let a=0,o=!1,l={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit){if(this._pickingMoved(s,t.pick))o&&!this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),o=!1,a=0;else if(a>i/10&&(n.isVisible=!0),(a+=this._scene.getEngine().getDeltaTime())>=i)this._scene.simulatePointerDown(t.pick,l),o=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{let e=1-a/i;n.scaling.set(e,e,e)}}else o=!1,a=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}}),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&o&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()})}_attachScreenRayMode(e){let t=this._controllers[e.uniqueId],i=!1,r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),t.pick&&(!this._options.disablePointerUpOnTouchOut||!i)&&(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)})})}_attachTrackedPointerRayMode(e){let t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);let 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){let r=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(r=>{if(r.changes.pressed){let s=r.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?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{let 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)},r=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:r,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",r)}}_convertNormalToDirectionOfRay(e,t){if(e){let i=Math.acos(rr.P.Dot(e,t.direction));i<Math.PI/2&&e.scaleInPlace(-1)}return e}_detachController(e){let t=this._controllers[e];if(t){if(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=>{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),!t.finalPointerUpTriggered&&t.pointerDownTriggered){let e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame(()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new sI.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){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){rZ.w1.Warn("controller already detached.")}})}}_generateNewMeshPair(e){let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||he.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():lV("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;let r=new lC("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;let s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():lG("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;let n=new lC("targetMat",t);return n.specularColor=rs.Wo.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,s.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||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));let r=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance,s=this._tmpVectorForPickCompare.length();return s>r}_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}}pw._IdCounter=200,pw.Name=sB.POINTER_SELECTION,pw.Version=1,sU.AddWebXRFeature(pw.Name,(e,t)=>()=>new pw(e,t),pw.Version,!0);var pB=i(1813);pB.P.prototype._projectOnTrianglesToRef=function(e,t,i,r,s,n){let a=rr.jp.Vector3[0],o=rr.jp.Vector3[1],l=Infinity;for(let n=this.indexStart;n<this.indexStart+this.indexCount-(3-r);n+=r){let r=i[n],h=i[n+1],u=i[n+2];if(s&&4294967295===u){n+=2;continue}let c=t[r],d=t[h],p=t[u];if(!c||!d||!p)continue;let _=rr.P.ProjectOnTriangleToRef(e,c,d,p,o);_<l&&(a.copyFrom(o),l=_)}return n.copyFrom(a),l},pB.P.prototype._projectOnUnIndexedTrianglesToRef=function(e,t,i,r){let s=rr.jp.Vector3[0],n=rr.jp.Vector3[1],a=Infinity;for(let i=this.verticesStart;i<this.verticesStart+this.verticesCount;i+=3){let r=t[i],o=t[i+1],l=t[i+2],h=rr.P.ProjectOnTriangleToRef(e,r,o,l,n);h<a&&(s.copyFrom(n),a=h)}return r.copyFrom(s),a},pB.P.prototype.projectToRef=function(e,t,i,r){let s=this.getMaterial();if(!s)return -1;let n=3,a=!1;switch(s.fillMode){case 3:case 5:case 6:case 8:return -1;case 7:n=1,a=!0}return 4===s.fillMode?-1:!i.length&&this._mesh._unIndexed?this._projectOnUnIndexedTrianglesToRef(e,t,i,r):this._projectOnTrianglesToRef(e,t,i,n,a,r)},(eR=iS||(iS={}))[eR.DEHYDRATED=0]="DEHYDRATED",eR[eR.HOVER=1]="HOVER",eR[eR.TOUCH=2]="TOUCH",(eP=iE||(iE={}))[eP.DISABLED=0]="DISABLED",eP[eP.CENTERED_ON_CONTROLLER=1]="CENTERED_ON_CONTROLLER",eP[eP.CENTERED_IN_FRONT=2]="CENTERED_IN_FRONT";class pU extends sV{constructor(e,t){super(e),this._options=t,this._tmpRay=new sD(new rr.P,new rr.P),this._attachController=e=>{if(this._controllers[e.uniqueId])return;let{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r,currentAnimationState:iS.DEHYDRATED,grabRay:new sD(new rr.P,new rr.P),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:pU._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 rs.Wo(.8,.8,.8),this.selectionMeshPickedColor=new rs.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=iE.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){let t=Object.keys(this._controllers);for(let i=0;i<t.length;++i)if(this._controllers[t[i]].id===e)return this._controllers[t[i]].xrController||null;return null}setFarInteractionFeature(e){this._farInteractionFeature=e}_nearPickPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearPickable}_nearGrabPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&e.isNearGrabbable}_nearInteractionPredicate(e){return e.isEnabled()&&e.isVisible&&e.isPickable&&(e.isNearPickable||e.isNearGrabbable)}_controllerAvailablePredicate(e,t){let i=e;for(;i;){if(i.reservedDataStore&&i.reservedDataStore.nearInteraction&&i.reservedDataStore.nearInteraction.excludedControllerId===t)return!1;i=i.parent}return!0}_handleTransitionAnimation(e,t){var i;if(e.currentAnimationState!==t&&this._options.nearInteractionControllerMode===iE.CENTERED_IN_FRONT&&(null===(i=e.xrController)||void 0===i||!i.inputSource.hand)){if(t>e.currentAnimationState)switch(e.currentAnimationState){case iS.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===iS.HOVER)break;case iS.HOVER:e.touchCollisionMeshFunction(!0),iS.TOUCH}else switch(e.currentAnimationState){case iS.TOUCH:if(e.touchCollisionMeshFunction(!1),t===iS.HOVER)break;case iS.HOVER:e.hydrateCollisionMeshFunction(!1),iS.DEHYDRATED}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var r;let s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(rr.jp.Vector3[0]),s.grabRay.direction.copyFrom(rr.jp.Vector3[0]),this._options.nearInteractionControllerMode!==iE.CENTERED_IN_FRONT||(null===(r=s.xrController)||void 0===r?void 0:r.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;let r=this._controllers[t],s=null===(i=r.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!r.xrController||!s&&(!this._options.nearInteractionControllerMode||!r.xrController.inputSource.gamepad)){r.pick=null;return}if(r.hoverInteraction=!1,r.nearInteraction=!1,!r.xrController)return;if(s){let i=s.get("index-finger-tip");if(i){let r=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(r&&r.transform){let e=this._scene.useRightHandedSystem?1:-1;rr.jp.Vector3[0].set(r.transform.position.x,r.transform.position.y,r.transform.position.z*e),rr.jp.Quaternion[0].set(r.transform.orientation.x,r.transform.orientation.y,r.transform.orientation.z*e,r.transform.orientation.w*e),this._processTouchPoint(t,rr.jp.Vector3[0],rr.jp.Quaternion[0])}}}else if(r.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==iE.DISABLED){let e=r.xrController.pointer;r.xrController.grip&&this._options.nearInteractionControllerMode===iE.CENTERED_ON_CONTROLLER&&(e=r.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}let n=(e,t)=>t&&t.hit?e&&e.hit?t.distance<e.distance?t:e:t:e,a=e=>{let t=new sI.p,i=!1,r=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),r&&!i&&(t=e),t};if(!r.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,this._hoverRadius,this._utilityLayerScene,e=>this._nearInteractionPredicate(e)));let i=this._pickWithSphere(r,this._hoverRadius,this._scene,e=>this._nearInteractionPredicate(e)),o=n(i,t);if(o&&o.hit&&(e=a(o)).hit&&(r.hoverInteraction=!0),r.hoverInteraction){let t=null,i=s?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,i,this._utilityLayerScene,e=>this._nearPickPredicate(e)));let o=this._pickWithSphere(r,i,this._scene,e=>this._nearPickPredicate(e)),l=n(o,t),h=a(l);h.hit&&(e=h,r.nearInteraction=!0)}r.stalePick=r.pick,r.pick=e,r.pick&&r.pick.pickedPoint&&r.pick.hit?(r.meshUnderPointer=r.pick.pickedMesh,r.pickedPointVisualCue.position.copyFrom(r.pick.pickedPoint),r.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!0)):(r.meshUnderPointer=null,r.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!1))}let o=iS.DEHYDRATED;r.grabInteraction||r.nearInteraction?o=iS.TOUCH:r.hoverInteraction&&(o=iS.HOVER),this._handleTransitionAnimation(r,o)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||he.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||he.DefaultUtilityLayer.utilityLayerScene:this._scene,t=ha("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=rr._f.Identity();let i=new lC("targetMat",e);return i.specularColor=rs.Wo.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){let 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))});let r=r=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),r&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!r||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){let i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(e=>{if(e.changes.pressed){let t=e.changes.pressed.current;r(t)}}):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(e=>{if(e.changes.pressed){let t=e.changes.pressed.current;r(t)}}))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{let 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))},r=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:r,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",r)}}_detachController(e){let 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=>{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{let e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new sI.p,e)}),delete this._controllers[e],this._attachedController===e)){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||he.DefaultUtilityLayer.utilityLayerScene:this._scene,t=ha("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:nY.ParseFromSnippetAsync("8RUNKL#3",e).then(e=>{t.material=e});let i=new rW;i.setEasingMode(rG.EASINGMODE_EASEINOUT);let r=new rr.P(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),s=this._controllerPickRadius*(4/3),n=new rr.P(s,s,s),a=this._controllerPickRadius*(7/6),o=new rr.P(a,a,a),l=.8*this._controllerPickRadius,h=new rr.P(l,l,l),u=1.5*this._controllerPickRadius,c=new rr.P(u,u,u),d=[{frame:0,value:r},{frame:10,value:c},{frame:18,value:n}],p=[{frame:0,value:n},{frame:10,value:h},{frame:18,value:r}],_=[{frame:0,value:rr.P.ZeroReadOnly},{frame:12,value:o},{frame:15,value:r}],f=[{frame:0,value:r},{frame:10,value:rr.P.ZeroReadOnly},{frame:15,value:rr.P.ZeroReadOnly}],m=new rE("touch","scaling",60,rE.ANIMATIONTYPE_VECTOR3,rE.ANIMATIONLOOPMODE_CONSTANT),g=new rE("release","scaling",60,rE.ANIMATIONTYPE_VECTOR3,rE.ANIMATIONLOOPMODE_CONSTANT),v=new rE("hydrate","scaling",60,rE.ANIMATIONTYPE_VECTOR3,rE.ANIMATIONLOOPMODE_CONSTANT),T=new rE("dehydrate","scaling",60,rE.ANIMATIONTYPE_VECTOR3,rE.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),T.setEasingFunction(i),m.setKeys(d),g.setKeys(p),v.setKeys(_),T.setKeys(f),{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{let r=i?m:g;e.beginDirectAnimation(t,[r],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{let r=i?v:T;i&&(t.isVisible=!0),e.beginDirectAnimation(t,[r],0,15,!1,1,()=>{i||(t.isVisible=!1)})}}}_pickWithSphere(e,t,i,r){let s=new sI.p;if(s.distance=Infinity,e.touchCollisionMesh&&e.xrController){let n=e.touchCollisionMesh.position,a=l6.K.CreateFromCenterAndRadius(n,t);for(let t=0;t<i.meshes.length;t++){let n=i.meshes[t];if(!r(n)||!this._controllerAvailablePredicate(n,e.xrController.uniqueId))continue;let o=pU.PickMeshWithSphere(n,a);o&&o.hit&&o.distance<s.distance&&(s.hit=o.hit,s.pickedMesh=n,s.pickedPoint=o.pickedPoint,s.aimTransform=e.xrController.pointer,s.gripTransform=e.xrController.grip||null,s.originMesh=e.touchCollisionMesh,s.distance=o.distance)}}return s}static PickMeshWithSphere(e,t,i=!1){let r,s,n;let a=e.subMeshes,o=new sI.p,l=e.getBoundingInfo();if(!e._generatePointsArray()||!e.subMeshes||!l||!i&&!l6.K.Intersects(l.boundingSphere,t))return o;let h=rr.jp.Vector3[0],u=rr.jp.Vector3[1],c=Infinity,d=rr.jp.Vector3[2],p=rr.jp.Matrix[0];p.copyFrom(e.getWorldMatrix()),p.invert(),rr.P.TransformCoordinatesToRef(t.center,p,d);for(let i=0;i<a.length;i++){let o=a[i];o.projectToRef(d,e._positions,e.getIndices(),u),rr.P.TransformCoordinatesToRef(u,e.getWorldMatrix(),u),r=rr.P.Distance(u,t.center),n=rr.P.Distance(u,e.getAbsolutePosition()),-1!==(s=rr.P.Distance(t.center,e.getAbsolutePosition()))&&-1!==n&&n>s&&(r=0,u.copyFrom(t.center)),-1!==r&&r<c&&(c=r,h.copyFrom(u))}return c<t.radius&&(o.hit=!0,o.distance=c,o.pickedMesh=e,o.pickedPoint=h.clone()),o}}pU._IdCounter=200,pU.Name=sB.NEAR_INTERACTION,pU.Version=1,sU.AddWebXRFeature(pU.Name,(e,t)=>()=>new pU(e,t),pU.Version,!0);class pV{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class pk{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new ri.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 rZ.w1.Warn("WebXR can only be served over HTTPS"),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;";let e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor",r="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",s=".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("+r+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';let n=document.createElement("style");n.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(n);let a=document.createElement("button");a.className="babylonVRicon",a.title=`${e} - ${i}`,this._buttons.push(new pV(a,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",a.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}let 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;let i=this._buttons.map(t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode));e.onStateChangedObservable.add(e=>{e==tD.NOT_IN_XR&&this._updateButtons(null)});let r=await Promise.all(i);r.forEach((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):rZ.w1.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){let r=new pk(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(this._helper.state==tD.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==tD.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(r){this._updateButtons(null);let t=this._buttons[e].element,i=t.title;t.title="Error entering XR session : "+i,t.classList.add("xr-error"),this.options.onError&&this.options.onError(r)}}dispose(){let 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 pG(e){var t;let i=0,r=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};let s=e.contextObservable.add(t=>{let n=Date.now();i=n-r;let a={startTime:r,currentTime:n,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(a),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(a)),i>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(a))},e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}(eI=iC||(iC={}))[eI.INIT=0]="INIT",eI[eI.STARTED=1]="STARTED",eI[eI.ENDED=2]="ENDED";class pz extends sV{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){let 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 rs.HE(1,1,1,1),this._tmpRay=new sD(new rr.P,new rr.P),this._tmpVector=new rr.P,this._tmpQuaternion=new rr._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 ri.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}};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let i=()=>{if(e.motionController){let i=e.motionController.getComponentOfType(pA.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(pA.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){let 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;let r=this._options.timeToTeleport||3e3;pG({timeout:r,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,rr._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);let 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;let e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);rr._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===sy.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;let i=this._options.timeToTeleport||3e3;pG({timeout:i,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else i.type===sy.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 rs.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){let t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];let t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){let 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<this._snapToPositions.length;++i)if(this._snapToPositions[i].equals(e)){t=i;break}}return -1!==t&&(this._snapToPositions.splice(t,1),!0)}setSelectionFeature(e){this._selectionFeature=e}_onXRFrame(e){let t=this._xrSessionManager.currentFrame,i=this._xrSessionManager.scene;if(!this.attach||!t)return;let r=this._options.teleportationTargetMesh;if(this._currentTeleportationControllerId){if(!r)return;r.rotationQuaternion=r.rotationQuaternion||new rr._f;let e=this._controllers[this._currentTeleportationControllerId];if(e&&e.teleportationState.forward){rr._f.RotationYawPitchRollToRef(e.teleportationState.currentRotation+e.teleportationState.baseRotation,0,0,r.rotationQuaternion);let t=!1;if(e.xrController.getWorldPointerRayToRef(this._tmpRay),this.straightRayEnabled){let r=i.pickWithRay(this._tmpRay,e=>{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;let t=this._floorMeshes.indexOf(e);return -1!==t&&this._floorMeshes[t].absolutePosition.y<this._options.xrInput.xrCamera.globalPosition.y});if(r&&r.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(r.pickedMesh)){e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(r);return}r&&r.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(r),this._setTargetMeshVisibility(!0),this._showParabolicPath(r))}if(this.parabolicRayEnabled&&!t){let r=e.xrController.pointer.rotationQuaternion.toEulerAngles().x,s=this.parabolicCheckRadius*(1+(Math.PI/2-Math.abs(r)));this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(2*s),this._tmpVector),this._tmpVector.y=this._tmpRay.origin.y,this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(s)),this._tmpVector.subtractToRef(this._tmpRay.origin,this._tmpRay.direction),this._tmpRay.direction.normalize();let n=i.pickWithRay(this._tmpRay,e=>!!this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e)||-1!==this._floorMeshes.indexOf(e));if(n&&n.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(n.pickedMesh)){e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(n);return}n&&n.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(n),this._setTargetMeshVisibility(!0),this._showParabolicPath(n))}this._setTargetMeshVisibility(t)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||he.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=lY("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{let i=new lb("teleportationPlaneDynamicTexture",512,e,!0);i.hasAlpha=!0;let r=i.getContext();r.beginPath(),r.arc(256,256,200,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),i.update();let s=new lC("teleportationPlaneMaterial",e);s.diffuseTexture=i,t.material=s}let i=lG("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){let t=new rE("animationInnerCircle","position.y",30,rE.ANIMATIONTYPE_FLOAT,rE.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),t.setKeys(r);let s=new rH;s.setEasingMode(rG.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}let r=lV("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate(rO.RD.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{let t=new lC("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new rs.Wo(.3,.3,1):t.diffuseColor=new rs.Wo(.3,.3,1),t.alpha=.9,i.material=t,r.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){let t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){let s=t*t;this._snapToPositions.forEach(t=>{let n=rr.P.DistanceSquared(t,e);n<=s&&n<r&&(r=n,i=t)})}return i}_setTargetMeshPosition(e){let t=e.pickedPoint;if(!this._options.teleportationTargetMesh||!t)return;let i=this._findClosestSnapPointWithRadius(t);this._snappedToPoint=!!i,this.snapPointsOnly&&!this._snappedToPoint&&this._teleportationRingMaterial?this._teleportationRingMaterial.diffuseColor.set(1,.3,.3):this.snapPointsOnly&&this._snappedToPoint&&this._teleportationRingMaterial&&this._teleportationRingMaterial.diffuseColor.set(.3,.3,1),this._options.teleportationTargetMesh.position.copyFrom(i||t),this._options.teleportationTargetMesh.position.y+=.01,this.onTargetMeshPositionUpdatedObservable.notifyObservers(e)}_setTargetMeshVisibility(e,t){this._options.teleportationTargetMesh&&(this._options.teleportationTargetMesh.isVisible!==e||t)&&(this._options.teleportationTargetMesh.isVisible=e,this._options.teleportationTargetMesh.getChildren(void 0,!1).forEach(t=>{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;let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||he.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=rk.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,n=Array(26).fill(s||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=hC("teleportation path line",{points:r.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){let t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint)){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){let 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,rr._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)}}}}pz.Name=sB.TELEPORTATION,pz.Version=1,sU.AddWebXRFeature(pz.Name,(e,t)=>()=>new pz(e,t),pz.Version,!0);class pW{constructor(){}static CreateAsync(e,t={}){let i=new pW;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){let r=Object.assign({renderTarget:i.renderTarget},t.uiOptions||{});t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new pk(e,r)}return py.CreateAsync(e).then(e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new pL(e.sessionManager,e.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){let e=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(pw.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(pz.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(pU.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=>(ru.Y.Error("Error initializing XR"),ru.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 pH(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}rI.x.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;e<this.lights.length;e++)this.lights[e].dispose();0===this.lights.length&&new oa("default light",rr.P.Up(),this)},rI.x.prototype.createDefaultCamera=function(e=!1,t=!1,i=!1){if(t&&this.activeCamera&&(this.activeCamera.dispose(),this.activeCamera=null),!this.activeCamera){let t;let r=this.getWorldExtends(e=>e.isVisible&&e.isEnabled()),s=r.max.subtract(r.min),n=r.min.add(s.scale(.5)),a=1.5*s.length();if(isFinite(a)||(a=1,n.copyFromFloats(0,0,0)),e){let e=new aA("default camera",-(Math.PI/2),Math.PI/2,a,n,this);e.lowerRadiusLimit=.01*a,e.wheelPrecision=100/a,t=e}else{let e=new ab("default camera",new rr.P(n.x,n.y,-a),this);e.setTarget(n),t=e}t.minZ=.01*a,t.maxZ=1e3*a,t.speed=.2*a,this.activeCamera=t,i&&t.attachControl()}},rI.x.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},rI.x.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,r=0,s=!0){if(!e)return ru.Y.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);let n=hs("hdrSkyBox",{size:i},this);if(t){let t=new pu("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=sv.SKYBOX_MODE),t.microSurface=1-r,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{let t=new lC("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=sv.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},rI.x.prototype.createDefaultEnvironment=function(e){return d_?new d_(e,this):null},rI.x.prototype.createDefaultVRExperience=function(e={}){return new l$(this,e)},rI.x.prototype.createDefaultXRExperienceAsync=function(e={}){return pW.CreateAsync(this,e).then(e=>e)};class pX extends sv{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new ri.y$),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):ru.Y.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if((null==e?void 0:e.name)==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}if(!this.video.muted){ru.Y.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,this.video.play().catch(e=>{this._processError(e)});return}}this._processError(e)})}constructor(e,t,i,r=!1,s=!1,n=sv.TRILINEAR_SAMPLINGMODE,a={},o,l=5){var h,u;super(null,i,!r,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||rZ.w1.IsExponentOfTwo(this.video.videoWidth)&&rZ.w1.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=sv.WRAP_ADDRESSMODE,this.wrapV=sv.WRAP_ADDRESSMODE):(this.wrapU=sv.CLAMP_ADDRESSMODE,this.wrapV=sv.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{let 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||this.video.readyState<this.video.HAVE_CURRENT_DATA||this._displayingPosterTexture)return;let e=this.getScene().getFrameId();this._frameId!==e&&(this._frameId=e,this._getEngine().updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:this.video,this._invertY))},this._settings=Object.assign({autoPlay:!0,loop:!0,autoUpdateTexture:!0},a),this._onError=o,this._generateMipMaps=r,this._initialSamplingMode=n,this.autoUpdateTexture=this._settings.autoUpdateTexture,this._currentSrc=t,this.name=e||this._getName(t),this.video=this._getVideo(t),this._externalTexture=null!==(u=null===(h=this._engine)||void 0===h?void 0:h.createExternalTexture(this.video))&&void 0!==u?u:null,!this._settings.independentVideoSource&&(this._settings.poster&&(this.video.poster=this._settings.poster),void 0!==this._settings.autoPlay&&(this.video.autoplay=this._settings.autoPlay),void 0!==this._settings.loop&&(this.video.loop=this._settings.loop),void 0!==this._settings.muted&&(this.video.muted=this._settings.muted),this.video.setAttribute("playsinline",""),this.video.addEventListener("paused",this._updateInternalTexture),this.video.addEventListener("seeked",this._updateInternalTexture),this.video.addEventListener("emptied",this._reset),this._settings.autoPlay&&this._handlePlay()),this._createInternalTextureOnEvent=this._settings.poster&&!this._settings.autoPlay?"play":"canplay",this.video.addEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._format=l;let c=this.video.readyState>=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&c?c&&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 rZ.w1.SetCorsBehavior(e.currentSrc,e),e;let t=document.createElement("video");return"string"==typeof e?(rZ.w1.SetCorsBehavior(e,t),t.src=e):(rZ.w1.SetCorsBehavior(e[0],t),e.forEach(e=>{let i=document.createElement("source");i.src=e,t.appendChild(i)})),this.onDisposeObservable.addOnce(()=>{pH(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 pX(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,r=!0){let 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=>{let i=()=>{let n=new pX("video",s,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce(()=>{s.remove()}),n.onDisposeObservable.addOnce(()=>{pH(s)}),t(n),s.removeEventListener("playing",i)};s.addEventListener("playing",i),s.play()})}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){let s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,s,t,r);return n.onDisposeObservable.addOnce(()=>{s.getTracks().forEach(e=>{e.stop()})}),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,s=!0){this.CreateFromWebCamAsync(e,i,r,s).then(function(e){t&&t(e)}).catch(function(e){ru.Y.Error(e.name)})}}class pY extends df{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){let r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new pX((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,sv.TRILINEAR_SAMPLINGMODE,r);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()},sy.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)}}pY.MODE_MONOSCOPIC=df.MODE_MONOSCOPIC,pY.MODE_TOPBOTTOM=df.MODE_TOPBOTTOM,pY.MODE_SIDEBYSIDE=df.MODE_SIDEBYSIDE;let pj=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) -#include<helperFunctions> -#endif -#ifdef DIFFUSE -varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; -#endif -#ifdef OPACITY -varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; -#endif -#ifdef EMISSIVE -varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; -#endif -#ifdef VERTEXALPHA -varying vec4 vColor; -#endif -uniform vec4 glowColor;uniform float glowIntensity; -#include<clipPlaneFragmentDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include<clipPlaneFragment> -vec4 finalColor=glowColor; -#ifdef DIFFUSE -vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); -#ifdef DIFFUSE_ISLINEAR -albedoTexture=toGammaSpace(albedoTexture); -#endif -#ifdef GLOW -finalColor.a*=albedoTexture.a; -#endif -#ifdef HIGHLIGHT -finalColor.a=albedoTexture.a; -#endif -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); -#ifdef OPACITYRGB -finalColor.a*=getLuminance(opacityMap.rgb); -#else -finalColor.a*=opacityMap.a; -#endif -finalColor.a*=opacityIntensity; -#endif -#ifdef VERTEXALPHA -finalColor.a*=vColor.a; -#endif -#ifdef ALPHATEST -if (finalColor.a<ALPHATESTVALUE) -discard; -#endif -#ifdef EMISSIVE -vec4 emissive=texture2D(emissiveSampler,vUVEmissive); -#ifdef EMISSIVE_ISLINEAR -emissive=toGammaSpace(emissive); -#endif -gl_FragColor=emissive*finalColor*glowIntensity; -#else -gl_FragColor=finalColor*glowIntensity; -#endif -#ifdef HIGHLIGHT -gl_FragColor.a=glowColor.a; -#endif -}`;no.v.ShadersStore.glowMapGenerationPixelShader=pj;let pq=`attribute vec3 position; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<clipPlaneVertexDeclaration> -#include<instancesDeclaration> -uniform mat4 viewProjection;varying vec4 vPosition; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef DIFFUSE -varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; -#endif -#ifdef OPACITY -varying vec2 vUVOpacity;uniform mat4 opacityMatrix; -#endif -#ifdef EMISSIVE -varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; -#endif -#ifdef VERTEXALPHA -attribute vec4 color;varying vec4 vColor; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef CUBEMAP -vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); -#else -vPosition=viewProjection*worldPos;gl_Position=vPosition; -#endif -#ifdef DIFFUSE -#ifdef DIFFUSEUV1 -vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef DIFFUSEUV2 -vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef OPACITY -#ifdef OPACITYUV1 -vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef OPACITYUV2 -vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef EMISSIVE -#ifdef EMISSIVEUV1 -vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef EMISSIVEUV2 -vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef VERTEXALPHA -vColor=color; -#endif -#include<clipPlaneVertex> -}`;no.v.ShadersStore.glowMapGenerationVertexShader=pq;class pK{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i<e.length;++i){let r=e[i];t?this._materialForRendering[r.uniqueId]=[r,t]:delete this._materialForRendering[r.uniqueId]}else t?this._materialForRendering[e.uniqueId]=[e,t]:delete this._materialForRendering[e.uniqueId]}getEffectIntensity(e){var t;return null!==(t=this._effectIntensity[e.uniqueId])&&void 0!==t?t:1}setEffectIntensity(e,t){this._effectIntensity[e.uniqueId]=t}constructor(e,t){this._vertexBuffers={},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._shouldRender=!0,this._postProcesses=[],this._textures=[],this._emissiveTextureAndColor={texture:null,color:new rs.HE},this._effectIntensity={},this.neutralColor=new rs.HE,this.isEnabled=!0,this.disableBoundingBoxesFromEffectLayer=!1,this.onDisposeObservable=new ri.y$,this.onBeforeRenderMainTextureObservable=new ri.y$,this.onBeforeComposeObservable=new ri.y$,this.onBeforeRenderMeshToEffect=new ri.y$,this.onAfterRenderMeshToEffect=new ri.y$,this.onAfterComposeObservable=new ri.y$,this.onSizeChangedObservable=new ri.y$,this._materialForRendering={},this.name=e,this._scene=t||rp.l.LastCreatedScene,pK._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.effectLayers.push(this),this._mergeDrawWrapper=[],this._generateIndexBuffer(),this._generateVertexBuffer()}_numInternalDraws(){return 1}_init(e){this._effectLayerOptions=Object.assign({mainTextureRatio:.5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,generateStencilBuffer:!1},e),this._setMainTextureSize(),this._createMainTexture(),this._createTextureAndPostProcesses()}_generateIndexBuffer(){let e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._engine.createIndexBuffer(e)}_generateVertexBuffer(){let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1);let t=new rQ.o(this._engine,e,rQ.o.PositionKind,!1,!1,2);this._vertexBuffers[rQ.o.PositionKind]=t}_setMainTextureSize(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?r7.D.GetExponentOfTwo(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?r7.D.GetExponentOfTwo(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)}_createMainTexture(){for(let e in this._mainTexture=new nV("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,!1,!0,this._effectLayerOptions.mainTextureType,!1,sv.TRILINEAR_SAMPLINGMODE,!0,this._effectLayerOptions.generateStencilBuffer),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=sv.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=sv.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(sv.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._materialForRendering){let[t,i]=this._materialForRendering[e];this._mainTexture.setMaterialForRendering(t,i)}if(this._mainTexture.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){let i=e.subMeshes[t],r=i.getMaterial(),s=i.getRenderingMesh();if(!r)continue;let n=s._getInstancesRenderList(i._id,!!i.getReplacementMesh()),a=n.hardwareInstancedRendering[i._id]||s.hasThinInstances;if(this._setEmissiveTextureAndColor(s,i,r),!this._isReady(i,a,this._emissiveTextureAndColor.texture))return!1}return!0},this._mainTexture.customRenderFunction=(e,t,i,r)=>{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);let n=this._scene.getEngine();if(r.length){for(n.setColorWrite(!1),s=0;s<r.length;s++)this._renderSubMesh(r.data[s]);n.setColorWrite(!0)}for(s=0;s<e.length;s++)this._renderSubMesh(e.data[s]);for(s=0;s<t.length;s++)this._renderSubMesh(t.data[s]);let a=n.getAlphaMode();for(s=0;s<i.length;s++)this._renderSubMesh(i.data[s],!0);n.setAlphaMode(a)},this._mainTexture.onClearObservable.add(e=>{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){let 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 r;let s=this._scene.getEngine(),n=e.getMesh(),a=null===(r=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[s.currentRenderPassId];if(a)return a.isReadyForSubMesh(n,e,t);let o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);let l=[],h=[rQ.o.PositionKind],u=!1,c=!1;if(o){let e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(l.push("#define DIFFUSE"),n.isVerticesDataPresent(rQ.o.UV2Kind)&&1===t.coordinatesIndex?(l.push("#define DIFFUSEUV2"),c=!0):n.isVerticesDataPresent(rQ.o.UVKind)&&(l.push("#define DIFFUSEUV1"),u=!0),e&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));let r=o.opacityTexture;r&&(l.push("#define OPACITY"),n.isVerticesDataPresent(rQ.o.UV2Kind)&&1===r.coordinatesIndex?(l.push("#define OPACITYUV2"),c=!0):n.isVerticesDataPresent(rQ.o.UVKind)&&(l.push("#define OPACITYUV1"),u=!0))}i&&(l.push("#define EMISSIVE"),n.isVerticesDataPresent(rQ.o.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),c=!0):n.isVerticesDataPresent(rQ.o.UVKind)&&(l.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent(rQ.o.ColorKind)&&n.hasVertexAlpha&&o.transparencyMode!==sX.F.MATERIAL_OPAQUE&&(h.push(rQ.o.ColorKind),l.push("#define VERTEXALPHA")),u&&(h.push(rQ.o.UVKind),l.push("#define UV1")),c&&(h.push(rQ.o.UV2Kind),l.push("#define UV2"));let d=new nn;if(n.useBones&&n.computeBonesUsingShaders){h.push(rQ.o.MatricesIndicesKind),h.push(rQ.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(h.push(rQ.o.MatricesIndicesExtraKind),h.push(rQ.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);let e=n.skeleton;e&&e.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),n.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,n)}else l.push("#define NUM_BONE_INFLUENCERS 0");let p=n.morphTargetManager,_=0;p&&p.numInfluencers>0&&(l.push("#define MORPHTARGETS"),_=p.numInfluencers,l.push("#define NUM_MORPH_INFLUENCERS "+_),p.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),s3.G.PrepareAttributesForMorphTargetsInfluencers(h,n,_)),t&&(l.push("#define INSTANCES"),s3.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),(0,lx.lK)(o,this._scene,l),this._addCustomEffectDefines(l);let f=e._getDrawWrapper(void 0,!0),m=f.defines,g=l.join("\n");if(m!==g){let e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];(0,lx.qx)(e),f.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:_}),g)}return f.effect.isReady()}render(){for(let e=0;e<this._postProcesses.length;e++)if(!this._postProcesses[e].isReady())return;let e=this._scene.getEngine(),t=this._numInternalDraws(),i=!0;for(let e=0;e<t;++e){let t=this._mergeDrawWrapper[e];t||(t=this._mergeDrawWrapper[e]=new nc.q(this._engine)).setEffect(this._createMergeEffect()),i=i&&t.effect.isReady()}if(!i)return;this.onBeforeComposeObservable.notifyObservers(this);let r=e.getAlphaMode();for(let i=0;i<t;++i){let t=this._mergeDrawWrapper[i];e.enableEffect(t),e.setState(!1),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t.effect),e.setAlphaMode(this._effectLayerOptions.alphaBlendingMode),this._internalRender(t.effect,i)}e.setAlphaMode(r),this.onAfterComposeObservable.notifyObservers(this);let s=this._mainTexture.getSize();this._setMainTextureSize(),(s.width!==this._mainTextureDesiredSize.width||s.height!==this._mainTextureDesiredSize.height)&&0!==this._mainTextureDesiredSize.width&&0!==this._mainTextureDesiredSize.height&&(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses())}hasMesh(e){return -1===this.renderingGroupId||e.renderingGroupId===this.renderingGroupId}shouldRender(){return this.isEnabled&&this._shouldRender}_shouldRenderMesh(e){return!0}_canRenderMesh(e,t){return!t.needAlphaBlendingForMesh(e)}_shouldRenderEmissiveTextureForMesh(){return!0}_renderSubMesh(e,t=!1){var i,r;if(!this.shouldRender())return;let s=e.getMaterial(),n=e.getMesh(),a=e.getReplacementMesh(),o=e.getRenderingMesh(),l=e.getEffectiveMesh(),h=this._scene,u=h.getEngine();if(l._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!s||!this._canRenderMesh(o,s))return;let c=null!==(i=o.overrideMaterialSideOrientation)&&void 0!==i?i:s.sideOrientation,d=l._getWorldMatrixDeterminant();d<0&&(c=c===sX.F.ClockWiseSideOrientation?sX.F.CounterClockWiseSideOrientation:sX.F.ClockWiseSideOrientation);let p=c===sX.F.ClockWiseSideOrientation;u.setState(s.backFaceCulling,s.zOffset,void 0,p,s.cullBackFaces,void 0,s.zOffsetUnits);let _=o._getInstancesRenderList(e._id,!!a);if(_.mustReturn||!this._shouldRenderMesh(o))return;let f=_.hardwareInstancedRendering[e._id]||o.hasThinInstances;if(this._setEmissiveTextureAndColor(o,e,s),this.onBeforeRenderMeshToEffect.notifyObservers(n),this._useMeshMaterial(o))o.render(e,t,a||void 0);else if(this._isReady(e,f,this._emissiveTextureAndColor.texture)){let i=null===(r=l._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[u.currentRenderPassId],n=e._getDrawWrapper();if(!n&&i&&(n=i._getDrawWrapper()),!n)return;let a=n.effect;if(u.enableEffect(n),f||o._bind(e,a,s.fillMode),i?i.bindForSubMesh(l.getWorldMatrix(),l,e):(a.setMatrix("viewProjection",h.getTransformMatrix()),a.setMatrix("world",l.getWorldMatrix()),a.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!i){let e=s.needAlphaTesting(),i=s.getAlphaTestTexture(),r=i&&i.hasAlpha&&(s.useAlphaFromDiffuseTexture||s._useAlphaFromAlbedoTexture);if(i&&(e||r)){a.setTexture("diffuseSampler",i);let e=i.getTextureMatrix();e&&a.setMatrix("diffuseMatrix",e)}let n=s.opacityTexture;if(n){a.setTexture("opacitySampler",n),a.setFloat("opacityIntensity",n.level);let e=n.getTextureMatrix();e&&a.setMatrix("opacityMatrix",e)}if(this._emissiveTextureAndColor.texture&&(a.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),a.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),o.useBones&&o.computeBonesUsingShaders&&o.skeleton){let e=o.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(o);if(!t)return;a.setTexture("boneSampler",t),a.setFloat("boneTextureWidth",4*(e.bones.length+1))}else a.setMatrices("mBones",e.getTransformMatrices(o))}s3.G.BindMorphTargetParameters(o,a),o.morphTargetManager&&o.morphTargetManager.isUsingTextureForTargets&&o.morphTargetManager._bind(a),t&&u.setAlphaMode(s.alphaMode),a.setFloat("glowIntensity",this.getEffectIntensity(o)),(0,lx.an)(a,s,h)}o._processRendering(l,e,a,s.fillMode,_,f,(e,t)=>a.setMatrix("world",t))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(n)}_useMeshMaterial(e){return!1}_rebuild(){let e=this._vertexBuffers[rQ.o.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e<this._postProcesses.length;e++)this._postProcesses[e]&&this._postProcesses[e].dispose();this._postProcesses=[];for(let e=0;e<this._textures.length;e++)this._textures[e]&&this._textures[e].dispose();this._textures=[]}dispose(){let e=this._vertexBuffers[rQ.o.PositionKind];for(let t of(e&&(e.dispose(),this._vertexBuffers[rQ.o.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._mergeDrawWrapper))t.dispose();this._mergeDrawWrapper=[],this._disposeTextureAndPostProcesses();let t=this._scene.effectLayers.indexOf(this,0);t>-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){let r=rZ.w1.Instantiate(e.customType);return r.Parse(e,t,i)}}pK._SceneComponentInitialization=e=>{throw(0,st.S)("EffectLayerSceneComponent")},(0,r0.gn)([(0,rg.qC)()],pK.prototype,"name",void 0),(0,r0.gn)([(0,rg.XX)()],pK.prototype,"neutralColor",void 0),(0,r0.gn)([(0,rg.qC)()],pK.prototype,"isEnabled",void 0),(0,r0.gn)([(0,rg.VE)()],pK.prototype,"camera",null),(0,r0.gn)([(0,rg.qC)()],pK.prototype,"renderingGroupId",null),(0,r0.gn)([(0,rg.qC)()],pK.prototype,"disableBoundingBoxesFromEffectLayer",void 0),re.p.AddParser(ss.l.NAME_EFFECTLAYER,(e,t,i,r)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let s=0;s<e.effectLayers.length;s++){let n=pK.Parse(e.effectLayers[s],t,r);i.effectLayers.push(n)}}}),re.p.prototype.removeEffectLayer=function(e){let t=this.effectLayers.indexOf(e);return -1!==t&&this.effectLayers.splice(t,1),t},re.p.prototype.addEffectLayer=function(e){this.effectLayers.push(e)};class p${constructor(e){if(this.name=ss.l.NAME_EFFECTLAYER,this._renderEffects=!1,this._needStencil=!1,this._previousStencilState=!1,this.scene=e||rp.l.LastCreatedScene,!this.scene)return;this._engine=this.scene.getEngine(),this.scene.effectLayers=[]}register(){this.scene._isReadyForMeshStage.registerStep(ss.l.STEP_ISREADYFORMESH_EFFECTLAYER,this,this._isReadyForMesh),this.scene._cameraDrawRenderTargetStage.registerStep(ss.l.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER,this,this._renderMainTexture),this.scene._beforeCameraDrawStage.registerStep(ss.l.STEP_BEFORECAMERADRAW_EFFECTLAYER,this,this._setStencil),this.scene._afterRenderingGroupDrawStage.registerStep(ss.l.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW,this,this._drawRenderingGroup),this.scene._afterCameraDrawStage.registerStep(ss.l.STEP_AFTERCAMERADRAW_EFFECTLAYER,this,this._setStencilBack),this.scene._afterCameraDrawStage.registerStep(ss.l.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW,this,this._drawCamera)}rebuild(){let e=this.scene.effectLayers;for(let t of e)t._rebuild()}serialize(e){e.effectLayers=[];let t=this.scene.effectLayers;for(let i of t)i.serialize&&e.effectLayers.push(i.serialize())}addFromContainer(e){e.effectLayers&&e.effectLayers.forEach(e=>{this.scene.addEffectLayer(e)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(e=>{this.scene.removeEffectLayer(e),t&&e.dispose()})}dispose(){let e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){let i=this._engine.currentRenderPassId,r=this.scene.effectLayers;for(let s of r){if(!s.hasMesh(e))continue;let r=s._mainTexture;for(let n of(this._engine.currentRenderPassId=r.renderPassId,e.subMeshes))if(!s.isReady(n,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1,i=this.scene.effectLayers;if(i&&i.length>0){for(let r of(this._previousStencilState=this._engine.getStencilBuffer(),i))if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===r4.V.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==r4.V.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();let e=r._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);let t=this.scene.effectLayers;for(let i=0;i<t.length;i++){let r=t[i];r.renderingGroupId===e&&r.shouldRender()&&r.render()}this._engine.setDepthBuffer(!0)}}_drawCamera(){this._renderEffects&&this._draw(-1)}_drawRenderingGroup(e){!this.scene._isInIntermediateRendering()&&this._renderEffects&&this._draw(e)}}pK._SceneComponentInitialization=e=>{let t=e._getComponent(ss.l.NAME_EFFECTLAYER);t||(t=new p$(e),e._addComponent(t))};let pQ=`varying vec2 vUV;uniform sampler2D textureSampler; -#ifdef EMISSIVE -uniform sampler2D textureSampler2; -#endif -uniform float offset; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV); -#ifdef EMISSIVE -baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; -#else -baseColor.a=abs(offset-baseColor.a); -#ifdef STROKE -float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; -#endif -#endif -#if LDR -baseColor=clamp(baseColor,0.,1.0); -#endif -gl_FragColor=baseColor; -#define CUSTOM_FRAGMENT_MAIN_END -}`;no.v.ShadersStore.glowMapMergePixelShader=pQ;let pZ=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.glowMapMergeVertexShader=pZ,re.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()===pJ.EffectName)return this.effectLayers[i];return null};class pJ extends pK{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;let 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 rs.HE(0,0,0,1),this._options=Object.assign({mainTextureRatio:pJ.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType,generateStencilBuffer:this._options.generateStencilBuffer})}getEffectName(){return pJ.EffectName}_createMergeEffect(){let e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[rQ.o.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?r7.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?r7.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new nV("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=sv.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=sv.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(sv.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;let r=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new nV("GlowLayerBlurRTT2",{width:r,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=sv.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=sv.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(sv.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];let n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new dr("GlowLayerHBP1",new rr.FM(1,0),n,{width:e,height:t},null,sv.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 dr("GlowLayerVBP1",new rr.FM(0,1),n,{width:e,height:t},null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new dr("GlowLayerHBP2",new rr.FM(1,0),n,{width:r,height:s},null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new dr("GlowLayerVBP2",new rr.FM(0,1),n,{width:r,height:s},null,sv.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(()=>{let e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);let 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){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;let 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);let t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(sX.F.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var r;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){let e=null!==(r=i.emissiveIntensity)&&void 0!==r?r:1;s*=e,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){let 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){let 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(){let e;let t=rg.p4.Serialize(this);if(t.customType="BABYLON.GlowLayer",t.includedMeshes=[],this._includedOnlyMeshes.length)for(e=0;e<this._includedOnlyMeshes.length;e++){let i=this._scene.getMeshByUniqueId(this._includedOnlyMeshes[e]);i&&t.includedMeshes.push(i.id)}if(t.excludedMeshes=[],this._excludedMeshes.length)for(e=0;e<this._excludedMeshes.length;e++){let i=this._scene.getMeshByUniqueId(this._excludedMeshes[e]);i&&t.excludedMeshes.push(i.id)}return t}static Parse(e,t,i){let r;let s=rg.p4.Parse(()=>new pJ(e.name,t,e.options),e,t,i);for(r=0;r<e.excludedMeshes.length;r++){let i=t.getMeshById(e.excludedMeshes[r]);i&&s.addExcludedMesh(i)}for(r=0;r<e.includedMeshes.length;r++){let i=t.getMeshById(e.includedMeshes[r]);i&&s.addIncludedOnlyMesh(i)}return s}}pJ.EffectName="GlowLayer",pJ.DefaultBlurKernelSize=32,pJ.DefaultTextureRatio=.5,(0,r0.gn)([(0,rg.qC)()],pJ.prototype,"blurKernelSize",null),(0,r0.gn)([(0,rg.qC)()],pJ.prototype,"intensity",null),(0,r0.gn)([(0,rg.qC)("options")],pJ.prototype,"_options",void 0),(0,rn.H)("BABYLON.GlowLayer",pJ);let p0=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color) -{return dot(color,vec3(0.2126,0.7152,0.0722));} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++) -{vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;} -gl_FragColor=baseColor;}`;no.v.ShadersStore.glowBlurPostProcessPixelShader=p0,re.p.prototype.getHighlightLayerByName=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()===p2.EffectName)return this.effectLayers[i];return null};class p1 extends np{constructor(e,t,i,r,s,n=sv.BILINEAR_SAMPLINGMODE,a,o){super(e,"glowBlurPostProcess",["screenSize","direction","blurWidth"],null,r,s,n,a,o),this.direction=t,this.kernel=i,this.onApplyObservable.add(e=>{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)})}}class p2 extends pK{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 ri.y$,this.onAfterBlurObservable=new ri.y$,this._instanceGlowingMeshStencilReference=p2.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=p2.NeutralColor,this._engine.isStencilEnable||ru.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 p2.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[rQ.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?r7.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?r7.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new nV("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=sv.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=sv.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(sv.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new az("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new p1("HighlightLayerHBP",new rr.FM(1,0),this._options.blurHorizontalSize,1,null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new p1("HighlightLayerVBP",new rr.FM(0,1),this._options.blurVerticalSize,1,null,sv.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 dr("HighlightLayerHBP",new rr.FM(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,sv.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 dr("HighlightLayerVBP",new rr.FM(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);let 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){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null,n=this._meshes[r.uniqueId];return n&&n.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);let 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(sX.F.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(sX.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){let r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];if(!t){let 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;let 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;let r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(e=>{this.isEnabled&&this._defaultStencilReference(e)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;let t=this._meshes[e.uniqueId];for(let i in t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1,this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(let e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){let t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(p2.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(let e in this._meshes){let 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(let e in this._excludedMeshes){let 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(){let e=rg.p4.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(let t in this._meshes){let 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(let t in this._excludedMeshes){let i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){let r;let s=rg.p4.Parse(()=>new p2(e.name,t,e.options),e,t,i);for(r=0;r<e.excludedMeshes.length;r++){let i=t.getMeshById(e.excludedMeshes[r]);i&&s.addExcludedMesh(i)}for(r=0;r<e.meshes.length;r++){let i=e.meshes[r],n=t.getMeshById(i.meshId);n&&s.addMesh(n,rs.Wo.FromArray(i.color),i.glowEmissiveOnly)}return s}}p2.EffectName="HighlightLayer",p2.NeutralColor=new rs.HE(0,0,0,0),p2.GlowingMeshStencilReference=2,p2.NormalMeshStencilReference=1,(0,r0.gn)([(0,rg.qC)()],p2.prototype,"innerGlow",void 0),(0,r0.gn)([(0,rg.qC)()],p2.prototype,"outerGlow",void 0),(0,r0.gn)([(0,rg.qC)()],p2.prototype,"blurHorizontalSize",null),(0,r0.gn)([(0,rg.qC)()],p2.prototype,"blurVerticalSize",null),(0,r0.gn)([(0,rg.qC)("options")],p2.prototype,"_options",void 0),(0,rn.H)("BABYLON.HighlightLayer",p2);let p3=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; -#include<helperFunctions> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV); -#ifdef LINEAR -baseColor.rgb=toGammaSpace(baseColor.rgb); -#endif -#ifdef ALPHATEST -if (baseColor.a<0.4) -discard; -#endif -gl_FragColor=baseColor*color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;no.v.ShadersStore.layerPixelShader=p3;let p4=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.layerVertexShader=p4;class p5{static AddFlare(e,t,i,r,s){return new p5(e,t,i,r,s)}constructor(e,t,i,r,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new rs.Wo(1,1,1),this.texture=r?new sv(r,s.getScene(),!0):null,this._system=s;let n=s.scene.getEngine();this._drawWrapper=new nc.q(n),this._drawWrapper.effect=n.createEffect("lensFlare",[rQ.o.PositionKind],["color","viewportMatrix"],["textureSampler"],""),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();let e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}let p6=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;no.v.ShadersStore.lensFlarePixelShader=p6;let p8=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.lensFlareVertexShader=p8;class p7{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||rp.l.LastCreatedScene,p7._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&(e.layerMask&i.activeCamera.layerMask)!=0;let r=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[rQ.o.PositionKind]=new rQ.o(r,s,rQ.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){let 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=rr.P.Project(t,rr.y3.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=rr.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);let i=this._scene.useRightHandedSystem,r=t.z>0&&!i||t.z<0&&i;return!!r&&(this._positionX>e.x&&this._positionX<e.x+e.width&&this._positionY>e.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;let e=this.getEmitterPosition(),t=e.subtract(this._scene.activeCamera.globalPosition),i=t.length();t.normalize();let r=new sD(this._scene.activeCamera.globalPosition,t),s=this._scene.pickWithRay(r,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>i}render(){let e,t;if(!this._scene.activeCamera)return!1;let i=this._scene.getEngine(),r=this._scene.activeCamera.viewport,s=r.toGlobal(i.getRenderWidth(!0),i.getRenderHeight(!0));if(!this.computeEffectivePosition(s)||!this._isVisible())return!1;let n=(e=this._positionX<this.borderLimit+s.x?this.borderLimit+s.x-this._positionX:this._positionX>s.x+s.width-this.borderLimit?this._positionX-s.x-s.width+this.borderLimit:0)>(t=this._positionY<this.borderLimit+s.y?this.borderLimit+s.y-this._positionY:this._positionY>s.y+s.height-this.borderLimit?this._positionY-s.y-s.height+this.borderLimit:0)?e:t;(n-=this.viewportBorder)>this.borderLimit&&(n=this.borderLimit);let a=1-rm.R.Clamp(n/this.borderLimit,0,1);if(a<0)return!1;a>1&&(a=1),this.viewportBorder>0&&(s.x+=this.viewportBorder,s.y+=this.viewportBorder,s.width-=2*this.viewportBorder,s.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);let o=s.x+s.width/2,l=s.y+s.height/2,h=o-this._positionX,u=l-this._positionY;i.setState(!1),i.setDepthBuffer(!1);for(let e=0;e<this.lensFlares.length;e++){let t=this.lensFlares[e];if(!t._drawWrapper.effect.isReady()||t.texture&&!t.texture.isReady())continue;i.enableEffect(t._drawWrapper),i.bindBuffers(this._vertexBuffers,this._indexBuffer,t._drawWrapper.effect),i.setAlphaMode(t.alphaMode);let r=o-h*t.position,n=l-u*t.position,c=t.size,d=t.size*i.getAspectRatio(this._scene.activeCamera,!0),p=2*(r/(s.width+2*s.x))-1,_=1-2*(n/(s.height+2*s.y)),f=rr.y3.FromValues(c/2,0,0,0,0,d/2,0,0,0,0,1,0,p,_,0,1);t._drawWrapper.effect.setMatrix("viewportMatrix",f),t._drawWrapper.effect.setTexture("textureSampler",t.texture),t._drawWrapper.effect.setFloat4("color",t.color.r*a,t.color.g*a,t.color.b*a,1),i.drawElementsType(sX.F.TriangleFillMode,0,6)}return i.setDepthBuffer(!0),i.setAlphaMode(0),!0}rebuild(){var e;for(let t in this._createIndexBuffer(),this._vertexBuffers)null===(e=this._vertexBuffers[t])||void 0===e||e._rebuild()}dispose(){let e=this._vertexBuffers[rQ.o.PositionKind];for(e&&(e.dispose(),this._vertexBuffers[rQ.o.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);this.lensFlares.length;)this.lensFlares[0].dispose();let t=this._scene.lensFlareSystems.indexOf(this);this._scene.lensFlareSystems.splice(t,1)}static Parse(e,t,i){let r=t.getLastEntryById(e.emitterId),s=e.name||"lensFlareSystem#"+e.emitterId,n=new p7(s,r,t);n.id=e.id||s,n.borderLimit=e.borderLimit;for(let t=0;t<e.flares.length;t++){let r=e.flares[t];p5.AddFlare(r.size,r.position,rs.Wo.FromArray(r.color),r.textureName?i+r.textureName:"",n)}return n}serialize(){let e={};e.id=this.id,e.name=this.name,e.emitterId=this.getEmitter().id,e.borderLimit=this.borderLimit,e.flares=[];for(let t=0;t<this.lensFlares.length;t++){let i=this.lensFlares[t];e.flares.push({size:i.size,position:i.position,color:i.color.asArray(),textureName:rZ.w1.GetFilename(i.texture?i.texture.name:"")})}return e}}p7._SceneComponentInitialization=e=>{throw(0,st.S)("LensFlareSystemSceneComponent")},re.p.AddParser(ss.l.NAME_LENSFLARESYSTEM,(e,t,i,r)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let s=0,n=e.lensFlareSystems.length;s<n;s++){let n=e.lensFlareSystems[s],a=p7.Parse(n,t,r);i.lensFlareSystems.push(a)}}}),re.p.prototype.getLensFlareSystemByName=function(e){for(let t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].name===e)return this.lensFlareSystems[t];return null},re.p.prototype.getLensFlareSystemById=function(e){for(let t=0;t<this.lensFlareSystems.length;t++)if(this.lensFlareSystems[t].id===e)return this.lensFlareSystems[t];return null},re.p.prototype.getLensFlareSystemByID=function(e){return this.getLensFlareSystemById(e)},re.p.prototype.removeLensFlareSystem=function(e){let t=this.lensFlareSystems.indexOf(e);return -1!==t&&this.lensFlareSystems.splice(t,1),t},re.p.prototype.addLensFlareSystem=function(e){this.lensFlareSystems.push(e)};class p9{constructor(e){this.name=ss.l.NAME_LENSFLARESYSTEM,this.scene=e,e.lensFlareSystems=[]}register(){this.scene._afterCameraDrawStage.registerStep(ss.l.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM,this,this._draw)}rebuild(){for(let e=0;e<this.scene.lensFlareSystems.length;e++)this.scene.lensFlareSystems[e].rebuild()}addFromContainer(e){e.lensFlareSystems&&e.lensFlareSystems.forEach(e=>{this.scene.addLensFlareSystem(e)})}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach(e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()})}serialize(e){e.lensFlareSystems=[];let t=this.scene.lensFlareSystems;for(let i of t)e.lensFlareSystems.push(i.serialize())}dispose(){let e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){let t=this.scene.lensFlareSystems;for(let i of(rZ.w1.StartPerformanceCounter("Lens flares",t.length>0),t))(e.layerMask&i.layerMask)!=0&&i.render();rZ.w1.EndPerformanceCounter("Lens flares",t.length>0)}}}p7._SceneComponentInitialization=e=>{let t=e._getComponent(ss.l.NAME_LENSFLARESYSTEM);t||(t=new p9(e),e._addComponent(t))};let _e=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} -float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); -vec2 P2=floor(0.5*mod(_P,4.0)); -return 4.0*bayerDither2(P1)+bayerDither2(P2);} -float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); -vec2 P2=floor(0.5 *mod(_P,4.0)); -vec2 P4=floor(0.25*mod(_P,8.0)); -return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} -`;no.v.IncludesShadersStore.bayerDitherFunctions=_e;let _t=`#if SM_FLOAT==0 -#include<packingFunctions> -#endif -#if SM_SOFTTRANSPARENTSHADOW==1 -#include<bayerDitherFunctions> -uniform float softTransparentShadowSM; -#endif -varying float vDepthMetricSM; -#if SM_USEDISTANCE==1 -uniform vec3 lightDataSM;varying vec3 vPositionWSM; -#endif -uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -varying float zSM; -#endif -`;no.v.IncludesShadersStore.shadowMapFragmentExtraDeclaration=_t;let _i=`float depthSM=vDepthMetricSM; -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -#if SM_USEDISTANCE==1 -depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -#ifdef USE_REVERSE_DEPTHBUFFER -depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#endif -#ifdef USE_REVERSE_DEPTHBUFFER -gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); -#else -gl_FragDepth=clamp(depthSM,0.0,1.0); -#endif -#elif SM_USEDISTANCE==1 -depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#if SM_ESM==1 -depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); -#endif -#if SM_FLOAT==1 -gl_FragColor=vec4(depthSM,1.0,1.0,1.0); -#else -gl_FragColor=pack(depthSM); -#endif -return;`;no.v.IncludesShadersStore.shadowMapFragment=_i;let _r=`#include<shadowMapFragmentExtraDeclaration> -#ifdef ALPHATEXTURE -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include<clipPlaneFragmentDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include<clipPlaneFragment> -#ifdef ALPHATEXTURE -float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; -#ifdef ALPHATESTVALUE -if (alphaFromAlphaTexture<ALPHATESTVALUE) -discard; -#endif -#endif -#if SM_SOFTTRANSPARENTSHADOW==1 -#ifdef ALPHATEXTURE -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alphaFromAlphaTexture) discard; -#else -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard; -#endif -#endif -#include<shadowMapFragment> -}`;no.v.ShadersStore.shadowMapPixelShader=_r;let _s=`uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; -`;no.v.IncludesShadersStore.sceneVertexDeclaration=_s;let _n=`uniform mat4 world;uniform float visibility; -`;no.v.IncludesShadersStore.meshVertexDeclaration=_n;let _a=`#include<sceneVertexDeclaration> -#include<meshVertexDeclaration> -`;no.v.IncludesShadersStore.shadowMapVertexDeclaration=_a;let _o=`layout(std140,column_major) uniform; -#include<sceneUboDeclaration> -#include<meshUboDeclaration> -`;no.v.IncludesShadersStore.shadowMapUboDeclaration=_o;let _l=`#if SM_NORMALBIAS==1 -uniform vec3 lightDataSM; -#endif -uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; -#if SM_USEDISTANCE==1 -varying vec3 vPositionWSM; -#endif -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -varying float zSM; -#endif -`;no.v.IncludesShadersStore.shadowMapVertexExtraDeclaration=_l;let _h=`#if SM_NORMALBIAS==1 -#if SM_DIRECTIONINLIGHTDATA==1 -vec3 worldLightDirSM=normalize(-lightDataSM.xyz); -#else -vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); -#endif -float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; -#endif -`;no.v.IncludesShadersStore.shadowMapVertexNormalBias=_h;let _u=`#if SM_USEDISTANCE==1 -vPositionWSM=worldPos.xyz; -#endif -#if SM_DEPTHTEXTURE==1 -#ifdef IS_NDC_HALF_ZRANGE -#define BIASFACTOR 0.5 -#else -#define BIASFACTOR 1.0 -#endif -#ifdef USE_REVERSE_DEPTHBUFFER -gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; -#else -gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; -#endif -#endif -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -zSM=gl_Position.z;gl_Position.z=0.0; -#elif SM_USEDISTANCE==0 -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#endif -`;no.v.IncludesShadersStore.shadowMapVertexMetric=_u;let _c=`attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#ifdef INSTANCES -attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; -#endif -#include<helperFunctions> -#include<__decl__shadowMapVertex> -#ifdef ALPHATEXTURE -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#include<shadowMapVertexExtraDeclaration> -#include<clipPlaneVertexDeclaration> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef NORMAL -mat3 normWorldSM=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normWorldSM=transposeMat3(inverseMat3(normWorldSM)); -#endif -vec3 vNormalW=normalize(normWorldSM*normalUpdated); -#endif -#endif -#include<shadowMapVertexNormalBias> -gl_Position=viewProjection*worldPos; -#include<shadowMapVertexMetric> -#ifdef ALPHATEXTURE -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#include<clipPlaneVertex> -}`;no.v.ShadersStore.shadowMapVertexShader=_c;let _d=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) -for (int y=-OFFSET; y<=OFFSET; y++) -colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;no.v.ShadersStore.depthBoxBlurPixelShader=_d;let _p=`#if SM_SOFTTRANSPARENTSHADOW==1 -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; -#endif -`;no.v.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow=_p;class __{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===__.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}if(e===__.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}if(e===__.FILTER_PCF||e===__.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===__.FILTER_PCF||e===__.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===__.FILTER_POISSONSAMPLING}set usePoissonSampling(e){let t=this._validateFilter(__.FILTER_POISSONSAMPLING);(e||this.filter===__.FILTER_POISSONSAMPLING)&&(this.filter=e?t:__.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===__.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){let t=this._validateFilter(__.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===__.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:__.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===__.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){let t=this._validateFilter(__.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===__.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:__.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===__.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){let t=this._validateFilter(__.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===__.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:__.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===__.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){let t=this._validateFilter(__.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===__.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:__.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===__.FILTER_PCF}set usePercentageCloserFiltering(e){let t=this._validateFilter(__.FILTER_PCF);(e||this.filter===__.FILTER_PCF)&&(this.filter=e?t:__.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===__.FILTER_PCSS}set useContactHardeningShadow(e){let t=this._validateFilter(__.FILTER_PCSS);(e||this.filter===__.FILTER_PCSS)&&(this.filter=e?t:__.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return __.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(let t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;let i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(let t of e.getChildren())this.removeShadowCaster(t);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,r,s){this.onBeforeShadowMapRenderObservable=new ri.y$,this.onAfterShadowMapRenderObservable=new ri.y$,this.onBeforeShadowMapRenderMeshObservable=new ri.y$,this.onAfterShadowMapRenderMeshObservable=new ri.y$,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=__.FILTER_NONE,this._filteringQuality=__.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=rr.P.Zero(),this._viewMatrix=rr.y3.Zero(),this._projectionMatrix=rr.y3.Zero(),this._transformMatrix=rr.y3.Zero(),this._cachedPosition=new rr.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new rr.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=rr.y3.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=r?r:null,this._useRedTextureType=!!s;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),__._SceneComponentInitialization(this._scene);let 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(){let e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new nV(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new nV(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=sv.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=sv.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(sv.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;let 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===__.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===__.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){null===(t=e._debugPopGroup)||void 0===t||t.call(e,1);return}let r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))});let t=new rs.HE(0,0,0,0),i=new rs.HE(1,1,1,1);this._shadowMap.onClearObservable.add(e=>{this._filter===__.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let e=nD.$.MIN_RENDERINGGROUPS;e<nD.$.MAX_RENDERINGGROUPS;e++)this._shadowMap.setRenderingAutoClearDepthStencil(e,!1)}_initializeBlurRTTAndPostProcesses(){let e=this._scene.getEngine(),t=this._mapSize/this.blurScale;this.useKernelBlur&&1===this.blurScale||(this._shadowMap2=new nV(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=sv.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=sv.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(sv.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new dr(this._light.name+"KernelBlurX",new rr.FM(1,0),this.blurKernel,1,null,sv.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=t,this._kernelBlurXPostprocess.height=t,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new dr(this._light.name+"KernelBlurY",new rr.FM(0,1),this.blurKernel,1,null,sv.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 np(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,sv.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,r){let s;if(r.length)for(s=0;s<r.length;s++)this._renderSubMeshForShadowMap(r.data[s]);for(s=0;s<e.length;s++)this._renderSubMeshForShadowMap(e.data[s]);for(s=0;s<t.length;s++)this._renderSubMeshForShadowMap(t.data[s]);if(this._transparencyShadow)for(s=0;s<i.length;s++)this._renderSubMeshForShadowMap(i.data[s],!0);else for(s=0;s<i.length;s++)i.data[s].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}_bindCustomEffectForRenderSubMeshForShadowMap(e,t,i){t.setMatrix("viewProjection",this.getTransformMatrix())}_renderSubMeshForShadowMap(e,t=!1){var i,r;let s=e.getRenderingMesh(),n=e.getEffectiveMesh(),a=this._scene,o=a.getEngine(),l=e.getMaterial();if(n._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!l||0===e.verticesCount||e._renderId===a.getRenderId())return;let h=0>n._getWorldMatrixDeterminant(),u=null!==(i=s.overrideMaterialSideOrientation)&&void 0!==i?i:l.sideOrientation;h&&(u=0===u?1:0);let c=0===u;o.setState(l.backFaceCulling,void 0,void 0,c,l.cullBackFaces);let d=s._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;let p=o.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||s.hasThinInstances);if(!this.customAllowRendering||this.customAllowRendering(e)){if(this.isReady(e,p,t)){e._renderId=a.getRenderId();let i=l.shadowDepthWrapper,h=null!==(r=null==i?void 0:i.getEffect(e,this,o.currentRenderPassId))&&void 0!==r?r:e._getDrawWrapper(),u=nc.q.GetEffect(h);o.enableEffect(h),p||s._bind(e,u,l.fillMode),this.getTransformMatrix(),u.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===r3.LIGHTTYPEID_DIRECTIONALLIGHT?u.setVector3("lightDataSM",this._cachedDirection):u.setVector3("lightDataSM",this._cachedPosition);let c=this._getCamera();if(c&&u.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(c),this.getLight().getDepthMinZ(c)+this.getLight().getDepthMaxZ(c)),t&&this.enableSoftTransparentShadow&&u.setFloat("softTransparentShadowSM",n.visibility*l.alpha),i)e._setMainDrawWrapperOverride(h),i.standalone?i.baseMaterial.bindForSubMesh(n.getWorldMatrix(),s,e):l.bindForSubMesh(n.getWorldMatrix(),s,e),e._setMainDrawWrapperOverride(null);else{if(this._opacityTexture&&(u.setTexture("diffuseSampler",this._opacityTexture),u.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),s.useBones&&s.computeBonesUsingShaders&&s.skeleton){let e=s.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(s);if(!t)return;u.setTexture("boneSampler",t),u.setFloat("boneTextureWidth",4*(e.bones.length+1))}else u.setMatrices("mBones",e.getTransformMatrices(s))}s3.G.BindMorphTargetParameters(s,u),s.morphTargetManager&&s.morphTargetManager.isUsingTextureForTargets&&s.morphTargetManager._bind(u),(0,lx.an)(u,l,a)}this._useUBO||i||this._bindCustomEffectForRenderSubMeshForShadowMap(e,u,n),s3.G.BindSceneUniformBuffer(u,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();let _=n.getWorldMatrix();p&&(n.getMeshUniformBuffer().bindToEffect(u,"Mesh"),n.transferToEffect(_)),this.forceBackFacesOnly&&o.setState(!0,0,!1,!0,l.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(s),this.onBeforeShadowMapRenderObservable.notifyObservers(u),s._processRendering(n,e,u,l.fillMode,d,p,(e,t)=>{n===s||e?(n.getMeshUniformBuffer().bindToEffect(u,"Mesh"),n.transferToEffect(e?t:_)):(s.getMeshUniformBuffer().bindToEffect(u,"Mesh"),s.transferToEffect(t))}),this.forceBackFacesOnly&&o.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(u),this.onAfterShadowMapRenderMeshObservable.notifyObservers(s)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}}_applyFilterValues(){this._shadowMap&&(this.filter===__.FILTER_NONE||this.filter===__.FILTER_PCSS?this._shadowMap.updateSamplingMode(sv.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(sv.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){let i=Object.assign({useInstances:!1},t),r=this.getShadowMap();if(!r){e&&e(this);return}let s=r.renderList;if(!s){e&&e(this);return}let n=[];for(let e of s)n.push(...e.subMeshes);if(0===n.length){e&&e(this);return}let a=0,o=()=>{var t,r;if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[a],i.useInstances,null!==(r=null===(t=n[a].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(n[a].getMesh()))&&void 0!==r&&r);)if(++a>=n.length){e&&e(this);return}setTimeout(o,16)}};o()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));let s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(rQ.o.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===r3.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var r;let s=e.getMaterial(),n=null==s?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;let a=[];if(this._prepareShadowDefines(e,t,a,i),n){if(!n.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{let i=e._getDrawWrapper(void 0,!0),n=i.effect,o=i.defines,l=[rQ.o.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(rQ.o.NormalKind)&&(l.push(rQ.o.NormalKind),a.push("#define NORMAL"),h.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));let u=s.needAlphaTesting();if((u||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;let e=null!==(r=s.alphaCutOff)&&void 0!==r?r:__.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),u&&a.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(rQ.o.UVKind)&&(l.push(rQ.o.UVKind),a.push("#define UV1")),h.isVerticesDataPresent(rQ.o.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(l.push(rQ.o.UV2Kind),a.push("#define UV2"))}let c=new nn;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(rQ.o.MatricesIndicesKind),l.push(rQ.o.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(rQ.o.MatricesIndicesExtraKind),l.push(rQ.o.MatricesWeightsExtraKind));let e=h.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");let d=h.morphTargetManager,p=0;if(d&&d.numInfluencers>0&&(a.push("#define MORPHTARGETS"),p=d.numInfluencers,a.push("#define NUM_MORPH_INFLUENCERS "+p),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),s3.G.PrepareAttributesForMorphTargetsInfluencers(l,h,p)),(0,lx.lK)(s,this._scene,a),t&&(a.push("#define INSTANCES"),s3.G.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(let e of this.customShaderOptions.defines)-1===a.indexOf(e)&&a.push(e);let _=a.join("\n");if(o!==_){o=_;let e="shadowMap",t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],r=["diffuseSampler","boneSampler","morphTargets"];if((0,lx.qx)(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(let e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(let e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(let e of this.customShaderOptions.samplers)-1===r.indexOf(e)&&r.push(e)}let s=this._scene.getEngine();n=s.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:["Scene","Mesh"],samplers:r,defines:_,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p}},s),i.setEffect(n,o)}if(!n.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){let i=this._scene,r=this._light;i.shadowsEnabled&&r.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===__.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===__.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===__.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===__.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let n=this.getShadowMap();n&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===__.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n.getSize().width,1/n.getSize().width,this.frustumEdgeFalloff,e)):this._filter===__.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/n.getSize().width,this._contactHardeningLightSizeUVRatio*n.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/n.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e))}getTransformMatrix(){let 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),rr.P.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(rr.P.Dot(this._lightDirection,rr.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),rr.y3.LookAtLHToRef(t,t.add(this._lightDirection),rr.P.Up(),this._viewMatrix);let e=this.getShadowMap();if(e){let t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){let e=this._shadowMap;if(!e)return;let t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t)for(let e of(this._shadowMap.renderList||(this._shadowMap.renderList=[]),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(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){let e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){let[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;let 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 e=0;e<i.renderList.length;e++){let r=i.renderList[e];t.renderList.push(r.id)}return t}static Parse(e,t,i){let r=t.getLightById(e.lightId),s=void 0!==e.cameraId?t.getCameraById(e.cameraId):null,n=i?i(e.mapSize,r,s):new __(e.mapSize,r,void 0,s),a=n.getShadowMap();for(let i=0;i<e.renderList.length;i++){let r=t.getMeshesById(e.renderList[i]);r.forEach(function(e){a&&(a.renderList||(a.renderList=[]),a.renderList.push(e))})}return void 0!==e.id&&(n.id=e.id),n.forceBackFacesOnly=!!e.forceBackFacesOnly,void 0!==e.darkness&&n.setDarkness(e.darkness),e.transparencyShadow&&n.setTransparencyShadow(!0),void 0!==e.frustumEdgeFalloff&&(n.frustumEdgeFalloff=e.frustumEdgeFalloff),void 0!==e.bias&&(n.bias=e.bias),void 0!==e.normalBias&&(n.normalBias=e.normalBias),e.usePercentageCloserFiltering?n.usePercentageCloserFiltering=!0:e.useContactHardeningShadow?n.useContactHardeningShadow=!0:e.usePoissonSampling?n.usePoissonSampling=!0:e.useExponentialShadowMap?n.useExponentialShadowMap=!0:e.useBlurExponentialShadowMap?n.useBlurExponentialShadowMap=!0:e.useCloseExponentialShadowMap?n.useCloseExponentialShadowMap=!0:e.useBlurCloseExponentialShadowMap?n.useBlurCloseExponentialShadowMap=!0:e.useVarianceShadowMap?n.useExponentialShadowMap=!0:e.useBlurVarianceShadowMap&&(n.useBlurExponentialShadowMap=!0),void 0!==e.contactHardeningLightSizeUVRatio&&(n.contactHardeningLightSizeUVRatio=e.contactHardeningLightSizeUVRatio),void 0!==e.filteringQuality&&(n.filteringQuality=e.filteringQuality),e.depthScale&&(n.depthScale=e.depthScale),e.blurScale&&(n.blurScale=e.blurScale),e.blurBoxOffset&&(n.blurBoxOffset=e.blurBoxOffset),e.useKernelBlur&&(n.useKernelBlur=e.useKernelBlur),e.blurKernel&&(n.blurKernel=e.blurKernel),n}}__.CLASSNAME="ShadowGenerator",__.FILTER_NONE=0,__.FILTER_EXPONENTIALSHADOWMAP=1,__.FILTER_POISSONSAMPLING=2,__.FILTER_BLUREXPONENTIALSHADOWMAP=3,__.FILTER_CLOSEEXPONENTIALSHADOWMAP=4,__.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP=5,__.FILTER_PCF=6,__.FILTER_PCSS=7,__.QUALITY_HIGH=0,__.QUALITY_MEDIUM=1,__.QUALITY_LOW=2,__.DEFAULT_ALPHA_CUTOFF=.5,__._SceneComponentInitialization=e=>{throw(0,st.S)("ShadowGeneratorSceneComponent")};let _f=`#ifdef ALPHATEST -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include<clipPlaneFragmentDeclaration> -varying float vDepthMetric; -#ifdef PACKED -#include<packingFunctions> -#endif -#ifdef STORE_CAMERASPACE_Z -varying vec4 vViewPos; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include<clipPlaneFragment> -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -#ifdef STORE_CAMERASPACE_Z -#ifdef PACKED -gl_FragColor=pack(vViewPos.z); -#else -gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); -#endif -#else -#ifdef NONLINEARDEPTH -#ifdef PACKED -gl_FragColor=pack(gl_FragCoord.z); -#else -gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); -#endif -#else -#ifdef PACKED -gl_FragColor=pack(vDepthMetric); -#else -gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); -#endif -#endif -#endif -}`;no.v.ShadersStore.depthPixelShader=_f;let _m=`attribute vec3 position; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<clipPlaneVertexDeclaration> -#include<instancesDeclaration> -uniform mat4 viewProjection;uniform vec2 depthValues; -#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#ifdef STORE_CAMERASPACE_Z -uniform mat4 view;varying vec4 vViewPos; -#endif -varying float vDepthMetric; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#include<clipPlaneVertex> -gl_Position=viewProjection*worldPos; -#ifdef STORE_CAMERASPACE_Z -vViewPos=view*worldPos; -#else -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); -#else -vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); -#endif -#endif -#if defined(ALPHATEST) || defined(BASIC_RENDER) -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -} -`;no.v.ShadersStore.depthVertexShader=_m;class _g{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,s=sv.TRILINEAR_SAMPLINGMODE,n=!1,a){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new rs.HE(1,1,1,1):this.clearColor=new rs.HE(n?1e8:1,0,0,1),_g._SceneComponentInitialization(this._scene);let o=e.getEngine();this._camera=i,s===sv.NEAREST_SAMPLINGMODE||(1!==t||o._caps.textureFloatLinearFiltering||(s=sv.NEAREST_SAMPLINGMODE),2!==t||o._caps.textureHalfFloatLinearFiltering||(s=sv.NEAREST_SAMPLINGMODE));let l=this.isPacked||!o._features.supportExtendedTextureFormats?5:6;this._depthMap=new nV(null!=a?a:"DepthRenderer",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,l),this._depthMap.wrapU=sv.CLAMP_ADDRESSMODE,this._depthMap.wrapV=sv.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=o._debugPushGroup)||void 0===e||e.call(o,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var e;null===(e=o._debugPopGroup)||void 0===e||e.call(o,1)}),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){let i=e.subMeshes[t],r=i.getRenderingMesh(),s=r._getInstancesRenderList(i._id,!!i.getReplacementMesh()),n=o.getCaps().instancedArrays&&(null!==s.visibleInstances[i._id]&&void 0!==s.visibleInstances[i._id]||r.hasThinInstances);if(!this.isReady(i,n))return!1}return!0};let h=e=>{var t,i;let r=e.getRenderingMesh(),s=e.getEffectiveMesh(),n=this._scene,a=n.getEngine(),o=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!o||s.infiniteDistance||o.disableDepthWrite||0===e.verticesCount||e._renderId===n.getRenderId())return;let l=0>s._getWorldMatrixDeterminant(),h=null!==(t=r.overrideMaterialSideOrientation)&&void 0!==t?t:o.sideOrientation;l&&(h=0===h?1:0);let u=0===h;a.setState(o.backFaceCulling,0,!1,u,this.reverseCulling?!o.cullBackFaces:o.cullBackFaces);let c=r._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(c.mustReturn)return;let d=a.getCaps().instancedArrays&&(null!==c.visibleInstances[e._id]&&void 0!==c.visibleInstances[e._id]||r.hasThinInstances),p=this._camera||n.activeCamera;if(this.isReady(e,d)&&p){let t,l;e._renderId=n.getRenderId();let h=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[a.currentRenderPassId],u=e._getDrawWrapper();!u&&h&&(u=h._getDrawWrapper());let _=p.mode===r4.V.ORTHOGRAPHIC_CAMERA;if(!u)return;let f=u.effect;if(a.enableEffect(u),d||r._bind(e,f,o.fillMode),h?h.bindForSubMesh(s.getWorldMatrix(),s,e):(f.setMatrix("viewProjection",n.getTransformMatrix()),f.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&f.setMatrix("view",n.getViewMatrix())),_?(t=!a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1,l=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1):(t=a.useReverseDepthBuffer&&a.isNDCHalfZRange?p.minZ:a.isNDCHalfZRange?0:p.minZ,l=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:p.maxZ),f.setFloat2("depthValues",t,t+l),!h){if(o.needAlphaTesting()){let e=o.getAlphaTestTexture();e&&(f.setTexture("diffuseSampler",e),f.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){let e=r.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(r);if(!t)return;f.setTexture("boneSampler",t),f.setFloat("boneTextureWidth",4*(e.bones.length+1))}else f.setMatrices("mBones",e.getTransformMatrices(r))}(0,lx.an)(f,o,n),s3.G.BindMorphTargetParameters(r,f),r.morphTargetManager&&r.morphTargetManager.isUsingTextureForTargets&&r.morphTargetManager._bind(f)}r._processRendering(s,e,f,o.fillMode,c,d,(e,t)=>f.setMatrix("world",t))}};this._depthMap.customRenderFunction=(e,t,i,r)=>{let s;if(r.length)for(s=0;s<r.length;s++)h(r.data[s]);for(s=0;s<e.length;s++)h(e.data[s]);for(s=0;s<t.length;s++)h(t.data[s]);if(this.forceDepthWriteTransparentMeshes)for(s=0;s<i.length;s++)h(i.data[s]);else for(s=0;s<i.length;s++)i.data[s].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate=!1}}isReady(e,t){var i;let r=this._scene.getEngine(),s=e.getMesh(),n=s.getScene(),a=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[r.currentRenderPassId];if(a)return a.isReadyForSubMesh(s,e,t);let o=e.getMaterial();if(!o||o.disableDepthWrite)return!1;let l=[],h=[rQ.o.PositionKind];if(o&&o.needAlphaTesting()&&o.getAlphaTestTexture()&&(l.push("#define ALPHATEST"),s.isVerticesDataPresent(rQ.o.UVKind)&&(h.push(rQ.o.UVKind),l.push("#define UV1")),s.isVerticesDataPresent(rQ.o.UV2Kind)&&(h.push(rQ.o.UV2Kind),l.push("#define UV2"))),s.useBones&&s.computeBonesUsingShaders){h.push(rQ.o.MatricesIndicesKind),h.push(rQ.o.MatricesWeightsKind),s.numBoneInfluencers>4&&(h.push(rQ.o.MatricesIndicesExtraKind),h.push(rQ.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));let t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");let u=s.morphTargetManager,c=0;u&&u.numInfluencers>0&&(c=u.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+c),u.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),s3.G.PrepareAttributesForMorphTargetsInfluencers(h,s,c)),t&&(l.push("#define INSTANCES"),s3.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,lx.lK)(o,n,l);let d=e._getDrawWrapper(void 0,!0),p=d.defines,_=l.join("\n");if(p!==_){let e=["world","mBones","boneTextureWidth","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,lx.qx)(e),d.setEffect(r.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),_)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){let e=[];for(let t in this._scene._depthRenderer){let i=this._scene._depthRenderer[t];i===this&&e.push(t)}if(e.length>0)for(let t of(this._depthMap.dispose(),e))delete this._scene._depthRenderer[t]}}_g._SceneComponentInitialization=e=>{throw(0,st.S)("DepthRendererSceneComponent")};let _v=`varying vec2 vUV;uniform sampler2D textureSampler; -#if defined(INITIAL) -uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); -#ifdef DEPTH_REDUX -float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); -#else -float maxz=max(max(max(f1,f2),f3),f4); -#endif -glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(MAIN) -uniform vec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(ONEBEFORELAST) -uniform ivec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(LAST) -void main(void) -{glFragColor=vec4(0.);if (true) { -discard;}} -#endif -`;no.v.ShadersStore.minmaxReduxPixelShader=_v;class _T{constructor(e){this.onAfterReductionPerformed=new ri.y$,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new nM.O(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){var s,n,a,o;if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;let l=this._camera.getScene(),h=new np("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,l.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);h.autoClear=!1,h.forceFullscreenViewport=r;let u=this._sourceTexture.getRenderWidth(),c=this._sourceTexture.getRenderHeight();h.onApply=(s=u,n=c,e=>{e.setTexture("sourceTexture",this._sourceTexture),e.setFloat2("texSize",s,n)}),this._reductionSteps.push(h);let d=1;for(;u>1||c>1;){u=Math.max(Math.round(u/2),1),c=Math.max(Math.round(c/2),1);let e=new np("Reduction phase "+d,"minmaxRedux",["texSize"],null,{width:u,height:c},null,1,l.getEngine(),!1,"#define "+(1==u&&1==c?"LAST":1==u||1==c?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=r,e.onApply=(a=u,o=c,e=>{1==a||1==o?e.setInt2("texSize",a,o):e.setFloat2("texSize",a,o)}),this._reductionSteps.push(e),d++,1==u&&1==c){let t=(e,t,i)=>{let r=new Float32Array(4*e*t),s={min:0,max:0};return()=>{l.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,r,!1),s.min=r[0],s.max=r[1],this.onAfterReductionPerformed.notifyObservers(s)}};e.onAfterRenderObservable.add(t(u,c,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;let 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;e<this._reductionSteps.length;++e)this._reductionSteps[e].dispose();this._reductionSteps=null}this._postProcessManager&&e&&this._postProcessManager.dispose(),this._sourceTexture=null}}class _x extends _T{get depthRenderer(){return this._depthRenderer}constructor(e){super(e)}setDepthRenderer(e=null,t=2,i=!0){let r=this._camera.getScene();this._depthRenderer&&(delete r._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),null===e&&(r._depthRenderer||(r._depthRenderer={}),(e=this._depthRenderer=new _g(r,t,this._camera,!1,1)).enabled=!1,this._depthRendererId="minmax"+this._camera.id,r._depthRenderer[this._depthRendererId]=e),super.setSourceTexture(e.getDepthMap(),!0,t,i)}setSourceTexture(e,t,i=2,r=!0){super.setSourceTexture(e,t,i,r)}activate(){this._depthRenderer&&(this._depthRenderer.enabled=!0),super.activate()}deactivate(){super.deactivate(),this._depthRenderer&&(this._depthRenderer.enabled=!1)}dispose(e=!0){if(super.dispose(e),this._depthRenderer&&e){let e=this._depthRenderer.getDepthMap().getScene();e&&delete e._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null}}}let _S=rr.P.Up(),_E=rr.P.Zero(),_C=new rr.P,_b=new rr.P,_y=new rr.y3;class _A extends __{_validateFilter(e){return e===__.FILTER_NONE||e===__.FILTER_PCF||e===__.FILTER_PCSS?e:(console.error('Unsupported filter "'+e+'"!'),__.FILTER_NONE)}get numCascades(){return this._numCascades}set numCascades(e){(e=Math.min(Math.max(e,_A.MIN_CASCADES_COUNT),_A.MAX_CASCADES_COUNT))!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())}get freezeShadowCastersBoundingInfo(){return this._freezeShadowCastersBoundingInfo}set freezeShadowCastersBoundingInfo(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._freezeShadowCastersBoundingInfoObservable||e||(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(Number.MIN_VALUE,Number.MIN_VALUE,Number.MIN_VALUE),this._shadowMap&&this._shadowMap.renderList){let e=this._shadowMap.renderList;for(let t=0;t<e.length;t++){let i=e[t];if(!i)continue;let r=i.getBoundingInfo(),s=r.boundingBox;this._scbiMin.minimizeInPlace(s.minimumWorld),this._scbiMax.maximizeInPlace(s.maximumWorld)}let t=this._scene.meshes;for(let e=0;e<t.length;e++){let i=t[e];if(!i||!i.isVisible||!i.isEnabled||!i.receiveShadows)continue;let r=i.getBoundingInfo(),s=r.boundingBox;this._scbiMin.minimizeInPlace(s.minimumWorld),this._scbiMax.maximizeInPlace(s.maximumWorld)}}this._shadowCastersBoundingInfo.reConstruct(this._scbiMin,this._scbiMax)}get shadowCastersBoundingInfo(){return this._shadowCastersBoundingInfo}set shadowCastersBoundingInfo(e){this._shadowCastersBoundingInfo=e}setMinMaxDistance(e,t){(this._minDistance!==e||this._maxDistance!==t)&&(e>t&&(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 _A.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e<this._numCascades?this._cascadeMinExtents[e]:null}getCascadeMaxExtents(e){return e>=0&&e<this._numCascades?this._cascadeMaxExtents[e]:null}get shadowMaxZ(){return this._getCamera()?this._shadowMaxZ:0}set shadowMaxZ(e){let t=this._getCamera();if(!t){this._shadowMaxZ=e;return}this._shadowMaxZ===e||e<t.minZ||e>t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){let t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e<this._numCascades?this._viewMatrices[e]:null}getCascadeProjectionMatrix(e){return e>=0&&e<this._numCascades?this._projectionMatrices[e]:null}getCascadeTransformMatrix(e){return e>=0&&e<this._numCascades?this._transformMatrices[e]:null}setDepthRenderer(e){this._depthRenderer=e,this._depthReducer&&this._depthReducer.setDepthRenderer(this._depthRenderer)}get autoCalcDepthBounds(){return this._autoCalcDepthBounds}set autoCalcDepthBounds(e){let t=this._getCamera();if(t){if(this._autoCalcDepthBounds=e,!e){this._depthReducer&&this._depthReducer.deactivate(),this.setMinMaxDistance(0,1);return}this._depthReducer||(this._depthReducer=new _x(t),this._depthReducer.onAfterReductionPerformed.add(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(){let e=this._getCamera();if(!e)return;let t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,n=this._shadowMaxZ<i&&this._shadowMaxZ>=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,a=t+s*r,o=t+n*r,l=o-a,h=o/a;for(let e=0;e<this._cascades.length;++e){let i=(e+1)/this._numCascades,n=a*h**i,o=a+l*i,u=this._lambda*(n-o)+o;this._cascades[e].prevBreakDistance=0===e?s:this._cascades[e-1].breakDistance,this._cascades[e].breakDistance=(u-t)/r,this._viewSpaceFrustumsZ[e]=u,this._frustumLengths[e]=(this._cascades[e].breakDistance-this._cascades[e].prevBreakDistance)*r}this._breaksAreDirty=!1}_computeMatrices(){let e=this._scene,t=this._getCamera();if(!t)return;rr.P.NormalizeToRef(this._light.getShadowDirection(0),this._lightDirection),1===Math.abs(rr.P.Dot(this._lightDirection,rr.P.Up()))&&(this._lightDirection.z=1e-13),this._cachedDirection.copyFrom(this._lightDirection);let i=e.getEngine().useReverseDepthBuffer;for(let t=0;t<this._numCascades;++t){this._computeFrustumInWorldSpace(t),this._computeCascadeFrustum(t),this._cascadeMaxExtents[t].subtractToRef(this._cascadeMinExtents[t],_C),this._frustumCenter[t].addToRef(this._lightDirection.scale(this._cascadeMinExtents[t].z),this._shadowCameraPos[t]),rr.y3.LookAtLHToRef(this._shadowCameraPos[t],this._frustumCenter[t],_S,this._viewMatrices[t]);let r=0,s=_C.z,n=this._shadowCastersBoundingInfo;n.update(this._viewMatrices[t]),s=Math.min(s,n.boundingBox.maximumWorld.z),r=this._depthClamp&&this.filter!==__.FILTER_PCSS?Math.max(r,n.boundingBox.minimumWorld.z):Math.min(r,n.boundingBox.minimumWorld.z),rr.y3.OrthoOffCenterLHToRef(this._cascadeMinExtents[t].x,this._cascadeMaxExtents[t].x,this._cascadeMinExtents[t].y,this._cascadeMaxExtents[t].y,i?s:r,i?r:s,this._projectionMatrices[t],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[t].z=r,this._cascadeMaxExtents[t].z=s,this._viewMatrices[t].multiplyToRef(this._projectionMatrices[t],this._transformMatrices[t]),rr.P.TransformCoordinatesToRef(_E,this._transformMatrices[t],_C),_C.scaleInPlace(this._mapSize/2),_b.copyFromFloats(Math.round(_C.x),Math.round(_C.y),Math.round(_C.z)),_b.subtractInPlace(_C).scaleInPlace(2/this._mapSize),rr.y3.TranslationToRef(_b.x,_b.y,0,_y),this._projectionMatrices[t].multiplyToRef(_y,this._projectionMatrices[t]),this._viewMatrices[t].multiplyToRef(this._projectionMatrices[t],this._transformMatrices[t]),this._transformMatrices[t].copyToArray(this._transformMatricesAsArray,16*t)}}_computeFrustumInWorldSpace(e){let t=this._getCamera();if(!t)return;let i=this._cascades[e].prevBreakDistance,r=this._cascades[e].breakDistance,s=this._scene.getEngine().isNDCHalfZRange;t.getViewMatrix();let n=0===t.maxZ,a=t.maxZ;n&&(t.maxZ=this._shadowMaxZ,t.getProjectionMatrix(!0));let o=rr.y3.Invert(t.getTransformationMatrix());n&&(t.maxZ=a,t.getProjectionMatrix(!0));let l=this._scene.getEngine().useReverseDepthBuffer?4:0;for(let t=0;t<_A._FrustumCornersNDCSpace.length;++t)_C.copyFrom(_A._FrustumCornersNDCSpace[(t+l)%_A._FrustumCornersNDCSpace.length]),s&&-1===_C.z&&(_C.z=0),rr.P.TransformCoordinatesToRef(_C,o,this._frustumCornersWorldSpace[e][t]);for(let t=0;t<_A._FrustumCornersNDCSpace.length/2;++t)_C.copyFrom(this._frustumCornersWorldSpace[e][t+4]).subtractInPlace(this._frustumCornersWorldSpace[e][t]),_b.copyFrom(_C).scaleInPlace(i),_C.scaleInPlace(r),_C.addInPlace(this._frustumCornersWorldSpace[e][t]),this._frustumCornersWorldSpace[e][t+4].copyFrom(_C),this._frustumCornersWorldSpace[e][t].addInPlace(_b)}_computeCascadeFrustum(e){this._cascadeMinExtents[e].copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cascadeMaxExtents[e].copyFromFloats(Number.MIN_VALUE,Number.MIN_VALUE,Number.MIN_VALUE),this._frustumCenter[e].copyFromFloats(0,0,0);let t=this._getCamera();if(t){for(let t=0;t<this._frustumCornersWorldSpace[e].length;++t)this._frustumCenter[e].addInPlace(this._frustumCornersWorldSpace[e][t]);if(this._frustumCenter[e].scaleInPlace(1/this._frustumCornersWorldSpace[e].length),this.stabilizeCascades){let t=0;for(let i=0;i<this._frustumCornersWorldSpace[e].length;++i){let r=this._frustumCornersWorldSpace[e][i].subtractToRef(this._frustumCenter[e],_C).length();t=Math.max(t,r)}t=Math.ceil(16*t)/16,this._cascadeMaxExtents[e].copyFromFloats(t,t,t),this._cascadeMinExtents[e].copyFromFloats(-t,-t,-t)}else{let t=this._frustumCenter[e];this._frustumCenter[e].addToRef(this._lightDirection,_C),rr.y3.LookAtLHToRef(t,_C,_S,_y);for(let t=0;t<this._frustumCornersWorldSpace[e].length;++t)rr.P.TransformCoordinatesToRef(this._frustumCornersWorldSpace[e][t],_y,_C),this._cascadeMinExtents[e].minimizeInPlace(_C),this._cascadeMaxExtents[e].maximizeInPlace(_C)}}}_recreateSceneUBOs(){if(this._disposeSceneUBOs(),this._sceneUBOs)for(let e=0;e<this._numCascades;++e)this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${e})`))}static get IsSupported(){let e=rp.l.LastCreatedEngine;return!!e&&e._features.supportCSM}constructor(e,t,i,r,s=!0){if(!_A.IsSupported){ru.Y.Error("CascadedShadowMap is not supported by the current engine.");return}super(e,t,i,r,s),this.usePercentageCloserFiltering=!0}_initializeGenerator(){var e,t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,T;this.penumbraDarkness=null!==(e=this.penumbraDarkness)&&void 0!==e?e:1,this._numCascades=null!==(t=this._numCascades)&&void 0!==t?t:_A.DEFAULT_CASCADES_COUNT,this.stabilizeCascades=null!==(i=this.stabilizeCascades)&&void 0!==i&&i,this._freezeShadowCastersBoundingInfoObservable=null!==(r=this._freezeShadowCastersBoundingInfoObservable)&&void 0!==r?r:null,this.freezeShadowCastersBoundingInfo=null!==(s=this.freezeShadowCastersBoundingInfo)&&void 0!==s&&s,this._scbiMin=null!==(n=this._scbiMin)&&void 0!==n?n:new rr.P(0,0,0),this._scbiMax=null!==(a=this._scbiMax)&&void 0!==a?a:new rr.P(0,0,0),this._shadowCastersBoundingInfo=null!==(o=this._shadowCastersBoundingInfo)&&void 0!==o?o:new l5.j(new rr.P(0,0,0),new rr.P(0,0,0)),this._breaksAreDirty=null===(l=this._breaksAreDirty)||void 0===l||l,this._minDistance=null!==(h=this._minDistance)&&void 0!==h?h:0,this._maxDistance=null!==(u=this._maxDistance)&&void 0!==u?u:1,this._currentLayer=null!==(c=this._currentLayer)&&void 0!==c?c:0,this._shadowMaxZ=null!==(_=null!==(d=this._shadowMaxZ)&&void 0!==d?d:null===(p=this._getCamera())||void 0===p?void 0:p.maxZ)&&void 0!==_?_:1e4,this._debug=null!==(f=this._debug)&&void 0!==f&&f,this._depthClamp=null===(m=this._depthClamp)||void 0===m||m,this._cascadeBlendPercentage=null!==(g=this._cascadeBlendPercentage)&&void 0!==g?g:.1,this._lambda=null!==(v=this._lambda)&&void 0!==v?v:.5,this._autoCalcDepthBounds=null!==(T=this._autoCalcDepthBounds)&&void 0!==T&&T,this._recreateSceneUBOs(),super._initializeGenerator()}_createTargetRenderTexture(){let e=this._scene.getEngine(),t={width:this._mapSize,height:this._mapSize,layers:this.numCascades};this._shadowMap=new nV(this._light.name+"_CSMShadowMap",t,this._scene,!1,!0,this._textureType,!1,void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(super._initializeShadowMap(),null===this._shadowMap)return;this._transformMatricesAsArray=new Float32Array(16*this._numCascades),this._viewSpaceFrustumsZ=Array(this._numCascades),this._frustumLengths=Array(this._numCascades),this._lightSizeUVCorrection=Array(2*this._numCascades),this._depthCorrection=Array(this._numCascades),this._cascades=[],this._viewMatrices=[],this._projectionMatrices=[],this._transformMatrices=[],this._cascadeMinExtents=[],this._cascadeMaxExtents=[],this._frustumCenter=[],this._shadowCameraPos=[],this._frustumCornersWorldSpace=[];for(let e=0;e<this._numCascades;++e){this._cascades[e]={prevBreakDistance:0,breakDistance:0},this._viewMatrices[e]=rr.y3.Zero(),this._projectionMatrices[e]=rr.y3.Zero(),this._transformMatrices[e]=rr.y3.Zero(),this._cascadeMinExtents[e]=new rr.P,this._cascadeMaxExtents[e]=new rr.P,this._frustumCenter[e]=new rr.P,this._shadowCameraPos[e]=new rr.P,this._frustumCornersWorldSpace[e]=Array(_A._FrustumCornersNDCSpace.length);for(let t=0;t<_A._FrustumCornersNDCSpace.length;++t)this._frustumCornersWorldSpace[e][t]=new rr.P}let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.clear(),this._shadowMap.onBeforeRenderObservable.clear(),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===__.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!==__.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);let i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;let s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let n=this.getShadowMap();if(!n)return;let a=n.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===__.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a,1/a,this.frustumEdgeFalloff,e);else if(this._filter===__.FILTER_PCSS){for(let e=0;e<this._numCascades;++e)this._lightSizeUVCorrection[2*e+0]=0===e?1:(this._cascadeMaxExtents[0].x-this._cascadeMinExtents[0].x)/(this._cascadeMaxExtents[e].x-this._cascadeMinExtents[e].x),this._lightSizeUVCorrection[2*e+1]=0===e?1:(this._cascadeMaxExtents[0].y-this._cascadeMinExtents[0].y)/(this._cascadeMaxExtents[e].y-this._cascadeMinExtents[e].y),this._depthCorrection[e]=0===e?1:(this._cascadeMaxExtents[e].z-this._cascadeMinExtents[e].z)/(this._cascadeMaxExtents[0].z-this._cascadeMinExtents[0].z);t.setDepthStencilTexture("shadowSampler"+e,n),t.setTexture("depthSampler"+e,n),t.setArray2("lightSizeUVCorrection"+e,this._lightSizeUVCorrection),t.setArray("depthCorrection"+e,this._depthCorrection),t.setFloat("penumbraDarkness"+e,this.penumbraDarkness),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a,this._contactHardeningLightSizeUVRatio*a,this.frustumEdgeFalloff,e)}else t.setTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a,1/a,this.frustumEdgeFalloff,e);i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}getTransformMatrix(){return this.getCascadeTransformMatrix(0)}dispose(){super.dispose(),this._freezeShadowCastersBoundingInfoObservable&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),this._depthReducer&&(this._depthReducer.dispose(),this._depthReducer=null)}serialize(){let e=super.serialize(),t=this.getShadowMap();if(!t)return e;if(e.numCascades=this._numCascades,e.debug=this._debug,e.stabilizeCascades=this.stabilizeCascades,e.lambda=this._lambda,e.cascadeBlendPercentage=this.cascadeBlendPercentage,e.depthClamp=this._depthClamp,e.autoCalcDepthBounds=this.autoCalcDepthBounds,e.shadowMaxZ=this._shadowMaxZ,e.penumbraDarkness=this.penumbraDarkness,e.freezeShadowCastersBoundingInfo=this._freezeShadowCastersBoundingInfo,e.minDistance=this.minDistance,e.maxDistance=this.maxDistance,e.renderList=[],t.renderList)for(let i=0;i<t.renderList.length;i++){let r=t.renderList[i];e.renderList.push(r.id)}return e}static Parse(e,t){let i=__.Parse(e,t,(e,t,i)=>new _A(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}}_A._FrustumCornersNDCSpace=[new rr.P(-1,1,-1),new rr.P(1,1,-1),new rr.P(1,-1,-1),new rr.P(-1,-1,-1),new rr.P(-1,1,1),new rr.P(1,1,1),new rr.P(1,-1,1),new rr.P(-1,-1,1)],_A.CLASSNAME="CascadedShadowGenerator",_A.DEFAULT_CASCADES_COUNT=4,_A.MIN_CASCADES_COUNT=2,_A.MAX_CASCADES_COUNT=4,_A._SceneComponentInitialization=e=>{throw(0,st.S)("ShadowGeneratorSceneComponent")},re.p.AddParser(ss.l.NAME_SHADOWGENERATOR,(e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,r=e.shadowGenerators.length;i<r;i++){let r=e.shadowGenerators[i];r.className===_A.CLASSNAME?_A.Parse(r,t):__.Parse(r,t)}});class _R{constructor(e){this.name=ss.l.NAME_SHADOWGENERATOR,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ss.l.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR,this,this._gatherRenderTargets)}rebuild(){}serialize(e){e.shadowGenerators=[];let t=this.scene.lights;for(let i of t){let t=i.getShadowGenerators();if(t){let i=t.values();for(let t=i.next();!0!==t.done;t=i.next()){let i=t.value;e.shadowGenerators.push(i.serialize())}}}}addFromContainer(e){}removeFromContainer(e,t){}dispose(){}_gatherRenderTargets(e){let t=this.scene;if(this.scene.shadowsEnabled)for(let i=0;i<t.lights.length;i++){let r=t.lights[i],s=r.getShadowGenerators();if(r.isEnabled()&&r.shadowEnabled&&s){let i=s.values();for(let r=i.next();!0!==r.done;r=i.next()){let i=r.value,s=i.getShadowMap();-1!==t.textures.indexOf(s)&&e.push(s)}}}}}__._SceneComponentInitialization=e=>{let t=e._getComponent(ss.l.NAME_SHADOWGENERATOR);t||(t=new _R(e),e._addComponent(t))},rT.N.AddNodeConstructor("Light_Type_0",(e,t)=>()=>new _P(e,rr.P.Zero(),t));class _P extends c2{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){let t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){let e=t.value;e.recreateShadowMap()}}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return r3.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new rr.P(1,0,0);case 1:return new rr.P(-1,0,0);case 2:return new rr.P(0,-1,0);case 3:return new rr.P(0,1,0);case 4:return new rr.P(0,0,1);case 5:return new rr.P(0,0,-1)}return rr.P.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;let s=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;rr.y3.PerspectiveFovLHToRef(this.shadowAngle,1,a?n:s,a?s:n,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,r0.gn)([(0,rg.qC)()],_P.prototype,"shadowAngle",null);class _I{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{let 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";let e=`@-webkit-keyframes spin1 {\ - 0% { -webkit-transform: rotate(0deg);} - 100% { -webkit-transform: rotate(360deg);} - }\ - @keyframes spin1 {\ - 0% { transform: rotate(0deg);} - 100% { transform: rotate(360deg);} - }`;this._style.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(this._style);let t=!!window.SVGSVGElement,i=new Image;_I.DefaultLogoUrl?i.src=_I.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";let r=document.createElement("div");r.style.width="300px",r.style.gridColumn="1",r.style.gridRow="1",r.style.top="50%",r.style.left="50%",r.style.transform="translate(-50%, -50%)",r.style.position="absolute";let s=new Image;if(_I.DefaultSpinnerUrl?s.src=_I.DefaultSpinnerUrl:s.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!t){let e={w:16,h:18.5},t={w:30,h:30};i.style.width=`${e.w}vh`,i.style.height=`${e.h}vh`,i.style.left=`calc(50% - ${e.w/2}vh)`,i.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${t.w}vh`,s.style.height=`${t.h}vh`,s.style.left=`calc(50% - ${t.w/2}vh)`,s.style.top=`calc(50% - ${t.h/2}vh)`}r.appendChild(s),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)}))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}_I.DefaultLogoUrl="",_I.DefaultSpinnerUrl="",r7.D.DefaultLoadingScreenFactory=e=>new _I(e);var _M=i(1397),_D=i(5816);class _O{static ConvertPanoramaToCubemap(e,t,i,r,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";let n=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s),a=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s),o=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s),l=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s),h=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s),u=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s);return{front:n,back:a,left:o,right:l,up:h,down:u,size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,n=!1){let a=new ArrayBuffer(e*e*12),o=new Float32Array(a),l=n?Math.max(1,Math.round(r/4/e)):1,h=1/l,u=h*h,c=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),p=1/e,_=0;for(let n=0;n<e;n++)for(let a=0;a<l;a++){let a=t[0],f=t[2];for(let t=0;t<e;t++)for(let h=0;h<l;h++){let l=f.subtract(a).scale(_).add(a);l.normalize();let h=this.CalcProjectionSpherical(l,i,r,s);o[n*e*3+3*t+0]+=h.r*u,o[n*e*3+3*t+1]+=h.g*u,o[n*e*3+3*t+2]+=h.b*u,a=a.add(c),f=f.add(d)}_+=p*h}return o}static CalcProjectionSpherical(e,t,i,r){let s=Math.atan2(e.z,e.x),n=Math.acos(e.y);for(;s<-Math.PI;)s+=2*Math.PI;for(;s>Math.PI;)s-=2*Math.PI;let a=s/Math.PI,o=Math.round((a=.5*a+.5)*i);o<0?o=0:o>=i&&(o=i-1);let l=Math.round(n/Math.PI*r);l<0?l=0:l>=r&&(l=r-1);let h=r-l-1,u=t[h*i*3+3*o+0],c=t[h*i*3+3*o+1],d=t[h*i*3+3*o+2];return{r:u,g:c,b:d}}}_O.FACE_LEFT=[new rr.P(-1,-1,-1),new rr.P(1,-1,-1),new rr.P(-1,1,-1),new rr.P(1,1,-1)],_O.FACE_RIGHT=[new rr.P(1,-1,1),new rr.P(-1,-1,1),new rr.P(1,1,1),new rr.P(-1,1,1)],_O.FACE_FRONT=[new rr.P(1,-1,-1),new rr.P(1,-1,1),new rr.P(1,1,-1),new rr.P(1,1,1)],_O.FACE_BACK=[new rr.P(-1,-1,1),new rr.P(-1,-1,-1),new rr.P(-1,1,1),new rr.P(-1,1,-1)],_O.FACE_DOWN=[new rr.P(1,1,-1),new rr.P(1,1,1),new rr.P(-1,1,-1),new rr.P(-1,1,1)],_O.FACE_UP=[new rr.P(-1,-1,-1),new rr.P(-1,-1,1),new rr.P(1,-1,-1),new rr.P(1,-1,1)];class _N{static _Ldexp(e,t){return t>1023?898846567431158e293*e*Math.pow(2,t-1023):t<-1074?5e-324*e*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,r,s,n){s>0?(s=this._Ldexp(1,s-136),e[n+0]=t*s,e[n+1]=i*s,e[n+2]=r*s):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",r="";for(let s=t;s<e.length-t&&"\n"!=(r=String.fromCharCode(e[s]));s++)i+=r;return i}static RGBE_ReadHeader(e){let t=0,i=0,r=this._ReadStringLine(e,0);if("#"!=r[0]||"?"!=r[1])throw"Bad HDR Format.";let s=!1,n=!1,a=0;do a+=r.length+1,"FORMAT=32-bit_rle_rgbe"==(r=this._ReadStringLine(e,a))?n=!0:0==r.length&&(s=!0);while(!s);if(!n)throw"HDR Bad header format, unsupported FORMAT";a+=r.length+1,r=this._ReadStringLine(e,a);let o=/^-Y (.*) \+X (.*)$/g.exec(r);if(!o||o.length<3)throw"HDR Bad header format, no size";if(i=parseInt(o[2]),t=parseInt(o[1]),i<8||i>32767)throw"HDR Bad header format, unsupported size";return{height:t,width:i,dataPosition:a+=r.length+1}}static GetCubeMapTextureData(e,t,i=!1){let r=new Uint8Array(e),s=this.RGBE_ReadHeader(r),n=this.RGBE_ReadPixels(r,s),a=_O.ConvertPanoramaToCubemap(n,s.width,s.height,t,i);return a}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i,r,s,n,a,o=t.height,l=t.width,h=t.dataPosition,u=0,c=0,d=0,p=new ArrayBuffer(4*l),_=new Uint8Array(p),f=new ArrayBuffer(t.width*t.height*12),m=new Float32Array(f);for(;o>0;){if(i=e[h++],r=e[h++],s=e[h++],n=e[h++],2!=i||2!=r||128&s||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((s<<8|n)!=l)throw"HDR Bad header format, wrong scan line width";for(d=0,u=0;d<4;d++)for(c=(d+1)*l;u<c;)if(i=e[h++],r=e[h++],i>128){if(0==(a=i-128)||a>c-u)throw"HDR Bad Format, bad scanline data (run)";for(;a-- >0;)_[u++]=r}else{if(0==(a=i)||a>c-u)throw"HDR Bad Format, bad scanline data (non-run)";if(_[u++]=r,--a>0)for(let t=0;t<a;t++)_[u++]=e[h++]}for(d=0;d<l;d++)i=_[d],r=_[d+l],s=_[d+2*l],n=_[d+3*l],this._Rgbe2float(m,i,r,s,n,(t.height-o)*l*3+3*d);o--}return m}static _RGBEReadPixelsNOTRLE(e,t){let i,r,s,n,a,o=t.height,l=t.width,h=t.dataPosition,u=new ArrayBuffer(t.width*t.height*12),c=new Float32Array(u);for(;o>0;){for(a=0;a<t.width;a++)i=e[h++],r=e[h++],s=e[h++],n=e[h++],this._Rgbe2float(c,i,r,s,n,(t.height-o)*l*3+3*a);o--}return c}}let _F=`attribute vec2 position;varying vec3 direction;uniform vec3 up;uniform vec3 right;uniform vec3 front; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -mat3 view=mat3(up,right,front);direction=view*vec3(position,1.0);gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.hdrFilteringVertexShader=_F;let _L=`#include<helperFunctions> -#include<importanceSampling> -#include<pbrBRDFFunctions> -#include<hdrFilteringFunctions> -uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`;no.v.ShadersStore.hdrFilteringPixelShader=_L;class _w{constructor(e,t={}){this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}_createRenderTarget(e){let t=0;this._engine.getCaps().textureHalfFloatRender?t=2:this._engine.getCaps().textureFloatRender&&(t=1);let i=this._engine.createRenderTargetCubeTexture(e,{format:5,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(i.texture,0,0,0),this._engine.updateTextureSamplingMode(3,i.texture,!0),i}_prefilterInternal(e){let t=e.getSize().width,i=rm.R.ILog2(t)+1,r=this._effectWrapper.effect,s=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();let n=e.getInternalTexture();n&&this._engine.updateTextureSamplingMode(3,n,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let a=[[new rr.P(0,0,-1),new rr.P(0,-1,0),new rr.P(1,0,0)],[new rr.P(0,0,1),new rr.P(0,-1,0),new rr.P(-1,0,0)],[new rr.P(1,0,0),new rr.P(0,0,1),new rr.P(0,1,0)],[new rr.P(1,0,0),new rr.P(0,0,-1),new rr.P(0,-1,0)],[new rr.P(1,0,0),new rr.P(0,-1,0),new rr.P(0,0,1)],[new rr.P(-1,0,0),new rr.P(0,-1,0),new rr.P(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let e=0;e<6;e++){r.setVector3("up",a[e][0]),r.setVector3("right",a[e][1]),r.setVector3("front",a[e][2]);for(let n=0;n<i;n++){this._engine.bindFramebuffer(s,e,void 0,void 0,!0,n),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let i=Math.pow(2,(n-this._lodGenerationOffset)/this._lodGenerationScale)/t;0===n&&(i=0),r.setFloat("alphaG",i),this._effectRenderer.draw()}}this._effectRenderer.restoreStates(),this._engine.restoreDefaultFramebuffer(),this._engine._releaseTexture(e._texture);let o=s.texture.type,l=s.texture.format;return s._swapAndDie(e._texture),e._texture.type=o,e._texture.format=l,e.gammaSpace=!1,e.lodGenerationOffset=this._lodGenerationOffset,e.lodGenerationScale=this._lodGenerationScale,e._prefiltered=!0,e}_createEffect(e,t){let i=[];e.gammaSpace&&i.push("#define GAMMA_INPUT"),i.push("#define NUM_SAMPLES "+this.quality+"u");let r=new nF({engine:this._engine,name:"hdrFiltering",vertexShader:"hdrFiltering",fragmentShader:"hdrFiltering",samplerNames:["inputTexture"],uniformNames:["vSampleDirections","vWeights","up","right","front","vFilteringInfo","hdrScale","alphaG"],useShaderStore:!0,defines:i,onCompiled:t});return r}isReady(e){return e.isReady()&&this._effectWrapper.effect.isReady()}prefilter(e,t=null){return this._engine._features.allowTexturePrefiltering?new Promise(i=>{this._effectRenderer=new nN(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(ru.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 _B extends su{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(rr.y3.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,s=!0,n=!1,a=!1,o=null,l=null,h=!1){var u;if(super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=rr.P.Zero(),this.onLoadObservable=new ri.y$,!e)return;this._coordinatesMode=sv.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=rr.y3.Identity(),this._prefilterOnLoad=a,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),o&&o()},this._onError=l,this.gammaSpace=n,this._noMipmap=r,this._size=i,this._supersample=h,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?rZ.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(){let e=this._getEngine(),t=e.getCaps(),i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){let t=this._onLoad,i=new _w(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;let t=_N.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){let e=ue.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}let r=[],s=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));let a=t[_B._FacesMapping[e]];if(this.gammaSpace||n||s){for(let e=0;e<this._size*this._size;e++)if(this.gammaSpace&&(a[3*e+0]=Math.pow(a[3*e+0],rL.zp),a[3*e+1]=Math.pow(a[3*e+1],rL.zp),a[3*e+2]=Math.pow(a[3*e+2],rL.zp)),n&&(n[3*e+0]=h6(a[3*e+0]),n[3*e+1]=h6(a[3*e+1]),n[3*e+2]=h6(a[3*e+2])),s){let t=Math.max(255*a[3*e+0],0),i=Math.max(255*a[3*e+1],0),r=Math.max(255*a[3*e+2],0),n=Math.max(Math.max(t,i),r);if(n>255){let e=255/n;t*=e,i*=e,r*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=r}}n?r.push(n):s?r.push(s):r.push(a)}return r},null,this._onLoad,this._onError)}clone(){let e=new _B(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 r=null;return e.name&&!e.isRenderTarget&&((r=new _B(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=rr.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=rr.P.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;let 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}}_B._FacesMapping=["right","left","up","down","front","back"],(0,rn.H)("BABYLON.HDRCubeTexture",_B);class _U{get influence(){return this._influence}set influence(e){if(this._influence===e)return;let t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new ri.y$,this._onDataLayoutChanged=new ri.y$,this._animationPropertiesOverride=null,this._scene=i||rp.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){let t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){let t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){let t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){let t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){let e=rg.p4.Clone(()=>new _U(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(){let 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())),rg.p4.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){let i=new _U(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t<e.animations.length;t++){let r=e.animations[t],s=(0,rn.q)("BABYLON.Animation");s&&i.animations.push(s.Parse(r))}e.autoAnimate&&t&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1)}return i}static FromMesh(e,t,i){t||(t=e.name);let r=new _U(t,i,e.getScene());return r.setPositions(e.getVerticesData(rQ.o.PositionKind)),e.isVerticesDataPresent(rQ.o.NormalKind)&&r.setNormals(e.getVerticesData(rQ.o.NormalKind)),e.isVerticesDataPresent(rQ.o.TangentKind)&&r.setTangents(e.getVerticesData(rQ.o.TangentKind)),e.isVerticesDataPresent(rQ.o.UVKind)&&r.setUVs(e.getVerticesData(rQ.o.UVKind)),r}}(0,r0.gn)([(0,rg.qC)()],_U.prototype,"id",void 0);class _V extends sv{get depth(){return this._depth}constructor(e,t,i,r,s,n,a=!0,o=!1,l=sv.TRILINEAR_SAMPLINGMODE,h=0,u){super(null,n,!a,o),this.format=s,this._texture=n.getEngine().createRawTexture2DArray(e,t,i,r,s,a,o,l,null,h,u),this._depth=r,this.is2DArray=!0}update(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}static CreateRGBATexture(e,t,i,r,s,n=!0,a=!1,o=3,l=0){return new _V(e,t,i,r,5,s,n,a,o,l)}}class _k{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null){if(this._targets=[],this._targetInfluenceChangedObservers=[],this._targetDataLayoutChangedObservers=[],this._activeTargets=new na.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=[],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=rp.l.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();let 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 _k.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){let 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(){let e=new _k(this._scene);for(let t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){let e={};for(let t of(e.id=this.uniqueId,e.targets=[],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(let e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=_k.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;let r=e.getPositions();if(r){let e=r.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e){ru.Y.Error("Incompatible target. Targets must all have the same vertices count.");return}}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e<t;e++)this._influences[e]=this._tempInfluences[e];e&&this.synchronize()}synchronize(){if(this._scene&&!this.areUpdatesFrozen){if(this.isUsingTextureForTargets&&this._vertexCount){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride,this._textureHeight=1;let e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){let 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();let e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4),i=0;for(let r=0;r<e;r++){let e=this._targets[r],s=e.getPositions(),n=e.getNormals(),a=e.getUVs(),o=e.getTangents();if(!s){0===r&&ru.Y.Error("Invalid morph target. Target must have positions.");return}i=r*this._textureWidth*this._textureHeight*4;for(let e=0;e<this._vertexCount;e++)t[i]=s[3*e],t[i+1]=s[3*e+1],t[i+2]=s[3*e+2],i+=4,this._supportsNormals&&n&&(t[i]=n[3*e],t[i+1]=n[3*e+1],t[i+2]=n[3*e+2],i+=4),this._supportsUVs&&a&&(t[i]=a[2*e],t[i+1]=a[2*e+1],i+=4),this._supportsTangents&&o&&(t[i]=o[3*e],t[i+1]=o[3*e+1],t[i+2]=o[3*e+2],i+=4)}this._targetStoreTexture=_V.CreateRGBATexture(t,this._textureWidth,this._textureHeight,e,this._scene,!1,!1,1,1)}}for(let e of this._scene.meshes)e.morphTargetManager===this&&e._syncGeometryWithMorphTargetManager()}}dispose(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this._scene){if(this._scene.removeMorphTargetManager(this),this._parentContainer){let e=this._parentContainer.morphTargetManagers.indexOf(this);e>-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(let e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){let i=new _k(t);for(let r of(i._uniqueId=e.id,e.targets))i.addTarget(_U.Parse(r,t));return i}}_k.EnableTextureStorage=!0,_k.MaxActiveMorphTargetsInVertexAttributeMode=8;class _G{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=rr.P.Zero(),this._hitPointWorld=rr.P.Zero(),this._rayFromWorld=rr.P.Zero(),this._rayToWorld=rr.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=rr.P.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=rr.P.Zero(),t=rr.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,this.body=void 0,this.bodyIndex=void 0}}class _z{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,st.S)("CannonJSPlugin")}constructor(e,t=_z.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new rr.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){let t=this._impostors.indexOf(e);if(t>-1){let i=this._impostors.splice(t,1);i.length&&this.getPhysicsPlugin().removePhysicsBody(e)}}addJoint(e,t,i){let r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){let r=this._joints.filter(function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e});r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach(e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t<this._impostors.length;++t)if(this._impostors[t].object===e)return this._impostors[t];return null}getImpostorWithPhysicsBody(e){for(let t=0;t<this._impostors.length;++t)if(this._impostors[t].physicsBody===e)return this._impostors[t];return null}raycast(e,t){return this._physicsPlugin.raycast(e,t)}raycastToRef(e,t,i){return this._physicsPlugin.raycastToRef(e,t,i)}}class _W{constructor(e=!0,t=10,i=CANNON){if(this._useDeltaForWorldStep=e,this.name="CannonJSPlugin",this._physicsMaterials=[],this._fixedTimeStep=1/60,this._physicsBodiesToRemoveAfterStep=[],this._firstFrame=!0,this._tmpQuaternion=new rr._f,this._minus90X=new rr._f(-.7071067811865475,0,0,.7071067811865475),this._plus90X=new rr._f(.7071067811865475,0,0,.7071067811865475),this._tmpPosition=rr.P.Zero(),this._tmpDeltaPosition=rr.P.Zero(),this._tmpUnityRotation=new rr._f,this.BJSCANNON=i,!this.isSupported()){ru.Y.Error("CannonJS is not available. Please make sure you included the js file.");return}this._extendNamespace(),this.world=new this.BJSCANNON.World,this.world.broadphase=new this.BJSCANNON.NaiveBroadphase,this.world.solver.iterations=t,this._cannonRaycastResult=new this.BJSCANNON.RaycastResult,this._raycastResult=new _G}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this._fixedTimeStep=e}getTimeStep(){return this._fixedTimeStep}executeStep(e,t){if(this._firstFrame)for(let e of(this._firstFrame=!1,t))e.type==sG.HeightmapImpostor||e.type===sG.PlaneImpostor||e.beforeStep();this.world.step(this._useDeltaForWorldStep?e:this._fixedTimeStep),this._removeMarkedPhysicsBodiesFromWorld()}_removeMarkedPhysicsBodiesFromWorld(){this._physicsBodiesToRemoveAfterStep.length>0&&(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){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,r)}applyForce(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){let t=this._createShape(e);if(!t){ru.Y.Warn("It was not possible to create a physics body for this object.");return}let i=e.physicsBody;i&&this.removePhysicsBody(e);let r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:r},n=e.getParam("nativeOptions");for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&(s[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(t){let r=i[t];e.physicsBody[t].set(r.x,r.y,r.z)}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}_processChildMeshes(e){let 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){let i=t=>{if(!t.rotationQuaternion)return;let r=t.getPhysicsImpostor();if(r){let i=r.parent;if(i!==e&&t.parent){let i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);r.physicsBody&&(this.removePhysicsBody(r),r.physicsBody=null),r.parent=e,r.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(r),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=r.getParam("mass")}}t.getChildMeshes(!0).filter(e=>!!e.physicsImpostor).forEach(i)};t.filter(e=>!!e.physicsImpostor).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,n={pivotA:s.mainPivot?new this.BJSCANNON.Vec3().set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?new this.BJSCANNON.Vec3().set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?new this.BJSCANNON.Vec3().set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?new this.BJSCANNON.Vec3().set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case sk.HingeJoint:case sk.Hinge2Joint:t=new this.BJSCANNON.HingeConstraint(i,r,n);break;case sk.DistanceJoint:t=new this.BJSCANNON.DistanceConstraint(i,r,s.maxDistance||2);break;case sk.SpringJoint:t=new this.BJSCANNON.Spring(i,r,{restLength:s.length,stiffness:s.stiffness,damping:s.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break;case sk.LockJoint:t=new this.BJSCANNON.LockConstraint(i,r,n);break;case sk.PointToPointJoint:case sk.BallAndSocketJoint:default:t=new this.BJSCANNON.PointToPointConstraint(i,n.pivotA,r,n.pivotB,n.maxForce)}t.collideConnected=!!s.collision,e.joint.physicsJoint=t,e.joint.type!==sk.SpringJoint?this.world.addConstraint(t):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){t.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==sk.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,s;for(r=0;r<this._physicsMaterials.length;r++)if((s=this._physicsMaterials[r]).friction===t&&s.restitution===i)return s;let n=new this.BJSCANNON.Material(e);return n.friction=t,n.restitution=i,this._physicsMaterials.push(n),n}_checkWithEpsilon(e){return e<rL.kn?rL.kn:e}_createShape(e){let t;let i=e.object,r=e.getObjectExtents();switch(e.type){case sG.SphereImpostor:{let e=r.x,i=r.y,s=r.z;t=new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(e),this._checkWithEpsilon(i),this._checkWithEpsilon(s))/2);break}case sG.CylinderImpostor:{let i=e.getParam("nativeOptions");i||(i={});let s=void 0!==i.radiusTop?i.radiusTop:this._checkWithEpsilon(r.x)/2,n=void 0!==i.radiusBottom?i.radiusBottom:this._checkWithEpsilon(r.x)/2,a=void 0!==i.height?i.height:this._checkWithEpsilon(r.y),o=void 0!==i.numSegments?i.numSegments:16;t=new this.BJSCANNON.Cylinder(s,n,a,o);let l=new this.BJSCANNON.Quaternion;l.setFromAxisAngle(new this.BJSCANNON.Vec3(1,0,0),-Math.PI/2);let h=new this.BJSCANNON.Vec3(0,0,0);t.transformAllPoints(h,l);break}case sG.BoxImpostor:{let e=r.scale(.5);t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(e.x),this._checkWithEpsilon(e.y),this._checkWithEpsilon(e.z)));break}case sG.PlaneImpostor:ru.Y.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead"),t=new this.BJSCANNON.Plane;break;case sG.MeshImpostor:{let r;let s=i.getVerticesData?i.getVerticesData(rQ.o.PositionKind):[],n=i.getIndices?i.getIndices():[];if(!s){ru.Y.Warn("Tried to create a MeshImpostor for an object without vertices. This will fail.");return}let a=i.position.clone(),o=i.rotation&&i.rotation.clone(),l=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace();let h=i.computeWorldMatrix(!0),u=[];for(r=0;r<s.length;r+=3)rr.P.TransformCoordinates(rr.P.FromArray(s,r),h).toArray(u,r);ru.Y.Warn("MeshImpostor only collides against spheres."),t=new this.BJSCANNON.Trimesh(u,n),i.position.copyFrom(a),o&&i.rotation&&i.rotation.copyFrom(o),l&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(l);break}case sG.HeightmapImpostor:{let r=i.position.clone(),s=i.rotation&&i.rotation.clone(),n=i.rotationQuaternion&&i.rotationQuaternion.clone();i.position.copyFromFloats(0,0,0),i.rotation&&i.rotation.copyFromFloats(0,0,0),i.rotationQuaternion&&i.rotationQuaternion.copyFrom(e.getParentsRotation()),i.rotationQuaternion&&i.parent&&i.rotationQuaternion.conjugateInPlace(),i.rotationQuaternion&&i.rotationQuaternion.multiplyInPlace(this._minus90X),t=this._createHeightmap(i),i.position.copyFrom(r),s&&i.rotation&&i.rotation.copyFrom(s),n&&i.rotationQuaternion&&i.rotationQuaternion.copyFrom(n),i.computeWorldMatrix(!0);break}case sG.ParticleImpostor:t=new this.BJSCANNON.Particle;break;case sG.NoImpostor:t=new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0,0,0))}return t}_createHeightmap(e,t){let i,r=e.getVerticesData(rQ.o.PositionKind),s=e.computeWorldMatrix(!0),n=[];for(i=0;i<r.length;i+=3)rr.P.TransformCoordinates(rr.P.FromArray(r,i),s).toArray(n,i);r=n;let a=[],o=t||~~(Math.sqrt(r.length/3)-1),l=e.getBoundingInfo(),h=Math.min(l.boundingBox.extendSizeWorld.x,l.boundingBox.extendSizeWorld.y),u=l.boundingBox.extendSizeWorld.z,c=2*h/o;for(let e=0;e<r.length;e+=3){let t=Math.round(r[e+0]/c+o/2),i=Math.round(-((r[e+1]/c-o/2)*1)),s=-r[e+2]+u;a[t]||(a[t]=[]),a[t][i]||(a[t][i]=s),a[t][i]=Math.max(s,a[t][i])}for(let e=0;e<=o;++e){if(!a[e]){let t=1;for(;!a[(e+t)%o];)t++;a[e]=a[(e+t)%o].slice()}for(let t=0;t<=o;++t)if(!a[e][t]){let i,r=1;for(;void 0===i;)i=a[e][(t+r++)%o];a[e][t]=i}}let d=new this.BJSCANNON.Heightfield(a,{elementSize:c});return d.minY=u,d}_updatePhysicsBodyTransformation(e){let t=e.object;if(t.computeWorldMatrix&&t.computeWorldMatrix(!0),!t.getBoundingInfo())return;let i=e.getObjectCenter();this._tmpDeltaPosition.copyFrom(t.getAbsolutePivotPoint().subtract(i)),this._tmpDeltaPosition.divideInPlace(e.object.scaling),this._tmpPosition.copyFrom(i);let r=t.rotationQuaternion;if(r){if((e.type===sG.PlaneImpostor||e.type===sG.HeightmapImpostor)&&(r=r.multiply(this._minus90X),e.setDeltaRotation(this._plus90X)),e.type===sG.HeightmapImpostor){let e=t.getBoundingInfo(),r=t.rotationQuaternion;t.rotationQuaternion=this._tmpUnityRotation,t.computeWorldMatrix(!0);let s=i.clone(),n=t.getPivotMatrix();n=n?n.clone():rr.y3.Identity();let a=rr.y3.Translation(e.boundingBox.extendSizeWorld.x,0,-e.boundingBox.extendSizeWorld.z);t.setPreTransformMatrix(a),t.computeWorldMatrix(!0),e=t.getBoundingInfo();let o=e.boundingBox.centerWorld.subtract(i).subtract(t.position).negate();this._tmpPosition.copyFromFloats(o.x,o.y-e.boundingBox.extendSizeWorld.y,o.z),this._tmpDeltaPosition.copyFrom(e.boundingBox.centerWorld.subtract(s)),this._tmpDeltaPosition.y+=e.boundingBox.extendSizeWorld.y,t.rotationQuaternion=r,t.setPreTransformMatrix(n),t.computeWorldMatrix(!0)}else e.type===sG.MeshImpostor&&this._tmpDeltaPosition.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpDeltaPosition),e.physicsBody.position.set(this._tmpPosition.x,this._tmpPosition.y,this._tmpPosition.z),e.physicsBody.quaternion.set(r.x,r.y,r.z,r.w)}}setTransformationFromPhysicsBody(e){if(e.object.position.set(e.physicsBody.position.x,e.physicsBody.position.y,e.physicsBody.position.z),e.object.rotationQuaternion){let t=e.physicsBody.quaternion;e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}setPhysicsBodyTransformation(e,t,i){e.physicsBody.position.set(t.x,t.y,t.z),e.physicsBody.quaternion.set(i.x,i.y,i.z,i.w)}isSupported(){return void 0!==this.BJSCANNON}setLinearVelocity(e,t){e.physicsBody.velocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){let t=e.physicsBody.velocity;return t?new rr.P(t.x,t.y,t.z):null}getAngularVelocity(e){let t=e.physicsBody.angularVelocity;return t?new rr.P(t.x,t.y,t.z):null}setBodyMass(e,t){e.physicsBody.mass=t,e.physicsBody.updateMassProperties()}getBodyMass(e){return e.physicsBody.mass}getBodyFriction(e){return e.physicsBody.material.friction}setBodyFriction(e,t){e.physicsBody.material.friction=t}getBodyRestitution(e){return e.physicsBody.material.restitution}setBodyRestitution(e,t){e.physicsBody.material.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.wakeUp()}updateDistanceJoint(e,t){e.physicsJoint.distance=t}setMotor(e,t,i,r){!r&&(e.physicsJoint.enableMotor(),e.physicsJoint.setMotorSpeed(t),i&&this.setLimit(e,i))}setLimit(e,t,i){e.physicsJoint.motorEquation.maxForce=i,e.physicsJoint.motorEquation.minForce=void 0===t?-t:t}syncMeshWithImpostor(e,t){let 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.quaternion.x,e.rotationQuaternion.y=i.quaternion.y,e.rotationQuaternion.z=i.quaternion.z,e.rotationQuaternion.w=i.quaternion.w)}getRadius(e){let t=e.physicsBody.shapes[0];return t.boundingSphereRadius}getBoxSizeToRef(e,t){let i=e.physicsBody.shapes[0];t.x=2*i.halfExtents.x,t.y=2*i.halfExtents.y,t.z=2*i.halfExtents.z}dispose(){}_extendNamespace(){let e=new this.BJSCANNON.Vec3,t=this.BJSCANNON;this.BJSCANNON.World.prototype.step=function(i,r,s){if(s=s||10,0===(r=r||0))this.internalStep(i),this.time+=i;else{let n=Math.floor((this.time+r)/i)-Math.floor(this.time/i);n=Math.min(n,s)||1;let a=performance.now();for(let e=0;e!==n&&(this.internalStep(i),!(performance.now()-a>1e3*i));e++);this.time+=r;let o=this.time%i,l=o/i,h=this.bodies;for(let i=0;i!==h.length;i++){let r=h[i];r.type!==t.Body.STATIC&&r.sleepState!==t.Body.SLEEPING?(r.position.vsub(r.previousPosition,e),e.scale(l,e),r.position.vadd(e,r.interpolatedPosition)):(r.interpolatedPosition.set(r.position.x,r.position.y,r.position.z),r.interpolatedQuaternion.set(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.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))}}_z.DefaultPluginFactory=()=>new _W;class _H{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=rr.P.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new _G}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}let e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];if(!e||!t){i=i.next;continue}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}}applyImpulse(e,t,i){let r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){ru.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());return}if(e.isBodyInitRequired()){var t;let i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},r=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach(function(e){e.physicsImpostor&&r.push(e.physicsImpostor)});let s=e=>Math.max(e,rL.kn),n=new rr._f;r.forEach(t=>{if(!t.object.rotationQuaternion)return;let r=t.object.rotationQuaternion;n.copyFrom(r),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);let a=n.toEulerAngles(),o=t.getObjectExtents();if(t===e){let t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{let e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(57.29577951308232*a.x,57.29577951308232*a.y,57.29577951308232*a.z)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case sG.ParticleImpostor:ru.Y.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case sG.SphereImpostor:{let e=o.x,t=o.y,r=o.z,n=Math.max(s(e),s(t),s(r))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case sG.CylinderImpostor:{let e=s(o.x)/2,t=s(o.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case sG.PlaneImpostor:case sG.BoxImpostor:default:{let e=s(o.x),t=s(o.y),r=s(o.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(r)}}t.object.rotationQuaternion=r}),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,n=s.nativeParams||{},a={body1:i,body2:r,axe1:n.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:n.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:n.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:n.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:n.min,max:n.max,collision:n.collision||s.collision,spring:n.spring,world:this.world};switch(e.joint.type){case sk.BallAndSocketJoint:t="jointBall";break;case sk.SpringJoint:ru.Y.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead"),a.min=s.length||a.min,a.max=Math.max(a.min,a.max);case sk.DistanceJoint:t="jointDistance",a.max=s.maxDistance;break;case sk.PrismaticJoint:t="jointPrisme";break;case sk.SliderJoint:t="jointSlide";break;case sk.WheelJoint:t="jointWheel";break;case sk.HingeJoint:default:t="jointHinge"}a.type=t,e.joint.physicsJoint=this.world.add(a)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){ru.Y.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{let t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){let t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){let t=e.physicsBody.linearVelocity;return t?new rr.P(t.x,t.y,t.z):null}getAngularVelocity(e){let t=e.physicsBody.angularVelocity;return t?new rr.P(t.x,t.y,t.z):null}setBodyMass(e,t){let i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){void 0!==i?ru.Y.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,r){let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){let 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){let 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 ru.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){ru.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class _X{constructor(e=!0,t=Ammo,i=null){if(this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new rr._f,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new rr.P,this._tmpContactNormal=new rr.P,this._tmpVec3=new rr.P,this._tmpMatrix=new rr.y3,"function"==typeof t){ru.Y.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}if(this.bjsAMMO=t,!this.isSupported()){ru.Y.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint);let t=e.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 _G,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i<i?(this.world.stepSimulation(e,0),e=0):(e-=i,this.world.stepSimulation(i,0)),t--}executeStep(e,t){for(let e of t)e.soft||e.beforeStep();for(let i of(this._stepSimulation(this._useDeltaForWorldStep?e:this._timeStep,this._maxSteps,this._fixedTimeStep),t))if(i.soft?this._afterSoftStep(i):i.afterStep(),i._onPhysicsCollideCallbacks.length>0&&this._isImpostorInContact(i))for(let e of i._onPhysicsCollideCallbacks)for(let 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===sG.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){let t,i,r,s;let n=e.physicsBody.get_m_nodes(),a=n.size(),o=[];for(let e=0;e<a;e++)i=(t=n.at(e).get_m_x()).x(),r=t.y(),s=t.z(),o.push(new rr.P(i,r,s));let l=e.object,h=e.getParam("shape");e._isFromLine?e.object=hC("lines",{points:o,instance:l}):e.object=hI("ext",{shape:h,path:o,instance:l})}_softbodyOrClothStep(e){let t,i,r,s,n,a,o,l;let h=e.type===sG.ClothImpostor?1:-1,u=e.object,c=u.getVerticesData(rQ.o.PositionKind);c||(c=[]);let d=u.getVerticesData(rQ.o.NormalKind);d||(d=[]);let p=c.length/3,_=e.physicsBody.get_m_nodes();for(let e=0;e<p;e++){r=(i=(t=_.at(e)).get_m_x()).x(),s=i.y(),n=i.z()*h;let u=t.get_m_n();a=u.x(),o=u.y(),l=u.z()*h,c[3*e]=r,c[3*e+1]=s,c[3*e+2]=n,d[3*e]=a,d[3*e+1]=o,d[3*e+2]=l}let f=new sN.x;f.positions=c,f.normals=d,f.uvs=u.getVerticesData(rQ.o.UVKind),f.colors=u.getVerticesData(rQ.o.ColorKind),u&&u.getIndices&&(f.indices=u.getIndices()),f.applyToMesh(u)}applyImpulse(e,t,i){if(e.soft)ru.Y.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();let r=this._tmpAmmoVectorA,s=this._tmpAmmoVectorB;e.object&&e.object.getWorldMatrix&&i.subtractInPlace(e.object.getWorldMatrix().getTranslation()),r.setValue(i.x,i.y,i.z),s.setValue(t.x,t.y,t.z),e.physicsBody.applyImpulse(s,r)}}applyForce(e,t,i){if(e.soft)ru.Y.Warn("Cannot be applied to a soft body");else{e.physicsBody.activate();let r=this._tmpAmmoVectorA,s=this._tmpAmmoVectorB;if(e.object&&e.object.getWorldMatrix){let t=e.object.getWorldMatrix().getTranslation();r.setValue(i.x-t.x,i.y-t.y,i.z-t.z)}else r.setValue(i.x,i.y,i.z);s.setValue(t.x,t.y,t.z),e.physicsBody.applyForce(s,r)}}generatePhysicsBody(e){if(e._pluginData.toDispose=[],e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){let t=this._createShape(e),i=e.getParam("mass");if(e._pluginData.mass=i,e.soft)t.get_m_cfg().set_collisions(17),t.get_m_cfg().set_kDP(e.getParam("damping")),this.bjsAMMO.castObject(t,this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(e.getParam("margin")),t.setActivationState(_X._DISABLE_DEACTIVATION_FLAG),this.world.addSoftBody(t,1,-1),e.physicsBody=t,e._pluginData.toDispose.push(t),this.setBodyPressure(e,0),e.type===sG.SoftbodyImpostor&&this.setBodyPressure(e,e.getParam("pressure")),this.setBodyStiffness(e,e.getParam("stiffness")),this.setBodyVelocityIterations(e,e.getParam("velocityIterations")),this.setBodyPositionIterations(e,e.getParam("positionIterations"));else{let r=new this.bjsAMMO.btVector3(0,0,0),s=new this.bjsAMMO.btTransform;e.object.computeWorldMatrix(!0),s.setIdentity(),0!==i&&t.calculateLocalInertia(i,r),this._tmpAmmoVectorA.setValue(e.object.position.x,e.object.position.y,e.object.position.z),this._tmpAmmoQuaternion.setValue(e.object.rotationQuaternion.x,e.object.rotationQuaternion.y,e.object.rotationQuaternion.z,e.object.rotationQuaternion.w),s.setOrigin(this._tmpAmmoVectorA),s.setRotation(this._tmpAmmoQuaternion);let n=new this.bjsAMMO.btDefaultMotionState(s),a=new this.bjsAMMO.btRigidBodyConstructionInfo(i,n,t,r),o=new this.bjsAMMO.btRigidBody(a);if(0===i&&(o.setCollisionFlags(o.getCollisionFlags()|_X._KINEMATIC_FLAG),o.setActivationState(_X._DISABLE_DEACTIVATION_FLAG)),e.type!=sG.NoImpostor||t.getChildShape||o.setCollisionFlags(o.getCollisionFlags()|_X._DISABLE_COLLISION_FLAG),e.type!==sG.MeshImpostor&&e.type!==sG.NoImpostor){let t=e.object.getBoundingInfo();this._tmpVec3.copyFrom(e.object.getAbsolutePosition()),this._tmpVec3.subtractInPlace(t.boundingBox.centerWorld),this._tmpVec3.x/=e.object.scaling.x,this._tmpVec3.y/=e.object.scaling.y,this._tmpVec3.z/=e.object.scaling.z,e.setDeltaPosition(this._tmpVec3)}let l=e.getParam("group"),h=e.getParam("mask");l&&h?this.world.addRigidBody(o,l,h):this.world.addRigidBody(o),e.physicsBody=o,e._pluginData.toDispose=e._pluginData.toDispose.concat([o,a,n,s,r,t])}this.setBodyRestitution(e,e.getParam("restitution")),this.setBodyFriction(e,e.getParam("friction"))}}removePhysicsBody(e){this.world&&(e.soft?this.world.removeSoftBody(e.physicsBody):this.world.removeRigidBody(e.physicsBody),e._pluginData&&(e._pluginData.toDispose.forEach(e=>{this.bjsAMMO.destroy(e)}),e._pluginData.toDispose=[]))}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData;switch(s.mainPivot||(s.mainPivot=new rr.P(0,0,0)),s.connectedPivot||(s.connectedPivot=new rr.P(0,0,0)),e.joint.type){case sk.DistanceJoint:{let e=s.maxDistance;e&&(s.mainPivot=new rr.P(0,-e/2,0),s.connectedPivot=new rr.P(0,e/2,0)),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case sk.HingeJoint:{s.mainAxis||(s.mainAxis=new rr.P(0,0,0)),s.connectedAxis||(s.connectedAxis=new rr.P(0,0,0));let e=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),n=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);t=new this.bjsAMMO.btHingeConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),e,n);break}case sk.BallAndSocketJoint:t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:ru.Y.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z))}this.world.addConstraint(t,!e.joint.jointData.collision),e.joint.physicsJoint=t}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s,n=i.getIndices();n||(n=[]);let a=i.getVerticesData(rQ.o.PositionKind);if(a||(a=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?rr._f.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):rr._f.Identity();let r=rr.y3.Compose(rr.P.One(),e,t.position);r.invertToRef(this._tmpMatrix);let n=i.computeWorldMatrix(!1);s=n.multiply(this._tmpMatrix)}else rr.y3.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),s=this._tmpMatrix;let o=n.length/3;for(let t=0;t<o;t++){let i=[];for(let e=0;e<3;e++){let r,o=new rr.P(a[3*n[3*t+e]+0],a[3*n[3*t+e]+1],a[3*n[3*t+e]+2]);o=rr.P.TransformCoordinates(o,s),(r=0==e?this._tmpAmmoVectorA:1==e?this._tmpAmmoVectorB:this._tmpAmmoVectorC).setValue(o.x,o.y,o.z),i.push(r)}e.addTriangle(i[0],i[1],i[2]),r++}i.getChildMeshes().forEach(i=>{r+=this._addMeshVerts(e,t,i)})}return r}_softVertexData(e){let t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(rQ.o.PositionKind);i||(i=[]);let r=t.getVerticesData(rQ.o.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);let s=[],n=[];for(let e=0;e<i.length;e+=3){let a=new rr.P(i[e],i[e+1],i[e+2]),o=new rr.P(r[e],r[e+1],r[e+2]);a=rr.P.TransformCoordinates(a,t.getWorldMatrix()),o=rr.P.TransformNormal(o,t.getWorldMatrix()),s.push(a.x,a.y,a.z),n.push(o.x,o.y,o.z)}let a=new sN.x;return a.positions=s,a.normals=n,a.uvs=t.getVerticesData(rQ.o.UVKind),a.colors=t.getVerticesData(rQ.o.ColorKind),t&&t.getIndices&&(a.indices=t.getIndices()),a.applyToMesh(t),t.position=rr.P.Zero(),t.rotationQuaternion=null,t.rotation=rr.P.Zero(),t.computeWorldMatrix(!0),a}return sN.x.ExtractFromMesh(t)}_createSoftbody(e){let t=e.object;if(t&&t.getIndices){let i=t.getIndices();i||(i=[]);let r=this._softVertexData(e),s=r.positions,n=r.normals;if(null===s||null===n)return new this.bjsAMMO.btCompoundShape;{let e;let r=[],a=[];for(let e=0;e<s.length;e+=3){let t=new rr.P(s[e],s[e+1],s[e+2]),i=new rr.P(n[e],n[e+1],n[e+2]);r.push(t.x,t.y,-t.z),a.push(i.x,i.y,-i.z)}let o=new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(),r,t.getIndices(),i.length/3,!0),l=s.length/3,h=o.get_m_nodes();for(let t=0;t<l;t++)(e=h.at(t).get_m_n()).setX(a[3*t]),e.setY(a[3*t+1]),e.setZ(a[3*t+2]);return o}}}_createCloth(e){let t=e.object;if(t&&t.getIndices){let i=t.getIndices();i||(i=[]);let r=this._softVertexData(e),s=r.positions,n=r.normals;if(null===s||null===n)return new this.bjsAMMO.btCompoundShape;{let t=s.length,i=Math.sqrt(t/3);e.segments=i;let r=i-1;this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[3*r],s[3*r+1],s[3*r+2]),this._tmpAmmoVectorD.setValue(s[t-3],s[t-2],s[t-1]),this._tmpAmmoVectorC.setValue(s[t-3-3*r],s[t-2-3*r],s[t-1-3*r]);let n=new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,this._tmpAmmoVectorC,this._tmpAmmoVectorD,i,i,e.getParam("fixedPoints"),!0);return n}}}_createRope(e){let t,i;let r=this._softVertexData(e),s=r.positions,n=r.normals;if(null===s||null===n)return new this.bjsAMMO.btCompoundShape;r.applyToMesh(e.object,!0),e._isFromLine=!0;let a=n.map(e=>e*e),o=a.reduce((e,t)=>e+t);if(0===o)i=(t=s.length)/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;let r=e.getParam("path"),s=e.getParam("shape");if(null===s)return ru.Y.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;i=(t=r.length)-1,this._tmpAmmoVectorA.setValue(r[0].x,r[0].y,r[0].z),this._tmpAmmoVectorB.setValue(r[t-1].x,r[t-1].y,r[t-1].z)}e.segments=i;let l=e.getParam("fixedPoints");l=l>3?3:l;let h=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,l);return h.get_m_cfg().set_collisions(17),h}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let n=i.getVerticesData(rQ.o.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);let a=s.length/3;for(let t=0;t<a;t++){let a=[];for(let e=0;e<3;e++){let r,o=new rr.P(n[3*s[3*t+e]+0],n[3*s[3*t+e]+1],n[3*s[3*t+e]+2]);rr.y3.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),o=rr.P.TransformCoordinates(o,this._tmpMatrix),(r=0==e?this._tmpAmmoVectorA:1==e?this._tmpAmmoVectorB:this._tmpAmmoVectorC).setValue(o.x,o.y,o.z),a.push(r)}e.addPoint(a[0],!0),e.addPoint(a[1],!0),e.addPoint(a[2],!0),r++}i.getChildMeshes().forEach(i=>{r+=this._addHullVerts(e,t,i)})}return r}_createShape(e,t=!1){let i;let r=e.object,s=e.getObjectExtents();if(!t){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];i=new this.bjsAMMO.btCompoundShape;let r=0;if(t.forEach(e=>{let t=e.getPhysicsImpostor();if(t){if(t.type==sG.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";let s=this._createShape(t),n=e.parent.getWorldMatrix().clone(),a=new rr.P;n.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),i.addChildShape(this._tmpAmmoTransform,s),t.dispose(),r++}}),r>0){if(e.type!=sG.NoImpostor){let 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),i.addChildShape(this._tmpAmmoTransform,t))}return i}this.bjsAMMO.destroy(i),i=null}switch(e.type){case sG.SphereImpostor:if(rm.R.WithinEpsilon(s.x,s.y,1e-4)&&rm.R.WithinEpsilon(s.x,s.z,1e-4))i=new this.bjsAMMO.btSphereShape(s.x/2);else{let e=[new this.bjsAMMO.btVector3(0,0,0)];(i=new this.bjsAMMO.btMultiSphereShape(e,[1],1)).setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case sG.CapsuleImpostor:{let e=s.x/2;i=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case sG.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case sG.PlaneImpostor:case sG.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case sG.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)i=this.onCreateCustomMeshImpostor(e);else{let t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);let s=this._addMeshVerts(t,r,r);i=0==s?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case sG.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)i=this.onCreateCustomConvexHullImpostor(e);else{let t=new this.bjsAMMO.btConvexHullShape,s=this._addHullVerts(t,r,r);0==s?(e._pluginData.toDispose.push(t),i=new this.bjsAMMO.btCompoundShape):i=t}break;case sG.NoImpostor:i=new this.bjsAMMO.btSphereShape(s.x/2);break;case sG.CustomImpostor:i=this._createCustom(e);break;case sG.SoftbodyImpostor:i=this._createSoftbody(e);break;case sG.ClothImpostor:i=this._createCloth(e);break;case sG.RopeImpostor:i=this._createRope(e);break;default:ru.Y.Warn("The impostor type is not currently supported by the ammo plugin.")}return i}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){let r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>rL.kn||Math.abs(r.getOrigin().y()-t.y)>rL.kn||Math.abs(r.getOrigin().z()-t.z)>rL.kn||Math.abs(r.getRotation().x()-i.x)>rL.kn||Math.abs(r.getRotation().y()-i.y)>rL.kn||Math.abs(r.getRotation().z()-i.z)>rL.kn||Math.abs(r.getRotation().w()-i.w)>rL.kn){if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),0==e.mass){let t=e.physicsBody.getMotionState();t&&t.setWorldTransform(r)}else e.physicsBody.activate()}}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(!(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity()))return null;let i=new rr.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()))return null;let i=new rr.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:(ru.Y.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===sG.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):ru.Y.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(ru.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):ru.Y.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(ru.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):ru.Y.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(ru.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):ru.Y.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,s=1,n=!1){let a=e.segments;e.physicsBody.appendAnchor(Math.round((a-1)*i)+a*(a-1-Math.round((a-1)*r)),t.physicsBody,n,s)}appendHook(e,t,i,r=1,s=!1){let n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,s,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){ru.Y.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){ru.Y.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){let i=t.physicsBody;i.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){let t=e.getObjectExtents();return t.x/2}getBoxSizeToRef(e,t){let 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);let r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}_X._DISABLE_COLLISION_FLAG=4,_X._KINEMATIC_FLAG=2,_X._DISABLE_DEACTIVATION_FLAG=4,re.p.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return -1;let t=this.reflectionProbes.indexOf(e);return -1!==t&&this.reflectionProbes.splice(t,1),t},re.p.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class _Y{constructor(e,t,i,r=!0,s=!1,n=!1){let a;if(this.name=e,this._viewMatrix=rr.y3.Identity(),this._target=rr.P.Zero(),this._add=rr.P.Zero(),this._invertYAxis=!1,this.position=rr.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=[]),this._scene.reflectionProbes.push(this);let o=0;if(s){let e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new nV(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;let l=i.getEngine().useReverseDepthBuffer;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);let t=i.useRightHandedSystem?rr.y3.LookAtRHToRef:rr.y3.LookAtLHToRef,r=i.useRightHandedSystem?rr.y3.PerspectiveFovRH:rr.y3.PerspectiveFovLH;t(this.position,this._target,rr.P.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=r(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,r;this._currentSceneUBO=i.getSceneUniformBuffer(),null===(r=(t=i.getEngine())._debugPushGroup)||void 0===r||r.call(t,`reflection probe generation for ${e}`,1),a=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var e,t;i.imageProcessingConfiguration.applyByPostProcess=a,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(){let e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){let 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(let 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(){let e=rg.p4.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let i=0;i<t.reflectionProbes.length;i++){let s=t.reflectionProbes[i];if(s.name===e.name){r=s;break}}return(r=rg.p4.Parse(()=>r||new _Y(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i)).cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}}(0,r0.gn)([(0,rg.RR)()],_Y.prototype,"_attachedMesh",void 0),(0,r0.gn)([(0,rg.hd)()],_Y.prototype,"position",void 0);class _j{}_j.LoaderInjectedPhysicsEngine=void 0;let _q={},_K={},_$=(e,t,i,r)=>{if(!t.materials)return null;for(let s=0,n=t.materials.length;s<n;s++){let n=t.materials[s];if(e(n))return{parsedMaterial:n,material:sX.F.Parse(n,i,r)}}return null},_Q=(e,t,i)=>{for(let r in t)if(e.name===t[r])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},_Z=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),_J=(e,t)=>{if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){let i=t._waitingData.lods.ids,r=t.isEnabled(!1);if(t._waitingData.lods.distances){let s=t._waitingData.lods.distances;if(s.length>=i.length){let n=s.length>i.length?s[s.length-1]:0;t.setEnabled(!1);for(let r=0;r<i.length;r++){let n=i[r],a=e.getMeshById(n);null!=a&&t.addLODLevel(s[r],a)}n>0&&t.addLODLevel(n,null),!0===r&&t.setEnabled(!0)}else rZ.w1.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},_0=(e,t,i)=>{if("number"!=typeof e){let r=i.getLastEntryById(e);if(r&&null!=t){let e=r.instances[parseInt(t)];return e}return r}let r=_q[e];if(r&&null!=t){let e=r.instances[parseInt(t)];return e}return r},_1=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):_K[e],_2=(e,t,i,r,s=!1)=>{let n=new r8(e),a="importScene has failed JSON parse";try{let r,s;var o=JSON.parse(t);a="";let l=sH.loggingLevel===sH.DETAILED_LOGGING;if(void 0!==o.environmentTexture&&null!==o.environmentTexture){let t=void 0===o.isPBR||o.isPBR;if(o.environmentTextureType&&"BABYLON.HDRCubeTexture"===o.environmentTextureType){let r=o.environmentTextureSize?o.environmentTextureSize:128,s=new _B((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,r,!0,!t,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(s.rotationY=o.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof o.environmentTexture){let t=dn.Parse(o.environmentTexture,e,i);e.environmentTexture=t}else if(o.environmentTexture.endsWith(".env")){let t=new dn((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}else{let t=dn.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}if(!0===o.createDefaultSkybox){let i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,r=o.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,r)}n.environmentTexture=e.environmentTexture}if(void 0!==o.environmentIntensity&&null!==o.environmentIntensity&&(e.environmentIntensity=o.environmentIntensity),void 0!==o.lights&&null!==o.lights)for(r=0,s=o.lights.length;r<s;r++){let t=o.lights[r],i=r3.Parse(t,e);i&&(_q[t.uniqueId]=i,n.lights.push(i),i._parentContainer=n,a+=(0===r?"\n Lights:":"")+"\n "+i.toString(l))}if(void 0!==o.reflectionProbes&&null!==o.reflectionProbes)for(r=0,s=o.reflectionProbes.length;r<s;r++){let t=o.reflectionProbes[r],s=_Y.Parse(t,e,i);s&&(n.reflectionProbes.push(s),s._parentContainer=n,a+=(0===r?"\n Reflection Probes:":"")+"\n "+s.toString(l))}if(void 0!==o.animations&&null!==o.animations)for(r=0,s=o.animations.length;r<s;r++){let t=o.animations[r],i=(0,rn.q)("BABYLON.Animation");if(i){let s=i.Parse(t);e.animations.push(s),n.animations.push(s),a+=(0===r?"\n Animations:":"")+"\n "+s.toString(l)}}if(void 0!==o.materials&&null!==o.materials)for(r=0,s=o.materials.length;r<s;r++){let t=o.materials[r],s=sX.F.Parse(t,e,i);if(s){_K[t.uniqueId||t.id]=s,n.materials.push(s),s._parentContainer=n,a+=(0===r?"\n Materials:":"")+"\n "+s.toString(l);let e=s.getActiveTextures();e.forEach(e=>{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})}}if(void 0!==o.multiMaterials&&null!==o.multiMaterials)for(r=0,s=o.multiMaterials.length;r<s;r++){let t=o.multiMaterials[r],i=_D.G.ParseMultiMaterial(t,e);_K[t.uniqueId||t.id]=i,n.multiMaterials.push(i),i._parentContainer=n,a+=(0===r?"\n MultiMaterials:":"")+"\n "+i.toString(l);let s=i.getActiveTextures();s.forEach(e=>{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})}if(void 0!==o.morphTargetManagers&&null!==o.morphTargetManagers)for(let t of o.morphTargetManagers){let i=_k.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==o.skeletons&&null!==o.skeletons)for(r=0,s=o.skeletons.length;r<s;r++){let t=o.skeletons[r],i=n1.Parse(t,e);n.skeletons.push(i),i._parentContainer=n,a+=(0===r?"\n Skeletons:":"")+"\n "+i.toString(l)}let h=o.geometries;if(null!=h){let t=[],a=h.vertexData;if(null!=a)for(r=0,s=a.length;r<s;r++){let s=a[r];t.push(_M.Z.Parse(s,e,i))}t.forEach(e=>{e&&(n.geometries.push(e),e._parentContainer=n)})}if(void 0!==o.transformNodes&&null!==o.transformNodes)for(r=0,s=o.transformNodes.length;r<s;r++){let t=o.transformNodes[r],s=rK.Y.Parse(t,e,i);_q[t.uniqueId]=s,n.transformNodes.push(s),s._parentContainer=n}if(void 0!==o.meshes&&null!==o.meshes)for(r=0,s=o.meshes.length;r<s;r++){let t=o.meshes[r],s=rq.Kj.Parse(t,e,i);if(_q[t.uniqueId]=s,n.meshes.push(s),s._parentContainer=n,s.hasInstances)for(let e of s.instances)n.meshes.push(e),e._parentContainer=n;a+=(0===r?"\n Meshes:":"")+"\n "+s.toString(l)}if(void 0!==o.cameras&&null!==o.cameras)for(r=0,s=o.cameras.length;r<s;r++){let t=o.cameras[r],i=r4.V.Parse(t,e);_q[t.uniqueId]=i,n.cameras.push(i),i._parentContainer=n,a+=(0===r?"\n Cameras:":"")+"\n "+i.toString(l)}if(void 0!==o.postProcesses&&null!==o.postProcesses)for(r=0,s=o.postProcesses.length;r<s;r++){let t=o.postProcesses[r],s=np.Parse(t,e,i);s&&(n.postProcesses.push(s),s._parentContainer=n,a+=(0===r?"\nPostprocesses:":"")+"\n "+s.toString())}if(void 0!==o.animationGroups&&null!==o.animationGroups)for(r=0,s=o.animationGroups.length;r<s;r++){let t=o.animationGroups[r],i=rj.Parse(t,e);n.animationGroups.push(i),i._parentContainer=n,a+=(0===r?"\n AnimationGroups:":"")+"\n "+i.toString(l)}for(r=0,s=e.cameras.length;r<s;r++){let t=e.cameras[r];null!==t._waitingParentId&&(t.parent=_0(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,s=e.lights.length;r<s;r++){let t=e.lights[r];t&&null!==t._waitingParentId&&(t.parent=_0(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,s=e.transformNodes.length;r<s;r++){let t=e.transformNodes[r];null!==t._waitingParentId&&(t.parent=_0(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null)}for(r=0,s=e.meshes.length;r<s;r++){let t=e.meshes[r];null!==t._waitingParentId&&(t.parent=_0(t._waitingParentId,t._waitingParentInstanceIndex,e),t._waitingParentId=null,t._waitingParentInstanceIndex=null),t._waitingData.lods&&_J(e,t)}for(e.multiMaterials.forEach(t=>{t._waitingSubMaterialsUniqueIds.forEach(i=>{t.subMaterials.push(_1(i,e))}),t._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(t=>{null!==t._waitingMaterialId&&(t.material=_1(t._waitingMaterialId,e),t._waitingMaterialId=null)}),r=0,s=e.skeletons.length;r<s;r++){let t=e.skeletons[r];t._hasWaitingData&&(null!=t.bones&&t.bones.forEach(t=>{if(t._waitingTransformNodeId){let i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}}),t._hasWaitingData=null)}for(r=0,s=e.meshes.length;r<s;r++){let t=e.meshes[r];t._waitingData.freezeWorldMatrix?(t.freezeWorldMatrix(),t._waitingData.freezeWorldMatrix=null):t.computeWorldMatrix(!0)}for(r=0,s=e.lights.length;r<s;r++){let t=e.lights[r];if(t._excludedMeshesIds.length>0){for(let i=0;i<t._excludedMeshesIds.length;i++){let r=e.getMeshById(t._excludedMeshesIds[i]);r&&t.excludedMeshes.push(r)}t._excludedMeshesIds=[]}if(t._includedOnlyMeshesIds.length>0){for(let i=0;i<t._includedOnlyMeshesIds.length;i++){let r=e.getMeshById(t._includedOnlyMeshesIds[i]);r&&t.includedOnlyMeshes.push(r)}t._includedOnlyMeshesIds=[]}}for(e.geometries.forEach(e=>{e._loadedUniqueId=""}),re.p.Parse(o,e,n,i),r=0,s=e.meshes.length;r<s;r++){let t=e.meshes[r];t._waitingData.actions&&(rf.Parse(t._waitingData.actions,t,e),t._waitingData.actions=null)}void 0!==o.actions&&null!==o.actions&&rf.Parse(o.actions,null,e)}catch(t){let e=_Z("loadAssets",o?o.producer:"Unknown")+a;if(r)r(e,t);else throw ru.Y.Log(e),t}finally{_q={},_K={},s||n.removeAllFromScene(),null!==a&&sH.loggingLevel!==sH.NO_LOGGING&&ru.Y.Log(_Z("loadAssets",o?o.producer:"Unknown")+(sH.loggingLevel!==sH.MINIMAL_LOGGING?a:""))}return n};sH.RegisterPlugin({name:"babylon.js",extensions:".babylon",canDirectLoad:e=>-1!==e.indexOf("babylon"),importMesh:(e,t,i,r,s,n,a,o)=>{var l;let h="importMesh has failed JSON parse";try{var u=JSON.parse(i);h="";let o=sH.loggingLevel===sH.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;let c=[],d=new Map,p=[];if(void 0!==u.transformNodes&&null!==u.transformNodes)for(let e=0,i=u.transformNodes.length;e<i;e++){let i=u.transformNodes[e],s=rK.Y.Parse(i,t,r);p.push(s),d.set(s._waitingParsedUniqueId,s),s._waitingParsedUniqueId=null}if(void 0!==u.meshes&&null!==u.meshes){let i;let n=[],_=[],f=[],m=[];for(let i=0,l=u.meshes.length;i<l;i++){let l=u.meshes[i];if(null===e||_Q(l,e,c)){if(null!==e&&delete e[e.indexOf(l.name)],void 0!==l.geometryId&&null!==l.geometryId&&void 0!==u.geometries&&null!==u.geometries){let e=!1;["boxes","spheres","cylinders","toruses","grounds","planes","torusKnots","vertexData"].forEach(i=>{!0!==e&&u.geometries[i]&&Array.isArray(u.geometries[i])&&u.geometries[i].forEach(s=>{s.id===l.geometryId&&("vertexData"===i&&_M.Z.Parse(s,t,r),e=!0)})}),!1===e&&ru.Y.Warn("Geometry not found for mesh "+l.id)}if(l.materialUniqueId||l.materialId){let e=l.materialUniqueId?f:_,i=-1!==e.indexOf(l.materialUniqueId||l.materialId);if(!1===i&&void 0!==u.multiMaterials&&null!==u.multiMaterials){let s=(i,s)=>{e.push(i);let n=_$(s,u,t,r);n&&n.material&&(_K[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,h+="\n Material "+n.material.toString(o))};for(let r=0,n=u.multiMaterials.length;r<n;r++){let n=u.multiMaterials[r];if(l.materialUniqueId&&n.uniqueId===l.materialUniqueId||n.id===l.materialId){n.materialsUniqueIds?n.materialsUniqueIds.forEach(e=>s(e,t=>t.uniqueId===e)):n.materials.forEach(e=>s(e,t=>t.id===e)),e.push(n.uniqueId||n.id);let r=_D.G.ParseMultiMaterial(n,t);_K[n.uniqueId||n.id]=r,r&&(i=!0,h+="\n Multi-Material "+r.toString(o));break}}}if(!1===i){e.push(l.materialUniqueId||l.materialId);let i=_$(e=>l.materialUniqueId&&e.uniqueId===l.materialUniqueId||e.id===l.materialId,u,t,r);i&&i.material?(_K[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,h+="\n Material "+i.material.toString(o)):ru.Y.Warn("Material not found for mesh "+l.id)}}if(null!==l.skeletonId&&void 0!==l.skeletonId&&-1!==u.skeletonId&&void 0!==u.skeletons&&null!==u.skeletons){let e=n.indexOf(l.skeletonId)>-1;if(!e)for(let e=0,i=u.skeletons.length;e<i;e++){let i=u.skeletons[e];if(i.id===l.skeletonId){let e=n1.Parse(i,t);a.push(e),n.push(i.id),h+="\n Skeleton "+e.toString(o)}}}if(l.morphTargetManagerId>-1&&void 0!==u.morphTargetManagers&&null!==u.morphTargetManagers){let e=m.indexOf(l.morphTargetManagerId)>-1;if(!e)for(let e=0,i=u.morphTargetManagers.length;e<i;e++){let i=u.morphTargetManagers[e];if(i.id===l.morphTargetManagerId){let e=_k.Parse(i,t);m.push(e.uniqueId),h+="\nMorph target "+e.toString()}}}let i=rq.Kj.Parse(l,t,r);s.push(i),d.set(i._waitingParsedUniqueId,i),i._waitingParsedUniqueId=null,h+="\n Mesh "+i.toString(o)}}t.multiMaterials.forEach(e=>{e._waitingSubMaterialsUniqueIds.forEach(i=>{e.subMaterials.push(_1(i,t))}),e._waitingSubMaterialsUniqueIds=[]}),t.meshes.forEach(e=>{null!==e._waitingMaterialId&&(e.material=_1(e._waitingMaterialId,t),e._waitingMaterialId=null)});for(let e=0,i=t.transformNodes.length;e<i;e++){let i=t.transformNodes[e];if(null!==i._waitingParentId){let e=d.get(parseInt(i._waitingParentId))||null;null===e&&(e=t.getLastEntryById(i._waitingParentId));let r=e;i._waitingParentInstanceIndex&&(r=e.instances[parseInt(i._waitingParentInstanceIndex)],i._waitingParentInstanceIndex=null),i.parent=r,i._waitingParentId=null}}for(let e=0,r=t.meshes.length;e<r;e++){if((i=t.meshes[e])._waitingParentId){let e=d.get(parseInt(i._waitingParentId))||null;null===e&&(e=t.getLastEntryById(i._waitingParentId));let r=e;if(i._waitingParentInstanceIndex&&(r=e.instances[parseInt(i._waitingParentInstanceIndex)],i._waitingParentInstanceIndex=null),i.parent=r,(null===(l=i.parent)||void 0===l?void 0:l.getClassName())==="TransformNode"){let e=p.indexOf(i.parent);e>-1&&p.splice(e,1)}i._waitingParentId=null}i._waitingData.lods&&_J(t,i)}for(let e of p)e.dispose();for(let e=0,i=t.skeletons.length;e<i;e++){let i=t.skeletons[e];i._hasWaitingData&&(null!=i.bones&&i.bones.forEach(e=>{if(e._waitingTransformNodeId){let i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}}),i._hasWaitingData=null)}for(let e=0,r=t.meshes.length;e<r;e++)(i=t.meshes[e])._waitingData.freezeWorldMatrix?(i.freezeWorldMatrix(),i._waitingData.freezeWorldMatrix=null):i.computeWorldMatrix(!0)}if(void 0!==u.particleSystems&&null!==u.particleSystems){let e=re.p.GetIndividualParser(ss.l.NAME_PARTICLESYSTEM);if(e)for(let i=0,s=u.particleSystems.length;i<s;i++){let s=u.particleSystems[i];-1!==c.indexOf(s.emitterId)&&n.push(e(s,t,r))}}return t.geometries.forEach(e=>{e._loadedUniqueId=""}),!0}catch(t){let e=_Z("importMesh",u?u.producer:"Unknown")+h;if(o)o(e,t);else throw ru.Y.Log(e),t}finally{null!==h&&sH.loggingLevel!==sH.NO_LOGGING&&ru.Y.Log(_Z("importMesh",u?u.producer:"Unknown")+(sH.loggingLevel!==sH.MINIMAL_LOGGING?h:"")),_K={}}return!1},load:(e,t,i,r)=>{let s="importScene has failed JSON parse";try{var n=JSON.parse(t);if(s="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!sH.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=rs.HE.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=rs.Wo.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=rr.P.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),n.fogMode&&0!==n.fogMode)switch(e.fogMode=n.fogMode,e.fogColor=rs.Wo.FromArray(n.fogColor),e.fogStart=n.fogStart,e.fogEnd=n.fogEnd,e.fogDensity=n.fogDensity,s+=" Fog mode for scene: ",e.fogMode){case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===_W.name?t=new _W(void 0,void 0,_j.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===_H.name?t=new _H(void 0,_j.LoaderInjectedPhysicsEngine):("ammo"===n.physicsEngine||n.physicsEngine===_X.name)&&(t=new _X(void 0,_j.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";let i=n.physicsGravity?rr.P.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled);let a=_2(e,t,i,r,!0);if(!a)return!1;return n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0}catch(t){let e=_Z("importScene",n?n.producer:"Unknown")+s;if(r)r(e,t);else throw ru.Y.Log(e),t}finally{null!==s&&sH.loggingLevel!==sH.NO_LOGGING&&ru.Y.Log(_Z("importScene",n?n.producer:"Unknown")+(sH.loggingLevel!==sH.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,r)=>{let s=_2(e,t,i,r);return s}}),i(2117);class _3{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,r7.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||rs.Wo.White(),this.rightColor=e.rightColor||rs.Wo.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){let e=new _3;return r_.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 _3({isEnabled:e.isEnabled,leftColor:rs.Wo.FromArray(e.leftColor),rightColor:rs.Wo.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}rg.p4._FresnelParametersParser=_3.Parse;class _4 extends ph{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 rs.Wo(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsLightsDirty")],_4.prototype,"maxSimultaneousLights",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsLightsDirty")],_4.prototype,"disableLighting",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],_4.prototype,"environmentTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],_4.prototype,"invertNormalMapX",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],_4.prototype,"invertNormalMapY",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],_4.prototype,"normalTexture",void 0),(0,r0.gn)([(0,rg.n9)("emissive"),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],_4.prototype,"emissiveColor",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],_4.prototype,"emissiveTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],_4.prototype,"occlusionStrength",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],_4.prototype,"occlusionTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],_4.prototype,"alphaCutOff",void 0),(0,r0.gn)([(0,rg.qC)()],_4.prototype,"doubleSided",null),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty",null)],_4.prototype,"lightmapTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],_4.prototype,"useLightmapAsShadowmap",void 0);class _5 extends _4{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){let t=rg.p4.Clone(()=>new _5(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(){let e=rg.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){let r=rg.p4.Parse(()=>new _5(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}(0,r0.gn)([(0,rg.n9)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],_5.prototype,"baseColor",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],_5.prototype,"baseTexture",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],_5.prototype,"metallic",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],_5.prototype,"roughness",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],_5.prototype,"metallicRoughnessTexture",void 0),(0,rn.H)("BABYLON.PBRMetallicRoughnessMaterial",_5);class _6 extends _4{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){let t=rg.p4.Clone(()=>new _6(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(){let e=rg.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){let r=rg.p4.Parse(()=>new _6(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}(0,r0.gn)([(0,rg.n9)("diffuse"),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],_6.prototype,"diffuseColor",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],_6.prototype,"diffuseTexture",void 0),(0,r0.gn)([(0,rg.n9)("specular"),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],_6.prototype,"specularColor",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_microSurface")],_6.prototype,"glossiness",void 0),(0,r0.gn)([(0,rg.oU)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],_6.prototype,"specularGlossinessTexture",void 0),(0,rn.H)("BABYLON.PBRSpecularGlossinessMaterial",_6);class _8 extends su{constructor(e,t,i=null){if(super(t),!e)return;if(this._textureMatrix=rr.y3.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{let e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){let e;let t=this._getEngine();e=t._features.support3DTextures?t.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):t.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=e,this._texture.isReady=!1,this.isCube=!1,this.is3D=t._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;let i=i=>{let r;if("string"!=typeof i)return;let s=null,n=null,a=i.split("\n"),o=0,l=0,h=0,u=0,c=0;for(let e=0;e<a.length;e++){if(r=a[e],!_8._NoneEmptyLineRegex.test(r)||0===r.indexOf("#"))continue;let t=r.split(" ");if(0===o){o=t.length,s=new Uint8Array(o*o*o*4),n=new Float32Array(o*o*o*4);continue}if(0!=o){let e=Math.max(parseInt(t[0]),0),i=Math.max(parseInt(t[1]),0),r=Math.max(parseInt(t[2]),0);c=Math.max(e,c),c=Math.max(i,c),c=Math.max(r,c);let s=(l+u*o+h*o*o)*4;n&&(n[s+0]=e,n[s+1]=i,n[s+2]=r),++h%o==0&&(h=0,++u%o==0&&(l++,u=0))}}if(n&&s)for(let e=0;e<n.length;e++)if(e>0&&(e+1)%4==0)s[e]=255;else{let t=n[e];s[e]=t/c*255}e.is3D?(e.updateSize(o,o,o),t.updateRawTexture3D(e,s,5,!1)):(e.updateSize(o*o,o),t.updateRawTexture(e,s,5,!1)),e.isReady=!0,this._triggerOnLoad()},r=this.getScene();return r?r._loadFile(this.url,i):t._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){let e=new _8(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 _8(e.name,t)).name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}_8._NoneEmptyLineRegex=/\S+/,(0,rn.H)("BABYLON.ColorGradingTexture",_8);class _7 extends su{constructor(e,t,i,r=!1,s=!0,n=null,a=null,o=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw Error("Image url is not set");this._coordinatesMode=sv.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=o,this._noMipmap=r,this.gammaSpace=s,this._onLoad=n,this._onError=a,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?rZ.w1.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(this._loadTexture.bind(this),this._onError)}_loadImage(e,t){let i=document.createElement("canvas");(0,sl.r6)(this.url,t=>{this._width=t.width,this._height=t.height,i.width=this._width,i.height=this._height;let r=i.getContext("2d");r.drawImage(t,0,0);let s=r.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(){let e=this.getScene();e&&(this._texture=e.getEngine().createRawCubeTextureFromUrl(this.url,e,this._size,4,e.getEngine().getCaps().textureFloat?1:7,this._noMipmap,()=>{let e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=_O.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){let r=t[_7._FacesMapping[e]];i.push(r)}return i},null,this._onLoad,this._onError))}_getFloat32ArrayFromArrayBuffer(e){let t=new DataView(e),i=new Float32Array(3*e.byteLength/4),r=0;for(let s=0;s<e.byteLength;s++)(s+1)%4!=0&&(i[r++]=t.getUint8(s)/255);return i}getClassName(){return"EquiRectangularCubeTexture"}clone(){let e=this.getScene();if(!e)return this;let t=new _7(this.url,e,this._size,this._noMipmap,this.gammaSpace);return t.level=this.level,t.wrapU=this.wrapU,t.wrapV=this.wrapV,t.coordinatesIndex=this.coordinatesIndex,t.coordinatesMode=this.coordinatesMode,t}}_7._FacesMapping=["right","left","up","down","front","back"];class _9 extends su{constructor(e,t,i){var r,s;if(super(i.scene||i.engine),this.onLoadObservable=new ri.y$,!t||!i.engine&&!i.scene)return;i=Object.assign(Object.assign({},_9._DefaultOptions),i),this._generateMipMaps=i.generateMipMaps,this._samplingMode=i.samplingMode,this._textureMatrix=rr.y3.Identity(),this._format=i.format,this.name=e,this.element=t,this._isVideo=!!t.getVideoPlaybackQuality,this._externalTexture=this._isVideo&&null!==(s=null===(r=this._engine)||void 0===r?void 0:r.createExternalTexture(t))&&void 0!==s?s:null,this.anisotropicFilteringLevel=1,this._createInternalTexture()}_createInternalTexture(){let e=0,t=0;this._isVideo?(e=this.element.videoWidth,t=this.element.videoHeight):(e=this.element.width,t=this.element.height);let i=this._getEngine();i&&(this._texture=i.createDynamicTexture(e,t,this._generateMipMaps,this._samplingMode),this._texture.format=this._format),this.update()}getTextureMatrix(){return this._textureMatrix}update(e=null){let t=this._getEngine();if(null==this._texture||null==t)return;let i=this.isReady();if(this._isVideo){let i=this.element;if(i.readyState<i.HAVE_CURRENT_DATA)return;t.updateVideoTexture(this._texture,this._externalTexture?this._externalTexture:i,null===e||e)}else{let i=this.element;t.updateDynamicTexture(this._texture,i,null===e||e,!1,this._format)}!i&&this.isReady()&&this.onLoadObservable.notifyObservers(this)}dispose(){this.onLoadObservable.clear(),super.dispose()}}function fe(e){let t=0,i={id_length:e[t++],colormap_type:e[t++],image_type:e[t++],colormap_index:e[t++]|e[t++]<<8,colormap_length:e[t++]|e[t++]<<8,colormap_size:e[t++],origin:[e[t++]|e[t++]<<8,e[t++]|e[t++]<<8],width:e[t++]|e[t++]<<8,height:e[t++]|e[t++]<<8,pixel_size:e[t++],flags:e[t++]};return i}function ft(e,t){let i,r,s,n,a,o,l,h;if(t.length<19){ru.Y.Error("Unable to load TGA file - Not enough data to contain header");return}let u=18,c=fe(t);if(c.id_length+u>t.length){ru.Y.Error("Unable to load TGA file - Not enough data");return}u+=c.id_length;let d=!1,p=!1,_=!1;switch(c.image_type){case 9:d=!0;case 1:p=!0;break;case 10:d=!0;case 2:break;case 11:d=!0;case 3:_=!0}let f=c.pixel_size>>3,m=c.width*c.height*f;if(p&&(r=t.subarray(u,u+=c.colormap_length*(c.colormap_size>>3))),d){let e,r,s;i=new Uint8Array(m);let n=0,a=new Uint8Array(f);for(;u<m&&n<m;)if(r=(127&(e=t[u++]))+1,128&e){for(s=0;s<f;++s)a[s]=t[u++];for(s=0;s<r;++s)i.set(a,n+s*f);n+=f*r}else{for(r*=f,s=0;s<r;++s)i[n+s]=t[u++];n+=r}}else i=t.subarray(u,u+=p?c.width*c.height:m);switch((48&c.flags)>>4){default:case 2:s=0,a=1,h=c.width,n=0,o=1,l=c.height;break;case 0:s=0,a=1,h=c.width,n=c.height-1,o=-1,l=-1;break;case 3:s=c.width-1,a=-1,h=-1,n=0,o=1,l=c.height;break;case 1:s=c.width-1,a=-1,h=-1,n=c.height-1,o=-1,l=-1}let g="_getImageData"+(_?"Grey":"")+c.pixel_size+"bits",v=fi[g](c,r,i,n,o,l,s,a,h),T=e.getEngine();T._uploadDataToTextureDirectly(e,v)}_9._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};let fi={GetTGAHeader:fe,UploadContent:ft,_getImageData8bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d++)c=i[d],f[(p+h*_)*4+3]=255,f[(p+h*_)*4+2]=t[3*c+0],f[(p+h*_)*4+1]=t[3*c+1],f[(p+h*_)*4+0]=t[3*c+2];return f},_getImageData16bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d+=2){c=i[d+0]+(i[d+1]<<8);let e=((31744&c)>>10)*255/31|0,t=((992&c)>>5)*255/31|0,r=(31&c)*255/31|0;f[(p+h*_)*4+0]=e,f[(p+h*_)*4+1]=t,f[(p+h*_)*4+2]=r,f[(p+h*_)*4+3]=32768&c?0:255}return f},_getImageData24bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=3)_[(d+h*p)*4+3]=255,_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+1]=i[c+1],_[(d+h*p)*4+0]=i[c+2];return _},_getImageData32bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=4)_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+1]=i[c+1],_[(d+h*p)*4+0]=i[c+2],_[(d+h*p)*4+3]=i[c+3];return _},_getImageDataGrey8bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d++)c=i[d],f[(p+h*_)*4+0]=c,f[(p+h*_)*4+1]=c,f[(p+h*_)*4+2]=c,f[(p+h*_)*4+3]=255;return f},_getImageDataGrey16bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=2)_[(d+h*p)*4+0]=i[c+0],_[(d+h*p)*4+1]=i[c+0],_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+3]=i[c+1];return _}};r7.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){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=fe(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{ft(t,r)})}}),r7.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){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=_N.RGBE_ReadHeader(r),n=_N.RGBE_ReadPixels(r,s),a=s.width*s.height,o=new Float32Array(4*a);for(let e=0;e<a;e+=1)o[4*e]=n[3*e],o[4*e+1]=n[3*e+1],o[4*e+2]=n[3*e+2],o[4*e+3]=1;i(s.width,s.height,t.generateMipMaps,!1,()=>{let e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,o)})}}),(eM=ib||(ib={}))[eM.cTFETC1=0]="cTFETC1",eM[eM.cTFETC2=1]="cTFETC2",eM[eM.cTFBC1=2]="cTFBC1",eM[eM.cTFBC3=3]="cTFBC3",eM[eM.cTFBC4=4]="cTFBC4",eM[eM.cTFBC5=5]="cTFBC5",eM[eM.cTFBC7=6]="cTFBC7",eM[eM.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",eM[eM.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",eM[eM.cTFASTC_4x4=10]="cTFASTC_4x4",eM[eM.cTFATC_RGB=11]="cTFATC_RGB",eM[eM.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",eM[eM.cTFRGBA32=13]="cTFRGBA32",eM[eM.cTFRGB565=14]="cTFRGB565",eM[eM.cTFBGR565=15]="cTFBGR565",eM[eM.cTFRGBA4444=16]="cTFRGBA4444",eM[eM.cTFFXT1_RGB=17]="cTFFXT1_RGB",eM[eM.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",eM[eM.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",eM[eM.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",eM[eM.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11";let fr={JSModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.js",WasmModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.wasm"},fs=null,fn=null,fa=0,fo=()=>(fs||(fs=new Promise((e,t)=>{fn?e(fn):rZ.w1.LoadFileAsync(fr.WasmModuleURL).then(i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");let r=URL.createObjectURL(new Blob([`(${fd})()`],{type:"application/javascript"}));fn=new Worker(r);let s=i=>{"init"===i.data.action?(fn.removeEventListener("message",s),e(fn)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};fn.addEventListener("message",s),fn.postMessage({action:"init",url:fr.JSModuleURL,wasmBinary:i})}).catch(t)})),fs),fl=(e,t)=>{let i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise((e,r)=>{fo().then(()=>{let s=fa++,n=t=>{"transcode"===t.data.action&&t.data.id===s&&(fn.removeEventListener("message",n),t.data.success?e(t.data):r("Transcode is not supported on this device"))};fn.addEventListener("message",n);let a=new Uint8Array(i.byteLength);a.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),fn.postMessage({action:"transcode",id:s,imageData:a,config:t,ignoreSupportedFormats:!1},[a.buffer])},e=>{r(e)})})},fh=(e,t)=>{var i,r;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(r=t._gl)||void 0===r?void 0:r.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},fu=(e,t)=>{let i=e.getEngine();for(let r=0;r<t.fileInfo.images.length;r++){let s=t.fileInfo.images[r].levels[0];if(e._invertVScale=e.invertY,-1===t.format||t.format===ib.cTFRGB565){if(e.type=10,e.format=4,i._features.basisNeedsPOT&&(rm.R.Log2(s.width)%1!=0||rm.R.Log2(s.height)%1!=0)){let t=new sT.l(i,sT.S.Temp);e._invertVScale=e.invertY,t.type=10,t.format=4,t.width=s.width+3&-4,t.height=s.height+3&-4,fh(t,i),i._uploadDataToTextureDirectly(t,new Uint16Array(s.transcodedPixels.buffer),r,0,4,!0),i._rescaleTexture(t,e,i.scenes[0],i._getInternalFormat(4),()=>{i._releaseTexture(t),fh(e,i)})}else e._invertVScale=!e.invertY,e.width=s.width+3&-4,e.height=s.height+3&-4,e.samplingMode=2,fh(e,i),i._uploadDataToTextureDirectly(e,new Uint16Array(s.transcodedPixels.buffer),r,0,4,!0)}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[r].levels.length>1;let n=fc.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,fh(e,i),t.fileInfo.images[r].levels.forEach((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,r,s)}),i._features.basisNeedsPOT&&(rm.R.Log2(e.width)%1!=0||rm.R.Log2(e.height)%1!=0)&&(rZ.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=sv.CLAMP_ADDRESSMODE,e._cachedWrapV=sv.CLAMP_ADDRESSMODE)}}},fc={JSModuleURL:fr.JSModuleURL,WasmModuleURL:fr.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case ib.cTFETC1:i=36196;break;case ib.cTFBC1:i=33776;break;case ib.cTFBC4:i=33779;break;case ib.cTFASTC_4x4:i=37808;break;case ib.cTFETC2:i=37496;break;case ib.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync:fl,LoadTextureFromTranscodeResult:fu};function fd(){let e={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC4:4,cTFBC5:5,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFBGR565:15,cTFRGBA4444:16,cTFFXT1_RGB:17,cTFPVRTC2_4_RGB:18,cTFPVRTC2_4_RGBA:19,cTFETC2_EAC_R11:20,cTFETC2_EAC_RG11:21},t=null;onmessage=i=>{if("init"===i.data.action){if(!t){try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}t=BASIS({wasmBinary:i.data.wasmBinary})}null!==t&&t.then(e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})})}else if("transcode"===i.data.action){var r;let t;let s=i.data.config,n=i.data.imageData,a=new BASIS.BasisFile(n),o=function(e){let t=e.getHasAlpha(),i=e.getNumImages(),r=[];for(let t=0;t<i;t++){let i={levels:[]},s=e.getNumLevels(t);for(let r=0;r<s;r++){let s={width:e.getImageWidth(t,r),height:e.getImageHeight(t,r)};i.levels.push(s)}r.push(i)}return{hasAlpha:t,images:r}}(a),l=i.data.ignoreSupportedFormats?null:(r=i.data.config,t=null,r.supportedCompressionFormats&&(t=r.supportedCompressionFormats.astc?e.cTFASTC_4x4:r.supportedCompressionFormats.bc7?e.cTFBC7:r.supportedCompressionFormats.s3tc?o.hasAlpha?e.cTFBC3:e.cTFBC1:r.supportedCompressionFormats.pvrtc?o.hasAlpha?e.cTFPVRTC1_4_RGBA:e.cTFPVRTC1_4_RGB:r.supportedCompressionFormats.etc2?e.cTFETC2:r.supportedCompressionFormats.etc1?e.cTFETC1:e.cTFRGB565),t),h=!1;null===l&&(h=!0,l=o.hasAlpha?e.cTFBC3:e.cTFBC1);let u=!0;a.startTranscoding()||(u=!1);let c=[];for(let e=0;e<o.images.length&&u;e++){let t=o.images[e];if(void 0===s.loadSingleImage||s.loadSingleImage===e){let i=t.levels.length;!1===s.loadMipmapLevels&&(i=1);for(let r=0;r<i;r++){let i=t.levels[r],s=function(e,t,i,r,s){let n=e.getImageTranscodedSizeInBytes(t,i,r),a=new Uint8Array(n);if(!e.transcodeImage(a,t,i,r,1,0))return null;if(s){let r=e.getImageWidth(t,i)+3&-4,s=e.getImageHeight(t,i)+3&-4;a=function(e,t,i,r){let s=new Uint16Array(4),n=new Uint16Array(i*r),a=i/4,o=r/4;for(let t=0;t<o;t++)for(let r=0;r<a;r++){let o=0+8*(t*a+r);s[0]=e[o]|e[o+1]<<8,s[1]=e[o+2]|e[o+3]<<8,s[2]=(2*(31&s[0])+1*(31&s[1]))/3|(2*(2016&s[0])+1*(2016&s[1]))/3&2016|(2*(63488&s[0])+1*(63488&s[1]))/3&63488,s[3]=(2*(31&s[1])+1*(31&s[0]))/3|(2*(2016&s[1])+1*(2016&s[0]))/3&2016|(2*(63488&s[1])+1*(63488&s[0]))/3&63488;for(let a=0;a<4;a++){let l=e[o+4+a],h=(4*t+a)*i+4*r;n[h++]=s[3&l],n[h++]=s[l>>2&3],n[h++]=s[l>>4&3],n[h++]=s[l>>6&3]}}return n}(a,0,r,s)}return a}(a,e,r,l,h);if(!s){u=!1;break}i.transcodedPixels=s,c.push(i.transcodedPixels.buffer)}}}a.close(),a.delete(),h&&(l=-1),u?postMessage({action:"transcode",success:u,id:i.data.id,fileInfo:o,format:l},c):postMessage({action:"transcode",success:u,id:i.data.id})}}}Object.defineProperty(fc,"JSModuleURL",{get:function(){return fr.JSModuleURL},set:function(e){fr.JSModuleURL=e}}),Object.defineProperty(fc,"WasmModuleURL",{get:function(){return fr.WasmModuleURL},set:function(e){fr.WasmModuleURL=e}}),r7.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let n=t.getEngine().getCaps(),a={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};fl(e,a).then(e=>{let i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;fu(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(e=>{rZ.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){let r=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};fl(e,s).then(e=>{let r=e.fileInfo.images[0].levels[0],s=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(r.width,r.height,s,-1!==e.format,()=>{fu(t,e)})}).catch(e=>{rZ.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),rZ.w1.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,()=>{},!0)})}});class fp extends nV{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;t<this._textures.length;t++)this._textures[t].wrapU=e}set wrapV(e){if(this._textures)for(let t=0;t<this._textures.length;t++)this._textures[t].wrapV=e}constructor(e,t,i,r,s,n){let a=!!s&&!!s.generateMipMaps&&s.generateMipMaps,o=!!s&&!!s.generateDepthTexture&&s.generateDepthTexture,l=s&&s.depthTextureFormat?s.depthTextureFormat:15,h=!s||void 0===s.doNotChangeAspectRatio||s.doNotChangeAspectRatio,u=!!s&&!!s.drawOnlyOnFirstAttachmentByDefault&&s.drawOnlyOnFirstAttachmentByDefault;if(super(e,t,r,a,h,void 0,void 0,void 0,void 0,void 0,void 0,void 0,!0),!this.isSupported){this.dispose();return}this._textureNames=n;let c=[],d=[],p=[],_=[],f=[],m=[],g=[],v=[];this._initTypes(i,c,d,p,_,f,m,g,v,s);let T=!s||void 0===s.generateDepthBuffer||s.generateDepthBuffer,x=!!s&&void 0!==s.generateStencilBuffer&&s.generateStencilBuffer;this._multiRenderTargetOptions={samplingModes:d,generateMipMaps:a,generateDepthBuffer:T,generateStencilBuffer:x,generateDepthTexture:o,depthTextureFormat:l,types:c,textureCount:i,useSRGBBuffers:p,formats:_,targetTypes:f,faceIndex:m,layerIndex:g,layerCounts:v},this._count=i,this._drawOnlyOnFirstAttachmentByDefault=u,i>0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,r,s,n,a,o,l,h){for(let u=0;u<e;u++)h&&h.types&&void 0!==h.types[u]?t.push(h.types[u]):t.push(h&&h.defaultType?h.defaultType:0),h&&h.samplingModes&&void 0!==h.samplingModes[u]?i.push(h.samplingModes[u]):i.push(sv.BILINEAR_SAMPLINGMODE),h&&h.useSRGBBuffers&&void 0!==h.useSRGBBuffers[u]?r.push(h.useSRGBBuffers[u]):r.push(!1),h&&h.formats&&void 0!==h.formats[u]?s.push(h.formats[u]):s.push(5),h&&h.targetTypes&&void 0!==h.targetTypes[u]?n.push(h.targetTypes[u]):n.push(3553),h&&h.faceIndex&&void 0!==h.faceIndex[u]?a.push(h.faceIndex[u]):a.push(0),h&&h.layerIndex&&void 0!==h.layerIndex[u]?o.push(h.layerIndex[u]):o.push(0),h&&h.layerCounts&&void 0!==h.layerCounts[u]?l.push(h.layerCounts[u]):l.push(1)}_createInternaTextureIndexMapping(){let e={},t=[];if(!this._renderTarget)return t;let i=this._renderTarget.textures;for(let r=0;r<i.length;r++){let s=i[r];if(!s)continue;let n=e[s.uniqueId];void 0!==n?t[r]=n:e[s.uniqueId]=r}return t}_rebuild(e=!1,t){if(this._count<1)return;let i=this._createInternaTextureIndexMapping();this.releaseInternalTextures(),this._createInternalTextures(),e&&(this._releaseTextures(),this._createTextures(t));let r=this._renderTarget.textures;for(let e=0;e<r.length;e++){let t=this._textures[e];void 0!==i[e]&&this._renderTarget.setTexture(r[i[e]],e),t._texture=r[e],t._texture&&(t._noMipmap=!t._texture.useMipMaps,t._useSRGBBuffer=t._texture._useSRGBBuffer)}1!==this.samples&&this._renderTarget.setSamples(this.samples,!this._drawOnlyOnFirstAttachmentByDefault,!0)}_createInternalTextures(){this._renderTarget=this._getEngine().createMultipleRenderTarget(this._size,this._multiRenderTargetOptions,!this._drawOnlyOnFirstAttachmentByDefault),this._texture=this._renderTarget.texture}_releaseTextures(){if(this._textures)for(let e=0;e<this._textures.length;e++)this._textures[e]._texture=null,this._textures[e].dispose()}_createTextures(e){let t=this._renderTarget.textures;this._textures=[];for(let i=0;i<t.length;i++){let r=new sv(null,this.getScene());(null==e?void 0:e[i])&&(r.name=e[i]),r._texture=t[i],r._texture&&(r._noMipmap=!r._texture.useMipMaps,r._useSRGBBuffer=r._texture._useSRGBBuffer),this._textures.push(r)}}setInternalTexture(e,t,i=!0){var r,s;if(this.renderTarget&&(0===t&&(this._texture=e),this.renderTarget.setTexture(e,t,i),this.textures[t]||(this.textures[t]=new sv(null,this.getScene()),this.textures[t].name=null!==(s=null===(r=this._textureNames)||void 0===r?void 0:r[t])&&void 0!==s?s:this.textures[t].name),this.textures[t]._texture=e,this.textures[t]._noMipmap=!e.useMipMaps,this.textures[t]._useSRGBBuffer=e._useSRGBBuffer,this._count=this.renderTarget.textures?this.renderTarget.textures.length:0,this._multiRenderTargetOptions.types&&(this._multiRenderTargetOptions.types[t]=e.type),this._multiRenderTargetOptions.samplingModes&&(this._multiRenderTargetOptions.samplingModes[t]=e.samplingMode),this._multiRenderTargetOptions.useSRGBBuffers&&(this._multiRenderTargetOptions.useSRGBBuffers[t]=e._useSRGBBuffer),this._multiRenderTargetOptions.targetTypes&&-1!==this._multiRenderTargetOptions.targetTypes[t])){let i=0;i=e.is2DArray?35866:e.isCube?34067:e.is3D?32879:3553,this._multiRenderTargetOptions.targetTypes[t]=i}}setLayerAndFaceIndex(e,t=-1,i=-1){this.textures[e]&&this.renderTarget&&(this._multiRenderTargetOptions.layerIndex&&(this._multiRenderTargetOptions.layerIndex[e]=t),this._multiRenderTargetOptions.faceIndex&&(this._multiRenderTargetOptions.faceIndex[e]=i),this.renderTarget.setLayerAndFaceIndex(e,t,i))}setLayerAndFaceIndices(e,t){this.renderTarget&&(this._multiRenderTargetOptions.layerIndex=e,this._multiRenderTargetOptions.faceIndex=t,this.renderTarget.setLayerAndFaceIndices(e,t))}get samples(){return this._samples}set samples(e){this._renderTarget?this._samples=this._renderTarget.setSamples(e):this._samples=e}resize(e){this._processSizeParameter(e,!1),this._rebuild(void 0,this._textureNames)}updateCount(e,t,i){this._multiRenderTargetOptions.textureCount=e,this._count=e;let r=[],s=[],n=[],a=[],o=[],l=[],h=[],u=[];this._textureNames=i,this._initTypes(e,r,s,n,a,o,l,h,u,t),this._multiRenderTargetOptions.types=r,this._multiRenderTargetOptions.samplingModes=s,this._multiRenderTargetOptions.useSRGBBuffers=n,this._multiRenderTargetOptions.formats=a,this._multiRenderTargetOptions.targetTypes=o,this._multiRenderTargetOptions.faceIndex=l,this._multiRenderTargetOptions.layerIndex=h,this._multiRenderTargetOptions.layerCounts=u,this._rebuild(!0,i)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindMultiColorAttachmentFramebuffer(this._renderTarget,this.isCube,()=>{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;let 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 f_{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class ff{constructor(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_,f,m;return this.name=e,this.meshes=t,this.scene=r,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!==(n=this.options.uvsIn)&&void 0!==n?n:rQ.o.UVKind,this.options.uvsOut=null!==(a=this.options.uvsOut)&&void 0!==a?a:rQ.o.UVKind,this.options.layout=null!==(o=this.options.layout)&&void 0!==o?o:ff.LAYOUT_STRIP,this.options.layout===ff.LAYOUT_COLNUM&&(this.options.colnum=null!==(l=this.options.colnum)&&void 0!==l?l:8),this.options.updateInputMeshes=null===(h=this.options.updateInputMeshes)||void 0===h||h,this.options.disposeSources=null===(u=this.options.disposeSources)||void 0===u||u,this._expecting=0,this.options.fillBlanks=null===(c=this.options.fillBlanks)||void 0===c||c,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(d=this.options.customFillColor)&&void 0!==d?d:"black"),this.options.frameSize=null!==(p=this.options.frameSize)&&void 0!==p?p: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!==(f=this.options.paddingMode)&&void 0!==f?f:ff.SUBUV_WRAP,this.options.paddingMode===ff.SUBUV_COLOR&&(this.options.paddingColor=null!==(m=this.options.paddingColor)&&void 0!==m?m:new rs.HE(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){let t=this._calculateSize(),i=new rr.FM(1,1).divide(t),r=0,s=this._expecting,n=this.meshes.length,a=Object.keys(this.sets);for(let e=0;e<a.length;e++){let i=a[e],r=new lb(this.name+".TexturePack."+i+"Set",{width:t.x,height:t.y},this.scene,!0,sv.TRILINEAR_SAMPLINGMODE,r7.D.TEXTUREFORMAT_RGBA),s=r.getContext();s.fillStyle="rgba(0,0,0,0)",s.fillRect(0,0,t.x,t.y),r.update(!1),this.sets[i]=r}let o=this.options.frameSize||256,l=this._paddingValue,h=o+2*l,u=()=>{this._calculateMeshUVFrames(o,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i<n;i++){let n=this.meshes[i],c=n.material;for(let n=0;n<a.length;n++){let d=new lb("temp",h,this.scene,!0),p=d.getContext(),_=this._getFrameOffset(i),f=()=>{r++,d.update(!1);let i=p.getImageData(0,0,h,h),n=this.sets[m],a=n.getContext();if(a.putImageData(i,t.x*_.x,t.y*_.y),d.dispose(),n.update(!1),r==s){u(),e();return}},m=a[n]||"_blank";if(c&&null!==c[m]){let e=c[m],t=new Image;e instanceof lb?t.src=e.getContext().canvas.toDataURL("image/png"):t.src=e.url,rZ.w1.SetCorsBehavior(t.src,t),t.onload=()=>{p.fillStyle="rgba(0,0,0,0)",p.fillRect(0,0,h,h),d.update(!1),p.setTransform(1,0,0,-1,0,0);let 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++)p.drawImage(t,0,0,t.width,t.height,l+o*e[i],l+o*e[i+1]-h,o,o);break;case 1:for(let e=0;e<l;e++)p.drawImage(t,0,0,t.width,t.height,e+0*o,l-h,o,o),p.drawImage(t,0,0,t.width,t.height,2*l-e,l-h,o,o),p.drawImage(t,0,0,t.width,t.height,l,e-h,o,o),p.drawImage(t,0,0,t.width,t.height,l,2*l-e-h,o,o);p.drawImage(t,0,0,t.width,t.height,l+0*o,l+0*o-h,o,o);break;case 2:p.fillStyle=(this.options.paddingColor||rs.Wo.Black()).toHexString(),p.fillRect(0,0,h,-h),p.clearRect(l,l,o,o),p.drawImage(t,0,0,t.width,t.height,l+0*o,l+0*o-h,o,o)}p.setTransform(1,0,0,1,0,0),f()}}else p.fillStyle="rgba(0,0,0,0)",this.options.fillBlanks&&(p.fillStyle=this.options.customFillColor),p.fillRect(0,0,h,h),f()}}}_calculateSize(){let e=this.meshes.length||0,t=this.options.frameSize||0,i=this._paddingValue||0;switch(this.options.layout){case 0:return new rr.FM(t*e+2*i*e,t+2*i);case 1:{let r=Math.max(2,Math.ceil(Math.sqrt(e))),s=t*r+2*i*r;return new rr.FM(s,s)}case 2:{let r=this.options.colnum||1,s=Math.max(1,Math.ceil(e/r));return new rr.FM(t*r+2*i*r,t*s+2*i*s)}}return rr.FM.Zero()}_calculateMeshUVFrames(e,t,i,r,s){let n=this.meshes.length;for(let a=0;a<n;a++){let n=this.meshes[a],o=new rr.FM(e/i.x,e/i.y),l=r.clone().scale(t),h=this._getFrameOffset(a),u=h.add(l),c=new f_(a,o,u);this.frames.push(c),s&&(this._updateMeshUV(n,a),this._updateTextureReferences(n))}}_getFrameOffset(e){let t,i,r;let s=this.meshes.length;switch(this.options.layout){case 0:return t=1/s,new rr.FM(e*t,0);case 1:{let n=Math.max(2,Math.ceil(Math.sqrt(s)));return i=Math.floor(e/n),r=e-i*n,t=1/n,new rr.FM(r*t,i*t)}case 2:{let n=this.options.colnum||1,a=Math.max(1,Math.ceil(s/n));return r=Math.floor(e/a),i=e-r*a,t=new rr.FM(1/n,1/a),new rr.FM(r*t.x,i*t.y)}}return rr.FM.Zero()}_updateMeshUV(e,t){let i=this.frames[t],r=e.getVerticesData(this.options.uvsIn||rQ.o.UVKind),s=[],n=0;r.length&&(n=r.length||0);for(let e=0;e<n;e+=2)s.push(r[e]*i.scale.x+i.offset.x,r[e+1]*i.scale.y+i.offset.y);e.setVerticesData(this.options.uvsOut||rQ.o.UVKind,s)}_updateTextureReferences(e,t=!1){let i=e.material,r=Object.keys(this.sets),s=e=>{e.dispose&&e.dispose()};for(let e=0;e<r.length;e++){let n=r[e];if(t)null!==i[n]&&s(i[n]),i[n]=this.sets[n];else{if(!i)return;null!==i[n]&&(s(i[n]),i[n]=this.sets[n])}}}setMeshToFrame(e,t,i=!1){this._updateMeshUV(e,t),i&&this._updateTextureReferences(e,!0)}processAsync(){return new Promise((e,t)=>{try{if(0===this.meshes.length){e();return}let t=0,i=i=>{if(t++,this.options.map){for(let e=0;e<this.options.map.length;e++){let t=this.options.map[e],r=i[t];null!==r&&(this.sets[this.options.map[e]]||(this.sets[this.options.map[e]]=!0),this._expecting++)}t===this.meshes.length&&this._createFrames(e)}};for(let r=0;r<this.meshes.length;r++){let s=this.meshes[r],n=s.material;if(!n){if(++t===this.meshes.length)return this._createFrames(e);continue}n.forceCompilationAsync(s).then(()=>{i(n)})}}catch(e){return t(e)}})}dispose(){let e=Object.keys(this.sets);for(let t=0;t<e.length;t++){let i=e[t];this.sets[i].dispose()}}download(e="png",t=1){setTimeout(()=>{let i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;s<r.length;s++){let n=r[s],a=this.sets[n];i.sets[n]=a.getContext().canvas.toDataURL("image/"+e,t)}for(let e=0;e<s.length;e++){let t=s[e];i.options[t]=this.options[t]}for(let e=0;e<this.frames.length;e++){let t=this.frames[e];i.frames.push(t.scale.x,t.scale.y,t.offset.x,t.offset.y)}}catch(e){ru.Y.Warn("Unable to download: "+e);return}let n="data:text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(i,null,4)),a=document.createElement("a");a.setAttribute("href",n),a.setAttribute("download",this.name+"_texurePackage.json"),document.body.appendChild(a),a.click(),a.remove()},0)}updateFromJSON(e){try{let t=JSON.parse(e);this.name=t.name;let i=Object.keys(t.options);for(let e=0;e<i.length;e++)this.options[i[e]]=t.options[i[e]];for(let e=0;e<t.frames.length;e+=4){let i=new f_(e/4,new rr.FM(t.frames[e],t.frames[e+1]),new rr.FM(t.frames[e+2],t.frames[e+3]));this.frames.push(i)}let r=Object.keys(t.sets);for(let e=0;e<r.length;e++){let i=new sv(t.sets[r[e]],this.scene,!1,!1);this.sets[r[e]]=i}}catch(e){ru.Y.Warn("Unable to update from JSON: "+e)}}}ff.LAYOUT_STRIP=0,ff.LAYOUT_POWER2=1,ff.LAYOUT_COLNUM=2,ff.SUBUV_WRAP=0,ff.SUBUV_EXTEND=1,ff.SUBUV_COLOR=2;let fm=`uniform float brightness;uniform float persistence;uniform float timeScale;varying vec2 vUV;vec2 hash22(vec2 p) -{p=p*mat2(127.1,311.7,269.5,183.3);p=-1.0+2.0*fract(sin(p)*43758.5453123);return sin(p*6.283+timeScale);} -float interpolationNoise(vec2 p) -{vec2 pi=floor(p);vec2 pf=p-pi;vec2 w=pf*pf*(3.-2.*pf);float f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));float f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));float f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));float f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));float xm1=mix(f00,f10,w.x);float xm2=mix(f01,f11,w.x);float ym=mix(xm1,xm2,w.y); -return ym;} -float perlinNoise2D(float x,float y) -{float sum=0.0;float frequency=0.0;float amplitude=0.0;for(int i=0; i<OCTAVES; i++) -{frequency=pow(2.0,float(i));amplitude=pow(persistence,float(i));sum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;} -return sum;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float x=abs(vUV.x);float y=abs(vUV.y);float noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);gl_FragColor=vec4(noise,noise,noise,1.0);} -`;no.v.ShadersStore.noisePixelShader=fm;class fg extends nz{constructor(e,t=256,i=rp.l.LastCreatedScene,r,s){super(e,t,"noise",i,r,s),this.time=0,this.brightness=.2,this.octaves=3,this.persistence=.8,this.animationSpeedFactor=1,this.autoClear=!1,this._updateShaderUniforms()}_updateShaderUniforms(){let e=this.getScene();e&&(this.time+=e.getAnimationRatio()*this.animationSpeedFactor*.01,this.setFloat("brightness",this.brightness),this.setFloat("persistence",this.persistence),this.setFloat("timeScale",this.time))}_getDefines(){return"#define OCTAVES "+(0|this.octaves)}render(e){this._updateShaderUniforms(),super.render(e)}serialize(){let e={};return e.customType="BABYLON.NoiseProceduralTexture",e.brightness=this.brightness,e.octaves=this.octaves,e.persistence=this.persistence,e.animationSpeedFactor=this.animationSpeedFactor,e.size=this.getSize().width,e.generateMipMaps=this._generateMipMaps,e.time=this.time,e}clone(){let e=this.getSize(),t=new fg(this.name,e.width,this.getScene(),this._fallbackTexture?this._fallbackTexture:void 0,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t.brightness=this.brightness,t.octaves=this.octaves,t.persistence=this.persistence,t.animationSpeedFactor=this.animationSpeedFactor,t.time=this.time,t}static Parse(e,t){var i;let r=new fg(e.name,e.size,t,void 0,e.generateMipMaps);return r.brightness=e.brightness,r.octaves=e.octaves,r.persistence=e.persistence,r.animationSpeedFactor=e.animationSpeedFactor,r.time=null!==(i=e.time)&&void 0!==i?i:0,r}}(0,rn.H)("BABYLON.NoiseProceduralTexture",fg);class fv extends sQ{constructor(e,t,i,r,s){super(e,t,i),this._blockType=r,this._blockName=s,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof fv&&e._blockName===this._blockName?tc.Compatible:tc.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}(0,rn.H)("BABYLON.BonesBlock",class extends sJ{constructor(e){super(e,tu.Vertex),this.registerInput("matricesIndices",th.Vector4),this.registerInput("matricesWeights",th.Vector4),this.registerInput("matricesIndicesExtra",th.Vector4,!0),this.registerInput("matricesWeightsExtra",th.Vector4,!0),this.registerInput("world",th.Matrix),this.registerOutput("output",th.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 ne("matricesIndices")).setAsAttribute("matricesIndices"),t.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let t=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesWeights"===e.name);t||(t=new ne("matricesWeights")).setAsAttribute("matricesWeights"),t.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let t=e.getInputBlockByPredicate(e=>e.systemValue===tf.World);t||(t=new ne("world")).setAsSystemValue(tf.World),t.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){s3.G.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&s3.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");let t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});let i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});let r=this._outputs[0],s=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 -`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName} * ${i}; -`,e.compilationString+=`#else -`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName}; -`,e.compilationString+=`#endif -`,this}}),(0,rn.H)("BABYLON.InstancesBlock",class extends sJ{constructor(e){super(e,tu.Vertex),this.registerInput("world0",th.Vector4),this.registerInput("world1",th.Vector4),this.registerInput("world2",th.Vector4),this.registerInput("world3",th.Vector4),this.registerInput("world",th.Matrix,!0),this.registerOutput("output",th.Matrix),this.registerOutput("instanceID",th.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 ne("world0")).setAsAttribute("world0"),t.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let t=e.getInputBlockByPredicate(e=>e.isAttribute&&"world1"===e.name);t||(t=new ne("world1")).setAsAttribute("world1"),t.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let t=e.getInputBlockByPredicate(e=>e.isAttribute&&"world2"===e.name);t||(t=new ne("world2")).setAsAttribute("world2"),t.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let t=e.getInputBlockByPredicate(e=>e.isAttribute&&"world3"===e.name);t||(t=new ne("world3")).setAsAttribute("world3"),t.output.connectTo(this.world3)}if(!this.world.connectedPoint){let t=e.getInputBlockByPredicate(e=>e.isAttribute&&"world"===e.name);t||(t=new ne("world")).setAsSystemValue(tf.World),t.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,s){let n=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),n=!0),s&&!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)!==i.THIN_INSTANCES&&(i.setValue("THIN_INSTANCES",!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);let t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);let i=this._outputs[0],r=this._outputs[1],s=this.world0,n=this.world1,a=this.world2,o=this.world3;return e.compilationString+=`#ifdef INSTANCES -`,e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${n.associatedVariableName}, ${a.associatedVariableName}, ${o.associatedVariableName}); -`,e.compilationString+=`#ifdef THIN_INSTANCES -`,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName}; -`,e.compilationString+=`#endif -`,t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(r,e)+` = float(gl_InstanceID); -`:e.compilationString+=this._declareOutput(r,e)+` = 0.0; -`,e.compilationString+=`#else -`,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName}; -`,e.compilationString+=this._declareOutput(r,e)+` = 0.0; -`,e.compilationString+=`#endif -`,this}});class fT extends sJ{constructor(e){super(e,tu.Vertex),this.registerInput("position",th.Vector3),this.registerInput("normal",th.Vector3),this.registerInput("tangent",th.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(th.Color4|th.Vector4|th.Vector3),this.registerInput("uv",th.Vector2),this.registerOutput("positionOutput",th.Vector3),this.registerOutput("normalOutput",th.Vector3),this.registerOutput("tangentOutput",th.Vector4),this.registerOutput("uvOutput",th.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 ne("position")).setAsAttribute(),t.output.connectTo(this.position)}if(!this.normal.isConnected){let t=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name);t||(t=new ne("normal")).setAsAttribute("normal"),t.output.connectTo(this.normal)}if(!this.tangent.isConnected){let t=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name);t||(t=new ne("tangent")).setAsAttribute("tangent"),t.output.connectTo(this.tangent)}if(!this.uv.isConnected){let t=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name);t||(t=new ne("uv")).setAsAttribute("uv"),t.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){let t=e.morphTargetManager;(null==t?void 0:t.isUsingTextureForTargets)&&t.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&s3.G.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(s3.G.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){let s=this.position,n=this.normal,a=this.tangent,o=this.uv,l=this.positionOutput,h=this.normalOutput,u=this.tangentOutput,c=this.uvOutput,d=r.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,_=p&&p.supportsNormals&&r.NORMAL,f=p&&p.supportsTangents&&r.TANGENT,m=p&&p.supportsUVs&&r.UV1,g="";(null==p?void 0:p.isUsingTextureForTargets)&&d>0&&(g+=`float vertexID; -`);for(let e=0;e<d;e++)g+=`#ifdef MORPHTARGETS -`,(null==p?void 0:p.isUsingTextureForTargets)?g+=`vertexID = float(gl_VertexID) * morphTargetTextureInfo.x; -${l.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID) - ${s.associatedVariableName}) * morphTargetInfluences[${e}]; -vertexID += 1.0; -`:g+=`${l.associatedVariableName} += (position${e} - ${s.associatedVariableName}) * morphTargetInfluences[${e}]; -`,_&&(g+=`#ifdef MORPHTARGETS_NORMAL -`,(null==p?void 0:p.isUsingTextureForTargets)?g+=`${h.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID) - ${n.associatedVariableName}) * morphTargetInfluences[${e}]; -vertexID += 1.0; -`:g+=`${h.associatedVariableName} += (normal${e} - ${n.associatedVariableName}) * morphTargetInfluences[${e}]; -`,g+=`#endif -`),m&&(g+=`#ifdef MORPHTARGETS_UV -`,(null==p?void 0:p.isUsingTextureForTargets)?g+=`${c.associatedVariableName} += (readVector3FromRawSampler(${e}, vertexID).xy - ${o.associatedVariableName}) * morphTargetInfluences[${e}]; -vertexID += 1.0; -`:g+=`${c.associatedVariableName}.xy += (uv_${e} - ${o.associatedVariableName}.xy) * morphTargetInfluences[${e}]; -`,g+=`#endif -`),f&&(g+=`#ifdef MORPHTARGETS_TANGENT -`,(null==p?void 0:p.isUsingTextureForTargets)?g+=`${u.associatedVariableName}.xyz += (readVector3FromRawSampler(${e}, vertexID) - ${a.associatedVariableName}.xyz) * morphTargetInfluences[${e}]; -`:g+=`${u.associatedVariableName}.xyz += (tangent${e} - ${a.associatedVariableName}.xyz) * morphTargetInfluences[${e}]; -`,a.type===th.Vector4?g+=`${u.associatedVariableName}.w = ${a.associatedVariableName}.w; -`:g+=`${u.associatedVariableName}.w = 1.; -`,g+=`#endif -`),g+=`#endif -`;if(e.compilationString=e.compilationString.replace(this._repeatableContentAnchor,g),d>0)for(let t=0;t<d;t++)e.attributes.push(rQ.o.PositionKind+t),_&&e.attributes.push(rQ.o.NormalKind+t),f&&e.attributes.push(rQ.o.TangentKind+t),m&&e.attributes.push(rQ.o.UVKind+"_"+t)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);let t=this.position,i=this.normal,r=this.tangent,s=this.uv,n=this.positionOutput,a=this.normalOutput,o=this.tangentOutput,l=this.uvOutput,h=`//${this.name}`;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",h),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",h,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=`${this._declareOutput(n,e)} = ${t.associatedVariableName}; -`,e.compilationString+=`#ifdef NORMAL -`,e.compilationString+=`${this._declareOutput(a,e)} = ${i.associatedVariableName}; -`,e.compilationString+=`#else -`,e.compilationString+=`${this._declareOutput(a,e)} = vec3(0., 0., 0.); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef TANGENT -`,e.compilationString+=`${this._declareOutput(o,e)} = ${r.associatedVariableName}; -`,e.compilationString+=`#else -`,e.compilationString+=`${this._declareOutput(o,e)} = vec4(0., 0., 0., 0.); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef UV1 -`,e.compilationString+=`${this._declareOutput(l,e)} = ${s.associatedVariableName}; -`,e.compilationString+=`#else -`,e.compilationString+=`${this._declareOutput(l,e)} = vec2(0., 0.); -`,e.compilationString+=`#endif -`,this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this}}(0,rn.H)("BABYLON.MorphTargetsBlock",fT),(0,rn.H)("BABYLON.LightInformationBlock",class extends sJ{constructor(e){super(e,tu.Vertex),this.registerInput("worldPosition",th.Vector4,!1,tu.Vertex),this.registerOutput("direction",th.Vector3),this.registerOutput("color",th.Color3),this.registerOutput("intensity",th.Float),this.registerOutput("shadowBias",th.Float),this.registerOutput("shadowNormalBias",th.Float),this.registerOutput("shadowDepthScale",th.Float),this.registerOutput("shadowDepthRange",th.Vector2)}getClassName(){return"LightInformationBlock"}get worldPosition(){return this._inputs[0]}get direction(){return this._outputs[0]}get color(){return this._outputs[1]}get intensity(){return this._outputs[2]}get shadowBias(){return this._outputs[3]}get shadowNormalBias(){return this._outputs[4]}get shadowDepthScale(){return this._outputs[5]}get shadowDepthRange(){return this._outputs[6]}bind(e,t,i){if(!i)return;this.light&&this.light.isDisposed()&&(this.light=null);let r=this.light,s=t.getScene();if(!r&&s.lights.length&&(r=this.light=s.lights[0],this._forcePrepareDefines=!0),!r||!r.isEnabled){e.setFloat3(this._lightDataUniformName,0,0,0),e.setFloat4(this._lightColorUniformName,0,0,0,0);return}r.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,r.diffuse,r.intensity);let n=r.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(n?e.setFloat3(this._lightShadowUniformName,n.bias,n.normalBias,n.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange){if(n&&s.activeCamera){let t=r;e.setFloat2(this._lightShadowExtraUniformName,t.getDepthMinZ(s.activeCamera),t.getDepthMinZ(s.activeCamera)+t.getDepthMaxZ(s.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}}prepareDefines(e,t,i){if(!i._areLightsDirty&&!this._forcePrepareDefines)return;this._forcePrepareDefines=!1;let r=this.light;i.setValue(this._lightTypeDefineName,!!r&&r instanceof _P,!0)}_buildBlock(e){super._buildBlock(e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);let t=this.direction,i=this.color,r=this.intensity,s=this.shadowBias,n=this.shadowNormalBias,a=this.shadowDepthScale,o=this.shadowDepthRange;return this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightShadowUniformName=e._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=e._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE"),e._emitUniformFromString(this._lightDataUniformName,"vec3"),e._emitUniformFromString(this._lightColorUniformName,"vec4"),e.compilationString+=`#ifdef ${this._lightTypeDefineName} -`,e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName}); -`,e.compilationString+=`#else -`,e.compilationString+=this._declareOutput(t,e)+` = ${this._lightDataUniformName}; -`,e.compilationString+=`#endif -`,e.compilationString+=this._declareOutput(i,e)+` = ${this._lightColorUniformName}.rgb; -`,e.compilationString+=this._declareOutput(r,e)+` = ${this._lightColorUniformName}.a; -`,(s.hasEndpoints||n.hasEndpoints||a.hasEndpoints)&&(e._emitUniformFromString(this._lightShadowUniformName,"vec3"),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${this._lightShadowUniformName}.x; -`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${this._lightShadowUniformName}.y; -`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${this._lightShadowUniformName}.z; -`)),o.hasEndpoints&&(e._emitUniformFromString(this._lightShadowExtraUniformName,"vec2"),e.compilationString+=this._declareOutput(o,e)+` = ${this._lightShadowUniformName}; -`),this}serialize(){let e=super.serialize();return 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))}});class fx extends sJ{constructor(e){super(e,tu.Fragment),this.convertInputToLinearSpace=!0,this.registerInput("color",th.AutoDetect),this.registerOutput("output",th.Color4),this.registerOutput("rgb",th.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Color4|th.Vector3|th.Vector4)}getClassName(){return"ImageProcessingBlock"}get color(){return this._inputs[0]}get output(){return this._outputs[0]}get rgb(){return this._outputs[1]}initialize(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")}isReady(e,t,i){return!i._areImageProcessingDirty||!t.imageProcessingConfiguration||!!t.imageProcessingConfiguration.isReady()}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_buildBlock(e){var t;super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity");let i=this.color,r=this._outputs[0],s=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("imageProcessingDeclaration",s),e._emitFunctionFromInclude("imageProcessingFunctions",s),(null===(t=i.connectedPoint)||void 0===t?void 0:t.isConnected)&&(i.connectedPoint.type===th.Color4||i.connectedPoint.type===th.Vector4?e.compilationString+=`${this._declareOutput(r,e)} = ${i.associatedVariableName}; -`:e.compilationString+=`${this._declareOutput(r,e)} = vec4(${i.associatedVariableName}, 1.0); -`,e.compilationString+=`#ifdef IMAGEPROCESSINGPOSTPROCESS -`,this.convertInputToLinearSpace&&(e.compilationString+=`${r.associatedVariableName}.rgb = toLinearSpace(${i.associatedVariableName}.rgb); -`),e.compilationString+=`#else -`,e.compilationString+=`#ifdef IMAGEPROCESSING -`,this.convertInputToLinearSpace&&(e.compilationString+=`${r.associatedVariableName}.rgb = toLinearSpace(${i.associatedVariableName}.rgb); -`),e.compilationString+=`${r.associatedVariableName} = applyImageProcessing(${r.associatedVariableName}); -`,e.compilationString+=`#endif -`,e.compilationString+=`#endif -`,this.rgb.hasEndpoints&&(e.compilationString+=this._declareOutput(this.rgb,e)+` = ${this.output.associatedVariableName}.xyz; -`)),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace}; -`}serialize(){let e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.convertInputToLinearSpace=null===(r=e.convertInputToLinearSpace)||void 0===r||r}}(0,r0.gn)([s2("Convert input to linear space",tp.Boolean,"ADVANCED")],fx.prototype,"convertInputToLinearSpace",void 0),(0,rn.H)("BABYLON.ImageProcessingBlock",fx);class fS extends sJ{constructor(e){super(e,tu.Fragment,!0),this.registerInput("normal",th.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(th.Color4|th.Vector4|th.Vector3),this.registerInput("tangent",th.Vector4,!1),this.registerInput("world",th.Matrix,!1),this.registerOutput("TBN",th.Object,tu.Fragment,new fv("TBN",this,td.Output,fS,"TBNBlock")),this.registerOutput("row0",th.Vector3,tu.Fragment),this.registerOutput("row1",th.Vector3,tu.Fragment),this.registerOutput("row2",th.Vector3,tu.Fragment)}getClassName(){return"TBNBlock"}initialize(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")}get normal(){return this._inputs[0]}get tangent(){return this._inputs[1]}get world(){return this._inputs[2]}get TBN(){return this._outputs[0]}get row0(){return this._outputs[1]}get row1(){return this._outputs[2]}get row2(){return this._outputs[3]}get target(){return tu.Fragment}set target(e){}autoConfigure(e){if(!this.world.isConnected){let t=e.getInputBlockByPredicate(e=>e.isSystemValue&&e.systemValue===tf.World);t||(t=new ne("world")).setAsSystemValue(tf.World),t.output.connectTo(this.world)}if(!this.normal.isConnected){let t=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name);t||(t=new ne("normal")).setAsAttribute("normal"),t.output.connectTo(this.normal)}if(!this.tangent.isConnected){let t=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&e.type===th.Vector4);t||(t=new ne("tangent")).setAsAttribute("tangent"),t.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var r,s,n,a;let o=this.normal,l=this.tangent,h=o.isConnected;(null===(r=o.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(s=o.connectInputBlock)||void 0===s?void 0:s.name)&&(h=!1);let u=l.isConnected;(null===(n=l.connectInputBlock)||void 0===n?void 0:n.isAttribute)&&!e.isVerticesDataPresent(null===(a=l.connectInputBlock)||void 0===a?void 0:a.name)&&(u=!1);let c=h&&u;i.setValue("TBNBLOCK",c,!0)}_buildBlock(e){super._buildBlock(e);let t=this.normal,i=this.tangent,r=this.world,s=this.TBN,n=this.row0,a=this.row1,o=this.row2;return e.target===tu.Fragment&&(e.compilationString+=` - // ${this.name} - vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz; - vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz); - vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; - mat3 ${s.associatedVariableName} = mat3(${r.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); - `,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]); -`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]); -`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]); -`),e.sharedData.blocksWithDefines.push(this)),this}}(0,rn.H)("BABYLON.TBNBlock",fS);class fE extends sJ{constructor(e){super(e,tu.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",th.Vector4,!1),this.registerInput("worldNormal",th.Vector4,!1),this.registerInput("worldTangent",th.Vector4,!0),this.registerInput("uv",th.Vector2,!1),this.registerInput("normalMapColor",th.Color3,!1),this.registerInput("strength",th.Float,!1),this.registerInput("viewDirection",th.Vector3,!0),this.registerInput("parallaxScale",th.Float,!0),this.registerInput("parallaxHeight",th.Float,!0),this.registerInput("TBN",th.Object,!0,tu.VertexAndFragment,new fv("TBN",this,td.Input,fS,"TBNBlock")),this.registerInput("world",th.Matrix,!0),this.registerOutput("output",th.Vector4),this.registerOutput("uvOffset",th.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){let r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("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,0>i.getWorldMatrix().determinant()?-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 ne("uv")).setAsAttribute(),t.output.connectTo(this.uv)}if(!this.strength.isConnected){let e=new ne("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`,i=this.uv,r=this.worldPosition,s=this.worldNormal,n=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 a=null;this.normalMapColor.connectedPoint&&(a=this.normalMapColor.connectedPoint._ownerBlock.samplerName);let o=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&a||!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?` -#if !defined(NORMALXYSCALE) -1.0/ -#endif -${e._emitFloat(this.strength.connectInputBlock.value)}`:` -#if !defined(NORMALXYSCALE) -1.0/ -#endif -${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let u={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},c=this.TBN;c.isConnected?e.compilationString+=` - #ifdef TBNBLOCK - mat3 vTBN = ${c.associatedVariableName}; - #endif - `:n.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz); -`,e.compilationString+=`vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); -`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; -`,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); -`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[u,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include<samplerFragmentDeclaration>\(_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\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_"}]});let d=o&&a?`texture2D(${a}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${d}`},{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, ${d}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o&&this.useParallaxOcclusion?a:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${o?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:r.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:o?this.viewDirection.associatedVariableName:"vec3(0.)"},u]}),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX}; -`+`${this._codeVariableName}.invertY = ${this.invertY}; -${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion}; -${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap}; -`}serialize(){let 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,r0.gn)([s2("Invert X axis",tp.Boolean,"PROPERTIES",{notifiers:{update:!1}})],fE.prototype,"invertX",void 0),(0,r0.gn)([s2("Invert Y axis",tp.Boolean,"PROPERTIES",{notifiers:{update:!1}})],fE.prototype,"invertY",void 0),(0,r0.gn)([s2("Use parallax occlusion",tp.Boolean)],fE.prototype,"useParallaxOcclusion",void 0),(0,r0.gn)([s2("Object Space Mode",tp.Boolean,"PROPERTIES",{notifiers:{update:!1}})],fE.prototype,"useObjectSpaceNormalMap",void 0),(0,rn.H)("BABYLON.PerturbNormalBlock",fE),(0,rn.H)("BABYLON.DiscardBlock",class extends sJ{constructor(e){super(e,tu.Fragment,!0),this.registerInput("value",th.Float,!0),this.registerInput("cutoff",th.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard; -`,this}}),(0,rn.H)("BABYLON.FrontFacingBlock",class extends sJ{constructor(e){super(e,tu.Fragment),this.registerOutput("output",th.Float,tu.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===tu.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = gl_FrontFacing ? 1.0 : 0.0; -`,this}}),(0,rn.H)("BABYLON.DerivativeBlock",class extends sJ{constructor(e){super(e,tu.Fragment),this.registerInput("input",th.AutoDetect,!1),this.registerOutput("dx",th.BasedOnInput),this.registerOutput("dy",th.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);let 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}); -`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName}); -`),this}}),(0,rn.H)("BABYLON.FragCoordBlock",class extends sJ{constructor(e){super(e,tu.Fragment),this.registerOutput("xy",th.Vector2,tu.Fragment),this.registerOutput("xyz",th.Vector3,tu.Fragment),this.registerOutput("xyzw",th.Vector4,tu.Fragment),this.registerOutput("x",th.Float,tu.Fragment),this.registerOutput("y",th.Float,tu.Fragment),this.registerOutput("z",th.Float,tu.Fragment),this.registerOutput("w",th.Float,tu.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(let i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name}; -`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===tu.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}),(0,rn.H)("BABYLON.ScreenSizeBlock",class extends sJ{constructor(e){super(e,tu.Fragment),this.registerOutput("xy",th.Vector2,tu.Fragment),this.registerOutput("x",th.Float,tu.Fragment),this.registerOutput("y",th.Float,tu.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){let t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; -`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===tu.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,rn.H)("BABYLON.ScreenSpaceBlock",class extends sJ{constructor(e){super(e,tu.Fragment),this.registerInput("vector",th.AutoDetect),this.registerInput("worldViewProjection",th.Matrix),this.registerOutput("output",th.Vector2),this.registerOutput("x",th.Float),this.registerOutput("y",th.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Vector3|th.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===tf.WorldViewProjection);t||(t=new ne("worldViewProjection")).setAsSystemValue(tf.WorldViewProjection),t.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;let r=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case th.Vector3:e.compilationString+=`vec4 ${s} = ${r} * vec4(${t.associatedVariableName}, 1.0); -`;break;case th.Vector4:e.compilationString+=`vec4 ${s} = ${r} * ${t.associatedVariableName}; -`}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; -`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x; -`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y; -`),this}}),(0,rn.H)("BABYLON.TwirlBlock",class extends sJ{constructor(e){super(e,tu.Fragment),this.registerInput("input",th.Vector2),this.registerInput("strength",th.Float),this.registerInput("center",th.Vector2),this.registerInput("offset",th.Vector2),this.registerOutput("output",th.Vector2),this.registerOutput("x",th.Float),this.registerOutput("y",th.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){let e=new ne("center");e.value=new rr.FM(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){let e=new ne("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){let e=new ne("offset");e.value=new rr.FM(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);let t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` - vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; - float ${i} = ${this.strength.associatedVariableName} * length(${t}); - float ${r} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; - float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; - vec2 ${n} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); - `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${n}; -`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${n}.x; -`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${n}.y; -`),this}});class fC extends sJ{constructor(e){super(e,tu.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",th.Float),this.registerInput("worldPosition",th.Vector3),this.registerInput("worldNormal",th.Vector3),this.registerInput("worldTangent",th.AutoDetect,!0),this.registerOutput("output",th.Vector4),this.registerOutput("xyz",th.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Vector3|th.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);let t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`);let i=this.generateInWorldSpace?"":` - vec3 biTangent = cross(normal, tangent); - mat3 TBN = mat3(tangent, biTangent, normal); - `,r=this.generateInWorldSpace?"":` - result = TBN * result; - result = result * vec3(0.5) + vec3(0.5); - `,s=` - vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { - ${i} - ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""} - ${this.automaticNormalizationNormal?"normal = normalize(normal);":""} - vec3 worlddX = dFdx(position); - vec3 worlddY = dFdy(position); - vec3 crossX = cross(normal, worlddX); - vec3 crossY = cross(normal, worlddY); - float d = abs(dot(crossY, worlddX)); - vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); - inToNormal.y *= -1.0; - vec3 result = normalize((d * normal) - inToNormal); - ${r} - return vec4(result, 0.); - }`;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}); -`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; -`),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace}; -${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal}; -${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent}; -`}serialize(){let 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,r0.gn)([s2("Generate in world space instead of tangent space",tp.Boolean,"PROPERTIES",{notifiers:{update:!0}})],fC.prototype,"generateInWorldSpace",void 0),(0,r0.gn)([s2("Force normalization for the worldNormal input",tp.Boolean,"PROPERTIES",{notifiers:{update:!0}})],fC.prototype,"automaticNormalizationNormal",void 0),(0,r0.gn)([s2("Force normalization for the worldTangent input",tp.Boolean,"PROPERTIES",{notifiers:{update:!0}})],fC.prototype,"automaticNormalizationTangent",void 0),(0,rn.H)("BABYLON.HeightToNormalBlock",fC),(0,rn.H)("BABYLON.FragDepthBlock",class extends sJ{constructor(e){super(e,tu.Fragment,!0),this.registerInput("depth",th.Float,!0),this.registerInput("worldPos",th.Vector4,!0),this.registerInput("viewProjection",th.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName}; -`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=` - vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; - float v = p.z / p.w; - #ifndef IS_NDC_HALF_ZRANGE - v = v * 0.5 + 0.5; - #endif - gl_FragDepth = v; - - `:console.warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}),(0,rn.H)("BABYLON.ShadowMapBlock",class extends sJ{constructor(e){super(e,tu.Fragment),this.registerInput("worldPosition",th.Vector4,!1),this.registerInput("viewProjection",th.Matrix,!1),this.registerInput("worldNormal",th.AutoDetect,!0),this.registerOutput("depth",th.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Vector3|th.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);let 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}; -`,e.compilationString+=`vec3 vPositionWSM; -`,e.compilationString+=`float vDepthMetricSM = 0.0; -`,e.compilationString+=`float zSM; -`,this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz; -`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos; -`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+=` - #if SM_DEPTHTEXTURE == 1 - #ifdef IS_NDC_HALF_ZRANGE - gl_FragDepth = (clipPos.z / clipPos.w); - #else - gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5; - #endif - #endif - `,e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.); -`,this}}),(0,rn.H)("BABYLON.FogBlock",class extends sJ{constructor(e){super(e,tu.VertexAndFragment,!1),this.registerInput("worldPosition",th.Vector4,!1,tu.Vertex),this.registerInput("view",th.Matrix,!1,tu.Vertex),this.registerInput("input",th.AutoDetect,!1,tu.Fragment),this.registerInput("fogColor",th.AutoDetect,!1,tu.Fragment),this.registerOutput("output",th.Color3,tu.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Vector3|th.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Vector3|th.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===tf.View);t||(t=new ne("view")).setAsSystemValue(tf.View),t.output.connectTo(this.view)}if(!this.fogColor.isConnected){let t=e.getInputBlockByPredicate(e=>e.systemValue===tf.FogColor);t||(t=new ne("fogColor",void 0,th.Color3)).setAsSystemValue(tf.FogColor),t.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){let r=e.getScene();i.setValue("FOG",t.fogEnabled&&s3.G.GetFogState(e,r))}bind(e,t,i){if(!i)return;let r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===tu.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)"}]});let t=e._getFreeVariableName("fog"),i=this.input,r=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");let s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+=`#ifdef FOG -`,e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters}); -`,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${r.associatedVariableName}.rgb; -`,e.compilationString+=`#else -${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb; -`,e.compilationString+=`#endif -`}else{let 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; -`}return this}});class fb extends sJ{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?tu.Fragment:tu.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tu.Fragment:tu.Vertex}constructor(e){super(e,tu.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",th.Vector4,!1,tu.Vertex),this.registerInput("worldNormal",th.Vector4,!1,tu.Fragment),this.registerInput("cameraPosition",th.Vector3,!1,tu.Fragment),this.registerInput("glossiness",th.Float,!0,tu.Fragment),this.registerInput("glossPower",th.Float,!0,tu.Fragment),this.registerInput("diffuseColor",th.Color3,!0,tu.Fragment),this.registerInput("specularColor",th.Color3,!0,tu.Fragment),this.registerInput("view",th.Matrix,!0),this.registerOutput("diffuseOutput",th.Color3,tu.Fragment),this.registerOutput("specularOutput",th.Color3,tu.Fragment),this.registerOutput("shadow",th.Float,tu.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===tf.CameraPosition);t||(t=new ne("cameraPosition")).setAsSystemValue(tf.CameraPosition),t.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;let r=e.getScene();if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};s3.G.PrepareDefinesForLight(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else s3.G.PrepareDefinesForLights(r,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s<t.maxSimultaneousLights&&i["LIGHT"+s];s++){let t=e.uniforms.indexOf("vLightData"+s)>=0;s3.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}bind(e,t,i){if(!i)return;let r=i.getScene();this.light?s3.G.BindLight(this.light,this._lightId,r,e,!0):s3.G.BindLights(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){let 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));let r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${t.associatedVariableName}; -`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName}; -`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; -`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==tu.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);let t=`//${this.name}`,i=this.worldPosition,r=i.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${r}; -`,t),e.compilationString+=`${r} = ${i.associatedVariableName}.xyz; -`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):r="v_"+r+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),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} - ${r}); -`),e.compilationString+=`lightingInfo info; -`,e.compilationString+=`float shadow = 1.; -`,e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; -`,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.); -`,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.); -`,e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz; -`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights"});let s=this.diffuseOutput,n=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; -`,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""}; -`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = shadow; -`),this}serialize(){let 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,r0.gn)([s2("Generate only fragment code",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:fb._OnGenerateOnlyFragmentCodeChanged}})],fb.prototype,"generateOnlyFragmentCode",void 0),(0,rn.H)("BABYLON.LightBlock",fb);class fy extends sJ{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rp.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,tu.VertexAndFragment),this.registerOutput("source",th.Object,tu.VertexAndFragment,new fv("source",this,td.Output,fy,"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===tu.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}); -${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; -${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; -${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; -${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; -${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; -${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; -${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; -${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; -${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; -${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`:e}serialize(){let 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&&!nY.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=sv.Parse(e.texture,t,i))}}(0,rn.H)("BABYLON.ImageSourceBlock",fy),(0,rn.H)("BABYLON.TextureBlock",class extends sJ{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;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rp.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)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rp.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)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rp.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?tu.Fragment:tu.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",th.AutoDetect,!1,tu.VertexAndFragment),this.registerInput("source",th.Object,!0,tu.VertexAndFragment,new fv("source",this,td.Input,fy,"ImageSourceBlock")),this.registerInput("layer",th.Float,!0),this.registerInput("lod",th.Float,!0),this.registerOutput("rgba",th.Color4,tu.Neutral),this.registerOutput("rgb",th.Color3,tu.Neutral),this.registerOutput("r",th.Float,tu.Neutral),this.registerOutput("g",th.Float,tu.Neutral),this.registerOutput("b",th.Float,tu.Neutral),this.registerOutput("a",th.Float,tu.Neutral),this.registerOutput("level",th.Float,tu.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Vector2|th.Vector3|th.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 tu.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return tu.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===tu.Fragment)return tu.Fragment;if(e.target===tu.Vertex)break;if(e.target===tu.Neutral||e.target===tu.VertexAndFragment){let t=e.ownerBlock;if(t.target===tu.Fragment)return tu.Fragment;for(let i of(e=null,t.inputs))if(i.connectedPoint){e=i.connectedPoint;break}}}return tu.VertexAndFragment}set target(e){}autoConfigure(e){if(!this.uv.isConnected){if(e.mode===tg.PostProcess){let t=e.getBlockByPredicate(e=>"uv"===e.name);t&&t.connectTo(this)}else{let t=e.mode===tg.Particle?"particle_uv":"uv",i=e.getInputBlockByPredicate(e=>e.isAttribute&&e.name===t);i||(i=new ne("uv")).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){this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0));return}let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),void 0==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!==tu.Fragment}_injectVertexCode(e){let 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} -`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0)); -`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) -`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; -`,e.compilationString+=`#endif -`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}_getUVW(e){var t,i,r;let s=e,n=null!==(r=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==r&&r;if(n){let t=this.layer.isConnected?this.layer.associatedVariableName:"0";s=`vec3(${e}, ${t})`}return s}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){let t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName} -`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix}); -`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) -`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix}); -`,e.compilationString+=`#endif -`}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tu.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===tu.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix}); -`;return}this._generateTextureLookup(e)}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} - ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); - #endif - `),e.compilationString+=`#ifdef ${this._gammaDefineName} - ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); - #endif - `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tu.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===tu.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,this._generateConversionCode(e,t,i);return}let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s}; -`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,r,s;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===tu.Vertex||this._fragmentOnly||e.target===tu.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===tu.Fragment||this._isMixed&&e.target===tu.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!==tu.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((null===(s=null===(r=this._texture)||void 0===r?void 0:r._texture)||void 0===s?void 0:s.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));let n=`//${this.name}`;for(let t of(e._emitFunctionFromInclude("helperFunctions",n),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; -${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; -${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; -`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); -${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; -${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; -${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; -${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; -${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; -${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; -${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; -${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; -${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; -${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`:e}serialize(){let 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&&!nY.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=sv.Parse(e.texture,t,i))}});class fA extends sJ{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rp.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?tu.Fragment:tu.VertexAndFragment)}constructor(e){super(e,tu.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 ne("position")).setAsAttribute(),t.output.connectTo(this.position)}if(!this.world.isConnected){let t=e.getInputBlockByPredicate(e=>e.systemValue===tf.World);t||(t=new ne("world")).setAsSystemValue(tf.World),t.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let t=e.getInputBlockByPredicate(e=>e.systemValue===tf.View);t||(t=new ne("view")).setAsSystemValue(tf.View),t.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this._getTexture();r&&r.getTextureMatrix&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===r.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===r.coordinatesMode,!0),i.setValue(this._defineCubicName,3===r.coordinatesMode||6===r.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===r.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===r.coordinatesMode,!0),i.setValue(this._definePlanarName,2===r.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===r.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===r.coordinatesMode,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){let r=this._getTexture();i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize&&(e.setVector3(this._reflectionPositionName,r.boundingBoxPosition),e.setVector3(this._reflectionSizeName,r.boundingBoxSize)))}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===tu.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");let i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName}; -`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName} -${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; -#endif -`),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) -${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0))); -#endif -`),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName} -`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; -`,e._samplerDeclaration+=`#else -`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; -`,e._samplerDeclaration+=`#endif -`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let 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,r=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);let s=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,a=`${this._positionUVWName}`,o=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=` - #ifdef ${this._defineMirroredEquirectangularFixedName} - vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n}); - #endif - - #ifdef ${this._defineEquirectangularFixedName} - vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n}); - #endif - - #ifdef ${this._defineEquirectangularName} - vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${o}.xyz, ${s}); - #endif - - #ifdef ${this._defineSphericalName} - vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s}); - #endif - - #ifdef ${this._definePlanarName} - vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${o}.xyz, ${s}); - #endif - - #ifdef ${this._defineCubicName} - #ifdef ${this._defineLocalCubicName} - vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${o}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); - #else - vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${o}.xyz, ${s}); - #endif - #endif - - #ifdef ${this._defineProjectionName} - vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s}); - #endif - - #ifdef ${this._defineSkyboxName} - vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${a}, ${s}); - #endif - - #ifdef ${this._defineExplicitName} - vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); - #endif -`;return r||(h+=`#ifdef ${this._defineOppositeZ} - ${this._reflectionVectorName}.z *= -1.0; - #endif -`),i||(h+=` - #ifdef ${this._define3DName} - vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName}; - #else - vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy; - #ifdef ${this._defineProjectionName} - ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; - #endif - ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; - #endif -`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i="vec"+(0===t.length?"4":t.length-1),r=`${i} ${this._reflectionColorName}; - #ifdef ${this._define3DName} -`;return e?r+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t}; -`:r+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t}; -`,r+=` - #else -`,e?r+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t}; -`:r+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t}; -`,r+=`#endif -`}writeOutputs(e,t){let i="";if(e.target===tu.Fragment)for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; -`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){let t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"}); -`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null); -`;return e+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`}serialize(){let 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&&!nY.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=dn.Parse(e.texture,t,i):this.texture=sv.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}(0,r0.gn)([s2("Generate only fragment code",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:fA._OnGenerateOnlyFragmentCodeChanged}})],fA.prototype,"generateOnlyFragmentCode",void 0),(0,rn.H)("BABYLON.ReflectionTextureBaseBlock",fA),(0,rn.H)("BABYLON.ReflectionTextureBlock",class extends fA{_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?tu.Fragment:tu.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tu.Fragment:tu.Vertex}constructor(e){super(e),this.registerInput("position",th.AutoDetect,!1,tu.Vertex),this.registerInput("worldPosition",th.Vector4,!1,tu.Vertex),this.registerInput("worldNormal",th.Vector4,!1,tu.Fragment),this.registerInput("world",th.Matrix,!1,tu.Vertex),this.registerInput("cameraPosition",th.Vector3,!1,tu.Fragment),this.registerInput("view",th.Matrix,!1,tu.Fragment),this.registerOutput("rgb",th.Color3,tu.Fragment),this.registerOutput("rgba",th.Color4,tu.Fragment),this.registerOutput("r",th.Float,tu.Fragment),this.registerOutput("g",th.Float,tu.Fragment),this.registerOutput("b",th.Float,tu.Fragment),this.registerOutput("a",th.Float,tu.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Vector3|th.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===tf.CameraPosition);t||(t=new ne("cameraPosition")).setAsSystemValue(tf.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!==tu.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);let t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName}); -`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}});class fR extends sJ{constructor(e){super(e,tu.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",th.AutoDetect,!1,tu.VertexAndFragment),this.registerOutput("depth",th.Float,tu.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Vector2|th.Vector3|th.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?tu.VertexAndFragment:tu.Fragment}_getTexture(e){let t=e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ);return t.getDepthMap()}bind(e,t){let i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput){let i=t.connectedPoint.ownerBlock;i.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===th.Vector3?"3":t.type===th.Vector4?"4":"2"))}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; -`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tu.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); -`;return}if(this.uv.ownerBlock.target===tu.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); -`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); -`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tu.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}if(this.uv.ownerBlock.target===tu.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.bindableBlocks.indexOf(this)&&e.sharedData.bindableBlocks.push(this),e.target!==tu.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(this._outputs.some(e=>e.isConnectedInFragmentShader)){for(let t of(e._emit2DSampler(this._samplerName),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){let 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,r0.gn)([s2("Use non linear depth",tp.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],fR.prototype,"useNonLinearDepth",void 0),(0,r0.gn)([s2("Store Camera space Z",tp.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],fR.prototype,"storeCameraSpaceZ",void 0),(0,r0.gn)([s2("Force 32 bits float",tp.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>null==e?void 0:e.disableDepthRenderer()}})],fR.prototype,"force32itsFloat",void 0),(0,rn.H)("BABYLON.SceneDepthBlock",fR),(0,rn.H)("BABYLON.ClipPlanesBlock",class extends sJ{constructor(e){super(e,tu.VertexAndFragment,!0),this.registerInput("worldPosition",th.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 tu.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var r,s,n,a,o,l;let h=e.getScene(),u=null!==(r=t.clipPlane)&&void 0!==r?!!r:!!h.clipPlane,c=null!==(s=t.clipPlane2)&&void 0!==s?!!s:!!h.clipPlane2,d=null!==(n=t.clipPlane3)&&void 0!==n?!!n:!!h.clipPlane3,p=null!==(a=t.clipPlane4)&&void 0!==a?!!a:!!h.clipPlane4,_=null!==(o=t.clipPlane5)&&void 0!==o?!!o:!!h.clipPlane5,f=null!==(l=t.clipPlane6)&&void 0!==l?!!l:!!h.clipPlane6;i.setValue("CLIPPLANE",u,!0),i.setValue("CLIPPLANE2",c,!0),i.setValue("CLIPPLANE3",d,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",_,!0),i.setValue("CLIPPLANE6",f,!0)}bind(e,t,i){if(!i)return;let r=i.getScene();(0,lx.an)(e,t,r)}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;if(e.target!==tu.Fragment){let i=this.worldPosition;e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),e._emitUniformFromString("vClipPlane6","vec4");return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}),(0,rn.H)("BABYLON.NodeMaterialTeleportInBlock",class extends sJ{get endpoints(){return this._endpoints}constructor(e){super(e,tu.Neutral),this._endpoints=[],this.registerInput("input",th.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some(e=>e.output.isConnectedInFragmentShader)}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){for(let e of(super.dispose(),this._endpoints))this.detachFromEndpoint(e);this._endpoints=[]}}),(0,rn.H)("BABYLON.NodeMaterialTeleportOutBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",th.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){(this._target&e)==0&&(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName}; -`)}clone(e,t=""){let i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); -`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}),(0,rn.H)("BABYLON.AddBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(th.Float),this._inputs[1].acceptedConnectionPointTypes.push(th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName}; -`,this}}),(0,rn.H)("BABYLON.ScaleBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("input",th.AutoDetect),this.registerInput("factor",th.Float),this.registerOutput("output",th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName}; -`,this}});class fP extends sJ{constructor(e){super(e,tu.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",th.AutoDetect),this.registerOutput("output",th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)}); -`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; -`+`${this._codeVariableName}.maximum = ${this.maximum}; -`}serialize(){let 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,r0.gn)([s2("Minimum",tp.Float)],fP.prototype,"minimum",void 0),(0,r0.gn)([s2("Maximum",tp.Float)],fP.prototype,"maximum",void 0),(0,rn.H)("BABYLON.ClampBlock",fP),(0,rn.H)("BABYLON.CrossBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerOutput("output",th.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(th.Float),this._inputs[0].excludedConnectionPointTypes.push(th.Matrix),this._inputs[0].excludedConnectionPointTypes.push(th.Vector2),this._inputs[1].excludedConnectionPointTypes.push(th.Float),this._inputs[1].excludedConnectionPointTypes.push(th.Matrix),this._inputs[1].excludedConnectionPointTypes.push(th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz); -`,this}}),(0,rn.H)("BABYLON.CustomBlock",class extends sJ{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)}),this._outputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)}),e._emitFunction(i,t,""),this._outputs.forEach(t=>{e.compilationString+=this._declareOutput(t,e)+";\n"}),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach((t,i)=>{var s,n,a;i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=null!==(a=null===(n=null===(s=t.connectedPoint)||void 0===s?void 0:s.ownerBlock)||void 0===n?void 0:n.samplerName)&&void 0!==a?a:t.associatedVariableName:e.compilationString+=t.associatedVariableName,r=!0}),this._outputs.forEach((t,i)=>{(i>0||r)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName}),e.compilationString+=");\n",this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.options = ${JSON.stringify(this._options)}; -`}serialize(){let 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,r;this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=tu[e.target],null===(t=e.inParameters)||void 0===t||t.forEach((e,t)=>{let i=th[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,th.Object,!0,tu.VertexAndFragment,new fv(e.name,this,td.Input,fy,"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,th[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===(r=e.inLinkedConnectionTypes)||void 0===r||r.forEach(e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t<this._inputs.length;t++)if(this._inputs[t].name===e)return[this._inputs[t],t];return null}}),(0,rn.H)("BABYLON.DotBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerOutput("output",th.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(th.Float),this._inputs[0].excludedConnectionPointTypes.push(th.Matrix),this._inputs[1].excludedConnectionPointTypes.push(th.Float),this._inputs[1].excludedConnectionPointTypes.push(th.Matrix)}getClassName(){return"DotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = dot(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.NormalizeBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("input",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(th.Float),this._inputs[0].excludedConnectionPointTypes.push(th.Matrix)}getClassName(){return"NormalizeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${i.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.ColorMergerBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.rSwizzle="r",this.gSwizzle="g",this.bSwizzle="b",this.aSwizzle="a",this.registerInput("rgb ",th.Color3,!0),this.registerInput("r",th.Float,!0),this.registerInput("g",th.Float,!0),this.registerInput("b",th.Float,!0),this.registerInput("a",th.Float,!0),this.registerOutput("rgba",th.Color4),this.registerOutput("rgb",th.Color3)}getClassName(){return"ColorMergerBlock"}get rgbIn(){return this._inputs[0]}get r(){return this._inputs[1]}get g(){return this._inputs[2]}get b(){return this._inputs[3]}get a(){return this._inputs[4]}get rgba(){return this._outputs[0]}get rgbOut(){return this._outputs[1]}get rgb(){return this.rgbOut}_inputRename(e){return"rgb "===e?"rgbIn":e}_buildSwizzle(e){let t=this.rSwizzle+this.gSwizzle+this.bSwizzle+this.aSwizzle;return"."+t.substr(0,e)}_buildBlock(e){super._buildBlock(e);let t=this.r,i=this.g,r=this.b,s=this.a,n=this.rgbIn,a=this._outputs[0],o=this._outputs[1];return n.isConnected?(a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec4(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${n.associatedVariableName}${this._buildSwizzle(3)}; -`)):(a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; -`)),this}serialize(){let e=super.serialize();return e.rSwizzle=this.rSwizzle,e.gSwizzle=this.gSwizzle,e.bSwizzle=this.bSwizzle,e.aSwizzle=this.aSwizzle,e}_deserialize(e,t,i){var r,s,n,a;super._deserialize(e,t,i),this.rSwizzle=null!==(r=e.rSwizzle)&&void 0!==r?r:"r",this.gSwizzle=null!==(s=e.gSwizzle)&&void 0!==s?s:"g",this.bSwizzle=null!==(n=e.bSwizzle)&&void 0!==n?n:"b",this.aSwizzle=null!==(a=e.aSwizzle)&&void 0!==a?a:"a"}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.rSwizzle = "${this.rSwizzle}"; -${this._codeVariableName}.gSwizzle = "${this.gSwizzle}"; -${this._codeVariableName}.bSwizzle = "${this.bSwizzle}"; -${this._codeVariableName}.aSwizzle = "${this.aSwizzle}"; -`}}),(0,rn.H)("BABYLON.VectorSplitterBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("xyzw",th.Vector4,!0),this.registerInput("xyz ",th.Vector3,!0),this.registerInput("xy ",th.Vector2,!0),this.registerOutput("xyz",th.Vector3),this.registerOutput("xy",th.Vector2),this.registerOutput("zw",th.Vector2),this.registerOutput("x",th.Float),this.registerOutput("y",th.Float),this.registerOutput("z",th.Float),this.registerOutput("w",th.Float),this.inputsAreExclusive=!0}getClassName(){return"VectorSplitterBlock"}get xyzw(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get xyzOut(){return this._outputs[0]}get xyOut(){return this._outputs[1]}get zw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get w(){return this._outputs[6]}_inputRename(e){switch(e){case"xy ":return"xyIn";case"xyz ":return"xyzIn";default:return e}}_outputRename(e){switch(e){case"xy":return"xyOut";case"xyz":return"xyzOut";default:return e}}_buildBlock(e){super._buildBlock(e);let t=this.xyzw.isConnected?this.xyzw:this.xyzIn.isConnected?this.xyzIn:this.xyIn,i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],n=this._outputs[3],a=this._outputs[4],o=this._outputs[5],l=this._outputs[6];return i.hasEndpoints&&(t===this.xyIn?e.compilationString+=this._declareOutput(i,e)+` = vec3(${t.associatedVariableName}, 0.0); -`:e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.xyz; -`),s.hasEndpoints&&this.xyzw.isConnected&&(e.compilationString+=this._declareOutput(s,e)+` = ${this.xyzw.associatedVariableName}.zw; -`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.xy; -`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.x; -`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.y; -`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.z; -`),l.hasEndpoints&&(e.compilationString+=this._declareOutput(l,e)+` = ${t.associatedVariableName}.w; -`),this}}),(0,rn.H)("BABYLON.LerpBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerInput("gradient",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(th.Float)}getClassName(){return"LerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.DivideBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(th.Float),this._inputs[1].acceptedConnectionPointTypes.push(th.Float)}getClassName(){return"DivideBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} / ${this.right.associatedVariableName}; -`,this}}),(0,rn.H)("BABYLON.SubtractBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(th.Float),this._inputs[1].acceptedConnectionPointTypes.push(th.Float)}getClassName(){return"SubtractBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} - ${this.right.associatedVariableName}; -`,this}}),(0,rn.H)("BABYLON.StepBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("value",th.Float),this.registerInput("edge",th.Float),this.registerOutput("output",th.Float)}getClassName(){return"StepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = step(${this.edge.associatedVariableName}, ${this.value.associatedVariableName}); -`,this}});class fI extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("input",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[0].excludedConnectionPointTypes.push(th.Matrix)}getClassName(){return"OneMinusBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = 1. - ${this.input.associatedVariableName}; -`,this}}(0,rn.H)("BABYLON.OneMinusBlock",fI),(0,rn.H)("BABYLON.OppositeBlock",fI);class fM extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("worldPosition",th.Vector4),this.registerInput("cameraPosition",th.Vector3),this.registerOutput("output",th.Vector3)}getClassName(){return"ViewDirectionBlock"}get worldPosition(){return this._inputs[0]}get cameraPosition(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(e){if(!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate(e=>e.systemValue===tf.CameraPosition);t||(t=new ne("cameraPosition")).setAsSystemValue(tf.CameraPosition),t.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz); -`,this}}(0,rn.H)("BABYLON.ViewDirectionBlock",fM),(0,rn.H)("BABYLON.FresnelBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("worldNormal",th.Vector4),this.registerInput("viewDirection",th.Vector3),this.registerInput("bias",th.Float),this.registerInput("power",th.Float),this.registerOutput("fresnel",th.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){let t=new fM("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){let e=new ne("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){let e=new ne("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);let 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}); -`,this}}),(0,rn.H)("BABYLON.MaxBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerOutput("output",th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.MinBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerOutput("output",th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.DistanceBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerOutput("output",th.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(th.Float),this._inputs[0].excludedConnectionPointTypes.push(th.Matrix),this._inputs[1].excludedConnectionPointTypes.push(th.Float),this._inputs[1].excludedConnectionPointTypes.push(th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.LengthBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("value",th.AutoDetect),this.registerOutput("output",th.Float),this._inputs[0].excludedConnectionPointTypes.push(th.Float),this._inputs[0].excludedConnectionPointTypes.push(th.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.NegateBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("value",th.AutoDetect),this.registerOutput("output",th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName}; -`,this}}),(0,rn.H)("BABYLON.PowBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("value",th.AutoDetect),this.registerInput("power",th.AutoDetect),this.registerOutput("output",th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.RandomNumberBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("seed",th.AutoDetect),this.registerOutput("output",th.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Vector2|th.Vector3|th.Vector4|th.Color3|th.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy); -`,this}}),(0,rn.H)("BABYLON.ArcTan2Block",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("x",th.Float),this.registerInput("y",th.Float),this.registerOutput("output",th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.SmoothStepBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("value",th.AutoDetect),this.registerInput("edge0",th.Float),this.registerInput("edge1",th.Float),this.registerOutput("output",th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.ReciprocalBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("input",th.AutoDetect),this.registerOutput("output",th.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);let t=this._outputs[0];return this.input.type===th.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); -`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName}; -`,this}}),(0,rn.H)("BABYLON.ReplaceColorBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("value",th.AutoDetect),this.registerInput("reference",th.AutoDetect),this.registerInput("distance",th.Float),this.registerInput("replacement",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(th.Float),this._inputs[0].excludedConnectionPointTypes.push(th.Matrix),this._inputs[1].excludedConnectionPointTypes.push(th.Float),this._inputs[1].excludedConnectionPointTypes.push(th.Matrix),this._inputs[3].excludedConnectionPointTypes.push(th.Float),this._inputs[3].excludedConnectionPointTypes.push(th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+`; -`,e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) { -`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName}; -`,e.compilationString+=`} else { -`,e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName}; -`,e.compilationString+=`} -`,this}}),(0,rn.H)("BABYLON.PosterizeBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("value",th.AutoDetect),this.registerInput("steps",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(th.Matrix),this._inputs[1].excludedConnectionPointTypes.push(th.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);let 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}); -`,this}}),(eD=iy||(iy={}))[eD.SawTooth=0]="SawTooth",eD[eD.Square=1]="Square",eD[eD.Triangle=2]="Triangle",(0,rn.H)("BABYLON.WaveBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.kind=iy.SawTooth,this.registerInput("input",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(th.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];switch(this.kind){case iy.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); -`;break;case iy.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); -`;break;case iy.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0; -`}return this}serialize(){let e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}});class fD{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,rn.H)("BABYLON.GradientBlock",class extends sJ{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,tu.Neutral),this.colorSteps=[new fD(0,rs.Wo.Black()),new fD(1,rs.Wo.White())],this.onValueChangedObservable=new ri.y$,this.registerInput("gradient",th.AutoDetect),this.registerOutput("output",th.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Float|th.Vector2|th.Vector3|th.Vector4|th.Color3|th.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){let t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=this._declareOutput(t,e)+` = vec3(0., 0., 0.); -`;return}let i=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)}; -`,e.compilationString+=`float ${r}; -`;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==th.Float&&(s+=".x");for(let t=1;t<this.colorSteps.length;t++){let n=this.colorSteps[t],a=this.colorSteps[t-1];e.compilationString+=`${r} = clamp((${s} - ${e._emitFloat(a.step)}) / (${e._emitFloat(n.step)} - ${e._emitFloat(a.step)}), 0.0, 1.0) * step(${e._emitFloat(t)}, ${e._emitFloat(this.colorSteps.length-1)}); -`,e.compilationString+=`${i} = mix(${i}, ${this._writeColorConstant(t)}, ${r}); -`}return e.compilationString+=this._declareOutput(t,e)+` = ${i}; -`,this}serialize(){let e=super.serialize();for(let t of(e.colorSteps=[],this.colorSteps))e.colorSteps.push({step:t.step,color:{r:t.color.r,g:t.color.g,b:t.color.b}});return e}_deserialize(e,t,i){for(let r of(super._deserialize(e,t,i),this.colorSteps.length=0,e.colorSteps))this.colorSteps.push(new fD(r.step,new rs.Wo(r.color.r,r.color.g,r.color.b)))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();for(let t of(e+=`${this._codeVariableName}.colorSteps = []; -`,this.colorSteps))e+=`${this._codeVariableName}.colorSteps.push(new BABYLON.GradientBlockColorStep(${t.step}, new BABYLON.Color3(${t.color.r}, ${t.color.g}, ${t.color.b}))); -`;return e}}),(0,rn.H)("BABYLON.NLerpBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerInput("gradient",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(1,2,!0),this._inputs[2].acceptedConnectionPointTypes.push(th.Float)}getClassName(){return"NLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName})); -`,this}});class fO extends sJ{constructor(e){super(e,tu.Neutral),this.manhattanDistance=!1,this.registerInput("seed",th.Vector3),this.registerInput("jitter",th.Float),this.registerOutput("output",th.Vector2),this.registerOutput("x",th.Float),this.registerOutput("y",th.Float)}getClassName(){return"WorleyNoise3DBlock"}get seed(){return this._inputs[0]}get jitter(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected||!this.output.hasEndpoints&&!this.x.hasEndpoints&&!this.y.hasEndpoints)return;let t=`vec3 permute(vec3 x){ -`;t+=` return mod((34.0 * x + 1.0) * x, 289.0); -} - -vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){ - return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z); -} - -vec2 worley(vec3 P, float jitter, bool manhattanDistance){ - float K = 0.142857142857; // 1/7 - float Ko = 0.428571428571; // 1/2-K/2 - float K2 = 0.020408163265306; // 1/(7*7) - float Kz = 0.166666666667; // 1/6 - float Kzo = 0.416666666667; // 1/2-1/6*2 - - vec3 Pi = mod(floor(P), 289.0); - vec3 Pf = fract(P) - 0.5; - - vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0); - vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0); - vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0); - - vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0)); - vec3 p1 = permute(p + Pi.y - 1.0); - vec3 p2 = permute(p + Pi.y); - vec3 p3 = permute(p + Pi.y + 1.0); - - vec3 p11 = permute(p1 + Pi.z - 1.0); - vec3 p12 = permute(p1 + Pi.z); - vec3 p13 = permute(p1 + Pi.z + 1.0); - - vec3 p21 = permute(p2 + Pi.z - 1.0); - vec3 p22 = permute(p2 + Pi.z); - vec3 p23 = permute(p2 + Pi.z + 1.0); - - vec3 p31 = permute(p3 + Pi.z - 1.0); - vec3 p32 = permute(p3 + Pi.z); - vec3 p33 = permute(p3 + Pi.z + 1.0); - - vec3 ox11 = fract(p11*K) - Ko; - vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko; - vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed - - vec3 ox12 = fract(p12*K) - Ko; - vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko; - vec3 oz12 = floor(p12*K2)*Kz - Kzo; - - vec3 ox13 = fract(p13*K) - Ko; - vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko; - vec3 oz13 = floor(p13*K2)*Kz - Kzo; - - vec3 ox21 = fract(p21*K) - Ko; - vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko; - vec3 oz21 = floor(p21*K2)*Kz - Kzo; - - vec3 ox22 = fract(p22*K) - Ko; - vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko; - vec3 oz22 = floor(p22*K2)*Kz - Kzo; - - vec3 ox23 = fract(p23*K) - Ko; - vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko; - vec3 oz23 = floor(p23*K2)*Kz - Kzo; - - vec3 ox31 = fract(p31*K) - Ko; - vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko; - vec3 oz31 = floor(p31*K2)*Kz - Kzo; - - vec3 ox32 = fract(p32*K) - Ko; - vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko; - vec3 oz32 = floor(p32*K2)*Kz - Kzo; - - vec3 ox33 = fract(p33*K) - Ko; - vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko; - vec3 oz33 = floor(p33*K2)*Kz - Kzo; - - vec3 dx11 = Pfx + jitter*ox11; - vec3 dy11 = Pfy.x + jitter*oy11; - vec3 dz11 = Pfz.x + jitter*oz11; - - vec3 dx12 = Pfx + jitter*ox12; - vec3 dy12 = Pfy.x + jitter*oy12; - vec3 dz12 = Pfz.y + jitter*oz12; - - vec3 dx13 = Pfx + jitter*ox13; - vec3 dy13 = Pfy.x + jitter*oy13; - vec3 dz13 = Pfz.z + jitter*oz13; - - vec3 dx21 = Pfx + jitter*ox21; - vec3 dy21 = Pfy.y + jitter*oy21; - vec3 dz21 = Pfz.x + jitter*oz21; - - vec3 dx22 = Pfx + jitter*ox22; - vec3 dy22 = Pfy.y + jitter*oy22; - vec3 dz22 = Pfz.y + jitter*oz22; - - vec3 dx23 = Pfx + jitter*ox23; - vec3 dy23 = Pfy.y + jitter*oy23; - vec3 dz23 = Pfz.z + jitter*oz23; - - vec3 dx31 = Pfx + jitter*ox31; - vec3 dy31 = Pfy.z + jitter*oy31; - vec3 dz31 = Pfz.x + jitter*oz31; - - vec3 dx32 = Pfx + jitter*ox32; - vec3 dy32 = Pfy.z + jitter*oy32; - vec3 dz32 = Pfz.y + jitter*oz32; - - vec3 dx33 = Pfx + jitter*ox33; - vec3 dy33 = Pfy.z + jitter*oy33; - vec3 dz33 = Pfz.z + jitter*oz33; - - vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance); - vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance); - vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance); - vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance); - vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance); - vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance); - vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance); - vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance); - vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance); - - vec3 d1a = min(d11, d12); - d12 = max(d11, d12); - d11 = min(d1a, d13); // Smallest now not in d12 or d13 - d13 = max(d1a, d13); - d12 = min(d12, d13); // 2nd smallest now not in d13 - vec3 d2a = min(d21, d22); - d22 = max(d21, d22); - d21 = min(d2a, d23); // Smallest now not in d22 or d23 - d23 = max(d2a, d23); - d22 = min(d22, d23); // 2nd smallest now not in d23 - vec3 d3a = min(d31, d32); - d32 = max(d31, d32); - d31 = min(d3a, d33); // Smallest now not in d32 or d33 - d33 = max(d3a, d33); - d32 = min(d32, d33); // 2nd smallest now not in d33 - vec3 da = min(d11, d21); - d21 = max(d11, d21); - d11 = min(da, d31); // Smallest now in d11 - d31 = max(da, d31); // 2nd smallest now not in d31 - d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx; - d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest - d12 = min(d12, d21); // 2nd smallest now not in d21 - d12 = min(d12, d22); // nor in d22 - d12 = min(d12, d31); // nor in d31 - d12 = min(d12, d32); // nor in d32 - d11.yz = min(d11.yz,d12.xy); // nor in d12.yz - d11.y = min(d11.y,d12.z); // Only two more to go - d11.y = min(d11.y,d11.z); // Done! (Phew!) - return sqrt(d11.xy); // F1, F2 -} - -`,e._emitFunction("worley3D",t,"// Worley3D");let i=e._getFreeVariableName("worleyTemp");return e.compilationString+=`vec2 ${i} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance}); -`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; -`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${i}.x; -`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${i}.y; -`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance}; -`;return e}serialize(){let e=super.serialize();return e.manhattanDistance=this.manhattanDistance,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.manhattanDistance=e.manhattanDistance}}(0,r0.gn)([s2("Use Manhattan Distance",tp.Boolean,"PROPERTIES",{notifiers:{update:!1}})],fO.prototype,"manhattanDistance",void 0),(0,rn.H)("BABYLON.WorleyNoise3DBlock",fO),(0,rn.H)("BABYLON.SimplexPerlin3DBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("seed",th.Vector3),this.registerOutput("output",th.Float)}getClassName(){return"SimplexPerlin3DBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;let t=`const float SKEWFACTOR = 1.0/3.0; -`;return t+=`const float UNSKEWFACTOR = 1.0/6.0; -const float SIMPLEX_CORNER_POS = 0.5; -const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485; -float SimplexPerlin3D( vec3 P ){ - P.x = P == vec3(0., 0., 0.) ? 0.00001 : P.x; - P *= SIMPLEX_TETRAHADRON_HEIGHT; - vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) ); vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) ); - vec3 g = step(x0.yzx, x0.xyz); - vec3 l = 1.0 - g; - vec3 Pi_1 = min( g.xyz, l.zxy ); - vec3 Pi_2 = max( g.xyz, l.zxy ); - vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR; - vec3 x2 = x0 - Pi_2 + SKEWFACTOR; - vec3 x3 = x0 - SIMPLEX_CORNER_POS; - vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x ); - vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y ); - vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z ); - Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0; - vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 ); - vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy; - Pt *= Pt; - vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) ); - Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w ); - const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 ); - const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 ); - vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) ); - vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) ); - Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods; - Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods; - vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999; - vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999; - vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999; - 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 ); - const float FINAL_NORMALIZATION = 37.837227241611314102871574478976; - vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z; - kernel_weights = max(0.5 - kernel_weights, 0.0); - kernel_weights = kernel_weights*kernel_weights*kernel_weights; - return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION; -} -`,e._emitFunction("SimplexPerlin3D",t,"// SimplexPerlin3D"),e.compilationString+=this._declareOutput(this._outputs[0],e)+` = SimplexPerlin3D(${this.seed.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.NormalBlendBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("normalMap0",th.AutoDetect),this.registerInput("normalMap1",th.AutoDetect),this.registerOutput("output",th.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Color4|th.Vector3|th.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Color4|th.Vector3|th.Vector4)}getClassName(){return"NormalBlendBlock"}get normalMap0(){return this._inputs[0]}get normalMap1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0],r=this._inputs[1],s=e._getFreeVariableName("stepR"),n=e._getFreeVariableName("stepG");return e.compilationString+=`float ${s} = step(0.5, ${i.associatedVariableName}.r); -`,e.compilationString+=`float ${n} = step(0.5, ${i.associatedVariableName}.g); -`,e.compilationString+=this._declareOutput(t,e)+`; -`,e.compilationString+=`${t.associatedVariableName}.r = (1.0 - ${s}) * ${i.associatedVariableName}.r * ${r.associatedVariableName}.r * 2.0 + ${s} * (1.0 - (1.0 - ${i.associatedVariableName}.r) * (1.0 - ${r.associatedVariableName}.r) * 2.0); -`,e.compilationString+=`${t.associatedVariableName}.g = (1.0 - ${n}) * ${i.associatedVariableName}.g * ${r.associatedVariableName}.g * 2.0 + ${n} * (1.0 - (1.0 - ${i.associatedVariableName}.g) * (1.0 - ${r.associatedVariableName}.g) * 2.0); -`,e.compilationString+=`${t.associatedVariableName}.b = ${i.associatedVariableName}.b * ${r.associatedVariableName}.b; -`,this}}),(0,rn.H)("BABYLON.Rotate2dBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("input",th.Vector2),this.registerInput("angle",th.Float),this.registerOutput("output",th.Vector2)}getClassName(){return"Rotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new ne("angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.angle,r=this.input;return e.compilationString+=this._declareOutput(t,e)+` = vec2(cos(${i.associatedVariableName}) * ${r.associatedVariableName}.x - sin(${i.associatedVariableName}) * ${r.associatedVariableName}.y, sin(${i.associatedVariableName}) * ${r.associatedVariableName}.x + cos(${i.associatedVariableName}) * ${r.associatedVariableName}.y); -`,this}}),(0,rn.H)("BABYLON.ReflectBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("incident",th.AutoDetect),this.registerInput("normal",th.AutoDetect),this.registerOutput("output",th.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Vector3|th.Vector4|th.Color3|th.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(th.Vector3|th.Vector4|th.Color3|th.Color4)}getClassName(){return"ReflectBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz); -`,this}}),(0,rn.H)("BABYLON.RefractBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("incident",th.AutoDetect),this.registerInput("normal",th.AutoDetect),this.registerInput("ior",th.Float),this.registerOutput("output",th.Vector3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Vector3|th.Vector4|th.Color3|th.Color4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(th.Vector3|th.Vector4|th.Color3|th.Color4)}getClassName(){return"RefractBlock"}get incident(){return this._inputs[0]}get normal(){return this._inputs[1]}get ior(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.DesaturateBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("color",th.Color3),this.registerInput("level",th.Float),this.registerOutput("output",th.Color3)}getClassName(){return"DesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.color,r=i.associatedVariableName,s=e._getFreeVariableName("colorMin"),n=e._getFreeVariableName("colorMax"),a=e._getFreeVariableName("colorMerge");return e.compilationString+=`float ${s} = min(min(${r}.x, ${r}.y), ${r}.z); -`,e.compilationString+=`float ${n} = max(max(${r}.x, ${r}.y), ${r}.z); -`,e.compilationString+=`float ${a} = 0.5 * (${s} + ${n}); -`,e.compilationString+=this._declareOutput(t,e)+` = mix(${r}, vec3(${a}, ${a}, ${a}), ${this.level.associatedVariableName}); -`,this}});class fN extends sJ{constructor(e){super(e,tu.Fragment),this.albedoScaling=!1,this.linkSheenWithAlbedo=!1,this._isUnique=!0,this.registerInput("intensity",th.Float,!0,tu.Fragment),this.registerInput("color",th.Color3,!0,tu.Fragment),this.registerInput("roughness",th.Float,!0,tu.Fragment),this.registerOutput("sheen",th.Object,tu.Fragment,new fv("sheen",this,td.Output,fN,"SheenBlock"))}initialize(e){e._excludeVariableName("sheenOut"),e._excludeVariableName("sheenMapData"),e._excludeVariableName("vSheenColor"),e._excludeVariableName("vSheenRoughness")}getClassName(){return"SheenBlock"}get intensity(){return this._inputs[0]}get color(){return this._inputs[1]}get roughness(){return this._inputs[2]}get sheen(){return this._outputs[0]}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("SHEEN",!0),i.setValue("SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("SHEEN_LINKWITHALBEDO",this.linkSheenWithAlbedo,!0),i.setValue("SHEEN_ROUGHNESS",this.roughness.isConnected,!0),i.setValue("SHEEN_ALBEDOSCALING",this.albedoScaling,!0)}getCode(e){let t=this.color.isConnected?this.color.associatedVariableName:"vec3(1.)",i=this.intensity.isConnected?this.intensity.associatedVariableName:"1.",r=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return`#ifdef SHEEN - sheenOutParams sheenOut; - - vec4 vSheenColor = vec4(${t}, ${i}); - - sheenBlock( - vSheenColor, - #ifdef SHEEN_ROUGHNESS - ${r}, - #endif - roughness, - #ifdef SHEEN_TEXTURE - vec4(0.), - 1.0, - #endif - reflectance, - #ifdef SHEEN_LINKWITHALBEDO - baseColor, - surfaceAlbedo, - #endif - #ifdef ENVIRONMENTBRDF - NdotV, - environmentBrdf, - #endif - #if defined(REFLECTION) && defined(ENVIRONMENTBRDF) - AARoughnessFactors, - ${null==e?void 0:e._vReflectionMicrosurfaceInfosName}, - ${null==e?void 0:e._vReflectionInfosName}, - ${null==e?void 0:e.reflectionColor}, - vLightingIntensity, - #ifdef ${null==e?void 0:e._define3DName} - ${null==e?void 0:e._cubeSamplerName}, - #else - ${null==e?void 0:e._2DSamplerName}, - #endif - reflectionOut.reflectionCoords, - NdotVUnclamped, - #ifndef LODBASEDMICROSFURACE - #ifdef ${null==e?void 0:e._define3DName} - ${null==e?void 0:e._cubeSamplerName}, - ${null==e?void 0:e._cubeSamplerName}, - #else - ${null==e?void 0:e._2DSamplerName}, - ${null==e?void 0:e._2DSamplerName}, - #endif - #endif - #if !defined(${null==e?void 0:e._defineSkyboxName}) && defined(RADIANCEOCCLUSION) - seo, - #endif - #if !defined(${null==e?void 0:e._defineSkyboxName}) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(${null==e?void 0:e._define3DName}) - eho, - #endif - #endif - sheenOut - ); - - #ifdef SHEEN_LINKWITHALBEDO - surfaceAlbedo = sheenOut.surfaceAlbedo; - #endif - #endif -`}_buildBlock(e){return e.target===tu.Fragment&&e.sharedData.blocksWithDefines.push(this),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.albedoScaling = ${this.albedoScaling}; -${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo}; -`}serialize(){let e=super.serialize();return e.albedoScaling=this.albedoScaling,e.linkSheenWithAlbedo=this.linkSheenWithAlbedo,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.albedoScaling=e.albedoScaling,this.linkSheenWithAlbedo=e.linkSheenWithAlbedo}}(0,r0.gn)([s2("Albedo scaling",tp.Boolean,"PROPERTIES",{notifiers:{update:!0}})],fN.prototype,"albedoScaling",void 0),(0,r0.gn)([s2("Link sheen with albedo",tp.Boolean,"PROPERTIES",{notifiers:{update:!0}})],fN.prototype,"linkSheenWithAlbedo",void 0),(0,rn.H)("BABYLON.SheenBlock",fN);class fF extends sJ{constructor(e){super(e,tu.Fragment),this._tangentCorrectionFactorName="",this._isUnique=!0,this.registerInput("intensity",th.Float,!0,tu.Fragment),this.registerInput("direction",th.Vector2,!0,tu.Fragment),this.registerInput("uv",th.Vector2,!0),this.registerInput("worldTangent",th.Vector4,!0),this.registerInput("TBN",th.Object,!0,tu.VertexAndFragment,new fv("TBN",this,td.Input,fS,"TBNBlock")),this.registerInput("roughness",th.Float,!0,tu.Fragment),this.registerOutput("anisotropy",th.Object,tu.Fragment,new fv("anisotropy",this,td.Output,fF,"AnisotropyBlock"))}initialize(e){e._excludeVariableName("anisotropicOut"),e._excludeVariableName("TBN")}getClassName(){return"AnisotropyBlock"}get intensity(){return this._inputs[0]}get direction(){return this._inputs[1]}get uv(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get TBN(){return this._inputs[4]}get roughness(){return this._inputs[5]}get anisotropy(){return this._outputs[0]}_generateTBNSpace(e){let t="",i=`//${this.name}`,r=this.uv,s=this.worldPositionConnectionPoint,n=this.worldNormalConnectionPoint,a=this.worldTangent;r.isConnected||console.error("You must connect the 'uv' input of the Anisotropy block!"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let o={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},l=this.TBN;return l.isConnected?e.compilationString+=` - #ifdef TBNBLOCK - mat3 vTBN = ${l.associatedVariableName}; - #endif - `:a.isConnected&&(t+=`vec3 tbnNormal = normalize(${n.associatedVariableName}.xyz); -vec3 tbnTangent = normalize(${a.associatedVariableName}.xyz); -vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; -mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); -`),t+=` - #if defined(${a.isConnected?"TANGENT":"IGNORE"}) && defined(NORMAL) - mat3 TBN = vTBN; - #else - mat3 TBN = cotangent_frame(${n.associatedVariableName+".xyz"}, ${"v_"+s.associatedVariableName+".xyz"}, ${r.isConnected?r.associatedVariableName:"vec2(0.)"}, vec2(1., 1.)); - #endif -`,e._emitFunctionFromInclude("bumpFragmentMainFunctions",i,{replaceStrings:[o]}),t}getCode(e,t=!1){let i="";t&&(i+=this._generateTBNSpace(e));let r=this.intensity.isConnected?this.intensity.associatedVariableName:"1.0",s=this.direction.isConnected?this.direction.associatedVariableName:"vec2(1., 0.)",n=this.roughness.isConnected?this.roughness.associatedVariableName:"0.";return i+`anisotropicOutParams anisotropicOut; - anisotropicBlock( - vec3(${s}, ${r}), - ${n}, - #ifdef ANISOTROPIC_TEXTURE - vec3(0.), - #endif - TBN, - normalW, - viewDirectionW, - anisotropicOut - ); -`}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("ANISOTROPIC",!0),i.setValue("ANISOTROPIC_TEXTURE",!1,!0),i.setValue("ANISOTROPIC_LEGACY",!this.roughness.isConnected)}bind(e,t,i){super.bind(e,t,i),i&&e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1)}_buildBlock(e){return e.target===tu.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}}(0,rn.H)("BABYLON.AnisotropyBlock",fF);class fL extends fA{_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._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?tu.Fragment:tu.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",th.AutoDetect,!1,tu.Vertex),this.registerInput("world",th.Matrix,!1,tu.Vertex),this.registerInput("color",th.Color3,!0,tu.Fragment),this.registerOutput("reflection",th.Object,tu.Fragment,new fv("reflection",this,td.Output,fL,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Vector3|th.Vector4)}getClassName(){return"ReflectionBlock"}get position(){return this._inputs[0]}get worldPosition(){return this.worldPositionConnectionPoint}get worldNormal(){return this.worldNormalConnectionPoint}get world(){return this._inputs[1]}get cameraPosition(){return this.cameraPositionConnectionPoint}get view(){return this.viewConnectionPoint}get color(){return this._inputs[2]}get reflection(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}get reflectionColor(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("REFLECTION",s,!0),s&&(i.setValue(this._defineLODReflectionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!r.invertZ:r.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",r.gammaSpace,!0),i.setValue("RGBDREFLECTION",r.isRGBD,!0),r&&r.coordinatesMode!==sv.SKYBOX_MODE&&r.isCube&&(i.setValue("USESPHERICALFROMREFLECTIONMAP",!0),i.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?i.setValue("USESPHERICALINVERTEX",!1):i.setValue("USESPHERICALINVERTEX",!0)))}bind(e,t,i,r){super.bind(e,t,i);let s=this._getTexture();if(!s||!r)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s);let n=s.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,n,s.lodGenerationScale,s.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,n,rm.R.Log2(n));let a=r.materialDefines,o=s.sphericalPolynomial;if(a.USESPHERICALFROMREFLECTIONMAP&&o){if(a.SPHERICAL_HARMONICS){let t=o.preScaledHarmonics;e.setVector3("vSphericalL00",t.l00),e.setVector3("vSphericalL1_1",t.l1_1),e.setVector3("vSphericalL10",t.l10),e.setVector3("vSphericalL11",t.l11),e.setVector3("vSphericalL2_2",t.l2_2),e.setVector3("vSphericalL2_1",t.l2_1),e.setVector3("vSphericalL20",t.l20),e.setVector3("vSphericalL21",t.l21),e.setVector3("vSphericalL22",t.l22)}else e.setFloat3("vSphericalX",o.x.x,o.x.y,o.x.z),e.setFloat3("vSphericalY",o.y.x,o.y.y,o.y.z),e.setFloat3("vSphericalZ",o.z.x,o.z.y,o.z.z),e.setFloat3("vSphericalXX_ZZ",o.xx.x-o.zz.x,o.xx.y-o.zz.y,o.xx.z-o.zz.z),e.setFloat3("vSphericalYY_ZZ",o.yy.x-o.zz.x,o.yy.y-o.zz.y,o.yy.z-o.zz.z),e.setFloat3("vSphericalZZ",o.zz.x,o.zz.y,o.zz.z),e.setFloat3("vSphericalXY",o.xy.x,o.xy.y,o.xy.z),e.setFloat3("vSphericalYZ",o.yz.x,o.yz.y,o.yz.z),e.setFloat3("vSphericalZX",o.zx.x,o.zx.y,o.zx.z)}}handleVertexSide(e){let t=super.handleVertexSide(e);e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});let i=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,"vec3","defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX","vec3","SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) - vec3 ${i} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; - #ifdef ${this._defineOppositeZ} - ${i}.z *= -1.0; - #endif - ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${i}); - #endif -`}getCode(e,t){let i="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection",` - #ifdef ${this._define3DName} - #define sampleReflection(s, c) textureCube(s, c) - #else - #define sampleReflection(s, c) texture2D(s, c) - #endif -`,`//${this.name}`),e._emitFunction("sampleReflectionLod",` - #ifdef ${this._define3DName} - #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l) - #else - #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l) - #endif -`,`//${this.name}`);let r=` - vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) { - ${this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0,!0)} - return ${this._reflectionVectorName}; - } -`;return e._emitFunction("computeReflectionCoordsPBR",r,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,"vec3"),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,"vec2"),i+=`#ifdef REFLECTION - vec2 ${this._vReflectionInfosName} = vec2(1., 0.); - - reflectionOutParams reflectionOut; - - reflectionBlock( - ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName}.xyz, - ${t}, - alphaG, - ${this._vReflectionMicrosurfaceInfosName}, - ${this._vReflectionInfosName}, - ${this.reflectionColor}, - #ifdef ANISOTROPIC - anisotropicOut, - #endif - #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName}) - NdotVUnclamped, - #endif - #ifdef ${this._defineLinearSpecularReflection} - roughness, - #endif - #ifdef ${this._define3DName} - ${this._cubeSamplerName}, - #else - ${this._2DSamplerName}, - #endif - #if defined(NORMAL) && defined(USESPHERICALINVERTEX) - ${this._vEnvironmentIrradianceName}, - #endif - #ifdef USESPHERICALFROMREFLECTIONMAP - #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) - ${this._reflectionMatrixName}, - #endif - #endif - #ifdef USEIRRADIANCEMAP - irradianceSampler, // ** not handled ** - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${this._define3DName} - ${this._cubeSamplerName}, - ${this._cubeSamplerName}, - #else - ${this._2DSamplerName}, - ${this._2DSamplerName}, - #endif - #endif - #ifdef REALTIME_FILTERING - ${this._vReflectionFilteringInfoName}, - #endif - reflectionOut - ); - #endif -`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==tu.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace}; -`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics}; -${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment}; -`}serialize(){var e,t;let i=super.serialize();return i.useSphericalHarmonics=this.useSphericalHarmonics,i.forceIrradianceInFragment=this.forceIrradianceInFragment,i.gammaSpace=null===(t=null===(e=this.texture)||void 0===e?void 0:e.gammaSpace)||void 0===t||t,i}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}}(0,r0.gn)([s2("Spherical Harmonics",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fL.prototype,"useSphericalHarmonics",void 0),(0,r0.gn)([s2("Force irradiance in fragment",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fL.prototype,"forceIrradianceInFragment",void 0),(0,rn.H)("BABYLON.ReflectionBlock",fL);class fw extends sJ{constructor(e){super(e,tu.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",th.Float,!1,tu.Fragment),this.registerInput("roughness",th.Float,!0,tu.Fragment),this.registerInput("indexOfRefraction",th.Float,!0,tu.Fragment),this.registerInput("normalMapColor",th.Color3,!0,tu.Fragment),this.registerInput("uv",th.Vector2,!0,tu.Fragment),this.registerInput("tintColor",th.Color3,!0,tu.Fragment),this.registerInput("tintAtDistance",th.Float,!0,tu.Fragment),this.registerInput("tintThickness",th.Float,!0,tu.Fragment),this.registerInput("worldTangent",th.Vector4,!0),this.registerInput("worldNormal",th.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(th.Color4|th.Vector4|th.Vector3),this.registerInput("TBN",th.Object,!0,tu.VertexAndFragment,new fv("TBN",this,td.Input,fS,"TBNBlock")),this.registerOutput("clearcoat",th.Object,tu.Fragment,new fv("clearcoat",this,td.Output,fw,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new ne("ClearCoat intensity",tu.Fragment,th.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===d7._DefaultIndexOfRefraction,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var r,s;super.bind(e,t,i);let n=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:d7._DefaultIndexOfRefraction,a=1-n,o=1+n,l=Math.pow(-a/o,2);e.setFloat4("vClearCoatRefractionParams",l,1/n,a,o);let h=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,u=(null==h?void 0:h.perturbedNormal.isConnected)?h.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",(null==u?void 0:u.invertX)?1:-1,(null==u?void 0:u.invertY)?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",(null==u?void 0:u.invertX)?-1:1,(null==u?void 0:u.invertY)?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1)}_generateTBNSpace(e,t,i){let r="",s=`//${this.name}`,n=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let a={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},o=this.TBN;return o.isConnected?e.compilationString+=` - #ifdef TBNBLOCK - mat3 vTBN = ${o.associatedVariableName}; - #endif - `:n.isConnected&&(r+=`vec3 tbnNormal = normalize(${i}.xyz); -vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); -vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; -mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); -`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[a]}),r}static GetCode(e,t,i,r,s,n,a){let o="",l=(null==t?void 0:t.intensity.isConnected)?t.intensity.associatedVariableName:"1.",h=(null==t?void 0:t.roughness.isConnected)?t.roughness.associatedVariableName:"0.",u=(null==t?void 0:t.normalMapColor.isConnected)?t.normalMapColor.associatedVariableName:"vec3(0.)",c=(null==t?void 0:t.uv.isConnected)?t.uv.associatedVariableName:"vec2(0.)",d=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",p=(null==t?void 0:t.tintThickness.isConnected)?t.tintThickness.associatedVariableName:"1.",_=(null==t?void 0:t.tintAtDistance.isConnected)?t.tintAtDistance.associatedVariableName:"1.";if(t){e._emitUniformFromString("vClearCoatRefractionParams","vec4"),e._emitUniformFromString("vClearCoatTangentSpaceParams","vec2");let i=t.worldNormal;o+=`vec3 vGeometricNormaClearCoatW = ${i.isConnected?"normalize("+i.associatedVariableName+".xyz)":"geometricNormalW"}; -`}else o+=`vec3 vGeometricNormaClearCoatW = geometricNormalW; -`;return s&&t&&(o+=t._generateTBNSpace(e,r,a),n=t.worldTangent.isConnected),o+=`clearcoatOutParams clearcoatOut; - - #ifdef CLEARCOAT - vec2 vClearCoatParams = vec2(${l}, ${h}); - vec4 vClearCoatTintParams = vec4(${d}, ${p}); - - clearcoatBlock( - ${r}.xyz, - vGeometricNormaClearCoatW, - viewDirectionW, - vClearCoatParams, - specularEnvironmentR0, - #ifdef CLEARCOAT_TEXTURE - vec2(0.), - #endif - #ifdef CLEARCOAT_TINT - vClearCoatTintParams, - ${_}, - vClearCoatRefractionParams, - #ifdef CLEARCOAT_TINT_TEXTURE - vec4(0.), - #endif - #endif - #ifdef CLEARCOAT_BUMP - vec2(0., 1.), - vec4(${u}, 0.), - ${c}, - #if defined(${n?"TANGENT":"IGNORE"}) && defined(NORMAL) - vTBN, - #else - vClearCoatTangentSpaceParams, - #endif - #ifdef OBJECTSPACE_NORMALMAP - normalMatrix, - #endif - #endif - #if defined(FORCENORMALFORWARD) && defined(NORMAL) - faceNormal, - #endif - #ifdef REFLECTION - ${null==i?void 0:i._vReflectionMicrosurfaceInfosName}, - ${null==i?void 0:i._vReflectionInfosName}, - ${null==i?void 0:i.reflectionColor}, - vLightingIntensity, - #ifdef ${null==i?void 0:i._define3DName} - ${null==i?void 0:i._cubeSamplerName}, - #else - ${null==i?void 0:i._2DSamplerName}, - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${null==i?void 0:i._define3DName} - ${null==i?void 0:i._cubeSamplerName}, - ${null==i?void 0:i._cubeSamplerName}, - #else - ${null==i?void 0:i._2DSamplerName}, - ${null==i?void 0:i._2DSamplerName}, - #endif - #endif - #endif - #if defined(ENVIRONMENTBRDF) && !defined(${null==i?void 0:i._defineSkyboxName}) - #ifdef RADIANCEOCCLUSION - ambientMonochrome, - #endif - #endif - #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) - (gl_FrontFacing ? 1. : -1.), - #endif - clearcoatOut - ); - #else - clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0; - #endif -`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===tu.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange}; -`}serialize(){let e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.remapF0OnInterfaceChange=null===(r=e.remapF0OnInterfaceChange)||void 0===r||r}}(0,r0.gn)([s2("Remap F0 on interface change",tp.Boolean,"ADVANCED")],fw.prototype,"remapF0OnInterfaceChange",void 0),(0,rn.H)("BABYLON.ClearCoatBlock",fw);class fB extends sJ{constructor(e){super(e,tu.Fragment),this._isUnique=!0,this.registerInput("intensity",th.Float,!0,tu.Fragment),this.registerInput("indexOfRefraction",th.Float,!0,tu.Fragment),this.registerInput("thickness",th.Float,!0,tu.Fragment),this.registerOutput("iridescence",th.Object,tu.Fragment,new fv("iridescence",this,td.Output,fB,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new ne("Iridescence intensity",tu.Fragment,th.Float);e.value=1,e.output.connectTo(this.intensity);let t=new ne("Iridescence ior",tu.Fragment,th.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);let i=new ne("Iridescence thickness",tu.Fragment,th.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e){let t=(null==e?void 0:e.intensity.isConnected)?e.intensity.associatedVariableName:"1.",i=(null==e?void 0:e.indexOfRefraction.isConnected)?e.indexOfRefraction.associatedVariableName:pe._DefaultIndexOfRefraction,r=(null==e?void 0:e.thickness.isConnected)?e.thickness.associatedVariableName:pe._DefaultMaximumThickness;return`iridescenceOutParams iridescenceOut; - - #ifdef IRIDESCENCE - iridescenceBlock( - vec4(${t}, ${i}, 1., ${r}), - NdotV, - specularEnvironmentR0, - #ifdef CLEARCOAT - NdotVUnclamped, - #endif - iridescenceOut - ); - - float iridescenceIntensity = iridescenceOut.iridescenceIntensity; - specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; - #endif -`}_buildBlock(e){return e.target===tu.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){let e=super.serialize();return e}_deserialize(e,t,i){super._deserialize(e,t,i)}}(0,rn.H)("BABYLON.IridescenceBlock",fB);class fU extends sJ{constructor(e){super(e,tu.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",th.Float,!1,tu.Fragment),this.registerInput("tintAtDistance",th.Float,!0,tu.Fragment),this.registerInput("volumeIndexOfRefraction",th.Float,!0,tu.Fragment),this.registerOutput("refraction",th.Object,tu.Fragment,new fv("refraction",this,td.Output,fU,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e){if(!this.intensity.isConnected){let e=new ne("Refraction intensity",tu.Fragment,th.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let t=e.getInputBlockByPredicate(e=>e.systemValue===tf.View);t||(t=new ne("view")).setAsSystemValue(tf.View),t.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){var r,s,n,a;super.bind(e,t,i);let o=this._getTexture();if(!o)return;o.isCube?e.setTexture(this._cubeSamplerName,o):e.setTexture(this._2DSamplerName,o),e.setMatrix(this._refractionMatrixName,o.getRefractionTextureMatrix());let l=1;!o.isCube&&o.depth&&(l=o.depth);let h=null!==(a=null!==(s=null===(r=this.volumeIndexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:null===(n=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==a?a:1.5;e.setFloat4(this._vRefractionInfosName,o.level,1/h,l,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,o.getSize().width,o.lodGenerationScale,o.lodGenerationOffset,1/h);let u=o.getSize().width;e.setFloat2(this._vRefractionFilteringInfoName,u,rm.R.Log2(u)),o.boundingBoxSize&&(e.setVector3("vRefractionPosition",o.boundingBoxPosition),e.setVector3("vRefractionSize",o.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} -`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; -`,e._samplerDeclaration+=`#else -`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; -`,e._samplerDeclaration+=`#endif -`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",` - #ifdef ${this._define3DName} - #define sampleRefraction(s, c) textureCube(s, c) - #else - #define sampleRefraction(s, c) texture2D(s, c) - #endif -`,`//${this.name}`),e._emitFunction("sampleRefractionLod",` - #ifdef ${this._define3DName} - #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) - #else - #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) - #endif -`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"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}"); -`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}"); -`)+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency}; -${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY}; -${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth}; -`}serialize(){let 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=dn.Parse(e.texture,t,i):this.texture=sv.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}(0,r0.gn)([s2("Link refraction to transparency",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fU.prototype,"linkRefractionWithTransparency",void 0),(0,r0.gn)([s2("Invert refraction Y",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fU.prototype,"invertRefractionY",void 0),(0,r0.gn)([s2("Use thickness as depth",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fU.prototype,"useThicknessAsDepth",void 0),(0,rn.H)("BABYLON.RefractionBlock",fU);class fV extends sJ{constructor(e){super(e,tu.Fragment),this._isUnique=!0,this.registerInput("thickness",th.Float,!1,tu.Fragment),this.registerInput("tintColor",th.Color3,!0,tu.Fragment),this.registerInput("translucencyIntensity",th.Float,!0,tu.Fragment),this.registerInput("translucencyDiffusionDist",th.Color3,!0,tu.Fragment),this.registerInput("refraction",th.Object,!0,tu.Fragment,new fv("refraction",this,td.Input,fU,"RefractionBlock")),this.registerOutput("subsurface",th.Object,tu.Fragment,new fv("subsurface",this,td.Output,fV,"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){let e=new ne("SubSurface thickness",tu.Fragment,th.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0)}static GetCode(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,T;let x=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",S=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",E=(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.)",b=(null==t?void 0:t.refraction.isConnected)?null===(s=null==t?void 0:t.refraction.connectedPoint)||void 0===s?void 0:s.ownerBlock:null,y=(null==b?void 0:b.tintAtDistance.isConnected)?b.tintAtDistance.associatedVariableName:"1.",A=(null==b?void 0:b.intensity.isConnected)?b.intensity.associatedVariableName:"1.",R=(null==b?void 0:b.view.isConnected)?b.view.associatedVariableName:"";return""+(null!==(n=null==b?void 0:b.getCode(e))&&void 0!==n?n:"")+`subSurfaceOutParams subSurfaceOut; - - #ifdef SUBSURFACE - vec2 vThicknessParam = vec2(0., ${x}); - vec4 vTintColor = vec4(${S}, ${y}); - vec3 vSubSurfaceIntensity = vec3(${A}, ${E}, 0.); - - subSurfaceBlock( - vSubSurfaceIntensity, - vThicknessParam, - vTintColor, - normalW, - specularEnvironmentReflectance, - #ifdef SS_THICKNESSANDMASK_TEXTURE - vec4(0.), - #endif - #ifdef REFLECTION - #ifdef SS_TRANSLUCENCY - ${null==i?void 0:i._reflectionMatrixName}, - #ifdef USESPHERICALFROMREFLECTIONMAP - #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) - reflectionOut.irradianceVector, - #endif - #if defined(REALTIME_FILTERING) - ${null==i?void 0:i._cubeSamplerName}, - ${null==i?void 0:i._vReflectionFilteringInfoName}, - #endif - #endif - #ifdef USEIRRADIANCEMAP - irradianceSampler, - #endif - #endif - #endif - #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) - surfaceAlbedo, - #endif - #ifdef SS_REFRACTION - ${r}.xyz, - viewDirectionW, - ${R}, - ${null!==(a=null==b?void 0:b._vRefractionInfosName)&&void 0!==a?a:""}, - ${null!==(o=null==b?void 0:b._refractionMatrixName)&&void 0!==o?o:""}, - ${null!==(l=null==b?void 0:b._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:""}, - vLightingIntensity, - #ifdef SS_LINKREFRACTIONTOTRANSPARENCY - alpha, - #endif - #ifdef ${null!==(h=null==b?void 0:b._defineLODRefractionAlpha)&&void 0!==h?h:"IGNORE"} - NdotVUnclamped, - #endif - #ifdef ${null!==(u=null==b?void 0:b._defineLinearSpecularRefraction)&&void 0!==u?u:"IGNORE"} - roughness, - #endif - alphaG, - #ifdef ${null!==(c=null==b?void 0:b._define3DName)&&void 0!==c?c:"IGNORE"} - ${null!==(d=null==b?void 0:b._cubeSamplerName)&&void 0!==d?d:""}, - #else - ${null!==(p=null==b?void 0:b._2DSamplerName)&&void 0!==p?p:""}, - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${null!==(_=null==b?void 0:b._define3DName)&&void 0!==_?_:"IGNORE"} - ${null!==(f=null==b?void 0:b._cubeSamplerName)&&void 0!==f?f:""}, - ${null!==(m=null==b?void 0:b._cubeSamplerName)&&void 0!==m?m:""}, - #else - ${null!==(g=null==b?void 0:b._2DSamplerName)&&void 0!==g?g:""}, - ${null!==(v=null==b?void 0:b._2DSamplerName)&&void 0!==v?v:""}, - #endif - #endif - #ifdef ANISOTROPIC - anisotropicOut, - #endif - #ifdef REALTIME_FILTERING - ${null!==(T=null==b?void 0:b._vRefractionFilteringInfoName)&&void 0!==T?T:""}, - #endif - #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC - vRefractionPosition, - vRefractionSize, - #endif - #endif - #ifdef SS_TRANSLUCENCY - ${C}, - #endif - subSurfaceOut - ); - - #ifdef SS_REFRACTION - surfaceAlbedo = subSurfaceOut.surfaceAlbedo; - #ifdef SS_LINKREFRACTIONTOTRANSPARENCY - alpha = subSurfaceOut.alpha; - #endif - #endif - #else - subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; - #endif -`}_buildBlock(e){return e.target===tu.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}(0,rn.H)("BABYLON.SubSurfaceBlock",fV);let fk={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 fG extends sJ{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?tu.Fragment:tu.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tu.Fragment:tu.Vertex}constructor(e){super(e,tu.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=rs.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",th.Vector4,!1,tu.Vertex),this.registerInput("worldNormal",th.Vector4,!1,tu.Fragment),this.registerInput("view",th.Matrix,!1),this.registerInput("cameraPosition",th.Vector3,!1,tu.Fragment),this.registerInput("perturbedNormal",th.Vector4,!0,tu.Fragment),this.registerInput("baseColor",th.Color3,!0,tu.Fragment),this.registerInput("metallic",th.Float,!1,tu.Fragment),this.registerInput("roughness",th.Float,!1,tu.Fragment),this.registerInput("ambientOcc",th.Float,!0,tu.Fragment),this.registerInput("opacity",th.Float,!0,tu.Fragment),this.registerInput("indexOfRefraction",th.Float,!0,tu.Fragment),this.registerInput("ambientColor",th.Color3,!0,tu.Fragment),this.registerInput("reflection",th.Object,!0,tu.Fragment,new fv("reflection",this,td.Input,fL,"ReflectionBlock")),this.registerInput("clearcoat",th.Object,!0,tu.Fragment,new fv("clearcoat",this,td.Input,fw,"ClearCoatBlock")),this.registerInput("sheen",th.Object,!0,tu.Fragment,new fv("sheen",this,td.Input,fN,"SheenBlock")),this.registerInput("subsurface",th.Object,!0,tu.Fragment,new fv("subsurface",this,td.Input,fV,"SubSurfaceBlock")),this.registerInput("anisotropy",th.Object,!0,tu.Fragment,new fv("anisotropy",this,td.Input,fF,"AnisotropyBlock")),this.registerInput("iridescence",th.Object,!0,tu.Fragment,new fv("iridescence",this,td.Input,fB,"IridescenceBlock")),this.registerOutput("ambientClr",th.Color3,tu.Fragment),this.registerOutput("diffuseDir",th.Color3,tu.Fragment),this.registerOutput("specularDir",th.Color3,tu.Fragment),this.registerOutput("clearcoatDir",th.Color3,tu.Fragment),this.registerOutput("sheenDir",th.Color3,tu.Fragment),this.registerOutput("diffuseInd",th.Color3,tu.Fragment),this.registerOutput("specularInd",th.Color3,tu.Fragment),this.registerOutput("clearcoatInd",th.Color3,tu.Fragment),this.registerOutput("sheenInd",th.Color3,tu.Fragment),this.registerOutput("refraction",th.Color3,tu.Fragment),this.registerOutput("lighting",th.Color3,tu.Fragment),this.registerOutput("shadow",th.Float,tu.Fragment),this.registerOutput("alpha",th.Float,tu.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===tf.CameraPosition);t||(t=new ne("cameraPosition")).setAsSystemValue(tf.CameraPosition),t.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let t=e.getInputBlockByPredicate(e=>e.systemValue===tf.View);t||(t=new ne("view")).setAsSystemValue(tf.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===ph.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===ph.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));let r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",0>r.indexOf(".")?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);let s=e.getScene(),n=s.getEngine();if(n._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&&od.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){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};s3.G.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else s3.G.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,s3.G.PrepareDefinesForMultiview(s,i)}}updateUniformsAndSamples(e,t,i,r){for(let s=0;s<t.maxSimultaneousLights&&i["LIGHT"+s];s++){let t=e.uniforms.indexOf("vLightData"+s)>=0;s3.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}isReady(e,t,i){return(!this._environmentBRDFTexture||!!this._environmentBRDFTexture.isReady())&&(!i._areImageProcessingDirty||!t.imageProcessingConfiguration||!!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var r,s;if(!i)return;let n=i.getScene();this.light?s3.G.BindLight(this.light,this._lightId,n,e,!0):s3.G.BindLights(n,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);let a=this._scene.ambientColor;a&&e.setColor3("ambientFromScene",a);let o=n.useRightHandedSystem===(null!=n._mirroredCameraPosition);e.setFloat(this._invertNormalName,o?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);let l=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((l-1)/(l+1),2)*this._metallicF0Factor,rs.zZ.Color3[0]);let h=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,rs.zZ.Color3[0],h),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;let r=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));let n="v_"+r.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${r.associatedVariableName}; -`);let a=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;a&&(a.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==a?void 0:a.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 -`,e._injectAtEnd+=`vClipSpacePosition = gl_Position; -`,e._injectAtEnd+=`#endif -`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:r.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${r.associatedVariableName}; -`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; -`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e=`albedoOpacityOutParams albedoOpacityOut; -`,t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+`albedoOpacityBlock( - vec4(${t}, 1.), - #ifdef ALBEDO - vec4(1.), - vec2(1., 1.), - #endif - #ifdef OPACITY - vec4(${i}), - vec2(1., 1.), - #endif - albedoOpacityOut - ); - - vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; - float alpha = albedoOpacityOut.alpha; -`}_getAmbientOcclusionCode(){let e=`ambientOcclusionOutParams aoOut; -`,t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+`ambientOcclusionBlock( - #ifdef AMBIENT - vec3(${t}), - vec4(0., 1.0, 1.0, 0.), - #endif - aoOut - ); -`}_getReflectivityCode(e){let t=`reflectivityOutParams reflectivityOut; -`;return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo; - - reflectivityBlock( - vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.), - #ifdef METALLICWORKFLOW - surfaceAlbedo, - ${this._vMetallicReflectanceFactorsName}, - #endif - #ifdef REFLECTIVITY - vec3(0., 0., 1.), - vec4(1.), - #endif - #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) - aoOut.ambientOcclusionColor, - #endif - #ifdef MICROSURFACEMAP - microSurfaceTexel, <== not handled! - #endif - reflectivityOut - ); - - float microSurface = reflectivityOut.microSurface; - float roughness = reflectivityOut.roughness; - - #ifdef METALLICWORKFLOW - surfaceAlbedo = reflectivityOut.surfaceAlbedo; - #endif - #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) - aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; - #endif -`}_buildBlock(e){var t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,T,x,S,E,C,b,y,A,R,P,I,M,D,O,N,F,L,w,B,U,V,k,G;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=dv(this._scene));let 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!==tu.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);let W=`//${this.name}`,H=this.perturbedNormal,X=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(X=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${X}; -`,W),e.compilationString+=`${X} = ${this.worldPosition.associatedVariableName}.xyz; -`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 -`,e.compilationString+=`vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0); -`,e.compilationString+=`#endif -`):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}); -`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${X}.xyz); -`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz; -`,e.compilationString+=`vec3 normalW = ${H.isConnected?"normalize("+H.associatedVariableName+".xyz)":"geometricNormalW"}; -`,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 - vec3 diffuseBase = vec3(1., 1., 1.); - #else -`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(r=null==z?void 0:z._defineSkyboxName)&&void 0!==r?r:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==z?void 0:z._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"}]});let Y=this.anisotropy.isConnected?null===(n=this.anisotropy.connectedPoint)||void 0===n?void 0:n.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!==(a=null==z?void 0:z._define3DName)&&void 0!==a?a:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(o=null==z?void 0:z._defineOppositeZ)&&void 0!==o?o:"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!==(u=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==u?u:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(c=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==c?c:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(d=null==z?void 0:z._vReflectionFilteringInfoName)&&void 0!==d?d:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",W,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});let 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!==(_=null==z?void 0:z._define3DName)&&void 0!==_?_:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(f=null==z?void 0:z._defineSkyboxName)&&void 0!==f?f:"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"}]});let q=this.iridescence.isConnected?null===(v=this.iridescence.connectedPoint)||void 0===v?void 0:v.ownerBlock:null;e.compilationString+=fB.GetCode(q),e._emitFunctionFromInclude("pbrBlockIridescence",W,{replaceStrings:[]});let K=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===(S=(null===(x=this.perturbedNormal.connectedPoint)||void 0===x?void 0:x.ownerBlock).worldTangent)||void 0===S?void 0:S.isConnected),Z=this.anisotropy.isConnected&&(null===(E=this.anisotropy.connectedPoint)||void 0===E?void 0:E.ownerBlock).worldTangent.isConnected,J=Q||!this.perturbedNormal.isConnected&&Z;e.compilationString+=fw.GetCode(e,K,z,X,$,J,this.worldNormal.associatedVariableName),$&&(J=null!==(C=null==K?void 0:K.worldTangent.isConnected)&&void 0!==C&&C),e._emitFunctionFromInclude("pbrBlockClearcoat",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(b=null==z?void 0:z._define3DName)&&void 0!==b?b:"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!==(D=null==z?void 0:z._define3DName)&&void 0!==D?D:"REFLECTIONMAP_3D"}]});let ee=this.subsurface.isConnected?null===(O=this.subsurface.connectedPoint)||void 0===O?void 0:O.ownerBlock:null,et=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;et&&(et.viewConnectionPoint=this.view,et.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=fV.GetCode(e,ee,z,X),e._emitFunctionFromInclude("pbrBlockSubSurface",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(L=null==z?void 0:z._define3DName)&&void 0!==L?L:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(w=null==z?void 0:z._defineOppositeZ)&&void 0!==w?w:"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==et?void 0:et._define3DName)&&void 0!==U?U:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(V=null==et?void 0:et._defineLODRefractionAlpha)&&void 0!==V?V:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(k=null==et?void 0:et._defineLinearSpecularRefraction)&&void 0!==k?k:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(G=null==et?void 0:et._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 -`;let ei=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",er=ph.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();for(let t of(-1===er.indexOf(".")&&(er+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",W,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:ei+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:er}]}),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.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]}),this._outputs))if(t.hasEndpoints){let i=fk[t.name];if(i){let[r,s]=i;s&&(e.compilationString+=`#if ${s} -`),e.compilationString+=`${this._declareOutput(t,e)} = ${r}; -`,s&&(e.compilationString+=`#else -`,e.compilationString+=`${this._declareOutput(t,e)} = vec3(0.); -`,e.compilationString+=`#endif -`)}else console.error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lightFalloff = ${this.lightFalloff}; -${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest}; -${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff}; -${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending}; -${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha}; -${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha}; -${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing}; -${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering}; -${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality}; -${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation}; -${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion}; -${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion}; -${this._codeVariableName}.unlit = ${this.unlit}; -${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward}; -${this._codeVariableName}.debugMode = ${this.debugMode}; -${this._codeVariableName}.debugLimit = ${this.debugLimit}; -${this._codeVariableName}.debugFactor = ${this.debugFactor}; -`}serialize(){let 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 r,s;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=null!==(r=e.lightFalloff)&&void 0!==r?r: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,r0.gn)([s2("Direct lights",tp.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],fG.prototype,"directIntensity",void 0),(0,r0.gn)([s2("Environment lights",tp.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],fG.prototype,"environmentIntensity",void 0),(0,r0.gn)([s2("Specular highlights",tp.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],fG.prototype,"specularIntensity",void 0),(0,r0.gn)([s2("Light falloff",tp.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:ph.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:ph.LIGHTFALLOFF_GLTF},{label:"Standard",value:ph.LIGHTFALLOFF_STANDARD}]})],fG.prototype,"lightFalloff",void 0),(0,r0.gn)([s2("Alpha Testing",tp.Boolean,"OPACITY")],fG.prototype,"useAlphaTest",void 0),(0,r0.gn)([s2("Alpha CutOff",tp.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],fG.prototype,"alphaTestCutoff",void 0),(0,r0.gn)([s2("Alpha blending",tp.Boolean,"OPACITY")],fG.prototype,"useAlphaBlending",void 0),(0,r0.gn)([s2("Radiance over alpha",tp.Boolean,"RENDERING",{notifiers:{update:!0}})],fG.prototype,"useRadianceOverAlpha",void 0),(0,r0.gn)([s2("Specular over alpha",tp.Boolean,"RENDERING",{notifiers:{update:!0}})],fG.prototype,"useSpecularOverAlpha",void 0),(0,r0.gn)([s2("Specular anti-aliasing",tp.Boolean,"RENDERING",{notifiers:{update:!0}})],fG.prototype,"enableSpecularAntiAliasing",void 0),(0,r0.gn)([s2("Realtime filtering",tp.Boolean,"RENDERING",{notifiers:{update:!0}})],fG.prototype,"realTimeFiltering",void 0),(0,r0.gn)([s2("Realtime filtering quality",tp.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],fG.prototype,"realTimeFilteringQuality",void 0),(0,r0.gn)([s2("Energy Conservation",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fG.prototype,"useEnergyConservation",void 0),(0,r0.gn)([s2("Radiance occlusion",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fG.prototype,"useRadianceOcclusion",void 0),(0,r0.gn)([s2("Horizon occlusion",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fG.prototype,"useHorizonOcclusion",void 0),(0,r0.gn)([s2("Unlit",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fG.prototype,"unlit",void 0),(0,r0.gn)([s2("Force normal forward",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fG.prototype,"forceNormalForward",void 0),(0,r0.gn)([s2("Generate only fragment code",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:fG._OnGenerateOnlyFragmentCodeChanged}})],fG.prototype,"generateOnlyFragmentCode",void 0),(0,r0.gn)([s2("Debug mode",tp.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}]})],fG.prototype,"debugMode",void 0),(0,r0.gn)([s2("Split position",tp.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],fG.prototype,"debugLimit",void 0),(0,r0.gn)([s2("Output factor",tp.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],fG.prototype,"debugFactor",void 0),(0,rn.H)("BABYLON.PBRMetallicRoughnessBlock",fG),(0,rn.H)("BABYLON.ModBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("left",th.AutoDetect),this.registerInput("right",th.AutoDetect),this.registerOutput("output",th.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);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.MatrixBuilder",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("row0",th.Vector4),this.registerInput("row1",th.Vector4),this.registerInput("row2",th.Vector4),this.registerInput("row3",th.Vector4),this.registerOutput("output",th.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){let e=new ne("row0");e.value=new rr.Lt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){let e=new ne("row1");e.value=new rr.Lt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){let e=new ne("row2");e.value=new rr.Lt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){let e=new ne("row3");e.value=new rr.Lt(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.row0,r=this.row1,s=this.row2,n=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${r.associatedVariableName}, ${s.associatedVariableName}, ${n.associatedVariableName}); -`,this}}),(eO=iA||(iA={}))[eO.Equal=0]="Equal",eO[eO.NotEqual=1]="NotEqual",eO[eO.LessThan=2]="LessThan",eO[eO.GreaterThan=3]="GreaterThan",eO[eO.LessOrEqual=4]="LessOrEqual",eO[eO.GreaterOrEqual=5]="GreaterOrEqual",eO[eO.Xor=6]="Xor",eO[eO.Or=7]="Or",eO[eO.And=8]="And",(0,rn.H)("BABYLON.ConditionalBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.condition=iA.LessThan,this.registerInput("a",th.Float),this.registerInput("b",th.Float),this.registerInput("true",th.AutoDetect,!0),this.registerInput("false",th.AutoDetect,!0),this.registerOutput("output",th.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=th.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);let t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case iA.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iA.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iA.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iA.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iA.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iA.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iA.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${r}; -`;break;case iA.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${r}; -`;break;case iA.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${r}; -`}return this}serialize(){let e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${iA[this.condition]}; -`;return e}});class fz extends sJ{constructor(e){super(e,tu.Neutral),this.octaves=6,this.registerInput("seed",th.AutoDetect),this.registerInput("chaos",th.AutoDetect,!0),this.registerInput("offsetX",th.Float,!0),this.registerInput("offsetY",th.Float,!0),this.registerInput("offsetZ",th.Float,!0),this.registerOutput("output",th.Float),this._inputs[0].acceptedConnectionPointTypes.push(th.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(th.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||!this._outputs[0].hasEndpoints)return;let r=` - - float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } - - // Based on Morgan McGuire @morgan3d - // https://www.shadertoy.com/view/4dS3Wd - float cloudNoise(in vec2 x, in vec2 chaos) { - vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); - - vec2 i = floor(x); - vec2 f = fract(x); - - float n = dot(i, step); - - vec2 u = f * f * (3.0 - 2.0 * f); - return mix( - mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), - mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), - u.y - ); - } - - float cloudNoise(in vec3 x, in vec3 chaos) { - vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); - - vec3 i = floor(x); - vec3 f = fract(x); - - float n = dot(i, step); - - vec3 u = f * f * (3.0 - 2.0 * f); - return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), - mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), - mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), - mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); - }`,s=` - float fbm(in vec2 st, in vec2 chaos) { - // Initial values - float value = 0.0; - float amplitude = .5; - float frequency = 0.; - - // Loop of octaves - for (int i = 0; i < OCTAVES; i++) { - value += amplitude * cloudNoise(st, chaos); - st *= 2.0; - amplitude *= 0.5; - } - return value; - } - - float fbm(in vec3 x, in vec3 chaos) { - // Initial values - float value = 0.0; - float amplitude = 0.5; - for (int i = 0; i < OCTAVES; ++i) { - value += amplitude * cloudNoise(x, chaos); - x = x * 2.0; - amplitude *= 0.5; - } - return value; - }`,n=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",r,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,s.replace(/fbm/gi,n).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");let a=e._getFreeVariableName("st"),o=(null===(t=this.seed.connectedPoint)||void 0===t?void 0:t.type)===th.Vector2?"vec2":"vec3";e.compilationString+=`${o} ${a} = ${this.seed.associatedVariableName}; -`,this.offsetX.isConnected&&(e.compilationString+=`${a}.x += 0.1 * ${this.offsetX.associatedVariableName}; -`),this.offsetY.isConnected&&(e.compilationString+=`${a}.y += 0.1 * ${this.offsetY.associatedVariableName}; -`),this.offsetZ.isConnected&&"vec3"===o&&(e.compilationString+=`${a}.z += 0.1 * ${this.offsetZ.associatedVariableName}; -`);let l="";return l=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===th.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${n}(${a}, ${l}); -`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves}; -`;return e}serialize(){let e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}(0,r0.gn)([s2("Octaves",tp.Int)],fz.prototype,"octaves",void 0),(0,rn.H)("BABYLON.CloudBlock",fz),(0,rn.H)("BABYLON.VoronoiNoiseBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("seed",th.Vector2),this.registerInput("offset",th.Float),this.registerInput("density",th.Float),this.registerOutput("output",th.Float),this.registerOutput("cells",th.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t=`vec2 voronoiRandom(vec2 seed, float offset){ - mat2 m = mat2(15.27, 47.63, 99.41, 89.98); - vec2 uv = fract(sin(m * seed) * 46839.32); - return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5); - } - `;e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ - vec2 g = floor(seed * density); - vec2 f = fract(seed * density); - float t = 8.0; - vec3 res = vec3(8.0, 0.0, 0.0); - - for(int y=-1; y<=1; y++) - { - for(int x=-1; x<=1; x++) - { - vec2 lattice = vec2(x,y); - vec2 randomOffset = voronoiRandom(lattice + g, offset); - float d = distance(lattice + randomOffset, f); - if(d < res.x) - { - res = vec3(d, randomOffset.x, randomOffset.y); - outValue = res.x; - cells = res.y; - } - } - } - } - `,e._emitFunction("voronoi",t,"// Voronoi");let i=e._getFreeVariableName("tempOutput"),r=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0; -`,e.compilationString+=`float ${r} = 0.0; -`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${r}); -`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; -`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${r}; -`),this}}),(0,rn.H)("BABYLON.ElbowBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("input",th.AutoDetect),this.registerOutput("output",th.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(){let e=this._inputs[0];if(e.isConnected){let t=e.connectedPoint.ownerBlock;if(t.target!==tu.VertexAndFragment)return t.target;if(e.connectedPoint.target!==tu.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){(this._target&e)==0&&(this._target=e)}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName}; -`,this}});class fW extends sJ{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;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rp.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(){let 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)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rp.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)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rp.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,tu.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",th.AutoDetect,!1),this.registerInput("normal",th.AutoDetect,!1),this.registerInput("sharpness",th.Float,!0),this.registerInput("source",th.Object,!0,tu.VertexAndFragment,new fv("source",this,td.Input,fy,"ImageSourceBlock")),this.registerInput("sourceY",th.Object,!0,tu.VertexAndFragment,new fv("sourceY",this,td.Input,fy,"ImageSourceBlock")),t||this.registerInput("sourceZ",th.Object,!0,tu.VertexAndFragment,new fv("sourceZ",this,td.Input,fy,"ImageSourceBlock")),this.registerOutput("rgba",th.Color4,tu.Neutral),this.registerOutput("rgb",th.Color3,tu.Neutral),this.registerOutput("r",th.Float,tu.Neutral),this.registerOutput("g",th.Float,tu.Neutral),this.registerOutput("b",th.Float,tu.Neutral),this.registerOutput("a",th.Float,tu.Neutral),this.registerOutput("level",th.Float,tu.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Vector3|th.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(th.Color3|th.Vector3|th.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;let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){var t,i;let r=this.samplerName,s=null!==(t=this.samplerYName)&&void 0!==t?t:r,n=null!==(i=this.samplerZName)&&void 0!==i?i:r,a=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",o=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),u=e._getFreeVariableName("w"),c=e._getFreeVariableName("n"),d=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),_=e._getFreeVariableName("uvz");e.compilationString+=` - vec3 ${c} = ${this.normal.associatedVariableName}.xyz; - - vec2 ${d} = ${this.position.associatedVariableName}.yz; - vec2 ${p} = ${this.position.associatedVariableName}.zx; - vec2 ${_} = ${this.position.associatedVariableName}.xy; - `,this.projectAsCube&&(e.compilationString+=` - ${d}.xy = ${d}.yx; - - if (${c}.x >= 0.0) { - ${d}.x = -${d}.x; - } - if (${c}.y < 0.0) { - ${p}.y = -${p}.y; - } - if (${c}.z < 0.0) { - ${_}.x = -${_}.x; - } - `),e.compilationString+=` - vec4 ${o} = texture2D(${r}, ${d}); - vec4 ${l} = texture2D(${s}, ${p}); - vec4 ${h} = texture2D(${n}, ${_}); - - // blend weights - vec3 ${u} = pow(abs(${c}), vec3(${a})); - - // blend and return - vec4 ${this._tempTextureRead} = (${o}*${u}.x + ${l}*${u}.y + ${h}*${u}.z) / (${u}.x + ${u}.y + ${u}.z); - `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} - ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); - #endif - `),e.compilationString+=`#ifdef ${this._gammaDefineName} - ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); - #endif - `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r}; -`,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);let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e),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}; -${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; -${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; -${this._codeVariableName}.projectAsCube = ${this.projectAsCube}; -`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); -${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; -${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; -${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; -${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; -${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; -${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; -${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; -${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; -${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; -${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`:e}serialize(){let 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&&!nY.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=sv.Parse(e.texture,t,i))}}(0,r0.gn)([s2("Project as cube",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],fW.prototype,"projectAsCube",void 0),(0,rn.H)("BABYLON.TriPlanarBlock",fW),(0,rn.H)("BABYLON.BiPlanarBlock",class extends fW{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;let i=this.samplerName,r=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("dpdx"),a=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),u=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+=` - // grab coord derivatives for texturing - vec3 ${n} = dFdx(${this.position.associatedVariableName}.xyz); - vec3 ${a} = dFdy(${this.position.associatedVariableName}.xyz); - vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz); - - // determine major axis (in x; yz are following axis) - ivec3 ${l} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) : - (${o}.y>${o}.z) ? ivec3(1,2,0) : - ivec3(2,0,1) ; - // determine minor axis (in x; yz are following axis) - ivec3 ${h} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) : - (${o}.y<${o}.z) ? ivec3(1,2,0) : - ivec3(2,0,1) ; - // determine median axis (in x; yz are following axis) - ivec3 ${u} = ivec3(3) - ${h} - ${l}; - - // project+fetch - vec4 ${c} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), - vec2(${n}[${l}.y],${n}[${l}.z]), - vec2(${a}[${l}.y],${a}[${l}.z]) ); - vec4 ${d} = textureGrad( ${r}, vec2( ${this.position.associatedVariableName}[${u}.y], ${this.position.associatedVariableName}[${u}.z]), - vec2(${n}[${u}.y],${n}[${u}.z]), - vec2(${a}[${u}.y],${a}[${u}.z]) ); - - // blend factors - vec2 ${p} = vec2(${o}[${l}.x],${o}[${u}.x]); - // make local support - ${p} = clamp( (${p}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); - // shape transition - ${p} = pow( ${p}, vec2(${s}/8.0) ); - // blend and return - vec4 ${this._tempTextureRead} = (${c}*${p}.x + ${d}*${p}.y) / (${p}.x + ${p}.y); - `}}),(0,rn.H)("BABYLON.MatrixDeterminantBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("input",th.Matrix),this.registerOutput("output",th.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName}); -`,this}}),(0,rn.H)("BABYLON.MatrixTransposeBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.registerInput("input",th.Matrix),this.registerOutput("output",th.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName}); -`,this}}),(eN=iR||(iR={}))[eN.None=0]="None",eN[eN.Normal=1]="Normal",eN[eN.Tangent=2]="Tangent",eN[eN.VertexColor=3]="VertexColor",eN[eN.UV1=4]="UV1",eN[eN.UV2=5]="UV2",eN[eN.UV3=6]="UV3",eN[eN.UV4=7]="UV4",eN[eN.UV5=8]="UV5",eN[eN.UV6=9]="UV6";class fH extends sJ{constructor(e){super(e,tu.Neutral),this.attributeType=iR.None,this.registerInput("input",th.AutoDetect),this.registerInput("fallback",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(e=>{var t;if(this.attributeType)return;let i=e.ownerBlock;if(i instanceof ne&&i.isAttribute)switch(i.name){case"color":this.attributeType=iR.VertexColor;break;case"normal":this.attributeType=iR.Normal;break;case"tangent":this.attributeType=iR.Tangent;break;case"uv":this.attributeType=iR.UV1;break;case"uv2":this.attributeType=iR.UV2;break;case"uv3":this.attributeType=iR.UV3;break;case"uv4":this.attributeType=iR.UV4;break;case"uv5":this.attributeType=iR.UV5;break;case"uv6":this.attributeType=iR.UV6}else if(i instanceof fT)switch(null===(t=this.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":this.attributeType=iR.Normal;break;case"tangentOutput":this.attributeType=iR.Tangent;break;case"uvOutput":this.attributeType=iR.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 iR.VertexColor:t="VERTEXCOLOR_NME";break;case iR.Normal:t="NORMAL";break;case iR.Tangent:t="TANGENT";break;case iR.UV1:t="UV1";break;case iR.UV2:t="UV2";break;case iR.UV3:t="UV3";break;case iR.UV4:t="UV4";break;case iR.UV5:t="UV5";break;case iR.UV6:t="UV6"}let i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t} -`),e.compilationString+=`${i} = ${this.input.associatedVariableName}; -`,t&&(e.compilationString+=`#else -`,e.compilationString+=`${i} = ${this.fallback.associatedVariableName}; -`,e.compilationString+=`#endif -`),this}serialize(){let e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.attributeType=null!==(r=e.attributeType)&&void 0!==r?r:iR.None}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.attributeType = ${this.attributeType}; -`}}(0,r0.gn)([s2("Attribute lookup",tp.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:iR.None},{label:"Normal",value:iR.Normal},{label:"Tangent",value:iR.Tangent},{label:"Vertex Color",value:iR.VertexColor},{label:"UV1",value:iR.UV1},{label:"UV2",value:iR.UV2},{label:"UV3",value:iR.UV3},{label:"UV4",value:iR.UV4},{label:"UV5",value:iR.UV5},{label:"UV6",value:iR.UV6}]})],fH.prototype,"attributeType",void 0),(0,rn.H)("BABYLON.MeshAttributeExistsBlock",fH),(eF=iP||(iP={}))[eF.EaseInSine=0]="EaseInSine",eF[eF.EaseOutSine=1]="EaseOutSine",eF[eF.EaseInOutSine=2]="EaseInOutSine",eF[eF.EaseInQuad=3]="EaseInQuad",eF[eF.EaseOutQuad=4]="EaseOutQuad",eF[eF.EaseInOutQuad=5]="EaseInOutQuad",eF[eF.EaseInCubic=6]="EaseInCubic",eF[eF.EaseOutCubic=7]="EaseOutCubic",eF[eF.EaseInOutCubic=8]="EaseInOutCubic",eF[eF.EaseInQuart=9]="EaseInQuart",eF[eF.EaseOutQuart=10]="EaseOutQuart",eF[eF.EaseInOutQuart=11]="EaseInOutQuart",eF[eF.EaseInQuint=12]="EaseInQuint",eF[eF.EaseOutQuint=13]="EaseOutQuint",eF[eF.EaseInOutQuint=14]="EaseInOutQuint",eF[eF.EaseInExpo=15]="EaseInExpo",eF[eF.EaseOutExpo=16]="EaseOutExpo",eF[eF.EaseInOutExpo=17]="EaseInOutExpo",eF[eF.EaseInCirc=18]="EaseInCirc",eF[eF.EaseOutCirc=19]="EaseOutCirc",eF[eF.EaseInOutCirc=20]="EaseInOutCirc",eF[eF.EaseInBack=21]="EaseInBack",eF[eF.EaseOutBack=22]="EaseOutBack",eF[eF.EaseInOutBack=23]="EaseInOutBack",eF[eF.EaseInElastic=24]="EaseInElastic",eF[eF.EaseOutElastic=25]="EaseOutElastic",eF[eF.EaseInOutElastic=26]="EaseInOutElastic",(0,rn.H)("BABYLON.CurveBlock",class extends sJ{constructor(e){super(e,tu.Neutral),this.type=iP.EaseInOutSine,this.registerInput("input",th.AutoDetect),this.registerOutput("output",th.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(th.Matrix),this._inputs[0].excludedConnectionPointTypes.push(th.Object),this._inputs[0].excludedConnectionPointTypes.push(th.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);let i=parseInt(t.replace("vec","")),r=` - vec${i} ret = vec${i}(0.0); - `;for(let t=1;t<=i;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+"return ret;\n"}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="",r="",s="";switch(this.input.type){case th.Float:s="float";break;case th.Vector2:s="vec2";break;case th.Vector3:case th.Color3:s="vec3";break;case th.Vector4:case th.Color4:s="vec4"}switch(r=iP[this.type]+"_"+s,this.type){case iP.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case iP.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case iP.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case iP.EaseInQuad:i="return v * v";break;case iP.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case iP.EaseInOutQuad:i=this._duplicateVector("VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0",s);break;case iP.EaseInCubic:i="return v * v * v";break;case iP.EaseOutCubic:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",s);break;case iP.EaseInOutCubic:i=this._duplicateVector("VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0",s);break;case iP.EaseInQuart:i="return v * v * v * v";break;case iP.EaseOutQuart:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",s);break;case iP.EaseInOutQuart:i=this._duplicateVector("VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0",s);break;case iP.EaseInQuint:i="return v * v * v * v * v";break;case iP.EaseOutQuint:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",s);break;case iP.EaseInOutQuint:i=this._duplicateVector("VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0",s);break;case iP.EaseInExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)",s);break;case iP.EaseOutExpo:i=this._duplicateVector("VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)",s);break;case iP.EaseInOutExpo:i=this._duplicateVector("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",s);break;case iP.EaseInCirc:i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",s);break;case iP.EaseOutCirc:i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",s);break;case iP.EaseInOutCirc:i=this._duplicateVector("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",s);break;case iP.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case iP.EaseOutBack:i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",s);break;case iP.EaseInOutBack:i=this._duplicateVector("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",s);break;case iP.EaseInElastic:i=this._duplicateVector("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))",s);break;case iP.EaseOutElastic:i=this._duplicateVector("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",s);break;case iP.EaseInOutElastic:i=this._duplicateVector("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",s)}return e._emitFunction(r,`${s} ${r}(${s} v) {${i};} -`,""),e.compilationString+=this._declareOutput(t,e)+` = ${r}(${this.input.associatedVariableName}); -`,this}serialize(){let e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${iP[this.type]}; -`;return e}});class fX extends s$.H{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class fY extends lg{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new fX,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,r){let s=r.getMesh().decalMap;return!this._isEnabled||null==s||!s.texture||!od.DecalMapEnabled||!t.texturesEnabled||s.isReady()}prepareDefines(e,t,i){let r=i.decalMap;if(this._isEnabled&&(null==r?void 0:r.texture)&&od.DecalMapEnabled&&t.texturesEnabled){let t=!e.DECAL||e.GAMMADECAL!==r.texture.gammaSpace;t&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=r.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,s3.G.PrepareDefinesForMergedUV(r.texture,e,"DECAL")}else{let t=e.DECAL;t&&e.markAsTexturesDirty(),e.DECAL=!1}}hardBindForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;if(!this._isEnabled||!(null==s?void 0:s.texture)||!od.DecalMapEnabled||!t.texturesEnabled)return;let n=this._material.isFrozen,a=s.texture;e.useUbo&&n&&e.isSync||(e.updateFloat4("vDecalInfos",a.coordinatesIndex,0,0,0),s3.G.BindTextureMatrix(a,e,"decal")),e.setTexture("decalSampler",a)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],fY.prototype,"isEnabled",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllSubMeshesAsTexturesDirty")],fY.prototype,"smoothAlpha",void 0),(0,rn.H)("BABYLON.DecalMapConfiguration",fY),(eL=iI||(iI={}))[eL.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",eL[eL.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",eL[eL.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE",(ew=iM||(iM={}))[ew.COLOR_MODE_SET=0]="COLOR_MODE_SET",ew[ew.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",ew[ew.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY",(eB=iD||(iD={}))[eB.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",eB[eB.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE";class fj extends s$.H{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1,this.GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM=!1}}class fq extends lg{constructor(e,t,i){var r,s,n,a,o,l,h,u,c,d,p,_,f,m,g;i=i||{color:fq.DEFAULT_COLOR};let v=new fj;v.GREASED_LINE_HAS_COLOR=!!i.color,v.GREASED_LINE_SIZE_ATTENUATION=null!==(r=i.sizeAttenuation)&&void 0!==r&&r,v.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===iD.COLOR_DISTRIBUTION_TYPE_LINE,v.GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM=(null!=t?t:e.getScene()).useRightHandedSystem,super(e,fq.GREASED_LINE_MATERIAL_NAME,200,v),this._scene=null!=t?t:e.getScene(),this._engine=this._scene.getEngine(),this.visibility=null!==(s=i.visibility)&&void 0!==s?s:1,this.useDash=null!==(n=i.useDash)&&void 0!==n&&n,this.dashRatio=null!==(a=i.dashRatio)&&void 0!==a?a:.5,this.dashOffset=null!==(o=i.dashOffset)&&void 0!==o?o:0,this.width=i.width?i.width:i.sizeAttenuation?fq.DEFAULT_WIDTH_ATTENUATED:fq.DEFAULT_WIDTH,this._sizeAttenuation=null!==(l=i.sizeAttenuation)&&void 0!==l&&l,this.colorMode=null!==(h=i.colorMode)&&void 0!==h?h:iM.COLOR_MODE_SET,this._color=null!==(u=i.color)&&void 0!==u?u:null,this.useColors=null!==(c=i.useColors)&&void 0!==c&&c,this._colorsDistributionType=null!==(d=i.colorDistributionType)&&void 0!==d?d:iD.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=null!==(p=i.colorsSampling)&&void 0!==p?p:sb.NEAREST_NEAREST,this._colors=null!==(_=i.colors)&&void 0!==_?_:null,this.dashCount=null!==(f=i.dashCount)&&void 0!==f?f:1,this.resolution=null!==(m=i.resolution)&&void 0!==m?m:new rr.FM(this._engine.getRenderWidth(),this._engine.getRenderHeight()),this._colors?this._createColorsTexture(`${e.name}-colors-texture`,this._colors):(this._color=null!==(g=this._color)&&void 0!==g?g:fq.DEFAULT_COLOR,fq._PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add(()=>{var e;null===(e=fq._EmptyColorsTexture)||void 0===e||e.dispose(),fq._EmptyColorsTexture=null}),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_aspect_resolution_lineWidth",size:4,type:"vec4"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}],vertex:` - uniform vec4 grl_aspect_resolution_lineWidth; - uniform mat4 grl_projection; - `,fragment:` - uniform vec4 grl_dashOptions; - uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; - uniform vec3 grl_singleColor; - `}}get isEnabled(){return!0}bindForSubMesh(e){var t;let i=this._scene.activeCamera;if(i){let t=i.getProjectionMatrix();e.updateMatrix("grl_projection",t)}else throw Error("GreasedLinePluginMaterial requires an active camera.");let r=rr.jp.Vector4[0];r.x=this._aspect,r.y=this._resolution.x,r.z=this._resolution.y,r.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",r);let s=rr.jp.Vector4[0];s.x=fq._BooleanToNumber(this.useDash),s.y=this._dashArray,s.z=this.dashOffset,s.w=this.dashRatio,e.updateVector4("grl_dashOptions",s);let n=rr.jp.Vector4[1];n.x=this.colorMode,n.y=this.visibility,n.z=this._colorsTexture?this._colorsTexture.getSize().width:0,n.w=fq._BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",n),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",null!==(t=this._colorsTexture)&&void 0!==t?t:fq._EmptyColorsTexture)}prepareDefines(e,t,i){var r;e.GREASED_LINE_HAS_COLOR=!!this._color,e.GREASED_LINE_SIZE_ATTENUATION=null!==(r=this._sizeAttenuation)&&void 0!==r&&r,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===iD.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem}getClassName(){return fq.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:` - attribute vec4 grl_previousAndSide; - attribute vec4 grl_nextAndCounters; - attribute float grl_widths; - attribute vec3 grl_offsets; - attribute float grl_colorPointers; - - varying float grlCounters; - varying float grlColorPointer; - - vec2 grlFix( vec4 i, float aspect ) { - vec2 res = i.xy / i.w; - res.x *= aspect; - return res; - } - `,CUSTOM_VERTEX_UPDATE_POSITION:` - vec3 grlPositionOffset = grl_offsets; - positionUpdated += grlPositionOffset; - `,CUSTOM_VERTEX_MAIN_END:` - - float grlAspect = grl_aspect_resolution_lineWidth.x; - float grlBaseWidth = grl_aspect_resolution_lineWidth.w; - - grlColorPointer = grl_colorPointers; - - vec3 grlPrevious = grl_previousAndSide.xyz; - float grlSide = grl_previousAndSide.w; - - vec3 grlNext = grl_nextAndCounters.xyz; - grlCounters = grl_nextAndCounters.w; - - - mat4 grlMatrix = viewProjection * world; - vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 ); - vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 ); - vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 ); - - vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect ); - vec2 grlPrevP = grlFix( grlPrevPos, grlAspect ); - vec2 grlNextP = grlFix( grlNextPos, grlAspect ); - - float grlWidth = grlBaseWidth * grl_widths; - - vec2 grlDir; - if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP ); - else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP ); - else { - vec2 grlDir1 = normalize( grlCurrentP - grlPrevP ); - vec2 grlDir2 = normalize( grlNextP - grlCurrentP ); - grlDir = normalize( grlDir1 + grlDir2 ); - } - vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. ); - #ifdef GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM - grlNormal.xy *= -.5 * grlWidth; - #else - grlNormal.xy *= .5 * grlWidth; - #endif - grlNormal *= grl_projection; - #ifdef GREASED_LINE_SIZE_ATTENUATION - grlNormal.xy *= grlFinalPosition.w; - grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy; - #endif - grlFinalPosition.xy += grlNormal.xy * grlSide; - gl_Position = grlFinalPosition; - - vPositionW = vec3(grlFinalPosition); - - `,"!gl_Position\\=viewProjection\\*worldPos;":"//"}:"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:` - varying float grlCounters; - varying float grlColorPointer; - uniform sampler2D grl_colors; - `,CUSTOM_FRAGMENT_MAIN_END:` - float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; - float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; - float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; - float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; - - float grlUseDash = grl_dashOptions.x; - float grlDashArray = grl_dashOptions.y; - float grlDashOffset = grl_dashOptions.z; - float grlDashRatio = grl_dashOptions.w; - - gl_FragColor.a *= step(grlCounters, grlVisibility); - if( gl_FragColor.a == 0. ) discard; - - if(grlUseDash == 1.){ - gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); - if (gl_FragColor.a == 0.) discard; - } - - #ifdef GREASED_LINE_HAS_COLOR - if (grlColorMode == ${iM.COLOR_MODE_SET}.) { - gl_FragColor.rgb = grl_singleColor; - } else if (grlColorMode == ${iM.COLOR_MODE_ADD}.) { - gl_FragColor.rgb += grl_singleColor; - } else if (grlColorMode == ${iM.COLOR_MODE_MULTIPLY}.) { - gl_FragColor.rgb *= grl_singleColor; - } - #else - if (grlUseColors == 1.) { - #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE - vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); - #else - vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.); - #endif - if (grlColorMode == ${iM.COLOR_MODE_SET}.) { - gl_FragColor = grlColor; - } else if (grlColorMode == ${iM.COLOR_MODE_ADD}.) { - gl_FragColor += grlColor; - } else if (grlColorMode == ${iM.COLOR_MODE_MULTIPLY}.) { - gl_FragColor *= grlColor; - } - } - #endif - `}:null}static _BooleanToNumber(e){return e?1:0}static _Color3toRGBAUint8(e){let t=new Uint8Array(4*e.length);for(let i=0,r=0;i<e.length;i++)t[r++]=255*e[i].r,t[r++]=255*e[i].g,t[r++]=255*e[i].b,t[r++]=255;return t}_createColorsTexture(e,t){let i=fq._Color3toRGBAUint8(t);this._colorsTexture=new sb(i,t.length,1,r7.D.TEXTUREFORMAT_RGBA,this._scene,!1,!0,this.colorsSampling),this._colorsTexture.name=e}dispose(){var e;null===(e=this._colorsTexture)||void 0===e||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,n,a;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(n=this._colorsTexture)||void 0===n||n.dispose();return}if(!t||i){if(this._colorsTexture&&o===e.length&&!i){let t=fq._Color3toRGBAUint8(e);this._colorsTexture.update(t)}else null===(a=this._colorsTexture)||void 0===a||a.dispose(),this._createColorsTexture(`${this._material.name}-colors-texture`,e)}}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,t||this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r;super.parse(e,t,i);let s=e.greasedLineMaterialOptions;null===(r=this._colorsTexture)||void 0===r||r.dispose(),s.colors?this._createColorsTexture(`${this._material.name}-colors-texture`,s.colors):fq._PrepareEmptyColorsTexture(t),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.markAllDefinesAsDirty()}copyTo(e){var t;null===(t=e._colorsTexture)||void 0===t||t.dispose(),this._colors&&e._createColorsTexture(`${e._material.name}-colors-texture`,this._colors),e.setColor(this.color,!0),e.colorsDistributionType=this.colorsDistributionType,e.colorsSampling=this.colorsSampling,e.colorMode=this.colorMode,e.useColors=this.useColors,e.visibility=this.visibility,e.useDash=this.useDash,e.dashCount=this.dashCount,e.dashRatio=this.dashRatio,e.dashOffset=this.dashOffset,e.width=this.width,e.sizeAttenuation=this.sizeAttenuation,e.resolution=this.resolution,e.markAllDefinesAsDirty()}static _PrepareEmptyColorsTexture(e){if(!this._EmptyColorsTexture){let t=new Uint8Array(4);fq._EmptyColorsTexture=new sb(t,1,1,r7.D.TEXTUREFORMAT_RGBA,e,!1,!1,sb.NEAREST_NEAREST),fq._EmptyColorsTexture.name="grlEmptyColorsTexture"}}}fq.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",fq.DEFAULT_COLOR=rs.Wo.White(),fq.DEFAULT_WIDTH_ATTENUATED=1,fq.DEFAULT_WIDTH=.1,(0,rn.H)(`BABYLON.${fq.GREASED_LINE_MATERIAL_NAME}`,fq);let fK=`#if defined(DBG_ENABLED) -attribute float dbg_initialPass; -varying vec3 dbg_vBarycentric; -flat varying vec3 dbg_vVertexWorldPos; -flat varying float dbg_vPass; -#endif`,f$=`#if defined(DBG_ENABLED) -float dbg_vertexIndex = mod(float(gl_VertexID), 3.); -if (dbg_vertexIndex == 0.0) { - dbg_vBarycentric = vec3(1.,0.,0.); -} -else if (dbg_vertexIndex == 1.0) { - dbg_vBarycentric = vec3(0.,1.,0.); -} -else { - dbg_vBarycentric = vec3(0.,0.,1.); -} - -dbg_vVertexWorldPos = vPositionW; -dbg_vPass = dbg_initialPass; -#endif`,fQ=`#if defined(DBG_ENABLED) -uniform vec3 dbg_shadedDiffuseColor; -uniform vec4 dbg_shadedSpecularColorPower; -uniform vec3 dbg_thicknessRadiusScale; - -#if DBG_MODE == 2 || DBG_MODE == 3 - uniform vec3 dbg_vertexColor; -#endif - -#if DBG_MODE == 1 - uniform vec3 dbg_wireframeTrianglesColor; -#elif DBG_MODE == 3 - uniform vec3 dbg_wireframeVerticesColor; -#elif DBG_MODE == 4 || DBG_MODE == 5 - uniform vec3 dbg_uvPrimaryColor; - uniform vec3 dbg_uvSecondaryColor; -#elif DBG_MODE == 7 - uniform vec3 dbg_materialColor; -#endif -#endif`,fZ=`#if defined(DBG_ENABLED) -varying vec3 dbg_vBarycentric; -flat varying vec3 dbg_vVertexWorldPos; -flat varying float dbg_vPass; - -#if !defined(DBG_MULTIPLY) - vec3 dbg_applyShading(vec3 color) { - vec3 N = vNormalW.xyz; - vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); - vec3 H = normalize(L + L); - float LdotN = clamp(dot(L,N), 0., 1.); - float HdotN = clamp(dot(H,N), 0., 1.); - float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); - color *= (LdotN / PI); - color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); - return color; - } -#endif - -#if DBG_MODE == 1 || DBG_MODE == 3 - float dbg_edgeFactor() { - vec3 d = fwidth(dbg_vBarycentric); - vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); - return min(min(a3.x, a3.y), a3.z); - } -#endif - -#if DBG_MODE == 2 || DBG_MODE == 3 - float dbg_cornerFactor() { - vec3 worldPos = vPositionW; - float dist = length(worldPos - dbg_vVertexWorldPos); - float camDist = length(worldPos - vEyePosition.xyz); - float d = sqrt(camDist) * .001; - return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); - } -#endif - -#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) - float dbg_checkerboardFactor(vec2 uv) { - vec2 f = fract(uv * dbg_thicknessRadiusScale.z); - f -= .5; - return (f.x * f.y) > 0. ? 1. : 0.; - } -#endif -#endif`,fJ=`#if defined(DBG_ENABLED) -vec3 dbg_color = vec3(1.); -#if DBG_MODE == 1 - dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); -#elif DBG_MODE == 2 || DBG_MODE == 3 - float dbg_cornerFactor = dbg_cornerFactor(); - if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; - dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); - #if DBG_MODE == 3 - dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); - #endif -#elif DBG_MODE == 4 && defined(UV1) - dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); -#elif DBG_MODE == 5 && defined(UV2) - dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); -#elif DBG_MODE == 6 && defined(VERTEXCOLOR) - dbg_color = vColor.rgb; -#elif DBG_MODE == 7 - dbg_color = dbg_materialColor; -#endif - -#if defined(DBG_MULTIPLY) - gl_FragColor *= vec4(dbg_color, 1.); -#else - #if DBG_MODE != 6 - gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); - #else - gl_FragColor = vec4(dbg_color, 1.); - #endif -#endif -#endif`,f0=[new rs.Wo(.98,.26,.38),new rs.Wo(.47,.75,.3),new rs.Wo(0,.26,.77),new rs.Wo(.97,.6,.76),new rs.Wo(.19,.63,.78),new rs.Wo(.98,.8,.6),new rs.Wo(.65,.43,.15),new rs.Wo(.15,.47,.22),new rs.Wo(.67,.71,.86),new rs.Wo(.09,.46,.56),new rs.Wo(.8,.98,.02),new rs.Wo(.39,.29,.13),new rs.Wo(.53,.63,.06),new rs.Wo(.95,.96,.41),new rs.Wo(1,.72,.94),new rs.Wo(.63,.08,.31),new rs.Wo(.66,.96,.95),new rs.Wo(.22,.14,.19),new rs.Wo(.14,.65,.59),new rs.Wo(.93,1,.68),new rs.Wo(.93,.14,.44),new rs.Wo(.47,.86,.67),new rs.Wo(.85,.07,.78),new rs.Wo(.53,.64,.98),new rs.Wo(.43,.37,.56),new rs.Wo(.71,.65,.25),new rs.Wo(.66,.19,.01),new rs.Wo(.94,.53,.12),new rs.Wo(.41,.44,.44),new rs.Wo(.24,.71,.96),new rs.Wo(.57,.28,.56),new rs.Wo(.44,.98,.42)];(eU=iO||(iO={}))[eU.NONE=0]="NONE",eU[eU.TRIANGLES=1]="TRIANGLES",eU[eU.VERTICES=2]="VERTICES",eU[eU.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",eU[eU.UV0=4]="UV0",eU[eU.UV1=5]="UV1",eU[eU.VERTEXCOLORS=6]="VERTEXCOLORS",eU[eU.MATERIALIDS=7]="MATERIALIDS";class f1 extends s$.H{constructor(){super(...arguments),this.DBG_MODE=iO.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class f2 extends lg{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){var i,r,s,n,a,o,l,h,u,c,d,p,_;let f=new f1;f.DBG_MODE=null!==(i=t.mode)&&void 0!==i?i:f.DBG_MODE,f.DBG_MULTIPLY=null!==(r=t.multiply)&&void 0!==r?r:f.DBG_MULTIPLY,super(e,"MeshDebug",200,f,!0,!0),this._mode=f.DBG_MODE,this._multiply=f.DBG_MULTIPLY,this.shadedDiffuseColor=null!==(s=t.shadedDiffuseColor)&&void 0!==s?s:new rs.Wo(1,1,1),this.shadedSpecularColor=null!==(n=t.shadedSpecularColor)&&void 0!==n?n:new rs.Wo(.8,.8,.8),this.shadedSpecularPower=null!==(a=t.shadedSpecularPower)&&void 0!==a?a:10,this.wireframeThickness=null!==(o=t.wireframeThickness)&&void 0!==o?o:.7,this.wireframeTrianglesColor=null!==(l=t.wireframeTrianglesColor)&&void 0!==l?l:new rs.Wo(0,0,0),this.wireframeVerticesColor=null!==(h=t.wireframeVerticesColor)&&void 0!==h?h:new rs.Wo(.8,.8,.8),this.vertexColor=null!==(u=t.vertexColor)&&void 0!==u?u:new rs.Wo(0,0,0),this.vertexRadius=null!==(c=t.vertexRadius)&&void 0!==c?c:1.2,this.uvScale=null!==(d=t.uvScale)&&void 0!==d?d:20,this.uvPrimaryColor=null!==(p=t.uvPrimaryColor)&&void 0!==p?p:new rs.Wo(1,1,1),this.uvSecondaryColor=null!==(_=t.uvSecondaryColor)&&void 0!==_?_:new rs.Wo(.5,.5,.5),this._materialColor=f2.MaterialColors[f2._PluginCount++%f2.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(1==this._material.getScene().getEngine().webGLVersion){ru.Y.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=iO.VERTICES&&this._mode!=iO.TRIANGLES&&this._mode!=iO.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||ru.Y.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:fQ}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:fK,CUSTOM_VERTEX_MAIN_END:f$}:{CUSTOM_FRAGMENT_DEFINITIONS:fZ,CUSTOM_FRAGMENT_MAIN_END:fJ}}static Reset(){this._PluginCount=0,this.MaterialColors=f0}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){let t=e.getVerticesDataKinds(),r=e.getIndices(),s={};for(let i of t)s[i]=e.getVerticesData(i);i=function(){for(let i of(e.setIndices(r),t)){let t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,s[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let r=Array.from(e.getIndices()),s=[];for(let e=0;e<r.length;e+=3)s.push(r[e+1],r[e+2],r[e+0]);e.setIndices(r.concat(s)),e.convertToUnIndexedMesh(),e.isUnIndexed=!1,r=Array.from(e.getIndices());let n=[];for(let e=r.length/2;e<r.length;e+=3)n.push(r[e+1],r[e+2],r[e+0]);e.setIndices(r.concat(n));let a=e.getTotalVertices(),o=a/2,l=Array(a).fill(1,0,o).fill(0,o,a);return e.setVerticesData("dbg_initialPass",l,!1,1),i}}f2._PluginCount=0,f2.MaterialColors=f0,(0,r0.gn)([(0,rg.n9)()],f2.prototype,"_materialColor",void 0),(0,r0.gn)([(0,rg.qC)()],f2.prototype,"_isEnabled",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllDefinesAsDirty")],f2.prototype,"mode",void 0),(0,r0.gn)([(0,rg.qC)(),(0,rg.wz)("_markAllDefinesAsDirty")],f2.prototype,"multiply",void 0),(0,r0.gn)([(0,rg.n9)()],f2.prototype,"shadedDiffuseColor",void 0),(0,r0.gn)([(0,rg.n9)()],f2.prototype,"shadedSpecularColor",void 0),(0,r0.gn)([(0,rg.qC)()],f2.prototype,"shadedSpecularPower",void 0),(0,r0.gn)([(0,rg.qC)()],f2.prototype,"wireframeThickness",void 0),(0,r0.gn)([(0,rg.n9)()],f2.prototype,"wireframeTrianglesColor",void 0),(0,r0.gn)([(0,rg.n9)()],f2.prototype,"wireframeVerticesColor",void 0),(0,r0.gn)([(0,rg.n9)()],f2.prototype,"vertexColor",void 0),(0,r0.gn)([(0,rg.qC)()],f2.prototype,"vertexRadius",void 0),(0,r0.gn)([(0,rg.qC)()],f2.prototype,"uvScale",void 0),(0,r0.gn)([(0,rg.n9)()],f2.prototype,"uvPrimaryColor",void 0),(0,r0.gn)([(0,rg.n9)()],f2.prototype,"uvSecondaryColor",void 0),(0,rn.H)("BABYLON.MeshDebugPluginMaterial",f2),Object.defineProperty(lC.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new fY(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(ph.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new fY(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(r$.x.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});var f3=i(4316);function f4(e,t,i,r,s,n){let a,o;let l=new e.DecoderBuffer;l.Init(t,t.byteLength);let h=new e.Decoder;try{let t=h.GetEncodedGeometryType(l);switch(t){case e.TRIANGULAR_MESH:a=new e.Mesh,o=h.DecodeBufferToMesh(l,a);break;case e.POINT_CLOUD:a=new e.PointCloud,o=h.DecodeBufferToPointCloud(l,a);break;default:throw Error(`Invalid geometry type ${t}`)}if(!o.ok()||!a.ptr)throw Error(o.error_msg());if(t===e.TRIANGULAR_MESH){let t=a.num_faces(),i=3*t,s=4*i,n=e._malloc(s);try{h.GetTrianglesUInt32Array(a,s,n);let t=new Uint32Array(i);t.set(new Uint32Array(e.HEAPF32.buffer,n,i)),r(t)}finally{e._free(n)}}let u=(t,i,r=1)=>{let n=i.num_components(),o=a.num_points(),l=o*n,u=l*Float32Array.BYTES_PER_ELEMENT,c=e._malloc(u);try{h.GetAttributeDataArrayForAllPoints(a,i,e.DT_FLOAT32,u,c);let d=new Float32Array(e.HEAPF32.buffer,c,l);if("color"===t&&3===n){let e=new Float32Array(4*o);for(let t=0,i=0;t<e.length;t+=4,i+=n)e[t+0]=d[i+0],e[t+1]=d[i+1],e[t+2]=d[i+2],e[t+3]=1;s(t,e)}else{let i=new Float32Array(l);if(i.set(new Float32Array(e.HEAPF32.buffer,c,l)),1!==r)for(let e=0;e<i.length;e++)i[e]=i[e]/r;s(t,i)}}finally{e._free(c)}};if(i)for(let e in i){let t=i[e],r=h.GetAttributeByUniqueId(a,t),s=n&&n[e]||1;u(e,r,s)}else{let t={position:"POSITION",normal:"NORMAL",color:"COLOR",uv:"TEX_COORD"};for(let i in t){let r=h.GetAttributeId(a,e[t[i]]);if(-1!==r){let e=h.GetAttribute(a,r);u(i,e)}}}}finally{a&&e.destroy(a),e.destroy(h),e.destroy(l)}}function f5(){let e;onmessage=t=>{let i=t.data;switch(i.id){case"init":{let t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage("done");break}case"decodeMesh":if(!e)throw Error("Draco decoder module is not available");e.then(e=>{f4(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 f6{static get DecoderAvailable(){let e=f6.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 f6._Default||(f6._Default=new f6),f6._Default}constructor(e=f6.DefaultNumWorkers){let t=f6.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:rZ.w1.GetAbsoluteUrl(t.wasmUrl),wasmBinaryPromise:rZ.w1.LoadFileAsync(rZ.w1.GetAbsoluteUrl(t.wasmBinaryUrl))}:{url:rZ.w1.GetAbsoluteUrl(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then(t=>{let r=`${f4}(${f5})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));return new pT(e,()=>new Promise((e,r)=>{let n=new Worker(s),a=e=>{n.removeEventListener("error",a),n.removeEventListener("message",o),r(e)},o=t=>{"done"===t.data&&(n.removeEventListener("error",a),n.removeEventListener("message",o),e(n))};n.addEventListener("error",a),n.addEventListener("message",o),n.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))}):this._decoderModulePromise=i.wasmBinaryPromise.then(e=>{if(!i.url)throw Error("Draco decoder module is not available");return rZ.w1.LoadScriptAsync(i.url).then(()=>new Promise(t=>{DracoDecoderModule({wasmBinary:e}).then(e=>{t({module:e})})}))})}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){let r=e instanceof ArrayBuffer?new Uint8Array(e):e;if(this._workerPoolPromise)return this._workerPoolPromise.then(e=>new Promise((s,n)=>{e.push((e,a)=>{let o=new sN.x,l=t=>{e.removeEventListener("error",l),e.removeEventListener("message",h),n(t),a()},h=t=>{if("done"===t.data)e.removeEventListener("error",l),e.removeEventListener("message",h),s(o),a();else if("indices"===t.data.id)o.indices=t.data.value;else{let e=i&&i[t.data.id]?i[t.data.id]:1;if(1!==e)for(let i=0;i<t.data.value.length;i++)t.data.value[i]=t.data.value[i]/e;o.set(t.data.value,t.data.id)}};e.addEventListener("error",l),e.addEventListener("message",h);let u=new Uint8Array(r.byteLength);u.set(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)),e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(e=>{let s=new sN.x;return f4(e.module,r,t,e=>{s.indices=e},(e,t)=>{s.set(t,e)},i),s});throw Error("Draco decoder module is not available")}}f6.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"}},f6.DefaultNumWorkers=f6.GetDefaultNumWorkers(),f6._Default=null;class f8{static get Default(){return f8._Default||(f8._Default=new f8),f8._Default}constructor(){let e=f8.Configuration.decoder;this._decoderModulePromise=rZ.w1.LoadScriptAsync(rZ.w1.GetAbsoluteUrl(e.url)).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,s){return this._decoderModulePromise.then(()=>{let n=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(n,t,i,e,r,s),n})}}f8.Configuration={decoder:{url:"https://preview.babylonjs.com/meshopt_decoder.js"}},f8._Default=null;class f7{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){let r=i.subtract(e),s=t.subtract(e);if(0===r.lengthSquared()||0===s.lengthSquared())return null;let n=rr.P.Normalize(rr.P.Cross(r,s));return new f7(n,rr.P.Dot(n,e))}clone(){return new f7(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,s){let n,a;let o=0,l=[];for(n=0;n<e.vertices.length;n++){a=rr.P.Dot(this.normal,e.vertices[n].pos)-this.w;let t=a<-f7.EPSILON?2:a>f7.EPSILON?1:0;o|=t,l.push(t)}switch(o){case 0:(rr.P.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:s.push(e);break;case 3:{let t;let i=[],o=[];for(n=0;n<e.vertices.length;n++){let t=(n+1)%e.vertices.length,r=l[n],s=l[t],h=e.vertices[n],u=e.vertices[t];if(2!==r&&i.push(h),1!==r&&o.push(2!==r?h.clone():h),(r|s)==3){a=(this.w-rr.P.Dot(this.normal,h.pos))/rr.P.Dot(this.normal,u.pos.subtract(h.pos));let e=h.interpolate(u,a);i.push(e),o.push(e.clone())}}i.length>=3&&(t=new f9(i,e.shared)).plane&&r.push(t),o.length>=3&&(t=new f9(o,e.shared)).plane&&s.push(t)}}}}f7.EPSILON=1e-5;class f9{constructor(e,t){this.vertices=e,this.shared=t,this.plane=f7.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){let e=this.vertices.map(e=>e.clone());return new f9(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}let me=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<instancesDeclaration> -void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normWorldSM=transposeMat3(inverseMat3(normWorldSM)); -#endif -vNormalW=normalize(normWorldSM*normalUpdated); -#endif -vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);} -`;no.v.ShadersStore.meshUVSpaceRendererVertexShader=me;let mt=`precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} -gl_FragColor=texture2D(textureSampler,vDecalTC);} -`;no.v.ShadersStore.meshUVSpaceRendererPixelShader=mt,rq.Kj._TrailMeshParser=(e,t)=>mi.Parse(e,t);class mi extends rq.Kj{constructor(e,t,i,r=1,s=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=n,this._generator=t,this.diameter=r,this._length=s,this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=rr.P.Zero(),this._sectionNormalVectors[e]=rr.P.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){let e=new sN.x,t=[],i=[],r=[],s=rr.P.Zero();s=this._generator instanceof r$.x&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.position;let n=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<this._sectionPolygonPointsCount;e++)t.push(s.x+Math.cos(e*n)*this.diameter,s.y+Math.sin(e*n)*this.diameter,s.z);for(let e=1;e<=this._length;e++){for(let e=0;e<this._sectionPolygonPointsCount;e++)t.push(s.x+Math.cos(e*n)*this.diameter,s.y+Math.sin(e*n)*this.diameter,s.z);let e=t.length/3-2*this._sectionPolygonPointsCount;for(let t=0;t<this._sectionPolygonPointsCount-1;t++)r.push(e+t,e+t+this._sectionPolygonPointsCount,e+t+this._sectionPolygonPointsCount+1),r.push(e+t,e+t+this._sectionPolygonPointsCount+1,e+t+1);r.push(e+this._sectionPolygonPointsCount-1,e+this._sectionPolygonPointsCount-1+this._sectionPolygonPointsCount,e+this._sectionPolygonPointsCount),r.push(e+this._sectionPolygonPointsCount-1,e+this._sectionPolygonPointsCount,e)}sN.x.ComputeNormals(t,r,i),e.positions=t,e.normals=i,e.indices=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add(()=>{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){let e=this.getVerticesData(rQ.o.PositionKind),t=this.getVerticesData(rQ.o.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let i=3*this._sectionPolygonPointsCount;i<e.length;i++)e[i-3*this._sectionPolygonPointsCount]=e[i]-t[i]/this._length*this.diameter;for(let e=3*this._sectionPolygonPointsCount;e<t.length;e++)t[e-3*this._sectionPolygonPointsCount]=t[e];let r=e.length-3*this._sectionPolygonPointsCount,s=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<this._sectionPolygonPointsCount;e++)this._sectionVectors[e].copyFromFloats(Math.cos(e*s)*this.diameter,Math.sin(e*s)*this.diameter,0),this._sectionNormalVectors[e].copyFromFloats(Math.cos(e*s),Math.sin(e*s),0),rr.P.TransformCoordinatesToRef(this._sectionVectors[e],i,this._sectionVectors[e]),rr.P.TransformNormalToRef(this._sectionNormalVectors[e],i,this._sectionNormalVectors[e]);for(let i=0;i<this._sectionPolygonPointsCount;i++)e[r+3*i]=this._sectionVectors[i].x,e[r+3*i+1]=this._sectionVectors[i].y,e[r+3*i+2]=this._sectionVectors[i].z,t[r+3*i]=this._sectionNormalVectors[i].x,t[r+3*i+1]=this._sectionNormalVectors[i].y,t[r+3*i+2]=this._sectionNormalVectors[i].z;this.updateVerticesData(rQ.o.PositionKind,e,!0,!1),this.updateVerticesData(rQ.o.NormalKind,t,!0,!1)}}clone(e="",t){return new mi(e,void 0===t?this._generator:t,this.getScene(),this.diameter,this._length,this._autoStart)}serialize(e){super.serialize(e),e.generatorId=this._generator.id}static Parse(e,t){var i,r;let s=null!==(i=t.getLastMeshById(e.generatorId))&&void 0!==i?i:t.getLastTransformNodeById(e.generatorId);if(!s)throw Error("TrailMesh: generator not found with ID "+e.generatorId);return new mi(e.name,s,t,null!==(r=e.diameter)&&void 0!==r?r:e._diameter,e._length,e._autoStart)}}class mr{constructor(){this.running=!1,this._simplificationArray=[]}addTask(e){this._simplificationArray.push(e)}executeNext(){let e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1}runSimplification(e){if(e.parallelProcessing)e.settings.forEach(t=>{let i=this._getSimplifier(e);i.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{let t=this._getSimplifier(e),i=(i,r)=>{t.simplify(i,t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,r()})};rZ.$g.Run(e.settings.length,t=>{i(e.settings[t.index],()=>{t.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){return e.simplificationType,iN.QUADRATIC,new ml(e.mesh)}}(eV=iN||(iN={}))[eV.QUADRATIC=0]="QUADRATIC";class ms{constructor(e){this._vertices=e,this.error=[,,,,],this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class mn{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new ma,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class ma{constructor(e){this.data=Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,s,n,a,o,l){let h=this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[r]*this.data[o]+this.data[t]*this.data[n]*this.data[a]-this.data[i]*this.data[s]*this.data[a]-this.data[e]*this.data[n]*this.data[o]-this.data[t]*this.data[r]*this.data[l];return h}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){let t=new ma;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new ma(ma.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}}class mo{constructor(e,t){this.vertexId=e,this.triangleId=t}}class ml{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=rL.kn}simplify(e,t){this._initDecimatedMesh(),rZ.$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){let r=~~(this._triangles.length*e.quality),s=0,n=this._triangles.length,a=(e,t)=>{setTimeout(()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e<this._triangles.length;++e)this._triangles[e].isDirty=!1;let i=1e-9*Math.pow(e+3,this.aggressiveness);rZ.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=~~((this._triangles.length/2+e)%this._triangles.length),r=this._triangles[t];if(r&&!(r.error[3]>i)&&!r.deleted&&!r.isDirty){for(let e=0;e<3;++e)if(r.error[e]<i){let t=[],i=[],n=r._vertices[e],a=r._vertices[(e+1)%3];if(n.isBorder||a.isBorder)continue;let o=rr.P.Zero();this._calculateError(n,a,o);let l=[];if(this._isFlipped(n,a,o,t,l)||this._isFlipped(a,n,o,i,l)||0>t.indexOf(!0)||0>i.indexOf(!0))continue;let h=[];if(l.forEach(e=>{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))}),h.length%2!=0)continue;n.q=a.q.add(n.q),n.updatePosition(o);let u=this._references.length;s=this._updateTriangles(n,n,t,s),s=this._updateTriangles(n,a,i,s);let c=this._references.length-u;if(c<=n.triangleCount){if(c)for(let e=0;e<c;e++)this._references[n.triangleStart+e]=this._references[u+e]}else n.triangleStart=u;n.triangleCount=c;break}}},t,()=>n-s<=r)},0)};rZ.$g.Run(this.decimationIterations,e=>{n-s<=r?e.breakLoop():a(e.index,()=>{e.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];let r=this._mesh.getVerticesData(rQ.o.PositionKind),s=this._mesh.getIndices(),n=this._mesh.subMeshes[e],a=e=>{if(i){for(let t=0;t<this._vertices.length;++t)if(this._vertices[t].position.equalsWithEpsilon(e,1e-4))return this._vertices[t]}return null},o=[],l=n.verticesCount;rZ.$g.SyncAsyncForLoop(l,this.syncIterations/4>>0,e=>{if(!r)return;let t=e+n.verticesStart,i=rr.P.FromArray(r,3*t),s=a(i)||new mn(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),o.push(s.id)},()=>{rZ.$g.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,e=>{if(!s)return;let t=n.indexStart/3+e,i=3*t,r=s[i+0],a=s[i+1],l=s[i+2],h=this._vertices[o[r-n.verticesStart]],u=this._vertices[o[a-n.verticesStart]],c=this._vertices[o[l-n.verticesStart]],d=new ms([h,u,c]);d.originalOffset=i,this._triangles.push(d)},()=>{this._init(t)})})}_init(e){rZ.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];t.normal=rr.P.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(ma.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-rr.P.Dot(t.normal,t._vertices[0].position)))},()=>{rZ.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])},()=>{e()})})}_reconstructMesh(e){let t,i,r;let s=[];for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleCount=0;for(t=0;t<this._triangles.length;++t)if(!this._triangles[t].deleted){for(r=0,i=this._triangles[t];r<3;++r)i._vertices[r].triangleCount=1;s.push(i)}let n=this._reconstructedMesh.getVerticesData(rQ.o.PositionKind)||[],a=this._reconstructedMesh.getVerticesData(rQ.o.NormalKind)||[],o=this._reconstructedMesh.getVerticesData(rQ.o.UVKind)||[],l=this._reconstructedMesh.getVerticesData(rQ.o.ColorKind)||[],h=this._mesh.getVerticesData(rQ.o.NormalKind),u=this._mesh.getVerticesData(rQ.o.UVKind),c=this._mesh.getVerticesData(rQ.o.ColorKind),d=0;for(t=0;t<this._vertices.length;++t){let e=this._vertices[t];e.id=d,e.triangleCount&&e.originalOffsets.forEach(t=>{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(a.push(h[3*t]),a.push(h[3*t+1]),a.push(h[3*t+2])),u&&u.length&&(o.push(u[2*t]),o.push(u[2*t+1])),c&&c.length&&(l.push(c[4*t]),l.push(c[4*t+1]),l.push(c[4*t+2]),l.push(c[4*t+3])),++d})}let p=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];let m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(t=0;t<s.length;++t)i=s[t],[0,1,2].forEach(e=>{let t=g[i.originalOffset+e],r=i._vertices[e].originalOffsets.indexOf(t);r<0&&(r=0),m.push(i._vertices[e].id+r+_)});this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(rQ.o.PositionKind,n),a.length>0&&this._reconstructedMesh.setVerticesData(rQ.o.NormalKind,a),o.length>0&&this._reconstructedMesh.setVerticesData(rQ.o.UVKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(rQ.o.ColorKind,l);let v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach(e=>{pB.P.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())}),pB.P.AddToMesh(v.materialIndex,_,d,p,3*s.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new rq.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,r,s){for(let n=0;n<e.triangleCount;++n){let a=this._triangles[this._references[e.triangleStart+n].triangleId];if(a.deleted)continue;let o=this._references[e.triangleStart+n].vertexId,l=a._vertices[(o+1)%3],h=a._vertices[(o+2)%3];if(l===t||h===t){r[n]=!0,s.push(a);continue}let u=l.position.subtract(i);u=u.normalize();let c=h.position.subtract(i);if(c=c.normalize(),Math.abs(rr.P.Dot(u,c))>.999)return!0;let d=rr.P.Cross(u,c).normalize();if(r[n]=!1,.2>rr.P.Dot(d,a.normal))return!0}return!1}_updateTriangles(e,t,i,r){let s=r;for(let r=0;r<t.triangleCount;++r){let n=this._references[t.triangleStart+r],a=this._triangles[n.triangleId];if(!a.deleted){if(i[r]&&a.deletePending){a.deleted=!0,s++;continue}a._vertices[n.vertexId]=e,a.isDirty=!0,a.error[0]=this._calculateError(a._vertices[0],a._vertices[1])+a.borderFactor/2,a.error[1]=this._calculateError(a._vertices[1],a._vertices[2])+a.borderFactor/2,a.error[2]=this._calculateError(a._vertices[2],a._vertices[0])+a.borderFactor/2,a.error[3]=Math.min(a.error[0],a.error[1],a.error[2]),this._references.push(n)}}return s}_identifyBorder(){for(let e=0;e<this._vertices.length;++e){let t;let i=[],r=[],s=this._vertices[e];for(t=0;t<s.triangleCount;++t){let e=this._triangles[this._references[s.triangleStart+t].triangleId];for(let t=0;t<3;t++){let s=0,n=e._vertices[t];for(;s<i.length&&r[s]!==n.id;)++s;s===i.length?(i.push(1),r.push(n.id)):i[s]++}}for(t=0;t<i.length;++t)1===i[t]?this._vertices[r[t]].isBorder=!0:this._vertices[r[t]].isBorder=!1}}_updateMesh(e=!1){let t,i,r,s;if(!e){let e=[];for(t=0;t<this._triangles.length;++t)this._triangles[t].deleted||e.push(this._triangles[t]);this._triangles=e}for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleCount=0,this._vertices[t].triangleStart=0;for(t=0;t<this._triangles.length;++t)for(r=0,i=this._triangles[t];r<3;++r)s=i._vertices[r],s.triangleCount++;let n=0;for(t=0;t<this._vertices.length;++t)this._vertices[t].triangleStart=n,n+=this._vertices[t].triangleCount,this._vertices[t].triangleCount=0;let a=Array(3*this._triangles.length);for(t=0;t<this._triangles.length;++t)for(r=0,i=this._triangles[t];r<3;++r)a[(s=i._vertices[r]).triangleStart+s.triangleCount]=new mo(r,t),s.triangleCount++;this._references=a,e&&this._identifyBorder()}_vertexError(e,t){let i=t.x,r=t.y,s=t.z;return e.data[0]*i*i+2*e.data[1]*i*r+2*e.data[2]*i*s+2*e.data[3]*i+e.data[4]*r*r+2*e.data[5]*r*s+2*e.data[6]*r+e.data[7]*s*s+2*e.data[8]*s+e.data[9]}_calculateError(e,t,i){let r=e.q.add(t.q),s=e.isBorder&&t.isBorder,n=0,a=r.det(0,1,2,1,4,5,2,5,7);if(0===a||s){let s=e.position.add(t.position).divide(new rr.P(2,2,2)),a=this._vertexError(r,e.position),o=this._vertexError(r,t.position),l=this._vertexError(r,s);(n=Math.min(a,o,l))===a?i&&i.copyFrom(e.position):n===o?i&&i.copyFrom(t.position):i&&i.copyFrom(s)}else i||(i=rr.P.Zero()),i.x=-1/a*r.det(1,2,3,4,5,6,5,7,8),i.y=1/a*r.det(0,2,3,1,5,6,2,7,8),i.z=-1/a*r.det(0,1,3,1,4,6,2,5,8),n=this._vertexError(r,i);return n}}Object.defineProperty(rI.x.prototype,"simplificationQueue",{get:function(){if(!this._simplificationQueue){this._simplificationQueue=new mr;let e=this._getComponent(ss.l.NAME_SIMPLIFICATIONQUEUE);e||(e=new mh(this),this._addComponent(e))}return this._simplificationQueue},set:function(e){this._simplificationQueue=e},enumerable:!0,configurable:!0}),rq.Kj.prototype.simplify=function(e,t=!0,i=iN.QUADRATIC,r){return this.getScene().simplificationQueue.addTask({settings:e,parallelProcessing:t,mesh:this,simplificationType:i,successCallback:r}),this};class mh{constructor(e){this.name=ss.l.NAME_SIMPLIFICATIONQUEUE,this.scene=e}register(){this.scene._beforeCameraUpdateStage.registerStep(ss.l.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE,this,this._beforeCameraUpdate)}rebuild(){}dispose(){}_beforeCameraUpdate(){this.scene._simplificationQueue&&!this.scene._simplificationQueue.running&&this.scene._simplificationQueue.executeNext()}}i(8675);class mu{static OmitZeroLengthPredicate(e,t,i){return 0===e.lengthSquared()&&0===t.lengthSquared()&&0===i.lengthSquared()}static MeshesToLines(e,t){let i=[];return e.forEach((e,r)=>{let s=e.getVerticesData(rQ.o.PositionKind),n=e.getIndices();if(s&&n)for(let a=0,o=0;a<n.length;a++){let l=3*n[o++],h=3*n[o++],u=3*n[o++],c=new rr.P(s[l],s[l+1],s[l+2]),d=new rr.P(s[h],s[h+1],s[h+2]),p=new rr.P(s[u],s[u+1],s[u+2]);if(t){let o=t(c,d,p,a,l,e,r,s,n);o&&i.push(o)}else i.push([c,d,p,c])}}),i}static ToVector3Array(e){let t=[];for(let i=0;i<e.length;i+=3)t.push(new rr.P(e[i],e[i+1],e[i+2]));return t}static ToNumberArray(e){return e.flatMap(e=>[e.x,e.y,e.z])}static GetPointsCountInfo(e){let t=Array(e.length),i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){let t;if(0===e.length)return 0;t="number"==typeof e[0]?mu.ToVector3Array(e):e;let i=rr.jp.Vector3[0],r=0;for(let e=0;e<t.length-1;e++){let s=t[e],n=t[e+1];r+=n.subtractToRef(s,i).length()}return r}static SegmentizeSegmentByCount(e,t,i){let r=[],s=t.subtract(e),n=rr.jp.Vector3[0];n.setAll(i);let a=rr.jp.Vector3[1];s.divideToRef(n,a);let o=e.clone();r.push(o);for(let e=0;e<i;e++)r.push((o=o.clone()).addInPlace(a));return r}static SegmentizeLineBySegmentLength(e,t){let i=e[0]instanceof rr.P?mu.GetLineSegments(e):e,r=[];return i.forEach(e=>{if(e.length>t){let i=mu.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t));i.forEach(e=>{r.push(e)})}else r.push(e.point1),r.push(e.point2)}),r}static SegmentizeLineBySegmentCount(e,t){let i=mu.GetLineLength(e)/t;return mu.SegmentizeLineBySegmentLength(e,i)}static GetLineSegments(e){let t=[];for(let i=0;i<e.length-1;i++){let r=e[i],s=e[i+1],n=s.subtract(r).length();t.push({point1:r,point2:s,length:n})}return t}static GetMinMaxSegmentLength(e){let t=mu.GetLineSegments(e),i=t.sort(e=>e.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){let s=t*i,n=0,a=0,o=e.length;for(let t=0;t<o;t++){if(s<=n+e[t].length){a=t;break}n+=e[t].length}let l=(s-n)/e[a].length;return e[a].point2.subtractToRef(e[a].point1,rr.jp.Vector3[0]),rr.jp.Vector3[1]=rr.jp.Vector3[0].multiplyByFloats(l,l,l),r||rr.jp.Vector3[1].addInPlace(e[a].point1),rr.jp.Vector3[1].clone()}static GetCircleLinePoints(e,t,i=0,r=e,s=2*Math.PI/t){let n=[];for(let a=0;a<=t;a++)n.push(new rr.P(Math.cos(a*s)*e,Math.sin(a*s)*r,i));return n}static GetBezierLinePoints(e,t,i,r){return rk.CreateQuadraticBezier(e,t,i,r).getPoints().flatMap(e=>[e.x,e.y,e.z])}static GetArrowCap(e,t,i,r,s,n=0,a=0){let o=[e.clone(),e.add(t.multiplyByFloats(i,i,i))];return{points:o,widths:[r,s,n,a]}}static GetPointsFromText(e,t,i,r,s=0,n=!0){let a=[],o=function(e,t,i,r){let s=Array.from(e),n=t/r.resolution,a=(r.boundingBox.yMax-r.boundingBox.yMin+r.underlineThickness)*n,o=[],l=0,h=0;for(let e=0;e<s.length;e++){let t=s[e];if("\n"===t)l=0,h-=a;else{let e=function(e,t,i,r,s,n){let a=n.glyphs[e]||n.glyphs["?"];if(!a)return null;let o=new hG(s);if(a.o){let e=a.o.split(" ");for(let s=0,n=e.length;s<n;){let n=e[s++];switch(n){case"m":{let n=parseInt(e[s++])*t+i,a=parseInt(e[s++])*t+r;o.moveTo(n,a);break}case"l":{let n=parseInt(e[s++])*t+i,a=parseInt(e[s++])*t+r;o.lineTo(n,a);break}case"q":{let n=parseInt(e[s++])*t+i,a=parseInt(e[s++])*t+r,l=parseInt(e[s++])*t+i,h=parseInt(e[s++])*t+r;o.quadraticCurveTo(l,h,n,a);break}case"b":{let n=parseInt(e[s++])*t+i,a=parseInt(e[s++])*t+r,l=parseInt(e[s++])*t+i,h=parseInt(e[s++])*t+r,u=parseInt(e[s++])*t+i,c=parseInt(e[s++])*t+r;o.bezierCurveTo(l,h,u,c,n,a)}}}}return o.extractHoles(),{offsetX:a.ha*t,shapePath:o}}(t,n,l,h,i,r);e&&(l+=e.offsetX,o.push(e.shapePath))}}return o}(e,t,i,r);for(let e of o){for(let t of e.paths){let e=[],i=t.getPoints();for(let t of i)e.push(t.x,t.y,s);a.push(e)}if(n)for(let t of e.holes){let e=[],i=t.getPoints();for(let t of i)e.push(t.x,t.y,s);a.push(e)}}return a}}let mc=`precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} -if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==1.) { -textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} -if (grlColorMode==0.) { -gl_FragColor=textureColor;} else if (grlColorMode==1.) { -gl_FragColor+=textureColor;} else if (grlColorMode==2.) { -gl_FragColor*=textureColor;}}} -`;no.v.ShadersStore.greasedLinePixelShader=mc;let md=`precision highp float;attribute vec4 grl_previousAndSide;attribute vec4 grl_nextAndCounters;attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;uniform mat4 worldViewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} -void main() {grlColorPointer=grl_colorPointers;float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=worldViewProjection;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );} -vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); -#ifdef GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM -grlNormal.xy*=-.5*grlWidth; -#else -grlNormal.xy*=.5*grlWidth; -#endif -grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} -grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;} -`;no.v.ShadersStore.greasedLineVertexShader=md;class mp extends hf{constructor(e,t,i){var r,s,n,a,o,l,h,u,c,d,p,_,f;super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:["position","normal","grl_previousAndSide","grl_nextAndCounters","grl_widths","grl_offsets","grl_colorPointers"],uniforms:["worldViewProjection","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:t.useRightHandedSystem?["GREASED_LNE_RIGHT_HANDED_COORDINATE_SYSTEM"]:[]}),this._color=rs.Wo.White(),this._colorsDistributionType=iD.COLOR_DISTRIBUTION_TYPE_SEGMENT,i=i||{color:mp.DEFAULT_COLOR},this._engine=t.getEngine(),this.visibility=null!==(r=i.visibility)&&void 0!==r?r:1,this.useDash=null!==(s=i.useDash)&&void 0!==s&&s,this.dashRatio=null!==(n=i.dashRatio)&&void 0!==n?n:.5,this.dashOffset=null!==(a=i.dashOffset)&&void 0!==a?a:0,this.dashCount=null!==(o=i.dashCount)&&void 0!==o?o:1,this.width=i.width?i.width:i.sizeAttenuation?mp.DEFAULT_WIDTH_ATTENUATED:mp.DEFAULT_WIDTH,this.sizeAttenuation=null!==(l=i.sizeAttenuation)&&void 0!==l&&l,this.color=null!==(h=i.color)&&void 0!==h?h:rs.Wo.White(),this.useColors=null!==(u=i.useColors)&&void 0!==u&&u,this.colorsDistributionType=null!==(c=i.colorDistributionType)&&void 0!==c?c:iD.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=null!==(d=i.colorsSampling)&&void 0!==d?d:sb.NEAREST_NEAREST,this.colorMode=null!==(p=i.colorMode)&&void 0!==p?p:iM.COLOR_MODE_SET,this._colors=null!==(_=i.colors)&&void 0!==_?_:null,this.resolution=null!==(f=i.resolution)&&void 0!==f?f:new rr.FM(this._engine.getRenderWidth(),this._engine.getRenderHeight()),this._colors&&this.setColors(this._colors),this._engine.onDisposeObservable.add(()=>{var e;null===(e=mp._EmptyColorsTexture)||void 0===e||e.dispose()})}static _BooleanToNumber(e){return e?1:0}static _Color3toRGBAUint8(e){let t=new Uint8Array(4*e.length);for(let i=0,r=0;i<e.length;i++)t[r++]=255*e[i].r,t[r++]=255*e[i].g,t[r++]=255*e[i].b,t[r++]=255;return t}_createColorsTexture(e,t){let i=mp._Color3toRGBAUint8(t);this._colorsTexture=new sb(i,t.length,1,r7.D.TEXTUREFORMAT_RGBA,this.getScene(),!1,!0,this._colorsSampling),this._colorsTexture.name=e}dispose(){var e;null===(e=this._colorsTexture)||void 0===e||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new rr.FM(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,n,a;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(n=this._colorsTexture)||void 0===n||n.dispose();return}if(!t||i){if(this._colorsTexture&&o===e.length&&!i){let t=mp._Color3toRGBAUint8(e);this._colorsTexture.update(t)}else null===(a=this._colorsTexture)||void 0===a||a.dispose(),this._createColorsTexture(`${this.name}-colors-texture`,e);this._colorsTexture&&(this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture))}}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",mp._BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",mp._BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",mp._BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=null!=e?e:mp.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r;let s=e.greasedLineMaterialOptions;null===(r=this._colorsTexture)||void 0===r||r.dispose(),s.colors?this._createColorsTexture(`${this.name}-colors-texture`,s.colors):mp._PrepareEmptyColorsTexture(t),s.color&&(this.color=s.color),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution)}static _PrepareEmptyColorsTexture(e){if(!this._EmptyColorsTexture){let t=new Uint8Array(4);mp._EmptyColorsTexture=new sb(t,1,1,r7.D.TEXTUREFORMAT_RGBA,e,!1,!1,sb.NEAREST_NEAREST),mp._EmptyColorsTexture.name="grlEmptyColorsTexture"}}}mp.DEFAULT_COLOR=rs.Wo.White(),mp.DEFAULT_WIDTH_ATTENUATED=1,mp.DEFAULT_WIDTH=.1,rq.Kj._GreasedLineMeshParser=(e,t)=>m_.Parse(e,t);class m_ extends rq.Kj{constructor(e,t,i){var r,s,n,a;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!==(r=i.lazy)&&void 0!==r&&r,this._updatable=null!==(s=i.updatable)&&void 0!==s&&s,this._vertexPositions=[],this._indices=[],this._uvs=[],this._points=[],this._colorPointers=null!==(n=i.colorPointers)&&void 0!==n?n:[],this._widths=null!==(a=i.widths)&&void 0!==a?a:Array(i.points.length).fill(1),this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(m_.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 rr.P){let t=[];for(let i=0;i<e.length;i++){let r=e[i];t.push(r.x,r.y,r.z)}return[t]}if(e.length>0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof rr.P){let 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){let 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 offsets(){return this._offsets}set offsets(e){this._offsets=e,this._offsetsBuffer?this._offsetsBuffer&&this._offsetsBuffer.update(e):this._createOffsetsBuffer(e)}get widths(){return this._widths}set widths(e){this._widths=e,!this._lazy&&this._widthsBuffer&&this._widthsBuffer.update(e)}get colorPointers(){return this._colorPointers}set colorPointers(e){this._colorPointers=e,!this._lazy&&this._colorPointersBuffer&&this._colorPointersBuffer.update(e)}get greasedLineMaterial(){var e,t;if(this.material&&this.material instanceof mp)return this.material;let i=null===(t=null===(e=this.material)||void 0===e?void 0:e.pluginManager)||void 0===t?void 0:t.getPlugin(fq.GREASED_LINE_MATERIAL_NAME);if(i)return i}get points(){let e=[];return r_.j.DeepCopy(this._points,e),e}addPoints(e){for(let t of 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<t.length;i+=3)this._colorPointers.push(e),this._colorPointers.push(e++)})}_updateWidths(){let e=0;for(let t of this._points)e+=t.length;let t=e/3*2-this._widths.length;for(let e=0;e<t;e++)this._widths.push(1)}setPoints(e){this._points=e,this._updateWidths(),this._updateColorPointers(),this._setPoints(e)}_setPoints(e){this._points=e,this._options.points=e,this._initGreasedLine();let t=0;e.forEach(e=>{var i;let r=[],s=[],n=[],a=mu.GetLineLength(e);for(let i=0,o=0;o<e.length;i++,o+=3){let l=e.slice(0,o+3),h=mu.GetLineLength(l),u=h/a;if(s.push(e[o],e[o+1],e[o+2]),s.push(e[o],e[o+1],e[o+2]),r.push(u),r.push(u),o<e.length-3){let e=2*i+t;n.push(e,e+1,e+2),n.push(e+2,e+1,e+3)}}t+=e.length/3*2;let o=[],l=[],h=[],u=[];for(let e of(this._preprocess(s,o,l,h,u),s))this._vertexPositions.push(e);for(let e of n)this._indices.push(e);for(let e=0;e<h.length;e++)this._previousAndSide.push(o[3*e],o[3*e+1],o[3*e+2],h[e]),this._nextAndCounters.push(l[3*e],l[3*e+1],l[3*e+2],r[e]);for(let e of u=null!==(i=this._options.uvs)&&void 0!==i?i:u)this._uvs.push(e)}),this._lazy||(this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(),this.refreshBoundingInfo())}_createLineOptions(){let e={points:this._points,colorPointers:this._colorPointers,lazy:this._lazy,updatable:this._updatable,uvs:this._uvs,widths:this._widths};return e}clone(e=`${this.name}-cloned`,t){let i=this._createLineOptions(),r={};r_.j.DeepCopy(i,r,["instance"]);let s=new m_(e,this._scene,r);return t&&(s.parent=t),s.material=this.material,s}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions()}static Parse(e,t){let i=e.lineOptions,r=e.name,s=new m_(r,t,i);return s}intersects(e,t,i,r=!1,s,n=!1){let a=new sI.p,o=this.findAllIntersections(e,t,i,r,s,n,!0);if((null==o?void 0:o.length)===1){let t=o[0];a.hit=!0,a.distance=t.distance,a.ray=e,a.pickedMesh=this,a.pickedPoint=t.point}return a}findAllIntersections(e,t,i,r=!1,s,n=!1,a=!1){var o,l;if(r&&!n&&!1===e.intersectsSphere(this._boundingSphere,this.intersectionThreshold))return;let h=this.getIndices(),u=this.getVerticesData(rQ.o.PositionKind),c=this._widths,d=null!==(l=null===(o=this.greasedLineMaterial)||void 0===o?void 0:o.width)&&void 0!==l?l:1,p=[];if(h&&u&&c){let t=0,i=0;for(t=0,i=h.length-1;t<i;t+=3){let i=h[t],r=h[t+1];m_._V_START.fromArray(u,3*i),m_._V_END.fromArray(u,3*r),this._offsets&&(m_._V_OFFSET_START.fromArray(this._offsets,3*i),m_._V_OFFSET_END.fromArray(this._offsets,3*r),m_._V_START.addInPlace(m_._V_OFFSET_START),m_._V_END.addInPlace(m_._V_OFFSET_END));let s=Math.floor(t/3),n=void 0!==c[s]?c[s]:1,o=this.intersectionThreshold*(d*n)/2,l=e.intersectionSegment(m_._V_START,m_._V_END,o);if(-1!==l&&(p.push({distance:l,point:e.direction.normalize().multiplyByFloats(l,l,l).add(e.origin)}),a))return p}t=i}return p}_initGreasedLine(){this._vertexPositions=[],this._previousAndSide=[],this._nextAndCounters=[],this._indices=[],this._uvs=[]}get _boundingSphere(){return this.getBoundingInfo().boundingSphere}static _CompareV3(e,t,i){let r=6*e,s=6*t;return i[r]===i[s]&&i[r+1]===i[s+1]&&i[r+2]===i[s+2]}static _CopyV3(e,t){let i=6*e;return[t[i],t[i+1],t[i+2]]}_preprocess(e,t,i,r,s){let n=e.length/6,a=[];a=m_._CompareV3(0,n-1,e)?m_._CopyV3(n-2,e):m_._CopyV3(0,e),t.push(a[0],a[1],a[2]),t.push(a[0],a[1],a[2]);for(let o=0;o<n;o++)r.push(1),r.push(-1),this._options.uvs||(s.push(o/(n-1),0),s.push(o/(n-1),1)),o<n-1&&(a=m_._CopyV3(o,e),t.push(a[0],a[1],a[2]),t.push(a[0],a[1],a[2])),o>0&&(a=m_._CopyV3(o,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]));return a=m_._CompareV3(n-1,0,e)?m_._CopyV3(1,e):m_._CopyV3(n-1,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]),{previous:t,next:i,uvs:s,side:r}}_createVertexBuffers(){let e=new sN.x;e.positions=this._vertexPositions,e.indices=this._indices,e.uvs=this._uvs,e.applyToMesh(this,this._options.updatable);let t=this._scene.getEngine(),i=new rQ.l(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));let r=new rQ.l(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(r.createVertexBuffer("grl_nextAndCounters",0,4));let s=new rQ.l(t,this._widths,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s;let n=new rQ.l(t,this._colorPointers,this._updatable,1);this.setVerticesBuffer(n.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=n}_createOffsetsBuffer(e){let t=this._scene.getEngine(),i=new rQ.l(t,e,this._updatable,3);this.setVerticesBuffer(i.createVertexBuffer("grl_offsets",0,3)),this._offsetsBuffer=i}}m_._V_START=new rr.P,m_._V_END=new rr.P,m_._V_OFFSET_START=new rr.P,m_._V_OFFSET_END=new rr.P,(ek=iF||(iF={}))[ek.COLOR_DISTRIBUTION_NONE=0]="COLOR_DISTRIBUTION_NONE",ek[ek.COLOR_DISTRIBUTION_REPEAT=1]="COLOR_DISTRIBUTION_REPEAT",ek[ek.COLOR_DISTRIBUTION_EVEN=2]="COLOR_DISTRIBUTION_EVEN",ek[ek.COLOR_DISTRIBUTION_START=3]="COLOR_DISTRIBUTION_START",ek[ek.COLOR_DISTRIBUTION_END=4]="COLOR_DISTRIBUTION_END",ek[ek.COLOR_DISTRIBUTION_START_END=5]="COLOR_DISTRIBUTION_START_END",(eG=iL||(iL={}))[eG.WIDTH_DISTRIBUTION_NONE=0]="WIDTH_DISTRIBUTION_NONE",eG[eG.WIDTH_DISTRIBUTION_REPEAT=1]="WIDTH_DISTRIBUTION_REPEAT",eG[eG.WIDTH_DISTRIBUTION_EVEN=2]="WIDTH_DISTRIBUTION_EVEN",eG[eG.WIDTH_DISTRIBUTION_START=3]="WIDTH_DISTRIBUTION_START",eG[eG.WIDTH_DISTRIBUTION_END=4]="WIDTH_DISTRIBUTION_END",eG[eG.WIDTH_DISTRIBUTION_START_END=5]="WIDTH_DISTRIBUTION_START_END",i(4696),rq.Kj.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return ru.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);let i=this._thinInstanceDataStorage.instancesCount;if(Array.isArray(e))for(let i=0;i<e.length;++i)this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e[i],i===e.length-1&&t);else this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e,t);return i},rq.Kj.prototype.thinInstanceAddSelf=function(e=!0){return this.thinInstanceAdd(rr.y3.IdentityReadOnly,e)},rq.Kj.prototype.thinInstanceRegisterAttribute=function(e,t){e===rQ.o.ColorKind&&(e=rQ.o.ColorInstanceKind),this.removeVerticesData(e),this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.strides[e]=t,this._userThinInstanceBuffersStorage.sizes[e]=t*Math.max(32,this._thinInstanceDataStorage.instancesCount),this._userThinInstanceBuffersStorage.data[e]=new Float32Array(this._userThinInstanceBuffersStorage.sizes[e]),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new rQ.o(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!0,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])},rq.Kj.prototype.thinInstanceSetMatrixAt=function(e,t,i=!0){if(!this._thinInstanceDataStorage.matrixData||e>=this._thinInstanceDataStorage.instancesCount)return!1;let r=this._thinInstanceDataStorage.matrixData;return t.copyToArray(r,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},rq.Kj.prototype.thinInstanceSetAttributeAt=function(e,t,i,r=!0){return e===rQ.o.ColorKind&&(e=rQ.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]),r&&this.thinInstanceBufferUpdated(e),!0)},Object.defineProperty(rq.Kj.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;let r=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData,s=r?r.length/16:0;e<=s&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),rq.Kj.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===rQ.o.ColorKind&&(e=rQ.o.ColorInstanceKind);let r=new rQ.l(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(r.createVertexBuffer(e+t,4*t,4));return r},rq.Kj.prototype.thinInstanceSetBuffer=function(e,t,i=0,r=!1){var s,n,a;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,r),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(null===(n=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===n||n.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,r))):(e===rQ.o.ColorKind&&(e=rQ.o.ColorInstanceKind),null===t?(null===(a=this._userThinInstanceBuffersStorage)||void 0===a?void 0:a.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 rQ.o(this.getEngine(),t,e,!r,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},rq.Kj.prototype.thinInstanceBufferUpdated=function(e){var t,i,r;"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===rQ.o.ColorKind&&(e=rQ.o.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},rq.Kj.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var r;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===rQ.o.ColorKind&&(e=rQ.o.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},rq.Kj.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];let e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;t<this._thinInstanceDataStorage.instancesCount;++t)this._thinInstanceDataStorage.worldMatrices[t]=rr.y3.FromArray(e,16*t)}return this._thinInstanceDataStorage.worldMatrices},rq.Kj.prototype.thinInstanceRefreshBoundingInfo=function(e=!1,t=!1,i=!1){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return;let r=this._thinInstanceDataStorage.boundingVectors;if(e||!this.rawBoundingInfo){r.length=0,this.refreshBoundingInfo(t,i);let e=this.getBoundingInfo();this.rawBoundingInfo=new l5.j(e.minimum,e.maximum)}let s=this.getBoundingInfo(),n=this._thinInstanceDataStorage.matrixData;if(0===r.length)for(let e=0;e<s.boundingBox.vectors.length;++e)r.push(s.boundingBox.vectors[e].clone());rr.jp.Vector3[0].setAll(Number.POSITIVE_INFINITY),rr.jp.Vector3[1].setAll(Number.NEGATIVE_INFINITY);for(let e=0;e<this._thinInstanceDataStorage.instancesCount;++e){rr.y3.FromArrayToRef(n,16*e,rr.jp.Matrix[0]);for(let e=0;e<r.length;++e)rr.P.TransformCoordinatesToRef(r[e],rr.jp.Matrix[0],rr.jp.Vector3[2]),rr.jp.Vector3[0].minimizeInPlace(rr.jp.Vector3[2]),rr.jp.Vector3[1].maximizeInPlace(rr.jp.Vector3[2])}s.reConstruct(rr.jp.Vector3[0],rr.jp.Vector3[1]),this._updateBoundingInfo()},rq.Kj.prototype._thinInstanceUpdateBufferSize=function(e,t=1){var i,r,s;e===rQ.o.ColorKind&&(e=rQ.o.ColorInstanceKind);let n="matrix"===e;if(!n&&(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.strides[e]))return;let a=n?16:this._userThinInstanceBuffersStorage.strides[e],o=n?this._thinInstanceDataStorage.matrixBufferSize:this._userThinInstanceBuffersStorage.sizes[e],l=n?this._thinInstanceDataStorage.matrixData:this._userThinInstanceBuffersStorage.data[e],h=(this._thinInstanceDataStorage.instancesCount+t)*a,u=o;for(;u<h;)u*=2;if(!l||o!=u){if(l){let e=new Float32Array(u);e.set(l,0),l=e}else l=new Float32Array(u);n?(null===(i=this._thinInstanceDataStorage.matrixBuffer)||void 0===i||i.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",l,!1),this._thinInstanceDataStorage.matrixData=l,this._thinInstanceDataStorage.matrixBufferSize=u,this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&(null===(r=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===r||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",l,!1))):(null===(s=this._userThinInstanceBuffersStorage.vertexBuffers[e])||void 0===s||s.dispose(),this._userThinInstanceBuffersStorage.data[e]=l,this._userThinInstanceBuffersStorage.sizes[e]=u,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new rQ.o(this.getEngine(),l,e,!0,!1,a,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))}},rq.Kj.prototype._thinInstanceInitializeUserStorage=function(){this._userThinInstanceBuffersStorage||(this._userThinInstanceBuffersStorage={data:{},sizes:{},vertexBuffers:{},strides:{}})},rq.Kj.prototype._disposeThinInstanceSpecificData=function(){var e;(null===(e=this._thinInstanceDataStorage)||void 0===e?void 0:e.matrixBuffer)&&(this._thinInstanceDataStorage.matrixBuffer.dispose(),this._thinInstanceDataStorage.matrixBuffer=null)},(ez=iw||(iw={}))[ez.Int=1]="Int",ez[ez.Float=2]="Float",ez[ez.Vector2=4]="Vector2",ez[ez.Vector3=8]="Vector3",ez[ez.Vector4=16]="Vector4",ez[ez.Matrix=32]="Matrix",ez[ez.Geometry=64]="Geometry",ez[ez.AutoDetect=1024]="AutoDetect",ez[ez.BasedOnInput=2048]="BasedOnInput",ez[ez.Undefined=4096]="Undefined",ez[ez.All=4095]="All",(eW=iB||(iB={}))[eW.Compatible=0]="Compatible",eW[eW.TypeIncompatible=1]="TypeIncompatible",eW[eW.HierarchyIssue=2]="HierarchyIssue",(eH=iU||(iU={}))[eH.Input=0]="Input",eH[eH.Output=1]="Output";class mf{get direction(){return this._direction}get type(){if(this._type===iw.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===iw.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._type=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map(e=>e.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}getConnectedValue(e){var t,i,r;return this.isConnected?(null===(t=this._connectedPoint)||void 0===t?void 0:t._storedFunction)?null===(i=this._connectedPoint)||void 0===i?void 0:i._storedFunction(e):null===(r=this._connectedPoint)||void 0===r?void 0:r._storedValue:this.value}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=[],this._type=iw.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new ri.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.value=null,this.valueMin=null,this.valueMax=null,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===iB.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==iw.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?iB.Compatible:iB.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return iB.TypeIncompatible;let r=i,s=t;return(this.direction===iU.Input&&(r=t,s=i),r.isAnAncestorOf(s))?iB.HierarchyIssue:iB.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t<iw.All;)e&t||this.excludedConnectionPointTypes.push(t),t<<=1}serialize(e=!0){let t={};return t.name=this.name,t.displayName=this.displayName,void 0!==this.value&&null!==this.value&&(this.value.asArray?(t.valueType="BABYLON."+this.value.getClassName(),t.value=this.value.asArray()):(t.valueType="number",t.value=this.value)),e&&this.connectedPoint&&(t.inputName=this.name,t.targetBlockId=this.connectedPoint.ownerBlock.uniqueId,t.targetConnectionName=this.connectedPoint.name),t}dispose(){this.onConnectionObservable.clear()}}class mm{get buildExecutionTime(){return this._buildExecutionTime}get inputs(){return this._inputs}get outputs(){return this._outputs}get name(){return this._name}set name(e){this._name=e}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isUnique(){return this._isUnique}getClassName(){return"NodeGeometryBlock"}_inputRename(e){return e}_outputRename(e){return e}isAnAncestorOf(e){for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock.isAnAncestorOfType(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(let t of this._outputs)if(t.hasEndpoints)for(let i of t.endpoints){let t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}constructor(e){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isUnique=!1,this._buildExecutionTime=0,this.onBuildObservable=new ri.y$,this._inputs=[],this._outputs=[],this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this._isInput="GeometryInputBlock"===this.getClassName(),this._isTeleportOut="TeleportOutBlock"===this.getClassName(),this._isTeleportIn="TeleportInBlock"===this.getClassName(),this.uniqueId=sZ.K.UniqueId}registerInput(e,t,i=!1,r,s,n){let a=new mf(e,this,iU.Input);return a.type=t,a.isOptional=i,a.value=r,a.valueMin=s,a.valueMax=n,this._inputs.push(a),this}registerOutput(e,t,i){return(i=null!=i?i:new mf(e,this,iU.Output)).type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}build(e){if(this._buildId===e.buildId)return!0;if(this._outputs.length>0&&!this._outputs.some(e=>e.hasEndpoints))return!1;for(let t of(this._buildId=e.buildId,this._inputs)){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}let i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&console.log(`Building ${this.name} [${this.getClassName()}]`);let t=rM.F.Now;for(let i of(this._buildBlock(e),this._buildExecutionTime=rM.F.Now-t,this._outputs))for(let t of i.endpoints){let i=t.ownerBlock;i&&i.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}serialize(e){let t={};for(let e of(t.customType="BABYLON."+this.getClassName(),t.id=this.uniqueId,t.name=this.name,t.inputs=[],t.outputs=[],this.inputs))t.inputs.push(e.serialize());for(let e of this.outputs)t.outputs.push(e.serialize(!1));return t}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach((e,t)=>{if(e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value){if("number"===e.valueType)this.inputs[t].value=e.value;else{let i=(0,rn.q)(e.valueType);i&&(this.inputs[t].value=i.FromArray(e.value))}}}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleOnFrame = ${this.visibleOnFrame}; -`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); -`}return t}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` -// ${this.getClassName()} -`;for(let i of(this.comments&&(r+=`// ${this.comments} -`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); -`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint,n=s.ownerBlock;-1===t.indexOf(n)&&(r+=n._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){let e=this.serialize(),t=(0,rn.q)(e.customType);if(t){let i=new t;return i._deserialize(e),i}return null}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose();this.onBuildObservable.clear()}}(0,r0.gn)([(0,rg.qC)("comment")],mm.prototype,"comments",void 0);class mg extends mm{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",iw.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}(0,rn.H)("BABYLON.GeometryOutputBlock",mg),(eX=iV||(iV={}))[eX.None=0]="None",eX[eX.Positions=1]="Positions",eX[eX.Normals=2]="Normals",eX[eX.Tangents=3]="Tangents",eX[eX.UV=4]="UV",eX[eX.UV2=5]="UV2",eX[eX.UV3=6]="UV3",eX[eX.UV4=7]="UV4",eX[eX.UV5=8]="UV5",eX[eX.UV6=9]="UV6",eX[eX.Colors=10]="Colors",eX[eX.VertexID=11]="VertexID",eX[eX.FaceID=12]="FaceID",eX[eX.GeometryID=13]="GeometryID",eX[eX.CollectionID=14]="CollectionID",eX[eX.LoopID=15]="LoopID";class mv{constructor(){this._rotationMatrix=new rr.y3,this._scalingMatrix=new rr.y3,this._positionMatrix=new rr.y3,this._scalingRotationMatrix=new rr.y3,this._transformMatrix=new rr.y3,this._tempVector3=new rr.P,this.notConnectedNonOptionalInputs=[],this.vertexData=null,this.geometryContext=null,this.executionContext=null}getContextualValue(e){if(!this.executionContext)return null;let t=this.executionContext.getExecutionIndex();switch(e){case iV.Positions:if(this.executionContext.getOverridePositionsContextualValue)return this.executionContext.getOverridePositionsContextualValue();if(!this.geometryContext||!this.geometryContext.positions)return rr.P.Zero();return rr.P.FromArray(this.geometryContext.positions,3*t);case iV.Normals:if(this.executionContext.getOverrideNormalsContextualValue)return this.executionContext.getOverrideNormalsContextualValue();if(!this.geometryContext||!this.geometryContext.normals)return rr.P.Zero();return rr.P.FromArray(this.geometryContext.normals,3*t);case iV.Colors:if(!this.geometryContext||!this.geometryContext.colors)return rr.Lt.Zero();return rr.Lt.FromArray(this.geometryContext.colors,4*t);case iV.Tangents:if(!this.geometryContext||!this.geometryContext.tangents)return rr.Lt.Zero();return rr.Lt.FromArray(this.geometryContext.tangents,4*t);case iV.UV:if(!this.geometryContext||!this.geometryContext.uvs)return rr.FM.Zero();return rr.FM.FromArray(this.geometryContext.uvs,2*t);case iV.UV2:if(!this.geometryContext||!this.geometryContext.uvs2)return rr.FM.Zero();return rr.FM.FromArray(this.geometryContext.uvs2,2*t);case iV.UV3:if(!this.geometryContext||!this.geometryContext.uvs3)return rr.FM.Zero();return rr.FM.FromArray(this.geometryContext.uvs3,2*t);case iV.UV4:if(!this.geometryContext||!this.geometryContext.uvs4)return rr.FM.Zero();return rr.FM.FromArray(this.geometryContext.uvs4,2*t);case iV.UV5:if(!this.geometryContext||!this.geometryContext.uvs5)return rr.FM.Zero();return rr.FM.FromArray(this.geometryContext.uvs5,2*t);case iV.UV6:if(!this.geometryContext||!this.geometryContext.uvs6)return rr.FM.Zero();return rr.FM.FromArray(this.geometryContext.uvs6,2*t);case iV.VertexID:return t;case iV.FaceID:return this.executionContext.getExecutionFaceIndex();case iV.LoopID:return this.executionContext.getExecutionLoopIndex();case iV.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case iV.CollectionID:if(!this.geometryContext||!this.geometryContext.metadata)return 0;return this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){let i=e.getConnectedValue(this);if(e.type===t)return i;switch(t){case iw.Vector2:return new rr.FM(i,i);case iw.Vector3:return new rr.P(i,i,i);case iw.Vector4:return new rr.Lt(i,i,i,i)}return null}adaptInput(e,t,i){var r;if(!e.isConnected)return e.value||i;let s=e.getConnectedValue(this);if((null===(r=e._connectedPoint)||void 0===r?void 0:r.type)===t)return s;switch(t){case iw.Vector2:return new rr.FM(s,s);case iw.Vector3:return new rr.P(s,s,s);case iw.Vector4:return new rr.Lt(s,s,s,s)}return null}emitErrors(){let e="";for(let t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. -`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,r,s){rr.y3.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),rr.y3.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),rr.y3.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;t<e.positions.length;t+=3)this._tempVector3.fromArray(e.positions,t),rr.P.TransformCoordinatesToRef(this._tempVector3,this._transformMatrix,this._tempVector3),this._tempVector3.toArray(e.positions,t),e.normals&&(this._tempVector3.fromArray(e.normals,t),rr.P.TransformNormalToRef(this._tempVector3,this._scalingRotationMatrix,this._tempVector3),this._tempVector3.toArray(e.normals,t));s.push(e)}_instantiateWithMatrix(e,t,i){for(let i=0;i<e.positions.length;i+=3)this._tempVector3.fromArray(e.positions,i),rr.P.TransformCoordinatesToRef(this._tempVector3,t,this._tempVector3),this._tempVector3.toArray(e.positions,i),e.normals&&(this._tempVector3.fromArray(e.normals,i),rr.P.TransformNormalToRef(this._tempVector3,t,this._tempVector3),this._tempVector3.toArray(e.normals,i));i.push(e)}}class mT extends mm{get type(){if(this._type===iw.AutoDetect&&null!=this.value){if(!isNaN(this.value))return this._type=iw.Float,this._type;switch(this.value.getClassName()){case"Vector2":this._type=iw.Vector2;break;case"Vector3":this._type=iw.Vector3;break;case"Vector4":this._type=iw.Vector4;break;case"Matrix":this._type=iw.Matrix}}return this._type}get isContextual(){return this._contextualSource!==iV.None}get contextualValue(){return this._contextualSource}set contextualValue(e){switch(this._contextualSource=e,e){case iV.Positions:case iV.Normals:this._type=iw.Vector3;break;case iV.Colors:case iV.Tangents:this._type=iw.Vector4;break;case iV.UV:case iV.UV2:case iV.UV3:case iV.UV4:case iV.UV5:case iV.UV6:this._type=iw.Vector2;break;case iV.VertexID:case iV.GeometryID:case iV.CollectionID:case iV.FaceID:case iV.LoopID:this._type=iw.Int}}constructor(e,t=iw.AutoDetect){super(e),this._type=iw.Undefined,this._contextualSource=iV.None,this.min=0,this.max=0,this.groupInInspector="",this.onValueChangedObservable=new ri.y$,this._type=t,this.setDefaultValue(),this.registerOutput("output",t)}get value(){return this._storedValue}set value(e){this.type===iw.Float&&this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e)),this._storedValue=e,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e}getClassName(){return"GeometryInputBlock"}get output(){return this._outputs[0]}setDefaultValue(){switch(this.contextualValue=iV.None,this.type){case iw.Int:case iw.Float:this.value=0;break;case iw.Vector2:this.value=rr.FM.Zero();break;case iw.Vector3:this.value=rr.P.Zero();break;case iw.Vector4:this.value=rr.Lt.Zero();break;case iw.Matrix:this.value=rr.y3.Identity()}}_buildBlock(e){super._buildBlock(e),this.isContextual?(this.output._storedValue=null,this.output._storedFunction=e=>e.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${iV[this._contextualSource]}; -`;let t=[],i="";switch(this.type){case iw.Float:case iw.Int:i=`${this.value}`;break;case iw.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case iw.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case iw.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),(this.type===iw.Float||this.type===iw.Int)&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){let e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=(0,rn.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}}(0,rn.H)("BABYLON.GeometryInputBlock",mT);class mx extends mm{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",iw.Float,!0,1),this.registerInput("width",iw.Float,!0,0),this.registerInput("height",iw.Float,!0,0),this.registerInput("depth",iw.Float,!0,0),this.registerInput("subdivisions",iw.Int,!0,1),this.registerInput("subdivisionsX",iw.Int,!0,0),this.registerInput("subdivisionsY",iw.Int,!0,0),this.registerInput("subdivisionsZ",iw.Int,!0,0),this.registerOutput("geometry",iw.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){let e=new mT("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new mT("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new mT("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){let e=new mT("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){let t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);let i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),r&&(t.widthSegments=r),s&&(t.heightSegments=s),n&&(t.depthSegments=n),function(e){let t=e.width||e.size||1,i=e.height||e.size||1,r=e.depth||e.size||1,s=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),a=0|(e.depthSegments||e.segments||1),o=new rr.y3,l=new rr.y3,h=new rr.y3,u=lW({width:t,height:r,subdivisionsX:s,subdivisionsY:a});rr.y3.TranslationToRef(0,-i/2,0,l),rr.y3.RotationZToRef(Math.PI,o),o.multiplyToRef(l,h),u.transform(h);let c=lW({width:t,height:r,subdivisionsX:s,subdivisionsY:a});rr.y3.TranslationToRef(0,i/2,0,h),c.transform(h);let d=lW({width:i,height:r,subdivisionsX:n,subdivisionsY:a});rr.y3.TranslationToRef(-t/2,0,0,l),rr.y3.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,h),d.transform(h);let p=lW({width:i,height:r,subdivisionsX:n,subdivisionsY:a});rr.y3.TranslationToRef(t/2,0,0,l),rr.y3.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,h),p.transform(h);let _=lW({width:t,height:i,subdivisionsX:s,subdivisionsY:n});rr.y3.TranslationToRef(0,0,-r/2,l),rr.y3.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,h),_.transform(h);let f=lW({width:t,height:i,subdivisionsX:s,subdivisionsY:n});return rr.y3.TranslationToRef(0,0,r/2,l),rr.y3.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,h),f.transform(h),u.merge([c,p,d,_,f],!0),u}(t)};this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedValue=i(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mx.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.BoxBlock",mx);class mS{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=mS._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new ri.y$,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){rZ.w1.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise(t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){let i=e&&e.editorURL?e.editorURL:mS.EditorURL;rZ.w1.LoadScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){let t=Object.assign({nodeGeometry:this},e);this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";let r=rM.F.Now;this._initializeBlock(this.outputBlock,i);let s=new mv;s.buildId=this._buildId,s.verbose=e,this.outputBlock.build(s),t&&(this._buildId=mS._BuildIdGenerator++),this._buildExecutionTime=rM.F.Now-r,s.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=s.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;let i=new rq.Kj(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){for(let i of(e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();let i={};for(let t of e.blocks){let e=(0,rn.q)(t.customType);if(e){let r=new e;r._deserialize(t),i[t.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e,r=t._tempEntryPointUniqueId;if(r){let e=i[r];e.attachToEndpoint(t)}}for(let r=0;r<e.blocks.length;r++){let s=e.blocks[r],n=i[s.id];!n||n.inputs.length&&s.inputs.some(e=>e.targetConnectionName)&&!t||this._restoreConnections(n,e,i)}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){let r=e.locations||e.editorData.locations;for(let e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);let s=[];for(let e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let n=i[s.id];if(n){for(let a of s.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===r.name){let e=n.getInputByName(a.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i);continue}}}}generateCode(){let e=[],t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); -`;for(let s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));return this.outputBlock&&(e=[],r+="\n`;// Connections\n`;"+this.outputBlock._dumpCodeForOutputConnections(e)+"\n`;// Output nodes\n`;"+`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; -`+`nodeGeometry.build(); -`),r}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}setToDefault(){this.clear(),this.editorData=null;let e=new mx("Box");e.autoConfigure();let t=new mg("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){let t=this.serialize(),i=rg.p4.Clone(()=>new mS(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e,t){let i=t?{}:rg.p4.Serialize(this);i.editorData=JSON.parse(JSON.stringify(this.editorData));let r=[];for(let s of(t?r=t:(i.customType="BABYLON.NodeGeometry",this.outputBlock&&(i.outputNodeId=this.outputBlock.uniqueId)),i.blocks=[],r))i.blocks.push(s.serialize(e));if(!t)for(let t of this.attachedBlocks)-1===r.indexOf(t)&&i.blocks.push(t.serialize(e));return i}dispose(){for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){let t=new mS(e);return t.setToDefault(),t.build(),t}static Parse(e){let t=rg.p4.Parse(()=>new mS(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(mS.CreateDefault("blank")):new Promise((r,s)=>{let n=new rS.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let a=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(a.nodeGeometry);t||(t=rg.p4.Parse(()=>new mS(e),o,null)),t.parseSerializedObject(o),t.snippetId=e;try{i||t.build(),r(t)}catch(e){s(e)}}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}mS._BuildIdGenerator=0,mS.EditorURL=`https://unpkg.com/babylonjs-node-geometry-editor@${r7.D.Version}/babylon.nodeGeometryEditor.js`,mS.SnippetUrl="https://snippet.babylonjs.com",(0,r0.gn)([(0,rg.qC)()],mS.prototype,"name",void 0),(0,r0.gn)([(0,rg.qC)("comment")],mS.prototype,"comment",void 0);class mE extends mm{constructor(e){super(e),this.evaluateContext=!1,this.epsilon=rL.kn,this.registerInput("geometry",iw.Geometry),this.registerOutput("output",iw.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e),i=[],r={};for(let e=0;e<t.positions.length;e+=3){let s=t.positions[e],n=t.positions[e+1],a=t.positions[e+2],o=!1;for(let t=0;t<i.length;t+=3)if(rm.R.WithinEpsilon(s,i[t],this.epsilon)&&rm.R.WithinEpsilon(n,i[t+1],this.epsilon)&&rm.R.WithinEpsilon(a,i[t+2],this.epsilon)){r[e/3]=t/3,o=!0;continue}o||(r[e/3]=i.length/3,i.push(s,n,a))}let s=new sN.x;return s.positions=i,s.indices=t.indices.map(e=>r[e]),s};this.evaluateContext?this.output._storedFunction=t:this.output._storedValue=t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`+`${this._codeVariableName}.epsilon = ${this.epsilon}; -`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mE.prototype,"evaluateContext",void 0),(0,r0.gn)([s2("Epsilon",tp.Float,"ADVANCED",{notifiers:{rebuild:!0}})],mE.prototype,"epsilon",void 0),(0,rn.H)("BABYLON.GeometryOptimizeBlock",mE);class mC extends mm{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",iw.Float,!0,1),this.registerInput("width",iw.Float,!0,0),this.registerInput("height",iw.Float,!0,0),this.registerOutput("geometry",iw.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){let e=new mT("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new mT("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new mT("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){let t={},i=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),sF(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedValue=i(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mC.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.PlaneBlock",mC),(0,rn.H)("BABYLON.MeshBlock",class extends mm{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.registerOutput("geometry",iw.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}this.geometry._storedValue=sN.x.ExtractFromMesh(this._mesh,!1,!0),this._cachedVertexData=null}serialize(e){let t=super.serialize();return e&&(this._mesh?t.cachedVertexData=sN.x.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(t.cachedVertexData=this._cachedVertexData.serialize())),t}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=sN.x.Parse(e.cachedVertexData))}});class mb extends mm{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",iw.Float,!0,1),this.registerInput("radiusX",iw.Float,!0,0),this.registerInput("radiusY",iw.Float,!0,0),this.registerInput("radiusZ",iw.Float,!0,0),this.registerInput("subdivisions",iw.Int,!0,4),this.registerOutput("geometry",iw.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new mT("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),nj(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedValue=i(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mb.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.IcoSphereBlock",mb);class my extends mm{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",iw.Int,!0,32),this.registerInput("diameter",iw.Float,!0,1),this.registerInput("diameterX",iw.Float,!0,0),this.registerInput("diameterY",iw.Float,!0,0),this.registerInput("diameterZ",iw.Float,!0,0),this.registerInput("arc",iw.Float,!0,1),this.registerInput("slice",iw.Float,!0,1),this.registerOutput("geometry",iw.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new mT("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),hn(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedValue=i(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],my.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.SphereBlock",my);class mA extends mm{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",iw.Float,!0,1),this.registerInput("height",iw.Float,!0,1),this.registerInput("subdivisions",iw.Int,!0,1),this.registerInput("subdivisionsX",iw.Int,!0,0),this.registerInput("subdivisionsY",iw.Int,!0,0),this.registerOutput("geometry",iw.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){let e=new mT("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new mT("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),lW(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedValue=i(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mA.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.GridBlock",mA);class mR extends mm{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",iw.Float,!0,1),this.registerInput("thickness",iw.Float,!0,.5),this.registerInput("tessellation",iw.Int,!0,16),this.registerOutput("geometry",iw.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new mT("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),lk(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedValue=i(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mR.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.TorusBlock",mR);class mP extends mm{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",iw.Float,!0,25),this.registerInput("diameter",iw.Float,!0,1),this.registerInput("diameterTop",iw.Float,!0,0),this.registerInput("diameterBottom",iw.Float,!0,0),this.registerInput("subdivisions",iw.Int,!0,1),this.registerInput("tessellation",iw.Int,!0,24),this.registerInput("arc",iw.Float,!0,1),this.registerOutput("geometry",iw.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new mT("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){let e=new mT("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameter||(t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e)),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),lU(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedValue=i(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mP.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.CylinderBlock",mP);class mI extends mm{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",iw.Float,!0,1),this.registerInput("radius",iw.Float,!0,.25),this.registerInput("tessellation",iw.Int,!0,16),this.registerInput("subdivisions",iw.Int,!0,2),this.registerOutput("geometry",iw.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){let e=new mT("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){let e=new mT("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),ho(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedValue=i(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mI.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.CapsuleBlock",mI);class mM extends mm{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",iw.Float,!0,.5),this.registerInput("tessellation",iw.Int,!0,64),this.registerInput("arc",iw.Float,!0,1),this.registerOutput("geometry",iw.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new mT("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),hu(t));this.evaluateContext?this.geometry._storedFunction=i:this.geometry._storedValue=i(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mM.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.DiscBlock",mM),(0,rn.H)("BABYLON.NullBlock",class extends mm{constructor(e){super(e),this.registerOutput("geometry",iw.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}),(0,rn.H)("BABYLON.SetPositionsBlock",class extends mm{constructor(e){super(e),this.registerInput("geometry",iw.Geometry),this.registerInput("positions",iw.Vector3),this.registerOutput("output",iw.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(e.executionContext=this,this._vertexData=this.geometry.getConnectedValue(e),e.geometryContext=this._vertexData,!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){e.executionContext=null,e.geometryContext=null,this.output._storedValue=null;return}let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.positions.getConnectedValue(e);t&&t.toArray(this._vertexData.positions,3*this._currentIndex)}this.output._storedValue=this._vertexData,e.executionContext=null,e.geometryContext=null}}),(0,rn.H)("BABYLON.SetNormalsBlock",class extends mm{constructor(e){super(e),this.registerInput("geometry",iw.Geometry),this.registerInput("normals",iw.Vector3),this.registerOutput("output",iw.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetNormalsBlock"}get geometry(){return this._inputs[0]}get normals(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(e.executionContext=this,this._vertexData=this.geometry.getConnectedValue(e),e.geometryContext=this._vertexData,!this._vertexData||!this._vertexData.positions){e.executionContext=null,e.geometryContext=null,this.output._storedValue=null;return}if(!this.normals.isConnected){e.executionContext=null,e.geometryContext=null,this.output._storedValue=this._vertexData;return}this._vertexData.normals||(this._vertexData.normals=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.normals.getConnectedValue(e);t&&t.toArray(this._vertexData.normals,3*this._currentIndex)}this.output._storedValue=this._vertexData,e.executionContext=null,e.geometryContext=null}});class mD extends mm{constructor(e){super(e),this.textureCoordinateIndex=0,this.registerInput("geometry",iw.Geometry),this.registerInput("uvs",iw.Vector2),this.registerOutput("output",iw.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetUVsBlock"}get geometry(){return this._inputs[0]}get uvs(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(e.executionContext=this,this._vertexData=this.geometry.getConnectedValue(e),e.geometryContext=this._vertexData,!this._vertexData||!this._vertexData.positions){e.executionContext=null,e.geometryContext=null,this.output._storedValue=null;return}if(!this.uvs.isConnected){e.executionContext=null,e.geometryContext=null,this.output._storedValue=this._vertexData;return}let t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<i;this._currentIndex++){let i=this.uvs.getConnectedValue(e);i&&i.toArray(t,2*this._currentIndex)}switch(this.textureCoordinateIndex){case 0:this._vertexData.uvs=t;break;case 1:this._vertexData.uvs2=t;break;case 2:this._vertexData.uvs3=t;break;case 3:this._vertexData.uvs4=t;break;case 4:this._vertexData.uvs5=t;break;case 5:this._vertexData.uvs6=t}this.output._storedValue=this._vertexData,e.executionContext=null,e.geometryContext=null}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.textureCoordinateIndex}; -`;return e}serialize(){let e=super.serialize();return e.textureCoordinateIndex=this.textureCoordinateIndex,e}_deserialize(e){super._deserialize(e),this.textureCoordinateIndex=e.textureCoordinateIndex}}(0,r0.gn)([s2("Texture coordinates index",tp.List,"ADVANCED",{notifiers:{update:!0},options:[{label:"UV1",value:0},{label:"UV2",value:1},{label:"UV3",value:2},{label:"UV4",value:3},{label:"UV5",value:4},{label:"UV6",value:5}]})],mD.prototype,"textureCoordinateIndex",void 0),(0,rn.H)("BABYLON.SetUVsBlock",mD),(0,rn.H)("BABYLON.SetColorsBlock",class extends mm{constructor(e){super(e),this.registerInput("geometry",iw.Geometry),this.registerInput("colors",iw.Vector4),this.registerOutput("output",iw.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetColorsBlock"}get geometry(){return this._inputs[0]}get colors(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(e.executionContext=this,this._vertexData=this.geometry.getConnectedValue(e),e.geometryContext=this._vertexData,!this._vertexData||!this._vertexData.positions){e.executionContext=null,e.geometryContext=null,this.output._storedValue=null;return}if(!this.colors.isConnected){e.executionContext=null,e.geometryContext=null,this.output._storedValue=this._vertexData;return}this._vertexData.colors||(this._vertexData.colors=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.colors.getConnectedValue(e);t&&t.toArray(this._vertexData.colors,4*this._currentIndex)}this.output._storedValue=this._vertexData,e.executionContext=null,e.geometryContext=null}}),(0,rn.H)("BABYLON.SetTangentsBlock",class extends mm{constructor(e){super(e),this.registerInput("geometry",iw.Geometry),this.registerInput("tangents",iw.Vector4),this.registerOutput("output",iw.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetTangentsBlock"}get geometry(){return this._inputs[0]}get tangents(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(e.executionContext=this,this._vertexData=this.geometry.getConnectedValue(e),e.geometryContext=this._vertexData,!this._vertexData||!this._vertexData.positions){e.executionContext=null,e.geometryContext=null,this.output._storedValue=null;return}if(!this.tangents.isConnected){e.executionContext=null,e.geometryContext=null,this.output._storedValue=this._vertexData;return}this._vertexData.tangents||(this._vertexData.tangents=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.tangents.getConnectedValue(e);t&&t.toArray(this._vertexData.tangents,4*this._currentIndex)}this.output._storedValue=this._vertexData,e.executionContext=null,e.geometryContext=null}}),(eY=ik||(ik={}))[eY.Add=0]="Add",eY[eY.Subtract=1]="Subtract",eY[eY.Multiply=2]="Multiply",eY[eY.Divide=3]="Divide",eY[eY.Max=4]="Max",eY[eY.Min=5]="Min";class mO extends mm{constructor(e){super(e),this.operation=ik.Add,this.registerInput("left",iw.AutoDetect),this.registerInput("right",iw.AutoDetect),this.registerOutput("output",iw.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iw.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iw.Geometry),this._inputs[1].excludedConnectionPointTypes.push(iw.Matrix),this._inputs[1].excludedConnectionPointTypes.push(iw.Geometry),this._linkConnectionTypes(0,1)}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;let t=this.left,i=this.right;if(!t.isConnected||!i.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let r=t.type===iw.Float||t.type===iw.Int;switch(this.operation){case ik.Add:e=r?e=>t.getConnectedValue(e)+i.getConnectedValue(e):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case ik.Subtract:e=r?e=>t.getConnectedValue(e)-i.getConnectedValue(e):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case ik.Multiply:e=r?e=>t.getConnectedValue(e)*i.getConnectedValue(e):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case ik.Divide:e=r?e=>t.getConnectedValue(e)/i.getConnectedValue(e):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case ik.Min:if(r)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case iw.Vector2:e=e=>rr.FM.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iw.Vector3:e=e=>rr.P.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iw.Vector4:e=e=>rr.Lt.Minimize(t.getConnectedValue(e),e.adapt(i,t.type))}break;case ik.Max:if(r)e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case iw.Vector2:e=e=>rr.FM.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iw.Vector3:e=e=>rr.P.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iw.Vector4:e=e=>rr.Lt.Maximize(t.getConnectedValue(e),e.adapt(i,t.type))}}this.output._storedFunction=i=>t.type===iw.Int?0|e(i):e(i)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${ik[this.operation]}; -`;return e}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}(0,r0.gn)([s2("Operation",tp.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:ik.Add},{label:"Subtract",value:ik.Subtract},{label:"Multiply",value:ik.Multiply},{label:"Divide",value:ik.Divide},{label:"Max",value:ik.Max},{label:"Min",value:ik.Min}]})],mO.prototype,"operation",void 0),(0,rn.H)("BABYLON.MathBlock",mO),(0,rn.H)("BABYLON.MapRangeBlock",class extends mm{constructor(e){super(e),this.registerInput("value",iw.AutoDetect),this.registerInput("fromMin",iw.Float,!0,0),this.registerInput("fromMax",iw.Float,!0,1),this.registerInput("toMin",iw.Float,!0,0),this.registerInput("toMax",iw.Float,!0,1),this.registerOutput("output",iw.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iw.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iw.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.output._storedFunction=e=>{let t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),n=this.toMax.getConnectedValue(e);return(t-i)/(r-i)*(n-s)+s}}}),(ej=iG||(iG={}))[ej.Equal=0]="Equal",ej[ej.NotEqual=1]="NotEqual",ej[ej.LessThan=2]="LessThan",ej[ej.GreaterThan=3]="GreaterThan",ej[ej.LessOrEqual=4]="LessOrEqual",ej[ej.GreaterOrEqual=5]="GreaterOrEqual",ej[ej.Xor=6]="Xor",ej[ej.Or=7]="Or",ej[ej.And=8]="And";class mN extends mm{constructor(e){super(e),this.test=iG.Equal,this.registerInput("left",iw.Float),this.registerInput("right",iw.Float,!0,0),this.registerInput("ifTrue",iw.AutoDetect,!0,1),this.registerInput("ifFalse",iw.AutoDetect,!0,0),this.registerOutput("output",iw.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=iw.Float,this._inputs[0].acceptedConnectionPointTypes.push(iw.Int),this._inputs[1].acceptedConnectionPointTypes.push(iw.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let e=e=>{let t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e),r=!1;switch(this.test){case iG.Equal:r=rm.R.WithinEpsilon(t,i,rL.kn);break;case iG.NotEqual:r=t!==i;break;case iG.LessThan:r=t<i;break;case iG.GreaterThan:r=t>i;break;case iG.LessOrEqual:r=t<=i;break;case iG.GreaterOrEqual:r=t>=i;break;case iG.Xor:r=!!t&&!i||!t&&!!i;break;case iG.Or:r=!!t||!!i;break;case iG.And:r=!!t&&!!i}return r};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${iG[this.test]}; -`;return e}serialize(){let e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}(0,r0.gn)([s2("Test",tp.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:iG.Equal},{label:"NotEqual",value:iG.NotEqual},{label:"LessThan",value:iG.LessThan},{label:"GreaterThan",value:iG.GreaterThan},{label:"LessOrEqual",value:iG.LessOrEqual},{label:"GreaterOrEqual",value:iG.GreaterOrEqual},{label:"Xor",value:iG.Xor},{label:"Or",value:iG.Or},{label:"And",value:iG.And}]})],mN.prototype,"test",void 0),(0,rn.H)("BABYLON.ConditionBlock",mN),(0,rn.H)("BABYLON.RandomBlock",class extends mm{constructor(e){super(e),this.registerInput("min",iw.AutoDetect),this.registerInput("max",iw.AutoDetect),this.registerOutput("output",iw.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iw.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iw.Geometry),this._inputs[1].excludedConnectionPointTypes.push(iw.Matrix),this._inputs[1].excludedConnectionPointTypes.push(iw.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){let e=new mT("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){let e=new mT("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this.min.type){case iw.Int:case iw.Float:e=e=>{let t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case iw.Vector2:e=e=>{let t=this.min.getConnectedValue(e)||rr.FM.Zero(),i=this.max.getConnectedValue(e)||rr.FM.Zero();return new rr.FM(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case iw.Vector3:e=e=>{let t=this.min.getConnectedValue(e)||rr.P.Zero(),i=this.max.getConnectedValue(e)||rr.P.Zero();return new rr.P(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case iw.Vector4:e=e=>{let t=this.min.getConnectedValue(e)||rr.Lt.Zero(),i=this.max.getConnectedValue(e)||rr.Lt.Zero();return new rr.Lt(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.output._storedFunction=e}}),(0,rn.H)("BABYLON.NoiseBlock",class extends mm{constructor(e){super(e),this.registerInput("offset",iw.Vector3,!0,rr.P.Zero()),this.registerInput("scale",iw.Float,!0,1),this.registerInput("octaves",iw.Float,!0,2,0,16),this.registerInput("roughness",iw.Float,!0,.5,0,1),this.registerOutput("output",iw.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,r){let s=15&e,n=s<8?t:i,a=12===s||14==s?t:r,o=s<4?i:a;return this._negateIf(n,s&n)+this._negateIf(o,2&s)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<<t|e>>32-t}_hash(e,t,i){let r,s,n;return r=s=n=3735928584,n+=i,s+=t,r+=e,n^=s,n-=this._hashBitRotate(s,14),r^=n,r-=this._hashBitRotate(n,11),s^=r,s-=this._hashBitRotate(r,25),n^=s,n-=this._hashBitRotate(s,16),r^=n,r-=this._hashBitRotate(n,4),s^=r,s-=this._hashBitRotate(r,14),n^=s,n-=this._hashBitRotate(s,24)}_mix(e,t,i,r,s,n,a,o,l,h,u){let c=1-l,d=1-h;return(1-u)*(d*(e*c+t*l)+h*(i*c+r*l))+u*(d*(s*c+n*l)+h*(a*c+o*l))}_perlinNoise(e){let t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),r=(0|e.z)-(e.z<0?1:0),s=e.x-t,n=e.y-i,a=e.z-r,o=this._fade(s),l=this._fade(n),h=this._fade(a);return this._mix(this._noiseGrad(this._hash(t,i,r),s,n,a),this._noiseGrad(this._hash(t+1,i,r),s-1,n,a),this._noiseGrad(this._hash(t,i+1,r),s,n-1,a),this._noiseGrad(this._hash(t+1,i+1,r),s-1,n-1,a),this._noiseGrad(this._hash(t,i,r+1),s,n,a-1),this._noiseGrad(this._hash(t+1,i,r+1),s-1,n,a-1),this._noiseGrad(this._hash(t,i+1,r+1),s,n-1,a-1),this._noiseGrad(this._hash(t+1,i+1,r+1),s-1,n-1,a-1),o,l,h)}_perlinSigned(e){return .982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,s){let n=new rr.P(i.x+r.x*s,i.y+r.y*s,i.z+r.z*s),a=1,o=1,l=0,h=0;e=rm.R.Clamp(e,0,15);let u=0|e;for(let e=0;e<=u;e++){let e=this._perlin(n.scale(a));h+=e*o,l+=o,o*=rm.R.Clamp(t,0,1),a*=2}let c=e-Math.floor(e);if(0==c)return h/l;let d=this._perlin(n.scale(a)),p=h+d*o;return(1-c)*(h/=l)+c*(p/=l+o)}_buildBlock(){this.output._storedFunction=e=>{let t=e.getContextualValue(iV.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,r,t,s,n)}}});class mF extends mm{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",iw.Geometry),this.registerInput("geometry1",iw.Geometry,!0),this.registerInput("geometry2",iw.Geometry,!0),this.registerInput("geometry3",iw.Geometry,!0),this.registerInput("geometry4",iw.Geometry,!0),this.registerOutput("output",iw.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{let t=this.geometry0.getConnectedValue(e),i=[];return this.geometry1.isConnected&&i.push(this.geometry1.getConnectedValue(e)),this.geometry2.isConnected&&i.push(this.geometry2.getConnectedValue(e)),this.geometry3.isConnected&&i.push(this.geometry3.getConnectedValue(e)),this.geometry4.isConnected&&i.push(this.geometry4.getConnectedValue(e)),i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=t:this.output._storedValue=t(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mF.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.MergeGeometryBlock",mF);class mL extends mm{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",iw.Geometry,!0),this.registerInput("geometry1",iw.Geometry,!0),this.registerInput("geometry2",iw.Geometry,!0),this.registerInput("geometry3",iw.Geometry,!0),this.registerInput("geometry4",iw.Geometry,!0),this.registerInput("geometry5",iw.Geometry,!0),this.registerInput("geometry6",iw.Geometry,!0),this.registerInput("geometry7",iw.Geometry,!0),this.registerInput("geometry8",iw.Geometry,!0),this.registerInput("geometry9",iw.Geometry,!0),this.registerOutput("output",iw.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){let s=e.getConnectedValue(t);s.metadata=s.metadata||{},s.metadata.collectionId=i,r.push(s)}}_buildBlock(e){let t=e=>{let t=[];return(this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length)?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:this.output._storedValue=t(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mL.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.GeometryCollectionBlock",mL),(0,rn.H)("BABYLON.GeometryElbowBlock",class extends mm{constructor(e){super(e),this.registerInput("input",iw.AutoDetect),this.registerOutput("output",iw.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}}),(0,rn.H)("BABYLON.ComputeNormalsBlock",class extends mm{constructor(e){super(e),this.registerInput("geometry",iw.Geometry),this.registerOutput("output",iw.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),sN.x.ComputeNormals(t.positions,t.indices,t.normals),t}}}),(0,rn.H)("BABYLON.VectorConverterBlock",class extends mm{constructor(e){super(e),this.registerInput("xyzw ",iw.Vector4,!0),this.registerInput("xyz ",iw.Vector3,!0),this.registerInput("xy ",iw.Vector2,!0),this.registerInput("zw ",iw.Vector2,!0),this.registerInput("x ",iw.Float,!0),this.registerInput("y ",iw.Float,!0),this.registerInput("z ",iw.Float,!0),this.registerInput("w ",iw.Float,!0),this.registerOutput("xyzw",iw.Vector4),this.registerOutput("xyz",iw.Vector3),this.registerOutput("xy",iw.Vector2),this.registerOutput("zw",iw.Vector2),this.registerOutput("x",iw.Float),this.registerOutput("y",iw.Float),this.registerOutput("z",iw.Float),this.registerOutput("w",iw.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);let t=this.xIn,i=this.yIn,r=this.zIn,s=this.wIn,n=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,u=this.xyzOut,c=this.xyOut,d=this.zwOut,p=this.xOut,_=this.yOut,f=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,u=0,c=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(u=i.getConnectedValue(e)),r.isConnected&&(c=r.getConnectedValue(e)),s.isConnected&&(d=s.getConnectedValue(e)),n.isConnected){let t=n.getConnectedValue(e);t&&(h=t.x,u=t.y)}if(a.isConnected){let t=a.getConnectedValue(e);t&&(c=t.x,d=t.y)}if(o.isConnected){let t=o.getConnectedValue(e);t&&(h=t.x,u=t.y,c=t.z)}return new rr.Lt(h,u,c,d)};h._storedFunction=e=>g(e),u._storedFunction=e=>{let t=g(e);return new rr.P(t.x,t.y,t.z)},c._storedFunction=e=>{let t=g(e);return new rr.FM(t.x,t.y)},d._storedFunction=e=>{let t=g(e);return new rr.FM(t.z,t.w)},p._storedFunction=e=>g(e).x,_._storedFunction=e=>g(e).y,f._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}),(0,rn.H)("BABYLON.NormalizeVectorBlock",class extends mm{constructor(e){super(e),this.registerInput("input",iw.AutoDetect),this.registerOutput("output",iw.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iw.Float),this._inputs[0].excludedConnectionPointTypes.push(iw.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iw.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),this.output._storedFunction=null,!this.input.isConnected){this.output._storedValue=null;return}this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize()}});class mw extends mm{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",iw.Geometry),this.registerInput("id",iw.Int,!0,0),this.registerOutput("output",iw.Geometry),this.id.acceptedConnectionPointTypes.push(iw.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let t=e=>{let t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;let i=new sN.D;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=t:this.output._storedValue=t(e)}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mw.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.SetMaterialIDBlock",mw),(eq=iz||(iz={}))[eq.Cos=0]="Cos",eq[eq.Sin=1]="Sin",eq[eq.Abs=2]="Abs",eq[eq.Exp=3]="Exp",eq[eq.Round=4]="Round",eq[eq.Floor=5]="Floor",eq[eq.Ceiling=6]="Ceiling",eq[eq.Sqrt=7]="Sqrt",eq[eq.Log=8]="Log",eq[eq.Tan=9]="Tan",eq[eq.ArcTan=10]="ArcTan",eq[eq.ArcCos=11]="ArcCos",eq[eq.ArcSin=12]="ArcSin",eq[eq.Sign=13]="Sign",eq[eq.Negate=14]="Negate",eq[eq.OneMinus=15]="OneMinus",eq[eq.Reciprocal=16]="Reciprocal",eq[eq.ToDegrees=17]="ToDegrees",eq[eq.ToRadians=18]="ToRadians";class mB extends mm{constructor(e){super(e),this.operation=iz.Cos,this.registerInput("input",iw.AutoDetect),this.registerOutput("output",iw.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iw.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iw.Geometry)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case iz.Cos:t=e=>Math.cos(e);break;case iz.Sin:t=e=>Math.sin(e);break;case iz.Abs:t=e=>Math.abs(e);break;case iz.Exp:t=e=>Math.exp(e);break;case iz.Round:t=e=>Math.round(e);break;case iz.Floor:t=e=>Math.floor(e);break;case iz.Ceiling:t=e=>Math.ceil(e);break;case iz.Sqrt:t=e=>Math.sqrt(e);break;case iz.Log:t=e=>Math.log(e);break;case iz.Tan:t=e=>Math.tan(e);break;case iz.ArcTan:t=e=>Math.atan(e);break;case iz.ArcCos:t=e=>Math.acos(e);break;case iz.ArcSin:t=e=>Math.asin(e);break;case iz.Sign:t=e=>Math.sign(e);break;case iz.Negate:t=e=>-e;break;case iz.OneMinus:t=e=>1-e;break;case iz.Reciprocal:t=e=>1/e;break;case iz.ToRadians:t=e=>e*Math.PI/180;break;case iz.ToDegrees:t=e=>180*e/Math.PI}if(!t){this.input._storedFunction=null,this.input._storedValue=null;return}switch(this.input.type){case iw.Int:case iw.Float:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return t(i)};break;case iw.Vector2:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rr.FM(t(i.x),t(i.y))};break;case iw.Vector3:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rr.P(t(i.x),t(i.y),t(i.z))};break;case iw.Vector4:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rr.Lt(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${iz[this.operation]}; -`;return e}}(0,r0.gn)([s2("Operation",tp.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:iz.Cos},{label:"Sin",value:iz.Sin},{label:"Abs",value:iz.Abs},{label:"Exp",value:iz.Exp},{label:"Round",value:iz.Round},{label:"Floor",value:iz.Floor},{label:"Ceiling",value:iz.Ceiling},{label:"Sqrt",value:iz.Sqrt},{label:"Log",value:iz.Log},{label:"Tan",value:iz.Tan},{label:"ArcTan",value:iz.ArcTan},{label:"ArcCos",value:iz.ArcCos},{label:"ArcSin",value:iz.ArcSin},{label:"Sign",value:iz.Sign},{label:"Negate",value:iz.Negate},{label:"OneMinus",value:iz.OneMinus},{label:"Reciprocal",value:iz.Reciprocal},{label:"ToDegrees",value:iz.ToDegrees},{label:"ToRadians",value:iz.ToRadians}]})],mB.prototype,"operation",void 0),(0,rn.H)("BABYLON.GeometryTrigonometryBlock",mB);class mU extends mm{constructor(e){super(e),this._rotationMatrix=new rr.y3,this._scalingMatrix=new rr.y3,this._translationMatrix=new rr.y3,this._scalingRotationMatrix=new rr.y3,this._transformMatrix=new rr.y3,this.evaluateContext=!0,this.registerInput("value",iw.AutoDetect),this.registerInput("matrix",iw.Matrix,!0),this.registerInput("translation",iw.Vector3,!0,rr.P.Zero()),this.registerInput("rotation",iw.Vector3,!0,rr.P.Zero()),this.registerInput("scaling",iw.Vector3,!0,rr.P.One()),this.registerOutput("output",iw.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iw.Float),this._inputs[0].excludedConnectionPointTypes.push(iw.Matrix)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let t=e=>{let t;let i=this.value.getConnectedValue(e);if(!i)return null;if(this.matrix.isConnected)t=this.matrix.getConnectedValue(e);else{let i=this.scaling.getConnectedValue(e),r=this.rotation.getConnectedValue(e),s=this.translation.getConnectedValue(e);rr.y3.ScalingToRef(i.x,i.y,i.z,this._scalingMatrix),rr.y3.RotationYawPitchRollToRef(r.y,r.x,r.z,this._rotationMatrix),rr.y3.TranslationToRef(s.x,s.y,s.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),t=this._transformMatrix}switch(this.value.type){case iw.Geometry:{let e=i.clone();return e.transform(t),e}case iw.Vector2:return rr.FM.Transform(i,t);case iw.Vector3:return rr.P.TransformCoordinates(i,t);case iw.Vector4:return rr.Lt.TransformCoordinates(i,t)}return null};this.evaluateContext?this.output._storedFunction=t:this.output._storedValue=t(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mU.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.GeometryTransformBlock",mU),(0,rn.H)("BABYLON.RotationXBlock",class extends mm{constructor(e){super(e),this.registerInput("angle",iw.Float,!1,0),this.registerOutput("matrix",iw.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new mT("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rr.y3.RotationX(this.angle.getConnectedValue(e))}}),(0,rn.H)("BABYLON.RotationYBlock",class extends mm{constructor(e){super(e),this.registerInput("angle",iw.Float,!1,0),this.registerOutput("matrix",iw.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new mT("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rr.y3.RotationY(this.angle.getConnectedValue(e))}}),(0,rn.H)("BABYLON.RotationZBlock",class extends mm{constructor(e){super(e),this.registerInput("angle",iw.Float,!1,0),this.registerOutput("matrix",iw.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new mT("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rr.y3.RotationZ(this.angle.getConnectedValue(e))}}),(0,rn.H)("BABYLON.ScalingBlock",class extends mm{constructor(e){super(e),this.registerInput("scale",iw.Vector3,!1,rr.P.One()),this.registerOutput("matrix",iw.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){let e=new mT("Scale");e.value=new rr.P(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.scale.getConnectedValue(e);return rr.y3.Scaling(t.x,t.y,t.z)}}}),(0,rn.H)("BABYLON.AlignBlock",class extends mm{constructor(e){super(e),this.registerInput("source",iw.Vector3,!0,rr.P.Up()),this.registerInput("target",iw.Vector3,!0,rr.P.Left()),this.registerOutput("matrix",iw.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),r=new rr.y3;return t.normalize(),i.normalize(),rr.y3.RotationAlignToRef(t,i,r),r}}}),(0,rn.H)("BABYLON.TranslationBlock",class extends mm{constructor(e){super(e),this.registerInput("translation",iw.Vector3,!1,rr.P.Zero()),this.registerOutput("matrix",iw.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){let e=new mT("Translation");e.value=new rr.P(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.translation.getConnectedValue(e);return rr.y3.Translation(t.x,t.y,t.z)}}});class mV extends mm{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",iw.Geometry),this.registerInput("instance",iw.Geometry,!0),this.registerInput("rotation",iw.Vector3,!0,rr.P.Zero()),this.registerInput("scaling",iw.Vector3,!0,rr.P.One()),this.registerInput("density",iw.Float,!0,1,0,1),this.scaling.acceptedConnectionPointTypes.push(iw.Float),this.registerOutput("output",iw.Geometry)}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get rotation(){return this._inputs[2]}get scaling(){return this._inputs[3]}get density(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.executionContext=this,this._vertexData=this.geometry.getConnectedValue(e),e.geometryContext=this._vertexData,!this._vertexData||!this._vertexData.positions||!this.instance.isConnected){e.executionContext=null,e.geometryContext=null,this.output._storedValue=null;return}let t=this._vertexData.positions.length/3,i=[],r=new rr.P,s=[],n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let e=n[3*this._currentIndex],t=n[3*this._currentIndex+1],i=n[3*this._currentIndex+2],r=!1;for(let n=0;n<s.length;n+=3)if(Math.abs(s[n]-e)<rL.kn&&Math.abs(s[n+1]-t)<rL.kn&&Math.abs(s[n+2]-i)<rL.kn){r=!0;break}r||(this._indexTranslation[s.length/3]=this._currentIndex,s.push(e,t,i))}t=(n=s).length/3}else this._indexTranslation=null;for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.instance.getConnectedValue(e);if(!t||!t.positions||0===t.positions.length)continue;let s=this.density.getConnectedValue(e);if(s<1&&Math.random()>s)continue;r.fromArray(n,3*this._currentIndex);let a=t.clone(),o=e.adaptInput(this.scaling,iw.Vector3,rr.P.OneReadOnly),l=this.rotation.getConnectedValue(e)||rr.P.ZeroReadOnly;e._instantiate(a,r,l,o,i),this._currentLoopIndex++}if(i.length){if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:this.output._storedValue=t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"}; -`+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`}serialize(){let e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mV.prototype,"evaluateContext",void 0),(0,r0.gn)([s2("Remove duplicated positions",tp.Boolean,"ADVANCED",{notifiers:{update:!0}})],mV.prototype,"removeDuplicatedPositions",void 0),(0,rn.H)("BABYLON.InstantiateOnVerticesBlock",mV);class mk extends mm{constructor(e){super(e),this._currentPosition=new rr.P,this._vertex0=new rr.P,this._vertex1=new rr.P,this._vertex2=new rr.P,this._tempVector0=new rr.P,this._tempVector1=new rr.P,this.evaluateContext=!0,this.registerInput("geometry",iw.Geometry),this.registerInput("instance",iw.Geometry,!0),this.registerInput("rotation",iw.Vector3,!0,rr.P.Zero()),this.registerInput("scaling",iw.Vector3,!0,rr.P.One()),this.registerInput("count",iw.Int,!0,256),this.scaling.acceptedConnectionPointTypes.push(iw.Float),this.registerOutput("output",iw.Geometry)}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),rr.P.Cross(this._tempVector1,this._tempVector0)}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get rotation(){return this._inputs[2]}get scaling(){return this._inputs[3]}get count(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.executionContext=this,this._vertexData=this.geometry.getConnectedValue(e),e.geometryContext=this._vertexData,!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.executionContext=null,e.geometryContext=null,this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=this._vertexData.indices.length/3,s=i/r,n=0,a=[],o=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex<r;this._currentFaceIndex++){this._vertex0.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*this._currentFaceIndex]),this._vertex1.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*this._currentFaceIndex+1]),this._vertex2.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*this._currentFaceIndex+2]),n+=s;let r=(0|n)-o;if(!(r<1))for(let s=0;s<r&&!(o>=i);s++){let i=Math.random(),r=Math.random();if(i>r){let e=i;i=r,r=e}let s=i,n=r-i,l=1-s-n;if(this._currentPosition.set(s*this._vertex0.x+n*this._vertex1.x+l*this._vertex2.x,s*this._vertex0.y+n*this._vertex1.y+l*this._vertex2.y,s*this._vertex0.z+n*this._vertex1.z+l*this._vertex2.z),!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length)continue;let h=t.clone(),u=e.adaptInput(this.scaling,iw.Vector3,rr.P.OneReadOnly),c=this.rotation.getConnectedValue(e)||rr.P.ZeroReadOnly;e._instantiate(h,this._currentPosition,c,u,a),o++,this._currentLoopIndex++}}if(a.length){if(1===a.length)this._vertexData=a[0];else{let e=a.splice(0,1)[0];this._vertexData=e.merge(a,!0,!1,!0,!0)}}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:this.output._storedValue=t(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mk.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.InstantiateOnFacesBlock",mk);class mG extends mm{constructor(e){super(e),this._currentPosition=new rr.P,this._vertex0=new rr.P,this._vertex1=new rr.P,this._vertex2=new rr.P,this.evaluateContext=!0,this.registerInput("geometry",iw.Geometry),this.registerInput("instance",iw.Geometry,!0),this.registerInput("rotation",iw.Vector3,!0,rr.P.Zero()),this.registerInput("scaling",iw.Vector3,!0,rr.P.One()),this.registerInput("count",iw.Int,!0,256),this.scaling.acceptedConnectionPointTypes.push(iw.Float),this.registerOutput("output",iw.Geometry)}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get rotation(){return this._inputs[2]}get scaling(){return this._inputs[3]}get count(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.executionContext=this,this._vertexData=this.geometry.getConnectedValue(e),e.geometryContext=this._vertexData,!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.executionContext=null,e.geometryContext=null,this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=[],s=(0,f3.k)(this._vertexData.positions,0,this._vertexData.positions.length/3),n=s.minimum,a=s.maximum,o=new rr.P(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let s=0;s<i;s++){this._currentPosition.set(Math.random()*(a.x-n.x)+n.x,Math.random()*(a.y-n.y)+n.y,Math.random()*(a.z-n.z)+n.z);let i=new sD(this._currentPosition,o),h=0;for(let e=0;e<l;e++){this._vertex0.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*e]),this._vertex1.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*e+1]),this._vertex2.fromArray(this._vertexData.positions,3*this._vertexData.indices[3*e+2]);let t=i.intersectsTriangle(this._vertex0,this._vertex1,this._vertex2);t&&t.distance>0&&h++}if(h%2==0){s--;continue}if(!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length)continue;let u=t.clone(),c=e.adaptInput(this.scaling,iw.Vector3,rr.P.OneReadOnly),d=this.rotation.getConnectedValue(e)||rr.P.ZeroReadOnly;e._instantiate(u,this._currentPosition,d,c,r),this._currentLoopIndex++}if(r.length){if(1===r.length)this._vertexData=r[0];else{let e=r.splice(0,1)[0];this._vertexData=e.merge(r,!0,!1,!0,!0)}}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:this.output._storedValue=t(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mG.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.InstantiateOnVolumeBlock",mG);class mz extends mm{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",iw.Geometry,!0),this.registerInput("count",iw.Int,!0,1),this.registerInput("position",iw.Vector3,!0,rr.P.Zero()),this.registerInput("rotation",iw.Vector3,!0,rr.P.Zero()),this.registerInput("scaling",iw.Vector3,!0,rr.P.One()),this.registerInput("matrix",iw.Matrix,!0),this.scaling.acceptedConnectionPointTypes.push(iw.Float),this.registerOutput("output",iw.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get position(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get matrix(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{e.executionContext=this;let t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex<t;this._currentIndex++){let t=this.instance.getConnectedValue(e);if(!t||!t.positions||0===t.positions.length)continue;let r=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithMatrix(r,t,i)}else{let t=this.position.getConnectedValue(e)||rr.P.ZeroReadOnly,s=e.adaptInput(this.scaling,iw.Vector3,rr.P.OneReadOnly),n=this.rotation.getConnectedValue(e)||rr.P.ZeroReadOnly;e._instantiate(r,t,n,s,i)}}if(i.length){if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:this.output._storedValue=t(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,r0.gn)([s2("Evaluate context",tp.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],mz.prototype,"evaluateContext",void 0),(0,rn.H)("BABYLON.InstantiateBlock",mz),(0,rn.H)("BABYLON.IntFloatConverterBlock",class extends mm{constructor(e){super(e),this.registerInput("float ",iw.Float,!0),this.registerInput("int ",iw.Int,!0),this.registerOutput("float",iw.Float),this.registerOutput("int",iw.Int)}getClassName(){return"IntFloatConverterBlock"}get floatIn(){return this._inputs[0]}get intIn(){return this._inputs[1]}get floatOut(){return this._outputs[0]}get intOut(){return this._outputs[1]}_inputRename(e){return"float "===e?"floatIn":"int "===e?"intIn":e}_buildBlock(){this.floatOut._storedFunction=e=>this.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?0|this.floatIn.getConnectedValue(e):this.intIn.isConnected?0|this.intIn.getConnectedValue(e):0}}),(0,rn.H)("BABYLON.DebugBlock",class extends mm{constructor(e){super(e),this.log=[],this.registerInput("input",iw.AutoDetect),this.registerOutput("output",iw.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iw.Geometry)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.log=[],this.output._storedFunction=e=>{let t=this.input.getConnectedValue(e);return this.log.push(null!=t?t.toString():"null"),t}}}),(0,rn.H)("BABYLON.GeometryInfoBlock",class extends mm{constructor(e){super(e),this.registerInput("geometry",iw.Geometry),this.registerOutput("output",iw.Geometry),this.registerOutput("id",iw.Int),this.registerOutput("collectionId",iw.Int),this.registerOutput("verticesCount",iw.Int),this.registerOutput("facesCount",iw.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected){this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,this.output._storedFunction=null;return}this.output._storedFunction=e=>this._currentVertexData||this.geometry.getConnectedValue(e),this.id._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}),(0,rn.H)("BABYLON.TeleportInBlock",class extends mm{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this.registerInput("input",iw.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(let e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}),(0,rn.H)("BABYLON.TeleportOutBlock",class extends mm{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",iw.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){let e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); -`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}),r7.D.OfflineProviderFactory=(e,t,i=!1)=>new mW(e,t,i);class mW{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=mW._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,mW.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,rZ.w1.SetImmediate(()=>{t(!0)})):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){let t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){let e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`},r=!1,s=i(),n=new rS.g;navigator.onLine&&(r=!0,s=s+(null==s.match(/\?/)?"?":"&")+Date.now()),n.open("GET",s),n.addEventListener("load",()=>{if(200===n.status||mW._ValidateXHRData(n,1))try{let t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&mW._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()},!1),n.addEventListener("error",()=>{if(r){r=!1;let e=i();n.open("GET",e),n.send()}else t()},!1);try{n.send()}catch(t){ru.Y.Error("Error on XHR send request."),e(!1)}}open(e,t){let 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;let t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{ru.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(e){ru.Y.Error("Error while creating object stores. Exception: "+e.message),i()}}}}else this._isSupported=!1,t&&t()}loadImage(e,t){let i=mW._ReturnFullUrlLocation(e),r=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?r():this._loadImageFromDBAsync(i,t,r)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let r;let s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;r&&"function"==typeof URL?(s=URL.createObjectURL(r.data),t.onerror=()=>{ru.Y.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};let n=s.objectStore("textures").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{ru.Y.Error("Error loading texture "+e+" from DB."),t.src=e}}else ru.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){let r=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(mW._IsUASupportingBlobStorage){let s=new rS.g;s.open("GET",e),s.responseType="blob",s.addEventListener("load",()=>{if(200===s.status&&this._db){i=s.response;let n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{let t=e.target,i=t.error;i&&"QuotaExceededError"===i.name&&(this._hasReachedQuota=!0)}catch(e){}r()},n.oncomplete=()=>{r()};let a={textureUrl:e,data:i};try{let e=n.objectStore("textures").put(a);e.onsuccess=()=>{},e.onerror=()=>{r()}}catch(i){25===i.code&&(mW._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),s.addEventListener("error",()=>{ru.Y.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),s.send()}else t.src=e}else ru.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 r;try{let s=this._db.transaction(["versions"]);s.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};let n=s.objectStore("versions").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{ru.Y.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){ru.Y.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else ru.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{let i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};let r={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(r);s.onsuccess=()=>{},s.onerror=()=>{ru.Y.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){ru.Y.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,r,s){let n=mW._ReturnFullUrlLocation(e),a=()=>{this._saveFileAsync(n,t,i,s,r)};this._checkVersionFromDB(n,e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,s,r):this._loadFileAsync(n,t,a):r&&r()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let r,s;r=-1!==e.indexOf(".babylon")?"scenes":"textures";let n=this._db.transaction([r]);n.oncomplete=()=>{s?t(s.data):i()},n.onabort=()=>{i()};let a=n.objectStore(r).get(e);a.onsuccess=e=>{s=e.target.result},a.onerror=()=>{ru.Y.Error("Error loading file "+e+" from DB."),i()}}else ru.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,s){if(this._isSupported){let n,a;n=-1!==e.indexOf(".babylon")?"scenes":"textures";let o=new rS.g;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(200===o.status||o.status<400&&mW._ValidateXHRData(o,r?6:1)){if(a=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){let i;let r=this._db.transaction([n],"readwrite");r.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},r.oncomplete=()=>{t(a)},i="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{let e=r.objectStore(n).put(i);e.onsuccess=()=>{},e.onerror=()=>{ru.Y.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a)}else o.status>=400&&s?s(o):t()},!1),o.addEventListener("error",()=>{ru.Y.Error("error on XHR request."),s&&s()},!1),o.send()}else ru.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){let i=fe(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){let t=new Uint8Array(e.response,0,3);if(68===t[0]&&68===t[1]&&83===t[2])return!0}}catch(e){}return!1}}mW._IsUASupportingBlobStorage=!0,mW.IDBStorageEnabled=!1,mW._ParseURL=e=>{let t=document.createElement("a");t.href=e;let i=e.substring(0,e.lastIndexOf("#")),r=e.substring(i.lastIndexOf("/")+1,e.length),s=e.substring(0,e.indexOf(r,0));return s},mW._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?mW._ParseURL(window.location.href)+e:e;class mH{_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))}}let mX=`#version 300 es -void main() {discard;} -`;no.v.ShadersStore.gpuUpdateParticlesPixelShader=mX;let mY=`#version 300 es -#define PI 3.14159 -uniform float currentCount;uniform float timeDelta;uniform float stopFactor; -#ifndef LOCAL -uniform mat4 emitterWM; -#endif -uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; -#ifndef COLORGRADIENTS -uniform vec4 color1;uniform vec4 color2; -#endif -uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; -#ifdef BOXEMITTER -uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; -#endif -#ifdef POINTEMITTER -uniform vec3 direction1;uniform vec3 direction2; -#endif -#ifdef HEMISPHERICEMITTER -uniform float radius;uniform float radiusRange;uniform float directionRandomizer; -#endif -#ifdef SPHEREEMITTER -uniform float radius;uniform float radiusRange; -#ifdef DIRECTEDSPHEREEMITTER -uniform vec3 direction1;uniform vec3 direction2; -#else -uniform float directionRandomizer; -#endif -#endif -#ifdef CYLINDEREMITTER -uniform float radius;uniform float height;uniform float radiusRange; -#ifdef DIRECTEDCYLINDEREMITTER -uniform vec3 direction1;uniform vec3 direction2; -#else -uniform float directionRandomizer; -#endif -#endif -#ifdef CONEEMITTER -uniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer; -#endif -in vec3 position; -#ifdef CUSTOMEMITTER -in vec3 initialPosition; -#endif -in float age;in float life;in vec4 seed;in vec3 size; -#ifndef COLORGRADIENTS -in vec4 color; -#endif -in vec3 direction; -#ifndef BILLBOARD -in vec3 initialDirection; -#endif -#ifdef ANGULARSPEEDGRADIENTS -in float angle; -#else -in vec2 angle; -#endif -#ifdef ANIMATESHEET -in float cellIndex; -#ifdef ANIMATESHEETRANDOMSTART -in float cellStartOffset; -#endif -#endif -#ifdef NOISE -in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; -#endif -out vec3 outPosition; -#ifdef CUSTOMEMITTER -out vec3 outInitialPosition; -#endif -out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; -#ifndef COLORGRADIENTS -out vec4 outColor; -#endif -out vec3 outDirection; -#ifndef BILLBOARD -out vec3 outInitialDirection; -#endif -#ifdef ANGULARSPEEDGRADIENTS -out float outAngle; -#else -out vec2 outAngle; -#endif -#ifdef ANIMATESHEET -out float outCellIndex; -#ifdef ANIMATESHEETRANDOMSTART -out float outCellStartOffset; -#endif -#endif -#ifdef NOISE -out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; -#endif -#ifdef SIZEGRADIENTS -uniform sampler2D sizeGradientSampler; -#endif -#ifdef ANGULARSPEEDGRADIENTS -uniform sampler2D angularSpeedGradientSampler; -#endif -#ifdef VELOCITYGRADIENTS -uniform sampler2D velocityGradientSampler; -#endif -#ifdef LIMITVELOCITYGRADIENTS -uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; -#endif -#ifdef DRAGGRADIENTS -uniform sampler2D dragGradientSampler; -#endif -#ifdef NOISE -uniform vec3 noiseStrength;uniform sampler2D noiseSampler; -#endif -#ifdef ANIMATESHEET -uniform vec4 cellInfos; -#endif -vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} -vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} -void main() {float newAge=age+timeDelta; -if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; -#ifdef SIZEGRADIENTS -outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; -#else -outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; -#endif -outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; -#ifndef COLORGRADIENTS -outColor=color1+(color2-color1)*randoms.b; -#endif -#ifndef ANGULARSPEEDGRADIENTS -outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; -#else -outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; -#endif -#ifdef POINTEMITTER -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; -#elif defined(BOXEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; -#elif defined(HEMISPHERICEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; -#elif defined(SPHEREEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); -#ifdef DIRECTEDSPHEREEMITTER -newDirection=normalize(direction1+(direction2-direction1)*randoms3); -#else -newDirection=normalize(newPosition+directionRandomizer*randoms3); -#endif -#elif defined(CYLINDEREMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); -#ifdef DIRECTEDCYLINDEREMITTER -newDirection=direction1+(direction2-direction1)*randoms3; -#else -angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); -#endif -#elif defined(CONEEMITTER) -vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; -#ifdef CONEEMITTERSPAWNPOINT -float h=0.0001; -#else -float h=randoms2.y*height.y;h=1.-h*h; -#endif -float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); -if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); } -#elif defined(CUSTOMEMITTER) -newPosition=initialPosition;outInitialPosition=initialPosition; -#else -newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); -#endif -float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; -#ifdef LOCAL -outPosition=newPosition; -#else -outPosition=(emitterWM*vec4(newPosition,1.)).xyz; -#endif -#ifdef CUSTOMEMITTER -outDirection=direction; -#ifndef BILLBOARD -outInitialDirection=direction; -#endif -#else -#ifdef LOCAL -vec3 initial=newDirection; -#else -vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; -#endif -outDirection=initial*power; -#ifndef BILLBOARD -outInitialDirection=initial; -#endif -#endif -#ifdef ANIMATESHEET -outCellIndex=cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -outCellStartOffset=randoms.a*outLife; -#endif -#endif -#ifdef NOISE -outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; -#endif -} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; -#ifdef VELOCITYGRADIENTS -directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; -#endif -#ifdef DRAGGRADIENTS -directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; -#endif -#if defined(CUSTOMEMITTER) -outPosition=position+(direction-position)*ageGradient; -outInitialPosition=initialPosition; -#else -outPosition=position+direction*directionScale; -#endif -outLife=life;outSeed=seed; -#ifndef COLORGRADIENTS -outColor=color; -#endif -#ifdef SIZEGRADIENTS -outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; -#else -outSize=size; -#endif -#ifndef BILLBOARD -outInitialDirection=initialDirection; -#endif -#ifdef CUSTOMEMITTER -outDirection=direction; -#else -vec3 updatedDirection=direction+gravity*timeDelta; -#ifdef LIMITVELOCITYGRADIENTS -float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} -#endif -outDirection=updatedDirection; -#ifdef NOISE -float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; -#endif -#endif -#ifdef ANGULARSPEEDGRADIENTS -float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; -#else -outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); -#endif -#ifdef ANIMATESHEET -float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; -#else -float cellStartOffset=0.; -#endif -float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} -else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} -outCellIndex=float(int(cellInfos.x+ratio*dist)); -#endif -}}`;no.v.ShadersStore.gpuUpdateParticlesVertexShader=mY,(0,rn.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:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}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 nA&&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 sj.Q("gpuUpdateParticles",this._updateEffectOptions,this._engine),new mH(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){let e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw 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);let r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e<this._updateVAO.length;e++)this._engine.releaseVertexArrayObject(this._updateVAO[e]);this._updateVAO.length=0;for(let e=0;e<this._renderVAO.length;e++)this._engine.releaseVertexArrayObject(this._renderVAO[e]);this._renderVAO.length=0}_createUpdateVAO(e){let t={};t.position=e.createVertexBuffer("position",0,3);let i=3;t.age=e.createVertexBuffer("age",i,1),i+=1,t.size=e.createVertexBuffer("size",i,3),i+=3,t.life=e.createVertexBuffer("life",i,1),i+=1,t.seed=e.createVertexBuffer("seed",i,4),i+=4,t.direction=e.createVertexBuffer("direction",i,3),i+=3,this._parent.particleEmitterType instanceof nA&&(t.initialPosition=e.createVertexBuffer("initialPosition",i,3),i+=3),this._parent._colorGradientsTexture||(t.color=e.createVertexBuffer("color",i,4),i+=4),this._parent._isBillboardBased||(t.initialDirection=e.createVertexBuffer("initialDirection",i,3),i+=3),this._parent.noiseTexture&&(t.noiseCoordinates1=e.createVertexBuffer("noiseCoordinates1",i,3),i+=3,t.noiseCoordinates2=e.createVertexBuffer("noiseCoordinates2",i,3),i+=3),this._parent._angularSpeedGradientsTexture?(t.angle=e.createVertexBuffer("angle",i,1),i+=1):(t.angle=e.createVertexBuffer("angle",i,2),i+=2),this._parent._isAnimationSheetEnabled&&(t.cellIndex=e.createVertexBuffer("cellIndex",i,1),i+=1,this._parent.spriteRandomStartCell&&(t.cellStartOffset=e.createVertexBuffer("cellStartOffset",i,1),i+=1));let r=this._engine.recordVertexArrayObject(t,null,this._updateEffect);return this._engine.bindArrayBuffer(null),r}});let mj=`struct Particle {position : vec3<f32>, -age : f32, -size : vec3<f32>, -life : f32, -seed : vec4<f32>, -direction : vec3<f32>, -dummy0: f32, -#ifdef CUSTOMEMITTER -initialPosition : vec3<f32>, -dummy1: f32, -#endif -#ifndef COLORGRADIENTS -color : vec4<f32>, -#endif -#ifndef BILLBOARD -initialDirection : vec3<f32>, -dummy2: f32, -#endif -#ifdef NOISE -noiseCoordinates1 : vec3<f32>, -dummy3: f32, -noiseCoordinates2 : vec3<f32>, -dummy4: f32, -#endif -#ifdef ANGULARSPEEDGRADIENTS -angle : f32, -#else -angle : vec2<f32>, -#endif -#ifdef ANIMATESHEET -cellIndex : f32, -#ifdef ANIMATESHEETRANDOMSTART -cellStartOffset : f32, -#endif -#endif -};struct Particles {particles : array<Particle>,};struct SimParams {currentCount : f32, -timeDelta : f32, -stopFactor : f32, -randomTextureSize: i32, -lifeTime : vec2<f32>, -emitPower : vec2<f32>, -#ifndef COLORGRADIENTS -color1 : vec4<f32>, -color2 : vec4<f32>, -#endif -sizeRange : vec2<f32>, -scaleRange : vec4<f32>, -angleRange : vec4<f32>, -gravity : vec3<f32>, -#ifdef LIMITVELOCITYGRADIENTS -limitVelocityDamping : f32, -#endif -#ifdef ANIMATESHEET -cellInfos : vec4<f32>, -#endif -#ifdef NOISE -noiseStrength : vec3<f32>, -#endif -#ifndef LOCAL -emitterWM : mat4x4<f32>, -#endif -#ifdef BOXEMITTER -direction1 : vec3<f32>, -direction2 : vec3<f32>, -minEmitBox : vec3<f32>, -maxEmitBox : vec3<f32>, -#endif -#ifdef CONEEMITTER -radius : vec2<f32>, -coneAngle : f32, -height : vec2<f32>, -directionRandomizer : f32, -#endif -#ifdef CYLINDEREMITTER -radius : f32, -height : f32, -radiusRange : f32, -#ifdef DIRECTEDCYLINDEREMITTER -direction1 : vec3<f32>, -direction2 : vec3<f32>, -#else -directionRandomizer : f32, -#endif -#endif -#ifdef HEMISPHERICEMITTER -radius : f32, -radiusRange : f32, -directionRandomizer : f32, -#endif -#ifdef POINTEMITTER -direction1 : vec3<f32>, -direction2 : vec3<f32>, -#endif -#ifdef SPHEREEMITTER -radius : f32, -radiusRange : f32, -#ifdef DIRECTEDSPHEREEMITTER -direction1 : vec3<f32>, -direction2 : vec3<f32>, -#else -directionRandomizer : f32, -#endif -#endif -};@binding(0) @group(0) var<uniform> params : SimParams;@binding(1) @group(0) var<storage,read> particlesIn : Particles;@binding(2) @group(0) var<storage,read_write> particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d<f32>;@binding(4) @group(0) var randomTexture2 : texture_2d<f32>; -#ifdef SIZEGRADIENTS -@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d<f32>; -#endif -#ifdef ANGULARSPEEDGRADIENTS -@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d<f32>; -#endif -#ifdef VELOCITYGRADIENTS -@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d<f32>; -#endif -#ifdef LIMITVELOCITYGRADIENTS -@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d<f32>; -#endif -#ifdef DRAGGRADIENTS -@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d<f32>; -#endif -#ifdef NOISE -@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d<f32>; -#endif -fn getRandomVec3(offset : f32,vertexID : f32)->vec3<f32> {return textureLoad(randomTexture2,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} -fn getRandomVec4(offset : f32,vertexID : f32)->vec4<f32> {return textureLoad(randomTexture,vec2<i32>(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} -@compute @workgroup_size(64) -fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3<u32>) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} -let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4<f32>=particlesIn.particles[index].seed;let direction : vec3<f32>=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3<f32>;var newDirection : vec3<f32>;let randoms : vec4<f32>=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; -#ifdef SIZEGRADIENTS -sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(0.,0.),0.).r; -#else -sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; -#endif -particlesOut.particles[index].size=vec3<f32>( -sizex, -params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, -params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); -#ifndef COLORGRADIENTS -particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; -#endif -#ifndef ANGULARSPEEDGRADIENTS -particlesOut.particles[index].angle=vec2<f32>( -params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, -params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); -#else -particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; -#endif -#if defined(POINTEMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=vec3<f32>(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#elif defined(BOXEMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#elif defined(HEMISPHERICEMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); -#elif defined(SPHEREEMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3<f32>(randX,randY,randZ); -#ifdef DIRECTEDSPHEREEMITTER -newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); -#else -newDirection=normalize(newPosition+params.directionRandomizer*randoms3); -#endif -#elif defined(CYLINDEREMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3<f32>(xPos,yPos,zPos); -#ifdef DIRECTEDCYLINDEREMITTER -newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#else -angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3<f32>(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); -#endif -#elif defined(CONEEMITTER) -let randoms2 : vec3<f32>=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; -#ifdef CONEEMITTERSPAWNPOINT -let h : f32=0.0001; -#else -var h : f32=randoms2.y*params.height.y;h=1.-h*h; -#endif -var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3<f32>(randX,randY,randZ); -if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3<f32>(0.,1.0,0.);} else {let randoms3 : vec3<f32>=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } -#elif defined(CUSTOMEMITTER) -newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; -#else -newPosition=vec3<f32>(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3<f32>(0.5,0.5,0.5)); -#endif -let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; -#ifdef LOCAL -particlesOut.particles[index].position=newPosition; -#else -particlesOut.particles[index].position=(params.emitterWM*vec4<f32>(newPosition,1.)).xyz; -#endif -#ifdef CUSTOMEMITTER -particlesOut.particles[index].direction=direction; -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=direction; -#endif -#else -#ifdef LOCAL -let initial : vec3<f32>=newDirection; -#else -let initial : vec3<f32>=(params.emitterWM*vec4<f32>(newDirection,0.)).xyz; -#endif -particlesOut.particles[index].direction=initial*power; -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=initial; -#endif -#endif -#ifdef ANIMATESHEET -particlesOut.particles[index].cellIndex=params.cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -particlesOut.particles[index].cellStartOffset=randoms.a*outLife; -#endif -#endif -#ifdef NOISE -particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; -#endif -} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; -#ifdef VELOCITYGRADIENTS -directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r; -#endif -#ifdef DRAGGRADIENTS -directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2<f32>(ageGradient,0.),0.).r); -#endif -let position : vec3<f32>=particlesIn.particles[index].position; -#if defined(CUSTOMEMITTER) -particlesOut.particles[index].position=position+(direction-position)*ageGradient; -particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; -#else -particlesOut.particles[index].position=position+direction*directionScale; -#endif -particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; -#ifndef COLORGRADIENTS -particlesOut.particles[index].color=particlesIn.particles[index].color; -#endif -#ifdef SIZEGRADIENTS -particlesOut.particles[index].size=vec3<f32>( -textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2<f32>(ageGradient,0.),0.).r, -particlesIn.particles[index].size.yz); -#else -particlesOut.particles[index].size=particlesIn.particles[index].size; -#endif -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; -#endif -#ifdef CUSTOMEMITTER -particlesOut.particles[index].direction=direction; -#else -var updatedDirection : vec3<f32>=direction+params.gravity*timeDelta; -#ifdef LIMITVELOCITYGRADIENTS -let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2<f32>(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} -#endif -particlesOut.particles[index].direction=updatedDirection; -#ifdef NOISE -let noiseCoordinates1 : vec3<f32>=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3<f32>=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.x,noiseCoordinates1.y)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates1.z,noiseCoordinates2.x)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2<f32>(noiseCoordinates2.y,noiseCoordinates2.z)*vec2<f32>(0.5,0.5)+vec2<f32>(0.5,0.5),0.).r;let force : vec3<f32>=vec3<f32>(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; -#endif -#endif -#ifdef ANGULARSPEEDGRADIENTS -let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2<f32>(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; -#else -let angle : vec2<f32>=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2<f32>(angle.x+angle.y*timeDelta,angle.y); -#endif -#ifdef ANIMATESHEET -var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; -#else -let cellStartOffset : f32=0.; -#endif -var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} -else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} -particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); -#endif -}} -`;no.v.ShadersStoreWGSL.gpuUpdateParticlesComputeShader=mj,(0,rn.H)("BABYLON.ComputeShaderParticleSystem",class{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}contextLost(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateComputeShader)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){var t;let i={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new l3("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split("\n")}),null===(t=this._simParamsComputeShader)||void 0===t||t.dispose(),this._simParamsComputeShader=new r1.M(this._engine),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new mH(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){let t=new n3(this._engine,4*e.length,11);return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)}preUpdateParticleBuffer(){}updateParticleBuffer(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[1^e]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let e=0;e<this._bufferComputeShader.length;++e)this._bufferComputeShader[e].dispose();this._bufferComputeShader.length=0,null===(e=this._simParamsComputeShader)||void 0===e||e.dispose(),this._simParamsComputeShader=null,this._updateComputeShader=null}releaseVertexBuffers(){this._renderVertexBuffers.length=0}});class mq{constructor(e,t,i){this.gradient=e,this.color1=t,this.color2=i}getColorToRef(e){if(!this.color2){e.copyFrom(this.color1);return}rs.HE.LerpToRef(this.color1,this.color2,Math.random(),e)}}class mK{constructor(e,t){this.gradient=e,this.color=t}}class m${constructor(e,t,i){this.gradient=e,this.factor1=t,this.factor2=i}getFactor(){return void 0===this.factor2||this.factor2===this.factor1?this.factor1:this.factor1+(this.factor2-this.factor1)*Math.random()}}class mQ{static GetCurrentGradient(e,t,i){if(t[0].gradient>e){i(t[0],t[0],1);return}for(let r=0;r<t.length-1;r++){let s=t[r],n=t[r+1];if(e>=s.gradient&&e<=n.gradient){let t=(e-s.gradient)/(n.gradient-s.gradient);i(s,n,t);return}}let r=t.length-1;i(t[r],t[r],1)}}class mZ{constructor(e){if(this.particleSystem=e,this.position=rr.P.Zero(),this.direction=rr.P.Zero(),this.color=new rs.HE(0,0,0,0),this.colorStep=new rs.HE(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new rr.FM(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new rs.HE(0,0,0,0),this._currentColor2=new rs.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=mZ._Count++,!this.particleSystem.isAnimationSheetEnabled)return;this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e,t=this.age,i=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===i?(i=1,t=this._randomCellOffset):t+=this._randomCellOffset);let r=this._initialEndSpriteCellID-this._initialStartSpriteCellID;e=this._initialSpriteCellLoop?rm.R.Clamp(t*i%this.lifeTime/this.lifeTime):rm.R.Clamp(t*i/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+e*r|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){let t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){let e=rr.jp.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else{let t=e.particleSystem.emitter;t.copyFrom(this.position)}this.direction.scaleToRef(e.inheritedVelocityAmount/2,rr.jp.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(rr.jp.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=mZ._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 rr.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()))}}mZ._Count=0,(eK=iW||(iW={}))[eK.ATTACHED=0]="ATTACHED",eK[eK.END=1]="END";class mJ{constructor(e){if(this.particleSystem=e,this.type=iW.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){let t=(0,rn.q)("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(e){if(e instanceof rr.P)e=e.clone();else if(-1!==e.getClassName().indexOf("Mesh")){let t=(0,rn.q)("BABYLON.Mesh");(e=new t("",e.getScene())).isVisible=!1}}else e=new rr.P;let t=new mJ(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){let t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw(0,st.S)("ParseParticle")}static Parse(e,t,i){let r=e.particleSystem,s=new mJ(mJ._ParseParticleSystem(r,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}let m0=`#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; -#include<clipPlaneFragmentDeclaration> -#include<imageProcessingDeclaration> -#include<logDepthDeclaration> -#include<helperFunctions> -#include<imageProcessingFunctions> -#ifdef RAMPGRADIENT -varying vec4 remapRanges;uniform sampler2D rampSampler; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; -#ifdef RAMPGRADIENT -float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); -#endif -#ifdef BLENDMULTIPLYMODE -float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); -#endif -#include<logDepthFragment> -#ifdef IMAGEPROCESSINGPOSTPROCESS -baseColor.rgb=toLinearSpace(baseColor.rgb); -#else -#ifdef IMAGEPROCESSING -baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); -#endif -#endif -gl_FragColor=baseColor; -#define CUSTOM_FRAGMENT_MAIN_END -}`;no.v.ShadersStore.particlesPixelShader=m0;let m1=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; -#ifdef ANIMATESHEET -attribute float cellIndex; -#endif -#ifndef BILLBOARD -attribute vec3 direction; -#endif -#ifdef BILLBOARDSTRETCHED -attribute vec3 direction; -#endif -#ifdef RAMPGRADIENT -attribute vec4 remapData; -#endif -attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; -#ifdef ANIMATESHEET -uniform vec3 particlesInfos; -#endif -varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; -#ifdef RAMPGRADIENT -varying vec4 remapRanges; -#endif -#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) -uniform mat4 invView; -#endif -#include<clipPlaneVertexDeclaration> -#include<logDepthDeclaration> -#ifdef BILLBOARD -uniform vec3 eyePosition; -#endif -vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} -#ifdef BILLBOARDSTRETCHED -vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); -#ifdef BILLBOARDSTRETCHED_LOCAL -vec3 row1=direction; -#else -vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); -#endif -mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; -#ifdef BILLBOARD -vec3 rotatedCorner; -#ifdef BILLBOARDY -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; -#elif defined(BILLBOARDSTRETCHED) -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; -#else -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; -#endif -#ifdef RAMPGRADIENT -remapRanges=remapData; -#endif -gl_Position=projection*vec4(viewPos,1.0); -#else -vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); -#endif -vColor=color; -#ifdef ANIMATESHEET -float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; -#else -vUV=offset; -#endif -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=vec4(vPositionW,1.0); -#endif -#include<clipPlaneVertex> -#include<logDepthVertex> -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.particlesVertexShader=m1;class m2 extends nP{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 nc.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 ri.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,s=!1,n=.01){super(e),this._emitterInverseWorldMatrix=rr.y3.Identity(),this._inheritedVelocityOffset=new rr.P,this.onDisposeObservable=new ri.y$,this.onStoppedObservable=new ri.y$,this._particles=[],this._stockParticles=[],this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new rs.HE(0,0,0,0),this._colorDiff=new rs.HE(0,0,0,0),this._scaledDirection=rr.P.Zero(),this._scaledGravity=rr.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=>{let 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())._reset():e=new mZ(this),this._subEmitters&&this._subEmitters.length>0){let t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(t=>{if(t.type===iW.ATTACHED){let i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}})}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;let t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach(t=>{if(t.type===iW.END){let i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}})},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=rr.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||rp.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 nc.q(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new nv;let a=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=>{a=e}));let r=e===this._particles;for(let t=0;t<e.length;t++){let s=e[t],n=this._scaledUpdateSpeed,o=s.age;if(s.age+=n,s.age>s.lifeTime){let e=s.age-o,t=s.lifeTime-o;n=t*n/e,s.age=s.lifeTime}let l=s.age/s.lifeTime;this._colorGradients&&this._colorGradients.length>0?mQ.GetCurrentGradient(l,this._colorGradients,(e,t,i)=>{e!==s._currentColorGradient&&(s._currentColor1.copyFrom(s._currentColor2),t.getColorToRef(s._currentColor2),s._currentColorGradient=e),rs.HE.LerpToRef(s._currentColor1,s._currentColor2,i,s.color)}):(s.colorStep.scaleToRef(n,this._scaledColorStep),s.color.addInPlace(this._scaledColorStep),s.color.a<0&&(s.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&mQ.GetCurrentGradient(l,this._angularSpeedGradients,(e,t,i)=>{e!==s._currentAngularSpeedGradient&&(s._currentAngularSpeed1=s._currentAngularSpeed2,s._currentAngularSpeed2=t.getFactor(),s._currentAngularSpeedGradient=e),s.angularSpeed=rm.R.Lerp(s._currentAngularSpeed1,s._currentAngularSpeed2,i)}),s.angle+=s.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&mQ.GetCurrentGradient(l,this._velocityGradients,(e,t,i)=>{e!==s._currentVelocityGradient&&(s._currentVelocity1=s._currentVelocity2,s._currentVelocity2=t.getFactor(),s._currentVelocityGradient=e),h*=rm.R.Lerp(s._currentVelocity1,s._currentVelocity2,i)}),s.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&mQ.GetCurrentGradient(l,this._limitVelocityGradients,(e,t,i)=>{e!==s._currentLimitVelocityGradient&&(s._currentLimitVelocity1=s._currentLimitVelocity2,s._currentLimitVelocity2=t.getFactor(),s._currentLimitVelocityGradient=e);let r=rm.R.Lerp(s._currentLimitVelocity1,s._currentLimitVelocity2,i),n=s.direction.length();n>r&&s.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&mQ.GetCurrentGradient(l,this._dragGradients,(e,t,i)=>{e!==s._currentDragGradient&&(s._currentDrag1=s._currentDrag2,s._currentDrag2=t.getFactor(),s._currentDragGradient=e);let r=rm.R.Lerp(s._currentDrag1,s._currentDrag2,i);this._scaledDirection.scaleInPlace(1-r)}),this.isLocal&&s._localPosition?(s._localPosition.addInPlace(this._scaledDirection),rr.P.TransformCoordinatesToRef(s._localPosition,this._emitterWorldMatrix,s.position)):s.position.addInPlace(this._scaledDirection),a&&i&&s._randomNoiseCoordinates1){let e=this._fetchR(s._randomNoiseCoordinates1.x,s._randomNoiseCoordinates1.y,i.width,i.height,a),t=this._fetchR(s._randomNoiseCoordinates1.z,s._randomNoiseCoordinates2.x,i.width,i.height,a),r=this._fetchR(s._randomNoiseCoordinates2.y,s._randomNoiseCoordinates2.z,i.width,i.height,a),o=rr.jp.Vector3[0],l=rr.jp.Vector3[1];o.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*t-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),o.scaleToRef(n,l),s.direction.addInPlace(l)}if(this.gravity.scaleToRef(n,this._scaledGravity),s.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&mQ.GetCurrentGradient(l,this._sizeGradients,(e,t,i)=>{e!==s._currentSizeGradient&&(s._currentSize1=s._currentSize2,s._currentSize2=t.getFactor(),s._currentSizeGradient=e),s.size=rm.R.Lerp(s._currentSize1,s._currentSize2,i)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&mQ.GetCurrentGradient(l,this._colorRemapGradients,(e,t,i)=>{let r=rm.R.Lerp(e.factor1,t.factor1,i),n=rm.R.Lerp(e.factor2,t.factor2,i);s.remapData.x=r,s.remapData.y=n-r}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&mQ.GetCurrentGradient(l,this._alphaRemapGradients,(e,t,i)=>{let r=rm.R.Lerp(e.factor1,t.factor1,i),n=rm.R.Lerp(e.factor2,t.factor2,i);s.remapData.z=r,s.remapData.w=n-r})),this._isAnimationSheetEnabled&&s.updateCellIndex(),s._inheritParticleInfoToSubEmitters(),s.age>=s.lifeTime){this._emitFromParticle(s),s._attachedSubEmitters&&(s._attachedSubEmitters.forEach(e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()}),s._attachedSubEmitters=null),this.recycleParticle(s),r&&t--;continue}}}}_addFactorGradient(e,t,i,r){let s=new m$(t,i,r);e.push(s),e.sort((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(let r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;let e=new Uint8Array(4*this._rawTextureWidth),t=rs.zZ.Color3[0];for(let i=0;i<this._rawTextureWidth;i++){let r=i/this._rawTextureWidth;mQ.GetCurrentGradient(r,this._rampGradients,(r,s,n)=>{rs.Wo.LerpToRef(r.color,s.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255})}this._rampGradientsTexture=sb.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.gradient<t.gradient?-1:e.gradient>t.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);let i=new mK(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=[]);let r=new mq(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(let i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(let e of this._drawWrappers)if(e)for(let t of e)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,s){e=.5*Math.abs(e)+.5,t=.5*Math.abs(t)+.5;let n=e*i%i|0,a=t*r%r|0;return s[(n+a*i)*4]/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(){let e;this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==m2.BILLBOARDMODE_STRETCHED&&this.billboardMode!==m2.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);let t=this._engine,i=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*i),this._vertexBuffer=new rQ.l(t,this._vertexData,!0,i);let r=0,s=this._vertexBuffer.createVertexBuffer(rQ.o.PositionKind,r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[rQ.o.PositionKind]=s,r+=3;let n=this._vertexBuffer.createVertexBuffer(rQ.o.ColorKind,r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[rQ.o.ColorKind]=n,r+=4;let a=this._vertexBuffer.createVertexBuffer("angle",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=a,r+=1;let o=this._vertexBuffer.createVertexBuffer("size",r,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,r+=2,this._isAnimationSheetEnabled){let e=this._vertexBuffer.createVertexBuffer("cellIndex",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,r+=1}if(!this._isBillboardBased||this.billboardMode===m2.BILLBOARDMODE_STRETCHED||this.billboardMode===m2.BILLBOARDMODE_STRETCHED_LOCAL){let e=this._vertexBuffer.createVertexBuffer("direction",r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,r+=3}if(this._useRampGradients){let e=this._vertexBuffer.createVertexBuffer("remapData",r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,r+=4}if(this._useInstancing){let i=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new rQ.l(t,i,!1,2),e=this._spriteBuffer.createVertexBuffer("offset",0,2)}else e=this._vertexBuffer.createVertexBuffer("offset",r,2,this._vertexBufferSize,this._useInstancing),r+=2;this._vertexBuffers.offset=e,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));return}let e=[],t=[],i=0;for(let r=0;r<this._capacity;r++)e.push(i),e.push(i+1),e.push(i+2),e.push(i),e.push(i+2),e.push(i+3),t.push(i,i+1,i+1,i+2,i+2,i+3,i+3,i,i,i+3),i+=4;this._indexBuffer=this._engine.createIndexBuffer(e),this._linesIndexBuffer=this._engine.createIndexBuffer(t)}getCapacity(){return this._capacity}isAlive(){return this._alive}isStarted(){return this._started}_prepareSubEmitterInternalArray(){this._subEmitters=[],this.subEmitters&&this.subEmitters.forEach(e=>{e instanceof m2?this._subEmitters.push([new mJ(e)]):e instanceof mJ?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);return}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[]),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){(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);let e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce(()=>{setTimeout(()=>{for(let t=0;t<this.preWarmCycles;t++)this.animate(!0),e.render()})});else for(let e=0;e<this.preWarmCycles;e++)this.animate(!0)}this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&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,r){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===m2.BILLBOARDMODE_STRETCHED||this.billboardMode===m2.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&&(rr.P.TransformNormalToRef(e,this._emitterWorldMatrix,rr.jp.Vector3[0]),e=rr.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&&(rr.P.TransformNormalToRef(e,this._emitterWorldMatrix,rr.jp.Vector3[0]),e=rr.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===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=r)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;let e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){let t;if(this._alive=this._particles.length>0,this.emitter.position){let e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{let e=this.emitter;this._emitterWorldMatrix=rr.y3.Translation(e.x,e.y,e.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i<e&&this._particles.length!==this._capacity;i++){if(t=this._createParticle(),this._particles.push(t),this.targetStopDuration&&this._lifeTimeGradients&&this._lifeTimeGradients.length>0){let e=rm.R.Clamp(this._actualFrame/this.targetStopDuration);mQ.GetCurrentGradient(e,this._lifeTimeGradients,(i,r)=>{let s=i.getFactor(),n=r.getFactor(),a=(e-i.gradient)/(r.gradient-i.gradient);t.lifeTime=rm.R.Lerp(s,n,a)})}else t.lifeTime=rm.R.RandomRange(this.minLifeTime,this.maxLifeTime);let e=rm.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(),rr.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=rm.R.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(rm.R.RandomRange(this.minScaleX,this.maxScaleX),rm.R.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){let e=this._actualFrame/this.targetStopDuration;mQ.GetCurrentGradient(e,this._startSizeGradients,(e,i,r)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);let s=rm.R.Lerp(this._currentStartSize1,this._currentStartSize2,r);t.scale.scaleInPlace(s)})}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=rm.R.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=rm.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{let e=rm.R.RandomRange(0,1);rs.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 rr.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 rr.P(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new rr.P(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){let r=[rQ.o.PositionKind,rQ.o.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1){let i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return(0,lx.qx)(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&(0,lx.lK)(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===m2.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case m2.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case m2.BILLBOARDMODE_STRETCHED:case m2.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===m2.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case m2.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(...m2._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==m2.BILLBOARDMODE_STRETCHED&&this.billboardMode!==m2.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...m2._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(ng.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ng.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0,s=this._drawWrappers[r];s||(s=this._drawWrappers[r]=[]);let n=s[e];n||((n=new nc.q(this._engine)).drawContext&&(n.drawContext.useInstancing=this._useInstancing),s[e]=n);let a=i.join("\n");if(n.defines!==a){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,a),a)}return n}animate(e=!1){var t;let i;if(this._started){if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}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){let t=this._actualFrame/this.targetStopDuration;mQ.GetCurrentGradient(t,this._emitRateGradients,(t,i,r)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=rm.R.Lerp(this._currentEmitRate1,this._currentEmitRate2,r)})}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<this._particles.length;t++){let i=this._particles[t];this._appendParticleVertices(e,i),e+=this._useInstancing?1:4}this._vertexBuffer&&this._vertexBuffer.updateDirectly(this._vertexData,0,this._particles.length)}0===this.manualEmitCount&&this.disposeOnStop&&this.stop()}}_appendParticleVertices(e,t){this._appendParticleVertex(e++,t,0,0),this._useInstancing||(this._appendParticleVertex(e++,t,1,0),this._appendParticleVertex(e++,t,1,1),this._appendParticleVertex(e++,t,0,1))}rebuild(){var e,t;for(let i in this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._createIndexBuffer(),null===(e=this._spriteBuffer)||void 0===e||e._rebuild(),null===(t=this._vertexBuffer)||void 0===t||t._rebuild(),this._vertexBuffers)this._vertexBuffers[i]._rebuild();this.resetDrawCache()}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==m2.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(m2.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(m2.BLENDMODE_ADD).effect.isReady())return!1;return!0}_render(e){var t,i,r,s,n,a,o,l;let h=this._getWrapper(e),u=h.effect,c=this._engine;c.enableEffect(h);let d=null!==(t=this.defaultViewMatrix)&&void 0!==t?t:this._scene.getViewMatrix();if(u.setTexture("diffuseSampler",this.particleTexture),u.setMatrix("view",d),u.setMatrix("projection",null!==(i=this.defaultProjectionMatrix)&&void 0!==i?i:this._scene.getProjectionMatrix()),this._isAnimationSheetEnabled&&this.particleTexture){let e=this.particleTexture.getBaseSize();u.setFloat3("particlesInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,this.spriteCellWidth/e.width)}if(u.setVector2("translationPivot",this.translationPivot),u.setFloat4("textureMask",this.textureMask.r,this.textureMask.g,this.textureMask.b,this.textureMask.a),this._isBillboardBased&&this._scene){let e=this._scene.activeCamera;u.setVector3("eyePosition",e.globalPosition)}this._rampGradientsTexture&&(this._rampGradients&&this._rampGradients.length||(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),u.setTexture("rampSampler",this._rampGradientsTexture));let p=u.defines;switch(this._scene&&(0,lx.an)(u,this,this._scene),p.indexOf("#define BILLBOARDMODE_ALL")>=0&&(d.invertToRef(rr.jp.Matrix[0]),u.setMatrix("invView",rr.jp.Matrix[0])),void 0!==this._vertexArrayObject?(null===(r=this._scene)||void 0===r?void 0:r.forceWireframe)?c.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,u):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,u)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?c.bindBuffers(this._vertexBuffers,(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)?this._linesIndexBuffer:this._indexBuffer,u):c.bindBuffers(this._vertexBuffers,(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._linesIndexBufferUseInstancing:null,u),this.useLogarithmicDepth&&this._scene&&s3.G.BindLogDepth(p,u,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(u),e){case m2.BLENDMODE_ADD:c.setAlphaMode(1);break;case m2.BLENDMODE_ONEONE:c.setAlphaMode(6);break;case m2.BLENDMODE_STANDARD:c.setAlphaMode(2);break;case m2.BLENDMODE_MULTIPLY:c.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(u),this._useInstancing?(null===(o=this._scene)||void 0===o?void 0:o.forceWireframe)?c.drawElementsType(6,0,10,this._particles.length):c.drawArraysType(7,0,4,this._particles.length):(null===(l=this._scene)||void 0===l?void 0:l.forceWireframe)?c.drawElementsType(1,0,10*this._particles.length):c.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;let e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===m2.BLENDMODE_MULTIPLYADD?this._render(m2.BLENDMODE_MULTIPLY)+this._render(m2.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._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let e=0;e<this._subEmitters.length;e++)for(let t of this._subEmitters[e])t.dispose();this._subEmitters=[],this.subEmitters=[]}if(this._disposeEmitterOnDispose&&this.emitter&&this.emitter.dispose&&this.emitter.dispose(!0),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){let e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){let r=Object.assign({},this._customWrappers),s=null,n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){s=this.customShader;let e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);r[0]?r[0].effect=t:this.setCustomEffect(t,0)}let a=this.serialize(i),o=m2.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,this.preventAutoStart||o.start(),o}serialize(e=!1){let t={};if(m2._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters)for(let i of(t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray(),this._subEmitters)){let r=[];for(let t of i)r.push(t.serialize(e));t.subEmitters.push(r)}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){let i=t.emitter;e.emitterId=i.id}else{let 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,rg.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;let r=t.getColorGradients();if(r)for(let t of(e.colorGradients=[],r)){let i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}let s=t.getRampGradients();if(s){for(let t of(e.rampGradients=[],s)){let i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}let n=t.getColorRemapGradients();if(n)for(let t of(e.colorRemapGradients=[],n)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}let a=t.getAlphaRemapGradients();if(a)for(let t of(e.alphaRemapGradients=[],a)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}let o=t.getSizeGradients();if(o)for(let t of(e.sizeGradients=[],o)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}let l=t.getAngularSpeedGradients();if(l)for(let t of(e.angularSpeedGradients=[],l)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}let h=t.getVelocityGradients();if(h)for(let t of(e.velocityGradients=[],h)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}let u=t.getDragGradients();if(u)for(let t of(e.dragGradients=[],u)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}let c=t.getEmitRateGradients();if(c)for(let t of(e.emitRateGradients=[],c)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}let d=t.getStartSizeGradients();if(d)for(let t of(e.startSizeGradients=[],d)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}let p=t.getLifeTimeGradients();if(p)for(let t of(e.lifeTimeGradients=[],p)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}let _=t.getLimitVelocityGradients();if(_){for(let t of(e.limitVelocityGradients=[],_)){let 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,r){var s,n,a;let o,l;o=i instanceof sx.B?null:i;let h=(0,rn.q)("BABYLON.Texture");if(h&&o&&(e.texture?t.particleTexture=h.Parse(e.texture,o,r):e.textureName&&(t.particleTexture=new h(r+e.textureName,o,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&o?t.emitter=o.getLastMeshById(e.emitterId):t.emitter=rr.P.FromArray(e.emitter):t.emitter=rr.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;i<e.animations.length;i++){let r=e.animations[i],s=(0,rn.q)("BABYLON.Animation");s&&t.animations.push(s.Parse(r))}t.beginAnimationOnStart=e.beginAnimationOnStart,t.beginAnimationFrom=e.beginAnimationFrom,t.beginAnimationTo=e.beginAnimationTo,t.beginAnimationLoop=e.beginAnimationLoop}if(e.autoAnimate&&o&&o.beginAnimation(t,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),t.startDelay=0|e.startDelay,t.minAngularSpeed=e.minAngularSpeed,t.maxAngularSpeed=e.maxAngularSpeed,t.minSize=e.minSize,t.maxSize=e.maxSize,e.minScaleX&&(t.minScaleX=e.minScaleX,t.maxScaleX=e.maxScaleX,t.minScaleY=e.minScaleY,t.maxScaleY=e.maxScaleY),void 0!==e.preWarmCycles&&(t.preWarmCycles=e.preWarmCycles,t.preWarmStepOffset=e.preWarmStepOffset),void 0!==e.minInitialRotation&&(t.minInitialRotation=e.minInitialRotation,t.maxInitialRotation=e.maxInitialRotation),t.minLifeTime=e.minLifeTime,t.maxLifeTime=e.maxLifeTime,t.minEmitPower=e.minEmitPower,t.maxEmitPower=e.maxEmitPower,t.emitRate=e.emitRate,t.gravity=rr.P.FromArray(e.gravity),e.noiseStrength&&(t.noiseStrength=rr.P.FromArray(e.noiseStrength)),t.color1=rs.HE.FromArray(e.color1),t.color2=rs.HE.FromArray(e.color2),t.colorDead=rs.HE.FromArray(e.colorDead),t.updateSpeed=e.updateSpeed,t.targetStopDuration=e.targetStopDuration,t.blendMode=e.blendMode,e.colorGradients)for(let i of e.colorGradients)t.addColorGradient(i.gradient,rs.HE.FromArray(i.color1),i.color2?rs.HE.FromArray(i.color2):void 0);if(e.rampGradients){for(let i of e.rampGradients)t.addRampGradient(i.gradient,rs.Wo.FromArray(i.color));t.useRampGradients=e.useRampGradients}if(e.colorRemapGradients)for(let i of e.colorRemapGradients)t.addColorRemapGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.alphaRemapGradients)for(let i of e.alphaRemapGradients)t.addAlphaRemapGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.sizeGradients)for(let i of e.sizeGradients)t.addSizeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.angularSpeedGradients)for(let i of e.angularSpeedGradients)t.addAngularSpeedGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.velocityGradients)for(let i of e.velocityGradients)t.addVelocityGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.dragGradients)for(let i of e.dragGradients)t.addDragGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.emitRateGradients)for(let i of e.emitRateGradients)t.addEmitRateGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.startSizeGradients)for(let i of e.startSizeGradients)t.addStartSizeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.lifeTimeGradients)for(let i of e.lifeTimeGradients)t.addLifeTimeGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);if(e.limitVelocityGradients){for(let i of e.limitVelocityGradients)t.addLimitVelocityGradient(i.gradient,void 0!==i.factor1?i.factor1:i.factor,i.factor2);t.limitVelocityDamping=e.limitVelocityDamping}if(e.noiseTexture&&o){let i=(0,rn.q)("BABYLON.ProceduralTexture");t.noiseTexture=i.Parse(e.noiseTexture,o,r)}if(e.particleEmitterType){switch(e.particleEmitterType.type){case"SphereParticleEmitter":l=new nb;break;case"SphereDirectedParticleEmitter":l=new ny;break;case"ConeEmitter":case"ConeParticleEmitter":l=new nT;break;case"CylinderParticleEmitter":l=new nx;break;case"CylinderDirectedParticleEmitter":l=new nS;break;case"HemisphericParticleEmitter":l=new nE;break;case"PointParticleEmitter":l=new nC;break;case"MeshParticleEmitter":l=new nR;break;default:l=new nv}l.parse(e.particleEmitterType,o)}else(l=new nv).parse(e,o);t.particleEmitterType=l,t.startSpriteCellID=e.startSpriteCellID,t.endSpriteCellID=e.endSpriteCellID,t.spriteCellLoop=null===(s=e.spriteCellLoop)||void 0===s||s,t.spriteCellWidth=e.spriteCellWidth,t.spriteCellHeight=e.spriteCellHeight,t.spriteCellChangeSpeed=e.spriteCellChangeSpeed,t.spriteRandomStartCell=e.spriteRandomStartCell,t.disposeOnStop=null!==(n=e.disposeOnStop)&&void 0!==n&&n,t.manualEmitCount=null!==(a=e.manualEmitCount)&&void 0!==a?a:-1}static Parse(e,t,i,r=!1,s){let n;let a=e.name,o=null,l=null;if(n=t instanceof sx.B?t:t.getEngine(),e.customShader&&n.createEffectForParticles){l=e.customShader;let t=l.shaderOptions.defines.length>0?l.shaderOptions.defines.join("\n"):"";o=n.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,t)}let h=new m2(a,s||e.capacity,t,o,e.isAnimationSheetEnabled);if(h.customShader=l,h._rootUrl=i,e.id&&(h.id=e.id),e.subEmitters)for(let r of(h.subEmitters=[],e.subEmitters)){let e=[];for(let s of r)e.push(mJ.Parse(s,t,i));h.subEmitters.push(e)}return m2._Parse(e,h,t,i),e.textureMask&&(h.textureMask=rs.HE.FromArray(e.textureMask)),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),r||h.preventAutoStart||h.start(),h}}m2.BILLBOARDMODE_Y=2,m2.BILLBOARDMODE_ALL=7,m2.BILLBOARDMODE_STRETCHED=8,m2.BILLBOARDMODE_STRETCHED_LOCAL=9,mJ._ParseParticleSystem=m2.Parse;let m3=`#ifdef CLIPPLANE -in float fClipDistance; -#endif -#ifdef CLIPPLANE2 -in float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -in float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -in float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -in float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -in float fClipDistance6; -#endif -`;no.v.IncludesShadersStore.clipPlaneFragmentDeclaration2=m3;let m4=`precision highp float; -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; -#include<clipPlaneFragmentDeclaration2> -#include<imageProcessingDeclaration> -#include<logDepthDeclaration> -#include<helperFunctions> -#include<imageProcessingFunctions> -void main() { -#include<clipPlaneFragment> -vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; -#ifdef BLENDMULTIPLYMODE -float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); -#endif -#include<logDepthFragment> -#ifdef IMAGEPROCESSINGPOSTPROCESS -gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); -#else -#ifdef IMAGEPROCESSING -gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); -#endif -#endif -} -`;no.v.ShadersStore.gpuRenderParticlesPixelShader=m4;let m5=`#ifdef CLIPPLANE -uniform vec4 vClipPlane;out float fClipDistance; -#endif -#ifdef CLIPPLANE2 -uniform vec4 vClipPlane2;out float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -uniform vec4 vClipPlane3;out float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -uniform vec4 vClipPlane4;out float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -uniform vec4 vClipPlane5;out float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -uniform vec4 vClipPlane6;out float fClipDistance6; -#endif -`;no.v.IncludesShadersStore.clipPlaneVertexDeclaration2=m5;let m6=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; -#ifdef LOCAL -uniform mat4 emitterWM; -#endif -attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; -#ifndef BILLBOARD -attribute vec3 initialDirection; -#endif -#ifdef BILLBOARDSTRETCHED -attribute vec3 direction; -#endif -attribute float angle; -#ifdef ANIMATESHEET -attribute float cellIndex; -#endif -attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; -#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) -uniform mat4 invView; -#endif -#include<clipPlaneVertexDeclaration2> -#include<logDepthDeclaration> -#ifdef COLORGRADIENTS -uniform sampler2D colorGradientSampler; -#else -uniform vec4 colorDead;attribute vec4 color; -#endif -#ifdef ANIMATESHEET -uniform vec3 sheetInfos; -#endif -#ifdef BILLBOARD -uniform vec3 eyePosition; -#endif -vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; -#ifdef LOCAL -return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; -#else -return (position+worldOffset)+alignedCorner; -#endif -} -#ifdef BILLBOARDSTRETCHED -vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; -#ifdef LOCAL -return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; -#else -return (position+worldOffset)+alignedCorner; -#endif -} -#endif -void main() { -#ifdef ANIMATESHEET -float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; -#else -vUV=uv; -#endif -float ratio=age/life; -#ifdef COLORGRADIENTS -vColor=texture2D(colorGradientSampler,vec2(ratio,0)); -#else -vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); -#endif -vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; -#ifdef BILLBOARD -vec4 rotatedCorner;rotatedCorner.w=0.; -#ifdef BILLBOARDY -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); -#elif defined(BILLBOARDSTRETCHED) -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); -#else -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; -#ifdef LOCAL -vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; -#else -vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; -#endif -vPositionW=(invView*viewPosition).xyz; -#endif -#else -vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); -#endif -gl_Position=projection*viewPosition; -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=vec4(vPositionW,1.0); -#endif -#include<clipPlaneVertex> -#include<logDepthVertex> -}`;no.v.ShadersStore.gpuRenderParticlesVertexShader=m6;class m8 extends nP{static get IsSupported(){if(!rp.l.LastCreatedEngine)return!1;let e=rp.l.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]))}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==m2.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(m2.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(m2.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t,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 nc.q(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new ri.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=[]);let i=new mq(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.gradient<t.gradient?-1:e.gradient>t.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(let t in this._drawWrappers){let i=this._drawWrappers[t];null===(e=i.drawContext)||void 0===e||e.reset()}}_addFactorGradient(e,t,i){let r=new m$(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){e&&(i&&e.sort((e,t)=>e.gradient<t.gradient?-1:e.gradient>t.gradient?1:0),this[t]&&(this[t].dispose(),this[t]=null))}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this.onDisposeObservable=new ri.y$,this.onStoppedObservable=new ri.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=rr.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||rp.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!(0,rn.q)("BABYLON.ComputeShaderParticleSystem"))throw Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,rn.q)("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!(0,rn.q)("BABYLON.WebGL2ParticleSystem"))throw Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,rn.q)("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new nc.q(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new nc.q(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=null!=t?t:{}).randomTextureSize||delete t.randomTextureSize;let n=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),a=t;isFinite(a)&&(n.capacity=a),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new nv;let o=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize),l=[];for(let e=0;e<o;++e)l.push(Math.random()),l.push(Math.random()),l.push(Math.random()),l.push(Math.random());this._randomTexture=new sb(new Float32Array(l),o,1,5,i,!1,!1,1,1),this._randomTexture.name="GPUParticleSystem_random1",this._randomTexture.wrapU=1,this._randomTexture.wrapV=1,l=[];for(let e=0;e<o;++e)l.push(Math.random()),l.push(Math.random()),l.push(Math.random()),l.push(Math.random());this._randomTexture2=new sb(new Float32Array(l),o,1,5,i,!1,!1,1,1),this._randomTexture2.name="GPUParticleSystem_random2",this._randomTexture2.wrapU=1,this._randomTexture2.wrapV=1,this._randomTextureSize=o}_reset(){this._releaseBuffers()}_createVertexBuffers(e,t,i){let r={};r.position=t.createVertexBuffer("position",0,3,this._attributesStrideSize,!0);let s=3;r.age=t.createVertexBuffer("age",s,1,this._attributesStrideSize,!0),s+=1,r.size=t.createVertexBuffer("size",s,3,this._attributesStrideSize,!0),s+=3,r.life=t.createVertexBuffer("life",s,1,this._attributesStrideSize,!0),s+=5,this.billboardMode===m2.BILLBOARDMODE_STRETCHED&&(r.direction=t.createVertexBuffer("direction",s,3,this._attributesStrideSize,!0)),s+=3,this._platform.alignDataInBuffer&&(s+=1),this.particleEmitterType instanceof nA&&(s+=3,this._platform.alignDataInBuffer&&(s+=1)),this._colorGradientsTexture||(r.color=t.createVertexBuffer("color",s,4,this._attributesStrideSize,!0),s+=4),!this._isBillboardBased&&(r.initialDirection=t.createVertexBuffer("initialDirection",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1)),this.noiseTexture&&(r.noiseCoordinates1=t.createVertexBuffer("noiseCoordinates1",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1),r.noiseCoordinates2=t.createVertexBuffer("noiseCoordinates2",s,3,this._attributesStrideSize,!0),s+=3,this._platform.alignDataInBuffer&&(s+=1)),r.angle=t.createVertexBuffer("angle",s,1,this._attributesStrideSize,!0),this._angularSpeedGradientsTexture?s++:s+=2,this._isAnimationSheetEnabled&&(r.cellIndex=t.createVertexBuffer("cellIndex",s,1,this._attributesStrideSize,!0),s+=1,this.spriteRandomStartCell&&(r.cellStartOffset=t.createVertexBuffer("cellStartOffset",s,1,this._attributesStrideSize,!0),s+=1)),r.offset=i.createVertexBuffer("offset",0,2),r.uv=i.createVertexBuffer("uv",2,2),this._renderVertexBuffers.push(r),this._platform.createVertexBuffers(e,r),this.resetDrawCache()}_initialize(e=!1){if(this._buffer0&&!e)return;let t=this._engine,i=[];this._attributesStrideSize=21,this._targetIndex=0,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1),this.particleEmitterType instanceof nA&&(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),!this.isBillboardBased&&(this._attributesStrideSize+=3,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=1)),this._colorGradientsTexture&&(this._attributesStrideSize-=4),this._angularSpeedGradientsTexture&&(this._attributesStrideSize-=1),this._isAnimationSheetEnabled&&(this._attributesStrideSize+=1,this.spriteRandomStartCell&&(this._attributesStrideSize+=1)),this.noiseTexture&&(this._attributesStrideSize+=6,this._platform.alignDataInBuffer&&(this._attributesStrideSize+=2)),this._platform.alignDataInBuffer&&(this._attributesStrideSize+=3-(this._attributesStrideSize+3&3));let r=this.particleEmitterType instanceof nA,s=rr.jp.Vector3[0],n=0;for(let e=0;e<this._capacity;e++)if(i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),r?(this.particleEmitterType.particleDestinationGenerator(e,null,s),i.push(s.x),i.push(s.y),i.push(s.z)):(i.push(0),i.push(0),i.push(0)),this._platform.alignDataInBuffer&&i.push(0),n+=16,r&&(this.particleEmitterType.particlePositionGenerator(e,null,s),i.push(s.x),i.push(s.y),i.push(s.z),this._platform.alignDataInBuffer&&i.push(0),n+=4),this._colorGradientsTexture||(i.push(0),i.push(0),i.push(0),i.push(0),n+=4),this.isBillboardBased||(i.push(0),i.push(0),i.push(0),this._platform.alignDataInBuffer&&i.push(0),n+=4),this.noiseTexture&&(i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),i.push(Math.random()),i.push(Math.random()),i.push(Math.random()),this._platform.alignDataInBuffer&&i.push(0),n+=8),i.push(0),n+=1,this._angularSpeedGradientsTexture||(i.push(0),n+=1),this._isAnimationSheetEnabled&&(i.push(0),n+=1,this.spriteRandomStartCell&&(i.push(0),n+=1)),this._platform.alignDataInBuffer){let e=3-(n+3&3);for(n+=e;e-- >0;)i.push(0)}let a=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),o=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new rQ.l(t,o,!1,this._attributesStrideSize),this._buffer1=new rQ.l(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new rQ.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){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||((r=new nc.q(this._engine)).drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);let s=i.join("\n");if(r.defines!==s){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){let s=[rQ.o.PositionKind,"age","life","size","angle"];return e||s.push(rQ.o.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),r&&s.push("direction"),s.push("offset",rQ.o.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1){let i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return(0,lx.qx)(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&(0,lx.lK)(this,this._scene,e),t===m2.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 m2.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case m2.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case m2.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(...m8._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===m2.BILLBOARDMODE_STRETCHED)),e.push(...m8._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(ng.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ng.$.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){let i=this[t];if(!e||!e.length||i)return;let r=new Float32Array(this._rawTextureWidth);for(let t=0;t<this._rawTextureWidth;t++){let i=t/this._rawTextureWidth;mQ.GetCurrentGradient(i,e,(e,i,s)=>{r[t]=rm.R.Lerp(e.factor1,i.factor1,s)})}this[t]=sb.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;let e=new Uint8Array(4*this._rawTextureWidth),t=rs.zZ.Color4[0];for(let i=0;i<this._rawTextureWidth;i++){let r=i/this._rawTextureWidth;mQ.GetCurrentGradient(r,this._colorGradients,(r,s,n)=>{rs.HE.LerpToRef(r.color1,s.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a})}this._colorGradientsTexture=sb.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,r,s,n,a;let o=this._getWrapper(e),l=o.effect;this._engine.enableEffect(o);let h=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||rr.y3.IdentityReadOnly;if(l.setMatrix("view",h),l.setMatrix("projection",null!==(r=this.defaultProjectionMatrix)&&void 0!==r?r:this._scene.getProjectionMatrix()),l.setTexture("diffuseSampler",this.particleTexture),l.setVector2("translationPivot",this.translationPivot),l.setVector3("worldOffset",this.worldOffset),this.isLocal&&l.setMatrix("emitterWM",t),this._colorGradientsTexture?l.setTexture("colorGradientSampler",this._colorGradientsTexture):l.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){let e=this.particleTexture.getBaseSize();l.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){let e=this._scene.activeCamera;l.setVector3("eyePosition",e.globalPosition)}let u=l.defines;if(this._scene&&(0,lx.an)(l,this,this._scene),u.indexOf("#define BILLBOARDMODE_ALL")>=0){let e=h.clone();e.invert(),l.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&s3.G.BindLogDepth(u,l,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(l),e){case m2.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case m2.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case m2.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case m2.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,l,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(l),(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect())return;if(!e){if(this.emitter.position){let t=this.emitter;e=t.getWorldMatrix()}else{let t=this.emitter;e=rr.jp.Matrix[0],rr.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);let t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){let i;if(!this._started||!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e<this.preWarmCycles;e++)this.animate(!0),this.render(!0,!0);this._preWarmDone=!0}if(this._currentRenderId===this._scene.getRenderId()&&(!this._scene.activeCamera||this._scene.activeCamera&&this._currentRenderingCameraUniqueId===this._scene.activeCamera.uniqueId))return 0;this._currentRenderId=this._scene.getRenderId(),this._scene.activeCamera&&(this._currentRenderingCameraUniqueId=this._scene.activeCamera.uniqueId)}if(this._initialize(),this._accumulatedCount+=this.emitRate*this._timeDelta,this._accumulatedCount>1){let e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;if(this.emitter.position){let e=this.emitter;i=e.getWorldMatrix()}else{let e=this.emitter;i=rr.jp.Matrix[0],rr.y3.TranslationToRef(e.x,e.y,e.z,i)}let r=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),s=this.blendMode===m2.BLENDMODE_MULTIPLYADD?this._render(m2.BLENDMODE_MULTIPLY,i)+this._render(m2.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){let e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?this._initialize(!0):setTimeout(e,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(let e in this._drawWrappers){let t=this._drawWrappers[e];t.dispose()}if(this._drawWrappers={},this._scene){let e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e<this._renderVertexBuffers.length;++e){let t=this._renderVertexBuffers[e];for(let e in t)t[e].dispose()}this._renderVertexBuffers=[],this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null),this._sizeGradientsTexture&&(this._sizeGradientsTexture.dispose(),this._sizeGradientsTexture=null),this._angularSpeedGradientsTexture&&(this._angularSpeedGradientsTexture.dispose(),this._angularSpeedGradientsTexture=null),this._velocityGradientsTexture&&(this._velocityGradientsTexture.dispose(),this._velocityGradientsTexture=null),this._limitVelocityGradientsTexture&&(this._limitVelocityGradientsTexture.dispose(),this._limitVelocityGradientsTexture=null),this._dragGradientsTexture&&(this._dragGradientsTexture.dispose(),this._dragGradientsTexture=null),this._randomTexture&&(this._randomTexture.dispose(),this._randomTexture=null),this._randomTexture2&&(this._randomTexture2.dispose(),this._randomTexture2=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this.onStoppedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}clone(e,t,i=!1){let r=Object.assign({},this._customWrappers),s=null,n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){s=this.customShader;let e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"";r[0]=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}let a=this.serialize(i),o=m8.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,o}serialize(e=!1){let t={};return m2._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,s){let n;let a=e.name;n=t instanceof sx.B?t:t.getEngine();let o=new m8(a,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(o._rootUrl=i,e.customShader&&n.createEffectForParticles){let t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",r=n.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,o);o.setCustomEffect(r,0),o.customShader=t}return e.id&&(o.id=e.id),e.activeParticleCount&&(o.activeParticleCount=e.activeParticleCount),m2._Parse(e,o,t,i),e.preventAutoStart&&(o.preventAutoStart=e.preventAutoStart),r||o.preventAutoStart||o.start(),o}}class m7{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){for(let t of(this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1),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};let r=ha("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;let s=new lC("emitterSphereMaterial",i);for(let t of(s.emissiveColor=e.color,r.material=s,this.systems))t.emitter=r;this._emitterNode=r}start(e){for(let t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(let e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){let t={};for(let i of(t.systems=[],this.systems))t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){let s=new m7,n=this.BaseAssetsUrl+"/textures/";for(let a of(t=t||rp.l.LastCreatedScene,e.systems))s.systems.push(i?m8.Parse(a,t,n,!0,r):m2.Parse(a,t,n,!0,r));if(e.emitter){let i=e.emitter.options;"Sphere"===e.emitter.kind&&s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:rs.Wo.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}}m7.BaseAssetsUrl="https://assets.babylonjs.com/particles";class m9{static CreateDefault(e,t=500,i,r=!1){let s;return(s=r?new m8("default system",{capacity:t},i):new m2("default system",t,i)).emitter=e,s.particleTexture=new sv("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new rs.HE(1,1,1,1),s.color2=new rs.HE(1,1,1,1),s.colorDead=new rs.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,r){t||(t=rp.l.LastCreatedScene);let s={};return t.addPendingData(s),new Promise((n,a)=>{if(i&&!m8.IsSupported)return t.removePendingData(s),a("Particle system with GPU is not supported.");rZ.w1.LoadFile(`${m9.BaseAssetsUrl}/systems/${e}.json`,e=>{t.removePendingData(s);let a=JSON.parse(e.toString());return n(m7.Parse(a,t,i,r))},void 0,void 0,void 0,()=>(t.removePendingData(s),a(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){let t=new m7;for(let i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,s="",n){return new Promise((a,o)=>{let l=new rS.g;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let t;let o=JSON.parse(l.responseText);t=r?m8.Parse(o,i,s,!1,n):m2.Parse(o,i,s,!1,n),e&&(t.name=e),a(t)}else o("Unable to load the particle system")}}),l.open("GET",t),l.send()})}static ParseFromSnippetAsync(e,t,i=!1,r="",s){if("_BLANK"===e){let e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise((n,a)=>{let o=new rS.g;o.addEventListener("readystatechange",()=>{if(4==o.readyState){if(200==o.status){let a;let l=JSON.parse(JSON.parse(o.responseText).jsonPayload),h=JSON.parse(l.particleSystem);(a=i?m8.Parse(h,t,r,!1,s):m2.Parse(h,t,r,!1,s)).snippetId=e,n(a)}else a("Unable to load the snippet "+e)}}),o.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),o.send()})}}m9.BaseAssetsUrl=m7.BaseAssetsUrl,m9.SnippetUrl="https://snippet.babylonjs.com",m9.CreateFromSnippetAsync=m9.ParseFromSnippetAsync,re.p.AddParser(ss.l.NAME_PARTICLESYSTEM,(e,t,i,r)=>{let s=re.p.GetIndividualParser(ss.l.NAME_PARTICLESYSTEM);if(s&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,a=e.particleSystems.length;n<a;n++){let a=e.particleSystems[n];i.particleSystems.push(s(a,t,r))}}),re.p.AddIndividualParser(ss.l.NAME_PARTICLESYSTEM,(e,t,i)=>{if(e.activeParticleCount){let r=m8.Parse(e,t,i);return r}{let r=m2.Parse(e,t,i);return r}}),r7.D.prototype.createEffectForParticles=function(e,t=[],i=[],r="",s,n,a,o){var l;let h=[],u=[],c=[];return o?o.fillUniformsAttributesAndSamplerNames(u,h,c):(h=m2._GetAttributeNamesOrOptions(),u=m2._GetEffectCreationOptions()),-1===r.indexOf(" BILLBOARD")&&(r+="\n#define BILLBOARD\n"),(null==o?void 0:o.isAnimationSheetEnabled)&&-1===r.indexOf(" ANIMATESHEET")&&(r+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==o?void 0:o.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},h,u.concat(t),c.concat(i),r,s,n,a)},rq.Kj.prototype.getEmittedParticleSystems=function(){let e=[];for(let t=0;t<this.getScene().particleSystems.length;t++){let i=this.getScene().particleSystems[t];i.emitter===this&&e.push(i)}return e},rq.Kj.prototype.getHierarchyEmittedParticleSystems=function(){let e=[],t=this.getDescendants();t.push(this);for(let i=0;i<this.getScene().particleSystems.length;i++){let r=this.getScene().particleSystems[i],s=r.emitter;s.position&&-1!==t.indexOf(s)&&e.push(r)}return e},(e$=iH||(iH={}))[e$.Color=2]="Color",e$[e$.UV=1]="UV",e$[e$.Random=0]="Random",e$[e$.Stated=3]="Stated",Object.defineProperty(r$.x.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0}),r$.x.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},r$.x.prototype.applyImpulse=function(e,t){return this.physicsImpostor&&this.physicsImpostor.applyImpulse(e,t),this},r$.x.prototype.setPhysicsLinkWith=function(e,t,i,r){return this.physicsImpostor&&e.physicsImpostor&&this.physicsImpostor.createJoint(e.physicsImpostor,sk.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:r}),this};class ge{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,st.S)("")}constructor(e,t=ge.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new rr.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){let t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){let r=new _G;return this._physicsPlugin.raycast(e,t,r,i),r}}(eQ=iX||(iX={}))[eQ.FREE=0]="FREE",eQ[eQ.LIMITED=1]="LIMITED",eQ[eQ.LOCKED=2]="LOCKED",(eZ=iY||(iY={}))[eZ.LINEAR_X=0]="LINEAR_X",eZ[eZ.LINEAR_Y=1]="LINEAR_Y",eZ[eZ.LINEAR_Z=2]="LINEAR_Z",eZ[eZ.ANGULAR_X=3]="ANGULAR_X",eZ[eZ.ANGULAR_Y=4]="ANGULAR_Y",eZ[eZ.ANGULAR_Z=5]="ANGULAR_Z",eZ[eZ.LINEAR_DISTANCE=6]="LINEAR_DISTANCE",(eJ=ij||(ij={}))[eJ.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",eJ[eJ.DISTANCE=2]="DISTANCE",eJ[eJ.HINGE=3]="HINGE",eJ[eJ.SLIDER=4]="SLIDER",eJ[eJ.LOCK=5]="LOCK",eJ[eJ.PRISMATIC=6]="PRISMATIC",eJ[eJ.SIX_DOF=7]="SIX_DOF",(e0=iq||(iq={}))[e0.SPHERE=0]="SPHERE",e0[e0.CAPSULE=1]="CAPSULE",e0[e0.CYLINDER=2]="CYLINDER",e0[e0.BOX=3]="BOX",e0[e0.CONVEX_HULL=4]="CONVEX_HULL",e0[e0.CONTAINER=5]="CONTAINER",e0[e0.MESH=6]="MESH",e0[e0.HEIGHTFIELD=7]="HEIGHTFIELD",(e1=iK||(iK={}))[e1.NONE=0]="NONE",e1[e1.VELOCITY=1]="VELOCITY",e1[e1.POSITION=2]="POSITION",(e2=i$||(i$={})).COLLISION_STARTED="COLLISION_STARTED",e2.COLLISION_CONTINUED="COLLISION_CONTINUED",e2.COLLISION_FINISHED="COLLISION_FINISHED",e2.TRIGGER_ENTERED="TRIGGER_ENTERED",e2.TRIGGER_EXITED="TRIGGER_EXITED",(e3=iQ||(iQ={}))[e3.STATIC=0]="STATIC",e3[e3.ANIMATED=1]="ANIMATED",e3[e3.DYNAMIC=2]="DYNAMIC",(e4=iZ||(iZ={}))[e4.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",e4[e4.MINIMUM=1]="MINIMUM",e4[e4.MAXIMUM=2]="MAXIMUM",e4[e4.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",e4[e4.MULTIPLY=4]="MULTIPLY",rI.x.prototype.getPhysicsEngine=function(){return this._physicsEngine},rI.x.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(ss.l.NAME_PHYSICSENGINE);i||(i=new gt(this),this._addComponent(i));try{if(t&&(null==t?void 0:t.getPluginVersion())!==1){if((null==t?void 0:t.getPluginVersion())===2)this._physicsEngine=new ge(e,t);else throw Error("Unsupported Physics plugin version.")}else this._physicsEngine=new _z(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return ru.Y.Error(e.message),!1}},rI.x.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},rI.x.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},rI.x.prototype.deleteCompoundImpostor=function(e){let t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},rI.x.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){let 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 gt{constructor(e){this.name=ss.l.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new ri.y$,this.scene.onAfterPhysicsObservable=new ri.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(rK.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}),rK.Y.prototype.getPhysicsBody=function(){return this.physicsBody},rK.Y.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this};class gi{static GetContactPointToRef(e,t,i,r,s){let n=e.getScene().getPhysicsEngine(),a=null==n?void 0:n.getPluginVersion();if(1===a){let s=new sD(t,i),n=s.intersectsMesh(e);if(n.hit&&n.pickedPoint)return r.copyFrom(n.pickedPoint),!0}else if(2===a)return e.physicsBody.getObjectCenterWorldToRef(r,s),!0;return!1}static HasAppliedForces(e,t){var i,r,s;return e.getMotionType(t)===iQ.STATIC||(null!==(r=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==r?r:0)===0||(null===(s=e.transformNode)||void 0===s?void 0:s.getTotalVertices())===0}static IsInsideCylinder(e,t,i,r){let s=rr.jp.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=r}}class gr{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=rr.P.Zero(),this._originDirection=rr.P.Zero(),this._cylinderPosition=rr.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new gn),this._options),this._origin.addToRef(new rr.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new rr.P(0,this._options.height,0),this._originTop),this._options.updraftMode===i0.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===i0.Perpendicular?this._originDirection:e.subtract(this._originTop);let r=rr.P.Distance(this._origin,e),s=-1*this._options.strength,n=i.multiplyByFloats(s,s,s);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(gi.HasAppliedForces(e))return!1;let r=e.getObjectCenterWorld(i);return!!gi.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){let e=gr._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=lV("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))}}gr._HitData={force:new rr.P,contactPoint:new rr.P,distanceFromOrigin:0};class gs{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=rr.P.Zero(),this._cylinderPosition=rr.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new ga),this._options),this._origin.addToRef(new rr.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new rr.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){let r,s,n;let a=gs.originOnPlane;a.set(this._origin.x,t.y,this._origin.z);let o=rr.jp.Vector3[0];t.subtractToRef(a,o);let l=rr.jp.Vector3[1],h=gi.GetContactPointToRef(e,a,o,l,i.instanceIndex);if(!h)return!1;let u=rr.P.Distance(l,a),c=u/this._options.radius,d=rr.jp.Vector3[2];if(l.normalizeToRef(d),c>this._options.centripetalForceThreshold&&d.negateInPlace(),c>this._options.centripetalForceThreshold)r=d.x*this._options.centripetalForceMultiplier,s=d.y*this._options.updraftForceMultiplier,n=d.z*this._options.centripetalForceMultiplier;else{let e=rr.P.Cross(a,t).normalize();r=(e.x+d.x)*this._options.centrifugalForceMultiplier,s=this._originTop.y*this._options.updraftForceMultiplier,n=(e.z+d.z)*this._options.centrifugalForceMultiplier}let p=rr.jp.Vector3[3];return p.set(r,s,n),p.scaleInPlace(this._options.strength),i.force.copyFrom(p),i.contactPoint.copyFrom(t),i.distanceFromOrigin=c,!0}_getBodyHitData(e,t,i){if(gi.HasAppliedForces(e,i))return!1;let r=e.transformNode,s=e.getObjectCenterWorld(i);return!!gi.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,s,t))}_getImpostorHitData(e,t){if(0===e.mass||"Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){let e=gs.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=lV("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)}}gs.originOnPlane=rr.P.Zero(),gs.hitData={force:new rr.P,contactPoint:new rr.P,distanceFromOrigin:0};class gn{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=i0.Center}}class ga{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}(e5=iJ||(iJ={}))[e5.Constant=0]="Constant",e5[e5.Linear=1]="Linear",(e6=i0||(i0={}))[e6.Center=0]="Center",e6[e6.Perpendicular=1]="Perpendicular";let go=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); -vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;no.v.ShadersStore.blackAndWhitePixelShader=go;class gl extends np{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,r,s,n){super(e,"blackAndWhite",["degree"],null,t,i,r,s,n),this.degree=1,this.onApplyObservable.add(e=>{e.setFloat("degree",this.degree)})}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new gl(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,r0.gn)([(0,rg.qC)()],gl.prototype,"degree",void 0),(0,rn.H)("BABYLON.BlackAndWhitePostProcess",gl);class gh{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(let e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){let t=this._postProcesses[e];for(let e=0;e<t.length;e++)if(!t[e].isSupported)return!1}return!0}_update(){}_attachCameras(e){let t;let i=rZ.w1.MakeArray(e||this._cameras);if(i)for(let e=0;e<i.length;e++){let r=i[e];if(!r)continue;let s=r.name;if(t=this._singleInstance?0:s,!this._postProcesses[t]){let e=this._getPostProcesses();e&&(this._postProcesses[t]=Array.isArray(e)?e:[e])}this._indicesForCamera[s]||(this._indicesForCamera[s]=[]),this._postProcesses[t].forEach(e=>{let t=r.attachPostProcess(e);this._indicesForCamera[s].push(t)}),this._cameras[s]||(this._cameras[s]=r)}}_detachCameras(e){let t=rZ.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){let i=t[e],r=i.name,s=this._postProcesses[this._singleInstance?0:r];s&&s.forEach(e=>{i.detachPostProcess(e)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){let t=rZ.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){let i=t[e],r=i.name,s=this._singleInstance?0:r;for(let n=0;n<this._indicesForCamera[r].length;n++){let a=this._indicesForCamera[r][n],o=i._postProcesses[a];null==o&&t[e].attachPostProcess(this._postProcesses[s][n],a)}}}_disable(e){let t=rZ.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e<t.length;e++){let i=t[e],r=i.name;this._postProcesses[this._singleInstance?0:r].forEach(e=>{i.detachPostProcess(e)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}let gu=`#include<helperFunctions> -varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;no.v.ShadersStore.extractHighlightsPixelShader=gu;class gc extends np{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,r,s,n,null,a,void 0,null,o),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,rL.zp)),e.setFloat("exposure",this._exposure)})}}(0,r0.gn)([(0,rg.qC)()],gc.prototype,"threshold",void 0),(0,rn.H)("BABYLON.ExtractHighlightsPostProcess",gc);let gd=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } -`;no.v.ShadersStore.bloomMergePixelShader=gd;class gp extends np{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,s,n,a,o,l,h=0,u=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,n,a,o,l,null,h,void 0,null,!0),this.weight=1,this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)}),u||this.updateEffect()}}(0,r0.gn)([(0,rg.qC)()],gp.prototype,"weight",void 0),(0,rn.H)("BABYLON.BloomMergePostProcess",gp);class g_ extends gh{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,r,s=0,n=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new gc("highlights",1,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,n),this._blurX=new dr("horizontal blur",new rr.FM(1,0),10,t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new dr("vertical blur",new rr.FM(0,1),10,t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new gp("bloomMerge",this._downscale,this._blurY,i,t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){for(let e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0}}let gf=`uniform sampler2D textureSampler; -uniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);} -float radius2=centered_screen_pos.x*centered_screen_pos.x -+ centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec4 original=texture2D(textureSampler,vUV);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);original.r=texture2D(textureSampler,ref_coords_r).r;original.g=texture2D(textureSampler,ref_coords_g).g;original.b=texture2D(textureSampler,ref_coords_b).b;original.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);gl_FragColor=original;}`;no.v.ShadersStore.chromaticAberrationPixelShader=gf;class gm extends np{getClassName(){return"ChromaticAberrationPostProcess"}constructor(e,t,i,r,s,n,a,o,l=0,h=!1){super(e,"chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],r,s,n,a,o,null,l,void 0,null,h),this.aberrationAmount=30,this.radialIntensity=0,this.direction=new rr.FM(.707,.707),this.centerPosition=new rr.FM(.5,.5),this.screenWidth=t,this.screenHeight=i,this.onApplyObservable.add(e=>{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,r){return rg.p4.Parse(()=>new gm(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}}(0,r0.gn)([(0,rg.qC)()],gm.prototype,"aberrationAmount",void 0),(0,r0.gn)([(0,rg.qC)()],gm.prototype,"radialIntensity",void 0),(0,r0.gn)([(0,rg.qC)()],gm.prototype,"direction",void 0),(0,r0.gn)([(0,rg.qC)()],gm.prototype,"centerPosition",void 0),(0,r0.gn)([(0,rg.qC)()],gm.prototype,"screenWidth",void 0),(0,r0.gn)([(0,rg.qC)()],gm.prototype,"screenHeight",void 0),(0,rn.H)("BABYLON.ChromaticAberrationPostProcess",gm);let gg=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float depth=texture2D(depthSampler,vUV).r; -#define CUSTOM_COC_DEPTH -float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; -#define CUSTOM_COC_PIXELDISTANCE -float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} -`;no.v.ShadersStore.circleOfConfusionPixelShader=gg;class gv extends np{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,r,s,n,a,null,o,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){ru.Y.Warn("No depth texture set on CircleOfConfusionPostProcess");return}e.setTexture("depthSampler",this._depthTexture);let t=this.lensSize/this.fStop,i=t*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",i);let r=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",r.minZ,r.maxZ-r.minZ)})}set depthTexture(e){this._depthTexture=e}}(0,r0.gn)([(0,rg.qC)()],gv.prototype,"lensSize",void 0),(0,r0.gn)([(0,rg.qC)()],gv.prototype,"fStop",void 0),(0,r0.gn)([(0,rg.qC)()],gv.prototype,"focusDistance",void 0),(0,r0.gn)([(0,rg.qC)()],gv.prototype,"focalLength",void 0),(0,rn.H)("BABYLON.CircleOfConfusionPostProcess",gv);let gT=`uniform sampler2D textureSampler; -uniform sampler2D colorTable; -varying vec2 vUV;const float SLICE_COUNT=16.0; -vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; -float slicePixelSize=sliceSize/width; -float sliceInnerSize=slicePixelSize*(width-1.0); -float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;no.v.ShadersStore.colorCorrectionPixelShader=gT;class gx extends np{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,s,n,a){super(e,"colorCorrection",null,["colorTable"],i,r,s,n,a);let o=(null==r?void 0:r.getScene())||null;this._colorTableTexture=new sv(t,o,!0,!1,sv.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=sv.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=sv.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new gx(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,r0.gn)([(0,rg.qC)()],gx.prototype,"colorTableUrl",void 0),(0,rn.H)("BABYLON.ColorCorrectionPostProcess",gx);let gS=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = -texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + -texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + -texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + -texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + -texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + -texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + -texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + -texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + -texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = -kernel[0] + -kernel[1] + -kernel[2] + -kernel[3] + -kernel[4] + -kernel[5] + -kernel[6] + -kernel[7] + -kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} -gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;no.v.ShadersStore.convolutionPixelShader=gS;class gE extends np{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,s,n,a,o=0){super(e,"convolution",["kernel","screenSize"],null,i,r,s,n,a,null,o),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new gE(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,r)}}gE.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],gE.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],gE.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],gE.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],gE.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],gE.GaussianKernel=[0,1,0,1,1,1,0,1,0],(0,r0.gn)([(0,rg.qC)()],gE.prototype,"kernel",void 0),(0,rn.H)("BABYLON.ConvolutionPostProcess",gE);class gC extends dr{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,s,n,a,o=null,l=sv.BILINEAR_SAMPLINGMODE,h,u,c=0,d=!1,p=5){super(e,i,r,s,n,2,h,u,c,`#define DOF 1 -`,d,p),this.direction=i,this.externalTextureSamplerBinding=!!o,this.onApplyObservable.add(e=>{null!=o&&e.setTextureFromPostProcess("textureSampler",o),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",a)})}}(0,r0.gn)([(0,rg.qC)()],gC.prototype,"direction",void 0),(0,rn.H)("BABYLON.DepthOfFieldBlurPostProcess",gC);let gb=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; -#if BLUR_LEVEL>0 -uniform sampler2D blurStep1; -#endif -#if BLUR_LEVEL>1 -uniform sampler2D blurStep2; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; -#if BLUR_LEVEL==0 -vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); -#endif -#if BLUR_LEVEL==1 -if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} -#endif -#if BLUR_LEVEL==2 -if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} -#endif -} -`;no.v.ShadersStore.depthOfFieldMergePixelShader=gb;class gy extends np{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,s,n,a,o,l,h=0,u=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,n,a,o,l,null,h,void 0,null,!0),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(r.length-i-1),t)})}),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,r,s,n){e||(e="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,r,s,n)}}(e8=i1||(i1={}))[e8.Low=0]="Low",e8[e8.Medium=1]="Medium",e8[e8.High=2]="High";class gA extends gh{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=i1.Low,r=0,s=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];let n=e.getEngine(),a=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new gv("circleOfConfusion",t,1,null,sv.BILINEAR_SAMPLINGMODE,n,!1,r,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let o=1,l=15;switch(i){case i1.High:o=3,l=51;break;case i1.Medium:o=2,l=31;break;default:l=15,o=1}let h=l/Math.pow(2,o-1),u=1;for(let t=0;t<o;t++){let i=new gC("vertical blur",e,new rr.FM(0,1),h,u,null,this._circleOfConfusion,0==t?this._circleOfConfusion:null,sv.BILINEAR_SAMPLINGMODE,n,!1,r,s,0==t?a:5);i.autoClear=!1,u=.75/Math.pow(2,t);let o=new gC("horizontal blur",e,new rr.FM(1,0),h,u,null,this._circleOfConfusion,null,sv.BILINEAR_SAMPLINGMODE,n,!1,r,s);o.autoClear=!1,this._depthOfFieldBlurY.push(i),this._depthOfFieldBlurX.push(o)}this._effects=[this._circleOfConfusion];for(let e=0;e<this._depthOfFieldBlurX.length;e++)this._effects.push(this._depthOfFieldBlurY[e]),this._effects.push(this._depthOfFieldBlurX[e]);this._dofMerge=new gy("dofMerge",this._circleOfConfusion,this._circleOfConfusion,this._depthOfFieldBlurX,u,null,sv.BILINEAR_SAMPLINGMODE,n,!1,r,s),this._dofMerge.autoClear=!1,this._effects.push(this._dofMerge)}getClassName(){return"DepthOfFieldEffect"}set depthTexture(e){this._circleOfConfusion.depthTexture=e}disposeEffects(e){for(let t=0;t<this._effects.length;t++)this._effects[t].dispose(e)}_updateEffects(){for(let e=0;e<this._effects.length;e++)this._effects[e].updateEffect()}_isReady(){for(let e=0;e<this._effects.length;e++)if(!this._effects[e].isReady())return!1;return!0}}let gR=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D passSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(passSampler,vUV);}`;no.v.ShadersStore.displayPassPixelShader=gR;class gP extends np{getClassName(){return"DisplayPassPostProcess"}constructor(e,t,i,r,s,n){super(e,"displayPass",["passSampler"],["passSampler"],t,i,r,s,n)}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new gP(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,rn.H)("BABYLON.DisplayPassPostProcess",gP);let gI=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;no.v.ShadersStore.filterPixelShader=gI;class gM extends np{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,s,n,a){super(e,"filter",["kernelMatrix"],null,i,r,s,n,a),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new gM(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,r0.gn)([(0,rg.oQ)()],gM.prototype,"kernelMatrix",void 0),(0,rn.H)("BABYLON.FilterPostProcess",gM);let gD=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); -#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) -void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); -#ifndef MALI -if(range<rangeMaxClamped) -{gl_FragColor=rgbyM;return;} -#endif -float lumaNW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNW,0.0));float lumaSE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSE,0.0));float lumaNE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordNE,0.0));float lumaSW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordSW,0.0));float lumaNS=lumaN+lumaS;float lumaWE=lumaW+lumaE;float subpixRcpRange=1.0/range;float subpixNSWE=lumaNS+lumaWE;float edgeHorz1=(-2.0*lumaM)+lumaNS;float edgeVert1=(-2.0*lumaM)+lumaWE;float lumaNESE=lumaNE+lumaSE;float lumaNWNE=lumaNW+lumaNE;float edgeHorz2=(-2.0*lumaE)+lumaNESE;float edgeVert2=(-2.0*lumaN)+lumaNWNE;float lumaNWSW=lumaNW+lumaSW;float lumaSWSE=lumaSW+lumaSE;float edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);float edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);float edgeHorz3=(-2.0*lumaW)+lumaNWSW;float edgeVert3=(-2.0*lumaS)+lumaSWSE;float edgeHorz=abs(edgeHorz3)+edgeHorz4;float edgeVert=abs(edgeVert3)+edgeVert4;float subpixNWSWNESE=lumaNWSW+lumaNESE;float lengthSign=texelSize.x;bool horzSpan=edgeHorz>=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) -{lumaN=lumaW;} -if (!horzSpan) -{lumaS=lumaE;} -if (horzSpan) -{lengthSign=texelSize.y;} -float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) -{lengthSign=-lengthSign;} -float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) -{posB.x+=lengthSign*0.5;} -if (horzSpan) -{posB.y+=lengthSign*0.5;} -vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) -{lumaNN=lumaSS;} -float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) -{posN.x-=offNP.x*3.0;} -if (!doneN) -{posN.y-=offNP.y*3.0;} -bool doneNP=(!doneN) || (!doneP);if (!doneP) -{posP.x+=offNP.x*3.0;} -if (!doneP) -{posP.y+=offNP.y*3.0;} -if (doneNP) -{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} -float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) -{dstN=posM.y-posN.y;} -if (!horzSpan) -{dstP=posP.y-posM.y;} -bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN<dstP;float dst=min(dstN,dstP);bool goodSpan=directionN ? goodSpanN : goodSpanP;float subpixG=subpixF*subpixF;float pixelOffset=(dst*(-spanLengthRcp))+0.5;float subpixH=subpixG*fxaaQualitySubpix;float pixelOffsetGood=goodSpan ? pixelOffset : 0.0;float pixelOffsetSubpix=max(pixelOffsetGood,subpixH);if (!horzSpan) -{posM.x+=pixelOffsetSubpix*lengthSign;} -if (horzSpan) -{posM.y+=pixelOffsetSubpix*lengthSign;} -#ifdef MALI -if(range<rangeMaxClamped) -{gl_FragColor=rgbyM;} -else -{gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0);} -#else -gl_FragColor=TEXTUREFUNC(textureSampler,posM,0.0); -#endif -}`;no.v.ShadersStore.fxaaPixelShader=gD;let gO=`attribute vec2 position;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.fxaaVertexShader=gO;class gN extends np{getClassName(){return"FxaaPostProcess"}constructor(e,t,i=null,r,s,n,a=0){super(e,"fxaa",["texelSize"],null,t,i,r||sv.BILINEAR_SAMPLINGMODE,s,n,null,a,"fxaa",void 0,!0);let o=this._getDefines();this.updateEffect(o),this.onApplyObservable.add(e=>{let t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)})}_getDefines(){let e=this.getEngine();if(!e)return null;let t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new gN(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,rn.H)("BABYLON.FxaaPostProcess",gN);let gF=`#include<helperFunctions> -uniform sampler2D textureSampler; -uniform float intensity;uniform float animatedSeed;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`;no.v.ShadersStore.grainPixelShader=gF;class gL extends np{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,s,n,null,a,void 0,null,o),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,r){return rg.p4.Parse(()=>new gL(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,r0.gn)([(0,rg.qC)()],gL.prototype,"intensity",void 0),(0,r0.gn)([(0,rg.qC)()],gL.prototype,"animated",void 0),(0,rn.H)("BABYLON.GrainPostProcess",gL);let gw=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;no.v.ShadersStore.highlightsPixelShader=gw;let gB=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -layout(location=0) out vec4 glFragData[{X}]; -#endif -`;no.v.IncludesShadersStore.mrtFragmentDeclaration=gB;let gU=`#extension GL_EXT_draw_buffers : require -#if defined(BUMP) || !defined(NORMAL) -#extension GL_OES_standard_derivatives : enable -#endif -precision highp float; -#ifdef BUMP -varying mat4 vWorldView;varying vec3 vNormalW; -#else -varying vec3 vNormalV; -#endif -varying vec4 vViewPos; -#if defined(POSITION) || defined(BUMP) -varying vec3 vPositionW; -#endif -#ifdef VELOCITY -varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#ifdef NEED_UV -varying vec2 vUV; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#if defined(REFLECTIVITY) -#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) -uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; -#endif -#ifdef ALBEDOTEXTURE -varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; -#endif -#ifdef REFLECTIVITYCOLOR -uniform vec3 reflectivityColor; -#endif -#ifdef ALBEDOCOLOR -uniform vec3 albedoColor; -#endif -#ifdef METALLIC -uniform float metallic; -#endif -#if defined(ROUGHNESS) || defined(GLOSSINESS) -uniform float glossiness; -#endif -#endif -#if defined(ALPHATEST) && defined(NEED_UV) -uniform sampler2D diffuseSampler; -#endif -#include<clipPlaneFragmentDeclaration> -#include<mrtFragmentDeclaration>[RENDER_TARGET_COUNT] -#include<bumpFragmentMainFunctions> -#include<bumpFragmentFunctions> -#include<helperFunctions> -void main() { -#include<clipPlaneFragment> -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -vec3 normalOutput; -#ifdef BUMP -vec3 normalW=normalize(vNormalW); -#include<bumpFragment> -normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); -#else -normalOutput=normalize(vNormalV); -#endif -#ifdef PREPASS -#ifdef PREPASS_DEPTH -gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); -#endif -#ifdef PREPASS_NORMAL -gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); -#endif -#else -gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); -#endif -#ifdef POSITION -gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); -#endif -#ifdef VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); -#endif -#ifdef REFLECTIVITY -vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); -#ifdef METALLICWORKFLOW -float metal=1.0;float roughness=1.0; -#ifdef ORMTEXTURE -metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; -#endif -#ifdef METALLIC -metal*=metallic; -#endif -#ifdef ROUGHNESS -roughness*=(1.0-glossiness); -#endif -reflectivity.a-=roughness;vec3 color=vec3(1.0); -#ifdef ALBEDOTEXTURE -color=texture2D(albedoSampler,vAlbedoUV).rgb; -#ifdef GAMMAALBEDO -color=toLinearSpace(color); -#endif -#endif -#ifdef ALBEDOCOLOR -color*=albedoColor.xyz; -#endif -reflectivity.rgb=mix(vec3(0.04),color,metal); -#else -#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) -reflectivity=texture2D(reflectivitySampler,vReflectivityUV); -#ifdef GAMMAREFLECTIVITYTEXTURE -reflectivity.rgb=toLinearSpace(reflectivity.rgb); -#endif -#else -#ifdef REFLECTIVITYCOLOR -reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; -#endif -#endif -#ifdef GLOSSINESSS -reflectivity.a*=glossiness; -#endif -#endif -gl_FragData[REFLECTIVITY_INDEX]=reflectivity; -#endif -} -`;no.v.ShadersStore.geometryPixelShader=gU,no.v.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";let gV=`#include<sceneUboDeclaration> -`;no.v.IncludesShadersStore.geometryUboDeclaration=gV;let gk=`precision highp float; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<instancesDeclaration> -#include<__decl__geometryVertex> -#include<clipPlaneVertexDeclaration> -attribute vec3 position;attribute vec3 normal; -#ifdef NEED_UV -varying vec2 vUV; -#ifdef ALPHATEST -uniform mat4 diffuseMatrix; -#endif -#ifdef BUMP -uniform mat4 bumpMatrix;varying vec2 vBumpUV; -#endif -#ifdef REFLECTIVITY -uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#ifdef BUMP -varying mat4 vWorldView; -#endif -#ifdef BUMP -varying vec3 vNormalW; -#else -varying vec3 vNormalV; -#endif -varying vec4 vViewPos; -#if defined(POSITION) || defined(BUMP) -varying vec3 vPositionW; -#endif -#ifdef VELOCITY -uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position;vec3 normalUpdated=normal; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); -#ifdef BUMP -vWorldView=view*finalWorld;vNormalW=normalUpdated; -#else -vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); -#endif -vViewPos=view*worldPos; -#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#if NUM_BONE_INFLUENCERS>0 -mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); -#else -vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#endif -#if defined(POSITION) || defined(BUMP) -vPositionW=worldPos.xyz/worldPos.w; -#endif -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#include<clipPlaneVertex> -#ifdef NEED_UV -#ifdef UV1 -#if defined(ALPHATEST) && defined(ALPHATEST_UV1) -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#else -vUV=uv; -#endif -#ifdef BUMP_UV1 -vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef REFLECTIVITY_UV1 -vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef ALBEDO_UV1 -vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#endif -#ifdef UV2 -#if defined(ALPHATEST) && defined(ALPHATEST_UV2) -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#else -vUV=uv2; -#endif -#ifdef BUMP_UV2 -vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); -#endif -#ifdef REFLECTIVITY_UV2 -vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); -#endif -#ifdef ALBEDO_UV2 -vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#endif -#include<bumpVertex> -} -`;no.v.ShadersStore.geometryVertexShader=gk;let gG=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,lx.qx)(gG);class gz{_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===gz.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===gz.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===gz.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===gz.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===gz.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 gz.POSITION_TEXTURE_TYPE:return this._positionIndex;case gz.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case gz.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 rs.HE(0,0,0,0),this._clearDepthColor=new rs.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,gz._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){let i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;let r=[],s=[rQ.o.PositionKind,rQ.o.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&od.BumpTextureEnabled&&(r.push("#define BUMP"),r.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&r.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&r.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&r.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&r.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}e&&(r.push("#define NEED_UV"),n.isVerticesDataPresent(rQ.o.UVKind)&&(s.push(rQ.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(rQ.o.UV2Kind)&&(s.push(rQ.o.UV2Kind),r.push("#define UV2")))}this._linkedWithPrePass&&(r.push("#define PREPASS"),-1!==this._depthIndex&&(r.push("#define DEPTH_INDEX "+this._depthIndex),r.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(r.push("#define NORMAL_INDEX "+this._normalIndex),r.push("#define PREPASS_NORMAL"))),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),n.useBones&&n.computeBonesUsingShaders?(s.push(rQ.o.MatricesIndicesKind),s.push(rQ.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(rQ.o.MatricesIndicesExtraKind),s.push(rQ.o.MatricesWeightsExtraKind)),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");let a=n.morphTargetManager,o=0;a&&a.numInfluencers>0&&(o=a.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+o),a.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),s3.G.PrepareAttributesForMorphTargetsInfluencers(s,n,o)),t&&(r.push("#define INSTANCES"),s3.G.PushAttributesForInstances(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):r.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),(0,lx.lK)(i,this._scene,r);let l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),u=h.defines,c=r.join("\n");return u!==c&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:gG,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets"],defines:c,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:o}},l),c),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){if(this._resizeObserver){let e=this._scene.getEngine();e.onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null}this.getGBuffer().dispose()}_assignRenderTargetIndices(){let e=[],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(){let e=this._scene.getEngine(),[t,i]=this._assignRenderTargetIndices(),r=0;if(e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2),this._multiRenderTarget=new fp("gBuffer",{width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio},t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:r,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=sv.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=sv.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;let s=[!0],n=[!1],a=[!0];for(let e=1;e<t;++e)s.push(!0),a.push(!1),n.push(!0);let o=e.buildTextureLayout(s),l=e.buildTextureLayout(n),h=e.buildTextureLayout(a);this._multiRenderTarget.onClearObservable.add(e=>{e.bindAttachments(this.useSpecificClearForDepthTexture?l:o),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(h),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(o)}),this._resizeObserver=e.onResizeObservable.add(()=>{this._multiRenderTarget&&this._multiRenderTarget.resize({width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio})});let u=e=>{let t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:rr.y3.Identity(),viewProjection:r.getTransformMatrix()},t.skeleton)){let e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}let a=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;let o=s.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,o)){let h;let u=e._getDrawWrapper();if(!u)return;let c=u.effect;s.enableEffect(u),o||t._bind(e,c,n.fillMode),this._useUbo?(s3.G.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("view",r.getViewMatrix()));let d=t._instanceDataStorage;if(!d.isFrozen&&(n.backFaceCulling||null!==t.overrideMaterialSideOrientation)){let e=i._getWorldMatrixDeterminant();null===(h=t.overrideMaterialSideOrientation)&&(h=n.sideOrientation),e<0&&(h=h===sX.F.ClockWiseSideOrientation?sX.F.CounterClockWiseSideOrientation:sX.F.ClockWiseSideOrientation)}else h=d.sideOrientation;if(n._preBind(u,h),n.needAlphaTesting()){let e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}n.bumpTexture&&r.getEngine().getCaps().standardDerivatives&&od.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),(0,lx.an)(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&(c.setMatrices("mBones",t.skeleton.getTransformMatrices(t)),this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])),s3.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)),o&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,a,o,(e,t)=>{e||c.setMatrix("world",t)})}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,r)=>{if((r||0===i)&&t.subMeshes)for(let i=0;i<t.subMeshes.length;++i){let r=t.subMeshes[i],s=r.getMaterial(),n=r.getRenderingMesh();if(!s)continue;let a=n._getInstancesRenderList(r._id,!!r.getReplacementMesh()),o=e.getCaps().instancedArrays&&(null!==a.visibleInstances[r._id]||n.hasThinInstances);if(!this.isReady(r,o))return!1}return!0},this._multiRenderTarget.customRenderFunction=(t,i,r,s)=>{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),n=0;n<s.length;n++)u(s.data[n]);e.setColorWrite(!0)}for(n=0;n<t.length;n++)u(t.data[n]);for(e.setDepthWrite(!1),n=0;n<i.length;n++)u(i.data[n]);if(this.renderTransparentMeshes)for(n=0;n<r.length;n++)u(r.data[n]);e.setDepthWrite(!0)}}_copyBonesTransformationMatrices(e,t){for(let i=0;i<e.length;i++)t[i]=e[i];return t}}gz.DEPTH_TEXTURE_TYPE=0,gz.NORMAL_TEXTURE_TYPE=1,gz.POSITION_TEXTURE_TYPE=2,gz.VELOCITY_TEXTURE_TYPE=3,gz.REFLECTIVITY_TEXTURE_TYPE=4,gz._SceneComponentInitialization=e=>{throw(0,st.S)("GeometryBufferRendererSceneComponent")};class gW{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(rI.x.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),rI.x.prototype.enableGeometryBufferRenderer=function(e=1,t=15){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new gz(this,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},rI.x.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class gH{constructor(e){this.name=ss.l.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ss.l.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}gz._SceneComponentInitialization=e=>{let t=e._getComponent(ss.l.NAME_GEOMETRYBUFFERRENDERER);t||(t=new gH(e),e._addComponent(t))};let gX=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; -#ifdef OBJECT_BASED -uniform sampler2D velocitySampler; -#else -uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#ifdef GEOMETRY_SUPPORTED -#ifdef OBJECT_BASED -vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) -{if (i>=samplesCount) -break;vec2 offset=vUV+velocity*(hlim+float(i)); -#if defined(WEBGPU) -result+=texture2DLodEXT(textureSampler,offset,0.0); -#else -result+=texture2D(textureSampler,offset); -#endif -} -gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; -#else -vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; -vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(SAMPLES); ++i) {if (i>=nSamples) -break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); -#if defined(WEBGPU) -result+=texture2DLodEXT(textureSampler,offset1,0.0); -#else -result+=texture2D(textureSampler,offset1); -#endif -} -gl_FragColor=result/float(nSamples); -#endif -#else -gl_FragColor=texture2D(textureSampler,vUV); -#endif -} -`;no.v.ShadersStore.motionBlurPixelShader=gX;class gY extends np{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,s,n,a,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",o,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 gW)),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}let 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 ru.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=rr.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 rr.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(gz.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){let t=rr.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 rr.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(gz.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){let e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new gY(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}}(0,r0.gn)([(0,rg.qC)()],gY.prototype,"motionStrength",void 0),(0,r0.gn)([(0,rg.qC)()],gY.prototype,"motionBlurSamples",null),(0,r0.gn)([(0,rg.qC)()],gY.prototype,"isObjectBased",null),(0,rn.H)("BABYLON.MotionBlurPostProcess",gY),no.v.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";class gj extends np{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,s,n,a,o,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,a,o,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add(e=>{this._refTexture=this._refTexture||new sv(t,e.getScene())}),this.onApplyObservable.add(e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new gj(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,r0.gn)([(0,rg.qC)()],gj.prototype,"color",void 0),(0,r0.gn)([(0,rg.qC)()],gj.prototype,"depth",void 0),(0,r0.gn)([(0,rg.qC)()],gj.prototype,"colorLevel",void 0),(0,r0.gn)([(0,rg.qC)()],gj.prototype,"refractionTextureUrl",void 0),(0,rn.H)("BABYLON.RefractionPostProcess",gj);let gq=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + -texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + -texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + -texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - -color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;no.v.ShadersStore.sharpenPixelShader=gq;class gK extends np{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,s,n,null,a,void 0,null,o),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,r){return rg.p4.Parse(()=>new gK(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}(0,r0.gn)([(0,rg.qC)()],gK.prototype,"colorAmount",void 0),(0,r0.gn)([(0,rg.qC)()],gK.prototype,"edgeAmount",void 0),(0,rn.H)("BABYLON.SharpenPostProcess",gK);class g${get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=[],this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(let 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){let i=this._renderEffects[e];i&&i._enable(rZ.w1.MakeArray(t||this._cameras))}_disableEffect(e,t){let i=this._renderEffects[e];i&&i._disable(rZ.w1.MakeArray(t||this._cameras))}_attachCameras(e,t){let i;let r=rZ.w1.MakeArray(e||this._cameras);if(!r)return;let s=[];for(i=0;i<r.length;i++){let e=r[i];e&&(-1===this._cameras.indexOf(e)?this._cameras.push(e):t&&s.push(i))}for(i=0;i<s.length;i++)r.splice(s[i],1);for(let e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._attachCameras(r)}_detachCameras(e){let t=rZ.w1.MakeArray(e||this._cameras);if(t){for(let e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._detachCameras(t);for(let e=0;e<t.length;e++)this._cameras.splice(this._cameras.indexOf(t[e]),1)}}_update(){for(let e in this._renderEffects)Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&this._renderEffects[e]._update();for(let e=0;e<this._cameras.length;e++){if(!this._cameras[e])continue;let t=this._cameras[e].name;this._renderEffectsForIsolatedPass[t]&&this._renderEffectsForIsolatedPass[t]._update()}}_reset(){this._renderEffects={},this._renderEffectsForIsolatedPass=[]}_enableMSAAOnFirstPostProcess(e){if(!this._engine._features.supportMSAA)return!1;let t=Object.keys(this._renderEffects);if(t.length>0){let i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}setPrePassRenderer(e){return!1}dispose(){}}(0,r0.gn)([(0,rg.qC)()],g$.prototype,"_name",void 0);class gQ{constructor(){this._renderPipelines={}}get supportedPipelines(){let e=[];for(let t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){let 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){let r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){let i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t._rebuild()}}dispose(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.dispose()}}}Object.defineProperty(rI.x.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(ss.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new gZ(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new gQ}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class gZ{constructor(e){this.name=ss.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ss.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 gJ extends g${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(){let e=this.bloom;this.bloom=new g_(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;t<this._cameras.length;t++)e.disposeEffects(this._cameras[t])}get depthOfFieldEnabled(){return this._depthOfFieldEnabled}set depthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get depthOfFieldBlurLevel(){return this._depthOfFieldBlurLevel}set depthOfFieldBlurLevel(e){if(this._depthOfFieldBlurLevel===e)return;this._depthOfFieldBlurLevel=e;let t=this.depthOfField;this.depthOfField=new gA(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!1),this.depthOfField.focalLength=t.focalLength,this.depthOfField.focusDistance=t.focusDistance,this.depthOfField.fStop=t.fStop,this.depthOfField.lensSize=t.lensSize;for(let e=0;e<this._cameras.length;e++)t.disposeEffects(this._cameras[e]);this._buildPipeline()}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}set imageProcessingEnabled(e){this._imageProcessingEnabled!==e&&(this._scene.imageProcessingConfiguration.isEnabled=e)}get imageProcessingEnabled(){return this._imageProcessingEnabled}set glowLayerEnabled(e){e&&!this._glowLayer?this._glowLayer=new pJ("",this._scene):!e&&this._glowLayer&&(this._glowLayer.dispose(),this._glowLayer=null)}get glowLayerEnabled(){return null!=this._glowLayer}get glowLayer(){return this._glowLayer}set chromaticAberrationEnabled(e){this._chromaticAberrationEnabled!==e&&(this._chromaticAberrationEnabled=e,this._buildPipeline())}get chromaticAberrationEnabled(){return this._chromaticAberrationEnabled}set grainEnabled(e){this._grainEnabled!==e&&(this._grainEnabled=e,this._buildPipeline())}get grainEnabled(){return this._grainEnabled}constructor(e="",t=!0,i=rp.l.LastCreatedScene,r,s=!0){super(i.getEngine(),e),this._camerasToBeAttached=[],this.SharpenPostProcessId="SharpenPostProcessEffect",this.ImageProcessingPostProcessId="ImageProcessingPostProcessEffect",this.FxaaPostProcessId="FxaaPostProcessEffect",this.ChromaticAberrationPostProcessId="ChromaticAberrationPostProcessEffect",this.GrainPostProcessId="GrainPostProcessEffect",this._glowLayer=null,this.animations=[],this._imageProcessingConfigurationObserver=null,this._sharpenEnabled=!1,this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._depthOfFieldBlurLevel=i1.Low,this._fxaaEnabled=!1,this._imageProcessingEnabled=!0,this._bloomScale=.5,this._chromaticAberrationEnabled=!1,this._grainEnabled=!1,this._buildAllowed=!0,this.onBuildObservable=new ri.y$,this._resizeObserver=null,this._hardwareScaleLevel=1,this._bloomKernel=64,this._bloomWeight=.15,this._bloomThreshold=.9,this._samples=1,this._hasCleared=!1,this._prevPostProcess=null,this._prevPrevPostProcess=null,this._depthOfFieldSceneObserver=null,this._activeCameraChangedObserver=null,this._activeCamerasChangedObserver=null,this._cameras=r||i.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._buildAllowed=s,this._scene=i;let n=this._scene.getEngine().getCaps();this._hdr=t&&(n.textureHalfFloatRender||n.textureFloatRender),this._hdr?n.textureHalfFloatRender?this._defaultPipelineTextureType=2:n.textureFloatRender&&(this._defaultPipelineTextureType=1):this._defaultPipelineTextureType=0,i.postProcessRenderPipelineManager.addPipeline(this);let a=this._scene.getEngine();this.sharpen=new gK("sharpen",1,null,sv.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._sharpenEffect=new gh(a,this.SharpenPostProcessId,()=>this.sharpen,!0),this.depthOfField=new gA(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 g_(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new gm("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,sv.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new gh(a,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new gL("Grain",1,null,sv.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new gh(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,rZ.w1.SetImmediate(()=>{this._buildPipeline()}))}),this._buildPipeline()}getClassName(){return"DefaultRenderingPipeline"}prepare(){let 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;let 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(let e of this._cameras){let t=this._scene.enableDepthRenderer(e);t.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);let 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 lA("imageProcessing",1,null,sv.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new gh(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 gN("fxaa",1,null,sv.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new gh(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&&ru.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;t<this._cameras.length;t++){let i=this._cameras[t];this.imageProcessing&&this.imageProcessing.dispose(i),this.fxaa&&this.fxaa.dispose(i),e&&(this.sharpen&&this.sharpen.dispose(i),this.depthOfField&&(this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver),this.depthOfField.disposeEffects(i)),this.bloom&&this.bloom.disposeEffects(i),this.chromaticAberration&&this.chromaticAberration.dispose(i),this.grain&&this.grain.dispose(i),this._glowLayer&&this._glowLayer.dispose())}this.imageProcessing=null,this.fxaa=null,e&&(this.sharpen=null,this._sharpenEffect=null,this.depthOfField=null,this.bloom=null,this.chromaticAberration=null,this._chromaticAberrationEffect=null,this.grain=null,this._grainEffect=null,this._glowLayer=null)}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){let t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._buildAllowed=!1,this.onBuildObservable.clear(),this._disposePostProcesses(!0),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._scene._postProcessRenderPipelineManager.removePipeline(this.name),this._scene.autoClear=!0,this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver),this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver),this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver),super.dispose()}serialize(){let e=rg.p4.Serialize(this);return e.customType="DefaultRenderingPipeline",e}static Parse(e,t,i){return rg.p4.Parse(()=>new gJ(e._name,e._name._hdr,t),e,t,i)}}(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"sharpenEnabled",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"bloomKernel",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"_bloomWeight",void 0),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"_bloomThreshold",void 0),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"_hdr",void 0),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"bloomWeight",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"bloomThreshold",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"bloomScale",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"bloomEnabled",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"depthOfFieldEnabled",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"depthOfFieldBlurLevel",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"fxaaEnabled",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"samples",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"imageProcessingEnabled",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"glowLayerEnabled",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"chromaticAberrationEnabled",null),(0,r0.gn)([(0,rg.qC)()],gJ.prototype,"grainEnabled",null),(0,rn.H)("BABYLON.DefaultRenderingPipeline",gJ);let g0=`uniform sampler2D textureSampler; -uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } -else { lum_threshold=0.5+0.44*threshold; } -luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} -float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); -#ifdef PENTAGON -blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); -#else -blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); -#endif -blurred/=39.0;gl_FragColor=blurred;}`;no.v.ShadersStore.lensHighlightsPixelShader=g0;let g1=`uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; -uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; -#define PI 3.14159265 -#define TWOPI 6.28318530 -#define inverse_focal_length 0.1 -vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) -{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} -vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } -vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} -float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} -float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} -vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} -if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} -col/=total_weight; -if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} -return col;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); -vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); -float depth=texture2D(depthSampler,distorted_coords).r; -float distance=near+(far-near)*depth; -vec4 color=texture2D(textureSampler,vUV); -float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } -float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} -float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} -else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} -if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} -if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} -`;no.v.ShadersStore.depthOfFieldPixelShader=g1;class g2{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}let g3=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSAO -float scales[16]=float[16]( -0.1, -0.11406250000000001, -0.131640625, -0.15625, -0.187890625, -0.2265625, -0.272265625, -0.325, -0.384765625, -0.4515625, -0.525390625, -0.60625, -0.694140625, -0.7890625, -0.891015625, -1.0 -);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() -{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=depth/abs(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i<SAMPLES; ++i) {vec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];samplePosition=samplePosition*correctedRadius+origin;vec4 offset=vec4(samplePosition,1.0);offset=projection*offset;offset.xyz/=offset.w;offset.xy=offset.xy*0.5+0.5;if (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {continue;} -float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} -occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} -#endif -#ifdef BLUR -uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; -#ifndef BLUR_BYPASS -uniform sampler2D depthSampler; -#ifdef BLUR_LEGACY -#define inline -float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} -#endif -#endif -void main() -{float result=0.0; -#ifdef BLUR_BYPASS -result=textureLod(textureSampler,vUV,0.0).r; -#else -#ifdef BLUR_H -vec2 step=vec2(1.0/outSize,0.0); -#else -vec2 step=vec2(0.0,1.0/outSize); -#endif -#ifdef BLUR_LEGACY -result=blur13Bilateral(textureSampler,vUV,step); -#else -float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i<samples; i+=2) -{vec2 samplePos=vUV+step*(float(i)+0.5);float sampleDepth=abs(textureLod(depthSampler,samplePos,0.0).r);float falloff=smoothstep(0.0, -float(samples), -float(samples)-abs(float(i))*soften);float minDivider=tolerance*0.5+0.003;float weight=falloff/( minDivider+abs(compareDepth-sampleDepth));result+=textureLod(textureSampler,samplePos,0.0).r*weight;weightSum+=weight;} -result/=weightSum; -#endif -#endif -gl_FragColor.rgb=vec3(result);gl_FragColor.a=1.0;} -#endif -`;no.v.ShadersStore.ssao2PixelShader=g3;let g4=`uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);vec4 sceneColor=texture2D(originalColor,vUV);gl_FragColor=sceneColor*ssaoColor; -#define CUSTOM_FRAGMENT_MAIN_END -} -`;no.v.ShadersStore.ssaoCombinePixelShader=g4;class g5 extends g${set epsilon(e){this._epsilon=e,this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO())}get epsilon(){return this._epsilon}set samples(e){this._samples=e,this._ssaoPostProcess.updateEffect(this._getDefinesForSSAO()),this._sampleSphere=this._generateHemisphere()}get samples(){return this._samples}set textureSamples(e){this._textureSamples=e,this._prePassRenderer?this._prePassRenderer.samples=e:this._originalColorPostProcess.samples=e}get textureSamples(){return this._textureSamples}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}set bypassBlur(e){let t=this._getDefinesForBlur(this.expensiveBlur,e),i=this._getSamplersForBlur(e);this._blurHPostProcess.updateEffect(t.h,null,i),this._blurVPostProcess.updateEffect(t.v,null,i),this._bypassBlur=e}get bypassBlur(){return this._bypassBlur}set expensiveBlur(e){let t=this._getDefinesForBlur(e,this._bypassBlur);this._blurHPostProcess.updateEffect(t.h),this._blurVPostProcess.updateEffect(t.v),this._expensiveBlur=e}get expensiveBlur(){return this._expensiveBlur}static get IsSupported(){let e=rp.l.LastCreatedEngine;return!!e&&e._features.supportSSAO2}get scene(){return this._scene}constructor(e,t,i,r,s=!1,n=0){if(super(t.getEngine(),e),this.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",this.SSAORenderEffect="SSAORenderEffect",this.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",this.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",this.SSAOCombineRenderEffect="SSAOCombineRenderEffect",this.totalStrength=1,this.maxZ=100,this.minZAspect=.2,this._epsilon=.02,this._samples=8,this._textureSamples=1,this._forceGeometryBuffer=!1,this.radius=2,this.base=0,this._bypassBlur=!1,this._expensiveBlur=!0,this.bilateralSamples=16,this.bilateralSoften=0,this.bilateralTolerance=0,this._bits=new Uint32Array(1),this._scene=t,this._ratio=i,this._textureType=n,this._forceGeometryBuffer=s,!this.isSupported){ru.Y.Error("The current engine does not support SSAO 2.");return}let a=this._ratio.ssaoRatio||i,o=this._ratio.blurRatio||i;this._forceGeometryBuffer?t.enableGeometryBufferRenderer():t.enablePrePassRenderer(),this._createRandomTexture(),this._originalColorPostProcess=new az("SSAOOriginalSceneColor",1,null,sv.BILINEAR_SAMPLINGMODE,t.getEngine(),void 0,this._textureType),this._originalColorPostProcess.samples=this.textureSamples,this._createSSAOPostProcess(1,n),this._createBlurPostProcess(a,o,this._textureType),this._createSSAOCombinePostProcess(o,this._textureType),this.addEffect(new gh(t.getEngine(),this.SSAOOriginalSceneColorEffect,()=>this._originalColorPostProcess,!0)),this.addEffect(new gh(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new gh(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new gh(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new gh(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e<this._scene.cameras.length;e++){let t=this._scene.cameras[e];this._originalColorPostProcess.dispose(t),this._ssaoPostProcess.dispose(t),this._blurHPostProcess.dispose(t),this._blurVPostProcess.dispose(t),this._ssaoCombinePostProcess.dispose(t)}this._randomTexture.dispose(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),super.dispose()}_rebuild(){super._rebuild()}_getSamplersForBlur(e){return e?["textureSampler"]:["textureSampler","depthSampler"]}_getDefinesForBlur(e,t){let i="#define BLUR\n";return t&&(i+="#define BLUR_BYPASS\n"),e||(i+="#define BLUR_LEGACY\n"),{h:i+"#define BLUR_H\n",v:i}}_createBlurPostProcess(e,t,i){let r=this._getDefinesForBlur(this.expensiveBlur,this.bypassBlur),s=this._getSamplersForBlur(this.bypassBlur);this._blurHPostProcess=this._createBlurFilter("BlurH",s,e,r.h,i,!0),this._blurVPostProcess=this._createBlurFilter("BlurV",s,t,r.v,i,!1)}_createBlurFilter(e,t,i,r,s,n){let a=new np(e,"ssao2",["outSize","samples","soften","tolerance"],t,i,null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,r,s);return a.onApply=e=>{if(!this._scene.activeCamera)return;let t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},a.samples=this.textureSamples,a}_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,23283064365386963e-26*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){let i=2*t*Math.PI,r=1-.85*e,s=Math.sqrt(1-r*r);return new rr.P(Math.cos(i)*s,Math.sin(i)*s,r)}_generateHemisphere(){let e;let t=this.samples,i=[],r=0;for(;r<t;){if(t<16)e=this._hemisphereSample_uniform(Math.random(),Math.random());else{let i=this._hammersley(r,t);e=this._hemisphereSample_uniform(i[0],i[1])}i.push(e.x,e.y,e.z),r++}return i}_getDefinesForSSAO(){let e=`#define SSAO -#define SAMPLES ${this.samples} -#define EPSILON ${this.epsilon.toFixed(4)}`;return e}_createSSAOPostProcess(e,t){this._sampleSphere=this._generateHemisphere();let i=this._getDefinesForSSAO();this._ssaoPostProcess=new np("ssao2","ssao2",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","base","range","projection","near","texelSize","xViewport","yViewport","maxZ","minZAspect","depthProjection"],["randomSampler","depthSampler","normalSampler"],e,null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i,t),this._ssaoPostProcess.onApply=e=>{var t,i,r,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===r4.V.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",g5.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{let n=this._scene.getEngine().getRenderWidth()/2,a=this._scene.getEngine().getRenderHeight()/2,o=null!==(t=this._scene.activeCamera.orthoLeft)&&void 0!==t?t:-n,l=null!==(i=this._scene.activeCamera.orthoRight)&&void 0!==i?i:n,h=null!==(r=this._scene.activeCamera.orthoBottom)&&void 0!==r?r:-a,u=null!==(s=this._scene.activeCamera.orthoTop)&&void 0!==s?s:a;e.setMatrix3x3("depthProjection",g5.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",(l-o)*.5),e.setFloat("yViewport",(u-h)*.5)}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 g2)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new np("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{let t=this._scene.activeCamera.viewport;e.setVector4("viewport",rr.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 lb("SSAORandomTexture",128,this._scene,!1,sv.BILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=sv.WRAP_ADDRESSMODE,this._randomTexture.wrapV=sv.WRAP_ADDRESSMODE;let e=this._randomTexture.getContext(),t=(e,t)=>Math.random()*(t-e)+e,i=rr.P.Zero();for(let r=0;r<128;r++)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(r,s,1,1);this._randomTexture.update(!1)}serialize(){let e=rg.p4.Serialize(this);return e.customType="SSAO2RenderingPipeline",e}static Parse(e,t,i){return rg.p4.Parse(()=>new g5(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}g5.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],g5.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],(0,r0.gn)([(0,rg.qC)()],g5.prototype,"totalStrength",void 0),(0,r0.gn)([(0,rg.qC)()],g5.prototype,"maxZ",void 0),(0,r0.gn)([(0,rg.qC)()],g5.prototype,"minZAspect",void 0),(0,r0.gn)([(0,rg.qC)("epsilon")],g5.prototype,"_epsilon",void 0),(0,r0.gn)([(0,rg.qC)("samples")],g5.prototype,"_samples",void 0),(0,r0.gn)([(0,rg.qC)("textureSamples")],g5.prototype,"_textureSamples",void 0),(0,r0.gn)([(0,rg.qC)()],g5.prototype,"_forceGeometryBuffer",void 0),(0,r0.gn)([(0,rg.qC)()],g5.prototype,"_ratio",void 0),(0,r0.gn)([(0,rg.qC)()],g5.prototype,"_textureType",void 0),(0,r0.gn)([(0,rg.qC)()],g5.prototype,"radius",void 0),(0,r0.gn)([(0,rg.qC)()],g5.prototype,"base",void 0),(0,r0.gn)([(0,rg.qC)("bypassBlur")],g5.prototype,"_bypassBlur",void 0),(0,r0.gn)([(0,rg.qC)("expensiveBlur")],g5.prototype,"_expensiveBlur",void 0),(0,r0.gn)([(0,rg.qC)()],g5.prototype,"bilateralSamples",void 0),(0,r0.gn)([(0,rg.qC)()],g5.prototype,"bilateralSoften",void 0),(0,r0.gn)([(0,rg.qC)()],g5.prototype,"bilateralTolerance",void 0),(0,rn.H)("BABYLON.SSAO2RenderingPipeline",g5);let g6=`uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSAO -uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) -{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} -void main() -{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; i<SAMPLES; i++) -{ray=radiusDepth*reflect(sampleSphere[i],random);hemiRay=position+sign(dot(ray,normal))*ray;occlusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;difference=depth-occlusionDepth;occlusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));} -float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor.r=result;gl_FragColor.g=result;gl_FragColor.b=result;gl_FragColor.a=1.0;} -#endif -`;no.v.ShadersStore.ssaoPixelShader=g6;class g8 extends g${get scene(){return this._scene}constructor(e,t,i,r){super(t.getEngine(),e),this.SSAOOriginalSceneColorEffect="SSAOOriginalSceneColorEffect",this.SSAORenderEffect="SSAORenderEffect",this.SSAOBlurHRenderEffect="SSAOBlurHRenderEffect",this.SSAOBlurVRenderEffect="SSAOBlurVRenderEffect",this.SSAOCombineRenderEffect="SSAOCombineRenderEffect",this.totalStrength=1,this.radius=1e-4,this.area=.0075,this.fallOff=1e-6,this.base=.5,this._firstUpdate=!0,this._scene=t,this._createRandomTexture();let s=i.ssaoRatio||i,n=i.combineRatio||i;this._originalColorPostProcess=new az("SSAOOriginalSceneColor",n,null,sv.BILINEAR_SAMPLINGMODE,t.getEngine(),!1),this._createSSAOPostProcess(s),this._createBlurPostProcess(s),this._createSSAOCombinePostProcess(n),this.addEffect(new gh(t.getEngine(),this.SSAOOriginalSceneColorEffect,()=>this._originalColorPostProcess,!0)),this.addEffect(new gh(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new gh(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new gh(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new gh(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){for(let i of(super._attachCameras(e,t),this._cameras))this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e<this._scene.cameras.length;e++){let t=this._scene.cameras[e];this._originalColorPostProcess.dispose(t),this._ssaoPostProcess.dispose(t),this._blurHPostProcess.dispose(t),this._blurVPostProcess.dispose(t),this._ssaoCombinePostProcess.dispose(t)}this._randomTexture.dispose(),e&&this._scene.disableDepthRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),super.dispose()}_createBlurPostProcess(e){this._blurHPostProcess=new dr("BlurH",new rr.FM(1,0),16,e,null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,0),this._blurVPostProcess=new dr("BlurV",new rr.FM(0,1),16,e,null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,0),this._blurHPostProcess.onActivateObservable.add(()=>{let e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e}),this._blurVPostProcess.onActivateObservable.add(()=>{let e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e})}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){let 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 np("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,sv.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 np("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,sv.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",rr.jp.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){this._randomTexture=new lb("SSAORandomTexture",512,this._scene,!1,sv.TRILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=sv.WRAP_ADDRESSMODE,this._randomTexture.wrapV=sv.WRAP_ADDRESSMODE;let e=this._randomTexture.getContext(),t=(e,t)=>Math.random()*(t-e)+e,i=rr.P.Zero();for(let r=0;r<512;r++)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(r,s,1,1);this._randomTexture.update(!1)}}(0,r0.gn)([(0,rg.qC)()],g8.prototype,"totalStrength",void 0),(0,r0.gn)([(0,rg.qC)()],g8.prototype,"radius",void 0),(0,r0.gn)([(0,rg.qC)()],g8.prototype,"area",void 0),(0,r0.gn)([(0,rg.qC)()],g8.prototype,"fallOff",void 0),(0,r0.gn)([(0,rg.qC)()],g8.prototype,"base",void 0);class g7{constructor(){this.enabled=!1,this.name="screenSpaceReflections",this.texturesRequired=[6,3,1]}}let g9=`uniform sampler2D textureSampler; -#ifdef SSR_SUPPORTED -uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D positionSampler; -#endif -uniform mat4 view;uniform mat4 projection;uniform float stepSize;uniform float strength;uniform float threshold;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;varying vec2 vUV; -#ifdef SSR_SUPPORTED -struct ReflectionInfo {vec3 color;vec4 coords;};/** -* According to specular,see https: -*/ -vec3 fresnelSchlick(float cosTheta,vec3 F0) -{return F0+(1.0-F0)*pow(1.0-cosTheta,5.0);} -/** -* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit -* by sampling multiple reflection pixels. -*/ -ReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord) -{ReflectionInfo info;info.color=vec3(0.0);vec4 projectedCoord;float sampledDepth;for(int i=0; i<SMOOTH_STEPS; i++) -{projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z;dir*=0.5;if(depth>0.0) -hitCoord-=dir;else -hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} -projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} -/** -* Tests the given world position (hitCoord) according to the given reflection vector (dir) -* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). -*/ -ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) -{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i<REFLECTION_SAMPLES; i++) -{hitCoord+=dir;projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);sampledDepth=(view*texture2D(positionSampler,projectedCoord.xy)).z;float depth=sampledDepth-hitCoord.z; -#ifdef RIGHT_HANDED_SCENE -depth*=-1.0; -#endif -if(((depth-dir.z)<threshold) && depth<=0.0) -{ -#ifdef ENABLE_SMOOTH_REFLECTIONS -return smoothReflectionInfo(dir,hitCoord); -#else -info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info; -#endif -}} -info.color=texture2D(textureSampler,projectedCoord.xy).rgb;info.coords=vec4(projectedCoord.xy,sampledDepth,0.0);return info;} -vec3 hash(vec3 a) -{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} -#endif -void main() -{ -#ifdef SSR_SUPPORTED -vec4 albedoFull=texture2D(textureSampler,vUV);vec3 albedo=albedoFull.rgb;float spec=texture2D(reflectivitySampler,vUV).r;if (spec==0.0) {gl_FragColor=albedoFull;return;} -vec3 normal=(texture2D(normalSampler,vUV)).xyz;vec3 position=(view*texture2D(positionSampler,vUV)).xyz;vec3 reflected=normalize(reflect(normalize(position),normalize(normal)));float roughness=1.0-texture2D(reflectivitySampler,vUV).a;vec3 jitt=mix(vec3(0.0),hash(position),roughness)*roughnessFactor;ReflectionInfo info=getReflectionInfo(jitt+reflected,position);vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-info.coords.xy));float screenEdgefactor=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);vec3 F0=vec3(0.04);F0 =mix(F0,albedo,spec);vec3 fresnel=fresnelSchlick(max(dot(normalize(normal),normalize(position)),0.0),F0); -#ifdef RIGHT_HANDED_SCENE -reflected.z*=-1.0; -#endif -float reflectionMultiplier=clamp(pow(spec*strength,reflectionSpecularFalloffExponent)*screenEdgefactor*reflected.z,0.0,0.9);float albedoMultiplier=1.0-reflectionMultiplier;vec3 SSR=info.color*fresnel;gl_FragColor=vec4((albedo*albedoMultiplier)+(SSR*reflectionMultiplier),albedoFull.a); -#else -gl_FragColor=texture2D(textureSampler,vUV); -#endif -} -`;no.v.ShadersStore.screenSpaceReflectionPixelShader=g9;class ve extends np{get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"ScreenSpaceReflectionPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1,h=!1){if(super(e,"screenSpaceReflection",["projection","view","threshold","reflectionSpecularFalloffExponent","strength","stepSize","roughnessFactor"],["textureSampler","normalSampler","positionSampler","reflectivitySampler"],i,r,s,n,a,"#define SSR_SUPPORTED\n#define REFLECTION_SAMPLES 64\n#define SMOOTH_STEPS 5\n",o,void 0,null,l),this.threshold=1.2,this.strength=1,this.reflectionSpecularFalloffExponent=3,this.step=1,this.roughnessFactor=.2,this._forceGeometryBuffer=!1,this._enableSmoothReflections=!1,this._reflectionSamples=64,this._smoothSteps=5,this._forceGeometryBuffer=h,this._forceGeometryBuffer){let e=t.enableGeometryBufferRenderer();e&&e.isSupported&&(e.enablePosition=!0,e.enableReflectivity=!0)}else{let e=t.enablePrePassRenderer();null==e||e.markAsDirty(),this._prePassEffectConfiguration=new g7}this._updateEffectDefines(),this.onApply=e=>{let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(!r&&!i)return;if(i){let t=i.getTextureIndex(gz.POSITION_TEXTURE_TYPE),r=i.getTextureIndex(gz.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[r])}else if(r){let t=r.getIndex(1),i=r.getIndex(3),s=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[s]),e.setTexture("positionSampler",r.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",r.getRenderTarget().textures[i])}let s=t.activeCamera;if(!s)return;let n=s.getViewMatrix(!0),a=s.getProjectionMatrix(!0);e.setMatrix("projection",a),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){let 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,r){return rg.p4.Parse(()=>new ve(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}(0,r0.gn)([(0,rg.qC)()],ve.prototype,"threshold",void 0),(0,r0.gn)([(0,rg.qC)()],ve.prototype,"strength",void 0),(0,r0.gn)([(0,rg.qC)()],ve.prototype,"reflectionSpecularFalloffExponent",void 0),(0,r0.gn)([(0,rg.qC)()],ve.prototype,"step",void 0),(0,r0.gn)([(0,rg.qC)()],ve.prototype,"roughnessFactor",void 0),(0,r0.gn)([(0,rg.qC)()],ve.prototype,"enableSmoothReflections",null),(0,r0.gn)([(0,rg.qC)()],ve.prototype,"reflectionSamples",null),(0,r0.gn)([(0,rg.qC)()],ve.prototype,"smoothSteps",null),(0,rn.H)("BABYLON.ScreenSpaceReflectionPostProcess",ve);let vt=`uniform sampler2D textureSampler;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -#if defined(PASS_POST_PROCESS) -void main(void) -{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} -#endif -#if defined(DOWN_SAMPLE_X4) -uniform vec2 dsOffsets[16];void main(void) -{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} -#endif -#if defined(BRIGHT_PASS) -uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) -{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminance<brightThreshold) {average=vec4(0.0,0.0,0.0,1.0);} -gl_FragColor=average;} -#endif -#if defined(TEXTURE_ADDER) -uniform sampler2D otherSampler;uniform sampler2D lensSampler;uniform float exposure;void main(void) -{vec3 colour=texture2D(textureSampler,vUV).rgb;colour*=exposure;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;colour+=colour*texture2D(lensSampler,vUV).rgb;vec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);gl_FragColor=finalColor;} -#endif -#if defined(VLS) -#define PI 3.1415926535897932384626433832795 -uniform mat4 shadowViewProjection;uniform mat4 lightWorld;uniform vec3 cameraPosition;uniform vec3 sunDirection;uniform vec3 sunColor;uniform vec2 depthValues;uniform float scatteringCoefficient;uniform float scatteringPower;uniform sampler2D shadowMapSampler;uniform sampler2D positionSampler;float computeScattering(float lightDotView) -{float result=1.0-scatteringCoefficient*scatteringCoefficient;result/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));return result;} -void main(void) -{vec3 worldPos=texture2D(positionSampler,vUV).rgb;vec3 startPosition=cameraPosition;vec3 rayVector=worldPos-startPosition;float rayLength=length(rayVector);vec3 rayDirection=rayVector/rayLength;float stepLength=rayLength/NB_STEPS;vec3 stepL=rayDirection*stepLength;vec3 currentPosition=startPosition;vec3 accumFog=vec3(0.0);for (int i=0; i<int(NB_STEPS); i++) -{vec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);float depthMetric= (worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);float shadowPixelDepth=clamp(depthMetric,0.0,1.0);worldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;worldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);float shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;if (shadowMapValue>shadowPixelDepth) -accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} -accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} -#endif -#if defined(VLSMERGE) -uniform sampler2D originalSampler;void main(void) -{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} -#endif -#if defined(LUMINANCE) -uniform vec2 lumOffsets[4];void main() -{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) -{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); -#ifdef WEIGHTED_AVERAGE -float GreyValue=dot(color.rgb,weight); -#endif -#ifdef BRIGHTNESS -float GreyValue=max(color.r,max(color.g,color.b)); -#endif -#ifdef HSL_COMPONENT -float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); -#endif -#ifdef MAGNITUDE -float GreyValue=length(color.rgb); -#endif -maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} -average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} -#endif -#if defined(LUMINANCE_DOWN_SAMPLE) -uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; -#ifdef FINAL_DOWN_SAMPLER -#include<packingFunctions> -#endif -void main() -{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) -{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} -average/=9.0; -#ifdef FINAL_DOWN_SAMPLER -gl_FragColor=pack(average); -#else -gl_FragColor=vec4(average,average,0.0,1.0); -#endif -} -#endif -#if defined(HDR) -uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() -{vec4 color=texture2D(textureAdderSampler,vUV); -#ifndef AUTO_EXPOSURE -vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; -#endif -gl_FragColor=color;} -#endif -#if defined(LENS_FLARE) -#define GHOSTS 3 -uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) -{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} -float noise(in vec2 p) -{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), -hash(i+vec2(1.0,0.0)),u.x), -mix(hash(i+vec2(0.0,1.0)), -hash(i+vec2(1.0,1.0)),u.x),u.y);} -float fbm(vec2 p) -{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} -vec3 pattern(vec2 uv) -{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} -float luminance(vec3 color) -{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} -vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) -{return vec4( -texture2D(tex,texcoord+direction*distortion.r).r, -texture2D(tex,texcoord+direction*distortion.g).g, -texture2D(tex,texcoord+direction*distortion.b).b, -1.0 -);} -void main(void) -{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i<GHOSTS; ++i) -{vec2 offset=fract(uv+ghostDir*ghostIndice);float weight=length(vec2(0.5)-offset)/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;ghostIndice+=1.0;} -vec2 haloVec=normalize(ghostDir)*haloWidth;float weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));weight=pow(1.0-weight,10.0);result+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;result*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));gl_FragColor=result;} -#endif -#if defined(LENS_FLARE_COMPOSE) -uniform sampler2D otherSampler;uniform sampler2D lensDirtSampler;uniform sampler2D lensStarSampler;uniform mat4 lensStarMatrix;void main(void) -{vec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;vec4 lensMod=texture2D(lensDirtSampler,vUV);lensMod+=texture2D(lensStarSampler,vUV/*lensFlareCoords*/);vec4 result=texture2D(textureSampler,vUV)*lensMod;gl_FragColor=texture2D(otherSampler,vUV)+result;} -#endif -#if defined(DEPTH_OF_FIELD) -uniform sampler2D otherSampler;uniform sampler2D depthSampler;uniform float distance;void main(void) -{vec4 sharp=texture2D(otherSampler,vUV);vec4 blur=texture2D(textureSampler,vUV);float dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);float factor=0.0;if (dist<0.05) -factor=1.0;else if (dist<0.1) -factor=20.0*(0.1-dist);else if (dist<0.5) -factor=0.0;else -factor=2.0*(dist-0.5);factor=clamp(factor,0.0,0.90);gl_FragColor=mix(sharp,blur,factor);} -#endif -#if defined(MOTION_BLUR) -uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform vec2 screenSize;uniform float motionScale;uniform float motionStrength;uniform sampler2D depthSampler;void main(void) -{vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=cpos*inverseViewProjection;vec4 ppos=cpos*prevViewProjection;ppos.xyz/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {if (i>=nSamples) -break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} -gl_FragColor=result/float(nSamples);} -#endif -`;no.v.ShadersStore.standardPixelShader=vt;class vi extends g${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){let 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){let 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){let e=this._scene.enableGeometryBufferRenderer();if(!e){ru.Y.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");return}}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){let 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 ve("HDRPass",t,e,null,sv.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new gh(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new np("HDRPass","standard",[],[],e,null,sv.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 gh(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 np("HDRDepthOfFieldSource","standard",[],[],e,null,sv.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new gh(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new np("HDRVLSFinal","standard",[],[],e,null,sv.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new gh(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new np("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,sv.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new gh(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new np("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,sv.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new gh(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 gN("fxaa",1,null,sv.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new gh(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&ru.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){let i=Array(32);this.downSampleX4PostProcess=new np("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0,r=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/r),i[t+1]=(n+.5)*(1/s),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new gh(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){let i=Array(8);this.brightPassPostProcess=new np("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{let t=1/this.brightPassPostProcess.width,r=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*r,i[2]=.5*t,i[3]=.5*r,i[4]=-.5*t,i[5]=-.5*r,i[6]=.5*t,i[7]=-.5*r,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new gh(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){let s=e.getEngine(),n=new dr("HDRBlurH_"+i,new rr.FM(1,0),this[r],t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),a=new dr("HDRBlurV_"+i,new rr.FM(0,1),this[r],t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add(()=>{let e=n.width/s.getRenderWidth();n.kernel=this[r]*e}),a.onActivateObservable.add(()=>{let e=a.height/s.getRenderHeight();a.kernel=this.horizontalBlur?64*e:this[r]*e}),this.addEffect(new gh(e.getEngine(),"HDRBlurH"+i,()=>n,!0)),this.addEffect(new gh(e.getEngine(),"HDRBlurV"+i,()=>a,!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(a)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new np("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,sv.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 gh(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){let i=e.enableGeometryBufferRenderer();i.enablePosition=!0;let r=i.getGBuffer();this.volumetricLightPostProcess=new np("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));let s=rr.FM.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){let t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new gh(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new np("HDRVLSMerge","standard",[],["originalSampler"],t,null,sv.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 gh(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,vi.LuminanceSteps);this.luminancePostProcess=new np("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);let r=[];this.luminancePostProcess.onApply=e=>{let t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;r[0]=-.5*t,r[1]=.5*i,r[2]=.5*t,r[3]=.5*i,r[4]=-.5*t,r[5]=-.5*i,r[6]=.5*t,r[7]=-.5*i,e.setArray2("lumOffsets",r)},this.addEffect(new gh(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let r=vi.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let s="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(s+="#define FINAL_DOWN_SAMPLER");let n=new np("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,t);this.luminanceDownSamplePostProcesses.push(n)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((t,i)=>{let r=Array(18);t.onApply=e=>{if(!s)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)r[n]=e/s.width,r[n+1]=t/s.height,n+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{let t=e.getEngine().readPixels(0,0,1,1),i=new rr.Lt(6030862941101084e-23,1/65025,1/255,1);t.then(e=>{let 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 gh(e.getEngine(),"HDRLuminanceDownSample"+i,()=>t,!0))})}_createHdrPostProcess(e,t){let i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new np("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let r=1,s=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{let e=(n-s)/1e3;this._hdrCurrentLuminance<r+this.hdrDecreaseRate*e?r+=this.hdrDecreaseRate*e:this._hdrCurrentLuminance>r-this.hdrIncreaseRate*e?r-=this.hdrIncreaseRate*e:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=rm.R.Clamp(r,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),n=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new gh(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new np("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new gh(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new np("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new gh(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));let i=new rr.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)};let r=rr.y3.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=rr.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);let t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2),n=rr.P.Dot(t.toVector3(),new rr.P(1,0,0))+rr.P.Dot(i.toVector3(),new rr.P(0,0,1));n*=4;let a=rr.y3.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),o=s.multiply(a).multiply(r);e.setMatrix("lensStarMatrix",o),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new np("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,sv.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 gh(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){let i=new gY("HDRMotionBlur",e,t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new np("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,sv.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,r=rr.y3.Identity(),s=rr.y3.Identity(),n=rr.y3.Identity(),a=rr.FM.Zero();this.motionBlurPostProcess.onApply=t=>{(n=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",r),r=n,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 gh(e.getEngine(),"HDRMotionBlur",()=>this.motionBlurPostProcess,!0))}_getDepthTexture(){if(this._scene.getEngine().getCaps().drawBuffersExtension){let e=this._scene.enableGeometryBufferRenderer();return e.getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;e<this._cameras.length;e++){let t=this._cameras[e];this.originalPostProcess&&this.originalPostProcess.dispose(t),this.screenSpaceReflectionPostProcess&&this.screenSpaceReflectionPostProcess.dispose(t),this.downSampleX4PostProcess&&this.downSampleX4PostProcess.dispose(t),this.brightPassPostProcess&&this.brightPassPostProcess.dispose(t),this.textureAdderPostProcess&&this.textureAdderPostProcess.dispose(t),this.volumetricLightPostProcess&&this.volumetricLightPostProcess.dispose(t),this.volumetricLightSmoothXPostProcess&&this.volumetricLightSmoothXPostProcess.dispose(t),this.volumetricLightSmoothYPostProcess&&this.volumetricLightSmoothYPostProcess.dispose(t),this.volumetricLightMergePostProces&&this.volumetricLightMergePostProces.dispose(t),this.volumetricLightFinalPostProcess&&this.volumetricLightFinalPostProcess.dispose(t),this.lensFlarePostProcess&&this.lensFlarePostProcess.dispose(t),this.lensFlareComposePostProcess&&this.lensFlareComposePostProcess.dispose(t);for(let e=0;e<this.luminanceDownSamplePostProcesses.length;e++)this.luminanceDownSamplePostProcesses[e].dispose(t);this.luminancePostProcess&&this.luminancePostProcess.dispose(t),this.hdrPostProcess&&this.hdrPostProcess.dispose(t),this.hdrFinalPostProcess&&this.hdrFinalPostProcess.dispose(t),this.depthOfFieldPostProcess&&this.depthOfFieldPostProcess.dispose(t),this.motionBlurPostProcess&&this.motionBlurPostProcess.dispose(t),this.fxaaPostProcess&&this.fxaaPostProcess.dispose(t);for(let e=0;e<this.blurHPostProcesses.length;e++)this.blurHPostProcesses[e].dispose(t);for(let e=0;e<this.blurVPostProcesses.length;e++)this.blurVPostProcesses[e].dispose(t)}this.originalPostProcess=null,this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.textureAdderPostProcess=null,this.textureAdderFinalPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.luminancePostProcess=null,this.hdrPostProcess=null,this.hdrFinalPostProcess=null,this.depthOfFieldPostProcess=null,this.motionBlurPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.luminanceDownSamplePostProcesses.length=0,this.blurHPostProcesses.length=0,this.blurVPostProcesses.length=0}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}serialize(){let e=rg.p4.Serialize(this);return this.sourceLight&&(e.sourceLightId=this.sourceLight.id),this.screenSpaceReflectionPostProcess&&(e.screenSpaceReflectionPostProcess=rg.p4.Serialize(this.screenSpaceReflectionPostProcess)),e.customType="StandardRenderingPipeline",e}static Parse(e,t,i){let r=rg.p4.Parse(()=>new vi(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&rg.p4.Parse(()=>r.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),r}}vi.LuminanceSteps=6,(0,r0.gn)([(0,rg.qC)()],vi.prototype,"brightThreshold",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"blurWidth",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"horizontalBlur",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"exposure",null),(0,r0.gn)([(0,rg.oU)("lensTexture")],vi.prototype,"lensTexture",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"volumetricLightCoefficient",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"volumetricLightPower",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"volumetricLightBlurScale",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"hdrMinimumLuminance",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"hdrDecreaseRate",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"hdrIncreaseRate",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"hdrAutoExposure",null),(0,r0.gn)([(0,rg.oU)("lensColorTexture")],vi.prototype,"lensColorTexture",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"lensFlareStrength",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"lensFlareGhostDispersal",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"lensFlareHaloWidth",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"lensFlareDistortionStrength",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"lensFlareBlurWidth",void 0),(0,r0.gn)([(0,rg.oU)("lensStarTexture")],vi.prototype,"lensStarTexture",void 0),(0,r0.gn)([(0,rg.oU)("lensFlareDirtTexture")],vi.prototype,"lensFlareDirtTexture",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"depthOfFieldDistance",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"depthOfFieldBlurWidth",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"motionStrength",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"objectBasedMotionBlur",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"_ratio",void 0),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"BloomEnabled",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"DepthOfFieldEnabled",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"LensFlareEnabled",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"HDREnabled",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"VLSEnabled",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"MotionBlurEnabled",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"fxaaEnabled",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"screenSpaceReflectionsEnabled",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"volumetricLightStepsCount",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"motionBlurSamples",null),(0,r0.gn)([(0,rg.qC)()],vi.prototype,"samples",null),(0,rn.H)("BABYLON.StandardRenderingPipeline",vi);class vr{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}let vs=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } -/** -param csOrigin Camera-space ray origin,which must be -within the view volume and must have z>0.01 and project within the valid screen rectangle -param csDirection Unit length camera-space ray direction -param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates -(**not** [-1,+1] normalized device coordinates). -param csZBuffer The camera-space Z buffer -param csZBufferSize Dimensions of csZBuffer -param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer -param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value -for clipping rays headed towards the camera -param stride Step in horizontal or vertical pixels between samples. This is a float -because integer math is slow on GPUs,but should be set to an integer>=1 -param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units -to conceal banding artifacts,plus the stride ray offset. -param maxSteps Maximum number of iterations. Higher gives better images but may be slow -param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss -param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. -1 is a reasonable value,depending on the scene you may need to set this value to 2 -param hitPixel Pixel coordinates of the first intersection with the scene -param numIterations number of iterations performed -param csHitPoint Camera space location of the ray hit -*/ -#define inline -bool traceScreenSpaceRay1( -vec3 csOrigin, -vec3 csDirection, -mat4 projectToPixelMatrix, -sampler2D csZBuffer, -vec2 csZBufferSize, -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -sampler2D csZBackBuffer, -float csZBackSizeFactor, -#endif -float csZThickness, -float nearPlaneZ, -float stride, -float jitterFraction, -float maxSteps, -float maxRayTraceDistance, -float selfCollisionNumSkip, -out vec2 startPixel, -out vec2 hitPixel, -out vec3 csHitPoint, -out float numIterations -#ifdef SSRAYTRACE_DEBUG -,out vec3 debugColor -#endif -) -{ -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; -#else -float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)<nearPlaneZ ? (nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; -#endif -vec3 csEndPoint=csOrigin+csDirection*rayLength;hitPixel=vec2(-1.0,-1.0);vec4 H0=projectToPixelMatrix*vec4(csOrigin,1.0);vec4 H1=projectToPixelMatrix*vec4(csEndPoint,1.0);float k0=1.0/H0.w;float k1=1.0/H1.w;vec3 Q0=csOrigin*k0;vec3 Q1=csEndPoint*k1;vec2 P0=H0.xy*k0;vec2 P1=H1.xy*k1; -#ifdef SSRAYTRACE_CLIP_TO_FRUSTUM -float xMax=csZBufferSize.x-0.5,xMin=0.5,yMax=csZBufferSize.y-0.5,yMin=0.5;float alpha=0.0;if ((P1.y>yMax) || (P1.y<yMin)) {alpha=(P1.y-((P1.y>yMax) ? yMax : yMin))/(P1.y-P0.y);} -if ((P1.x>xMax) || (P1.x<xMin)) {alpha=max(alpha,(P1.x-((P1.x>xMax) ? xMax : xMin))/(P1.x-P0.x));} -P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); -#endif -P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)<abs(delta.y)) { -permute=true;delta=delta.yx;P0=P0.yx;P1=P1.yx; } -float stepDirection=sign(delta.x);float invdx=stepDirection/delta.x;vec2 dP=vec2(stepDirection,delta.y*invdx);vec3 dQ=(Q1-Q0)*invdx;float dk=(k1-k0)*invdx;float zMin=min(csEndPoint.z,csOrigin.z);float zMax=max(csEndPoint.z,csOrigin.z);dP*=stride; dQ*=stride; dk*=stride;P0+=dP*jitterFraction; Q0+=dQ*jitterFraction; k0+=dk*jitterFraction;vec4 pqk=vec4(P0,Q0.z,k0);vec4 dPQK=vec4(dP,dQ.z,dk);startPixel=permute ? P0.yx : P0.xy;float prevZMaxEstimate=csOrigin.z;float rayZMin=prevZMaxEstimate,rayZMax=prevZMaxEstimate;float sceneZMax=rayZMax+1e4;float end=P1.x*stepDirection;bool hit=false;float stepCount;for (stepCount=0.0;stepCount<=selfCollisionNumSkip || -(pqk.x*stepDirection)<=end && -stepCount<maxSteps && -!hit && -sceneZMax != 0.0; -pqk+=dPQK,++stepCount) -{hitPixel=permute ? pqk.yx : pqk.xy;rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;if (rayZMin>rayZMax) { -float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} -sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); -#else -hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); -#endif -#else -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); -#else -hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); -#endif -#endif -} -pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} -#ifdef SSRAYTRACE_ENABLE_REFINEMENT -if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || -(refinementStepCount<=stride*1.4) && -(rayZMax<sceneZMax) && (sceneZMax != 0.0);pqk+=dPQK,refinementStepCount+=1.0) -{rayZMin=prevZMaxEstimate;rayZMax=(dPQK.z*0.5+pqk.z)/(dPQK.w*0.5+pqk.w);rayZMax=clamp(rayZMax,zMin,zMax);prevZMaxEstimate=rayZMax;rayZMax=max(rayZMax,rayZMin);hitPixel=permute ? pqk.yx : pqk.xy;sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;} -pqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;} -#endif -Q0.xy+=dQ.xy*stepCount;Q0.z=pqk.z;csHitPoint=Q0/pqk.w;numIterations=stepCount+1.0; -#ifdef SSRAYTRACE_DEBUG -if (((pqk.x+dPQK.x)*stepDirection)>end) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} -#endif -return hit;} -/** -texCoord: in the [0,1] range -depth: depth in view space (range [znear,zfar]]) -*/ -vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -ndc.z=-projection[2].z-projection[3].z/depth; -#else -ndc.z=projection[2].z+projection[3].z/depth; -#endif -ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} -`;no.v.IncludesShadersStore.screenSpaceRayTrace=vs;let vn=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSR_SUPPORTED -uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -uniform sampler2D backDepthSampler;uniform float backSizeFactor; -#endif -#ifdef SSR_USE_ENVIRONMENT_CUBE -uniform samplerCube envCubeSampler; -#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; -#include<helperFunctions> -#include<pbrBRDFFunctions> -#include<screenSpaceRayTrace> -vec3 hash(vec3 a) -{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} -float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; -#ifdef SSR_ATTENUATE_SCREEN_BORDERS -vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); -#endif -#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE -attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); -#endif -#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS -attenuation*=1.0-(numIterations/maxSteps); -#endif -#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION -vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; -#endif -return attenuation;} -#endif -void main() -{ -#ifdef SSR_SUPPORTED -vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0); -#ifndef SSR_DISABLE_REFLECTIVITY_TEST -if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { -#ifdef SSR_USE_BLUR -gl_FragColor=vec4(0.); -#else -gl_FragColor=colorFull; -#endif -return;} -#endif -#ifdef SSR_INPUT_IS_GAMMA_SPACE -color=toLinearSpace(color); -#endif -vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; -float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal); -#ifdef SSR_USE_ENVIRONMENT_CUBE -vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); -#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC -vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); -#endif -#ifdef SSR_INVERTCUBICMAP -wReflectedVector.y*=-1.0; -#endif -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -wReflectedVector.z*=-1.0; -#endif -vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; -#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE -envColor=toLinearSpace(envColor); -#endif -#else -vec3 envColor=color; -#endif -float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; -#ifdef SSRAYTRACE_DEBUG -vec3 debugColor; -#endif -#ifdef SSR_ATTENUATE_FACING_CAMERA -reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); -#endif -if (reflectionAttenuation>0.0) { -#ifdef SSR_USE_BLUR -vec3 jitt=vec3(0.); -#else -float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; -#endif -vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); -rayHasHit=traceScreenSpaceRay1( -csPosition, -normalize(csReflectedVector+jitt), -projectionPixel, -depthSampler, -texSize, -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -backDepthSampler, -backSizeFactor, -#endif -thickness, -nearPlaneZ, -stepSize, -jitter, -maxSteps, -maxDistance, -selfCollisionNumSkip, -startPixel, -hitPixel, -hitPoint, -numIterations -#ifdef SSRAYTRACE_DEBUG -,debugColor -#endif -);} -#ifdef SSRAYTRACE_DEBUG -gl_FragColor=vec4(debugColor,1.);return; -#endif -vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; -#ifdef SSR_INPUT_IS_GAMMA_SPACE -reflectedColor=toLinearSpace(reflectedColor); -#endif -reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} -#ifndef SSR_BLEND_WITH_FRESNEL -SSR*=fresnel; -#endif -#ifdef SSR_USE_BLUR -float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; -float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} -gl_FragColor=vec4(SSR,blur_radius/255.0); -#else -#ifdef SSR_BLEND_WITH_FRESNEL -vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#else -vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#endif -vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); -#ifdef SSR_OUTPUT_IS_GAMMA_SPACE -finalColor=toGammaSpace(finalColor); -#endif -gl_FragColor=vec4(finalColor,colorFull.a); -#endif -#else -gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); -#endif -} -`;no.v.ShadersStore.screenSpaceReflection2PixelShader=vn;let va=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) -{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} -void main() -{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} -float blurRadius=colorFull.a*255.0; -vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} -`;no.v.ShadersStore.screenSpaceReflection2BlurPixelShader=va;let vo=`uniform sampler2D textureSampler; -uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; -#include<helperFunctions> -#ifdef SSR_BLEND_WITH_FRESNEL -#include<pbrBRDFFunctions> -#include<screenSpaceRayTrace> -uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler; -#endif -void main() -{ -#ifdef SSRAYTRACE_DEBUG -gl_FragColor=texture2D(textureSampler,vUV); -#else -vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); -#ifndef SSR_DISABLE_REFLECTIVITY_TEST -if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} -#endif -#ifdef SSR_INPUT_IS_GAMMA_SPACE -color=toLinearSpace(color); -#endif -#ifdef SSR_BLEND_WITH_FRESNEL -vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#else -vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#endif -vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); -#ifdef SSR_OUTPUT_IS_GAMMA_SPACE -finalColor=toGammaSpace(finalColor); -#endif -gl_FragColor=vec4(finalColor,color.a); -#endif -} -`;no.v.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader=vo;let vl=rr.y3.Compose(new rr.P(.5,.5,.5),rr._f.Identity(),new rr.P(.5,.5,.5)),vh=rr.y3.Compose(new rr.P(.5,.5,1),rr._f.Identity(),new rr.P(.5,.5,0));class vu extends g${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;let 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(){let e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!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=r,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){let e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{let e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){let 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;let i=this._scene.getEngine(),r=this._prePassRenderer,s={width:i.getRenderWidth(),height:i.getRenderHeight()};if(r&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){let e=r.getRenderTarget();e&&e.textures&&(s=e.textures[r.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;let 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){this._isDirty=!0;return}this._isDirty=!1;let 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){let t=null===(e=this._cameras)||void 0===e?void 0:e[0];t&&(this._depthRendererCamera=t,this._depthRenderer=new _g(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 gh(t,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new gh(t,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new gh(t,this.SSRCombineRenderEffect,()=>this._blurCombinerPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;let e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==r)&&this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){let 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,r;for(let s=0;s<this._cameras.length;s++){let n=this._cameras[s];null===(e=this._ssrPostProcess)||void 0===e||e.dispose(n),null===(t=this._blurPostProcessX)||void 0===t||t.dispose(n),null===(i=this._blurPostProcessY)||void 0===i||i.dispose(n),null===(r=this._blurCombinerPostProcess)||void 0===r||r.dispose(n)}this._ssrPostProcess=null,this._blurPostProcessX=null,this._blurPostProcessY=null,this._blurCombinerPostProcess=null}_createSSRPostProcess(){this._ssrPostProcess=new np("ssr","screenSpaceReflection2",["projection","invProjectionMatrix","view","invView","thickness","reflectionSpecularFalloffExponent","strength","stepSize","maxSteps","roughnessFactor","projectionPixel","nearPlaneZ","maxDistance","selfCollisionNumSkip","vReflectionPosition","vReflectionSize","backSizeFactor","reflectivityThreshold"],["textureSampler","normalSampler","reflectivitySampler","depthSampler","envCubeSampler","backDepthSampler"],1,null,this._textureType,this._scene.getEngine(),!1,"",this._textureType),this._updateEffectDefines(),this._ssrPostProcess.onApply=e=>{this._resizeDepthRenderer();let t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){let i=t.getTextureIndex(gz.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){let t=i.getIndex(5),r=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[r])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));let r=this._scene.activeCamera;if(!r)return;let s=r.getViewMatrix(!0),n=r.getProjectionMatrix(!0);n.invertToRef(rr.jp.Matrix[0]),s.invertToRef(rr.jp.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",s),e.setMatrix("invView",rr.jp.Matrix[1]),e.setMatrix("invProjectionMatrix",rr.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",r.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);let a=this._getTextureSize();rr.y3.ScalingToRef(a.width,a.height,1,rr.jp.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?vh:vl,rr.jp.Matrix[3]),rr.jp.Matrix[3].multiplyToRef(rr.jp.Matrix[2],rr.jp.Matrix[4]),e.setMatrix("projectionPixel",rr.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 vr)}_createBlurAndCombinerPostProcesses(){let e=this._scene.getEngine();this._blurPostProcessX=new np("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;let r=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/r,0)}),this._blurPostProcessY=new np("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;let r=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/r)});let t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"],r="";this._debug&&(r+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(r+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(r+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(r+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(r+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new np("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,r,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(e=>{var t;let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(r||i){if(r&&(null===(t=this._scene.activeCamera)||void 0===t?void 0:t._getFirstPostProcess())===this._ssrPostProcess){let t=r.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[r.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(i){let t=i.getTextureIndex(gz.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(r){let t=r.getIndex(3);if(e.setTexture("reflectivitySampler",r.getRenderTarget().textures[t]),this.useFresnel){let t=r.getIndex(5),i=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[i]),e.setTexture("depthSampler",r.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();i.invertToRef(rr.jp.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",rr.jp.Matrix[0])}}}})}serialize(){let e=rg.p4.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return rg.p4.Parse(()=>new vu(e._name,t,e._ratio),e,t,i)}}(0,r0.gn)([(0,rg.qC)()],vu.prototype,"samples",null),(0,r0.gn)([(0,rg.qC)()],vu.prototype,"maxDistance",void 0),(0,r0.gn)([(0,rg.qC)()],vu.prototype,"step",void 0),(0,r0.gn)([(0,rg.qC)()],vu.prototype,"thickness",void 0),(0,r0.gn)([(0,rg.qC)()],vu.prototype,"strength",void 0),(0,r0.gn)([(0,rg.qC)()],vu.prototype,"reflectionSpecularFalloffExponent",void 0),(0,r0.gn)([(0,rg.qC)()],vu.prototype,"maxSteps",void 0),(0,r0.gn)([(0,rg.qC)()],vu.prototype,"roughnessFactor",void 0),(0,r0.gn)([(0,rg.qC)()],vu.prototype,"selfCollisionNumSkip",void 0),(0,r0.gn)([(0,rg.qC)()],vu.prototype,"_reflectivityThreshold",void 0),(0,r0.gn)([(0,rg.qC)("_ssrDownsample")],vu.prototype,"_ssrDownsample",void 0),(0,r0.gn)([(0,rg.qC)()],vu.prototype,"ssrDownsample",null),(0,r0.gn)([(0,rg.qC)("blurDispersionStrength")],vu.prototype,"_blurDispersionStrength",void 0),(0,r0.gn)([(0,rg.qC)("blurDownsample")],vu.prototype,"_blurDownsample",void 0),(0,r0.gn)([(0,rg.qC)("enableSmoothReflections")],vu.prototype,"_enableSmoothReflections",void 0),(0,r0.gn)([(0,rg.qC)("environmentTexture")],vu.prototype,"_environmentTexture",void 0),(0,r0.gn)([(0,rg.qC)("environmentTextureIsProbe")],vu.prototype,"_environmentTextureIsProbe",void 0),(0,r0.gn)([(0,rg.qC)("attenuateScreenBorders")],vu.prototype,"_attenuateScreenBorders",void 0),(0,r0.gn)([(0,rg.qC)("attenuateIntersectionDistance")],vu.prototype,"_attenuateIntersectionDistance",void 0),(0,r0.gn)([(0,rg.qC)("attenuateIntersectionIterations")],vu.prototype,"_attenuateIntersectionIterations",void 0),(0,r0.gn)([(0,rg.qC)("attenuateFacingCamera")],vu.prototype,"_attenuateFacingCamera",void 0),(0,r0.gn)([(0,rg.qC)("attenuateBackfaceReflection")],vu.prototype,"_attenuateBackfaceReflection",void 0),(0,r0.gn)([(0,rg.qC)("clipToFrustum")],vu.prototype,"_clipToFrustum",void 0),(0,r0.gn)([(0,rg.qC)("useFresnel")],vu.prototype,"_useFresnel",void 0),(0,r0.gn)([(0,rg.qC)("enableAutomaticThicknessComputation")],vu.prototype,"_enableAutomaticThicknessComputation",void 0),(0,r0.gn)([(0,rg.qC)("backfaceDepthTextureDownsample")],vu.prototype,"_backfaceDepthTextureDownsample",void 0),(0,r0.gn)([(0,rg.qC)("backfaceForceDepthWriteTransparentMeshes")],vu.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),(0,r0.gn)([(0,rg.qC)("isEnabled")],vu.prototype,"_isEnabled",void 0),(0,r0.gn)([(0,rg.qC)("inputTextureColorIsInGammaSpace")],vu.prototype,"_inputTextureColorIsInGammaSpace",void 0),(0,r0.gn)([(0,rg.qC)("generateOutputInGammaSpace")],vu.prototype,"_generateOutputInGammaSpace",void 0),(0,r0.gn)([(0,rg.qC)("debug")],vu.prototype,"_debug",void 0),(0,rn.H)("BABYLON.SSRRenderingPipeline",vu);let vc=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; -#if defined(HABLE_TONEMAPPING) -const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2; -#endif -float Luminance(vec3 c) -{return dot(c,vec3(0.22,0.707,0.071));} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 colour=texture2D(textureSampler,vUV).rgb; -#if defined(REINHARD_TONEMAPPING) -float lum=Luminance(colour.rgb); -float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); -colour*=scale/lum; -#elif defined(HABLE_TONEMAPPING) -colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; -#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) -colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; -#elif defined(PHOTOGRAPHIC_TONEMAPPING) -colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); -#endif -gl_FragColor=vec4(colour.rgb,1.0);}`;no.v.ShadersStore.tonemapPixelShader=vc,(e7=i2||(i2={}))[e7.Hable=0]="Hable",e7[e7.Reinhard=1]="Reinhard",e7[e7.HejiDawson=2]="HejiDawson",e7[e7.Photographic=3]="Photographic";let vd=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i<NUM_SAMPLES; i++) {tc-=deltaTexCoord;vec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;dataSample*=illuminationDecay*weight;color+=dataSample;illuminationDecay*=decay;} -vec4 realColor=texture2D(textureSampler,vUV);gl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4))); -#define CUSTOM_FRAGMENT_MAIN_END -} -`;no.v.ShadersStore.volumetricLightScatteringPixelShader=vd;let vp=`attribute vec3 position; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<instancesDeclaration> -uniform mat4 viewProjection;uniform vec2 depthValues; -#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#if defined(ALPHATEST) || defined(BASIC_RENDER) -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -} -`;no.v.ShadersStore.volumetricLightScatteringPassVertexShader=vp;let v_=`#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV; -#endif -#if defined(ALPHATEST) -uniform sampler2D diffuseSampler; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#if defined(ALPHATEST) -vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) -discard; -#endif -gl_FragColor=vec4(0.0,0.0,0.0,1.0);} -`;no.v.ShadersStore.volumetricLightScatteringPassPixelShader=v_;class vf extends np{get useDiffuseColor(){return ru.Y.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){ru.Y.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,r,s=100,n=sv.BILINEAR_SAMPLINGMODE,a,o,l){var h,u;super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,n,a,o,"#define NUM_SAMPLES "+s),this._screenCoordinates=rr.FM.Zero(),this.customMeshPosition=rr.P.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,a=(l=null!==(u=null!==(h=null==i?void 0:i.getScene())&&void 0!==h?h:l)&&void 0!==u?u:this._scene).getEngine(),this._viewPort=new s6.l(0,0,1,1).toGlobal(a.getRenderWidth(),a.getRenderHeight()),this.mesh=null!=r?r:vf.CreateDefaultMesh("VolumetricLightScatteringMesh",l),this._createPass(l,t.passRatio||t),this.onActivate=e=>{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add(e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;let r=e.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);let s=null===(i=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(r,e,t);let n=[],a=[rQ.o.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(rQ.o.UVKind)&&(a.push(rQ.o.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(rQ.o.UV2Kind)&&(a.push(rQ.o.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(a.push(rQ.o.MatricesIndicesKind),a.push(rQ.o.MatricesWeightsKind),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"),t&&(n.push("#define INSTANCES"),s3.G.PushAttributesForInstances(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));let l=e._getDrawWrapper(void 0,!0),h=l.defines,u=n.join("\n");return h!==u&&l.setEffect(r.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:r.numBoneInfluencers}),u),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){let 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){let i;let r=e.getEngine();this._volumetricLightScatteringRTT=new nV("volumetricLightScatteringMap",{width:r.getRenderWidth()*t,height:r.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=sv.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=sv.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;let s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);let n=e=>{var t;let i=e.getRenderingMesh(),r=e.getEffectiveMesh();if(this._meshExcluded(i))return;r._internalAbstractMeshDataInfo._isActiveIntermediate=!1;let s=e.getMaterial();if(!s)return;let n=i.getScene(),a=n.getEngine();a.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);let o=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;let l=a.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||i.hasThinInstances);if(this._isReady(e,l)){let h=null===(t=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[a.currentRenderPassId],u=e._getDrawWrapper();if(i!==this.mesh||u||(u=s._getDrawWrapper()),!u)return;let c=u.effect;if(a.enableEffect(u),l||i._bind(e,c,s.fillMode),i===this.mesh)s.bind(r.getWorldMatrix(),i);else if(h)h.bindForSubMesh(r.getWorldMatrix(),r,e);else{if(c.setMatrix("viewProjection",n.getTransformMatrix()),s&&s.needAlphaTesting()){let e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&c.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}l&&i.hasThinInstances&&c.setMatrix("world",r.getWorldMatrix()),i._processRendering(r,e,c,sX.F.TriangleFillMode,o,l,(e,t)=>{e||c.setMatrix("world",t)})}},a=new rs.HE(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{i=e.clearColor,e.clearColor=a}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=i}),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t<e.subMeshes.length;++t){let i=e.subMeshes[t],s=i.getMaterial(),n=i.getRenderingMesh();if(!s)continue;let a=n._getInstancesRenderList(i._id,!!i.getReplacementMesh()),o=r.getCaps().instancedArrays&&(null!==a.visibleInstances[i._id]||n.hasThinInstances);if(!this._isReady(i,o))return!1}return!0},this._volumetricLightScatteringRTT.customRenderFunction=(t,i,r,s)=>{let a;let o=e.getEngine();if(s.length){for(o.setColorWrite(!1),a=0;a<s.length;a++)n(s.data[a]);o.setColorWrite(!0)}for(a=0;a<t.length;a++)n(t.data[a]);for(a=0;a<i.length;a++)n(i.data[a]);if(r.length){for(a=0;a<r.length;a++){let t=r.data[a],i=t.getBoundingInfo();i&&e.activeCamera&&(t._alphaIndex=t.getMesh().alphaIndex,t._distanceToCamera=i.boundingSphere.centerWorld.subtract(e.activeCamera.position).length())}let t=r.data.slice(0,r.length);for(t.sort((e,t)=>e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0),o.setAlphaMode(2),a=0;a<t.length;a++)n(t[a]);o.setAlphaMode(0)}}}_updateMeshScreenCoordinates(e){let t;let i=e.getTransformMatrix();t=this.useCustomMeshPosition?this.customMeshPosition:this.attachedNode?this.attachedNode.position:this.mesh.parent?this.mesh.getAbsolutePosition():this.mesh.position;let r=rr.P.Project(t,rr.y3.Identity(),i,this._viewPort);this._screenCoordinates.x=r.x/this._viewPort.width,this._screenCoordinates.y=r.y/this._viewPort.height,this.invert&&(this._screenCoordinates.y=1-this._screenCoordinates.y)}static CreateDefaultMesh(e,t){let i=sL(e,{size:1},t);i.billboardMode=r$.x.BILLBOARDMODE_ALL;let r=new lC(e+"Material",t);return r.emissiveColor=new rs.Wo(1,1,1),i.material=r,i}}(0,r0.gn)([(0,rg.hd)()],vf.prototype,"customMeshPosition",void 0),(0,r0.gn)([(0,rg.qC)()],vf.prototype,"useCustomMeshPosition",void 0),(0,r0.gn)([(0,rg.qC)()],vf.prototype,"invert",void 0),(0,r0.gn)([(0,rg.RR)()],vf.prototype,"mesh",void 0),(0,r0.gn)([(0,rg.qC)()],vf.prototype,"excludedMeshes",void 0),(0,r0.gn)([(0,rg.qC)()],vf.prototype,"includedMeshes",void 0),(0,r0.gn)([(0,rg.qC)()],vf.prototype,"exposure",void 0),(0,r0.gn)([(0,rg.qC)()],vf.prototype,"decay",void 0),(0,r0.gn)([(0,rg.qC)()],vf.prototype,"weight",void 0),(0,r0.gn)([(0,rg.qC)()],vf.prototype,"density",void 0),(0,rn.H)("BABYLON.VolumetricLightScatteringPostProcess",vf);let vm=`precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform float curvature_ridge;uniform float curvature_valley; -#ifndef CURVATURE_OFFSET -#define CURVATURE_OFFSET 1 -#endif -float curvature_soft_clamp(float curvature,float control) -{if (curvature<0.5/control) -return curvature*(1.0-curvature*control);return 0.25/control;} -float calculate_curvature(ivec2 texel,float ridge,float valley) -{vec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;vec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;vec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;vec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;float normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));if (normal_diff<0.0) -return -2.0*curvature_soft_clamp(-normal_diff,valley);return 2.0*curvature_soft_clamp(normal_diff,ridge);} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ivec2 texel=ivec2(gl_FragCoord.xy);vec4 baseColor=texture2D(textureSampler,vUV);float curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);baseColor.rgb*=curvature+1.0;gl_FragColor=baseColor;}`;no.v.ShadersStore.screenSpaceCurvaturePixelShader=vm;class vg extends np{getClassName(){return"ScreenSpaceCurvaturePostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1){super(e,"screenSpaceCurvature",["curvature_ridge","curvature_valley"],["textureSampler","normalSampler"],i,r,s,n,a,void 0,o,void 0,null,l),this.ridge=1,this.valley=1,this._geometryBufferRenderer=t.enableGeometryBufferRenderer(),this._geometryBufferRenderer?this.onApply=e=>{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));let t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}:ru.Y.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){let e=rp.l.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,r){return rg.p4.Parse(()=>new vg(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}(0,r0.gn)([(0,rg.qC)()],vg.prototype,"ridge",void 0),(0,r0.gn)([(0,rg.qC)()],vg.prototype,"valley",void 0),(0,rn.H)("BABYLON.ScreenSpaceCurvaturePostProcess",vg);let vv=`uniform vec4 color; -`;no.v.IncludesShadersStore.boundingBoxRendererFragmentDeclaration=vv;let vT=`#ifdef WEBGL2 -uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -#else -layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; -#endif -`;no.v.IncludesShadersStore.boundingBoxRendererUboDeclaration=vT;let vx=`#include<__decl__boundingBoxRendererFragment> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;no.v.ShadersStore.boundingBoxRendererPixelShader=vx;let vS=`uniform mat4 world;uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -`;no.v.IncludesShadersStore.boundingBoxRendererVertexDeclaration=vS;let vE=`attribute vec3 position; -#include<__decl__boundingBoxRendererVertex> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec4 worldPos=world*vec4(position,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -} -`;no.v.ShadersStore.boundingBoxRendererVertexShader=vE,Object.defineProperty(rI.x.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),rI.x.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new vC(this)),this._boundingBoxRenderer},Object.defineProperty(r$.x.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class vC{constructor(e){this.name=ss.l.NAME_BOUNDINGBOXRENDERER,this.frontColor=new rs.Wo(1,1,1),this.backColor=new rs.Wo(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new ri.y$,this.onAfterBoxRenderingObservable=new ri.y$,this.onResourcesReadyObservable=new ri.y$,this.enabled=!0,this.renderList=new na.t(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new r1.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new r1.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(ss.l.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(ss.l.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(ss.l.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(ss.l.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){let i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){let t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new hf("colorShader",this.scene,"boundingBoxRenderer",{attributes:[rQ.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new hf("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[rQ.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};let e=this.scene.getEngine(),t=hr({size:1});this._vertexBuffers[rQ.o.PositionKind]=new rQ.o(e,t.positions,rQ.o.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){let 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(){let e=this._vertexBuffers[rQ.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(0===this.renderList.length||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;let r=this.scene.getEngine();r.setDepthWrite(!1);let s=this.scene.getTransformMatrix();for(let n=0;n<this.renderList.length;n++){let a=this.renderList.data[n];if(a._tag!==e)continue;this._createWrappersForBoundingBox(a),this.onBeforeBoxRenderingObservable.notifyObservers(a);let o=a.minimum,l=a.maximum,h=l.subtract(o),u=o.add(h.scale(.5)),c=rr.y3.Scaling(h.x,h.y,h.z).multiply(rr.y3.Translation(u.x,u.y,u.z)).multiply(a.getWorldMatrix()),d=r.useReverseDepthBuffer;if(this.showBackLines){let e=null!==(t=a._drawWrapperBack)&&void 0!==t?t:this._colorShader._getDrawWrapper();this._colorShader._preBind(e),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),d?r.setDepthFunctionToLessOrEqual():r.setDepthFunctionToGreaterOrEqual(),this._uniformBufferBack.bindToEffect(e.effect,"BoundingBoxRenderer"),this._uniformBufferBack.updateColor4("color",this.backColor,1),this._uniformBufferBack.updateMatrix("world",c),this._uniformBufferBack.updateMatrix("viewProjection",s),this._uniformBufferBack.update(),r.drawElementsType(sX.F.LineListDrawMode,0,24)}let p=null!==(i=a._drawWrapperFront)&&void 0!==i?i:this._colorShader._getDrawWrapper();this._colorShader._preBind(p),r.bindBuffers(this._vertexBuffers,this._indexBuffer,this._colorShader.getEffect()),d?r.setDepthFunctionToGreater():r.setDepthFunctionToLess(),this._uniformBufferFront.bindToEffect(p.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateColor4("color",this.frontColor,1),this._uniformBufferFront.updateMatrix("world",c),this._uniformBufferFront.updateMatrix("viewProjection",s),this._uniformBufferFront.update(),r.drawElementsType(sX.F.LineListDrawMode,0,24),this.onAfterBoxRenderingObservable.notifyObservers(a)}this._colorShader.unbind(),r.setDepthFunctionToLessOrEqual(),r.setDepthWrite(!0)}_createWrappersForBoundingBox(e){if(!e._drawWrapperFront){let t=this.scene.getEngine();e._drawWrapperFront=new nc.q(t),e._drawWrapperBack=new nc.q(t),e._drawWrapperFront.setEffect(this._colorShader.getEffect()),e._drawWrapperBack.setEffect(this._colorShader.getEffect())}}renderOcclusionBoundingBox(e){let t=this.scene.getEngine();void 0===this._renderPassIdForOcclusionQuery&&(this._renderPassIdForOcclusionQuery=t.createRenderPassId("Render pass for occlusion query"));let i=t.currentRenderPassId;t.currentRenderPassId=this._renderPassIdForOcclusionQuery,this._prepareResources();let r=e.subMeshes[0];if(!this._colorShaderForOcclusionQuery.isReady(e,void 0,r)||!e.hasBoundingInfo){t.currentRenderPassId=i;return}this._fillIndexBuffer||(this._fillIndexBuffer=t.createIndexBuffer(this._fillIndexData));let s=t.useReverseDepthBuffer;t.setDepthWrite(!1),t.setColorWrite(!1);let n=e.getBoundingInfo().boundingBox,a=n.minimum,o=n.maximum,l=o.subtract(a),h=a.add(l.scale(.5)),u=rr.y3.Scaling(l.x,l.y,l.z).multiply(rr.y3.Translation(h.x,h.y,h.z)).multiply(n.getWorldMatrix()),c=r._drawWrapper;this._colorShaderForOcclusionQuery._preBind(c),t.bindBuffers(this._vertexBuffers,this._fillIndexBuffer,c.effect),s?t.setDepthFunctionToGreater():t.setDepthFunctionToLess(),this.scene.resetCachedMaterial(),this._uniformBufferFront.bindToEffect(c.effect,"BoundingBoxRenderer"),this._uniformBufferFront.updateMatrix("world",u),this._uniformBufferFront.updateMatrix("viewProjection",this.scene.getTransformMatrix()),this._uniformBufferFront.update(),t.drawElementsType(sX.F.TriangleFillMode,0,36),this._colorShaderForOcclusionQuery.unbind(),t.setDepthFunctionToLessOrEqual(),t.setDepthWrite(!0),t.setColorWrite(!0),t.currentRenderPassId=i}dispose(){if(void 0!==this._renderPassIdForOcclusionQuery&&(this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery),this._renderPassIdForOcclusionQuery=void 0),!this._colorShader)return;this.onBeforeBoxRenderingObservable.clear(),this.onAfterBoxRenderingObservable.clear(),this.onResourcesReadyObservable.clear(),this.renderList.dispose(),this._colorShader.dispose(),this._colorShaderForOcclusionQuery.dispose(),this._uniformBufferFront.dispose(),this._uniformBufferBack.dispose();let e=this._vertexBuffers[rQ.o.PositionKind];e&&(e.dispose(),this._vertexBuffers[rQ.o.PositionKind]=null),this.scene.getEngine()._releaseBuffer(this._indexBuffer),this._fillIndexBuffer&&(this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer),this._fillIndexBuffer=null)}}rI.x.prototype.enableDepthRenderer=function(e,t=!1,i=!1,r=3,s=!1){if(!(e=e||this.activeCamera))throw"No camera available to enable depth renderer";if(this._depthRenderer||(this._depthRenderer={}),!this._depthRenderer[e.id]){let n=!!this.getEngine().getCaps().textureFloatRender,a=0;a=!this.getEngine().getCaps().textureHalfFloatRender||i&&n?n?1:0:2,this._depthRenderer[e.id]=new _g(this,a,e,t,r,s)}return this._depthRenderer[e.id]},rI.x.prototype.disableDepthRenderer=function(e){(e=e||this.activeCamera)&&this._depthRenderer&&this._depthRenderer[e.id]&&this._depthRenderer[e.id].dispose()};class vb{constructor(e){this.name=ss.l.NAME_DEPTHRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ss.l.STEP_GATHERRENDERTARGETS_DEPTHRENDERER,this,this._gatherRenderTargets),this.scene._gatherActiveCameraRenderTargetsStage.registerStep(ss.l.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER,this,this._gatherActiveCameraRenderTargets)}rebuild(){}dispose(){for(let e in this.scene._depthRenderer)this.scene._depthRenderer[e].dispose()}_gatherRenderTargets(e){if(this.scene._depthRenderer)for(let t in this.scene._depthRenderer){let i=this.scene._depthRenderer[t];i.enabled&&!i.useOnlyInActiveCamera&&e.push(i.getDepthMap())}}_gatherActiveCameraRenderTargets(e){if(this.scene._depthRenderer)for(let t in this.scene._depthRenderer){let i=this.scene._depthRenderer[t];i.enabled&&i.useOnlyInActiveCamera&&this.scene.activeCamera.id===t&&e.push(i.getDepthMap())}}}_g._SceneComponentInitialization=e=>{let t=e._getComponent(ss.l.NAME_DEPTHRENDERER);t||(t=new vb(e),e._addComponent(t))};let vy=`precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( -frontColor.rgb+alphaMultiplier*backColor.rgb, -frontColor.a+backColor.a -);}`;no.v.ShadersStore.oitFinalPixelShader=vy;let vA=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { -discard;}}`;no.v.ShadersStore.oitBackBlendPixelShader=vA;class vR{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class vP{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){let 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 na.t(10),this._excludedSubMeshes=new na.t(10),this._excludedMeshes=[],this._colorCache=[new rs.HE(vP._DEPTH_CLEAR_VALUE,vP._DEPTH_CLEAR_VALUE,0,0),new rs.HE(-vP._MIN_DEPTH,vP._MAX_DEPTH,0,0),new rs.HE(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){ru.Y.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let e=0;e<this._layoutCacheFormat.length;++e)this._layoutCache[e]=this._engine.buildTextureLayout(this._layoutCacheFormat[e]);this._renderPassIds=[],this.useRenderPasses=!1,this._prePassEffectConfiguration=new vR,this._createTextures(),this._createEffects()}_createRenderPassIds(){if(this._releaseRenderPassIds(),this._useRenderPasses)for(let e=0;e<this._passCount+1;++e)this._renderPassIds[e]||(this._renderPassIds[e]=this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${e}`))}_releaseRenderPassIds(){for(let e=0;e<this._renderPassIds.length;++e)this._engine.releaseRenderPassId(this._renderPassIds[e]);this._renderPassIds=[]}_createTextures(){let e={width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()};this._depthMrts=[new fp("depthPeelingDepth0",e,3,this._scene),new fp("depthPeelingDepth1",e,3,this._scene)],this._colorMrts=[new fp("depthPeelingColor0",e,2,this._scene,{generateDepthBuffer:!1}),new fp("depthPeelingColor1",e,2,this._scene,{generateDepthBuffer:!1})],this._blendBackMrt=new fp("depthPeelingBack",e,1,this._scene,{generateDepthBuffer:!1}),this._outputRT=new nV("depthPeelingOutput",e,this._scene,!1);let t=[{format:7,samplingMode:1,type:this._engine.getCaps().textureFloatLinearFiltering?1:2,label:"DepthPeelingRenderer-DepthTexture"},{format:5,samplingMode:1,type:2,label:"DepthPeelingRenderer-ColorTexture"}];for(let i=0;i<2;i++){let r=this._engine._createInternalTexture(e,t[0],!1),s=this._engine._createInternalTexture(e,t[1],!1),n=this._engine._createInternalTexture(e,t[1],!1);this._depthMrts[i].setInternalTexture(r,0),this._depthMrts[i].setInternalTexture(s,1),this._depthMrts[i].setInternalTexture(n,2),this._colorMrts[i].setInternalTexture(s,0),this._colorMrts[i].setInternalTexture(n,1),this._thinTextures.push(new sh(r),new sh(s),new sh(n))}}_disposeTextures(){for(let e=0;e<this._thinTextures.length;e++)6!==e&&this._thinTextures[e].dispose();for(let e=0;e<2;e++)this._depthMrts[e].dispose(!0),this._colorMrts[e].dispose(!0),this._blendBackMrt.dispose(!0);this._outputRT.dispose(),this._thinTextures=[],this._colorMrts=[],this._depthMrts=[]}_updateTextures(){return(this._depthMrts[0].getSize().width!==this._engine.getRenderWidth()||this._depthMrts[0].getSize().height!==this._engine.getRenderHeight())&&(this._disposeTextures(),this._createTextures()),this._updateTextureReferences()}_updateTextureReferences(){var e;let t=this._scene.prePassRenderer;if(!t)return!1;let i=t.getIndex(4),r=(null===(e=t.defaultRT.textures)||void 0===e?void 0:e.length)?t.defaultRT.textures[i].getInternalTexture():null;return!!r&&(this._blendBackTexture!==r&&(this._blendBackTexture=r,this._blendBackMrt.setInternalTexture(this._blendBackTexture,0),this._thinTextures[6]&&this._thinTextures[6].dispose(),this._thinTextures[6]=new sh(this._blendBackTexture),t.defaultRT.renderTarget._shareDepth(this._depthMrts[0].renderTarget)),!0)}_createEffects(){this._blendBackEffectWrapper=new nF({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._blendBackEffectWrapperPingPong=new nF({fragmentShader:"oitBackBlend",useShaderStore:!0,engine:this._engine,samplerNames:["uBackColor"],uniformNames:[]}),this._finalEffectWrapper=new nF({fragmentShader:"oitFinal",useShaderStore:!0,engine:this._engine,samplerNames:["uFrontColor","uBackColor"],uniformNames:[]}),this._effectRenderer=new nN(this._engine)}setPrePassRenderer(e){e.addEffectConfiguration(this._prePassEffectConfiguration)}bind(e){e.setTexture("oitDepthSampler",this._thinTextures[3*this._currentPingPongState]),e.setTexture("oitFrontColorSampler",this._thinTextures[3*this._currentPingPongState+1])}_renderSubMeshes(e){let t;this._useRenderPasses&&(t={});for(let i=0;i<e.length;i++){let r;let s=e.data[i].getMaterial(),n=!0,a=!1,o=e.data[i],l=!1;if(this._useRenderPasses&&(l=!(r=o._getDrawWrapper())),s&&(n=s.allowShaderHotSwapping,a=s.backFaceCulling,s.allowShaderHotSwapping=!1,s.backFaceCulling=!1),o.render(!1),l&&(r=o._getDrawWrapper()).materialContext){let e=t[r.materialContext.uniqueId];e||(e=t[r.materialContext.uniqueId]=this._engine.createMaterialContext()),o._getDrawWrapper().materialContext=e}s&&(s.allowShaderHotSwapping=n,s.backFaceCulling=a)}}_finalCompose(e){var t;let i=null===(t=this._scene.prePassRenderer)||void 0===t?void 0:t.setCustomOutput(this._outputRT);i?this._engine.bindFramebuffer(this._outputRT.renderTarget):this._engine.restoreDefaultFramebuffer(),this._engine.setAlphaMode(0),this._engine.applyStates(),this._engine.enableEffect(this._finalEffectWrapper._drawWrapper),this._finalEffectWrapper.effect.setTexture("uFrontColor",this._thinTextures[3*e+1]),this._finalEffectWrapper.effect.setTexture("uBackColor",this._thinTextures[6]),this._effectRenderer.render(this._finalEffectWrapper)}render(e){if(this._candidateSubMeshes.length=0,this._excludedSubMeshes.length=0,!this._blendBackEffectWrapper.effect.isReady()||!this._blendBackEffectWrapperPingPong.effect.isReady()||!this._finalEffectWrapper.effect.isReady()||!this._updateTextures())return this._excludedSubMeshes;for(let t=0;t<e.length;t++){let i=e.data[t],r=i.getMaterial(),s=r&&i.getRenderingMesh()._getRenderingFillMode(r.fillMode);r&&(s===sX.F.TriangleFanDrawMode||s===sX.F.TriangleFillMode||s===sX.F.TriangleStripDrawMode)&&-1===this._excludedMeshes.indexOf(i.getMesh().uniqueId)?this._candidateSubMeshes.push(i):this._excludedSubMeshes.push(i)}if(!this._candidateSubMeshes.length)return this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._finalCompose(1),this._excludedSubMeshes;let t=this._engine.currentRenderPassId;this._scene.prePassRenderer._enabled=!1,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[0]),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[1],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget),this._engine.bindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget),this._engine.bindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget),this._engine.bindFramebuffer(this._depthMrts[0].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaMode(11),this._engine.setAlphaEquation(3),this._engine.depthCullingState.depthMask=!1,this._engine.depthCullingState.depthTest=!0,this._engine.applyStates(),this._currentPingPongState=1,this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget),this._scene.resetCachedMaterial();let i=0,r=0;for(let e=0;e<this._passCount;e++){r=1-(i=e%2),this._currentPingPongState=i,this._useRenderPasses&&(this._engine.currentRenderPassId=this._renderPassIds[e+1]),this._engine.bindFramebuffer(this._depthMrts[r].renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.clear(this._colorCache[0],!0,!1,!1),this._engine.unBindFramebuffer(this._depthMrts[r].renderTarget),this._engine.bindFramebuffer(this._colorMrts[r].renderTarget),this._engine.bindAttachments(this._layoutCache[1]),this._engine.clear(this._colorCache[2],!0,!1,!1),this._engine.unBindFramebuffer(this._colorMrts[r].renderTarget),this._engine.bindFramebuffer(this._depthMrts[r].renderTarget),this._engine.bindAttachments(this._layoutCache[2]),this._engine.setAlphaMode(11),this._engine.setAlphaEquation(3),this._engine.depthCullingState.depthTest=!1,this._engine.applyStates(),this._renderSubMeshes(this._candidateSubMeshes),this._engine.unBindFramebuffer(this._depthMrts[r].renderTarget),this._scene.resetCachedMaterial(),this._engine.bindFramebuffer(this._blendBackMrt.renderTarget),this._engine.bindAttachments(this._layoutCache[0]),this._engine.setAlphaEquation(0),this._engine.setAlphaMode(17),this._engine.applyStates();let t=0!==r&&this._useRenderPasses?this._blendBackEffectWrapperPingPong:this._blendBackEffectWrapper;this._engine.enableEffect(t._drawWrapper),t.effect.setTexture("uBackColor",this._thinTextures[3*r+2]),this._effectRenderer.render(t),this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget)}return this._engine.currentRenderPassId=t,this._finalCompose(r),this._scene.prePassRenderer._enabled=!0,this._engine.depthCullingState.depthMask=!0,this._engine.depthCullingState.depthTest=!0,this._excludedSubMeshes}dispose(){this._disposeTextures(),this._blendBackEffectWrapper.dispose(),this._finalEffectWrapper.dispose(),this._effectRenderer.dispose(),this._releaseRenderPassIds()}}vP._DEPTH_CLEAR_VALUE=-99999,vP._MIN_DEPTH=0,vP._MAX_DEPTH=1,Object.defineProperty(rI.x.prototype,"depthPeelingRenderer",{get:function(){if(!this._depthPeelingRenderer){let e=this._getComponent(ss.l.NAME_DEPTHPEELINGRENDERER);e||(e=new vI(this),this._addComponent(e))}return this._depthPeelingRenderer},set:function(e){this._depthPeelingRenderer=e},enumerable:!0,configurable:!0}),Object.defineProperty(rI.x.prototype,"useOrderIndependentTransparency",{get:function(){return this._useOrderIndependentTransparency},set:function(e){var t;this._useOrderIndependentTransparency!==e&&(this._useOrderIndependentTransparency=e,this.markAllMaterialsAsDirty(63),null===(t=this.prePassRenderer)||void 0===t||t.markAsDirty())},enumerable:!0,configurable:!0});class vI{constructor(e){this.name=ss.l.NAME_DEPTHPEELINGRENDERER,this.scene=e,e.depthPeelingRenderer=new vP(e)}register(){}rebuild(){}dispose(){var e;null===(e=this.scene.depthPeelingRenderer)||void 0===e||e.dispose(),this.scene.depthPeelingRenderer=null}}let vM=`#include<clipPlaneFragmentDeclaration> -uniform vec4 color; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;no.v.ShadersStore.linePixelShader=vM;let vD=`#include<instancesDeclaration> -#include<clipPlaneVertexDeclaration> -attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#include<instancesVertex> -mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=finalWorld*vec4(position,1.0); -#include<clipPlaneVertex> -#endif -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.lineVertexShader=vD,r$.x.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},r$.x.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new vN(this,e,t,!0,i),this},Object.defineProperty(r$.x.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),hv.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new vF(this,e,t),this},hT.prototype.enableEdgesRendering=function(e=.95,t=!1){return hv.prototype.enableEdgesRendering.apply(this,arguments),this};class vO{constructor(){this.edges=[],this.edgesConnectedCount=0}}class vN{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){let t=new hf("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,r=!0,s){var n;this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=[],this._linesNormals=[],this._linesIndices=[],this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new na.t(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=null!=s?s:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new nc.q(e.getEngine())),this._prepareRessources(),r&&(null===(n=null==s?void 0:s.useAlternateEdgeFinder)||void 0===n||n?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=vN._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[rQ.o.PositionKind];e&&e._rebuild(),(e=this._buffers[rQ.o.NormalKind])&&e._rebuild();let t=this._source.getScene(),i=t.getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[rQ.o.PositionKind];t&&(t.dispose(),this._buffers[rQ.o.PositionKind]=null),(t=this._buffers[rQ.o.NormalKind])&&(t.dispose(),this._buffers[rQ.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,r,s){return e===i&&t===r||e===r&&t===i?0:e===r&&t===s||e===s&&t===r?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,s){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)?1:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)?2:-1}_checkEdge(e,t,i,r,s){let n;if(void 0===t)n=!0;else{let r=rr.P.Dot(i[e],i[t]);n=r<this._epsilon}n&&this.createLine(r,s,this._linesPositions.length/3)}createLine(e,t,i){this._linesPositions.push(e.x,e.y,e.z,e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z),this._linesNormals.push(t.x,t.y,t.z,-1,t.x,t.y,t.z,1,e.x,e.y,e.z,-1,e.x,e.y,e.z,1),this._linesIndices.push(i,i+1,i+2,i,i+2,i+3)}_tessellateTriangle(e,t,i,r){let s=(e,t,i)=>{i>=0&&t.push(i);for(let i=0;i<e.length;++i)t.push(e[i][0])},n=0;e[1].length>=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let t=0;t<3;++t)t===n?e[t].sort((e,t)=>e[1]<t[1]?-1:e[1]>t[1]?1:0):e[t].sort((e,t)=>e[1]>t[1]?-1:e[1]<t[1]?1:0);let a=[],o=[];s(e[n],a,-1);let l=a.length;for(let a=n+2;a>=n+1;--a)s(e[a%3],o,a!==n+2?r[i[t+(a+1)%3]]:-1);let h=o.length;i.push(r[i[t+n]],a[0],o[0]),i.push(r[i[t+(n+1)%3]],o[h-1],a[l-1]);let u=l<=h,c=u?l:h,d=u?h:l,p=u?l-1:h-1,_=u?0:1,f=l+h-2,m=0,g=0,v=u?a:o,T=u?o:a,x=0;for(;f-- >0;){let e;_?i.push(v[m],T[g]):i.push(T[g],v[m]),(x+=c)>=d&&m<p?(e=v[++m],x-=d):e=T[++g],i.push(e)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3}_generateEdgesLinesAlternate(){var e,t,i,r,s,n,a,o,l,h;let u=this._source.getVerticesData(rQ.o.PositionKind),c=this._source.getIndices();if(!c||!u)return;Array.isArray(c)||(c=Array.from(c));let d=null===(t=null===(e=this._options)||void 0===e?void 0:e.useFastVertexMerger)||void 0===t||t,p=d?Math.round(-Math.log(null!==(r=null===(i=this._options)||void 0===i?void 0:i.epsilonVertexMerge)&&void 0!==r?r:1e-6)/Math.log(10)):null!==(n=null===(s=this._options)||void 0===s?void 0:s.epsilonVertexMerge)&&void 0!==n?n:1e-6,_=[],f=[];if(d){let e={};for(let t=0;t<u.length;t+=3){let i=u[t+0],r=u[t+1],s=u[t+2],n=i.toFixed(p)+"|"+r.toFixed(p)+"|"+s.toFixed(p);if(void 0!==e[n])_.push(e[n]);else{let i=t/3;e[n]=i,_.push(i),f.push(i)}}}else for(let e=0;e<u.length;e+=3){let t=u[e+0],i=u[e+1],r=u[e+2],s=!1;for(let n=0;n<e&&!s;n+=3){let e=u[n+0],a=u[n+1],o=u[n+2];if(Math.abs(t-e)<p&&Math.abs(i-a)<p&&Math.abs(r-o)<p){_.push(n/3),s=!0;break}}s||(_.push(e/3),f.push(e/3))}if(null===(a=this._options)||void 0===a?void 0:a.applyTessellation){let e=null!==(l=null===(o=this._options)||void 0===o?void 0:o.epsilonVertexAligned)&&void 0!==l?l:1e-6,t=[];for(let i=0;i<c.length;i+=3){let r;for(let s=0;s<3;++s){let n=_[c[i+s]],a=_[c[i+(s+1)%3]],o=_[c[i+(s+2)%3]];if(n===a)continue;let l=u[3*n+0],h=u[3*n+1],d=u[3*n+2],p=u[3*a+0],m=u[3*a+1],g=u[3*a+2],v=Math.sqrt((p-l)*(p-l)+(m-h)*(m-h)+(g-d)*(g-d));for(let c=0;c<f.length-1;c++){let _=f[c];if(_===n||_===a||_===o)continue;let T=u[3*_+0],x=u[3*_+1],S=u[3*_+2],E=Math.sqrt((T-l)*(T-l)+(x-h)*(x-h)+(S-d)*(S-d)),C=Math.sqrt((T-p)*(T-p)+(x-m)*(x-m)+(S-g)*(S-g));Math.abs(E+C-v)<e&&(r||(r={index:i,edgesPoints:[[],[],[]]},t.push(r)),r.edgesPoints[s].push([_,E]))}}}for(let e=0;e<t.length;++e){let i=t[e];this._tessellateTriangle(i.edgesPoints,i.index,c,_)}t.length=0}let m={};for(let e=0;e<c.length;e+=3){let t;for(let i=0;i<3;++i){let r=_[c[e+i]],s=_[c[e+(i+1)%3]],n=_[c[e+(i+2)%3]];if(r===s||(r===n||s===n)&&(null===(h=this._options)||void 0===h?void 0:h.removeDegeneratedTriangles))continue;if(rr.jp.Vector3[0].copyFromFloats(u[3*r+0],u[3*r+1],u[3*r+2]),rr.jp.Vector3[1].copyFromFloats(u[3*s+0],u[3*s+1],u[3*s+2]),rr.jp.Vector3[2].copyFromFloats(u[3*n+0],u[3*n+1],u[3*n+2]),t||(rr.jp.Vector3[1].subtractToRef(rr.jp.Vector3[0],rr.jp.Vector3[3]),rr.jp.Vector3[2].subtractToRef(rr.jp.Vector3[1],rr.jp.Vector3[4]),(t=rr.P.Cross(rr.jp.Vector3[3],rr.jp.Vector3[4])).normalize()),r>s){let e=r;r=s,s=e}let a=r+"_"+s,o=m[a];if(o){if(!o.done){let e=rr.P.Dot(t,o.normal);e<this._epsilon&&this.createLine(rr.jp.Vector3[0],rr.jp.Vector3[1],this._linesPositions.length/3),o.done=!0}}else m[a]={normal:t,done:!1,index:e,i:i}}}for(let e in m){let t=m[e];if(!t.done){let e=_[c[t.index+t.i]],i=_[c[t.index+(t.i+1)%3]];rr.jp.Vector3[0].copyFromFloats(u[3*e+0],u[3*e+1],u[3*e+2]),rr.jp.Vector3[1].copyFromFloats(u[3*i+0],u[3*i+1],u[3*i+2]),this.createLine(rr.jp.Vector3[0],rr.jp.Vector3[1],this._linesPositions.length/3)}}let g=this._source.getScene().getEngine();this._buffers[rQ.o.PositionKind]=new rQ.o(g,this._linesPositions,rQ.o.PositionKind,!1),this._buffers[rQ.o.NormalKind]=new rQ.o(g,this._linesNormals,rQ.o.NormalKind,!1,!1,4),this._buffersForInstances[rQ.o.PositionKind]=this._buffers[rQ.o.PositionKind],this._buffersForInstances[rQ.o.NormalKind]=this._buffers[rQ.o.NormalKind],this._ib=g.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}_generateEdgesLines(){let e,t;let i=this._source.getVerticesData(rQ.o.PositionKind),r=this._source.getIndices();if(!r||!i)return;let s=[],n=[];for(e=0;e<r.length;e+=3){t=new vO;let a=r[e],o=r[e+1],l=r[e+2];t.p0=new rr.P(i[3*a],i[3*a+1],i[3*a+2]),t.p1=new rr.P(i[3*o],i[3*o+1],i[3*o+2]),t.p2=new rr.P(i[3*l],i[3*l+1],i[3*l+2]);let h=rr.P.Cross(t.p1.subtract(t.p0),t.p2.subtract(t.p1));h.normalize(),n.push(h),s.push(t)}for(e=0;e<s.length;e++){t=s[e];for(let i=e+1;i<s.length;i++){let n=s[i];if(3===t.edgesConnectedCount)break;if(3===n.edgesConnectedCount)continue;let a=r[3*i],o=r[3*i+1],l=r[3*i+2];for(let s=0;s<3;s++){let h=0;if(void 0===t.edges[s]){switch(s){case 0:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(t.p0,t.p1,n.p0,n.p1,n.p2):this._processEdgeForAdjacencies(r[3*e],r[3*e+1],a,o,l);break;case 1:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(t.p1,t.p2,n.p0,n.p1,n.p2):this._processEdgeForAdjacencies(r[3*e+1],r[3*e+2],a,o,l);break;case 2:h=this._checkVerticesInsteadOfIndices?this._processEdgeForAdjacenciesWithVertices(t.p2,t.p0,n.p0,n.p1,n.p2):this._processEdgeForAdjacencies(r[3*e+2],r[3*e],a,o,l)}if(-1!==h&&(t.edges[s]=i,n.edges[h]=e,t.edgesConnectedCount++,n.edgesConnectedCount++,3===t.edgesConnectedCount))break}}}}for(e=0;e<s.length;e++){let t=s[e];this._checkEdge(e,t.edges[0],n,t.p0,t.p1),this._checkEdge(e,t.edges[1],n,t.p1,t.p2),this._checkEdge(e,t.edges[2],n,t.p2,t.p0)}let a=this._source.getScene().getEngine();this._buffers[rQ.o.PositionKind]=new rQ.o(a,this._linesPositions,rQ.o.PositionKind,!1),this._buffers[rQ.o.NormalKind]=new rQ.o(a,this._linesNormals,rQ.o.NormalKind,!1,!1,4),this._buffersForInstances[rQ.o.PositionKind]=this._buffers[rQ.o.PositionKind],this._buffersForInstances[rQ.o.NormalKind]=this._buffers[rQ.o.NormalKind],this._ib=a.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}isReady(){return this._lineShader.isReady(this._source,this._source.hasInstances&&this.customInstances.length>0||this._source.hasThinInstances)}render(){let e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}let i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances,s=0;if(r){if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){let e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!e.isFrozen){let t=0;for(let i=0;i<s;++i)this.customInstances.data[i].copyToArray(e.instancesData,t),t+=16;e.instancesBuffer.updateDirectly(e.instancesData,0,s)}}else s=this._source.thinInstanceCount}let n=e.getEngine();this._lineShader._preBind(),1!==this._source.edgesColor.a?n.setAlphaMode(2):n.setAlphaMode(0),n.bindBuffers(r?this._buffersForInstances:this._buffers,this._ib,this._lineShader.getEffect()),e.resetCachedMaterial(),this._lineShader.setColor4("color",this._source.edgesColor),e.activeCamera.mode===r4.V.ORTHOGRAPHIC_CAMERA?this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForOrthographic):this._lineShader.setFloat("width",this._source.edgesWidth/this.edgesWidthScalerForPerspective),this._lineShader.setFloat("aspectRatio",n.getAspectRatio(e.activeCamera)),this._lineShader.bind(this._source.getWorldMatrix()),n.drawElementsType(sX.F.TriangleFillMode,0,this._indicesCount,s),this._lineShader.unbind(),r&&n.unbindInstanceAttributes(),this._source.getScene()._activeMeshesFrozen||this.customInstances.reset(),this._lineShader._setDrawWrapper(t)}}class vF extends vN{constructor(e,t=.95,i=!1){super(e,t,i,!1),this._generateEdgesLines()}_generateEdgesLines(){let e=this._source.getVerticesData(rQ.o.PositionKind),t=this._source.getIndices();if(!t||!e)return;let i=rr.jp.Vector3[0],r=rr.jp.Vector3[1],s=t.length-1;for(let n=0,a=0;n<s;n+=2,a+=4)rr.P.FromArrayToRef(e,3*t[n],i),rr.P.FromArrayToRef(e,3*t[n+1],r),this.createLine(i,r,a);let n=this._source.getScene().getEngine();this._buffers[rQ.o.PositionKind]=new rQ.o(n,this._linesPositions,rQ.o.PositionKind,!1),this._buffers[rQ.o.NormalKind]=new rQ.o(n,this._linesNormals,rQ.o.NormalKind,!1,!1,4),this._ib=n.createIndexBuffer(this._linesIndices),this._indicesCount=this._linesIndices.length}}class vL extends fp{constructor(e,t,i,r,s,n){super(e,i,r,s,n),this._beforeCompositionPostProcesses=[],this._internalTextureDirty=!1,this.enabled=!1,this.renderTargetTexture=null,this.renderTargetTexture=t}_createCompositionEffect(){this.imageProcessingPostProcess=new lA("prePassComposition",1,null,void 0,this._engine),this.imageProcessingPostProcess._updateParameters()}_checkSize(){let e=this._engine.getRenderWidth(!0),t=this._engine.getRenderHeight(!0),i=this.getRenderWidth(),r=this.getRenderHeight();(i!==e||r!==t)&&(this.resize({width:e,height:t}),this._internalTextureDirty=!0)}updateCount(e,t,i){super.updateCount(e,t,i),this._internalTextureDirty=!0}_resetPostProcessChain(){this._beforeCompositionPostProcesses.length=0}dispose(){let e=this._scene;if(super.dispose(),e&&e.prePassRenderer){let t=e.prePassRenderer.renderTargets.indexOf(this);-1!==t&&e.prePassRenderer.renderTargets.splice(t,1)}this.imageProcessingPostProcess&&this.imageProcessingPostProcess.dispose(),this.renderTargetTexture&&(this.renderTargetTexture._prePassRenderTarget=null),this._outputPostProcess&&(this._outputPostProcess.autoClear=!0,this._outputPostProcess.restoreDefaultInputTexture())}}class vw{getIndex(e){return this._textureIndices[e]}get samples(){return this.defaultRT.samples}set samples(e){this.defaultRT.samples=e}get useSpecificClearForDepthTexture(){return this._useSpecificClearForDepthTexture}set useSpecificClearForDepthTexture(e){this._useSpecificClearForDepthTexture!==e&&(this._useSpecificClearForDepthTexture=e,this._isDirty=!0)}getRenderTarget(){return this._currentTarget}_setRenderTarget(e){var t,i;e?this._currentTarget=e:(this._currentTarget=this.defaultRT,this._engine.currentRenderPassId=null!==(i=null===(t=this._scene.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==i?i:this._currentTarget.renderPassId)}get currentRTisSceneRT(){return this._currentTarget===this.defaultRT}_refreshGeometryBufferRendererLink(){if(this.doNotUseGeometryRendererFallback)this._geometryBuffer&&this._geometryBuffer._unlinkPrePassRenderer(),this._geometryBuffer=null,this._scene.disableGeometryBufferRenderer();else{if(this._geometryBuffer=this._scene.enableGeometryBufferRenderer(),!this._geometryBuffer){this.doNotUseGeometryRendererFallback=!0;return}this._geometryBuffer._linkPrePassRenderer(this)}}get enabled(){return this._enabled}constructor(e){this.excludedSkinnedMesh=[],this.excludedMaterials=[],this.mrtCount=0,this._mrtTypes=[],this._mrtFormats=[],this._mrtLayout=[],this._mrtNames=[],this._textureIndices=[],this._useSpecificClearForDepthTexture=!1,this._isDirty=!0,this._effectConfigurations=[],this.doNotUseGeometryRendererFallback=!0,this.renderTargets=[],this._clearColor=new rs.HE(0,0,0,0),this._clearDepthColor=new rs.HE(1e8,0,0,1),this._enabled=!1,this._needsCompositionForThisPass=!1,this.disableGammaTransform=!1,this._scene=e,this._engine=e.getEngine();let t=0;if(this._engine._caps.textureFloat&&this._engine._caps.textureFloatLinearFiltering?t=1:this._engine._caps.textureHalfFloat&&this._engine._caps.textureHalfFloatLinearFiltering&&(t=2),1!==t)for(let e=0;e<vw.TextureFormats.length;++e)1===vw.TextureFormats[e].type&&(vw.TextureFormats[5].type=t);vw._SceneComponentInitialization(this._scene),this.defaultRT=this._createRenderTarget("sceneprePassRT",null),this._currentTarget=this.defaultRT}_createRenderTarget(e,t){let i=new vL(e,t,{width:this._engine.getRenderWidth(),height:this._engine.getRenderHeight()},0,this._scene,{generateMipMaps:!1,generateStencilBuffer:this._engine.isStencilEnable,defaultType:0,types:[],drawOnlyOnFirstAttachmentByDefault:!0});return this.renderTargets.push(i),this._enabled&&this._update(),i}get isSupported(){return this._scene.getEngine().getCaps().drawBuffersExtension}bindAttachmentsForEffect(e,t){let i=t.getMaterial(),r=i&&i.isPrePassCapable,s=i&&-1!==this.excludedMaterials.indexOf(i);this.enabled&&this._currentTarget.enabled&&(e._multiTarget&&r&&!s?this._engine.bindAttachments(this._multiRenderAttachments):(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment(),this._geometryBuffer&&this.currentRTisSceneRT&&!s&&this._geometryBuffer.renderList.push(t.getRenderingMesh())))}_reinitializeAttachments(){let e=[],t=[!1],i=[!1],r=[!0];for(let s=0;s<this.mrtCount;s++)e.push(!0),s>0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;e<vw.TextureFormats.length;e++)this._textureIndices[vw.TextureFormats[e].purpose]=-1;this._textureIndices[4]=0,this._mrtLayout=[4],this._mrtTypes=[vw.TextureFormats[4].type],this._mrtFormats=[vw.TextureFormats[4].format],this._mrtNames=[vw.TextureFormats[4].name],this.mrtCount=1}_updateGeometryBufferLayout(){if(this._refreshGeometryBufferRendererLink(),this._geometryBuffer){this._geometryBuffer._resetLayout();let e=[];for(let t=0;t<this._mrtLayout.length;t++)e.push(!1);this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture());let t=[{prePassConstant:5,geometryBufferConstant:gz.DEPTH_TEXTURE_TYPE},{prePassConstant:6,geometryBufferConstant:gz.NORMAL_TEXTURE_TYPE},{prePassConstant:1,geometryBufferConstant:gz.POSITION_TEXTURE_TYPE},{prePassConstant:3,geometryBufferConstant:gz.REFLECTIVITY_TEXTURE_TYPE},{prePassConstant:2,geometryBufferConstant:gz.VELOCITY_TEXTURE_TYPE}];for(let i=0;i<t.length;i++){let r=this._mrtLayout.indexOf(t[i].prePassConstant);-1!==r&&(this._geometryBuffer._forceTextureType(t[i].geometryBufferConstant,r),e[r]=!0)}this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(e))}}restoreAttachments(){this.enabled&&this._currentTarget.enabled&&this._defaultAttachments&&(this._engine._currentRenderTarget?this._engine.bindAttachments(this._defaultAttachments):this._engine.restoreSingleAttachment())}_beforeDraw(e,t,i){this._isDirty&&this._update(),this._enabled&&this._currentTarget.enabled&&(this._geometryBuffer&&(this._geometryBuffer.renderList=[]),this._setupOutputForThisPass(this._currentTarget,e))}_prepareFrame(e,t,i){e.renderTargetTexture?e.renderTargetTexture._prepareFrame(this._scene,t,i,e.renderTargetTexture.useCameraPostProcesses):this._postProcessesSourceForThisPass.length?this._scene.postProcessManager._prepareFrame():this._engine.restoreDefaultFramebuffer()}setCustomOutput(e){let t=this._postProcessesSourceForThisPass[0];return!!t&&(t.inputTexture=e.renderTarget,!0)}_renderPostProcesses(e,t){var i;let r=this._postProcessesSourceForThisPass[0],s=r?r.inputTexture:e.renderTargetTexture?e.renderTargetTexture.renderTarget:null,n=this._currentTarget._beforeCompositionPostProcesses;this._needsCompositionForThisPass&&(n=n.concat([this._currentTarget.imageProcessingPostProcess])),n.length&&(this._scene.postProcessManager._prepareFrame(null===(i=this._currentTarget.renderTarget)||void 0===i?void 0:i.texture,n),this._scene.postProcessManager.directRender(n,s,!1,t))}_afterDraw(e,t){this._enabled&&this._currentTarget.enabled&&(this._prepareFrame(this._currentTarget,e,t),this._renderPostProcesses(this._currentTarget,e))}_clear(){this._enabled&&this._currentTarget.enabled&&(this._bindFrameBuffer(this._currentTarget),this._engine.bindAttachments(this._clearAttachments),this._engine.clear(this._clearColor,!0,!1,!1),this._useSpecificClearForDepthTexture&&(this._engine.bindAttachments(this._clearDepthAttachments),this._engine.clear(this._clearDepthColor,!0,!1,!1)),this._engine.bindAttachments(this._defaultAttachments))}_bindFrameBuffer(e){if(this._enabled&&this._currentTarget.enabled){this._currentTarget._checkSize();let e=this._currentTarget.renderTarget;e&&this._engine.bindFramebuffer(e)}}_setEnabled(e){this._enabled=e}_setRenderTargetEnabled(e,t){e.enabled=t,t||this._unlinkInternalTexture(e)}addEffectConfiguration(e){for(let t=0;t<this._effectConfigurations.length;t++)if(this._effectConfigurations[t].name===e.name)return this._effectConfigurations[t];return this._effectConfigurations.push(e),e}_enable(){let e=this.mrtCount;for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled&&this._enableTextures(this._effectConfigurations[e].texturesRequired);for(let t=0;t<this.renderTargets.length;t++){(this.mrtCount!==e||this.renderTargets[t].count!==this.mrtCount)&&this.renderTargets[t].updateCount(this.mrtCount,{types:this._mrtTypes,formats:this._mrtFormats},this._mrtNames.concat("prePass_DepthBuffer")),this.renderTargets[t]._resetPostProcessChain();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled&&(!this._effectConfigurations[e].postProcess&&this._effectConfigurations[e].createPostProcess&&this._effectConfigurations[e].createPostProcess(),this._effectConfigurations[e].postProcess&&this.renderTargets[t]._beforeCompositionPostProcesses.push(this._effectConfigurations[e].postProcess))}this._reinitializeAttachments(),this._setEnabled(!0),this._updateGeometryBufferLayout()}_disable(){this._setEnabled(!1);for(let e=0;e<this.renderTargets.length;e++)this._setRenderTargetEnabled(this.renderTargets[e],!1);this._resetLayout();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].enabled=!1}_getPostProcessesSource(e,t){if(t)return t._postProcesses;if(!e.renderTargetTexture)return this._scene.activeCamera?this._scene.activeCamera._postProcesses:[];if(e.renderTargetTexture.useCameraPostProcesses){let t=e.renderTargetTexture.activeCamera?e.renderTargetTexture.activeCamera:this._scene.activeCamera;return t?t._postProcesses:[]}return e.renderTargetTexture.postProcesses?e.renderTargetTexture.postProcesses:[]}_setupOutputForThisPass(e,t){let i=t&&this._scene.activeCameras&&!!this._scene.activeCameras.length&&0!==this._scene.activeCameras.indexOf(t);this._postProcessesSourceForThisPass=this._getPostProcessesSource(e,t),this._postProcessesSourceForThisPass=this._postProcessesSourceForThisPass.filter(e=>null!=e),this._scene.autoClear=!0;let r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;let s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0],a=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?a=n:this._needsCompositionForThisPass?a=e.imageProcessingPostProcess:s&&(a=s),this._bindFrameBuffer(e),this._linkInternalTexture(e,a)}_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;e<this._effectConfigurations.length;e++)if(this._effectConfigurations[e].enabled&&this._effectConfigurations[e].needsImageProcessing)return!0;return!1}_hasImageProcessing(e){var t;let i=!1;if(e){for(let r=0;r<e.length;r++)if((null===(t=e[r])||void 0===t?void 0:t.getClassName())==="ImageProcessingPostProcess"){i=!0;break}}return i}_getFirstPostProcess(e){for(let t=0;t<e.length;t++)if(null!==e[t])return e[t];return null}markAsDirty(){this._isDirty=!0}_enableTextures(e){this._scene.needsPreviousWorldMatrices=!1;for(let t=0;t<e.length;t++){let i=e[t];-1===this._textureIndices[i]&&(this._textureIndices[i]=this._mrtLayout.length,this._mrtLayout.push(i),this._mrtTypes.push(vw.TextureFormats[i].type),this._mrtFormats.push(vw.TextureFormats[i].format),this._mrtNames.push(vw.TextureFormats[i].name),this.mrtCount++),2===i&&(this._scene.needsPreviousWorldMatrices=!0)}}update(){this._isDirty&&this._update()}_update(){let e;this._disable();let t=!1;this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._scene._depthPeelingRenderer&&this._scene.useOrderIndependentTransparency&&(this._scene._depthPeelingRenderer.setPrePassRenderer(this),t=!0);for(let e=0;e<this._scene.materials.length;e++)this._scene.materials[e].setPrePassRenderer(this)&&(t=!0);t&&this._setRenderTargetEnabled(this.defaultRT,!0);for(let i=0;i<this.renderTargets.length;i++){if(this.renderTargets[i].renderTargetTexture)e=this._getPostProcessesSource(this.renderTargets[i]);else{let t=this._scene.activeCamera;if(!t)continue;e=t._postProcesses}if(e&&(e=e.filter(e=>null!=e))){for(let r=0;r<e.length;r++)e[r].setPrePassRenderer(this)&&(this._setRenderTargetEnabled(this.renderTargets[i],!0),t=!0);this._hasImageProcessing(e)&&(this._scene.imageProcessingConfiguration.applyByPostProcess=!0)}}this._markAllMaterialsAsPrePassDirty(),this._isDirty=!1,t&&this._enable()}_markAllMaterialsAsPrePassDirty(){let e=this._scene.materials;for(let t=0;t<e.length;t++)e[t].markAsDirty(sX.F.PrePassDirtyFlag)}dispose(){for(let e=this.renderTargets.length-1;e>=0;e--)this.renderTargets[e].dispose();for(let e=0;e<this._effectConfigurations.length;e++)this._effectConfigurations[e].dispose&&this._effectConfigurations[e].dispose()}}vw._SceneComponentInitialization=e=>{throw(0,st.S)("PrePassRendererSceneComponent")},vw.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(rI.x.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),rI.x.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new vw(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,ru.Y.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},rI.x.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class vB{constructor(e){this.name=ss.l.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(ss.l.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(ss.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(ss.l.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(ss.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(ss.l.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(ss.l.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(ss.l.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(ss.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,r){if(!r)return;let s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){let t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}}vw._SceneComponentInitialization=e=>{let t=e._getComponent(ss.l.NAME_PREPASSRENDERER);t||(t=new vB(e),e._addComponent(t))};let vU=`#define rcp(x) 1./x -#define GOLDEN_RATIO 1.618033988749895 -#define TWO_PI 6.2831855 -vec2 Golden2dSeq(int i,float n) -{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} -vec2 SampleDiskGolden(int i,int sampleCount) -{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;no.v.IncludesShadersStore.fibonacci=vU,no.v.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";let vV=`#include<fibonacci> -#include<helperFunctions> -#include<subSurfaceScatteringFunctions> -#include<diffusionProfile> -varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; -#define rcp(x) 1./x -#define Sq(x) x*x -#define SSS_BILATERAL_FILTER true -vec3 EvalBurleyDiffusionProfile(float r,vec3 S) -{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); -vec3 expSum=exp_13*(1.+exp_13*exp_13); -return (S*rcp(8.*PI))*expSum; } -vec2 SampleBurleyDiffusionProfile(float u,float rcpS) -{u=1.-u; -float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); -float p=(g*n)*n; -float c=1.+p+n; -float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); -float x=(3./LOG2_E)*log2(c)-d; -float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; -return vec2(r,rcpPdf);} -vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) -{ -#ifndef SSS_BILATERAL_FILTER -z=0.; -#endif -float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; -#if SSS_CLAMP_ARTIFACT -return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); -#else -return EvalBurleyDiffusionProfile(r,S)*area; -#endif -} -void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, -float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) -{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; -float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; -vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; -float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) -{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} -else -{}} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) -{centerDepth=texture2D(depthSampler,vUV).r;} -if (!passedStencilTest) { -gl_FragColor=inputColor;return;} -float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; -vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; -float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) -{ -#ifdef DEBUG_SSS_SAMPLES -vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; -#endif -gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} -#ifdef DEBUG_SSS_SAMPLES -vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; -#endif -float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); -vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i<n; i++) -{EvaluateSample(i,n,S,d,centerPosVS,mmPerUnit,pixelsPerMm, -phase,totalIrradiance,totalWeight);} -totalWeight=max(totalWeight,HALF_MIN);gl_FragColor=vec4(inputColor.rgb+albedo*max(totalIrradiance/totalWeight,vec3(0.0)),1.);}`;no.v.ShadersStore.subSurfaceScatteringPixelShader=vV;class vk extends np{getClassName(){return"SubSurfaceScatteringPostProcess"}constructor(e,t,i,r=null,s,n,a,o=0){super(e,"subSurfaceScattering",["texelSize","viewportSize","metersPerUnit"],["diffusionS","diffusionD","filterRadii","irradianceSampler","depthSampler","albedoSampler"],i,r,s||sv.BILINEAR_SAMPLINGMODE,n,a,null,o,"postprocess",void 0,!0),this._scene=t,this.updateEffect(),this.onApplyObservable.add(e=>{if(!t.prePassRenderer||!t.subSurfaceConfiguration){ru.Y.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}let 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 vG{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=ss.l.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new rs.Wo(1,1,1)),this._scene=e,vG._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return ru.Y.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t<this._ssDiffusionS.length/3;t++)if(this._ssDiffusionS[3*t]===e.r&&this._ssDiffusionS[3*t+1]===e.g&&this._ssDiffusionS[3*t+2]===e.b)return t;return this._ssDiffusionS.push(e.r,e.b,e.g),this._ssDiffusionD.push(Math.max(Math.max(e.r,e.b),e.g)),this._ssFilterRadii.push(this.getDiffusionProfileParameters(e)),this.ssDiffusionProfileColors.push(e),this._ssDiffusionD.length-1}createPostProcess(){return this.postProcess=new vk("subSurfaceScattering",this._scene,1,null,void 0,this._scene.getEngine()),this.postProcess.autoClear=!1,this.postProcess}clearAllDiffusionProfiles(){this._ssDiffusionD=[],this._ssDiffusionS=[],this._ssFilterRadii=[],this.ssDiffusionProfileColors=[]}dispose(){this.clearAllDiffusionProfiles(),this.postProcess&&this.postProcess.dispose()}getDiffusionProfileParameters(e){let t=Math.max(e.r,e.g,e.b);return this._sampleBurleyDiffusionProfile(.997,t)}_sampleBurleyDiffusionProfile(e,t){e=1-e;let i=1+4*e*(2*e+Math.sqrt(1+4*e*e)),r=Math.pow(i,-1/3),s=3*Math.log((1+i*r*r+r)/(4*e));return s*t}}vG._SceneComponentInitialization=e=>{throw(0,st.S)("SubSurfaceSceneComponent")},re.p.AddParser(ss.l.NAME_SUBSURFACE,(e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,r=e.ssDiffusionProfileColors.length;i<r;i++){let r=e.ssDiffusionProfileColors[i];t.subSurfaceConfiguration.addDiffusionProfile(new rs.Wo(r.r,r.g,r.b))}}),Object.defineProperty(rI.x.prototype,"subSurfaceConfiguration",{get:function(){return this._subSurfaceConfiguration},set:function(e){e&&this.enablePrePassRenderer()&&(this._subSurfaceConfiguration=e)},enumerable:!0,configurable:!0}),rI.x.prototype.enableSubSurfaceForPrePass=function(){if(this._subSurfaceConfiguration)return this._subSurfaceConfiguration;let e=this.enablePrePassRenderer();return e?(this._subSurfaceConfiguration=new vG(this),e.addEffectConfiguration(this._subSurfaceConfiguration),this._subSurfaceConfiguration):null},rI.x.prototype.disableSubSurfaceForPrePass=function(){this._subSurfaceConfiguration&&(this._subSurfaceConfiguration.dispose(),this._subSurfaceConfiguration=null)};class vz{constructor(e){this.name=ss.l.NAME_PREPASSRENDERER,this.scene=e}register(){}serialize(e){if(!this.scene.subSurfaceConfiguration)return;let t=this.scene.subSurfaceConfiguration.ssDiffusionProfileColors;e.ssDiffusionProfileColors=[];for(let i=0;i<t.length;i++)e.ssDiffusionProfileColors.push({r:t[i].r,g:t[i].g,b:t[i].b})}addFromContainer(){}removeFromContainer(){this.scene.prePassRenderer&&this.scene.subSurfaceConfiguration&&this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles()}rebuild(){}dispose(){}}vG._SceneComponentInitialization=e=>{let t=e._getComponent(ss.l.NAME_SUBSURFACE);t||(t=new vz(e),e._addComponent(t))};let vW=`#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -uniform vec4 color; -#ifdef ALPHATEST -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include<clipPlaneFragmentDeclaration> -#include<logDepthDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include<clipPlaneFragment> -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -#include<logDepthFragment> -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;no.v.ShadersStore.outlinePixelShader=vW;let vH=`attribute vec3 position;attribute vec3 normal; -#include<bonesDeclaration> -#include<bakedVertexAnimationDeclaration> -#include<morphTargetsVertexGlobalDeclaration> -#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets] -#include<clipPlaneVertexDeclaration> -uniform float offset; -#include<instancesDeclaration> -uniform mat4 viewProjection; -#ifdef ALPHATEST -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#include<logDepthDeclaration> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position;vec3 normalUpdated=normal; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include<morphTargetsVertexGlobal> -#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets] -vec3 offsetPosition=positionUpdated+(normalUpdated*offset); -#include<instancesVertex> -#include<bonesVertex> -#include<bakedVertexAnimation> -vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; -#ifdef ALPHATEST -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#include<clipPlaneVertex> -#include<logDepthVertex> -} -`;no.v.ShadersStore.outlineVertexShader=vH,rI.x.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new vX(this)),this._outlineRenderer},Object.defineProperty(rq.Kj.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(rq.Kj.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class vX{constructor(e){this.name=ss.l.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(ss.l.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(ss.l.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e<this._passIdForDrawWrapper.length;++e)this._engine.releaseRenderPassId(this._passIdForDrawWrapper[e])}render(e,t,i=!1,r){r=null!=r?r:this._passIdForDrawWrapper[0];let s=this.scene,n=s.getEngine(),a=n.getCaps().instancedArrays&&(null!==t.visibleInstances[e._id]&&void 0!==t.visibleInstances[e._id]||e.getRenderingMesh().hasThinInstances);if(!this.isReady(e,a,r))return;let o=e.getMesh(),l=o._internalAbstractMeshDataInfo._actAsRegularMesh?o:null,h=e.getRenderingMesh(),u=l||h,c=e.getMaterial();if(!c||!s.activeCamera)return;let d=e._getDrawWrapper(r),p=nc.q.GetEffect(d);if(n.enableEffect(d),c.useLogarithmicDepth&&p.setFloat("logarithmicDepthConstant",2/(Math.log(s.activeCamera.maxZ+1)/Math.LN2)),p.setFloat("offset",i?0:h.outlineWidth),p.setColor4("color",i?h.overlayColor:h.outlineColor,i?h.overlayAlpha:c.alpha),p.setMatrix("viewProjection",s.getTransformMatrix()),p.setMatrix("world",u.getWorldMatrix()),h.useBones&&h.computeBonesUsingShaders&&h.skeleton&&p.setMatrices("mBones",h.skeleton.getTransformMatrices(h)),h.morphTargetManager&&h.morphTargetManager.isUsingTextureForTargets&&h.morphTargetManager._bind(p),s3.G.BindMorphTargetParameters(h,p),a||h._bind(e,p,c.fillMode),c&&c.needAlphaTesting()){let e=c.getAlphaTestTexture();e&&(p.setTexture("diffuseSampler",e),p.setMatrix("diffuseMatrix",e.getTextureMatrix()))}(0,lx.an)(p,c,s),n.setZOffset(-this.zOffset),n.setZOffsetUnits(-this.zOffsetUnits),h._processRendering(u,e,p,c.fillMode,t,a,(e,t)=>{p.setMatrix("world",t)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];let r=[],s=[rQ.o.PositionKind,rQ.o.NormalKind],n=e.getMesh(),a=e.getMaterial();if(!a)return!1;let o=n.getScene();a.needAlphaTesting()&&(r.push("#define ALPHATEST"),n.isVerticesDataPresent(rQ.o.UVKind)&&(s.push(rQ.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(rQ.o.UV2Kind)&&(s.push(rQ.o.UV2Kind),r.push("#define UV2"))),a.useLogarithmicDepth&&r.push("#define LOGARITHMICDEPTH"),(0,lx.lK)(a,o,r),n.useBones&&n.computeBonesUsingShaders?(s.push(rQ.o.MatricesIndicesKind),s.push(rQ.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(rQ.o.MatricesIndicesExtraKind),s.push(rQ.o.MatricesWeightsExtraKind)),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");let l=n.morphTargetManager,h=0;l&&l.numInfluencers>0&&(h=l.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),s3.G.PrepareAttributesForMorphTargetsInfluencers(s,n,h)),t&&(r.push("#define INSTANCES"),s3.G.PushAttributesForInstances(s),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));let u=e._getDrawWrapper(i,!0),c=u.defines,d=r.join("\n");if(c!==d){let e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,lx.qx)(e),u.setEffect(this.scene.getEngine().createEffect("outline",s,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return u.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){let r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(vX._StencilReference),this._engine.setStencilFunctionReference(vX._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){let e=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}vX._StencilReference=4,i(9623);class vY{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 ri.y$,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){let 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 nF({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new nF({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;let e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){let e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;let 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(){let e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;let 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 vj extends vY{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 vq{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){let 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,r,s,n,a=1,o=6,l=1,h=6,u=!1,c=null,d=!0,p=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 ri.y$,this._name=e,this._scene=t,this._camera=c,this._engine=t.getEngine(),this._width=i,this._height=r,this._blurTextureSizeX=s,this._blurTextureSizeY=n,this._textureType=a,this._textureFormat=o,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=u,this._generateDepthBuffer=d,this._samples=p,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==n,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){let[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}`});let e=this._rt.texture;e.incrementReferences(),this._texture=new sv(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=sv.CLAMP_ADDRESSMODE,this._texture.wrapV=sv.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,r,s,n=!1){let a=this._scene.getEngine(),o=new rr.FM(Math.floor(this._blurTextureSizeX/r),Math.floor(this._blurTextureSizeY/r)),l=1===t&&a.getCaps().textureFloatLinearFiltering||2===t&&a.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:o.x,height:o.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${s}`}),u=h.texture;u.incrementReferences();let c=new sv(null,this._scene);if(c.name="rttBlurred"+s,c._texture=u,c.wrapU=sv.CLAMP_ADDRESSMODE,c.wrapV=sv.CLAMP_ADDRESSMODE,c.anisotropicFilteringLevel=1,n){let r=new np("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),r.onSizeChangedObservable.add(()=>{r._textures.forEach(e=>{e.texture.wrapU=sv.CLAMP_ADDRESSMODE,e.texture.wrapV=sv.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(r);let s=new np("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=sv.CLAMP_ADDRESSMODE,e.texture.wrapV=sv.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s),r.autoClear=!1,s.autoClear=!1;let n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?s:r;return[h,c,n]}{let r=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],s=new np("BilateralBlurX","fluidRenderingBilateralBlur",r,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=sv.CLAMP_ADDRESSMODE,e.texture.wrapV=sv.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s);let n=new np("BilateralBlurY","fluidRenderingBilateralBlur",r,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.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++}),n.onSizeChangedObservable.add(()=>{n._textures.forEach(e=>{e.texture.wrapU=sv.CLAMP_ADDRESSMODE,e.texture.wrapV=sv.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(n),s.autoClear=!1,n.autoClear=!1;let o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?n:s;return[h,c,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,r;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===(r=this._textureBlurred)||void 0===r||r.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}(e9=i3||(i3={}))[e9.DepthTexture=0]="DepthTexture",e9[e9.DepthBlurredTexture=1]="DepthBlurredTexture",e9[e9.ThicknessTexture=2]="ThicknessTexture",e9[e9.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e9[e9.DiffuseTexture=4]="DiffuseTexture",e9[e9.Normals=5]="Normals",e9[e9.DiffuseRendering=6]="DiffuseRendering";class vK{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 rs.Wo(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new rr.P(-2,-1,1).normalize(),this._debugFeature=i3.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 ri.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 rr.y3,this._depthClearColor=new rs.HE(1e6,1e6,1e6,1),this._thicknessClearColor=new rs.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;let r=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 vq("Depth",this._scene,r,s,r,s,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){let 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 vq("Diffuse",this._scene,e,i,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}let n=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),a=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new vq("Thickness",this._scene,n,a,n,a,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;let t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],r=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;let n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new rr.FM(1/n.getSize().width,1/n.getSize().height);if(this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap){let t=null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture;t&&(r.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT"))}this._diffuseRenderTarget?(r.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(r.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),r.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),r.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===i3.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===i3.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),r.push("debugSampler"),(this._debugFeature===i3.DepthTexture||this._debugFeature===i3.DepthBlurredTexture)&&s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new np("FluidRendering","fluidRenderingRender",i,r,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,r,s,n,o,l,h,u,c,d,p,_,f,m,g,v,T,x,S,E,C,b,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!==(n=null===(s=this._depthRenderTarget.textureBlur)||void 0===s?void 0:s.getInternalTexture())&&void 0!==n?n:null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(r=null===(i=this._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==r?r:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(u=null===(h=this._diffuseRenderTarget.textureBlur)||void 0===h?void 0:h.getInternalTexture())&&void 0!==u?u: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!==(c=this._bgDepthTexture)&&void 0!==c?c:null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(f=null===(_=this._thicknessRenderTarget.textureBlur)||void 0===_?void 0:_.getInternalTexture())&&void 0!==f?f:null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(p=null===(d=this._thicknessRenderTarget.texture)||void 0===d?void 0:d.getInternalTexture())&&void 0!==p?p:null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){let 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 i3.DepthTexture:i=this._depthRenderTarget.texture;break;case i3.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case i3.ThicknessTexture:i=null!==(T=null===(v=this._thicknessRenderTarget)||void 0===v?void 0:v.texture)&&void 0!==T?T:null;break;case i3.ThicknessBlurredTexture:i=(null===(x=this._thicknessRenderTarget)||void 0===x?void 0:x.enableBlur)?null!==(E=null===(S=this._thicknessRenderTarget)||void 0===S?void 0:S.textureBlur)&&void 0!==E?E:null:null!==(b=null===(C=this._thicknessRenderTarget)||void 0===C?void 0:C.texture)&&void 0!==b?b:null;break;case i3.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==i3.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,r,s,n,a;if(this._needInitialization||!e.isReady())return;let o=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===(r=this._thicknessRenderTarget)||void 0===r?void 0:r.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===(n=this._diffuseRenderTarget)||void 0===n||n.applyBlurPostProcesses(),null===(a=this._thicknessRenderTarget)||void 0===a||a.applyBlurPostProcesses(),o&&this._engine.bindFramebuffer(o)}dispose(e=!1){var t,i,r,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===(r=this._thicknessRenderTarget)||void 0===r||r.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 v$ extends vY{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(let t in e){let i;let r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1}this._vertexBuffers[t]=new rQ.o(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new nF({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 rQ.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(){let e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;let 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;for(let t in super.dispose(),null===(e=this._diffuseEffectWrapper)||void 0===e||e.dispose(),this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}let vQ=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; -#include<helperFunctions> -void main(void) -{vec4 color=texture2D(textureSampler,vUV); -#ifdef DEPTH_TEXTURE -gl_FragDepth=color.r; -#else -if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} -gl_FragColor=color; -#endif -} -`;no.v.ShadersStore.copyTextureToTexturePixelShader=vQ,(te=i4||(i4={}))[te.None=0]="None",te[te.ToLinearSpace=1]="ToLinearSpace",te[te.ToGammaSpace=2]="ToGammaSpace";class vZ{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new nN(e),this._effectWrapper=new nF({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=i4.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;let r=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&r&&(this._engine.depthCullingState.depthFunc=r),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class vJ{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new vZ(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil")}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}let v0=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; -#ifdef FLUIDRENDERING_VELOCITY -attribute vec3 velocity;varying float velocityNorm; -#endif -void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; -#ifdef FLUIDRENDERING_VELOCITY -velocityNorm=length(velocity); -#endif -} -`;no.v.ShadersStore.fluidRenderingParticleDepthVertexShader=v0;let v1=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; -#ifdef FLUIDRENDERING_VELOCITY -varying float velocityNorm; -#endif -void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); -#ifndef FLUIDRENDERING_RHS -normal.z=-normal.z; -#endif -vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; -#ifdef WEBGPU -gl_FragDepth=clipSpacePos.z/clipSpacePos.w; -#else -gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; -#endif -#ifdef FLUIDRENDERING_RHS -realViewPos.z=-realViewPos.z; -#endif -#ifdef FLUIDRENDERING_VELOCITY -glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); -#else -glFragColor=vec4(realViewPos.z,0.,0.,1.); -#endif -} -`;no.v.ShadersStore.fluidRenderingParticleDepthPixelShader=v1;let v2=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} -`;no.v.ShadersStore.fluidRenderingParticleThicknessVertexShader=v2;let v3=`uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} -`;no.v.ShadersStore.fluidRenderingParticleThicknessPixelShader=v3;let v4=`attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} -`;no.v.ShadersStore.fluidRenderingParticleDiffuseVertexShader=v4;let v5=`uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} -`;no.v.ShadersStore.fluidRenderingParticleDiffusePixelShader=v5;let v6=`uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} -int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} -glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} -`;no.v.ShadersStore.fluidRenderingBilateralBlurPixelShader=v6;let v8=`uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} -float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} -sum/=wsum;glFragColor=vec4(sum.rgb,1.);} -`;no.v.ShadersStore.fluidRenderingStandardBlurPixelShader=v8;let v7=`/* disable_uniformity_analysis */ -#define IOR 1.333 -#define ETA 1.0/IOR -#define F0 0.02 -uniform sampler2D textureSampler;uniform sampler2D depthSampler; -#ifdef FLUIDRENDERING_DIFFUSETEXTURE -uniform sampler2D diffuseSampler; -#else -uniform vec3 diffuseColor; -#endif -#ifdef FLUIDRENDERING_FIXED_THICKNESS -uniform float thickness;uniform sampler2D bgDepthSampler; -#else -uniform float minimumThickness;uniform sampler2D thicknessSampler; -#endif -#ifdef FLUIDRENDERING_ENVIRONMENT -uniform samplerCube reflectionSampler; -#endif -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) -uniform sampler2D debugSampler; -#endif -uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; -#ifdef FLUIDRENDERING_RHS -ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; -#else -ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; -#endif -ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} -vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} -void main(void) {vec2 texCoord=vUV; -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) -vec4 color=texture2D(debugSampler,texCoord); -#ifdef FLUIDRENDERING_DEBUG_DEPTH -glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} -#else -glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} -#endif -return; -#endif -vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; -#ifndef FLUIDRENDERING_FIXED_THICKNESS -float thickness=texture2D(thicknessSampler,texCoord).x; -#else -float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; -#endif -vec4 backColor=texture2D(textureSampler,texCoord); -#ifndef FLUIDRENDERING_FIXED_THICKNESS -if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { -#else -if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { -#endif -glFragColor=backColor;return;} -vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} -vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} -vec3 normal=normalize(cross(ddy,ddx)); -#ifdef FLUIDRENDERING_RHS -normal=-normal; -#endif -#ifndef WEBGPU -if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} -#endif -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) -glFragColor=vec4(normal*0.5+0.5,1.0);return; -#endif -vec3 rayDir=normalize(viewPos); -#ifdef FLUIDRENDERING_DIFFUSETEXTURE -vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; -#endif -vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); -#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING -float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; -#endif -vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); -vec3 refractionColor=transmitted.rgb*transmittance; -#ifdef FLUIDRENDERING_ENVIRONMENT -vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; -#else -vec3 finalColor=refractionColor+specular; -#endif -#ifdef FLUIDRENDERING_VELOCITY -float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); -#endif -glFragColor=vec4(finalColor,transmitted.a);} -`;no.v.ShadersStore.fluidRenderingRenderPixelShader=v7,Object.defineProperty(rI.x.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),rI.x.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new Te(this)),this._fluidRenderer},rI.x.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};class v9{constructor(e){this.name=ss.l.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(ss.l.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(ss.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 Te{static _SceneComponentInitialization(e){let t=e._getComponent(ss.l.NAME_FLUIDRENDERER);t||(t=new v9(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,Te._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add(()=>{this._initialize()})}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){let t=this._getParticleSystemIndex(e);return -1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){let s=new vj(this._scene,e);s.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)),i||(i=new vK(this._scene,r),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)),void 0!==t&&(i.generateDiffuseTexture=t);let n={object:s,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,r,s){let n=new v$(this._scene,e,t);n.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)),r||(r=new vK(this._scene,s),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)),void 0!==i&&(r.generateDiffuseTexture=i);let a={object:n,targetRenderer:r};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}removeRenderObject(e,t=!0){let 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.priority<t.object.priority?-1:e.object.priority>t.object.priority?1:0)}_removeUnusedTargetRenderers(){let e={};for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t].targetRenderer;e[this.targetRenderers.indexOf(i)]=!0}let t=!1,i=[];for(let r=0;r<this.targetRenderers.length;++r)e[r]?i.push(this.targetRenderers[r]):(this.targetRenderers[r].dispose(),t=!0);return t&&(this.targetRenderers.length=0,this.targetRenderers.push(...i)),t}_getParticleSystemIndex(e){for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t].object;if(i.particleSystem&&i.particleSystem===e)return t}return -1}_initialize(){for(let e=0;e<this.targetRenderers.length;++e)this.targetRenderers[e].dispose();let e=new Map;for(let t=0;t<this.targetRenderers.length;++t){let i=this.targetRenderers[t];if(i._initialize(),i.camera&&i._renderPostProcess){let r=e.get(i.camera);r||(r=[[],{}],e.set(i.camera,r)),r[0].push(i),i.camera.attachPostProcess(i._renderPostProcess,t)}}let t=e.keys();for(let i=t.next();!0!==i.done;i=t.next()){let t=i.value,r=e.get(t),s=t._getFirstPostProcess();if(!s)continue;let[n,a]=r;s.onSizeChangedObservable.add(()=>{var e;for(let t of(s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`),n)){let i=null===(e=t._thicknessRenderTarget)||void 0===e?void 0:e.renderTarget,r=null==i?void 0:i.texture;if(i&&r){let e=r.width+"_"+r.height,t=a[e];t||(t=a[e]=new vJ(this._engine,r.width,r.height)),t.depthRTWrapper._shareDepth(i)}}})}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){let t=i.value,r=this._cameras.get(t),s=r[1],n=e.get(t);if(n)for(let e in s)n[1][e]||s[e].dispose();else for(let e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){let e=new Map;for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t],r=e.get(i.targetRenderer);void 0===r&&(r=0),e.set(i.targetRenderer,Math.max(r,i.object.particleSize))}e.forEach((e,t)=>{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)})}_setUseVelocityForRenderObject(){for(let e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(let e of this.targetRenderers)if(e.needInitialization){this._initialize();return}}_render(e){var t;for(let t=0;t<this.targetRenderers.length;++t)e&&this.targetRenderers[t].camera!==e||this.targetRenderers[t]._clearTargets();let i=this._cameras.keys();for(let r=i.next();!0!==r.done;r=i.next()){let i=r.value,s=this._cameras.get(i);if(e&&i!==e)continue;let n=i._getFirstPostProcess();if(!n)continue;let a=null===(t=n.inputTexture)||void 0===t?void 0:t.depthStencilTexture;if(a){let[e,t]=s;for(let t of e)t._bgDepthTexture=a;for(let e in t)t[e].copy(a)}}for(let t=0;t<this.renderObjects.length;++t){let i=this.renderObjects[t];e&&i.targetRenderer.camera!==e||i.targetRenderer._render(i.object)}}dispose(){this._engine.onResizeObservable.remove(this._onEngineResizeObserver),this._onEngineResizeObserver=null;for(let e=0;e<this.renderObjects.length;++e)this.renderObjects[e].object.dispose();for(let e=0;e<this.targetRenderers.length;++e)this.targetRenderers[e].dispose();this._cameras.forEach(e=>{let t=e[1];for(let e in t)t[e].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class Tt{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,e<t?this._direction=1:(this._direction=-1,this._toIndex=e,this._fromIndex=t),this.cellIndex=e,this._time=0}stopAnimation(){this._animationStarted=!1}_animate(e){this._animationStarted&&(this._time+=e,this._time>this._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex<this._fromIndex)&&(this._loopAnimation?this.cellIndex=this._direction>0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class Ti extends Tt{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=[],this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new ri.y$,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new rs.HE(1,1,1,1),this.position=rr.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,r,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e<this._manager.sprites.length;e++)this._manager.sprites[e]==this&&this._manager.sprites.splice(e,1);this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}serialize(){let e={};return e.name=this.name,e.position=this.position.asArray(),e.color=this.color.asArray(),e.width=this.width,e.height=this.height,e.angle=this.angle,e.cellIndex=this.cellIndex,e.cellRef=this.cellRef,e.invertU=this.invertU,e.invertV=this.invertV,e.disposeWhenFinishedAnimating=this.disposeWhenFinishedAnimating,e.isPickable=this.isPickable,e.isVisible=this.isVisible,e.useAlphaForPicking=this.useAlphaForPicking,e.animationStarted=this.animationStarted,e.fromIndex=this.fromIndex,e.toIndex=this.toIndex,e.loopAnimation=this.loopAnimation,e.delay=this.delay,e}static Parse(e,t){let i=new Ti(e.name,t);return i.position=rr.P.FromArray(e.position),i.color=rs.HE.FromArray(e.color),i.width=e.width,i.height=e.height,i.angle=e.angle,i.cellIndex=e.cellIndex,i.cellRef=e.cellRef,i.invertU=e.invertU,i.invertV=e.invertV,i.disposeWhenFinishedAnimating=e.disposeWhenFinishedAnimating,i.isPickable=e.isPickable,i.isVisible=e.isVisible,i.useAlphaForPicking=e.useAlphaForPicking,i._fromIndex=e.fromIndex,i._toIndex=e.toIndex,i._loopAnimation=e.loopAnimation,i._delay=e.delay,e.animationStarted&&i.playAnimation(i.fromIndex,i.toIndex,i.loopAnimation,i.delay),i}}rI.x.prototype._internalPickSprites=function(e,t,i,r){if(!sI.p)return null;let s=null;if(!r){if(!this.activeCamera)return null;r=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let n=0;n<this.spriteManagers.length;n++){let a=this.spriteManagers[n];if(!a.isPickable)continue;let o=a.intersects(e,r,t,i);if(o&&o.hit&&(i||null==s||!(o.distance>=s.distance))&&(s=o,i))break}return s||new sI.p},rI.x.prototype._internalMultiPickSprites=function(e,t,i){if(!sI.p)return null;let r=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s<this.spriteManagers.length;s++){let n=this.spriteManagers[s];if(!n.isPickable)continue;let a=n.multiIntersects(e,i,t);null!==a&&(r=r.concat(a))}return r},rI.x.prototype.pickSprite=function(e,t,i,r,s){if(!this._tempSpritePickingRay)return null;this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,s);let n=this._internalPickSprites(this._tempSpritePickingRay,i,r,s);return n&&(n.ray=this.createPickingRayInCameraSpace(e,t,s)),n},rI.x.prototype.pickSpriteWithRay=function(e,t,i,r){if(!this._tempSpritePickingRay)return null;if(!r){if(!this.activeCamera)return null;r=this.activeCamera}sD.TransformToRef(e,r.getViewMatrix(),this._tempSpritePickingRay);let s=this._internalPickSprites(this._tempSpritePickingRay,t,i,r);return s&&(s.ray=e),s},rI.x.prototype.multiPickSprite=function(e,t,i,r){return this.createPickingRayInCameraSpaceToRef(e,t,this._tempSpritePickingRay,r),this._internalMultiPickSprites(this._tempSpritePickingRay,i,r)},rI.x.prototype.multiPickSpriteWithRay=function(e,t,i){if(!this._tempSpritePickingRay)return null;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}return sD.TransformToRef(e,i.getViewMatrix(),this._tempSpritePickingRay),this._internalMultiPickSprites(this._tempSpritePickingRay,t,i)},rI.x.prototype.setPointerOverSprite=function(e){this._pointerOverSprite!==e&&(this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(10,ro.V.CreateNewFromSprite(this._pointerOverSprite,this)),this._pointerOverSprite=e,this._pointerOverSprite&&this._pointerOverSprite.actionManager&&this._pointerOverSprite.actionManager.processTrigger(9,ro.V.CreateNewFromSprite(this._pointerOverSprite,this)))},rI.x.prototype.getPointerOverSprite=function(){return this._pointerOverSprite};class Tr{constructor(e){this.name=ss.l.NAME_SPRITE,this.scene=e,this.scene.spriteManagers=[],this.scene._tempSpritePickingRay=sD?sD.Zero():null,this.scene.onBeforeSpritesRenderingObservable=new ri.y$,this.scene.onAfterSpritesRenderingObservable=new ri.y$,this._spritePredicate=e=>!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(ss.l.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(ss.l.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(ss.l.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();let e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,s){let n=this.scene.pickSprite(t,i,this._spritePredicate,r,s);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,r,s){let n=this.scene;return r?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&s&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,r){let s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,ro.V.CreateNewFromSprite(i.pickedSprite,s,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,ro.V.CreateNewFromSprite(i.pickedSprite,s,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,ro.V.CreateNewFromSprite(i.pickedSprite,s,r))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,ro.V.CreateNewFromSprite(i.pickedSprite,s,r))}return i}_pointerUp(e,t,i,r,s){let n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){let i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,ro.V.CreateNewFromSprite(i.pickedSprite,n,r)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,ro.V.CreateNewFromSprite(i.pickedSprite,n,r)),s&&i.pickedSprite.actionManager.processTrigger(6,ro.V.CreateNewFromSprite(i.pickedSprite,n,r)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,ro.V.CreateNewFromSprite(n._pickedDownSprite,n,r)))}return i}}let Ts=`#ifdef IMAGEPROCESSINGPOSTPROCESS -gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); -#endif -`;no.v.IncludesShadersStore.imageProcessingCompatibility=Ts;let Tn=`uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; -#include<fogFragmentDeclaration> -#define CUSTOM_FRAGMENT_DEFINITIONS -#ifdef PIXEL_PERFECT -vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} -#endif -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#ifdef PIXEL_PERFECT -vec2 uv=uvPixelPerfect(vUV); -#else -vec2 uv=vUV; -#endif -vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) -{if (color.a<0.95) -discard;} -color*=vColor; -#include<fogFragment> -gl_FragColor=color; -#include<imageProcessingCompatibility> -#define CUSTOM_FRAGMENT_MAIN_END -}`;no.v.ShadersStore.spritesPixelShader=Tn;let Ta=`attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; -#include<fogVertexDeclaration> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; -vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); -vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; -#ifdef FOG -vFogDistance=viewPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.spritesVertexShader=Ta;class To{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,r=null){let s;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=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new rQ.l(e,this._vertexData,!0,this._vertexBufferSize);let n=this._buffer.createVertexBuffer(rQ.o.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),a=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing),o=6;if(this._useInstancing){let t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new rQ.l(e,t,!1,2),s=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else s=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;let l=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer(rQ.o.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[rQ.o.PositionKind]=n,this._vertexBuffers.options=a,this._vertexBuffers.offsets=s,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[rQ.o.ColorKind]=u,this._createEffects()}_createEffects(){var e,t,i,r;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===(r=this._drawWrapperFogDepth)||void 0===r||r.dispose(),this._drawWrapperBase=new nc.q(this._engine),this._drawWrapperFog=new nc.q(this._engine),this._drawWrapperDepth=new nc.q(this._engine,!1),this._drawWrapperFogDepth=new nc.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);let s=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[rQ.o.PositionKind,"options","offsets","inverts","cellInfo",rQ.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",[rQ.o.PositionKind,"options","offsets","inverts","cellInfo",rQ.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,r,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let n=this._drawWrapperBase,a=this._drawWrapperDepth,o=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(n=this._drawWrapperFog,a=this._drawWrapperFogDepth,o=!0);let l=n.effect;if(!l.isReady())return;let h=this._engine,u=!!(this._scene&&this._scene.useRightHandedSystem),c=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length),p=0,_=!0;for(let i=0;i<d;i++){let r=e[i];r&&r.isVisible&&(_=!1,r._animate(t),this._appendSpriteVertex(p++,r,0,0,c,u,s),this._useInstancing||(this._appendSpriteVertex(p++,r,1,0,c,u,s),this._appendSpriteVertex(p++,r,1,1,c,u,s),this._appendSpriteVertex(p++,r,0,1,c,u,s)))}if(_)return;this._buffer.update(this._vertexData);let f=!!h.depthCullingState.cull,m=h.depthCullingState.zOffset,g=h.depthCullingState.zOffsetUnits;if(h.setState(f,m,!1,!1,void 0,void 0,g),h.enableEffect(n),l.setTexture("diffuseSampler",this.texture),l.setMatrix("view",i),l.setMatrix("projection",r),o){let e=this._scene;l.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),l.setColor3("vFogColor",e.fogColor)}this._useVAO?(this._vertexArrayObject||(this._vertexArrayObject=h.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,l)),h.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):h.bindBuffers(this._vertexBuffers,this._indexBuffer,l),h.depthCullingState.depthFunc=h.useReverseDepthBuffer?518:515,this.disableDepthWrite||(l.setBool("alphaTest",!0),h.setColorWrite(!1),h.enableEffect(a),this._useInstancing?h.drawArraysType(7,0,4,p):h.drawElementsType(0,0,p/4*6),h.enableEffect(n),h.setColorWrite(!0),l.setBool("alphaTest",!1)),h.setAlphaMode(this.blendMode),this._useInstancing?h.drawArraysType(7,0,4,p):h.drawElementsType(0,0,p/4*6),this.autoResetAlpha&&h.setAlphaMode(0),u&&this._scene.getEngine().setState(f,m,!1,!0,void 0,void 0,g),h.unbindInstanceAttributes()}_appendSpriteVertex(e,t,i,r,s,n,a){let o=e*this._vertexBufferSize;if(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon),a)a(t,s);else{t.cellIndex||(t.cellIndex=0);let e=s.width/this.cellWidth,i=t.cellIndex/e>>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[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._useInstancing?o-=2:(this._vertexData[o+6]=i,this._vertexData[o+7]=r),n?this._vertexData[o+8]=t.invertU?0:1:this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0,this._vertexData[o+10]=t._xOffset,this._vertexData[o+11]=t._yOffset,this._vertexData[o+12]=t._xSize/s.width,this._vertexData[o+13]=t._ySize/s.height,this._vertexData[o+14]=t.color.r,this._vertexData[o+15]=t.color.g,this._vertexData[o+16]=t.color.b,this._vertexData[o+17]=t.color.a}_buildIndexBuffer(){let e=[],t=0;for(let i=0;i<this._capacity;i++)e.push(t),e.push(t+1),e.push(t+2),e.push(t),e.push(t+2),e.push(t+3),t+=4;this._indexBuffer=this._engine.createIndexBuffer(e)}rebuild(){var e;for(let e in this._indexBuffer&&this._buildIndexBuffer(),this._useVAO&&(this._vertexArrayObject=void 0),this._buffer._rebuild(),this._vertexBuffers){let t=this._vertexBuffers[e];t._rebuild()}null===(e=this._spriteBuffer)||void 0===e||e._rebuild()}dispose(){this._buffer&&(this._buffer.dispose(),this._buffer=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),this.texture&&(this.texture.dispose(),this.texture=null),this._drawWrapperBase.dispose(),this._drawWrapperFog.dispose(),this._drawWrapperDepth.dispose(),this._drawWrapperFogDepth.dispose()}}class Tl{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get children(){return this.sprites}get scene(){return this._scene}get capacity(){return this._spriteRenderer.capacity}get texture(){return this._spriteRenderer.texture}set texture(e){e.wrapU=sv.CLAMP_ADDRESSMODE,e.wrapV=sv.CLAMP_ADDRESSMODE,this._spriteRenderer.texture=e,this._textureContent=null}get cellWidth(){return this._spriteRenderer.cellWidth}set cellWidth(e){this._spriteRenderer.cellWidth=e}get cellHeight(){return this._spriteRenderer.cellHeight}set cellHeight(e){this._spriteRenderer.cellHeight=e}get fogEnabled(){return this._spriteRenderer.fogEnabled}set fogEnabled(e){this._spriteRenderer.fogEnabled=e}get blendMode(){return this._spriteRenderer.blendMode}set blendMode(e){this._spriteRenderer.blendMode=e}get disableDepthWrite(){return this._disableDepthWrite}set disableDepthWrite(e){this._disableDepthWrite=e,this._spriteRenderer.disableDepthWrite=e}get pixelPerfect(){return this._spriteRenderer.pixelPerfect}set pixelPerfect(e){this._spriteRenderer.pixelPerfect=e,e&&3!==this.texture.samplingMode&&this.texture.updateSamplingMode(3)}constructor(e,t,i,r,s,n=.01,a=sv.TRILINEAR_SAMPLINGMODE,o=!1,l=null){this.name=e,this.sprites=[],this.renderingGroupId=0,this.layerMask=268435455,this.isPickable=!1,this.metadata=null,this._wasDispatched=!1,this.onDisposeObservable=new ri.y$,this._disableDepthWrite=!1,this._packedAndReady=!1,this._customUpdate=(e,t)=>{e.cellRef||(e.cellIndex=0);let 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=rp.l.LastCreatedScene),s._getComponent(ss.l.NAME_SPRITE)||s._addComponent(new Tr(s)),this._fromPacked=o,this._scene=s;let h=this._scene.getEngine();if(this._spriteRenderer=new To(h,i,n,s),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else if(void 0!==r)this.cellWidth=r,this.cellHeight=r;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new sv(t,s,!0,!1,a)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if((e="string"==typeof t?JSON.parse(t):t).frames.length){let t={};for(let i=0;i<e.frames.length;i++){let r=e.frames[i];if("string"!=typeof Object.keys(r)[0])throw Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter.");let s=r[Object.keys(r)[0]];t[s]=r}e.frames=t}let i=Reflect.ownKeys(e.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=e.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,Error("Invalid JSON from string. Spritesheet managed with constant cell size.")}else{let t;let i=/\./g;do t=i.lastIndex,i.test(e);while(i.lastIndex>0);let r=e.substring(0,t-1)+".json";rZ.w1.LoadFile(r,e=>{try{let t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,Error("Invalid JSON format. Please check documentation for format specifications.")}},void 0,void 0,!1,()=>{ru.Y.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1})}}_checkTextureAlpha(e,t,i,r,s){if(!e.useAlphaForPicking||!this.texture)return!0;let n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));let a=rr.jp.Vector3[0];a.copyFrom(t.direction),a.normalize(),a.scaleInPlace(i),a.addInPlace(t.origin);let o=(a.x-r.x)/(s.x-r.x),l=1-(a.y-r.y)/(s.y-r.y),h=e._xOffset*n.width+o*e._xSize|0,u=e._yOffset*n.height+l*e._ySize|0,c=this._textureContent[(h+u*n.width)*4+3];return c>.5}intersects(e,t,i,r){let s=Math.min(this.capacity,this.sprites.length),n=rr.P.Zero(),a=rr.P.Zero(),o=Number.MAX_VALUE,l=null,h=rr.jp.Vector3[0],u=rr.jp.Vector3[1],c=t.getViewMatrix(),d=e,p=e;for(let t=0;t<s;t++){let s=this.sprites[t];if(s){if(i){if(!i(s))continue}else if(!s.isPickable)continue;if(rr.P.TransformCoordinatesToRef(s.position,c,u),s.angle?(rr.y3.TranslationToRef(-u.x,-u.y,0,rr.jp.Matrix[1]),rr.y3.TranslationToRef(u.x,u.y,0,rr.jp.Matrix[2]),rr.y3.RotationZToRef(-s.angle,rr.jp.Matrix[3]),rr.jp.Matrix[1].multiplyToRef(rr.jp.Matrix[3],rr.jp.Matrix[4]),rr.jp.Matrix[4].multiplyToRef(rr.jp.Matrix[2],rr.jp.Matrix[0]),d=e.clone(),rr.P.TransformCoordinatesToRef(e.origin,rr.jp.Matrix[0],d.origin),rr.P.TransformNormalToRef(e.direction,rr.jp.Matrix[0],d.direction)):d=e,n.copyFromFloats(u.x-s.width/2,u.y-s.height/2,u.z),a.copyFromFloats(u.x+s.width/2,u.y+s.height/2,u.z),d.intersectsBoxMinMax(n,a)){let e=rr.P.Distance(u,d.origin);if(o>e){if(!this._checkTextureAlpha(s,d,e,n,a))continue;if(p=d,o=e,l=s,r)break}}}}if(l){let e=new sI.p;c.invertToRef(rr.jp.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=o;let t=rr.jp.Vector3[2];return t.copyFrom(p.direction),t.normalize(),t.scaleInPlace(o),p.origin.addToRef(t,h),e.pickedPoint=rr.P.TransformCoordinates(h,rr.jp.Matrix[0]),e}return null}multiIntersects(e,t,i){let r;let s=Math.min(this.capacity,this.sprites.length),n=rr.P.Zero(),a=rr.P.Zero(),o=[],l=rr.jp.Vector3[0].copyFromFloats(0,0,0),h=rr.jp.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix();for(let t=0;t<s;t++){let s=this.sprites[t];if(s){if(i){if(!i(s))continue}else if(!s.isPickable)continue;if(rr.P.TransformCoordinatesToRef(s.position,u,h),n.copyFromFloats(h.x-s.width/2,h.y-s.height/2,h.z),a.copyFromFloats(h.x+s.width/2,h.y+s.height/2,h.z),e.intersectsBoxMinMax(n,a)){if(r=rr.P.Distance(h,e.origin),!this._checkTextureAlpha(s,e,r,n,a))continue;let t=new sI.p;o.push(t),u.invertToRef(rr.jp.Matrix[0]),t.hit=!0,t.pickedSprite=s,t.distance=r;let i=rr.jp.Vector3[2];i.copyFrom(e.direction),i.normalize(),i.scaleInPlace(r),e.origin.addToRef(i,l),t.pickedPoint=rr.P.TransformCoordinates(l,rr.jp.Matrix[0])}}}return o}render(){if(this._fromPacked&&(!this._packedAndReady||!this._spriteMap||!this._cellData))return;let e=this._scene.getEngine(),t=e.getDeltaTime();this._packedAndReady?this._spriteRenderer.render(this.sprites,t,this._scene.getViewMatrix(),this._scene.getProjectionMatrix(),this._customUpdate):this._spriteRenderer.render(this.sprites,t,this._scene.getViewMatrix(),this._scene.getProjectionMatrix())}rebuild(){var e;null===(e=this._spriteRenderer)||void 0===e||e.rebuild()}dispose(){if(this._spriteRenderer&&(this._spriteRenderer.dispose(),this._spriteRenderer=null),this._textureContent=null,this._scene.spriteManagers){let e=this._scene.spriteManagers.indexOf(this);this._scene.spriteManagers.splice(e,1)}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null}serialize(e=!1){let t={};for(let i of(t.name=this.name,t.capacity=this.capacity,t.cellWidth=this.cellWidth,t.cellHeight=this.cellHeight,t.fogEnabled=this.fogEnabled,t.blendMode=this.blendMode,t.disableDepthWrite=this.disableDepthWrite,t.pixelPerfect=this.pixelPerfect,this.texture&&(e?t.texture=this.texture.serialize():(t.textureUrl=this.texture.name,t.invertY=this.texture._invertY)),t.sprites=[],this.sprites))t.sprites.push(i.serialize());return t.metadata=this.metadata,t}static Parse(e,t,i){let r=new Tl(e.name,"",e.capacity,{width:e.cellWidth,height:e.cellHeight},t);for(let s of(void 0!==e.fogEnabled&&(r.fogEnabled=e.fogEnabled),void 0!==e.blendMode&&(r.blendMode=e.blendMode),void 0!==e.disableDepthWrite&&(r.disableDepthWrite=e.disableDepthWrite),void 0!==e.pixelPerfect&&(r.pixelPerfect=e.pixelPerfect),void 0!==e.metadata&&(r.metadata=e.metadata),e.texture?r.texture=sv.Parse(e.texture,t,i):e.textureName&&(r.texture=new sv(i+e.textureUrl,t,!1,void 0===e.invertY||e.invertY)),e.sprites))Ti.Parse(s,r);return r}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,n)=>{let a=new rS.g;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let t=JSON.parse(a.responseText),n=Tl.Parse(t,i||rp.l.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the sprite manager")}}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new Tl("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((r,s)=>{let n=new rS.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let s=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(s.spriteManager),o=Tl.Parse(a,t||rp.l.LastCreatedScene,i);o.snippetId=e,r(o)}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}Tl.SnippetUrl="https://snippet.babylonjs.com",Tl.CreateFromSnippetAsync=Tl.ParseFromSnippetAsync;let Th=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4( -texture2D(frameMap,vec2(fX,0.),0.), -texture2D(frameMap,vec2(fX,fdStep*1.),0.), -texture2D(frameMap,vec2(fX,fdStep*2.),0.), -vec4(0.) -);} -void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV); -#ifdef FLIPU -tileUV.y=1.0-tileUV.y; -#endif -vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i<LAYERS; i++) {float frameID; -#define LAYER_ID_SWITCH -vec4 animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,0.),0.);if(animationData.y>0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; f<MAX_ANIMATION_FRAMES; f++){if(animationData.y>mt){frameID=animationData.x;break;} -animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}} -mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;} -vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} -color.xyz*=colorMul;gl_FragColor=color;}`;no.v.ShadersStore.spriteMapPixelShader=Th;let Tu=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; -gl_Position=worldViewProjection*p;}`;no.v.ShadersStore.spriteMapVertexShader=Tu,i(7339),i(2267),i(2703),(tt=i5||(i5={}))[tt.INIT=0]="INIT",tt[tt.RUNNING=1]="RUNNING",tt[tt.DONE=2]="DONE",tt[tt.ERROR=3]="ERROR",i(4129),ri.y$.prototype.notifyObserversWithPromise=async function(e,t=-1,i,r,s){let n=Promise.resolve(e);if(!this.observers.length)return n;let a=this._eventState;return a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.userInfo=s,this.observers.forEach(i=>{!a.skipNextObservers&&!i._willBeUnregistered&&i.mask&t&&(n=i.scope?n.then(t=>(a.lastReturnValue=t,i.callback.apply(i.scope,[e,a]))):n.then(t=>(a.lastReturnValue=t,i.callback(e,a))),i.unregisterOnNextCall&&this._deferUnregister(i))}),await n,e},i(2241);class Tc{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class Td extends Tc{constructor(){super(...arguments),this._canBeMerged=e=>e instanceof rq.Kj&&!e.isDisposed()&&!!e.isVisible&&!!e.isEnabled()&&!(e.instances.length>0)&&!e.skeleton&&!e.hasLODLevels&&0!==e.getTotalVertices()}static get UpdateSelectionTree(){return Td._UpdateSelectionTree}static set UpdateSelectionTree(e){Td._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){let r=e.meshes.slice(0),s=r.length;for(let e=0;e<s;e++){let t=[],i=r[e];if(this._canBeMerged(i)){t.push(i);for(let n=e+1;n<s;n++){let e=r[n];this._canBeMerged(e)&&e.material===i.material&&e.checkCollisions===i.checkCollisions&&(t.push(e),s--,r.splice(n,1),n--)}t.length<2||rq.Kj.MergeMeshes(t,void 0,!0)}}return e.createOrUpdateSelectionOctree&&(void 0!=i?i&&e.createOrUpdateSelectionOctree():Td.UpdateSelectionTree&&e.createOrUpdateSelectionOctree()),!0}}Td._UpdateSelectionTree=!1;let Tp=[],T_=(e,t)=>{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),Tp[e.id]=!0)},Tf=(e,t)=>{let i={},r=e._geometry;return r&&!e.getScene().getGeometryById(r.id)&&T_(r,t.geometries),e.serialize&&e.serialize(i),i},Tm=(e,t)=>{if(e._isMesh){if(1===e.delayLoadState||0===e.delayLoadState){let 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 _D.G){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some(t=>t.id===e.material.id))for(let r of(t.multiMaterials.push(e.material.serialize()),e.material.subMaterials))r&&i(r)}else i(e.material)}else e.material||i(e.getScene().defaultMaterial);let r=e._geometry;r&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),T_(r,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(Tf(e,t))}}else"TransformNode"===e.getClassName()?t.transformNodes.push(e.serialize()):-1!==e.getClassName().indexOf("Camera")?t.cameras.push(e.serialize()):-1!==e.getClassName().indexOf("Light")&&t.lights.push(e.serialize())};class Tg{static ClearCache(){Tp=[]}static Serialize(e){return Tg._Serialize(e)}static _Serialize(e,t=!0){let i,r,s;let n={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&sv.ForceSerializeBuffers&&console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),Tg.ClearCache(),n.useDelayedTextureLoading=e.useDelayedTextureLoading,n.autoClear=e.autoClear,n.clearColor=e.clearColor.asArray(),n.ambientColor=e.ambientColor.asArray(),n.gravity=e.gravity.asArray(),n.collisionsEnabled=e.collisionsEnabled,n.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(n.fogMode=e.fogMode,n.fogColor=e.fogColor.asArray(),n.fogStart=e.fogStart,n.fogEnd=e.fogEnd,n.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){let t=e.getPhysicsEngine();t&&(n.physicsEnabled=!0,n.physicsGravity=t.gravity.asArray(),n.physicsEngine=t.getPhysicsPluginName())}for(let t of(e.metadata&&(n.metadata=e.metadata),n.morphTargetManagers=[],e.meshes)){let e=t.morphTargetManager;e&&n.morphTargetManagers.push(e.serialize())}for(i=0,n.lights=[];i<e.lights.length;i++)(r=e.lights[i]).doNotSerialize||n.lights.push(r.serialize());for(i=0,n.cameras=[];i<e.cameras.length;i++){let t=e.cameras[i];t.doNotSerialize||n.cameras.push(t.serialize())}if(e.activeCamera&&(n.activeCameraID=e.activeCamera.id),rg.p4.AppendSerializedAnimations(e,n),e.animationGroups&&e.animationGroups.length>0){n.animationGroups=[];for(let t=0;t<e.animationGroups.length;t++){let i=e.animationGroups[t];n.animationGroups.push(i.serialize())}}if(e.reflectionProbes&&e.reflectionProbes.length>0)for(i=0,n.reflectionProbes=[];i<e.reflectionProbes.length;i++){let t=e.reflectionProbes[i];n.reflectionProbes.push(t.serialize())}for(i=0,n.materials=[],n.multiMaterials=[];i<e.materials.length;i++)(s=e.materials[i]).doNotSerialize||n.materials.push(s.serialize());for(i=0,n.multiMaterials=[];i<e.multiMaterials.length;i++){let t=e.multiMaterials[i];n.multiMaterials.push(t.serialize())}for(e.environmentTexture&&(e.environmentTexture._files?n.environmentTexture=e.environmentTexture.serialize():(n.environmentTexture=e.environmentTexture.name,n.environmentTextureRotationY=e.environmentTexture.rotationY)),n.environmentIntensity=e.environmentIntensity,n.skeletons=[],i=0;i<e.skeletons.length;i++){let t=e.skeletons[i];t.doNotSerialize||n.skeletons.push(t.serialize())}for(i=0,n.transformNodes=[];i<e.transformNodes.length;i++)e.transformNodes[i].doNotSerialize||n.transformNodes.push(e.transformNodes[i].serialize());n.geometries={},n.geometries.boxes=[],n.geometries.spheres=[],n.geometries.cylinders=[],n.geometries.toruses=[],n.geometries.grounds=[],n.geometries.planes=[],n.geometries.torusKnots=[],n.geometries.vertexData=[],Tp=[];let a=e.getGeometries();for(i=0;i<a.length;i++){let e=a[i];e.isReady()&&T_(e,n.geometries)}for(i=0,n.meshes=[];i<e.meshes.length;i++){let t=e.meshes[i];t instanceof rq.Kj&&!t.doNotSerialize&&(1===t.delayLoadState||0===t.delayLoadState)&&n.meshes.push(Tf(t,n))}for(i=0,n.particleSystems=[];i<e.particleSystems.length;i++)n.particleSystems.push(e.particleSystems[i].serialize(!1));for(i=0,n.postProcesses=[];i<e.postProcesses.length;i++)n.postProcesses.push(e.postProcesses[i].serialize());for(let t of(e.actionManager&&(n.actions=e.actionManager.serialize("scene")),e._serializableComponents))t.serialize(n);return n}static SerializeAsync(e){let t=Tg._Serialize(e,!1),i=[];return this._CollectPromises(t,i),Promise.all(i).then(()=>t)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;i<e.length;++i){let r=e[i];r instanceof Promise?t.push(r.then(t=>e[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object){for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];r instanceof Promise?t.push(r.then(t=>e[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}}static SerializeMesh(e,t=!1,i=!1){let r={};if(r.meshes=[],r.transformNodes=[],r.cameras=[],r.lights=[],Tg.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let r=0;r<e.length;++r)i&&e[r].getDescendants().forEach(t=>{0>e.indexOf(t)&&!t.doNotSerialize&&e.push(t)}),t&&e[r].parent&&0>e.indexOf(e[r].parent)&&!e[r].parent.doNotSerialize&&e.push(e[r].parent);return e.forEach(e=>{Tm(e,r)}),r}}class Tv{static IsSupported(e){let t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!Tv.IsSupported(e))throw"Your browser does not support recording so far.";let 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({},Tv._DefaultOptions),t);let r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(let e of this._options.audioTracks)r.addTrack(e);this._mediaRecorder=new MediaRecorder(r,{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)this._reject(e.error);else throw new e.error}_handleStop(){this.stopRecording();let e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&rZ.w1.Download(e,this._fileName)}}Tv._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let TT=null;function Tx(e,t,i,r,s="image/png",n=!1,a){let{height:o,width:l}=TE(e,t,i);if(!(o&&l)){ru.Y.Error("Invalid 'size' parameter !");return}TT||(TT=document.createElement("canvas")),TT.width=l,TT.height=o;let h=TT.getContext("2d"),u=e.getRenderWidth()/e.getRenderHeight(),c=l,d=c/u;d>o&&(c=(d=o)*u);let p=Math.max(0,l-c)/2,_=Math.max(0,o-d)/2,f=t.getScene();f.activeCamera!==t?TS(e,t,i,e=>{if(n){let t=new Blob([e]);rZ.w1.DownloadBlob(t),r&&r("")}else r&&r(e)},s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,a):e.onEndFrameObservable.addOnce(()=>{let t=e.getRenderingCanvas();h&&t&&h.drawImage(t,p,_,c,d),TT&&(n?(rZ.w1.EncodeScreenshotCanvasData(TT,void 0,s,void 0,a),r&&r("")):rZ.w1.EncodeScreenshotCanvasData(TT,r,s,void 0,a))})}function TS(e,t,i,r,s="image/png",n=1,a=!1,o,l=!1,h=!1,u=!0,c){let{height:d,width:p,finalWidth:_,finalHeight:f}=TE(e,t,i);if(!(d&&p)){ru.Y.Error("Invalid 'size' parameter !");return}let m={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(p,d);let g=t.getScene(),v=new nV("screenShot",{width:p,height:d},g,!1,!1,0,!1,sv.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);v.renderList=g.meshes.slice(),v.samples=n,v.renderSprites=l,v.activeCamera=t,v.forceLayerMaskCheck=u;let T=()=>{e.onEndFrameObservable.addOnce(()=>{_===p&&f===d?v.readPixels(void 0,void 0,void 0,!1).then(e=>{nU.DumpData(p,d,e,r,s,o,!0,void 0,c),v.dispose()}):h5("pass",v.getInternalTexture(),g,void 0,void 0,void 0,_,f).then(t=>{e._readTexturePixels(t,_,f,-1,0,null,!0,!1,0,0).then(e=>{nU.DumpData(_,f,e,r,s,o,!0,void 0,c),t.dispose()})})}),g.incrementRenderId(),g.resetCachedMaterial(),v.render(!0),g.incrementRenderId(),g.resetCachedMaterial(),e.setSize(m.width,m.height),t.getProjectionMatrix(!0),g.render()};if(a){let e=new gN("antialiasing",1,g.activeCamera);v.addPostProcess(e),e.getEffect().isReady()?T():e.getEffect().onCompiled=()=>{T()}}else T()}function TE(e,t,i){let r=0,s=0,n=0,a=0;if("object"==typeof i){let o=i.precision?Math.abs(i.precision):1;i.width&&i.height?(r=i.height*o,s=i.width*o):i.width&&!i.height?r=Math.round((s=i.width*o)/e.getAspectRatio(t)):i.height&&!i.width?s=Math.round((r=i.height*o)*e.getAspectRatio(t)):r=Math.round((s=Math.round(e.getRenderWidth()*o))/e.getAspectRatio(t)),i.finalWidth&&i.finalHeight?(a=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?a=Math.round((n=i.finalWidth)/e.getAspectRatio(t)):i.finalHeight&&!i.finalWidth?n=Math.round((a=i.finalHeight)*e.getAspectRatio(t)):(n=s,a=r)}else isNaN(i)||(r=i,s=i,n=i,a=i);return s&&(s=Math.floor(s)),r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),a&&(a=Math.floor(a)),{height:0|r,width:0|s,finalWidth:0|n,finalHeight:0|a}}rZ.w1.CreateScreenshot=Tx,rZ.w1.CreateScreenshotAsync=function(e,t,i,r="image/png",s){return new Promise((n,a)=>{Tx(e,t,i,e=>{void 0!==e?n(e):a(Error("Data is undefined"))},r,void 0,s)})},rZ.w1.CreateScreenshotUsingRenderTarget=TS,rZ.w1.CreateScreenshotUsingRenderTargetAsync=function(e,t,i,r="image/png",s=1,n=!1,a,o=!1,l=!1,h=!0,u){return new Promise((c,d)=>{TS(e,t,i,e=>{void 0!==e?c(e):d(Error("Data is undefined"))},r,s,n,a,o,l,h,u)})},(ti=i6||(i6={}))[ti.Checkbox=0]="Checkbox",ti[ti.Slider=1]="Slider",ti[ti.Vector3=2]="Vector3",ti[ti.Quaternion=3]="Quaternion",ti[ti.Color3=4]="Color3",ti[ti.String=5]="String",ti[ti.Button=6]="Button",ti[ti.Options=7]="Options",ti[ti.Tab=8]="Tab",ti[ti.FileButton=9]="FileButton",ti[ti.Vector2=10]="Vector2",i(3367);class TC{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(t){let e={};return{getItem:t=>{let i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){let i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){let 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){let i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}TC._Storage=TC._GetStorage(),function(e){class t{serialize(){let e={},t=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){let i=JSON.parse(e),r=new t(i.characters);return r._insertionCosts=i.insertionCosts,r._deletionCosts=i.deletionCosts,r._substitutionCosts=i.substitutionCosts,r}constructor(e,t=null,i=null,r=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,r=null!=r?r:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=Array(e.length),this._deletionCosts=Array(e.length),this._substitutionCosts=Array(e.length);for(let n=0;n<e.length;++n){s=e[n],this._characterToIdx.set(s,n),this._insertionCosts[n]=t(s),this._deletionCosts[n]=i(s),this._substitutionCosts[n]=Array(e.length);for(let t=n;t<e.length;++t)this._substitutionCosts[n][t]=r(s,e[t])}}getCharacterIdx(e){return this._characterToIdx.get(e)}getInsertionCost(e){return this._insertionCosts[e]}getDeletionCost(e){return this._deletionCosts[e]}getSubstitutionCost(e,t){return this._substitutionCosts[Math.min(e,t)][Math.max(e,t)]}}e.Alphabet=t;class i{serialize(){return JSON.stringify(this._characters)}static Deserialize(e,t){let r=new i([],t);return r._characters=JSON.parse(e),r}constructor(e,t){if(e.length>i._MAX_SEQUENCE_LENGTH)throw 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){let r=e._alphabet;if(r!==t._alphabet)throw Error("Cannot Levenshtein compare Sequences built from different alphabets.");let s=e._characters,n=t._characters,a=s.length,o=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;e<a;++e)l[e+1][0]=l[e][0]+r.getInsertionCost(s[e]);for(let e=0;e<o;++e)l[0][e+1]=l[0][e]+r.getInsertionCost(n[e]);for(let e=0;e<a;++e)for(let t=0;t<o;++t)i._InsertionCost=l[e+1][t]+r.getInsertionCost(n[t]),i._DeletionCost=l[e][t+1]+r.getDeletionCost(s[e]),i._SubstitutionCost=l[e][t]+r.getSubstitutionCost(s[e],n[t]),l[e+1][t+1]=Math.min(i._InsertionCost,i._DeletionCost,i._SubstitutionCost);return l[a][o]}}i._MAX_SEQUENCE_LENGTH=256,i._CostMatrix=[...Array(i._MAX_SEQUENCE_LENGTH+1)].map(()=>Array(i._MAX_SEQUENCE_LENGTH+1)),e.Sequence=i}(i8||(i8={}));class Tb{serialize(){return JSON.stringify(this)}static Deserialize(e){let t=JSON.parse(e),i=new Tb(t._segmentLength);return i._points=t._points.map(e=>new rr.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{let i=()=>this._segmentLength/rr.P.Distance(this._points[t-1],e);for(let r=i();r<=1;r=i()){let i=this._points[t-1].scale(1-r);e.scaleAndAddToRef(r,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){let t=new Tb(this.getLength()/e);return this._points.forEach(e=>{t.add(e)}),t}tokenize(e){let t=[],i=new rr.P;for(let r=2;r<this._points.length;++r)Tb._TransformSegmentDirToRef(this._points[r-2],this._points[r-1],this._points[r],i)&&t.push(Tb._TokenizeSegment(i,e));return t}static _TransformSegmentDirToRef(e,t,i,r){return t.subtractToRef(e,Tb._ForwardDir),Tb._ForwardDir.normalize(),t.scaleToRef(-1,Tb._InverseFromVec),Tb._InverseFromVec.normalize(),!(Math.abs(rr.P.Dot(Tb._ForwardDir,Tb._InverseFromVec))>.98)&&(rr.P.CrossToRef(Tb._ForwardDir,Tb._InverseFromVec,Tb._UpDir),Tb._UpDir.normalize(),rr.y3.LookAtLHToRef(e,t,Tb._UpDir,Tb._LookMatrix),i.subtractToRef(t,Tb._FromToVec),Tb._FromToVec.normalize(),rr.P.TransformNormalToRef(Tb._FromToVec,Tb._LookMatrix,r),!0)}static _TokenizeSegment(e,t){Tb._BestMatch=0,Tb._Score=rr.P.Dot(e,t[0]),Tb._BestScore=Tb._Score;for(let i=1;i<t.length;++i)Tb._Score=rr.P.Dot(e,t[i]),Tb._Score>Tb._BestScore&&(Tb._BestMatch=i,Tb._BestScore=Tb._Score);return Tb._BestMatch}}Tb._ForwardDir=new rr.P,Tb._InverseFromVec=new rr.P,Tb._UpDir=new rr.P,Tb._FromToVec=new rr.P,Tb._LookMatrix=new rr.y3;class Ty{serialize(){return JSON.stringify(this._sequences.map(e=>e.serialize()))}static Deserialize(e,t){let i=new Ty;return i._sequences=JSON.parse(e).map(e=>i8.Sequence.Deserialize(e,t)),i}static CreateFromTrajectory(e,t,i){return Ty.CreateFromTokenizationPyramid(Ty._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){let i=new Ty;return i._sequences=e.map(e=>new i8.Sequence(e,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=Ty._FINEST_DESCRIPTOR_RESOLUTION){let r=[];for(let s=i;s>4;s=Math.floor(s/2))r.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return r}distance(e){let t=0;for(let i=0;i<this._sequences.length;++i)t+=Math.pow(2,i)*this._sequences[i].distance(e._sequences[i]);return t}}Ty._FINEST_DESCRIPTOR_RESOLUTION=32;class TA{serialize(){let e={};return e.descriptors=this._descriptors.map(e=>e.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){let i=JSON.parse(e),r=new TA;return r._descriptors=i.descriptors.map(e=>Ty.Deserialize(e,t)),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map(t=>t.distance(e)))}_refreshDescription(){let e;this._centroidIdx=-1;let t=this._descriptors.map(t=>(e=0,this._descriptors.forEach(i=>{e+=t.distance(i)}),e));for(let e=0;e<t.length;++e)(this._centroidIdx<0||t[e]<t[this._centroidIdx])&&(this._centroidIdx=e);this._averageDistance=0,this._descriptors.forEach(e=>{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])}),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,TA._MIN_AVERAGE_DISTANCE))}}TA._MIN_AVERAGE_DISTANCE=1;class TR{constructor(e,t,i){this._scene=e,ru.Y.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{let t=e.data;if(t.startsWith(TR._SERVER_PREFIX)){let e=t.substr(TR._SERVER_PREFIX.length);ru.Y.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),this._handleServerMessage(e);return}ru.Y.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{ru.Y.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&Tg.SerializeAsync(this._scene).then(e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)})}_handleClientMessage(){}}TR._SERVER_PREFIX="$$";class TP{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(){let e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}let TI="timestamp",TM="numPoints",TD=/\r/g;class TO{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{let e=rM.F.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength,r=0;if(i>0){let e=this.datasets.startingIndices.at(i-1);r=e+this.datasets.data.at(e+TO.NumberOfPointsOffset)+TO.SliceDataOffset}if(this.datasets.startingIndices.push(r),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())}),this.datasetObservable.hasObservers()){let i=[e,t];for(let e=0;e<t;e++)i.push(this.datasets.data.at(r+TO.SliceDataOffset+e));this.datasetObservable.notifyObservers(i)}},this.datasets={ids:[],data:new TP(1800),startingIndices:new TP(1800)},this._strategies=new Map,this._datasetMeta=new Map,this._eventRestoreSet=new Set,this._customEventObservable=new ri.y$,this.datasetObservable=new ri.y$,this.metadataObservable=new ri.y$(e=>e.callback(this._datasetMeta,new ri.he(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var r;return this._strategies.has(e)&&!t?void 0:(this._strategies.has(e)&&t&&(null===(r=this._strategies.get(e))||void 0===r||r.dispose(),this._strategies.delete(e)),this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,r=0,s=t.onAfterRenderObservable.add(()=>{r=i,i=0}),n=this._customEventObservable.add(t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)});return{id:e,getData:()=>r,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(n)}}},category:i}),{name:e})}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach(e=>{this.registerEvent(e,!0)})}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:r}of e){let e=t(this._scene);if(this._strategies.has(e.id)){e.dispose();continue}this.datasets.ids.push(e.id),i&&(i=i.replace(RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:r}),this._strategies.set(e.id,e)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);let i="#";for(let e=0;e<24;e+=8){let r=t>>e&255;i+=("0"+r.toString(16)).substr(-2)}return i}getCurrentSlice(){let e=rM.F.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasetObservable.hasObservers()&&i.push(t.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){let r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new TP(1800),this.datasets.ids.length=0,this.datasets.startingIndices=new TP(1800),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){let i=e.replace(TD,"").split("\n").map(e=>e.split(",").filter(e=>e.length>0)).filter(e=>e.length>0),r=TO.NumberOfPointsOffset;if(i.length<2)return!1;let s={ids:[],data:new TP(1800),startingIndices:new TP(1800)},[n,...a]=i;if(n.length<2||n[0]!==TI||n[r]!==TM)return!1;let o=new Map;for(let e=TO.SliceDataOffset;e<n.length;e++){let[t,i]=n[e].split("@");s.ids.push(t),o.set(t,i)}let l=0;for(let e of a){if(e.length<2)return!1;let t=parseFloat(e[0]),i=parseInt(e[r]);if(isNaN(i)||isNaN(t)||(s.data.push(t),s.data.push(i),i+TO.SliceDataOffset!==e.length))return!1;for(let t=TO.SliceDataOffset;t<e.length;t++){let i=parseFloat(e[t]);if(isNaN(i))return!1;s.data.push(i)}s.startingIndices.push(l),l+=e.length}if(this.datasets.ids=s.ids,this.datasets.data=s.data,this.datasets.startingIndices=s.startingIndices,t||this._datasetMeta.clear(),this._strategies.forEach(e=>e.dispose()),this._strategies.clear(),!t)for(let e of this.datasets.ids){let t=o.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${TI},${TM}`;for(let t=0;t<this.datasets.ids.length;t++)if(e+=`,${this.datasets.ids[t]}`,this._datasetMeta){let i=this._datasetMeta.get(this.datasets.ids[t]);(null==i?void 0:i.category)&&(e+=`@${i.category}`)}e+="\n";for(let t=0;t<this.datasets.startingIndices.itemLength;t++){let i=this.datasets.startingIndices.at(t),r=this.datasets.data.at(i),s=this.datasets.data.at(i+TO.NumberOfPointsOffset);e+=`${r},${s}`;for(let t=0;t<s;t++)e+=`,${this.datasets.data.at(i+TO.SliceDataOffset+t)}`;for(let t=0;t<this.datasets.ids.length-s;t++)e+=",";e+="\n"}let t=`${new Date().toISOString()}-perfdata.csv`;rZ.w1.Download(new Blob([e],{type:"text/csv"}),t)}start(e){e?void 0===this._startingTimestamp&&(this._startingTimestamp=rM.F.Now):(this.datasets.data=new TP(1800),this.datasets.startingIndices=new TP(1800),this._startingTimestamp=rM.F.Now),this._scene.onAfterRenderObservable.add(this._collectDataAtFrame),this._restoreStringEvents(),this._isStarted=!0}stop(){this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame),this._isStarted=!1}get isStarted(){return this._isStarted}dispose(){this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame),this._datasetMeta.clear(),this._strategies.forEach(e=>{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}rI.x.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new TO(this)),this._perfCollector};var TN=i(9357);ri.y$.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){let e=function(e){let t=[],i=[],r=[],s=e.add(()=>{let e=t.length;for(let s=0;s<e;s++)(0,TN.WP)(t.shift(),i.shift(),r.shift())});return{scheduler:(e,s,n)=>{t.push(e),i.push(s),r.push(n)},dispose:()=>{e.remove(s)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return(0,TN.sM)(e,this._coroutineScheduler)},ri.y$.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};class TF extends sV{constructor(e,t={}){super(e),this.options=t,this._direction=new rr.P(0,0,-1),this._mat=new rr.y3,this._onSelectEnabled=!1,this._origin=new rr.P(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new ri.y$,this._onHitTestResults=e=>{let t=e.map(e=>{let t=rr.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&&TF.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",rZ.w1.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then(e=>{let t=r||(e=>!!e.hitMatrix);return e.filter(t)})}static XRHitTestWithSelectEvent(e,t){let i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);let r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;rr.y3.FromArrayToRef(t.transform.matrix,0,this._mat),rr.P.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),rr.P.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();let 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});TF.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}TF.Name=sB.HIT_TEST,TF.Version=1,sU.AddWebXRFeature(TF.Name,(e,t)=>()=>new TF(e,t),TF.Version,!1);let TL=0;class Tw extends sV{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 ri.y$,this.onAnchorRemovedObservable=new ri.y$,this.onAnchorUpdatedObservable=new ri.y$,this._tmpVector=new rr.P,this._tmpQuaternion=new rr._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 rr.P,i=new rr._f){this._populateTmpTransformation(t,i);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(e.xrHitResult.createAnchor)try{let t=await e.xrHitResult.createAnchor(r);return new Promise((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:r,resolve:e,reject:i})})}catch(e){throw Error(e)}else throw this.detach(),Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new rr._f,i=!1){this._populateTmpTransformation(e,t);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:r,resolve:e,reject:t})})}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){let e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;let t=e.trackedAnchors;if(t){let i=this._trackedAnchors.filter(e=>!t.has(e.xrAnchor)).map(e=>{let t=this._trackedAnchors.indexOf(e);return t}),r=0;i.forEach(e=>{let t=this._trackedAnchors.splice(e-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),r++}),t.forEach(t=>{if(this._lastFrameDetected.has(t)){let i=this._findIndexInAnchorArray(t),r=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,r,e),r.attachedNode&&(r.attachedNode.rotationQuaternion=r.attachedNode.rotationQuaternion||new rr._f,r.transformationMatrix.decompose(r.attachedNode.scaling,r.attachedNode.rotationQuaternion,r.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(r)}catch(e){rZ.w1.Warn("Anchor could not be updated")}}else{let i={id:TL++,xrAnchor:t,remove:()=>t.delete()},r=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(r),this.onAnchorAddedObservable.notifyObservers(r);let s=this._futureAnchors.filter(e=>e.nativeAnchor===t),n=s[0];n&&(n.resolve(r),n.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<this._trackedAnchors.length;++t)if(this._trackedAnchors[t].xrAnchor===e)return t;return -1}_updateAnchorWithXRFrame(e,t,i){let r=i.getPose(e.anchorSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new rr.y3;rr.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}async _createAnchorAtTransformation(e,t){var i;if(t.createAnchor)try{return t.createAnchor(e,null!==(i=this._referenceSpaceForFrameAnchors)&&void 0!==i?i:this._xrSessionManager.referenceSpace)}catch(e){throw Error(e)}else throw this.detach(),Error("Anchors are not enabled in your browser")}}Tw.Name=sB.ANCHOR_SYSTEM,Tw.Version=1,sU.AddWebXRFeature(Tw.Name,(e,t)=>()=>new Tw(e,t),Tw.Version);let TB=0;class TU extends sV{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new ri.y$,this.onPlaneRemovedObservable=new ri.y$,this.onPlaneUpdatedObservable=new ri.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;){let 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;let i=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(i){for(let e=0;e<this._detectedPlanes.length;e++){let t=this._detectedPlanes[e];i.has(t.xrPlane)||(this._detectedPlanes.splice(e--,1),this.onPlaneRemovedObservable.notifyObservers(t))}i.forEach(t=>{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._findIndexInPlaneArray(t),r=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,r,e),this.onPlaneUpdatedObservable.notifyObservers(r)}}else{let i={id:TB++,xrPlane:t,polygonDefinition:[]},r=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(r),this.onPlaneAddedObservable.notifyObservers(r)}}),this._lastFrameDetected=i}}_init(){let e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};if(this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),!this._xrSessionManager.session.updateWorldTrackingState){e();return}this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map(e=>{let t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new rr.P(e.x,e.y,e.z*t)});let r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new rr.y3;rr.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t<this._detectedPlanes.length;++t)if(this._detectedPlanes[t].xrPlane===e)return t;return -1}}TU.Name=sB.PLANE_DETECTION,TU.Version=1,sU.AddWebXRFeature(TU.Name,(e,t)=>()=>new TU(e,t),TU.Version);class TV extends sV{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new ri.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){let t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper){if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){let i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){let i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{let i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(t=>t.setEnabled(e)),this.onBackgroundStateChangedObservable.notifyObservers(e)}}TV.Name=sB.BACKGROUND_REMOVER,TV.Version=1,sU.AddWebXRFeature(TV.Name,(e,t)=>()=>new TV(e,t),TV.Version,!0);class Tk extends sV{_createPhysicsImpostor(e){let t=this._options.physicsProperties.impostorType||sG.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=ha("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new rr._f;let s=e.grip||e.pointer;r.position.copyFrom(s.position),r.rotationQuaternion.copyFrom(s.rotationQuaternion);let n=new sG(r,t,Object.assign({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||ru.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(()=>{let i=new sG(t.rootMesh,sG.MeshImpostor,Object.assign({mass:0},this._options.physicsProperties)),r=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:r.position.clone(),oldRotation:r.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new rr._f,this._tmpVector=new rr.P,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach(e=>{let 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){let e=this._options.headsetImpostorParams||{impostorType:sG.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=ha("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 rr._f,this._headsetMesh.isVisible=!1,this._headsetImpostor=new sG(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){let 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){let 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){let 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;let r=this._controllers[e],s=r.xrController.grip||r.xrController.pointer,n=r.oldPos||r.impostorMesh.position;if(null===(t=r.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){let e=r.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setLinearVelocity(this._tmpVector)}else s.position.subtractToRef(n,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),r.impostor.setLinearVelocity(this._tmpVector);n.copyFrom(s.position),this._debugMode&&console.log(this._tmpVector,"linear");let a=r.oldRotation||r.impostorMesh.rotationQuaternion;if(null===(i=r.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){let e=r.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setAngularVelocity(this._tmpVector)}else if(!a.equalsWithEpsilon(s.rotationQuaternion)){a.conjugateInPlace().multiplyToRef(s.rotationQuaternion,this._tmpQuaternion);let 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{let t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}r.impostor.setAngularVelocity(this._tmpVector)}a.copyFrom(s.rotationQuaternion),this._debugMode&&console.log(this._tmpVector,this._tmpQuaternion,"angular")})}_detachController(e){let t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}Tk.Name=sB.PHYSICS_CONTROLLERS,Tk.Version=1,sU.AddWebXRFeature(Tk.Name,(e,t)=>()=>new Tk(e,t),Tk.Version,!0);class TG extends sV{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new rr.y3,this._tmpPos=new rr.P,this._tmpQuat=new rr._f,this._initHitTestSource=e=>{if(!e)return;let t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};if(this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),!i.space){rZ.w1.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(i).then(e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new ri.y$,this.paused=!1,this.xrNativeFeatureName="hit-test",rZ.w1.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach()||!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){let 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){let t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}if(this._transientXrHitTestSource){let t=e.getHitTestResultsForTransientInput(this._transientXrHitTestSource);t.forEach(e=>{this._processWebXRHitTestResult(e.results,e.inputSource)})}}}_processWebXRHitTestResult(e,t){let i=[];e.forEach(e=>{let r=e.getPose(this._xrSessionManager.referenceSpace);if(!r)return;let s=r.transform.position,n=r.transform.orientation;this._tmpPos.set(s.x,s.y,s.z),this._tmpQuat.set(n.x,n.y,n.z,n.w),rr.y3.FromFloat32ArrayToRefScaled(r.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());let 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)}}TG.Name=sB.HIT_TEST,TG.Version=2,sU.AddWebXRFeature(TG.Name,(e,t)=>()=>new TG(e,t),TG.Version,!1);class Tz extends sV{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new ri.y$,this.onFeaturePointsUpdatedObservable=new ri.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;let t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw Error("Received malformed feature point cloud of length: "+t.length);let e=t.length/5,i=[],r=[];for(let s=0;s<e;s++){let e=5*s,n=t[e+4];this._featurePointCloud[n]?i.push(n):(this._featurePointCloud[n]={position:new rr.P,confidenceValue:0},r.push(n)),this._featurePointCloud[n].position.x=t[e],this._featurePointCloud[n].position.y=t[e+1],this._featurePointCloud[n].position.z=t[e+2],this._featurePointCloud[n].confidenceValue=t[e+3]}r.length>0&&this.onFeaturePointsAddedObservable.notifyObservers(r),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}Tz.Name=sB.FEATURE_POINTS,Tz.Version=1,sU.AddWebXRFeature(Tz.Name,e=>()=>new Tz(e),Tz.Version);let TW=0;class TH extends sV{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new ri.y$,this.onMeshRemovedObservable=new ri.y$,this.onMeshUpdatedObservable=new ri.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;let i=null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes;if(i){let t=new Set;this._detectedMeshes.forEach((e,r)=>{i.has(r)||t.add(r)}),t.forEach(e=>{let 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){let i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{let i={id:TW++,xrMesh:t},r=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,r),this.onMeshAddedObservable.notifyObservers(r)}})}}catch(e){console.log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){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<e.positions.length;i+=3)t.positions[i]=e.positions[i],t.positions[i+1]=e.positions[i+1],t.positions[i+2]=-1*e.positions[i+2];if(e.normals){t.normals=new Float32Array(e.normals.length);for(let i=0;i<e.normals.length;i+=3)t.normals[i]=e.normals[i],t.normals[i+1]=e.normals[i+1],t.normals[i+2]=-1*e.normals[i+2]}}t.indices=e.indices;let r=i.getPose(e.meshSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new rr.y3;rr.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}}return t}}TH.Name=sB.MESH_DETECTION,TH.Version=1,sU.AddWebXRFeature(TH.Name,(e,t)=>()=>new TH(e,t),TH.Version,!1),(tr=i7||(i7={}))[tr.NotReceived=0]="NotReceived",tr[tr.Waiting=1]="Waiting",tr[tr.Received=2]="Received";class TX extends sV{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new ri.y$,this.onTrackableImageFoundObservable=new ri.y$,this.onTrackedImageUpdatedObservable=new ri.y$,this._trackableScoreStatus=i7.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{};let e=this.options.images.map(e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src));try{let t=await Promise.all(e);return this._originalTrackingRequest=t.map((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch(e){return rZ.w1.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===i7.Waiting)return;if(this._trackableScoreStatus===i7.NotReceived){this._checkScoresAsync();return}let t=e.getImageTrackingResults();for(let i of t){let t=!1,r=i.index,s=this._trackedImages[r];if(!s)continue;s.xrTrackingResult=i,s.realWorldWidth!==i.measuredWidthInMeters&&(s.realWorldWidth=i.measuredWidthInMeters,t=!0);let n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){let e=s.transformationMatrix;rr.y3.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}let a=i.trackingState,o="emulated"===a;s.emulated!==o&&(s.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==i7.NotReceived)return;this._trackableScoreStatus=i7.Waiting;let e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||0===e.length){this._trackableScoreStatus=i7.NotReceived;return}for(let t=0;t<e.length;++t)if("untrackable"==e[t])this.onUntrackableImageFoundObservable.notifyObservers(t);else{let e=this._originalTrackingRequest[t].image,i={id:t,originalBitmap:e,transformationMatrix:new rr.y3,ratio:e.width/e.height};this._trackedImages[t]=i,this.onTrackableImageFoundObservable.notifyObservers(i)}this._trackableScoreStatus=e.length>0?i7.Received:i7.NotReceived}}TX.Name=sB.IMAGE_TRACKING,TX.Version=1,sU.AddWebXRFeature(TX.Name,(e,t)=>()=>new TX(e,t),TX.Version,!1);class TY extends sV{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",rZ.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 rZ.w1.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){let e=document.querySelector(this.options.element);if(null===e)return rZ.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}}}}TY.Name=sB.DOM_OVERLAY,TY.Version=1,sU.AddWebXRFeature(TY.Name,(e,t)=>()=>new TY(e,t),TY.Version,!1);class Tj extends sV{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,r,s,n,a,o;if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new rr._f,this._tmpRotationMatrix=rr.y3.Identity(),this._tmpTranslationDirection=new rr.P,this._tmpMovementTranslation=new rr.P,this._tempCacheQuaternion=new rr._f,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let i=()=>{if(e.motionController)for(let i of this._currentRegistrationConfigurations){let r=null;if(i.allowedComponentTypes)for(let t of i.allowedComponentTypes){let i=e.motionController.getComponentOfType(t);if(null!==i){r=i;break}}if(i.mainComponentOnly){let t=e.motionController.getMainComponent();if(null===t)continue;r=t}if("function"==typeof i.componentSelectionPredicate&&(r=i.componentSelectionPredicate(e)),r&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness||null===r)continue;let s={registrationConfiguration:i,component:r};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=r.onAxisValueChangedObservable.add(e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in i&&(s.onButtonChangedObserver=r.onButtonStateChangedObservable.add(()=>{r.changes.pressed&&i.buttonChangedhandler(r.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce(()=>{i()})}},!t||void 0===t.xrInput){rZ.w1.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=Tj.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(i=t.movementOrientationFollowsViewerPose)||void 0===i||i,movementSpeed:null!==(r=t.movementSpeed)&&void 0!==r?r:1,movementThreshold:null!==(s=t.movementThreshold)&&void 0!==s?s:.25,rotationEnabled:null===(n=t.rotationEnabled)||void 0===n||n,rotationSpeed:null!==(a=t.rotationSpeed)&&void 0!==a?a:1,rotationThreshold:null!==(o=t.rotationThreshold)&&void 0!==o?o:.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){let e=this._xrSessionManager.scene.getEngine().getDeltaTime(),t=.001*e*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=t,rr._f.RotationYawPitchRollToRef(t,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(rr._f.RotationYawPitchRollToRef(3*t,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(rr.y3.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),rr.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){let t=this._controllers[e];if(t){for(let e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}Tj.Name=sB.MOVEMENT,Tj.REGISTRATIONS={default:[{allowedComponentTypes:[pA.THUMBSTICK_TYPE,pA.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:[pA.THUMBSTICK_TYPE,pA.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}}]},Tj.Version=1,sU.AddWebXRFeature(Tj.Name,(e,t)=>()=>new Tj(e,t),Tj.Version,!0);class Tq extends sV{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=rr.P.Up().negateInPlace(),this._lightColor=rs.Wo.White(),this._intensity=1,this._sphericalHarmonics=new h2,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new ri.y$,this._updateReflectionCubeMap=()=>{var e;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){let e=Date.now();if(e-this._cubeMapPollTime<this.options.cubeMapPollInterval)return;this._cubeMapPollTime=e}let t=this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe);if(t&&this._reflectionCubeMap){if(this._reflectionCubeMap._texture)null===(e=this._reflectionCubeMap._texture._hardwareTexture)||void 0===e||e.set(t),this._reflectionCubeMap._texture.getEngine().resetTextureCache();else{let e=new sT.l(this._xrSessionManager.scene.getEngine(),sT.S.Unknown);e.isCube=!0,e.invertY=!1,e._useSRGBBuffer="srgba8"===this.options.reflectionFormat,e.format=5,e.generateMipMaps=!0,e.type="srgba8"!==this.options.reflectionFormat?2:0,e.samplingMode=3,e.width=this._reflectionCubeMapTextureSize,e.height=this._reflectionCubeMapTextureSize,e._cachedWrapU=1,e._cachedWrapV=1,e._hardwareTexture=new lP.B(t,this._getCanvasContext()),this._reflectionCubeMap._texture=e}this._reflectionCubeMap._texture.isReady=!0,this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap)}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new c3("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new rr.P(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=r2.m.FALLOFF_GLTF),rZ.w1.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){let e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){var e;if(!super.attach())return!1;let t=null!==(e=this.options.reflectionFormat)&&void 0!==e?e:this._xrSessionManager.session.preferredReflectionFormat||"srgba8";return this.options.reflectionFormat=t,this._xrSessionManager.session.requestLightProbe({reflectionFormat:t}).then(e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(!this._reflectionCubeMap&&(this._reflectionCubeMap=new su(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(){let 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){let e=Date.now();if(e-this._lightEstimationPollTime<this.options.lightEstimationPollInterval)return;this._lightEstimationPollTime=e}if(this._xrLightEstimate=e.getLightEstimate(this._xrLightProbe),this._xrLightEstimate){this._intensity=Math.max(1,this._xrLightEstimate.primaryLightIntensity.x,this._xrLightEstimate.primaryLightIntensity.y,this._xrLightEstimate.primaryLightIntensity.z);let e=this._xrSessionManager.scene.useRightHandedSystem?1:-1;this.options.disableVectorReuse&&(this._lightDirection=new rr.P,this._lightColor=new rs.Wo,this.directionalLight&&(this.directionalLight.direction=this._lightDirection,this.directionalLight.diffuse=this._lightColor)),this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x,this._xrLightEstimate.primaryLightDirection.y,this._xrLightEstimate.primaryLightDirection.z*e),this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x/this._intensity,this._xrLightEstimate.primaryLightIntensity.y/this._intensity,this._xrLightEstimate.primaryLightIntensity.z/this._intensity),this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients),this._reflectionCubeMap&&!this.options.disableSphericalPolynomial&&(this._reflectionCubeMap.sphericalPolynomial=this._reflectionCubeMap.sphericalPolynomial||new h3,null===(t=this._reflectionCubeMap.sphericalPolynomial)||void 0===t||t.updateFromHarmonics(this._sphericalHarmonics)),this._lightDirection.negateInPlace(),this.directionalLight&&(this.directionalLight.direction.copyFrom(this._lightDirection),this.directionalLight.intensity=Math.min(this._intensity,1),this.directionalLight.diffuse.copyFrom(this._lightColor))}}}}Tq.Name=sB.LIGHT_ESTIMATION,Tq.Version=1,sU.AddWebXRFeature(Tq.Name,(e,t)=>()=>new Tq(e,t),Tq.Version,!1);class TK extends sV{constructor(e){super(e),this.onEyeTrackingStartedObservable=new ri.y$,this.onEyeTrackingEndedObservable=new ri.y$,this.onEyeTrackingFrameUpdateObservable=new ri.y$,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new sD(rr.P.Zero(),rr.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){let 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);let e=t.transform.orientation;rr.jp.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?rr.P.RightHandedForwardReadOnly.rotateByQuaternionToRef(rr.jp.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,rr.jp.Quaternion[0].z*=-1,rr.jp.Quaternion[0].w*=-1,rr.P.LeftHandedForwardReadOnly.rotateByQuaternionToRef(rr.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))}}TK.Name=sB.EYE_TRACKING,TK.Version=1,sU.AddWebXRFeature(TK.Name,e=>()=>new TK(e),TK.Version,!1);class T${constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i<e;++i)this._samples.push(t?t():rr.FM.Zero())}get length(){return this._samples.length}push(e,t){this._idx=(this._idx+this._samples.length-1)%this._samples.length,this.at(0).copyFromFloats(e,t)}at(e){if(e>=this._samples.length)throw Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class TQ{constructor(){this._samples=new T$(20),this._entropy=0,this.onFirstStepDetected=new ri.y$}update(e,t,i,r){let s,n;this._samples.push(e,t);let a=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=rr.FM.Distance(a,this._samples.at(1)),this._entropy>this._entropyThreshold)return;for(s=this._samePointCheckStartIdx;s<this._samples.length&&!(rr.FM.DistanceSquared(a,this._samples.at(s))<this._samePointSquaredDistanceThreshold);++s);if(s===this._samples.length)return;let o=-1,l=0;for(let e,t=1;t<s;++t)(e=rr.FM.DistanceSquared(a,this._samples.at(t)))>o&&(l=t,o=e);if(o<this._apexSquaredDistanceThreshold)return;let h=this._samples.at(l),u=h.subtract(a);u.normalize();let c=rr.jp.Vector2[0],d=0;for(let e=1;e<s;++e)this._samples.at(e).subtractToRef(a,c),n=rr.FM.Dot(u,c),d+=c.lengthSquared()-n*n;if(d>s*this._squaredProjectionDistanceThreshold)return;let p=rr.jp.Vector3[0];p.set(i,r,0);let _=rr.jp.Vector3[1];_.set(u.x,u.y,0);let f=rr.P.Cross(p,_).z>0,m=a.clone(),g=a.clone();h.subtractToRef(a,u),f?(u.scaleAndAddToRef(this._axisToApexShrinkFactor,m),u.scaleAndAddToRef(this._axisToApexExtendFactor,g)):(u.scaleAndAddToRef(this._axisToApexExtendFactor,m),u.scaleAndAddToRef(this._axisToApexShrinkFactor,g)),this.onFirstStepDetected.notifyObservers({leftApex:m,rightApex:g,currentPosition:a,currentStepDirection:f?"right":"left"})}reset(){for(let e=0;e<this._samples.length;++e)this._samples.at(e).copyFromFloats(0,0)}get _samePointCheckStartIdx(){return Math.floor(this._samples.length/3)}get _samePointSquaredDistanceThreshold(){return 9e-4}get _apexSquaredDistanceThreshold(){return .0081}get _squaredProjectionDistanceThreshold(){return 9e-4}get _axisToApexShrinkFactor(){return .8}get _axisToApexExtendFactor(){return -1.6}get _entropyDecayFactor(){return .93}get _entropyThreshold(){return .4}}class TZ{constructor(e,t,i,r){this._leftApex=new rr.FM,this._rightApex=new rr.FM,this._currentPosition=new rr.FM,this._axis=new rr.FM,this._axisLength=-1,this._forward=new rr.FM,this._steppingLeft=!1,this._t=-1,this._maxT=-1,this._maxTPosition=new rr.FM,this._vitality=0,this.onMovement=new ri.y$,this.onFootfall=new ri.y$,this._reset(e,t,i,"left"===r)}_reset(e,t,i,r){this._leftApex.copyFrom(e),this._rightApex.copyFrom(t),this._steppingLeft=r,this._steppingLeft?(this._leftApex.subtractToRef(this._rightApex,this._axis),this._forward.copyFromFloats(-this._axis.y,this._axis.x)):(this._rightApex.subtractToRef(this._leftApex,this._axis),this._forward.copyFromFloats(this._axis.y,-this._axis.x)),this._axisLength=this._axis.length(),this._forward.scaleInPlace(1/this._axisLength),this._updateTAndVitality(i.x,i.y),this._maxT=this._t,this._maxTPosition.copyFrom(i),this._vitality=1}_updateTAndVitality(e,t){this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._currentPosition.subtractInPlace(this._rightApex):this._currentPosition.subtractInPlace(this._leftApex);let i=this._t,r=rr.FM.Dot(this._currentPosition,this._axis);this._t=r/(this._axisLength*this._axisLength);let s=this._currentPosition.lengthSquared()-r/this._axisLength*(r/this._axisLength);this._vitality*=.92-100*Math.max(s-.0016,0)+Math.max(this._t-i,0)}update(e,t){if(this._vitality<this._vitalityThreshold)return!1;let i=this._t;return this._updateTAndVitality(e,t),this._t>this._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitality<this._vitalityThreshold)&&(this._t>i&&(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 TJ{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new TQ,this._walker=null,this._movement=new rr.FM,this._millisecondsSinceLastUpdate=TJ._MillisecondsPerUpdate,this.movementThisFrame=rr.P.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(e=>{this._walker||(this._walker=new TZ(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>=TJ._MillisecondsPerUpdate){if(this._millisecondsSinceLastUpdate-=TJ._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker){let t=this._walker.update(e.x,e.z);t||(this._walker=null)}this._movement.scaleInPlace(.85)}this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class T0 extends sV{static get Name(){return sB.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 rr.P,this._forward=new rr.P,this._position=new rr.P,this._movement=new rr.P,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&ru.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 TJ(this._sessionManager.scene.getEngine()),!0)}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){let t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;let i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||rr.P.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}sU.AddWebXRFeature(T0.Name,(e,t)=>()=>new T0(e,t),T0.Version,!1);class T1 extends lR{constructor(e,t,i,r,s,n){super(e,t,i,r,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=s,this.createRTTProvider=n}}class T2 extends lI{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,r,s,n;let a=this._lastSubImages.get(t),o="left"==t?0:1,l=null!==(i=e.colorTextureWidth)&&void 0!==i?i:e.textureWidth,h=null!==(r=e.colorTextureHeight)&&void 0!==r?r:e.textureHeight;if(!this._renderTargetTextures[o]||(null==a?void 0:a.textureWidth)!==l||(null==a?void 0:a.textureHeight)!==h){let t;let i=null!==(s=e.depthStencilTextureWidth)&&void 0!==s?s:l,r=null!==(n=e.depthStencilTextureHeight)&&void 0!==n?n:h;(l===i||h===r)&&(t=e.depthStencilTexture),this._renderTargetTextures[o]=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[o]}_getSubImageForEye(e){let t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){let t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}_setViewportForSubImage(e,t){var i,r;let s=null!==(i=t.colorTextureWidth)&&void 0!==i?i:t.textureWidth,n=null!==(r=t.colorTextureWidth)&&void 0!==r?r:t.textureHeight,a=t.viewport;e.x=a.x/s,e.y=a.y/n,e.width=a.width/s,e.height=a.height/n}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class T3 extends T1{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,e=>new T4(e,i,this)),this.layer=e}}class T4 extends T2{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){let t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}let T5={},T6={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};class T8 extends sV{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;let t=Object.assign({},T6),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=T5){let t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new lM(t)}createProjectionLayer(e=T6,t=!1){if(t&&"texture-array"!==e.textureType)throw 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 Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.");let i=this._xrWebGLBinding.createProjectionLayer(e);return new T3(i,t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;let 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){}}T8.Name=sB.LAYERS,T8.Version=1,sU.AddWebXRFeature(T8.Name,(e,t)=>()=>new T8(e,t),T8.Version,!1);class T7 extends sV{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;let i=this._xrSessionManager.scene.getEngine(),r=new sT.l(i,sT.S.Unknown);return r.isCube=!1,r.invertY=!1,r._useSRGBBuffer=!1,r.format="ushort"===this.depthDataFormat?2:5,r.generateMipMaps=!1,r.type="ushort"===this.depthDataFormat?5:1,r.samplingMode=7,r.width=null!==(e=this.width)&&void 0!==e?e:0,r.height=null!==(t=this.height)&&void 0!==t?t:0,r._cachedWrapU=1,r._cachedWrapV=1,r._hardwareTexture=new lP.B(this._cachedWebGLTexture,i._gl),r}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 ri.y$,this.xrNativeFeatureName="depth-sensing",rZ.w1.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){if(!super.attach(e))return!1;let t=null==this._xrSessionManager.session.depthDataFormat||null==this._xrSessionManager.session.depthUsage;return!t&&(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){let t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(let t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:rZ.w1.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{data:s,width:n,height:a,rawValueToMeters:o,getDepthInMeters:l}=r;switch(this._width=n,this._height=a,this._rawValueToMeters=o,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=sb.CreateRTexture(null,n,a,this._xrSessionManager.scene,!1,!0,sv.NEAREST_SAMPLINGMODE,r7.D.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map(e=>e*o));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map(e=>e*o))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{texture:s,width:n,height:a}=r;this._width=n,this._height=a,this._cachedWebGLTexture=s;let o=this._xrSessionManager.scene,l=o.getEngine(),h=l.wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=sb.CreateRTexture(null,n,a,o,!1,!0,sv.NEAREST_SAMPLINGMODE,"ushort"===i?r7.D.TEXTURETYPE_UNSIGNED_BYTE:r7.D.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=h}getXRSessionInitExtension(){let 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){let e=this.options.usagePreference.map(e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),t=this.options.dataFormatPreference.map(e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:e,dataFormatPreference:t}})}else i({})})}}T7.Name=sB.DEPTH_SENSING,T7.Version=1,sU.AddWebXRFeature(T7.Name,(e,t)=>()=>new T7(e,t),T7.Version,!1);let T9=`precision highp float; -#define CUSTOM_FRAGMENT_BEGIN -varying vec4 clipPos;varying vec4 previousClipPos; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; -#define CUSTOM_FRAGMENT_MAIN_END -}`;no.v.ShadersStore.velocityPixelShader=T9;let xe=`#define CUSTOM_VERTEX_BEGIN -#define VELOCITY -attribute vec3 position; -#include<instancesDeclaration> -uniform mat4 viewProjection;uniform mat4 previousViewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; -#endif -varying vec4 clipPos;varying vec4 previousClipPos; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#include<instancesVertex> -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} -#elif -clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -}`;no.v.ShadersStore.velocityVertexShader=xe;class xt extends nV{constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[rr.y3.Identity(),rr.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 hf("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;let 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 xi{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){let t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw Error('For Space Warp, the base layer type should "XRProjectionLayer".');let i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,s){if(!this._engine)throw Error("Engine is disposed");let n=new xt(r,s,this._scene,{width:e,height:t}),a=n.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=r,a._depthStencilTextureArray=s,n.disableRescaling(),n.renderListPredicate=()=>!0,n}_getRenderTargetForSubImage(e,t){let i=this._lastSubImages.get(t),r=this._renderTargetTextures.get(t.eye),s=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return r&&(null==i?void 0:i.textureWidth)===s&&(null==i?void 0:i.textureHeight)==n||(r=this._createRenderTargetTexture(s,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:n}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){let i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){let t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){let t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}}class xr extends sV{constructor(e){super(e),this.dependsOn=[sB.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new xi(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){let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;let i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}xr.Name=sB.SPACE_WARP,xr.Version=1,sU.AddWebXRFeature(xr.Name,e=>()=>new xr(e),xr.Version,!1);class xs extends pR{constructor(e,t,i){super(e,xn[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(){}}pO.RegisterController("generic-hand-select-grasp",(e,t)=>new xs(t,e.gamepad,e.handedness));let xn={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 xa extends pR{constructor(e,t,i){super(e,xo["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?xa.MODEL_LEFT_FILENAME:xa.MODEL_RIGHT_FILENAME;let t=xa.MODEL_BASE_URL+"default/";return{filename:e,path:t}}_getModelLoadingConstraints(){let e=sH.IsPluginForExtensionAvailable(".glb");return e||ru.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){let i=this._mapping.buttons[e],r=i.rootNodeName;if(!r){ru.Y.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);return}let s=this._getChildByName(this.rootMesh,r);if(!s){ru.Y.Warn("Missing button mesh with name: "+r);return}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){let t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add(e=>{this._lerpTransform(i,e.value)},void 0,!0)}else ru.Y.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(e=>{let t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach(i=>{if(!this.rootMesh)return;let r=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,r.rootNodeName);if(!s){ru.Y.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?t&&t.onAxisValueChangedObservable.add(e=>{let t="x-axis"===i?e.x:e.y;this._lerpTransform(r,t,!0)},void 0,!0):ru.Y.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){let t;this.rootMesh=new rq.Kj(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i<e.length;i++){let r=e[i];r.isPickable=!1,r.parent||(t=r)}t&&t.setParent(this.rootMesh),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=rr._f.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}xa.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",xa.MODEL_LEFT_FILENAME="left.glb",xa.MODEL_RIGHT_FILENAME="right.glb",pO.RegisterController("windows-mixed-reality",(e,t)=>new xa(t,e.gamepad,e.handedness));let xo={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 xl extends pR{constructor(e,t,i,r=!1,s=!1){super(e,xh[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";e="left"===this.handedness?xl.MODEL_LEFT_FILENAME:xl.MODEL_RIGHT_FILENAME;let t=this._isQuest()?xl.QUEST_MODEL_BASE_URL:xl.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){let t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach(e=>{let r=e&&this.getComponent(e);r&&r.onButtonStateChangedObservable.add(r=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-(.2*r.value),this._modelRootNode.getChildren()[3].position.y=-(.005*r.value),this._modelRootNode.getChildren()[3].position.z=-(.005*r.value));return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*r.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(r.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(r.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new rq.Kj(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=rr._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}}xl.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",xl.MODEL_LEFT_FILENAME="left.babylon",xl.MODEL_RIGHT_FILENAME="right.babylon",xl.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",pO.RegisterController("oculus-touch",(e,t)=>new xl(t,e.gamepad,e.handedness)),pO.RegisterController("oculus-touch-legacy",(e,t)=>new xl(t,e.gamepad,e.handedness,!0));let xh={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 xu extends pR{constructor(e,t,i){super(e,xc[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){let e=xu.MODEL_FILENAME,t=xu.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add(t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-(.15*t.value);return;case"xr-standard-touchpad":case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new rq.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=rr._f.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}xu.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",xu.MODEL_FILENAME="wand.babylon",pO.RegisterController("htc-vive",(e,t)=>new xu(t,e.gamepad,e.handedness));let xc={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"}};uT("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 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 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;let i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];let r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw Error("This function is not available in Babylon Native")}}),(ts=i9||(i9={}))[ts.Input=0]="Input",ts[ts.Output=1]="Output"},9747:function(e,t,i){i.d(t,{N:function(){return u}});var r=i(6851),s=i(1823),n=i(6816),a=i(6702),o=i(3914),l=i(4620);class h{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new a.y$,this._onClonedObservable=new a.y$}}class u{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){let s=this._NodeConstructors[e];return s?s(t,i,r):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;let t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){let 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=[]),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){let 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 a.y$,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=s.y3.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new a.y$,this._onDisposeObserver=null,this._behaviors=[],this.name=e,this.id=e,this._scene=t||o.l.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){let i=this._behaviors.indexOf(e);return -1!==i||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{e.attach(this)}):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){let 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(let 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 r=0;r<this._children.length;r++){let s=this._children[r];(!i||i(s))&&e.push(s),t||s._getDescendants(e,!1,i)}}getDescendants(e,t){let i=[];return this._getDescendants(i,e,t),i}getChildMeshes(e,t){let i=[];return this._getDescendants(i,e,e=>(!t||t(e))&&void 0!==e.cullingStrategy),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;t<this.animations.length;t++){let i=this.animations[t];if(i.name===e)return i}return null}createAnimationRange(e,t,i){if(!this._ranges[e]){this._ranges[e]=u._AnimationRangeFactory(e,t,i);for(let r=0,s=this.animations.length;r<s;r++)this.animations[r]&&this.animations[r].createRange(e,t,i)}}deleteAnimationRange(e,t=!0){for(let i=0,r=this.animations.length;i<r;i++)this.animations[i]&&this.animations[i].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(e,t,i){let r=n.p4.Clone(()=>new u(e,this.getScene()),this);if(t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;i<t.length;i++){let s=t[i];s.clone(e+"."+s.name,r)}}return r}getAnimationRanges(){let e;let t=[];for(e in this._ranges)t.push(this._ranges[e]);return t}beginAnimation(e,t,i,r){let s=this.getAnimationRange(e);return s?this._scene.beginAnimation(this,s.from,s.to,t,i,r):null}serializeAnimationRanges(){let e=[];for(let t in this._ranges){let i=this._ranges[t];if(!i)continue;let r={};r.name=t,r.from=i.from,r.to=i.to,e.push(r)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=s.y3.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){let i=this.getDescendants(!0);for(let r of i)r.dispose(e,t)}for(let e of(this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear(),this._behaviors))e.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,i){if(t.ranges)for(let i=0;i<t.ranges.length;i++){let r=t.ranges[i];e.createAnimationRange(r.name,r.from,r.to)}}getHierarchyBoundingVectors(e=!0,t=null){let i,r;if(this.getScene().incrementRenderId(),this.computeWorldMatrix(!0),this.getBoundingInfo&&this.subMeshes){let e=this.getBoundingInfo();i=e.boundingBox.minimumWorld.clone(),r=e.boundingBox.maximumWorld.clone()}else i=new s.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new s.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){let e=this.getDescendants(!1);for(let n of e){let e=n;if(e.computeWorldMatrix(!0),t&&!t(e)||!e.getBoundingInfo||0===e.getTotalVertices())continue;let a=e.getBoundingInfo(),o=a.boundingBox,l=o.minimumWorld,h=o.maximumWorld;s.P.CheckExtends(l,i,r),s.P.CheckExtends(h,i,r)}}return{min:i,max:r}}}u._AnimationRangeFactory=(e,t,i)=>{throw(0,l.S)("AnimationRange")},u._NodeConstructors={},(0,r.gn)([(0,n.qC)()],u.prototype,"name",void 0),(0,r.gn)([(0,n.qC)()],u.prototype,"id",void 0),(0,r.gn)([(0,n.qC)()],u.prototype,"uniqueId",void 0),(0,r.gn)([(0,n.qC)()],u.prototype,"state",void 0),(0,r.gn)([(0,n.qC)()],u.prototype,"metadata",void 0)},176:function(e,t,i){i.d(t,{H:function(){return s},l:function(){return r}});class r{}r.NAME_EFFECTLAYER="EffectLayer",r.NAME_LAYER="Layer",r.NAME_LENSFLARESYSTEM="LensFlareSystem",r.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",r.NAME_PARTICLESYSTEM="ParticleSystem",r.NAME_GAMEPAD="Gamepad",r.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",r.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",r.NAME_PREPASSRENDERER="PrePassRenderer",r.NAME_DEPTHRENDERER="DepthRenderer",r.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",r.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",r.NAME_SPRITE="Sprite",r.NAME_SUBSURFACE="SubSurface",r.NAME_OUTLINERENDERER="Outline",r.NAME_PROCEDURALTEXTURE="ProceduralTexture",r.NAME_SHADOWGENERATOR="ShadowGenerator",r.NAME_OCTREE="Octree",r.NAME_PHYSICSENGINE="PhysicsEngine",r.NAME_AUDIO="Audio",r.NAME_FLUIDRENDERER="FluidRenderer",r.STEP_ISREADYFORMESH_EFFECTLAYER=0,r.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,r.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,r.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,r.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,r.STEP_BEFORECAMERADRAW_PREPASS=0,r.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,r.STEP_BEFORECAMERADRAW_LAYER=2,r.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,r.STEP_BEFORERENDERTARGETDRAW_LAYER=1,r.STEP_BEFORERENDERINGMESH_PREPASS=0,r.STEP_BEFORERENDERINGMESH_OUTLINE=1,r.STEP_AFTERRENDERINGMESH_PREPASS=0,r.STEP_AFTERRENDERINGMESH_OUTLINE=1,r.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,r.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,r.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,r.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,r.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,r.STEP_BEFORECLEAR_PREPASS=1,r.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,r.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,r.STEP_AFTERRENDERTARGETDRAW_LAYER=1,r.STEP_AFTERCAMERADRAW_PREPASS=0,r.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,r.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,r.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,r.STEP_AFTERCAMERADRAW_LAYER=4,r.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,r.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,r.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,r.STEP_AFTERRENDER_AUDIO=0,r.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,r.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,r.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,r.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,r.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,r.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,r.STEP_POINTERMOVE_SPRITE=0,r.STEP_POINTERDOWN_SPRITE=0,r.STEP_POINTERUP_SPRITE=0;class s extends Array{constructor(e){super(...e)}static Create(){return Object.create(s.prototype)}registerStep(e,t,i){let r=0;for(;r<this.length;r++){let t=this[r];if(e<t.index)break}this.splice(r,0,{index:e,component:t,action:i.bind(t)})}clear(){this.length=0}}},6851:function(e,t,i){i.d(t,{gn:function(){return r}});function r(e,t,i,r){var s,n=arguments.length,a=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,r);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(a=(n<3?s(a):n>3?s(t,i,a):s(t,i))||a);return n>3&&a&&Object.defineProperty(t,i,a),a}}}]); \ No newline at end of file diff --git a/.next/static/chunks/2443530c-097fe1871e1d7679.js b/.next/static/chunks/2443530c-097fe1871e1d7679.js deleted file mode 100644 index cfcb8bb..0000000 --- a/.next/static/chunks/2443530c-097fe1871e1d7679.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[667],{2614:function(e,t,n){/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var r,l=n(6006),a=n(6183),o={usingClientEntryPoint:!1,Events:null,Dispatcher:{current:null}};function i(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var u=Object.assign,s=l.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,c=[],f=-1;function d(e){return{current:e}}function p(e){0>f||(e.current=c[f],c[f]=null,f--)}function h(e,t){c[++f]=e.current,e.current=t}var m=Symbol.for("react.element"),g=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),v=Symbol.for("react.strict_mode"),b=Symbol.for("react.profiler"),k=Symbol.for("react.provider"),w=Symbol.for("react.context"),S=Symbol.for("react.server_context"),E=Symbol.for("react.forward_ref"),x=Symbol.for("react.suspense"),C=Symbol.for("react.suspense_list"),z=Symbol.for("react.memo"),P=Symbol.for("react.lazy"),N=Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");var _=Symbol.for("react.offscreen"),L=Symbol.for("react.legacy_hidden"),T=Symbol.for("react.cache");Symbol.for("react.tracing_marker");var M=Symbol.for("react.default_value"),F=Symbol.iterator;function D(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=F&&e[F]||e["@@iterator"])?e:null}var R=d(null),O=d(null),A=d(null);function I(e,t){switch(h(A,t),h(O,e),h(R,null),e=t.nodeType){case 9:case 11:t=(t=t.documentElement)&&(t=t.namespaceURI)?sb(t):0;break;default:if(t=(e=8===e?t.parentNode:t).tagName,e=e.namespaceURI)t=sk(e=sb(e),t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}p(R),h(R,t)}function U(){p(R),p(O),p(A)}function B(e){var t=R.current,n=sk(t,e.type);t!==n&&(h(O,e),h(R,n))}function V(e){O.current===e&&(p(R),p(O))}var Q=a.unstable_scheduleCallback,$=a.unstable_cancelCallback,W=a.unstable_shouldYield,j=a.unstable_requestPaint,H=a.unstable_now,q=a.unstable_getCurrentPriorityLevel,K=a.unstable_ImmediatePriority,Y=a.unstable_UserBlockingPriority,X=a.unstable_NormalPriority,G=a.unstable_LowPriority,Z=a.unstable_IdlePriority,J=null,ee=null,et=Math.clz32?Math.clz32:function(e){return 0==(e>>>=0)?32:31-(en(e)/er|0)|0},en=Math.log,er=Math.LN2,el=128,ea=8388608;function eo(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:return 8388480&e;case 8388608:case 16777216:case 33554432:case 67108864:return 125829120&e;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function ei(e,t){var n=e.pendingLanes;if(0===n)return 0;var r=0,l=e.suspendedLanes,a=e.pingedLanes,o=268435455&n;if(0!==o){var i=o&~l;0!==i?r=eo(i):0!=(a&=o)&&(r=eo(a))}else 0!=(o=n&~l)?r=eo(o):0!==a&&(r=eo(a));if(0===r)return 0;if(0!==t&&t!==r&&0==(t&l)&&((l=r&-r)>=(a=t&-t)||32===l&&0!=(8388480&a)))return t;if(0!=(8&r)&&(r|=32&n),0!==(t=e.entangledLanes))for(e=e.entanglements,t&=r;0<t;)l=1<<(n=31-et(t)),r|=e[n],t&=~l;return r}function eu(e,t){return e.errorRecoveryDisabledLanes&t?0:0!=(e=-1073741825&e.pendingLanes)?e:1073741824&e?1073741824:0}function es(){var e=el;return 0==(8388480&(el<<=1))&&(el=128),e}function ec(){var e=ea;return 0==(125829120&(ea<<=1))&&(ea=8388608),e}function ef(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function ed(e,t){e.pendingLanes|=t,536870912!==t&&(e.suspendedLanes=0,e.pingedLanes=0)}function ep(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-et(n),l=1<<r;l&t|e[r]&t&&(e[r]|=t),n&=~l}}var eh=0;function em(e){return 2<(e&=-e)?8<e?0!=(268435455&e)?32:536870912:8:2}var eg=Object.prototype.hasOwnProperty,ey=Math.random().toString(36).slice(2),ev="__reactFiber$"+ey,eb="__reactProps$"+ey,ek="__reactContainer$"+ey,ew="__reactEvents$"+ey,eS="__reactListeners$"+ey,eE="__reactHandles$"+ey,ex="__reactResources$"+ey,eC="__reactMarker$"+ey;function ez(e){delete e[ev],delete e[eb],delete e[ew],delete e[eS],delete e[eE]}function eP(e){var t=e[ev];if(t)return t;for(var n=e.parentNode;n;){if(t=n[ek]||n[ev]){if(n=t.alternate,null!==t.child||null!==n&&null!==n.child)for(e=sT(e);null!==e;){if(n=e[ev])return n;e=sT(e)}return t}n=(e=n).parentNode}return null}function eN(e){if(e=e[ev]||e[ek]){var t=e.tag;if(5===t||6===t||13===t||26===t||27===t||3===t)return e}return null}function e_(e){var t=e.tag;if(5===t||26===t||27===t||6===t)return e.stateNode;throw Error(i(33))}function eL(e){return e[eb]||null}function eT(e){var t=e[ex];return t||(t=e[ex]={hoistableStyles:new Map,hoistableScripts:new Map}),t}function eM(e){e[eC]=!0}var eF=new Set,eD={};function eR(e,t){eO(e,t),eO(e+"Capture",t)}function eO(e,t){for(eD[e]=t,e=0;e<t.length;e++)eF.add(t[e])}var eA=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),eI=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),eU={},eB={};function eV(e,t,n){if(eg.call(eB,t)||!eg.call(eU,t)&&(eI.test(t)?eB[t]=!0:(eU[t]=!0,!1))){if(null===n)e.removeAttribute(t);else{switch(typeof n){case"undefined":case"function":case"symbol":e.removeAttribute(t);return;case"boolean":var r=t.toLowerCase().slice(0,5);if("data-"!==r&&"aria-"!==r){e.removeAttribute(t);return}}e.setAttribute(t,""+n)}}}function eQ(e,t,n){if(null===n)e.removeAttribute(t);else{switch(typeof n){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(t);return}e.setAttribute(t,""+n)}}function e$(e,t,n,r){if(null===r)e.removeAttribute(n);else{switch(typeof r){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(n);return}e.setAttributeNS(t,n,""+r)}}function eW(e){if(void 0===im)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);im=t&&t[1]||""}return"\n"+im+e}var ej=!1;function eH(e,t){if(!e||ej)return"";ej=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t){if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(t,[])}catch(e){var r=e}Reflect.construct(e,[],t)}else{try{t.call()}catch(e){r=e}e.call(t.prototype)}}else{try{throw Error()}catch(e){r=e}e()}}catch(t){if(t&&r&&"string"==typeof t.stack){for(var l=t.stack.split("\n"),a=r.stack.split("\n"),o=l.length-1,i=a.length-1;1<=o&&0<=i&&l[o]!==a[i];)i--;for(;1<=o&&0<=i;o--,i--)if(l[o]!==a[i]){if(1!==o||1!==i)do if(o--,0>--i||l[o]!==a[i]){var u="\n"+l[o].replace(" at new "," at ");return e.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",e.displayName)),u}while(1<=o&&0<=i);break}}}finally{ej=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?eW(e):""}function eq(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function eK(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function eY(e){e._valueTracker||(e._valueTracker=function(e){var t=eK(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&void 0!==n&&"function"==typeof n.get&&"function"==typeof n.set){var l=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(e){r=""+e,a.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function eX(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=eK(e)?e.checked?"true":"false":e.value),(e=r)!==n&&(t.setValue(e),!0)}function eG(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}var eZ=/[\n"\\]/g;function eJ(e){return e.replace(eZ,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function e0(e,t,n,r,l,a,o,i){e.name="",null!=o&&"function"!=typeof o&&"symbol"!=typeof o&&"boolean"!=typeof o?e.type=o:e.removeAttribute("type"),null!=t?"number"===o?(0===t&&""===e.value||e.value!=t)&&(e.value=""+eq(t)):e.value!==""+eq(t)&&(e.value=""+eq(t)):"submit"!==o&&"reset"!==o||e.removeAttribute("value"),null!=t?e2(e,o,eq(t)):null!=n?e2(e,o,eq(n)):null!=r&&e.removeAttribute("value"),null==l&&null!=a&&(e.defaultChecked=!!a),null!=l&&!!l!==e.checked&&(e.checked=l),null!=i&&"function"!=typeof i&&"symbol"!=typeof i&&"boolean"!=typeof i?e.name=""+eq(i):e.removeAttribute("name")}function e1(e,t,n,r,l,a,o,i){if(null!=a&&"function"!=typeof a&&"symbol"!=typeof a&&"boolean"!=typeof a&&(e.type=a),null!=t||null!=n){if(!("submit"!==a&&"reset"!==a||null!=t))return;n=null!=n?""+eq(n):"",t=null!=t?""+eq(t):n,i||t===e.value||(e.value=t),e.defaultValue=t}r="function"!=typeof(r=null!=r?r:l)&&"symbol"!=typeof r&&!!r,i||(e.checked=!!r),e.defaultChecked=!!r,null!=o&&"function"!=typeof o&&"symbol"!=typeof o&&"boolean"!=typeof o&&(e.name=o)}function e2(e,t,n){"number"===t&&eG(e.ownerDocument)===e||e.defaultValue===""+n||(e.defaultValue=""+n)}var e3=Array.isArray;function e4(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l<n.length;l++)t["$"+n[l]]=!0;for(n=0;n<e.length;n++)l=t.hasOwnProperty("$"+e[n].value),e[n].selected!==l&&(e[n].selected=l),l&&r&&(e[n].defaultSelected=!0)}else{for(l=0,n=""+eq(n),t=null;l<e.length;l++){if(e[l].value===n){e[l].selected=!0,r&&(e[l].defaultSelected=!0);return}null!==t||e[l].disabled||(t=e[l])}null!==t&&(t.selected=!0)}}function e8(e,t,n){if(null!=t&&((t=""+eq(t))!==e.value&&(e.value=t),null==n)){e.defaultValue!==t&&(e.defaultValue=t);return}e.defaultValue=null!=n?""+eq(n):""}function e6(e,t,n,r){if(null==t){if(null!=r){if(null!=n)throw Error(i(92));if(e3(r)){if(1<r.length)throw Error(i(93));r=r[0]}n=r}null==n&&(n=""),t=n}n=eq(t),e.defaultValue=n,(r=e.textContent)===n&&""!==r&&null!==r&&(e.value=r)}function e5(e,t){if("http://www.w3.org/2000/svg"!==e.namespaceURI||"innerHTML"in e)e.innerHTML=t;else{for((ig=ig||document.createElement("div")).innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=ig.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}}var e7=e5;"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(e7=function(e,t){return MSApp.execUnsafeLocalFunction(function(){return e5(e,t)})});var e9=e7;function te(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType){n.nodeValue=t;return}}e.textContent=t}var tt=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function tn(e,t){if(null!=t&&"object"!=typeof t)throw Error(i(62));for(var n in e=e.style,t)if(t.hasOwnProperty(n)){var r=t[n],l=0===n.indexOf("--");null==r||"boolean"==typeof r||""===r?l?e.setProperty(n,""):"float"===n?e.cssFloat="":e[n]="":l?e.setProperty(n,r):"number"!=typeof r||0===r||tt.has(n)?"float"===n?e.cssFloat=r:e[n]=(""+r).trim():e[n]=r+"px"}}function tr(e){if(-1===e.indexOf("-"))return!1;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var tl=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),ta=null;function to(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}var ti=null,tu=null;function ts(e){var t=eN(e);if(t&&(e=t.stateNode)){var n=eL(e);e:switch(e=t.stateNode,t.type){case"input":if(e0(e,n.value,n.defaultValue,n.defaultValue,n.checked,n.defaultChecked,n.type,n.name),t=n.name,"radio"===n.type&&null!=t){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll('input[name="'+eJ(""+t)+'"][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var l=eL(r);if(!l)throw Error(i(90));eX(r),e0(r,l.value,l.defaultValue,l.defaultValue,l.checked,l.defaultChecked,l.type,l.name)}}}break e;case"textarea":e8(e,n.value,n.defaultValue);break e;case"select":null!=(t=n.value)&&e4(e,!!n.multiple,t,!1)}}}function tc(e){ti?tu?tu.push(e):tu=[e]:ti=e}function tf(){if(ti){var e=ti,t=tu;if(tu=ti=null,ts(e),t)for(e=0;e<t.length;e++)ts(t[e])}}function td(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do 0!=(4098&(t=e).flags)&&(n=t.return),e=t.return;while(e)}return 3===t.tag?n:null}function tp(e){if(13===e.tag){var t=e.memoizedState;if(null===t&&null!==(e=e.alternate)&&(t=e.memoizedState),null!==t)return t.dehydrated}return null}function th(e){if(td(e)!==e)throw Error(i(188))}function tm(e){return null!==(e=function(e){var t=e.alternate;if(!t){if(null===(t=td(e)))throw Error(i(188));return t!==e?null:e}for(var n=e,r=t;;){var l=n.return;if(null===l)break;var a=l.alternate;if(null===a){if(null!==(r=l.return)){n=r;continue}break}if(l.child===a.child){for(a=l.child;a;){if(a===n)return th(l),e;if(a===r)return th(l),t;a=a.sibling}throw Error(i(188))}if(n.return!==r.return)n=l,r=a;else{for(var o=!1,u=l.child;u;){if(u===n){o=!0,n=l,r=a;break}if(u===r){o=!0,r=l,n=a;break}u=u.sibling}if(!o){for(u=a.child;u;){if(u===n){o=!0,n=a,r=l;break}if(u===r){o=!0,r=a,n=l;break}u=u.sibling}if(!o)throw Error(i(189))}}if(n.alternate!==r)throw Error(i(190))}if(3!==n.tag)throw Error(i(188));return n.stateNode.current===n?e:t}(e))?function e(t){var n=t.tag;if(5===n||26===n||27===n||6===n)return t;for(t=t.child;null!==t;){if(null!==(n=e(t)))return n;t=t.sibling}return null}(e):null}var tg={},ty=d(tg),tv=d(!1),tb=tg;function tk(e,t){var n=e.type.contextTypes;if(!n)return tg;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l,a={};for(l in n)a[l]=t[l];return r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function tw(e){return null!=(e=e.childContextTypes)}function tS(){p(tv),p(ty)}function tE(e,t,n){if(ty.current!==tg)throw Error(i(168));h(ty,t),h(tv,n)}function tx(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,"function"!=typeof r.getChildContext)return n;for(var l in r=r.getChildContext())if(!(l in t))throw Error(i(108,function(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=(e=t.render).displayName||e.name||"",t.displayName||(""!==e?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 26:case 27:case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return function e(t){if(null==t)return null;if("function"==typeof t)return t.displayName||t.name||null;if("string"==typeof t)return t;switch(t){case y:return"Fragment";case g:return"Portal";case b:return"Profiler";case v:return"StrictMode";case x:return"Suspense";case C:return"SuspenseList";case T:return"Cache"}if("object"==typeof t)switch(t.$$typeof){case w:return(t.displayName||"Context")+".Consumer";case k:return(t._context.displayName||"Context")+".Provider";case E:var n=t.render;return(t=t.displayName)||(t=""!==(t=n.displayName||n.name||"")?"ForwardRef("+t+")":"ForwardRef"),t;case z:return null!==(n=t.displayName||null)?n:e(t.type)||"Memo";case P:n=t._payload,t=t._init;try{return e(t(n))}catch(e){break}case S:return(t.displayName||t._globalName)+".Provider"}return null}(t);case 8:return t===v?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof t)return t.displayName||t.name||null;if("string"==typeof t)return t}return null}(e)||"Unknown",l));return u({},n,r)}function tC(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||tg,tb=ty.current,h(ty,e),h(tv,tv.current),!0}function tz(e,t,n){var r=e.stateNode;if(!r)throw Error(i(169));n?(e=tx(e,t,tb),r.__reactInternalMemoizedMergedChildContext=e,p(tv),p(ty),h(ty,e)):p(tv),h(tv,n)}var tP="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},tN=[],t_=0,tL=null,tT=0,tM=[],tF=0,tD=null,tR=1,tO="";function tA(e,t){tN[t_++]=tT,tN[t_++]=tL,tL=e,tT=t}function tI(e,t,n){tM[tF++]=tR,tM[tF++]=tO,tM[tF++]=tD,tD=e;var r=tR;e=tO;var l=32-et(r)-1;r&=~(1<<l),n+=1;var a=32-et(t)+l;if(30<a){var o=l-l%5;a=(r&(1<<o)-1).toString(32),r>>=o,l-=o,tR=1<<32-et(t)+l|n<<l|r,tO=a+e}else tR=1<<a|n<<l|r,tO=e}function tU(e){null!==e.return&&(tA(e,1),tI(e,1,0))}function tB(e){for(;e===tL;)tL=tN[--t_],tN[t_]=null,tT=tN[--t_],tN[t_]=null;for(;e===tD;)tD=tM[--tF],tM[tF]=null,tO=tM[--tF],tM[tF]=null,tR=tM[--tF],tM[tF]=null}var tV=null,tQ=null,t$=!1,tW=null,tj=!1;function tH(e,t){var n=oX(5,null,null,0);n.elementType="DELETED",n.stateNode=t,n.return=e,null===(t=e.deletions)?(e.deletions=[n],e.flags|=16):t.push(n)}function tq(e,t){t.flags=-4097&t.flags|2}function tK(e,t){return null!==(t=function(e,t,n,r){for(;1===e.nodeType;){if(e.nodeName.toLowerCase()!==t.toLowerCase()){if(!r)break}else{if(!r)return e;if(!e[eC])switch(t){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":var l=e.getAttribute("rel");if("stylesheet"===l&&e.hasAttribute("data-precedence")||l!==n.rel||e.getAttribute("href")!==(null==n.href?null:n.href)||e.getAttribute("crossorigin")!==(null==n.crossOrigin?null:n.crossOrigin)||e.getAttribute("title")!==(null==n.title?null:n.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if((l=e.getAttribute("src"))&&e.hasAttribute("async")&&!e.hasAttribute("itemprop")||l!==(null==n.src?null:n.src)||e.getAttribute("type")!==(null==n.type?null:n.type)||e.getAttribute("crossorigin")!==(null==n.crossOrigin?null:n.crossOrigin))break;return e;default:return e}}if(null===(e=sL(e.nextSibling)))break}return null}(t,e.type,e.pendingProps,tj))&&(e.stateNode=t,tV=e,tQ=sL(t.firstChild),tj=!1,!0)}function tY(e,t){return null!==(t=function(e,t,n){if(""===t)return null;for(;3!==e.nodeType;)if(!n||null===(e=sL(e.nextSibling)))return null;return e}(t,e.pendingProps,tj))&&(e.stateNode=t,tV=e,tQ=null,!0)}function tX(e,t){e:{var n=t;for(t=tj;8!==n.nodeType;)if(!t||null===(n=sL(n.nextSibling))){t=null;break e}t=n}return null!==t&&(n=null!==tD?{id:tR,overflow:tO}:null,e.memoizedState={dehydrated:t,treeContext:n,retryLane:1073741824},(n=oX(18,null,null,0)).stateNode=t,n.return=e,e.child=n,tV=e,tQ=null,!0)}function tG(e){return 0!=(1&e.mode)&&0==(128&e.flags)}function tZ(){throw Error(i(418))}function tJ(e){var t=e.stateNode,n=e.type,r=e.memoizedProps;t[ev]=e,t[eb]=r;var l=0!=(1&e.mode);switch(n){case"dialog":u5("cancel",t),u5("close",t);break;case"iframe":case"object":case"embed":u5("load",t);break;case"video":case"audio":for(n=0;n<u3.length;n++)u5(u3[n],t);break;case"source":u5("error",t);break;case"img":case"image":case"link":u5("error",t),u5("load",t);break;case"details":u5("toggle",t);break;case"input":u5("invalid",t),e1(t,r.value,r.defaultValue,r.checked,r.defaultChecked,r.type,r.name,!0),eY(t);break;case"select":u5("invalid",t);break;case"textarea":u5("invalid",t),e6(t,r.value,r.defaultValue,r.children),eY(t)}n=null;var a=r.children;return"string"!=typeof a&&"number"!=typeof a||t.textContent===""+a||(!0!==r.suppressHydrationWarning&&sc(t.textContent,a,l),l||(n=["children",a])),null!=r.onScroll&&u5("scroll",t),null!=r.onClick&&(t.onclick=sf),t=n,e.updateQueue=t,null!==t}function t0(e){for(tV=e.return;tV;)switch(tV.tag){case 3:case 27:tj=!0;return;case 5:case 13:tj=!1;return;default:tV=tV.return}}function t1(e){if(e!==tV)return!1;if(!t$)return t0(e),t$=!0,!1;var t=!1;if(3===e.tag||27===e.tag||5===e.tag&&sw(e.type,e.memoizedProps)||(t=!0),t&&(t=tQ)){if(tG(e))t2(),tZ();else for(;t;)tH(e,t),t=sL(t.nextSibling)}if(t0(e),13===e.tag){if(!(e=null!==(e=e.memoizedState)?e.dehydrated:null))throw Error(i(317));e:{for(t=0,e=e.nextSibling;e;){if(8===e.nodeType){var n=e.data;if("/$"===n){if(0===t){tQ=sL(e.nextSibling);break e}t--}else"$"!==n&&"$!"!==n&&"$?"!==n||t++}e=e.nextSibling}tQ=null}}else tQ=tV?sL(e.stateNode.nextSibling):null;return!0}function t2(){for(var e=tQ;e;)e=sL(e.nextSibling)}function t3(){tQ=tV=null,t$=!1}function t4(e){null===tW?tW=[e]:tW.push(e)}var t8=[],t6=0,t5=0;function t7(){for(var e=t6,t=t5=t6=0;t<e;){var n=t8[t];t8[t++]=null;var r=t8[t];t8[t++]=null;var l=t8[t];t8[t++]=null;var a=t8[t];if(t8[t++]=null,null!==r&&null!==l){var o=r.pending;null===o?l.next=l:(l.next=o.next,o.next=l),r.pending=l}0!==a&&nt(n,l,a)}}function t9(e,t,n,r){t8[t6++]=e,t8[t6++]=t,t8[t6++]=n,t8[t6++]=r,t5|=r,e.lanes|=r,null!==(e=e.alternate)&&(e.lanes|=r)}function ne(e,t){return t9(e,null,null,t),nn(e)}function nt(e,t,n){e.lanes|=n;var r=e.alternate;null!==r&&(r.lanes|=n);for(var l=!1,a=e.return;null!==a;)a.childLanes|=n,null!==(r=a.alternate)&&(r.childLanes|=n),22===a.tag&&(null===(e=a.stateNode)||1&e._visibility||(l=!0)),e=a,a=a.return;l&&null!==t&&3===e.tag&&(a=e.stateNode,l=31-et(n),null===(e=(a=a.hiddenUpdates)[l])?a[l]=[t]:e.push(t),t.lane=1073741824|n)}function nn(e){if(50<og)throw og=0,oy=null,Error(i(185));for(var t=e.return;null!==t;)t=(e=t).return;return 3===e.tag?e.stateNode:null}var nr=!1;function nl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function na(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function no(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function ni(e,t,n){var r=e.updateQueue;if(null===r)return null;if(r=r.shared,0!=(2&a0)){var l=r.pending;return null===l?t.next=t:(t.next=l.next,l.next=t),r.pending=t,t=nn(e),nt(e,null,n),t}return t9(e,r,t,n),nn(e)}function nu(e,t,n){if(null!==(t=t.updateQueue)&&(t=t.shared,0!=(8388480&n))){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ep(e,n)}}function ns(e,t){var n=e.updateQueue,r=e.alternate;if(null!==r&&n===(r=r.updateQueue)){var l=null,a=null;if(null!==(n=n.firstBaseUpdate)){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};null===a?l=a=o:a=a.next=o,n=n.next}while(null!==n);null===a?l=a=t:a=a.next=t}else l=a=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}null===(e=n.lastBaseUpdate)?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function nc(e,t,n,r){var l=e.updateQueue;nr=!1;var a=l.firstBaseUpdate,o=l.lastBaseUpdate,i=l.shared.pending;if(null!==i){l.shared.pending=null;var s=i,c=s.next;s.next=null,null===o?a=c:o.next=c,o=s;var f=e.alternate;null!==f&&(i=(f=f.updateQueue).lastBaseUpdate)!==o&&(null===i?f.firstBaseUpdate=c:i.next=c,f.lastBaseUpdate=s)}if(null!==a){var d=l.baseState;for(o=0,f=c=s=null,i=a;;){var p=-1073741825&i.lane,h=p!==i.lane;if(h?(a3&p)===p:(r&p)===p){null!==f&&(f=f.next={lane:0,tag:i.tag,payload:i.payload,callback:null,next:null});e:{var m=e,g=i;switch(p=t,g.tag){case 1:if("function"==typeof(m=g.payload)){d=m.call(n,d,p);break e}d=m;break e;case 3:m.flags=-65537&m.flags|128;case 0:if(null==(p="function"==typeof(m=g.payload)?m.call(n,d,p):m))break e;d=u({},d,p);break e;case 2:nr=!0}}null!==(p=i.callback)&&(e.flags|=64,h&&(e.flags|=8192),null===(h=l.callbacks)?l.callbacks=[p]:h.push(p))}else h={lane:p,tag:i.tag,payload:i.payload,callback:i.callback,next:null},null===f?(c=f=h,s=d):f=f.next=h,o|=p;if(null===(i=i.next)){if(null===(i=l.shared.pending))break;i=(h=i).next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}null===f&&(s=d),l.baseState=s,l.firstBaseUpdate=c,l.lastBaseUpdate=f,null===a&&(l.shared.lanes=0),oe|=o,e.lanes=o,e.memoizedState=d}}function nf(e,t){if("function"!=typeof e)throw Error(i(191,e));e.call(t)}function nd(e,t){var n=e.callbacks;if(null!==n)for(e.callbacks=null,e=0;e<n.length;e++)nf(n[e],t)}function np(e,t){if(tP(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var l=n[r];if(!eg.call(t,l)||!tP(e[l],t[l]))return!1}return!0}var nh=Error(i(460)),nm=Error(i(474)),ng={then:function(){}};function ny(e){return"fulfilled"===(e=e.status)||"rejected"===e}function nv(){}function nb(e,t,n){switch(void 0===(n=e[n])?e.push(t):n!==t&&(t.then(nv,nv),t=n),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch("string"==typeof t.status?t.then(nv,nv):((e=t).status="pending",e.then(function(e){if("pending"===t.status){var n=t;n.status="fulfilled",n.value=e}},function(e){if("pending"===t.status){var n=t;n.status="rejected",n.reason=e}})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}throw nk=t,nh}}var nk=null;function nw(){if(null===nk)throw Error(i(459));var e=nk;return nk=null,e}var nS=null,nE=0;function nx(e){var t=nE;return nE+=1,null===nS&&(nS=[]),nb(nS,e,t)}function nC(e,t,n){if(null!==(e=n.ref)&&"function"!=typeof e&&"object"!=typeof e){if(n._owner){if(n=n._owner){if(1!==n.tag)throw Error(i(309));var r=n.stateNode}if(!r)throw Error(i(147,e));var l=r,a=""+e;return null!==t&&null!==t.ref&&"function"==typeof t.ref&&t.ref._stringRef===a?t.ref:((t=function(e){var t=l.refs;null===e?delete t[a]:t[a]=e})._stringRef=a,t)}if("string"!=typeof e)throw Error(i(284));if(!n._owner)throw Error(i(290,e))}return e}function nz(e,t){throw Error(i(31,"[object Object]"===(e=Object.prototype.toString.call(t))?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function nP(e){return(0,e._init)(e._payload)}function nN(e){function t(t,n){if(e){var r=t.deletions;null===r?(t.deletions=[n],t.flags|=16):r.push(n)}}function n(n,r){if(!e)return null;for(;null!==r;)t(n,r),r=r.sibling;return null}function r(e,t){for(e=new Map;null!==t;)null!==t.key?e.set(t.key,t):e.set(t.index,t),t=t.sibling;return e}function l(e,t){return(e=oZ(e,t)).index=0,e.sibling=null,e}function a(t,n,r){return(t.index=r,e)?null!==(r=t.alternate)?(r=r.index)<n?(t.flags|=33554434,n):r:(t.flags|=33554434,n):(t.flags|=1048576,n)}function o(t){return e&&null===t.alternate&&(t.flags|=33554434),t}function u(e,t,n,r){return null===t||6!==t.tag?((t=o3(n,e.mode,r)).return=e,t):((t=l(t,n)).return=e,t)}function s(e,t,n,r){var a=n.type;return a===y?f(e,t,n.props.children,r,n.key):null!==t&&(t.elementType===a||"object"==typeof a&&null!==a&&a.$$typeof===P&&nP(a)===t.type)?((r=l(t,n.props)).ref=nC(e,t,n),r.return=e,r):((r=o0(n.type,n.key,n.props,null,e.mode,r)).ref=nC(e,t,n),r.return=e,r)}function c(e,t,n,r){return null===t||4!==t.tag||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation?((t=o4(n,e.mode,r)).return=e,t):((t=l(t,n.children||[])).return=e,t)}function f(e,t,n,r,a){return null===t||7!==t.tag?((t=o1(n,e.mode,r,a)).return=e,t):((t=l(t,n)).return=e,t)}function d(e,t,n){if("string"==typeof t&&""!==t||"number"==typeof t)return(t=o3(""+t,e.mode,n)).return=e,t;if("object"==typeof t&&null!==t){switch(t.$$typeof){case m:return(n=o0(t.type,t.key,t.props,null,e.mode,n)).ref=nC(e,null,t),n.return=e,n;case g:return(t=o4(t,e.mode,n)).return=e,t;case P:var r=t._init;return d(e,r(t._payload),n)}if(e3(t)||D(t))return(t=o1(t,e.mode,n,null)).return=e,t;if("function"==typeof t.then)return d(e,nx(t),n);if(t.$$typeof===w||t.$$typeof===S)return d(e,l$(e,t,n),n);nz(e,t)}return null}function p(e,t,n,r){var l=null!==t?t.key:null;if("string"==typeof n&&""!==n||"number"==typeof n)return null!==l?null:u(e,t,""+n,r);if("object"==typeof n&&null!==n){switch(n.$$typeof){case m:return n.key===l?s(e,t,n,r):null;case g:return n.key===l?c(e,t,n,r):null;case P:return p(e,t,(l=n._init)(n._payload),r)}if(e3(n)||D(n))return null!==l?null:f(e,t,n,r,null);if("function"==typeof n.then)return p(e,t,nx(n),r);if(n.$$typeof===w||n.$$typeof===S)return p(e,t,l$(e,n,r),r);nz(e,n)}return null}function h(e,t,n,r,l){if("string"==typeof r&&""!==r||"number"==typeof r)return u(t,e=e.get(n)||null,""+r,l);if("object"==typeof r&&null!==r){switch(r.$$typeof){case m:return s(t,e=e.get(null===r.key?n:r.key)||null,r,l);case g:return c(t,e=e.get(null===r.key?n:r.key)||null,r,l);case P:return h(e,t,n,(0,r._init)(r._payload),l)}if(e3(r)||D(r))return f(t,e=e.get(n)||null,r,l,null);if("function"==typeof r.then)return h(e,t,n,nx(r),l);if(r.$$typeof===w||r.$$typeof===S)return h(e,t,n,l$(t,r,l),l);nz(t,r)}return null}return function u(s,c,f,v){return nE=0,s=function s(c,f,v,b){if("object"==typeof v&&null!==v&&v.type===y&&null===v.key&&(v=v.props.children),"object"==typeof v&&null!==v){switch(v.$$typeof){case m:e:{for(var k=v.key,E=f;null!==E;){if(E.key===k){if((k=v.type)===y){if(7===E.tag){n(c,E.sibling),(f=l(E,v.props.children)).return=c,c=f;break e}}else if(E.elementType===k||"object"==typeof k&&null!==k&&k.$$typeof===P&&nP(k)===E.type){n(c,E.sibling),(f=l(E,v.props)).ref=nC(c,E,v),f.return=c,c=f;break e}n(c,E);break}t(c,E),E=E.sibling}v.type===y?((f=o1(v.props.children,c.mode,b,v.key)).return=c,c=f):((b=o0(v.type,v.key,v.props,null,c.mode,b)).ref=nC(c,f,v),b.return=c,c=b)}return o(c);case g:e:{for(E=v.key;null!==f;){if(f.key===E){if(4===f.tag&&f.stateNode.containerInfo===v.containerInfo&&f.stateNode.implementation===v.implementation){n(c,f.sibling),(f=l(f,v.children||[])).return=c,c=f;break e}n(c,f);break}t(c,f),f=f.sibling}(f=o4(v,c.mode,b)).return=c,c=f}return o(c);case P:return u(c,f,(E=v._init)(v._payload),b)}if(e3(v))return function(l,o,i,u){for(var s=null,c=null,f=o,m=o=0,g=null;null!==f&&m<i.length;m++){f.index>m?(g=f,f=null):g=f.sibling;var y=p(l,f,i[m],u);if(null===y){null===f&&(f=g);break}e&&f&&null===y.alternate&&t(l,f),o=a(y,o,m),null===c?s=y:c.sibling=y,c=y,f=g}if(m===i.length)return n(l,f),t$&&tA(l,m),s;if(null===f){for(;m<i.length;m++)null!==(f=d(l,i[m],u))&&(o=a(f,o,m),null===c?s=f:c.sibling=f,c=f);return t$&&tA(l,m),s}for(f=r(l,f);m<i.length;m++)null!==(g=h(f,l,m,i[m],u))&&(e&&null!==g.alternate&&f.delete(null===g.key?m:g.key),o=a(g,o,m),null===c?s=g:c.sibling=g,c=g);return e&&f.forEach(function(e){return t(l,e)}),t$&&tA(l,m),s}(c,f,v,b);if(D(v))return function(l,o,u,s){var c=D(u);if("function"!=typeof c)throw Error(i(150));if(null==(u=c.call(u)))throw Error(i(151));for(var f=c=null,m=o,g=o=0,y=null,v=u.next();null!==m&&!v.done;g++,v=u.next()){m.index>g?(y=m,m=null):y=m.sibling;var b=p(l,m,v.value,s);if(null===b){null===m&&(m=y);break}e&&m&&null===b.alternate&&t(l,m),o=a(b,o,g),null===f?c=b:f.sibling=b,f=b,m=y}if(v.done)return n(l,m),t$&&tA(l,g),c;if(null===m){for(;!v.done;g++,v=u.next())null!==(v=d(l,v.value,s))&&(o=a(v,o,g),null===f?c=v:f.sibling=v,f=v);return t$&&tA(l,g),c}for(m=r(l,m);!v.done;g++,v=u.next())null!==(v=h(m,l,g,v.value,s))&&(e&&null!==v.alternate&&m.delete(null===v.key?g:v.key),o=a(v,o,g),null===f?c=v:f.sibling=v,f=v);return e&&m.forEach(function(e){return t(l,e)}),t$&&tA(l,g),c}(c,f,v,b);if("function"==typeof v.then)return s(c,f,nx(v),b);if(v.$$typeof===w||v.$$typeof===S)return s(c,f,l$(c,v,b),b);nz(c,v)}return"string"==typeof v&&""!==v||"number"==typeof v?(v=""+v,null!==f&&6===f.tag?(n(c,f.sibling),(f=l(f,v)).return=c,c=f):(n(c,f),(f=o3(v,c.mode,b)).return=c,c=f),o(c)):n(c,f)}(s,c,f,v),nS=null,s}}var n_=nN(!0),nL=nN(!1),nT=d(null),nM=d(0);function nF(e,t){h(nM,e=a5),h(nT,t),a5=e|t.baseLanes}function nD(){h(nM,a5),h(nT,nT.current)}function nR(){a5=nM.current,p(nT),p(nM)}var nO=d(null),nA=null;function nI(e){var t=e.alternate;h(nQ,1&nQ.current),h(nO,e),null===nA&&(null===t||null!==nT.current?nA=e:null!==t.memoizedState&&(nA=e))}function nU(e){if(22===e.tag){if(h(nQ,nQ.current),h(nO,e),null===nA){var t=e.alternate;null!==t&&null!==t.memoizedState&&(nA=e)}}else nB(e)}function nB(){h(nQ,nQ.current),h(nO,nO.current)}function nV(e){p(nO),nA===e&&(nA=null),p(nQ)}var nQ=d(0);function n$(e){for(var t=e;null!==t;){if(13===t.tag){var n=t.memoizedState;if(null!==n&&(null===(n=n.dehydrated)||"$?"===n.data||"$!"===n.data))return t}else if(19===t.tag&&void 0!==t.memoizedProps.revealOrder){if(0!=(128&t.flags))return t}else if(null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var nW=[];function nj(){for(var e=0;e<nW.length;e++)nW[e]._workInProgressVersionPrimary=null;nW.length=0}var nH=null,nq=null,nK=!1,nY=!1,nX=!1,nG=0;function nZ(e){e!==nq&&null===e.next&&(null===nq?nH=nq=e:nq=nq.next=e),nY=!0,nK||(nK=!0,n3(n1))}function nJ(e){if(!nX&&nY){var t=a1,n=a3,r=null;nX=!0;do for(var l=!1,a=nH;null!==a;){if((!e||0===a.tag)&&0!=(3&ei(a,a===t?n:0)))try{l=!0;var o=a;if(0!=(6&a0))throw Error(i(327));oV();var u=ei(o,0);if(0!=(3&u)){var s=oD(o,u);if(0!==o.tag&&2===s){var c=u,f=eu(o,c);0!==f&&(u=f,s=ow(o,c,f))}if(1===s)throw c=a9,oN(o,0),ox(o,u),nZ(o),c;6===s?ox(o,u):(o.finishedWork=o.current.alternate,o.finishedLanes=u,oU(o,ol,oi))}nZ(o)}catch(e){null===r?r=[e]:r.push(e)}a=a.next}while(l);if(nX=!1,null!==r){if(1<r.length){if("function"==typeof AggregateError)throw AggregateError(r);for(e=1;e<r.length;e++)n3(n0.bind(null,r[e]))}throw r[0]}}}function n0(e){throw e}function n1(){nY=nK=!1;for(var e=H(),t=null,n=nH;null!==n;){var r=n.next;0!==nG&&window.event&&"popstate"===window.event.type&&ep(n,2|nG);var l=n2(n,e);0===l?(n.next=null,null===t?nH=r:t.next=r,null===r&&(nq=t)):(t=n,0!=(3&l)&&(nY=!0)),n=r}nG=0,nJ(!1)}function n2(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,a=-125829121&e.pendingLanes;0<a;){var o=31-et(a),i=1<<o,u=l[o];-1===u?(0==(i&n)||0!=(i&r))&&(l[o]=function(e,t){switch(e){case 1:case 2:case 4:case 8:return t+250;case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:return t+5e3;default:return -1}}(i,t)):u<=t&&(e.expiredLanes|=i),a&=~i}if(t=a1,n=a3,n=ei(e,e===t?n:0),r=e.callbackNode,0===n||e===t&&2===a4||null!==e.cancelPendingCommit)return null!==r&&null!==r&&$(r),e.callbackNode=null,e.callbackPriority=0;if(0!=(3&n))return null!==r&&null!==r&&$(r),e.callbackPriority=2,e.callbackNode=null,2;if((t=n&-n)===e.callbackPriority)return t;switch(null!==r&&$(r),em(n)){case 2:n=K;break;case 8:n=Y;break;case 32:default:n=X;break;case 536870912:n=Z}return r=ok.bind(null,e),n=Q(n,r),e.callbackPriority=t,e.callbackNode=n,t}function n3(e){sC(function(){0!=(6&a0)?Q(K,e):e()})}var n4=s.ReactCurrentDispatcher,n8=s.ReactCurrentBatchConfig,n6=0,n5=null,n7=null,n9=null,re=!1,rt=!1,rn=!1,rr=0,rl=0,ra=null,ro=0;function ri(){throw Error(i(321))}function ru(e,t){if(null===t)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!tP(e[n],t[n]))return!1;return!0}function rs(e,t,n,r,l,a){return n6=a,n5=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,n4.current=null===e||null===e.memoizedState?r0:r1,rn=!1,e=n(r,l),rn=!1,rt&&(e=rf(t,n,r,l)),rc(),e}function rc(){n4.current=rJ;var e=null!==n7&&null!==n7.next;if(n6=0,n9=n7=n5=null,re=!1,rl=0,ra=null,e)throw Error(i(300))}function rf(e,t,n,r){n5=e;var l=0;do{if(rt&&(ra=null),rl=0,rt=!1,25<=l)throw Error(i(301));l+=1,n9=n7=null,e.updateQueue=null,n4.current=r2;var a=t(n,r)}while(rt);return a}function rd(){var e=0!==rr;return rr=0,e}function rp(e,t,n){t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~n}function rh(e){if(re){for(e=e.memoizedState;null!==e;){var t=e.queue;null!==t&&(t.pending=null),e=e.next}re=!1}n6=0,n9=n7=n5=null,rt=!1,rl=rr=0,ra=null}function rm(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===n9?n5.memoizedState=n9=e:n9=n9.next=e,n9}function rg(){if(null===n7){var e=n5.alternate;e=null!==e?e.memoizedState:null}else e=n7.next;var t=null===n9?n5.memoizedState:n9.next;if(null!==t)n9=t,n7=e;else{if(null===e){if(null===n5.alternate)throw Error(i(467));throw Error(i(310))}e={memoizedState:(n7=e).memoizedState,baseState:n7.baseState,baseQueue:n7.baseQueue,queue:n7.queue,next:null},null===n9?n5.memoizedState=n9=e:n9=n9.next=e}return n9}function ry(e){var t=rl;return rl+=1,null===ra&&(ra=[]),e=nb(ra,e,t),null===n5.alternate&&(null===n9?null===n5.memoizedState:null===n9.next)&&(n4.current=r0),e}function rv(e){if(null!==e&&"object"==typeof e){if("function"==typeof e.then)return ry(e);if(e.$$typeof===w||e.$$typeof===S)return lQ(e)}throw Error(i(438,String(e)))}function rb(e,t){return"function"==typeof t?t(e):t}function rk(e){var t=rg(),n=n7,r=t.queue;if(null===r)throw Error(i(311));r.lastRenderedReducer=e;var l=t.baseQueue,a=r.pending;if(null!==a){if(null!==l){var o=l.next;l.next=a.next,a.next=o}n.baseQueue=l=a,r.pending=null}if(null!==l){n=l.next,a=t.baseState;var u=o=null,s=null,c=n;do{var f=-1073741825&c.lane;if(f!==c.lane?(a3&f)===f:(n6&f)===f)null!==s&&(s=s.next={lane:0,revertLane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),f=c.action,rn&&e(a,f),a=c.hasEagerState?c.eagerState:e(a,f);else{var d={lane:f,revertLane:c.revertLane,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};null===s?(u=s=d,o=a):s=s.next=d,n5.lanes|=f,oe|=f}c=c.next}while(null!==c&&c!==n);null===s?o=a:s.next=u,tP(a,t.memoizedState)||(lu=!0),t.memoizedState=a,t.baseState=o,t.baseQueue=s,r.lastRenderedState=a}return null===l&&(r.lanes=0),[t.memoizedState,r.dispatch]}function rw(e){var t=rg(),n=t.queue;if(null===n)throw Error(i(311));n.lastRenderedReducer=e;var r=n.dispatch,l=n.pending,a=t.memoizedState;if(null!==l){n.pending=null;var o=l=l.next;do a=e(a,o.action),o=o.next;while(o!==l);tP(a,t.memoizedState)||(lu=!0),t.memoizedState=a,null===t.baseQueue&&(t.baseState=a),n.lastRenderedState=a}return[a,r]}function rS(){}function rE(e,t){var n=n5,r=rg(),l=t(),a=!tP((n7||r).memoizedState,l);if(a&&(r.memoizedState=l,lu=!0),r=r.queue,rR(rz.bind(null,n,r,e),[e]),r.getSnapshot!==t||a||null!==n9&&1&n9.memoizedState.tag){if(n.flags|=2048,rL(9,rC.bind(null,n,r,l,t),{destroy:void 0},null),null===a1)throw Error(i(349));0!=(60&n6)||rx(n,t,l)}return l}function rx(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},null===(t=n5.updateQueue)?(t=iy(),n5.updateQueue=t,t.stores=[e]):null===(n=t.stores)?t.stores=[e]:n.push(e)}function rC(e,t,n,r){t.value=n,t.getSnapshot=r,rP(t)&&rN(e)}function rz(e,t,n){return n(function(){rP(t)&&rN(e)})}function rP(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!tP(e,n)}catch(e){return!0}}function rN(e){var t=ne(e,2);null!==t&&ob(t,e,2)}function r_(e){var t=rm();return"function"==typeof e&&(e=e()),t.memoizedState=t.baseState=e,t.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:rb,lastRenderedState:e},t}function rL(e,t,n,r){return e={tag:e,create:t,inst:n,deps:r,next:null},null===(t=n5.updateQueue)?(t=iy(),n5.updateQueue=t,t.lastEffect=e.next=e):null===(n=t.lastEffect)?t.lastEffect=e.next=e:(r=n.next,n.next=e,e.next=r,t.lastEffect=e),e}function rT(){return rg().memoizedState}function rM(e,t,n,r){var l=rm();n5.flags|=e,l.memoizedState=rL(1|t,n,{destroy:void 0},void 0===r?null:r)}function rF(e,t,n,r){var l=rg();r=void 0===r?null:r;var a=l.memoizedState.inst;null!==n7&&null!==r&&ru(r,n7.memoizedState.deps)?l.memoizedState=rL(t,n,a,r):(n5.flags|=e,l.memoizedState=rL(1|t,n,a,r))}function rD(e,t){rM(8390656,8,e,t)}function rR(e,t){rF(2048,8,e,t)}function rO(e,t){return rF(4,2,e,t)}function rA(e,t){return rF(4,4,e,t)}function rI(e,t){return"function"==typeof t?(t(e=e()),function(){t(null)}):null!=t?(e=e(),t.current=e,function(){t.current=null}):void 0}function rU(e,t,n){n=null!=n?n.concat([e]):null,rF(4,4,rI.bind(null,t,e),n)}function rB(){}function rV(e,t){var n=rg();t=void 0===t?null:t;var r=n.memoizedState;return null!==t&&ru(t,r[1])?r[0]:(n.memoizedState=[e,t],e)}function rQ(e,t){var n=rg();t=void 0===t?null:t;var r=n.memoizedState;return null!==t&&ru(t,r[1])?r[0]:(rn&&e(),e=e(),n.memoizedState=[e,t],e)}function r$(e,t,n){return 0==(42&n6)?(e.baseState&&(e.baseState=!1,lu=!0),e.memoizedState=n):(tP(n,t)||(n=es(),n5.lanes|=n,oe|=n,e.baseState=!0),t)}function rW(e,t,n,r,l){var a=eh;eh=0!==a&&8>a?a:8;var o=n8.transition;n8.transition=null,rY(e,t,n),n8.transition={};try{rY(e,t,r),l()}catch(e){throw e}finally{eh=a,n8.transition=o}}function rj(){return rg().memoizedState}function rH(){return rg().memoizedState}function rq(e){for(var t=e.return;null!==t;){switch(t.tag){case 24:case 3:var n=ov(t);e=no(n);var r=ni(t,e,n);null!==r&&(ob(r,t,n),nu(r,t,n)),t={cache:lY()},e.payload=t;return}t=t.return}}function rK(e,t,n){var r=ov(e);n={lane:r,revertLane:0,action:n,hasEagerState:!1,eagerState:null,next:null},rX(e)?rG(t,n):(t9(e,t,n,r),null!==(n=nn(e))&&(ob(n,e,r),rZ(n,t,r)))}function rY(e,t,n){var r=ov(e),l={lane:r,revertLane:0,action:n,hasEagerState:!1,eagerState:null,next:null};if(rX(e))rG(t,l);else{var a=e.alternate;if(0===e.lanes&&(null===a||0===a.lanes)&&null!==(a=t.lastRenderedReducer))try{var o=t.lastRenderedState,i=a(o,n);if(l.hasEagerState=!0,l.eagerState=i,tP(i,o)){t9(e,t,l,0),null===a1&&t7();return}}catch(e){}finally{}t9(e,t,l,r),null!==(n=nn(e))&&(ob(n,e,r),rZ(n,t,r))}}function rX(e){var t=e.alternate;return e===n5||null!==t&&t===n5}function rG(e,t){rt=re=!0;var n=e.pending;null===n?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function rZ(e,t,n){if(0!=(8388480&n)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ep(e,n)}}iy=function(){return{lastEffect:null,events:null,stores:null}};var rJ={readContext:lQ,use:rv,useCallback:ri,useContext:ri,useEffect:ri,useImperativeHandle:ri,useInsertionEffect:ri,useLayoutEffect:ri,useMemo:ri,useReducer:ri,useRef:ri,useState:ri,useDebugValue:ri,useDeferredValue:ri,useTransition:ri,useMutableSource:ri,useSyncExternalStore:ri,useId:ri};rJ.useCacheRefresh=ri;var r0={readContext:lQ,use:rv,useCallback:function(e,t){return rm().memoizedState=[e,void 0===t?null:t],e},useContext:lQ,useEffect:rD,useImperativeHandle:function(e,t,n){n=null!=n?n.concat([e]):null,rM(4194308,4,rI.bind(null,t,e),n)},useLayoutEffect:function(e,t){return rM(4194308,4,e,t)},useInsertionEffect:function(e,t){rM(4,2,e,t)},useMemo:function(e,t){var n=rm();return t=void 0===t?null:t,rn&&e(),e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=rm();return t=void 0!==n?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=rK.bind(null,n5,e),[r.memoizedState,e]},useRef:function(e){return e={current:e},rm().memoizedState=e},useState:function(e){var t=(e=r_(e)).queue,n=rY.bind(null,n5,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:rB,useDeferredValue:function(e){return rm().memoizedState=e},useTransition:function(){var e=r_(!1);return e=rW.bind(null,n5,e.queue,!0,!1),rm().memoizedState=e,[!1,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=n5,l=rm();if(t$){if(void 0===n)throw Error(i(407));n=n()}else{if(n=t(),null===a1)throw Error(i(349));0!=(60&n6)||rx(r,t,n)}l.memoizedState=n;var a={value:n,getSnapshot:t};return l.queue=a,rD(rz.bind(null,r,a,e),[e]),r.flags|=2048,rL(9,rC.bind(null,r,a,n,t),{destroy:void 0},null),n},useId:function(){var e=rm(),t=a1.identifierPrefix;if(t$){var n=tO,r=tR;t=":"+t+"R"+(n=(r&~(1<<32-et(r)-1)).toString(32)+n),0<(n=rr++)&&(t+="H"+n.toString(32)),t+=":"}else t=":"+t+"r"+(n=ro++).toString(32)+":";return e.memoizedState=t},useCacheRefresh:function(){return rm().memoizedState=rq.bind(null,n5)}},r1={readContext:lQ,use:rv,useCallback:rV,useContext:lQ,useEffect:rR,useImperativeHandle:rU,useInsertionEffect:rO,useLayoutEffect:rA,useMemo:rQ,useReducer:rk,useRef:rT,useState:function(){return rk(rb)},useDebugValue:rB,useDeferredValue:function(e){return r$(rg(),n7.memoizedState,e)},useTransition:function(){var e=rk(rb)[0],t=rg().memoizedState;return["boolean"==typeof e?e:ry(e),t]},useMutableSource:rS,useSyncExternalStore:rE,useId:rj};r1.useCacheRefresh=rH;var r2={readContext:lQ,use:rv,useCallback:rV,useContext:lQ,useEffect:rR,useImperativeHandle:rU,useInsertionEffect:rO,useLayoutEffect:rA,useMemo:rQ,useReducer:rw,useRef:rT,useState:function(){return rw(rb)},useDebugValue:rB,useDeferredValue:function(e){var t=rg();return null===n7?t.memoizedState=e:r$(t,n7.memoizedState,e)},useTransition:function(){var e=rw(rb)[0],t=rg().memoizedState;return["boolean"==typeof e?e:ry(e),t]},useMutableSource:rS,useSyncExternalStore:rE,useId:rj};function r3(e,t){if(e&&e.defaultProps)for(var n in t=u({},t),e=e.defaultProps)void 0===t[n]&&(t[n]=e[n]);return t}function r4(e,t,n,r){t=e.memoizedState,n=null==(n=n(r,t))?t:u({},t,n),e.memoizedState=n,0===e.lanes&&(e.updateQueue.baseState=n)}r2.useCacheRefresh=rH;var r8={isMounted:function(e){return!!(e=e._reactInternals)&&td(e)===e},enqueueSetState:function(e,t,n){var r=ov(e=e._reactInternals),l=no(r);l.payload=t,null!=n&&(l.callback=n),null!==(t=ni(e,l,r))&&(ob(t,e,r),nu(t,e,r))},enqueueReplaceState:function(e,t,n){var r=ov(e=e._reactInternals),l=no(r);l.tag=1,l.payload=t,null!=n&&(l.callback=n),null!==(t=ni(e,l,r))&&(ob(t,e,r),nu(t,e,r))},enqueueForceUpdate:function(e,t){var n=ov(e=e._reactInternals),r=no(n);r.tag=2,null!=t&&(r.callback=t),null!==(t=ni(e,r,n))&&(ob(t,e,n),nu(t,e,n))}};function r6(e,t,n,r,l,a,o){return"function"==typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,a,o):!t.prototype||!t.prototype.isPureReactComponent||!np(n,r)||!np(l,a)}function r5(e,t,n){var r=!1,l=tg,a=t.contextType;return"object"==typeof a&&null!==a?a=lQ(a):(l=tw(t)?tb:ty.current,a=(r=null!=(r=t.contextTypes))?tk(e,l):tg),t=new t(n,a),e.memoizedState=null!==t.state&&void 0!==t.state?t.state:null,t.updater=r8,e.stateNode=t,t._reactInternals=e,r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=a),t}function r7(e,t,n,r){e=t.state,"function"==typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(n,r),"function"==typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&r8.enqueueReplaceState(t,t.state,null)}function r9(e,t,n,r){var l=e.stateNode;l.props=n,l.state=e.memoizedState,l.refs={},nl(e);var a=t.contextType;"object"==typeof a&&null!==a?l.context=lQ(a):(a=tw(t)?tb:ty.current,l.context=tk(e,a)),l.state=e.memoizedState,"function"==typeof(a=t.getDerivedStateFromProps)&&(r4(e,t,a,n),l.state=e.memoizedState),"function"==typeof t.getDerivedStateFromProps||"function"==typeof l.getSnapshotBeforeUpdate||"function"!=typeof l.UNSAFE_componentWillMount&&"function"!=typeof l.componentWillMount||(t=l.state,"function"==typeof l.componentWillMount&&l.componentWillMount(),"function"==typeof l.UNSAFE_componentWillMount&&l.UNSAFE_componentWillMount(),t!==l.state&&r8.enqueueReplaceState(l,l.state,null),nc(e,n,l,r),l.state=e.memoizedState),"function"==typeof l.componentDidMount&&(e.flags|=4194308)}function le(e,t){try{var n="",r=t;do n+=function(e){switch(e.tag){case 26:case 27:case 5:return eW(e.type);case 16:return eW("Lazy");case 13:return eW("Suspense");case 19:return eW("SuspenseList");case 0:case 2:case 15:return e=eH(e.type,!1);case 11:return e=eH(e.type.render,!1);case 1:return e=eH(e.type,!0);default:return""}}(r),r=r.return;while(r);var l=n}catch(e){l="\nError generating stack: "+e.message+"\n"+e.stack}return{value:e,source:t,stack:l,digest:null}}function lt(e,t,n){return{value:e,source:null,stack:null!=n?n:null,digest:null!=t?t:null}}function ln(e,t){try{console.error(t.value)}catch(e){setTimeout(function(){throw e})}}function lr(e,t,n){(n=no(n)).tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){ou||(ou=!0,os=r),ln(e,t)},n}function ll(e,t,n){(n=no(n)).tag=3;var r=e.type.getDerivedStateFromError;if("function"==typeof r){var l=t.value;n.payload=function(){return r(l)},n.callback=function(){ln(e,t)}}var a=e.stateNode;return null!==a&&"function"==typeof a.componentDidCatch&&(n.callback=function(){ln(e,t),"function"!=typeof r&&(null===oc?oc=new Set([this]):oc.add(this));var n=t.stack;this.componentDidCatch(t.value,{componentStack:null!==n?n:""})}),n}function la(e,t,n,r,l){return 0==(1&e.mode)?(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,1===n.tag&&(null===n.alternate?n.tag=17:((t=no(2)).tag=2,ni(n,t,2))),n.lanes|=2),e):(e.flags|=65536,e.lanes=l,e)}var lo=s.ReactCurrentOwner,li=Error(i(461)),lu=!1;function ls(e,t,n,r){t.child=null===e?nL(t,null,n,r):n_(t,e.child,n,r)}function lc(e,t,n,r,l){n=n.render;var a=t.ref;return(lV(t,l),r=rs(e,t,n,r,a,l),n=rd(),null===e||lu)?(t$&&n&&tU(t),t.flags|=1,ls(e,t,r,l),t.child):(rp(e,t,l),lT(e,t,l))}function lf(e,t,n,r,l){if(null===e){var a=n.type;return"function"!=typeof a||oG(a)||void 0!==a.defaultProps||null!==n.compare||void 0!==n.defaultProps?((e=o0(n.type,null,r,t,t.mode,l)).ref=t.ref,e.return=t,t.child=e):(t.tag=15,t.type=a,ld(e,t,a,r,l))}if(a=e.child,0==(e.lanes&l)){var o=a.memoizedProps;if((n=null!==(n=n.compare)?n:np)(o,r)&&e.ref===t.ref)return lT(e,t,l)}return t.flags|=1,(e=oZ(a,r)).ref=t.ref,e.return=t,t.child=e}function ld(e,t,n,r,l){if(null!==e){var a=e.memoizedProps;if(np(a,r)&&e.ref===t.ref){if(lu=!1,t.pendingProps=r=a,0==(e.lanes&l))return t.lanes=e.lanes,lT(e,t,l);0!=(131072&e.flags)&&(lu=!0)}}return lg(e,t,n,r,l)}function lp(e,t,n){var r=t.pendingProps,l=r.children,a=0!=(2&t.stateNode._pendingVisibility),o=null!==e?e.memoizedState:null;if(lm(e,t),"hidden"===r.mode||a){if(0!=(128&t.flags)){if(n=null!==o?o.baseLanes|n:n,null!==e){for(l=0,r=t.child=e.child;null!==r;)l=l|r.lanes|r.childLanes,r=r.sibling;t.childLanes=l&~n}else t.childLanes=0,t.child=null;return lh(e,t,n)}if(0==(1&t.mode))t.memoizedState={baseLanes:0,cachePool:null},null!==e&&l0(t,null),nD(),nU(t);else{if(0==(1073741824&n))return t.lanes=t.childLanes=1073741824,lh(e,t,null!==o?o.baseLanes|n:n);t.memoizedState={baseLanes:0,cachePool:null},null!==e&&l0(t,null!==o?o.cachePool:null),null!==o?nF(t,o):nD(),nU(t)}}else null!==o?(l0(t,o.cachePool),nF(t,o),nB(t),t.memoizedState=null):(null!==e&&l0(t,null),nD(),nB(t));return ls(e,t,l,n),t.child}function lh(e,t,n){var r=lJ();return r=null===r?null:{parent:lK._currentValue,pool:r},t.memoizedState={baseLanes:n,cachePool:r},null!==e&&l0(t,null),nD(),nU(t),null}function lm(e,t){var n=t.ref;(null===e&&null!==n||null!==e&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function lg(e,t,n,r,l){var a=tw(n)?tb:ty.current;return(a=tk(t,a),lV(t,l),n=rs(e,t,n,r,a,l),r=rd(),null===e||lu)?(t$&&r&&tU(t),t.flags|=1,ls(e,t,n,l),t.child):(rp(e,t,l),lT(e,t,l))}function ly(e,t,n,r,l,a){return(lV(t,a),n=rf(t,r,n,l),rc(),r=rd(),null===e||lu)?(t$&&r&&tU(t),t.flags|=1,ls(e,t,n,a),t.child):(rp(e,t,a),lT(e,t,a))}function lv(e,t,n,r,l){if(tw(n)){var a=!0;tC(t)}else a=!1;if(lV(t,l),null===t.stateNode)lL(e,t),r5(t,n,r),r9(t,n,r,l),r=!0;else if(null===e){var o=t.stateNode,i=t.memoizedProps;o.props=i;var u=o.context,s=n.contextType;s="object"==typeof s&&null!==s?lQ(s):tk(t,s=tw(n)?tb:ty.current);var c=n.getDerivedStateFromProps,f="function"==typeof c||"function"==typeof o.getSnapshotBeforeUpdate;f||"function"!=typeof o.UNSAFE_componentWillReceiveProps&&"function"!=typeof o.componentWillReceiveProps||(i!==r||u!==s)&&r7(t,o,r,s),nr=!1;var d=t.memoizedState;o.state=d,nc(t,r,o,l),u=t.memoizedState,i!==r||d!==u||tv.current||nr?("function"==typeof c&&(r4(t,n,c,r),u=t.memoizedState),(i=nr||r6(t,n,i,r,d,u,s))?(f||"function"!=typeof o.UNSAFE_componentWillMount&&"function"!=typeof o.componentWillMount||("function"==typeof o.componentWillMount&&o.componentWillMount(),"function"==typeof o.UNSAFE_componentWillMount&&o.UNSAFE_componentWillMount()),"function"==typeof o.componentDidMount&&(t.flags|=4194308)):("function"==typeof o.componentDidMount&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=u),o.props=r,o.state=u,o.context=s,r=i):("function"==typeof o.componentDidMount&&(t.flags|=4194308),r=!1)}else{o=t.stateNode,na(e,t),i=t.memoizedProps,s=t.type===t.elementType?i:r3(t.type,i),o.props=s,f=t.pendingProps,d=o.context,u="object"==typeof(u=n.contextType)&&null!==u?lQ(u):tk(t,u=tw(n)?tb:ty.current);var p=n.getDerivedStateFromProps;(c="function"==typeof p||"function"==typeof o.getSnapshotBeforeUpdate)||"function"!=typeof o.UNSAFE_componentWillReceiveProps&&"function"!=typeof o.componentWillReceiveProps||(i!==f||d!==u)&&r7(t,o,r,u),nr=!1,d=t.memoizedState,o.state=d,nc(t,r,o,l);var h=t.memoizedState;i!==f||d!==h||tv.current||nr?("function"==typeof p&&(r4(t,n,p,r),h=t.memoizedState),(s=nr||r6(t,n,s,r,d,h,u)||!1)?(c||"function"!=typeof o.UNSAFE_componentWillUpdate&&"function"!=typeof o.componentWillUpdate||("function"==typeof o.componentWillUpdate&&o.componentWillUpdate(r,h,u),"function"==typeof o.UNSAFE_componentWillUpdate&&o.UNSAFE_componentWillUpdate(r,h,u)),"function"==typeof o.componentDidUpdate&&(t.flags|=4),"function"==typeof o.getSnapshotBeforeUpdate&&(t.flags|=1024)):("function"!=typeof o.componentDidUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),"function"!=typeof o.getSnapshotBeforeUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=h),o.props=r,o.state=h,o.context=u,r=s):("function"!=typeof o.componentDidUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),"function"!=typeof o.getSnapshotBeforeUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),r=!1)}return lb(e,t,n,r,a,l)}function lb(e,t,n,r,l,a){lm(e,t);var o=0!=(128&t.flags);if(!r&&!o)return l&&tz(t,n,!1),lT(e,t,a);r=t.stateNode,lo.current=t;var i=o&&"function"!=typeof n.getDerivedStateFromError?null:r.render();return t.flags|=1,null!==e&&o?(t.child=n_(t,e.child,null,a),t.child=n_(t,null,i,a)):ls(e,t,i,a),t.memoizedState=r.state,l&&tz(t,n,!0),t.child}function lk(e){var t=e.stateNode;t.pendingContext?tE(e,t.pendingContext,t.pendingContext!==t.context):t.context&&tE(e,t.context,!1),I(e,t.containerInfo)}function lw(e,t,n,r,l){return t3(),t4(l),t.flags|=256,ls(e,t,n,r),t.child}var lS={dehydrated:null,treeContext:null,retryLane:0};function lE(e){return{baseLanes:e,cachePool:l1()}}function lx(e,t,n){var r,l=t.pendingProps,a=!1,o=0!=(128&t.flags);if((r=o)||(r=(null===e||null!==e.memoizedState)&&0!=(2&nQ.current)),r&&(a=!0,t.flags&=-129),null===e){if(t$){if(a?nI(t):nB(t),t$&&((o=e=tQ)?tX(t,o)||(tG(t)&&tZ(),tQ=sL(o.nextSibling),r=tV,tQ&&tX(t,tQ)?tH(r,o):(tq(tV,t),t$=!1,tV=t,tQ=e)):(tG(t)&&tZ(),tq(tV,t),t$=!1,tV=t,tQ=e)),null!==(e=t.memoizedState)&&null!==(e=e.dehydrated))return 0==(1&t.mode)?t.lanes=2:"$!"===e.data?t.lanes=16:t.lanes=1073741824,null;nV(t)}return(o=l.children,e=l.fallback,a)?(nB(t),l=t.mode,a=t.child,o={mode:"hidden",children:o},0==(1&l)&&null!==a?(a.childLanes=0,a.pendingProps=o):a=o2(o,l,0,null),e=o1(e,l,n,null),a.return=t,e.return=t,a.sibling=e,t.child=a,t.child.memoizedState=lE(n),t.memoizedState=lS,e):(nI(t),lC(t,o))}if(null!==(r=e.memoizedState)){var u=r.dehydrated;if(null!==u)return function(e,t,n,r,l,a,o){if(n)return 256&t.flags?(nI(t),t.flags&=-257,lz(e,t,o,r=lt(Error(i(422))))):null!==t.memoizedState?(nB(t),t.child=e.child,t.flags|=128,null):(nB(t),a=r.fallback,l=t.mode,r=o2({mode:"visible",children:r.children},l,0,null),a=o1(a,l,o,null),a.flags|=2,r.return=t,a.return=t,r.sibling=a,t.child=r,0!=(1&t.mode)&&n_(t,e.child,null,o),t.child.memoizedState=lE(o),t.memoizedState=lS,a);if(nI(t),0==(1&t.mode))return lz(e,t,o,null);if("$!"===l.data){if(r=l.nextSibling&&l.nextSibling.dataset)var u=r.dgst;return r=u,(a=Error(i(419))).digest=r,r=lt(a,r,void 0),lz(e,t,o,r)}if(u=0!=(o&e.childLanes),lu||u){if(null!==(r=a1)){switch(o&-o){case 2:l=1;break;case 8:l=4;break;case 32:l=16;break;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:l=64;break;case 536870912:l=268435456;break;default:l=0}if(0!==(l=0!=(l&(r.suspendedLanes|o))?0:l)&&l!==a.retryLane)throw a.retryLane=l,ne(e,l),ob(r,e,l),li}return oF(),lz(e,t,o,null)}return"$?"===l.data?(t.flags|=128,t.child=e.child,t=oq.bind(null,e),l._reactRetry=t,null):(e=a.treeContext,tQ=sL(l.nextSibling),tV=t,t$=!0,tW=null,tj=!1,null!==e&&(tM[tF++]=tR,tM[tF++]=tO,tM[tF++]=tD,tR=e.id,tO=e.overflow,tD=t),t=lC(t,r.children),t.flags|=4096,t)}(e,t,o,l,u,r,n)}if(a){nB(t),a=l.fallback,o=t.mode,u=(r=e.child).sibling;var s={mode:"hidden",children:l.children};return 0==(1&o)&&t.child!==r?((l=t.child).childLanes=0,l.pendingProps=s,t.deletions=null):(l=oZ(r,s)).subtreeFlags=31457280&r.subtreeFlags,null!==u?a=oZ(u,a):(a=o1(a,o,n,null),a.flags|=2),a.return=t,l.return=t,l.sibling=a,t.child=l,l=a,a=t.child,null===(o=e.child.memoizedState)?o=lE(n):(null!==(r=o.cachePool)?(u=lK._currentValue,r=r.parent!==u?{parent:u,pool:u}:r):r=l1(),o={baseLanes:o.baseLanes|n,cachePool:r}),a.memoizedState=o,a.childLanes=e.childLanes&~n,t.memoizedState=lS,l}return nI(t),e=(a=e.child).sibling,l=oZ(a,{mode:"visible",children:l.children}),0==(1&t.mode)&&(l.lanes=n),l.return=t,l.sibling=null,null!==e&&(null===(n=t.deletions)?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=l,t.memoizedState=null,l}function lC(e,t){return(t=o2({mode:"visible",children:t},e.mode,0,null)).return=e,e.child=t}function lz(e,t,n,r){return null!==r&&t4(r),n_(t,e.child,null,n),e=lC(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function lP(e,t,n){e.lanes|=t;var r=e.alternate;null!==r&&(r.lanes|=t),lU(e.return,t,n)}function lN(e,t,n,r,l){var a=e.memoizedState;null===a?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:l}:(a.isBackwards=t,a.rendering=null,a.renderingStartTime=0,a.last=r,a.tail=n,a.tailMode=l)}function l_(e,t,n){var r=t.pendingProps,l=r.revealOrder,a=r.tail;if(ls(e,t,r.children,n),0!=(2&(r=nQ.current)))r=1&r|2,t.flags|=128;else{if(null!==e&&0!=(128&e.flags))e:for(e=t.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&lP(e,n,t);else if(19===e.tag)lP(e,n,t);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;null===e.sibling;){if(null===e.return||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(h(nQ,r),0==(1&t.mode))t.memoizedState=null;else switch(l){case"forwards":for(l=null,n=t.child;null!==n;)null!==(e=n.alternate)&&null===n$(e)&&(l=n),n=n.sibling;null===(n=l)?(l=t.child,t.child=null):(l=n.sibling,n.sibling=null),lN(t,!1,l,n,a);break;case"backwards":for(n=null,l=t.child,t.child=null;null!==l;){if(null!==(e=l.alternate)&&null===n$(e)){t.child=l;break}e=l.sibling,l.sibling=n,n=l,l=e}lN(t,!0,n,null,a);break;case"together":lN(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function lL(e,t){0==(1&t.mode)&&null!==e&&(e.alternate=null,t.alternate=null,t.flags|=2)}function lT(e,t,n){if(null!==e&&(t.dependencies=e.dependencies),oe|=t.lanes,0==(n&t.childLanes))return null;if(null!==e&&t.child!==e.child)throw Error(i(153));if(null!==t.child){for(n=oZ(e=t.child,e.pendingProps),t.child=n,n.return=t;null!==e.sibling;)e=e.sibling,(n=n.sibling=oZ(e,e.pendingProps)).return=t;n.sibling=null}return t.child}var lM=d(null),lF=null,lD=null,lR=null;function lO(){lR=lD=lF=null}function lA(e,t,n){h(lM,t._currentValue),t._currentValue=n}function lI(e){var t=lM.current;e._currentValue=t===M?e._defaultValue:t,p(lM)}function lU(e,t,n){for(;null!==e;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,null!==r&&(r.childLanes|=t)):null!==r&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function lB(e,t,n){var r=e.child;for(null!==r&&(r.return=e);null!==r;){var l=r.dependencies;if(null!==l)for(var a=r.child,o=l.firstContext;null!==o;){if(o.context===t){if(1===r.tag){(o=no(n&-n)).tag=2;var u=r.updateQueue;if(null!==u){var s=(u=u.shared).pending;null===s?o.next=o:(o.next=s.next,s.next=o),u.pending=o}}r.lanes|=n,null!==(o=r.alternate)&&(o.lanes|=n),lU(r.return,n,e),l.lanes|=n;break}o=o.next}else if(10===r.tag)a=r.type===e.type?null:r.child;else if(18===r.tag){if(null===(a=r.return))throw Error(i(341));a.lanes|=n,null!==(l=a.alternate)&&(l.lanes|=n),lU(a,n,e),a=r.sibling}else a=r.child;if(null!==a)a.return=r;else for(a=r;null!==a;){if(a===e){a=null;break}if(null!==(r=a.sibling)){r.return=a.return,a=r;break}a=a.return}r=a}}function lV(e,t){lF=e,lR=lD=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(0!=(e.lanes&t)&&(lu=!0),e.firstContext=null)}function lQ(e){return lW(lF,e)}function l$(e,t,n){return null===lF&&lV(e,n),lW(e,t)}function lW(e,t){var n=t._currentValue;if(lR!==t){if(t={context:t,memoizedValue:n,next:null},null===lD){if(null===e)throw Error(i(308));lD=t,e.dependencies={lanes:0,firstContext:t}}else lD=lD.next=t}return n}var lj="undefined"!=typeof AbortController?AbortController:function(){var e=[],t=this.signal={aborted:!1,addEventListener:function(t,n){e.push(n)}};this.abort=function(){t.aborted=!0,e.forEach(function(e){return e()})}},lH=a.unstable_scheduleCallback,lq=a.unstable_NormalPriority,lK={$$typeof:w,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0,_defaultValue:null,_globalName:null};function lY(){return{controller:new lj,data:new Map,refCount:0}}function lX(e){e.refCount--,0===e.refCount&&lH(lq,function(){e.controller.abort()})}var lG=s.ReactCurrentBatchConfig,lZ=d(null);function lJ(){var e=lZ.current;return null!==e?e:a1.pooledCache}function l0(e,t){null===t?h(lZ,lZ.current):h(lZ,t.pool)}function l1(){var e=lJ();return null===e?null:{parent:lK._currentValue,pool:e}}function l2(e){e.flags|=4}function l3(e){e.flags|=2097664}function l4(e,t,n,r){if((e=e.memoizedProps)!==r){n=null;var l,a,o=null;for(l in e)if(!r.hasOwnProperty(l)&&e.hasOwnProperty(l)&&null!=e[l]){if("style"===l){var i=e[l];for(a in i)i.hasOwnProperty(a)&&(o||(o={}),o[a]="")}else(n=n||[]).push(l,null)}for(l in r){i=r[l];var u=null!=e?e[l]:void 0;if(r.hasOwnProperty(l)&&i!==u&&(null!=i||null!=u)){if("style"===l){if(u){for(a in u)!u.hasOwnProperty(a)||i&&i.hasOwnProperty(a)||(o||(o={}),o[a]="");for(a in i)i.hasOwnProperty(a)&&u[a]!==i[a]&&(o||(o={}),o[a]=i[a])}else o||(n||(n=[]),n.push(l,o)),o=i}else(n=n||[]).push(l,i)}}o&&(n=n||[]).push("style",o),r=n,(t.updateQueue=r)&&l2(t)}}function l8(e,t){if("stylesheet"!==t.type||0!=(4&t.state.loading))e.flags&=-16777217;else if(e.flags|=16777216,0==(42&a3)&&!(t="stylesheet"!==t.type||0!=(3&t.state.loading))){if(oL())e.flags|=8192;else throw nk=ng,nm}}function l6(e,t){null!==t?e.flags|=4:16384&e.flags&&(t=22!==e.tag?ec():1073741824,e.lanes|=t)}function l5(e,t){if(!t$)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;null!==t;)null!==t.alternate&&(n=t),t=t.sibling;null===n?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;null!==n;)null!==n.alternate&&(r=n),n=n.sibling;null===r?t||null===e.tail?e.tail=null:e.tail.sibling=null:r.sibling=null}}function l7(e){var t=null!==e.alternate&&e.alternate.child===e.child,n=0,r=0;if(t)for(var l=e.child;null!==l;)n|=l.lanes|l.childLanes,r|=31457280&l.subtreeFlags,r|=31457280&l.flags,l.return=e,l=l.sibling;else for(l=e.child;null!==l;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function l9(e,t){switch(tB(t),t.tag){case 1:null!=(e=t.type.childContextTypes)&&tS();break;case 3:lI(lK),U(),p(tv),p(ty),nj();break;case 26:case 27:case 5:V(t);break;case 4:U();break;case 13:nV(t);break;case 19:p(nQ);break;case 10:lI(t.type._context);break;case 22:case 23:nV(t),nR(),null!==e&&p(lZ);break;case 24:lI(lK)}}function ae(e,t,n){var r=Array.prototype.slice.call(arguments,3);try{t.apply(n,r)}catch(e){this.onError(e)}}var at=!1,an=null,ar=!1,al=null,aa={onError:function(e){at=!0,an=e}};function ao(e,t,n,r,l,a,o,i,u){at=!1,an=null,ae.apply(aa,arguments)}var ai=!1,au=!1,as="function"==typeof WeakSet?WeakSet:Set,ac=null;function af(e,t){try{var n=e.ref;if(null!==n){var r=e.stateNode;switch(e.tag){case 26:case 27:case 5:var l=r;break;default:l=r}"function"==typeof n?e.refCleanup=n(l):n.current=l}}catch(n){o$(e,t,n)}}function ad(e,t){var n=e.ref,r=e.refCleanup;if(null!==n){if("function"==typeof r)try{r()}catch(n){o$(e,t,n)}finally{e.refCleanup=null,null!=(e=e.alternate)&&(e.refCleanup=null)}else if("function"==typeof n)try{n(null)}catch(n){o$(e,t,n)}else n.current=null}}function ap(e,t,n){try{n()}catch(n){o$(e,t,n)}}var ah=!1;function am(e,t,n){var r=t.updateQueue;if(null!==(r=null!==r?r.lastEffect:null)){var l=r=r.next;do{if((l.tag&e)===e){var a=l.inst,o=a.destroy;void 0!==o&&(a.destroy=void 0,ap(t,n,o))}l=l.next}while(l!==r)}}function ag(e,t){if(null!==(t=null!==(t=t.updateQueue)?t.lastEffect:null)){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create,l=n.inst;r=r(),l.destroy=r}n=n.next}while(n!==t)}}function ay(e,t){try{ag(t,e)}catch(t){o$(e,e.return,t)}}function av(e){var t=e.updateQueue;if(null!==t){var n=e.stateNode;try{nd(t,n)}catch(t){o$(e,e.return,t)}}}function ab(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":n.autoFocus&&r.focus();break e;case"img":n.src&&(r.src=n.src)}}catch(t){o$(e,e.return,t)}}function ak(e,t,n){var r=n.flags;switch(n.tag){case 0:case 11:case 15:aD(e,n),4&r&&ay(n,5);break;case 1:if(aD(e,n),4&r){if(e=n.stateNode,null===t)try{e.componentDidMount()}catch(e){o$(n,n.return,e)}else{var l=n.elementType===n.type?t.memoizedProps:r3(n.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(l,t,e.__reactInternalSnapshotBeforeUpdate)}catch(e){o$(n,n.return,e)}}}64&r&&av(n),512&r&&af(n,n.return);break;case 3:if(aD(e,n),64&r&&null!==(r=n.updateQueue)){if(e=null,null!==n.child)switch(n.child.tag){case 27:case 5:case 1:e=n.child.stateNode}try{nd(r,e)}catch(e){o$(n,n.return,e)}}break;case 26:aD(e,n),512&r&&af(n,n.return);break;case 27:case 5:aD(e,n),null===t&&4&r&&ab(n),512&r&&af(n,n.return);break;case 12:default:aD(e,n);break;case 13:aD(e,n),4&r&&aN(e,n);break;case 22:if(0!=(1&n.mode)){if(!(l=null!==n.memoizedState||ai)){t=null!==t&&null!==t.memoizedState||au;var a=ai,o=au;ai=l,(au=t)&&!o?function e(t,n,r){for(r=r&&0!=(8772&n.subtreeFlags),n=n.child;null!==n;){var l=n.alternate,a=t,o=n,i=o.flags;switch(o.tag){case 0:case 11:case 15:e(a,o,r),ay(o,4);break;case 1:if(e(a,o,r),"function"==typeof(a=o.stateNode).componentDidMount)try{a.componentDidMount()}catch(e){o$(o,o.return,e)}if(null!==(l=o.updateQueue)){var u=l.shared.hiddenCallbacks;if(null!==u)for(l.shared.hiddenCallbacks=null,l=0;l<u.length;l++)nf(u[l],a)}r&&64&i&&av(o),af(o,o.return);break;case 26:case 27:case 5:e(a,o,r),r&&null===l&&4&i&&ab(o),af(o,o.return);break;case 12:default:e(a,o,r);break;case 13:e(a,o,r),r&&4&i&&aN(a,o);break;case 22:null===o.memoizedState&&e(a,o,r),af(o,o.return)}n=n.sibling}}(e,n,0!=(8772&n.subtreeFlags)):aD(e,n),ai=a,au=o}}else aD(e,n);512&r&&("manual"===n.memoizedProps.mode?af(n,n.return):ad(n,n.return))}}function aw(e){return 5===e.tag||3===e.tag||26===e.tag||27===e.tag||4===e.tag}function aS(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||aw(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&27!==e.tag&&18!==e.tag;){if(2&e.flags||null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function aE(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(4!==r&&27!==r&&null!==(e=e.child))for(aE(e,t,n),e=e.sibling;null!==e;)aE(e,t,n),e=e.sibling}var ax=null,aC=!1;function az(e,t,n){for(n=n.child;null!==n;)aP(e,t,n),n=n.sibling}function aP(e,t,n){if(ee&&"function"==typeof ee.onCommitFiberUnmount)try{ee.onCommitFiberUnmount(J,n)}catch(e){}switch(n.tag){case 26:au||ad(n,t),az(e,t,n),n.memoizedState?n.memoizedState.count--:n.stateNode&&(n=n.stateNode).parentNode.removeChild(n);break;case 27:au||ad(n,t);var r=ax,l=aC;for(ax=n.stateNode,az(e,t,n),e=(n=n.stateNode).attributes;e.length;)n.removeAttributeNode(e[0]);ez(n),ax=r,aC=l;break;case 5:au||ad(n,t);case 6:r=ax,l=aC,ax=null,az(e,t,n),ax=r,aC=l,null!==ax&&(aC?(e=ax,n=n.stateNode,8===e.nodeType?e.parentNode.removeChild(n):e.removeChild(n)):ax.removeChild(n.stateNode));break;case 18:null!==ax&&(aC?(e=ax,n=n.stateNode,8===e.nodeType?sP(e.parentNode,n):1===e.nodeType&&sP(e,n),i4(e)):sP(ax,n.stateNode));break;case 4:r=ax,l=aC,ax=n.stateNode.containerInfo,aC=!0,az(e,t,n),ax=r,aC=l;break;case 0:case 11:case 14:case 15:if(!au&&null!==(r=n.updateQueue)&&null!==(r=r.lastEffect)){l=r=r.next;do{var a=l.tag,o=l.inst,i=o.destroy;void 0!==i&&(0!=(2&a)?(o.destroy=void 0,ap(n,t,i)):0!=(4&a)&&(o.destroy=void 0,ap(n,t,i))),l=l.next}while(l!==r)}az(e,t,n);break;case 1:if(!au&&(ad(n,t),"function"==typeof(r=n.stateNode).componentWillUnmount))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(e){o$(n,t,e)}az(e,t,n);break;case 21:default:az(e,t,n);break;case 22:ad(n,t),1&n.mode?(au=(r=au)||null!==n.memoizedState,az(e,t,n),au=r):az(e,t,n)}}function aN(e,t){if(null===t.memoizedState&&null!==(e=t.alternate)&&null!==(e=e.memoizedState)&&null!==(e=e.dehydrated))try{i4(e)}catch(e){o$(t,t.return,e)}}function a_(e,t){var n=function(e){switch(e.tag){case 13:case 19:var t=e.stateNode;return null===t&&(t=e.stateNode=new as),t;case 22:return null===(t=(e=e.stateNode)._retryCache)&&(t=e._retryCache=new as),t;default:throw Error(i(435,e.tag))}}(e);t.forEach(function(t){var r=oK.bind(null,e,t);n.has(t)||(n.add(t),t.then(r,r))})}function aL(e,t){var n=t.deletions;if(null!==n)for(var r=0;r<n.length;r++){var l=n[r];try{var a=t,o=a;e:for(;null!==o;){switch(o.tag){case 27:case 5:ax=o.stateNode,aC=!1;break e;case 3:case 4:ax=o.stateNode.containerInfo,aC=!0;break e}o=o.return}if(null===ax)throw Error(i(160));aP(e,a,l),ax=null,aC=!1;var u=l.alternate;null!==u&&(u.return=null),l.return=null}catch(e){o$(l,t,e)}}if(12854&t.subtreeFlags)for(t=t.child;null!==t;)aM(t,e),t=t.sibling}var aT=null;function aM(e,t){var n=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(aL(t,e),aF(e),4&r){try{am(3,e,e.return),ag(3,e)}catch(t){o$(e,e.return,t)}try{am(5,e,e.return)}catch(t){o$(e,e.return,t)}}break;case 1:aL(t,e),aF(e),512&r&&null!==n&&ad(n,n.return),64&r&&ai&&null!==(e=e.updateQueue)&&null!==(n=e.callbacks)&&(r=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=null===r?n:r.concat(n));break;case 26:var l=aT;if(aL(t,e),aF(e),512&r&&null!==n&&ad(n,n.return),4&r){if(t=null!==n?n.memoizedState:null,r=e.memoizedState,null===n){if(null===r){if(null===e.stateNode){e:{n=e.type,r=e.memoizedProps,t=l.ownerDocument||l;t:switch(n){case"title":(!(l=t.getElementsByTagName("title")[0])||l[eC]||l[ev]||"http://www.w3.org/2000/svg"===l.namespaceURI||l.hasAttribute("itemprop"))&&(l=t.createElement(n),t.head.insertBefore(l,t.querySelector("head > title"))),sh(l,n,r),l[ev]=e,eM(l),n=l;break e;case"link":var a=sq("link","href",t).get(n+(r.href||""));if(a){for(var o=0;o<a.length;o++)if((l=a[o]).getAttribute("href")===(null==r.href?null:r.href)&&l.getAttribute("rel")===(null==r.rel?null:r.rel)&&l.getAttribute("title")===(null==r.title?null:r.title)&&l.getAttribute("crossorigin")===(null==r.crossOrigin?null:r.crossOrigin)){a.splice(o,1);break t}}sh(l=t.createElement(n),n,r),t.head.appendChild(l);break;case"meta":if(a=sq("meta","content",t).get(n+(r.content||""))){for(o=0;o<a.length;o++)if((l=a[o]).getAttribute("content")===(null==r.content?null:""+r.content)&&l.getAttribute("name")===(null==r.name?null:r.name)&&l.getAttribute("property")===(null==r.property?null:r.property)&&l.getAttribute("http-equiv")===(null==r.httpEquiv?null:r.httpEquiv)&&l.getAttribute("charset")===(null==r.charSet?null:r.charSet)){a.splice(o,1);break t}}sh(l=t.createElement(n),n,r),t.head.appendChild(l);break;default:throw Error(i(468,n))}l[ev]=e,eM(l),n=l}e.stateNode=n}else sK(l,e.type,e.stateNode)}else e.stateNode=sQ(l,r,e.memoizedProps)}else if(t!==r)null===t?null!==n.stateNode&&(n=n.stateNode).parentNode.removeChild(n):t.count--,null===r?sK(l,e.type,e.stateNode):sQ(l,r,e.memoizedProps);else if(null===r&&null!==e.stateNode&&(r=e.updateQueue,e.updateQueue=null,null!==r))try{var u=e.stateNode,s=e.memoizedProps;sm(u,r,e.type,n.memoizedProps,s),u[eb]=s}catch(t){o$(e,e.return,t)}}break;case 27:if(4&r&&null===e.alternate){for(l=e.stateNode,a=e.memoizedProps,o=l.firstChild;o;){var c=o.nextSibling,f=o.nodeName;o[eC]||"HEAD"===f||"BODY"===f||"STYLE"===f||"LINK"===f&&"stylesheet"===o.rel.toLowerCase()||l.removeChild(o),o=c}for(o=e.type,c=l.attributes;c.length;)l.removeAttributeNode(c[0]);sh(l,o,a),l[ev]=e,l[eb]=a}case 5:if(aL(t,e),aF(e),512&r&&null!==n&&ad(n,n.return),32&e.flags){t=e.stateNode;try{te(t,"")}catch(t){o$(e,e.return,t)}}if(4&r&&null!=(r=e.stateNode)&&(t=e.memoizedProps,n=null!==n?n.memoizedProps:t,l=e.type,a=e.updateQueue,e.updateQueue=null,null!==a))try{sm(r,a,l,n,t),r[eb]=t}catch(t){o$(e,e.return,t)}break;case 6:if(aL(t,e),aF(e),4&r){if(null===e.stateNode)throw Error(i(162));n=e.stateNode,r=e.memoizedProps;try{n.nodeValue=r}catch(t){o$(e,e.return,t)}}break;case 3:if(sH=null,l=aT,aT=sR(t.containerInfo),aL(t,e),aT=l,aF(e),4&r&&null!==n&&n.memoizedState.isDehydrated)try{i4(t.containerInfo)}catch(t){o$(e,e.return,t)}break;case 4:n=aT,aT=sR(e.stateNode.containerInfo),aL(t,e),aF(e),aT=n;break;case 13:aL(t,e),aF(e),8192&(n=e.child).flags&&null!==n.memoizedState&&(null===n.alternate||null===n.alternate.memoizedState)&&(oa=H()),4&r&&null!==(n=e.updateQueue)&&(e.updateQueue=null,a_(e,n));break;case 22:if(512&r&&null!==n&&ad(n,n.return),u=null!==e.memoizedState,s=null!==n&&null!==n.memoizedState,1&e.mode){var d=ai,p=au;ai=d||u,au=p||s,aL(t,e),au=p,ai=d}else aL(t,e);if(aF(e),(t=e.stateNode)._current=e,t._visibility&=-3,t._visibility|=2&t._pendingVisibility,8192&r&&(t._visibility=u?-2&t._visibility:1|t._visibility,u&&(t=ai||au,null===n||s||t||0!=(1&e.mode)&&function e(t){for(t=t.child;null!==t;){var n=t;switch(n.tag){case 0:case 11:case 14:case 15:am(4,n,n.return),e(n);break;case 1:ad(n,n.return);var r=n.stateNode;if("function"==typeof r.componentWillUnmount){var l=n.return;try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(e){o$(n,l,e)}}e(n);break;case 26:case 27:case 5:ad(n,n.return),e(n);break;case 22:ad(n,n.return),null===n.memoizedState&&e(n);break;default:e(n)}t=t.sibling}}(e)),null===e.memoizedProps||"manual"!==e.memoizedProps.mode))e:for(n=null,t=e;;){if(5===t.tag||26===t.tag||27===t.tag){if(null===n){n=t;try{l=t.stateNode,u?(a=l.style,"function"==typeof a.setProperty?a.setProperty("display","none","important"):a.display="none"):(o=t.stateNode,f=null!=(c=t.memoizedProps.style)&&c.hasOwnProperty("display")?c.display:null,o.style.display=null==f||"boolean"==typeof f?"":(""+f).trim())}catch(t){o$(e,e.return,t)}}}else if(6===t.tag){if(null===n)try{t.stateNode.nodeValue=u?"":t.memoizedProps}catch(t){o$(e,e.return,t)}}else if((22!==t.tag&&23!==t.tag||null===t.memoizedState||t===e)&&null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break e;for(;null===t.sibling;){if(null===t.return||t.return===e)break e;n===t&&(n=null),t=t.return}n===t&&(n=null),t.sibling.return=t.return,t=t.sibling}4&r&&null!==(n=e.updateQueue)&&null!==(r=n.retryQueue)&&(n.retryQueue=null,a_(e,r));break;case 19:aL(t,e),aF(e),4&r&&null!==(n=e.updateQueue)&&(e.updateQueue=null,a_(e,n));break;case 21:break;default:aL(t,e),aF(e)}}function aF(e){var t=e.flags;if(2&t){try{if(27!==e.tag){t:{for(var n=e.return;null!==n;){if(aw(n)){var r=n;break t}n=n.return}throw Error(i(160))}switch(r.tag){case 27:var l=r.stateNode,a=aS(e);aE(e,a,l);break;case 5:var o=r.stateNode;32&r.flags&&(te(o,""),r.flags&=-33);var u=aS(e);aE(e,u,o);break;case 3:case 4:var s=r.stateNode.containerInfo,c=aS(e);!function e(t,n,r){var l=t.tag;if(5===l||6===l)t=t.stateNode,n?8===r.nodeType?r.parentNode.insertBefore(t,n):r.insertBefore(t,n):(8===r.nodeType?(n=r.parentNode).insertBefore(t,r):(n=r).appendChild(t),null!=(r=r._reactRootContainer)||null!==n.onclick||(n.onclick=sf));else if(4!==l&&27!==l&&null!==(t=t.child))for(e(t,n,r),t=t.sibling;null!==t;)e(t,n,r),t=t.sibling}(e,c,s);break;default:throw Error(i(161))}}}catch(t){o$(e,e.return,t)}e.flags&=-3}4096&t&&(e.flags&=-4097)}function aD(e,t){if(8772&t.subtreeFlags)for(t=t.child;null!==t;)ak(e,t.alternate,t),t=t.sibling}function aR(e,t){try{ag(t,e)}catch(t){o$(e,e.return,t)}}function aO(e,t){var n=null;null!==e&&null!==e.memoizedState&&null!==e.memoizedState.cachePool&&(n=e.memoizedState.cachePool.pool),e=null,null!==t.memoizedState&&null!==t.memoizedState.cachePool&&(e=t.memoizedState.cachePool.pool),e!==n&&(null!=e&&e.refCount++,null!=n&&lX(n))}function aA(e,t){e=null,null!==t.alternate&&(e=t.alternate.memoizedState.cache),(t=t.memoizedState.cache)!==e&&(t.refCount++,null!=e&&lX(e))}function aI(e,t,n,r){if(10256&t.subtreeFlags)for(t=t.child;null!==t;)aU(e,t,n,r),t=t.sibling}function aU(e,t,n,r){var l=t.flags;switch(t.tag){case 0:case 11:case 15:aI(e,t,n,r),2048&l&&aR(t,9);break;case 3:aI(e,t,n,r),2048&l&&(e=null,null!==t.alternate&&(e=t.alternate.memoizedState.cache),(t=t.memoizedState.cache)!==e&&(t.refCount++,null!=e&&lX(e)));break;case 23:break;case 22:var a=t.stateNode;null!==t.memoizedState?4&a._visibility?aI(e,t,n,r):1&t.mode?aB(e,t):(a._visibility|=4,aI(e,t,n,r)):4&a._visibility?aI(e,t,n,r):(a._visibility|=4,function e(t,n,r,l,a){for(a=a&&0!=(10256&n.subtreeFlags),n=n.child;null!==n;){var o=n,i=o.flags;switch(o.tag){case 0:case 11:case 15:e(t,o,r,l,a),aR(o,8);break;case 23:break;case 22:var u=o.stateNode;null!==o.memoizedState?4&u._visibility?e(t,o,r,l,a):1&o.mode?aB(t,o):(u._visibility|=4,e(t,o,r,l,a)):(u._visibility|=4,e(t,o,r,l,a)),a&&2048&i&&aO(o.alternate,o);break;case 24:e(t,o,r,l,a),a&&2048&i&&aA(o.alternate,o);break;default:e(t,o,r,l,a)}n=n.sibling}}(e,t,n,r,0!=(10256&t.subtreeFlags))),2048&l&&aO(t.alternate,t);break;case 24:aI(e,t,n,r),2048&l&&aA(t.alternate,t);break;default:aI(e,t,n,r)}}function aB(e,t){if(10256&t.subtreeFlags)for(t=t.child;null!==t;){var n=t,r=n.flags;switch(n.tag){case 22:aB(e,n),2048&r&&aO(n.alternate,n);break;case 24:aB(e,n),2048&r&&aA(n.alternate,n);break;default:aB(e,n)}t=t.sibling}}var aV=8192;function aQ(e){if(e.subtreeFlags&aV)for(e=e.child;null!==e;)a$(e),e=e.sibling}function a$(e){switch(e.tag){case 26:aQ(e),e.flags&aV&&null!==e.memoizedState&&function(e,t,n){if(null===sY)throw Error(i(475));var r=sY;if("stylesheet"===t.type&&("string"!=typeof n.media||!1!==matchMedia(n.media).matches)){if(null===t.instance){var l=sI(n.href),a=e.querySelector(sU(l));if(a){null!==(e=a._p)&&"object"==typeof e&&"function"==typeof e.then&&(r.count++,r=sG.bind(r),e.then(r,r)),t.state.loading|=4,t.instance=a,eM(a);return}a=e.ownerDocument||e,n=sB(n),(l=sF.get(l))&&sW(n,l),eM(a=a.createElement("link"));var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),sh(a,"link",n),t.instance=a}null===r.stylesheets&&(r.stylesheets=new Map),r.stylesheets.set(t,e),(e=t.state.preload)&&0==(3&t.state.loading)&&(r.count++,t=sG.bind(r),e.addEventListener("load",t),e.addEventListener("error",t))}}(aT,e.memoizedState,e.memoizedProps);break;case 5:default:aQ(e);break;case 3:case 4:var t=aT;aT=sR(e.stateNode.containerInfo),aQ(e),aT=t;break;case 22:null===e.memoizedState&&(null!==(t=e.alternate)&&null!==t.memoizedState?(t=aV,aV=16777216,aQ(e),aV=t):aQ(e))}}function aW(e){var t=e.alternate;if(null!==t&&null!==(e=t.child)){t.child=null;do t=e.sibling,e.sibling=null,e=t;while(null!==e)}}function aj(e){var t=e.deletions;if(0!=(16&e.flags)){if(null!==t)for(var n=0;n<t.length;n++){var r=t[n];ac=r,aq(r,e)}aW(e)}if(10256&e.subtreeFlags)for(e=e.child;null!==e;)aH(e),e=e.sibling}function aH(e){switch(e.tag){case 0:case 11:case 15:aj(e),2048&e.flags&&am(9,e,e.return);break;case 22:var t=e.stateNode;null!==e.memoizedState&&4&t._visibility&&(null===e.return||13!==e.return.tag)?(t._visibility&=-5,function e(t){var n=t.deletions;if(0!=(16&t.flags)){if(null!==n)for(var r=0;r<n.length;r++){var l=n[r];ac=l,aq(l,t)}aW(t)}for(t=t.child;null!==t;){switch((n=t).tag){case 0:case 11:case 15:am(8,n,n.return),e(n);break;case 22:4&(r=n.stateNode)._visibility&&(r._visibility&=-5,e(n));break;default:e(n)}t=t.sibling}}(e)):aj(e);break;default:aj(e)}}function aq(e,t){for(;null!==ac;){var n=ac;switch(n.tag){case 0:case 11:case 15:am(8,n,t);break;case 23:case 22:if(null!==n.memoizedState&&null!==n.memoizedState.cachePool){var r=n.memoizedState.cachePool.pool;null!=r&&r.refCount++}break;case 24:lX(n.memoizedState.cache)}if(null!==(r=n.child))r.return=n,ac=r;else e:for(n=e;null!==ac;){var l=(r=ac).sibling,a=r.return;if(!function e(t){var n=t.alternate;null!==n&&(t.alternate=null,e(n)),t.child=null,t.deletions=null,t.sibling=null,5===t.tag&&null!==(n=t.stateNode)&&ez(n),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}(r),r===n){ac=null;break e}if(null!==l){l.return=a,ac=l;break e}ac=a}}}var aK={getCacheSignal:function(){return lQ(lK).controller.signal},getCacheForType:function(e){var t=lQ(lK),n=t.data.get(e);return void 0===n&&(n=e(),t.data.set(e,n)),n}},aY="function"==typeof WeakMap?WeakMap:Map,aX=s.ReactCurrentDispatcher,aG=s.ReactCurrentCache,aZ=s.ReactCurrentOwner,aJ=s.ReactCurrentBatchConfig,a0=0,a1=null,a2=null,a3=0,a4=0,a8=null,a6=!1,a5=0,a7=0,a9=null,oe=0,ot=0,on=0,or=null,ol=null,oa=0,oo=1/0,oi=null,ou=!1,os=null,oc=null,of=!1,od=null,op=0,oh=0,om=null,og=0,oy=null;function ov(e){return 0==(1&e.mode)?2:0!=(2&a0)&&0!==a3?a3&-a3:null!==lG.transition?(0==(e=0)&&(0===nG&&(nG=es()),e=nG),e):0!==(e=eh)?e:e=void 0===(e=window.event)?32:un(e.type)}function ob(e,t,n){(e===a1&&2===a4||null!==e.cancelPendingCommit)&&(oN(e,0),ox(e,a3)),ed(e,n),(0==(2&a0)||e!==a1)&&(e===a1&&(0==(2&a0)&&(ot|=n),4===a7&&ox(e,a3)),nZ(e),2===n&&0===a0&&0==(1&t.mode)&&(oo=H()+500,nJ(!0)))}function ok(e,t){if(0!=(6&a0))throw Error(i(327));var n=e.callbackNode;if(oV()&&e.callbackNode!==n)return null;var r=ei(e,e===a1?a3:0);if(0===r)return null;if(0!==(t=0!=(60&r)||0!=(r&e.expiredLanes)||t?oD(e,r):function(e,t){var n=a0;a0|=2;var r=oT(),l=oM();(a1!==e||a3!==t)&&(oi=null,oo=H()+500,oN(e,t));e:for(;;)try{if(0!==a4&&null!==a2){t=a2;var a=a8;t:switch(a4){case 1:case 6:a4=0,a8=null,oA(t,a);break;case 2:if(ny(a)){a4=0,a8=null,oO(t);break}t=function(){2===a4&&a1===e&&(a4=7),nZ(e)},a.then(t,t);break e;case 3:a4=7;break e;case 4:a4=5;break e;case 7:ny(a)?(a4=0,a8=null,oO(t)):(a4=0,a8=null,oA(t,a));break;case 5:switch(a2.tag){case 5:case 26:case 27:t=a2,a4=0,a8=null;var o=t.sibling;if(null!==o)a2=o;else{var u=t.return;null!==u?(a2=u,oI(u)):a2=null}break t}a4=0,a8=null,oA(t,a);break;case 8:oP(),a7=6;break e;default:throw Error(i(462))}}!function(){for(;null!==a2&&!W();)oR(a2)}();break}catch(t){o_(e,t)}return(lO(),aX.current=r,aG.current=l,a0=n,null!==a2)?0:(a1=null,a3=0,t7(),a7)}(e,r))){if(2===t){var l=r,a=eu(e,l);0!==a&&(r=a,t=ow(e,l,a))}if(1===t)throw n=a9,oN(e,0),ox(e,r),nZ(e),n;if(6===t)ox(e,r);else{if(l=e.current.alternate,0==(60&r)&&!function(e){for(var t=e;;){if(16384&t.flags){var n=t.updateQueue;if(null!==n&&null!==(n=n.stores))for(var r=0;r<n.length;r++){var l=n[r],a=l.getSnapshot;l=l.value;try{if(!tP(a(),l))return!1}catch(e){return!1}}}if(n=t.child,16384&t.subtreeFlags&&null!==n)n.return=t,t=n;else{if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}(l)){if(2===(t=oD(e,r))){a=r;var o=eu(e,a);0!==o&&(r=o,t=ow(e,a,o))}if(1===t)throw n=a9,oN(e,0),ox(e,r),nZ(e),n}e.finishedWork=l,e.finishedLanes=r;e:{switch(t){case 0:case 1:throw Error(i(345));case 4:if((8388480&r)===r){ox(e,r);break e}break;case 2:case 3:case 5:break;default:throw Error(i(329))}if((125829120&r)===r&&10<(t=oa+500-H())){if(ox(e,r),0!==ei(e,0))break e;e.timeoutHandle=sS(oE.bind(null,e,l,ol,oi,r),t);break e}oE(e,l,ol,oi,r)}}}return nZ(e),n2(e,H()),e=e.callbackNode===n?ok.bind(null,e):null}function ow(e,t,n){var r=or,l=e.current.memoizedState.isDehydrated;if(l&&(oN(e,n).flags|=256),2!==(n=oD(e,n))){if(a6&&!l)return e.errorRecoveryDisabledLanes|=t,ot|=t,4;e=ol,ol=r,null!==e&&oS(e)}return n}function oS(e){null===ol?ol=e:ol.push.apply(ol,e)}function oE(e,t,n,r,l){if(0==(42&l)&&(sY={stylesheets:null,count:0,unsuspend:sX},a$(t),null!==(t=function(){if(null===sY)throw Error(i(475));var e=sY;return e.stylesheets&&0===e.count&&sJ(e,e.stylesheets),0<e.count?function(t){var n=setTimeout(function(){if(e.stylesheets&&sJ(e,e.stylesheets),e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}},6e4);return e.unsuspend=t,function(){e.unsuspend=null,clearTimeout(n)}}:null}()))){e.cancelPendingCommit=t(oU.bind(null,e,n,r)),ox(e,l);return}oU(e,n,r)}function ox(e,t){for(t&=~on,t&=~ot,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var n=31-et(t),r=1<<n;e[n]=-1,t&=~r}}function oC(e,t){var n=a0;a0|=1;try{return e(t)}finally{0===(a0=n)&&(oo=H()+500,nJ(!0))}}function oz(e){null!==od&&0===od.tag&&0==(6&a0)&&oV();var t=a0;a0|=1;var n=aJ.transition,r=eh;try{if(aJ.transition=null,eh=2,e)return e()}finally{eh=r,aJ.transition=n,0==(6&(a0=t))&&nJ(!1)}}function oP(){if(null!==a2){if(0===a4)var e=a2.return;else e=a2,lO(),rh(e),nS=null,nE=0,e=a2;for(;null!==e;)l9(e.alternate,e),e=e.return;a2=null}}function oN(e,t){e.finishedWork=null,e.finishedLanes=0;var n=e.timeoutHandle;return -1!==n&&(e.timeoutHandle=-1,sE(n)),null!==(n=e.cancelPendingCommit)&&(e.cancelPendingCommit=null,n()),oP(),a1=e,a2=e=oZ(e.current,null),a3=a5=t,a4=0,a8=null,a6=!1,a7=0,a9=null,on=ot=oe=0,ol=or=null,t7(),e}function o_(e,t){n5=null,n4.current=rJ,aZ.current=null,t===nh?(t=nw(),a4=oL()&&0==(268435455&oe)&&0==(268435455&ot)?2:3):t===nm?(t=nw(),a4=4):a4=t===li?8:null!==t&&"object"==typeof t&&"function"==typeof t.then?6:1,a8=t,null===a2&&(a7=1,a9=t)}function oL(){if((8388480&a3)===a3)return null===nA;var e=nO.current;return null!==e&&((125829120&a3)===a3||0!=(1073741824&a3))&&e===nA}function oT(){var e=aX.current;return aX.current=rJ,null===e?rJ:e}function oM(){var e=aG.current;return aG.current=aK,e}function oF(){a7=4,null===a1||0==(268435455&oe)&&0==(268435455&ot)||ox(a1,a3)}function oD(e,t){var n=a0;a0|=2;var r=oT(),l=oM();(a1!==e||a3!==t)&&(oi=null,oN(e,t));e:for(;;)try{if(0!==a4&&null!==a2){t=a2;var a=a8;if(8===a4){oP(),a7=6;break e}a4=0,a8=null,oA(t,a)}!function(){for(;null!==a2;)oR(a2)}();break}catch(t){o_(e,t)}if(lO(),a0=n,aX.current=r,aG.current=l,null!==a2)throw Error(i(261));return a1=null,a3=0,t7(),a7}function oR(e){var t=iv(e.alternate,e,a5);e.memoizedProps=e.pendingProps,null===t?oI(e):a2=t,aZ.current=null}function oO(e){var t=e.alternate;switch(e.tag){case 2:e.tag=0;case 15:case 0:var n=e.type,r=e.pendingProps;r=e.elementType===n?r:r3(n,r);var l=tw(n)?tb:ty.current;l=tk(e,l),t=ly(t,e,r,n,l,a3);break;case 11:n=e.type.render,r=e.pendingProps,r=e.elementType===n?r:r3(n,r),t=ly(t,e,r,n,e.ref,a3);break;case 5:rh(e);default:l9(t,e),e=a2=oJ(e,a5),t=iv(t,e,a5)}e.memoizedProps=e.pendingProps,null===t?oI(e):a2=t,aZ.current=null}function oA(e,t){lO(),rh(e),nS=null,nE=0;var n=e.return;if(null===n||null===a1)a7=1,a9=t,a2=null;else{try{e:{var r=a1,l=t;if(t=a3,e.flags|=32768,null!==l&&"object"==typeof l&&"function"==typeof l.then){var a=l,o=e.tag;if(0==(1&e.mode)&&(0===o||11===o||15===o)){var u=e.alternate;u?(e.updateQueue=u.updateQueue,e.memoizedState=u.memoizedState,e.lanes=u.lanes):(e.updateQueue=null,e.memoizedState=null)}var s=nO.current;if(null!==s){switch(s.tag){case 13:if(1&e.mode&&(null===nA?oF():null===s.alternate&&0===a7&&(a7=3)),s.flags&=-257,la(s,n,e,r,t),a===ng)s.flags|=16384;else{var c=s.updateQueue;null===c?s.updateQueue=new Set([a]):c.add(a)}break;case 22:if(1&s.mode){if(s.flags|=65536,a===ng)s.flags|=16384;else{var f=s.updateQueue;if(null===f){var d={transitions:null,markerInstances:null,retryQueue:new Set([a])};s.updateQueue=d}else{var h=f.retryQueue;null===h?f.retryQueue=new Set([a]):h.add(a)}}break}default:throw Error(i(435,s.tag))}1&s.mode&&oW(r,a,t);break e}if(1===r.tag){oW(r,a,t),oF();break e}l=Error(i(426))}else if(t$&&1&e.mode&&(a=nO.current,null!==a)){0==(65536&a.flags)&&(a.flags|=256),la(a,n,e,r,t),t4(le(l,e));break e}r=l=le(l,e),4!==a7&&(a7=2),null===or?or=[r]:or.push(r),r=n;do{switch(r.tag){case 3:var m=l;r.flags|=65536,t&=-t,r.lanes|=t;var g=lr(r,m,t);ns(r,g);break e;case 1:o=l;var y=r.type,v=r.stateNode;if(0==(128&r.flags)&&("function"==typeof y.getDerivedStateFromError||null!==v&&"function"==typeof v.componentDidCatch&&(null===oc||!oc.has(v)))){r.flags|=65536,g=t&-t,r.lanes|=g,m=ll(r,o,g),ns(r,m);break e}}r=r.return}while(null!==r)}}catch(e){throw a2=n,e}if(32768&e.flags)e:{do{if(null!==(n=function(e,t){switch(tB(t),t.tag){case 1:return tw(t.type)&&tS(),65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 3:return lI(lK),U(),p(tv),p(ty),nj(),0!=(65536&(e=t.flags))&&0==(128&e)?(t.flags=-65537&e|128,t):null;case 26:case 27:case 5:return V(t),null;case 13:if(nV(t),null!==(e=t.memoizedState)&&null!==e.dehydrated){if(null===t.alternate)throw Error(i(340));t3()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 19:return p(nQ),null;case 4:return U(),null;case 10:return lI(t.type._context),null;case 22:case 23:return nV(t),nR(),null!==e&&p(lZ),65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 24:return lI(lK),null;default:return null}}(e.alternate,e))){n.flags&=32767,a2=n;break e}null!==(e=e.return)&&(e.flags|=32768,e.subtreeFlags=0,e.deletions=null),a2=e}while(null!==e);a7=6,a2=null}else oI(e)}}function oI(e){var t=e;do{e=t.return;var n=function(e,t,n){var r=t.pendingProps;switch(tB(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return l7(t),null;case 1:case 17:return tw(t.type)&&tS(),l7(t),null;case 3:return r=t.stateNode,n=null,null!==e&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),lI(lK),U(),p(tv),p(ty),nj(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(null===e||null===e.child)&&(t1(t)?l2(t):null===e||e.memoizedState.isDehydrated&&0==(256&t.flags)||(t.flags|=1024,null!==tW&&(oS(tW),tW=null))),l7(t),null;case 26:n=t.type;var l=t.memoizedState;if(null===e)l2(t),null!==t.ref&&l3(t),null!==l?(l7(t),l8(t,l)):(l7(t),t.flags&=-16777217);else{var a=e.memoizedState;l!==a&&l2(t),e.ref!==t.ref&&l3(t),null!==l?(l7(t),l===a?t.flags&=-16777217:l8(t,l)):(l4(e,t,n,r),l7(t),t.flags&=-16777217)}return null;case 27:if(V(t),n=A.current,l=t.type,null!==e&&null!=t.stateNode)l4(e,t,l,r),e.ref!==t.ref&&l3(t);else{if(!r){if(null===t.stateNode)throw Error(i(166));return l7(t),null}e=R.current,t1(t)?tJ(t,e):(e=sM(l,r,n),t.stateNode=e,l2(t)),null!==t.ref&&l3(t)}return l7(t),null;case 5:if(V(t),n=t.type,null!==e&&null!=t.stateNode)l4(e,t,n,r),e.ref!==t.ref&&l3(t);else{if(!r){if(null===t.stateNode)throw Error(i(166));return l7(t),null}if(e=R.current,t1(t))tJ(t,e)&&l2(t);else{switch(l=sv(A.current),e){case 1:e=l.createElementNS("http://www.w3.org/2000/svg",n);break;case 2:e=l.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;default:switch(n){case"svg":e=l.createElementNS("http://www.w3.org/2000/svg",n);break;case"math":e=l.createElementNS("http://www.w3.org/1998/Math/MathML",n);break;case"script":(e=l.createElement("div")).innerHTML="<script></script>",e=e.removeChild(e.firstChild);break;case"select":e="string"==typeof r.is?l.createElement("select",{is:r.is}):l.createElement("select"),r.multiple?e.multiple=!0:r.size&&(e.size=r.size);break;default:e="string"==typeof r.is?l.createElement(n,{is:r.is}):l.createElement(n)}}e[ev]=t,e[eb]=r;e:for(l=t.child;null!==l;){if(5===l.tag||6===l.tag)e.appendChild(l.stateNode);else if(4!==l.tag&&27!==l.tag&&null!==l.child){l.child.return=l,l=l.child;continue}if(l===t)break e;for(;null===l.sibling;){if(null===l.return||l.return===t)break e;l=l.return}l.sibling.return=l.return,l=l.sibling}t.stateNode=e;e:switch(sh(e,n,r),n){case"button":case"input":case"select":case"textarea":e=!!r.autoFocus;break e;case"img":e=!0;break e;default:e=!1}e&&l2(t)}null!==t.ref&&l3(t)}return l7(t),t.flags&=-16777217,null;case 6:if(e&&null!=t.stateNode)e.memoizedProps!==r&&l2(t);else{if("string"!=typeof r&&null===t.stateNode)throw Error(i(166));if(e=A.current,t1(t)){e:{if(e=t.stateNode,r=t.memoizedProps,e[ev]=t,(n=e.nodeValue!==r)&&null!==(l=tV))switch(l.tag){case 3:if(l=0!=(1&l.mode),sc(e.nodeValue,r,l),l){e=!1;break e}break;case 27:case 5:if(a=0!=(1&l.mode),!0!==l.memoizedProps.suppressHydrationWarning&&sc(e.nodeValue,r,a),a){e=!1;break e}}e=n}e&&l2(t)}else(e=sv(e).createTextNode(r))[ev]=t,t.stateNode=e}return l7(t),null;case 13:if(nV(t),r=t.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(t$&&null!==tQ&&0!=(1&t.mode)&&0==(128&t.flags))t2(),t3(),t.flags|=384,l=!1;else if(l=t1(t),null!==r&&null!==r.dehydrated){if(null===e){if(!l)throw Error(i(318));if(!(l=null!==(l=t.memoizedState)?l.dehydrated:null))throw Error(i(317));l[ev]=t}else t3(),0==(128&t.flags)&&(t.memoizedState=null),t.flags|=4;l7(t),l=!1}else null!==tW&&(oS(tW),tW=null),l=!0;if(!l)return 256&t.flags?t:null}if(0!=(128&t.flags))return t.lanes=n,t;return r=null!==r,e=null!==e&&null!==e.memoizedState,r&&(n=t.child,l=null,null!==n.alternate&&null!==n.alternate.memoizedState&&null!==n.alternate.memoizedState.cachePool&&(l=n.alternate.memoizedState.cachePool.pool),a=null,null!==n.memoizedState&&null!==n.memoizedState.cachePool&&(a=n.memoizedState.cachePool.pool),a!==l&&(n.flags|=2048)),r!==e&&r&&(t.child.flags|=8192),l6(t,t.updateQueue),l7(t),null;case 4:return U(),null===e&&se(t.stateNode.containerInfo),l7(t),null;case 10:return lI(t.type._context),l7(t),null;case 19:if(p(nQ),null===(l=t.memoizedState))return l7(t),null;if(r=0!=(128&t.flags),null===(a=l.rendering)){if(r)l5(l,!1);else{if(0!==a7||null!==e&&0!=(128&e.flags))for(e=t.child;null!==e;){if(null!==(a=n$(e))){for(t.flags|=128,l5(l,!1),e=a.updateQueue,t.updateQueue=e,l6(t,e),t.subtreeFlags=0,e=n,r=t.child;null!==r;)oJ(r,e),r=r.sibling;return h(nQ,1&nQ.current|2),t.child}e=e.sibling}null!==l.tail&&H()>oo&&(t.flags|=128,r=!0,l5(l,!1),t.lanes=8388608)}}else{if(!r){if(null!==(e=n$(a))){if(t.flags|=128,r=!0,e=e.updateQueue,t.updateQueue=e,l6(t,e),l5(l,!0),null===l.tail&&"hidden"===l.tailMode&&!a.alternate&&!t$)return l7(t),null}else 2*H()-l.renderingStartTime>oo&&1073741824!==n&&(t.flags|=128,r=!0,l5(l,!1),t.lanes=8388608)}l.isBackwards?(a.sibling=t.child,t.child=a):(null!==(e=l.last)?e.sibling=a:t.child=a,l.last=a)}if(null!==l.tail)return t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=H(),t.sibling=null,e=nQ.current,h(nQ,r?1&e|2:1&e),t;return l7(t),null;case 22:case 23:return nV(t),nR(),r=null!==t.memoizedState,null!==e?null!==e.memoizedState!==r&&(t.flags|=8192):r&&(t.flags|=8192),r&&0!=(1&t.mode)?0!=(1073741824&n)&&0==(128&t.flags)&&(l7(t),6&t.subtreeFlags&&(t.flags|=8192)):l7(t),null!==(r=t.updateQueue)&&l6(t,r.retryQueue),r=null,null!==e&&null!==e.memoizedState&&null!==e.memoizedState.cachePool&&(r=e.memoizedState.cachePool.pool),n=null,null!==t.memoizedState&&null!==t.memoizedState.cachePool&&(n=t.memoizedState.cachePool.pool),n!==r&&(t.flags|=2048),null!==e&&p(lZ),null;case 24:return r=null,null!==e&&(r=e.memoizedState.cache),t.memoizedState.cache!==r&&(t.flags|=2048),lI(lK),l7(t),null;case 25:return null}throw Error(i(156,t.tag))}(t.alternate,t,a5);if(null!==n){a2=n;return}if(null!==(t=t.sibling)){a2=t;return}a2=t=e}while(null!==t);0===a7&&(a7=5)}function oU(e,t,n){var r=eh,l=aJ.transition;try{aJ.transition=null,eh=2,function(e,t,n,r){do oV();while(null!==od);if(0!=(6&a0))throw Error(i(327));var l=e.finishedWork,a=e.finishedLanes;if(null!==l){if(e.finishedWork=null,e.finishedLanes=0,l===e.current)throw Error(i(177));e.callbackNode=null,e.callbackPriority=0,e.cancelPendingCommit=null;var o=l.lanes|l.childLanes;if(function(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,e.errorRecoveryDisabledLanes&=t,t=e.entanglements;var r=e.expirationTimes;for(e=e.hiddenUpdates;0<n;){var l=31-et(n),a=1<<l;t[l]=0,r[l]=-1;var o=e[l];if(null!==o)for(e[l]=null,l=0;l<o.length;l++){var i=o[l];null!==i&&(i.lane&=-1073741825)}n&=~a}}(e,o|=t5),e===a1&&(a2=a1=null,a3=0),0==(10256&l.subtreeFlags)&&0==(10256&l.flags)||of||(of=!0,oh=o,om=n,Q(X,function(){return oV(),null})),n=0!=(15990&l.flags),0!=(15990&l.subtreeFlags)||n){n=aJ.transition,aJ.transition=null;var u=eh;eh=2;var s=a0;a0|=4,aZ.current=null,function(e,t){if(sg=i6,uO(e=uR())){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{var r=(n=(n=e.ownerDocument)&&n.defaultView||window).getSelection&&n.getSelection();if(r&&0!==r.rangeCount){n=r.anchorNode;var l,a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch(e){n=null;break e}var u=0,s=-1,c=-1,f=0,d=0,p=e,h=null;t:for(;;){for(;p!==n||0!==a&&3!==p.nodeType||(s=u+a),p!==o||0!==r&&3!==p.nodeType||(c=u+r),3===p.nodeType&&(u+=p.nodeValue.length),null!==(l=p.firstChild);)h=p,p=l;for(;;){if(p===e)break t;if(h===n&&++f===a&&(s=u),h===o&&++d===r&&(c=u),null!==(l=p.nextSibling))break;h=(p=h).parentNode}p=l}n=-1===s||-1===c?null:{start:s,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(sy={focusedElem:e,selectionRange:n},i6=!1,ac=t;null!==ac;)if(e=(t=ac).child,0!=(1028&t.subtreeFlags)&&null!==e)e.return=t,ac=e;else for(;null!==ac;){t=ac;try{var m=t.alternate,g=t.flags;switch(t.tag){case 0:case 11:case 15:case 5:case 26:case 27:case 6:case 4:case 17:break;case 1:if(0!=(1024&g)&&null!==m){var y=m.memoizedProps,v=m.memoizedState,b=t.stateNode,k=b.getSnapshotBeforeUpdate(t.elementType===t.type?y:r3(t.type,y),v);b.__reactInternalSnapshotBeforeUpdate=k}break;case 3:0!=(1024&g)&&sN(t.stateNode.containerInfo);break;default:if(0!=(1024&g))throw Error(i(163))}}catch(e){o$(t,t.return,e)}if(null!==(e=t.sibling)){e.return=t.return,ac=e;break}ac=t.return}m=ah,ah=!1}(e,l),aM(l,e),function(e){var t=uR(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&function e(t,n){return!!t&&!!n&&(t===n||(!t||3!==t.nodeType)&&(n&&3===n.nodeType?e(t,n.parentNode):"contains"in t?t.contains(n):!!t.compareDocumentPosition&&!!(16&t.compareDocumentPosition(n))))}(n.ownerDocument.documentElement,n)){if(null!==r&&uO(n)){if(t=r.start,void 0===(e=r.end)&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if((e=(t=n.ownerDocument||document)&&t.defaultView||window).getSelection){e=e.getSelection();var l=n.textContent.length,a=Math.min(r.start,l);r=void 0===r.end?a:Math.min(r.end,l),!e.extend&&a>r&&(l=r,r=a,a=l),l=uD(n,a);var o=uD(n,r);l&&o&&(1!==e.rangeCount||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&((t=t.createRange()).setStart(l.node,l.offset),e.removeAllRanges(),a>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)1===e.nodeType&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"==typeof n.focus&&n.focus(),n=0;n<t.length;n++)(e=t[n]).element.scrollLeft=e.left,e.element.scrollTop=e.top}}(sy),i6=!!sg,sy=sg=null,e.current=l,ak(e,l.alternate,l),j(),a0=s,eh=u,aJ.transition=n}else e.current=l;if(of?(of=!1,od=e,op=a):oB(e,o),0===(o=e.pendingLanes)&&(oc=null),function(e){if(ee&&"function"==typeof ee.onCommitFiberRoot)try{ee.onCommitFiberRoot(J,e,void 0,128==(128&e.current.flags))}catch(e){}}(l.stateNode,r),nZ(e),null!==t)for(r=e.onRecoverableError,l=0;l<t.length;l++)o={digest:(a=t[l]).digest,componentStack:a.stack},r(a.value,o);if(ou)throw ou=!1,e=os,os=null,e;0!=(3&op)&&0!==e.tag&&oV(),0!=(3&(o=e.pendingLanes))?e===oy?og++:(og=0,oy=e):og=0,nJ(!1)}}(e,t,n,r)}finally{aJ.transition=l,eh=r}return null}function oB(e,t){0==(e.pooledCacheLanes&=t)&&null!=(t=e.pooledCache)&&(e.pooledCache=null,lX(t))}function oV(){if(null!==od){var e=od,t=oh;oh=0;var n=em(op),r=32>n?32:n;n=aJ.transition;var l=eh;try{if(aJ.transition=null,eh=r,null===od)var a=!1;else{r=om,om=null;var o=od,u=op;if(od=null,op=0,0!=(6&a0))throw Error(i(331));var s=a0;if(a0|=4,aH(o.current),aU(o,o.current,u,r),a0=s,nJ(!1),ee&&"function"==typeof ee.onPostCommitFiberRoot)try{ee.onPostCommitFiberRoot(J,o)}catch(e){}a=!0}return a}finally{eh=l,aJ.transition=n,oB(e,t)}}return!1}function oQ(e,t,n){t=le(n,t),t=lr(e,t,2),null!==(e=ni(e,t,2))&&(ed(e,2),nZ(e))}function o$(e,t,n){if(3===e.tag)oQ(e,e,n);else for(;null!==t;){if(3===t.tag){oQ(t,e,n);break}if(1===t.tag){var r=t.stateNode;if("function"==typeof t.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===oc||!oc.has(r))){e=le(n,e),e=ll(t,e,2),null!==(t=ni(t,e,2))&&(ed(t,2),nZ(t));break}}t=t.return}}function oW(e,t,n){var r=e.pingCache;if(null===r){r=e.pingCache=new aY;var l=new Set;r.set(t,l)}else void 0===(l=r.get(t))&&(l=new Set,r.set(t,l));l.has(n)||(a6=!0,l.add(n),e=oj.bind(null,e,t,n),t.then(e,e))}function oj(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,a1===e&&(a3&n)===n&&(4===a7||3===a7&&(125829120&a3)===a3&&500>H()-oa?0==(2&a0)&&oN(e,0):on|=n),nZ(e)}function oH(e,t){0===t&&(t=0==(1&e.mode)?2:ec()),null!==(e=ne(e,t))&&(ed(e,t),nZ(e))}function oq(e){var t=e.memoizedState,n=0;null!==t&&(n=t.retryLane),oH(e,n)}function oK(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;null!==l&&(n=l.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}null!==r&&r.delete(t),oH(e,n)}function oY(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function oX(e,t,n,r){return new oY(e,t,n,r)}function oG(e){return!(!(e=e.prototype)||!e.isReactComponent)}function oZ(e,t){var n=e.alternate;return null===n?((n=oX(e.tag,t,e.key,e.mode)).elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=31457280&e.flags,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=null===t?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n.refCleanup=e.refCleanup,n}function oJ(e,t){e.flags&=31457282;var n=e.alternate;return null===n?(e.childLanes=0,e.lanes=t,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=n.childLanes,e.lanes=n.lanes,e.child=n.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=n.memoizedProps,e.memoizedState=n.memoizedState,e.updateQueue=n.updateQueue,e.type=n.type,t=n.dependencies,e.dependencies=null===t?null:{lanes:t.lanes,firstContext:t.firstContext}),e}function o0(e,t,n,r,l,a){var o=2;if(r=e,"function"==typeof e)oG(e)&&(o=1);else if("string"==typeof e)o=!function(e,t,n){if(1===n||null!=t.itemProp)return!1;switch(e){case"meta":case"title":return!0;case"style":if("string"!=typeof t.precedence||"string"!=typeof t.href||""===t.href)break;return!0;case"link":if("string"!=typeof t.rel||"string"!=typeof t.href||""===t.href||t.onLoad||t.onError)break;if("stylesheet"===t.rel)return e=t.disabled,"string"==typeof t.precedence&&null==e;return!0;case"script":if(!0===t.async&&!t.onLoad&&!t.onError&&"string"==typeof t.src&&t.src)return!0}return!1}(e,n,R.current)?"html"===e||"head"===e||"body"===e?27:5:26;else e:switch(e){case y:return o1(n.children,l,a,t);case v:o=8,0!=(1&(l|=8))&&(l|=16);break;case b:return(e=oX(12,n,t,2|l)).elementType=b,e.lanes=a,e;case x:return(e=oX(13,n,t,l)).elementType=x,e.lanes=a,e;case C:return(e=oX(19,n,t,l)).elementType=C,e.lanes=a,e;case _:return o2(n,l,a,t);case L:case N:case T:return(e=oX(24,n,t,l)).elementType=T,e.lanes=a,e;default:if("object"==typeof e&&null!==e)switch(e.$$typeof){case k:o=10;break e;case w:o=9;break e;case E:o=11;break e;case z:o=14;break e;case P:o=16,r=null;break e}throw Error(i(130,null==e?e:typeof e,""))}return(t=oX(o,n,t,l)).elementType=e,t.type=r,t.lanes=a,t}function o1(e,t,n,r){return(e=oX(7,e,r,t)).lanes=n,e}function o2(e,t,n,r){(e=oX(22,e,r,t)).elementType=_,e.lanes=n;var l={_visibility:1,_pendingVisibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null,_current:null,detach:function(){var e=l._current;if(null===e)throw Error(i(456));if(0==(2&l._pendingVisibility)){var t=ne(e,2);null!==t&&(l._pendingVisibility|=2,ob(t,e,2))}},attach:function(){var e=l._current;if(null===e)throw Error(i(456));if(0!=(2&l._pendingVisibility)){var t=ne(e,2);null!==t&&(l._pendingVisibility&=-3,ob(t,e,2))}}};return e.stateNode=l,e}function o3(e,t,n){return(e=oX(6,e,null,t)).lanes=n,e}function o4(e,t,n){return(t=oX(4,null!==e.children?e.children:[],e.key,t)).lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function o8(e,t,n,r,l){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=ef(-1),this.entangledLanes=this.errorRecoveryDisabledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ef(0),this.hiddenUpdates=ef(null),this.identifierPrefix=r,this.onRecoverableError=l,this.pooledCache=null,this.pooledCacheLanes=0,this.mutableSourceEagerHydrationData=null,this.incompleteTransitions=new Map}function o6(e,t,n,r,l,a,o,i,u){return e=new o8(e,t,n,i,u),1===t?(t=1,!0===a&&(t|=24)):t=0,a=oX(3,null,null,t),e.current=a,a.stateNode=e,t=lY(),t.refCount++,e.pooledCache=t,t.refCount++,a.memoizedState={element:r,isDehydrated:n,cache:t},nl(a),e}function o5(e){if(!e)return tg;e=e._reactInternals;e:{if(td(e)!==e||1!==e.tag)throw Error(i(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(tw(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(null!==t);throw Error(i(171))}if(1===e.tag){var n=e.type;if(tw(n))return tx(e,n,t)}return t}function o7(e,t,n,r,l,a,o,i,u){return(e=o6(n,r,!0,e,l,a,o,i,u)).context=o5(null),(l=no(r=ov(n=e.current))).callback=null!=t?t:null,ni(n,l,r),e.current.lanes=r,ed(e,r),nZ(e),e}function o9(e,t,n,r){var l=t.current,a=ov(l);return n=o5(n),null===t.context?t.context=n:t.pendingContext=n,(t=no(a)).payload={element:e},null!==(r=void 0===r?null:r)&&(t.callback=r),null!==(e=ni(l,t,a))&&(ob(e,l,a),nu(e,l,a)),a}function ie(e){return(e=e.current).child?(e.child.tag,e.child.stateNode):null}function it(e,t){if(null!==(e=e.memoizedState)&&null!==e.dehydrated){var n=e.retryLane;e.retryLane=0!==n&&n<t?n:t}}function ir(e,t){it(e,t),(e=e.alternate)&&it(e,t)}function il(e){if(13===e.tag){var t=ne(e,134217728);null!==t&&ob(t,e,134217728),ir(e,134217728)}}iv=function(e,t,n){if(null!==e){if(e.memoizedProps!==t.pendingProps||tv.current)lu=!0;else{if(0==(e.lanes&n)&&0==(128&t.flags))return lu=!1,function(e,t,n){switch(t.tag){case 3:lk(t),lA(t,lK,e.memoizedState.cache),t3();break;case 27:case 5:B(t);break;case 1:tw(t.type)&&tC(t);break;case 4:I(t,t.stateNode.containerInfo);break;case 10:lA(t,t.type._context,t.memoizedProps.value);break;case 13:var r=t.memoizedState;if(null!==r){if(null!==r.dehydrated)return nI(t),t.flags|=128,null;if(0!=(n&t.child.childLanes))return lx(e,t,n);return nI(t),null!==(e=lT(e,t,n))?e.sibling:null}nI(t);break;case 19:if(r=0!=(n&t.childLanes),0!=(128&e.flags)){if(r)return l_(e,t,n);t.flags|=128}var l=t.memoizedState;if(null!==l&&(l.rendering=null,l.tail=null,l.lastEffect=null),h(nQ,nQ.current),!r)return null;break;case 22:case 23:return t.lanes=0,lp(e,t,n);case 24:lA(t,lK,e.memoizedState.cache)}return lT(e,t,n)}(e,t,n);lu=0!=(131072&e.flags)}}else lu=!1,t$&&0!=(1048576&t.flags)&&tI(t,tT,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;lL(e,t),e=t.pendingProps;var l=tk(t,ty.current);lV(t,n),l=rs(null,t,r,e,l,n);var a=rd();return t.flags|=1,"object"==typeof l&&null!==l&&"function"==typeof l.render&&void 0===l.$$typeof?(t.tag=1,t.memoizedState=null,t.updateQueue=null,tw(r)?(a=!0,tC(t)):a=!1,t.memoizedState=null!==l.state&&void 0!==l.state?l.state:null,nl(t),l.updater=r8,t.stateNode=l,l._reactInternals=t,r9(t,r,e,n),t=lb(null,t,r,!0,a,n)):(t.tag=0,t$&&a&&tU(t),ls(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(lL(e,t),e=t.pendingProps,r=(l=r._init)(r._payload),t.type=r,l=t.tag=function(e){if("function"==typeof e)return oG(e)?1:0;if(null!=e){if((e=e.$$typeof)===E)return 11;if(e===z)return 14}return 2}(r),e=r3(r,e),l){case 0:t=lg(null,t,r,e,n);break e;case 1:t=lv(null,t,r,e,n);break e;case 11:t=lc(null,t,r,e,n);break e;case 14:t=lf(null,t,r,r3(r.type,e),n);break e}throw Error(i(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:r3(r,l),lg(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:r3(r,l),lv(e,t,r,l,n);case 3:e:{if(lk(t),null===e)throw Error(i(387));l=t.pendingProps,r=(a=t.memoizedState).element,na(e,t),nc(t,l,null,n);var o=t.memoizedState;if(lA(t,lK,l=o.cache),l!==a.cache&&lB(t,lK,n),l=o.element,a.isDehydrated){if(a={element:l,isDehydrated:!1,cache:o.cache},t.updateQueue.baseState=a,t.memoizedState=a,256&t.flags){r=le(Error(i(423)),t),t=lw(e,t,l,n,r);break e}if(l!==r){r=le(Error(i(424)),t),t=lw(e,t,l,n,r);break e}for(tQ=sL(t.stateNode.containerInfo.firstChild),tV=t,t$=!0,tW=null,tj=!0,n=nL(t,null,l,n),t.child=n;n;)n.flags=-3&n.flags|4096,n=n.sibling}else{if(t3(),l===r){t=lT(e,t,n);break e}ls(e,t,l,n)}t=t.child}return t;case 26:return lm(e,t),n=t.memoizedState=function(e,t,n){if(!(t=(t=A.current)?sR(t):null))throw Error(i(446));switch(e){case"meta":case"title":return null;case"style":return"string"==typeof n.precedence&&"string"==typeof n.href?(n=sI(n.href),(e=(t=eT(t).hoistableStyles).get(n))||(e={type:"style",instance:null,count:0,state:null},t.set(n,e)),e):{type:"void",instance:null,count:0,state:null};case"link":if("stylesheet"===n.rel&&"string"==typeof n.href&&"string"==typeof n.precedence){e=sI(n.href);var r,l,a,o,u=eT(t).hoistableStyles,s=u.get(e);return s||(t=t.ownerDocument||t,s={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},u.set(e,s),sF.has(e)||(r=t,l=e,a={rel:"preload",as:"style",href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},o=s.state,sF.set(l,a),r.querySelector(sU(l))||(r.querySelector('link[rel="preload"][as="style"]['+l+"]")?o.loading=1:(l=r.createElement("link"),o.preload=l,l.addEventListener("load",function(){return o.loading|=1}),l.addEventListener("error",function(){return o.loading|=2}),sh(l,"link",a),eM(l),r.head.appendChild(l))))),s}return null;case"script":return"string"==typeof n.src&&!0===n.async?(n=sV(n.src),(e=(t=eT(t).hoistableScripts).get(n))||(e={type:"script",instance:null,count:0,state:null},t.set(n,e)),e):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,e))}}(t.type,null===e?null:e.memoizedProps,t.pendingProps),null!==e||t$||null!==n||(n=t.type,e=t.pendingProps,(r=sv(A.current).createElement(n))[ev]=t,r[eb]=e,sh(r,n,e),eM(r),t.stateNode=r),null;case 27:return B(t),null===e&&t$&&(r=t.stateNode=sM(t.type,t.pendingProps,A.current),tV=t,tj=!0,tQ=sL(r.firstChild)),r=t.pendingProps.children,null!==e||t$?ls(e,t,r,n):t.child=n_(t,null,r,n),lm(e,t),t.child;case 5:return B(t),null===e&&t$&&((r=t.pendingProps,"script"===t.type?(l=r.onLoad,a=r.onError,r=!(r.async&&(l||a))):r=!0,r)?(l=r=tQ)?tK(t,l)||(tG(t)&&tZ(),tQ=sL(l.nextSibling),a=tV,tQ&&tK(t,tQ)?tH(a,l):(tq(tV,t),t$=!1,tV=t,tQ=r)):(tG(t)&&tZ(),tq(tV,t),t$=!1,tV=t,tQ=r):(t.flags=-4097&t.flags|2,t$=!1,tV=t)),r=t.type,l=t.pendingProps,a=null!==e?e.memoizedProps:null,o=l.children,sw(r,l)?o=null:null!==a&&sw(r,a)&&(t.flags|=32),lm(e,t),ls(e,t,o,n),t.child;case 6:return null===e&&t$&&((r=""!==t.pendingProps,(e=n=tQ)&&r)?tY(t,e)||(tG(t)&&tZ(),tQ=sL(e.nextSibling),r=tV,tQ&&tY(t,tQ)?tH(r,e):(tq(tV,t),t$=!1,tV=t,tQ=n)):(tG(t)&&tZ(),tq(tV,t),t$=!1,tV=t,tQ=n)),null;case 13:return lx(e,t,n);case 4:return I(t,t.stateNode.containerInfo),r=t.pendingProps,null===e?t.child=n_(t,null,r,n):ls(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:r3(r,l),lc(e,t,r,l,n);case 7:return ls(e,t,t.pendingProps,n),t.child;case 8:case 12:return ls(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,a=t.memoizedProps,o=l.value,lA(t,r,o),null!==a){if(tP(a.value,o)){if(a.children===l.children&&!tv.current){t=lT(e,t,n);break e}}else lB(t,r,n)}ls(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,lV(t,n),l=lQ(l),r=r(l),t.flags|=1,ls(e,t,r,n),t.child;case 14:return l=r3(r=t.type,t.pendingProps),l=r3(r.type,l),lf(e,t,r,l,n);case 15:return ld(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:r3(r,l),lL(e,t),t.tag=1,tw(r)?(e=!0,tC(t)):e=!1,lV(t,n),r5(t,r,l),r9(t,r,l,n),lb(null,t,r,!0,e,n);case 19:return l_(e,t,n);case 22:return lp(e,t,n);case 24:return lV(t,n),r=lQ(lK),null===e?(null===(l=lJ())&&(l=a1,a=lY(),l.pooledCache=a,a.refCount++,null!==a&&(l.pooledCacheLanes|=n),l=a),t.memoizedState={parent:r,cache:l},nl(t),lA(t,lK,l)):(0!=(e.lanes&n)&&(na(e,t),nc(t,null,null,n)),l=e.memoizedState,a=t.memoizedState,l.parent!==r?(l={parent:r,cache:r},t.memoizedState=l,0===t.lanes&&(t.memoizedState=t.updateQueue.baseState=l),lA(t,lK,r)):(r=a.cache,lA(t,lK,r),r!==l.cache&&lB(t,lK,n))),ls(e,t,t.pendingProps.children,n),t.child}throw Error(i(156,t.tag))};var ia=!1;function io(e,t,n){if(ia)return e(t,n);ia=!0;try{return oC(e,t,n)}finally{ia=!1,(null!==ti||null!==tu)&&(oz(),tf())}}function ii(e,t){var n=e.stateNode;if(null===n)return null;var r=eL(n);if(null===r)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(r=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!r;break e;default:e=!1}if(e)return null;if(n&&"function"!=typeof n)throw Error(i(231,t,typeof n));return n}var iu=!1;if(eA)try{var is={};Object.defineProperty(is,"passive",{get:function(){iu=!0}}),window.addEventListener("test",is,is),window.removeEventListener("test",is,is)}catch(e){iu=!1}function ic(e){var t=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===t&&(e=13):e=t,10===e&&(e=13),32<=e||13===e?e:0}function id(){return!0}function ip(){return!1}function ih(e){function t(t,n,r,l,a){for(var o in this._reactName=t,this._targetInst=r,this.type=n,this.nativeEvent=l,this.target=a,this.currentTarget=null,e)e.hasOwnProperty(o)&&(t=e[o],this[o]=t?t(l):l[o]);return this.isDefaultPrevented=(null!=l.defaultPrevented?l.defaultPrevented:!1===l.returnValue)?id:ip,this.isPropagationStopped=ip,this}return u(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=id)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=id)},persist:function(){},isPersistent:id}),t}var im,ig,iy,iv,ib,ik,iw,iS={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},iE=ih(iS),ix=u({},iS,{view:0,detail:0}),iC=ih(ix),iz=u({},ix,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:iA,button:0,buttons:0,relatedTarget:function(e){return void 0===e.relatedTarget?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==iw&&(iw&&"mousemove"===e.type?(ib=e.screenX-iw.screenX,ik=e.screenY-iw.screenY):ik=ib=0,iw=e),ib)},movementY:function(e){return"movementY"in e?e.movementY:ik}}),iP=ih(iz),iN=ih(u({},iz,{dataTransfer:0})),i_=ih(u({},ix,{relatedTarget:0})),iL=ih(u({},iS,{animationName:0,elapsedTime:0,pseudoElement:0})),iT=ih(u({},iS,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}})),iM=ih(u({},iS,{data:0})),iF={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},iD={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},iR={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function iO(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):!!(e=iR[e])&&!!t[e]}function iA(){return iO}var iI=ih(u({},ix,{key:function(e){if(e.key){var t=iF[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"===e.type?13===(e=ic(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?iD[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:iA,charCode:function(e){return"keypress"===e.type?ic(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?ic(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}})),iU=ih(u({},iz,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),iB=ih(u({},ix,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:iA})),iV=ih(u({},iS,{propertyName:0,elapsedTime:0,pseudoElement:0})),iQ=ih(u({},iz,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0})),i$=!1,iW=null,ij=null,iH=null,iq=new Map,iK=new Map,iY=[],iX="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function iG(e,t){switch(e){case"focusin":case"focusout":iW=null;break;case"dragenter":case"dragleave":ij=null;break;case"mouseover":case"mouseout":iH=null;break;case"pointerover":case"pointerout":iq.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":iK.delete(t.pointerId)}}function iZ(e,t,n,r,l,a){return null===e||e.nativeEvent!==a?(e={blockedOn:t,domEventName:n,eventSystemFlags:r,nativeEvent:a,targetContainers:[l]},null!==t&&null!==(t=eN(t))&&il(t),e):(e.eventSystemFlags|=r,t=e.targetContainers,null!==l&&-1===t.indexOf(l)&&t.push(l),e)}function iJ(e){var t=eP(e.target);if(null!==t){var n=td(t);if(null!==n){if(13===(t=n.tag)){if(null!==(t=tp(n))){e.blockedOn=t,function(e,t){var n=eh;try{return eh=e,t()}finally{eh=n}}(e.priority,function(){if(13===n.tag){var e=ov(n),t=ne(n,e);null!==t&&ob(t,n,e),ir(n,e)}});return}}else if(3===t&&n.stateNode.current.memoizedState.isDehydrated){e.blockedOn=3===n.tag?n.stateNode.containerInfo:null;return}}}e.blockedOn=null}function i0(e){if(null!==e.blockedOn)return!1;for(var t=e.targetContainers;0<t.length;){var n=ue(e.nativeEvent);if(null!==n)return null!==(t=eN(n))&&il(t),e.blockedOn=n,!1;var r=new(n=e.nativeEvent).constructor(n.type,n);ta=r,n.target.dispatchEvent(r),ta=null,t.shift()}return!0}function i1(e,t,n){i0(e)&&n.delete(t)}function i2(){i$=!1,null!==iW&&i0(iW)&&(iW=null),null!==ij&&i0(ij)&&(ij=null),null!==iH&&i0(iH)&&(iH=null),iq.forEach(i1),iK.forEach(i1)}function i3(e,t){e.blockedOn===t&&(e.blockedOn=null,i$||(i$=!0,a.unstable_scheduleCallback(a.unstable_NormalPriority,i2)))}function i4(e){function t(t){return i3(t,e)}null!==iW&&i3(iW,e),null!==ij&&i3(ij,e),null!==iH&&i3(iH,e),iq.forEach(t),iK.forEach(t);for(var n=0;n<iY.length;n++){var r=iY[n];r.blockedOn===e&&(r.blockedOn=null)}for(;0<iY.length&&null===(n=iY[0]).blockedOn;)iJ(n),null===n.blockedOn&&iY.shift()}var i8=s.ReactCurrentBatchConfig,i6=!0;function i5(e,t,n,r){var l=eh,a=i8.transition;i8.transition=null;try{eh=2,i9(e,t,n,r)}finally{eh=l,i8.transition=a}}function i7(e,t,n,r){var l=eh,a=i8.transition;i8.transition=null;try{eh=8,i9(e,t,n,r)}finally{eh=l,i8.transition=a}}function i9(e,t,n,r){if(i6){var l=ue(r);if(null===l)sn(e,t,r,ut,n),iG(e,r);else if(function(e,t,n,r,l){switch(t){case"focusin":return iW=iZ(iW,e,t,n,r,l),!0;case"dragenter":return ij=iZ(ij,e,t,n,r,l),!0;case"mouseover":return iH=iZ(iH,e,t,n,r,l),!0;case"pointerover":var a=l.pointerId;return iq.set(a,iZ(iq.get(a)||null,e,t,n,r,l)),!0;case"gotpointercapture":return a=l.pointerId,iK.set(a,iZ(iK.get(a)||null,e,t,n,r,l)),!0}return!1}(l,e,t,n,r))r.stopPropagation();else if(iG(e,r),4&t&&-1<iX.indexOf(e)){for(;null!==l;){var a=eN(l);if(null!==a&&function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var n=eo(t.pendingLanes);0!==n&&(ep(t,2|n),nZ(t),0==(6&a0)&&(oo=H()+500,nJ(!1)))}break;case 13:oz(function(){var t=ne(e,2);null!==t&&ob(t,e,2)}),ir(e,2)}}(a),null===(a=ue(r))&&sn(e,t,r,ut,n),a===l)break;l=a}null!==l&&r.stopPropagation()}else sn(e,t,r,null,n)}}function ue(e){e=to(e);e:{if(ut=null,null!==(e=eP(e))){var t=td(e);if(null===t)e=null;else{var n=t.tag;if(13===n){if(null!==(e=tp(t)))break e;e=null}else if(3===n){if(t.stateNode.current.memoizedState.isDehydrated){e=3===t.tag?t.stateNode.containerInfo:null;break e}e=null}else t!==e&&(e=null)}}ut=e,e=null}return e}var ut=null;function un(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(q()){case K:return 2;case Y:return 8;case X:case G:return 32;case Z:return 536870912;default:return 32}default:return 32}}var ur=null,ul=null,ua=null;function uo(){if(ua)return ua;var e,t,n=ul,r=n.length,l="value"in ur?ur.value:ur.textContent,a=l.length;for(e=0;e<r&&n[e]===l[e];e++);var o=r-e;for(t=1;t<=o&&n[r-t]===l[a-t];t++);return ua=l.slice(e,1<t?1-t:void 0)}var ui=[9,13,27,32],uu=eA&&"CompositionEvent"in window,us=null;eA&&"documentMode"in document&&(us=document.documentMode);var uc=eA&&"TextEvent"in window&&!us,uf=eA&&(!uu||us&&8<us&&11>=us),ud=!1;function up(e,t){switch(e){case"keyup":return -1!==ui.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function uh(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var um=!1,ug={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function uy(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!ug[e.type]:"textarea"===t}function uv(e,t,n,r){tc(r),0<(t=sl(t,"onChange")).length&&(n=new iE("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var ub=null,uk=null;function uw(e){u6(e,0)}function uS(e){if(eX(e_(e)))return e}function uE(e,t){if("change"===e)return t}var ux=!1;if(eA){if(eA){var uC="oninput"in document;if(!uC){var uz=document.createElement("div");uz.setAttribute("oninput","return;"),uC="function"==typeof uz.oninput}r=uC}else r=!1;ux=r&&(!document.documentMode||9<document.documentMode)}function uP(){ub&&(ub.detachEvent("onpropertychange",uN),uk=ub=null)}function uN(e){if("value"===e.propertyName&&uS(uk)){var t=[];uv(t,uk,e,to(e)),io(uw,t)}}function u_(e,t,n){"focusin"===e?(uP(),ub=t,uk=n,ub.attachEvent("onpropertychange",uN)):"focusout"===e&&uP()}function uL(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return uS(uk)}function uT(e,t){if("click"===e)return uS(t)}function uM(e,t){if("input"===e||"change"===e)return uS(t)}function uF(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function uD(e,t){var n,r=uF(e);for(e=0;r;){if(3===r.nodeType){if(n=e+r.textContent.length,e<=t&&n>=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=uF(r)}}function uR(){for(var e=window,t=eG();t instanceof e.HTMLIFrameElement;){try{var n="string"==typeof t.contentWindow.location.href}catch(e){n=!1}if(n)e=t.contentWindow;else break;t=eG(e.document)}return t}function uO(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}var uA=eA&&"documentMode"in document&&11>=document.documentMode,uI=null,uU=null,uB=null,uV=!1;function uQ(e,t,n){var r=n.window===n?n.document:9===n.nodeType?n:n.ownerDocument;uV||null==uI||uI!==eG(r)||(r="selectionStart"in(r=uI)&&uO(r)?{start:r.selectionStart,end:r.selectionEnd}:{anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},uB&&np(uB,r)||(uB=r,0<(r=sl(uU,"onSelect")).length&&(t=new iE("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=uI)))}function u$(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var uW={animationend:u$("Animation","AnimationEnd"),animationiteration:u$("Animation","AnimationIteration"),animationstart:u$("Animation","AnimationStart"),transitionend:u$("Transition","TransitionEnd")},uj={},uH={};function uq(e){if(uj[e])return uj[e];if(!uW[e])return e;var t,n=uW[e];for(t in n)if(n.hasOwnProperty(t)&&t in uH)return uj[e]=n[t];return e}eA&&(uH=document.createElement("div").style,"AnimationEvent"in window||(delete uW.animationend.animation,delete uW.animationiteration.animation,delete uW.animationstart.animation),"TransitionEvent"in window||delete uW.transitionend.transition);var uK=uq("animationend"),uY=uq("animationiteration"),uX=uq("animationstart"),uG=uq("transitionend"),uZ=new Map,uJ="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function u0(e,t){uZ.set(e,t),eR(t,[e])}for(var u1=0;u1<uJ.length;u1++){var u2=uJ[u1];u0(u2.toLowerCase(),"on"+(u2[0].toUpperCase()+u2.slice(1)))}u0(uK,"onAnimationEnd"),u0(uY,"onAnimationIteration"),u0(uX,"onAnimationStart"),u0("dblclick","onDoubleClick"),u0("focusin","onFocus"),u0("focusout","onBlur"),u0(uG,"onTransitionEnd"),eO("onMouseEnter",["mouseout","mouseover"]),eO("onMouseLeave",["mouseout","mouseover"]),eO("onPointerEnter",["pointerout","pointerover"]),eO("onPointerLeave",["pointerout","pointerover"]),eR("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),eR("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),eR("onBeforeInput",["compositionend","keypress","textInput","paste"]),eR("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),eR("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),eR("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var u3="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),u4=new Set("cancel close invalid load scroll toggle".split(" ").concat(u3));function u8(e,t,n){var r=e.type||"unknown-event";e.currentTarget=n,function(e,t,n,r,l,a,o,u,s){if(ao.apply(this,arguments),at){if(at){var c=an;at=!1,an=null}else throw Error(i(198));ar||(ar=!0,al=c)}}(r,t,void 0,e),e.currentTarget=null}function u6(e,t){t=0!=(4&t);for(var n=0;n<e.length;n++){var r=e[n],l=r.event;r=r.listeners;e:{var a=void 0;if(t)for(var o=r.length-1;0<=o;o--){var i=r[o],u=i.instance,s=i.currentTarget;if(i=i.listener,u!==a&&l.isPropagationStopped())break e;u8(l,i,s),a=u}else for(o=0;o<r.length;o++){if(u=(i=r[o]).instance,s=i.currentTarget,i=i.listener,u!==a&&l.isPropagationStopped())break e;u8(l,i,s),a=u}}}if(ar)throw e=al,ar=!1,al=null,e}function u5(e,t){var n=t[ew];void 0===n&&(n=t[ew]=new Set);var r=e+"__bubble";n.has(r)||(st(t,e,2,!1),n.add(r))}function u7(e,t,n){var r=0;t&&(r|=4),st(n,e,r,t)}var u9="_reactListening"+Math.random().toString(36).slice(2);function se(e){if(!e[u9]){e[u9]=!0,eF.forEach(function(t){"selectionchange"!==t&&(u4.has(t)||u7(t,!1,e),u7(t,!0,e))});var t=9===e.nodeType?e:e.ownerDocument;null===t||t[u9]||(t[u9]=!0,u7("selectionchange",!1,t))}}function st(e,t,n,r){switch(un(t)){case 2:var l=i5;break;case 8:l=i7;break;default:l=i9}n=l.bind(null,t,n,e),l=void 0,iu&&("touchstart"===t||"touchmove"===t||"wheel"===t)&&(l=!0),r?void 0!==l?e.addEventListener(t,n,{capture:!0,passive:l}):e.addEventListener(t,n,!0):void 0!==l?e.addEventListener(t,n,{passive:l}):e.addEventListener(t,n,!1)}function sn(e,t,n,r,l){var a=r;if(0==(1&t)&&0==(2&t)&&null!==r)e:for(;;){if(null===r)return;var o=r.tag;if(3===o||4===o){var i=r.stateNode.containerInfo;if(i===l||8===i.nodeType&&i.parentNode===l)break;if(4===o)for(o=r.return;null!==o;){var u=o.tag;if((3===u||4===u)&&((u=o.stateNode.containerInfo)===l||8===u.nodeType&&u.parentNode===l))return;o=o.return}for(;null!==i;){if(null===(o=eP(i)))return;if(5===(u=o.tag)||6===u||26===u||27===u){r=a=o;continue e}i=i.parentNode}}r=r.return}io(function(){var r=a,l=to(n),o=[];e:{var i=uZ.get(e);if(void 0!==i){var u=iE,s=e;switch(e){case"keypress":if(0===ic(n))break e;case"keydown":case"keyup":u=iI;break;case"focusin":s="focus",u=i_;break;case"focusout":s="blur",u=i_;break;case"beforeblur":case"afterblur":u=i_;break;case"click":if(2===n.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":u=iP;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":u=iN;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":u=iB;break;case uK:case uY:case uX:u=iL;break;case uG:u=iV;break;case"scroll":u=iC;break;case"wheel":u=iQ;break;case"copy":case"cut":case"paste":u=iT;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":u=iU}var c=0!=(4&t),f=!c&&"scroll"===e,d=c?null!==i?i+"Capture":null:i;c=[];for(var p,h=r;null!==h;){var m=h;if(p=m.stateNode,5!==(m=m.tag)&&26!==m&&27!==m||null===p||null===d||null!=(m=ii(h,d))&&c.push(sr(h,m,p)),f)break;h=h.return}0<c.length&&(i=new u(i,s,null,n,l),o.push({event:i,listeners:c}))}}if(0==(7&t)){e:if(i="mouseover"===e||"pointerover"===e,u="mouseout"===e||"pointerout"===e,!(i&&n!==ta&&(s=n.relatedTarget||n.fromElement)&&(eP(s)||s[ek]))&&(u||i)&&(i=l.window===l?l:(i=l.ownerDocument)?i.defaultView||i.parentWindow:window,u?(s=n.relatedTarget||n.toElement,u=r,null!==(s=s?eP(s):null)&&(f=td(s),c=s.tag,s!==f||5!==c&&27!==c&&6!==c)&&(s=null)):(u=null,s=r),u!==s)){if(c=iP,m="onMouseLeave",d="onMouseEnter",h="mouse",("pointerout"===e||"pointerover"===e)&&(c=iU,m="onPointerLeave",d="onPointerEnter",h="pointer"),f=null==u?i:e_(u),p=null==s?i:e_(s),(i=new c(m,h+"leave",u,n,l)).target=f,i.relatedTarget=p,m=null,eP(l)===r&&((c=new c(d,h+"enter",s,n,l)).target=p,c.relatedTarget=f,m=c),f=m,u&&s)t:{for(c=u,d=s,h=0,p=c;p;p=sa(p))h++;for(p=0,m=d;m;m=sa(m))p++;for(;0<h-p;)c=sa(c),h--;for(;0<p-h;)d=sa(d),p--;for(;h--;){if(c===d||null!==d&&c===d.alternate)break t;c=sa(c),d=sa(d)}c=null}else c=null;null!==u&&so(o,i,u,c,!1),null!==s&&null!==f&&so(o,f,s,c,!0)}e:{if("select"===(u=(i=r?e_(r):window).nodeName&&i.nodeName.toLowerCase())||"input"===u&&"file"===i.type)var g,y=uE;else if(uy(i)){if(ux)y=uM;else{y=uL;var v=u_}}else(u=i.nodeName)&&"input"===u.toLowerCase()&&("checkbox"===i.type||"radio"===i.type)&&(y=uT);if(y&&(y=y(e,r))){uv(o,y,n,l);break e}v&&v(e,i,r),"focusout"===e&&r&&"number"===i.type&&null!=r.memoizedProps.value&&e2(i,"number",i.value)}switch(v=r?e_(r):window,e){case"focusin":(uy(v)||"true"===v.contentEditable)&&(uI=v,uU=r,uB=null);break;case"focusout":uB=uU=uI=null;break;case"mousedown":uV=!0;break;case"contextmenu":case"mouseup":case"dragend":uV=!1,uQ(o,n,l);break;case"selectionchange":if(uA)break;case"keydown":case"keyup":uQ(o,n,l)}if(uu)t:{switch(e){case"compositionstart":var b="onCompositionStart";break t;case"compositionend":b="onCompositionEnd";break t;case"compositionupdate":b="onCompositionUpdate";break t}b=void 0}else um?up(e,n)&&(b="onCompositionEnd"):"keydown"===e&&229===n.keyCode&&(b="onCompositionStart");b&&(uf&&"ko"!==n.locale&&(um||"onCompositionStart"!==b?"onCompositionEnd"===b&&um&&(g=uo()):(ul="value"in(ur=l)?ur.value:ur.textContent,um=!0)),0<(v=sl(r,b)).length&&(b=new iM(b,e,null,n,l),o.push({event:b,listeners:v}),g?b.data=g:null!==(g=uh(n))&&(b.data=g))),(g=uc?function(e,t){switch(e){case"compositionend":return uh(t);case"keypress":if(32!==t.which)return null;return ud=!0," ";case"textInput":return" "===(e=t.data)&&ud?null:e;default:return null}}(e,n):function(e,t){if(um)return"compositionend"===e||!uu&&up(e,t)?(e=uo(),ua=ul=ur=null,um=!1,e):null;switch(e){case"paste":default:return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return uf&&"ko"!==t.locale?null:t.data}}(e,n))&&0<(r=sl(r,"onBeforeInput")).length&&(l=new iM("onBeforeInput","beforeinput",null,n,l),o.push({event:l,listeners:r}),l.data=g)}u6(o,t)})}function sr(e,t,n){return{instance:e,listener:t,currentTarget:n}}function sl(e,t){for(var n=t+"Capture",r=[];null!==e;){var l=e,a=l.stateNode;5!==(l=l.tag)&&26!==l&&27!==l||null===a||(null!=(l=ii(e,n))&&r.unshift(sr(e,l,a)),null!=(l=ii(e,t))&&r.push(sr(e,l,a))),e=e.return}return r}function sa(e){if(null===e)return null;do e=e.return;while(e&&5!==e.tag&&27!==e.tag);return e||null}function so(e,t,n,r,l){for(var a=t._reactName,o=[];null!==n&&n!==r;){var i=n,u=i.alternate,s=i.stateNode;if(i=i.tag,null!==u&&u===r)break;5!==i&&26!==i&&27!==i||null===s||(u=s,l?null!=(s=ii(n,a))&&o.unshift(sr(n,s,u)):l||null!=(s=ii(n,a))&&o.push(sr(n,s,u))),n=n.return}0!==o.length&&e.push({event:t,listeners:o})}var si=/\r\n?/g,su=/\u0000|\uFFFD/g;function ss(e){return("string"==typeof e?e:""+e).replace(si,"\n").replace(su,"")}function sc(e,t,n){if(t=ss(t),ss(e)!==t&&n)throw Error(i(425))}function sf(){}function sd(e,t,n,r,l){switch(n){case"children":"string"==typeof r?"body"===t||"textarea"===t&&""===r||te(e,r):"number"==typeof r&&"body"!==t&&te(e,""+r);break;case"className":eQ(e,"class",r);break;case"tabIndex":eQ(e,"tabindex",r);break;case"dir":case"role":case"viewBox":case"width":case"height":eQ(e,n,r);break;case"style":tn(e,r);break;case"src":case"href":case"action":case"formAction":if(null==r||"function"==typeof r||"symbol"==typeof r||"boolean"==typeof r){e.removeAttribute(n);break}e.setAttribute(n,""+r);break;case"onClick":null!=r&&(e.onclick=sf);break;case"onScroll":null!=r&&u5("scroll",e);break;case"dangerouslySetInnerHTML":if(null!=r){if("object"!=typeof r||!("__html"in r))throw Error(i(61));if(null!=(r=r.__html)){if(null!=l.children)throw Error(i(60));e9(e,r)}}break;case"multiple":e.multiple=r&&"function"!=typeof r&&"symbol"!=typeof r;break;case"muted":e.muted=r&&"function"!=typeof r&&"symbol"!=typeof r;break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"autoFocus":break;case"xlinkHref":if(null==r||"function"==typeof r||"boolean"==typeof r||"symbol"==typeof r){e.removeAttribute("xlink:href");break}e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",""+r);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":null!=r&&"function"!=typeof r&&"symbol"!=typeof r?e.setAttribute(n,""+r):e.removeAttribute(n);break;case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":r&&"function"!=typeof r&&"symbol"!=typeof r?e.setAttribute(n,""):e.removeAttribute(n);break;case"capture":case"download":!0===r?e.setAttribute(n,""):!1!==r&&null!=r&&"function"!=typeof r&&"symbol"!=typeof r?e.setAttribute(n,r):e.removeAttribute(n);break;case"cols":case"rows":case"size":case"span":null!=r&&"function"!=typeof r&&"symbol"!=typeof r&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case"rowSpan":case"start":null==r||"function"==typeof r||"symbol"==typeof r||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case"xlinkActuate":e$(e,"http://www.w3.org/1999/xlink","xlink:actuate",r);break;case"xlinkArcrole":e$(e,"http://www.w3.org/1999/xlink","xlink:arcrole",r);break;case"xlinkRole":e$(e,"http://www.w3.org/1999/xlink","xlink:role",r);break;case"xlinkShow":e$(e,"http://www.w3.org/1999/xlink","xlink:show",r);break;case"xlinkTitle":e$(e,"http://www.w3.org/1999/xlink","xlink:title",r);break;case"xlinkType":e$(e,"http://www.w3.org/1999/xlink","xlink:type",r);break;case"xmlBase":e$(e,"http://www.w3.org/XML/1998/namespace","xml:base",r);break;case"xmlLang":e$(e,"http://www.w3.org/XML/1998/namespace","xml:lang",r);break;case"xmlSpace":e$(e,"http://www.w3.org/XML/1998/namespace","xml:space",r);break;case"is":eV(e,"is",r);break;default:2<n.length&&("o"===n[0]||"O"===n[0])&&("n"===n[1]||"N"===n[1])||eV(e,l=tl.get(n)||n,r)}}function sp(e,t,n,r,l){switch(n){case"style":tn(e,r);break;case"dangerouslySetInnerHTML":if(null!=r){if("object"!=typeof r||!("__html"in r))throw Error(i(61));if(null!=(t=r.__html)){if(null!=l.children)throw Error(i(60));e9(e,t)}}break;case"children":"string"==typeof r?te(e,r):"number"==typeof r&&te(e,""+r);break;case"onScroll":null!=r&&u5("scroll",e);break;case"onClick":null!=r&&(e.onclick=sf);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":break;default:eD.hasOwnProperty(n)||("boolean"==typeof r&&(r=""+r),eV(e,n,r))}}function sh(e,t,n){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":u5("invalid",e);var r=null,l=null,a=null,o=null,u=null,s=null;for(f in n)if(n.hasOwnProperty(f)){var c=n[f];if(null!=c)switch(f){case"name":r=c;break;case"type":l=c;break;case"checked":u=c;break;case"defaultChecked":s=c;break;case"value":a=c;break;case"defaultValue":o=c;break;case"children":case"dangerouslySetInnerHTML":if(null!=c)throw Error(i(137,t));break;default:sd(e,t,f,c,n)}}e1(e,a,o,u,s,l,r,!1),eY(e);return;case"select":u5("invalid",e);var f=l=a=null;for(r in n)if(n.hasOwnProperty(r)&&null!=(o=n[r]))switch(r){case"value":a=o;break;case"defaultValue":l=o;break;case"multiple":f=o;default:sd(e,t,r,o,n)}t=a,n=l,e.multiple=!!f,null!=t?e4(e,!!f,t,!1):null!=n&&e4(e,!!f,n,!0);return;case"textarea":for(l in u5("invalid",e),a=r=f=null,n)if(n.hasOwnProperty(l)&&null!=(o=n[l]))switch(l){case"value":f=o;break;case"defaultValue":r=o;break;case"children":a=o;break;case"dangerouslySetInnerHTML":if(null!=o)throw Error(i(91));break;default:sd(e,t,l,o,n)}e6(e,f,r,a),eY(e);return;case"option":for(o in n)n.hasOwnProperty(o)&&null!=(f=n[o])&&("selected"===o?e.selected=f&&"function"!=typeof f&&"symbol"!=typeof f:sd(e,t,o,f,n));return;case"dialog":u5("cancel",e),u5("close",e);break;case"iframe":case"object":u5("load",e);break;case"video":case"audio":for(f=0;f<u3.length;f++)u5(u3[f],e);break;case"image":u5("error",e),u5("load",e);break;case"details":u5("toggle",e);break;case"embed":case"source":case"img":case"link":u5("error",e),u5("load",e);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(u in n)if(n.hasOwnProperty(u)&&null!=(f=n[u]))switch(u){case"children":case"dangerouslySetInnerHTML":throw Error(i(137,t));default:sd(e,t,u,f,n)}return;default:if(tr(t)){for(s in n)n.hasOwnProperty(s)&&null!=(f=n[s])&&sp(e,t,s,f,n);return}}for(a in n)n.hasOwnProperty(a)&&null!=(f=n[a])&&sd(e,t,a,f,n)}function sm(e,t,n,r,l){switch(n){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var a=l.name,o=l.type,u=l.value,s=l.defaultValue;r=r.defaultValue;for(var c=l.checked,f=l.defaultChecked,d=0;d<t.length;d+=2){var p=t[d],h=t[d+1];switch(p){case"type":case"name":case"checked":case"defaultChecked":case"value":case"defaultValue":break;case"children":case"dangerouslySetInnerHTML":if(null!=h)throw Error(i(137,n));break;default:sd(e,n,p,h,l)}}e0(e,u,s,r,c,f,o,a);return;case"select":for(a=l.value,o=l.defaultValue,u=l.multiple,s=r.multiple,r=0;r<t.length;r+=2)c=t[r],f=t[r+1],"value"===c||sd(e,n,c,f,l);null!=a?e4(e,!!u,a,!1):!!s!=!!u&&(null!=o?e4(e,!!u,o,!0):e4(e,!!u,u?[]:"",!1));return;case"textarea":for(u=0,a=l.value,o=l.defaultValue;u<t.length;u+=2)switch(s=t[u],r=t[u+1],s){case"value":case"children":break;case"dangerouslySetInnerHTML":if(null!=r)throw Error(i(91));break;default:sd(e,n,s,r,l)}e8(e,a,o);return;case"option":for(a=0;a<t.length;a+=2)(o=t[a],u=t[a+1],"selected"===o)?e.selected=u&&"function"!=typeof u&&"symbol"!=typeof u:sd(e,n,o,u,l);return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(a=0;a<t.length;a+=2)switch(o=t[a],u=t[a+1],o){case"children":case"dangerouslySetInnerHTML":if(null!=u)throw Error(i(137,n));break;default:sd(e,n,o,u,l)}return;default:if(tr(n)){for(a=0;a<t.length;a+=2)sp(e,n,t[a],t[a+1],l);return}}for(a=0;a<t.length;a+=2)sd(e,n,t[a],t[a+1],l)}var sg=null,sy=null;function sv(e){return 9===e.nodeType?e:e.ownerDocument}function sb(e){switch(e){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function sk(e,t){if(0===e)switch(t){case"svg":return 1;case"math":return 2;default:return 0}return 1===e&&"foreignObject"===t?0:e}function sw(e,t){return"textarea"===e||"noscript"===e||"string"==typeof t.children||"number"==typeof t.children||"object"==typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&null!=t.dangerouslySetInnerHTML.__html}var sS="function"==typeof setTimeout?setTimeout:void 0,sE="function"==typeof clearTimeout?clearTimeout:void 0,sx="function"==typeof Promise?Promise:void 0,sC="function"==typeof queueMicrotask?queueMicrotask:void 0!==sx?function(e){return sx.resolve(null).then(e).catch(sz)}:sS;function sz(e){setTimeout(function(){throw e})}function sP(e,t){var n=t,r=0;do{var l=n.nextSibling;if(e.removeChild(n),l&&8===l.nodeType){if("/$"===(n=l.data)){if(0===r){e.removeChild(l),i4(t);return}r--}else"$"!==n&&"$?"!==n&&"$!"!==n||r++}n=l}while(n);i4(t)}function sN(e){var t=e.nodeType;if(9===t)s_(e);else if(1===t)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":s_(e);break;default:e.textContent=""}}function s_(e){var t=e.firstChild;for(t&&10===t.nodeType&&(t=t.nextSibling);t;){var n=t;switch(t=t.nextSibling,n.nodeName){case"HTML":case"HEAD":case"BODY":s_(n),ez(n);continue;case"STYLE":continue;case"LINK":if("stylesheet"===n.rel.toLowerCase())continue}e.removeChild(n)}}function sL(e){for(;null!=e;e=e.nextSibling){var t=e.nodeType;if(1===t||3===t)break;if(8===t){if("$"===(t=e.data)||"$!"===t||"$?"===t)break;if("/$"===t)return null}}return e}function sT(e){e=e.previousSibling;for(var t=0;e;){if(8===e.nodeType){var n=e.data;if("$"===n||"$!"===n||"$?"===n){if(0===t)return e;t--}else"/$"===n&&t++}e=e.previousSibling}return null}function sM(e,t,n){switch(t=sv(n),e){case"html":if(!(e=t.documentElement))throw Error(i(452));return e;case"head":if(!(e=t.head))throw Error(i(453));return e;case"body":if(!(e=t.body))throw Error(i(454));return e;default:throw Error(i(451))}}var sF=new Map,sD=new Set;function sR(e){return"function"==typeof e.getRootNode?e.getRootNode():e.ownerDocument}var sO={prefetchDNS:function(e){sA("dns-prefetch",null,e)},preconnect:function(e,t){sA("preconnect",null==t||"string"!=typeof t.crossOrigin?null:"use-credentials"===t.crossOrigin?"use-credentials":"",e)},preload:function(e,t){var n=document;if("string"==typeof e&&e&&"object"==typeof t&&null!==t&&n){var r=t.as,l=eJ(e),a=l='link[rel="preload"][as="'+r+'"][href="'+l+'"]';switch(r){case"style":a=sI(e);break;case"script":a=sV(e)}sF.has(a)||(e={href:e,rel:"preload",as:r,crossOrigin:"font"===r?"":t.crossOrigin,integrity:t.integrity,type:t.type},sF.set(a,e),null!==n.querySelector(l)||"style"===r&&n.querySelector(sU(a))||"script"===r&&n.querySelector("script[async]"+a)||(sh(r=n.createElement("link"),"link",e),eM(r),n.head.appendChild(r)))}},preinit:function(e,t){var n=document;if("string"==typeof e&&e&&"object"==typeof t&&null!==t)switch(t.as){case"style":var r=eT(n).hoistableStyles,l=sI(e),a=t.precedence||"default",o=r.get(l);if(o)break;var i={loading:0,preload:null};if(o=n.querySelector(sU(l)))i.loading=1;else{e={rel:"stylesheet",href:e,"data-precedence":a,crossOrigin:t.crossOrigin},(t=sF.get(l))&&sW(e,t);var u=o=n.createElement("link");eM(u),sh(u,"link",e),u._p=new Promise(function(e,t){u.onload=e,u.onerror=t}),u.addEventListener("load",function(){i.loading|=1}),u.addEventListener("error",function(){i.loading|=2}),i.loading|=4,s$(o,a,n)}o={type:"stylesheet",instance:o,count:1,state:i},r.set(l,o);break;case"script":r=eT(n).hoistableScripts,l=sV(e),(a=r.get(l))||((a=n.querySelector("script[async]"+l))||(e={src:e,async:!0,crossOrigin:t.crossOrigin,integrity:t.integrity,nonce:t.nonce},(t=sF.get(l))&&sj(e,t),eM(a=n.createElement("script")),sh(a,"link",e),n.head.appendChild(a)),a={type:"script",instance:a,count:1,state:null},r.set(l,a))}}};function sA(e,t,n){var r=document;if("string"==typeof n&&n){var l=eJ(n);l='link[rel="'+e+'"][href="'+l+'"]',"string"==typeof t&&(l+='[crossorigin="'+t+'"]'),sD.has(l)||(sD.add(l),e={rel:e,crossOrigin:t,href:n},null===r.querySelector(l)&&(sh(t=r.createElement("link"),"link",e),eM(t),r.head.appendChild(t)))}}function sI(e){return'href="'+eJ(e)+'"'}function sU(e){return'link[rel="stylesheet"]['+e+"]"}function sB(e){return u({},e,{"data-precedence":e.precedence,precedence:null})}function sV(e){return'[src="'+eJ(e)+'"]'}function sQ(e,t,n){if(t.count++,null===t.instance)switch(t.type){case"style":var r=e.querySelector('style[data-href~="'+eJ(n.href)+'"]');if(r)return t.instance=r,eM(r),r;var l=u({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return eM(r=(e.ownerDocument||e).createElement("style")),sh(r,"style",l),s$(r,n.precedence,e),t.instance=r;case"stylesheet":l=sI(n.href);var a=e.querySelector(sU(l));if(a)return t.instance=a,eM(a),a;r=sB(n),(l=sF.get(l))&&sW(r,l),eM(a=(e.ownerDocument||e).createElement("link"));var o=a;return o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),sh(a,"link",r),t.state.loading|=4,s$(a,n.precedence,e),t.instance=a;case"script":if(a=sV(n.src),l=e.querySelector("script[async]"+a))return t.instance=l,eM(l),l;return r=n,(l=sF.get(a))&&sj(r=u({},n),l),eM(l=(e=e.ownerDocument||e).createElement("script")),sh(l,"link",r),e.head.appendChild(l),t.instance=l;case"void":return null;default:throw Error(i(443,t.type))}else"stylesheet"===t.type&&0==(4&t.state.loading)&&(r=t.instance,t.state.loading|=4,s$(r,n.precedence,e));return t.instance}function s$(e,t,n){for(var r=n.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),l=r.length?r[r.length-1]:null,a=l,o=0;o<r.length;o++){var i=r[o];if(i.dataset.precedence===t)a=i;else if(a!==l)break}a?a.parentNode.insertBefore(e,a.nextSibling):(t=9===n.nodeType?n.head:n).insertBefore(e,t.firstChild)}function sW(e,t){null==e.crossOrigin&&(e.crossOrigin=t.crossOrigin),null==e.referrerPolicy&&(e.referrerPolicy=t.referrerPolicy),null==e.title&&(e.title=t.title)}function sj(e,t){null==e.crossOrigin&&(e.crossOrigin=t.crossOrigin),null==e.referrerPolicy&&(e.referrerPolicy=t.referrerPolicy),null==e.integrity&&(e.referrerPolicy=t.integrity)}var sH=null;function sq(e,t,n){if(null===sH){var r=new Map,l=sH=new Map;l.set(n,r)}else(r=(l=sH).get(n))||(r=new Map,l.set(n,r));if(r.has(e))return r;for(r.set(e,null),n=n.getElementsByTagName(e),l=0;l<n.length;l++){var a=n[l];if(!(a[eC]||a[ev]||"link"===e&&"stylesheet"===a.getAttribute("rel"))&&"http://www.w3.org/2000/svg"!==a.namespaceURI){var o=a.getAttribute(t)||"";o=e+o;var i=r.get(o);i?i.push(a):r.set(o,[a])}}return r}function sK(e,t,n){(e=e.ownerDocument||e).head.insertBefore(n,"title"===t?e.querySelector("head > title"):null)}var sY=null;function sX(){}function sG(){if(this.count--,0===this.count){if(this.stylesheets)sJ(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var sZ=null;function sJ(e,t){e.stylesheets=null,null!==e.unsuspend&&(e.count++,sZ=new Map,t.forEach(s0,e),sZ=null,sG.call(e))}function s0(e,t){if(!(4&t.state.loading)){var n=sZ.get(e);if(n)var r=n.get("last");else{n=new Map,sZ.set(e,n);for(var l=e.querySelectorAll("link[data-precedence],style[data-precedence]"),a=0;a<l.length;a++){var o=l[a];("link"===o.nodeName||"not all"!==o.getAttribute("media"))&&(n.set("p"+o.dataset.precedence,o),r=o)}r&&n.set("last",r)}o=(l=t.instance).getAttribute("data-precedence"),(a=n.get("p"+o)||r)===r&&n.set("last",l),n.set(o,l),this.count++,r=sG.bind(this),l.addEventListener("load",r),l.addEventListener("error",r),a?a.parentNode.insertBefore(l,a.nextSibling):(e=9===e.nodeType?e.head:e).insertBefore(l,e.firstChild),t.state.loading|=4}}var s1=o.Dispatcher;"undefined"!=typeof document&&(s1.current=sO);var s2="function"==typeof reportError?reportError:function(e){console.error(e)};function s3(e){this._internalRoot=e}function s4(e){this._internalRoot=e}function s8(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType)}function s6(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function s5(){}function s7(e,t,n,r,l){var a=n._reactRootContainer;if(a){var o=a;if("function"==typeof l){var i=l;l=function(){var e=ie(o);i.call(e)}}o9(t,o,e,l)}else o=function(e,t,n,r,l){if(l){if("function"==typeof r){var a=r;r=function(){var e=ie(o);a.call(e)}}var o=o7(t,r,e,0,null,!1,!1,"",s5);return e._reactRootContainer=o,e[ek]=o.current,se(8===e.nodeType?e.parentNode:e),oz(),o}if(sN(e),"function"==typeof r){var i=r;r=function(){var e=ie(u);i.call(e)}}var u=o6(e,0,!1,null,null,!1,!1,"",s5);return e._reactRootContainer=u,e[ek]=u.current,se(8===e.nodeType?e.parentNode:e),oz(function(){o9(t,u,n,r)}),u}(n,t,e,l,r);return ie(o)}s4.prototype.render=s3.prototype.render=function(e){var t=this._internalRoot;if(null===t)throw Error(i(409));o9(e,t,null,null)},s4.prototype.unmount=s3.prototype.unmount=function(){var e=this._internalRoot;if(null!==e){this._internalRoot=null;var t=e.containerInfo;oz(function(){o9(null,e,null,null)}),t[ek]=null}},s4.prototype.unstable_scheduleHydration=function(e){if(e){var t=eh;e={blockedOn:null,target:e,priority:t};for(var n=0;n<iY.length&&0!==t&&t<iY[n].priority;n++);iY.splice(n,0,e),0===n&&iJ(e)}};var s9=o.Dispatcher;o.Events=[eN,e_,eL,tc,tf,oC];var ce={findFiberByHostInstance:eP,bundleType:0,version:"18.3.0-canary-16d053d59-20230506",rendererPackageName:"react-dom"},ct={bundleType:ce.bundleType,version:ce.version,rendererPackageName:ce.rendererPackageName,rendererConfig:ce.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:s.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return null===(e=tm(e))?null:e.stateNode},findFiberByHostInstance:ce.findFiberByHostInstance||function(){return null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.0-canary-16d053d59-20230506"};if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var cn=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!cn.isDisabled&&cn.supportsFiber)try{J=cn.inject(ct),ee=cn}catch(e){}}t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=o,t.createPortal=function(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!s8(t))throw Error(i(200));return function(e,t,n){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:g,key:null==r?null:""+r,children:e,containerInfo:t,implementation:null}}(e,t,null,n)},t.createRoot=function(e,t){if(!s8(e))throw Error(i(299));var n=!1,r="",l=s2;return null!=t&&(!0===t.unstable_strictMode&&(n=!0),void 0!==t.identifierPrefix&&(r=t.identifierPrefix),void 0!==t.onRecoverableError&&(l=t.onRecoverableError)),t=o6(e,1,!1,null,null,n,!1,r,l),e[ek]=t.current,s1.current=sO,se(8===e.nodeType?e.parentNode:e),new s3(t)},t.findDOMNode=function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=e._reactInternals;if(void 0===t){if("function"==typeof e.render)throw Error(i(188));throw Error(i(268,e=Object.keys(e).join(",")))}return e=null===(e=tm(t))?null:e.stateNode},t.flushSync=function(e){return oz(e)},t.hydrate=function(e,t,n){if(!s6(t))throw Error(i(200));return s7(null,e,t,!0,n)},t.hydrateRoot=function(e,t,n){if(!s8(e))throw Error(i(405));var r=null!=n&&n.hydratedSources||null,l=!1,a="",o=s2;if(null!=n&&(!0===n.unstable_strictMode&&(l=!0),void 0!==n.identifierPrefix&&(a=n.identifierPrefix),void 0!==n.onRecoverableError&&(o=n.onRecoverableError)),t=o7(t,null,e,1,null!=n?n:null,l,!1,a,o),e[ek]=t.current,s1.current=sO,se(e),r)for(e=0;e<r.length;e++)l=(l=(n=r[e])._getVersion)(n._source),null==t.mutableSourceEagerHydrationData?t.mutableSourceEagerHydrationData=[n,l]:t.mutableSourceEagerHydrationData.push(n,l);return new s4(t)},t.preconnect=function(e,t){var n=s9.current;n&&n.preconnect(e,t)},t.prefetchDNS=function(e){var t=s9.current;t&&t.prefetchDNS(e)},t.preinit=function(e,t){var n=s9.current;n&&n.preinit(e,t)},t.preload=function(e,t){var n=s9.current;n&&n.preload(e,t)},t.render=function(e,t,n){if(!s6(t))throw Error(i(200));return s7(null,e,t,!1,n)},t.unmountComponentAtNode=function(e){if(!s6(e))throw Error(i(40));return!!e._reactRootContainer&&(oz(function(){s7(null,null,e,!1,function(){e._reactRootContainer=null,e[ek]=null})}),!0)},t.unstable_batchedUpdates=oC,t.unstable_renderSubtreeIntoContainer=function(e,t,n,r){if(!s6(n))throw Error(i(200));if(null==e||void 0===e._reactInternals)throw Error(i(38));return s7(e,t,n,!1,r)},t.version="18.3.0-canary-16d053d59-20230506"}}]); \ No newline at end of file diff --git a/.next/static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js b/.next/static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js deleted file mode 100644 index b581512..0000000 --- a/.next/static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[267],{7104:function(e,t,s){s.d(t,{Kj:function(){return w},gW:function(){return P}});var i=s(6702),r=s(3636),a=s(5754),n=s(8772),o=s(9357),l=s(7419),h=s(6438),d=s(1823),c=s(6762),u=s(9747),f=s(7620),g=s(3795),_=s(1397),m=s(1572),I=s(1813),M=s(1870),p=s(5816),v=s(199),D=s(6816),y=s(7694),b=s(9678),S=s(4620),x=s(176),B=s(8675);class P{}class A{constructor(){this.visibleInstances={},this.batchCache=new O,this.batchCacheReplacementModeInFrozenMode=new O,this.instancesBufferSize=2048}}class O{constructor(){this.mustReturn=!1,this.visibleInstances=[],this.renderSelf=[],this.hardwareInstancedRendering=[]}}class C{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class F{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=[],this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class w extends m.x{static _GetDefaultSideOrientation(e){return e||w.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(f.o.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(f.o.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new i.y$),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new i.y$),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new i.y$),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new i.y$),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new i.y$),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){var e;return(null!==(e=this._thinInstanceDataStorage.instancesCount)&&void 0!==e?e:0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,s=null,r=null,o,l=!0){if(super(e,t),this._internalMeshDataInfo=new F,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new A,this._thinInstanceDataStorage=new C,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=w.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,s)=>{e&&s&&(this._uniformBuffer?this.transferToEffect(t):s.bindOnlyWorldMatrix(t))},r){if(r._geometry&&r._geometry.applyToMesh(this),a.j.DeepCopy(r,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=r,t.useClonedMeshMap&&(r._internalMeshDataInfo.meshMap||(r._internalMeshDataInfo.meshMap={}),r._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=r._originalBuilderSideOrientation,this._creationDataStorage=r._creationDataStorage,r._ranges){let e=r._ranges;for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(r.metadata&&r.metadata.clone?this.metadata=r.metadata.clone():this.metadata=r.metadata,this._internalMetadata=r._internalMetadata,n.$&&n.$.HasTags(r)&&n.$.AddTagsTo(this,n.$.GetTags(r,!0)),this.setEnabled(r.isEnabled(!1)),this.parent=r.parent,this.setPivotMatrix(r.getPivotMatrix()),this.id=e+"."+r.id,this.material=r.material,!o){let t=r.getDescendants(!0);for(let s=0;s<t.length;s++){let i=t[s];i.clone&&i.clone(e+"."+i.name,this)}}if(r.morphTargetManager&&(this.morphTargetManager=r.morphTargetManager),t.getPhysicsEngine){let e=t.getPhysicsEngine();if(l&&e){if(1===e.getPluginVersion()){let t=e.getImpostorForPhysicsObject(r);t&&(this.physicsImpostor=t.clone(this))}else 2===e.getPluginVersion()&&r.physicsBody&&r.physicsBody.clone(this)}}for(let e=0;e<t.particleSystems.length;e++){let s=t.particleSystems[e];s.emitter===r&&s.clone(s.name,this)}this.skeleton=r.skeleton,this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}null!==s&&(this.parent=s),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=e=>{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new i.y$(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,s){let i=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));for(let r of(i.parent=e||this.parent,i.position=this.position.clone(),i.scaling=this.scaling.clone(),this.rotationQuaternion?i.rotationQuaternion=this.rotationQuaternion.clone():i.rotation=this.rotation.clone(),s&&s(this,i),this.getChildTransformNodes(!0)))"InstancedMesh"===r.getClassName()&&"Mesh"===i.getClassName()&&r.sourceMesh===this?r.instantiateHierarchy(i,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:i},s):r.instantiateHierarchy(i,t,s);return i}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices()+", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let s=0;s<this.animations.length;s++)t+=", animation[0]: "+this.animations[s].toString(e);if(e){if(this._geometry){let e=this.getIndices(),s=this.getVerticesData(f.o.PositionKind);s&&e&&(t+=", flat shading: "+(s.length/3===e.length?"YES":"NO"))}else t+=", flat shading: UNKNOWN"}return t}_unBindEffect(){for(let e of(super._unBindEffect(),this.instances))e._unBindEffect()}get hasLODLevels(){return this._internalMeshDataInfo._LODLevels.length>0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){let e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,s)=>t.distanceOrScreenCoverage<s.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>s.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return y.Y.Warn("You cannot use a mesh as LOD level twice"),this;let s=new B.g(e,t);return this._internalMeshDataInfo._LODLevels.push(s),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){let t=this._internalMeshDataInfo;for(let s=0;s<t._LODLevels.length;s++){let i=t._LODLevels[s];if(i.distanceOrScreenCoverage===e)return i.mesh}return null}removeLODLevel(e){let t=this._internalMeshDataInfo;for(let s=0;s<t._LODLevels.length;s++)t._LODLevels[s].mesh===e&&(t._LODLevels.splice(s,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){let s=this._internalMeshDataInfo;if(!s._LODLevels||0===s._LODLevels.length)return this;let i=t||this.getBoundingInfo().boundingSphere,r=e.mode===l.V.ORTHOGRAPHIC_CAMERA?e.minZ:i.centerWorld.subtract(e.globalPosition).length(),a=r,n=1;if(s._useLODScreenCoverage){let t=e.screenArea,s=i.radiusWorld*e.minZ/r;a=(s=s*s*Math.PI)/t,n=-1}if(n*s._LODLevels[s._LODLevels.length-1].distanceOrScreenCoverage>n*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let e=0;e<s._LODLevels.length;e++){let t=s._LODLevels[e];if(n*t.distanceOrScreenCoverage<n*a){if(t.mesh){if(4===t.mesh.delayLoadState)return t.mesh._checkDelayState(),this;if(2===t.mesh.delayLoadState)return this;t.mesh._preActivate(),t.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,t.mesh),t.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return null===this._geometry||void 0===this._geometry?0:this._geometry.getTotalVertices()}getVerticesData(e,t,s,i){var r,a;if(!this._geometry)return null;let n=i?void 0:null===(a=null===(r=this._userInstancedBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])||void 0===a?void 0:a.getFloatData(this.instances.length+1,s||t&&1!==this._geometry.meshes.length);return n||(n=this._geometry.getVerticesData(e,t,s)),n}getVertexBuffer(e,t){var s,i;return this._geometry?null!==(i=t?void 0:null===(s=this._userInstancedBuffersStorage)||void 0===s?void 0:s.vertexBuffers[e])&&void 0!==i?i:this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){var s;return this._geometry?!t&&(null===(s=this._userInstancedBuffersStorage)||void 0===s?void 0:s.vertexBuffers[e])!==void 0||this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}isVertexBufferUpdatable(e,t){var s;if(!this._geometry)return!!this._delayInfo&&-1!==this._delayInfo.indexOf(e);if(!t){let t=null===(s=this._userInstancedBuffersStorage)||void 0===s?void 0:s.vertexBuffers[e];if(t)return t.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){let e=[];return this._delayInfo&&this._delayInfo.forEach(function(t){e.push(t)}),e}let t=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(let e in this._userInstancedBuffersStorage.vertexBuffers)-1===t.indexOf(e)&&t.push(e);return t}getTotalIndices(){return this._geometry?this._geometry.getTotalIndices():0}getIndices(e,t){return this._geometry?this._geometry.getIndices(e,t):[]}get isBlocked(){return null!==this._masterMesh&&void 0!==this._masterMesh}isReady(e=!1,t=!1){var s,i,r,a,n,o,l;if(2===this.delayLoadState||!super.isReady(e))return!1;if(!this.subMeshes||0===this.subMeshes.length||!e)return!0;let h=this.getEngine(),d=this.getScene(),c=t||h.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();let u=this.material||d.defaultMaterial;if(u){if(u._storeEffectOnSubMeshes)for(let e of this.subMeshes){let t=e.getMaterial();if(t){if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,c))return!1}else if(!t.isReady(this,c))return!1}}else if(!u.isReady(this,c))return!1}let f=h.currentRenderPassId;for(let e of this.lightSources){let t=e.getShadowGenerators();if(!t)continue;let d=t.values();for(let e=d.next();!0!==e.done;e=d.next()){let t=e.value;if(t&&(!(null===(s=t.getShadowMap())||void 0===s?void 0:s.renderList)||(null===(i=t.getShadowMap())||void 0===i?void 0:i.renderList)&&(null===(a=null===(r=t.getShadowMap())||void 0===r?void 0:r.renderList)||void 0===a?void 0:a.indexOf(this))!==-1)){let e=t.getShadowMap(),s=null!==(n=e.renderPassIds)&&void 0!==n?n:[h.currentRenderPassId];for(let e=0;e<s.length;++e)for(let i of(h.currentRenderPassId=s[e],this.subMeshes))if(!t.isReady(i,c,null!==(l=null===(o=i.getMaterial())||void 0===o?void 0:o.needAlphaBlendingForMesh(this))&&void 0!==l&&l))return h.currentRenderPassId=f,!1;h.currentRenderPassId=f}}}for(let e of this._internalMeshDataInfo._LODLevels)if(e.mesh&&!e.mesh.isReady(c))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_preActivate(){let e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t||(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null),this}_preActivateForIntermediateRendering(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(void 0!==this._instanceDataStorage.previousRenderId&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=t,this._instanceDataStorage.visibleInstances[t]=[]),this._instanceDataStorage.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let s=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getPositionData(e,t),s),this}_createGlobalSubMesh(e){let t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){let s=this.getIndices();if(!s)return null;let i=s.length,r=!1;if(e)r=!0;else for(let e of this.subMeshes)if(e.indexStart+e.indexCount>i||e.verticesStart+e.verticesCount>t){r=!0;break}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new I.P(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;let t=this.getTotalIndices(),s=t/e|0,i=0;for(;s%3!=0;)s++;this.releaseSubMeshes();for(let r=0;r<e&&!(i>=t);r++)I.P.CreateFromIndices(0,i,r===e-1?t-i:s,this,void 0,!1),i+=s;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,s=!1,i){if(this._geometry)this._geometry.setVerticesData(e,t,s,i);else{let i=new g.x;i.set(t,e);let r=this.getScene();new _.Z(_.Z.RandomId(),r,i,s,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){let s=this.getVertexBuffer(e);s&&s.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=_.Z.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,s,i){return this._geometry&&(i?(this.makeGeometryUnique(),this.updateVerticesData(e,t,s,!1)):this._geometry.updateVerticesData(e,t,s)),this}updateMeshPositions(e,t=!0){let s=this.getVerticesData(f.o.PositionKind);if(!s)return this;if(e(s),this.updateVerticesData(f.o.PositionKind,s,!1,!1),t){let e=this.getIndices(),t=this.getVerticesData(f.o.NormalKind);if(!t)return this;g.x.ComputeNormals(s,e,t),this.updateVerticesData(f.o.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry||1===this._geometry.meshes.length)return this;let e=this._geometry,t=this._geometry.copy(_.Z.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndices(e,t=null,s=!1){if(this._geometry)this._geometry.setIndices(e,t,s);else{let t=new g.x;t.indices=e;let i=this.getScene();new _.Z(_.Z.RandomId(),i,t,s,this)}return this}updateIndices(e,t,s=!1){return this._geometry&&this._geometry.updateIndices(e,t,s),this}toLeftHanded(){return this._geometry&&this._geometry.toLeftHanded(),this}_bind(e,t,s,i=!0){let r;if(!this._geometry)return this;let a=this.getScene().getEngine();if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)r=null;else switch(this._getRenderingFillMode(s)){case M.F.PointFillMode:r=null;break;case M.F.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),a);break;default:case M.F.TriangleFillMode:r=this._geometry.getIndexBuffer()}return i&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,r,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,r),this}_draw(e,t,s){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);let i=this.getScene(),r=i.getEngine();return this._unIndexed||t==M.F.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||s):t==M.F.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||s):r.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||s),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}let s=this.getScene(),i=s._isInIntermediateRendering(),r=i?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=this._instanceDataStorage.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){let t=this._instanceDataStorage.visibleInstances,r=s.getRenderId(),n=i?t.intermediateDefaultRenderId:t.defaultRenderId;a.visibleInstances[e]=t[r],!a.visibleInstances[e]&&n&&(a.visibleInstances[e]=t[n])}return a.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==a.visibleInstances[e]&&void 0!==a.visibleInstances[e],this._instanceDataStorage.previousBatch=a,a}_renderWithInstances(e,t,s,i,r){var a;let n=s.visibleInstances[e._id],o=n?n.length:0,l=this._instanceDataStorage,h=l.instancesBufferSize,c=l.instancesBuffer,u=l.instancesPreviousBuffer,g=64*(o+1);for(;l.instancesBufferSize<g;)l.instancesBufferSize*=2;l.instancesData&&h==l.instancesBufferSize||(l.instancesData=new Float32Array(l.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!l.instancesPreviousData||h!=l.instancesBufferSize)&&(l.instancesPreviousData=new Float32Array(l.instancesBufferSize/4));let _=0,m=0,I=s.renderSelf[e._id],M=!c||h!==l.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!l.instancesPreviousBuffer;if(this._instanceDataStorage.manualUpdate||l.isFrozen&&!M)m=(I?1:0)+o;else{let t=this.getWorldMatrix();if(I&&(this._scene.needsPreviousWorldMatrices&&(l.masterMeshPreviousWorldMatrix?(l.masterMeshPreviousWorldMatrix.copyToArray(l.instancesPreviousData,_),l.masterMeshPreviousWorldMatrix.copyFrom(t)):(l.masterMeshPreviousWorldMatrix=t.clone(),l.masterMeshPreviousWorldMatrix.copyToArray(l.instancesPreviousData,_))),t.copyToArray(l.instancesData,_),_+=16,m++),n){if(w.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&(null===(a=e.getMaterial())||void 0===a?void 0:a.needAlphaBlendingForMesh(e.getRenderingMesh()))){let e=this._scene.activeCamera.globalPosition;for(let t=0;t<n.length;t++){let s=n[t];s._distanceToCamera=d.P.Distance(s.getBoundingInfo().boundingSphere.centerWorld,e)}n.sort((e,t)=>e._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera<t._distanceToCamera?1:0)}for(let e=0;e<n.length;e++){let t=n[e],s=t.getWorldMatrix();s.copyToArray(l.instancesData,_),this._scene.needsPreviousWorldMatrices&&(t._previousWorldMatrix?(t._previousWorldMatrix.copyToArray(l.instancesPreviousData,_),t._previousWorldMatrix.copyFrom(s)):(t._previousWorldMatrix=s.clone(),t._previousWorldMatrix.copyToArray(l.instancesPreviousData,_))),_+=16,m++}}}return M?(c&&c.dispose(),u&&u.dispose(),c=new f.l(r,l.instancesData,!0,16,!1,!0),l.instancesBuffer=c,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=c.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=c.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=c.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=c.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(u=new f.l(r,l.instancesPreviousData,!0,16,!1,!0),l.instancesPreviousBuffer=u,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=u.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=u.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=u.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=u.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&(c.updateDirectly(l.instancesData,0,m),this._scene.needsPreviousWorldMatrices&&(!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.previousManualUpdate)&&u.updateDirectly(l.instancesPreviousData,0,m)),this._processInstancedBuffers(n,I),this.getScene()._activeIndices.addCount(e.indexCount*m,!1),r._currentDrawContext&&(r._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,m),this._scene.needsPreviousWorldMatrices&&!M&&this._instanceDataStorage.manualUpdate&&(!this._instanceDataStorage.isFrozen||this._instanceDataStorage.forceMatrixUpdates)&&!this._instanceDataStorage.previousManualUpdate&&u.updateDirectly(l.instancesData,0,m),r.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,s,i){var r,a;let n=null!==(a=null===(r=this._thinInstanceDataStorage)||void 0===r?void 0:r.instancesCount)&&void 0!==a?a:0;this.getScene()._activeIndices.addCount(e.indexCount*n,!1),i._currentDrawContext&&(i._currentDrawContext.useInstancing=!0),this._bind(e,s,t),this._draw(e,t,n),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,n):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),i.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,s,i,r,a,n,o){let l=this.getScene(),h=l.getEngine();if(i=this._getRenderingFillMode(i),a&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,i,s,h),this;if(a)this._renderWithInstances(t,i,r,s,h);else{h._currentDrawContext&&(h._currentDrawContext.useInstancing=!1);let s=0;r.renderSelf[t._id]&&(n&&n(!1,e.getWorldMatrix(),o),s++,this._draw(t,i,this._instanceDataStorage.overridenInstanceCount));let a=r.visibleInstances[t._id];if(a){let e=a.length;s+=e;for(let s=0;s<e;s++){let e=a[s],r=e.getWorldMatrix();n&&n(!0,r,o),this._draw(t,i)}}l._activeIndices.addCount(t.indexCount*s,!1)}return this}_rebuild(e=!1){if(this._instanceDataStorage.instancesBuffer&&(e&&this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),this._userInstancedBuffersStorage){for(let t in this._userInstancedBuffersStorage.vertexBuffers){let s=this._userInstancedBuffersStorage.vertexBuffers[t];s&&(e&&s.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(e)}_freeze(){if(this.subMeshes){for(let e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}}_unFreeze(){this._instanceDataStorage.isFrozen=!1,this._instanceDataStorage.previousBatch=null}render(e,t,s){var i,r,a;let n,o;let l=this.getScene();if(this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1,this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;let d=this._getInstancesRenderList(e._id,!!s);if(d.mustReturn||!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let c=l.getEngine(),u=0,f=null;this.ignoreCameraMaxZ&&l.activeCamera&&!l._isInIntermediateRendering()&&(u=l.activeCamera.maxZ,f=l.activeCamera,l.activeCamera.maxZ=0,l.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);let g=e.getRenderingMesh(),_=d.hardwareInstancedRendering[e._id]||g.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,m=this._instanceDataStorage,I=e.getMaterial();if(!I)return f&&(f.maxZ=u,l.updateTransformMatrix(!0)),this;if(m.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===I){if(I._storeEffectOnSubMeshes&&!(null===(i=e.effect)||void 0===i?void 0:i._wasPreviouslyReady)||!I._storeEffectOnSubMeshes&&!(null===(r=I.getEffect())||void 0===r?void 0:r._wasPreviouslyReady))return f&&(f.maxZ=u,l.updateTransformMatrix(!0)),this}else{if(I._storeEffectOnSubMeshes){if(!I.isReadyForSubMesh(this,e,_))return f&&(f.maxZ=u,l.updateTransformMatrix(!0)),this}else if(!I.isReady(this,_))return f&&(f.maxZ=u,l.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=I}t&&c.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),n=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();let p=null!==(a=null==n?void 0:n.effect)&&void 0!==a?a:null;for(let t of l._beforeRenderingMeshStage)t.action(this,e,d,p);if(!n||!p)return f&&(f.maxZ=u,l.updateTransformMatrix(!0)),this;let v=s||this;if(!m.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||null!==this.overrideMaterialSideOrientation)){let e=v._getWorldMatrixDeterminant();null==(o=this.overrideMaterialSideOrientation)&&(o=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(o=o===M.F.ClockWiseSideOrientation?M.F.CounterClockWiseSideOrientation:M.F.ClockWiseSideOrientation),m.sideOrientation=o}else o=m.sideOrientation;let D=this._internalMeshDataInfo._effectiveMaterial._preBind(n,o);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&c.setDepthWrite(!0);let y=this._internalMeshDataInfo._effectiveMaterial,b=y.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),_||this._bind(e,p,b,!1);let S=v.getWorldMatrix();for(let t of(y._storeEffectOnSubMeshes?y.bindForSubMesh(S,this,e):y.bind(S,this),!y.backFaceCulling&&y.separateCullingPass&&(c.setState(!0,y.zOffset,!1,!D,y.cullBackFaces,y.stencil,y.zOffsetUnits),this._processRendering(this,e,p,b,d,_,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),c.setState(!0,y.zOffset,!1,D,y.cullBackFaces,y.stencil,y.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,p,b,d,_,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind(),l._afterRenderingMeshStage))t.action(this,e,d,p);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),f&&(f.maxZ=u,l.updateTransformMatrix(!0)),l.performancePriority!==h.a.Aggressive||m.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(f.o.MatricesWeightsKind)&&(this.isVerticesDataPresent(f.o.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){let e=this.getVerticesData(f.o.MatricesWeightsKind),t=e.length;for(let s=0;s<t;s+=4){let t=e[s]+e[s+1]+e[s+2]+e[s+3];if(0===t)e[s]=1;else{let i=1/t;e[s]*=i,e[s+1]*=i,e[s+2]*=i,e[s+3]*=i}}this.setVerticesData(f.o.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){let e=this.getVerticesData(f.o.MatricesWeightsExtraKind),t=this.getVerticesData(f.o.MatricesWeightsKind),s=t.length;for(let i=0;i<s;i+=4){let s=t[i]+t[i+1]+t[i+2]+t[i+3];if(0===(s+=e[i]+e[i+1]+e[i+2]+e[i+3]))t[i]=1;else{let r=1/s;t[i]*=r,t[i+1]*=r,t[i+2]*=r,t[i+3]*=r,e[i]*=r,e[i+1]*=r,e[i+2]*=r,e[i+3]*=r}}this.setVerticesData(f.o.MatricesWeightsKind,t),this.setVerticesData(f.o.MatricesWeightsKind,e)}validateSkinning(){let e=this.getVerticesData(f.o.MatricesWeightsExtraKind),t=this.getVerticesData(f.o.MatricesWeightsKind);if(null===t||null==this.skeleton)return{skinned:!1,valid:!0,report:"not skinned"};let s=t.length,i=0,r=0,a=0,n=0,o=null===e?4:8,l=[];for(let e=0;e<=o;e++)l[e]=0;for(let h=0;h<s;h+=4){let s=t[h],d=s,c=0===d?0:1;for(let r=1;r<o;r++){let a=r<4?t[h+r]:e[h+r-4];a>s&&i++,0!==a&&c++,d+=a,s=a}if(l[c]++,c>a&&(a=c),0===d)r++;else{let s=1/d,i=0;for(let r=0;r<o;r++)r<4?i+=Math.abs(t[h+r]-t[h+r]*s):i+=Math.abs(e[h+r-4]-e[h+r-4]*s);i>.001&&n++}}let h=this.skeleton.bones.length,d=this.getVerticesData(f.o.MatricesIndicesKind),c=this.getVerticesData(f.o.MatricesIndicesExtraKind),u=0;for(let e=0;e<s;e+=4)for(let t=0;t<o;t++){let s=t<4?d[e+t]:c[e+t-4];(s>=h||s<0)&&u++}let g="Number of Weights = "+s/4+"\nMaximum influences = "+a+"\nMissing Weights = "+r+"\nNot Sorted = "+i+"\nNot Normalized = "+n+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+u;return{skinned:!0,valid:0===r&&0===n&&0===u,report:g}}_checkDelayState(){let e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);let t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return r.w1.LoadFile(this.delayLoadingFile,t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach(e=>{e.refreshBoundingInfo(),e._syncSubMeshes()}),this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return!!(2!==this.delayLoadState&&super.isInFrustum(e))&&(this._checkDelayState(),!0)}setMaterialById(e){let t;let s=this.getScene().materials;for(t=s.length-1;t>-1;t--)if(s[t].id===e)return this.material=s[t],this;let i=this.getScene().multiMaterials;for(t=i.length-1;t>-1;t--)if(i[t].id===e){this.material=i[t];break}return this}getAnimatables(){let e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){let t;if(!this.isVerticesDataPresent(f.o.PositionKind))return this;let s=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(f.o.PositionKind),r=d.P.Zero();for(t=0;t<i.length;t+=3)d.P.TransformCoordinatesFromFloatsToRef(i[t],i[t+1],i[t+2],e,r).toArray(i,t);if(this.setVerticesData(f.o.PositionKind,i,this.getVertexBuffer(f.o.PositionKind).isUpdatable()),this.isVerticesDataPresent(f.o.NormalKind)){for(t=0,i=this.getVerticesData(f.o.NormalKind);t<i.length;t+=3)d.P.TransformNormalFromFloatsToRef(i[t],i[t+1],i[t+2],e,r).normalize().toArray(i,t);this.setVerticesData(f.o.NormalKind,i,this.getVertexBuffer(f.o.NormalKind).isUpdatable())}return 0>e.determinant()&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=s,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions?this._internalAbstractMeshDataInfo._positions:this._geometry?this._geometry._positions:null}_resetPointsArrayCache(){return this._geometry&&this._geometry._resetPointsArrayCache(),this}_generatePointsArray(){return!!this._geometry&&this._geometry._generatePointsArray()}clone(e="",t=null,s,i=!0){return new w(e,this.getScene(),t,this,s,i)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);let s=this._internalMeshDataInfo;if(s._onBeforeDrawObservable&&s._onBeforeDrawObservable.clear(),s._onBeforeBindObservable&&s._onBeforeBindObservable.clear(),s._onBeforeRenderObservable&&s._onBeforeRenderObservable.clear(),s._onAfterRenderObservable&&s._onAfterRenderObservable.clear(),s._onBetweenPassObservable&&s._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(s.meshMap)for(let e in s.meshMap){let t=s.meshMap[e];t&&(t._internalMeshDataInfo._source=null,s.meshMap[e]=void 0)}s._source&&s._source._internalMeshDataInfo.meshMap&&(s._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{let e=this.getScene().meshes;for(let t of e){let e=t;e._internalMeshDataInfo&&e._internalMeshDataInfo._source&&e._internalMeshDataInfo._source===this&&(e._internalMeshDataInfo._source=null)}}s._source=null,this._instanceDataStorage.visibleInstances={},this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,s,i,a,n,o=!1){let l=this.getScene();return r.w1.LoadImage(e,e=>{let r=e.width,l=e.height,h=this.getEngine().createCanvas(r,l),d=h.getContext("2d");d.drawImage(e,0,0);let c=d.getImageData(0,0,r,l).data;this.applyDisplacementMapFromBuffer(c,r,l,t,s,a,n,o),i&&i(this)},()=>{},l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,s,i,r,a,n,o=!1){if(!this.isVerticesDataPresent(f.o.PositionKind)||!this.isVerticesDataPresent(f.o.NormalKind)||!this.isVerticesDataPresent(f.o.UVKind))return y.Y.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;let l=this.getVerticesData(f.o.PositionKind,!0,!0),h=this.getVerticesData(f.o.NormalKind),c=this.getVerticesData(f.o.UVKind),u=d.P.Zero(),_=d.P.Zero(),m=d.FM.Zero();a=a||d.FM.Zero(),n=n||new d.FM(1,1);for(let o=0;o<l.length;o+=3){d.P.FromArrayToRef(l,o,u),d.P.FromArrayToRef(h,o,_),d.FM.FromArrayToRef(c,o/3*2,m);let f=Math.abs(m.x*n.x+a.x%1)*(t-1)%t|0,g=Math.abs(m.y*n.y+a.y%1)*(s-1)%s|0,I=(f+g*t)*4,M=e[I]/255,p=e[I+1]/255,v=e[I+2]/255,D=.3*M+.59*p+.11*v;_.normalize(),_.scaleInPlace(i+(r-i)*D),(u=u.add(_)).toArray(l,o)}return g.x.ComputeNormals(l,this.getIndices(),h),o?(this.setVerticesData(f.o.PositionKind,l),this.setVerticesData(f.o.NormalKind,h),this.setVerticesData(f.o.UVKind,c)):(this.updateVerticesData(f.o.PositionKind,l),this.updateVerticesData(f.o.NormalKind,h)),this}_getFlattenedNormals(e,t){let s=new Float32Array(3*e.length),i=0,r=this.overrideMaterialSideOrientation===(this._scene.useRightHandedSystem?1:0);for(let a=0;a<e.length;a+=3){let n=d.P.FromArray(t,3*e[a]),o=d.P.FromArray(t,3*e[a+1]),l=d.P.FromArray(t,3*e[a+2]),h=n.subtract(o),c=l.subtract(o),u=d.P.Normalize(d.P.Cross(h,c));r&&u.scaleInPlace(-1);for(let e=0;e<3;e++)s[i++]=u.x,s[i++]=u.y,s[i++]=u.z}return s}_convertToUnIndexedMesh(e=!1){let t=this.getVerticesDataKinds(),s=this.getIndices(),i={},r=(e,t)=>{let i=new Float32Array(s.length*t),r=0;for(let a=0;a<s.length;a++)for(let n=0;n<t;n++)i[r++]=e[s[a]*t+n];return i},a=this.geometry?this.subMeshes.slice(0):[];for(let e of t)i[e]=this.getVerticesData(e);for(let a of t){let t=this.getVertexBuffer(a),n=t.getStrideSize();if(e&&a===f.o.NormalKind){let e=this._getFlattenedNormals(s,i[f.o.PositionKind]);this.setVerticesData(f.o.NormalKind,e,t.isUpdatable(),n)}else this.setVerticesData(a,r(i[a],n),t.isUpdatable(),n)}if(this.morphTargetManager){for(let t=0;t<this.morphTargetManager.numTargets;t++){let i=this.morphTargetManager.getTarget(t),a=i.getPositions();i.setPositions(r(a,3));let n=i.getNormals();n&&i.setNormals(e?this._getFlattenedNormals(s,a):r(n,3));let o=i.getTangents();o&&i.setTangents(r(o,3));let l=i.getUVs();l&&i.setUVs(r(l,2))}this.morphTargetManager.synchronize()}for(let e=0;e<s.length;e++)s[e]=e;for(let e of(this.setIndices(s),this._unIndexed=!0,this.releaseSubMeshes(),a))I.P.AddToMesh(e.materialIndex,e.indexStart,e.indexCount,e.indexStart,e.indexCount,this);return this.synchronizeInstances(),this}convertToFlatShadedMesh(){return this._convertToUnIndexedMesh(!0)}convertToUnIndexedMesh(){return this._convertToUnIndexedMesh()}flipFaces(e=!1){let t;let s=g.x.ExtractFromMesh(this);if(e&&this.isVerticesDataPresent(f.o.NormalKind)&&s.normals)for(t=0;t<s.normals.length;t++)s.normals[t]*=-1;if(s.indices){let e;for(t=0;t<s.indices.length;t+=3)e=s.indices[t+1],s.indices[t+1]=s.indices[t+2],s.indices[t+2]=e}return s.applyToMesh(this,this.isVertexBufferUpdatable(f.o.PositionKind)),this}increaseVertices(e=1){let t=g.x.ExtractFromMesh(this),s=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,i=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,r=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,a=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(s&&i){let n,o,l,h,c;t.indices=s,t.positions=i,r&&(t.uvs=r),a&&(t.normals=a);let u=e+1,g=[];for(let e=0;e<u+1;e++)g[e]=[];let _=new d.P(0,0,0),m=new d.P(0,0,0),I=new d.FM(0,0),M=[],p=[],v=[],D=i.length;r&&(h=r.length),a&&(c=a.length);for(let e=0;e<s.length;e+=3){p[0]=s[e],p[1]=s[e+1],p[2]=s[e+2];for(let e=0;e<3;e++)if(n=p[e],o=p[(e+1)%3],void 0===v[n]&&void 0===v[o]?(v[n]=[],v[o]=[]):(void 0===v[n]&&(v[n]=[]),void 0===v[o]&&(v[o]=[])),void 0===v[n][o]&&void 0===v[o][n]){v[n][o]=[],_.x=(i[3*o]-i[3*n])/u,_.y=(i[3*o+1]-i[3*n+1])/u,_.z=(i[3*o+2]-i[3*n+2])/u,a&&(m.x=(a[3*o]-a[3*n])/u,m.y=(a[3*o+1]-a[3*n+1])/u,m.z=(a[3*o+2]-a[3*n+2])/u),r&&(I.x=(r[2*o]-r[2*n])/u,I.y=(r[2*o+1]-r[2*n+1])/u),v[n][o].push(n);for(let e=1;e<u;e++)v[n][o].push(i.length/3),i[D++]=i[3*n]+e*_.x,i[D++]=i[3*n+1]+e*_.y,i[D++]=i[3*n+2]+e*_.z,a&&(a[c++]=a[3*n]+e*m.x,a[c++]=a[3*n+1]+e*m.y,a[c++]=a[3*n+2]+e*m.z),r&&(r[h++]=r[2*n]+e*I.x,r[h++]=r[2*n+1]+e*I.y);v[n][o].push(o),v[o][n]=[],l=v[n][o].length;for(let e=0;e<l;e++)v[o][n][e]=v[n][o][l-1-e]}g[0][0]=s[e],g[1][0]=v[s[e]][s[e+1]][1],g[1][1]=v[s[e]][s[e+2]][1];for(let t=2;t<u;t++){g[t][0]=v[s[e]][s[e+1]][t],g[t][t]=v[s[e]][s[e+2]][t],_.x=(i[3*g[t][t]]-i[3*g[t][0]])/t,_.y=(i[3*g[t][t]+1]-i[3*g[t][0]+1])/t,_.z=(i[3*g[t][t]+2]-i[3*g[t][0]+2])/t,a&&(m.x=(a[3*g[t][t]]-a[3*g[t][0]])/t,m.y=(a[3*g[t][t]+1]-a[3*g[t][0]+1])/t,m.z=(a[3*g[t][t]+2]-a[3*g[t][0]+2])/t),r&&(I.x=(r[2*g[t][t]]-r[2*g[t][0]])/t,I.y=(r[2*g[t][t]+1]-r[2*g[t][0]+1])/t);for(let e=1;e<t;e++)g[t][e]=i.length/3,i[D++]=i[3*g[t][0]]+e*_.x,i[D++]=i[3*g[t][0]+1]+e*_.y,i[D++]=i[3*g[t][0]+2]+e*_.z,a&&(a[c++]=a[3*g[t][0]]+e*m.x,a[c++]=a[3*g[t][0]+1]+e*m.y,a[c++]=a[3*g[t][0]+2]+e*m.z),r&&(r[h++]=r[2*g[t][0]]+e*I.x,r[h++]=r[2*g[t][0]+1]+e*I.y)}g[u]=v[s[e+1]][s[e+2]],M.push(g[0][0],g[1][0],g[1][1]);for(let e=1;e<u;e++){let t;for(t=0;t<e;t++)M.push(g[e][t],g[e+1][t],g[e+1][t+1]),M.push(g[e][t],g[e+1][t+1],g[e][t+1]);M.push(g[e][t],g[e+1][t],g[e+1][t+1])}}t.indices=M,t.applyToMesh(this,this.isVertexBufferUpdatable(f.o.PositionKind))}else y.Y.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions")}forceSharedVertices(){let e=g.x.ExtractFromMesh(this),t=e.uvs,s=e.indices,i=e.positions,r=e.colors,a=e.matricesIndices,n=e.matricesWeights,o=e.matricesIndicesExtra,l=e.matricesWeightsExtra;if(void 0===s||void 0===i||null===s||null===i)y.Y.Warn("VertexData contains empty entries");else{let h,d;let c=[],u=[],_=[],m=[],I=[],M=[],p=[],v=[],D=[],y=0,b={};for(let e=0;e<s.length;e+=3){d=[s[e],s[e+1],s[e+2]],D=[];for(let e=0;e<3;e++){D[e]="";for(let t=0;t<3;t++)1e-8>Math.abs(i[3*d[e]+t])&&(i[3*d[e]+t]=0),D[e]+=i[3*d[e]+t]+"|"}if(!(D[0]==D[1]||D[0]==D[2]||D[1]==D[2]))for(let e=0;e<3;e++){if(void 0===(h=b[D[e]])){b[D[e]]=y,h=y++;for(let t=0;t<3;t++)c.push(i[3*d[e]+t]);if(null!=r)for(let t=0;t<4;t++)m.push(r[4*d[e]+t]);if(null!=t)for(let s=0;s<2;s++)_.push(t[2*d[e]+s]);if(null!=a)for(let t=0;t<4;t++)I.push(a[4*d[e]+t]);if(null!=n)for(let t=0;t<4;t++)M.push(n[4*d[e]+t]);if(null!=o)for(let t=0;t<4;t++)p.push(o[4*d[e]+t]);if(null!=l)for(let t=0;t<4;t++)v.push(l[4*d[e]+t])}u.push(h)}}let S=[];g.x.ComputeNormals(c,u,S),e.positions=c,e.indices=u,e.normals=S,null!=t&&(e.uvs=_),null!=r&&(e.colors=m),null!=a&&(e.matricesIndices=I),null!=n&&(e.matricesWeights=M),null!=o&&(e.matricesIndicesExtra=p),null!=n&&(e.matricesWeightsExtra=v),e.applyToMesh(this,this.isVertexBufferUpdatable(f.o.PositionKind))}}static _instancedMeshFactory(e,t){throw(0,S.S)("InstancedMesh")}static _PhysicsImpostorParser(e,t,s){throw(0,S.S)("PhysicsImpostor")}createInstance(e){return w._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e<this.instances.length;e++){let t=this.instances[e];t._syncSubMeshes()}return this}optimizeIndices(e){let t=this.getIndices(),s=this.getVerticesData(f.o.PositionKind);if(!s||!t)return this;let i=[];for(let e=0;e<s.length;e+=3)i.push(d.P.FromArray(s,e));let a=[];return r.$g.SyncAsyncForLoop(i.length,40,e=>{let t=i.length-1-e,s=i[t];for(let e=0;e<t;++e){let r=i[e];if(s.equals(r)){a[t]=e;break}}},()=>{for(let e=0;e<t.length;++e)t[e]=a[t[e]]||t[e];let s=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=s,e&&e(this)}),this}serialize(e={}){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),n.$&&n.$.HasTags(this)&&(e.tags=n.$.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.checkCollisions=this.checkCollisions,e.isBlocker=this.isBlocker,e.overrideMaterialSideOrientation=this.overrideMaterialSideOrientation,this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;let t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(let t=0;t<this.subMeshes.length;t++){let s=this.subMeshes[t];e.subMeshes.push({materialIndex:s.materialIndex,verticesStart:s.verticesStart,verticesCount:s.verticesCount,indexStart:s.indexStart,indexCount:s.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(x.l.NAME_PHYSICSENGINE)){let t=this.getPhysicsImpostor();t&&(e.physicsMass=t.getParam("mass"),e.physicsFriction=t.getParam("friction"),e.physicsRestitution=t.getParam("mass"),e.physicsImpostor=t.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(let t=0;t<this.instances.length;t++){let s=this.instances[t];if(s.doNotSerialize)continue;let i={name:s.name,id:s.id,isEnabled:s.isEnabled(!1),isVisible:s.isVisible,isPickable:s.isPickable,checkCollisions:s.checkCollisions,position:s.position.asArray(),scaling:s.scaling.asArray()};if(s.parent&&s.parent._serializeAsParent(i),s.rotationQuaternion?i.rotationQuaternion=s.rotationQuaternion.asArray():s.rotation&&(i.rotation=s.rotation.asArray()),this.getScene()._getComponent(x.l.NAME_PHYSICSENGINE)){let e=s.getPhysicsImpostor();e&&(i.physicsMass=e.getParam("mass"),i.physicsFriction=e.getParam("friction"),i.physicsRestitution=e.getParam("mass"),i.physicsImpostor=e.type)}s.metadata&&(i.metadata=s.metadata),s.actionManager&&(i.actions=s.actionManager.serialize(s.name)),e.instances.push(i),D.p4.AppendSerializedAnimations(s,i),i.ranges=s.serializeAnimationRanges()}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){let t={data:{},sizes:{},strides:{}};for(let e in this._userThinInstanceBuffersStorage.data)t.data[e]=Array.from(this._userThinInstanceBuffersStorage.data[e]),t.sizes[e]=this._userThinInstanceBuffersStorage.sizes[e],t.strides[e]=this._userThinInstanceBuffersStorage.strides[e];e.thinInstances.userThinInstance=t}return D.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e}_syncGeometryWithMorphTargetManager(){if(!this.geometry)return;this._markSubMeshesAsAttributesDirty();let e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices()){y.Y.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),this.morphTargetManager=null;return}if(e.isUsingTextureForTargets)return;for(let t=0;t<e.numInfluencers;t++){let s=e.getActiveTarget(t),i=s.getPositions();if(!i){y.Y.Error("Invalid morph target. Target must have positions.");return}this.geometry.setVerticesData(f.o.PositionKind+t,i,!1,3);let r=s.getNormals();r&&this.geometry.setVerticesData(f.o.NormalKind+t,r,!1,3);let a=s.getTangents();a&&this.geometry.setVerticesData(f.o.TangentKind+t,a,!1,3);let n=s.getUVs();n&&this.geometry.setVerticesData(f.o.UVKind+"_"+t,n,!1,2)}}else{let e=0;for(;this.geometry.isVerticesDataPresent(f.o.PositionKind+e);)this.geometry.removeVerticesData(f.o.PositionKind+e),this.geometry.isVerticesDataPresent(f.o.NormalKind+e)&&this.geometry.removeVerticesData(f.o.NormalKind+e),this.geometry.isVerticesDataPresent(f.o.TangentKind+e)&&this.geometry.removeVerticesData(f.o.TangentKind+e),this.geometry.isVerticesDataPresent(f.o.UVKind+e)&&this.geometry.removeVerticesData(f.o.UVKind+"_"+e),e++}}static Parse(e,t,s){let i;if((i=e.type&&"LinesMesh"===e.type?w._LinesMeshParser(e,t):e.type&&"GroundMesh"===e.type?w._GroundMeshParser(e,t):e.type&&"GoldbergMesh"===e.type?w._GoldbergMeshParser(e,t):e.type&&"GreasedLineMesh"===e.type?w._GreasedLineMeshParser(e,t):e.type&&"TrailMesh"===e.type?w._TrailMeshParser(e,t):new w(e.name,t)).id=e.id,i._waitingParsedUniqueId=e.uniqueId,n.$&&n.$.AddTagsTo(i,e.tags),i.position=d.P.FromArray(e.position),void 0!==e.metadata&&(i.metadata=e.metadata),e.rotationQuaternion?i.rotationQuaternion=d._f.FromArray(e.rotationQuaternion):e.rotation&&(i.rotation=d.P.FromArray(e.rotation)),i.scaling=d.P.FromArray(e.scaling),e.localMatrix?i.setPreTransformMatrix(d.y3.FromArray(e.localMatrix)):e.pivotMatrix&&i.setPivotMatrix(d.y3.FromArray(e.pivotMatrix)),i.setEnabled(e.isEnabled),i.isVisible=e.isVisible,i.infiniteDistance=e.infiniteDistance,i.showBoundingBox=e.showBoundingBox,i.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,void 0!==e.applyFog&&(i.applyFog=e.applyFog),void 0!==e.pickable&&(i.isPickable=e.pickable),void 0!==e.alphaIndex&&(i.alphaIndex=e.alphaIndex),i.receiveShadows=e.receiveShadows,void 0!==e.billboardMode&&(i.billboardMode=e.billboardMode),void 0!==e.visibility&&(i.visibility=e.visibility),i.checkCollisions=e.checkCollisions,i.overrideMaterialSideOrientation=e.overrideMaterialSideOrientation,void 0!==e.isBlocker&&(i.isBlocker=e.isBlocker),i._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(i._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),void 0!==e.parentId&&(i._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(i._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.actions&&(i._waitingData.actions=e.actions),void 0!==e.overlayAlpha&&(i.overlayAlpha=e.overlayAlpha),void 0!==e.overlayColor&&(i.overlayColor=c.Wo.FromArray(e.overlayColor)),void 0!==e.renderOverlay&&(i.renderOverlay=e.renderOverlay),i.isUnIndexed=!!e.isUnIndexed,i.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(i.delayLoadState=4,i.delayLoadingFile=s+e.delayLoadingFile,i.buildBoundingInfo(d.P.FromArray(e.boundingBoxMinimum),d.P.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(i._binaryInfo=e._binaryInfo),i._delayInfo=[],e.hasUVs&&i._delayInfo.push(f.o.UVKind),e.hasUVs2&&i._delayInfo.push(f.o.UV2Kind),e.hasUVs3&&i._delayInfo.push(f.o.UV3Kind),e.hasUVs4&&i._delayInfo.push(f.o.UV4Kind),e.hasUVs5&&i._delayInfo.push(f.o.UV5Kind),e.hasUVs6&&i._delayInfo.push(f.o.UV6Kind),e.hasColors&&i._delayInfo.push(f.o.ColorKind),e.hasMatricesIndices&&i._delayInfo.push(f.o.MatricesIndicesKind),e.hasMatricesWeights&&i._delayInfo.push(f.o.MatricesWeightsKind),i._delayLoadingFunction=_.Z._ImportGeometry,v.Z.ForceFullSceneLoadingForIncremental&&i._checkDelayState()):_.Z._ImportGeometry(e,i),e.materialUniqueId?i._waitingMaterialId=e.materialUniqueId:e.materialId&&(i._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(i.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(i.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(i.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t<e.animations.length;t++){let s=e.animations[t],r=(0,b.q)("BABYLON.Animation");r&&i.animations.push(r.Parse(s))}u.N.ParseAnimationRanges(i,e,t)}if(e.autoAnimate&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?i.layerMask=Math.abs(parseInt(e.layerMask)):i.layerMask=268435455,e.physicsImpostor&&w._PhysicsImpostorParser(t,i,e),e.lodMeshIds&&(i._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let s=0;s<e.instances.length;s++){let r=e.instances[s],a=i.createInstance(r.name);if(r.id&&(a.id=r.id),n.$&&(r.tags?n.$.AddTagsTo(a,r.tags):n.$.AddTagsTo(a,e.tags)),a.position=d.P.FromArray(r.position),void 0!==r.metadata&&(a.metadata=r.metadata),void 0!==r.parentId&&(a._waitingParentId=r.parentId),void 0!==r.parentInstanceIndex&&(a._waitingParentInstanceIndex=r.parentInstanceIndex),void 0!==r.isEnabled&&null!==r.isEnabled&&a.setEnabled(r.isEnabled),void 0!==r.isVisible&&null!==r.isVisible&&(a.isVisible=r.isVisible),void 0!==r.isPickable&&null!==r.isPickable&&(a.isPickable=r.isPickable),r.rotationQuaternion?a.rotationQuaternion=d._f.FromArray(r.rotationQuaternion):r.rotation&&(a.rotation=d.P.FromArray(r.rotation)),a.scaling=d.P.FromArray(r.scaling),void 0!=r.checkCollisions&&null!=r.checkCollisions&&(a.checkCollisions=r.checkCollisions),void 0!=r.pickable&&null!=r.pickable&&(a.isPickable=r.pickable),void 0!=r.showBoundingBox&&null!=r.showBoundingBox&&(a.showBoundingBox=r.showBoundingBox),void 0!=r.showSubMeshesBoundingBox&&null!=r.showSubMeshesBoundingBox&&(a.showSubMeshesBoundingBox=r.showSubMeshesBoundingBox),void 0!=r.alphaIndex&&null!=r.showSubMeshesBoundingBox&&(a.alphaIndex=r.alphaIndex),r.physicsImpostor&&w._PhysicsImpostorParser(t,a,r),void 0!==r.actions&&(a._waitingData.actions=r.actions),r.animations){for(let e=0;e<r.animations.length;e++){let t=r.animations[e],s=(0,b.q)("BABYLON.Animation");s&&a.animations.push(s.Parse(t))}u.N.ParseAnimationRanges(a,r,t),r.autoAnimate&&t.beginAnimation(a,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1)}}if(e.thinInstances){let t=e.thinInstances;if(i.thinInstanceEnablePicking=!!t.enablePicking,t.matrixData?(i.thinInstanceSetBuffer("matrix",new Float32Array(t.matrixData),16,!1),i._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,i._thinInstanceDataStorage.instancesCount=t.instancesCount):i._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,e.thinInstances.userThinInstance){let t=e.thinInstances.userThinInstance;for(let e in t.data)i.thinInstanceSetBuffer(e,new Float32Array(t.data[e]),t.strides[e],!1),i._userThinInstanceBuffersStorage.sizes[e]=t.sizes[e]}}return i}setPositionsForCPUSkinning(){let e=this._internalMeshDataInfo;if(!e._sourcePositions){let t=this.getVerticesData(f.o.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(f.o.PositionKind)||this.setVerticesData(f.o.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){let e=this._internalMeshDataInfo;if(!e._sourceNormals){let t=this.getVerticesData(f.o.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(f.o.NormalKind)||this.setVerticesData(f.o.NormalKind,t,!0)}return e._sourceNormals}applySkeleton(e){let t;if(!this.geometry||this.geometry._softwareSkinningFrameId==this.getScene().getFrameId()||(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(f.o.PositionKind)||!this.isVerticesDataPresent(f.o.MatricesIndicesKind)||!this.isVerticesDataPresent(f.o.MatricesWeightsKind)))return this;let s=this.isVerticesDataPresent(f.o.NormalKind),i=this._internalMeshDataInfo;if(!i._sourcePositions){let e=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=e}s&&!i._sourceNormals&&this.setNormalsForCPUSkinning();let r=this.getVerticesData(f.o.PositionKind);if(!r)return this;r instanceof Float32Array||(r=new Float32Array(r));let a=this.getVerticesData(f.o.NormalKind);if(s){if(!a)return this;a instanceof Float32Array||(a=new Float32Array(a))}let n=this.getVerticesData(f.o.MatricesIndicesKind),o=this.getVerticesData(f.o.MatricesWeightsKind);if(!o||!n)return this;let l=this.numBoneInfluencers>4,h=l?this.getVerticesData(f.o.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(f.o.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),g=d.P.Zero(),_=new d.y3,m=new d.y3,I=0;for(let e=0;e<r.length;e+=3,I+=4){let f;for(t=0;t<4;t++)(f=o[I+t])>0&&(d.y3.FromFloat32ArrayToRefScaled(u,Math.floor(16*n[I+t]),f,m),_.addToSelf(m));if(l)for(t=0;t<4;t++)(f=c[I+t])>0&&(d.y3.FromFloat32ArrayToRefScaled(u,Math.floor(16*h[I+t]),f,m),_.addToSelf(m));d.P.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],_,g),g.toArray(r,e),s&&(d.P.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],_,g),g.toArray(a,e)),_.reset()}return this.updateVerticesData(f.o.PositionKind,r),s&&this.updateVerticesData(f.o.NormalKind,a),this}static MinMax(e){let t=null,s=null;return(e.forEach(function(e){let i=e.getBoundingInfo(),r=i.boundingBox;t&&s?(t.minimizeInPlace(r.minimumWorld),s.maximizeInPlace(r.maximumWorld)):(t=r.minimumWorld,s=r.maximumWorld)}),t&&s)?{min:t,max:s}:{min:d.P.Zero(),max:d.P.Zero()}}static Center(e){let t=e instanceof Array?w.MinMax(e):e;return d.P.Center(t.min,t.max)}static MergeMeshes(e,t=!0,s,i,r,a){return(0,o.s3)(w._MergeMeshesCoroutine(e,t,s,i,r,a,!1))}static MergeMeshesAsync(e,t=!0,s,i,r,a){return(0,o.sM)(w._MergeMeshesCoroutine(e,t,s,i,r,a,!0),(0,o.KO)())}static*_MergeMeshesCoroutine(e,t=!0,s,i,r,a,n){let o;if(0===(e=e.filter(Boolean)).length)return null;if(!s){let t=0;for(o=0;o<e.length;o++)if((t+=e[o].getTotalVertices())>=65536)return y.Y.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}a&&(r=!1);let l=[],h=[],d=[],c=e[0].overrideMaterialSideOrientation;for(o=0;o<e.length;o++){let t=e[o];if(t.isAnInstance)return y.Y.Warn("Cannot merge instance meshes."),null;if(c!==t.overrideMaterialSideOrientation)return y.Y.Warn("Cannot merge meshes with different overrideMaterialSideOrientation values."),null;if(r&&d.push(t.getTotalIndices()),a){if(t.material){let e=t.material;if(e instanceof p.G){for(let t=0;t<e.subMaterials.length;t++)0>l.indexOf(e.subMaterials[t])&&l.push(e.subMaterials[t]);for(let s=0;s<t.subMeshes.length;s++)h.push(l.indexOf(e.subMaterials[t.subMeshes[s].materialIndex])),d.push(t.subMeshes[s].indexCount)}else{0>l.indexOf(e)&&l.push(e);for(let s=0;s<t.subMeshes.length;s++)h.push(l.indexOf(e)),d.push(t.subMeshes[s].indexCount)}}else for(let e=0;e<t.subMeshes.length;e++)h.push(0),d.push(t.subMeshes[e].indexCount)}}let u=e[0],f=e=>{let t=e.computeWorldMatrix(!0),s=g.x.ExtractFromMesh(e,!1,!1);return{vertexData:s,transform:t}},{vertexData:_,transform:m}=f(u);n&&(yield);let M=Array(e.length-1);for(let t=1;t<e.length;t++)M[t-1]=f(e[t]),n&&(yield);let v=_._mergeCoroutine(m,M,s,n,!t),D=v.next();for(;!D.done;)n&&(yield),D=v.next();let b=D.value;i||(i=new w(u.name+"_merged",u.getScene()));let S=b._applyToCoroutine(i,void 0,n),x=S.next();for(;!x.done;)n&&(yield),x=S.next();if(i.checkCollisions=u.checkCollisions,i.overrideMaterialSideOrientation=u.overrideMaterialSideOrientation,t)for(o=0;o<e.length;o++)e[o].dispose();if(r||a){i.releaseSubMeshes(),o=0;let e=0;for(;o<d.length;)I.P.CreateFromIndices(0,e,d[o],i,void 0,!1),e+=d[o],o++;for(let e of i.subMeshes)e.refreshBoundingInfo();i.computeWorldMatrix(!0)}if(a){let e=new p.G(u.name+"_merged",u.getScene());e.subMaterials=l;for(let e=0;e<i.subMeshes.length;e++)i.subMeshes[e].materialIndex=h[e];i.material=e}else i.material=u.material;return i}addInstance(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)}removeInstance(e){let t=e._indexInSourceMeshInstanceArray;if(-1!=t){if(t!==this.instances.length-1){let e=this.instances[this.instances.length-1];this.instances[t]=e,e._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}}_shouldConvertRHS(){return this.overrideMaterialSideOrientation===M.F.CounterClockWiseSideOrientation}_getRenderingFillMode(e){var t;let s=this.getScene();return s.forcePointsCloud?M.F.PointFillMode:s.forceWireframe?M.F.WireFrameFillMode:null!==(t=this.overrideRenderingFillMode)&&void 0!==t?t:e}setMaterialByID(e){return this.setMaterialById(e)}static CreateRibbon(e,t,s,i,r,a,n,o,l){throw Error("Import MeshBuilder to populate this function")}static CreateDisc(e,t,s,i,r,a){throw Error("Import MeshBuilder to populate this function")}static CreateBox(e,t,s,i,r){throw Error("Import MeshBuilder to populate this function")}static CreateSphere(e,t,s,i,r,a){throw Error("Import MeshBuilder to populate this function")}static CreateHemisphere(e,t,s,i){throw Error("Import MeshBuilder to populate this function")}static CreateCylinder(e,t,s,i,r,a,n,o,l){throw Error("Import MeshBuilder to populate this function")}static CreateTorus(e,t,s,i,r,a,n){throw Error("Import MeshBuilder to populate this function")}static CreateTorusKnot(e,t,s,i,r,a,n,o,l,h){throw Error("Import MeshBuilder to populate this function")}static CreateLines(e,t,s,i,r){throw Error("Import MeshBuilder to populate this function")}static CreateDashedLines(e,t,s,i,r,a,n,o){throw Error("Import MeshBuilder to populate this function")}static CreatePolygon(e,t,s,i,r,a,n){throw Error("Import MeshBuilder to populate this function")}static ExtrudePolygon(e,t,s,i,r,a,n,o){throw Error("Import MeshBuilder to populate this function")}static ExtrudeShape(e,t,s,i,r,a,n,o,l,h){throw Error("Import MeshBuilder to populate this function")}static ExtrudeShapeCustom(e,t,s,i,r,a,n,o,l,h,d,c){throw Error("Import MeshBuilder to populate this function")}static CreateLathe(e,t,s,i,r,a,n){throw Error("Import MeshBuilder to populate this function")}static CreatePlane(e,t,s,i,r){throw Error("Import MeshBuilder to populate this function")}static CreateGround(e,t,s,i,r,a){throw Error("Import MeshBuilder to populate this function")}static CreateTiledGround(e,t,s,i,r,a,n,o,l){throw Error("Import MeshBuilder to populate this function")}static CreateGroundFromHeightMap(e,t,s,i,r,a,n,o,l,h,d){throw Error("Import MeshBuilder to populate this function")}static CreateTube(e,t,s,i,r,a,n,o,l,h){throw Error("Import MeshBuilder to populate this function")}static CreatePolyhedron(e,t,s){throw Error("Import MeshBuilder to populate this function")}static CreateIcoSphere(e,t,s){throw Error("Import MeshBuilder to populate this function")}static CreateDecal(e,t,s,i,r,a){throw Error("Import MeshBuilder to populate this function")}static CreateCapsule(e,t,s){throw Error("Import MeshBuilder to populate this function")}static ExtendToGoldberg(e){throw Error("Import MeshBuilder to populate this function")}}w.FRONTSIDE=g.x.FRONTSIDE,w.BACKSIDE=g.x.BACKSIDE,w.DOUBLESIDE=g.x.DOUBLESIDE,w.DEFAULTSIDE=g.x.DEFAULTSIDE,w.NO_CAP=0,w.CAP_START=1,w.CAP_END=2,w.CAP_ALL=3,w.NO_FLIP=0,w.FLIP_TILE=1,w.ROTATE_TILE=2,w.FLIP_ROW=3,w.ROTATE_ROW=4,w.FLIP_N_ROTATE_TILE=5,w.FLIP_N_ROTATE_ROW=6,w.CENTER=0,w.LEFT=1,w.RIGHT=2,w.TOP=3,w.BOTTOM=4,w.INSTANCEDMESH_SORT_TRANSPARENT=!1,w._GroundMeshParser=(e,t)=>{throw(0,S.S)("GroundMesh")},w._GoldbergMeshParser=(e,t)=>{throw(0,S.S)("GoldbergMesh")},w._LinesMeshParser=(e,t)=>{throw(0,S.S)("LinesMesh")},w._GreasedLineMeshParser=(e,t)=>{throw(0,S.S)("GreasedLineMesh")},w._TrailMeshParser=(e,t)=>{throw(0,S.S)("TrailMesh")},(0,b.H)("BABYLON.Mesh",w)}}]); \ No newline at end of file diff --git a/.next/static/chunks/472-51fd3a56159f1e5b.js b/.next/static/chunks/472-51fd3a56159f1e5b.js new file mode 100644 index 0000000..66d69cd --- /dev/null +++ b/.next/static/chunks/472-51fd3a56159f1e5b.js @@ -0,0 +1,25 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[472],{5844:function(t,r){"use strict";function getDeploymentIdQueryOrEmptyString(){return""}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"getDeploymentIdQueryOrEmptyString",{enumerable:!0,get:function(){return getDeploymentIdQueryOrEmptyString}})},2335:function(){"trimStart"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),"trimEnd"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),"description"in Symbol.prototype||Object.defineProperty(Symbol.prototype,"description",{configurable:!0,get:function(){var t=/\((.*)\)/.exec(this.toString());return t?t[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(t,r){return r=this.concat.apply([],this),t>1&&r.some(Array.isArray)?r.flat(t-1):r},Array.prototype.flatMap=function(t,r){return this.map(t,r).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(t){if("function"!=typeof t)return this.then(t,t);var r=this.constructor||Promise;return this.then(function(n){return r.resolve(t()).then(function(){return n})},function(n){return r.resolve(t()).then(function(){throw n})})}),Object.fromEntries||(Object.fromEntries=function(t){return Array.from(t).reduce(function(t,r){return t[r[0]]=r[1],t},{})}),Array.prototype.at||(Array.prototype.at=function(t){var r=Math.trunc(t)||0;if(r<0&&(r+=this.length),!(r<0||r>=this.length))return this[r]})},9872:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"addBasePath",{enumerable:!0,get:function(){return addBasePath}});let o=n(8356),a=n(3997);function addBasePath(t,r){return(0,a.normalizePathTrailingSlash)((0,o.addPathPrefix)(t,""))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5354:function(t,r){"use strict";function loadScriptsInSequence(t,r){return t&&t.length?t.reduce((t,r)=>{let[n,o]=r;return t.then(()=>new Promise((t,r)=>{let a=document.createElement("script");if(o)for(let t in o)"children"!==t&&a.setAttribute(t,o[t]);n?(a.src=n,a.onload=()=>t(),a.onerror=r):o&&(a.innerHTML=o.children,setTimeout(t)),document.head.appendChild(a)}))},Promise.resolve()).catch(t=>{console.error(t)}).then(()=>{r()}):r()}function appBootstrap(t){loadScriptsInSequence(self.__next_s,()=>{t()})}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"appBootstrap",{enumerable:!0,get:function(){return appBootstrap}}),window.next={version:"14.0.1",appDir:!0},("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5231:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"callServer",{enumerable:!0,get:function(){return callServer}});let o=n(3728);async function callServer(t,r){let n=(0,o.getServerActionDispatcher)();if(!n)throw Error("Invariant: missing action dispatcher.");return new Promise((o,a)=>{n({actionId:t,actionArgs:r,resolve:o,reject:a})})}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},811:function(t,r,n){"use strict";let o,a;Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"hydrate",{enumerable:!0,get:function(){return hydrate}});let u=n(1024),i=n(8533);n(2335);let s=u._(n(4040)),d=i._(n(2265)),p=n(6671),_=n(1852);n(6313);let b=u._(n(2504)),m=n(5231),j=n(4119),C=window.console.error;window.console.error=function(){for(var t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];(0,j.isNextRouterError)(r[0])||C.apply(window.console,r)},window.addEventListener("error",t=>{if((0,j.isNextRouterError)(t.error)){t.preventDefault();return}});let w=document,getCacheKey=()=>{let{pathname:t,search:r}=location;return t+r},D=new TextEncoder,U=!1,B=!1,$=null;function nextServerDataCallback(t){if(0===t[0])o=[];else if(1===t[0]){if(!o)throw Error("Unexpected server data: missing bootstrap script.");a?a.enqueue(D.encode(t[1])):o.push(t[1])}else 2===t[0]&&($=t[1])}function nextServerDataRegisterWriter(t){o&&(o.forEach(r=>{t.enqueue(D.encode(r))}),U&&!B&&(t.close(),B=!0,o=void 0)),a=t}let DOMContentLoaded=function(){a&&!B&&(a.close(),B=!0,o=void 0),U=!0};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",DOMContentLoaded,!1):DOMContentLoaded();let K=self.__next_f=self.__next_f||[];function createResponseCache(){return new Map}K.forEach(nextServerDataCallback),K.push=nextServerDataCallback;let q=createResponseCache();function useInitialServerResponse(t){let r=q.get(t);if(r)return r;let n=new ReadableStream({start(t){nextServerDataRegisterWriter(t)}}),o=(0,p.createFromReadableStream)(n,{callServer:m.callServer});return q.set(t,o),o}function ServerRoot(t){let{cacheKey:r}=t;d.default.useEffect(()=>{q.delete(r)});let n=useInitialServerResponse(r),o=(0,d.use)(n);return o}let ee=d.default.StrictMode;function Root(t){let{children:r}=t;return r}function RSCComponent(t){return d.default.createElement(ServerRoot,{...t,cacheKey:getCacheKey()})}function hydrate(){let t=d.default.createElement(ee,null,d.default.createElement(_.HeadManagerContext.Provider,{value:{appDir:!0}},d.default.createElement(Root,null,d.default.createElement(RSCComponent,null)))),r={onRecoverableError:b.default},n="__next_error__"===document.documentElement.id;n?s.default.createRoot(w,r).render(t):d.default.startTransition(()=>s.default.hydrateRoot(w,t,{...r,formState:$}))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2019:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0});let o=n(5354);(0,o.appBootstrap)(()=>{n(1055);let{hydrate:t}=n(811);n(3728),n(6954),t()}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1055:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),n(5844);{let t=n.u;n.u=function(){for(var r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];return encodeURI(t(...n))}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8325:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"AppRouterAnnouncer",{enumerable:!0,get:function(){return AppRouterAnnouncer}});let o=n(2265),a=n(4887),u="next-route-announcer";function getAnnouncerNode(){var t;let r=document.getElementsByName(u)[0];if(null==r?void 0:null==(t=r.shadowRoot)?void 0:t.childNodes[0])return r.shadowRoot.childNodes[0];{let t=document.createElement(u);t.style.cssText="position:absolute";let r=document.createElement("div");r.ariaLive="assertive",r.id="__next-route-announcer__",r.role="alert",r.style.cssText="position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal";let n=t.attachShadow({mode:"open"});return n.appendChild(r),document.body.appendChild(t),r}}function AppRouterAnnouncer(t){let{tree:r}=t,[n,i]=(0,o.useState)(null);(0,o.useEffect)(()=>{let t=getAnnouncerNode();return i(t),()=>{let t=document.getElementsByTagName(u)[0];(null==t?void 0:t.isConnected)&&document.body.removeChild(t)}},[]);let[s,d]=(0,o.useState)(""),p=(0,o.useRef)();return(0,o.useEffect)(()=>{let t="";if(document.title)t=document.title;else{let r=document.querySelector("h1");r&&(t=r.innerText||r.textContent||"")}void 0!==p.current&&p.current!==t&&d(t),p.current=t},[r]),n?(0,a.createPortal)(s,n):null}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8343:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{RSC:function(){return n},ACTION:function(){return o},NEXT_ROUTER_STATE_TREE:function(){return a},NEXT_ROUTER_PREFETCH:function(){return u},NEXT_URL:function(){return i},RSC_CONTENT_TYPE_HEADER:function(){return s},RSC_VARY_HEADER:function(){return d},FLIGHT_PARAMETERS:function(){return p},NEXT_RSC_UNION_QUERY:function(){return _}});let n="RSC",o="Next-Action",a="Next-Router-State-Tree",u="Next-Router-Prefetch",i="Next-Url",s="text/x-component",d=n+", "+a+", "+u+", "+i,p=[[n],[a],[u]],_="_rsc";("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3728:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{getServerActionDispatcher:function(){return getServerActionDispatcher},urlToUrlWithoutFlightMarker:function(){return urlToUrlWithoutFlightMarker},default:function(){return AppRouter}});let o=n(8533),a=o._(n(2265)),u=n(6313),i=n(7205),s=n(9706),d=n(2301),p=n(7407),_=n(2327),b=n(9928),m=n(5311),j=n(2169),C=n(9872),w=n(8325),D=n(5138),U=n(6700),B=n(3085),$=n(8343),K=n(3714),q=n(6746),ee=new Map,et=null;function getServerActionDispatcher(){return et}let er={refresh:()=>{}};function urlToUrlWithoutFlightMarker(t){let r=new URL(t,location.origin);return r.searchParams.delete($.NEXT_RSC_UNION_QUERY),r}function isExternalURL(t){return t.origin!==window.location.origin}function HistoryUpdater(t){let{tree:r,pushRef:n,canonicalUrl:o,sync:u}=t;return(0,a.useInsertionEffect)(()=>{let t={__NA:!0,tree:r};n.pendingPush&&(0,d.createHrefFromUrl)(new URL(window.location.href))!==o?(n.pendingPush=!1,window.history.pushState(t,"",o)):window.history.replaceState(t,"",o),u()},[r,n,o,u]),null}let createEmptyCacheNode=()=>({status:u.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map});function useServerActionDispatcher(t){let r=(0,a.useCallback)(r=>{(0,a.startTransition)(()=>{t({...r,type:s.ACTION_SERVER_ACTION,mutable:{globalMutable:er},cache:createEmptyCacheNode()})})},[t]);et=r}function useChangeByServerResponse(t){return(0,a.useCallback)((r,n,o)=>{(0,a.startTransition)(()=>{t({type:s.ACTION_SERVER_PATCH,flightData:n,previousTree:r,overrideCanonicalUrl:o,cache:createEmptyCacheNode(),mutable:{globalMutable:er}})})},[t])}function useNavigate(t){return(0,a.useCallback)((r,n,o,a)=>{let u=new URL((0,C.addBasePath)(r),location.href);return er.pendingNavigatePath=(0,d.createHrefFromUrl)(u),t({type:s.ACTION_NAVIGATE,url:u,isExternalUrl:isExternalURL(u),locationSearch:location.search,forceOptimisticNavigation:o,shouldScroll:null==a||a,navigateType:n,cache:createEmptyCacheNode(),mutable:{globalMutable:er}})},[t])}function Router(t){let{buildId:r,initialHead:n,initialTree:o,initialCanonicalUrl:d,children:b,assetPrefix:$}=t,et=(0,a.useMemo)(()=>(0,m.createInitialRouterState)({buildId:r,children:b,initialCanonicalUrl:d,initialTree:o,initialParallelRoutes:ee,isServer:!1,location:window.location,initialHead:n}),[r,b,d,o,n]),[{tree:en,cache:eo,prefetchCache:eu,pushRef:el,focusAndScrollRef:ei,canonicalUrl:ec,nextUrl:es},ef,ed]=(0,_.useReducerWithReduxDevtools)(i.reducer,et);(0,a.useEffect)(()=>{ee=null},[]);let{searchParams:ep,pathname:eh}=(0,a.useMemo)(()=>{let t=new URL(ec,window.location.href);return{searchParams:t.searchParams,pathname:(0,q.hasBasePath)(t.pathname)?(0,K.removeBasePath)(t.pathname):t.pathname}},[ec]),e_=useChangeByServerResponse(ef),ey=useNavigate(ef);useServerActionDispatcher(ef);let eg=(0,a.useMemo)(()=>{let t={back:()=>window.history.back(),forward:()=>window.history.forward(),prefetch:(t,r)=>{if((0,j.isBot)(window.navigator.userAgent))return;let n=new URL((0,C.addBasePath)(t),location.href);isExternalURL(n)||(0,a.startTransition)(()=>{var t;ef({type:s.ACTION_PREFETCH,url:n,kind:null!=(t=null==r?void 0:r.kind)?t:s.PrefetchKind.FULL})})},replace:(t,r)=>{void 0===r&&(r={}),(0,a.startTransition)(()=>{var n;ey(t,"replace",!!r.forceOptimisticNavigation,null==(n=r.scroll)||n)})},push:(t,r)=>{void 0===r&&(r={}),(0,a.startTransition)(()=>{var n;ey(t,"push",!!r.forceOptimisticNavigation,null==(n=r.scroll)||n)})},refresh:()=>{(0,a.startTransition)(()=>{ef({type:s.ACTION_REFRESH,cache:createEmptyCacheNode(),mutable:{globalMutable:er},origin:window.location.origin})})},fastRefresh:()=>{throw Error("fastRefresh can only be used in development mode. Please use refresh instead.")}};return t},[ef,ey]);if((0,a.useEffect)(()=>{window.next&&(window.next.router=eg)},[eg]),(0,a.useEffect)(()=>{er.refresh=eg.refresh},[eg.refresh]),(0,a.useEffect)(()=>{function handlePageShow(t){var r;t.persisted&&(null==(r=window.history.state)?void 0:r.tree)&&ef({type:s.ACTION_RESTORE,url:new URL(window.location.href),tree:window.history.state.tree})}return window.addEventListener("pageshow",handlePageShow),()=>{window.removeEventListener("pageshow",handlePageShow)}},[ef]),el.mpaNavigation){if(er.pendingMpaPath!==ec){let t=window.location;el.pendingPush?t.assign(ec):t.replace(ec),er.pendingMpaPath=ec}(0,a.use)((0,B.createInfinitePromise)())}let eb=(0,a.useCallback)(t=>{let{state:r}=t;if(r){if(!r.__NA){window.location.reload();return}(0,a.startTransition)(()=>{ef({type:s.ACTION_RESTORE,url:new URL(window.location.href),tree:r.tree})})}},[ef]);(0,a.useEffect)(()=>(window.addEventListener("popstate",eb),()=>{window.removeEventListener("popstate",eb)}),[eb]);let em=(0,a.useMemo)(()=>(0,U.findHeadInCache)(eo,en[1]),[eo,en]),ev=a.default.createElement(D.RedirectBoundary,null,em,eo.subTreeData,a.default.createElement(w.AppRouterAnnouncer,{tree:en}));return a.default.createElement(a.default.Fragment,null,a.default.createElement(HistoryUpdater,{tree:en,pushRef:el,canonicalUrl:ec,sync:ed}),a.default.createElement(p.PathnameContext.Provider,{value:eh},a.default.createElement(p.SearchParamsContext.Provider,{value:ep},a.default.createElement(u.GlobalLayoutRouterContext.Provider,{value:{buildId:r,changeByServerResponse:e_,tree:en,focusAndScrollRef:ei,nextUrl:es}},a.default.createElement(u.AppRouterContext.Provider,{value:eg},a.default.createElement(u.LayoutRouterContext.Provider,{value:{childNodes:eo.parallelRoutes,tree:en,url:ec}},ev))))))}function AppRouter(t){let{globalErrorComponent:r,...n}=t;return a.default.createElement(b.ErrorBoundary,{errorComponent:r},a.default.createElement(Router,n))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3940:function(t,r,n){"use strict";function clientHookInServerComponentError(t){}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"clientHookInServerComponentError",{enumerable:!0,get:function(){return clientHookInServerComponentError}}),n(1024),n(2265),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},9928:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{ErrorBoundaryHandler:function(){return ErrorBoundaryHandler},GlobalError:function(){return GlobalError},default:function(){return s},ErrorBoundary:function(){return ErrorBoundary}});let o=n(1024),a=o._(n(2265)),u=n(94),i={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},text:{fontSize:"14px",fontWeight:400,lineHeight:"28px",margin:"0 8px"}};function HandleISRError(t){let{error:r}=t;if("function"==typeof fetch.__nextGetStaticStore){var n;let t=null==(n=fetch.__nextGetStaticStore())?void 0:n.getStore();if((null==t?void 0:t.isRevalidate)||(null==t?void 0:t.isStaticGeneration))throw console.error(r),r}return null}let ErrorBoundaryHandler=class ErrorBoundaryHandler extends a.default.Component{static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,r){return t.pathname!==r.previousPathname&&r.error?{error:null,previousPathname:t.pathname}:{error:r.error,previousPathname:t.pathname}}render(){return this.state.error?a.default.createElement(a.default.Fragment,null,a.default.createElement(HandleISRError,{error:this.state.error}),this.props.errorStyles,this.props.errorScripts,a.default.createElement(this.props.errorComponent,{error:this.state.error,reset:this.reset})):this.props.children}constructor(t){super(t),this.reset=()=>{this.setState({error:null})},this.state={error:null,previousPathname:this.props.pathname}}};function GlobalError(t){let{error:r}=t,n=null==r?void 0:r.digest;return a.default.createElement("html",{id:"__next_error__"},a.default.createElement("head",null),a.default.createElement("body",null,a.default.createElement(HandleISRError,{error:r}),a.default.createElement("div",{style:i.error},a.default.createElement("div",null,a.default.createElement("h2",{style:i.text},"Application error: a "+(n?"server":"client")+"-side exception has occurred (see the "+(n?"server logs":"browser console")+" for more information)."),n?a.default.createElement("p",{style:i.text},"Digest: "+n):null))))}let s=GlobalError;function ErrorBoundary(t){let{errorComponent:r,errorStyles:n,errorScripts:o,children:i}=t,s=(0,u.usePathname)();return r?a.default.createElement(ErrorBoundaryHandler,{pathname:s,errorComponent:r,errorStyles:n,errorScripts:o},i):a.default.createElement(a.default.Fragment,null,i)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1351:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{DYNAMIC_ERROR_CODE:function(){return n},DynamicServerError:function(){return DynamicServerError}});let n="DYNAMIC_SERVER_USAGE";let DynamicServerError=class DynamicServerError extends Error{constructor(t){super("Dynamic server usage: "+t),this.digest=n}};("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3085:function(t,r){"use strict";let n;function createInfinitePromise(){return n||(n=new Promise(()=>{})),n}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createInfinitePromise",{enumerable:!0,get:function(){return createInfinitePromise}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},4119:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"isNextRouterError",{enumerable:!0,get:function(){return isNextRouterError}});let o=n(9273),a=n(8466);function isNextRouterError(t){return t&&t.digest&&((0,a.isRedirectError)(t)||(0,o.isNotFoundError)(t))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},6954:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"default",{enumerable:!0,get:function(){return OuterLayoutRouter}});let o=n(1024),a=n(8533),u=a._(n(2265)),i=o._(n(4887)),s=n(6313),d=n(8146),p=n(3085),_=n(9928),b=n(8163),m=n(280),j=n(5138),C=n(3170),w=n(1263),D=n(3322),U=n(3559);function walkAddRefetch(t,r){if(t){let[n,o]=t,a=2===t.length;if((0,b.matchSegment)(r[0],n)&&r[1].hasOwnProperty(o)){if(a){let t=walkAddRefetch(void 0,r[1][o]);return[r[0],{...r[1],[o]:[t[0],t[1],t[2],"refetch"]}]}return[r[0],{...r[1],[o]:walkAddRefetch(t.slice(2),r[1][o])}]}}return r}function findDOMNode(t){return i.default.findDOMNode(t)}let B=["bottom","height","left","right","top","width","x","y"];function shouldSkipElement(t){if(["sticky","fixed"].includes(getComputedStyle(t).position))return!0;let r=t.getBoundingClientRect();return B.every(t=>0===r[t])}function topOfElementInViewport(t,r){let n=t.getBoundingClientRect();return n.top>=0&&n.top<=r}function getHashFragmentDomNode(t){var r;return"top"===t?document.body:null!=(r=document.getElementById(t))?r:document.getElementsByName(t)[0]}let InnerScrollAndFocusHandler=class InnerScrollAndFocusHandler extends u.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...t){super(...t),this.handlePotentialScroll=()=>{let{focusAndScrollRef:t,segmentPath:r}=this.props;if(t.apply){if(0!==t.segmentPaths.length&&!t.segmentPaths.some(t=>r.every((r,n)=>(0,b.matchSegment)(r,t[n]))))return;let n=null,o=t.hashFragment;if(o&&(n=getHashFragmentDomNode(o)),n||(n=findDOMNode(this)),!(n instanceof Element))return;for(;!(n instanceof HTMLElement)||shouldSkipElement(n);){if(null===n.nextElementSibling)return;n=n.nextElementSibling}t.apply=!1,t.hashFragment=null,t.segmentPaths=[],(0,m.handleSmoothScroll)(()=>{if(o){n.scrollIntoView();return}let t=document.documentElement,r=t.clientHeight;!topOfElementInViewport(n,r)&&(t.scrollTop=0,topOfElementInViewport(n,r)||n.scrollIntoView())},{dontForceLayout:!0,onlyHashChange:t.onlyHashChange}),t.onlyHashChange=!1,n.focus()}}}};function ScrollAndFocusHandler(t){let{segmentPath:r,children:n}=t,o=(0,u.useContext)(s.GlobalLayoutRouterContext);if(!o)throw Error("invariant global layout router not mounted");return u.default.createElement(InnerScrollAndFocusHandler,{segmentPath:r,focusAndScrollRef:o.focusAndScrollRef},n)}function InnerLayoutRouter(t){let{parallelRouterKey:r,url:n,childNodes:o,childProp:a,segmentPath:i,tree:_,cacheKey:b}=t,m=(0,u.useContext)(s.GlobalLayoutRouterContext);if(!m)throw Error("invariant global layout router not mounted");let{buildId:j,changeByServerResponse:C,tree:w}=m,D=o.get(b);if(a&&null!==a.current&&(D?D.status===s.CacheStates.LAZY_INITIALIZED&&(D.status=s.CacheStates.READY,D.subTreeData=a.current):(D={status:s.CacheStates.READY,data:null,subTreeData:a.current,parallelRoutes:new Map},o.set(b,D))),!D||D.status===s.CacheStates.LAZY_INITIALIZED){let t=walkAddRefetch(["",...i],w);D={status:s.CacheStates.DATA_FETCH,data:(0,U.createRecordFromThenable)((0,d.fetchServerResponse)(new URL(n,location.origin),t,m.nextUrl,j)),subTreeData:null,head:D&&D.status===s.CacheStates.LAZY_INITIALIZED?D.head:void 0,parallelRoutes:D&&D.status===s.CacheStates.LAZY_INITIALIZED?D.parallelRoutes:new Map},o.set(b,D)}if(!D)throw Error("Child node should always exist");if(D.subTreeData&&D.data)throw Error("Child node should not have both subTreeData and data");if(D.data){let[t,r]=(0,u.use)(D.data);D.data=null,setTimeout(()=>{(0,u.startTransition)(()=>{C(w,t,r)})}),(0,u.use)((0,p.createInfinitePromise)())}D.subTreeData||(0,u.use)((0,p.createInfinitePromise)());let B=u.default.createElement(s.LayoutRouterContext.Provider,{value:{tree:_[1][r],childNodes:D.parallelRoutes,url:n}},D.subTreeData);return B}function LoadingBoundary(t){let{children:r,loading:n,loadingStyles:o,loadingScripts:a,hasLoading:i}=t;return i?u.default.createElement(u.Suspense,{fallback:u.default.createElement(u.default.Fragment,null,o,a,n)},r):u.default.createElement(u.default.Fragment,null,r)}function OuterLayoutRouter(t){let{parallelRouterKey:r,segmentPath:n,childProp:o,error:a,errorStyles:i,errorScripts:d,templateStyles:p,templateScripts:m,loading:U,loadingStyles:B,loadingScripts:$,hasLoading:K,template:q,notFound:ee,notFoundStyles:et,styles:er}=t,en=(0,u.useContext)(s.LayoutRouterContext);if(!en)throw Error("invariant expected layout router to be mounted");let{childNodes:eo,tree:eu,url:el}=en,ei=eo.get(r);ei||(ei=new Map,eo.set(r,ei));let ec=eu[1][r][0],es=o.segment,ef=(0,w.getSegmentValue)(ec),ed=[ec];return u.default.createElement(u.default.Fragment,null,er,ed.map(t=>{let er=(0,b.matchSegment)(t,es),en=(0,w.getSegmentValue)(t),eo=(0,D.createRouterCacheKey)(t);return u.default.createElement(s.TemplateContext.Provider,{key:(0,D.createRouterCacheKey)(t,!0),value:u.default.createElement(ScrollAndFocusHandler,{segmentPath:n},u.default.createElement(_.ErrorBoundary,{errorComponent:a,errorStyles:i,errorScripts:d},u.default.createElement(LoadingBoundary,{hasLoading:K,loading:U,loadingStyles:B,loadingScripts:$},u.default.createElement(C.NotFoundBoundary,{notFound:ee,notFoundStyles:et},u.default.createElement(j.RedirectBoundary,null,u.default.createElement(InnerLayoutRouter,{parallelRouterKey:r,url:el,tree:eu,childNodes:ei,childProp:er?o:null,segmentPath:n,cacheKey:eo,isActive:ef===en}))))))},p,m,q)}))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8163:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{matchSegment:function(){return matchSegment},canSegmentBeOverridden:function(){return canSegmentBeOverridden}});let o=n(5682),matchSegment=(t,r)=>"string"==typeof t?"string"==typeof r&&t===r:"string"!=typeof r&&t[0]===r[0]&&t[1]===r[1],canSegmentBeOverridden=(t,r)=>{var n;return!Array.isArray(t)&&!!Array.isArray(r)&&(null==(n=(0,o.getSegmentParam)(t))?void 0:n.param)===r[0]};("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5437:function(t,r,n){"use strict";function maybePostpone(t,r){if(!t.isStaticGeneration||!t.experimental.ppr)return;let o=n(2265);"function"==typeof o.unstable_postpone&&o.unstable_postpone(r)}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"maybePostpone",{enumerable:!0,get:function(){return maybePostpone}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},94:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{ReadonlyURLSearchParams:function(){return ReadonlyURLSearchParams},useSearchParams:function(){return useSearchParams},usePathname:function(){return usePathname},ServerInsertedHTMLContext:function(){return d.ServerInsertedHTMLContext},useServerInsertedHTML:function(){return d.useServerInsertedHTML},useRouter:function(){return useRouter},useParams:function(){return useParams},useSelectedLayoutSegments:function(){return useSelectedLayoutSegments},useSelectedLayoutSegment:function(){return useSelectedLayoutSegment},redirect:function(){return p.redirect},permanentRedirect:function(){return p.permanentRedirect},RedirectType:function(){return p.RedirectType},notFound:function(){return _.notFound}});let o=n(2265),a=n(6313),u=n(7407),i=n(3940),s=n(1263),d=n(3972),p=n(8466),_=n(9273),b=Symbol("internal for urlsearchparams readonly");function readonlyURLSearchParamsError(){return Error("ReadonlyURLSearchParams cannot be modified")}let ReadonlyURLSearchParams=class ReadonlyURLSearchParams{[Symbol.iterator](){return this[b][Symbol.iterator]()}append(){throw readonlyURLSearchParamsError()}delete(){throw readonlyURLSearchParamsError()}set(){throw readonlyURLSearchParamsError()}sort(){throw readonlyURLSearchParamsError()}constructor(t){this[b]=t,this.entries=t.entries.bind(t),this.forEach=t.forEach.bind(t),this.get=t.get.bind(t),this.getAll=t.getAll.bind(t),this.has=t.has.bind(t),this.keys=t.keys.bind(t),this.values=t.values.bind(t),this.toString=t.toString.bind(t),this.size=t.size}};function useSearchParams(){(0,i.clientHookInServerComponentError)("useSearchParams");let t=(0,o.useContext)(u.SearchParamsContext),r=(0,o.useMemo)(()=>t?new ReadonlyURLSearchParams(t):null,[t]);return r}function usePathname(){return(0,i.clientHookInServerComponentError)("usePathname"),(0,o.useContext)(u.PathnameContext)}function useRouter(){(0,i.clientHookInServerComponentError)("useRouter");let t=(0,o.useContext)(a.AppRouterContext);if(null===t)throw Error("invariant expected app router to be mounted");return t}function getSelectedParams(t,r){void 0===r&&(r={});let n=t[1];for(let t of Object.values(n)){let n=t[0],o=Array.isArray(n),a=o?n[1]:n;if(!a||a.startsWith("__PAGE__"))continue;let u=o&&("c"===n[2]||"oc"===n[2]);u?r[n[0]]=n[1].split("/"):o&&(r[n[0]]=n[1]),r=getSelectedParams(t,r)}return r}function useParams(){(0,i.clientHookInServerComponentError)("useParams");let t=(0,o.useContext)(a.GlobalLayoutRouterContext),r=(0,o.useContext)(u.PathParamsContext);return(0,o.useMemo)(()=>(null==t?void 0:t.tree)?getSelectedParams(t.tree):r,[null==t?void 0:t.tree,r])}function getSelectedLayoutSegmentPath(t,r,n,o){let a;if(void 0===n&&(n=!0),void 0===o&&(o=[]),n)a=t[1][r];else{var u;let r=t[1];a=null!=(u=r.children)?u:Object.values(r)[0]}if(!a)return o;let i=a[0],d=(0,s.getSegmentValue)(i);return!d||d.startsWith("__PAGE__")?o:(o.push(d),getSelectedLayoutSegmentPath(a,r,!1,o))}function useSelectedLayoutSegments(t){void 0===t&&(t="children"),(0,i.clientHookInServerComponentError)("useSelectedLayoutSegments");let{tree:r}=(0,o.useContext)(a.LayoutRouterContext);return getSelectedLayoutSegmentPath(r,t)}function useSelectedLayoutSegment(t){void 0===t&&(t="children"),(0,i.clientHookInServerComponentError)("useSelectedLayoutSegment");let r=useSelectedLayoutSegments(t);return 0===r.length?null:r[0]}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3170:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"NotFoundBoundary",{enumerable:!0,get:function(){return NotFoundBoundary}});let o=n(1024),a=o._(n(2265)),u=n(94);let NotFoundErrorBoundary=class NotFoundErrorBoundary extends a.default.Component{static getDerivedStateFromError(t){if((null==t?void 0:t.digest)==="NEXT_NOT_FOUND")return{notFoundTriggered:!0};throw t}static getDerivedStateFromProps(t,r){return t.pathname!==r.previousPathname&&r.notFoundTriggered?{notFoundTriggered:!1,previousPathname:t.pathname}:{notFoundTriggered:r.notFoundTriggered,previousPathname:t.pathname}}render(){return this.state.notFoundTriggered?a.default.createElement(a.default.Fragment,null,a.default.createElement("meta",{name:"robots",content:"noindex"}),!1,this.props.notFoundStyles,this.props.notFound):this.props.children}constructor(t){super(t),this.state={notFoundTriggered:!!t.asNotFound,previousPathname:t.pathname}}};function NotFoundBoundary(t){let{notFound:r,notFoundStyles:n,asNotFound:o,children:i}=t,s=(0,u.usePathname)();return r?a.default.createElement(NotFoundErrorBoundary,{pathname:s,notFound:r,notFoundStyles:n,asNotFound:o},i):a.default.createElement(a.default.Fragment,null,i)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},9273:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{notFound:function(){return notFound},isNotFoundError:function(){return isNotFoundError}});let n="NEXT_NOT_FOUND";function notFound(){let t=Error(n);throw t.digest=n,t}function isNotFoundError(t){return(null==t?void 0:t.digest)===n}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},839:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"PromiseQueue",{enumerable:!0,get:function(){return PromiseQueue}});let o=n(4677),a=n(6249);var u=a._("_maxConcurrency"),i=a._("_runningCount"),s=a._("_queue"),d=a._("_processNext");let PromiseQueue=class PromiseQueue{enqueue(t){let r,n;let a=new Promise((t,o)=>{r=t,n=o}),task=async()=>{try{o._(this,i)[i]++;let n=await t();r(n)}catch(t){n(t)}finally{o._(this,i)[i]--,o._(this,d)[d]()}};return o._(this,s)[s].push({promiseFn:a,task}),o._(this,d)[d](),a}bump(t){let r=o._(this,s)[s].findIndex(r=>r.promiseFn===t);if(r>-1){let t=o._(this,s)[s].splice(r,1)[0];o._(this,s)[s].unshift(t),o._(this,d)[d](!0)}}constructor(t=5){Object.defineProperty(this,d,{value:processNext}),Object.defineProperty(this,u,{writable:!0,value:void 0}),Object.defineProperty(this,i,{writable:!0,value:void 0}),Object.defineProperty(this,s,{writable:!0,value:void 0}),o._(this,u)[u]=t,o._(this,i)[i]=0,o._(this,s)[s]=[]}};function processNext(t){if(void 0===t&&(t=!1),(o._(this,i)[i]<o._(this,u)[u]||t)&&o._(this,s)[s].length>0){var r;null==(r=o._(this,s)[s].shift())||r.task()}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5138:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{RedirectErrorBoundary:function(){return RedirectErrorBoundary},RedirectBoundary:function(){return RedirectBoundary}});let o=n(8533),a=o._(n(2265)),u=n(94),i=n(8466);function HandleRedirect(t){let{redirect:r,reset:n,redirectType:o}=t,s=(0,u.useRouter)();return(0,a.useEffect)(()=>{a.default.startTransition(()=>{o===i.RedirectType.push?s.push(r,{}):s.replace(r,{}),n()})},[r,o,n,s]),null}let RedirectErrorBoundary=class RedirectErrorBoundary extends a.default.Component{static getDerivedStateFromError(t){if((0,i.isRedirectError)(t)){let r=(0,i.getURLFromRedirectError)(t),n=(0,i.getRedirectTypeFromError)(t);return{redirect:r,redirectType:n}}throw t}render(){let{redirect:t,redirectType:r}=this.state;return null!==t&&null!==r?a.default.createElement(HandleRedirect,{redirect:t,redirectType:r,reset:()=>this.setState({redirect:null})}):this.props.children}constructor(t){super(t),this.state={redirect:null,redirectType:null}}};function RedirectBoundary(t){let{children:r}=t,n=(0,u.useRouter)();return a.default.createElement(RedirectErrorBoundary,{router:n},r)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8466:function(t,r,n){"use strict";var o,a;Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{RedirectType:function(){return o},getRedirectError:function(){return getRedirectError},redirect:function(){return redirect},permanentRedirect:function(){return permanentRedirect},isRedirectError:function(){return isRedirectError},getURLFromRedirectError:function(){return getURLFromRedirectError},getRedirectTypeFromError:function(){return getRedirectTypeFromError}});let u=n(228),i="NEXT_REDIRECT";function getRedirectError(t,r,n){void 0===n&&(n=!1);let o=Error(i);o.digest=i+";"+r+";"+t+";"+n;let a=u.requestAsyncStorage.getStore();return a&&(o.mutableCookies=a.mutableCookies),o}function redirect(t,r){throw void 0===r&&(r="replace"),getRedirectError(t,r,!1)}function permanentRedirect(t,r){throw void 0===r&&(r="replace"),getRedirectError(t,r,!0)}function isRedirectError(t){if("string"!=typeof(null==t?void 0:t.digest))return!1;let[r,n,o,a]=t.digest.split(";",4);return r===i&&("replace"===n||"push"===n)&&"string"==typeof o&&("true"===a||"false"===a)}function getURLFromRedirectError(t){return isRedirectError(t)?t.digest.split(";",3)[2]:null}function getRedirectTypeFromError(t){if(!isRedirectError(t))throw Error("Not a redirect error");return t.digest.split(";",2)[1]}(a=o||(o={})).push="push",a.replace="replace",("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},7264:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"default",{enumerable:!0,get:function(){return RenderFromTemplateContext}});let o=n(8533),a=o._(n(2265)),u=n(6313);function RenderFromTemplateContext(){let t=(0,a.useContext)(u.TemplateContext);return a.default.createElement(a.default.Fragment,null,t)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},228:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"requestAsyncStorage",{enumerable:!0,get:function(){return a}});let o=n(7346),a=(0,o.createAsyncLocalStorage)();("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2713:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"applyFlightData",{enumerable:!0,get:function(){return applyFlightData}});let o=n(6313),a=n(782),u=n(1956);function applyFlightData(t,r,n,i){void 0===i&&(i=!1);let[s,d,p]=n.slice(-3);return null!==d&&(3===n.length?(r.status=o.CacheStates.READY,r.subTreeData=d,(0,a.fillLazyItemsTillLeafWithHead)(r,t,s,p,i)):(r.status=o.CacheStates.READY,r.subTreeData=t.subTreeData,r.parallelRoutes=new Map(t.parallelRoutes),(0,u.fillCacheWithNewSubTreeData)(r,t,n,i)),!0)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8934:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"applyRouterStatePatchToTree",{enumerable:!0,get:function(){return applyRouterStatePatchToTree}});let o=n(8163);function applyPatch(t,r){let[n,a]=t,[u,i]=r;if("__DEFAULT__"===u&&"__DEFAULT__"!==n)return t;if((0,o.matchSegment)(n,u)){let r={};for(let t in a){let n=void 0!==i[t];n?r[t]=applyPatch(a[t],i[t]):r[t]=a[t]}for(let t in i)r[t]||(r[t]=i[t]);let o=[n,r];return t[2]&&(o[2]=t[2]),t[3]&&(o[3]=t[3]),t[4]&&(o[4]=t[4]),o}return r}function applyRouterStatePatchToTree(t,r,n){let a;let[u,i,,,s]=r;if(1===t.length){let t=applyPatch(r,n);return t}let[d,p]=t;if(!(0,o.matchSegment)(d,u))return null;let _=2===t.length;if(_)a=applyPatch(i[p],n);else if(null===(a=applyRouterStatePatchToTree(t.slice(2),i[p],n)))return null;let b=[t[0],{...i,[p]:a}];return s&&(b[4]=!0),b}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2082:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{extractPathFromFlightRouterState:function(){return extractPathFromFlightRouterState},computeChangedPath:function(){return computeChangedPath}});let o=n(4507),a=n(1706),u=n(8163),removeLeadingSlash=t=>"/"===t[0]?t.slice(1):t,segmentToPathname=t=>"string"==typeof t?t:t[1];function normalizeSegments(t){return t.reduce((t,r)=>""===(r=removeLeadingSlash(r))||(0,a.isGroupSegment)(r)?t:t+"/"+r,"")||"/"}function extractPathFromFlightRouterState(t){var r;let n=Array.isArray(t[0])?t[0][1]:t[0];if("__DEFAULT__"===n||o.INTERCEPTION_ROUTE_MARKERS.some(t=>n.startsWith(t)))return;if(n.startsWith("__PAGE__"))return"";let a=[n],u=null!=(r=t[1])?r:{},i=u.children?extractPathFromFlightRouterState(u.children):void 0;if(void 0!==i)a.push(i);else for(let[t,r]of Object.entries(u)){if("children"===t)continue;let n=extractPathFromFlightRouterState(r);void 0!==n&&a.push(n)}return normalizeSegments(a)}function computeChangedPathImpl(t,r){let[n,a]=t,[i,s]=r,d=segmentToPathname(n),p=segmentToPathname(i);if(o.INTERCEPTION_ROUTE_MARKERS.some(t=>d.startsWith(t)||p.startsWith(t)))return"";if(!(0,u.matchSegment)(n,i)){var _;return null!=(_=extractPathFromFlightRouterState(r))?_:""}for(let t in a)if(s[t]){let r=computeChangedPathImpl(a[t],s[t]);if(null!==r)return segmentToPathname(i)+"/"+r}return null}function computeChangedPath(t,r){let n=computeChangedPathImpl(t,r);return null==n||"/"===n?n:normalizeSegments(n.split("/"))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2301:function(t,r){"use strict";function createHrefFromUrl(t,r){return void 0===r&&(r=!0),t.pathname+t.search+(r?t.hash:"")}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createHrefFromUrl",{enumerable:!0,get:function(){return createHrefFromUrl}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5311:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createInitialRouterState",{enumerable:!0,get:function(){return createInitialRouterState}});let o=n(6313),a=n(2301),u=n(782),i=n(2082);function createInitialRouterState(t){var r;let{buildId:n,initialTree:s,children:d,initialCanonicalUrl:p,initialParallelRoutes:_,isServer:b,location:m,initialHead:j}=t,C={status:o.CacheStates.READY,data:null,subTreeData:d,parallelRoutes:b?new Map:_};return(null===_||0===_.size)&&(0,u.fillLazyItemsTillLeafWithHead)(C,void 0,s,j),{buildId:n,tree:s,cache:C,prefetchCache:new Map,pushRef:{pendingPush:!1,mpaNavigation:!1},focusAndScrollRef:{apply:!1,onlyHashChange:!1,hashFragment:null,segmentPaths:[]},canonicalUrl:m?(0,a.createHrefFromUrl)(m):p,nextUrl:null!=(r=(0,i.extractPathFromFlightRouterState)(s)||(null==m?void 0:m.pathname))?r:null}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},180:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createOptimisticTree",{enumerable:!0,get:function(){return createOptimisticTree}});let o=n(8163);function createOptimisticTree(t,r,n){let a;let[u,i,s,d,p]=r||[null,{}],_=t[0],b=1===t.length,m=null!==u&&(0,o.matchSegment)(u,_),j=Object.keys(i).length>1,C=!r||!m||j,w={};if(null!==u&&m&&(w=i),!b&&!j){let r=createOptimisticTree(t.slice(1),w?w.children:null,n||C);a=r}let D=[_,{...w,...a?{children:a}:{}}];return s&&(D[2]=s),!n&&C?D[3]="refetch":m&&d&&(D[3]=d),m&&p&&(D[4]=p),D}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3559:function(t,r){"use strict";function createRecordFromThenable(t){return t.status="pending",t.then(r=>{"pending"===t.status&&(t.status="fulfilled",t.value=r)},r=>{"pending"===t.status&&(t.status="rejected",t.reason=r)}),t}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createRecordFromThenable",{enumerable:!0,get:function(){return createRecordFromThenable}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3322:function(t,r){"use strict";function createRouterCacheKey(t,r){return void 0===r&&(r=!1),Array.isArray(t)?(t[0]+"|"+t[1]+"|"+t[2]).toLowerCase():r&&t.startsWith("__PAGE__")?"__PAGE__":t}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createRouterCacheKey",{enumerable:!0,get:function(){return createRouterCacheKey}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8146:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"fetchServerResponse",{enumerable:!0,get:function(){return fetchServerResponse}});let o=n(8343),a=n(3728),u=n(5231),i=n(9706),s=n(6360),d=n(1824),{createFromFetch:p}=n(6671);function doMpaNavigation(t){return[(0,a.urlToUrlWithoutFlightMarker)(t).toString(),void 0]}async function fetchServerResponse(t,r,n,_,b){let m={[o.RSC]:"1",[o.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(r))};b===i.PrefetchKind.AUTO&&(m[o.NEXT_ROUTER_PREFETCH]="1"),n&&(m[o.NEXT_URL]=n);let j=(0,s.hexHash)([m[o.NEXT_ROUTER_PREFETCH]||"0",m[o.NEXT_ROUTER_STATE_TREE],m[o.NEXT_URL]].join(","));try{let r=new URL(t);r.searchParams.set(o.NEXT_RSC_UNION_QUERY,j);let n=await fetch(r,{credentials:"same-origin",headers:m}),i=(0,a.urlToUrlWithoutFlightMarker)(n.url),s=n.redirected?i:void 0,b=n.headers.get("content-type")||"",C=!!n.headers.get(d.NEXT_DID_POSTPONE_HEADER);if(b!==o.RSC_CONTENT_TYPE_HEADER||!n.ok)return t.hash&&(i.hash=t.hash),doMpaNavigation(i.toString());let[w,D]=await p(Promise.resolve(n),{callServer:u.callServer});if(_!==w)return doMpaNavigation(n.url);return[D,s,C]}catch(r){return console.error("Failed to fetch RSC payload for "+t+". Falling back to browser navigation.",r),[t.toString(),void 0]}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},6443:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"fillCacheWithDataProperty",{enumerable:!0,get:function(){return fillCacheWithDataProperty}});let o=n(6313),a=n(3322);function fillCacheWithDataProperty(t,r,n,u,i){void 0===i&&(i=!1);let s=n.length<=2,[d,p]=n,_=(0,a.createRouterCacheKey)(p),b=r.parallelRoutes.get(d);if(!b||i&&r.parallelRoutes.size>1)return{bailOptimistic:!0};let m=t.parallelRoutes.get(d);m&&m!==b||(m=new Map(b),t.parallelRoutes.set(d,m));let j=b.get(_),C=m.get(_);if(s){C&&C.data&&C!==j||m.set(_,{status:o.CacheStates.DATA_FETCH,data:u(),subTreeData:null,parallelRoutes:new Map});return}if(!C||!j){C||m.set(_,{status:o.CacheStates.DATA_FETCH,data:u(),subTreeData:null,parallelRoutes:new Map});return}return C===j&&(C={status:C.status,data:C.data,subTreeData:C.subTreeData,parallelRoutes:new Map(C.parallelRoutes)},m.set(_,C)),fillCacheWithDataProperty(C,j,n.slice(2),u)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1956:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"fillCacheWithNewSubTreeData",{enumerable:!0,get:function(){return fillCacheWithNewSubTreeData}});let o=n(6313),a=n(5303),u=n(782),i=n(3322);function fillCacheWithNewSubTreeData(t,r,n,s){let d=n.length<=5,[p,_]=n,b=(0,i.createRouterCacheKey)(_),m=r.parallelRoutes.get(p);if(!m)return;let j=t.parallelRoutes.get(p);j&&j!==m||(j=new Map(m),t.parallelRoutes.set(p,j));let C=m.get(b),w=j.get(b);if(d){w&&w.data&&w!==C||(w={status:o.CacheStates.READY,data:null,subTreeData:n[3],parallelRoutes:C?new Map(C.parallelRoutes):new Map},C&&(0,a.invalidateCacheByRouterState)(w,C,n[2]),(0,u.fillLazyItemsTillLeafWithHead)(w,C,n[2],n[4],s),j.set(b,w));return}w&&C&&(w===C&&(w={status:w.status,data:w.data,subTreeData:w.subTreeData,parallelRoutes:new Map(w.parallelRoutes)},j.set(b,w)),fillCacheWithNewSubTreeData(w,C,n.slice(2),s))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},782:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"fillLazyItemsTillLeafWithHead",{enumerable:!0,get:function(){return fillLazyItemsTillLeafWithHead}});let o=n(6313),a=n(3322);function fillLazyItemsTillLeafWithHead(t,r,n,u,i){let s=0===Object.keys(n[1]).length;if(s){t.head=u;return}for(let s in n[1]){let d=n[1][s],p=d[0],_=(0,a.createRouterCacheKey)(p);if(r){let n=r.parallelRoutes.get(s);if(n){let r=new Map(n),a=r.get(_),p=i&&a?{status:a.status,data:a.data,subTreeData:a.subTreeData,parallelRoutes:new Map(a.parallelRoutes)}:{status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map(null==a?void 0:a.parallelRoutes)};r.set(_,p),fillLazyItemsTillLeafWithHead(p,a,d,u,i),t.parallelRoutes.set(s,r);continue}}let b={status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map},m=t.parallelRoutes.get(s);m?m.set(_,b):t.parallelRoutes.set(s,new Map([[_,b]])),fillLazyItemsTillLeafWithHead(b,void 0,d,u,i)}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2800:function(t,r){"use strict";var n,o;function getPrefetchEntryCacheStatus(t){let{kind:r,prefetchTime:n,lastUsedTime:o}=t;return Date.now()<(null!=o?o:n)+3e4?o?"reusable":"fresh":"auto"===r&&Date.now()<n+3e5?"stale":"full"===r&&Date.now()<n+3e5?"reusable":"expired"}Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{PrefetchCacheEntryStatus:function(){return n},getPrefetchEntryCacheStatus:function(){return getPrefetchEntryCacheStatus}}),(o=n||(n={})).fresh="fresh",o.reusable="reusable",o.expired="expired",o.stale="stale",("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8543:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"handleMutable",{enumerable:!0,get:function(){return handleMutable}});let o=n(2082);function handleMutable(t,r){var n,a,u,i;let s=null==(a=r.shouldScroll)||a;return{buildId:t.buildId,canonicalUrl:null!=r.canonicalUrl?r.canonicalUrl===t.canonicalUrl?t.canonicalUrl:r.canonicalUrl:t.canonicalUrl,pushRef:{pendingPush:null!=r.pendingPush?r.pendingPush:t.pushRef.pendingPush,mpaNavigation:null!=r.mpaNavigation?r.mpaNavigation:t.pushRef.mpaNavigation},focusAndScrollRef:{apply:!!s&&((null==r?void 0:r.scrollableSegments)!==void 0||t.focusAndScrollRef.apply),onlyHashChange:!!r.hashFragment&&t.canonicalUrl.split("#",1)[0]===(null==(n=r.canonicalUrl)?void 0:n.split("#",1)[0]),hashFragment:s?r.hashFragment&&""!==r.hashFragment?decodeURIComponent(r.hashFragment.slice(1)):t.focusAndScrollRef.hashFragment:null,segmentPaths:s?null!=(u=null==r?void 0:r.scrollableSegments)?u:t.focusAndScrollRef.segmentPaths:[]},cache:r.cache?r.cache:t.cache,prefetchCache:r.prefetchCache?r.prefetchCache:t.prefetchCache,tree:void 0!==r.patchedTree?r.patchedTree:t.tree,nextUrl:void 0!==r.patchedTree?null!=(i=(0,o.computeChangedPath)(t.tree,r.patchedTree))?i:t.canonicalUrl:t.nextUrl}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},4819:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"invalidateCacheBelowFlightSegmentPath",{enumerable:!0,get:function(){return invalidateCacheBelowFlightSegmentPath}});let o=n(3322);function invalidateCacheBelowFlightSegmentPath(t,r,n){let a=n.length<=2,[u,i]=n,s=(0,o.createRouterCacheKey)(i),d=r.parallelRoutes.get(u);if(!d)return;let p=t.parallelRoutes.get(u);if(p&&p!==d||(p=new Map(d),t.parallelRoutes.set(u,p)),a){p.delete(s);return}let _=d.get(s),b=p.get(s);b&&_&&(b===_&&(b={status:b.status,data:b.data,subTreeData:b.subTreeData,parallelRoutes:new Map(b.parallelRoutes)},p.set(s,b)),invalidateCacheBelowFlightSegmentPath(b,_,n.slice(2)))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5303:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"invalidateCacheByRouterState",{enumerable:!0,get:function(){return invalidateCacheByRouterState}});let o=n(3322);function invalidateCacheByRouterState(t,r,n){for(let a in n[1]){let u=n[1][a][0],i=(0,o.createRouterCacheKey)(u),s=r.parallelRoutes.get(a);if(s){let r=new Map(s);r.delete(i),t.parallelRoutes.set(a,r)}}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2782:function(t,r){"use strict";function isNavigatingToNewRootLayout(t,r){let n=t[0],o=r[0];if(Array.isArray(n)&&Array.isArray(o)){if(n[0]!==o[0]||n[2]!==o[2])return!0}else if(n!==o)return!0;if(t[4])return!r[4];if(r[4])return!0;let a=Object.values(t[1])[0],u=Object.values(r[1])[0];return!a||!u||isNavigatingToNewRootLayout(a,u)}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"isNavigatingToNewRootLayout",{enumerable:!0,get:function(){return isNavigatingToNewRootLayout}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},929:function(t,r){"use strict";function readRecordValue(t){if("fulfilled"===t.status)return t.value;throw t}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"readRecordValue",{enumerable:!0,get:function(){return readRecordValue}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3682:function(t,r,n){"use strict";function fastRefreshReducerNoop(t,r){return t}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"fastRefreshReducer",{enumerable:!0,get:function(){return o}}),n(8146),n(3559),n(929),n(2301),n(8934),n(2782),n(8640),n(8543),n(2713);let o=fastRefreshReducerNoop;("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},6700:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"findHeadInCache",{enumerable:!0,get:function(){return findHeadInCache}});let o=n(3322);function findHeadInCache(t,r){let n=0===Object.keys(r).length;if(n)return t.head;for(let n in r){let[a,u]=r[n],i=t.parallelRoutes.get(n);if(!i)continue;let s=(0,o.createRouterCacheKey)(a),d=i.get(s);if(!d)continue;let p=findHeadInCache(d,u);if(p)return p}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1263:function(t,r){"use strict";function getSegmentValue(t){return Array.isArray(t)?t[1]:t}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"getSegmentValue",{enumerable:!0,get:function(){return getSegmentValue}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8640:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{handleExternalUrl:function(){return handleExternalUrl},navigateReducer:function(){return navigateReducer}});let o=n(6313),a=n(8146),u=n(3559),i=n(929),s=n(2301),d=n(4819),p=n(6443),_=n(180),b=n(8934),m=n(3006),j=n(2782),C=n(9706),w=n(8543),D=n(2713),U=n(2800),B=n(3627),$=n(3709);function handleExternalUrl(t,r,n,o){return r.previousTree=t.tree,r.mpaNavigation=!0,r.canonicalUrl=n,r.pendingPush=o,r.scrollableSegments=void 0,(0,w.handleMutable)(t,r)}function generateSegmentsFromPatch(t){let r=[],[n,o]=t;if(0===Object.keys(o).length)return[[n]];for(let[t,a]of Object.entries(o))for(let o of generateSegmentsFromPatch(a))""===n?r.push([t,...o]):r.push([n,t,...o]);return r}function addRefetchToLeafSegments(t,r,n,a,u){let i=!1;t.status=o.CacheStates.READY,t.subTreeData=r.subTreeData,t.parallelRoutes=new Map(r.parallelRoutes);let s=generateSegmentsFromPatch(a).map(t=>[...n,...t]);for(let n of s){let o=(0,p.fillCacheWithDataProperty)(t,r,n,u);(null==o?void 0:o.bailOptimistic)||(i=!0)}return i}function navigateReducer(t,r){let{url:n,isExternalUrl:K,navigateType:q,cache:ee,mutable:et,forceOptimisticNavigation:er,shouldScroll:en}=r,{pathname:eo,hash:eu}=n,el=(0,s.createHrefFromUrl)(n),ei="push"===q;(0,B.prunePrefetchCache)(t.prefetchCache);let ec=JSON.stringify(et.previousTree)===JSON.stringify(t.tree);if(ec)return(0,w.handleMutable)(t,et);if(K)return handleExternalUrl(t,et,n.toString(),ei);let es=t.prefetchCache.get((0,s.createHrefFromUrl)(n,!1));if(er&&(null==es?void 0:es.kind)!==C.PrefetchKind.TEMPORARY){let r=eo.split("/");r.push("__PAGE__");let i=(0,_.createOptimisticTree)(r,t.tree,!1),d={...ee};d.status=o.CacheStates.READY,d.subTreeData=t.cache.subTreeData,d.parallelRoutes=new Map(t.cache.parallelRoutes);let b=null,m=r.slice(1).map(t=>["children",t]).flat(),j=(0,p.fillCacheWithDataProperty)(d,t.cache,m,()=>(b||(b=(0,u.createRecordFromThenable)((0,a.fetchServerResponse)(n,i,t.nextUrl,t.buildId))),b),!0);if(!(null==j?void 0:j.bailOptimistic))return et.previousTree=t.tree,et.patchedTree=i,et.pendingPush=ei,et.hashFragment=eu,et.shouldScroll=en,et.scrollableSegments=[],et.cache=d,et.canonicalUrl=el,t.prefetchCache.set((0,s.createHrefFromUrl)(n,!1),{data:b?(0,u.createRecordFromThenable)(Promise.resolve(b)):null,kind:C.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:t.tree,lastUsedTime:Date.now()}),(0,w.handleMutable)(t,et)}if(!es){let r=(0,u.createRecordFromThenable)((0,a.fetchServerResponse)(n,t.tree,t.nextUrl,t.buildId,void 0)),o={data:(0,u.createRecordFromThenable)(Promise.resolve(r)),kind:C.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:t.tree,lastUsedTime:null};t.prefetchCache.set((0,s.createHrefFromUrl)(n,!1),o),es=o}let ef=(0,U.getPrefetchEntryCacheStatus)(es),{treeAtTimeOfPrefetch:ed,data:ep}=es;$.prefetchQueue.bump(ep);let[eh,e_,ey]=(0,i.readRecordValue)(ep);if(es.lastUsedTime||(es.lastUsedTime=Date.now()),"string"==typeof eh)return handleExternalUrl(t,et,eh,ei);let eg=t.tree,eb=t.cache,em=[];for(let r of eh){let i=r.slice(0,-4),s=r.slice(-3)[0],p=["",...i],_=(0,b.applyRouterStatePatchToTree)(p,eg,s);if(null===_&&(_=(0,b.applyRouterStatePatchToTree)(p,ed,s)),null!==_){if((0,j.isNavigatingToNewRootLayout)(eg,_))return handleExternalUrl(t,et,el,ei);let b=!ey&&(0,D.applyFlightData)(eb,ee,r,"auto"===es.kind&&ef===U.PrefetchCacheEntryStatus.reusable);b||ef!==U.PrefetchCacheEntryStatus.stale||(b=addRefetchToLeafSegments(ee,eb,i,s,()=>(0,u.createRecordFromThenable)((0,a.fetchServerResponse)(n,eg,t.nextUrl,t.buildId))));let C=(0,m.shouldHardNavigate)(p,eg);for(let t of(C?(ee.status=o.CacheStates.READY,ee.subTreeData=eb.subTreeData,(0,d.invalidateCacheBelowFlightSegmentPath)(ee,eb,i),et.cache=ee):b&&(et.cache=ee),eb=ee,eg=_,generateSegmentsFromPatch(s))){let r=[...i,...t];"__DEFAULT__"!==r[r.length-1]&&em.push(r)}}}return et.previousTree=t.tree,et.patchedTree=eg,et.canonicalUrl=e_?(0,s.createHrefFromUrl)(e_):el,et.pendingPush=ei,et.scrollableSegments=em,et.hashFragment=eu,et.shouldScroll=en,(0,w.handleMutable)(t,et)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3709:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{prefetchQueue:function(){return _},prefetchReducer:function(){return prefetchReducer}});let o=n(2301),a=n(8146),u=n(9706),i=n(3559),s=n(3627),d=n(8343),p=n(839),_=new p.PromiseQueue(5);function prefetchReducer(t,r){(0,s.prunePrefetchCache)(t.prefetchCache);let{url:n}=r;n.searchParams.delete(d.NEXT_RSC_UNION_QUERY);let p=(0,o.createHrefFromUrl)(n,!1),b=t.prefetchCache.get(p);if(b&&(b.kind===u.PrefetchKind.TEMPORARY&&t.prefetchCache.set(p,{...b,kind:r.kind}),!(b.kind===u.PrefetchKind.AUTO&&r.kind===u.PrefetchKind.FULL)))return t;let m=(0,i.createRecordFromThenable)(_.enqueue(()=>(0,a.fetchServerResponse)(n,t.tree,t.nextUrl,t.buildId,r.kind)));return t.prefetchCache.set(p,{treeAtTimeOfPrefetch:t.tree,data:m,kind:r.kind,prefetchTime:Date.now(),lastUsedTime:null}),t}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3627:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"prunePrefetchCache",{enumerable:!0,get:function(){return prunePrefetchCache}});let o=n(2800);function prunePrefetchCache(t){for(let[r,n]of t)(0,o.getPrefetchEntryCacheStatus)(n)===o.PrefetchCacheEntryStatus.expired&&t.delete(r)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2701:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"refreshReducer",{enumerable:!0,get:function(){return refreshReducer}});let o=n(8146),a=n(3559),u=n(929),i=n(2301),s=n(8934),d=n(2782),p=n(8640),_=n(8543),b=n(6313),m=n(782);function refreshReducer(t,r){let{cache:n,mutable:j,origin:C}=r,w=t.canonicalUrl,D=t.tree,U=JSON.stringify(j.previousTree)===JSON.stringify(D);if(U)return(0,_.handleMutable)(t,j);n.data||(n.data=(0,a.createRecordFromThenable)((0,o.fetchServerResponse)(new URL(w,C),[D[0],D[1],D[2],"refetch"],t.nextUrl,t.buildId)));let[B,$]=(0,u.readRecordValue)(n.data);if("string"==typeof B)return(0,p.handleExternalUrl)(t,j,B,t.pushRef.pendingPush);for(let r of(n.data=null,B)){if(3!==r.length)return console.log("REFRESH FAILED"),t;let[o]=r,a=(0,s.applyRouterStatePatchToTree)([""],D,o);if(null===a)throw Error("SEGMENT MISMATCH");if((0,d.isNavigatingToNewRootLayout)(D,a))return(0,p.handleExternalUrl)(t,j,w,t.pushRef.pendingPush);let u=$?(0,i.createHrefFromUrl)($):void 0;$&&(j.canonicalUrl=u);let[_,C]=r.slice(-2);null!==_&&(n.status=b.CacheStates.READY,n.subTreeData=_,(0,m.fillLazyItemsTillLeafWithHead)(n,void 0,o,C),j.cache=n,j.prefetchCache=new Map),j.previousTree=D,j.patchedTree=a,j.canonicalUrl=w,D=a}return(0,_.handleMutable)(t,j)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1705:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"restoreReducer",{enumerable:!0,get:function(){return restoreReducer}});let o=n(2301);function restoreReducer(t,r){let{url:n,tree:a}=r,u=(0,o.createHrefFromUrl)(n);return{buildId:t.buildId,canonicalUrl:u,pushRef:t.pushRef,focusAndScrollRef:t.focusAndScrollRef,cache:t.cache,prefetchCache:t.prefetchCache,tree:a,nextUrl:n.pathname}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1383:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"serverActionReducer",{enumerable:!0,get:function(){return serverActionReducer}});let o=n(5231),a=n(8343),u=n(3559),i=n(929),s=n(9872),d=n(2301),p=n(8640),_=n(8934),b=n(2782),m=n(6313),j=n(8543),C=n(782),{createFromFetch:w,encodeReply:D}=n(6671);async function fetchServerAction(t,r){let n,{actionId:u,actionArgs:i}=r,d=await D(i),p=await fetch("",{method:"POST",headers:{Accept:a.RSC_CONTENT_TYPE_HEADER,[a.ACTION]:u,[a.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(t.tree)),...t.nextUrl?{[a.NEXT_URL]:t.nextUrl}:{}},body:d}),_=p.headers.get("x-action-redirect");try{let t=JSON.parse(p.headers.get("x-action-revalidated")||"[[],0,0]");n={paths:t[0]||[],tag:!!t[1],cookie:t[2]}}catch(t){n={paths:[],tag:!1,cookie:!1}}let b=_?new URL((0,s.addBasePath)(_),new URL(t.canonicalUrl,window.location.href)):void 0;if(p.headers.get("content-type")===a.RSC_CONTENT_TYPE_HEADER){let t=await w(Promise.resolve(p),{callServer:o.callServer});if(_){let[,r]=null!=t?t:[];return{actionFlightData:r,redirectLocation:b,revalidatedParts:n}}let[r,[,a]]=null!=t?t:[];return{actionResult:r,actionFlightData:a,redirectLocation:b,revalidatedParts:n}}return{redirectLocation:b,revalidatedParts:n}}function serverActionReducer(t,r){let{mutable:n,cache:o,resolve:a,reject:s}=r,w=t.canonicalUrl,D=t.tree,U=JSON.stringify(n.previousTree)===JSON.stringify(D);if(U)return(0,j.handleMutable)(t,n);if(n.inFlightServerAction){if("fulfilled"!==n.inFlightServerAction.status&&n.globalMutable.pendingNavigatePath&&n.globalMutable.pendingNavigatePath!==w)return n.inFlightServerAction.then(()=>{n.actionResultResolved||(n.inFlightServerAction=null,n.globalMutable.pendingNavigatePath=void 0,n.globalMutable.refresh(),n.actionResultResolved=!0)},()=>{}),t}else n.inFlightServerAction=(0,u.createRecordFromThenable)(fetchServerAction(t,r));try{let{actionResult:r,actionFlightData:u,redirectLocation:s}=(0,i.readRecordValue)(n.inFlightServerAction);if(s&&(t.pushRef.pendingPush=!0,n.pendingPush=!0),n.previousTree=t.tree,!u){if(n.actionResultResolved||(a(r),n.actionResultResolved=!0),s)return(0,p.handleExternalUrl)(t,n,s.href,t.pushRef.pendingPush);return t}if("string"==typeof u)return(0,p.handleExternalUrl)(t,n,u,t.pushRef.pendingPush);for(let r of(n.inFlightServerAction=null,u)){if(3!==r.length)return console.log("SERVER ACTION APPLY FAILED"),t;let[a]=r,u=(0,_.applyRouterStatePatchToTree)([""],D,a);if(null===u)throw Error("SEGMENT MISMATCH");if((0,b.isNavigatingToNewRootLayout)(D,u))return(0,p.handleExternalUrl)(t,n,w,t.pushRef.pendingPush);let[i,s]=r.slice(-2);null!==i&&(o.status=m.CacheStates.READY,o.subTreeData=i,(0,C.fillLazyItemsTillLeafWithHead)(o,void 0,a,s),n.cache=o,n.prefetchCache=new Map),n.previousTree=D,n.patchedTree=u,n.canonicalUrl=w,D=u}if(s){let t=(0,d.createHrefFromUrl)(s,!1);n.canonicalUrl=t}return n.actionResultResolved||(a(r),n.actionResultResolved=!0),(0,j.handleMutable)(t,n)}catch(r){if("rejected"===r.status)return n.actionResultResolved||(s(r.reason),n.actionResultResolved=!0),t;throw r}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5330:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"serverPatchReducer",{enumerable:!0,get:function(){return serverPatchReducer}});let o=n(2301),a=n(8934),u=n(2782),i=n(8640),s=n(2713),d=n(8543);function serverPatchReducer(t,r){let{flightData:n,previousTree:p,overrideCanonicalUrl:_,cache:b,mutable:m}=r,j=JSON.stringify(p)===JSON.stringify(t.tree);if(!j)return console.log("TREE MISMATCH"),t;if(m.previousTree)return(0,d.handleMutable)(t,m);if("string"==typeof n)return(0,i.handleExternalUrl)(t,m,n,t.pushRef.pendingPush);let C=t.tree,w=t.cache;for(let r of n){let n=r.slice(0,-4),[d]=r.slice(-3,-2),p=(0,a.applyRouterStatePatchToTree)(["",...n],C,d);if(null===p)throw Error("SEGMENT MISMATCH");if((0,u.isNavigatingToNewRootLayout)(C,p))return(0,i.handleExternalUrl)(t,m,t.canonicalUrl,t.pushRef.pendingPush);let j=_?(0,o.createHrefFromUrl)(_):void 0;j&&(m.canonicalUrl=j),(0,s.applyFlightData)(w,b,r),m.previousTree=C,m.patchedTree=p,m.cache=b,w=b,C=p}return(0,d.handleMutable)(t,m)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},9706:function(t,r){"use strict";var n,o;Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{PrefetchKind:function(){return n},ACTION_REFRESH:function(){return a},ACTION_NAVIGATE:function(){return u},ACTION_RESTORE:function(){return i},ACTION_SERVER_PATCH:function(){return s},ACTION_PREFETCH:function(){return d},ACTION_FAST_REFRESH:function(){return p},ACTION_SERVER_ACTION:function(){return _}});let a="refresh",u="navigate",i="restore",s="server-patch",d="prefetch",p="fast-refresh",_="server-action";(o=n||(n={})).AUTO="auto",o.FULL="full",o.TEMPORARY="temporary",("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},7205:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"reducer",{enumerable:!0,get:function(){return b}});let o=n(9706),a=n(8640),u=n(5330),i=n(1705),s=n(2701),d=n(3709),p=n(3682),_=n(1383);function clientReducer(t,r){switch(r.type){case o.ACTION_NAVIGATE:return(0,a.navigateReducer)(t,r);case o.ACTION_SERVER_PATCH:return(0,u.serverPatchReducer)(t,r);case o.ACTION_RESTORE:return(0,i.restoreReducer)(t,r);case o.ACTION_REFRESH:return(0,s.refreshReducer)(t,r);case o.ACTION_FAST_REFRESH:return(0,p.fastRefreshReducer)(t,r);case o.ACTION_PREFETCH:return(0,d.prefetchReducer)(t,r);case o.ACTION_SERVER_ACTION:return(0,_.serverActionReducer)(t,r);default:throw Error("Unknown action")}}let b=clientReducer;("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3006:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"shouldHardNavigate",{enumerable:!0,get:function(){return shouldHardNavigate}});let o=n(8163);function shouldHardNavigate(t,r){let[n,a]=r,[u,i]=t;if(!(0,o.matchSegment)(u,n))return!!Array.isArray(u);let s=t.length<=2;return!s&&shouldHardNavigate(t.slice(2),a[i])}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8519:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createSearchParamsBailoutProxy",{enumerable:!0,get:function(){return createSearchParamsBailoutProxy}});let o=n(2004);function createSearchParamsBailoutProxy(){return new Proxy({},{get(t,r){"string"==typeof r&&(0,o.staticGenerationBailout)("searchParams."+r)}})}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8985:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"staticGenerationAsyncStorage",{enumerable:!0,get:function(){return a}});let o=n(7346),a=(0,o.createAsyncLocalStorage)();("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2004:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"staticGenerationBailout",{enumerable:!0,get:function(){return staticGenerationBailout}});let o=n(1351),a=n(5437),u=n(8985);let StaticGenBailoutError=class StaticGenBailoutError extends Error{constructor(...t){super(...t),this.code="NEXT_STATIC_GEN_BAILOUT"}};function formatErrorMessage(t,r){let{dynamic:n,link:o}=r||{};return"Page"+(n?' with `dynamic = "'+n+'"`':"")+" couldn't be rendered statically because it used `"+t+"`."+(o?" See more info here: "+o:"")}let staticGenerationBailout=(t,r)=>{let n=u.staticGenerationAsyncStorage.getStore();if(!n)return!1;if(n.forceStatic)return!0;if(n.dynamicShouldError){var i;throw new StaticGenBailoutError(formatErrorMessage(t,{...r,dynamic:null!=(i=null==r?void 0:r.dynamic)?i:"error"}))}let s=formatErrorMessage(t,{...r,link:"https://nextjs.org/docs/messages/dynamic-server-error"});if((0,a.maybePostpone)(n,s),n.revalidate=0,(null==r?void 0:r.dynamic)||(n.staticPrefetchBailout=!0),n.isStaticGeneration){let r=new o.DynamicServerError(s);throw n.dynamicUsageDescription=t,n.dynamicUsageStack=r.stack,r}return!1};("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8297:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"default",{enumerable:!0,get:function(){return StaticGenerationSearchParamsBailoutProvider}});let o=n(1024),a=o._(n(2265)),u=n(8519);function StaticGenerationSearchParamsBailoutProvider(t){let{Component:r,propsForComponent:n,isStaticGeneration:o}=t;if(o){let t=(0,u.createSearchParamsBailoutProxy)();return a.default.createElement(r,{searchParams:t,...n})}return a.default.createElement(r,n)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2327:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"useReducerWithReduxDevtools",{enumerable:!0,get:function(){return a}});let o=n(2265);function normalizeRouterState(t){if(t instanceof Map){let r={};for(let[n,o]of t.entries()){if("function"==typeof o){r[n]="fn()";continue}if("object"==typeof o&&null!==o){if(o.$$typeof){r[n]=o.$$typeof.toString();continue}if(o._bundlerConfig){r[n]="FlightData";continue}}r[n]=normalizeRouterState(o)}return r}if("object"==typeof t&&null!==t){let r={};for(let n in t){let o=t[n];if("function"==typeof o){r[n]="fn()";continue}if("object"==typeof o&&null!==o){if(o.$$typeof){r[n]=o.$$typeof.toString();continue}if(o.hasOwnProperty("_bundlerConfig")){r[n]="FlightData";continue}}r[n]=normalizeRouterState(o)}return r}return Array.isArray(t)?t.map(normalizeRouterState):t}function devToolReducer(t,r){return(n,o)=>{let a=t(n,o);return r.current&&r.current.send(o,normalizeRouterState(a)),a}}function useReducerWithReduxDevtoolsImpl(t,r){let n=(0,o.useRef)(),a=(0,o.useRef)();(0,o.useEffect)(()=>{if(!n.current&&!1!==a.current){if(void 0===a.current&&void 0===window.__REDUX_DEVTOOLS_EXTENSION__){a.current=!1;return}return n.current=window.__REDUX_DEVTOOLS_EXTENSION__.connect({instanceId:8e3,name:"next-router"}),n.current&&n.current.init(normalizeRouterState(r)),()=>{n.current=void 0}}},[r]);let[u,i]=(0,o.useReducer)(devToolReducer(t,n),r),s=(0,o.useCallback)(()=>{n.current&&n.current.send({type:"RENDER_SYNC"},normalizeRouterState(u))},[u]);return[u,i,s]}let a=useReducerWithReduxDevtoolsImpl;("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},6746:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"hasBasePath",{enumerable:!0,get:function(){return hasBasePath}});let o=n(1446);function hasBasePath(t){return(0,o.pathHasPrefix)(t,"")}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3997:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return normalizePathTrailingSlash}});let o=n(9006),a=n(9466),normalizePathTrailingSlash=t=>{if(!t.startsWith("/"))return t;let{pathname:r,query:n,hash:u}=(0,a.parsePath)(t);return""+(0,o.removeTrailingSlash)(r)+n+u};("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2504:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"default",{enumerable:!0,get:function(){return onRecoverableError}});let o=n(1283);function onRecoverableError(t){let r="function"==typeof reportError?reportError:t=>{window.console.error(t)};t.digest!==o.NEXT_DYNAMIC_NO_SSR_CODE&&r(t)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3714:function(t,r,n){"use strict";function removeBasePath(t){return t}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"removeBasePath",{enumerable:!0,get:function(){return removeBasePath}}),n(6746),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},6313:function(t,r,n){"use strict";var o,a;Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{CacheStates:function(){return o},AppRouterContext:function(){return s},LayoutRouterContext:function(){return d},GlobalLayoutRouterContext:function(){return p},TemplateContext:function(){return _}});let u=n(1024),i=u._(n(2265));(a=o||(o={})).LAZY_INITIALIZED="LAZYINITIALIZED",a.DATA_FETCH="DATAFETCH",a.READY="READY";let s=i.default.createContext(null),d=i.default.createContext(null),p=i.default.createContext(null),_=i.default.createContext(null)},6360:function(t,r){"use strict";function djb2Hash(t){let r=5381;for(let n=0;n<t.length;n++){let o=t.charCodeAt(n);r=(r<<5)+r+o}return Math.abs(r)}function hexHash(t){return djb2Hash(t).toString(36).slice(0,5)}Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{djb2Hash:function(){return djb2Hash},hexHash:function(){return hexHash}})},1852:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"HeadManagerContext",{enumerable:!0,get:function(){return u}});let o=n(1024),a=o._(n(2265)),u=a.default.createContext({})},7407:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{SearchParamsContext:function(){return a},PathnameContext:function(){return u},PathParamsContext:function(){return i}});let o=n(2265),a=(0,o.createContext)(null),u=(0,o.createContext)(null),i=(0,o.createContext)(null)},1283:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{NEXT_DYNAMIC_NO_SSR_CODE:function(){return n},throwWithNoSSR:function(){return throwWithNoSSR}});let n="NEXT_DYNAMIC_NO_SSR_CODE";function throwWithNoSSR(){let t=Error(n);throw t.digest=n,t}},951:function(t,r){"use strict";function ensureLeadingSlash(t){return t.startsWith("/")?t:"/"+t}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"ensureLeadingSlash",{enumerable:!0,get:function(){return ensureLeadingSlash}})},8356:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"addPathPrefix",{enumerable:!0,get:function(){return addPathPrefix}});let o=n(9466);function addPathPrefix(t,r){if(!t.startsWith("/")||!r)return t;let{pathname:n,query:a,hash:u}=(0,o.parsePath)(t);return""+r+n+a+u}},3701:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{normalizeAppPath:function(){return normalizeAppPath},normalizeRscURL:function(){return normalizeRscURL},normalizePostponedURL:function(){return normalizePostponedURL}});let o=n(951),a=n(1706);function normalizeAppPath(t){return(0,o.ensureLeadingSlash)(t.split("/").reduce((t,r,n,o)=>!r||(0,a.isGroupSegment)(r)||"@"===r[0]||("page"===r||"route"===r)&&n===o.length-1?t:t+"/"+r,""))}function normalizeRscURL(t){return t.replace(/\.rsc($|\?)/,"$1")}function normalizePostponedURL(t){let r=new URL(t),{pathname:n}=r;return n&&n.startsWith("/_next/postponed")?(r.pathname=n.substring(16)||"/",r.toString()):t}},280:function(t,r){"use strict";function handleSmoothScroll(t,r){if(void 0===r&&(r={}),r.onlyHashChange){t();return}let n=document.documentElement,o=n.style.scrollBehavior;n.style.scrollBehavior="auto",r.dontForceLayout||n.getClientRects(),t(),n.style.scrollBehavior=o}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"handleSmoothScroll",{enumerable:!0,get:function(){return handleSmoothScroll}})},2169:function(t,r){"use strict";function isBot(t){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(t)}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"isBot",{enumerable:!0,get:function(){return isBot}})},9466:function(t,r){"use strict";function parsePath(t){let r=t.indexOf("#"),n=t.indexOf("?"),o=n>-1&&(r<0||n<r);return o||r>-1?{pathname:t.substring(0,o?n:r),query:o?t.substring(n,r>-1?r:void 0):"",hash:r>-1?t.slice(r):""}:{pathname:t,query:"",hash:""}}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"parsePath",{enumerable:!0,get:function(){return parsePath}})},1446:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"pathHasPrefix",{enumerable:!0,get:function(){return pathHasPrefix}});let o=n(9466);function pathHasPrefix(t,r){if("string"!=typeof t)return!1;let{pathname:n}=(0,o.parsePath)(t);return n===r||n.startsWith(r+"/")}},9006:function(t,r){"use strict";function removeTrailingSlash(t){return t.replace(/\/$/,"")||"/"}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"removeTrailingSlash",{enumerable:!0,get:function(){return removeTrailingSlash}})},1706:function(t,r){"use strict";function isGroupSegment(t){return"("===t[0]&&t.endsWith(")")}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"isGroupSegment",{enumerable:!0,get:function(){return isGroupSegment}})},3972:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{ServerInsertedHTMLContext:function(){return u},useServerInsertedHTML:function(){return useServerInsertedHTML}});let o=n(8533),a=o._(n(2265)),u=a.default.createContext(null);function useServerInsertedHTML(t){let r=(0,a.useContext)(u);r&&r(t)}},7346:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createAsyncLocalStorage",{enumerable:!0,get:function(){return createAsyncLocalStorage}});let n=Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available");let FakeAsyncLocalStorage=class FakeAsyncLocalStorage{disable(){throw n}getStore(){}run(){throw n}exit(){throw n}enterWith(){throw n}};let o=globalThis.AsyncLocalStorage;function createAsyncLocalStorage(){return o?new o:new FakeAsyncLocalStorage}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},4040:function(t,r,n){"use strict";var o=n(4887);r.createRoot=o.createRoot,r.hydrateRoot=o.hydrateRoot},4887:function(t,r,n){"use strict";function checkDCE(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE)}catch(t){console.error(t)}}checkDCE(),t.exports=n(4417)},7950:function(t,r,n){"use strict";/** + * @license React + * react-server-dom-webpack-client.browser.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var o=n(4887),a=n(2265),u={stream:!0};function v(t,r){if(t){var n=t[r[0]];if(t=n[r[2]])n=t.name;else{if(!(t=n["*"]))throw Error('Could not find the module "'+r[0]+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');n=r[2]}return 4===r.length?[t.id,t.chunks,n,1]:[t.id,t.chunks,n]}return r}var i=new Map;function x(t){var r=n(t);return"function"!=typeof r.then||"fulfilled"===r.status?null:(r.then(function(t){r.status="fulfilled",r.value=t},function(t){r.status="rejected",r.reason=t}),r)}function y(){}function z(t){for(var r=t[1],o=[],a=0;a<r.length;){var u=r[a++],d=r[a++],p=i.get(u);void 0===p?(s.set(u,d),d=n.e(u),o.push(d),p=i.set.bind(i,u,null),d.then(p,y),i.set(u,d)):null!==p&&o.push(p)}return 4===t.length?0===o.length?x(t[0]):Promise.all(o).then(function(){return x(t[0])}):0<o.length?Promise.all(o):null}var s=new Map,d=n.u;n.u=function(t){var r=s.get(t);return void 0!==r?r:d(t)};var p=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Dispatcher,_=Symbol.for("react.element"),b=Symbol.for("react.provider"),m=Symbol.for("react.server_context"),j=Symbol.for("react.lazy"),C=Symbol.for("react.default_value"),w=Symbol.iterator;function ea(t){return null===t||"object"!=typeof t?null:"function"==typeof(t=w&&t[w]||t["@@iterator"])?t:null}var D=Array.isArray,U=Object.getPrototypeOf,B=Object.prototype,$=new WeakMap;function ia(t){return Number.isFinite(t)?0===t&&-1/0==1/t?"$-0":t:1/0===t?"$Infinity":-1/0===t?"$-Infinity":"$NaN"}function ja(t,r,n,o){function l(t,s){if(null===s)return null;if("object"==typeof s){if("function"==typeof s.then){null===i&&(i=new FormData),u++;var d=a++;return s.then(function(t){t=JSON.stringify(t,l);var o=i;o.append(r+d,t),0==--u&&n(o)},function(t){o(t)}),"$@"+d.toString(16)}if(D(s))return s;if(s instanceof FormData){null===i&&(i=new FormData);var p=i,_=r+(t=a++)+"_";return s.forEach(function(t,r){p.append(_+r,t)}),"$K"+t.toString(16)}if(s instanceof Map)return s=JSON.stringify(Array.from(s),l),null===i&&(i=new FormData),t=a++,i.append(r+t,s),"$Q"+t.toString(16);if(s instanceof Set)return s=JSON.stringify(Array.from(s),l),null===i&&(i=new FormData),t=a++,i.append(r+t,s),"$W"+t.toString(16);if(ea(s))return Array.from(s);if((t=U(s))!==B&&(null===t||null!==U(t)))throw Error("Only plain objects, and a few built-ins, can be passed to Server Actions. Classes or null prototypes are not supported.");return s}if("string"==typeof s)return"Z"===s[s.length-1]&&this[t]instanceof Date?"$D"+s:s="$"===s[0]?"$"+s:s;if("boolean"==typeof s)return s;if("number"==typeof s)return ia(s);if(void 0===s)return"$undefined";if("function"==typeof s){if(void 0!==(s=$.get(s)))return s=JSON.stringify(s,l),null===i&&(i=new FormData),t=a++,i.set(r+t,s),"$F"+t.toString(16);throw Error("Client Functions cannot be passed directly to Server Functions. Only Functions passed from the Server can be passed back again.")}if("symbol"==typeof s){if(Symbol.for(t=s.description)!==s)throw Error("Only global symbols received from Symbol.for(...) can be passed to Server Functions. The symbol Symbol.for("+s.description+") cannot be found among global symbols.");return"$S"+t}if("bigint"==typeof s)return"$n"+s.toString(10);throw Error("Type "+typeof s+" is not supported as an argument to a Server Function.")}var a=1,u=0,i=null;t=JSON.stringify(t,l),null===i?n(t):(i.set(r+"0",t),0===u&&n(i))}var K=a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ContextRegistry;function L(t,r,n,o){this.status=t,this.value=r,this.reason=n,this._response=o}function ka(t){switch(t.status){case"resolved_model":M(t);break;case"resolved_module":N(t)}switch(t.status){case"fulfilled":return t.value;case"pending":case"blocked":case"cyclic":throw t;default:throw t.reason}}function O(t,r){for(var n=0;n<t.length;n++)(0,t[n])(r)}function P(t,r,n){switch(t.status){case"fulfilled":O(r,t.value);break;case"pending":case"blocked":case"cyclic":t.value=r,t.reason=n;break;case"rejected":n&&O(n,t.reason)}}function Q(t,r){if("pending"===t.status||"blocked"===t.status){var n=t.reason;t.status="rejected",t.reason=r,null!==n&&O(n,r)}}function R(t,r){if("pending"===t.status||"blocked"===t.status){var n=t.value,o=t.reason;t.status="resolved_module",t.value=r,null!==n&&(N(t),P(t,n,o))}}L.prototype=Object.create(Promise.prototype),L.prototype.then=function(t,r){switch(this.status){case"resolved_model":M(this);break;case"resolved_module":N(this)}switch(this.status){case"fulfilled":t(this.value);break;case"pending":case"blocked":case"cyclic":t&&(null===this.value&&(this.value=[]),this.value.push(t)),r&&(null===this.reason&&(this.reason=[]),this.reason.push(r));break;default:r(this.reason)}};var q=null,ee=null;function M(t){var r=q,n=ee;q=t,ee=null;var o=t.value;t.status="cyclic",t.value=null,t.reason=null;try{var a=JSON.parse(o,t._response._fromJSON);if(null!==ee&&0<ee.deps)ee.value=a,t.status="blocked",t.value=null,t.reason=null;else{var u=t.value;t.status="fulfilled",t.value=a,null!==u&&O(u,a)}}catch(r){t.status="rejected",t.reason=r}finally{q=r,ee=n}}function N(t){try{var r=t.value,o=n(r[0]);if(4===r.length&&"function"==typeof o.then){if("fulfilled"===o.status)o=o.value;else throw o.reason}var a="*"===r[2]?o:""===r[2]?o.__esModule?o.default:o:o[r[2]];t.status="fulfilled",t.value=a}catch(r){t.status="rejected",t.reason=r}}function V(t,r){t._chunks.forEach(function(t){"pending"===t.status&&Q(t,r)})}function W(t,r){var n=t._chunks,o=n.get(r);return o||(o=new L("pending",null,null,t),n.set(r,o)),o}function la(t,r,n,o){if(ee){var a=ee;o||a.deps++}else a=ee={deps:o?0:1,value:null};return function(o){r[n]=o,a.deps--,0===a.deps&&"blocked"===t.status&&(o=t.value,t.status="fulfilled",t.value=a.value,null!==o&&O(o,a.value))}}function ma(t){return function(r){return Q(t,r)}}function na(t,r){function c(){var t=Array.prototype.slice.call(arguments),n=r.bound;return n?"fulfilled"===n.status?o(r.id,n.value.concat(t)):Promise.resolve(n).then(function(n){return o(r.id,n.concat(t))}):o(r.id,t)}var n,o=t._callServer;return n=c,$.set(n,r),c}function X(t,r){if("resolved_model"===(t=W(t,r)).status&&M(t),"fulfilled"===t.status)return t.value;throw t.reason}function oa(t,r,n,o){if("$"===o[0]){if("$"===o)return _;switch(o[1]){case"$":return o.slice(1);case"L":return{$$typeof:j,_payload:t=W(t,r=parseInt(o.slice(2),16)),_init:ka};case"@":return W(t,r=parseInt(o.slice(2),16));case"S":return Symbol.for(o.slice(2));case"P":return K[t=o.slice(2)]||((r={$$typeof:m,_currentValue:C,_currentValue2:C,_defaultValue:C,_threadCount:0,Provider:null,Consumer:null,_globalName:t}).Provider={$$typeof:b,_context:r},K[t]=r),K[t].Provider;case"F":return r=X(t,r=parseInt(o.slice(2),16)),na(t,r);case"Q":return t=X(t,r=parseInt(o.slice(2),16)),new Map(t);case"W":return t=X(t,r=parseInt(o.slice(2),16)),new Set(t);case"I":return 1/0;case"-":return"$-0"===o?-0:-1/0;case"N":return NaN;case"u":return;case"D":return new Date(Date.parse(o.slice(2)));case"n":return BigInt(o.slice(2));default:switch((t=W(t,o=parseInt(o.slice(1),16))).status){case"resolved_model":M(t);break;case"resolved_module":N(t)}switch(t.status){case"fulfilled":return t.value;case"pending":case"blocked":case"cyclic":return o=q,t.then(la(o,r,n,"cyclic"===t.status),ma(o)),null;default:throw t.reason}}}return o}function pa(){throw Error('Trying to call a function from "use server" but the callServer option was not implemented in your router runtime.')}function Y(t,r,n,o){return(t={_bundlerConfig:t,_moduleLoading:r,_callServer:void 0!==n?n:pa,_nonce:o,_chunks:new Map,_stringDecoder:new TextDecoder,_fromJSON:null,_rowState:0,_rowID:0,_rowTag:0,_rowLength:0,_buffer:[]})._fromJSON=qa(t),t}function ra(t,r,n){var o=t._chunks,a=o.get(r);n=JSON.parse(n,t._fromJSON);var u=v(t._bundlerConfig,n);if(n=z(u)){if(a){var i=a;i.status="blocked"}else i=new L("blocked",null,null,t),o.set(r,i);n.then(function(){return R(i,u)},function(t){return Q(i,t)})}else a?R(a,u):o.set(r,new L("resolved_module",u,null,t))}function qa(t){return function(r,n){return"string"==typeof n?oa(t,this,r,n):"object"==typeof n&&null!==n?r=n[0]===_?{$$typeof:_,type:n[1],key:n[2],ref:null,props:n[3],_owner:null}:n:n}}function Z(t,r){function c(r){var o=r.value;if(r.done)V(t,Error("Connection closed."));else{var a=0,i=t._rowState,s=t._rowID,d=t._rowTag,_=t._rowLength;r=t._buffer;for(var b=o.length;a<b;){var m=-1;switch(i){case 0:58===(m=o[a++])?i=1:s=s<<4|(96<m?m-87:m-48);continue;case 1:84===(i=o[a])?(d=i,i=2,a++):64<i&&91>i?(d=i,i=3,a++):(d=0,i=3);continue;case 2:44===(m=o[a++])?i=4:_=_<<4|(96<m?m-87:m-48);continue;case 3:m=o.indexOf(10,a);break;case 4:(m=a+_)>o.length&&(m=-1)}var j=o.byteOffset+a;if(-1<m){a=new Uint8Array(o.buffer,j,m-a),_=t,j=d;var C=_._stringDecoder;d="";for(var w=0;w<r.length;w++)d+=C.decode(r[w],u);switch(d+=C.decode(a),j){case 73:ra(_,s,d);break;case 72:if(s=d[0],_=JSON.parse(d=d.slice(1),_._fromJSON),d=p.current)switch(s){case"D":d.prefetchDNS(_);break;case"C":"string"==typeof _?d.preconnect(_):d.preconnect(_[0],_[1]);break;case"L":s=_[0],a=_[1],3===_.length?d.preload(s,a,_[2]):d.preload(s,a);break;case"m":"string"==typeof _?d.preloadModule(_):d.preloadModule(_[0],_[1]);break;case"S":"string"==typeof _?d.preinitStyle(_):d.preinitStyle(_[0],0===_[1]?void 0:_[1],3===_.length?_[2]:void 0);break;case"X":"string"==typeof _?d.preinitScript(_):d.preinitScript(_[0],_[1]);break;case"M":"string"==typeof _?d.preinitModuleScript(_):d.preinitModuleScript(_[0],_[1])}break;case 69:a=(d=JSON.parse(d)).digest,(d=Error("An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.")).stack="Error: "+d.message,d.digest=a,(j=(a=_._chunks).get(s))?Q(j,d):a.set(s,new L("rejected",null,d,_));break;case 84:_._chunks.set(s,new L("fulfilled",d,null,_));break;default:(j=(a=_._chunks).get(s))?(_=j,s=d,"pending"===_.status&&(d=_.value,a=_.reason,_.status="resolved_model",_.value=s,null!==d&&(M(_),P(_,d,a)))):a.set(s,new L("resolved_model",d,null,_))}a=m,3===i&&a++,_=s=d=i=0,r.length=0}else{o=new Uint8Array(o.buffer,j,o.byteLength-a),r.push(o),_-=o.byteLength;break}}return t._rowState=i,t._rowID=s,t._rowTag=d,t._rowLength=_,n.read().then(c).catch(e)}}function e(r){V(t,r)}var n=r.getReader();n.read().then(c).catch(e)}r.createFromFetch=function(t,r){var n=Y(null,null,r&&r.callServer?r.callServer:void 0,void 0);return t.then(function(t){Z(n,t.body)},function(t){V(n,t)}),W(n,0)},r.createFromReadableStream=function(t,r){return Z(r=Y(null,null,r&&r.callServer?r.callServer:void 0,void 0),t),W(r,0)},r.createServerReference=function(t,r){var n;function c(){var n=Array.prototype.slice.call(arguments);return r(t,n)}return n=c,$.set(n,{id:t,bound:null}),c},r.encodeReply=function(t){return new Promise(function(r,n){ja(t,"",r,n)})}},6703:function(t,r,n){"use strict";t.exports=n(7950)},6671:function(t,r,n){"use strict";t.exports=n(6703)},7869:function(t,r){"use strict";/** + * @license React + * react.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var n=Symbol.for("react.element"),o=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),u=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),s=Symbol.for("react.provider"),d=Symbol.for("react.context"),p=Symbol.for("react.forward_ref"),_=Symbol.for("react.suspense"),b=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),j=Symbol.iterator;function A(t){return null===t||"object"!=typeof t?null:"function"==typeof(t=j&&t[j]||t["@@iterator"])?t:null}var C={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},w=Object.assign,D={};function E(t,r,n){this.props=t,this.context=r,this.refs=D,this.updater=n||C}function F(){}function G(t,r,n){this.props=t,this.context=r,this.refs=D,this.updater=n||C}E.prototype.isReactComponent={},E.prototype.setState=function(t,r){if("object"!=typeof t&&"function"!=typeof t&&null!=t)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,r,"setState")},E.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")},F.prototype=E.prototype;var U=G.prototype=new F;U.constructor=G,w(U,E.prototype),U.isPureReactComponent=!0;var B=Array.isArray,$=Object.prototype.hasOwnProperty,K={current:null},q={key:!0,ref:!0,__self:!0,__source:!0};function M(t,r,o){var a,u={},i=null,s=null;if(null!=r)for(a in void 0!==r.ref&&(s=r.ref),void 0!==r.key&&(i=""+r.key),r)$.call(r,a)&&!q.hasOwnProperty(a)&&(u[a]=r[a]);var d=arguments.length-2;if(1===d)u.children=o;else if(1<d){for(var p=Array(d),_=0;_<d;_++)p[_]=arguments[_+2];u.children=p}if(t&&t.defaultProps)for(a in d=t.defaultProps)void 0===u[a]&&(u[a]=d[a]);return{$$typeof:n,type:t,key:i,ref:s,props:u,_owner:K.current}}function N(t,r){return{$$typeof:n,type:t.type,key:r,ref:t.ref,props:t.props,_owner:t._owner}}function O(t){return"object"==typeof t&&null!==t&&t.$$typeof===n}function escape(t){var r={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(t){return r[t]})}var ee=/\/+/g;function Q(t,r){return"object"==typeof t&&null!==t&&null!=t.key?escape(""+t.key):r.toString(36)}function R(t,r,a,u,i){var s=typeof t;("undefined"===s||"boolean"===s)&&(t=null);var d=!1;if(null===t)d=!0;else switch(s){case"string":case"number":d=!0;break;case"object":switch(t.$$typeof){case n:case o:d=!0}}if(d)return i=i(d=t),t=""===u?"."+Q(d,0):u,B(i)?(a="",null!=t&&(a=t.replace(ee,"$&/")+"/"),R(i,r,a,"",function(t){return t})):null!=i&&(O(i)&&(i=N(i,a+(!i.key||d&&d.key===i.key?"":(""+i.key).replace(ee,"$&/")+"/")+t)),r.push(i)),1;if(d=0,u=""===u?".":u+":",B(t))for(var p=0;p<t.length;p++){var _=u+Q(s=t[p],p);d+=R(s,r,a,_,i)}else if("function"==typeof(_=A(t)))for(t=_.call(t),p=0;!(s=t.next()).done;)_=u+Q(s=s.value,p++),d+=R(s,r,a,_,i);else if("object"===s)throw Error("Objects are not valid as a React child (found: "+("[object Object]"===(r=String(t))?"object with keys {"+Object.keys(t).join(", ")+"}":r)+"). If you meant to render a collection of children, use an array instead.");return d}function S(t,r,n){if(null==t)return t;var o=[],a=0;return R(t,o,"","",function(t){return r.call(n,t,a++)}),o}function T(t){if(-1===t._status){var r=t._result;(r=r()).then(function(r){(0===t._status||-1===t._status)&&(t._status=1,t._result=r)},function(r){(0===t._status||-1===t._status)&&(t._status=2,t._result=r)}),-1===t._status&&(t._status=0,t._result=r)}if(1===t._status)return t._result.default;throw t._result}var et={current:null};function V(){return new WeakMap}function W(){return{s:0,v:void 0,o:null,p:null}}var er={current:null},en={transition:null};r.Children={map:S,forEach:function(t,r,n){S(t,function(){r.apply(this,arguments)},n)},count:function(t){var r=0;return S(t,function(){r++}),r},toArray:function(t){return S(t,function(t){return t})||[]},only:function(t){if(!O(t))throw Error("React.Children.only expected to receive a single React element child.");return t}},r.Component=E,r.Fragment=a,r.Profiler=i,r.PureComponent=G,r.StrictMode=u,r.Suspense=_,r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED={ReactCurrentDispatcher:er,ReactCurrentCache:et,ReactCurrentBatchConfig:en,ReactCurrentOwner:K},r.cache=function(t){return function(){var r=et.current;if(!r)return t.apply(null,arguments);var n=r.getCacheForType(V);void 0===(r=n.get(t))&&(r=W(),n.set(t,r)),n=0;for(var o=arguments.length;n<o;n++){var a=arguments[n];if("function"==typeof a||"object"==typeof a&&null!==a){var u=r.o;null===u&&(r.o=u=new WeakMap),void 0===(r=u.get(a))&&(r=W(),u.set(a,r))}else null===(u=r.p)&&(r.p=u=new Map),void 0===(r=u.get(a))&&(r=W(),u.set(a,r))}if(1===r.s)return r.v;if(2===r.s)throw r.v;try{var i=t.apply(null,arguments);return(n=r).s=1,n.v=i}catch(t){throw(i=r).s=2,i.v=t,t}}},r.cloneElement=function(t,r,o){if(null==t)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+t+".");var a=w({},t.props),u=t.key,i=t.ref,s=t._owner;if(null!=r){if(void 0!==r.ref&&(i=r.ref,s=K.current),void 0!==r.key&&(u=""+r.key),t.type&&t.type.defaultProps)var d=t.type.defaultProps;for(p in r)$.call(r,p)&&!q.hasOwnProperty(p)&&(a[p]=void 0===r[p]&&void 0!==d?d[p]:r[p])}var p=arguments.length-2;if(1===p)a.children=o;else if(1<p){d=Array(p);for(var _=0;_<p;_++)d[_]=arguments[_+2];a.children=d}return{$$typeof:n,type:t.type,key:u,ref:i,props:a,_owner:s}},r.createContext=function(t){return(t={$$typeof:d,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:s,_context:t},t.Consumer=t},r.createElement=M,r.createFactory=function(t){var r=M.bind(null,t);return r.type=t,r},r.createRef=function(){return{current:null}},r.forwardRef=function(t){return{$$typeof:p,render:t}},r.isValidElement=O,r.lazy=function(t){return{$$typeof:m,_payload:{_status:-1,_result:t},_init:T}},r.memo=function(t,r){return{$$typeof:b,type:t,compare:void 0===r?null:r}},r.startTransition=function(t){var r=en.transition;en.transition={};try{t()}finally{en.transition=r}},r.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.")},r.unstable_useCacheRefresh=function(){return er.current.useCacheRefresh()},r.use=function(t){return er.current.use(t)},r.useCallback=function(t,r){return er.current.useCallback(t,r)},r.useContext=function(t){return er.current.useContext(t)},r.useDebugValue=function(){},r.useDeferredValue=function(t,r){return er.current.useDeferredValue(t,r)},r.useEffect=function(t,r){return er.current.useEffect(t,r)},r.useId=function(){return er.current.useId()},r.useImperativeHandle=function(t,r,n){return er.current.useImperativeHandle(t,r,n)},r.useInsertionEffect=function(t,r){return er.current.useInsertionEffect(t,r)},r.useLayoutEffect=function(t,r){return er.current.useLayoutEffect(t,r)},r.useMemo=function(t,r){return er.current.useMemo(t,r)},r.useOptimistic=function(t,r){return er.current.useOptimistic(t,r)},r.useReducer=function(t,r,n){return er.current.useReducer(t,r,n)},r.useRef=function(t){return er.current.useRef(t)},r.useState=function(t){return er.current.useState(t)},r.useSyncExternalStore=function(t,r,n){return er.current.useSyncExternalStore(t,r,n)},r.useTransition=function(){return er.current.useTransition()},r.version="18.3.0-canary-0c6348758-20231030"},2265:function(t,r,n){"use strict";t.exports=n(7869)},1756:function(t,r){"use strict";/** + * @license React + * scheduler.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */function f(t,r){var n=t.length;for(t.push(r);0<n;){var o=n-1>>>1,a=t[o];if(0<g(a,r))t[o]=r,t[n]=a,n=o;else break}}function h(t){return 0===t.length?null:t[0]}function k(t){if(0===t.length)return null;var r=t[0],n=t.pop();if(n!==r){t[0]=n;for(var o=0,a=t.length,u=a>>>1;o<u;){var i=2*(o+1)-1,s=t[i],d=i+1,p=t[d];if(0>g(s,n))d<a&&0>g(p,s)?(t[o]=p,t[d]=n,o=d):(t[o]=s,t[i]=n,o=i);else if(d<a&&0>g(p,n))t[o]=p,t[d]=n,o=d;else break}}return r}function g(t,r){var n=t.sortIndex-r.sortIndex;return 0!==n?n:t.id-r.id}if(r.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var n,o=performance;r.unstable_now=function(){return o.now()}}else{var a=Date,u=a.now();r.unstable_now=function(){return a.now()-u}}var i=[],s=[],d=1,p=null,_=3,b=!1,m=!1,j=!1,C="function"==typeof setTimeout?setTimeout:null,w="function"==typeof clearTimeout?clearTimeout:null,D="undefined"!=typeof setImmediate?setImmediate:null;function G(t){for(var r=h(s);null!==r;){if(null===r.callback)k(s);else if(r.startTime<=t)k(s),r.sortIndex=r.expirationTime,f(i,r);else break;r=h(s)}}function H(t){if(j=!1,G(t),!m){if(null!==h(i))m=!0,I();else{var r=h(s);null!==r&&J(H,r.startTime-t)}}}"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var U=!1,B=-1,$=5,K=-1;function O(){return!(r.unstable_now()-K<$)}function P(){if(U){var t=r.unstable_now();K=t;var o=!0;try{e:{m=!1,j&&(j=!1,w(B),B=-1),b=!0;var a=_;try{t:{for(G(t),p=h(i);null!==p&&!(p.expirationTime>t&&O());){var u=p.callback;if("function"==typeof u){p.callback=null,_=p.priorityLevel;var d=u(p.expirationTime<=t);if(t=r.unstable_now(),"function"==typeof d){p.callback=d,G(t),o=!0;break t}p===h(i)&&k(i),G(t)}else k(i);p=h(i)}if(null!==p)o=!0;else{var C=h(s);null!==C&&J(H,C.startTime-t),o=!1}}break e}finally{p=null,_=a,b=!1}o=void 0}}finally{o?n():U=!1}}}if("function"==typeof D)n=function(){D(P)};else if("undefined"!=typeof MessageChannel){var q=new MessageChannel,ee=q.port2;q.port1.onmessage=P,n=function(){ee.postMessage(null)}}else n=function(){C(P,0)};function I(){U||(U=!0,n())}function J(t,n){B=C(function(){t(r.unstable_now())},n)}r.unstable_IdlePriority=5,r.unstable_ImmediatePriority=1,r.unstable_LowPriority=4,r.unstable_NormalPriority=3,r.unstable_Profiling=null,r.unstable_UserBlockingPriority=2,r.unstable_cancelCallback=function(t){t.callback=null},r.unstable_continueExecution=function(){m||b||(m=!0,I())},r.unstable_forceFrameRate=function(t){0>t||125<t?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):$=0<t?Math.floor(1e3/t):5},r.unstable_getCurrentPriorityLevel=function(){return _},r.unstable_getFirstCallbackNode=function(){return h(i)},r.unstable_next=function(t){switch(_){case 1:case 2:case 3:var r=3;break;default:r=_}var n=_;_=r;try{return t()}finally{_=n}},r.unstable_pauseExecution=function(){},r.unstable_requestPaint=function(){},r.unstable_runWithPriority=function(t,r){switch(t){case 1:case 2:case 3:case 4:case 5:break;default:t=3}var n=_;_=t;try{return r()}finally{_=n}},r.unstable_scheduleCallback=function(t,n,o){var a=r.unstable_now();switch(o="object"==typeof o&&null!==o&&"number"==typeof(o=o.delay)&&0<o?a+o:a,t){case 1:var u=-1;break;case 2:u=250;break;case 5:u=1073741823;break;case 4:u=1e4;break;default:u=5e3}return u=o+u,t={id:d++,callback:n,priorityLevel:t,startTime:o,expirationTime:u,sortIndex:-1},o>a?(t.sortIndex=o,f(s,t),null===h(i)&&t===h(s)&&(j?(w(B),B=-1):j=!0,J(H,o-a))):(t.sortIndex=u,f(i,t),m||b||(m=!0,I())),t},r.unstable_shouldYield=O,r.unstable_wrapCallback=function(t){var r=_;return function(){var n=_;_=r;try{return t.apply(this,arguments)}finally{_=n}}}},8261:function(t,r,n){"use strict";t.exports=n(1756)},1824:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{NEXT_QUERY_PARAM_PREFIX:function(){return n},PRERENDER_REVALIDATE_HEADER:function(){return o},PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER:function(){return a},NEXT_DID_POSTPONE_HEADER:function(){return u},NEXT_CACHE_TAGS_HEADER:function(){return i},NEXT_CACHE_SOFT_TAGS_HEADER:function(){return s},NEXT_CACHE_REVALIDATED_TAGS_HEADER:function(){return d},NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER:function(){return p},NEXT_CACHE_TAG_MAX_LENGTH:function(){return _},NEXT_CACHE_SOFT_TAG_MAX_LENGTH:function(){return b},NEXT_CACHE_IMPLICIT_TAG_ID:function(){return m},CACHE_ONE_YEAR:function(){return j},MIDDLEWARE_FILENAME:function(){return C},MIDDLEWARE_LOCATION_REGEXP:function(){return w},INSTRUMENTATION_HOOK_FILENAME:function(){return D},PAGES_DIR_ALIAS:function(){return U},DOT_NEXT_ALIAS:function(){return B},ROOT_DIR_ALIAS:function(){return $},APP_DIR_ALIAS:function(){return K},RSC_MOD_REF_PROXY_ALIAS:function(){return q},RSC_ACTION_VALIDATE_ALIAS:function(){return ee},RSC_ACTION_PROXY_ALIAS:function(){return et},RSC_ACTION_ENCRYPTION_ALIAS:function(){return er},RSC_ACTION_CLIENT_WRAPPER_ALIAS:function(){return en},PUBLIC_DIR_MIDDLEWARE_CONFLICT:function(){return eo},SSG_GET_INITIAL_PROPS_CONFLICT:function(){return eu},SERVER_PROPS_GET_INIT_PROPS_CONFLICT:function(){return el},SERVER_PROPS_SSG_CONFLICT:function(){return ei},STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR:function(){return ec},SERVER_PROPS_EXPORT_ERROR:function(){return es},GSP_NO_RETURNED_VALUE:function(){return ef},GSSP_NO_RETURNED_VALUE:function(){return ed},UNSTABLE_REVALIDATE_RENAME_ERROR:function(){return ep},GSSP_COMPONENT_MEMBER_ERROR:function(){return eh},NON_STANDARD_NODE_ENV:function(){return e_},SSG_FALLBACK_EXPORT_ERROR:function(){return ey},ESLINT_DEFAULT_DIRS:function(){return eg},ESLINT_PROMPT_VALUES:function(){return eb},SERVER_RUNTIME:function(){return em},WEBPACK_LAYERS:function(){return eR},WEBPACK_RESOURCE_QUERIES:function(){return eS}});let n="nxtP",o="x-prerender-revalidate",a="x-prerender-revalidate-if-generated",u="x-nextjs-postponed",i="x-next-cache-tags",s="x-next-cache-soft-tags",d="x-next-revalidated-tags",p="x-next-revalidate-tag-token",_=256,b=1024,m="_N_T_",j=31536e3,C="middleware",w=`(?:src/)?${C}`,D="instrumentation",U="private-next-pages",B="private-dot-next",$="private-next-root-dir",K="private-next-app-dir",q="private-next-rsc-mod-ref-proxy",ee="private-next-rsc-action-validate",et="private-next-rsc-action-proxy",er="private-next-rsc-action-encryption",en="private-next-rsc-action-client-wrapper",eo="You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict",eu="You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps",el="You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.",ei="You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps",ec="can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props",es="pages with `getServerSideProps` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export",ef="Your `getStaticProps` function did not return an object. Did you forget to add a `return`?",ed="Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?",ep="The `unstable_revalidate` property is available for general use.\nPlease use `revalidate` instead.",eh="can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member",e_='You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env',ey="Pages with `fallback` enabled in `getStaticPaths` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export",eg=["app","pages","components","lib","src"],eb=[{title:"Strict",recommended:!0,config:{extends:"next/core-web-vitals"}},{title:"Base",config:{extends:"next"}},{title:"Cancel",config:null}],em={edge:"edge",experimentalEdge:"experimental-edge",nodejs:"nodejs"},ev={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",api:"api",middleware:"middleware",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",appMetadataRoute:"app-metadata-route",appRouteHandler:"app-route-handler"},eR={...ev,GROUP:{server:[ev.reactServerComponents,ev.actionBrowser,ev.appMetadataRoute,ev.appRouteHandler],nonClientServerTarget:[ev.middleware,ev.api],app:[ev.reactServerComponents,ev.actionBrowser,ev.appMetadataRoute,ev.appRouteHandler,ev.serverSideRendering,ev.appPagesBrowser]}},eS={edgeSSREntry:"__next_edge_ssr_entry__",metadata:"__next_metadata__",metadataRoute:"__next_metadata_route__",metadataImageMeta:"__next_metadata_image_meta__"}},5682:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"getSegmentParam",{enumerable:!0,get:function(){return getSegmentParam}});let o=n(4507);function getSegmentParam(t){let r=o.INTERCEPTION_ROUTE_MARKERS.find(r=>t.startsWith(r));return(r&&(t=t.slice(r.length)),t.startsWith("[[...")&&t.endsWith("]]"))?{type:"optional-catchall",param:t.slice(5,-2)}:t.startsWith("[...")&&t.endsWith("]")?{type:"catchall",param:t.slice(4,-1)}:t.startsWith("[")&&t.endsWith("]")?{type:"dynamic",param:t.slice(1,-1)}:null}},4507:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{INTERCEPTION_ROUTE_MARKERS:function(){return a},isInterceptionRouteAppPath:function(){return isInterceptionRouteAppPath},extractInterceptionRouteInformation:function(){return extractInterceptionRouteInformation}});let o=n(3701),a=["(..)(..)","(.)","(..)","(...)"];function isInterceptionRouteAppPath(t){return void 0!==t.split("/").find(t=>a.find(r=>t.startsWith(r)))}function extractInterceptionRouteInformation(t){let r,n,u;for(let o of t.split("/"))if(n=a.find(t=>o.startsWith(t))){[r,u]=t.split(n,2);break}if(!r||!n||!u)throw Error(`Invalid interception route: ${t}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`);switch(r=(0,o.normalizeAppPath)(r),n){case"(.)":u="/"===r?`/${u}`:r+"/"+u;break;case"(..)":if("/"===r)throw Error(`Invalid interception route: ${t}. Cannot use (..) marker at the root level, use (.) instead.`);u=r.split("/").slice(0,-1).concat(u).join("/");break;case"(...)":u="/"+u;break;case"(..)(..)":let i=r.split("/");if(i.length<=2)throw Error(`Invalid interception route: ${t}. Cannot use (..)(..) marker at the root level or one level up.`);u=i.slice(0,-2).concat(u).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:r,interceptedRoute:u}}},4677:function(t,r,n){"use strict";function _class_private_field_loose_base(t,r){if(!Object.prototype.hasOwnProperty.call(t,r))throw TypeError("attempted to use private field on non-instance");return t}n.r(r),n.d(r,{_:function(){return _class_private_field_loose_base},_class_private_field_loose_base:function(){return _class_private_field_loose_base}})},6249:function(t,r,n){"use strict";n.r(r),n.d(r,{_:function(){return _class_private_field_loose_key},_class_private_field_loose_key:function(){return _class_private_field_loose_key}});var o=0;function _class_private_field_loose_key(t){return"__private_"+o+++"_"+t}},1024:function(t,r,n){"use strict";function _interop_require_default(t){return t&&t.__esModule?t:{default:t}}n.r(r),n.d(r,{_:function(){return _interop_require_default},_interop_require_default:function(){return _interop_require_default}})},8533:function(t,r,n){"use strict";function _getRequireWildcardCache(t){if("function"!=typeof WeakMap)return null;var r=new WeakMap,n=new WeakMap;return(_getRequireWildcardCache=function(t){return t?n:r})(t)}function _interop_require_wildcard(t,r){if(!r&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var n=_getRequireWildcardCache(r);if(n&&n.has(t))return n.get(t);var o={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in t)if("default"!==u&&Object.prototype.hasOwnProperty.call(t,u)){var i=a?Object.getOwnPropertyDescriptor(t,u):null;i&&(i.get||i.set)?Object.defineProperty(o,u,i):o[u]=t[u]}return o.default=t,n&&n.set(t,o),o}n.r(r),n.d(r,{_:function(){return _interop_require_wildcard},_interop_require_wildcard:function(){return _interop_require_wildcard}})}}]); \ No newline at end of file diff --git a/.next/static/chunks/488-66ca2c1db348e680.js b/.next/static/chunks/488-66ca2c1db348e680.js deleted file mode 100644 index 9fe6f3b..0000000 --- a/.next/static/chunks/488-66ca2c1db348e680.js +++ /dev/null @@ -1,25 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[488],{3644:function(){"trimStart"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),"trimEnd"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),"description"in Symbol.prototype||Object.defineProperty(Symbol.prototype,"description",{configurable:!0,get:function(){var e=/\((.*)\)/.exec(this.toString());return e?e[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(e,t){return t=this.concat.apply([],this),e>1&&t.some(Array.isArray)?t.flat(e-1):t},Array.prototype.flatMap=function(e,t){return this.map(e,t).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(e){if("function"!=typeof e)return this.then(e,e);var t=this.constructor||Promise;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})}),Object.fromEntries||(Object.fromEntries=function(e){return Array.from(e).reduce(function(e,t){return e[t[0]]=t[1],e},{})})},2035:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addBasePath",{enumerable:!0,get:function(){return o}});let n=r(5697),u=r(7052);function o(e,t){return(0,u.normalizePathTrailingSlash)((0,n.addPathPrefix)(e,""))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9215:function(e,t){"use strict";function r(e){var t,r;t=self.__next_s,r=()=>{e()},t&&t.length?t.reduce((e,t)=>{let[r,n]=t;return e.then(()=>new Promise((e,t)=>{let u=document.createElement("script");if(n)for(let e in n)"children"!==e&&u.setAttribute(e,n[e]);r?(u.src=r,u.onload=()=>e(),u.onerror=t):n&&(u.innerHTML=n.children,setTimeout(e)),document.head.appendChild(u)}))},Promise.resolve()).then(()=>{r()}).catch(e=>{console.error(e),r()}):r()}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"appBootstrap",{enumerable:!0,get:function(){return r}}),window.next={version:"13.4.4",appDir:!0},("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9663:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"callServer",{enumerable:!0,get:function(){return u}});let n=r(8827);async function u(e,t){let r=(0,n.getServerActionDispatcher)();if(!r)throw Error("Invariant: missing action dispatcher.");return new Promise((n,u)=>{r({actionId:e,actionArgs:t,resolve:n,reject:u})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},119:function(e,t,r){"use strict";let n,u;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hydrate",{enumerable:!0,get:function(){return A}});let o=r(6927),a=r(5909);r(3644);let l=o._(r(3194)),i=a._(r(6006)),c=r(5456),s=r(5415);r(6406);let f=o._(r(7483)),d=r(9663),p=r(815),h=r(8654),y=window.console.error;window.console.error=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];(0,p.isNextRouterError)(t[0])||y.apply(window.console,t)},window.addEventListener("error",e=>{if((0,p.isNextRouterError)(e.error)){e.preventDefault();return}});let _=r.u,b={};r.u=e=>encodeURI(b[e]||_(e)),self.__next_require__=r,self.__next_chunk_load__=e=>{if(!e)return Promise.resolve();let[t,n]=e.split(":");return b[t]=n,r.e(t)};let v=document,m=()=>{let{pathname:e,search:t}=location;return e+t},g=new TextEncoder,O=!1,P=!1;function E(e){if(0===e[0])n=[];else{if(!n)throw Error("Unexpected server data: missing bootstrap script.");u?u.enqueue(g.encode(e[1])):n.push(e[1])}}let R=function(){u&&!P&&(u.close(),P=!0,n=void 0),O=!0};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",R,!1):R();let j=self.__next_f=self.__next_f||[];j.forEach(E),j.push=E;let S=new Map;function T(e){let{cacheKey:t}=e;i.default.useEffect(()=>{S.delete(t)});let r=function(e){let t=S.get(e);if(t)return t;let r=new ReadableStream({start(e){n&&(n.forEach(t=>{e.enqueue(g.encode(t))}),O&&!P&&(e.close(),P=!0,n=void 0)),u=e}}),o=(0,c.createFromReadableStream)(r,{callServer:d.callServer});return S.set(e,o),o}(t),o=(0,i.use)(r);return o}let M=i.default.Fragment;function w(e){let{children:t}=e;return i.default.useEffect(()=>{},[]),t}function C(e){let t=m();return i.default.createElement(T,{...e,cacheKey:t})}function A(){let e=i.default.createElement(M,null,i.default.createElement(s.HeadManagerContext.Provider,{value:{appDir:!0}},i.default.createElement(w,null,i.default.createElement(C,null)))),t={onRecoverableError:f.default},r="__next_error__"===document.documentElement.id,n=r?l.default.createRoot(v,t):i.default.startTransition(()=>l.default.hydrateRoot(v,e,t));r&&n.render(e),(0,h.linkGc)()}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8654:function(e,t){"use strict";function r(){}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"linkGc",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4918:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});let n=r(9215);(0,n.appBootstrap)(()=>{r(8827),r(4463);let{hydrate:e}=r(119);e()}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1474:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AppRouterAnnouncer",{enumerable:!0,get:function(){return a}});let n=r(6006),u=r(8431),o="next-route-announcer";function a(e){let{tree:t}=e,[r,a]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=function(){var e;let t=document.getElementsByName(o)[0];if(null==t?void 0:null==(e=t.shadowRoot)?void 0:e.childNodes[0])return t.shadowRoot.childNodes[0];{let e=document.createElement(o);e.style.cssText="position:absolute";let t=document.createElement("div");t.setAttribute("aria-live","assertive"),t.setAttribute("id","__next-route-announcer__"),t.setAttribute("role","alert"),t.style.cssText="position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal";let r=e.attachShadow({mode:"open"});return r.appendChild(t),document.body.appendChild(e),t}}();return a(e),()=>{let e=document.getElementsByTagName(o)[0];(null==e?void 0:e.isConnected)&&document.body.removeChild(e)}},[]);let[l,i]=(0,n.useState)(""),c=(0,n.useRef)();return(0,n.useEffect)(()=>{let e="";if(document.title)e=document.title;else{let t=document.querySelector("h1");t&&(e=t.innerText||t.textContent||"")}void 0!==c.current&&i(e),c.current=e},[t]),r?(0,u.createPortal)(l,r):null}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8896:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RSC:function(){return r},ACTION:function(){return n},NEXT_ROUTER_STATE_TREE:function(){return u},NEXT_ROUTER_PREFETCH:function(){return o},NEXT_URL:function(){return a},FETCH_CACHE_HEADER:function(){return l},RSC_CONTENT_TYPE_HEADER:function(){return i},RSC_VARY_HEADER:function(){return c},FLIGHT_PARAMETERS:function(){return s}});let r="RSC",n="Next-Action",u="Next-Router-State-Tree",o="Next-Router-Prefetch",a="Next-Url",l="x-vercel-sc-headers",i="text/x-component; charset=utf-8",c=r+", "+u+", "+o,s=[[r],[u],[o]];("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8827:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getServerActionDispatcher:function(){return P},urlToUrlWithoutFlightMarker:function(){return E},default:function(){return T}});let n=r(5909),u=n._(r(6006)),o=r(6406),a=r(8061),l=r(2003),i=r(3542),c=r(1416),s=r(7744),f=r(9126),d=r(2306),p=r(7377),h=r(2035),y=r(1474),_=r(1785),b=r(6678),v=r(6386),m=r(9970),g=new Map,O=null;function P(){return O}function E(e){let t=new URL(e,location.origin);return t}function R(e){return e.origin!==window.location.origin}function j(e){let{tree:t,pushRef:r,canonicalUrl:n,sync:o}=e;return u.default.useInsertionEffect(()=>{let e={__NA:!0,tree:t};r.pendingPush&&(0,i.createHrefFromUrl)(new URL(window.location.href))!==n?(r.pendingPush=!1,window.history.pushState(e,"",n)):window.history.replaceState(e,"",n),o()},[t,r,n,o]),null}function S(e){let{initialHead:t,initialTree:r,initialCanonicalUrl:n,children:i,assetPrefix:f,notFound:P,notFoundStyles:E,asNotFound:S}=e,T=(0,u.useMemo)(()=>(0,d.createInitialRouterState)({children:i,initialCanonicalUrl:n,initialTree:r,initialParallelRoutes:g,isServer:!1,location:window.location,initialHead:t}),[i,n,r,t]),[{tree:M,cache:w,prefetchCache:C,pushRef:A,focusAndScrollRef:x,canonicalUrl:I,nextUrl:N},D,F]=(0,s.useReducerWithReduxDevtools)(a.reducer,T);(0,u.useEffect)(()=>{g=null},[]);let{searchParams:k,pathname:L}=(0,u.useMemo)(()=>{let e=new URL(I,window.location.href);return{searchParams:e.searchParams,pathname:e.pathname}},[I]),U=(0,u.useCallback)((e,t,r)=>{u.default.startTransition(()=>{D({type:l.ACTION_SERVER_PATCH,flightData:t,previousTree:e,overrideCanonicalUrl:r,cache:{status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map},mutable:{}})})},[D]),H=(0,u.useCallback)((e,t,r)=>{let n=new URL((0,h.addBasePath)(e),location.origin);return D({type:l.ACTION_NAVIGATE,url:n,isExternalUrl:R(n),locationSearch:location.search,forceOptimisticNavigation:r,navigateType:t,cache:{status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map},mutable:{}})},[D]),$=(0,u.useCallback)(e=>{u.default.startTransition(()=>{D({...e,type:l.ACTION_SERVER_ACTION,mutable:{},navigate:H,changeByServerResponse:U})})},[U,D,H]);O=$;let B=(0,u.useMemo)(()=>{let e={back:()=>window.history.back(),forward:()=>window.history.forward(),prefetch:(e,t)=>{if((0,p.isBot)(window.navigator.userAgent))return;let r=new URL((0,h.addBasePath)(e),location.origin);R(r)||u.default.startTransition(()=>{var e;D({type:l.ACTION_PREFETCH,url:r,kind:null!=(e=null==t?void 0:t.kind)?e:l.PrefetchKind.FULL})})},replace:(e,t)=>{void 0===t&&(t={}),u.default.startTransition(()=>{H(e,"replace",!!t.forceOptimisticNavigation)})},push:(e,t)=>{void 0===t&&(t={}),u.default.startTransition(()=>{H(e,"push",!!t.forceOptimisticNavigation)})},refresh:()=>{u.default.startTransition(()=>{D({type:l.ACTION_REFRESH,cache:{status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map},mutable:{},origin:window.location.origin})})},fastRefresh:()=>{throw Error("fastRefresh can only be used in development mode. Please use refresh instead.")}};return e},[D,H]);if((0,u.useEffect)(()=>{window.next&&(window.next.router=B)},[B]),(0,u.useEffect)(()=>{window.nd={router:B,cache:w,prefetchCache:C,tree:M}},[B,w,C,M]),A.mpaNavigation){let e=window.location;A.pendingPush?e.assign(I):e.replace(I),(0,u.use)((0,m.createInfinitePromise)())}let W=(0,u.useCallback)(e=>{let{state:t}=e;if(t){if(!t.__NA){window.location.reload();return}u.default.startTransition(()=>{D({type:l.ACTION_RESTORE,url:new URL(window.location.href),tree:t.tree})})}},[D]);(0,u.useEffect)(()=>(window.addEventListener("popstate",W),()=>{window.removeEventListener("popstate",W)}),[W]);let Y=(0,u.useMemo)(()=>(0,v.findHeadInCache)(w,M[1]),[w,M]),V=u.default.createElement(b.NotFoundBoundary,{notFound:P,notFoundStyles:E,asNotFound:S},u.default.createElement(_.RedirectBoundary,null,Y,w.subTreeData,u.default.createElement(y.AppRouterAnnouncer,{tree:M})));return u.default.createElement(u.default.Fragment,null,u.default.createElement(j,{tree:M,pushRef:A,canonicalUrl:I,sync:F}),u.default.createElement(c.PathnameContext.Provider,{value:L},u.default.createElement(c.SearchParamsContext.Provider,{value:k},u.default.createElement(o.GlobalLayoutRouterContext.Provider,{value:{changeByServerResponse:U,tree:M,focusAndScrollRef:x,nextUrl:N}},u.default.createElement(o.AppRouterContext.Provider,{value:B},u.default.createElement(o.LayoutRouterContext.Provider,{value:{childNodes:w.parallelRoutes,tree:M,url:I}},V))))))}function T(e){let{globalErrorComponent:t,...r}=e;return u.default.createElement(f.ErrorBoundary,{errorComponent:t},u.default.createElement(S,r))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2143:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createAsyncLocalStorage",{enumerable:!0,get:function(){return n}});class r{disable(){throw Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available")}getStore(){}run(){throw Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available")}exit(){throw Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available")}enterWith(){throw Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available")}}function n(){return globalThis.AsyncLocalStorage?new globalThis.AsyncLocalStorage:new r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3603:function(e,t,r){"use strict";function n(e){}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"clientHookInServerComponentError",{enumerable:!0,get:function(){return n}}),r(6927),r(6006),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9126:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ErrorBoundaryHandler:function(){return l},default:function(){return i},ErrorBoundary:function(){return c}});let n=r(6927),u=n._(r(6006)),o=r(3027),a={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{textAlign:"left"},text:{fontSize:"14px",fontWeight:400,lineHeight:"3em",margin:0}};class l extends u.default.Component{static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.error?{error:null,previousPathname:e.pathname}:{error:t.error,previousPathname:e.pathname}}render(){return this.state.error?u.default.createElement(u.default.Fragment,null,this.props.errorStyles,u.default.createElement(this.props.errorComponent,{error:this.state.error,reset:this.reset})):this.props.children}constructor(e){super(e),this.reset=()=>{this.setState({error:null})},this.state={error:null,previousPathname:this.props.pathname}}}function i(e){let{error:t}=e;return u.default.createElement("html",null,u.default.createElement("head",null),u.default.createElement("body",null,u.default.createElement("div",{style:a.error},u.default.createElement("div",{style:a.desc},u.default.createElement("h2",{style:a.text},"Application error: a client-side exception has occurred (see the browser console for more information)."),(null==t?void 0:t.digest)&&u.default.createElement("p",{style:a.text},"Digest: "+t.digest)))))}function c(e){let{errorComponent:t,errorStyles:r,children:n}=e,a=(0,o.usePathname)();return t?u.default.createElement(l,{pathname:a,errorComponent:t,errorStyles:r},n):u.default.createElement(u.default.Fragment,null,n)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9811:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DYNAMIC_ERROR_CODE:function(){return r},DynamicServerError:function(){return n}});let r="DYNAMIC_SERVER_USAGE";class n extends Error{constructor(e){super("Dynamic server usage: "+e),this.digest=r}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9970:function(e,t){"use strict";let r;function n(){return r||(r=new Promise(()=>{})),r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInfinitePromise",{enumerable:!0,get:function(){return n}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},815:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNextRouterError",{enumerable:!0,get:function(){return o}});let n=r(1891),u=r(3034);function o(e){return e&&e.digest&&((0,u.isRedirectError)(e)||(0,n.isNotFoundError)(e))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4463:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return E}});let n=r(6927),u=r(5909),o=u._(r(6006)),a=n._(r(8431)),l=r(6406),i=r(6828),c=r(9970),s=r(9126),f=r(2628),d=r(1200),p=r(1785),h=r(6678),y=r(4185),_=r(2846),b=["bottom","height","left","right","top","width","x","y"];function v(e,t){let r=e.getBoundingClientRect();return r.top>=0&&r.top<=t}class m extends o.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...e){super(...e),this.handlePotentialScroll=()=>{let{focusAndScrollRef:e,segmentPath:t}=this.props;if(e.apply){var r;if(0!==e.segmentPaths.length&&!e.segmentPaths.some(e=>t.every((t,r)=>(0,f.matchSegment)(t,e[r]))))return;let n=null,u=e.hashFragment;if(u&&(n="top"===u?document.body:null!=(r=document.getElementById(u))?r:document.getElementsByName(u)[0]),n||(n=a.default.findDOMNode(this)),!(n instanceof Element))return;for(;!(n instanceof HTMLElement)||function(e){let t=e.getBoundingClientRect();return b.every(e=>0===t[e])}(n);){if(null===n.nextElementSibling)return;n=n.nextElementSibling}e.apply=!1,e.hashFragment=null,e.segmentPaths=[],(0,d.handleSmoothScroll)(()=>{if(u){window.scrollTo(0,n.offsetTop);return}let e=document.documentElement,t=e.clientHeight;!v(n,t)&&(e.scrollTop=0,v(n,t)||n.scrollIntoView())},{dontForceLayout:!0}),n.focus()}}}}function g(e){let{segmentPath:t,children:r}=e,n=(0,o.useContext)(l.GlobalLayoutRouterContext);if(!n)throw Error("invariant global layout router not mounted");return o.default.createElement(m,{segmentPath:t,focusAndScrollRef:n.focusAndScrollRef},r)}function O(e){let{parallelRouterKey:t,url:r,childNodes:n,childProp:u,segmentPath:a,tree:s,cacheKey:d}=e,p=(0,o.useContext)(l.GlobalLayoutRouterContext);if(!p)throw Error("invariant global layout router not mounted");let{changeByServerResponse:h,tree:y}=p,_=n.get(d);if(u&&null!==u.current&&(_?_.status===l.CacheStates.LAZY_INITIALIZED&&(_.status=l.CacheStates.READY,_.subTreeData=u.current):(n.set(d,{status:l.CacheStates.READY,data:null,subTreeData:u.current,parallelRoutes:new Map}),_=n.get(d))),!_||_.status===l.CacheStates.LAZY_INITIALIZED){let e=function e(t,r){if(t){let[n,u]=t,o=2===t.length;if((0,f.matchSegment)(r[0],n)&&r[1].hasOwnProperty(u)){if(o){let t=e(void 0,r[1][u]);return[r[0],{...r[1],[u]:[t[0],t[1],t[2],"refetch"]}]}return[r[0],{...r[1],[u]:e(t.slice(2),r[1][u])}]}}return r}(["",...a],y);n.set(d,{status:l.CacheStates.DATA_FETCH,data:(0,i.fetchServerResponse)(new URL(r,location.origin),e,p.nextUrl),subTreeData:null,head:_&&_.status===l.CacheStates.LAZY_INITIALIZED?_.head:void 0,parallelRoutes:_&&_.status===l.CacheStates.LAZY_INITIALIZED?_.parallelRoutes:new Map}),_=n.get(d)}if(!_)throw Error("Child node should always exist");if(_.subTreeData&&_.data)throw Error("Child node should not have both subTreeData and data");if(_.data){let[e,t]=(0,o.use)(_.data);if("string"==typeof e)return window.location.href=r,null;_.data=null,setTimeout(()=>{o.default.startTransition(()=>{h(y,e,t)})}),(0,o.use)((0,c.createInfinitePromise)())}_.subTreeData||(0,o.use)((0,c.createInfinitePromise)());let b=o.default.createElement(l.LayoutRouterContext.Provider,{value:{tree:s[1][t],childNodes:_.parallelRoutes,url:r}},_.subTreeData);return b}function P(e){let{children:t,loading:r,loadingStyles:n,hasLoading:u}=e;return u?o.default.createElement(o.default.Suspense,{fallback:o.default.createElement(o.default.Fragment,null,n,r)},t):o.default.createElement(o.default.Fragment,null,t)}function E(e){let{parallelRouterKey:t,segmentPath:r,childProp:n,error:u,errorStyles:a,templateStyles:i,loading:c,loadingStyles:d,hasLoading:b,template:v,notFound:m,notFoundStyles:E,asNotFound:R,styles:j}=e,S=(0,o.useContext)(l.LayoutRouterContext);if(!S)throw Error("invariant expected layout router to be mounted");let{childNodes:T,tree:M,url:w}=S,C=T.get(t);C||(T.set(t,new Map),C=T.get(t));let A=M[1][t][0],x=n.segment,I=(0,y.getSegmentValue)(A),N=[A];return o.default.createElement(o.default.Fragment,null,j,N.map(e=>{let j=(0,f.matchSegment)(e,x),S=(0,y.getSegmentValue)(e),T=(0,_.createRouterCacheKey)(e);return o.default.createElement(l.TemplateContext.Provider,{key:(0,_.createRouterCacheKey)(e,!0),value:o.default.createElement(g,{segmentPath:r},o.default.createElement(s.ErrorBoundary,{errorComponent:u,errorStyles:a},o.default.createElement(P,{hasLoading:b,loading:c,loadingStyles:d},o.default.createElement(h.NotFoundBoundary,{notFound:m,notFoundStyles:E,asNotFound:R},o.default.createElement(p.RedirectBoundary,null,o.default.createElement(O,{parallelRouterKey:t,url:w,tree:M,childNodes:C,childProp:j?n:null,segmentPath:r,cacheKey:T,isActive:I===S}))))))},o.default.createElement(o.default.Fragment,null,i,v))}))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2628:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{matchSegment:function(){return u},canSegmentBeOverridden:function(){return o}});let n=r(4778),u=(e,t)=>"string"==typeof e&&"string"==typeof t?e===t:!!(Array.isArray(e)&&Array.isArray(t))&&e[0]===t[0]&&e[1]===t[1],o=(e,t)=>{var r;return!Array.isArray(e)&&!!Array.isArray(t)&&(null==(r=(0,n.getSegmentParam)(e))?void 0:r.param)===t[0]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3027:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ReadonlyURLSearchParams:function(){return p},useSearchParams:function(){return h},usePathname:function(){return y},ServerInsertedHTMLContext:function(){return i.ServerInsertedHTMLContext},useServerInsertedHTML:function(){return i.useServerInsertedHTML},useRouter:function(){return _},useParams:function(){return b},useSelectedLayoutSegments:function(){return v},useSelectedLayoutSegment:function(){return m},redirect:function(){return c.redirect},notFound:function(){return s.notFound}});let n=r(6006),u=r(6406),o=r(1416),a=r(3603),l=r(4185),i=r(3063),c=r(3034),s=r(1891),f=Symbol("internal for urlsearchparams readonly");function d(){return Error("ReadonlyURLSearchParams cannot be modified")}class p{[Symbol.iterator](){return this[f][Symbol.iterator]()}append(){throw d()}delete(){throw d()}set(){throw d()}sort(){throw d()}constructor(e){this[f]=e,this.entries=e.entries.bind(e),this.forEach=e.forEach.bind(e),this.get=e.get.bind(e),this.getAll=e.getAll.bind(e),this.has=e.has.bind(e),this.keys=e.keys.bind(e),this.values=e.values.bind(e),this.toString=e.toString.bind(e)}}function h(){(0,a.clientHookInServerComponentError)("useSearchParams");let e=(0,n.useContext)(o.SearchParamsContext),t=(0,n.useMemo)(()=>e?new p(e):null,[e]);return t}function y(){return(0,a.clientHookInServerComponentError)("usePathname"),(0,n.useContext)(o.PathnameContext)}function _(){(0,a.clientHookInServerComponentError)("useRouter");let e=(0,n.useContext)(u.AppRouterContext);if(null===e)throw Error("invariant expected app router to be mounted");return e}function b(){(0,a.clientHookInServerComponentError)("useParams");let e=(0,n.useContext)(u.GlobalLayoutRouterContext);return e?function e(t,r){void 0===r&&(r={});let n=t[1];for(let t of Object.values(n)){let n=t[0],u=Array.isArray(n),o=u?n[1]:n;!o||o.startsWith("__PAGE__")||(u&&(r[n[0]]=n[1]),r=e(t,r))}return r}(e.tree):null}function v(e){void 0===e&&(e="children"),(0,a.clientHookInServerComponentError)("useSelectedLayoutSegments");let{tree:t}=(0,n.useContext)(u.LayoutRouterContext);return function e(t,r,n,u){let o;if(void 0===n&&(n=!0),void 0===u&&(u=[]),n)o=t[1][r];else{var a;let e=t[1];o=null!=(a=e.children)?a:Object.values(e)[0]}if(!o)return u;let i=o[0],c=(0,l.getSegmentValue)(i);return!c||c.startsWith("__PAGE__")?u:(u.push(c),e(o,r,!1,u))}(t,e)}function m(e){void 0===e&&(e="children"),(0,a.clientHookInServerComponentError)("useSelectedLayoutSegment");let t=v(e);return 0===t.length?null:t[0]}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6678:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NotFoundBoundary",{enumerable:!0,get:function(){return l}});let n=r(6927),u=n._(r(6006)),o=r(3027);class a extends u.default.Component{static getDerivedStateFromError(e){if((null==e?void 0:e.digest)==="NEXT_NOT_FOUND")return{notFoundTriggered:!0};throw e}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.notFoundTriggered?{notFoundTriggered:!1,previousPathname:e.pathname}:{notFoundTriggered:t.notFoundTriggered,previousPathname:e.pathname}}render(){return this.state.notFoundTriggered?u.default.createElement(u.default.Fragment,null,u.default.createElement("meta",{name:"robots",content:"noindex"}),this.props.notFoundStyles,this.props.notFound):this.props.children}constructor(e){super(e),this.state={notFoundTriggered:!!e.asNotFound,previousPathname:e.pathname}}}function l(e){let{notFound:t,notFoundStyles:r,asNotFound:n,children:l}=e,i=(0,o.usePathname)();return t?u.default.createElement(a,{pathname:i,notFound:t,notFoundStyles:r,asNotFound:n},l):u.default.createElement(u.default.Fragment,null,l)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1891:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{notFound:function(){return n},isNotFoundError:function(){return u}});let r="NEXT_NOT_FOUND";function n(){let e=Error(r);throw e.digest=r,e}function u(e){return(null==e?void 0:e.digest)===r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1785:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectErrorBoundary:function(){return i},RedirectBoundary:function(){return c}});let n=r(5909),u=n._(r(6006)),o=r(3027),a=r(3034);function l(e){let{redirect:t,reset:r,redirectType:n}=e,l=(0,o.useRouter)();return(0,u.useEffect)(()=>{u.default.startTransition(()=>{n===a.RedirectType.push?l.push(t,{}):l.replace(t,{}),r()})},[t,n,r,l]),null}class i extends u.default.Component{static getDerivedStateFromError(e){if((0,a.isRedirectError)(e)){let t=(0,a.getURLFromRedirectError)(e),r=(0,a.getRedirectTypeFromError)(e);return{redirect:t,redirectType:r}}throw e}render(){let{redirect:e,redirectType:t}=this.state;return null!==e&&null!==t?u.default.createElement(l,{redirect:e,redirectType:t,reset:()=>this.setState({redirect:null})}):this.props.children}constructor(e){super(e),this.state={redirect:null,redirectType:null}}}function c(e){let{children:t}=e,r=(0,o.useRouter)();return u.default.createElement(i,{router:r},t)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3034:function(e,t,r){"use strict";var n,u;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectType:function(){return n},getRedirectError:function(){return l},redirect:function(){return i},isRedirectError:function(){return c},getURLFromRedirectError:function(){return s},getRedirectTypeFromError:function(){return f}});let o=r(5863),a="NEXT_REDIRECT";function l(e,t){let r=Error(a);r.digest=a+";"+t+";"+e;let n=o.requestAsyncStorage.getStore();return n&&(r.mutableCookies=n.mutableCookies),r}function i(e,t){throw void 0===t&&(t="replace"),l(e,t)}function c(e){if("string"!=typeof(null==e?void 0:e.digest))return!1;let[t,r,n]=e.digest.split(";",3);return t===a&&("replace"===r||"push"===r)&&"string"==typeof n}function s(e){return c(e)?e.digest.split(";",3)[2]:null}function f(e){if(!c(e))throw Error("Not a redirect error");return e.digest.split(";",3)[1]}(u=n||(n={})).push="push",u.replace="replace",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1010:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let n=r(5909),u=n._(r(6006)),o=r(6406);function a(){let e=(0,u.useContext)(o.TemplateContext);return u.default.createElement(u.default.Fragment,null,e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6639:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyFlightData",{enumerable:!0,get:function(){return a}});let n=r(6406),u=r(7051),o=r(5369);function a(e,t,r,a){void 0===a&&(a=!1);let[l,i,c]=r.slice(-3);return null!==i&&(3===r.length?(t.status=n.CacheStates.READY,t.subTreeData=i,(0,u.fillLazyItemsTillLeafWithHead)(t,e,l,c,a)):(t.status=n.CacheStates.READY,t.subTreeData=e.subTreeData,t.parallelRoutes=new Map(e.parallelRoutes),(0,o.fillCacheWithNewSubTreeData)(t,e,r,a)),!0)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2341:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyRouterStatePatchToTree",{enumerable:!0,get:function(){return function e(t,r,o){let a;let[l,i,,,c]=r;if(1===t.length){let e=u(r,o);return e}let[s,f]=t;if(!(0,n.matchSegment)(s,l))return null;let d=2===t.length;if(d)a=u(i[f],o);else if(null===(a=e(t.slice(2),i[f],o)))return null;let p=[t[0],{...i,[f]:a}];return c&&(p[4]=!0),p}}});let n=r(2628);function u(e,t){let[r,o]=e,[a,l]=t;if("__DEFAULT__"===a&&"__DEFAULT__"!==r)return e;if((0,n.matchSegment)(r,a)){let t={};for(let e in o){let r=void 0!==l[e];r?t[e]=u(o[e],l[e]):t[e]=o[e]}for(let e in l)t[e]||(t[e]=l[e]);let n=[r,t];return e[2]&&(n[2]=e[2]),e[3]&&(n[3]=e[3]),e[4]&&(n[4]=e[4]),n}return t}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},925:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{extractPathFromFlightRouterState:function(){return l},computeChangedPath:function(){return i}});let n=r(7399),u=r(2628),o=e=>"string"==typeof e?e:e[1];function a(e){return e.split("/").reduce((e,t)=>""===t||t.startsWith("(")&&t.endsWith(")")?e:e+"/"+t,"")||"/"}function l(e){var t;let r=Array.isArray(e[0])?e[0][1]:e[0];if("__DEFAULT__"===r||n.INTERCEPTION_ROUTE_MARKERS.some(e=>r.startsWith(e)))return;if(r.startsWith("__PAGE__"))return"";let u=[r],o=null!=(t=e[1])?t:{},i=o.children?l(o.children):void 0;if(void 0!==i)u.push(i);else for(let[e,t]of Object.entries(o)){if("children"===e)continue;let r=l(t);void 0!==r&&u.push(r)}return a(u.join("/"))}function i(e,t){let r=function e(t,r){let[a,i]=t,[c,s]=r,f=o(a),d=o(c);if(n.INTERCEPTION_ROUTE_MARKERS.some(e=>f.startsWith(e)||d.startsWith(e)))return"";if(!(0,u.matchSegment)(a,c)){var p;return null!=(p=l(r))?p:""}for(let t in i)if(s[t]){let r=e(i[t],s[t]);if(null!==r)return o(c)+"/"+r}return null}(e,t);return null==r||"/"===r?r:a(r)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3542:function(e,t){"use strict";function r(e,t){return void 0===t&&(t=!0),e.pathname+e.search+(t?e.hash:"")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createHrefFromUrl",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2306:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInitialRouterState",{enumerable:!0,get:function(){return l}});let n=r(6406),u=r(3542),o=r(7051),a=r(925);function l(e){var t;let{initialTree:r,children:l,initialCanonicalUrl:i,initialParallelRoutes:c,isServer:s,location:f,initialHead:d}=e,p={status:n.CacheStates.READY,data:null,subTreeData:l,parallelRoutes:s?new Map:c};return(null===c||0===c.size)&&(0,o.fillLazyItemsTillLeafWithHead)(p,void 0,r,d),{tree:r,cache:p,prefetchCache:new Map,pushRef:{pendingPush:!1,mpaNavigation:!1},focusAndScrollRef:{apply:!1,hashFragment:null,segmentPaths:[]},canonicalUrl:f?(0,u.createHrefFromUrl)(f):i,nextUrl:null!=(t=(0,a.extractPathFromFlightRouterState)(r)||(null==f?void 0:f.pathname))?t:null}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6501:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createOptimisticTree",{enumerable:!0,get:function(){return function e(t,r,u){let o;let[a,l,i,c,s]=r||[null,{}],f=t[0],d=1===t.length,p=null!==a&&(0,n.matchSegment)(a,f),h=Object.keys(l).length>1,y=!r||!p||h,_={};if(null!==a&&p&&(_=l),!d&&!h){let r=e(t.slice(1),_?_.children:null,u||y);o=r}let b=[f,{..._,...o?{children:o}:{}}];return i&&(b[2]=i),!u&&y?b[3]="refetch":p&&c&&(b[3]=c),p&&s&&(b[4]=s),b}}});let n=r(2628);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3891:function(e,t){"use strict";function r(e){return e.status="pending",e.then(t=>{"pending"===e.status&&(e.status="fulfilled",e.value=t)},t=>{"pending"===e.status&&(e.status="rejected",e.value=t)}),e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRecordFromThenable",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2846:function(e,t){"use strict";function r(e,t){return void 0===t&&(t=!1),Array.isArray(e)?e[0]+"|"+e[1]+"|"+e[2]:t&&e.startsWith("__PAGE__")?"__PAGE__":e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRouterCacheKey",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6828:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fetchServerResponse",{enumerable:!0,get:function(){return i}});let n=r(5456),u=r(8896),o=r(8827),a=r(9663),l=r(2003);async function i(e,t,r,i){let c={[u.RSC]:"1",[u.NEXT_ROUTER_STATE_TREE]:JSON.stringify(t)};i===l.PrefetchKind.AUTO&&(c[u.NEXT_ROUTER_PREFETCH]="1"),r&&(c[u.NEXT_URL]=r);try{let t=await fetch(e,{credentials:"same-origin",headers:c}),r=t.redirected?(0,o.urlToUrlWithoutFlightMarker)(t.url):void 0,l=t.headers.get("content-type")||"";if(l!==u.RSC_CONTENT_TYPE_HEADER||!t.ok)return[t.url,void 0];let i=await (0,n.createFromFetch)(Promise.resolve(t),{callServer:a.callServer});return[i,r]}catch(t){return console.error("Failed to fetch RSC payload. Falling back to browser navigation.",t),[e.toString(),void 0]}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9778:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithDataProperty",{enumerable:!0,get:function(){return function e(t,r,o,a,l){void 0===l&&(l=!1);let i=o.length<=2,[c,s]=o,f=(0,u.createRouterCacheKey)(s),d=r.parallelRoutes.get(c);if(!d||l&&r.parallelRoutes.size>1)return{bailOptimistic:!0};let p=t.parallelRoutes.get(c);p&&p!==d||(p=new Map(d),t.parallelRoutes.set(c,p));let h=d.get(f),y=p.get(f);if(i){y&&y.data&&y!==h||p.set(f,{status:n.CacheStates.DATA_FETCH,data:a(),subTreeData:null,parallelRoutes:new Map});return}if(!y||!h){y||p.set(f,{status:n.CacheStates.DATA_FETCH,data:a(),subTreeData:null,parallelRoutes:new Map});return}return y===h&&(y={status:y.status,data:y.data,subTreeData:y.subTreeData,parallelRoutes:new Map(y.parallelRoutes)},p.set(f,y)),e(y,h,o.slice(2),a)}}});let n=r(6406),u=r(2846);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5369:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithNewSubTreeData",{enumerable:!0,get:function(){return function e(t,r,l,i){let c=l.length<=5,[s,f]=l,d=(0,a.createRouterCacheKey)(f),p=r.parallelRoutes.get(s);if(!p)return;let h=t.parallelRoutes.get(s);h&&h!==p||(h=new Map(p),t.parallelRoutes.set(s,h));let y=p.get(d),_=h.get(d);if(c){_&&_.data&&_!==y||(_={status:n.CacheStates.READY,data:null,subTreeData:l[3],parallelRoutes:y?new Map(y.parallelRoutes):new Map},y&&(0,u.invalidateCacheByRouterState)(_,y,l[2]),(0,o.fillLazyItemsTillLeafWithHead)(_,y,l[2],l[4],i),h.set(d,_));return}_&&y&&(_===y&&(_={status:_.status,data:_.data,subTreeData:_.subTreeData,parallelRoutes:new Map(_.parallelRoutes)},h.set(d,_)),e(_,y,l.slice(2),i))}}});let n=r(6406),u=r(2594),o=r(7051),a=r(2846);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7051:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillLazyItemsTillLeafWithHead",{enumerable:!0,get:function(){return function e(t,r,o,a,l){let i=0===Object.keys(o[1]).length;if(i){t.head=a;return}for(let i in o[1]){let c=o[1][i],s=c[0],f=(0,u.createRouterCacheKey)(s);if(r){let u=r.parallelRoutes.get(i);if(u){let r=new Map(u),o=r.get(f),s=l&&o?{status:o.status,data:o.data,subTreeData:o.subTreeData,parallelRoutes:new Map(o.parallelRoutes)}:{status:n.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map(null==o?void 0:o.parallelRoutes)};r.set(f,s),e(s,o,c,a,l),t.parallelRoutes.set(i,r);continue}}let d={status:n.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map},p=t.parallelRoutes.get(i);p?p.set(f,d):t.parallelRoutes.set(i,new Map([[f,d]])),e(d,void 0,c,a,l)}}}});let n=r(6406),u=r(2846);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5237:function(e,t){"use strict";var r,n;function u(e){let{kind:t,prefetchTime:r,lastUsedTime:n}=e;return Date.now()<(null!=n?n:r)+3e4?n?"reusable":"fresh":"auto"===t&&Date.now()<r+3e5?"stale":"full"===t&&Date.now()<r+3e5?"reusable":"expired"}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PrefetchCacheEntryStatus:function(){return r},getPrefetchEntryCacheStatus:function(){return u}}),(n=r||(r={})).fresh="fresh",n.reusable="reusable",n.expired="expired",n.stale="stale",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},911:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleMutable",{enumerable:!0,get:function(){return u}});let n=r(925);function u(e,t){var r,u;return{canonicalUrl:void 0!==t.canonicalUrl?t.canonicalUrl===e.canonicalUrl?e.canonicalUrl:t.canonicalUrl:e.canonicalUrl,pushRef:{pendingPush:void 0!==t.pendingPush?t.pendingPush:e.pushRef.pendingPush,mpaNavigation:void 0!==t.mpaNavigation?t.mpaNavigation:e.pushRef.mpaNavigation},focusAndScrollRef:{apply:(null==t?void 0:t.scrollableSegments)!==void 0||e.focusAndScrollRef.apply,hashFragment:t.hashFragment&&""!==t.hashFragment?decodeURIComponent(t.hashFragment.slice(1)):e.focusAndScrollRef.hashFragment,segmentPaths:null!=(r=null==t?void 0:t.scrollableSegments)?r:e.focusAndScrollRef.segmentPaths},cache:t.cache?t.cache:e.cache,prefetchCache:t.prefetchCache?t.prefetchCache:e.prefetchCache,tree:void 0!==t.patchedTree?t.patchedTree:e.tree,nextUrl:void 0!==t.patchedTree?null!=(u=(0,n.computeChangedPath)(e.tree,t.patchedTree))?u:e.canonicalUrl:e.nextUrl}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2399:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheBelowFlightSegmentPath",{enumerable:!0,get:function(){return function e(t,r,u){let o=u.length<=2,[a,l]=u,i=(0,n.createRouterCacheKey)(l),c=r.parallelRoutes.get(a);if(!c)return;let s=t.parallelRoutes.get(a);if(s&&s!==c||(s=new Map(c),t.parallelRoutes.set(a,s)),o){s.delete(i);return}let f=c.get(i),d=s.get(i);d&&f&&(d===f&&(d={status:d.status,data:d.data,subTreeData:d.subTreeData,parallelRoutes:new Map(d.parallelRoutes)},s.set(i,d)),e(d,f,u.slice(2)))}}});let n=r(2846);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2594:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheByRouterState",{enumerable:!0,get:function(){return u}});let n=r(2846);function u(e,t,r){for(let u in r[1]){let o=r[1][u][0],a=(0,n.createRouterCacheKey)(o),l=t.parallelRoutes.get(u);if(l){let t=new Map(l);t.delete(a),e.parallelRoutes.set(u,t)}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8912:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNavigatingToNewRootLayout",{enumerable:!0,get:function(){return function e(t,r){let n=t[0],u=r[0];if(Array.isArray(n)&&Array.isArray(u)){if(n[0]!==u[0]||n[2]!==u[2])return!0}else if(n!==u)return!0;if(t[4])return!r[4];if(r[4])return!0;let o=Object.values(t[1])[0],a=Object.values(r[1])[0];return!o||!a||e(o,a)}}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7712:function(e,t){"use strict";function r(e){if("fulfilled"===e.status)return e.value;throw e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"readRecordValue",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9851:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fastRefreshReducer",{enumerable:!0,get:function(){return n}}),r(6828),r(3891),r(7712),r(3542),r(2341),r(8912),r(9964),r(911),r(6639);let n=function(e,t){return e};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6386:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"findHeadInCache",{enumerable:!0,get:function(){return function e(t,r){let u=0===Object.keys(r).length;if(u)return t.head;for(let u in r){let[o,a]=r[u],l=t.parallelRoutes.get(u);if(!l)continue;let i=(0,n.createRouterCacheKey)(o),c=l.get(i);if(!c)continue;let s=e(c,a);if(s)return s}}}});let n=r(2846);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4185:function(e,t){"use strict";function r(e){return Array.isArray(e)?e[1]:e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentValue",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9964:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{handleExternalUrl:function(){return m},navigateReducer:function(){return O}});let n=r(6406),u=r(6828),o=r(3891),a=r(7712),l=r(3542),i=r(2399),c=r(9778),s=r(6501),f=r(2341),d=r(3973),p=r(8912),h=r(2003),y=r(911),_=r(6639),b=r(5237),v=r(874);function m(e,t,r,n){return t.previousTree=e.tree,t.mpaNavigation=!0,t.canonicalUrl=r,t.pendingPush=n,t.scrollableSegments=void 0,(0,y.handleMutable)(e,t)}function g(e){let t=[],[r,n]=e;if(0===Object.keys(n).length)return[[r]];for(let[e,u]of Object.entries(n))for(let n of g(u))""===r?t.push([e,...n]):t.push([r,e,...n]);return t}function O(e,t){let{url:r,isExternalUrl:O,navigateType:P,cache:E,mutable:R,forceOptimisticNavigation:j}=t,{pathname:S,hash:T}=r,M=(0,l.createHrefFromUrl)(r),w="push"===P;(0,v.prunePrefetchCache)(e.prefetchCache);let C=JSON.stringify(R.previousTree)===JSON.stringify(e.tree);if(C)return(0,y.handleMutable)(e,R);if(O)return m(e,R,r.toString(),w);let A=e.prefetchCache.get((0,l.createHrefFromUrl)(r,!1));if(j&&(null==A?void 0:A.kind)!==h.PrefetchKind.TEMPORARY){let t=S.split("/");t.push("__PAGE__");let a=(0,s.createOptimisticTree)(t,e.tree,!1),i={...E};i.status=n.CacheStates.READY,i.subTreeData=e.cache.subTreeData,i.parallelRoutes=new Map(e.cache.parallelRoutes);let f=(0,o.createRecordFromThenable)((0,u.fetchServerResponse)(r,a,e.nextUrl)),d=t.slice(1).map(e=>["children",e]).flat(),p=(0,c.fillCacheWithDataProperty)(i,e.cache,d,()=>f,!0);if(!(null==p?void 0:p.bailOptimistic))return R.previousTree=e.tree,R.patchedTree=a,R.pendingPush=w,R.hashFragment=T,R.scrollableSegments=[],R.cache=i,R.canonicalUrl=M,e.prefetchCache.set((0,l.createHrefFromUrl)(r,!1),{data:Promise.resolve(f),kind:h.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:e.tree,lastUsedTime:Date.now()}),(0,y.handleMutable)(e,R)}if(!A){let t=(0,o.createRecordFromThenable)((0,u.fetchServerResponse)(r,e.tree,e.nextUrl)),n={data:Promise.resolve(t),kind:h.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:e.tree,lastUsedTime:null};e.prefetchCache.set((0,l.createHrefFromUrl)(r,!1),n),A=n}let x=(0,b.getPrefetchEntryCacheStatus)(A),{treeAtTimeOfPrefetch:I,data:N}=A,[D,F]=(0,a.readRecordValue)(N);if(A.lastUsedTime=Date.now(),"string"==typeof D)return m(e,R,D,w);let k=e.tree,L=e.cache,U=[];for(let t of D){let o=t.slice(0,-4),[a]=t.slice(-3),l=(0,f.applyRouterStatePatchToTree)(["",...o],k,a);if(null===l&&(l=(0,f.applyRouterStatePatchToTree)(["",...o],I,a)),null!==l){if((0,p.isNavigatingToNewRootLayout)(k,l))return m(e,R,M,w);let s=(0,_.applyFlightData)(L,E,t,"auto"===A.kind&&x===b.PrefetchCacheEntryStatus.reusable);s||x!==b.PrefetchCacheEntryStatus.stale||(s=function(e,t,r,u,o){let a=!1;e.status=n.CacheStates.READY,e.subTreeData=t.subTreeData,e.parallelRoutes=new Map(t.parallelRoutes);let l=g(u).map(e=>[...r,...e]);for(let r of l){let n=(0,c.fillCacheWithDataProperty)(e,t,r,o);(null==n?void 0:n.bailOptimistic)||(a=!0)}return a}(E,L,o,a,()=>(0,u.fetchServerResponse)(r,k,e.nextUrl)));let f=(0,d.shouldHardNavigate)(["",...o],k);for(let e of(f?(E.status=n.CacheStates.READY,E.subTreeData=L.subTreeData,(0,i.invalidateCacheBelowFlightSegmentPath)(E,L,o),R.cache=E):s&&(R.cache=E),L=E,k=l,g(a))){let t=[...o,...e];"__DEFAULT__"!==t[t.length-1]&&U.push(t)}}}return R.previousTree=e.tree,R.patchedTree=k,R.scrollableSegments=U,R.canonicalUrl=F?(0,l.createHrefFromUrl)(F):M,R.pendingPush=w,R.hashFragment=T,(0,y.handleMutable)(e,R)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4605:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"prefetchReducer",{enumerable:!0,get:function(){return i}});let n=r(3542),u=r(6828),o=r(2003),a=r(3891),l=r(874);function i(e,t){(0,l.prunePrefetchCache)(e.prefetchCache);let{url:r}=t,i=(0,n.createHrefFromUrl)(r,!1),c=e.prefetchCache.get(i);if(c&&(c.kind===o.PrefetchKind.TEMPORARY&&e.prefetchCache.set(i,{...c,kind:t.kind}),!(c.kind===o.PrefetchKind.AUTO&&t.kind===o.PrefetchKind.FULL)))return e;let s=(0,a.createRecordFromThenable)((0,u.fetchServerResponse)(r,e.tree,e.nextUrl,t.kind));return e.prefetchCache.set(i,{treeAtTimeOfPrefetch:e.tree,data:s,kind:t.kind,prefetchTime:Date.now(),lastUsedTime:null}),e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},874:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"prunePrefetchCache",{enumerable:!0,get:function(){return u}});let n=r(5237);function u(e){for(let[t,r]of e)(0,n.getPrefetchEntryCacheStatus)(r)===n.PrefetchCacheEntryStatus.expired&&e.delete(t)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4531:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"refreshReducer",{enumerable:!0,get:function(){return p}});let n=r(6828),u=r(3891),o=r(7712),a=r(3542),l=r(2341),i=r(8912),c=r(9964),s=r(911),f=r(6406),d=r(7051);function p(e,t){let{cache:r,mutable:p,origin:h}=t,y=e.canonicalUrl,_=JSON.stringify(p.previousTree)===JSON.stringify(e.tree);if(_)return(0,s.handleMutable)(e,p);r.data||(r.data=(0,u.createRecordFromThenable)((0,n.fetchServerResponse)(new URL(y,h),[e.tree[0],e.tree[1],e.tree[2],"refetch"],e.nextUrl)));let[b,v]=(0,o.readRecordValue)(r.data);if("string"==typeof b)return(0,c.handleExternalUrl)(e,p,b,e.pushRef.pendingPush);r.data=null;let m=e.tree;for(let t of b){if(3!==t.length)return console.log("REFRESH FAILED"),e;let[n]=t,u=(0,l.applyRouterStatePatchToTree)([""],m,n);if(null===u)throw Error("SEGMENT MISMATCH");if((0,i.isNavigatingToNewRootLayout)(m,u))return(0,c.handleExternalUrl)(e,p,y,e.pushRef.pendingPush);let o=v?(0,a.createHrefFromUrl)(v):void 0;v&&(p.canonicalUrl=o);let[s,h]=t.slice(-2);null!==s&&(r.status=f.CacheStates.READY,r.subTreeData=s,(0,d.fillLazyItemsTillLeafWithHead)(r,void 0,n,h),p.cache=r,p.prefetchCache=new Map),p.previousTree=m,p.patchedTree=u,p.canonicalUrl=y,m=u}return(0,s.handleMutable)(e,p)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2721:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"restoreReducer",{enumerable:!0,get:function(){return u}});let n=r(3542);function u(e,t){let{url:r,tree:u}=t,o=(0,n.createHrefFromUrl)(r);return{canonicalUrl:o,pushRef:e.pushRef,focusAndScrollRef:e.focusAndScrollRef,cache:e.cache,prefetchCache:e.prefetchCache,tree:u,nextUrl:r.pathname}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6227:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverActionReducer",{enumerable:!0,get:function(){return p}});let n=r(9663),u=r(8896),o=r(3891),a=r(7712),l=r(5456),i=r(2003),c=r(2035),s=r(3542),f=r(3034);async function d(e,t){let{actionId:r,actionArgs:o}=t,a=await (0,l.encodeReply)(o),i=await fetch("",{method:"POST",headers:{Accept:u.RSC_CONTENT_TYPE_HEADER,"Next-Action":r,[u.NEXT_ROUTER_STATE_TREE]:JSON.stringify(e.tree),...e.nextUrl?{[u.NEXT_URL]:e.nextUrl}:{}},body:a}),s=i.headers.get("x-action-redirect"),f=s?new URL((0,c.addBasePath)(s),window.location.origin):void 0;if(i.headers.get("content-type")===u.RSC_CONTENT_TYPE_HEADER){let e=await (0,l.createFromFetch)(Promise.resolve(i),{callServer:n.callServer});if(s)return{actionFlightData:e,redirectLocation:f};{let[t,r]=null!=e?e:[];return{actionResult:t,actionFlightData:r,redirectLocation:f}}}return{redirectLocation:f}}function p(e,t){if(t.mutable.serverActionApplied)return e;t.mutable.inFlightServerAction||(t.mutable.previousTree=e.tree,t.mutable.previousUrl=e.canonicalUrl,t.mutable.inFlightServerAction=(0,o.createRecordFromThenable)(d(e,t)));try{var r,n;let{actionResult:u,actionFlightData:l,redirectLocation:c}=(0,a.readRecordValue)(t.mutable.inFlightServerAction);if(c){if(l){let n=(0,s.createHrefFromUrl)(c,!1),u=e.prefetchCache.get(n);e.prefetchCache.set(n,{data:(0,o.createRecordFromThenable)(Promise.resolve([l,void 0])),kind:null!=(r=null==u?void 0:u.kind)?r:i.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:t.mutable.previousTree,lastUsedTime:null})}t.reject((0,f.getRedirectError)(c.toString(),f.RedirectType.push))}else{if(l){let r=(0,s.createHrefFromUrl)(new URL(t.mutable.previousUrl,window.location.origin),!1),u=e.prefetchCache.get(r);e.prefetchCache.set((0,s.createHrefFromUrl)(new URL(t.mutable.previousUrl,window.location.origin),!1),{data:(0,o.createRecordFromThenable)(Promise.resolve([l,void 0])),kind:null!=(n=null==u?void 0:u.kind)?n:i.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:t.mutable.previousTree,lastUsedTime:null}),setTimeout(()=>{t.changeByServerResponse(t.mutable.previousTree,l,void 0)})}t.resolve(u)}}catch(e){if("rejected"===e.status)t.reject(e.value);else throw e}return t.mutable.serverActionApplied=!0,e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2767:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverPatchReducer",{enumerable:!0,get:function(){return c}});let n=r(3542),u=r(2341),o=r(8912),a=r(9964),l=r(6639),i=r(911);function c(e,t){let{flightData:r,previousTree:c,overrideCanonicalUrl:s,cache:f,mutable:d}=t,p=JSON.stringify(c)===JSON.stringify(e.tree);if(!p)return console.log("TREE MISMATCH"),e;if(d.previousTree)return(0,i.handleMutable)(e,d);if("string"==typeof r)return(0,a.handleExternalUrl)(e,d,r,e.pushRef.pendingPush);let h=e.tree,y=e.cache;for(let t of r){let r=t.slice(0,-4),[i]=t.slice(-3,-2),c=(0,u.applyRouterStatePatchToTree)(["",...r],h,i);if(null===c)throw Error("SEGMENT MISMATCH");if((0,o.isNavigatingToNewRootLayout)(h,c))return(0,a.handleExternalUrl)(e,d,e.canonicalUrl,e.pushRef.pendingPush);let p=s?(0,n.createHrefFromUrl)(s):void 0;p&&(d.canonicalUrl=p),(0,l.applyFlightData)(y,f,t),d.previousTree=h,d.patchedTree=c,d.cache=f,y=f,h=c}return(0,i.handleMutable)(e,d)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2003:function(e,t){"use strict";var r,n;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PrefetchKind:function(){return r},ACTION_REFRESH:function(){return u},ACTION_NAVIGATE:function(){return o},ACTION_RESTORE:function(){return a},ACTION_SERVER_PATCH:function(){return l},ACTION_PREFETCH:function(){return i},ACTION_FAST_REFRESH:function(){return c},ACTION_SERVER_ACTION:function(){return s}});let u="refresh",o="navigate",a="restore",l="server-patch",i="prefetch",c="fast-refresh",s="server-action";(n=r||(r={})).AUTO="auto",n.FULL="full",n.TEMPORARY="temporary",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8061:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"reducer",{enumerable:!0,get:function(){return f}});let n=r(2003),u=r(9964),o=r(2767),a=r(2721),l=r(4531),i=r(4605),c=r(9851),s=r(6227),f=function(e,t){switch(t.type){case n.ACTION_NAVIGATE:return(0,u.navigateReducer)(e,t);case n.ACTION_SERVER_PATCH:return(0,o.serverPatchReducer)(e,t);case n.ACTION_RESTORE:return(0,a.restoreReducer)(e,t);case n.ACTION_REFRESH:return(0,l.refreshReducer)(e,t);case n.ACTION_FAST_REFRESH:return(0,c.fastRefreshReducer)(e,t);case n.ACTION_PREFETCH:return(0,i.prefetchReducer)(e,t);case n.ACTION_SERVER_ACTION:return(0,s.serverActionReducer)(e,t);default:throw Error("Unknown action")}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3973:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"shouldHardNavigate",{enumerable:!0,get:function(){return function e(t,r){let[u,o]=r,[a,l]=t;if(!(0,n.matchSegment)(a,u))return!!Array.isArray(a);let i=t.length<=2;return!i&&e(t.slice(2),o[l])}}});let n=r(2628);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9425:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createSearchParamsBailoutProxy",{enumerable:!0,get:function(){return u}});let n=r(4702);function u(){return new Proxy({},{get(e,t){"string"==typeof t&&(0,n.staticGenerationBailout)("searchParams."+t)}})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4702:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationBailout",{enumerable:!0,get:function(){return a}});let n=r(9811),u=r(7832);class o extends Error{constructor(...e){super(...e),this.code="NEXT_STATIC_GEN_BAILOUT"}}let a=(e,t)=>{let r=u.staticGenerationAsyncStorage.getStore();if(null==r?void 0:r.forceStatic)return!0;if(null==r?void 0:r.dynamicShouldError){let{dynamic:r="error",link:n}=t||{};throw new o('Page with `dynamic = "'+r+"\"` couldn't be rendered statically because it used `"+e+"`."+(n?" See more info here: "+n:""))}if(r&&(r.revalidate=0),null==r?void 0:r.isStaticGeneration){let t=new n.DynamicServerError(e);throw r.dynamicUsageDescription=e,r.dynamicUsageStack=t.stack,t}return!1};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4143:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let n=r(6927),u=n._(r(6006)),o=r(9425);function a(e){let{Component:t,propsForComponent:r}=e,n=(0,o.createSearchParamsBailoutProxy)();return u.default.createElement(t,{searchParams:n,...r})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7744:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"useReducerWithReduxDevtools",{enumerable:!0,get:function(){return o}});let n=r(6006);function u(e){if(e instanceof Map){let t={};for(let[r,n]of e.entries()){if("function"==typeof n){t[r]="fn()";continue}if("object"==typeof n&&null!==n){if(n.$$typeof){t[r]=n.$$typeof.toString();continue}if(n._bundlerConfig){t[r]="FlightData";continue}}t[r]=u(n)}return t}if("object"==typeof e&&null!==e){let t={};for(let r in e){let n=e[r];if("function"==typeof n){t[r]="fn()";continue}if("object"==typeof n&&null!==n){if(n.$$typeof){t[r]=n.$$typeof.toString();continue}if(n.hasOwnProperty("_bundlerConfig")){t[r]="FlightData";continue}}t[r]=u(n)}return t}return Array.isArray(e)?e.map(u):e}let o=function(e,t){let r=(0,n.useRef)(),o=(0,n.useRef)();(0,n.useEffect)(()=>{if(!r.current&&!1!==o.current){if(void 0===o.current&&void 0===window.__REDUX_DEVTOOLS_EXTENSION__){o.current=!1;return}return r.current=window.__REDUX_DEVTOOLS_EXTENSION__.connect({instanceId:8e3,name:"next-router"}),r.current&&r.current.init(u(t)),()=>{r.current=void 0}}},[t]);let[a,l]=(0,n.useReducer)((t,n)=>{let o=e(t,n);return r.current&&r.current.send(n,u(o)),o},t),i=(0,n.useCallback)(()=>{r.current&&r.current.send({type:"RENDER_SYNC"},u(a))},[a]);return[a,l,i]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7052:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return o}});let n=r(694),u=r(9854),o=e=>{if(!e.startsWith("/"))return e;let{pathname:t,query:r,hash:o}=(0,u.parsePath)(e);return""+(0,n.removeTrailingSlash)(t)+r+o};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7483:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return u}});let n=r(4722);function u(e){let t="function"==typeof reportError?reportError:e=>{window.console.error(e)};e.digest!==n.NEXT_DYNAMIC_NO_SSR_CODE&&t(e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6406:function(e,t,r){"use strict";var n,u;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{CacheStates:function(){return n},AppRouterContext:function(){return l},LayoutRouterContext:function(){return i},GlobalLayoutRouterContext:function(){return c},TemplateContext:function(){return s}});let o=r(6927),a=o._(r(6006));(u=n||(n={})).LAZY_INITIALIZED="LAZYINITIALIZED",u.DATA_FETCH="DATAFETCH",u.READY="READY";let l=a.default.createContext(null),i=a.default.createContext(null),c=a.default.createContext(null),s=a.default.createContext(null)},5415:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HeadManagerContext",{enumerable:!0,get:function(){return o}});let n=r(6927),u=n._(r(6006)),o=u.default.createContext({})},1416:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{SearchParamsContext:function(){return u},PathnameContext:function(){return o}});let n=r(6006),u=(0,n.createContext)(null),o=(0,n.createContext)(null)},4722:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NEXT_DYNAMIC_NO_SSR_CODE",{enumerable:!0,get:function(){return r}});let r="NEXT_DYNAMIC_NO_SSR_CODE"},5612:function(e,t){"use strict";function r(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return r}})},5697:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return u}});let n=r(9854);function u(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:u,hash:o}=(0,n.parsePath)(e);return""+t+r+u+o}},6811:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeAppPath:function(){return u},normalizeRscPath:function(){return o}});let n=r(5612);function u(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,r,n)=>!t||t.startsWith("(")&&t.endsWith(")")||t.startsWith("@")||("page"===t||"route"===t)&&r===n.length-1?e:e+"/"+t,""))}function o(e,t){return t?e.replace(/\.rsc($|\?)/,"$1"):e}},1200:function(e,t){"use strict";function r(e,t){void 0===t&&(t={});let r=document.documentElement,n=r.style.scrollBehavior;r.style.scrollBehavior="auto",t.dontForceLayout||r.getClientRects(),e(),r.style.scrollBehavior=n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSmoothScroll",{enumerable:!0,get:function(){return r}})},7377:function(e,t){"use strict";function r(e){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isBot",{enumerable:!0,get:function(){return r}})},9854:function(e,t){"use strict";function r(e){let t=e.indexOf("#"),r=e.indexOf("?"),n=r>-1&&(t<0||r<t);return n||t>-1?{pathname:e.substring(0,n?r:t),query:n?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return r}})},694:function(e,t){"use strict";function r(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return r}})},3063:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ServerInsertedHTMLContext:function(){return o},useServerInsertedHTML:function(){return a}});let n=r(5909),u=n._(r(6006)),o=u.default.createContext(null);function a(e){let t=(0,u.useContext)(o);t&&t(e)}},5863:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"requestAsyncStorage",{enumerable:!0,get:function(){return u}});let n=r(2143),u=(0,n.createAsyncLocalStorage)();("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7832:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationAsyncStorage",{enumerable:!0,get:function(){return u}});let n=r(2143),u=(0,n.createAsyncLocalStorage)();("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3194:function(e,t,r){"use strict";var n=r(8431);t.createRoot=n.createRoot,t.hydrateRoot=n.hydrateRoot},8431:function(e,t,r){"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=r(2614)},2672:function(e,t,r){"use strict";/** - * @license React - * react-server-dom-webpack-client.browser.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var n=r(8431),u=r(6006),o={stream:!0},a=new Map,l=new Map;function i(){}var c=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Dispatcher,s=Symbol.for("react.element"),f=Symbol.for("react.lazy"),d=Symbol.for("react.default_value"),p=Symbol.iterator,h=Array.isArray,y=new WeakMap;function _(e,t,r,n){var u=1,o=0,a=null;e=JSON.stringify(e,function e(l,i){if(null===i)return null;if("object"==typeof i){if("function"==typeof i.then){null===a&&(a=new FormData),o++;var c,s,f=u++;return i.then(function(n){n=JSON.stringify(n,e);var u=a;u.append(t+f,n),0==--o&&r(u)},function(e){n(e)}),"$@"+f.toString(16)}if(i instanceof FormData){null===a&&(a=new FormData);var d=a,_=t+(l=u++)+"_";return i.forEach(function(e,t){d.append(_+t,e)}),"$K"+l.toString(16)}return!h(i)&&(null===(s=i)||"object"!=typeof s?null:"function"==typeof(s=p&&s[p]||s["@@iterator"])?s:null)?Array.from(i):i}if("string"==typeof i)return"Z"===i[i.length-1]&&this[l]instanceof Date?"$D"+i:i="$"===i[0]?"$"+i:i;if("boolean"==typeof i)return i;if("number"==typeof i)return Number.isFinite(c=i)?0===c&&-1/0==1/c?"$-0":c:1/0===c?"$Infinity":-1/0===c?"$-Infinity":"$NaN";if(void 0===i)return"$undefined";if("function"==typeof i){if(void 0!==(i=y.get(i)))return i=JSON.stringify(i,e),null===a&&(a=new FormData),l=u++,a.set(t+l,i),"$F"+l.toString(16);throw Error("Client Functions cannot be passed directly to Server Functions. Only Functions passed from the Server can be passed back again.")}if("symbol"==typeof i){if(Symbol.for(l=i.description)!==i)throw Error("Only global symbols received from Symbol.for(...) can be passed to Server Functions. The symbol Symbol.for("+i.description+") cannot be found among global symbols.");return"$S"+l}if("bigint"==typeof i)return"$n"+i.toString(10);throw Error("Type "+typeof i+" is not supported as an argument to a Server Function.")}),null===a?r(e):(a.set(t+"0",e),0===o&&r(a))}var b=new WeakMap;function v(e){var t=y.get(this);if(!t)throw Error("Tried to encode a Server Action from a different instance than the encoder is from. This is a bug in React.");var r=null;if(null!==t.bound){if((r=b.get(t))||(n=t,a=new Promise(function(e,t){u=e,o=t}),_(n,"",function(e){if("string"==typeof e){var t=new FormData;t.append("0",e),e=t}a.status="fulfilled",a.value=e,u(e)},function(e){a.status="rejected",a.reason=e,o(e)}),r=a,b.set(t,r)),"rejected"===r.status)throw r.reason;if("fulfilled"!==r.status)throw r;t=r.value;var n,u,o,a,l=new FormData;t.forEach(function(t,r){l.append("$ACTION_"+e+":"+r,t)}),r=l,t="$ACTION_REF_"+e}else t="$ACTION_ID_"+t.id;return{name:t,method:"POST",encType:"multipart/form-data",data:r}}var m=u.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ContextRegistry;function g(e,t,r,n){this.status=e,this.value=t,this.reason=r,this._response=n}function O(e){switch(e.status){case"resolved_model":M(e);break;case"resolved_module":w(e)}switch(e.status){case"fulfilled":return e.value;case"pending":case"blocked":throw e;default:throw e.reason}}function P(e,t){for(var r=0;r<e.length;r++)(0,e[r])(t)}function E(e,t,r){switch(e.status){case"fulfilled":P(t,e.value);break;case"pending":case"blocked":e.value=t,e.reason=r;break;case"rejected":r&&P(r,e.reason)}}function R(e,t){if("pending"===e.status||"blocked"===e.status){var r=e.reason;e.status="rejected",e.reason=t,null!==r&&P(r,t)}}function j(e,t){if("pending"===e.status||"blocked"===e.status){var r=e.value,n=e.reason;e.status="resolved_module",e.value=t,null!==r&&(w(e),E(e,r,n))}}g.prototype=Object.create(Promise.prototype),g.prototype.then=function(e,t){switch(this.status){case"resolved_model":M(this);break;case"resolved_module":w(this)}switch(this.status){case"fulfilled":e(this.value);break;case"pending":case"blocked":e&&(null===this.value&&(this.value=[]),this.value.push(e)),t&&(null===this.reason&&(this.reason=[]),this.reason.push(t));break;default:t(this.reason)}};var S=null,T=null;function M(e){var t=S,r=T;S=e,T=null;try{var n=JSON.parse(e.value,e._response._fromJSON);null!==T&&0<T.deps?(T.value=n,e.status="blocked",e.value=null,e.reason=null):(e.status="fulfilled",e.value=n)}catch(t){e.status="rejected",e.reason=t}finally{S=t,T=r}}function w(e){try{var t=e.value;if(t.async){var r=l.get(t.id);if("fulfilled"===r.status)var n=r.value;else throw r.reason}else n=globalThis.__next_require__(t.id);var u="*"===t.name?n:""===t.name?n.__esModule?n.default:n:n[t.name];e.status="fulfilled",e.value=u}catch(t){e.status="rejected",e.reason=t}}function C(e,t){e._chunks.forEach(function(e){"pending"===e.status&&R(e,t)})}function A(e,t){var r=e._chunks,n=r.get(t);return n||(n=new g("pending",null,null,e),r.set(t,n)),n}function x(){throw Error('Trying to call a function from "use server" but the callServer option was not implemented in your router runtime.')}function I(e){C(e,Error("Connection closed."))}function N(e,t){if(""!==t){var r=t.indexOf(":",0),n=parseInt(t.slice(0,r),16);switch(t[r+1]){case"I":!function(e,t,r){var n=e._chunks,u=n.get(t);r=JSON.parse(r,e._fromJSON);var o=function(e,t){if(e){var r=e[t.id];if(e=r[t.name])r=e.name;else{if(!(e=r["*"]))throw Error('Could not find the module "'+t.id+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');r=t.name}return{id:e.id,chunks:e.chunks,name:r,async:!!t.async}}return t}(e._bundlerConfig,r);if(r=function(e){for(var t=e.chunks,r=[],n=0;n<t.length;n++){var u=t[n],o=a.get(u);if(void 0===o){o=globalThis.__next_chunk_load__(u),r.push(o);var c=a.set.bind(a,u,null);o.then(c,i),a.set(u,o)}else null!==o&&r.push(o)}if(e.async){if(t=l.get(e.id))return"fulfilled"===t.status?null:t;var s=Promise.all(r).then(function(){return globalThis.__next_require__(e.id)});return s.then(function(e){s.status="fulfilled",s.value=e},function(e){s.status="rejected",s.reason=e}),l.set(e.id,s),s}return 0<r.length?Promise.all(r):null}(o)){if(u){var c=u;c.status="blocked"}else c=new g("blocked",null,null,e),n.set(t,c);r.then(function(){return j(c,o)},function(e){return R(c,e)})}else u?j(u,o):n.set(t,new g("resolved_module",o,null,e))}(e,n,t.slice(r+2));break;case"H":if(n=t[r+2],e=JSON.parse(t=t.slice(r+3),e._fromJSON),t=c.current){if("string"==typeof e)r=e;else{r=e[0];var u=e[1]}switch(n){case"D":t.prefetchDNS(r,u);break;case"C":t.preconnect(r,u);break;case"L":t.preload(r,u);break;case"I":t.preinit(r,u)}}break;case"E":t=JSON.parse(t.slice(r+2)).digest,(u=Error("An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.")).stack="Error: "+u.message,u.digest=t,(r=(t=e._chunks).get(n))?R(r,u):t.set(n,new g("rejected",null,u,e));break;default:u=t.slice(r+1),(t=(r=e._chunks).get(n))?"pending"===t.status&&(e=t.value,n=t.reason,t.status="resolved_model",t.value=u,null!==e&&(M(t),E(t,e,n))):r.set(n,new g("resolved_model",u,null,e))}}}function D(e){e=e&&e.callServer?e.callServer:void 0;var t,r=new TextDecoder;return(e={_bundlerConfig:null,_callServer:void 0!==e?e:x,_chunks:new Map,_partialRow:"",_stringDecoder:r})._fromJSON=(t=e,function(e,r){return"string"==typeof r?function(e,t,r,n){if("$"===n[0]){if("$"===n)return s;switch(n[1]){case"$":return n.slice(1);case"L":return{$$typeof:f,_payload:e=A(e,t=parseInt(n.slice(2),16)),_init:O};case"@":return A(e,t=parseInt(n.slice(2),16));case"S":return Symbol.for(n.slice(2));case"P":return m[e=n.slice(2)]||(m[e]=u.createServerContext(e,d)),m[e].Provider;case"F":if("resolved_model"===(t=A(e,t=parseInt(n.slice(2),16))).status&&M(t),"fulfilled"===t.status)return function(e,t){function r(){var e=Array.prototype.slice.call(arguments),r=t.bound;return r?"fulfilled"===r.status?n(t.id,r.value.concat(e)):Promise.resolve(r).then(function(r){return n(t.id,r.concat(e))}):n(t.id,e)}var n=e._callServer;return r.$$FORM_ACTION=v,y.set(r,t),r}(e,t.value);throw t.reason;case"I":return 1/0;case"-":return"$-0"===n?-0:-1/0;case"N":return NaN;case"u":return;case"D":return new Date(Date.parse(n.slice(2)));case"n":return BigInt(n.slice(2));default:switch((e=A(e,n=parseInt(n.slice(1),16))).status){case"resolved_model":M(e);break;case"resolved_module":w(e)}switch(e.status){case"fulfilled":return e.value;case"pending":case"blocked":var o;return n=S,e.then(function(e,t,r){if(T){var n=T;n.deps++}else n=T={deps:1,value:null};return function(u){t[r]=u,n.deps--,0===n.deps&&"blocked"===e.status&&(u=e.value,e.status="fulfilled",e.value=n.value,null!==u&&P(u,n.value))}}(n,t,r),(o=n,function(e){return R(o,e)})),null;default:throw e.reason}}}return n}(t,this,e,r):"object"==typeof r&&null!==r?e=r[0]===s?{$$typeof:s,type:r[1],key:r[2],ref:null,props:r[3],_owner:null}:r:r}),e}function F(e,t){function r(t){C(e,t)}var n=t.getReader();n.read().then(function t(u){var a=u.value;if(u.done)I(e);else{u=a,a=e._stringDecoder;for(var l=u.indexOf(10);-1<l;){var i=e._partialRow,c=u.subarray(0,l);N(e,i+(c=a.decode(c))),e._partialRow="",l=(u=u.subarray(l+1)).indexOf(10)}return e._partialRow+=a.decode(u,o),n.read().then(t).catch(r)}}).catch(r)}t.createFromFetch=function(e,t){var r=D(t);return e.then(function(e){F(r,e.body)},function(e){C(r,e)}),A(r,0)},t.createFromReadableStream=function(e,t){return F(t=D(t),e),A(t,0)},t.createFromXHR=function(e,t){function r(){for(var t=e.responseText,r=o,n=t.indexOf("\n",r);-1<n;)r=u._partialRow+t.slice(r,n),N(u,r),u._partialRow="",r=n+1,n=t.indexOf("\n",r);u._partialRow+=t.slice(r),o=t.length}function n(){C(u,TypeError("Network error"))}var u=D(t),o=0;return e.addEventListener("progress",r),e.addEventListener("load",function(){r(),I(u)}),e.addEventListener("error",n),e.addEventListener("abort",n),e.addEventListener("timeout",n),A(u,0)},t.createServerReference=function(e,t){function r(){var r=Array.prototype.slice.call(arguments);return t(e,r)}return r.$$FORM_ACTION=v,y.set(r,{id:e,bound:null}),r},t.encodeReply=function(e){return new Promise(function(t,r){_(e,"",t,r)})}},3488:function(e,t,r){"use strict";e.exports=r(2672)},5456:function(e,t,r){"use strict";e.exports=r(3488)},8110:function(e,t){"use strict";/** - * @license React - * react.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var r=Symbol.for("react.element"),n=Symbol.for("react.portal"),u=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),i=Symbol.for("react.context"),c=Symbol.for("react.server_context"),s=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),h=Symbol.for("react.default_value"),y=Symbol.iterator,_={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b=Object.assign,v={};function m(e,t,r){this.props=e,this.context=t,this.refs=v,this.updater=r||_}function g(){}function O(e,t,r){this.props=e,this.context=t,this.refs=v,this.updater=r||_}m.prototype.isReactComponent={},m.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},m.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},g.prototype=m.prototype;var P=O.prototype=new g;P.constructor=O,b(P,m.prototype),P.isPureReactComponent=!0;var E=Array.isArray,R=Object.prototype.hasOwnProperty,j={current:null},S={key:!0,ref:!0,__self:!0,__source:!0};function T(e,t,n){var u,o={},a=null,l=null;if(null!=t)for(u in void 0!==t.ref&&(l=t.ref),void 0!==t.key&&(a=""+t.key),t)R.call(t,u)&&!S.hasOwnProperty(u)&&(o[u]=t[u]);var i=arguments.length-2;if(1===i)o.children=n;else if(1<i){for(var c=Array(i),s=0;s<i;s++)c[s]=arguments[s+2];o.children=c}if(e&&e.defaultProps)for(u in i=e.defaultProps)void 0===o[u]&&(o[u]=i[u]);return{$$typeof:r,type:e,key:a,ref:l,props:o,_owner:j.current}}function M(e){return"object"==typeof e&&null!==e&&e.$$typeof===r}var w=/\/+/g;function C(e,t){var r,n;return"object"==typeof e&&null!==e&&null!=e.key?(r=""+e.key,n={"=":"=0",":":"=2"},"$"+r.replace(/[=:]/g,function(e){return n[e]})):t.toString(36)}function A(e,t,u){if(null==e)return e;var o=[],a=0;return!function e(t,u,o,a,l){var i,c,s,f=typeof t;("undefined"===f||"boolean"===f)&&(t=null);var d=!1;if(null===t)d=!0;else switch(f){case"string":case"number":d=!0;break;case"object":switch(t.$$typeof){case r:case n:d=!0}}if(d)return l=l(d=t),t=""===a?"."+C(d,0):a,E(l)?(o="",null!=t&&(o=t.replace(w,"$&/")+"/"),e(l,u,o,"",function(e){return e})):null!=l&&(M(l)&&(i=l,c=o+(!l.key||d&&d.key===l.key?"":(""+l.key).replace(w,"$&/")+"/")+t,l={$$typeof:r,type:i.type,key:c,ref:i.ref,props:i.props,_owner:i._owner}),u.push(l)),1;if(d=0,a=""===a?".":a+":",E(t))for(var p=0;p<t.length;p++){f=t[p];var h=a+C(f,p);d+=e(f,u,o,h,l)}else if("function"==typeof(h=null===(s=t)||"object"!=typeof s?null:"function"==typeof(s=y&&s[y]||s["@@iterator"])?s:null))for(t=h.call(t),p=0;!(f=t.next()).done;)h=a+C(f=f.value,p++),d+=e(f,u,o,h,l);else if("object"===f)throw Error("Objects are not valid as a React child (found: "+("[object Object]"===(u=String(t))?"object with keys {"+Object.keys(t).join(", ")+"}":u)+"). If you meant to render a collection of children, use an array instead.");return d}(e,o,"","",function(e){return t.call(u,e,a++)}),o}function x(e){if(-1===e._status){var t=e._result;(t=t()).then(function(t){(0===e._status||-1===e._status)&&(e._status=1,e._result=t)},function(t){(0===e._status||-1===e._status)&&(e._status=2,e._result=t)}),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var I={current:null};function N(){return new WeakMap}function D(){return{s:0,v:void 0,o:null,p:null}}var F={current:null},k={transition:null},L={ReactCurrentDispatcher:F,ReactCurrentCache:I,ReactCurrentBatchConfig:k,ReactCurrentOwner:j,ContextRegistry:{}},U=L.ContextRegistry;t.Children={map:A,forEach:function(e,t,r){A(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return A(e,function(){t++}),t},toArray:function(e){return A(e,function(e){return e})||[]},only:function(e){if(!M(e))throw Error("React.Children.only expected to receive a single React element child.");return e}},t.Component=m,t.Fragment=u,t.Profiler=a,t.PureComponent=O,t.StrictMode=o,t.Suspense=f,t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=L,t.cache=function(e){return function(){var t=I.current;if(!t)return e.apply(null,arguments);var r=t.getCacheForType(N);void 0===(t=r.get(e))&&(t=D(),r.set(e,t)),r=0;for(var n=arguments.length;r<n;r++){var u=arguments[r];if("function"==typeof u||"object"==typeof u&&null!==u){var o=t.o;null===o&&(t.o=o=new WeakMap),void 0===(t=o.get(u))&&(t=D(),o.set(u,t))}else null===(o=t.p)&&(t.p=o=new Map),void 0===(t=o.get(u))&&(t=D(),o.set(u,t))}if(1===t.s)return t.v;if(2===t.s)throw t.v;try{var a=e.apply(null,arguments);return(r=t).s=1,r.v=a}catch(e){throw(a=t).s=2,a.v=e,e}}},t.cloneElement=function(e,t,n){if(null==e)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var u=b({},e.props),o=e.key,a=e.ref,l=e._owner;if(null!=t){if(void 0!==t.ref&&(a=t.ref,l=j.current),void 0!==t.key&&(o=""+t.key),e.type&&e.type.defaultProps)var i=e.type.defaultProps;for(c in t)R.call(t,c)&&!S.hasOwnProperty(c)&&(u[c]=void 0===t[c]&&void 0!==i?i[c]:t[c])}var c=arguments.length-2;if(1===c)u.children=n;else if(1<c){i=Array(c);for(var s=0;s<c;s++)i[s]=arguments[s+2];u.children=i}return{$$typeof:r,type:e.type,key:o,ref:a,props:u,_owner:l}},t.createContext=function(e){return(e={$$typeof:i,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:l,_context:e},e.Consumer=e},t.createElement=T,t.createFactory=function(e){var t=T.bind(null,e);return t.type=e,t},t.createRef=function(){return{current:null}},t.createServerContext=function(e,t){var r=!0;if(!U[e]){r=!1;var n={$$typeof:c,_currentValue:t,_currentValue2:t,_defaultValue:t,_threadCount:0,Provider:null,Consumer:null,_globalName:e};n.Provider={$$typeof:l,_context:n},U[e]=n}if((n=U[e])._defaultValue===h)n._defaultValue=t,n._currentValue===h&&(n._currentValue=t),n._currentValue2===h&&(n._currentValue2=t);else if(r)throw Error("ServerContext: "+e+" already defined");return n},t.forwardRef=function(e){return{$$typeof:s,render:e}},t.isValidElement=M,t.lazy=function(e){return{$$typeof:p,_payload:{_status:-1,_result:e},_init:x}},t.memo=function(e,t){return{$$typeof:d,type:e,compare:void 0===t?null:t}},t.startTransition=function(e){var t=k.transition;k.transition={};try{e()}finally{k.transition=t}},t.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.")},t.unstable_useCacheRefresh=function(){return F.current.useCacheRefresh()},t.use=function(e){return F.current.use(e)},t.useCallback=function(e,t){return F.current.useCallback(e,t)},t.useContext=function(e){return F.current.useContext(e)},t.useDebugValue=function(){},t.useDeferredValue=function(e){return F.current.useDeferredValue(e)},t.useEffect=function(e,t){return F.current.useEffect(e,t)},t.useId=function(){return F.current.useId()},t.useImperativeHandle=function(e,t,r){return F.current.useImperativeHandle(e,t,r)},t.useInsertionEffect=function(e,t){return F.current.useInsertionEffect(e,t)},t.useLayoutEffect=function(e,t){return F.current.useLayoutEffect(e,t)},t.useMemo=function(e,t){return F.current.useMemo(e,t)},t.useReducer=function(e,t,r){return F.current.useReducer(e,t,r)},t.useRef=function(e){return F.current.useRef(e)},t.useState=function(e){return F.current.useState(e)},t.useSyncExternalStore=function(e,t,r){return F.current.useSyncExternalStore(e,t,r)},t.useTransition=function(){return F.current.useTransition()},t.version="18.3.0-canary-16d053d59-20230506"},6006:function(e,t,r){"use strict";e.exports=r(8110)},4248:function(e,t){"use strict";/** - * @license React - * scheduler.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */function r(e,t){var r=e.length;e.push(t);e:for(;0<r;){var n=r-1>>>1,u=e[n];if(0<o(u,t))e[n]=t,e[r]=u,r=n;else break e}}function n(e){return 0===e.length?null:e[0]}function u(e){if(0===e.length)return null;var t=e[0],r=e.pop();if(r!==t){e[0]=r;e:for(var n=0,u=e.length,a=u>>>1;n<a;){var l=2*(n+1)-1,i=e[l],c=l+1,s=e[c];if(0>o(i,r))c<u&&0>o(s,i)?(e[n]=s,e[c]=r,n=c):(e[n]=i,e[l]=r,n=l);else if(c<u&&0>o(s,r))e[n]=s,e[c]=r,n=c;else break e}}return t}function o(e,t){var r=e.sortIndex-t.sortIndex;return 0!==r?r:e.id-t.id}if(t.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var a,l=performance;t.unstable_now=function(){return l.now()}}else{var i=Date,c=i.now();t.unstable_now=function(){return i.now()-c}}var s=[],f=[],d=1,p=null,h=3,y=!1,_=!1,b=!1,v="function"==typeof setTimeout?setTimeout:null,m="function"==typeof clearTimeout?clearTimeout:null,g="undefined"!=typeof setImmediate?setImmediate:null;function O(e){for(var t=n(f);null!==t;){if(null===t.callback)u(f);else if(t.startTime<=e)u(f),t.sortIndex=t.expirationTime,r(s,t);else break;t=n(f)}}function P(e){if(b=!1,O(e),!_){if(null!==n(s))_=!0,I(E);else{var t=n(f);null!==t&&N(P,t.startTime-e)}}}function E(e,r){_=!1,b&&(b=!1,m(S),S=-1),y=!0;var o=h;try{e:{for(O(r),p=n(s);null!==p&&(!(p.expirationTime>r)||e&&!w());){var a=p.callback;if("function"==typeof a){p.callback=null,h=p.priorityLevel;var l=a(p.expirationTime<=r);if(r=t.unstable_now(),"function"==typeof l){p.callback=l,O(r);var i=!0;break e}p===n(s)&&u(s),O(r)}else u(s);p=n(s)}if(null!==p)i=!0;else{var c=n(f);null!==c&&N(P,c.startTime-r),i=!1}}return i}finally{p=null,h=o,y=!1}}"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var R=!1,j=null,S=-1,T=5,M=-1;function w(){return!(t.unstable_now()-M<T)}function C(){if(null!==j){var e=t.unstable_now();M=e;var r=!0;try{r=j(!0,e)}finally{r?a():(R=!1,j=null)}}else R=!1}if("function"==typeof g)a=function(){g(C)};else if("undefined"!=typeof MessageChannel){var A=new MessageChannel,x=A.port2;A.port1.onmessage=C,a=function(){x.postMessage(null)}}else a=function(){v(C,0)};function I(e){j=e,R||(R=!0,a())}function N(e,r){S=v(function(){e(t.unstable_now())},r)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){_||y||(_=!0,I(E))},t.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):T=0<e?Math.floor(1e3/e):5},t.unstable_getCurrentPriorityLevel=function(){return h},t.unstable_getFirstCallbackNode=function(){return n(s)},t.unstable_next=function(e){switch(h){case 1:case 2:case 3:var t=3;break;default:t=h}var r=h;h=t;try{return e()}finally{h=r}},t.unstable_pauseExecution=function(){},t.unstable_requestPaint=function(){},t.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var r=h;h=e;try{return t()}finally{h=r}},t.unstable_scheduleCallback=function(e,u,o){var a=t.unstable_now();switch(o="object"==typeof o&&null!==o&&"number"==typeof(o=o.delay)&&0<o?a+o:a,e){case 1:var l=-1;break;case 2:l=250;break;case 5:l=1073741823;break;case 4:l=1e4;break;default:l=5e3}return l=o+l,e={id:d++,callback:u,priorityLevel:e,startTime:o,expirationTime:l,sortIndex:-1},o>a?(e.sortIndex=o,r(f,e),null===n(s)&&e===n(f)&&(b?(m(S),S=-1):b=!0,N(P,o-a))):(e.sortIndex=l,r(s,e),_||y||(_=!0,I(E))),e},t.unstable_shouldYield=w,t.unstable_wrapCallback=function(e){var t=h;return function(){var r=h;h=t;try{return e.apply(this,arguments)}finally{h=r}}}},6183:function(e,t,r){"use strict";e.exports=r(4248)},4778:function(e,t){"use strict";function r(e){return e.startsWith("[[...")&&e.endsWith("]]")?{type:"optional-catchall",param:e.slice(5,-2)}:e.startsWith("[...")&&e.endsWith("]")?{type:"catchall",param:e.slice(4,-1)}:e.startsWith("[")&&e.endsWith("]")?{type:"dynamic",param:e.slice(1,-1)}:null}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentParam",{enumerable:!0,get:function(){return r}})},7399:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return u},isInterceptionRouteAppPath:function(){return o},extractInterceptionRouteInformation:function(){return a}});let n=r(6811),u=["(..)(..)","(.)","(..)","(...)"];function o(e){return void 0!==e.split("/").find(e=>u.find(t=>e.startsWith(t)))}function a(e){let t,r,o;for(let n of e.split("/"))if(r=u.find(e=>n.startsWith(e))){[t,o]=e.split(r,2);break}if(!t||!r||!o)throw Error(`Invalid interception route: ${e}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`);switch(t=(0,n.normalizeAppPath)(t),r){case"(.)":o="/"===t?`/${o}`:t+"/"+o;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);o=t.split("/").slice(0,-1).concat(o).join("/");break;case"(...)":o="/"+o;break;case"(..)(..)":let a=t.split("/");if(a.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);o=a.slice(0,-2).concat(o).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:o}}},6927:function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:function(){return n},_interop_require_default:function(){return n}})},5909:function(e,t,r){"use strict";function n(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(n=function(e){return e?r:t})(e)}function u(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=n(t);if(r&&r.has(e))return r.get(e);var u={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&Object.prototype.hasOwnProperty.call(e,a)){var l=o?Object.getOwnPropertyDescriptor(e,a):null;l&&(l.get||l.set)?Object.defineProperty(u,a,l):u[a]=e[a]}return u.default=e,r&&r.set(e,u),u}r.r(t),r.d(t,{_:function(){return u},_interop_require_wildcard:function(){return u}})}}]); \ No newline at end of file diff --git a/.next/static/chunks/51231e76-cf1b2fc1d6b83e48.js b/.next/static/chunks/51231e76-cf1b2fc1d6b83e48.js deleted file mode 100644 index f04bb2e..0000000 --- a/.next/static/chunks/51231e76-cf1b2fc1d6b83e48.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[669],{4826:function(e,t,r){r.d(t,{B:function(){return S}});var i=r(3914),s=r(4213),n=r(4620),a=r(6702),l=r(3430),_=r(2267),h=r(7339),o=r(6452),u=r(7694),d=r(216),c=r(5310),g=r(6983),f=r(4696),E=r(5342),p=r(4499),T=r(9123),R=r(1470),x=r(3076),m=r(3587),b=r(8257);class A{}class S{static get NpmPackage(){return"babylonjs@6.18.0"}static get Version(){return"6.18.0"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return s.Q.ShadersRepository}static set ShadersRepository(e){s.Q.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){let e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);let r=document.createElement("canvas");return r.width=e,r.height=t,r}createCanvas(e,t){return S._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,r,i){var s,n,o,f,E,T,R,m,C,B,v;this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new a.y$,this._frameId=0,this._uniformBuffers=[],this._storageBuffers=[],this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=[],this.onContextLostObservable=new a.y$,this.onContextRestoredObservable=new a.y$,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new l.k,this._stencilStateComposer=new x.C,this._stencilState=new _.s,this._alphaState=new h.Q,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=[],this._renderTargetWrapperCache=[],this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=[],this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=[],this._currentInstanceLocations=[],this._currentInstanceBuffers=[],this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=[],this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=[],this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new a.y$,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=b.F.Now;let L=null;r=r||{},this._creationOptions=r,this.adaptToDeviceRatio=null!=i&&i,this._stencilStateComposer.stencilGlobal=this._stencilState,p.Z.SetMatrixPrecision(!!r.useHighPrecisionMatrix),r.antialias=null!=t?t:r.antialias,r.deterministicLockstep=null!==(s=r.deterministicLockstep)&&void 0!==s&&s,r.lockstepMaxSteps=null!==(n=r.lockstepMaxSteps)&&void 0!==n?n:4,r.timeStep=null!==(o=r.timeStep)&&void 0!==o?o:1/60,r.audioEngine=null===(f=r.audioEngine)||void 0===f||f,r.stencil=null===(E=r.stencil)||void 0===E||E,this._audioContext=null!==(R=null===(T=r.audioEngineOptions)||void 0===T?void 0:T.audioContext)&&void 0!==R?R:null,this._audioDestination=null!==(C=null===(m=r.audioEngineOptions)||void 0===m?void 0:m.audioDestination)&&void 0!==C?C:null,this.premultipliedAlpha=null===(B=r.premultipliedAlpha)||void 0===B||B,this.useExactSrgbConversions=null!==(v=r.useExactSrgbConversions)&&void 0!==v&&v,this._doNotHandleContextLost=!!r.doNotHandleContextLost,this._isStencilEnable=!!r.stencil,i=i||r.adaptToDeviceRatio||!1;let w=(0,d.CG)()&&window.devicePixelRatio||1,I=r.limitDeviceRatio||w;if(this._hardwareScalingLevel=i?1/Math.min(I,w):1,this._lastDevicePixelRatio=w,!e)return;if(e.getContext){if(L=e,this._renderingCanvas=L,void 0===r.preserveDrawingBuffer&&(r.preserveDrawingBuffer=!1),void 0===r.xrCompatible&&(r.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();let e=navigator.userAgent;for(let t of S.ExceptionList){let i=t.key,s=t.targets,n=new RegExp(i);if(n.test(e)){if(t.capture&&t.captureConstraint){let r=t.capture,i=t.captureConstraint,s=new RegExp(r),n=s.exec(e);if(n&&n.length>0){let e=parseInt(n[n.length-1]);if(e>=i)continue}}for(let e of s)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":r.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,u.Y.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(this._initGLContext.bind(this))},L.addEventListener("webglcontextlost",this._onContextLost,!1),L.addEventListener("webglcontextrestored",this._onContextRestored,!1),r.powerPreference=r.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(r.xrCompatible=!1),!r.disableWebGL2Support)try{this._gl=L.getContext("webgl2",r)||L.getContext("experimental-webgl2",r),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!L)throw Error("The provided canvas is null or undefined.");try{this._gl=L.getContext("webgl",r)||L.getContext("experimental-webgl",r)}catch(e){throw Error("WebGL not supported")}}if(!this._gl)throw Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";let t=this._gl.getContextAttributes();t&&(r.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==r.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=r.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e<this._caps.maxVertexAttribs;e++)this._currentBufferPointers[e]=new A;this._shaderProcessor=this.webGLVersion>1?new g.C:new c.f,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);let F=`Babylon.js v${S.Version}`;console.log(F+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",F)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{let e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&(0,d.n5)()&&"ontouchend"in document},this._checkForMobile(),(0,d.CG)()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null;let r=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),null===(t=this._rebuildComputeEffects)||void 0===t||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=r,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=n,u.Y.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){let e=this._internalTexturesCache.slice();for(let t of e)t._rebuild()}_rebuildRenderTargetWrappers(){let e=this._renderTargetWrapperCache.slice();for(let t of e)t._rebuild()}_rebuildEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}s.Q.ResetCache()}areAllEffectsReady(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];if(!t.isReady())return!1}return!0}_rebuildBuffers(){for(let e of this._uniformBuffers)e._rebuild();for(let e of this._storageBuffers)e._rebuild()}_initGLContext(){var e;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._glVersion=this._gl.getParameter(this._gl.VERSION);let t=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=t&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(null!==(e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))&&void 0!==e?e:0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{let e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{let e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{let e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{let e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){let e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{let e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{let e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!!(this._creationOptions&&this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e<this._maxSimultaneousTextures;e++)this._nextFreeTextureSlots.push(e);"Mali-G72"===this._glRenderer&&(this._caps.disableMorphTargetTexture=!0)}_initFeatures(){this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:1!==this._webGLVersion,supportDepthStencilTexture:1!==this._webGLVersion,supportShadowSamplers:1!==this._webGLVersion,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:1!==this._webGLVersion,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:1!==this._webGLVersion,basisNeedsPOT:1===this._webGLVersion,support3DTextures:1!==this._webGLVersion,needTypeSuffixInShaderConstants:1!==this._webGLVersion,supportMSAA:1!==this._webGLVersion,supportSSAO2:1!==this._webGLVersion,supportExtendedTextureFormats:1!==this._webGLVersion,supportSwitchCaseInShader:1!==this._webGLVersion,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}get isStencilEnable(){return this._isStencilEnable}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);let e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}resetTextureCache(){for(let e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}getLoadedTexturesCache(){return this._internalTexturesCache}getCaps(){return this._caps}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}let t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(this._renderingQueueLaunched&&this._frameHandler){if(this._renderingQueueLaunched=!1,(0,d.CG)()){let{cancelAnimationFrame:e}=this.getHostWindow()||window;if("function"==typeof e)return e(this._frameHandler)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(this._frameHandler);return clearTimeout(this._frameHandler)}}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e<this._activeRenderLoops.length;e++){let t=this._activeRenderLoops[e];t()}this.endFrame()}}this._activeRenderLoops.length>0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return(0,d.CG)()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}_queueNewFrame(e,t){return S.QueueNewFrame(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=this._renderLoop.bind(this),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,r,i=!1){var s,n;let a=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=a;let l=0;if(t&&e){let t=!0;if(this._currentRenderTarget){let r=null===(s=this._currentRenderTarget.texture)||void 0===s?void 0:s.format;if(8===r||9===r||10===r||11===r){let r=null===(n=this._currentRenderTarget.texture)||void 0===n?void 0:n.type;7===r||5===r?(S._TempClearColorUint32[0]=255*e.r,S._TempClearColorUint32[1]=255*e.g,S._TempClearColorUint32[2]=255*e.b,S._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,S._TempClearColorUint32),t=!1):(S._TempClearColorInt32[0]=255*e.r,S._TempClearColorInt32[1]=255*e.g,S._TempClearColorInt32[2]=255*e.b,S._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,S._TempClearColorInt32),t=!1)}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),l|=this._gl.COLOR_BUFFER_BIT)}r&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),l|=this._gl.DEPTH_BUFFER_BIT),i&&(this._gl.clearStencil(0),l|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(l)}_viewport(e,t,r,i){(e!==this._viewportCached.x||t!==this._viewportCached.y||r!==this._viewportCached.z||i!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=r,this._viewportCached.w=i,this._gl.viewport(e,t,r,i))}setViewport(e,t,r){let i=t||this.getRenderWidth(),s=r||this.getRenderHeight(),n=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(n*i,a*s,i*e.width,s*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,r;if(this.adaptToDeviceRatio){let e=(0,d.CG)()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if((0,d.CG)()&&(0,d.n5)()){if(this._renderingCanvas){let e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,r=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,r=window.innerHeight}else t=this._renderingCanvas?this._renderingCanvas.width:100,r=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,r/this._hardwareScalingLevel,e)}setSize(e,t,r=!1){return!!this._renderingCanvas&&(e|=0,t|=0,(!!r||this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)&&(this._renderingCanvas.width=e,this._renderingCanvas.height=t,!0))}bindFramebuffer(e,t=0,r,i,s,n=0,a=0){var l,_,h,o,u;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer);let d=this._gl;!e.isMulti&&(e.is2DArray?d.framebufferTextureLayer(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,null===(l=e.texture._hardwareTexture)||void 0===l?void 0:l.underlyingResource,n,a):e.isCube&&d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(_=e.texture._hardwareTexture)||void 0===_?void 0:_.underlyingResource,n));let c=e._depthStencilTexture;if(c){let r=e._depthStencilTextureWithStencil?d.DEPTH_STENCIL_ATTACHMENT:d.DEPTH_ATTACHMENT;e.is2DArray?d.framebufferTextureLayer(d.FRAMEBUFFER,r,null===(h=c._hardwareTexture)||void 0===h?void 0:h.underlyingResource,n,a):e.isCube?d.framebufferTexture2D(d.FRAMEBUFFER,r,d.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(o=c._hardwareTexture)||void 0===o?void 0:o.underlyingResource,n):d.framebufferTexture2D(d.FRAMEBUFFER,r,d.TEXTURE_2D,null===(u=c._hardwareTexture)||void 0===u?void 0:u.underlyingResource,n)}this._cachedViewport&&!s?this.setViewport(this._cachedViewport,r,i):(!r&&(r=e.width,n&&(r/=Math.pow(2,n))),!i&&(i=e.height,n&&(i/=Math.pow(2,n))),this._viewport(0,0,r,i)),this.wipeCaches()}setState(e,t=0,r,i=!1,s,n,a=0){var l,_;(this._depthCullingState.cull!==e||r)&&(this._depthCullingState.cull=e);let h=null===(_=null!==(l=this.cullBackFaces)&&void 0!==l?l:s)||void 0===_||_?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||r)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(a);let o=i?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==o||r)&&(this._depthCullingState.frontFace=o),this._stencilStateComposer.stencilMaterial=n}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){let e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){let e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,r){var i;this._currentRenderTarget=null;let s=this._gl;if(e._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,r);return}s.bindFramebuffer(s.READ_FRAMEBUFFER,e._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,e._framebuffer),s.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s.COLOR_BUFFER_BIT,s.NEAREST)}(null===(i=e.texture)||void 0===i?void 0:i.generateMipMaps)&&!t&&!e.isCube&&this.generateMipmaps(e.texture),r&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),r()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){let r=this._gl.createBuffer();if(!r)throw Error("Unable to create vertex buffer");let i=new f.M(r);return this.bindArrayBuffer(i),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),this._resetVertexBufferBinding(),i.references=1,i}createDynamicVertexBuffer(e){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t){let r=this._gl.createBuffer(),i=new f.M(r);if(!r)throw Error("Unable to create index buffer");this.bindIndexBuffer(i);let s=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),i.references=1,i.is32Bits=4===s.BYTES_PER_ELEMENT,i}_normalizeIndexData(e){let t=e.BYTES_PER_ELEMENT;if(2===t)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let t=0;t<e.length;t++)if(e[t]>=65535)return new Uint32Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,r){let i=e.program,s=this._gl.getUniformBlockIndex(i,t);this._gl.uniformBlockBinding(i,s,r)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,r,i,s,n,a){let l=this._currentBufferPointers[t];if(!l)return;let _=!1;l.active?(l.buffer!==e&&(l.buffer=e,_=!0),l.size!==r&&(l.size=r,_=!0),l.type!==i&&(l.type=i,_=!0),l.normalized!==s&&(l.normalized=s,_=!0),l.stride!==n&&(l.stride=n,_=!0),l.offset!==a&&(l.offset=a,_=!0)):(_=!0,l.active=!0,l.index=t,l.size=r,l.type=i,l.normalized=s,l.stride=n,l.offset=a,l.buffer=e),(_||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),i===this._gl.UNSIGNED_INT||i===this._gl.INT?this._gl.vertexAttribIPointer(t,r,i,n,a):this._gl.vertexAttribPointer(t,r,i,s,n,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,r){let i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s<i.length;s++){let n=t.getAttributeLocation(s);if(n>=0){let t=i[s],a=null;if(r&&(a=r[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);let l=a.getBuffer();l&&(this._vertexAttribPointer(l,n,a.getSize(),a.type,a.normalized,a.byteStride,a.byteOffset),a.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,a.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(l))))}}}recordVertexArrayObject(e,t,r,i){let s=this._gl.createVertexArray();if(!s)throw Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,r,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,r,i,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;let t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let a=0;a<t;a++)if(a<r.length){let t=s.getAttributeLocation(a);t>=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,r[a],this._gl.FLOAT,!1,i,n)),n+=4*r[a]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,r,i){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r,this._bindVertexBuffersAttributes(e,r,i)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,r=this._currentInstanceLocations.length;t<r;t++){let r=this._currentInstanceBuffers[t];e!=r&&r.references&&(e=r,this.bindArrayBuffer(r));let i=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(i,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0}releaseVertexArrayObject(e){this._gl.deleteVertexArray(e)}_releaseBuffer(e){return e.references--,0===e.references&&(this._deleteBuffer(e),!0)}_deleteBuffer(e){this._gl.deleteBuffer(e.underlyingResource)}updateAndBindInstancesBuffer(e,t,r){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==r[0].index)this.bindInstancesBuffer(e,r,!0);else for(let t=0;t<4;t++){let i=r[t];this._vertexAttribArraysEnabled[i]||(this._gl.enableVertexAttribArray(i),this._vertexAttribArraysEnabled[i]=!0),this._vertexAttribPointer(e,i,4,this._gl.FLOAT,!1,64,16*t),this._gl.vertexAttribDivisor(i,1),this._currentInstanceLocations.push(i),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,r=!0){this.bindArrayBuffer(e);let i=0;if(r)for(let e=0;e<t.length;e++){let r=t[e];i+=4*r.attributeSize}for(let r=0;r<t.length;r++){let s=t[r];void 0===s.index&&(s.index=this._currentEffect.getAttributeLocationByName(s.attributeName)),s.index<0||(this._vertexAttribArraysEnabled[s.index]||(this._gl.enableVertexAttribArray(s.index),this._vertexAttribArraysEnabled[s.index]=!0),this._vertexAttribPointer(e,s.index,s.attributeSize,s.attributeType||this._gl.FLOAT,s.normalized||!1,i,s.offset),this._gl.vertexAttribDivisor(s.index,void 0===s.divisor?1:s.divisor),this._currentInstanceLocations.push(s.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;let t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t,r=!1;for(;-1!==(t=this._currentInstanceLocations.indexOf(e));)this._currentInstanceLocations.splice(t,1),this._currentInstanceBuffers.splice(t,1),r=!0,t=this._currentInstanceLocations.indexOf(e);r&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))}disableAttributeByIndex(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1}draw(e,t,r,i){this.drawElementsType(e?0:1,t,r,i)}drawPointClouds(e,t,r){this.drawArraysType(2,e,t,r)}drawUnIndexed(e,t,r,i){this.drawArraysType(e?0:1,t,r,i)}drawElementsType(e,t,r,i){this.applyStates(),this._reportDrawCall();let s=this._drawMode(e),n=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,a=this._uintIndicesCurrentlySet?4:2;i?this._gl.drawElementsInstanced(s,r,n,t*a,i):this._gl.drawElements(s,r,n,t*a)}drawArraysType(e,t,r,i){this.applyStates(),this._reportDrawCall();let s=this._drawMode(e);i?this._gl.drawArraysInstanced(s,t,r,i):this._gl.drawArrays(s,t,r)}_drawMode(e){switch(e){case 0:default:return this._gl.TRIANGLES;case 2:case 3:return this._gl.POINTS;case 1:case 4:return this._gl.LINES;case 5:return this._gl.LINE_LOOP;case 6:return this._gl.LINE_STRIP;case 7:return this._gl.TRIANGLE_STRIP;case 8:return this._gl.TRIANGLE_FAN}}_reportDrawCall(){}_releaseEffect(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];let t=e.getPipelineContext();t&&this._deletePipelineContext(t)}_deletePipelineContext(e){e&&e.program&&(e.program.__SPECTOR_rebuildProgram=null,this._gl.deleteProgram(e.program))}_getGlobalDefines(e){if(e){this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS;return}{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}createEffect(e,t,r,i,n,a,l,_,h,o=m.x.GLSL){var u;let d=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,c=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,g=this._getGlobalDefines(),f=null!==(u=null!=n?n:t.defines)&&void 0!==u?u:"";g&&(f+=g);let E=d+"+"+c+"@"+f;if(this._compiledEffects[E]){let e=this._compiledEffects[E];return l&&e.isReady()&&l(e),e}let p=new s.Q(e,t,r,i,this,n,a,l,_,h,E,o);return this._compiledEffects[E]=p,p}static _ConcatenateShader(e,t,r=""){return r+(t?t+"\n":"")+e}_compileShader(e,t,r,i){return this._compileRawShader(S._ConcatenateShader(e,r,i),t)}_compileRawShader(e,t){let r=this._gl,i=r.createShader("vertex"===t?r.VERTEX_SHADER:r.FRAGMENT_SHADER);if(!i){let e=r.NO_ERROR,i=r.NO_ERROR;for(;(i=r.getError())!==r.NO_ERROR;)e=i;throw Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${r.isContextLost()}, _contextWasLost=${this._contextWasLost}`)}return r.shaderSource(i,e),r.compileShader(i),i}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,r,i,s=null){i=i||this._gl;let n=this._compileRawShader(t,"vertex"),a=this._compileRawShader(r,"fragment");return this._createShaderProgram(e,n,a,i,s)}createShaderProgram(e,t,r,i,s,n=null){s=s||this._gl;let a=this._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",l=this._compileShader(t,"vertex",i,a),_=this._compileShader(r,"fragment",i,a);return this._createShaderProgram(e,l,_,s,n)}inlineShaderCode(e){return e}createPipelineContext(e){let t=new E.y;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,r,i,s=null){let n=i.createProgram();if(e.program=n,!n)throw Error("Unable to create program");return i.attachShader(n,t),i.attachShader(n,r),i.linkProgram(n),e.context=i,e.vertexShader=t,e.fragmentShader=r,e.isParallelCompiled||this._finalizePipelineContext(e),n}_finalizePipelineContext(e){let t=e.context,r=e.vertexShader,i=e.fragmentShader,s=e.program,n=t.getProgramParameter(s,t.LINK_STATUS);if(!n){if(!this._gl.getShaderParameter(r,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(r);if(t)throw e.vertexCompilationError=t,Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(i);if(t)throw e.fragmentCompilationError=t,Error("FRAGMENT SHADER "+t)}let n=t.getProgramInfoLog(s);if(n)throw e.programLinkError=n,Error(n)}if(this.validateShaderPrograms){t.validateProgram(s);let r=t.getProgramParameter(s,t.VALIDATE_STATUS);if(!r){let r=t.getProgramInfoLog(s);if(r)throw e.programValidationError=r,Error(r)}}t.deleteShader(r),t.deleteShader(i),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,r,i,s,n,a,l,_,h){i?e.program=this.createRawShaderProgram(e,t,r,void 0,_):e.program=this.createShaderProgram(e,t,r,l,void 0,_),e.program.__SPECTOR_rebuildProgram=a}_isRenderingStateCompiled(e){return!this._isDisposed&&!e._isDisposed&&!!this._gl.getProgramParameter(e.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(e),!0)}_executeWhenRenderingStateIsCompiled(e,t){if(!e.isParallelCompiled){t();return}let r=e.onCompiled;r?e.onCompiled=()=>{r(),t()}:e.onCompiled=t}getUniforms(e,t){let r=[];for(let i=0;i<t.length;i++)r.push(this._gl.getUniformLocation(e.program,t[i]));return r}getAttributes(e,t){let r=[];for(let i=0;i<t.length;i++)try{r.push(this._gl.getAttribLocation(e.program,t[i]))}catch(e){r.push(-1)}return r}enableEffect(e){(e=null!==e&&R.q.IsWrapper(e)?e.effect:e)&&e!==this._currentEffect&&(this._stencilStateComposer.stencilMaterial=void 0,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return!!e&&(this._gl.uniform1i(e,t),!0)}setInt2(e,t,r){return!!e&&(this._gl.uniform2i(e,t,r),!0)}setInt3(e,t,r,i){return!!e&&(this._gl.uniform3i(e,t,r,i),!0)}setInt4(e,t,r,i,s){return!!e&&(this._gl.uniform4i(e,t,r,i,s),!0)}setIntArray(e,t){return!!e&&(this._gl.uniform1iv(e,t),!0)}setIntArray2(e,t){return!!e&&t.length%2==0&&(this._gl.uniform2iv(e,t),!0)}setIntArray3(e,t){return!!e&&t.length%3==0&&(this._gl.uniform3iv(e,t),!0)}setIntArray4(e,t){return!!e&&t.length%4==0&&(this._gl.uniform4iv(e,t),!0)}setUInt(e,t){return!!e&&(this._gl.uniform1ui(e,t),!0)}setUInt2(e,t,r){return!!e&&(this._gl.uniform2ui(e,t,r),!0)}setUInt3(e,t,r,i){return!!e&&(this._gl.uniform3ui(e,t,r,i),!0)}setUInt4(e,t,r,i,s){return!!e&&(this._gl.uniform4ui(e,t,r,i,s),!0)}setUIntArray(e,t){return!!e&&(this._gl.uniform1uiv(e,t),!0)}setUIntArray2(e,t){return!!e&&t.length%2==0&&(this._gl.uniform2uiv(e,t),!0)}setUIntArray3(e,t){return!!e&&t.length%3==0&&(this._gl.uniform3uiv(e,t),!0)}setUIntArray4(e,t){return!!e&&t.length%4==0&&(this._gl.uniform4uiv(e,t),!0)}setArray(e,t){return!!e&&!(t.length<1)&&(this._gl.uniform1fv(e,t),!0)}setArray2(e,t){return!!e&&t.length%2==0&&(this._gl.uniform2fv(e,t),!0)}setArray3(e,t){return!!e&&t.length%3==0&&(this._gl.uniform3fv(e,t),!0)}setArray4(e,t){return!!e&&t.length%4==0&&(this._gl.uniform4fv(e,t),!0)}setMatrices(e,t){return!!e&&(this._gl.uniformMatrix4fv(e,!1,t),!0)}setMatrix3x3(e,t){return!!e&&(this._gl.uniformMatrix3fv(e,!1,t),!0)}setMatrix2x2(e,t){return!!e&&(this._gl.uniformMatrix2fv(e,!1,t),!0)}setFloat(e,t){return!!e&&(this._gl.uniform1f(e,t),!0)}setFloat2(e,t,r){return!!e&&(this._gl.uniform2f(e,t,r),!0)}setFloat3(e,t,r,i){return!!e&&(this._gl.uniform3f(e,t,r,i),!0)}setFloat4(e,t,r,i,s){return!!e&&(this._gl.uniform4f(e,t,r,i,s),!0)}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;let e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}clearInternalTexturesCache(){this._internalTexturesCache.length=0}wipeCaches(e){(!this.preventCacheWipeBetweenFrames||e)&&(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){let r=this._gl,i=r.NEAREST,s=r.NEAREST;switch(e){case 11:i=r.LINEAR,s=t?r.LINEAR_MIPMAP_NEAREST:r.LINEAR;break;case 3:i=r.LINEAR,s=t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR;break;case 8:i=r.NEAREST,s=t?r.NEAREST_MIPMAP_LINEAR:r.NEAREST;break;case 4:i=r.NEAREST,s=t?r.NEAREST_MIPMAP_NEAREST:r.NEAREST;break;case 5:i=r.NEAREST,s=t?r.LINEAR_MIPMAP_NEAREST:r.LINEAR;break;case 6:i=r.NEAREST,s=t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR;break;case 7:i=r.NEAREST,s=r.LINEAR;break;case 1:i=r.NEAREST,s=r.NEAREST;break;case 9:i=r.LINEAR,s=t?r.NEAREST_MIPMAP_NEAREST:r.NEAREST;break;case 10:i=r.LINEAR,s=t?r.NEAREST_MIPMAP_LINEAR:r.NEAREST;break;case 2:i=r.LINEAR,s=r.LINEAR;break;case 12:i=r.LINEAR,s=r.NEAREST}return{min:s,mag:i}}_createTexture(){let e=this._gl.createTexture();if(!e)throw Error("Unable to create texture");return e}_createHardwareTexture(){return new T.B(this._createTexture(),this._gl)}_createInternalTexture(e,t,r=!0,i=o.S.Unknown){var s;let n;let a=!1,l=0,_=3,h=5,d=!1,c=1;void 0!==t&&"object"==typeof t?(a=!!t.generateMipMaps,l=void 0===t.type?0:t.type,_=void 0===t.samplingMode?3:t.samplingMode,h=void 0===t.format?5:t.format,d=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=null!==(s=t.samples)&&void 0!==s?s:1,n=t.label):a=!!t,d&&(d=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(1!==l||this._caps.textureFloatLinearFiltering)&&(2!==l||this._caps.textureHalfFloatLinearFiltering)||(_=1),1!==l||this._caps.textureFloat||(l=0,u.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let g=this._gl,f=new o.l(this,i),E=e.width||e,p=e.height||e,T=e.layers||0,R=this._getSamplingParameters(_,a),x=0!==T?g.TEXTURE_2D_ARRAY:g.TEXTURE_2D,m=this._getRGBABufferInternalSizedFormat(l,h,d),b=this._getInternalFormat(h),A=this._getWebGLTextureType(l);return this._bindTextureDirectly(x,f),0!==T?(f.is2DArray=!0,g.texImage3D(x,0,m,E,p,T,0,b,A,null)):g.texImage2D(x,0,m,E,p,0,b,A,null),g.texParameteri(x,g.TEXTURE_MAG_FILTER,R.mag),g.texParameteri(x,g.TEXTURE_MIN_FILTER,R.min),g.texParameteri(x,g.TEXTURE_WRAP_S,g.CLAMP_TO_EDGE),g.texParameteri(x,g.TEXTURE_WRAP_T,g.CLAMP_TO_EDGE),a&&this._gl.generateMipmap(x),this._bindTextureDirectly(x,null),f._useSRGBBuffer=d,f.baseWidth=E,f.baseHeight=p,f.width=E,f.height=p,f.depth=T,f.isReady=!0,f.samples=c,f.generateMipMaps=a,f.samplingMode=_,f.type=l,f.format=h,f.label=n,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,r,s,n=3,a=null,l=null,_,h,d=null,c=null,g=null,f=null,E,p,T){e=e||"";let R="data:"===e.substr(0,5),x="blob:"===e.substr(0,5),m=R&&-1!==e.indexOf(";base64,"),b=c||new o.l(this,o.S.Url);b!==c&&(b.label=e.substring(0,60));let A=e;!this._transformTextureUrl||m||c||d||(e=this._transformTextureUrl(e)),A!==e&&(b._originalUrl=A);let C=e.lastIndexOf("."),B=f||(C>-1?e.substring(C).toLowerCase():""),v=null,L=B.indexOf("?");for(let e of(L>-1&&(B=B.split("?")[0]),S._TextureLoaders))if(e.canLoad(B,E)){v=e;break}s&&s.addPendingData(b),b.url=e,b.generateMipMaps=!t,b.samplingMode=n,b.invertY=r,b._useSRGBBuffer=this._getUseSRGBBuffer(!!T,t),this._doNotHandleContextLost||(b._buffer=d);let w=null;a&&!c&&(w=b.onLoadedObservable.add(a)),c||this._internalTexturesCache.push(b);let I=(r,o)=>{s&&s.removePendingData(b),e===A?(w&&b.onLoadedObservable.remove(w),i.l.UseFallbackTexture&&this._createTextureBase(i.l.FallbackTexture,t,b.invertY,s,n,null,l,_,h,d,b),r=(r||"Unknown error")+(i.l.UseFallbackTexture?" - Fallback texture was used":""),b.onErrorObservable.notifyObservers({message:r,exception:o}),l&&l(r,o)):(u.Y.Warn(`Failed to load ${e}, falling back to ${A}`),this._createTextureBase(A,t,b.invertY,s,n,a,l,_,h,d,b,g,f,E,p,T))};if(v){let t=e=>{v.loadData(e,b,(e,t,r,i,a,l)=>{l?I("TextureLoader failed to load data"):_(b,B,s,{width:e,height:t},b.invertY,!r,i,()=>(a(),!1),n)},p)};d?d instanceof ArrayBuffer?t(new Uint8Array(d)):ArrayBuffer.isView(d)?t(d):l&&l("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,e=>t(new Uint8Array(e)),void 0,s?s.offlineProvider:void 0,!0,(e,t)=>{I("Unable to load "+(e&&e.responseURL,t))})}else{let r=e=>{x&&!this._doNotHandleContextLost&&(b._buffer=e),_(b,B,s,e,b.invertY,t,!1,h,n)};!R||m?d&&("string"==typeof d.decoding||d.close)?r(d):S._FileToolsLoadImage(e,r,I,s?s.offlineProvider:null,E,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof d||d instanceof ArrayBuffer||ArrayBuffer.isView(d)||d instanceof Blob?S._FileToolsLoadImage(d,r,I,s?s.offlineProvider:null,E,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):d&&r(d)}return b}createTexture(e,t,r,i,s=3,n=null,a=null,l=null,_=null,h=null,u=null,d,c,g,f){return this._createTextureBase(e,t,r,i,s,n,a,this._prepareWebGLTexture.bind(this),(e,t,r,s,n,a)=>{let l=this._gl,_=r.width===e&&r.height===t,u=h?this._getInternalFormat(h,n._useSRGBBuffer):".jpg"!==s||n._useSRGBBuffer?n._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:l.RGBA:l.RGB,d=h?this._getInternalFormat(h):".jpg"!==s||n._useSRGBBuffer?l.RGBA:l.RGB;if(n._useSRGBBuffer&&1===this.webGLVersion&&(d=u),_)return l.texImage2D(l.TEXTURE_2D,0,u,d,l.UNSIGNED_BYTE,r),!1;let c=this._caps.maxTextureSize;if(r.width>c||r.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!!this._workingCanvas&&!!this._workingContext&&(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(r,0,0,r.width,r.height,0,0,e,t),l.texImage2D(l.TEXTURE_2D,0,u,d,l.UNSIGNED_BYTE,this._workingCanvas),n.width=e,n.height=t,!1);{let e=new o.l(this,o.S.Temp);this._bindTextureDirectly(l.TEXTURE_2D,e,!0),l.texImage2D(l.TEXTURE_2D,0,u,d,l.UNSIGNED_BYTE,r),this._rescaleTexture(e,n,i,u,()=>{this._releaseTexture(e),this._bindTextureDirectly(l.TEXTURE_2D,n,!0),a()})}return!0},l,_,h,u,d,c,f)}static _FileToolsLoadImage(e,t,r,i,s,a){throw(0,n.S)("FileTools")}_rescaleTexture(e,t,r,i,s){}createRawTexture(e,t,r,i,s,a,l,_=null,h=0,o=0,u=!1){throw(0,n.S)("Engine.RawTexture")}createRawCubeTexture(e,t,r,i,s,a,l,_=null){throw(0,n.S)("Engine.RawTexture")}createRawTexture3D(e,t,r,i,s,a,l,_,h=null,o=0){throw(0,n.S)("Engine.RawTexture")}createRawTexture2DArray(e,t,r,i,s,a,l,_,h=null,o=0){throw(0,n.S)("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,r=!1){let i=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||r);this._setTextureParameterInteger(i,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(i,this._gl.TEXTURE_MIN_FILTER,s.min),r&&(t.generateMipMaps=!0,this._gl.generateMipmap(i)),this._bindTextureDirectly(i,null),t.samplingMode=e}updateTextureDimensions(e,t,r,i=1){}updateTextureWrappingMode(e,t,r=null,i=null){let s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==r&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(r),e),e._cachedWrapV=r),(e.is2DArray||e.is3D)&&null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(i),e),e._cachedWrapR=i),this._bindTextureDirectly(s,null)}_setupDepthStencilTexture(e,t,r,i,s,n=1){let a=t.width||t,l=t.height||t,_=t.layers||0;e.baseWidth=a,e.baseHeight=l,e.width=a,e.height=l,e.is2DArray=_>0,e.depth=_,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=i?2:1,e.type=0,e._comparisonFunction=s;let h=this._gl,o=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(o,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(o,h.TEXTURE_MIN_FILTER,u.min),h.texParameteri(o,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(o,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===s?(h.texParameteri(o,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(o,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(o,h.TEXTURE_COMPARE_FUNC,s),h.texParameteri(o,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,r,i,s,n=0,a=0){let l=this._gl,_=l.TEXTURE_2D;if(e.isCube&&(_=l.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(_,a,t,r,i,0,s)}_uploadDataToTextureDirectly(e,t,r=0,i=0,s,n=!1){let a=this._gl,l=this._getWebGLTextureType(e.type),_=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let o=a.TEXTURE_2D;e.isCube&&(o=a.TEXTURE_CUBE_MAP_POSITIVE_X+r);let u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),c=n?e.width:Math.pow(2,Math.max(u-i,0)),g=n?e.height:Math.pow(2,Math.max(d-i,0));a.texImage2D(o,i,h,c,g,0,_,l,t)}updateTextureData(e,t,r,i,s,n,a=0,l=0,_=!1){let h=this._gl,o=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,c=h.TEXTURE_2D;e.isCube&&(c=h.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(c,l,r,i,s,n,u,o,t),_&&this._gl.generateMipmap(c),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,r=0,i=0){let s=this._gl,n=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,r,i),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,r,i,s){let n=this._gl;if(!n)return;let a=this._getSamplingParameters(s,!r);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),r||i||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,r,i,s,n,a,l,_=3){let h=this.getCaps().maxTextureSize,o=Math.min(h,this.needPOTTextures?S.GetExponentOfTwo(i.width,h):i.width),u=Math.min(h,this.needPOTTextures?S.GetExponentOfTwo(i.height,h):i.height),d=this._gl;if(d){if(!e._hardwareTexture){r&&r.removePendingData(e);return}this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=i.width,e.baseHeight=i.height,e.width=o,e.height=u,e.isReady=!0,l(o,u,i,t,e,()=>{this._prepareWebGLTextureContinuation(e,r,n,a,_)})||this._prepareWebGLTextureContinuation(e,r,n,a,_)}}_setupFramebufferDepthAttachments(e,t,r,i,s=1){let n=this._gl;if(e&&t)return this._createRenderBuffer(r,i,s,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(r,i,s,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(r,i,s,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,r,i,s,n,a=!0){let l=this._gl,_=l.createRenderbuffer();return this._updateRenderBuffer(_,e,t,r,i,s,n,a)}_updateRenderBuffer(e,t,r,i,s,n,a,l=!0){let _=this._gl;return _.bindRenderbuffer(_.RENDERBUFFER,e),i>1&&_.renderbufferStorageMultisample?_.renderbufferStorageMultisample(_.RENDERBUFFER,i,n,t,r):_.renderbufferStorage(_.RENDERBUFFER,s,t,r),_.framebufferRenderbuffer(_.FRAMEBUFFER,a,_.RENDERBUFFER,e),l&&_.bindRenderbuffer(_.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource),this.unbindAllTextures();let r=this._internalTexturesCache.indexOf(e);-1!==r&&this._internalTexturesCache.splice(r,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){let t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.program);let r=e.getSamplers();for(let t=0;t<r.length;t++){let i=e.getUniform(r[t]);i&&(this._boundUniforms[t]=i)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,r=!1,i=!1){var s,n;let a=!1,l=t&&t._associatedChannel>-1;r&&l&&(this._activeChannel=t._associatedChannel);let _=this._boundTexturesCache[this._activeChannel];if(_!==t||i){if(this._activateCurrentTexture(),t&&t.isMultiview)throw console.error(e,t),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,null!==(n=null===(s=null==t?void 0:t._hardwareTexture)||void 0===s?void 0:s.underlyingResource)&&void 0!==n?n:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else r&&(a=!0,this._activateCurrentTexture());return l&&!r&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a}_bindTexture(e,t,r){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;let i=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(i,t)}unbindAllTextures(){for(let e=0;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,r,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,r))}_bindSamplerUniformToChannel(e,t){let r=this._boundUniforms[e];r&&r._currentState!==t&&(this._gl.uniform1i(r,t),r._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:break;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,r=!1,i=!1,s=""){let n;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;let r=t.getInternalTexture();r&&(r._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;n=i?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!r&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(r||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;let l=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(l,n,r),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;let e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(l,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,r,i){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===r.length||(this._textureUnits=new Int32Array(r.length));for(let t=0;t<r.length;t++){let i=r[t].getInternalTexture();i?(this._textureUnits[t]=e+t,i._associatedChannel=e+t):this._textureUnits[t]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let e=0;e<r.length;e++)this._setTexture(this._textureUnits[e],r[e],!0)}}_setAnisotropicLevel(e,t,r){let i=this._caps.textureAnisotropicFilterExtension;11!==t.samplingMode&&3!==t.samplingMode&&2!==t.samplingMode&&(r=1),i&&t._cachedAnisotropicFilteringLevel!==r&&(this._setTextureParameterFloat(e,i.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(r,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=r)}_setTextureParameterFloat(e,t,r,i){this._bindTextureDirectly(e,i,!0,!0),this._gl.texParameterf(e,t,r)}_setTextureParameterInteger(e,t,r,i){i&&this._bindTextureDirectly(e,i,!0,!0),this._gl.texParameteri(e,t,r)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e);return}for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)!(e>=this._caps.maxVertexAttribs)&&this._vertexAttribArraysEnabled[e]&&this.disableAttributeByIndex(e)}releaseEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e;for(let t of(this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),null===(e=this.releaseComputeEffects)||void 0===e||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},(0,d.CG)()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,s.Q.ResetCache(),this._activeRequests))t.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){let t=this._gl;for(;t.getError()!==t.NO_ERROR;);let r=!0,i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);let s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0);let n=t.checkFramebufferStatus(t.FRAMEBUFFER);if((r=(r=r&&n===t.FRAMEBUFFER_COMPLETE)&&t.getError()===t.NO_ERROR)&&(t.clear(t.COLOR_BUFFER_BIT),r=r&&t.getError()===t.NO_ERROR),r){t.bindFramebuffer(t.FRAMEBUFFER,null);let e=t.RGBA,i=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,i,s),r=r&&t.getError()===t.NO_ERROR}for(t.deleteTexture(i),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!r&&t.getError()!==t.NO_ERROR;);return r}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:break;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:break;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let r=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:r=this._gl.ALPHA;break;case 1:r=this._gl.LUMINANCE;break;case 2:r=this._gl.LUMINANCE_ALPHA;break;case 6:r=this._gl.RED;break;case 7:r=this._gl.RG;break;case 4:r=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:r=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:r=this._gl.RED_INTEGER;break;case 9:r=this._gl.RG_INTEGER;break;case 10:r=this._gl.RGB_INTEGER;break;case 11:r=this._gl.RGBA_INTEGER}return r}_getRGBABufferInternalSizedFormat(e,t,r=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return r?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return r?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return r?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return r?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_getRGBAMultiSampleBufferFormat(e,t=5){switch(e){case 1:if(6===t)return this._gl.R32F;return this._gl.RGBA32F;case 2:if(6===t)return this._gl.R16F;return this._gl.RGBA16F}return this._gl.RGBA8}_loadFile(e,t,r,i,s,n){let a=S._FileToolsLoadFile(e,t,r,i,s,n);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}static _FileToolsLoadFile(e,t,r,i,s,a){throw(0,n.S)("FileTools")}readPixels(e,t,r,i,s=!0,n=!0){let a=s?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(i*r*(s?4:3));return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,r,i,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{let e=this._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{let e=this._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){let t=S.CeilingPOT(e),r=S.FloorPOT(e);return t-e>e-r?r:t}static GetExponentOfTwo(e,t,r=2){let i;switch(r){case 1:i=S.FloorPOT(e);break;case 2:i=S.NearestPOT(e);break;default:i=S.CeilingPOT(e)}return Math.min(i,t)}static QueueNewFrame(e,t){if((0,d.CG)()){let{requestAnimationFrame:r}=t||window;if("function"==typeof r)return r(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:(0,d.n5)()?document:null}}S._TempClearColorUint32=new Uint32Array(4),S._TempClearColorInt32=new Int32Array(4),S.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],S._TextureLoaders=[],S.CollisionsEpsilon=.001,S._IsSupported=null,S._HasMajorPerformanceCaveat=null}}]); \ No newline at end of file diff --git a/.next/static/chunks/53417c1a-c755bb806ffa7a5d.js b/.next/static/chunks/53417c1a-c755bb806ffa7a5d.js deleted file mode 100644 index 68b9f09..0000000 --- a/.next/static/chunks/53417c1a-c755bb806ffa7a5d.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[369],{3294:function(t,e){!function(t){"use strict";class e{constructor(t){this.controller_=t}get element(){return this.controller_.view.element}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(t){this.controller_.viewProps.set("disabled",t)}get hidden(){return this.controller_.viewProps.get("hidden")}set hidden(t){this.controller_.viewProps.set("hidden",t)}dispose(){this.controller_.viewProps.set("disposed",!0)}}class i{constructor(t){this.target=t}}class n extends i{constructor(t,e,i,n){super(t),this.value=e,this.presetKey=i,this.last=null==n||n}}class r extends i{constructor(t,e,i){super(t),this.value=e,this.presetKey=i}}class s extends i{constructor(t,e){super(t),this.expanded=e}}class o extends i{constructor(t,e){super(t),this.index=e}}function a(t){return null==t}function l(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0}function p(t,e){let i=t;do{let t=Object.getOwnPropertyDescriptor(i,e);if(t&&(void 0!==t.set||!0===t.writable))return!0;i=Object.getPrototypeOf(i)}while(null!==i);return!1}let d={alreadydisposed:()=>"View has been already disposed",invalidparams:t=>`Invalid parameters for '${t.name}'`,nomatchingcontroller:t=>`No matching controller for '${t.key}'`,nomatchingview:t=>`No matching view for '${JSON.stringify(t.params)}'`,notbindable:()=>"Value is not bindable",propertynotfound:t=>`Property '${t.name}' not found`,shouldneverhappen:()=>"This error should never happen"};class h{static alreadyDisposed(){return new h({type:"alreadydisposed"})}static notBindable(){return new h({type:"notbindable"})}static propertyNotFound(t){return new h({type:"propertynotfound",context:{name:t}})}static shouldNeverHappen(){return new h({type:"shouldneverhappen"})}constructor(t){var e;this.message=null!==(e=d[t.type](t.context))&&void 0!==e?e:"Unexpected error",this.name=this.constructor.name,this.stack=Error(this.message).stack,this.type=t.type}}class u{constructor(t,e,i){this.obj_=t,this.key_=e,this.presetKey_=null!=i?i:e}static isBindable(t){return null!==t&&("object"==typeof t||"function"==typeof t)}get key(){return this.key_}get presetKey(){return this.presetKey_}read(){return this.obj_[this.key_]}write(t){this.obj_[this.key_]=t}writeProperty(t,e){let i=this.read();if(!u.isBindable(i))throw h.notBindable();if(!(t in i))throw h.propertyNotFound(t);i[t]=e}}class c extends e{get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}get title(){var t;return null!==(t=this.controller_.valueController.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller_.valueController.props.set("title",t)}on(t,e){let n=e.bind(this),r=this.controller_.valueController.emitter;return r.on(t,()=>{n(new i(this))}),this}}class v{constructor(){this.observers_={}}on(t,e){let i=this.observers_[t];return i||(i=this.observers_[t]=[]),i.push({handler:e}),this}off(t,e){let i=this.observers_[t];return i&&(this.observers_[t]=i.filter(t=>t.handler!==e)),this}emit(t,e){let i=this.observers_[t];i&&i.forEach(t=>{t.handler(e)})}}function m(t){return(e,i)=>["tp","-",t,"v",e?`_${e}`:"",i?`-${i}`:""].join("")}function b(t,e){t.emitter.on("change",t=>e(t.rawValue)),e(t.rawValue)}function _(t,e,i){b(t.value(e),i)}function g(t,e){return i=>{i?t.classList.add(e):t.classList.remove(e)}}function f(t,e){b(t,t=>{e.textContent=null!=t?t:""})}let w=m("btn");class x{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(w()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("button");i.classList.add(w("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let n=t.createElement("div");n.classList.add(w("t")),f(e.props.value("title"),n),this.buttonElement.appendChild(n)}}class C{constructor(t,e){this.emitter=new v,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new x(t,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}}class y{constructor(t,e){var i;this.constraint_=null==e?void 0:e.constraint,this.equals_=null!==(i=null==e?void 0:e.equals)&&void 0!==i?i:(t,e)=>t===e,this.emitter=new v,this.rawValue_=t}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){let i=null!=e?e:{forceEmit:!1,last:!0},n=this.constraint_?this.constraint_.constrain(t):t,r=this.rawValue_,s=!this.equals_(r,n);(s||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=n,this.emitter.emit("change",{options:i,previousRawValue:r,rawValue:n,sender:this}))}}class P{constructor(t){this.emitter=new v,this.value_=t}get rawValue(){return this.value_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){let i=null!=e?e:{forceEmit:!1,last:!0},n=this.value_;(n!==t||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=t,this.emitter.emit("change",{options:i,previousRawValue:n,rawValue:this.value_,sender:this}))}}function k(t,e){let i=null==e?void 0:e.constraint,n=null==e?void 0:e.equals;return i||n?new y(t,e):new P(t)}class E{constructor(t){for(let e in this.emitter=new v,this.valMap_=t,this.valMap_){let t=this.valMap_[e];t.emitter.on("change",()=>{this.emitter.emit("change",{key:e,sender:this})})}}static createCore(t){let e=Object.keys(t);return e.reduce((e,i)=>Object.assign(e,{[i]:k(t[i])}),{})}static fromObject(t){let e=this.createCore(t);return new E(e)}get(t){return this.valMap_[t].rawValue}set(t,e){this.valMap_[t].rawValue=e}value(t){return this.valMap_[t]}}function V(t){return e=>i=>{if(!e&&void 0===i)return{succeeded:!1,value:void 0};if(e&&void 0===i)return{succeeded:!0,value:void 0};let n=t(i);return void 0!==n?{succeeded:!0,value:n}:{succeeded:!1,value:void 0}}}function L(t){return{custom:e=>V(e)(t),boolean:V(t=>"boolean"==typeof t?t:void 0)(t),number:V(t=>"number"==typeof t?t:void 0)(t),string:V(t=>"string"==typeof t?t:void 0)(t),function:V(t=>"function"==typeof t?t:void 0)(t),constant:e=>V(t=>t===e?e:void 0)(t),raw:V(t=>t)(t),object:e=>V(t=>{if(null!==t&&"object"==typeof t)return function(t,e){let i=Object.keys(e),n=i.reduce((i,n)=>{if(void 0===i)return;let r=e[n],s=r(t[n]);return s.succeeded?Object.assign(Object.assign({},i),{[n]:s.value}):void 0},{});return n}(t,e)})(t),array:e=>V(t=>{if(Array.isArray(t))return t.reduce((t,i)=>{if(void 0===t)return;let n=e(i);if(n.succeeded&&void 0!==n.value)return[...t,n.value]},[])})(t)}}let M={optional:L(!0),required:L(!1)};function S(t,e){let i=M.required.object(e)(t);return i.succeeded?i.value:void 0}function A(t){console.warn(`Missing '${t.key}' of ${t.target} in ${t.place}. Please rebuild plugins with the latest core package.`)}class D{constructor(t){this.value_=t}static create(t){return[new D(t),(e,i)=>{t.setRawValue(e,i)}]}get emitter(){return this.value_.emitter}get rawValue(){return this.value_.rawValue}}let j=m("");function R(t,e){return g(t,j(void 0,e))}class O extends E{constructor(t){var e;super(t),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=D.create(k(this.getGlobalDisabled_())),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(t){var e,i,n;let r=null!=t?t:{};return new O(E.createCore({disabled:null!==(e=r.disabled)&&void 0!==e&&e,disposed:!1,hidden:null!==(i=r.hidden)&&void 0!==i&&i,parent:null!==(n=r.parent)&&void 0!==n?n:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(t){b(this.globalDisabled_,R(t,"disabled")),_(this,"hidden",R(t,"hidden"))}bindDisabled(t){b(this.globalDisabled_,e=>{t.disabled=e})}bindTabIndex(t){b(this.globalDisabled_,e=>{t.tabIndex=e?-1:0})}handleDispose(t){this.value("disposed").emitter.on("change",e=>{e&&t()})}getGlobalDisabled_(){let t=this.get("parent"),e=!!t&&t.globalDisabled.rawValue;return e||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(t){var e;let i=t.previousRawValue;null==i||i.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}}let I=m(""),N={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"};class K{constructor(t){this.parent_=null,this.blade=t.blade,this.view=t.view,this.viewProps=t.viewProps;let e=this.view.element;this.blade.value("positions").emitter.on("change",()=>{["veryfirst","first","last","verylast"].forEach(t=>{e.classList.remove(I(void 0,N[t]))}),this.blade.get("positions").forEach(t=>{e.classList.add(I(void 0,N[t]))})}),this.viewProps.handleDispose(()=>{e&&e.parentElement&&e.parentElement.removeChild(e)})}get parent(){return this.parent_}set parent(t){if(this.parent_=t,!("parent"in this.viewProps.valMap_)){A({key:"parent",target:O.name,place:"BladeController.parent"});return}this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}}let U="http://www.w3.org/2000/svg";function B(t){t.offsetHeight}function T(t){return void 0!==t.ontouchstart}let F={check:'<path d="M2 8l4 4l8 -8"/>',dropdown:'<path d="M5 7h6l-3 3 z"/>',p2dpad:'<path d="M8 4v8"/><path d="M4 8h8"/><circle cx="12" cy="12" r="1.2"/>'};function $(t,e){let i=t.createElementNS(U,"svg");return i.innerHTML=F[e],i}function H(t,e,i){t.insertBefore(e,t.children[i])}function z(t){t.parentElement&&t.parentElement.removeChild(t)}function q(t){for(;t.children.length>0;)t.removeChild(t.children[0])}function G(t){return t.relatedTarget?t.relatedTarget:"explicitOriginalTarget"in t?t.explicitOriginalTarget:null}let Y=m("lbl");class X{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(Y()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(Y("l")),_(e.props,"label",e=>{a(e)?this.element.classList.add(Y(void 0,"nol")):(this.element.classList.remove(Y(void 0,"nol")),function(t){for(;t.childNodes.length>0;)t.removeChild(t.childNodes[0])}(i),i.appendChild(function(t,e){let i=t.createDocumentFragment(),n=e.split("\n").map(e=>t.createTextNode(e));return n.forEach((e,n)=>{n>0&&i.appendChild(t.createElement("br")),i.appendChild(e)}),i}(t,e)))}),this.element.appendChild(i),this.labelElement=i;let n=t.createElement("div");n.classList.add(Y("v")),this.element.appendChild(n),this.valueElement=n}}class Q extends K{constructor(t,e){let i=e.valueController.viewProps;super(Object.assign(Object.assign({},e),{view:new X(t,{props:e.props,viewProps:i}),viewProps:i})),this.props=e.props,this.valueController=e.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}}let J={id:"button",type:"blade",accept(t){let e=S(t,{title:M.required.string,view:M.required.constant("button"),label:M.optional.string});return e?{params:e}:null},controller:t=>new Q(t.document,{blade:t.blade,props:E.fromObject({label:t.params.label}),valueController:new C(t.document,{props:E.fromObject({title:t.params.title}),viewProps:t.viewProps})}),api:t=>t.controller instanceof Q&&t.controller.valueController instanceof C?new c(t.controller):null};class W extends K{constructor(t){super(t),this.value=t.value}}function Z(){return new E({positions:k([],{equals:l})})}class tt extends E{constructor(t){super(t)}static create(t){let e=E.createCore({completed:!0,expanded:t,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null});return new tt(e)}get styleExpanded(){var t;return null!==(t=this.get("temporaryExpanded"))&&void 0!==t?t:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";let t=this.get("expandedHeight");return this.get("shouldFixHeight")&&!a(t)?`${t}px`:"auto"}bindExpandedClass(t,e){let i=()=>{let i=this.styleExpanded;i?t.classList.add(e):t.classList.remove(e)};_(this,"expanded",i),_(this,"temporaryExpanded",i)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}}function te(t,e){e.style.height=t.styleHeight}function ti(t,e){t.value("expanded").emitter.on("beforechange",()=>{if(t.set("completed",!1),a(t.get("expandedHeight"))){let i;let n=(i=0,function(t,e){let i=t.style.transition;t.style.transition="none",e(),t.style.transition=i}(e,()=>{t.set("expandedHeight",null),t.set("temporaryExpanded",!0),B(e),i=e.clientHeight,t.set("temporaryExpanded",null),B(e)}),i);n>0&&t.set("expandedHeight",n)}t.set("shouldFixHeight",!0),B(e)}),t.emitter.on("change",()=>{te(t,e)}),te(t,e),e.addEventListener("transitionend",e=>{"height"===e.propertyName&&t.cleanUpTransition()})}class tn extends e{constructor(t,e){super(t),this.rackApi_=e}}class tr{constructor(t){this.emitter=new v,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=t}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(t){for(let e of this.allItems())if(t(e))return e;return null}includes(t){return this.cache_.has(t)}add(t,e){if(this.includes(t))throw h.shouldNeverHappen();let i=void 0!==e?e:this.items_.length;this.items_.splice(i,0,t),this.cache_.add(t);let n=this.extract_(t);n&&(n.emitter.on("add",this.onSubListAdd_),n.emitter.on("remove",this.onSubListRemove_),n.allItems().forEach(t=>{this.cache_.add(t)})),this.emitter.emit("add",{index:i,item:t,root:this,target:this})}remove(t){let e=this.items_.indexOf(t);if(e<0)return;this.items_.splice(e,1),this.cache_.delete(t);let i=this.extract_(t);i&&(i.emitter.off("add",this.onSubListAdd_),i.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:e,item:t,root:this,target:this})}onSubListAdd_(t){this.cache_.add(t.item),this.emitter.emit("add",{index:t.index,item:t.item,root:this,target:t.target})}onSubListRemove_(t){this.cache_.delete(t.item),this.emitter.emit("remove",{index:t.index,item:t.item,root:this,target:t.target})}}class ts extends e{constructor(t){super(t),this.onBindingChange_=this.onBindingChange_.bind(this),this.emitter_=new v,this.controller_.binding.emitter.on("change",this.onBindingChange_)}get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}refresh(){this.controller_.binding.read()}onBindingChange_(t){let e=t.sender.target.read();this.emitter_.emit("change",{event:new n(this,e,this.controller_.binding.target.presetKey,t.options.last)})}}class to extends Q{constructor(t,e){super(t,e),this.binding=e.binding}}class ta extends e{constructor(t){super(t),this.onBindingUpdate_=this.onBindingUpdate_.bind(this),this.emitter_=new v,this.controller_.binding.emitter.on("update",this.onBindingUpdate_)}get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}refresh(){this.controller_.binding.read()}onBindingUpdate_(t){let e=t.sender.target.read();this.emitter_.emit("update",{event:new r(this,e,this.controller_.binding.target.presetKey)})}}class tl extends Q{constructor(t,e){super(t,e),this.binding=e.binding,this.viewProps.bindDisabled(this.binding.ticker),this.viewProps.handleDispose(()=>{this.binding.dispose()})}}function tp(t){return t instanceof tu?t.apiSet_:t instanceof tn?t.rackApi_.apiSet_:null}function td(t,e){let i=t.find(t=>t.controller_===e);if(!i)throw h.shouldNeverHappen();return i}function th(t,e,i){if(!u.isBindable(t))throw h.notBindable();return new u(t,e,i)}class tu extends e{constructor(t,e){super(t),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this),this.onRackInputChange_=this.onRackInputChange_.bind(this),this.onRackMonitorUpdate_=this.onRackMonitorUpdate_.bind(this),this.emitter_=new v,this.apiSet_=new tr(tp),this.pool_=e;let i=this.controller_.rack;i.emitter.on("add",this.onRackAdd_),i.emitter.on("remove",this.onRackRemove_),i.emitter.on("inputchange",this.onRackInputChange_),i.emitter.on("monitorupdate",this.onRackMonitorUpdate_),i.children.forEach(t=>{this.setUpApi_(t)})}get children(){return this.controller_.rack.children.map(t=>td(this.apiSet_,t))}addInput(t,e,i){let n=null!=i?i:{},r=this.controller_.view.element.ownerDocument,s=this.pool_.createInput(r,th(t,e,n.presetKey),n),o=new ts(s);return this.add(o,n.index)}addMonitor(t,e,i){let n=null!=i?i:{},r=this.controller_.view.element.ownerDocument,s=this.pool_.createMonitor(r,th(t,e),n),o=new ta(s);return this.add(o,n.index)}addFolder(t){return this.addBlade(Object.assign(Object.assign({},t),{view:"folder"}))}addButton(t){return this.addBlade(Object.assign(Object.assign({},t),{view:"button"}))}addSeparator(t){return function(t,e){let i=null!=e?e:{};return t.addBlade(Object.assign(Object.assign({},i),{view:"separator"}))}(this,t)}addTab(t){return this.addBlade(Object.assign(Object.assign({},t),{view:"tab"}))}add(t,e){this.controller_.rack.add(t.controller_,e);let i=this.apiSet_.find(e=>e.controller_===t.controller_);return i&&this.apiSet_.remove(i),this.apiSet_.add(t),t}remove(t){this.controller_.rack.remove(t.controller_)}addBlade(t){let e=this.controller_.view.element.ownerDocument,i=this.pool_.createBlade(e,t),n=this.pool_.createBladeApi(i);return this.add(n,t.index)}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}setUpApi_(t){let e=this.apiSet_.find(e=>e.controller_===t);e||this.apiSet_.add(this.pool_.createBladeApi(t))}onRackAdd_(t){this.setUpApi_(t.bladeController)}onRackRemove_(t){if(t.isRoot){let e=td(this.apiSet_,t.bladeController);this.apiSet_.remove(e)}}onRackInputChange_(t){let e=t.bladeController;if(e instanceof to){let i=td(this.apiSet_,e),r=e.binding;this.emitter_.emit("change",{event:new n(i,r.target.read(),r.target.presetKey,t.options.last)})}else if(e instanceof W){let i=td(this.apiSet_,e);this.emitter_.emit("change",{event:new n(i,e.value.rawValue,void 0,t.options.last)})}}onRackMonitorUpdate_(t){if(!(t.bladeController instanceof tl))throw h.shouldNeverHappen();let e=td(this.apiSet_,t.bladeController),i=t.bladeController.binding;this.emitter_.emit("update",{event:new r(e,i.target.read(),i.target.presetKey)})}}class tc extends tn{constructor(t,e){super(t,new tu(t.rackController,e)),this.emitter_=new v,this.controller_.foldable.value("expanded").emitter.on("change",t=>{this.emitter_.emit("fold",{event:new s(this,t.sender.rawValue)})}),this.rackApi_.on("change",t=>{this.emitter_.emit("change",{event:t})}),this.rackApi_.on("update",t=>{this.emitter_.emit("update",{event:t})})}get expanded(){return this.controller_.foldable.get("expanded")}set expanded(t){this.controller_.foldable.set("expanded",t)}get title(){return this.controller_.props.get("title")}set title(t){this.controller_.props.set("title",t)}get children(){return this.rackApi_.children}addInput(t,e,i){return this.rackApi_.addInput(t,e,i)}addMonitor(t,e,i){return this.rackApi_.addMonitor(t,e,i)}addFolder(t){return this.rackApi_.addFolder(t)}addButton(t){return this.rackApi_.addButton(t)}addSeparator(t){return this.rackApi_.addSeparator(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){return this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addBlade(t){return this.rackApi_.addBlade(t)}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}}class tv extends K{constructor(t){super({blade:t.blade,view:t.view,viewProps:t.rackController.viewProps}),this.rackController=t.rackController}}class tm{constructor(t,e){let i=m(e.viewName);this.element=t.createElement("div"),this.element.classList.add(i()),e.viewProps.bindClassModifiers(this.element)}}function tb(t){return t instanceof tf?t.rack:t instanceof tv?t.rackController.rack:null}function t_(t){let e=tb(t);return e?e.bcSet_:null}class tg{constructor(t){var e,i;this.onBladePositionsChange_=this.onBladePositionsChange_.bind(this),this.onSetAdd_=this.onSetAdd_.bind(this),this.onSetRemove_=this.onSetRemove_.bind(this),this.onChildDispose_=this.onChildDispose_.bind(this),this.onChildPositionsChange_=this.onChildPositionsChange_.bind(this),this.onChildInputChange_=this.onChildInputChange_.bind(this),this.onChildMonitorUpdate_=this.onChildMonitorUpdate_.bind(this),this.onChildValueChange_=this.onChildValueChange_.bind(this),this.onChildViewPropsChange_=this.onChildViewPropsChange_.bind(this),this.onDescendantLayout_=this.onDescendantLayout_.bind(this),this.onDescendantInputChange_=this.onDescendantInputChange_.bind(this),this.onDescendantMonitorUpdate_=this.onDescendantMonitorUpdate_.bind(this),this.emitter=new v,this.blade_=null!==(e=t.blade)&&void 0!==e?e:null,null===(i=this.blade_)||void 0===i||i.value("positions").emitter.on("change",this.onBladePositionsChange_),this.viewProps=t.viewProps,this.bcSet_=new tr(t_),this.bcSet_.emitter.on("add",this.onSetAdd_),this.bcSet_.emitter.on("remove",this.onSetRemove_)}get children(){return this.bcSet_.items}add(t,e){var i;null===(i=t.parent)||void 0===i||i.remove(t),p(t,"parent")?t.parent=this:(t.parent_=this,A({key:"parent",target:"BladeController",place:"BladeRack.add"})),this.bcSet_.add(t,e)}remove(t){p(t,"parent")?t.parent=null:(t.parent_=null,A({key:"parent",target:"BladeController",place:"BladeRack.remove"})),this.bcSet_.remove(t)}find(t){return this.bcSet_.allItems().filter(e=>e instanceof t)}onSetAdd_(t){this.updatePositions_();let e=t.target===t.root;if(this.emitter.emit("add",{bladeController:t.item,index:t.index,isRoot:e,sender:this}),!e)return;let i=t.item;if(i.viewProps.emitter.on("change",this.onChildViewPropsChange_),i.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),i.viewProps.handleDispose(this.onChildDispose_),i instanceof to)i.binding.emitter.on("change",this.onChildInputChange_);else if(i instanceof tl)i.binding.emitter.on("update",this.onChildMonitorUpdate_);else if(i instanceof W)i.value.emitter.on("change",this.onChildValueChange_);else{let t=tb(i);if(t){let e=t.emitter;e.on("layout",this.onDescendantLayout_),e.on("inputchange",this.onDescendantInputChange_),e.on("monitorupdate",this.onDescendantMonitorUpdate_)}}}onSetRemove_(t){this.updatePositions_();let e=t.target===t.root;if(this.emitter.emit("remove",{bladeController:t.item,isRoot:e,sender:this}),!e)return;let i=t.item;if(i instanceof to)i.binding.emitter.off("change",this.onChildInputChange_);else if(i instanceof tl)i.binding.emitter.off("update",this.onChildMonitorUpdate_);else if(i instanceof W)i.value.emitter.off("change",this.onChildValueChange_);else{let t=tb(i);if(t){let e=t.emitter;e.off("layout",this.onDescendantLayout_),e.off("inputchange",this.onDescendantInputChange_),e.off("monitorupdate",this.onDescendantMonitorUpdate_)}}}updatePositions_(){let t=this.bcSet_.items.filter(t=>!t.viewProps.get("hidden")),e=t[0],i=t[t.length-1];this.bcSet_.items.forEach(t=>{let n=[];t===e&&(n.push("first"),(!this.blade_||this.blade_.get("positions").includes("veryfirst"))&&n.push("veryfirst")),t===i&&(n.push("last"),(!this.blade_||this.blade_.get("positions").includes("verylast"))&&n.push("verylast")),t.blade.set("positions",n)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(t){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){let t=this.bcSet_.items.filter(t=>t.viewProps.get("disposed"));t.forEach(t=>{this.bcSet_.remove(t)})}onChildInputChange_(t){let e=function(t,e){for(let i=0;i<t.length;i++){let n=t[i];if(n instanceof to&&n.binding===e)return n}return null}(this.find(to),t.sender);if(!e)throw h.alreadyDisposed();this.emitter.emit("inputchange",{bladeController:e,options:t.options,sender:this})}onChildMonitorUpdate_(t){let e=function(t,e){for(let i=0;i<t.length;i++){let n=t[i];if(n instanceof tl&&n.binding===e)return n}return null}(this.find(tl),t.sender);if(!e)throw h.alreadyDisposed();this.emitter.emit("monitorupdate",{bladeController:e,sender:this})}onChildValueChange_(t){let e=function(t,e){for(let i=0;i<t.length;i++){let n=t[i];if(n instanceof W&&n.value===e)return n}return null}(this.find(W),t.sender);if(!e)throw h.alreadyDisposed();this.emitter.emit("inputchange",{bladeController:e,options:t.options,sender:this})}onDescendantLayout_(t){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onDescendantInputChange_(t){this.emitter.emit("inputchange",{bladeController:t.bladeController,options:t.options,sender:this})}onDescendantMonitorUpdate_(t){this.emitter.emit("monitorupdate",{bladeController:t.bladeController,sender:this})}onBladePositionsChange_(){this.updatePositions_()}}class tf extends K{constructor(t,e){super(Object.assign(Object.assign({},e),{view:new tm(t,{viewName:"brk",viewProps:e.viewProps})})),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this);let i=new tg({blade:e.root?void 0:e.blade,viewProps:e.viewProps});i.emitter.on("add",this.onRackAdd_),i.emitter.on("remove",this.onRackRemove_),this.rack=i,this.viewProps.handleDispose(()=>{for(let t=this.rack.children.length-1;t>=0;t--){let e=this.rack.children[t];e.viewProps.set("disposed",!0)}})}onRackAdd_(t){t.isRoot&&H(this.view.element,t.bladeController.view.element,t.index)}onRackRemove_(t){t.isRoot&&z(t.bladeController.view.element)}}let tw=m("cnt");class tx{constructor(t,e){var i;this.className_=m(null!==(i=e.viewName)&&void 0!==i?i:"fld"),this.element=t.createElement("div"),this.element.classList.add(this.className_(),tw()),e.viewProps.bindClassModifiers(this.element),this.foldable_=e.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),_(this.foldable_,"completed",g(this.element,this.className_(void 0,"cpl")));let n=t.createElement("button");n.classList.add(this.className_("b")),_(e.props,"title",t=>{a(t)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n;let r=t.createElement("div");r.classList.add(this.className_("i")),this.element.appendChild(r);let s=t.createElement("div");s.classList.add(this.className_("t")),f(e.props.value("title"),s),this.buttonElement.appendChild(s),this.titleElement=s;let o=t.createElement("div");o.classList.add(this.className_("m")),this.buttonElement.appendChild(o);let l=e.containerElement;l.classList.add(this.className_("c")),this.element.appendChild(l),this.containerElement=l}}class tC extends tv{constructor(t,e){var i;let n=tt.create(null===(i=e.expanded)||void 0===i||i),r=new tf(t,{blade:e.blade,root:e.root,viewProps:e.viewProps});super(Object.assign(Object.assign({},e),{rackController:r,view:new tx(t,{containerElement:r.view.element,foldable:n,props:e.props,viewName:e.root?"rot":void 0,viewProps:e.viewProps})})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=e.props,this.foldable=n,ti(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}}let ty={id:"folder",type:"blade",accept(t){let e=S(t,{title:M.required.string,view:M.required.constant("folder"),expanded:M.optional.boolean});return e?{params:e}:null},controller:t=>new tC(t.document,{blade:t.blade,expanded:t.params.expanded,props:E.fromObject({title:t.params.title}),viewProps:t.viewProps}),api:t=>t.controller instanceof tC?new tc(t.controller,t.pool):null};class tP extends W{constructor(t,e){let i=e.valueController.viewProps;super(Object.assign(Object.assign({},e),{value:e.valueController.value,view:new X(t,{props:e.props,viewProps:i}),viewProps:i})),this.props=e.props,this.valueController=e.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}}class tk extends e{}let tE=m("spr");class tV{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(tE()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("hr");i.classList.add(tE("r")),this.element.appendChild(i)}}class tL extends K{constructor(t,e){super(Object.assign(Object.assign({},e),{view:new tV(t,{viewProps:e.viewProps})}))}}let tM={id:"separator",type:"blade",accept(t){let e=S(t,{view:M.required.constant("separator")});return e?{params:e}:null},controller:t=>new tL(t.document,{blade:t.blade,viewProps:t.viewProps}),api:t=>t.controller instanceof tL?new tk(t.controller):null},tS=m("tbi");class tA{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(tS()),e.viewProps.bindClassModifiers(this.element),_(e.props,"selected",t=>{t?this.element.classList.add(tS(void 0,"sel")):this.element.classList.remove(tS(void 0,"sel"))});let i=t.createElement("button");i.classList.add(tS("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let n=t.createElement("div");n.classList.add(tS("t")),f(e.props.value("title"),n),this.buttonElement.appendChild(n),this.titleElement=n}}class tD{constructor(t,e){this.emitter=new v,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new tA(t,{props:e.props,viewProps:e.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}}class tj{constructor(t,e){this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new tD(t,{props:e.itemProps,viewProps:O.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.cc_=new tf(t,{blade:Z(),viewProps:O.create()}),this.props=e.props,_(this.props,"selected",t=>{this.itemController.props.set("selected",t),this.contentController.viewProps.set("hidden",!t)})}get itemController(){return this.ic_}get contentController(){return this.cc_}onItemClick_(){this.props.set("selected",!0)}}class tR{constructor(t,e){this.controller_=t,this.rackApi_=e}get title(){var t;return null!==(t=this.controller_.itemController.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller_.itemController.props.set("title",t)}get selected(){return this.controller_.props.get("selected")}set selected(t){this.controller_.props.set("selected",t)}get children(){return this.rackApi_.children}addButton(t){return this.rackApi_.addButton(t)}addFolder(t){return this.rackApi_.addFolder(t)}addSeparator(t){return this.rackApi_.addSeparator(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addInput(t,e,i){return this.rackApi_.addInput(t,e,i)}addMonitor(t,e,i){return this.rackApi_.addMonitor(t,e,i)}addBlade(t){return this.rackApi_.addBlade(t)}}class tO extends tn{constructor(t,e){super(t,new tu(t.rackController,e)),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.onSelect_=this.onSelect_.bind(this),this.emitter_=new v,this.pageApiMap_=new Map,this.rackApi_.on("change",t=>{this.emitter_.emit("change",{event:t})}),this.rackApi_.on("update",t=>{this.emitter_.emit("update",{event:t})}),this.controller_.tab.selectedIndex.emitter.on("change",this.onSelect_),this.controller_.pageSet.emitter.on("add",this.onPageAdd_),this.controller_.pageSet.emitter.on("remove",this.onPageRemove_),this.controller_.pageSet.items.forEach(t=>{this.setUpPageApi_(t)})}get pages(){return this.controller_.pageSet.items.map(t=>{let e=this.pageApiMap_.get(t);if(!e)throw h.shouldNeverHappen();return e})}addPage(t){let e=this.controller_.view.element.ownerDocument,i=new tj(e,{itemProps:E.fromObject({selected:!1,title:t.title}),props:E.fromObject({selected:!1})});this.controller_.add(i,t.index);let n=this.pageApiMap_.get(i);if(!n)throw h.shouldNeverHappen();return n}removePage(t){this.controller_.remove(t)}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}setUpPageApi_(t){let e=this.rackApi_.apiSet_.find(e=>e.controller_===t.contentController);if(!e)throw h.shouldNeverHappen();let i=new tR(t,e);this.pageApiMap_.set(t,i)}onPageAdd_(t){this.setUpPageApi_(t.item)}onPageRemove_(t){let e=this.pageApiMap_.get(t.item);if(!e)throw h.shouldNeverHappen();this.pageApiMap_.delete(t.item)}onSelect_(t){this.emitter_.emit("select",{event:new o(this,t.rawValue)})}}class tI{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=k(!0),this.selectedIndex=k(-1),this.items_=[]}add(t,e){let i=null!=e?e:this.items_.length;this.items_.splice(i,0,t),t.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(t){let e=this.items_.indexOf(t);e<0||(this.items_.splice(e,1),t.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length){this.selectedIndex.rawValue=-1,this.empty.rawValue=!0;return}let t=this.items_.findIndex(t=>t.rawValue);t<0?(this.items_.forEach((t,e)=>{t.rawValue=0===e}),this.selectedIndex.rawValue=0):(this.items_.forEach((e,i)=>{e.rawValue=i===t}),this.selectedIndex.rawValue=t),this.empty.rawValue=!1}onItemSelectedChange_(t){if(t.rawValue){let e=this.items_.findIndex(e=>e===t.sender);this.items_.forEach((t,i)=>{t.rawValue=i===e}),this.selectedIndex.rawValue=e}else this.keepSelection_()}}let tN=m("tab");class tK{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(tN(),tw()),e.viewProps.bindClassModifiers(this.element),b(e.empty,g(this.element,tN(void 0,"nop")));let i=t.createElement("div");i.classList.add(tN("t")),this.element.appendChild(i),this.itemsElement=i;let n=t.createElement("div");n.classList.add(tN("i")),this.element.appendChild(n);let r=e.contentsElement;r.classList.add(tN("c")),this.element.appendChild(r),this.contentsElement=r}}class tU extends tv{constructor(t,e){let i=new tf(t,{blade:e.blade,viewProps:e.viewProps}),n=new tI;super({blade:e.blade,rackController:i,view:new tK(t,{contentsElement:i.view.element,empty:n.empty,viewProps:e.viewProps})}),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.pageSet_=new tr(()=>null),this.pageSet_.emitter.on("add",this.onPageAdd_),this.pageSet_.emitter.on("remove",this.onPageRemove_),this.tab=n}get pageSet(){return this.pageSet_}add(t,e){this.pageSet_.add(t,e)}remove(t){this.pageSet_.remove(this.pageSet_.items[t])}onPageAdd_(t){let e=t.item;H(this.view.itemsElement,e.itemController.view.element,t.index),e.itemController.viewProps.set("parent",this.viewProps),this.rackController.rack.add(e.contentController,t.index),this.tab.add(e.props.value("selected"))}onPageRemove_(t){let e=t.item;z(e.itemController.view.element),e.itemController.viewProps.set("parent",null),this.rackController.rack.remove(e.contentController),this.tab.remove(e.props.value("selected"))}}let tB={id:"tab",type:"blade",accept(t){let e=S(t,{pages:M.required.array(M.required.object({title:M.required.string})),view:M.required.constant("tab")});return e&&0!==e.pages.length?{params:e}:null},controller(t){let e=new tU(t.document,{blade:t.blade,viewProps:t.viewProps});return t.params.pages.forEach(i=>{let n=new tj(t.document,{itemProps:E.fromObject({selected:!1,title:i.title}),props:E.fromObject({selected:!1})});e.add(n)}),e},api:t=>t.controller instanceof tU?new tO(t.controller,t.pool):null};class tT{constructor(){this.disabled=!1,this.emitter=new v}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}}class tF{constructor(t,e){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=t,this.emitter=new v,this.interval_=e,this.setTimer_()}get disabled(){return this.disabled_}set disabled(t){this.disabled_=t,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;let t=this.doc_.defaultView;t&&t.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;let t=this.doc_.defaultView;t&&(this.timerId_=t.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}}class t${constructor(t){this.onValueChange_=this.onValueChange_.bind(this),this.reader=t.reader,this.writer=t.writer,this.emitter=new v,this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.target=t.target,this.read()}read(){let t=this.target.read();void 0!==t&&(this.value.rawValue=this.reader(t))}write_(t){this.writer(this.target,t)}onValueChange_(t){this.write_(t.rawValue),this.emitter.emit("change",{options:t.options,rawValue:t.rawValue,sender:this})}}function tH(t,e){for(;t.length<e;)t.push(void 0)}class tz{constructor(t){this.onTick_=this.onTick_.bind(this),this.reader_=t.reader,this.target=t.target,this.emitter=new v,this.value=t.value,this.ticker=t.ticker,this.ticker.emitter.on("tick",this.onTick_),this.read()}dispose(){this.ticker.dispose()}read(){let t=this.target.read();if(void 0===t)return;let e=this.value.rawValue,i=this.reader_(t);this.value.rawValue=function(t,e){let i=[...function(t){let e=t.indexOf(void 0);return e<0?t:t.slice(0,e)}(t),e];return i.length>t.length?i.splice(0,i.length-t.length):tH(i,t.length),i}(e,i),this.emitter.emit("update",{rawValue:i,sender:this})}onTick_(t){this.read()}}class tq{constructor(t){this.constraints=t}constrain(t){return this.constraints.reduce((t,e)=>e.constrain(t),t)}}function tG(t,e){if(t instanceof e)return t;if(t instanceof tq){let i=t.constraints.reduce((t,i)=>t||(i instanceof e?i:null),null);if(i)return i}return null}class tY{constructor(t){this.values=E.fromObject({max:t.max,min:t.min})}constrain(t){let e=this.values.get("max"),i=this.values.get("min");return Math.min(Math.max(t,i),e)}}class tX{constructor(t){this.values=E.fromObject({options:t})}get options(){return this.values.get("options")}constrain(t){let e=this.values.get("options");if(0===e.length)return t;let i=e.filter(e=>e.value===t).length>0;return i?t:e[0].value}}class tQ{constructor(t){this.values=E.fromObject({max:t.max,min:t.min})}get maxValue(){return this.values.get("max")}get minValue(){return this.values.get("min")}constrain(t){let e=this.values.get("max"),i=this.values.get("min"),n=t;return a(i)||(n=Math.max(n,i)),a(e)||(n=Math.min(n,e)),n}}class tJ{constructor(t,e=0){this.step=t,this.origin=e}constrain(t){let e=this.origin%this.step,i=Math.round((t-e)/this.step);return e+i*this.step}}let tW=m("lst");class tZ{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.props_=e.props,this.element=t.createElement("div"),this.element.classList.add(tW()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("select");i.classList.add(tW("s")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.selectElement=i;let n=t.createElement("div");n.classList.add(tW("m")),n.appendChild($(t,"dropdown")),this.element.appendChild(n),e.value.emitter.on("change",this.onValueChange_),this.value_=e.value,_(this.props_,"options",e=>{q(this.selectElement),e.forEach(e=>{let i=t.createElement("option");i.textContent=e.text,this.selectElement.appendChild(i)}),this.update_()})}update_(){let t=this.props_.get("options").map(t=>t.value);this.selectElement.selectedIndex=t.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}}class t0{constructor(t,e){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new tZ(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(t){let e=t.currentTarget;this.value.rawValue=this.props.get("options")[e.selectedIndex].value}}let t1=m("pop");class t2{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(t1()),e.viewProps.bindClassModifiers(this.element),b(e.shows,g(this.element,t1(void 0,"v")))}}class t5{constructor(t,e){this.shows=k(!1),this.viewProps=e.viewProps,this.view=new t2(t,{shows:this.shows,viewProps:this.viewProps})}}let t6=m("txt");class t4{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(t6()),e.viewProps.bindClassModifiers(this.element),this.props_=e.props,this.props_.emitter.on("change",this.onChange_);let i=t.createElement("input");i.classList.add(t6("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onChange_),this.value_=e.value,this.refresh()}refresh(){let t=this.props_.get("formatter");this.inputElement.value=t(this.value_.rawValue)}onChange_(){this.refresh()}}class t8{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=e.parser,this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new t4(t,{props:e.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(t){let e=t.currentTarget,i=e.value,n=this.parser_(i);a(n)||(this.value.rawValue=n),this.view.refresh()}}function t3(t){return"false"!==t&&!!t}function t9(t){return String(t)}class t7{constructor(t){this.text=t}evaluate(){return Number(this.text)}toString(){return this.text}}let et={"**":(t,e)=>Math.pow(t,e),"*":(t,e)=>t*e,"/":(t,e)=>t/e,"%":(t,e)=>t%e,"+":(t,e)=>t+e,"-":(t,e)=>t-e,"<<":(t,e)=>t<<e,">>":(t,e)=>t>>e,">>>":(t,e)=>t>>>e,"&":(t,e)=>t&e,"^":(t,e)=>t^e,"|":(t,e)=>t|e};class ee{constructor(t,e,i){this.left=e,this.operator=t,this.right=i}evaluate(){let t=et[this.operator];if(!t)throw Error(`unexpected binary operator: '${this.operator}`);return t(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}}let ei={"+":t=>t,"-":t=>-t,"~":t=>~t};class en{constructor(t,e){this.operator=t,this.expression=e}evaluate(){let t=ei[this.operator];if(!t)throw Error(`unexpected unary operator: '${this.operator}`);return t(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}}function er(t){return(e,i)=>{for(let n=0;n<t.length;n++){let r=t[n](e,i);if(""!==r)return r}return""}}function es(t,e){var i;let n=t.substr(e).match(/^\s+/);return null!==(i=n&&n[0])&&void 0!==i?i:""}function eo(t,e){var i;let n=t.substr(e).match(/^[0-9]+/);return null!==(i=n&&n[0])&&void 0!==i?i:""}function ea(t,e){let i=t.substr(e,1);if(e+=1,"e"!==i.toLowerCase())return"";let n=function(t,e){let i=eo(t,e);if(""!==i)return i;let n=t.substr(e,1);if(e+=1,"-"!==n&&"+"!==n)return"";let r=eo(t,e);return""===r?"":n+r}(t,e);return""===n?"":i+n}function el(t,e){let i=t.substr(e,1);if("0"===i)return i;let n=function(t,e){let i=t.substr(e,1);return i.match(/^[1-9]$/)?i:""}(t,e);return(e+=n.length,""===n)?"":n+eo(t,e)}let ep=er([function(t,e){let i=el(t,e);if(e+=i.length,""===i)return"";let n=t.substr(e,1);if(e+=n.length,"."!==n)return"";let r=eo(t,e);return e+=r.length,i+n+r+ea(t,e)},function(t,e){let i=t.substr(e,1);if(e+=i.length,"."!==i)return"";let n=eo(t,e);return(e+=n.length,""===n)?"":i+n+ea(t,e)},function(t,e){let i=el(t,e);return(e+=i.length,""===i)?"":i+ea(t,e)}]),ed=er([function(t,e){let i=t.substr(e,2);if(e+=i.length,"0b"!==i.toLowerCase())return"";let n=function(t,e){var i;let n=t.substr(e).match(/^[01]+/);return null!==(i=n&&n[0])&&void 0!==i?i:""}(t,e);return""===n?"":i+n},function(t,e){let i=t.substr(e,2);if(e+=i.length,"0o"!==i.toLowerCase())return"";let n=function(t,e){var i;let n=t.substr(e).match(/^[0-7]+/);return null!==(i=n&&n[0])&&void 0!==i?i:""}(t,e);return""===n?"":i+n},function(t,e){let i=t.substr(e,2);if(e+=i.length,"0x"!==i.toLowerCase())return"";let n=function(t,e){var i;let n=t.substr(e).match(/^[0-9a-f]+/i);return null!==(i=n&&n[0])&&void 0!==i?i:""}(t,e);return""===n?"":i+n}]),eh=er([ed,ep]),eu=[["**"],["*","/","%"],["+","-"],["<<",">>>",">>"],["&"],["^"],["|"]].reduce((t,e)=>(i,n)=>{let r=t(i,n);if(!r)return null;n=r.cursor;let s=r.evaluable;for(;;){let r=function(t,e,i){i+=es(e,i).length;let n=t.filter(t=>e.startsWith(t,i))[0];return n?(i+=n.length,{cursor:i+=es(e,i).length,operator:n}):null}(e,i,n);if(!r)break;n=r.cursor;let o=t(i,n);if(!o)return null;n=o.cursor,s=new ee(r.operator,s,o.evaluable)}return s?{cursor:n,evaluable:s}:null},function t(e,i){var n,r;let s=null!==(r=function(t,e){let i=eh(t,e);return(e+=i.length,""===i)?null:{evaluable:new t7(i),cursor:e}}(e,n=i))&&void 0!==r?r:function(t,e){let i=t.substr(e,1);if(e+=i.length,"("!==i)return null;let n=ec(t,e);if(!n)return null;e=n.cursor,e+=es(t,e).length;let r=t.substr(e,1);return(e+=r.length,")"!==r)?null:{evaluable:n.evaluable,cursor:e}}(e,n);if(s)return s;let o=e.substr(i,1);if(i+=o.length,"+"!==o&&"-"!==o&&"~"!==o)return null;let a=t(e,i);return a?{cursor:i=a.cursor,evaluable:new en(o,a.evaluable)}:null});function ec(t,e){return e+=es(t,e).length,eu(t,e)}function ev(t){var e;let i=function(t){let e=ec(t,0);if(!e)return null;let i=e.cursor+es(t,e.cursor).length;return i!==t.length?null:e.evaluable}(t);return null!==(e=null==i?void 0:i.evaluate())&&void 0!==e?e:null}function em(t){if("number"==typeof t)return t;if("string"==typeof t){let e=ev(t);if(!a(e))return e}return 0}function eb(t){return String(t)}function e_(t){return e=>e.toFixed(Math.max(Math.min(t,20),0))}let eg=e_(0);function ef(t){return eg(t)+"%"}function ew(t){return String(t)}function ex(t){return t}function eC({primary:t,secondary:e,forward:i,backward:n}){let r=!1;function s(t){r||(r=!0,t(),r=!1)}t.emitter.on("change",n=>{s(()=>{e.setRawValue(i(t,e),n.options)})}),e.emitter.on("change",r=>{s(()=>{t.setRawValue(n(t,e),r.options)}),s(()=>{e.setRawValue(i(t,e),r.options)})}),s(()=>{e.setRawValue(i(t,e),{forceEmit:!1,last:!0})})}function ey(t,e){let i=t*(e.altKey?.1:1)*(e.shiftKey?10:1);return e.upKey?+i:e.downKey?-i:0}function eP(t){return{altKey:t.altKey,downKey:"ArrowDown"===t.key,shiftKey:t.shiftKey,upKey:"ArrowUp"===t.key}}function ek(t){return{altKey:t.altKey,downKey:"ArrowLeft"===t.key,shiftKey:t.shiftKey,upKey:"ArrowRight"===t.key}}function eE(t){return"ArrowUp"===t||"ArrowDown"===t||"ArrowLeft"===t||"ArrowRight"===t}function eV(t,e){var i,n;let r=e.ownerDocument.defaultView,s=e.getBoundingClientRect();return{x:t.pageX-((null!==(i=r&&r.scrollX)&&void 0!==i?i:0)+s.left),y:t.pageY-((null!==(n=r&&r.scrollY)&&void 0!==n?n:0)+s.top)}}class eL{constructor(t){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=t,this.emitter=new v,t.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),t.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),t.addEventListener("touchend",this.onTouchEnd_),t.addEventListener("mousedown",this.onMouseDown_)}computePosition_(t){let e=this.elem_.getBoundingClientRect();return{bounds:{width:e.width,height:e.height},point:t?{x:t.x,y:t.y}:null}}onMouseDown_(t){var e;t.preventDefault(),null===(e=t.currentTarget)||void 0===e||e.focus();let i=this.elem_.ownerDocument;i.addEventListener("mousemove",this.onDocumentMouseMove_),i.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(eV(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseMove_(t){this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(eV(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseUp_(t){let e=this.elem_.ownerDocument;e.removeEventListener("mousemove",this.onDocumentMouseMove_),e.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(eV(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onTouchStart_(t){t.preventDefault();let e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchMove_(t){let e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchEnd_(t){var e;let i=null!==(e=t.targetTouches.item(0))&&void 0!==e?e:this.lastTouch_,n=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(i?{x:i.clientX-n.left,y:i.clientY-n.top}:void 0),sender:this,shiftKey:t.shiftKey})}}function eM(t,e,i,n,r){return n+(t-e)/(i-e)*(r-n)}function eS(t){let e=String(t.toFixed(10)),i=e.split(".")[1];return i.replace(/0+$/,"").length}function eA(t,e,i){return Math.min(Math.max(t,e),i)}let eD=m("txt");class ej{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(eD(),eD(void 0,"num")),e.arrayPosition&&this.element.classList.add(eD(void 0,e.arrayPosition)),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("input");i.classList.add(eD("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=e.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(eD()),this.inputElement.classList.add(eD("i"));let n=t.createElement("div");n.classList.add(eD("k")),this.element.appendChild(n),this.knobElement=n;let r=t.createElementNS(U,"svg");r.classList.add(eD("g")),this.knobElement.appendChild(r);let s=t.createElementNS(U,"path");s.classList.add(eD("gb")),r.appendChild(s),this.guideBodyElem_=s;let o=t.createElementNS(U,"path");o.classList.add(eD("gh")),r.appendChild(o),this.guideHeadElem_=o;let a=t.createElement("div");a.classList.add(m("tt")()),this.knobElement.appendChild(a),this.tooltipElem_=a,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.refresh()}onDraggingChange_(t){if(null===t.rawValue){this.element.classList.remove(eD(void 0,"drg"));return}this.element.classList.add(eD(void 0,"drg"));let e=t.rawValue/this.props_.get("draggingScale"),i=e+(e>0?-1:e<0?1:0),n=eA(-i,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",`M ${i+n},0 L${i},4 L${i+n},8 M ${e},-1 L${e},9`),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${e},4`);let r=this.props_.get("formatter");this.tooltipElem_.textContent=r(this.value.rawValue),this.tooltipElem_.style.left=`${e}px`}refresh(){let t=this.props_.get("formatter");this.inputElement.value=t(this.value.rawValue)}onChange_(){this.refresh()}}class eR{constructor(t,e){var i;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=e.baseStep,this.parser_=e.parser,this.props=e.props,this.sliderProps_=null!==(i=e.sliderProps)&&void 0!==i?i:null,this.value=e.value,this.viewProps=e.viewProps,this.dragging_=k(null),this.view=new ej(t,{arrayPosition:e.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);let n=new eL(this.view.knobElement);n.emitter.on("down",this.onPointerDown_),n.emitter.on("move",this.onPointerMove_),n.emitter.on("up",this.onPointerUp_)}constrainValue_(t){var e,i;let n=null===(e=this.sliderProps_)||void 0===e?void 0:e.get("minValue"),r=null===(i=this.sliderProps_)||void 0===i?void 0:i.get("maxValue"),s=t;return void 0!==n&&(s=Math.max(s,n)),void 0!==r&&(s=Math.min(s,r)),s}onInputChange_(t){let e=t.currentTarget,i=e.value,n=this.parser_(i);a(n)||(this.value.rawValue=this.constrainValue_(n)),this.view.refresh()}onInputKeyDown_(t){let e=ey(this.baseStep_,eP(t));0!==e&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+e),{forceEmit:!1,last:!1})}onInputKeyUp_(t){let e=ey(this.baseStep_,eP(t));0!==e&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(t){if(!t.point)return null;let e=t.point.x-t.bounds.width/2;return this.constrainValue_(this.originRawValue_+e*this.props.get("draggingScale"))}onPointerMove_(t){let e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(t){let e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}}let eO=m("sld");class eI{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(eO()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(eO("t")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.trackElement=i;let n=t.createElement("div");n.classList.add(eO("k")),this.trackElement.appendChild(n),this.knobElement=n,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.update_()}update_(){let t=eA(eM(this.value.rawValue,this.props_.get("minValue"),this.props_.get("maxValue"),0,100),0,100);this.knobElement.style.width=`${t}%`}onChange_(){this.update_()}}class eN{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=e.baseStep,this.value=e.value,this.viewProps=e.viewProps,this.props=e.props,this.view=new eI(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new eL(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){t.point&&this.value.setRawValue(eM(eA(t.point.x,0,t.bounds.width),0,t.bounds.width,this.props.get("minValue"),this.props.get("maxValue")),e)}onPointerDownOrMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){let e=ey(this.baseStep_,ek(t));0!==e&&this.value.setRawValue(this.value.rawValue+e,{forceEmit:!1,last:!1})}onKeyUp_(t){let e=ey(this.baseStep_,ek(t));0!==e&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}let eK=m("sldtxt");class eU{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(eK());let i=t.createElement("div");i.classList.add(eK("s")),this.sliderView_=e.sliderView,i.appendChild(this.sliderView_.element),this.element.appendChild(i);let n=t.createElement("div");n.classList.add(eK("t")),this.textView_=e.textView,n.appendChild(this.textView_.element),this.element.appendChild(n)}}class eB{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.sliderC_=new eN(t,{baseStep:e.baseStep,props:e.sliderProps,value:e.value,viewProps:this.viewProps}),this.textC_=new eR(t,{baseStep:e.baseStep,parser:e.parser,props:e.textProps,sliderProps:e.sliderProps,value:e.value,viewProps:e.viewProps}),this.view=new eU(t,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}}function eT(t,e){t.write(e)}function eF(t){return Array.isArray(t)?M.required.array(M.required.object({text:M.required.string,value:M.required.raw}))(t).value:"object"==typeof t?M.required.raw(t).value:void 0}function e$(t){if("inline"===t||"popup"===t)return t}function eH(t){return M.required.object({max:M.optional.number,min:M.optional.number,step:M.optional.number})(t).value}function ez(t){if(Array.isArray(t))return t;let e=[];return Object.keys(t).forEach(i=>{e.push({text:i,value:t[i]})}),e}function eq(t){return a(t)?null:new tX(ez(t))}function eG(t,e){let i=t&&tG(t,tJ);return i?eS(i.step):Math.max(eS(e),2)}function eY(t){let e=function(t){let e=t?tG(t,tJ):null;return e?e.step:null}(t);return null!=e?e:1}function eX(t,e){var i;let n=t&&tG(t,tJ),r=Math.abs(null!==(i=null==n?void 0:n.step)&&void 0!==i?i:e);return 0===r?.1:Math.pow(10,Math.floor(Math.log10(r))-1)}let eQ=m("ckb");class eJ{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(eQ()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("label");i.classList.add(eQ("l")),this.element.appendChild(i);let n=t.createElement("input");n.classList.add(eQ("i")),n.type="checkbox",i.appendChild(n),this.inputElement=n,e.viewProps.bindDisabled(this.inputElement);let r=t.createElement("div");r.classList.add(eQ("w")),i.appendChild(r);let s=$(t,"check");r.appendChild(s),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}}class eW{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new eJ(t,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(t){let e=t.currentTarget;this.value.rawValue=e.checked}}let eZ={id:"input-bool",type:"input",accept:(t,e)=>{if("boolean"!=typeof t)return null;let i=S(e,{options:M.optional.custom(eF)});return i?{initialValue:t,params:i}:null},binding:{reader:t=>t3,constraint:t=>(function(t){let e=[],i=eq(t.options);return i&&e.push(i),new tq(e)})(t.params),writer:t=>eT},controller:t=>{let e=t.document,i=t.value,n=t.constraint,r=n&&tG(n,tX);return r?new t0(e,{props:new E({options:r.values.value("options")}),value:i,viewProps:t.viewProps}):new eW(e,{value:i,viewProps:t.viewProps})}},e0=m("col");class e1{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(e0()),e.foldable.bindExpandedClass(this.element,e0(void 0,"expanded")),_(e.foldable,"completed",g(this.element,e0(void 0,"cpl")));let i=t.createElement("div");i.classList.add(e0("h")),this.element.appendChild(i);let n=t.createElement("div");n.classList.add(e0("s")),i.appendChild(n),this.swatchElement=n;let r=t.createElement("div");if(r.classList.add(e0("t")),i.appendChild(r),this.textElement=r,"inline"===e.pickerLayout){let e=t.createElement("div");e.classList.add(e0("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}}function e2(t,e,i){let n,r,s;let o=(t%360+360)%360,a=eA(e/100,0,1),l=eA(i/100,0,1),p=l*a,d=p*(1-Math.abs(o/60%2-1)),h=l-p;return o>=0&&o<60?[n,r,s]=[p,d,0]:o>=60&&o<120?[n,r,s]=[d,p,0]:o>=120&&o<180?[n,r,s]=[0,p,d]:o>=180&&o<240?[n,r,s]=[0,d,p]:o>=240&&o<300?[n,r,s]=[d,0,p]:[n,r,s]=[p,0,d],[(n+h)*255,(r+h)*255,(s+h)*255]}function e5(t){return[t[0],t[1],t[2]]}function e6(t,e){return[t[0],t[1],t[2],e]}let e4={hsl:{hsl:(t,e,i)=>[t,e,i],hsv:function(t,e,i){let n=i+e*(100-Math.abs(2*i-100))/200;return[t,0!==n?e*(100-Math.abs(2*i-100))/n:0,i+e*(100-Math.abs(2*i-100))/200]},rgb:function(t,e,i){let n,r,s;let o=(t%360+360)%360,a=eA(e/100,0,1),l=eA(i/100,0,1),p=(1-Math.abs(2*l-1))*a,d=p*(1-Math.abs(o/60%2-1)),h=l-p/2;return o>=0&&o<60?[n,r,s]=[p,d,0]:o>=60&&o<120?[n,r,s]=[d,p,0]:o>=120&&o<180?[n,r,s]=[0,p,d]:o>=180&&o<240?[n,r,s]=[0,d,p]:o>=240&&o<300?[n,r,s]=[d,0,p]:[n,r,s]=[p,0,d],[(n+h)*255,(r+h)*255,(s+h)*255]}},hsv:{hsl:function(t,e,i){let n=100-Math.abs(i*(200-e)/100-100);return[t,0!==n?e*i/n:0,i*(200-e)/200]},hsv:(t,e,i)=>[t,e,i],rgb:e2},rgb:{hsl:function(t,e,i){let n=eA(t/255,0,1),r=eA(e/255,0,1),s=eA(i/255,0,1),o=Math.max(n,r,s),a=Math.min(n,r,s),l=o-a,p=0,d=0;return 0!==l&&(d=l/(1-Math.abs(o+a-1)),p=(p=n===o?(r-s)/l:r===o?2+(s-n)/l:4+(n-r)/l)/6+(p<0?1:0)),[360*p,100*d,100*((a+o)/2)]},hsv:function(t,e,i){let n=eA(t/255,0,1),r=eA(e/255,0,1),s=eA(i/255,0,1),o=Math.max(n,r,s),a=o-Math.min(n,r,s);return[0===a?0:o===n?60*(((r-s)/a%6+6)%6):o===r?60*((s-n)/a+2):60*((n-r)/a+4),100*(0===o?0:a/o),100*o]},rgb:(t,e,i)=>[t,e,i]}};function e8(t,e){return["float"===e?1:"rgb"===t?255:360,"float"===e?1:"rgb"===t?255:100,"float"===e?1:"rgb"===t?255:100]}function e3(t,e,i,n){let r=e8(e,i),s=e8(e,n);return t.map((t,e)=>t/r[e]*s[e])}function e9(t,e){return!("object"!=typeof t||a(t))&&e in t&&"number"==typeof t[e]}class e7{static black(t="int"){return new e7([0,0,0],"rgb",t)}static fromObject(t,e="int"){let i="a"in t?[t.r,t.g,t.b,t.a]:[t.r,t.g,t.b];return new e7(i,"rgb",e)}static toRgbaObject(t,e="int"){return t.toRgbaObject(e)}static isRgbColorObject(t){return e9(t,"r")&&e9(t,"g")&&e9(t,"b")}static isRgbaColorObject(t){return this.isRgbColorObject(t)&&e9(t,"a")}static isColorObject(t){return this.isRgbColorObject(t)}static equals(t,e){if(t.mode!==e.mode)return!1;let i=t.comps_,n=e.comps_;for(let t=0;t<i.length;t++)if(i[t]!==n[t])return!1;return!0}constructor(t,e,i="int"){this.mode=e,this.type=i,this.comps_=function(t,e,i){var n,r,s;let o=e8(e,i);return["rgb"===e?eA(t[0],0,o[0]):(r=t[0])===(s=o[0])?s:(r%s+s)%s,eA(t[1],0,o[1]),eA(t[2],0,o[2]),eA(null!==(n=t[3])&&void 0!==n?n:1,0,1)]}(t,e,i)}getComponents(t,e="int"){return e6(function(t,e,i){let n=e3(t,e.mode,e.type,"int"),r=e4[e.mode][i.mode](...n);return e3(r,i.mode,"int",i.type)}(e5(this.comps_),{mode:this.mode,type:this.type},{mode:null!=t?t:this.mode,type:e}),this.comps_[3])}toRgbaObject(t="int"){let e=this.getComponents("rgb",t);return{r:e[0],g:e[1],b:e[2],a:e[3]}}}let it=m("colp");class ie{constructor(t,e){this.alphaViews_=null,this.element=t.createElement("div"),this.element.classList.add(it()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(it("hsv"));let n=t.createElement("div");n.classList.add(it("sv")),this.svPaletteView_=e.svPaletteView,n.appendChild(this.svPaletteView_.element),i.appendChild(n);let r=t.createElement("div");r.classList.add(it("h")),this.hPaletteView_=e.hPaletteView,r.appendChild(this.hPaletteView_.element),i.appendChild(r),this.element.appendChild(i);let s=t.createElement("div");if(s.classList.add(it("rgb")),this.textView_=e.textView,s.appendChild(this.textView_.element),this.element.appendChild(s),e.alphaViews){this.alphaViews_={palette:e.alphaViews.palette,text:e.alphaViews.text};let i=t.createElement("div");i.classList.add(it("a"));let n=t.createElement("div");n.classList.add(it("ap")),n.appendChild(this.alphaViews_.palette.element),i.appendChild(n);let r=t.createElement("div");r.classList.add(it("at")),r.appendChild(this.alphaViews_.text.element),i.appendChild(r),this.element.appendChild(i)}}get allFocusableElements(){let t=[this.svPaletteView_.element,this.hPaletteView_.element,this.textView_.modeSelectElement,...this.textView_.textViews.map(t=>t.inputElement)];return this.alphaViews_&&t.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),t}}function ii(t){return"int"===t?"int":"float"===t?"float":void 0}function ir(t){return S(t,{alpha:M.optional.boolean,color:M.optional.object({alpha:M.optional.boolean,type:M.optional.custom(ii)}),expanded:M.optional.boolean,picker:M.optional.custom(e$)})}function is(t){return t?.1:1}function io(t){var e;return null===(e=t.color)||void 0===e?void 0:e.type}function ia(t,e){let i=t.match(/^(.+)%$/);return i?Math.min(.01*parseFloat(i[1])*e,e):Math.min(parseFloat(t),e)}let il={deg:t=>t,grad:t=>360*t/400,rad:t=>360*t/(2*Math.PI),turn:t=>360*t};function ip(t){let e=t.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!e)return parseFloat(t);let i=parseFloat(e[1]),n=e[2];return il[n](i)}function id(t){let e=t.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;let i=[ia(e[1],255),ia(e[2],255),ia(e[3],255)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function ih(t){return e=>{let i=id(e);return i?new e7(i,"rgb",t):null}}function iu(t){let e=t.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;let i=[ia(e[1],255),ia(e[2],255),ia(e[3],255),ia(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function ic(t){return e=>{let i=iu(e);return i?new e7(i,"rgb",t):null}}function iv(t){let e=t.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;let i=[ip(e[1]),ia(e[2],100),ia(e[3],100)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function im(t){return e=>{let i=iv(e);return i?new e7(i,"hsl",t):null}}function ib(t){let e=t.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;let i=[ip(e[1]),ia(e[2],100),ia(e[3],100),ia(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function i_(t){return e=>{let i=ib(e);return i?new e7(i,"hsl",t):null}}function ig(t){let e=t.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)];let i=t.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]:null}function iw(t){let e=t.match(/^#?([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16),eM(parseInt(e[4]+e[4],16),0,255,0,1)];let i=t.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16),eM(parseInt(i[4],16),0,255,0,1)]:null}function ix(t){let e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;let i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function iC(t){return e=>{let i=ix(e);return i?new e7(i,"rgb",t):null}}function iy(t){let e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;let i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3]),parseFloat(e[4])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function iP(t){return e=>{let i=iy(e);return i?new e7(i,"rgb",t):null}}let ik=[{parser:ig,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:iw,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:id,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:iu,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:iv,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:ib,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:ix,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:iy,result:{alpha:!0,mode:"rgb",notation:"object"}}];function iE(t,e="int"){let i=ik.reduce((e,{parser:i,result:n})=>e||(i(t)?n:null),null);return i?"hex"===i.notation&&"float"!==e?Object.assign(Object.assign({},i),{type:"int"}):"func"===i.notation?Object.assign(Object.assign({},i),{type:e}):null:null}let iV={int:[function(t){let e=ig(t);return e?new e7(e,"rgb","int"):null},function(t){let e=iw(t);return e?new e7(e,"rgb","int"):null},ih("int"),ic("int"),im("int"),i_("int"),iC("int"),iP("int")],float:[ih("float"),ic("float"),im("float"),i_("float"),iC("float"),iP("float")]};function iL(t){let e=iV[t];return t=>e.reduce((e,i)=>e||i(t),null)}function iM(t){let e=eA(Math.floor(t),0,255).toString(16);return 1===e.length?`0${e}`:e}function iS(t,e="#"){let i=e5(t.getComponents("rgb")).map(iM).join("");return`${e}${i}`}function iA(t,e="#"){let i=t.getComponents("rgb"),n=[i[0],i[1],i[2],255*i[3]].map(iM).join("");return`${e}${n}`}function iD(t,e){let i=e_("float"===e?2:0),n=e5(t.getComponents("rgb",e)).map(t=>i(t));return`rgb(${n.join(", ")})`}function ij(t,e){let i=e_(2),n=e_("float"===e?2:0),r=t.getComponents("rgb",e).map((t,e)=>(3===e?i:n)(t));return`rgba(${r.join(", ")})`}function iR(t,e){let i=e_("float"===e?2:0),n=["r","g","b"],r=e5(t.getComponents("rgb",e)).map((t,e)=>`${n[e]}: ${i(t)}`);return`{${r.join(", ")}}`}function iO(t,e){let i=e_(2),n=e_("float"===e?2:0),r=["r","g","b","a"],s=t.getComponents("rgb",e).map((t,e)=>`${r[e]}: ${(3===e?i:n)(t)}`);return`{${s.join(", ")}}`}let iI=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:iS},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:iA},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){let e=[e_(0),ef,ef],i=e5(t.getComponents("hsl")).map((t,i)=>e[i](t));return`hsl(${i.join(", ")})`}},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){let e=[e_(0),ef,ef,e_(2)],i=t.getComponents("hsl").map((t,i)=>e[i](t));return`hsla(${i.join(", ")})`}},...["int","float"].reduce((t,e)=>[...t,{format:{alpha:!1,mode:"rgb",notation:"func",type:e},stringifier:t=>iD(t,e)},{format:{alpha:!0,mode:"rgb",notation:"func",type:e},stringifier:t=>ij(t,e)},{format:{alpha:!1,mode:"rgb",notation:"object",type:e},stringifier:t=>iR(t,e)},{format:{alpha:!0,mode:"rgb",notation:"object",type:e},stringifier:t=>iO(t,e)}],[])];function iN(t){return iI.reduce((e,i)=>{var n;return e||((n=i.format).alpha===t.alpha&&n.mode===t.mode&&n.notation===t.notation&&n.type===t.type?i.stringifier:null)},null)}let iK=m("apl");class iU{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(iK()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);let i=t.createElement("div");i.classList.add(iK("b")),this.element.appendChild(i);let n=t.createElement("div");n.classList.add(iK("c")),i.appendChild(n),this.colorElem_=n;let r=t.createElement("div");r.classList.add(iK("m")),this.element.appendChild(r),this.markerElem_=r;let s=t.createElement("div");s.classList.add(iK("p")),this.markerElem_.appendChild(s),this.previewElem_=s,this.update_()}update_(){let t=this.value.rawValue,e=t.getComponents("rgb"),i=new e7([e[0],e[1],e[2],0],"rgb"),n=new e7([e[0],e[1],e[2],255],"rgb"),r=["to right",ij(i),ij(n)];this.colorElem_.style.background=`linear-gradient(${r.join(",")})`,this.previewElem_.style.backgroundColor=ij(t);let s=eM(e[3],0,1,0,100);this.markerElem_.style.left=`${s}%`}onValueChange_(){this.update_()}}class iB{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new iU(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new eL(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;let i=t.point.x/t.bounds.width,n=this.value.rawValue,[r,s,o]=n.getComponents("hsv");this.value.setRawValue(new e7([r,s,o,i],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){let e=ey(is(!0),ek(t));if(0===e)return;let i=this.value.rawValue,[n,r,s,o]=i.getComponents("hsv");this.value.setRawValue(new e7([n,r,s,o+e],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){let e=ey(is(!0),ek(t));0!==e&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}let iT=m("coltxt");class iF{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(iT()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(iT("m")),this.modeElem_=function(t){let e=t.createElement("select");return e.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"}].reduce((e,i)=>{let n=t.createElement("option");return n.textContent=i.text,n.value=i.value,e.appendChild(n),e},t.createDocumentFragment())),e}(t),this.modeElem_.classList.add(iT("ms")),i.appendChild(this.modeSelectElement),e.viewProps.bindDisabled(this.modeElem_);let n=t.createElement("div");n.classList.add(iT("mm")),n.appendChild($(t,"dropdown")),i.appendChild(n),this.element.appendChild(i);let r=t.createElement("div");r.classList.add(iT("w")),this.element.appendChild(r),this.textsElem_=r,this.textViews_=e.textViews,this.applyTextViews_(),b(e.colorMode,t=>{this.modeElem_.value=t})}get modeSelectElement(){return this.modeElem_}get textViews(){return this.textViews_}set textViews(t){this.textViews_=t,this.applyTextViews_()}applyTextViews_(){q(this.textsElem_);let t=this.element.ownerDocument;this.textViews_.forEach(e=>{let i=t.createElement("div");i.classList.add(iT("c")),i.appendChild(e.element),this.textsElem_.appendChild(i)})}}function i$(t,e,i){return new eR(t,{arrayPosition:0===i?"fst":2===i?"lst":"mid",baseStep:is(!1),parser:e.parser,props:E.fromObject({draggingScale:"float"===e.colorType?.01:1,formatter:e_("float"===e.colorType?2:0)}),value:k(0,{constraint:function(t,e,i){let n=e8(t,e)[i];return new tY({min:0,max:n})}(e.colorMode,e.colorType,i)}),viewProps:e.viewProps})}class iH{constructor(t,e){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=e.colorType,this.parser_=e.parser,this.value=e.value,this.viewProps=e.viewProps,this.colorMode=k(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(t),this.view=new iF(t,{colorMode:this.colorMode,textViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(t){let e={colorMode:this.colorMode.rawValue,colorType:this.colorType_,parser:this.parser_,viewProps:this.viewProps},i=[i$(t,e,0),i$(t,e,1),i$(t,e,2)];return i.forEach((t,e)=>{eC({primary:this.value,secondary:t.value,forward:t=>t.rawValue.getComponents(this.colorMode.rawValue,this.colorType_)[e],backward:(t,i)=>{let n=this.colorMode.rawValue,r=t.rawValue.getComponents(n,this.colorType_);return r[e]=i.rawValue,new e7(e6(e5(r),r[3]),n,this.colorType_)}})}),i}onModeSelectChange_(t){let e=t.currentTarget;this.colorMode.rawValue=e.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.textViews=[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view]}}let iz=m("hpl");class iq{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(iz()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);let i=t.createElement("div");i.classList.add(iz("c")),this.element.appendChild(i);let n=t.createElement("div");n.classList.add(iz("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){let t=this.value.rawValue,[e]=t.getComponents("hsv");this.markerElem_.style.backgroundColor=iD(new e7([e,100,100],"hsv"));let i=eM(e,0,360,0,100);this.markerElem_.style.left=`${i}%`}onValueChange_(){this.update_()}}class iG{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new iq(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new eL(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;let i=eM(eA(t.point.x,0,t.bounds.width),0,t.bounds.width,0,360),n=this.value.rawValue,[,r,s,o]=n.getComponents("hsv");this.value.setRawValue(new e7([i,r,s,o],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){let e=ey(is(!1),ek(t));if(0===e)return;let i=this.value.rawValue,[n,r,s,o]=i.getComponents("hsv");this.value.setRawValue(new e7([n+e,r,s,o],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){let e=ey(is(!1),ek(t));0!==e&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}let iY=m("svp");class iX{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(iY()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);let i=t.createElement("canvas");i.height=64,i.width=64,i.classList.add(iY("c")),this.element.appendChild(i),this.canvasElement=i;let n=t.createElement("div");n.classList.add(iY("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){let t=function(t){let e=t.ownerDocument.defaultView;return e&&"document"in e?t.getContext("2d",{willReadFrequently:!0}):null}(this.canvasElement);if(!t)return;let e=this.value.rawValue,i=e.getComponents("hsv"),n=this.canvasElement.width,r=this.canvasElement.height,s=t.getImageData(0,0,n,r),o=s.data;for(let t=0;t<r;t++)for(let e=0;e<n;e++){let s=eM(e,0,n,0,100),a=eM(t,0,r,100,0),l=e2(i[0],s,a),p=(t*n+e)*4;o[p]=l[0],o[p+1]=l[1],o[p+2]=l[2],o[p+3]=255}t.putImageData(s,0,0);let a=eM(i[1],0,100,0,100);this.markerElem_.style.left=`${a}%`;let l=eM(i[2],0,100,100,0);this.markerElem_.style.top=`${l}%`}onValueChange_(){this.update_()}}class iQ{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new iX(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new eL(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;let i=eM(t.point.x,0,t.bounds.width,0,100),n=eM(t.point.y,0,t.bounds.height,100,0),[r,,,s]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new e7([r,i,n,s],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){eE(t.key)&&t.preventDefault();let[e,i,n,r]=this.value.rawValue.getComponents("hsv"),s=is(!1),o=ey(s,ek(t)),a=ey(s,eP(t));(0!==o||0!==a)&&this.value.setRawValue(new e7([e,i+o,n+a,r],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){let e=is(!1),i=ey(e,ek(t)),n=ey(e,eP(t));(0!==i||0!==n)&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}class iJ{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.hPaletteC_=new iG(t,{value:this.value,viewProps:this.viewProps}),this.svPaletteC_=new iQ(t,{value:this.value,viewProps:this.viewProps}),this.alphaIcs_=e.supportsAlpha?{palette:new iB(t,{value:this.value,viewProps:this.viewProps}),text:new eR(t,{parser:ev,baseStep:.1,props:E.fromObject({draggingScale:.01,formatter:e_(2)}),value:k(0,{constraint:new tY({min:0,max:1})}),viewProps:this.viewProps})}:null,this.alphaIcs_&&eC({primary:this.value,secondary:this.alphaIcs_.text.value,forward:t=>t.rawValue.getComponents()[3],backward:(t,e)=>{let i=t.rawValue.getComponents();return i[3]=e.rawValue,new e7(i,t.rawValue.mode)}}),this.textC_=new iH(t,{colorType:e.colorType,parser:ev,value:this.value,viewProps:this.viewProps}),this.view=new ie(t,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:e.supportsAlpha,svPaletteView:this.svPaletteC_.view,textView:this.textC_.view,viewProps:this.viewProps})}get textController(){return this.textC_}}let iW=m("colsw");class iZ{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.element=t.createElement("div"),this.element.classList.add(iW()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(iW("sw")),this.element.appendChild(i),this.swatchElem_=i;let n=t.createElement("button");n.classList.add(iW("b")),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n,this.update_()}update_(){let t=this.value.rawValue;this.swatchElem_.style.backgroundColor=iA(t)}onValueChange_(){this.update_()}}class i0{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new iZ(t,{value:this.value,viewProps:this.viewProps})}}class i1{constructor(t,e){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=tt.create(e.expanded),this.swatchC_=new i0(t,{value:this.value,viewProps:this.viewProps});let i=this.swatchC_.view.buttonElement;i.addEventListener("blur",this.onButtonBlur_),i.addEventListener("click",this.onButtonClick_),this.textC_=new t8(t,{parser:e.parser,props:E.fromObject({formatter:e.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new e1(t,{foldable:this.foldable_,pickerLayout:e.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===e.pickerLayout?new t5(t,{viewProps:this.viewProps}):null;let n=new iJ(t,{colorType:e.colorType,supportsAlpha:e.supportsAlpha,value:this.value,viewProps:this.viewProps});n.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=n,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(n.view.element),eC({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t.rawValue,backward:(t,e)=>e.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),ti(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(t){if(!this.popC_)return;let e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;let e=this.popC_.view.element,i=G(t);!(i&&e.contains(i))&&(!i||i!==this.swatchC_.view.buttonElement||T(e.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.swatchC_.view.buttonElement.focus()}}function i2(t){return e5(t.getComponents("rgb")).reduce((t,e)=>t<<8|255&Math.floor(e),0)}function i5(t){return t.getComponents("rgb").reduce((t,e,i)=>t<<8|255&Math.floor(3===i?255*e:e),0)>>>0}function i6(t){return"number"!=typeof t?e7.black():new e7([t>>16&255,t>>8&255,255&t],"rgb")}function i4(t){return"number"!=typeof t?e7.black():new e7([t>>24&255,t>>16&255,t>>8&255,eM(255&t,0,255,0,1)],"rgb")}function i8(t){var e;return null!=t&&!!t.alpha||null!==(e=null==t?void 0:t.color)&&void 0!==e&&!!e.alpha}let i3={id:"input-color-number",type:"input",accept:(t,e)=>{if("number"!=typeof t||!("color"in e||"view"in e&&"color"===e.view))return null;let i=ir(e);return i?{initialValue:t,params:i}:null},binding:{reader:t=>i8(t.params)?i4:i6,equals:e7.equals,writer:t=>(function(t){let e=t?i5:i2;return(t,i)=>{eT(t,e(i))}})(i8(t.params))},controller:t=>{let e=i8(t.params),i="expanded"in t.params?t.params.expanded:void 0,n="picker"in t.params?t.params.picker:void 0;return new i1(t.document,{colorType:"int",expanded:null!=i&&i,formatter:e?t=>iA(t,"0x"):t=>iS(t,"0x"),parser:iL("int"),pickerLayout:null!=n?n:"popup",supportsAlpha:e,value:t.value,viewProps:t.viewProps})}},i9={id:"input-color-object",type:"input",accept:(t,e)=>{if(!e7.isColorObject(t))return null;let i=ir(e);return i?{initialValue:t,params:i}:null},binding:{reader:t=>{var e;return e=io(t.params),t=>e7.isColorObject(t)?e7.fromObject(t,e):e7.black(e)},equals:e7.equals,writer:t=>{var e,i,n;return e=t.initialValue,i=e7.isRgbaColorObject(e),n=io(t.params),(t,e)=>{i?function(t,e,i){let n=e.toRgbaObject(i);t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b),t.writeProperty("a",n.a)}(t,e,n):function(t,e,i){let n=e.toRgbaObject(i);t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b)}(t,e,n)}}},controller:t=>{var e;let i=e7.isRgbaColorObject(t.initialValue),n="expanded"in t.params?t.params.expanded:void 0,r="picker"in t.params?t.params.picker:void 0,s=null!==(e=io(t.params))&&void 0!==e?e:"int";return new i1(t.document,{colorType:s,expanded:null!=n&&n,formatter:t=>i?iO(t,s):iR(t,s),parser:iL(s),pickerLayout:null!=r?r:"popup",supportsAlpha:i,value:t.value,viewProps:t.viewProps})}},i7={id:"input-color-string",type:"input",accept:(t,e)=>{if("string"!=typeof t||"view"in e&&"text"===e.view)return null;let i=iE(t,io(e));if(!i)return null;let n=iN(i);if(!n)return null;let r=ir(e);return r?{initialValue:t,params:r}:null},binding:{reader:t=>{var e;return function(t){let e=iV[t];return i=>{if("string"!=typeof i)return e7.black(t);let n=e.reduce((t,e)=>t||e(i),null);return null!=n?n:e7.black(t)}}(null!==(e=io(t.params))&&void 0!==e?e:"int")},equals:e7.equals,writer:t=>{let e=iE(t.initialValue,io(t.params));if(!e)throw h.shouldNeverHappen();let i=function(t){let e=iN(t);return e?(t,i)=>{eT(t,e(i))}:null}(e);if(!i)throw h.notBindable();return i}},controller:t=>{let e=iE(t.initialValue,io(t.params));if(!e)throw h.shouldNeverHappen();let i=iN(e);if(!i)throw h.shouldNeverHappen();let n="expanded"in t.params?t.params.expanded:void 0,r="picker"in t.params?t.params.picker:void 0;return new i1(t.document,{colorType:e.type,expanded:null!=n&&n,formatter:i,parser:iL(e.type),pickerLayout:null!=r?r:"popup",supportsAlpha:e.alpha,value:t.value,viewProps:t.viewProps})}};class nt{constructor(t){this.components=t.components,this.asm_=t.assembly}constrain(t){let e=this.asm_.toComponents(t).map((t,e)=>{var i,n;return null!==(n=null===(i=this.components[e])||void 0===i?void 0:i.constrain(t))&&void 0!==n?n:t});return this.asm_.fromComponents(e)}}let ne=m("pndtxt");class ni{constructor(t,e){this.textViews=e.textViews,this.element=t.createElement("div"),this.element.classList.add(ne()),this.textViews.forEach(e=>{let i=t.createElement("div");i.classList.add(ne("a")),i.appendChild(e.element),this.element.appendChild(i)})}}class nn{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.acs_=e.axes.map((i,n)=>new eR(t,{arrayPosition:0===n?"fst":n===e.axes.length-1?"lst":"mid",baseStep:e.axes[n].baseStep,parser:e.parser,props:e.axes[n].textProps,value:k(0,{constraint:e.axes[n].constraint}),viewProps:e.viewProps})),this.acs_.forEach((t,i)=>{eC({primary:this.value,secondary:t.value,forward:t=>e.assembly.toComponents(t.rawValue)[i],backward:(t,n)=>{let r=e.assembly.toComponents(t.rawValue);return r[i]=n.rawValue,e.assembly.fromComponents(r)}})}),this.view=new ni(t,{textViews:this.acs_.map(t=>t.view)})}}function nr(t,e){return"step"in t&&!a(t.step)?new tJ(t.step,e):null}function ns(t){return a(t.max)||a(t.min)?a(t.max)&&a(t.min)?null:new tQ({max:t.max,min:t.min}):new tY({max:t.max,min:t.min})}let no={id:"input-number",type:"input",accept:(t,e)=>{if("number"!=typeof t)return null;let i=S(e,{format:M.optional.function,max:M.optional.number,min:M.optional.number,options:M.optional.custom(eF),step:M.optional.number});return i?{initialValue:t,params:i}:null},binding:{reader:t=>em,constraint:t=>(function(t,e){let i=[],n=nr(t,e);n&&i.push(n);let r=ns(t);r&&i.push(r);let s=eq(t.options);return s&&i.push(s),new tq(i)})(t.params,t.initialValue),writer:t=>eT},controller:t=>{var e;let i=t.value,n=t.constraint,r=n&&tG(n,tX);if(r)return new t0(t.document,{props:new E({options:r.values.value("options")}),value:i,viewProps:t.viewProps});let s=null!==(e="format"in t.params?t.params.format:void 0)&&void 0!==e?e:e_(eG(n,i.rawValue)),o=n&&tG(n,tY);return o?new eB(t.document,{baseStep:eY(n),parser:ev,sliderProps:new E({maxValue:o.values.value("max"),minValue:o.values.value("min")}),textProps:E.fromObject({draggingScale:eX(n,i.rawValue),formatter:s}),value:i,viewProps:t.viewProps}):new eR(t.document,{baseStep:eY(n),parser:ev,props:E.fromObject({draggingScale:eX(n,i.rawValue),formatter:s}),value:i,viewProps:t.viewProps})}};class na{constructor(t=0,e=0){this.x=t,this.y=e}getComponents(){return[this.x,this.y]}static isObject(t){if(a(t))return!1;let e=t.x,i=t.y;return"number"==typeof e&&"number"==typeof i}static equals(t,e){return t.x===e.x&&t.y===e.y}toObject(){return{x:this.x,y:this.y}}}let nl={toComponents:t=>t.getComponents(),fromComponents:t=>new na(...t)},np=m("p2d");class nd{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(np()),e.viewProps.bindClassModifiers(this.element),b(e.expanded,g(this.element,np(void 0,"expanded")));let i=t.createElement("div");i.classList.add(np("h")),this.element.appendChild(i);let n=t.createElement("button");n.classList.add(np("b")),n.appendChild($(t,"p2dpad")),e.viewProps.bindDisabled(n),i.appendChild(n),this.buttonElement=n;let r=t.createElement("div");if(r.classList.add(np("t")),i.appendChild(r),this.textElement=r,"inline"===e.pickerLayout){let e=t.createElement("div");e.classList.add(np("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}}let nh=m("p2dp");class nu{constructor(t,e){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.invertsY_=e.invertsY,this.maxValue_=e.maxValue,this.element=t.createElement("div"),this.element.classList.add(nh()),"popup"===e.layout&&this.element.classList.add(nh(void 0,"p")),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(nh("p")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.padElement=i;let n=t.createElementNS(U,"svg");n.classList.add(nh("g")),this.padElement.appendChild(n),this.svgElem_=n;let r=t.createElementNS(U,"line");r.classList.add(nh("ax")),r.setAttributeNS(null,"x1","0"),r.setAttributeNS(null,"y1","50%"),r.setAttributeNS(null,"x2","100%"),r.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(r);let s=t.createElementNS(U,"line");s.classList.add(nh("ax")),s.setAttributeNS(null,"x1","50%"),s.setAttributeNS(null,"y1","0"),s.setAttributeNS(null,"x2","50%"),s.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(s);let o=t.createElementNS(U,"line");o.classList.add(nh("l")),o.setAttributeNS(null,"x1","50%"),o.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(o),this.lineElem_=o;let a=t.createElement("div");a.classList.add(nh("m")),this.padElement.appendChild(a),this.markerElem_=a,e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){let[t,e]=this.value.rawValue.getComponents(),i=this.maxValue_,n=eM(t,-i,+i,0,100),r=eM(e,-i,+i,0,100),s=this.invertsY_?100-r:r;this.lineElem_.setAttributeNS(null,"x2",`${n}%`),this.lineElem_.setAttributeNS(null,"y2",`${s}%`),this.markerElem_.style.left=`${n}%`,this.markerElem_.style.top=`${s}%`}onValueChange_(){this.update_()}onFoldableChange_(){this.update_()}}function nc(t,e,i){return[ey(e[0],ek(t)),ey(e[1],eP(t))*(i?1:-1)]}class nv{constructor(t,e){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.baseSteps_=e.baseSteps,this.maxValue_=e.maxValue,this.invertsY_=e.invertsY,this.view=new nu(t,{invertsY:this.invertsY_,layout:e.layout,maxValue:this.maxValue_,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new eL(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;let i=this.maxValue_,n=eM(t.point.x,0,t.bounds.width,-i,+i),r=eM(this.invertsY_?t.bounds.height-t.point.y:t.point.y,0,t.bounds.height,-i,+i);this.value.setRawValue(new na(n,r),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onPadKeyDown_(t){eE(t.key)&&t.preventDefault();let[e,i]=nc(t,this.baseSteps_,this.invertsY_);(0!==e||0!==i)&&this.value.setRawValue(new na(this.value.rawValue.x+e,this.value.rawValue.y+i),{forceEmit:!1,last:!1})}onPadKeyUp_(t){let[e,i]=nc(t,this.baseSteps_,this.invertsY_);(0!==e||0!==i)&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}class nm{constructor(t,e){var i,n;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=tt.create(e.expanded),this.popC_="popup"===e.pickerLayout?new t5(t,{viewProps:this.viewProps}):null;let r=new nv(t,{baseSteps:[e.axes[0].baseStep,e.axes[1].baseStep],invertsY:e.invertsY,layout:e.pickerLayout,maxValue:e.maxValue,value:this.value,viewProps:this.viewProps});r.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=r,this.textC_=new nn(t,{assembly:nl,axes:e.axes,parser:e.parser,value:this.value,viewProps:this.viewProps}),this.view=new nd(t,{expanded:this.foldable_.value("expanded"),pickerLayout:e.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("blur",this.onPadButtonBlur_),null===(n=this.view.buttonElement)||void 0===n||n.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),eC({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t.rawValue,backward:(t,e)=>e.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),ti(this.foldable_,this.view.pickerElement))}onPadButtonBlur_(t){if(!this.popC_)return;let e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;let e=this.popC_.view.element,i=G(t);!(i&&e.contains(i))&&(!i||i!==this.view.buttonElement||T(e.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.view.buttonElement.focus()}}class nb{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}getComponents(){return[this.x,this.y,this.z]}static isObject(t){if(a(t))return!1;let e=t.x,i=t.y,n=t.z;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z}toObject(){return{x:this.x,y:this.y,z:this.z}}}let n_={toComponents:t=>t.getComponents(),fromComponents:t=>new nb(...t)};function ng(t){return nb.isObject(t)?new nb(t.x,t.y,t.z):new nb}function nf(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z)}function nw(t,e){return{baseStep:eY(e),constraint:e,textProps:E.fromObject({draggingScale:eX(e,t),formatter:e_(eG(e,t))})}}let nx={id:"input-point3d",type:"input",accept:(t,e)=>{if(!nb.isObject(t))return null;let i=S(e,{x:M.optional.custom(eH),y:M.optional.custom(eH),z:M.optional.custom(eH)});return i?{initialValue:t,params:i}:null},binding:{reader:t=>ng,constraint:t=>{var e,i;return e=t.params,i=t.initialValue,new nt({assembly:n_,components:[nq("x"in e?e.x:void 0,i.x),nq("y"in e?e.y:void 0,i.y),nq("z"in e?e.z:void 0,i.z)]})},equals:nb.equals,writer:t=>nf},controller:t=>{let e=t.value,i=t.constraint;if(!(i instanceof nt))throw h.shouldNeverHappen();return new nn(t.document,{assembly:n_,axes:[nw(e.rawValue.x,i.components[0]),nw(e.rawValue.y,i.components[1]),nw(e.rawValue.z,i.components[2])],parser:ev,value:e,viewProps:t.viewProps})}};class nC{constructor(t=0,e=0,i=0,n=0){this.x=t,this.y=e,this.z=i,this.w=n}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(t){if(a(t))return!1;let e=t.x,i=t.y,n=t.z,r=t.w;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n&&"number"==typeof r}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z&&t.w===e.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}}let ny={toComponents:t=>t.getComponents(),fromComponents:t=>new nC(...t)};function nP(t){return nC.isObject(t)?new nC(t.x,t.y,t.z,t.w):new nC}function nk(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z),t.writeProperty("w",e.w)}let nE={id:"input-point4d",type:"input",accept:(t,e)=>{if(!nC.isObject(t))return null;let i=S(e,{x:M.optional.custom(eH),y:M.optional.custom(eH),z:M.optional.custom(eH),w:M.optional.custom(eH)});return i?{initialValue:t,params:i}:null},binding:{reader:t=>nP,constraint:t=>{var e,i;return e=t.params,i=t.initialValue,new nt({assembly:ny,components:[nq("x"in e?e.x:void 0,i.x),nq("y"in e?e.y:void 0,i.y),nq("z"in e?e.z:void 0,i.z),nq("w"in e?e.w:void 0,i.w)]})},equals:nC.equals,writer:t=>nk},controller:t=>{let e=t.value,i=t.constraint;if(!(i instanceof nt))throw h.shouldNeverHappen();return new nn(t.document,{assembly:ny,axes:e.rawValue.getComponents().map((t,e)=>{var n;return{baseStep:eY(n=i.components[e]),constraint:n,textProps:E.fromObject({draggingScale:eX(n,t),formatter:e_(eG(n,t))})}}),parser:ev,value:e,viewProps:t.viewProps})}},nV={id:"input-string",type:"input",accept:(t,e)=>{if("string"!=typeof t)return null;let i=S(e,{options:M.optional.custom(eF)});return i?{initialValue:t,params:i}:null},binding:{reader:t=>ew,constraint:t=>(function(t){let e=[],i=eq(t.options);return i&&e.push(i),new tq(e)})(t.params),writer:t=>eT},controller:t=>{let e=t.document,i=t.value,n=t.constraint,r=n&&tG(n,tX);return r?new t0(e,{props:new E({options:r.values.value("options")}),value:i,viewProps:t.viewProps}):new t8(e,{parser:t=>t,props:E.fromObject({formatter:ex}),value:i,viewProps:t.viewProps})}},nL={monitor:{defaultInterval:200,defaultLineCount:3}},nM=m("mll");class nS{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(nM()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("textarea");i.classList.add(nM("i")),i.style.height=`calc(var(--bld-us) * ${e.lineCount})`,i.readOnly=!0,e.viewProps.bindDisabled(i),this.element.appendChild(i),this.textareaElem_=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){let t=this.textareaElem_,e=t.scrollTop===t.scrollHeight-t.clientHeight,i=[];this.value.rawValue.forEach(t=>{void 0!==t&&i.push(this.formatter_(t))}),t.textContent=i.join("\n"),e&&(t.scrollTop=t.scrollHeight)}onValueUpdate_(){this.update_()}}class nA{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new nS(t,{formatter:e.formatter,lineCount:e.lineCount,value:this.value,viewProps:this.viewProps})}}let nD=m("sgl");class nj{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(nD()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("input");i.classList.add(nD("i")),i.readOnly=!0,i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){let t=this.value.rawValue,e=t[t.length-1];this.inputElement.value=void 0!==e?this.formatter_(e):""}onValueUpdate_(){this.update_()}}class nR{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new nj(t,{formatter:e.formatter,value:this.value,viewProps:this.viewProps})}}let nO={id:"monitor-bool",type:"monitor",accept:(t,e)=>{if("boolean"!=typeof t)return null;let i=S(e,{lineCount:M.optional.number});return i?{initialValue:t,params:i}:null},binding:{reader:t=>t3},controller:t=>{var e;return 1===t.value.rawValue.length?new nR(t.document,{formatter:t9,value:t.value,viewProps:t.viewProps}):new nA(t.document,{formatter:t9,lineCount:null!==(e=t.params.lineCount)&&void 0!==e?e:nL.monitor.defaultLineCount,value:t.value,viewProps:t.viewProps})}},nI=m("grl");class nN{constructor(t,e){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=t.createElement("div"),this.element.classList.add(nI()),e.viewProps.bindClassModifiers(this.element),this.formatter_=e.formatter,this.props_=e.props,this.cursor_=e.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);let i=t.createElementNS(U,"svg");i.classList.add(nI("g")),i.style.height=`calc(var(--bld-us) * ${e.lineCount})`,this.element.appendChild(i),this.svgElem_=i;let n=t.createElementNS(U,"polyline");this.svgElem_.appendChild(n),this.lineElem_=n;let r=t.createElement("div");r.classList.add(nI("t"),m("tt")()),this.element.appendChild(r),this.tooltipElem_=r,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}get graphElement(){return this.svgElem_}update_(){let t=this.svgElem_.getBoundingClientRect(),e=this.value.rawValue.length-1,i=this.props_.get("minValue"),n=this.props_.get("maxValue"),r=[];this.value.rawValue.forEach((s,o)=>{if(void 0===s)return;let a=eM(o,0,e,0,t.width),l=eM(s,i,n,t.height,0);r.push([a,l].join(","))}),this.lineElem_.setAttributeNS(null,"points",r.join(" "));let s=this.tooltipElem_,o=this.value.rawValue[this.cursor_.rawValue];if(void 0===o){s.classList.remove(nI("t","a"));return}let a=eM(this.cursor_.rawValue,0,e,0,t.width),l=eM(o,i,n,t.height,0);s.style.left=`${a}px`,s.style.top=`${l}px`,s.textContent=`${this.formatter_(o)}`,s.classList.contains(nI("t","a"))||(s.classList.add(nI("t","a"),nI("t","in")),B(s),s.classList.remove(nI("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}}class nK{constructor(t,e){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props_=e.props,this.value=e.value,this.viewProps=e.viewProps,this.cursor_=k(-1),this.view=new nN(t,{cursor:this.cursor_,formatter:e.formatter,lineCount:e.lineCount,props:this.props_,value:this.value,viewProps:this.viewProps}),T(t)){let t=new eL(this.view.element);t.emitter.on("down",this.onGraphPointerDown_),t.emitter.on("move",this.onGraphPointerMove_),t.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(t){let e=this.view.element.getBoundingClientRect();this.cursor_.rawValue=Math.floor(eM(t.offsetX,0,e.width,0,this.value.rawValue.length))}onGraphPointerDown_(t){this.onGraphPointerMove_(t)}onGraphPointerMove_(t){if(!t.data.point){this.cursor_.rawValue=-1;return}this.cursor_.rawValue=Math.floor(eM(t.data.point.x,0,t.data.bounds.width,0,this.value.rawValue.length))}onGraphPointerUp_(){this.cursor_.rawValue=-1}}function nU(t){return"format"in t&&!a(t.format)?t.format:e_(2)}function nB(t){return"view"in t&&"graph"===t.view}let nT={id:"monitor-number",type:"monitor",accept:(t,e)=>{if("number"!=typeof t)return null;let i=S(e,{format:M.optional.function,lineCount:M.optional.number,max:M.optional.number,min:M.optional.number,view:M.optional.string});return i?{initialValue:t,params:i}:null},binding:{defaultBufferSize:t=>nB(t)?64:1,reader:t=>em},controller:t=>{var e,i,n,r;return nB(t.params)?new nK(t.document,{formatter:nU(t.params),lineCount:null!==(e=t.params.lineCount)&&void 0!==e?e:nL.monitor.defaultLineCount,props:E.fromObject({maxValue:null!==(i="max"in t.params?t.params.max:null)&&void 0!==i?i:100,minValue:null!==(n="min"in t.params?t.params.min:null)&&void 0!==n?n:0}),value:t.value,viewProps:t.viewProps}):1===t.value.rawValue.length?new nR(t.document,{formatter:nU(t.params),value:t.value,viewProps:t.viewProps}):new nA(t.document,{formatter:nU(t.params),lineCount:null!==(r=t.params.lineCount)&&void 0!==r?r:nL.monitor.defaultLineCount,value:t.value,viewProps:t.viewProps})}},nF={id:"monitor-string",type:"monitor",accept:(t,e)=>{if("string"!=typeof t)return null;let i=S(e,{lineCount:M.optional.number,multiline:M.optional.boolean});return i?{initialValue:t,params:i}:null},binding:{reader:t=>ew},controller:t=>{var e;let i=t.value,n=i.rawValue.length>1||"multiline"in t.params&&t.params.multiline;return n?new nA(t.document,{formatter:ex,lineCount:null!==(e=t.params.lineCount)&&void 0!==e?e:nL.monitor.defaultLineCount,value:i,viewProps:t.viewProps}):new nR(t.document,{formatter:ex,value:i,viewProps:t.viewProps})}};class n${constructor(){this.pluginsMap_={blades:[],inputs:[],monitors:[]}}getAll(){return[...this.pluginsMap_.blades,...this.pluginsMap_.inputs,...this.pluginsMap_.monitors]}register(t){"blade"===t.type?this.pluginsMap_.blades.unshift(t):"input"===t.type?this.pluginsMap_.inputs.unshift(t):"monitor"===t.type&&this.pluginsMap_.monitors.unshift(t)}createInput(t,e,i){let n=e.read();if(a(n))throw new h({context:{key:e.key},type:"nomatchingcontroller"});let r=this.pluginsMap_.inputs.reduce((n,r)=>null!=n?n:function(t,e){var i;let n=t.accept(e.target.read(),e.params);if(a(n))return null;let r={target:e.target,initialValue:n.initialValue,params:n.params},s=t.binding.reader(r),o=t.binding.constraint?t.binding.constraint(r):void 0,l=k(s(n.initialValue),{constraint:o,equals:t.binding.equals}),p=new t$({reader:s,target:e.target,value:l,writer:t.binding.writer(r)}),d=M.optional.boolean(e.params.disabled).value,h=M.optional.boolean(e.params.hidden).value,u=t.controller({constraint:o,document:e.document,initialValue:n.initialValue,params:n.params,value:p.value,viewProps:O.create({disabled:d,hidden:h})});return new to(e.document,{binding:p,blade:Z(),props:E.fromObject({label:"label"in e.params?null!==(i=M.optional.string(e.params.label).value)&&void 0!==i?i:null:e.target.key}),valueController:u})}(r,{document:t,target:e,params:i}),null);if(r)return r;throw new h({context:{key:e.key},type:"nomatchingcontroller"})}createMonitor(t,e,i){let n=this.pluginsMap_.monitors.reduce((n,r)=>null!=n?n:function(t,e){var i,n,r,s;let o=t.accept(e.target.read(),e.params);if(a(o))return null;let l={target:e.target,initialValue:o.initialValue,params:o.params},p=t.binding.reader(l),d=null!==(n=null!==(i=M.optional.number(e.params.bufferSize).value)&&void 0!==i?i:t.binding.defaultBufferSize&&t.binding.defaultBufferSize(o.params))&&void 0!==n?n:1,h=M.optional.number(e.params.interval).value,u=new tz({reader:p,target:e.target,ticker:(s=e.document,0===h?new tT:new tF(s,null!=h?h:nL.monitor.defaultInterval)),value:function(t){let e=[];return tH(e,t),k(e)}(d)}),c=M.optional.boolean(e.params.disabled).value,v=M.optional.boolean(e.params.hidden).value,m=t.controller({document:e.document,params:o.params,value:u.value,viewProps:O.create({disabled:c,hidden:v})});return new tl(e.document,{binding:u,blade:Z(),props:E.fromObject({label:"label"in e.params?null!==(r=M.optional.string(e.params.label).value)&&void 0!==r?r:null:e.target.key}),valueController:m})}(r,{document:t,params:i,target:e}),null);if(n)return n;throw new h({context:{key:e.key},type:"nomatchingcontroller"})}createBlade(t,e){let i=this.pluginsMap_.blades.reduce((i,n)=>null!=i?i:function(t,e){let i=t.accept(e.params);if(!i)return null;let n=M.optional.boolean(e.params.disabled).value,r=M.optional.boolean(e.params.hidden).value;return t.controller({blade:Z(),document:e.document,params:Object.assign(Object.assign({},i.params),{disabled:n,hidden:r}),viewProps:O.create({disabled:n,hidden:r})})}(n,{document:t,params:e}),null);if(!i)throw new h({type:"nomatchingview",context:{params:e}});return i}createBladeApi(t){if(t instanceof to)return new ts(t);if(t instanceof tl)return new ta(t);if(t instanceof tf)return new tu(t,this);let e=this.pluginsMap_.blades.reduce((e,i)=>null!=e?e:i.api({controller:t,pool:this}),null);if(!e)throw h.shouldNeverHappen();return e}}function nH(t){return na.isObject(t)?new na(t.x,t.y):new na}function nz(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y)}function nq(t,e){if(!t)return;let i=[],n=nr(t,e);n&&i.push(n);let r=ns(t);return r&&i.push(r),new tq(i)}function nG(t,e){let[i,n]=t?function(t){let e=tG(t,tY);if(e)return[e.values.get("min"),e.values.get("max")];let i=tG(t,tQ);return i?[i.minValue,i.maxValue]:[void 0,void 0]}(t):[];if(!a(i)||!a(n))return Math.max(Math.abs(null!=i?i:0),Math.abs(null!=n?n:0));let r=eY(t);return Math.max(10*Math.abs(r),10*Math.abs(e))}function nY(t,e){return{baseStep:eY(e),constraint:e,textProps:E.fromObject({draggingScale:eX(e,t),formatter:e_(eG(e,t))})}}let nX={id:"input-point2d",type:"input",accept:(t,e)=>{if(!na.isObject(t))return null;let i=S(e,{expanded:M.optional.boolean,picker:M.optional.custom(e$),x:M.optional.custom(eH),y:M.optional.object({inverted:M.optional.boolean,max:M.optional.number,min:M.optional.number,step:M.optional.number})});return i?{initialValue:t,params:i}:null},binding:{reader:t=>nH,constraint:t=>{var e,i;return e=t.params,i=t.initialValue,new nt({assembly:nl,components:[nq("x"in e?e.x:void 0,i.x),nq("y"in e?e.y:void 0,i.y)]})},equals:na.equals,writer:t=>nz},controller:t=>{let e=t.document,i=t.value,n=t.constraint;if(!(n instanceof nt))throw h.shouldNeverHappen();let r="expanded"in t.params?t.params.expanded:void 0,s="picker"in t.params?t.params.picker:void 0;return new nm(e,{axes:[nY(i.rawValue.x,n.components[0]),nY(i.rawValue.y,n.components[1])],expanded:null!=r&&r,invertsY:function(t){if(!("y"in t))return!1;let e=t.y;return!!e&&"inverted"in e&&!!e.inverted}(t.params),maxValue:function(t,e){let i=e instanceof nt?e.components[0]:void 0,n=e instanceof nt?e.components[1]:void 0,r=nG(i,t.x),s=nG(n,t.y);return Math.max(r,s)}(i.rawValue,n),parser:ev,pickerLayout:null!=s?s:"popup",value:i,viewProps:t.viewProps})}};class nQ extends e{constructor(t){super(t),this.emitter_=new v,this.controller_.valueController.value.emitter.on("change",t=>{this.emitter_.emit("change",{event:new n(this,t.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}get options(){return this.controller_.valueController.props.get("options")}set options(t){this.controller_.valueController.props.set("options",t)}get value(){return this.controller_.valueController.value.rawValue}set value(t){this.controller_.valueController.value.rawValue=t}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}}class nJ extends e{constructor(t){super(t),this.emitter_=new v,this.controller_.valueController.value.emitter.on("change",t=>{this.emitter_.emit("change",{event:new n(this,t.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}get maxValue(){return this.controller_.valueController.sliderController.props.get("maxValue")}set maxValue(t){this.controller_.valueController.sliderController.props.set("maxValue",t)}get minValue(){return this.controller_.valueController.sliderController.props.get("minValue")}set minValue(t){this.controller_.valueController.sliderController.props.set("minValue",t)}get value(){return this.controller_.valueController.value.rawValue}set value(t){this.controller_.valueController.value.rawValue=t}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}}class nW extends e{constructor(t){super(t),this.emitter_=new v,this.controller_.valueController.value.emitter.on("change",t=>{this.emitter_.emit("change",{event:new n(this,t.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}get formatter(){return this.controller_.valueController.props.get("formatter")}set formatter(t){this.controller_.valueController.props.set("formatter",t)}get value(){return this.controller_.valueController.value.rawValue}set value(t){this.controller_.valueController.value.rawValue=t}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}}let nZ={id:"list",type:"blade",accept(t){let e=S(t,{options:M.required.custom(eF),value:M.required.raw,view:M.required.constant("list"),label:M.optional.string});return e?{params:e}:null},controller(t){let e=new tX(ez(t.params.options)),i=k(t.params.value,{constraint:e}),n=new t0(t.document,{props:new E({options:e.values.value("options")}),value:i,viewProps:t.viewProps});return new tP(t.document,{blade:t.blade,props:E.fromObject({label:t.params.label}),valueController:n})},api:t=>t.controller instanceof tP&&t.controller.valueController instanceof t0?new nQ(t.controller):null};class n0 extends tc{constructor(t,e){super(t,e)}get element(){return this.controller_.view.element}importPreset(t){let e=this.controller_.rackController.rack.find(to).map(t=>t.binding);(function(t,e){t.forEach(t=>{let i=e[t.target.presetKey];void 0!==i&&t.writer(t.target,t.reader(i))})})(e,t),this.refresh()}exportPreset(){let t=this.controller_.rackController.rack.find(to).map(t=>t.binding.target);return t.reduce((t,e)=>Object.assign(t,{[e.presetKey]:e.read()}),{})}refresh(){this.controller_.rackController.rack.find(to).forEach(t=>{t.binding.read()}),this.controller_.rackController.rack.find(tl).forEach(t=>{t.binding.read()})}}class n1 extends tC{constructor(t,e){super(t,{expanded:e.expanded,blade:e.blade,props:e.props,root:!0,viewProps:e.viewProps})}}let n2={id:"slider",type:"blade",accept(t){let e=S(t,{max:M.required.number,min:M.required.number,view:M.required.constant("slider"),format:M.optional.function,label:M.optional.string,value:M.optional.number});return e?{params:e}:null},controller(t){var e,i;let n=null!==(e=t.params.value)&&void 0!==e?e:0,r=new tY({max:t.params.max,min:t.params.min}),s=new eB(t.document,{baseStep:1,parser:ev,sliderProps:new E({maxValue:r.values.value("max"),minValue:r.values.value("min")}),textProps:E.fromObject({draggingScale:eX(void 0,n),formatter:null!==(i=t.params.format)&&void 0!==i?i:eb}),value:k(n,{constraint:r}),viewProps:t.viewProps});return new tP(t.document,{blade:t.blade,props:E.fromObject({label:t.params.label}),valueController:s})},api:t=>t.controller instanceof tP&&t.controller.valueController instanceof eB?new nJ(t.controller):null},n5={id:"text",type:"blade",accept(t){let e=S(t,{parse:M.required.function,value:M.required.raw,view:M.required.constant("text"),format:M.optional.function,label:M.optional.string});return e?{params:e}:null},controller(t){var e;let i=new t8(t.document,{parser:t.params.parse,props:E.fromObject({formatter:null!==(e=t.params.format)&&void 0!==e?e:t=>String(t)}),value:k(t.params.value),viewProps:t.viewProps});return new tP(t.document,{blade:t.blade,props:E.fromObject({label:t.params.label}),valueController:i})},api:t=>t.controller instanceof tP&&t.controller.valueController instanceof t8?new nW(t.controller):null};function n6(t,e,i){if(t.querySelector(`style[data-tp-style=${e}]`))return;let n=t.createElement("style");n.dataset.tpStyle=e,n.textContent=i,t.head.appendChild(n)}let n4=new class{constructor(t){let[e,i]=t.split("-"),n=e.split(".");this.major=parseInt(n[0],10),this.minor=parseInt(n[1],10),this.patch=parseInt(n[2],10),this.prerelease=null!=i?i:null}toString(){let t=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[t,this.prerelease].join("-"):t}}("3.1.10");t.BladeApi=e,t.ButtonApi=c,t.FolderApi=tc,t.InputBindingApi=ts,t.ListApi=nQ,t.MonitorBindingApi=ta,t.Pane=class extends n0{constructor(t){var e,i;let n=null!=t?t:{},r=null!==(e=n.document)&&void 0!==e?e:function(){let t=globalThis;return t.document}(),s=function(){let t=new n$;return[nX,nx,nE,nV,no,i7,i9,i3,eZ,nO,nF,nT,J,ty,tM,tB].forEach(e=>{t.register(e)}),t}(),o=new n1(r,{expanded:n.expanded,blade:Z(),props:E.fromObject({title:n.title}),viewProps:O.create()});super(o,s),this.pool_=s,this.containerElem_=null!==(i=n.container)&&void 0!==i?i:function(t){let e=t.createElement("div");return e.classList.add(m("dfw")()),t.body&&t.body.appendChild(e),e}(r),this.containerElem_.appendChild(this.element),this.doc_=r,this.usesDefaultWrapper_=!n.container,this.setUpDefaultPlugins_()}get document(){if(!this.doc_)throw h.alreadyDisposed();return this.doc_}dispose(){let t=this.containerElem_;if(!t)throw h.alreadyDisposed();if(this.usesDefaultWrapper_){let e=t.parentElement;e&&e.removeChild(t)}this.containerElem_=null,this.doc_=null,super.dispose()}registerPlugin(t){let e="plugin"in t?[t.plugin]:"plugins"in t?t.plugins:[];e.forEach(t=>{this.pool_.register(t),this.embedPluginStyle_(t)})}embedPluginStyle_(t){t.css&&n6(this.document,`plugin-${t.id}`,t.css)}setUpDefaultPlugins_(){n6(this.document,"default",'.tp-tbiv_b,.tp-coltxtv_ms,.tp-ckbv_i,.tp-rotv_b,.tp-fldv_b,.tp-mllv_i,.tp-sglv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--elm-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--bld-us);line-height:var(--bld-us);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--bld-us);line-height:var(--bld-us);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-mllv_i,.tp-sglv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--mo-fg);height:var(--bld-us);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-mllv_i::-webkit-scrollbar,.tp-sglv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-mllv_i::-webkit-scrollbar-corner,.tp-sglv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-mllv_i::-webkit-scrollbar-thumb,.tp-sglv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-rotv{--font-family: var(--tp-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-br: var(--tp-base-border-radius, 6px);--cnt-h-p: var(--tp-container-horizontal-padding, 4px);--cnt-v-p: var(--tp-container-vertical-padding, 4px);--elm-br: var(--tp-element-border-radius, 2px);--bld-s: var(--tp-blade-spacing, 4px);--bld-us: var(--tp-blade-unit-size, 20px);--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tabv_c .tp-brkv>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-v-p))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tabv_c .tp-brkv>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--bld-s)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tabv_c .tp-brkv>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tabv_c .tp-brkv>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--elm-br);border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tabv_c .tp-brkv .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--elm-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);overflow:hidden;padding-left:var(--cnt-h-p);padding-right:calc(4px + var(--bld-us) + var(--cnt-h-p));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-h-p) + (var(--bld-us) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-v-p);padding-top:var(--cnt-v-p);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--elm-br);cursor:pointer;display:block;height:var(--bld-us);position:relative;width:var(--bld-us)}.tp-ckbv_w svg{bottom:0;display:block;height:16px;left:0;margin:auto;opacity:0;position:absolute;right:0;top:0;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--bld-us)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--bld-s);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--bld-s)}.tp-colpv_rgb{display:flex;margin-top:var(--bld-s);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-v-p);padding-top:calc(var(--cnt-v-p) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-h-p));position:absolute;right:calc(-1*var(--cnt-h-p));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--elm-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--bld-us)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--elm-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;pointer-events:none;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--elm-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;cursor:pointer;display:block;height:var(--bld-us);left:0;margin:0;outline:none;padding:0;position:absolute;top:0;width:var(--bld-us)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--elm-br);bottom:0;content:"";display:block;left:0;position:absolute;right:0;top:0}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--elm-br);color:var(--lbl-fg);cursor:pointer;height:var(--bld-us);line-height:var(--bld-us);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv.tp-fldv-not .tp-fldv_b{display:none}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--bld-us)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-h-p);padding-right:var(--cnt-h-p)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:160px}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding:0 4px}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--bld-us)*3);line-height:var(--bld-us);padding:0 4px;resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--bld-us);margin-right:4px;position:relative;width:var(--bld-us)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--bld-s);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-p2dpv{padding-left:calc(var(--bld-us) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:6px;box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:168px;padding:var(--cnt-v-p) var(--cnt-h-p);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--bld-us);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin:auto;position:absolute;right:0;top:0}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin-bottom:auto;margin-top:auto;position:absolute;right:0;top:0}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--elm-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--bld-us) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_c{padding-bottom:var(--cnt-v-p);padding-left:4px;padding-top:var(--cnt-v-p)}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-h-p) + 4px);padding-right:calc(var(--cnt-h-p) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);bottom:2px;content:"";left:0;pointer-events:none;position:absolute;right:0;top:0}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);opacity:.5;overflow:hidden;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-txtv{position:relative}.tp-txtv_i{padding:0 4px}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:-3px;position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--bld-us) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--elm-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--font-family);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--bld-us) + var(--cnt-h-p));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0}.tp-rotv.tp-rotv-not .tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}'),this.pool_.getAll().forEach(t=>{this.embedPluginStyle_(t)}),this.registerPlugin({plugins:[n2,nZ,tB,n5]})}},t.SeparatorApi=tk,t.SliderApi=nJ,t.TabApi=tO,t.TabPageApi=tR,t.TextApi=nW,t.TpChangeEvent=n,t.VERSION=n4,Object.defineProperty(t,"__esModule",{value:!0})}(e)}}]); \ No newline at end of file diff --git a/.next/static/chunks/537cd76e-7aba1cf7a4752418.js b/.next/static/chunks/537cd76e-7aba1cf7a4752418.js new file mode 100644 index 0000000..a1069f4 --- /dev/null +++ b/.next/static/chunks/537cd76e-7aba1cf7a4752418.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[116],{7089:function(e,t){/*! Tweakpane 3.1.10 (c) 2016 cocopon, licensed under the MIT license. */!function(e){"use strict";let Semver=class Semver{constructor(e){let[t,r]=e.split("-"),i=t.split(".");this.major=parseInt(i[0],10),this.minor=parseInt(i[1],10),this.patch=parseInt(i[2],10),this.prerelease=null!=r?r:null}toString(){let e=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[e,this.prerelease].join("-"):e}};let BladeApi=class BladeApi{constructor(e){this.controller_=e}get element(){return this.controller_.view.element}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(e){this.controller_.viewProps.set("disabled",e)}get hidden(){return this.controller_.viewProps.get("hidden")}set hidden(e){this.controller_.viewProps.set("hidden",e)}dispose(){this.controller_.viewProps.set("disposed",!0)}};let TpEvent=class TpEvent{constructor(e){this.target=e}};let TpChangeEvent=class TpChangeEvent extends TpEvent{constructor(e,t,r,i){super(e),this.value=t,this.presetKey=r,this.last=null==i||i}};let TpUpdateEvent=class TpUpdateEvent extends TpEvent{constructor(e,t,r){super(e),this.value=t,this.presetKey=r}};let TpFoldEvent=class TpFoldEvent extends TpEvent{constructor(e,t){super(e),this.expanded=t}};let TpTabSelectEvent=class TpTabSelectEvent extends TpEvent{constructor(e,t){super(e),this.index=t}};function isEmpty(e){return null==e}function deepEqualsArray(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function isPropertyWritable(e,t){let r=e;do{let e=Object.getOwnPropertyDescriptor(r,t);if(e&&(void 0!==e.set||!0===e.writable))return!0;r=Object.getPrototypeOf(r)}while(null!==r);return!1}let t={alreadydisposed:()=>"View has been already disposed",invalidparams:e=>`Invalid parameters for '${e.name}'`,nomatchingcontroller:e=>`No matching controller for '${e.key}'`,nomatchingview:e=>`No matching view for '${JSON.stringify(e.params)}'`,notbindable:()=>"Value is not bindable",propertynotfound:e=>`Property '${e.name}' not found`,shouldneverhappen:()=>"This error should never happen"};let TpError=class TpError{static alreadyDisposed(){return new TpError({type:"alreadydisposed"})}static notBindable(){return new TpError({type:"notbindable"})}static propertyNotFound(e){return new TpError({type:"propertynotfound",context:{name:e}})}static shouldNeverHappen(){return new TpError({type:"shouldneverhappen"})}constructor(e){var r;this.message=null!==(r=t[e.type](e.context))&&void 0!==r?r:"Unexpected error",this.name=this.constructor.name,this.stack=Error(this.message).stack,this.type=e.type}};let BindingTarget=class BindingTarget{constructor(e,t,r){this.obj_=e,this.key_=t,this.presetKey_=null!=r?r:t}static isBindable(e){return null!==e&&("object"==typeof e||"function"==typeof e)}get key(){return this.key_}get presetKey(){return this.presetKey_}read(){return this.obj_[this.key_]}write(e){this.obj_[this.key_]=e}writeProperty(e,t){let r=this.read();if(!BindingTarget.isBindable(r))throw TpError.notBindable();if(!(e in r))throw TpError.propertyNotFound(e);r[e]=t}};let ButtonApi=class ButtonApi extends BladeApi{get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get title(){var e;return null!==(e=this.controller_.valueController.props.get("title"))&&void 0!==e?e:""}set title(e){this.controller_.valueController.props.set("title",e)}on(e,t){let r=t.bind(this),i=this.controller_.valueController.emitter;return i.on(e,()=>{r(new TpEvent(this))}),this}};let Emitter=class Emitter{constructor(){this.observers_={}}on(e,t){let r=this.observers_[e];return r||(r=this.observers_[e]=[]),r.push({handler:t}),this}off(e,t){let r=this.observers_[e];return r&&(this.observers_[e]=r.filter(e=>e.handler!==t)),this}emit(e,t){let r=this.observers_[e];r&&r.forEach(e=>{e.handler(t)})}};function ClassName(e){return(t,r)=>["tp","-",e,"v",t?`_${t}`:"",r?`-${r}`:""].join("")}function compose(e,t){return r=>t(e(r))}function extractValue(e){return e.rawValue}function bindValue(e,t){e.emitter.on("change",compose(extractValue,t)),t(e.rawValue)}function bindValueMap(e,t,r){bindValue(e.value(t),r)}function applyClass(e,t,r){r?e.classList.add(t):e.classList.remove(t)}function valueToClassName(e,t){return r=>{applyClass(e,t,r)}}function bindValueToTextContent(e,t){bindValue(e,e=>{t.textContent=null!=e?e:""})}let r=ClassName("btn");let ButtonView=class ButtonView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(r()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("button");i.classList.add(r("b")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let n=e.createElement("div");n.classList.add(r("t")),bindValueToTextContent(t.props.value("title"),n),this.buttonElement.appendChild(n)}};let ButtonController=class ButtonController{constructor(e,t){this.emitter=new Emitter,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new ButtonView(e,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}};let BoundValue=class BoundValue{constructor(e,t){var r;this.constraint_=null==t?void 0:t.constraint,this.equals_=null!==(r=null==t?void 0:t.equals)&&void 0!==r?r:(e,t)=>e===t,this.emitter=new Emitter,this.rawValue_=e}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let r=null!=t?t:{forceEmit:!1,last:!0},i=this.constraint_?this.constraint_.constrain(e):e,n=this.rawValue_,o=!this.equals_(n,i);(o||r.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=i,this.emitter.emit("change",{options:r,previousRawValue:n,rawValue:i,sender:this}))}};let PrimitiveValue=class PrimitiveValue{constructor(e){this.emitter=new Emitter,this.value_=e}get rawValue(){return this.value_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let r=null!=t?t:{forceEmit:!1,last:!0},i=this.value_;(i!==e||r.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=e,this.emitter.emit("change",{options:r,previousRawValue:i,rawValue:this.value_,sender:this}))}};function createValue(e,t){let r=null==t?void 0:t.constraint,i=null==t?void 0:t.equals;return r||i?new BoundValue(e,t):new PrimitiveValue(e)}let ValueMap=class ValueMap{constructor(e){for(let t in this.emitter=new Emitter,this.valMap_=e,this.valMap_){let e=this.valMap_[t];e.emitter.on("change",()=>{this.emitter.emit("change",{key:t,sender:this})})}}static createCore(e){let t=Object.keys(e);return t.reduce((t,r)=>Object.assign(t,{[r]:createValue(e[r])}),{})}static fromObject(e){let t=this.createCore(e);return new ValueMap(t)}get(e){return this.valMap_[e].rawValue}set(e,t){this.valMap_[e].rawValue=t}value(e){return this.valMap_[e]}};function parseObject(e,t){let r=Object.keys(t),i=r.reduce((r,i)=>{if(void 0===r)return;let n=t[i],o=n(e[i]);return o.succeeded?Object.assign(Object.assign({},r),{[i]:o.value}):void 0},{});return i}function parseArray(e,t){return e.reduce((e,r)=>{if(void 0===e)return;let i=t(r);if(i.succeeded&&void 0!==i.value)return[...e,i.value]},[])}function isObject(e){return null!==e&&"object"==typeof e}function createParamsParserBuilder(e){return t=>r=>{if(!t&&void 0===r)return{succeeded:!1,value:void 0};if(t&&void 0===r)return{succeeded:!0,value:void 0};let i=e(r);return void 0!==i?{succeeded:!0,value:i}:{succeeded:!1,value:void 0}}}function createParamsParserBuilders(e){return{custom:t=>createParamsParserBuilder(t)(e),boolean:createParamsParserBuilder(e=>"boolean"==typeof e?e:void 0)(e),number:createParamsParserBuilder(e=>"number"==typeof e?e:void 0)(e),string:createParamsParserBuilder(e=>"string"==typeof e?e:void 0)(e),function:createParamsParserBuilder(e=>"function"==typeof e?e:void 0)(e),constant:t=>createParamsParserBuilder(e=>e===t?t:void 0)(e),raw:createParamsParserBuilder(e=>e)(e),object:t=>createParamsParserBuilder(e=>{if(isObject(e))return parseObject(e,t)})(e),array:t=>createParamsParserBuilder(e=>{if(Array.isArray(e))return parseArray(e,t)})(e)}}let i={optional:createParamsParserBuilders(!0),required:createParamsParserBuilders(!1)};function parseParams(e,t){let r=i.required.object(t)(e);return r.succeeded?r.value:void 0}function warnMissing(e){console.warn(`Missing '${e.key}' of ${e.target} in ${e.place}. Please rebuild plugins with the latest core package.`)}function disposeElement(e){return e&&e.parentElement&&e.parentElement.removeChild(e),null}let ReadonlyValue=class ReadonlyValue{constructor(e){this.value_=e}static create(e){return[new ReadonlyValue(e),(t,r)=>{e.setRawValue(t,r)}]}get emitter(){return this.value_.emitter}get rawValue(){return this.value_.rawValue}};let n=ClassName("");function valueToModifier(e,t){return valueToClassName(e,n(void 0,t))}let ViewProps=class ViewProps extends ValueMap{constructor(e){var t;super(e),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=ReadonlyValue.create(createValue(this.getGlobalDisabled_())),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(t=this.get("parent"))||void 0===t||t.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(e){var t,r,i;let n=null!=e?e:{};return new ViewProps(ValueMap.createCore({disabled:null!==(t=n.disabled)&&void 0!==t&&t,disposed:!1,hidden:null!==(r=n.hidden)&&void 0!==r&&r,parent:null!==(i=n.parent)&&void 0!==i?i:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(e){bindValue(this.globalDisabled_,valueToModifier(e,"disabled")),bindValueMap(this,"hidden",valueToModifier(e,"hidden"))}bindDisabled(e){bindValue(this.globalDisabled_,t=>{e.disabled=t})}bindTabIndex(e){bindValue(this.globalDisabled_,t=>{e.tabIndex=t?-1:0})}handleDispose(e){this.value("disposed").emitter.on("change",t=>{t&&e()})}getGlobalDisabled_(){let e=this.get("parent"),t=!!e&&e.globalDisabled.rawValue;return t||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(e){var t;let r=e.previousRawValue;null==r||r.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(t=this.get("parent"))||void 0===t||t.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}};function getAllBladePositions(){return["veryfirst","first","last","verylast"]}let o=ClassName(""),a={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"};let BladeController=class BladeController{constructor(e){this.parent_=null,this.blade=e.blade,this.view=e.view,this.viewProps=e.viewProps;let t=this.view.element;this.blade.value("positions").emitter.on("change",()=>{getAllBladePositions().forEach(e=>{t.classList.remove(o(void 0,a[e]))}),this.blade.get("positions").forEach(e=>{t.classList.add(o(void 0,a[e]))})}),this.viewProps.handleDispose(()=>{disposeElement(t)})}get parent(){return this.parent_}set parent(e){if(this.parent_=e,!("parent"in this.viewProps.valMap_)){warnMissing({key:"parent",target:ViewProps.name,place:"BladeController.parent"});return}this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}};let l="http://www.w3.org/2000/svg";function forceReflow(e){e.offsetHeight}function disableTransitionTemporarily(e,t){let r=e.style.transition;e.style.transition="none",t(),e.style.transition=r}function supportsTouch(e){return void 0!==e.ontouchstart}function getGlobalObject(){return globalThis}function getWindowDocument(){let e=getGlobalObject();return e.document}function getCanvasContext(e){let t=e.ownerDocument.defaultView;return t&&"document"in t?e.getContext("2d",{willReadFrequently:!0}):null}let s={check:'<path d="M2 8l4 4l8 -8"/>',dropdown:'<path d="M5 7h6l-3 3 z"/>',p2dpad:'<path d="M8 4v8"/><path d="M4 8h8"/><circle cx="12" cy="12" r="1.2"/>'};function createSvgIconElement(e,t){let r=e.createElementNS(l,"svg");return r.innerHTML=s[t],r}function insertElementAt(e,t,r){e.insertBefore(t,e.children[r])}function removeElement(e){e.parentElement&&e.parentElement.removeChild(e)}function removeChildElements(e){for(;e.children.length>0;)e.removeChild(e.children[0])}function removeChildNodes(e){for(;e.childNodes.length>0;)e.removeChild(e.childNodes[0])}function findNextTarget(e){return e.relatedTarget?e.relatedTarget:"explicitOriginalTarget"in e?e.explicitOriginalTarget:null}let p=ClassName("lbl");function createLabelNode(e,t){let r=e.createDocumentFragment(),i=t.split("\n").map(t=>e.createTextNode(t));return i.forEach((t,i)=>{i>0&&r.appendChild(e.createElement("br")),r.appendChild(t)}),r}let LabelView=class LabelView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(p()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add(p("l")),bindValueMap(t.props,"label",t=>{isEmpty(t)?this.element.classList.add(p(void 0,"nol")):(this.element.classList.remove(p(void 0,"nol")),removeChildNodes(r),r.appendChild(createLabelNode(e,t)))}),this.element.appendChild(r),this.labelElement=r;let i=e.createElement("div");i.classList.add(p("v")),this.element.appendChild(i),this.valueElement=i}};let LabelController=class LabelController extends BladeController{constructor(e,t){let r=t.valueController.viewProps;super(Object.assign(Object.assign({},t),{view:new LabelView(e,{props:t.props,viewProps:r}),viewProps:r})),this.props=t.props,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}};let d={id:"button",type:"blade",accept(e){let t=parseParams(e,{title:i.required.string,view:i.required.constant("button"),label:i.optional.string});return t?{params:t}:null},controller:e=>new LabelController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:new ButtonController(e.document,{props:ValueMap.fromObject({title:e.params.title}),viewProps:e.viewProps})}),api:e=>e.controller instanceof LabelController&&e.controller.valueController instanceof ButtonController?new ButtonApi(e.controller):null};let ValueBladeController=class ValueBladeController extends BladeController{constructor(e){super(e),this.value=e.value}};function createBlade(){return new ValueMap({positions:createValue([],{equals:deepEqualsArray})})}let Foldable=class Foldable extends ValueMap{constructor(e){super(e)}static create(e){let t=ValueMap.createCore({completed:!0,expanded:e,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null});return new Foldable(t)}get styleExpanded(){var e;return null!==(e=this.get("temporaryExpanded"))&&void 0!==e?e:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";let e=this.get("expandedHeight");return this.get("shouldFixHeight")&&!isEmpty(e)?`${e}px`:"auto"}bindExpandedClass(e,t){let onExpand=()=>{let r=this.styleExpanded;r?e.classList.add(t):e.classList.remove(t)};bindValueMap(this,"expanded",onExpand),bindValueMap(this,"temporaryExpanded",onExpand)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}};function computeExpandedFolderHeight(e,t){let r=0;return disableTransitionTemporarily(t,()=>{e.set("expandedHeight",null),e.set("temporaryExpanded",!0),forceReflow(t),r=t.clientHeight,e.set("temporaryExpanded",null),forceReflow(t)}),r}function applyHeight(e,t){t.style.height=e.styleHeight}function bindFoldable(e,t){e.value("expanded").emitter.on("beforechange",()=>{if(e.set("completed",!1),isEmpty(e.get("expandedHeight"))){let r=computeExpandedFolderHeight(e,t);r>0&&e.set("expandedHeight",r)}e.set("shouldFixHeight",!0),forceReflow(t)}),e.emitter.on("change",()=>{applyHeight(e,t)}),applyHeight(e,t),t.addEventListener("transitionend",t=>{"height"===t.propertyName&&e.cleanUpTransition()})}let RackLikeApi=class RackLikeApi extends BladeApi{constructor(e,t){super(e),this.rackApi_=t}};function addButtonAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"button"}))}function addFolderAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"folder"}))}function addSeparatorAsBlade(e,t){let r=null!=t?t:{};return e.addBlade(Object.assign(Object.assign({},r),{view:"separator"}))}function addTabAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"tab"}))}let NestedOrderedSet=class NestedOrderedSet{constructor(e){this.emitter=new Emitter,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=e}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(e){for(let t of this.allItems())if(e(t))return t;return null}includes(e){return this.cache_.has(e)}add(e,t){if(this.includes(e))throw TpError.shouldNeverHappen();let r=void 0!==t?t:this.items_.length;this.items_.splice(r,0,e),this.cache_.add(e);let i=this.extract_(e);i&&(i.emitter.on("add",this.onSubListAdd_),i.emitter.on("remove",this.onSubListRemove_),i.allItems().forEach(e=>{this.cache_.add(e)})),this.emitter.emit("add",{index:r,item:e,root:this,target:this})}remove(e){let t=this.items_.indexOf(e);if(t<0)return;this.items_.splice(t,1),this.cache_.delete(e);let r=this.extract_(e);r&&(r.emitter.off("add",this.onSubListAdd_),r.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:t,item:e,root:this,target:this})}onSubListAdd_(e){this.cache_.add(e.item),this.emitter.emit("add",{index:e.index,item:e.item,root:this,target:e.target})}onSubListRemove_(e){this.cache_.delete(e.item),this.emitter.emit("remove",{index:e.index,item:e.item,root:this,target:e.target})}};let InputBindingApi=class InputBindingApi extends BladeApi{constructor(e){super(e),this.onBindingChange_=this.onBindingChange_.bind(this),this.emitter_=new Emitter,this.controller_.binding.emitter.on("change",this.onBindingChange_)}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}refresh(){this.controller_.binding.read()}onBindingChange_(e){let t=e.sender.target.read();this.emitter_.emit("change",{event:new TpChangeEvent(this,t,this.controller_.binding.target.presetKey,e.options.last)})}};let InputBindingController=class InputBindingController extends LabelController{constructor(e,t){super(e,t),this.binding=t.binding}};let MonitorBindingApi=class MonitorBindingApi extends BladeApi{constructor(e){super(e),this.onBindingUpdate_=this.onBindingUpdate_.bind(this),this.emitter_=new Emitter,this.controller_.binding.emitter.on("update",this.onBindingUpdate_)}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}refresh(){this.controller_.binding.read()}onBindingUpdate_(e){let t=e.sender.target.read();this.emitter_.emit("update",{event:new TpUpdateEvent(this,t,this.controller_.binding.target.presetKey)})}};let MonitorBindingController=class MonitorBindingController extends LabelController{constructor(e,t){super(e,t),this.binding=t.binding,this.viewProps.bindDisabled(this.binding.ticker),this.viewProps.handleDispose(()=>{this.binding.dispose()})}};function findSubBladeApiSet(e){return e instanceof RackApi?e.apiSet_:e instanceof RackLikeApi?e.rackApi_.apiSet_:null}function getApiByController(e,t){let r=e.find(e=>e.controller_===t);if(!r)throw TpError.shouldNeverHappen();return r}function createBindingTarget(e,t,r){if(!BindingTarget.isBindable(e))throw TpError.notBindable();return new BindingTarget(e,t,r)}let RackApi=class RackApi extends BladeApi{constructor(e,t){super(e),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this),this.onRackInputChange_=this.onRackInputChange_.bind(this),this.onRackMonitorUpdate_=this.onRackMonitorUpdate_.bind(this),this.emitter_=new Emitter,this.apiSet_=new NestedOrderedSet(findSubBladeApiSet),this.pool_=t;let r=this.controller_.rack;r.emitter.on("add",this.onRackAdd_),r.emitter.on("remove",this.onRackRemove_),r.emitter.on("inputchange",this.onRackInputChange_),r.emitter.on("monitorupdate",this.onRackMonitorUpdate_),r.children.forEach(e=>{this.setUpApi_(e)})}get children(){return this.controller_.rack.children.map(e=>getApiByController(this.apiSet_,e))}addInput(e,t,r){let i=null!=r?r:{},n=this.controller_.view.element.ownerDocument,o=this.pool_.createInput(n,createBindingTarget(e,t,i.presetKey),i),a=new InputBindingApi(o);return this.add(a,i.index)}addMonitor(e,t,r){let i=null!=r?r:{},n=this.controller_.view.element.ownerDocument,o=this.pool_.createMonitor(n,createBindingTarget(e,t),i),a=new MonitorBindingApi(o);return this.add(a,i.index)}addFolder(e){return addFolderAsBlade(this,e)}addButton(e){return addButtonAsBlade(this,e)}addSeparator(e){return addSeparatorAsBlade(this,e)}addTab(e){return addTabAsBlade(this,e)}add(e,t){this.controller_.rack.add(e.controller_,t);let r=this.apiSet_.find(t=>t.controller_===e.controller_);return r&&this.apiSet_.remove(r),this.apiSet_.add(e),e}remove(e){this.controller_.rack.remove(e.controller_)}addBlade(e){let t=this.controller_.view.element.ownerDocument,r=this.pool_.createBlade(t,e),i=this.pool_.createBladeApi(r);return this.add(i,e.index)}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}setUpApi_(e){let t=this.apiSet_.find(t=>t.controller_===e);t||this.apiSet_.add(this.pool_.createBladeApi(e))}onRackAdd_(e){this.setUpApi_(e.bladeController)}onRackRemove_(e){if(e.isRoot){let t=getApiByController(this.apiSet_,e.bladeController);this.apiSet_.remove(t)}}onRackInputChange_(e){let t=e.bladeController;if(t instanceof InputBindingController){let r=getApiByController(this.apiSet_,t),i=t.binding;this.emitter_.emit("change",{event:new TpChangeEvent(r,i.target.read(),i.target.presetKey,e.options.last)})}else if(t instanceof ValueBladeController){let r=getApiByController(this.apiSet_,t);this.emitter_.emit("change",{event:new TpChangeEvent(r,t.value.rawValue,void 0,e.options.last)})}}onRackMonitorUpdate_(e){if(!(e.bladeController instanceof MonitorBindingController))throw TpError.shouldNeverHappen();let t=getApiByController(this.apiSet_,e.bladeController),r=e.bladeController.binding;this.emitter_.emit("update",{event:new TpUpdateEvent(t,r.target.read(),r.target.presetKey)})}};let FolderApi=class FolderApi extends RackLikeApi{constructor(e,t){super(e,new RackApi(e.rackController,t)),this.emitter_=new Emitter,this.controller_.foldable.value("expanded").emitter.on("change",e=>{this.emitter_.emit("fold",{event:new TpFoldEvent(this,e.sender.rawValue)})}),this.rackApi_.on("change",e=>{this.emitter_.emit("change",{event:e})}),this.rackApi_.on("update",e=>{this.emitter_.emit("update",{event:e})})}get expanded(){return this.controller_.foldable.get("expanded")}set expanded(e){this.controller_.foldable.set("expanded",e)}get title(){return this.controller_.props.get("title")}set title(e){this.controller_.props.set("title",e)}get children(){return this.rackApi_.children}addInput(e,t,r){return this.rackApi_.addInput(e,t,r)}addMonitor(e,t,r){return this.rackApi_.addMonitor(e,t,r)}addFolder(e){return this.rackApi_.addFolder(e)}addButton(e){return this.rackApi_.addButton(e)}addSeparator(e){return this.rackApi_.addSeparator(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){return this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addBlade(e){return this.rackApi_.addBlade(e)}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}};let RackLikeController=class RackLikeController extends BladeController{constructor(e){super({blade:e.blade,view:e.view,viewProps:e.rackController.viewProps}),this.rackController=e.rackController}};let PlainView=class PlainView{constructor(e,t){let r=ClassName(t.viewName);this.element=e.createElement("div"),this.element.classList.add(r()),t.viewProps.bindClassModifiers(this.element)}};function findInputBindingController(e,t){for(let r=0;r<e.length;r++){let i=e[r];if(i instanceof InputBindingController&&i.binding===t)return i}return null}function findMonitorBindingController(e,t){for(let r=0;r<e.length;r++){let i=e[r];if(i instanceof MonitorBindingController&&i.binding===t)return i}return null}function findValueBladeController(e,t){for(let r=0;r<e.length;r++){let i=e[r];if(i instanceof ValueBladeController&&i.value===t)return i}return null}function findSubRack(e){return e instanceof RackController?e.rack:e instanceof RackLikeController?e.rackController.rack:null}function findSubBladeControllerSet(e){let t=findSubRack(e);return t?t.bcSet_:null}let BladeRack=class BladeRack{constructor(e){var t,r;this.onBladePositionsChange_=this.onBladePositionsChange_.bind(this),this.onSetAdd_=this.onSetAdd_.bind(this),this.onSetRemove_=this.onSetRemove_.bind(this),this.onChildDispose_=this.onChildDispose_.bind(this),this.onChildPositionsChange_=this.onChildPositionsChange_.bind(this),this.onChildInputChange_=this.onChildInputChange_.bind(this),this.onChildMonitorUpdate_=this.onChildMonitorUpdate_.bind(this),this.onChildValueChange_=this.onChildValueChange_.bind(this),this.onChildViewPropsChange_=this.onChildViewPropsChange_.bind(this),this.onDescendantLayout_=this.onDescendantLayout_.bind(this),this.onDescendantInputChange_=this.onDescendantInputChange_.bind(this),this.onDescendantMonitorUpdate_=this.onDescendantMonitorUpdate_.bind(this),this.emitter=new Emitter,this.blade_=null!==(t=e.blade)&&void 0!==t?t:null,null===(r=this.blade_)||void 0===r||r.value("positions").emitter.on("change",this.onBladePositionsChange_),this.viewProps=e.viewProps,this.bcSet_=new NestedOrderedSet(findSubBladeControllerSet),this.bcSet_.emitter.on("add",this.onSetAdd_),this.bcSet_.emitter.on("remove",this.onSetRemove_)}get children(){return this.bcSet_.items}add(e,t){var r;null===(r=e.parent)||void 0===r||r.remove(e),isPropertyWritable(e,"parent")?e.parent=this:(e.parent_=this,warnMissing({key:"parent",target:"BladeController",place:"BladeRack.add"})),this.bcSet_.add(e,t)}remove(e){isPropertyWritable(e,"parent")?e.parent=null:(e.parent_=null,warnMissing({key:"parent",target:"BladeController",place:"BladeRack.remove"})),this.bcSet_.remove(e)}find(e){return this.bcSet_.allItems().filter(t=>t instanceof e)}onSetAdd_(e){this.updatePositions_();let t=e.target===e.root;if(this.emitter.emit("add",{bladeController:e.item,index:e.index,isRoot:t,sender:this}),!t)return;let r=e.item;if(r.viewProps.emitter.on("change",this.onChildViewPropsChange_),r.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),r.viewProps.handleDispose(this.onChildDispose_),r instanceof InputBindingController)r.binding.emitter.on("change",this.onChildInputChange_);else if(r instanceof MonitorBindingController)r.binding.emitter.on("update",this.onChildMonitorUpdate_);else if(r instanceof ValueBladeController)r.value.emitter.on("change",this.onChildValueChange_);else{let e=findSubRack(r);if(e){let t=e.emitter;t.on("layout",this.onDescendantLayout_),t.on("inputchange",this.onDescendantInputChange_),t.on("monitorupdate",this.onDescendantMonitorUpdate_)}}}onSetRemove_(e){this.updatePositions_();let t=e.target===e.root;if(this.emitter.emit("remove",{bladeController:e.item,isRoot:t,sender:this}),!t)return;let r=e.item;if(r instanceof InputBindingController)r.binding.emitter.off("change",this.onChildInputChange_);else if(r instanceof MonitorBindingController)r.binding.emitter.off("update",this.onChildMonitorUpdate_);else if(r instanceof ValueBladeController)r.value.emitter.off("change",this.onChildValueChange_);else{let e=findSubRack(r);if(e){let t=e.emitter;t.off("layout",this.onDescendantLayout_),t.off("inputchange",this.onDescendantInputChange_),t.off("monitorupdate",this.onDescendantMonitorUpdate_)}}}updatePositions_(){let e=this.bcSet_.items.filter(e=>!e.viewProps.get("hidden")),t=e[0],r=e[e.length-1];this.bcSet_.items.forEach(e=>{let i=[];e===t&&(i.push("first"),(!this.blade_||this.blade_.get("positions").includes("veryfirst"))&&i.push("veryfirst")),e===r&&(i.push("last"),(!this.blade_||this.blade_.get("positions").includes("verylast"))&&i.push("verylast")),e.blade.set("positions",i)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(e){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){let e=this.bcSet_.items.filter(e=>e.viewProps.get("disposed"));e.forEach(e=>{this.bcSet_.remove(e)})}onChildInputChange_(e){let t=findInputBindingController(this.find(InputBindingController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("inputchange",{bladeController:t,options:e.options,sender:this})}onChildMonitorUpdate_(e){let t=findMonitorBindingController(this.find(MonitorBindingController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("monitorupdate",{bladeController:t,sender:this})}onChildValueChange_(e){let t=findValueBladeController(this.find(ValueBladeController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("inputchange",{bladeController:t,options:e.options,sender:this})}onDescendantLayout_(e){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onDescendantInputChange_(e){this.emitter.emit("inputchange",{bladeController:e.bladeController,options:e.options,sender:this})}onDescendantMonitorUpdate_(e){this.emitter.emit("monitorupdate",{bladeController:e.bladeController,sender:this})}onBladePositionsChange_(){this.updatePositions_()}};let RackController=class RackController extends BladeController{constructor(e,t){super(Object.assign(Object.assign({},t),{view:new PlainView(e,{viewName:"brk",viewProps:t.viewProps})})),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this);let r=new BladeRack({blade:t.root?void 0:t.blade,viewProps:t.viewProps});r.emitter.on("add",this.onRackAdd_),r.emitter.on("remove",this.onRackRemove_),this.rack=r,this.viewProps.handleDispose(()=>{for(let e=this.rack.children.length-1;e>=0;e--){let t=this.rack.children[e];t.viewProps.set("disposed",!0)}})}onRackAdd_(e){e.isRoot&&insertElementAt(this.view.element,e.bladeController.view.element,e.index)}onRackRemove_(e){e.isRoot&&removeElement(e.bladeController.view.element)}};let u=ClassName("cnt");let FolderView=class FolderView{constructor(e,t){var r;this.className_=ClassName(null!==(r=t.viewName)&&void 0!==r?r:"fld"),this.element=e.createElement("div"),this.element.classList.add(this.className_(),u()),t.viewProps.bindClassModifiers(this.element),this.foldable_=t.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),bindValueMap(this.foldable_,"completed",valueToClassName(this.element,this.className_(void 0,"cpl")));let i=e.createElement("button");i.classList.add(this.className_("b")),bindValueMap(t.props,"title",e=>{isEmpty(e)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let n=e.createElement("div");n.classList.add(this.className_("i")),this.element.appendChild(n);let o=e.createElement("div");o.classList.add(this.className_("t")),bindValueToTextContent(t.props.value("title"),o),this.buttonElement.appendChild(o),this.titleElement=o;let a=e.createElement("div");a.classList.add(this.className_("m")),this.buttonElement.appendChild(a);let l=t.containerElement;l.classList.add(this.className_("c")),this.element.appendChild(l),this.containerElement=l}};let FolderController=class FolderController extends RackLikeController{constructor(e,t){var r;let i=Foldable.create(null===(r=t.expanded)||void 0===r||r),n=new RackController(e,{blade:t.blade,root:t.root,viewProps:t.viewProps});super(Object.assign(Object.assign({},t),{rackController:n,view:new FolderView(e,{containerElement:n.view.element,foldable:i,props:t.props,viewName:t.root?"rot":void 0,viewProps:t.viewProps})})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=t.props,this.foldable=i,bindFoldable(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}};let c={id:"folder",type:"blade",accept(e){let t=parseParams(e,{title:i.required.string,view:i.required.constant("folder"),expanded:i.optional.boolean});return t?{params:t}:null},controller:e=>new FolderController(e.document,{blade:e.blade,expanded:e.params.expanded,props:ValueMap.fromObject({title:e.params.title}),viewProps:e.viewProps}),api:e=>e.controller instanceof FolderController?new FolderApi(e.controller,e.pool):null};let LabeledValueController=class LabeledValueController extends ValueBladeController{constructor(e,t){let r=t.valueController.viewProps;super(Object.assign(Object.assign({},t),{value:t.valueController.value,view:new LabelView(e,{props:t.props,viewProps:r}),viewProps:r})),this.props=t.props,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}};let SeparatorApi=class SeparatorApi extends BladeApi{};let h=ClassName("spr");let SeparatorView=class SeparatorView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(h()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("hr");r.classList.add(h("r")),this.element.appendChild(r)}};let SeparatorController=class SeparatorController extends BladeController{constructor(e,t){super(Object.assign(Object.assign({},t),{view:new SeparatorView(e,{viewProps:t.viewProps})}))}};let v={id:"separator",type:"blade",accept(e){let t=parseParams(e,{view:i.required.constant("separator")});return t?{params:t}:null},controller:e=>new SeparatorController(e.document,{blade:e.blade,viewProps:e.viewProps}),api:e=>e.controller instanceof SeparatorController?new SeparatorApi(e.controller):null},m=ClassName("tbi");let TabItemView=class TabItemView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(m()),t.viewProps.bindClassModifiers(this.element),bindValueMap(t.props,"selected",e=>{e?this.element.classList.add(m(void 0,"sel")):this.element.classList.remove(m(void 0,"sel"))});let r=e.createElement("button");r.classList.add(m("b")),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r;let i=e.createElement("div");i.classList.add(m("t")),bindValueToTextContent(t.props.value("title"),i),this.buttonElement.appendChild(i),this.titleElement=i}};let TabItemController=class TabItemController{constructor(e,t){this.emitter=new Emitter,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new TabItemView(e,{props:t.props,viewProps:t.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}};let TabPageController=class TabPageController{constructor(e,t){this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new TabItemController(e,{props:t.itemProps,viewProps:ViewProps.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.cc_=new RackController(e,{blade:createBlade(),viewProps:ViewProps.create()}),this.props=t.props,bindValueMap(this.props,"selected",e=>{this.itemController.props.set("selected",e),this.contentController.viewProps.set("hidden",!e)})}get itemController(){return this.ic_}get contentController(){return this.cc_}onItemClick_(){this.props.set("selected",!0)}};let TabPageApi=class TabPageApi{constructor(e,t){this.controller_=e,this.rackApi_=t}get title(){var e;return null!==(e=this.controller_.itemController.props.get("title"))&&void 0!==e?e:""}set title(e){this.controller_.itemController.props.set("title",e)}get selected(){return this.controller_.props.get("selected")}set selected(e){this.controller_.props.set("selected",e)}get children(){return this.rackApi_.children}addButton(e){return this.rackApi_.addButton(e)}addFolder(e){return this.rackApi_.addFolder(e)}addSeparator(e){return this.rackApi_.addSeparator(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addInput(e,t,r){return this.rackApi_.addInput(e,t,r)}addMonitor(e,t,r){return this.rackApi_.addMonitor(e,t,r)}addBlade(e){return this.rackApi_.addBlade(e)}};let TabApi=class TabApi extends RackLikeApi{constructor(e,t){super(e,new RackApi(e.rackController,t)),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.onSelect_=this.onSelect_.bind(this),this.emitter_=new Emitter,this.pageApiMap_=new Map,this.rackApi_.on("change",e=>{this.emitter_.emit("change",{event:e})}),this.rackApi_.on("update",e=>{this.emitter_.emit("update",{event:e})}),this.controller_.tab.selectedIndex.emitter.on("change",this.onSelect_),this.controller_.pageSet.emitter.on("add",this.onPageAdd_),this.controller_.pageSet.emitter.on("remove",this.onPageRemove_),this.controller_.pageSet.items.forEach(e=>{this.setUpPageApi_(e)})}get pages(){return this.controller_.pageSet.items.map(e=>{let t=this.pageApiMap_.get(e);if(!t)throw TpError.shouldNeverHappen();return t})}addPage(e){let t=this.controller_.view.element.ownerDocument,r=new TabPageController(t,{itemProps:ValueMap.fromObject({selected:!1,title:e.title}),props:ValueMap.fromObject({selected:!1})});this.controller_.add(r,e.index);let i=this.pageApiMap_.get(r);if(!i)throw TpError.shouldNeverHappen();return i}removePage(e){this.controller_.remove(e)}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}setUpPageApi_(e){let t=this.rackApi_.apiSet_.find(t=>t.controller_===e.contentController);if(!t)throw TpError.shouldNeverHappen();let r=new TabPageApi(e,t);this.pageApiMap_.set(e,r)}onPageAdd_(e){this.setUpPageApi_(e.item)}onPageRemove_(e){let t=this.pageApiMap_.get(e.item);if(!t)throw TpError.shouldNeverHappen();this.pageApiMap_.delete(e.item)}onSelect_(e){this.emitter_.emit("select",{event:new TpTabSelectEvent(this,e.rawValue)})}};let Tab=class Tab{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=createValue(!0),this.selectedIndex=createValue(-1),this.items_=[]}add(e,t){let r=null!=t?t:this.items_.length;this.items_.splice(r,0,e),e.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(e){let t=this.items_.indexOf(e);t<0||(this.items_.splice(t,1),e.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length){this.selectedIndex.rawValue=-1,this.empty.rawValue=!0;return}let e=this.items_.findIndex(e=>e.rawValue);e<0?(this.items_.forEach((e,t)=>{e.rawValue=0===t}),this.selectedIndex.rawValue=0):(this.items_.forEach((t,r)=>{t.rawValue=r===e}),this.selectedIndex.rawValue=e),this.empty.rawValue=!1}onItemSelectedChange_(e){if(e.rawValue){let t=this.items_.findIndex(t=>t===e.sender);this.items_.forEach((e,r)=>{e.rawValue=r===t}),this.selectedIndex.rawValue=t}else this.keepSelection_()}};let b=ClassName("tab");let TabView=class TabView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(b(),u()),t.viewProps.bindClassModifiers(this.element),bindValue(t.empty,valueToClassName(this.element,b(void 0,"nop")));let r=e.createElement("div");r.classList.add(b("t")),this.element.appendChild(r),this.itemsElement=r;let i=e.createElement("div");i.classList.add(b("i")),this.element.appendChild(i);let n=t.contentsElement;n.classList.add(b("c")),this.element.appendChild(n),this.contentsElement=n}};let TabController=class TabController extends RackLikeController{constructor(e,t){let r=new RackController(e,{blade:t.blade,viewProps:t.viewProps}),i=new Tab;super({blade:t.blade,rackController:r,view:new TabView(e,{contentsElement:r.view.element,empty:i.empty,viewProps:t.viewProps})}),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.pageSet_=new NestedOrderedSet(()=>null),this.pageSet_.emitter.on("add",this.onPageAdd_),this.pageSet_.emitter.on("remove",this.onPageRemove_),this.tab=i}get pageSet(){return this.pageSet_}add(e,t){this.pageSet_.add(e,t)}remove(e){this.pageSet_.remove(this.pageSet_.items[e])}onPageAdd_(e){let t=e.item;insertElementAt(this.view.itemsElement,t.itemController.view.element,e.index),t.itemController.viewProps.set("parent",this.viewProps),this.rackController.rack.add(t.contentController,e.index),this.tab.add(t.props.value("selected"))}onPageRemove_(e){let t=e.item;removeElement(t.itemController.view.element),t.itemController.viewProps.set("parent",null),this.rackController.rack.remove(t.contentController),this.tab.remove(t.props.value("selected"))}};let g={id:"tab",type:"blade",accept(e){let t=parseParams(e,{pages:i.required.array(i.required.object({title:i.required.string})),view:i.required.constant("tab")});return t&&0!==t.pages.length?{params:t}:null},controller(e){let t=new TabController(e.document,{blade:e.blade,viewProps:e.viewProps});return e.params.pages.forEach(r=>{let i=new TabPageController(e.document,{itemProps:ValueMap.fromObject({selected:!1,title:r.title}),props:ValueMap.fromObject({selected:!1})});t.add(i)}),t},api:e=>e.controller instanceof TabController?new TabApi(e.controller,e.pool):null};function createBladeController(e,t){let r=e.accept(t.params);if(!r)return null;let n=i.optional.boolean(t.params.disabled).value,o=i.optional.boolean(t.params.hidden).value;return e.controller({blade:createBlade(),document:t.document,params:Object.assign(Object.assign({},r.params),{disabled:n,hidden:o}),viewProps:ViewProps.create({disabled:n,hidden:o})})}let ManualTicker=class ManualTicker{constructor(){this.disabled=!1,this.emitter=new Emitter}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}};let IntervalTicker=class IntervalTicker{constructor(e,t){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=e,this.emitter=new Emitter,this.interval_=t,this.setTimer_()}get disabled(){return this.disabled_}set disabled(e){this.disabled_=e,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;let e=this.doc_.defaultView;e&&e.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;let e=this.doc_.defaultView;e&&(this.timerId_=e.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}};let InputBinding=class InputBinding{constructor(e){this.onValueChange_=this.onValueChange_.bind(this),this.reader=e.reader,this.writer=e.writer,this.emitter=new Emitter,this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.target=e.target,this.read()}read(){let e=this.target.read();void 0!==e&&(this.value.rawValue=this.reader(e))}write_(e){this.writer(this.target,e)}onValueChange_(e){this.write_(e.rawValue),this.emitter.emit("change",{options:e.options,rawValue:e.rawValue,sender:this})}};function fillBuffer(e,t){for(;e.length<t;)e.push(void 0)}function initializeBuffer(e){let t=[];return fillBuffer(t,e),createValue(t)}function createTrimmedBuffer(e){let t=e.indexOf(void 0);return t<0?e:e.slice(0,t)}function createPushedBuffer(e,t){let r=[...createTrimmedBuffer(e),t];return r.length>e.length?r.splice(0,r.length-e.length):fillBuffer(r,e.length),r}let MonitorBinding=class MonitorBinding{constructor(e){this.onTick_=this.onTick_.bind(this),this.reader_=e.reader,this.target=e.target,this.emitter=new Emitter,this.value=e.value,this.ticker=e.ticker,this.ticker.emitter.on("tick",this.onTick_),this.read()}dispose(){this.ticker.dispose()}read(){let e=this.target.read();if(void 0===e)return;let t=this.value.rawValue,r=this.reader_(e);this.value.rawValue=createPushedBuffer(t,r),this.emitter.emit("update",{rawValue:r,sender:this})}onTick_(e){this.read()}};let CompositeConstraint=class CompositeConstraint{constructor(e){this.constraints=e}constrain(e){return this.constraints.reduce((e,t)=>t.constrain(e),e)}};function findConstraint(e,t){if(e instanceof t)return e;if(e instanceof CompositeConstraint){let r=e.constraints.reduce((e,r)=>e||(r instanceof t?r:null),null);if(r)return r}return null}let DefiniteRangeConstraint=class DefiniteRangeConstraint{constructor(e){this.values=ValueMap.fromObject({max:e.max,min:e.min})}constrain(e){let t=this.values.get("max"),r=this.values.get("min");return Math.min(Math.max(e,r),t)}};let ListConstraint=class ListConstraint{constructor(e){this.values=ValueMap.fromObject({options:e})}get options(){return this.values.get("options")}constrain(e){let t=this.values.get("options");if(0===t.length)return e;let r=t.filter(t=>t.value===e).length>0;return r?e:t[0].value}};let RangeConstraint=class RangeConstraint{constructor(e){this.values=ValueMap.fromObject({max:e.max,min:e.min})}get maxValue(){return this.values.get("max")}get minValue(){return this.values.get("min")}constrain(e){let t=this.values.get("max"),r=this.values.get("min"),i=e;return isEmpty(r)||(i=Math.max(i,r)),isEmpty(t)||(i=Math.min(i,t)),i}};let StepConstraint=class StepConstraint{constructor(e,t=0){this.step=e,this.origin=t}constrain(e){let t=this.origin%this.step,r=Math.round((e-t)/this.step);return t+r*this.step}};let _=ClassName("lst");let ListView=class ListView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.props_=t.props,this.element=e.createElement("div"),this.element.classList.add(_()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("select");r.classList.add(_("s")),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.selectElement=r;let i=e.createElement("div");i.classList.add(_("m")),i.appendChild(createSvgIconElement(e,"dropdown")),this.element.appendChild(i),t.value.emitter.on("change",this.onValueChange_),this.value_=t.value,bindValueMap(this.props_,"options",t=>{removeChildElements(this.selectElement),t.forEach(t=>{let r=e.createElement("option");r.textContent=t.text,this.selectElement.appendChild(r)}),this.update_()})}update_(){let e=this.props_.get("options").map(e=>e.value);this.selectElement.selectedIndex=e.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}};let ListController=class ListController{constructor(e,t){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new ListView(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(e){let t=e.currentTarget;this.value.rawValue=this.props.get("options")[t.selectedIndex].value}};let f=ClassName("pop");let PopupView=class PopupView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(f()),t.viewProps.bindClassModifiers(this.element),bindValue(t.shows,valueToClassName(this.element,f(void 0,"v")))}};let PopupController=class PopupController{constructor(e,t){this.shows=createValue(!1),this.viewProps=t.viewProps,this.view=new PopupView(e,{shows:this.shows,viewProps:this.viewProps})}};let w=ClassName("txt");let TextView=class TextView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.element=e.createElement("div"),this.element.classList.add(w()),t.viewProps.bindClassModifiers(this.element),this.props_=t.props,this.props_.emitter.on("change",this.onChange_);let r=e.createElement("input");r.classList.add(w("i")),r.type="text",t.viewProps.bindDisabled(r),this.element.appendChild(r),this.inputElement=r,t.value.emitter.on("change",this.onChange_),this.value_=t.value,this.refresh()}refresh(){let e=this.props_.get("formatter");this.inputElement.value=e(this.value_.rawValue)}onChange_(){this.refresh()}};let TextController=class TextController{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=t.parser,this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new TextView(e,{props:t.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(e){let t=e.currentTarget,r=t.value,i=this.parser_(r);isEmpty(i)||(this.value.rawValue=i),this.view.refresh()}};function boolToString(e){return String(e)}function boolFromUnknown(e){return"false"!==e&&!!e}function BooleanFormatter(e){return boolToString(e)}let NumberLiteralNode=class NumberLiteralNode{constructor(e){this.text=e}evaluate(){return Number(this.text)}toString(){return this.text}};let C={"**":(e,t)=>Math.pow(e,t),"*":(e,t)=>e*t,"/":(e,t)=>e/t,"%":(e,t)=>e%t,"+":(e,t)=>e+t,"-":(e,t)=>e-t,"<<":(e,t)=>e<<t,">>":(e,t)=>e>>t,">>>":(e,t)=>e>>>t,"&":(e,t)=>e&t,"^":(e,t)=>e^t,"|":(e,t)=>e|t};let BinaryOperationNode=class BinaryOperationNode{constructor(e,t,r){this.left=t,this.operator=e,this.right=r}evaluate(){let e=C[this.operator];if(!e)throw Error(`unexpected binary operator: '${this.operator}`);return e(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}};let x={"+":e=>e,"-":e=>-e,"~":e=>~e};let UnaryOperationNode=class UnaryOperationNode{constructor(e,t){this.operator=e,this.expression=t}evaluate(){let e=x[this.operator];if(!e)throw Error(`unexpected unary operator: '${this.operator}`);return e(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}};function combineReader(e){return(t,r)=>{for(let i=0;i<e.length;i++){let n=e[i](t,r);if(""!==n)return n}return""}}function readWhitespace(e,t){var r;let i=e.substr(t).match(/^\s+/);return null!==(r=i&&i[0])&&void 0!==r?r:""}function readNonZeroDigit(e,t){let r=e.substr(t,1);return r.match(/^[1-9]$/)?r:""}function readDecimalDigits(e,t){var r;let i=e.substr(t).match(/^[0-9]+/);return null!==(r=i&&i[0])&&void 0!==r?r:""}function readSignedInteger(e,t){let r=readDecimalDigits(e,t);if(""!==r)return r;let i=e.substr(t,1);if(t+=1,"-"!==i&&"+"!==i)return"";let n=readDecimalDigits(e,t);return""===n?"":i+n}function readExponentPart(e,t){let r=e.substr(t,1);if(t+=1,"e"!==r.toLowerCase())return"";let i=readSignedInteger(e,t);return""===i?"":r+i}function readDecimalIntegerLiteral(e,t){let r=e.substr(t,1);if("0"===r)return r;let i=readNonZeroDigit(e,t);return(t+=i.length,""===i)?"":i+readDecimalDigits(e,t)}function readDecimalLiteral1(e,t){let r=readDecimalIntegerLiteral(e,t);if(t+=r.length,""===r)return"";let i=e.substr(t,1);if(t+=i.length,"."!==i)return"";let n=readDecimalDigits(e,t);return t+=n.length,r+i+n+readExponentPart(e,t)}function readDecimalLiteral2(e,t){let r=e.substr(t,1);if(t+=r.length,"."!==r)return"";let i=readDecimalDigits(e,t);return(t+=i.length,""===i)?"":r+i+readExponentPart(e,t)}function readDecimalLiteral3(e,t){let r=readDecimalIntegerLiteral(e,t);return(t+=r.length,""===r)?"":r+readExponentPart(e,t)}let P=combineReader([readDecimalLiteral1,readDecimalLiteral2,readDecimalLiteral3]);function parseBinaryDigits(e,t){var r;let i=e.substr(t).match(/^[01]+/);return null!==(r=i&&i[0])&&void 0!==r?r:""}function readBinaryIntegerLiteral(e,t){let r=e.substr(t,2);if(t+=r.length,"0b"!==r.toLowerCase())return"";let i=parseBinaryDigits(e,t);return""===i?"":r+i}function readOctalDigits(e,t){var r;let i=e.substr(t).match(/^[0-7]+/);return null!==(r=i&&i[0])&&void 0!==r?r:""}function readOctalIntegerLiteral(e,t){let r=e.substr(t,2);if(t+=r.length,"0o"!==r.toLowerCase())return"";let i=readOctalDigits(e,t);return""===i?"":r+i}function readHexDigits(e,t){var r;let i=e.substr(t).match(/^[0-9a-f]+/i);return null!==(r=i&&i[0])&&void 0!==r?r:""}function readHexIntegerLiteral(e,t){let r=e.substr(t,2);if(t+=r.length,"0x"!==r.toLowerCase())return"";let i=readHexDigits(e,t);return""===i?"":r+i}let y=combineReader([readBinaryIntegerLiteral,readOctalIntegerLiteral,readHexIntegerLiteral]),E=combineReader([y,P]);function parseLiteral(e,t){let r=E(e,t);return(t+=r.length,""===r)?null:{evaluable:new NumberLiteralNode(r),cursor:t}}function parseParenthesizedExpression(e,t){let r=e.substr(t,1);if(t+=r.length,"("!==r)return null;let i=parseExpression(e,t);if(!i)return null;t=i.cursor,t+=readWhitespace(e,t).length;let n=e.substr(t,1);return(t+=n.length,")"!==n)?null:{evaluable:i.evaluable,cursor:t}}function parsePrimaryExpression(e,t){var r;return null!==(r=parseLiteral(e,t))&&void 0!==r?r:parseParenthesizedExpression(e,t)}function parseUnaryExpression(e,t){let r=parsePrimaryExpression(e,t);if(r)return r;let i=e.substr(t,1);if(t+=i.length,"+"!==i&&"-"!==i&&"~"!==i)return null;let n=parseUnaryExpression(e,t);return n?{cursor:t=n.cursor,evaluable:new UnaryOperationNode(i,n.evaluable)}:null}function readBinaryOperator(e,t,r){r+=readWhitespace(t,r).length;let i=e.filter(e=>t.startsWith(e,r))[0];return i?(r+=i.length,{cursor:r+=readWhitespace(t,r).length,operator:i}):null}function createBinaryOperationExpressionParser(e,t){return(r,i)=>{let n=e(r,i);if(!n)return null;i=n.cursor;let o=n.evaluable;for(;;){let n=readBinaryOperator(t,r,i);if(!n)break;i=n.cursor;let a=e(r,i);if(!a)return null;i=a.cursor,o=new BinaryOperationNode(n.operator,o,a.evaluable)}return o?{cursor:i,evaluable:o}:null}}let V=[["**"],["*","/","%"],["+","-"],["<<",">>>",">>"],["&"],["^"],["|"]].reduce((e,t)=>createBinaryOperationExpressionParser(e,t),parseUnaryExpression);function parseExpression(e,t){return t+=readWhitespace(e,t).length,V(e,t)}function parseEcmaNumberExpression(e){let t=parseExpression(e,0);if(!t)return null;let r=t.cursor+readWhitespace(e,t.cursor).length;return r!==e.length?null:t.evaluable}function parseNumber(e){var t;let r=parseEcmaNumberExpression(e);return null!==(t=null==r?void 0:r.evaluate())&&void 0!==t?t:null}function numberFromUnknown(e){if("number"==typeof e)return e;if("string"==typeof e){let t=parseNumber(e);if(!isEmpty(t))return t}return 0}function numberToString(e){return String(e)}function createNumberFormatter(e){return t=>t.toFixed(Math.max(Math.min(e,20),0))}let k=createNumberFormatter(0);function formatPercentage(e){return k(e)+"%"}function stringFromUnknown(e){return String(e)}function formatString(e){return e}function connectValues({primary:e,secondary:t,forward:r,backward:i}){let n=!1;function preventFeedback(e){n||(n=!0,e(),n=!1)}e.emitter.on("change",i=>{preventFeedback(()=>{t.setRawValue(r(e,t),i.options)})}),t.emitter.on("change",n=>{preventFeedback(()=>{e.setRawValue(i(e,t),n.options)}),preventFeedback(()=>{t.setRawValue(r(e,t),n.options)})}),preventFeedback(()=>{t.setRawValue(r(e,t),{forceEmit:!1,last:!0})})}function getStepForKey(e,t){let r=e*(t.altKey?.1:1)*(t.shiftKey?10:1);return t.upKey?+r:t.downKey?-r:0}function getVerticalStepKeys(e){return{altKey:e.altKey,downKey:"ArrowDown"===e.key,shiftKey:e.shiftKey,upKey:"ArrowUp"===e.key}}function getHorizontalStepKeys(e){return{altKey:e.altKey,downKey:"ArrowLeft"===e.key,shiftKey:e.shiftKey,upKey:"ArrowRight"===e.key}}function isVerticalArrowKey(e){return"ArrowUp"===e||"ArrowDown"===e}function isArrowKey(e){return isVerticalArrowKey(e)||"ArrowLeft"===e||"ArrowRight"===e}function computeOffset$1(e,t){var r,i;let n=t.ownerDocument.defaultView,o=t.getBoundingClientRect();return{x:e.pageX-((null!==(r=n&&n.scrollX)&&void 0!==r?r:0)+o.left),y:e.pageY-((null!==(i=n&&n.scrollY)&&void 0!==i?i:0)+o.top)}}let PointerHandler=class PointerHandler{constructor(e){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=e,this.emitter=new Emitter,e.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),e.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),e.addEventListener("touchend",this.onTouchEnd_),e.addEventListener("mousedown",this.onMouseDown_)}computePosition_(e){let t=this.elem_.getBoundingClientRect();return{bounds:{width:t.width,height:t.height},point:e?{x:e.x,y:e.y}:null}}onMouseDown_(e){var t;e.preventDefault(),null===(t=e.currentTarget)||void 0===t||t.focus();let r=this.elem_.ownerDocument;r.addEventListener("mousemove",this.onDocumentMouseMove_),r.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseMove_(e){this.emitter.emit("move",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseUp_(e){let t=this.elem_.ownerDocument;t.removeEventListener("mousemove",this.onDocumentMouseMove_),t.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onTouchStart_(e){e.preventDefault();let t=e.targetTouches.item(0),r=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-r.left,y:t.clientY-r.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchMove_(e){let t=e.targetTouches.item(0),r=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-r.left,y:t.clientY-r.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchEnd_(e){var t;let r=null!==(t=e.targetTouches.item(0))&&void 0!==t?t:this.lastTouch_,i=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:e.altKey,data:this.computePosition_(r?{x:r.clientX-i.left,y:r.clientY-i.top}:void 0),sender:this,shiftKey:e.shiftKey})}};function mapRange(e,t,r,i,n){return i+(e-t)/(r-t)*(n-i)}function getDecimalDigits(e){let t=String(e.toFixed(10)),r=t.split(".")[1];return r.replace(/0+$/,"").length}function constrainRange(e,t,r){return Math.min(Math.max(e,t),r)}let S=ClassName("txt");let NumberTextView=class NumberTextView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on("change",this.onChange_),this.element=e.createElement("div"),this.element.classList.add(S(),S(void 0,"num")),t.arrayPosition&&this.element.classList.add(S(void 0,t.arrayPosition)),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("input");r.classList.add(S("i")),r.type="text",t.viewProps.bindDisabled(r),this.element.appendChild(r),this.inputElement=r,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=t.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(S()),this.inputElement.classList.add(S("i"));let i=e.createElement("div");i.classList.add(S("k")),this.element.appendChild(i),this.knobElement=i;let n=e.createElementNS(l,"svg");n.classList.add(S("g")),this.knobElement.appendChild(n);let o=e.createElementNS(l,"path");o.classList.add(S("gb")),n.appendChild(o),this.guideBodyElem_=o;let a=e.createElementNS(l,"path");a.classList.add(S("gh")),n.appendChild(a),this.guideHeadElem_=a;let s=e.createElement("div");s.classList.add(ClassName("tt")()),this.knobElement.appendChild(s),this.tooltipElem_=s,t.value.emitter.on("change",this.onChange_),this.value=t.value,this.refresh()}onDraggingChange_(e){if(null===e.rawValue){this.element.classList.remove(S(void 0,"drg"));return}this.element.classList.add(S(void 0,"drg"));let t=e.rawValue/this.props_.get("draggingScale"),r=t+(t>0?-1:t<0?1:0),i=constrainRange(-r,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",`M ${r+i},0 L${r},4 L${r+i},8 M ${t},-1 L${t},9`),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${t},4`);let n=this.props_.get("formatter");this.tooltipElem_.textContent=n(this.value.rawValue),this.tooltipElem_.style.left=`${t}px`}refresh(){let e=this.props_.get("formatter");this.inputElement.value=e(this.value.rawValue)}onChange_(){this.refresh()}};let NumberTextController=class NumberTextController{constructor(e,t){var r;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=t.baseStep,this.parser_=t.parser,this.props=t.props,this.sliderProps_=null!==(r=t.sliderProps)&&void 0!==r?r:null,this.value=t.value,this.viewProps=t.viewProps,this.dragging_=createValue(null),this.view=new NumberTextView(e,{arrayPosition:t.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);let i=new PointerHandler(this.view.knobElement);i.emitter.on("down",this.onPointerDown_),i.emitter.on("move",this.onPointerMove_),i.emitter.on("up",this.onPointerUp_)}constrainValue_(e){var t,r;let i=null===(t=this.sliderProps_)||void 0===t?void 0:t.get("minValue"),n=null===(r=this.sliderProps_)||void 0===r?void 0:r.get("maxValue"),o=e;return void 0!==i&&(o=Math.max(o,i)),void 0!==n&&(o=Math.min(o,n)),o}onInputChange_(e){let t=e.currentTarget,r=t.value,i=this.parser_(r);isEmpty(i)||(this.value.rawValue=this.constrainValue_(i)),this.view.refresh()}onInputKeyDown_(e){let t=getStepForKey(this.baseStep_,getVerticalStepKeys(e));0!==t&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+t),{forceEmit:!1,last:!1})}onInputKeyUp_(e){let t=getStepForKey(this.baseStep_,getVerticalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(e){if(!e.point)return null;let t=e.point.x-e.bounds.width/2;return this.constrainValue_(this.originRawValue_+t*this.props.get("draggingScale"))}onPointerMove_(e){let t=this.computeDraggingValue_(e.data);null!==t&&(this.value.setRawValue(t,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(e){let t=this.computeDraggingValue_(e.data);null!==t&&(this.value.setRawValue(t,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}};let T=ClassName("sld");let SliderView=class SliderView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on("change",this.onChange_),this.element=e.createElement("div"),this.element.classList.add(T()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add(T("t")),t.viewProps.bindTabIndex(r),this.element.appendChild(r),this.trackElement=r;let i=e.createElement("div");i.classList.add(T("k")),this.trackElement.appendChild(i),this.knobElement=i,t.value.emitter.on("change",this.onChange_),this.value=t.value,this.update_()}update_(){let e=constrainRange(mapRange(this.value.rawValue,this.props_.get("minValue"),this.props_.get("maxValue"),0,100),0,100);this.knobElement.style.width=`${e}%`}onChange_(){this.update_()}};let SliderController=class SliderController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=t.baseStep,this.value=t.value,this.viewProps=t.viewProps,this.props=t.props,this.view=new SliderView(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){e.point&&this.value.setRawValue(mapRange(constrainRange(e.point.x,0,e.bounds.width),0,e.bounds.width,this.props.get("minValue"),this.props.get("maxValue")),t)}onPointerDownOrMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(this.baseStep_,getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue+t,{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(this.baseStep_,getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let R=ClassName("sldtxt");let SliderTextView=class SliderTextView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(R());let r=e.createElement("div");r.classList.add(R("s")),this.sliderView_=t.sliderView,r.appendChild(this.sliderView_.element),this.element.appendChild(r);let i=e.createElement("div");i.classList.add(R("t")),this.textView_=t.textView,i.appendChild(this.textView_.element),this.element.appendChild(i)}};let SliderTextController=class SliderTextController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.sliderC_=new SliderController(e,{baseStep:t.baseStep,props:t.sliderProps,value:t.value,viewProps:this.viewProps}),this.textC_=new NumberTextController(e,{baseStep:t.baseStep,parser:t.parser,props:t.textProps,sliderProps:t.sliderProps,value:t.value,viewProps:t.viewProps}),this.view=new SliderTextView(e,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}};function writePrimitive(e,t){e.write(t)}function parseListOptions(e){return Array.isArray(e)?i.required.array(i.required.object({text:i.required.string,value:i.required.raw}))(e).value:"object"==typeof e?i.required.raw(e).value:void 0}function parsePickerLayout(e){if("inline"===e||"popup"===e)return e}function parsePointDimensionParams(e){return i.required.object({max:i.optional.number,min:i.optional.number,step:i.optional.number})(e).value}function normalizeListOptions(e){if(Array.isArray(e))return e;let t=[];return Object.keys(e).forEach(r=>{t.push({text:r,value:e[r]})}),t}function createListConstraint(e){return isEmpty(e)?null:new ListConstraint(normalizeListOptions(e))}function findStep(e){let t=e?findConstraint(e,StepConstraint):null;return t?t.step:null}function getSuitableDecimalDigits(e,t){let r=e&&findConstraint(e,StepConstraint);return r?getDecimalDigits(r.step):Math.max(getDecimalDigits(t),2)}function getBaseStep(e){let t=findStep(e);return null!=t?t:1}function getSuitableDraggingScale(e,t){var r;let i=e&&findConstraint(e,StepConstraint),n=Math.abs(null!==(r=null==i?void 0:i.step)&&void 0!==r?r:t);return 0===n?.1:Math.pow(10,Math.floor(Math.log10(n))-1)}let M=ClassName("ckb");let CheckboxView=class CheckboxView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.element=e.createElement("div"),this.element.classList.add(M()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("label");r.classList.add(M("l")),this.element.appendChild(r);let i=e.createElement("input");i.classList.add(M("i")),i.type="checkbox",r.appendChild(i),this.inputElement=i,t.viewProps.bindDisabled(this.inputElement);let n=e.createElement("div");n.classList.add(M("w")),r.appendChild(n);let o=createSvgIconElement(e,"check");n.appendChild(o),t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}};let CheckboxController=class CheckboxController{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new CheckboxView(e,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(e){let t=e.currentTarget;this.value.rawValue=t.checked}};function createConstraint$6(e){let t=[],r=createListConstraint(e.options);return r&&t.push(r),new CompositeConstraint(t)}let L={id:"input-bool",type:"input",accept:(e,t)=>{if("boolean"!=typeof e)return null;let r=parseParams(t,{options:i.optional.custom(parseListOptions)});return r?{initialValue:e,params:r}:null},binding:{reader:e=>boolFromUnknown,constraint:e=>createConstraint$6(e.params),writer:e=>writePrimitive},controller:e=>{let t=e.document,r=e.value,i=e.constraint,n=i&&findConstraint(i,ListConstraint);return n?new ListController(t,{props:new ValueMap({options:n.values.value("options")}),value:r,viewProps:e.viewProps}):new CheckboxController(t,{value:r,viewProps:e.viewProps})}},A=ClassName("col");let ColorView=class ColorView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(A()),t.foldable.bindExpandedClass(this.element,A(void 0,"expanded")),bindValueMap(t.foldable,"completed",valueToClassName(this.element,A(void 0,"cpl")));let r=e.createElement("div");r.classList.add(A("h")),this.element.appendChild(r);let i=e.createElement("div");i.classList.add(A("s")),r.appendChild(i),this.swatchElement=i;let n=e.createElement("div");if(n.classList.add(A("t")),r.appendChild(n),this.textElement=n,"inline"===t.pickerLayout){let t=e.createElement("div");t.classList.add(A("p")),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}};function rgbToHslInt(e,t,r){let i=constrainRange(e/255,0,1),n=constrainRange(t/255,0,1),o=constrainRange(r/255,0,1),a=Math.max(i,n,o),l=Math.min(i,n,o),s=a-l,p=0,d=0;return 0!==s&&(d=s/(1-Math.abs(a+l-1)),p=(p=i===a?(n-o)/s:n===a?2+(o-i)/s:4+(i-n)/s)/6+(p<0?1:0)),[360*p,100*d,100*((l+a)/2)]}function hslToRgbInt(e,t,r){let i,n,o;let a=(e%360+360)%360,l=constrainRange(t/100,0,1),s=constrainRange(r/100,0,1),p=(1-Math.abs(2*s-1))*l,d=p*(1-Math.abs(a/60%2-1)),u=s-p/2;return a>=0&&a<60?[i,n,o]=[p,d,0]:a>=60&&a<120?[i,n,o]=[d,p,0]:a>=120&&a<180?[i,n,o]=[0,p,d]:a>=180&&a<240?[i,n,o]=[0,d,p]:a>=240&&a<300?[i,n,o]=[d,0,p]:[i,n,o]=[p,0,d],[(i+u)*255,(n+u)*255,(o+u)*255]}function rgbToHsvInt(e,t,r){let i=constrainRange(e/255,0,1),n=constrainRange(t/255,0,1),o=constrainRange(r/255,0,1),a=Math.max(i,n,o),l=a-Math.min(i,n,o);return[0===l?0:a===i?60*(((n-o)/l%6+6)%6):a===n?60*((o-i)/l+2):60*((i-n)/l+4),100*(0===a?0:l/a),100*a]}function hsvToRgbInt(e,t,r){let i,n,o;let a=(e%360+360)%360,l=constrainRange(t/100,0,1),s=constrainRange(r/100,0,1),p=s*l,d=p*(1-Math.abs(a/60%2-1)),u=s-p;return a>=0&&a<60?[i,n,o]=[p,d,0]:a>=60&&a<120?[i,n,o]=[d,p,0]:a>=120&&a<180?[i,n,o]=[0,p,d]:a>=180&&a<240?[i,n,o]=[0,d,p]:a>=240&&a<300?[i,n,o]=[d,0,p]:[i,n,o]=[p,0,d],[(i+u)*255,(n+u)*255,(o+u)*255]}function hslToHsvInt(e,t,r){let i=r+t*(100-Math.abs(2*r-100))/200;return[e,0!==i?t*(100-Math.abs(2*r-100))/i:0,r+t*(100-Math.abs(2*r-100))/200]}function hsvToHslInt(e,t,r){let i=100-Math.abs(r*(200-t)/100-100);return[e,0!==i?t*r/i:0,r*(200-t)/200]}function removeAlphaComponent(e){return[e[0],e[1],e[2]]}function appendAlphaComponent(e,t){return[e[0],e[1],e[2],t]}let B={hsl:{hsl:(e,t,r)=>[e,t,r],hsv:hslToHsvInt,rgb:hslToRgbInt},hsv:{hsl:hsvToHslInt,hsv:(e,t,r)=>[e,t,r],rgb:hsvToRgbInt},rgb:{hsl:rgbToHslInt,hsv:rgbToHsvInt,rgb:(e,t,r)=>[e,t,r]}};function getColorMaxComponents(e,t){return["float"===t?1:"rgb"===e?255:360,"float"===t?1:"rgb"===e?255:100,"float"===t?1:"rgb"===e?255:100]}function loopHueRange(e,t){return e===t?t:(e%t+t)%t}function constrainColorComponents(e,t,r){var i;let n=getColorMaxComponents(t,r);return["rgb"===t?constrainRange(e[0],0,n[0]):loopHueRange(e[0],n[0]),constrainRange(e[1],0,n[1]),constrainRange(e[2],0,n[2]),constrainRange(null!==(i=e[3])&&void 0!==i?i:1,0,1)]}function convertColorType(e,t,r,i){let n=getColorMaxComponents(t,r),o=getColorMaxComponents(t,i);return e.map((e,t)=>e/n[t]*o[t])}function convertColor(e,t,r){let i=convertColorType(e,t.mode,t.type,"int"),n=B[t.mode][r.mode](...i);return convertColorType(n,r.mode,"int",r.type)}function isRgbColorComponent(e,t){return!("object"!=typeof e||isEmpty(e))&&t in e&&"number"==typeof e[t]}let Color=class Color{static black(e="int"){return new Color([0,0,0],"rgb",e)}static fromObject(e,t="int"){let r="a"in e?[e.r,e.g,e.b,e.a]:[e.r,e.g,e.b];return new Color(r,"rgb",t)}static toRgbaObject(e,t="int"){return e.toRgbaObject(t)}static isRgbColorObject(e){return isRgbColorComponent(e,"r")&&isRgbColorComponent(e,"g")&&isRgbColorComponent(e,"b")}static isRgbaColorObject(e){return this.isRgbColorObject(e)&&isRgbColorComponent(e,"a")}static isColorObject(e){return this.isRgbColorObject(e)}static equals(e,t){if(e.mode!==t.mode)return!1;let r=e.comps_,i=t.comps_;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1;return!0}constructor(e,t,r="int"){this.mode=t,this.type=r,this.comps_=constrainColorComponents(e,t,r)}getComponents(e,t="int"){return appendAlphaComponent(convertColor(removeAlphaComponent(this.comps_),{mode:this.mode,type:this.type},{mode:null!=e?e:this.mode,type:t}),this.comps_[3])}toRgbaObject(e="int"){let t=this.getComponents("rgb",e);return{r:t[0],g:t[1],b:t[2],a:t[3]}}};let D=ClassName("colp");let ColorPickerView=class ColorPickerView{constructor(e,t){this.alphaViews_=null,this.element=e.createElement("div"),this.element.classList.add(D()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add(D("hsv"));let i=e.createElement("div");i.classList.add(D("sv")),this.svPaletteView_=t.svPaletteView,i.appendChild(this.svPaletteView_.element),r.appendChild(i);let n=e.createElement("div");n.classList.add(D("h")),this.hPaletteView_=t.hPaletteView,n.appendChild(this.hPaletteView_.element),r.appendChild(n),this.element.appendChild(r);let o=e.createElement("div");if(o.classList.add(D("rgb")),this.textView_=t.textView,o.appendChild(this.textView_.element),this.element.appendChild(o),t.alphaViews){this.alphaViews_={palette:t.alphaViews.palette,text:t.alphaViews.text};let r=e.createElement("div");r.classList.add(D("a"));let i=e.createElement("div");i.classList.add(D("ap")),i.appendChild(this.alphaViews_.palette.element),r.appendChild(i);let n=e.createElement("div");n.classList.add(D("at")),n.appendChild(this.alphaViews_.text.element),r.appendChild(n),this.element.appendChild(r)}}get allFocusableElements(){let e=[this.svPaletteView_.element,this.hPaletteView_.element,this.textView_.modeSelectElement,...this.textView_.textViews.map(e=>e.inputElement)];return this.alphaViews_&&e.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),e}};function parseColorType(e){return"int"===e?"int":"float"===e?"float":void 0}function parseColorInputParams(e){return parseParams(e,{alpha:i.optional.boolean,color:i.optional.object({alpha:i.optional.boolean,type:i.optional.custom(parseColorType)}),expanded:i.optional.boolean,picker:i.optional.custom(parsePickerLayout)})}function getBaseStepForColor(e){return e?.1:1}function extractColorType(e){var t;return null===(t=e.color)||void 0===t?void 0:t.type}function equalsStringColorFormat(e,t){return e.alpha===t.alpha&&e.mode===t.mode&&e.notation===t.notation&&e.type===t.type}function parseCssNumberOrPercentage(e,t){let r=e.match(/^(.+)%$/);return r?Math.min(.01*parseFloat(r[1])*t,t):Math.min(parseFloat(e),t)}let N={deg:e=>e,grad:e=>360*e/400,rad:e=>360*e/(2*Math.PI),turn:e=>360*e};function parseCssNumberOrAngle(e){let t=e.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!t)return parseFloat(e);let r=parseFloat(t[1]),i=t[2];return N[i](r)}function parseFunctionalRgbColorComponents(e){let t=e.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let r=[parseCssNumberOrPercentage(t[1],255),parseCssNumberOrPercentage(t[2],255),parseCssNumberOrPercentage(t[3],255)];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])?null:r}function createFunctionalRgbColorParser(e){return t=>{let r=parseFunctionalRgbColorComponents(t);return r?new Color(r,"rgb",e):null}}function parseFunctionalRgbaColorComponents(e){let t=e.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let r=[parseCssNumberOrPercentage(t[1],255),parseCssNumberOrPercentage(t[2],255),parseCssNumberOrPercentage(t[3],255),parseCssNumberOrPercentage(t[4],1)];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])||isNaN(r[3])?null:r}function createFunctionalRgbaColorParser(e){return t=>{let r=parseFunctionalRgbaColorComponents(t);return r?new Color(r,"rgb",e):null}}function parseHslColorComponents(e){let t=e.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let r=[parseCssNumberOrAngle(t[1]),parseCssNumberOrPercentage(t[2],100),parseCssNumberOrPercentage(t[3],100)];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])?null:r}function createHslColorParser(e){return t=>{let r=parseHslColorComponents(t);return r?new Color(r,"hsl",e):null}}function parseHslaColorComponents(e){let t=e.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let r=[parseCssNumberOrAngle(t[1]),parseCssNumberOrPercentage(t[2],100),parseCssNumberOrPercentage(t[3],100),parseCssNumberOrPercentage(t[4],1)];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])||isNaN(r[3])?null:r}function createHslaColorParser(e){return t=>{let r=parseHslaColorComponents(t);return r?new Color(r,"hsl",e):null}}function parseHexRgbColorComponents(e){let t=e.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)];let r=e.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return r?[parseInt(r[1],16),parseInt(r[2],16),parseInt(r[3],16)]:null}function parseHexRgbColor(e){let t=parseHexRgbColorComponents(e);return t?new Color(t,"rgb","int"):null}function parseHexRgbaColorComponents(e){let t=e.match(/^#?([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16),mapRange(parseInt(t[4]+t[4],16),0,255,0,1)];let r=e.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return r?[parseInt(r[1],16),parseInt(r[2],16),parseInt(r[3],16),mapRange(parseInt(r[4],16),0,255,0,1)]:null}function parseHexRgbaColor(e){let t=parseHexRgbaColorComponents(e);return t?new Color(t,"rgb","int"):null}function parseObjectRgbColorComponents(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let r=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])?null:r}function createObjectRgbColorParser(e){return t=>{let r=parseObjectRgbColorComponents(t);return r?new Color(r,"rgb",e):null}}function parseObjectRgbaColorComponents(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let r=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),parseFloat(t[4])];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])||isNaN(r[3])?null:r}function createObjectRgbaColorParser(e){return t=>{let r=parseObjectRgbaColorComponents(t);return r?new Color(r,"rgb",e):null}}let F=[{parser:parseHexRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:parseHexRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:parseFunctionalRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:parseFunctionalRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:parseHslColorComponents,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:parseHslaColorComponents,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:parseObjectRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:parseObjectRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"object"}}];function detectStringColor(e){return F.reduce((t,{parser:r,result:i})=>t||(r(e)?i:null),null)}function detectStringColorFormat(e,t="int"){let r=detectStringColor(e);return r?"hex"===r.notation&&"float"!==t?Object.assign(Object.assign({},r),{type:"int"}):"func"===r.notation?Object.assign(Object.assign({},r),{type:t}):null:null}let O={int:[parseHexRgbColor,parseHexRgbaColor,createFunctionalRgbColorParser("int"),createFunctionalRgbaColorParser("int"),createHslColorParser("int"),createHslaColorParser("int"),createObjectRgbColorParser("int"),createObjectRgbaColorParser("int")],float:[createFunctionalRgbColorParser("float"),createFunctionalRgbaColorParser("float"),createHslColorParser("float"),createHslaColorParser("float"),createObjectRgbColorParser("float"),createObjectRgbaColorParser("float")]};function createColorStringBindingReader(e){let t=O[e];return r=>{if("string"!=typeof r)return Color.black(e);let i=t.reduce((e,t)=>e||t(r),null);return null!=i?i:Color.black(e)}}function createColorStringParser(e){let t=O[e];return e=>t.reduce((t,r)=>t||r(e),null)}function zerofill(e){let t=constrainRange(Math.floor(e),0,255).toString(16);return 1===t.length?`0${t}`:t}function colorToHexRgbString(e,t="#"){let r=removeAlphaComponent(e.getComponents("rgb")).map(zerofill).join("");return`${t}${r}`}function colorToHexRgbaString(e,t="#"){let r=e.getComponents("rgb"),i=[r[0],r[1],r[2],255*r[3]].map(zerofill).join("");return`${t}${i}`}function colorToFunctionalRgbString(e,t){let r=createNumberFormatter("float"===t?2:0),i=removeAlphaComponent(e.getComponents("rgb",t)).map(e=>r(e));return`rgb(${i.join(", ")})`}function createFunctionalRgbColorFormatter(e){return t=>colorToFunctionalRgbString(t,e)}function colorToFunctionalRgbaString(e,t){let r=createNumberFormatter(2),i=createNumberFormatter("float"===t?2:0),n=e.getComponents("rgb",t).map((e,t)=>(3===t?r:i)(e));return`rgba(${n.join(", ")})`}function createFunctionalRgbaColorFormatter(e){return t=>colorToFunctionalRgbaString(t,e)}function colorToFunctionalHslString(e){let t=[createNumberFormatter(0),formatPercentage,formatPercentage],r=removeAlphaComponent(e.getComponents("hsl")).map((e,r)=>t[r](e));return`hsl(${r.join(", ")})`}function colorToFunctionalHslaString(e){let t=[createNumberFormatter(0),formatPercentage,formatPercentage,createNumberFormatter(2)],r=e.getComponents("hsl").map((e,r)=>t[r](e));return`hsla(${r.join(", ")})`}function colorToObjectRgbString(e,t){let r=createNumberFormatter("float"===t?2:0),i=["r","g","b"],n=removeAlphaComponent(e.getComponents("rgb",t)).map((e,t)=>`${i[t]}: ${r(e)}`);return`{${n.join(", ")}}`}function createObjectRgbColorFormatter(e){return t=>colorToObjectRgbString(t,e)}function colorToObjectRgbaString(e,t){let r=createNumberFormatter(2),i=createNumberFormatter("float"===t?2:0),n=["r","g","b","a"],o=e.getComponents("rgb",t).map((e,t)=>`${n[t]}: ${(3===t?r:i)(e)}`);return`{${o.join(", ")}}`}function createObjectRgbaColorFormatter(e){return t=>colorToObjectRgbaString(t,e)}let I=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:colorToHexRgbString},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:colorToHexRgbaString},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:colorToFunctionalHslString},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:colorToFunctionalHslaString},...["int","float"].reduce((e,t)=>[...e,{format:{alpha:!1,mode:"rgb",notation:"func",type:t},stringifier:createFunctionalRgbColorFormatter(t)},{format:{alpha:!0,mode:"rgb",notation:"func",type:t},stringifier:createFunctionalRgbaColorFormatter(t)},{format:{alpha:!1,mode:"rgb",notation:"object",type:t},stringifier:createObjectRgbColorFormatter(t)},{format:{alpha:!0,mode:"rgb",notation:"object",type:t},stringifier:createObjectRgbaColorFormatter(t)}],[])];function findColorStringifier(e){return I.reduce((t,r)=>t||(equalsStringColorFormat(r.format,e)?r.stringifier:null),null)}let j=ClassName("apl");let APaletteView=class APaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(j()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let r=e.createElement("div");r.classList.add(j("b")),this.element.appendChild(r);let i=e.createElement("div");i.classList.add(j("c")),r.appendChild(i),this.colorElem_=i;let n=e.createElement("div");n.classList.add(j("m")),this.element.appendChild(n),this.markerElem_=n;let o=e.createElement("div");o.classList.add(j("p")),this.markerElem_.appendChild(o),this.previewElem_=o,this.update_()}update_(){let e=this.value.rawValue,t=e.getComponents("rgb"),r=new Color([t[0],t[1],t[2],0],"rgb"),i=new Color([t[0],t[1],t[2],255],"rgb"),n=["to right",colorToFunctionalRgbaString(r),colorToFunctionalRgbaString(i)];this.colorElem_.style.background=`linear-gradient(${n.join(",")})`,this.previewElem_.style.backgroundColor=colorToFunctionalRgbaString(e);let o=mapRange(t[3],0,1,0,100);this.markerElem_.style.left=`${o}%`}onValueChange_(){this.update_()}};let APaletteController=class APaletteController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new APaletteView(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let r=e.point.x/e.bounds.width,i=this.value.rawValue,[n,o,a]=i.getComponents("hsv");this.value.setRawValue(new Color([n,o,a,r],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(getBaseStepForColor(!0),getHorizontalStepKeys(e));if(0===t)return;let r=this.value.rawValue,[i,n,o,a]=r.getComponents("hsv");this.value.setRawValue(new Color([i,n,o,a+t],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(getBaseStepForColor(!0),getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let K=ClassName("coltxt");function createModeSelectElement(e){let t=e.createElement("select");return t.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"}].reduce((t,r)=>{let i=e.createElement("option");return i.textContent=r.text,i.value=r.value,t.appendChild(i),t},e.createDocumentFragment())),t}let ColorTextView=class ColorTextView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(K()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add(K("m")),this.modeElem_=createModeSelectElement(e),this.modeElem_.classList.add(K("ms")),r.appendChild(this.modeSelectElement),t.viewProps.bindDisabled(this.modeElem_);let i=e.createElement("div");i.classList.add(K("mm")),i.appendChild(createSvgIconElement(e,"dropdown")),r.appendChild(i),this.element.appendChild(r);let n=e.createElement("div");n.classList.add(K("w")),this.element.appendChild(n),this.textsElem_=n,this.textViews_=t.textViews,this.applyTextViews_(),bindValue(t.colorMode,e=>{this.modeElem_.value=e})}get modeSelectElement(){return this.modeElem_}get textViews(){return this.textViews_}set textViews(e){this.textViews_=e,this.applyTextViews_()}applyTextViews_(){removeChildElements(this.textsElem_);let e=this.element.ownerDocument;this.textViews_.forEach(t=>{let r=e.createElement("div");r.classList.add(K("c")),r.appendChild(t.element),this.textsElem_.appendChild(r)})}};function createFormatter$2(e){return createNumberFormatter("float"===e?2:0)}function createConstraint$5(e,t,r){let i=getColorMaxComponents(e,t)[r];return new DefiniteRangeConstraint({min:0,max:i})}function createComponentController(e,t,r){return new NumberTextController(e,{arrayPosition:0===r?"fst":2===r?"lst":"mid",baseStep:getBaseStepForColor(!1),parser:t.parser,props:ValueMap.fromObject({draggingScale:"float"===t.colorType?.01:1,formatter:createFormatter$2(t.colorType)}),value:createValue(0,{constraint:createConstraint$5(t.colorMode,t.colorType,r)}),viewProps:t.viewProps})}let ColorTextController=class ColorTextController{constructor(e,t){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=t.colorType,this.parser_=t.parser,this.value=t.value,this.viewProps=t.viewProps,this.colorMode=createValue(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(e),this.view=new ColorTextView(e,{colorMode:this.colorMode,textViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(e){let t={colorMode:this.colorMode.rawValue,colorType:this.colorType_,parser:this.parser_,viewProps:this.viewProps},r=[createComponentController(e,t,0),createComponentController(e,t,1),createComponentController(e,t,2)];return r.forEach((e,t)=>{connectValues({primary:this.value,secondary:e.value,forward:e=>e.rawValue.getComponents(this.colorMode.rawValue,this.colorType_)[t],backward:(e,r)=>{let i=this.colorMode.rawValue,n=e.rawValue.getComponents(i,this.colorType_);return n[t]=r.rawValue,new Color(appendAlphaComponent(removeAlphaComponent(n),n[3]),i,this.colorType_)}})}),r}onModeSelectChange_(e){let t=e.currentTarget;this.colorMode.rawValue=t.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.textViews=[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view]}};let H=ClassName("hpl");let HPaletteView=class HPaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(H()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let r=e.createElement("div");r.classList.add(H("c")),this.element.appendChild(r);let i=e.createElement("div");i.classList.add(H("m")),this.element.appendChild(i),this.markerElem_=i,this.update_()}update_(){let e=this.value.rawValue,[t]=e.getComponents("hsv");this.markerElem_.style.backgroundColor=colorToFunctionalRgbString(new Color([t,100,100],"hsv"));let r=mapRange(t,0,360,0,100);this.markerElem_.style.left=`${r}%`}onValueChange_(){this.update_()}};let HPaletteController=class HPaletteController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new HPaletteView(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let r=mapRange(constrainRange(e.point.x,0,e.bounds.width),0,e.bounds.width,0,360),i=this.value.rawValue,[,n,o,a]=i.getComponents("hsv");this.value.setRawValue(new Color([r,n,o,a],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(getBaseStepForColor(!1),getHorizontalStepKeys(e));if(0===t)return;let r=this.value.rawValue,[i,n,o,a]=r.getComponents("hsv");this.value.setRawValue(new Color([i+t,n,o,a],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(getBaseStepForColor(!1),getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let U=ClassName("svp");let SvPaletteView=class SvPaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(U()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let r=e.createElement("canvas");r.height=64,r.width=64,r.classList.add(U("c")),this.element.appendChild(r),this.canvasElement=r;let i=e.createElement("div");i.classList.add(U("m")),this.element.appendChild(i),this.markerElem_=i,this.update_()}update_(){let e=getCanvasContext(this.canvasElement);if(!e)return;let t=this.value.rawValue,r=t.getComponents("hsv"),i=this.canvasElement.width,n=this.canvasElement.height,o=e.getImageData(0,0,i,n),a=o.data;for(let e=0;e<n;e++)for(let t=0;t<i;t++){let o=mapRange(t,0,i,0,100),l=mapRange(e,0,n,100,0),s=hsvToRgbInt(r[0],o,l),p=(e*i+t)*4;a[p]=s[0],a[p+1]=s[1],a[p+2]=s[2],a[p+3]=255}e.putImageData(o,0,0);let l=mapRange(r[1],0,100,0,100);this.markerElem_.style.left=`${l}%`;let s=mapRange(r[2],0,100,100,0);this.markerElem_.style.top=`${s}%`}onValueChange_(){this.update_()}};let SvPaletteController=class SvPaletteController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new SvPaletteView(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let r=mapRange(e.point.x,0,e.bounds.width,0,100),i=mapRange(e.point.y,0,e.bounds.height,100,0),[n,,,o]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new Color([n,r,i,o],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){isArrowKey(e.key)&&e.preventDefault();let[t,r,i,n]=this.value.rawValue.getComponents("hsv"),o=getBaseStepForColor(!1),a=getStepForKey(o,getHorizontalStepKeys(e)),l=getStepForKey(o,getVerticalStepKeys(e));(0!==a||0!==l)&&this.value.setRawValue(new Color([t,r+a,i+l,n],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getBaseStepForColor(!1),r=getStepForKey(t,getHorizontalStepKeys(e)),i=getStepForKey(t,getVerticalStepKeys(e));(0!==r||0!==i)&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let ColorPickerController=class ColorPickerController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.hPaletteC_=new HPaletteController(e,{value:this.value,viewProps:this.viewProps}),this.svPaletteC_=new SvPaletteController(e,{value:this.value,viewProps:this.viewProps}),this.alphaIcs_=t.supportsAlpha?{palette:new APaletteController(e,{value:this.value,viewProps:this.viewProps}),text:new NumberTextController(e,{parser:parseNumber,baseStep:.1,props:ValueMap.fromObject({draggingScale:.01,formatter:createNumberFormatter(2)}),value:createValue(0,{constraint:new DefiniteRangeConstraint({min:0,max:1})}),viewProps:this.viewProps})}:null,this.alphaIcs_&&connectValues({primary:this.value,secondary:this.alphaIcs_.text.value,forward:e=>e.rawValue.getComponents()[3],backward:(e,t)=>{let r=e.rawValue.getComponents();return r[3]=t.rawValue,new Color(r,e.rawValue.mode)}}),this.textC_=new ColorTextController(e,{colorType:t.colorType,parser:parseNumber,value:this.value,viewProps:this.viewProps}),this.view=new ColorPickerView(e,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:t.supportsAlpha,svPaletteView:this.svPaletteC_.view,textView:this.textC_.view,viewProps:this.viewProps})}get textController(){return this.textC_}};let $=ClassName("colsw");let ColorSwatchView=class ColorSwatchView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.element=e.createElement("div"),this.element.classList.add($()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add($("sw")),this.element.appendChild(r),this.swatchElem_=r;let i=e.createElement("button");i.classList.add($("b")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i,this.update_()}update_(){let e=this.value.rawValue;this.swatchElem_.style.backgroundColor=colorToHexRgbaString(e)}onValueChange_(){this.update_()}};let ColorSwatchController=class ColorSwatchController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new ColorSwatchView(e,{value:this.value,viewProps:this.viewProps})}};let ColorController=class ColorController{constructor(e,t){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=Foldable.create(t.expanded),this.swatchC_=new ColorSwatchController(e,{value:this.value,viewProps:this.viewProps});let r=this.swatchC_.view.buttonElement;r.addEventListener("blur",this.onButtonBlur_),r.addEventListener("click",this.onButtonClick_),this.textC_=new TextController(e,{parser:t.parser,props:ValueMap.fromObject({formatter:t.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new ColorView(e,{foldable:this.foldable_,pickerLayout:t.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===t.pickerLayout?new PopupController(e,{viewProps:this.viewProps}):null;let i=new ColorPickerController(e,{colorType:t.colorType,supportsAlpha:t.supportsAlpha,value:this.value,viewProps:this.viewProps});i.view.allFocusableElements.forEach(e=>{e.addEventListener("blur",this.onPopupChildBlur_),e.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=i,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(i.view.element),connectValues({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:e=>e.rawValue,backward:(e,t)=>t.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),bindFoldable(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,r=e.relatedTarget;r&&t.contains(r)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,r=findNextTarget(e);!(r&&t.contains(r))&&(!r||r!==this.swatchC_.view.buttonElement||supportsTouch(t.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?"Escape"===e.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===e.key&&this.swatchC_.view.buttonElement.focus()}};function colorFromObject(e,t){return Color.isColorObject(e)?Color.fromObject(e,t):Color.black(t)}function colorToRgbNumber(e){return removeAlphaComponent(e.getComponents("rgb")).reduce((e,t)=>e<<8|255&Math.floor(t),0)}function colorToRgbaNumber(e){return e.getComponents("rgb").reduce((e,t,r)=>e<<8|255&Math.floor(3===r?255*t:t),0)>>>0}function numberToRgbColor(e){return new Color([e>>16&255,e>>8&255,255&e],"rgb")}function numberToRgbaColor(e){return new Color([e>>24&255,e>>16&255,e>>8&255,mapRange(255&e,0,255,0,1)],"rgb")}function colorFromRgbNumber(e){return"number"!=typeof e?Color.black():numberToRgbColor(e)}function colorFromRgbaNumber(e){return"number"!=typeof e?Color.black():numberToRgbaColor(e)}function createColorStringWriter(e){let t=findColorStringifier(e);return t?(e,r)=>{writePrimitive(e,t(r))}:null}function createColorNumberWriter(e){let t=e?colorToRgbaNumber:colorToRgbNumber;return(e,r)=>{writePrimitive(e,t(r))}}function writeRgbaColorObject(e,t,r){let i=t.toRgbaObject(r);e.writeProperty("r",i.r),e.writeProperty("g",i.g),e.writeProperty("b",i.b),e.writeProperty("a",i.a)}function writeRgbColorObject(e,t,r){let i=t.toRgbaObject(r);e.writeProperty("r",i.r),e.writeProperty("g",i.g),e.writeProperty("b",i.b)}function createColorObjectWriter(e,t){return(r,i)=>{e?writeRgbaColorObject(r,i,t):writeRgbColorObject(r,i,t)}}function shouldSupportAlpha$1(e){var t;return null!=e&&!!e.alpha||null!==(t=null==e?void 0:e.color)&&void 0!==t&&!!t.alpha}function createFormatter$1(e){return e?e=>colorToHexRgbaString(e,"0x"):e=>colorToHexRgbString(e,"0x")}function isForColor(e){return"color"in e||"view"in e&&"color"===e.view}let z={id:"input-color-number",type:"input",accept:(e,t)=>{if("number"!=typeof e||!isForColor(t))return null;let r=parseColorInputParams(t);return r?{initialValue:e,params:r}:null},binding:{reader:e=>shouldSupportAlpha$1(e.params)?colorFromRgbaNumber:colorFromRgbNumber,equals:Color.equals,writer:e=>createColorNumberWriter(shouldSupportAlpha$1(e.params))},controller:e=>{let t=shouldSupportAlpha$1(e.params),r="expanded"in e.params?e.params.expanded:void 0,i="picker"in e.params?e.params.picker:void 0;return new ColorController(e.document,{colorType:"int",expanded:null!=r&&r,formatter:createFormatter$1(t),parser:createColorStringParser("int"),pickerLayout:null!=i?i:"popup",supportsAlpha:t,value:e.value,viewProps:e.viewProps})}};function shouldSupportAlpha(e){return Color.isRgbaColorObject(e)}function createColorObjectReader(e){return t=>colorFromObject(t,e)}function createColorObjectFormatter(e,t){return r=>e?colorToObjectRgbaString(r,t):colorToObjectRgbString(r,t)}let q={id:"input-color-object",type:"input",accept:(e,t)=>{if(!Color.isColorObject(e))return null;let r=parseColorInputParams(t);return r?{initialValue:e,params:r}:null},binding:{reader:e=>createColorObjectReader(extractColorType(e.params)),equals:Color.equals,writer:e=>createColorObjectWriter(shouldSupportAlpha(e.initialValue),extractColorType(e.params))},controller:e=>{var t;let r=Color.isRgbaColorObject(e.initialValue),i="expanded"in e.params?e.params.expanded:void 0,n="picker"in e.params?e.params.picker:void 0,o=null!==(t=extractColorType(e.params))&&void 0!==t?t:"int";return new ColorController(e.document,{colorType:o,expanded:null!=i&&i,formatter:createColorObjectFormatter(r,o),parser:createColorStringParser(o),pickerLayout:null!=n?n:"popup",supportsAlpha:r,value:e.value,viewProps:e.viewProps})}},G={id:"input-color-string",type:"input",accept:(e,t)=>{if("string"!=typeof e||"view"in t&&"text"===t.view)return null;let r=detectStringColorFormat(e,extractColorType(t));if(!r)return null;let i=findColorStringifier(r);if(!i)return null;let n=parseColorInputParams(t);return n?{initialValue:e,params:n}:null},binding:{reader:e=>{var t;return createColorStringBindingReader(null!==(t=extractColorType(e.params))&&void 0!==t?t:"int")},equals:Color.equals,writer:e=>{let t=detectStringColorFormat(e.initialValue,extractColorType(e.params));if(!t)throw TpError.shouldNeverHappen();let r=createColorStringWriter(t);if(!r)throw TpError.notBindable();return r}},controller:e=>{let t=detectStringColorFormat(e.initialValue,extractColorType(e.params));if(!t)throw TpError.shouldNeverHappen();let r=findColorStringifier(t);if(!r)throw TpError.shouldNeverHappen();let i="expanded"in e.params?e.params.expanded:void 0,n="picker"in e.params?e.params.picker:void 0;return new ColorController(e.document,{colorType:t.type,expanded:null!=i&&i,formatter:r,parser:createColorStringParser(t.type),pickerLayout:null!=n?n:"popup",supportsAlpha:t.alpha,value:e.value,viewProps:e.viewProps})}};let PointNdConstraint=class PointNdConstraint{constructor(e){this.components=e.components,this.asm_=e.assembly}constrain(e){let t=this.asm_.toComponents(e).map((e,t)=>{var r,i;return null!==(i=null===(r=this.components[t])||void 0===r?void 0:r.constrain(e))&&void 0!==i?i:e});return this.asm_.fromComponents(t)}};let Y=ClassName("pndtxt");let PointNdTextView=class PointNdTextView{constructor(e,t){this.textViews=t.textViews,this.element=e.createElement("div"),this.element.classList.add(Y()),this.textViews.forEach(t=>{let r=e.createElement("div");r.classList.add(Y("a")),r.appendChild(t.element),this.element.appendChild(r)})}};function createAxisController(e,t,r){return new NumberTextController(e,{arrayPosition:0===r?"fst":r===t.axes.length-1?"lst":"mid",baseStep:t.axes[r].baseStep,parser:t.parser,props:t.axes[r].textProps,value:createValue(0,{constraint:t.axes[r].constraint}),viewProps:t.viewProps})}let PointNdTextController=class PointNdTextController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.acs_=t.axes.map((r,i)=>createAxisController(e,t,i)),this.acs_.forEach((e,r)=>{connectValues({primary:this.value,secondary:e.value,forward:e=>t.assembly.toComponents(e.rawValue)[r],backward:(e,i)=>{let n=t.assembly.toComponents(e.rawValue);return n[r]=i.rawValue,t.assembly.fromComponents(n)}})}),this.view=new PointNdTextView(e,{textViews:this.acs_.map(e=>e.view)})}};function createStepConstraint(e,t){return"step"in e&&!isEmpty(e.step)?new StepConstraint(e.step,t):null}function createRangeConstraint(e){return isEmpty(e.max)||isEmpty(e.min)?isEmpty(e.max)&&isEmpty(e.min)?null:new RangeConstraint({max:e.max,min:e.min}):new DefiniteRangeConstraint({max:e.max,min:e.min})}function findNumberRange(e){let t=findConstraint(e,DefiniteRangeConstraint);if(t)return[t.values.get("min"),t.values.get("max")];let r=findConstraint(e,RangeConstraint);return r?[r.minValue,r.maxValue]:[void 0,void 0]}function createConstraint$4(e,t){let r=[],i=createStepConstraint(e,t);i&&r.push(i);let n=createRangeConstraint(e);n&&r.push(n);let o=createListConstraint(e.options);return o&&r.push(o),new CompositeConstraint(r)}let W={id:"input-number",type:"input",accept:(e,t)=>{if("number"!=typeof e)return null;let r=parseParams(t,{format:i.optional.function,max:i.optional.number,min:i.optional.number,options:i.optional.custom(parseListOptions),step:i.optional.number});return r?{initialValue:e,params:r}:null},binding:{reader:e=>numberFromUnknown,constraint:e=>createConstraint$4(e.params,e.initialValue),writer:e=>writePrimitive},controller:e=>{var t;let r=e.value,i=e.constraint,n=i&&findConstraint(i,ListConstraint);if(n)return new ListController(e.document,{props:new ValueMap({options:n.values.value("options")}),value:r,viewProps:e.viewProps});let o=null!==(t="format"in e.params?e.params.format:void 0)&&void 0!==t?t:createNumberFormatter(getSuitableDecimalDigits(i,r.rawValue)),a=i&&findConstraint(i,DefiniteRangeConstraint);return a?new SliderTextController(e.document,{baseStep:getBaseStep(i),parser:parseNumber,sliderProps:new ValueMap({maxValue:a.values.value("max"),minValue:a.values.value("min")}),textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(i,r.rawValue),formatter:o}),value:r,viewProps:e.viewProps}):new NumberTextController(e.document,{baseStep:getBaseStep(i),parser:parseNumber,props:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(i,r.rawValue),formatter:o}),value:r,viewProps:e.viewProps})}};let Point2d=class Point2d{constructor(e=0,t=0){this.x=e,this.y=t}getComponents(){return[this.x,this.y]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,r=e.y;return"number"==typeof t&&"number"==typeof r}static equals(e,t){return e.x===t.x&&e.y===t.y}toObject(){return{x:this.x,y:this.y}}};let X={toComponents:e=>e.getComponents(),fromComponents:e=>new Point2d(...e)},J=ClassName("p2d");let Point2dView=class Point2dView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(J()),t.viewProps.bindClassModifiers(this.element),bindValue(t.expanded,valueToClassName(this.element,J(void 0,"expanded")));let r=e.createElement("div");r.classList.add(J("h")),this.element.appendChild(r);let i=e.createElement("button");i.classList.add(J("b")),i.appendChild(createSvgIconElement(e,"p2dpad")),t.viewProps.bindDisabled(i),r.appendChild(i),this.buttonElement=i;let n=e.createElement("div");if(n.classList.add(J("t")),r.appendChild(n),this.textElement=n,"inline"===t.pickerLayout){let t=e.createElement("div");t.classList.add(J("p")),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}};let Q=ClassName("p2dp");let Point2dPickerView=class Point2dPickerView{constructor(e,t){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.invertsY_=t.invertsY,this.maxValue_=t.maxValue,this.element=e.createElement("div"),this.element.classList.add(Q()),"popup"===t.layout&&this.element.classList.add(Q(void 0,"p")),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add(Q("p")),t.viewProps.bindTabIndex(r),this.element.appendChild(r),this.padElement=r;let i=e.createElementNS(l,"svg");i.classList.add(Q("g")),this.padElement.appendChild(i),this.svgElem_=i;let n=e.createElementNS(l,"line");n.classList.add(Q("ax")),n.setAttributeNS(null,"x1","0"),n.setAttributeNS(null,"y1","50%"),n.setAttributeNS(null,"x2","100%"),n.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(n);let o=e.createElementNS(l,"line");o.classList.add(Q("ax")),o.setAttributeNS(null,"x1","50%"),o.setAttributeNS(null,"y1","0"),o.setAttributeNS(null,"x2","50%"),o.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(o);let a=e.createElementNS(l,"line");a.classList.add(Q("l")),a.setAttributeNS(null,"x1","50%"),a.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(a),this.lineElem_=a;let s=e.createElement("div");s.classList.add(Q("m")),this.padElement.appendChild(s),this.markerElem_=s,t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){let[e,t]=this.value.rawValue.getComponents(),r=this.maxValue_,i=mapRange(e,-r,+r,0,100),n=mapRange(t,-r,+r,0,100),o=this.invertsY_?100-n:n;this.lineElem_.setAttributeNS(null,"x2",`${i}%`),this.lineElem_.setAttributeNS(null,"y2",`${o}%`),this.markerElem_.style.left=`${i}%`,this.markerElem_.style.top=`${o}%`}onValueChange_(){this.update_()}onFoldableChange_(){this.update_()}};function computeOffset(e,t,r){return[getStepForKey(t[0],getHorizontalStepKeys(e)),getStepForKey(t[1],getVerticalStepKeys(e))*(r?1:-1)]}let Point2dPickerController=class Point2dPickerController{constructor(e,t){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.baseSteps_=t.baseSteps,this.maxValue_=t.maxValue,this.invertsY_=t.invertsY,this.view=new Point2dPickerView(e,{invertsY:this.invertsY_,layout:t.layout,maxValue:this.maxValue_,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let r=this.maxValue_,i=mapRange(e.point.x,0,e.bounds.width,-r,+r),n=mapRange(this.invertsY_?e.bounds.height-e.point.y:e.point.y,0,e.bounds.height,-r,+r);this.value.setRawValue(new Point2d(i,n),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onPadKeyDown_(e){isArrowKey(e.key)&&e.preventDefault();let[t,r]=computeOffset(e,this.baseSteps_,this.invertsY_);(0!==t||0!==r)&&this.value.setRawValue(new Point2d(this.value.rawValue.x+t,this.value.rawValue.y+r),{forceEmit:!1,last:!1})}onPadKeyUp_(e){let[t,r]=computeOffset(e,this.baseSteps_,this.invertsY_);(0!==t||0!==r)&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let Point2dController=class Point2dController{constructor(e,t){var r,i;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=Foldable.create(t.expanded),this.popC_="popup"===t.pickerLayout?new PopupController(e,{viewProps:this.viewProps}):null;let n=new Point2dPickerController(e,{baseSteps:[t.axes[0].baseStep,t.axes[1].baseStep],invertsY:t.invertsY,layout:t.pickerLayout,maxValue:t.maxValue,value:this.value,viewProps:this.viewProps});n.view.allFocusableElements.forEach(e=>{e.addEventListener("blur",this.onPopupChildBlur_),e.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=n,this.textC_=new PointNdTextController(e,{assembly:X,axes:t.axes,parser:t.parser,value:this.value,viewProps:this.viewProps}),this.view=new Point2dView(e,{expanded:this.foldable_.value("expanded"),pickerLayout:t.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(r=this.view.buttonElement)||void 0===r||r.addEventListener("blur",this.onPadButtonBlur_),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),connectValues({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:e=>e.rawValue,backward:(e,t)=>t.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),bindFoldable(this.foldable_,this.view.pickerElement))}onPadButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,r=e.relatedTarget;r&&t.contains(r)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,r=findNextTarget(e);!(r&&t.contains(r))&&(!r||r!==this.view.buttonElement||supportsTouch(t.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?"Escape"===e.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===e.key&&this.view.buttonElement.focus()}};let Point3d=class Point3d{constructor(e=0,t=0,r=0){this.x=e,this.y=t,this.z=r}getComponents(){return[this.x,this.y,this.z]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,r=e.y,i=e.z;return"number"==typeof t&&"number"==typeof r&&"number"==typeof i}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}toObject(){return{x:this.x,y:this.y,z:this.z}}};let Z={toComponents:e=>e.getComponents(),fromComponents:e=>new Point3d(...e)};function point3dFromUnknown(e){return Point3d.isObject(e)?new Point3d(e.x,e.y,e.z):new Point3d}function writePoint3d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y),e.writeProperty("z",t.z)}function createConstraint$3(e,t){return new PointNdConstraint({assembly:Z,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y),createDimensionConstraint("z"in e?e.z:void 0,t.z)]})}function createAxis$2(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}let ee={id:"input-point3d",type:"input",accept:(e,t)=>{if(!Point3d.isObject(e))return null;let r=parseParams(t,{x:i.optional.custom(parsePointDimensionParams),y:i.optional.custom(parsePointDimensionParams),z:i.optional.custom(parsePointDimensionParams)});return r?{initialValue:e,params:r}:null},binding:{reader:e=>point3dFromUnknown,constraint:e=>createConstraint$3(e.params,e.initialValue),equals:Point3d.equals,writer:e=>writePoint3d},controller:e=>{let t=e.value,r=e.constraint;if(!(r instanceof PointNdConstraint))throw TpError.shouldNeverHappen();return new PointNdTextController(e.document,{assembly:Z,axes:[createAxis$2(t.rawValue.x,r.components[0]),createAxis$2(t.rawValue.y,r.components[1]),createAxis$2(t.rawValue.z,r.components[2])],parser:parseNumber,value:t,viewProps:e.viewProps})}};let Point4d=class Point4d{constructor(e=0,t=0,r=0,i=0){this.x=e,this.y=t,this.z=r,this.w=i}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,r=e.y,i=e.z,n=e.w;return"number"==typeof t&&"number"==typeof r&&"number"==typeof i&&"number"==typeof n}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}};let et={toComponents:e=>e.getComponents(),fromComponents:e=>new Point4d(...e)};function point4dFromUnknown(e){return Point4d.isObject(e)?new Point4d(e.x,e.y,e.z,e.w):new Point4d}function writePoint4d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y),e.writeProperty("z",t.z),e.writeProperty("w",t.w)}function createConstraint$2(e,t){return new PointNdConstraint({assembly:et,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y),createDimensionConstraint("z"in e?e.z:void 0,t.z),createDimensionConstraint("w"in e?e.w:void 0,t.w)]})}function createAxis$1(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}let er={id:"input-point4d",type:"input",accept:(e,t)=>{if(!Point4d.isObject(e))return null;let r=parseParams(t,{x:i.optional.custom(parsePointDimensionParams),y:i.optional.custom(parsePointDimensionParams),z:i.optional.custom(parsePointDimensionParams),w:i.optional.custom(parsePointDimensionParams)});return r?{initialValue:e,params:r}:null},binding:{reader:e=>point4dFromUnknown,constraint:e=>createConstraint$2(e.params,e.initialValue),equals:Point4d.equals,writer:e=>writePoint4d},controller:e=>{let t=e.value,r=e.constraint;if(!(r instanceof PointNdConstraint))throw TpError.shouldNeverHappen();return new PointNdTextController(e.document,{assembly:et,axes:t.rawValue.getComponents().map((e,t)=>createAxis$1(e,r.components[t])),parser:parseNumber,value:t,viewProps:e.viewProps})}};function createConstraint$1(e){let t=[],r=createListConstraint(e.options);return r&&t.push(r),new CompositeConstraint(t)}let ei={id:"input-string",type:"input",accept:(e,t)=>{if("string"!=typeof e)return null;let r=parseParams(t,{options:i.optional.custom(parseListOptions)});return r?{initialValue:e,params:r}:null},binding:{reader:e=>stringFromUnknown,constraint:e=>createConstraint$1(e.params),writer:e=>writePrimitive},controller:e=>{let t=e.document,r=e.value,i=e.constraint,n=i&&findConstraint(i,ListConstraint);return n?new ListController(t,{props:new ValueMap({options:n.values.value("options")}),value:r,viewProps:e.viewProps}):new TextController(t,{parser:e=>e,props:ValueMap.fromObject({formatter:formatString}),value:r,viewProps:e.viewProps})}},en={monitor:{defaultInterval:200,defaultLineCount:3}},eo=ClassName("mll");let MultiLogView=class MultiLogView{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement("div"),this.element.classList.add(eo()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("textarea");r.classList.add(eo("i")),r.style.height=`calc(var(--bld-us) * ${t.lineCount})`,r.readOnly=!0,t.viewProps.bindDisabled(r),this.element.appendChild(r),this.textareaElem_=r,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.textareaElem_,t=e.scrollTop===e.scrollHeight-e.clientHeight,r=[];this.value.rawValue.forEach(e=>{void 0!==e&&r.push(this.formatter_(e))}),e.textContent=r.join("\n"),t&&(e.scrollTop=e.scrollHeight)}onValueUpdate_(){this.update_()}};let MultiLogController=class MultiLogController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new MultiLogView(e,{formatter:t.formatter,lineCount:t.lineCount,value:this.value,viewProps:this.viewProps})}};let ea=ClassName("sgl");let SingleLogView=class SingleLogView{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement("div"),this.element.classList.add(ea()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("input");r.classList.add(ea("i")),r.readOnly=!0,r.type="text",t.viewProps.bindDisabled(r),this.element.appendChild(r),this.inputElement=r,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.value.rawValue,t=e[e.length-1];this.inputElement.value=void 0!==t?this.formatter_(t):""}onValueUpdate_(){this.update_()}};let SingleLogController=class SingleLogController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new SingleLogView(e,{formatter:t.formatter,value:this.value,viewProps:this.viewProps})}};let el={id:"monitor-bool",type:"monitor",accept:(e,t)=>{if("boolean"!=typeof e)return null;let r=parseParams(t,{lineCount:i.optional.number});return r?{initialValue:e,params:r}:null},binding:{reader:e=>boolFromUnknown},controller:e=>{var t;return 1===e.value.rawValue.length?new SingleLogController(e.document,{formatter:BooleanFormatter,value:e.value,viewProps:e.viewProps}):new MultiLogController(e.document,{formatter:BooleanFormatter,lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:en.monitor.defaultLineCount,value:e.value,viewProps:e.viewProps})}},es=ClassName("grl");let GraphLogView=class GraphLogView{constructor(e,t){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=e.createElement("div"),this.element.classList.add(es()),t.viewProps.bindClassModifiers(this.element),this.formatter_=t.formatter,this.props_=t.props,this.cursor_=t.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);let r=e.createElementNS(l,"svg");r.classList.add(es("g")),r.style.height=`calc(var(--bld-us) * ${t.lineCount})`,this.element.appendChild(r),this.svgElem_=r;let i=e.createElementNS(l,"polyline");this.svgElem_.appendChild(i),this.lineElem_=i;let n=e.createElement("div");n.classList.add(es("t"),ClassName("tt")()),this.element.appendChild(n),this.tooltipElem_=n,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}get graphElement(){return this.svgElem_}update_(){let e=this.svgElem_.getBoundingClientRect(),t=this.value.rawValue.length-1,r=this.props_.get("minValue"),i=this.props_.get("maxValue"),n=[];this.value.rawValue.forEach((o,a)=>{if(void 0===o)return;let l=mapRange(a,0,t,0,e.width),s=mapRange(o,r,i,e.height,0);n.push([l,s].join(","))}),this.lineElem_.setAttributeNS(null,"points",n.join(" "));let o=this.tooltipElem_,a=this.value.rawValue[this.cursor_.rawValue];if(void 0===a){o.classList.remove(es("t","a"));return}let l=mapRange(this.cursor_.rawValue,0,t,0,e.width),s=mapRange(a,r,i,e.height,0);o.style.left=`${l}px`,o.style.top=`${s}px`,o.textContent=`${this.formatter_(a)}`,o.classList.contains(es("t","a"))||(o.classList.add(es("t","a"),es("t","in")),forceReflow(o),o.classList.remove(es("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}};let GraphLogController=class GraphLogController{constructor(e,t){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props_=t.props,this.value=t.value,this.viewProps=t.viewProps,this.cursor_=createValue(-1),this.view=new GraphLogView(e,{cursor:this.cursor_,formatter:t.formatter,lineCount:t.lineCount,props:this.props_,value:this.value,viewProps:this.viewProps}),supportsTouch(e)){let e=new PointerHandler(this.view.element);e.emitter.on("down",this.onGraphPointerDown_),e.emitter.on("move",this.onGraphPointerMove_),e.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(e){let t=this.view.element.getBoundingClientRect();this.cursor_.rawValue=Math.floor(mapRange(e.offsetX,0,t.width,0,this.value.rawValue.length))}onGraphPointerDown_(e){this.onGraphPointerMove_(e)}onGraphPointerMove_(e){if(!e.data.point){this.cursor_.rawValue=-1;return}this.cursor_.rawValue=Math.floor(mapRange(e.data.point.x,0,e.data.bounds.width,0,this.value.rawValue.length))}onGraphPointerUp_(){this.cursor_.rawValue=-1}};function createFormatter(e){return"format"in e&&!isEmpty(e.format)?e.format:createNumberFormatter(2)}function createTextMonitor(e){var t;return 1===e.value.rawValue.length?new SingleLogController(e.document,{formatter:createFormatter(e.params),value:e.value,viewProps:e.viewProps}):new MultiLogController(e.document,{formatter:createFormatter(e.params),lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:en.monitor.defaultLineCount,value:e.value,viewProps:e.viewProps})}function createGraphMonitor(e){var t,r,i;return new GraphLogController(e.document,{formatter:createFormatter(e.params),lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:en.monitor.defaultLineCount,props:ValueMap.fromObject({maxValue:null!==(r="max"in e.params?e.params.max:null)&&void 0!==r?r:100,minValue:null!==(i="min"in e.params?e.params.min:null)&&void 0!==i?i:0}),value:e.value,viewProps:e.viewProps})}function shouldShowGraph(e){return"view"in e&&"graph"===e.view}let ep={id:"monitor-number",type:"monitor",accept:(e,t)=>{if("number"!=typeof e)return null;let r=parseParams(t,{format:i.optional.function,lineCount:i.optional.number,max:i.optional.number,min:i.optional.number,view:i.optional.string});return r?{initialValue:e,params:r}:null},binding:{defaultBufferSize:e=>shouldShowGraph(e)?64:1,reader:e=>numberFromUnknown},controller:e=>shouldShowGraph(e.params)?createGraphMonitor(e):createTextMonitor(e)},ed={id:"monitor-string",type:"monitor",accept:(e,t)=>{if("string"!=typeof e)return null;let r=parseParams(t,{lineCount:i.optional.number,multiline:i.optional.boolean});return r?{initialValue:e,params:r}:null},binding:{reader:e=>stringFromUnknown},controller:e=>{var t;let r=e.value,i=r.rawValue.length>1||"multiline"in e.params&&e.params.multiline;return i?new MultiLogController(e.document,{formatter:formatString,lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:en.monitor.defaultLineCount,value:r,viewProps:e.viewProps}):new SingleLogController(e.document,{formatter:formatString,value:r,viewProps:e.viewProps})}};function createInputBindingController(e,t){var r;let n=e.accept(t.target.read(),t.params);if(isEmpty(n))return null;let o={target:t.target,initialValue:n.initialValue,params:n.params},a=e.binding.reader(o),l=e.binding.constraint?e.binding.constraint(o):void 0,s=createValue(a(n.initialValue),{constraint:l,equals:e.binding.equals}),p=new InputBinding({reader:a,target:t.target,value:s,writer:e.binding.writer(o)}),d=i.optional.boolean(t.params.disabled).value,u=i.optional.boolean(t.params.hidden).value,c=e.controller({constraint:l,document:t.document,initialValue:n.initialValue,params:n.params,value:p.value,viewProps:ViewProps.create({disabled:d,hidden:u})});return new InputBindingController(t.document,{binding:p,blade:createBlade(),props:ValueMap.fromObject({label:"label"in t.params?null!==(r=i.optional.string(t.params.label).value)&&void 0!==r?r:null:t.target.key}),valueController:c})}function createTicker(e,t){return 0===t?new ManualTicker:new IntervalTicker(e,null!=t?t:en.monitor.defaultInterval)}function createMonitorBindingController(e,t){var r,n,o;let a=e.accept(t.target.read(),t.params);if(isEmpty(a))return null;let l={target:t.target,initialValue:a.initialValue,params:a.params},s=e.binding.reader(l),p=null!==(n=null!==(r=i.optional.number(t.params.bufferSize).value)&&void 0!==r?r:e.binding.defaultBufferSize&&e.binding.defaultBufferSize(a.params))&&void 0!==n?n:1,d=i.optional.number(t.params.interval).value,u=new MonitorBinding({reader:s,target:t.target,ticker:createTicker(t.document,d),value:initializeBuffer(p)}),c=i.optional.boolean(t.params.disabled).value,h=i.optional.boolean(t.params.hidden).value,v=e.controller({document:t.document,params:a.params,value:u.value,viewProps:ViewProps.create({disabled:c,hidden:h})});return new MonitorBindingController(t.document,{binding:u,blade:createBlade(),props:ValueMap.fromObject({label:"label"in t.params?null!==(o=i.optional.string(t.params.label).value)&&void 0!==o?o:null:t.target.key}),valueController:v})}let PluginPool=class PluginPool{constructor(){this.pluginsMap_={blades:[],inputs:[],monitors:[]}}getAll(){return[...this.pluginsMap_.blades,...this.pluginsMap_.inputs,...this.pluginsMap_.monitors]}register(e){"blade"===e.type?this.pluginsMap_.blades.unshift(e):"input"===e.type?this.pluginsMap_.inputs.unshift(e):"monitor"===e.type&&this.pluginsMap_.monitors.unshift(e)}createInput(e,t,r){let i=t.read();if(isEmpty(i))throw new TpError({context:{key:t.key},type:"nomatchingcontroller"});let n=this.pluginsMap_.inputs.reduce((i,n)=>null!=i?i:createInputBindingController(n,{document:e,target:t,params:r}),null);if(n)return n;throw new TpError({context:{key:t.key},type:"nomatchingcontroller"})}createMonitor(e,t,r){let i=this.pluginsMap_.monitors.reduce((i,n)=>null!=i?i:createMonitorBindingController(n,{document:e,params:r,target:t}),null);if(i)return i;throw new TpError({context:{key:t.key},type:"nomatchingcontroller"})}createBlade(e,t){let r=this.pluginsMap_.blades.reduce((r,i)=>null!=r?r:createBladeController(i,{document:e,params:t}),null);if(!r)throw new TpError({type:"nomatchingview",context:{params:t}});return r}createBladeApi(e){if(e instanceof InputBindingController)return new InputBindingApi(e);if(e instanceof MonitorBindingController)return new MonitorBindingApi(e);if(e instanceof RackController)return new RackApi(e,this);let t=this.pluginsMap_.blades.reduce((t,r)=>null!=t?t:r.api({controller:e,pool:this}),null);if(!t)throw TpError.shouldNeverHappen();return t}};function createDefaultPluginPool(){let e=new PluginPool;return[eu,ee,er,ei,W,G,q,z,L,el,ed,ep,d,c,v,g].forEach(t=>{e.register(t)}),e}function point2dFromUnknown(e){return Point2d.isObject(e)?new Point2d(e.x,e.y):new Point2d}function writePoint2d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y)}function createDimensionConstraint(e,t){if(!e)return;let r=[],i=createStepConstraint(e,t);i&&r.push(i);let n=createRangeConstraint(e);return n&&r.push(n),new CompositeConstraint(r)}function createConstraint(e,t){return new PointNdConstraint({assembly:X,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y)]})}function getSuitableMaxDimensionValue(e,t){let[r,i]=e?findNumberRange(e):[];if(!isEmpty(r)||!isEmpty(i))return Math.max(Math.abs(null!=r?r:0),Math.abs(null!=i?i:0));let n=getBaseStep(e);return Math.max(10*Math.abs(n),10*Math.abs(t))}function getSuitableMaxValue(e,t){let r=t instanceof PointNdConstraint?t.components[0]:void 0,i=t instanceof PointNdConstraint?t.components[1]:void 0,n=getSuitableMaxDimensionValue(r,e.x),o=getSuitableMaxDimensionValue(i,e.y);return Math.max(n,o)}function createAxis(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}function shouldInvertY(e){if(!("y"in e))return!1;let t=e.y;return!!t&&"inverted"in t&&!!t.inverted}let eu={id:"input-point2d",type:"input",accept:(e,t)=>{if(!Point2d.isObject(e))return null;let r=parseParams(t,{expanded:i.optional.boolean,picker:i.optional.custom(parsePickerLayout),x:i.optional.custom(parsePointDimensionParams),y:i.optional.object({inverted:i.optional.boolean,max:i.optional.number,min:i.optional.number,step:i.optional.number})});return r?{initialValue:e,params:r}:null},binding:{reader:e=>point2dFromUnknown,constraint:e=>createConstraint(e.params,e.initialValue),equals:Point2d.equals,writer:e=>writePoint2d},controller:e=>{let t=e.document,r=e.value,i=e.constraint;if(!(i instanceof PointNdConstraint))throw TpError.shouldNeverHappen();let n="expanded"in e.params?e.params.expanded:void 0,o="picker"in e.params?e.params.picker:void 0;return new Point2dController(t,{axes:[createAxis(r.rawValue.x,i.components[0]),createAxis(r.rawValue.y,i.components[1])],expanded:null!=n&&n,invertsY:shouldInvertY(e.params),maxValue:getSuitableMaxValue(r.rawValue,i),parser:parseNumber,pickerLayout:null!=o?o:"popup",value:r,viewProps:e.viewProps})}};let ListApi=class ListApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get options(){return this.controller_.valueController.props.get("options")}set options(e){this.controller_.valueController.props.set("options",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}};let SliderApi=class SliderApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get maxValue(){return this.controller_.valueController.sliderController.props.get("maxValue")}set maxValue(e){this.controller_.valueController.sliderController.props.set("maxValue",e)}get minValue(){return this.controller_.valueController.sliderController.props.get("minValue")}set minValue(e){this.controller_.valueController.sliderController.props.set("minValue",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}};let TextApi=class TextApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get formatter(){return this.controller_.valueController.props.get("formatter")}set formatter(e){this.controller_.valueController.props.set("formatter",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}};let ec={id:"list",type:"blade",accept(e){let t=parseParams(e,{options:i.required.custom(parseListOptions),value:i.required.raw,view:i.required.constant("list"),label:i.optional.string});return t?{params:t}:null},controller(e){let t=new ListConstraint(normalizeListOptions(e.params.options)),r=createValue(e.params.value,{constraint:t}),i=new ListController(e.document,{props:new ValueMap({options:t.values.value("options")}),value:r,viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:i})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof ListController?new ListApi(e.controller):null};function exportPresetJson(e){return e.reduce((e,t)=>Object.assign(e,{[t.presetKey]:t.read()}),{})}function importPresetJson(e,t){e.forEach(e=>{let r=t[e.target.presetKey];void 0!==r&&e.writer(e.target,e.reader(r))})}let RootApi=class RootApi extends FolderApi{constructor(e,t){super(e,t)}get element(){return this.controller_.view.element}importPreset(e){let t=this.controller_.rackController.rack.find(InputBindingController).map(e=>e.binding);importPresetJson(t,e),this.refresh()}exportPreset(){let e=this.controller_.rackController.rack.find(InputBindingController).map(e=>e.binding.target);return exportPresetJson(e)}refresh(){this.controller_.rackController.rack.find(InputBindingController).forEach(e=>{e.binding.read()}),this.controller_.rackController.rack.find(MonitorBindingController).forEach(e=>{e.binding.read()})}};let RootController=class RootController extends FolderController{constructor(e,t){super(e,{expanded:t.expanded,blade:t.blade,props:t.props,root:!0,viewProps:t.viewProps})}};let eh={id:"slider",type:"blade",accept(e){let t=parseParams(e,{max:i.required.number,min:i.required.number,view:i.required.constant("slider"),format:i.optional.function,label:i.optional.string,value:i.optional.number});return t?{params:t}:null},controller(e){var t,r;let i=null!==(t=e.params.value)&&void 0!==t?t:0,n=new DefiniteRangeConstraint({max:e.params.max,min:e.params.min}),o=new SliderTextController(e.document,{baseStep:1,parser:parseNumber,sliderProps:new ValueMap({maxValue:n.values.value("max"),minValue:n.values.value("min")}),textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(void 0,i),formatter:null!==(r=e.params.format)&&void 0!==r?r:numberToString}),value:createValue(i,{constraint:n}),viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:o})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof SliderTextController?new SliderApi(e.controller):null},ev={id:"text",type:"blade",accept(e){let t=parseParams(e,{parse:i.required.function,value:i.required.raw,view:i.required.constant("text"),format:i.optional.function,label:i.optional.string});return t?{params:t}:null},controller(e){var t;let r=new TextController(e.document,{parser:e.params.parse,props:ValueMap.fromObject({formatter:null!==(t=e.params.format)&&void 0!==t?t:e=>String(e)}),value:createValue(e.params.value),viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:r})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof TextController?new TextApi(e.controller):null};function createDefaultWrapperElement(e){let t=e.createElement("div");return t.classList.add(ClassName("dfw")()),e.body&&e.body.appendChild(t),t}function embedStyle(e,t,r){if(e.querySelector(`style[data-tp-style=${t}]`))return;let i=e.createElement("style");i.dataset.tpStyle=t,i.textContent=r,e.head.appendChild(i)}let Pane=class Pane extends RootApi{constructor(e){var t,r;let i=null!=e?e:{},n=null!==(t=i.document)&&void 0!==t?t:getWindowDocument(),o=createDefaultPluginPool(),a=new RootController(n,{expanded:i.expanded,blade:createBlade(),props:ValueMap.fromObject({title:i.title}),viewProps:ViewProps.create()});super(a,o),this.pool_=o,this.containerElem_=null!==(r=i.container)&&void 0!==r?r:createDefaultWrapperElement(n),this.containerElem_.appendChild(this.element),this.doc_=n,this.usesDefaultWrapper_=!i.container,this.setUpDefaultPlugins_()}get document(){if(!this.doc_)throw TpError.alreadyDisposed();return this.doc_}dispose(){let e=this.containerElem_;if(!e)throw TpError.alreadyDisposed();if(this.usesDefaultWrapper_){let t=e.parentElement;t&&t.removeChild(e)}this.containerElem_=null,this.doc_=null,super.dispose()}registerPlugin(e){let t="plugin"in e?[e.plugin]:"plugins"in e?e.plugins:[];t.forEach(e=>{this.pool_.register(e),this.embedPluginStyle_(e)})}embedPluginStyle_(e){e.css&&embedStyle(this.document,`plugin-${e.id}`,e.css)}setUpDefaultPlugins_(){embedStyle(this.document,"default",'.tp-tbiv_b,.tp-coltxtv_ms,.tp-ckbv_i,.tp-rotv_b,.tp-fldv_b,.tp-mllv_i,.tp-sglv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--elm-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--bld-us);line-height:var(--bld-us);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--bld-us);line-height:var(--bld-us);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-mllv_i,.tp-sglv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--mo-fg);height:var(--bld-us);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-mllv_i::-webkit-scrollbar,.tp-sglv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-mllv_i::-webkit-scrollbar-corner,.tp-sglv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-mllv_i::-webkit-scrollbar-thumb,.tp-sglv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-rotv{--font-family: var(--tp-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-br: var(--tp-base-border-radius, 6px);--cnt-h-p: var(--tp-container-horizontal-padding, 4px);--cnt-v-p: var(--tp-container-vertical-padding, 4px);--elm-br: var(--tp-element-border-radius, 2px);--bld-s: var(--tp-blade-spacing, 4px);--bld-us: var(--tp-blade-unit-size, 20px);--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tabv_c .tp-brkv>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-v-p))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tabv_c .tp-brkv>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--bld-s)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tabv_c .tp-brkv>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tabv_c .tp-brkv>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--elm-br);border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tabv_c .tp-brkv .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--elm-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);overflow:hidden;padding-left:var(--cnt-h-p);padding-right:calc(4px + var(--bld-us) + var(--cnt-h-p));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-h-p) + (var(--bld-us) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-v-p);padding-top:var(--cnt-v-p);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--elm-br);cursor:pointer;display:block;height:var(--bld-us);position:relative;width:var(--bld-us)}.tp-ckbv_w svg{bottom:0;display:block;height:16px;left:0;margin:auto;opacity:0;position:absolute;right:0;top:0;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--bld-us)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--bld-s);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--bld-s)}.tp-colpv_rgb{display:flex;margin-top:var(--bld-s);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-v-p);padding-top:calc(var(--cnt-v-p) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-h-p));position:absolute;right:calc(-1*var(--cnt-h-p));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--elm-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--bld-us)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--elm-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;pointer-events:none;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--elm-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;cursor:pointer;display:block;height:var(--bld-us);left:0;margin:0;outline:none;padding:0;position:absolute;top:0;width:var(--bld-us)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--elm-br);bottom:0;content:"";display:block;left:0;position:absolute;right:0;top:0}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--elm-br);color:var(--lbl-fg);cursor:pointer;height:var(--bld-us);line-height:var(--bld-us);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv.tp-fldv-not .tp-fldv_b{display:none}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--bld-us)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-h-p);padding-right:var(--cnt-h-p)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:160px}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding:0 4px}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--bld-us)*3);line-height:var(--bld-us);padding:0 4px;resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--bld-us);margin-right:4px;position:relative;width:var(--bld-us)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--bld-s);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-p2dpv{padding-left:calc(var(--bld-us) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:6px;box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:168px;padding:var(--cnt-v-p) var(--cnt-h-p);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--bld-us);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin:auto;position:absolute;right:0;top:0}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin-bottom:auto;margin-top:auto;position:absolute;right:0;top:0}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--elm-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--bld-us) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_c{padding-bottom:var(--cnt-v-p);padding-left:4px;padding-top:var(--cnt-v-p)}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-h-p) + 4px);padding-right:calc(var(--cnt-h-p) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);bottom:2px;content:"";left:0;pointer-events:none;position:absolute;right:0;top:0}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);opacity:.5;overflow:hidden;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-txtv{position:relative}.tp-txtv_i{padding:0 4px}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:-3px;position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--bld-us) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--elm-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--font-family);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--bld-us) + var(--cnt-h-p));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0}.tp-rotv.tp-rotv-not .tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}'),this.pool_.getAll().forEach(e=>{this.embedPluginStyle_(e)}),this.registerPlugin({plugins:[eh,ec,g,ev]})}};let em=new Semver("3.1.10");e.BladeApi=BladeApi,e.ButtonApi=ButtonApi,e.FolderApi=FolderApi,e.InputBindingApi=InputBindingApi,e.ListApi=ListApi,e.MonitorBindingApi=MonitorBindingApi,e.Pane=Pane,e.SeparatorApi=SeparatorApi,e.SliderApi=SliderApi,e.TabApi=TabApi,e.TabPageApi=TabPageApi,e.TextApi=TextApi,e.TpChangeEvent=TpChangeEvent,e.VERSION=em,Object.defineProperty(e,"__esModule",{value:!0})}(t)}}]); \ No newline at end of file diff --git a/.next/static/chunks/604a08ec-59af37265fb99b3d.js b/.next/static/chunks/604a08ec-59af37265fb99b3d.js new file mode 100644 index 0000000..595c780 --- /dev/null +++ b/.next/static/chunks/604a08ec-59af37265fb99b3d.js @@ -0,0 +1,4 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[735],{78:function(t,e,r){r.d(e,{FM:function(){return Vector2},Lt:function(){return Vector4},P:function(){return Vector3},_f:function(){return Quaternion},jp:function(){return TmpVectors},y3:function(){return Matrix}});var i=r(5762),s=r(9806),o=r(4254),a=r(3048),n=r(4548),h=r(6030);let _ExtractAsInt=t=>parseInt(t.toString().replace(/\W/g,""));let Vector2=class Vector2{constructor(t=0,e=0){this.x=t,this.y=e}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let t=_ExtractAsInt(this.x),e=_ExtractAsInt(this.y);return 397*t^e}toArray(t,e=0){return t[e]=this.x,t[e+1]=this.y,this}fromArray(t,e=0){return Vector2.FromArrayToRef(t,e,this),this}asArray(){let t=[];return this.toArray(t,0),t}copyFrom(t){return this.x=t.x,this.y=t.y,this}copyFromFloats(t,e){return this.x=t,this.y=e,this}set(t,e){return this.copyFromFloats(t,e)}add(t){return new this.constructor(this.x+t.x,this.y+t.y)}addToRef(t,e){return e.x=this.x+t.x,e.y=this.y+t.y,e}addInPlace(t){return this.x+=t.x,this.y+=t.y,this}addVector3(t){return new this.constructor(this.x+t.x,this.y+t.y)}subtract(t){return new this.constructor(this.x-t.x,this.y-t.y)}subtractToRef(t,e){return e.x=this.x-t.x,e.y=this.y-t.y,e}subtractInPlace(t){return this.x-=t.x,this.y-=t.y,this}multiplyInPlace(t){return this.x*=t.x,this.y*=t.y,this}multiply(t){return new this.constructor(this.x*t.x,this.y*t.y)}multiplyToRef(t,e){return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByFloats(t,e){return new this.constructor(this.x*t,this.y*e)}divide(t){return new this.constructor(this.x/t.x,this.y/t.y)}divideToRef(t,e){return e.x=this.x/t.x,e.y=this.y/t.y,e}divideInPlace(t){return this.divideToRef(t,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(t){return t.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(t){return this.x*=t,this.y*=t,this}scale(t){let e=new this.constructor(0,0);return this.scaleToRef(t,e),e}scaleToRef(t,e){return e.x=this.x*t,e.y=this.y*t,e}scaleAndAddToRef(t,e){return e.x+=this.x*t,e.y+=this.y*t,e}equals(t){return t&&this.x===t.x&&this.y===t.y}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this.x,t.x,e)&&i.R.WithinEpsilon(this.y,t.y,e)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(t,e){let r=Math.cos(t),i=Math.sin(t),s=r*this.x-i*this.y,o=i*this.x+r*this.y;return e.x=s,e.y=o,e}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return Vector2.NormalizeToRef(this,this),this}clone(){return new this.constructor(this.x,this.y)}static Zero(){return new Vector2(0,0)}static One(){return new Vector2(1,1)}static Random(t=0,e=1){return new Vector2(i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static get ZeroReadOnly(){return Vector2._ZeroReadOnly}static FromArray(t,e=0){return new Vector2(t[e],t[e+1])}static FromArrayToRef(t,e,r){return r.x=t[e],r.y=t[e+1],r}static CatmullRom(t,e,r,i,s){let o=s*s,a=s*o,n=.5*(2*e.x+(-t.x+r.x)*s+(2*t.x-5*e.x+4*r.x-i.x)*o+(-t.x+3*e.x-3*r.x+i.x)*a),h=.5*(2*e.y+(-t.y+r.y)*s+(2*t.y-5*e.y+4*r.y-i.y)*o+(-t.y+3*e.y-3*r.y+i.y)*a);return new t.constructor(n,h)}static Clamp(t,e,r){let i=t.x;i=(i=i>r.x?r.x:i)<e.x?e.x:i;let s=t.y;return s=(s=s>r.y?r.y:s)<e.y?e.y:s,new t.constructor(i,s)}static Hermite(t,e,r,i,s){let o=s*s,a=s*o,n=2*a-3*o+1,h=-2*a+3*o,c=a-2*o+s,_=a-o,l=t.x*n+r.x*h+e.x*c+i.x*_,u=t.y*n+r.y*h+e.y*c+i.y*_;return new t.constructor(l,u)}static Hermite1stDerivative(t,e,r,i,s){let o=new t.constructor;return this.Hermite1stDerivativeToRef(t,e,r,i,s,o),o}static Hermite1stDerivativeToRef(t,e,r,i,s,o){let a=s*s;return o.x=(a-s)*6*t.x+(3*a-4*s+1)*e.x+(-a+s)*6*r.x+(3*a-2*s)*i.x,o.y=(a-s)*6*t.y+(3*a-4*s+1)*e.y+(-a+s)*6*r.y+(3*a-2*s)*i.y,o}static Lerp(t,e,r){let i=t.x+(e.x-t.x)*r,s=t.y+(e.y-t.y)*r;return new t.constructor(i,s)}static Dot(t,e){return t.x*e.x+t.y*e.y}static Normalize(t){let e=new t.constructor;return this.NormalizeToRef(t,e),e}static NormalizeToRef(t,e){let r=t.length();return 0===r||(e.x=t.x/r,e.y=t.y/r),e}static Minimize(t,e){let r=t.x<e.x?t.x:e.x,i=t.y<e.y?t.y:e.y;return new t.constructor(r,i)}static Maximize(t,e){let r=t.x>e.x?t.x:e.x,i=t.y>e.y?t.y:e.y;return new t.constructor(r,i)}static Transform(t,e){let r=new t.constructor;return Vector2.TransformToRef(t,e,r),r}static TransformToRef(t,e,r){let i=e.m,s=t.x*i[0]+t.y*i[4]+i[12],o=t.x*i[1]+t.y*i[5]+i[13];return r.x=s,r.y=o,r}static PointInTriangle(t,e,r,i){let s=.5*(-r.y*i.x+e.y*(-r.x+i.x)+e.x*(r.y-i.y)+r.x*i.y),o=s<0?-1:1,a=(e.y*i.x-e.x*i.y+(i.y-e.y)*t.x+(e.x-i.x)*t.y)*o,n=(e.x*r.y-e.y*r.x+(e.y-r.y)*t.x+(r.x-e.x)*t.y)*o;return a>0&&n>0&&a+n<2*s*o}static Distance(t,e){return Math.sqrt(Vector2.DistanceSquared(t,e))}static DistanceSquared(t,e){let r=t.x-e.x,i=t.y-e.y;return r*r+i*i}static Center(t,e){let r=new t.constructor;return Vector2.CenterToRef(t,e,r)}static CenterToRef(t,e,r){return r.copyFromFloats((t.x+e.x)/2,(t.y+e.y)/2)}static DistanceOfPointFromSegment(t,e,r){let i=Vector2.DistanceSquared(e,r);if(0===i)return Vector2.Distance(t,e);let s=r.subtract(e),o=Math.max(0,Math.min(1,Vector2.Dot(t.subtract(e),s)/i)),a=e.add(s.multiplyByFloats(o,o));return Vector2.Distance(t,a)}};Vector2._ZeroReadOnly=Vector2.Zero();let Vector3=class Vector3{get x(){return this._x}set x(t){this._x=t,this._isDirty=!0}get y(){return this._y}set y(t){this._y=t,this._isDirty=!0}get z(){return this._z}set z(t){this._z=t,this._isDirty=!0}constructor(t=0,e=0,r=0){this._isDirty=!0,this._x=t,this._y=e,this._z=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let t=_ExtractAsInt(this._x),e=_ExtractAsInt(this._y),r=_ExtractAsInt(this._z),i=t;return 397*(i=397*i^e)^r}asArray(){let t=[];return this.toArray(t,0),t}toArray(t,e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,this}fromArray(t,e=0){return Vector3.FromArrayToRef(t,e,this),this}toQuaternion(){return Quaternion.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(t){return this.addInPlaceFromFloats(t._x,t._y,t._z)}addInPlaceFromFloats(t,e,r){return this._x+=t,this._y+=e,this._z+=r,this._isDirty=!0,this}add(t){return new this.constructor(this._x+t._x,this._y+t._y,this._z+t._z)}addToRef(t,e){return e.copyFromFloats(this._x+t._x,this._y+t._y,this._z+t._z)}subtractInPlace(t){return this._x-=t._x,this._y-=t._y,this._z-=t._z,this._isDirty=!0,this}subtract(t){return new this.constructor(this._x-t._x,this._y-t._y,this._z-t._z)}subtractToRef(t,e){return this.subtractFromFloatsToRef(t._x,t._y,t._z,e)}subtractFromFloats(t,e,r){return new this.constructor(this._x-t,this._y-e,this._z-r)}subtractFromFloatsToRef(t,e,r,i){return i.copyFromFloats(this._x-t,this._y-e,this._z-r)}negate(){return new this.constructor(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(t){return t.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(t){return this._x*=t,this._y*=t,this._z*=t,this._isDirty=!0,this}scale(t){return new this.constructor(this._x*t,this._y*t,this._z*t)}scaleToRef(t,e){return e.copyFromFloats(this._x*t,this._y*t,this._z*t)}getNormalToRef(t){let e=this.length(),r=Math.acos(this.y/e),i=Math.atan2(this.z,this.x);r>Math.PI/2?r-=Math.PI/2:r+=Math.PI/2;let s=e*Math.sin(r)*Math.cos(i),o=e*Math.cos(r),a=e*Math.sin(r)*Math.sin(i);return t.set(s,o,a),t}applyRotationQuaternionToRef(t,e){let r=this._x,i=this._y,s=this._z,o=t._x,a=t._y,n=t._z,h=t._w,c=2*(a*s-n*i),_=2*(n*r-o*s),l=2*(o*i-a*r);return e._x=r+h*c+a*l-n*_,e._y=i+h*_+n*c-o*l,e._z=s+h*l+o*_-a*c,e._isDirty=!0,e}applyRotationQuaternionInPlace(t){return this.applyRotationQuaternionToRef(t,this)}applyRotationQuaternion(t){return this.applyRotationQuaternionToRef(t,new this.constructor)}scaleAndAddToRef(t,e){return e.addInPlaceFromFloats(this._x*t,this._y*t,this._z*t)}projectOnPlane(t,e){let r=new this.constructor;return this.projectOnPlaneToRef(t,e,r),r}projectOnPlaneToRef(t,e,r){let i=t.normal,s=t.d,o=MathTmp.Vector3[0];this.subtractToRef(e,o),o.normalize();let a=Vector3.Dot(o,i);if(1e-10>Math.abs(a))r.setAll(1/0);else{let t=-(Vector3.Dot(e,i)+s)/a,n=o.scaleInPlace(t);e.addToRef(n,r)}return r}equals(t){return t&&this._x===t._x&&this._y===t._y&&this._z===t._z}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this._x,t._x,e)&&i.R.WithinEpsilon(this._y,t._y,e)&&i.R.WithinEpsilon(this._z,t._z,e)}equalsToFloats(t,e,r){return this._x===t&&this._y===e&&this._z===r}multiplyInPlace(t){return this._x*=t._x,this._y*=t._y,this._z*=t._z,this._isDirty=!0,this}multiply(t){return this.multiplyByFloats(t._x,t._y,t._z)}multiplyToRef(t,e){return e.copyFromFloats(this._x*t._x,this._y*t._y,this._z*t._z)}multiplyByFloats(t,e,r){return new this.constructor(this._x*t,this._y*e,this._z*r)}divide(t){return new this.constructor(this._x/t._x,this._y/t._y,this._z/t._z)}divideToRef(t,e){return e.copyFromFloats(this._x/t._x,this._y/t._y,this._z/t._z)}divideInPlace(t){return this.divideToRef(t,this)}minimizeInPlace(t){return this.minimizeInPlaceFromFloats(t._x,t._y,t._z)}maximizeInPlace(t){return this.maximizeInPlaceFromFloats(t._x,t._y,t._z)}minimizeInPlaceFromFloats(t,e,r){return t<this._x&&(this.x=t),e<this._y&&(this.y=e),r<this._z&&(this.z=r),this}maximizeInPlaceFromFloats(t,e,r){return t>this._x&&(this.x=t),e>this._y&&(this.y=e),r>this._z&&(this.z=r),this}isNonUniformWithinEpsilon(t){let e=Math.abs(this._x),r=Math.abs(this._y);if(!i.R.WithinEpsilon(e,r,t))return!0;let s=Math.abs(this._z);return!(i.R.WithinEpsilon(e,s,t)&&i.R.WithinEpsilon(r,s,t))}get isNonUniform(){let t=Math.abs(this._x),e=Math.abs(this._y);if(t!==e)return!0;let r=Math.abs(this._z);return t!==r}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(t){return"xyz"===(t=t.toLowerCase())||(MathTmp.Vector3[0].copyFrom(this),["x","y","z"].forEach((e,r)=>{this[e]=MathTmp.Vector3[0][t[r]]})),this}rotateByQuaternionToRef(t,e){return t.toRotationMatrix(MathTmp.Matrix[0]),Vector3.TransformCoordinatesToRef(this,MathTmp.Matrix[0],e),e}rotateByQuaternionAroundPointToRef(t,e,r){return this.subtractToRef(e,MathTmp.Vector3[0]),MathTmp.Vector3[0].rotateByQuaternionToRef(t,MathTmp.Vector3[0]),e.addToRef(MathTmp.Vector3[0],r),r}cross(t){let e=new this.constructor;return Vector3.CrossToRef(this,t,e)}normalizeFromLength(t){return 0===t||1===t?this:this.scaleInPlace(1/t)}normalizeToNew(){let t=new this.constructor(0,0,0);return this.normalizeToRef(t),t}normalizeToRef(t){let e=this.length();return 0===e||1===e?t.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/e,t)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(t){return this.copyFromFloats(t._x,t._y,t._z)}copyFromFloats(t,e,r){return this._x=t,this._y=e,this._z=r,this._isDirty=!0,this}set(t,e,r){return this.copyFromFloats(t,e,r)}setAll(t){return this._x=this._y=this._z=t,this._isDirty=!0,this}static GetClipFactor(t,e,r,i){let s=Vector3.Dot(t,r)-i,o=Vector3.Dot(e,r)-i;return s/(s-o)}static GetAngleBetweenVectors(t,e,r){let s=t.normalizeToRef(MathTmp.Vector3[1]),o=e.normalizeToRef(MathTmp.Vector3[2]),a=Vector3.Dot(s,o);a=i.R.Clamp(a,-1,1);let n=Math.acos(a),h=MathTmp.Vector3[3];return(Vector3.CrossToRef(s,o,h),Vector3.Dot(h,r)>0)?isNaN(n)?0:n:isNaN(n)?-Math.PI:-Math.acos(a)}static GetAngleBetweenVectorsOnPlane(t,e,r){MathTmp.Vector3[0].copyFrom(t);let s=MathTmp.Vector3[0];MathTmp.Vector3[1].copyFrom(e);let o=MathTmp.Vector3[1];MathTmp.Vector3[2].copyFrom(r);let a=MathTmp.Vector3[2],n=MathTmp.Vector3[3],h=MathTmp.Vector3[4];s.normalize(),o.normalize(),a.normalize(),Vector3.CrossToRef(a,s,n),Vector3.CrossToRef(n,a,h);let c=Math.atan2(Vector3.Dot(o,n),Vector3.Dot(o,h));return i.R.NormalizeRadians(c)}static PitchYawRollToMoveBetweenPointsToRef(t,e,r){let i=TmpVectors.Vector3[0];return e.subtractToRef(t,i),r._y=Math.atan2(i.x,i.z)||0,r._x=Math.atan2(Math.sqrt(i.x**2+i.z**2),i.y)||0,r._z=0,r._isDirty=!0,r}static PitchYawRollToMoveBetweenPoints(t,e){let r=Vector3.Zero();return Vector3.PitchYawRollToMoveBetweenPointsToRef(t,e,r)}static SlerpToRef(t,e,r,o){let a,n;r=i.R.Clamp(r,0,1);let h=MathTmp.Vector3[0],c=MathTmp.Vector3[1];h.copyFrom(t);let _=h.length();h.normalizeFromLength(_),c.copyFrom(e);let l=c.length();c.normalizeFromLength(l);let u=Vector3.Dot(h,c);if(u<1-s.kn){let t=Math.acos(u),e=1/Math.sin(t);a=Math.sin((1-r)*t)*e,n=Math.sin(r*t)*e}else a=1-r,n=r;return h.scaleInPlace(a),c.scaleInPlace(n),o.copyFrom(h).addInPlace(c),o.scaleInPlace(i.R.Lerp(_,l,r)),o}static SmoothToRef(t,e,r,i,s){return Vector3.SlerpToRef(t,e,0===i?1:r/i,s),s}static FromArray(t,e=0){return new Vector3(t[e],t[e+1],t[e+2])}static FromFloatArray(t,e){return Vector3.FromArray(t,e)}static FromArrayToRef(t,e,r){return r._x=t[e],r._y=t[e+1],r._z=t[e+2],r._isDirty=!0,r}static FromFloatArrayToRef(t,e,r){return Vector3.FromArrayToRef(t,e,r)}static FromFloatsToRef(t,e,r,i){return i.copyFromFloats(t,e,r),i}static Zero(){return new Vector3(0,0,0)}static One(){return new Vector3(1,1,1)}static Up(){return new Vector3(0,1,0)}static get UpReadOnly(){return Vector3._UpReadOnly}static get DownReadOnly(){return Vector3._DownReadOnly}static get RightReadOnly(){return Vector3._RightReadOnly}static get LeftReadOnly(){return Vector3._LeftReadOnly}static get LeftHandedForwardReadOnly(){return Vector3._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return Vector3._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return Vector3._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return Vector3._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return Vector3._ZeroReadOnly}static get OneReadOnly(){return Vector3._OneReadOnly}static Down(){return new Vector3(0,-1,0)}static Forward(t=!1){return new Vector3(0,0,t?-1:1)}static Backward(t=!1){return new Vector3(0,0,t?1:-1)}static Right(){return new Vector3(1,0,0)}static Left(){return new Vector3(-1,0,0)}static Random(t=0,e=1){return new Vector3(i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static TransformCoordinates(t,e){let r=Vector3.Zero();return Vector3.TransformCoordinatesToRef(t,e,r),r}static TransformCoordinatesToRef(t,e,r){return Vector3.TransformCoordinatesFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformCoordinatesFromFloatsToRef(t,e,r,i,s){let o=i.m,a=t*o[0]+e*o[4]+r*o[8]+o[12],n=t*o[1]+e*o[5]+r*o[9]+o[13],h=t*o[2]+e*o[6]+r*o[10]+o[14],c=1/(t*o[3]+e*o[7]+r*o[11]+o[15]);return s._x=a*c,s._y=n*c,s._z=h*c,s._isDirty=!0,s}static TransformNormal(t,e){let r=Vector3.Zero();return Vector3.TransformNormalToRef(t,e,r),r}static TransformNormalToRef(t,e,r){return this.TransformNormalFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformNormalFromFloatsToRef(t,e,r,i,s){let o=i.m;return s._x=t*o[0]+e*o[4]+r*o[8],s._y=t*o[1]+e*o[5]+r*o[9],s._z=t*o[2]+e*o[6]+r*o[10],s._isDirty=!0,s}static CatmullRom(t,e,r,i,s){let o=s*s,a=s*o,n=.5*(2*e._x+(-t._x+r._x)*s+(2*t._x-5*e._x+4*r._x-i._x)*o+(-t._x+3*e._x-3*r._x+i._x)*a),h=.5*(2*e._y+(-t._y+r._y)*s+(2*t._y-5*e._y+4*r._y-i._y)*o+(-t._y+3*e._y-3*r._y+i._y)*a),c=.5*(2*e._z+(-t._z+r._z)*s+(2*t._z-5*e._z+4*r._z-i._z)*o+(-t._z+3*e._z-3*r._z+i._z)*a);return new t.constructor(n,h,c)}static Clamp(t,e,r){let i=new t.constructor;return Vector3.ClampToRef(t,e,r,i),i}static ClampToRef(t,e,r,i){let s=t._x;s=(s=s>r._x?r._x:s)<e._x?e._x:s;let o=t._y;o=(o=o>r._y?r._y:o)<e._y?e._y:o;let a=t._z;return a=(a=a>r._z?r._z:a)<e._z?e._z:a,i.copyFromFloats(s,o,a),i}static CheckExtends(t,e,r){e.minimizeInPlace(t),r.maximizeInPlace(t)}static Hermite(t,e,r,i,s){let o=s*s,a=s*o,n=2*a-3*o+1,h=-2*a+3*o,c=a-2*o+s,_=a-o,l=t._x*n+r._x*h+e._x*c+i._x*_,u=t._y*n+r._y*h+e._y*c+i._y*_,y=t._z*n+r._z*h+e._z*c+i._z*_;return new t.constructor(l,u,y)}static Hermite1stDerivative(t,e,r,i,s){let o=new t.constructor;return this.Hermite1stDerivativeToRef(t,e,r,i,s,o),o}static Hermite1stDerivativeToRef(t,e,r,i,s,o){let a=s*s;return o._x=(a-s)*6*t._x+(3*a-4*s+1)*e._x+(-a+s)*6*r._x+(3*a-2*s)*i._x,o._y=(a-s)*6*t._y+(3*a-4*s+1)*e._y+(-a+s)*6*r._y+(3*a-2*s)*i._y,o._z=(a-s)*6*t._z+(3*a-4*s+1)*e._z+(-a+s)*6*r._z+(3*a-2*s)*i._z,o._isDirty=!0,o}static Lerp(t,e,r){let i=new t.constructor(0,0,0);return Vector3.LerpToRef(t,e,r,i),i}static LerpToRef(t,e,r,i){return i._x=t._x+(e._x-t._x)*r,i._y=t._y+(e._y-t._y)*r,i._z=t._z+(e._z-t._z)*r,i._isDirty=!0,i}static Dot(t,e){return t._x*e._x+t._y*e._y+t._z*e._z}static Cross(t,e){let r=new t.constructor;return Vector3.CrossToRef(t,e,r),r}static CrossToRef(t,e,r){let i=t._y*e._z-t._z*e._y,s=t._z*e._x-t._x*e._z,o=t._x*e._y-t._y*e._x;return r.copyFromFloats(i,s,o),r}static Normalize(t){let e=Vector3.Zero();return Vector3.NormalizeToRef(t,e),e}static NormalizeToRef(t,e){return t.normalizeToRef(e),e}static Project(t,e,r,i){let s=new t.constructor;return Vector3.ProjectToRef(t,e,r,i,s),s}static ProjectToRef(t,e,r,i,s){let o=i.width,a=i.height,n=i.x,h=i.y,c=MathTmp.Matrix[1];Matrix.FromValuesToRef(o/2,0,0,0,0,-a/2,0,0,0,0,.5,0,n+o/2,a/2+h,.5,1,c);let _=MathTmp.Matrix[0];return e.multiplyToRef(r,_),_.multiplyToRef(c,_),Vector3.TransformCoordinatesToRef(t,_,s),s}static Reflect(t,e){return this.ReflectToRef(t,e,new Vector3)}static ReflectToRef(t,e,r){let i=TmpVectors.Vector3[0];return i.copyFrom(e).scaleInPlace(2*Vector3.Dot(t,e)),r.copyFrom(t).subtractInPlace(i)}static _UnprojectFromInvertedMatrixToRef(t,e,r){Vector3.TransformCoordinatesToRef(t,e,r);let s=e.m,o=t._x*s[3]+t._y*s[7]+t._z*s[11]+s[15];return i.R.WithinEpsilon(o,1)&&r.scaleInPlace(1/o),r}static UnprojectFromTransform(t,e,r,i,s){return this.Unproject(t,e,r,i,s,Matrix.IdentityReadOnly)}static Unproject(t,e,r,i,s,o){let a=new t.constructor;return Vector3.UnprojectToRef(t,e,r,i,s,o,a),a}static UnprojectToRef(t,e,r,i,s,o,a){return Vector3.UnprojectFloatsToRef(t._x,t._y,t._z,e,r,i,s,o,a),a}static UnprojectFloatsToRef(t,e,r,i,s,o,a,n,c){var _;let l=MathTmp.Matrix[0];o.multiplyToRef(a,l),l.multiplyToRef(n,l),l.invert();let u=MathTmp.Vector3[0];return u.x=t/i*2-1,u.y=-(e/s*2-1),(null===(_=h.l.LastCreatedEngine)||void 0===_?void 0:_.isNDCHalfZRange)?u.z=r:u.z=2*r-1,Vector3._UnprojectFromInvertedMatrixToRef(u,l,c),c}static Minimize(t,e){let r=new t.constructor;return r.copyFrom(t),r.minimizeInPlace(e),r}static Maximize(t,e){let r=new t.constructor;return r.copyFrom(t),r.maximizeInPlace(e),r}static Distance(t,e){return Math.sqrt(Vector3.DistanceSquared(t,e))}static DistanceSquared(t,e){let r=t._x-e._x,i=t._y-e._y,s=t._z-e._z;return r*r+i*i+s*s}static ProjectOnTriangleToRef(t,e,r,o,a){let n,h,c;let _=MathTmp.Vector3[0],l=MathTmp.Vector3[1],u=MathTmp.Vector3[2],y=MathTmp.Vector3[3],m=MathTmp.Vector3[4];r.subtractToRef(e,_),o.subtractToRef(e,l),o.subtractToRef(r,u);let x=_.length(),R=l.length(),T=u.length();if(x<s.kn||R<s.kn||T<s.kn)return a.copyFrom(e),Vector3.Distance(t,e);t.subtractToRef(e,m),Vector3.CrossToRef(_,l,y);let f=y.length();if(f<s.kn)return a.copyFrom(e),Vector3.Distance(t,e);y.normalizeFromLength(f);let d=m.length();if(d<s.kn)return a.copyFrom(e),0;m.normalizeFromLength(d);let p=Vector3.Dot(y,m),z=MathTmp.Vector3[5],M=MathTmp.Vector3[6];z.copyFrom(y).scaleInPlace(-d*p),M.copyFrom(t).addInPlace(z);let w=MathTmp.Vector3[4],F=MathTmp.Vector3[5],V=MathTmp.Vector3[7],I=MathTmp.Vector3[8];w.copyFrom(_).scaleInPlace(1/x),I.copyFrom(l).scaleInPlace(1/R),w.addInPlace(I).scaleInPlace(-1),F.copyFrom(_).scaleInPlace(-1/x),I.copyFrom(u).scaleInPlace(1/T),F.addInPlace(I).scaleInPlace(-1),V.copyFrom(u).scaleInPlace(-1/T),I.copyFrom(l).scaleInPlace(-1/R),V.addInPlace(I).scaleInPlace(-1);let g=MathTmp.Vector3[9];g.copyFrom(M).subtractInPlace(e),Vector3.CrossToRef(w,g,I),n=Vector3.Dot(I,y);let A=n;g.copyFrom(M).subtractInPlace(r),Vector3.CrossToRef(F,g,I),n=Vector3.Dot(I,y);let D=n;g.copyFrom(M).subtractInPlace(o),Vector3.CrossToRef(V,g,I),n=Vector3.Dot(I,y);let P=n,C=MathTmp.Vector3[10];A>0&&D<0?(C.copyFrom(_),h=e,c=r):D>0&&P<0?(C.copyFrom(u),h=r,c=o):(C.copyFrom(l).scaleInPlace(-1),h=o,c=e);let L=MathTmp.Vector3[9],O=MathTmp.Vector3[4];h.subtractToRef(M,I),c.subtractToRef(M,L),Vector3.CrossToRef(I,L,O);let H=0>Vector3.Dot(O,y);if(!H)return a.copyFrom(M),Math.abs(d*p);let k=MathTmp.Vector3[5];Vector3.CrossToRef(C,O,k),k.normalize();let v=MathTmp.Vector3[9];v.copyFrom(h).subtractInPlace(M);let Q=v.length();if(Q<s.kn)return a.copyFrom(h),Vector3.Distance(t,h);v.normalizeFromLength(Q);let S=Vector3.Dot(k,v),B=MathTmp.Vector3[7];B.copyFrom(M).addInPlace(k.scaleInPlace(Q*S)),I.copyFrom(B).subtractInPlace(h),d=C.length(),C.normalizeFromLength(d);let b=Vector3.Dot(I,C)/Math.max(d,s.kn);return b=i.R.Clamp(b,0,1),B.copyFrom(h).addInPlace(C.scaleInPlace(b*d)),a.copyFrom(B),Vector3.Distance(t,B)}static Center(t,e){return Vector3.CenterToRef(t,e,Vector3.Zero())}static CenterToRef(t,e,r){return r.copyFromFloats((t._x+e._x)/2,(t._y+e._y)/2,(t._z+e._z)/2)}static RotationFromAxis(t,e,r){let i=new t.constructor;return Vector3.RotationFromAxisToRef(t,e,r,i),i}static RotationFromAxisToRef(t,e,r,i){let s=MathTmp.Quaternion[0];return Quaternion.RotationQuaternionFromAxisToRef(t,e,r,s),s.toEulerAnglesToRef(i),i}};Vector3._UpReadOnly=Vector3.Up(),Vector3._DownReadOnly=Vector3.Down(),Vector3._LeftHandedForwardReadOnly=Vector3.Forward(!1),Vector3._RightHandedForwardReadOnly=Vector3.Forward(!0),Vector3._LeftHandedBackwardReadOnly=Vector3.Backward(!1),Vector3._RightHandedBackwardReadOnly=Vector3.Backward(!0),Vector3._RightReadOnly=Vector3.Right(),Vector3._LeftReadOnly=Vector3.Left(),Vector3._ZeroReadOnly=Vector3.Zero(),Vector3._OneReadOnly=Vector3.One();let Vector4=class Vector4{constructor(t=0,e=0,r=0,i=0){this.x=t,this.y=e,this.z=r,this.w=i}toString(){return`{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`}getClassName(){return"Vector4"}getHashCode(){let t=_ExtractAsInt(this.x),e=_ExtractAsInt(this.y),r=_ExtractAsInt(this.z),i=_ExtractAsInt(this.w),s=t;return 397*(s=397*(s=397*s^e)^r)^i}asArray(){let t=[];return this.toArray(t,0),t}toArray(t,e){return void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,this}fromArray(t,e=0){return Vector4.FromArrayToRef(t,e,this),this}addInPlace(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}add(t){return new this.constructor(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)}addToRef(t,e){return e.x=this.x+t.x,e.y=this.y+t.y,e.z=this.z+t.z,e.w=this.w+t.w,e}subtractInPlace(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subtract(t){return new this.constructor(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)}subtractToRef(t,e){return e.x=this.x-t.x,e.y=this.y-t.y,e.z=this.z-t.z,e.w=this.w-t.w,e}subtractFromFloats(t,e,r,i){return new this.constructor(this.x-t,this.y-e,this.z-r,this.w-i)}subtractFromFloatsToRef(t,e,r,i,s){return s.x=this.x-t,s.y=this.y-e,s.z=this.z-r,s.w=this.w-i,s}negate(){return new this.constructor(-this.x,-this.y,-this.z,-this.w)}negateInPlace(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this}negateToRef(t){return t.copyFromFloats(-1*this.x,-1*this.y,-1*this.z,-1*this.w)}scaleInPlace(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}scale(t){return new this.constructor(this.x*t,this.y*t,this.z*t,this.w*t)}scaleToRef(t,e){return e.x=this.x*t,e.y=this.y*t,e.z=this.z*t,e.w=this.w*t,e}scaleAndAddToRef(t,e){return e.x+=this.x*t,e.y+=this.y*t,e.z+=this.z*t,e.w+=this.w*t,e}equals(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this.x,t.x,e)&&i.R.WithinEpsilon(this.y,t.y,e)&&i.R.WithinEpsilon(this.z,t.z,e)&&i.R.WithinEpsilon(this.w,t.w,e)}equalsToFloats(t,e,r,i){return this.x===t&&this.y===e&&this.z===r&&this.w===i}multiplyInPlace(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiply(t){return new this.constructor(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)}multiplyToRef(t,e){return e.x=this.x*t.x,e.y=this.y*t.y,e.z=this.z*t.z,e.w=this.w*t.w,e}multiplyByFloats(t,e,r,i){return new this.constructor(this.x*t,this.y*e,this.z*r,this.w*i)}divide(t){return new this.constructor(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)}divideToRef(t,e){return e.x=this.x/t.x,e.y=this.y/t.y,e.z=this.z/t.z,e.w=this.w/t.w,e}divideInPlace(t){return this.divideToRef(t,this)}minimizeInPlace(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this}maximizeInPlace(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){let t=this.length();return 0===t?this:this.scaleInPlace(1/t)}toVector3(){return new Vector3(this.x,this.y,this.z)}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copyFrom(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}copyFromFloats(t,e,r,i){return this.x=t,this.y=e,this.z=r,this.w=i,this}set(t,e,r,i){return this.copyFromFloats(t,e,r,i)}setAll(t){return this.x=this.y=this.z=this.w=t,this}static FromArray(t,e){return e||(e=0),new Vector4(t[e],t[e+1],t[e+2],t[e+3])}static FromArrayToRef(t,e,r){return r.x=t[e],r.y=t[e+1],r.z=t[e+2],r.w=t[e+3],r}static FromFloatArrayToRef(t,e,r){return Vector4.FromArrayToRef(t,e,r),r}static FromFloatsToRef(t,e,r,i,s){return s.x=t,s.y=e,s.z=r,s.w=i,s}static Zero(){return new Vector4(0,0,0,0)}static One(){return new Vector4(1,1,1,1)}static Random(t=0,e=1){return new Vector4(i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static get ZeroReadOnly(){return Vector4._ZeroReadOnly}static Normalize(t){let e=Vector4.Zero();return Vector4.NormalizeToRef(t,e),e}static NormalizeToRef(t,e){return e.copyFrom(t),e.normalize(),e}static Minimize(t,e){let r=new t.constructor;return r.copyFrom(t),r.minimizeInPlace(e),r}static Maximize(t,e){let r=new t.constructor;return r.copyFrom(t),r.maximizeInPlace(e),r}static Distance(t,e){return Math.sqrt(Vector4.DistanceSquared(t,e))}static DistanceSquared(t,e){let r=t.x-e.x,i=t.y-e.y,s=t.z-e.z,o=t.w-e.w;return r*r+i*i+s*s+o*o}static Center(t,e){return Vector4.CenterToRef(t,e,Vector4.Zero())}static CenterToRef(t,e,r){return r.copyFromFloats((t.x+e.x)/2,(t.y+e.y)/2,(t.z+e.z)/2,(t.w+e.w)/2)}static TransformCoordinates(t,e){let r=Vector4.Zero();return Vector4.TransformCoordinatesToRef(t,e,r),r}static TransformCoordinatesToRef(t,e,r){return Vector4.TransformCoordinatesFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformCoordinatesFromFloatsToRef(t,e,r,i,s){let o=i.m,a=t*o[0]+e*o[4]+r*o[8]+o[12],n=t*o[1]+e*o[5]+r*o[9]+o[13],h=t*o[2]+e*o[6]+r*o[10]+o[14],c=t*o[3]+e*o[7]+r*o[11]+o[15];return s.x=a,s.y=n,s.z=h,s.w=c,s}static TransformNormal(t,e){let r=new t.constructor;return Vector4.TransformNormalToRef(t,e,r),r}static TransformNormalToRef(t,e,r){let i=e.m,s=t.x*i[0]+t.y*i[4]+t.z*i[8],o=t.x*i[1]+t.y*i[5]+t.z*i[9],a=t.x*i[2]+t.y*i[6]+t.z*i[10];return r.x=s,r.y=o,r.z=a,r.w=t.w,r}static TransformNormalFromFloatsToRef(t,e,r,i,s,o){let a=s.m;return o.x=t*a[0]+e*a[4]+r*a[8],o.y=t*a[1]+e*a[5]+r*a[9],o.z=t*a[2]+e*a[6]+r*a[10],o.w=i,o}static FromVector3(t,e=0){return new Vector4(t._x,t._y,t._z,e)}};Vector4._ZeroReadOnly=Vector4.Zero();let Quaternion=class Quaternion{get x(){return this._x}set x(t){this._x=t,this._isDirty=!0}get y(){return this._y}set y(t){this._y=t,this._isDirty=!0}get z(){return this._z}set z(t){this._z=t,this._isDirty=!0}get w(){return this._w}set w(t){this._w=t,this._isDirty=!0}constructor(t=0,e=0,r=0,i=1){this._isDirty=!0,this._x=t,this._y=e,this._z=r,this._w=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let t=_ExtractAsInt(this._x),e=_ExtractAsInt(this._y),r=_ExtractAsInt(this._z),i=_ExtractAsInt(this._w),s=t;return 397*(s=397*(s=397*s^e)^r)^i}asArray(){return[this._x,this._y,this._z,this._w]}toArray(t,e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,this}equals(t){return t&&this._x===t._x&&this._y===t._y&&this._z===t._z&&this._w===t._w}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this._x,t._x,e)&&i.R.WithinEpsilon(this._y,t._y,e)&&i.R.WithinEpsilon(this._z,t._z,e)&&i.R.WithinEpsilon(this._w,t._w,e)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._w=t._w,this._isDirty=!0,this}copyFromFloats(t,e,r,i){return this._x=t,this._y=e,this._z=r,this._w=i,this._isDirty=!0,this}set(t,e,r,i){return this.copyFromFloats(t,e,r,i)}add(t){return new this.constructor(this._x+t._x,this._y+t._y,this._z+t._z,this._w+t._w)}addInPlace(t){return this._x+=t._x,this._y+=t._y,this._z+=t._z,this._w+=t._w,this._isDirty=!0,this}subtract(t){return new this.constructor(this._x-t._x,this._y-t._y,this._z-t._z,this._w-t._w)}subtractInPlace(t){return this._x-=t._x,this._y-=t._y,this._z-=t._z,this._w-=t._w,this._isDirty=!0,this}scale(t){return new this.constructor(this._x*t,this._y*t,this._z*t,this._w*t)}scaleToRef(t,e){return e._x=this._x*t,e._y=this._y*t,e._z=this._z*t,e._w=this._w*t,e._isDirty=!0,e}scaleInPlace(t){return this._x*=t,this._y*=t,this._z*=t,this._w*=t,this._isDirty=!0,this}scaleAndAddToRef(t,e){return e._x+=this._x*t,e._y+=this._y*t,e._z+=this._z*t,e._w+=this._w*t,e._isDirty=!0,e}multiply(t){let e=new this.constructor(0,0,0,1);return this.multiplyToRef(t,e),e}multiplyToRef(t,e){let r=this._x*t._w+this._y*t._z-this._z*t._y+this._w*t._x,i=-this._x*t._z+this._y*t._w+this._z*t._x+this._w*t._y,s=this._x*t._y-this._y*t._x+this._z*t._w+this._w*t._z,o=-this._x*t._x-this._y*t._y-this._z*t._z+this._w*t._w;return e.copyFromFloats(r,i,s,o),e}multiplyInPlace(t){return this.multiplyToRef(t,this),this}conjugateToRef(t){return t.copyFromFloats(-this._x,-this._y,-this._z,this._w),t}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){let t=this.conjugate(),e=this.lengthSquared();return 0==e||1==e||t.scaleInPlace(1/e),t}invertInPlace(){this.conjugateInPlace();let t=this.lengthSquared();return 0==t||1==t||this.scaleInPlace(1/t),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){let t=this.length();return 0===t||this.scaleInPlace(1/t),this}normalizeToNew(){let t=this.length();return 0===t?this.clone():this.scale(1/t)}toEulerAngles(){let t=Vector3.Zero();return this.toEulerAnglesToRef(t),t}toEulerAnglesToRef(t){let e=this._z,r=this._x,i=this._y,s=this._w,o=i*e-r*s;if(o<-.4999999)t._y=2*Math.atan2(i,s),t._x=Math.PI/2,t._z=0,t._isDirty=!0;else if(o>.4999999)t._y=2*Math.atan2(i,s),t._x=-Math.PI/2,t._z=0,t._isDirty=!0;else{let a=s*s,n=e*e,h=r*r,c=i*i;t._z=Math.atan2(2*(r*i+e*s),-n-h+c+a),t._x=Math.asin(-2*o),t._y=Math.atan2(2*(e*r+i*s),n-h-c+a),t._isDirty=!0}return t}toRotationMatrix(t){return Matrix.FromQuaternionToRef(this,t),t}fromRotationMatrix(t){return Quaternion.FromRotationMatrixToRef(t,this),this}static FromRotationMatrix(t){let e=new Quaternion;return Quaternion.FromRotationMatrixToRef(t,e),e}static FromRotationMatrixToRef(t,e){let r;let i=t.m,s=i[0],o=i[4],a=i[8],n=i[1],h=i[5],c=i[9],_=i[2],l=i[6],u=i[10],y=s+h+u;return y>0?(r=.5/Math.sqrt(y+1),e._w=.25/r,e._x=(l-c)*r,e._y=(a-_)*r,e._z=(n-o)*r):s>h&&s>u?(r=2*Math.sqrt(1+s-h-u),e._w=(l-c)/r,e._x=.25*r,e._y=(o+n)/r,e._z=(a+_)/r):h>u?(r=2*Math.sqrt(1+h-s-u),e._w=(a-_)/r,e._x=(o+n)/r,e._y=.25*r,e._z=(c+l)/r):(r=2*Math.sqrt(1+u-s-h),e._w=(n-o)/r,e._x=(a+_)/r,e._y=(c+l)/r,e._z=.25*r),e._isDirty=!0,e}static Dot(t,e){return t._x*e._x+t._y*e._y+t._z*e._z+t._w*e._w}static AreClose(t,e,r=.1){let i=Quaternion.Dot(t,e);return 1-i*i<=r}static SmoothToRef(t,e,r,s,o){let a=0===s?1:r/s;return a=i.R.Clamp(a,0,1),Quaternion.SlerpToRef(t,e,a,o),o}static Zero(){return new Quaternion(0,0,0,0)}static Inverse(t){return new t.constructor(-t._x,-t._y,-t._z,t._w)}static InverseToRef(t,e){return e.set(-t._x,-t._y,-t._z,t._w),e}static Identity(){return new Quaternion(0,0,0,1)}static IsIdentity(t){return t&&0===t._x&&0===t._y&&0===t._z&&1===t._w}static RotationAxis(t,e){return Quaternion.RotationAxisToRef(t,e,new Quaternion)}static RotationAxisToRef(t,e,r){let i=Math.sin(e/2);return t.normalize(),r._w=Math.cos(e/2),r._x=t._x*i,r._y=t._y*i,r._z=t._z*i,r._isDirty=!0,r}static FromArray(t,e){return e||(e=0),new Quaternion(t[e],t[e+1],t[e+2],t[e+3])}static FromArrayToRef(t,e,r){return r._x=t[e],r._y=t[e+1],r._z=t[e+2],r._w=t[e+3],r._isDirty=!0,r}static FromEulerAngles(t,e,r){let i=new Quaternion;return Quaternion.RotationYawPitchRollToRef(e,t,r,i),i}static FromEulerAnglesToRef(t,e,r,i){return Quaternion.RotationYawPitchRollToRef(e,t,r,i),i}static FromEulerVector(t){let e=new Quaternion;return Quaternion.RotationYawPitchRollToRef(t._y,t._x,t._z,e),e}static FromEulerVectorToRef(t,e){return Quaternion.RotationYawPitchRollToRef(t._y,t._x,t._z,e),e}static FromUnitVectorsToRef(t,e,r,i=s.kn){let o=Vector3.Dot(t,e)+1;return o<i?Math.abs(t.x)>Math.abs(t.z)?r.set(-t.y,t.x,0,0):r.set(0,-t.z,t.y,0):(Vector3.CrossToRef(t,e,TmpVectors.Vector3[0]),r.set(TmpVectors.Vector3[0].x,TmpVectors.Vector3[0].y,TmpVectors.Vector3[0].z,o)),r.normalize()}static RotationYawPitchRoll(t,e,r){let i=new Quaternion;return Quaternion.RotationYawPitchRollToRef(t,e,r,i),i}static RotationYawPitchRollToRef(t,e,r,i){let s=.5*r,o=.5*e,a=.5*t,n=Math.sin(s),h=Math.cos(s),c=Math.sin(o),_=Math.cos(o),l=Math.sin(a),u=Math.cos(a);return i._x=u*c*h+l*_*n,i._y=l*_*h-u*c*n,i._z=u*_*n-l*c*h,i._w=u*_*h+l*c*n,i._isDirty=!0,i}static RotationAlphaBetaGamma(t,e,r){let i=new Quaternion;return Quaternion.RotationAlphaBetaGammaToRef(t,e,r,i),i}static RotationAlphaBetaGammaToRef(t,e,r,i){let s=(r+t)*.5,o=(r-t)*.5,a=.5*e;return i._x=Math.cos(o)*Math.sin(a),i._y=Math.sin(o)*Math.sin(a),i._z=Math.sin(s)*Math.cos(a),i._w=Math.cos(s)*Math.cos(a),i._isDirty=!0,i}static RotationQuaternionFromAxis(t,e,r){let i=new Quaternion(0,0,0,0);return Quaternion.RotationQuaternionFromAxisToRef(t,e,r,i),i}static RotationQuaternionFromAxisToRef(t,e,r,i){let s=MathTmp.Matrix[0];return Matrix.FromXYZAxesToRef(t.normalize(),e.normalize(),r.normalize(),s),Quaternion.FromRotationMatrixToRef(s,i),i}static FromLookDirectionLH(t,e){let r=new Quaternion;return Quaternion.FromLookDirectionLHToRef(t,e,r),r}static FromLookDirectionLHToRef(t,e,r){let i=MathTmp.Matrix[0];return Matrix.LookDirectionLHToRef(t,e,i),Quaternion.FromRotationMatrixToRef(i,r),r}static FromLookDirectionRH(t,e){let r=new Quaternion;return Quaternion.FromLookDirectionRHToRef(t,e,r),r}static FromLookDirectionRHToRef(t,e,r){let i=MathTmp.Matrix[0];return Matrix.LookDirectionRHToRef(t,e,i),Quaternion.FromRotationMatrixToRef(i,r)}static Slerp(t,e,r){let i=Quaternion.Identity();return Quaternion.SlerpToRef(t,e,r,i),i}static SlerpToRef(t,e,r,i){let s,o;let a=t._x*e._x+t._y*e._y+t._z*e._z+t._w*e._w,n=!1;if(a<0&&(n=!0,a=-a),a>.999999)o=1-r,s=n?-r:r;else{let t=Math.acos(a),e=1/Math.sin(t);o=Math.sin((1-r)*t)*e,s=n?-Math.sin(r*t)*e:Math.sin(r*t)*e}return i._x=o*t._x+s*e._x,i._y=o*t._y+s*e._y,i._z=o*t._z+s*e._z,i._w=o*t._w+s*e._w,i._isDirty=!0,i}static Hermite(t,e,r,i,s){let o=s*s,a=s*o,n=2*a-3*o+1,h=-2*a+3*o,c=a-2*o+s,_=a-o,l=t._x*n+r._x*h+e._x*c+i._x*_,u=t._y*n+r._y*h+e._y*c+i._y*_,y=t._z*n+r._z*h+e._z*c+i._z*_,m=t._w*n+r._w*h+e._w*c+i._w*_;return new t.constructor(l,u,y,m)}static Hermite1stDerivative(t,e,r,i,s){let o=new t.constructor;return this.Hermite1stDerivativeToRef(t,e,r,i,s,o),o}static Hermite1stDerivativeToRef(t,e,r,i,s,o){let a=s*s;return o._x=(a-s)*6*t._x+(3*a-4*s+1)*e._x+(-a+s)*6*r._x+(3*a-2*s)*i._x,o._y=(a-s)*6*t._y+(3*a-4*s+1)*e._y+(-a+s)*6*r._y+(3*a-2*s)*i._y,o._z=(a-s)*6*t._z+(3*a-4*s+1)*e._z+(-a+s)*6*r._z+(3*a-2*s)*i._z,o._w=(a-s)*6*t._w+(3*a-4*s+1)*e._w+(-a+s)*6*r._w+(3*a-2*s)*i._w,o._isDirty=!0,o}};let Matrix=class Matrix{static get Use64Bits(){return n.Z.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=Matrix._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(t,e=!1,r=!1,i=!0){this._isIdentity=t,this._isIdentity3x2=t||r,this._isIdentityDirty=!this._isIdentity&&e,this._isIdentity3x2Dirty=!this._isIdentity3x2&&i}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,n.Z.MatrixTrackPrecisionChange&&n.Z.MatrixTrackedMatrices.push(this),this._m=new n.Z.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;let t=this._m;this._isIdentity=1===t[0]&&0===t[1]&&0===t[2]&&0===t[3]&&0===t[4]&&1===t[5]&&0===t[6]&&0===t[7]&&0===t[8]&&0===t[9]&&1===t[10]&&0===t[11]&&0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]?this._isIdentity3x2=!1:0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;let t=this._m,e=t[0],r=t[1],i=t[2],s=t[3],o=t[4],a=t[5],n=t[6],h=t[7],c=t[8],_=t[9],l=t[10],u=t[11],y=t[12],m=t[13],x=t[14],R=t[15],T=l*R-x*u,f=_*R-m*u,d=_*x-m*l,p=c*R-y*u,z=c*x-l*y,M=c*m-y*_;return e*+(a*T-n*f+h*d)+-(r*(o*T-n*p+h*z))+i*+(o*f-a*p+h*M)+-(s*(o*d-a*z+n*M))}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} +${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]} +${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]} +${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return Matrix.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(t){let e=new this.constructor;return this.addToRef(t,e),e}addToRef(t,e){let r=this._m,i=e._m,s=t.m;for(let t=0;t<16;t++)i[t]=r[t]+s[t];return e.markAsUpdated(),e}addToSelf(t){let e=this._m,r=t.m;for(let t=0;t<16;t++)e[t]+=r[t];return this.markAsUpdated(),this}invertToRef(t){if(!0===this._isIdentity)return Matrix.IdentityToRef(t),t;let e=this._m,r=e[0],i=e[1],s=e[2],o=e[3],a=e[4],n=e[5],h=e[6],c=e[7],_=e[8],l=e[9],u=e[10],y=e[11],m=e[12],x=e[13],R=e[14],T=e[15],f=u*T-R*y,d=l*T-x*y,p=l*R-x*u,z=_*T-m*y,M=_*R-u*m,w=_*x-m*l,F=+(n*f-h*d+c*p),V=-(a*f-h*z+c*M),I=+(a*d-n*z+c*w),g=-(a*p-n*M+h*w),A=r*F+i*V+s*I+o*g;if(0===A)return t.copyFrom(this),t;let D=1/A,P=h*T-R*c,C=n*T-x*c,L=n*R-x*h,O=a*T-m*c,H=a*R-m*h,k=a*x-m*n,v=h*y-u*c,Q=n*y-l*c,S=n*u-l*h,B=a*y-_*c,b=a*u-_*h,E=a*l-_*n;return Matrix.FromValuesToRef(F*D,-(i*f-s*d+o*p)*D,+(i*P-s*C+o*L)*D,-(i*v-s*Q+o*S)*D,V*D,+(r*f-s*z+o*M)*D,-(r*P-s*O+o*H)*D,+(r*v-s*B+o*b)*D,I*D,-(r*d-i*z+o*w)*D,+(r*C-i*O+o*k)*D,-(r*Q-i*B+o*E)*D,g*D,+(r*p-i*M+s*w)*D,-(r*L-i*H+s*k)*D,+(r*S-i*b+s*E)*D,t),t}addAtIndex(t,e){return this._m[t]+=e,this.markAsUpdated(),this}multiplyAtIndex(t,e){return this._m[t]*=e,this.markAsUpdated(),this}setTranslationFromFloats(t,e,r){return this._m[12]=t,this._m[13]=e,this._m[14]=r,this.markAsUpdated(),this}addTranslationFromFloats(t,e,r){return this._m[12]+=t,this._m[13]+=e,this._m[14]+=r,this.markAsUpdated(),this}setTranslation(t){return this.setTranslationFromFloats(t._x,t._y,t._z)}getTranslation(){return new Vector3(this._m[12],this._m[13],this._m[14])}getTranslationToRef(t){return t.x=this._m[12],t.y=this._m[13],t.z=this._m[14],t}removeRotationAndScaling(){let t=this.m;return Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t[12],t[13],t[14],t[15],this),this._updateIdentityStatus(0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]),this}multiply(t){let e=new this.constructor;return this.multiplyToRef(t,e),e}copyFrom(t){return t.copyToArray(this._m),this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(t,e=0){let r=this._m;return t[e]=r[0],t[e+1]=r[1],t[e+2]=r[2],t[e+3]=r[3],t[e+4]=r[4],t[e+5]=r[5],t[e+6]=r[6],t[e+7]=r[7],t[e+8]=r[8],t[e+9]=r[9],t[e+10]=r[10],t[e+11]=r[11],t[e+12]=r[12],t[e+13]=r[13],t[e+14]=r[14],t[e+15]=r[15],this}multiplyToRef(t,e){return this._isIdentity?e.copyFrom(t):t._isIdentity?e.copyFrom(this):(this.multiplyToArray(t,e._m,0),e.markAsUpdated()),e}multiplyToArray(t,e,r){let i=this._m,s=t.m,o=i[0],a=i[1],n=i[2],h=i[3],c=i[4],_=i[5],l=i[6],u=i[7],y=i[8],m=i[9],x=i[10],R=i[11],T=i[12],f=i[13],d=i[14],p=i[15],z=s[0],M=s[1],w=s[2],F=s[3],V=s[4],I=s[5],g=s[6],A=s[7],D=s[8],P=s[9],C=s[10],L=s[11],O=s[12],H=s[13],k=s[14],v=s[15];return e[r]=o*z+a*V+n*D+h*O,e[r+1]=o*M+a*I+n*P+h*H,e[r+2]=o*w+a*g+n*C+h*k,e[r+3]=o*F+a*A+n*L+h*v,e[r+4]=c*z+_*V+l*D+u*O,e[r+5]=c*M+_*I+l*P+u*H,e[r+6]=c*w+_*g+l*C+u*k,e[r+7]=c*F+_*A+l*L+u*v,e[r+8]=y*z+m*V+x*D+R*O,e[r+9]=y*M+m*I+x*P+R*H,e[r+10]=y*w+m*g+x*C+R*k,e[r+11]=y*F+m*A+x*L+R*v,e[r+12]=T*z+f*V+d*D+p*O,e[r+13]=T*M+f*I+d*P+p*H,e[r+14]=T*w+f*g+d*C+p*k,e[r+15]=T*F+f*A+d*L+p*v,this}equals(t){if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;let e=this.m,r=t.m;return e[0]===r[0]&&e[1]===r[1]&&e[2]===r[2]&&e[3]===r[3]&&e[4]===r[4]&&e[5]===r[5]&&e[6]===r[6]&&e[7]===r[7]&&e[8]===r[8]&&e[9]===r[9]&&e[10]===r[10]&&e[11]===r[11]&&e[12]===r[12]&&e[13]===r[13]&&e[14]===r[14]&&e[15]===r[15]}clone(){let t=new this.constructor;return t.copyFrom(this),t}getClassName(){return"Matrix"}getHashCode(){let t=_ExtractAsInt(this._m[0]);for(let e=1;e<16;e++)t=397*t^_ExtractAsInt(this._m[e]);return t}decomposeToTransformNode(t){return t.rotationQuaternion=t.rotationQuaternion||new Quaternion,this.decompose(t.scaling,t.rotationQuaternion,t.position)}decompose(t,e,r,i){if(this._isIdentity)return r&&r.setAll(0),t&&t.setAll(1),e&&e.copyFromFloats(0,0,0,1),!0;let s=this._m;if(r&&r.copyFromFloats(s[12],s[13],s[14]),(t=t||MathTmp.Vector3[0]).x=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]),t.y=Math.sqrt(s[4]*s[4]+s[5]*s[5]+s[6]*s[6]),t.z=Math.sqrt(s[8]*s[8]+s[9]*s[9]+s[10]*s[10]),i){let e=i.absoluteScaling.x<0?-1:1,r=i.absoluteScaling.y<0?-1:1,s=i.absoluteScaling.z<0?-1:1;t.x*=e,t.y*=r,t.z*=s}else 0>=this.determinant()&&(t.y*=-1);if(0===t._x||0===t._y||0===t._z)return e&&e.copyFromFloats(0,0,0,1),!1;if(e){let r=1/t._x,i=1/t._y,o=1/t._z;Matrix.FromValuesToRef(s[0]*r,s[1]*r,s[2]*r,0,s[4]*i,s[5]*i,s[6]*i,0,s[8]*o,s[9]*o,s[10]*o,0,0,0,0,1,MathTmp.Matrix[0]),Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0],e)}return!0}getRow(t){if(t<0||t>3)return null;let e=4*t;return new Vector4(this._m[e+0],this._m[e+1],this._m[e+2],this._m[e+3])}getRowToRef(t,e){if(t>=0&&t<3){let r=4*t;e.x=this._m[r+0],e.y=this._m[r+1],e.z=this._m[r+2],e.w=this._m[r+3]}return e}setRow(t,e){return this.setRowFromFloats(t,e.x,e.y,e.z,e.w)}transpose(){let t=new this.constructor;return Matrix.TransposeToRef(this,t),t}transposeToRef(t){return Matrix.TransposeToRef(this,t),t}setRowFromFloats(t,e,r,i,s){if(t<0||t>3)return this;let o=4*t;return this._m[o+0]=e,this._m[o+1]=r,this._m[o+2]=i,this._m[o+3]=s,this.markAsUpdated(),this}scale(t){let e=new this.constructor;return this.scaleToRef(t,e),e}scaleToRef(t,e){for(let r=0;r<16;r++)e._m[r]=this._m[r]*t;return e.markAsUpdated(),e}scaleAndAddToRef(t,e){for(let r=0;r<16;r++)e._m[r]+=this._m[r]*t;return e.markAsUpdated(),e}toNormalMatrix(t){let e=MathTmp.Matrix[0];this.invertToRef(e),e.transposeToRef(t);let r=t._m;return Matrix.FromValuesToRef(r[0],r[1],r[2],0,r[4],r[5],r[6],0,r[8],r[9],r[10],0,0,0,0,1,t),t}getRotationMatrix(){let t=new this.constructor;return this.getRotationMatrixToRef(t),t}getRotationMatrixToRef(t){let e=MathTmp.Vector3[0];if(!this.decompose(e))return Matrix.IdentityToRef(t),t;let r=this._m,i=1/e._x,s=1/e._y,o=1/e._z;return Matrix.FromValuesToRef(r[0]*i,r[1]*i,r[2]*i,0,r[4]*s,r[5]*s,r[6]*s,0,r[8]*o,r[9]*o,r[10]*o,0,0,0,0,1,t),t}toggleModelMatrixHandInPlace(){let t=this._m;return t[2]*=-1,t[6]*=-1,t[8]*=-1,t[9]*=-1,t[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){let t=this._m;return t[8]*=-1,t[9]*=-1,t[10]*=-1,t[11]*=-1,this.markAsUpdated(),this}static FromArray(t,e=0){let r=new Matrix;return Matrix.FromArrayToRef(t,e,r),r}static FromArrayToRef(t,e,r){for(let i=0;i<16;i++)r._m[i]=t[i+e];return r.markAsUpdated(),r}static FromFloat32ArrayToRefScaled(t,e,r,i){for(let s=0;s<16;s++)i._m[s]=t[s+e]*r;return i.markAsUpdated(),i}static get IdentityReadOnly(){return Matrix._IdentityReadOnly}static FromValuesToRef(t,e,r,i,s,o,a,n,h,c,_,l,u,y,m,x,R){let T=R._m;T[0]=t,T[1]=e,T[2]=r,T[3]=i,T[4]=s,T[5]=o,T[6]=a,T[7]=n,T[8]=h,T[9]=c,T[10]=_,T[11]=l,T[12]=u,T[13]=y,T[14]=m,T[15]=x,R.markAsUpdated()}static FromValues(t,e,r,i,s,o,a,n,h,c,_,l,u,y,m,x){let R=new Matrix,T=R._m;return T[0]=t,T[1]=e,T[2]=r,T[3]=i,T[4]=s,T[5]=o,T[6]=a,T[7]=n,T[8]=h,T[9]=c,T[10]=_,T[11]=l,T[12]=u,T[13]=y,T[14]=m,T[15]=x,R.markAsUpdated(),R}static Compose(t,e,r){let i=new Matrix;return Matrix.ComposeToRef(t,e,r,i),i}static ComposeToRef(t,e,r,i){let s=i._m,o=e._x,a=e._y,n=e._z,h=e._w,c=o+o,_=a+a,l=n+n,u=o*c,y=o*_,m=o*l,x=a*_,R=a*l,T=n*l,f=h*c,d=h*_,p=h*l,z=t._x,M=t._y,w=t._z;return s[0]=(1-(x+T))*z,s[1]=(y+p)*z,s[2]=(m-d)*z,s[3]=0,s[4]=(y-p)*M,s[5]=(1-(u+T))*M,s[6]=(R+f)*M,s[7]=0,s[8]=(m+d)*w,s[9]=(R-f)*w,s[10]=(1-(u+x))*w,s[11]=0,s[12]=r._x,s[13]=r._y,s[14]=r._z,s[15]=1,i.markAsUpdated(),i}static Identity(){let t=Matrix.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return t._updateIdentityStatus(!0),t}static IdentityToRef(t){return Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(!0),t}static Zero(){let t=Matrix.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return t._updateIdentityStatus(!1),t}static RotationX(t){let e=new Matrix;return Matrix.RotationXToRef(t,e),e}static Invert(t){let e=new t.constructor;return t.invertToRef(e),e}static RotationXToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return Matrix.FromValuesToRef(1,0,0,0,0,i,r,0,0,-r,i,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationY(t){let e=new Matrix;return Matrix.RotationYToRef(t,e),e}static RotationYToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return Matrix.FromValuesToRef(i,0,-r,0,0,1,0,0,r,0,i,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationZ(t){let e=new Matrix;return Matrix.RotationZToRef(t,e),e}static RotationZToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return Matrix.FromValuesToRef(i,r,0,0,-r,i,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationAxis(t,e){let r=new Matrix;return Matrix.RotationAxisToRef(t,e,r),r}static RotationAxisToRef(t,e,r){let i=Math.sin(-e),s=Math.cos(-e),o=1-s;t.normalize();let a=r._m;return a[0]=t._x*t._x*o+s,a[1]=t._x*t._y*o-t._z*i,a[2]=t._x*t._z*o+t._y*i,a[3]=0,a[4]=t._y*t._x*o+t._z*i,a[5]=t._y*t._y*o+s,a[6]=t._y*t._z*o-t._x*i,a[7]=0,a[8]=t._z*t._x*o-t._y*i,a[9]=t._z*t._y*o+t._x*i,a[10]=t._z*t._z*o+s,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,r.markAsUpdated(),r}static RotationAlignToRef(t,e,r,i=!1){let o=Vector3.Dot(e,t),a=r._m;if(o<-1+s.kn)a[0]=-1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=i?1:-1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=i?-1:1,a[11]=0;else{let r=Vector3.Cross(e,t),i=1/(1+o);a[0]=r._x*r._x*i+o,a[1]=r._y*r._x*i-r._z,a[2]=r._z*r._x*i+r._y,a[3]=0,a[4]=r._x*r._y*i+r._z,a[5]=r._y*r._y*i+o,a[6]=r._z*r._y*i-r._x,a[7]=0,a[8]=r._x*r._z*i-r._y,a[9]=r._y*r._z*i+r._x,a[10]=r._z*r._z*i+o,a[11]=0}return a[12]=0,a[13]=0,a[14]=0,a[15]=1,r.markAsUpdated(),r}static RotationYawPitchRoll(t,e,r){let i=new Matrix;return Matrix.RotationYawPitchRollToRef(t,e,r,i),i}static RotationYawPitchRollToRef(t,e,r,i){return Quaternion.RotationYawPitchRollToRef(t,e,r,MathTmp.Quaternion[0]),MathTmp.Quaternion[0].toRotationMatrix(i),i}static Scaling(t,e,r){let i=new Matrix;return Matrix.ScalingToRef(t,e,r,i),i}static ScalingToRef(t,e,r,i){return Matrix.FromValuesToRef(t,0,0,0,0,e,0,0,0,0,r,0,0,0,0,1,i),i._updateIdentityStatus(1===t&&1===e&&1===r),i}static Translation(t,e,r){let i=new Matrix;return Matrix.TranslationToRef(t,e,r,i),i}static TranslationToRef(t,e,r,i){return Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,e,r,1,i),i._updateIdentityStatus(0===t&&0===e&&0===r),i}static Lerp(t,e,r){let i=new t.constructor;return Matrix.LerpToRef(t,e,r,i),i}static LerpToRef(t,e,r,i){let s=i._m,o=t.m,a=e.m;for(let t=0;t<16;t++)s[t]=o[t]*(1-r)+a[t]*r;return i.markAsUpdated(),i}static DecomposeLerp(t,e,r){let i=new t.constructor;return Matrix.DecomposeLerpToRef(t,e,r,i),i}static DecomposeLerpToRef(t,e,r,i){let s=MathTmp.Vector3[0],o=MathTmp.Quaternion[0],a=MathTmp.Vector3[1];t.decompose(s,o,a);let n=MathTmp.Vector3[2],h=MathTmp.Quaternion[1],c=MathTmp.Vector3[3];e.decompose(n,h,c);let _=MathTmp.Vector3[4];Vector3.LerpToRef(s,n,r,_);let l=MathTmp.Quaternion[2];Quaternion.SlerpToRef(o,h,r,l);let u=MathTmp.Vector3[5];return Vector3.LerpToRef(a,c,r,u),Matrix.ComposeToRef(_,l,u,i),i}static LookAtLH(t,e,r){let i=new Matrix;return Matrix.LookAtLHToRef(t,e,r,i),i}static LookAtLHToRef(t,e,r,i){let s=MathTmp.Vector3[0],o=MathTmp.Vector3[1],a=MathTmp.Vector3[2];e.subtractToRef(t,a),a.normalize(),Vector3.CrossToRef(r,a,s);let n=s.lengthSquared();0===n?s.x=1:s.normalizeFromLength(Math.sqrt(n)),Vector3.CrossToRef(a,s,o),o.normalize();let h=-Vector3.Dot(s,t),c=-Vector3.Dot(o,t),_=-Vector3.Dot(a,t);Matrix.FromValuesToRef(s._x,o._x,a._x,0,s._y,o._y,a._y,0,s._z,o._z,a._z,0,h,c,_,1,i)}static LookAtRH(t,e,r){let i=new Matrix;return Matrix.LookAtRHToRef(t,e,r,i),i}static LookAtRHToRef(t,e,r,i){let s=MathTmp.Vector3[0],o=MathTmp.Vector3[1],a=MathTmp.Vector3[2];t.subtractToRef(e,a),a.normalize(),Vector3.CrossToRef(r,a,s);let n=s.lengthSquared();0===n?s.x=1:s.normalizeFromLength(Math.sqrt(n)),Vector3.CrossToRef(a,s,o),o.normalize();let h=-Vector3.Dot(s,t),c=-Vector3.Dot(o,t),_=-Vector3.Dot(a,t);return Matrix.FromValuesToRef(s._x,o._x,a._x,0,s._y,o._y,a._y,0,s._z,o._z,a._z,0,h,c,_,1,i),i}static LookDirectionLH(t,e){let r=new Matrix;return Matrix.LookDirectionLHToRef(t,e,r),r}static LookDirectionLHToRef(t,e,r){let i=MathTmp.Vector3[0];i.copyFrom(t),i.scaleInPlace(-1);let s=MathTmp.Vector3[1];return Vector3.CrossToRef(e,i,s),Matrix.FromValuesToRef(s._x,s._y,s._z,0,e._x,e._y,e._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static LookDirectionRH(t,e){let r=new Matrix;return Matrix.LookDirectionRHToRef(t,e,r),r}static LookDirectionRHToRef(t,e,r){let i=MathTmp.Vector3[2];return Vector3.CrossToRef(e,t,i),Matrix.FromValuesToRef(i._x,i._y,i._z,0,e._x,e._y,e._z,0,t._x,t._y,t._z,0,0,0,0,1,r),r}static OrthoLH(t,e,r,i,s){let o=new Matrix;return Matrix.OrthoLHToRef(t,e,r,i,o,s),o}static OrthoLHToRef(t,e,r,i,s,o){let a=2/t,n=2/e,h=2/(i-r),_=-(i+r)/(i-r);return Matrix.FromValuesToRef(a,0,0,0,0,n,0,0,0,0,h,0,0,0,_,1,s),o&&s.multiplyToRef(c,s),s._updateIdentityStatus(1===a&&1===n&&1===h&&0===_),s}static OrthoOffCenterLH(t,e,r,i,s,o,a){let n=new Matrix;return Matrix.OrthoOffCenterLHToRef(t,e,r,i,s,o,n,a),n}static OrthoOffCenterLHToRef(t,e,r,i,s,o,a,n){return Matrix.FromValuesToRef(2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,2/(o-s),0,(t+e)/(t-e),(i+r)/(r-i),-(o+s)/(o-s),1,a),n&&a.multiplyToRef(c,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(t,e,r,i,s,o,a,n,h,c,_){let l=-a*Math.cos(n),u=-a*Math.sin(n);return Matrix.TranslationToRef(0,0,-h,MathTmp.Matrix[1]),Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,l,u,1,0,0,0,0,1,MathTmp.Matrix[0]),MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0],MathTmp.Matrix[0]),Matrix.TranslationToRef(0,0,h,MathTmp.Matrix[1]),MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1],MathTmp.Matrix[0]),Matrix.OrthoOffCenterLHToRef(t,e,r,i,s,o,c,_),MathTmp.Matrix[0].multiplyToRef(c,c),c}static OrthoOffCenterRH(t,e,r,i,s,o,a){let n=new Matrix;return Matrix.OrthoOffCenterRHToRef(t,e,r,i,s,o,n,a),n}static OrthoOffCenterRHToRef(t,e,r,i,s,o,a,n){return Matrix.OrthoOffCenterLHToRef(t,e,r,i,s,o,a,n),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(t,e,r,i,s,o,a,n,h,c,_){let l=a*Math.cos(n),u=a*Math.sin(n);return Matrix.TranslationToRef(0,0,h,MathTmp.Matrix[1]),Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,l,u,1,0,0,0,0,1,MathTmp.Matrix[0]),MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0],MathTmp.Matrix[0]),Matrix.TranslationToRef(0,0,-h,MathTmp.Matrix[1]),MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1],MathTmp.Matrix[0]),Matrix.OrthoOffCenterRHToRef(t,e,r,i,s,o,c,_),MathTmp.Matrix[0].multiplyToRef(c,c),c}static PerspectiveLH(t,e,r,i,s,o=0){let a=new Matrix,n=Math.tan(o);return Matrix.FromValuesToRef(2*r/t,0,0,0,0,2*r/e,0,n,0,0,(i+r)/(i-r),1,0,0,-2*i*r/(i-r),0,a),s&&a.multiplyToRef(c,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(t,e,r,i,s,o=0,a=!1){let n=new Matrix;return Matrix.PerspectiveFovLHToRef(t,e,r,i,n,!0,s,o,a),n}static PerspectiveFovLHToRef(t,e,r,i,s,o=!0,a,n=0,h=!1){let _=1/Math.tan(.5*t),l=o?_/e:_,u=o?_:_*e,y=h&&0===r?-1:0!==i?(i+r)/(i-r):1,m=h&&0===r?2*i:0!==i?-2*i*r/(i-r):-2*r,x=Math.tan(n);return Matrix.FromValuesToRef(l,0,0,0,0,u,0,x,0,0,y,1,0,0,m,0,s),a&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(t,e,r,i,s,o=!0,a,n=0){let h=1/Math.tan(.5*t),_=o?h/e:h,l=o?h:h*e,u=Math.tan(n);return Matrix.FromValuesToRef(_,0,0,0,0,l,0,u,0,0,-r,1,0,0,1,0,s),a&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(t,e,r,i,s,o=0,a=!1){let n=new Matrix;return Matrix.PerspectiveFovRHToRef(t,e,r,i,n,!0,s,o,a),n}static PerspectiveFovRHToRef(t,e,r,i,s,o=!0,a,n=0,h=!1){let _=1/Math.tan(.5*t),l=o?_/e:_,u=o?_:_*e,y=h&&0===r?1:0!==i?-(i+r)/(i-r):-1,m=h&&0===r?2*i:0!==i?-2*i*r/(i-r):-2*r,x=Math.tan(n);return Matrix.FromValuesToRef(l,0,0,0,0,u,0,x,0,0,y,-1,0,0,m,0,s),a&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(t,e,r,i,s,o=!0,a,n=0){let h=1/Math.tan(.5*t),_=o?h/e:h,l=o?h:h*e,u=Math.tan(n);return Matrix.FromValuesToRef(_,0,0,0,0,l,0,u,0,0,-r,-1,0,0,-1,0,s),a&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(t,e,r,i,s,o){let a=t.width,n=t.height,h=t.x,c=t.y,_=Matrix.FromValues(a/2,0,0,0,0,-n/2,0,0,0,0,o-s,0,h+a/2,n/2+c,s,1),l=new e.constructor;return e.multiplyToRef(r,l),l.multiplyToRef(i,l),l.multiplyToRef(_,l)}static GetAsMatrix2x2(t){let e=t.m,r=[e[0],e[1],e[4],e[5]];return n.Z.MatrixUse64Bits?r:new Float32Array(r)}static GetAsMatrix3x3(t){let e=t.m,r=[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]];return n.Z.MatrixUse64Bits?r:new Float32Array(r)}static Transpose(t){let e=new t.constructor;return Matrix.TransposeToRef(t,e),e}static TransposeToRef(t,e){let r=t.m,i=r[0],s=r[4],o=r[8],a=r[12],n=r[1],h=r[5],c=r[9],_=r[13],l=r[2],u=r[6],y=r[10],m=r[14],x=r[3],R=r[7],T=r[11],f=r[15],d=e._m;return d[0]=i,d[1]=s,d[2]=o,d[3]=a,d[4]=n,d[5]=h,d[6]=c,d[7]=_,d[8]=l,d[9]=u,d[10]=y,d[11]=m,d[12]=x,d[13]=R,d[14]=T,d[15]=f,e.markAsUpdated(),e._updateIdentityStatus(t._isIdentity,t._isIdentityDirty),e}static Reflection(t){let e=new Matrix;return Matrix.ReflectionToRef(t,e),e}static ReflectionToRef(t,e){t.normalize();let r=t.normal.x,i=t.normal.y,s=t.normal.z,o=-2*r,a=-2*i,n=-2*s;return Matrix.FromValuesToRef(o*r+1,a*r,n*r,0,o*i,a*i+1,n*i,0,o*s,a*s,n*s+1,0,o*t.d,a*t.d,n*t.d,1,e),e}static FromXYZAxesToRef(t,e,r,i){return Matrix.FromValuesToRef(t._x,t._y,t._z,0,e._x,e._y,e._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static FromQuaternionToRef(t,e){let r=t._x*t._x,i=t._y*t._y,s=t._z*t._z,o=t._x*t._y,a=t._z*t._w,n=t._z*t._x,h=t._y*t._w,c=t._y*t._z,_=t._x*t._w;return e._m[0]=1-2*(i+s),e._m[1]=2*(o+a),e._m[2]=2*(n-h),e._m[3]=0,e._m[4]=2*(o-a),e._m[5]=1-2*(s+r),e._m[6]=2*(c+_),e._m[7]=0,e._m[8]=2*(n+h),e._m[9]=2*(c-_),e._m[10]=1-2*(i+r),e._m[11]=0,e._m[12]=0,e._m[13]=0,e._m[14]=0,e._m[15]=1,e.markAsUpdated(),e}};Matrix._UpdateFlagSeed=0,Matrix._IdentityReadOnly=Matrix.Identity();let MathTmp=class MathTmp{};MathTmp.Vector3=o.B.BuildTuple(11,Vector3.Zero),MathTmp.Matrix=o.B.BuildTuple(2,Matrix.Identity),MathTmp.Quaternion=o.B.BuildTuple(3,Quaternion.Zero);let TmpVectors=class TmpVectors{};TmpVectors.Vector2=o.B.BuildTuple(3,Vector2.Zero),TmpVectors.Vector3=o.B.BuildTuple(13,Vector3.Zero),TmpVectors.Vector4=o.B.BuildTuple(3,Vector4.Zero),TmpVectors.Quaternion=o.B.BuildTuple(2,Quaternion.Zero),TmpVectors.Matrix=o.B.BuildTuple(8,Matrix.Identity),(0,a.H)("BABYLON.Vector2",Vector2),(0,a.H)("BABYLON.Vector3",Vector3),(0,a.H)("BABYLON.Vector4",Vector4),(0,a.H)("BABYLON.Matrix",Matrix);let c=Matrix.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1)}}]); \ No newline at end of file diff --git a/.next/static/chunks/716.9317a587abbcf60a.js b/.next/static/chunks/716.9317a587abbcf60a.js deleted file mode 100644 index 76c5d25..0000000 --- a/.next/static/chunks/716.9317a587abbcf60a.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[716],{6716:function(n,e,r){r.r(e),r.d(e,{default:function(){return o}});var t=r(9268),i=r(6006),s=r(870),a=r(553);class o extends i.PureComponent{componentDidMount(){console.clear(),this.setup(this.canvas)}render(){return(0,t.jsx)(t.Fragment,{children:(0,t.jsx)("canvas",{id:this.id,ref:this.onMount,style:f})})}constructor(...n){super(...n),this.setup=async n=>{s.vGS.ShadersStoreWGSL.starsPixelShader="\n uniform seed : f32;\n uniform density : f32;\n uniform brightness : f32;\n\n fn rand(seed : vec2<f32>) -> f32 {\n return fract(sin(dot(seed, vec2(12.9898, 78.233))) * 43758.5453);\n }\n\n @fragment\n fn main(input : FragmentInputs) -> FragmentOutputs {\n\n let random = rand(input.vUV*uniforms.seed);\n var brightness = 0.0;\n if (random < uniforms.density){\n brightness = random/uniforms.density*uniforms.brightness;\n }\n //fragmentOutputs.color = vec4(1., 1., 1., brightness);\n fragmentOutputs.color = vec4(brightness, brightness, brightness, 1.);\n }\n ",s.vGS.ShadersStoreWGSL.nebulasPixelShader="\n var textureSampler: texture_2d<f32>;\n var textureSamplerSampler: sampler;\n\n uniform seed: f32;\n uniform color: vec4<f32>;\n uniform nebulascale: u32;\n uniform depth: u32;\n uniform intensity: f32;\n uniform falloff: f32;\n uniform persistence: f32;\n\n fn mod289(x: vec2<f32>) -> vec2<f32> {\n return x - floor(x * (1. / 289.)) * 289.;\n }\n \n fn mod289_3(x: vec3<f32>) -> vec3<f32> {\n return x - floor(x * (1. / 289.)) * 289.;\n }\n \n fn permute3(x: vec3<f32>) -> vec3<f32> {\n return mod289_3(((x * 34.) + 1.) * x);\n }\n \n // MIT License. \xa9 Ian McEwan, Stefan Gustavson, Munrocket\n fn simplexNoise2(v: vec2<f32>) -> f32 {\n let C = vec4(\n 0.211324865405187, // (3.0-sqrt(3.0))/6.0\n 0.366025403784439, // 0.5*(sqrt(3.0)-1.0)\n -0.577350269189626, // -1.0 + 2.0 * C.x\n 0.024390243902439 // 1.0 / 41.0\n );\n \n // First corner\n var i = floor(v + dot(v, C.yy));\n let x0 = v - i + dot(i, C.xx);\n \n // Other corners\n var i1 = select(vec2(0., 1.), vec2(1., 0.), x0.x > x0.y);\n \n // x0 = x0 - 0.0 + 0.0 * C.xx ;\n // x1 = x0 - i1 + 1.0 * C.xx ;\n // x2 = x0 - 1.0 + 2.0 * C.xx ;\n var x12 = x0.xyxy + C.xxzz;\n x12.x = x12.x - i1.x;\n x12.y = x12.y - i1.y;\n \n // Permutations\n i = mod289(i); // Avoid truncation effects in permutation\n \n var p = permute3(permute3(i.y + vec3(0., i1.y, 1.)) + i.x + vec3(0., i1.x, 1.));\n var m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), vec3(0.));\n m *= m;\n m *= m;\n \n // Gradients: 41 points uniformly over a line, mapped onto a diamond.\n // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)\n let x = 2. * fract(p * C.www) - 1.;\n let h = abs(x) - 0.5;\n let ox = floor(x + 0.5);\n let a0 = x - ox;\n \n // Normalize gradients implicitly by scaling m\n // Approximation of: m *= inversesqrt( a0*a0 + h*h );\n m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);\n \n // Compute final noise value at P\n let g = vec3(a0.x * x0.x + h.x * x0.y, a0.yz * x12.xz + h.yz * x12.yw);\n return 130. * dot(m, g);\n }\n\n fn normalNoise(v: vec2<f32>) -> f32 {\n return simplexNoise2(v)*0.5 + 0.5;\n }\n\n @fragment\n fn main(input : FragmentInputs) -> FragmentOutputs {\n let sampleColor = textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV);\n\n var offset = 0.;\n let scaledUV = (input.vUV+offset+uniforms.seed)*f32(uniforms.nebulascale)/uniforms.scale;\n\n var displace = 0.;\n var i=u32(0);\n for (i=0; i<uniforms.depth; i++){\n displace = normalNoise(scaledUV*pow(uniforms.persistence,f32(i+1))+displace);\n }\n var finalTransparency = normalNoise(scaledUV+displace);\n finalTransparency = pow(max(finalTransparency+uniforms.intensity,0), uniforms.falloff);\n\n fragmentOutputs.color = mix(sampleColor,uniforms.color,finalTransparency);\n }\n ";let e=await this.createEngine(n),r=new s.xsS(e);r.clearColor=new s.HEv(0,0,0,0);let t=new s.YfP("camera",0,0,0,new s.Pa4(0,0,0),r);a.Z.initialize(n,e,r,t),a.Z.generateFrame()},this.createEngine=async n=>{let e;return await s.fWK.IsSupportedAsync?(e=new s.fWK(n),await e.initAsync()):(console.log("WebGPU is not supported (or turned on) for this browser!"),e=new s.fWK(n)),e},this.id="Babylon",this.onMount=n=>this.canvas=n}}let f={width:window.innerWidth,height:window.innerHeight,background:"transparent"}}}]); \ No newline at end of file diff --git a/.next/static/chunks/751.591370f90aaa22a6.js b/.next/static/chunks/751.591370f90aaa22a6.js new file mode 100644 index 0000000..ed21cd4 --- /dev/null +++ b/.next/static/chunks/751.591370f90aaa22a6.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[751],{2751:function(n,e,r){r.r(e),r.d(e,{default:function(){return BabylonScene}});var t=r(7437),i=r(2265),s=r(9111),a=r(1128);let BabylonScene=class BabylonScene extends i.PureComponent{componentDidMount(){console.clear(),this.setup(this.canvas)}render(){return(0,t.jsx)(t.Fragment,{children:(0,t.jsx)("canvas",{id:this.id,ref:this.onMount,style:o})})}constructor(...n){super(...n),this.setup=async n=>{s.vGS.ShadersStoreWGSL.starsPixelShader="\n uniform seed : f32;\n uniform density : f32;\n uniform brightness : f32;\n\n fn rand(seed : vec2<f32>) -> f32 {\n return fract(sin(dot(seed, vec2(12.9898, 78.233))) * 43758.5453);\n }\n\n @fragment\n fn main(input : FragmentInputs) -> FragmentOutputs {\n\n let random = rand(input.vUV*uniforms.seed);\n var brightness = 0.0;\n if (random < uniforms.density){\n brightness = random/uniforms.density*uniforms.brightness;\n }\n //fragmentOutputs.color = vec4(1., 1., 1., brightness);\n fragmentOutputs.color = vec4(brightness, brightness, brightness, 1.);\n }\n ",s.vGS.ShadersStoreWGSL.nebulasPixelShader="\n var textureSampler: texture_2d<f32>;\n var textureSamplerSampler: sampler;\n\n uniform seed: f32;\n uniform color: vec4<f32>;\n uniform nebulascale: u32;\n uniform depth: u32;\n uniform intensity: f32;\n uniform falloff: f32;\n uniform persistence: f32;\n\n fn mod289(x: vec2<f32>) -> vec2<f32> {\n return x - floor(x * (1. / 289.)) * 289.;\n }\n \n fn mod289_3(x: vec3<f32>) -> vec3<f32> {\n return x - floor(x * (1. / 289.)) * 289.;\n }\n \n fn permute3(x: vec3<f32>) -> vec3<f32> {\n return mod289_3(((x * 34.) + 1.) * x);\n }\n \n // MIT License. \xa9 Ian McEwan, Stefan Gustavson, Munrocket\n fn simplexNoise2(v: vec2<f32>) -> f32 {\n let C = vec4(\n 0.211324865405187, // (3.0-sqrt(3.0))/6.0\n 0.366025403784439, // 0.5*(sqrt(3.0)-1.0)\n -0.577350269189626, // -1.0 + 2.0 * C.x\n 0.024390243902439 // 1.0 / 41.0\n );\n \n // First corner\n var i = floor(v + dot(v, C.yy));\n let x0 = v - i + dot(i, C.xx);\n \n // Other corners\n var i1 = select(vec2(0., 1.), vec2(1., 0.), x0.x > x0.y);\n \n // x0 = x0 - 0.0 + 0.0 * C.xx ;\n // x1 = x0 - i1 + 1.0 * C.xx ;\n // x2 = x0 - 1.0 + 2.0 * C.xx ;\n var x12 = x0.xyxy + C.xxzz;\n x12.x = x12.x - i1.x;\n x12.y = x12.y - i1.y;\n \n // Permutations\n i = mod289(i); // Avoid truncation effects in permutation\n \n var p = permute3(permute3(i.y + vec3(0., i1.y, 1.)) + i.x + vec3(0., i1.x, 1.));\n var m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), vec3(0.));\n m *= m;\n m *= m;\n \n // Gradients: 41 points uniformly over a line, mapped onto a diamond.\n // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)\n let x = 2. * fract(p * C.www) - 1.;\n let h = abs(x) - 0.5;\n let ox = floor(x + 0.5);\n let a0 = x - ox;\n \n // Normalize gradients implicitly by scaling m\n // Approximation of: m *= inversesqrt( a0*a0 + h*h );\n m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);\n \n // Compute final noise value at P\n let g = vec3(a0.x * x0.x + h.x * x0.y, a0.yz * x12.xz + h.yz * x12.yw);\n return 130. * dot(m, g);\n }\n\n fn normalNoise(v: vec2<f32>) -> f32 {\n return simplexNoise2(v)*0.5 + 0.5;\n }\n\n @fragment\n fn main(input : FragmentInputs) -> FragmentOutputs {\n let sampleColor = textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV);\n\n var offset = 0.;\n let scaledUV = (input.vUV+offset+uniforms.seed)*f32(uniforms.nebulascale)/uniforms.scale;\n\n var displace = 0.;\n var i=u32(0);\n for (i=0; i<uniforms.depth; i++){\n displace = normalNoise(scaledUV*pow(uniforms.persistence,f32(i+1))+displace);\n }\n var finalTransparency = normalNoise(scaledUV+displace);\n finalTransparency = pow(max(finalTransparency+uniforms.intensity,0), uniforms.falloff);\n\n fragmentOutputs.color = mix(sampleColor,uniforms.color,finalTransparency);\n }\n ";let e=await this.createEngine(n),r=new s.xsS(e);r.clearColor=new s.HEv(0,0,0,0);let t=new s.YfP("camera",0,0,0,new s.Pa4(0,0,0),r);a.Z.initialize(n,e,r,t),a.Z.generateFrame()},this.createEngine=async n=>{let e;return await s.fWK.IsSupportedAsync?(e=new s.fWK(n),await e.initAsync()):(console.log("WebGPU is not supported (or turned on) for this browser!"),e=new s.fWK(n)),e},this.id="Babylon",this.onMount=n=>this.canvas=n}};let o={width:window.innerWidth,height:window.innerHeight,background:"transparent"}}}]); \ No newline at end of file diff --git a/.next/static/chunks/986-37229c658d9b7b30.js b/.next/static/chunks/986-37229c658d9b7b30.js new file mode 100644 index 0000000..e04715c --- /dev/null +++ b/.next/static/chunks/986-37229c658d9b7b30.js @@ -0,0 +1,9 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[986],{413:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Image",{enumerable:!0,get:function(){return m}});let r=n(1024),i=n(8533),o=i._(n(2265)),a=r._(n(4887)),l=r._(n(5793)),u=n(7929),s=n(5751),d=n(7327);n(2637);let c=n(6304),f=r._(n(9950)),p={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1};function handleLoading(e,t,n,r,i,o){let a=null==e?void 0:e.src;if(!e||e["data-loaded-src"]===a)return;e["data-loaded-src"]=a;let l="decode"in e?e.decode():Promise.resolve();l.catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("empty"!==t&&i(!0),null==n?void 0:n.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let r=!1,i=!1;n.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>r,isPropagationStopped:()=>i,persist:()=>{},preventDefault:()=>{r=!0,t.preventDefault()},stopPropagation:()=>{i=!0,t.stopPropagation()}})}(null==r?void 0:r.current)&&r.current(e)}})}function getDynamicProps(e){let[t,n]=o.version.split(".",2),r=parseInt(t,10),i=parseInt(n,10);return r>18||18===r&&i>=3?{fetchPriority:e}:{fetchpriority:e}}let g=(0,o.forwardRef)((e,t)=>{let{src:n,srcSet:r,sizes:i,height:a,width:l,decoding:u,className:s,style:d,fetchPriority:c,placeholder:f,loading:p,unoptimized:g,fill:m,onLoadRef:h,onLoadingCompleteRef:y,setBlurComplete:b,setShowAltText:_,onLoad:v,onError:S,...w}=e;return o.default.createElement("img",{...w,...getDynamicProps(c),loading:p,width:l,height:a,decoding:u,"data-nimg":m?"fill":"1",className:s,style:d,sizes:i,srcSet:r,src:n,ref:(0,o.useCallback)(e=>{t&&("function"==typeof t?t(e):"object"==typeof t&&(t.current=e)),e&&(S&&(e.src=e.src),e.complete&&handleLoading(e,f,h,y,b,g))},[n,f,h,y,b,S,g,t]),onLoad:e=>{let t=e.currentTarget;handleLoading(t,f,h,y,b,g)},onError:e=>{_(!0),"empty"!==f&&b(!0),S&&S(e)}})});function ImagePreload(e){let{isAppRouter:t,imgAttributes:n}=e,r={as:"image",imageSrcSet:n.srcSet,imageSizes:n.sizes,crossOrigin:n.crossOrigin,referrerPolicy:n.referrerPolicy,...getDynamicProps(n.fetchPriority)};return t&&a.default.preload?(a.default.preload(n.src,r),null):o.default.createElement(l.default,null,o.default.createElement("link",{key:"__nimg-"+n.src+n.srcSet+n.sizes,rel:"preload",href:n.srcSet?void 0:n.src,...r}))}let m=(0,o.forwardRef)((e,t)=>{let n=(0,o.useContext)(c.RouterContext),r=(0,o.useContext)(d.ImageConfigContext),i=(0,o.useMemo)(()=>{let e=p||r||s.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),n=e.deviceSizes.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:n}},[r]),{onLoad:a,onLoadingComplete:l}=e,m=(0,o.useRef)(a);(0,o.useEffect)(()=>{m.current=a},[a]);let h=(0,o.useRef)(l);(0,o.useEffect)(()=>{h.current=l},[l]);let[y,b]=(0,o.useState)(!1),[_,v]=(0,o.useState)(!1),{props:S,meta:w}=(0,u.getImgProps)(e,{defaultLoader:f.default,imgConf:i,blurComplete:y,showAltText:_});return o.default.createElement(o.default.Fragment,null,o.default.createElement(g,{...S,unoptimized:w.unoptimized,placeholder:w.placeholder,fill:w.fill,onLoadRef:m,onLoadingCompleteRef:h,setBlurComplete:b,setShowAltText:v,ref:t}),w.priority?o.default.createElement(ImagePreload,{isAppRouter:!n,imgAttributes:S}):null)});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8569:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AmpStateContext",{enumerable:!0,get:function(){return o}});let r=n(1024),i=r._(n(2265)),o=i.default.createContext({})},4472:function(e,t){"use strict";function isInAmpMode(e){let{ampFirst:t=!1,hybrid:n=!1,hasQuery:r=!1}=void 0===e?{}:e;return t||n&&r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return isInAmpMode}})},7929:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImgProps",{enumerable:!0,get:function(){return getImgProps}}),n(2637);let r=n(1511),i=n(5751);function isStaticRequire(e){return void 0!==e.default}function isStaticImageData(e){return void 0!==e.src}function isStaticImport(e){return"object"==typeof e&&(isStaticRequire(e)||isStaticImageData(e))}function getInt(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function getWidths(e,t,n){let{deviceSizes:r,allSizes:i}=e;if(n){let e=/(^|\s)(1?\d?\d)vw/g,t=[];for(let r;r=e.exec(n);r)t.push(parseInt(r[2]));if(t.length){let e=.01*Math.min(...t);return{widths:i.filter(t=>t>=r[0]*e),kind:"w"}}return{widths:i,kind:"w"}}if("number"!=typeof t)return{widths:r,kind:"w"};let o=[...new Set([t,2*t].map(e=>i.find(t=>t>=e)||i[i.length-1]))];return{widths:o,kind:"x"}}function generateImgAttrs(e){let{config:t,src:n,unoptimized:r,width:i,quality:o,sizes:a,loader:l}=e;if(r)return{src:n,srcSet:void 0,sizes:void 0};let{widths:u,kind:s}=getWidths(t,i,a),d=u.length-1;return{sizes:a||"w"!==s?a:"100vw",srcSet:u.map((e,r)=>l({config:t,src:n,quality:o,width:e})+" "+("w"===s?e:r+1)+s).join(", "),src:l({config:t,src:n,quality:o,width:u[d]})}}function getImgProps(e,t){let n,o,a,{src:l,sizes:u,unoptimized:s=!1,priority:d=!1,loading:c,className:f,quality:p,width:g,height:m,fill:h=!1,style:y,onLoad:b,onLoadingComplete:_,placeholder:v="empty",blurDataURL:S,fetchPriority:w,layout:P,objectFit:C,objectPosition:O,lazyBoundary:I,lazyRoot:j,...E}=e,{imgConf:x,showAltText:M,blurComplete:z,defaultLoader:k}=t,R=x||i.imageConfigDefault;if("allSizes"in R)n=R;else{let e=[...R.deviceSizes,...R.imageSizes].sort((e,t)=>e-t),t=R.deviceSizes.sort((e,t)=>e-t);n={...R,allSizes:e,deviceSizes:t}}let A=E.loader||k;delete E.loader,delete E.srcSet;let D="__next_img_default"in A;if(D){if("custom"===n.loader)throw Error('Image with src "'+l+'" is missing "loader" prop.\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader')}else{let e=A;A=t=>{let{config:n,...r}=t;return e(r)}}if(P){"fill"===P&&(h=!0);let e={intrinsic:{maxWidth:"100%",height:"auto"},responsive:{width:"100%",height:"auto"}}[P];e&&(y={...y,...e});let t={responsive:"100vw",fill:"100vw"}[P];t&&!u&&(u=t)}let L="",U=getInt(g),N=getInt(m);if(isStaticImport(l)){let e=isStaticRequire(l)?l.default:l;if(!e.src)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received "+JSON.stringify(e));if(!e.height||!e.width)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received "+JSON.stringify(e));if(o=e.blurWidth,a=e.blurHeight,S=S||e.blurDataURL,L=e.src,!h){if(U||N){if(U&&!N){let t=U/e.width;N=Math.round(e.height*t)}else if(!U&&N){let t=N/e.height;U=Math.round(e.width*t)}}else U=e.width,N=e.height}}let B=!d&&("lazy"===c||void 0===c);(!(l="string"==typeof l?l:L)||l.startsWith("data:")||l.startsWith("blob:"))&&(s=!0,B=!1),n.unoptimized&&(s=!0),D&&l.endsWith(".svg")&&!n.dangerouslyAllowSVG&&(s=!0),d&&(w="high");let F=getInt(p),T=Object.assign(h?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:C,objectPosition:O}:{},M?{}:{color:"transparent"},y),W=z||"empty"===v?null:"blur"===v?'url("data:image/svg+xml;charset=utf-8,'+(0,r.getImageBlurSvg)({widthInt:U,heightInt:N,blurWidth:o,blurHeight:a,blurDataURL:S||"",objectFit:T.objectFit})+'")':'url("'+v+'")',H=W?{backgroundSize:T.objectFit||"cover",backgroundPosition:T.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:W}:{},G=generateImgAttrs({config:n,src:l,unoptimized:s,width:U,quality:F,sizes:u,loader:A}),V={...E,loading:B?"lazy":c,fetchPriority:w,width:U,height:N,decoding:"async",className:f,style:{...T,...H},sizes:G.sizes,srcSet:G.srcSet,src:G.src},$={unoptimized:s,priority:d,placeholder:v,fill:h};return{props:V,meta:$}}},5793:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{defaultHead:function(){return defaultHead},default:function(){return c}});let r=n(1024),i=n(8533),o=i._(n(2265)),a=r._(n(110)),l=n(8569),u=n(1852),s=n(4472);function defaultHead(e){void 0===e&&(e=!1);let t=[o.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(o.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function onlyReactElement(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===o.default.Fragment?e.concat(o.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}n(2637);let d=["name","httpEquiv","charSet","itemProp"];function unique(){let e=new Set,t=new Set,n=new Set,r={};return i=>{let o=!0,a=!1;if(i.key&&"number"!=typeof i.key&&i.key.indexOf("$")>0){a=!0;let t=i.key.slice(i.key.indexOf("$")+1);e.has(t)?o=!1:e.add(t)}switch(i.type){case"title":case"base":t.has(i.type)?o=!1:t.add(i.type);break;case"meta":for(let e=0,t=d.length;e<t;e++){let t=d[e];if(i.props.hasOwnProperty(t)){if("charSet"===t)n.has(t)?o=!1:n.add(t);else{let e=i.props[t],n=r[t]||new Set;("name"!==t||!a)&&n.has(e)?o=!1:(n.add(e),r[t]=n)}}}}return o}}function reduceComponents(e,t){let{inAmpMode:n}=t;return e.reduce(onlyReactElement,[]).reverse().concat(defaultHead(n).reverse()).filter(unique()).reverse().map((e,t)=>{let r=e.key||t;if(!n&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,o.default.cloneElement(e,t)}return o.default.cloneElement(e,{key:r})})}function Head(e){let{children:t}=e,n=(0,o.useContext)(l.AmpStateContext),r=(0,o.useContext)(u.HeadManagerContext);return o.default.createElement(a.default,{reduceComponentsToState:reduceComponents,headManager:r,inAmpMode:(0,s.isInAmpMode)(n)},t)}let c=Head;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1511:function(e,t){"use strict";function getImageBlurSvg(e){let{widthInt:t,heightInt:n,blurWidth:r,blurHeight:i,blurDataURL:o,objectFit:a}=e,l=r?40*r:t,u=i?40*i:n,s=l&&u?"viewBox='0 0 "+l+" "+u+"'":"";return"%3Csvg xmlns='http://www.w3.org/2000/svg' "+s+"%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='"+(s?"none":"contain"===a?"xMidYMid":"cover"===a?"xMidYMid slice":"none")+"' style='filter: url(%23b);' href='"+o+"'/%3E%3C/svg%3E"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImageBlurSvg",{enumerable:!0,get:function(){return getImageBlurSvg}})},7327:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ImageConfigContext",{enumerable:!0,get:function(){return a}});let r=n(1024),i=r._(n(2265)),o=n(5751),a=i.default.createContext(o.imageConfigDefault)},5751:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{VALID_LOADERS:function(){return n},imageConfigDefault:function(){return r}});let n=["default","imgix","cloudinary","akamai","custom"],r={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"inline",remotePatterns:[],unoptimized:!1}},679:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{unstable_getImgProps:function(){return unstable_getImgProps},default:function(){return u}});let r=n(1024),i=n(7929),o=n(2637),a=n(413),l=r._(n(9950)),unstable_getImgProps=e=>{(0,o.warnOnce)("Warning: unstable_getImgProps() is experimental and may change or be removed at any time. Use at your own risk.");let{props:t}=(0,i.getImgProps)(e,{defaultLoader:l.default,imgConf:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1}});for(let[e,n]of Object.entries(t))void 0===n&&delete t[e];return{props:t}},u=a.Image},9950:function(e,t){"use strict";function defaultLoader(e){let{config:t,src:n,width:r,quality:i}=e;return t.path+"?url="+encodeURIComponent(n)+"&w="+r+"&q="+(i||75)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}}),defaultLoader.__next_img_default=!0;let n=defaultLoader},6304:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RouterContext",{enumerable:!0,get:function(){return o}});let r=n(1024),i=r._(n(2265)),o=i.default.createContext(null)},110:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return SideEffect}});let r=n(2265),i=r.useLayoutEffect,o=r.useEffect;function SideEffect(e){let{headManager:t,reduceComponentsToState:n}=e;function emitChange(){if(t&&t.mountedInstances){let i=r.Children.toArray(Array.from(t.mountedInstances).filter(Boolean));t.updateHead(n(i,e))}}return i(()=>{var n;return null==t||null==(n=t.mountedInstances)||n.add(e.children),()=>{var n;null==t||null==(n=t.mountedInstances)||n.delete(e.children)}}),i(()=>(t&&(t._pendingUpdate=emitChange),()=>{t&&(t._pendingUpdate=emitChange)})),o(()=>(t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null),()=>{t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null)})),null}},2637:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return warnOnce}});let warnOnce=e=>{}},622:function(e,t,n){"use strict";/** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var r=n(2265),i=Symbol.for("react.element"),o=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,l=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function q(e,t,n){var r,o={},s=null,d=null;for(r in void 0!==n&&(s=""+n),void 0!==t.key&&(s=""+t.key),void 0!==t.ref&&(d=t.ref),t)a.call(t,r)&&!u.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===o[r]&&(o[r]=t[r]);return{$$typeof:i,type:e,key:s,ref:d,props:o,_owner:l.current}}t.Fragment=o,t.jsx=q,t.jsxs=q},7437:function(e,t,n){"use strict";e.exports=n(622)},6691:function(e,t,n){e.exports=n(679)}}]); \ No newline at end of file diff --git a/.next/static/chunks/app/_not-found-fbdfab077d258bb2.js b/.next/static/chunks/app/_not-found-fbdfab077d258bb2.js new file mode 100644 index 0000000..c2ef014 --- /dev/null +++ b/.next/static/chunks/app/_not-found-fbdfab077d258bb2.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[165],{3155:function(e,t,n){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_not-found",function(){return n(1038)}])},1038:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return NotFound}});let l=n(1024),o=l._(n(2265)),r={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{display:"inline-block"},h1:{display:"inline-block",margin:"0 20px 0 0",padding:"0 23px 0 0",fontSize:24,fontWeight:500,verticalAlign:"top",lineHeight:"49px"},h2:{fontSize:14,fontWeight:400,lineHeight:"49px",margin:0}};function NotFound(){return o.default.createElement(o.default.Fragment,null,o.default.createElement("title",null,"404: This page could not be found."),o.default.createElement("div",{style:r.error},o.default.createElement("div",null,o.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}),o.default.createElement("h1",{className:"next-error-h1",style:r.h1},"404"),o.default.createElement("div",{style:r.desc},o.default.createElement("h2",{style:r.h2},"This page could not be found.")))))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)}},function(e){e.O(0,[971,472,744],function(){return e(e.s=3155)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/everyone-votes/privacy/page-29a62894605199e6.js b/.next/static/chunks/app/everyone-votes/privacy/page-29a62894605199e6.js new file mode 100644 index 0000000..0b435b5 --- /dev/null +++ b/.next/static/chunks/app/everyone-votes/privacy/page-29a62894605199e6.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[369,181,447,619],{3521:function(){}},function(n){n.O(0,[971,472,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/everyone-votes/privacy/page-4d788de82a96b899.js b/.next/static/chunks/app/everyone-votes/privacy/page-4d788de82a96b899.js deleted file mode 100644 index 4a7d9e3..0000000 --- a/.next/static/chunks/app/everyone-votes/privacy/page-4d788de82a96b899.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[527,447,181],{7155:function(){}},function(n){n.O(0,[667,488,744],function(){return n(n.s=7155)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/everyone-votes/terms/page-5aa776690a4e5edf.js b/.next/static/chunks/app/everyone-votes/terms/page-5aa776690a4e5edf.js deleted file mode 100644 index b60833f..0000000 --- a/.next/static/chunks/app/everyone-votes/terms/page-5aa776690a4e5edf.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[181,447,527],{7155:function(){}},function(n){n.O(0,[667,488,744],function(){return n(n.s=7155)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/everyone-votes/terms/page-c0da9088d7e5e9ae.js b/.next/static/chunks/app/everyone-votes/terms/page-c0da9088d7e5e9ae.js new file mode 100644 index 0000000..1fadcce --- /dev/null +++ b/.next/static/chunks/app/everyone-votes/terms/page-c0da9088d7e5e9ae.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[181,369,447,619],{3521:function(){}},function(n){n.O(0,[971,472,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/layout-3d94fcc1098e9e97.js b/.next/static/chunks/app/layout-3d94fcc1098e9e97.js deleted file mode 100644 index 3601e76..0000000 --- a/.next/static/chunks/app/layout-3d94fcc1098e9e97.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{8228:function(e,n,t){Promise.resolve().then(t.t.bind(t,915,23)),Promise.resolve().then(t.t.bind(t,6408,23))},6408:function(){},915:function(e){e.exports={style:{fontFamily:"'__Inter_0ec1f4', '__Inter_Fallback_0ec1f4'",fontStyle:"normal"},className:"__className_0ec1f4"}}},function(e){e.O(0,[667,488,744],function(){return e(e.s=8228)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/layout-ca25527909104096.js b/.next/static/chunks/app/layout-ca25527909104096.js new file mode 100644 index 0000000..8a367be --- /dev/null +++ b/.next/static/chunks/app/layout-ca25527909104096.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{7552:function(e,n,t){Promise.resolve().then(t.t.bind(t,1371,23)),Promise.resolve().then(t.t.bind(t,595,23))},595:function(){},1371:function(e){e.exports={style:{fontFamily:"'__Inter_e66fe9', '__Inter_Fallback_e66fe9'",fontStyle:"normal"},className:"__className_e66fe9"}}},function(e){e.O(0,[971,472,744],function(){return e(e.s=7552)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/page-39b6caed82efc627.js b/.next/static/chunks/app/page-39b6caed82efc627.js new file mode 100644 index 0000000..5579229 --- /dev/null +++ b/.next/static/chunks/app/page-39b6caed82efc627.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{2729:function(e,s,t){Promise.resolve().then(t.bind(t,6916))},6916:function(e,s,t){"use strict";let a;t.r(s),t.d(s,{default:function(){return Home}});var i=t(7437),o=t(2265);t(4456);var l=t(6691),n=t.n(l);function Card(e){return(0,i.jsxs)("a",{className:"w-[20rem] h-[8rem] p-2 rounded-2xl bg-slate-800 shadow-lg ".concat(e.shadow," flex flex-col flex-shrink-0 ease-out duration-300 hover:scale-105 hover:-translate-y-1 transition-all"),href:e.link,target:"_blank",children:[(0,i.jsxs)("div",{className:"flex flex-row items-center gap-1 ml-2 h-[2rem] w-full rounded-2xl",children:[(0,i.jsx)("span",{className:"text-l font-bold text-cyan-500",children:"sukadia.dev"}),(0,i.jsxs)("span",{className:"text-xl font-bold dark:text-white",children:["/ ",e.title]})]}),(0,i.jsxs)("div",{className:"flex flex-row w-full overflow-clip h-[84px]",children:[(0,i.jsx)("div",{className:"h-full aspect-square rounded-2xl relative",children:(0,i.jsx)("div",{className:"h-full w-full aspect-square relative rounded-2xl overflow-hidden",children:(0,i.jsx)(n(),{fill:!0,src:e.icon,sizes:"128px",alt:"thumbnail",className:""})})}),(0,i.jsx)("div",{className:"h-full w-full m-2 ml-4 rounded-2xl",children:(0,i.jsx)("p",{children:e.description})})]})]})}function Home(){let[e,s]=(0,o.useState)(""),t=(0,o.useRef)("undefined"!=typeof Audio?new Audio("audio/the-fabled-period-button.mp3"):void 0).current,l=0;return(0,i.jsxs)("main",{className:"select-none",children:[(0,i.jsx)("div",{className:"flex flex-col items-center h-screen overflow-hidden",children:(0,i.jsxs)("div",{className:("sukadia"==e||"dev"==e?"-translate-y-24":"")+" flex flex-row w-screen items-center justify-center overflow-hidden text-6xl min-[437px]:text-7xl min-[577px]:text-8xl md:text-9xl m-auto transition-all duration-500 z-20",children:[(0,i.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:t=>{s("sukadia"==e?"":"sukadia")},children:(0,i.jsx)("div",{id:"sukadia",className:("sukadia"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"sukadia"})}),(0,i.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:i=>{s("."==e?"":".");let o=++l;a=setTimeout(()=>{l==o&&(null==t?void 0:t.cloneNode()).play()},100)},onMouseUp:e=>{s(""),clearTimeout(a)},children:(0,i.jsx)("div",{id:".",className:("."==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"."})}),(0,i.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:t=>{s("dev"==e?"":"dev")},children:(0,i.jsx)("div",{id:"dev",className:("dev"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"dev"})})]})}),(0,i.jsx)("div",{className:("sukadia"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("sukadia"==e?"opacity-100 z-10":"opacity-0 pointer-events-none -translate-y-12 z-1")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[(0,i.jsx)(Card,{title:"Youtube",description:"Lots of VRChat videos focusing on roleplay.",icon:"/images/YoutubeIcon.png",link:"/youtube",shadow:"shadow-red-950"}),(0,i.jsx)(Card,{title:"Twitch",description:"Occasional streams for whatever seems fun at the moment.",icon:"/images/TwitchIcon.png",link:"/twitch",shadow:"shadow-violet-950"}),(0,i.jsx)(Card,{title:"Discord",description:"The hub for all my socials & projects. Join to stay updated!",icon:"/images/DiscordIcon.png",link:"/discord",shadow:"shadow-blue-900"}),(0,i.jsx)(Card,{title:"Ko-fi",description:"Support me monthly to help me make more content.",icon:"/images/KofiIcon.png",link:"/ko-fi",shadow:"shadow-sky-900"})]})}),(0,i.jsx)("div",{className:("dev"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("dev"==e?"opacity-100 z-10":"opacity-0 -translate-y-12 z-0")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[(0,i.jsx)(Card,{title:"Everyone-Votes",description:"A Discord bot that sends and tallies daily polls from thousands of servers.",icon:"/images/EveryoneVotesIcon.png",link:"/everyone-votes",shadow:"shadow-blue-900"}),(0,i.jsx)(Card,{title:"Space",description:"A WebGPU space/nebula image generator with lots of parameters to modify.",icon:"/images/SpaceIcon.png",link:"/space",shadow:"shadow-violet-950"}),(0,i.jsx)(Card,{title:"Dark",description:"A VSCode color theme based off of Brackets Dark.",icon:"/images/DarkIcon.png",link:"/dark",shadow:"shadow-yellow-950"})]})})]})}},4456:function(){}},function(e){e.O(0,[986,971,472,744],function(){return e(e.s=2729)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/page-8204c3b0f59bd205.js b/.next/static/chunks/app/page-8204c3b0f59bd205.js deleted file mode 100644 index b2bcdcb..0000000 --- a/.next/static/chunks/app/page-8204c3b0f59bd205.js +++ /dev/null @@ -1,9 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{6436:function(e,t,n){Promise.resolve().then(n.bind(n,2645))},2645:function(e,t,n){"use strict";let r;n.r(t),n.d(t,{default:function(){return d}});var i=n(9268),o=n(6006);n(4982);var a=n(6394),l=n.n(a);function s(e){return(0,i.jsxs)("a",{className:"w-[20rem] h-[8rem] p-2 rounded-2xl bg-slate-800 shadow-lg ".concat(e.shadow," flex flex-col flex-shrink-0 ease-out duration-300 hover:scale-105 hover:-translate-y-1 transition-all"),href:e.link,target:"_blank",children:[(0,i.jsxs)("div",{className:"flex flex-row items-center gap-1 ml-2 h-[2rem] w-full rounded-2xl",children:[(0,i.jsx)("span",{className:"text-l font-bold text-cyan-500",children:"sukadia.dev"}),(0,i.jsxs)("span",{className:"text-xl font-bold dark:text-white",children:["/ ",e.title]})]}),(0,i.jsxs)("div",{className:"flex flex-row w-full overflow-clip h-[84px]",children:[(0,i.jsx)("div",{className:"h-full aspect-square rounded-2xl relative",children:(0,i.jsx)("div",{className:"h-full w-full aspect-square relative rounded-2xl overflow-hidden",children:(0,i.jsx)(l(),{fill:!0,src:e.icon,sizes:"128px",alt:"thumbnail",className:""})})}),(0,i.jsx)("div",{className:"h-full w-full m-2 ml-4 rounded-2xl",children:(0,i.jsx)("p",{children:e.description})})]})]})}function d(){let[e,t]=(0,o.useState)(""),n=(0,o.useRef)("undefined"!=typeof Audio?new Audio("audio/the-fabled-period-button.mp3"):void 0).current,a=0;return(0,i.jsxs)("main",{className:"select-none",children:[(0,i.jsx)("div",{className:"flex flex-col items-center h-screen overflow-hidden",children:(0,i.jsxs)("div",{className:("sukadia"==e||"dev"==e?"-translate-y-24":"")+" flex flex-row w-screen items-center justify-center overflow-hidden text-6xl min-[437px]:text-7xl min-[577px]:text-8xl md:text-9xl m-auto transition-all duration-500 z-20",children:[(0,i.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:n=>{t("sukadia"==e?"":"sukadia")},children:(0,i.jsx)("div",{id:"sukadia",className:("sukadia"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"sukadia"})}),(0,i.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:i=>{t("."==e?"":".");let o=++a;r=setTimeout(()=>{a==o&&(null==n?void 0:n.cloneNode()).play()},100)},onMouseUp:e=>{t(""),clearTimeout(r)},children:(0,i.jsx)("div",{id:".",className:("."==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"."})}),(0,i.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:n=>{t("dev"==e?"":"dev")},children:(0,i.jsx)("div",{id:"dev",className:("dev"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"dev"})})]})}),(0,i.jsx)("div",{className:("sukadia"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("sukadia"==e?"opacity-100 z-10":"opacity-0 pointer-events-none -translate-y-12 z-1")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[(0,i.jsx)(s,{title:"Youtube",description:"Lots of VRChat videos focusing on roleplay.",icon:"/images/YoutubeIcon.png",link:"/youtube",shadow:"shadow-red-950"}),(0,i.jsx)(s,{title:"Twitch",description:"Occasional streams for whatever seems fun at the moment.",icon:"/images/TwitchIcon.png",link:"/twitch",shadow:"shadow-violet-950"}),(0,i.jsx)(s,{title:"Discord",description:"The hub for all my socials & projects. Join to stay updated!",icon:"/images/DiscordIcon.png",link:"/discord",shadow:"shadow-blue-900"}),(0,i.jsx)(s,{title:"Ko-fi",description:"Support me monthly to help me make more content.",icon:"/images/KofiIcon.png",link:"/ko-fi",shadow:"shadow-sky-900"})]})}),(0,i.jsx)("div",{className:("dev"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("dev"==e?"opacity-100 z-10":"opacity-0 -translate-y-12 z-0")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[(0,i.jsx)(s,{title:"Everyone-Votes",description:"A Discord bot that sends and tallies daily polls from thousands of servers.",icon:"/images/EveryoneVotesIcon.png",link:"/everyone-votes",shadow:"shadow-blue-900"}),(0,i.jsx)(s,{title:"Space",description:"A WebGPU space/nebula image generator with lots of parameters to modify.",icon:"/images/SpaceIcon.png",link:"/space",shadow:"shadow-violet-950"}),(0,i.jsx)(s,{title:"Dark",description:"A VSCode color theme based off of Brackets Dark.",icon:"/images/DarkIcon.png",link:"/dark",shadow:"shadow-yellow-950"})]})})]})}},8707:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return y}});let r=n(6927),i=n(5909),o=i._(n(6006)),a=r._(n(9209)),l=n(3930),s=n(8706),d=n(3278);n(4745);let u=r._(n(8685)),c={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1};function f(e){return void 0!==e.default}function p(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function m(e,t,n,r,i,o,a){if(!e||e["data-loaded-src"]===t)return;e["data-loaded-src"]=t;let l="decode"in e?e.decode():Promise.resolve();l.catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("blur"===n&&o(!0),null==r?void 0:r.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let n=!1,i=!1;r.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>n,isPropagationStopped:()=>i,persist:()=>{},preventDefault:()=>{n=!0,t.preventDefault()},stopPropagation:()=>{i=!0,t.stopPropagation()}})}(null==i?void 0:i.current)&&i.current(e)}})}function h(e){let[t,n]=o.version.split("."),r=parseInt(t,10),i=parseInt(n,10);return r>18||18===r&&i>=3?{fetchPriority:e}:{fetchpriority:e}}let g=(0,o.forwardRef)((e,t)=>{let{imgAttributes:n,heightInt:r,widthInt:i,qualityInt:a,className:l,imgStyle:s,blurStyle:d,isLazy:u,fetchPriority:c,fill:f,placeholder:p,loading:g,srcString:v,config:y,unoptimized:x,loader:w,onLoadRef:b,onLoadingCompleteRef:_,setBlurComplete:j,setShowAltText:k,onLoad:S,onError:E,...O}=e;return g=u?"lazy":g,o.default.createElement("img",{...O,...h(c),loading:g,width:i,height:r,decoding:"async","data-nimg":f?"fill":"1",className:l,style:{...s,...d},...n,ref:(0,o.useCallback)(e=>{t&&("function"==typeof t?t(e):"object"==typeof t&&(t.current=e)),e&&(E&&(e.src=e.src),e.complete&&m(e,v,p,b,_,j,x))},[v,p,b,_,j,E,x,t]),onLoad:e=>{let t=e.currentTarget;m(t,v,p,b,_,j,x)},onError:e=>{k(!0),"blur"===p&&j(!0),E&&E(e)}})}),v=(0,o.forwardRef)((e,t)=>{var n;let r,i,{src:m,sizes:v,unoptimized:y=!1,priority:x=!1,loading:w,className:b,quality:_,width:j,height:k,fill:S,style:E,onLoad:O,onLoadingComplete:C,placeholder:P="empty",blurDataURL:N,fetchPriority:I,layout:M,objectFit:A,objectPosition:z,lazyBoundary:D,lazyRoot:R,...T}=e,U=(0,o.useContext)(d.ImageConfigContext),F=(0,o.useMemo)(()=>{let e=c||U||s.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),n=e.deviceSizes.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:n}},[U]),L=T.loader||u.default;delete T.loader;let V="__next_img_default"in L;if(V){if("custom"===F.loader)throw Error('Image with src "'+m+'" is missing "loader" prop.\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader')}else{let e=L;L=t=>{let{config:n,...r}=t;return e(r)}}if(M){"fill"===M&&(S=!0);let e={intrinsic:{maxWidth:"100%",height:"auto"},responsive:{width:"100%",height:"auto"}}[M];e&&(E={...E,...e});let t={responsive:"100vw",fill:"100vw"}[M];t&&!v&&(v=t)}let W="",B=p(j),G=p(k);if("object"==typeof(n=m)&&(f(n)||void 0!==n.src)){let e=f(m)?m.default:m;if(!e.src)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received "+JSON.stringify(e));if(!e.height||!e.width)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received "+JSON.stringify(e));if(r=e.blurWidth,i=e.blurHeight,N=N||e.blurDataURL,W=e.src,!S){if(B||G){if(B&&!G){let t=B/e.width;G=Math.round(e.height*t)}else if(!B&&G){let t=G/e.height;B=Math.round(e.width*t)}}else B=e.width,G=e.height}}let q=!x&&("lazy"===w||void 0===w);(!(m="string"==typeof m?m:W)||m.startsWith("data:")||m.startsWith("blob:"))&&(y=!0,q=!1),F.unoptimized&&(y=!0),V&&m.endsWith(".svg")&&!F.dangerouslyAllowSVG&&(y=!0),x&&(I="high");let[Y,$]=(0,o.useState)(!1),[H,J]=(0,o.useState)(!1),K=p(_),Q=Object.assign(S?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:A,objectPosition:z}:{},H?{}:{color:"transparent"},E),X="blur"===P&&N&&!Y?{backgroundSize:Q.objectFit||"cover",backgroundPosition:Q.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:'url("data:image/svg+xml;charset=utf-8,'+(0,l.getImageBlurSvg)({widthInt:B,heightInt:G,blurWidth:r,blurHeight:i,blurDataURL:N,objectFit:Q.objectFit})+'")'}:{},Z=function(e){let{config:t,src:n,unoptimized:r,width:i,quality:o,sizes:a,loader:l}=e;if(r)return{src:n,srcSet:void 0,sizes:void 0};let{widths:s,kind:d}=function(e,t,n){let{deviceSizes:r,allSizes:i}=e;if(n){let e=/(^|\s)(1?\d?\d)vw/g,t=[];for(let r;r=e.exec(n);r)t.push(parseInt(r[2]));if(t.length){let e=.01*Math.min(...t);return{widths:i.filter(t=>t>=r[0]*e),kind:"w"}}return{widths:i,kind:"w"}}if("number"!=typeof t)return{widths:r,kind:"w"};let o=[...new Set([t,2*t].map(e=>i.find(t=>t>=e)||i[i.length-1]))];return{widths:o,kind:"x"}}(t,i,a),u=s.length-1;return{sizes:a||"w"!==d?a:"100vw",srcSet:s.map((e,r)=>l({config:t,src:n,quality:o,width:e})+" "+("w"===d?e:r+1)+d).join(", "),src:l({config:t,src:n,quality:o,width:s[u]})}}({config:F,src:m,unoptimized:y,width:B,quality:K,sizes:v,loader:L}),ee=m,et=(0,o.useRef)(O);(0,o.useEffect)(()=>{et.current=O},[O]);let en=(0,o.useRef)(C);(0,o.useEffect)(()=>{en.current=C},[C]);let er={isLazy:q,imgAttributes:Z,heightInt:G,widthInt:B,qualityInt:K,className:b,imgStyle:Q,blurStyle:X,loading:w,config:F,fetchPriority:I,fill:S,unoptimized:y,placeholder:P,loader:L,srcString:ee,onLoadRef:et,onLoadingCompleteRef:en,setBlurComplete:$,setShowAltText:J,...T};return o.default.createElement(o.default.Fragment,null,o.default.createElement(g,{...er,ref:t}),x?o.default.createElement(a.default,null,o.default.createElement("link",{key:"__nimg-"+Z.src+Z.srcSet+Z.sizes,rel:"preload",as:"image",href:Z.srcSet?void 0:Z.src,imageSrcSet:Z.srcSet,imageSizes:Z.sizes,crossOrigin:T.crossOrigin,referrerPolicy:T.referrerPolicy,...h(I)})):null)}),y=v;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1909:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AmpStateContext",{enumerable:!0,get:function(){return o}});let r=n(6927),i=r._(n(6006)),o=i.default.createContext({})},7060:function(e,t){"use strict";function n(e){let{ampFirst:t=!1,hybrid:n=!1,hasQuery:r=!1}=void 0===e?{}:e;return t||n&&r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return n}})},9209:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{defaultHead:function(){return u},default:function(){return m}});let r=n(6927),i=n(5909),o=i._(n(6006)),a=r._(n(9797)),l=n(1909),s=n(5415),d=n(7060);function u(e){void 0===e&&(e=!1);let t=[o.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(o.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function c(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===o.default.Fragment?e.concat(o.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}n(4745);let f=["name","httpEquiv","charSet","itemProp"];function p(e,t){let{inAmpMode:n}=t;return e.reduce(c,[]).reverse().concat(u(n).reverse()).filter(function(){let e=new Set,t=new Set,n=new Set,r={};return i=>{let o=!0,a=!1;if(i.key&&"number"!=typeof i.key&&i.key.indexOf("$")>0){a=!0;let t=i.key.slice(i.key.indexOf("$")+1);e.has(t)?o=!1:e.add(t)}switch(i.type){case"title":case"base":t.has(i.type)?o=!1:t.add(i.type);break;case"meta":for(let e=0,t=f.length;e<t;e++){let t=f[e];if(i.props.hasOwnProperty(t)){if("charSet"===t)n.has(t)?o=!1:n.add(t);else{let e=i.props[t],n=r[t]||new Set;("name"!==t||!a)&&n.has(e)?o=!1:(n.add(e),r[t]=n)}}}}return o}}()).reverse().map((e,t)=>{let r=e.key||t;if(!n&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,o.default.cloneElement(e,t)}return o.default.cloneElement(e,{key:r})})}let m=function(e){let{children:t}=e,n=(0,o.useContext)(l.AmpStateContext),r=(0,o.useContext)(s.HeadManagerContext);return o.default.createElement(a.default,{reduceComponentsToState:p,headManager:r,inAmpMode:(0,d.isInAmpMode)(n)},t)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3930:function(e,t){"use strict";function n(e){let{widthInt:t,heightInt:n,blurWidth:r,blurHeight:i,blurDataURL:o,objectFit:a}=e,l=r||t,s=i||n,d=o.startsWith("data:image/jpeg")?"%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1'/%3E%3C/feComponentTransfer%3E%":"";return l&&s?"%3Csvg xmlns='http%3A//www.w3.org/2000/svg' viewBox='0 0 "+l+" "+s+"'%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='"+(r&&i?"1":"20")+"'/%3E"+d+"%3C/filter%3E%3Cimage preserveAspectRatio='none' filter='url(%23b)' x='0' y='0' height='100%25' width='100%25' href='"+o+"'/%3E%3C/svg%3E":"%3Csvg xmlns='http%3A//www.w3.org/2000/svg'%3E%3Cimage style='filter:blur(20px)' preserveAspectRatio='"+("contain"===a?"xMidYMid":"cover"===a?"xMidYMid slice":"none")+"' x='0' y='0' height='100%25' width='100%25' href='"+o+"'/%3E%3C/svg%3E"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImageBlurSvg",{enumerable:!0,get:function(){return n}})},3278:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ImageConfigContext",{enumerable:!0,get:function(){return a}});let r=n(6927),i=r._(n(6006)),o=n(8706),a=i.default.createContext(o.imageConfigDefault)},8706:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{VALID_LOADERS:function(){return n},imageConfigDefault:function(){return r}});let n=["default","imgix","cloudinary","akamai","custom"],r={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"inline",remotePatterns:[],unoptimized:!1}},8685:function(e,t){"use strict";function n(e){let{config:t,src:n,width:r,quality:i}=e;return t.path+"?url="+encodeURIComponent(n)+"&w="+r+"&q="+(i||75)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r}}),n.__next_img_default=!0;let r=n},9797:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return l}});let r=n(5909),i=r._(n(6006)),o=i.useLayoutEffect,a=i.useEffect;function l(e){let{headManager:t,reduceComponentsToState:n}=e;function r(){if(t&&t.mountedInstances){let r=i.Children.toArray(Array.from(t.mountedInstances).filter(Boolean));t.updateHead(n(r,e))}}return o(()=>{var n;return null==t||null==(n=t.mountedInstances)||n.add(e.children),()=>{var n;null==t||null==(n=t.mountedInstances)||n.delete(e.children)}}),o(()=>(t&&(t._pendingUpdate=r),()=>{t&&(t._pendingUpdate=r)})),a(()=>(t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null),()=>{t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null)})),null}},4745:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return n}});let n=e=>{}},4982:function(){},3177:function(e,t,n){"use strict";/** - * @license React - * react-jsx-runtime.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var r=n(6006),i=Symbol.for("react.element"),o=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,l=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function d(e,t,n){var r,o={},d=null,u=null;for(r in void 0!==n&&(d=""+n),void 0!==t.key&&(d=""+t.key),void 0!==t.ref&&(u=t.ref),t)a.call(t,r)&&!s.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===o[r]&&(o[r]=t[r]);return{$$typeof:i,type:e,key:d,ref:u,props:o,_owner:l.current}}t.Fragment=o,t.jsx=d,t.jsxs=d},9268:function(e,t,n){"use strict";e.exports=n(3177)},6394:function(e,t,n){e.exports=n(8707)}},function(e){e.O(0,[667,488,744],function(){return e(e.s=6436)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/space/loading-12fd180f06101306.js b/.next/static/chunks/app/space/loading-12fd180f06101306.js new file mode 100644 index 0000000..808746b --- /dev/null +++ b/.next/static/chunks/app/space/loading-12fd180f06101306.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[447,181,369,619],{3521:function(){}},function(n){n.O(0,[971,472,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/space/loading-df1b886b524be596.js b/.next/static/chunks/app/space/loading-df1b886b524be596.js deleted file mode 100644 index 4d73f2c..0000000 --- a/.next/static/chunks/app/space/loading-df1b886b524be596.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[447,527,181],{7155:function(){}},function(n){n.O(0,[667,488,744],function(){return n(n.s=7155)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/space/page-aa0f5917bd776cea.js b/.next/static/chunks/app/space/page-aa0f5917bd776cea.js deleted file mode 100644 index 87fa1c1..0000000 --- a/.next/static/chunks/app/space/page-aa0f5917bd776cea.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[514],{5334:function(e,t,n){Promise.resolve().then(n.bind(n,476))},553:function(e,t,n){"use strict";let a,r,d,o,i,s,l;n.d(t,{Z:function(){return p}});var c=n(870),h=n(3866);let u=[];class p{static generateFrame(){if(!a)return;let e=performance.now(),t=(0,h.g)();if((a.width!=t.width||a.height!=t.height)&&this.resizeFrame(t.width,t.height),s!=t.seed){var n,c;c=Math.imul((c=n=function(e){var t,n=0;for(t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t)|0;return Math.abs(n)}(t.seed)+1831565813)^c>>>15,1|c),l=(((c^=c+Math.imul(c^c>>>7,61|c))^c>>>14)>>>0)/4294967296,s=t.seed,console.log(1)}i.onApply=e=>{e.setFloat("seed",l+5),e.setFloat("density",t.density/100),e.setFloat("brightness",t.brightness/100)};for(let e=0;e<u.length;e++)o.detachPostProcess(u[e]);for(let e=0;e<t.count;e++)o.attachPostProcess(u[e]),u[e].onApply=n=>{n.setFloat("seed",1e3*l*(e+1)),n.setFloat4("color",t["color".concat(e+1)].r/255,t["color".concat(e+1)].g/255,t["color".concat(e+1)].b/255,1),n.setUInt("nebulascale",t.scale),n.setUInt("depth",t.depth),n.setFloat("intensity",t.intensity/100-1),n.setFloat("falloff",t.falloff),n.setFloat("persistence",t.persistence)},u[e].onApplyObservable.add(t=>{t.setTextureSampler("textureSamplerSampler",u[e].inputTexture.texture)});d.onAfterRenderObservable.addOnce(()=>{console.log("Rendered in ".concat(Math.round((performance.now()-e)*100)/100,"ms"))}),r.beginFrame(),d.render(),r.endFrame()}static resizeFrame(e,t){a.style.width=e.toString()+"px",a.style.height=t.toString()+"px",r.resize()}static async exportFrame(){let e=(0,h.g)();c.w1W.CreateScreenshotUsingRenderTarget(r,o,{width:a.width,height:a.height},void 0,void 0,void 0,void 0,"nebula-".concat(e.seed)),this.generateFrame()}static setTransparency(e){e?d.clearColor=new c.HEv(0,0,0,0):d.clearColor=new c.HEv(0,0,0,1)}static initialize(e,t,n,s){a=e,r=t,d=n,o=s,i=new c.Dso("StarShader","stars",null,null,1,o,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL),o.attachPostProcess(i);for(let e=0;e<10;e++)u.push(new c.Dso("NebulaShader","nebulas",null,null,1,o,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL))}}},3866:function(e,t,n){"use strict";let a;n.d(t,{Z:function(){return o},g:function(){return i}});var r=n(3294),d=n(553);function o(){a=new r.Pane({title:"Parameters",container:document.getElementById("TweakPane")||void 0});let e={width:window.innerWidth,height:window.innerHeight,transparent:!1,autoupdate:!1},t=a.addFolder({title:"Canvas",expanded:!0});t.addInput(e,"width",{min:100,max:7680,step:1}),t.addInput(e,"height",{min:100,max:4320,step:1}),t.addInput(e,"transparent").on("change",()=>{console.log(1),d.Z.setTransparency(e.transparent)});let n={density:1.5,brightness:100},o=a.addFolder({title:"Stars",expanded:!0});o.addInput(n,"density",{min:0,max:10,step:.01,format:e=>e.toFixed(2)+"%"}),o.addInput(n,"brightness",{min:0,max:200,step:.1,format:e=>e.toFixed(1)+"%"});let i={count:2,scale:5,depth:2,intensity:100,falloff:2,persistence:.5},s=a.addFolder({title:"Nebula",expanded:!0});s.addInput(i,"count",{min:0,max:3,step:1}).on("change",()=>{if(0==i.count)c.hidden=!0;else{c.hidden=!1;for(let e=0;e<h.length;e++)e<i.count?h[e].hidden=!1:h[e].hidden=!0}a.refresh()});let l={},c=s.addFolder({title:"Colors",expanded:!1}),h=[];for(let e=0;e<3;e++)l["color"+(e+1)]={r:Math.ceil(255*Math.random()),g:Math.ceil(255*Math.random()),b:Math.ceil(255*Math.random())},h.push(c.addInput(l,"color"+(e+1))),e>i.count-1&&(h[e].hidden=!0);s.addInput(i,"scale",{min:1,max:50,step:1}),s.addInput(i,"depth",{min:0,max:20,step:1}),s.addInput(i,"intensity",{min:50,max:150,step:1,format:e=>e+"%"}),s.addInput(i,"falloff",{min:1,max:10,step:.1}),s.addInput(i,"persistence",{min:0,max:1,step:.01});let u={seed:""+Math.floor(1e12*Math.random())},p=a.addFolder({title:"Seed",expanded:!1});p.addInput(u,"seed",{format:e=>e.toFixed(0)}),p.addButton({title:"Randomize seed"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString(),a.refresh(),d.Z.generateFrame()}),a.addSeparator(),a.addButton({title:"Render"}).on("click",()=>{d.Z.generateFrame()}),a.addButton({title:"Render Random"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString();for(let e=0;e<3;e++)l["color"+(e+1)]={r:Math.ceil(255*Math.random()),g:Math.ceil(255*Math.random()),b:Math.ceil(255*Math.random())};a.refresh(),d.Z.generateFrame()}),a.addSeparator(),a.addButton({title:"Save Image"}).on("click",()=>{d.Z.exportFrame()}),a.addSeparator(),a.addInput(e,"autoupdate"),a.on("change",t=>{let n=t.presetKey;e.autoupdate&&(("width"==n||"height"==n)&&d.Z.resizeFrame(e.width,e.height),d.Z.generateFrame())})}function i(){return a.exportPreset()}},476:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return c}});var a=n(9268),r=n(6006),d=n(1301),o=n.n(d);function i(){return(0,a.jsx)("div",{className:"flex h-screen justify-center items-center",children:(0,a.jsx)("div",{className:"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin",children:(0,a.jsx)("div",{className:"h-10 w-10 rounded-full bg-black"})})})}var s=n(3866);let l=o()(()=>n.e(716).then(n.bind(n,6716)),{loadableGenerated:{webpack:()=>[6716]},ssr:!1});function c(){let[e,t]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{t(!0),(0,s.Z)()},[]),(0,a.jsxs)("main",{children:[(0,a.jsx)("div",{id:"TweakPane",className:"fixed top-2.5 right-2.5"}),e&&(0,a.jsx)(l,{}),!e&&(0,a.jsx)(i,{})]})}}},function(e){e.O(0,[995,267,9,669,369,23,667,488,744],function(){return e(e.s=5334)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/space/page-b8120f6d5470d1c7.js b/.next/static/chunks/app/space/page-b8120f6d5470d1c7.js new file mode 100644 index 0000000..78bbb26 --- /dev/null +++ b/.next/static/chunks/app/space/page-b8120f6d5470d1c7.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[514],{4310:function(e,t,n){Promise.resolve().then(n.bind(n,341))},1128:function(e,t,n){"use strict";let a,r,d,o,i,s,l;n.d(t,{Z:function(){return BabylonInteractivity}});var c=n(9111),h=n(6086);let u=[];function hashString(e){var t,n=0;for(t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t)|0;return Math.abs(n)}function mulberry32(e){var t=e+=1831565813;return t=Math.imul(t^t>>>15,1|t),(((t^=t+Math.imul(t^t>>>7,61|t))^t>>>14)>>>0)/4294967296}let BabylonInteractivity=class BabylonInteractivity{static generateFrame(){if(!a)return;let e=performance.now(),t=(0,h.g)();(a.width!=t.width||a.height!=t.height)&&this.resizeFrame(t.width,t.height),s!=t.seed&&(l=mulberry32(hashString(t.seed)),s=t.seed,console.log(1)),i.onApply=e=>{e.setFloat("seed",l+5),e.setFloat("density",t.density/100),e.setFloat("brightness",t.brightness/100)};for(let e=0;e<u.length;e++)o.detachPostProcess(u[e]);for(let e=0;e<t.count;e++)o.attachPostProcess(u[e]),u[e].onApply=n=>{n.setFloat("seed",1e3*l*(e+1)),n.setFloat4("color",t["color".concat(e+1)].r/255,t["color".concat(e+1)].g/255,t["color".concat(e+1)].b/255,1),n.setUInt("nebulascale",t.scale),n.setUInt("depth",t.depth),n.setFloat("intensity",t.intensity/100-1),n.setFloat("falloff",t.falloff),n.setFloat("persistence",t.persistence)},u[e].onApplyObservable.add(t=>{t.setTextureSampler("textureSamplerSampler",u[e].inputTexture.texture)});d.onAfterRenderObservable.addOnce(()=>{console.log("Rendered in ".concat(Math.round((performance.now()-e)*100)/100,"ms"))}),r.beginFrame(),d.render(),r.endFrame()}static resizeFrame(e,t){a.style.width=e.toString()+"px",a.style.height=t.toString()+"px",r.resize()}static async exportFrame(){let e=(0,h.g)();c.w1W.CreateScreenshotUsingRenderTarget(r,o,{width:a.width,height:a.height},void 0,void 0,void 0,void 0,"nebula-".concat(e.seed)),this.generateFrame()}static setTransparency(e){e?d.clearColor=new c.HEv(0,0,0,0):d.clearColor=new c.HEv(0,0,0,1)}static initialize(e,t,n,s){a=e,r=t,d=n,o=s,i=new c.Dso("StarShader","stars",null,null,1,o,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL),o.attachPostProcess(i);for(let e=0;e<10;e++)u.push(new c.Dso("NebulaShader","nebulas",null,null,1,o,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL))}}},6086:function(e,t,n){"use strict";let a;n.d(t,{Z:function(){return ParameterPanel},g:function(){return getParameters}});var r=n(7089),d=n(1128);function ParameterPanel(){a=new r.Pane({title:"Parameters",container:document.getElementById("TweakPane")||void 0});let e={width:window.innerWidth,height:window.innerHeight,transparent:!1,autoupdate:!1},t=a.addFolder({title:"Canvas",expanded:!0});t.addInput(e,"width",{min:100,max:7680,step:1}),t.addInput(e,"height",{min:100,max:4320,step:1}),t.addInput(e,"transparent").on("change",()=>{console.log(1),d.Z.setTransparency(e.transparent)});let n={density:1.5,brightness:100},o=a.addFolder({title:"Stars",expanded:!0});o.addInput(n,"density",{min:0,max:10,step:.01,format:e=>e.toFixed(2)+"%"}),o.addInput(n,"brightness",{min:0,max:200,step:.1,format:e=>e.toFixed(1)+"%"});let i={count:2,scale:5,depth:2,intensity:100,falloff:2,persistence:.5},s=a.addFolder({title:"Nebula",expanded:!0});s.addInput(i,"count",{min:0,max:3,step:1}).on("change",()=>{if(0==i.count)c.hidden=!0;else{c.hidden=!1;for(let e=0;e<h.length;e++)e<i.count?h[e].hidden=!1:h[e].hidden=!0}a.refresh()});let l={},c=s.addFolder({title:"Colors",expanded:!1}),h=[];for(let e=0;e<3;e++)l["color"+(e+1)]={r:Math.ceil(255*Math.random()),g:Math.ceil(255*Math.random()),b:Math.ceil(255*Math.random())},h.push(c.addInput(l,"color"+(e+1))),e>i.count-1&&(h[e].hidden=!0);s.addInput(i,"scale",{min:1,max:50,step:1}),s.addInput(i,"depth",{min:0,max:20,step:1}),s.addInput(i,"intensity",{min:50,max:150,step:1,format:e=>e+"%"}),s.addInput(i,"falloff",{min:1,max:10,step:.1}),s.addInput(i,"persistence",{min:0,max:1,step:.01});let u={seed:""+Math.floor(1e12*Math.random())},m=a.addFolder({title:"Seed",expanded:!1});m.addInput(u,"seed",{format:e=>e.toFixed(0)}),m.addButton({title:"Randomize seed"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString(),a.refresh(),d.Z.generateFrame()}),a.addSeparator(),a.addButton({title:"Render"}).on("click",()=>{d.Z.generateFrame()}),a.addButton({title:"Render Random"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString();for(let e=0;e<3;e++)l["color"+(e+1)]={r:Math.ceil(255*Math.random()),g:Math.ceil(255*Math.random()),b:Math.ceil(255*Math.random())};a.refresh(),d.Z.generateFrame()}),a.addSeparator(),a.addButton({title:"Save Image"}).on("click",()=>{d.Z.exportFrame()}),a.addSeparator(),a.addInput(e,"autoupdate"),a.on("change",t=>{let n=t.presetKey;e.autoupdate&&(("width"==n||"height"==n)&&d.Z.resizeFrame(e.width,e.height),d.Z.generateFrame())})}function getParameters(){return a.exportPreset()}},341:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return Sp}});var a=n(7437),r=n(2265),d=n(8811),o=n.n(d);function Loading(){return(0,a.jsx)("div",{className:"flex h-screen justify-center items-center",children:(0,a.jsx)("div",{className:"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin",children:(0,a.jsx)("div",{className:"h-10 w-10 rounded-full bg-black"})})})}var i=n(6086);let s=o()(()=>n.e(751).then(n.bind(n,2751)),{loadableGenerated:{webpack:()=>[2751]},ssr:!1});function Sp(){let[e,t]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{t(!0),(0,i.Z)()},[]),(0,a.jsxs)("main",{children:[(0,a.jsx)("div",{id:"TweakPane",className:"fixed top-2.5 right-2.5"}),e&&(0,a.jsx)(s,{}),!e&&(0,a.jsx)(Loading,{})]})}}},function(e){e.O(0,[732,105,735,790,116,173,971,472,744],function(){return e(e.s=4310)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/wiston/page-becb82f49ed47545.js b/.next/static/chunks/app/wiston/page-becb82f49ed47545.js deleted file mode 100644 index 1f46f8a..0000000 --- a/.next/static/chunks/app/wiston/page-becb82f49ed47545.js +++ /dev/null @@ -1,9 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[619],{6670:function(r,s,x){Promise.resolve().then(x.bind(x,1899))},1899:function(r,s,x){"use strict";x.r(s),x.d(s,{default:function(){return e},metadata:function(){return j}});var b=x(9268);let j={title:"wiston"};function e(){return(0,b.jsx)("main",{className:"flex flex-col items-center",children:(0,b.jsxs)("span",{className:"whitespace-pre-wrap font-mono text-[0.2rem] leading-[0.25rem]",children:["‎ -+=-:. - ",(0,b.jsx)("br",{}),"‎ .*%#%#%%%%#*+-. ++= .:-==: ",(0,b.jsx)("br",{}),"‎ =%%########%##%%%*-. ++-# .-+*%%%###%#- ",(0,b.jsx)("br",{}),"‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#. ",(0,b.jsx)("br",{}),"‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%= ",(0,b.jsx)("br",{}),"‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%# ",(0,b.jsx)("br",{}),"‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%: ",(0,b.jsx)("br",{}),"‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%- ",(0,b.jsx)("br",{}),"‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%- ",(0,b.jsx)("br",{}),"‎ %%###################%*--------#**********#%%######################%%#%%%######%@- ",(0,b.jsx)("br",{}),"‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@- ",(0,b.jsx)("br",{}),"‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@: ",(0,b.jsx)("br",{}),"‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%. ",(0,b.jsx)("br",{}),"‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%% ",(0,b.jsx)("br",{}),"‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%* ",(0,b.jsx)("br",{}),"‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%= ",(0,b.jsx)("br",{}),"‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%. ",(0,b.jsx)("br",{}),"‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%# ",(0,b.jsx)("br",{}),"‎ ######%%%%%%%######################################################%@%######%%#%#%##########%- ",(0,b.jsx)("br",{}),"‎ %%#%%%%%%%%########################################################%@%#########%%%###########% ",(0,b.jsx)("br",{}),"‎ .%%%%%%%%%###########################################################%###########%@###########%+ ",(0,b.jsx)("br",{}),"‎ =#%%%%%%########################################################################################% ",(0,b.jsx)("br",{}),"‎ +%%%%%############################################%%#%############################################%- ",(0,b.jsx)("br",{}),"‎ =%%%%##########%#########################################%%##########################################%%**++======+**#% ",(0,b.jsx)("br",{}),"‎ -#%%%#########################################################%####################################%###################%. ",(0,b.jsx)("br",{}),"‎ *%%%#####################################################################################################%###%##########% ",(0,b.jsx)("br",{}),"‎ .#%###################################################################%##%###############%###############################%# ",(0,b.jsx)("br",{}),"‎ .+%##############################################################################%#########################################%= ",(0,b.jsx)("br",{}),"‎ .+%#########################################################################################################################%% ",(0,b.jsx)("br",{}),"‎ +%##########################################################################################################################%%. ",(0,b.jsx)("br",{}),"‎ =%#################################################################################%%@%%#####################################%%: ",(0,b.jsx)("br",{}),"‎ -#################################################################################%@@@%#######################################%%. ",(0,b.jsx)("br",{}),"‎ :################################################################################%@@#%########################################%%+ ",(0,b.jsx)("br",{}),"‎ +%#############################################################################%@@#- +######################################%+. ",(0,b.jsx)("br",{}),"‎ -#############################################################################%@@#= :*#################################%*- ",(0,b.jsx)("br",{}),"‎ =%##########################################################################%@%*- :==- +################################%. ",(0,b.jsx)("br",{}),"‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################. ",(0,b.jsx)("br",{}),"‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+: ",(0,b.jsx)("br",{}),"‎ : .-+####################################################################: #%@+--- =############%#= ",(0,b.jsx)("br",{}),"‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=: ",(0,b.jsx)("br",{}),"‎ .:. :-+*############################################################: :+*+- - .... ",(0,b.jsx)("br",{}),"‎ ::. .:=+*########################################################=. = ",(0,b.jsx)("br",{}),"‎ ::. .:-=*####################################################*: .- ",(0,b.jsx)("br",{}),"‎ ::. .:-=+*##########################################*=: .- ",(0,b.jsx)("br",{}),"‎ .:: ..:--==++***################***++===-::. .- ",(0,b.jsx)("br",{}),"‎ :-. ..... ..:::. .= ",(0,b.jsx)("br",{}),"‎ .::. .-+****+====+==: + ",(0,b.jsx)("br",{}),"‎ :::. .-+#*=:. . + ",(0,b.jsx)("br",{}),"‎ .::. .=*#+: .::::. =: ",(0,b.jsx)("br",{}),"‎ .... =*=. ::::: .+ ",(0,b.jsx)("br",{}),"‎ .:::. ::::. + ",(0,b.jsx)("br",{}),"‎ .:::::.. .:::::. .= ",(0,b.jsx)("br",{}),"‎ .::::::::::::.......::::::::::+-. =. ",(0,b.jsx)("br",{}),"‎ ...... .+. + ",(0,b.jsx)("br",{}),"‎ .::+ .- ",(0,b.jsx)("br",{}),"‎ .::. +. .: ",(0,b.jsx)("br",{}),"‎ -: :-. :: ",(0,b.jsx)("br",{}),"‎ -- .-=: .:::. :. ",(0,b.jsx)("br",{}),"‎ --.-=:. .---. :. ",(0,b.jsx)("br",{}),"‎ -=. ==: :=-. :. ",(0,b.jsx)("br",{}),"‎ :+: :-+. .-=: - ",(0,b.jsx)("br",{}),"‎ :+- .=-. :=-. - ",(0,b.jsx)("br",{}),"‎ .+- :-- :=- :. - ",(0,b.jsx)("br",{}),"‎ .+=. = -=: :: .- ",(0,b.jsx)("br",{}),"‎ .+=. =:-: -+: .-. .- ",(0,b.jsx)("br",{}),"‎ .==. .:::::--:.=+ .=: :- .: ",(0,b.jsx)("br",{}),"‎ ::=:---: .---. .:--+: .-. :: ",(0,b.jsx)("br",{}),"‎ --. .+-:. .--: :- :. ",(0,b.jsx)("br",{}),"‎ :- .. .:: .-. -. ",(0,b.jsx)("br",{}),"‎ :: : .=. :: -. ",(0,b.jsx)("br",{}),"‎ = .: .+: ::. -. ",(0,b.jsx)("br",{}),"‎ =. - +. .:. -. ",(0,b.jsx)("br",{}),"‎ + - .+ :: :: ",(0,b.jsx)("br",{}),"‎ + . :-. + .:. :: ",(0,b.jsx)("br",{}),"‎ + .: :- =. .:. .- ",(0,b.jsx)("br",{}),"‎ -. .: :- .--. .:: .- ",(0,b.jsx)("br",{}),"‎ = ::. .= == :: .- ",(0,b.jsx)("br",{}),"‎ :: ::: :: .:-- .:. - ",(0,b.jsx)("br",{}),"‎ -. .:::: = :---. .:. :. ",(0,b.jsx)("br",{}),"‎ :. .:::::::=:--:. :: :. ",(0,b.jsx)("br",{}),"‎ .:. :-= .: ",(0,b.jsx)("br",{}),"‎ .:: .-. .: ",(0,b.jsx)("br",{}),"‎ ::. .-: - ",(0,b.jsx)("br",{}),"‎ .::. :-. = ",(0,b.jsx)("br",{}),"‎ :::: .-. .= ",(0,b.jsx)("br",{}),"‎ ::::. :: .- ",(0,b.jsx)("br",{}),"‎ .::::::::::::. :- ",(0,b.jsx)("br",{}),"‎ - -: ",(0,b.jsx)("br",{}),"‎ - = ",(0,b.jsx)("br",{}),"‎ ::::-----:::::=. = ",(0,b.jsx)("br",{}),"‎ ::--:. .: .: ",(0,b.jsx)("br",{}),"‎ :--:. : : ",(0,b.jsx)("br",{}),"‎ :--. .-: : ",(0,b.jsx)("br",{}),"‎ ----------. .==. - ",(0,b.jsx)("br",{}),"‎ = -+. .- ",(0,b.jsx)("br",{}),"‎ =. .+- = ",(0,b.jsx)("br",{}),"‎ +. .*: + ",(0,b.jsx)("br",{}),"‎ .::--: .*. + ",(0,b.jsx)("br",{}),"‎ .- .+. :- ",(0,b.jsx)("br",{}),"‎ :: +. --: ",(0,b.jsx)("br",{}),"‎ -. :- .---::::. ",(0,b.jsx)("br",{}),"‎ .: + .-",(0,b.jsx)("br",{}),"‎ = .- .-",(0,b.jsx)("br",{}),"‎ -. -. :=",(0,b.jsx)("br",{}),"‎ = = .-=: ",(0,b.jsx)("br",{}),"‎ -: - .=---: ",(0,b.jsx)("br",{}),"‎ = -. .--:- ",(0,b.jsx)("br",{}),"‎ = ....:::-= .=. ",(0,b.jsx)("br",{}),"‎ ..::::......:::::::::::. + .:.. .::::. :== ",(0,b.jsx)("br",{}),"‎ :::::::. .::-::::: = .... :---:. .:-==: ",(0,b.jsx)("br",{}),"‎ .- .. .:-::: = .:.. .:--:. -- ",(0,b.jsx)("br",{}),"‎ .:=. :+ .:. ::::. .* ",(0,b.jsx)("br",{}),"‎ -: :: ::. :::: *. ",(0,b.jsx)("br",{}),"‎ .: -. .-. .. .:. -- ",(0,b.jsx)("br",{}),"‎ - .-: .=. .= .=- =. .+ ",(0,b.jsx)("br",{}),"‎ - -=. .=. -. :+. +: .+ ",(0,b.jsx)("br",{}),"‎ - =- .=. = :*. +: + ",(0,b.jsx)("br",{}),"‎ .: := -: - .*. :+ =. ",(0,b.jsx)("br",{}),"‎ :. * .-. + +: *. .- ",(0,b.jsx)("br",{}),"‎ :: + :-. --:. .* .* ::. ",(0,b.jsx)("br",{}),"‎ ::. + --. ...-:. := .+ :-: ",(0,b.jsx)("br",{}),"‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:. ",(0,b.jsx)("br",{}),"‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--: ",(0,b.jsx)("br",{}),"‎ .:::::::::... ..... + .... .:--:: ",(0,b.jsx)("br",{}),"‎ ..::::::::..:- .:..:::::. .::-::::: ",(0,b.jsx)("br",{})]})})}},3177:function(r,s,x){"use strict";/** - * @license React - * react-jsx-runtime.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var b=x(6006),j=Symbol.for("react.element"),e=Symbol.for("react.fragment"),t=Object.prototype.hasOwnProperty,n=b.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function f(r,s,x){var b,e={},f=null,i=null;for(b in void 0!==x&&(f=""+x),void 0!==s.key&&(f=""+s.key),void 0!==s.ref&&(i=s.ref),s)t.call(s,b)&&!o.hasOwnProperty(b)&&(e[b]=s[b]);if(r&&r.defaultProps)for(b in s=r.defaultProps)void 0===e[b]&&(e[b]=s[b]);return{$$typeof:j,type:r,key:f,ref:i,props:e,_owner:n.current}}s.Fragment=e,s.jsx=f,s.jsxs=f},9268:function(r,s,x){"use strict";r.exports=x(3177)}},function(r){r.O(0,[667,488,744],function(){return r(r.s=6670)}),_N_E=r.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/wiston/page-c31b345ea6ea73af.js b/.next/static/chunks/app/wiston/page-c31b345ea6ea73af.js new file mode 100644 index 0000000..54b989f --- /dev/null +++ b/.next/static/chunks/app/wiston/page-c31b345ea6ea73af.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[619,181,369,447],{3521:function(){}},function(n){n.O(0,[971,472,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/d67c510a-e497b3cd5bf43bb4.js b/.next/static/chunks/d67c510a-e497b3cd5bf43bb4.js new file mode 100644 index 0000000..8660c20 --- /dev/null +++ b/.next/static/chunks/d67c510a-e497b3cd5bf43bb4.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[790],{6465:function(e,t,r){r.d(t,{B:function(){return ThinEngine}});var i=r(6030),s=r(1088),n=r(6131),a=r(4800),l=r(7987),_=r(6807),h=r(3609),o=r(3912),u=r(9626),d=r(7209),g=r(5410),c=r(7666),f=r(998),E=r(856),p=r(4548),T=r(5342),R=r(1606),x=r(5122),m=r(5550),b=r(7662);let BufferPointer=class BufferPointer{};let ThinEngine=class ThinEngine{static get NpmPackage(){return"babylonjs@6.28.1"}static get Version(){return"6.28.1"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return s.Q.ShadersRepository}static set ShadersRepository(e){s.Q.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){let e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);let r=document.createElement("canvas");return r.width=e,r.height=t,r}createCanvas(e,t){return ThinEngine._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,r,i){var s,n,o,f,E,T,R,m,A,S,C;this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new a.y$,this._frameId=0,this._uniformBuffers=[],this._storageBuffers=[],this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=[],this.onContextLostObservable=new a.y$,this.onContextRestoredObservable=new a.y$,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new l.k,this._stencilStateComposer=new x.C,this._stencilState=new _.s,this._alphaState=new h.Q,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=[],this._renderTargetWrapperCache=[],this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=[],this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=[],this._currentInstanceLocations=[],this._currentInstanceBuffers=[],this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=[],this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=[],this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new a.y$,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=b.F.Now;let B=null;r=r||{},this._creationOptions=r,this.adaptToDeviceRatio=null!=i&&i,this._stencilStateComposer.stencilGlobal=this._stencilState,p.Z.SetMatrixPrecision(!!r.useHighPrecisionMatrix),r.antialias=null!=t?t:r.antialias,r.deterministicLockstep=null!==(s=r.deterministicLockstep)&&void 0!==s&&s,r.lockstepMaxSteps=null!==(n=r.lockstepMaxSteps)&&void 0!==n?n:4,r.timeStep=null!==(o=r.timeStep)&&void 0!==o?o:1/60,r.audioEngine=null===(f=r.audioEngine)||void 0===f||f,r.stencil=null===(E=r.stencil)||void 0===E||E,this._audioContext=null!==(R=null===(T=r.audioEngineOptions)||void 0===T?void 0:T.audioContext)&&void 0!==R?R:null,this._audioDestination=null!==(A=null===(m=r.audioEngineOptions)||void 0===m?void 0:m.audioDestination)&&void 0!==A?A:null,this.premultipliedAlpha=null===(S=r.premultipliedAlpha)||void 0===S||S,this.useExactSrgbConversions=null!==(C=r.useExactSrgbConversions)&&void 0!==C&&C,this._doNotHandleContextLost=!!r.doNotHandleContextLost,this._isStencilEnable=!!r.stencil,i=i||r.adaptToDeviceRatio||!1;let v=(0,d.CG)()&&window.devicePixelRatio||1,L=r.limitDeviceRatio||v;if(this._hardwareScalingLevel=i?1/Math.min(L,v):1,this._lastDevicePixelRatio=v,!e)return;if(e.getContext){if(B=e,this._renderingCanvas=B,void 0===r.preserveDrawingBuffer&&(r.preserveDrawingBuffer=!1),void 0===r.xrCompatible&&(r.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();let e=navigator.userAgent;for(let t of ThinEngine.ExceptionList){let i=t.key,s=t.targets,n=new RegExp(i);if(n.test(e)){if(t.capture&&t.captureConstraint){let r=t.capture,i=t.captureConstraint,s=new RegExp(r),n=s.exec(e);if(n&&n.length>0){let e=parseInt(n[n.length-1]);if(e>=i)continue}}for(let e of s)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":r.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,u.Y.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},B.addEventListener("webglcontextlost",this._onContextLost,!1),B.addEventListener("webglcontextrestored",this._onContextRestored,!1),r.powerPreference=r.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(r.xrCompatible=!1),!r.disableWebGL2Support)try{this._gl=B.getContext("webgl2",r)||B.getContext("experimental-webgl2",r),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!B)throw Error("The provided canvas is null or undefined.");try{this._gl=B.getContext("webgl",r)||B.getContext("experimental-webgl",r)}catch(e){throw Error("WebGL not supported")}}if(!this._gl)throw Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";let t=this._gl.getContextAttributes();t&&(r.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==r.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=r.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e<this._caps.maxVertexAttribs;e++)this._currentBufferPointers[e]=new BufferPointer;this._shaderProcessor=this.webGLVersion>1?new c.C:new g.f,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);let w=`Babylon.js v${ThinEngine.Version}`;console.log(w+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",w)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{let e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&(0,d.n5)()&&"ontouchend"in document},this._checkForMobile(),(0,d.CG)()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null;let r=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),null===(t=this._rebuildComputeEffects)||void 0===t||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=r,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=n,u.Y.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){let e=this._internalTexturesCache.slice();for(let t of e)t._rebuild()}_rebuildRenderTargetWrappers(){let e=this._renderTargetWrapperCache.slice();for(let t of e)t._rebuild()}_rebuildEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}s.Q.ResetCache()}areAllEffectsReady(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];if(!t.isReady())return!1}return!0}_rebuildBuffers(){for(let e of this._uniformBuffers)e._rebuild();for(let e of this._storageBuffers)e._rebuild()}_initGLContext(){var e;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._glVersion=this._gl.getParameter(this._gl.VERSION);let t=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=t&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(null!==(e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))&&void 0!==e?e:0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{let e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{let e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{let e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{let e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){let e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{let e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{let e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!!(this._creationOptions&&this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e<this._maxSimultaneousTextures;e++)this._nextFreeTextureSlots.push(e);"Mali-G72"===this._glRenderer&&(this._caps.disableMorphTargetTexture=!0)}_initFeatures(){this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:1!==this._webGLVersion,supportDepthStencilTexture:1!==this._webGLVersion,supportShadowSamplers:1!==this._webGLVersion,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:1!==this._webGLVersion,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:1!==this._webGLVersion,basisNeedsPOT:1===this._webGLVersion,support3DTextures:1!==this._webGLVersion,needTypeSuffixInShaderConstants:1!==this._webGLVersion,supportMSAA:1!==this._webGLVersion,supportSSAO2:1!==this._webGLVersion,supportExtendedTextureFormats:1!==this._webGLVersion,supportSwitchCaseInShader:1!==this._webGLVersion,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}get isStencilEnable(){return this._isStencilEnable}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);let e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}resetTextureCache(){for(let e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}getLoadedTexturesCache(){return this._internalTexturesCache}getCaps(){return this._caps}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}let t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(this._renderingQueueLaunched&&this._frameHandler){if(this._renderingQueueLaunched=!1,(0,d.CG)()){let{cancelAnimationFrame:e}=this.getHostWindow()||window;if("function"==typeof e)return e(this._frameHandler)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(this._frameHandler);return clearTimeout(this._frameHandler)}}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e<this._activeRenderLoops.length;e++){let t=this._activeRenderLoops[e];t()}this.endFrame()}}this._activeRenderLoops.length>0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return(0,d.CG)()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}_queueNewFrame(e,t){return ThinEngine.QueueNewFrame(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=()=>this._renderLoop(),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,r,i=!1){var s,n;let a=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=a;let l=0;if(t&&e){let t=!0;if(this._currentRenderTarget){let r=null===(s=this._currentRenderTarget.texture)||void 0===s?void 0:s.format;if(8===r||9===r||10===r||11===r){let r=null===(n=this._currentRenderTarget.texture)||void 0===n?void 0:n.type;7===r||5===r?(ThinEngine._TempClearColorUint32[0]=255*e.r,ThinEngine._TempClearColorUint32[1]=255*e.g,ThinEngine._TempClearColorUint32[2]=255*e.b,ThinEngine._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,ThinEngine._TempClearColorUint32)):(ThinEngine._TempClearColorInt32[0]=255*e.r,ThinEngine._TempClearColorInt32[1]=255*e.g,ThinEngine._TempClearColorInt32[2]=255*e.b,ThinEngine._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,ThinEngine._TempClearColorInt32)),t=!1}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),l|=this._gl.COLOR_BUFFER_BIT)}r&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),l|=this._gl.DEPTH_BUFFER_BIT),i&&(this._gl.clearStencil(0),l|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(l)}_viewport(e,t,r,i){(e!==this._viewportCached.x||t!==this._viewportCached.y||r!==this._viewportCached.z||i!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=r,this._viewportCached.w=i,this._gl.viewport(e,t,r,i))}setViewport(e,t,r){let i=t||this.getRenderWidth(),s=r||this.getRenderHeight(),n=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(n*i,a*s,i*e.width,s*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,r;if(this.adaptToDeviceRatio){let e=(0,d.CG)()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if((0,d.CG)()&&(0,d.n5)()){if(this._renderingCanvas){let e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,r=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,r=window.innerHeight}else t=this._renderingCanvas?this._renderingCanvas.width:100,r=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,r/this._hardwareScalingLevel,e)}setSize(e,t,r=!1){return!!this._renderingCanvas&&(e|=0,t|=0,(!!r||this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)&&(this._renderingCanvas.width=e,this._renderingCanvas.height=t,!0))}bindFramebuffer(e,t=0,r,i,s,n=0,a=0){var l,_,h,o,u,d;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer);let g=this._gl;e.isMulti||(e.is2DArray?g.framebufferTextureLayer(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,null===(l=e.texture._hardwareTexture)||void 0===l?void 0:l.underlyingResource,n,a):e.isCube?g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(_=e.texture._hardwareTexture)||void 0===_?void 0:_.underlyingResource,n):e._currentLOD===n||(g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_2D,null===(h=e.texture._hardwareTexture)||void 0===h?void 0:h.underlyingResource,n),e._currentLOD=n));let c=e._depthStencilTexture;if(c){let r=e._depthStencilTextureWithStencil?g.DEPTH_STENCIL_ATTACHMENT:g.DEPTH_ATTACHMENT;e.is2DArray?g.framebufferTextureLayer(g.FRAMEBUFFER,r,null===(o=c._hardwareTexture)||void 0===o?void 0:o.underlyingResource,n,a):e.isCube?g.framebufferTexture2D(g.FRAMEBUFFER,r,g.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(u=c._hardwareTexture)||void 0===u?void 0:u.underlyingResource,n):g.framebufferTexture2D(g.FRAMEBUFFER,r,g.TEXTURE_2D,null===(d=c._hardwareTexture)||void 0===d?void 0:d.underlyingResource,n)}this._cachedViewport&&!s?this.setViewport(this._cachedViewport,r,i):(!r&&(r=e.width,n&&(r/=Math.pow(2,n))),!i&&(i=e.height,n&&(i/=Math.pow(2,n))),this._viewport(0,0,r,i)),this.wipeCaches()}setState(e,t=0,r,i=!1,s,n,a=0){var l,_;(this._depthCullingState.cull!==e||r)&&(this._depthCullingState.cull=e);let h=null===(_=null!==(l=this.cullBackFaces)&&void 0!==l?l:s)||void 0===_||_?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||r)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(a);let o=i?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==o||r)&&(this._depthCullingState.frontFace=o),this._stencilStateComposer.stencilMaterial=n}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){let e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){let e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,r){var i;this._currentRenderTarget=null;let s=this._gl;if(e._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,r);return}s.bindFramebuffer(s.READ_FRAMEBUFFER,e._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,e._framebuffer),s.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s.COLOR_BUFFER_BIT,s.NEAREST)}(null===(i=e.texture)||void 0===i?void 0:i.generateMipMaps)&&!t&&!e.isCube&&this.generateMipmaps(e.texture),r&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),r()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,t,r){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){let r=this._gl.createBuffer();if(!r)throw Error("Unable to create vertex buffer");let i=new f.M(r);return this.bindArrayBuffer(i),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),this._resetVertexBufferBinding(),i.references=1,i}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,r){let i=this._gl.createBuffer(),s=new f.M(i);if(!i)throw Error("Unable to create index buffer");this.bindIndexBuffer(s);let n=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),s.references=1,s.is32Bits=4===n.BYTES_PER_ELEMENT,s}_normalizeIndexData(e){let t=e.BYTES_PER_ELEMENT;if(2===t)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let t=0;t<e.length;t++)if(e[t]>=65535)return new Uint32Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,r){let i=e.program,s=this._gl.getUniformBlockIndex(i,t);this._gl.uniformBlockBinding(i,s,r)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,r,i,s,n,a){let l=this._currentBufferPointers[t];if(!l)return;let _=!1;l.active?(l.buffer!==e&&(l.buffer=e,_=!0),l.size!==r&&(l.size=r,_=!0),l.type!==i&&(l.type=i,_=!0),l.normalized!==s&&(l.normalized=s,_=!0),l.stride!==n&&(l.stride=n,_=!0),l.offset!==a&&(l.offset=a,_=!0)):(_=!0,l.active=!0,l.index=t,l.size=r,l.type=i,l.normalized=s,l.stride=n,l.offset=a,l.buffer=e),(_||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),i===this._gl.UNSIGNED_INT||i===this._gl.INT?this._gl.vertexAttribIPointer(t,r,i,n,a):this._gl.vertexAttribPointer(t,r,i,s,n,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,r){let i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s<i.length;s++){let n=t.getAttributeLocation(s);if(n>=0){let t=i[s],a=null;if(r&&(a=r[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);let l=a.getBuffer();l&&(this._vertexAttribPointer(l,n,a.getSize(),a.type,a.normalized,a.byteStride,a.byteOffset),a.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,a.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(l))))}}}recordVertexArrayObject(e,t,r,i){let s=this._gl.createVertexArray();if(!s)throw Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,r,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,r,i,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;let t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let a=0;a<t;a++)if(a<r.length){let t=s.getAttributeLocation(a);t>=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,r[a],this._gl.FLOAT,!1,i,n)),n+=4*r[a]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,r,i){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r,this._bindVertexBuffersAttributes(e,r,i)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,r=this._currentInstanceLocations.length;t<r;t++){let r=this._currentInstanceBuffers[t];e!=r&&r.references&&(e=r,this.bindArrayBuffer(r));let i=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(i,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0}releaseVertexArrayObject(e){this._gl.deleteVertexArray(e)}_releaseBuffer(e){return e.references--,0===e.references&&(this._deleteBuffer(e),!0)}_deleteBuffer(e){this._gl.deleteBuffer(e.underlyingResource)}updateAndBindInstancesBuffer(e,t,r){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==r[0].index)this.bindInstancesBuffer(e,r,!0);else for(let t=0;t<4;t++){let i=r[t];this._vertexAttribArraysEnabled[i]||(this._gl.enableVertexAttribArray(i),this._vertexAttribArraysEnabled[i]=!0),this._vertexAttribPointer(e,i,4,this._gl.FLOAT,!1,64,16*t),this._gl.vertexAttribDivisor(i,1),this._currentInstanceLocations.push(i),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,r=!0){this.bindArrayBuffer(e);let i=0;if(r)for(let e=0;e<t.length;e++){let r=t[e];i+=4*r.attributeSize}for(let r=0;r<t.length;r++){let s=t[r];void 0===s.index&&(s.index=this._currentEffect.getAttributeLocationByName(s.attributeName)),s.index<0||(this._vertexAttribArraysEnabled[s.index]||(this._gl.enableVertexAttribArray(s.index),this._vertexAttribArraysEnabled[s.index]=!0),this._vertexAttribPointer(e,s.index,s.attributeSize,s.attributeType||this._gl.FLOAT,s.normalized||!1,i,s.offset),this._gl.vertexAttribDivisor(s.index,void 0===s.divisor?1:s.divisor),this._currentInstanceLocations.push(s.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;let t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t,r=!1;for(;-1!==(t=this._currentInstanceLocations.indexOf(e));)this._currentInstanceLocations.splice(t,1),this._currentInstanceBuffers.splice(t,1),r=!0,t=this._currentInstanceLocations.indexOf(e);r&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))}disableAttributeByIndex(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1}draw(e,t,r,i){this.drawElementsType(e?0:1,t,r,i)}drawPointClouds(e,t,r){this.drawArraysType(2,e,t,r)}drawUnIndexed(e,t,r,i){this.drawArraysType(e?0:1,t,r,i)}drawElementsType(e,t,r,i){this.applyStates(),this._reportDrawCall();let s=this._drawMode(e),n=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,a=this._uintIndicesCurrentlySet?4:2;i?this._gl.drawElementsInstanced(s,r,n,t*a,i):this._gl.drawElements(s,r,n,t*a)}drawArraysType(e,t,r,i){this.applyStates(),this._reportDrawCall();let s=this._drawMode(e);i?this._gl.drawArraysInstanced(s,t,r,i):this._gl.drawArrays(s,t,r)}_drawMode(e){switch(e){case 0:default:return this._gl.TRIANGLES;case 2:case 3:return this._gl.POINTS;case 1:case 4:return this._gl.LINES;case 5:return this._gl.LINE_LOOP;case 6:return this._gl.LINE_STRIP;case 7:return this._gl.TRIANGLE_STRIP;case 8:return this._gl.TRIANGLE_FAN}}_reportDrawCall(){}_releaseEffect(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];let t=e.getPipelineContext();t&&this._deletePipelineContext(t)}_deletePipelineContext(e){e&&e.program&&(e.program.__SPECTOR_rebuildProgram=null,this._gl.deleteProgram(e.program))}_getGlobalDefines(e){if(e){this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS;return}{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}createEffect(e,t,r,i,n,a,l,_,h,o=m.x.GLSL){var u;let d=e.vertexElement||e.vertex||e.vertexToken||e.vertexSource||e,g=e.fragmentElement||e.fragment||e.fragmentToken||e.fragmentSource||e,c=this._getGlobalDefines(),f=null!==(u=null!=n?n:t.defines)&&void 0!==u?u:"";c&&(f+=c);let E=d+"+"+g+"@"+f;if(this._compiledEffects[E]){let e=this._compiledEffects[E];return l&&e.isReady()&&l(e),e}let p=new s.Q(e,t,r,i,this,n,a,l,_,h,E,o);return this._compiledEffects[E]=p,p}static _ConcatenateShader(e,t,r=""){return r+(t?t+"\n":"")+e}_compileShader(e,t,r,i){return this._compileRawShader(ThinEngine._ConcatenateShader(e,r,i),t)}_compileRawShader(e,t){let r=this._gl,i=r.createShader("vertex"===t?r.VERTEX_SHADER:r.FRAGMENT_SHADER);if(!i){let e=r.NO_ERROR,i=r.NO_ERROR;for(;(i=r.getError())!==r.NO_ERROR;)e=i;throw Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${r.isContextLost()}, _contextWasLost=${this._contextWasLost}`)}return r.shaderSource(i,e),r.compileShader(i),i}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,r,i,s=null){i=i||this._gl;let n=this._compileRawShader(t,"vertex"),a=this._compileRawShader(r,"fragment");return this._createShaderProgram(e,n,a,i,s)}createShaderProgram(e,t,r,i,s,n=null){s=s||this._gl;let a=this._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"",l=this._compileShader(t,"vertex",i,a),_=this._compileShader(r,"fragment",i,a);return this._createShaderProgram(e,l,_,s,n)}inlineShaderCode(e){return e}createPipelineContext(e){let t=new E.y;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,r,i,s=null){let n=i.createProgram();if(e.program=n,!n)throw Error("Unable to create program");return i.attachShader(n,t),i.attachShader(n,r),i.linkProgram(n),e.context=i,e.vertexShader=t,e.fragmentShader=r,e.isParallelCompiled||this._finalizePipelineContext(e),n}_finalizePipelineContext(e){let t=e.context,r=e.vertexShader,i=e.fragmentShader,s=e.program,n=t.getProgramParameter(s,t.LINK_STATUS);if(!n){if(!this._gl.getShaderParameter(r,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(r);if(t)throw e.vertexCompilationError=t,Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(i);if(t)throw e.fragmentCompilationError=t,Error("FRAGMENT SHADER "+t)}let n=t.getProgramInfoLog(s);if(n)throw e.programLinkError=n,Error(n)}if(this.validateShaderPrograms){t.validateProgram(s);let r=t.getProgramParameter(s,t.VALIDATE_STATUS);if(!r){let r=t.getProgramInfoLog(s);if(r)throw e.programValidationError=r,Error(r)}}t.deleteShader(r),t.deleteShader(i),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,r,i,s,n,a,l,_,h){i?e.program=this.createRawShaderProgram(e,t,r,void 0,_):e.program=this.createShaderProgram(e,t,r,l,void 0,_),e.program.__SPECTOR_rebuildProgram=a}_isRenderingStateCompiled(e){return!this._isDisposed&&!e._isDisposed&&!!this._gl.getProgramParameter(e.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(e),!0)}_executeWhenRenderingStateIsCompiled(e,t){if(!e.isParallelCompiled){t();return}let r=e.onCompiled;r?e.onCompiled=()=>{r(),t()}:e.onCompiled=t}getUniforms(e,t){let r=[];for(let i=0;i<t.length;i++)r.push(this._gl.getUniformLocation(e.program,t[i]));return r}getAttributes(e,t){let r=[];for(let i=0;i<t.length;i++)try{r.push(this._gl.getAttribLocation(e.program,t[i]))}catch(e){r.push(-1)}return r}enableEffect(e){(e=null!==e&&R.q.IsWrapper(e)?e.effect:e)&&e!==this._currentEffect&&(this._stencilStateComposer.stencilMaterial=void 0,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return!!e&&(this._gl.uniform1i(e,t),!0)}setInt2(e,t,r){return!!e&&(this._gl.uniform2i(e,t,r),!0)}setInt3(e,t,r,i){return!!e&&(this._gl.uniform3i(e,t,r,i),!0)}setInt4(e,t,r,i,s){return!!e&&(this._gl.uniform4i(e,t,r,i,s),!0)}setIntArray(e,t){return!!e&&(this._gl.uniform1iv(e,t),!0)}setIntArray2(e,t){return!!e&&t.length%2==0&&(this._gl.uniform2iv(e,t),!0)}setIntArray3(e,t){return!!e&&t.length%3==0&&(this._gl.uniform3iv(e,t),!0)}setIntArray4(e,t){return!!e&&t.length%4==0&&(this._gl.uniform4iv(e,t),!0)}setUInt(e,t){return!!e&&(this._gl.uniform1ui(e,t),!0)}setUInt2(e,t,r){return!!e&&(this._gl.uniform2ui(e,t,r),!0)}setUInt3(e,t,r,i){return!!e&&(this._gl.uniform3ui(e,t,r,i),!0)}setUInt4(e,t,r,i,s){return!!e&&(this._gl.uniform4ui(e,t,r,i,s),!0)}setUIntArray(e,t){return!!e&&(this._gl.uniform1uiv(e,t),!0)}setUIntArray2(e,t){return!!e&&t.length%2==0&&(this._gl.uniform2uiv(e,t),!0)}setUIntArray3(e,t){return!!e&&t.length%3==0&&(this._gl.uniform3uiv(e,t),!0)}setUIntArray4(e,t){return!!e&&t.length%4==0&&(this._gl.uniform4uiv(e,t),!0)}setArray(e,t){return!!e&&!(t.length<1)&&(this._gl.uniform1fv(e,t),!0)}setArray2(e,t){return!!e&&t.length%2==0&&(this._gl.uniform2fv(e,t),!0)}setArray3(e,t){return!!e&&t.length%3==0&&(this._gl.uniform3fv(e,t),!0)}setArray4(e,t){return!!e&&t.length%4==0&&(this._gl.uniform4fv(e,t),!0)}setMatrices(e,t){return!!e&&(this._gl.uniformMatrix4fv(e,!1,t),!0)}setMatrix3x3(e,t){return!!e&&(this._gl.uniformMatrix3fv(e,!1,t),!0)}setMatrix2x2(e,t){return!!e&&(this._gl.uniformMatrix2fv(e,!1,t),!0)}setFloat(e,t){return!!e&&(this._gl.uniform1f(e,t),!0)}setFloat2(e,t,r){return!!e&&(this._gl.uniform2f(e,t,r),!0)}setFloat3(e,t,r,i){return!!e&&(this._gl.uniform3f(e,t,r,i),!0)}setFloat4(e,t,r,i,s){return!!e&&(this._gl.uniform4f(e,t,r,i,s),!0)}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;let e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}clearInternalTexturesCache(){this._internalTexturesCache.length=0}wipeCaches(e){(!this.preventCacheWipeBetweenFrames||e)&&(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=1,this._alphaEquation=0,this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){let r=this._gl,i=r.NEAREST,s=r.NEAREST;switch(e){case 11:i=r.LINEAR,s=t?r.LINEAR_MIPMAP_NEAREST:r.LINEAR;break;case 3:i=r.LINEAR,s=t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR;break;case 8:i=r.NEAREST,s=t?r.NEAREST_MIPMAP_LINEAR:r.NEAREST;break;case 4:i=r.NEAREST,s=t?r.NEAREST_MIPMAP_NEAREST:r.NEAREST;break;case 5:i=r.NEAREST,s=t?r.LINEAR_MIPMAP_NEAREST:r.LINEAR;break;case 6:i=r.NEAREST,s=t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR;break;case 7:i=r.NEAREST,s=r.LINEAR;break;case 1:i=r.NEAREST,s=r.NEAREST;break;case 9:i=r.LINEAR,s=t?r.NEAREST_MIPMAP_NEAREST:r.NEAREST;break;case 10:i=r.LINEAR,s=t?r.NEAREST_MIPMAP_LINEAR:r.NEAREST;break;case 2:i=r.LINEAR,s=r.LINEAR;break;case 12:i=r.LINEAR,s=r.NEAREST}return{min:s,mag:i}}_createTexture(){let e=this._gl.createTexture();if(!e)throw Error("Unable to create texture");return e}_createHardwareTexture(){return new T.B(this._createTexture(),this._gl)}_createInternalTexture(e,t,r=!0,i=o.S.Unknown){var s;let n;let a=!1,l=0,_=3,h=5,d=!1,g=1;void 0!==t&&"object"==typeof t?(a=!!t.generateMipMaps,l=void 0===t.type?0:t.type,_=void 0===t.samplingMode?3:t.samplingMode,h=void 0===t.format?5:t.format,d=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,g=null!==(s=t.samples)&&void 0!==s?s:1,n=t.label):a=!!t,d&&(d=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(1!==l||this._caps.textureFloatLinearFiltering)&&(2!==l||this._caps.textureHalfFloatLinearFiltering)||(_=1),1!==l||this._caps.textureFloat||(l=0,u.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let c=this._gl,f=new o.l(this,i),E=e.width||e,p=e.height||e,T=e.layers||0,R=this._getSamplingParameters(_,a),x=0!==T?c.TEXTURE_2D_ARRAY:c.TEXTURE_2D,m=this._getRGBABufferInternalSizedFormat(l,h,d),b=this._getInternalFormat(h),A=this._getWebGLTextureType(l);return this._bindTextureDirectly(x,f),0!==T?(f.is2DArray=!0,c.texImage3D(x,0,m,E,p,T,0,b,A,null)):c.texImage2D(x,0,m,E,p,0,b,A,null),c.texParameteri(x,c.TEXTURE_MAG_FILTER,R.mag),c.texParameteri(x,c.TEXTURE_MIN_FILTER,R.min),c.texParameteri(x,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(x,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),a&&this._gl.generateMipmap(x),this._bindTextureDirectly(x,null),f._useSRGBBuffer=d,f.baseWidth=E,f.baseHeight=p,f.width=E,f.height=p,f.depth=T,f.isReady=!0,f.samples=g,f.generateMipMaps=a,f.samplingMode=_,f.type=l,f.format=h,f.label=n,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,r,s,n=3,a=null,l=null,_,h,d=null,g=null,c=null,f=null,E,p,T){e=e||"";let R="data:"===e.substr(0,5),x="blob:"===e.substr(0,5),m=R&&-1!==e.indexOf(";base64,"),b=g||new o.l(this,o.S.Url);b!==g&&(b.label=e.substring(0,60));let A=e;!this._transformTextureUrl||m||g||d||(e=this._transformTextureUrl(e)),A!==e&&(b._originalUrl=A);let S=e.lastIndexOf("."),C=f||(S>-1?e.substring(S).toLowerCase():""),B=null,v=C.indexOf("?");for(let e of(v>-1&&(C=C.split("?")[0]),ThinEngine._TextureLoaders))if(e.canLoad(C,E)){B=e;break}s&&s.addPendingData(b),b.url=e,b.generateMipMaps=!t,b.samplingMode=n,b.invertY=r,b._useSRGBBuffer=this._getUseSRGBBuffer(!!T,t),this._doNotHandleContextLost||(b._buffer=d);let L=null;a&&!g&&(L=b.onLoadedObservable.add(a)),g||this._internalTexturesCache.push(b);let onInternalError=(r,o)=>{s&&s.removePendingData(b),e===A?(L&&b.onLoadedObservable.remove(L),i.l.UseFallbackTexture&&this._createTextureBase(i.l.FallbackTexture,t,b.invertY,s,n,null,l,_,h,d,b),r=(r||"Unknown error")+(i.l.UseFallbackTexture?" - Fallback texture was used":""),b.onErrorObservable.notifyObservers({message:r,exception:o}),l&&l(r,o)):(u.Y.Warn(`Failed to load ${e}, falling back to ${A}`),this._createTextureBase(A,t,b.invertY,s,n,a,l,_,h,d,b,c,f,E,p,T))};if(B){let callback=e=>{B.loadData(e,b,(e,t,r,i,a,l)=>{l?onInternalError("TextureLoader failed to load data"):_(b,C,s,{width:e,height:t},b.invertY,!r,i,()=>(a(),!1),n)},p)};d?d instanceof ArrayBuffer?callback(new Uint8Array(d)):ArrayBuffer.isView(d)?callback(d):l&&l("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,e=>callback(new Uint8Array(e)),void 0,s?s.offlineProvider:void 0,!0,(e,t)=>{onInternalError("Unable to load "+(e&&e.responseURL,t))})}else{let onload=e=>{x&&!this._doNotHandleContextLost&&(b._buffer=e),_(b,C,s,e,b.invertY,t,!1,h,n)};!R||m?d&&("string"==typeof d.decoding||d.close)?onload(d):ThinEngine._FileToolsLoadImage(e,onload,onInternalError,s?s.offlineProvider:null,E,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof d||d instanceof ArrayBuffer||ArrayBuffer.isView(d)||d instanceof Blob?ThinEngine._FileToolsLoadImage(d,onload,onInternalError,s?s.offlineProvider:null,E,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):d&&onload(d)}return b}createTexture(e,t,r,i,s=3,n=null,a=null,l=null,_=null,h=null,u=null,d,g,c,f){return this._createTextureBase(e,t,r,i,s,n,a,this._prepareWebGLTexture.bind(this),(e,t,r,s,n,a)=>{let l=this._gl,_=r.width===e&&r.height===t,u=this._getTexImageParametersForCreateTexture(h,s,n._useSRGBBuffer);if(_)return l.texImage2D(l.TEXTURE_2D,0,u.internalFormat,u.format,u.type,r),!1;let d=this._caps.maxTextureSize;if(r.width>d||r.height>d||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!!this._workingCanvas&&!!this._workingContext&&(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(r,0,0,r.width,r.height,0,0,e,t),l.texImage2D(l.TEXTURE_2D,0,u.internalFormat,u.format,u.type,this._workingCanvas),n.width=e,n.height=t,!1);{let e=new o.l(this,o.S.Temp);this._bindTextureDirectly(l.TEXTURE_2D,e,!0),l.texImage2D(l.TEXTURE_2D,0,u.internalFormat,u.format,u.type,r),this._rescaleTexture(e,n,i,u.format,()=>{this._releaseTexture(e),this._bindTextureDirectly(l.TEXTURE_2D,n,!0),a()})}return!0},l,_,h,u,d,g,f)}_getTexImageParametersForCreateTexture(e,t,r){let i,s;return null==e&&(e=".jpg"!==t||r?5:4),1===this.webGLVersion?s=i=this._getInternalFormat(e,r):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,r)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}static _FileToolsLoadImage(e,t,r,i,s,a){throw(0,n.S)("FileTools")}_rescaleTexture(e,t,r,i,s){}createRawTexture(e,t,r,i,s,a,l,_=null,h=0,o=0,u=!1){throw(0,n.S)("Engine.RawTexture")}createRawCubeTexture(e,t,r,i,s,a,l,_=null){throw(0,n.S)("Engine.RawTexture")}createRawTexture3D(e,t,r,i,s,a,l,_,h=null,o=0){throw(0,n.S)("Engine.RawTexture")}createRawTexture2DArray(e,t,r,i,s,a,l,_,h=null,o=0){throw(0,n.S)("Engine.RawTexture")}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,r=!1){let i=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||r);this._setTextureParameterInteger(i,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(i,this._gl.TEXTURE_MIN_FILTER,s.min),r&&(t.generateMipMaps=!0,this._gl.generateMipmap(i)),this._bindTextureDirectly(i,null),t.samplingMode=e}updateTextureDimensions(e,t,r,i=1){}updateTextureWrappingMode(e,t,r=null,i=null){let s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==r&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(r),e),e._cachedWrapV=r),(e.is2DArray||e.is3D)&&null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(i),e),e._cachedWrapR=i),this._bindTextureDirectly(s,null)}_setupDepthStencilTexture(e,t,r,i,s,n=1){let a=t.width||t,l=t.height||t,_=t.layers||0;e.baseWidth=a,e.baseHeight=l,e.width=a,e.height=l,e.is2DArray=_>0,e.depth=_,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=i?2:1,e.type=0,e._comparisonFunction=s;let h=this._gl,o=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(o,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(o,h.TEXTURE_MIN_FILTER,u.min),h.texParameteri(o,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(o,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===s?(h.texParameteri(o,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(o,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(o,h.TEXTURE_COMPARE_FUNC,s),h.texParameteri(o,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,r,i,s,n=0,a=0){let l=this._gl,_=l.TEXTURE_2D;if(e.isCube&&(_=l.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(_,a,t,r,i,0,s)}_uploadDataToTextureDirectly(e,t,r=0,i=0,s,n=!1){let a=this._gl,l=this._getWebGLTextureType(e.type),_=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let o=a.TEXTURE_2D;e.isCube&&(o=a.TEXTURE_CUBE_MAP_POSITIVE_X+r);let u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),g=n?e.width:Math.pow(2,Math.max(u-i,0)),c=n?e.height:Math.pow(2,Math.max(d-i,0));a.texImage2D(o,i,h,g,c,0,_,l,t)}updateTextureData(e,t,r,i,s,n,a=0,l=0,_=!1){let h=this._gl,o=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,g=h.TEXTURE_2D;e.isCube&&(g=h.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(g,l,r,i,s,n,u,o,t),_&&this._gl.generateMipmap(g),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,r=0,i=0){let s=this._gl,n=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,r,i),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,r,i,s){let n=this._gl;if(!n)return;let a=this._getSamplingParameters(s,!r);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),r||i||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,r,i,s,n,a,l,_=3){let h=this.getCaps().maxTextureSize,o=Math.min(h,this.needPOTTextures?ThinEngine.GetExponentOfTwo(i.width,h):i.width),u=Math.min(h,this.needPOTTextures?ThinEngine.GetExponentOfTwo(i.height,h):i.height),d=this._gl;if(d){if(!e._hardwareTexture){r&&r.removePendingData(e);return}this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=i.width,e.baseHeight=i.height,e.width=o,e.height=u,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:".jpg"!==t||e._useSRGBBuffer?5:4,l(o,u,i,t,e,()=>{this._prepareWebGLTextureContinuation(e,r,n,a,_)})||this._prepareWebGLTextureContinuation(e,r,n,a,_)}}_setupFramebufferDepthAttachments(e,t,r,i,s=1){let n=this._gl;if(e&&t)return this._createRenderBuffer(r,i,s,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(r,i,s,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(r,i,s,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,r,i,s,n,a=!0){let l=this._gl,_=l.createRenderbuffer();return this._updateRenderBuffer(_,e,t,r,i,s,n,a)}_updateRenderBuffer(e,t,r,i,s,n,a,l=!0){let _=this._gl;return _.bindRenderbuffer(_.RENDERBUFFER,e),i>1&&_.renderbufferStorageMultisample?_.renderbufferStorageMultisample(_.RENDERBUFFER,i,n,t,r):_.renderbufferStorage(_.RENDERBUFFER,s,t,r),_.framebufferRenderbuffer(_.FRAMEBUFFER,a,_.RENDERBUFFER,e),l&&_.bindRenderbuffer(_.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource),this.unbindAllTextures();let r=this._internalTexturesCache.indexOf(e);-1!==r&&this._internalTexturesCache.splice(r,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){let t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.program);let r=e.getSamplers();for(let t=0;t<r.length;t++){let i=e.getUniform(r[t]);i&&(this._boundUniforms[t]=i)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,r=!1,i=!1){var s,n;let a=!1,l=t&&t._associatedChannel>-1;r&&l&&(this._activeChannel=t._associatedChannel);let _=this._boundTexturesCache[this._activeChannel];if(_!==t||i){if(this._activateCurrentTexture(),t&&t.isMultiview)throw console.error(e,t),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,null!==(n=null===(s=null==t?void 0:t._hardwareTexture)||void 0===s?void 0:s.underlyingResource)&&void 0!==n?n:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else r&&(a=!0,this._activateCurrentTexture());return l&&!r&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a}_bindTexture(e,t,r){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;let i=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(i,t)}unbindAllTextures(){for(let e=0;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,r,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,r))}_bindSamplerUniformToChannel(e,t){let r=this._boundUniforms[e];r&&r._currentState!==t&&(this._gl.uniform1i(r,t),r._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:break;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,r=!1,i=!1,s=""){let n;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;let r=t.getInternalTexture();r&&(r._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;n=i?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!r&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(r||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;let l=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(l,n,r),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;let e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(l,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,r,i){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===r.length||(this._textureUnits=new Int32Array(r.length));for(let t=0;t<r.length;t++){let i=r[t].getInternalTexture();i?(this._textureUnits[t]=e+t,i._associatedChannel=e+t):this._textureUnits[t]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let e=0;e<r.length;e++)this._setTexture(this._textureUnits[e],r[e],!0)}}_setAnisotropicLevel(e,t,r){let i=this._caps.textureAnisotropicFilterExtension;11!==t.samplingMode&&3!==t.samplingMode&&2!==t.samplingMode&&(r=1),i&&t._cachedAnisotropicFilteringLevel!==r&&(this._setTextureParameterFloat(e,i.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(r,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=r)}_setTextureParameterFloat(e,t,r,i){this._bindTextureDirectly(e,i,!0,!0),this._gl.texParameterf(e,t,r)}_setTextureParameterInteger(e,t,r,i){i&&this._bindTextureDirectly(e,i,!0,!0),this._gl.texParameteri(e,t,r)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e);return}for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)!(e>=this._caps.maxVertexAttribs)&&this._vertexAttribArraysEnabled[e]&&this.disableAttributeByIndex(e)}releaseEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e,t;for(let t of(this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),null===(e=this.releaseComputeEffects)||void 0===e||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},(0,d.CG)()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,s.Q.ResetCache(),this._activeRequests))t.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._creationOptions.loseContextOnDispose&&(null===(t=this._gl.getExtension("WEBGL_lose_context"))||void 0===t||t.loseContext())}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){let t=this._gl;for(;t.getError()!==t.NO_ERROR;);let r=!0,i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);let s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0);let n=t.checkFramebufferStatus(t.FRAMEBUFFER);if((r=(r=r&&n===t.FRAMEBUFFER_COMPLETE)&&t.getError()===t.NO_ERROR)&&(t.clear(t.COLOR_BUFFER_BIT),r=r&&t.getError()===t.NO_ERROR),r){t.bindFramebuffer(t.FRAMEBUFFER,null);let e=t.RGBA,i=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,i,s),r=r&&t.getError()===t.NO_ERROR}for(t.deleteTexture(i),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!r&&t.getError()!==t.NO_ERROR;);return r}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:break;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:break;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let r=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:r=this._gl.ALPHA;break;case 1:r=this._gl.LUMINANCE;break;case 2:r=this._gl.LUMINANCE_ALPHA;break;case 6:r=this._gl.RED;break;case 7:r=this._gl.RG;break;case 4:r=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:r=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:r=this._gl.RED_INTEGER;break;case 9:r=this._gl.RG_INTEGER;break;case 10:r=this._gl.RGB_INTEGER;break;case 11:r=this._gl.RGBA_INTEGER}return r}_getRGBABufferInternalSizedFormat(e,t,r=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return r?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return r?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return r?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return r?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_getRGBAMultiSampleBufferFormat(e,t=5){switch(e){case 1:if(6===t)return this._gl.R32F;return this._gl.RGBA32F;case 2:if(6===t)return this._gl.R16F;return this._gl.RGBA16F}return this._gl.RGBA8}_loadFile(e,t,r,i,s,n){let a=ThinEngine._FileToolsLoadFile(e,t,r,i,s,n);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}static _FileToolsLoadFile(e,t,r,i,s,a){throw(0,n.S)("FileTools")}readPixels(e,t,r,i,s=!0,n=!0){let a=s?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(i*r*(s?4:3));return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,r,i,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{let e=this._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{let e=this._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){let t=ThinEngine.CeilingPOT(e),r=ThinEngine.FloorPOT(e);return t-e>e-r?r:t}static GetExponentOfTwo(e,t,r=2){let i;switch(r){case 1:i=ThinEngine.FloorPOT(e);break;case 2:i=ThinEngine.NearestPOT(e);break;default:i=ThinEngine.CeilingPOT(e)}return Math.min(i,t)}static QueueNewFrame(e,t){if((0,d.CG)()){let{requestAnimationFrame:r}=t||window;if("function"==typeof r)return r(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:(0,d.n5)()?document:null}};ThinEngine._TempClearColorUint32=new Uint32Array(4),ThinEngine._TempClearColorInt32=new Int32Array(4),ThinEngine.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],ThinEngine._TextureLoaders=[],ThinEngine.CollisionsEpsilon=.001,ThinEngine._IsSupported=null,ThinEngine._HasMajorPerformanceCaveat=null}}]); \ No newline at end of file diff --git a/.next/static/chunks/e1206f8c-ab5b5541f866e530.js b/.next/static/chunks/e1206f8c-ab5b5541f866e530.js new file mode 100644 index 0000000..ebacd7b --- /dev/null +++ b/.next/static/chunks/e1206f8c-ab5b5541f866e530.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[732],{6540:function(e,t,s){s.d(t,{a:function(){return r},x:function(){return Scene}});var i,r,a=s(5132),n=s(7662),o=s(4800),h=s(8355),l=s(1186),d=s(1803),c=s(78),u=s(800),g=s(1974),m=s(9691),f=s(2248),_=s(9528),v=s(5184),b=s(2195),p=s(7609),M=s(7209),C=s(6030),y=s(6131),R=s(8668),O=s(7263),S=s(2983),A=s(2975),P=s(7531),w=s(1166),T=s(6972),B=s(4254),D=s(7077),k=s(9626);(i=r||(r={}))[i.BackwardCompatible=0]="BackwardCompatible",i[i.Intermediate=1]="Intermediate",i[i.Aggressive=2]="Aggressive";let Scene=class Scene extends u.p{static DefaultMaterialFactory(e){throw(0,y.S)("StandardMaterial")}static CollisionCoordinatorFactory(){throw(0,y.S)("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case r.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case r.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case r.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return R.$.DragMovementThreshold}static set DragMovementThreshold(e){R.$.DragMovementThreshold=e}static get LongPressDelay(){return R.$.LongPressDelay}static set LongPressDelay(e){R.$.LongPressDelay=e}static get DoubleClickDelay(){return R.$.DoubleClickDelay}static set DoubleClickDelay(e){R.$.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return R.$.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){R.$.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",s=!1){let i=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return c.jp.Vector4[0].set(i.x,i.y,i.z,r?-1:1),e&&(s?e.setFloat3(t,c.jp.Vector4[0].x,c.jp.Vector4[0].y,c.jp.Vector4[0].z):e.setVector4(t,c.jp.Vector4[0])),c.jp.Vector4[0]}finalizeSceneUbo(){let e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=(0,B.M)(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=Scene.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=Scene.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(let e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e),e.addFromContainer&&e.serialize&&this._serializableComponents.push(e)}_getComponent(e){for(let t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new R.$(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new S.HE(.2,.2,.3,1),this.ambientColor=new S.Wo(0,0,0),this.environmentIntensity=1,this._performancePriority=r.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new o.y$,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new o.y$,this._onDisposeObserver=null,this.onBeforeRenderObservable=new o.y$,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new o.y$,this.onAfterRenderCameraObservable=new o.y$,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new o.y$,this.onAfterAnimationsObservable=new o.y$,this.onBeforeDrawPhaseObservable=new o.y$,this.onAfterDrawPhaseObservable=new o.y$,this.onReadyObservable=new o.y$,this.onBeforeCameraRenderObservable=new o.y$,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new o.y$,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new o.y$,this.onAfterActiveMeshesEvaluationObservable=new o.y$,this.onBeforeParticlesRenderingObservable=new o.y$,this.onAfterParticlesRenderingObservable=new o.y$,this.onDataLoadedObservable=new o.y$,this.onNewCameraAddedObservable=new o.y$,this.onCameraRemovedObservable=new o.y$,this.onNewLightAddedObservable=new o.y$,this.onLightRemovedObservable=new o.y$,this.onNewGeometryAddedObservable=new o.y$,this.onGeometryRemovedObservable=new o.y$,this.onNewTransformNodeAddedObservable=new o.y$,this.onTransformNodeRemovedObservable=new o.y$,this.onNewMeshAddedObservable=new o.y$,this.onMeshRemovedObservable=new o.y$,this.onNewSkeletonAddedObservable=new o.y$,this.onSkeletonRemovedObservable=new o.y$,this.onNewMaterialAddedObservable=new o.y$,this.onNewMultiMaterialAddedObservable=new o.y$,this.onMaterialRemovedObservable=new o.y$,this.onMultiMaterialRemovedObservable=new o.y$,this.onNewTextureAddedObservable=new o.y$,this.onTextureRemovedObservable=new o.y$,this.onBeforeRenderTargetsRenderObservable=new o.y$,this.onAfterRenderTargetsRenderObservable=new o.y$,this.onBeforeStepObservable=new o.y$,this.onAfterStepObservable=new o.y$,this.onActiveCameraChanged=new o.y$,this.onActiveCamerasChanged=new o.y$,this.onBeforeRenderingGroupObservable=new o.y$,this.onAfterRenderingGroupObservable=new o.y$,this.onMeshImportedObservable=new o.y$,this.onAnimationFileImportedObservable=new o.y$,this._registeredForLateAnimationBindings=new h.f(256),this._pointerPickingConfiguration=new D.M,this.onPrePointerObservable=new o.y$,this.onPointerObservable=new o.y$,this.onPreKeyboardObservable=new o.y$,this.onKeyboardObservable=new o.y$,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Scene.FOGMODE_NONE,this.fogColor=new S.Wo(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new c.P(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new h.f(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new O.z,this._activeIndices=new O.z,this._activeParticles=new O.z,this._activeBones=new O.z,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=Array(256),this._activeRequests=[],this._pendingData=[],this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new h.t(256),this._processedMaterials=new h.t(256),this._renderTargets=new h.f(256),this._materialsRenderTargets=new h.f(256),this._activeParticleSystems=new h.t(256),this._activeSkeletons=new h.f(32),this._softwareSkinnedMeshes=new h.f(32),this._activeAnimatables=[],this._transformMatrix=c.y3.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=p.H.Create(),this._beforeClearStage=p.H.Create(),this._beforeRenderTargetClearStage=p.H.Create(),this._gatherRenderTargetsStage=p.H.Create(),this._gatherActiveCameraRenderTargetsStage=p.H.Create(),this._isReadyForMeshStage=p.H.Create(),this._beforeEvaluateActiveMeshStage=p.H.Create(),this._evaluateSubMeshStage=p.H.Create(),this._preActiveMeshStage=p.H.Create(),this._cameraDrawRenderTargetStage=p.H.Create(),this._beforeCameraDrawStage=p.H.Create(),this._beforeRenderTargetDrawStage=p.H.Create(),this._beforeRenderingGroupDrawStage=p.H.Create(),this._beforeRenderingMeshStage=p.H.Create(),this._afterRenderingMeshStage=p.H.Create(),this._afterRenderingGroupDrawStage=p.H.Create(),this._afterCameraDrawStage=p.H.Create(),this._afterCameraPostProcessStage=p.H.Create(),this._afterRenderTargetDrawStage=p.H.Create(),this._afterRenderTargetPostProcessStage=p.H.Create(),this._afterRenderStage=p.H.Create(),this._pointerMoveStage=p.H.Create(),this._pointerDownStage=p.H.Create(),this._pointerUpStage=p.H.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];let s=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);e=this._engine=e||C.l.LastCreatedEngine,s.virtual?e._virtualScenes.push(this):(C.l._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new b.$(this),v.O&&(this.postProcessManager=new v.O(this)),(0,M.CG)()&&this.attachControl(),this._createUbo(),g.$&&(this._imageProcessingConfiguration=new g.$),this.setDefaultCandidateProviders(),s.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=s.useMaterialMeshMap,this.useClonedMeshMap=s.useClonedMeshMap,t&&t.virtual||e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,s=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==s}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,s){return this._inputManager.simulatePointerUp(e,t,s),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,s=!0){this._inputManager.attachControl(e,t,s)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var t,s,i;let r;if(this._isDisposed)return!1;let a=this.getEngine(),n=a.currentRenderPassId;a.currentRenderPassId=null!==(s=null===(t=this.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==s?s:n;let o=!0;for(this._pendingData.length>0&&(o=!1),null===(i=this.prePassRenderer)||void 0===i||i.update(),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),r=0;r<this.meshes.length;r++){let t=this.meshes[r];if(!t.subMeshes||0===t.subMeshes.length)continue;if(!t.isReady(!0)){o=!1;continue}let s=t.hasThinInstances||"InstancedMesh"===t.getClassName()||"InstancedLinesMesh"===t.getClassName()||a.getCaps().instancedArrays&&t.instances.length>0;for(let e of this._isReadyForMeshStage)e.action(t,s)||(o=!1);if(!e)continue;let i=t.material||this.defaultMaterial;if(i){if(i._storeEffectOnSubMeshes)for(let e of t.subMeshes){let t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else i.hasRenderTargetTextures&&null!=i.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(i)&&(this._processedMaterials.push(i),this._materialsRenderTargets.concatWithNoDuplicate(i.getRenderTargetTextures()))}}if(e)for(r=0;r<this._materialsRenderTargets.length;++r){let e=this._materialsRenderTargets.data[r];e.isReadyForRendering()||(o=!1)}for(r=0;r<this.geometries.length;r++){let e=this.geometries[r];2===e.delayLoadState&&(o=!1)}if(this.activeCameras&&this.activeCameras.length>0)for(let e of this.activeCameras)e.isReady(!0)||(o=!1);else this.activeCamera&&!this.activeCamera.isReady(!0)&&(o=!1);for(let e of this.particleSystems)e.isReady()||(o=!1);if(this.layers)for(let e of this.layers)e.isReady()||(o=!1);return a.areAllEffectsReady()||(o=!1),a.currentRenderPassId=n,o}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){let execFunc=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(execFunc)})};this.registerBeforeRender(execFunc)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){let t=this.isLoading,s=this._pendingData.indexOf(e);-1!==s&&this._pendingData.splice(s,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_checkIsReady(e=!1){if(this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=n.F.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,s,i){s||i||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),(this._viewUpdateFlag!==e.updateFlag||this._projectionUpdateFlag!==t.updateFlag)&&(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?A.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=A.i.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(s,i):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){let t=new m.M(this._engine,void 0,!1,null!=e?e:"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return P.K.UniqueId}addMesh(e,t=!1){!this._blockEntityCollection&&(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(e=>{this.addMesh(e)}))}removeMesh(e,t=!1){let s=this.meshes.indexOf(e);return -1===s||(this.meshes[s]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(e=>{this.removeMesh(e)}),s}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){let t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){let e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){let t=this.skeletons.indexOf(e);return -1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){let t=this.morphTargetManagers.indexOf(e);return -1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){let t=this.lights.indexOf(e);if(-1!==t){for(let t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){let t=this.cameras.indexOf(e);if(-1===t||(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){let t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){let t=this.particleSystems.indexOf(e);return -1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){let t=this.animations.indexOf(e);return -1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,s){}removeAnimationGroup(e){let t=this.animationGroups.indexOf(e);return -1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){let t=this.multiMaterials.indexOf(e);return -1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){let t=e._indexInSceneMaterialArray;if(-1!==t&&t<this.materials.length){if(t!==this.materials.length-1){let e=this.materials[this.materials.length-1];this.materials[t]=e,e._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t}removeActionManager(e){let t=this.actionManagers.indexOf(e);return -1!==t&&this.actionManagers.splice(t,1),t}removeTexture(e){let t=this.textures.indexOf(e);return -1!==t&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t}addLight(e){if(!this._blockEntityCollection){for(let t of(this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes(),this.meshes))-1===t.lightSources.indexOf(e)&&(t.lightSources.push(e),t._resyncLightSources());this.onNewLightAddedObservable.notifyObservers(e)}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(T.m.CompareLightsPriority)}addCamera(e){!this._blockEntityCollection&&(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),this.onNewSkeletonAddedObservable.notifyObservers(e))}addParticleSystem(e){this._blockEntityCollection||this.particleSystems.push(e)}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||this.animationGroups.push(e)}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),this.onNewMultiMaterialAddedObservable.notifyObservers(e))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),this.onNewMaterialAddedObservable.notifyObservers(e))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}switchActiveCamera(e,t=!0){let s=this._engine.getInputElement();s&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){let t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){let t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null}_getMaterial(e,t){for(let e=0;e<this.materials.length;e++){let s=this.materials[e];if(t(s))return s}if(e)for(let e=0;e<this.multiMaterials.length;e++){let s=this.multiMaterials[e];if(t(s))return s}return null}getMaterialByUniqueID(e,t=!1){return this._getMaterial(t,t=>t.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,t=>t.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,t=>t.name===e)}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t){for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t]}return null}getTextureByUniqueId(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null}getTextureByName(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null}getCameraById(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null}getCameraByUniqueId(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null}getCameraByName(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null}getBoneById(e){for(let t=0;t<this.skeletons.length;t++){let s=this.skeletons[t];for(let t=0;t<s.bones.length;t++)if(s.bones[t].id===e)return s.bones[t]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){let s=this.skeletons[t];for(let t=0;t<s.bones.length;t++)if(s.bones[t].name===e)return s.bones[t]}return null}getLightByName(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null}getLightById(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null}getLightByUniqueId(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null}getParticleSystemById(e){for(let t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null}getGeometryById(e){for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null}_getGeometryByUniqueId(e){if(this._geometriesByUniqueId){let t=this._geometriesByUniqueId[e];if(void 0!==t)return this.geometries[t]}else for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null}pushGeometry(e,t){return!(!t&&this._getGeometryByUniqueId(e.uniqueId))&&(this.addGeometry(e),this.onNewGeometryAddedObservable.notifyObservers(e),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(void 0===(t=this._geometriesByUniqueId[e.uniqueId]))return!1}else if((t=this.geometries.indexOf(e))<0)return!1;if(t!==this.geometries.length-1){let e=this.geometries[this.geometries.length-1];e&&(this.geometries[t]=e,this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null}getMeshesById(e){return this.meshes.filter(function(t){return t.id===e})}getTransformNodeById(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getTransformNodeByUniqueId(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null}getTransformNodesById(e){return this.transformNodes.filter(function(t){return t.id===e})}getMeshByUniqueId(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null}getLastMeshById(e){for(let t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){let t=this.getMeshById(e);if(t)return t;let s=this.getTransformNodeById(e);if(s)return s;let i=this.getLightById(e);if(i)return i;let r=this.getCameraById(e);if(r)return r;let a=this.getBoneById(e);return a||null}getNodeByName(e){let t=this.getMeshByName(e);if(t)return t;let s=this.getTransformNodeByName(e);if(s)return s;let i=this.getLightByName(e);if(i)return i;let r=this.getCameraByName(e);if(r)return r;let a=this.getBoneByName(e);return a||null}getMeshByName(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null}getTransformNodeByName(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null}getLastSkeletonById(e){for(let t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null}getSkeletonById(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByName(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null}getMorphTargetManagerById(e){for(let t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null}getMorphTargetById(e){for(let t=0;t<this.morphTargetManagers.length;++t){let s=this.morphTargetManagers[t];for(let t=0;t<s.numTargets;++t){let i=s.getTarget(t);if(i.id===e)return i}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){let s=this.morphTargetManagers[t];for(let t=0;t<s.numTargets;++t){let i=s.getTarget(t);if(i.name===e)return i}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){let s=this.postProcesses[t];if(s.name===e)return s}return null}isActiveMesh(e){return -1!==this._activeMeshes.indexOf(e)}get uid(){return this._uid||(this._uid=a.w1.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new l.x),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new l.x),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,s,i){if(i||e.isInFrustum(this._frustumPlanes)){for(let s of this._evaluateSubMeshStage)s.action(t,e);let s=e.getMaterial();null!=s&&(s.hasRenderTargetTextures&&null!=s.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(s)&&(this._processedMaterials.push(s),this._materialsRenderTargets.concatWithNoDuplicate(s.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,s))}}freeProcessedMaterials(){this._processedMaterials.dispose()}get blockfreeActiveMeshesAndRenderingGroups(){return this._preventFreeActiveMeshesAndRenderingGroups}set blockfreeActiveMeshesAndRenderingGroups(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)}freeActiveMeshes(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(let e=0;e<this.activeCameras.length;e++){let t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}}freeRenderingGroups(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(let e=0;e<this.textures.length;e++){let t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}}_isInIntermediateRendering(){return this._intermediateRendering}freezeActiveMeshes(e=!1,t,s,i=!0,r=!1){return this.executeWhenReady(()=>{if(!this.activeCamera){s&&s("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,i)for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._freeze();t&&t()}),this}unfreezeActiveMeshes(){for(let e=0;e<this.meshes.length;e++){let t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this}_executeActiveContainerCleanup(e){let t=this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode;!t&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce(()=>e.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode){this._activeMeshes.length>0&&(null===(e=this.activeCamera)||void 0===e||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){let e=this._activeMeshes.length;for(let t=0;t<e;t++){let e=this._activeMeshes.data[t];e.computeWorldMatrix()}}if(this._activeParticleSystems){let e=this._activeParticleSystems.length;for(let t=0;t<e;t++)this._activeParticleSystems.data[t].animate()}this._renderingManager.resetSprites();return}if(!this.activeCamera)return;for(let e of(this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset(),this._beforeEvaluateActiveMeshStage))e.action();let t=this.getActiveMeshCandidates(),s=t.length;for(let e=0;e<s;e++){let s=t.data[e];if(s._internalAbstractMeshDataInfo._currentLODIsUpToDate=!1,s.isBlocked||(this._totalVertices.addCount(s.getTotalVertices(),!1),!s.isReady()||!s.isEnabled()||s.scaling.hasAZeroComponent))continue;s.computeWorldMatrix(),s.actionManager&&s.actionManager.hasSpecificTriggers2(12,13)&&this._meshesForIntersections.pushNoDuplicate(s);let i=this.customLODSelector?this.customLODSelector(s,this.activeCamera):s.getLOD(this.activeCamera);if(s._internalAbstractMeshDataInfo._currentLOD=i,s._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,null!=i&&(i!==s&&0!==i.billboardMode&&i.computeWorldMatrix(),s._preActivate(),s.isVisible&&s.visibility>0&&(s.layerMask&this.activeCamera.layerMask)!=0&&(this._skipFrustumClipping||s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes)))){for(let e of(this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),i!==s&&i._activate(this._renderId,!1),this._preActiveMeshStage))e.action(s);s._activate(this._renderId,!1)&&(s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(i=s):i._internalAbstractMeshDataInfo._onlyForInstances=!1,i._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,i)),s._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e<this.particleSystems.length;e++){let t=this.particleSystems[e];if(!t.isStarted()||!t.emitter)continue;let s=t.emitter;(!s.position||s.isEnabled())&&(this._activeParticleSystems.push(t),t.animate(),this._renderingManager.dispatchParticles(t))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_activeMesh(e,t){this._skeletonsEnabled&&null!==t.skeleton&&void 0!==t.skeleton&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&(t.skeleton.prepare(),this._activeBones.addCount(t.skeleton.bones.length,!1)),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t));let s=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){let i=this.getActiveSubMeshCandidates(t),r=i.length;s=s||1===r;for(let a=0;a<r;a++){let r=i.data[a];this._evaluateSubMesh(r,t,e,s)}}}updateTransformMatrix(e){if(this.activeCamera){if(this.activeCamera._renderingMultiview){let t=this.activeCamera._rigCameras[0],s=this.activeCamera._rigCameras[1];this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e),s.getViewMatrix(),s.getProjectionMatrix(e))}else this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(e))}}_bindFrameBuffer(e,t=!0){e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer(),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(e&&e._multiviewTexture);else if(e&&e.outputRenderTarget&&!e._renderingMultiview){let t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):t.skipInitialClear||(this.autoClear&&this._engine.clear(t.clearColor||this.clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,s=!0){var i,r,n;if(e&&e._skipRendering)return;let o=this._engine;if(this._activeCamera=e,!this.activeCamera)throw Error("Active camera not set");if(o.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&s){let t=!0;e._renderingMultiview&&e.outputRenderTarget&&(t=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=t)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(let e=0;e<this._softwareSkinnedMeshes.length;e++){let t=this._softwareSkinnedMeshes.data[e];t.applySkeleton(t.skeleton)}for(let s of(this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture),this._gatherActiveCameraRenderTargetsStage))s.action(this._renderTargets);let h=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){a.w1.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e<this._renderTargets.length;e++){let t=this._renderTargets.data[e];if(t._shouldRender()){this._renderId++;let e=t.activeCamera&&t.activeCamera!==this.activeCamera;t.render(e,this.dumpNextRenderTargets),h=!0}}a.w1.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(let e of this._cameraDrawRenderTargetStage)h=e.action(this.activeCamera)||h;this._intermediateRendering=!1}for(let t of(this._engine.currentRenderPassId=null!==(n=null!==(r=null===(i=e.outputRenderTarget)||void 0===i?void 0:i.renderPassId)&&void 0!==r?r:e.renderPassId)&&void 0!==n?n:0,h&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame(),this._beforeCameraDrawStage))t.action(this.activeCamera);for(let e of(this.onBeforeDrawPhaseObservable.notifyObservers(this),o.snapshotRendering&&1===o.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this),this._afterCameraDrawStage))e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){let t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(let e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t<e._rigCameras.length;t++)this._renderForCamera(e._rigCameras[t],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)}_checkIntersections(){for(let e=0;e<this._meshesForIntersections.length;e++){let t=this._meshesForIntersections.data[e];if(t.actionManager)for(let e=0;t.actionManager&&e<t.actionManager.actions.length;e++){let s=t.actionManager.actions[e];if(12===s.trigger||13===s.trigger){let e=s.getTriggerParameter(),i=e.mesh?e.mesh:e,r=i.intersectsMesh(t,e.usePreciseIntersection),a=t._intersectionsInProgress.indexOf(i);r&&-1===a?12===s.trigger?(s._executeCurrent(_.V.CreateNew(t,void 0,i)),t._intersectionsInProgress.push(i)):13===s.trigger&&t._intersectionsInProgress.push(i):r||!(a>-1)||(13===s.trigger&&s._executeCurrent(_.V.CreateNew(t,void 0,i)),t.actionManager.hasSpecificTrigger(13,e=>{let t=e.mesh?e.mesh:e;return i===t})&&13!==s.trigger||t._intersectionsInProgress.splice(a,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Scene.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Scene.MaxDeltaTime))+this._timeAccumulator,t=this._engine.getTimeStep(),s=1e3/t/1e3,i=0,r=this._engine.getLockstepMaxSteps(),a=Math.floor(e/t);for(a=Math.min(a,r);e>0&&i<a;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*s,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,i++,e-=t;this._timeAccumulator=e<0?0:e}else{let e=this.useConstantAnimationDeltaTime?16:Math.max(Scene.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Scene.MaxDeltaTime));this._animationRatio=.06*e,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}}_clear(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)}_checkCameraRenderTarget(e){var t;if((null==e?void 0:e.outputRenderTarget)&&!(null==e?void 0:e.isRigCamera)&&(e.outputRenderTarget._cleared=!1),null===(t=null==e?void 0:e.rigCameras)||void 0===t?void 0:t.length)for(let t=0;t<e.rigCameras.length;++t){let s=e.rigCameras[t].outputRenderTarget;s&&(s._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(let t of this.meshes)t.resetDrawCache(e)}render(e=!0,t=!1){var s,i,r;if(this.isDisposed)return;for(let e of(this.onReadyObservable.hasObservers()&&null===this._executeWhenReadyTimeoutId&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),(null===(s=this.activeCameras)||void 0===s?void 0:s.length)&&this.activeCameras.forEach(this._checkCameraRenderTarget),this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(11),t||this.animate(),this._beforeCameraUpdateStage))e.action();if(e){if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++){let t=this.activeCameras[e];if(t.update(),0!==t.cameraRigMode)for(let e=0;e<t._rigCameras.length;e++)t._rigCameras[e].update()}else if(this.activeCamera&&(this.activeCamera.update(),0!==this.activeCamera.cameraRigMode))for(let e=0;e<this.activeCamera._rigCameras.length;e++)this.activeCamera._rigCameras[e].update()}this.onBeforeRenderObservable.notifyObservers(this);let n=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);let o=(null===(i=this.activeCameras)||void 0===i?void 0:i.length)?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){a.w1.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(let e=0;e<this.customRenderTargets.length;e++){let t=this.customRenderTargets[e];if(t._shouldRender()){if(this._renderId++,this.activeCamera=t.activeCamera||this.activeCamera,!this.activeCamera)throw Error("Active camera not set");n.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),t.render(o!==this.activeCamera,this.dumpNextRenderTargets)}}a.w1.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}for(let e of(this._engine.currentRenderPassId=null!==(r=null==o?void 0:o.renderPassId)&&void 0!==r?r:0,this.activeCamera=o,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this._beforeClearStage))e.action();for(let e of(this._clearFrameBuffer(this.activeCamera),this._gatherRenderTargetsStage))e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++)this._processSubCameras(this.activeCameras[e],e>0);else{if(!this.activeCamera)throw Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}for(let e of(this._checkIntersections(),this._afterRenderStage))e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e<this._toBeDisposed.length;e++){let t=this._toBeDisposed[e];t&&t.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this.importedMeshesFiles=[],this.stopAllAnimations&&(this._activeAnimatables.forEach(e=>{e.onAnimationEndObservable.clear(),e.onAnimationEnd=null}),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;let e=this._activeRequests.slice();for(let t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){console.error("An error occurred while calling onDisposeObservable!",e)}this.detachControl();let t=this._engine.getInputElement();if(t)for(let e=0;e<this.cameras.length;e++)this.cameras[e].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._disposeList(this.meshes,e=>e.dispose(!0)),this._disposeList(this.transformNodes,e=>e.dispose(!0));let s=this.cameras;this._disposeList(s),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),C.l._LastCreatedScene===this&&(this._engine.scenes.length>0?C.l._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:C.l._LastCreatedScene=null),(i=this._engine._virtualScenes.indexOf(this))>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){let s=e.slice(0);for(let e of(t=null!=t?t:e=>e.dispose(),s))t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e<this.meshes.length;e++){let t=this.meshes[e],s=t.geometry;s&&s.clearCachedData()}}cleanCachedTextureBuffer(){for(let e of this.textures){let t=e._buffer;t&&(e._buffer=null)}}getWorldExtends(e){let t=new c.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new c.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||(()=>!0),this.meshes.filter(e).forEach(e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;let i=e.getBoundingInfo(),r=i.boundingBox.minimumWorld,a=i.boundingBox.maximumWorld;c.P.CheckExtends(r,t,s),c.P.CheckExtends(a,t,s)}),{min:t,max:s}}createPickingRay(e,t,s,i,r=!1){throw(0,y.S)("Ray")}createPickingRayToRef(e,t,s,i,r,a=!1,n=!1){throw(0,y.S)("Ray")}createPickingRayInCameraSpace(e,t,s){throw(0,y.S)("Ray")}createPickingRayInCameraSpaceToRef(e,t,s,i){throw(0,y.S)("Ray")}get _pickingAvailable(){return!1}pick(e,t,s,i,r,a){let n=(0,y.S)("Ray",!0);return n&&k.Y.Warn(n),new f.p}pickWithBoundingInfo(e,t,s,i,r){let a=(0,y.S)("Ray",!0);return a&&k.Y.Warn(a),new f.p}pickWithRay(e,t,s,i){throw(0,y.S)("Ray")}multiPick(e,t,s,i,r){throw(0,y.S)("Ray")}multiPickWithRay(e,t,s){throw(0,y.S)("Ray")}setPointerOverMesh(e,t,s){this._inputManager.setPointerOverMesh(e,t,s)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of(this.postProcessManager&&this.postProcessManager._rebuild(),this._components))e.rebuild();for(let e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(let e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(let e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,s){if(void 0===t)return e;let i=[];for(let r in e){let a=e[r];d.$&&d.$.MatchesQuery(a,t)&&(!s||s(a))&&i.push(a)}return i}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,s=null,i=null){this._renderingManager.setRenderingOrder(e,t,s,i)}setRenderingAutoClearDepthStencil(e,t,s=!0,i=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,s,i)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(let s of this.materials)(!t||t(s))&&s.markAsDirty(e)}_loadFile(e,t,s,i,r,a,n){let o=(0,w.vP)(e,t,s,i?this.offlineProvider:void 0,r,a,n);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}_loadFileAsync(e,t,s,i,r){return new Promise((a,n)=>{this._loadFile(e,e=>{a(e)},t,s,i,(e,t)=>{n(t)},r)})}_requestFile(e,t,s,i,r,a,n){let o=(0,w.FV)(e,t,s,i?this.offlineProvider:void 0,r,a,n);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}_requestFileAsync(e,t,s,i,r){return new Promise((a,n)=>{this._requestFile(e,e=>{a(e)},t,s,i,e=>{n(e)},r)})}_readFile(e,t,s,i,r){let a=(0,w.Ip)(e,t,s,i,r);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}_readFileAsync(e,t,s){return new Promise((i,r)=>{this._readFile(e,e=>{i(e)},t,s,e=>{r(e)})})}getPerfCollector(){throw(0,y.S)("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}};Scene.FOGMODE_NONE=0,Scene.FOGMODE_EXP=1,Scene.FOGMODE_EXP2=2,Scene.FOGMODE_LINEAR=3,Scene.MinDeltaTime=1,Scene.MaxDeltaTime=1e3}}]); \ No newline at end of file diff --git a/.next/static/chunks/f126df28-0647fc1012c29407.js b/.next/static/chunks/f126df28-0647fc1012c29407.js deleted file mode 100644 index 6fe78b8..0000000 --- a/.next/static/chunks/f126df28-0647fc1012c29407.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9],{1823:function(t,e,r){r.d(e,{FM:function(){return l},Lt:function(){return y},P:function(){return c},_f:function(){return u},jp:function(){return R},y3:function(){return m}});var i=r(5526),s=r(156),o=r(4046),n=r(9678),a=r(4499),h=r(3914);let _=t=>parseInt(t.toString().replace(/\W/g,""));class l{constructor(t=0,e=0){this.x=t,this.y=e}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let t=_(this.x),e=_(this.y);return 397*t^e}toArray(t,e=0){return t[e]=this.x,t[e+1]=this.y,this}fromArray(t,e=0){return l.FromArrayToRef(t,e,this),this}asArray(){let t=[];return this.toArray(t,0),t}copyFrom(t){return this.x=t.x,this.y=t.y,this}copyFromFloats(t,e){return this.x=t,this.y=e,this}set(t,e){return this.copyFromFloats(t,e)}add(t){return new this.constructor(this.x+t.x,this.y+t.y)}addToRef(t,e){return e.x=this.x+t.x,e.y=this.y+t.y,e}addInPlace(t){return this.x+=t.x,this.y+=t.y,this}addVector3(t){return new this.constructor(this.x+t.x,this.y+t.y)}subtract(t){return new this.constructor(this.x-t.x,this.y-t.y)}subtractToRef(t,e){return e.x=this.x-t.x,e.y=this.y-t.y,e}subtractInPlace(t){return this.x-=t.x,this.y-=t.y,this}multiplyInPlace(t){return this.x*=t.x,this.y*=t.y,this}multiply(t){return new this.constructor(this.x*t.x,this.y*t.y)}multiplyToRef(t,e){return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByFloats(t,e){return new this.constructor(this.x*t,this.y*e)}divide(t){return new this.constructor(this.x/t.x,this.y/t.y)}divideToRef(t,e){return e.x=this.x/t.x,e.y=this.y/t.y,e}divideInPlace(t){return this.divideToRef(t,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(t){return t.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(t){return this.x*=t,this.y*=t,this}scale(t){let e=new this.constructor(0,0);return this.scaleToRef(t,e),e}scaleToRef(t,e){return e.x=this.x*t,e.y=this.y*t,e}scaleAndAddToRef(t,e){return e.x+=this.x*t,e.y+=this.y*t,e}equals(t){return t&&this.x===t.x&&this.y===t.y}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this.x,t.x,e)&&i.R.WithinEpsilon(this.y,t.y,e)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(t,e){let r=Math.cos(t),i=Math.sin(t),s=r*this.x-i*this.y,o=i*this.x+r*this.y;return e.x=s,e.y=o,e}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return l.NormalizeToRef(this,this),this}clone(){return new this.constructor(this.x,this.y)}static Zero(){return new l(0,0)}static One(){return new l(1,1)}static Random(t=0,e=1){return new l(i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static get ZeroReadOnly(){return l._ZeroReadOnly}static FromArray(t,e=0){return new l(t[e],t[e+1])}static FromArrayToRef(t,e,r){return r.x=t[e],r.y=t[e+1],r}static CatmullRom(t,e,r,i,s){let o=s*s,n=s*o,a=.5*(2*e.x+(-t.x+r.x)*s+(2*t.x-5*e.x+4*r.x-i.x)*o+(-t.x+3*e.x-3*r.x+i.x)*n),h=.5*(2*e.y+(-t.y+r.y)*s+(2*t.y-5*e.y+4*r.y-i.y)*o+(-t.y+3*e.y-3*r.y+i.y)*n);return new t.constructor(a,h)}static Clamp(t,e,r){let i=t.x;i=(i=i>r.x?r.x:i)<e.x?e.x:i;let s=t.y;return s=(s=s>r.y?r.y:s)<e.y?e.y:s,new t.constructor(i,s)}static Hermite(t,e,r,i,s){let o=s*s,n=s*o,a=2*n-3*o+1,h=-2*n+3*o,_=n-2*o+s,l=n-o,c=t.x*a+r.x*h+e.x*_+i.x*l,y=t.y*a+r.y*h+e.y*_+i.y*l;return new t.constructor(c,y)}static Hermite1stDerivative(t,e,r,i,s){let o=new t.constructor;return this.Hermite1stDerivativeToRef(t,e,r,i,s,o),o}static Hermite1stDerivativeToRef(t,e,r,i,s,o){let n=s*s;return o.x=(n-s)*6*t.x+(3*n-4*s+1)*e.x+(-n+s)*6*r.x+(3*n-2*s)*i.x,o.y=(n-s)*6*t.y+(3*n-4*s+1)*e.y+(-n+s)*6*r.y+(3*n-2*s)*i.y,o}static Lerp(t,e,r){let i=t.x+(e.x-t.x)*r,s=t.y+(e.y-t.y)*r;return new t.constructor(i,s)}static Dot(t,e){return t.x*e.x+t.y*e.y}static Normalize(t){let e=new t.constructor;return this.NormalizeToRef(t,e),e}static NormalizeToRef(t,e){let r=t.length();return 0===r||(e.x=t.x/r,e.y=t.y/r),e}static Minimize(t,e){let r=t.x<e.x?t.x:e.x,i=t.y<e.y?t.y:e.y;return new t.constructor(r,i)}static Maximize(t,e){let r=t.x>e.x?t.x:e.x,i=t.y>e.y?t.y:e.y;return new t.constructor(r,i)}static Transform(t,e){let r=new t.constructor;return l.TransformToRef(t,e,r),r}static TransformToRef(t,e,r){let i=e.m,s=t.x*i[0]+t.y*i[4]+i[12],o=t.x*i[1]+t.y*i[5]+i[13];return r.x=s,r.y=o,r}static PointInTriangle(t,e,r,i){let s=.5*(-r.y*i.x+e.y*(-r.x+i.x)+e.x*(r.y-i.y)+r.x*i.y),o=s<0?-1:1,n=(e.y*i.x-e.x*i.y+(i.y-e.y)*t.x+(e.x-i.x)*t.y)*o,a=(e.x*r.y-e.y*r.x+(e.y-r.y)*t.x+(r.x-e.x)*t.y)*o;return n>0&&a>0&&n+a<2*s*o}static Distance(t,e){return Math.sqrt(l.DistanceSquared(t,e))}static DistanceSquared(t,e){let r=t.x-e.x,i=t.y-e.y;return r*r+i*i}static Center(t,e){let r=new t.constructor;return l.CenterToRef(t,e,r)}static CenterToRef(t,e,r){return r.copyFromFloats((t.x+e.x)/2,(t.y+e.y)/2)}static DistanceOfPointFromSegment(t,e,r){let i=l.DistanceSquared(e,r);if(0===i)return l.Distance(t,e);let s=r.subtract(e),o=Math.max(0,Math.min(1,l.Dot(t.subtract(e),s)/i)),n=e.add(s.multiplyByFloats(o,o));return l.Distance(t,n)}}l._ZeroReadOnly=l.Zero();class c{get x(){return this._x}set x(t){this._x=t,this._isDirty=!0}get y(){return this._y}set y(t){this._y=t,this._isDirty=!0}get z(){return this._z}set z(t){this._z=t,this._isDirty=!0}constructor(t=0,e=0,r=0){this._isDirty=!0,this._x=t,this._y=e,this._z=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let t=_(this._x),e=_(this._y),r=_(this._z),i=t;return 397*(i=397*i^e)^r}asArray(){let t=[];return this.toArray(t,0),t}toArray(t,e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,this}fromArray(t,e=0){return c.FromArrayToRef(t,e,this),this}toQuaternion(){return u.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(t){return this.addInPlaceFromFloats(t._x,t._y,t._z)}addInPlaceFromFloats(t,e,r){return this._x+=t,this._y+=e,this._z+=r,this._isDirty=!0,this}add(t){return new this.constructor(this._x+t._x,this._y+t._y,this._z+t._z)}addToRef(t,e){return e.copyFromFloats(this._x+t._x,this._y+t._y,this._z+t._z)}subtractInPlace(t){return this._x-=t._x,this._y-=t._y,this._z-=t._z,this._isDirty=!0,this}subtract(t){return new this.constructor(this._x-t._x,this._y-t._y,this._z-t._z)}subtractToRef(t,e){return this.subtractFromFloatsToRef(t._x,t._y,t._z,e)}subtractFromFloats(t,e,r){return new this.constructor(this._x-t,this._y-e,this._z-r)}subtractFromFloatsToRef(t,e,r,i){return i.copyFromFloats(this._x-t,this._y-e,this._z-r)}negate(){return new this.constructor(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(t){return t.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(t){return this._x*=t,this._y*=t,this._z*=t,this._isDirty=!0,this}scale(t){return new this.constructor(this._x*t,this._y*t,this._z*t)}scaleToRef(t,e){return e.copyFromFloats(this._x*t,this._y*t,this._z*t)}getNormalToRef(t){let e=this.length(),r=Math.acos(this.y/e),i=Math.atan2(this.z,this.x);r>Math.PI/2?r-=Math.PI/2:r+=Math.PI/2;let s=e*Math.sin(r)*Math.cos(i),o=e*Math.cos(r),n=e*Math.sin(r)*Math.sin(i);return t.set(s,o,n),t}applyRotationQuaternionToRef(t,e){let r=this._x,i=this._y,s=this._z,o=t._x,n=t._y,a=t._z,h=t._w,_=2*(n*s-a*i),l=2*(a*r-o*s),c=2*(o*i-n*r);return e._x=r+h*_+n*c-a*l,e._y=i+h*l+a*_-o*c,e._z=s+h*c+o*l-n*_,e._isDirty=!0,e}applyRotationQuaternionInPlace(t){return this.applyRotationQuaternionToRef(t,this)}applyRotationQuaternion(t){return this.applyRotationQuaternionToRef(t,new this.constructor)}scaleAndAddToRef(t,e){return e.addInPlaceFromFloats(this._x*t,this._y*t,this._z*t)}projectOnPlane(t,e){let r=new this.constructor;return this.projectOnPlaneToRef(t,e,r),r}projectOnPlaneToRef(t,e,r){let i=t.normal,s=t.d,o=x.Vector3[0];this.subtractToRef(e,o),o.normalize();let n=c.Dot(o,i);if(1e-10>Math.abs(n))r.setAll(1/0);else{let t=-(c.Dot(e,i)+s)/n,a=o.scaleInPlace(t);e.addToRef(a,r)}return r}equals(t){return t&&this._x===t._x&&this._y===t._y&&this._z===t._z}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this._x,t._x,e)&&i.R.WithinEpsilon(this._y,t._y,e)&&i.R.WithinEpsilon(this._z,t._z,e)}equalsToFloats(t,e,r){return this._x===t&&this._y===e&&this._z===r}multiplyInPlace(t){return this._x*=t._x,this._y*=t._y,this._z*=t._z,this._isDirty=!0,this}multiply(t){return this.multiplyByFloats(t._x,t._y,t._z)}multiplyToRef(t,e){return e.copyFromFloats(this._x*t._x,this._y*t._y,this._z*t._z)}multiplyByFloats(t,e,r){return new this.constructor(this._x*t,this._y*e,this._z*r)}divide(t){return new this.constructor(this._x/t._x,this._y/t._y,this._z/t._z)}divideToRef(t,e){return e.copyFromFloats(this._x/t._x,this._y/t._y,this._z/t._z)}divideInPlace(t){return this.divideToRef(t,this)}minimizeInPlace(t){return this.minimizeInPlaceFromFloats(t._x,t._y,t._z)}maximizeInPlace(t){return this.maximizeInPlaceFromFloats(t._x,t._y,t._z)}minimizeInPlaceFromFloats(t,e,r){return t<this._x&&(this.x=t),e<this._y&&(this.y=e),r<this._z&&(this.z=r),this}maximizeInPlaceFromFloats(t,e,r){return t>this._x&&(this.x=t),e>this._y&&(this.y=e),r>this._z&&(this.z=r),this}isNonUniformWithinEpsilon(t){let e=Math.abs(this._x),r=Math.abs(this._y);if(!i.R.WithinEpsilon(e,r,t))return!0;let s=Math.abs(this._z);return!(i.R.WithinEpsilon(e,s,t)&&i.R.WithinEpsilon(r,s,t))}get isNonUniform(){let t=Math.abs(this._x),e=Math.abs(this._y);if(t!==e)return!0;let r=Math.abs(this._z);return t!==r}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(t){return"xyz"===(t=t.toLowerCase())||(x.Vector3[0].copyFrom(this),["x","y","z"].forEach((e,r)=>{this[e]=x.Vector3[0][t[r]]})),this}rotateByQuaternionToRef(t,e){return t.toRotationMatrix(x.Matrix[0]),c.TransformCoordinatesToRef(this,x.Matrix[0],e),e}rotateByQuaternionAroundPointToRef(t,e,r){return this.subtractToRef(e,x.Vector3[0]),x.Vector3[0].rotateByQuaternionToRef(t,x.Vector3[0]),e.addToRef(x.Vector3[0],r),r}cross(t){let e=new this.constructor;return c.CrossToRef(this,t,e)}normalizeFromLength(t){return 0===t||1===t?this:this.scaleInPlace(1/t)}normalizeToNew(){let t=new this.constructor(0,0,0);return this.normalizeToRef(t),t}normalizeToRef(t){let e=this.length();return 0===e||1===e?t.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/e,t)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(t){return this.copyFromFloats(t._x,t._y,t._z)}copyFromFloats(t,e,r){return this._x=t,this._y=e,this._z=r,this._isDirty=!0,this}set(t,e,r){return this.copyFromFloats(t,e,r)}setAll(t){return this._x=this._y=this._z=t,this._isDirty=!0,this}static GetClipFactor(t,e,r,i){let s=c.Dot(t,r)-i,o=c.Dot(e,r)-i;return s/(s-o)}static GetAngleBetweenVectors(t,e,r){let s=t.normalizeToRef(x.Vector3[1]),o=e.normalizeToRef(x.Vector3[2]),n=c.Dot(s,o);n=i.R.Clamp(n,-1,1);let a=Math.acos(n),h=x.Vector3[3];return(c.CrossToRef(s,o,h),c.Dot(h,r)>0)?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(t,e,r){x.Vector3[0].copyFrom(t);let s=x.Vector3[0];x.Vector3[1].copyFrom(e);let o=x.Vector3[1];x.Vector3[2].copyFrom(r);let n=x.Vector3[2],a=x.Vector3[3],h=x.Vector3[4];s.normalize(),o.normalize(),n.normalize(),c.CrossToRef(n,s,a),c.CrossToRef(a,n,h);let _=Math.atan2(c.Dot(o,a),c.Dot(o,h));return i.R.NormalizeRadians(_)}static PitchYawRollToMoveBetweenPointsToRef(t,e,r){let i=R.Vector3[0];return e.subtractToRef(t,i),r._y=Math.atan2(i.x,i.z)||0,r._x=Math.atan2(Math.sqrt(i.x**2+i.z**2),i.y)||0,r._z=0,r._isDirty=!0,r}static PitchYawRollToMoveBetweenPoints(t,e){let r=c.Zero();return c.PitchYawRollToMoveBetweenPointsToRef(t,e,r)}static SlerpToRef(t,e,r,o){let n,a;r=i.R.Clamp(r,0,1);let h=x.Vector3[0],_=x.Vector3[1];h.copyFrom(t);let l=h.length();h.normalizeFromLength(l),_.copyFrom(e);let y=_.length();_.normalizeFromLength(y);let u=c.Dot(h,_);if(u<1-s.kn){let t=Math.acos(u),e=1/Math.sin(t);n=Math.sin((1-r)*t)*e,a=Math.sin(r*t)*e}else n=1-r,a=r;return h.scaleInPlace(n),_.scaleInPlace(a),o.copyFrom(h).addInPlace(_),o.scaleInPlace(i.R.Lerp(l,y,r)),o}static SmoothToRef(t,e,r,i,s){return c.SlerpToRef(t,e,0===i?1:r/i,s),s}static FromArray(t,e=0){return new c(t[e],t[e+1],t[e+2])}static FromFloatArray(t,e){return c.FromArray(t,e)}static FromArrayToRef(t,e,r){return r._x=t[e],r._y=t[e+1],r._z=t[e+2],r._isDirty=!0,r}static FromFloatArrayToRef(t,e,r){return c.FromArrayToRef(t,e,r)}static FromFloatsToRef(t,e,r,i){return i.copyFromFloats(t,e,r),i}static Zero(){return new c(0,0,0)}static One(){return new c(1,1,1)}static Up(){return new c(0,1,0)}static get UpReadOnly(){return c._UpReadOnly}static get DownReadOnly(){return c._DownReadOnly}static get RightReadOnly(){return c._RightReadOnly}static get LeftReadOnly(){return c._LeftReadOnly}static get LeftHandedForwardReadOnly(){return c._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return c._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return c._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return c._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return c._ZeroReadOnly}static get OneReadOnly(){return c._OneReadOnly}static Down(){return new c(0,-1,0)}static Forward(t=!1){return new c(0,0,t?-1:1)}static Backward(t=!1){return new c(0,0,t?1:-1)}static Right(){return new c(1,0,0)}static Left(){return new c(-1,0,0)}static Random(t=0,e=1){return new c(i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static TransformCoordinates(t,e){let r=c.Zero();return c.TransformCoordinatesToRef(t,e,r),r}static TransformCoordinatesToRef(t,e,r){return c.TransformCoordinatesFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformCoordinatesFromFloatsToRef(t,e,r,i,s){let o=i.m,n=t*o[0]+e*o[4]+r*o[8]+o[12],a=t*o[1]+e*o[5]+r*o[9]+o[13],h=t*o[2]+e*o[6]+r*o[10]+o[14],_=1/(t*o[3]+e*o[7]+r*o[11]+o[15]);return s._x=n*_,s._y=a*_,s._z=h*_,s._isDirty=!0,s}static TransformNormal(t,e){let r=c.Zero();return c.TransformNormalToRef(t,e,r),r}static TransformNormalToRef(t,e,r){return this.TransformNormalFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformNormalFromFloatsToRef(t,e,r,i,s){let o=i.m;return s._x=t*o[0]+e*o[4]+r*o[8],s._y=t*o[1]+e*o[5]+r*o[9],s._z=t*o[2]+e*o[6]+r*o[10],s._isDirty=!0,s}static CatmullRom(t,e,r,i,s){let o=s*s,n=s*o,a=.5*(2*e._x+(-t._x+r._x)*s+(2*t._x-5*e._x+4*r._x-i._x)*o+(-t._x+3*e._x-3*r._x+i._x)*n),h=.5*(2*e._y+(-t._y+r._y)*s+(2*t._y-5*e._y+4*r._y-i._y)*o+(-t._y+3*e._y-3*r._y+i._y)*n),_=.5*(2*e._z+(-t._z+r._z)*s+(2*t._z-5*e._z+4*r._z-i._z)*o+(-t._z+3*e._z-3*r._z+i._z)*n);return new t.constructor(a,h,_)}static Clamp(t,e,r){let i=new t.constructor;return c.ClampToRef(t,e,r,i),i}static ClampToRef(t,e,r,i){let s=t._x;s=(s=s>r._x?r._x:s)<e._x?e._x:s;let o=t._y;o=(o=o>r._y?r._y:o)<e._y?e._y:o;let n=t._z;return n=(n=n>r._z?r._z:n)<e._z?e._z:n,i.copyFromFloats(s,o,n),i}static CheckExtends(t,e,r){e.minimizeInPlace(t),r.maximizeInPlace(t)}static Hermite(t,e,r,i,s){let o=s*s,n=s*o,a=2*n-3*o+1,h=-2*n+3*o,_=n-2*o+s,l=n-o,c=t._x*a+r._x*h+e._x*_+i._x*l,y=t._y*a+r._y*h+e._y*_+i._y*l,u=t._z*a+r._z*h+e._z*_+i._z*l;return new t.constructor(c,y,u)}static Hermite1stDerivative(t,e,r,i,s){let o=new t.constructor;return this.Hermite1stDerivativeToRef(t,e,r,i,s,o),o}static Hermite1stDerivativeToRef(t,e,r,i,s,o){let n=s*s;return o._x=(n-s)*6*t._x+(3*n-4*s+1)*e._x+(-n+s)*6*r._x+(3*n-2*s)*i._x,o._y=(n-s)*6*t._y+(3*n-4*s+1)*e._y+(-n+s)*6*r._y+(3*n-2*s)*i._y,o._z=(n-s)*6*t._z+(3*n-4*s+1)*e._z+(-n+s)*6*r._z+(3*n-2*s)*i._z,o._isDirty=!0,o}static Lerp(t,e,r){let i=new t.constructor(0,0,0);return c.LerpToRef(t,e,r,i),i}static LerpToRef(t,e,r,i){return i._x=t._x+(e._x-t._x)*r,i._y=t._y+(e._y-t._y)*r,i._z=t._z+(e._z-t._z)*r,i._isDirty=!0,i}static Dot(t,e){return t._x*e._x+t._y*e._y+t._z*e._z}static Cross(t,e){let r=new t.constructor;return c.CrossToRef(t,e,r),r}static CrossToRef(t,e,r){let i=t._y*e._z-t._z*e._y,s=t._z*e._x-t._x*e._z,o=t._x*e._y-t._y*e._x;return r.copyFromFloats(i,s,o),r}static Normalize(t){let e=c.Zero();return c.NormalizeToRef(t,e),e}static NormalizeToRef(t,e){return t.normalizeToRef(e),e}static Project(t,e,r,i){let s=new t.constructor;return c.ProjectToRef(t,e,r,i,s),s}static ProjectToRef(t,e,r,i,s){let o=i.width,n=i.height,a=i.x,h=i.y,_=x.Matrix[1];m.FromValuesToRef(o/2,0,0,0,0,-n/2,0,0,0,0,.5,0,a+o/2,n/2+h,.5,1,_);let l=x.Matrix[0];return e.multiplyToRef(r,l),l.multiplyToRef(_,l),c.TransformCoordinatesToRef(t,l,s),s}static Reflect(t,e){return this.ReflectToRef(t,e,new c)}static ReflectToRef(t,e,r){let i=R.Vector3[0];return i.copyFrom(e).scaleInPlace(2*c.Dot(t,e)),r.copyFrom(t).subtractInPlace(i)}static _UnprojectFromInvertedMatrixToRef(t,e,r){c.TransformCoordinatesToRef(t,e,r);let s=e.m,o=t._x*s[3]+t._y*s[7]+t._z*s[11]+s[15];return i.R.WithinEpsilon(o,1)&&r.scaleInPlace(1/o),r}static UnprojectFromTransform(t,e,r,i,s){return this.Unproject(t,e,r,i,s,m.IdentityReadOnly)}static Unproject(t,e,r,i,s,o){let n=new t.constructor;return c.UnprojectToRef(t,e,r,i,s,o,n),n}static UnprojectToRef(t,e,r,i,s,o,n){return c.UnprojectFloatsToRef(t._x,t._y,t._z,e,r,i,s,o,n),n}static UnprojectFloatsToRef(t,e,r,i,s,o,n,a,_){var l;let y=x.Matrix[0];o.multiplyToRef(n,y),y.multiplyToRef(a,y),y.invert();let u=x.Vector3[0];return u.x=t/i*2-1,u.y=-(e/s*2-1),(null===(l=h.l.LastCreatedEngine)||void 0===l?void 0:l.isNDCHalfZRange)?u.z=r:u.z=2*r-1,c._UnprojectFromInvertedMatrixToRef(u,y,_),_}static Minimize(t,e){let r=new t.constructor;return r.copyFrom(t),r.minimizeInPlace(e),r}static Maximize(t,e){let r=new t.constructor;return r.copyFrom(t),r.maximizeInPlace(e),r}static Distance(t,e){return Math.sqrt(c.DistanceSquared(t,e))}static DistanceSquared(t,e){let r=t._x-e._x,i=t._y-e._y,s=t._z-e._z;return r*r+i*i+s*s}static ProjectOnTriangleToRef(t,e,r,o,n){let a,h,_;let l=x.Vector3[0],y=x.Vector3[1],u=x.Vector3[2],m=x.Vector3[3],R=x.Vector3[4];r.subtractToRef(e,l),o.subtractToRef(e,y),o.subtractToRef(r,u);let f=l.length(),d=y.length(),z=u.length();if(f<s.kn||d<s.kn||z<s.kn)return n.copyFrom(e),c.Distance(t,e);t.subtractToRef(e,R),c.CrossToRef(l,y,m);let T=m.length();if(T<s.kn)return n.copyFrom(e),c.Distance(t,e);m.normalizeFromLength(T);let w=R.length();if(w<s.kn)return n.copyFrom(e),0;R.normalizeFromLength(w);let p=c.Dot(m,R),F=x.Vector3[5],I=x.Vector3[6];F.copyFrom(m).scaleInPlace(-w*p),I.copyFrom(t).addInPlace(F);let M=x.Vector3[4],g=x.Vector3[5],D=x.Vector3[7],P=x.Vector3[8];M.copyFrom(l).scaleInPlace(1/f),P.copyFrom(y).scaleInPlace(1/d),M.addInPlace(P).scaleInPlace(-1),g.copyFrom(l).scaleInPlace(-1/f),P.copyFrom(u).scaleInPlace(1/z),g.addInPlace(P).scaleInPlace(-1),D.copyFrom(u).scaleInPlace(-1/z),P.copyFrom(y).scaleInPlace(-1/d),D.addInPlace(P).scaleInPlace(-1);let A=x.Vector3[9];A.copyFrom(I).subtractInPlace(e),c.CrossToRef(M,A,P),a=c.Dot(P,m);let V=a;A.copyFrom(I).subtractInPlace(r),c.CrossToRef(g,A,P),a=c.Dot(P,m);let C=a;A.copyFrom(I).subtractInPlace(o),c.CrossToRef(D,A,P),a=c.Dot(P,m);let L=a,k=x.Vector3[10];V>0&&C<0?(k.copyFrom(l),h=e,_=r):C>0&&L<0?(k.copyFrom(u),h=r,_=o):(k.copyFrom(y).scaleInPlace(-1),h=o,_=e);let H=x.Vector3[9],O=x.Vector3[4];h.subtractToRef(I,P),_.subtractToRef(I,H),c.CrossToRef(P,H,O);let v=0>c.Dot(O,m);if(!v)return n.copyFrom(I),Math.abs(w*p);let S=x.Vector3[5];c.CrossToRef(k,O,S),S.normalize();let B=x.Vector3[9];B.copyFrom(h).subtractInPlace(I);let U=B.length();if(U<s.kn)return n.copyFrom(h),c.Distance(t,h);B.normalizeFromLength(U);let b=c.Dot(S,B),Z=x.Vector3[7];Z.copyFrom(I).addInPlace(S.scaleInPlace(U*b)),P.copyFrom(Z).subtractInPlace(h),w=k.length(),k.normalizeFromLength(w);let q=c.Dot(P,k)/Math.max(w,s.kn);return q=i.R.Clamp(q,0,1),Z.copyFrom(h).addInPlace(k.scaleInPlace(q*w)),n.copyFrom(Z),c.Distance(t,Z)}static Center(t,e){return c.CenterToRef(t,e,c.Zero())}static CenterToRef(t,e,r){return r.copyFromFloats((t._x+e._x)/2,(t._y+e._y)/2,(t._z+e._z)/2)}static RotationFromAxis(t,e,r){let i=new t.constructor;return c.RotationFromAxisToRef(t,e,r,i),i}static RotationFromAxisToRef(t,e,r,i){let s=x.Quaternion[0];return u.RotationQuaternionFromAxisToRef(t,e,r,s),s.toEulerAnglesToRef(i),i}}c._UpReadOnly=c.Up(),c._DownReadOnly=c.Down(),c._LeftHandedForwardReadOnly=c.Forward(!1),c._RightHandedForwardReadOnly=c.Forward(!0),c._LeftHandedBackwardReadOnly=c.Backward(!1),c._RightHandedBackwardReadOnly=c.Backward(!0),c._RightReadOnly=c.Right(),c._LeftReadOnly=c.Left(),c._ZeroReadOnly=c.Zero(),c._OneReadOnly=c.One();class y{constructor(t=0,e=0,r=0,i=0){this.x=t,this.y=e,this.z=r,this.w=i}toString(){return`{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`}getClassName(){return"Vector4"}getHashCode(){let t=_(this.x),e=_(this.y),r=_(this.z),i=_(this.w),s=t;return 397*(s=397*(s=397*s^e)^r)^i}asArray(){let t=[];return this.toArray(t,0),t}toArray(t,e){return void 0===e&&(e=0),t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,this}fromArray(t,e=0){return y.FromArrayToRef(t,e,this),this}addInPlace(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}add(t){return new this.constructor(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)}addToRef(t,e){return e.x=this.x+t.x,e.y=this.y+t.y,e.z=this.z+t.z,e.w=this.w+t.w,e}subtractInPlace(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subtract(t){return new this.constructor(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)}subtractToRef(t,e){return e.x=this.x-t.x,e.y=this.y-t.y,e.z=this.z-t.z,e.w=this.w-t.w,e}subtractFromFloats(t,e,r,i){return new this.constructor(this.x-t,this.y-e,this.z-r,this.w-i)}subtractFromFloatsToRef(t,e,r,i,s){return s.x=this.x-t,s.y=this.y-e,s.z=this.z-r,s.w=this.w-i,s}negate(){return new this.constructor(-this.x,-this.y,-this.z,-this.w)}negateInPlace(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this}negateToRef(t){return t.copyFromFloats(-1*this.x,-1*this.y,-1*this.z,-1*this.w)}scaleInPlace(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}scale(t){return new this.constructor(this.x*t,this.y*t,this.z*t,this.w*t)}scaleToRef(t,e){return e.x=this.x*t,e.y=this.y*t,e.z=this.z*t,e.w=this.w*t,e}scaleAndAddToRef(t,e){return e.x+=this.x*t,e.y+=this.y*t,e.z+=this.z*t,e.w+=this.w*t,e}equals(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this.x,t.x,e)&&i.R.WithinEpsilon(this.y,t.y,e)&&i.R.WithinEpsilon(this.z,t.z,e)&&i.R.WithinEpsilon(this.w,t.w,e)}equalsToFloats(t,e,r,i){return this.x===t&&this.y===e&&this.z===r&&this.w===i}multiplyInPlace(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiply(t){return new this.constructor(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)}multiplyToRef(t,e){return e.x=this.x*t.x,e.y=this.y*t.y,e.z=this.z*t.z,e.w=this.w*t.w,e}multiplyByFloats(t,e,r,i){return new this.constructor(this.x*t,this.y*e,this.z*r,this.w*i)}divide(t){return new this.constructor(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)}divideToRef(t,e){return e.x=this.x/t.x,e.y=this.y/t.y,e.z=this.z/t.z,e.w=this.w/t.w,e}divideInPlace(t){return this.divideToRef(t,this)}minimizeInPlace(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this}maximizeInPlace(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){let t=this.length();return 0===t?this:this.scaleInPlace(1/t)}toVector3(){return new c(this.x,this.y,this.z)}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copyFrom(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}copyFromFloats(t,e,r,i){return this.x=t,this.y=e,this.z=r,this.w=i,this}set(t,e,r,i){return this.copyFromFloats(t,e,r,i)}setAll(t){return this.x=this.y=this.z=this.w=t,this}static FromArray(t,e){return e||(e=0),new y(t[e],t[e+1],t[e+2],t[e+3])}static FromArrayToRef(t,e,r){return r.x=t[e],r.y=t[e+1],r.z=t[e+2],r.w=t[e+3],r}static FromFloatArrayToRef(t,e,r){return y.FromArrayToRef(t,e,r),r}static FromFloatsToRef(t,e,r,i,s){return s.x=t,s.y=e,s.z=r,s.w=i,s}static Zero(){return new y(0,0,0,0)}static One(){return new y(1,1,1,1)}static Random(t=0,e=1){return new y(i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static get ZeroReadOnly(){return y._ZeroReadOnly}static Normalize(t){let e=y.Zero();return y.NormalizeToRef(t,e),e}static NormalizeToRef(t,e){return e.copyFrom(t),e.normalize(),e}static Minimize(t,e){let r=new t.constructor;return r.copyFrom(t),r.minimizeInPlace(e),r}static Maximize(t,e){let r=new t.constructor;return r.copyFrom(t),r.maximizeInPlace(e),r}static Distance(t,e){return Math.sqrt(y.DistanceSquared(t,e))}static DistanceSquared(t,e){let r=t.x-e.x,i=t.y-e.y,s=t.z-e.z,o=t.w-e.w;return r*r+i*i+s*s+o*o}static Center(t,e){return y.CenterToRef(t,e,y.Zero())}static CenterToRef(t,e,r){return r.copyFromFloats((t.x+e.x)/2,(t.y+e.y)/2,(t.z+e.z)/2,(t.w+e.w)/2)}static TransformCoordinates(t,e){let r=y.Zero();return y.TransformCoordinatesToRef(t,e,r),r}static TransformCoordinatesToRef(t,e,r){return y.TransformCoordinatesFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformCoordinatesFromFloatsToRef(t,e,r,i,s){let o=i.m,n=t*o[0]+e*o[4]+r*o[8]+o[12],a=t*o[1]+e*o[5]+r*o[9]+o[13],h=t*o[2]+e*o[6]+r*o[10]+o[14],_=t*o[3]+e*o[7]+r*o[11]+o[15];return s.x=n,s.y=a,s.z=h,s.w=_,s}static TransformNormal(t,e){let r=new t.constructor;return y.TransformNormalToRef(t,e,r),r}static TransformNormalToRef(t,e,r){let i=e.m,s=t.x*i[0]+t.y*i[4]+t.z*i[8],o=t.x*i[1]+t.y*i[5]+t.z*i[9],n=t.x*i[2]+t.y*i[6]+t.z*i[10];return r.x=s,r.y=o,r.z=n,r.w=t.w,r}static TransformNormalFromFloatsToRef(t,e,r,i,s,o){let n=s.m;return o.x=t*n[0]+e*n[4]+r*n[8],o.y=t*n[1]+e*n[5]+r*n[9],o.z=t*n[2]+e*n[6]+r*n[10],o.w=i,o}static FromVector3(t,e=0){return new y(t._x,t._y,t._z,e)}}y._ZeroReadOnly=y.Zero();class u{get x(){return this._x}set x(t){this._x=t,this._isDirty=!0}get y(){return this._y}set y(t){this._y=t,this._isDirty=!0}get z(){return this._z}set z(t){this._z=t,this._isDirty=!0}get w(){return this._w}set w(t){this._w=t,this._isDirty=!0}constructor(t=0,e=0,r=0,i=1){this._isDirty=!0,this._x=t,this._y=e,this._z=r,this._w=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let t=_(this._x),e=_(this._y),r=_(this._z),i=_(this._w),s=t;return 397*(s=397*(s=397*s^e)^r)^i}asArray(){return[this._x,this._y,this._z,this._w]}toArray(t,e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,this}equals(t){return t&&this._x===t._x&&this._y===t._y&&this._z===t._z&&this._w===t._w}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this._x,t._x,e)&&i.R.WithinEpsilon(this._y,t._y,e)&&i.R.WithinEpsilon(this._z,t._z,e)&&i.R.WithinEpsilon(this._w,t._w,e)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._w=t._w,this._isDirty=!0,this}copyFromFloats(t,e,r,i){return this._x=t,this._y=e,this._z=r,this._w=i,this._isDirty=!0,this}set(t,e,r,i){return this.copyFromFloats(t,e,r,i)}add(t){return new this.constructor(this._x+t._x,this._y+t._y,this._z+t._z,this._w+t._w)}addInPlace(t){return this._x+=t._x,this._y+=t._y,this._z+=t._z,this._w+=t._w,this._isDirty=!0,this}subtract(t){return new this.constructor(this._x-t._x,this._y-t._y,this._z-t._z,this._w-t._w)}subtractInPlace(t){return this._x-=t._x,this._y-=t._y,this._z-=t._z,this._w-=t._w,this._isDirty=!0,this}scale(t){return new this.constructor(this._x*t,this._y*t,this._z*t,this._w*t)}scaleToRef(t,e){return e._x=this._x*t,e._y=this._y*t,e._z=this._z*t,e._w=this._w*t,e._isDirty=!0,e}scaleInPlace(t){return this._x*=t,this._y*=t,this._z*=t,this._w*=t,this._isDirty=!0,this}scaleAndAddToRef(t,e){return e._x+=this._x*t,e._y+=this._y*t,e._z+=this._z*t,e._w+=this._w*t,e._isDirty=!0,e}multiply(t){let e=new this.constructor(0,0,0,1);return this.multiplyToRef(t,e),e}multiplyToRef(t,e){let r=this._x*t._w+this._y*t._z-this._z*t._y+this._w*t._x,i=-this._x*t._z+this._y*t._w+this._z*t._x+this._w*t._y,s=this._x*t._y-this._y*t._x+this._z*t._w+this._w*t._z,o=-this._x*t._x-this._y*t._y-this._z*t._z+this._w*t._w;return e.copyFromFloats(r,i,s,o),e}multiplyInPlace(t){return this.multiplyToRef(t,this),this}conjugateToRef(t){return t.copyFromFloats(-this._x,-this._y,-this._z,this._w),t}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){let t=this.conjugate(),e=this.lengthSquared();return 0==e||1==e||t.scaleInPlace(1/e),t}invertInPlace(){this.conjugateInPlace();let t=this.lengthSquared();return 0==t||1==t||this.scaleInPlace(1/t),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){let t=this.length();return 0===t||this.scaleInPlace(1/t),this}normalizeToNew(){let t=this.length();return 0===t?this.clone():this.scale(1/t)}toEulerAngles(){let t=c.Zero();return this.toEulerAnglesToRef(t),t}toEulerAnglesToRef(t){let e=this._z,r=this._x,i=this._y,s=this._w,o=i*e-r*s;if(o<-.4999999)t._y=2*Math.atan2(i,s),t._x=Math.PI/2,t._z=0,t._isDirty=!0;else if(o>.4999999)t._y=2*Math.atan2(i,s),t._x=-Math.PI/2,t._z=0,t._isDirty=!0;else{let n=s*s,a=e*e,h=r*r,_=i*i;t._z=Math.atan2(2*(r*i+e*s),-a-h+_+n),t._x=Math.asin(-2*o),t._y=Math.atan2(2*(e*r+i*s),a-h-_+n),t._isDirty=!0}return t}toRotationMatrix(t){return m.FromQuaternionToRef(this,t),t}fromRotationMatrix(t){return u.FromRotationMatrixToRef(t,this),this}static FromRotationMatrix(t){let e=new u;return u.FromRotationMatrixToRef(t,e),e}static FromRotationMatrixToRef(t,e){let r;let i=t.m,s=i[0],o=i[4],n=i[8],a=i[1],h=i[5],_=i[9],l=i[2],c=i[6],y=i[10],u=s+h+y;return u>0?(r=.5/Math.sqrt(u+1),e._w=.25/r,e._x=(c-_)*r,e._y=(n-l)*r,e._z=(a-o)*r,e._isDirty=!0):s>h&&s>y?(r=2*Math.sqrt(1+s-h-y),e._w=(c-_)/r,e._x=.25*r,e._y=(o+a)/r,e._z=(n+l)/r,e._isDirty=!0):h>y?(r=2*Math.sqrt(1+h-s-y),e._w=(n-l)/r,e._x=(o+a)/r,e._y=.25*r,e._z=(_+c)/r,e._isDirty=!0):(r=2*Math.sqrt(1+y-s-h),e._w=(a-o)/r,e._x=(n+l)/r,e._y=(_+c)/r,e._z=.25*r,e._isDirty=!0),e}static Dot(t,e){return t._x*e._x+t._y*e._y+t._z*e._z+t._w*e._w}static AreClose(t,e,r=.1){let i=u.Dot(t,e);return 1-i*i<=r}static SmoothToRef(t,e,r,s,o){let n=0===s?1:r/s;return n=i.R.Clamp(n,0,1),u.SlerpToRef(t,e,n,o),o}static Zero(){return new u(0,0,0,0)}static Inverse(t){return new t.constructor(-t._x,-t._y,-t._z,t._w)}static InverseToRef(t,e){return e.set(-t._x,-t._y,-t._z,t._w),e}static Identity(){return new u(0,0,0,1)}static IsIdentity(t){return t&&0===t._x&&0===t._y&&0===t._z&&1===t._w}static RotationAxis(t,e){return u.RotationAxisToRef(t,e,new u)}static RotationAxisToRef(t,e,r){let i=Math.sin(e/2);return t.normalize(),r._w=Math.cos(e/2),r._x=t._x*i,r._y=t._y*i,r._z=t._z*i,r._isDirty=!0,r}static FromArray(t,e){return e||(e=0),new u(t[e],t[e+1],t[e+2],t[e+3])}static FromArrayToRef(t,e,r){return r._x=t[e],r._y=t[e+1],r._z=t[e+2],r._w=t[e+3],r._isDirty=!0,r}static FromEulerAngles(t,e,r){let i=new u;return u.RotationYawPitchRollToRef(e,t,r,i),i}static FromEulerAnglesToRef(t,e,r,i){return u.RotationYawPitchRollToRef(e,t,r,i),i}static FromEulerVector(t){let e=new u;return u.RotationYawPitchRollToRef(t._y,t._x,t._z,e),e}static FromEulerVectorToRef(t,e){return u.RotationYawPitchRollToRef(t._y,t._x,t._z,e),e}static FromUnitVectorsToRef(t,e,r,i=s.kn){let o=c.Dot(t,e)+1;return o<i?Math.abs(t.x)>Math.abs(t.z)?r.set(-t.y,t.x,0,0):r.set(0,-t.z,t.y,0):(c.CrossToRef(t,e,R.Vector3[0]),r.set(R.Vector3[0].x,R.Vector3[0].y,R.Vector3[0].z,o)),r.normalize()}static RotationYawPitchRoll(t,e,r){let i=new u;return u.RotationYawPitchRollToRef(t,e,r,i),i}static RotationYawPitchRollToRef(t,e,r,i){let s=.5*r,o=.5*e,n=.5*t,a=Math.sin(s),h=Math.cos(s),_=Math.sin(o),l=Math.cos(o),c=Math.sin(n),y=Math.cos(n);return i._x=y*_*h+c*l*a,i._y=c*l*h-y*_*a,i._z=y*l*a-c*_*h,i._w=y*l*h+c*_*a,i._isDirty=!0,i}static RotationAlphaBetaGamma(t,e,r){let i=new u;return u.RotationAlphaBetaGammaToRef(t,e,r,i),i}static RotationAlphaBetaGammaToRef(t,e,r,i){let s=(r+t)*.5,o=(r-t)*.5,n=.5*e;return i._x=Math.cos(o)*Math.sin(n),i._y=Math.sin(o)*Math.sin(n),i._z=Math.sin(s)*Math.cos(n),i._w=Math.cos(s)*Math.cos(n),i._isDirty=!0,i}static RotationQuaternionFromAxis(t,e,r){let i=new u(0,0,0,0);return u.RotationQuaternionFromAxisToRef(t,e,r,i),i}static RotationQuaternionFromAxisToRef(t,e,r,i){let s=x.Matrix[0];return m.FromXYZAxesToRef(t.normalize(),e.normalize(),r.normalize(),s),u.FromRotationMatrixToRef(s,i),i}static FromLookDirectionLH(t,e){let r=new u;return u.FromLookDirectionLHToRef(t,e,r),r}static FromLookDirectionLHToRef(t,e,r){let i=x.Matrix[0];return m.LookDirectionLHToRef(t,e,i),u.FromRotationMatrixToRef(i,r),r}static FromLookDirectionRH(t,e){let r=new u;return u.FromLookDirectionRHToRef(t,e,r),r}static FromLookDirectionRHToRef(t,e,r){let i=x.Matrix[0];return m.LookDirectionRHToRef(t,e,i),u.FromRotationMatrixToRef(i,r)}static Slerp(t,e,r){let i=u.Identity();return u.SlerpToRef(t,e,r,i),i}static SlerpToRef(t,e,r,i){let s,o;let n=t._x*e._x+t._y*e._y+t._z*e._z+t._w*e._w,a=!1;if(n<0&&(a=!0,n=-n),n>.999999)o=1-r,s=a?-r:r;else{let t=Math.acos(n),e=1/Math.sin(t);o=Math.sin((1-r)*t)*e,s=a?-Math.sin(r*t)*e:Math.sin(r*t)*e}return i._x=o*t._x+s*e._x,i._y=o*t._y+s*e._y,i._z=o*t._z+s*e._z,i._w=o*t._w+s*e._w,i._isDirty=!0,i}static Hermite(t,e,r,i,s){let o=s*s,n=s*o,a=2*n-3*o+1,h=-2*n+3*o,_=n-2*o+s,l=n-o,c=t._x*a+r._x*h+e._x*_+i._x*l,y=t._y*a+r._y*h+e._y*_+i._y*l,u=t._z*a+r._z*h+e._z*_+i._z*l,m=t._w*a+r._w*h+e._w*_+i._w*l;return new t.constructor(c,y,u,m)}static Hermite1stDerivative(t,e,r,i,s){let o=new t.constructor;return this.Hermite1stDerivativeToRef(t,e,r,i,s,o),o}static Hermite1stDerivativeToRef(t,e,r,i,s,o){let n=s*s;return o._x=(n-s)*6*t._x+(3*n-4*s+1)*e._x+(-n+s)*6*r._x+(3*n-2*s)*i._x,o._y=(n-s)*6*t._y+(3*n-4*s+1)*e._y+(-n+s)*6*r._y+(3*n-2*s)*i._y,o._z=(n-s)*6*t._z+(3*n-4*s+1)*e._z+(-n+s)*6*r._z+(3*n-2*s)*i._z,o._w=(n-s)*6*t._w+(3*n-4*s+1)*e._w+(-n+s)*6*r._w+(3*n-2*s)*i._w,o._isDirty=!0,o}}class m{static get Use64Bits(){return a.Z.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=m._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(t,e=!1,r=!1,i=!0){this._isIdentity=t,this._isIdentity3x2=t||r,this._isIdentityDirty=!this._isIdentity&&e,this._isIdentity3x2Dirty=!this._isIdentity3x2&&i}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,a.Z.MatrixTrackPrecisionChange&&a.Z.MatrixTrackedMatrices.push(this),this._m=new a.Z.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;let t=this._m;this._isIdentity=1===t[0]&&0===t[1]&&0===t[2]&&0===t[3]&&0===t[4]&&1===t[5]&&0===t[6]&&0===t[7]&&0===t[8]&&0===t[9]&&1===t[10]&&0===t[11]&&0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]?this._isIdentity3x2=!1:0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;let t=this._m,e=t[0],r=t[1],i=t[2],s=t[3],o=t[4],n=t[5],a=t[6],h=t[7],_=t[8],l=t[9],c=t[10],y=t[11],u=t[12],m=t[13],x=t[14],R=t[15],f=c*R-x*y,d=l*R-m*y,z=l*x-m*c,T=_*R-u*y,w=_*x-c*u,p=_*m-u*l;return e*+(n*f-a*d+h*z)+-(r*(o*f-a*T+h*w))+i*+(o*d-n*T+h*p)+-(s*(o*z-n*w+a*p))}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return m.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(t){let e=new this.constructor;return this.addToRef(t,e),e}addToRef(t,e){let r=this._m,i=e._m,s=t.m;for(let t=0;t<16;t++)i[t]=r[t]+s[t];return e.markAsUpdated(),e}addToSelf(t){let e=this._m,r=t.m;for(let t=0;t<16;t++)e[t]+=r[t];return this.markAsUpdated(),this}invertToRef(t){if(!0===this._isIdentity)return m.IdentityToRef(t),t;let e=this._m,r=e[0],i=e[1],s=e[2],o=e[3],n=e[4],a=e[5],h=e[6],_=e[7],l=e[8],c=e[9],y=e[10],u=e[11],x=e[12],R=e[13],f=e[14],d=e[15],z=y*d-f*u,T=c*d-R*u,w=c*f-R*y,p=l*d-x*u,F=l*f-y*x,I=l*R-x*c,M=+(a*z-h*T+_*w),g=-(n*z-h*p+_*F),D=+(n*T-a*p+_*I),P=-(n*w-a*F+h*I),A=r*M+i*g+s*D+o*P;if(0===A)return t.copyFrom(this),t;let V=1/A,C=h*d-f*_,L=a*d-R*_,k=a*f-R*h,H=n*d-x*_,O=n*f-x*h,v=n*R-x*a,S=h*u-y*_,B=a*u-c*_,U=a*y-c*h,b=n*u-l*_,Z=n*y-l*h,q=n*c-l*a;return m.FromValuesToRef(M*V,-(i*z-s*T+o*w)*V,+(i*C-s*L+o*k)*V,-(i*S-s*B+o*U)*V,g*V,+(r*z-s*p+o*F)*V,-(r*C-s*H+o*O)*V,+(r*S-s*b+o*Z)*V,D*V,-(r*T-i*p+o*I)*V,+(r*L-i*H+o*v)*V,-(r*B-i*b+o*q)*V,P*V,+(r*w-i*F+s*I)*V,-(r*k-i*O+s*v)*V,+(r*U-i*Z+s*q)*V,t),t}addAtIndex(t,e){return this._m[t]+=e,this.markAsUpdated(),this}multiplyAtIndex(t,e){return this._m[t]*=e,this.markAsUpdated(),this}setTranslationFromFloats(t,e,r){return this._m[12]=t,this._m[13]=e,this._m[14]=r,this.markAsUpdated(),this}addTranslationFromFloats(t,e,r){return this._m[12]+=t,this._m[13]+=e,this._m[14]+=r,this.markAsUpdated(),this}setTranslation(t){return this.setTranslationFromFloats(t._x,t._y,t._z)}getTranslation(){return new c(this._m[12],this._m[13],this._m[14])}getTranslationToRef(t){return t.x=this._m[12],t.y=this._m[13],t.z=this._m[14],t}removeRotationAndScaling(){let t=this.m;return m.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t[12],t[13],t[14],t[15],this),this._updateIdentityStatus(0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]),this}multiply(t){let e=new this.constructor;return this.multiplyToRef(t,e),e}copyFrom(t){return t.copyToArray(this._m),this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(t,e=0){let r=this._m;return t[e]=r[0],t[e+1]=r[1],t[e+2]=r[2],t[e+3]=r[3],t[e+4]=r[4],t[e+5]=r[5],t[e+6]=r[6],t[e+7]=r[7],t[e+8]=r[8],t[e+9]=r[9],t[e+10]=r[10],t[e+11]=r[11],t[e+12]=r[12],t[e+13]=r[13],t[e+14]=r[14],t[e+15]=r[15],this}multiplyToRef(t,e){return this._isIdentity?(e.copyFrom(t),e):t._isIdentity?(e.copyFrom(this),e):(this.multiplyToArray(t,e._m,0),e.markAsUpdated(),e)}multiplyToArray(t,e,r){let i=this._m,s=t.m,o=i[0],n=i[1],a=i[2],h=i[3],_=i[4],l=i[5],c=i[6],y=i[7],u=i[8],m=i[9],x=i[10],R=i[11],f=i[12],d=i[13],z=i[14],T=i[15],w=s[0],p=s[1],F=s[2],I=s[3],M=s[4],g=s[5],D=s[6],P=s[7],A=s[8],V=s[9],C=s[10],L=s[11],k=s[12],H=s[13],O=s[14],v=s[15];return e[r]=o*w+n*M+a*A+h*k,e[r+1]=o*p+n*g+a*V+h*H,e[r+2]=o*F+n*D+a*C+h*O,e[r+3]=o*I+n*P+a*L+h*v,e[r+4]=_*w+l*M+c*A+y*k,e[r+5]=_*p+l*g+c*V+y*H,e[r+6]=_*F+l*D+c*C+y*O,e[r+7]=_*I+l*P+c*L+y*v,e[r+8]=u*w+m*M+x*A+R*k,e[r+9]=u*p+m*g+x*V+R*H,e[r+10]=u*F+m*D+x*C+R*O,e[r+11]=u*I+m*P+x*L+R*v,e[r+12]=f*w+d*M+z*A+T*k,e[r+13]=f*p+d*g+z*V+T*H,e[r+14]=f*F+d*D+z*C+T*O,e[r+15]=f*I+d*P+z*L+T*v,this}equals(t){if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;let e=this.m,r=t.m;return e[0]===r[0]&&e[1]===r[1]&&e[2]===r[2]&&e[3]===r[3]&&e[4]===r[4]&&e[5]===r[5]&&e[6]===r[6]&&e[7]===r[7]&&e[8]===r[8]&&e[9]===r[9]&&e[10]===r[10]&&e[11]===r[11]&&e[12]===r[12]&&e[13]===r[13]&&e[14]===r[14]&&e[15]===r[15]}clone(){let t=new this.constructor;return t.copyFrom(this),t}getClassName(){return"Matrix"}getHashCode(){let t=_(this._m[0]);for(let e=1;e<16;e++)t=397*t^_(this._m[e]);return t}decomposeToTransformNode(t){return t.rotationQuaternion=t.rotationQuaternion||new u,this.decompose(t.scaling,t.rotationQuaternion,t.position)}decompose(t,e,r,i){if(this._isIdentity)return r&&r.setAll(0),t&&t.setAll(1),e&&e.copyFromFloats(0,0,0,1),!0;let s=this._m;if(r&&r.copyFromFloats(s[12],s[13],s[14]),(t=t||x.Vector3[0]).x=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]),t.y=Math.sqrt(s[4]*s[4]+s[5]*s[5]+s[6]*s[6]),t.z=Math.sqrt(s[8]*s[8]+s[9]*s[9]+s[10]*s[10]),i){let e=i.scaling.x<0?-1:1,r=i.scaling.y<0?-1:1,s=i.scaling.z<0?-1:1;t.x*=e,t.y*=r,t.z*=s}else 0>=this.determinant()&&(t.y*=-1);if(0===t._x||0===t._y||0===t._z)return e&&e.copyFromFloats(0,0,0,1),!1;if(e){let r=1/t._x,i=1/t._y,o=1/t._z;m.FromValuesToRef(s[0]*r,s[1]*r,s[2]*r,0,s[4]*i,s[5]*i,s[6]*i,0,s[8]*o,s[9]*o,s[10]*o,0,0,0,0,1,x.Matrix[0]),u.FromRotationMatrixToRef(x.Matrix[0],e)}return!0}getRow(t){if(t<0||t>3)return null;let e=4*t;return new y(this._m[e+0],this._m[e+1],this._m[e+2],this._m[e+3])}getRowToRef(t,e){if(t>=0&&t<3){let r=4*t;e.x=this._m[r+0],e.y=this._m[r+1],e.z=this._m[r+2],e.w=this._m[r+3]}return e}setRow(t,e){return this.setRowFromFloats(t,e.x,e.y,e.z,e.w)}transpose(){let t=new this.constructor;return m.TransposeToRef(this,t),t}transposeToRef(t){return m.TransposeToRef(this,t),t}setRowFromFloats(t,e,r,i,s){if(t<0||t>3)return this;let o=4*t;return this._m[o+0]=e,this._m[o+1]=r,this._m[o+2]=i,this._m[o+3]=s,this.markAsUpdated(),this}scale(t){let e=new this.constructor;return this.scaleToRef(t,e),e}scaleToRef(t,e){for(let r=0;r<16;r++)e._m[r]=this._m[r]*t;return e.markAsUpdated(),e}scaleAndAddToRef(t,e){for(let r=0;r<16;r++)e._m[r]+=this._m[r]*t;return e.markAsUpdated(),e}toNormalMatrix(t){let e=x.Matrix[0];this.invertToRef(e),e.transposeToRef(t);let r=t._m;return m.FromValuesToRef(r[0],r[1],r[2],0,r[4],r[5],r[6],0,r[8],r[9],r[10],0,0,0,0,1,t),t}getRotationMatrix(){let t=new this.constructor;return this.getRotationMatrixToRef(t),t}getRotationMatrixToRef(t){let e=x.Vector3[0];if(!this.decompose(e))return m.IdentityToRef(t),t;let r=this._m,i=1/e._x,s=1/e._y,o=1/e._z;return m.FromValuesToRef(r[0]*i,r[1]*i,r[2]*i,0,r[4]*s,r[5]*s,r[6]*s,0,r[8]*o,r[9]*o,r[10]*o,0,0,0,0,1,t),t}toggleModelMatrixHandInPlace(){let t=this._m;return t[2]*=-1,t[6]*=-1,t[8]*=-1,t[9]*=-1,t[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){let t=this._m;return t[8]*=-1,t[9]*=-1,t[10]*=-1,t[11]*=-1,this.markAsUpdated(),this}static FromArray(t,e=0){let r=new m;return m.FromArrayToRef(t,e,r),r}static FromArrayToRef(t,e,r){for(let i=0;i<16;i++)r._m[i]=t[i+e];return r.markAsUpdated(),r}static FromFloat32ArrayToRefScaled(t,e,r,i){for(let s=0;s<16;s++)i._m[s]=t[s+e]*r;return i.markAsUpdated(),i}static get IdentityReadOnly(){return m._IdentityReadOnly}static FromValuesToRef(t,e,r,i,s,o,n,a,h,_,l,c,y,u,m,x,R){let f=R._m;f[0]=t,f[1]=e,f[2]=r,f[3]=i,f[4]=s,f[5]=o,f[6]=n,f[7]=a,f[8]=h,f[9]=_,f[10]=l,f[11]=c,f[12]=y,f[13]=u,f[14]=m,f[15]=x,R.markAsUpdated()}static FromValues(t,e,r,i,s,o,n,a,h,_,l,c,y,u,x,R){let f=new m,d=f._m;return d[0]=t,d[1]=e,d[2]=r,d[3]=i,d[4]=s,d[5]=o,d[6]=n,d[7]=a,d[8]=h,d[9]=_,d[10]=l,d[11]=c,d[12]=y,d[13]=u,d[14]=x,d[15]=R,f.markAsUpdated(),f}static Compose(t,e,r){let i=new m;return m.ComposeToRef(t,e,r,i),i}static ComposeToRef(t,e,r,i){let s=i._m,o=e._x,n=e._y,a=e._z,h=e._w,_=o+o,l=n+n,c=a+a,y=o*_,u=o*l,m=o*c,x=n*l,R=n*c,f=a*c,d=h*_,z=h*l,T=h*c,w=t._x,p=t._y,F=t._z;return s[0]=(1-(x+f))*w,s[1]=(u+T)*w,s[2]=(m-z)*w,s[3]=0,s[4]=(u-T)*p,s[5]=(1-(y+f))*p,s[6]=(R+d)*p,s[7]=0,s[8]=(m+z)*F,s[9]=(R-d)*F,s[10]=(1-(y+x))*F,s[11]=0,s[12]=r._x,s[13]=r._y,s[14]=r._z,s[15]=1,i.markAsUpdated(),i}static Identity(){let t=m.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return t._updateIdentityStatus(!0),t}static IdentityToRef(t){return m.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(!0),t}static Zero(){let t=m.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return t._updateIdentityStatus(!1),t}static RotationX(t){let e=new m;return m.RotationXToRef(t,e),e}static Invert(t){let e=new t.constructor;return t.invertToRef(e),e}static RotationXToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return m.FromValuesToRef(1,0,0,0,0,i,r,0,0,-r,i,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationY(t){let e=new m;return m.RotationYToRef(t,e),e}static RotationYToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return m.FromValuesToRef(i,0,-r,0,0,1,0,0,r,0,i,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationZ(t){let e=new m;return m.RotationZToRef(t,e),e}static RotationZToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return m.FromValuesToRef(i,r,0,0,-r,i,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationAxis(t,e){let r=new m;return m.RotationAxisToRef(t,e,r),r}static RotationAxisToRef(t,e,r){let i=Math.sin(-e),s=Math.cos(-e),o=1-s;t.normalize();let n=r._m;return n[0]=t._x*t._x*o+s,n[1]=t._x*t._y*o-t._z*i,n[2]=t._x*t._z*o+t._y*i,n[3]=0,n[4]=t._y*t._x*o+t._z*i,n[5]=t._y*t._y*o+s,n[6]=t._y*t._z*o-t._x*i,n[7]=0,n[8]=t._z*t._x*o-t._y*i,n[9]=t._z*t._y*o+t._x*i,n[10]=t._z*t._z*o+s,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,r.markAsUpdated(),r}static RotationAlignToRef(t,e,r){let i=c.Dot(e,t),o=r._m;if(i<-1+s.kn)o[0]=-1,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=-1,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=1,o[11]=0;else{let r=c.Cross(e,t),s=1/(1+i);o[0]=r._x*r._x*s+i,o[1]=r._y*r._x*s-r._z,o[2]=r._z*r._x*s+r._y,o[3]=0,o[4]=r._x*r._y*s+r._z,o[5]=r._y*r._y*s+i,o[6]=r._z*r._y*s-r._x,o[7]=0,o[8]=r._x*r._z*s-r._y,o[9]=r._y*r._z*s+r._x,o[10]=r._z*r._z*s+i,o[11]=0}return o[12]=0,o[13]=0,o[14]=0,o[15]=1,r.markAsUpdated(),r}static RotationYawPitchRoll(t,e,r){let i=new m;return m.RotationYawPitchRollToRef(t,e,r,i),i}static RotationYawPitchRollToRef(t,e,r,i){return u.RotationYawPitchRollToRef(t,e,r,x.Quaternion[0]),x.Quaternion[0].toRotationMatrix(i),i}static Scaling(t,e,r){let i=new m;return m.ScalingToRef(t,e,r,i),i}static ScalingToRef(t,e,r,i){return m.FromValuesToRef(t,0,0,0,0,e,0,0,0,0,r,0,0,0,0,1,i),i._updateIdentityStatus(1===t&&1===e&&1===r),i}static Translation(t,e,r){let i=new m;return m.TranslationToRef(t,e,r,i),i}static TranslationToRef(t,e,r,i){return m.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,e,r,1,i),i._updateIdentityStatus(0===t&&0===e&&0===r),i}static Lerp(t,e,r){let i=new t.constructor;return m.LerpToRef(t,e,r,i),i}static LerpToRef(t,e,r,i){let s=i._m,o=t.m,n=e.m;for(let t=0;t<16;t++)s[t]=o[t]*(1-r)+n[t]*r;return i.markAsUpdated(),i}static DecomposeLerp(t,e,r){let i=new t.constructor;return m.DecomposeLerpToRef(t,e,r,i),i}static DecomposeLerpToRef(t,e,r,i){let s=x.Vector3[0],o=x.Quaternion[0],n=x.Vector3[1];t.decompose(s,o,n);let a=x.Vector3[2],h=x.Quaternion[1],_=x.Vector3[3];e.decompose(a,h,_);let l=x.Vector3[4];c.LerpToRef(s,a,r,l);let y=x.Quaternion[2];u.SlerpToRef(o,h,r,y);let R=x.Vector3[5];return c.LerpToRef(n,_,r,R),m.ComposeToRef(l,y,R,i),i}static LookAtLH(t,e,r){let i=new m;return m.LookAtLHToRef(t,e,r,i),i}static LookAtLHToRef(t,e,r,i){let s=x.Vector3[0],o=x.Vector3[1],n=x.Vector3[2];e.subtractToRef(t,n),n.normalize(),c.CrossToRef(r,n,s);let a=s.lengthSquared();0===a?s.x=1:s.normalizeFromLength(Math.sqrt(a)),c.CrossToRef(n,s,o),o.normalize();let h=-c.Dot(s,t),_=-c.Dot(o,t),l=-c.Dot(n,t);m.FromValuesToRef(s._x,o._x,n._x,0,s._y,o._y,n._y,0,s._z,o._z,n._z,0,h,_,l,1,i)}static LookAtRH(t,e,r){let i=new m;return m.LookAtRHToRef(t,e,r,i),i}static LookAtRHToRef(t,e,r,i){let s=x.Vector3[0],o=x.Vector3[1],n=x.Vector3[2];t.subtractToRef(e,n),n.normalize(),c.CrossToRef(r,n,s);let a=s.lengthSquared();0===a?s.x=1:s.normalizeFromLength(Math.sqrt(a)),c.CrossToRef(n,s,o),o.normalize();let h=-c.Dot(s,t),_=-c.Dot(o,t),l=-c.Dot(n,t);return m.FromValuesToRef(s._x,o._x,n._x,0,s._y,o._y,n._y,0,s._z,o._z,n._z,0,h,_,l,1,i),i}static LookDirectionLH(t,e){let r=new m;return m.LookDirectionLHToRef(t,e,r),r}static LookDirectionLHToRef(t,e,r){let i=x.Vector3[0];i.copyFrom(t),i.scaleInPlace(-1);let s=x.Vector3[1];return c.CrossToRef(e,i,s),m.FromValuesToRef(s._x,s._y,s._z,0,e._x,e._y,e._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static LookDirectionRH(t,e){let r=new m;return m.LookDirectionRHToRef(t,e,r),r}static LookDirectionRHToRef(t,e,r){let i=x.Vector3[2];return c.CrossToRef(e,t,i),m.FromValuesToRef(i._x,i._y,i._z,0,e._x,e._y,e._z,0,t._x,t._y,t._z,0,0,0,0,1,r),r}static OrthoLH(t,e,r,i,s){let o=new m;return m.OrthoLHToRef(t,e,r,i,o,s),o}static OrthoLHToRef(t,e,r,i,s,o){let n=2/t,a=2/e,h=2/(i-r),_=-(i+r)/(i-r);return m.FromValuesToRef(n,0,0,0,0,a,0,0,0,0,h,0,0,0,_,1,s),o&&s.multiplyToRef(f,s),s._updateIdentityStatus(1===n&&1===a&&1===h&&0===_),s}static OrthoOffCenterLH(t,e,r,i,s,o,n){let a=new m;return m.OrthoOffCenterLHToRef(t,e,r,i,s,o,a,n),a}static OrthoOffCenterLHToRef(t,e,r,i,s,o,n,a){return m.FromValuesToRef(2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,2/(o-s),0,(t+e)/(t-e),(i+r)/(r-i),-(o+s)/(o-s),1,n),a&&n.multiplyToRef(f,n),n.markAsUpdated(),n}static OrthoOffCenterRH(t,e,r,i,s,o,n){let a=new m;return m.OrthoOffCenterRHToRef(t,e,r,i,s,o,a,n),a}static OrthoOffCenterRHToRef(t,e,r,i,s,o,n,a){return m.OrthoOffCenterLHToRef(t,e,r,i,s,o,n,a),n._m[10]*=-1,n}static PerspectiveLH(t,e,r,i,s,o=0){let n=new m,a=Math.tan(o);return m.FromValuesToRef(2*r/t,0,0,0,0,2*r/e,0,a,0,0,(i+r)/(i-r),1,0,0,-2*i*r/(i-r),0,n),s&&n.multiplyToRef(f,n),n._updateIdentityStatus(!1),n}static PerspectiveFovLH(t,e,r,i,s,o=0,n=!1){let a=new m;return m.PerspectiveFovLHToRef(t,e,r,i,a,!0,s,o,n),a}static PerspectiveFovLHToRef(t,e,r,i,s,o=!0,n,a=0,h=!1){let _=1/Math.tan(.5*t),l=o?_/e:_,c=o?_:_*e,y=h&&0===r?-1:0!==i?(i+r)/(i-r):1,u=h&&0===r?2*i:0!==i?-2*i*r/(i-r):-2*r,x=Math.tan(a);return m.FromValuesToRef(l,0,0,0,0,c,0,x,0,0,y,1,0,0,u,0,s),n&&s.multiplyToRef(f,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(t,e,r,i,s,o=!0,n,a=0){let h=1/Math.tan(.5*t),_=o?h/e:h,l=o?h:h*e,c=Math.tan(a);return m.FromValuesToRef(_,0,0,0,0,l,0,c,0,0,-r,1,0,0,1,0,s),n&&s.multiplyToRef(f,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(t,e,r,i,s,o=0,n=!1){let a=new m;return m.PerspectiveFovRHToRef(t,e,r,i,a,!0,s,o,n),a}static PerspectiveFovRHToRef(t,e,r,i,s,o=!0,n,a=0,h=!1){let _=1/Math.tan(.5*t),l=o?_/e:_,c=o?_:_*e,y=h&&0===r?1:0!==i?-(i+r)/(i-r):-1,u=h&&0===r?2*i:0!==i?-2*i*r/(i-r):-2*r,x=Math.tan(a);return m.FromValuesToRef(l,0,0,0,0,c,0,x,0,0,y,-1,0,0,u,0,s),n&&s.multiplyToRef(f,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(t,e,r,i,s,o=!0,n,a=0){let h=1/Math.tan(.5*t),_=o?h/e:h,l=o?h:h*e,c=Math.tan(a);return m.FromValuesToRef(_,0,0,0,0,l,0,c,0,0,-r,-1,0,0,-1,0,s),n&&s.multiplyToRef(f,s),s._updateIdentityStatus(!1),s}static PerspectiveFovWebVRToRef(t,e,r,i,s=!1,o,n=0){let a=Math.tan(t.upDegrees*Math.PI/180),h=Math.tan(t.downDegrees*Math.PI/180),_=Math.tan(t.leftDegrees*Math.PI/180),l=Math.tan(t.rightDegrees*Math.PI/180),c=2/(_+l),y=2/(a+h),u=i._m;return u[0]=c,u[1]=u[2]=u[3]=u[4]=0,u[5]=y,u[6]=0,u[7]=Math.tan(n),u[8]=(_-l)*c*.5,u[9]=-((a-h)*y*.5),u[10]=-r/(e-r),u[11]=1*(s?-1:1),u[12]=u[13]=u[15]=0,u[14]=-(2*r*e)/(r-e),o&&i.multiplyToRef(f,i),i.markAsUpdated(),i}static GetFinalMatrix(t,e,r,i,s,o){let n=t.width,a=t.height,h=t.x,_=t.y,l=m.FromValues(n/2,0,0,0,0,-a/2,0,0,0,0,o-s,0,h+n/2,a/2+_,s,1),c=new e.constructor;return e.multiplyToRef(r,c),c.multiplyToRef(i,c),c.multiplyToRef(l,c)}static GetAsMatrix2x2(t){let e=t.m,r=[e[0],e[1],e[4],e[5]];return a.Z.MatrixUse64Bits?r:new Float32Array(r)}static GetAsMatrix3x3(t){let e=t.m,r=[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]];return a.Z.MatrixUse64Bits?r:new Float32Array(r)}static Transpose(t){let e=new t.constructor;return m.TransposeToRef(t,e),e}static TransposeToRef(t,e){let r=e._m,i=t.m;return r[0]=i[0],r[1]=i[4],r[2]=i[8],r[3]=i[12],r[4]=i[1],r[5]=i[5],r[6]=i[9],r[7]=i[13],r[8]=i[2],r[9]=i[6],r[10]=i[10],r[11]=i[14],r[12]=i[3],r[13]=i[7],r[14]=i[11],r[15]=i[15],e.markAsUpdated(),e._updateIdentityStatus(t._isIdentity,t._isIdentityDirty),e}static Reflection(t){let e=new m;return m.ReflectionToRef(t,e),e}static ReflectionToRef(t,e){t.normalize();let r=t.normal.x,i=t.normal.y,s=t.normal.z,o=-2*r,n=-2*i,a=-2*s;return m.FromValuesToRef(o*r+1,n*r,a*r,0,o*i,n*i+1,a*i,0,o*s,n*s,a*s+1,0,o*t.d,n*t.d,a*t.d,1,e),e}static FromXYZAxesToRef(t,e,r,i){return m.FromValuesToRef(t._x,t._y,t._z,0,e._x,e._y,e._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static FromQuaternionToRef(t,e){let r=t._x*t._x,i=t._y*t._y,s=t._z*t._z,o=t._x*t._y,n=t._z*t._w,a=t._z*t._x,h=t._y*t._w,_=t._y*t._z,l=t._x*t._w;return e._m[0]=1-2*(i+s),e._m[1]=2*(o+n),e._m[2]=2*(a-h),e._m[3]=0,e._m[4]=2*(o-n),e._m[5]=1-2*(s+r),e._m[6]=2*(_+l),e._m[7]=0,e._m[8]=2*(a+h),e._m[9]=2*(_-l),e._m[10]=1-2*(i+r),e._m[11]=0,e._m[12]=0,e._m[13]=0,e._m[14]=0,e._m[15]=1,e.markAsUpdated(),e}}m._UpdateFlagSeed=0,m._IdentityReadOnly=m.Identity();class x{}x.Vector3=o.B.BuildTuple(11,c.Zero),x.Matrix=o.B.BuildTuple(2,m.Identity),x.Quaternion=o.B.BuildTuple(3,u.Zero);class R{}R.Vector2=o.B.BuildTuple(3,l.Zero),R.Vector3=o.B.BuildTuple(13,c.Zero),R.Vector4=o.B.BuildTuple(3,y.Zero),R.Quaternion=o.B.BuildTuple(2,u.Zero),R.Matrix=o.B.BuildTuple(8,m.Identity),(0,n.H)("BABYLON.Vector2",l),(0,n.H)("BABYLON.Vector3",c),(0,n.H)("BABYLON.Vector4",y),(0,n.H)("BABYLON.Matrix",m);let f=m.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1)}}]); \ No newline at end of file diff --git a/.next/static/chunks/f75787ed-011198ef7e5d7754.js b/.next/static/chunks/f75787ed-011198ef7e5d7754.js deleted file mode 100644 index f17ce58..0000000 --- a/.next/static/chunks/f75787ed-011198ef7e5d7754.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[995],{6438:function(e,t,s){s.d(t,{a:function(){return r},x:function(){return D}});var i,r,a=s(3636),n=s(8257),o=s(6702),h=s(1945),l=s(4346),d=s(8772),u=s(1823),c=s(2725),g=s(9290),m=s(1378),f=s(9657),_=s(9326),v=s(1970),b=s(7077),p=s(176),M=s(216),C=s(3914),y=s(4620),R=s(8033),O=s(6339),A=s(6762),P=s(9320),S=s(2853),w=s(41),T=s(8463),B=s(4046),I=s(9334);(i=r||(r={}))[i.BackwardCompatible=0]="BackwardCompatible",i[i.Intermediate=1]="Intermediate",i[i.Aggressive=2]="Aggressive";class D extends c.p{static DefaultMaterialFactory(e){throw(0,y.S)("StandardMaterial")}static CollisionCoordinatorFactory(){throw(0,y.S)("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case r.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case r.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case r.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return R.$.DragMovementThreshold}static set DragMovementThreshold(e){R.$.DragMovementThreshold=e}static get LongPressDelay(){return R.$.LongPressDelay}static set LongPressDelay(e){R.$.LongPressDelay=e}static get DoubleClickDelay(){return R.$.DoubleClickDelay}static set DoubleClickDelay(e){R.$.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return R.$.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){R.$.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",s=!1){var i;let r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:null!==(i=this.activeCamera.globalPosition)&&void 0!==i?i:this.activeCamera.devicePosition,a=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return u.jp.Vector4[0].set(r.x,r.y,r.z,a?-1:1),e&&(s?e.setFloat3(t,u.jp.Vector4[0].x,u.jp.Vector4[0].y,u.jp.Vector4[0].z):e.setVector4(t,u.jp.Vector4[0])),u.jp.Vector4[0]}finalizeSceneUbo(){let e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=(0,B.M)(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=D.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=D.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(let e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e),e.addFromContainer&&e.serialize&&this._serializableComponents.push(e)}_getComponent(e){for(let t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new R.$(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new A.HE(.2,.2,.3,1),this.ambientColor=new A.Wo(0,0,0),this.environmentIntensity=1,this._performancePriority=r.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new o.y$,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new o.y$,this._onDisposeObserver=null,this.onBeforeRenderObservable=new o.y$,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new o.y$,this.onAfterRenderCameraObservable=new o.y$,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new o.y$,this.onAfterAnimationsObservable=new o.y$,this.onBeforeDrawPhaseObservable=new o.y$,this.onAfterDrawPhaseObservable=new o.y$,this.onReadyObservable=new o.y$,this.onBeforeCameraRenderObservable=new o.y$,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new o.y$,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new o.y$,this.onAfterActiveMeshesEvaluationObservable=new o.y$,this.onBeforeParticlesRenderingObservable=new o.y$,this.onAfterParticlesRenderingObservable=new o.y$,this.onDataLoadedObservable=new o.y$,this.onNewCameraAddedObservable=new o.y$,this.onCameraRemovedObservable=new o.y$,this.onNewLightAddedObservable=new o.y$,this.onLightRemovedObservable=new o.y$,this.onNewGeometryAddedObservable=new o.y$,this.onGeometryRemovedObservable=new o.y$,this.onNewTransformNodeAddedObservable=new o.y$,this.onTransformNodeRemovedObservable=new o.y$,this.onNewMeshAddedObservable=new o.y$,this.onMeshRemovedObservable=new o.y$,this.onNewSkeletonAddedObservable=new o.y$,this.onSkeletonRemovedObservable=new o.y$,this.onNewMaterialAddedObservable=new o.y$,this.onNewMultiMaterialAddedObservable=new o.y$,this.onMaterialRemovedObservable=new o.y$,this.onMultiMaterialRemovedObservable=new o.y$,this.onNewTextureAddedObservable=new o.y$,this.onTextureRemovedObservable=new o.y$,this.onBeforeRenderTargetsRenderObservable=new o.y$,this.onAfterRenderTargetsRenderObservable=new o.y$,this.onBeforeStepObservable=new o.y$,this.onAfterStepObservable=new o.y$,this.onActiveCameraChanged=new o.y$,this.onActiveCamerasChanged=new o.y$,this.onBeforeRenderingGroupObservable=new o.y$,this.onAfterRenderingGroupObservable=new o.y$,this.onMeshImportedObservable=new o.y$,this.onAnimationFileImportedObservable=new o.y$,this._registeredForLateAnimationBindings=new h.f(256),this._pointerPickingConfiguration=new I.M,this.onPrePointerObservable=new o.y$,this.onPointerObservable=new o.y$,this.onPreKeyboardObservable=new o.y$,this.onKeyboardObservable=new o.y$,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=D.FOGMODE_NONE,this.fogColor=new A.Wo(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new u.P(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new h.f(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new O.z,this._activeIndices=new O.z,this._activeParticles=new O.z,this._activeBones=new O.z,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=Array(256),this._activeRequests=[],this._pendingData=[],this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new h.t(256),this._processedMaterials=new h.t(256),this._renderTargets=new h.f(256),this._materialsRenderTargets=new h.f(256),this._activeParticleSystems=new h.t(256),this._activeSkeletons=new h.f(32),this._softwareSkinnedMeshes=new h.f(32),this._activeAnimatables=[],this._transformMatrix=u.y3.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=p.H.Create(),this._beforeClearStage=p.H.Create(),this._beforeRenderTargetClearStage=p.H.Create(),this._gatherRenderTargetsStage=p.H.Create(),this._gatherActiveCameraRenderTargetsStage=p.H.Create(),this._isReadyForMeshStage=p.H.Create(),this._beforeEvaluateActiveMeshStage=p.H.Create(),this._evaluateSubMeshStage=p.H.Create(),this._preActiveMeshStage=p.H.Create(),this._cameraDrawRenderTargetStage=p.H.Create(),this._beforeCameraDrawStage=p.H.Create(),this._beforeRenderTargetDrawStage=p.H.Create(),this._beforeRenderingGroupDrawStage=p.H.Create(),this._beforeRenderingMeshStage=p.H.Create(),this._afterRenderingMeshStage=p.H.Create(),this._afterRenderingGroupDrawStage=p.H.Create(),this._afterCameraDrawStage=p.H.Create(),this._afterCameraPostProcessStage=p.H.Create(),this._afterRenderTargetDrawStage=p.H.Create(),this._afterRenderTargetPostProcessStage=p.H.Create(),this._afterRenderStage=p.H.Create(),this._pointerMoveStage=p.H.Create(),this._pointerDownStage=p.H.Create(),this._pointerUpStage=p.H.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];let s=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);this._engine=e||C.l.LastCreatedEngine,s.virtual?this._engine._virtualScenes.push(this):(C.l._LastCreatedScene=this,this._engine.scenes.push(this)),this._uid=null,this._renderingManager=new b.$(this),v.O&&(this.postProcessManager=new v.O(this)),(0,M.CG)()&&this.attachControl(),this._createUbo(),g.$&&(this._imageProcessingConfiguration=new g.$),this.setDefaultCandidateProviders(),s.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=s.useMaterialMeshMap,this.useClonedMeshMap=s.useClonedMeshMap,t&&t.virtual||this._engine.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=this._getDefaultMeshCandidates.bind(this),this.getActiveSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getIntersectingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this),this.getCollidingSubMeshCandidates=this._getDefaultSubMeshCandidates.bind(this)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,s=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==s}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,s){return this._inputManager.simulatePointerUp(e,t,s),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,s=!0){this._inputManager.attachControl(e,t,s)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var t,s,i;let r;if(this._isDisposed)return!1;let a=this.getEngine(),n=a.currentRenderPassId;a.currentRenderPassId=null!==(s=null===(t=this.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==s?s:n;let o=!0;for(this._pendingData.length>0&&(o=!1),null===(i=this.prePassRenderer)||void 0===i||i.update(),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),r=0;r<this.meshes.length;r++){let t=this.meshes[r];if(!t.subMeshes||0===t.subMeshes.length)continue;if(!t.isReady(!0)){o=!1;continue}let s=t.hasThinInstances||"InstancedMesh"===t.getClassName()||"InstancedLinesMesh"===t.getClassName()||a.getCaps().instancedArrays&&t.instances.length>0;for(let e of this._isReadyForMeshStage)e.action(t,s)||(o=!1);if(!e)continue;let i=t.material||this.defaultMaterial;if(i){if(i._storeEffectOnSubMeshes)for(let e of t.subMeshes){let t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else i.hasRenderTargetTextures&&null!=i.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(i)&&(this._processedMaterials.push(i),this._materialsRenderTargets.concatWithNoDuplicate(i.getRenderTargetTextures()))}}if(e)for(r=0;r<this._materialsRenderTargets.length;++r){let e=this._materialsRenderTargets.data[r];e.isReadyForRendering()||(o=!1)}for(r=0;r<this.geometries.length;r++){let e=this.geometries[r];2===e.delayLoadState&&(o=!1)}if(this.activeCameras&&this.activeCameras.length>0)for(let e of this.activeCameras)e.isReady(!0)||(o=!1);else this.activeCamera&&!this.activeCamera.isReady(!0)&&(o=!1);for(let e of this.particleSystems)e.isReady()||(o=!1);if(this.layers)for(let e of this.layers)e.isReady()||(o=!1);return a.areAllEffectsReady()||(o=!1),a.currentRenderPassId=n,o}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){let t=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(t)})};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){let t=this.isLoading,s=this._pendingData.indexOf(e);-1!==s&&this._pendingData.splice(s,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_checkIsReady(e=!1){if(this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=n.F.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,s,i){s||i||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),(this._viewUpdateFlag!==e.updateFlag||this._projectionUpdateFlag!==t.updateFlag)&&(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?P.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=P.i.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(s,i):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){let t=new m.M(this._engine,void 0,!1,null!=e?e:"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return S.K.UniqueId}addMesh(e,t=!1){!this._blockEntityCollection&&(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(e=>{this.addMesh(e)}))}removeMesh(e,t=!1){let s=this.meshes.indexOf(e);return -1===s||(this.meshes[s]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(e=>{this.removeMesh(e)}),s}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){let t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){let e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){let t=this.skeletons.indexOf(e);return -1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){let t=this.morphTargetManagers.indexOf(e);return -1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){let t=this.lights.indexOf(e);if(-1!==t){for(let t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){let t=this.cameras.indexOf(e);if(-1===t||(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){let t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){let t=this.particleSystems.indexOf(e);return -1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){let t=this.animations.indexOf(e);return -1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,s){}removeAnimationGroup(e){let t=this.animationGroups.indexOf(e);return -1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){let t=this.multiMaterials.indexOf(e);return -1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){let t=e._indexInSceneMaterialArray;if(-1!==t&&t<this.materials.length){if(t!==this.materials.length-1){let e=this.materials[this.materials.length-1];this.materials[t]=e,e._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t}removeActionManager(e){let t=this.actionManagers.indexOf(e);return -1!==t&&this.actionManagers.splice(t,1),t}removeTexture(e){let t=this.textures.indexOf(e);return -1!==t&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t}addLight(e){if(!this._blockEntityCollection){for(let t of(this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes(),this.meshes))-1===t.lightSources.indexOf(e)&&(t.lightSources.push(e),t._resyncLightSources());this.onNewLightAddedObservable.notifyObservers(e)}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(T.m.CompareLightsPriority)}addCamera(e){!this._blockEntityCollection&&(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),this.onNewSkeletonAddedObservable.notifyObservers(e))}addParticleSystem(e){this._blockEntityCollection||this.particleSystems.push(e)}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||this.animationGroups.push(e)}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),this.onNewMultiMaterialAddedObservable.notifyObservers(e))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),this.onNewMaterialAddedObservable.notifyObservers(e))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}switchActiveCamera(e,t=!0){let s=this._engine.getInputElement();s&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){let t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){let t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null}_getMaterial(e,t){for(let e=0;e<this.materials.length;e++){let s=this.materials[e];if(t(s))return s}if(e)for(let e=0;e<this.multiMaterials.length;e++){let s=this.multiMaterials[e];if(t(s))return s}return null}getMaterialByUniqueID(e,t=!1){return this._getMaterial(t,t=>t.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,t=>t.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,t=>t.name===e)}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t){for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t]}return null}getTextureByUniqueId(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null}getTextureByName(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null}getCameraById(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null}getCameraByUniqueId(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null}getCameraByName(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null}getBoneById(e){for(let t=0;t<this.skeletons.length;t++){let s=this.skeletons[t];for(let t=0;t<s.bones.length;t++)if(s.bones[t].id===e)return s.bones[t]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){let s=this.skeletons[t];for(let t=0;t<s.bones.length;t++)if(s.bones[t].name===e)return s.bones[t]}return null}getLightByName(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null}getLightById(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null}getLightByUniqueId(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null}getParticleSystemById(e){for(let t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null}getGeometryById(e){for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null}_getGeometryByUniqueId(e){if(this._geometriesByUniqueId){let t=this._geometriesByUniqueId[e];if(void 0!==t)return this.geometries[t]}else for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null}pushGeometry(e,t){return!(!t&&this._getGeometryByUniqueId(e.uniqueId))&&(this.addGeometry(e),this.onNewGeometryAddedObservable.notifyObservers(e),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(void 0===(t=this._geometriesByUniqueId[e.uniqueId]))return!1}else if((t=this.geometries.indexOf(e))<0)return!1;if(t!==this.geometries.length-1){let e=this.geometries[this.geometries.length-1];e&&(this.geometries[t]=e,this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null}getMeshesById(e){return this.meshes.filter(function(t){return t.id===e})}getTransformNodeById(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getTransformNodeByUniqueId(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null}getTransformNodesById(e){return this.transformNodes.filter(function(t){return t.id===e})}getMeshByUniqueId(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null}getLastMeshById(e){for(let t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){let t=this.getMeshById(e);if(t)return t;let s=this.getTransformNodeById(e);if(s)return s;let i=this.getLightById(e);if(i)return i;let r=this.getCameraById(e);if(r)return r;let a=this.getBoneById(e);return a||null}getNodeByName(e){let t=this.getMeshByName(e);if(t)return t;let s=this.getTransformNodeByName(e);if(s)return s;let i=this.getLightByName(e);if(i)return i;let r=this.getCameraByName(e);if(r)return r;let a=this.getBoneByName(e);return a||null}getMeshByName(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null}getTransformNodeByName(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null}getLastSkeletonById(e){for(let t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null}getSkeletonById(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByName(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null}getMorphTargetManagerById(e){for(let t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null}getMorphTargetById(e){for(let t=0;t<this.morphTargetManagers.length;++t){let s=this.morphTargetManagers[t];for(let t=0;t<s.numTargets;++t){let i=s.getTarget(t);if(i.id===e)return i}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){let s=this.morphTargetManagers[t];for(let t=0;t<s.numTargets;++t){let i=s.getTarget(t);if(i.name===e)return i}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){let s=this.postProcesses[t];if(s.name===e)return s}return null}isActiveMesh(e){return -1!==this._activeMeshes.indexOf(e)}get uid(){return this._uid||(this._uid=a.w1.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new l.x),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new l.x),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,s,i){if(i||e.isInFrustum(this._frustumPlanes)){for(let s of this._evaluateSubMeshStage)s.action(t,e);let s=e.getMaterial();null!=s&&(s.hasRenderTargetTextures&&null!=s.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(s)&&(this._processedMaterials.push(s),this._materialsRenderTargets.concatWithNoDuplicate(s.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,s))}}freeProcessedMaterials(){this._processedMaterials.dispose()}get blockfreeActiveMeshesAndRenderingGroups(){return this._preventFreeActiveMeshesAndRenderingGroups}set blockfreeActiveMeshesAndRenderingGroups(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)}freeActiveMeshes(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(let e=0;e<this.activeCameras.length;e++){let t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}}freeRenderingGroups(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(let e=0;e<this.textures.length;e++){let t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}}_isInIntermediateRendering(){return this._intermediateRendering}freezeActiveMeshes(e=!1,t,s,i=!0,r=!1){return this.executeWhenReady(()=>{if(!this.activeCamera){s&&s("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,i)for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._freeze();t&&t()}),this}unfreezeActiveMeshes(){for(let e=0;e<this.meshes.length;e++){let t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this}_executeActiveContainerCleanup(e){let t=this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode;!t&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce(()=>e.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode){this._activeMeshes.length>0&&(null===(e=this.activeCamera)||void 0===e||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){let e=this._activeMeshes.length;for(let t=0;t<e;t++){let e=this._activeMeshes.data[t];e.computeWorldMatrix()}}if(this._activeParticleSystems){let e=this._activeParticleSystems.length;for(let t=0;t<e;t++)this._activeParticleSystems.data[t].animate()}this._renderingManager.resetSprites();return}if(!this.activeCamera)return;for(let e of(this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset(),this._beforeEvaluateActiveMeshStage))e.action();let t=this.getActiveMeshCandidates(),s=t.length;for(let e=0;e<s;e++){let s=t.data[e];if(s._internalAbstractMeshDataInfo._currentLODIsUpToDate=!1,s.isBlocked||(this._totalVertices.addCount(s.getTotalVertices(),!1),!s.isReady()||!s.isEnabled()||s.scaling.hasAZeroComponent))continue;s.computeWorldMatrix(),s.actionManager&&s.actionManager.hasSpecificTriggers2(12,13)&&this._meshesForIntersections.pushNoDuplicate(s);let i=this.customLODSelector?this.customLODSelector(s,this.activeCamera):s.getLOD(this.activeCamera);if(s._internalAbstractMeshDataInfo._currentLOD=i,s._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,null!=i&&(i!==s&&0!==i.billboardMode&&i.computeWorldMatrix(),s._preActivate(),s.isVisible&&s.visibility>0&&(s.layerMask&this.activeCamera.layerMask)!=0&&(this._skipFrustumClipping||s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes)))){for(let e of(this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),i!==s&&i._activate(this._renderId,!1),this._preActiveMeshStage))e.action(s);s._activate(this._renderId,!1)&&(s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(i=s):i._internalAbstractMeshDataInfo._onlyForInstances=!1,i._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,i)),s._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e<this.particleSystems.length;e++){let t=this.particleSystems[e];if(!t.isStarted()||!t.emitter)continue;let s=t.emitter;(!s.position||s.isEnabled())&&(this._activeParticleSystems.push(t),t.animate(),this._renderingManager.dispatchParticles(t))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_activeMesh(e,t){this._skeletonsEnabled&&null!==t.skeleton&&void 0!==t.skeleton&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&(t.skeleton.prepare(),this._activeBones.addCount(t.skeleton.bones.length,!1)),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t));let s=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){let i=this.getActiveSubMeshCandidates(t),r=i.length;s=s||1===r;for(let a=0;a<r;a++){let r=i.data[a];this._evaluateSubMesh(r,t,e,s)}}}updateTransformMatrix(e){if(this.activeCamera){if(this.activeCamera._renderingMultiview){let t=this.activeCamera._rigCameras[0],s=this.activeCamera._rigCameras[1];this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e),s.getViewMatrix(),s.getProjectionMatrix(e))}else this.setTransformMatrix(this.activeCamera.getViewMatrix(),this.activeCamera.getProjectionMatrix(e))}}_bindFrameBuffer(e,t=!0){e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer(),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(e&&e._multiviewTexture);else if(e&&e.outputRenderTarget&&!e._renderingMultiview){let t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):t.skipInitialClear||(this.autoClear&&this._engine.clear(t.clearColor||this.clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,s=!0){var i,r,n;if(e&&e._skipRendering)return;let o=this._engine;if(this._activeCamera=e,!this.activeCamera)throw Error("Active camera not set");if(o.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&s){let t=!0;e._renderingMultiview&&e.outputRenderTarget&&(t=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=t)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(let e=0;e<this._softwareSkinnedMeshes.length;e++){let t=this._softwareSkinnedMeshes.data[e];t.applySkeleton(t.skeleton)}for(let s of(this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture),this._gatherActiveCameraRenderTargetsStage))s.action(this._renderTargets);let h=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){a.w1.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e<this._renderTargets.length;e++){let t=this._renderTargets.data[e];if(t._shouldRender()){this._renderId++;let e=t.activeCamera&&t.activeCamera!==this.activeCamera;t.render(e,this.dumpNextRenderTargets),h=!0}}a.w1.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(let e of this._cameraDrawRenderTargetStage)h=e.action(this.activeCamera)||h;this._intermediateRendering=!1}for(let t of(this._engine.currentRenderPassId=null!==(n=null!==(r=null===(i=e.outputRenderTarget)||void 0===i?void 0:i.renderPassId)&&void 0!==r?r:e.renderPassId)&&void 0!==n?n:0,h&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame(),this._beforeCameraDrawStage))t.action(this.activeCamera);for(let e of(this.onBeforeDrawPhaseObservable.notifyObservers(this),o.snapshotRendering&&1===o.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this),this._afterCameraDrawStage))e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){let t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(let e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t<e._rigCameras.length;t++)this._renderForCamera(e._rigCameras[t],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)}_checkIntersections(){for(let e=0;e<this._meshesForIntersections.length;e++){let t=this._meshesForIntersections.data[e];if(t.actionManager)for(let e=0;t.actionManager&&e<t.actionManager.actions.length;e++){let s=t.actionManager.actions[e];if(12===s.trigger||13===s.trigger){let e=s.getTriggerParameter(),i=e.mesh?e.mesh:e,r=i.intersectsMesh(t,e.usePreciseIntersection),a=t._intersectionsInProgress.indexOf(i);r&&-1===a?12===s.trigger?(s._executeCurrent(_.V.CreateNew(t,void 0,i)),t._intersectionsInProgress.push(i)):13===s.trigger&&t._intersectionsInProgress.push(i):r||!(a>-1)||(13===s.trigger&&s._executeCurrent(_.V.CreateNew(t,void 0,i)),t.actionManager.hasSpecificTrigger(13,e=>{let t=e.mesh?e.mesh:e;return i===t})&&13!==s.trigger||t._intersectionsInProgress.splice(a,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(D.MinDeltaTime,Math.min(this._engine.getDeltaTime(),D.MaxDeltaTime))+this._timeAccumulator,t=this._engine.getTimeStep(),s=1e3/t/1e3,i=0,r=this._engine.getLockstepMaxSteps(),a=Math.floor(e/t);for(a=Math.min(a,r);e>0&&i<a;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*s,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,i++,e-=t;this._timeAccumulator=e<0?0:e}else{let e=this.useConstantAnimationDeltaTime?16:Math.max(D.MinDeltaTime,Math.min(this._engine.getDeltaTime(),D.MaxDeltaTime));this._animationRatio=.06*e,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}}_clear(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)}_checkCameraRenderTarget(e){var t;if((null==e?void 0:e.outputRenderTarget)&&!(null==e?void 0:e.isRigCamera)&&(e.outputRenderTarget._cleared=!1),null===(t=null==e?void 0:e.rigCameras)||void 0===t?void 0:t.length)for(let t=0;t<e.rigCameras.length;++t){let s=e.rigCameras[t].outputRenderTarget;s&&(s._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(let t of this.meshes)t.resetDrawCache(e)}render(e=!0,t=!1){var s,i,r;if(this.isDisposed)return;for(let e of(this.onReadyObservable.hasObservers()&&null===this._executeWhenReadyTimeoutId&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),(null===(s=this.activeCameras)||void 0===s?void 0:s.length)&&this.activeCameras.forEach(this._checkCameraRenderTarget),this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(11),t||this.animate(),this._beforeCameraUpdateStage))e.action();if(e){if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++){let t=this.activeCameras[e];if(t.update(),0!==t.cameraRigMode)for(let e=0;e<t._rigCameras.length;e++)t._rigCameras[e].update()}else if(this.activeCamera&&(this.activeCamera.update(),0!==this.activeCamera.cameraRigMode))for(let e=0;e<this.activeCamera._rigCameras.length;e++)this.activeCamera._rigCameras[e].update()}this.onBeforeRenderObservable.notifyObservers(this);let n=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);let o=(null===(i=this.activeCameras)||void 0===i?void 0:i.length)?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){a.w1.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(let e=0;e<this.customRenderTargets.length;e++){let t=this.customRenderTargets[e];if(t._shouldRender()){if(this._renderId++,this.activeCamera=t.activeCamera||this.activeCamera,!this.activeCamera)throw Error("Active camera not set");n.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),t.render(o!==this.activeCamera,this.dumpNextRenderTargets)}}a.w1.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}for(let e of(this._engine.currentRenderPassId=null!==(r=null==o?void 0:o.renderPassId)&&void 0!==r?r:0,this.activeCamera=o,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this._beforeClearStage))e.action();for(let e of(this._clearFrameBuffer(this.activeCamera),this._gatherRenderTargetsStage))e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++)this._processSubCameras(this.activeCameras[e],e>0);else{if(!this.activeCamera)throw Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}for(let e of(this._checkIntersections(),this._afterRenderStage))e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e<this._toBeDisposed.length;e++){let t=this._toBeDisposed[e];t&&t.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this.importedMeshesFiles=[],this.stopAllAnimations&&(this._activeAnimatables.forEach(e=>{e.onAnimationEndObservable.clear(),e.onAnimationEnd=null}),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;let e=this._activeRequests.slice();for(let t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){console.error("An error occurred while calling onDisposeObservable!",e)}this.detachControl();let t=this._engine.getInputElement();if(t)for(let e=0;e<this.cameras.length;e++)this.cameras[e].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._disposeList(this.meshes,e=>e.dispose(!0)),this._disposeList(this.transformNodes,e=>e.dispose(!0));let s=this.cameras;this._disposeList(s),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),C.l._LastCreatedScene===this&&(this._engine.scenes.length>0?C.l._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:C.l._LastCreatedScene=null),(i=this._engine._virtualScenes.indexOf(this))>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){let s=e.slice(0);for(let e of(t=null!=t?t:e=>e.dispose(),s))t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e<this.meshes.length;e++){let t=this.meshes[e],s=t.geometry;s&&s.clearCachedData()}}cleanCachedTextureBuffer(){for(let e of this.textures){let t=e._buffer;t&&(e._buffer=null)}}getWorldExtends(e){let t=new u.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new u.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||(()=>!0),this.meshes.filter(e).forEach(e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;let i=e.getBoundingInfo(),r=i.boundingBox.minimumWorld,a=i.boundingBox.maximumWorld;u.P.CheckExtends(r,t,s),u.P.CheckExtends(a,t,s)}),{min:t,max:s}}createPickingRay(e,t,s,i,r=!1){throw(0,y.S)("Ray")}createPickingRayToRef(e,t,s,i,r,a=!1,n=!1){throw(0,y.S)("Ray")}createPickingRayInCameraSpace(e,t,s){throw(0,y.S)("Ray")}createPickingRayInCameraSpaceToRef(e,t,s,i){throw(0,y.S)("Ray")}get _pickingAvailable(){return!1}pick(e,t,s,i,r,a){return new f.p}pickWithBoundingInfo(e,t,s,i,r){return new f.p}pickWithRay(e,t,s,i){throw(0,y.S)("Ray")}multiPick(e,t,s,i,r){throw(0,y.S)("Ray")}multiPickWithRay(e,t,s){throw(0,y.S)("Ray")}setPointerOverMesh(e,t,s){this._inputManager.setPointerOverMesh(e,t,s)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of(this.postProcessManager&&this.postProcessManager._rebuild(),this._components))e.rebuild();for(let e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(let e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(let e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,s){if(void 0===t)return e;let i=[];for(let r in s=s||(e=>{}),e){let a=e[r];d.$&&d.$.MatchesQuery(a,t)&&(i.push(a),s(a))}return i}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,s=null,i=null){this._renderingManager.setRenderingOrder(e,t,s,i)}setRenderingAutoClearDepthStencil(e,t,s=!0,i=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,s,i)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(let s of this.materials)(!t||t(s))&&s.markAsDirty(e)}_loadFile(e,t,s,i,r,a,n){let o=(0,w.vP)(e,t,s,i?this.offlineProvider:void 0,r,a,n);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}_loadFileAsync(e,t,s,i,r){return new Promise((a,n)=>{this._loadFile(e,e=>{a(e)},t,s,i,(e,t)=>{n(t)},r)})}_requestFile(e,t,s,i,r,a,n){let o=(0,w.FV)(e,t,s,i?this.offlineProvider:void 0,r,a,n);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}_requestFileAsync(e,t,s,i,r){return new Promise((a,n)=>{this._requestFile(e,e=>{a(e)},t,s,i,e=>{n(e)},r)})}_readFile(e,t,s,i,r){let a=(0,w.Ip)(e,t,s,i,r);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}_readFileAsync(e,t,s){return new Promise((i,r)=>{this._readFile(e,e=>{i(e)},t,s,e=>{r(e)})})}getPerfCollector(){throw(0,y.S)("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}D.FOGMODE_NONE=0,D.FOGMODE_EXP=1,D.FOGMODE_EXP2=2,D.FOGMODE_LINEAR=3,D.MinDeltaTime=1,D.MaxDeltaTime=1e3}}]); \ No newline at end of file diff --git a/.next/static/chunks/fd9d1056-ba10bf844a47945b.js b/.next/static/chunks/fd9d1056-ba10bf844a47945b.js new file mode 100644 index 0000000..36a67a6 --- /dev/null +++ b/.next/static/chunks/fd9d1056-ba10bf844a47945b.js @@ -0,0 +1,9 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[971],{4417:function(n,a,i){/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var o,s=i(2265),m=i(8261),y={usingClientEntryPoint:!1,Events:null,Dispatcher:{current:null}};function t(n){for(var a="https://reactjs.org/docs/error-decoder.html?invariant="+n,i=1;i<arguments.length;i++)a+="&args[]="+encodeURIComponent(arguments[i]);return"Minified React error #"+n+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var v=Object.assign,k=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,S=k.ReactCurrentDispatcher,C={pending:!1,data:null,method:null,action:null},x=[],P=-1;function ka(n){return{current:n}}function D(n){0>P||(n.current=x[P],x[P]=null,P--)}function E(n,a){x[++P]=n.current,n.current=a}var N=Symbol.for("react.element"),j=Symbol.for("react.portal"),L=Symbol.for("react.fragment"),_=Symbol.for("react.strict_mode"),M=Symbol.for("react.profiler"),R=Symbol.for("react.provider"),F=Symbol.for("react.context"),O=Symbol.for("react.server_context"),A=Symbol.for("react.forward_ref"),I=Symbol.for("react.suspense"),Q=Symbol.for("react.suspense_list"),$=Symbol.for("react.memo"),H=Symbol.for("react.lazy"),K=Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");var X=Symbol.for("react.offscreen"),G=Symbol.for("react.legacy_hidden"),J=Symbol.for("react.cache");Symbol.for("react.tracing_marker");var ee=Symbol.iterator;function Da(n){return null===n||"object"!=typeof n?null:"function"==typeof(n=ee&&n[ee]||n["@@iterator"])?n:null}var et=ka(null),en=ka(null),er=ka(null),ea=ka(null),ei={$$typeof:F,_currentValue:null,_currentValue2:null,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};function Ja(n,a){switch(E(er,a),E(en,n),E(et,null),n=a.nodeType){case 9:case 11:a=(a=a.documentElement)&&(a=a.namespaceURI)?Ka(a):0;break;default:if(a=(n=8===n?a.parentNode:a).tagName,n=n.namespaceURI)a=La(n=Ka(n),a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}D(et),E(et,a)}function Ma(){D(et),D(en),D(er)}function Na(n){null!==n.memoizedState&&E(ea,n);var a=et.current,i=La(a,n.type);a!==i&&(E(en,n),E(et,i))}function Oa(n){en.current===n&&(D(et),D(en)),ea.current===n&&(D(ea),ei._currentValue=null)}var eu=m.unstable_scheduleCallback,es=m.unstable_cancelCallback,ed=m.unstable_shouldYield,ep=m.unstable_requestPaint,em=m.unstable_now,eb=m.unstable_getCurrentPriorityLevel,ey=m.unstable_ImmediatePriority,ev=m.unstable_UserBlockingPriority,ek=m.unstable_NormalPriority,ew=m.unstable_LowPriority,eS=m.unstable_IdlePriority,eE=null,eC=null;function bb(n){if(eC&&"function"==typeof eC.onCommitFiberRoot)try{eC.onCommitFiberRoot(eE,n,void 0,128==(128&n.current.flags))}catch(n){}}var ex=Math.clz32?Math.clz32:cb,ez=Math.log,eP=Math.LN2;function cb(n){return 0==(n>>>=0)?32:31-(ez(n)/eP|0)|0}var eN=128,eT=4194304;function ib(n){switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194176&n;case 4194304:case 8388608:case 16777216:case 33554432:return 62914560&n;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function jb(n,a){var i=n.pendingLanes;if(0===i)return 0;var o=0,s=n.suspendedLanes;n=n.pingedLanes;var m=134217727&i;return 0!==m?0!=(i=m&~s)?o=ib(i):0!=(n&=m)&&(o=ib(n)):0!=(i&=~s)?o=ib(i):0!==n&&(o=ib(n)),0===o?0:0!==a&&a!==o&&0==(a&s)&&((s=o&-o)>=(n=a&-a)||32===s&&0!=(4194176&n))?a:o}function kb(n,a){switch(n){case 1:case 2:case 4:case 8:return a+250;case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;default:return -1}}function lb(n,a){return n.errorRecoveryDisabledLanes&a?0:0!=(n=-536870913&n.pendingLanes)?n:536870912&n?536870912:0}function mb(){var n=eT;return 0==(62914560&(eT<<=1))&&(eT=4194304),n}function nb(n){for(var a=[],i=0;31>i;i++)a.push(n);return a}function ob(n,a){n.pendingLanes|=a,268435456!==a&&(n.suspendedLanes=0,n.pingedLanes=0)}function pb(n,a,i){var o=n.pendingLanes&~a;n.pendingLanes=a,n.suspendedLanes=0,n.pingedLanes=0,n.expiredLanes&=a,n.entangledLanes&=a,n.errorRecoveryDisabledLanes&=a,n.shellSuspendCounter=0,a=n.entanglements;for(var s=n.expirationTimes,m=n.hiddenUpdates;0<o;){var y=31-ex(o),v=1<<y;a[y]=0,s[y]=-1;var k=m[y];if(null!==k)for(m[y]=null,y=0;y<k.length;y++){var S=k[y];null!==S&&(S.lane&=-536870913)}o&=~v}0!==i&&qb(n,i,0)}function qb(n,a,i){n.pendingLanes|=a,n.suspendedLanes&=~a;var o=31-ex(a);n.entangledLanes|=a,n.entanglements[o]=1073741824|n.entanglements[o]|4194218&i}function rb(n,a){var i=n.entangledLanes|=a;for(n=n.entanglements;i;){var o=31-ex(i),s=1<<o;s&a|n[o]&a&&(n[o]|=a),i&=~s}}function sb(n,a){for(n.pendingLanes|=2,n.entangledLanes|=2;a;){var i=1<<31-ex(a);n.entanglements[1]|=i,a&=~i}}var eL=0;function tb(n,a){var i=eL;try{return eL=n,a()}finally{eL=i}}function ub(n){return 2<(n&=-n)?8<n?0!=(134217727&n)?32:268435456:8:2}var e_=Object.prototype.hasOwnProperty,eD=Math.random().toString(36).slice(2),eM="__reactFiber$"+eD,eR="__reactProps$"+eD,eF="__reactContainer$"+eD,eO="__reactEvents$"+eD,eA="__reactListeners$"+eD,eI="__reactHandles$"+eD,eU="__reactResources$"+eD,eB="__reactMarker$"+eD;function Gb(n){delete n[eM],delete n[eR],delete n[eO],delete n[eA],delete n[eI]}function Hb(n){var a=n[eM];if(a)return a;for(var i=n.parentNode;i;){if(a=i[eF]||i[eM]){if(i=a.alternate,null!==a.child||null!==i&&null!==i.child)for(n=Ib(n);null!==n;){if(i=n[eM])return i;n=Ib(n)}return a}i=(n=i).parentNode}return null}function Jb(n){if(n=n[eM]||n[eF]){var a=n.tag;if(5===a||6===a||13===a||26===a||27===a||3===a)return n}return null}function Kb(n){var a=n.tag;if(5===a||26===a||27===a||6===a)return n.stateNode;throw Error(t(33))}function Lb(n){return n[eR]||null}function Mb(n){var a=n[eU];return a||(a=n[eU]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function Nb(n){n[eB]=!0}var eW=new Set,eQ={};function Qb(n,a){Rb(n,a),Rb(n+"Capture",a)}function Rb(n,a){for(eQ[n]=a,n=0;n<a.length;n++)eW.add(a[n])}var e$=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),eV=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),eY={},eq={};function Wb(n){return!!e_.call(eq,n)||!e_.call(eY,n)&&(eV.test(n)?eq[n]=!0:(eY[n]=!0,!1))}function Xb(n,a,i){if(Wb(a)){if(null===i)n.removeAttribute(a);else{switch(typeof i){case"undefined":case"function":case"symbol":n.removeAttribute(a);return;case"boolean":var o=a.toLowerCase().slice(0,5);if("data-"!==o&&"aria-"!==o){n.removeAttribute(a);return}}n.setAttribute(a,""+i)}}}function Yb(n,a,i){if(null===i)n.removeAttribute(a);else{switch(typeof i){case"undefined":case"function":case"symbol":case"boolean":n.removeAttribute(a);return}n.setAttribute(a,""+i)}}function Zb(n,a,i,o){if(null===o)n.removeAttribute(i);else{switch(typeof o){case"undefined":case"function":case"symbol":case"boolean":n.removeAttribute(i);return}n.setAttributeNS(a,i,""+o)}}function ac(n){if(void 0===rw)try{throw Error()}catch(n){var a=n.stack.trim().match(/\n( *(at )?)/);rw=a&&a[1]||""}return"\n"+rw+n}var eH=!1;function cc(n,a){if(!n||eH)return"";eH=!0;var i=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(a){if(a=function(){throw Error()},Object.defineProperty(a.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(a,[])}catch(n){var o=n}Reflect.construct(n,[],a)}else{try{a.call()}catch(n){o=n}n.call(a.prototype)}}else{try{throw Error()}catch(n){o=n}var s=n();s&&"function"==typeof s.catch&&s.catch(function(){})}}catch(a){if(a&&o&&"string"==typeof a.stack){for(var m=a.stack.split("\n"),y=o.stack.split("\n"),v=m.length-1,k=y.length-1;1<=v&&0<=k&&m[v]!==y[k];)k--;for(;1<=v&&0<=k;v--,k--)if(m[v]!==y[k]){if(1!==v||1!==k)do if(v--,0>--k||m[v]!==y[k]){var S="\n"+m[v].replace(" at new "," at ");return n.displayName&&S.includes("<anonymous>")&&(S=S.replace("<anonymous>",n.displayName)),S}while(1<=v&&0<=k);break}}}finally{eH=!1,Error.prepareStackTrace=i}return(n=n?n.displayName||n.name:"")?ac(n):""}function dc(n){switch(n.tag){case 26:case 27:case 5:return ac(n.type);case 16:return ac("Lazy");case 13:return ac("Suspense");case 19:return ac("SuspenseList");case 0:case 2:case 15:return n=cc(n.type,!1);case 11:return n=cc(n.type.render,!1);case 1:return n=cc(n.type,!0);default:return""}}function ec(n){if(null==n)return null;if("function"==typeof n)return n.displayName||n.name||null;if("string"==typeof n)return n;switch(n){case L:return"Fragment";case j:return"Portal";case M:return"Profiler";case _:return"StrictMode";case I:return"Suspense";case Q:return"SuspenseList";case J:return"Cache"}if("object"==typeof n)switch(n.$$typeof){case F:return(n.displayName||"Context")+".Consumer";case R:return(n._context.displayName||"Context")+".Provider";case A:var a=n.render;return(n=n.displayName)||(n=""!==(n=a.displayName||a.name||"")?"ForwardRef("+n+")":"ForwardRef"),n;case $:return null!==(a=n.displayName||null)?a:ec(n.type)||"Memo";case H:a=n._payload,n=n._init;try{return ec(n(a))}catch(n){}}return null}function fc(n){var a=n.type;switch(n.tag){case 24:return"Cache";case 9:return(a.displayName||"Context")+".Consumer";case 10:return(a._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return n=(n=a.render).displayName||n.name||"",a.displayName||(""!==n?"ForwardRef("+n+")":"ForwardRef");case 7:return"Fragment";case 26:case 27:case 5:return a;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ec(a);case 8:return a===_?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof a)return a.displayName||a.name||null;if("string"==typeof a)return a}return null}function gc(n){switch(typeof n){case"boolean":case"number":case"string":case"undefined":case"object":return n;default:return""}}function hc(n){var a=n.type;return(n=n.nodeName)&&"input"===n.toLowerCase()&&("checkbox"===a||"radio"===a)}function ic(n){var a=hc(n)?"checked":"value",i=Object.getOwnPropertyDescriptor(n.constructor.prototype,a),o=""+n[a];if(!n.hasOwnProperty(a)&&void 0!==i&&"function"==typeof i.get&&"function"==typeof i.set){var s=i.get,m=i.set;return Object.defineProperty(n,a,{configurable:!0,get:function(){return s.call(this)},set:function(n){o=""+n,m.call(this,n)}}),Object.defineProperty(n,a,{enumerable:i.enumerable}),{getValue:function(){return o},setValue:function(n){o=""+n},stopTracking:function(){n._valueTracker=null,delete n[a]}}}}function jc(n){n._valueTracker||(n._valueTracker=ic(n))}function kc(n){if(!n)return!1;var a=n._valueTracker;if(!a)return!0;var i=a.getValue(),o="";return n&&(o=hc(n)?n.checked?"true":"false":n.value),(n=o)!==i&&(a.setValue(n),!0)}function lc(n){if(void 0===(n=n||("undefined"!=typeof document?document:void 0)))return null;try{return n.activeElement||n.body}catch(a){return n.body}}var eZ=/[\n"\\]/g;function nc(n){return n.replace(eZ,function(n){return"\\"+n.charCodeAt(0).toString(16)+" "})}function oc(n,a,i,o,s,m,y,v){n.name="",null!=y&&"function"!=typeof y&&"symbol"!=typeof y&&"boolean"!=typeof y?n.type=y:n.removeAttribute("type"),null!=a?"number"===y?(0===a&&""===n.value||n.value!=a)&&(n.value=""+gc(a)):n.value!==""+gc(a)&&(n.value=""+gc(a)):"submit"!==y&&"reset"!==y||n.removeAttribute("value"),null!=a?pc(n,y,gc(a)):null!=i?pc(n,y,gc(i)):null!=o&&n.removeAttribute("value"),null==s&&null!=m&&(n.defaultChecked=!!m),null!=s&&(n.checked=s&&"function"!=typeof s&&"symbol"!=typeof s),null!=v&&"function"!=typeof v&&"symbol"!=typeof v&&"boolean"!=typeof v?n.name=""+gc(v):n.removeAttribute("name")}function qc(n,a,i,o,s,m,y,v){if(null!=m&&"function"!=typeof m&&"symbol"!=typeof m&&"boolean"!=typeof m&&(n.type=m),null!=a||null!=i){if(!("submit"!==m&&"reset"!==m||null!=a))return;i=null!=i?""+gc(i):"",a=null!=a?""+gc(a):i,v||a===n.value||(n.value=a),n.defaultValue=a}o="function"!=typeof(o=null!=o?o:s)&&"symbol"!=typeof o&&!!o,n.checked=v?n.checked:!!o,n.defaultChecked=!!o,null!=y&&"function"!=typeof y&&"symbol"!=typeof y&&"boolean"!=typeof y&&(n.name=y)}function pc(n,a,i){"number"===a&&lc(n.ownerDocument)===n||n.defaultValue===""+i||(n.defaultValue=""+i)}var eK=Array.isArray;function sc(n,a,i,o){if(n=n.options,a){a={};for(var s=0;s<i.length;s++)a["$"+i[s]]=!0;for(i=0;i<n.length;i++)s=a.hasOwnProperty("$"+n[i].value),n[i].selected!==s&&(n[i].selected=s),s&&o&&(n[i].defaultSelected=!0)}else{for(s=0,i=""+gc(i),a=null;s<n.length;s++){if(n[s].value===i){n[s].selected=!0,o&&(n[s].defaultSelected=!0);return}null!==a||n[s].disabled||(a=n[s])}null!==a&&(a.selected=!0)}}function tc(n,a,i){if(null!=a&&((a=""+gc(a))!==n.value&&(n.value=a),null==i)){n.defaultValue!==a&&(n.defaultValue=a);return}n.defaultValue=null!=i?""+gc(i):""}function uc(n,a,i,o){if(null==a){if(null!=o){if(null!=i)throw Error(t(92));if(eK(o)){if(1<o.length)throw Error(t(93));o=o[0]}i=o}null==i&&(i=""),a=i}i=gc(a),n.defaultValue=i,(o=n.textContent)===i&&""!==o&&null!==o&&(n.value=o)}function wc(n,a){if("http://www.w3.org/2000/svg"!==n.namespaceURI||"innerHTML"in n)n.innerHTML=a;else{for((rS=rS||document.createElement("div")).innerHTML="<svg>"+a.valueOf().toString()+"</svg>",a=rS.firstChild;n.firstChild;)n.removeChild(n.firstChild);for(;a.firstChild;)n.appendChild(a.firstChild)}}var eX=wc;"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(eX=function(n,a){return MSApp.execUnsafeLocalFunction(function(){return wc(n,a)})});var eG=eX;function zc(n,a){if(a){var i=n.firstChild;if(i&&i===n.lastChild&&3===i.nodeType){i.nodeValue=a;return}}n.textContent=a}var eJ=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Bc(n,a,i){var o=0===a.indexOf("--");null==i||"boolean"==typeof i||""===i?o?n.setProperty(a,""):"float"===a?n.cssFloat="":n[a]="":o?n.setProperty(a,i):"number"!=typeof i||0===i||eJ.has(a)?"float"===a?n.cssFloat=i:n[a]=(""+i).trim():n[a]=i+"px"}function Cc(n,a,i){if(null!=a&&"object"!=typeof a)throw Error(t(62));if(n=n.style,null!=i){for(var o in i)!i.hasOwnProperty(o)||null!=a&&a.hasOwnProperty(o)||(0===o.indexOf("--")?n.setProperty(o,""):"float"===o?n.cssFloat="":n[o]="");for(var s in a)o=a[s],a.hasOwnProperty(s)&&i[s]!==o&&Bc(n,s,o)}else for(var m in a)a.hasOwnProperty(m)&&Bc(n,m,a[m])}function Dc(n){if(-1===n.indexOf("-"))return!1;switch(n){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var e0=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),e1=null;function Gc(n){return(n=n.target||n.srcElement||window).correspondingUseElement&&(n=n.correspondingUseElement),3===n.nodeType?n.parentNode:n}var e2=null,e3=null;function Jc(n){var a=Jb(n);if(a&&(n=a.stateNode)){var i=Lb(n);switch(n=a.stateNode,a.type){case"input":if(oc(n,i.value,i.defaultValue,i.defaultValue,i.checked,i.defaultChecked,i.type,i.name),a=i.name,"radio"===i.type&&null!=a){for(i=n;i.parentNode;)i=i.parentNode;for(i=i.querySelectorAll('input[name="'+nc(""+a)+'"][type="radio"]'),a=0;a<i.length;a++){var o=i[a];if(o!==n&&o.form===n.form){var s=Lb(o);if(!s)throw Error(t(90));oc(o,s.value,s.defaultValue,s.defaultValue,s.checked,s.defaultChecked,s.type,s.name)}}for(a=0;a<i.length;a++)(o=i[a]).form===n.form&&kc(o)}break;case"textarea":tc(n,i.value,i.defaultValue);break;case"select":null!=(a=i.value)&&sc(n,!!i.multiple,a,!1)}}}function Kc(n){e2?e3?e3.push(n):e3=[n]:e2=n}function Lc(){if(e2){var n=e2,a=e3;if(e3=e2=null,Jc(n),a)for(n=0;n<a.length;n++)Jc(a[n])}}function Mc(n){var a=n,i=n;if(n.alternate)for(;a.return;)a=a.return;else{n=a;do 0!=(4098&(a=n).flags)&&(i=a.return),n=a.return;while(n)}return 3===a.tag?i:null}function Nc(n){if(13===n.tag){var a=n.memoizedState;if(null===a&&null!==(n=n.alternate)&&(a=n.memoizedState),null!==a)return a.dehydrated}return null}function Oc(n){if(Mc(n)!==n)throw Error(t(188))}function Pc(n){var a=n.alternate;if(!a){if(null===(a=Mc(n)))throw Error(t(188));return a!==n?null:n}for(var i=n,o=a;;){var s=i.return;if(null===s)break;var m=s.alternate;if(null===m){if(null!==(o=s.return)){i=o;continue}break}if(s.child===m.child){for(m=s.child;m;){if(m===i)return Oc(s),n;if(m===o)return Oc(s),a;m=m.sibling}throw Error(t(188))}if(i.return!==o.return)i=s,o=m;else{for(var y=!1,v=s.child;v;){if(v===i){y=!0,i=s,o=m;break}if(v===o){y=!0,o=s,i=m;break}v=v.sibling}if(!y){for(v=m.child;v;){if(v===i){y=!0,i=m,o=s;break}if(v===o){y=!0,o=m,i=s;break}v=v.sibling}if(!y)throw Error(t(189))}}if(i.alternate!==o)throw Error(t(190))}if(3!==i.tag)throw Error(t(188));return i.stateNode.current===i?n:a}function Qc(n){return null!==(n=Pc(n))?Rc(n):null}function Rc(n){var a=n.tag;if(5===a||26===a||27===a||6===a)return n;for(n=n.child;null!==n;){if(null!==(a=Rc(n)))return a;n=n.sibling}return null}var e4={},e6=ka(e4),e8=ka(!1),e5=e4;function Wc(n,a){var i=n.type.contextTypes;if(!i)return e4;var o=n.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===a)return o.__reactInternalMemoizedMaskedChildContext;var s,m={};for(s in i)m[s]=a[s];return o&&((n=n.stateNode).__reactInternalMemoizedUnmaskedChildContext=a,n.__reactInternalMemoizedMaskedChildContext=m),m}function Xc(n){return null!=(n=n.childContextTypes)}function Yc(){D(e8),D(e6)}function Zc(n,a,i){if(e6.current!==e4)throw Error(t(168));E(e6,a),E(e8,i)}function $c(n,a,i){var o=n.stateNode;if(a=a.childContextTypes,"function"!=typeof o.getChildContext)return i;for(var s in o=o.getChildContext())if(!(s in a))throw Error(t(108,fc(n)||"Unknown",s));return v({},i,o)}function ad(n){return n=(n=n.stateNode)&&n.__reactInternalMemoizedMergedChildContext||e4,e5=e6.current,E(e6,n),E(e8,e8.current),!0}function bd(n,a,i){var o=n.stateNode;if(!o)throw Error(t(169));i?(n=$c(n,a,e5),o.__reactInternalMemoizedMergedChildContext=n,D(e8),D(e6),E(e6,n)):D(e8),E(e8,i)}function cd(n,a){return n===a&&(0!==n||1/n==1/a)||n!=n&&a!=a}var e7="function"==typeof Object.is?Object.is:cd,e9=[],tt=0,tn=null,tr=0,tl=[],ta=0,tu=null,ts=1,tf="";function nd(n,a){e9[tt++]=tr,e9[tt++]=tn,tn=n,tr=a}function od(n,a,i){tl[ta++]=ts,tl[ta++]=tf,tl[ta++]=tu,tu=n;var o=ts;n=tf;var s=32-ex(o)-1;o&=~(1<<s),i+=1;var m=32-ex(a)+s;if(30<m){var y=s-s%5;m=(o&(1<<y)-1).toString(32),o>>=y,s-=y,ts=1<<32-ex(a)+s|i<<s|o,tf=m+n}else ts=1<<m|i<<s|o,tf=n}function pd(n){null!==n.return&&(nd(n,1),od(n,1,0))}function qd(n){for(;n===tn;)tn=e9[--tt],e9[tt]=null,tr=e9[--tt],e9[tt]=null;for(;n===tu;)tu=tl[--ta],tl[ta]=null,tf=tl[--ta],tl[ta]=null,ts=tl[--ta],tl[ta]=null}var tp=null,th=null,ty=!1,tv=null,tw=!1;function td(n,a){var i=ud(5,null,null,0);i.elementType="DELETED",i.stateNode=a,i.return=n,null===(a=n.deletions)?(n.deletions=[i],n.flags|=16):a.push(i)}function vd(n,a){a.flags=-4097&a.flags|2}function wd(n,a){return null!==(a=xd(a,n.type,n.pendingProps,tw))&&(n.stateNode=a,tp=n,th=yd(a.firstChild),tw=!1,!0)}function zd(n,a){return null!==(a=Ad(a,n.pendingProps,tw))&&(n.stateNode=a,tp=n,th=null,!0)}function Bd(n,a){e:{var i=a;for(a=tw;8!==i.nodeType;)if(!a||null===(i=Cd(i))){a=null;break e}a=i}return null!==a&&(i=null!==tu?{id:ts,overflow:tf}:null,n.memoizedState={dehydrated:a,treeContext:i,retryLane:536870912},(i=ud(18,null,null,0)).stateNode=a,i.return=n,n.child=i,tp=n,th=null,!0)}function Dd(n){return 0!=(1&n.mode)&&0==(128&n.flags)}function Ed(){throw Error(t(418))}function Fd(){if(!ty)return!1;if(th){e:{for(var n=th,a=tw;8!==n.nodeType;)if(!a||null===(n=Cd(n))){n=null;break e}n="F!"===(a=n.data)||"F"===a?n:null}if(n)return th=Cd(n),"F!"===n.data}return Ed(),!1}function Gd(n){for(tp=n.return;tp;)switch(tp.tag){case 3:case 27:tw=!0;return;case 5:case 13:tw=!1;return;default:tp=tp.return}}function Hd(n){if(n!==tp)return!1;if(!ty)return Gd(n),ty=!0,!1;var a,i=!1;if((a=3!==n.tag&&27!==n.tag)&&((a=5===n.tag)&&(a=!("form"!==(a=n.type)&&"button"!==a)||Id(n.type,n.memoizedProps)),a=!a),a&&(i=!0),i&&(i=th)){if(Dd(n))Jd(),Ed();else for(;i;)td(n,i),i=Cd(i)}if(Gd(n),13===n.tag){if(!(n=null!==(n=n.memoizedState)?n.dehydrated:null))throw Error(t(317));e:{for(i=0,n=n.nextSibling;n;){if(8===n.nodeType){if("/$"===(a=n.data)){if(0===i){th=Cd(n);break e}i--}else"$"!==a&&"$!"!==a&&"$?"!==a||i++}n=n.nextSibling}th=null}}else th=tp?Cd(n.stateNode):null;return!0}function Jd(){for(var n=th;n;)n=Cd(n)}function Kd(){th=tp=null,ty=!1}function Ld(n){null===tv?tv=[n]:tv.push(n)}var tS=[],tE=0,tC=0;function Pd(){for(var n=tE,a=tC=tE=0;a<n;){var i=tS[a];tS[a++]=null;var o=tS[a];tS[a++]=null;var s=tS[a];tS[a++]=null;var m=tS[a];if(tS[a++]=null,null!==o&&null!==s){var y=o.pending;null===y?s.next=s:(s.next=y.next,y.next=s),o.pending=s}0!==m&&Qd(i,s,m)}}function Rd(n,a,i,o){tS[tE++]=n,tS[tE++]=a,tS[tE++]=i,tS[tE++]=o,tC|=o,n.lanes|=o,null!==(n=n.alternate)&&(n.lanes|=o)}function Sd(n,a,i,o){return Rd(n,a,i,o),Td(n)}function Ud(n,a){return Rd(n,null,null,a),Td(n)}function Qd(n,a,i){n.lanes|=i;var o=n.alternate;null!==o&&(o.lanes|=i);for(var s=!1,m=n.return;null!==m;)m.childLanes|=i,null!==(o=m.alternate)&&(o.childLanes|=i),22===m.tag&&(null===(n=m.stateNode)||1&n._visibility||(s=!0)),n=m,m=m.return;s&&null!==a&&3===n.tag&&(m=n.stateNode,s=31-ex(i),null===(n=(m=m.hiddenUpdates)[s])?m[s]=[a]:n.push(a),a.lane=536870912|i)}function Td(n){if(50<rp)throw rp=0,rh=null,Error(t(185));for(var a=n.return;null!==a;)a=(n=a).return;return 3===n.tag?n.stateNode:null}var tx=!1;function Yd(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Zd(n,a){n=n.updateQueue,a.updateQueue===n&&(a.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function $d(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function ae(n,a,i){var o=n.updateQueue;if(null===o)return null;if(o=o.shared,0!=(2&nq)){var s=o.pending;return null===s?a.next=a:(a.next=s.next,s.next=a),o.pending=a,a=Td(n),Qd(n,null,i),a}return Rd(n,o,a,i),Td(n)}function be(n,a,i){if(null!==(a=a.updateQueue)&&(a=a.shared,0!=(4194176&i))){var o=a.lanes;o&=n.pendingLanes,i|=o,a.lanes=i,rb(n,i)}}function ce(n,a){var i=n.updateQueue,o=n.alternate;if(null!==o&&i===(o=o.updateQueue)){var s=null,m=null;if(null!==(i=i.firstBaseUpdate)){do{var y={lane:i.lane,tag:i.tag,payload:i.payload,callback:null,next:null};null===m?s=m=y:m=m.next=y,i=i.next}while(null!==i);null===m?s=m=a:m=m.next=a}else s=m=a;i={baseState:o.baseState,firstBaseUpdate:s,lastBaseUpdate:m,shared:o.shared,callbacks:o.callbacks},n.updateQueue=i;return}null===(n=i.lastBaseUpdate)?i.firstBaseUpdate=a:n.next=a,i.lastBaseUpdate=a}function de(n,a,i,o){var s=n.updateQueue;tx=!1;var m=s.firstBaseUpdate,y=s.lastBaseUpdate,k=s.shared.pending;if(null!==k){s.shared.pending=null;var S=k,C=S.next;S.next=null,null===y?m=C:y.next=C,y=S;var x=n.alternate;null!==x&&(k=(x=x.updateQueue).lastBaseUpdate)!==y&&(null===k?x.firstBaseUpdate=C:k.next=C,x.lastBaseUpdate=S)}if(null!==m){var P=s.baseState;for(y=0,x=C=S=null,k=m;;){var N=-536870913&k.lane,j=N!==k.lane;if(j?(nK&N)===N:(o&N)===N){null!==x&&(x=x.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var L=n,_=k;switch(N=a,_.tag){case 1:if("function"==typeof(L=_.payload)){P=L.call(i,P,N);break e}P=L;break e;case 3:L.flags=-65537&L.flags|128;case 0:if(null==(N="function"==typeof(L=_.payload)?L.call(i,P,N):L))break e;P=v({},P,N);break e;case 2:tx=!0}}null!==(N=k.callback)&&(n.flags|=64,j&&(n.flags|=8192),null===(j=s.callbacks)?s.callbacks=[N]:j.push(N))}else j={lane:N,tag:k.tag,payload:k.payload,callback:k.callback,next:null},null===x?(C=x=j,S=P):x=x.next=j,y|=N;if(null===(k=k.next)){if(null===(k=s.shared.pending))break;k=(j=k).next,j.next=null,s.lastBaseUpdate=j,s.shared.pending=null}}null===x&&(S=P),s.baseState=S,s.firstBaseUpdate=C,s.lastBaseUpdate=x,null===m&&(s.shared.lanes=0),n3|=y,n.lanes=y,n.memoizedState=P}}function fe(n,a){if("function"!=typeof n)throw Error(t(191,n));n.call(a)}function ge(n,a){var i=n.callbacks;if(null!==i)for(n.callbacks=null,n=0;n<i.length;n++)fe(i[n],a)}function he(n,a){if(e7(n,a))return!0;if("object"!=typeof n||null===n||"object"!=typeof a||null===a)return!1;var i=Object.keys(n),o=Object.keys(a);if(i.length!==o.length)return!1;for(o=0;o<i.length;o++){var s=i[o];if(!e_.call(a,s)||!e7(n[s],a[s]))return!1}return!0}var tz=Error(t(460)),tP=Error(t(474)),tN={then:function(){}};function le(n){return"fulfilled"===(n=n.status)||"rejected"===n}function me(){}function ne(n,a,i){switch(void 0===(i=n[i])?n.push(a):i!==a&&(a.then(me,me),a=i),a.status){case"fulfilled":return a.value;case"rejected":if((n=a.reason)===tz)throw Error(t(483));throw n;default:if("string"==typeof a.status)a.then(me,me);else{if(null!==(n=nH)&&100<n.shellSuspendCounter)throw Error(t(482));switch((n=a).status="pending",n.then(function(n){if("pending"===a.status){var i=a;i.status="fulfilled",i.value=n}},function(n){if("pending"===a.status){var i=a;i.status="rejected",i.reason=n}}),a.status){case"fulfilled":return a.value;case"rejected":if((n=a.reason)===tz)throw Error(t(483));throw n}}throw tj=a,tz}}var tj=null;function pe(){if(null===tj)throw Error(t(459));var n=tj;return tj=null,n}var tT=null,tL=0;function se(n){var a=tL;return tL+=1,null===tT&&(tT=[]),ne(tT,n,a)}function te(n,a,i){if(null!==(n=i.ref)&&"function"!=typeof n&&"object"!=typeof n){if(i._owner){if(i=i._owner){if(1!==i.tag)throw Error(t(309));var o=i.stateNode}if(!o)throw Error(t(147,n));var s=o,m=""+n;return null!==a&&null!==a.ref&&"function"==typeof a.ref&&a.ref._stringRef===m?a.ref:((a=function(n){var a=s.refs;null===n?delete a[m]:a[m]=n})._stringRef=m,a)}if("string"!=typeof n)throw Error(t(284));if(!i._owner)throw Error(t(290,n))}return n}function ue(n,a){throw Error(t(31,"[object Object]"===(n=Object.prototype.toString.call(a))?"object with keys {"+Object.keys(a).join(", ")+"}":n))}function ve(n){return(0,n._init)(n._payload)}function we(n){function b(a,i){if(n){var o=a.deletions;null===o?(a.deletions=[i],a.flags|=16):o.push(i)}}function c(a,i){if(!n)return null;for(;null!==i;)b(a,i),i=i.sibling;return null}function d(n,a){for(n=new Map;null!==a;)null!==a.key?n.set(a.key,a):n.set(a.index,a),a=a.sibling;return n}function e(n,a){return(n=xe(n,a)).index=0,n.sibling=null,n}function f(a,i,o){return(a.index=o,n)?null!==(o=a.alternate)?(o=o.index)<i?(a.flags|=33554434,i):o:(a.flags|=33554434,i):(a.flags|=1048576,i)}function g(a){return n&&null===a.alternate&&(a.flags|=33554434),a}function h(n,a,i,o){return null===a||6!==a.tag?(a=ye(i,n.mode,o)).return=n:(a=e(a,i)).return=n,a}function l(n,a,i,o){var s=i.type;return s===L?q(n,a,i.props.children,o,i.key):(null!==a&&(a.elementType===s||"object"==typeof s&&null!==s&&s.$$typeof===H&&ve(s)===a.type)?(o=e(a,i.props)).ref=te(n,a,i):(o=ze(i.type,i.key,i.props,null,null,n.mode,o)).ref=te(n,a,i),o.return=n,o)}function p(n,a,i,o){return null===a||4!==a.tag||a.stateNode.containerInfo!==i.containerInfo||a.stateNode.implementation!==i.implementation?(a=Ae(i,n.mode,o)).return=n:(a=e(a,i.children||[])).return=n,a}function q(n,a,i,o,s){return null===a||7!==a.tag?(a=Be(i,n.mode,o,s)).return=n:(a=e(a,i)).return=n,a}function w(n,a,i){if("string"==typeof a&&""!==a||"number"==typeof a)return(a=ye(""+a,n.mode,i)).return=n,a;if("object"==typeof a&&null!==a){switch(a.$$typeof){case N:return(i=ze(a.type,a.key,a.props,null,null,n.mode,i)).ref=te(n,null,a),i.return=n,i;case j:return(a=Ae(a,n.mode,i)).return=n,a;case H:return w(n,(0,a._init)(a._payload),i)}if(eK(a)||Da(a))return(a=Be(a,n.mode,i,null)).return=n,a;if("function"==typeof a.then)return w(n,se(a),i);if(a.$$typeof===F||a.$$typeof===O)return w(n,Ce(n,a,i),i);ue(n,a)}return null}function r(n,a,i,o){var s=null!==a?a.key:null;if("string"==typeof i&&""!==i||"number"==typeof i)return null!==s?null:h(n,a,""+i,o);if("object"==typeof i&&null!==i){switch(i.$$typeof){case N:return i.key===s?l(n,a,i,o):null;case j:return i.key===s?p(n,a,i,o):null;case H:return r(n,a,(s=i._init)(i._payload),o)}if(eK(i)||Da(i))return null!==s?null:q(n,a,i,o,null);if("function"==typeof i.then)return r(n,a,se(i),o);if(i.$$typeof===F||i.$$typeof===O)return r(n,a,Ce(n,i,o),o);ue(n,i)}return null}function u(n,a,i,o,s){if("string"==typeof o&&""!==o||"number"==typeof o)return h(a,n=n.get(i)||null,""+o,s);if("object"==typeof o&&null!==o){switch(o.$$typeof){case N:return l(a,n=n.get(null===o.key?i:o.key)||null,o,s);case j:return p(a,n=n.get(null===o.key?i:o.key)||null,o,s);case H:return u(n,a,i,(0,o._init)(o._payload),s)}if(eK(o)||Da(o))return q(a,n=n.get(i)||null,o,s,null);if("function"==typeof o.then)return u(n,a,i,se(o),s);if(o.$$typeof===F||o.$$typeof===O)return u(n,a,i,Ce(a,o,s),s);ue(a,o)}return null}function z(a,i,o,s){for(var m=null,y=null,v=i,k=i=0,S=null;null!==v&&k<o.length;k++){v.index>k?(S=v,v=null):S=v.sibling;var C=r(a,v,o[k],s);if(null===C){null===v&&(v=S);break}n&&v&&null===C.alternate&&b(a,v),i=f(C,i,k),null===y?m=C:y.sibling=C,y=C,v=S}if(k===o.length)return c(a,v),ty&&nd(a,k),m;if(null===v){for(;k<o.length;k++)null!==(v=w(a,o[k],s))&&(i=f(v,i,k),null===y?m=v:y.sibling=v,y=v);return ty&&nd(a,k),m}for(v=d(a,v);k<o.length;k++)null!==(S=u(v,a,k,o[k],s))&&(n&&null!==S.alternate&&v.delete(null===S.key?k:S.key),i=f(S,i,k),null===y?m=S:y.sibling=S,y=S);return n&&v.forEach(function(n){return b(a,n)}),ty&&nd(a,k),m}function B(a,i,o,s){var m=Da(o);if("function"!=typeof m)throw Error(t(150));if(null==(o=m.call(o)))throw Error(t(151));for(var y=m=null,v=i,k=i=0,S=null,C=o.next();null!==v&&!C.done;k++,C=o.next()){v.index>k?(S=v,v=null):S=v.sibling;var x=r(a,v,C.value,s);if(null===x){null===v&&(v=S);break}n&&v&&null===x.alternate&&b(a,v),i=f(x,i,k),null===y?m=x:y.sibling=x,y=x,v=S}if(C.done)return c(a,v),ty&&nd(a,k),m;if(null===v){for(;!C.done;k++,C=o.next())null!==(C=w(a,C.value,s))&&(i=f(C,i,k),null===y?m=C:y.sibling=C,y=C);return ty&&nd(a,k),m}for(v=d(a,v);!C.done;k++,C=o.next())null!==(C=u(v,a,k,C.value,s))&&(n&&null!==C.alternate&&v.delete(null===C.key?k:C.key),i=f(C,i,k),null===y?m=C:y.sibling=C,y=C);return n&&v.forEach(function(n){return b(a,n)}),ty&&nd(a,k),m}function U(n,a,i,o){if("object"==typeof i&&null!==i&&i.type===L&&null===i.key&&(i=i.props.children),"object"==typeof i&&null!==i){switch(i.$$typeof){case N:e:{for(var s=i.key,m=a;null!==m;){if(m.key===s){if((s=i.type)===L){if(7===m.tag){c(n,m.sibling),(a=e(m,i.props.children)).return=n,n=a;break e}}else if(m.elementType===s||"object"==typeof s&&null!==s&&s.$$typeof===H&&ve(s)===m.type){c(n,m.sibling),(a=e(m,i.props)).ref=te(n,m,i),a.return=n,n=a;break e}c(n,m);break}b(n,m),m=m.sibling}i.type===L?((a=Be(i.props.children,n.mode,o,i.key)).return=n,n=a):((o=ze(i.type,i.key,i.props,null,null,n.mode,o)).ref=te(n,a,i),o.return=n,n=o)}return g(n);case j:e:{for(m=i.key;null!==a;){if(a.key===m){if(4===a.tag&&a.stateNode.containerInfo===i.containerInfo&&a.stateNode.implementation===i.implementation){c(n,a.sibling),(a=e(a,i.children||[])).return=n,n=a;break e}c(n,a);break}b(n,a),a=a.sibling}(a=Ae(i,n.mode,o)).return=n,n=a}return g(n);case H:return V(n,a,(m=i._init)(i._payload),o)}if(eK(i))return z(n,a,i,o);if(Da(i))return B(n,a,i,o);if("function"==typeof i.then)return U(n,a,se(i),o);if(i.$$typeof===F||i.$$typeof===O)return U(n,a,Ce(n,i,o),o);ue(n,i)}return"string"==typeof i&&""!==i||"number"==typeof i?(i=""+i,null!==a&&6===a.tag?(c(n,a.sibling),(a=e(a,i)).return=n):(c(n,a),(a=ye(i,n.mode,o)).return=n),g(n=a)):c(n,a)}function V(n,a,i,o){return tL=0,n=U(n,a,i,o),tT=null,n}return V}var t_=we(!0),tD=we(!1),tM=ka(null),tR=ka(0);function He(n,a){E(tR,n=n0),E(tM,a),n0=n|a.baseLanes}function Je(){E(tR,n0),E(tM,tM.current)}function Ke(){n0=tR.current,D(tM),D(tR)}var tF=ka(null),tO=null;function Ne(n){var a=n.alternate;E(tA,1&tA.current),E(tF,n),null===tO&&(null===a||null!==tM.current?tO=n:null!==a.memoizedState&&(tO=n))}function Pe(n){if(22===n.tag){if(E(tA,tA.current),E(tF,n),null===tO){var a=n.alternate;null!==a&&null!==a.memoizedState&&(tO=n)}}else Qe(n)}function Qe(){E(tA,tA.current),E(tF,tF.current)}function Re(n){D(tF),tO===n&&(tO=null),D(tA)}var tA=ka(0);function Se(n){for(var a=n;null!==a;){if(13===a.tag){var i=a.memoizedState;if(null!==i&&(null===(i=i.dehydrated)||"$?"===i.data||"$!"===i.data))return a}else if(19===a.tag&&void 0!==a.memoizedProps.revealOrder){if(0!=(128&a.flags))return a}else if(null!==a.child){a.child.return=a,a=a.child;continue}if(a===n)break;for(;null===a.sibling;){if(null===a.return||a.return===n)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var tI=null,tU=null,tB=!1,tW=!1,tQ=!1,t$=0;function Ze(n){n!==tU&&null===n.next&&(null===tU?tI=tU=n:tU=tU.next=n),tW=!0,tB||(tB=!0,$e(af))}function bf(n){if(!tQ&&tW){var a=null;tQ=!0;do for(var i=!1,o=tI;null!==o;){if(!n||0===o.tag){var s=nK,m=jb(o,o===nH?s:0);if(0!=(3&m))try{if(i=!0,s=o,0!=(6&nq))throw Error(t(327));if(!cf()){var y=df(s,m);if(0!==s.tag&&2===y){var v=m,k=lb(s,v);0!==k&&(m=k,y=ef(s,v,k))}if(1===y)throw v=n2,gf(s,0),hf(s,m,0),Ze(s),v;6===y?hf(s,m,0):(s.finishedWork=s.current.alternate,s.finishedLanes=m,jf(s,n7,rt,n8))}Ze(s)}catch(n){null===a?a=[n]:a.push(n)}}o=o.next}while(i);if(tQ=!1,null!==a){if(1<a.length){if("function"==typeof AggregateError)throw AggregateError(a);for(n=1;n<a.length;n++)$e(nf.bind(null,a[n]))}throw a[0]}}}function nf(n){throw n}function af(){tW=tB=!1;for(var n=em(),a=null,i=tI;null!==i;){var o=i.next;if(0!==t$&&of()){var s=i,m=t$;s.pendingLanes|=2,s.entangledLanes|=2,s.entanglements[1]|=m}0===(s=pf(i,n))?(i.next=null,null===a?tI=o:a.next=o,null===o&&(tU=a)):(a=i,0!=(3&s)&&(tW=!0)),i=o}t$=0,bf(!1)}function pf(n,a){for(var i=n.suspendedLanes,o=n.pingedLanes,s=n.expirationTimes,m=-62914561&n.pendingLanes;0<m;){var y=31-ex(m),v=1<<y,k=s[y];-1===k?(0==(v&i)||0!=(v&o))&&(s[y]=kb(v,a)):k<=a&&(n.expiredLanes|=v),m&=~v}if(a=nH,i=nK,i=jb(n,n===a?i:0),o=n.callbackNode,0===i||n===a&&2===nX||null!==n.cancelPendingCommit)return null!==o&&null!==o&&es(o),n.callbackNode=null,n.callbackPriority=0;if(0!=(3&i))return null!==o&&null!==o&&es(o),n.callbackPriority=2,n.callbackNode=null,2;if((a=i&-i)===n.callbackPriority)return a;switch(null!==o&&es(o),ub(i)){case 2:i=ey;break;case 8:i=ev;break;case 32:default:i=ek;break;case 268435456:i=eS}return i=eu(i,o=qf.bind(null,n)),n.callbackPriority=a,n.callbackNode=i,a}function $e(n){lq(function(){0!=(6&nq)?eu(ey,n):n()})}function sf(){if(0===t$){var n=eN;0==(4194176&(eN<<=1))&&(eN=128),t$=n}return t$}var tV=null,tY=0,tq=0;function wf(n,a){if(null===tV){var i=tV=[];tY=0,tq=sf()}else i=tV;tY++;var o,s,m=xf(i),y="pending";return n.then(function(n){y="fulfilled",o=null!==a?a:n,yf()},function(n){y="rejected",s=n,yf()}),i.push(function(){switch(y){case"fulfilled":m.status="fulfilled",m.value=o;break;case"rejected":m.status="rejected",m.reason=s;break;default:throw Error(t(478))}}),m}function zf(n,a){var i=null!==a?a:n;if(null===tV)return i;var o=xf(n=tV);return n.push(function(){o.status="fulfilled",o.value=i}),o}function yf(){if(null!==tV&&0==--tY){var n=tV;tV=null;for(var a=tq=0;a<n.length;a++)(0,n[a])()}}function xf(n){return{status:"pending",value:null,reason:null,then:function(a){n.push(a)}}}var tH=k.ReactCurrentDispatcher,tZ=k.ReactCurrentBatchConfig,tK=0,tX=null,tG=null,tJ=null,t0=!1,t1=!1,t2=!1,t3=0,t4=0,t6=null,t8=0;function Kf(){throw Error(t(321))}function Lf(n,a){if(null===a)return!1;for(var i=0;i<a.length&&i<n.length;i++)if(!e7(n[i],a[i]))return!1;return!0}function Mf(n,a,i,o,s,m){return tK=m,tX=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,tH.current=null===n||null===n.memoizedState?t7:t9,t2=!1,n=i(o,s),t2=!1,t1&&(n=Pf(a,i,o,s)),Qf(),n}function Qf(){tH.current=t5;var n=null!==tG&&null!==tG.next;if(tK=0,tJ=tG=tX=null,t0=!1,t4=0,t6=null,n)throw Error(t(300))}function Pf(n,a,i,o){tX=n;var s=0;do{if(t1&&(t6=null),t4=0,t1=!1,25<=s)throw Error(t(301));s+=1,tJ=tG=null,n.updateQueue=null,tH.current=nt;var m=a(i,o)}while(t1);return m}function Tf(){var n=tH.current.useState()[0];return"function"==typeof n.then?Uf(n):n}function Vf(){var n=0!==t3;return t3=0,n}function Wf(n,a,i){a.updateQueue=n.updateQueue,a.flags&=-2053,n.lanes&=~i}function Xf(n){if(t0){for(n=n.memoizedState;null!==n;){var a=n.queue;null!==a&&(a.pending=null),n=n.next}t0=!1}tK=0,tJ=tG=tX=null,t1=!1,t4=t3=0,t6=null}function Yf(){var n={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===tJ?tX.memoizedState=tJ=n:tJ=tJ.next=n,tJ}function Zf(){if(null===tG){var n=tX.alternate;n=null!==n?n.memoizedState:null}else n=tG.next;var a=null===tJ?tX.memoizedState:tJ.next;if(null!==a)tJ=a,tG=n;else{if(null===n){if(null===tX.alternate)throw Error(t(467));throw Error(t(310))}n={memoizedState:(tG=n).memoizedState,baseState:tG.baseState,baseQueue:tG.baseQueue,queue:tG.queue,next:null},null===tJ?tX.memoizedState=tJ=n:tJ=tJ.next=n}return tJ}function Uf(n){var a=t4;return t4+=1,null===t6&&(t6=[]),n=ne(t6,n,a),null===tX.alternate&&(null===tJ?null===tX.memoizedState:null===tJ.next)&&(tH.current=t7),n}function ag(n){if(null!==n&&"object"==typeof n){if("function"==typeof n.then)return Uf(n);if(n.$$typeof===F||n.$$typeof===O)return bg(n)}throw Error(t(438,String(n)))}function cg(n,a){return"function"==typeof a?a(n):a}function dg(n){return eg(Zf(),tG,n)}function eg(n,a,i){var o=n.queue;if(null===o)throw Error(t(311));o.lastRenderedReducer=i;var s=n.baseQueue,m=o.pending;if(null!==m){if(null!==s){var y=s.next;s.next=m.next,m.next=y}a.baseQueue=s=m,o.pending=null}if(null!==s){a=s.next,m=n.baseState;var v=y=null,k=null,S=a;do{var C=-536870913&S.lane;if(C!==S.lane?(nK&C)===C:(tK&C)===C){if(0===(C=S.revertLane))null!==k&&(k=k.next={lane:0,revertLane:0,action:S.action,hasEagerState:S.hasEagerState,eagerState:S.eagerState,next:null});else if((tK&C)===C){S=S.next;continue}else{var x={lane:0,revertLane:S.revertLane,action:S.action,hasEagerState:S.hasEagerState,eagerState:S.eagerState,next:null};null===k?(v=k=x,y=m):k=k.next=x,tX.lanes|=C,n3|=C}C=S.action,t2&&i(m,C),m=S.hasEagerState?S.eagerState:i(m,C)}else x={lane:C,revertLane:S.revertLane,action:S.action,hasEagerState:S.hasEagerState,eagerState:S.eagerState,next:null},null===k?(v=k=x,y=m):k=k.next=x,tX.lanes|=C,n3|=C;S=S.next}while(null!==S&&S!==a);null===k?y=m:k.next=v,e7(m,n.memoizedState)||(ni=!0),n.memoizedState=m,n.baseState=y,n.baseQueue=k,o.lastRenderedState=m}return null===s&&(o.lanes=0),[n.memoizedState,o.dispatch]}function gg(n){var a=Zf(),i=a.queue;if(null===i)throw Error(t(311));i.lastRenderedReducer=n;var o=i.dispatch,s=i.pending,m=a.memoizedState;if(null!==s){i.pending=null;var y=s=s.next;do m=n(m,y.action),y=y.next;while(y!==s);e7(m,a.memoizedState)||(ni=!0),a.memoizedState=m,null===a.baseQueue&&(a.baseState=m),i.lastRenderedState=m}return[m,o]}function hg(n,a,i){var o=tX,s=Zf(),m=ty;if(m){if(void 0===i)throw Error(t(407));i=i()}else i=a();var y=!e7((tG||s).memoizedState,i);if(y&&(s.memoizedState=i,ni=!0),s=s.queue,ig(jg.bind(null,o,s,n),[n]),s.getSnapshot!==a||y||null!==tJ&&1&tJ.memoizedState.tag){if(o.flags|=2048,kg(9,lg.bind(null,o,s,i,a),{destroy:void 0},null),null===nH)throw Error(t(349));m||0!=(60&tK)||mg(o,a,i)}return i}function mg(n,a,i){n.flags|=16384,n={getSnapshot:a,value:i},null===(a=tX.updateQueue)?(a=rE(),tX.updateQueue=a,a.stores=[n]):null===(i=a.stores)?a.stores=[n]:i.push(n)}function lg(n,a,i,o){a.value=i,a.getSnapshot=o,ng(a)&&og(n)}function jg(n,a,i){return i(function(){ng(a)&&og(n)})}function ng(n){var a=n.getSnapshot;n=n.value;try{var i=a();return!e7(n,i)}catch(n){return!0}}function og(n){var a=Ud(n,2);null!==a&&pg(a,n,2)}function qg(n){var a=Yf();return"function"==typeof n&&(n=n()),a.memoizedState=a.baseState=n,a.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:cg,lastRenderedState:n},a}function rg(n,a,i,o){return n.baseState=i,eg(n,tG,"function"==typeof o?o:cg)}function sg(n,a,i,o){if(tg(n))throw Error(t(485));null===(n=a.pending)?((n={payload:o,next:null}).next=a.pending=n,ug(a,i,o)):a.pending=n.next={payload:o,next:n.next}}function ug(n,a,i){var o=n.action,s=n.state,m=tZ.transition;tZ.transition={};try{var y=o(s,i);y.then(function(i){n.state=i,vg(n,a)},function(){return vg(n,a)});var v=wf(y,null);a(v)}finally{tZ.transition=m}}function vg(n,a){var i=n.pending;if(null!==i){var o=i.next;o===i?n.pending=null:(o=o.next,i.next=o,ug(n,a,o.payload))}}function wg(n,a){return a}function xg(n,a,i){n=Uf(n=eg(n,a,wg)[0]);var o=(a=Zf()).queue,s=o.dispatch;return i!==a.memoizedState&&(tX.flags|=2048,kg(9,yg.bind(null,o,i),{destroy:void 0},null)),[n,s]}function yg(n,a){n.action=a}function kg(n,a,i,o){return n={tag:n,create:a,inst:i,deps:o,next:null},null===(a=tX.updateQueue)?(a=rE(),tX.updateQueue=a,a.lastEffect=n.next=n):null===(i=a.lastEffect)?a.lastEffect=n.next=n:(o=i.next,i.next=n,n.next=o,a.lastEffect=n),n}function zg(){return Zf().memoizedState}function Ag(n,a,i,o){var s=Yf();tX.flags|=n,s.memoizedState=kg(1|a,i,{destroy:void 0},void 0===o?null:o)}function Bg(n,a,i,o){var s=Zf();o=void 0===o?null:o;var m=s.memoizedState.inst;null!==tG&&null!==o&&Lf(o,tG.memoizedState.deps)?s.memoizedState=kg(a,i,m,o):(tX.flags|=n,s.memoizedState=kg(1|a,i,m,o))}function Cg(n,a){Ag(8390656,8,n,a)}function ig(n,a){Bg(2048,8,n,a)}function Dg(n,a){return Bg(4,2,n,a)}function Eg(n,a){return Bg(4,4,n,a)}function Fg(n,a){return"function"==typeof a?(a(n=n()),function(){a(null)}):null!=a?(n=n(),a.current=n,function(){a.current=null}):void 0}function Gg(n,a,i){i=null!=i?i.concat([n]):null,Bg(4,4,Fg.bind(null,a,n),i)}function Hg(){}function Ig(n,a){var i=Zf();a=void 0===a?null:a;var o=i.memoizedState;return null!==a&&Lf(a,o[1])?o[0]:(i.memoizedState=[n,a],n)}function Jg(n,a){var i=Zf();a=void 0===a?null:a;var o=i.memoizedState;return null!==a&&Lf(a,o[1])?o[0]:(t2&&n(),n=n(),i.memoizedState=[n,a],n)}function Kg(n,a,i){return e7(i,a)?i:null!==tM.current?(n.memoizedState=i,e7(i,a)||(ni=!0),i):0==(42&tK)?(ni=!0,n.memoizedState=i):(0===n8&&(n8=0==(536870912&nK)||ty?sf():536870912),n=n8,tX.lanes|=n,n3|=n,a)}function Lg(n,a,i,o,s){var m=eL;eL=0!==m&&8>m?m:8;var y=tZ.transition;tZ.transition={},Mg(n,!1,a,i);try{var v=s();if(null!==v&&"object"==typeof v&&"function"==typeof v.then){var k=wf(v,o);Ng(n,a,k)}else{var S=zf(v,o);Ng(n,a,S)}}catch(i){Ng(n,a,{then:function(){},status:"rejected",reason:i})}finally{eL=m,tZ.transition=y}}function Og(n,a,i,o){if(5!==n.tag)throw Error(t(476));if(null===n.memoizedState){var s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:cg,lastRenderedState:C},m=s;s={memoizedState:C,baseState:C,baseQueue:null,queue:s,next:null},n.memoizedState=s;var y=n.alternate;null!==y&&(y.memoizedState=s)}else m=n.memoizedState.queue;Lg(n,m,a,C,function(){return i(o)})}function Pg(){var n=bg(ei);return null!==n?n:C}function Qg(){return Zf().memoizedState}function Rg(){return Zf().memoizedState}function Sg(n){for(var a=n.return;null!==a;){switch(a.tag){case 24:case 3:var i=Tg(a),o=ae(a,n=$d(i),i);null!==o&&(pg(o,a,i),be(o,a,i)),a={cache:Ug()},n.payload=a;return}a=a.return}}function Vg(n,a,i){var o=Tg(n);i={lane:o,revertLane:0,action:i,hasEagerState:!1,eagerState:null,next:null},tg(n)?Wg(a,i):null!==(i=Sd(n,a,i,o))&&(pg(i,n,o),Xg(i,a,o))}function Ng(n,a,i){var o=Tg(n),s={lane:o,revertLane:0,action:i,hasEagerState:!1,eagerState:null,next:null};if(tg(n))Wg(a,s);else{var m=n.alternate;if(0===n.lanes&&(null===m||0===m.lanes)&&null!==(m=a.lastRenderedReducer))try{var y=a.lastRenderedState,v=m(y,i);if(s.hasEagerState=!0,s.eagerState=v,e7(v,y)){Rd(n,a,s,0),null===nH&&Pd();return}}catch(n){}finally{}null!==(i=Sd(n,a,s,o))&&(pg(i,n,o),Xg(i,a,o))}}function Mg(n,a,i,o){if(o={lane:2,revertLane:sf(),action:o,hasEagerState:!1,eagerState:null,next:null},tg(n)){if(a)throw Error(t(479))}else null!==(a=Sd(n,i,o,2))&&pg(a,n,2)}function tg(n){var a=n.alternate;return n===tX||null!==a&&a===tX}function Wg(n,a){t1=t0=!0;var i=n.pending;null===i?a.next=a:(a.next=i.next,i.next=a),n.pending=a}function Xg(n,a,i){if(0!=(4194176&i)){var o=a.lanes;o&=n.pendingLanes,i|=o,a.lanes=i,rb(n,i)}}rE=function(){return{lastEffect:null,events:null,stores:null}};var t5={readContext:bg,use:ag,useCallback:Kf,useContext:Kf,useEffect:Kf,useImperativeHandle:Kf,useInsertionEffect:Kf,useLayoutEffect:Kf,useMemo:Kf,useReducer:Kf,useRef:Kf,useState:Kf,useDebugValue:Kf,useDeferredValue:Kf,useTransition:Kf,useSyncExternalStore:Kf,useId:Kf};t5.useCacheRefresh=Kf,t5.useHostTransitionStatus=Kf,t5.useFormState=Kf,t5.useOptimistic=Kf;var t7={readContext:bg,use:ag,useCallback:function(n,a){return Yf().memoizedState=[n,void 0===a?null:a],n},useContext:bg,useEffect:Cg,useImperativeHandle:function(n,a,i){i=null!=i?i.concat([n]):null,Ag(4194308,4,Fg.bind(null,a,n),i)},useLayoutEffect:function(n,a){return Ag(4194308,4,n,a)},useInsertionEffect:function(n,a){Ag(4,2,n,a)},useMemo:function(n,a){var i=Yf();return a=void 0===a?null:a,t2&&n(),n=n(),i.memoizedState=[n,a],n},useReducer:function(n,a,i){var o=Yf();return a=void 0!==i?i(a):a,o.memoizedState=o.baseState=a,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:a},o.queue=n,n=n.dispatch=Vg.bind(null,tX,n),[o.memoizedState,n]},useRef:function(n){return n={current:n},Yf().memoizedState=n},useState:function(n){var a=(n=qg(n)).queue,i=Ng.bind(null,tX,a);return a.dispatch=i,[n.memoizedState,i]},useDebugValue:Hg,useDeferredValue:function(n){return Yf().memoizedState=n,n},useTransition:function(){var n=qg(!1);return n=Lg.bind(null,tX,n.queue,!0,!1),Yf().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,a,i){var o=tX,s=Yf();if(ty){if(void 0===i)throw Error(t(407));i=i()}else{if(i=a(),null===nH)throw Error(t(349));0!=(60&nK)||mg(o,a,i)}s.memoizedState=i;var m={value:i,getSnapshot:a};return s.queue=m,Cg(jg.bind(null,o,m,n),[n]),o.flags|=2048,kg(9,lg.bind(null,o,m,i,a),{destroy:void 0},null),i},useId:function(){var n=Yf(),a=nH.identifierPrefix;if(ty){var i=tf,o=ts;a=":"+a+"R"+(i=(o&~(1<<32-ex(o)-1)).toString(32)+i),0<(i=t3++)&&(a+="H"+i.toString(32)),a+=":"}else a=":"+a+"r"+(i=t8++).toString(32)+":";return n.memoizedState=a},useCacheRefresh:function(){return Yf().memoizedState=Sg.bind(null,tX)}};t7.useHostTransitionStatus=Pg,t7.useFormState=function(n,a){if(ty){var i=nH.formState;null!==i&&Fd()&&(a=i[0])}var o={status:"fulfilled",value:a,then:function(){}};(i=Yf()).memoizedState=i.baseState=o,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:wg,lastRenderedState:o},i.queue=o,i=Ng.bind(null,tX,o),o.dispatch=i;var s={state:a,dispatch:null,action:n,pending:null};return(o=Yf()).queue=s,i=sg.bind(null,tX,s,i),s.dispatch=i,o.memoizedState=n,[a,i]},t7.useOptimistic=function(n){var a=Yf();a.memoizedState=a.baseState=n;var i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return a.queue=i,a=Mg.bind(null,tX,!0,i),i.dispatch=a,[n,a]};var t9={readContext:bg,use:ag,useCallback:Ig,useContext:bg,useEffect:ig,useImperativeHandle:Gg,useInsertionEffect:Dg,useLayoutEffect:Eg,useMemo:Jg,useReducer:dg,useRef:zg,useState:function(){return dg(cg)},useDebugValue:Hg,useDeferredValue:function(n){return Kg(Zf(),tG.memoizedState,n)},useTransition:function(){var n=dg(cg)[0],a=Zf().memoizedState;return["boolean"==typeof n?n:Uf(n),a]},useSyncExternalStore:hg,useId:Qg};t9.useCacheRefresh=Rg,t9.useHostTransitionStatus=Pg,t9.useFormState=function(n){return xg(Zf(),tG,n)},t9.useOptimistic=function(n,a){return rg(Zf(),tG,n,a)};var nt={readContext:bg,use:ag,useCallback:Ig,useContext:bg,useEffect:ig,useImperativeHandle:Gg,useInsertionEffect:Dg,useLayoutEffect:Eg,useMemo:Jg,useReducer:gg,useRef:zg,useState:function(){return gg(cg)},useDebugValue:Hg,useDeferredValue:function(n){var a=Zf();return null===tG?(a.memoizedState=n,n):Kg(a,tG.memoizedState,n)},useTransition:function(){var n=gg(cg)[0],a=Zf().memoizedState;return["boolean"==typeof n?n:Uf(n),a]},useSyncExternalStore:hg,useId:Qg};function Yg(n,a){if(n&&n.defaultProps)for(var i in a=v({},a),n=n.defaultProps)void 0===a[i]&&(a[i]=n[i]);return a}function Zg(n,a,i,o){i=null==(i=i(o,a=n.memoizedState))?a:v({},a,i),n.memoizedState=i,0===n.lanes&&(n.updateQueue.baseState=i)}nt.useCacheRefresh=Rg,nt.useHostTransitionStatus=Pg,nt.useFormState=function(n){var a=Zf(),i=tG;if(null!==i)return xg(a,i,n);a=Uf(a.memoizedState);var o=(i=Zf()).queue.dispatch;return i.memoizedState=n,[a,o]},nt.useOptimistic=function(n,a){var i=Zf();return null!==tG?rg(i,tG,n,a):(i.baseState=n,[n,i.queue.dispatch])};var nr={isMounted:function(n){return!!(n=n._reactInternals)&&Mc(n)===n},enqueueSetState:function(n,a,i){var o=Tg(n=n._reactInternals),s=$d(o);s.payload=a,null!=i&&(s.callback=i),null!==(a=ae(n,s,o))&&(pg(a,n,o),be(a,n,o))},enqueueReplaceState:function(n,a,i){var o=Tg(n=n._reactInternals),s=$d(o);s.tag=1,s.payload=a,null!=i&&(s.callback=i),null!==(a=ae(n,s,o))&&(pg(a,n,o),be(a,n,o))},enqueueForceUpdate:function(n,a){var i=Tg(n=n._reactInternals),o=$d(i);o.tag=2,null!=a&&(o.callback=a),null!==(a=ae(n,o,i))&&(pg(a,n,i),be(a,n,i))}};function ah(n,a,i,o,s,m,y){return"function"==typeof(n=n.stateNode).shouldComponentUpdate?n.shouldComponentUpdate(o,m,y):!a.prototype||!a.prototype.isPureReactComponent||!he(i,o)||!he(s,m)}function bh(n,a,i){var o=!1,s=e4,m=a.contextType;return"object"==typeof m&&null!==m?m=bg(m):(s=Xc(a)?e5:e6.current,m=(o=null!=(o=a.contextTypes))?Wc(n,s):e4),a=new a(i,m),n.memoizedState=null!==a.state&&void 0!==a.state?a.state:null,a.updater=nr,n.stateNode=a,a._reactInternals=n,o&&((n=n.stateNode).__reactInternalMemoizedUnmaskedChildContext=s,n.__reactInternalMemoizedMaskedChildContext=m),a}function ch(n,a,i,o){n=a.state,"function"==typeof a.componentWillReceiveProps&&a.componentWillReceiveProps(i,o),"function"==typeof a.UNSAFE_componentWillReceiveProps&&a.UNSAFE_componentWillReceiveProps(i,o),a.state!==n&&nr.enqueueReplaceState(a,a.state,null)}function dh(n,a,i,o){var s=n.stateNode;s.props=i,s.state=n.memoizedState,s.refs={},Yd(n);var m=a.contextType;"object"==typeof m&&null!==m?s.context=bg(m):(m=Xc(a)?e5:e6.current,s.context=Wc(n,m)),s.state=n.memoizedState,"function"==typeof(m=a.getDerivedStateFromProps)&&(Zg(n,a,m,i),s.state=n.memoizedState),"function"==typeof a.getDerivedStateFromProps||"function"==typeof s.getSnapshotBeforeUpdate||"function"!=typeof s.UNSAFE_componentWillMount&&"function"!=typeof s.componentWillMount||(a=s.state,"function"==typeof s.componentWillMount&&s.componentWillMount(),"function"==typeof s.UNSAFE_componentWillMount&&s.UNSAFE_componentWillMount(),a!==s.state&&nr.enqueueReplaceState(s,s.state,null),de(n,i,s,o),s.state=n.memoizedState),"function"==typeof s.componentDidMount&&(n.flags|=4194308)}function eh(n,a){try{var i="",o=a;do i+=dc(o),o=o.return;while(o);var s=i}catch(n){s="\nError generating stack: "+n.message+"\n"+n.stack}return{value:n,source:a,stack:s,digest:null}}function fh(n,a,i){return{value:n,source:null,stack:null!=i?i:null,digest:null!=a?a:null}}function gh(n,a){try{console.error(a.value)}catch(n){setTimeout(function(){throw n})}}function hh(n,a,i){(i=$d(i)).tag=3,i.payload={element:null};var o=a.value;return i.callback=function(){rn||(rn=!0,rr=o),gh(n,a)},i}function kh(n,a,i){(i=$d(i)).tag=3;var o=n.type.getDerivedStateFromError;if("function"==typeof o){var s=a.value;i.payload=function(){return o(s)},i.callback=function(){gh(n,a)}}var m=n.stateNode;return null!==m&&"function"==typeof m.componentDidCatch&&(i.callback=function(){gh(n,a),"function"!=typeof o&&(null===ra?ra=new Set([this]):ra.add(this));var i=a.stack;this.componentDidCatch(a.value,{componentStack:null!==i?i:""})}),i}function mh(n,a,i,o,s){return 0==(1&n.mode)?n===a?n.flags|=65536:(n.flags|=128,i.flags|=131072,i.flags&=-52805,1===i.tag&&(null===i.alternate?i.tag=17:((a=$d(2)).tag=2,ae(i,a,2))),i.lanes|=2):(n.flags|=65536,n.lanes=s),n}function nh(n,a,i,o,s){if(i.flags|=32768,null!==o&&"object"==typeof o&&"function"==typeof o.then){var m=i.tag;if(0!=(1&i.mode)||0!==m&&11!==m&&15!==m||((m=i.alternate)?(i.updateQueue=m.updateQueue,i.memoizedState=m.memoizedState,i.lanes=m.lanes):(i.updateQueue=null,i.memoizedState=null)),null!==(m=tF.current)){switch(m.tag){case 13:1&i.mode&&(null===tO?oh():null===m.alternate&&0===n1&&(n1=3)),m.flags&=-257,mh(m,a,i,n,s),o===tN?m.flags|=16384:(null===(a=m.updateQueue)?m.updateQueue=new Set([o]):a.add(o),1&m.mode&&qh(n,o,s));return;case 22:if(1&m.mode){m.flags|=65536,o===tN?m.flags|=16384:(null===(a=m.updateQueue)?(a={transitions:null,markerInstances:null,retryQueue:new Set([o])},m.updateQueue=a):null===(i=a.retryQueue)?a.retryQueue=new Set([o]):i.add(o),qh(n,o,s));return}}throw Error(t(435,m.tag))}if(1===n.tag){qh(n,o,s),oh();return}o=Error(t(426))}if(ty&&1&i.mode&&null!==(m=tF.current)){0==(65536&m.flags)&&(m.flags|=256),mh(m,a,i,n,s),Ld(eh(o,i));return}n=o=eh(o,i),4!==n1&&(n1=2),null===n5?n5=[n]:n5.push(n),n=a;do{switch(n.tag){case 3:n.flags|=65536,s&=-s,n.lanes|=s,s=hh(n,o,s),ce(n,s);return;case 1:if(a=o,i=n.type,m=n.stateNode,0==(128&n.flags)&&("function"==typeof i.getDerivedStateFromError||null!==m&&"function"==typeof m.componentDidCatch&&(null===ra||!ra.has(m)))){n.flags|=65536,s&=-s,n.lanes|=s,s=kh(n,a,s),ce(n,s);return}}n=n.return}while(null!==n)}var nl=k.ReactCurrentOwner,na=Error(t(461)),ni=!1;function uh(n,a,i,o){a.child=null===n?tD(a,null,i,o):t_(a,n.child,i,o)}function vh(n,a,i,o,s){i=i.render;var m=a.ref;return(wh(a,s),o=Mf(n,a,i,o,m,s),i=Vf(),null===n||ni)?(ty&&i&&pd(a),a.flags|=1,uh(n,a,o,s),a.child):(Wf(n,a,s),xh(n,a,s))}function yh(n,a,i,o,s){if(null===n){var m=i.type;return"function"!=typeof m||zh(m)||void 0!==m.defaultProps||null!==i.compare||void 0!==i.defaultProps?((n=ze(i.type,null,o,null,a,a.mode,s)).ref=a.ref,n.return=a,a.child=n):(a.tag=15,a.type=m,Ah(n,a,m,o,s))}if(m=n.child,0==(n.lanes&s)){var y=m.memoizedProps;if((i=null!==(i=i.compare)?i:he)(y,o)&&n.ref===a.ref)return xh(n,a,s)}return a.flags|=1,(n=xe(m,o)).ref=a.ref,n.return=a,a.child=n}function Ah(n,a,i,o,s){if(null!==n){var m=n.memoizedProps;if(he(m,o)&&n.ref===a.ref){if(ni=!1,a.pendingProps=o=m,0==(n.lanes&s))return a.lanes=n.lanes,xh(n,a,s);0!=(131072&n.flags)&&(ni=!0)}}return Bh(n,a,i,o,s)}function Ch(n,a,i){var o=a.pendingProps,s=o.children,m=0!=(2&a.stateNode._pendingVisibility),y=null!==n?n.memoizedState:null;if(Dh(n,a),"hidden"===o.mode||m){if(0!=(128&a.flags)){if(i=null!==y?y.baseLanes|i:i,null!==n){for(s=0,o=a.child=n.child;null!==o;)s=s|o.lanes|o.childLanes,o=o.sibling;a.childLanes=s&~i}else a.childLanes=0,a.child=null;return Eh(n,a,i)}if(0==(1&a.mode))a.memoizedState={baseLanes:0,cachePool:null},null!==n&&Fh(a,null),Je(),Pe(a);else{if(0==(536870912&i))return a.lanes=a.childLanes=536870912,Eh(n,a,null!==y?y.baseLanes|i:i);a.memoizedState={baseLanes:0,cachePool:null},null!==n&&Fh(a,null!==y?y.cachePool:null),null!==y?He(a,y):Je(),Pe(a)}}else null!==y?(Fh(a,y.cachePool),He(a,y),Qe(a),a.memoizedState=null):(null!==n&&Fh(a,null),Je(),Qe(a));return uh(n,a,s,i),a.child}function Eh(n,a,i){var o=Gh();return o=null===o?null:{parent:nE._currentValue,pool:o},a.memoizedState={baseLanes:i,cachePool:o},null!==n&&Fh(a,null),Je(),Pe(a),null}function Dh(n,a){var i=a.ref;(null===n&&null!==i||null!==n&&n.ref!==i)&&(a.flags|=512,a.flags|=2097152)}function Bh(n,a,i,o,s){var m=Xc(i)?e5:e6.current;return(m=Wc(a,m),wh(a,s),i=Mf(n,a,i,o,m,s),o=Vf(),null===n||ni)?(ty&&o&&pd(a),a.flags|=1,uh(n,a,i,s),a.child):(Wf(n,a,s),xh(n,a,s))}function Hh(n,a,i,o,s,m){return(wh(a,m),i=Pf(a,o,i,s),Qf(),o=Vf(),null===n||ni)?(ty&&o&&pd(a),a.flags|=1,uh(n,a,i,m),a.child):(Wf(n,a,m),xh(n,a,m))}function Ih(n,a,i,o,s){if(Xc(i)){var m=!0;ad(a)}else m=!1;if(wh(a,s),null===a.stateNode)Jh(n,a),bh(a,i,o),dh(a,i,o,s),o=!0;else if(null===n){var y=a.stateNode,v=a.memoizedProps;y.props=v;var k=y.context,S=i.contextType;S="object"==typeof S&&null!==S?bg(S):Wc(a,S=Xc(i)?e5:e6.current);var C=i.getDerivedStateFromProps,x="function"==typeof C||"function"==typeof y.getSnapshotBeforeUpdate;x||"function"!=typeof y.UNSAFE_componentWillReceiveProps&&"function"!=typeof y.componentWillReceiveProps||(v!==o||k!==S)&&ch(a,y,o,S),tx=!1;var P=a.memoizedState;y.state=P,de(a,o,y,s),k=a.memoizedState,v!==o||P!==k||e8.current||tx?("function"==typeof C&&(Zg(a,i,C,o),k=a.memoizedState),(v=tx||ah(a,i,v,o,P,k,S))?(x||"function"!=typeof y.UNSAFE_componentWillMount&&"function"!=typeof y.componentWillMount||("function"==typeof y.componentWillMount&&y.componentWillMount(),"function"==typeof y.UNSAFE_componentWillMount&&y.UNSAFE_componentWillMount()),"function"==typeof y.componentDidMount&&(a.flags|=4194308)):("function"==typeof y.componentDidMount&&(a.flags|=4194308),a.memoizedProps=o,a.memoizedState=k),y.props=o,y.state=k,y.context=S,o=v):("function"==typeof y.componentDidMount&&(a.flags|=4194308),o=!1)}else{y=a.stateNode,Zd(n,a),v=a.memoizedProps,S=a.type===a.elementType?v:Yg(a.type,v),y.props=S,x=a.pendingProps,P=y.context,k="object"==typeof(k=i.contextType)&&null!==k?bg(k):Wc(a,k=Xc(i)?e5:e6.current);var N=i.getDerivedStateFromProps;(C="function"==typeof N||"function"==typeof y.getSnapshotBeforeUpdate)||"function"!=typeof y.UNSAFE_componentWillReceiveProps&&"function"!=typeof y.componentWillReceiveProps||(v!==x||P!==k)&&ch(a,y,o,k),tx=!1,P=a.memoizedState,y.state=P,de(a,o,y,s);var j=a.memoizedState;v!==x||P!==j||e8.current||tx?("function"==typeof N&&(Zg(a,i,N,o),j=a.memoizedState),(S=tx||ah(a,i,S,o,P,j,k)||!1)?(C||"function"!=typeof y.UNSAFE_componentWillUpdate&&"function"!=typeof y.componentWillUpdate||("function"==typeof y.componentWillUpdate&&y.componentWillUpdate(o,j,k),"function"==typeof y.UNSAFE_componentWillUpdate&&y.UNSAFE_componentWillUpdate(o,j,k)),"function"==typeof y.componentDidUpdate&&(a.flags|=4),"function"==typeof y.getSnapshotBeforeUpdate&&(a.flags|=1024)):("function"!=typeof y.componentDidUpdate||v===n.memoizedProps&&P===n.memoizedState||(a.flags|=4),"function"!=typeof y.getSnapshotBeforeUpdate||v===n.memoizedProps&&P===n.memoizedState||(a.flags|=1024),a.memoizedProps=o,a.memoizedState=j),y.props=o,y.state=j,y.context=k,o=S):("function"!=typeof y.componentDidUpdate||v===n.memoizedProps&&P===n.memoizedState||(a.flags|=4),"function"!=typeof y.getSnapshotBeforeUpdate||v===n.memoizedProps&&P===n.memoizedState||(a.flags|=1024),o=!1)}return Kh(n,a,i,o,m,s)}function Kh(n,a,i,o,s,m){Dh(n,a);var y=0!=(128&a.flags);if(!o&&!y)return s&&bd(a,i,!1),xh(n,a,m);o=a.stateNode,nl.current=a;var v=y&&"function"!=typeof i.getDerivedStateFromError?null:o.render();return a.flags|=1,null!==n&&y?(a.child=t_(a,n.child,null,m),a.child=t_(a,null,v,m)):uh(n,a,v,m),a.memoizedState=o.state,s&&bd(a,i,!0),a.child}function Lh(n){var a=n.stateNode;a.pendingContext?Zc(n,a.pendingContext,a.pendingContext!==a.context):a.context&&Zc(n,a.context,!1),Ja(n,a.containerInfo)}function Mh(n,a,i,o,s){return Kd(),Ld(s),a.flags|=256,uh(n,a,i,o),a.child}var nu={dehydrated:null,treeContext:null,retryLane:0};function Oh(n){return{baseLanes:n,cachePool:Ph()}}function Qh(n,a,i){var o,s=a.pendingProps,m=!1,y=0!=(128&a.flags);if((o=y)||(o=(null===n||null!==n.memoizedState)&&0!=(2&tA.current)),o&&(m=!0,a.flags&=-129),null===n){if(ty){if(m?Ne(a):Qe(a),ty&&((y=n=th)?Bd(a,y)||(Dd(a)&&Ed(),th=Cd(y),o=tp,th&&Bd(a,th)?td(o,y):(vd(tp,a),ty=!1,tp=a,th=n)):(Dd(a)&&Ed(),vd(tp,a),ty=!1,tp=a,th=n)),null!==(n=a.memoizedState)&&null!==(n=n.dehydrated))return 0==(1&a.mode)?a.lanes=2:"$!"===n.data?a.lanes=16:a.lanes=536870912,null;Re(a)}return(y=s.children,n=s.fallback,m)?(Qe(a),s=a.mode,m=a.child,y={mode:"hidden",children:y},0==(1&s)&&null!==m?(m.childLanes=0,m.pendingProps=y):m=Rh(y,s,0,null),n=Be(n,s,i,null),m.return=a,n.return=a,m.sibling=n,a.child=m,a.child.memoizedState=Oh(i),a.memoizedState=nu,n):(Ne(a),Sh(a,y))}if(null!==(o=n.memoizedState)){var v=o.dehydrated;if(null!==v)return Th(n,a,y,s,v,o,i)}if(m){Qe(a),m=s.fallback,y=a.mode,v=(o=n.child).sibling;var k={mode:"hidden",children:s.children};return 0==(1&y)&&a.child!==o?((s=a.child).childLanes=0,s.pendingProps=k,a.deletions=null):(s=xe(o,k)).subtreeFlags=31457280&o.subtreeFlags,null!==v?m=xe(v,m):(m=Be(m,y,i,null),m.flags|=2),m.return=a,s.return=a,s.sibling=m,a.child=s,s=m,m=a.child,null===(y=n.child.memoizedState)?y=Oh(i):(null!==(o=y.cachePool)?(v=nE._currentValue,o=o.parent!==v?{parent:v,pool:v}:o):o=Ph(),y={baseLanes:y.baseLanes|i,cachePool:o}),m.memoizedState=y,m.childLanes=n.childLanes&~i,a.memoizedState=nu,s}return Ne(a),n=(m=n.child).sibling,s=xe(m,{mode:"visible",children:s.children}),0==(1&a.mode)&&(s.lanes=i),s.return=a,s.sibling=null,null!==n&&(null===(i=a.deletions)?(a.deletions=[n],a.flags|=16):i.push(n)),a.child=s,a.memoizedState=null,s}function Sh(n,a){return(a=Rh({mode:"visible",children:a},n.mode,0,null)).return=n,n.child=a}function Uh(n,a,i,o){return null!==o&&Ld(o),t_(a,n.child,null,i),n=Sh(a,a.pendingProps.children),n.flags|=2,a.memoizedState=null,n}function Th(n,a,i,o,s,m,y){if(i)return 256&a.flags?(Ne(a),a.flags&=-257,Uh(n,a,y,s=fh(Error(t(422))))):null!==a.memoizedState?(Qe(a),a.child=n.child,a.flags|=128,null):(Qe(a),s=o.fallback,m=a.mode,o=Rh({mode:"visible",children:o.children},m,0,null),s=Be(s,m,y,null),s.flags|=2,o.return=a,s.return=a,o.sibling=s,a.child=o,0!=(1&a.mode)&&t_(a,n.child,null,y),a.child.memoizedState=Oh(y),a.memoizedState=nu,s);if(Ne(a),0==(1&a.mode))return Uh(n,a,y,null);if("$!"===s.data){if(s=s.nextSibling&&s.nextSibling.dataset)var v=s.dgst;return s=v,(o=Error(t(419))).digest=s,Uh(n,a,y,s=fh(o,s,void 0))}if(v=0!=(y&n.childLanes),ni||v){if(null!==(o=nH)){switch(y&-y){case 2:v=1;break;case 8:v=4;break;case 32:v=16;break;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:v=64;break;case 268435456:v=134217728;break;default:v=0}if(0!==(v=0!=(v&(o.suspendedLanes|y))?0:v)&&v!==m.retryLane)throw m.retryLane=v,Ud(n,v),pg(o,n,v),na}return"$?"!==s.data&&oh(),Uh(n,a,y,null)}return"$?"===s.data?(a.flags|=128,a.child=n.child,a=Vh.bind(null,n),s._reactRetry=a,null):(n=m.treeContext,th=yd(s.nextSibling),tp=a,ty=!0,tv=null,tw=!1,null!==n&&(tl[ta++]=ts,tl[ta++]=tf,tl[ta++]=tu,ts=n.id,tf=n.overflow,tu=a),a=Sh(a,o.children),a.flags|=4096,a)}function Wh(n,a,i){n.lanes|=a;var o=n.alternate;null!==o&&(o.lanes|=a),Xh(n.return,a,i)}function Yh(n,a,i,o,s){var m=n.memoizedState;null===m?n.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:o,tail:i,tailMode:s}:(m.isBackwards=a,m.rendering=null,m.renderingStartTime=0,m.last=o,m.tail=i,m.tailMode=s)}function Zh(n,a,i){var o=a.pendingProps,s=o.revealOrder,m=o.tail;if(uh(n,a,o.children,i),0!=(2&(o=tA.current)))o=1&o|2,a.flags|=128;else{if(null!==n&&0!=(128&n.flags))e:for(n=a.child;null!==n;){if(13===n.tag)null!==n.memoizedState&&Wh(n,i,a);else if(19===n.tag)Wh(n,i,a);else if(null!==n.child){n.child.return=n,n=n.child;continue}if(n===a)break;for(;null===n.sibling;){if(null===n.return||n.return===a)break e;n=n.return}n.sibling.return=n.return,n=n.sibling}o&=1}if(E(tA,o),0==(1&a.mode))a.memoizedState=null;else switch(s){case"forwards":for(s=null,i=a.child;null!==i;)null!==(n=i.alternate)&&null===Se(n)&&(s=i),i=i.sibling;null===(i=s)?(s=a.child,a.child=null):(s=i.sibling,i.sibling=null),Yh(a,!1,s,i,m);break;case"backwards":for(i=null,s=a.child,a.child=null;null!==s;){if(null!==(n=s.alternate)&&null===Se(n)){a.child=s;break}n=s.sibling,s.sibling=i,i=s,s=n}Yh(a,!0,i,null,m);break;case"together":Yh(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function Jh(n,a){0==(1&a.mode)&&null!==n&&(n.alternate=null,a.alternate=null,a.flags|=2)}function xh(n,a,i){if(null!==n&&(a.dependencies=n.dependencies),n3|=a.lanes,0==(i&a.childLanes))return null;if(null!==n&&a.child!==n.child)throw Error(t(153));if(null!==a.child){for(i=xe(n=a.child,n.pendingProps),a.child=i,i.return=a;null!==n.sibling;)n=n.sibling,(i=i.sibling=xe(n,n.pendingProps)).return=a;i.sibling=null}return a.child}function $h(n,a,i){switch(a.tag){case 3:Lh(a),ai(a,nE,n.memoizedState.cache),Kd();break;case 27:case 5:Na(a);break;case 1:Xc(a.type)&&ad(a);break;case 4:Ja(a,a.stateNode.containerInfo);break;case 10:ai(a,a.type._context,a.memoizedProps.value);break;case 13:var o=a.memoizedState;if(null!==o){if(null!==o.dehydrated)return Ne(a),a.flags|=128,null;if(0!=(i&a.child.childLanes))return Qh(n,a,i);return Ne(a),null!==(n=xh(n,a,i))?n.sibling:null}Ne(a);break;case 19:if(o=0!=(i&a.childLanes),0!=(128&n.flags)){if(o)return Zh(n,a,i);a.flags|=128}var s=a.memoizedState;if(null!==s&&(s.rendering=null,s.tail=null,s.lastEffect=null),E(tA,tA.current),!o)return null;break;case 22:case 23:return a.lanes=0,Ch(n,a,i);case 24:ai(a,nE,n.memoizedState.cache)}return xh(n,a,i)}var ns=ka(null),np=null,ny=null,nv=null;function fi(){nv=ny=np=null}function ai(n,a,i){E(ns,a._currentValue),a._currentValue=i}function gi(n){n._currentValue=ns.current,D(ns)}function Xh(n,a,i){for(;null!==n;){var o=n.alternate;if((n.childLanes&a)!==a?(n.childLanes|=a,null!==o&&(o.childLanes|=a)):null!==o&&(o.childLanes&a)!==a&&(o.childLanes|=a),n===i)break;n=n.return}}function hi(n,a,i){var o=n.child;for(null!==o&&(o.return=n);null!==o;){var s=o.dependencies;if(null!==s)for(var m=o.child,y=s.firstContext;null!==y;){if(y.context===a){if(1===o.tag){(y=$d(i&-i)).tag=2;var v=o.updateQueue;if(null!==v){var k=(v=v.shared).pending;null===k?y.next=y:(y.next=k.next,k.next=y),v.pending=y}}o.lanes|=i,null!==(y=o.alternate)&&(y.lanes|=i),Xh(o.return,i,n),s.lanes|=i;break}y=y.next}else if(10===o.tag)m=o.type===n.type?null:o.child;else if(18===o.tag){if(null===(m=o.return))throw Error(t(341));m.lanes|=i,null!==(s=m.alternate)&&(s.lanes|=i),Xh(m,i,n),m=o.sibling}else m=o.child;if(null!==m)m.return=o;else for(m=o;null!==m;){if(m===n){m=null;break}if(null!==(o=m.sibling)){o.return=m.return,m=o;break}m=m.return}o=m}}function wh(n,a){np=n,nv=ny=null,null!==(n=n.dependencies)&&null!==n.firstContext&&(0!=(n.lanes&a)&&(ni=!0),n.firstContext=null)}function bg(n){return ii(np,n)}function Ce(n,a,i){return null===np&&wh(n,i),ii(n,a)}function ii(n,a){var i=a._currentValue;if(nv!==a){if(a={context:a,memoizedValue:i,next:null},null===ny){if(null===n)throw Error(t(308));ny=a,n.dependencies={lanes:0,firstContext:a}}else ny=ny.next=a}return i}var nk="undefined"!=typeof AbortController?AbortController:function(){var n=[],a=this.signal={aborted:!1,addEventListener:function(a,i){n.push(i)}};this.abort=function(){a.aborted=!0,n.forEach(function(n){return n()})}},nw=m.unstable_scheduleCallback,nS=m.unstable_NormalPriority,nE={$$typeof:F,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0,_defaultValue:null,_globalName:null};function Ug(){return{controller:new nk,data:new Map,refCount:0}}function mi(n){n.refCount--,0===n.refCount&&nw(nS,function(){n.controller.abort()})}var nC=k.ReactCurrentBatchConfig,nx=ka(null);function Gh(){var n=nx.current;return null!==n?n:nH.pooledCache}function Fh(n,a){null===a?E(nx,nx.current):E(nx,a.pool)}function Ph(){var n=Gh();return null===n?null:{parent:nE._currentValue,pool:n}}function pi(n){n.flags|=4}function qi(n){n.flags|=2097664}function ri(n,a){if("stylesheet"!==a.type||0!=(4&a.state.loading))n.flags&=-16777217;else if(n.flags|=16777216,0==(42&nK)&&!(a="stylesheet"!==a.type||0!=(3&a.state.loading))){if(si())n.flags|=8192;else throw tj=tN,tP}}function ti(n,a){null!==a?n.flags|=4:16384&n.flags&&(a=22!==n.tag?mb():536870912,n.lanes|=a)}function ui(n,a){if(!ty)switch(n.tailMode){case"hidden":a=n.tail;for(var i=null;null!==a;)null!==a.alternate&&(i=a),a=a.sibling;null===i?n.tail=null:i.sibling=null;break;case"collapsed":i=n.tail;for(var o=null;null!==i;)null!==i.alternate&&(o=i),i=i.sibling;null===o?a||null===n.tail?n.tail=null:n.tail.sibling=null:o.sibling=null}}function T(n){var a=null!==n.alternate&&n.alternate.child===n.child,i=0,o=0;if(a)for(var s=n.child;null!==s;)i|=s.lanes|s.childLanes,o|=31457280&s.subtreeFlags,o|=31457280&s.flags,s.return=n,s=s.sibling;else for(s=n.child;null!==s;)i|=s.lanes|s.childLanes,o|=s.subtreeFlags,o|=s.flags,s.return=n,s=s.sibling;return n.subtreeFlags|=o,n.childLanes=i,a}function vi(n,a,i){var o=a.pendingProps;switch(qd(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return T(a),null;case 1:case 17:return Xc(a.type)&&Yc(),T(a),null;case 3:return i=a.stateNode,o=null,null!==n&&(o=n.memoizedState.cache),a.memoizedState.cache!==o&&(a.flags|=2048),gi(nE),Ma(),D(e8),D(e6),i.pendingContext&&(i.context=i.pendingContext,i.pendingContext=null),(null===n||null===n.child)&&(Hd(a)?pi(a):null===n||n.memoizedState.isDehydrated&&0==(256&a.flags)||(a.flags|=1024,null!==tv&&(wi(tv),tv=null))),T(a),null;case 26:if(i=a.memoizedState,null===n)pi(a),null!==a.ref&&qi(a),null!==i?(T(a),ri(a,i)):(T(a),a.flags&=-16777217);else{var s=n.memoizedState;i!==s&&pi(a),n.ref!==a.ref&&qi(a),null!==i?(T(a),i===s?a.flags&=-16777217:ri(a,i)):(n.memoizedProps!==o&&pi(a),T(a),a.flags&=-16777217)}return null;case 27:if(Oa(a),i=er.current,s=a.type,null!==n&&null!=a.stateNode)n.memoizedProps!==o&&pi(a),n.ref!==a.ref&&qi(a);else{if(!o){if(null===a.stateNode)throw Error(t(166));return T(a),null}n=et.current,Hd(a)?xi(a.stateNode,a.type,a.memoizedProps,n,a):(n=yi(s,o,i),a.stateNode=n,pi(a)),null!==a.ref&&qi(a)}return T(a),null;case 5:if(Oa(a),i=a.type,null!==n&&null!=a.stateNode)n.memoizedProps!==o&&pi(a),n.ref!==a.ref&&qi(a);else{if(!o){if(null===a.stateNode)throw Error(t(166));return T(a),null}if(n=et.current,Hd(a))xi(a.stateNode,a.type,a.memoizedProps,n,a);else{switch(s=zi(er.current),n){case 1:n=s.createElementNS("http://www.w3.org/2000/svg",i);break;case 2:n=s.createElementNS("http://www.w3.org/1998/Math/MathML",i);break;default:switch(i){case"svg":n=s.createElementNS("http://www.w3.org/2000/svg",i);break;case"math":n=s.createElementNS("http://www.w3.org/1998/Math/MathML",i);break;case"script":(n=s.createElement("div")).innerHTML="<script></script>",n=n.removeChild(n.firstChild);break;case"select":n="string"==typeof o.is?s.createElement("select",{is:o.is}):s.createElement("select"),o.multiple?n.multiple=!0:o.size&&(n.size=o.size);break;default:n="string"==typeof o.is?s.createElement(i,{is:o.is}):s.createElement(i)}}n[eM]=a,n[eR]=o;e:for(s=a.child;null!==s;){if(5===s.tag||6===s.tag)n.appendChild(s.stateNode);else if(4!==s.tag&&27!==s.tag&&null!==s.child){s.child.return=s,s=s.child;continue}if(s===a)break;for(;null===s.sibling;){if(null===s.return||s.return===a)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}switch(a.stateNode=n,Ai(n,i,o),i){case"button":case"input":case"select":case"textarea":n=!!o.autoFocus;break;case"img":n=!0;break;default:n=!1}n&&pi(a)}null!==a.ref&&qi(a)}return T(a),a.flags&=-16777217,null;case 6:if(n&&null!=a.stateNode)n.memoizedProps!==o&&pi(a);else{if("string"!=typeof o&&null===a.stateNode)throw Error(t(166));if(n=er.current,Hd(a)){e:{if(n=a.stateNode,i=a.memoizedProps,n[eM]=a,(o=n.nodeValue!==i)&&null!==(s=tp))switch(s.tag){case 3:if(s=0!=(1&s.mode),Bi(n.nodeValue,i,s),s){n=!1;break e}break;case 27:case 5:var m=0!=(1&s.mode);if(!0!==s.memoizedProps.suppressHydrationWarning&&Bi(n.nodeValue,i,m),m){n=!1;break e}}n=o}n&&pi(a)}else(n=zi(n).createTextNode(o))[eM]=a,a.stateNode=n}return T(a),null;case 13:if(Re(a),o=a.memoizedState,null===n||null!==n.memoizedState&&null!==n.memoizedState.dehydrated){if(ty&&null!==th&&0!=(1&a.mode)&&0==(128&a.flags))Jd(),Kd(),a.flags|=384,s=!1;else if(s=Hd(a),null!==o&&null!==o.dehydrated){if(null===n){if(!s)throw Error(t(318));if(!(s=null!==(s=a.memoizedState)?s.dehydrated:null))throw Error(t(317));s[eM]=a}else Kd(),0==(128&a.flags)&&(a.memoizedState=null),a.flags|=4;T(a),s=!1}else null!==tv&&(wi(tv),tv=null),s=!0;if(!s)return 256&a.flags?a:null}if(0!=(128&a.flags))return a.lanes=i,a;return i=null!==o,n=null!==n&&null!==n.memoizedState,i&&(o=a.child,s=null,null!==o.alternate&&null!==o.alternate.memoizedState&&null!==o.alternate.memoizedState.cachePool&&(s=o.alternate.memoizedState.cachePool.pool),m=null,null!==o.memoizedState&&null!==o.memoizedState.cachePool&&(m=o.memoizedState.cachePool.pool),m!==s&&(o.flags|=2048)),i!==n&&i&&(a.child.flags|=8192),ti(a,a.updateQueue),T(a),null;case 4:return Ma(),null===n&&Ci(a.stateNode.containerInfo),T(a),null;case 10:return gi(a.type._context),T(a),null;case 19:if(D(tA),null===(s=a.memoizedState))return T(a),null;if(o=0!=(128&a.flags),null===(m=s.rendering)){if(o)ui(s,!1);else{if(0!==n1||null!==n&&0!=(128&n.flags))for(n=a.child;null!==n;){if(null!==(m=Se(n))){for(a.flags|=128,ui(s,!1),n=m.updateQueue,a.updateQueue=n,ti(a,n),a.subtreeFlags=0,n=i,i=a.child;null!==i;)Di(i,n),i=i.sibling;return E(tA,1&tA.current|2),a.child}n=n.sibling}null!==s.tail&&em()>re&&(a.flags|=128,o=!0,ui(s,!1),a.lanes=4194304)}}else{if(!o){if(null!==(n=Se(m))){if(a.flags|=128,o=!0,n=n.updateQueue,a.updateQueue=n,ti(a,n),ui(s,!0),null===s.tail&&"hidden"===s.tailMode&&!m.alternate&&!ty)return T(a),null}else 2*em()-s.renderingStartTime>re&&536870912!==i&&(a.flags|=128,o=!0,ui(s,!1),a.lanes=4194304)}s.isBackwards?(m.sibling=a.child,a.child=m):(null!==(n=s.last)?n.sibling=m:a.child=m,s.last=m)}if(null!==s.tail)return a=s.tail,s.rendering=a,s.tail=a.sibling,s.renderingStartTime=em(),a.sibling=null,n=tA.current,E(tA,o?1&n|2:1&n),a;return T(a),null;case 22:case 23:return Re(a),Ke(),o=null!==a.memoizedState,null!==n?null!==n.memoizedState!==o&&(a.flags|=8192):o&&(a.flags|=8192),o&&0!=(1&a.mode)?0!=(536870912&i)&&0==(128&a.flags)&&(T(a),6&a.subtreeFlags&&(a.flags|=8192)):T(a),null!==(i=a.updateQueue)&&ti(a,i.retryQueue),i=null,null!==n&&null!==n.memoizedState&&null!==n.memoizedState.cachePool&&(i=n.memoizedState.cachePool.pool),o=null,null!==a.memoizedState&&null!==a.memoizedState.cachePool&&(o=a.memoizedState.cachePool.pool),o!==i&&(a.flags|=2048),null!==n&&D(nx),null;case 24:return i=null,null!==n&&(i=n.memoizedState.cache),a.memoizedState.cache!==i&&(a.flags|=2048),gi(nE),T(a),null;case 25:return null}throw Error(t(156,a.tag))}function Fi(n,a){switch(qd(a),a.tag){case 1:return Xc(a.type)&&Yc(),65536&(n=a.flags)?(a.flags=-65537&n|128,a):null;case 3:return gi(nE),Ma(),D(e8),D(e6),0!=(65536&(n=a.flags))&&0==(128&n)?(a.flags=-65537&n|128,a):null;case 26:case 27:case 5:return Oa(a),null;case 13:if(Re(a),null!==(n=a.memoizedState)&&null!==n.dehydrated){if(null===a.alternate)throw Error(t(340));Kd()}return 65536&(n=a.flags)?(a.flags=-65537&n|128,a):null;case 19:return D(tA),null;case 4:return Ma(),null;case 10:return gi(a.type._context),null;case 22:case 23:return Re(a),Ke(),null!==n&&D(nx),65536&(n=a.flags)?(a.flags=-65537&n|128,a):null;case 24:return gi(nE),null;default:return null}}function Gi(n,a){switch(qd(a),a.tag){case 1:null!=(n=a.type.childContextTypes)&&Yc();break;case 3:gi(nE),Ma(),D(e8),D(e6);break;case 26:case 27:case 5:Oa(a);break;case 4:Ma();break;case 13:Re(a);break;case 19:D(tA);break;case 10:gi(a.type._context);break;case 22:case 23:Re(a),Ke(),null!==n&&D(nx);break;case 24:gi(nE)}}function Hi(n,a,i){var o=Array.prototype.slice.call(arguments,3);try{a.apply(i,o)}catch(n){this.onError(n)}}var nz=!1,nP=null,nN=!1,nT=null,nL={onError:function(n){nz=!0,nP=n}};function Ni(n,a,i,o,s,m,y,v,k){nz=!1,nP=null,Hi.apply(nL,arguments)}function Oi(n,a,i,o,s,m,y,v,k){if(Ni.apply(this,arguments),nz){if(nz){var S=nP;nz=!1,nP=null}else throw Error(t(198));nN||(nN=!0,nT=S)}}var n_=!1,nD=!1,nM="function"==typeof WeakSet?WeakSet:Set,nR=null;function Ti(n,a){try{var i=n.ref;if(null!==i){var o=n.stateNode;switch(n.tag){case 26:case 27:case 5:var s=o;break;default:s=o}"function"==typeof i?n.refCleanup=i(s):i.current=s}}catch(i){W(n,a,i)}}function Ui(n,a){var i=n.ref,o=n.refCleanup;if(null!==i){if("function"==typeof o)try{o()}catch(i){W(n,a,i)}finally{n.refCleanup=null,null!=(n=n.alternate)&&(n.refCleanup=null)}else if("function"==typeof i)try{i(null)}catch(i){W(n,a,i)}else i.current=null}}function Vi(n,a,i){try{i()}catch(i){W(n,a,i)}}var nF=!1;function Xi(n,a){if(lB=r4,aj(n=$i())){if("selectionStart"in n)var i={start:n.selectionStart,end:n.selectionEnd};else e:{var o=(i=(i=n.ownerDocument)&&i.defaultView||window).getSelection&&i.getSelection();if(o&&0!==o.rangeCount){i=o.anchorNode;var s,m=o.anchorOffset,y=o.focusNode;o=o.focusOffset;try{i.nodeType,y.nodeType}catch(n){i=null;break e}var v=0,k=-1,S=-1,C=0,x=0,P=n,N=null;t:for(;;){for(;P!==i||0!==m&&3!==P.nodeType||(k=v+m),P!==y||0!==o&&3!==P.nodeType||(S=v+o),3===P.nodeType&&(v+=P.nodeValue.length),null!==(s=P.firstChild);)N=P,P=s;for(;;){if(P===n)break t;if(N===i&&++C===m&&(k=v),N===y&&++x===o&&(S=v),null!==(s=P.nextSibling))break;N=(P=N).parentNode}P=s}i=-1===k||-1===S?null:{start:k,end:S}}else i=null}i=i||{start:0,end:0}}else i=null;for(lW={focusedElem:n,selectionRange:i},r4=!1,nR=a;null!==nR;)if(n=(a=nR).child,0!=(1028&a.subtreeFlags)&&null!==n)n.return=a,nR=n;else for(;null!==nR;){a=nR;try{var j=a.alternate,L=a.flags;switch(a.tag){case 0:case 11:case 15:case 5:case 26:case 27:case 6:case 4:case 17:break;case 1:if(0!=(1024&L)&&null!==j){var _=j.memoizedProps,M=j.memoizedState,R=a.stateNode,F=R.getSnapshotBeforeUpdate(a.elementType===a.type?_:Yg(a.type,_),M);R.__reactInternalSnapshotBeforeUpdate=F}break;case 3:0!=(1024&L)&&cj(a.stateNode.containerInfo);break;default:if(0!=(1024&L))throw Error(t(163))}}catch(n){W(a,a.return,n)}if(null!==(n=a.sibling)){n.return=a.return,nR=n;break}nR=a.return}return j=nF,nF=!1,j}function dj(n,a,i){var o=a.updateQueue;if(null!==(o=null!==o?o.lastEffect:null)){var s=o=o.next;do{if((s.tag&n)===n){var m=s.inst,y=m.destroy;void 0!==y&&(m.destroy=void 0,Vi(a,i,y))}s=s.next}while(s!==o)}}function ej(n,a){if(null!==(a=null!==(a=a.updateQueue)?a.lastEffect:null)){var i=a=a.next;do{if((i.tag&n)===n){var o=i.create,s=i.inst;o=o(),s.destroy=o}i=i.next}while(i!==a)}}function fj(n,a){try{ej(a,n)}catch(a){W(n,n.return,a)}}function gj(n){var a=n.updateQueue;if(null!==a){var i=n.stateNode;try{ge(a,i)}catch(a){W(n,n.return,a)}}}function hj(n){var a=n.type,i=n.memoizedProps,o=n.stateNode;try{switch(a){case"button":case"input":case"select":case"textarea":i.autoFocus&&o.focus();break;case"img":i.src&&(o.src=i.src)}}catch(a){W(n,n.return,a)}}function ij(n,a,i){var o=i.flags;switch(i.tag){case 0:case 11:case 15:jj(n,i),4&o&&fj(i,5);break;case 1:if(jj(n,i),4&o){if(n=i.stateNode,null===a)try{n.componentDidMount()}catch(n){W(i,i.return,n)}else{var s=i.elementType===i.type?a.memoizedProps:Yg(i.type,a.memoizedProps);a=a.memoizedState;try{n.componentDidUpdate(s,a,n.__reactInternalSnapshotBeforeUpdate)}catch(n){W(i,i.return,n)}}}64&o&&gj(i),512&o&&Ti(i,i.return);break;case 3:if(jj(n,i),64&o&&null!==(o=i.updateQueue)){if(n=null,null!==i.child)switch(i.child.tag){case 27:case 5:case 1:n=i.child.stateNode}try{ge(o,n)}catch(n){W(i,i.return,n)}}break;case 26:jj(n,i),512&o&&Ti(i,i.return);break;case 27:case 5:jj(n,i),null===a&&4&o&&hj(i),512&o&&Ti(i,i.return);break;case 12:default:jj(n,i);break;case 13:jj(n,i),4&o&&kj(n,i);break;case 22:if(0!=(1&i.mode)){if(!(s=null!==i.memoizedState||n_)){a=null!==a&&null!==a.memoizedState||nD;var m=n_,y=nD;n_=s,(nD=a)&&!y?lj(n,i,0!=(8772&i.subtreeFlags)):jj(n,i),n_=m,nD=y}}else jj(n,i);512&o&&("manual"===i.memoizedProps.mode?Ti(i,i.return):Ui(i,i.return))}}function mj(n){var a=n.alternate;null!==a&&(n.alternate=null,mj(a)),n.child=null,n.deletions=null,n.sibling=null,5===n.tag&&null!==(a=n.stateNode)&&Gb(a),n.stateNode=null,n.return=null,n.dependencies=null,n.memoizedProps=null,n.memoizedState=null,n.pendingProps=null,n.stateNode=null,n.updateQueue=null}function nj(n){return 5===n.tag||3===n.tag||26===n.tag||27===n.tag||4===n.tag}function oj(n){e:for(;;){for(;null===n.sibling;){if(null===n.return||nj(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;5!==n.tag&&6!==n.tag&&27!==n.tag&&18!==n.tag;){if(2&n.flags||null===n.child||4===n.tag)continue e;n.child.return=n,n=n.child}if(!(2&n.flags))return n.stateNode}}function pj(n,a,i){var o=n.tag;if(5===o||6===o)n=n.stateNode,a?8===i.nodeType?i.parentNode.insertBefore(n,a):i.insertBefore(n,a):(8===i.nodeType?(a=i.parentNode).insertBefore(n,i):(a=i).appendChild(n),null!=(i=i._reactRootContainer)||null!==a.onclick||(a.onclick=qj));else if(4!==o&&27!==o&&null!==(n=n.child))for(pj(n,a,i),n=n.sibling;null!==n;)pj(n,a,i),n=n.sibling}function rj(n,a,i){var o=n.tag;if(5===o||6===o)n=n.stateNode,a?i.insertBefore(n,a):i.appendChild(n);else if(4!==o&&27!==o&&null!==(n=n.child))for(rj(n,a,i),n=n.sibling;null!==n;)rj(n,a,i),n=n.sibling}var nO=null,nA=!1;function uj(n,a,i){for(i=i.child;null!==i;)vj(n,a,i),i=i.sibling}function vj(n,a,i){if(eC&&"function"==typeof eC.onCommitFiberUnmount)try{eC.onCommitFiberUnmount(eE,i)}catch(n){}switch(i.tag){case 26:nD||Ui(i,a),uj(n,a,i),i.memoizedState?i.memoizedState.count--:i.stateNode&&(i=i.stateNode).parentNode.removeChild(i);break;case 27:nD||Ui(i,a);var o=nO,s=nA;for(nO=i.stateNode,uj(n,a,i),n=(i=i.stateNode).attributes;n.length;)i.removeAttributeNode(n[0]);Gb(i),nO=o,nA=s;break;case 5:nD||Ui(i,a);case 6:o=nO,s=nA,nO=null,uj(n,a,i),nO=o,nA=s,null!==nO&&(nA?(n=nO,i=i.stateNode,8===n.nodeType?n.parentNode.removeChild(i):n.removeChild(i)):nO.removeChild(i.stateNode));break;case 18:null!==nO&&(nA?(n=nO,i=i.stateNode,8===n.nodeType?wj(n.parentNode,i):1===n.nodeType&&wj(n,i),xj(n)):wj(nO,i.stateNode));break;case 4:o=nO,s=nA,nO=i.stateNode.containerInfo,nA=!0,uj(n,a,i),nO=o,nA=s;break;case 0:case 11:case 14:case 15:if(!nD&&null!==(o=i.updateQueue)&&null!==(o=o.lastEffect)){s=o=o.next;do{var m=s.tag,y=s.inst,v=y.destroy;void 0!==v&&(0!=(2&m)?(y.destroy=void 0,Vi(i,a,v)):0!=(4&m)&&(y.destroy=void 0,Vi(i,a,v))),s=s.next}while(s!==o)}uj(n,a,i);break;case 1:if(!nD&&(Ui(i,a),"function"==typeof(o=i.stateNode).componentWillUnmount))try{o.props=i.memoizedProps,o.state=i.memoizedState,o.componentWillUnmount()}catch(n){W(i,a,n)}uj(n,a,i);break;case 21:default:uj(n,a,i);break;case 22:Ui(i,a),1&i.mode?(nD=(o=nD)||null!==i.memoizedState,uj(n,a,i),nD=o):uj(n,a,i)}}function kj(n,a){if(null===a.memoizedState&&null!==(n=a.alternate)&&null!==(n=n.memoizedState)&&null!==(n=n.dehydrated))try{xj(n)}catch(n){W(a,a.return,n)}}function yj(n){switch(n.tag){case 13:case 19:var a=n.stateNode;return null===a&&(a=n.stateNode=new nM),a;case 22:return null===(a=(n=n.stateNode)._retryCache)&&(a=n._retryCache=new nM),a;default:throw Error(t(435,n.tag))}}function zj(n,a){var i=yj(n);a.forEach(function(a){var o=Aj.bind(null,n,a);i.has(a)||(i.add(a),a.then(o,o))})}function Bj(n,a){var i=a.deletions;if(null!==i)for(var o=0;o<i.length;o++){var s=i[o];try{var m=a,y=m;e:for(;null!==y;){switch(y.tag){case 27:case 5:nO=y.stateNode,nA=!1;break e;case 3:case 4:nO=y.stateNode.containerInfo,nA=!0;break e}y=y.return}if(null===nO)throw Error(t(160));vj(n,m,s),nO=null,nA=!1;var v=s.alternate;null!==v&&(v.return=null),s.return=null}catch(n){W(s,a,n)}}if(12854&a.subtreeFlags)for(a=a.child;null!==a;)Cj(a,n),a=a.sibling}var nI=null;function Cj(n,a){var i=n.alternate,o=n.flags;switch(n.tag){case 0:case 11:case 14:case 15:if(Bj(a,n),Ej(n),4&o){try{dj(3,n,n.return),ej(3,n)}catch(a){W(n,n.return,a)}try{dj(5,n,n.return)}catch(a){W(n,n.return,a)}}break;case 1:Bj(a,n),Ej(n),512&o&&null!==i&&Ui(i,i.return),64&o&&n_&&null!==(n=n.updateQueue)&&null!==(i=n.callbacks)&&(o=n.shared.hiddenCallbacks,n.shared.hiddenCallbacks=null===o?i:o.concat(i));break;case 26:var s=nI;if(Bj(a,n),Ej(n),512&o&&null!==i&&Ui(i,i.return),4&o){if(a=null!==i?i.memoizedState:null,o=n.memoizedState,null===i){if(null===o){if(null===n.stateNode){e:{i=n.type,o=n.memoizedProps,a=s.ownerDocument||s;t:switch(i){case"title":(!(s=a.getElementsByTagName("title")[0])||s[eB]||s[eM]||"http://www.w3.org/2000/svg"===s.namespaceURI||s.hasAttribute("itemprop"))&&(s=a.createElement(i),a.head.insertBefore(s,a.querySelector("head > title"))),Ai(s,i,o),s[eM]=n,Nb(s),i=s;break e;case"link":var m=Fj("link","href",a).get(i+(o.href||""));if(m){for(var y=0;y<m.length;y++)if((s=m[y]).getAttribute("href")===(null==o.href?null:o.href)&&s.getAttribute("rel")===(null==o.rel?null:o.rel)&&s.getAttribute("title")===(null==o.title?null:o.title)&&s.getAttribute("crossorigin")===(null==o.crossOrigin?null:o.crossOrigin)){m.splice(y,1);break t}}Ai(s=a.createElement(i),i,o),a.head.appendChild(s);break;case"meta":if(m=Fj("meta","content",a).get(i+(o.content||""))){for(y=0;y<m.length;y++)if((s=m[y]).getAttribute("content")===(null==o.content?null:""+o.content)&&s.getAttribute("name")===(null==o.name?null:o.name)&&s.getAttribute("property")===(null==o.property?null:o.property)&&s.getAttribute("http-equiv")===(null==o.httpEquiv?null:o.httpEquiv)&&s.getAttribute("charset")===(null==o.charSet?null:o.charSet)){m.splice(y,1);break t}}Ai(s=a.createElement(i),i,o),a.head.appendChild(s);break;default:throw Error(t(468,i))}s[eM]=n,Nb(s),i=s}n.stateNode=i}else Gj(s,n.type,n.stateNode)}else n.stateNode=Hj(s,o,n.memoizedProps)}else if(a!==o)null===a?null!==i.stateNode&&(i=i.stateNode).parentNode.removeChild(i):a.count--,null===o?Gj(s,n.type,n.stateNode):Hj(s,o,n.memoizedProps);else if(null===o&&null!==n.stateNode){n.updateQueue=null;try{var v=n.stateNode,k=n.memoizedProps;Ij(v,n.type,i.memoizedProps,k),v[eR]=k}catch(a){W(n,n.return,a)}}}break;case 27:if(4&o&&null===n.alternate){for(s=n.stateNode,m=n.memoizedProps,y=s.firstChild;y;){var S=y.nextSibling,C=y.nodeName;y[eB]||"HEAD"===C||"BODY"===C||"SCRIPT"===C||"STYLE"===C||"LINK"===C&&"stylesheet"===y.rel.toLowerCase()||s.removeChild(y),y=S}for(y=n.type,S=s.attributes;S.length;)s.removeAttributeNode(S[0]);Ai(s,y,m),s[eM]=n,s[eR]=m}case 5:if(Bj(a,n),Ej(n),512&o&&null!==i&&Ui(i,i.return),32&n.flags){a=n.stateNode;try{zc(a,"")}catch(a){W(n,n.return,a)}}if(4&o&&null!=(o=n.stateNode)){a=n.memoizedProps,i=null!==i?i.memoizedProps:a,s=n.type,n.updateQueue=null;try{Ij(o,s,i,a),o[eR]=a}catch(a){W(n,n.return,a)}}break;case 6:if(Bj(a,n),Ej(n),4&o){if(null===n.stateNode)throw Error(t(162));i=n.stateNode,o=n.memoizedProps;try{i.nodeValue=o}catch(a){W(n,n.return,a)}}break;case 3:if(lX=null,s=nI,nI=Kj(a.containerInfo),Bj(a,n),nI=s,Ej(n),4&o&&null!==i&&i.memoizedState.isDehydrated)try{xj(a.containerInfo)}catch(a){W(n,n.return,a)}break;case 4:i=nI,nI=Kj(n.stateNode.containerInfo),Bj(a,n),Ej(n),nI=i;break;case 13:Bj(a,n),Ej(n),8192&n.child.flags&&null!==n.memoizedState!=(null!==i&&null!==i.memoizedState)&&(n9=em()),4&o&&null!==(i=n.updateQueue)&&(n.updateQueue=null,zj(n,i));break;case 22:if(512&o&&null!==i&&Ui(i,i.return),v=null!==n.memoizedState,k=null!==i&&null!==i.memoizedState,1&n.mode){var x=n_,P=nD;n_=x||v,nD=P||k,Bj(a,n),nD=P,n_=x}else Bj(a,n);if(Ej(n),(a=n.stateNode)._current=n,a._visibility&=-3,a._visibility|=2&a._pendingVisibility,8192&o&&(a._visibility=v?-2&a._visibility:1|a._visibility,v&&(a=n_||nD,null===i||k||a||0!=(1&n.mode)&&Mj(n)),null===n.memoizedProps||"manual"!==n.memoizedProps.mode))e:for(i=null,a=n;;){if(5===a.tag||26===a.tag||27===a.tag){if(null===i){i=a;try{s=a.stateNode,v?(m=s.style,"function"==typeof m.setProperty?m.setProperty("display","none","important"):m.display="none"):(y=a.stateNode,C=null!=(S=a.memoizedProps.style)&&S.hasOwnProperty("display")?S.display:null,y.style.display=null==C||"boolean"==typeof C?"":(""+C).trim())}catch(a){W(n,n.return,a)}}}else if(6===a.tag){if(null===i)try{a.stateNode.nodeValue=v?"":a.memoizedProps}catch(a){W(n,n.return,a)}}else if((22!==a.tag&&23!==a.tag||null===a.memoizedState||a===n)&&null!==a.child){a.child.return=a,a=a.child;continue}if(a===n)break;for(;null===a.sibling;){if(null===a.return||a.return===n)break e;i===a&&(i=null),a=a.return}i===a&&(i=null),a.sibling.return=a.return,a=a.sibling}4&o&&null!==(i=n.updateQueue)&&null!==(o=i.retryQueue)&&(i.retryQueue=null,zj(n,o));break;case 19:Bj(a,n),Ej(n),4&o&&null!==(i=n.updateQueue)&&(n.updateQueue=null,zj(n,i));break;case 21:break;default:Bj(a,n),Ej(n)}}function Ej(n){var a=n.flags;if(2&a){try{if(27!==n.tag){t:{for(var i=n.return;null!==i;){if(nj(i)){var o=i;break t}i=i.return}throw Error(t(160))}switch(o.tag){case 27:var s=o.stateNode,m=oj(n);rj(n,m,s);break;case 5:var y=o.stateNode;32&o.flags&&(zc(y,""),o.flags&=-33);var v=oj(n);rj(n,v,y);break;case 3:case 4:var k=o.stateNode.containerInfo,S=oj(n);pj(n,S,k);break;default:throw Error(t(161))}}}catch(a){W(n,n.return,a)}n.flags&=-3}4096&a&&(n.flags&=-4097)}function jj(n,a){if(8772&a.subtreeFlags)for(a=a.child;null!==a;)ij(n,a.alternate,a),a=a.sibling}function Mj(n){for(n=n.child;null!==n;){var a=n;switch(a.tag){case 0:case 11:case 14:case 15:dj(4,a,a.return),Mj(a);break;case 1:Ui(a,a.return);var i=a.stateNode;if("function"==typeof i.componentWillUnmount){var o=a.return;try{i.props=a.memoizedProps,i.state=a.memoizedState,i.componentWillUnmount()}catch(n){W(a,o,n)}}Mj(a);break;case 26:case 27:case 5:Ui(a,a.return),Mj(a);break;case 22:Ui(a,a.return),null===a.memoizedState&&Mj(a);break;default:Mj(a)}n=n.sibling}}function lj(n,a,i){for(i=i&&0!=(8772&a.subtreeFlags),a=a.child;null!==a;){var o=a.alternate,s=n,m=a,y=m.flags;switch(m.tag){case 0:case 11:case 15:lj(s,m,i),fj(m,4);break;case 1:if(lj(s,m,i),"function"==typeof(s=m.stateNode).componentDidMount)try{s.componentDidMount()}catch(n){W(m,m.return,n)}if(null!==(o=m.updateQueue)){var v=o.shared.hiddenCallbacks;if(null!==v)for(o.shared.hiddenCallbacks=null,o=0;o<v.length;o++)fe(v[o],s)}i&&64&y&&gj(m),Ti(m,m.return);break;case 26:case 27:case 5:lj(s,m,i),i&&null===o&&4&y&&hj(m),Ti(m,m.return);break;case 12:default:lj(s,m,i);break;case 13:lj(s,m,i),i&&4&y&&kj(s,m);break;case 22:null===m.memoizedState&&lj(s,m,i),Ti(m,m.return)}a=a.sibling}}function Nj(n,a){try{ej(a,n)}catch(a){W(n,n.return,a)}}function Oj(n,a){var i=null;null!==n&&null!==n.memoizedState&&null!==n.memoizedState.cachePool&&(i=n.memoizedState.cachePool.pool),n=null,null!==a.memoizedState&&null!==a.memoizedState.cachePool&&(n=a.memoizedState.cachePool.pool),n!==i&&(null!=n&&n.refCount++,null!=i&&mi(i))}function Pj(n,a){n=null,null!==a.alternate&&(n=a.alternate.memoizedState.cache),(a=a.memoizedState.cache)!==n&&(a.refCount++,null!=n&&mi(n))}function Qj(n,a,i,o){if(10256&a.subtreeFlags)for(a=a.child;null!==a;)Rj(n,a,i,o),a=a.sibling}function Rj(n,a,i,o){var s=a.flags;switch(a.tag){case 0:case 11:case 15:Qj(n,a,i,o),2048&s&&Nj(a,9);break;case 3:Qj(n,a,i,o),2048&s&&(n=null,null!==a.alternate&&(n=a.alternate.memoizedState.cache),(a=a.memoizedState.cache)!==n&&(a.refCount++,null!=n&&mi(n)));break;case 23:break;case 22:var m=a.stateNode;null!==a.memoizedState?4&m._visibility?Qj(n,a,i,o):1&a.mode?Sj(n,a):(m._visibility|=4,Qj(n,a,i,o)):4&m._visibility?Qj(n,a,i,o):(m._visibility|=4,Tj(n,a,i,o,0!=(10256&a.subtreeFlags))),2048&s&&Oj(a.alternate,a);break;case 24:Qj(n,a,i,o),2048&s&&Pj(a.alternate,a);break;default:Qj(n,a,i,o)}}function Tj(n,a,i,o,s){for(s=s&&0!=(10256&a.subtreeFlags),a=a.child;null!==a;){var m=a,y=m.flags;switch(m.tag){case 0:case 11:case 15:Tj(n,m,i,o,s),Nj(m,8);break;case 23:break;case 22:var v=m.stateNode;null!==m.memoizedState?4&v._visibility?Tj(n,m,i,o,s):1&m.mode?Sj(n,m):(v._visibility|=4,Tj(n,m,i,o,s)):(v._visibility|=4,Tj(n,m,i,o,s)),s&&2048&y&&Oj(m.alternate,m);break;case 24:Tj(n,m,i,o,s),s&&2048&y&&Pj(m.alternate,m);break;default:Tj(n,m,i,o,s)}a=a.sibling}}function Sj(n,a){if(10256&a.subtreeFlags)for(a=a.child;null!==a;){var i=a,o=i.flags;switch(i.tag){case 22:Sj(n,i),2048&o&&Oj(i.alternate,i);break;case 24:Sj(n,i),2048&o&&Pj(i.alternate,i);break;default:Sj(n,i)}a=a.sibling}}var nU=8192;function Vj(n){if(n.subtreeFlags&nU)for(n=n.child;null!==n;)Wj(n),n=n.sibling}function Wj(n){switch(n.tag){case 26:Vj(n),n.flags&nU&&null!==n.memoizedState&&Xj(nI,n.memoizedState,n.memoizedProps);break;case 5:default:Vj(n);break;case 3:case 4:var a=nI;nI=Kj(n.stateNode.containerInfo),Vj(n),nI=a;break;case 22:null===n.memoizedState&&(null!==(a=n.alternate)&&null!==a.memoizedState?(a=nU,nU=16777216,Vj(n),nU=a):Vj(n))}}function Yj(n){var a=n.alternate;if(null!==a&&null!==(n=a.child)){a.child=null;do a=n.sibling,n.sibling=null,n=a;while(null!==n)}}function Zj(n){var a=n.deletions;if(0!=(16&n.flags)){if(null!==a)for(var i=0;i<a.length;i++){var o=a[i];nR=o,ak(o,n)}Yj(n)}if(10256&n.subtreeFlags)for(n=n.child;null!==n;)bk(n),n=n.sibling}function bk(n){switch(n.tag){case 0:case 11:case 15:Zj(n),2048&n.flags&&dj(9,n,n.return);break;case 22:var a=n.stateNode;null!==n.memoizedState&&4&a._visibility&&(null===n.return||13!==n.return.tag)?(a._visibility&=-5,ck(n)):Zj(n);break;default:Zj(n)}}function ck(n){var a=n.deletions;if(0!=(16&n.flags)){if(null!==a)for(var i=0;i<a.length;i++){var o=a[i];nR=o,ak(o,n)}Yj(n)}for(n=n.child;null!==n;){switch((a=n).tag){case 0:case 11:case 15:dj(8,a,a.return),ck(a);break;case 22:4&(i=a.stateNode)._visibility&&(i._visibility&=-5,ck(a));break;default:ck(a)}n=n.sibling}}function ak(n,a){for(;null!==nR;){var i=nR;switch(i.tag){case 0:case 11:case 15:dj(8,i,a);break;case 23:case 22:if(null!==i.memoizedState&&null!==i.memoizedState.cachePool){var o=i.memoizedState.cachePool.pool;null!=o&&o.refCount++}break;case 24:mi(i.memoizedState.cache)}if(null!==(o=i.child))o.return=i,nR=o;else for(i=n;null!==nR;){var s=(o=nR).sibling,m=o.return;if(mj(o),o===i){nR=null;break}if(null!==s){s.return=m,nR=s;break}nR=m}}}var nB={getCacheSignal:function(){return bg(nE).controller.signal},getCacheForType:function(n){var a=bg(nE),i=a.data.get(n);return void 0===i&&(i=n(),a.data.set(n,i)),i}},nW="function"==typeof WeakMap?WeakMap:Map,nQ=k.ReactCurrentDispatcher,n$=k.ReactCurrentCache,nV=k.ReactCurrentOwner,nY=k.ReactCurrentBatchConfig,nq=0,nH=null,nZ=null,nK=0,nX=0,nG=null,nJ=!1,n0=0,n1=0,n2=null,n3=0,n4=0,n6=0,n8=0,n5=null,n7=null,n9=0,re=1/0,rt=null,rn=!1,rr=null,ra=null,ru=!1,rc=null,rs=0,rf=0,rd=null,rp=0,rh=null;function Tg(n){return 0==(1&n.mode)?2:0!=(2&nq)&&0!==nK?nK&-nK:null!==nC.transition?0!==(n=tq)?n:sf():0!==(n=eL)?n:n=void 0===(n=window.event)?32:sk(n.type)}function pg(n,a,i){(n===nH&&2===nX||null!==n.cancelPendingCommit)&&(gf(n,0),hf(n,nK,n8)),ob(n,i),(0==(2&nq)||n!==nH)&&(n===nH&&(0==(2&nq)&&(n4|=i),4===n1&&hf(n,nK,n8)),Ze(n),2===i&&0===nq&&0==(1&a.mode)&&(re=em()+500,bf(!0)))}function qf(n,a){if(0!=(6&nq))throw Error(t(327));var i=n.callbackNode;if(cf()&&n.callbackNode!==i)return null;var o=jb(n,n===nH?nK:0);if(0===o)return null;var s=0==(60&o)&&0==(o&n.expiredLanes)&&!a;if(0!==(a=s?tk(n,o):df(n,o)))for(var m=s;;){if(6===a)hf(n,o,0);else{if(s=n.current.alternate,m&&!uk(s)){a=df(n,o),m=!1;continue}if(2===a){var y=lb(n,m=o);0!==y&&(o=y,a=ef(n,m,y))}if(1===a)throw i=n2,gf(n,0),hf(n,o,0),Ze(n),i;n.finishedWork=s,n.finishedLanes=o;e:{switch(m=n,a){case 0:case 1:throw Error(t(345));case 4:if((4194176&o)===o){hf(m,o,n8);break e}break;case 2:case 3:case 5:break;default:throw Error(t(329))}if((62914560&o)===o&&10<(a=n9+300-em())){if(hf(m,o,n8),0!==jb(m,0))break e;m.timeoutHandle=l$(wk.bind(null,m,s,n7,rt,o,n8),a);break e}wk(m,s,n7,rt,o,n8)}}break}return Ze(n),pf(n,em()),n=n.callbackNode===i?qf.bind(null,n):null}function ef(n,a,i){var o=n5,s=n.current.memoizedState.isDehydrated;if(s&&(gf(n,i).flags|=256),2!==(i=df(n,i))){if(nJ&&!s)return n.errorRecoveryDisabledLanes|=a,n4|=a,4;n=n7,n7=o,null!==n&&wi(n)}return i}function wi(n){null===n7?n7=n:n7.push.apply(n7,n)}function wk(n,a,i,o,s,m){if(0==(42&s)&&(lG={stylesheets:null,count:0,unsuspend:yk},Wj(a),null!==(a=zk()))){n.cancelPendingCommit=a(jf.bind(null,n,i,o)),hf(n,s,m);return}jf(n,i,o,m)}function uk(n){for(var a=n;;){if(16384&a.flags){var i=a.updateQueue;if(null!==i&&null!==(i=i.stores))for(var o=0;o<i.length;o++){var s=i[o],m=s.getSnapshot;s=s.value;try{if(!e7(m(),s))return!1}catch(n){return!1}}}if(i=a.child,16384&a.subtreeFlags&&null!==i)i.return=a,a=i;else{if(a===n)break;for(;null===a.sibling;){if(null===a.return||a.return===n)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function hf(n,a,i){a&=~n6,a&=~n4,n.suspendedLanes|=a,n.pingedLanes&=~a;for(var o=n.expirationTimes,s=a;0<s;){var m=31-ex(s),y=1<<m;o[m]=-1,s&=~y}0!==i&&qb(n,i,a)}function Ak(n,a){var i=nq;nq|=1;try{return n(a)}finally{0===(nq=i)&&(re=em()+500,bf(!0))}}function Bk(n){null!==rc&&0===rc.tag&&0==(6&nq)&&cf();var a=nq;nq|=1;var i=nY.transition,o=eL;try{if(nY.transition=null,eL=2,n)return n()}finally{eL=o,nY.transition=i,0==(6&(nq=a))&&bf(!1)}}function Ck(){if(null!==nZ){if(0===nX)var n=nZ.return;else n=nZ,fi(),Xf(n),tT=null,tL=0,n=nZ;for(;null!==n;)Gi(n.alternate,n),n=n.return;nZ=null}}function gf(n,a){n.finishedWork=null,n.finishedLanes=0;var i=n.timeoutHandle;-1!==i&&(n.timeoutHandle=-1,lV(i)),null!==(i=n.cancelPendingCommit)&&(n.cancelPendingCommit=null,i()),Ck(),nH=n,nZ=i=xe(n.current,null),nK=a,nX=0,nG=null,nJ=!1,n1=0,n2=null,n8=n6=n4=n3=0,n7=n5=null,0!=(8&a)&&(a|=32&a);var o=n.entangledLanes;if(0!==o)for(n=n.entanglements,o&=a;0<o;){var s=31-ex(o),m=1<<s;a|=n[s],o&=~m}return n0=a,Pd(),i}function Ek(n,a){tX=null,tH.current=t5,nV.current=null,a===tz?(a=pe(),nX=si()&&0==(134217727&n3)&&0==(134217727&n4)?2:3):a===tP?(a=pe(),nX=4):nX=a===na?8:null!==a&&"object"==typeof a&&"function"==typeof a.then?6:1,nG=a,null===nZ&&(n1=1,n2=a)}function si(){var n=tF.current;return null===n||((4194176&nK)===nK?null===tO:((62914560&nK)===nK||0!=(536870912&nK))&&n===tO)}function Fk(){var n=nQ.current;return nQ.current=t5,null===n?t5:n}function Gk(){var n=n$.current;return n$.current=nB,n}function oh(){n1=4,0==(134217727&n3)&&0==(134217727&n4)||null===nH||hf(nH,nK,n8)}function df(n,a){var i=nq;nq|=2;var o=Fk(),s=Gk();(nH!==n||nK!==a)&&(rt=null,gf(n,a)),a=!1;e:for(;;)try{if(0!==nX&&null!==nZ){var m=nZ,y=nG;switch(nX){case 8:Ck(),n1=6;break e;case 3:case 2:a||null!==tF.current||(a=!0);default:nX=0,nG=null,Hk(m,y)}}Ik();break}catch(a){Ek(n,a)}if(a&&n.shellSuspendCounter++,fi(),nq=i,nQ.current=o,n$.current=s,null!==nZ)throw Error(t(261));return nH=null,nK=0,Pd(),n1}function Ik(){for(;null!==nZ;)Jk(nZ)}function tk(n,a){var i=nq;nq|=2;var o=Fk(),s=Gk();(nH!==n||nK!==a)&&(rt=null,re=em()+500,gf(n,a));e:for(;;)try{if(0!==nX&&null!==nZ){a=nZ;var m=nG;t:switch(nX){case 1:case 6:nX=0,nG=null,Hk(a,m);break;case 2:if(le(m)){nX=0,nG=null,Kk(a);break}a=function(){2===nX&&nH===n&&(nX=7),Ze(n)},m.then(a,a);break e;case 3:nX=7;break e;case 4:nX=5;break e;case 7:le(m)?(nX=0,nG=null,Kk(a)):(nX=0,nG=null,Hk(a,m));break;case 5:switch(nZ.tag){case 5:case 26:case 27:a=nZ,nX=0,nG=null;var y=a.sibling;if(null!==y)nZ=y;else{var v=a.return;null!==v?(nZ=v,Lk(v)):nZ=null}break t}nX=0,nG=null,Hk(a,m);break;case 8:Ck(),n1=6;break e;default:throw Error(t(462))}}Mk();break}catch(a){Ek(n,a)}return(fi(),nQ.current=o,n$.current=s,nq=i,null!==nZ)?0:(nH=null,nK=0,Pd(),n1)}function Mk(){for(;null!==nZ&&!ed();)Jk(nZ)}function Jk(n){var a=rC(n.alternate,n,n0);n.memoizedProps=n.pendingProps,null===a?Lk(n):nZ=a,nV.current=null}function Kk(n){var a=n.alternate;switch(n.tag){case 2:n.tag=0;case 15:case 0:var i=n.type,o=n.pendingProps;o=n.elementType===i?o:Yg(i,o);var s=Xc(i)?e5:e6.current;s=Wc(n,s),a=Hh(a,n,o,i,s,nK);break;case 11:i=n.type.render,o=n.pendingProps,o=n.elementType===i?o:Yg(i,o),a=Hh(a,n,o,i,n.ref,nK);break;case 5:Xf(n);default:Gi(a,n),n=nZ=Di(n,n0),a=rC(a,n,n0)}n.memoizedProps=n.pendingProps,null===a?Lk(n):nZ=a,nV.current=null}function Hk(n,a){fi(),Xf(n),tT=null,tL=0;var i=n.return;if(null===i||null===nH)n1=1,n2=a,nZ=null;else{try{nh(nH,i,n,a,nK)}catch(n){throw nZ=i,n}if(32768&n.flags)e:{do{if(null!==(a=Fi(n.alternate,n))){a.flags&=32767,nZ=a;break e}null!==(n=n.return)&&(n.flags|=32768,n.subtreeFlags=0,n.deletions=null),nZ=n}while(null!==n);n1=6,nZ=null}else Lk(n)}}function Lk(n){var a=n;do{n=a.return;var i=vi(a.alternate,a,n0);if(null!==i){nZ=i;return}if(null!==(a=a.sibling)){nZ=a;return}nZ=a=n}while(null!==a);0===n1&&(n1=5)}function jf(n,a,i,o){var s=eL,m=nY.transition;try{nY.transition=null,eL=2,Ok(n,a,i,s,o)}finally{nY.transition=m,eL=s}return null}function Ok(n,a,i,o,s){do cf();while(null!==rc);if(0!=(6&nq))throw Error(t(327));var m=n.finishedWork,y=n.finishedLanes;if(null===m)return null;if(n.finishedWork=null,n.finishedLanes=0,m===n.current)throw Error(t(177));n.callbackNode=null,n.callbackPriority=0,n.cancelPendingCommit=null;var v=m.lanes|m.childLanes;if(pb(n,v|=tC,s),n===nH&&(nZ=nH=null,nK=0),0==(10256&m.subtreeFlags)&&0==(10256&m.flags)||ru||(ru=!0,rf=v,rd=i,Pk(ek,function(){return cf(),null})),i=0!=(15990&m.flags),0!=(15990&m.subtreeFlags)||i){i=nY.transition,nY.transition=null,s=eL,eL=2;var k=nq;nq|=4,nV.current=null,Xi(n,m),Cj(m,n),Qk(lW),r4=!!lB,lW=lB=null,n.current=m,ij(n,m.alternate,m),ep(),nq=k,eL=s,nY.transition=i}else n.current=m;if(ru?(ru=!1,rc=n,rs=y):Rk(n,v),0===(v=n.pendingLanes)&&(ra=null),bb(m.stateNode,o),Ze(n),null!==a)for(o=n.onRecoverableError,m=0;m<a.length;m++)i={digest:(v=a[m]).digest,componentStack:v.stack},o(v.value,i);if(rn)throw rn=!1,n=rr,rr=null,n;return 0!=(3&rs)&&0!==n.tag&&cf(),v=n.pendingLanes,0!=(4194218&y)&&0!=(2&v)?n===rh?rp++:(rp=0,rh=n):rp=0,bf(!1),null}function Rk(n,a){0==(n.pooledCacheLanes&=a)&&null!=(a=n.pooledCache)&&(n.pooledCache=null,mi(a))}function cf(){if(null!==rc){var n=rc,a=rf;rf=0;var i=ub(rs),o=32>i?32:i;i=nY.transition;var s=eL;try{if(nY.transition=null,eL=o,null===rc)var m=!1;else{o=rd,rd=null;var y=rc,v=rs;if(rc=null,rs=0,0!=(6&nq))throw Error(t(331));var k=nq;if(nq|=4,bk(y.current),Rj(y,y.current,v,o),nq=k,bf(!1),eC&&"function"==typeof eC.onPostCommitFiberRoot)try{eC.onPostCommitFiberRoot(eE,y)}catch(n){}m=!0}return m}finally{eL=s,nY.transition=i,Rk(n,a)}}return!1}function Sk(n,a,i){a=hh(n,a=eh(i,a),2),null!==(n=ae(n,a,2))&&(ob(n,2),Ze(n))}function W(n,a,i){if(3===n.tag)Sk(n,n,i);else for(;null!==a;){if(3===a.tag){Sk(a,n,i);break}if(1===a.tag){var o=a.stateNode;if("function"==typeof a.type.getDerivedStateFromError||"function"==typeof o.componentDidCatch&&(null===ra||!ra.has(o))){n=kh(a,n=eh(i,n),2),null!==(a=ae(a,n,2))&&(ob(a,2),Ze(a));break}}a=a.return}}function qh(n,a,i){var o=n.pingCache;if(null===o){o=n.pingCache=new nW;var s=new Set;o.set(a,s)}else void 0===(s=o.get(a))&&(s=new Set,o.set(a,s));s.has(i)||(nJ=!0,s.add(i),n=Tk.bind(null,n,a,i),a.then(n,n))}function Tk(n,a,i){var o=n.pingCache;null!==o&&o.delete(a),n.pingedLanes|=n.suspendedLanes&i,nH===n&&(nK&i)===i&&(4===n1||3===n1&&(62914560&nK)===nK&&300>em()-n9?0==(2&nq)&&gf(n,0):n6|=i),Ze(n)}function Uk(n,a){0===a&&(a=0==(1&n.mode)?2:mb()),null!==(n=Ud(n,a))&&(ob(n,a),Ze(n))}function Vh(n){var a=n.memoizedState,i=0;null!==a&&(i=a.retryLane),Uk(n,i)}function Aj(n,a){var i=0;switch(n.tag){case 13:var o=n.stateNode,s=n.memoizedState;null!==s&&(i=s.retryLane);break;case 19:o=n.stateNode;break;case 22:o=n.stateNode._retryCache;break;default:throw Error(t(314))}null!==o&&o.delete(a),Uk(n,i)}function Pk(n,a){return eu(n,a)}function Xk(n,a,i,o){this.tag=n,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ud(n,a,i,o){return new Xk(n,a,i,o)}function zh(n){return!(!(n=n.prototype)||!n.isReactComponent)}function Vk(n){if("function"==typeof n)return zh(n)?1:0;if(null!=n){if((n=n.$$typeof)===A)return 11;if(n===$)return 14}return 2}function xe(n,a){var i=n.alternate;return null===i?((i=ud(n.tag,a,n.key,n.mode)).elementType=n.elementType,i.type=n.type,i.stateNode=n.stateNode,i.alternate=n,n.alternate=i):(i.pendingProps=a,i.type=n.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=31457280&n.flags,i.childLanes=n.childLanes,i.lanes=n.lanes,i.child=n.child,i.memoizedProps=n.memoizedProps,i.memoizedState=n.memoizedState,i.updateQueue=n.updateQueue,a=n.dependencies,i.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext},i.sibling=n.sibling,i.index=n.index,i.ref=n.ref,i.refCleanup=n.refCleanup,i}function Di(n,a){n.flags&=31457282;var i=n.alternate;return null===i?(n.childLanes=0,n.lanes=a,n.child=null,n.subtreeFlags=0,n.memoizedProps=null,n.memoizedState=null,n.updateQueue=null,n.dependencies=null,n.stateNode=null):(n.childLanes=i.childLanes,n.lanes=i.lanes,n.child=i.child,n.subtreeFlags=0,n.deletions=null,n.memoizedProps=i.memoizedProps,n.memoizedState=i.memoizedState,n.updateQueue=i.updateQueue,n.type=i.type,a=i.dependencies,n.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext}),n}function ze(n,a,i,o,s,m,y){if(s=2,o=n,"function"==typeof n)zh(n)&&(s=1);else if("string"==typeof n)s=Yk(n,i,et.current)?26:"html"===n||"head"===n||"body"===n?27:5;else e:switch(n){case L:return Be(i.children,m,y,a);case _:s=8,0!=(1&(m|=8))&&(m|=16);break;case M:return(n=ud(12,i,a,2|m)).elementType=M,n.lanes=y,n;case I:return(n=ud(13,i,a,m)).elementType=I,n.lanes=y,n;case Q:return(n=ud(19,i,a,m)).elementType=Q,n.lanes=y,n;case X:return Rh(i,m,y,a);case G:case K:case J:return(n=ud(24,i,a,m)).elementType=J,n.lanes=y,n;default:if("object"==typeof n&&null!==n)switch(n.$$typeof){case R:s=10;break e;case F:s=9;break e;case A:s=11;break e;case $:s=14;break e;case H:s=16,o=null;break e}throw Error(t(130,null==n?n:typeof n,""))}return(a=ud(s,i,a,m)).elementType=n,a.type=o,a.lanes=y,a}function Be(n,a,i,o){return(n=ud(7,n,o,a)).lanes=i,n}function Rh(n,a,i,o){(n=ud(22,n,o,a)).elementType=X,n.lanes=i;var s={_visibility:1,_pendingVisibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null,_current:null,detach:function(){var n=s._current;if(null===n)throw Error(t(456));if(0==(2&s._pendingVisibility)){var a=Ud(n,2);null!==a&&(s._pendingVisibility|=2,pg(a,n,2))}},attach:function(){var n=s._current;if(null===n)throw Error(t(456));if(0!=(2&s._pendingVisibility)){var a=Ud(n,2);null!==a&&(s._pendingVisibility&=-3,pg(a,n,2))}}};return n.stateNode=s,n}function ye(n,a,i){return(n=ud(6,n,null,a)).lanes=i,n}function Ae(n,a,i){return(a=ud(4,null!==n.children?n.children:[],n.key,a)).lanes=i,a.stateNode={containerInfo:n.containerInfo,pendingChildren:null,implementation:n.implementation},a}function Zk(n,a,i,o,s,m){this.tag=a,this.containerInfo=n,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=nb(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.finishedLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=nb(0),this.hiddenUpdates=nb(null),this.identifierPrefix=o,this.onRecoverableError=s,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=m,this.incompleteTransitions=new Map}function $k(n,a,i,o,s,m,y,v,k,S,C){return n=new Zk(n,a,i,v,k,C),1===a?(a=1,!0===m&&(a|=24)):a=0,m=ud(3,null,null,a),n.current=m,m.stateNode=n,a=Ug(),a.refCount++,n.pooledCache=a,a.refCount++,m.memoizedState={element:o,isDehydrated:i,cache:a},Yd(m),n}function al(n,a,i){var o=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:j,key:null==o?null:""+o,children:n,containerInfo:a,implementation:i}}function bl(n){if(!n)return e4;n=n._reactInternals;e:{if(Mc(n)!==n||1!==n.tag)throw Error(t(170));var a=n;do{switch(a.tag){case 3:a=a.stateNode.context;break e;case 1:if(Xc(a.type)){a=a.stateNode.__reactInternalMemoizedMergedChildContext;break e}}a=a.return}while(null!==a);throw Error(t(171))}if(1===n.tag){var i=n.type;if(Xc(i))return $c(n,i,a)}return a}function cl(n,a,i,o,s,m,y,v,k,S,C){return(n=$k(i,o,!0,n,s,m,y,v,k,S,C)).context=bl(null),(s=$d(o=Tg(i=n.current))).callback=null!=a?a:null,ae(i,s,o),n.current.lanes=o,ob(n,o),Ze(n),n}function dl(n,a,i,o){var s=a.current,m=Tg(s);return i=bl(i),null===a.context?a.context=i:a.pendingContext=i,(a=$d(m)).payload={element:n},null!==(o=void 0===o?null:o)&&(a.callback=o),null!==(n=ae(s,a,m))&&(pg(n,s,m),be(n,s,m)),m}function el(n){return(n=n.current).child?(n.child.tag,n.child.stateNode):null}function fl(n){switch(n.tag){case 3:var a=n.stateNode;if(a.current.memoizedState.isDehydrated){var i=ib(a.pendingLanes);0!==i&&(sb(a,i),Ze(a),0==(6&nq)&&(re=em()+500,bf(!1)))}break;case 13:Bk(function(){var a=Ud(n,2);null!==a&&pg(a,n,2)}),gl(n,2)}}function hl(n,a){if(null!==(n=n.memoizedState)&&null!==n.dehydrated){var i=n.retryLane;n.retryLane=0!==i&&i<a?i:a}}function gl(n,a){hl(n,a),(n=n.alternate)&&hl(n,a)}function il(n){if(13===n.tag){var a=Ud(n,67108864);null!==a&&pg(a,n,67108864),gl(n,67108864)}}function jl(){return null}rC=function(n,a,i){if(null!==n){if(n.memoizedProps!==a.pendingProps||e8.current)ni=!0;else{if(0==(n.lanes&i)&&0==(128&a.flags))return ni=!1,$h(n,a,i);ni=0!=(131072&n.flags)}}else ni=!1,ty&&0!=(1048576&a.flags)&&od(a,tr,a.index);switch(a.lanes=0,a.tag){case 2:var o=a.type;Jh(n,a),n=a.pendingProps;var s=Wc(a,e6.current);wh(a,i),s=Mf(null,a,o,n,s,i);var m=Vf();return a.flags|=1,"object"==typeof s&&null!==s&&"function"==typeof s.render&&void 0===s.$$typeof?(a.tag=1,a.memoizedState=null,a.updateQueue=null,Xc(o)?(m=!0,ad(a)):m=!1,a.memoizedState=null!==s.state&&void 0!==s.state?s.state:null,Yd(a),s.updater=nr,a.stateNode=s,s._reactInternals=a,dh(a,o,n,i),a=Kh(null,a,o,!0,m,i)):(a.tag=0,ty&&m&&pd(a),uh(null,a,s,i),a=a.child),a;case 16:o=a.elementType;e:{switch(Jh(n,a),n=a.pendingProps,o=(s=o._init)(o._payload),a.type=o,s=a.tag=Vk(o),n=Yg(o,n),s){case 0:a=Bh(null,a,o,n,i);break e;case 1:a=Ih(null,a,o,n,i);break e;case 11:a=vh(null,a,o,n,i);break e;case 14:a=yh(null,a,o,Yg(o.type,n),i);break e}throw Error(t(306,o,""))}return a;case 0:return o=a.type,s=a.pendingProps,s=a.elementType===o?s:Yg(o,s),Bh(n,a,o,s,i);case 1:return o=a.type,s=a.pendingProps,s=a.elementType===o?s:Yg(o,s),Ih(n,a,o,s,i);case 3:e:{if(Lh(a),null===n)throw Error(t(387));s=a.pendingProps,o=(m=a.memoizedState).element,Zd(n,a),de(a,s,null,i);var y=a.memoizedState;if(ai(a,nE,s=y.cache),s!==m.cache&&hi(a,nE,i),s=y.element,m.isDehydrated){if(m={element:s,isDehydrated:!1,cache:y.cache},a.updateQueue.baseState=m,a.memoizedState=m,256&a.flags){o=eh(Error(t(423)),a),a=Mh(n,a,s,i,o);break e}if(s!==o){o=eh(Error(t(424)),a),a=Mh(n,a,s,i,o);break e}for(th=yd(a.stateNode.containerInfo.firstChild),tp=a,ty=!0,tv=null,tw=!0,i=tD(a,null,s,i),a.child=i;i;)i.flags=-3&i.flags|4096,i=i.sibling}else{if(Kd(),s===o){a=xh(n,a,i);break e}uh(n,a,s,i)}a=a.child}return a;case 26:return Dh(n,a),i=a.memoizedState=Wk(a.type,null===n?null:n.memoizedProps,a.pendingProps),null!==n||ty||null!==i||(i=a.type,n=a.pendingProps,(o=zi(er.current).createElement(i))[eM]=a,o[eR]=n,Ai(o,i,n),Nb(o),a.stateNode=o),null;case 27:return Na(a),null===n&&ty&&(o=a.stateNode=yi(a.type,a.pendingProps,er.current),tp=a,tw=!0,th=yd(o.firstChild)),o=a.pendingProps.children,null!==n||ty?uh(n,a,o,i):a.child=t_(a,null,o,i),Dh(n,a),a.child;case 5:return Na(a),null===n&&ty&&((s=o=th)?wd(a,s)||(Dd(a)&&Ed(),th=Cd(s),m=tp,th&&wd(a,th)?td(m,s):(vd(tp,a),ty=!1,tp=a,th=o)):(Dd(a)&&Ed(),vd(tp,a),ty=!1,tp=a,th=o)),s=a.type,m=a.pendingProps,y=null!==n?n.memoizedProps:null,o=m.children,Id(s,m)?o=null:null!==y&&Id(s,y)&&(a.flags|=32),null!==a.memoizedState&&(s=Mf(n,a,Tf,null,null,i),ei._currentValue=s,ni&&null!==n&&n.memoizedState.memoizedState!==s&&hi(a,ei,i)),Dh(n,a),uh(n,a,o,i),a.child;case 6:return null===n&&ty&&((o=""!==a.pendingProps,(n=i=th)&&o)?zd(a,n)||(Dd(a)&&Ed(),th=Cd(n),o=tp,th&&zd(a,th)?td(o,n):(vd(tp,a),ty=!1,tp=a,th=i)):(Dd(a)&&Ed(),vd(tp,a),ty=!1,tp=a,th=i)),null;case 13:return Qh(n,a,i);case 4:return Ja(a,a.stateNode.containerInfo),o=a.pendingProps,null===n?a.child=t_(a,null,o,i):uh(n,a,o,i),a.child;case 11:return o=a.type,s=a.pendingProps,s=a.elementType===o?s:Yg(o,s),vh(n,a,o,s,i);case 7:return uh(n,a,a.pendingProps,i),a.child;case 8:case 12:return uh(n,a,a.pendingProps.children,i),a.child;case 10:e:{if(o=a.type._context,s=a.pendingProps,m=a.memoizedProps,ai(a,o,y=s.value),null!==m){if(e7(m.value,y)){if(m.children===s.children&&!e8.current){a=xh(n,a,i);break e}}else hi(a,o,i)}uh(n,a,s.children,i),a=a.child}return a;case 9:return s=a.type,o=a.pendingProps.children,wh(a,i),o=o(s=bg(s)),a.flags|=1,uh(n,a,o,i),a.child;case 14:return s=Yg(o=a.type,a.pendingProps),s=Yg(o.type,s),yh(n,a,o,s,i);case 15:return Ah(n,a,a.type,a.pendingProps,i);case 17:return o=a.type,s=a.pendingProps,s=a.elementType===o?s:Yg(o,s),Jh(n,a),a.tag=1,Xc(o)?(n=!0,ad(a)):n=!1,wh(a,i),bh(a,o,s),dh(a,o,s,i),Kh(null,a,o,!0,n,i);case 19:return Zh(n,a,i);case 22:return Ch(n,a,i);case 24:return wh(a,i),o=bg(nE),null===n?(null===(s=Gh())&&(s=nH,m=Ug(),s.pooledCache=m,m.refCount++,null!==m&&(s.pooledCacheLanes|=i),s=m),a.memoizedState={parent:o,cache:s},Yd(a),ai(a,nE,s)):(0!=(n.lanes&i)&&(Zd(n,a),de(a,null,null,i)),s=n.memoizedState,m=a.memoizedState,s.parent!==o?(s={parent:o,cache:o},a.memoizedState=s,0===a.lanes&&(a.memoizedState=a.updateQueue.baseState=s),ai(a,nE,o)):(ai(a,nE,o=m.cache),o!==s.cache&&hi(a,nE,i))),uh(n,a,a.pendingProps.children,i),a.child}throw Error(t(156,a.tag))};var ry=!1;function ll(n,a,i){if(ry)return n(a,i);ry=!0;try{return Ak(n,a,i)}finally{ry=!1,(null!==e2||null!==e3)&&(Bk(),Lc())}}function ml(n,a){var i=n.stateNode;if(null===i)return null;var o=Lb(i);if(null===o)return null;switch(i=o[a],a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(o=!o.disabled)||(o=!("button"===(n=n.type)||"input"===n||"select"===n||"textarea"===n)),n=!o;break;default:n=!1}if(n)return null;if(i&&"function"!=typeof i)throw Error(t(231,a,typeof i));return i}var rv=!1;if(e$)try{var rk={};Object.defineProperty(rk,"passive",{get:function(){rv=!0}}),window.addEventListener("test",rk,rk),window.removeEventListener("test",rk,rk)}catch(n){rv=!1}function pl(n){var a=n.keyCode;return"charCode"in n?0===(n=n.charCode)&&13===a&&(n=13):n=a,10===n&&(n=13),32<=n||13===n?n:0}function ql(){return!0}function rl(){return!1}function sl(n){function b(a,i,o,s,m){for(var y in this._reactName=a,this._targetInst=o,this.type=i,this.nativeEvent=s,this.target=m,this.currentTarget=null,n)n.hasOwnProperty(y)&&(a=n[y],this[y]=a?a(s):s[y]);return this.isDefaultPrevented=(null!=s.defaultPrevented?s.defaultPrevented:!1===s.returnValue)?ql:rl,this.isPropagationStopped=rl,this}return v(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():"unknown"!=typeof n.returnValue&&(n.returnValue=!1),this.isDefaultPrevented=ql)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():"unknown"!=typeof n.cancelBubble&&(n.cancelBubble=!0),this.isPropagationStopped=ql)},persist:function(){},isPersistent:ql}),b}var rw,rS,rE,rC,rx,rz,rP,rN={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(n){return n.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},rT=sl(rN),rL=v({},rN,{view:0,detail:0}),r_=sl(rL),rD=v({},rL,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Al,button:0,buttons:0,relatedTarget:function(n){return void 0===n.relatedTarget?n.fromElement===n.srcElement?n.toElement:n.fromElement:n.relatedTarget},movementX:function(n){return"movementX"in n?n.movementX:(n!==rP&&(rP&&"mousemove"===n.type?(rx=n.screenX-rP.screenX,rz=n.screenY-rP.screenY):rz=rx=0,rP=n),rx)},movementY:function(n){return"movementY"in n?n.movementY:rz}}),rM=sl(rD),rR=sl(v({},rD,{dataTransfer:0})),rF=sl(v({},rL,{relatedTarget:0})),rO=sl(v({},rN,{animationName:0,elapsedTime:0,pseudoElement:0})),rA=sl(v({},rN,{clipboardData:function(n){return"clipboardData"in n?n.clipboardData:window.clipboardData}})),rI=sl(v({},rN,{data:0})),rU={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},rB={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},rW={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Ql(n){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(n):!!(n=rW[n])&&!!a[n]}function Al(){return Ql}var rQ=sl(v({},rL,{key:function(n){if(n.key){var a=rU[n.key]||n.key;if("Unidentified"!==a)return a}return"keypress"===n.type?13===(n=pl(n))?"Enter":String.fromCharCode(n):"keydown"===n.type||"keyup"===n.type?rB[n.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Al,charCode:function(n){return"keypress"===n.type?pl(n):0},keyCode:function(n){return"keydown"===n.type||"keyup"===n.type?n.keyCode:0},which:function(n){return"keypress"===n.type?pl(n):"keydown"===n.type||"keyup"===n.type?n.keyCode:0}})),r$=sl(v({},rD,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),rV=sl(v({},rL,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Al})),rY=sl(v({},rN,{propertyName:0,elapsedTime:0,pseudoElement:0})),rq=sl(v({},rD,{deltaX:function(n){return"deltaX"in n?n.deltaX:"wheelDeltaX"in n?-n.wheelDeltaX:0},deltaY:function(n){return"deltaY"in n?n.deltaY:"wheelDeltaY"in n?-n.wheelDeltaY:"wheelDelta"in n?-n.wheelDelta:0},deltaZ:0,deltaMode:0}));function am(n,a,i,o,s){if("submit"===a&&i&&i.stateNode===s){var m=Lb(s).action,y=o.submitter;if(y&&null!=(a=(a=Lb(y))?a.formAction:y.getAttribute("formAction"))&&(m=a,y=null),"function"==typeof m){var v=new rT("action","action",null,o,s);n.push({event:v,listeners:[{instance:null,listener:function(){if(!o.defaultPrevented){if(v.preventDefault(),y){var n=y.ownerDocument.createElement("input");n.name=y.name,n.value=y.value,y.parentNode.insertBefore(n,y);var a=new FormData(s);n.parentNode.removeChild(n)}else a=new FormData(s);Og(i,{pending:!0,data:a,method:s.method,action:m},m,a)}},currentTarget:s}]})}}}var rH=!1,rZ=null,rK=null,rX=null,rG=new Map,rJ=new Map,r0=[],r1="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function jm(n,a){switch(n){case"focusin":case"focusout":rZ=null;break;case"dragenter":case"dragleave":rK=null;break;case"mouseover":case"mouseout":rX=null;break;case"pointerover":case"pointerout":rG.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":rJ.delete(a.pointerId)}}function km(n,a,i,o,s,m){return null===n||n.nativeEvent!==m?(n={blockedOn:a,domEventName:i,eventSystemFlags:o,nativeEvent:m,targetContainers:[s]},null!==a&&null!==(a=Jb(a))&&il(a)):(n.eventSystemFlags|=o,a=n.targetContainers,null!==s&&-1===a.indexOf(s)&&a.push(s)),n}function lm(n,a,i,o,s){switch(a){case"focusin":return rZ=km(rZ,n,a,i,o,s),!0;case"dragenter":return rK=km(rK,n,a,i,o,s),!0;case"mouseover":return rX=km(rX,n,a,i,o,s),!0;case"pointerover":var m=s.pointerId;return rG.set(m,km(rG.get(m)||null,n,a,i,o,s)),!0;case"gotpointercapture":return m=s.pointerId,rJ.set(m,km(rJ.get(m)||null,n,a,i,o,s)),!0}return!1}function mm(n){var a=Hb(n.target);if(null!==a){var i=Mc(a);if(null!==i){if(13===(a=i.tag)){if(null!==(a=Nc(i))){n.blockedOn=a,tb(n.priority,function(){if(13===i.tag){var n=Tg(i),a=Ud(i,n);null!==a&&pg(a,i,n),gl(i,n)}});return}}else if(3===a&&i.stateNode.current.memoizedState.isDehydrated){n.blockedOn=3===i.tag?i.stateNode.containerInfo:null;return}}}n.blockedOn=null}function nm(n){if(null!==n.blockedOn)return!1;for(var a=n.targetContainers;0<a.length;){var i=om(n.nativeEvent);if(null!==i)return null!==(a=Jb(i))&&il(a),n.blockedOn=i,!1;var o=new(i=n.nativeEvent).constructor(i.type,i);e1=o,i.target.dispatchEvent(o),e1=null,a.shift()}return!0}function pm(n,a,i){nm(n)&&i.delete(a)}function qm(){rH=!1,null!==rZ&&nm(rZ)&&(rZ=null),null!==rK&&nm(rK)&&(rK=null),null!==rX&&nm(rX)&&(rX=null),rG.forEach(pm),rJ.forEach(pm)}function rm(n,a){n.blockedOn===a&&(n.blockedOn=null,rH||(rH=!0,m.unstable_scheduleCallback(m.unstable_NormalPriority,qm)))}var r2=null;function tm(n){r2!==n&&(r2=n,m.unstable_scheduleCallback(m.unstable_NormalPriority,function(){r2===n&&(r2=null);for(var a=0;a<n.length;a+=3){var i=n[a],o=n[a+1],s=n[a+2];if("function"!=typeof o){if(null===um(o||i))continue;break}var m=Jb(i);null!==m&&(n.splice(a,3),a-=3,Og(m,{pending:!0,data:s,method:i.method,action:o},o,s))}}))}function xj(n){function b(a){return rm(a,n)}null!==rZ&&rm(rZ,n),null!==rK&&rm(rK,n),null!==rX&&rm(rX,n),rG.forEach(b),rJ.forEach(b);for(var a=0;a<r0.length;a++){var i=r0[a];i.blockedOn===n&&(i.blockedOn=null)}for(;0<r0.length&&null===(a=r0[0]).blockedOn;)mm(a),null===a.blockedOn&&r0.shift();if(null!=(a=n.getRootNode().$$reactFormReplay))for(i=0;i<a.length;i+=3){var o=a[i],s=a[i+1],m=Lb(o);if("function"==typeof s)m||tm(a);else if(m){var y=null;if(s&&s.hasAttribute("formAction")){if(o=s,m=Lb(s))y=m.formAction;else if(null!==um(o))continue}else y=m.action;"function"==typeof y?a[i+1]=y:(a.splice(i,3),i-=3),tm(a)}}}var r3=k.ReactCurrentBatchConfig,r4=!0;function wm(n,a,i,o){var s=eL,m=r3.transition;r3.transition=null;try{eL=2,xm(n,a,i,o)}finally{eL=s,r3.transition=m}}function ym(n,a,i,o){var s=eL,m=r3.transition;r3.transition=null;try{eL=8,xm(n,a,i,o)}finally{eL=s,r3.transition=m}}function xm(n,a,i,o){if(r4){var s=om(o);if(null===s)zm(n,a,o,r6,i),jm(n,o);else if(lm(s,n,a,i,o))o.stopPropagation();else if(jm(n,o),4&a&&-1<r1.indexOf(n)){for(;null!==s;){var m=Jb(s);if(null!==m&&fl(m),null===(m=om(o))&&zm(n,a,o,r6,i),m===s)break;s=m}null!==s&&o.stopPropagation()}else zm(n,a,o,null,i)}}function om(n){return um(n=Gc(n))}var r6=null;function um(n){if(r6=null,null!==(n=Hb(n))){var a=Mc(n);if(null===a)n=null;else{var i=a.tag;if(13===i){if(null!==(n=Nc(a)))return n;n=null}else if(3===i){if(a.stateNode.current.memoizedState.isDehydrated)return 3===a.tag?a.stateNode.containerInfo:null;n=null}else a!==n&&(n=null)}}return r6=n,null}function sk(n){switch(n){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch(eb()){case ey:return 2;case ev:return 8;case ek:case ew:return 32;case eS:return 268435456;default:return 32}default:return 32}}var r8=null,r5=null,r7=null;function Em(){if(r7)return r7;var n,a,i=r5,o=i.length,s="value"in r8?r8.value:r8.textContent,m=s.length;for(n=0;n<o&&i[n]===s[n];n++);var y=o-n;for(a=1;a<=y&&i[o-a]===s[m-a];a++);return r7=s.slice(n,1<a?1-a:void 0)}var r9=[9,13,27,32],lt=e$&&"CompositionEvent"in window,lr=null;e$&&"documentMode"in document&&(lr=document.documentMode);var la=e$&&"TextEvent"in window&&!lr,li=e$&&(!lt||lr&&8<lr&&11>=lr),lo=!1;function Nm(n,a){switch(n){case"keyup":return -1!==r9.indexOf(a.keyCode);case"keydown":return 229!==a.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Om(n){return"object"==typeof(n=n.detail)&&"data"in n?n.data:null}var lu=!1;function Qm(n,a){switch(n){case"compositionend":return Om(a);case"keypress":if(32!==a.which)return null;return lo=!0," ";case"textInput":return" "===(n=a.data)&&lo?null:n;default:return null}}function Rm(n,a){if(lu)return"compositionend"===n||!lt&&Nm(n,a)?(n=Em(),r7=r5=r8=null,lu=!1,n):null;switch(n){case"paste":default:return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return li&&"ko"!==a.locale?null:a.data}}var ls={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Tm(n){var a=n&&n.nodeName&&n.nodeName.toLowerCase();return"input"===a?!!ls[n.type]:"textarea"===a}function Um(n,a,i,o){Kc(o),0<(a=Vm(a,"onChange")).length&&(i=new rT("onChange","change",null,i,o),n.push({event:i,listeners:a}))}var lf=null,ld=null;function Ym(n){Zm(n,0)}function $m(n){if(kc(Kb(n)))return n}function an(n,a){if("change"===n)return a}var lp=!1;if(e$){if(e$){var lh="oninput"in document;if(!lh){var ly=document.createElement("div");ly.setAttribute("oninput","return;"),lh="function"==typeof ly.oninput}o=lh}else o=!1;lp=o&&(!document.documentMode||9<document.documentMode)}function fn(){lf&&(lf.detachEvent("onpropertychange",gn),ld=lf=null)}function gn(n){if("value"===n.propertyName&&$m(ld)){var a=[];Um(a,ld,n,Gc(n)),ll(Ym,a)}}function hn(n,a,i){"focusin"===n?(fn(),lf=a,ld=i,lf.attachEvent("onpropertychange",gn)):"focusout"===n&&fn()}function jn(n){if("selectionchange"===n||"keyup"===n||"keydown"===n)return $m(ld)}function kn(n,a){if("click"===n)return $m(a)}function ln(n,a){if("input"===n||"change"===n)return $m(a)}function mn(n){for(;n&&n.firstChild;)n=n.firstChild;return n}function nn(n,a){var i,o=mn(n);for(n=0;o;){if(3===o.nodeType){if(i=n+o.textContent.length,n<=a&&i>=a)return{node:o,offset:a-n};n=i}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=mn(o)}}function on(n,a){return!!n&&!!a&&(n===a||(!n||3!==n.nodeType)&&(a&&3===a.nodeType?on(n,a.parentNode):"contains"in n?n.contains(a):!!n.compareDocumentPosition&&!!(16&n.compareDocumentPosition(a))))}function $i(){for(var n=window,a=lc();a instanceof n.HTMLIFrameElement;){try{var i="string"==typeof a.contentWindow.location.href}catch(n){i=!1}if(i)n=a.contentWindow;else break;a=lc(n.document)}return a}function aj(n){var a=n&&n.nodeName&&n.nodeName.toLowerCase();return a&&("input"===a&&("text"===n.type||"search"===n.type||"tel"===n.type||"url"===n.type||"password"===n.type)||"textarea"===a||"true"===n.contentEditable)}function Qk(n){var a=$i(),i=n.focusedElem,o=n.selectionRange;if(a!==i&&i&&i.ownerDocument&&on(i.ownerDocument.documentElement,i)){if(null!==o&&aj(i)){if(a=o.start,void 0===(n=o.end)&&(n=a),"selectionStart"in i)i.selectionStart=a,i.selectionEnd=Math.min(n,i.value.length);else if((n=(a=i.ownerDocument||document)&&a.defaultView||window).getSelection){n=n.getSelection();var s=i.textContent.length,m=Math.min(o.start,s);o=void 0===o.end?m:Math.min(o.end,s),!n.extend&&m>o&&(s=o,o=m,m=s),s=nn(i,m);var y=nn(i,o);s&&y&&(1!==n.rangeCount||n.anchorNode!==s.node||n.anchorOffset!==s.offset||n.focusNode!==y.node||n.focusOffset!==y.offset)&&((a=a.createRange()).setStart(s.node,s.offset),n.removeAllRanges(),m>o?(n.addRange(a),n.extend(y.node,y.offset)):(a.setEnd(y.node,y.offset),n.addRange(a)))}}for(a=[],n=i;n=n.parentNode;)1===n.nodeType&&a.push({element:n,left:n.scrollLeft,top:n.scrollTop});for("function"==typeof i.focus&&i.focus(),i=0;i<a.length;i++)(n=a[i]).element.scrollLeft=n.left,n.element.scrollTop=n.top}}var lv=e$&&"documentMode"in document&&11>=document.documentMode,lk=null,lw=null,lS=null,lE=!1;function un(n,a,i){var o=i.window===i?i.document:9===i.nodeType?i:i.ownerDocument;lE||null==lk||lk!==lc(o)||(o="selectionStart"in(o=lk)&&aj(o)?{start:o.selectionStart,end:o.selectionEnd}:{anchorNode:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset},lS&&he(lS,o)||(lS=o,0<(o=Vm(lw,"onSelect")).length&&(a=new rT("onSelect","select",null,a,i),n.push({event:a,listeners:o}),a.target=lk)))}function vn(n,a){var i={};return i[n.toLowerCase()]=a.toLowerCase(),i["Webkit"+n]="webkit"+a,i["Moz"+n]="moz"+a,i}var lC={animationend:vn("Animation","AnimationEnd"),animationiteration:vn("Animation","AnimationIteration"),animationstart:vn("Animation","AnimationStart"),transitionend:vn("Transition","TransitionEnd")},lx={},lz={};function zn(n){if(lx[n])return lx[n];if(!lC[n])return n;var a,i=lC[n];for(a in i)if(i.hasOwnProperty(a)&&a in lz)return lx[n]=i[a];return n}e$&&(lz=document.createElement("div").style,"AnimationEvent"in window||(delete lC.animationend.animation,delete lC.animationiteration.animation,delete lC.animationstart.animation),"TransitionEvent"in window||delete lC.transitionend.transition);var lP=zn("animationend"),lN=zn("animationiteration"),lT=zn("animationstart"),lL=zn("transitionend"),l_=new Map,lD="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll scrollEnd toggle touchMove waiting wheel".split(" ");function Gn(n,a){l_.set(n,a),Qb(a,[n])}for(var lM=0;lM<lD.length;lM++){var lR=lD[lM];Gn(lR.toLowerCase(),"on"+(lR[0].toUpperCase()+lR.slice(1)))}Gn(lP,"onAnimationEnd"),Gn(lN,"onAnimationIteration"),Gn(lT,"onAnimationStart"),Gn("dblclick","onDoubleClick"),Gn("focusin","onFocus"),Gn("focusout","onBlur"),Gn(lL,"onTransitionEnd"),Rb("onMouseEnter",["mouseout","mouseover"]),Rb("onMouseLeave",["mouseout","mouseover"]),Rb("onPointerEnter",["pointerout","pointerover"]),Rb("onPointerLeave",["pointerout","pointerover"]),Qb("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Qb("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Qb("onBeforeInput",["compositionend","keypress","textInput","paste"]),Qb("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Qb("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Qb("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var lF="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),lO=new Set("cancel close invalid load scroll scrollend toggle".split(" ").concat(lF));function Nn(n,a,i){var o=n.type||"unknown-event";n.currentTarget=i,Oi(o,a,void 0,n),n.currentTarget=null}function Zm(n,a){a=0!=(4&a);for(var i=0;i<n.length;i++){var o=n[i],s=o.event;o=o.listeners;e:{var m=void 0;if(a)for(var y=o.length-1;0<=y;y--){var v=o[y],k=v.instance,S=v.currentTarget;if(v=v.listener,k!==m&&s.isPropagationStopped())break e;Nn(s,v,S),m=k}else for(y=0;y<o.length;y++){if(k=(v=o[y]).instance,S=v.currentTarget,v=v.listener,k!==m&&s.isPropagationStopped())break e;Nn(s,v,S),m=k}}}if(nN)throw n=nT,nN=!1,nT=null,n}function Y(n,a){var i=a[eO];void 0===i&&(i=a[eO]=new Set);var o=n+"__bubble";i.has(o)||(On(a,n,2,!1),i.add(o))}function Pn(n,a,i){var o=0;a&&(o|=4),On(i,n,o,a)}var lA="_reactListening"+Math.random().toString(36).slice(2);function Ci(n){if(!n[lA]){n[lA]=!0,eW.forEach(function(a){"selectionchange"!==a&&(lO.has(a)||Pn(a,!1,n),Pn(a,!0,n))});var a=9===n.nodeType?n:n.ownerDocument;null===a||a[lA]||(a[lA]=!0,Pn("selectionchange",!1,a))}}function On(n,a,i,o){switch(sk(a)){case 2:var s=wm;break;case 8:s=ym;break;default:s=xm}i=s.bind(null,a,i,n),s=void 0,rv&&("touchstart"===a||"touchmove"===a||"wheel"===a)&&(s=!0),o?void 0!==s?n.addEventListener(a,i,{capture:!0,passive:s}):n.addEventListener(a,i,!0):void 0!==s?n.addEventListener(a,i,{passive:s}):n.addEventListener(a,i,!1)}function zm(n,a,i,o,s){var m=o;if(0==(1&a)&&0==(2&a)&&null!==o)e:for(;;){if(null===o)return;var y=o.tag;if(3===y||4===y){var v=o.stateNode.containerInfo;if(v===s||8===v.nodeType&&v.parentNode===s)break;if(4===y)for(y=o.return;null!==y;){var k=y.tag;if((3===k||4===k)&&((k=y.stateNode.containerInfo)===s||8===k.nodeType&&k.parentNode===s))return;y=y.return}for(;null!==v;){if(null===(y=Hb(v)))return;if(5===(k=y.tag)||6===k||26===k||27===k){o=m=y;continue e}v=v.parentNode}}o=o.return}ll(function(){var o=m,s=Gc(i),y=[];e:{var v=l_.get(n);if(void 0!==v){var k=rT,S=n;switch(n){case"keypress":if(0===pl(i))break e;case"keydown":case"keyup":k=rQ;break;case"focusin":S="focus",k=rF;break;case"focusout":S="blur",k=rF;break;case"beforeblur":case"afterblur":k=rF;break;case"click":if(2===i.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":k=rM;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":k=rR;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":k=rV;break;case lP:case lN:case lT:k=rO;break;case lL:k=rY;break;case"scroll":case"scrollend":k=r_;break;case"wheel":k=rq;break;case"copy":case"cut":case"paste":k=rA;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":k=r$}var C=0!=(4&a),x=!C&&("scroll"===n||"scrollend"===n),P=C?null!==v?v+"Capture":null:v;C=[];for(var N,j=o;null!==j;){var L=j;if(N=L.stateNode,5!==(L=L.tag)&&26!==L&&27!==L||null===N||null===P||null!=(L=ml(j,P))&&C.push(Rn(j,L,N)),x)break;j=j.return}0<C.length&&(v=new k(v,S,null,i,s),y.push({event:v,listeners:C}))}}if(0==(7&a)){if(v="mouseover"===n||"pointerover"===n,k="mouseout"===n||"pointerout"===n,!(v&&i!==e1&&(S=i.relatedTarget||i.fromElement)&&(Hb(S)||S[eF]))&&(k||v)&&(v=s.window===s?s:(v=s.ownerDocument)?v.defaultView||v.parentWindow:window,k?(S=i.relatedTarget||i.toElement,k=o,null!==(S=S?Hb(S):null)&&(x=Mc(S),C=S.tag,S!==x||5!==C&&27!==C&&6!==C)&&(S=null)):(k=null,S=o),k!==S)){if(C=rM,L="onMouseLeave",P="onMouseEnter",j="mouse",("pointerout"===n||"pointerover"===n)&&(C=r$,L="onPointerLeave",P="onPointerEnter",j="pointer"),x=null==k?v:Kb(k),N=null==S?v:Kb(S),(v=new C(L,j+"leave",k,i,s)).target=x,v.relatedTarget=N,L=null,Hb(s)===o&&((C=new C(P,j+"enter",S,i,s)).target=N,C.relatedTarget=x,L=C),x=L,k&&S)t:{for(C=k,P=S,j=0,N=C;N;N=Sn(N))j++;for(N=0,L=P;L;L=Sn(L))N++;for(;0<j-N;)C=Sn(C),j--;for(;0<N-j;)P=Sn(P),N--;for(;j--;){if(C===P||null!==P&&C===P.alternate)break t;C=Sn(C),P=Sn(P)}C=null}else C=null;null!==k&&Tn(y,v,k,C,!1),null!==S&&null!==x&&Tn(y,x,S,C,!0)}e:{if("select"===(k=(v=o?Kb(o):window).nodeName&&v.nodeName.toLowerCase())||"input"===k&&"file"===v.type)var _,M=an;else if(Tm(v)){if(lp)M=ln;else{M=jn;var R=hn}}else(k=v.nodeName)&&"input"===k.toLowerCase()&&("checkbox"===v.type||"radio"===v.type)&&(M=kn);if(M&&(M=M(n,o))){Um(y,M,i,s);break e}R&&R(n,v,o),"focusout"===n&&o&&"number"===v.type&&null!=o.memoizedProps.value&&pc(v,"number",v.value)}switch(R=o?Kb(o):window,n){case"focusin":(Tm(R)||"true"===R.contentEditable)&&(lk=R,lw=o,lS=null);break;case"focusout":lS=lw=lk=null;break;case"mousedown":lE=!0;break;case"contextmenu":case"mouseup":case"dragend":lE=!1,un(y,i,s);break;case"selectionchange":if(lv)break;case"keydown":case"keyup":un(y,i,s)}if(lt)t:{switch(n){case"compositionstart":var F="onCompositionStart";break t;case"compositionend":F="onCompositionEnd";break t;case"compositionupdate":F="onCompositionUpdate";break t}F=void 0}else lu?Nm(n,i)&&(F="onCompositionEnd"):"keydown"===n&&229===i.keyCode&&(F="onCompositionStart");F&&(li&&"ko"!==i.locale&&(lu||"onCompositionStart"!==F?"onCompositionEnd"===F&&lu&&(_=Em()):(r5="value"in(r8=s)?r8.value:r8.textContent,lu=!0)),0<(R=Vm(o,F)).length&&(F=new rI(F,n,null,i,s),y.push({event:F,listeners:R}),_?F.data=_:null!==(_=Om(i))&&(F.data=_))),(_=la?Qm(n,i):Rm(n,i))&&0<(F=Vm(o,"onBeforeInput")).length&&(R=new rI("onBeforeInput","beforeinput",null,i,s),y.push({event:R,listeners:F}),R.data=_),am(y,n,o,i,s)}Zm(y,a)})}function Rn(n,a,i){return{instance:n,listener:a,currentTarget:i}}function Vm(n,a){for(var i=a+"Capture",o=[];null!==n;){var s=n,m=s.stateNode;5!==(s=s.tag)&&26!==s&&27!==s||null===m||(null!=(s=ml(n,i))&&o.unshift(Rn(n,s,m)),null!=(s=ml(n,a))&&o.push(Rn(n,s,m))),n=n.return}return o}function Sn(n){if(null===n)return null;do n=n.return;while(n&&5!==n.tag&&27!==n.tag);return n||null}function Tn(n,a,i,o,s){for(var m=a._reactName,y=[];null!==i&&i!==o;){var v=i,k=v.alternate,S=v.stateNode;if(v=v.tag,null!==k&&k===o)break;5!==v&&26!==v&&27!==v||null===S||(k=S,s?null!=(S=ml(i,m))&&y.unshift(Rn(i,S,k)):s||null!=(S=ml(i,m))&&y.push(Rn(i,S,k))),i=i.return}0!==y.length&&n.push({event:a,listeners:y})}var lI=/\r\n?/g,lU=/\u0000|\uFFFD/g;function Wn(n){return("string"==typeof n?n:""+n).replace(lI,"\n").replace(lU,"")}function Bi(n,a,i){if(a=Wn(a),Wn(n)!==a&&i)throw Error(t(425))}function qj(){}function Z(n,a,i,o,s,m){switch(i){case"children":"string"==typeof o?"body"===a||"textarea"===a&&""===o||zc(n,o):"number"==typeof o&&"body"!==a&&zc(n,""+o);break;case"className":Yb(n,"class",o);break;case"tabIndex":Yb(n,"tabindex",o);break;case"dir":case"role":case"viewBox":case"width":case"height":Yb(n,i,o);break;case"style":Cc(n,o,m);break;case"src":case"href":if(null==o||"function"==typeof o||"symbol"==typeof o||"boolean"==typeof o){n.removeAttribute(i);break}n.setAttribute(i,""+o);break;case"action":case"formAction":if("function"==typeof o){n.setAttribute(i,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}if("function"==typeof m&&("formAction"===i?("input"!==a&&Z(n,a,"name",s.name,s,null),Z(n,a,"formEncType",s.formEncType,s,null),Z(n,a,"formMethod",s.formMethod,s,null),Z(n,a,"formTarget",s.formTarget,s,null)):(Z(n,a,"encType",s.encType,s,null),Z(n,a,"method",s.method,s,null),Z(n,a,"target",s.target,s,null))),null==o||"symbol"==typeof o||"boolean"==typeof o){n.removeAttribute(i);break}n.setAttribute(i,""+o);break;case"onClick":null!=o&&(n.onclick=qj);break;case"onScroll":null!=o&&Y("scroll",n);break;case"onScrollEnd":null!=o&&Y("scrollend",n);break;case"dangerouslySetInnerHTML":if(null!=o){if("object"!=typeof o||!("__html"in o))throw Error(t(61));if(null!=(o=o.__html)){if(null!=s.children)throw Error(t(60));eG(n,o)}}break;case"multiple":n.multiple=o&&"function"!=typeof o&&"symbol"!=typeof o;break;case"muted":n.muted=o&&"function"!=typeof o&&"symbol"!=typeof o;break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"autoFocus":break;case"xlinkHref":if(null==o||"function"==typeof o||"boolean"==typeof o||"symbol"==typeof o){n.removeAttribute("xlink:href");break}n.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",""+o);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":null!=o&&"function"!=typeof o&&"symbol"!=typeof o?n.setAttribute(i,""+o):n.removeAttribute(i);break;case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":o&&"function"!=typeof o&&"symbol"!=typeof o?n.setAttribute(i,""):n.removeAttribute(i);break;case"capture":case"download":!0===o?n.setAttribute(i,""):!1!==o&&null!=o&&"function"!=typeof o&&"symbol"!=typeof o?n.setAttribute(i,o):n.removeAttribute(i);break;case"cols":case"rows":case"size":case"span":null!=o&&"function"!=typeof o&&"symbol"!=typeof o&&!isNaN(o)&&1<=o?n.setAttribute(i,o):n.removeAttribute(i);break;case"rowSpan":case"start":null==o||"function"==typeof o||"symbol"==typeof o||isNaN(o)?n.removeAttribute(i):n.setAttribute(i,o);break;case"xlinkActuate":Zb(n,"http://www.w3.org/1999/xlink","xlink:actuate",o);break;case"xlinkArcrole":Zb(n,"http://www.w3.org/1999/xlink","xlink:arcrole",o);break;case"xlinkRole":Zb(n,"http://www.w3.org/1999/xlink","xlink:role",o);break;case"xlinkShow":Zb(n,"http://www.w3.org/1999/xlink","xlink:show",o);break;case"xlinkTitle":Zb(n,"http://www.w3.org/1999/xlink","xlink:title",o);break;case"xlinkType":Zb(n,"http://www.w3.org/1999/xlink","xlink:type",o);break;case"xmlBase":Zb(n,"http://www.w3.org/XML/1998/namespace","xml:base",o);break;case"xmlLang":Zb(n,"http://www.w3.org/XML/1998/namespace","xml:lang",o);break;case"xmlSpace":Zb(n,"http://www.w3.org/XML/1998/namespace","xml:space",o);break;case"is":Xb(n,"is",o);break;default:2<i.length&&("o"===i[0]||"O"===i[0])&&("n"===i[1]||"N"===i[1])||Xb(n,s=e0.get(i)||i,o)}}function Xn(n,a,i,o,s,m){switch(i){case"style":Cc(n,o,m);break;case"dangerouslySetInnerHTML":if(null!=o){if("object"!=typeof o||!("__html"in o))throw Error(t(61));if(null!=(a=o.__html)){if(null!=s.children)throw Error(t(60));eG(n,a)}}break;case"children":"string"==typeof o?zc(n,o):"number"==typeof o&&zc(n,""+o);break;case"onScroll":null!=o&&Y("scroll",n);break;case"onScrollEnd":null!=o&&Y("scrollend",n);break;case"onClick":null!=o&&(n.onclick=qj);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":break;default:eQ.hasOwnProperty(i)||("boolean"==typeof o&&(o=""+o),Xb(n,i,o))}}function Ai(n,a,i){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":Y("invalid",n);var o=null,s=null,m=null,y=null,v=null,k=null;for(C in i)if(i.hasOwnProperty(C)){var S=i[C];if(null!=S)switch(C){case"name":o=S;break;case"type":s=S;break;case"checked":v=S;break;case"defaultChecked":k=S;break;case"value":m=S;break;case"defaultValue":y=S;break;case"children":case"dangerouslySetInnerHTML":if(null!=S)throw Error(t(137,a));break;default:Z(n,a,C,S,i,null)}}qc(n,m,y,v,k,s,o,!1),jc(n);return;case"select":Y("invalid",n);var C=s=m=null;for(o in i)if(i.hasOwnProperty(o)&&null!=(y=i[o]))switch(o){case"value":m=y;break;case"defaultValue":s=y;break;case"multiple":C=y;default:Z(n,a,o,y,i,null)}a=m,i=s,n.multiple=!!C,null!=a?sc(n,!!C,a,!1):null!=i&&sc(n,!!C,i,!0);return;case"textarea":for(s in Y("invalid",n),m=o=C=null,i)if(i.hasOwnProperty(s)&&null!=(y=i[s]))switch(s){case"value":C=y;break;case"defaultValue":o=y;break;case"children":m=y;break;case"dangerouslySetInnerHTML":if(null!=y)throw Error(t(91));break;default:Z(n,a,s,y,i,null)}uc(n,C,o,m),jc(n);return;case"option":for(y in i)i.hasOwnProperty(y)&&null!=(C=i[y])&&("selected"===y?n.selected=C&&"function"!=typeof C&&"symbol"!=typeof C:Z(n,a,y,C,i,null));return;case"dialog":Y("cancel",n),Y("close",n);break;case"iframe":case"object":Y("load",n);break;case"video":case"audio":for(C=0;C<lF.length;C++)Y(lF[C],n);break;case"image":Y("error",n),Y("load",n);break;case"details":Y("toggle",n);break;case"embed":case"source":case"img":case"link":Y("error",n),Y("load",n);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(v in i)if(i.hasOwnProperty(v)&&null!=(C=i[v]))switch(v){case"children":case"dangerouslySetInnerHTML":throw Error(t(137,a));default:Z(n,a,v,C,i,null)}return;default:if(Dc(a)){for(k in i)i.hasOwnProperty(k)&&null!=(C=i[k])&&Xn(n,a,k,C,i,null);return}}for(m in i)i.hasOwnProperty(m)&&null!=(C=i[m])&&Z(n,a,m,C,i,null)}function Ij(n,a,i,o){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var s=null,m=null,y=null,v=null,k=null,S=null,C=null;for(N in i){var x=i[N];if(i.hasOwnProperty(N)&&null!=x)switch(N){case"checked":case"value":break;case"defaultValue":k=x;default:o.hasOwnProperty(N)||Z(n,a,N,null,o,x)}}for(var P in o){var N=o[P];if(x=i[P],o.hasOwnProperty(P)&&(null!=N||null!=x))switch(P){case"type":m=N;break;case"name":s=N;break;case"checked":S=N;break;case"defaultChecked":C=N;break;case"value":y=N;break;case"defaultValue":v=N;break;case"children":case"dangerouslySetInnerHTML":if(null!=N)throw Error(t(137,a));break;default:N!==x&&Z(n,a,P,N,o,x)}}oc(n,y,v,k,S,C,m,s);return;case"select":for(m in N=y=v=P=null,i)if(k=i[m],i.hasOwnProperty(m)&&null!=k)switch(m){case"value":break;case"multiple":N=k;default:o.hasOwnProperty(m)||Z(n,a,m,null,o,k)}for(s in o)if(m=o[s],k=i[s],o.hasOwnProperty(s)&&(null!=m||null!=k))switch(s){case"value":P=m;break;case"defaultValue":v=m;break;case"multiple":y=m;default:m!==k&&Z(n,a,s,m,o,k)}a=v,i=y,o=N,null!=P?sc(n,!!i,P,!1):!!o!=!!i&&(null!=a?sc(n,!!i,a,!0):sc(n,!!i,i?[]:"",!1));return;case"textarea":for(v in N=P=null,i)if(s=i[v],i.hasOwnProperty(v)&&null!=s&&!o.hasOwnProperty(v))switch(v){case"value":case"children":break;default:Z(n,a,v,null,o,s)}for(y in o)if(s=o[y],m=i[y],o.hasOwnProperty(y)&&(null!=s||null!=m))switch(y){case"value":P=s;break;case"defaultValue":N=s;break;case"children":break;case"dangerouslySetInnerHTML":if(null!=s)throw Error(t(91));break;default:s!==m&&Z(n,a,y,s,o,m)}tc(n,P,N);return;case"option":for(var j in i)P=i[j],i.hasOwnProperty(j)&&null!=P&&!o.hasOwnProperty(j)&&("selected"===j?n.selected=!1:Z(n,a,j,null,o,P));for(k in o)P=o[k],N=i[k],o.hasOwnProperty(k)&&P!==N&&(null!=P||null!=N)&&("selected"===k?n.selected=P&&"function"!=typeof P&&"symbol"!=typeof P:Z(n,a,k,P,o,N));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var L in i)P=i[L],i.hasOwnProperty(L)&&null!=P&&!o.hasOwnProperty(L)&&Z(n,a,L,null,o,P);for(S in o)if(P=o[S],N=i[S],o.hasOwnProperty(S)&&P!==N&&(null!=P||null!=N))switch(S){case"children":case"dangerouslySetInnerHTML":if(null!=P)throw Error(t(137,a));break;default:Z(n,a,S,P,o,N)}return;default:if(Dc(a)){for(var _ in i)P=i[_],i.hasOwnProperty(_)&&null!=P&&!o.hasOwnProperty(_)&&Xn(n,a,_,null,o,P);for(C in o)P=o[C],N=i[C],o.hasOwnProperty(C)&&P!==N&&(null!=P||null!=N)&&Xn(n,a,C,P,o,N);return}}for(var M in i)P=i[M],i.hasOwnProperty(M)&&null!=P&&!o.hasOwnProperty(M)&&Z(n,a,M,null,o,P);for(x in o)P=o[x],N=i[x],o.hasOwnProperty(x)&&P!==N&&(null!=P||null!=N)&&Z(n,a,x,P,o,N)}var lB=null,lW=null;function zi(n){return 9===n.nodeType?n:n.ownerDocument}function Ka(n){switch(n){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function La(n,a){if(0===n)switch(a){case"svg":return 1;case"math":return 2;default:return 0}return 1===n&&"foreignObject"===a?0:n}function Id(n,a){return"textarea"===n||"noscript"===n||"string"==typeof a.children||"number"==typeof a.children||"object"==typeof a.dangerouslySetInnerHTML&&null!==a.dangerouslySetInnerHTML&&null!=a.dangerouslySetInnerHTML.__html}var lQ=null;function of(){var n=window.event;return n&&"popstate"===n.type?n!==lQ&&(lQ=n,!0):(lQ=null,!1)}var l$="function"==typeof setTimeout?setTimeout:void 0,lV="function"==typeof clearTimeout?clearTimeout:void 0,lY="function"==typeof Promise?Promise:void 0,lq="function"==typeof queueMicrotask?queueMicrotask:void 0!==lY?function(n){return lY.resolve(null).then(n).catch($n)}:l$;function $n(n){setTimeout(function(){throw n})}function wj(n,a){var i=a,o=0;do{var s=i.nextSibling;if(n.removeChild(i),s&&8===s.nodeType){if("/$"===(i=s.data)){if(0===o){n.removeChild(s),xj(a);return}o--}else"$"!==i&&"$?"!==i&&"$!"!==i||o++}i=s}while(i);xj(a)}function cj(n){var a=n.nodeType;if(9===a)ao(n);else if(1===a)switch(n.nodeName){case"HEAD":case"HTML":case"BODY":ao(n);break;default:n.textContent=""}}function ao(n){var a=n.firstChild;for(a&&10===a.nodeType&&(a=a.nextSibling);a;){var i=a;switch(a=a.nextSibling,i.nodeName){case"HTML":case"HEAD":case"BODY":ao(i),Gb(i);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if("stylesheet"===i.rel.toLowerCase())continue}n.removeChild(i)}}function xd(n,a,i,o){for(;1===n.nodeType;){if(n.nodeName.toLowerCase()!==a.toLowerCase()){if(!o&&("INPUT"!==n.nodeName||"hidden"!==n.type))break}else if(o){if(!n[eB])switch(a){case"meta":if(!n.hasAttribute("itemprop"))break;return n;case"link":if("stylesheet"===(s=n.getAttribute("rel"))&&n.hasAttribute("data-precedence")||s!==i.rel||n.getAttribute("href")!==(null==i.href?null:i.href)||n.getAttribute("crossorigin")!==(null==i.crossOrigin?null:i.crossOrigin)||n.getAttribute("title")!==(null==i.title?null:i.title))break;return n;case"style":if(n.hasAttribute("data-precedence"))break;return n;case"script":if(((s=n.getAttribute("src"))!==(null==i.src?null:i.src)||n.getAttribute("type")!==(null==i.type?null:i.type)||n.getAttribute("crossorigin")!==(null==i.crossOrigin?null:i.crossOrigin))&&s&&n.hasAttribute("async")&&!n.hasAttribute("itemprop"))break;return n;default:return n}}else{if("input"!==a||"hidden"!==n.type)return n;var s=null==i.name?null:""+i.name;if("hidden"===i.type&&n.getAttribute("name")===s)return n}if(null===(n=Cd(n)))break}return null}function Ad(n,a,i){if(""===a)return null;for(;3!==n.nodeType;)if((1!==n.nodeType||"INPUT"!==n.nodeName||"hidden"!==n.type)&&!i||null===(n=Cd(n)))return null;return n}function yd(n){for(;null!=n;n=n.nextSibling){var a=n.nodeType;if(1===a||3===a)break;if(8===a){if("$"===(a=n.data)||"$!"===a||"$?"===a||"F!"===a||"F"===a)break;if("/$"===a)return null}}return n}function Cd(n){return yd(n.nextSibling)}function xi(n,a,i,o,s){switch(n[eM]=s,n[eR]=i,o=0!=(1&s.mode),a){case"dialog":Y("cancel",n),Y("close",n);break;case"iframe":case"object":case"embed":Y("load",n);break;case"video":case"audio":for(s=0;s<lF.length;s++)Y(lF[s],n);break;case"source":Y("error",n);break;case"img":case"image":case"link":Y("error",n),Y("load",n);break;case"details":Y("toggle",n);break;case"input":Y("invalid",n),qc(n,i.value,i.defaultValue,i.checked,i.defaultChecked,i.type,i.name,!0),jc(n);break;case"select":Y("invalid",n);break;case"textarea":Y("invalid",n),uc(n,i.value,i.defaultValue,i.children),jc(n)}"string"!=typeof(s=i.children)&&"number"!=typeof s||n.textContent===""+s||(!0!==i.suppressHydrationWarning&&Bi(n.textContent,s,o),o||"body"===a||(n.textContent=s)),null!=i.onScroll&&Y("scroll",n),null!=i.onScrollEnd&&Y("scrollend",n),null!=i.onClick&&(n.onclick=qj)}function Ib(n){n=n.previousSibling;for(var a=0;n;){if(8===n.nodeType){var i=n.data;if("$"===i||"$!"===i||"$?"===i){if(0===a)return n;a--}else"/$"===i&&a++}n=n.previousSibling}return null}function yi(n,a,i){switch(a=zi(i),n){case"html":if(!(n=a.documentElement))throw Error(t(452));return n;case"head":if(!(n=a.head))throw Error(t(453));return n;case"body":if(!(n=a.body))throw Error(t(454));return n;default:throw Error(t(451))}}var lH=new Map,lZ=new Set;function Kj(n){return"function"==typeof n.getRootNode?n.getRootNode():n.ownerDocument}var lK={prefetchDNS:eo,preconnect:fo,preload:go,preloadModule:ho,preinitStyle:io,preinitScript:jo,preinitModuleScript:ko};function mo(n,a,i){var o=document;if("string"==typeof a&&a){var s=nc(a);s='link[rel="'+n+'"][href="'+s+'"]',"string"==typeof i&&(s+='[crossorigin="'+i+'"]'),lZ.has(s)||(lZ.add(s),n={rel:n,crossOrigin:i,href:a},null===o.querySelector(s)&&(Ai(a=o.createElement("link"),"link",n),Nb(a),o.head.appendChild(a)))}}function eo(n){mo("dns-prefetch",n,null)}function fo(n,a){mo("preconnect",n,a)}function go(n,a,i){var o=document;if(n&&a&&o){var s='link[rel="preload"][as="'+nc(a)+'"]';"image"===a&&i&&i.imageSrcSet?(s+='[imagesrcset="'+nc(i.imageSrcSet)+'"]',"string"==typeof i.imageSizes&&(s+='[imagesizes="'+nc(i.imageSizes)+'"]')):s+='[href="'+nc(n)+'"]';var m=s;switch(a){case"style":m=no(n);break;case"script":m=oo(n)}lH.has(m)||(n=v({rel:"preload",href:"image"===a&&i&&i.imageSrcSet?void 0:n,as:a},i),lH.set(m,n),null!==o.querySelector(s)||"style"===a&&o.querySelector(po(m))||"script"===a&&o.querySelector(qo(m))||(Ai(a=o.createElement("link"),"link",n),Nb(a),o.head.appendChild(a)))}}function ho(n,a){var i=document;if(n){var o=a&&"string"==typeof a.as?a.as:"script",s='link[rel="modulepreload"][as="'+nc(o)+'"][href="'+nc(n)+'"]',m=s;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":m=oo(n)}if(!lH.has(m)&&(n=v({rel:"modulepreload",href:n},a),lH.set(m,n),null===i.querySelector(s))){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(qo(m)))return}Ai(o=i.createElement("link"),"link",n),Nb(o),i.head.appendChild(o)}}}function io(n,a,i){var o=document;if(n){var s=Mb(o).hoistableStyles,m=no(n);a=a||"default";var y=s.get(m);if(!y){var k={loading:0,preload:null};if(y=o.querySelector(po(m)))k.loading=5;else{n=v({rel:"stylesheet",href:n,"data-precedence":a},i),(i=lH.get(m))&&ro(n,i);var S=y=o.createElement("link");Nb(S),Ai(S,"link",n),S._p=new Promise(function(n,a){S.onload=n,S.onerror=a}),S.addEventListener("load",function(){k.loading|=1}),S.addEventListener("error",function(){k.loading|=2}),k.loading|=4,so(y,a,o)}y={type:"stylesheet",instance:y,count:1,state:k},s.set(m,y)}}}function jo(n,a){var i=document;if(n){var o=Mb(i).hoistableScripts,s=oo(n),m=o.get(s);m||((m=i.querySelector(qo(s)))||(n=v({src:n,async:!0},a),(a=lH.get(s))&&to(n,a),Nb(m=i.createElement("script")),Ai(m,"link",n),i.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},o.set(s,m))}}function ko(n,a){var i=document;if(n){var o=Mb(i).hoistableScripts,s=oo(n),m=o.get(s);m||((m=i.querySelector(qo(s)))||(n=v({src:n,async:!0,type:"module"},a),(a=lH.get(s))&&to(n,a),Nb(m=i.createElement("script")),Ai(m,"link",n),i.head.appendChild(m)),m={type:"script",instance:m,count:1,state:null},o.set(s,m))}}function Wk(n,a,i){if(!(a=(a=er.current)?Kj(a):null))throw Error(t(446));switch(n){case"meta":case"title":return null;case"style":return"string"==typeof i.precedence&&"string"==typeof i.href?(i=no(i.href),(n=(a=Mb(a).hoistableStyles).get(i))||(n={type:"style",instance:null,count:0,state:null},a.set(i,n)),n):{type:"void",instance:null,count:0,state:null};case"link":if("stylesheet"===i.rel&&"string"==typeof i.href&&"string"==typeof i.precedence){n=no(i.href);var o=Mb(a).hoistableStyles,s=o.get(n);return s||(a=a.ownerDocument||a,s={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},o.set(n,s),lH.has(n)||uo(a,n,{rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},s.state)),s}return null;case"script":return"string"==typeof i.src&&!0===i.async?(i=oo(i.src),(n=(a=Mb(a).hoistableScripts).get(i))||(n={type:"script",instance:null,count:0,state:null},a.set(i,n)),n):{type:"void",instance:null,count:0,state:null};default:throw Error(t(444,n))}}function no(n){return'href="'+nc(n)+'"'}function po(n){return'link[rel="stylesheet"]['+n+"]"}function vo(n){return v({},n,{"data-precedence":n.precedence,precedence:null})}function uo(n,a,i,o){lH.set(a,i),n.querySelector(po(a))||(n.querySelector('link[rel="preload"][as="style"]['+a+"]")?o.loading=1:(a=n.createElement("link"),o.preload=a,a.addEventListener("load",function(){return o.loading|=1}),a.addEventListener("error",function(){return o.loading|=2}),Ai(a,"link",i),Nb(a),n.head.appendChild(a)))}function oo(n){return'[src="'+nc(n)+'"]'}function qo(n){return"script[async]"+n}function Hj(n,a,i){if(a.count++,null===a.instance)switch(a.type){case"style":var o=n.querySelector('style[data-href~="'+nc(i.href)+'"]');if(o)return a.instance=o,Nb(o),o;var s=v({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return Nb(o=(n.ownerDocument||n).createElement("style")),Ai(o,"style",s),so(o,i.precedence,n),a.instance=o;case"stylesheet":s=no(i.href);var m=n.querySelector(po(s));if(m)return a.state.loading|=4,a.instance=m,Nb(m),m;o=vo(i),(s=lH.get(s))&&ro(o,s),Nb(m=(n.ownerDocument||n).createElement("link"));var y=m;return y._p=new Promise(function(n,a){y.onload=n,y.onerror=a}),Ai(m,"link",o),a.state.loading|=4,so(m,i.precedence,n),a.instance=m;case"script":if(m=oo(i.src),s=n.querySelector(qo(m)))return a.instance=s,Nb(s),s;return o=i,(s=lH.get(m))&&to(o=v({},i),s),Nb(s=(n=n.ownerDocument||n).createElement("script")),Ai(s,"link",o),n.head.appendChild(s),a.instance=s;case"void":return null;default:throw Error(t(443,a.type))}else"stylesheet"===a.type&&0==(4&a.state.loading)&&(o=a.instance,a.state.loading|=4,so(o,i.precedence,n));return a.instance}function so(n,a,i){for(var o=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),s=o.length?o[o.length-1]:null,m=s,y=0;y<o.length;y++){var v=o[y];if(v.dataset.precedence===a)m=v;else if(m!==s)break}m?m.parentNode.insertBefore(n,m.nextSibling):(a=9===i.nodeType?i.head:i).insertBefore(n,a.firstChild)}function ro(n,a){null==n.crossOrigin&&(n.crossOrigin=a.crossOrigin),null==n.referrerPolicy&&(n.referrerPolicy=a.referrerPolicy),null==n.title&&(n.title=a.title)}function to(n,a){null==n.crossOrigin&&(n.crossOrigin=a.crossOrigin),null==n.referrerPolicy&&(n.referrerPolicy=a.referrerPolicy),null==n.integrity&&(n.integrity=a.integrity)}var lX=null;function Fj(n,a,i){if(null===lX){var o=new Map,s=lX=new Map;s.set(i,o)}else(o=(s=lX).get(i))||(o=new Map,s.set(i,o));if(o.has(n))return o;for(o.set(n,null),i=i.getElementsByTagName(n),s=0;s<i.length;s++){var m=i[s];if(!(m[eB]||m[eM]||"link"===n&&"stylesheet"===m.getAttribute("rel"))&&"http://www.w3.org/2000/svg"!==m.namespaceURI){var y=m.getAttribute(a)||"";y=n+y;var v=o.get(y);v?v.push(m):o.set(y,[m])}}return o}function Gj(n,a,i){(n=n.ownerDocument||n).head.insertBefore(i,"title"===a?n.querySelector("head > title"):null)}function Yk(n,a,i){if(1===i||null!=a.itemProp)return!1;switch(n){case"meta":case"title":return!0;case"style":if("string"!=typeof a.precedence||"string"!=typeof a.href||""===a.href)break;return!0;case"link":if("string"!=typeof a.rel||"string"!=typeof a.href||""===a.href||a.onLoad||a.onError)break;if("stylesheet"===a.rel)return n=a.disabled,"string"==typeof a.precedence&&null==n;return!0;case"script":if(!0===a.async&&!a.onLoad&&!a.onError&&"string"==typeof a.src&&a.src)return!0}return!1}var lG=null;function yk(){}function Xj(n,a,i){if(null===lG)throw Error(t(475));var o=lG;if("stylesheet"===a.type&&("string"!=typeof i.media||!1!==matchMedia(i.media).matches)&&0==(4&a.state.loading)){if(null===a.instance){var s=no(i.href),m=n.querySelector(po(s));if(m){null!==(n=m._p)&&"object"==typeof n&&"function"==typeof n.then&&(o.count++,o=wo.bind(o),n.then(o,o)),a.state.loading|=4,a.instance=m,Nb(m);return}m=n.ownerDocument||n,i=vo(i),(s=lH.get(s))&&ro(i,s),Nb(m=m.createElement("link"));var y=m;y._p=new Promise(function(n,a){y.onload=n,y.onerror=a}),Ai(m,"link",i),a.instance=m}null===o.stylesheets&&(o.stylesheets=new Map),o.stylesheets.set(a,n),(n=a.state.preload)&&0==(3&a.state.loading)&&(o.count++,a=wo.bind(o),n.addEventListener("load",a),n.addEventListener("error",a))}}function zk(){if(null===lG)throw Error(t(475));var n=lG;return n.stylesheets&&0===n.count&&xo(n,n.stylesheets),0<n.count?function(a){var i=setTimeout(function(){if(n.stylesheets&&xo(n,n.stylesheets),n.unsuspend){var a=n.unsuspend;n.unsuspend=null,a()}},6e4);return n.unsuspend=a,function(){n.unsuspend=null,clearTimeout(i)}}:null}function wo(){if(this.count--,0===this.count){if(this.stylesheets)xo(this,this.stylesheets);else if(this.unsuspend){var n=this.unsuspend;this.unsuspend=null,n()}}}var lJ=null;function xo(n,a){n.stylesheets=null,null!==n.unsuspend&&(n.count++,lJ=new Map,a.forEach(zo,n),lJ=null,wo.call(n))}function zo(n,a){if(!(4&a.state.loading)){var i=lJ.get(n);if(i)var o=i.get("last");else{i=new Map,lJ.set(n,i);for(var s=n.querySelectorAll("link[data-precedence],style[data-precedence]"),m=0;m<s.length;m++){var y=s[m];("link"===y.nodeName||"not all"!==y.getAttribute("media"))&&(i.set("p"+y.dataset.precedence,y),o=y)}o&&i.set("last",o)}y=(s=a.instance).getAttribute("data-precedence"),(m=i.get("p"+y)||o)===o&&i.set("last",s),i.set(y,s),this.count++,o=wo.bind(this),s.addEventListener("load",o),s.addEventListener("error",o),m?m.parentNode.insertBefore(s,m.nextSibling):(n=9===n.nodeType?n.head:n).insertBefore(s,n.firstChild),a.state.loading|=4}}var l0=y.Dispatcher;"undefined"!=typeof document&&(l0.current=lK);var l1="function"==typeof reportError?reportError:function(n){console.error(n)};function Co(n){this._internalRoot=n}function Do(n){this._internalRoot=n}function Eo(n){return!(!n||1!==n.nodeType&&9!==n.nodeType&&11!==n.nodeType)}function Fo(n){return!(!n||1!==n.nodeType&&9!==n.nodeType&&11!==n.nodeType&&(8!==n.nodeType||" react-mount-point-unstable "!==n.nodeValue))}function Go(){}function Ho(n,a,i,o,s){if(s){if("function"==typeof o){var m=o;o=function(){var n=el(y);m.call(n)}}var y=cl(a,o,n,0,null,!1,!1,"",Go,null,null);return n._reactRootContainer=y,n[eF]=y.current,Ci(8===n.nodeType?n.parentNode:n),Bk(),y}if(cj(n),"function"==typeof o){var v=o;o=function(){var n=el(k);v.call(n)}}var k=$k(n,0,!1,null,null,!1,!1,"",Go,null,null);return n._reactRootContainer=k,n[eF]=k.current,Ci(8===n.nodeType?n.parentNode:n),Bk(function(){dl(a,k,i,o)}),k}function Io(n,a,i,o,s){var m=i._reactRootContainer;if(m){var y=m;if("function"==typeof s){var v=s;s=function(){var n=el(y);v.call(n)}}dl(a,y,n,s)}else y=Ho(i,a,n,s,o);return el(y)}function Jo(n,a){return"font"===n?"":"string"==typeof a?"use-credentials"===a?a:"":void 0}Do.prototype.render=Co.prototype.render=function(n){var a=this._internalRoot;if(null===a)throw Error(t(409));dl(n,a,null,null)},Do.prototype.unmount=Co.prototype.unmount=function(){var n=this._internalRoot;if(null!==n){this._internalRoot=null;var a=n.containerInfo;Bk(function(){dl(null,n,null,null)}),a[eF]=null}},Do.prototype.unstable_scheduleHydration=function(n){if(n){var a=eL;n={blockedOn:null,target:n,priority:a};for(var i=0;i<r0.length&&0!==a&&a<r0[i].priority;i++);r0.splice(i,0,n),0===i&&mm(n)}};var l2=y.Dispatcher;y.Events=[Jb,Kb,Lb,Kc,Lc,Ak];var l3={findFiberByHostInstance:Hb,bundleType:0,version:"18.3.0-canary-0c6348758-20231030",rendererPackageName:"react-dom"},l4={bundleType:l3.bundleType,version:l3.version,rendererPackageName:l3.rendererPackageName,rendererConfig:l3.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:k.ReactCurrentDispatcher,findHostInstanceByFiber:function(n){return null===(n=Qc(n))?null:n.stateNode},findFiberByHostInstance:l3.findFiberByHostInstance||jl,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.0-canary-0c6348758-20231030"};if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var l6=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!l6.isDisabled&&l6.supportsFiber)try{eE=l6.inject(l4),eC=l6}catch(n){}}a.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=y,a.createPortal=function(n,a){var i=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!Eo(a))throw Error(t(200));return al(n,a,null,i)},a.createRoot=function(n,a){if(!Eo(n))throw Error(t(299));var i=!1,o="",s=l1,m=null;return null!=a&&(!0===a.unstable_strictMode&&(i=!0),void 0!==a.identifierPrefix&&(o=a.identifierPrefix),void 0!==a.onRecoverableError&&(s=a.onRecoverableError),void 0!==a.unstable_transitionCallbacks&&(m=a.unstable_transitionCallbacks)),a=$k(n,1,!1,null,null,i,!1,o,s,m,null),n[eF]=a.current,l0.current=lK,Ci(8===n.nodeType?n.parentNode:n),new Co(a)},a.findDOMNode=function(n){if(null==n)return null;if(1===n.nodeType)return n;var a=n._reactInternals;if(void 0===a){if("function"==typeof n.render)throw Error(t(188));throw Error(t(268,n=Object.keys(n).join(",")))}return n=null===(n=Qc(a))?null:n.stateNode},a.flushSync=function(n){return Bk(n)},a.hydrate=function(n,a,i){if(!Fo(a))throw Error(t(200));return Io(null,n,a,!0,i)},a.hydrateRoot=function(n,a,i){if(!Eo(n))throw Error(t(405));var o=!1,s="",m=l1,y=null,v=null;return null!=i&&(!0===i.unstable_strictMode&&(o=!0),void 0!==i.identifierPrefix&&(s=i.identifierPrefix),void 0!==i.onRecoverableError&&(m=i.onRecoverableError),void 0!==i.unstable_transitionCallbacks&&(y=i.unstable_transitionCallbacks),void 0!==i.formState&&(v=i.formState)),a=cl(a,null,n,1,null!=i?i:null,o,!1,s,m,y,v),n[eF]=a.current,l0.current=lK,Ci(n),new Do(a)},a.preconnect=function(n,a){var i=l2.current;i&&"string"==typeof n&&(a=a?"string"==typeof(a=a.crossOrigin)?"use-credentials"===a?a:"":void 0:null,i.preconnect(n,a))},a.prefetchDNS=function(n){var a=l2.current;a&&"string"==typeof n&&a.prefetchDNS(n)},a.preinit=function(n,a){var i=l2.current;if(i&&"string"==typeof n&&a&&"string"==typeof a.as){var o=a.as,s=Jo(o,a.crossOrigin),m="string"==typeof a.integrity?a.integrity:void 0,y="string"==typeof a.fetchPriority?a.fetchPriority:void 0;"style"===o?i.preinitStyle(n,"string"==typeof a.precedence?a.precedence:void 0,{crossOrigin:s,integrity:m,fetchPriority:y}):"script"===o&&i.preinitScript(n,{crossOrigin:s,integrity:m,fetchPriority:y,nonce:"string"==typeof a.nonce?a.nonce:void 0})}},a.preinitModule=function(n,a){var i=l2.current;if(i&&"string"==typeof n){if("object"==typeof a&&null!==a){if(null==a.as||"script"===a.as){var o=Jo(a.as,a.crossOrigin);i.preinitModuleScript(n,{crossOrigin:o,integrity:"string"==typeof a.integrity?a.integrity:void 0,nonce:"string"==typeof a.nonce?a.nonce:void 0})}}else null==a&&i.preinitModuleScript(n)}},a.preload=function(n,a){var i=l2.current;if(i&&"string"==typeof n&&"object"==typeof a&&null!==a&&"string"==typeof a.as){var o=a.as,s=Jo(o,a.crossOrigin);i.preload(n,o,{crossOrigin:s,integrity:"string"==typeof a.integrity?a.integrity:void 0,nonce:"string"==typeof a.nonce?a.nonce:void 0,type:"string"==typeof a.type?a.type:void 0,fetchPriority:"string"==typeof a.fetchPriority?a.fetchPriority:void 0,referrerPolicy:"string"==typeof a.referrerPolicy?a.referrerPolicy:void 0,imageSrcSet:"string"==typeof a.imageSrcSet?a.imageSrcSet:void 0,imageSizes:"string"==typeof a.imageSizes?a.imageSizes:void 0})}},a.preloadModule=function(n,a){var i=l2.current;if(i&&"string"==typeof n){if(a){var o=Jo(a.as,a.crossOrigin);i.preloadModule(n,{as:"string"==typeof a.as&&"script"!==a.as?a.as:void 0,crossOrigin:o,integrity:"string"==typeof a.integrity?a.integrity:void 0})}else i.preloadModule(n)}},a.render=function(n,a,i){if(!Fo(a))throw Error(t(200));return Io(null,n,a,!1,i)},a.unmountComponentAtNode=function(n){if(!Fo(n))throw Error(t(40));return!!n._reactRootContainer&&(Bk(function(){Io(null,null,n,!1,function(){n._reactRootContainer=null,n[eF]=null})}),!0)},a.unstable_batchedUpdates=Ak,a.unstable_renderSubtreeIntoContainer=function(n,a,i,o){if(!Fo(i))throw Error(t(200));if(null==n||void 0===n._reactInternals)throw Error(t(38));return Io(n,a,i,!1,o)},a.useFormState=function(n,a,i){return S.current.useFormState(n,a,i)},a.useFormStatus=function(){return S.current.useHostTransitionStatus()},a.version="18.3.0-canary-0c6348758-20231030"}}]); \ No newline at end of file diff --git a/.next/static/chunks/framework-8883d1e9be70c3da.js b/.next/static/chunks/framework-8883d1e9be70c3da.js index f89af55..fb7ba1b 100644 --- a/.next/static/chunks/framework-8883d1e9be70c3da.js +++ b/.next/static/chunks/framework-8883d1e9be70c3da.js @@ -1,4 +1,4 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[774],{4448:function(e,n,t){/** +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[774],{4448:function(a,u,i){/** * @license React * react-dom.production.min.js * @@ -6,7 +6,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var r,l,a,u,o,i,s=t(7294),c=t(3840);function f(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t<arguments.length;t++)n+="&args[]="+encodeURIComponent(arguments[t]);return"Minified React error #"+e+"; visit "+n+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var d=new Set,p={};function m(e,n){h(e,n),h(e+"Capture",n)}function h(e,n){for(p[e]=n,e=0;e<n.length;e++)d.add(n[e])}var g=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),v=Object.prototype.hasOwnProperty,y=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,b={},k={};function w(e,n,t,r,l,a,u){this.acceptsBooleans=2===n||3===n||4===n,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=t,this.propertyName=e,this.type=n,this.sanitizeURL=a,this.removeEmptyString=u}var S={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){S[e]=new w(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var n=e[0];S[n]=new w(n,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){S[e]=new w(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){S[e]=new w(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){S[e]=new w(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){S[e]=new w(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){S[e]=new w(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){S[e]=new w(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){S[e]=new w(e,5,!1,e.toLowerCase(),null,!1,!1)});var x=/[\-:]([a-z])/g;function E(e){return e[1].toUpperCase()}function C(e,n,t,r){var l,a=S.hasOwnProperty(n)?S[n]:null;(null!==a?0!==a.type:r||!(2<n.length)||"o"!==n[0]&&"O"!==n[0]||"n"!==n[1]&&"N"!==n[1])&&(function(e,n,t,r){if(null==n||function(e,n,t,r){if(null!==t&&0===t.type)return!1;switch(typeof n){case"function":case"symbol":return!0;case"boolean":if(r)return!1;if(null!==t)return!t.acceptsBooleans;return"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e;default:return!1}}(e,n,t,r))return!0;if(r)return!1;if(null!==t)switch(t.type){case 3:return!n;case 4:return!1===n;case 5:return isNaN(n);case 6:return isNaN(n)||1>n}return!1}(n,t,a,r)&&(t=null),r||null===a?(l=n,(!!v.call(k,l)||!v.call(b,l)&&(y.test(l)?k[l]=!0:(b[l]=!0,!1)))&&(null===t?e.removeAttribute(n):e.setAttribute(n,""+t))):a.mustUseProperty?e[a.propertyName]=null===t?3!==a.type&&"":t:(n=a.attributeName,r=a.attributeNamespace,null===t?e.removeAttribute(n):(t=3===(a=a.type)||4===a&&!0===t?"":""+t,r?e.setAttributeNS(r,n,t):e.setAttribute(n,t))))}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var n=e.replace(x,E);S[n]=new w(n,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var n=e.replace(x,E);S[n]=new w(n,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var n=e.replace(x,E);S[n]=new w(n,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){S[e]=new w(e,1,!1,e.toLowerCase(),null,!1,!1)}),S.xlinkHref=new w("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){S[e]=new w(e,1,!1,e.toLowerCase(),null,!0,!0)});var _=s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,P=Symbol.for("react.element"),N=Symbol.for("react.portal"),z=Symbol.for("react.fragment"),T=Symbol.for("react.strict_mode"),L=Symbol.for("react.profiler"),R=Symbol.for("react.provider"),M=Symbol.for("react.context"),F=Symbol.for("react.forward_ref"),O=Symbol.for("react.suspense"),D=Symbol.for("react.suspense_list"),I=Symbol.for("react.memo"),U=Symbol.for("react.lazy");Symbol.for("react.scope"),Symbol.for("react.debug_trace_mode");var V=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden"),Symbol.for("react.cache"),Symbol.for("react.tracing_marker");var A=Symbol.iterator;function $(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=A&&e[A]||e["@@iterator"])?e:null}var j,B=Object.assign;function H(e){if(void 0===j)try{throw Error()}catch(e){var n=e.stack.trim().match(/\n( *(at )?)/);j=n&&n[1]||""}return"\n"+j+e}var W=!1;function Q(e,n){if(!e||W)return"";W=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(n){if(n=function(){throw Error()},Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}}else{try{throw Error()}catch(e){r=e}e()}}catch(n){if(n&&r&&"string"==typeof n.stack){for(var l=n.stack.split("\n"),a=r.stack.split("\n"),u=l.length-1,o=a.length-1;1<=u&&0<=o&&l[u]!==a[o];)o--;for(;1<=u&&0<=o;u--,o--)if(l[u]!==a[o]){if(1!==u||1!==o)do if(u--,0>--o||l[u]!==a[o]){var i="\n"+l[u].replace(" at new "," at ");return e.displayName&&i.includes("<anonymous>")&&(i=i.replace("<anonymous>",e.displayName)),i}while(1<=u&&0<=o);break}}}finally{W=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?H(e):""}function q(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function K(e){var n=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===n||"radio"===n)}function Y(e){e._valueTracker||(e._valueTracker=function(e){var n=K(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&void 0!==t&&"function"==typeof t.get&&"function"==typeof t.set){var l=t.get,a=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return l.call(this)},set:function(e){r=""+e,a.call(this,e)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}(e))}function X(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=K(e)?e.checked?"true":"false":e.value),(e=r)!==t&&(n.setValue(e),!0)}function G(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(n){return e.body}}function Z(e,n){var t=n.checked;return B({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=t?t:e._wrapperState.initialChecked})}function J(e,n){var t=null==n.defaultValue?"":n.defaultValue,r=null!=n.checked?n.checked:n.defaultChecked;t=q(null!=n.value?n.value:t),e._wrapperState={initialChecked:r,initialValue:t,controlled:"checkbox"===n.type||"radio"===n.type?null!=n.checked:null!=n.value}}function ee(e,n){null!=(n=n.checked)&&C(e,"checked",n,!1)}function en(e,n){ee(e,n);var t=q(n.value),r=n.type;if(null!=t)"number"===r?(0===t&&""===e.value||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if("submit"===r||"reset"===r){e.removeAttribute("value");return}n.hasOwnProperty("value")?er(e,n.type,t):n.hasOwnProperty("defaultValue")&&er(e,n.type,q(n.defaultValue)),null==n.checked&&null!=n.defaultChecked&&(e.defaultChecked=!!n.defaultChecked)}function et(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(!("submit"!==r&&"reset"!==r||void 0!==n.value&&null!==n.value))return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}""!==(t=e.name)&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,""!==t&&(e.name=t)}function er(e,n,t){("number"!==n||G(e.ownerDocument)!==e)&&(null==t?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}var el=Array.isArray;function ea(e,n,t,r){if(e=e.options,n){n={};for(var l=0;l<t.length;l++)n["$"+t[l]]=!0;for(t=0;t<e.length;t++)l=n.hasOwnProperty("$"+e[t].value),e[t].selected!==l&&(e[t].selected=l),l&&r&&(e[t].defaultSelected=!0)}else{for(l=0,t=""+q(t),n=null;l<e.length;l++){if(e[l].value===t){e[l].selected=!0,r&&(e[l].defaultSelected=!0);return}null!==n||e[l].disabled||(n=e[l])}null!==n&&(n.selected=!0)}}function eu(e,n){if(null!=n.dangerouslySetInnerHTML)throw Error(f(91));return B({},n,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function eo(e,n){var t=n.value;if(null==t){if(t=n.children,n=n.defaultValue,null!=t){if(null!=n)throw Error(f(92));if(el(t)){if(1<t.length)throw Error(f(93));t=t[0]}n=t}null==n&&(n=""),t=n}e._wrapperState={initialValue:q(t)}}function ei(e,n){var t=q(n.value),r=q(n.defaultValue);null!=t&&((t=""+t)!==e.value&&(e.value=t),null==n.defaultValue&&e.defaultValue!==t&&(e.defaultValue=t)),null!=r&&(e.defaultValue=""+r)}function es(e){var n=e.textContent;n===e._wrapperState.initialValue&&""!==n&&null!==n&&(e.value=n)}function ec(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function ef(e,n){return null==e||"http://www.w3.org/1999/xhtml"===e?ec(n):"http://www.w3.org/2000/svg"===e&&"foreignObject"===n?"http://www.w3.org/1999/xhtml":e}var ed,ep,em=(ed=function(e,n){if("http://www.w3.org/2000/svg"!==e.namespaceURI||"innerHTML"in e)e.innerHTML=n;else{for((ep=ep||document.createElement("div")).innerHTML="<svg>"+n.valueOf().toString()+"</svg>",n=ep.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}},"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(e,n,t,r){MSApp.execUnsafeLocalFunction(function(){return ed(e,n,t,r)})}:ed);function eh(e,n){if(n){var t=e.firstChild;if(t&&t===e.lastChild&&3===t.nodeType){t.nodeValue=n;return}}e.textContent=n}var eg={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ev=["Webkit","ms","Moz","O"];function ey(e,n,t){return null==n||"boolean"==typeof n||""===n?"":t||"number"!=typeof n||0===n||eg.hasOwnProperty(e)&&eg[e]?(""+n).trim():n+"px"}function eb(e,n){for(var t in e=e.style,n)if(n.hasOwnProperty(t)){var r=0===t.indexOf("--"),l=ey(t,n[t],r);"float"===t&&(t="cssFloat"),r?e.setProperty(t,l):e[t]=l}}Object.keys(eg).forEach(function(e){ev.forEach(function(n){eg[n=n+e.charAt(0).toUpperCase()+e.substring(1)]=eg[e]})});var ek=B({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ew(e,n){if(n){if(ek[e]&&(null!=n.children||null!=n.dangerouslySetInnerHTML))throw Error(f(137,e));if(null!=n.dangerouslySetInnerHTML){if(null!=n.children)throw Error(f(60));if("object"!=typeof n.dangerouslySetInnerHTML||!("__html"in n.dangerouslySetInnerHTML))throw Error(f(61))}if(null!=n.style&&"object"!=typeof n.style)throw Error(f(62))}}function eS(e,n){if(-1===e.indexOf("-"))return"string"==typeof n.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ex=null;function eE(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}var eC=null,e_=null,eP=null;function eN(e){if(e=rD(e)){if("function"!=typeof eC)throw Error(f(280));var n=e.stateNode;n&&(n=rU(n),eC(e.stateNode,e.type,n))}}function ez(e){e_?eP?eP.push(e):eP=[e]:e_=e}function eT(){if(e_){var e=e_,n=eP;if(eP=e_=null,eN(e),n)for(e=0;e<n.length;e++)eN(n[e])}}function eL(e,n){return e(n)}function eR(){}var eM=!1;function eF(e,n,t){if(eM)return e(n,t);eM=!0;try{return eL(e,n,t)}finally{eM=!1,(null!==e_||null!==eP)&&(eR(),eT())}}function eO(e,n){var t=e.stateNode;if(null===t)return null;var r=rU(t);if(null===r)return null;t=r[n];e:switch(n){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(r=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!r;break e;default:e=!1}if(e)return null;if(t&&"function"!=typeof t)throw Error(f(231,n,typeof t));return t}var eD=!1;if(g)try{var eI={};Object.defineProperty(eI,"passive",{get:function(){eD=!0}}),window.addEventListener("test",eI,eI),window.removeEventListener("test",eI,eI)}catch(e){eD=!1}function eU(e,n,t,r,l,a,u,o,i){var s=Array.prototype.slice.call(arguments,3);try{n.apply(t,s)}catch(e){this.onError(e)}}var eV=!1,eA=null,e$=!1,ej=null,eB={onError:function(e){eV=!0,eA=e}};function eH(e,n,t,r,l,a,u,o,i){eV=!1,eA=null,eU.apply(eB,arguments)}function eW(e){var n=e,t=e;if(e.alternate)for(;n.return;)n=n.return;else{e=n;do 0!=(4098&(n=e).flags)&&(t=n.return),e=n.return;while(e)}return 3===n.tag?t:null}function eQ(e){if(13===e.tag){var n=e.memoizedState;if(null===n&&null!==(e=e.alternate)&&(n=e.memoizedState),null!==n)return n.dehydrated}return null}function eq(e){if(eW(e)!==e)throw Error(f(188))}function eK(e){return null!==(e=function(e){var n=e.alternate;if(!n){if(null===(n=eW(e)))throw Error(f(188));return n!==e?null:e}for(var t=e,r=n;;){var l=t.return;if(null===l)break;var a=l.alternate;if(null===a){if(null!==(r=l.return)){t=r;continue}break}if(l.child===a.child){for(a=l.child;a;){if(a===t)return eq(l),e;if(a===r)return eq(l),n;a=a.sibling}throw Error(f(188))}if(t.return!==r.return)t=l,r=a;else{for(var u=!1,o=l.child;o;){if(o===t){u=!0,t=l,r=a;break}if(o===r){u=!0,r=l,t=a;break}o=o.sibling}if(!u){for(o=a.child;o;){if(o===t){u=!0,t=a,r=l;break}if(o===r){u=!0,r=a,t=l;break}o=o.sibling}if(!u)throw Error(f(189))}}if(t.alternate!==r)throw Error(f(190))}if(3!==t.tag)throw Error(f(188));return t.stateNode.current===t?e:n}(e))?function e(n){if(5===n.tag||6===n.tag)return n;for(n=n.child;null!==n;){var t=e(n);if(null!==t)return t;n=n.sibling}return null}(e):null}var eY=c.unstable_scheduleCallback,eX=c.unstable_cancelCallback,eG=c.unstable_shouldYield,eZ=c.unstable_requestPaint,eJ=c.unstable_now,e0=c.unstable_getCurrentPriorityLevel,e1=c.unstable_ImmediatePriority,e2=c.unstable_UserBlockingPriority,e3=c.unstable_NormalPriority,e4=c.unstable_LowPriority,e8=c.unstable_IdlePriority,e6=null,e5=null,e9=Math.clz32?Math.clz32:function(e){return 0==(e>>>=0)?32:31-(e7(e)/ne|0)|0},e7=Math.log,ne=Math.LN2,nn=64,nt=4194304;function nr(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194240&e;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return 130023424&e;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function nl(e,n){var t=e.pendingLanes;if(0===t)return 0;var r=0,l=e.suspendedLanes,a=e.pingedLanes,u=268435455&t;if(0!==u){var o=u&~l;0!==o?r=nr(o):0!=(a&=u)&&(r=nr(a))}else 0!=(u=t&~l)?r=nr(u):0!==a&&(r=nr(a));if(0===r)return 0;if(0!==n&&n!==r&&0==(n&l)&&((l=r&-r)>=(a=n&-n)||16===l&&0!=(4194240&a)))return n;if(0!=(4&r)&&(r|=16&t),0!==(n=e.entangledLanes))for(e=e.entanglements,n&=r;0<n;)l=1<<(t=31-e9(n)),r|=e[t],n&=~l;return r}function na(e){return 0!=(e=-1073741825&e.pendingLanes)?e:1073741824&e?1073741824:0}function nu(){var e=nn;return 0==(4194240&(nn<<=1))&&(nn=64),e}function no(e){for(var n=[],t=0;31>t;t++)n.push(e);return n}function ni(e,n,t){e.pendingLanes|=n,536870912!==n&&(e.suspendedLanes=0,e.pingedLanes=0),(e=e.eventTimes)[n=31-e9(n)]=t}function ns(e,n){var t=e.entangledLanes|=n;for(e=e.entanglements;t;){var r=31-e9(t),l=1<<r;l&n|e[r]&n&&(e[r]|=n),t&=~l}}var nc=0;function nf(e){return 1<(e&=-e)?4<e?0!=(268435455&e)?16:536870912:4:1}var nd,np,nm,nh,ng,nv=!1,ny=[],nb=null,nk=null,nw=null,nS=new Map,nx=new Map,nE=[],nC="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function n_(e,n){switch(e){case"focusin":case"focusout":nb=null;break;case"dragenter":case"dragleave":nk=null;break;case"mouseover":case"mouseout":nw=null;break;case"pointerover":case"pointerout":nS.delete(n.pointerId);break;case"gotpointercapture":case"lostpointercapture":nx.delete(n.pointerId)}}function nP(e,n,t,r,l,a){return null===e||e.nativeEvent!==a?(e={blockedOn:n,domEventName:t,eventSystemFlags:r,nativeEvent:a,targetContainers:[l]},null!==n&&null!==(n=rD(n))&&np(n),e):(e.eventSystemFlags|=r,n=e.targetContainers,null!==l&&-1===n.indexOf(l)&&n.push(l),e)}function nN(e){var n=rO(e.target);if(null!==n){var t=eW(n);if(null!==t){if(13===(n=t.tag)){if(null!==(n=eQ(t))){e.blockedOn=n,ng(e.priority,function(){nm(t)});return}}else if(3===n&&t.stateNode.current.memoizedState.isDehydrated){e.blockedOn=3===t.tag?t.stateNode.containerInfo:null;return}}}e.blockedOn=null}function nz(e){if(null!==e.blockedOn)return!1;for(var n=e.targetContainers;0<n.length;){var t=nA(e.domEventName,e.eventSystemFlags,n[0],e.nativeEvent);if(null!==t)return null!==(n=rD(t))&&np(n),e.blockedOn=t,!1;var r=new(t=e.nativeEvent).constructor(t.type,t);ex=r,t.target.dispatchEvent(r),ex=null,n.shift()}return!0}function nT(e,n,t){nz(e)&&t.delete(n)}function nL(){nv=!1,null!==nb&&nz(nb)&&(nb=null),null!==nk&&nz(nk)&&(nk=null),null!==nw&&nz(nw)&&(nw=null),nS.forEach(nT),nx.forEach(nT)}function nR(e,n){e.blockedOn===n&&(e.blockedOn=null,nv||(nv=!0,c.unstable_scheduleCallback(c.unstable_NormalPriority,nL)))}function nM(e){function n(n){return nR(n,e)}if(0<ny.length){nR(ny[0],e);for(var t=1;t<ny.length;t++){var r=ny[t];r.blockedOn===e&&(r.blockedOn=null)}}for(null!==nb&&nR(nb,e),null!==nk&&nR(nk,e),null!==nw&&nR(nw,e),nS.forEach(n),nx.forEach(n),t=0;t<nE.length;t++)(r=nE[t]).blockedOn===e&&(r.blockedOn=null);for(;0<nE.length&&null===(t=nE[0]).blockedOn;)nN(t),null===t.blockedOn&&nE.shift()}var nF=_.ReactCurrentBatchConfig,nO=!0;function nD(e,n,t,r){var l=nc,a=nF.transition;nF.transition=null;try{nc=1,nU(e,n,t,r)}finally{nc=l,nF.transition=a}}function nI(e,n,t,r){var l=nc,a=nF.transition;nF.transition=null;try{nc=4,nU(e,n,t,r)}finally{nc=l,nF.transition=a}}function nU(e,n,t,r){if(nO){var l=nA(e,n,t,r);if(null===l)ro(e,n,r,nV,t),n_(e,r);else if(function(e,n,t,r,l){switch(n){case"focusin":return nb=nP(nb,e,n,t,r,l),!0;case"dragenter":return nk=nP(nk,e,n,t,r,l),!0;case"mouseover":return nw=nP(nw,e,n,t,r,l),!0;case"pointerover":var a=l.pointerId;return nS.set(a,nP(nS.get(a)||null,e,n,t,r,l)),!0;case"gotpointercapture":return a=l.pointerId,nx.set(a,nP(nx.get(a)||null,e,n,t,r,l)),!0}return!1}(l,e,n,t,r))r.stopPropagation();else if(n_(e,r),4&n&&-1<nC.indexOf(e)){for(;null!==l;){var a=rD(l);if(null!==a&&nd(a),null===(a=nA(e,n,t,r))&&ro(e,n,r,nV,t),a===l)break;l=a}null!==l&&r.stopPropagation()}else ro(e,n,r,null,t)}}var nV=null;function nA(e,n,t,r){if(nV=null,null!==(e=rO(e=eE(r)))){if(null===(n=eW(e)))e=null;else if(13===(t=n.tag)){if(null!==(e=eQ(n)))return e;e=null}else if(3===t){if(n.stateNode.current.memoizedState.isDehydrated)return 3===n.tag?n.stateNode.containerInfo:null;e=null}else n!==e&&(e=null)}return nV=e,null}function n$(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(e0()){case e1:return 1;case e2:return 4;case e3:case e4:return 16;case e8:return 536870912;default:return 16}default:return 16}}var nj=null,nB=null,nH=null;function nW(){if(nH)return nH;var e,n,t=nB,r=t.length,l="value"in nj?nj.value:nj.textContent,a=l.length;for(e=0;e<r&&t[e]===l[e];e++);var u=r-e;for(n=1;n<=u&&t[r-n]===l[a-n];n++);return nH=l.slice(e,1<n?1-n:void 0)}function nQ(e){var n=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===n&&(e=13):e=n,10===e&&(e=13),32<=e||13===e?e:0}function nq(){return!0}function nK(){return!1}function nY(e){function n(n,t,r,l,a){for(var u in this._reactName=n,this._targetInst=r,this.type=t,this.nativeEvent=l,this.target=a,this.currentTarget=null,e)e.hasOwnProperty(u)&&(n=e[u],this[u]=n?n(l):l[u]);return this.isDefaultPrevented=(null!=l.defaultPrevented?l.defaultPrevented:!1===l.returnValue)?nq:nK,this.isPropagationStopped=nK,this}return B(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=nq)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=nq)},persist:function(){},isPersistent:nq}),n}var nX,nG,nZ,nJ={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},n0=nY(nJ),n1=B({},nJ,{view:0,detail:0}),n2=nY(n1),n3=B({},n1,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:tl,button:0,buttons:0,relatedTarget:function(e){return void 0===e.relatedTarget?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==nZ&&(nZ&&"mousemove"===e.type?(nX=e.screenX-nZ.screenX,nG=e.screenY-nZ.screenY):nG=nX=0,nZ=e),nX)},movementY:function(e){return"movementY"in e?e.movementY:nG}}),n4=nY(n3),n8=nY(B({},n3,{dataTransfer:0})),n6=nY(B({},n1,{relatedTarget:0})),n5=nY(B({},nJ,{animationName:0,elapsedTime:0,pseudoElement:0})),n9=nY(B({},nJ,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}})),n7=nY(B({},nJ,{data:0})),te={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},tn={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},tt={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function tr(e){var n=this.nativeEvent;return n.getModifierState?n.getModifierState(e):!!(e=tt[e])&&!!n[e]}function tl(){return tr}var ta=nY(B({},n1,{key:function(e){if(e.key){var n=te[e.key]||e.key;if("Unidentified"!==n)return n}return"keypress"===e.type?13===(e=nQ(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?tn[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:tl,charCode:function(e){return"keypress"===e.type?nQ(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?nQ(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}})),tu=nY(B({},n3,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),to=nY(B({},n1,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:tl})),ti=nY(B({},nJ,{propertyName:0,elapsedTime:0,pseudoElement:0})),ts=nY(B({},n3,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0})),tc=[9,13,27,32],tf=g&&"CompositionEvent"in window,td=null;g&&"documentMode"in document&&(td=document.documentMode);var tp=g&&"TextEvent"in window&&!td,tm=g&&(!tf||td&&8<td&&11>=td),th=!1;function tg(e,n){switch(e){case"keyup":return -1!==tc.indexOf(n.keyCode);case"keydown":return 229!==n.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function tv(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var ty=!1,tb={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function tk(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===n?!!tb[e.type]:"textarea"===n}function tw(e,n,t,r){ez(r),0<(n=rs(n,"onChange")).length&&(t=new n0("onChange","change",null,t,r),e.push({event:t,listeners:n}))}var tS=null,tx=null;function tE(e){rn(e,0)}function tC(e){if(X(rI(e)))return e}function t_(e,n){if("change"===e)return n}var tP=!1;if(g){if(g){var tN="oninput"in document;if(!tN){var tz=document.createElement("div");tz.setAttribute("oninput","return;"),tN="function"==typeof tz.oninput}r=tN}else r=!1;tP=r&&(!document.documentMode||9<document.documentMode)}function tT(){tS&&(tS.detachEvent("onpropertychange",tL),tx=tS=null)}function tL(e){if("value"===e.propertyName&&tC(tx)){var n=[];tw(n,tx,e,eE(e)),eF(tE,n)}}function tR(e,n,t){"focusin"===e?(tT(),tS=n,tx=t,tS.attachEvent("onpropertychange",tL)):"focusout"===e&&tT()}function tM(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return tC(tx)}function tF(e,n){if("click"===e)return tC(n)}function tO(e,n){if("input"===e||"change"===e)return tC(n)}var tD="function"==typeof Object.is?Object.is:function(e,n){return e===n&&(0!==e||1/e==1/n)||e!=e&&n!=n};function tI(e,n){if(tD(e,n))return!0;if("object"!=typeof e||null===e||"object"!=typeof n||null===n)return!1;var t=Object.keys(e),r=Object.keys(n);if(t.length!==r.length)return!1;for(r=0;r<t.length;r++){var l=t[r];if(!v.call(n,l)||!tD(e[l],n[l]))return!1}return!0}function tU(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function tV(e,n){var t,r=tU(e);for(e=0;r;){if(3===r.nodeType){if(t=e+r.textContent.length,e<=n&&t>=n)return{node:r,offset:n-e};e=t}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=tU(r)}}function tA(){for(var e=window,n=G();n instanceof e.HTMLIFrameElement;){try{var t="string"==typeof n.contentWindow.location.href}catch(e){t=!1}if(t)e=n.contentWindow;else break;n=G(e.document)}return n}function t$(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&("input"===n&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===n||"true"===e.contentEditable)}var tj=g&&"documentMode"in document&&11>=document.documentMode,tB=null,tH=null,tW=null,tQ=!1;function tq(e,n,t){var r=t.window===t?t.document:9===t.nodeType?t:t.ownerDocument;tQ||null==tB||tB!==G(r)||(r="selectionStart"in(r=tB)&&t$(r)?{start:r.selectionStart,end:r.selectionEnd}:{anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},tW&&tI(tW,r)||(tW=r,0<(r=rs(tH,"onSelect")).length&&(n=new n0("onSelect","select",null,n,t),e.push({event:n,listeners:r}),n.target=tB)))}function tK(e,n){var t={};return t[e.toLowerCase()]=n.toLowerCase(),t["Webkit"+e]="webkit"+n,t["Moz"+e]="moz"+n,t}var tY={animationend:tK("Animation","AnimationEnd"),animationiteration:tK("Animation","AnimationIteration"),animationstart:tK("Animation","AnimationStart"),transitionend:tK("Transition","TransitionEnd")},tX={},tG={};function tZ(e){if(tX[e])return tX[e];if(!tY[e])return e;var n,t=tY[e];for(n in t)if(t.hasOwnProperty(n)&&n in tG)return tX[e]=t[n];return e}g&&(tG=document.createElement("div").style,"AnimationEvent"in window||(delete tY.animationend.animation,delete tY.animationiteration.animation,delete tY.animationstart.animation),"TransitionEvent"in window||delete tY.transitionend.transition);var tJ=tZ("animationend"),t0=tZ("animationiteration"),t1=tZ("animationstart"),t2=tZ("transitionend"),t3=new Map,t4="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function t8(e,n){t3.set(e,n),m(n,[e])}for(var t6=0;t6<t4.length;t6++){var t5=t4[t6];t8(t5.toLowerCase(),"on"+(t5[0].toUpperCase()+t5.slice(1)))}t8(tJ,"onAnimationEnd"),t8(t0,"onAnimationIteration"),t8(t1,"onAnimationStart"),t8("dblclick","onDoubleClick"),t8("focusin","onFocus"),t8("focusout","onBlur"),t8(t2,"onTransitionEnd"),h("onMouseEnter",["mouseout","mouseover"]),h("onMouseLeave",["mouseout","mouseover"]),h("onPointerEnter",["pointerout","pointerover"]),h("onPointerLeave",["pointerout","pointerover"]),m("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),m("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),m("onBeforeInput",["compositionend","keypress","textInput","paste"]),m("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),m("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),m("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var t9="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),t7=new Set("cancel close invalid load scroll toggle".split(" ").concat(t9));function re(e,n,t){var r=e.type||"unknown-event";e.currentTarget=t,function(e,n,t,r,l,a,u,o,i){if(eH.apply(this,arguments),eV){if(eV){var s=eA;eV=!1,eA=null}else throw Error(f(198));e$||(e$=!0,ej=s)}}(r,n,void 0,e),e.currentTarget=null}function rn(e,n){n=0!=(4&n);for(var t=0;t<e.length;t++){var r=e[t],l=r.event;r=r.listeners;e:{var a=void 0;if(n)for(var u=r.length-1;0<=u;u--){var o=r[u],i=o.instance,s=o.currentTarget;if(o=o.listener,i!==a&&l.isPropagationStopped())break e;re(l,o,s),a=i}else for(u=0;u<r.length;u++){if(i=(o=r[u]).instance,s=o.currentTarget,o=o.listener,i!==a&&l.isPropagationStopped())break e;re(l,o,s),a=i}}}if(e$)throw e=ej,e$=!1,ej=null,e}function rt(e,n){var t=n[rR];void 0===t&&(t=n[rR]=new Set);var r=e+"__bubble";t.has(r)||(ru(n,e,2,!1),t.add(r))}function rr(e,n,t){var r=0;n&&(r|=4),ru(t,e,r,n)}var rl="_reactListening"+Math.random().toString(36).slice(2);function ra(e){if(!e[rl]){e[rl]=!0,d.forEach(function(n){"selectionchange"!==n&&(t7.has(n)||rr(n,!1,e),rr(n,!0,e))});var n=9===e.nodeType?e:e.ownerDocument;null===n||n[rl]||(n[rl]=!0,rr("selectionchange",!1,n))}}function ru(e,n,t,r){switch(n$(n)){case 1:var l=nD;break;case 4:l=nI;break;default:l=nU}t=l.bind(null,n,t,e),l=void 0,eD&&("touchstart"===n||"touchmove"===n||"wheel"===n)&&(l=!0),r?void 0!==l?e.addEventListener(n,t,{capture:!0,passive:l}):e.addEventListener(n,t,!0):void 0!==l?e.addEventListener(n,t,{passive:l}):e.addEventListener(n,t,!1)}function ro(e,n,t,r,l){var a=r;if(0==(1&n)&&0==(2&n)&&null!==r)e:for(;;){if(null===r)return;var u=r.tag;if(3===u||4===u){var o=r.stateNode.containerInfo;if(o===l||8===o.nodeType&&o.parentNode===l)break;if(4===u)for(u=r.return;null!==u;){var i=u.tag;if((3===i||4===i)&&((i=u.stateNode.containerInfo)===l||8===i.nodeType&&i.parentNode===l))return;u=u.return}for(;null!==o;){if(null===(u=rO(o)))return;if(5===(i=u.tag)||6===i){r=a=u;continue e}o=o.parentNode}}r=r.return}eF(function(){var r=a,l=eE(t),u=[];e:{var o=t3.get(e);if(void 0!==o){var i=n0,s=e;switch(e){case"keypress":if(0===nQ(t))break e;case"keydown":case"keyup":i=ta;break;case"focusin":s="focus",i=n6;break;case"focusout":s="blur",i=n6;break;case"beforeblur":case"afterblur":i=n6;break;case"click":if(2===t.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":i=n4;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":i=n8;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":i=to;break;case tJ:case t0:case t1:i=n5;break;case t2:i=ti;break;case"scroll":i=n2;break;case"wheel":i=ts;break;case"copy":case"cut":case"paste":i=n9;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":i=tu}var c=0!=(4&n),f=!c&&"scroll"===e,d=c?null!==o?o+"Capture":null:o;c=[];for(var p,m=r;null!==m;){var h=(p=m).stateNode;if(5===p.tag&&null!==h&&(p=h,null!==d&&null!=(h=eO(m,d))&&c.push(ri(m,h,p))),f)break;m=m.return}0<c.length&&(o=new i(o,s,null,t,l),u.push({event:o,listeners:c}))}}if(0==(7&n)){e:if(o="mouseover"===e||"pointerover"===e,i="mouseout"===e||"pointerout"===e,!(o&&t!==ex&&(s=t.relatedTarget||t.fromElement)&&(rO(s)||s[rL]))&&(i||o)&&(o=l.window===l?l:(o=l.ownerDocument)?o.defaultView||o.parentWindow:window,i?(s=t.relatedTarget||t.toElement,i=r,null!==(s=s?rO(s):null)&&(f=eW(s),s!==f||5!==s.tag&&6!==s.tag)&&(s=null)):(i=null,s=r),i!==s)){if(c=n4,h="onMouseLeave",d="onMouseEnter",m="mouse",("pointerout"===e||"pointerover"===e)&&(c=tu,h="onPointerLeave",d="onPointerEnter",m="pointer"),f=null==i?o:rI(i),p=null==s?o:rI(s),(o=new c(h,m+"leave",i,t,l)).target=f,o.relatedTarget=p,h=null,rO(l)===r&&((c=new c(d,m+"enter",s,t,l)).target=p,c.relatedTarget=f,h=c),f=h,i&&s)n:{for(c=i,d=s,m=0,p=c;p;p=rc(p))m++;for(p=0,h=d;h;h=rc(h))p++;for(;0<m-p;)c=rc(c),m--;for(;0<p-m;)d=rc(d),p--;for(;m--;){if(c===d||null!==d&&c===d.alternate)break n;c=rc(c),d=rc(d)}c=null}else c=null;null!==i&&rf(u,o,i,c,!1),null!==s&&null!==f&&rf(u,f,s,c,!0)}e:{if("select"===(i=(o=r?rI(r):window).nodeName&&o.nodeName.toLowerCase())||"input"===i&&"file"===o.type)var g,v=t_;else if(tk(o)){if(tP)v=tO;else{v=tM;var y=tR}}else(i=o.nodeName)&&"input"===i.toLowerCase()&&("checkbox"===o.type||"radio"===o.type)&&(v=tF);if(v&&(v=v(e,r))){tw(u,v,t,l);break e}y&&y(e,o,r),"focusout"===e&&(y=o._wrapperState)&&y.controlled&&"number"===o.type&&er(o,"number",o.value)}switch(y=r?rI(r):window,e){case"focusin":(tk(y)||"true"===y.contentEditable)&&(tB=y,tH=r,tW=null);break;case"focusout":tW=tH=tB=null;break;case"mousedown":tQ=!0;break;case"contextmenu":case"mouseup":case"dragend":tQ=!1,tq(u,t,l);break;case"selectionchange":if(tj)break;case"keydown":case"keyup":tq(u,t,l)}if(tf)n:{switch(e){case"compositionstart":var b="onCompositionStart";break n;case"compositionend":b="onCompositionEnd";break n;case"compositionupdate":b="onCompositionUpdate";break n}b=void 0}else ty?tg(e,t)&&(b="onCompositionEnd"):"keydown"===e&&229===t.keyCode&&(b="onCompositionStart");b&&(tm&&"ko"!==t.locale&&(ty||"onCompositionStart"!==b?"onCompositionEnd"===b&&ty&&(g=nW()):(nB="value"in(nj=l)?nj.value:nj.textContent,ty=!0)),0<(y=rs(r,b)).length&&(b=new n7(b,e,null,t,l),u.push({event:b,listeners:y}),g?b.data=g:null!==(g=tv(t))&&(b.data=g))),(g=tp?function(e,n){switch(e){case"compositionend":return tv(n);case"keypress":if(32!==n.which)return null;return th=!0," ";case"textInput":return" "===(e=n.data)&&th?null:e;default:return null}}(e,t):function(e,n){if(ty)return"compositionend"===e||!tf&&tg(e,n)?(e=nW(),nH=nB=nj=null,ty=!1,e):null;switch(e){case"paste":default:return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1<n.char.length)return n.char;if(n.which)return String.fromCharCode(n.which)}return null;case"compositionend":return tm&&"ko"!==n.locale?null:n.data}}(e,t))&&0<(r=rs(r,"onBeforeInput")).length&&(l=new n7("onBeforeInput","beforeinput",null,t,l),u.push({event:l,listeners:r}),l.data=g)}rn(u,n)})}function ri(e,n,t){return{instance:e,listener:n,currentTarget:t}}function rs(e,n){for(var t=n+"Capture",r=[];null!==e;){var l=e,a=l.stateNode;5===l.tag&&null!==a&&(l=a,null!=(a=eO(e,t))&&r.unshift(ri(e,a,l)),null!=(a=eO(e,n))&&r.push(ri(e,a,l))),e=e.return}return r}function rc(e){if(null===e)return null;do e=e.return;while(e&&5!==e.tag);return e||null}function rf(e,n,t,r,l){for(var a=n._reactName,u=[];null!==t&&t!==r;){var o=t,i=o.alternate,s=o.stateNode;if(null!==i&&i===r)break;5===o.tag&&null!==s&&(o=s,l?null!=(i=eO(t,a))&&u.unshift(ri(t,i,o)):l||null!=(i=eO(t,a))&&u.push(ri(t,i,o))),t=t.return}0!==u.length&&e.push({event:n,listeners:u})}var rd=/\r\n?/g,rp=/\u0000|\uFFFD/g;function rm(e){return("string"==typeof e?e:""+e).replace(rd,"\n").replace(rp,"")}function rh(e,n,t){if(n=rm(n),rm(e)!==n&&t)throw Error(f(425))}function rg(){}var rv=null,ry=null;function rb(e,n){return"textarea"===e||"noscript"===e||"string"==typeof n.children||"number"==typeof n.children||"object"==typeof n.dangerouslySetInnerHTML&&null!==n.dangerouslySetInnerHTML&&null!=n.dangerouslySetInnerHTML.__html}var rk="function"==typeof setTimeout?setTimeout:void 0,rw="function"==typeof clearTimeout?clearTimeout:void 0,rS="function"==typeof Promise?Promise:void 0,rx="function"==typeof queueMicrotask?queueMicrotask:void 0!==rS?function(e){return rS.resolve(null).then(e).catch(rE)}:rk;function rE(e){setTimeout(function(){throw e})}function rC(e,n){var t=n,r=0;do{var l=t.nextSibling;if(e.removeChild(t),l&&8===l.nodeType){if("/$"===(t=l.data)){if(0===r){e.removeChild(l),nM(n);return}r--}else"$"!==t&&"$?"!==t&&"$!"!==t||r++}t=l}while(t);nM(n)}function r_(e){for(;null!=e;e=e.nextSibling){var n=e.nodeType;if(1===n||3===n)break;if(8===n){if("$"===(n=e.data)||"$!"===n||"$?"===n)break;if("/$"===n)return null}}return e}function rP(e){e=e.previousSibling;for(var n=0;e;){if(8===e.nodeType){var t=e.data;if("$"===t||"$!"===t||"$?"===t){if(0===n)return e;n--}else"/$"===t&&n++}e=e.previousSibling}return null}var rN=Math.random().toString(36).slice(2),rz="__reactFiber$"+rN,rT="__reactProps$"+rN,rL="__reactContainer$"+rN,rR="__reactEvents$"+rN,rM="__reactListeners$"+rN,rF="__reactHandles$"+rN;function rO(e){var n=e[rz];if(n)return n;for(var t=e.parentNode;t;){if(n=t[rL]||t[rz]){if(t=n.alternate,null!==n.child||null!==t&&null!==t.child)for(e=rP(e);null!==e;){if(t=e[rz])return t;e=rP(e)}return n}t=(e=t).parentNode}return null}function rD(e){return(e=e[rz]||e[rL])&&(5===e.tag||6===e.tag||13===e.tag||3===e.tag)?e:null}function rI(e){if(5===e.tag||6===e.tag)return e.stateNode;throw Error(f(33))}function rU(e){return e[rT]||null}var rV=[],rA=-1;function r$(e){return{current:e}}function rj(e){0>rA||(e.current=rV[rA],rV[rA]=null,rA--)}function rB(e,n){rV[++rA]=e.current,e.current=n}var rH={},rW=r$(rH),rQ=r$(!1),rq=rH;function rK(e,n){var t=e.type.contextTypes;if(!t)return rH;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l,a={};for(l in t)a[l]=n[l];return r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=a),a}function rY(e){return null!=(e=e.childContextTypes)}function rX(){rj(rQ),rj(rW)}function rG(e,n,t){if(rW.current!==rH)throw Error(f(168));rB(rW,n),rB(rQ,t)}function rZ(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,"function"!=typeof r.getChildContext)return t;for(var l in r=r.getChildContext())if(!(l in n))throw Error(f(108,function(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=(e=n.render).displayName||e.name||"",n.displayName||(""!==e?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return function e(n){if(null==n)return null;if("function"==typeof n)return n.displayName||n.name||null;if("string"==typeof n)return n;switch(n){case z:return"Fragment";case N:return"Portal";case L:return"Profiler";case T:return"StrictMode";case O:return"Suspense";case D:return"SuspenseList"}if("object"==typeof n)switch(n.$$typeof){case M:return(n.displayName||"Context")+".Consumer";case R:return(n._context.displayName||"Context")+".Provider";case F:var t=n.render;return(n=n.displayName)||(n=""!==(n=t.displayName||t.name||"")?"ForwardRef("+n+")":"ForwardRef"),n;case I:return null!==(t=n.displayName||null)?t:e(n.type)||"Memo";case U:t=n._payload,n=n._init;try{return e(n(t))}catch(e){}}return null}(n);case 8:return n===T?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof n)return n.displayName||n.name||null;if("string"==typeof n)return n}return null}(e)||"Unknown",l));return B({},t,r)}function rJ(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||rH,rq=rW.current,rB(rW,e),rB(rQ,rQ.current),!0}function r0(e,n,t){var r=e.stateNode;if(!r)throw Error(f(169));t?(e=rZ(e,n,rq),r.__reactInternalMemoizedMergedChildContext=e,rj(rQ),rj(rW),rB(rW,e)):rj(rQ),rB(rQ,t)}var r1=null,r2=!1,r3=!1;function r4(){if(!r3&&null!==r1){r3=!0;var e=0,n=nc;try{var t=r1;for(nc=1;e<t.length;e++){var r=t[e];do r=r(!0);while(null!==r)}r1=null,r2=!1}catch(n){throw null!==r1&&(r1=r1.slice(e+1)),eY(e1,r4),n}finally{nc=n,r3=!1}}return null}var r8=[],r6=0,r5=null,r9=0,r7=[],le=0,ln=null,lt=1,lr="";function ll(e,n){r8[r6++]=r9,r8[r6++]=r5,r5=e,r9=n}function la(e,n,t){r7[le++]=lt,r7[le++]=lr,r7[le++]=ln,ln=e;var r=lt;e=lr;var l=32-e9(r)-1;r&=~(1<<l),t+=1;var a=32-e9(n)+l;if(30<a){var u=l-l%5;a=(r&(1<<u)-1).toString(32),r>>=u,l-=u,lt=1<<32-e9(n)+l|t<<l|r,lr=a+e}else lt=1<<a|t<<l|r,lr=e}function lu(e){null!==e.return&&(ll(e,1),la(e,1,0))}function lo(e){for(;e===r5;)r5=r8[--r6],r8[r6]=null,r9=r8[--r6],r8[r6]=null;for(;e===ln;)ln=r7[--le],r7[le]=null,lr=r7[--le],r7[le]=null,lt=r7[--le],r7[le]=null}var li=null,ls=null,lc=!1,lf=null;function ld(e,n){var t=oQ(5,null,null,0);t.elementType="DELETED",t.stateNode=n,t.return=e,null===(n=e.deletions)?(e.deletions=[t],e.flags|=16):n.push(t)}function lp(e,n){switch(e.tag){case 5:var t=e.type;return null!==(n=1!==n.nodeType||t.toLowerCase()!==n.nodeName.toLowerCase()?null:n)&&(e.stateNode=n,li=e,ls=r_(n.firstChild),!0);case 6:return null!==(n=""===e.pendingProps||3!==n.nodeType?null:n)&&(e.stateNode=n,li=e,ls=null,!0);case 13:return null!==(n=8!==n.nodeType?null:n)&&(t=null!==ln?{id:lt,overflow:lr}:null,e.memoizedState={dehydrated:n,treeContext:t,retryLane:1073741824},(t=oQ(18,null,null,0)).stateNode=n,t.return=e,e.child=t,li=e,ls=null,!0);default:return!1}}function lm(e){return 0!=(1&e.mode)&&0==(128&e.flags)}function lh(e){if(lc){var n=ls;if(n){var t=n;if(!lp(e,n)){if(lm(e))throw Error(f(418));n=r_(t.nextSibling);var r=li;n&&lp(e,n)?ld(r,t):(e.flags=-4097&e.flags|2,lc=!1,li=e)}}else{if(lm(e))throw Error(f(418));e.flags=-4097&e.flags|2,lc=!1,li=e}}}function lg(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&13!==e.tag;)e=e.return;li=e}function lv(e){if(e!==li)return!1;if(!lc)return lg(e),lc=!0,!1;if((n=3!==e.tag)&&!(n=5!==e.tag)&&(n="head"!==(n=e.type)&&"body"!==n&&!rb(e.type,e.memoizedProps)),n&&(n=ls)){if(lm(e))throw ly(),Error(f(418));for(;n;)ld(e,n),n=r_(n.nextSibling)}if(lg(e),13===e.tag){if(!(e=null!==(e=e.memoizedState)?e.dehydrated:null))throw Error(f(317));e:{for(n=0,e=e.nextSibling;e;){if(8===e.nodeType){var n,t=e.data;if("/$"===t){if(0===n){ls=r_(e.nextSibling);break e}n--}else"$"!==t&&"$!"!==t&&"$?"!==t||n++}e=e.nextSibling}ls=null}}else ls=li?r_(e.stateNode.nextSibling):null;return!0}function ly(){for(var e=ls;e;)e=r_(e.nextSibling)}function lb(){ls=li=null,lc=!1}function lk(e){null===lf?lf=[e]:lf.push(e)}var lw=_.ReactCurrentBatchConfig;function lS(e,n){if(e&&e.defaultProps)for(var t in n=B({},n),e=e.defaultProps)void 0===n[t]&&(n[t]=e[t]);return n}var lx=r$(null),lE=null,lC=null,l_=null;function lP(){l_=lC=lE=null}function lN(e){var n=lx.current;rj(lx),e._currentValue=n}function lz(e,n,t){for(;null!==e;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,null!==r&&(r.childLanes|=n)):null!==r&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function lT(e,n){lE=e,l_=lC=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(0!=(e.lanes&n)&&(ua=!0),e.firstContext=null)}function lL(e){var n=e._currentValue;if(l_!==e){if(e={context:e,memoizedValue:n,next:null},null===lC){if(null===lE)throw Error(f(308));lC=e,lE.dependencies={lanes:0,firstContext:e}}else lC=lC.next=e}return n}var lR=null;function lM(e){null===lR?lR=[e]:lR.push(e)}function lF(e,n,t,r){var l=n.interleaved;return null===l?(t.next=t,lM(n)):(t.next=l.next,l.next=t),n.interleaved=t,lO(e,r)}function lO(e,n){e.lanes|=n;var t=e.alternate;for(null!==t&&(t.lanes|=n),t=e,e=e.return;null!==e;)e.childLanes|=n,null!==(t=e.alternate)&&(t.childLanes|=n),t=e,e=e.return;return 3===t.tag?t.stateNode:null}var lD=!1;function lI(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function lU(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function lV(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function lA(e,n,t){var r=e.updateQueue;if(null===r)return null;if(r=r.shared,0!=(2&u2)){var l=r.pending;return null===l?n.next=n:(n.next=l.next,l.next=n),r.pending=n,lO(e,t)}return null===(l=r.interleaved)?(n.next=n,lM(r)):(n.next=l.next,l.next=n),r.interleaved=n,lO(e,t)}function l$(e,n,t){if(null!==(n=n.updateQueue)&&(n=n.shared,0!=(4194240&t))){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,ns(e,t)}}function lj(e,n){var t=e.updateQueue,r=e.alternate;if(null!==r&&t===(r=r.updateQueue)){var l=null,a=null;if(null!==(t=t.firstBaseUpdate)){do{var u={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};null===a?l=a=u:a=a.next=u,t=t.next}while(null!==t);null===a?l=a=n:a=a.next=n}else l=a=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:a,shared:r.shared,effects:r.effects},e.updateQueue=t;return}null===(e=t.lastBaseUpdate)?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function lB(e,n,t,r){var l=e.updateQueue;lD=!1;var a=l.firstBaseUpdate,u=l.lastBaseUpdate,o=l.shared.pending;if(null!==o){l.shared.pending=null;var i=o,s=i.next;i.next=null,null===u?a=s:u.next=s,u=i;var c=e.alternate;null!==c&&(o=(c=c.updateQueue).lastBaseUpdate)!==u&&(null===o?c.firstBaseUpdate=s:o.next=s,c.lastBaseUpdate=i)}if(null!==a){var f=l.baseState;for(u=0,c=s=i=null,o=a;;){var d=o.lane,p=o.eventTime;if((r&d)===d){null!==c&&(c=c.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var m=e,h=o;switch(d=n,p=t,h.tag){case 1:if("function"==typeof(m=h.payload)){f=m.call(p,f,d);break e}f=m;break e;case 3:m.flags=-65537&m.flags|128;case 0:if(null==(d="function"==typeof(m=h.payload)?m.call(p,f,d):m))break e;f=B({},f,d);break e;case 2:lD=!0}}null!==o.callback&&0!==o.lane&&(e.flags|=64,null===(d=l.effects)?l.effects=[o]:d.push(o))}else p={eventTime:p,lane:d,tag:o.tag,payload:o.payload,callback:o.callback,next:null},null===c?(s=c=p,i=f):c=c.next=p,u|=d;if(null===(o=o.next)){if(null===(o=l.shared.pending))break;o=(d=o).next,d.next=null,l.lastBaseUpdate=d,l.shared.pending=null}}if(null===c&&(i=f),l.baseState=i,l.firstBaseUpdate=s,l.lastBaseUpdate=c,null!==(n=l.shared.interleaved)){l=n;do u|=l.lane,l=l.next;while(l!==n)}else null===a&&(l.shared.lanes=0);oe|=u,e.lanes=u,e.memoizedState=f}}function lH(e,n,t){if(e=n.effects,n.effects=null,null!==e)for(n=0;n<e.length;n++){var r=e[n],l=r.callback;if(null!==l){if(r.callback=null,r=t,"function"!=typeof l)throw Error(f(191,l));l.call(r)}}}var lW=(new s.Component).refs;function lQ(e,n,t,r){n=e.memoizedState,t=null==(t=t(r,n))?n:B({},n,t),e.memoizedState=t,0===e.lanes&&(e.updateQueue.baseState=t)}var lq={isMounted:function(e){return!!(e=e._reactInternals)&&eW(e)===e},enqueueSetState:function(e,n,t){e=e._reactInternals;var r=oy(),l=ob(e),a=lV(r,l);a.payload=n,null!=t&&(a.callback=t),null!==(n=lA(e,a,l))&&(ok(n,e,l,r),l$(n,e,l))},enqueueReplaceState:function(e,n,t){e=e._reactInternals;var r=oy(),l=ob(e),a=lV(r,l);a.tag=1,a.payload=n,null!=t&&(a.callback=t),null!==(n=lA(e,a,l))&&(ok(n,e,l,r),l$(n,e,l))},enqueueForceUpdate:function(e,n){e=e._reactInternals;var t=oy(),r=ob(e),l=lV(t,r);l.tag=2,null!=n&&(l.callback=n),null!==(n=lA(e,l,r))&&(ok(n,e,r,t),l$(n,e,r))}};function lK(e,n,t,r,l,a,u){return"function"==typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,a,u):!n.prototype||!n.prototype.isPureReactComponent||!tI(t,r)||!tI(l,a)}function lY(e,n,t){var r=!1,l=rH,a=n.contextType;return"object"==typeof a&&null!==a?a=lL(a):(l=rY(n)?rq:rW.current,a=(r=null!=(r=n.contextTypes))?rK(e,l):rH),n=new n(t,a),e.memoizedState=null!==n.state&&void 0!==n.state?n.state:null,n.updater=lq,e.stateNode=n,n._reactInternals=e,r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=a),n}function lX(e,n,t,r){e=n.state,"function"==typeof n.componentWillReceiveProps&&n.componentWillReceiveProps(t,r),"function"==typeof n.UNSAFE_componentWillReceiveProps&&n.UNSAFE_componentWillReceiveProps(t,r),n.state!==e&&lq.enqueueReplaceState(n,n.state,null)}function lG(e,n,t,r){var l=e.stateNode;l.props=t,l.state=e.memoizedState,l.refs=lW,lI(e);var a=n.contextType;"object"==typeof a&&null!==a?l.context=lL(a):(a=rY(n)?rq:rW.current,l.context=rK(e,a)),l.state=e.memoizedState,"function"==typeof(a=n.getDerivedStateFromProps)&&(lQ(e,n,a,t),l.state=e.memoizedState),"function"==typeof n.getDerivedStateFromProps||"function"==typeof l.getSnapshotBeforeUpdate||"function"!=typeof l.UNSAFE_componentWillMount&&"function"!=typeof l.componentWillMount||(n=l.state,"function"==typeof l.componentWillMount&&l.componentWillMount(),"function"==typeof l.UNSAFE_componentWillMount&&l.UNSAFE_componentWillMount(),n!==l.state&&lq.enqueueReplaceState(l,l.state,null),lB(e,t,l,r),l.state=e.memoizedState),"function"==typeof l.componentDidMount&&(e.flags|=4194308)}function lZ(e,n,t){if(null!==(e=t.ref)&&"function"!=typeof e&&"object"!=typeof e){if(t._owner){if(t=t._owner){if(1!==t.tag)throw Error(f(309));var r=t.stateNode}if(!r)throw Error(f(147,e));var l=r,a=""+e;return null!==n&&null!==n.ref&&"function"==typeof n.ref&&n.ref._stringRef===a?n.ref:((n=function(e){var n=l.refs;n===lW&&(n=l.refs={}),null===e?delete n[a]:n[a]=e})._stringRef=a,n)}if("string"!=typeof e)throw Error(f(284));if(!t._owner)throw Error(f(290,e))}return e}function lJ(e,n){throw Error(f(31,"[object Object]"===(e=Object.prototype.toString.call(n))?"object with keys {"+Object.keys(n).join(", ")+"}":e))}function l0(e){return(0,e._init)(e._payload)}function l1(e){function n(n,t){if(e){var r=n.deletions;null===r?(n.deletions=[t],n.flags|=16):r.push(t)}}function t(t,r){if(!e)return null;for(;null!==r;)n(t,r),r=r.sibling;return null}function r(e,n){for(e=new Map;null!==n;)null!==n.key?e.set(n.key,n):e.set(n.index,n),n=n.sibling;return e}function l(e,n){return(e=oK(e,n)).index=0,e.sibling=null,e}function a(n,t,r){return(n.index=r,e)?null!==(r=n.alternate)?(r=r.index)<t?(n.flags|=2,t):r:(n.flags|=2,t):(n.flags|=1048576,t)}function u(n){return e&&null===n.alternate&&(n.flags|=2),n}function o(e,n,t,r){return null===n||6!==n.tag?((n=oZ(t,e.mode,r)).return=e,n):((n=l(n,t)).return=e,n)}function i(e,n,t,r){var a=t.type;return a===z?c(e,n,t.props.children,r,t.key):null!==n&&(n.elementType===a||"object"==typeof a&&null!==a&&a.$$typeof===U&&l0(a)===n.type)?((r=l(n,t.props)).ref=lZ(e,n,t),r.return=e,r):((r=oY(t.type,t.key,t.props,null,e.mode,r)).ref=lZ(e,n,t),r.return=e,r)}function s(e,n,t,r){return null===n||4!==n.tag||n.stateNode.containerInfo!==t.containerInfo||n.stateNode.implementation!==t.implementation?((n=oJ(t,e.mode,r)).return=e,n):((n=l(n,t.children||[])).return=e,n)}function c(e,n,t,r,a){return null===n||7!==n.tag?((n=oX(t,e.mode,r,a)).return=e,n):((n=l(n,t)).return=e,n)}function d(e,n,t){if("string"==typeof n&&""!==n||"number"==typeof n)return(n=oZ(""+n,e.mode,t)).return=e,n;if("object"==typeof n&&null!==n){switch(n.$$typeof){case P:return(t=oY(n.type,n.key,n.props,null,e.mode,t)).ref=lZ(e,null,n),t.return=e,t;case N:return(n=oJ(n,e.mode,t)).return=e,n;case U:var r=n._init;return d(e,r(n._payload),t)}if(el(n)||$(n))return(n=oX(n,e.mode,t,null)).return=e,n;lJ(e,n)}return null}function p(e,n,t,r){var l=null!==n?n.key:null;if("string"==typeof t&&""!==t||"number"==typeof t)return null!==l?null:o(e,n,""+t,r);if("object"==typeof t&&null!==t){switch(t.$$typeof){case P:return t.key===l?i(e,n,t,r):null;case N:return t.key===l?s(e,n,t,r):null;case U:return p(e,n,(l=t._init)(t._payload),r)}if(el(t)||$(t))return null!==l?null:c(e,n,t,r,null);lJ(e,t)}return null}function m(e,n,t,r,l){if("string"==typeof r&&""!==r||"number"==typeof r)return o(n,e=e.get(t)||null,""+r,l);if("object"==typeof r&&null!==r){switch(r.$$typeof){case P:return i(n,e=e.get(null===r.key?t:r.key)||null,r,l);case N:return s(n,e=e.get(null===r.key?t:r.key)||null,r,l);case U:return m(e,n,t,(0,r._init)(r._payload),l)}if(el(r)||$(r))return c(n,e=e.get(t)||null,r,l,null);lJ(n,r)}return null}return function o(i,s,c,h){if("object"==typeof c&&null!==c&&c.type===z&&null===c.key&&(c=c.props.children),"object"==typeof c&&null!==c){switch(c.$$typeof){case P:e:{for(var g=c.key,v=s;null!==v;){if(v.key===g){if((g=c.type)===z){if(7===v.tag){t(i,v.sibling),(s=l(v,c.props.children)).return=i,i=s;break e}}else if(v.elementType===g||"object"==typeof g&&null!==g&&g.$$typeof===U&&l0(g)===v.type){t(i,v.sibling),(s=l(v,c.props)).ref=lZ(i,v,c),s.return=i,i=s;break e}t(i,v);break}n(i,v),v=v.sibling}c.type===z?((s=oX(c.props.children,i.mode,h,c.key)).return=i,i=s):((h=oY(c.type,c.key,c.props,null,i.mode,h)).ref=lZ(i,s,c),h.return=i,i=h)}return u(i);case N:e:{for(v=c.key;null!==s;){if(s.key===v){if(4===s.tag&&s.stateNode.containerInfo===c.containerInfo&&s.stateNode.implementation===c.implementation){t(i,s.sibling),(s=l(s,c.children||[])).return=i,i=s;break e}t(i,s);break}n(i,s),s=s.sibling}(s=oJ(c,i.mode,h)).return=i,i=s}return u(i);case U:return o(i,s,(v=c._init)(c._payload),h)}if(el(c))return function(l,u,o,i){for(var s=null,c=null,f=u,h=u=0,g=null;null!==f&&h<o.length;h++){f.index>h?(g=f,f=null):g=f.sibling;var v=p(l,f,o[h],i);if(null===v){null===f&&(f=g);break}e&&f&&null===v.alternate&&n(l,f),u=a(v,u,h),null===c?s=v:c.sibling=v,c=v,f=g}if(h===o.length)return t(l,f),lc&&ll(l,h),s;if(null===f){for(;h<o.length;h++)null!==(f=d(l,o[h],i))&&(u=a(f,u,h),null===c?s=f:c.sibling=f,c=f);return lc&&ll(l,h),s}for(f=r(l,f);h<o.length;h++)null!==(g=m(f,l,h,o[h],i))&&(e&&null!==g.alternate&&f.delete(null===g.key?h:g.key),u=a(g,u,h),null===c?s=g:c.sibling=g,c=g);return e&&f.forEach(function(e){return n(l,e)}),lc&&ll(l,h),s}(i,s,c,h);if($(c))return function(l,u,o,i){var s=$(o);if("function"!=typeof s)throw Error(f(150));if(null==(o=s.call(o)))throw Error(f(151));for(var c=s=null,h=u,g=u=0,v=null,y=o.next();null!==h&&!y.done;g++,y=o.next()){h.index>g?(v=h,h=null):v=h.sibling;var b=p(l,h,y.value,i);if(null===b){null===h&&(h=v);break}e&&h&&null===b.alternate&&n(l,h),u=a(b,u,g),null===c?s=b:c.sibling=b,c=b,h=v}if(y.done)return t(l,h),lc&&ll(l,g),s;if(null===h){for(;!y.done;g++,y=o.next())null!==(y=d(l,y.value,i))&&(u=a(y,u,g),null===c?s=y:c.sibling=y,c=y);return lc&&ll(l,g),s}for(h=r(l,h);!y.done;g++,y=o.next())null!==(y=m(h,l,g,y.value,i))&&(e&&null!==y.alternate&&h.delete(null===y.key?g:y.key),u=a(y,u,g),null===c?s=y:c.sibling=y,c=y);return e&&h.forEach(function(e){return n(l,e)}),lc&&ll(l,g),s}(i,s,c,h);lJ(i,c)}return"string"==typeof c&&""!==c||"number"==typeof c?(c=""+c,null!==s&&6===s.tag?(t(i,s.sibling),(s=l(s,c)).return=i,i=s):(t(i,s),(s=oZ(c,i.mode,h)).return=i,i=s),u(i)):t(i,s)}}var l2=l1(!0),l3=l1(!1),l4={},l8=r$(l4),l6=r$(l4),l5=r$(l4);function l9(e){if(e===l4)throw Error(f(174));return e}function l7(e,n){switch(rB(l5,n),rB(l6,e),rB(l8,l4),e=n.nodeType){case 9:case 11:n=(n=n.documentElement)?n.namespaceURI:ef(null,"");break;default:n=(e=8===e?n.parentNode:n).namespaceURI||null,e=e.tagName,n=ef(n,e)}rj(l8),rB(l8,n)}function ae(){rj(l8),rj(l6),rj(l5)}function an(e){l9(l5.current);var n=l9(l8.current),t=ef(n,e.type);n!==t&&(rB(l6,e),rB(l8,t))}function at(e){l6.current===e&&(rj(l8),rj(l6))}var ar=r$(0);function al(e){for(var n=e;null!==n;){if(13===n.tag){var t=n.memoizedState;if(null!==t&&(null===(t=t.dehydrated)||"$?"===t.data||"$!"===t.data))return n}else if(19===n.tag&&void 0!==n.memoizedProps.revealOrder){if(0!=(128&n.flags))return n}else if(null!==n.child){n.child.return=n,n=n.child;continue}if(n===e)break;for(;null===n.sibling;){if(null===n.return||n.return===e)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}return null}var aa=[];function au(){for(var e=0;e<aa.length;e++)aa[e]._workInProgressVersionPrimary=null;aa.length=0}var ao=_.ReactCurrentDispatcher,ai=_.ReactCurrentBatchConfig,as=0,ac=null,af=null,ad=null,ap=!1,am=!1,ah=0,ag=0;function av(){throw Error(f(321))}function ay(e,n){if(null===n)return!1;for(var t=0;t<n.length&&t<e.length;t++)if(!tD(e[t],n[t]))return!1;return!0}function ab(e,n,t,r,l,a){if(as=a,ac=n,n.memoizedState=null,n.updateQueue=null,n.lanes=0,ao.current=null===e||null===e.memoizedState?a2:a3,e=t(r,l),am){a=0;do{if(am=!1,ah=0,25<=a)throw Error(f(301));a+=1,ad=af=null,n.updateQueue=null,ao.current=a4,e=t(r,l)}while(am)}if(ao.current=a1,n=null!==af&&null!==af.next,as=0,ad=af=ac=null,ap=!1,n)throw Error(f(300));return e}function ak(){var e=0!==ah;return ah=0,e}function aw(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===ad?ac.memoizedState=ad=e:ad=ad.next=e,ad}function aS(){if(null===af){var e=ac.alternate;e=null!==e?e.memoizedState:null}else e=af.next;var n=null===ad?ac.memoizedState:ad.next;if(null!==n)ad=n,af=e;else{if(null===e)throw Error(f(310));e={memoizedState:(af=e).memoizedState,baseState:af.baseState,baseQueue:af.baseQueue,queue:af.queue,next:null},null===ad?ac.memoizedState=ad=e:ad=ad.next=e}return ad}function ax(e,n){return"function"==typeof n?n(e):n}function aE(e){var n=aS(),t=n.queue;if(null===t)throw Error(f(311));t.lastRenderedReducer=e;var r=af,l=r.baseQueue,a=t.pending;if(null!==a){if(null!==l){var u=l.next;l.next=a.next,a.next=u}r.baseQueue=l=a,t.pending=null}if(null!==l){a=l.next,r=r.baseState;var o=u=null,i=null,s=a;do{var c=s.lane;if((as&c)===c)null!==i&&(i=i.next={lane:0,action:s.action,hasEagerState:s.hasEagerState,eagerState:s.eagerState,next:null}),r=s.hasEagerState?s.eagerState:e(r,s.action);else{var d={lane:c,action:s.action,hasEagerState:s.hasEagerState,eagerState:s.eagerState,next:null};null===i?(o=i=d,u=r):i=i.next=d,ac.lanes|=c,oe|=c}s=s.next}while(null!==s&&s!==a);null===i?u=r:i.next=o,tD(r,n.memoizedState)||(ua=!0),n.memoizedState=r,n.baseState=u,n.baseQueue=i,t.lastRenderedState=r}if(null!==(e=t.interleaved)){l=e;do a=l.lane,ac.lanes|=a,oe|=a,l=l.next;while(l!==e)}else null===l&&(t.lanes=0);return[n.memoizedState,t.dispatch]}function aC(e){var n=aS(),t=n.queue;if(null===t)throw Error(f(311));t.lastRenderedReducer=e;var r=t.dispatch,l=t.pending,a=n.memoizedState;if(null!==l){t.pending=null;var u=l=l.next;do a=e(a,u.action),u=u.next;while(u!==l);tD(a,n.memoizedState)||(ua=!0),n.memoizedState=a,null===n.baseQueue&&(n.baseState=a),t.lastRenderedState=a}return[a,r]}function a_(){}function aP(e,n){var t=ac,r=aS(),l=n(),a=!tD(r.memoizedState,l);if(a&&(r.memoizedState=l,ua=!0),r=r.queue,aV(aT.bind(null,t,r,e),[e]),r.getSnapshot!==n||a||null!==ad&&1&ad.memoizedState.tag){if(t.flags|=2048,aF(9,az.bind(null,t,r,l,n),void 0,null),null===u3)throw Error(f(349));0!=(30&as)||aN(t,n,l)}return l}function aN(e,n,t){e.flags|=16384,e={getSnapshot:n,value:t},null===(n=ac.updateQueue)?(n={lastEffect:null,stores:null},ac.updateQueue=n,n.stores=[e]):null===(t=n.stores)?n.stores=[e]:t.push(e)}function az(e,n,t,r){n.value=t,n.getSnapshot=r,aL(n)&&aR(e)}function aT(e,n,t){return t(function(){aL(n)&&aR(e)})}function aL(e){var n=e.getSnapshot;e=e.value;try{var t=n();return!tD(e,t)}catch(e){return!0}}function aR(e){var n=lO(e,1);null!==n&&ok(n,e,1,-1)}function aM(e){var n=aw();return"function"==typeof e&&(e=e()),n.memoizedState=n.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ax,lastRenderedState:e},n.queue=e,e=e.dispatch=aG.bind(null,ac,e),[n.memoizedState,e]}function aF(e,n,t,r){return e={tag:e,create:n,destroy:t,deps:r,next:null},null===(n=ac.updateQueue)?(n={lastEffect:null,stores:null},ac.updateQueue=n,n.lastEffect=e.next=e):null===(t=n.lastEffect)?n.lastEffect=e.next=e:(r=t.next,t.next=e,e.next=r,n.lastEffect=e),e}function aO(){return aS().memoizedState}function aD(e,n,t,r){var l=aw();ac.flags|=e,l.memoizedState=aF(1|n,t,void 0,void 0===r?null:r)}function aI(e,n,t,r){var l=aS();r=void 0===r?null:r;var a=void 0;if(null!==af){var u=af.memoizedState;if(a=u.destroy,null!==r&&ay(r,u.deps)){l.memoizedState=aF(n,t,a,r);return}}ac.flags|=e,l.memoizedState=aF(1|n,t,a,r)}function aU(e,n){return aD(8390656,8,e,n)}function aV(e,n){return aI(2048,8,e,n)}function aA(e,n){return aI(4,2,e,n)}function a$(e,n){return aI(4,4,e,n)}function aj(e,n){return"function"==typeof n?(n(e=e()),function(){n(null)}):null!=n?(e=e(),n.current=e,function(){n.current=null}):void 0}function aB(e,n,t){return t=null!=t?t.concat([e]):null,aI(4,4,aj.bind(null,n,e),t)}function aH(){}function aW(e,n){var t=aS();n=void 0===n?null:n;var r=t.memoizedState;return null!==r&&null!==n&&ay(n,r[1])?r[0]:(t.memoizedState=[e,n],e)}function aQ(e,n){var t=aS();n=void 0===n?null:n;var r=t.memoizedState;return null!==r&&null!==n&&ay(n,r[1])?r[0]:(e=e(),t.memoizedState=[e,n],e)}function aq(e,n,t){return 0==(21&as)?(e.baseState&&(e.baseState=!1,ua=!0),e.memoizedState=t):(tD(t,n)||(t=nu(),ac.lanes|=t,oe|=t,e.baseState=!0),n)}function aK(e,n){var t=nc;nc=0!==t&&4>t?t:4,e(!0);var r=ai.transition;ai.transition={};try{e(!1),n()}finally{nc=t,ai.transition=r}}function aY(){return aS().memoizedState}function aX(e,n,t){var r=ob(e);t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},aZ(e)?aJ(n,t):null!==(t=lF(e,n,t,r))&&(ok(t,e,r,oy()),a0(t,n,r))}function aG(e,n,t){var r=ob(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(aZ(e))aJ(n,l);else{var a=e.alternate;if(0===e.lanes&&(null===a||0===a.lanes)&&null!==(a=n.lastRenderedReducer))try{var u=n.lastRenderedState,o=a(u,t);if(l.hasEagerState=!0,l.eagerState=o,tD(o,u)){var i=n.interleaved;null===i?(l.next=l,lM(n)):(l.next=i.next,i.next=l),n.interleaved=l;return}}catch(e){}finally{}null!==(t=lF(e,n,l,r))&&(ok(t,e,r,l=oy()),a0(t,n,r))}}function aZ(e){var n=e.alternate;return e===ac||null!==n&&n===ac}function aJ(e,n){am=ap=!0;var t=e.pending;null===t?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function a0(e,n,t){if(0!=(4194240&t)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,ns(e,t)}}var a1={readContext:lL,useCallback:av,useContext:av,useEffect:av,useImperativeHandle:av,useInsertionEffect:av,useLayoutEffect:av,useMemo:av,useReducer:av,useRef:av,useState:av,useDebugValue:av,useDeferredValue:av,useTransition:av,useMutableSource:av,useSyncExternalStore:av,useId:av,unstable_isNewReconciler:!1},a2={readContext:lL,useCallback:function(e,n){return aw().memoizedState=[e,void 0===n?null:n],e},useContext:lL,useEffect:aU,useImperativeHandle:function(e,n,t){return t=null!=t?t.concat([e]):null,aD(4194308,4,aj.bind(null,n,e),t)},useLayoutEffect:function(e,n){return aD(4194308,4,e,n)},useInsertionEffect:function(e,n){return aD(4,2,e,n)},useMemo:function(e,n){var t=aw();return n=void 0===n?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=aw();return n=void 0!==t?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=aX.bind(null,ac,e),[r.memoizedState,e]},useRef:function(e){return e={current:e},aw().memoizedState=e},useState:aM,useDebugValue:aH,useDeferredValue:function(e){return aw().memoizedState=e},useTransition:function(){var e=aM(!1),n=e[0];return e=aK.bind(null,e[1]),aw().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ac,l=aw();if(lc){if(void 0===t)throw Error(f(407));t=t()}else{if(t=n(),null===u3)throw Error(f(349));0!=(30&as)||aN(r,n,t)}l.memoizedState=t;var a={value:t,getSnapshot:n};return l.queue=a,aU(aT.bind(null,r,a,e),[e]),r.flags|=2048,aF(9,az.bind(null,r,a,t,n),void 0,null),t},useId:function(){var e=aw(),n=u3.identifierPrefix;if(lc){var t=lr,r=lt;n=":"+n+"R"+(t=(r&~(1<<32-e9(r)-1)).toString(32)+t),0<(t=ah++)&&(n+="H"+t.toString(32)),n+=":"}else n=":"+n+"r"+(t=ag++).toString(32)+":";return e.memoizedState=n},unstable_isNewReconciler:!1},a3={readContext:lL,useCallback:aW,useContext:lL,useEffect:aV,useImperativeHandle:aB,useInsertionEffect:aA,useLayoutEffect:a$,useMemo:aQ,useReducer:aE,useRef:aO,useState:function(){return aE(ax)},useDebugValue:aH,useDeferredValue:function(e){return aq(aS(),af.memoizedState,e)},useTransition:function(){return[aE(ax)[0],aS().memoizedState]},useMutableSource:a_,useSyncExternalStore:aP,useId:aY,unstable_isNewReconciler:!1},a4={readContext:lL,useCallback:aW,useContext:lL,useEffect:aV,useImperativeHandle:aB,useInsertionEffect:aA,useLayoutEffect:a$,useMemo:aQ,useReducer:aC,useRef:aO,useState:function(){return aC(ax)},useDebugValue:aH,useDeferredValue:function(e){var n=aS();return null===af?n.memoizedState=e:aq(n,af.memoizedState,e)},useTransition:function(){return[aC(ax)[0],aS().memoizedState]},useMutableSource:a_,useSyncExternalStore:aP,useId:aY,unstable_isNewReconciler:!1};function a8(e,n){try{var t="",r=n;do t+=function(e){switch(e.tag){case 5:return H(e.type);case 16:return H("Lazy");case 13:return H("Suspense");case 19:return H("SuspenseList");case 0:case 2:case 15:return e=Q(e.type,!1);case 11:return e=Q(e.type.render,!1);case 1:return e=Q(e.type,!0);default:return""}}(r),r=r.return;while(r);var l=t}catch(e){l="\nError generating stack: "+e.message+"\n"+e.stack}return{value:e,source:n,stack:l,digest:null}}function a6(e,n,t){return{value:e,source:null,stack:null!=t?t:null,digest:null!=n?n:null}}function a5(e,n){try{console.error(n.value)}catch(e){setTimeout(function(){throw e})}}var a9="function"==typeof WeakMap?WeakMap:Map;function a7(e,n,t){(t=lV(-1,t)).tag=3,t.payload={element:null};var r=n.value;return t.callback=function(){oi||(oi=!0,os=r),a5(e,n)},t}function ue(e,n,t){(t=lV(-1,t)).tag=3;var r=e.type.getDerivedStateFromError;if("function"==typeof r){var l=n.value;t.payload=function(){return r(l)},t.callback=function(){a5(e,n)}}var a=e.stateNode;return null!==a&&"function"==typeof a.componentDidCatch&&(t.callback=function(){a5(e,n),"function"!=typeof r&&(null===oc?oc=new Set([this]):oc.add(this));var t=n.stack;this.componentDidCatch(n.value,{componentStack:null!==t?t:""})}),t}function un(e,n,t){var r=e.pingCache;if(null===r){r=e.pingCache=new a9;var l=new Set;r.set(n,l)}else void 0===(l=r.get(n))&&(l=new Set,r.set(n,l));l.has(t)||(l.add(t),e=o$.bind(null,e,n,t),n.then(e,e))}function ut(e){do{var n;if((n=13===e.tag)&&(n=null===(n=e.memoizedState)||null!==n.dehydrated),n)return e;e=e.return}while(null!==e);return null}function ur(e,n,t,r,l){return 0==(1&e.mode)?(e===n?e.flags|=65536:(e.flags|=128,t.flags|=131072,t.flags&=-52805,1===t.tag&&(null===t.alternate?t.tag=17:((n=lV(-1,1)).tag=2,lA(t,n,1))),t.lanes|=1),e):(e.flags|=65536,e.lanes=l,e)}var ul=_.ReactCurrentOwner,ua=!1;function uu(e,n,t,r){n.child=null===e?l3(n,null,t,r):l2(n,e.child,t,r)}function uo(e,n,t,r,l){t=t.render;var a=n.ref;return(lT(n,l),r=ab(e,n,t,r,a,l),t=ak(),null===e||ua)?(lc&&t&&lu(n),n.flags|=1,uu(e,n,r,l),n.child):(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~l,u_(e,n,l))}function ui(e,n,t,r,l){if(null===e){var a=t.type;return"function"!=typeof a||oq(a)||void 0!==a.defaultProps||null!==t.compare||void 0!==t.defaultProps?((e=oY(t.type,null,r,n,n.mode,l)).ref=n.ref,e.return=n,n.child=e):(n.tag=15,n.type=a,us(e,n,a,r,l))}if(a=e.child,0==(e.lanes&l)){var u=a.memoizedProps;if((t=null!==(t=t.compare)?t:tI)(u,r)&&e.ref===n.ref)return u_(e,n,l)}return n.flags|=1,(e=oK(a,r)).ref=n.ref,e.return=n,n.child=e}function us(e,n,t,r,l){if(null!==e){var a=e.memoizedProps;if(tI(a,r)&&e.ref===n.ref){if(ua=!1,n.pendingProps=r=a,0==(e.lanes&l))return n.lanes=e.lanes,u_(e,n,l);0!=(131072&e.flags)&&(ua=!0)}}return ud(e,n,t,r,l)}function uc(e,n,t){var r=n.pendingProps,l=r.children,a=null!==e?e.memoizedState:null;if("hidden"===r.mode){if(0==(1&n.mode))n.memoizedState={baseLanes:0,cachePool:null,transitions:null},rB(u5,u6),u6|=t;else{if(0==(1073741824&t))return e=null!==a?a.baseLanes|t:t,n.lanes=n.childLanes=1073741824,n.memoizedState={baseLanes:e,cachePool:null,transitions:null},n.updateQueue=null,rB(u5,u6),u6|=e,null;n.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=null!==a?a.baseLanes:t,rB(u5,u6),u6|=r}}else null!==a?(r=a.baseLanes|t,n.memoizedState=null):r=t,rB(u5,u6),u6|=r;return uu(e,n,l,t),n.child}function uf(e,n){var t=n.ref;(null===e&&null!==t||null!==e&&e.ref!==t)&&(n.flags|=512,n.flags|=2097152)}function ud(e,n,t,r,l){var a=rY(t)?rq:rW.current;return(a=rK(n,a),lT(n,l),t=ab(e,n,t,r,a,l),r=ak(),null===e||ua)?(lc&&r&&lu(n),n.flags|=1,uu(e,n,t,l),n.child):(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~l,u_(e,n,l))}function up(e,n,t,r,l){if(rY(t)){var a=!0;rJ(n)}else a=!1;if(lT(n,l),null===n.stateNode)uC(e,n),lY(n,t,r),lG(n,t,r,l),r=!0;else if(null===e){var u=n.stateNode,o=n.memoizedProps;u.props=o;var i=u.context,s=t.contextType;s="object"==typeof s&&null!==s?lL(s):rK(n,s=rY(t)?rq:rW.current);var c=t.getDerivedStateFromProps,f="function"==typeof c||"function"==typeof u.getSnapshotBeforeUpdate;f||"function"!=typeof u.UNSAFE_componentWillReceiveProps&&"function"!=typeof u.componentWillReceiveProps||(o!==r||i!==s)&&lX(n,u,r,s),lD=!1;var d=n.memoizedState;u.state=d,lB(n,r,u,l),i=n.memoizedState,o!==r||d!==i||rQ.current||lD?("function"==typeof c&&(lQ(n,t,c,r),i=n.memoizedState),(o=lD||lK(n,t,o,r,d,i,s))?(f||"function"!=typeof u.UNSAFE_componentWillMount&&"function"!=typeof u.componentWillMount||("function"==typeof u.componentWillMount&&u.componentWillMount(),"function"==typeof u.UNSAFE_componentWillMount&&u.UNSAFE_componentWillMount()),"function"==typeof u.componentDidMount&&(n.flags|=4194308)):("function"==typeof u.componentDidMount&&(n.flags|=4194308),n.memoizedProps=r,n.memoizedState=i),u.props=r,u.state=i,u.context=s,r=o):("function"==typeof u.componentDidMount&&(n.flags|=4194308),r=!1)}else{u=n.stateNode,lU(e,n),o=n.memoizedProps,s=n.type===n.elementType?o:lS(n.type,o),u.props=s,f=n.pendingProps,d=u.context,i="object"==typeof(i=t.contextType)&&null!==i?lL(i):rK(n,i=rY(t)?rq:rW.current);var p=t.getDerivedStateFromProps;(c="function"==typeof p||"function"==typeof u.getSnapshotBeforeUpdate)||"function"!=typeof u.UNSAFE_componentWillReceiveProps&&"function"!=typeof u.componentWillReceiveProps||(o!==f||d!==i)&&lX(n,u,r,i),lD=!1,d=n.memoizedState,u.state=d,lB(n,r,u,l);var m=n.memoizedState;o!==f||d!==m||rQ.current||lD?("function"==typeof p&&(lQ(n,t,p,r),m=n.memoizedState),(s=lD||lK(n,t,s,r,d,m,i)||!1)?(c||"function"!=typeof u.UNSAFE_componentWillUpdate&&"function"!=typeof u.componentWillUpdate||("function"==typeof u.componentWillUpdate&&u.componentWillUpdate(r,m,i),"function"==typeof u.UNSAFE_componentWillUpdate&&u.UNSAFE_componentWillUpdate(r,m,i)),"function"==typeof u.componentDidUpdate&&(n.flags|=4),"function"==typeof u.getSnapshotBeforeUpdate&&(n.flags|=1024)):("function"!=typeof u.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=4),"function"!=typeof u.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=1024),n.memoizedProps=r,n.memoizedState=m),u.props=r,u.state=m,u.context=i,r=s):("function"!=typeof u.componentDidUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=4),"function"!=typeof u.getSnapshotBeforeUpdate||o===e.memoizedProps&&d===e.memoizedState||(n.flags|=1024),r=!1)}return um(e,n,t,r,a,l)}function um(e,n,t,r,l,a){uf(e,n);var u=0!=(128&n.flags);if(!r&&!u)return l&&r0(n,t,!1),u_(e,n,a);r=n.stateNode,ul.current=n;var o=u&&"function"!=typeof t.getDerivedStateFromError?null:r.render();return n.flags|=1,null!==e&&u?(n.child=l2(n,e.child,null,a),n.child=l2(n,null,o,a)):uu(e,n,o,a),n.memoizedState=r.state,l&&r0(n,t,!0),n.child}function uh(e){var n=e.stateNode;n.pendingContext?rG(e,n.pendingContext,n.pendingContext!==n.context):n.context&&rG(e,n.context,!1),l7(e,n.containerInfo)}function ug(e,n,t,r,l){return lb(),lk(l),n.flags|=256,uu(e,n,t,r),n.child}var uv={dehydrated:null,treeContext:null,retryLane:0};function uy(e){return{baseLanes:e,cachePool:null,transitions:null}}function ub(e,n,t){var r,l=n.pendingProps,a=ar.current,u=!1,o=0!=(128&n.flags);if((r=o)||(r=(null===e||null!==e.memoizedState)&&0!=(2&a)),r?(u=!0,n.flags&=-129):(null===e||null!==e.memoizedState)&&(a|=1),rB(ar,1&a),null===e)return(lh(n),null!==(e=n.memoizedState)&&null!==(e=e.dehydrated))?(0==(1&n.mode)?n.lanes=1:"$!"===e.data?n.lanes=8:n.lanes=1073741824,null):(o=l.children,e=l.fallback,u?(l=n.mode,u=n.child,o={mode:"hidden",children:o},0==(1&l)&&null!==u?(u.childLanes=0,u.pendingProps=o):u=oG(o,l,0,null),e=oX(e,l,t,null),u.return=n,e.return=n,u.sibling=e,n.child=u,n.child.memoizedState=uy(t),n.memoizedState=uv,e):uk(n,o));if(null!==(a=e.memoizedState)&&null!==(r=a.dehydrated))return function(e,n,t,r,l,a,u){if(t)return 256&n.flags?(n.flags&=-257,uw(e,n,u,r=a6(Error(f(422))))):null!==n.memoizedState?(n.child=e.child,n.flags|=128,null):(a=r.fallback,l=n.mode,r=oG({mode:"visible",children:r.children},l,0,null),a=oX(a,l,u,null),a.flags|=2,r.return=n,a.return=n,r.sibling=a,n.child=r,0!=(1&n.mode)&&l2(n,e.child,null,u),n.child.memoizedState=uy(u),n.memoizedState=uv,a);if(0==(1&n.mode))return uw(e,n,u,null);if("$!"===l.data){if(r=l.nextSibling&&l.nextSibling.dataset)var o=r.dgst;return r=o,r=a6(a=Error(f(419)),r,void 0),uw(e,n,u,r)}if(o=0!=(u&e.childLanes),ua||o){if(null!==(r=u3)){switch(u&-u){case 4:l=2;break;case 16:l=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:l=32;break;case 536870912:l=268435456;break;default:l=0}0!==(l=0!=(l&(r.suspendedLanes|u))?0:l)&&l!==a.retryLane&&(a.retryLane=l,lO(e,l),ok(r,e,l,-1))}return oM(),uw(e,n,u,r=a6(Error(f(421))))}return"$?"===l.data?(n.flags|=128,n.child=e.child,n=oB.bind(null,e),l._reactRetry=n,null):(e=a.treeContext,ls=r_(l.nextSibling),li=n,lc=!0,lf=null,null!==e&&(r7[le++]=lt,r7[le++]=lr,r7[le++]=ln,lt=e.id,lr=e.overflow,ln=n),n=uk(n,r.children),n.flags|=4096,n)}(e,n,o,l,r,a,t);if(u){u=l.fallback,o=n.mode,r=(a=e.child).sibling;var i={mode:"hidden",children:l.children};return 0==(1&o)&&n.child!==a?((l=n.child).childLanes=0,l.pendingProps=i,n.deletions=null):(l=oK(a,i)).subtreeFlags=14680064&a.subtreeFlags,null!==r?u=oK(r,u):(u=oX(u,o,t,null),u.flags|=2),u.return=n,l.return=n,l.sibling=u,n.child=l,l=u,u=n.child,o=null===(o=e.child.memoizedState)?uy(t):{baseLanes:o.baseLanes|t,cachePool:null,transitions:o.transitions},u.memoizedState=o,u.childLanes=e.childLanes&~t,n.memoizedState=uv,l}return e=(u=e.child).sibling,l=oK(u,{mode:"visible",children:l.children}),0==(1&n.mode)&&(l.lanes=t),l.return=n,l.sibling=null,null!==e&&(null===(t=n.deletions)?(n.deletions=[e],n.flags|=16):t.push(e)),n.child=l,n.memoizedState=null,l}function uk(e,n){return(n=oG({mode:"visible",children:n},e.mode,0,null)).return=e,e.child=n}function uw(e,n,t,r){return null!==r&&lk(r),l2(n,e.child,null,t),e=uk(n,n.pendingProps.children),e.flags|=2,n.memoizedState=null,e}function uS(e,n,t){e.lanes|=n;var r=e.alternate;null!==r&&(r.lanes|=n),lz(e.return,n,t)}function ux(e,n,t,r,l){var a=e.memoizedState;null===a?e.memoizedState={isBackwards:n,rendering:null,renderingStartTime:0,last:r,tail:t,tailMode:l}:(a.isBackwards=n,a.rendering=null,a.renderingStartTime=0,a.last=r,a.tail=t,a.tailMode=l)}function uE(e,n,t){var r=n.pendingProps,l=r.revealOrder,a=r.tail;if(uu(e,n,r.children,t),0!=(2&(r=ar.current)))r=1&r|2,n.flags|=128;else{if(null!==e&&0!=(128&e.flags))e:for(e=n.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&uS(e,t,n);else if(19===e.tag)uS(e,t,n);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===n)break e;for(;null===e.sibling;){if(null===e.return||e.return===n)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(rB(ar,r),0==(1&n.mode))n.memoizedState=null;else switch(l){case"forwards":for(l=null,t=n.child;null!==t;)null!==(e=t.alternate)&&null===al(e)&&(l=t),t=t.sibling;null===(t=l)?(l=n.child,n.child=null):(l=t.sibling,t.sibling=null),ux(n,!1,l,t,a);break;case"backwards":for(t=null,l=n.child,n.child=null;null!==l;){if(null!==(e=l.alternate)&&null===al(e)){n.child=l;break}e=l.sibling,l.sibling=t,t=l,l=e}ux(n,!0,t,null,a);break;case"together":ux(n,!1,null,null,void 0);break;default:n.memoizedState=null}return n.child}function uC(e,n){0==(1&n.mode)&&null!==e&&(e.alternate=null,n.alternate=null,n.flags|=2)}function u_(e,n,t){if(null!==e&&(n.dependencies=e.dependencies),oe|=n.lanes,0==(t&n.childLanes))return null;if(null!==e&&n.child!==e.child)throw Error(f(153));if(null!==n.child){for(t=oK(e=n.child,e.pendingProps),n.child=t,t.return=n;null!==e.sibling;)e=e.sibling,(t=t.sibling=oK(e,e.pendingProps)).return=n;t.sibling=null}return n.child}function uP(e,n){if(!lc)switch(e.tailMode){case"hidden":n=e.tail;for(var t=null;null!==n;)null!==n.alternate&&(t=n),n=n.sibling;null===t?e.tail=null:t.sibling=null;break;case"collapsed":t=e.tail;for(var r=null;null!==t;)null!==t.alternate&&(r=t),t=t.sibling;null===r?n||null===e.tail?e.tail=null:e.tail.sibling=null:r.sibling=null}}function uN(e){var n=null!==e.alternate&&e.alternate.child===e.child,t=0,r=0;if(n)for(var l=e.child;null!==l;)t|=l.lanes|l.childLanes,r|=14680064&l.subtreeFlags,r|=14680064&l.flags,l.return=e,l=l.sibling;else for(l=e.child;null!==l;)t|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=t,n}l=function(e,n){for(var t=n.child;null!==t;){if(5===t.tag||6===t.tag)e.appendChild(t.stateNode);else if(4!==t.tag&&null!==t.child){t.child.return=t,t=t.child;continue}if(t===n)break;for(;null===t.sibling;){if(null===t.return||t.return===n)return;t=t.return}t.sibling.return=t.return,t=t.sibling}},a=function(){},u=function(e,n,t,r){var l=e.memoizedProps;if(l!==r){e=n.stateNode,l9(l8.current);var a,u=null;switch(t){case"input":l=Z(e,l),r=Z(e,r),u=[];break;case"select":l=B({},l,{value:void 0}),r=B({},r,{value:void 0}),u=[];break;case"textarea":l=eu(e,l),r=eu(e,r),u=[];break;default:"function"!=typeof l.onClick&&"function"==typeof r.onClick&&(e.onclick=rg)}for(s in ew(t,r),t=null,l)if(!r.hasOwnProperty(s)&&l.hasOwnProperty(s)&&null!=l[s]){if("style"===s){var o=l[s];for(a in o)o.hasOwnProperty(a)&&(t||(t={}),t[a]="")}else"dangerouslySetInnerHTML"!==s&&"children"!==s&&"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&"autoFocus"!==s&&(p.hasOwnProperty(s)?u||(u=[]):(u=u||[]).push(s,null))}for(s in r){var i=r[s];if(o=null!=l?l[s]:void 0,r.hasOwnProperty(s)&&i!==o&&(null!=i||null!=o)){if("style"===s){if(o){for(a in o)!o.hasOwnProperty(a)||i&&i.hasOwnProperty(a)||(t||(t={}),t[a]="");for(a in i)i.hasOwnProperty(a)&&o[a]!==i[a]&&(t||(t={}),t[a]=i[a])}else t||(u||(u=[]),u.push(s,t)),t=i}else"dangerouslySetInnerHTML"===s?(i=i?i.__html:void 0,o=o?o.__html:void 0,null!=i&&o!==i&&(u=u||[]).push(s,i)):"children"===s?"string"!=typeof i&&"number"!=typeof i||(u=u||[]).push(s,""+i):"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&(p.hasOwnProperty(s)?(null!=i&&"onScroll"===s&&rt("scroll",e),u||o===i||(u=[])):(u=u||[]).push(s,i))}}t&&(u=u||[]).push("style",t);var s=u;(n.updateQueue=s)&&(n.flags|=4)}},o=function(e,n,t,r){t!==r&&(n.flags|=4)};var uz=!1,uT=!1,uL="function"==typeof WeakSet?WeakSet:Set,uR=null;function uM(e,n){var t=e.ref;if(null!==t){if("function"==typeof t)try{t(null)}catch(t){oA(e,n,t)}else t.current=null}}function uF(e,n,t){try{t()}catch(t){oA(e,n,t)}}var uO=!1;function uD(e,n,t){var r=n.updateQueue;if(null!==(r=null!==r?r.lastEffect:null)){var l=r=r.next;do{if((l.tag&e)===e){var a=l.destroy;l.destroy=void 0,void 0!==a&&uF(n,t,a)}l=l.next}while(l!==r)}}function uI(e,n){if(null!==(n=null!==(n=n.updateQueue)?n.lastEffect:null)){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function uU(e){var n=e.ref;if(null!==n){var t=e.stateNode;e.tag,e=t,"function"==typeof n?n(e):n.current=e}}function uV(e){return 5===e.tag||3===e.tag||4===e.tag}function uA(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||uV(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(2&e.flags||null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}var u$=null,uj=!1;function uB(e,n,t){for(t=t.child;null!==t;)uH(e,n,t),t=t.sibling}function uH(e,n,t){if(e5&&"function"==typeof e5.onCommitFiberUnmount)try{e5.onCommitFiberUnmount(e6,t)}catch(e){}switch(t.tag){case 5:uT||uM(t,n);case 6:var r=u$,l=uj;u$=null,uB(e,n,t),u$=r,uj=l,null!==u$&&(uj?(e=u$,t=t.stateNode,8===e.nodeType?e.parentNode.removeChild(t):e.removeChild(t)):u$.removeChild(t.stateNode));break;case 18:null!==u$&&(uj?(e=u$,t=t.stateNode,8===e.nodeType?rC(e.parentNode,t):1===e.nodeType&&rC(e,t),nM(e)):rC(u$,t.stateNode));break;case 4:r=u$,l=uj,u$=t.stateNode.containerInfo,uj=!0,uB(e,n,t),u$=r,uj=l;break;case 0:case 11:case 14:case 15:if(!uT&&null!==(r=t.updateQueue)&&null!==(r=r.lastEffect)){l=r=r.next;do{var a=l,u=a.destroy;a=a.tag,void 0!==u&&(0!=(2&a)?uF(t,n,u):0!=(4&a)&&uF(t,n,u)),l=l.next}while(l!==r)}uB(e,n,t);break;case 1:if(!uT&&(uM(t,n),"function"==typeof(r=t.stateNode).componentWillUnmount))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(e){oA(t,n,e)}uB(e,n,t);break;case 21:default:uB(e,n,t);break;case 22:1&t.mode?(uT=(r=uT)||null!==t.memoizedState,uB(e,n,t),uT=r):uB(e,n,t)}}function uW(e){var n=e.updateQueue;if(null!==n){e.updateQueue=null;var t=e.stateNode;null===t&&(t=e.stateNode=new uL),n.forEach(function(n){var r=oH.bind(null,e,n);t.has(n)||(t.add(n),n.then(r,r))})}}function uQ(e,n){var t=n.deletions;if(null!==t)for(var r=0;r<t.length;r++){var l=t[r];try{var a=n,u=a;e:for(;null!==u;){switch(u.tag){case 5:u$=u.stateNode,uj=!1;break e;case 3:case 4:u$=u.stateNode.containerInfo,uj=!0;break e}u=u.return}if(null===u$)throw Error(f(160));uH(e,a,l),u$=null,uj=!1;var o=l.alternate;null!==o&&(o.return=null),l.return=null}catch(e){oA(l,n,e)}}if(12854&n.subtreeFlags)for(n=n.child;null!==n;)uq(n,e),n=n.sibling}function uq(e,n){var t=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(uQ(n,e),uK(e),4&r){try{uD(3,e,e.return),uI(3,e)}catch(n){oA(e,e.return,n)}try{uD(5,e,e.return)}catch(n){oA(e,e.return,n)}}break;case 1:uQ(n,e),uK(e),512&r&&null!==t&&uM(t,t.return);break;case 5:if(uQ(n,e),uK(e),512&r&&null!==t&&uM(t,t.return),32&e.flags){var l=e.stateNode;try{eh(l,"")}catch(n){oA(e,e.return,n)}}if(4&r&&null!=(l=e.stateNode)){var a=e.memoizedProps,u=null!==t?t.memoizedProps:a,o=e.type,i=e.updateQueue;if(e.updateQueue=null,null!==i)try{"input"===o&&"radio"===a.type&&null!=a.name&&ee(l,a),eS(o,u);var s=eS(o,a);for(u=0;u<i.length;u+=2){var c=i[u],d=i[u+1];"style"===c?eb(l,d):"dangerouslySetInnerHTML"===c?em(l,d):"children"===c?eh(l,d):C(l,c,d,s)}switch(o){case"input":en(l,a);break;case"textarea":ei(l,a);break;case"select":var p=l._wrapperState.wasMultiple;l._wrapperState.wasMultiple=!!a.multiple;var m=a.value;null!=m?ea(l,!!a.multiple,m,!1):!!a.multiple!==p&&(null!=a.defaultValue?ea(l,!!a.multiple,a.defaultValue,!0):ea(l,!!a.multiple,a.multiple?[]:"",!1))}l[rT]=a}catch(n){oA(e,e.return,n)}}break;case 6:if(uQ(n,e),uK(e),4&r){if(null===e.stateNode)throw Error(f(162));l=e.stateNode,a=e.memoizedProps;try{l.nodeValue=a}catch(n){oA(e,e.return,n)}}break;case 3:if(uQ(n,e),uK(e),4&r&&null!==t&&t.memoizedState.isDehydrated)try{nM(n.containerInfo)}catch(n){oA(e,e.return,n)}break;case 4:default:uQ(n,e),uK(e);break;case 13:uQ(n,e),uK(e),8192&(l=e.child).flags&&(a=null!==l.memoizedState,l.stateNode.isHidden=a,a&&(null===l.alternate||null===l.alternate.memoizedState)&&(oa=eJ())),4&r&&uW(e);break;case 22:if(c=null!==t&&null!==t.memoizedState,1&e.mode?(uT=(s=uT)||c,uQ(n,e),uT=s):uQ(n,e),uK(e),8192&r){if(s=null!==e.memoizedState,(e.stateNode.isHidden=s)&&!c&&0!=(1&e.mode))for(uR=e,c=e.child;null!==c;){for(d=uR=c;null!==uR;){switch(m=(p=uR).child,p.tag){case 0:case 11:case 14:case 15:uD(4,p,p.return);break;case 1:uM(p,p.return);var h=p.stateNode;if("function"==typeof h.componentWillUnmount){r=p,t=p.return;try{n=r,h.props=n.memoizedProps,h.state=n.memoizedState,h.componentWillUnmount()}catch(e){oA(r,t,e)}}break;case 5:uM(p,p.return);break;case 22:if(null!==p.memoizedState){uX(d);continue}}null!==m?(m.return=p,uR=m):uX(d)}c=c.sibling}e:for(c=null,d=e;;){if(5===d.tag){if(null===c){c=d;try{l=d.stateNode,s?(a=l.style,"function"==typeof a.setProperty?a.setProperty("display","none","important"):a.display="none"):(o=d.stateNode,u=null!=(i=d.memoizedProps.style)&&i.hasOwnProperty("display")?i.display:null,o.style.display=ey("display",u))}catch(n){oA(e,e.return,n)}}}else if(6===d.tag){if(null===c)try{d.stateNode.nodeValue=s?"":d.memoizedProps}catch(n){oA(e,e.return,n)}}else if((22!==d.tag&&23!==d.tag||null===d.memoizedState||d===e)&&null!==d.child){d.child.return=d,d=d.child;continue}if(d===e)break e;for(;null===d.sibling;){if(null===d.return||d.return===e)break e;c===d&&(c=null),d=d.return}c===d&&(c=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:uQ(n,e),uK(e),4&r&&uW(e);case 21:}}function uK(e){var n=e.flags;if(2&n){try{e:{for(var t=e.return;null!==t;){if(uV(t)){var r=t;break e}t=t.return}throw Error(f(160))}switch(r.tag){case 5:var l=r.stateNode;32&r.flags&&(eh(l,""),r.flags&=-33);var a=uA(e);!function e(n,t,r){var l=n.tag;if(5===l||6===l)n=n.stateNode,t?r.insertBefore(n,t):r.appendChild(n);else if(4!==l&&null!==(n=n.child))for(e(n,t,r),n=n.sibling;null!==n;)e(n,t,r),n=n.sibling}(e,a,l);break;case 3:case 4:var u=r.stateNode.containerInfo,o=uA(e);!function e(n,t,r){var l=n.tag;if(5===l||6===l)n=n.stateNode,t?8===r.nodeType?r.parentNode.insertBefore(n,t):r.insertBefore(n,t):(8===r.nodeType?(t=r.parentNode).insertBefore(n,r):(t=r).appendChild(n),null!=(r=r._reactRootContainer)||null!==t.onclick||(t.onclick=rg));else if(4!==l&&null!==(n=n.child))for(e(n,t,r),n=n.sibling;null!==n;)e(n,t,r),n=n.sibling}(e,o,u);break;default:throw Error(f(161))}}catch(n){oA(e,e.return,n)}e.flags&=-3}4096&n&&(e.flags&=-4097)}function uY(e){for(;null!==uR;){var n=uR;if(0!=(8772&n.flags)){var t=n.alternate;try{if(0!=(8772&n.flags))switch(n.tag){case 0:case 11:case 15:uT||uI(5,n);break;case 1:var r=n.stateNode;if(4&n.flags&&!uT){if(null===t)r.componentDidMount();else{var l=n.elementType===n.type?t.memoizedProps:lS(n.type,t.memoizedProps);r.componentDidUpdate(l,t.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}}var a=n.updateQueue;null!==a&&lH(n,a,r);break;case 3:var u=n.updateQueue;if(null!==u){if(t=null,null!==n.child)switch(n.child.tag){case 5:case 1:t=n.child.stateNode}lH(n,u,t)}break;case 5:var o=n.stateNode;if(null===t&&4&n.flags){t=o;var i=n.memoizedProps;switch(n.type){case"button":case"input":case"select":case"textarea":i.autoFocus&&t.focus();break;case"img":i.src&&(t.src=i.src)}}break;case 6:case 4:case 12:case 19:case 17:case 21:case 22:case 23:case 25:break;case 13:if(null===n.memoizedState){var s=n.alternate;if(null!==s){var c=s.memoizedState;if(null!==c){var d=c.dehydrated;null!==d&&nM(d)}}}break;default:throw Error(f(163))}uT||512&n.flags&&uU(n)}catch(e){oA(n,n.return,e)}}if(n===e){uR=null;break}if(null!==(t=n.sibling)){t.return=n.return,uR=t;break}uR=n.return}}function uX(e){for(;null!==uR;){var n=uR;if(n===e){uR=null;break}var t=n.sibling;if(null!==t){t.return=n.return,uR=t;break}uR=n.return}}function uG(e){for(;null!==uR;){var n=uR;try{switch(n.tag){case 0:case 11:case 15:var t=n.return;try{uI(4,n)}catch(e){oA(n,t,e)}break;case 1:var r=n.stateNode;if("function"==typeof r.componentDidMount){var l=n.return;try{r.componentDidMount()}catch(e){oA(n,l,e)}}var a=n.return;try{uU(n)}catch(e){oA(n,a,e)}break;case 5:var u=n.return;try{uU(n)}catch(e){oA(n,u,e)}}}catch(e){oA(n,n.return,e)}if(n===e){uR=null;break}var o=n.sibling;if(null!==o){o.return=n.return,uR=o;break}uR=n.return}}var uZ=Math.ceil,uJ=_.ReactCurrentDispatcher,u0=_.ReactCurrentOwner,u1=_.ReactCurrentBatchConfig,u2=0,u3=null,u4=null,u8=0,u6=0,u5=r$(0),u9=0,u7=null,oe=0,on=0,ot=0,or=null,ol=null,oa=0,ou=1/0,oo=null,oi=!1,os=null,oc=null,of=!1,od=null,op=0,om=0,oh=null,og=-1,ov=0;function oy(){return 0!=(6&u2)?eJ():-1!==og?og:og=eJ()}function ob(e){return 0==(1&e.mode)?1:0!=(2&u2)&&0!==u8?u8&-u8:null!==lw.transition?(0===ov&&(ov=nu()),ov):0!==(e=nc)?e:e=void 0===(e=window.event)?16:n$(e.type)}function ok(e,n,t,r){if(50<om)throw om=0,oh=null,Error(f(185));ni(e,t,r),(0==(2&u2)||e!==u3)&&(e===u3&&(0==(2&u2)&&(on|=t),4===u9&&oC(e,u8)),ow(e,r),1===t&&0===u2&&0==(1&n.mode)&&(ou=eJ()+500,r2&&r4()))}function ow(e,n){var t,r,l,a=e.callbackNode;!function(e,n){for(var t=e.suspendedLanes,r=e.pingedLanes,l=e.expirationTimes,a=e.pendingLanes;0<a;){var u=31-e9(a),o=1<<u,i=l[u];-1===i?(0==(o&t)||0!=(o&r))&&(l[u]=function(e,n){switch(e){case 1:case 2:case 4:return n+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return n+5e3;default:return -1}}(o,n)):i<=n&&(e.expiredLanes|=o),a&=~o}}(e,n);var u=nl(e,e===u3?u8:0);if(0===u)null!==a&&eX(a),e.callbackNode=null,e.callbackPriority=0;else if(n=u&-u,e.callbackPriority!==n){if(null!=a&&eX(a),1===n){;0===e.tag&&(r2=!0),t=o_.bind(null,e),null===r1?r1=[t]:r1.push(t),rx(function(){0==(6&u2)&&r4()}),a=null}else{switch(nf(u)){case 1:a=e1;break;case 4:a=e2;break;case 16:default:a=e3;break;case 536870912:a=e8}r=a,l=oS.bind(null,e),a=eY(r,l)}e.callbackPriority=n,e.callbackNode=a}}function oS(e,n){if(og=-1,ov=0,0!=(6&u2))throw Error(f(327));var t=e.callbackNode;if(oU()&&e.callbackNode!==t)return null;var r=nl(e,e===u3?u8:0);if(0===r)return null;if(0!=(30&r)||0!=(r&e.expiredLanes)||n)n=oF(e,r);else{n=r;var l=u2;u2|=2;var a=oR();for((u3!==e||u8!==n)&&(oo=null,ou=eJ()+500,oT(e,n));;)try{!function(){for(;null!==u4&&!eG();)oO(u4)}();break}catch(n){oL(e,n)}lP(),uJ.current=a,u2=l,null!==u4?n=0:(u3=null,u8=0,n=u9)}if(0!==n){if(2===n&&0!==(l=na(e))&&(r=l,n=ox(e,l)),1===n)throw t=u7,oT(e,0),oC(e,r),ow(e,eJ()),t;if(6===n)oC(e,r);else{if(l=e.current.alternate,0==(30&r)&&!function(e){for(var n=e;;){if(16384&n.flags){var t=n.updateQueue;if(null!==t&&null!==(t=t.stores))for(var r=0;r<t.length;r++){var l=t[r],a=l.getSnapshot;l=l.value;try{if(!tD(a(),l))return!1}catch(e){return!1}}}if(t=n.child,16384&n.subtreeFlags&&null!==t)t.return=n,n=t;else{if(n===e)break;for(;null===n.sibling;){if(null===n.return||n.return===e)return!0;n=n.return}n.sibling.return=n.return,n=n.sibling}}return!0}(l)&&(2===(n=oF(e,r))&&0!==(a=na(e))&&(r=a,n=ox(e,a)),1===n))throw t=u7,oT(e,0),oC(e,r),ow(e,eJ()),t;switch(e.finishedWork=l,e.finishedLanes=r,n){case 0:case 1:throw Error(f(345));case 2:case 5:oI(e,ol,oo);break;case 3:if(oC(e,r),(130023424&r)===r&&10<(n=oa+500-eJ())){if(0!==nl(e,0))break;if(((l=e.suspendedLanes)&r)!==r){oy(),e.pingedLanes|=e.suspendedLanes&l;break}e.timeoutHandle=rk(oI.bind(null,e,ol,oo),n);break}oI(e,ol,oo);break;case 4:if(oC(e,r),(4194240&r)===r)break;for(l=-1,n=e.eventTimes;0<r;){var u=31-e9(r);a=1<<u,(u=n[u])>l&&(l=u),r&=~a}if(r=l,10<(r=(120>(r=eJ()-r)?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*uZ(r/1960))-r)){e.timeoutHandle=rk(oI.bind(null,e,ol,oo),r);break}oI(e,ol,oo);break;default:throw Error(f(329))}}}return ow(e,eJ()),e.callbackNode===t?oS.bind(null,e):null}function ox(e,n){var t=or;return e.current.memoizedState.isDehydrated&&(oT(e,n).flags|=256),2!==(e=oF(e,n))&&(n=ol,ol=t,null!==n&&oE(n)),e}function oE(e){null===ol?ol=e:ol.push.apply(ol,e)}function oC(e,n){for(n&=~ot,n&=~on,e.suspendedLanes|=n,e.pingedLanes&=~n,e=e.expirationTimes;0<n;){var t=31-e9(n),r=1<<t;e[t]=-1,n&=~r}}function o_(e){if(0!=(6&u2))throw Error(f(327));oU();var n=nl(e,0);if(0==(1&n))return ow(e,eJ()),null;var t=oF(e,n);if(0!==e.tag&&2===t){var r=na(e);0!==r&&(n=r,t=ox(e,r))}if(1===t)throw t=u7,oT(e,0),oC(e,n),ow(e,eJ()),t;if(6===t)throw Error(f(345));return e.finishedWork=e.current.alternate,e.finishedLanes=n,oI(e,ol,oo),ow(e,eJ()),null}function oP(e,n){var t=u2;u2|=1;try{return e(n)}finally{0===(u2=t)&&(ou=eJ()+500,r2&&r4())}}function oN(e){null!==od&&0===od.tag&&0==(6&u2)&&oU();var n=u2;u2|=1;var t=u1.transition,r=nc;try{if(u1.transition=null,nc=1,e)return e()}finally{nc=r,u1.transition=t,0==(6&(u2=n))&&r4()}}function oz(){u6=u5.current,rj(u5)}function oT(e,n){e.finishedWork=null,e.finishedLanes=0;var t=e.timeoutHandle;if(-1!==t&&(e.timeoutHandle=-1,rw(t)),null!==u4)for(t=u4.return;null!==t;){var r=t;switch(lo(r),r.tag){case 1:null!=(r=r.type.childContextTypes)&&rX();break;case 3:ae(),rj(rQ),rj(rW),au();break;case 5:at(r);break;case 4:ae();break;case 13:case 19:rj(ar);break;case 10:lN(r.type._context);break;case 22:case 23:oz()}t=t.return}if(u3=e,u4=e=oK(e.current,null),u8=u6=n,u9=0,u7=null,ot=on=oe=0,ol=or=null,null!==lR){for(n=0;n<lR.length;n++)if(null!==(r=(t=lR[n]).interleaved)){t.interleaved=null;var l=r.next,a=t.pending;if(null!==a){var u=a.next;a.next=l,r.next=u}t.pending=r}lR=null}return e}function oL(e,n){for(;;){var t=u4;try{if(lP(),ao.current=a1,ap){for(var r=ac.memoizedState;null!==r;){var l=r.queue;null!==l&&(l.pending=null),r=r.next}ap=!1}if(as=0,ad=af=ac=null,am=!1,ah=0,u0.current=null,null===t||null===t.return){u9=1,u7=n,u4=null;break}e:{var a=e,u=t.return,o=t,i=n;if(n=u8,o.flags|=32768,null!==i&&"object"==typeof i&&"function"==typeof i.then){var s=i,c=o,d=c.tag;if(0==(1&c.mode)&&(0===d||11===d||15===d)){var p=c.alternate;p?(c.updateQueue=p.updateQueue,c.memoizedState=p.memoizedState,c.lanes=p.lanes):(c.updateQueue=null,c.memoizedState=null)}var m=ut(u);if(null!==m){m.flags&=-257,ur(m,u,o,a,n),1&m.mode&&un(a,s,n),n=m,i=s;var h=n.updateQueue;if(null===h){var g=new Set;g.add(i),n.updateQueue=g}else h.add(i);break e}if(0==(1&n)){un(a,s,n),oM();break e}i=Error(f(426))}else if(lc&&1&o.mode){var v=ut(u);if(null!==v){0==(65536&v.flags)&&(v.flags|=256),ur(v,u,o,a,n),lk(a8(i,o));break e}}a=i=a8(i,o),4!==u9&&(u9=2),null===or?or=[a]:or.push(a),a=u;do{switch(a.tag){case 3:a.flags|=65536,n&=-n,a.lanes|=n;var y=a7(a,i,n);lj(a,y);break e;case 1:o=i;var b=a.type,k=a.stateNode;if(0==(128&a.flags)&&("function"==typeof b.getDerivedStateFromError||null!==k&&"function"==typeof k.componentDidCatch&&(null===oc||!oc.has(k)))){a.flags|=65536,n&=-n,a.lanes|=n;var w=ue(a,o,n);lj(a,w);break e}}a=a.return}while(null!==a)}oD(t)}catch(e){n=e,u4===t&&null!==t&&(u4=t=t.return);continue}break}}function oR(){var e=uJ.current;return uJ.current=a1,null===e?a1:e}function oM(){(0===u9||3===u9||2===u9)&&(u9=4),null===u3||0==(268435455&oe)&&0==(268435455&on)||oC(u3,u8)}function oF(e,n){var t=u2;u2|=2;var r=oR();for((u3!==e||u8!==n)&&(oo=null,oT(e,n));;)try{!function(){for(;null!==u4;)oO(u4)}();break}catch(n){oL(e,n)}if(lP(),u2=t,uJ.current=r,null!==u4)throw Error(f(261));return u3=null,u8=0,u9}function oO(e){var n=i(e.alternate,e,u6);e.memoizedProps=e.pendingProps,null===n?oD(e):u4=n,u0.current=null}function oD(e){var n=e;do{var t=n.alternate;if(e=n.return,0==(32768&n.flags)){if(null!==(t=function(e,n,t){var r=n.pendingProps;switch(lo(n),n.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return uN(n),null;case 1:case 17:return rY(n.type)&&rX(),uN(n),null;case 3:return r=n.stateNode,ae(),rj(rQ),rj(rW),au(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(null===e||null===e.child)&&(lv(n)?n.flags|=4:null===e||e.memoizedState.isDehydrated&&0==(256&n.flags)||(n.flags|=1024,null!==lf&&(oE(lf),lf=null))),a(e,n),uN(n),null;case 5:at(n);var i=l9(l5.current);if(t=n.type,null!==e&&null!=n.stateNode)u(e,n,t,r,i),e.ref!==n.ref&&(n.flags|=512,n.flags|=2097152);else{if(!r){if(null===n.stateNode)throw Error(f(166));return uN(n),null}if(e=l9(l8.current),lv(n)){r=n.stateNode,t=n.type;var s=n.memoizedProps;switch(r[rz]=n,r[rT]=s,e=0!=(1&n.mode),t){case"dialog":rt("cancel",r),rt("close",r);break;case"iframe":case"object":case"embed":rt("load",r);break;case"video":case"audio":for(i=0;i<t9.length;i++)rt(t9[i],r);break;case"source":rt("error",r);break;case"img":case"image":case"link":rt("error",r),rt("load",r);break;case"details":rt("toggle",r);break;case"input":J(r,s),rt("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!s.multiple},rt("invalid",r);break;case"textarea":eo(r,s),rt("invalid",r)}for(var c in ew(t,s),i=null,s)if(s.hasOwnProperty(c)){var d=s[c];"children"===c?"string"==typeof d?r.textContent!==d&&(!0!==s.suppressHydrationWarning&&rh(r.textContent,d,e),i=["children",d]):"number"==typeof d&&r.textContent!==""+d&&(!0!==s.suppressHydrationWarning&&rh(r.textContent,d,e),i=["children",""+d]):p.hasOwnProperty(c)&&null!=d&&"onScroll"===c&&rt("scroll",r)}switch(t){case"input":Y(r),et(r,s,!0);break;case"textarea":Y(r),es(r);break;case"select":case"option":break;default:"function"==typeof s.onClick&&(r.onclick=rg)}r=i,n.updateQueue=r,null!==r&&(n.flags|=4)}else{c=9===i.nodeType?i:i.ownerDocument,"http://www.w3.org/1999/xhtml"===e&&(e=ec(t)),"http://www.w3.org/1999/xhtml"===e?"script"===t?((e=c.createElement("div")).innerHTML="<script></script>",e=e.removeChild(e.firstChild)):"string"==typeof r.is?e=c.createElement(t,{is:r.is}):(e=c.createElement(t),"select"===t&&(c=e,r.multiple?c.multiple=!0:r.size&&(c.size=r.size))):e=c.createElementNS(e,t),e[rz]=n,e[rT]=r,l(e,n,!1,!1),n.stateNode=e;e:{switch(c=eS(t,r),t){case"dialog":rt("cancel",e),rt("close",e),i=r;break;case"iframe":case"object":case"embed":rt("load",e),i=r;break;case"video":case"audio":for(i=0;i<t9.length;i++)rt(t9[i],e);i=r;break;case"source":rt("error",e),i=r;break;case"img":case"image":case"link":rt("error",e),rt("load",e),i=r;break;case"details":rt("toggle",e),i=r;break;case"input":J(e,r),i=Z(e,r),rt("invalid",e);break;case"option":default:i=r;break;case"select":e._wrapperState={wasMultiple:!!r.multiple},i=B({},r,{value:void 0}),rt("invalid",e);break;case"textarea":eo(e,r),i=eu(e,r),rt("invalid",e)}for(s in ew(t,i),d=i)if(d.hasOwnProperty(s)){var m=d[s];"style"===s?eb(e,m):"dangerouslySetInnerHTML"===s?null!=(m=m?m.__html:void 0)&&em(e,m):"children"===s?"string"==typeof m?("textarea"!==t||""!==m)&&eh(e,m):"number"==typeof m&&eh(e,""+m):"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&"autoFocus"!==s&&(p.hasOwnProperty(s)?null!=m&&"onScroll"===s&&rt("scroll",e):null!=m&&C(e,s,m,c))}switch(t){case"input":Y(e),et(e,r,!1);break;case"textarea":Y(e),es(e);break;case"option":null!=r.value&&e.setAttribute("value",""+q(r.value));break;case"select":e.multiple=!!r.multiple,null!=(s=r.value)?ea(e,!!r.multiple,s,!1):null!=r.defaultValue&&ea(e,!!r.multiple,r.defaultValue,!0);break;default:"function"==typeof i.onClick&&(e.onclick=rg)}switch(t){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(n.flags|=4)}null!==n.ref&&(n.flags|=512,n.flags|=2097152)}return uN(n),null;case 6:if(e&&null!=n.stateNode)o(e,n,e.memoizedProps,r);else{if("string"!=typeof r&&null===n.stateNode)throw Error(f(166));if(t=l9(l5.current),l9(l8.current),lv(n)){if(r=n.stateNode,t=n.memoizedProps,r[rz]=n,(s=r.nodeValue!==t)&&null!==(e=li))switch(e.tag){case 3:rh(r.nodeValue,t,0!=(1&e.mode));break;case 5:!0!==e.memoizedProps.suppressHydrationWarning&&rh(r.nodeValue,t,0!=(1&e.mode))}s&&(n.flags|=4)}else(r=(9===t.nodeType?t:t.ownerDocument).createTextNode(r))[rz]=n,n.stateNode=r}return uN(n),null;case 13:if(rj(ar),r=n.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(lc&&null!==ls&&0!=(1&n.mode)&&0==(128&n.flags))ly(),lb(),n.flags|=98560,s=!1;else if(s=lv(n),null!==r&&null!==r.dehydrated){if(null===e){if(!s)throw Error(f(318));if(!(s=null!==(s=n.memoizedState)?s.dehydrated:null))throw Error(f(317));s[rz]=n}else lb(),0==(128&n.flags)&&(n.memoizedState=null),n.flags|=4;uN(n),s=!1}else null!==lf&&(oE(lf),lf=null),s=!0;if(!s)return 65536&n.flags?n:null}if(0!=(128&n.flags))return n.lanes=t,n;return(r=null!==r)!=(null!==e&&null!==e.memoizedState)&&r&&(n.child.flags|=8192,0!=(1&n.mode)&&(null===e||0!=(1&ar.current)?0===u9&&(u9=3):oM())),null!==n.updateQueue&&(n.flags|=4),uN(n),null;case 4:return ae(),a(e,n),null===e&&ra(n.stateNode.containerInfo),uN(n),null;case 10:return lN(n.type._context),uN(n),null;case 19:if(rj(ar),null===(s=n.memoizedState))return uN(n),null;if(r=0!=(128&n.flags),null===(c=s.rendering)){if(r)uP(s,!1);else{if(0!==u9||null!==e&&0!=(128&e.flags))for(e=n.child;null!==e;){if(null!==(c=al(e))){for(n.flags|=128,uP(s,!1),null!==(r=c.updateQueue)&&(n.updateQueue=r,n.flags|=4),n.subtreeFlags=0,r=t,t=n.child;null!==t;)s=t,e=r,s.flags&=14680066,null===(c=s.alternate)?(s.childLanes=0,s.lanes=e,s.child=null,s.subtreeFlags=0,s.memoizedProps=null,s.memoizedState=null,s.updateQueue=null,s.dependencies=null,s.stateNode=null):(s.childLanes=c.childLanes,s.lanes=c.lanes,s.child=c.child,s.subtreeFlags=0,s.deletions=null,s.memoizedProps=c.memoizedProps,s.memoizedState=c.memoizedState,s.updateQueue=c.updateQueue,s.type=c.type,e=c.dependencies,s.dependencies=null===e?null:{lanes:e.lanes,firstContext:e.firstContext}),t=t.sibling;return rB(ar,1&ar.current|2),n.child}e=e.sibling}null!==s.tail&&eJ()>ou&&(n.flags|=128,r=!0,uP(s,!1),n.lanes=4194304)}}else{if(!r){if(null!==(e=al(c))){if(n.flags|=128,r=!0,null!==(t=e.updateQueue)&&(n.updateQueue=t,n.flags|=4),uP(s,!0),null===s.tail&&"hidden"===s.tailMode&&!c.alternate&&!lc)return uN(n),null}else 2*eJ()-s.renderingStartTime>ou&&1073741824!==t&&(n.flags|=128,r=!0,uP(s,!1),n.lanes=4194304)}s.isBackwards?(c.sibling=n.child,n.child=c):(null!==(t=s.last)?t.sibling=c:n.child=c,s.last=c)}if(null!==s.tail)return n=s.tail,s.rendering=n,s.tail=n.sibling,s.renderingStartTime=eJ(),n.sibling=null,t=ar.current,rB(ar,r?1&t|2:1&t),n;return uN(n),null;case 22:case 23:return oz(),r=null!==n.memoizedState,null!==e&&null!==e.memoizedState!==r&&(n.flags|=8192),r&&0!=(1&n.mode)?0!=(1073741824&u6)&&(uN(n),6&n.subtreeFlags&&(n.flags|=8192)):uN(n),null;case 24:case 25:return null}throw Error(f(156,n.tag))}(t,n,u6))){u4=t;return}}else{if(null!==(t=function(e,n){switch(lo(n),n.tag){case 1:return rY(n.type)&&rX(),65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 3:return ae(),rj(rQ),rj(rW),au(),0!=(65536&(e=n.flags))&&0==(128&e)?(n.flags=-65537&e|128,n):null;case 5:return at(n),null;case 13:if(rj(ar),null!==(e=n.memoizedState)&&null!==e.dehydrated){if(null===n.alternate)throw Error(f(340));lb()}return 65536&(e=n.flags)?(n.flags=-65537&e|128,n):null;case 19:return rj(ar),null;case 4:return ae(),null;case 10:return lN(n.type._context),null;case 22:case 23:return oz(),null;default:return null}}(t,n))){t.flags&=32767,u4=t;return}if(null!==e)e.flags|=32768,e.subtreeFlags=0,e.deletions=null;else{u9=6,u4=null;return}}if(null!==(n=n.sibling)){u4=n;return}u4=n=e}while(null!==n);0===u9&&(u9=5)}function oI(e,n,t){var r=nc,l=u1.transition;try{u1.transition=null,nc=1,function(e,n,t,r){do oU();while(null!==od);if(0!=(6&u2))throw Error(f(327));t=e.finishedWork;var l=e.finishedLanes;if(null!==t){if(e.finishedWork=null,e.finishedLanes=0,t===e.current)throw Error(f(177));e.callbackNode=null,e.callbackPriority=0;var a=t.lanes|t.childLanes;if(function(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0<t;){var l=31-e9(t),a=1<<l;n[l]=0,r[l]=-1,e[l]=-1,t&=~a}}(e,a),e===u3&&(u4=u3=null,u8=0),0==(2064&t.subtreeFlags)&&0==(2064&t.flags)||of||(of=!0,u=e3,o=function(){return oU(),null},eY(u,o)),a=0!=(15990&t.flags),0!=(15990&t.subtreeFlags)||a){a=u1.transition,u1.transition=null;var u,o,i,s,c,d=nc;nc=1;var p=u2;u2|=4,u0.current=null,function(e,n){if(rv=nO,t$(e=tA())){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:{var r=(t=(t=e.ownerDocument)&&t.defaultView||window).getSelection&&t.getSelection();if(r&&0!==r.rangeCount){t=r.anchorNode;var l,a=r.anchorOffset,u=r.focusNode;r=r.focusOffset;try{t.nodeType,u.nodeType}catch(e){t=null;break e}var o=0,i=-1,s=-1,c=0,d=0,p=e,m=null;n:for(;;){for(;p!==t||0!==a&&3!==p.nodeType||(i=o+a),p!==u||0!==r&&3!==p.nodeType||(s=o+r),3===p.nodeType&&(o+=p.nodeValue.length),null!==(l=p.firstChild);)m=p,p=l;for(;;){if(p===e)break n;if(m===t&&++c===a&&(i=o),m===u&&++d===r&&(s=o),null!==(l=p.nextSibling))break;m=(p=m).parentNode}p=l}t=-1===i||-1===s?null:{start:i,end:s}}else t=null}t=t||{start:0,end:0}}else t=null;for(ry={focusedElem:e,selectionRange:t},nO=!1,uR=n;null!==uR;)if(e=(n=uR).child,0!=(1028&n.subtreeFlags)&&null!==e)e.return=n,uR=e;else for(;null!==uR;){n=uR;try{var h=n.alternate;if(0!=(1024&n.flags))switch(n.tag){case 0:case 11:case 15:case 5:case 6:case 4:case 17:break;case 1:if(null!==h){var g=h.memoizedProps,v=h.memoizedState,y=n.stateNode,b=y.getSnapshotBeforeUpdate(n.elementType===n.type?g:lS(n.type,g),v);y.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var k=n.stateNode.containerInfo;1===k.nodeType?k.textContent="":9===k.nodeType&&k.documentElement&&k.removeChild(k.documentElement);break;default:throw Error(f(163))}}catch(e){oA(n,n.return,e)}if(null!==(e=n.sibling)){e.return=n.return,uR=e;break}uR=n.return}h=uO,uO=!1}(e,t),uq(t,e),function(e){var n=tA(),t=e.focusedElem,r=e.selectionRange;if(n!==t&&t&&t.ownerDocument&&function e(n,t){return!!n&&!!t&&(n===t||(!n||3!==n.nodeType)&&(t&&3===t.nodeType?e(n,t.parentNode):"contains"in n?n.contains(t):!!n.compareDocumentPosition&&!!(16&n.compareDocumentPosition(t))))}(t.ownerDocument.documentElement,t)){if(null!==r&&t$(t)){if(n=r.start,void 0===(e=r.end)&&(e=n),"selectionStart"in t)t.selectionStart=n,t.selectionEnd=Math.min(e,t.value.length);else if((e=(n=t.ownerDocument||document)&&n.defaultView||window).getSelection){e=e.getSelection();var l=t.textContent.length,a=Math.min(r.start,l);r=void 0===r.end?a:Math.min(r.end,l),!e.extend&&a>r&&(l=r,r=a,a=l),l=tV(t,a);var u=tV(t,r);l&&u&&(1!==e.rangeCount||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==u.node||e.focusOffset!==u.offset)&&((n=n.createRange()).setStart(l.node,l.offset),e.removeAllRanges(),a>r?(e.addRange(n),e.extend(u.node,u.offset)):(n.setEnd(u.node,u.offset),e.addRange(n)))}}for(n=[],e=t;e=e.parentNode;)1===e.nodeType&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"==typeof t.focus&&t.focus(),t=0;t<n.length;t++)(e=n[t]).element.scrollLeft=e.left,e.element.scrollTop=e.top}}(ry),nO=!!rv,ry=rv=null,e.current=t,i=t,s=e,c=l,uR=i,function e(n,t,r){for(var l=0!=(1&n.mode);null!==uR;){var a=uR,u=a.child;if(22===a.tag&&l){var o=null!==a.memoizedState||uz;if(!o){var i=a.alternate,s=null!==i&&null!==i.memoizedState||uT;i=uz;var c=uT;if(uz=o,(uT=s)&&!c)for(uR=a;null!==uR;)s=(o=uR).child,22===o.tag&&null!==o.memoizedState?uG(a):null!==s?(s.return=o,uR=s):uG(a);for(;null!==u;)uR=u,e(u,t,r),u=u.sibling;uR=a,uz=i,uT=c}uY(n,t,r)}else 0!=(8772&a.subtreeFlags)&&null!==u?(u.return=a,uR=u):uY(n,t,r)}}(i,s,c),eZ(),u2=p,nc=d,u1.transition=a}else e.current=t;if(of&&(of=!1,od=e,op=l),0===(a=e.pendingLanes)&&(oc=null),function(e){if(e5&&"function"==typeof e5.onCommitFiberRoot)try{e5.onCommitFiberRoot(e6,e,void 0,128==(128&e.current.flags))}catch(e){}}(t.stateNode,r),ow(e,eJ()),null!==n)for(r=e.onRecoverableError,t=0;t<n.length;t++)r((l=n[t]).value,{componentStack:l.stack,digest:l.digest});if(oi)throw oi=!1,e=os,os=null,e;0!=(1&op)&&0!==e.tag&&oU(),0!=(1&(a=e.pendingLanes))?e===oh?om++:(om=0,oh=e):om=0,r4()}}(e,n,t,r)}finally{u1.transition=l,nc=r}return null}function oU(){if(null!==od){var e=nf(op),n=u1.transition,t=nc;try{if(u1.transition=null,nc=16>e?16:e,null===od)var r=!1;else{if(e=od,od=null,op=0,0!=(6&u2))throw Error(f(331));var l=u2;for(u2|=4,uR=e.current;null!==uR;){var a=uR,u=a.child;if(0!=(16&uR.flags)){var o=a.deletions;if(null!==o){for(var i=0;i<o.length;i++){var s=o[i];for(uR=s;null!==uR;){var c=uR;switch(c.tag){case 0:case 11:case 15:uD(8,c,a)}var d=c.child;if(null!==d)d.return=c,uR=d;else for(;null!==uR;){var p=(c=uR).sibling,m=c.return;if(!function e(n){var t=n.alternate;null!==t&&(n.alternate=null,e(t)),n.child=null,n.deletions=null,n.sibling=null,5===n.tag&&null!==(t=n.stateNode)&&(delete t[rz],delete t[rT],delete t[rR],delete t[rM],delete t[rF]),n.stateNode=null,n.return=null,n.dependencies=null,n.memoizedProps=null,n.memoizedState=null,n.pendingProps=null,n.stateNode=null,n.updateQueue=null}(c),c===s){uR=null;break}if(null!==p){p.return=m,uR=p;break}uR=m}}}var h=a.alternate;if(null!==h){var g=h.child;if(null!==g){h.child=null;do{var v=g.sibling;g.sibling=null,g=v}while(null!==g)}}uR=a}}if(0!=(2064&a.subtreeFlags)&&null!==u)u.return=a,uR=u;else n:for(;null!==uR;){if(a=uR,0!=(2048&a.flags))switch(a.tag){case 0:case 11:case 15:uD(9,a,a.return)}var y=a.sibling;if(null!==y){y.return=a.return,uR=y;break n}uR=a.return}}var b=e.current;for(uR=b;null!==uR;){var k=(u=uR).child;if(0!=(2064&u.subtreeFlags)&&null!==k)k.return=u,uR=k;else n:for(u=b;null!==uR;){if(o=uR,0!=(2048&o.flags))try{switch(o.tag){case 0:case 11:case 15:uI(9,o)}}catch(e){oA(o,o.return,e)}if(o===u){uR=null;break n}var w=o.sibling;if(null!==w){w.return=o.return,uR=w;break n}uR=o.return}}if(u2=l,r4(),e5&&"function"==typeof e5.onPostCommitFiberRoot)try{e5.onPostCommitFiberRoot(e6,e)}catch(e){}r=!0}return r}finally{nc=t,u1.transition=n}}return!1}function oV(e,n,t){n=a8(t,n),n=a7(e,n,1),e=lA(e,n,1),n=oy(),null!==e&&(ni(e,1,n),ow(e,n))}function oA(e,n,t){if(3===e.tag)oV(e,e,t);else for(;null!==n;){if(3===n.tag){oV(n,e,t);break}if(1===n.tag){var r=n.stateNode;if("function"==typeof n.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===oc||!oc.has(r))){e=a8(t,e),e=ue(n,e,1),n=lA(n,e,1),e=oy(),null!==n&&(ni(n,1,e),ow(n,e));break}}n=n.return}}function o$(e,n,t){var r=e.pingCache;null!==r&&r.delete(n),n=oy(),e.pingedLanes|=e.suspendedLanes&t,u3===e&&(u8&t)===t&&(4===u9||3===u9&&(130023424&u8)===u8&&500>eJ()-oa?oT(e,0):ot|=t),ow(e,n)}function oj(e,n){0===n&&(0==(1&e.mode)?n=1:(n=nt,0==(130023424&(nt<<=1))&&(nt=4194304)));var t=oy();null!==(e=lO(e,n))&&(ni(e,n,t),ow(e,t))}function oB(e){var n=e.memoizedState,t=0;null!==n&&(t=n.retryLane),oj(e,t)}function oH(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;null!==l&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(f(314))}null!==r&&r.delete(n),oj(e,t)}function oW(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function oQ(e,n,t,r){return new oW(e,n,t,r)}function oq(e){return!(!(e=e.prototype)||!e.isReactComponent)}function oK(e,n){var t=e.alternate;return null===t?((t=oQ(e.tag,n,e.key,e.mode)).elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=14680064&e.flags,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=null===n?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function oY(e,n,t,r,l,a){var u=2;if(r=e,"function"==typeof e)oq(e)&&(u=1);else if("string"==typeof e)u=5;else e:switch(e){case z:return oX(t.children,l,a,n);case T:u=8,l|=8;break;case L:return(e=oQ(12,t,n,2|l)).elementType=L,e.lanes=a,e;case O:return(e=oQ(13,t,n,l)).elementType=O,e.lanes=a,e;case D:return(e=oQ(19,t,n,l)).elementType=D,e.lanes=a,e;case V:return oG(t,l,a,n);default:if("object"==typeof e&&null!==e)switch(e.$$typeof){case R:u=10;break e;case M:u=9;break e;case F:u=11;break e;case I:u=14;break e;case U:u=16,r=null;break e}throw Error(f(130,null==e?e:typeof e,""))}return(n=oQ(u,t,n,l)).elementType=e,n.type=r,n.lanes=a,n}function oX(e,n,t,r){return(e=oQ(7,e,r,n)).lanes=t,e}function oG(e,n,t,r){return(e=oQ(22,e,r,n)).elementType=V,e.lanes=t,e.stateNode={isHidden:!1},e}function oZ(e,n,t){return(e=oQ(6,e,null,n)).lanes=t,e}function oJ(e,n,t){return(n=oQ(4,null!==e.children?e.children:[],e.key,n)).lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function o0(e,n,t,r,l){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=no(0),this.expirationTimes=no(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=no(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function o1(e,n,t,r,l,a,u,o,i){return e=new o0(e,n,t,o,i),1===n?(n=1,!0===a&&(n|=8)):n=0,a=oQ(3,null,null,n),e.current=a,a.stateNode=e,a.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},lI(a),e}function o2(e){if(!e)return rH;e=e._reactInternals;e:{if(eW(e)!==e||1!==e.tag)throw Error(f(170));var n=e;do{switch(n.tag){case 3:n=n.stateNode.context;break e;case 1:if(rY(n.type)){n=n.stateNode.__reactInternalMemoizedMergedChildContext;break e}}n=n.return}while(null!==n);throw Error(f(171))}if(1===e.tag){var t=e.type;if(rY(t))return rZ(e,t,n)}return n}function o3(e,n,t,r,l,a,u,o,i){return(e=o1(t,r,!0,e,l,a,u,o,i)).context=o2(null),t=e.current,(a=lV(r=oy(),l=ob(t))).callback=null!=n?n:null,lA(t,a,l),e.current.lanes=l,ni(e,l,r),ow(e,r),e}function o4(e,n,t,r){var l=n.current,a=oy(),u=ob(l);return t=o2(t),null===n.context?n.context=t:n.pendingContext=t,(n=lV(a,u)).payload={element:e},null!==(r=void 0===r?null:r)&&(n.callback=r),null!==(e=lA(l,n,u))&&(ok(e,l,u,a),l$(e,l,u)),u}function o8(e){return(e=e.current).child?(e.child.tag,e.child.stateNode):null}function o6(e,n){if(null!==(e=e.memoizedState)&&null!==e.dehydrated){var t=e.retryLane;e.retryLane=0!==t&&t<n?t:n}}function o5(e,n){o6(e,n),(e=e.alternate)&&o6(e,n)}i=function(e,n,t){if(null!==e){if(e.memoizedProps!==n.pendingProps||rQ.current)ua=!0;else{if(0==(e.lanes&t)&&0==(128&n.flags))return ua=!1,function(e,n,t){switch(n.tag){case 3:uh(n),lb();break;case 5:an(n);break;case 1:rY(n.type)&&rJ(n);break;case 4:l7(n,n.stateNode.containerInfo);break;case 10:var r=n.type._context,l=n.memoizedProps.value;rB(lx,r._currentValue),r._currentValue=l;break;case 13:if(null!==(r=n.memoizedState)){if(null!==r.dehydrated)return rB(ar,1&ar.current),n.flags|=128,null;if(0!=(t&n.child.childLanes))return ub(e,n,t);return rB(ar,1&ar.current),null!==(e=u_(e,n,t))?e.sibling:null}rB(ar,1&ar.current);break;case 19:if(r=0!=(t&n.childLanes),0!=(128&e.flags)){if(r)return uE(e,n,t);n.flags|=128}if(null!==(l=n.memoizedState)&&(l.rendering=null,l.tail=null,l.lastEffect=null),rB(ar,ar.current),!r)return null;break;case 22:case 23:return n.lanes=0,uc(e,n,t)}return u_(e,n,t)}(e,n,t);ua=0!=(131072&e.flags)}}else ua=!1,lc&&0!=(1048576&n.flags)&&la(n,r9,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;uC(e,n),e=n.pendingProps;var l=rK(n,rW.current);lT(n,t),l=ab(null,n,r,e,l,t);var a=ak();return n.flags|=1,"object"==typeof l&&null!==l&&"function"==typeof l.render&&void 0===l.$$typeof?(n.tag=1,n.memoizedState=null,n.updateQueue=null,rY(r)?(a=!0,rJ(n)):a=!1,n.memoizedState=null!==l.state&&void 0!==l.state?l.state:null,lI(n),l.updater=lq,n.stateNode=l,l._reactInternals=n,lG(n,r,e,t),n=um(null,n,r,!0,a,t)):(n.tag=0,lc&&a&&lu(n),uu(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(uC(e,n),e=n.pendingProps,r=(l=r._init)(r._payload),n.type=r,l=n.tag=function(e){if("function"==typeof e)return oq(e)?1:0;if(null!=e){if((e=e.$$typeof)===F)return 11;if(e===I)return 14}return 2}(r),e=lS(r,e),l){case 0:n=ud(null,n,r,e,t);break e;case 1:n=up(null,n,r,e,t);break e;case 11:n=uo(null,n,r,e,t);break e;case 14:n=ui(null,n,r,lS(r.type,e),t);break e}throw Error(f(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:lS(r,l),ud(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:lS(r,l),up(e,n,r,l,t);case 3:e:{if(uh(n),null===e)throw Error(f(387));r=n.pendingProps,l=(a=n.memoizedState).element,lU(e,n),lB(n,r,null,t);var u=n.memoizedState;if(r=u.element,a.isDehydrated){if(a={element:r,isDehydrated:!1,cache:u.cache,pendingSuspenseBoundaries:u.pendingSuspenseBoundaries,transitions:u.transitions},n.updateQueue.baseState=a,n.memoizedState=a,256&n.flags){l=a8(Error(f(423)),n),n=ug(e,n,r,t,l);break e}if(r!==l){l=a8(Error(f(424)),n),n=ug(e,n,r,t,l);break e}for(ls=r_(n.stateNode.containerInfo.firstChild),li=n,lc=!0,lf=null,t=l3(n,null,r,t),n.child=t;t;)t.flags=-3&t.flags|4096,t=t.sibling}else{if(lb(),r===l){n=u_(e,n,t);break e}uu(e,n,r,t)}n=n.child}return n;case 5:return an(n),null===e&&lh(n),r=n.type,l=n.pendingProps,a=null!==e?e.memoizedProps:null,u=l.children,rb(r,l)?u=null:null!==a&&rb(r,a)&&(n.flags|=32),uf(e,n),uu(e,n,u,t),n.child;case 6:return null===e&&lh(n),null;case 13:return ub(e,n,t);case 4:return l7(n,n.stateNode.containerInfo),r=n.pendingProps,null===e?n.child=l2(n,null,r,t):uu(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:lS(r,l),uo(e,n,r,l,t);case 7:return uu(e,n,n.pendingProps,t),n.child;case 8:case 12:return uu(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,a=n.memoizedProps,u=l.value,rB(lx,r._currentValue),r._currentValue=u,null!==a){if(tD(a.value,u)){if(a.children===l.children&&!rQ.current){n=u_(e,n,t);break e}}else for(null!==(a=n.child)&&(a.return=n);null!==a;){var o=a.dependencies;if(null!==o){u=a.child;for(var i=o.firstContext;null!==i;){if(i.context===r){if(1===a.tag){(i=lV(-1,t&-t)).tag=2;var s=a.updateQueue;if(null!==s){var c=(s=s.shared).pending;null===c?i.next=i:(i.next=c.next,c.next=i),s.pending=i}}a.lanes|=t,null!==(i=a.alternate)&&(i.lanes|=t),lz(a.return,t,n),o.lanes|=t;break}i=i.next}}else if(10===a.tag)u=a.type===n.type?null:a.child;else if(18===a.tag){if(null===(u=a.return))throw Error(f(341));u.lanes|=t,null!==(o=u.alternate)&&(o.lanes|=t),lz(u,t,n),u=a.sibling}else u=a.child;if(null!==u)u.return=a;else for(u=a;null!==u;){if(u===n){u=null;break}if(null!==(a=u.sibling)){a.return=u.return,u=a;break}u=u.return}a=u}}uu(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,lT(n,t),l=lL(l),r=r(l),n.flags|=1,uu(e,n,r,t),n.child;case 14:return l=lS(r=n.type,n.pendingProps),l=lS(r.type,l),ui(e,n,r,l,t);case 15:return us(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:lS(r,l),uC(e,n),n.tag=1,rY(r)?(e=!0,rJ(n)):e=!1,lT(n,t),lY(n,r,l),lG(n,r,l,t),um(null,n,r,!0,e,t);case 19:return uE(e,n,t);case 22:return uc(e,n,t)}throw Error(f(156,n.tag))};var o9="function"==typeof reportError?reportError:function(e){console.error(e)};function o7(e){this._internalRoot=e}function ie(e){this._internalRoot=e}function it(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType)}function ir(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function il(){}function ia(e,n,t,r,l){var a=t._reactRootContainer;if(a){var u=a;if("function"==typeof l){var o=l;l=function(){var e=o8(u);o.call(e)}}o4(n,u,e,l)}else u=function(e,n,t,r,l){if(l){if("function"==typeof r){var a=r;r=function(){var e=o8(u);a.call(e)}}var u=o3(n,r,e,0,null,!1,!1,"",il);return e._reactRootContainer=u,e[rL]=u.current,ra(8===e.nodeType?e.parentNode:e),oN(),u}for(;l=e.lastChild;)e.removeChild(l);if("function"==typeof r){var o=r;r=function(){var e=o8(i);o.call(e)}}var i=o1(e,0,!1,null,null,!1,!1,"",il);return e._reactRootContainer=i,e[rL]=i.current,ra(8===e.nodeType?e.parentNode:e),oN(function(){o4(n,i,t,r)}),i}(t,n,e,l,r);return o8(u)}ie.prototype.render=o7.prototype.render=function(e){var n=this._internalRoot;if(null===n)throw Error(f(409));o4(e,n,null,null)},ie.prototype.unmount=o7.prototype.unmount=function(){var e=this._internalRoot;if(null!==e){this._internalRoot=null;var n=e.containerInfo;oN(function(){o4(null,e,null,null)}),n[rL]=null}},ie.prototype.unstable_scheduleHydration=function(e){if(e){var n=nh();e={blockedOn:null,target:e,priority:n};for(var t=0;t<nE.length&&0!==n&&n<nE[t].priority;t++);nE.splice(t,0,e),0===t&&nN(e)}},nd=function(e){switch(e.tag){case 3:var n=e.stateNode;if(n.current.memoizedState.isDehydrated){var t=nr(n.pendingLanes);0!==t&&(ns(n,1|t),ow(n,eJ()),0==(6&u2)&&(ou=eJ()+500,r4()))}break;case 13:oN(function(){var n=lO(e,1);null!==n&&ok(n,e,1,oy())}),o5(e,1)}},np=function(e){if(13===e.tag){var n=lO(e,134217728);null!==n&&ok(n,e,134217728,oy()),o5(e,134217728)}},nm=function(e){if(13===e.tag){var n=ob(e),t=lO(e,n);null!==t&&ok(t,e,n,oy()),o5(e,n)}},nh=function(){return nc},ng=function(e,n){var t=nc;try{return nc=e,n()}finally{nc=t}},eC=function(e,n,t){switch(n){case"input":if(en(e,t),n=t.name,"radio"===t.type&&null!=n){for(t=e;t.parentNode;)t=t.parentNode;for(t=t.querySelectorAll("input[name="+JSON.stringify(""+n)+'][type="radio"]'),n=0;n<t.length;n++){var r=t[n];if(r!==e&&r.form===e.form){var l=rU(r);if(!l)throw Error(f(90));X(r),en(r,l)}}}break;case"textarea":ei(e,t);break;case"select":null!=(n=t.value)&&ea(e,!!t.multiple,n,!1)}},eL=oP,eR=oN;var iu={findFiberByHostInstance:rO,bundleType:0,version:"18.2.0",rendererPackageName:"react-dom"},io={bundleType:iu.bundleType,version:iu.version,rendererPackageName:iu.rendererPackageName,rendererConfig:iu.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:_.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return null===(e=eK(e))?null:e.stateNode},findFiberByHostInstance:iu.findFiberByHostInstance||function(){return null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0-next-9e3b772b8-20220608"};if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var ii=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!ii.isDisabled&&ii.supportsFiber)try{e6=ii.inject(io),e5=ii}catch(e){}}n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED={usingClientEntryPoint:!1,Events:[rD,rI,rU,ez,eT,oP]},n.createPortal=function(e,n){var t=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!it(n))throw Error(f(200));return function(e,n,t){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:N,key:null==r?null:""+r,children:e,containerInfo:n,implementation:null}}(e,n,null,t)},n.createRoot=function(e,n){if(!it(e))throw Error(f(299));var t=!1,r="",l=o9;return null!=n&&(!0===n.unstable_strictMode&&(t=!0),void 0!==n.identifierPrefix&&(r=n.identifierPrefix),void 0!==n.onRecoverableError&&(l=n.onRecoverableError)),n=o1(e,1,!1,null,null,t,!1,r,l),e[rL]=n.current,ra(8===e.nodeType?e.parentNode:e),new o7(n)},n.findDOMNode=function(e){if(null==e)return null;if(1===e.nodeType)return e;var n=e._reactInternals;if(void 0===n){if("function"==typeof e.render)throw Error(f(188));throw Error(f(268,e=Object.keys(e).join(",")))}return e=null===(e=eK(n))?null:e.stateNode},n.flushSync=function(e){return oN(e)},n.hydrate=function(e,n,t){if(!ir(n))throw Error(f(200));return ia(null,e,n,!0,t)},n.hydrateRoot=function(e,n,t){if(!it(e))throw Error(f(405));var r=null!=t&&t.hydratedSources||null,l=!1,a="",u=o9;if(null!=t&&(!0===t.unstable_strictMode&&(l=!0),void 0!==t.identifierPrefix&&(a=t.identifierPrefix),void 0!==t.onRecoverableError&&(u=t.onRecoverableError)),n=o3(n,null,e,1,null!=t?t:null,l,!1,a,u),e[rL]=n.current,ra(e),r)for(e=0;e<r.length;e++)l=(l=(t=r[e])._getVersion)(t._source),null==n.mutableSourceEagerHydrationData?n.mutableSourceEagerHydrationData=[t,l]:n.mutableSourceEagerHydrationData.push(t,l);return new ie(n)},n.render=function(e,n,t){if(!ir(n))throw Error(f(200));return ia(null,e,n,!1,t)},n.unmountComponentAtNode=function(e){if(!ir(e))throw Error(f(40));return!!e._reactRootContainer&&(oN(function(){ia(null,null,e,!1,function(){e._reactRootContainer=null,e[rL]=null})}),!0)},n.unstable_batchedUpdates=oP,n.unstable_renderSubtreeIntoContainer=function(e,n,t,r){if(!ir(t))throw Error(f(200));if(null==e||void 0===e._reactInternals)throw Error(f(38));return ia(e,n,t,!1,r)},n.version="18.2.0-next-9e3b772b8-20220608"},745:function(e,n,t){var r=t(3935);n.createRoot=r.createRoot,n.hydrateRoot=r.hydrateRoot},3935:function(e,n,t){!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=t(4448)},2408:function(e,n){/** + */var o,s,w,x,C,_,j=i(7294),z=i(3840);function p(a){for(var u="https://reactjs.org/docs/error-decoder.html?invariant="+a,i=1;i<arguments.length;i++)u+="&args[]="+encodeURIComponent(arguments[i]);return"Minified React error #"+a+"; visit "+u+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var P=new Set,U={};function fa(a,u){ha(a,u),ha(a+"Capture",u)}function ha(a,u){for(U[a]=u,a=0;a<u.length;a++)P.add(u[a])}var V=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),B=Object.prototype.hasOwnProperty,$=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Y={},Z={};function oa(a){return!!B.call(Z,a)||!B.call(Y,a)&&($.test(a)?Z[a]=!0:(Y[a]=!0,!1))}function pa(a,u,i,o){if(null!==i&&0===i.type)return!1;switch(typeof u){case"function":case"symbol":return!0;case"boolean":if(o)return!1;if(null!==i)return!i.acceptsBooleans;return"data-"!==(a=a.toLowerCase().slice(0,5))&&"aria-"!==a;default:return!1}}function qa(a,u,i,o){if(null==u||pa(a,u,i,o))return!0;if(o)return!1;if(null!==i)switch(i.type){case 3:return!u;case 4:return!1===u;case 5:return isNaN(u);case 6:return isNaN(u)||1>u}return!1}function v(a,u,i,o,s,w,x){this.acceptsBooleans=2===u||3===u||4===u,this.attributeName=o,this.attributeNamespace=s,this.mustUseProperty=i,this.propertyName=a,this.type=u,this.sanitizeURL=w,this.removeEmptyString=x}var X={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){X[a]=new v(a,0,!1,a,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var u=a[0];X[u]=new v(u,1,!1,a[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(a){X[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){X[a]=new v(a,2,!1,a,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){X[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(a){X[a]=new v(a,3,!0,a,null,!1,!1)}),["capture","download"].forEach(function(a){X[a]=new v(a,4,!1,a,null,!1,!1)}),["cols","rows","size","span"].forEach(function(a){X[a]=new v(a,6,!1,a,null,!1,!1)}),["rowSpan","start"].forEach(function(a){X[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ee=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}function ta(a,u,i,o){var s=X.hasOwnProperty(u)?X[u]:null;(null!==s?0!==s.type:o||!(2<u.length)||"o"!==u[0]&&"O"!==u[0]||"n"!==u[1]&&"N"!==u[1])&&(qa(u,i,s,o)&&(i=null),o||null===s?oa(u)&&(null===i?a.removeAttribute(u):a.setAttribute(u,""+i)):s.mustUseProperty?a[s.propertyName]=null===i?3!==s.type&&"":i:(u=s.attributeName,o=s.attributeNamespace,null===i?a.removeAttribute(u):(i=3===(s=s.type)||4===s&&!0===i?"":""+i,o?a.setAttributeNS(o,u,i):a.setAttribute(u,i))))}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var u=a.replace(ee,sa);X[u]=new v(u,1,!1,a,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var u=a.replace(ee,sa);X[u]=new v(u,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(a){var u=a.replace(ee,sa);X[u]=new v(u,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(a){X[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)}),X.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(a){X[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});var en=j.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,et=Symbol.for("react.element"),er=Symbol.for("react.portal"),ea=Symbol.for("react.fragment"),eu=Symbol.for("react.strict_mode"),eo=Symbol.for("react.profiler"),es=Symbol.for("react.provider"),ec=Symbol.for("react.context"),ef=Symbol.for("react.forward_ref"),ep=Symbol.for("react.suspense"),eg=Symbol.for("react.suspense_list"),em=Symbol.for("react.memo"),ev=Symbol.for("react.lazy");Symbol.for("react.scope"),Symbol.for("react.debug_trace_mode");var eb=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden"),Symbol.for("react.cache"),Symbol.for("react.tracing_marker");var ey=Symbol.iterator;function Ka(a){return null===a||"object"!=typeof a?null:"function"==typeof(a=ey&&a[ey]||a["@@iterator"])?a:null}var ew,eS=Object.assign;function Ma(a){if(void 0===ew)try{throw Error()}catch(a){var u=a.stack.trim().match(/\n( *(at )?)/);ew=u&&u[1]||""}return"\n"+ew+a}var eE=!1;function Oa(a,u){if(!a||eE)return"";eE=!0;var i=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(u){if(u=function(){throw Error()},Object.defineProperty(u.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(u,[])}catch(a){var o=a}Reflect.construct(a,[],u)}else{try{u.call()}catch(a){o=a}a.call(u.prototype)}}else{try{throw Error()}catch(a){o=a}a()}}catch(u){if(u&&o&&"string"==typeof u.stack){for(var s=u.stack.split("\n"),w=o.stack.split("\n"),x=s.length-1,C=w.length-1;1<=x&&0<=C&&s[x]!==w[C];)C--;for(;1<=x&&0<=C;x--,C--)if(s[x]!==w[C]){if(1!==x||1!==C)do if(x--,0>--C||s[x]!==w[C]){var _="\n"+s[x].replace(" at new "," at ");return a.displayName&&_.includes("<anonymous>")&&(_=_.replace("<anonymous>",a.displayName)),_}while(1<=x&&0<=C);break}}}finally{eE=!1,Error.prepareStackTrace=i}return(a=a?a.displayName||a.name:"")?Ma(a):""}function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1);case 11:return a=Oa(a.type.render,!1);case 1:return a=Oa(a.type,!0);default:return""}}function Qa(a){if(null==a)return null;if("function"==typeof a)return a.displayName||a.name||null;if("string"==typeof a)return a;switch(a){case ea:return"Fragment";case er:return"Portal";case eo:return"Profiler";case eu:return"StrictMode";case ep:return"Suspense";case eg:return"SuspenseList"}if("object"==typeof a)switch(a.$$typeof){case ec:return(a.displayName||"Context")+".Consumer";case es:return(a._context.displayName||"Context")+".Provider";case ef:var u=a.render;return(a=a.displayName)||(a=""!==(a=u.displayName||u.name||"")?"ForwardRef("+a+")":"ForwardRef"),a;case em:return null!==(u=a.displayName||null)?u:Qa(a.type)||"Memo";case ev:u=a._payload,a=a._init;try{return Qa(a(u))}catch(a){}}return null}function Ra(a){var u=a.type;switch(a.tag){case 24:return"Cache";case 9:return(u.displayName||"Context")+".Consumer";case 10:return(u._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=(a=u.render).displayName||a.name||"",u.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return u;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Qa(u);case 8:return u===eu?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof u)return u.displayName||u.name||null;if("string"==typeof u)return u}return null}function Sa(a){switch(typeof a){case"boolean":case"number":case"string":case"undefined":case"object":return a;default:return""}}function Ta(a){var u=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===u||"radio"===u)}function Ua(a){var u=Ta(a)?"checked":"value",i=Object.getOwnPropertyDescriptor(a.constructor.prototype,u),o=""+a[u];if(!a.hasOwnProperty(u)&&void 0!==i&&"function"==typeof i.get&&"function"==typeof i.set){var s=i.get,w=i.set;return Object.defineProperty(a,u,{configurable:!0,get:function(){return s.call(this)},set:function(a){o=""+a,w.call(this,a)}}),Object.defineProperty(a,u,{enumerable:i.enumerable}),{getValue:function(){return o},setValue:function(a){o=""+a},stopTracking:function(){a._valueTracker=null,delete a[u]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var u=a._valueTracker;if(!u)return!0;var i=u.getValue(),o="";return a&&(o=Ta(a)?a.checked?"true":"false":a.value),(a=o)!==i&&(u.setValue(a),!0)}function Xa(a){if(void 0===(a=a||("undefined"!=typeof document?document:void 0)))return null;try{return a.activeElement||a.body}catch(u){return a.body}}function Ya(a,u){var i=u.checked;return eS({},u,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=i?i:a._wrapperState.initialChecked})}function Za(a,u){var i=null==u.defaultValue?"":u.defaultValue,o=null!=u.checked?u.checked:u.defaultChecked;i=Sa(null!=u.value?u.value:i),a._wrapperState={initialChecked:o,initialValue:i,controlled:"checkbox"===u.type||"radio"===u.type?null!=u.checked:null!=u.value}}function ab(a,u){null!=(u=u.checked)&&ta(a,"checked",u,!1)}function bb(a,u){ab(a,u);var i=Sa(u.value),o=u.type;if(null!=i)"number"===o?(0===i&&""===a.value||a.value!=i)&&(a.value=""+i):a.value!==""+i&&(a.value=""+i);else if("submit"===o||"reset"===o){a.removeAttribute("value");return}u.hasOwnProperty("value")?cb(a,u.type,i):u.hasOwnProperty("defaultValue")&&cb(a,u.type,Sa(u.defaultValue)),null==u.checked&&null!=u.defaultChecked&&(a.defaultChecked=!!u.defaultChecked)}function db(a,u,i){if(u.hasOwnProperty("value")||u.hasOwnProperty("defaultValue")){var o=u.type;if(!("submit"!==o&&"reset"!==o||void 0!==u.value&&null!==u.value))return;u=""+a._wrapperState.initialValue,i||u===a.value||(a.value=u),a.defaultValue=u}""!==(i=a.name)&&(a.name=""),a.defaultChecked=!!a._wrapperState.initialChecked,""!==i&&(a.name=i)}function cb(a,u,i){("number"!==u||Xa(a.ownerDocument)!==a)&&(null==i?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+i&&(a.defaultValue=""+i))}var ex=Array.isArray;function fb(a,u,i,o){if(a=a.options,u){u={};for(var s=0;s<i.length;s++)u["$"+i[s]]=!0;for(i=0;i<a.length;i++)s=u.hasOwnProperty("$"+a[i].value),a[i].selected!==s&&(a[i].selected=s),s&&o&&(a[i].defaultSelected=!0)}else{for(s=0,i=""+Sa(i),u=null;s<a.length;s++){if(a[s].value===i){a[s].selected=!0,o&&(a[s].defaultSelected=!0);return}null!==u||a[s].disabled||(u=a[s])}null!==u&&(u.selected=!0)}}function gb(a,u){if(null!=u.dangerouslySetInnerHTML)throw Error(p(91));return eS({},u,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function hb(a,u){var i=u.value;if(null==i){if(i=u.children,u=u.defaultValue,null!=i){if(null!=u)throw Error(p(92));if(ex(i)){if(1<i.length)throw Error(p(93));i=i[0]}u=i}null==u&&(u=""),i=u}a._wrapperState={initialValue:Sa(i)}}function ib(a,u){var i=Sa(u.value),o=Sa(u.defaultValue);null!=i&&((i=""+i)!==a.value&&(a.value=i),null==u.defaultValue&&a.defaultValue!==i&&(a.defaultValue=i)),null!=o&&(a.defaultValue=""+o)}function jb(a){var u=a.textContent;u===a._wrapperState.initialValue&&""!==u&&null!==u&&(a.value=u)}function kb(a){switch(a){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function lb(a,u){return null==a||"http://www.w3.org/1999/xhtml"===a?kb(u):"http://www.w3.org/2000/svg"===a&&"foreignObject"===u?"http://www.w3.org/1999/xhtml":a}var eC,e_,ez=(eC=function(a,u){if("http://www.w3.org/2000/svg"!==a.namespaceURI||"innerHTML"in a)a.innerHTML=u;else{for((e_=e_||document.createElement("div")).innerHTML="<svg>"+u.valueOf().toString()+"</svg>",u=e_.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;u.firstChild;)a.appendChild(u.firstChild)}},"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(a,u,i,o){MSApp.execUnsafeLocalFunction(function(){return eC(a,u,i,o)})}:eC);function ob(a,u){if(u){var i=a.firstChild;if(i&&i===a.lastChild&&3===i.nodeType){i.nodeValue=u;return}}a.textContent=u}var eL={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},eN=["Webkit","ms","Moz","O"];function rb(a,u,i){return null==u||"boolean"==typeof u||""===u?"":i||"number"!=typeof u||0===u||eL.hasOwnProperty(a)&&eL[a]?(""+u).trim():u+"px"}function sb(a,u){for(var i in a=a.style,u)if(u.hasOwnProperty(i)){var o=0===i.indexOf("--"),s=rb(i,u[i],o);"float"===i&&(i="cssFloat"),o?a.setProperty(i,s):a[i]=s}}Object.keys(eL).forEach(function(a){eN.forEach(function(u){eL[u=u+a.charAt(0).toUpperCase()+a.substring(1)]=eL[a]})});var eP=eS({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ub(a,u){if(u){if(eP[a]&&(null!=u.children||null!=u.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=u.dangerouslySetInnerHTML){if(null!=u.children)throw Error(p(60));if("object"!=typeof u.dangerouslySetInnerHTML||!("__html"in u.dangerouslySetInnerHTML))throw Error(p(61))}if(null!=u.style&&"object"!=typeof u.style)throw Error(p(62))}}function vb(a,u){if(-1===a.indexOf("-"))return"string"==typeof u.is;switch(a){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var eT=null;function xb(a){return(a=a.target||a.srcElement||window).correspondingUseElement&&(a=a.correspondingUseElement),3===a.nodeType?a.parentNode:a}var eD=null,eM=null,eR=null;function Bb(a){if(a=Cb(a)){if("function"!=typeof eD)throw Error(p(280));var u=a.stateNode;u&&(u=Db(u),eD(a.stateNode,a.type,u))}}function Eb(a){eM?eR?eR.push(a):eR=[a]:eM=a}function Fb(){if(eM){var a=eM,u=eR;if(eR=eM=null,Bb(a),u)for(a=0;a<u.length;a++)Bb(u[a])}}function Gb(a,u){return a(u)}function Hb(){}var eI=!1;function Jb(a,u,i){if(eI)return a(u,i);eI=!0;try{return Gb(a,u,i)}finally{eI=!1,(null!==eM||null!==eR)&&(Hb(),Fb())}}function Kb(a,u){var i=a.stateNode;if(null===i)return null;var o=Db(i);if(null===o)return null;switch(i=o[u],u){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(o=!o.disabled)||(o=!("button"===(a=a.type)||"input"===a||"select"===a||"textarea"===a)),a=!o;break;default:a=!1}if(a)return null;if(i&&"function"!=typeof i)throw Error(p(231,u,typeof i));return i}var eF=!1;if(V)try{var eO={};Object.defineProperty(eO,"passive",{get:function(){eF=!0}}),window.addEventListener("test",eO,eO),window.removeEventListener("test",eO,eO)}catch(a){eF=!1}function Nb(a,u,i,o,s,w,x,C,_){var j=Array.prototype.slice.call(arguments,3);try{u.apply(i,j)}catch(a){this.onError(a)}}var eU=!1,eV=null,eW=!1,eA=null,eQ={onError:function(a){eU=!0,eV=a}};function Tb(a,u,i,o,s,w,x,C,_){eU=!1,eV=null,Nb.apply(eQ,arguments)}function Ub(a,u,i,o,s,w,x,C,_){if(Tb.apply(this,arguments),eU){if(eU){var j=eV;eU=!1,eV=null}else throw Error(p(198));eW||(eW=!0,eA=j)}}function Vb(a){var u=a,i=a;if(a.alternate)for(;u.return;)u=u.return;else{a=u;do 0!=(4098&(u=a).flags)&&(i=u.return),a=u.return;while(a)}return 3===u.tag?i:null}function Wb(a){if(13===a.tag){var u=a.memoizedState;if(null===u&&null!==(a=a.alternate)&&(u=a.memoizedState),null!==u)return u.dehydrated}return null}function Xb(a){if(Vb(a)!==a)throw Error(p(188))}function Yb(a){var u=a.alternate;if(!u){if(null===(u=Vb(a)))throw Error(p(188));return u!==a?null:a}for(var i=a,o=u;;){var s=i.return;if(null===s)break;var w=s.alternate;if(null===w){if(null!==(o=s.return)){i=o;continue}break}if(s.child===w.child){for(w=s.child;w;){if(w===i)return Xb(s),a;if(w===o)return Xb(s),u;w=w.sibling}throw Error(p(188))}if(i.return!==o.return)i=s,o=w;else{for(var x=!1,C=s.child;C;){if(C===i){x=!0,i=s,o=w;break}if(C===o){x=!0,o=s,i=w;break}C=C.sibling}if(!x){for(C=w.child;C;){if(C===i){x=!0,i=w,o=s;break}if(C===o){x=!0,o=w,i=s;break}C=C.sibling}if(!x)throw Error(p(189))}}if(i.alternate!==o)throw Error(p(190))}if(3!==i.tag)throw Error(p(188));return i.stateNode.current===i?a:u}function Zb(a){return null!==(a=Yb(a))?$b(a):null}function $b(a){if(5===a.tag||6===a.tag)return a;for(a=a.child;null!==a;){var u=$b(a);if(null!==u)return u;a=a.sibling}return null}var eB=z.unstable_scheduleCallback,e$=z.unstable_cancelCallback,eH=z.unstable_shouldYield,eK=z.unstable_requestPaint,eG=z.unstable_now,eY=z.unstable_getCurrentPriorityLevel,eq=z.unstable_ImmediatePriority,eZ=z.unstable_UserBlockingPriority,eX=z.unstable_NormalPriority,eJ=z.unstable_LowPriority,e0=z.unstable_IdlePriority,e1=null,e2=null;function mc(a){if(e2&&"function"==typeof e2.onCommitFiberRoot)try{e2.onCommitFiberRoot(e1,a,void 0,128==(128&a.current.flags))}catch(a){}}var e3=Math.clz32?Math.clz32:nc,e4=Math.log,e8=Math.LN2;function nc(a){return 0==(a>>>=0)?32:31-(e4(a)/e8|0)|0}var e6=64,e5=4194304;function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194240&a;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return 130023424&a;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return a}}function uc(a,u){var i=a.pendingLanes;if(0===i)return 0;var o=0,s=a.suspendedLanes,w=a.pingedLanes,x=268435455&i;if(0!==x){var C=x&~s;0!==C?o=tc(C):0!=(w&=x)&&(o=tc(w))}else 0!=(x=i&~s)?o=tc(x):0!==w&&(o=tc(w));if(0===o)return 0;if(0!==u&&u!==o&&0==(u&s)&&((s=o&-o)>=(w=u&-u)||16===s&&0!=(4194240&w)))return u;if(0!=(4&o)&&(o|=16&i),0!==(u=a.entangledLanes))for(a=a.entanglements,u&=o;0<u;)s=1<<(i=31-e3(u)),o|=a[i],u&=~s;return o}function vc(a,u){switch(a){case 1:case 2:case 4:return u+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return u+5e3;default:return -1}}function wc(a,u){for(var i=a.suspendedLanes,o=a.pingedLanes,s=a.expirationTimes,w=a.pendingLanes;0<w;){var x=31-e3(w),C=1<<x,_=s[x];-1===_?(0==(C&i)||0!=(C&o))&&(s[x]=vc(C,u)):_<=u&&(a.expiredLanes|=C),w&=~C}}function xc(a){return 0!=(a=-1073741825&a.pendingLanes)?a:1073741824&a?1073741824:0}function yc(){var a=e6;return 0==(4194240&(e6<<=1))&&(e6=64),a}function zc(a){for(var u=[],i=0;31>i;i++)u.push(a);return u}function Ac(a,u,i){a.pendingLanes|=u,536870912!==u&&(a.suspendedLanes=0,a.pingedLanes=0),(a=a.eventTimes)[u=31-e3(u)]=i}function Bc(a,u){var i=a.pendingLanes&~u;a.pendingLanes=u,a.suspendedLanes=0,a.pingedLanes=0,a.expiredLanes&=u,a.mutableReadLanes&=u,a.entangledLanes&=u,u=a.entanglements;var o=a.eventTimes;for(a=a.expirationTimes;0<i;){var s=31-e3(i),w=1<<s;u[s]=0,o[s]=-1,a[s]=-1,i&=~w}}function Cc(a,u){var i=a.entangledLanes|=u;for(a=a.entanglements;i;){var o=31-e3(i),s=1<<o;s&u|a[o]&u&&(a[o]|=u),i&=~s}}var e9=0;function Dc(a){return 1<(a&=-a)?4<a?0!=(268435455&a)?16:536870912:4:1}var e7,nn,nt,nr,na,nu=!1,no=[],ns=null,np=null,nh=null,ng=new Map,nm=new Map,nv=[],nb="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Sc(a,u){switch(a){case"focusin":case"focusout":ns=null;break;case"dragenter":case"dragleave":np=null;break;case"mouseover":case"mouseout":nh=null;break;case"pointerover":case"pointerout":ng.delete(u.pointerId);break;case"gotpointercapture":case"lostpointercapture":nm.delete(u.pointerId)}}function Tc(a,u,i,o,s,w){return null===a||a.nativeEvent!==w?(a={blockedOn:u,domEventName:i,eventSystemFlags:o,nativeEvent:w,targetContainers:[s]},null!==u&&null!==(u=Cb(u))&&nn(u)):(a.eventSystemFlags|=o,u=a.targetContainers,null!==s&&-1===u.indexOf(s)&&u.push(s)),a}function Uc(a,u,i,o,s){switch(u){case"focusin":return ns=Tc(ns,a,u,i,o,s),!0;case"dragenter":return np=Tc(np,a,u,i,o,s),!0;case"mouseover":return nh=Tc(nh,a,u,i,o,s),!0;case"pointerover":var w=s.pointerId;return ng.set(w,Tc(ng.get(w)||null,a,u,i,o,s)),!0;case"gotpointercapture":return w=s.pointerId,nm.set(w,Tc(nm.get(w)||null,a,u,i,o,s)),!0}return!1}function Vc(a){var u=Wc(a.target);if(null!==u){var i=Vb(u);if(null!==i){if(13===(u=i.tag)){if(null!==(u=Wb(i))){a.blockedOn=u,na(a.priority,function(){nt(i)});return}}else if(3===u&&i.stateNode.current.memoizedState.isDehydrated){a.blockedOn=3===i.tag?i.stateNode.containerInfo:null;return}}}a.blockedOn=null}function Xc(a){if(null!==a.blockedOn)return!1;for(var u=a.targetContainers;0<u.length;){var i=Yc(a.domEventName,a.eventSystemFlags,u[0],a.nativeEvent);if(null!==i)return null!==(u=Cb(i))&&nn(u),a.blockedOn=i,!1;var o=new(i=a.nativeEvent).constructor(i.type,i);eT=o,i.target.dispatchEvent(o),eT=null,u.shift()}return!0}function Zc(a,u,i){Xc(a)&&i.delete(u)}function $c(){nu=!1,null!==ns&&Xc(ns)&&(ns=null),null!==np&&Xc(np)&&(np=null),null!==nh&&Xc(nh)&&(nh=null),ng.forEach(Zc),nm.forEach(Zc)}function ad(a,u){a.blockedOn===u&&(a.blockedOn=null,nu||(nu=!0,z.unstable_scheduleCallback(z.unstable_NormalPriority,$c)))}function bd(a){function b(u){return ad(u,a)}if(0<no.length){ad(no[0],a);for(var u=1;u<no.length;u++){var i=no[u];i.blockedOn===a&&(i.blockedOn=null)}}for(null!==ns&&ad(ns,a),null!==np&&ad(np,a),null!==nh&&ad(nh,a),ng.forEach(b),nm.forEach(b),u=0;u<nv.length;u++)(i=nv[u]).blockedOn===a&&(i.blockedOn=null);for(;0<nv.length&&null===(u=nv[0]).blockedOn;)Vc(u),null===u.blockedOn&&nv.shift()}var ny=en.ReactCurrentBatchConfig,nk=!0;function ed(a,u,i,o){var s=e9,w=ny.transition;ny.transition=null;try{e9=1,fd(a,u,i,o)}finally{e9=s,ny.transition=w}}function gd(a,u,i,o){var s=e9,w=ny.transition;ny.transition=null;try{e9=4,fd(a,u,i,o)}finally{e9=s,ny.transition=w}}function fd(a,u,i,o){if(nk){var s=Yc(a,u,i,o);if(null===s)hd(a,u,o,nw,i),Sc(a,o);else if(Uc(s,a,u,i,o))o.stopPropagation();else if(Sc(a,o),4&u&&-1<nb.indexOf(a)){for(;null!==s;){var w=Cb(s);if(null!==w&&e7(w),null===(w=Yc(a,u,i,o))&&hd(a,u,o,nw,i),w===s)break;s=w}null!==s&&o.stopPropagation()}else hd(a,u,o,null,i)}}var nw=null;function Yc(a,u,i,o){if(nw=null,null!==(a=Wc(a=xb(o)))){if(null===(u=Vb(a)))a=null;else if(13===(i=u.tag)){if(null!==(a=Wb(u)))return a;a=null}else if(3===i){if(u.stateNode.current.memoizedState.isDehydrated)return 3===u.tag?u.stateNode.containerInfo:null;a=null}else u!==a&&(a=null)}return nw=a,null}function jd(a){switch(a){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(eY()){case eq:return 1;case eZ:return 4;case eX:case eJ:return 16;case e0:return 536870912;default:return 16}default:return 16}}var nS=null,nE=null,nx=null;function nd(){if(nx)return nx;var a,u,i=nE,o=i.length,s="value"in nS?nS.value:nS.textContent,w=s.length;for(a=0;a<o&&i[a]===s[a];a++);var x=o-a;for(u=1;u<=x&&i[o-u]===s[w-u];u++);return nx=s.slice(a,1<u?1-u:void 0)}function od(a){var u=a.keyCode;return"charCode"in a?0===(a=a.charCode)&&13===u&&(a=13):a=u,10===a&&(a=13),32<=a||13===a?a:0}function pd(){return!0}function qd(){return!1}function rd(a){function b(u,i,o,s,w){for(var x in this._reactName=u,this._targetInst=o,this.type=i,this.nativeEvent=s,this.target=w,this.currentTarget=null,a)a.hasOwnProperty(x)&&(u=a[x],this[x]=u?u(s):s[x]);return this.isDefaultPrevented=(null!=s.defaultPrevented?s.defaultPrevented:!1===s.returnValue)?pd:qd,this.isPropagationStopped=qd,this}return eS(b.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!=typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=pd)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!=typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=pd)},persist:function(){},isPersistent:pd}),b}var nC,n_,nj,nz={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},nL=rd(nz),nN=eS({},nz,{view:0,detail:0}),nP=rd(nN),nT=eS({},nN,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:zd,button:0,buttons:0,relatedTarget:function(a){return void 0===a.relatedTarget?a.fromElement===a.srcElement?a.toElement:a.fromElement:a.relatedTarget},movementX:function(a){return"movementX"in a?a.movementX:(a!==nj&&(nj&&"mousemove"===a.type?(nC=a.screenX-nj.screenX,n_=a.screenY-nj.screenY):n_=nC=0,nj=a),nC)},movementY:function(a){return"movementY"in a?a.movementY:n_}}),nD=rd(nT),nM=rd(eS({},nT,{dataTransfer:0})),nR=rd(eS({},nN,{relatedTarget:0})),nI=rd(eS({},nz,{animationName:0,elapsedTime:0,pseudoElement:0})),nF=rd(eS({},nz,{clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}})),nO=rd(eS({},nz,{data:0})),nU={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},nV={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},nW={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Pd(a){var u=this.nativeEvent;return u.getModifierState?u.getModifierState(a):!!(a=nW[a])&&!!u[a]}function zd(){return Pd}var nA=rd(eS({},nN,{key:function(a){if(a.key){var u=nU[a.key]||a.key;if("Unidentified"!==u)return u}return"keypress"===a.type?13===(a=od(a))?"Enter":String.fromCharCode(a):"keydown"===a.type||"keyup"===a.type?nV[a.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:zd,charCode:function(a){return"keypress"===a.type?od(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===a.type?od(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}})),nQ=rd(eS({},nT,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),nB=rd(eS({},nN,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:zd})),n$=rd(eS({},nz,{propertyName:0,elapsedTime:0,pseudoElement:0})),nH=rd(eS({},nT,{deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:0,deltaMode:0})),nK=[9,13,27,32],nG=V&&"CompositionEvent"in window,nY=null;V&&"documentMode"in document&&(nY=document.documentMode);var nq=V&&"TextEvent"in window&&!nY,nZ=V&&(!nG||nY&&8<nY&&11>=nY),nX=!1;function ge(a,u){switch(a){case"keyup":return -1!==nK.indexOf(u.keyCode);case"keydown":return 229!==u.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function he(a){return"object"==typeof(a=a.detail)&&"data"in a?a.data:null}var nJ=!1;function je(a,u){switch(a){case"compositionend":return he(u);case"keypress":if(32!==u.which)return null;return nX=!0," ";case"textInput":return" "===(a=u.data)&&nX?null:a;default:return null}}function ke(a,u){if(nJ)return"compositionend"===a||!nG&&ge(a,u)?(a=nd(),nx=nE=nS=null,nJ=!1,a):null;switch(a){case"paste":default:return null;case"keypress":if(!(u.ctrlKey||u.altKey||u.metaKey)||u.ctrlKey&&u.altKey){if(u.char&&1<u.char.length)return u.char;if(u.which)return String.fromCharCode(u.which)}return null;case"compositionend":return nZ&&"ko"!==u.locale?null:u.data}}var n0={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function me(a){var u=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===u?!!n0[a.type]:"textarea"===u}function ne(a,u,i,o){Eb(o),0<(u=oe(u,"onChange")).length&&(i=new nL("onChange","change",null,i,o),a.push({event:i,listeners:u}))}var n1=null,n2=null;function re(a){se(a,0)}function te(a){if(Wa(ue(a)))return a}function ve(a,u){if("change"===a)return u}var n3=!1;if(V){if(V){var n4="oninput"in document;if(!n4){var n8=document.createElement("div");n8.setAttribute("oninput","return;"),n4="function"==typeof n8.oninput}o=n4}else o=!1;n3=o&&(!document.documentMode||9<document.documentMode)}function Ae(){n1&&(n1.detachEvent("onpropertychange",Be),n2=n1=null)}function Be(a){if("value"===a.propertyName&&te(n2)){var u=[];ne(u,n2,a,xb(a)),Jb(re,u)}}function Ce(a,u,i){"focusin"===a?(Ae(),n1=u,n2=i,n1.attachEvent("onpropertychange",Be)):"focusout"===a&&Ae()}function De(a){if("selectionchange"===a||"keyup"===a||"keydown"===a)return te(n2)}function Ee(a,u){if("click"===a)return te(u)}function Fe(a,u){if("input"===a||"change"===a)return te(u)}function Ge(a,u){return a===u&&(0!==a||1/a==1/u)||a!=a&&u!=u}var n6="function"==typeof Object.is?Object.is:Ge;function Ie(a,u){if(n6(a,u))return!0;if("object"!=typeof a||null===a||"object"!=typeof u||null===u)return!1;var i=Object.keys(a),o=Object.keys(u);if(i.length!==o.length)return!1;for(o=0;o<i.length;o++){var s=i[o];if(!B.call(u,s)||!n6(a[s],u[s]))return!1}return!0}function Je(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function Ke(a,u){var i,o=Je(a);for(a=0;o;){if(3===o.nodeType){if(i=a+o.textContent.length,a<=u&&i>=u)return{node:o,offset:u-a};a=i}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=Je(o)}}function Le(a,u){return!!a&&!!u&&(a===u||(!a||3!==a.nodeType)&&(u&&3===u.nodeType?Le(a,u.parentNode):"contains"in a?a.contains(u):!!a.compareDocumentPosition&&!!(16&a.compareDocumentPosition(u))))}function Me(){for(var a=window,u=Xa();u instanceof a.HTMLIFrameElement;){try{var i="string"==typeof u.contentWindow.location.href}catch(a){i=!1}if(i)a=u.contentWindow;else break;u=Xa(a.document)}return u}function Ne(a){var u=a&&a.nodeName&&a.nodeName.toLowerCase();return u&&("input"===u&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===u||"true"===a.contentEditable)}function Oe(a){var u=Me(),i=a.focusedElem,o=a.selectionRange;if(u!==i&&i&&i.ownerDocument&&Le(i.ownerDocument.documentElement,i)){if(null!==o&&Ne(i)){if(u=o.start,void 0===(a=o.end)&&(a=u),"selectionStart"in i)i.selectionStart=u,i.selectionEnd=Math.min(a,i.value.length);else if((a=(u=i.ownerDocument||document)&&u.defaultView||window).getSelection){a=a.getSelection();var s=i.textContent.length,w=Math.min(o.start,s);o=void 0===o.end?w:Math.min(o.end,s),!a.extend&&w>o&&(s=o,o=w,w=s),s=Ke(i,w);var x=Ke(i,o);s&&x&&(1!==a.rangeCount||a.anchorNode!==s.node||a.anchorOffset!==s.offset||a.focusNode!==x.node||a.focusOffset!==x.offset)&&((u=u.createRange()).setStart(s.node,s.offset),a.removeAllRanges(),w>o?(a.addRange(u),a.extend(x.node,x.offset)):(u.setEnd(x.node,x.offset),a.addRange(u)))}}for(u=[],a=i;a=a.parentNode;)1===a.nodeType&&u.push({element:a,left:a.scrollLeft,top:a.scrollTop});for("function"==typeof i.focus&&i.focus(),i=0;i<u.length;i++)(a=u[i]).element.scrollLeft=a.left,a.element.scrollTop=a.top}}var n5=V&&"documentMode"in document&&11>=document.documentMode,n9=null,n7=null,tn=null,tt=!1;function Ue(a,u,i){var o=i.window===i?i.document:9===i.nodeType?i:i.ownerDocument;tt||null==n9||n9!==Xa(o)||(o="selectionStart"in(o=n9)&&Ne(o)?{start:o.selectionStart,end:o.selectionEnd}:{anchorNode:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset},tn&&Ie(tn,o)||(tn=o,0<(o=oe(n7,"onSelect")).length&&(u=new nL("onSelect","select",null,u,i),a.push({event:u,listeners:o}),u.target=n9)))}function Ve(a,u){var i={};return i[a.toLowerCase()]=u.toLowerCase(),i["Webkit"+a]="webkit"+u,i["Moz"+a]="moz"+u,i}var tr={animationend:Ve("Animation","AnimationEnd"),animationiteration:Ve("Animation","AnimationIteration"),animationstart:Ve("Animation","AnimationStart"),transitionend:Ve("Transition","TransitionEnd")},tl={},tu={};function Ze(a){if(tl[a])return tl[a];if(!tr[a])return a;var u,i=tr[a];for(u in i)if(i.hasOwnProperty(u)&&u in tu)return tl[a]=i[u];return a}V&&(tu=document.createElement("div").style,"AnimationEvent"in window||(delete tr.animationend.animation,delete tr.animationiteration.animation,delete tr.animationstart.animation),"TransitionEvent"in window||delete tr.transitionend.transition);var to=Ze("animationend"),ts=Ze("animationiteration"),td=Ze("animationstart"),tp=Ze("transitionend"),tm=new Map,tv="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function ff(a,u){tm.set(a,u),fa(u,[a])}for(var tb=0;tb<tv.length;tb++){var ty=tv[tb];ff(ty.toLowerCase(),"on"+(ty[0].toUpperCase()+ty.slice(1)))}ff(to,"onAnimationEnd"),ff(ts,"onAnimationIteration"),ff(td,"onAnimationStart"),ff("dblclick","onDoubleClick"),ff("focusin","onFocus"),ff("focusout","onBlur"),ff(tp,"onTransitionEnd"),ha("onMouseEnter",["mouseout","mouseover"]),ha("onMouseLeave",["mouseout","mouseover"]),ha("onPointerEnter",["pointerout","pointerover"]),ha("onPointerLeave",["pointerout","pointerover"]),fa("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),fa("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),fa("onBeforeInput",["compositionend","keypress","textInput","paste"]),fa("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),fa("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),fa("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var tk="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),tw=new Set("cancel close invalid load scroll toggle".split(" ").concat(tk));function nf(a,u,i){var o=a.type||"unknown-event";a.currentTarget=i,Ub(o,u,void 0,a),a.currentTarget=null}function se(a,u){u=0!=(4&u);for(var i=0;i<a.length;i++){var o=a[i],s=o.event;o=o.listeners;e:{var w=void 0;if(u)for(var x=o.length-1;0<=x;x--){var C=o[x],_=C.instance,j=C.currentTarget;if(C=C.listener,_!==w&&s.isPropagationStopped())break e;nf(s,C,j),w=_}else for(x=0;x<o.length;x++){if(_=(C=o[x]).instance,j=C.currentTarget,C=C.listener,_!==w&&s.isPropagationStopped())break e;nf(s,C,j),w=_}}}if(eW)throw a=eA,eW=!1,eA=null,a}function D(a,u){var i=u[tI];void 0===i&&(i=u[tI]=new Set);var o=a+"__bubble";i.has(o)||(pf(u,a,2,!1),i.add(o))}function qf(a,u,i){var o=0;u&&(o|=4),pf(i,a,o,u)}var tS="_reactListening"+Math.random().toString(36).slice(2);function sf(a){if(!a[tS]){a[tS]=!0,P.forEach(function(u){"selectionchange"!==u&&(tw.has(u)||qf(u,!1,a),qf(u,!0,a))});var u=9===a.nodeType?a:a.ownerDocument;null===u||u[tS]||(u[tS]=!0,qf("selectionchange",!1,u))}}function pf(a,u,i,o){switch(jd(u)){case 1:var s=ed;break;case 4:s=gd;break;default:s=fd}i=s.bind(null,u,i,a),s=void 0,eF&&("touchstart"===u||"touchmove"===u||"wheel"===u)&&(s=!0),o?void 0!==s?a.addEventListener(u,i,{capture:!0,passive:s}):a.addEventListener(u,i,!0):void 0!==s?a.addEventListener(u,i,{passive:s}):a.addEventListener(u,i,!1)}function hd(a,u,i,o,s){var w=o;if(0==(1&u)&&0==(2&u)&&null!==o)e:for(;;){if(null===o)return;var x=o.tag;if(3===x||4===x){var C=o.stateNode.containerInfo;if(C===s||8===C.nodeType&&C.parentNode===s)break;if(4===x)for(x=o.return;null!==x;){var _=x.tag;if((3===_||4===_)&&((_=x.stateNode.containerInfo)===s||8===_.nodeType&&_.parentNode===s))return;x=x.return}for(;null!==C;){if(null===(x=Wc(C)))return;if(5===(_=x.tag)||6===_){o=w=x;continue e}C=C.parentNode}}o=o.return}Jb(function(){var o=w,s=xb(i),x=[];e:{var C=tm.get(a);if(void 0!==C){var _=nL,j=a;switch(a){case"keypress":if(0===od(i))break e;case"keydown":case"keyup":_=nA;break;case"focusin":j="focus",_=nR;break;case"focusout":j="blur",_=nR;break;case"beforeblur":case"afterblur":_=nR;break;case"click":if(2===i.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":_=nD;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":_=nM;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":_=nB;break;case to:case ts:case td:_=nI;break;case tp:_=n$;break;case"scroll":_=nP;break;case"wheel":_=nH;break;case"copy":case"cut":case"paste":_=nF;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":_=nQ}var z=0!=(4&u),P=!z&&"scroll"===a,U=z?null!==C?C+"Capture":null:C;z=[];for(var V,B=o;null!==B;){var $=(V=B).stateNode;if(5===V.tag&&null!==$&&(V=$,null!==U&&null!=($=Kb(B,U))&&z.push(tf(B,$,V))),P)break;B=B.return}0<z.length&&(C=new _(C,j,null,i,s),x.push({event:C,listeners:z}))}}if(0==(7&u)){if(C="mouseover"===a||"pointerover"===a,_="mouseout"===a||"pointerout"===a,!(C&&i!==eT&&(j=i.relatedTarget||i.fromElement)&&(Wc(j)||j[tR]))&&(_||C)&&(C=s.window===s?s:(C=s.ownerDocument)?C.defaultView||C.parentWindow:window,_?(j=i.relatedTarget||i.toElement,_=o,null!==(j=j?Wc(j):null)&&(P=Vb(j),j!==P||5!==j.tag&&6!==j.tag)&&(j=null)):(_=null,j=o),_!==j)){if(z=nD,$="onMouseLeave",U="onMouseEnter",B="mouse",("pointerout"===a||"pointerover"===a)&&(z=nQ,$="onPointerLeave",U="onPointerEnter",B="pointer"),P=null==_?C:ue(_),V=null==j?C:ue(j),(C=new z($,B+"leave",_,i,s)).target=P,C.relatedTarget=V,$=null,Wc(s)===o&&((z=new z(U,B+"enter",j,i,s)).target=V,z.relatedTarget=P,$=z),P=$,_&&j)n:{for(z=_,U=j,B=0,V=z;V;V=vf(V))B++;for(V=0,$=U;$;$=vf($))V++;for(;0<B-V;)z=vf(z),B--;for(;0<V-B;)U=vf(U),V--;for(;B--;){if(z===U||null!==U&&z===U.alternate)break n;z=vf(z),U=vf(U)}z=null}else z=null;null!==_&&wf(x,C,_,z,!1),null!==j&&null!==P&&wf(x,P,j,z,!0)}e:{if("select"===(_=(C=o?ue(o):window).nodeName&&C.nodeName.toLowerCase())||"input"===_&&"file"===C.type)var Y,Z=ve;else if(me(C)){if(n3)Z=Fe;else{Z=De;var X=Ce}}else(_=C.nodeName)&&"input"===_.toLowerCase()&&("checkbox"===C.type||"radio"===C.type)&&(Z=Ee);if(Z&&(Z=Z(a,o))){ne(x,Z,i,s);break e}X&&X(a,C,o),"focusout"===a&&(X=C._wrapperState)&&X.controlled&&"number"===C.type&&cb(C,"number",C.value)}switch(X=o?ue(o):window,a){case"focusin":(me(X)||"true"===X.contentEditable)&&(n9=X,n7=o,tn=null);break;case"focusout":tn=n7=n9=null;break;case"mousedown":tt=!0;break;case"contextmenu":case"mouseup":case"dragend":tt=!1,Ue(x,i,s);break;case"selectionchange":if(n5)break;case"keydown":case"keyup":Ue(x,i,s)}if(nG)n:{switch(a){case"compositionstart":var ee="onCompositionStart";break n;case"compositionend":ee="onCompositionEnd";break n;case"compositionupdate":ee="onCompositionUpdate";break n}ee=void 0}else nJ?ge(a,i)&&(ee="onCompositionEnd"):"keydown"===a&&229===i.keyCode&&(ee="onCompositionStart");ee&&(nZ&&"ko"!==i.locale&&(nJ||"onCompositionStart"!==ee?"onCompositionEnd"===ee&&nJ&&(Y=nd()):(nE="value"in(nS=s)?nS.value:nS.textContent,nJ=!0)),0<(X=oe(o,ee)).length&&(ee=new nO(ee,a,null,i,s),x.push({event:ee,listeners:X}),Y?ee.data=Y:null!==(Y=he(i))&&(ee.data=Y))),(Y=nq?je(a,i):ke(a,i))&&0<(o=oe(o,"onBeforeInput")).length&&(s=new nO("onBeforeInput","beforeinput",null,i,s),x.push({event:s,listeners:o}),s.data=Y)}se(x,u)})}function tf(a,u,i){return{instance:a,listener:u,currentTarget:i}}function oe(a,u){for(var i=u+"Capture",o=[];null!==a;){var s=a,w=s.stateNode;5===s.tag&&null!==w&&(s=w,null!=(w=Kb(a,i))&&o.unshift(tf(a,w,s)),null!=(w=Kb(a,u))&&o.push(tf(a,w,s))),a=a.return}return o}function vf(a){if(null===a)return null;do a=a.return;while(a&&5!==a.tag);return a||null}function wf(a,u,i,o,s){for(var w=u._reactName,x=[];null!==i&&i!==o;){var C=i,_=C.alternate,j=C.stateNode;if(null!==_&&_===o)break;5===C.tag&&null!==j&&(C=j,s?null!=(_=Kb(i,w))&&x.unshift(tf(i,_,C)):s||null!=(_=Kb(i,w))&&x.push(tf(i,_,C))),i=i.return}0!==x.length&&a.push({event:u,listeners:x})}var tE=/\r\n?/g,tx=/\u0000|\uFFFD/g;function zf(a){return("string"==typeof a?a:""+a).replace(tE,"\n").replace(tx,"")}function Af(a,u,i){if(u=zf(u),zf(a)!==u&&i)throw Error(p(425))}function Bf(){}var tC=null,t_=null;function Ef(a,u){return"textarea"===a||"noscript"===a||"string"==typeof u.children||"number"==typeof u.children||"object"==typeof u.dangerouslySetInnerHTML&&null!==u.dangerouslySetInnerHTML&&null!=u.dangerouslySetInnerHTML.__html}var tz="function"==typeof setTimeout?setTimeout:void 0,tL="function"==typeof clearTimeout?clearTimeout:void 0,tN="function"==typeof Promise?Promise:void 0,tP="function"==typeof queueMicrotask?queueMicrotask:void 0!==tN?function(a){return tN.resolve(null).then(a).catch(If)}:tz;function If(a){setTimeout(function(){throw a})}function Kf(a,u){var i=u,o=0;do{var s=i.nextSibling;if(a.removeChild(i),s&&8===s.nodeType){if("/$"===(i=s.data)){if(0===o){a.removeChild(s),bd(u);return}o--}else"$"!==i&&"$?"!==i&&"$!"!==i||o++}i=s}while(i);bd(u)}function Lf(a){for(;null!=a;a=a.nextSibling){var u=a.nodeType;if(1===u||3===u)break;if(8===u){if("$"===(u=a.data)||"$!"===u||"$?"===u)break;if("/$"===u)return null}}return a}function Mf(a){a=a.previousSibling;for(var u=0;a;){if(8===a.nodeType){var i=a.data;if("$"===i||"$!"===i||"$?"===i){if(0===u)return a;u--}else"/$"===i&&u++}a=a.previousSibling}return null}var tT=Math.random().toString(36).slice(2),tD="__reactFiber$"+tT,tM="__reactProps$"+tT,tR="__reactContainer$"+tT,tI="__reactEvents$"+tT,tF="__reactListeners$"+tT,tO="__reactHandles$"+tT;function Wc(a){var u=a[tD];if(u)return u;for(var i=a.parentNode;i;){if(u=i[tR]||i[tD]){if(i=u.alternate,null!==u.child||null!==i&&null!==i.child)for(a=Mf(a);null!==a;){if(i=a[tD])return i;a=Mf(a)}return u}i=(a=i).parentNode}return null}function Cb(a){return(a=a[tD]||a[tR])&&(5===a.tag||6===a.tag||13===a.tag||3===a.tag)?a:null}function ue(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(p(33))}function Db(a){return a[tM]||null}var tU=[],tV=-1;function Uf(a){return{current:a}}function E(a){0>tV||(a.current=tU[tV],tU[tV]=null,tV--)}function G(a,u){tU[++tV]=a.current,a.current=u}var tW={},tA=Uf(tW),tQ=Uf(!1),tB=tW;function Yf(a,u){var i=a.type.contextTypes;if(!i)return tW;var o=a.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===u)return o.__reactInternalMemoizedMaskedChildContext;var s,w={};for(s in i)w[s]=u[s];return o&&((a=a.stateNode).__reactInternalMemoizedUnmaskedChildContext=u,a.__reactInternalMemoizedMaskedChildContext=w),w}function Zf(a){return null!=(a=a.childContextTypes)}function $f(){E(tQ),E(tA)}function ag(a,u,i){if(tA.current!==tW)throw Error(p(168));G(tA,u),G(tQ,i)}function bg(a,u,i){var o=a.stateNode;if(u=u.childContextTypes,"function"!=typeof o.getChildContext)return i;for(var s in o=o.getChildContext())if(!(s in u))throw Error(p(108,Ra(a)||"Unknown",s));return eS({},i,o)}function cg(a){return a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||tW,tB=tA.current,G(tA,a),G(tQ,tQ.current),!0}function dg(a,u,i){var o=a.stateNode;if(!o)throw Error(p(169));i?(a=bg(a,u,tB),o.__reactInternalMemoizedMergedChildContext=a,E(tQ),E(tA),G(tA,a)):E(tQ),G(tQ,i)}var t$=null,tH=!1,tK=!1;function hg(a){null===t$?t$=[a]:t$.push(a)}function ig(a){tH=!0,hg(a)}function jg(){if(!tK&&null!==t$){tK=!0;var a=0,u=e9;try{var i=t$;for(e9=1;a<i.length;a++){var o=i[a];do o=o(!0);while(null!==o)}t$=null,tH=!1}catch(u){throw null!==t$&&(t$=t$.slice(a+1)),eB(eq,jg),u}finally{e9=u,tK=!1}}return null}var tG=[],tY=0,tq=null,tZ=0,tX=[],tJ=0,t0=null,t1=1,t2="";function tg(a,u){tG[tY++]=tZ,tG[tY++]=tq,tq=a,tZ=u}function ug(a,u,i){tX[tJ++]=t1,tX[tJ++]=t2,tX[tJ++]=t0,t0=a;var o=t1;a=t2;var s=32-e3(o)-1;o&=~(1<<s),i+=1;var w=32-e3(u)+s;if(30<w){var x=s-s%5;w=(o&(1<<x)-1).toString(32),o>>=x,s-=x,t1=1<<32-e3(u)+s|i<<s|o,t2=w+a}else t1=1<<w|i<<s|o,t2=a}function vg(a){null!==a.return&&(tg(a,1),ug(a,1,0))}function wg(a){for(;a===tq;)tq=tG[--tY],tG[tY]=null,tZ=tG[--tY],tG[tY]=null;for(;a===t0;)t0=tX[--tJ],tX[tJ]=null,t2=tX[--tJ],tX[tJ]=null,t1=tX[--tJ],tX[tJ]=null}var t3=null,t4=null,t8=!1,t6=null;function Ag(a,u){var i=Bg(5,null,null,0);i.elementType="DELETED",i.stateNode=u,i.return=a,null===(u=a.deletions)?(a.deletions=[i],a.flags|=16):u.push(i)}function Cg(a,u){switch(a.tag){case 5:var i=a.type;return null!==(u=1!==u.nodeType||i.toLowerCase()!==u.nodeName.toLowerCase()?null:u)&&(a.stateNode=u,t3=a,t4=Lf(u.firstChild),!0);case 6:return null!==(u=""===a.pendingProps||3!==u.nodeType?null:u)&&(a.stateNode=u,t3=a,t4=null,!0);case 13:return null!==(u=8!==u.nodeType?null:u)&&(i=null!==t0?{id:t1,overflow:t2}:null,a.memoizedState={dehydrated:u,treeContext:i,retryLane:1073741824},(i=Bg(18,null,null,0)).stateNode=u,i.return=a,a.child=i,t3=a,t4=null,!0);default:return!1}}function Dg(a){return 0!=(1&a.mode)&&0==(128&a.flags)}function Eg(a){if(t8){var u=t4;if(u){var i=u;if(!Cg(a,u)){if(Dg(a))throw Error(p(418));u=Lf(i.nextSibling);var o=t3;u&&Cg(a,u)?Ag(o,i):(a.flags=-4097&a.flags|2,t8=!1,t3=a)}}else{if(Dg(a))throw Error(p(418));a.flags=-4097&a.flags|2,t8=!1,t3=a}}}function Fg(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;t3=a}function Gg(a){if(a!==t3)return!1;if(!t8)return Fg(a),t8=!0,!1;if((u=3!==a.tag)&&!(u=5!==a.tag)&&(u="head"!==(u=a.type)&&"body"!==u&&!Ef(a.type,a.memoizedProps)),u&&(u=t4)){if(Dg(a))throw Hg(),Error(p(418));for(;u;)Ag(a,u),u=Lf(u.nextSibling)}if(Fg(a),13===a.tag){if(!(a=null!==(a=a.memoizedState)?a.dehydrated:null))throw Error(p(317));e:{for(u=0,a=a.nextSibling;a;){if(8===a.nodeType){var u,i=a.data;if("/$"===i){if(0===u){t4=Lf(a.nextSibling);break e}u--}else"$"!==i&&"$!"!==i&&"$?"!==i||u++}a=a.nextSibling}t4=null}}else t4=t3?Lf(a.stateNode.nextSibling):null;return!0}function Hg(){for(var a=t4;a;)a=Lf(a.nextSibling)}function Ig(){t4=t3=null,t8=!1}function Jg(a){null===t6?t6=[a]:t6.push(a)}var t5=en.ReactCurrentBatchConfig;function Lg(a,u){if(a&&a.defaultProps)for(var i in u=eS({},u),a=a.defaultProps)void 0===u[i]&&(u[i]=a[i]);return u}var t9=Uf(null),t7=null,rn=null,rt=null;function Qg(){rt=rn=t7=null}function Rg(a){var u=t9.current;E(t9),a._currentValue=u}function Sg(a,u,i){for(;null!==a;){var o=a.alternate;if((a.childLanes&u)!==u?(a.childLanes|=u,null!==o&&(o.childLanes|=u)):null!==o&&(o.childLanes&u)!==u&&(o.childLanes|=u),a===i)break;a=a.return}}function Tg(a,u){t7=a,rt=rn=null,null!==(a=a.dependencies)&&null!==a.firstContext&&(0!=(a.lanes&u)&&(rF=!0),a.firstContext=null)}function Vg(a){var u=a._currentValue;if(rt!==a){if(a={context:a,memoizedValue:u,next:null},null===rn){if(null===t7)throw Error(p(308));rn=a,t7.dependencies={lanes:0,firstContext:a}}else rn=rn.next=a}return u}var rr=null;function Xg(a){null===rr?rr=[a]:rr.push(a)}function Yg(a,u,i,o){var s=u.interleaved;return null===s?(i.next=i,Xg(u)):(i.next=s.next,s.next=i),u.interleaved=i,Zg(a,o)}function Zg(a,u){a.lanes|=u;var i=a.alternate;for(null!==i&&(i.lanes|=u),i=a,a=a.return;null!==a;)a.childLanes|=u,null!==(i=a.alternate)&&(i.childLanes|=u),i=a,a=a.return;return 3===i.tag?i.stateNode:null}var ra=!1;function ah(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function bh(a,u){a=a.updateQueue,u.updateQueue===a&&(u.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function ch(a,u){return{eventTime:a,lane:u,tag:0,payload:null,callback:null,next:null}}function dh(a,u,i){var o=a.updateQueue;if(null===o)return null;if(o=o.shared,0!=(2&rq)){var s=o.pending;return null===s?u.next=u:(u.next=s.next,s.next=u),o.pending=u,Zg(a,i)}return null===(s=o.interleaved)?(u.next=u,Xg(o)):(u.next=s.next,s.next=u),o.interleaved=u,Zg(a,i)}function eh(a,u,i){if(null!==(u=u.updateQueue)&&(u=u.shared,0!=(4194240&i))){var o=u.lanes;o&=a.pendingLanes,i|=o,u.lanes=i,Cc(a,i)}}function fh(a,u){var i=a.updateQueue,o=a.alternate;if(null!==o&&i===(o=o.updateQueue)){var s=null,w=null;if(null!==(i=i.firstBaseUpdate)){do{var x={eventTime:i.eventTime,lane:i.lane,tag:i.tag,payload:i.payload,callback:i.callback,next:null};null===w?s=w=x:w=w.next=x,i=i.next}while(null!==i);null===w?s=w=u:w=w.next=u}else s=w=u;i={baseState:o.baseState,firstBaseUpdate:s,lastBaseUpdate:w,shared:o.shared,effects:o.effects},a.updateQueue=i;return}null===(a=i.lastBaseUpdate)?i.firstBaseUpdate=u:a.next=u,i.lastBaseUpdate=u}function gh(a,u,i,o){var s=a.updateQueue;ra=!1;var w=s.firstBaseUpdate,x=s.lastBaseUpdate,C=s.shared.pending;if(null!==C){s.shared.pending=null;var _=C,j=_.next;_.next=null,null===x?w=j:x.next=j,x=_;var z=a.alternate;null!==z&&(C=(z=z.updateQueue).lastBaseUpdate)!==x&&(null===C?z.firstBaseUpdate=j:C.next=j,z.lastBaseUpdate=_)}if(null!==w){var P=s.baseState;for(x=0,z=j=_=null,C=w;;){var U=C.lane,V=C.eventTime;if((o&U)===U){null!==z&&(z=z.next={eventTime:V,lane:0,tag:C.tag,payload:C.payload,callback:C.callback,next:null});e:{var B=a,$=C;switch(U=u,V=i,$.tag){case 1:if("function"==typeof(B=$.payload)){P=B.call(V,P,U);break e}P=B;break e;case 3:B.flags=-65537&B.flags|128;case 0:if(null==(U="function"==typeof(B=$.payload)?B.call(V,P,U):B))break e;P=eS({},P,U);break e;case 2:ra=!0}}null!==C.callback&&0!==C.lane&&(a.flags|=64,null===(U=s.effects)?s.effects=[C]:U.push(C))}else V={eventTime:V,lane:U,tag:C.tag,payload:C.payload,callback:C.callback,next:null},null===z?(j=z=V,_=P):z=z.next=V,x|=U;if(null===(C=C.next)){if(null===(C=s.shared.pending))break;C=(U=C).next,U.next=null,s.lastBaseUpdate=U,s.shared.pending=null}}if(null===z&&(_=P),s.baseState=_,s.firstBaseUpdate=j,s.lastBaseUpdate=z,null!==(u=s.shared.interleaved)){s=u;do x|=s.lane,s=s.next;while(s!==u)}else null===w&&(s.shared.lanes=0);r4|=x,a.lanes=x,a.memoizedState=P}}function ih(a,u,i){if(a=u.effects,u.effects=null,null!==a)for(u=0;u<a.length;u++){var o=a[u],s=o.callback;if(null!==s){if(o.callback=null,o=i,"function"!=typeof s)throw Error(p(191,s));s.call(o)}}}var ru=(new j.Component).refs;function kh(a,u,i,o){i=null==(i=i(o,u=a.memoizedState))?u:eS({},u,i),a.memoizedState=i,0===a.lanes&&(a.updateQueue.baseState=i)}var ro={isMounted:function(a){return!!(a=a._reactInternals)&&Vb(a)===a},enqueueSetState:function(a,u,i){a=a._reactInternals;var o=L(),s=lh(a),w=ch(o,s);w.payload=u,null!=i&&(w.callback=i),null!==(u=dh(a,w,s))&&(mh(u,a,s,o),eh(u,a,s))},enqueueReplaceState:function(a,u,i){a=a._reactInternals;var o=L(),s=lh(a),w=ch(o,s);w.tag=1,w.payload=u,null!=i&&(w.callback=i),null!==(u=dh(a,w,s))&&(mh(u,a,s,o),eh(u,a,s))},enqueueForceUpdate:function(a,u){a=a._reactInternals;var i=L(),o=lh(a),s=ch(i,o);s.tag=2,null!=u&&(s.callback=u),null!==(u=dh(a,s,o))&&(mh(u,a,o,i),eh(u,a,o))}};function oh(a,u,i,o,s,w,x){return"function"==typeof(a=a.stateNode).shouldComponentUpdate?a.shouldComponentUpdate(o,w,x):!u.prototype||!u.prototype.isPureReactComponent||!Ie(i,o)||!Ie(s,w)}function ph(a,u,i){var o=!1,s=tW,w=u.contextType;return"object"==typeof w&&null!==w?w=Vg(w):(s=Zf(u)?tB:tA.current,w=(o=null!=(o=u.contextTypes))?Yf(a,s):tW),u=new u(i,w),a.memoizedState=null!==u.state&&void 0!==u.state?u.state:null,u.updater=ro,a.stateNode=u,u._reactInternals=a,o&&((a=a.stateNode).__reactInternalMemoizedUnmaskedChildContext=s,a.__reactInternalMemoizedMaskedChildContext=w),u}function qh(a,u,i,o){a=u.state,"function"==typeof u.componentWillReceiveProps&&u.componentWillReceiveProps(i,o),"function"==typeof u.UNSAFE_componentWillReceiveProps&&u.UNSAFE_componentWillReceiveProps(i,o),u.state!==a&&ro.enqueueReplaceState(u,u.state,null)}function rh(a,u,i,o){var s=a.stateNode;s.props=i,s.state=a.memoizedState,s.refs=ru,ah(a);var w=u.contextType;"object"==typeof w&&null!==w?s.context=Vg(w):(w=Zf(u)?tB:tA.current,s.context=Yf(a,w)),s.state=a.memoizedState,"function"==typeof(w=u.getDerivedStateFromProps)&&(kh(a,u,w,i),s.state=a.memoizedState),"function"==typeof u.getDerivedStateFromProps||"function"==typeof s.getSnapshotBeforeUpdate||"function"!=typeof s.UNSAFE_componentWillMount&&"function"!=typeof s.componentWillMount||(u=s.state,"function"==typeof s.componentWillMount&&s.componentWillMount(),"function"==typeof s.UNSAFE_componentWillMount&&s.UNSAFE_componentWillMount(),u!==s.state&&ro.enqueueReplaceState(s,s.state,null),gh(a,i,s,o),s.state=a.memoizedState),"function"==typeof s.componentDidMount&&(a.flags|=4194308)}function sh(a,u,i){if(null!==(a=i.ref)&&"function"!=typeof a&&"object"!=typeof a){if(i._owner){if(i=i._owner){if(1!==i.tag)throw Error(p(309));var o=i.stateNode}if(!o)throw Error(p(147,a));var s=o,w=""+a;return null!==u&&null!==u.ref&&"function"==typeof u.ref&&u.ref._stringRef===w?u.ref:((u=function(a){var u=s.refs;u===ru&&(u=s.refs={}),null===a?delete u[w]:u[w]=a})._stringRef=w,u)}if("string"!=typeof a)throw Error(p(284));if(!i._owner)throw Error(p(290,a))}return a}function th(a,u){throw Error(p(31,"[object Object]"===(a=Object.prototype.toString.call(u))?"object with keys {"+Object.keys(u).join(", ")+"}":a))}function uh(a){return(0,a._init)(a._payload)}function vh(a){function b(u,i){if(a){var o=u.deletions;null===o?(u.deletions=[i],u.flags|=16):o.push(i)}}function c(u,i){if(!a)return null;for(;null!==i;)b(u,i),i=i.sibling;return null}function d(a,u){for(a=new Map;null!==u;)null!==u.key?a.set(u.key,u):a.set(u.index,u),u=u.sibling;return a}function e(a,u){return(a=wh(a,u)).index=0,a.sibling=null,a}function f(u,i,o){return(u.index=o,a)?null!==(o=u.alternate)?(o=o.index)<i?(u.flags|=2,i):o:(u.flags|=2,i):(u.flags|=1048576,i)}function g(u){return a&&null===u.alternate&&(u.flags|=2),u}function h(a,u,i,o){return null===u||6!==u.tag?(u=xh(i,a.mode,o)).return=a:(u=e(u,i)).return=a,u}function k(a,u,i,o){var s=i.type;return s===ea?m(a,u,i.props.children,o,i.key):(null!==u&&(u.elementType===s||"object"==typeof s&&null!==s&&s.$$typeof===ev&&uh(s)===u.type)?(o=e(u,i.props)).ref=sh(a,u,i):(o=yh(i.type,i.key,i.props,null,a.mode,o)).ref=sh(a,u,i),o.return=a,o)}function l(a,u,i,o){return null===u||4!==u.tag||u.stateNode.containerInfo!==i.containerInfo||u.stateNode.implementation!==i.implementation?(u=zh(i,a.mode,o)).return=a:(u=e(u,i.children||[])).return=a,u}function m(a,u,i,o,s){return null===u||7!==u.tag?(u=Ah(i,a.mode,o,s)).return=a:(u=e(u,i)).return=a,u}function q(a,u,i){if("string"==typeof u&&""!==u||"number"==typeof u)return(u=xh(""+u,a.mode,i)).return=a,u;if("object"==typeof u&&null!==u){switch(u.$$typeof){case et:return(i=yh(u.type,u.key,u.props,null,a.mode,i)).ref=sh(a,null,u),i.return=a,i;case er:return(u=zh(u,a.mode,i)).return=a,u;case ev:return q(a,(0,u._init)(u._payload),i)}if(ex(u)||Ka(u))return(u=Ah(u,a.mode,i,null)).return=a,u;th(a,u)}return null}function r(a,u,i,o){var s=null!==u?u.key:null;if("string"==typeof i&&""!==i||"number"==typeof i)return null!==s?null:h(a,u,""+i,o);if("object"==typeof i&&null!==i){switch(i.$$typeof){case et:return i.key===s?k(a,u,i,o):null;case er:return i.key===s?l(a,u,i,o):null;case ev:return r(a,u,(s=i._init)(i._payload),o)}if(ex(i)||Ka(i))return null!==s?null:m(a,u,i,o,null);th(a,i)}return null}function y(a,u,i,o,s){if("string"==typeof o&&""!==o||"number"==typeof o)return h(u,a=a.get(i)||null,""+o,s);if("object"==typeof o&&null!==o){switch(o.$$typeof){case et:return k(u,a=a.get(null===o.key?i:o.key)||null,o,s);case er:return l(u,a=a.get(null===o.key?i:o.key)||null,o,s);case ev:return y(a,u,i,(0,o._init)(o._payload),s)}if(ex(o)||Ka(o))return m(u,a=a.get(i)||null,o,s,null);th(u,o)}return null}function n(u,i,o,s){for(var w=null,x=null,C=i,_=i=0,j=null;null!==C&&_<o.length;_++){C.index>_?(j=C,C=null):j=C.sibling;var z=r(u,C,o[_],s);if(null===z){null===C&&(C=j);break}a&&C&&null===z.alternate&&b(u,C),i=f(z,i,_),null===x?w=z:x.sibling=z,x=z,C=j}if(_===o.length)return c(u,C),t8&&tg(u,_),w;if(null===C){for(;_<o.length;_++)null!==(C=q(u,o[_],s))&&(i=f(C,i,_),null===x?w=C:x.sibling=C,x=C);return t8&&tg(u,_),w}for(C=d(u,C);_<o.length;_++)null!==(j=y(C,u,_,o[_],s))&&(a&&null!==j.alternate&&C.delete(null===j.key?_:j.key),i=f(j,i,_),null===x?w=j:x.sibling=j,x=j);return a&&C.forEach(function(a){return b(u,a)}),t8&&tg(u,_),w}function t(u,i,o,s){var w=Ka(o);if("function"!=typeof w)throw Error(p(150));if(null==(o=w.call(o)))throw Error(p(151));for(var x=w=null,C=i,_=i=0,j=null,z=o.next();null!==C&&!z.done;_++,z=o.next()){C.index>_?(j=C,C=null):j=C.sibling;var P=r(u,C,z.value,s);if(null===P){null===C&&(C=j);break}a&&C&&null===P.alternate&&b(u,C),i=f(P,i,_),null===x?w=P:x.sibling=P,x=P,C=j}if(z.done)return c(u,C),t8&&tg(u,_),w;if(null===C){for(;!z.done;_++,z=o.next())null!==(z=q(u,z.value,s))&&(i=f(z,i,_),null===x?w=z:x.sibling=z,x=z);return t8&&tg(u,_),w}for(C=d(u,C);!z.done;_++,z=o.next())null!==(z=y(C,u,_,z.value,s))&&(a&&null!==z.alternate&&C.delete(null===z.key?_:z.key),i=f(z,i,_),null===x?w=z:x.sibling=z,x=z);return a&&C.forEach(function(a){return b(u,a)}),t8&&tg(u,_),w}function J(a,u,i,o){if("object"==typeof i&&null!==i&&i.type===ea&&null===i.key&&(i=i.props.children),"object"==typeof i&&null!==i){switch(i.$$typeof){case et:e:{for(var s=i.key,w=u;null!==w;){if(w.key===s){if((s=i.type)===ea){if(7===w.tag){c(a,w.sibling),(u=e(w,i.props.children)).return=a,a=u;break e}}else if(w.elementType===s||"object"==typeof s&&null!==s&&s.$$typeof===ev&&uh(s)===w.type){c(a,w.sibling),(u=e(w,i.props)).ref=sh(a,w,i),u.return=a,a=u;break e}c(a,w);break}b(a,w),w=w.sibling}i.type===ea?((u=Ah(i.props.children,a.mode,o,i.key)).return=a,a=u):((o=yh(i.type,i.key,i.props,null,a.mode,o)).ref=sh(a,u,i),o.return=a,a=o)}return g(a);case er:e:{for(w=i.key;null!==u;){if(u.key===w){if(4===u.tag&&u.stateNode.containerInfo===i.containerInfo&&u.stateNode.implementation===i.implementation){c(a,u.sibling),(u=e(u,i.children||[])).return=a,a=u;break e}c(a,u);break}b(a,u),u=u.sibling}(u=zh(i,a.mode,o)).return=a,a=u}return g(a);case ev:return J(a,u,(w=i._init)(i._payload),o)}if(ex(i))return n(a,u,i,o);if(Ka(i))return t(a,u,i,o);th(a,i)}return"string"==typeof i&&""!==i||"number"==typeof i?(i=""+i,null!==u&&6===u.tag?(c(a,u.sibling),(u=e(u,i)).return=a):(c(a,u),(u=xh(i,a.mode,o)).return=a),g(a=u)):c(a,u)}return J}var rs=vh(!0),rc=vh(!1),rf={},rp=Uf(rf),rg=Uf(rf),rm=Uf(rf);function Hh(a){if(a===rf)throw Error(p(174));return a}function Ih(a,u){switch(G(rm,u),G(rg,a),G(rp,rf),a=u.nodeType){case 9:case 11:u=(u=u.documentElement)?u.namespaceURI:lb(null,"");break;default:u=lb(u=(a=8===a?u.parentNode:u).namespaceURI||null,a=a.tagName)}E(rp),G(rp,u)}function Jh(){E(rp),E(rg),E(rm)}function Kh(a){Hh(rm.current);var u=Hh(rp.current),i=lb(u,a.type);u!==i&&(G(rg,a),G(rp,i))}function Lh(a){rg.current===a&&(E(rp),E(rg))}var rv=Uf(0);function Mh(a){for(var u=a;null!==u;){if(13===u.tag){var i=u.memoizedState;if(null!==i&&(null===(i=i.dehydrated)||"$?"===i.data||"$!"===i.data))return u}else if(19===u.tag&&void 0!==u.memoizedProps.revealOrder){if(0!=(128&u.flags))return u}else if(null!==u.child){u.child.return=u,u=u.child;continue}if(u===a)break;for(;null===u.sibling;){if(null===u.return||u.return===a)return null;u=u.return}u.sibling.return=u.return,u=u.sibling}return null}var ry=[];function Oh(){for(var a=0;a<ry.length;a++)ry[a]._workInProgressVersionPrimary=null;ry.length=0}var rk=en.ReactCurrentDispatcher,rw=en.ReactCurrentBatchConfig,rS=0,rE=null,rx=null,rC=null,r_=!1,rz=!1,rL=0,rN=0;function Q(){throw Error(p(321))}function Wh(a,u){if(null===u)return!1;for(var i=0;i<u.length&&i<a.length;i++)if(!n6(a[i],u[i]))return!1;return!0}function Xh(a,u,i,o,s,w){if(rS=w,rE=u,u.memoizedState=null,u.updateQueue=null,u.lanes=0,rk.current=null===a||null===a.memoizedState?rT:rD,a=i(o,s),rz){w=0;do{if(rz=!1,rL=0,25<=w)throw Error(p(301));w+=1,rC=rx=null,u.updateQueue=null,rk.current=rM,a=i(o,s)}while(rz)}if(rk.current=rP,u=null!==rx&&null!==rx.next,rS=0,rC=rx=rE=null,r_=!1,u)throw Error(p(300));return a}function bi(){var a=0!==rL;return rL=0,a}function ci(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===rC?rE.memoizedState=rC=a:rC=rC.next=a,rC}function di(){if(null===rx){var a=rE.alternate;a=null!==a?a.memoizedState:null}else a=rx.next;var u=null===rC?rE.memoizedState:rC.next;if(null!==u)rC=u,rx=a;else{if(null===a)throw Error(p(310));a={memoizedState:(rx=a).memoizedState,baseState:rx.baseState,baseQueue:rx.baseQueue,queue:rx.queue,next:null},null===rC?rE.memoizedState=rC=a:rC=rC.next=a}return rC}function ei(a,u){return"function"==typeof u?u(a):u}function fi(a){var u=di(),i=u.queue;if(null===i)throw Error(p(311));i.lastRenderedReducer=a;var o=rx,s=o.baseQueue,w=i.pending;if(null!==w){if(null!==s){var x=s.next;s.next=w.next,w.next=x}o.baseQueue=s=w,i.pending=null}if(null!==s){w=s.next,o=o.baseState;var C=x=null,_=null,j=w;do{var z=j.lane;if((rS&z)===z)null!==_&&(_=_.next={lane:0,action:j.action,hasEagerState:j.hasEagerState,eagerState:j.eagerState,next:null}),o=j.hasEagerState?j.eagerState:a(o,j.action);else{var P={lane:z,action:j.action,hasEagerState:j.hasEagerState,eagerState:j.eagerState,next:null};null===_?(C=_=P,x=o):_=_.next=P,rE.lanes|=z,r4|=z}j=j.next}while(null!==j&&j!==w);null===_?x=o:_.next=C,n6(o,u.memoizedState)||(rF=!0),u.memoizedState=o,u.baseState=x,u.baseQueue=_,i.lastRenderedState=o}if(null!==(a=i.interleaved)){s=a;do w=s.lane,rE.lanes|=w,r4|=w,s=s.next;while(s!==a)}else null===s&&(i.lanes=0);return[u.memoizedState,i.dispatch]}function gi(a){var u=di(),i=u.queue;if(null===i)throw Error(p(311));i.lastRenderedReducer=a;var o=i.dispatch,s=i.pending,w=u.memoizedState;if(null!==s){i.pending=null;var x=s=s.next;do w=a(w,x.action),x=x.next;while(x!==s);n6(w,u.memoizedState)||(rF=!0),u.memoizedState=w,null===u.baseQueue&&(u.baseState=w),i.lastRenderedState=w}return[w,o]}function hi(){}function ii(a,u){var i=rE,o=di(),s=u(),w=!n6(o.memoizedState,s);if(w&&(o.memoizedState=s,rF=!0),o=o.queue,ji(ki.bind(null,i,o,a),[a]),o.getSnapshot!==u||w||null!==rC&&1&rC.memoizedState.tag){if(i.flags|=2048,li(9,mi.bind(null,i,o,s,u),void 0,null),null===rZ)throw Error(p(349));0!=(30&rS)||ni(i,u,s)}return s}function ni(a,u,i){a.flags|=16384,a={getSnapshot:u,value:i},null===(u=rE.updateQueue)?(u={lastEffect:null,stores:null},rE.updateQueue=u,u.stores=[a]):null===(i=u.stores)?u.stores=[a]:i.push(a)}function mi(a,u,i,o){u.value=i,u.getSnapshot=o,oi(u)&&pi(a)}function ki(a,u,i){return i(function(){oi(u)&&pi(a)})}function oi(a){var u=a.getSnapshot;a=a.value;try{var i=u();return!n6(a,i)}catch(a){return!0}}function pi(a){var u=Zg(a,1);null!==u&&mh(u,a,1,-1)}function qi(a){var u=ci();return"function"==typeof a&&(a=a()),u.memoizedState=u.baseState=a,a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:ei,lastRenderedState:a},u.queue=a,a=a.dispatch=ri.bind(null,rE,a),[u.memoizedState,a]}function li(a,u,i,o){return a={tag:a,create:u,destroy:i,deps:o,next:null},null===(u=rE.updateQueue)?(u={lastEffect:null,stores:null},rE.updateQueue=u,u.lastEffect=a.next=a):null===(i=u.lastEffect)?u.lastEffect=a.next=a:(o=i.next,i.next=a,a.next=o,u.lastEffect=a),a}function si(){return di().memoizedState}function ti(a,u,i,o){var s=ci();rE.flags|=a,s.memoizedState=li(1|u,i,void 0,void 0===o?null:o)}function ui(a,u,i,o){var s=di();o=void 0===o?null:o;var w=void 0;if(null!==rx){var x=rx.memoizedState;if(w=x.destroy,null!==o&&Wh(o,x.deps)){s.memoizedState=li(u,i,w,o);return}}rE.flags|=a,s.memoizedState=li(1|u,i,w,o)}function vi(a,u){return ti(8390656,8,a,u)}function ji(a,u){return ui(2048,8,a,u)}function wi(a,u){return ui(4,2,a,u)}function xi(a,u){return ui(4,4,a,u)}function yi(a,u){return"function"==typeof u?(u(a=a()),function(){u(null)}):null!=u?(a=a(),u.current=a,function(){u.current=null}):void 0}function zi(a,u,i){return i=null!=i?i.concat([a]):null,ui(4,4,yi.bind(null,u,a),i)}function Ai(){}function Bi(a,u){var i=di();u=void 0===u?null:u;var o=i.memoizedState;return null!==o&&null!==u&&Wh(u,o[1])?o[0]:(i.memoizedState=[a,u],a)}function Ci(a,u){var i=di();u=void 0===u?null:u;var o=i.memoizedState;return null!==o&&null!==u&&Wh(u,o[1])?o[0]:(a=a(),i.memoizedState=[a,u],a)}function Di(a,u,i){return 0==(21&rS)?(a.baseState&&(a.baseState=!1,rF=!0),a.memoizedState=i):(n6(i,u)||(i=yc(),rE.lanes|=i,r4|=i,a.baseState=!0),u)}function Ei(a,u){var i=e9;e9=0!==i&&4>i?i:4,a(!0);var o=rw.transition;rw.transition={};try{a(!1),u()}finally{e9=i,rw.transition=o}}function Fi(){return di().memoizedState}function Gi(a,u,i){var o=lh(a);i={lane:o,action:i,hasEagerState:!1,eagerState:null,next:null},Hi(a)?Ii(u,i):null!==(i=Yg(a,u,i,o))&&(mh(i,a,o,L()),Ji(i,u,o))}function ri(a,u,i){var o=lh(a),s={lane:o,action:i,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(u,s);else{var w=a.alternate;if(0===a.lanes&&(null===w||0===w.lanes)&&null!==(w=u.lastRenderedReducer))try{var x=u.lastRenderedState,C=w(x,i);if(s.hasEagerState=!0,s.eagerState=C,n6(C,x)){var _=u.interleaved;null===_?(s.next=s,Xg(u)):(s.next=_.next,_.next=s),u.interleaved=s;return}}catch(a){}finally{}null!==(i=Yg(a,u,s,o))&&(mh(i,a,o,s=L()),Ji(i,u,o))}}function Hi(a){var u=a.alternate;return a===rE||null!==u&&u===rE}function Ii(a,u){rz=r_=!0;var i=a.pending;null===i?u.next=u:(u.next=i.next,i.next=u),a.pending=u}function Ji(a,u,i){if(0!=(4194240&i)){var o=u.lanes;o&=a.pendingLanes,i|=o,u.lanes=i,Cc(a,i)}}var rP={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},rT={readContext:Vg,useCallback:function(a,u){return ci().memoizedState=[a,void 0===u?null:u],a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,u,i){return i=null!=i?i.concat([a]):null,ti(4194308,4,yi.bind(null,u,a),i)},useLayoutEffect:function(a,u){return ti(4194308,4,a,u)},useInsertionEffect:function(a,u){return ti(4,2,a,u)},useMemo:function(a,u){var i=ci();return u=void 0===u?null:u,a=a(),i.memoizedState=[a,u],a},useReducer:function(a,u,i){var o=ci();return u=void 0!==i?i(u):u,o.memoizedState=o.baseState=u,a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:u},o.queue=a,a=a.dispatch=Gi.bind(null,rE,a),[o.memoizedState,a]},useRef:function(a){return a={current:a},ci().memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),u=a[0];return a=Ei.bind(null,a[1]),ci().memoizedState=a,[u,a]},useMutableSource:function(){},useSyncExternalStore:function(a,u,i){var o=rE,s=ci();if(t8){if(void 0===i)throw Error(p(407));i=i()}else{if(i=u(),null===rZ)throw Error(p(349));0!=(30&rS)||ni(o,u,i)}s.memoizedState=i;var w={value:i,getSnapshot:u};return s.queue=w,vi(ki.bind(null,o,w,a),[a]),o.flags|=2048,li(9,mi.bind(null,o,w,i,u),void 0,null),i},useId:function(){var a=ci(),u=rZ.identifierPrefix;if(t8){var i=t2,o=t1;u=":"+u+"R"+(i=(o&~(1<<32-e3(o)-1)).toString(32)+i),0<(i=rL++)&&(u+="H"+i.toString(32)),u+=":"}else u=":"+u+"r"+(i=rN++).toString(32)+":";return a.memoizedState=u},unstable_isNewReconciler:!1},rD={readContext:Vg,useCallback:Bi,useContext:Vg,useEffect:ji,useImperativeHandle:zi,useInsertionEffect:wi,useLayoutEffect:xi,useMemo:Ci,useReducer:fi,useRef:si,useState:function(){return fi(ei)},useDebugValue:Ai,useDeferredValue:function(a){return Di(di(),rx.memoizedState,a)},useTransition:function(){return[fi(ei)[0],di().memoizedState]},useMutableSource:hi,useSyncExternalStore:ii,useId:Fi,unstable_isNewReconciler:!1},rM={readContext:Vg,useCallback:Bi,useContext:Vg,useEffect:ji,useImperativeHandle:zi,useInsertionEffect:wi,useLayoutEffect:xi,useMemo:Ci,useReducer:gi,useRef:si,useState:function(){return gi(ei)},useDebugValue:Ai,useDeferredValue:function(a){var u=di();return null===rx?u.memoizedState=a:Di(u,rx.memoizedState,a)},useTransition:function(){return[gi(ei)[0],di().memoizedState]},useMutableSource:hi,useSyncExternalStore:ii,useId:Fi,unstable_isNewReconciler:!1};function Ki(a,u){try{var i="",o=u;do i+=Pa(o),o=o.return;while(o);var s=i}catch(a){s="\nError generating stack: "+a.message+"\n"+a.stack}return{value:a,source:u,stack:s,digest:null}}function Li(a,u,i){return{value:a,source:null,stack:null!=i?i:null,digest:null!=u?u:null}}function Mi(a,u){try{console.error(u.value)}catch(a){setTimeout(function(){throw a})}}var rR="function"==typeof WeakMap?WeakMap:Map;function Oi(a,u,i){(i=ch(-1,i)).tag=3,i.payload={element:null};var o=u.value;return i.callback=function(){lt||(lt=!0,lr=o),Mi(a,u)},i}function Ri(a,u,i){(i=ch(-1,i)).tag=3;var o=a.type.getDerivedStateFromError;if("function"==typeof o){var s=u.value;i.payload=function(){return o(s)},i.callback=function(){Mi(a,u)}}var w=a.stateNode;return null!==w&&"function"==typeof w.componentDidCatch&&(i.callback=function(){Mi(a,u),"function"!=typeof o&&(null===ll?ll=new Set([this]):ll.add(this));var i=u.stack;this.componentDidCatch(u.value,{componentStack:null!==i?i:""})}),i}function Ti(a,u,i){var o=a.pingCache;if(null===o){o=a.pingCache=new rR;var s=new Set;o.set(u,s)}else void 0===(s=o.get(u))&&(s=new Set,o.set(u,s));s.has(i)||(s.add(i),a=Ui.bind(null,a,u,i),u.then(a,a))}function Vi(a){do{var u;if((u=13===a.tag)&&(u=null===(u=a.memoizedState)||null!==u.dehydrated),u)return a;a=a.return}while(null!==a);return null}function Wi(a,u,i,o,s){return 0==(1&a.mode)?a===u?a.flags|=65536:(a.flags|=128,i.flags|=131072,i.flags&=-52805,1===i.tag&&(null===i.alternate?i.tag=17:((u=ch(-1,1)).tag=2,dh(i,u,1))),i.lanes|=1):(a.flags|=65536,a.lanes=s),a}var rI=en.ReactCurrentOwner,rF=!1;function Yi(a,u,i,o){u.child=null===a?rc(u,null,i,o):rs(u,a.child,i,o)}function Zi(a,u,i,o,s){i=i.render;var w=u.ref;return(Tg(u,s),o=Xh(a,u,i,o,w,s),i=bi(),null===a||rF)?(t8&&i&&vg(u),u.flags|=1,Yi(a,u,o,s),u.child):(u.updateQueue=a.updateQueue,u.flags&=-2053,a.lanes&=~s,$i(a,u,s))}function aj(a,u,i,o,s){if(null===a){var w=i.type;return"function"!=typeof w||bj(w)||void 0!==w.defaultProps||null!==i.compare||void 0!==i.defaultProps?((a=yh(i.type,null,o,u,u.mode,s)).ref=u.ref,a.return=u,u.child=a):(u.tag=15,u.type=w,cj(a,u,w,o,s))}if(w=a.child,0==(a.lanes&s)){var x=w.memoizedProps;if((i=null!==(i=i.compare)?i:Ie)(x,o)&&a.ref===u.ref)return $i(a,u,s)}return u.flags|=1,(a=wh(w,o)).ref=u.ref,a.return=u,u.child=a}function cj(a,u,i,o,s){if(null!==a){var w=a.memoizedProps;if(Ie(w,o)&&a.ref===u.ref){if(rF=!1,u.pendingProps=o=w,0==(a.lanes&s))return u.lanes=a.lanes,$i(a,u,s);0!=(131072&a.flags)&&(rF=!0)}}return dj(a,u,i,o,s)}function ej(a,u,i){var o=u.pendingProps,s=o.children,w=null!==a?a.memoizedState:null;if("hidden"===o.mode){if(0==(1&u.mode))u.memoizedState={baseLanes:0,cachePool:null,transitions:null},G(r1,r0),r0|=i;else{if(0==(1073741824&i))return a=null!==w?w.baseLanes|i:i,u.lanes=u.childLanes=1073741824,u.memoizedState={baseLanes:a,cachePool:null,transitions:null},u.updateQueue=null,G(r1,r0),r0|=a,null;u.memoizedState={baseLanes:0,cachePool:null,transitions:null},o=null!==w?w.baseLanes:i,G(r1,r0),r0|=o}}else null!==w?(o=w.baseLanes|i,u.memoizedState=null):o=i,G(r1,r0),r0|=o;return Yi(a,u,s,i),u.child}function hj(a,u){var i=u.ref;(null===a&&null!==i||null!==a&&a.ref!==i)&&(u.flags|=512,u.flags|=2097152)}function dj(a,u,i,o,s){var w=Zf(i)?tB:tA.current;return(w=Yf(u,w),Tg(u,s),i=Xh(a,u,i,o,w,s),o=bi(),null===a||rF)?(t8&&o&&vg(u),u.flags|=1,Yi(a,u,i,s),u.child):(u.updateQueue=a.updateQueue,u.flags&=-2053,a.lanes&=~s,$i(a,u,s))}function ij(a,u,i,o,s){if(Zf(i)){var w=!0;cg(u)}else w=!1;if(Tg(u,s),null===u.stateNode)jj(a,u),ph(u,i,o),rh(u,i,o,s),o=!0;else if(null===a){var x=u.stateNode,C=u.memoizedProps;x.props=C;var _=x.context,j=i.contextType;j="object"==typeof j&&null!==j?Vg(j):Yf(u,j=Zf(i)?tB:tA.current);var z=i.getDerivedStateFromProps,P="function"==typeof z||"function"==typeof x.getSnapshotBeforeUpdate;P||"function"!=typeof x.UNSAFE_componentWillReceiveProps&&"function"!=typeof x.componentWillReceiveProps||(C!==o||_!==j)&&qh(u,x,o,j),ra=!1;var U=u.memoizedState;x.state=U,gh(u,o,x,s),_=u.memoizedState,C!==o||U!==_||tQ.current||ra?("function"==typeof z&&(kh(u,i,z,o),_=u.memoizedState),(C=ra||oh(u,i,C,o,U,_,j))?(P||"function"!=typeof x.UNSAFE_componentWillMount&&"function"!=typeof x.componentWillMount||("function"==typeof x.componentWillMount&&x.componentWillMount(),"function"==typeof x.UNSAFE_componentWillMount&&x.UNSAFE_componentWillMount()),"function"==typeof x.componentDidMount&&(u.flags|=4194308)):("function"==typeof x.componentDidMount&&(u.flags|=4194308),u.memoizedProps=o,u.memoizedState=_),x.props=o,x.state=_,x.context=j,o=C):("function"==typeof x.componentDidMount&&(u.flags|=4194308),o=!1)}else{x=u.stateNode,bh(a,u),C=u.memoizedProps,j=u.type===u.elementType?C:Lg(u.type,C),x.props=j,P=u.pendingProps,U=x.context,_="object"==typeof(_=i.contextType)&&null!==_?Vg(_):Yf(u,_=Zf(i)?tB:tA.current);var V=i.getDerivedStateFromProps;(z="function"==typeof V||"function"==typeof x.getSnapshotBeforeUpdate)||"function"!=typeof x.UNSAFE_componentWillReceiveProps&&"function"!=typeof x.componentWillReceiveProps||(C!==P||U!==_)&&qh(u,x,o,_),ra=!1,U=u.memoizedState,x.state=U,gh(u,o,x,s);var B=u.memoizedState;C!==P||U!==B||tQ.current||ra?("function"==typeof V&&(kh(u,i,V,o),B=u.memoizedState),(j=ra||oh(u,i,j,o,U,B,_)||!1)?(z||"function"!=typeof x.UNSAFE_componentWillUpdate&&"function"!=typeof x.componentWillUpdate||("function"==typeof x.componentWillUpdate&&x.componentWillUpdate(o,B,_),"function"==typeof x.UNSAFE_componentWillUpdate&&x.UNSAFE_componentWillUpdate(o,B,_)),"function"==typeof x.componentDidUpdate&&(u.flags|=4),"function"==typeof x.getSnapshotBeforeUpdate&&(u.flags|=1024)):("function"!=typeof x.componentDidUpdate||C===a.memoizedProps&&U===a.memoizedState||(u.flags|=4),"function"!=typeof x.getSnapshotBeforeUpdate||C===a.memoizedProps&&U===a.memoizedState||(u.flags|=1024),u.memoizedProps=o,u.memoizedState=B),x.props=o,x.state=B,x.context=_,o=j):("function"!=typeof x.componentDidUpdate||C===a.memoizedProps&&U===a.memoizedState||(u.flags|=4),"function"!=typeof x.getSnapshotBeforeUpdate||C===a.memoizedProps&&U===a.memoizedState||(u.flags|=1024),o=!1)}return kj(a,u,i,o,w,s)}function kj(a,u,i,o,s,w){hj(a,u);var x=0!=(128&u.flags);if(!o&&!x)return s&&dg(u,i,!1),$i(a,u,w);o=u.stateNode,rI.current=u;var C=x&&"function"!=typeof i.getDerivedStateFromError?null:o.render();return u.flags|=1,null!==a&&x?(u.child=rs(u,a.child,null,w),u.child=rs(u,null,C,w)):Yi(a,u,C,w),u.memoizedState=o.state,s&&dg(u,i,!0),u.child}function lj(a){var u=a.stateNode;u.pendingContext?ag(a,u.pendingContext,u.pendingContext!==u.context):u.context&&ag(a,u.context,!1),Ih(a,u.containerInfo)}function mj(a,u,i,o,s){return Ig(),Jg(s),u.flags|=256,Yi(a,u,i,o),u.child}var rO={dehydrated:null,treeContext:null,retryLane:0};function oj(a){return{baseLanes:a,cachePool:null,transitions:null}}function pj(a,u,i){var o,s=u.pendingProps,w=rv.current,x=!1,C=0!=(128&u.flags);if((o=C)||(o=(null===a||null!==a.memoizedState)&&0!=(2&w)),o?(x=!0,u.flags&=-129):(null===a||null!==a.memoizedState)&&(w|=1),G(rv,1&w),null===a)return(Eg(u),null!==(a=u.memoizedState)&&null!==(a=a.dehydrated))?(0==(1&u.mode)?u.lanes=1:"$!"===a.data?u.lanes=8:u.lanes=1073741824,null):(C=s.children,a=s.fallback,x?(s=u.mode,x=u.child,C={mode:"hidden",children:C},0==(1&s)&&null!==x?(x.childLanes=0,x.pendingProps=C):x=qj(C,s,0,null),a=Ah(a,s,i,null),x.return=u,a.return=u,x.sibling=a,u.child=x,u.child.memoizedState=oj(i),u.memoizedState=rO,a):rj(u,C));if(null!==(w=a.memoizedState)&&null!==(o=w.dehydrated))return sj(a,u,C,s,o,w,i);if(x){x=s.fallback,C=u.mode,o=(w=a.child).sibling;var _={mode:"hidden",children:s.children};return 0==(1&C)&&u.child!==w?((s=u.child).childLanes=0,s.pendingProps=_,u.deletions=null):(s=wh(w,_)).subtreeFlags=14680064&w.subtreeFlags,null!==o?x=wh(o,x):(x=Ah(x,C,i,null),x.flags|=2),x.return=u,s.return=u,s.sibling=x,u.child=s,s=x,x=u.child,C=null===(C=a.child.memoizedState)?oj(i):{baseLanes:C.baseLanes|i,cachePool:null,transitions:C.transitions},x.memoizedState=C,x.childLanes=a.childLanes&~i,u.memoizedState=rO,s}return a=(x=a.child).sibling,s=wh(x,{mode:"visible",children:s.children}),0==(1&u.mode)&&(s.lanes=i),s.return=u,s.sibling=null,null!==a&&(null===(i=u.deletions)?(u.deletions=[a],u.flags|=16):i.push(a)),u.child=s,u.memoizedState=null,s}function rj(a,u){return(u=qj({mode:"visible",children:u},a.mode,0,null)).return=a,a.child=u}function tj(a,u,i,o){return null!==o&&Jg(o),rs(u,a.child,null,i),a=rj(u,u.pendingProps.children),a.flags|=2,u.memoizedState=null,a}function sj(a,u,i,o,s,w,x){if(i)return 256&u.flags?(u.flags&=-257,tj(a,u,x,o=Li(Error(p(422))))):null!==u.memoizedState?(u.child=a.child,u.flags|=128,null):(w=o.fallback,s=u.mode,o=qj({mode:"visible",children:o.children},s,0,null),w=Ah(w,s,x,null),w.flags|=2,o.return=u,w.return=u,o.sibling=w,u.child=o,0!=(1&u.mode)&&rs(u,a.child,null,x),u.child.memoizedState=oj(x),u.memoizedState=rO,w);if(0==(1&u.mode))return tj(a,u,x,null);if("$!"===s.data){if(o=s.nextSibling&&s.nextSibling.dataset)var C=o.dgst;return o=C,tj(a,u,x,o=Li(w=Error(p(419)),o,void 0))}if(C=0!=(x&a.childLanes),rF||C){if(null!==(o=rZ)){switch(x&-x){case 4:s=2;break;case 16:s=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:s=32;break;case 536870912:s=268435456;break;default:s=0}0!==(s=0!=(s&(o.suspendedLanes|x))?0:s)&&s!==w.retryLane&&(w.retryLane=s,Zg(a,s),mh(o,a,s,-1))}return uj(),tj(a,u,x,o=Li(Error(p(421))))}return"$?"===s.data?(u.flags|=128,u.child=a.child,u=vj.bind(null,a),s._reactRetry=u,null):(a=w.treeContext,t4=Lf(s.nextSibling),t3=u,t8=!0,t6=null,null!==a&&(tX[tJ++]=t1,tX[tJ++]=t2,tX[tJ++]=t0,t1=a.id,t2=a.overflow,t0=u),u=rj(u,o.children),u.flags|=4096,u)}function wj(a,u,i){a.lanes|=u;var o=a.alternate;null!==o&&(o.lanes|=u),Sg(a.return,u,i)}function xj(a,u,i,o,s){var w=a.memoizedState;null===w?a.memoizedState={isBackwards:u,rendering:null,renderingStartTime:0,last:o,tail:i,tailMode:s}:(w.isBackwards=u,w.rendering=null,w.renderingStartTime=0,w.last=o,w.tail=i,w.tailMode=s)}function yj(a,u,i){var o=u.pendingProps,s=o.revealOrder,w=o.tail;if(Yi(a,u,o.children,i),0!=(2&(o=rv.current)))o=1&o|2,u.flags|=128;else{if(null!==a&&0!=(128&a.flags))e:for(a=u.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&wj(a,i,u);else if(19===a.tag)wj(a,i,u);else if(null!==a.child){a.child.return=a,a=a.child;continue}if(a===u)break;for(;null===a.sibling;){if(null===a.return||a.return===u)break e;a=a.return}a.sibling.return=a.return,a=a.sibling}o&=1}if(G(rv,o),0==(1&u.mode))u.memoizedState=null;else switch(s){case"forwards":for(s=null,i=u.child;null!==i;)null!==(a=i.alternate)&&null===Mh(a)&&(s=i),i=i.sibling;null===(i=s)?(s=u.child,u.child=null):(s=i.sibling,i.sibling=null),xj(u,!1,s,i,w);break;case"backwards":for(i=null,s=u.child,u.child=null;null!==s;){if(null!==(a=s.alternate)&&null===Mh(a)){u.child=s;break}a=s.sibling,s.sibling=i,i=s,s=a}xj(u,!0,i,null,w);break;case"together":xj(u,!1,null,null,void 0);break;default:u.memoizedState=null}return u.child}function jj(a,u){0==(1&u.mode)&&null!==a&&(a.alternate=null,u.alternate=null,u.flags|=2)}function $i(a,u,i){if(null!==a&&(u.dependencies=a.dependencies),r4|=u.lanes,0==(i&u.childLanes))return null;if(null!==a&&u.child!==a.child)throw Error(p(153));if(null!==u.child){for(i=wh(a=u.child,a.pendingProps),u.child=i,i.return=u;null!==a.sibling;)a=a.sibling,(i=i.sibling=wh(a,a.pendingProps)).return=u;i.sibling=null}return u.child}function zj(a,u,i){switch(u.tag){case 3:lj(u),Ig();break;case 5:Kh(u);break;case 1:Zf(u.type)&&cg(u);break;case 4:Ih(u,u.stateNode.containerInfo);break;case 10:var o=u.type._context,s=u.memoizedProps.value;G(t9,o._currentValue),o._currentValue=s;break;case 13:if(null!==(o=u.memoizedState)){if(null!==o.dehydrated)return G(rv,1&rv.current),u.flags|=128,null;if(0!=(i&u.child.childLanes))return pj(a,u,i);return G(rv,1&rv.current),null!==(a=$i(a,u,i))?a.sibling:null}G(rv,1&rv.current);break;case 19:if(o=0!=(i&u.childLanes),0!=(128&a.flags)){if(o)return yj(a,u,i);u.flags|=128}if(null!==(s=u.memoizedState)&&(s.rendering=null,s.tail=null,s.lastEffect=null),G(rv,rv.current),!o)return null;break;case 22:case 23:return u.lanes=0,ej(a,u,i)}return $i(a,u,i)}function Ej(a,u){if(!t8)switch(a.tailMode){case"hidden":u=a.tail;for(var i=null;null!==u;)null!==u.alternate&&(i=u),u=u.sibling;null===i?a.tail=null:i.sibling=null;break;case"collapsed":i=a.tail;for(var o=null;null!==i;)null!==i.alternate&&(o=i),i=i.sibling;null===o?u||null===a.tail?a.tail=null:a.tail.sibling=null:o.sibling=null}}function S(a){var u=null!==a.alternate&&a.alternate.child===a.child,i=0,o=0;if(u)for(var s=a.child;null!==s;)i|=s.lanes|s.childLanes,o|=14680064&s.subtreeFlags,o|=14680064&s.flags,s.return=a,s=s.sibling;else for(s=a.child;null!==s;)i|=s.lanes|s.childLanes,o|=s.subtreeFlags,o|=s.flags,s.return=a,s=s.sibling;return a.subtreeFlags|=o,a.childLanes=i,u}function Fj(a,u,i){var o=u.pendingProps;switch(wg(u),u.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return S(u),null;case 1:case 17:return Zf(u.type)&&$f(),S(u),null;case 3:return o=u.stateNode,Jh(),E(tQ),E(tA),Oh(),o.pendingContext&&(o.context=o.pendingContext,o.pendingContext=null),(null===a||null===a.child)&&(Gg(u)?u.flags|=4:null===a||a.memoizedState.isDehydrated&&0==(256&u.flags)||(u.flags|=1024,null!==t6&&(Gj(t6),t6=null))),w(a,u),S(u),null;case 5:Lh(u);var _=Hh(rm.current);if(i=u.type,null!==a&&null!=u.stateNode)x(a,u,i,o,_),a.ref!==u.ref&&(u.flags|=512,u.flags|=2097152);else{if(!o){if(null===u.stateNode)throw Error(p(166));return S(u),null}if(a=Hh(rp.current),Gg(u)){o=u.stateNode,i=u.type;var j=u.memoizedProps;switch(o[tD]=u,o[tM]=j,a=0!=(1&u.mode),i){case"dialog":D("cancel",o),D("close",o);break;case"iframe":case"object":case"embed":D("load",o);break;case"video":case"audio":for(_=0;_<tk.length;_++)D(tk[_],o);break;case"source":D("error",o);break;case"img":case"image":case"link":D("error",o),D("load",o);break;case"details":D("toggle",o);break;case"input":Za(o,j),D("invalid",o);break;case"select":o._wrapperState={wasMultiple:!!j.multiple},D("invalid",o);break;case"textarea":hb(o,j),D("invalid",o)}for(var z in ub(i,j),_=null,j)if(j.hasOwnProperty(z)){var P=j[z];"children"===z?"string"==typeof P?o.textContent!==P&&(!0!==j.suppressHydrationWarning&&Af(o.textContent,P,a),_=["children",P]):"number"==typeof P&&o.textContent!==""+P&&(!0!==j.suppressHydrationWarning&&Af(o.textContent,P,a),_=["children",""+P]):U.hasOwnProperty(z)&&null!=P&&"onScroll"===z&&D("scroll",o)}switch(i){case"input":Va(o),db(o,j,!0);break;case"textarea":Va(o),jb(o);break;case"select":case"option":break;default:"function"==typeof j.onClick&&(o.onclick=Bf)}o=_,u.updateQueue=o,null!==o&&(u.flags|=4)}else{z=9===_.nodeType?_:_.ownerDocument,"http://www.w3.org/1999/xhtml"===a&&(a=kb(i)),"http://www.w3.org/1999/xhtml"===a?"script"===i?((a=z.createElement("div")).innerHTML="<script></script>",a=a.removeChild(a.firstChild)):"string"==typeof o.is?a=z.createElement(i,{is:o.is}):(a=z.createElement(i),"select"===i&&(z=a,o.multiple?z.multiple=!0:o.size&&(z.size=o.size))):a=z.createElementNS(a,i),a[tD]=u,a[tM]=o,s(a,u,!1,!1),u.stateNode=a;e:{switch(z=vb(i,o),i){case"dialog":D("cancel",a),D("close",a),_=o;break;case"iframe":case"object":case"embed":D("load",a),_=o;break;case"video":case"audio":for(_=0;_<tk.length;_++)D(tk[_],a);_=o;break;case"source":D("error",a),_=o;break;case"img":case"image":case"link":D("error",a),D("load",a),_=o;break;case"details":D("toggle",a),_=o;break;case"input":Za(a,o),_=Ya(a,o),D("invalid",a);break;case"option":default:_=o;break;case"select":a._wrapperState={wasMultiple:!!o.multiple},_=eS({},o,{value:void 0}),D("invalid",a);break;case"textarea":hb(a,o),_=gb(a,o),D("invalid",a)}for(j in ub(i,_),P=_)if(P.hasOwnProperty(j)){var V=P[j];"style"===j?sb(a,V):"dangerouslySetInnerHTML"===j?null!=(V=V?V.__html:void 0)&&ez(a,V):"children"===j?"string"==typeof V?("textarea"!==i||""!==V)&&ob(a,V):"number"==typeof V&&ob(a,""+V):"suppressContentEditableWarning"!==j&&"suppressHydrationWarning"!==j&&"autoFocus"!==j&&(U.hasOwnProperty(j)?null!=V&&"onScroll"===j&&D("scroll",a):null!=V&&ta(a,j,V,z))}switch(i){case"input":Va(a),db(a,o,!1);break;case"textarea":Va(a),jb(a);break;case"option":null!=o.value&&a.setAttribute("value",""+Sa(o.value));break;case"select":a.multiple=!!o.multiple,null!=(j=o.value)?fb(a,!!o.multiple,j,!1):null!=o.defaultValue&&fb(a,!!o.multiple,o.defaultValue,!0);break;default:"function"==typeof _.onClick&&(a.onclick=Bf)}switch(i){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}}o&&(u.flags|=4)}null!==u.ref&&(u.flags|=512,u.flags|=2097152)}return S(u),null;case 6:if(a&&null!=u.stateNode)C(a,u,a.memoizedProps,o);else{if("string"!=typeof o&&null===u.stateNode)throw Error(p(166));if(i=Hh(rm.current),Hh(rp.current),Gg(u)){if(o=u.stateNode,i=u.memoizedProps,o[tD]=u,(j=o.nodeValue!==i)&&null!==(a=t3))switch(a.tag){case 3:Af(o.nodeValue,i,0!=(1&a.mode));break;case 5:!0!==a.memoizedProps.suppressHydrationWarning&&Af(o.nodeValue,i,0!=(1&a.mode))}j&&(u.flags|=4)}else(o=(9===i.nodeType?i:i.ownerDocument).createTextNode(o))[tD]=u,u.stateNode=o}return S(u),null;case 13:if(E(rv),o=u.memoizedState,null===a||null!==a.memoizedState&&null!==a.memoizedState.dehydrated){if(t8&&null!==t4&&0!=(1&u.mode)&&0==(128&u.flags))Hg(),Ig(),u.flags|=98560,j=!1;else if(j=Gg(u),null!==o&&null!==o.dehydrated){if(null===a){if(!j)throw Error(p(318));if(!(j=null!==(j=u.memoizedState)?j.dehydrated:null))throw Error(p(317));j[tD]=u}else Ig(),0==(128&u.flags)&&(u.memoizedState=null),u.flags|=4;S(u),j=!1}else null!==t6&&(Gj(t6),t6=null),j=!0;if(!j)return 65536&u.flags?u:null}if(0!=(128&u.flags))return u.lanes=i,u;return(o=null!==o)!=(null!==a&&null!==a.memoizedState)&&o&&(u.child.flags|=8192,0!=(1&u.mode)&&(null===a||0!=(1&rv.current)?0===r2&&(r2=3):uj())),null!==u.updateQueue&&(u.flags|=4),S(u),null;case 4:return Jh(),w(a,u),null===a&&sf(u.stateNode.containerInfo),S(u),null;case 10:return Rg(u.type._context),S(u),null;case 19:if(E(rv),null===(j=u.memoizedState))return S(u),null;if(o=0!=(128&u.flags),null===(z=j.rendering)){if(o)Ej(j,!1);else{if(0!==r2||null!==a&&0!=(128&a.flags))for(a=u.child;null!==a;){if(null!==(z=Mh(a))){for(u.flags|=128,Ej(j,!1),null!==(o=z.updateQueue)&&(u.updateQueue=o,u.flags|=4),u.subtreeFlags=0,o=i,i=u.child;null!==i;)j=i,a=o,j.flags&=14680066,null===(z=j.alternate)?(j.childLanes=0,j.lanes=a,j.child=null,j.subtreeFlags=0,j.memoizedProps=null,j.memoizedState=null,j.updateQueue=null,j.dependencies=null,j.stateNode=null):(j.childLanes=z.childLanes,j.lanes=z.lanes,j.child=z.child,j.subtreeFlags=0,j.deletions=null,j.memoizedProps=z.memoizedProps,j.memoizedState=z.memoizedState,j.updateQueue=z.updateQueue,j.type=z.type,a=z.dependencies,j.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext}),i=i.sibling;return G(rv,1&rv.current|2),u.child}a=a.sibling}null!==j.tail&&eG()>le&&(u.flags|=128,o=!0,Ej(j,!1),u.lanes=4194304)}}else{if(!o){if(null!==(a=Mh(z))){if(u.flags|=128,o=!0,null!==(i=a.updateQueue)&&(u.updateQueue=i,u.flags|=4),Ej(j,!0),null===j.tail&&"hidden"===j.tailMode&&!z.alternate&&!t8)return S(u),null}else 2*eG()-j.renderingStartTime>le&&1073741824!==i&&(u.flags|=128,o=!0,Ej(j,!1),u.lanes=4194304)}j.isBackwards?(z.sibling=u.child,u.child=z):(null!==(i=j.last)?i.sibling=z:u.child=z,j.last=z)}if(null!==j.tail)return u=j.tail,j.rendering=u,j.tail=u.sibling,j.renderingStartTime=eG(),u.sibling=null,i=rv.current,G(rv,o?1&i|2:1&i),u;return S(u),null;case 22:case 23:return Ij(),o=null!==u.memoizedState,null!==a&&null!==a.memoizedState!==o&&(u.flags|=8192),o&&0!=(1&u.mode)?0!=(1073741824&r0)&&(S(u),6&u.subtreeFlags&&(u.flags|=8192)):S(u),null;case 24:case 25:return null}throw Error(p(156,u.tag))}function Jj(a,u){switch(wg(u),u.tag){case 1:return Zf(u.type)&&$f(),65536&(a=u.flags)?(u.flags=-65537&a|128,u):null;case 3:return Jh(),E(tQ),E(tA),Oh(),0!=(65536&(a=u.flags))&&0==(128&a)?(u.flags=-65537&a|128,u):null;case 5:return Lh(u),null;case 13:if(E(rv),null!==(a=u.memoizedState)&&null!==a.dehydrated){if(null===u.alternate)throw Error(p(340));Ig()}return 65536&(a=u.flags)?(u.flags=-65537&a|128,u):null;case 19:return E(rv),null;case 4:return Jh(),null;case 10:return Rg(u.type._context),null;case 22:case 23:return Ij(),null;default:return null}}s=function(a,u){for(var i=u.child;null!==i;){if(5===i.tag||6===i.tag)a.appendChild(i.stateNode);else if(4!==i.tag&&null!==i.child){i.child.return=i,i=i.child;continue}if(i===u)break;for(;null===i.sibling;){if(null===i.return||i.return===u)return;i=i.return}i.sibling.return=i.return,i=i.sibling}},w=function(){},x=function(a,u,i,o){var s=a.memoizedProps;if(s!==o){a=u.stateNode,Hh(rp.current);var w,x=null;switch(i){case"input":s=Ya(a,s),o=Ya(a,o),x=[];break;case"select":s=eS({},s,{value:void 0}),o=eS({},o,{value:void 0}),x=[];break;case"textarea":s=gb(a,s),o=gb(a,o),x=[];break;default:"function"!=typeof s.onClick&&"function"==typeof o.onClick&&(a.onclick=Bf)}for(j in ub(i,o),i=null,s)if(!o.hasOwnProperty(j)&&s.hasOwnProperty(j)&&null!=s[j]){if("style"===j){var C=s[j];for(w in C)C.hasOwnProperty(w)&&(i||(i={}),i[w]="")}else"dangerouslySetInnerHTML"!==j&&"children"!==j&&"suppressContentEditableWarning"!==j&&"suppressHydrationWarning"!==j&&"autoFocus"!==j&&(U.hasOwnProperty(j)?x||(x=[]):(x=x||[]).push(j,null))}for(j in o){var _=o[j];if(C=null!=s?s[j]:void 0,o.hasOwnProperty(j)&&_!==C&&(null!=_||null!=C)){if("style"===j){if(C){for(w in C)!C.hasOwnProperty(w)||_&&_.hasOwnProperty(w)||(i||(i={}),i[w]="");for(w in _)_.hasOwnProperty(w)&&C[w]!==_[w]&&(i||(i={}),i[w]=_[w])}else i||(x||(x=[]),x.push(j,i)),i=_}else"dangerouslySetInnerHTML"===j?(_=_?_.__html:void 0,C=C?C.__html:void 0,null!=_&&C!==_&&(x=x||[]).push(j,_)):"children"===j?"string"!=typeof _&&"number"!=typeof _||(x=x||[]).push(j,""+_):"suppressContentEditableWarning"!==j&&"suppressHydrationWarning"!==j&&(U.hasOwnProperty(j)?(null!=_&&"onScroll"===j&&D("scroll",a),x||C===_||(x=[])):(x=x||[]).push(j,_))}}i&&(x=x||[]).push("style",i);var j=x;(u.updateQueue=j)&&(u.flags|=4)}},C=function(a,u,i,o){i!==o&&(u.flags|=4)};var rU=!1,rV=!1,rW="function"==typeof WeakSet?WeakSet:Set,rA=null;function Mj(a,u){var i=a.ref;if(null!==i){if("function"==typeof i)try{i(null)}catch(i){W(a,u,i)}else i.current=null}}function Nj(a,u,i){try{i()}catch(i){W(a,u,i)}}var rQ=!1;function Pj(a,u){if(tC=nk,Ne(a=Me())){if("selectionStart"in a)var i={start:a.selectionStart,end:a.selectionEnd};else e:{var o=(i=(i=a.ownerDocument)&&i.defaultView||window).getSelection&&i.getSelection();if(o&&0!==o.rangeCount){i=o.anchorNode;var s,w=o.anchorOffset,x=o.focusNode;o=o.focusOffset;try{i.nodeType,x.nodeType}catch(a){i=null;break e}var C=0,_=-1,j=-1,z=0,P=0,U=a,V=null;n:for(;;){for(;U!==i||0!==w&&3!==U.nodeType||(_=C+w),U!==x||0!==o&&3!==U.nodeType||(j=C+o),3===U.nodeType&&(C+=U.nodeValue.length),null!==(s=U.firstChild);)V=U,U=s;for(;;){if(U===a)break n;if(V===i&&++z===w&&(_=C),V===x&&++P===o&&(j=C),null!==(s=U.nextSibling))break;V=(U=V).parentNode}U=s}i=-1===_||-1===j?null:{start:_,end:j}}else i=null}i=i||{start:0,end:0}}else i=null;for(t_={focusedElem:a,selectionRange:i},nk=!1,rA=u;null!==rA;)if(a=(u=rA).child,0!=(1028&u.subtreeFlags)&&null!==a)a.return=u,rA=a;else for(;null!==rA;){u=rA;try{var B=u.alternate;if(0!=(1024&u.flags))switch(u.tag){case 0:case 11:case 15:case 5:case 6:case 4:case 17:break;case 1:if(null!==B){var $=B.memoizedProps,Y=B.memoizedState,Z=u.stateNode,X=Z.getSnapshotBeforeUpdate(u.elementType===u.type?$:Lg(u.type,$),Y);Z.__reactInternalSnapshotBeforeUpdate=X}break;case 3:var ee=u.stateNode.containerInfo;1===ee.nodeType?ee.textContent="":9===ee.nodeType&&ee.documentElement&&ee.removeChild(ee.documentElement);break;default:throw Error(p(163))}}catch(a){W(u,u.return,a)}if(null!==(a=u.sibling)){a.return=u.return,rA=a;break}rA=u.return}return B=rQ,rQ=!1,B}function Qj(a,u,i){var o=u.updateQueue;if(null!==(o=null!==o?o.lastEffect:null)){var s=o=o.next;do{if((s.tag&a)===a){var w=s.destroy;s.destroy=void 0,void 0!==w&&Nj(u,i,w)}s=s.next}while(s!==o)}}function Rj(a,u){if(null!==(u=null!==(u=u.updateQueue)?u.lastEffect:null)){var i=u=u.next;do{if((i.tag&a)===a){var o=i.create;i.destroy=o()}i=i.next}while(i!==u)}}function Sj(a){var u=a.ref;if(null!==u){var i=a.stateNode;a.tag,a=i,"function"==typeof u?u(a):u.current=a}}function Tj(a){var u=a.alternate;null!==u&&(a.alternate=null,Tj(u)),a.child=null,a.deletions=null,a.sibling=null,5===a.tag&&null!==(u=a.stateNode)&&(delete u[tD],delete u[tM],delete u[tI],delete u[tF],delete u[tO]),a.stateNode=null,a.return=null,a.dependencies=null,a.memoizedProps=null,a.memoizedState=null,a.pendingProps=null,a.stateNode=null,a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}function Vj(a){e:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(2&a.flags||null===a.child||4===a.tag)continue e;a.child.return=a,a=a.child}if(!(2&a.flags))return a.stateNode}}function Wj(a,u,i){var o=a.tag;if(5===o||6===o)a=a.stateNode,u?8===i.nodeType?i.parentNode.insertBefore(a,u):i.insertBefore(a,u):(8===i.nodeType?(u=i.parentNode).insertBefore(a,i):(u=i).appendChild(a),null!=(i=i._reactRootContainer)||null!==u.onclick||(u.onclick=Bf));else if(4!==o&&null!==(a=a.child))for(Wj(a,u,i),a=a.sibling;null!==a;)Wj(a,u,i),a=a.sibling}function Xj(a,u,i){var o=a.tag;if(5===o||6===o)a=a.stateNode,u?i.insertBefore(a,u):i.appendChild(a);else if(4!==o&&null!==(a=a.child))for(Xj(a,u,i),a=a.sibling;null!==a;)Xj(a,u,i),a=a.sibling}var rB=null,r$=!1;function Zj(a,u,i){for(i=i.child;null!==i;)ak(a,u,i),i=i.sibling}function ak(a,u,i){if(e2&&"function"==typeof e2.onCommitFiberUnmount)try{e2.onCommitFiberUnmount(e1,i)}catch(a){}switch(i.tag){case 5:rV||Mj(i,u);case 6:var o=rB,s=r$;rB=null,Zj(a,u,i),rB=o,r$=s,null!==rB&&(r$?(a=rB,i=i.stateNode,8===a.nodeType?a.parentNode.removeChild(i):a.removeChild(i)):rB.removeChild(i.stateNode));break;case 18:null!==rB&&(r$?(a=rB,i=i.stateNode,8===a.nodeType?Kf(a.parentNode,i):1===a.nodeType&&Kf(a,i),bd(a)):Kf(rB,i.stateNode));break;case 4:o=rB,s=r$,rB=i.stateNode.containerInfo,r$=!0,Zj(a,u,i),rB=o,r$=s;break;case 0:case 11:case 14:case 15:if(!rV&&null!==(o=i.updateQueue)&&null!==(o=o.lastEffect)){s=o=o.next;do{var w=s,x=w.destroy;w=w.tag,void 0!==x&&(0!=(2&w)?Nj(i,u,x):0!=(4&w)&&Nj(i,u,x)),s=s.next}while(s!==o)}Zj(a,u,i);break;case 1:if(!rV&&(Mj(i,u),"function"==typeof(o=i.stateNode).componentWillUnmount))try{o.props=i.memoizedProps,o.state=i.memoizedState,o.componentWillUnmount()}catch(a){W(i,u,a)}Zj(a,u,i);break;case 21:default:Zj(a,u,i);break;case 22:1&i.mode?(rV=(o=rV)||null!==i.memoizedState,Zj(a,u,i),rV=o):Zj(a,u,i)}}function bk(a){var u=a.updateQueue;if(null!==u){a.updateQueue=null;var i=a.stateNode;null===i&&(i=a.stateNode=new rW),u.forEach(function(u){var o=ck.bind(null,a,u);i.has(u)||(i.add(u),u.then(o,o))})}}function dk(a,u){var i=u.deletions;if(null!==i)for(var o=0;o<i.length;o++){var s=i[o];try{var w=u,x=w;e:for(;null!==x;){switch(x.tag){case 5:rB=x.stateNode,r$=!1;break e;case 3:case 4:rB=x.stateNode.containerInfo,r$=!0;break e}x=x.return}if(null===rB)throw Error(p(160));ak(a,w,s),rB=null,r$=!1;var C=s.alternate;null!==C&&(C.return=null),s.return=null}catch(a){W(s,u,a)}}if(12854&u.subtreeFlags)for(u=u.child;null!==u;)ek(u,a),u=u.sibling}function ek(a,u){var i=a.alternate,o=a.flags;switch(a.tag){case 0:case 11:case 14:case 15:if(dk(u,a),fk(a),4&o){try{Qj(3,a,a.return),Rj(3,a)}catch(u){W(a,a.return,u)}try{Qj(5,a,a.return)}catch(u){W(a,a.return,u)}}break;case 1:dk(u,a),fk(a),512&o&&null!==i&&Mj(i,i.return);break;case 5:if(dk(u,a),fk(a),512&o&&null!==i&&Mj(i,i.return),32&a.flags){var s=a.stateNode;try{ob(s,"")}catch(u){W(a,a.return,u)}}if(4&o&&null!=(s=a.stateNode)){var w=a.memoizedProps,x=null!==i?i.memoizedProps:w,C=a.type,_=a.updateQueue;if(a.updateQueue=null,null!==_)try{"input"===C&&"radio"===w.type&&null!=w.name&&ab(s,w),vb(C,x);var j=vb(C,w);for(x=0;x<_.length;x+=2){var z=_[x],P=_[x+1];"style"===z?sb(s,P):"dangerouslySetInnerHTML"===z?ez(s,P):"children"===z?ob(s,P):ta(s,z,P,j)}switch(C){case"input":bb(s,w);break;case"textarea":ib(s,w);break;case"select":var U=s._wrapperState.wasMultiple;s._wrapperState.wasMultiple=!!w.multiple;var V=w.value;null!=V?fb(s,!!w.multiple,V,!1):!!w.multiple!==U&&(null!=w.defaultValue?fb(s,!!w.multiple,w.defaultValue,!0):fb(s,!!w.multiple,w.multiple?[]:"",!1))}s[tM]=w}catch(u){W(a,a.return,u)}}break;case 6:if(dk(u,a),fk(a),4&o){if(null===a.stateNode)throw Error(p(162));s=a.stateNode,w=a.memoizedProps;try{s.nodeValue=w}catch(u){W(a,a.return,u)}}break;case 3:if(dk(u,a),fk(a),4&o&&null!==i&&i.memoizedState.isDehydrated)try{bd(u.containerInfo)}catch(u){W(a,a.return,u)}break;case 4:default:dk(u,a),fk(a);break;case 13:dk(u,a),fk(a),8192&(s=a.child).flags&&(w=null!==s.memoizedState,s.stateNode.isHidden=w,w&&(null===s.alternate||null===s.alternate.memoizedState)&&(r7=eG())),4&o&&bk(a);break;case 22:if(z=null!==i&&null!==i.memoizedState,1&a.mode?(rV=(j=rV)||z,dk(u,a),rV=j):dk(u,a),fk(a),8192&o){if(j=null!==a.memoizedState,(a.stateNode.isHidden=j)&&!z&&0!=(1&a.mode))for(rA=a,z=a.child;null!==z;){for(P=rA=z;null!==rA;){switch(V=(U=rA).child,U.tag){case 0:case 11:case 14:case 15:Qj(4,U,U.return);break;case 1:Mj(U,U.return);var B=U.stateNode;if("function"==typeof B.componentWillUnmount){o=U,i=U.return;try{u=o,B.props=u.memoizedProps,B.state=u.memoizedState,B.componentWillUnmount()}catch(a){W(o,i,a)}}break;case 5:Mj(U,U.return);break;case 22:if(null!==U.memoizedState){hk(P);continue}}null!==V?(V.return=U,rA=V):hk(P)}z=z.sibling}e:for(z=null,P=a;;){if(5===P.tag){if(null===z){z=P;try{s=P.stateNode,j?(w=s.style,"function"==typeof w.setProperty?w.setProperty("display","none","important"):w.display="none"):(C=P.stateNode,x=null!=(_=P.memoizedProps.style)&&_.hasOwnProperty("display")?_.display:null,C.style.display=rb("display",x))}catch(u){W(a,a.return,u)}}}else if(6===P.tag){if(null===z)try{P.stateNode.nodeValue=j?"":P.memoizedProps}catch(u){W(a,a.return,u)}}else if((22!==P.tag&&23!==P.tag||null===P.memoizedState||P===a)&&null!==P.child){P.child.return=P,P=P.child;continue}if(P===a)break;for(;null===P.sibling;){if(null===P.return||P.return===a)break e;z===P&&(z=null),P=P.return}z===P&&(z=null),P.sibling.return=P.return,P=P.sibling}}break;case 19:dk(u,a),fk(a),4&o&&bk(a);case 21:}}function fk(a){var u=a.flags;if(2&u){try{e:{for(var i=a.return;null!==i;){if(Uj(i)){var o=i;break e}i=i.return}throw Error(p(160))}switch(o.tag){case 5:var s=o.stateNode;32&o.flags&&(ob(s,""),o.flags&=-33);var w=Vj(a);Xj(a,w,s);break;case 3:case 4:var x=o.stateNode.containerInfo,C=Vj(a);Wj(a,C,x);break;default:throw Error(p(161))}}catch(u){W(a,a.return,u)}a.flags&=-3}4096&u&&(a.flags&=-4097)}function ik(a,u,i){rA=a,jk(a,u,i)}function jk(a,u,i){for(var o=0!=(1&a.mode);null!==rA;){var s=rA,w=s.child;if(22===s.tag&&o){var x=null!==s.memoizedState||rU;if(!x){var C=s.alternate,_=null!==C&&null!==C.memoizedState||rV;C=rU;var j=rV;if(rU=x,(rV=_)&&!j)for(rA=s;null!==rA;)_=(x=rA).child,22===x.tag&&null!==x.memoizedState?kk(s):null!==_?(_.return=x,rA=_):kk(s);for(;null!==w;)rA=w,jk(w,u,i),w=w.sibling;rA=s,rU=C,rV=j}lk(a,u,i)}else 0!=(8772&s.subtreeFlags)&&null!==w?(w.return=s,rA=w):lk(a,u,i)}}function lk(a){for(;null!==rA;){var u=rA;if(0!=(8772&u.flags)){var i=u.alternate;try{if(0!=(8772&u.flags))switch(u.tag){case 0:case 11:case 15:rV||Rj(5,u);break;case 1:var o=u.stateNode;if(4&u.flags&&!rV){if(null===i)o.componentDidMount();else{var s=u.elementType===u.type?i.memoizedProps:Lg(u.type,i.memoizedProps);o.componentDidUpdate(s,i.memoizedState,o.__reactInternalSnapshotBeforeUpdate)}}var w=u.updateQueue;null!==w&&ih(u,w,o);break;case 3:var x=u.updateQueue;if(null!==x){if(i=null,null!==u.child)switch(u.child.tag){case 5:case 1:i=u.child.stateNode}ih(u,x,i)}break;case 5:var C=u.stateNode;if(null===i&&4&u.flags){i=C;var _=u.memoizedProps;switch(u.type){case"button":case"input":case"select":case"textarea":_.autoFocus&&i.focus();break;case"img":_.src&&(i.src=_.src)}}break;case 6:case 4:case 12:case 19:case 17:case 21:case 22:case 23:case 25:break;case 13:if(null===u.memoizedState){var j=u.alternate;if(null!==j){var z=j.memoizedState;if(null!==z){var P=z.dehydrated;null!==P&&bd(P)}}}break;default:throw Error(p(163))}rV||512&u.flags&&Sj(u)}catch(a){W(u,u.return,a)}}if(u===a){rA=null;break}if(null!==(i=u.sibling)){i.return=u.return,rA=i;break}rA=u.return}}function hk(a){for(;null!==rA;){var u=rA;if(u===a){rA=null;break}var i=u.sibling;if(null!==i){i.return=u.return,rA=i;break}rA=u.return}}function kk(a){for(;null!==rA;){var u=rA;try{switch(u.tag){case 0:case 11:case 15:var i=u.return;try{Rj(4,u)}catch(a){W(u,i,a)}break;case 1:var o=u.stateNode;if("function"==typeof o.componentDidMount){var s=u.return;try{o.componentDidMount()}catch(a){W(u,s,a)}}var w=u.return;try{Sj(u)}catch(a){W(u,w,a)}break;case 5:var x=u.return;try{Sj(u)}catch(a){W(u,x,a)}}}catch(a){W(u,u.return,a)}if(u===a){rA=null;break}var C=u.sibling;if(null!==C){C.return=u.return,rA=C;break}rA=u.return}}var rH=Math.ceil,rK=en.ReactCurrentDispatcher,rG=en.ReactCurrentOwner,rY=en.ReactCurrentBatchConfig,rq=0,rZ=null,rX=null,rJ=0,r0=0,r1=Uf(0),r2=0,r3=null,r4=0,r8=0,r6=0,r5=null,r9=null,r7=0,le=1/0,ln=null,lt=!1,lr=null,ll=null,la=!1,lu=null,lo=0,ls=0,lc=null,lf=-1,ld=0;function L(){return 0!=(6&rq)?eG():-1!==lf?lf:lf=eG()}function lh(a){return 0==(1&a.mode)?1:0!=(2&rq)&&0!==rJ?rJ&-rJ:null!==t5.transition?(0===ld&&(ld=yc()),ld):0!==(a=e9)?a:a=void 0===(a=window.event)?16:jd(a.type)}function mh(a,u,i,o){if(50<ls)throw ls=0,lc=null,Error(p(185));Ac(a,i,o),(0==(2&rq)||a!==rZ)&&(a===rZ&&(0==(2&rq)&&(r8|=i),4===r2&&Dk(a,rJ)),Ek(a,o),1===i&&0===rq&&0==(1&u.mode)&&(le=eG()+500,tH&&jg()))}function Ek(a,u){var i,o,s=a.callbackNode;wc(a,u);var w=uc(a,a===rZ?rJ:0);if(0===w)null!==s&&e$(s),a.callbackNode=null,a.callbackPriority=0;else if(u=w&-w,a.callbackPriority!==u){if(null!=s&&e$(s),1===u)0===a.tag?ig(Fk.bind(null,a)):hg(Fk.bind(null,a)),tP(function(){0==(6&rq)&&jg()}),s=null;else{switch(Dc(w)){case 1:s=eq;break;case 4:s=eZ;break;case 16:default:s=eX;break;case 536870912:s=e0}s=eB(s,Hk.bind(null,a))}a.callbackPriority=u,a.callbackNode=s}}function Hk(a,u){if(lf=-1,ld=0,0!=(6&rq))throw Error(p(327));var i=a.callbackNode;if(Ik()&&a.callbackNode!==i)return null;var o=uc(a,a===rZ?rJ:0);if(0===o)return null;if(0!=(30&o)||0!=(o&a.expiredLanes)||u)u=Jk(a,o);else{u=o;var s=rq;rq|=2;var w=Kk();for((rZ!==a||rJ!==u)&&(ln=null,le=eG()+500,Lk(a,u));;)try{Mk();break}catch(u){Nk(a,u)}Qg(),rK.current=w,rq=s,null!==rX?u=0:(rZ=null,rJ=0,u=r2)}if(0!==u){if(2===u&&0!==(s=xc(a))&&(o=s,u=Ok(a,s)),1===u)throw i=r3,Lk(a,0),Dk(a,o),Ek(a,eG()),i;if(6===u)Dk(a,o);else{if(s=a.current.alternate,0==(30&o)&&!Pk(s)&&(2===(u=Jk(a,o))&&0!==(w=xc(a))&&(o=w,u=Ok(a,w)),1===u))throw i=r3,Lk(a,0),Dk(a,o),Ek(a,eG()),i;switch(a.finishedWork=s,a.finishedLanes=o,u){case 0:case 1:throw Error(p(345));case 2:case 5:Qk(a,r9,ln);break;case 3:if(Dk(a,o),(130023424&o)===o&&10<(u=r7+500-eG())){if(0!==uc(a,0))break;if(((s=a.suspendedLanes)&o)!==o){L(),a.pingedLanes|=a.suspendedLanes&s;break}a.timeoutHandle=tz(Qk.bind(null,a,r9,ln),u);break}Qk(a,r9,ln);break;case 4:if(Dk(a,o),(4194240&o)===o)break;for(s=-1,u=a.eventTimes;0<o;){var x=31-e3(o);w=1<<x,(x=u[x])>s&&(s=x),o&=~w}if(o=s,10<(o=(120>(o=eG()-o)?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*rH(o/1960))-o)){a.timeoutHandle=tz(Qk.bind(null,a,r9,ln),o);break}Qk(a,r9,ln);break;default:throw Error(p(329))}}}return Ek(a,eG()),a.callbackNode===i?Hk.bind(null,a):null}function Ok(a,u){var i=r5;return a.current.memoizedState.isDehydrated&&(Lk(a,u).flags|=256),2!==(a=Jk(a,u))&&(u=r9,r9=i,null!==u&&Gj(u)),a}function Gj(a){null===r9?r9=a:r9.push.apply(r9,a)}function Pk(a){for(var u=a;;){if(16384&u.flags){var i=u.updateQueue;if(null!==i&&null!==(i=i.stores))for(var o=0;o<i.length;o++){var s=i[o],w=s.getSnapshot;s=s.value;try{if(!n6(w(),s))return!1}catch(a){return!1}}}if(i=u.child,16384&u.subtreeFlags&&null!==i)i.return=u,u=i;else{if(u===a)break;for(;null===u.sibling;){if(null===u.return||u.return===a)return!0;u=u.return}u.sibling.return=u.return,u=u.sibling}}return!0}function Dk(a,u){for(u&=~r6,u&=~r8,a.suspendedLanes|=u,a.pingedLanes&=~u,a=a.expirationTimes;0<u;){var i=31-e3(u),o=1<<i;a[i]=-1,u&=~o}}function Fk(a){if(0!=(6&rq))throw Error(p(327));Ik();var u=uc(a,0);if(0==(1&u))return Ek(a,eG()),null;var i=Jk(a,u);if(0!==a.tag&&2===i){var o=xc(a);0!==o&&(u=o,i=Ok(a,o))}if(1===i)throw i=r3,Lk(a,0),Dk(a,u),Ek(a,eG()),i;if(6===i)throw Error(p(345));return a.finishedWork=a.current.alternate,a.finishedLanes=u,Qk(a,r9,ln),Ek(a,eG()),null}function Rk(a,u){var i=rq;rq|=1;try{return a(u)}finally{0===(rq=i)&&(le=eG()+500,tH&&jg())}}function Sk(a){null!==lu&&0===lu.tag&&0==(6&rq)&&Ik();var u=rq;rq|=1;var i=rY.transition,o=e9;try{if(rY.transition=null,e9=1,a)return a()}finally{e9=o,rY.transition=i,0==(6&(rq=u))&&jg()}}function Ij(){r0=r1.current,E(r1)}function Lk(a,u){a.finishedWork=null,a.finishedLanes=0;var i=a.timeoutHandle;if(-1!==i&&(a.timeoutHandle=-1,tL(i)),null!==rX)for(i=rX.return;null!==i;){var o=i;switch(wg(o),o.tag){case 1:null!=(o=o.type.childContextTypes)&&$f();break;case 3:Jh(),E(tQ),E(tA),Oh();break;case 5:Lh(o);break;case 4:Jh();break;case 13:case 19:E(rv);break;case 10:Rg(o.type._context);break;case 22:case 23:Ij()}i=i.return}if(rZ=a,rX=a=wh(a.current,null),rJ=r0=u,r2=0,r3=null,r6=r8=r4=0,r9=r5=null,null!==rr){for(u=0;u<rr.length;u++)if(null!==(o=(i=rr[u]).interleaved)){i.interleaved=null;var s=o.next,w=i.pending;if(null!==w){var x=w.next;w.next=s,o.next=x}i.pending=o}rr=null}return a}function Nk(a,u){for(;;){var i=rX;try{if(Qg(),rk.current=rP,r_){for(var o=rE.memoizedState;null!==o;){var s=o.queue;null!==s&&(s.pending=null),o=o.next}r_=!1}if(rS=0,rC=rx=rE=null,rz=!1,rL=0,rG.current=null,null===i||null===i.return){r2=1,r3=u,rX=null;break}e:{var w=a,x=i.return,C=i,_=u;if(u=rJ,C.flags|=32768,null!==_&&"object"==typeof _&&"function"==typeof _.then){var j=_,z=C,P=z.tag;if(0==(1&z.mode)&&(0===P||11===P||15===P)){var U=z.alternate;U?(z.updateQueue=U.updateQueue,z.memoizedState=U.memoizedState,z.lanes=U.lanes):(z.updateQueue=null,z.memoizedState=null)}var V=Vi(x);if(null!==V){V.flags&=-257,Wi(V,x,C,w,u),1&V.mode&&Ti(w,j,u),u=V,_=j;var B=u.updateQueue;if(null===B){var $=new Set;$.add(_),u.updateQueue=$}else B.add(_);break e}if(0==(1&u)){Ti(w,j,u),uj();break e}_=Error(p(426))}else if(t8&&1&C.mode){var Y=Vi(x);if(null!==Y){0==(65536&Y.flags)&&(Y.flags|=256),Wi(Y,x,C,w,u),Jg(Ki(_,C));break e}}w=_=Ki(_,C),4!==r2&&(r2=2),null===r5?r5=[w]:r5.push(w),w=x;do{switch(w.tag){case 3:w.flags|=65536,u&=-u,w.lanes|=u;var Z=Oi(w,_,u);fh(w,Z);break e;case 1:C=_;var X=w.type,ee=w.stateNode;if(0==(128&w.flags)&&("function"==typeof X.getDerivedStateFromError||null!==ee&&"function"==typeof ee.componentDidCatch&&(null===ll||!ll.has(ee)))){w.flags|=65536,u&=-u,w.lanes|=u;var en=Ri(w,C,u);fh(w,en);break e}}w=w.return}while(null!==w)}Tk(i)}catch(a){u=a,rX===i&&null!==i&&(rX=i=i.return);continue}break}}function Kk(){var a=rK.current;return rK.current=rP,null===a?rP:a}function uj(){(0===r2||3===r2||2===r2)&&(r2=4),null===rZ||0==(268435455&r4)&&0==(268435455&r8)||Dk(rZ,rJ)}function Jk(a,u){var i=rq;rq|=2;var o=Kk();for((rZ!==a||rJ!==u)&&(ln=null,Lk(a,u));;)try{Uk();break}catch(u){Nk(a,u)}if(Qg(),rq=i,rK.current=o,null!==rX)throw Error(p(261));return rZ=null,rJ=0,r2}function Uk(){for(;null!==rX;)Vk(rX)}function Mk(){for(;null!==rX&&!eH();)Vk(rX)}function Vk(a){var u=_(a.alternate,a,r0);a.memoizedProps=a.pendingProps,null===u?Tk(a):rX=u,rG.current=null}function Tk(a){var u=a;do{var i=u.alternate;if(a=u.return,0==(32768&u.flags)){if(null!==(i=Fj(i,u,r0))){rX=i;return}}else{if(null!==(i=Jj(i,u))){i.flags&=32767,rX=i;return}if(null!==a)a.flags|=32768,a.subtreeFlags=0,a.deletions=null;else{r2=6,rX=null;return}}if(null!==(u=u.sibling)){rX=u;return}rX=u=a}while(null!==u);0===r2&&(r2=5)}function Qk(a,u,i){var o=e9,s=rY.transition;try{rY.transition=null,e9=1,Xk(a,u,i,o)}finally{rY.transition=s,e9=o}return null}function Xk(a,u,i,o){do Ik();while(null!==lu);if(0!=(6&rq))throw Error(p(327));i=a.finishedWork;var s=a.finishedLanes;if(null===i)return null;if(a.finishedWork=null,a.finishedLanes=0,i===a.current)throw Error(p(177));a.callbackNode=null,a.callbackPriority=0;var w=i.lanes|i.childLanes;if(Bc(a,w),a===rZ&&(rX=rZ=null,rJ=0),0==(2064&i.subtreeFlags)&&0==(2064&i.flags)||la||(la=!0,eB(eX,function(){return Ik(),null})),w=0!=(15990&i.flags),0!=(15990&i.subtreeFlags)||w){w=rY.transition,rY.transition=null;var x=e9;e9=1;var C=rq;rq|=4,rG.current=null,Pj(a,i),ek(i,a),Oe(t_),nk=!!tC,t_=tC=null,a.current=i,ik(i,a,s),eK(),rq=C,e9=x,rY.transition=w}else a.current=i;if(la&&(la=!1,lu=a,lo=s),0===(w=a.pendingLanes)&&(ll=null),mc(i.stateNode,o),Ek(a,eG()),null!==u)for(o=a.onRecoverableError,i=0;i<u.length;i++)o((s=u[i]).value,{componentStack:s.stack,digest:s.digest});if(lt)throw lt=!1,a=lr,lr=null,a;return 0!=(1&lo)&&0!==a.tag&&Ik(),0!=(1&(w=a.pendingLanes))?a===lc?ls++:(ls=0,lc=a):ls=0,jg(),null}function Ik(){if(null!==lu){var a=Dc(lo),u=rY.transition,i=e9;try{if(rY.transition=null,e9=16>a?16:a,null===lu)var o=!1;else{if(a=lu,lu=null,lo=0,0!=(6&rq))throw Error(p(331));var s=rq;for(rq|=4,rA=a.current;null!==rA;){var w=rA,x=w.child;if(0!=(16&rA.flags)){var C=w.deletions;if(null!==C){for(var _=0;_<C.length;_++){var j=C[_];for(rA=j;null!==rA;){var z=rA;switch(z.tag){case 0:case 11:case 15:Qj(8,z,w)}var P=z.child;if(null!==P)P.return=z,rA=P;else for(;null!==rA;){var U=(z=rA).sibling,V=z.return;if(Tj(z),z===j){rA=null;break}if(null!==U){U.return=V,rA=U;break}rA=V}}}var B=w.alternate;if(null!==B){var $=B.child;if(null!==$){B.child=null;do{var Y=$.sibling;$.sibling=null,$=Y}while(null!==$)}}rA=w}}if(0!=(2064&w.subtreeFlags)&&null!==x)x.return=w,rA=x;else for(;null!==rA;){if(w=rA,0!=(2048&w.flags))switch(w.tag){case 0:case 11:case 15:Qj(9,w,w.return)}var Z=w.sibling;if(null!==Z){Z.return=w.return,rA=Z;break}rA=w.return}}var X=a.current;for(rA=X;null!==rA;){var ee=(x=rA).child;if(0!=(2064&x.subtreeFlags)&&null!==ee)ee.return=x,rA=ee;else for(x=X;null!==rA;){if(C=rA,0!=(2048&C.flags))try{switch(C.tag){case 0:case 11:case 15:Rj(9,C)}}catch(a){W(C,C.return,a)}if(C===x){rA=null;break}var en=C.sibling;if(null!==en){en.return=C.return,rA=en;break}rA=C.return}}if(rq=s,jg(),e2&&"function"==typeof e2.onPostCommitFiberRoot)try{e2.onPostCommitFiberRoot(e1,a)}catch(a){}o=!0}return o}finally{e9=i,rY.transition=u}}return!1}function Yk(a,u,i){u=Oi(a,u=Ki(i,u),1),a=dh(a,u,1),u=L(),null!==a&&(Ac(a,1,u),Ek(a,u))}function W(a,u,i){if(3===a.tag)Yk(a,a,i);else for(;null!==u;){if(3===u.tag){Yk(u,a,i);break}if(1===u.tag){var o=u.stateNode;if("function"==typeof u.type.getDerivedStateFromError||"function"==typeof o.componentDidCatch&&(null===ll||!ll.has(o))){a=Ri(u,a=Ki(i,a),1),u=dh(u,a,1),a=L(),null!==u&&(Ac(u,1,a),Ek(u,a));break}}u=u.return}}function Ui(a,u,i){var o=a.pingCache;null!==o&&o.delete(u),u=L(),a.pingedLanes|=a.suspendedLanes&i,rZ===a&&(rJ&i)===i&&(4===r2||3===r2&&(130023424&rJ)===rJ&&500>eG()-r7?Lk(a,0):r6|=i),Ek(a,u)}function Zk(a,u){0===u&&(0==(1&a.mode)?u=1:(u=e5,0==(130023424&(e5<<=1))&&(e5=4194304)));var i=L();null!==(a=Zg(a,u))&&(Ac(a,u,i),Ek(a,i))}function vj(a){var u=a.memoizedState,i=0;null!==u&&(i=u.retryLane),Zk(a,i)}function ck(a,u){var i=0;switch(a.tag){case 13:var o=a.stateNode,s=a.memoizedState;null!==s&&(i=s.retryLane);break;case 19:o=a.stateNode;break;default:throw Error(p(314))}null!==o&&o.delete(u),Zk(a,i)}function al(a,u,i,o){this.tag=a,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=u,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Bg(a,u,i,o){return new al(a,u,i,o)}function bj(a){return!(!(a=a.prototype)||!a.isReactComponent)}function $k(a){if("function"==typeof a)return bj(a)?1:0;if(null!=a){if((a=a.$$typeof)===ef)return 11;if(a===em)return 14}return 2}function wh(a,u){var i=a.alternate;return null===i?((i=Bg(a.tag,u,a.key,a.mode)).elementType=a.elementType,i.type=a.type,i.stateNode=a.stateNode,i.alternate=a,a.alternate=i):(i.pendingProps=u,i.type=a.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=14680064&a.flags,i.childLanes=a.childLanes,i.lanes=a.lanes,i.child=a.child,i.memoizedProps=a.memoizedProps,i.memoizedState=a.memoizedState,i.updateQueue=a.updateQueue,u=a.dependencies,i.dependencies=null===u?null:{lanes:u.lanes,firstContext:u.firstContext},i.sibling=a.sibling,i.index=a.index,i.ref=a.ref,i}function yh(a,u,i,o,s,w){var x=2;if(o=a,"function"==typeof a)bj(a)&&(x=1);else if("string"==typeof a)x=5;else e:switch(a){case ea:return Ah(i.children,s,w,u);case eu:x=8,s|=8;break;case eo:return(a=Bg(12,i,u,2|s)).elementType=eo,a.lanes=w,a;case ep:return(a=Bg(13,i,u,s)).elementType=ep,a.lanes=w,a;case eg:return(a=Bg(19,i,u,s)).elementType=eg,a.lanes=w,a;case eb:return qj(i,s,w,u);default:if("object"==typeof a&&null!==a)switch(a.$$typeof){case es:x=10;break e;case ec:x=9;break e;case ef:x=11;break e;case em:x=14;break e;case ev:x=16,o=null;break e}throw Error(p(130,null==a?a:typeof a,""))}return(u=Bg(x,i,u,s)).elementType=a,u.type=o,u.lanes=w,u}function Ah(a,u,i,o){return(a=Bg(7,a,o,u)).lanes=i,a}function qj(a,u,i,o){return(a=Bg(22,a,o,u)).elementType=eb,a.lanes=i,a.stateNode={isHidden:!1},a}function xh(a,u,i){return(a=Bg(6,a,null,u)).lanes=i,a}function zh(a,u,i){return(u=Bg(4,null!==a.children?a.children:[],a.key,u)).lanes=i,u.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation},u}function bl(a,u,i,o,s){this.tag=u,this.containerInfo=a,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zc(0),this.expirationTimes=zc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zc(0),this.identifierPrefix=o,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function cl(a,u,i,o,s,w,x,C,_){return a=new bl(a,u,i,C,_),1===u?(u=1,!0===w&&(u|=8)):u=0,w=Bg(3,null,null,u),a.current=w,w.stateNode=a,w.memoizedState={element:o,isDehydrated:i,cache:null,transitions:null,pendingSuspenseBoundaries:null},ah(w),a}function dl(a,u,i){var o=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:er,key:null==o?null:""+o,children:a,containerInfo:u,implementation:i}}function el(a){if(!a)return tW;a=a._reactInternals;e:{if(Vb(a)!==a||1!==a.tag)throw Error(p(170));var u=a;do{switch(u.tag){case 3:u=u.stateNode.context;break e;case 1:if(Zf(u.type)){u=u.stateNode.__reactInternalMemoizedMergedChildContext;break e}}u=u.return}while(null!==u);throw Error(p(171))}if(1===a.tag){var i=a.type;if(Zf(i))return bg(a,i,u)}return u}function fl(a,u,i,o,s,w,x,C,_){return(a=cl(i,o,!0,a,s,w,x,C,_)).context=el(null),i=a.current,(w=ch(o=L(),s=lh(i))).callback=null!=u?u:null,dh(i,w,s),a.current.lanes=s,Ac(a,s,o),Ek(a,o),a}function gl(a,u,i,o){var s=u.current,w=L(),x=lh(s);return i=el(i),null===u.context?u.context=i:u.pendingContext=i,(u=ch(w,x)).payload={element:a},null!==(o=void 0===o?null:o)&&(u.callback=o),null!==(a=dh(s,u,x))&&(mh(a,s,x,w),eh(a,s,x)),x}function hl(a){return(a=a.current).child?(a.child.tag,a.child.stateNode):null}function il(a,u){if(null!==(a=a.memoizedState)&&null!==a.dehydrated){var i=a.retryLane;a.retryLane=0!==i&&i<u?i:u}}function jl(a,u){il(a,u),(a=a.alternate)&&il(a,u)}function kl(){return null}_=function(a,u,i){if(null!==a){if(a.memoizedProps!==u.pendingProps||tQ.current)rF=!0;else{if(0==(a.lanes&i)&&0==(128&u.flags))return rF=!1,zj(a,u,i);rF=0!=(131072&a.flags)}}else rF=!1,t8&&0!=(1048576&u.flags)&&ug(u,tZ,u.index);switch(u.lanes=0,u.tag){case 2:var o=u.type;jj(a,u),a=u.pendingProps;var s=Yf(u,tA.current);Tg(u,i),s=Xh(null,u,o,a,s,i);var w=bi();return u.flags|=1,"object"==typeof s&&null!==s&&"function"==typeof s.render&&void 0===s.$$typeof?(u.tag=1,u.memoizedState=null,u.updateQueue=null,Zf(o)?(w=!0,cg(u)):w=!1,u.memoizedState=null!==s.state&&void 0!==s.state?s.state:null,ah(u),s.updater=ro,u.stateNode=s,s._reactInternals=u,rh(u,o,a,i),u=kj(null,u,o,!0,w,i)):(u.tag=0,t8&&w&&vg(u),Yi(null,u,s,i),u=u.child),u;case 16:o=u.elementType;e:{switch(jj(a,u),a=u.pendingProps,o=(s=o._init)(o._payload),u.type=o,s=u.tag=$k(o),a=Lg(o,a),s){case 0:u=dj(null,u,o,a,i);break e;case 1:u=ij(null,u,o,a,i);break e;case 11:u=Zi(null,u,o,a,i);break e;case 14:u=aj(null,u,o,Lg(o.type,a),i);break e}throw Error(p(306,o,""))}return u;case 0:return o=u.type,s=u.pendingProps,s=u.elementType===o?s:Lg(o,s),dj(a,u,o,s,i);case 1:return o=u.type,s=u.pendingProps,s=u.elementType===o?s:Lg(o,s),ij(a,u,o,s,i);case 3:e:{if(lj(u),null===a)throw Error(p(387));o=u.pendingProps,s=(w=u.memoizedState).element,bh(a,u),gh(u,o,null,i);var x=u.memoizedState;if(o=x.element,w.isDehydrated){if(w={element:o,isDehydrated:!1,cache:x.cache,pendingSuspenseBoundaries:x.pendingSuspenseBoundaries,transitions:x.transitions},u.updateQueue.baseState=w,u.memoizedState=w,256&u.flags){s=Ki(Error(p(423)),u),u=mj(a,u,o,i,s);break e}if(o!==s){s=Ki(Error(p(424)),u),u=mj(a,u,o,i,s);break e}for(t4=Lf(u.stateNode.containerInfo.firstChild),t3=u,t8=!0,t6=null,i=rc(u,null,o,i),u.child=i;i;)i.flags=-3&i.flags|4096,i=i.sibling}else{if(Ig(),o===s){u=$i(a,u,i);break e}Yi(a,u,o,i)}u=u.child}return u;case 5:return Kh(u),null===a&&Eg(u),o=u.type,s=u.pendingProps,w=null!==a?a.memoizedProps:null,x=s.children,Ef(o,s)?x=null:null!==w&&Ef(o,w)&&(u.flags|=32),hj(a,u),Yi(a,u,x,i),u.child;case 6:return null===a&&Eg(u),null;case 13:return pj(a,u,i);case 4:return Ih(u,u.stateNode.containerInfo),o=u.pendingProps,null===a?u.child=rs(u,null,o,i):Yi(a,u,o,i),u.child;case 11:return o=u.type,s=u.pendingProps,s=u.elementType===o?s:Lg(o,s),Zi(a,u,o,s,i);case 7:return Yi(a,u,u.pendingProps,i),u.child;case 8:case 12:return Yi(a,u,u.pendingProps.children,i),u.child;case 10:e:{if(o=u.type._context,s=u.pendingProps,w=u.memoizedProps,x=s.value,G(t9,o._currentValue),o._currentValue=x,null!==w){if(n6(w.value,x)){if(w.children===s.children&&!tQ.current){u=$i(a,u,i);break e}}else for(null!==(w=u.child)&&(w.return=u);null!==w;){var C=w.dependencies;if(null!==C){x=w.child;for(var _=C.firstContext;null!==_;){if(_.context===o){if(1===w.tag){(_=ch(-1,i&-i)).tag=2;var j=w.updateQueue;if(null!==j){var z=(j=j.shared).pending;null===z?_.next=_:(_.next=z.next,z.next=_),j.pending=_}}w.lanes|=i,null!==(_=w.alternate)&&(_.lanes|=i),Sg(w.return,i,u),C.lanes|=i;break}_=_.next}}else if(10===w.tag)x=w.type===u.type?null:w.child;else if(18===w.tag){if(null===(x=w.return))throw Error(p(341));x.lanes|=i,null!==(C=x.alternate)&&(C.lanes|=i),Sg(x,i,u),x=w.sibling}else x=w.child;if(null!==x)x.return=w;else for(x=w;null!==x;){if(x===u){x=null;break}if(null!==(w=x.sibling)){w.return=x.return,x=w;break}x=x.return}w=x}}Yi(a,u,s.children,i),u=u.child}return u;case 9:return s=u.type,o=u.pendingProps.children,Tg(u,i),o=o(s=Vg(s)),u.flags|=1,Yi(a,u,o,i),u.child;case 14:return s=Lg(o=u.type,u.pendingProps),s=Lg(o.type,s),aj(a,u,o,s,i);case 15:return cj(a,u,u.type,u.pendingProps,i);case 17:return o=u.type,s=u.pendingProps,s=u.elementType===o?s:Lg(o,s),jj(a,u),u.tag=1,Zf(o)?(a=!0,cg(u)):a=!1,Tg(u,i),ph(u,o,s),rh(u,o,s,i),kj(null,u,o,!0,a,i);case 19:return yj(a,u,i);case 22:return ej(a,u,i)}throw Error(p(156,u.tag))};var lp="function"==typeof reportError?reportError:function(a){console.error(a)};function ml(a){this._internalRoot=a}function nl(a){this._internalRoot=a}function ol(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType)}function pl(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}function ql(){}function rl(a,u,i,o,s){if(s){if("function"==typeof o){var w=o;o=function(){var a=hl(x);w.call(a)}}var x=fl(u,o,a,0,null,!1,!1,"",ql);return a._reactRootContainer=x,a[tR]=x.current,sf(8===a.nodeType?a.parentNode:a),Sk(),x}for(;s=a.lastChild;)a.removeChild(s);if("function"==typeof o){var C=o;o=function(){var a=hl(_);C.call(a)}}var _=cl(a,0,!1,null,null,!1,!1,"",ql);return a._reactRootContainer=_,a[tR]=_.current,sf(8===a.nodeType?a.parentNode:a),Sk(function(){gl(u,_,i,o)}),_}function sl(a,u,i,o,s){var w=i._reactRootContainer;if(w){var x=w;if("function"==typeof s){var C=s;s=function(){var a=hl(x);C.call(a)}}gl(u,x,a,s)}else x=rl(i,u,a,s,o);return hl(x)}nl.prototype.render=ml.prototype.render=function(a){var u=this._internalRoot;if(null===u)throw Error(p(409));gl(a,u,null,null)},nl.prototype.unmount=ml.prototype.unmount=function(){var a=this._internalRoot;if(null!==a){this._internalRoot=null;var u=a.containerInfo;Sk(function(){gl(null,a,null,null)}),u[tR]=null}},nl.prototype.unstable_scheduleHydration=function(a){if(a){var u=nr();a={blockedOn:null,target:a,priority:u};for(var i=0;i<nv.length&&0!==u&&u<nv[i].priority;i++);nv.splice(i,0,a),0===i&&Vc(a)}},e7=function(a){switch(a.tag){case 3:var u=a.stateNode;if(u.current.memoizedState.isDehydrated){var i=tc(u.pendingLanes);0!==i&&(Cc(u,1|i),Ek(u,eG()),0==(6&rq)&&(le=eG()+500,jg()))}break;case 13:Sk(function(){var u=Zg(a,1);null!==u&&mh(u,a,1,L())}),jl(a,1)}},nn=function(a){if(13===a.tag){var u=Zg(a,134217728);null!==u&&mh(u,a,134217728,L()),jl(a,134217728)}},nt=function(a){if(13===a.tag){var u=lh(a),i=Zg(a,u);null!==i&&mh(i,a,u,L()),jl(a,u)}},nr=function(){return e9},na=function(a,u){var i=e9;try{return e9=a,u()}finally{e9=i}},eD=function(a,u,i){switch(u){case"input":if(bb(a,i),u=i.name,"radio"===i.type&&null!=u){for(i=a;i.parentNode;)i=i.parentNode;for(i=i.querySelectorAll("input[name="+JSON.stringify(""+u)+'][type="radio"]'),u=0;u<i.length;u++){var o=i[u];if(o!==a&&o.form===a.form){var s=Db(o);if(!s)throw Error(p(90));Wa(o),bb(o,s)}}}break;case"textarea":ib(a,i);break;case"select":null!=(u=i.value)&&fb(a,!!i.multiple,u,!1)}},Gb=Rk,Hb=Sk;var lg={findFiberByHostInstance:Wc,bundleType:0,version:"18.2.0",rendererPackageName:"react-dom"},lm={bundleType:lg.bundleType,version:lg.version,rendererPackageName:lg.rendererPackageName,rendererConfig:lg.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:en.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){return null===(a=Zb(a))?null:a.stateNode},findFiberByHostInstance:lg.findFiberByHostInstance||kl,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0-next-9e3b772b8-20220608"};if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var lv=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!lv.isDisabled&&lv.supportsFiber)try{e1=lv.inject(lm),e2=lv}catch(a){}}u.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED={usingClientEntryPoint:!1,Events:[Cb,ue,Db,Eb,Fb,Rk]},u.createPortal=function(a,u){var i=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!ol(u))throw Error(p(200));return dl(a,u,null,i)},u.createRoot=function(a,u){if(!ol(a))throw Error(p(299));var i=!1,o="",s=lp;return null!=u&&(!0===u.unstable_strictMode&&(i=!0),void 0!==u.identifierPrefix&&(o=u.identifierPrefix),void 0!==u.onRecoverableError&&(s=u.onRecoverableError)),u=cl(a,1,!1,null,null,i,!1,o,s),a[tR]=u.current,sf(8===a.nodeType?a.parentNode:a),new ml(u)},u.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var u=a._reactInternals;if(void 0===u){if("function"==typeof a.render)throw Error(p(188));throw Error(p(268,a=Object.keys(a).join(",")))}return a=null===(a=Zb(u))?null:a.stateNode},u.flushSync=function(a){return Sk(a)},u.hydrate=function(a,u,i){if(!pl(u))throw Error(p(200));return sl(null,a,u,!0,i)},u.hydrateRoot=function(a,u,i){if(!ol(a))throw Error(p(405));var o=null!=i&&i.hydratedSources||null,s=!1,w="",x=lp;if(null!=i&&(!0===i.unstable_strictMode&&(s=!0),void 0!==i.identifierPrefix&&(w=i.identifierPrefix),void 0!==i.onRecoverableError&&(x=i.onRecoverableError)),u=fl(u,null,a,1,null!=i?i:null,s,!1,w,x),a[tR]=u.current,sf(a),o)for(a=0;a<o.length;a++)s=(s=(i=o[a])._getVersion)(i._source),null==u.mutableSourceEagerHydrationData?u.mutableSourceEagerHydrationData=[i,s]:u.mutableSourceEagerHydrationData.push(i,s);return new nl(u)},u.render=function(a,u,i){if(!pl(u))throw Error(p(200));return sl(null,a,u,!1,i)},u.unmountComponentAtNode=function(a){if(!pl(a))throw Error(p(40));return!!a._reactRootContainer&&(Sk(function(){sl(null,null,a,!1,function(){a._reactRootContainer=null,a[tR]=null})}),!0)},u.unstable_batchedUpdates=Rk,u.unstable_renderSubtreeIntoContainer=function(a,u,i,o){if(!pl(i))throw Error(p(200));if(null==a||void 0===a._reactInternals)throw Error(p(38));return sl(a,u,i,!1,o)},u.version="18.2.0-next-9e3b772b8-20220608"},745:function(a,u,i){var o=i(3935);u.createRoot=o.createRoot,u.hydrateRoot=o.hydrateRoot},3935:function(a,u,i){function checkDCE(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE)}catch(a){console.error(a)}}checkDCE(),a.exports=i(4448)},2408:function(a,u){/** * @license React * react.production.min.js * @@ -14,7 +14,7 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var t=Symbol.for("react.element"),r=Symbol.for("react.portal"),l=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),u=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),i=Symbol.for("react.context"),s=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),p=Symbol.iterator,m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},h=Object.assign,g={};function v(e,n,t){this.props=e,this.context=n,this.refs=g,this.updater=t||m}function y(){}function b(e,n,t){this.props=e,this.context=n,this.refs=g,this.updater=t||m}v.prototype.isReactComponent={},v.prototype.setState=function(e,n){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,n,"setState")},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},y.prototype=v.prototype;var k=b.prototype=new y;k.constructor=b,h(k,v.prototype),k.isPureReactComponent=!0;var w=Array.isArray,S=Object.prototype.hasOwnProperty,x={current:null},E={key:!0,ref:!0,__self:!0,__source:!0};function C(e,n,r){var l,a={},u=null,o=null;if(null!=n)for(l in void 0!==n.ref&&(o=n.ref),void 0!==n.key&&(u=""+n.key),n)S.call(n,l)&&!E.hasOwnProperty(l)&&(a[l]=n[l]);var i=arguments.length-2;if(1===i)a.children=r;else if(1<i){for(var s=Array(i),c=0;c<i;c++)s[c]=arguments[c+2];a.children=s}if(e&&e.defaultProps)for(l in i=e.defaultProps)void 0===a[l]&&(a[l]=i[l]);return{$$typeof:t,type:e,key:u,ref:o,props:a,_owner:x.current}}function _(e){return"object"==typeof e&&null!==e&&e.$$typeof===t}var P=/\/+/g;function N(e,n){var t,r;return"object"==typeof e&&null!==e&&null!=e.key?(t=""+e.key,r={"=":"=0",":":"=2"},"$"+t.replace(/[=:]/g,function(e){return r[e]})):n.toString(36)}function z(e,n,l){if(null==e)return e;var a=[],u=0;return!function e(n,l,a,u,o){var i,s,c,f=typeof n;("undefined"===f||"boolean"===f)&&(n=null);var d=!1;if(null===n)d=!0;else switch(f){case"string":case"number":d=!0;break;case"object":switch(n.$$typeof){case t:case r:d=!0}}if(d)return o=o(d=n),n=""===u?"."+N(d,0):u,w(o)?(a="",null!=n&&(a=n.replace(P,"$&/")+"/"),e(o,l,a,"",function(e){return e})):null!=o&&(_(o)&&(i=o,s=a+(!o.key||d&&d.key===o.key?"":(""+o.key).replace(P,"$&/")+"/")+n,o={$$typeof:t,type:i.type,key:s,ref:i.ref,props:i.props,_owner:i._owner}),l.push(o)),1;if(d=0,u=""===u?".":u+":",w(n))for(var m=0;m<n.length;m++){f=n[m];var h=u+N(f,m);d+=e(f,l,a,h,o)}else if("function"==typeof(h=null===(c=n)||"object"!=typeof c?null:"function"==typeof(c=p&&c[p]||c["@@iterator"])?c:null))for(n=h.call(n),m=0;!(f=n.next()).done;)h=u+N(f=f.value,m++),d+=e(f,l,a,h,o);else if("object"===f)throw Error("Objects are not valid as a React child (found: "+("[object Object]"===(l=String(n))?"object with keys {"+Object.keys(n).join(", ")+"}":l)+"). If you meant to render a collection of children, use an array instead.");return d}(e,a,"","",function(e){return n.call(l,e,u++)}),a}function T(e){if(-1===e._status){var n=e._result;(n=n()).then(function(n){(0===e._status||-1===e._status)&&(e._status=1,e._result=n)},function(n){(0===e._status||-1===e._status)&&(e._status=2,e._result=n)}),-1===e._status&&(e._status=0,e._result=n)}if(1===e._status)return e._result.default;throw e._result}var L={current:null},R={transition:null};n.Children={map:z,forEach:function(e,n,t){z(e,function(){n.apply(this,arguments)},t)},count:function(e){var n=0;return z(e,function(){n++}),n},toArray:function(e){return z(e,function(e){return e})||[]},only:function(e){if(!_(e))throw Error("React.Children.only expected to receive a single React element child.");return e}},n.Component=v,n.Fragment=l,n.Profiler=u,n.PureComponent=b,n.StrictMode=a,n.Suspense=c,n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED={ReactCurrentDispatcher:L,ReactCurrentBatchConfig:R,ReactCurrentOwner:x},n.cloneElement=function(e,n,r){if(null==e)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var l=h({},e.props),a=e.key,u=e.ref,o=e._owner;if(null!=n){if(void 0!==n.ref&&(u=n.ref,o=x.current),void 0!==n.key&&(a=""+n.key),e.type&&e.type.defaultProps)var i=e.type.defaultProps;for(s in n)S.call(n,s)&&!E.hasOwnProperty(s)&&(l[s]=void 0===n[s]&&void 0!==i?i[s]:n[s])}var s=arguments.length-2;if(1===s)l.children=r;else if(1<s){i=Array(s);for(var c=0;c<s;c++)i[c]=arguments[c+2];l.children=i}return{$$typeof:t,type:e.type,key:a,ref:u,props:l,_owner:o}},n.createContext=function(e){return(e={$$typeof:i,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:o,_context:e},e.Consumer=e},n.createElement=C,n.createFactory=function(e){var n=C.bind(null,e);return n.type=e,n},n.createRef=function(){return{current:null}},n.forwardRef=function(e){return{$$typeof:s,render:e}},n.isValidElement=_,n.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:T}},n.memo=function(e,n){return{$$typeof:f,type:e,compare:void 0===n?null:n}},n.startTransition=function(e){var n=R.transition;R.transition={};try{e()}finally{R.transition=n}},n.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.")},n.useCallback=function(e,n){return L.current.useCallback(e,n)},n.useContext=function(e){return L.current.useContext(e)},n.useDebugValue=function(){},n.useDeferredValue=function(e){return L.current.useDeferredValue(e)},n.useEffect=function(e,n){return L.current.useEffect(e,n)},n.useId=function(){return L.current.useId()},n.useImperativeHandle=function(e,n,t){return L.current.useImperativeHandle(e,n,t)},n.useInsertionEffect=function(e,n){return L.current.useInsertionEffect(e,n)},n.useLayoutEffect=function(e,n){return L.current.useLayoutEffect(e,n)},n.useMemo=function(e,n){return L.current.useMemo(e,n)},n.useReducer=function(e,n,t){return L.current.useReducer(e,n,t)},n.useRef=function(e){return L.current.useRef(e)},n.useState=function(e){return L.current.useState(e)},n.useSyncExternalStore=function(e,n,t){return L.current.useSyncExternalStore(e,n,t)},n.useTransition=function(){return L.current.useTransition()},n.version="18.2.0"},7294:function(e,n,t){e.exports=t(2408)},53:function(e,n){/** + */var i=Symbol.for("react.element"),o=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),w=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),C=Symbol.for("react.provider"),_=Symbol.for("react.context"),j=Symbol.for("react.forward_ref"),z=Symbol.for("react.suspense"),P=Symbol.for("react.memo"),U=Symbol.for("react.lazy"),V=Symbol.iterator;function A(a){return null===a||"object"!=typeof a?null:"function"==typeof(a=V&&a[V]||a["@@iterator"])?a:null}var B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},$=Object.assign,Y={};function E(a,u,i){this.props=a,this.context=u,this.refs=Y,this.updater=i||B}function F(){}function G(a,u,i){this.props=a,this.context=u,this.refs=Y,this.updater=i||B}E.prototype.isReactComponent={},E.prototype.setState=function(a,u){if("object"!=typeof a&&"function"!=typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,u,"setState")},E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")},F.prototype=E.prototype;var Z=G.prototype=new F;Z.constructor=G,$(Z,E.prototype),Z.isPureReactComponent=!0;var X=Array.isArray,ee=Object.prototype.hasOwnProperty,en={current:null},et={key:!0,ref:!0,__self:!0,__source:!0};function M(a,u,o){var s,w={},x=null,C=null;if(null!=u)for(s in void 0!==u.ref&&(C=u.ref),void 0!==u.key&&(x=""+u.key),u)ee.call(u,s)&&!et.hasOwnProperty(s)&&(w[s]=u[s]);var _=arguments.length-2;if(1===_)w.children=o;else if(1<_){for(var j=Array(_),z=0;z<_;z++)j[z]=arguments[z+2];w.children=j}if(a&&a.defaultProps)for(s in _=a.defaultProps)void 0===w[s]&&(w[s]=_[s]);return{$$typeof:i,type:a,key:x,ref:C,props:w,_owner:en.current}}function N(a,u){return{$$typeof:i,type:a.type,key:u,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return"object"==typeof a&&null!==a&&a.$$typeof===i}function escape(a){var u={"=":"=0",":":"=2"};return"$"+a.replace(/[=:]/g,function(a){return u[a]})}var er=/\/+/g;function Q(a,u){return"object"==typeof a&&null!==a&&null!=a.key?escape(""+a.key):u.toString(36)}function R(a,u,s,w,x){var C=typeof a;("undefined"===C||"boolean"===C)&&(a=null);var _=!1;if(null===a)_=!0;else switch(C){case"string":case"number":_=!0;break;case"object":switch(a.$$typeof){case i:case o:_=!0}}if(_)return x=x(_=a),a=""===w?"."+Q(_,0):w,X(x)?(s="",null!=a&&(s=a.replace(er,"$&/")+"/"),R(x,u,s,"",function(a){return a})):null!=x&&(O(x)&&(x=N(x,s+(!x.key||_&&_.key===x.key?"":(""+x.key).replace(er,"$&/")+"/")+a)),u.push(x)),1;if(_=0,w=""===w?".":w+":",X(a))for(var j=0;j<a.length;j++){var z=w+Q(C=a[j],j);_+=R(C,u,s,z,x)}else if("function"==typeof(z=A(a)))for(a=z.call(a),j=0;!(C=a.next()).done;)z=w+Q(C=C.value,j++),_+=R(C,u,s,z,x);else if("object"===C)throw Error("Objects are not valid as a React child (found: "+("[object Object]"===(u=String(a))?"object with keys {"+Object.keys(a).join(", ")+"}":u)+"). If you meant to render a collection of children, use an array instead.");return _}function S(a,u,i){if(null==a)return a;var o=[],s=0;return R(a,o,"","",function(a){return u.call(i,a,s++)}),o}function T(a){if(-1===a._status){var u=a._result;(u=u()).then(function(u){(0===a._status||-1===a._status)&&(a._status=1,a._result=u)},function(u){(0===a._status||-1===a._status)&&(a._status=2,a._result=u)}),-1===a._status&&(a._status=0,a._result=u)}if(1===a._status)return a._result.default;throw a._result}var ea={current:null},eu={transition:null};u.Children={map:S,forEach:function(a,u,i){S(a,function(){u.apply(this,arguments)},i)},count:function(a){var u=0;return S(a,function(){u++}),u},toArray:function(a){return S(a,function(a){return a})||[]},only:function(a){if(!O(a))throw Error("React.Children.only expected to receive a single React element child.");return a}},u.Component=E,u.Fragment=s,u.Profiler=x,u.PureComponent=G,u.StrictMode=w,u.Suspense=z,u.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED={ReactCurrentDispatcher:ea,ReactCurrentBatchConfig:eu,ReactCurrentOwner:en},u.cloneElement=function(a,u,o){if(null==a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var s=$({},a.props),w=a.key,x=a.ref,C=a._owner;if(null!=u){if(void 0!==u.ref&&(x=u.ref,C=en.current),void 0!==u.key&&(w=""+u.key),a.type&&a.type.defaultProps)var _=a.type.defaultProps;for(j in u)ee.call(u,j)&&!et.hasOwnProperty(j)&&(s[j]=void 0===u[j]&&void 0!==_?_[j]:u[j])}var j=arguments.length-2;if(1===j)s.children=o;else if(1<j){_=Array(j);for(var z=0;z<j;z++)_[z]=arguments[z+2];s.children=_}return{$$typeof:i,type:a.type,key:w,ref:x,props:s,_owner:C}},u.createContext=function(a){return(a={$$typeof:_,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:C,_context:a},a.Consumer=a},u.createElement=M,u.createFactory=function(a){var u=M.bind(null,a);return u.type=a,u},u.createRef=function(){return{current:null}},u.forwardRef=function(a){return{$$typeof:j,render:a}},u.isValidElement=O,u.lazy=function(a){return{$$typeof:U,_payload:{_status:-1,_result:a},_init:T}},u.memo=function(a,u){return{$$typeof:P,type:a,compare:void 0===u?null:u}},u.startTransition=function(a){var u=eu.transition;eu.transition={};try{a()}finally{eu.transition=u}},u.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.")},u.useCallback=function(a,u){return ea.current.useCallback(a,u)},u.useContext=function(a){return ea.current.useContext(a)},u.useDebugValue=function(){},u.useDeferredValue=function(a){return ea.current.useDeferredValue(a)},u.useEffect=function(a,u){return ea.current.useEffect(a,u)},u.useId=function(){return ea.current.useId()},u.useImperativeHandle=function(a,u,i){return ea.current.useImperativeHandle(a,u,i)},u.useInsertionEffect=function(a,u){return ea.current.useInsertionEffect(a,u)},u.useLayoutEffect=function(a,u){return ea.current.useLayoutEffect(a,u)},u.useMemo=function(a,u){return ea.current.useMemo(a,u)},u.useReducer=function(a,u,i){return ea.current.useReducer(a,u,i)},u.useRef=function(a){return ea.current.useRef(a)},u.useState=function(a){return ea.current.useState(a)},u.useSyncExternalStore=function(a,u,i){return ea.current.useSyncExternalStore(a,u,i)},u.useTransition=function(){return ea.current.useTransition()},u.version="18.2.0"},7294:function(a,u,i){a.exports=i(2408)},53:function(a,u){/** * @license React * scheduler.production.min.js * @@ -22,4 +22,4 @@ * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */function t(e,n){var t=e.length;e.push(n);e:for(;0<t;){var r=t-1>>>1,l=e[r];if(0<a(l,n))e[r]=n,e[t]=l,t=r;else break e}}function r(e){return 0===e.length?null:e[0]}function l(e){if(0===e.length)return null;var n=e[0],t=e.pop();if(t!==n){e[0]=t;e:for(var r=0,l=e.length,u=l>>>1;r<u;){var o=2*(r+1)-1,i=e[o],s=o+1,c=e[s];if(0>a(i,t))s<l&&0>a(c,i)?(e[r]=c,e[s]=t,r=s):(e[r]=i,e[o]=t,r=o);else if(s<l&&0>a(c,t))e[r]=c,e[s]=t,r=s;else break e}}return n}function a(e,n){var t=e.sortIndex-n.sortIndex;return 0!==t?t:e.id-n.id}if("object"==typeof performance&&"function"==typeof performance.now){var u,o=performance;n.unstable_now=function(){return o.now()}}else{var i=Date,s=i.now();n.unstable_now=function(){return i.now()-s}}var c=[],f=[],d=1,p=null,m=3,h=!1,g=!1,v=!1,y="function"==typeof setTimeout?setTimeout:null,b="function"==typeof clearTimeout?clearTimeout:null,k="undefined"!=typeof setImmediate?setImmediate:null;function w(e){for(var n=r(f);null!==n;){if(null===n.callback)l(f);else if(n.startTime<=e)l(f),n.sortIndex=n.expirationTime,t(c,n);else break;n=r(f)}}function S(e){if(v=!1,w(e),!g){if(null!==r(c))g=!0,M(x);else{var n=r(f);null!==n&&F(S,n.startTime-e)}}}function x(e,t){g=!1,v&&(v=!1,b(_),_=-1),h=!0;var a=m;try{for(w(t),p=r(c);null!==p&&(!(p.expirationTime>t)||e&&!z());){var u=p.callback;if("function"==typeof u){p.callback=null,m=p.priorityLevel;var o=u(p.expirationTime<=t);t=n.unstable_now(),"function"==typeof o?p.callback=o:p===r(c)&&l(c),w(t)}else l(c);p=r(c)}if(null!==p)var i=!0;else{var s=r(f);null!==s&&F(S,s.startTime-t),i=!1}return i}finally{p=null,m=a,h=!1}}"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var E=!1,C=null,_=-1,P=5,N=-1;function z(){return!(n.unstable_now()-N<P)}function T(){if(null!==C){var e=n.unstable_now();N=e;var t=!0;try{t=C(!0,e)}finally{t?u():(E=!1,C=null)}}else E=!1}if("function"==typeof k)u=function(){k(T)};else if("undefined"!=typeof MessageChannel){var L=new MessageChannel,R=L.port2;L.port1.onmessage=T,u=function(){R.postMessage(null)}}else u=function(){y(T,0)};function M(e){C=e,E||(E=!0,u())}function F(e,t){_=y(function(){e(n.unstable_now())},t)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(e){e.callback=null},n.unstable_continueExecution=function(){g||h||(g=!0,M(x))},n.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):P=0<e?Math.floor(1e3/e):5},n.unstable_getCurrentPriorityLevel=function(){return m},n.unstable_getFirstCallbackNode=function(){return r(c)},n.unstable_next=function(e){switch(m){case 1:case 2:case 3:var n=3;break;default:n=m}var t=m;m=n;try{return e()}finally{m=t}},n.unstable_pauseExecution=function(){},n.unstable_requestPaint=function(){},n.unstable_runWithPriority=function(e,n){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var t=m;m=e;try{return n()}finally{m=t}},n.unstable_scheduleCallback=function(e,l,a){var u=n.unstable_now();switch(a="object"==typeof a&&null!==a&&"number"==typeof(a=a.delay)&&0<a?u+a:u,e){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return o=a+o,e={id:d++,callback:l,priorityLevel:e,startTime:a,expirationTime:o,sortIndex:-1},a>u?(e.sortIndex=a,t(f,e),null===r(c)&&e===r(f)&&(v?(b(_),_=-1):v=!0,F(S,a-u))):(e.sortIndex=o,t(c,e),g||h||(g=!0,M(x))),e},n.unstable_shouldYield=z,n.unstable_wrapCallback=function(e){var n=m;return function(){var t=m;m=n;try{return e.apply(this,arguments)}finally{m=t}}}},3840:function(e,n,t){e.exports=t(53)}}]); \ No newline at end of file + */function f(a,u){var i=a.length;for(a.push(u);0<i;){var o=i-1>>>1,s=a[o];if(0<g(s,u))a[o]=u,a[i]=s,i=o;else break}}function h(a){return 0===a.length?null:a[0]}function k(a){if(0===a.length)return null;var u=a[0],i=a.pop();if(i!==u){a[0]=i;for(var o=0,s=a.length,w=s>>>1;o<w;){var x=2*(o+1)-1,C=a[x],_=x+1,j=a[_];if(0>g(C,i))_<s&&0>g(j,C)?(a[o]=j,a[_]=i,o=_):(a[o]=C,a[x]=i,o=x);else if(_<s&&0>g(j,i))a[o]=j,a[_]=i,o=_;else break}}return u}function g(a,u){var i=a.sortIndex-u.sortIndex;return 0!==i?i:a.id-u.id}if("object"==typeof performance&&"function"==typeof performance.now){var i,o=performance;u.unstable_now=function(){return o.now()}}else{var s=Date,w=s.now();u.unstable_now=function(){return s.now()-w}}var x=[],C=[],_=1,j=null,z=3,P=!1,U=!1,V=!1,B="function"==typeof setTimeout?setTimeout:null,$="function"==typeof clearTimeout?clearTimeout:null,Y="undefined"!=typeof setImmediate?setImmediate:null;function G(a){for(var u=h(C);null!==u;){if(null===u.callback)k(C);else if(u.startTime<=a)k(C),u.sortIndex=u.expirationTime,f(x,u);else break;u=h(C)}}function H(a){if(V=!1,G(a),!U){if(null!==h(x))U=!0,I(J);else{var u=h(C);null!==u&&K(H,u.startTime-a)}}}function J(a,i){U=!1,V&&(V=!1,$(ee),ee=-1),P=!0;var o=z;try{for(G(i),j=h(x);null!==j&&(!(j.expirationTime>i)||a&&!M());){var s=j.callback;if("function"==typeof s){j.callback=null,z=j.priorityLevel;var w=s(j.expirationTime<=i);i=u.unstable_now(),"function"==typeof w?j.callback=w:j===h(x)&&k(x),G(i)}else k(x);j=h(x)}if(null!==j)var _=!0;else{var B=h(C);null!==B&&K(H,B.startTime-i),_=!1}return _}finally{j=null,z=o,P=!1}}"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var Z=!1,X=null,ee=-1,en=5,et=-1;function M(){return!(u.unstable_now()-et<en)}function R(){if(null!==X){var a=u.unstable_now();et=a;var o=!0;try{o=X(!0,a)}finally{o?i():(Z=!1,X=null)}}else Z=!1}if("function"==typeof Y)i=function(){Y(R)};else if("undefined"!=typeof MessageChannel){var er=new MessageChannel,ea=er.port2;er.port1.onmessage=R,i=function(){ea.postMessage(null)}}else i=function(){B(R,0)};function I(a){X=a,Z||(Z=!0,i())}function K(a,i){ee=B(function(){a(u.unstable_now())},i)}u.unstable_IdlePriority=5,u.unstable_ImmediatePriority=1,u.unstable_LowPriority=4,u.unstable_NormalPriority=3,u.unstable_Profiling=null,u.unstable_UserBlockingPriority=2,u.unstable_cancelCallback=function(a){a.callback=null},u.unstable_continueExecution=function(){U||P||(U=!0,I(J))},u.unstable_forceFrameRate=function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):en=0<a?Math.floor(1e3/a):5},u.unstable_getCurrentPriorityLevel=function(){return z},u.unstable_getFirstCallbackNode=function(){return h(x)},u.unstable_next=function(a){switch(z){case 1:case 2:case 3:var u=3;break;default:u=z}var i=z;z=u;try{return a()}finally{z=i}},u.unstable_pauseExecution=function(){},u.unstable_requestPaint=function(){},u.unstable_runWithPriority=function(a,u){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var i=z;z=a;try{return u()}finally{z=i}},u.unstable_scheduleCallback=function(a,i,o){var s=u.unstable_now();switch(o="object"==typeof o&&null!==o&&"number"==typeof(o=o.delay)&&0<o?s+o:s,a){case 1:var w=-1;break;case 2:w=250;break;case 5:w=1073741823;break;case 4:w=1e4;break;default:w=5e3}return w=o+w,a={id:_++,callback:i,priorityLevel:a,startTime:o,expirationTime:w,sortIndex:-1},o>s?(a.sortIndex=o,f(C,a),null===h(x)&&a===h(C)&&(V?($(ee),ee=-1):V=!0,K(H,o-s))):(a.sortIndex=w,f(x,a),U||P||(U=!0,I(J))),a},u.unstable_shouldYield=M,u.unstable_wrapCallback=function(a){var u=z;return function(){var i=z;z=u;try{return a.apply(this,arguments)}finally{z=i}}}},3840:function(a,u,i){a.exports=i(53)}}]); \ No newline at end of file diff --git a/.next/static/chunks/main-07bf56c05aa7cd6e.js b/.next/static/chunks/main-07bf56c05aa7cd6e.js new file mode 100644 index 0000000..114c633 --- /dev/null +++ b/.next/static/chunks/main-07bf56c05aa7cd6e.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[179],{4878:function(r,n){"use strict";function getDeploymentIdQueryOrEmptyString(){return""}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"getDeploymentIdQueryOrEmptyString",{enumerable:!0,get:function(){return getDeploymentIdQueryOrEmptyString}})},37:function(){"trimStart"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),"trimEnd"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),"description"in Symbol.prototype||Object.defineProperty(Symbol.prototype,"description",{configurable:!0,get:function(){var r=/\((.*)\)/.exec(this.toString());return r?r[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(r,n){return n=this.concat.apply([],this),r>1&&n.some(Array.isArray)?n.flat(r-1):n},Array.prototype.flatMap=function(r,n){return this.map(r,n).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(r){if("function"!=typeof r)return this.then(r,r);var n=this.constructor||Promise;return this.then(function(o){return n.resolve(r()).then(function(){return o})},function(o){return n.resolve(r()).then(function(){throw o})})}),Object.fromEntries||(Object.fromEntries=function(r){return Array.from(r).reduce(function(r,n){return r[n[0]]=n[1],r},{})}),Array.prototype.at||(Array.prototype.at=function(r){var n=Math.trunc(r)||0;if(n<0&&(n+=this.length),!(n<0||n>=this.length))return this[n]})},5864:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"addBasePath",{enumerable:!0,get:function(){return addBasePath}});let l=o(3776),u=o(2955);function addBasePath(r,n){return(0,u.normalizePathTrailingSlash)((0,l.addPathPrefix)(r,""))}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},2048:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"addLocale",{enumerable:!0,get:function(){return addLocale}}),o(2955);let addLocale=function(r){for(var n=arguments.length,o=Array(n>1?n-1:0),l=1;l<n;l++)o[l-1]=arguments[l];return r};("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},4287:function(r,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"detectDomainLocale",{enumerable:!0,get:function(){return detectDomainLocale}});let detectDomainLocale=function(){for(var r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o]};("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},6948:function(r,n){"use strict";let o;Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{addMessageListener:function(){return addMessageListener},sendMessage:function(){return sendMessage},connectHMR:function(){return connectHMR}});let l=[];function getSocketProtocol(r){let n=location.protocol;try{n=new URL(r).protocol}catch(r){}return"http:"===n?"ws":"wss"}function addMessageListener(r){l.push(r)}function sendMessage(r){if(o&&o.readyState===o.OPEN)return o.send(r)}let u=0;function connectHMR(r){function init(){let n;function handleOnline(){u=0,window.console.log("[HMR] connected")}function handleMessage(r){let n=JSON.parse(r.data);for(let r of l)r(n)}function handleDisconnect(){if(o.onerror=null,o.onclose=null,o.close(),++u>25){window.location.reload();return}clearTimeout(n),n=setTimeout(init,u>5?5e3:1e3)}o&&o.close();let{hostname:s,port:d}=location,f=getSocketProtocol(r.assetPrefix||""),h=r.assetPrefix.replace(/^\/+/,""),g=f+"://"+s+":"+d+(h?"/"+h:"");h.startsWith("http")&&(g=f+"://"+h.split("://",2)[1]),(o=new window.WebSocket(""+g+r.path)).onopen=handleOnline,o.onerror=handleDisconnect,o.onclose=handleDisconnect,o.onmessage=handleMessage}init()}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},5213:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"hasBasePath",{enumerable:!0,get:function(){return hasBasePath}});let l=o(6315);function hasBasePath(r){return(0,l.pathHasPrefix)(r,"")}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},4477:function(r,n){"use strict";let o;Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{DOMAttributeNames:function(){return l},isEqualNode:function(){return isEqualNode},default:function(){return initHeadManager}});let l={acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv",noModule:"noModule"};function reactElementToDOM(r){let{type:n,props:o}=r,u=document.createElement(n);for(let r in o){if(!o.hasOwnProperty(r)||"children"===r||"dangerouslySetInnerHTML"===r||void 0===o[r])continue;let s=l[r]||r.toLowerCase();"script"===n&&("async"===s||"defer"===s||"noModule"===s)?u[s]=!!o[r]:u.setAttribute(s,o[r])}let{children:s,dangerouslySetInnerHTML:d}=o;return d?u.innerHTML=d.__html||"":s&&(u.textContent="string"==typeof s?s:Array.isArray(s)?s.join(""):""),u}function isEqualNode(r,n){if(r instanceof HTMLElement&&n instanceof HTMLElement){let o=n.getAttribute("nonce");if(o&&!r.getAttribute("nonce")){let l=n.cloneNode(!0);return l.setAttribute("nonce",""),l.nonce=o,o===r.nonce&&r.isEqualNode(l)}}return r.isEqualNode(n)}function initHeadManager(){return{mountedInstances:new Set,updateHead:r=>{let n={};r.forEach(r=>{if("link"===r.type&&r.props["data-optimized-fonts"]){if(document.querySelector('style[data-href="'+r.props["data-href"]+'"]'))return;r.props.href=r.props["data-href"],r.props["data-href"]=void 0}let o=n[r.type]||[];o.push(r),n[r.type]=o});let l=n.title?n.title[0]:null,u="";if(l){let{children:r}=l.props;u="string"==typeof r?r:Array.isArray(r)?r.join(""):""}u!==document.title&&(document.title=u),["meta","base","link","style","script"].forEach(r=>{o(r,n[r]||[])})}}}o=(r,n)=>{let o=document.getElementsByTagName("head")[0],l=o.querySelector("meta[name=next-head-count]"),u=Number(l.content),s=[];for(let n=0,o=l.previousElementSibling;n<u;n++,o=(null==o?void 0:o.previousElementSibling)||null){var d;(null==o?void 0:null==(d=o.tagName)?void 0:d.toLowerCase())===r&&s.push(o)}let f=n.map(reactElementToDOM).filter(r=>{for(let n=0,o=s.length;n<o;n++){let o=s[n];if(isEqualNode(o,r))return s.splice(n,1),!1}return!0});s.forEach(r=>{var n;return null==(n=r.parentNode)?void 0:n.removeChild(r)}),f.forEach(r=>o.insertBefore(r,l)),l.content=(u-s.length+f.length).toString()},("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},223:function(r,n,o){"use strict";let l,u,s,d,f,h,g,_,y,P,b,E;Object.defineProperty(n,"__esModule",{value:!0});let S=o(1757);Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{version:function(){return J},router:function(){return l},emitter:function(){return Z},initialize:function(){return initialize},hydrate:function(){return hydrate}});let R=o(8754);o(37);let w=R._(o(7294)),O=R._(o(745)),j=o(7768),A=R._(o(3745)),M=o(637),C=o(9987),I=o(8011),x=o(4828),L=o(510),N=o(1306),D=o(5091),k=R._(o(4477)),F=R._(o(7375)),U=R._(o(3129)),H=o(9513),B=o(4751),W=o(676),q=o(4955),z=o(7786),G=o(5213),V=o(1158),X=o(7178),Y=o(8197),K=R._(o(2565)),Q=R._(o(2295)),$=R._(o(6077)),J="14.0.1",Z=(0,A.default)(),looseToArray=r=>[].slice.call(r),ee=!1;let Container=class Container extends w.default.Component{componentDidCatch(r,n){this.props.fn(r,n)}componentDidMount(){this.scrollToHash(),l.isSsr&&(u.isFallback||u.nextExport&&((0,I.isDynamicRoute)(l.pathname)||location.search||ee)||u.props&&u.props.__N_SSG&&(location.search||ee))&&l.replace(l.pathname+"?"+String((0,x.assign)((0,x.urlQueryToSearchParams)(l.query),new URLSearchParams(location.search))),s,{_h:1,shallow:!u.isFallback&&!ee}).catch(r=>{if(!r.cancelled)throw r})}componentDidUpdate(){this.scrollToHash()}scrollToHash(){let{hash:r}=location;if(!(r=r&&r.substring(1)))return;let n=document.getElementById(r);n&&setTimeout(()=>n.scrollIntoView(),0)}render(){return this.props.children}};async function initialize(r){void 0===r&&(r={}),Q.default.onSpanEnd($.default),u=JSON.parse(document.getElementById("__NEXT_DATA__").textContent),window.__NEXT_DATA__=u,E=u.defaultLocale;let n=u.assetPrefix||"";if(self.__next_set_public_path__(""+n+"/_next/"),(0,L.setConfig)({serverRuntimeConfig:{},publicRuntimeConfig:u.runtimeConfig||{}}),s=(0,N.getURL)(),(0,G.hasBasePath)(s)&&(s=(0,z.removeBasePath)(s)),u.scriptLoader){let{initScriptLoader:r}=o(2288);r(u.scriptLoader)}d=new F.default(u.buildId,n);let register=r=>{let[n,o]=r;return d.routeLoader.onEntrypoint(n,o)};return window.__NEXT_P&&window.__NEXT_P.map(r=>setTimeout(()=>register(r),0)),window.__NEXT_P=[],window.__NEXT_P.push=register,(h=(0,k.default)()).getIsSsr=()=>l.isSsr,f=document.getElementById("__next"),{assetPrefix:n}}function renderApp(r,n){return w.default.createElement(r,n)}function AppContainer(r){var n;let{children:o}=r,u=w.default.useMemo(()=>(0,X.adaptForAppRouterInstance)(l),[]);return w.default.createElement(Container,{fn:r=>renderError({App:y,err:r}).catch(r=>console.error("Error rendering page: ",r))},w.default.createElement(V.AppRouterContext.Provider,{value:u},w.default.createElement(Y.SearchParamsContext.Provider,{value:(0,X.adaptForSearchParams)(l)},w.default.createElement(X.PathnameContextProviderAdapter,{router:l,isAutoExport:null!=(n=self.__NEXT_DATA__.autoExport)&&n},w.default.createElement(Y.PathParamsContext.Provider,{value:(0,X.adaptForPathParams)(l)},w.default.createElement(M.RouterContext.Provider,{value:(0,B.makePublicRouterInstance)(l)},w.default.createElement(j.HeadManagerContext.Provider,{value:h},w.default.createElement(q.ImageConfigContext.Provider,{value:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1}},o))))))))}let wrapApp=r=>n=>{let o={...n,Component:b,err:u.err,router:l};return w.default.createElement(AppContainer,null,renderApp(r,o))};function renderError(r){let{App:n,err:f}=r;return console.error(f),console.error("A client-side exception has occurred, see here for more info: https://nextjs.org/docs/messages/client-side-exception-occurred"),d.loadPage("/_error").then(l=>{let{page:u,styleSheets:s}=l;return(null==g?void 0:g.Component)===u?Promise.resolve().then(()=>S._(o(4570))).then(l=>Promise.resolve().then(()=>S._(o(8955))).then(o=>(n=o.default,r.App=n,l))).then(r=>({ErrorComponent:r.default,styleSheets:[]})):{ErrorComponent:u,styleSheets:s}}).then(o=>{var d;let{ErrorComponent:h,styleSheets:g}=o,_=wrapApp(n),y={Component:h,AppTree:_,router:l,ctx:{err:f,pathname:u.page,query:u.query,asPath:s,AppTree:_}};return Promise.resolve((null==(d=r.props)?void 0:d.err)?r.props:(0,N.loadGetInitialProps)(n,y)).then(n=>doRender({...r,err:f,Component:h,styleSheets:g,props:n}))})}function Head(r){let{callback:n}=r;return w.default.useLayoutEffect(()=>n(),[n]),null}let et={navigationStart:"navigationStart",beforeRender:"beforeRender",afterRender:"afterRender",afterHydrate:"afterHydrate",routeChange:"routeChange"},er={hydration:"Next.js-hydration",beforeHydration:"Next.js-before-hydration",routeChangeToRender:"Next.js-route-change-to-render",render:"Next.js-render"},en=null,ea=!0;function clearMarks(){[et.beforeRender,et.afterHydrate,et.afterRender,et.routeChange].forEach(r=>performance.clearMarks(r))}function markHydrateComplete(){if(!N.ST)return;performance.mark(et.afterHydrate);let r=performance.getEntriesByName(et.beforeRender,"mark").length;r&&(performance.measure(er.beforeHydration,et.navigationStart,et.beforeRender),performance.measure(er.hydration,et.beforeRender,et.afterHydrate)),P&&performance.getEntriesByName(er.hydration).forEach(P),clearMarks()}function markRenderComplete(){if(!N.ST)return;performance.mark(et.afterRender);let r=performance.getEntriesByName(et.routeChange,"mark");if(!r.length)return;let n=performance.getEntriesByName(et.beforeRender,"mark").length;n&&(performance.measure(er.routeChangeToRender,r[0].name,et.beforeRender),performance.measure(er.render,et.beforeRender,et.afterRender),P&&(performance.getEntriesByName(er.render).forEach(P),performance.getEntriesByName(er.routeChangeToRender).forEach(P))),clearMarks(),[er.routeChangeToRender,er.render].forEach(r=>performance.clearMeasures(r))}function renderReactElement(r,n){N.ST&&performance.mark(et.beforeRender);let o=n(ea?markHydrateComplete:markRenderComplete);if(en){let r=w.default.startTransition;r(()=>{en.render(o)})}else en=O.default.hydrateRoot(r,o,{onRecoverableError:K.default}),ea=!1}function Root(r){let{callbacks:n,children:o}=r;return w.default.useLayoutEffect(()=>n.forEach(r=>r()),[n]),w.default.useEffect(()=>{(0,U.default)(P)},[]),o}function doRender(r){let n,{App:o,Component:u,props:s,err:d}=r,h="initial"in r?void 0:r.styleSheets;u=u||g.Component,s=s||g.props;let y={...s,Component:u,err:d,router:l};g=y;let P=!1,b=new Promise((r,o)=>{_&&_(),n=()=>{_=null,r()},_=()=>{P=!0,_=null;let r=Error("Cancel rendering route");r.cancelled=!0,o(r)}});function onHeadCommit(){if(h&&!P){let r=new Set(h.map(r=>r.href)),n=looseToArray(document.querySelectorAll("style[data-n-href]")),o=n.map(r=>r.getAttribute("data-n-href"));for(let l=0;l<o.length;++l)r.has(o[l])?n[l].removeAttribute("media"):n[l].setAttribute("media","x");let l=document.querySelector("noscript[data-n-css]");l&&h.forEach(r=>{let{href:n}=r,o=document.querySelector('style[data-n-href="'+n+'"]');o&&(l.parentNode.insertBefore(o,l.nextSibling),l=o)}),looseToArray(document.querySelectorAll("link[data-n-p]")).forEach(r=>{r.parentNode.removeChild(r)})}if(r.scroll){let{x:n,y:o}=r.scroll;(0,C.handleSmoothScroll)(()=>{window.scrollTo(n,o)})}}function onRootCommit(){n()}!function(){if(!h)return;let r=looseToArray(document.querySelectorAll("style[data-n-href]")),n=new Set(r.map(r=>r.getAttribute("data-n-href"))),o=document.querySelector("noscript[data-n-css]"),l=null==o?void 0:o.getAttribute("data-n-css");h.forEach(r=>{let{href:o,text:u}=r;if(!n.has(o)){let r=document.createElement("style");r.setAttribute("data-n-href",o),r.setAttribute("media","x"),l&&r.setAttribute("nonce",l),document.head.appendChild(r),r.appendChild(document.createTextNode(u))}})}();let E=w.default.createElement(w.default.Fragment,null,w.default.createElement(Head,{callback:onHeadCommit}),w.default.createElement(AppContainer,null,renderApp(o,y),w.default.createElement(D.Portal,{type:"next-route-announcer"},w.default.createElement(H.RouteAnnouncer,null))));return renderReactElement(f,r=>w.default.createElement(Root,{callbacks:[r,onRootCommit]},E)),b}async function render(r){if(r.err){await renderError(r);return}try{await doRender(r)}catch(o){let n=(0,W.getProperError)(o);if(n.cancelled)throw n;await renderError({...r,err:n})}}async function hydrate(r){let n=u.err;try{let r=await d.routeLoader.whenEntrypoint("/_app");if("error"in r)throw r.error;let{component:n,exports:o}=r;y=n,o&&o.reportWebVitals&&(P=r=>{let n,{id:l,name:u,startTime:s,value:d,duration:f,entryType:h,entries:g,attribution:_}=r,y=Date.now()+"-"+(Math.floor(Math.random()*(9e12-1))+1e12);g&&g.length&&(n=g[0].startTime);let P={id:l||y,name:u,startTime:s||n,value:null==d?f:d,label:"mark"===h||"measure"===h?"custom":"web-vital"};_&&(P.attribution=_),o.reportWebVitals(P)});let l=await d.routeLoader.whenEntrypoint(u.page);if("error"in l)throw l.error;b=l.component}catch(r){n=(0,W.getProperError)(r)}window.__NEXT_PRELOADREADY&&await window.__NEXT_PRELOADREADY(u.dynamicIds),l=(0,B.createRouter)(u.page,u.query,s,{initialProps:u.props,pageLoader:d,App:y,Component:b,wrapApp,err:n,isFallback:!!u.isFallback,subscription:(r,n,o)=>render(Object.assign({},r,{App:n,scroll:o})),locale:u.locale,locales:u.locales,defaultLocale:E,domainLocales:u.domainLocales,isPreview:u.isPreview}),ee=await l._initialMatchesMiddlewarePromise;let o={App:y,initial:!0,Component:b,props:u.props,err:n};(null==r?void 0:r.beforeRender)&&await r.beforeRender(),render(o)}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},6653:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),o(1867);let l=o(223);window.next={version:l.version,get router(){return l.router},emitter:l.emitter},(0,l.initialize)({}).then(()=>(0,l.hydrate)()).catch(console.error),("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},2955:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return normalizePathTrailingSlash}});let l=o(6082),u=o(891),normalizePathTrailingSlash=r=>{if(!r.startsWith("/"))return r;let{pathname:n,query:o,hash:s}=(0,u.parsePath)(r);return""+(0,l.removeTrailingSlash)(n)+o+s};("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},2565:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return onRecoverableError}});let l=o(4600);function onRecoverableError(r){let n="function"==typeof reportError?reportError:r=>{window.console.error(r)};r.digest!==l.NEXT_DYNAMIC_NO_SSR_CODE&&n(r)}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},7375:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return PageLoader}});let l=o(8754),u=o(5864),s=o(9381),d=l._(o(8052)),f=o(2048),h=o(8011),g=o(9823),_=o(6082),y=o(7159);o(729);let PageLoader=class PageLoader{getPageList(){return(0,y.getClientBuildManifest)().then(r=>r.sortedPages)}getMiddleware(){return window.__MIDDLEWARE_MATCHERS=[],window.__MIDDLEWARE_MATCHERS}getDataHref(r){let{asPath:n,href:o,locale:l}=r,{pathname:y,query:P,search:b}=(0,g.parseRelativeUrl)(o),{pathname:E}=(0,g.parseRelativeUrl)(n),S=(0,_.removeTrailingSlash)(y);if("/"!==S[0])throw Error('Route name should start with a "/", got "'+S+'"');return(r=>{let n=(0,d.default)((0,_.removeTrailingSlash)((0,f.addLocale)(r,l)),".json");return(0,u.addBasePath)("/_next/data/"+this.buildId+n+b,!0)})(r.skipInterpolation?E:(0,h.isDynamicRoute)(S)?(0,s.interpolateAs)(y,E,P).result:S)}_isSsg(r){return this.promisedSsgManifest.then(n=>n.has(r))}loadPage(r){return this.routeLoader.loadRoute(r).then(r=>{if("component"in r)return{page:r.component,mod:r.exports,styleSheets:r.styles.map(r=>({href:r.href,text:r.content}))};throw r.error})}prefetch(r){return this.routeLoader.prefetch(r)}constructor(r,n){this.routeLoader=(0,y.createRouteLoader)(n),this.buildId=r,this.assetPrefix=n,this.promisedSsgManifest=new Promise(r=>{window.__SSG_MANIFEST?r(window.__SSG_MANIFEST):window.__SSG_MANIFEST_CB=()=>{r(window.__SSG_MANIFEST)}})}};("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},3129:function(r,n,o){"use strict";let l;Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return _default}});let u=["CLS","FCP","FID","INP","LCP","TTFB"];location.href;let s=!1;function onReport(r){l&&l(r)}let _default=r=>{if(l=r,!s)for(let r of(s=!0,u))try{let n;n||(n=o(8018)),n["on"+r](onReport)}catch(n){console.warn("Failed to track "+r+" web-vital",n)}};("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},5091:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"Portal",{enumerable:!0,get:function(){return Portal}});let l=o(7294),u=o(3935),Portal=r=>{let{children:n,type:o}=r,[s,d]=(0,l.useState)(null);return(0,l.useEffect)(()=>{let r=document.createElement(o);return document.body.appendChild(r),d(r),()=>{document.body.removeChild(r)}},[o]),s?(0,u.createPortal)(n,s):null};("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},7786:function(r,n,o){"use strict";function removeBasePath(r){return r}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"removeBasePath",{enumerable:!0,get:function(){return removeBasePath}}),o(5213),("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},3099:function(r,n,o){"use strict";function removeLocale(r,n){return r}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"removeLocale",{enumerable:!0,get:function(){return removeLocale}}),o(891),("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},3767:function(r,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{requestIdleCallback:function(){return o},cancelIdleCallback:function(){return l}});let o="undefined"!=typeof self&&self.requestIdleCallback&&self.requestIdleCallback.bind(window)||function(r){let n=Date.now();return self.setTimeout(function(){r({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-n))}})},1)},l="undefined"!=typeof self&&self.cancelIdleCallback&&self.cancelIdleCallback.bind(window)||function(r){return clearTimeout(r)};("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},4785:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"resolveHref",{enumerable:!0,get:function(){return resolveHref}});let l=o(4828),u=o(3833),s=o(9302),d=o(1306),f=o(2955),h=o(4131),g=o(1232),_=o(9381);function resolveHref(r,n,o){let y;let P="string"==typeof n?n:(0,u.formatWithValidation)(n),b=P.match(/^[a-zA-Z]{1,}:\/\//),E=b?P.slice(b[0].length):P,S=E.split("?",1);if((S[0]||"").match(/(\/\/|\\)/)){console.error("Invalid href '"+P+"' passed to next/router in page: '"+r.pathname+"'. Repeated forward-slashes (//) or backslashes \\ are not valid in the href.");let n=(0,d.normalizeRepeatedSlashes)(E);P=(b?b[0]:"")+n}if(!(0,h.isLocalURL)(P))return o?[P]:P;try{y=new URL(P.startsWith("#")?r.asPath:r.pathname,"http://n")}catch(r){y=new URL("/","http://n")}try{let r=new URL(P,y);r.pathname=(0,f.normalizePathTrailingSlash)(r.pathname);let n="";if((0,g.isDynamicRoute)(r.pathname)&&r.searchParams&&o){let o=(0,l.searchParamsToUrlQuery)(r.searchParams),{result:d,params:f}=(0,_.interpolateAs)(r.pathname,r.pathname,o);d&&(n=(0,u.formatWithValidation)({pathname:d,hash:r.hash,query:(0,s.omit)(o,f)}))}let d=r.origin===y.origin?r.href.slice(r.origin.length):r.href;return o?[d,n||d]:d}catch(r){return o?[P]:P}}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},9513:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{RouteAnnouncer:function(){return RouteAnnouncer},default:function(){return f}});let l=o(8754),u=l._(o(7294)),s=o(4751),d={border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"absolute",top:0,width:"1px",whiteSpace:"nowrap",wordWrap:"normal"},RouteAnnouncer=()=>{let{asPath:r}=(0,s.useRouter)(),[n,o]=u.default.useState(""),l=u.default.useRef(r);return u.default.useEffect(()=>{if(l.current!==r){if(l.current=r,document.title)o(document.title);else{var n;let l=document.querySelector("h1"),u=null!=(n=null==l?void 0:l.innerText)?n:null==l?void 0:l.textContent;o(u||r)}}},[r]),u.default.createElement("p",{"aria-live":"assertive",id:"__next-route-announcer__",role:"alert",style:d},n)},f=RouteAnnouncer;("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},7159:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{markAssetError:function(){return markAssetError},isAssetError:function(){return isAssetError},getClientBuildManifest:function(){return getClientBuildManifest},createRouteLoader:function(){return createRouteLoader}}),o(8754),o(8052);let l=o(4581),u=o(3767),s=o(4878);function withFuture(r,n,o){let l,u=n.get(r);if(u)return"future"in u?u.future:Promise.resolve(u);let s=new Promise(r=>{l=r});return n.set(r,u={resolve:l,future:s}),o?o().then(r=>(l(r),r)).catch(o=>{throw n.delete(r),o}):s}let d=Symbol("ASSET_LOAD_ERROR");function markAssetError(r){return Object.defineProperty(r,d,{})}function isAssetError(r){return r&&d in r}function hasPrefetch(r){try{return r=document.createElement("link"),!!window.MSInputMethodContext&&!!document.documentMode||r.relList.supports("prefetch")}catch(r){return!1}}let f=hasPrefetch(),getAssetQueryString=()=>(0,s.getDeploymentIdQueryOrEmptyString)();function prefetchViaDom(r,n,o){return new Promise((l,u)=>{let s='\n link[rel="prefetch"][href^="'+r+'"],\n link[rel="preload"][href^="'+r+'"],\n script[src^="'+r+'"]';if(document.querySelector(s))return l();o=document.createElement("link"),n&&(o.as=n),o.rel="prefetch",o.crossOrigin=void 0,o.onload=l,o.onerror=()=>u(markAssetError(Error("Failed to prefetch: "+r))),o.href=r,document.head.appendChild(o)})}function appendScript(r,n){return new Promise((o,l)=>{(n=document.createElement("script")).onload=o,n.onerror=()=>l(markAssetError(Error("Failed to load script: "+r))),n.crossOrigin=void 0,n.src=r,document.body.appendChild(n)})}function resolvePromiseWithTimeout(r,n,o){return new Promise((l,s)=>{let d=!1;r.then(r=>{d=!0,l(r)}).catch(s),(0,u.requestIdleCallback)(()=>setTimeout(()=>{d||s(o)},n))})}function getClientBuildManifest(){if(self.__BUILD_MANIFEST)return Promise.resolve(self.__BUILD_MANIFEST);let r=new Promise(r=>{let n=self.__BUILD_MANIFEST_CB;self.__BUILD_MANIFEST_CB=()=>{r(self.__BUILD_MANIFEST),n&&n()}});return resolvePromiseWithTimeout(r,3800,markAssetError(Error("Failed to load client build manifest")))}function getFilesForRoute(r,n){return getClientBuildManifest().then(o=>{if(!(n in o))throw markAssetError(Error("Failed to lookup route: "+n));let u=o[n].map(n=>r+"/_next/"+encodeURI(n));return{scripts:u.filter(r=>r.endsWith(".js")).map(r=>(0,l.__unsafeCreateTrustedScriptURL)(r)+getAssetQueryString()),css:u.filter(r=>r.endsWith(".css")).map(r=>r+getAssetQueryString())}})}function createRouteLoader(r){let n=new Map,o=new Map,l=new Map,s=new Map;function maybeExecuteScript(r){{let n=o.get(r.toString());return n||(document.querySelector('script[src^="'+r+'"]')?Promise.resolve():(o.set(r.toString(),n=appendScript(r)),n))}}function fetchStyleSheet(r){let n=l.get(r);return n||l.set(r,n=fetch(r).then(n=>{if(!n.ok)throw Error("Failed to load stylesheet: "+r);return n.text().then(n=>({href:r,content:n}))}).catch(r=>{throw markAssetError(r)})),n}return{whenEntrypoint:r=>withFuture(r,n),onEntrypoint(r,o){(o?Promise.resolve().then(()=>o()).then(r=>({component:r&&r.default||r,exports:r}),r=>({error:r})):Promise.resolve(void 0)).then(o=>{let l=n.get(r);l&&"resolve"in l?o&&(n.set(r,o),l.resolve(o)):(o?n.set(r,o):n.delete(r),s.delete(r))})},loadRoute(o,l){return withFuture(o,s,()=>{let u;return resolvePromiseWithTimeout(getFilesForRoute(r,o).then(r=>{let{scripts:l,css:u}=r;return Promise.all([n.has(o)?[]:Promise.all(l.map(maybeExecuteScript)),Promise.all(u.map(fetchStyleSheet))])}).then(r=>this.whenEntrypoint(o).then(n=>({entrypoint:n,styles:r[1]}))),3800,markAssetError(Error("Route did not complete loading: "+o))).then(r=>{let{entrypoint:n,styles:o}=r,l=Object.assign({styles:o},n);return"error"in n?n:l}).catch(r=>{if(l)throw r;return{error:r}}).finally(()=>null==u?void 0:u())})},prefetch(n){let o;return(o=navigator.connection)&&(o.saveData||/2g/.test(o.effectiveType))?Promise.resolve():getFilesForRoute(r,n).then(r=>Promise.all(f?r.scripts.map(r=>prefetchViaDom(r.toString(),"script")):[])).then(()=>{(0,u.requestIdleCallback)(()=>this.loadRoute(n,!0).catch(()=>{}))}).catch(()=>{})}}}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},4751:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{Router:function(){return s.default},default:function(){return P},withRouter:function(){return h.default},useRouter:function(){return useRouter},createRouter:function(){return createRouter},makePublicRouterInstance:function(){return makePublicRouterInstance}});let l=o(8754),u=l._(o(7294)),s=l._(o(7797)),d=o(637),f=l._(o(676)),h=l._(o(7727)),g={router:null,readyCallbacks:[],ready(r){if(this.router)return r();this.readyCallbacks.push(r)}},_=["pathname","route","query","asPath","components","isFallback","basePath","locale","locales","defaultLocale","isReady","isPreview","isLocaleDomain","domainLocales"],y=["push","replace","reload","back","prefetch","beforePopState"];function getRouter(){if(!g.router)throw Error('No router instance found.\nYou should only use "next/router" on the client side of your app.\n');return g.router}Object.defineProperty(g,"events",{get:()=>s.default.events}),_.forEach(r=>{Object.defineProperty(g,r,{get(){let n=getRouter();return n[r]}})}),y.forEach(r=>{g[r]=function(){for(var n=arguments.length,o=Array(n),l=0;l<n;l++)o[l]=arguments[l];let u=getRouter();return u[r](...o)}}),["routeChangeStart","beforeHistoryChange","routeChangeComplete","routeChangeError","hashChangeStart","hashChangeComplete"].forEach(r=>{g.ready(()=>{s.default.events.on(r,function(){for(var n=arguments.length,o=Array(n),l=0;l<n;l++)o[l]=arguments[l];let u="on"+r.charAt(0).toUpperCase()+r.substring(1);if(g[u])try{g[u](...o)}catch(r){console.error("Error when running the Router event: "+u),console.error((0,f.default)(r)?r.message+"\n"+r.stack:r+"")}})})});let P=g;function useRouter(){let r=u.default.useContext(d.RouterContext);if(!r)throw Error("NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted");return r}function createRouter(){for(var r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];return g.router=new s.default(...n),g.readyCallbacks.forEach(r=>r()),g.readyCallbacks=[],g.router}function makePublicRouterInstance(r){let n={};for(let o of _){if("object"==typeof r[o]){n[o]=Object.assign(Array.isArray(r[o])?[]:{},r[o]);continue}n[o]=r[o]}return n.events=s.default.events,y.forEach(o=>{n[o]=function(){for(var n=arguments.length,l=Array(n),u=0;u<n;u++)l[u]=arguments[u];return r[o](...l)}}),n}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},2288:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{handleClientScriptLoad:function(){return handleClientScriptLoad},initScriptLoader:function(){return initScriptLoader},default:function(){return b}});let l=o(8754),u=o(1757),s=l._(o(3935)),d=u._(o(7294)),f=o(7768),h=o(4477),g=o(3767),_=new Map,y=new Set,P=["onLoad","onReady","dangerouslySetInnerHTML","children","onError","strategy","stylesheets"],insertStylesheets=r=>{if(s.default.preinit){r.forEach(r=>{s.default.preinit(r,{as:"style"})});return}{let n=document.head;r.forEach(r=>{let o=document.createElement("link");o.type="text/css",o.rel="stylesheet",o.href=r,n.appendChild(o)})}},loadScript=r=>{let{src:n,id:o,onLoad:l=()=>{},onReady:u=null,dangerouslySetInnerHTML:s,children:d="",strategy:f="afterInteractive",onError:g,stylesheets:b}=r,E=o||n;if(E&&y.has(E))return;if(_.has(n)){y.add(E),_.get(n).then(l,g);return}let afterLoad=()=>{u&&u(),y.add(E)},S=document.createElement("script"),R=new Promise((r,n)=>{S.addEventListener("load",function(n){r(),l&&l.call(this,n),afterLoad()}),S.addEventListener("error",function(r){n(r)})}).catch(function(r){g&&g(r)});for(let[o,l]of(s?(S.innerHTML=s.__html||"",afterLoad()):d?(S.textContent="string"==typeof d?d:Array.isArray(d)?d.join(""):"",afterLoad()):n&&(S.src=n,_.set(n,R)),Object.entries(r))){if(void 0===l||P.includes(o))continue;let r=h.DOMAttributeNames[o]||o.toLowerCase();S.setAttribute(r,l)}"worker"===f&&S.setAttribute("type","text/partytown"),S.setAttribute("data-nscript",f),b&&insertStylesheets(b),document.body.appendChild(S)};function handleClientScriptLoad(r){let{strategy:n="afterInteractive"}=r;"lazyOnload"===n?window.addEventListener("load",()=>{(0,g.requestIdleCallback)(()=>loadScript(r))}):loadScript(r)}function loadLazyScript(r){"complete"===document.readyState?(0,g.requestIdleCallback)(()=>loadScript(r)):window.addEventListener("load",()=>{(0,g.requestIdleCallback)(()=>loadScript(r))})}function addBeforeInteractiveToCache(){let r=[...document.querySelectorAll('[data-nscript="beforeInteractive"]'),...document.querySelectorAll('[data-nscript="beforePageRender"]')];r.forEach(r=>{let n=r.id||r.getAttribute("src");y.add(n)})}function initScriptLoader(r){r.forEach(handleClientScriptLoad),addBeforeInteractiveToCache()}function Script(r){let{id:n,src:o="",onLoad:l=()=>{},onReady:u=null,strategy:h="afterInteractive",onError:g,stylesheets:_,...P}=r,{updateScripts:b,scripts:E,getIsSsr:S,appDir:R,nonce:w}=(0,d.useContext)(f.HeadManagerContext),O=(0,d.useRef)(!1);(0,d.useEffect)(()=>{let r=n||o;O.current||(u&&r&&y.has(r)&&u(),O.current=!0)},[u,n,o]);let j=(0,d.useRef)(!1);if((0,d.useEffect)(()=>{j.current||("afterInteractive"===h?loadScript(r):"lazyOnload"===h&&loadLazyScript(r),j.current=!0)},[r,h]),("beforeInteractive"===h||"worker"===h)&&(b?(E[h]=(E[h]||[]).concat([{id:n,src:o,onLoad:l,onReady:u,onError:g,...P}]),b(E)):S&&S()?y.add(n||o):S&&!S()&&loadScript(r)),R){if(_&&_.forEach(r=>{s.default.preinit(r,{as:"style"})}),"beforeInteractive"===h)return o?(s.default.preload(o,P.integrity?{as:"script",integrity:P.integrity}:{as:"script"}),d.default.createElement("script",{nonce:w,dangerouslySetInnerHTML:{__html:"(self.__next_s=self.__next_s||[]).push("+JSON.stringify([o])+")"}})):(P.dangerouslySetInnerHTML&&(P.children=P.dangerouslySetInnerHTML.__html,delete P.dangerouslySetInnerHTML),d.default.createElement("script",{nonce:w,dangerouslySetInnerHTML:{__html:"(self.__next_s=self.__next_s||[]).push("+JSON.stringify([0,{...P}])+")"}}));"afterInteractive"===h&&o&&s.default.preload(o,P.integrity?{as:"script",integrity:P.integrity}:{as:"script"})}return null}Object.defineProperty(Script,"__nextScript",{value:!0});let b=Script;("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},6077:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return reportToSocket}});let l=o(6948);function reportToSocket(r){if("ended"!==r.state.state)throw Error("Expected span to be ended");(0,l.sendMessage)(JSON.stringify({event:"span-end",startTime:r.startTime,endTime:r.state.endTime,spanName:r.name,attributes:r.attributes}))}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},2295:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return s}});let l=o(8754),u=l._(o(3745));let Span=class Span{end(r){if("ended"===this.state.state)throw Error("Span has already ended");this.state={state:"ended",endTime:null!=r?r:Date.now()},this.onSpanEnd(this)}constructor(r,n,o){var l,u;this.name=r,this.attributes=null!=(l=n.attributes)?l:{},this.startTime=null!=(u=n.startTime)?u:Date.now(),this.onSpanEnd=o,this.state={state:"inprogress"}}};let Tracer=class Tracer{startSpan(r,n){return new Span(r,n,this.handleSpanEnd)}onSpanEnd(r){return this._emitter.on("spanend",r),()=>{this._emitter.off("spanend",r)}}constructor(){this._emitter=(0,u.default)(),this.handleSpanEnd=r=>{this._emitter.emit("spanend",r)}}};let s=new Tracer;("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},4581:function(r,n){"use strict";let o;function getPolicy(){if(void 0===o){var r;o=(null==(r=window.trustedTypes)?void 0:r.createPolicy("nextjs",{createHTML:r=>r,createScript:r=>r,createScriptURL:r=>r}))||null}return o}function __unsafeCreateTrustedScriptURL(r){var n;return(null==(n=getPolicy())?void 0:n.createScriptURL(r))||r}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"__unsafeCreateTrustedScriptURL",{enumerable:!0,get:function(){return __unsafeCreateTrustedScriptURL}}),("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},1867:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),o(4878),self.__next_set_public_path__=r=>{o.p=r},("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},7727:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return withRouter}});let l=o(8754),u=l._(o(7294)),s=o(4751);function withRouter(r){function WithRouterWrapper(n){return u.default.createElement(r,{router:(0,s.useRouter)(),...n})}return WithRouterWrapper.getInitialProps=r.getInitialProps,WithRouterWrapper.origGetInitialProps=r.origGetInitialProps,WithRouterWrapper}("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},8955:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return App}});let l=o(8754),u=l._(o(7294)),s=o(1306);async function appGetInitialProps(r){let{Component:n,ctx:o}=r,l=await (0,s.loadGetInitialProps)(n,o);return{pageProps:l}}let App=class App extends u.default.Component{render(){let{Component:r,pageProps:n}=this.props;return u.default.createElement(r,n)}};App.origGetInitialProps=appGetInitialProps,App.getInitialProps=appGetInitialProps,("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},4570:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return Error}});let l=o(8754),u=l._(o(7294)),s=l._(o(46)),d={400:"Bad Request",404:"This page could not be found",405:"Method Not Allowed",500:"Internal Server Error"};function _getInitialProps(r){let{res:n,err:o}=r,l=n&&n.statusCode?n.statusCode:o?o.statusCode:404;return{statusCode:l}}let f={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{lineHeight:"48px"},h1:{display:"inline-block",margin:"0 20px 0 0",paddingRight:23,fontSize:24,fontWeight:500,verticalAlign:"top"},h2:{fontSize:14,fontWeight:400,lineHeight:"28px"},wrap:{display:"inline-block"}};let Error=class Error extends u.default.Component{render(){let{statusCode:r,withDarkMode:n=!0}=this.props,o=this.props.title||d[r]||"An unexpected error has occurred";return u.default.createElement("div",{style:f.error},u.default.createElement(s.default,null,u.default.createElement("title",null,r?r+": "+o:"Application error: a client-side exception has occurred")),u.default.createElement("div",{style:f.desc},u.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}"+(n?"@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}":"")}}),r?u.default.createElement("h1",{className:"next-error-h1",style:f.h1},r):null,u.default.createElement("div",{style:f.wrap},u.default.createElement("h2",{style:f.h2},this.props.title||r?o:u.default.createElement(u.default.Fragment,null,"Application error: a client-side exception has occurred (see the browser console for more information)"),"."))))}};Error.displayName="ErrorPage",Error.getInitialProps=_getInitialProps,Error.origGetInitialProps=_getInitialProps,("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},5938:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"AmpStateContext",{enumerable:!0,get:function(){return s}});let l=o(8754),u=l._(o(7294)),s=u.default.createContext({})},8926:function(r,n){"use strict";function isInAmpMode(r){let{ampFirst:n=!1,hybrid:o=!1,hasQuery:l=!1}=void 0===r?{}:r;return n||o&&l}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"isInAmpMode",{enumerable:!0,get:function(){return isInAmpMode}})},1158:function(r,n,o){"use strict";var l,u;Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{CacheStates:function(){return l},AppRouterContext:function(){return f},LayoutRouterContext:function(){return h},GlobalLayoutRouterContext:function(){return g},TemplateContext:function(){return _}});let s=o(8754),d=s._(o(7294));(u=l||(l={})).LAZY_INITIALIZED="LAZYINITIALIZED",u.DATA_FETCH="DATAFETCH",u.READY="READY";let f=d.default.createContext(null),h=d.default.createContext(null),g=d.default.createContext(null),_=d.default.createContext(null)},1403:function(r,n){"use strict";function murmurhash2(r){let n=0;for(let o=0;o<r.length;o++){let l=r.charCodeAt(o);n=Math.imul(n^l,1540483477),n^=n>>>13,n=Math.imul(n,1540483477)}return n>>>0}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"BloomFilter",{enumerable:!0,get:function(){return BloomFilter}});let BloomFilter=class BloomFilter{static from(r,n){void 0===n&&(n=.01);let o=new BloomFilter(r.length,n);for(let n of r)o.add(n);return o}export(){let r={numItems:this.numItems,errorRate:this.errorRate,numBits:this.numBits,numHashes:this.numHashes,bitArray:this.bitArray};return r}import(r){this.numItems=r.numItems,this.errorRate=r.errorRate,this.numBits=r.numBits,this.numHashes=r.numHashes,this.bitArray=r.bitArray}add(r){let n=this.getHashValues(r);n.forEach(r=>{this.bitArray[r]=1})}contains(r){let n=this.getHashValues(r);return n.every(r=>this.bitArray[r])}getHashValues(r){let n=[];for(let o=1;o<=this.numHashes;o++){let l=murmurhash2(""+r+o)%this.numBits;n.push(l)}return n}constructor(r,n){this.numItems=r,this.errorRate=n,this.numBits=Math.ceil(-(r*Math.log(n))/(Math.log(2)*Math.log(2))),this.numHashes=Math.ceil(this.numBits/r*Math.log(2)),this.bitArray=Array(this.numBits).fill(0)}}},729:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{MODERN_BROWSERSLIST_TARGET:function(){return u.default},COMPILER_NAMES:function(){return s},INTERNAL_HEADERS:function(){return d},COMPILER_INDEXES:function(){return f},PHASE_EXPORT:function(){return h},PHASE_PRODUCTION_BUILD:function(){return g},PHASE_PRODUCTION_SERVER:function(){return _},PHASE_DEVELOPMENT_SERVER:function(){return y},PHASE_TEST:function(){return P},PHASE_INFO:function(){return b},PAGES_MANIFEST:function(){return E},APP_PATHS_MANIFEST:function(){return S},APP_PATH_ROUTES_MANIFEST:function(){return R},BUILD_MANIFEST:function(){return w},APP_BUILD_MANIFEST:function(){return O},FUNCTIONS_CONFIG_MANIFEST:function(){return j},SUBRESOURCE_INTEGRITY_MANIFEST:function(){return A},NEXT_FONT_MANIFEST:function(){return M},EXPORT_MARKER:function(){return C},EXPORT_DETAIL:function(){return I},PRERENDER_MANIFEST:function(){return x},ROUTES_MANIFEST:function(){return L},IMAGES_MANIFEST:function(){return N},SERVER_FILES_MANIFEST:function(){return D},DEV_CLIENT_PAGES_MANIFEST:function(){return k},MIDDLEWARE_MANIFEST:function(){return F},DEV_MIDDLEWARE_MANIFEST:function(){return U},REACT_LOADABLE_MANIFEST:function(){return H},FONT_MANIFEST:function(){return B},SERVER_DIRECTORY:function(){return W},CONFIG_FILES:function(){return q},BUILD_ID_FILE:function(){return z},BLOCKED_PAGES:function(){return G},CLIENT_PUBLIC_FILES_PATH:function(){return V},CLIENT_STATIC_FILES_PATH:function(){return X},STRING_LITERAL_DROP_BUNDLE:function(){return Y},NEXT_BUILTIN_DOCUMENT:function(){return K},BARREL_OPTIMIZATION_PREFIX:function(){return Q},CLIENT_REFERENCE_MANIFEST:function(){return $},SERVER_REFERENCE_MANIFEST:function(){return J},MIDDLEWARE_BUILD_MANIFEST:function(){return Z},MIDDLEWARE_REACT_LOADABLE_MANIFEST:function(){return ee},CLIENT_STATIC_FILES_RUNTIME_MAIN:function(){return et},CLIENT_STATIC_FILES_RUNTIME_MAIN_APP:function(){return er},APP_CLIENT_INTERNALS:function(){return en},CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH:function(){return ea},CLIENT_STATIC_FILES_RUNTIME_AMP:function(){return eo},CLIENT_STATIC_FILES_RUNTIME_WEBPACK:function(){return ei},CLIENT_STATIC_FILES_RUNTIME_POLYFILLS:function(){return el},CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL:function(){return eu},EDGE_RUNTIME_WEBPACK:function(){return es},TEMPORARY_REDIRECT_STATUS:function(){return ec},PERMANENT_REDIRECT_STATUS:function(){return ed},STATIC_PROPS_ID:function(){return ef},SERVER_PROPS_ID:function(){return ep},PAGE_SEGMENT_KEY:function(){return eh},GOOGLE_FONT_PROVIDER:function(){return em},OPTIMIZED_FONT_PROVIDERS:function(){return eg},DEFAULT_SERIF_FONT:function(){return e_},DEFAULT_SANS_SERIF_FONT:function(){return ey},STATIC_STATUS_PAGES:function(){return eP},TRACE_OUTPUT_VERSION:function(){return eb},TURBO_TRACE_DEFAULT_MEMORY_LIMIT:function(){return ev},RSC_MODULE_TYPES:function(){return eE},EDGE_UNSUPPORTED_NODE_APIS:function(){return eS},SYSTEM_ENTRYPOINTS:function(){return eR}});let l=o(8754),u=l._(o(1329)),s={client:"client",server:"server",edgeServer:"edge-server"},d=["x-invoke-path","x-invoke-status","x-invoke-error","x-invoke-query","x-middleware-invoke"],f={[s.client]:0,[s.server]:1,[s.edgeServer]:2},h="phase-export",g="phase-production-build",_="phase-production-server",y="phase-development-server",P="phase-test",b="phase-info",E="pages-manifest.json",S="app-paths-manifest.json",R="app-path-routes-manifest.json",w="build-manifest.json",O="app-build-manifest.json",j="functions-config-manifest.json",A="subresource-integrity-manifest",M="next-font-manifest",C="export-marker.json",I="export-detail.json",x="prerender-manifest.json",L="routes-manifest.json",N="images-manifest.json",D="required-server-files.json",k="_devPagesManifest.json",F="middleware-manifest.json",U="_devMiddlewareManifest.json",H="react-loadable-manifest.json",B="font-manifest.json",W="server",q=["next.config.js","next.config.mjs"],z="BUILD_ID",G=["/_document","/_app","/_error"],V="public",X="static",Y="__NEXT_DROP_CLIENT_FILE__",K="__NEXT_BUILTIN_DOCUMENT__",Q="__barrel_optimize__",$="client-reference-manifest",J="server-reference-manifest",Z="middleware-build-manifest",ee="middleware-react-loadable-manifest",et="main",er=""+et+"-app",en="app-pages-internals",ea="react-refresh",eo="amp",ei="webpack",el="polyfills",eu=Symbol(el),es="edge-runtime-webpack",ec=307,ed=308,ef="__N_SSG",ep="__N_SSP",eh="__PAGE__",em="https://fonts.googleapis.com/",eg=[{url:em,preconnect:"https://fonts.gstatic.com"},{url:"https://use.typekit.net",preconnect:"https://use.typekit.net"}],e_={name:"Times New Roman",xAvgCharWidth:821,azAvgWidth:854.3953488372093,unitsPerEm:2048},ey={name:"Arial",xAvgCharWidth:904,azAvgWidth:934.5116279069767,unitsPerEm:2048},eP=["/500"],eb=1,ev=6e3,eE={client:"client",server:"server"},eS=["clearImmediate","setImmediate","BroadcastChannel","ByteLengthQueuingStrategy","CompressionStream","CountQueuingStrategy","DecompressionStream","DomException","MessageChannel","MessageEvent","MessagePort","ReadableByteStreamController","ReadableStreamBYOBRequest","ReadableStreamDefaultController","TransformStreamDefaultController","WritableStreamDefaultController"],eR=new Set([et,ea,eo,er]);("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},4125:function(r,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"escapeStringRegexp",{enumerable:!0,get:function(){return escapeStringRegexp}});let o=/[|\\{}()[\]^$+*?.-]/,l=/[|\\{}()[\]^$+*?.-]/g;function escapeStringRegexp(r){return o.test(r)?r.replace(l,"\\$&"):r}},7768:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"HeadManagerContext",{enumerable:!0,get:function(){return s}});let l=o(8754),u=l._(o(7294)),s=u.default.createContext({})},46:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{defaultHead:function(){return defaultHead},default:function(){return y}});let l=o(8754),u=o(1757),s=u._(o(7294)),d=l._(o(3632)),f=o(5938),h=o(7768),g=o(8926);function defaultHead(r){void 0===r&&(r=!1);let n=[s.default.createElement("meta",{charSet:"utf-8"})];return r||n.push(s.default.createElement("meta",{name:"viewport",content:"width=device-width"})),n}function onlyReactElement(r,n){return"string"==typeof n||"number"==typeof n?r:n.type===s.default.Fragment?r.concat(s.default.Children.toArray(n.props.children).reduce((r,n)=>"string"==typeof n||"number"==typeof n?r:r.concat(n),[])):r.concat(n)}o(9941);let _=["name","httpEquiv","charSet","itemProp"];function unique(){let r=new Set,n=new Set,o=new Set,l={};return u=>{let s=!0,d=!1;if(u.key&&"number"!=typeof u.key&&u.key.indexOf("$")>0){d=!0;let n=u.key.slice(u.key.indexOf("$")+1);r.has(n)?s=!1:r.add(n)}switch(u.type){case"title":case"base":n.has(u.type)?s=!1:n.add(u.type);break;case"meta":for(let r=0,n=_.length;r<n;r++){let n=_[r];if(u.props.hasOwnProperty(n)){if("charSet"===n)o.has(n)?s=!1:o.add(n);else{let r=u.props[n],o=l[n]||new Set;("name"!==n||!d)&&o.has(r)?s=!1:(o.add(r),l[n]=o)}}}}return s}}function reduceComponents(r,n){let{inAmpMode:o}=n;return r.reduce(onlyReactElement,[]).reverse().concat(defaultHead(o).reverse()).filter(unique()).reverse().map((r,n)=>{let l=r.key||n;if(!o&&"link"===r.type&&r.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(n=>r.props.href.startsWith(n))){let n={...r.props||{}};return n["data-href"]=n.href,n.href=void 0,n["data-optimized-fonts"]=!0,s.default.cloneElement(r,n)}return s.default.cloneElement(r,{key:l})})}function Head(r){let{children:n}=r,o=(0,s.useContext)(f.AmpStateContext),l=(0,s.useContext)(h.HeadManagerContext);return s.default.createElement(d.default,{reduceComponentsToState:reduceComponents,headManager:l,inAmpMode:(0,g.isInAmpMode)(o)},n)}let y=Head;("function"==typeof n.default||"object"==typeof n.default&&null!==n.default)&&void 0===n.default.__esModule&&(Object.defineProperty(n.default,"__esModule",{value:!0}),Object.assign(n.default,n),r.exports=n.default)},8197:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{SearchParamsContext:function(){return u},PathnameContext:function(){return s},PathParamsContext:function(){return d}});let l=o(7294),u=(0,l.createContext)(null),s=(0,l.createContext)(null),d=(0,l.createContext)(null)},4656:function(r,n){"use strict";function normalizeLocalePath(r,n){let o;let l=r.split("/");return(n||[]).some(n=>!!l[1]&&l[1].toLowerCase()===n.toLowerCase()&&(o=n,l.splice(1,1),r=l.join("/")||"/",!0)),{pathname:r,detectedLocale:o}}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"normalizeLocalePath",{enumerable:!0,get:function(){return normalizeLocalePath}})},4955:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"ImageConfigContext",{enumerable:!0,get:function(){return d}});let l=o(8754),u=l._(o(7294)),s=o(7599),d=u.default.createContext(s.imageConfigDefault)},7599:function(r,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{VALID_LOADERS:function(){return o},imageConfigDefault:function(){return l}});let o=["default","imgix","cloudinary","akamai","custom"],l={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"inline",remotePatterns:[],unoptimized:!1}},9942:function(r,n){"use strict";function getObjectClassLabel(r){return Object.prototype.toString.call(r)}function isPlainObject(r){if("[object Object]"!==getObjectClassLabel(r))return!1;let n=Object.getPrototypeOf(r);return null===n||n.hasOwnProperty("isPrototypeOf")}Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{getObjectClassLabel:function(){return getObjectClassLabel},isPlainObject:function(){return isPlainObject}})},4600:function(r,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{NEXT_DYNAMIC_NO_SSR_CODE:function(){return o},throwWithNoSSR:function(){return throwWithNoSSR}});let o="NEXT_DYNAMIC_NO_SSR_CODE";function throwWithNoSSR(){let r=Error(o);throw r.digest=o,r}},3745:function(r,n){"use strict";function mitt(){let r=Object.create(null);return{on(n,o){(r[n]||(r[n]=[])).push(o)},off(n,o){r[n]&&r[n].splice(r[n].indexOf(o)>>>0,1)},emit(n){for(var o=arguments.length,l=Array(o>1?o-1:0),u=1;u<o;u++)l[u-1]=arguments[u];(r[n]||[]).slice().map(r=>{r(...l)})}}}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return mitt}})},1329:function(r){"use strict";r.exports=["chrome 64","edge 79","firefox 67","opera 51","safari 12"]},8902:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"denormalizePagePath",{enumerable:!0,get:function(){return denormalizePagePath}});let l=o(1232),u=o(7932);function denormalizePagePath(r){let n=(0,u.normalizePathSep)(r);return n.startsWith("/index/")&&!(0,l.isDynamicRoute)(n)?n.slice(6):"/index"!==n?n:"/"}},3029:function(r,n){"use strict";function ensureLeadingSlash(r){return r.startsWith("/")?r:"/"+r}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"ensureLeadingSlash",{enumerable:!0,get:function(){return ensureLeadingSlash}})},7932:function(r,n){"use strict";function normalizePathSep(r){return r.replace(/\\/g,"/")}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"normalizePathSep",{enumerable:!0,get:function(){return normalizePathSep}})},637:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"RouterContext",{enumerable:!0,get:function(){return s}});let l=o(8754),u=l._(o(7294)),s=u.default.createContext(null)},7178:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{adaptForAppRouterInstance:function(){return adaptForAppRouterInstance},adaptForSearchParams:function(){return adaptForSearchParams},adaptForPathParams:function(){return adaptForPathParams},PathnameContextProviderAdapter:function(){return PathnameContextProviderAdapter}});let l=o(1757),u=l._(o(7294)),s=o(8197),d=o(1232),f=o(2391),h=o(8300);function adaptForAppRouterInstance(r){return{back(){r.back()},forward(){r.forward()},refresh(){r.reload()},push(n,o){let{scroll:l}=void 0===o?{}:o;r.push(n,void 0,{scroll:l})},replace(n,o){let{scroll:l}=void 0===o?{}:o;r.replace(n,void 0,{scroll:l})},prefetch(n){r.prefetch(n)}}}function adaptForSearchParams(r){return r.isReady&&r.query?(0,f.asPathToSearchParams)(r.asPath):new URLSearchParams}function adaptForPathParams(r){if(!r.isReady||!r.query)return null;let n={},o=(0,h.getRouteRegex)(r.pathname),l=Object.keys(o.groups);for(let o of l)n[o]=r.query[o];return n}function PathnameContextProviderAdapter(r){let{children:n,router:o,...l}=r,f=(0,u.useRef)(l.isAutoExport),h=(0,u.useMemo)(()=>{let r;let n=f.current;if(n&&(f.current=!1),(0,d.isDynamicRoute)(o.pathname)&&(o.isFallback||n&&!o.isReady))return null;try{r=new URL(o.asPath,"http://f")}catch(r){return"/"}return r.pathname},[o.asPath,o.isFallback,o.isReady,o.pathname]);return u.default.createElement(s.PathnameContext.Provider,{value:h},n)}},7797:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{default:function(){return Router},matchesMiddleware:function(){return matchesMiddleware},createKey:function(){return createKey}});let l=o(8754),u=o(1757),s=o(6082),d=o(7159),f=o(2288),h=u._(o(676)),g=o(8902),_=o(4656),y=l._(o(3745)),P=o(1306),b=o(8011),E=o(9823);o(2431);let S=o(9001),R=o(8300),w=o(3833);o(4287);let O=o(891),j=o(2048),A=o(3099),M=o(7786),C=o(5864),I=o(5213),x=o(4785),L=o(9423),N=o(673),D=o(8979),k=o(1530),F=o(4131),U=o(6116),H=o(9302),B=o(9381),W=o(9987);function buildCancellationError(){return Object.assign(Error("Route Cancelled"),{cancelled:!0})}async function matchesMiddleware(r){let n=await Promise.resolve(r.router.pageLoader.getMiddleware());if(!n)return!1;let{pathname:o}=(0,O.parsePath)(r.asPath),l=(0,I.hasBasePath)(o)?(0,M.removeBasePath)(o):o,u=(0,C.addBasePath)((0,j.addLocale)(l,r.locale));return n.some(r=>new RegExp(r.regexp).test(u))}function stripOrigin(r){let n=(0,P.getLocationOrigin)();return r.startsWith(n)?r.substring(n.length):r}function prepareUrlAs(r,n,o){let[l,u]=(0,x.resolveHref)(r,n,!0),s=(0,P.getLocationOrigin)(),d=l.startsWith(s),f=u&&u.startsWith(s);l=stripOrigin(l),u=u?stripOrigin(u):u;let h=d?l:(0,C.addBasePath)(l),g=o?stripOrigin((0,x.resolveHref)(r,o)):u||l;return{url:h,as:f?g:(0,C.addBasePath)(g)}}function resolveDynamicRoute(r,n){let o=(0,s.removeTrailingSlash)((0,g.denormalizePagePath)(r));return"/404"===o||"/_error"===o?r:(n.includes(o)||n.some(n=>{if((0,b.isDynamicRoute)(n)&&(0,R.getRouteRegex)(n).re.test(o))return r=n,!0}),(0,s.removeTrailingSlash)(r))}function getMiddlewareData(r,n,o){let l={basePath:o.router.basePath,i18n:{locales:o.router.locales},trailingSlash:!1},u=n.headers.get("x-nextjs-rewrite"),f=u||n.headers.get("x-nextjs-matched-path"),h=n.headers.get("x-matched-path");if(!h||f||h.includes("__next_data_catchall")||h.includes("/_error")||h.includes("/404")||(f=h),f){if(f.startsWith("/")){let n=(0,E.parseRelativeUrl)(f),h=(0,N.getNextPathnameInfo)(n.pathname,{nextConfig:l,parseData:!0}),g=(0,s.removeTrailingSlash)(h.pathname);return Promise.all([o.router.pageLoader.getPageList(),(0,d.getClientBuildManifest)()]).then(s=>{let[d,{__rewrites:f}]=s,y=(0,j.addLocale)(h.pathname,h.locale);if((0,b.isDynamicRoute)(y)||!u&&d.includes((0,_.normalizeLocalePath)((0,M.removeBasePath)(y),o.router.locales).pathname)){let o=(0,N.getNextPathnameInfo)((0,E.parseRelativeUrl)(r).pathname,{nextConfig:l,parseData:!0});y=(0,C.addBasePath)(o.pathname),n.pathname=y}if(!d.includes(g)){let r=resolveDynamicRoute(g,d);r!==g&&(g=r)}let P=d.includes(g)?g:resolveDynamicRoute((0,_.normalizeLocalePath)((0,M.removeBasePath)(n.pathname),o.router.locales).pathname,d);if((0,b.isDynamicRoute)(P)){let r=(0,S.getRouteMatcher)((0,R.getRouteRegex)(P))(y);Object.assign(n.query,r||{})}return{type:"rewrite",parsedAs:n,resolvedHref:P}})}let n=(0,O.parsePath)(r),h=(0,D.formatNextPathnameInfo)({...(0,N.getNextPathnameInfo)(n.pathname,{nextConfig:l,parseData:!0}),defaultLocale:o.router.defaultLocale,buildId:""});return Promise.resolve({type:"redirect-external",destination:""+h+n.query+n.hash})}let g=n.headers.get("x-nextjs-redirect");if(g){if(g.startsWith("/")){let r=(0,O.parsePath)(g),n=(0,D.formatNextPathnameInfo)({...(0,N.getNextPathnameInfo)(r.pathname,{nextConfig:l,parseData:!0}),defaultLocale:o.router.defaultLocale,buildId:""});return Promise.resolve({type:"redirect-internal",newAs:""+n+r.query+r.hash,newUrl:""+n+r.query+r.hash})}return Promise.resolve({type:"redirect-external",destination:g})}return Promise.resolve({type:"next"})}async function withMiddlewareEffects(r){let n=await matchesMiddleware(r);if(!n||!r.fetchData)return null;try{let n=await r.fetchData(),o=await getMiddlewareData(n.dataHref,n.response,r);return{dataHref:n.dataHref,json:n.json,response:n.response,text:n.text,cacheKey:n.cacheKey,effect:o}}catch(r){return null}}let q=Symbol("SSG_DATA_NOT_FOUND");function fetchRetry(r,n,o){return fetch(r,{credentials:"same-origin",method:o.method||"GET",headers:Object.assign({},o.headers,{"x-nextjs-data":"1"})}).then(l=>!l.ok&&n>1&&l.status>=500?fetchRetry(r,n-1,o):l)}function tryToParseAsJSON(r){try{return JSON.parse(r)}catch(r){return null}}function fetchNextData(r){var n;let{dataHref:o,inflightCache:l,isPrefetch:u,hasMiddleware:s,isServerRender:f,parseJSON:h,persistCache:g,isBackground:_,unstable_skipClientCache:y}=r,{href:P}=new URL(o,window.location.href),getData=r=>fetchRetry(o,f?3:1,{headers:Object.assign({},u?{purpose:"prefetch"}:{},u&&s?{"x-middleware-prefetch":"1"}:{}),method:null!=(n=null==r?void 0:r.method)?n:"GET"}).then(n=>n.ok&&(null==r?void 0:r.method)==="HEAD"?{dataHref:o,response:n,text:"",json:{},cacheKey:P}:n.text().then(r=>{if(!n.ok){if(s&&[301,302,307,308].includes(n.status))return{dataHref:o,response:n,text:r,json:{},cacheKey:P};if(404===n.status){var l;if(null==(l=tryToParseAsJSON(r))?void 0:l.notFound)return{dataHref:o,json:{notFound:q},response:n,text:r,cacheKey:P}}let u=Error("Failed to load static props");throw f||(0,d.markAssetError)(u),u}return{dataHref:o,json:h?tryToParseAsJSON(r):null,response:n,text:r,cacheKey:P}})).then(r=>(g&&"no-cache"!==r.response.headers.get("x-middleware-cache")||delete l[P],r)).catch(r=>{throw y||delete l[P],("Failed to fetch"===r.message||"NetworkError when attempting to fetch resource."===r.message||"Load failed"===r.message)&&(0,d.markAssetError)(r),r});return y&&g?getData({}).then(r=>(l[P]=Promise.resolve(r),r)):void 0!==l[P]?l[P]:l[P]=getData(_?{method:"HEAD"}:{})}function createKey(){return Math.random().toString(36).slice(2,10)}function handleHardNavigation(r){let{url:n,router:o}=r;if(n===(0,C.addBasePath)((0,j.addLocale)(o.asPath,o.locale)))throw Error("Invariant: attempted to hard navigate to the same URL "+n+" "+location.href);window.location.href=n}let getCancelledHandler=r=>{let{route:n,router:o}=r,l=!1,u=o.clc=()=>{l=!0};return()=>{if(l){let r=Error('Abort fetching component for route: "'+n+'"');throw r.cancelled=!0,r}u===o.clc&&(o.clc=null)}};let Router=class Router{reload(){window.location.reload()}back(){window.history.back()}forward(){window.history.forward()}push(r,n,o){return void 0===o&&(o={}),{url:r,as:n}=prepareUrlAs(this,r,n),this.change("pushState",r,n,o)}replace(r,n,o){return void 0===o&&(o={}),{url:r,as:n}=prepareUrlAs(this,r,n),this.change("replaceState",r,n,o)}async _bfl(r,n,o,l){{let h=!1,g=!1;for(let _ of[r,n])if(_){let n=(0,s.removeTrailingSlash)(new URL(_,"http://n").pathname),y=(0,C.addBasePath)((0,j.addLocale)(n,o||this.locale));if(n!==(0,s.removeTrailingSlash)(new URL(this.asPath,"http://n").pathname)){var u,d,f;for(let r of(h=h||!!(null==(u=this._bfl_s)?void 0:u.contains(n))||!!(null==(d=this._bfl_s)?void 0:d.contains(y)),[n,y])){let n=r.split("/");for(let r=0;!g&&r<n.length+1;r++){let o=n.slice(0,r).join("/");if(o&&(null==(f=this._bfl_d)?void 0:f.contains(o))){g=!0;break}}}if(h||g){if(l)return!0;return handleHardNavigation({url:(0,C.addBasePath)((0,j.addLocale)(r,o||this.locale,this.defaultLocale)),router:this}),new Promise(()=>{})}}}}return!1}async change(r,n,o,l,u){var g,_,y,x,L,N,D,U,W;let z,G;if(!(0,F.isLocalURL)(n))return handleHardNavigation({url:n,router:this}),!1;let V=1===l._h;V||l.shallow||await this._bfl(o,void 0,l.locale);let X=V||l._shouldResolveHref||(0,O.parsePath)(n).pathname===(0,O.parsePath)(o).pathname,Y={...this.state},K=!0!==this.isReady;this.isReady=!0;let Q=this.isSsr;if(V||(this.isSsr=!1),V&&this.clc)return!1;let $=Y.locale;P.ST&&performance.mark("routeChange");let{shallow:J=!1,scroll:Z=!0}=l,ee={shallow:J};this._inFlightRoute&&this.clc&&(Q||Router.events.emit("routeChangeError",buildCancellationError(),this._inFlightRoute,ee),this.clc(),this.clc=null),o=(0,C.addBasePath)((0,j.addLocale)((0,I.hasBasePath)(o)?(0,M.removeBasePath)(o):o,l.locale,this.defaultLocale));let et=(0,A.removeLocale)((0,I.hasBasePath)(o)?(0,M.removeBasePath)(o):o,Y.locale);this._inFlightRoute=o;let er=$!==Y.locale;if(!V&&this.onlyAHashChange(et)&&!er){Y.asPath=et,Router.events.emit("hashChangeStart",o,ee),this.changeState(r,n,o,{...l,scroll:!1}),Z&&this.scrollToHash(et);try{await this.set(Y,this.components[Y.route],null)}catch(r){throw(0,h.default)(r)&&r.cancelled&&Router.events.emit("routeChangeError",r,et,ee),r}return Router.events.emit("hashChangeComplete",o,ee),!0}let en=(0,E.parseRelativeUrl)(n),{pathname:ea,query:eo}=en;if(null==(g=this.components[ea])?void 0:g.__appRouter)return handleHardNavigation({url:o,router:this}),new Promise(()=>{});try{[z,{__rewrites:G}]=await Promise.all([this.pageLoader.getPageList(),(0,d.getClientBuildManifest)(),this.pageLoader.getMiddleware()])}catch(r){return handleHardNavigation({url:o,router:this}),!1}this.urlIsNew(et)||er||(r="replaceState");let ei=o;ea=ea?(0,s.removeTrailingSlash)((0,M.removeBasePath)(ea)):ea;let el=(0,s.removeTrailingSlash)(ea),eu=o.startsWith("/")&&(0,E.parseRelativeUrl)(o).pathname,es=!!(eu&&el!==eu&&(!(0,b.isDynamicRoute)(el)||!(0,S.getRouteMatcher)((0,R.getRouteRegex)(el))(eu))),ec=!l.shallow&&await matchesMiddleware({asPath:o,locale:Y.locale,router:this});if(V&&ec&&(X=!1),X&&"/_error"!==ea&&(l._shouldResolveHref=!0,en.pathname=resolveDynamicRoute(ea,z),en.pathname===ea||(ea=en.pathname,en.pathname=(0,C.addBasePath)(ea),ec||(n=(0,w.formatWithValidation)(en)))),!(0,F.isLocalURL)(o))return handleHardNavigation({url:o,router:this}),!1;ei=(0,A.removeLocale)((0,M.removeBasePath)(ei),Y.locale),el=(0,s.removeTrailingSlash)(ea);let ed=!1;if((0,b.isDynamicRoute)(el)){let r=(0,E.parseRelativeUrl)(ei),l=r.pathname,u=(0,R.getRouteRegex)(el);ed=(0,S.getRouteMatcher)(u)(l);let s=el===l,d=s?(0,B.interpolateAs)(el,l,eo):{};if(ed&&(!s||d.result))s?o=(0,w.formatWithValidation)(Object.assign({},r,{pathname:d.result,query:(0,H.omit)(eo,d.params)})):Object.assign(eo,ed);else{let r=Object.keys(u.groups).filter(r=>!eo[r]&&!u.groups[r].optional);if(r.length>0&&!ec)throw Error((s?"The provided `href` ("+n+") value is missing query values ("+r.join(", ")+") to be interpolated properly. ":"The provided `as` value ("+l+") is incompatible with the `href` value ("+el+"). ")+"Read more: https://nextjs.org/docs/messages/"+(s?"href-interpolation-failed":"incompatible-href-as"))}}V||Router.events.emit("routeChangeStart",o,ee);let ef="/404"===this.pathname||"/_error"===this.pathname;try{let s=await this.getRouteInfo({route:el,pathname:ea,query:eo,as:o,resolvedAs:ei,routeProps:ee,locale:Y.locale,isPreview:Y.isPreview,hasMiddleware:ec,unstable_skipClientCache:l.unstable_skipClientCache,isQueryUpdating:V&&!this.isFallback,isMiddlewareRewrite:es});if(V||l.shallow||await this._bfl(o,"resolvedAs"in s?s.resolvedAs:void 0,Y.locale),"route"in s&&ec){el=ea=s.route||el,ee.shallow||(eo=Object.assign({},s.query||{},eo));let r=(0,I.hasBasePath)(en.pathname)?(0,M.removeBasePath)(en.pathname):en.pathname;if(ed&&ea!==r&&Object.keys(ed).forEach(r=>{ed&&eo[r]===ed[r]&&delete eo[r]}),(0,b.isDynamicRoute)(ea)){let r=!ee.shallow&&s.resolvedAs?s.resolvedAs:(0,C.addBasePath)((0,j.addLocale)(new URL(o,location.href).pathname,Y.locale),!0),n=r;(0,I.hasBasePath)(n)&&(n=(0,M.removeBasePath)(n));let l=(0,R.getRouteRegex)(ea),u=(0,S.getRouteMatcher)(l)(new URL(n,location.href).pathname);u&&Object.assign(eo,u)}}if("type"in s){if("redirect-internal"===s.type)return this.change(r,s.newUrl,s.newAs,l);return handleHardNavigation({url:s.destination,router:this}),new Promise(()=>{})}let d=s.Component;if(d&&d.unstable_scriptLoader){let r=[].concat(d.unstable_scriptLoader());r.forEach(r=>{(0,f.handleClientScriptLoad)(r.props)})}if((s.__N_SSG||s.__N_SSP)&&s.props){if(s.props.pageProps&&s.props.pageProps.__N_REDIRECT){l.locale=!1;let n=s.props.pageProps.__N_REDIRECT;if(n.startsWith("/")&&!1!==s.props.pageProps.__N_REDIRECT_BASE_PATH){let o=(0,E.parseRelativeUrl)(n);o.pathname=resolveDynamicRoute(o.pathname,z);let{url:u,as:s}=prepareUrlAs(this,n,n);return this.change(r,u,s,l)}return handleHardNavigation({url:n,router:this}),new Promise(()=>{})}if(Y.isPreview=!!s.props.__N_PREVIEW,s.props.notFound===q){let r;try{await this.fetchComponent("/404"),r="/404"}catch(n){r="/_error"}if(s=await this.getRouteInfo({route:r,pathname:r,query:eo,as:o,resolvedAs:ei,routeProps:{shallow:!1},locale:Y.locale,isPreview:Y.isPreview,isNotFound:!0}),"type"in s)throw Error("Unexpected middleware effect on /404")}}V&&"/_error"===this.pathname&&(null==(y=self.__NEXT_DATA__.props)?void 0:null==(_=y.pageProps)?void 0:_.statusCode)===500&&(null==(x=s.props)?void 0:x.pageProps)&&(s.props.pageProps.statusCode=500);let g=l.shallow&&Y.route===(null!=(L=s.route)?L:el),P=null!=(N=l.scroll)?N:!V&&!g,w=null!=u?u:P?{x:0,y:0}:null,O={...Y,route:el,pathname:ea,query:eo,asPath:et,isFallback:!1};if(V&&ef){if(s=await this.getRouteInfo({route:this.pathname,pathname:this.pathname,query:eo,as:o,resolvedAs:ei,routeProps:{shallow:!1},locale:Y.locale,isPreview:Y.isPreview,isQueryUpdating:V&&!this.isFallback}),"type"in s)throw Error("Unexpected middleware effect on "+this.pathname);"/_error"===this.pathname&&(null==(U=self.__NEXT_DATA__.props)?void 0:null==(D=U.pageProps)?void 0:D.statusCode)===500&&(null==(W=s.props)?void 0:W.pageProps)&&(s.props.pageProps.statusCode=500);try{await this.set(O,s,w)}catch(r){throw(0,h.default)(r)&&r.cancelled&&Router.events.emit("routeChangeError",r,et,ee),r}return!0}Router.events.emit("beforeHistoryChange",o,ee),this.changeState(r,n,o,l);let A=V&&!w&&!K&&!er&&(0,k.compareRouterStates)(O,this.state);if(!A){try{await this.set(O,s,w)}catch(r){if(r.cancelled)s.error=s.error||r;else throw r}if(s.error)throw V||Router.events.emit("routeChangeError",s.error,et,ee),s.error;V||Router.events.emit("routeChangeComplete",o,ee),P&&/#.+$/.test(o)&&this.scrollToHash(o)}return!0}catch(r){if((0,h.default)(r)&&r.cancelled)return!1;throw r}}changeState(r,n,o,l){void 0===l&&(l={}),("pushState"!==r||(0,P.getURL)()!==o)&&(this._shallow=l.shallow,window.history[r]({url:n,as:o,options:l,__N:!0,key:this._key="pushState"!==r?this._key:createKey()},"",o))}async handleRouteInfoError(r,n,o,l,u,s){if(console.error(r),r.cancelled)throw r;if((0,d.isAssetError)(r)||s)throw Router.events.emit("routeChangeError",r,l,u),handleHardNavigation({url:l,router:this}),buildCancellationError();try{let l;let{page:u,styleSheets:s}=await this.fetchComponent("/_error"),d={props:l,Component:u,styleSheets:s,err:r,error:r};if(!d.props)try{d.props=await this.getInitialProps(u,{err:r,pathname:n,query:o})}catch(r){console.error("Error in error page `getInitialProps`: ",r),d.props={}}return d}catch(r){return this.handleRouteInfoError((0,h.default)(r)?r:Error(r+""),n,o,l,u,!0)}}async getRouteInfo(r){let{route:n,pathname:o,query:l,as:u,resolvedAs:d,routeProps:f,locale:g,hasMiddleware:y,isPreview:P,unstable_skipClientCache:b,isQueryUpdating:E,isMiddlewareRewrite:S,isNotFound:R}=r,O=n;try{var j,A,C,I;let r=getCancelledHandler({route:O,router:this}),n=this.components[O];if(f.shallow&&n&&this.route===O)return n;y&&(n=void 0);let h=!n||"initial"in n?void 0:n,x={dataHref:this.pageLoader.getDataHref({href:(0,w.formatWithValidation)({pathname:o,query:l}),skipInterpolation:!0,asPath:R?"/404":d,locale:g}),hasMiddleware:!0,isServerRender:this.isSsr,parseJSON:!0,inflightCache:E?this.sbc:this.sdc,persistCache:!P,isPrefetch:!1,unstable_skipClientCache:b,isBackground:E},N=E&&!S?null:await withMiddlewareEffects({fetchData:()=>fetchNextData(x),asPath:R?"/404":d,locale:g,router:this}).catch(r=>{if(E)return null;throw r});if(N&&("/_error"===o||"/404"===o)&&(N.effect=void 0),E&&(N?N.json=self.__NEXT_DATA__.props:N={json:self.__NEXT_DATA__.props}),r(),(null==N?void 0:null==(j=N.effect)?void 0:j.type)==="redirect-internal"||(null==N?void 0:null==(A=N.effect)?void 0:A.type)==="redirect-external")return N.effect;if((null==N?void 0:null==(C=N.effect)?void 0:C.type)==="rewrite"){let r=(0,s.removeTrailingSlash)(N.effect.resolvedHref),u=await this.pageLoader.getPageList();if((!E||u.includes(r))&&(O=r,o=N.effect.resolvedHref,l={...l,...N.effect.parsedAs.query},d=(0,M.removeBasePath)((0,_.normalizeLocalePath)(N.effect.parsedAs.pathname,this.locales).pathname),n=this.components[O],f.shallow&&n&&this.route===O&&!y))return{...n,route:O}}if((0,L.isAPIRoute)(O))return handleHardNavigation({url:u,router:this}),new Promise(()=>{});let D=h||await this.fetchComponent(O).then(r=>({Component:r.page,styleSheets:r.styleSheets,__N_SSG:r.mod.__N_SSG,__N_SSP:r.mod.__N_SSP})),k=null==N?void 0:null==(I=N.response)?void 0:I.headers.get("x-middleware-skip"),F=D.__N_SSG||D.__N_SSP;k&&(null==N?void 0:N.dataHref)&&delete this.sdc[N.dataHref];let{props:U,cacheKey:H}=await this._getData(async()=>{if(F){if((null==N?void 0:N.json)&&!k)return{cacheKey:N.cacheKey,props:N.json};let r=(null==N?void 0:N.dataHref)?N.dataHref:this.pageLoader.getDataHref({href:(0,w.formatWithValidation)({pathname:o,query:l}),asPath:d,locale:g}),n=await fetchNextData({dataHref:r,isServerRender:this.isSsr,parseJSON:!0,inflightCache:k?{}:this.sdc,persistCache:!P,isPrefetch:!1,unstable_skipClientCache:b});return{cacheKey:n.cacheKey,props:n.json||{}}}return{headers:{},props:await this.getInitialProps(D.Component,{pathname:o,query:l,asPath:u,locale:g,locales:this.locales,defaultLocale:this.defaultLocale})}});return D.__N_SSP&&x.dataHref&&H&&delete this.sdc[H],this.isPreview||!D.__N_SSG||E||fetchNextData(Object.assign({},x,{isBackground:!0,persistCache:!1,inflightCache:this.sbc})).catch(()=>{}),U.pageProps=Object.assign({},U.pageProps),D.props=U,D.route=O,D.query=l,D.resolvedAs=d,this.components[O]=D,D}catch(r){return this.handleRouteInfoError((0,h.getProperError)(r),o,l,u,f)}}set(r,n,o){return this.state=r,this.sub(n,this.components["/_app"].Component,o)}beforePopState(r){this._bps=r}onlyAHashChange(r){if(!this.asPath)return!1;let[n,o]=this.asPath.split("#",2),[l,u]=r.split("#",2);return!!u&&n===l&&o===u||n===l&&o!==u}scrollToHash(r){let[,n=""]=r.split("#",2);(0,W.handleSmoothScroll)(()=>{if(""===n||"top"===n){window.scrollTo(0,0);return}let r=decodeURIComponent(n),o=document.getElementById(r);if(o){o.scrollIntoView();return}let l=document.getElementsByName(r)[0];l&&l.scrollIntoView()},{onlyHashChange:this.onlyAHashChange(r)})}urlIsNew(r){return this.asPath!==r}async prefetch(r,n,o){if(void 0===n&&(n=r),void 0===o&&(o={}),(0,U.isBot)(window.navigator.userAgent))return;let l=(0,E.parseRelativeUrl)(r),u=l.pathname,{pathname:d,query:f}=l,h=d,g=await this.pageLoader.getPageList(),_=n,y=void 0!==o.locale?o.locale||void 0:this.locale,P=await matchesMiddleware({asPath:n,locale:y,router:this});l.pathname=resolveDynamicRoute(l.pathname,g),(0,b.isDynamicRoute)(l.pathname)&&(d=l.pathname,l.pathname=d,Object.assign(f,(0,S.getRouteMatcher)((0,R.getRouteRegex)(l.pathname))((0,O.parsePath)(n).pathname)||{}),P||(r=(0,w.formatWithValidation)(l)));let j=await withMiddlewareEffects({fetchData:()=>fetchNextData({dataHref:this.pageLoader.getDataHref({href:(0,w.formatWithValidation)({pathname:h,query:f}),skipInterpolation:!0,asPath:_,locale:y}),hasMiddleware:!0,isServerRender:this.isSsr,parseJSON:!0,inflightCache:this.sdc,persistCache:!this.isPreview,isPrefetch:!0}),asPath:n,locale:y,router:this});if((null==j?void 0:j.effect.type)==="rewrite"&&(l.pathname=j.effect.resolvedHref,d=j.effect.resolvedHref,f={...f,...j.effect.parsedAs.query},_=j.effect.parsedAs.pathname,r=(0,w.formatWithValidation)(l)),(null==j?void 0:j.effect.type)==="redirect-external")return;let A=(0,s.removeTrailingSlash)(d);await this._bfl(n,_,o.locale,!0)&&(this.components[u]={__appRouter:!0}),await Promise.all([this.pageLoader._isSsg(A).then(n=>!!n&&fetchNextData({dataHref:(null==j?void 0:j.json)?null==j?void 0:j.dataHref:this.pageLoader.getDataHref({href:r,asPath:_,locale:y}),isServerRender:!1,parseJSON:!0,inflightCache:this.sdc,persistCache:!this.isPreview,isPrefetch:!0,unstable_skipClientCache:o.unstable_skipClientCache||o.priority&&!0}).then(()=>!1).catch(()=>!1)),this.pageLoader[o.priority?"loadPage":"prefetch"](A)])}async fetchComponent(r){let n=getCancelledHandler({route:r,router:this});try{let o=await this.pageLoader.loadPage(r);return n(),o}catch(r){throw n(),r}}_getData(r){let n=!1,cancel=()=>{n=!0};return this.clc=cancel,r().then(r=>{if(cancel===this.clc&&(this.clc=null),n){let r=Error("Loading initial props cancelled");throw r.cancelled=!0,r}return r})}_getFlightData(r){return fetchNextData({dataHref:r,isServerRender:!0,parseJSON:!1,inflightCache:this.sdc,persistCache:!1,isPrefetch:!1}).then(r=>{let{text:n}=r;return{data:n}})}getInitialProps(r,n){let{Component:o}=this.components["/_app"],l=this._wrapApp(o);return n.AppTree=l,(0,P.loadGetInitialProps)(o,{AppTree:l,Component:r,router:this,ctx:n})}get route(){return this.state.route}get pathname(){return this.state.pathname}get query(){return this.state.query}get asPath(){return this.state.asPath}get locale(){return this.state.locale}get isFallback(){return this.state.isFallback}get isPreview(){return this.state.isPreview}constructor(r,n,l,{initialProps:u,pageLoader:d,App:f,wrapApp:h,Component:g,err:_,subscription:y,isFallback:S,locale:R,locales:O,defaultLocale:j,domainLocales:A,isPreview:M}){this.sdc={},this.sbc={},this.isFirstPopStateEvent=!0,this._key=createKey(),this.onPopState=r=>{let n;let{isFirstPopStateEvent:o}=this;this.isFirstPopStateEvent=!1;let l=r.state;if(!l){let{pathname:r,query:n}=this;this.changeState("replaceState",(0,w.formatWithValidation)({pathname:(0,C.addBasePath)(r),query:n}),(0,P.getURL)());return}if(l.__NA){window.location.reload();return}if(!l.__N||o&&this.locale===l.options.locale&&l.as===this.asPath)return;let{url:u,as:s,options:d,key:f}=l;this._key=f;let{pathname:h}=(0,E.parseRelativeUrl)(u);(!this.isSsr||s!==(0,C.addBasePath)(this.asPath)||h!==(0,C.addBasePath)(this.pathname))&&(!this._bps||this._bps(l))&&this.change("replaceState",u,s,Object.assign({},d,{shallow:d.shallow&&this._shallow,locale:d.locale||this.defaultLocale,_h:0}),n)};let I=(0,s.removeTrailingSlash)(r);this.components={},"/_error"!==r&&(this.components[I]={Component:g,initial:!0,props:u,err:_,__N_SSG:u&&u.__N_SSG,__N_SSP:u&&u.__N_SSP}),this.components["/_app"]={Component:f,styleSheets:[]};{let{BloomFilter:r}=o(1403),n={numItems:7,errorRate:.01,numBits:68,numHashes:7,bitArray:[1,0,1,0,1,0,0,0,1,1,0,0,1,0,1,0,1,0,0,1,0,1,1,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,1,1,0,0,0,1,0,0,1,1,1,1,0,1,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,1]},l={numItems:0,errorRate:.01,numBits:0,numHashes:null,bitArray:[]};(null==n?void 0:n.numHashes)&&(this._bfl_s=new r(n.numItems,n.errorRate),this._bfl_s.import(n)),(null==l?void 0:l.numHashes)&&(this._bfl_d=new r(l.numItems,l.errorRate),this._bfl_d.import(l))}this.events=Router.events,this.pageLoader=d;let x=(0,b.isDynamicRoute)(r)&&self.__NEXT_DATA__.autoExport;if(this.basePath="",this.sub=y,this.clc=null,this._wrapApp=h,this.isSsr=!0,this.isLocaleDomain=!1,this.isReady=!!(self.__NEXT_DATA__.gssp||self.__NEXT_DATA__.gip||self.__NEXT_DATA__.isExperimentalCompile||self.__NEXT_DATA__.appGip&&!self.__NEXT_DATA__.gsp||!x&&!self.location.search),this.state={route:I,pathname:r,query:n,asPath:x?r:l,isPreview:!!M,locale:void 0,isFallback:S},this._initialMatchesMiddlewarePromise=Promise.resolve(!1),!l.startsWith("//")){let o={locale:R},u=(0,P.getURL)();this._initialMatchesMiddlewarePromise=matchesMiddleware({router:this,locale:R,asPath:u}).then(s=>(o._shouldResolveHref=l!==r,this.changeState("replaceState",s?u:(0,w.formatWithValidation)({pathname:(0,C.addBasePath)(r),query:n}),u,o),s))}window.addEventListener("popstate",this.onPopState)}};Router.events=(0,y.default)()},142:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"addLocale",{enumerable:!0,get:function(){return addLocale}});let l=o(3776),u=o(6315);function addLocale(r,n,o,s){if(!n||n===o)return r;let d=r.toLowerCase();return!s&&((0,u.pathHasPrefix)(d,"/api")||(0,u.pathHasPrefix)(d,"/"+n.toLowerCase()))?r:(0,l.addPathPrefix)(r,"/"+n)}},3776:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"addPathPrefix",{enumerable:!0,get:function(){return addPathPrefix}});let l=o(891);function addPathPrefix(r,n){if(!r.startsWith("/")||!n)return r;let{pathname:o,query:u,hash:s}=(0,l.parsePath)(r);return""+n+o+u+s}},93:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"addPathSuffix",{enumerable:!0,get:function(){return addPathSuffix}});let l=o(891);function addPathSuffix(r,n){if(!r.startsWith("/")||!n)return r;let{pathname:o,query:u,hash:s}=(0,l.parsePath)(r);return""+o+n+u+s}},9537:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{normalizeAppPath:function(){return normalizeAppPath},normalizeRscURL:function(){return normalizeRscURL},normalizePostponedURL:function(){return normalizePostponedURL}});let l=o(3029),u=o(7494);function normalizeAppPath(r){return(0,l.ensureLeadingSlash)(r.split("/").reduce((r,n,o,l)=>!n||(0,u.isGroupSegment)(n)||"@"===n[0]||("page"===n||"route"===n)&&o===l.length-1?r:r+"/"+n,""))}function normalizeRscURL(r){return r.replace(/\.rsc($|\?)/,"$1")}function normalizePostponedURL(r){let n=new URL(r),{pathname:o}=n;return o&&o.startsWith("/_next/postponed")?(n.pathname=o.substring(16)||"/",n.toString()):r}},2391:function(r,n){"use strict";function asPathToSearchParams(r){return new URL(r,"http://n").searchParams}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"asPathToSearchParams",{enumerable:!0,get:function(){return asPathToSearchParams}})},1530:function(r,n){"use strict";function compareRouterStates(r,n){let o=Object.keys(r);if(o.length!==Object.keys(n).length)return!1;for(let l=o.length;l--;){let u=o[l];if("query"===u){let o=Object.keys(r.query);if(o.length!==Object.keys(n.query).length)return!1;for(let l=o.length;l--;){let u=o[l];if(!n.query.hasOwnProperty(u)||r.query[u]!==n.query[u])return!1}}else if(!n.hasOwnProperty(u)||r[u]!==n[u])return!1}return!0}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"compareRouterStates",{enumerable:!0,get:function(){return compareRouterStates}})},8979:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"formatNextPathnameInfo",{enumerable:!0,get:function(){return formatNextPathnameInfo}});let l=o(6082),u=o(3776),s=o(93),d=o(142);function formatNextPathnameInfo(r){let n=(0,d.addLocale)(r.pathname,r.locale,r.buildId?void 0:r.defaultLocale,r.ignorePrefix);return(r.buildId||!r.trailingSlash)&&(n=(0,l.removeTrailingSlash)(n)),r.buildId&&(n=(0,s.addPathSuffix)((0,u.addPathPrefix)(n,"/_next/data/"+r.buildId),"/"===r.pathname?"index.json":".json")),n=(0,u.addPathPrefix)(n,r.basePath),!r.buildId&&r.trailingSlash?n.endsWith("/")?n:(0,s.addPathSuffix)(n,"/"):(0,l.removeTrailingSlash)(n)}},3833:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{formatUrl:function(){return formatUrl},urlObjectKeys:function(){return d},formatWithValidation:function(){return formatWithValidation}});let l=o(1757),u=l._(o(4828)),s=/https?|ftp|gopher|file/;function formatUrl(r){let{auth:n,hostname:o}=r,l=r.protocol||"",d=r.pathname||"",f=r.hash||"",h=r.query||"",g=!1;n=n?encodeURIComponent(n).replace(/%3A/i,":")+"@":"",r.host?g=n+r.host:o&&(g=n+(~o.indexOf(":")?"["+o+"]":o),r.port&&(g+=":"+r.port)),h&&"object"==typeof h&&(h=String(u.urlQueryToSearchParams(h)));let _=r.search||h&&"?"+h||"";return l&&!l.endsWith(":")&&(l+=":"),r.slashes||(!l||s.test(l))&&!1!==g?(g="//"+(g||""),d&&"/"!==d[0]&&(d="/"+d)):g||(g=""),f&&"#"!==f[0]&&(f="#"+f),_&&"?"!==_[0]&&(_="?"+_),""+l+g+(d=d.replace(/[?#]/g,encodeURIComponent))+(_=_.replace("#","%23"))+f}let d=["auth","hash","host","hostname","href","path","pathname","port","protocol","query","search","slashes"];function formatWithValidation(r){return formatUrl(r)}},8052:function(r,n){"use strict";function getAssetPathFromRoute(r,n){void 0===n&&(n="");let o="/"===r?"/index":/^\/index(\/|$)/.test(r)?"/index"+r:""+r;return o+n}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return getAssetPathFromRoute}})},673:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"getNextPathnameInfo",{enumerable:!0,get:function(){return getNextPathnameInfo}});let l=o(4656),u=o(4980),s=o(6315);function getNextPathnameInfo(r,n){var o,d;let{basePath:f,i18n:h,trailingSlash:g}=null!=(o=n.nextConfig)?o:{},_={pathname:r,trailingSlash:"/"!==r?r.endsWith("/"):g};f&&(0,s.pathHasPrefix)(_.pathname,f)&&(_.pathname=(0,u.removePathPrefix)(_.pathname,f),_.basePath=f);let y=_.pathname;if(_.pathname.startsWith("/_next/data/")&&_.pathname.endsWith(".json")){let r=_.pathname.replace(/^\/_next\/data\//,"").replace(/\.json$/,"").split("/"),o=r[0];_.buildId=o,y="index"!==r[1]?"/"+r.slice(1).join("/"):"/",!0===n.parseData&&(_.pathname=y)}if(h){let r=n.i18nProvider?n.i18nProvider.analyze(_.pathname):(0,l.normalizeLocalePath)(_.pathname,h.locales);_.locale=r.detectedLocale,_.pathname=null!=(d=r.pathname)?d:_.pathname,!r.detectedLocale&&_.buildId&&(r=n.i18nProvider?n.i18nProvider.analyze(y):(0,l.normalizeLocalePath)(y,h.locales)).detectedLocale&&(_.locale=r.detectedLocale)}return _}},9987:function(r,n){"use strict";function handleSmoothScroll(r,n){if(void 0===n&&(n={}),n.onlyHashChange){r();return}let o=document.documentElement,l=o.style.scrollBehavior;o.style.scrollBehavior="auto",n.dontForceLayout||o.getClientRects(),r(),o.style.scrollBehavior=l}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"handleSmoothScroll",{enumerable:!0,get:function(){return handleSmoothScroll}})},1232:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{getSortedRoutes:function(){return l.getSortedRoutes},isDynamicRoute:function(){return u.isDynamicRoute}});let l=o(2839),u=o(8011)},9381:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"interpolateAs",{enumerable:!0,get:function(){return interpolateAs}});let l=o(9001),u=o(8300);function interpolateAs(r,n,o){let s="",d=(0,u.getRouteRegex)(r),f=d.groups,h=(n!==r?(0,l.getRouteMatcher)(d)(n):"")||o;s=r;let g=Object.keys(f);return g.every(r=>{let n=h[r]||"",{repeat:o,optional:l}=f[r],u="["+(o?"...":"")+r+"]";return l&&(u=(n?"":"/")+"["+u+"]"),o&&!Array.isArray(n)&&(n=[n]),(l||r in h)&&(s=s.replace(u,o?n.map(r=>encodeURIComponent(r)).join("/"):encodeURIComponent(n))||"/")})||(s=""),{params:g,result:s}}},6116:function(r,n){"use strict";function isBot(r){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(r)}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"isBot",{enumerable:!0,get:function(){return isBot}})},8011:function(r,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"isDynamicRoute",{enumerable:!0,get:function(){return isDynamicRoute}});let o=/\/\[[^/]+?\](?=\/|$)/;function isDynamicRoute(r){return o.test(r)}},4131:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"isLocalURL",{enumerable:!0,get:function(){return isLocalURL}});let l=o(1306),u=o(5213);function isLocalURL(r){if(!(0,l.isAbsoluteUrl)(r))return!0;try{let n=(0,l.getLocationOrigin)(),o=new URL(r,n);return o.origin===n&&(0,u.hasBasePath)(o.pathname)}catch(r){return!1}}},9302:function(r,n){"use strict";function omit(r,n){let o={};return Object.keys(r).forEach(l=>{n.includes(l)||(o[l]=r[l])}),o}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"omit",{enumerable:!0,get:function(){return omit}})},891:function(r,n){"use strict";function parsePath(r){let n=r.indexOf("#"),o=r.indexOf("?"),l=o>-1&&(n<0||o<n);return l||n>-1?{pathname:r.substring(0,l?o:n),query:l?r.substring(o,n>-1?n:void 0):"",hash:n>-1?r.slice(n):""}:{pathname:r,query:"",hash:""}}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"parsePath",{enumerable:!0,get:function(){return parsePath}})},9823:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"parseRelativeUrl",{enumerable:!0,get:function(){return parseRelativeUrl}});let l=o(1306),u=o(4828);function parseRelativeUrl(r,n){let o=new URL((0,l.getLocationOrigin)()),s=n?new URL(n,o):r.startsWith(".")?new URL(window.location.href):o,{pathname:d,searchParams:f,search:h,hash:g,href:_,origin:y}=new URL(r,s);if(y!==o.origin)throw Error("invariant: invalid relative URL, router received "+r);return{pathname:d,query:(0,u.searchParamsToUrlQuery)(f),search:h,hash:g,href:_.slice(o.origin.length)}}},6315:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"pathHasPrefix",{enumerable:!0,get:function(){return pathHasPrefix}});let l=o(891);function pathHasPrefix(r,n){if("string"!=typeof r)return!1;let{pathname:o}=(0,l.parsePath)(r);return o===n||o.startsWith(n+"/")}},4828:function(r,n){"use strict";function searchParamsToUrlQuery(r){let n={};return r.forEach((r,o)=>{void 0===n[o]?n[o]=r:Array.isArray(n[o])?n[o].push(r):n[o]=[n[o],r]}),n}function stringifyUrlQueryParam(r){return"string"!=typeof r&&("number"!=typeof r||isNaN(r))&&"boolean"!=typeof r?"":String(r)}function urlQueryToSearchParams(r){let n=new URLSearchParams;return Object.entries(r).forEach(r=>{let[o,l]=r;Array.isArray(l)?l.forEach(r=>n.append(o,stringifyUrlQueryParam(r))):n.set(o,stringifyUrlQueryParam(l))}),n}function assign(r){for(var n=arguments.length,o=Array(n>1?n-1:0),l=1;l<n;l++)o[l-1]=arguments[l];return o.forEach(n=>{Array.from(n.keys()).forEach(n=>r.delete(n)),n.forEach((n,o)=>r.append(o,n))}),r}Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{searchParamsToUrlQuery:function(){return searchParamsToUrlQuery},urlQueryToSearchParams:function(){return urlQueryToSearchParams},assign:function(){return assign}})},4980:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"removePathPrefix",{enumerable:!0,get:function(){return removePathPrefix}});let l=o(6315);function removePathPrefix(r,n){if(!(0,l.pathHasPrefix)(r,n))return r;let o=r.slice(n.length);return o.startsWith("/")?o:"/"+o}},6082:function(r,n){"use strict";function removeTrailingSlash(r){return r.replace(/\/$/,"")||"/"}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"removeTrailingSlash",{enumerable:!0,get:function(){return removeTrailingSlash}})},9001:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"getRouteMatcher",{enumerable:!0,get:function(){return getRouteMatcher}});let l=o(1306);function getRouteMatcher(r){let{re:n,groups:o}=r;return r=>{let u=n.exec(r);if(!u)return!1;let decode=r=>{try{return decodeURIComponent(r)}catch(r){throw new l.DecodeError("failed to decode param")}},s={};return Object.keys(o).forEach(r=>{let n=o[r],l=u[n.pos];void 0!==l&&(s[r]=~l.indexOf("/")?l.split("/").map(r=>decode(r)):n.repeat?[decode(l)]:decode(l))}),s}}},8300:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{getRouteRegex:function(){return getRouteRegex},getNamedRouteRegex:function(){return getNamedRouteRegex},getNamedMiddlewareRegex:function(){return getNamedMiddlewareRegex}});let l=o(2407),u=o(4125),s=o(6082);function parseParameter(r){let n=r.startsWith("[")&&r.endsWith("]");n&&(r=r.slice(1,-1));let o=r.startsWith("...");return o&&(r=r.slice(3)),{key:r,repeat:o,optional:n}}function getParametrizedRoute(r){let n=(0,s.removeTrailingSlash)(r).slice(1).split("/"),o={},d=1;return{parameterizedRoute:n.map(r=>{let n=l.INTERCEPTION_ROUTE_MARKERS.find(n=>r.startsWith(n)),s=r.match(/\[((?:\[.*\])|.+)\]/);if(n&&s){let{key:r,optional:l,repeat:f}=parseParameter(s[1]);return o[r]={pos:d++,repeat:f,optional:l},"/"+(0,u.escapeStringRegexp)(n)+"([^/]+?)"}if(!s)return"/"+(0,u.escapeStringRegexp)(r);{let{key:r,repeat:n,optional:l}=parseParameter(s[1]);return o[r]={pos:d++,repeat:n,optional:l},n?l?"(?:/(.+?))?":"/(.+?)":"/([^/]+?)"}}).join(""),groups:o}}function getRouteRegex(r){let{parameterizedRoute:n,groups:o}=getParametrizedRoute(r);return{re:RegExp("^"+n+"(?:/)?$"),groups:o}}function buildGetSafeRouteKey(){let r=0;return()=>{let n="",o=++r;for(;o>0;)n+=String.fromCharCode(97+(o-1)%26),o=Math.floor((o-1)/26);return n}}function getSafeKeyFromSegment(r){let{getSafeRouteKey:n,segment:o,routeKeys:l,keyPrefix:u}=r,{key:s,optional:d,repeat:f}=parseParameter(o),h=s.replace(/\W/g,"");u&&(h=""+u+h);let g=!1;return(0===h.length||h.length>30)&&(g=!0),isNaN(parseInt(h.slice(0,1)))||(g=!0),g&&(h=n()),u?l[h]=""+u+s:l[h]=""+s,f?d?"(?:/(?<"+h+">.+?))?":"/(?<"+h+">.+?)":"/(?<"+h+">[^/]+?)"}function getNamedParametrizedRoute(r,n){let o=(0,s.removeTrailingSlash)(r).slice(1).split("/"),d=buildGetSafeRouteKey(),f={};return{namedParameterizedRoute:o.map(r=>{let o=l.INTERCEPTION_ROUTE_MARKERS.some(n=>r.startsWith(n)),s=r.match(/\[((?:\[.*\])|.+)\]/);return o&&s?getSafeKeyFromSegment({getSafeRouteKey:d,segment:s[1],routeKeys:f,keyPrefix:n?"nxtI":void 0}):s?getSafeKeyFromSegment({getSafeRouteKey:d,segment:s[1],routeKeys:f,keyPrefix:n?"nxtP":void 0}):"/"+(0,u.escapeStringRegexp)(r)}).join(""),routeKeys:f}}function getNamedRouteRegex(r,n){let o=getNamedParametrizedRoute(r,n);return{...getRouteRegex(r),namedRegex:"^"+o.namedParameterizedRoute+"(?:/)?$",routeKeys:o.routeKeys}}function getNamedMiddlewareRegex(r,n){let{parameterizedRoute:o}=getParametrizedRoute(r),{catchAll:l=!0}=n;if("/"===o)return{namedRegex:"^/"+(l?".*":"")+"$"};let{namedParameterizedRoute:u}=getNamedParametrizedRoute(r,!1);return{namedRegex:"^"+u+(l?"(?:(/.*)?)":"")+"$"}}},2839:function(r,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"getSortedRoutes",{enumerable:!0,get:function(){return getSortedRoutes}});let UrlNode=class UrlNode{insert(r){this._insert(r.split("/").filter(Boolean),[],!1)}smoosh(){return this._smoosh()}_smoosh(r){void 0===r&&(r="/");let n=[...this.children.keys()].sort();null!==this.slugName&&n.splice(n.indexOf("[]"),1),null!==this.restSlugName&&n.splice(n.indexOf("[...]"),1),null!==this.optionalRestSlugName&&n.splice(n.indexOf("[[...]]"),1);let o=n.map(n=>this.children.get(n)._smoosh(""+r+n+"/")).reduce((r,n)=>[...r,...n],[]);if(null!==this.slugName&&o.push(...this.children.get("[]")._smoosh(r+"["+this.slugName+"]/")),!this.placeholder){let n="/"===r?"/":r.slice(0,-1);if(null!=this.optionalRestSlugName)throw Error('You cannot define a route with the same specificity as a optional catch-all route ("'+n+'" and "'+n+"[[..."+this.optionalRestSlugName+']]").');o.unshift(n)}return null!==this.restSlugName&&o.push(...this.children.get("[...]")._smoosh(r+"[..."+this.restSlugName+"]/")),null!==this.optionalRestSlugName&&o.push(...this.children.get("[[...]]")._smoosh(r+"[[..."+this.optionalRestSlugName+"]]/")),o}_insert(r,n,o){if(0===r.length){this.placeholder=!1;return}if(o)throw Error("Catch-all must be the last part of the URL.");let l=r[0];if(l.startsWith("[")&&l.endsWith("]")){let u=l.slice(1,-1),s=!1;if(u.startsWith("[")&&u.endsWith("]")&&(u=u.slice(1,-1),s=!0),u.startsWith("...")&&(u=u.substring(3),o=!0),u.startsWith("[")||u.endsWith("]"))throw Error("Segment names may not start or end with extra brackets ('"+u+"').");if(u.startsWith("."))throw Error("Segment names may not start with erroneous periods ('"+u+"').");function handleSlug(r,o){if(null!==r&&r!==o)throw Error("You cannot use different slug names for the same dynamic path ('"+r+"' !== '"+o+"').");n.forEach(r=>{if(r===o)throw Error('You cannot have the same slug name "'+o+'" repeat within a single dynamic path');if(r.replace(/\W/g,"")===l.replace(/\W/g,""))throw Error('You cannot have the slug names "'+r+'" and "'+o+'" differ only by non-word symbols within a single dynamic path')}),n.push(o)}if(o){if(s){if(null!=this.restSlugName)throw Error('You cannot use both an required and optional catch-all route at the same level ("[...'+this.restSlugName+']" and "'+r[0]+'" ).');handleSlug(this.optionalRestSlugName,u),this.optionalRestSlugName=u,l="[[...]]"}else{if(null!=this.optionalRestSlugName)throw Error('You cannot use both an optional and required catch-all route at the same level ("[[...'+this.optionalRestSlugName+']]" and "'+r[0]+'").');handleSlug(this.restSlugName,u),this.restSlugName=u,l="[...]"}}else{if(s)throw Error('Optional route parameters are not yet supported ("'+r[0]+'").');handleSlug(this.slugName,u),this.slugName=u,l="[]"}}this.children.has(l)||this.children.set(l,new UrlNode),this.children.get(l)._insert(r.slice(1),n,o)}constructor(){this.placeholder=!0,this.children=new Map,this.slugName=null,this.restSlugName=null,this.optionalRestSlugName=null}};function getSortedRoutes(r){let n=new UrlNode;return r.forEach(r=>n.insert(r)),n.smoosh()}},510:function(r,n){"use strict";let o;Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{default:function(){return _default},setConfig:function(){return setConfig}});let _default=()=>o;function setConfig(r){o=r}},7494:function(r,n){"use strict";function isGroupSegment(r){return"("===r[0]&&r.endsWith(")")}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"isGroupSegment",{enumerable:!0,get:function(){return isGroupSegment}})},3632:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"default",{enumerable:!0,get:function(){return SideEffect}});let l=o(7294),u=l.useLayoutEffect,s=l.useEffect;function SideEffect(r){let{headManager:n,reduceComponentsToState:o}=r;function emitChange(){if(n&&n.mountedInstances){let u=l.Children.toArray(Array.from(n.mountedInstances).filter(Boolean));n.updateHead(o(u,r))}}return u(()=>{var o;return null==n||null==(o=n.mountedInstances)||o.add(r.children),()=>{var o;null==n||null==(o=n.mountedInstances)||o.delete(r.children)}}),u(()=>(n&&(n._pendingUpdate=emitChange),()=>{n&&(n._pendingUpdate=emitChange)})),s(()=>(n&&n._pendingUpdate&&(n._pendingUpdate(),n._pendingUpdate=null),()=>{n&&n._pendingUpdate&&(n._pendingUpdate(),n._pendingUpdate=null)})),null}},1306:function(r,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{WEB_VITALS:function(){return o},execOnce:function(){return execOnce},isAbsoluteUrl:function(){return isAbsoluteUrl},getLocationOrigin:function(){return getLocationOrigin},getURL:function(){return getURL},getDisplayName:function(){return getDisplayName},isResSent:function(){return isResSent},normalizeRepeatedSlashes:function(){return normalizeRepeatedSlashes},loadGetInitialProps:function(){return loadGetInitialProps},SP:function(){return u},ST:function(){return s},DecodeError:function(){return DecodeError},NormalizeError:function(){return NormalizeError},PageNotFoundError:function(){return PageNotFoundError},MissingStaticPage:function(){return MissingStaticPage},MiddlewareNotFoundError:function(){return MiddlewareNotFoundError},stringifyError:function(){return stringifyError}});let o=["CLS","FCP","FID","INP","LCP","TTFB"];function execOnce(r){let n,o=!1;return function(){for(var l=arguments.length,u=Array(l),s=0;s<l;s++)u[s]=arguments[s];return o||(o=!0,n=r(...u)),n}}let l=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,isAbsoluteUrl=r=>l.test(r);function getLocationOrigin(){let{protocol:r,hostname:n,port:o}=window.location;return r+"//"+n+(o?":"+o:"")}function getURL(){let{href:r}=window.location,n=getLocationOrigin();return r.substring(n.length)}function getDisplayName(r){return"string"==typeof r?r:r.displayName||r.name||"Unknown"}function isResSent(r){return r.finished||r.headersSent}function normalizeRepeatedSlashes(r){let n=r.split("?"),o=n[0];return o.replace(/\\/g,"/").replace(/\/\/+/g,"/")+(n[1]?"?"+n.slice(1).join("?"):"")}async function loadGetInitialProps(r,n){let o=n.res||n.ctx&&n.ctx.res;if(!r.getInitialProps)return n.ctx&&n.Component?{pageProps:await loadGetInitialProps(n.Component,n.ctx)}:{};let l=await r.getInitialProps(n);if(o&&isResSent(o))return l;if(!l){let n='"'+getDisplayName(r)+'.getInitialProps()" should resolve to an object. But found "'+l+'" instead.';throw Error(n)}return l}let u="undefined"!=typeof performance,s=u&&["mark","measure","getEntriesByName"].every(r=>"function"==typeof performance[r]);let DecodeError=class DecodeError extends Error{};let NormalizeError=class NormalizeError extends Error{};let PageNotFoundError=class PageNotFoundError extends Error{constructor(r){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+r}};let MissingStaticPage=class MissingStaticPage extends Error{constructor(r,n){super(),this.message="Failed to load static file for page: "+r+" "+n}};let MiddlewareNotFoundError=class MiddlewareNotFoundError extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}};function stringifyError(r){return JSON.stringify({message:r.message,stack:r.stack})}},9941:function(r,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"warnOnce",{enumerable:!0,get:function(){return warnOnce}});let warnOnce=r=>{}},8018:function(r){var n,o,l,u,s,d,f,h,g,_,y,P,b,E,S,R,w,O,j,A,M,C,I,x,L,N,D,k,F,U,H,B,W,q,z,G,V,X,Y,K,Q,$,J,Z,ee,et;(n={}).d=function(r,o){for(var l in o)n.o(o,l)&&!n.o(r,l)&&Object.defineProperty(r,l,{enumerable:!0,get:o[l]})},n.o=function(r,n){return Object.prototype.hasOwnProperty.call(r,n)},n.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},void 0!==n&&(n.ab="//"),o={},n.r(o),n.d(o,{getCLS:function(){return I},getFCP:function(){return A},getFID:function(){return U},getINP:function(){return $},getLCP:function(){return Z},getTTFB:function(){return et},onCLS:function(){return I},onFCP:function(){return A},onFID:function(){return U},onINP:function(){return $},onLCP:function(){return Z},onTTFB:function(){return et}}),h=-1,g=function(r){addEventListener("pageshow",function(n){n.persisted&&(h=n.timeStamp,r(n))},!0)},_=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},y=function(){var r=_();return r&&r.activationStart||0},P=function(r,n){var o=_(),l="navigate";return h>=0?l="back-forward-cache":o&&(l=document.prerendering||y()>0?"prerender":o.type.replace(/_/g,"-")),{name:r,value:void 0===n?-1:n,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:l}},b=function(r,n,o){try{if(PerformanceObserver.supportedEntryTypes.includes(r)){var l=new PerformanceObserver(function(r){n(r.getEntries())});return l.observe(Object.assign({type:r,buffered:!0},o||{})),l}}catch(r){}},E=function(r,n){var T=function t(o){"pagehide"!==o.type&&"hidden"!==document.visibilityState||(r(o),n&&(removeEventListener("visibilitychange",t,!0),removeEventListener("pagehide",t,!0)))};addEventListener("visibilitychange",T,!0),addEventListener("pagehide",T,!0)},S=function(r,n,o,l){var u,s;return function(d){var f;n.value>=0&&(d||l)&&((s=n.value-(u||0))||void 0===u)&&(u=n.value,n.delta=s,n.rating=(f=n.value)>o[1]?"poor":f>o[0]?"needs-improvement":"good",r(n))}},R=-1,w=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},O=function(){E(function(r){R=r.timeStamp},!0)},j=function(){return R<0&&(R=w(),O(),g(function(){setTimeout(function(){R=w(),O()},0)})),{get firstHiddenTime(){return R}}},A=function(r,n){n=n||{};var o,l=[1800,3e3],u=j(),s=P("FCP"),c=function(r){r.forEach(function(r){"first-contentful-paint"===r.name&&(f&&f.disconnect(),r.startTime<u.firstHiddenTime&&(s.value=r.startTime-y(),s.entries.push(r),o(!0)))})},d=window.performance&&window.performance.getEntriesByName&&window.performance.getEntriesByName("first-contentful-paint")[0],f=d?null:b("paint",c);(d||f)&&(o=S(r,s,l,n.reportAllChanges),d&&c([d]),g(function(u){o=S(r,s=P("FCP"),l,n.reportAllChanges),requestAnimationFrame(function(){requestAnimationFrame(function(){s.value=performance.now()-u.timeStamp,o(!0)})})}))},M=!1,C=-1,I=function(r,n){n=n||{};var o=[.1,.25];M||(A(function(r){C=r.value}),M=!0);var l,i=function(n){C>-1&&r(n)},u=P("CLS",0),s=0,d=[],p=function(r){r.forEach(function(r){if(!r.hadRecentInput){var n=d[0],o=d[d.length-1];s&&r.startTime-o.startTime<1e3&&r.startTime-n.startTime<5e3?(s+=r.value,d.push(r)):(s=r.value,d=[r]),s>u.value&&(u.value=s,u.entries=d,l())}})},f=b("layout-shift",p);f&&(l=S(i,u,o,n.reportAllChanges),E(function(){p(f.takeRecords()),l(!0)}),g(function(){s=0,C=-1,l=S(i,u=P("CLS",0),o,n.reportAllChanges)}))},x={passive:!0,capture:!0},L=new Date,N=function(r,n){l||(l=n,u=r,s=new Date,F(removeEventListener),D())},D=function(){if(u>=0&&u<s-L){var r={entryType:"first-input",name:l.type,target:l.target,cancelable:l.cancelable,startTime:l.timeStamp,processingStart:l.timeStamp+u};d.forEach(function(n){n(r)}),d=[]}},k=function(r){if(r.cancelable){var n,o,l,u=(r.timeStamp>1e12?new Date:performance.now())-r.timeStamp;"pointerdown"==r.type?(n=function(){N(u,r),l()},o=function(){l()},l=function(){removeEventListener("pointerup",n,x),removeEventListener("pointercancel",o,x)},addEventListener("pointerup",n,x),addEventListener("pointercancel",o,x)):N(u,r)}},F=function(r){["mousedown","keydown","touchstart","pointerdown"].forEach(function(n){return r(n,k,x)})},U=function(r,n){n=n||{};var o,s=[100,300],f=j(),h=P("FID"),v=function(r){r.startTime<f.firstHiddenTime&&(h.value=r.processingStart-r.startTime,h.entries.push(r),o(!0))},m=function(r){r.forEach(v)},_=b("first-input",m);o=S(r,h,s,n.reportAllChanges),_&&E(function(){m(_.takeRecords()),_.disconnect()},!0),_&&g(function(){o=S(r,h=P("FID"),s,n.reportAllChanges),d=[],u=-1,l=null,F(addEventListener),d.push(v),D()})},H=0,B=1/0,W=0,q=function(r){r.forEach(function(r){r.interactionId&&(B=Math.min(B,r.interactionId),H=(W=Math.max(W,r.interactionId))?(W-B)/7+1:0)})},z=function(){return f?H:performance.interactionCount||0},G=function(){"interactionCount"in performance||f||(f=b("event",q,{type:"event",buffered:!0,durationThreshold:0}))},V=0,X=function(){return z()-V},Y=[],K={},Q=function(r){var n=Y[Y.length-1],o=K[r.interactionId];if(o||Y.length<10||r.duration>n.latency){if(o)o.entries.push(r),o.latency=Math.max(o.latency,r.duration);else{var l={id:r.interactionId,latency:r.duration,entries:[r]};K[l.id]=l,Y.push(l)}Y.sort(function(r,n){return n.latency-r.latency}),Y.splice(10).forEach(function(r){delete K[r.id]})}},$=function(r,n){n=n||{};var o=[200,500];G();var l,u=P("INP"),a=function(r){r.forEach(function(r){r.interactionId&&Q(r),"first-input"!==r.entryType||Y.some(function(n){return n.entries.some(function(n){return r.duration===n.duration&&r.startTime===n.startTime})})||Q(r)});var n,o=(n=Math.min(Y.length-1,Math.floor(X()/50)),Y[n]);o&&o.latency!==u.value&&(u.value=o.latency,u.entries=o.entries,l())},s=b("event",a,{durationThreshold:n.durationThreshold||40});l=S(r,u,o,n.reportAllChanges),s&&(s.observe({type:"first-input",buffered:!0}),E(function(){a(s.takeRecords()),u.value<0&&X()>0&&(u.value=0,u.entries=[]),l(!0)}),g(function(){Y=[],V=z(),l=S(r,u=P("INP"),o,n.reportAllChanges)}))},J={},Z=function(r,n){n=n||{};var o,l=[2500,4e3],u=j(),s=P("LCP"),c=function(r){var n=r[r.length-1];if(n){var l=n.startTime-y();l<u.firstHiddenTime&&(s.value=l,s.entries=[n],o())}},d=b("largest-contentful-paint",c);if(d){o=S(r,s,l,n.reportAllChanges);var v=function(){J[s.id]||(c(d.takeRecords()),d.disconnect(),J[s.id]=!0,o(!0))};["keydown","click"].forEach(function(r){addEventListener(r,v,{once:!0,capture:!0})}),E(v,!0),g(function(u){o=S(r,s=P("LCP"),l,n.reportAllChanges),requestAnimationFrame(function(){requestAnimationFrame(function(){s.value=performance.now()-u.timeStamp,J[s.id]=!0,o(!0)})})})}},ee=function e(r){document.prerendering?addEventListener("prerenderingchange",function(){return e(r)},!0):"complete"!==document.readyState?addEventListener("load",function(){return e(r)},!0):setTimeout(r,0)},et=function(r,n){n=n||{};var o=[800,1800],l=P("TTFB"),u=S(r,l,o,n.reportAllChanges);ee(function(){var s=_();if(s){if(l.value=Math.max(s.responseStart-y(),0),l.value<0||l.value>performance.now())return;l.entries=[s],u(!0),g(function(){(u=S(r,l=P("TTFB",0),o,n.reportAllChanges))(!0)})}})},r.exports=o},9423:function(r,n){"use strict";function isAPIRoute(r){return"/api"===r||!!(null==r?void 0:r.startsWith("/api/"))}Object.defineProperty(n,"__esModule",{value:!0}),Object.defineProperty(n,"isAPIRoute",{enumerable:!0,get:function(){return isAPIRoute}})},676:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{default:function(){return isError},getProperError:function(){return getProperError}});let l=o(9942);function isError(r){return"object"==typeof r&&null!==r&&"name"in r&&"message"in r}function getProperError(r){return isError(r)?r:Error((0,l.isPlainObject)(r)?JSON.stringify(r):r+"")}},2407:function(r,n,o){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),function(r,n){for(var o in n)Object.defineProperty(r,o,{enumerable:!0,get:n[o]})}(n,{INTERCEPTION_ROUTE_MARKERS:function(){return u},isInterceptionRouteAppPath:function(){return isInterceptionRouteAppPath},extractInterceptionRouteInformation:function(){return extractInterceptionRouteInformation}});let l=o(9537),u=["(..)(..)","(.)","(..)","(...)"];function isInterceptionRouteAppPath(r){return void 0!==r.split("/").find(r=>u.find(n=>r.startsWith(n)))}function extractInterceptionRouteInformation(r){let n,o,s;for(let l of r.split("/"))if(o=u.find(r=>l.startsWith(r))){[n,s]=r.split(o,2);break}if(!n||!o||!s)throw Error(`Invalid interception route: ${r}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`);switch(n=(0,l.normalizeAppPath)(n),o){case"(.)":s="/"===n?`/${s}`:n+"/"+s;break;case"(..)":if("/"===n)throw Error(`Invalid interception route: ${r}. Cannot use (..) marker at the root level, use (.) instead.`);s=n.split("/").slice(0,-1).concat(s).join("/");break;case"(...)":s="/"+s;break;case"(..)(..)":let d=n.split("/");if(d.length<=2)throw Error(`Invalid interception route: ${r}. Cannot use (..)(..) marker at the root level or one level up.`);s=d.slice(0,-2).concat(s).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:n,interceptedRoute:s}}},2431:function(){},8754:function(r,n,o){"use strict";function _interop_require_default(r){return r&&r.__esModule?r:{default:r}}o.r(n),o.d(n,{_:function(){return _interop_require_default},_interop_require_default:function(){return _interop_require_default}})},1757:function(r,n,o){"use strict";function _getRequireWildcardCache(r){if("function"!=typeof WeakMap)return null;var n=new WeakMap,o=new WeakMap;return(_getRequireWildcardCache=function(r){return r?o:n})(r)}function _interop_require_wildcard(r,n){if(!n&&r&&r.__esModule)return r;if(null===r||"object"!=typeof r&&"function"!=typeof r)return{default:r};var o=_getRequireWildcardCache(n);if(o&&o.has(r))return o.get(r);var l={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in r)if("default"!==s&&Object.prototype.hasOwnProperty.call(r,s)){var d=u?Object.getOwnPropertyDescriptor(r,s):null;d&&(d.get||d.set)?Object.defineProperty(l,s,d):l[s]=r[s]}return l.default=r,o&&o.set(r,l),l}o.r(n),o.d(n,{_:function(){return _interop_require_wildcard},_interop_require_wildcard:function(){return _interop_require_wildcard}})}},function(r){r.O(0,[774],function(){return r(r.s=6653)}),_N_E=r.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/main-app-0be5dce44311dbbf.js b/.next/static/chunks/main-app-0be5dce44311dbbf.js deleted file mode 100644 index 34fcf3d..0000000 --- a/.next/static/chunks/main-app-0be5dce44311dbbf.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[744],{6539:function(e,n,t){Promise.resolve().then(t.t.bind(t,8827,23)),Promise.resolve().then(t.t.bind(t,4463,23)),Promise.resolve().then(t.t.bind(t,1010,23)),Promise.resolve().then(t.t.bind(t,9126,23)),Promise.resolve().then(t.t.bind(t,4143,23))}},function(e){var n=function(n){return e(e.s=n)};e.O(0,[667,488],function(){return n(4918),n(6539)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/main-app-cf3eb22ffef632f7.js b/.next/static/chunks/main-app-cf3eb22ffef632f7.js new file mode 100644 index 0000000..0019b9e --- /dev/null +++ b/.next/static/chunks/main-app-cf3eb22ffef632f7.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[744],{2060:function(e,n,_){Promise.resolve().then(_.t.bind(_,3728,23)),Promise.resolve().then(_.t.bind(_,9928,23)),Promise.resolve().then(_.t.bind(_,6954,23)),Promise.resolve().then(_.t.bind(_,3170,23)),Promise.resolve().then(_.t.bind(_,7264,23)),Promise.resolve().then(_.t.bind(_,8297,23))}},function(e){var __webpack_exec__=function(n){return e(e.s=n)};e.O(0,[971,472],function(){return __webpack_exec__(2019),__webpack_exec__(2060)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/main-dba5d122367f02b7.js b/.next/static/chunks/main-dba5d122367f02b7.js deleted file mode 100644 index 68a4915..0000000 --- a/.next/static/chunks/main-dba5d122367f02b7.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[179],{37:function(){"trimStart"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),"trimEnd"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),"description"in Symbol.prototype||Object.defineProperty(Symbol.prototype,"description",{configurable:!0,get:function(){var e=/\((.*)\)/.exec(this.toString());return e?e[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(e,t){return t=this.concat.apply([],this),e>1&&t.some(Array.isArray)?t.flat(e-1):t},Array.prototype.flatMap=function(e,t){return this.map(e,t).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(e){if("function"!=typeof e)return this.then(e,e);var t=this.constructor||Promise;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})}),Object.fromEntries||(Object.fromEntries=function(e){return Array.from(e).reduce(function(e,t){return e[t[0]]=t[1],e},{})})},7800:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addBasePath",{enumerable:!0,get:function(){return o}});let n=r(1250),a=r(2432);function o(e,t){return(0,a.normalizePathTrailingSlash)((0,n.addPathPrefix)(e,""))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},328:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addLocale",{enumerable:!0,get:function(){return n}}),r(2432);let n=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return e};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4512:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"detectDomainLocale",{enumerable:!0,get:function(){return r}});let r=function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1146:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hasBasePath",{enumerable:!0,get:function(){return a}});let n=r(7751);function a(e){return(0,n.pathHasPrefix)(e,"")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8321:function(e,t){"use strict";let r;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DOMAttributeNames:function(){return n},isEqualNode:function(){return o},default:function(){return i}});let n={acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv",noModule:"noModule"};function a(e){let{type:t,props:r}=e,a=document.createElement(t);for(let e in r){if(!r.hasOwnProperty(e)||"children"===e||"dangerouslySetInnerHTML"===e||void 0===r[e])continue;let o=n[e]||e.toLowerCase();"script"===t&&("async"===o||"defer"===o||"noModule"===o)?a[o]=!!r[e]:a.setAttribute(o,r[e])}let{children:o,dangerouslySetInnerHTML:i}=r;return i?a.innerHTML=i.__html||"":o&&(a.textContent="string"==typeof o?o:Array.isArray(o)?o.join(""):""),a}function o(e,t){if(e instanceof HTMLElement&&t instanceof HTMLElement){let r=t.getAttribute("nonce");if(r&&!e.getAttribute("nonce")){let n=t.cloneNode(!0);return n.setAttribute("nonce",""),n.nonce=r,r===e.nonce&&e.isEqualNode(n)}}return e.isEqualNode(t)}function i(){return{mountedInstances:new Set,updateHead:e=>{let t={};e.forEach(e=>{if("link"===e.type&&e.props["data-optimized-fonts"]){if(document.querySelector('style[data-href="'+e.props["data-href"]+'"]'))return;e.props.href=e.props["data-href"],e.props["data-href"]=void 0}let r=t[e.type]||[];r.push(e),t[e.type]=r});let n=t.title?t.title[0]:null,a="";if(n){let{children:e}=n.props;a="string"==typeof e?e:Array.isArray(e)?e.join(""):""}a!==document.title&&(document.title=a),["meta","base","link","style","script"].forEach(e=>{r(e,t[e]||[])})}}}r=(e,t)=>{let r=document.getElementsByTagName("head")[0],n=r.querySelector("meta[name=next-head-count]"),i=Number(n.content),l=[];for(let t=0,r=n.previousElementSibling;t<i;t++,r=(null==r?void 0:r.previousElementSibling)||null){var u;(null==r?void 0:null==(u=r.tagName)?void 0:u.toLowerCase())===e&&l.push(r)}let s=t.map(a).filter(e=>{for(let t=0,r=l.length;t<r;t++){let r=l[t];if(o(r,e))return l.splice(t,1),!1}return!0});l.forEach(e=>{var t;return null==(t=e.parentNode)?void 0:t.removeChild(e)}),s.forEach(e=>r.insertBefore(e,n)),n.content=(i-l.length+s.length).toString()},("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4274:function(e,t,r){"use strict";let n,a,o,i,l,u,s,c,f,d,h,p;Object.defineProperty(t,"__esModule",{value:!0});let m=r(1757);Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{version:function(){return F},router:function(){return n},emitter:function(){return q},initialize:function(){return V},hydrate:function(){return ei}});let g=r(8754);r(37);let y=g._(r(7294)),_=g._(r(745)),b=r(1595),v=g._(r(4742)),P=r(5330),w=r(294),S=r(5136),j=r(9719),O=r(3009),E=r(6139),x=r(4842),R=g._(r(8321)),C=g._(r(309)),M=g._(r(2073)),A=r(4105),L=r(9843),T=r(676),I=r(7529),N=r(8673),k=r(1146),D=r(2429),B=r(5174),H=r(9731),U=g._(r(2856)),F="13.4.4",q=(0,v.default)(),W=e=>[].slice.call(e),z=!1;self.__next_require__=r;class G extends y.default.Component{componentDidCatch(e,t){this.props.fn(e,t)}componentDidMount(){this.scrollToHash(),n.isSsr&&(a.isFallback||a.nextExport&&((0,S.isDynamicRoute)(n.pathname)||location.search||z)||a.props&&a.props.__N_SSG&&(location.search||z))&&n.replace(n.pathname+"?"+String((0,j.assign)((0,j.urlQueryToSearchParams)(n.query),new URLSearchParams(location.search))),o,{_h:1,shallow:!a.isFallback&&!z}).catch(e=>{if(!e.cancelled)throw e})}componentDidUpdate(){this.scrollToHash()}scrollToHash(){let{hash:e}=location;if(!(e=e&&e.substring(1)))return;let t=document.getElementById(e);t&&setTimeout(()=>t.scrollIntoView(),0)}render(){return this.props.children}}async function V(e){void 0===e&&(e={}),a=JSON.parse(document.getElementById("__NEXT_DATA__").textContent),window.__NEXT_DATA__=a,p=a.defaultLocale;let t=a.assetPrefix||"";if(r.p=""+t+"/_next/",(0,O.setConfig)({serverRuntimeConfig:{},publicRuntimeConfig:a.runtimeConfig||{}}),o=(0,E.getURL)(),(0,k.hasBasePath)(o)&&(o=(0,N.removeBasePath)(o)),a.scriptLoader){let{initScriptLoader:e}=r(1827);e(a.scriptLoader)}i=new C.default(a.buildId,t);let s=e=>{let[t,r]=e;return i.routeLoader.onEntrypoint(t,r)};return window.__NEXT_P&&window.__NEXT_P.map(e=>setTimeout(()=>s(e),0)),window.__NEXT_P=[],window.__NEXT_P.push=s,(u=(0,R.default)()).getIsSsr=()=>n.isSsr,l=document.getElementById("__next"),{assetPrefix:t}}function X(e,t){return y.default.createElement(e,t)}function Y(e){var t;let{children:r}=e;return y.default.createElement(G,{fn:e=>J({App:f,err:e}).catch(e=>console.error("Error rendering page: ",e))},y.default.createElement(D.AppRouterContext.Provider,{value:(0,B.adaptForAppRouterInstance)(n)},y.default.createElement(H.SearchParamsContext.Provider,{value:(0,B.adaptForSearchParams)(n)},y.default.createElement(B.PathnameContextProviderAdapter,{router:n,isAutoExport:null!=(t=self.__NEXT_DATA__.autoExport)&&t},y.default.createElement(P.RouterContext.Provider,{value:(0,L.makePublicRouterInstance)(n)},y.default.createElement(b.HeadManagerContext.Provider,{value:u},y.default.createElement(I.ImageConfigContext.Provider,{value:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1}},r)))))))}let $=e=>t=>{let r={...t,Component:h,err:a.err,router:n};return y.default.createElement(Y,null,X(e,r))};function J(e){let{App:t,err:l}=e;return console.error(l),console.error("A client-side exception has occurred, see here for more info: https://nextjs.org/docs/messages/client-side-exception-occurred"),i.loadPage("/_error").then(n=>{let{page:a,styleSheets:o}=n;return(null==s?void 0:s.Component)===a?Promise.resolve().then(()=>m._(r(8495))).then(n=>Promise.resolve().then(()=>m._(r(3739))).then(r=>(t=r.default,e.App=t,n))).then(e=>({ErrorComponent:e.default,styleSheets:[]})):{ErrorComponent:a,styleSheets:o}}).then(r=>{var i;let{ErrorComponent:u,styleSheets:s}=r,c=$(t),f={Component:u,AppTree:c,router:n,ctx:{err:l,pathname:a.page,query:a.query,asPath:o,AppTree:c}};return Promise.resolve((null==(i=e.props)?void 0:i.err)?e.props:(0,E.loadGetInitialProps)(t,f)).then(t=>ea({...e,err:l,Component:u,styleSheets:s,props:t}))})}function K(e){let{callback:t}=e;return y.default.useLayoutEffect(()=>t(),[t]),null}let Q=null,Z=!0;function ee(){["beforeRender","afterHydrate","afterRender","routeChange"].forEach(e=>performance.clearMarks(e))}function et(){E.ST&&(performance.mark("afterHydrate"),performance.measure("Next.js-before-hydration","navigationStart","beforeRender"),performance.measure("Next.js-hydration","beforeRender","afterHydrate"),d&&performance.getEntriesByName("Next.js-hydration").forEach(d),ee())}function er(){if(!E.ST)return;performance.mark("afterRender");let e=performance.getEntriesByName("routeChange","mark");e.length&&(performance.measure("Next.js-route-change-to-render",e[0].name,"beforeRender"),performance.measure("Next.js-render","beforeRender","afterRender"),d&&(performance.getEntriesByName("Next.js-render").forEach(d),performance.getEntriesByName("Next.js-route-change-to-render").forEach(d)),ee(),["Next.js-route-change-to-render","Next.js-render"].forEach(e=>performance.clearMeasures(e)))}function en(e){let{callbacks:t,children:r}=e;return y.default.useLayoutEffect(()=>t.forEach(e=>e()),[t]),y.default.useEffect(()=>{(0,M.default)(d)},[]),r}function ea(e){let t,{App:r,Component:a,props:o,err:i}=e,u="initial"in e?void 0:e.styleSheets;a=a||s.Component,o=o||s.props;let f={...o,Component:a,err:i,router:n};s=f;let d=!1,h=new Promise((e,r)=>{c&&c(),t=()=>{c=null,e()},c=()=>{d=!0,c=null;let e=Error("Cancel rendering route");e.cancelled=!0,r(e)}});function p(){t()}!function(){if(!u)return;let e=W(document.querySelectorAll("style[data-n-href]")),t=new Set(e.map(e=>e.getAttribute("data-n-href"))),r=document.querySelector("noscript[data-n-css]"),n=null==r?void 0:r.getAttribute("data-n-css");u.forEach(e=>{let{href:r,text:a}=e;if(!t.has(r)){let e=document.createElement("style");e.setAttribute("data-n-href",r),e.setAttribute("media","x"),n&&e.setAttribute("nonce",n),document.head.appendChild(e),e.appendChild(document.createTextNode(a))}})}();let m=y.default.createElement(y.default.Fragment,null,y.default.createElement(K,{callback:function(){if(u&&!d){let e=new Set(u.map(e=>e.href)),t=W(document.querySelectorAll("style[data-n-href]")),r=t.map(e=>e.getAttribute("data-n-href"));for(let n=0;n<r.length;++n)e.has(r[n])?t[n].removeAttribute("media"):t[n].setAttribute("media","x");let n=document.querySelector("noscript[data-n-css]");n&&u.forEach(e=>{let{href:t}=e,r=document.querySelector('style[data-n-href="'+t+'"]');r&&(n.parentNode.insertBefore(r,n.nextSibling),n=r)}),W(document.querySelectorAll("link[data-n-p]")).forEach(e=>{e.parentNode.removeChild(e)})}if(e.scroll){let{x:t,y:r}=e.scroll;(0,w.handleSmoothScroll)(()=>{window.scrollTo(t,r)})}}}),y.default.createElement(Y,null,X(r,f),y.default.createElement(x.Portal,{type:"next-route-announcer"},y.default.createElement(A.RouteAnnouncer,null))));return!function(e,t){E.ST&&performance.mark("beforeRender");let r=t(Z?et:er);if(Q){let e=y.default.startTransition;e(()=>{Q.render(r)})}else Q=_.default.hydrateRoot(e,r,{onRecoverableError:U.default}),Z=!1}(l,e=>y.default.createElement(en,{callbacks:[e,p]},m)),h}async function eo(e){if(e.err){await J(e);return}try{await ea(e)}catch(r){let t=(0,T.getProperError)(r);if(t.cancelled)throw t;await J({...e,err:t})}}async function ei(e){let t=a.err;try{let e=await i.routeLoader.whenEntrypoint("/_app");if("error"in e)throw e.error;let{component:t,exports:r}=e;f=t,r&&r.reportWebVitals&&(d=e=>{let t,{id:n,name:a,startTime:o,value:i,duration:l,entryType:u,entries:s,attribution:c}=e,f=Date.now()+"-"+(Math.floor(Math.random()*(9e12-1))+1e12);s&&s.length&&(t=s[0].startTime);let d={id:n||f,name:a,startTime:o||t,value:null==i?l:i,label:"mark"===u||"measure"===u?"custom":"web-vital"};c&&(d.attribution=c),r.reportWebVitals(d)});let n=await i.routeLoader.whenEntrypoint(a.page);if("error"in n)throw n.error;h=n.component}catch(e){t=(0,T.getProperError)(e)}window.__NEXT_PRELOADREADY&&await window.__NEXT_PRELOADREADY(a.dynamicIds),n=(0,L.createRouter)(a.page,a.query,o,{initialProps:a.props,pageLoader:i,App:f,Component:h,wrapApp:$,err:t,isFallback:!!a.isFallback,subscription:(e,t,r)=>eo(Object.assign({},e,{App:t,scroll:r})),locale:a.locale,locales:a.locales,defaultLocale:p,domainLocales:a.domainLocales,isPreview:a.isPreview}),z=await n._initialMatchesMiddlewarePromise;let r={App:f,initial:!0,Component:h,props:a.props,err:t};(null==e?void 0:e.beforeRender)&&await e.beforeRender(),eo(r)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},155:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});let n=r(4274);window.next={version:n.version,get router(){return n.router},emitter:n.emitter},(0,n.initialize)({}).then(()=>(0,n.hydrate)()).catch(console.error),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2432:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return o}});let n=r(7479),a=r(4460),o=e=>{if(!e.startsWith("/"))return e;let{pathname:t,query:r,hash:o}=(0,a.parsePath)(e);return""+(0,n.removeTrailingSlash)(t)+r+o};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2856:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let n=r(4785);function a(e){let t="function"==typeof reportError?reportError:e=>{window.console.error(e)};e.digest!==n.NEXT_DYNAMIC_NO_SSR_CODE&&t(e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},309:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return d}});let n=r(8754),a=r(7800),o=r(4021),i=n._(r(1323)),l=r(328),u=r(5136),s=r(4547),c=r(7479),f=r(6810);class d{getPageList(){return(0,f.getClientBuildManifest)().then(e=>e.sortedPages)}getMiddleware(){return window.__MIDDLEWARE_MATCHERS=[],window.__MIDDLEWARE_MATCHERS}getDataHref(e){let{asPath:t,href:r,locale:n}=e,{pathname:f,query:d,search:h}=(0,s.parseRelativeUrl)(r),{pathname:p}=(0,s.parseRelativeUrl)(t),m=(0,c.removeTrailingSlash)(f);if("/"!==m[0])throw Error('Route name should start with a "/", got "'+m+'"');return(e=>{let t=(0,i.default)((0,c.removeTrailingSlash)((0,l.addLocale)(e,n)),".json");return(0,a.addBasePath)("/_next/data/"+this.buildId+t+h,!0)})(e.skipInterpolation?p:(0,u.isDynamicRoute)(m)?(0,o.interpolateAs)(f,p,d).result:m)}_isSsg(e){return this.promisedSsgManifest.then(t=>t.has(e))}loadPage(e){return this.routeLoader.loadRoute(e).then(e=>{if("component"in e)return{page:e.component,mod:e.exports,styleSheets:e.styles.map(e=>({href:e.href,text:e.content}))};throw e.error})}prefetch(e){return this.routeLoader.prefetch(e)}constructor(e,t){this.routeLoader=(0,f.createRouteLoader)(t),this.buildId=e,this.assetPrefix=t,this.promisedSsgManifest=new Promise(e=>{window.__SSG_MANIFEST?e(window.__SSG_MANIFEST):window.__SSG_MANIFEST_CB=()=>{e(window.__SSG_MANIFEST)}})}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2073:function(e,t,r){"use strict";let n;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return l}});let a=["CLS","FCP","FID","INP","LCP","TTFB"];location.href;let o=!1;function i(e){n&&n(e)}let l=e=>{if(n=e,!o)for(let e of(o=!0,a))try{let t;t||(t=r(8018)),t["on"+e](i)}catch(t){console.warn("Failed to track "+e+" web-vital",t)}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4842:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Portal",{enumerable:!0,get:function(){return o}});let n=r(7294),a=r(3935),o=e=>{let{children:t,type:r}=e,[o,i]=(0,n.useState)(null);return(0,n.useEffect)(()=>{let e=document.createElement(r);return document.body.appendChild(e),i(e),()=>{document.body.removeChild(e)}},[r]),o?(0,a.createPortal)(t,o):null};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8673:function(e,t,r){"use strict";function n(e){return(e=e.slice(0)).startsWith("/")||(e="/"+e),e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeBasePath",{enumerable:!0,get:function(){return n}}),r(1146),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},489:function(e,t,r){"use strict";function n(e,t){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeLocale",{enumerable:!0,get:function(){return n}}),r(4460),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9616:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{requestIdleCallback:function(){return r},cancelIdleCallback:function(){return n}});let r="undefined"!=typeof self&&self.requestIdleCallback&&self.requestIdleCallback.bind(window)||function(e){let t=Date.now();return self.setTimeout(function(){e({didTimeout:!1,timeRemaining:function(){return Math.max(0,50-(Date.now()-t))}})},1)},n="undefined"!=typeof self&&self.cancelIdleCallback&&self.cancelIdleCallback.bind(window)||function(e){return clearTimeout(e)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4105:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RouteAnnouncer:function(){return l},default:function(){return u}});let n=r(8754),a=n._(r(7294)),o=r(9843),i={border:0,clip:"rect(0 0 0 0)",height:"1px",margin:"-1px",overflow:"hidden",padding:0,position:"absolute",top:0,width:"1px",whiteSpace:"nowrap",wordWrap:"normal"},l=()=>{let{asPath:e}=(0,o.useRouter)(),[t,r]=a.default.useState(""),n=a.default.useRef(e);return a.default.useEffect(()=>{if(n.current!==e){if(n.current=e,document.title)r(document.title);else{var t;let n=document.querySelector("h1"),a=null!=(t=null==n?void 0:n.innerText)?t:null==n?void 0:n.textContent;r(a||e)}}},[e]),a.default.createElement("p",{"aria-live":"assertive",id:"__next-route-announcer__",role:"alert",style:i},t)},u=l;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6810:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{markAssetError:function(){return l},isAssetError:function(){return u},getClientBuildManifest:function(){return f},createRouteLoader:function(){return h}}),r(8754),r(1323);let n=r(1251),a=r(9616);function o(e,t,r){let n,a=t.get(e);if(a)return"future"in a?a.future:Promise.resolve(a);let o=new Promise(e=>{n=e});return t.set(e,a={resolve:n,future:o}),r?r().then(e=>(n(e),e)).catch(r=>{throw t.delete(e),r}):o}let i=Symbol("ASSET_LOAD_ERROR");function l(e){return Object.defineProperty(e,i,{})}function u(e){return e&&i in e}let s=function(e){try{return e=document.createElement("link"),!!window.MSInputMethodContext&&!!document.documentMode||e.relList.supports("prefetch")}catch(e){return!1}}();function c(e,t,r){return new Promise((n,o)=>{let i=!1;e.then(e=>{i=!0,n(e)}).catch(o),(0,a.requestIdleCallback)(()=>setTimeout(()=>{i||o(r)},t))})}function f(){if(self.__BUILD_MANIFEST)return Promise.resolve(self.__BUILD_MANIFEST);let e=new Promise(e=>{let t=self.__BUILD_MANIFEST_CB;self.__BUILD_MANIFEST_CB=()=>{e(self.__BUILD_MANIFEST),t&&t()}});return c(e,3800,l(Error("Failed to load client build manifest")))}function d(e,t){return f().then(r=>{if(!(t in r))throw l(Error("Failed to lookup route: "+t));let a=r[t].map(t=>e+"/_next/"+encodeURI(t));return{scripts:a.filter(e=>e.endsWith(".js")).map(e=>(0,n.__unsafeCreateTrustedScriptURL)(e)),css:a.filter(e=>e.endsWith(".css"))}})}function h(e){let t=new Map,r=new Map,n=new Map,i=new Map;function u(e){{var t;let n=r.get(e.toString());return n||(document.querySelector('script[src^="'+e+'"]')?Promise.resolve():(r.set(e.toString(),n=new Promise((r,n)=>{(t=document.createElement("script")).onload=r,t.onerror=()=>n(l(Error("Failed to load script: "+e))),t.crossOrigin=void 0,t.src=e,document.body.appendChild(t)})),n))}}function f(e){let t=n.get(e);return t||n.set(e,t=fetch(e).then(t=>{if(!t.ok)throw Error("Failed to load stylesheet: "+e);return t.text().then(t=>({href:e,content:t}))}).catch(e=>{throw l(e)})),t}return{whenEntrypoint:e=>o(e,t),onEntrypoint(e,r){(r?Promise.resolve().then(()=>r()).then(e=>({component:e&&e.default||e,exports:e}),e=>({error:e})):Promise.resolve(void 0)).then(r=>{let n=t.get(e);n&&"resolve"in n?r&&(t.set(e,r),n.resolve(r)):(r?t.set(e,r):t.delete(e),i.delete(e))})},loadRoute(r,n){return o(r,i,()=>{let a;return c(d(e,r).then(e=>{let{scripts:n,css:a}=e;return Promise.all([t.has(r)?[]:Promise.all(n.map(u)),Promise.all(a.map(f))])}).then(e=>this.whenEntrypoint(r).then(t=>({entrypoint:t,styles:e[1]}))),3800,l(Error("Route did not complete loading: "+r))).then(e=>{let{entrypoint:t,styles:r}=e,n=Object.assign({styles:r},t);return"error"in t?t:n}).catch(e=>{if(n)throw e;return{error:e}}).finally(()=>null==a?void 0:a())})},prefetch(t){let r;return(r=navigator.connection)&&(r.saveData||/2g/.test(r.effectiveType))?Promise.resolve():d(e,t).then(e=>Promise.all(s?e.scripts.map(e=>{var t,r,n;return t=e.toString(),r="script",new Promise((e,a)=>{let o='\n link[rel="prefetch"][href^="'+t+'"],\n link[rel="preload"][href^="'+t+'"],\n script[src^="'+t+'"]';if(document.querySelector(o))return e();n=document.createElement("link"),r&&(n.as=r),n.rel="prefetch",n.crossOrigin=void 0,n.onload=e,n.onerror=()=>a(l(Error("Failed to prefetch: "+t))),n.href=t,document.head.appendChild(n)})}):[])).then(()=>{(0,a.requestIdleCallback)(()=>this.loadRoute(t,!0).catch(()=>{}))}).catch(()=>{})}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9843:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{Router:function(){return o.default},default:function(){return h},withRouter:function(){return u.default},useRouter:function(){return p},createRouter:function(){return m},makePublicRouterInstance:function(){return g}});let n=r(8754),a=n._(r(7294)),o=n._(r(7630)),i=r(5330),l=n._(r(676)),u=n._(r(9987)),s={router:null,readyCallbacks:[],ready(e){if(this.router)return e();this.readyCallbacks.push(e)}},c=["pathname","route","query","asPath","components","isFallback","basePath","locale","locales","defaultLocale","isReady","isPreview","isLocaleDomain","domainLocales"],f=["push","replace","reload","back","prefetch","beforePopState"];function d(){if(!s.router)throw Error('No router instance found.\nYou should only use "next/router" on the client side of your app.\n');return s.router}Object.defineProperty(s,"events",{get:()=>o.default.events}),c.forEach(e=>{Object.defineProperty(s,e,{get(){let t=d();return t[e]}})}),f.forEach(e=>{s[e]=function(){for(var t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];let a=d();return a[e](...r)}}),["routeChangeStart","beforeHistoryChange","routeChangeComplete","routeChangeError","hashChangeStart","hashChangeComplete"].forEach(e=>{s.ready(()=>{o.default.events.on(e,function(){for(var t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];let a="on"+e.charAt(0).toUpperCase()+e.substring(1);if(s[a])try{s[a](...r)}catch(e){console.error("Error when running the Router event: "+a),console.error((0,l.default)(e)?e.message+"\n"+e.stack:e+"")}})})});let h=s;function p(){let e=a.default.useContext(i.RouterContext);if(!e)throw Error("NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted");return e}function m(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return s.router=new o.default(...t),s.readyCallbacks.forEach(e=>e()),s.readyCallbacks=[],s.router}function g(e){let t={};for(let r of c){if("object"==typeof e[r]){t[r]=Object.assign(Array.isArray(e[r])?[]:{},e[r]);continue}t[r]=e[r]}return t.events=o.default.events,f.forEach(r=>{t[r]=function(){for(var t=arguments.length,n=Array(t),a=0;a<t;a++)n[a]=arguments[a];return e[r](...n)}}),t}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1827:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{handleClientScriptLoad:function(){return p},initScriptLoader:function(){return m},default:function(){return y}});let n=r(8754),a=r(1757),o=n._(r(3935)),i=a._(r(7294)),l=r(1595),u=r(8321),s=r(9616),c=new Map,f=new Set,d=["onLoad","onReady","dangerouslySetInnerHTML","children","onError","strategy"],h=e=>{let{src:t,id:r,onLoad:n=()=>{},onReady:a=null,dangerouslySetInnerHTML:o,children:i="",strategy:l="afterInteractive",onError:s}=e,h=r||t;if(h&&f.has(h))return;if(c.has(t)){f.add(h),c.get(t).then(n,s);return}let p=()=>{a&&a(),f.add(h)},m=document.createElement("script"),g=new Promise((e,t)=>{m.addEventListener("load",function(t){e(),n&&n.call(this,t),p()}),m.addEventListener("error",function(e){t(e)})}).catch(function(e){s&&s(e)});for(let[r,n]of(o?(m.innerHTML=o.__html||"",p()):i?(m.textContent="string"==typeof i?i:Array.isArray(i)?i.join(""):"",p()):t&&(m.src=t,c.set(t,g)),Object.entries(e))){if(void 0===n||d.includes(r))continue;let e=u.DOMAttributeNames[r]||r.toLowerCase();m.setAttribute(e,n)}"worker"===l&&m.setAttribute("type","text/partytown"),m.setAttribute("data-nscript",l),document.body.appendChild(m)};function p(e){let{strategy:t="afterInteractive"}=e;"lazyOnload"===t?window.addEventListener("load",()=>{(0,s.requestIdleCallback)(()=>h(e))}):h(e)}function m(e){e.forEach(p),function(){let e=[...document.querySelectorAll('[data-nscript="beforeInteractive"]'),...document.querySelectorAll('[data-nscript="beforePageRender"]')];e.forEach(e=>{let t=e.id||e.getAttribute("src");f.add(t)})}()}function g(e){let{id:t,src:r="",onLoad:n=()=>{},onReady:a=null,strategy:u="afterInteractive",onError:c,...d}=e,{updateScripts:p,scripts:m,getIsSsr:g,appDir:y,nonce:_}=(0,i.useContext)(l.HeadManagerContext),b=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=t||r;b.current||(a&&e&&f.has(e)&&a(),b.current=!0)},[a,t,r]);let v=(0,i.useRef)(!1);if((0,i.useEffect)(()=>{!v.current&&("afterInteractive"===u?h(e):"lazyOnload"===u&&("complete"===document.readyState?(0,s.requestIdleCallback)(()=>h(e)):window.addEventListener("load",()=>{(0,s.requestIdleCallback)(()=>h(e))})),v.current=!0)},[e,u]),("beforeInteractive"===u||"worker"===u)&&(p?(m[u]=(m[u]||[]).concat([{id:t,src:r,onLoad:n,onReady:a,onError:c,...d}]),p(m)):g&&g()?f.add(t||r):g&&!g()&&h(e)),y){if("beforeInteractive"===u)return r?(o.default.preload(r,d.integrity?{as:"script",integrity:d.integrity}:{as:"script"}),i.default.createElement("script",{nonce:_,dangerouslySetInnerHTML:{__html:"(self.__next_s=self.__next_s||[]).push("+JSON.stringify([r])+")"}})):(d.dangerouslySetInnerHTML&&(d.children=d.dangerouslySetInnerHTML.__html,delete d.dangerouslySetInnerHTML),i.default.createElement("script",{nonce:_,dangerouslySetInnerHTML:{__html:"(self.__next_s=self.__next_s||[]).push("+JSON.stringify([0,{...d}])+")"}}));"afterInteractive"===u&&r&&o.default.preload(r,d.integrity?{as:"script",integrity:d.integrity}:{as:"script"})}return null}Object.defineProperty(g,"__nextScript",{value:!0});let y=g;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1251:function(e,t){"use strict";let r;function n(e){var t;return(null==(t=function(){if(void 0===r){var e;r=(null==(e=window.trustedTypes)?void 0:e.createPolicy("nextjs",{createHTML:e=>e,createScript:e=>e,createScriptURL:e=>e}))||null}return r}())?void 0:t.createScriptURL(e))||e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"__unsafeCreateTrustedScriptURL",{enumerable:!0,get:function(){return n}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9987:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return i}});let n=r(8754),a=n._(r(7294)),o=r(9843);function i(e){function t(t){return a.default.createElement(e,{router:(0,o.useRouter)(),...t})}return t.getInitialProps=e.getInitialProps,t.origGetInitialProps=e.origGetInitialProps,t}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3739:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return l}});let n=r(8754),a=n._(r(7294)),o=r(6139);async function i(e){let{Component:t,ctx:r}=e,n=await (0,o.loadGetInitialProps)(t,r);return{pageProps:n}}class l extends a.default.Component{render(){let{Component:e,pageProps:t}=this.props;return a.default.createElement(e,t)}}l.origGetInitialProps=i,l.getInitialProps=i,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8495:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return s}});let n=r(8754),a=n._(r(7294)),o=n._(r(429)),i={400:"Bad Request",404:"This page could not be found",405:"Method Not Allowed",500:"Internal Server Error"};function l(e){let{res:t,err:r}=e,n=t&&t.statusCode?t.statusCode:r?r.statusCode:404;return{statusCode:n}}let u={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{display:"inline-block",textAlign:"left"},h1:{display:"inline-block",margin:"0 20px 0 0",paddingRight:23,fontSize:24,fontWeight:500,verticalAlign:"top",lineHeight:"49px"},h2:{fontSize:14,fontWeight:400,lineHeight:"49px",margin:0}};class s extends a.default.Component{render(){let{statusCode:e,withDarkMode:t=!0}=this.props,r=this.props.title||i[e]||"An unexpected error has occurred";return a.default.createElement("div",{style:u.error},a.default.createElement(o.default,null,a.default.createElement("title",null,e?e+": "+r:"Application error: a client-side exception has occurred")),a.default.createElement("div",null,a.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}"+(t?"@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}":"")}}),e?a.default.createElement("h1",{className:"next-error-h1",style:u.h1},e):null,a.default.createElement("div",{style:u.desc},a.default.createElement("h2",{style:u.h2},this.props.title||e?r:a.default.createElement(a.default.Fragment,null,"Application error: a client-side exception has occurred (see the browser console for more information)"),"."))))}}s.displayName="ErrorPage",s.getInitialProps=l,s.origGetInitialProps=l,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1438:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AmpStateContext",{enumerable:!0,get:function(){return o}});let n=r(8754),a=n._(r(7294)),o=a.default.createContext({})},6309:function(e,t){"use strict";function r(e){let{ampFirst:t=!1,hybrid:r=!1,hasQuery:n=!1}=void 0===e?{}:e;return t||r&&n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return r}})},2429:function(e,t,r){"use strict";var n,a;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{CacheStates:function(){return n},AppRouterContext:function(){return l},LayoutRouterContext:function(){return u},GlobalLayoutRouterContext:function(){return s},TemplateContext:function(){return c}});let o=r(8754),i=o._(r(7294));(a=n||(n={})).LAZY_INITIALIZED="LAZYINITIALIZED",a.DATA_FETCH="DATAFETCH",a.READY="READY";let l=i.default.createContext(null),u=i.default.createContext(null),s=i.default.createContext(null),c=i.default.createContext(null)},101:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"BloomFilter",{enumerable:!0,get:function(){return r}});class r{static from(e,t){void 0===t&&(t=.01);let n=new r(e.length,t);for(let t of e)n.add(t);return n}export(){let e={numItems:this.numItems,errorRate:this.errorRate,numBits:this.numBits,numHashes:this.numHashes,bitArray:this.bitArray};return e}import(e){this.numItems=e.numItems,this.errorRate=e.errorRate,this.numBits=e.numBits,this.numHashes=e.numHashes,this.bitArray=e.bitArray}add(e){let t=this.getHashValues(e);t.forEach(e=>{this.bitArray[e]=1})}contains(e){let t=this.getHashValues(e);return t.every(e=>this.bitArray[e])}getHashValues(e){let t=[];for(let r=1;r<=this.numHashes;r++){let n=function(e){let t=0;for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);t=Math.imul(t^n,1540483477),t^=t>>>13,t=Math.imul(t,1540483477)}return t>>>0}(""+e+r)%this.numBits;t.push(n)}return t}constructor(e,t){this.numItems=e,this.errorRate=t,this.numBits=Math.ceil(-(e*Math.log(t))/(Math.log(2)*Math.log(2))),this.numHashes=Math.ceil(this.numBits/e*Math.log(2)),this.bitArray=Array(this.numBits).fill(0)}}},9713:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"escapeStringRegexp",{enumerable:!0,get:function(){return a}});let r=/[|\\{}()[\]^$+*?.-]/,n=/[|\\{}()[\]^$+*?.-]/g;function a(e){return r.test(e)?e.replace(n,"\\$&"):e}},1595:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HeadManagerContext",{enumerable:!0,get:function(){return o}});let n=r(8754),a=n._(r(7294)),o=a.default.createContext({})},429:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{defaultHead:function(){return c},default:function(){return p}});let n=r(8754),a=r(1757),o=a._(r(7294)),i=n._(r(4831)),l=r(1438),u=r(1595),s=r(6309);function c(e){void 0===e&&(e=!1);let t=[o.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(o.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function f(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===o.default.Fragment?e.concat(o.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}r(6308);let d=["name","httpEquiv","charSet","itemProp"];function h(e,t){let{inAmpMode:r}=t;return e.reduce(f,[]).reverse().concat(c(r).reverse()).filter(function(){let e=new Set,t=new Set,r=new Set,n={};return a=>{let o=!0,i=!1;if(a.key&&"number"!=typeof a.key&&a.key.indexOf("$")>0){i=!0;let t=a.key.slice(a.key.indexOf("$")+1);e.has(t)?o=!1:e.add(t)}switch(a.type){case"title":case"base":t.has(a.type)?o=!1:t.add(a.type);break;case"meta":for(let e=0,t=d.length;e<t;e++){let t=d[e];if(a.props.hasOwnProperty(t)){if("charSet"===t)r.has(t)?o=!1:r.add(t);else{let e=a.props[t],r=n[t]||new Set;("name"!==t||!i)&&r.has(e)?o=!1:(r.add(e),n[t]=r)}}}}return o}}()).reverse().map((e,t)=>{let n=e.key||t;if(!r&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,o.default.cloneElement(e,t)}return o.default.cloneElement(e,{key:n})})}let p=function(e){let{children:t}=e,r=(0,o.useContext)(l.AmpStateContext),n=(0,o.useContext)(u.HeadManagerContext);return o.default.createElement(i.default,{reduceComponentsToState:h,headManager:n,inAmpMode:(0,s.isInAmpMode)(r)},t)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9731:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{SearchParamsContext:function(){return a},PathnameContext:function(){return o}});let n=r(7294),a=(0,n.createContext)(null),o=(0,n.createContext)(null)},1141:function(e,t){"use strict";function r(e,t){let r;let n=e.split("/");return(t||[]).some(t=>!!n[1]&&n[1].toLowerCase()===t.toLowerCase()&&(r=t,n.splice(1,1),e=n.join("/")||"/",!0)),{pathname:e,detectedLocale:r}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizeLocalePath",{enumerable:!0,get:function(){return r}})},7529:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ImageConfigContext",{enumerable:!0,get:function(){return i}});let n=r(8754),a=n._(r(7294)),o=r(8992),i=a.default.createContext(o.imageConfigDefault)},8992:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{VALID_LOADERS:function(){return r},imageConfigDefault:function(){return n}});let r=["default","imgix","cloudinary","akamai","custom"],n={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"inline",remotePatterns:[],unoptimized:!1}},5410:function(e,t){"use strict";function r(e){return Object.prototype.toString.call(e)}function n(e){if("[object Object]"!==r(e))return!1;let t=Object.getPrototypeOf(e);return null===t||t.hasOwnProperty("isPrototypeOf")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getObjectClassLabel:function(){return r},isPlainObject:function(){return n}})},4785:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NEXT_DYNAMIC_NO_SSR_CODE",{enumerable:!0,get:function(){return r}});let r="NEXT_DYNAMIC_NO_SSR_CODE"},4742:function(e,t){"use strict";function r(){let e=Object.create(null);return{on(t,r){(e[t]||(e[t]=[])).push(r)},off(t,r){e[t]&&e[t].splice(e[t].indexOf(r)>>>0,1)},emit(t){for(var r=arguments.length,n=Array(r>1?r-1:0),a=1;a<r;a++)n[a-1]=arguments[a];(e[t]||[]).slice().map(e=>{e(...n)})}}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r}})},3872:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"denormalizePagePath",{enumerable:!0,get:function(){return o}});let n=r(8865),a=r(8886);function o(e){let t=(0,a.normalizePathSep)(e);return t.startsWith("/index/")&&!(0,n.isDynamicRoute)(t)?t.slice(6):"/index"!==t?t:"/"}},8886:function(e,t){"use strict";function r(e){return e.replace(/\\/g,"/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathSep",{enumerable:!0,get:function(){return r}})},5330:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RouterContext",{enumerable:!0,get:function(){return o}});let n=r(8754),a=n._(r(7294)),o=a.default.createContext(null)},5174:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{adaptForAppRouterInstance:function(){return l},adaptForSearchParams:function(){return u},PathnameContextProviderAdapter:function(){return s}});let n=r(1757),a=n._(r(7294)),o=r(9731),i=r(8865);function l(e){return{back(){e.back()},forward(){e.forward()},refresh(){e.reload()},push(t){e.push(t)},replace(t){e.replace(t)},prefetch(t){e.prefetch(t)}}}function u(e){return e.isReady&&e.query?function(e){let t=new URLSearchParams;for(let[r,n]of Object.entries(e))if(Array.isArray(n))for(let e of n)t.append(r,e);else void 0!==n&&t.append(r,n);return t}(e.query):new URLSearchParams}function s(e){let{children:t,router:r,...n}=e,l=(0,a.useRef)(n.isAutoExport),u=(0,a.useMemo)(()=>{let e;let t=l.current;if(t&&(l.current=!1),(0,i.isDynamicRoute)(r.pathname)&&(r.isFallback||t&&!r.isReady))return null;try{e=new URL(r.asPath,"http://f")}catch(e){return"/"}return e.pathname},[r.asPath,r.isFallback,r.isReady,r.pathname]);return a.default.createElement(o.PathnameContext.Provider,{value:u},t)}},7630:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return V},matchesMiddleware:function(){return N},createKey:function(){return W}});let n=r(8754),a=r(1757),o=r(7479),i=r(6810),l=r(1827),u=a._(r(676)),s=r(3872),c=r(1141),f=n._(r(4742)),d=r(6139),h=r(5136),p=r(4547);r(2431);let m=r(8262),g=r(3952),y=r(3507);r(4512);let _=r(4460),b=r(328),v=r(489),P=r(8673),w=r(7800),S=r(1146),j=r(9423),O=r(5007),E=r(8581),x=r(7956),R=r(2009),C=r(3222),M=r(7025),A=r(8769),L=r(4021),T=r(294);function I(){return Object.assign(Error("Route Cancelled"),{cancelled:!0})}async function N(e){let t=await Promise.resolve(e.router.pageLoader.getMiddleware());if(!t)return!1;let{pathname:r}=(0,_.parsePath)(e.asPath),n=(0,S.hasBasePath)(r)?(0,P.removeBasePath)(r):r,a=(0,w.addBasePath)((0,b.addLocale)(n,e.locale));return t.some(e=>new RegExp(e.regexp).test(a))}function k(e){let t=(0,d.getLocationOrigin)();return e.startsWith(t)?e.substring(t.length):e}function D(e,t,r){let[n,a]=(0,A.resolveHref)(e,t,!0),o=(0,d.getLocationOrigin)(),i=n.startsWith(o),l=a&&a.startsWith(o);n=k(n),a=a?k(a):a;let u=i?n:(0,w.addBasePath)(n),s=r?k((0,A.resolveHref)(e,r)):a||n;return{url:u,as:l?s:(0,w.addBasePath)(s)}}function B(e,t){let r=(0,o.removeTrailingSlash)((0,s.denormalizePagePath)(e));return"/404"===r||"/_error"===r?e:(t.includes(r)||t.some(t=>{if((0,h.isDynamicRoute)(t)&&(0,g.getRouteRegex)(t).re.test(r))return e=t,!0}),(0,o.removeTrailingSlash)(e))}async function H(e){let t=await N(e);if(!t||!e.fetchData)return null;try{let t=await e.fetchData(),r=await function(e,t,r){let n={basePath:r.router.basePath,i18n:{locales:r.router.locales},trailingSlash:!1},a=t.headers.get("x-nextjs-rewrite"),l=a||t.headers.get("x-nextjs-matched-path"),u=t.headers.get("x-matched-path");if(!u||l||u.includes("__next_data_catchall")||u.includes("/_error")||u.includes("/404")||(l=u),l){if(l.startsWith("/")){let t=(0,p.parseRelativeUrl)(l),u=(0,O.getNextPathnameInfo)(t.pathname,{nextConfig:n,parseData:!0}),s=(0,o.removeTrailingSlash)(u.pathname);return Promise.all([r.router.pageLoader.getPageList(),(0,i.getClientBuildManifest)()]).then(o=>{let[i,{__rewrites:l}]=o,f=(0,b.addLocale)(u.pathname,u.locale);if((0,h.isDynamicRoute)(f)||!a&&i.includes((0,c.normalizeLocalePath)((0,P.removeBasePath)(f),r.router.locales).pathname)){let r=(0,O.getNextPathnameInfo)((0,p.parseRelativeUrl)(e).pathname,{nextConfig:n,parseData:!0});f=(0,w.addBasePath)(r.pathname),t.pathname=f}if(!i.includes(s)){let e=B(s,i);e!==s&&(s=e)}let d=i.includes(s)?s:B((0,c.normalizeLocalePath)((0,P.removeBasePath)(t.pathname),r.router.locales).pathname,i);if((0,h.isDynamicRoute)(d)){let e=(0,m.getRouteMatcher)((0,g.getRouteRegex)(d))(f);Object.assign(t.query,e||{})}return{type:"rewrite",parsedAs:t,resolvedHref:d}})}let t=(0,_.parsePath)(e),u=(0,E.formatNextPathnameInfo)({...(0,O.getNextPathnameInfo)(t.pathname,{nextConfig:n,parseData:!0}),defaultLocale:r.router.defaultLocale,buildId:""});return Promise.resolve({type:"redirect-external",destination:""+u+t.query+t.hash})}let s=t.headers.get("x-nextjs-redirect");if(s){if(s.startsWith("/")){let e=(0,_.parsePath)(s),t=(0,E.formatNextPathnameInfo)({...(0,O.getNextPathnameInfo)(e.pathname,{nextConfig:n,parseData:!0}),defaultLocale:r.router.defaultLocale,buildId:""});return Promise.resolve({type:"redirect-internal",newAs:""+t+e.query+e.hash,newUrl:""+t+e.query+e.hash})}return Promise.resolve({type:"redirect-external",destination:s})}return Promise.resolve({type:"next"})}(t.dataHref,t.response,e);return{dataHref:t.dataHref,json:t.json,response:t.response,text:t.text,cacheKey:t.cacheKey,effect:r}}catch(e){return null}}let U=Symbol("SSG_DATA_NOT_FOUND");function F(e){try{return JSON.parse(e)}catch(e){return null}}function q(e){var t;let{dataHref:r,inflightCache:n,isPrefetch:a,hasMiddleware:o,isServerRender:l,parseJSON:u,persistCache:s,isBackground:c,unstable_skipClientCache:f}=e,{href:d}=new URL(r,window.location.href),h=e=>(function e(t,r,n){return fetch(t,{credentials:"same-origin",method:n.method||"GET",headers:Object.assign({},n.headers,{"x-nextjs-data":"1"})}).then(a=>!a.ok&&r>1&&a.status>=500?e(t,r-1,n):a)})(r,l?3:1,{headers:Object.assign({},a?{purpose:"prefetch"}:{},a&&o?{"x-middleware-prefetch":"1"}:{}),method:null!=(t=null==e?void 0:e.method)?t:"GET"}).then(t=>t.ok&&(null==e?void 0:e.method)==="HEAD"?{dataHref:r,response:t,text:"",json:{},cacheKey:d}:t.text().then(e=>{if(!t.ok){if(o&&[301,302,307,308].includes(t.status))return{dataHref:r,response:t,text:e,json:{},cacheKey:d};if(404===t.status){var n;if(null==(n=F(e))?void 0:n.notFound)return{dataHref:r,json:{notFound:U},response:t,text:e,cacheKey:d}}let a=Error("Failed to load static props");throw l||(0,i.markAssetError)(a),a}return{dataHref:r,json:u?F(e):null,response:t,text:e,cacheKey:d}})).then(e=>(s&&"no-cache"!==e.response.headers.get("x-middleware-cache")||delete n[d],e)).catch(e=>{throw f||delete n[d],("Failed to fetch"===e.message||"NetworkError when attempting to fetch resource."===e.message||"Load failed"===e.message)&&(0,i.markAssetError)(e),e});return f&&s?h({}).then(e=>(n[d]=Promise.resolve(e),e)):void 0!==n[d]?n[d]:n[d]=h(c?{method:"HEAD"}:{})}function W(){return Math.random().toString(36).slice(2,10)}function z(e){let{url:t,router:r}=e;if(t===(0,w.addBasePath)((0,b.addLocale)(r.asPath,r.locale)))throw Error("Invariant: attempted to hard navigate to the same URL "+t+" "+location.href);window.location.href=t}let G=e=>{let{route:t,router:r}=e,n=!1,a=r.clc=()=>{n=!0};return()=>{if(n){let e=Error('Abort fetching component for route: "'+t+'"');throw e.cancelled=!0,e}a===r.clc&&(r.clc=null)}};class V{reload(){window.location.reload()}back(){window.history.back()}forward(){window.history.forward()}push(e,t,r){return void 0===r&&(r={}),{url:e,as:t}=D(this,e,t),this.change("pushState",e,t,r)}replace(e,t,r){return void 0===r&&(r={}),{url:e,as:t}=D(this,e,t),this.change("replaceState",e,t,r)}async _bfl(e,t,r,n){{let u=!1,s=!1;for(let c of[e,t])if(c){let t=(0,o.removeTrailingSlash)(new URL(c,"http://n").pathname),f=(0,w.addBasePath)((0,b.addLocale)(t,r||this.locale));if(t!==(0,o.removeTrailingSlash)(new URL(this.asPath,"http://n").pathname)){var a,i,l;for(let e of(u=u||!!(null==(a=this._bfl_s)?void 0:a.contains(t))||!!(null==(i=this._bfl_s)?void 0:i.contains(f)),[t,f])){let t=e.split("/");for(let e=0;!s&&e<t.length+1;e++){let r=t.slice(0,e).join("/");if(r&&(null==(l=this._bfl_d)?void 0:l.contains(r))){s=!0;break}}}if(u||s){if(n)return!0;return z({url:(0,w.addBasePath)((0,b.addLocale)(e,r||this.locale,this.defaultLocale)),router:this}),new Promise(()=>{})}}}}return!1}async change(e,t,r,n,a){var s,c,f,j,O,E,C,A,T;let k,H;if(!(0,R.isLocalURL)(t))return z({url:t,router:this}),!1;let F=1===n._h;F||n.shallow||await this._bfl(r,void 0,n.locale);let q=F||n._shouldResolveHref||(0,_.parsePath)(t).pathname===(0,_.parsePath)(r).pathname,W={...this.state},G=!0!==this.isReady;this.isReady=!0;let X=this.isSsr;if(F||(this.isSsr=!1),F&&this.clc)return!1;let Y=W.locale;d.ST&&performance.mark("routeChange");let{shallow:$=!1,scroll:J=!0}=n,K={shallow:$};this._inFlightRoute&&this.clc&&(X||V.events.emit("routeChangeError",I(),this._inFlightRoute,K),this.clc(),this.clc=null),r=(0,w.addBasePath)((0,b.addLocale)((0,S.hasBasePath)(r)?(0,P.removeBasePath)(r):r,n.locale,this.defaultLocale));let Q=(0,v.removeLocale)((0,S.hasBasePath)(r)?(0,P.removeBasePath)(r):r,W.locale);this._inFlightRoute=r;let Z=Y!==W.locale;if(!F&&this.onlyAHashChange(Q)&&!Z){W.asPath=Q,V.events.emit("hashChangeStart",r,K),this.changeState(e,t,r,{...n,scroll:!1}),J&&this.scrollToHash(Q);try{await this.set(W,this.components[W.route],null)}catch(e){throw(0,u.default)(e)&&e.cancelled&&V.events.emit("routeChangeError",e,Q,K),e}return V.events.emit("hashChangeComplete",r,K),!0}let ee=(0,p.parseRelativeUrl)(t),{pathname:et,query:er}=ee;if(null==(s=this.components[et])?void 0:s.__appRouter)return z({url:r,router:this}),new Promise(()=>{});try{[k,{__rewrites:H}]=await Promise.all([this.pageLoader.getPageList(),(0,i.getClientBuildManifest)(),this.pageLoader.getMiddleware()])}catch(e){return z({url:r,router:this}),!1}this.urlIsNew(Q)||Z||(e="replaceState");let en=r;et=et?(0,o.removeTrailingSlash)((0,P.removeBasePath)(et)):et;let ea=(0,o.removeTrailingSlash)(et),eo=r.startsWith("/")&&(0,p.parseRelativeUrl)(r).pathname,ei=!!(eo&&ea!==eo&&(!(0,h.isDynamicRoute)(ea)||!(0,m.getRouteMatcher)((0,g.getRouteRegex)(ea))(eo))),el=!n.shallow&&await N({asPath:r,locale:W.locale,router:this});if(F&&el&&(q=!1),q&&"/_error"!==et&&(n._shouldResolveHref=!0,ee.pathname=B(et,k),ee.pathname===et||(et=ee.pathname,ee.pathname=(0,w.addBasePath)(et),el||(t=(0,y.formatWithValidation)(ee)))),!(0,R.isLocalURL)(r))return z({url:r,router:this}),!1;en=(0,v.removeLocale)((0,P.removeBasePath)(en),W.locale),ea=(0,o.removeTrailingSlash)(et);let eu=!1;if((0,h.isDynamicRoute)(ea)){let e=(0,p.parseRelativeUrl)(en),n=e.pathname,a=(0,g.getRouteRegex)(ea);eu=(0,m.getRouteMatcher)(a)(n);let o=ea===n,i=o?(0,L.interpolateAs)(ea,n,er):{};if(eu&&(!o||i.result))o?r=(0,y.formatWithValidation)(Object.assign({},e,{pathname:i.result,query:(0,M.omit)(er,i.params)})):Object.assign(er,eu);else{let e=Object.keys(a.groups).filter(e=>!er[e]&&!a.groups[e].optional);if(e.length>0&&!el)throw Error((o?"The provided `href` ("+t+") value is missing query values ("+e.join(", ")+") to be interpolated properly. ":"The provided `as` value ("+n+") is incompatible with the `href` value ("+ea+"). ")+"Read more: https://nextjs.org/docs/messages/"+(o?"href-interpolation-failed":"incompatible-href-as"))}}F||V.events.emit("routeChangeStart",r,K);let es="/404"===this.pathname||"/_error"===this.pathname;try{let o=await this.getRouteInfo({route:ea,pathname:et,query:er,as:r,resolvedAs:en,routeProps:K,locale:W.locale,isPreview:W.isPreview,hasMiddleware:el,unstable_skipClientCache:n.unstable_skipClientCache,isQueryUpdating:F&&!this.isFallback,isMiddlewareRewrite:ei});if(F||n.shallow||await this._bfl(r,"resolvedAs"in o?o.resolvedAs:void 0,W.locale),"route"in o&&el){ea=et=o.route||ea,K.shallow||(er=Object.assign({},o.query||{},er));let e=(0,S.hasBasePath)(ee.pathname)?(0,P.removeBasePath)(ee.pathname):ee.pathname;if(eu&&et!==e&&Object.keys(eu).forEach(e=>{eu&&er[e]===eu[e]&&delete er[e]}),(0,h.isDynamicRoute)(et)){let e=!K.shallow&&o.resolvedAs?o.resolvedAs:(0,w.addBasePath)((0,b.addLocale)(new URL(r,location.href).pathname,W.locale),!0),t=e;(0,S.hasBasePath)(t)&&(t=(0,P.removeBasePath)(t));let n=(0,g.getRouteRegex)(et),a=(0,m.getRouteMatcher)(n)(new URL(t,location.href).pathname);a&&Object.assign(er,a)}}if("type"in o){if("redirect-internal"===o.type)return this.change(e,o.newUrl,o.newAs,n);return z({url:o.destination,router:this}),new Promise(()=>{})}let i=o.Component;if(i&&i.unstable_scriptLoader){let e=[].concat(i.unstable_scriptLoader());e.forEach(e=>{(0,l.handleClientScriptLoad)(e.props)})}if((o.__N_SSG||o.__N_SSP)&&o.props){if(o.props.pageProps&&o.props.pageProps.__N_REDIRECT){n.locale=!1;let t=o.props.pageProps.__N_REDIRECT;if(t.startsWith("/")&&!1!==o.props.pageProps.__N_REDIRECT_BASE_PATH){let r=(0,p.parseRelativeUrl)(t);r.pathname=B(r.pathname,k);let{url:a,as:o}=D(this,t,t);return this.change(e,a,o,n)}return z({url:t,router:this}),new Promise(()=>{})}if(W.isPreview=!!o.props.__N_PREVIEW,o.props.notFound===U){let e;try{await this.fetchComponent("/404"),e="/404"}catch(t){e="/_error"}if(o=await this.getRouteInfo({route:e,pathname:e,query:er,as:r,resolvedAs:en,routeProps:{shallow:!1},locale:W.locale,isPreview:W.isPreview,isNotFound:!0}),"type"in o)throw Error("Unexpected middleware effect on /404")}}F&&"/_error"===this.pathname&&(null==(c=self.__NEXT_DATA__.props)?void 0:null==(f=c.pageProps)?void 0:f.statusCode)===500&&(null==(j=o.props)?void 0:j.pageProps)&&(o.props.pageProps.statusCode=500);let s=n.shallow&&W.route===(null!=(O=o.route)?O:ea),d=null!=(E=n.scroll)?E:!F&&!s,y=null!=a?a:d?{x:0,y:0}:null,_={...W,route:ea,pathname:et,query:er,asPath:Q,isFallback:!1};if(F&&es){if(o=await this.getRouteInfo({route:this.pathname,pathname:this.pathname,query:er,as:r,resolvedAs:en,routeProps:{shallow:!1},locale:W.locale,isPreview:W.isPreview,isQueryUpdating:F&&!this.isFallback}),"type"in o)throw Error("Unexpected middleware effect on "+this.pathname);"/_error"===this.pathname&&(null==(C=self.__NEXT_DATA__.props)?void 0:null==(A=C.pageProps)?void 0:A.statusCode)===500&&(null==(T=o.props)?void 0:T.pageProps)&&(o.props.pageProps.statusCode=500);try{await this.set(_,o,y)}catch(e){throw(0,u.default)(e)&&e.cancelled&&V.events.emit("routeChangeError",e,Q,K),e}return!0}V.events.emit("beforeHistoryChange",r,K),this.changeState(e,t,r,n);let v=F&&!y&&!G&&!Z&&(0,x.compareRouterStates)(_,this.state);if(!v){try{await this.set(_,o,y)}catch(e){if(e.cancelled)o.error=o.error||e;else throw e}if(o.error)throw F||V.events.emit("routeChangeError",o.error,Q,K),o.error;F||V.events.emit("routeChangeComplete",r,K),d&&/#.+$/.test(r)&&this.scrollToHash(r)}return!0}catch(e){if((0,u.default)(e)&&e.cancelled)return!1;throw e}}changeState(e,t,r,n){void 0===n&&(n={}),("pushState"!==e||(0,d.getURL)()!==r)&&(this._shallow=n.shallow,window.history[e]({url:t,as:r,options:n,__N:!0,key:this._key="pushState"!==e?this._key:W()},"",r))}async handleRouteInfoError(e,t,r,n,a,o){if(console.error(e),e.cancelled)throw e;if((0,i.isAssetError)(e)||o)throw V.events.emit("routeChangeError",e,n,a),z({url:n,router:this}),I();try{let n;let{page:a,styleSheets:o}=await this.fetchComponent("/_error"),i={props:n,Component:a,styleSheets:o,err:e,error:e};if(!i.props)try{i.props=await this.getInitialProps(a,{err:e,pathname:t,query:r})}catch(e){console.error("Error in error page `getInitialProps`: ",e),i.props={}}return i}catch(e){return this.handleRouteInfoError((0,u.default)(e)?e:Error(e+""),t,r,n,a,!0)}}async getRouteInfo(e){let{route:t,pathname:r,query:n,as:a,resolvedAs:i,routeProps:l,locale:s,hasMiddleware:f,isPreview:d,unstable_skipClientCache:h,isQueryUpdating:p,isMiddlewareRewrite:m,isNotFound:g}=e,_=t;try{var b,v,w,S;let e=G({route:_,router:this}),t=this.components[_];if(l.shallow&&t&&this.route===_)return t;f&&(t=void 0);let u=!t||"initial"in t?void 0:t,O={dataHref:this.pageLoader.getDataHref({href:(0,y.formatWithValidation)({pathname:r,query:n}),skipInterpolation:!0,asPath:g?"/404":i,locale:s}),hasMiddleware:!0,isServerRender:this.isSsr,parseJSON:!0,inflightCache:p?this.sbc:this.sdc,persistCache:!d,isPrefetch:!1,unstable_skipClientCache:h,isBackground:p},E=p&&!m?null:await H({fetchData:()=>q(O),asPath:g?"/404":i,locale:s,router:this}).catch(e=>{if(p)return null;throw e});if(E&&("/_error"===r||"/404"===r)&&(E.effect=void 0),p&&(E?E.json=self.__NEXT_DATA__.props:E={json:self.__NEXT_DATA__.props}),e(),(null==E?void 0:null==(b=E.effect)?void 0:b.type)==="redirect-internal"||(null==E?void 0:null==(v=E.effect)?void 0:v.type)==="redirect-external")return E.effect;if((null==E?void 0:null==(w=E.effect)?void 0:w.type)==="rewrite"){let e=(0,o.removeTrailingSlash)(E.effect.resolvedHref),a=await this.pageLoader.getPageList();if((!p||a.includes(e))&&(_=e,r=E.effect.resolvedHref,n={...n,...E.effect.parsedAs.query},i=(0,P.removeBasePath)((0,c.normalizeLocalePath)(E.effect.parsedAs.pathname,this.locales).pathname),t=this.components[_],l.shallow&&t&&this.route===_&&!f))return{...t,route:_}}if((0,j.isAPIRoute)(_))return z({url:a,router:this}),new Promise(()=>{});let x=u||await this.fetchComponent(_).then(e=>({Component:e.page,styleSheets:e.styleSheets,__N_SSG:e.mod.__N_SSG,__N_SSP:e.mod.__N_SSP})),R=null==E?void 0:null==(S=E.response)?void 0:S.headers.get("x-middleware-skip"),C=x.__N_SSG||x.__N_SSP;R&&(null==E?void 0:E.dataHref)&&delete this.sdc[E.dataHref];let{props:M,cacheKey:A}=await this._getData(async()=>{if(C){if((null==E?void 0:E.json)&&!R)return{cacheKey:E.cacheKey,props:E.json};let e=(null==E?void 0:E.dataHref)?E.dataHref:this.pageLoader.getDataHref({href:(0,y.formatWithValidation)({pathname:r,query:n}),asPath:i,locale:s}),t=await q({dataHref:e,isServerRender:this.isSsr,parseJSON:!0,inflightCache:R?{}:this.sdc,persistCache:!d,isPrefetch:!1,unstable_skipClientCache:h});return{cacheKey:t.cacheKey,props:t.json||{}}}return{headers:{},props:await this.getInitialProps(x.Component,{pathname:r,query:n,asPath:a,locale:s,locales:this.locales,defaultLocale:this.defaultLocale})}});return x.__N_SSP&&O.dataHref&&A&&delete this.sdc[A],this.isPreview||!x.__N_SSG||p||q(Object.assign({},O,{isBackground:!0,persistCache:!1,inflightCache:this.sbc})).catch(()=>{}),M.pageProps=Object.assign({},M.pageProps),x.props=M,x.route=_,x.query=n,x.resolvedAs=i,this.components[_]=x,x}catch(e){return this.handleRouteInfoError((0,u.getProperError)(e),r,n,a,l)}}set(e,t,r){return this.state=e,this.sub(t,this.components["/_app"].Component,r)}beforePopState(e){this._bps=e}onlyAHashChange(e){if(!this.asPath)return!1;let[t,r]=this.asPath.split("#"),[n,a]=e.split("#");return!!a&&t===n&&r===a||t===n&&r!==a}scrollToHash(e){let[,t=""]=e.split("#");if(""===t||"top"===t){(0,T.handleSmoothScroll)(()=>window.scrollTo(0,0));return}let r=decodeURIComponent(t),n=document.getElementById(r);if(n){(0,T.handleSmoothScroll)(()=>n.scrollIntoView());return}let a=document.getElementsByName(r)[0];a&&(0,T.handleSmoothScroll)(()=>a.scrollIntoView())}urlIsNew(e){return this.asPath!==e}async prefetch(e,t,r){if(void 0===t&&(t=e),void 0===r&&(r={}),(0,C.isBot)(window.navigator.userAgent))return;let n=(0,p.parseRelativeUrl)(e),a=n.pathname,{pathname:i,query:l}=n,u=i,s=await this.pageLoader.getPageList(),c=t,f=void 0!==r.locale?r.locale||void 0:this.locale,d=await N({asPath:t,locale:f,router:this});n.pathname=B(n.pathname,s),(0,h.isDynamicRoute)(n.pathname)&&(i=n.pathname,n.pathname=i,Object.assign(l,(0,m.getRouteMatcher)((0,g.getRouteRegex)(n.pathname))((0,_.parsePath)(t).pathname)||{}),d||(e=(0,y.formatWithValidation)(n)));let b=await H({fetchData:()=>q({dataHref:this.pageLoader.getDataHref({href:(0,y.formatWithValidation)({pathname:u,query:l}),skipInterpolation:!0,asPath:c,locale:f}),hasMiddleware:!0,isServerRender:this.isSsr,parseJSON:!0,inflightCache:this.sdc,persistCache:!this.isPreview,isPrefetch:!0}),asPath:t,locale:f,router:this});if((null==b?void 0:b.effect.type)==="rewrite"&&(n.pathname=b.effect.resolvedHref,i=b.effect.resolvedHref,l={...l,...b.effect.parsedAs.query},c=b.effect.parsedAs.pathname,e=(0,y.formatWithValidation)(n)),(null==b?void 0:b.effect.type)==="redirect-external")return;let v=(0,o.removeTrailingSlash)(i);await this._bfl(t,c,r.locale,!0)&&(this.components[a]={__appRouter:!0}),await Promise.all([this.pageLoader._isSsg(v).then(t=>!!t&&q({dataHref:(null==b?void 0:b.json)?null==b?void 0:b.dataHref:this.pageLoader.getDataHref({href:e,asPath:c,locale:f}),isServerRender:!1,parseJSON:!0,inflightCache:this.sdc,persistCache:!this.isPreview,isPrefetch:!0,unstable_skipClientCache:r.unstable_skipClientCache||r.priority&&!0}).then(()=>!1).catch(()=>!1)),this.pageLoader[r.priority?"loadPage":"prefetch"](v)])}async fetchComponent(e){let t=G({route:e,router:this});try{let r=await this.pageLoader.loadPage(e);return t(),r}catch(e){throw t(),e}}_getData(e){let t=!1,r=()=>{t=!0};return this.clc=r,e().then(e=>{if(r===this.clc&&(this.clc=null),t){let e=Error("Loading initial props cancelled");throw e.cancelled=!0,e}return e})}_getFlightData(e){return q({dataHref:e,isServerRender:!0,parseJSON:!1,inflightCache:this.sdc,persistCache:!1,isPrefetch:!1}).then(e=>{let{text:t}=e;return{data:t}})}getInitialProps(e,t){let{Component:r}=this.components["/_app"],n=this._wrapApp(r);return t.AppTree=n,(0,d.loadGetInitialProps)(r,{AppTree:n,Component:e,router:this,ctx:t})}get route(){return this.state.route}get pathname(){return this.state.pathname}get query(){return this.state.query}get asPath(){return this.state.asPath}get locale(){return this.state.locale}get isFallback(){return this.state.isFallback}get isPreview(){return this.state.isPreview}constructor(e,t,n,{initialProps:a,pageLoader:i,App:l,wrapApp:u,Component:s,err:c,subscription:f,isFallback:m,locale:g,locales:_,defaultLocale:b,domainLocales:v,isPreview:P}){this.sdc={},this.sbc={},this.isFirstPopStateEvent=!0,this._key=W(),this.onPopState=e=>{let t;let{isFirstPopStateEvent:r}=this;this.isFirstPopStateEvent=!1;let n=e.state;if(!n){let{pathname:e,query:t}=this;this.changeState("replaceState",(0,y.formatWithValidation)({pathname:(0,w.addBasePath)(e),query:t}),(0,d.getURL)());return}if(n.__NA){window.location.reload();return}if(!n.__N||r&&this.locale===n.options.locale&&n.as===this.asPath)return;let{url:a,as:o,options:i,key:l}=n;this._key=l;let{pathname:u}=(0,p.parseRelativeUrl)(a);(!this.isSsr||o!==(0,w.addBasePath)(this.asPath)||u!==(0,w.addBasePath)(this.pathname))&&(!this._bps||this._bps(n))&&this.change("replaceState",a,o,Object.assign({},i,{shallow:i.shallow&&this._shallow,locale:i.locale||this.defaultLocale,_h:0}),t)};let S=(0,o.removeTrailingSlash)(e);this.components={},"/_error"!==e&&(this.components[S]={Component:s,initial:!0,props:a,err:c,__N_SSG:a&&a.__N_SSG,__N_SSP:a&&a.__N_SSP}),this.components["/_app"]={Component:l,styleSheets:[]};{let{BloomFilter:e}=r(101),t={numItems:6,errorRate:.01,numBits:58,numHashes:7,bitArray:[1,1,0,0,1,1,1,0,0,0,1,1,1,0,0,1,1,0,0,0,1,0,0,1,1,0,1,1,1,0,1,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,1,1,0,1,0,1,1,1,1,0]},n={numItems:0,errorRate:.01,numBits:0,numHashes:null,bitArray:[]};(null==t?void 0:t.numHashes)&&(this._bfl_s=new e(t.numItems,t.errorRate),this._bfl_s.import(t)),(null==n?void 0:n.numHashes)&&(this._bfl_d=new e(n.numItems,n.errorRate),this._bfl_d.import(n))}this.events=V.events,this.pageLoader=i;let j=(0,h.isDynamicRoute)(e)&&self.__NEXT_DATA__.autoExport;if(this.basePath="",this.sub=f,this.clc=null,this._wrapApp=u,this.isSsr=!0,this.isLocaleDomain=!1,this.isReady=!!(self.__NEXT_DATA__.gssp||self.__NEXT_DATA__.gip||self.__NEXT_DATA__.appGip&&!self.__NEXT_DATA__.gsp||!j&&!self.location.search),this.state={route:S,pathname:e,query:t,asPath:j?e:n,isPreview:!!P,locale:void 0,isFallback:m},this._initialMatchesMiddlewarePromise=Promise.resolve(!1),!n.startsWith("//")){let r={locale:g},a=(0,d.getURL)();this._initialMatchesMiddlewarePromise=N({router:this,locale:g,asPath:a}).then(o=>(r._shouldResolveHref=n!==e,this.changeState("replaceState",o?a:(0,y.formatWithValidation)({pathname:(0,w.addBasePath)(e),query:t}),a,r),o))}window.addEventListener("popstate",this.onPopState)}}V.events=(0,f.default)()},8045:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addLocale",{enumerable:!0,get:function(){return o}});let n=r(1250),a=r(7751);function o(e,t,r,o){if(!t||t===r)return e;let i=e.toLowerCase();return!o&&((0,a.pathHasPrefix)(i,"/api")||(0,a.pathHasPrefix)(i,"/"+t.toLowerCase()))?e:(0,n.addPathPrefix)(e,"/"+t)}},1250:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return a}});let n=r(4460);function a(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:a,hash:o}=(0,n.parsePath)(e);return""+t+r+a+o}},1317:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathSuffix",{enumerable:!0,get:function(){return a}});let n=r(4460);function a(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:a,hash:o}=(0,n.parsePath)(e);return""+r+t+a+o}},7956:function(e,t){"use strict";function r(e,t){let r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(let n=r.length;n--;){let a=r[n];if("query"===a){let r=Object.keys(e.query);if(r.length!==Object.keys(t.query).length)return!1;for(let n=r.length;n--;){let a=r[n];if(!t.query.hasOwnProperty(a)||e.query[a]!==t.query[a])return!1}}else if(!t.hasOwnProperty(a)||e[a]!==t[a])return!1}return!0}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"compareRouterStates",{enumerable:!0,get:function(){return r}})},8581:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"formatNextPathnameInfo",{enumerable:!0,get:function(){return l}});let n=r(7479),a=r(1250),o=r(1317),i=r(8045);function l(e){let t=(0,i.addLocale)(e.pathname,e.locale,e.buildId?void 0:e.defaultLocale,e.ignorePrefix);return(e.buildId||!e.trailingSlash)&&(t=(0,n.removeTrailingSlash)(t)),e.buildId&&(t=(0,o.addPathSuffix)((0,a.addPathPrefix)(t,"/_next/data/"+e.buildId),"/"===e.pathname?"index.json":".json")),t=(0,a.addPathPrefix)(t,e.basePath),!e.buildId&&e.trailingSlash?t.endsWith("/")?t:(0,o.addPathSuffix)(t,"/"):(0,n.removeTrailingSlash)(t)}},3507:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{formatUrl:function(){return i},urlObjectKeys:function(){return l},formatWithValidation:function(){return u}});let n=r(1757),a=n._(r(9719)),o=/https?|ftp|gopher|file/;function i(e){let{auth:t,hostname:r}=e,n=e.protocol||"",i=e.pathname||"",l=e.hash||"",u=e.query||"",s=!1;t=t?encodeURIComponent(t).replace(/%3A/i,":")+"@":"",e.host?s=t+e.host:r&&(s=t+(~r.indexOf(":")?"["+r+"]":r),e.port&&(s+=":"+e.port)),u&&"object"==typeof u&&(u=String(a.urlQueryToSearchParams(u)));let c=e.search||u&&"?"+u||"";return n&&!n.endsWith(":")&&(n+=":"),e.slashes||(!n||o.test(n))&&!1!==s?(s="//"+(s||""),i&&"/"!==i[0]&&(i="/"+i)):s||(s=""),l&&"#"!==l[0]&&(l="#"+l),c&&"?"!==c[0]&&(c="?"+c),""+n+s+(i=i.replace(/[?#]/g,encodeURIComponent))+(c=c.replace("#","%23"))+l}let l=["auth","hash","host","hostname","href","path","pathname","port","protocol","query","search","slashes"];function u(e){return i(e)}},1323:function(e,t){"use strict";function r(e,t){void 0===t&&(t="");let r="/"===e?"/index":/^\/index(\/|$)/.test(e)?"/index"+e:""+e;return r+t}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r}})},5007:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getNextPathnameInfo",{enumerable:!0,get:function(){return i}});let n=r(1141),a=r(1606),o=r(7751);function i(e,t){var r,i,l;let{basePath:u,i18n:s,trailingSlash:c}=null!=(r=t.nextConfig)?r:{},f={pathname:e,trailingSlash:"/"!==e?e.endsWith("/"):c};if(u&&(0,o.pathHasPrefix)(f.pathname,u)&&(f.pathname=(0,a.removePathPrefix)(f.pathname,u),f.basePath=u),!0===t.parseData&&f.pathname.startsWith("/_next/data/")&&f.pathname.endsWith(".json")){let e=f.pathname.replace(/^\/_next\/data\//,"").replace(/\.json$/,"").split("/"),t=e[0];f.pathname="index"!==e[1]?"/"+e.slice(1).join("/"):"/",f.buildId=t}if(t.i18nProvider){let e=t.i18nProvider.analyze(f.pathname);f.locale=e.detectedLocale,f.pathname=null!=(i=e.pathname)?i:f.pathname}else if(s){let e=(0,n.normalizeLocalePath)(f.pathname,s.locales);f.locale=e.detectedLocale,f.pathname=null!=(l=e.pathname)?l:f.pathname}return f}},294:function(e,t){"use strict";function r(e,t){void 0===t&&(t={});let r=document.documentElement,n=r.style.scrollBehavior;r.style.scrollBehavior="auto",t.dontForceLayout||r.getClientRects(),e(),r.style.scrollBehavior=n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSmoothScroll",{enumerable:!0,get:function(){return r}})},8865:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getSortedRoutes:function(){return n.getSortedRoutes},isDynamicRoute:function(){return a.isDynamicRoute}});let n=r(1062),a=r(5136)},4021:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"interpolateAs",{enumerable:!0,get:function(){return o}});let n=r(8262),a=r(3952);function o(e,t,r){let o="",i=(0,a.getRouteRegex)(e),l=i.groups,u=(t!==e?(0,n.getRouteMatcher)(i)(t):"")||r;o=e;let s=Object.keys(l);return s.every(e=>{let t=u[e]||"",{repeat:r,optional:n}=l[e],a="["+(r?"...":"")+e+"]";return n&&(a=(t?"":"/")+"["+a+"]"),r&&!Array.isArray(t)&&(t=[t]),(n||e in u)&&(o=o.replace(a,r?t.map(e=>encodeURIComponent(e)).join("/"):encodeURIComponent(t))||"/")})||(o=""),{params:s,result:o}}},3222:function(e,t){"use strict";function r(e){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isBot",{enumerable:!0,get:function(){return r}})},5136:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isDynamicRoute",{enumerable:!0,get:function(){return n}});let r=/\/\[[^/]+?\](?=\/|$)/;function n(e){return r.test(e)}},2009:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isLocalURL",{enumerable:!0,get:function(){return o}});let n=r(6139),a=r(1146);function o(e){if(!(0,n.isAbsoluteUrl)(e))return!0;try{let t=(0,n.getLocationOrigin)(),r=new URL(e,t);return r.origin===t&&(0,a.hasBasePath)(r.pathname)}catch(e){return!1}}},7025:function(e,t){"use strict";function r(e,t){let r={};return Object.keys(e).forEach(n=>{t.includes(n)||(r[n]=e[n])}),r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"omit",{enumerable:!0,get:function(){return r}})},4460:function(e,t){"use strict";function r(e){let t=e.indexOf("#"),r=e.indexOf("?"),n=r>-1&&(t<0||r<t);return n||t>-1?{pathname:e.substring(0,n?r:t),query:n?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return r}})},4547:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseRelativeUrl",{enumerable:!0,get:function(){return o}});let n=r(6139),a=r(9719);function o(e,t){let r=new URL((0,n.getLocationOrigin)()),o=t?new URL(t,r):e.startsWith(".")?new URL(window.location.href):r,{pathname:i,searchParams:l,search:u,hash:s,href:c,origin:f}=new URL(e,o);if(f!==r.origin)throw Error("invariant: invalid relative URL, router received "+e);return{pathname:i,query:(0,a.searchParamsToUrlQuery)(l),search:u,hash:s,href:c.slice(r.origin.length)}}},7751:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return a}});let n=r(4460);function a(e,t){if("string"!=typeof e)return!1;let{pathname:r}=(0,n.parsePath)(e);return r===t||r.startsWith(t+"/")}},9719:function(e,t){"use strict";function r(e){let t={};return e.forEach((e,r)=>{void 0===t[r]?t[r]=e:Array.isArray(t[r])?t[r].push(e):t[r]=[t[r],e]}),t}function n(e){return"string"!=typeof e&&("number"!=typeof e||isNaN(e))&&"boolean"!=typeof e?"":String(e)}function a(e){let t=new URLSearchParams;return Object.entries(e).forEach(e=>{let[r,a]=e;Array.isArray(a)?a.forEach(e=>t.append(r,n(e))):t.set(r,n(a))}),t}function o(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return r.forEach(t=>{Array.from(t.keys()).forEach(t=>e.delete(t)),t.forEach((t,r)=>e.append(r,t))}),e}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{searchParamsToUrlQuery:function(){return r},urlQueryToSearchParams:function(){return a},assign:function(){return o}})},1606:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removePathPrefix",{enumerable:!0,get:function(){return a}});let n=r(7751);function a(e,t){if(!(0,n.pathHasPrefix)(e,t))return e;let r=e.slice(t.length);return r.startsWith("/")?r:"/"+r}},7479:function(e,t){"use strict";function r(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return r}})},8769:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"resolveHref",{enumerable:!0,get:function(){return f}});let n=r(9719),a=r(3507),o=r(7025),i=r(6139),l=r(2432),u=r(2009),s=r(5136),c=r(4021);function f(e,t,r){let f;let d="string"==typeof t?t:(0,a.formatWithValidation)(t),h=d.match(/^[a-zA-Z]{1,}:\/\//),p=h?d.slice(h[0].length):d,m=p.split("?");if((m[0]||"").match(/(\/\/|\\)/)){console.error("Invalid href '"+d+"' passed to next/router in page: '"+e.pathname+"'. Repeated forward-slashes (//) or backslashes \\ are not valid in the href.");let t=(0,i.normalizeRepeatedSlashes)(p);d=(h?h[0]:"")+t}if(!(0,u.isLocalURL)(d))return r?[d]:d;try{f=new URL(d.startsWith("#")?e.asPath:e.pathname,"http://n")}catch(e){f=new URL("/","http://n")}try{let e=new URL(d,f);e.pathname=(0,l.normalizePathTrailingSlash)(e.pathname);let t="";if((0,s.isDynamicRoute)(e.pathname)&&e.searchParams&&r){let r=(0,n.searchParamsToUrlQuery)(e.searchParams),{result:i,params:l}=(0,c.interpolateAs)(e.pathname,e.pathname,r);i&&(t=(0,a.formatWithValidation)({pathname:i,hash:e.hash,query:(0,o.omit)(r,l)}))}let i=e.origin===f.origin?e.href.slice(e.origin.length):e.href;return r?[i,t||i]:i}catch(e){return r?[d]:d}}},8262:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getRouteMatcher",{enumerable:!0,get:function(){return a}});let n=r(6139);function a(e){let{re:t,groups:r}=e;return e=>{let a=t.exec(e);if(!a)return!1;let o=e=>{try{return decodeURIComponent(e)}catch(e){throw new n.DecodeError("failed to decode param")}},i={};return Object.keys(r).forEach(e=>{let t=r[e],n=a[t.pos];void 0!==n&&(i[e]=~n.indexOf("/")?n.split("/").map(e=>o(e)):t.repeat?[o(n)]:o(n))}),i}}},3952:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getRouteRegex:function(){return u},getNamedRouteRegex:function(){return c},getNamedMiddlewareRegex:function(){return f}});let n=r(9713),a=r(7479),o="nxtP";function i(e){let t=e.startsWith("[")&&e.endsWith("]");t&&(e=e.slice(1,-1));let r=e.startsWith("...");return r&&(e=e.slice(3)),{key:e,repeat:r,optional:t}}function l(e){let t=(0,a.removeTrailingSlash)(e).slice(1).split("/"),r={},o=1;return{parameterizedRoute:t.map(e=>{if(!(e.startsWith("[")&&e.endsWith("]")))return"/"+(0,n.escapeStringRegexp)(e);{let{key:t,optional:n,repeat:a}=i(e.slice(1,-1));return r[t]={pos:o++,repeat:a,optional:n},a?n?"(?:/(.+?))?":"/(.+?)":"/([^/]+?)"}}).join(""),groups:r}}function u(e){let{parameterizedRoute:t,groups:r}=l(e);return{re:RegExp("^"+t+"(?:/)?$"),groups:r}}function s(e,t){let r,l;let u=(0,a.removeTrailingSlash)(e).slice(1).split("/"),s=(r=97,l=1,()=>{let e="";for(let t=0;t<l;t++)e+=String.fromCharCode(r),++r>122&&(l++,r=97);return e}),c={};return{namedParameterizedRoute:u.map(e=>{if(!(e.startsWith("[")&&e.endsWith("]")))return"/"+(0,n.escapeStringRegexp)(e);{let{key:r,optional:n,repeat:a}=i(e.slice(1,-1)),l=r.replace(/\W/g,"");t&&(l=""+o+l);let u=!1;return(0===l.length||l.length>30)&&(u=!0),isNaN(parseInt(l.slice(0,1)))||(u=!0),u&&(l=s()),t?c[l]=""+o+r:c[l]=""+r,a?n?"(?:/(?<"+l+">.+?))?":"/(?<"+l+">.+?)":"/(?<"+l+">[^/]+?)"}}).join(""),routeKeys:c}}function c(e,t){let r=s(e,t);return{...u(e),namedRegex:"^"+r.namedParameterizedRoute+"(?:/)?$",routeKeys:r.routeKeys}}function f(e,t){let{parameterizedRoute:r}=l(e),{catchAll:n=!0}=t;if("/"===r)return{namedRegex:"^/"+(n?".*":"")+"$"};let{namedParameterizedRoute:a}=s(e,!1);return{namedRegex:"^"+a+(n?"(?:(/.*)?)":"")+"$"}}},1062:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSortedRoutes",{enumerable:!0,get:function(){return n}});class r{insert(e){this._insert(e.split("/").filter(Boolean),[],!1)}smoosh(){return this._smoosh()}_smoosh(e){void 0===e&&(e="/");let t=[...this.children.keys()].sort();null!==this.slugName&&t.splice(t.indexOf("[]"),1),null!==this.restSlugName&&t.splice(t.indexOf("[...]"),1),null!==this.optionalRestSlugName&&t.splice(t.indexOf("[[...]]"),1);let r=t.map(t=>this.children.get(t)._smoosh(""+e+t+"/")).reduce((e,t)=>[...e,...t],[]);if(null!==this.slugName&&r.push(...this.children.get("[]")._smoosh(e+"["+this.slugName+"]/")),!this.placeholder){let t="/"===e?"/":e.slice(0,-1);if(null!=this.optionalRestSlugName)throw Error('You cannot define a route with the same specificity as a optional catch-all route ("'+t+'" and "'+t+"[[..."+this.optionalRestSlugName+']]").');r.unshift(t)}return null!==this.restSlugName&&r.push(...this.children.get("[...]")._smoosh(e+"[..."+this.restSlugName+"]/")),null!==this.optionalRestSlugName&&r.push(...this.children.get("[[...]]")._smoosh(e+"[[..."+this.optionalRestSlugName+"]]/")),r}_insert(e,t,n){if(0===e.length){this.placeholder=!1;return}if(n)throw Error("Catch-all must be the last part of the URL.");let a=e[0];if(a.startsWith("[")&&a.endsWith("]")){let r=a.slice(1,-1),i=!1;if(r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1),i=!0),r.startsWith("...")&&(r=r.substring(3),n=!0),r.startsWith("[")||r.endsWith("]"))throw Error("Segment names may not start or end with extra brackets ('"+r+"').");if(r.startsWith("."))throw Error("Segment names may not start with erroneous periods ('"+r+"').");function o(e,r){if(null!==e&&e!==r)throw Error("You cannot use different slug names for the same dynamic path ('"+e+"' !== '"+r+"').");t.forEach(e=>{if(e===r)throw Error('You cannot have the same slug name "'+r+'" repeat within a single dynamic path');if(e.replace(/\W/g,"")===a.replace(/\W/g,""))throw Error('You cannot have the slug names "'+e+'" and "'+r+'" differ only by non-word symbols within a single dynamic path')}),t.push(r)}if(n){if(i){if(null!=this.restSlugName)throw Error('You cannot use both an required and optional catch-all route at the same level ("[...'+this.restSlugName+']" and "'+e[0]+'" ).');o(this.optionalRestSlugName,r),this.optionalRestSlugName=r,a="[[...]]"}else{if(null!=this.optionalRestSlugName)throw Error('You cannot use both an optional and required catch-all route at the same level ("[[...'+this.optionalRestSlugName+']]" and "'+e[0]+'").');o(this.restSlugName,r),this.restSlugName=r,a="[...]"}}else{if(i)throw Error('Optional route parameters are not yet supported ("'+e[0]+'").');o(this.slugName,r),this.slugName=r,a="[]"}}this.children.has(a)||this.children.set(a,new r),this.children.get(a)._insert(e.slice(1),t,n)}constructor(){this.placeholder=!0,this.children=new Map,this.slugName=null,this.restSlugName=null,this.optionalRestSlugName=null}}function n(e){let t=new r;return e.forEach(e=>t.insert(e)),t.smoosh()}},3009:function(e,t){"use strict";let r;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return n},setConfig:function(){return a}});let n=()=>r;function a(e){r=e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4831:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return l}});let n=r(1757),a=n._(r(7294)),o=a.useLayoutEffect,i=a.useEffect;function l(e){let{headManager:t,reduceComponentsToState:r}=e;function n(){if(t&&t.mountedInstances){let n=a.Children.toArray(Array.from(t.mountedInstances).filter(Boolean));t.updateHead(r(n,e))}}return o(()=>{var r;return null==t||null==(r=t.mountedInstances)||r.add(e.children),()=>{var r;null==t||null==(r=t.mountedInstances)||r.delete(e.children)}}),o(()=>(t&&(t._pendingUpdate=n),()=>{t&&(t._pendingUpdate=n)})),i(()=>(t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null),()=>{t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null)})),null}},6139:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{WEB_VITALS:function(){return r},execOnce:function(){return n},isAbsoluteUrl:function(){return o},getLocationOrigin:function(){return i},getURL:function(){return l},getDisplayName:function(){return u},isResSent:function(){return s},normalizeRepeatedSlashes:function(){return c},loadGetInitialProps:function(){return f},SP:function(){return d},ST:function(){return h},DecodeError:function(){return p},NormalizeError:function(){return m},PageNotFoundError:function(){return g},MissingStaticPage:function(){return y},MiddlewareNotFoundError:function(){return _}});let r=["CLS","FCP","FID","INP","LCP","TTFB"];function n(e){let t,r=!1;return function(){for(var n=arguments.length,a=Array(n),o=0;o<n;o++)a[o]=arguments[o];return r||(r=!0,t=e(...a)),t}}let a=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,o=e=>a.test(e);function i(){let{protocol:e,hostname:t,port:r}=window.location;return e+"//"+t+(r?":"+r:"")}function l(){let{href:e}=window.location,t=i();return e.substring(t.length)}function u(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function s(e){return e.finished||e.headersSent}function c(e){let t=e.split("?"),r=t[0];return r.replace(/\\/g,"/").replace(/\/\/+/g,"/")+(t[1]?"?"+t.slice(1).join("?"):"")}async function f(e,t){let r=t.res||t.ctx&&t.ctx.res;if(!e.getInitialProps)return t.ctx&&t.Component?{pageProps:await f(t.Component,t.ctx)}:{};let n=await e.getInitialProps(t);if(r&&s(r))return n;if(!n){let t='"'+u(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.';throw Error(t)}return n}let d="undefined"!=typeof performance,h=d&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);class p extends Error{}class m extends Error{}class g extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}}class y extends Error{constructor(e,t){super(),this.message="Failed to load static file for page: "+e+" "+t}}class _ extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}}},6308:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return r}});let r=e=>{}},8018:function(e){var t,r,n,a,o,i,l,u,s,c,f,d,h,p,m,g,y,_,b,v,P,w,S,j,O,E,x,R,C,M,A,L,T,I,N,k,D,B,H,U,F,q,W,z,G,V;(t={}).d=function(e,r){for(var n in r)t.o(r,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:r[n]})},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},void 0!==t&&(t.ab="//"),r={},t.r(r),t.d(r,{getCLS:function(){return S},getFCP:function(){return v},getFID:function(){return M},getINP:function(){return q},getLCP:function(){return z},getTTFB:function(){return V},onCLS:function(){return S},onFCP:function(){return v},onFID:function(){return M},onINP:function(){return q},onLCP:function(){return z},onTTFB:function(){return V}}),u=-1,s=function(e){addEventListener("pageshow",function(t){t.persisted&&(u=t.timeStamp,e(t))},!0)},c=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},f=function(){var e=c();return e&&e.activationStart||0},d=function(e,t){var r=c(),n="navigate";return u>=0?n="back-forward-cache":r&&(n=document.prerendering||f()>0?"prerender":r.type.replace(/_/g,"-")),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:n}},h=function(e,t,r){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var n=new PerformanceObserver(function(e){t(e.getEntries())});return n.observe(Object.assign({type:e,buffered:!0},r||{})),n}}catch(e){}},p=function(e,t){var r=function r(n){"pagehide"!==n.type&&"hidden"!==document.visibilityState||(e(n),t&&(removeEventListener("visibilitychange",r,!0),removeEventListener("pagehide",r,!0)))};addEventListener("visibilitychange",r,!0),addEventListener("pagehide",r,!0)},m=function(e,t,r,n){var a,o;return function(i){var l;t.value>=0&&(i||n)&&((o=t.value-(a||0))||void 0===a)&&(a=t.value,t.delta=o,t.rating=(l=t.value)>r[1]?"poor":l>r[0]?"needs-improvement":"good",e(t))}},g=-1,y=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},_=function(){p(function(e){g=e.timeStamp},!0)},b=function(){return g<0&&(g=y(),_(),s(function(){setTimeout(function(){g=y(),_()},0)})),{get firstHiddenTime(){return g}}},v=function(e,t){t=t||{};var r,n=[1800,3e3],a=b(),o=d("FCP"),i=function(e){e.forEach(function(e){"first-contentful-paint"===e.name&&(u&&u.disconnect(),e.startTime<a.firstHiddenTime&&(o.value=e.startTime-f(),o.entries.push(e),r(!0)))})},l=window.performance&&window.performance.getEntriesByName&&window.performance.getEntriesByName("first-contentful-paint")[0],u=l?null:h("paint",i);(l||u)&&(r=m(e,o,n,t.reportAllChanges),l&&i([l]),s(function(a){r=m(e,o=d("FCP"),n,t.reportAllChanges),requestAnimationFrame(function(){requestAnimationFrame(function(){o.value=performance.now()-a.timeStamp,r(!0)})})}))},P=!1,w=-1,S=function(e,t){t=t||{};var r=[.1,.25];P||(v(function(e){w=e.value}),P=!0);var n,a=function(t){w>-1&&e(t)},o=d("CLS",0),i=0,l=[],u=function(e){e.forEach(function(e){if(!e.hadRecentInput){var t=l[0],r=l[l.length-1];i&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(i+=e.value,l.push(e)):(i=e.value,l=[e]),i>o.value&&(o.value=i,o.entries=l,n())}})},c=h("layout-shift",u);c&&(n=m(a,o,r,t.reportAllChanges),p(function(){u(c.takeRecords()),n(!0)}),s(function(){i=0,w=-1,n=m(a,o=d("CLS",0),r,t.reportAllChanges)}))},j={passive:!0,capture:!0},O=new Date,E=function(e,t){n||(n=t,a=e,o=new Date,C(removeEventListener),x())},x=function(){if(a>=0&&a<o-O){var e={entryType:"first-input",name:n.type,target:n.target,cancelable:n.cancelable,startTime:n.timeStamp,processingStart:n.timeStamp+a};i.forEach(function(t){t(e)}),i=[]}},R=function(e){if(e.cancelable){var t,r,n,a=(e.timeStamp>1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?(t=function(){E(a,e),n()},r=function(){n()},n=function(){removeEventListener("pointerup",t,j),removeEventListener("pointercancel",r,j)},addEventListener("pointerup",t,j),addEventListener("pointercancel",r,j)):E(a,e)}},C=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach(function(t){return e(t,R,j)})},M=function(e,t){t=t||{};var r,o=[100,300],l=b(),u=d("FID"),c=function(e){e.startTime<l.firstHiddenTime&&(u.value=e.processingStart-e.startTime,u.entries.push(e),r(!0))},f=function(e){e.forEach(c)},g=h("first-input",f);r=m(e,u,o,t.reportAllChanges),g&&p(function(){f(g.takeRecords()),g.disconnect()},!0),g&&s(function(){r=m(e,u=d("FID"),o,t.reportAllChanges),i=[],a=-1,n=null,C(addEventListener),i.push(c),x()})},A=0,L=1/0,T=0,I=function(e){e.forEach(function(e){e.interactionId&&(L=Math.min(L,e.interactionId),A=(T=Math.max(T,e.interactionId))?(T-L)/7+1:0)})},N=function(){return l?A:performance.interactionCount||0},k=function(){"interactionCount"in performance||l||(l=h("event",I,{type:"event",buffered:!0,durationThreshold:0}))},D=0,B=function(){return N()-D},H=[],U={},F=function(e){var t=H[H.length-1],r=U[e.interactionId];if(r||H.length<10||e.duration>t.latency){if(r)r.entries.push(e),r.latency=Math.max(r.latency,e.duration);else{var n={id:e.interactionId,latency:e.duration,entries:[e]};U[n.id]=n,H.push(n)}H.sort(function(e,t){return t.latency-e.latency}),H.splice(10).forEach(function(e){delete U[e.id]})}},q=function(e,t){t=t||{};var r=[200,500];k();var n,a=d("INP"),o=function(e){e.forEach(function(e){e.interactionId&&F(e),"first-input"!==e.entryType||H.some(function(t){return t.entries.some(function(t){return e.duration===t.duration&&e.startTime===t.startTime})})||F(e)});var t,r=(t=Math.min(H.length-1,Math.floor(B()/50)),H[t]);r&&r.latency!==a.value&&(a.value=r.latency,a.entries=r.entries,n())},i=h("event",o,{durationThreshold:t.durationThreshold||40});n=m(e,a,r,t.reportAllChanges),i&&(i.observe({type:"first-input",buffered:!0}),p(function(){o(i.takeRecords()),a.value<0&&B()>0&&(a.value=0,a.entries=[]),n(!0)}),s(function(){H=[],D=N(),n=m(e,a=d("INP"),r,t.reportAllChanges)}))},W={},z=function(e,t){t=t||{};var r,n=[2500,4e3],a=b(),o=d("LCP"),i=function(e){var t=e[e.length-1];if(t){var n=t.startTime-f();n<a.firstHiddenTime&&(o.value=n,o.entries=[t],r())}},l=h("largest-contentful-paint",i);if(l){r=m(e,o,n,t.reportAllChanges);var u=function(){W[o.id]||(i(l.takeRecords()),l.disconnect(),W[o.id]=!0,r(!0))};["keydown","click"].forEach(function(e){addEventListener(e,u,{once:!0,capture:!0})}),p(u,!0),s(function(a){r=m(e,o=d("LCP"),n,t.reportAllChanges),requestAnimationFrame(function(){requestAnimationFrame(function(){o.value=performance.now()-a.timeStamp,W[o.id]=!0,r(!0)})})})}},G=function e(t){document.prerendering?addEventListener("prerenderingchange",function(){return e(t)},!0):"complete"!==document.readyState?addEventListener("load",function(){return e(t)},!0):setTimeout(t,0)},V=function(e,t){t=t||{};var r=[800,1800],n=d("TTFB"),a=m(e,n,r,t.reportAllChanges);G(function(){var o=c();if(o){if(n.value=Math.max(o.responseStart-f(),0),n.value<0||n.value>performance.now())return;n.entries=[o],a(!0),s(function(){(a=m(e,n=d("TTFB",0),r,t.reportAllChanges))(!0)})}})},e.exports=r},9423:function(e,t){"use strict";function r(e){return"/api"===e||!!(null==e?void 0:e.startsWith("/api/"))}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isAPIRoute",{enumerable:!0,get:function(){return r}})},676:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{default:function(){return a},getProperError:function(){return o}});let n=r(5410);function a(e){return"object"==typeof e&&null!==e&&"name"in e&&"message"in e}function o(e){return a(e)?e:Error((0,n.isPlainObject)(e)?JSON.stringify(e):e+"")}},2431:function(){},8754:function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:function(){return n},_interop_require_default:function(){return n}})},1757:function(e,t,r){"use strict";function n(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(n=function(e){return e?r:t})(e)}function a(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=n(t);if(r&&r.has(e))return r.get(e);var a={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if("default"!==i&&Object.prototype.hasOwnProperty.call(e,i)){var l=o?Object.getOwnPropertyDescriptor(e,i):null;l&&(l.get||l.set)?Object.defineProperty(a,i,l):a[i]=e[i]}return a.default=e,r&&r.set(e,a),a}r.r(t),r.d(t,{_:function(){return a},_interop_require_wildcard:function(){return a}})}},function(e){e.O(0,[774],function(){return e(e.s=155)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/pages/_app-1534f180665c857f.js b/.next/static/chunks/pages/_app-1534f180665c857f.js new file mode 100644 index 0000000..793ae70 --- /dev/null +++ b/.next/static/chunks/pages/_app-1534f180665c857f.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[888],{1597:function(_,n,e){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_app",function(){return e(8955)}])}},function(_){var __webpack_exec__=function(n){return _(_.s=n)};_.O(0,[774,179],function(){return __webpack_exec__(1597),__webpack_exec__(4751)}),_N_E=_.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/pages/_app-b555d5e1eab47959.js b/.next/static/chunks/pages/_app-b555d5e1eab47959.js deleted file mode 100644 index 9ef9b06..0000000 --- a/.next/static/chunks/pages/_app-b555d5e1eab47959.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[888],{1597:function(n,_,u){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_app",function(){return u(3739)}])}},function(n){var _=function(_){return n(n.s=_)};n.O(0,[774,179],function(){return _(1597),_(9843)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/pages/_error-d79168f986538ac0.js b/.next/static/chunks/pages/_error-b646007f40c4f0a8.js similarity index 74% rename from .next/static/chunks/pages/_error-d79168f986538ac0.js rename to .next/static/chunks/pages/_error-b646007f40c4f0a8.js index 9e654fc..38884fa 100644 --- a/.next/static/chunks/pages/_error-d79168f986538ac0.js +++ b/.next/static/chunks/pages/_error-b646007f40c4f0a8.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[820],{1981:function(n,_,u){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_error",function(){return u(8495)}])}},function(n){n.O(0,[888,774,179],function(){return n(n.s=1981)}),_N_E=n.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[820],{1981:function(n,_,u){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_error",function(){return u(4570)}])}},function(n){n.O(0,[888,774,179],function(){return n(n.s=1981)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/webpack-54b114c68857d808.js b/.next/static/chunks/webpack-54b114c68857d808.js deleted file mode 100644 index aeb2a85..0000000 --- a/.next/static/chunks/webpack-54b114c68857d808.js +++ /dev/null @@ -1 +0,0 @@ -!function(){"use strict";var e,t,r,n,o,u,i,c,f,a={},l={};function s(e){var t=l[e];if(void 0!==t)return t.exports;var r=l[e]={exports:{}},n=!0;try{a[e].call(r.exports,r,r.exports,s),n=!1}finally{n&&delete l[e]}return r.exports}s.m=a,e=[],s.O=function(t,r,n,o){if(r){o=o||0;for(var u=e.length;u>0&&e[u-1][2]>o;u--)e[u]=e[u-1];e[u]=[r,n,o];return}for(var i=1/0,u=0;u<e.length;u++){for(var r=e[u][0],n=e[u][1],o=e[u][2],c=!0,f=0;f<r.length;f++)i>=o&&Object.keys(s.O).every(function(e){return s.O[e](r[f])})?r.splice(f--,1):(c=!1,o<i&&(i=o));if(c){e.splice(u--,1);var a=n();void 0!==a&&(t=a)}}return t},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,{a:t}),t},r=Object.getPrototypeOf?function(e){return Object.getPrototypeOf(e)}:function(e){return e.__proto__},s.t=function(e,n){if(1&n&&(e=this(e)),8&n||"object"==typeof e&&e&&(4&n&&e.__esModule||16&n&&"function"==typeof e.then))return e;var o=Object.create(null);s.r(o);var u={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;"object"==typeof i&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(function(t){u[t]=function(){return e[t]}});return u.default=function(){return e},s.d(o,u),o},s.d=function(e,t){for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.f={},s.e=function(e){return Promise.all(Object.keys(s.f).reduce(function(t,r){return s.f[r](e,t),t},[]))},s.u=function(e){return"static/chunks/"+e+".9317a587abbcf60a.js"},s.miniCssF=function(e){return"static/css/"+({185:"3930d1a0ca01c66f",931:"60c69e914bf8dd4b"})[e]+".css"},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n={},o="_N_E:",s.l=function(e,t,r,u){if(n[e]){n[e].push(t);return}if(void 0!==r)for(var i,c,f=document.getElementsByTagName("script"),a=0;a<f.length;a++){var l=f[a];if(l.getAttribute("src")==e||l.getAttribute("data-webpack")==o+r){i=l;break}}i||(c=!0,(i=document.createElement("script")).charset="utf-8",i.timeout=120,s.nc&&i.setAttribute("nonce",s.nc),i.setAttribute("data-webpack",o+r),i.src=s.tu(e)),n[e]=[t];var d=function(t,r){i.onerror=i.onload=null,clearTimeout(p);var o=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),o&&o.forEach(function(e){return e(r)}),t)return t(r)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=d.bind(null,i.onerror),i.onload=d.bind(null,i.onload),c&&document.head.appendChild(i)},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.tt=function(){return void 0===u&&(u={createScriptURL:function(e){return e}},"undefined"!=typeof trustedTypes&&trustedTypes.createPolicy&&(u=trustedTypes.createPolicy("nextjs#bundler",u))),u},s.tu=function(e){return s.tt().createScriptURL(e)},s.p="/_next/",i={272:0},s.f.j=function(e,t){var r=s.o(i,e)?i[e]:void 0;if(0!==r){if(r)t.push(r[2]);else if(272!=e){var n=new Promise(function(t,n){r=i[e]=[t,n]});t.push(r[2]=n);var o=s.p+s.u(e),u=Error();s.l(o,function(t){if(s.o(i,e)&&(0!==(r=i[e])&&(i[e]=void 0),r)){var n=t&&("load"===t.type?"missing":t.type),o=t&&t.target&&t.target.src;u.message="Loading chunk "+e+" failed.\n("+n+": "+o+")",u.name="ChunkLoadError",u.type=n,u.request=o,r[1](u)}},"chunk-"+e,e)}else i[e]=0}},s.O.j=function(e){return 0===i[e]},c=function(e,t){var r,n,o=t[0],u=t[1],c=t[2],f=0;if(o.some(function(e){return 0!==i[e]})){for(r in u)s.o(u,r)&&(s.m[r]=u[r]);if(c)var a=c(s)}for(e&&e(t);f<o.length;f++)n=o[f],s.o(i,n)&&i[n]&&i[n][0](),i[n]=0;return s.O(a)},(f=self.webpackChunk_N_E=self.webpackChunk_N_E||[]).forEach(c.bind(null,0)),f.push=c.bind(null,f.push.bind(f))}(); \ No newline at end of file diff --git a/.next/static/chunks/webpack-c42a79c5d8b7c910.js b/.next/static/chunks/webpack-c42a79c5d8b7c910.js new file mode 100644 index 0000000..9a871e4 --- /dev/null +++ b/.next/static/chunks/webpack-c42a79c5d8b7c910.js @@ -0,0 +1 @@ +!function(){"use strict";var e,r,_,t,n,u,i,c,o,a={},p={};function __webpack_require__(e){var r=p[e];if(void 0!==r)return r.exports;var _=p[e]={exports:{}},t=!0;try{a[e].call(_.exports,_,_.exports,__webpack_require__),t=!1}finally{t&&delete p[e]}return _.exports}__webpack_require__.m=a,e=[],__webpack_require__.O=function(r,_,t,n){if(_){n=n||0;for(var u=e.length;u>0&&e[u-1][2]>n;u--)e[u]=e[u-1];e[u]=[_,t,n];return}for(var i=1/0,u=0;u<e.length;u++){for(var _=e[u][0],t=e[u][1],n=e[u][2],c=!0,o=0;o<_.length;o++)i>=n&&Object.keys(__webpack_require__.O).every(function(e){return __webpack_require__.O[e](_[o])})?_.splice(o--,1):(c=!1,n<i&&(i=n));if(c){e.splice(u--,1);var a=t()}}return a},__webpack_require__.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return __webpack_require__.d(r,{a:r}),r},_=Object.getPrototypeOf?function(e){return Object.getPrototypeOf(e)}:function(e){return e.__proto__},__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t||"object"==typeof e&&e&&(4&t&&e.__esModule||16&t&&"function"==typeof e.then))return e;var n=Object.create(null);__webpack_require__.r(n);var u={};r=r||[null,_({}),_([]),_(_)];for(var i=2&t&&e;"object"==typeof i&&!~r.indexOf(i);i=_(i))Object.getOwnPropertyNames(i).forEach(function(r){u[r]=function(){return e[r]}});return u.default=function(){return e},__webpack_require__.d(n,u),n},__webpack_require__.d=function(e,r){for(var _ in r)__webpack_require__.o(r,_)&&!__webpack_require__.o(e,_)&&Object.defineProperty(e,_,{enumerable:!0,get:r[_]})},__webpack_require__.f={},__webpack_require__.e=function(e){return Promise.all(Object.keys(__webpack_require__.f).reduce(function(r,_){return __webpack_require__.f[_](e,r),r},[]))},__webpack_require__.u=function(e){return"static/chunks/"+e+".591370f90aaa22a6.js"},__webpack_require__.miniCssF=function(e){return"static/css/"+({185:"1d2d59615145af7d",931:"60c69e914bf8dd4b"})[e]+".css"},__webpack_require__.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t={},n="_N_E:",__webpack_require__.l=function(e,r,_,u){if(t[e]){t[e].push(r);return}if(void 0!==_)for(var i,c,o=document.getElementsByTagName("script"),a=0;a<o.length;a++){var p=o[a];if(p.getAttribute("src")==e||p.getAttribute("data-webpack")==n+_){i=p;break}}i||(c=!0,(i=document.createElement("script")).charset="utf-8",i.timeout=120,__webpack_require__.nc&&i.setAttribute("nonce",__webpack_require__.nc),i.setAttribute("data-webpack",n+_),i.src=__webpack_require__.tu(e)),t[e]=[r];var onScriptComplete=function(r,_){i.onerror=i.onload=null,clearTimeout(f);var n=t[e];if(delete t[e],i.parentNode&&i.parentNode.removeChild(i),n&&n.forEach(function(e){return e(_)}),r)return r(_)},f=setTimeout(onScriptComplete.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=onScriptComplete.bind(null,i.onerror),i.onload=onScriptComplete.bind(null,i.onload),c&&document.head.appendChild(i)},__webpack_require__.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.tt=function(){return void 0===u&&(u={createScriptURL:function(e){return e}},"undefined"!=typeof trustedTypes&&trustedTypes.createPolicy&&(u=trustedTypes.createPolicy("nextjs#bundler",u))),u},__webpack_require__.tu=function(e){return __webpack_require__.tt().createScriptURL(e)},__webpack_require__.p="/_next/",i={272:0},__webpack_require__.f.j=function(e,r){var _=__webpack_require__.o(i,e)?i[e]:void 0;if(0!==_){if(_)r.push(_[2]);else if(272!=e){var t=new Promise(function(r,t){_=i[e]=[r,t]});r.push(_[2]=t);var n=__webpack_require__.p+__webpack_require__.u(e),u=Error();__webpack_require__.l(n,function(r){if(__webpack_require__.o(i,e)&&(0!==(_=i[e])&&(i[e]=void 0),_)){var t=r&&("load"===r.type?"missing":r.type),n=r&&r.target&&r.target.src;u.message="Loading chunk "+e+" failed.\n("+t+": "+n+")",u.name="ChunkLoadError",u.type=t,u.request=n,_[1](u)}},"chunk-"+e,e)}else i[e]=0}},__webpack_require__.O.j=function(e){return 0===i[e]},c=function(e,r){var _,t,n=r[0],u=r[1],c=r[2],o=0;if(n.some(function(e){return 0!==i[e]})){for(_ in u)__webpack_require__.o(u,_)&&(__webpack_require__.m[_]=u[_]);if(c)var a=c(__webpack_require__)}for(e&&e(r);o<n.length;o++)t=n[o],__webpack_require__.o(i,t)&&i[t]&&i[t][0](),i[t]=0;return __webpack_require__.O(a)},(o=self.webpackChunk_N_E=self.webpackChunk_N_E||[]).forEach(c.bind(null,0)),o.push=c.bind(null,o.push.bind(o))}(); \ No newline at end of file diff --git a/.next/static/css/3930d1a0ca01c66f.css b/.next/static/css/1d2d59615145af7d.css similarity index 90% rename from .next/static/css/3930d1a0ca01c66f.css rename to .next/static/css/1d2d59615145af7d.css index 4226b24..4876b14 100644 --- a/.next/static/css/3930d1a0ca01c66f.css +++ b/.next/static/css/1d2d59615145af7d.css @@ -1,4 +1,4 @@ -@font-face{font-family:__Inter_0ec1f4;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/d1d9458b69004127-s.woff2) format("woff2");unicode-range:U+0460-052f,U+1c80-1c88,U+20b4,U+2de0-2dff,U+a640-a69f,U+fe2e-fe2f}@font-face{font-family:__Inter_0ec1f4;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/b967158bc7d7a9fb-s.woff2) format("woff2");unicode-range:U+0301,U+0400-045f,U+0490-0491,U+04b0-04b1,U+2116}@font-face{font-family:__Inter_0ec1f4;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/ae9ae6716d4f8bf8-s.woff2) format("woff2");unicode-range:U+1f??}@font-face{font-family:__Inter_0ec1f4;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/c0f5ec5bbf5913b7-s.woff2) format("woff2");unicode-range:U+0370-03ff}@font-face{font-family:__Inter_0ec1f4;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/b1db3e28af9ef94a-s.woff2) format("woff2");unicode-range:U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01a0-01a1,U+01af-01b0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1ea0-1ef9,U+20ab}@font-face{font-family:__Inter_0ec1f4;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/9c4f34569c9b36ca-s.woff2) format("woff2");unicode-range:U+0100-02af,U+0304,U+0308,U+0329,U+1e00-1e9f,U+1ef2-1eff,U+2020,U+20a0-20ab,U+20ad-20cf,U+2113,U+2c60-2c7f,U+a720-a7ff}@font-face{font-family:__Inter_0ec1f4;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/2aaf0723e720e8b9-s.p.woff2) format("woff2");unicode-range:U+00??,U+0131,U+0152-0153,U+02bb-02bc,U+02c6,U+02da,U+02dc,U+0304,U+0308,U+0329,U+2000-206f,U+2074,U+20ac,U+2122,U+2191,U+2193,U+2212,U+2215,U+feff,U+fffd}@font-face{font-family:__Inter_Fallback_0ec1f4;src:local("Arial");ascent-override:90.20%;descent-override:22.48%;line-gap-override:0.00%;size-adjust:107.40%}.__className_0ec1f4{font-family:__Inter_0ec1f4,__Inter_Fallback_0ec1f4;font-style:normal} +@font-face{font-family:__Inter_e66fe9;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/ec159349637c90ad-s.woff2) format("woff2");unicode-range:U+0460-052f,U+1c80-1c88,U+20b4,U+2de0-2dff,U+a640-a69f,U+fe2e-fe2f}@font-face{font-family:__Inter_e66fe9;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/513657b02c5c193f-s.woff2) format("woff2");unicode-range:U+0301,U+0400-045f,U+0490-0491,U+04b0-04b1,U+2116}@font-face{font-family:__Inter_e66fe9;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/fd4db3eb5472fc27-s.woff2) format("woff2");unicode-range:U+1f??}@font-face{font-family:__Inter_e66fe9;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/51ed15f9841b9f9d-s.woff2) format("woff2");unicode-range:U+0370-03ff}@font-face{font-family:__Inter_e66fe9;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/05a31a2ca4975f99-s.woff2) format("woff2");unicode-range:U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01a0-01a1,U+01af-01b0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1ea0-1ef9,U+20ab}@font-face{font-family:__Inter_e66fe9;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/d6b16ce4a6175f26-s.woff2) format("woff2");unicode-range:U+0100-02af,U+0304,U+0308,U+0329,U+1e00-1e9f,U+1ef2-1eff,U+2020,U+20a0-20ab,U+20ad-20cf,U+2113,U+2c60-2c7f,U+a720-a7ff}@font-face{font-family:__Inter_e66fe9;font-style:normal;font-weight:100 900;font-display:swap;src:url(/_next/static/media/c9a5bc6a7c948fb0-s.p.woff2) format("woff2");unicode-range:U+00??,U+0131,U+0152-0153,U+02bb-02bc,U+02c6,U+02da,U+02dc,U+0304,U+0308,U+0329,U+2000-206f,U+2074,U+20ac,U+2122,U+2191,U+2193,U+2212,U+2215,U+feff,U+fffd}@font-face{font-family:__Inter_Fallback_e66fe9;src:local("Arial");ascent-override:90.20%;descent-override:22.48%;line-gap-override:0.00%;size-adjust:107.40%}.__className_e66fe9{font-family:__Inter_e66fe9,__Inter_Fallback_e66fe9;font-style:normal} /* ! tailwindcss v3.3.2 | MIT License | https://tailwindcss.com diff --git a/.next/static/media/05a31a2ca4975f99-s.woff2 b/.next/static/media/05a31a2ca4975f99-s.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..cbcdad70bc33360913ebad795dacd68cbe2ebead GIT binary patch literal 10496 zcmV+bDgV}YPew8T0RR9104V?f5&!@I09#N104S9J0RR9100000000000000000000 z0000Qf)X2&XdHtgKS)+VQi5y-U_Vn-K~#Y_0D^cgY!L_wuNbI)3xYNPFv(~EHUcCA zglGgH1%+G(j2j!uRTb=3Y_|i@_VvA|jzkC>2Qrwn%l`kAAms?t*k1~)U=S|dT~U~7 zrP0!knOcg1*eEPau#Igjq9724CN7ENbh~|bxrHIb&>Q17t3FyM{!kGvA!dq^hu`Lo z?Db5K#PPxZ*G5P(3;$33_5RxDRMowW=YEVj$p^$hoPBsGa4?KqKk&@$|J=(3E^xP9 z6&+4g+)#0%GKY$~+=Zc{k)t(ruBkZZ#<ppwQ>QM4LCP~Mo{{d^GPJ!O75VmzXJll& zq{T~AO1|-xl9Xp;v{2DdX&kO;?!S1K6j-QM%}vPyfennlb>wFR8jT8x2)x~|8gLjv zVu?=RK|R>T+<qmI64z(yn1zyn=zqUHtNXrz<uKR?Ni%=hMrhD`eBk!HkZ@~*D#D<R zi;9jgB!Rmgx_JSw*>hIT=(A&>bo2ZU1l-t;c}NKz8>UirI7LKPM@tx#CVkgduAef1 zAR(vje{`Db|1v!JFmMD;Ull0P9LFU-;Hkrig6J$+cEZna<Z}wLONN4@L)!%(5p`>y zjsqpY9f(Jqfreq^VcrYR*WAB0H)nSy54eO1jrz|PP*tf%nY`_03!DO=0@@<lvQorC z{i&++C{=|lK{%$i@K<76VLT?q?=Zs5=&4CgBmsu)obPLPnx^TP{x@va2OfJl8+x&A zN+U(YUnB&P#?(oVa|b{;ouK-&`~Z}8DBTeHOoT98354yHLD<(q2#2E}9AgE9vpf&s zT=ftxr-g8hEfDU~1>q4dLl}nz8k2by8dEt8f`E1?&;;B7!QRIQ07s#~P=En?sp04Q zH9<Vo9-?BN|CfX)p-GC8lB71}Un9UmhzK!~q#zA=xExd^fotmVMoff34Z{HCH<8<h zCA)BD57rzYki)og78{UjLDquY0r(#TXg2{HV;9BH<4zC^n7Pu^1T&$xUcXHs>|mzj z#{iiNDYd!1wBZ9l^Q=Oyb#LFzVF1WEOjjI4ZoT@BMv-k*P-yUB*PExu?S5tFwgz53 zXtbaNX}1`LL{Qa_=g=@aD9n-o%1!$<Plcz<!Q0MFtjPiWlpJwMQ=^a1;^AUJMs*Iv zZmM>ewGQfgqC;s#O%4@jfnKUho!b@Hp>~!eXrNPB7R4sJ9<tb$jw6t5qr?XkHhwZw zQGVm6E5HBvF4e5M%c?jkmH(E{yQWybEyM&6@JB$nYukpPQ)yg5Ydx(nSbbytOthjG zz1Dl?^(d`_AOIIW6A?3q`7A+&hFUh*wt?@&E!gzY8cS0YGEVq1UM9#yDVCBSgV1M& znP!nFQ*Iua`4(76<yji5thFxGPjAv`hn;pQppV{INRf;azKoX%GEs`9#4LZ$jaJ9I z{-v=(tXp78d8v@bew`(#b=b~kCo+Q_lCiToXx=tAI_*rIh3q;OEN(+VCg(&SRf5JC z7c^64r7o2$T3_Slfii1${m$%(>^1K#*(rCa)+on!77&$M+8WShyLD1DL`l1JG@wVS zPs*s5MW-NG!U}3wzeHDJph9nz<JpW*f=*^J1``^HAT3%>?ktNE1cu<(wv&+uF%e~7 z<!{>0Tx<@s5R)FfM+}2};p}Zxz_ow|_A(Z}<+TDd4mel6x5g-m@I>UP@JOVssRx2e zcw5!<weY5@IxFFI)u5?ym5^K}5_M5f;S3`Mr<gSC2~FXq$Dl2HkU=bVKW3av_d*+X z2Sn0>5s|D^L)%CP5EQmOG_huNgoj8|R7)g(nd?N=h(HpRvK<Am0g1s#YqkWn1^zc& zxxa0O1HXsg<}AgRhNS%zLh`oJNM2tLy+vum1rl2i{WaJs2n<l8g&{JiA)<H#M4}af ziphD0#a8rDia9w@P`42>`0o=ifK4al+H1!JCZI9Y6f;L#>j694n*i-WHa1`?>_vMZ z%DJwcZBp2|PVM1AsT4X_k*J_j3qf271;j=5mk@*@#_=i$aZugcppg!pi)pv$v<H1! z0|&4|KlKQ`oB-!T`R;x`V1ToD0VE6<?Cwy;Q3hoSGog%U7L-XypiE|-frZGJ&jQ-m zLOUI7rjssqu#;UdgtmSnY%_E?!dyQA%qnByu$H)KrWxBS_ilwy?Wh6xmRO_qoKMoX zJ;-m~=TrLBAx%UXQAe~X)f&+T0QOTseFvZjiUBfwScM9P+n}!x5NbQUJwSgavwQ}G zIZpKEi1-mj;&KWO>q3*$BFSm#vMI3KUBSzB!pj}OqXUZ$`gGvXLB9^Aa{crfre78_ ziVuuMd$6bTIykmN`jkj#lqI4pDPPh`NQhacC?I-fBiTV>Sv{K638{1b{HbOYftbBZ zU{~i><~7UN1sp=R6c=tcxwK@`wBkAJ87&ZsnX*BLVuy4b;3t{pf8uk$5gjIEXi8`P z<f{tL`9vLj$e$0-JGT~r=~-(|K+6G0lmJZxLX;TLzy`L1K6qnuLJEL;*K|Ti5E=x; zWK?Qtb?9OS0Z<1`pl;YjAh}y&^Z`wUvH|wCzE{7}XgJ8~5{H-@4s$`b;cliO#EpeD zkI>MihMtwln3~d>1h89sG{0!b2u)L~PHMmr8b)K$N_^VT$ITbb87n{$QX=W(&_5mA zB^>CW(XkJ5CI9)h8n=$N>Vf~B0RdpJ2?UA>O(9YW0N4QlCC507#w2S==}p$C+*SuU zz^hnbb2<)ZAUH`Lr^x421)PSo%m`IRT5OahxRx4CiRT4l)he>mIIHljHeQ_x)|jYX zv2{wUH^oL%H4)ilnr5Y1Os6B(YKAs5wVS1b#Aao-m}8r{wwtGu%ntMIw7@P4b$P}f zi|kdY8|CFb9x57Glx0FfQ<-J}ISNN@$Oxe6?*jO|5Q>0#iF$1c)h}EFgA8_&I3)3H z7-sOMeK?ImC`%iaVG-X%wI9Igz-IyRCm;cS9{@za2>E38IO2BksWaTA)x!9BJVfi` zd9>U7yv;4taWNPPz5&+NDHgMxG|^jKmFS~~^Mq^dafL#@WkCXYN;;ejWp07LcM_Aa z5uZPmas`$?9^wI)(n5ix*X0U%Q_q~$<*K=jOP|@Ld|rYZp}0mF6{(-QSqmJ~hO7`L zcTbpu*z7wv^@jln?&j56#*bELB!n56sE{knL{p2VU7m06o4x9PF;-Yyy~VjcFRQm( z{?caO4J{vsjg?J-I_Z+Qw!*cOk0kLK>=F?$6m64JD2h<&LGNs>?WbKVFcQEKu93}O z*cQ=JvWb9Kc*w8egi}D=4=*d##@tT-Tln_KP0BQ9Z0p$#2rn8mr;1lbfv}@HdOR@O z;Vk4HoZe1MN_Qix4z!*y^T{@THp{k;n+%g&DZ)z%ZG6CkAe4E@b8@dqhE8(VJ{NZi zqdRB1@R;2T1)V5b*Zd*MG?<F$n!YHRauH!bJ!bL_n0L4#cd`kth38J^Vj=iuRxJkd z<I_Ft>&DRN{mQQqo}Cw|aC79W)W;y1O}j$HM#u7HDvgSHq8J8yB}itT$hKZ#2GryE z?4srDzW_dHm#}ZEh3zH|W})%RY=g~=bbme7+)WjP+XLEZUEeXA#@O^f_Ja)o+n$nR zPM>N7^)d@*;>E_MEb)?psy<$nw?rj>&|9h1RxZ}oWA*Cm7gyG6pYppK^uI=<!_QrK zxAmXQ$v2L^6c*){{v-WUU=ejY`0=CZ762SF;4sQx;n9D2Erf?<cVD#6^RAvS5jUyB z-giOy)Az@6jP0>pCMxU5->c3KY<}UhbLWC);(7Lt%dWjWnNLjS`1@Y}4`#aKTEWH- zAp>3gonQ63_uf6x5`Va59>2C_M@@;e`HK%9noo(NV7&Ea!ryrwwS@iF<1fDW@eQU! zIm`n55|ft~|FHNom2UN4YIy7UBXf!0w!He?QFBZGM{B>E*_QX}h|?oAGv?!V$Gh*o z|HT_qUbtDk@YO)y(4x-ezG8R#uK)ieoeU9MU)uU<^@gif-{!`Tw2_~h_&wY``L!={ zPDr)7`n_knq0A@nP5$!lP3il8&!_(9%cG|o8@i8i)4u{vJjwst`hEXu+<x`73-(R; zY1c;dg3Wexu(uIA)!)P(?1Q6E@FV4SH71iT-P~_NUB6U+ac1k}@0%RKfu81z-W`U+ z!9$yW*l#)AmHNK>^|eQ(o7=`$->xj#{{HF5S|Y$82@IGg!s5oY3Pt1E#nQ4|9i#?9 zNcPp~jYFx^C9I*^xhXYtPosh>S5I6#xq*57_y*R+cTdcOcf~+p)}LU(KhPPC4{{zm z3+?k0-k8dm?d;{yPV0St!%AYL=)8UEwC(1;{ooHJeNOM!Z`7S#)BPzF3}vXdI{0<7 zyT4mkF{Y=8rd$0+%#{^uNAeb4SvlIoY1Wl?PTy5>0EZ%TfQ%aiqQThooyNWoo`q~w z0}zE0M(Dv6?z}57>jd-Qfjo!dxl&l<7+LjBWbuuf1m2+M6XxGee`%b*dP;R!?UcFm zSJYL0T+ny=6XW7FQx=y!H)a0(<#oVS1y{L;lmQ4h15h4-=&75Re4qb#=~Q&ZsvWJZ z^*dlLPBD)q+K<6uHcg9{LeKtUiVwK_5gmQi49VP=%j%iOu7qFjYBsKYjssF8o9oE( zufwr@v6B}r1igNfD_1vkwAMF_TK7gl>}G*J>A|}H@QqzA4M+A}JNfy!{||^%u54&- z<`cHM-b?#uBU(3pYU%Dt^_=bh{ib8}if-j{9Lf)dqsANW`9A;gJ!7<TmA18Ym3H-a zyGojke{EjArmVWGV#Xq6`QC9GjeX5CmW@|VRgIrML!kuP3EpGv(YaG_`|5midmmhA z5f-+9LPa#Lpx}-6UmtwY2gkKTnM$;`JyY<M^E8t;{F4uzo)_rVf*F#wsn0V_?oW0% z*Kg4%ahPKv-mT7Xu2RV0hOS=!(!}RY2ejpj`I}tRN|#j%+s8e>|B$w{YTQ+7+|&pE zLLl6H@Ea$B)!{{3ay#Zd8G~yjAqk*6NGJeIOrk)^Fi@ay`27g~@Mck_uVfrc5rD&6 zQzqk33YmlnGiJ$PSjKF?24~EXSP5z_UIo`+M@GqvR-D$bumduE;u(@KYNn(n%E9g! zxJR_I5X0&UL&iqo`cXLG3L`+I3Jck(3JZjFAx)~VM9f;%4FXx>LLNv3UJIcg!Kf+0 zO)6B1g}!H1D6~!(5E&&b(4~Y0^($dPQY9>EAf|PbGcWd78Ou{d6Q2n-j*?#Q5xCi) zR?n{2=6DR0uG|-0y4?8`-^!;OSWd;tr{Jz4n<R7v5nVw7`7>kjq70vg+wQ3E5nZD* zmzmxxv^p-7yv6`An>33oVDm8Ij>{+CP0J%^?xCNs@}OYtImFTAo1psOJhM0`?AXyv ze8ROXay71W=^At$_Do{bL)uBR1cdtRr@S~UT&gBK%+*AtJwaDMzTurXYTGT~8p=9v zK)>j0dQVXsipdfONtfFY7^K<|&d?k1stw_3dc*YrN*Xsm$;Edho?0_Yyd`YaC>(tE z^re*9`|4P$JH6bvt$yfLTNnS&eVc@8;MR1vy?dK?w4;k)_V%2i)NXs0ua$o+?3}Fs zF*g`6=KFj96aOJ8$Zc`ESJr>gH-CO-_=|5*E>NfdriiVQ%^XcYh^R4#t1CDJCRT9x zAQcfRtxjdOCARKH7_{HnY}Nu~P@_lj2q<!hJX?AkBhKOHqPmd3lR<IRES0&O#@2xu zz#43iKwTUHf;s}_;{eVa!Svw#$ao7en(?(dmD%Rmx)+oUYzJ0x2p&kI#!kZRkTF_F zd@lVz!Ie0u%Q*xVQfAqXMAx-#VFliuf(FiZI6SrB9X6#DY(`^4S4J%CzQ)uT+8^3> zCJ&2m)6nGxLjKsqWvNq{sa3@@L$DuvPYwsCmMs$L$53Pud0cv2^0N3jx6bla%cB&Z z0gtN^!F4$YK<mP#5CKpNi%8W8NCu~*#GtOlfLaL(Q&8Zqoj@z9m4IXbr%uL>J2)+# zfs|})SBy@Gn2c74&@5p9m=T5@DM;L5(Q&pkA{a{0{_msvdbzR|14>y0E07NNogv`q ze;c3HF+4fRUYhd)ObUnWxBqMZv}z+42p|k}3daG^82~$)s?HT|@;f;sh)mQBJ)`He zR-5&*4(lELQ(x$cZt9*bwHDi9W;<dh?O*1zD|XXTmK#CZc;D~Yz{ZNgv>*%1LS4{> zUE!7RX6O$ehsVRv*V5bRyXhACG5UM-v-Gd%VFobTK>!k<7&jQdF#cdNm|QGI2`<7F z%(cvR=5FRe<}sY4iBv{^$3Mm|^y`Cvi^uTa@nKdTYdou(wSlE)8Cb8gPOxcgBl~ss zJM53xUiL-yb@pBMV-C*Yai((Sa`tfk!ugf+gkTdzL@BX=SWeUvZxb%UO9Y7<L^2QZ zxOofncIADNcQJ1`pPfH3e^&nf{ImIA<|p$r1#=5_6kH-_lWWPtWMo9;h?)_u5$8u- zqVQozAYdFIFj)Y=4To*Ev#kJSQyt^55wuzzP~8SEDs&I*5D|)=zB2%TvNpINw@&52 zoC8t0-F8P5DC_DKIcd@(9M<14QK3dMuA9-1)By%goOBZ;7~MdH#`ua{QZjH{o>Qt^ z$#Kix+9qF&5@j7~R7U*d3jRs1+O2sOmaLeqdr~I_oe47lVz1!we()StSjQIGANKsf zyG0B>#2jw}9_zA6=88>A!O90jIg@gLli5k-5;#eKJHcZ#hcM%bc-ZZ}ku6jzx07UV zxPRJAsYDjC@(gLCWvlO&flM{n0<A9?MG#aDE{g>do8F>j@ET^z4B2`&e%^f}ql5vj zhTOU-%0on3E7y@-g?JwB1|nzhz(7A)Bn+lxP#i#Dpf~40vK-uL6#zVH2z?8pRv<xi znTZp1kRg;>0tsMyz(7<|#~yRS0RuX){X;n5PG}%WGz@2fiI@pIqRC8z7-<){4s|d* z(|TM6EAL96C!*2Jm{oExVt9CeLn)a^z`Y;84PE)}2b)cGOC%Z?fOM6@Cb8S);1z7% z9tHGW{S$`Lu|NMb53$=VHesT8TzFpTQn^B<>Vh+qNMK_Y*1Eh%BnKaMF|1afPmXza z6GTR171<3OPeJy2l^eyxW>?y9Halz{DXlhD>NpB`rA)?PQx!wyv3YI&h=HOn2Gob5 zYl>LA&%lQsU+9zuN`C0A6mf=30~5UIf=G!?;sa%wYH>GWjucu`!YHGiv_v){5ijr; z5l$G90FbP*1REn{E|MX)8)cLu4gd+!A;k^oh734$MAzIF4Owf%1AB@4S9<_ienJ31 z&mQyQ)(_H91Vt(Eg;jl;l1z9VsLcRWXN>RB5+n$t(&1!I$0ei{Db!k513#$o1!z)% zF>ZI@R`Owi(5oaLC2s}XO|MmtOP)WZuu}x@4t|y#r`hyYH3Pz7^<ZoQ9{%y9_~Rk) z+ZEtsXIVB+fID{&ws%>)88^wXV!hZwNhUl9hr<shNT?14Sf!+f4J2A6ghGH|2o0?S zY^|FyL0bl7=w8qAAO#}}dT0eB;q*115ko(R=V_?91{X?@PFu~91l!RlL*i(~z=Z%; z@sOWmc}F=?D2}g@!)Mqxq--R_<y(dUUrCM-oX+Pk#HmK%DRf}KDz^d4ZDTgS1+6|e zS)KY2XbYl225oe?Vh;!eLC0JG(@+79Y<;y^0<?QcfSw&UC5W%CQg3f)1rpTi`I0Pb z9(l~8l{Z6hWCmm%Ja)Rl)-%&d<3_AIqVYtNYEwE%EUtB#gm3{amMJXvg?yLcAwsNN zs#4h^K6^wIH^{+K%1z)Idl)E&4bW*lXwq*|*Z`F@`I9C}{Cov66+ejw`>oxo@Ikhv zB>uM%=R9$!ObC<_7jtn!8^pO{Bcj@`gsXvp$&&r5a>sf?3z?U?#^<-jA=RzPXlA=U z5-B?i6$qLY5a2GMp>A0}FU*%ai>R&Luu39XA|bX}$upuZ*9nDP&cYZN`#x72Vi#`; z3A`!AAuuM1M1njd3y3*jagG5sExZOU1A3M#Qt*#+hdT`~+MpL`60wieV6k=59t1o+ zIheSkj)6fgU_B2f!<3B!@Ti<ReFH*8uCBAI;&OpfUq&PpGEx}MDqJCPBV=I1VoVZ5 zSc1`X8mQn6klo!y%Glu6(IE!)`c~M2*Cf}e9>qiCjo?zH>QieGUNp6dS8qi_q!R#H z8lNQgtd9n-@t-io72Nb*_^U<C{mJM5{b#pfMpwZS-tV_U*J$nFiE~yqP?wF3t9=H1 zRe)iC-cO!A?z$AdeB-y2azho^#U1~*^Bq$B4-CU@U1c^HF`aHU3zO&c>My;+ZtC2+ zrLCo@ZaQSXqtvhLzPFri-^8icEcU-B-DL-^asG>Fmcs>N;XgvD%Mbaxl;Guy1A9T* zC@b7!ON6KR=HV*!e1oma+rLZ|tE%8AA#v4nJE*IGAcpUyhqB~&9$7SrOL`R6icInD zfLv{r44i1!K8=cu7>>u2ggp2U@TL0vbl>M^KJ|Lf4-N@lq`+SGDQWPv@-nC!>3m3X z)R20t$qk&1({_9=+GY2<_Su1GJuCqpM9f5>R1*9#6O`%!L}FkVw*<nWM3{>>M}dN% zd#C`bnLg+M5|U=(poa{221}$(YuC8r6mklsuLW_`*iP=oo1eI!KQ;)s9}oOoEIB#l zxvrvi51%g)+`SU`fgx}O?Rvm_RACn?7;k(EzB01%M?mT~3~tmfFDq%yZ&_B-;HGlv zy`B~56woVz7kz0qWTRdo<9(isL3dw0Z{KhIo5O5b{502#2M?`!SbF5P+qqXU{%KY} zA7QE`aD<`fn|Esx+XQ7X2;$)oCKB|}xcP~M2_wm5icmm|82z~j2CvzySUkrq8G_kz zI8Lm{YOn<amrLde9%Wb;$dQQb8My3fjSycAG|w<7%YazLCbQI-t}FnBY1a6_3C!e^ zhc|=1$-chsH=o6mH=I>=r|2qPw0@bMT)nEc|GmHvq^d^bjl_rl?7RJ5yermd{Qjp6 zUDMa51#wHqeyVtYs&C#pV{_eMnptG#n%_O&5A$o_@8J+;;f_FH*KB;(c>6cew#9IT zCuDF}e!f}5&-jj76!h^PujMjO6$8VvS)5JpVa2}*CPN{qG=2C?jo8TM6u+)FySob9 z;stvrwyG(xrdEiVN-D(-saE?ym8v(Dnm`rprp@Fa&@o6j#P%PORK+u37AnAIt`GZw zgp|2BIv@ky*rTkbLN}x&Q9L|wT(?;QcxA|rh^xV-?4vZAQJ)(OpNEYoFJ_a!exhcJ z@c<CFTTTj|-Sd+Z9x_?etpE=yif*9jFB8Y%xRx!h!_39mYmV1Gta;CEc0^HjJA@_J z$YlCYups>d2DP2`b3u~QWVnOiLBEET?1XSJk`82;UoqfHY>|r+G``R?@o9-mAG<QS zFC~5x)}3DRTO$6^!@rU1HiWX|aY*cs$ERf;VI-%|ryshEE!exw-UZm@Lo!=5eAQ3I z)nQT1%L=fHjf|IT#9^gdREiC4iLiJH7`PRLpwo|Gf@c2}=y6RUM=^(sLB|vjAb@$4 z;y)i!thbqQ=x4lC4rT%=Mm@O?85r_hTe&bi^N-=-2ag$TivQFcg%%a5<#3ckqqtPS zZQ)NIbVqRDxMz(_rdXqk_9sf=sDg0#1Dnlmf9G7>e!r_bA@nE#&=igfJvY`G{}?l3 zUkDLAoTurP^^~FM_iE}kL(|V_>UKlZ@oPr&oDi~-fG_;~ryc}{;5dAP%4+dNqty-^ zzN1QNku0&8)@c&Jd8m|m8clzH1lH9pu3f%J=3u=!S8!Ra2BHP#6-}jn>p_|K14hJS zud+cXx_E6xLLvDsFJLEmcc-pLFP{6i+g(M96!-YY(%oA4El~Ih#3ocAKzq>9ysQ!J zH8@I?&Hi)r>$5l_irT^YUeoY_<EkXp1#Wy|V8C+Fp}f}HYk_L@eAS}aVh6)V>xHaX zr36Y&u~R8_`7%{J{=d7y|6*!cC=oMaLe?RL5GT%`AwsH<SWF&#gwM`qvvBv<8{d58 z_bUSsKoIx@>)1W@C!nI&$ma7igDzJj@*5GI)}_<MeU?i^n}!H{(XaTTpCC}9>5Vq& z)0)n>)Ts>;t&kzT`uIWXLGLi>!UeGCk1Me6JVow&d1VMgMG`94nc<*Vp3}Q?G4u_B zql^ejC~}=@ZO<M<(kPcFuh78FjQM=WvZq1((d|oa`v65MDax)S5>jL?G8Vp^6qYg~ z>>>qxM~Ji8F7O-WIB*oItt&N`xi*f<AzR`%igoC60X;gXP@)=mWZ-f7m^M5likLeR zULxwvo;%Q2s2=O2a<#R<0w5{^Xg<K97`$epk*O3pH3~bL?kt*$#Zo4ly&$s{RBj)q zI&gWqZ{Y-@m=uQ|#m>ZWDV6IOy}jTlJb@(=F^?yfFeylq2@K)$tDryBNEitls7M(n z_=}bm3bSd$xhTEiWBd7~1!*7(3dnJkCOY^d#$slFPh33>nR>Xkc5Kj-{`0ZZ_;;7< zH)&Gkb9Il-8dIS#7zB4aMKAK$na4Mx(z0<RGyUsBd;~KU;!s(w(JYxO7SEU>q3}EL z+e3fiIL;mBQHBfe2r8$o`}}XN-TL4E?%W&0&-A&k-~8b_&Wx|lzi)>ADr{(&6h_j2 zKN~Q9<aR%-NLsp5`@`B`BDNJ3l`VQf*H*V=>9kS`dd}}}UAIy(ziQR`Z9vgih1qm@ zl~TE&R3MmCB$Q^aN4~#xFPqKcrq}AZoLxJ`uuac4m4UKrDnbIO6hJU@IE$E8>^d8M z%63Oc_=0HYE|vN<^lw*T7lLfV30Y>ua!vQ<Ow<%>HQ(}=^DFYd8dMyYuFyQcO>&+{ z#7xr26p7|3?b1XbouK!Fc{NiC*UVr(=3hyKPs-tRFiZx7%QYjxxLk2(?@D7at3g=r z{kZk?w&YAPbQ%eQ375k%1uP}Z<B$qEy@YxHtucYxxGr$#n`b`v7q?IAFDC3=xYL$O zIrd#Va;(;M&%c#RU1zr|6$vIi-P_|qpUdMQHNLrKNii|I_W~81FAqw9O9Z({m@~LH z`xjO`^XvjsK{Pt}^^e)&DrNH5EHP>rHG%DR2ZsCmz5bw`=KQ?<_g}2sjP3E><8Rua z!dO627(z>@V=<vn$SW0#O{vEII-SCzK1u|DGZ6&k-Jt#Wy0L2e=tyKVD$Tl%b|Nxe zSt&3!%*lB89IX<p1Q2OmIX2s1a-<5g8<`xm<#o?S()F$pL`M5F(fX81+ph58TwR{w z^Pf-N0C!sFGfKmJNZwC!!b$Z&jleJ-<whQcrL%WIS}2nVP0)P?VXk7ipc#8LEG$`| zY1_+H%E5zej*UG=?4}o6y=eqS55@?%Tmh3`Gvy}Bj<#K%$|L3NPb#hR>P1D%ULsa| z0K<e`z2FzWgkMm|#)7+N38uJO^Q^PJzbxy`6}xlub!q95Bd=9aSl6iD(*1iMymi!m z<m8FI#V(g%!j9WjPO6i}@nJCW5Dwjcit(n4Gk*-TN9X06s<4n`h&T3X+L-}zq(t38 z!J&I}so=NQ!q@(nOiK22?a}LiqBk{y-)T6xG!mE2;Pd10pCdnp!vw)f|C!B(iY>TG zu5xEzFO}pfcSrBmyn6QRzm6_(@4mpCQ@z6V?%N!+9DL1Uq3j0ieBXRvJ9gA+P}uE$ z_e{zuC4BTKZ-EPWhk`rzA>TQ1?z;ylz$d^+=0CY}?qP7fb@;W{-!@fYAj%D1eO5E- z>wsXQRMWJd(6uz_npenVRnMxkPoHM9_*jvc&l%5ojM%LJjJJ&W44#oDB1RG<mNgpB z3k1C6@g<_%oTCUQJzU6>>nihmD0ePzvs8s!`got2RNIS*@pu^4gyBZOO*jrDk;Db0 zh5}otx@(hc(&Hh?0O{~}9E3O>MGwEKd%G*A?Ch{xLvFIzMfuGWpt{Y7N(BN63|oOf z$`cBCCKbKd>BNQ;D;AVkvz8njx6Y2qWGR^}76}9*reO;!t5)`p!`E~BY*Z0<ZYd=C zVdcw_6DQt2vQ(XIRy)no@-R-8n3QCV;bB+>hVgLx{)3T1d5cb1QX*L}eu9a?700CA z5)}o8b0VCB<2X+!s#bzQNG}(!;Ckyd^^l~EBt7Z0_p9@+_xt*S!EXbx+p&PKNwd~{ zcli8leHQ27amy;}RF%r>t#!F_=R4Qwj**?>(&{QorBthNl@02Ac~X6#CP<SVfJu3h z@lsb&HSX%#-Aaim;q0kV@Zg8&jg;wtB|8K<3Oq}bTGqM!S?I^jIb6KSL986-Dq(s# zwzM^@+PGT|7R<SI9#Dj8LM&5WG8S|p$=UBPe(3a`9Y}I}yrus&jbR!fkaxWZy94!C z0HluKrvHE^RPb&EJ{P)_0sb#YK__!{zLFXjs3+H@)M)dJPJLzLMf}zI^K$NR=aD3c z8XiUt9GDcQ8#eijq+rt1wCQnsc#lKrZq-cQy>pyTq1*Y79Iw-k)mrqJQU<~A%|8=4 zqqFx=k<*z`n`8pe4x$T<i(gj*cs5a3S0GH3yb0=p<O&D?(6AqB?!G%|eL=;;Ot~Ca z1AxC*eKrUH{yAUse-hoQtz_x|Bn$w-cZ-D;9Wr-M282pj)O>{^0|3QcsLqB>YF?8> z_9i<SjFO|O0!@&?Vwfevtie)?vo!BrtvRztM1}>-Sa1+5b4QsPR9!fw*hZfRnu%eU z)s2$f=xu#C;g2|(9g<gF&SdL}cA3~l&3-l{J5rm7V8l|#!;uQm?&8ekZ0s^gCGtez z`)D8>Qdno$Z;S%l$e_)&z@}&dVc61ubyi+pnZ7;DF-}IKPKstSjahvz0>a8|z!onE zu!wo+T*eFmNUplO+`aM!7GTdWC{bkwWwf%0a`xh+0s|sc<N)`n#6U#bwz6LoJ3<Pe zuALMKTRqeWa9OEQaAOxo_jOKtp??<CSO}e=#zE#hH6C1-sfmotwVO8ywh~l%iQaD8 zv}&Q#Nnkd~nM<Iy!cD$qw&*;I+f39<u9vj!rHz&@xg9C$>hNv06A%%&I_d9R3(P9+ z7Oh5R#Mfx1jn-|mS(dKNwkyAtIB}X6v1Srm#$6pY+`YHuW|Al~-$FHB@SGPcv>eQg z`M}zo1kx(_wrllLe-HsFALK{r3=$j6QAT2}O(Yt<@R9PfZrg24qf4*zD$VpEb|jk^ zv86X)wI$S6+mveQ1qzm!O*ESZ*J51|w<%9;G4Pf6-222PbM3Gh^c6Sz6kgKN;N`&1 z7A@x?Y@>E4)lqJf;N$Q8B7he`5G7erHQg{R+i^WIg-W9{m@GDj%i{}#BC$k@$#A(s zsZwjSI=#VYGFu3%&F*lz+#avb4~4-INE8}_#o-A=5}87!(HTq@o5SVt1wxTnB9+M% zN|jop)#(jJli6am*`1tST;1F~JiWYqeElH8gfcA03!)?|s-_#JWjn6tSNN@^00iZC z^AZgDctaHgO?vh?7Z7o{t77H}h`f%E<`H75u24xSl~PeNkR6h%ejW8%)BJ)e)LQF) zAHiJ}(+1>=e9cvh&vu*_N@I*M-91xfs7aDIFSmK0oF?bOGKf=ArDj6HWM3gq)a?mw zRxYHr5YsTHG3HiO*~{A?+qUKyY6~%CLTU?xSq-rzfHEPq4ICJzEaF#}x0IOskkl9c zsO#|`RR8^dfA7!p^|!+8?zH{Jn<4?>A~<M+2%T}G=41i0BZoynY?3+y{zVT-eNzCm C0|Gh# literal 0 HcmV?d00001 diff --git a/.next/static/media/2aaf0723e720e8b9-s.p.woff2 b/.next/static/media/2aaf0723e720e8b9-s.p.woff2 deleted file mode 100644 index 980853fec144d92ffd3712e7f2eec6395f638f2d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 37780 zcmV)YK&-!aPew8T0RR910F#se5&!@I0c@}U0Fx#F0RR9100000000000000000000 z0000Qf>j%VuL>N-20utvK~jl724Fu^R6$gMH~@tNFKiJA3W23ifrfhvg){&#f{<nb zHUcCAiev;J1%+G(AX{!(aROVny%LAstm=0@fC68j+&;l=gIq3e{^*&>I5q(r2SCm6 ze)9kSCng&)+=1Hxz&m|at4b0Ek3fJT%S2;DtoSrLGq-&nXHV-qF{_v}#m<(@$p~@X zi6@Z=7*@xqpa&6d=6<Z!Ro&&t6m<n6uu?R}j)&lZjI!YfaVxj^T6Mz{t+7orP?`FW zH$|D&SNOt7-KcC|?vfNv@emG|(*(`L`GE<-hKWtMe>Ag3Qy3^3q_NM0i*E21-#_OV zo47NN%x$2kJ!YDjsic0X_YTUGkHW?N`dCyNv1@Jb@+*sKQTzR~1p&jPOUh8L7yd7} zaIMncCzh`7w+xJ31|_1+o_K$rf9LvN`}`9Q$$=a~NDlNQ9737~I6w-4rf{Gs2Bnp@ zRIy^k4pvlJX^T#^)Fy$}AMZU>RK{WE@~#~p_I5_zl;_|d=kmPF4C7!gDr(f&p*2&} z8rzfxIKTn8?f+0qo+GK~X=yLZG0Tyw96QOmQ4~Z}R8&;N1wxLAV`CDaJ2SPVW+tXq zmNusJva<E_m6et6SI_?+bJ|}UVFW0NLug7nZVpZ9vU6tW9A@S(kYu)<zwFGiE|!`8 z%ygs6PEwj7shg10VM!ctKp_Sc5JrIP2%{L;7WM-k;$eglMz*1sroDQSc3plcm5{K4 zgJ=Mk&zA})@bD1X^y^i3&x|C0Ef9xCAg#S{5kZC-MVQ@`<s-xh7(-?^|9sr1=XO^t zctQ7tL(mCOF@TwHF$SIg_~&ac?w+?Z`J05&Y?PyPVL%wVvEV#Xlqzh-1BY{V*STa5 ztbi2&JD|WbyHQRU+p<ZA@P5A@m-g-MJxMP7ErT>zfkH`)s1wKzKL3=Pe_z;AikjMp zDMmWL2qTU-Ld1X(UM7<;&>@WJ0E3MXH0Yoa$29t*P|GxQ-~YbYb+_m9cg{Kdz5BvB zhwhXI&-eTNZ*4q^cw@Rf!Q{)ih+h66s$DdZh&o*~YNSF)TG`9Z`QF-95F?lV|7cr( zUtXp((azsm*<ULA>&u%0TT1_>m6u6?s8J(E95G_Vhyw%}Fu;JL4lv-@M-J<b{IO$a zTjwm})9b7Uo28-a>sghLwR+jsR1vkJ2wA-d<xV~{O@F?<ESmjCQM4MN+@7^(oxFQ# z<^G3sNCq=;9$_%X4B^E)4FgQg5WHcUPLoF%yhCc*Svt_6JJ4C`4I|E!>B?JtY_0@= z2HUzw+;+g5Y6#J_RCR%+Hwn@pyIX3TG%UH?o~{C*vO1a5S^&7?UG|mGUG(K#_U>s~ zZK6%pjFKpg%&M)Vilf@c^u+lCKJj^TZvcEE%xoH`NBER;YA{9D;{>7uVQ$UjwsX!g zlxz?!#r<^kN(=U`G`1K1PwK{SfG`>b?7Pl;A*cYWa2IZg3@@pgm~AuktT}jRexBc^ z3PThMcYtw#ZGRNqTO3Me{k^GH>3;+vHpc>^<!rA9XP3LJv6QCvVwv-{a&JDm8*B%N zO+b`DfSdtIN!Os!d;r8;0}y8jLex;Cq;Xbbto;Cnt0p;`g9yrStu^7f$VE2XyJ%{o z4KKVPz94fZbta5A3NHzKeDgoG+59xe9&RmTdi-NAi$tPwKe<a6YYoM_^#3HZNk1ct zv6nDtgD^;w6t?=kD#jKD<AHx_SxWcMyHUukDb=pvN^(Xn0g|~g!l$0TF#ETaQcD>* z#sCdXQ-C7WCfoqJ449#<TBdYI`>l}AAp#OIU<n{IcE7*>ues6cN<M{Mtx|f2n4p;f zlMRi{LMFt>888!If}sgq8(qeQXh{8$HCf5h%~t(isKT=o==bW|;Nr5MNs{y3zVGXv z1nimJ6{=}Of&>XcL<(`G?z{K-Id7H~llOwxO18924<aHWGLSJ$TWKAfk7hWEedMpn z($XW*uCNEu%2*VW_DcWd7<=`_w6@#-)|c0%)+SU9AQC}DM7bFE`#D^HjQf=fYeqlT zKd%lDT)HE*n}jq7%S?54LTC~L;Q?_F9!7<5R2GC2+llau6X7SPO~PrTI&Ib*3LOh5 zvfbv)v%y)Y(6L+K|BXWc1S9|#01tru0A2+!%?A4<4gi3{4iEqk7~VIUKobChW&w{U z%v3s)-3p>4E2@TxVdgA4FpxJ1*`mWGD`d*f;~xTgf%xYA+sp0yt&HUcH=@#Y4P#vG zyG+Ara(*bmH~6SHDCmwTWQ2&aQS8-_^d}BUnKA<nAV5F?CUAj|e1J|NQ{X~CFbJ&e zi@^p!%S417Jl72Dc^u76U=Q@jci9P`AUZq%00aQTz@%3jtgR6Mv<-X!isMDO3&^*> zzS7*UcvBzPPOE$}$5j?J<^CS|ts~K#G6Il+=QgKL%KXhf&6|Lr=ta0q$rG+=EHOij z+*AjQC$5-@Kc1DbAWON2;)+biGmi6*-*<&+hpWElf5dSeaGi7I@oB(K4o(|4o;sk= z-4B>*RH4@H4jz;}*&gFwTRk;Brm4Wzhddv8CV5(s`4GvB*m%-&E@Q>)g<e~|(17)R z0UyBjaUZg=>|JftF=3`FnMKM9&MsN~Se_p%U)G3q&G_+A1pA4mRwduPYmgz263e)Q zz4BME`3+zY3#?>IEk)U7y4LVB*q?RJqZB=4BW)wzgJ;T(U;tPDvXQ+BP{wtIJqyF{ zaILYz(rV^Hj7E_~)x&=xOxf@{T!>1iY3zkv;b2epJl^GNJtYbw1?Z6q-0JGOuSqd1 zW90tTga@DgzrZ)R<>Ve@qS6$WdH#!^Y}Fcf%qq(HnK_pVIu4w}V$Y2L7^xCqv0lcA z5~!IedQ6P;7l&kXy{-sWml<VgQZ^vCJQ098-|M_o&SW)Ba1`b@@N(grdtqnQ3~JO< zO}C*L|F-Hpv!!sj73r$^2*|8QYT8>e{%r$`hk-TDms_Dtg4olzk`=1P66tOH>;?aD zA~mj3GmY%k=n*h!>=s%-OnT*#qUBNq4g1O9*d@`NVkqm#?M>QRj-YV%Fp?9xW*?HK zJNDBDwO0Nl0+Stckw4+<L{#!jlC}m}+3AUX?dPC_yjo=KYs+vMc-W~mt~C`k@8>kI zEgbd>Sy4&ut6uo)?`TQ`S*;<BcoiprwEny4ud`)5yvD5Oe8Y7gz-3rwwEW5osI*U! z?Ic+-ZF{S=B$MGdfS1uvc<zzu822{-7D=1h2T?l(u4mb3=HDVfT86X|?_~|;Yt1yM z`&bO_YI`u(7*moh7aSy1qq$v}eH&D4>Df{qlkRpB-j`uiL=Q+3YZ{yBrXMZLXuNfb zGy(P3;q%NG6h_kTIV*B5$TYV?Kk3!)P$I~!<9pL(8TH0+KZi*g+epSLY9~FBddmh+ z;q<YXsfucEB)t|EiaPkePcaqapt}vF$iw+Lz#~yu$hel4Q`L-MzlNus`Tmrj^|s+z zPi2kj&N(nlx0YNn{^}5oxNzkaHDPbArwOU0yOvqeWFiiuR?jC}l_V#6@XIf+%J??H zGN&>rYmWEwPgE+C{h^#7mF`mJ7~0}(Cwn_(%v5oJoAynBG8v8W-j0}++><S6aY-NY zG3#X%_3vTx^dUTmTK>QQ$deh@O{UEYx#pi3iS$V^C^<eNMJmi=o|ep07Rg@6%VVo) zitYsf7VeGl?a^kWqeI9iLoqYCpHN+VDW_8^dlKZS8huf}60d2<uR$$+M7pYI8AX0j zT&7$i6`H-ktZC@~8s5|#uMlb1S}MyWs?~A6plMSEh1oY7kHsWOD+c4zAHuJ)5ffA- z@uJ4=h4xR^@^~HfRD9t~#_IIEjj}=PW8&k3RI$<poN4`IQQ`;44lkBsfUh4{OJ7&s zE&UpPVH@bhu^(!1NOV|=N1J$<2h1)PYBxD)dO#!Tml1~r#onu4DbSs)jTC<Sd6}lX z%#a{?Svt>`8Jx$mEl?gQ9n{u#&Dn}IsFq|Wt-izSSCgG$GV*b4R5-kry@OfTwI06` z$l`%?r0{h?S-&0_i?Yjm9rPW~*EW>*6>5UD69au(8iZ3`?>1tV&urZ<nI)?ckL=i; z`Z<M8QNxMas<$ZyGQh8At<u+#UzA*UXP;gA@_`W1d>au5kIm`b+0yCYBHB~fUxt0J zp1i&0%OKm77MRzmfpt;ZJCczXAz*MT@L$yYXVXf-GRR<LlEp%hEyp?{E1O)BJa+lk zb1G1%h^$zNQf?cSDd*wi%8dt4UcCA6<;P!uKq10}!y_Py6)#D$6sgjrqszrqfQ7A4 zwOV!Rb?VZiSD!P6jX3Xui!PaP#U$PYL5OI^tT|!xq7*TzxP&Cll9V)L*@{&dk+EYp z7NsH`(j!iqbOyW(Ic#z{RH(Fx-*K)21SVx*NC21`WB`8$8E5d%Tni{j<ccl052f2q zOi%!u9-)qyRCK!`{N387%0j~#!BfWm%;dm#$B8fGNm+jAv^mdDdCWhKmo&t+u1;LX zz8kdgpbu9$*g&!gulL9eXL{^1r&<5`kI4@aMf#CWb=b(1taMIwE-f8Lv^6N=jxPbj zzYd>kV&9%cPulGisMz>?rw4~*MV_6uIsS{z;By0g&qaIjai#`E-&JGBC{A^`mmJY# zze>+vRL)PIfZ$%tJmM54*p}=et`W{Vlh7L!!tFxXh2kdyk!NB!g$uUnpsNYFWQwSI ztq0NlD+*H3&=?g4pi%Jy>1!l01kjmqh{GJY<LiUu!>vK46Y@D9k8_7=DWd}QzyQu% z5C;E2dNWp#j_{P23_X+kQ}Ta<&-jwB2=i@fAkF!0SLO?8szOo~7X~0Oa0p1KtFjOP zXw6BS%qg78X`Id(oXO>*yS8)?Re@?6*j8<S08n<KfN3rh6FVi)UO111hXi8@I0PgV zGz=CO7`t?=_K1EX_qmeClkm>M<6VC+m;Mk;tWDYm2Vgsm>|p0C+VI(+qf<`{aMzZH z%BeE~?D|LKLcu$8=yxer%NPN+TPn9$_jJq{fkQw-LBrUxTCOl~C9w%Fo2jB2#kJ$` z7T{wmb=-oVdTtB12YB{9n~i(C7u-uL_wftge-1q6#}SVAk4m7MdrLzh)a&jkg<iek zWVbox=bO)`PmfMI8D?0+{%Df?=Y;<Zf9WKD3xDsRM2?k337}tysEP}100IMtfUKwo zfE{|f0i51maq6VwcG+CJoPDqrKLQSMSV!V~LJIgT(SIV3Bg}W~OSX;@|Kf7>V?pfN z+OozPYcLoL27|R-h=%%y?L$Rjti8cG#!oWPo^FHj1OgHY8fI-;DM)=#CiHl?n8&O| z=C?26kp;189{Z0r;av~0KLiuU3<_de_8(v$Y8Z-L^ure)A`WvTzFlZ{!F=|iSjIe_ z>+RhvKxq>uX5L;bP959JY3BOgO9&$UQt<1GSyDW7bCAo)fl3Gw9&#<G7hYAm97Xud zkw5+%MriD++QwcCP7YoMPEBKV@B(1ZXkgk{Gv~h*pxXrOC2>%rZ2}Gf2?Z@CZcS(+ zk;=xQ=YVwNJN6D<3f{P?-7EW~!F>%7NI6P^kwl6uY(*O6w3}j`o9GDz5U^*I?p62= z_POzR9DB)yOREMgIyG5JXj7*Ic&ymSMIsM7`8aSUFA7}*WQr+qX-`k!!Z^Mw6yZ(` zH#2v!k2W8)@*!}TBR<|;d2*TCnb1(sqJ5I`sWB+xbAj>j{SdxDz6k%2pNS3q7HN8> z9l?vMnIsn^85!M|qwT5#$pSR{Ie;4KXrPG}+UPz;d%jqTZi3Ii-ppM9#<k~=;l?Dx z!ki2@XWdB-iw=jSK`hUreE!77>|igT698|30HA`E|Ak-<0000mm<Dy^4vW_`(rMrL zR7MgW)hS1T*nsO2B1UN44pR3vA1GKbWigj;p^LFXSO7X*<UA%z+DA2KhI{5{&?;Y> zhZEXEp;Mtq*VT*l=u_g1%Rj(%73cVvD!%Kgmx)~Wx;YDPSm3SWr#wDBeZ#AB--Vs` z$%aeTJzViU4EXog2K|bH_mV>y{a3l`SNpUI-p=Re*28wMK~LFs$7f1o$S}&h3<tmr z^Vp$mN^Yx_&jDe5{5WGhcXi6LffjasH15o7U4$5FkPLl9b46J;LduFVDWM#KSf8An zi2U{nn;31DimU3?aG+4O0G!EU_~QAt9#sUzq4PcxANO%4P5NU?fQ%Z1L~jUgo=XB? z-7R-E1n|WIxP~Ujx*-4n`!t}(76XU7rV>s^*4+aF*HyzPSX~Oht&MS0KNm%FVPn{) z!LG!>i_0pW8=u)sPsY~~0K_IJ8<S_+ijU+e{l_xpI&At{r_0i9*)iKfuq)=nAZ+8p zHU$v64Pn;ZzPT7uN{g%NRj8!*Ca>69jonvNXd^dAo{lGLW*_V360A1C;d@ikG=oJT z#J6Y5W*hD`T!%BW+#*?H7p-FU7-Gg}_VOuYgw&aJ?TWZ!Ie;>rtF8y&v;o*0cn<RZ zcp>sh1-LX%f}*na0z<^Gg6TwfgJ3Wq84E_EGm{(094W8h2*}W2Xppc>)F>^3lX-S( zCFxGdrEd^O37B*ZqJ>gggVBk}xS{w4(U9g8kSc4&T*cN%whaASfHXA@VUfX=ov{)Y zn@vE<Y>;$Pye@|{3z;$wOHgjcT%DzWBgYvmE@K0<0Z^$E(*y~XPC|Ib8bFu+H{ROE z<lmiE_V8Dk940T5jvU7PuaM@qaQ88JUj}Q>Ck|)v{q_HG{QCU64UvFa;;a6i1}g$J zk-I`mMe5R*iLB%#_kUA30y3%`Y~||k^%^odHd7Zi=DBs?L|i;^lB@yrJGT8t28UJw z5Y`bdvvznrqtwyg22CU7>UG*z=FSXJXGq9K@!qi-Thq-kp+avh%NTXI70DUEW!ylc zwAS_d2%bbQ$ko4++!(+h2hJ6M{OWl%+rqWPtNTh0)USo7pG`#L-(G#B<2en79C02v z#Zx}|QI38=`+hmDs%!g2E^*y=6))*hua!%_(3QJ&-;Uhw`_>!Z{J!s=zSX;SC+^(C zKk`%elpgs!^UOWfC;E_K9(sJrrg7NZHPbUU#;B7;*B(Wo*!<A^1zi9<hcWQTA5&z_ zfefoW2{9tZ)!XTTsDeB>J%0WVPDFaYd{%{3&Qj7w5#~*gUeyD_K~{z1AwV%(lX!z* z1k=E(tho3hv`0^<QGpaA*yB?g5Fn!wI-gNb>m<oCxRpa1_$9=ONPm9279=1&5&VlD z*ODki7fZ&MoHfmC!0<zjYxndRTdzTlY+QGFQIvUZupU>U1-8TvN8l2Qp#&DP{ZDT0 z{=DW#Wic}`$_$&{Nx_POA_5c$LpUN3i72E+DM*88!~nYJE-=&C{g?Ol?{_mx<+M`X z4uDaXj&@D@uuY`o^*SwECU*9#ww*Pu9qd%Yrs(!d&k><snEvs;&@U90^uFdg)qI6f z4VIfnxnc-;s*p@?J_=<jP<r3jiJ_e>$yhq1oXW^>Y3=mx==+LL76RYO`OL=q2St2r zXa+N@^;JW3eC$rl?7sGze$;p+_uIkuZ`>pe(I9)}M5}~IiRG)RUG?E)YLn$Q@bWWp zIWajYH?mw-?V=86#i0M;&KFXVVV%mVM$G+K7cYHTnW<ERtP+pbyqS;2GO)AX%aY2A zS?(7EWQdfLywp#^2RT0aTE>gO5$D|aH^cl*frptI4v+j3`hMa=A*LJBh>}_*b6@u* z(rrB(u`3T(Gbye^mi!)g&bbTMULXhif%;34P;l!-@2cD)c5+VH*Hk6lg>}XTKd&Z+ z3fm>P{ImwKR2Uaga5kfot$tlbp-(GxF4y^mh$26zq`ZeVY@ALfmwca^8lLlC{(2F` zKB`eH&H21PRYpl80IKJ)`=(Sn?XQ(K=wXp?32uKwgOr7i3n*fv*ELFo)DH`ODWl9w znxsnVM+F}$sJu~V+1zrS<0nrDcU_rF>x(wyz{X9fnl@zBskid=paI2JTcU~(ct_Hk zUL&dWOAKZQ2D3SVO-8IZFA)3WY@+rO;%JNWE~q4%&5}2HfP*G)<_1z_$HTrNkocPC z1gZ_yj|%$IdT$%(p~`IgR4SzHW=FCkS7F0*1O*_U71y?ajEYL;z=kP4Ee%hXQJdO; zPjfC8_PyA-GQ0IlfX7?>fxEfsHD<}{$Dkih@-esi{H7WAIXBe#soYNR$FZq5q_3TH z#-OvN;AD}6QsWcn`gT00@Cj5rboP$8Nj5KfTyab6N&o)`H|{)m^5V^hFF*cCOl=)7 zJG3^WZFfRRB70v|I>+V7$M~BN@r1&^>kzKG-Xho6dP=bprOK46P^k*Xv{7Tm*<iBm zhM00LIjKx}TD@NVFdvUAl(>^`n{jG8lq2Gx9}UOgabvnLEiJfh-<5m&#_iNyuxmDN z5A4xB!)8S4*~qmhfXtX02=*1+nSjnGrB%0uJCL^d$eaMpVoa3qvPN=W`E~Dw!3#F9 z$vhhvw8|Z*<$Wgj3?C8WU-^v;s;P}Zn=QGJR_m_CvE@9%#1B<C^#h)=;8|AWH7}4v zbcaYOwiCwA23FsfsZeqlN;ER3(;J1Ck_g}&@8}LQ!{<Qr1z*LRpZFzrkcDR&i8-|S zk}<?F`3ent`<IyB4Rnik+6}vLyZvZnr!i`|-`t7san1#oEYq6$TVCX8f9wz+_UDdq z#J}kJ2~TQqUW*{wA88L`!$lbiGeAl(A{6%lDI!uvWf_48Dk~VQn%VfM1=}sV(mq>; z#-{e>6J0;OlbgbnMxOb>GcnS{22Ezv^^M1jL?J^?x5z_q5W6IfDFkNs(Bptk2$=*J z1J%UFz{ZdTUBzEdWU#;oJ`5W8zz6q^RgFxXBtH)aV~QC23oQQ?(Tvql`~TZBM@nHl zsg0F<NSuhIc_32}G8-ie(G!ZCL~yc&y?iIsoH|-kZ|e$LENxKPyUI0R)Dx|Au|{XB zG*!~2B?6BG!fRXCmaVcg3%9gvqg8v~!Y!`2<yCiig^jGbD{JgjvH;B_OPwKWu3QFD z!K29?WZ{`cVh)WeB2hGSOzoa-i?*G*_vxJ2CAo?Bn6qF>*?F-OO2$NHv~n~`SFPW& zb5{9CPNK92no4LkrG@lD$tA*N2b=~Ac{DM`7I(Y}g+LNC3gF0tI6;L)3}#VCL0FQY zyjW(Ja~^fo-v~*jnq#5RqM~J0mlcetx}xD~jHa@xYpAuZc@|hi#FEM=uflTWn{Kvp z^DR~_RHRs`^s=pva(#Q=>)!Xd@BKc{1ukO5C5<}z7>AC#woY{D4)8f0x+CK)?FL^9 z%sN$^ulla}*Q=uqCGNcGSR^qS9AhY{;u*)HLu#8^rl@!o%$whU5{TrceH3kHY-hFK zx8;1r$z;YE{Z4QE@Ey^z^CKe)>K!V9c{Tzb<x!v8+)?!`{2yna)x>{GgQMoZMW%$$ zW|2&6NQnZ4oMbUvN;GG}Ms!wq@cr#!R7M_?$r6V3bN+^acTL4QV@QN4PyDKfV!qaf z?fcFHVQeYR*L8KDGs*rGCe<k-VSfc5jo<6De}k`~Cp;?j&FJK*nWs4WI1Vtr#(_nz znw5};(>hT!?wFmukkJ8u_{b+`{9V|dsIav^VJPhq0Ma0-gz+vny?oUs&04e;8!VOG zPqp;GN#iPDh>Im&pjpN__Uk<zc<L(}qkLLo_j2S8mwc8==-y$Z<HLGL^#?#(-O+}= zCag7~%Y+pZdUTl6p+kik71m_<l3_)JHxcG|C_K!ta7bTh`2rwfvphekI>PUr#9zjs zRFJ^Nc)NYRG~5{8_dmaBATviHwqMUth?PW=lq3lN05dZ?OHcYdY>I;j=<#f~P6$&k zV^AtcASlgAk|Y5D0D_vBE7%lPN?k$-fJP?p?7W7Ia!?&8#OmsubIy?@DM=Cl0A^+u zJ8#rS<|rgN=bUpSNlKCg0Dzg9C6Odak|arzBuSDaNs^=_Ns=T<k|arzBuSDa0RR9D zqL4(Aq$EiI03-nb%*@Qp22n^NNm7y|007L)EU_W?-p1Gz2NBS7SA)aha5xAdgb*Qw z5CQ-I05A;0Fg=-&27THju^v8se9Sp1|L`NByy4kgz9gm7Ym<o0w&+Ba8d)i2@}|04 zhMT#}kn=fh%UsKxo^!Xk+jO<uE`+QGbC|;%&7Hm@iD=*(CbsdebB$$nds(P<^(Sp< z*^zxgg-@{k7i^H-PtG0`5=w4~Fq3&YX7Y+blMRPJk39?65-BOt1G%Y+>glrykNyBq zm64zHi@0rAFC+n;_5KM%jTiqMn9aJLRdZ9JE^IFiEHz5H+>nne6P1vnDf^Z4YKMAQ zJ-u*T>-gaC(taGmKCIysws2<I(goeCcT`h`Xn1Nab5dl?8ne-QPx`s7*qWWP(@v-^ zdz_yz#u`!MC&qE}lVw^KJuq_Cj_tqb&h?~wf7?+Q+ZWAP@fs%9#n9WZA=yzx-o`~@ z9eeH@BR?_fID2^owq$RZAG2f*v`Ih^97ryJA|O};7J-3s43juQC;=2f5CKV`Nk|@n zDg#@FniBB>Y85mlU<xMcbRBd9WRq=zXhAm9w(&CT*hGx=JBQV6CJDQ^Dnwu5(xw;N z+dSAD!dL)%cu(?AJRl?az>G$RkPc+d5&RmV00<P+s*WbtU~w36oFGi%JV=LWO(7j1 zzhw@<-<S+OIM`hay)@YzSU&?Bp|r|*;BsyyHsqOCrm%vxt3DQR-OD^r78NkiBOR(t z>MaePzS5TQJI)X#SDDQD-NPs<{@yf*o55+PECuY<C4oINZSfUpIW|e9;HG(Dis;O1 zp)Xkp#3-KTVO4=VIVz@r6%y&O-$4nnnP*1|ZDv`Sb8?u_^S{-+wh=9rh{S1_-=g|2 zw{{<g-UAdzCNSk|*CH(bmV0+x9N4#*hN*LiG&oM<RKqjMlEV?oV5U?zDeGEAK&{9; z!{15%2<@&nAv*@4o?n4uLX`hi!J#CsMLCQBdnE}Zvmp>d6mrN#BL=a^N{d+J$x-s) zw8PhK0U3h^*nsthfU4P+^IU*EX90f7B5?)<<A+HI0f@&VO6AXsArMoc{<Z-6s*_g( z`0xE%{KvS%RT#2Dq+(J&fQRiYcV6^fh)K1}RE+!$1_oxjS@hb#Nnvylz0`c@uV!EX zcv=7w><J&N98mx`@;H$rs1TmW#lz1Z4jBy_0sx>>YXi^wr#BVO<P!c+EHd>6*hllv zoGU^4=TGy~FD%x-c!}lG)l08J^Md(n3#S0EQq1Sa{Xmq?>ne$eX#fAq3QyWZ#dgj3 z%#^Q6_!37v70<;xqFKxlZK7Q)6)Qy_*TtQ!v00z5d9gNqb&A74B&#%>k)1Pk{Oa4H zNffqUB35`?J*({h^6E{RnfMV%`)SX<0YrXW&MmrG7rLtZ#`C$w;9~#hl^aXzLqezo zaEHGEdIfIZcN9IZKSa0b1s4d>((ZZZr{!y-#a<E(>2*ctd^O)Uez-$k!iAur#nLh0 zWiZ}UK(pRPz_;O=iH2JUl<P65N3$2yoK>jdz=`utagXB71oj&wSg2@-v5^!?e8Zw@ z(WTXcHuj<{**eg5`=<?EgiKm=&PsAWkgOxE?;)%BO1o;AkX@eqULu7=!C`2O6ndOA z=}fYiWwtxj+aVk@m(6)~PguD}5m~FWNj0x33P&z5jyrZ!gcdIuIT|4n4*A2}^FI=h zC5nTRnG?0$S5W7!o$-xD^l2DiNkSUT>MQ}_#DuwR0d%rzAfwa$Ftr^1;I;&vt!+Z* zD*O$dUyVITxiG><(Z$vHCB94T=0;F2Isx$DX8>Ry2+-pK{tUpn0g#)3xJ>{6Bn;7y z1POy12rQL+x{riQ2#FR_5nRKQQ4k547jqLIqQ0S4vf*#pqS#PQSE&Y&Xg7))7s?9m zfceNws%vO`w0;N*@oq<>;QF7DD8pgMU$T)}6RWd3S_d<15IktanjZm)qF(CzVhKk! zn>Ci4-EIohk7Lmz%W;kCk4y8lBk5=uqm<h4(;*N;%XJ=pxCU@2<~n)CKTxR7y?EaN zx_2IfH7u&!-yjKLi=SppY}TU^`*L!fR7Ibe5P2H9cTKOa(|8cpz!-QzUs0C53@*y3 zWc~a`9w)T3Ru1mA<E*s^8}9KcUn1>J(e5_4JU=9@OCk6RDm=xeWY!wk|4)xo)`Zs% z!F%jyKu(5TjdQ>jKfz$A7%X>G-PO8sG1P~m8>a>Q$@RxAq@ABlkGH{YB5%h%_VZ}y z?#MCY0<6EE6BOla9?BkxId=+$q4y$IV@l%XzV;mT+5B4+7!AZYvQwCp-!d(UMdh;s zIhrnmcjGBfBd(fN&ytnMC|ngrz3~TrBgn4e80>H~>rY_;b-zx_Hi8@Mn+!GrkDyVq z+%ctWp>t;`??nU66*kC+j5GI9S(f|f*zvYdqvv|$+{yk2vyouoWoE_(E0%`Xs@n*u zRibgKm{dNtry_X{eUlK!kn2e=!dGxv-ZQf|^;yWDM66W3u21T!5V4Fxl<6bq`@A74 z^1zZ3STSy{$4mMcj3!}<B_&Iav{#72y;XWAo7MZ8p6k)&y_aPjQkV5H@?DXqR1+EA z+VQa3JiwR8xu>cj7hbf;NmA(C{*Dq2=96u+kSaHj$JY-r>JsC$fe}w}aULYK53K1_ zLG2k3QE8J}3{H$xR0w}4lI8s|7CldX6^xx8xu7vo*uW5*1VFbMb-|e2dgL?e1QqNQ zj!Q;)Q=r9*01u0_g}vK%d4%+N?DH-3H&FufmGnnN-!%%^Q86Z>HA~U>QkiPC9rei( zzy!yI<9%ScpiZhXq8WGnr7|tj(rg@8?(t{Uo*=vT;wA}Ja~qwXo%}$5Sn^au2m{ox zHRvYJ_+j=Lzh_QxpM{V<HiW;IhIrZzNuRZW*2~Q39vGphMLS00j}Ax5;=1Xp?2|G4 z*p+ZyrZ&QG4x0@tfE^-_oWv7UIz94>dVWdBQh;Y=v2(65ywI+d%r+^q7VVUu1-=cg z$WC@dH<_$eGFLAM*5v1&=?rKH37_}m_JV{92g!k+u;%c@5W1}KYP2DCxN`Sh<%p@T z)N`ZzUKr_y;{aP6G77J2-WGq!xzQ|>y=i%wD)X*V{JRk&-wmCs7GUd#d?VA0G!rgN z15132@WAmcE=65?Px1le_oHqi{w}GD*y*#EL(qSxC4s8gsS@KAd1}e6PvR10;|ikg z9|n8-=3vhp9_%kCj%9TXbVh@Ltx8Vz8tv@wbB>B5oPvchC=0F8kx*^=X`qvf?r`IE zmDRHrIl&t&+S}QioByTC5x_<bis(tXw6@V@?N_4R4N4c2@kwGQ8dx0A@E9g2Qdk}8 z!3f7YQbVZTI^-I&Wbew`Dr2J9WfD)c9^vm3Nz+A=Doey0OGO^@wg^S$-bB8a>dn8K zr7hfLylrjNNKv1LP;9{%MBDjU1e7%Bv;?)$7nHrBbncLaDV%jTy#_v#yE+;irbnGa zm-wF`Fr|i9Im>A)-%D=8lpRWuhMN>OMc&vZ-8^KRaBFcC@kHk)u{R!x2m{+A63e~H z+e!4TsI2;@gEV(F83lq7BIU(aW1(%b8lvQqQjBZ1xMPT|!37iKT<-d-(j&APG+d%R z=;ln;R*GJBg!LD2Q(KQe?2Wxr$+2LGi=Tk4{W_%tH9;>yS)SvuaCMS2x_@rCQW%@& zNYZ~d-JO>o{z#Umsm6-`z1}neBLS#{7^p$TZAC3Sqk`UnPQH)vsJmN`;pVS)WH1~u z=$eNpY}Z2<n`|iuj44roP#*Gpr#6mfYAxu(YJ<ISlE7Np=JDqU^)jwZ4Qs9HALP`k zA^uu=^1IZf<VU!BoZJ?YtjjdEc^;U2ctyJkA_cH$!8zS?s!XMHH?cd}w$<R4s6Al^ z57~Q5@W?-Ryrg2Wxk1l2LNm_dP96eKHh(ygF`u$W{i@+nBX>1ex{NDb6TM#(ovnvC zyJ7*eejhk%#0B)JM|6OExJP)H9Wv}W-Um8F?bs*b3F)Zq>LYyYx}vKvgHyNXO%-n9 zT_!fwq&zT|`N;=R--~q;&W1c#ZLXSxXRG3RD-lBUc_US@O6zH~W4crD9SpShT}D6P z=WSYCOE)*N^#z{WOxD)pjd|?{p=xCY_toppsJA;$3jpzahm-Eb9mlg=Ni&Zp;OcQn z^m<JGXz<xrEt0jW_%f^-kJ_zqLs6NR(g828@}B8)FA|uX>j6dpr@?nJZ+A=grl!js zB+bxUyn*k!{D9`9n(a%ta$^j5cHp~d*Kk}u2Mu`;H7lt{!y}0dt+(HDnHij9{E^)p zmr+5TE9+kgajZdJJXdHu5wCdL>c-bee5l61P4gBT1wOKLxU*UEX$?1dpt#!}S~OBk zoFK3U&S}_EqyvuU+;694kW1qwAQXZztaZ`n!Ew3J;7NYb&-(h|YZ4EfO+*5*@7Syy zXi?zQc<b1LXjjZc*`=OG9#2;z2<P|*9r<>u4?XM}pmlt}-<EWDkV9PY7XhFBCUzVe zx1Mz&ay(@Cjma`WIL;tfl1(_@iM+&JPay4m4YMqTXYDy+1Ich7857k$_jXR=!WoL- zY$gPXNU8wj$=2zV%hLfY#$IM*b_4L%)$raB(?u<6cYQ4eTe=g>A4J!zY4wFU!d>15 zorj{PTC&9o;ajt&W5ejH(Heg%4!>|*Q_0>6YHBpOQgGLW`#lTKv|L}LNX-;9y>+Pn zX-OD8+xiSX%XF)DiyC)FNEqVS{EPeU2-lhCp+OYHqb6+Al&(^h_$Ei>HnAqYy;vn4 zpcvj0p9XA^ch~tpdvSr@rRhi7<&R%tlI4O1DFenWZ)>8yZXBiR$W;<6)ljz0jN9UH zw$8XvT)WUvXWLNR&n$Oe3)LA6t*3|P?ZIMsczYApns=G>s<QF%x3(sq4Ssb4zYP-Z zwS#bYge&G=TotbX%@3H)stX*&b7DvWgXzzA)f9biV2AfL;DZ#=*e#bc^Plru%Dx?} z`tsqAt6!(JB2wI-D86vxag8z(6yHuR8XKR#509N-Z0w3BpK3`OGbfJfj}0cu$N)nh zC0f`njm+N_x1r3f{jnsYLRz;rZodDWoEWpd^~;!l{?vYlP8u*6(Cu1(Vc6Kcnjijt zVTtmehe#0j|BX{b`^mLFpsb3;*HaQ=bf0d$VgSa71Vhg1BIRPSaaLQ=yqBHu{Slg& zRtK?L7^;MLUQNm+%jEMqV`ma&WX>iUj7<#6H8h~d-4sY-Iq~n$U!u*gb1j=Izth(O z_NVPG)z|n+IPqZZx^mr^oymSDPTn=(R0sP!Dhzx%QLk<K^zl}TVFSoVr>nMasTk_s zLa%?-wjLD7Xmp86s1NZR$QL%9q|y=AhLfp?YdTHP*JoYa+}Bh)4$%C#81z?x_ML@7 zB~i2=L=-45uMLPWJcOh0s8a3mtuq+QuWpo`bz9wgG&sfvZ!~yD!b?6mda=Qy5?<@W zHp#M3#vbIGevPpqNUNtaSDN)sE|WZ~0bWiUo5<N4{@WHD<rbcHVxZK)8Qs~=xG!r6 z>t3I+->-*`eKzi|)i`&qM$2g6(^}Z;m`w?t%FYhGdOfLY1f+SW;uxq`dX`>(BGhv| zb2lv!Mlx|K*V<uztunn<(dgty!)0yZTx96ru}|2A>x9nNIG3ntAFD}qpJWpR6vFm3 zn_Z*DH-ae5(Y~J4Z1*C=$^~;T^z`wOy!30F&VE_fwpFoR#rfZ|UGT@n#SM2c^vW0E ztWF9sCI6CF!rq@QpPUpo7aRqv<<m2V%SXOSwE*%;bukVg+zZltk^}Gy;F+|$)0mj? z&!2&{a`(!8y>-EtS?|_+`})4I3*I#VIuCaDxDq$4JL5oy8WL3V3>&R{jI9I(-73HA zC<rkeisph$FIcfZs$E^%30zdVUeXDLc6A*mKq?Sdfy#}naV1Pc<&e{e`-VG=jW}<m zgo}gipzt47!mrh8{z)pk+rW+$p2pri6fa-4ePD<8!6V2zo<PuZrB>7LxtC?x9QUIQ z)phc~NJ8e53+t<<TuO4vC9kM^<&%lgr*V&85L61#^lkoOvL{V&q|og1IlMOo@!dPV zKPx9Uqjvow3PW(sxMFS>MiPnq$cT1WMKtq6VjBGu(lBlbG=G25-7xL1{@^f(Gd};( zoYVX1dRpb$Jng;Lm7x@kM+DydU;**wcsiqEzBKXgyyAhZwMVa4VjD~n<M(>KvQ<m# z8Tc3HHMuBBGwGgrbCHDo5%&(o$)TM;iUqRvl#t&&S&mKXpKXrJ6Z@04i2Bic1B6xo z3rLjz#1TvIjo~>1(G62tS3B@u);kCqQ<HUPqa*X0RaPZ8%P~k%U1i-2mmnkLM@!8# zHE={6yac$J>SObpT`_O|*H1LNvB;Oq?0B@ZYIP6kBA;7&yE0W`V2C1pyShBQ-ZnOK zm*48nBJN{&5{k2`lNwVUg!L~Sc&)2b4Fl2PIgRM`Rls0ArqUdlcQ!ihUZtom2074= zmk@C{4Kq#AQhXsnW`+x<S=GPoru(B;SNln3Hx_NlJj(~#!m5r!4x99sv}&yVS?h_x zly^>{5P+IzXP>ziloXVx+~;_6*NemH#Pn34z6&N4*Y_=uUvA(v#`-sk-0NL7`gwTL z0^J-zAB<=i)jZSdwYK_Bgx2I#!(enoPNUNL3ZTS~hc@)7a+2<qB4*6j-cI~)(Ilr~ zrZIYx%OkAMWI-j&<*ovQSe!S_cwBz2?L$rh%*?D#UKpS2qMnZ;jlpA}5CaNy7i^8j zIygjQo%2$?^sq@;RiLjw^@`3PopvQ|VJf9gPKg!Ep;<CMFJ0P&B4YA$29j!Wd!PEv zd+5JJ`oO^7W8L|qOK?!c1(j;37G!va&&PQK`h((zrW?f;bkxy|59J-Vw}8HQRjT(= zbsqohRQ<a(fz`t+3_lr#>ra`~-$`LU4|S<>fcrj=3DZZtb7MDzDT7flR1>DUXmM=- z|8eaPF<M<L2V>SgS{N1!_fFnC6(!x$67|PT!O24wup6?pz1D|q5>m6lapW<-##qO# zCQoOs<}r}#c6w9|3|(0l=IiA`>%&$%+I_o(ojy9jMyZ>D4wdzlGeX<H&OFgOe`ATF zbW)ZoO80mmjN(K7at56P;RHTu9(J(1?^&9-6Ik}K6{8G%aDGhD{#WL=jIPh0VmB<v zXAXZjd{bNW+<ag5P<D04R5{)|nVhy~)AFv-^xgJ?n%Vyj@mHi~AqnJSU&9X>_CT+E ze(ML}nc<IBM(C*>8!`|1wg1W1j4X>+5>EyNwGvJ~xOIMHnGsV%^b&@1CT2TY=P%a6 zmPII!!IUufHhC4uM+rxx!&ObRlwKO#qXq16AWQ`0oGAoX32ON&P>2zzjnr5C0nYQh ze88;UJw96-d_E-SlA~#><+-Hsi8uyhB3^rQ`VsST)<>V^UDp%m+0f+Fp`|^y7S^N| z%<>${8r)YOgCsxQghI2MexaS}xMjL-!;VHXq_|2%fKn|arv(S<)22hoeh$>zO-wsv zYlYpRWVsNqizQ1W=~DGF)e4cE?<|hdWxWh0x7V%fCLu!XVsScWN6gqbl)E@*+*B$U zMHYkZs#C2_AG;!-9z5A9!{-auGkA&;qbf!IF?=dDrc)GLiGp3y+{5<ej<t!RJm-D; z;AMf^!>9BcNxLrfQcrtjW-6ogvd^d)?f)k$wyP@;BQH<njZ1HIMI5|%{a($rBK+&h zf{;zoce3VcedISzamdFjbs&EgtaezkEI;8^k+beph@YKm?SPKz;r-E`0;LE*i_`ph zXsSBNMc)B~(>Teuyx#Z5G2}taQLlJuN=@sqsb>Z4^bL1SxnMp*8*yQls}#W5LDM9J z!;8zCw!#(Rr&<X~!j@c%``#8m%&lxQceN`cL<H$41N&4exK;0o?Wb)YtE9ZOm5&YO z@LWT2XG2rQA?%ud*sKo&TxKx{4$I_FLKLe%a^c_q;n#XFuvcNMEm1~>FiPtU<{m8e zs>UynqIVOTztcA#{!UK7DD8VYIuXi2IBosC>!GK6_d}bFWfvH_yQhWizjb}_$K@Yy za%3p!cSUu7|2tMClbm+<DpXbjFh~NmB=^<r*QTG@F~O@0X7i+LZv>gxb~Ye6V*nR% zI(>DdL*cJihDUZawjoZYct4!kdS?9Q2h>F|c$mtJNzup`Y2GjC=*-Hi9vSSLVQB(# zN^<|BD6UW}q+bjowUbF<&7A=$@uTkP9I2SKExdDIG>gtoC^S|7TYY-uYs(?j)qPKp zqOK97`70n0%v(5f>Z}O5Y!lSDSW@sZ63Ay(fdOnJDucVrdcI1xuF01!kF@1Yr&DgT z3aNK*W)%Py{(t4~xBn<DT62hlUBcvET(*xL*Bt6Lot+*qHW~!;tV%B8XV}8i+zb^| zjPR=Jj{4L6a>YGgl}@hjFA<&Ne?+xGI?CL?g*Ij%H>fsn#&~9;=cw_;+t2dma;f(U z@+phc*?ExyS31+VGn}4!Z;lD*yIs&IRk1HXv_e`5%81JCqcvwF;CH}`6_3;<@06?2 zIQ<{|JG8ccQ>qvlQmo*8gI@!G;J+#jxul(E>*B-^gpNT8ix=jX%C3hb3Lp`Vq@TSJ zQ^1;!p`L{_I6xNM3_*(KlX`=q+8_=dh-~TcPf6?Z$F@K$Jcw)S3xYDQ%5hk}XW?;f z`kw8?&dL4eS@f<eo?2HepFYq3XGa^|IsBTlT=9eI0|VUgZVTf}3xC(<Q13DrHaaSJ zKo~9c&TF7iR^^6TZ5yJKL7tiH%?;363bY_G<2;M2lRYy$9cXqK&l-A@z1Pv{92G-W zcLMXwz1Ul{Qu^ZG)P|O48JSb5wbhSu!y64sVxq3-;_w~kV(8SR=%F!^bjQj(7Li_k zc*1%jI_V%8tX@FT$#-&KWHHJ$F3vU8$k4~z5cFlJ{x^7+=EWKtdi(qelhVl|Cfr_> zl|>yDV57~LUeRGy%^nfHjgB$Z(&@jXdw8Fb`TRktvdXXAB!{y(WkIGvW^puw4n($G zvX{6W@JQow@V@)YveGEanh3lZ!+TT*v3l#*+uC!=mb^$4Ny?o_AI8zA>E~q@U7~YT zvB4(E!ym)mw+bRzi#8se1{B~nUy(BOp54|CGH9Hp0F$Ro!v-&|>d8VC!gIRVWkS1B zlk1tRS=-uaD%-`ZA)Vu?ou3$X!$?Q{SM7kB$uhZKYA0lub>;8_&UpM$?8!+tt7l`V zhaIQaVm?%a31i8asiC928`v&?<lX6@V*H@f)=}`lK%?`Pjl*2e{@tDDRm>_`x2u(P zLN-Pl+mChWF=J!{<g%h;Pg<u)GNrD?voAWVR~C6auk4y6B+KIe5U9stmgFe+i~X_r zp+s_-w%SS|Mylr3^V9m#S3ab2B+#cye{L3*Ar*?sA?bmRz{t}4!jqZ9%lqX8Duo>h zZcjS9{l)}tv{YV(|1_21xZGR{_cM?%C8oM5i+!_^4DfBf4i@a1^eB`H)kLL7t6=#< z?vV=@axIqMYcYFzwV7Jax3Kj5Bctblc0tcl_Cvy{vtjSpLnqbbP78(GPV>};26^h+ z1`e?;+Piit3%X>EY422S7bq&?CcE<-iUNU*<66EhMP;bW<8+SKJr)P3`JM8@)V%@S z5bhSsUuOu#LbzAj%Iw4viy2~Qmi!0?14J0D7^D`9w5-{TjM*%D#*D^6pUHqu&$2M^ z-Y)E<j}_)}#)$9Hi<EvZ+x%FYknpMGi?Bxl_GMPXM0m1(<mK+a03%;ib$Kq=^&H9< zDI}m$oFtFGR&*R$(7B^4Azvt)3_S`7l`}g%N%gL-i`udXb`8XT6Vj6I79|j#sSQG} z<VWTwte~4#cz20}<)!9p#{tVBo_7HUtOv#U+WG2I0QNa7GI>VoPD%WD@v(=5H>E%+ z^uZP(5@sMfs4x36U>WvFa+bXTBGAm>9b=Ok8-4f~qbZLewV^m9wQnPl+%TkAd3R%D zF>bLWDYl&P4g&)pV|EZMFKr-3xRIru-`VT0pq5ea!@Uw6Dc8@35sBTw<cQ<8!G}!) z@i~Z$$2}+I`UP%RaAE|;Hssd(kSK@(*gnkB@2hg;e0h2ND@UZ=r6^w|lk&ADMVav~ zw*P9*s>>vK1-$}lm;?wzzQ-Fwz-*T77U57*!m8u2lI<{PVur$nv=5P8MK=S^xWUGV zlXuSs(2?q1W*m$&b|rcHcu<m#7;U48_q*FWIJq0_ZHZS7yAU=s90on;&i&a-OWFH7 zI|Xapj?~FAcU<Y-DG==J?q<xxyR)4HeI8D?%geV5E7!8x?(SfJ*-1QCKqUyGq67p2 zVIm1sUICi;Wk}TCeUnuwT*ey~>ODD6^8^PD2y@{p_(~D`59A7-E}64c4+!8jlyC92 zPcQ$)i+o*p1A6oI8bc?)uU7}mOGfYvbdTsSU+6Lb^IFyUIs27zmDxJVUuG;rE@_#^ z;6)}=>?q*iY59xU*^Bx42gdOHvN>-SlkV)Cj=>P7;TZg42PHi3evoIdPiTy@!-t)v z@6L%vmL@I_I&8~wTmKYHw7kZfqa}n{9dWbqw@5W|cR8TgzSo||tmqi(t!VyV=Rcr% zkxQ;jTY8XN^Y`!c2aZj7axdE&vF(!`IXja_OHbuxlWA#!V4WcV<P6x|x7*5|Ka6oP zG?d_BLl^yIKJ4NI8MWQr_wD8fk!p7c2xPA4`oR7BgJfDZ9?xJvsI+=qpZfG*XX}B{ zi#Y6H_fvwx-xM!FaC@Q33bUZMA~e<B3~y}ZNW%O6WW9>P9}kPSs=~Uu*XE_TDN4E6 zI0|ufRTFQ+*(bl{l)d4-s~zMPC3lmP-5q1_&OcetiCh2Pfo#RWVqEHT(|r_?AKkgQ zoZQK!q{^1(1zB&lIDR>5iVJZ6S@h~ss*!)TKaNUw)lYlWNH>T`2g{G)n%45u`_7LR z=Ycr`L-*R9t+7!CVJ4v^aYQmJ6}#B?d$G!%jYt-feC^B1>JuX+Um*#DpfSAm?BlS! zQ;0aRgm-;(a(Y98zdtXbh`=Kx*Wvv=b7P3a8oY$xA|j67emjIwa4jggIhtHslCT|F zgXXp;6LWdb!hxE3*R9U7s#^<hw?(R+&3vnZAuY~B>7u1yE?ML+t)-=3`AFGc`cM1P zOXozFOJ~y4OJ^>NO6TA)qKxd>`@1eI+CiYHFE-LUDB0FC3mY1m740+E{CZ+^^w~rO z#v(iKL~Ov)Fj9R4)XErh0jc%4`_Al8Jf0EZjHw7p4Xz8uvjd$SQbIyQb3>iy5!l4) zF+UpZf@f@TFqV~_unk$bol}YrPvKnmg}X&U*+-m};DirSi`|i;4crAL704{3kNG9k zBckRdJm}a^;)x6_t|X0kgk<zYq-AM2-Hq0=l(Ic#=|k!dByvef$$i(NU_%+U)0)XV zexsr@;g375Eq%`}Z!1}pb&B`&VY42LB2~8yVu|q`A(5@o@#L<lC{{b3O$!PtqT(D9 zEG#2}kRkLG7*Z8+khpHEZdFkeXqB-Sd@{=daV^c%?Z^alW~IMxB6G|wgF5O)X8QVP zRwkg4baY)aHZZg7mJhSmDc-=!%Meo>i+3O&wDU5?6vmQ11<|4$9B2R`K;FODpwM)z zgF|{0Sb2YGe+<F|nLFH;fv1m9+t!PX19B;m`R#T@b1Upoe|9Dw6K`u485vPtbTk+V z^Kv%G{4x0NthI&LJacASrL_>8N^=G*7}=W}6xZ|*iv8OCU{y=~46^O({a?dE=^%53 z(uG9dl=^u~pU6k%-xyTm&k@h<L*`8~F#vK#l}5-tVPWkTxn%l{PBZxuA+`-VN@_}U zhwV%TnG!xaL}3)1p@fW5E}WsGgH~rLVWT&f$k?D7a$H~y_5^-cT4;?s>t>%rkXxU* zmXhmU{Q8fO`2rLXGDlxel+E)qDxUiqdEXfu-4_=WtFer7Y=7*3S&ahI=*0`t%>z@+ zBSD&8M*f;+M?8aVhZVR37nsf=n$AWZnn#Yf1_NI`-`4QW!PJNxcZTOz;WNil+yC#z z3^P5`3SJ(v%=mQXeg1-UE0%uL**V521qm-(NHRX9G&g2t5qTiyV`XL5K<`4&M0dvn zgx|8BESulHe*0FZY-wp22jO#3;uF)s(_t@V^T(@hM1aqO)6%TW2RUnwZwM=00xF5{ zJc%R8Z%KR2fn=Nt7boK&$3&eHi=%j_W5d6<Dut%2VRg{)a19RD+wo47QDj7q)bUxL zb>i8h2zu9QM~3mE&S`s1lWzw~mmi*axz|RXR3EEl?%w=7P?^lE)-+PPJ=fTrm38^q zu;(2#y=Og+;lcOZ%VRkGHM<y|{l~R0y8jA3I!!t6<=7f)AMLzI1HkG50e~h3$c}ND zqsxim0=8UFTulLK<l$kd%QxfaM}*fBNZ4{c^nL-{YbfO6Onbbka^7<73~jl7S#AoJ z4W4KU$=CDdw(-}Saq7*yRBy(Yx2nPQR(@S?UH7G-3zl%b4QBk$v;_+K1*m+CLeAI1 zg2J5pluaq&CZ5l4p*2LPpGWnM*mr(w#S!H`Bn(6Vz)y$8q+@z+Jm6mC8Egu{P7GFy z^&oOR*fTQF1=!jcI9bVtrzg97W^x$oC;9a~*5?2yIDUzphbIHb0Z!cI1O!e=76dH_ z-DW}0B@22Vwcz9p-*xH|SWm;t01QWK@CpX;E4+$dt09kEt{=3YL1*a&_j}MEj?UNs zW4-G6_*MZypP_T6TD_eu#@VsHwy4lre6KJ>OGopuRH2Z3IKq|`eDF80Q<+3Q5?lZC zUz+CdkS_MoQuWj;_^X=DP*k6_!K}K_wz{Ef^fp{a0ynULn@D02OQq#jWNcbOCYk76 zltmxa=8AVg09nEUl32pBy4HqI;5rhxfd$+|5{p=BT0R4w!djIFwUO+Bi5Dk^1VCZ! z!q6&FieHbW+1o=86NN^V-~iYJFRG!S2DR7%pWYfNNS*Hf@2%S(bNznFICM@#eHDHG z#5og*Prn@+2<z4YL)`gx---lm-~i~grL)(r0RWC11NZ^jQT_><QZ200>f4b1Kj>+9 zcc2Bxa5Wh0?R^#Y8Gz!@agOR4-79Ivq#Mh7Aocn*?)PIM!@M@q!;_p1M)q%OO)V)* zh2SAWi<|7p2B4lf{y*Y6?dE5@!(0|(+u2(N&?GJ!z+#*kWB`XI*f<Bg&;`grue)a1 z2w2!~MSEn`QW_$uH-<j1f`tvowuAaVS2~exz0vDqv%7<I10YU&0dWA7;C8{SPy++8 zn(9zkQeAF<*?x2M15Ly;@Pz=)N@-7!M;P#<X94J43^vn*8h{~aMWcH{I|c@(`g9LY zK{^6P1;StC0Ki{x1^9z6OaNv;C|9D`EFFjLk`^L)0j36}Nb~|c-J}zY3*E~ty(I+T zpgP2<_6=eYq5)>Q&v?kcLpf$K7pY;uM6{O(P^si5Fie>yiW{JD#!E}Qv~x%xt)-o1 z02hnuxVr?vP)tzs4h2KU?L4$3v>to8I+q6{G~wAS`t9S_@I3N=6X1ywMww9<iiYhf ze4^{?B`t1&Rf$w&XCDZ|?uL;r$tFPUdOeG#K{|H3T8c(MtZIVu4^@w1nMRB>fX^;8 z#1aIf?5FxAVY*3)qflrONs%TBhk@;NZZNH`cy12Ks^EE=3uB5XVNqrxv_!)+k3`qk zOIq9lt0O}5`vEjlG(a0_*R?_?jT{8MZY`t1Tp&skw0a+ceHmDvVF|}`nv*kTGy}Ba z1}n^;xgWu!7X!ei{u>T$dVl@Xi2)z`++7di1U-lT%U<a^&%K9n{H~%`ipKFv_%uF; z|3UeS|D*Wj;@?xV)CKD2QcuaZOWrC`UEh^naok>d*RfL8UiMPi+nyIZi}Y6ax$?}j zdVHT0Db=w>PIa~=%uBh^itjwu>V8$!?LEKhhrtgQKXRWMKMjAHcc(@aKX({zoHVbr zv%apkzGL%S^inpvVl}LX|8Mo%`uF_5UrPMFqSsdH{}lc?q^PGTRQyLNUg`60tKE#< zRl8s9{=5gwWqXSD5chEQ+*1xxCMwq|KUIlSS=-Cm``=$ye+}+a-N)Y7sVc4dE7iOE zkMDnbK>on{YQAbwY8176wMsRvTA$h_wK=s%YH!p9>dP8?HO^={YBDr0YCh2Xtd*mU z)-lm>(DBxZ&>`#4b&7Qwbf$Feb^UY+x_P=BUB2#s?q%J1-3`4z^f*05y?uJldU1Lg zdWCxRdL4SN_1@KHWM<_iHx*gt{X9-kLp%M9a-Vhb2p^I=wCNDx5c5#$p@Bnp42%tY z4Ne&>8vJYcr{N((J41rul;MKmGs7Q7NTWg{qEV8O*f`I4<nWfm#}3~-{LMti#KY9V z6ldCNhB9+DJ7Fd;duQ%xo@IW+Lf^vC0`i1vZjWAKO)$$M>lJv`E8cR!WwTu!rS`Y4 zzu>k+TCTIyv$U}Ew2ZV&x9qZfWckYSljTn<X)A-(J}W&db1O$HFDsl?iWS59ptZeq zfOWU^ZyR+RoDI)r#O9@~y)E6gz_!$(`UxGjePH{;1)io^N)J6muOn}Xf6bF>;^Di5 zpMAahYHO93Z){Ay(shSErk_7b2{5_<3l^+{JPrUqFSTpD86Y}c)&#T&JFX4*?*UB$ ztwB6%2#%NC0sv4tR0z*>gc)rksZz5FB?pL(mKuR3qs~e{K3pKtPg>noA);oq!3fFg zYHHC9B1or3a1S2QObs(JR~I<=#X4*pI!tj!*{y86JN8tw7R&y~F>Z3dg^q6c4eMd0 zNX3HinZEHaqc)#iVw^}Ht9h;nkE#p32Z?a){$R<tzYClboQyodFjKma9>Wa7YM2n# zqs(TJH)GEKtxSc_u~uE^D|;oEf(A5;1MX{OXpemcblF8KR!+on2w^pl<6vlk{wg-d z6bp<($9g^KaAR`1M^;Ma{8ihCm=U}Y*^$t(Eep2C-kdnD7I1fw|Jc2aOCtJUO!rTp zUDv)_KCY~4Y_@5|#>RRDFY2{!$zfUCG6fmkr!A_YgD*NwGOe)Rqa<_G(M~)532Ba! z);E{gIm?^+a$KP`OY6z7G?&zK^bKr4C2grJz+Xf8muX(Tib{9{%K7s7CN1|luSgJL z^!^5;B_I%HZuZB3<W1_<3=h2Uzzu@kLi!PdNlW4l`tfyy`YfdPixCFx3NveJ-`y@J z*Q@H%>_xk9vy&V*GuqAFcJ6_jZZkHg$PGfjR=xee`LXb*?NCoCWaLc}6<6`{{5(dP zAeFumN8(h~js`*x#!pn34#^NuksaTsRyG`q0A3E4t&iyXamFOD92m;PfV<s)O&{W# z`t5i#_+T-2F{X!ME%*$cA?8S-jC!#&kL4n%S_5yS++kcqa3?x6_5si*;;TRNGOC8e zc?|c$6NQ<{U!OZUQWujtr~;MnFf@+u896zbKXYlloQh>Ro~OVqV29?XDQKq1EkBx- zA)(dki2xY;riuDg^NGVHL9UqAg?L5_3;$xdZ%0HAh3^BfEKME`?pJU*M6@%o+5-X0 zm#;;oAmh!_oL(Ii_$v}WE*Z0My9~xOG{Z=u0E@XmC#xV(5s!Oe$IV!>cA4&~Dz3Gq zCihDr{u+U*RV){uecMo=5W~Y~5>&Tn<M2$^Y$U?y0GrU(XB6n7pICygemWyg&)#bP z#5fSfF7$XJ*~s-nGi4V>5-WM|>)~?z5LJFMn7ZHLBfN1(Qz_ozP=G^vI^rY;-r6IQ zKC#D~A?nodtCm%OqiV1AMiG~yN39y=iFv3;yH^1jRTN1o&R!Np62@!QO9aPg${RUl z3LNtCzNKy0^`KMH!#m#69?-$kD0&e<RiO5%S*{rdqv-mGDymq6q&6IHtrye<12Q$! zRC*qn@;|C&w4D6sx%hJ}sPEq`U}-qomFYPru6saN(CtNl9XdG<&t0>dD`N|Z*)%p! zC-Fet3?6WHq-b;KAZAAhphtXwBGryyq<=Oww@*`ds(!hRhMRkf1Vp$(I~*Syy0_SC zy#1msF{~sE^`$pGRkbT;(^-Qn(a9J#({rjhW!G?^AI1W)j&X!1-?ts8hSir)@?@E~ z4}5dH!{+y`4C~UQz~VnGmb*AL-zGRgF((e(sb*pSG|{a40{B~WA5d$@bF~q*V1Qg7 zRHclVL;`j;dmC+Ork11lNuqFfbl!Ko+dNvOck_D`7}I}mVSAqEe|<WbO|h<3%PP~- zA-tr=l?TwTYm~6nO+S9}<C`A@KuPFN;LcIphYZTiVI9+uPT=er!-^`YtdqjdI*cI< zQ-GuI{;OYLNAnhiy0oJ*WH8o;w3-;~-Pd(ZC0<k`mgyol>}Y|V5<f%`R2rQb3|{mn zdzNt~*+zd&V)@<bez|A5fy#dLr)2Yi1lk)?z;EC}zm4|J<S&G=X?%imqCV*hY=$jS zkRwdir_>6n%@kIhby5xEgk!d^5T=SGz$tQbLXzcw9`7_)MOHOR(i|NsdcfGX<4-}G z0>k}*%rDN_l)77%#%^=d<#8Sebc&oeXbB<RjxHcP{DgC?6-so3n1oy?N~8ShO&a_C zb+>{p8+it5AY@!f%LUz_CGr%vp+5Cq?oL4Oyx9=|ufJ}YgY7dxxxu2*jvNRIP9gW8 z2*@DFzYFu<RQ$7T_Vf4wKlHVTkk1#;2O8W%A(W+qf5VX1rB=Ss`5g91eH8<yS&h1C zf+-3L(b+U-&*F06HW4QO5UORw8j5dYPWtx)`YManUiu)j$M))Qx%7Nm9K?BQmS6Hn z1k6b2(J%<1p~Yhl@eQc<YSj-Z3Q?~^g1C%i&<zop8Kx?+>CdfYT!<Fs$IO4s^y(N) zG4>MCyZ0Q(unXE&Gd}3#6L?E+Psd2`eLvpbw=OocM3;O<hVkuF@6*R%CqpTk5U*w7 z#y?p8<`%dPnGgF*<8@%tBf$0YPYRWCu1k`%nIkC~8C)kY0zxdM!2H<WDghi7E1;60 zs~aKydSBTO>(fy_@VuFDZT1WBBl~$gdVgdP;8zfxU$LS2vet)Hu50Z4dJAL81%HL3 z)mn9PTdU^Ajp{ZJ>Ju^$cvued%EdVelY+5#EiM363b-2%Tq)-H#tN^R+(_KgYib=- z<to7Lj~b?0%#F+)t?@;n)#Ns!-#j;{Zzcx{=~4k`fi^=M%Nu!2nXCA?B1l?ToVwqy z^Ln`{Ht`bACd+-hF-R%$7zQi<XFY?sI-0tFMOdrq74H1O3`g3dO<+Cy1F<p>byXrp zcR+n4E6C6SGHU8ql*wb@09X7;%PR(wM9dNSuV*cLP3R!s;Ck_6`#M#izMnZly>}#B z61OdFch0b#O@M6#?pHrLMxN50hDubYzq`<BzH_nM9hRE3(XWA$(k#O!xqPP;=&$LC zeR3j#Q34b=;``M5=kJrjCB?^<EpDEl{%b^wb4jPBy@j6f?q`TQ5?-9|TNXAJklqs+ zT{qXaGQ6Q40gv&9hYOwnK*81NhGO9z&YUD(hv_0Y-)O9oylX*4Biwt>4_$8Tu6kh- z$5r){;Ne6^^Av6+9D+%KIwPfpTYSwjsgmYdy?p(Gs*+2L7P$-k=QXsHW~DW_O6!b3 z5B43ebj2f}<q|(bAP9jT=~Okor+XxKlkwN=KE2`!AB~ei_vg-pPNsxc;(^t~Y+@2U z-giSJur@4cqCN#72SO$pdf~K*kz2She}XwbwFV?S7BlZ&^;>C+w-$G7t)80U26-85 zE#|C}qqR*5n%3nQ{v{3R#J1C*CWC*806_`#+4a05YjKYA8H}};5(eR<#e^tw&v+Z- zoQ3*|YFW9aUDzvGGz)JGB;HF@F^1gx`=AFx0INdsGFX%ax6~Yk9K{SR%9_8NPEoM; zjn#$_eS%s5Q8>sA1*U{^cKdMNH7tWCLNkyF^nsT5Vtw(-{+-fY$)r8HEh9r_fz7aR zpo@>)SKZMB^Y!r|@kU^?Dc7-*m`v?nWw{?NFeyViGWbct5eZ^QT5DD6Ijsp#1wh}T zvSQ@l9)Lgu0+q1UP_U=X5GU!3OX+f*%F(ue#M+W!u-F;GPTY+VV(AHSv7l$LPQ(6o z4tt1OW^ZzAOPbK7hQnZ>z#_l(I&~CxPzsC`y)G}qs360OLFB(w!6!iww_f<}C)9$o zQH7f*7>~@Kh;LvL4c?ED#D9Jel_}3@{@L==>)K~CS;j*6DMg1@EIxSCi3;&SrI|3n z9k73+k%Ua_UNjStJNpSV1v%#Rq;?e@*a)79k;$tt>_%X=!hnkjK0H`(%KdJK$cspZ zpE7EidoSV<BChdfkhu8S7>224IC_w2=pkL`D2Bt7jC)!s?6OfngKY3<K+l@gW=d~d z9}G<}ykcKhtMNjbM@sE5A|$bb2#NYNS%7Ywr`{V$NCkQ$+@yu{v%e3RqNS)k>H;z4 z&#e<6=r#7<KSF{$u=~L@9Tma8n`$LAzZxo`9$!Q>Bf1IyG{FwMo1+&H+ue|dvh6Oz z0PkL8x~Kf=yOGwwAPiM-=$I7-vu5$r5JG5D5Gj~&|B`4*%mb&^>d0ukFxWQ<_)R0a z;Iws_zTLloh5(Eho<-U!GUvir#PxNV%i_Dh@bgLq|2-F6PxrCF(^%Q`Q$mcCjAPer z+?}L<-!&+^8*r8p#7YKVYP1hXp@lW#+ZF*2<e^nZfZ3)fc44lp#o^nnW(_sOFZt-G zzb$uk;^2X_xd~dIYm%@2p>;_|UCqlCeX;lB^<dh5I=DZK^W2zxfyn&iRliiAS?W{t z(w_!3q23d{`_*T{@?AkYk6gT8^hc0qCQ~m*(4S>2ySicM7PsESnXNoGPK8NWzfCz2 z6Pj{}Kfh9Xz~LEY9y2ved=#(utZa5{?(WZIc8=<`7g6wzo$)3kfK63@uxSFg=o8>? z`|Deg&%CLA0$|Np&o2h)az~Noo?POuQ)&~(`a2dXN;X>k@8C8ccgB=!@1oUFcwBE) z?ahcTye+iHzOqsF$d+(wAf3#GxhSzuB}~EhM@O|(Be~TFH2MiY24VWZ$`mhAIiAk- zC&fCsIrY9ENwjDSd2fz($q{GK;0w7Ioc3BH+x(N6q}3$L@_K7a<`Z$z#eRoJNlwrq zaG2$?bN;p0*kZ?*=KDt5&U}8t*g&d$gVRUh4OvASiQ1YQD*t+7O<vtvC)LWSDuID- zsu4lgtJSpxUMnQ*YFbjjmkP3(?!L>DNcv=^w|0HrDi|D2{&wr(tYpO&QFCJ~ToVZl zJ>k1r)6$Uf36P&9pq1imqhoS`B8cxNS02&zGkWgskkx9#1Fp(9O>fgCxLx|;Zp}Vd z2GVU%5T<=U6U9|M_Qh|6e*RY2j7Q91l>KW6PuT=z1^QILJmSzX3=?4Cv<kVRh&{<4 z?z%WNHAP=SVHGCVQPIW5^zS|rdq>WkYIC^6#ubXbL~$z4*q5J*^`r7_<wCUIerJA` z8-`kP1TjctB9+U0^AiFV#fCuQ87hDxt#noMUDJ=ZQAyrjj>aL4f-9{&(e!)^LK)|- zPC(+UcdA4)w_LfEf@w1>(HUiceGsHORQ0=t)^yYihkS;tyAH}5pLc4OWtszLOu9gg zLXCu(x@rQ>xWJx&(g%K-2?G09vIwuPSntfK(bt+SDPh5K+7eBRcCH8YsZ}ztqQO38 zQH-@idB#1_1CGRW%`#1`0`7O9R4w&IMAIibHQ;m8N)rd+8J^2Hj-tK%WdTtj^exs! z<Jjp5!gd8BH#Lf-1m+*ugVz04Wf^wE0V923Z!Vt`W@`*(xF`McrgA@gf+}}YJS-k2 z`dh5@lLOnwz)vwq(!_Fpkh_9m*=D9tYf}>^*`;g$8*X&dZ1Xuvqd_JP+g%wMXPl?B zA^ROUJ9<{xPdf)+3|&&%m)!<Man6a@2LhXJf>>K6hS(7LtSzR6*%-Y@&Q0j)!U0y| zx<rT1UXE`h?C~yIv8@*V606GSN`5Uo-l2<TbfZ|}n#QLOOB-Q~L^~A(S-d>W-*Slb z;!!@(z=crk?+?g!`E+UU$3p>ZQtH|&=k8Kn1T~L!g$YZvVq0gUDz=kJ!#kATClHz& z(l6L9UyKr+vDHm&Jbk*@xS)#|6Q!qQ`gQRB7^Zv~S_m~j30t~Z_J&S5xDe)7BIMyq zXN<75nIV=cREvFSj0rd4=`f01k!bsvo&!MUVtF>1L*v|yMS=7V<KO2ma5omb7q-~c zg}5OjuW!KkX-i&D_L-Af<u3Rxn4>*+TM(I*RoRGMANOS>n5*9`2nhwFvV)UQOz|8p zz7j{?d>|Xe$L=#>Dp!ZQ{7LQ=g(8@hEA>do{>oD=T1)Bx%|qagjr#{yTU*Y^CpFfO z8ygd_58l@QLE;rXqRkMTWaA}{%7YCBSLrC^nQ=ya@pT{UG0JAJwaR(16?f2KdEt1Y z?-eJUw^m%Ay%>nkmXHwhcLlOyZiIMd(}2V~!AO$|fCuUc<9Cg}pEf9?jVESKG#wm| zVBMQ+0Xf;&nn;hsvuY`s(fKe98B%IjYDNG-i#fSV(@C9nHPvIB0Al<P)+r4bnqkCC z)pWmVY^13Yi&X2Qo}<&Sv}R256yXJUoi5H7%;!5s+Q+d}ArULv{uxAiWphLw(I%E$ zq9B+@V&)(pEfKwnSl|a&n+%p80QGM0)fM0mq!jx~)A`%eZQEDgK)zTGOW-YS(r3YJ z#tP`8l2n{0<^x}MvOdDcxn>jK%DWa$EKP-@9pXaR(fjf7^s9>bxL7a>-J^Pjbw$gv zY`dCv24|NKn3svuDMEJ`45RpV9+V*x)4G|9VLoEfqs2_y`G$vZW4XlwOMQjn?NYeN z*=zj|$BJRgQz&;(4%-aVb!w%jlZ-VfH8l$8o7?@f;5Ssj38@{YT6vbc$#@*(-!n+@ z({!usw>e_WxfdtZcGX>Vx0U);E*i+5nfT8zmS+5v4azO<xM=~g+`m#(5YT}O(?xAN zEL$tEgo`*pPx%m(p;d01*QlTSK4Uw^-JI#QcHsiefG2AJ(3n$`$h2cal(>8KDH-a{ zD!M@sQwj{5M=YDEv)8JTPJED>y5xBPh2ExvrNPM#?K*@n%?*k*S04z48tVh<`Y7yO zS9M&_&nxL$9F)s@^rc`)l@7XBsI={ICwxO=+G%(Dl~`{p$iWcE&F3*xKgXtVsv!AM z6Z1K`wRgHem7Hyd_cp=0A2JbcgI&QKdK;FjdZ#j~MXhE@wyE*aca31z#;&y~gSXQ~ zuD^SdMTqcc8{i08gXN}(UlV`>rcZW5Wgnkddr#X$WNrq7LRg;ea~_`+qxV5W0o@%` zntgt0ltH5}M)-g&zI=M?CsetDiz&lIs85S1t$j@afSY2sfVwp_ZNf_Dy!B}&BFW#2 znqOjK7))N*M4(pKG3G?^kv?cJ8c|;^4N=cE{#z^2Xi6qB>pxN>zVkGLP99YYzmI_q zbfrLIqbQOaZU(^u1Sz};6S}mx0Q=$Clv6yx0bPmLC{4|p5;G=5@+3*nTZlH})Jfx| zA4K&4^Q>2$E})EaEQ><;8=jA|C`<(rVVAq=&yFT8h+<E4+<tM7I)lcXhdV89bKllf zh-|FQi`)-DdL-z@Dm@L!2#(t}eV9`pmv$rqtr6)n!N@o_EyP*;?GTq>(M38qXbO+w zgBHsQRt;t1(qo#+wizCtWkT7c*Xs#TBm(<WZ`p35;x3DOzt|%b%U==O3Ly$0ASZ*P zjQ^Ny=j<|C-tBUFA&c1^Wv@7h&^$|q-OK|F^Lr%%Z;pVYsa~7o96)Pz=Bm0YNIT!F zu<{u&$xsScyuCxIH<_ilvmMVzW)D)8llvTNCqjQS{Ep?hpnB&Dj>IJ)lCF9@A<lXM znhE^_S&zg(yXlO_T|m!34jp8&PZ!n>+ZqrQNz}q%V5-xd{u_OJcVy4gPP^e@6^1s> zZ<raf?puot4_QmDeXgwk=}{zWRbXo;u(VeU%)K2TVJ~!EDLGGG#gD0sG0zoM>k6Ug z-Me|39yLevtHMD^nH!_4E{zt8YbQFG*=GZ<SII2-J(tybR6I+Z>JA|c)c;zR#DX0` zEj`RjS9@{tNviQyj<GY8Jq(&2K=rDu+g;iDmD3AhY#K0$NSho-yKuDuTONs-vw&eA z^r#L~VPe{zw7|WsLYkR;V(eMAF=<-+ILZn^9m#S7g}XIS{Cu#vZfro+s;?<l6&-V) zqFE=?cpgy6$__zE%Z$ofYAX<2R_6oI!9S?``S72^LL>Fh>a2@niT7ocf`{P=m3L=r zFNcu9G5QTh`fjPB=DcP@DRpJTO0siJk17}I)2HJr*R>L@_s;hf<IFuCZjO<#fPdo2 znvQ-uQ^^A3-Rv>&2C=Dx>4bWfk@IS5Vq1P7tdLaK@Lnm{Y2|`MSF7Pk7&(jN0(_L> z-R9{Sk3FGYt?dy!nESknMQ7>JV;HPzykfVIY<MPvhDzq<>c`!H9&UFvJPMG*BZ~~D z%q~rR_m3s}G~2HBk;zsDwQl_Jce{3R>3Q+y7A};FCvi9|O>Dd>pIHHNay&f}!6cYY zXLSd+_S{F)*-?3MBZO7LzfJv%yvN5TD{D0^w!@XnrI*(10>N)n@@loBA?tIl&k0hn z8~(<!YsOUV{N|KHX-PVH($Vuj%nnZ&^TIpHExTrVzhNe_rwM8jsZe9s7C5CJA1_sP zH0pyxx}>K_Zl<8aKdIO6Wp%qhIqW1ibmvp~5FlUR7@X2Ieiz-sWadwc>|Qe*of7t0 zf*`|QDbg}T(Pl1HXXlH=Q-=(Ec<5u7Sejflwil+8ah%&03XldqGok0cR5UFU!dV-; zoMLTC=-K7+0reCirv3QI?mlI1^Y~Bn!3_sEKT8G*Q{?+3L0%+Jp+!~oB2#;JHA&&s zcKATy&hYYr5<6^0Kr_<EX(j=JGdHj2LIL8swC*r@vvK(6uh=kFLdbg$DJ2N>ct-Un z-l&2bNb4ZVRe>tFO}I$ptD7$Ovc<JoIW#2)ddJ8@wIqY(`F0$lzJ~Ff1|jwecxYx! zCQ^b&K-PZCtmM0w#t!~o0qa$Jab!oQ4*m1qttsy}bBD@KMlolRZ2p|(Dcyq?3|qcj zaG)xD5ncbORY}u~8a*8zP#<}S_82-GBgPRYYYzGv-#xB}#gHZ~w?i{xvqjLgu}mgk zDU$;|j$2+}!#k~eeC?+|jQvozL*%ex89vnw)B*AwIJXa^cm6|7A2<(29fo??;b&#R z5qdI}-mjoGqvPd1QdBhUTS;6A`mqce6EDz6U~aYzt8S=H!U(~6(n2_GP-9x!7pZEY z8T|0zPWaO=)#kyfUTV?z_6x^PMW9M|3p2q?h&af#SAkM@%Bi?d?D54(wPcz9J-inA zWYd7-M{OL)`eN4z1*(*65mX5^j2W1~@|09McjhWtVInQz5ulU>ufeyEU<bR_&1=@I zKIJwbu#e@KO!WgNlr<q~e`0m)NdGWBr5(FzRLr550MEQTNr5<UA;!0@C-jKQc-tDK zQJW>Gmk#U9Gc?2Ra#}V~Ska#?_%>OZj1}4O#n3mObxAx<=|YC<Q7-k6I%cc>qUde+ z089quBlyiz32rq0wGTJkXvX{(TF|>pMg|a2GD6`9_^0A9psJAe(k{9*GObgXgBRd@ z{}OE`ZH(@9hzMg*Nf`v!N7<B{M^j(8sYSEb-_iYzKrbYx`t%gRFABYlclq4pgX9h@ z&jj`h(6we6mzn0v!`x)BAgHa?Y-A2jZpfoGX|C^|k~7BL5-FmV&Y~&@PRz^EX2z|= z35!;Z!8_z&;t<X%ayq{v!saD8$I7WTHm)LdN`?YwFrLIY!<8Efm`0l>GzLhWL7c^c zsOI8p?U0J&F0n<EnW|5#Asx3Ea9c#e46kn)h8BvGkE!ty1{0m2!I$|MKtI)jEi-0= z1-I&!(2V$gRK2=RBhoaeqAhn<+Tq<~OA;`d(t`KInb=7h`<v0roQ|VrrfhZ;0Bt*U zkvd%AZc{MJ0Au!~wt#CI<YzilFH~>+Kw!Ldf1^3wP29D4sbOsn$&A}QvnMr)W(xxJ zegJfQutW7aizIaw)#`ow-?DwOlH5sqdb8Da-Sx<huh@CvAO>z#o1aIQ2V5m+Ua&j3 zYQHDyE@$>>F^123%vu$ML)I}1-p4x&_7uhw>KBJD-Z>ZncVBz7O*{8=XayIMLZ*&8 z`P6tYAD1h;iakpub$L{GE3RHCk{c@iKwtiE8$}>@uXeO1&dADae*1&Ag7>*3%_t}E ziv)MNlp<CH1B)i0pCw#gm7Y#hjP5o5lR0<iuHks7!UBC3C26wmXwRQ?gU5(dK4+)~ zZ(CFoI1K-@BwC)4ZCU>6$4$y(c5pH1Un^%!!pTO5YOg8hAJ<EUE9z92qO?u>RlQn* z((0D$?FJT*!x@4PD}!#-1`NlMnmu6Nz5hMFe_i==8x42dGqvdMYu~Cw<^Eh3F8V*~ z8b*2-o9T~ZlLwB<I8AZ7cC4tsD_EerAn1q$E~aW6)M-<U`S(MwC=l3SS@u0*5>NyC zzy@6q8uSXn&{q*_+kRaHo`y45HOqO<+Q_{xOWBW=@1Lddd-o;j9$L_m8x0s6oga@a zTT-N1tA!F0Tims08cu1ocgV=YylsE=lG;Iaf_>lXFUD+T3!addj*9t9iWI=G70XUw ztJ3G#s?5~cMMjLQe^e+@c)!cU^`T{p-Q`#V=J^P2ZIjKMc<OTet30INq%c<L88*vJ zPdcc2Zs2GmyhNTE(bby>vV&i(fk+f9kO&w3coww#7_u~xPTw0${QLZGZQ_TtCDkgu zYC%2G6czLm-oFa}kc#C)D;#?oro4BX<GrbRDJJma?L=~|^o||N<?_8Xk|uuRy72Q0 z*{JWw8@xxvN~<}>GCjP65yog81XT-8a&b3PC)cmA?#$rbR<I^3;|PHezf2Se%`o|D zs8%K}|5oMO^%eL(@xZ{UV^?#&L(0os-*RyTj47wtZG7|CgNBT~k%AtWCg2nW>gpkK zHE=k^mx?Q(ji_rn-F!h`HO9IufihvTE8=38Ts-C*!Y|+vQa9`L#eGw~%V=!PW4+0+ z1i<4Y$0|H5Z1Kc1_Gh@8(BODy|9jKCSm8ST$yT%L6AgGqyAQmVMMddOEMTJ)(1!R_ z4*p+R_}ebjq<TcRX)WIE@jN({k3kMI`8u(D4DuOA^Lqo_(d=Y?xK(5dWqb3J$1$7` zaa<zoA42!+clUK$z6j~v+|zZdB!-g#$qv9JI3nvTpCA^^gy6e{z~bC+KLFa9_39qO z6|r|&uS=?#>ndbjtl)nXy@>7dVxkXFiagE0(tlakat>%38h2GJL)VeHs2Nt{>T`*7 zCGg|DWuHjlvU^nUJ`5ZA7xI((T#n!(e(;sF5!O@;yqjSsb>tpW27j4JL>>41lD?zb z@sJBc>NeJzsi~FvrO~4<a7_~Ncc+WomQ!N|1Td>LK|#H%bh`Xg5FM&fozd#)9o*{E zP(}+P4<kbX@wU`wD0bKZZKOq#h3XwzlEDmB8#K)gv6VKWmn?O*?JP7;Ox;_{ghw3a z30Or&6l#yp@J``qoYESKb?a?{qqx#r%dmJ%`@onJ{Jzi1_&jCrld-2w6dihH^UR@C z56<`ux-ObBAaR~uVIFb|1gCXw{`!m-HD+8nr`wmiEh|q#?&UZ)*xH~`94^;ohbLh$ zj)?47B#+l<5}$p8TFC}Veec)&XI9L5_i9#RQts92)bE#Z^U`J02(L6XpstL4{Vn@1 zoMc3hLG<PG)}ZSow;xrk|CAqP<(OTfXZ_TRj`|>4DX;-<y(tX`<_1EUl{Q{n>{*$h z)Lg*V?ZVG*(h)oEFFVKFglmDgJ{w${Slj=h*inm773wgsqUEeBtRUwcY#AFJ83iTF zuyc--CZtlt>k_sdMZt=CMlP+7>+5H_K-J0hm;7qf%VOHb2qFZdZ;}nH#lAVSOc9za z&Ok{TilH=vbcs#xd9Fx{j{-o1Sgl#+P;0VhM#%d^Q9z}RgQod?c=V4?x@N?-zn@+@ zidRviyT*xSMJyMaCP)dw20B;4>5fh=_FcGn_bY-q@I)LjHnLjD^L1)hXrGR~L0h?X zD<XG#i+P*$w4ypAc^FM+5@Oipx<yVHqs>rA5v>;7@Lq!ypSc5ubkR}!NIc*OUZG;F zMv^-UJmu7NvXF1%+r=+?(v-Su4ldg})vy$X??3TW7^l=?y7NJ7b{44R9QSFkh=w&Q zEP0EL2B?aO*wSm;3idGwak%aj)C*UuRTOQ?n8v2y5gD^Tea5x)=E-iGR>aT`|3;)t z1rvK@#gNm!Op@N;<^og0+P?WfeVxJtZCoGMYa)97c3fkACm*u{l~0{9Un8{%C1^}b zZUVSup4FO0OZ>f!2R*PZ2>*671PJv1H>VMMnoN?=nH9BNOe2v8qfTKnUr}lkE%~V_ zB@_y@ZMi(s>+~Glb_IK07A|V2*RkP(e-+04m4R4vQ!5ChLkO;DxT9)(*}Cn@HSXH- zqvpvN&RPwG03nz&$*&2SXZ3)%*<;n(Lip=$!-xmbHUN3}&?h?%mOh4Bm#&C~`;+pu z&Udvl5Jw~&E_QsspsB{4Ap=_)B^rib7&fnfjE4`BQAC#eCP6v^bNy1l6jz?<!Mp@% zzb9mZ)ohn6;8hrZ@;X1NkTyEj%T)~;tr4we9EXSd)BR1Vy3X!Ob@d&>w#u>em|WhN zew`K_Q71c`If~0`$E|T%+6Z^h_Q+X|Lt|h+enDI%D7|hbO4EJ1l2C}yo4kZ!ZXiU| z5_>=%?mLLA4I0r+DhfUSI6_xa69)t(rz^LniwcIXeA4Xpj>KqiR4IlolbX6wX~j`+ zGg1-T+hL9t+Wz3)p%TBdf6*?6`<<T2C#)EbxEtBT<p}OMb9YWkt}C~S{~FG_(xlko zS^FnqN)&@M%W75)!z9>PEU=*!(^w_yYZS^^mIfpPnO)r};ll|g+=b=AF!mA$pHhD{ z*n!H>rr>613OW6LrQp}YD}Axa8)w62io7%9o}I@;ZC{yk6EXdGqmUyAR^kZLAxdye z(clG*6*ESaj8Ry}r1%l_zDIOfM$W`&O9)|D5Z=G}QV-Y$*CCQ$9x^jw7nO48`~^?$ zorp`iXh1KoV>=sE84QuIL;g#;aE|95(~h{acD1(67q0O~XjxT0wXNY#>CAx}y~zz* z2f5*M_iEo!u;hO=+;L%b!f0OL&)e<eccEq1Ls!FNLVSBIGjG7M6cnrh`P>QKt1XyL zC90G`D@W9kG#(2V4vsDNj@7!Tt3D(cpbHBaU;-#&m4h;RZ)Bjs3fSX|_S*XwZM4rU zRH&dTljklH3P;=L7oDhzEgacrtAs3KpImg*9$O#@qwv0w_8)kHhqEln%0VG9E?kmh z5>RK`q6u`+`P+d@PG_VV(uKN+GEKURVVQq-*2*~_+^gD+l{W9-lCF{zo)M=OHU!#& z7+4`{prPKhN>1;+%~s-gJT8{hb(n$_ooe#5okBWA6EsxukG6tu+gTh5s8vRAViH<S z2@En^eXO3XOkwrCvx$r>m~&ZYw`E2$?pF47A+G}T<3uudZ?<D!T2n@G>yP0RJz&Yf zC$KX9pi%zf_;A3UsbknJa5#J;W2;>1iJ5qjtqZCa#lZESjrpg45{^f7ISG#`>20ss zF(UGAH1+>Pe%5dGo?immlHhZ6JyAL~b9*;R98&uUOnx(})04}=q25%%@}{7|loHUt z-}qk0pv@Z%426v-?gi6nZjpmFV)C_KOY4G}Wunk?j_MIuqbyYA`>nEex;7I9^f5D% zr!h0Z&i)>S!vE8Q##97hpVn<`*OJdr3YCYEfrsY|lpC0|iuhYe16I@(Q7!c!ECoCZ zc7U(#JyoiQuohvf4o7MifKydMHXWsp;U$R4V72#apMvJ=lWb~#jwjFq0~DP%R4Jx7 zckI-NNXzo6=b=VHcRaftmj^c*qP1*PYvd)WTB7~Y=5~A*Y#SrD6O@Dq1zK)?e-S%{ zT%qFNMCQkQ+_^f4;u+Sb%@%6M4#cT?i~=>0kCYJaO<$4%gS?RCo67zOSQj)|Et$DZ zw|kNIr{JNBf~)E;x683m^myA_C*|&qfhB7+T+6=%%_Q1_ekI)_X0lb^&IQz{Q=CXY zPPJl(Y#%R<p6co7EqOkYEb*kNgy1B+Bwkou4Tqb}u#LB5q%H4*J;lAZjhNrv)L)RZ zdY;1CeUj+1OVX^D%D|YUaUkTc{aIL+{zm?C{{F2Jc)vHkIK{;6|AO;~Ib0sfK%uj( zLn8m?TL1JJwjr-T9PF+p)}y-{S<eHr4@E<ZipeL)vm{O$p>zf&6>4{<p7xOdO2b{h z!>=Eyi<1twb7@Qk!*mBOT{pRIW=`E^l_{&d4V;?vG;2&BkZ00Pp;>_d?@Z;h9}Rk_ zB`wPfD;Axi)nVVCXVwRaK`kPqk0e<E?FqxkLm8A!iVOaq_)mI{Hey_bks#pAv@`g1 z*DUJOf}y|8yFF9q26fn^_c+Me)`KU5JpN?#lE=s)avO1`!5Z?AgGHEk3c<<Q<DF)i zv!$~)Juo8ru9Xf&P%5}ZrlSdmv|Dp|6Rs`v!DVFXt@mZh8tQraJJaCy`+7S+ANPcp zj?LBZm!~^-?iP{=_E;1@TS?7ynd)FkaTC|Bq<h;-Z|qzTdjEBh5es~ToggR1R0%Na z^cFDoBS-*oaG-5UAjHhkkXFT~DUA7mdw|~IEWwy05poHN(1gR>B6x{yID-RdC<Y33 zeLyR7MK)aWr7{^OzVC3=>2vo+a^!&*LaRT${1N}iseK^i<@i(8JMV2xn7>|K&$=m$ z-FA(?%q%R-&TH<nMD(Km^6o*?Z?PBVaRZB8WnSmy8Te)L>1&>OZH<(KBdc*LG>y{B zplnhP(StDk!0sxCHy5=<kG!U7pIrhojIV3Ci!cG->uyG&h?UNdepN0I6ehE}JQ*#K zl<LHnihqwhYiW7JR}fFvwS9tSz*RO}bimw&#A227M6hST-%cndjl|9g&%rC2-;}h~ zBZ1Mz;G93VT;uq%`O$MkN3~b(vB22twEDMo92`%MeCp(`2}ge_)25Z!>I>$emAb8K z!VnCyIqiG&*?EQef=XuXeVHF7T9cDY(b)ykaZ1K6yD_!k+AdYmsx<^oE$$V}3xYUo zm(7kc3MR|6^r(vBt2F;j9nUS;kH2*6DhSO#4HuW#?gM~%VdgeqYn`pzd{K{(3GCV1 zN3UC)*qZG$_bpG5=bbt>%kpSyNKR`Xe+{kLQo{8^j6$=;R2MBV$U{QrgYOAz3F`4x zE8^LXajP`(oz!IXo~bZc+$mjQ-sLIEA|in`)w@b=9qsq$@rO8~8n;CG^q<-`-3Tk{ z@Cr?L&&QMfBi(lEUhuy@GQy<w$~Jyg+g(ZE;E|Qy<9lYQ)*Ve^LJB1<f@J!sGYMI| z{kO|?no?<#ZO7Ka+CSrGlVG%JRj{zI^8@90BVgI7r%R@FX+$!Wb7}UHj|9DX@t^uG zQlC#(dy5o)88X(Wh$UCYcPILo$|i9~A=kto87DK_Ogej<{i4lN(P)C<Rs^y-VAzX@ z<ndnP;SWT>pFD39FFm%KOX@XZP7lUmz{~#Z32-!FYxX3)#&82B`u{nefw8@tBShje zU1~k(%axQ(Gg_HYCK_U7ajW4-3}rTPYqs9a+Nv~7G8Pq)tXHanN8~bDexxz}sjUBV z@90%!)pcxB#;J))z(=VeC9*uK#g}VgPEV1eg40&TiK`#4mG0`_mrC0?n>fC7TJ^e1 z&4&^jX4{i%muD?={CJa=7{~Jz>~fCpw_mQiS4Y~3{z&VZ+lmUrQ-v+E{1CiM0<zdj zKi4GkfdFlMuRsr)1^zXIN5Bf})6-P-S?pZ0ocm)lNs|F4C}H1|nMlU3tl$SStA+^G zZ9b0)L*{-Mm|ijT<L%$w6KO*LI*CTh8J$~rB&Ob@g}IrTD;Ea!3s*Kb|7MS^pMQYS z+RRm&B}XmVCQMKbD3gf>yUmPPowM8YjJZ|&Jsx{zC}q}8_Z&W}@s^<YFH2TLx)FTx zjNK!0Ab+`?K(Fnh^wNTENi%9|WX$a^J#u8cpNp-Xt&1O?oRaGVPeT=O#9X{1H-${X z<08v*H7b^zkd~d3otEGN8-)<<ISMJdtS|)9qD64G2OKRH2zsu%&Zo4B8c2LMkjac2 zz_^sCJr#ZP><`4USL=ZDv~raIC2_)*m=S>>OtO3*5uv;V#`%A(eMckA&Tx>*z%_Cf zvfIaUeDhRnvttN3ks#2MT&thEB5<?x2b!x+)rQfG_+f;Z*tOHZhHsj*Z@(YbyB8mz zjHnY2KqB(30YQ4oB19b-U%`E<{_(+8_e)X0g3!4=)B<*;+<>PQjCqerwY!v{c3{GE zNTIuBwH<wNpRrPkOSY*3iC=<$3S*3V>YGUmvun0`2ZWi6r54x8R|B7~5gp)ow-*io zwKBNLdM3fb<RU;5-<wCIX-0ZMC2O#U7O%CrM2)er%H;!e*wO}GW7m>-z1onWhN^u* zdSC=8z>cPlV6k2tO4i^h&LVoF$Y3sj(BN%g<po-gKH1lnO6Phy@<0Lg7GNqUDRT^X zWwMxNf3riCGe9Kg_-+mumGB@y`$PbU4jy1yDo~|?p<|&0ng*<BOZ4wpM4;lu_q-%C zLflYSJl$0g-!7b&KgjPL8-O`m3vY!0W)=+&uC*%XfF{}*kM3sOW7vE{!2!D_<v#!; zU<`;^HAtNv$3Yv85W;|ynZ*+fEy&BQvA_{VBlu}F4D>|h^sIKIZ5<-eaTG*wnZ0$# z^C`7oU23M&l@;ZcJ`GFBFp*KoxDlIjD%6piJeJA)^<y<93y?~N)mYRBa><<{9dLm& zLPwYe4ykbamXNOV)DYmrBf*a~kGp(YoUU-2G7c&@SRdDrOn!VepfjM9vVcf5<gneT zMcglmMnNHKi$LRO_4Png?wSdUqsF2w$O?oQPyZ!&c(M7EV!Io$d+Bm<%dXTFEr(cp z+o?pGyyJpXrN<MUJSn@f8+Ut6O)Pfl_s4yXe@AG0NCs=6jAbLA^y|j-i4@LKz<T!1 z$@@cX(cRQj+d}KE$z9elTDIIHF{?vX3N^5K9fMNjs^M^5O-2pzZ=HFnldDqM%5)sT zL!J$0Ae;#puHlf%%C(Jr=_O%oZyprTKr6wI7D(=-EumZw(1R(MGExEibW*9P4|Xmi z0kFBykpQ6J=LitcBk8ybbI_N57Uh_zUr*!Em=nW+CB3qbV!)9;(vln!V&fZ~%^1i= z|JCqlJeahh(_n`U8Ms2HSy+Gy4S}F<?@=Zv&(R9BnzSfJVWzcqXj=IALyJbQs`h-E zGf)Zi7K~|q*Evk0f(lJ3K!iL~N`N%%OvWB~+7u*z*`yimgjy+R!OVCF{B(<S8HSbK zrqkXt3S<bCCi)y=p8x~jjgaPBqmCf7RG&KUx52N@d>b&fkK8LJqc$)j`tMu+i0OiC zkdSX`Y?c~*_`?I3*avkNjf(Uf0gO>FAB$OQGT!N{ChU!;fxyRfE6VDy*{XppqRCkE zAGn{=0H<f;w!ckgc?%pn^mqe$Y5Hz33+Gqe_ep#4T^B*Kmcqat6?@6k)>T4ePXlc$ z+)J@1mz?HL7K#q~eO^mij6U3PT0kN#9t@?==3}f1JxC!9E>R!jZUoyC`Rv*w>&l7c zv`}BddugeBt#NeOBJmf^8i%~6tK0)BBe0nXPNm<^7=L$?@e`_W`~C7FE%P=drC@>q zD<?{8D-*!2W7*bK7k_B_SNpS$iPndeU;@*Z7QWYV0)|jGa=u5cOruQ$s?g3?FUaPK zMBK_Fe`{7s9|{gDt9KP*b~jy@oPA9JoL4FzPA^vK>htQnd{YY8{GGOabVNv7Ct8i3 zo>}vYAyj*ArfFpj&y59t-^8ei=?IO6d;>>wGR7Px%s{2<^uEXQWUAPUb(C=L7{f+R z-1lvt*j8(`b^#kL2|A0Tap3`uQ%!!!@%w^WIAI!n92!wxF#SPv!m*IBN=!A*4;GrH zk3H@za<N99{{794vS{tudcoh5eQ8PNn1b&Jy2onk9`2@}3+_tdaO)4vmzxxf@jw<o zz+;SYFB4I-<t>S>Nb9KwXyu$#hLiR}mJ6cnYPKbTc0@r#@_J@*C1T@6zW~=Kzal4U z1Yo+S6r~4j+Z7ybsRs~xZ~7fyCz<Ok9-$1n!C-^zcyd(JQu8_2)ev3muom5`KDV)8 zznaO+AT4xrnQ}?{>Gxtn2L{qT=2#X)xF9-h$@Cx}Hc`{46sb*ek$U>9Imlgm^Bm`4 z?#AF0{BV7udo<sOy!s4kwkXtcR66>cC)!OFHbaJL0mfxA?U_W(VeXNmI!(vjOy^i$ z*+Z!c*arv5tSWP)_|0YN+31+6x)RBW629^D)XJC2ZAcoHK||MaFAvuz)@jYhJks1H zaMl#Kj1p`)SLuldKf!;Y`!$VlT;&ia{V1YN7$|;|<EEHhP}imW@vbXXtF>g{Bypg5 zku#qri)CCPdI!{$=HAdV3#-{=msloqOR<7xLi2@XBA2Owo4;10&+;~un>e+BLHMm- zmrll53Js6_ep4WQ{#AV81bJ|>DsYGbPM7B7-0N0*kwdvD1vv%8<La%o4z9m0Vx;O= znL@`sHAotXo}Z78JUhU#EpYkCVb%M^j;*EF=$nE$bG!_8+6SUrZwpgiy@gFyt+knq zh|LOAd}!s4${2$(*7wz^lg}%YD{Gr-g|%q_eOnbM#9t-OnPX5{=Y(VIag#yxFyFO> z5NWefRqdfRck||vlHD;TBTFu~bE3VlL@V=jFVYGvsfCmKP?cpQ=aZ?hPwGVAn6L~0 zbW_oeyzy2ZA#d`DBcch;jb+$9z2X3$iA4@#4#Wzu^F|cZ(BZZyrlU0#28KhSD0cUy z?r<r%U^gF!!RLUMplz}bw;6$p*jf>e$U@?m5=S-Q&Pb9Ise)S{v#2}Hdlt5(O(p0u zu`#wu^!Uv5OU~B1;LgeAR{C%(5nOje@m$a5Q?fXzJZouIIL#K;5c)X#4K`0pTWA{~ z>?|D6n+NhYbt}f!Z}J1p`gI}`=Y7g7+|@TWm5<XRS{Uv~Brc`2L6ycc7ORbr^qv~C z#W1Rr-y5&FCF0tp-uf!b9Hllq(K<^w_zrWyX4}L=X-JYHSL%W2TNV*^tnIXJTuoGl z;Gtk}F;5XV7H%S;X1+gavN5^BszoAyhUFJ9QWVc!0U#6K?5)l>Z1x+5q9n}G%wZg~ z)9KV2Ob+RC^_#m#(yr0nMqDjdPl8ZM5$+!$wRrNBEmf_ZoRug=2^QRF#{2~hv>4#k z_2H}y4W!nyjAdprQ#z^!(cB=NX+Zb9Pq4Z2e#&^knAWg@4P=(vZ{|t~{8|MzPHokH zWz2Kh6&Qw}?XK}=?UuN)C&SsFG}Ms)0dZq@im$Q?#21AjwctT(YS4AS83F4lXjsZZ z9U&KTO=+TQKtH)FnO#;#JE$X|rxcJS8qauxei&ECg*h|gw|D!%3N~+QYintP_#B=@ za;BCRuV^)`NOYk93S?u!RT*M-U1GJ4DndvdUXf!7@dC%PR0uJ=<MQZvS?ww;?8wYp zt+h3lv<_K;=7<tW&LI8<!j7c5%PgVb^hHI(x7sEoF&jwGq#%c|h3PB^Ked*A6ifjO zA%v5%F-&3J7+_Q#=@!G*Koq0Q`u`ElRU@JwHTwASvpn&&mTTdocHu}GMUjzY4b&z0 zKmr2ia#5D6X523Dg2F_n2i_@}3M+~|(Ng>j9HVEI<T!%kZnUfpz5rt&u_sySxysHB zMB3k~RW<gx-@p9G83a8!zq+r>J)vhEX@<`})ni<R(g}o>C0gXJZxV_L@z*1Pj5SIv z>*}3%F6p(#e*&93ZH%jGL6+kv&h=@R-W;n|k5llYt4dqJeb!GTVXB(uAviUfKA@Y( zIZK7^cNKB7ZJ9^R)5wsHecf<ayr2<-7`V>gy7e_l^C+HMW-#a8dUk*{HYsXUG^DzO zN-0jF!&xp-r{}^r!x?9lJO}DAF)U~yk`x$S51u;>1U<Pq*&TLI`a5gS5v!W}O}6zw z_Q+t!)uv#MPB&+2*_Cc0D8eXty*})BSIe&66I~id7@dh_E0Q_6BjOY~5;CrH_9@nV zU9DLdXw<0(D5fk=U8o<mWw?Bt!3|SXgWJKmmLYp}U&$5s6y%a2=cjwZlUMkrc!9*V zmV!=);a3}THCG%DwXl^m`2`3!x}a)t$eXP6uqf1RM610s8+FTS8Su=Zfvm<zl0T=C zqmrB+@@aF#%6cX6w5rPG^BNVCrJ!c{=4Nx&*yN=hsR;MWfnPRYS-l|$IxN&d`IUq` zplTZi_6sEBzNX5dKu&Ffj_y^La4+0TE&2$)*CY?D%;N)8+%mV8i%_0IjCQ@#{AP(I zsfoB=qtmw68zNHUV5E4*K#Jm5#O^v-=0US;UW(=>R5;Pdusq56Od2=8v>B~Q{fY@o z&WhhZ)M@&W6L&{^NvU=5bi>rrnwm2;htRyu4A($1Ih3Mb&<MSbcqPv8-m30kcM3Ox zsDah0!)pC3i5nIhSit>qU@fw}TDuzsg-}S+f?t`pnCCTNrdMfaVZ}(_0wIz7XlSX7 z@x3fpk3jfIPekSF`1p?xztmmh#56a$6*kRYGX05bZ2I+nRsAdQZ;&QbgF8Y`q8i$M z44$~?jS=M#qqd8|zel)~>Im568Abyuhh-~J&I~4wLd;fu39h|N`jSLpwp{9LVLK%a z5}%txkVuhR0>@_*3T|qB2oKj@=SwNUQ>lU?1}Ta-sk-Txo3@u&S?lwB8%tnpZeNA2 z;~`_tUK*;PiZFWlL=8_6N8@MWt8$8VIic1~PUa&k+hCc3gZYA0+G<Ib&r`?<dCj7y zP6_twy1X!=nx70GDU>nfoe{H)7;?BkF!3*1Sr(#SfNTtCS2Us1kv+1U)m!U|CXdgO z_U-8zP(O;@D#=5}K73Fyca`VzN6XztDxUNvMTi)V_>*#Vr_-%gd+!mbfp<#uUd`AF zH80PZg-+SpLX?-xS~ftiyqB>c&BLomRa!QP3|ZAH#f~kD&~x0D?dnT6HaWkuQVEx4 zn*CZNm;>D+5rzflNqfa^;(iiPJ*&YpXVg+Iw(F)&7V>q2o~01jA=j2h(gV6I2icMt zU?3%upLL5yA14{V9>JHMoHMWS)!ukZ$z&Ff>9p1$6NUf5@%E{aIo>cduL$kJt#B(< znp@dx;|KJff+1+)s5s%bZ<0@2X)Eb$Ni@{2@}mxboZ{?-gd_zFv4=>eLhI23!C<Fd z5y0bN!U&P&wwuJ)Oew8pLl=iBGRg$ODgUN5HG&O#PdHfDtBFoUAW}pm6$}=ngWbX` z_-O}K<PHuQl^&NED|v<{SciMyE}~#Q36BXXN~!YYrAoO4lLz#~p)OHf8?y4IsidF9 zfi;S@VHlJYZ(rHgQDV&s*ZX+M+r_j*5tdgnlwE@sq3=;ltzSh$hIE%?PhZrcq`hvj z#>(N|o~uXKjd4TON33v}?G7$k>LJOu&obJIp+7}ed}*Do+IsTp&pX29YPW`hh1^at zoq)DSY!{YQcSVhOSK6#YDoTBVDH0HdBaAd@zA-ufXRg!EIIg%rl<i`G8#Ka^(8Y8y zD&{dGq)WrFIX(`vB8{BZUG<ig&^cCC(r=es%Tl0$vD?PCB=&}MNm2U+@Z<=r=FCii z0(^~06uJdb%o=V4v25lF;C)+v5m&fHTepfs-lAL(+FOFsF09I)yE(Y~t8l53l*AkY zPOix9s%+4<dpIQ`hsA=f3|G4~>EFQV&K8ps+R!G5luHAeFQ<s*HL{QoV<k)0b{BeT zrW;m${SjRpw<<!@?3~aRa4%}popG^4+K#)>U12X#_|lZGK~Z{JLEgy|2K2thC53fa zf@GJ}krr3R1TljlmGFX?b`_NLs8*3W^9fw&`iqJ(cwgUJV;e71kK?|+y|<o=p?qmM zzN4-1WrxGtWSQ1s5}COCnW{r1Un9+wNvLa@I2leTt2ZK>P1MRfV5n_wx<1R3<U%Zb zD|n5w&93Fw5?k_gA)?|ObiAr-OtZV<QuHaQ%h)u00<u9p?Z8^rxgu(f?|<CVhB7!7 zw75hhpvo6Y&@RD(dO{7_El5yOkfDU2K>G#5YWJ~JBXl_vwB-;;%M|3o(d`kEgTOo? zGUY5n$}&pGnU6BqMKxXC0^Vzcl~S|GOMuLKc1B%$UIG0&nr<v5lZdi$3b<dRAF%td zVdPg$`fd4mftsv)vI5#>8(({*f^xjnFb4t4E<}!(&)8j0Lch+hG1zoHD6*crDhJu& z`E#Gpr$5t@MiR%~iabj|M)o+sO+MDZDi{^G)9`*g=|Qu}n95ADOz`JOlFr5om1cqG z%~?HjVz^AmA3vB<j!fnKs~AZ4?mB%zw^N|t>K8+9bTzSsAJ~QAF?q-s6;6R8Gt2H8 zl8Lg)Fjty+-nQN*m=6(2vKnP-OKX9-NP=WSG9ov0rwJ2A-1AceoZDn3r(q4dYIa^l zsj4eyH_Rp#wW{u%DxFO#<SHVkB4v|NjWQ&a84@jERLyU6Lm-X`-qz+0+GfFHW^JL_ zxoxFJ&;SjM0RW_i+{EUC5OOcQk5~W(VNA96qR~aUf4xz-O?}1P3}4>^4$FxLT;Iu| zr$6W>;l7p8ppOWLPjbKW#zrDuyZv2fC(n_0oi;MDXr0{CD!>dTc=1L+lszJE#5P0o zuH#W3*X2roFhw~mh{lTQ6>NEGbw%UWa$j(^7qg8^vdi*Rd?LfDSMu(${D-^2ddElV zpnPPcvE@Klzz3c1pIU~)dfAq&3|5JLh>bg%jz&?Wq{+p0$Y?Xb)JAmKWpoHspsHzt zf{(q!VWTc!Z4J?#-r_fR8y|FEo$_-I=x$z8T{S`eyFl*=x0~Nqq$xIasT{(5R$s~P zgC1B5*uOzGK8|=Ww?Lc&JKOo=!<US!D(NZuMNo-MS!$*4a5nw#C9oZCjlTu<=MVvp z!dB&SD_n{Lb09CpZh$MV(_W9x8S++rTGjRBS_LQ-Z7_9(%$O<9@)A?2(dfd!ly0B_ zAdXG<Z*knXJ8Rm7<D_4^!L8N@mp0a6&pST{U(2;6hRxlmMCKeg8t;7WNg)SpFKFbN zYf^YS<EG4uLIO~Fqf`{B{`5)Yp)|CDK!Se@#AqOvZT8P3d^ZC<v0BHgofXQSJZ=EU z`sr0py#b6~&#hDRm#Q&JL#yj(?gF%OQIm1rbULo}CS99t`^^TmdYa+|GgMe4O$$jv zn*CaHXF+M$YT;;Ob&E;kdloTJ-KXoZR+p>5E-UU;Eve@jhT$1$^lW3W^U3WsSo(4# zv9y%hFxLOka3&US&5jPW${^;VmSoLrI&KW6Tpf<{q1SOsf9i1@Ed&o&nTxA-SqIHn z*G8v;(bb9Z;eNSo%fLuB3bDjRs_}t{qO?0j(Q205YE-_N*ihxA6>~Vd%$ZiZ+&-gj z{>%ElKaCjtBBHjm2HAmp?sq?WF-Ro7uJL{SmvG~q*1b@h0!OIhyS()7m{K5h`|Bvp zgjQ|_47-`T8O-3WY0*X0;Y7@c5xgL`?%PyY96m7yHnGLY8$1a_?^}K;N9H3)Ds(ka z^fpl<$YF_+gCW^lI%tVu@2l@ZjnRco2-5j=7z2V#P@WI2-lT)aJ^Ys{=1ylh#=@}n zk0m_bRN_GuQ<fp)ON(Z+Bf*|3*5FwldE|cb0C@<D(KQvt85W!43(c8C%PocydKiuS zQWp@`Zt6zQQsH$EY`kWX;7|prqZetB8mzG){3fGr!JB%!xU1v-?gv*HgoT-k6JGL7 zN5CVVvQ8BF!^q&-yZ8G|qjbPpxsiUO8n@A9D+wzbPx347KZyKezuP~b*{9xiN?Sys zgtWu<gdH3EPM$baDzULvNS!=-T>EN?=TK({b%h*GKx#v_m|_c3PiC%{3$C=^-k?rw z!NRK|?Rab{zOd&=Gfp;@%ipeG;fPAbz@mR$QN7Ou6Ueh~%m-U)2iqvFrUY#(<Y6zv zf2T)aTI8gvdcxQp%x$vZmKNyQamWo|Zj_n)E-DLb-VM?ZZ8Iv8$RVV*qo_!L<zEl# zfHIMs0%9M_g|__0%y#Dh?|WhUg=MrK%e&A75FdZF=V=1I@lg}KMjhP4cZ#R+NO4V? z_*fhDzOpX2x)(&H9kt?I-$tqyod<0{9d?iHi1lh6g@Z#-@ZX#21({%xu}lA3;#|l5 z-4Y|RK%1T!?{AwZk1^t-Ndo`*Z8n)kqd#{4w(-D&tB?d`V<TFTO*xRnkSzHvBQs#& zj5i#>8Xc;?i%aEJQsM=vZdJZy>+wbSW*g6nf_7pp0N_amW|D!r!))AFJ0@h-hd^$C zmcO@-H_%nruWtqA^lQVp6{FDDtWzs`+`KnqL#fym!9GO=g_*#n-=UhLyLENXm?HE5 zKmdRf-#nCPaoxKr{uymK8vp>pe|h&x007_IzvEx`B3Ad<hbjO7P=Emd00Q_|f8NsU z>5n5u!gUbqAbmSRca{5KPMt_RF{}DKQxvTQzz91<q4j+(YJC7&N>_8c;9@1Tiks?U z#b@WS`jCX5Pu+rKeK{q&FZ|!ER!GdMd&#Kk3Qr6qCjy2i4(y_>Y!Z7xD{j2ZiT;V? z@e?$<AdPOorj;uyvl5m731%139#fO>iLvsM0kF#uNbqUX48&JqKzliZiec(eX4${{ z*!j)s2iUZlCo~4O2h&XL!vyeTwi-b5I1HO%ZvHlx2x{S@LH#uvU<^&@9`jZ-w%YO| z6MAc5z)>ysjV13OKpscHngC{WVsRV=dkjNm^n)Fz;A9?|L>RZ4bR%aqTtx&JuuyYX zd>YR{f8}7|0mA^KU0hXdt|n-U(12QZfp4GhRX^DBl*TyJml@DiV?fjbYIikk40jGe z80-oFNP%;uWYQ`XamBzE23)QmV;7@2Wv~_9$i<Diz7MW-&0TqDm4TV1y?W#?H(Ir^ zG!%yb*@uTr3h97e2vkLc(uu~Ob-Z1{mMp5I1L=VVf%8nQfGZBS#?ib3z*ytoY7&Qz zh(M;L!Hk1Y7&*Xt80m(9Y41U%)galD7^<5<wKzsv0?9Ujp%%qRi({xdkZAoFYH?7t zZS@O!cUMCXZX47x0Mh3@5cT>hM$=M_v^0_nAMkM06=PpSbq7!&uM1#i2!Pe%@bn_O z$}mW^&-9lrQcXb(;O?{n<{-4QKd()Q?;=HKfU9o35OaYX#@mWWf=-!`jXqf~>_}v| z{2;FT&szSct2%N<lHS7_DQ(H%vJ$9i0H7b_b%<7f9Y*KXI-G2zj$k%dM=Eozj$+R7 z2pxB|2S9pY<FPs}ZG`I5Vxq6k5Z{23(X)?enQe%u%ZiOZ)>-2Epe{QmKB-$*dY?aT z*0d3I^lJ}!E3)fM92w|)oNqV+Q>rzl1MzTl7=#cyCe?~?Ya=qt&yM0Fno+9ElW?Zj zW8GH0zESC^hJG)zZ>i+A!=tyj@m%2gEO_PQ-wyWl^^cvMo4+)Fw&Drhw_A$`IwE;A zVms_Te#G21%iUQh59hD4Z=}{&ajSQ1LyW8AWWG68;}yN00dc)^>g^L&LF*%zd8-(R wKg>A7xP+r3x0JVJd}+QVwHtof$Y0KdUQthP9+x62i;{CXS#{U{GTaXOKIl9gFaQ7m diff --git a/.next/static/media/513657b02c5c193f-s.woff2 b/.next/static/media/513657b02c5c193f-s.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..fd86d822946a2ee228b991ca228eba67fccc57cd GIT binary patch literal 17612 zcmV(<K-#}|Pew8T0RR9107T3H5&!@I0EUPF07PE^0RR9100000000000000000000 z0000Qf-@VQbR2<3KS)+VQiEOwU_Vn-K~#Y_0D>$pY!L_w$Vj^p3xXs7F#QezHUcCA zghT`&1%+G(i#!{5eKpE$Ck2`pz(&jEeV`)|!o~rJ1Y0~3A#5CgAlc=~|Nk|C$`Fmy zRW>jfzk)O7SYL|D8p%eo5lg5gv0A6j=`n)hS?MV1P&;MC+p-`T%}CNwXfUpAnYy}B z@a%`U=OyR8_t8a9(U|s6hg!^M=BiVq;?O|{-Pdjq8t6bS7j~T|{~1l5xZ{QQZD(NH z$e-lo^}i>b_2<5R-D(9SAvIax1_YKpGS(R3kwNyfS^}CG8OxyY;*3LPJ#xqlBMF?@ zS-FZ0`Txw{5F)jIgKNs0sVz2BTQiwog}wYW!<$dHSIyvy2G1`+JitZ#emFc()whdI zL&pxI=`eOQ`2T+HAJ@K+<Rv9m>}tg0X~&b$6|U~?mtR0oohk%f1vnlE4gzj$$2_D2 zRJcmJXQcbIejjLnjE))t11_!X1P4HnEduCJFB`{LBy$1=6A#G5f>p}}s&GyI=Xu=p z&kIk85HMn9V~HAV+R}}+w4-aLe0vijrjB))pKWxX{?d+Z{*7*I^KWdQ_P-=SQ~K1W zMvXRN)KpT9nCh!WjQWI#&o<&ypZdh7JTYo&pBOM=)Ci_?v|O+@S8N*qSMvWl{Nf-y z|3BvLTLSNdMkk3&Tt$+~=^El9uB{VyX#4ko*Udl4m_pPb5yFzFu~Lc?tT+=SR$Pmr zSwMh*p#%s+iI5VMEG6!^0C(im7;9A827?#`C%C@v*Hq*BJ~09<u~MUB!&t|85d@Fc z%$dVvX7^C|mtPdN!UeDZxVK{h#eggrN5WRv4YzD|3%%2_)PBE>;^!zv^^Ut@qCxn3 zQ_c22fWWLWflD|?o-E7&j^w497jos0YS*z_{N2?if?O^H9TtEj0FrzQkkssA2?kJ{ z2wEgWr<j*mVGiK}m@ZMe<P>A;I`vmHu3UOtRKBKknJX7%<)U<D`2YX?exDZ;vjZM! zL<XTjO(y$o%<jWIiA5@<Qj*ITPruY(LirHdWO{sWhE*bzCmF3E+#C2gOl)b4gaf(9 zRfJKEpxxts?QT@r7&=~m7YQP1kW_+%)O-KKyjr_Zgo%5f$6aHp520hzwM-h3-~xQs zS95t~AQGRFejr(ew2atlTjJnC+--?hIpS|iD%Bu$F4Ev4%`Vc?mV|_nwzedq9eK({ zHn~VwGua%tyPjsadKg^KGP(NMTmw9={YckAylaH)Is@?+;VSgvztLg^caTXXgaBR) zpaZrb?9W>OVAxYo2_W>ji83)xkP>n#FZ7-f&_iJhM<v1#2r1>b{|){(Dfk!oJp5U3 zYP~uFRC045wdi`}>}d>Olb&=IeYf!W)9Ayfn1DEd033iz+p7_!GYSg;r?c9TDFA1` zQ|)}g2~IfG;a8{^3YP{8;JRO!f?0S5B`gS9jOBKfxAyig-`!Gx$2x~Gmj{*|{!YsJ zhRNrG2*=dz_xM+enXXMxO$scYTkDuR6Mm!Dd1pf1TCgbceDYELtj(TJ?eg8C0ifRz zY8|?4x&UF5MLE~q7@hU;yr97IAv~)Hx9%Pu4PNrQ5cvUtJu6?TinK6g<MhJH*?^l7 zHPN6__#P5XMf*QFuSio@20RC@ghex*&H0XZ+}?iw6((weoi?x+lSdNhVl-u(6xWWM zdasJ*K%_i@h9?6I!!*lXIj7-Ibb(TIcyH;r{+J+9o<vI<y$AF~?YVWikssM*Y~Af_ z6vy<-<4=@xg#*6Yoa|yhM+P2`&L8Wa7hofKs9k*=NMD+48j+gLO-NQaICL?E(~IW5 z1wRQl|HO0+%DvS&4}bRa6dZlWogJC>RrCcqA3bg>KaQTx@*}yJg~!J+%B!nC;N|>t z1gSdk_!bSig_j5eLDI}_^3TTe$0FkM4ub+!-~i;0h@t0()CXk0;zT>DSV%QLrG}sJ z3*O}e?BpRWRe#-p9@(MRPF`u)>A8OP&hplZyj(yOA}Jrx;AZELu>tb{Ub&n=suMsk z@qECE4>x|wARNdrB$YeakP<Ns_sjqs85KKDTzDzRhaZiap;{d^G<YhkvMK1gLZi(K zO`c|aLP$Dl?ZMV@7K4cp?w`^RH)DX$ynRTy?4UHAg4?q9$+UNcc`uHYfieJ~Hvey_ zifSi_06SEz#BUA&Ce=Fd`i`?CugY7UVwf#?$qjHF=9%JD14Ck4?dp&Uow^(pN+=iT z_bDq1Mr%zA#UxUv(rEQ)+3g`CHEKhP%Un8*s_yj3<<lHM{Af<{SEs>~eLZmhYKJe4 zLQ|?7b&ei)c%^cA-0pb8h+Ia-qB6W|HnxGt>D+*9Ug4doYV}QHH}aC8!`(B57gT<< z)Xx(cDZ9(e7{G%0ast$H@S)40cjwSY(x6q_LvQ9f=C;5T@Th~P`6ZI}8rcxC*r!NP z=%M*`rdE>;*2)mjTAd!l7$U5<(t$x=FV<nr9bSilW41t4SOeOQgc&C|PSW!7HE1LS zPrn8D+aniRH^gB2zYI<A)!tNwn{HZPEHAc~me1y&n(sHwl=j!YyzGJPH`ZCpY|X4~ zw&C~a_w{o|u~M@B**0IEu)Sh=!yuQ+)&*-`x2Rt%TWrcN`!_CG0pwDdCK^Lf0t^fU z;QrMRx)#`LF((QBTOoBT_`4zeAjBR7_oLu@6atTe|4ERag2>ZAJ_GLOApQb)-vHt* z@Vy0rw;=EVcs~X1OK|_F(Ck4m6kq^og<#6@I~X-ShP8?s9gi7BqgrfOjRfXefh!TU z){7zA1nF7<jEkJL;;f`-ksPfOVg6r&Nw{}oI-xr(t*veG<~BB#mm3`HwGqM>`~6H& z_+72tzH_Huin7n`sOa{Wr2hU?s_!3YG@fWk<jJ=~>R(b{-#Rf_h#Fe69V@=P+N>(8 zZVHwXHw12l)7sVQuJM2xtC*~>$pluqd=r#V=-v-(?LCnOo51fz_P(@qeBc(dYQ(@( zZK9CDHtIG5{EC)I|K5tl8TrC@4F@(x0aWSt2F_at@y4n<9KnKHf#W9=1oRC6<!@cT zU_>gmGdRv<_hZM;(*c~jo%ZJ2{%5+d7z=?UO1Xvrpe%<Kw3c&Ro}cV2s_bfEOr%N_ zV9kA--&I5DbX*;)n^`YAZk42uHA*f$8&P)^>|?-!(yog{T{u<8yijwOmmrogzMrqb zf1WdaLUcESm+%&&zwze(k11RJbOkU0_&NN<+brSavfC}Y^xY(WaQvR*WOG}!JDyQ0 zsa#RFDm_lMt6?!{<5p+fgzIkHw8d`Pn&Iq&V@Ggt^BA^QP)OK>gQ9@@j-WAE>rU9z z;-p=t=pU<WtAJE7=kLv=lu2uaO}b*+2JJeW7dP!C?`4o2AzfB_3=@YLwNoP=0ib}s zfWHbTEh73TFXJa6${@>Bmg3-KkW*9#KV@phio=pY4pUd}{X!_{3IN;#fO-I*0(%2^ zb||1<Ko0;w1~5GEq%z1Tgt)TJ_+Go9PF+lfB>G5^Fq|;PR;RaS_NKavI--<80>(&a z6_%SV4cZC+I*!P6b+96Q(n|^|p&ZA-b^_p~Tt%{}UL=}1-OpF5Ua{_*oXD~UR2b23 zZ2F(A6**K~P+v<yDu*yK0QF%Z<|KD=GO3>vU)VCRFOOXdN^Ij%Yui63N5yC}>G|B7 z=;-~L?9zYzi2D$EVX{=&$*t(A4MPcR4I27&X(hT+mP`pn`?brAICh>JjG(_{Skk%9 zHoFF_R`dU%%X;oO=9&~1{FQ_x6a}VXv%U2u`Ip~IZ`$nK0qvsp{&f9MbNUD)O9@$! zSF$zZsO-6-xaj0AiCpFx#UGm08hNxGt792yT5T$2JAvn`Hjqw}Axpw@t3*w_PbTq4 zQF~=e?K;!>kD<^xh$8QR2+Me&$d&9=I2ajS=bEb^Fye0M6+L)JtF<m1um4e=R!u>H zgy~?#UN0FX_NX@z#rJ0X9bzQ}EQ&a$(%opaGS4r05g~nnYoU+eCopu@F>z5ft34f& zctcw;`M~O&@uwGg%iRGa=9U0&slKRrcDT7%qZ=h6;ea{jcVj3XBN+A^b4rHMj3{x0 z??-tm9qkBgo(Xht6Mh#&8$$r&-`v!^Pf<I50xKwES*|ssL)TPX)=(JuGjELL$>Y82 zV~VU!+5RzUeA7?hBsZJ(w;|MO?_?bB@EW74D7WtDo43^Mo9fQ(TQeTz$oJyywzWLx zIAwE8AafPcprAc~b;a=gG<-}GmfYtcyRsW{s2=)KRzXSft#=`pWZ+_pq@NM1tJLMV z>;;3gJ;#Xfmoc~0peqF?8AhQ?5#1-2A_^&i$57<*ND{LRNA}@M>$x9LcnP6!MjCp< z(JSjijP^U55be}wp(k(7K>36QA9)T2up<kA><9rBwh^#gFl3o52pNNMrjOYPrtddl zWk5cmZM+Cm7^;%buIzm-(uTP!pq)|%S$4N2haD*e^~N#lsiKI;^n(nq>Xm~r+dZzK zHZYBNFez98oXkO$avs7dB#xX(jW)`y<33Ke;iihIU62N>wA=o%m?Jj*Xpa<IT;Tqc zq#UF~v0N&kP(qz+oOf;;Jc;Hc-^W+~%EmTkI%|i}Boifu4V~;AZsLYXf4c(;yOmTo z<nJ~PUC1356`r)7bj(?v>suUhz<2c1vHLk4Qs`+Pv$%jTG15V_%d){JuWv;Cth!Oc z9BqUb=+JF!If^jl!l8k)9eGU~vP_{+xnB}8ywKu79qj64ycbK<kW_ERwE;-wcqP{2 zx*o8;l}jYw4HY(Yq82wMjZ;m8q@c(@SdtNa#=4h>V2^%_=lkrzemZU()61)6J_)wo zU!s7*XRT9Dz=E*42<Nbyx<6tn^9DAYz66ndJB>qd7G&aJvxx0mUxNg-I<54}m;dH? z6JZStCWR_#Rg8jQnliu5r1FPJz4fH8ugZ1Zm5jlUP86R30OL3QV~`Qdt3M!<GTvfa zBETCa8&jDO4?DzAB~Sn;DHnV{W`(^;k2L<B62QLM*w*S+S_H?$Ko~71{(Y_U`TY5b z{1m);DJhBbQ}|!jAA6928oDnA?ot1}&y{w5pJ+o6JstOJN#*l~Lv??BtM7k*1s#Y- z)spNMM^26RNnB>#kaJ9`zSi2^3&m|pZ(xq}#G(9aahX@6ueIcn$soOSHB-pAF=<0! zwl~C7KlCg_+jJPe-}mk@m#d^o_`^zSsQz#I7QG^3H6bP&iq!4)8Z3tI7Nf-ov!kG5 zses|e;e=mr*N?)jw4A|}?R|M<aKn1#{v<)}-c8G!D-m2RFJpGKmpjv8n%ORnj;^-( z!VkcdTTnWsrio!DY#`z-;57|<0Ey6mknE*NLzJd32JZp#9>St0cJMqPF5r19|7>;J zM~<vp<z`nDD}N)bBh$?F6E0oaGihq`M~|31d9xtpdU<(DTW9`hE93=X-Ex?^-*>vZ z_SOd3LE-A<^73SLtnO~y3VQnz>-M4>hErzB4@XdBf%cbwDW_rbx!QdXcxAdj)2dI& zG7BoNtjG=hlJt=q<hyIW3YEI{j_Dff0QL|lZ?X_Rz?=*6f*ETAK}3ke)Y6hHHW$XU zArfPuA<3G|1q=s%3v^M{tqlAvWX5o<$=+o6?72N3^6MV#Q)M+>NPiHMGqP?}^XQe| z&L(<}H#VOAy?)}F=PTyaIZb`@<UiQQTXRdEULHg_YQffmD=P#&8hf7b0{_XMVrCV+ z%ztev<>(B)B&Gb93aC&<Jc;W%o$>nr=FC~Q?loXaPCg!^M}sA{2Gg!Px*z?TEi%HL z-I}z$^Rr3<*Pvt6rYEo+Ubjd5v7p^7L{YP3?{63t?^gV7DVXqBe7w7*DzmG#NU81K zmG{5O+Gd64ajQOk-;BJR&=oJ|M-`rJ{>;blG=&lL0dy0%j$<;RKm?l7%q)JQxpd@x zMHTdMsQq%Q^R)aIf#lkh9X6Q_qH>cc;Xq!tVdh#E&+m-$g*=d7xk2%rYQZ@z03N8d zBJ{$-57HMc3MPKD?d<t!8kYo|%Y`=v{|d|L_;;@t7^w`ENTsWqMB9s6pBy1cMjM-S z=)L$G&7wX}*YCV=uNukl^hG2p-0eBqbwWTmbVxwzYCJk{jT!()h`-d}(wjgu+=IIP zX%)@Feb*<oofP#Co@|_O-ERC@xMll6dNd@W<_x04s55q$#N?(1A-3bdK7+#`@`F{b zGd*)=B#WyTW@)b~MH?$K)R8aaZcpv(KB3xocVx-M_tU%Bj^}aV<(Bf@C$DQn|5iYw z!M-^UrnWygR<-Bm*S|Knu{VKH1AqB@ZKi$nH8*Ts(@cBgBeC!|6VgXB=G<KuSWU^4 zd?TMy5>-QlV3m_*-(i5=;hIvs!*p)x(4Kl05YZR&Yk=pi04jpAQ(4c%zr#@ykr=%R zXR(+9Vm2X!$3)F_nb;z(|FieOE`_k(0Iuqgbgx^*nX7oQwqoQ2MK9l8O2|$WO<4e` z-@i#)<p#s6DbMHRq>qJEl2vO+Qo>|a^h69F9m&z4Mz#{?N%+OVW{!7gcu^P<j7nz5 z47IhNaD12`EYY<sD^_)-7B)%?wwfOcOif5rnQepQm{gK_@YK43oU6%225g20cl=WS zMD@?V1svG@dG{Xcz@e9EZQ)Oej?-3R+(!5f1JRh!usJFpi9$M^qhL>WsAj4vz?w)< zY8&U}k-t?`Aug>PI_rmtEik1!-hX%j-sbLr(s1>vRi3nYZSdQYx5^*HvlpeV3SSz% zID-0|#T&u(633sPb@G;+#$QAxn6IXC-GZ*pT#u*oL&0tL-t6VG=Dyu!B&(&2;2))# zyVOMuK<%>EETI*lA$P$|p{v0slRyaQfvfK-@H)Y3_GX*g7OU1ArW%8EkzBfK5xpu> z6Lf+q>WwXJ2zasFPvnb(TPz^&F96X+9Jz6|>F#srJ3{F#$$=a9{VS-3S_0rd2qfh9 zL3a!(xyc%a6aR~(A$65JI5D7`83NVI#)A@Upy!TUY&?LbKjzmj7~Sz}$`aRDViyyA z!9m=}pn?-i!DoF`Jk-;2ZZj7RrHR*VS}W4(T+zPzV80t%izFj&dLZKQpKm^g<r~F` zc6YC8k=NRF;AZaD&M{h;=4g)nzWMb(e|mePDHsiQGzebz4Vqh;V<3}oy#GI-Pj!k@ zFPE36v^cjkv0br!Q;*gMUAj~sGQGiLt>j7=;TUfO%&{}yi29t3qwL}Lu5A71Bgbj5 z$B@rrNjudY_i{>4!BJ|}Gy9#La|bSVD3NUa4YC?bx#OI&;`r2yCihx5%*K#NSq!D( zL)XH67sfdZn_pf$=3Da^=2@LHJ@-Fl_Agh&ZR8oCngN7gdm;XHoIM)h1Iz(l0jS{` z80`j_^OK8@@}ZVpP@+%dT%P%cqQxD<-Pacc1l*u6(~nUfwT7QQy`=xsxp$|v-nldL z`gtX@X++wn&BSs{8%7@(dRkcLtjqm+At-&{S+31$Oe|E-bBx&L_h}|P0X*cHsOL7# z$pbrr*HVse$v#zDTyo`ku4&+L`rkVX#U(py%LcnWThudnLayLMzRn2NK0sK&1!cek z`tm9^q8s0oH`Z*wY*e~91=CDXFGe1pzU5xm-x4Egli7~dyLrS(PKIYm7PP#GQDqG< ze0suw8Y+AbwW5KE4k|Nmox+G36_k4T=ZaxMmN~ah*D0@Fw)DrH^EVTFiQ1Y<e%9`a z8udj5cC!~#uK#UFdc2`eR%I`%+I=i9lC~bF6eb<zYxds3$<8#6$l3QB^!`^2w}}RL zpn(`{fDQ{8o*Y)|Gfg@ioBMJShZ#Gh=4-(w#wVuEir*FH#oI$pL+>NS1uKH02+?U_ znQdnUN-$#!B2{+R<QiZ~I{>LEx;s*;p)wk__DYeJNL+o>EL(;S+R*Zn5kO3eF2uXU z^}}FB6&1)XRNfiy-<y207w?IpELIWg@_iqCkO#TZMLlc{yZFLpS;MUR@{B6)?CBD$ zBU;}Vv8)zR)a85W2YO1(X&blQD=fg@2U`R0<O0Y+p&RuCn0Pa<{T5w`ew&0cw|&EM zfhy^*AS*(TL|<S?aNo}eMrm2RY5&0`{C)kiVC0P(SjK(-3c^Fq0F($Mq<+xGA{jri zhFw}Mr`P5mI`zS>O4pE!R<ZD_+^e}*FE6`zP-BDHi$M$_B~z}`L$z~RmDdJh-oOwC zgdZ0=5*rdlicSm5XgecNE??1*8CJUy*?8}Jhk5(ye%nfG*;7<*k!e4DewY})0{lPE zsap9~yybF({@xnd16I$0)b9AM18J<D2WN1`y`K*zHwgC~P1^)*aQJh<=gRmhzW3^m z^6SWP1m;xpk!a-RG3Fo7tC#=Lx<Qt~q>y*lkxE&<Zre5wlJZ^8EA7_mD!cmfPAVW5 zuKi!&?QM0odMz?2zHN8S!w<RZQQWPw67;oMG^=y&-T-i&2%<zF3eOFk(Zt<_?-nQy z4Lok+2{X`$zwjd`Alskcw*UIa?FMA|`l9UYlp@GL4W8LGEIQzW>1x_y#!pngvq;)4 z>AqNQd{iXw(beh-dma|;G4>YyxLsG!(^ItjCN>+(YZZm{iuaD%a=8&yl4|Ds5k)Kb z0boNp##Dfx0)Bx10^d!71X6AVsG2*`HqZ|+QUPtPSjT3J&tNox9;Bkp#Wi)JF@=Cy zt0y!ORBJ-(A{2~%+GTa@Wy5*@(_kIzEedQTMyJI`S&%!1HwL>;ALHMIAuc?P05;Sz zM!n}BX@ofocNHr#cM_NcP;C{W$4nY|uqmeLWC-V{`D3K?-lT$SC$!$krgJ3zj>}yi z3f7MP+EH)luxa_XrF`Bm&uOHuYWD#00O-ZH2>=VQg&cnBQ2|Tqm0KI-xefV#Kyk2z zIf)ja6SP2zV#~7lRUxE4058}w4u3VkbR_zSk_mr^UE_eL<7>U5IYz1hr?5fk*CPl3 zdn0NI0<@$Pj|7qzEua4TK9<H(PX~%dN_Vb7I1kp;ilHrld|3eut2~LZbm&NoEvjxs zt#F`KS8h_*$oJ85SXuM{4r9x(H0bsOr8g)uP4{JG-n*9g)p_#KtRJ6L9tQ!w4zpd~ z?}^8)5Jav_sC^8e*t4?`=U3PN#jWEEgUEW1{zTWXaYa6>W-l@ev$6Nthpd(LD$Xb- zq_bp^{wn>yv@+*o&J&*4B<u@pAC8Pmn6wm+!3W?=@YVPs!db#4f`f3EI9|Df_>lO9 zlrZ_Hq-v6$beQys^e<UR&L_Vi4^U*33d$*ph4L3QUR6y^p%zlxsn17#U-&P7ivR4Q zfA|~y9|dd*Pz5}oO{OiSRnZ=eVvWif)i-+0Xy<5TOzfER^wIQL^t*v^flC9k0v%&% zV-JkIGWKoI#Gn;H*+I&n!wfDXgP~%yF<y=vJ8u0r^SHs_jNoe_(?ZUKc$hyjRm=lS zGt=j%R{uG3!OXsymuB9Wd2i;ES+-gJS^8P8%vvz(?S}Uo{?hPK!^&Bo&H4htKqPRX z4j5W=0PWX2MWu@Y6ku#DAQLOE4y=n2#R_p@?<hj(lXo2eMiAD(6mE_ZpAL&Ap`lp> z6z<VxB27B;d~<FbMGa*_y%E4R0>?B#T8R@^E0Ao3Hj@o_tyB}@h@&|LPM@i>>LRLM z9Z}Dds_P;Bb(1i29*t7%d5I2g@`>~_x)Ix;sn%YNtTe|MU*xbda#j1=mW<WY?L#EU zk`ZIx?|MP93lRfeW!aYGlHY@Eu-uY1k#dl>miCFJuVkxI`Ycu1D|Fl8^c3ubLyzZW z@Xtaqf>;7>tt?1D$tVB{XPnCsVWWp(H!+5Gjb$yL`!e(oQOA74FlSFJwEJ(BQl-=D zFw9)7qbO_k*!>!KvlJ3`7LE;S4Y}7P`P<8v<>Y9=6iCfQKrWtNBk0T71NquhCVXHq z;~LUfb0G<;8ql7%W-=E)s6(Z^og+P9LWsYz0KP-s!JELGM8cQVitJTJyn|^_UT_u$ zw(5WMyh<&~9RA?+TzeG~XvkxvY4H}wn%!_ANSK`fdPIOM$R_9}F>Z(Q4eW=jrPZ01 zYghL-%e>Dlk`281c=@^au3o!5bNb%o+&9L&K`uf)Cg)Cm`!u9oP<;8}Srb9nFIPr^ z-H7~9NW{vsIf;c#HJTkb(Sb*QI@ljQoYRbFEXkJbiMht#r*KYsZU(;mAzE_TyHFq% z<Y6aKz8v#In!7w#Gg=$^xd|5?_!}%UrX;HMF^vb#EMgIaxA!<kwp#9Y^g$N!@U^26 z2i~88Vvj@NIk(LK;78SAn_{E26zl6$l!^%i!l#y+3H%F(X<A#s&<vxcsXVgB&69|P z4QLab7O;U$$tPwv*+wX6Q@b|1-G1ho5L7z{&+JO27FcS$Xgp362peh)<PIk4McJFn zpvyzEfmFwqcIv=Rxb(DKqO9H1H+MyjA2DWt5m|GfiL-`Pc0<yjkh2ChqofXqBt@#; zP)W49jr&ghoWUd@%Ax%rcL9GT0*vj7C-EB&{L@Llf1M>O0(d|1-Xu7I-5^bx`$TI- z^qEV$LuL}(=2%xT^u(Q$EFcKm6$!Bt2j;)M7yjXPyEqO%C@g8*33}KSU~o;*1<(xZ z^AyV}QAG2R&ofU|+YCj4&kj?{)@x`-)L1-sVH$EV3=FaGNDu+ZXjRLHq;wPB(M@z7 z1*(EcjFg$64L0V(S_*e0_=W>u4o})@16k(r`>jMK!8A6F(-a0W6kaU$I*`lIQf1sM zNXf{BrX$To=D*hwOC+=$^JH{PCnd7_5Y1~^@sRh)ddwDawm=Jn4kcMr9yh`-Piiun z(fNQCW5I4pG4(i2f&8umxglm`!f3s2cJ6}~bDAb0^!HLhmSSxq+8qnyaR`LiubYzF z?Ser#ykF&)X?93{;PDn^hFH2WyRA+>+U`}3XusmHTw*%{!30LJ7jd!+4}W*?p$DKl z<xcvSyau>+k9m{r^$Dj5(zU5ZWY&G2>ivcY8c~7tiE2_%K74U-IxaUvfa+OwXfT2G zjTHHSBN&wv;6v9|z2`W^=IDYYTl7B1UY5-E;cS4-;#PwXvEJxJ=7OLpQoH^<>G!8@ zPOca#PQINkl^|?q(U>R7-&k^-=)Q4iO8Gz%4h&f1JIbnQ`oIJ!t-G}K6&g+a6N_ea zRd(8+awaey9#!s_^Z7EpvdY+jlXh07>jZjD)d68ZGOED@{D)qRw5vsS%V~bI6a>m; zAUZM}iSj<_5*{^eG@2%^_TK)5@VGI;w7D&<%=1f`_AP(ZgUkj25fd;k3BNo7;`FzI zr86F#XTm;$*ewpFInMuoh~t=*D5t$~92BIyH%fYNYougy;)_F;CXiY#$7USehL|t{ zR_JE~Ex2i*o7=?Mil42xYFet|)aPL{42M~sljC_?%(`&nYO8vpa(s7ackk2iJ`)}S z_#4;^#8xvcyn*E1#`vT5?R)m*4s?9)d*v!{F%~%1JDqzja+fswW$*3&7=94_PrnP9 z$<^VL-#HX-x(KITIc?xW{*cT)ay|tok(w($KSxkcB_Os!1YW^bbfAE`=~@%X8TNt> z>CGLLNr(Q^^e9y{5lt5l$&v=jWrBdXW^pVX>m@=~1=UiG`2E4pOlgwx6&)be76?-S zVPa(ufxk8nt@)@nggKb7VTy46Du-qd9MmXwk8_6jsm2V+JsCma4oT&1D9O@kD1jtV zF)F*k=}`}Pm{wzp$~j^BkM&*DJ<cnee=yp+#$Bel&cyEBrXOUeFW251;x6X&^|N39 z<sRc@duPe}fbkS8e`i!ausL*^@8|aHgU2G^fJbUK<x6J}A7W|sqKA;S11phCBjHZ7 z;bV`H#qxsuoGkIiDd4?<d~hb44xh0i)1a$0?nI6bQ7$|EOwC*fz2L&y_bl+S={&Q9 z3sE@cEF^_N)kVHcFlJ2AgIbOc@{(LR@@`Tzj{_Tks}`>)gc^GQmHPG5U|&`p%Af^D z(rLCuKBDqbW6MGxS(C5>^XLk~-hm|&-6(aT7QeuSDgJ||&n;J4TYu~5i%4Ano>63D zoHeix<!Rva_(vI7GnAA@j$N|x(=^JC)P*f(Q+$!j=Cdi!qT`3Z-F^5Rq+C$pZ2a-l zX_T$HTtg<j(7#CZ>`;f<4CY>U$&L+WTz0lH5aS{*D9T1m?5CG-F@;j)XH&Q!6}xKq zU0oKLdO74X6XrO(Bm~0kTr3wW#p#RKLszwC9OY+Y)cN3`q8ICDS@kqA7(Dy*(Hb0U z?J0*F4#E|+YH{++Abn@$$&Vin#>@JAty|Bk@|9qfTANFeJ?WNhJF@?=lO3)$Pc1A~ z$IJZnn>%H;%uMXb9=&sG7SR<m4hi4-**+?CE6+t+x>)Mccwis}2kp3IN>0`kh*;*9 zyQP2Y#u*-yfyErDn*teTgWHUcovcbrU^T&_mb1!yxj5PVbzJ7Sii-3~QyeVnc3s^E zv;S%XU72iELD~SB_`xg1;C~*zpVc*9d&S(UdTeQSO`6I}Q-_@K(3C}v75R8O(aq7+ z9#%-c4&WhEPkD=94byWKpPThGp&EJb47AV8QXcM`%?W1}mbgu3Pqx%StdX^why^zb z)`IK7)38$wOp->UX$hjk-PYzNs<>7o@raMq=>h>@3{A6QIQ!JWhE&D^#@p+(%!nc# z`m<CwZX#9vMAM5AOAB1&9trMnkC87?t^L(R<#z(d7?C8I5Fjv1AYbaN=#D2Hig&kg zJNUQyX0F_>(jL@mgO&v+;BKTX>gJEZwo?z(qULbft3N?~(F)bIc4ce))?<$T4o6C8 zWQX6=5}i?<nt|R@@~1*S>!!tlYr8z2&O@<1G_CFB1#Hiew~dWBh|Ige!_%Qtaw9-p zY`qR-Ns!nQ9LCf%TgHEcAdc{M1>?_@X=vwAk`{oJP4vHLNiyqs+o*{MkE#L+4RID6 z_g~C54aqY%WiR^a0HG`!x)Z~g@&GSlYuf^cpTYJGX~Ncp7*str&#F&Snd#o+jC<S` z15C)*?cNT&owzNsjo!baOp>I+iUIRh?N{ge0yMsrOJNm^2(4=ED6qUSS%&8720nzv zYR>?)K}W=AOz}FcJ0OoPXYui|)EH_8Z@a><FX6yO@NNObNiT|;f!>g+5j<uNAH5Wd z#V-hFXnN;36(b<$`|%VQjuK_hPG#0OHrROx6#NxD3xmZQRE)gwOf5ZC@^RPPj;lMc zQd+GPp^V&2MWpd9IL%3s+G<&QU#d-kQ2VKZXl+8rPBC^0(*vG^V`}XyIl3TybUDe> z`$InT>EvBQU0?IvWMU7_U;7N*0M7P8ikClpgyVc^3|BiL5h7w~@5kp|yYwmV#QWQk zX6Cb3&c~$h{CH^Kg)BkM+Xlk?9FsYcqh<4D)gTzc`>el0G_W~kPPXMjII0i0B6AZg zEUx^Gdb{2H`)_cz-&TG<0T*lpW8<7QI0)nBp_tL*A*fTg<IFaaT7Q%s>RUxDhEUXQ zJ~<YM!BFxbc_Bol%D82TV+_MZemIhC#W24u@l(1fh6lX=#i*8hDK5J<7nMYxBI2)O z_3{alOh6WaE;eN#*4v=r$Oyx0Bzl=o){`E|nL&}LlE~y^z_8Rctv=bH$&Q@2$s$d$ zAR>ehKX9pB3$j{mhXpAFkRY=;O#^36aR#33QT5@EE$nQ9qi|zrxMY~|@QSd<#g?r! z^BH04i3($_A$R)$aiW4P>J-e4)Sf;p>|6~YE9l1aNvwwA%Nf_}6F+z@!kiEWM~c#L zirr?8QNKVgI}-)wbh@Xj>^U`#^ZIc_s<6U$8cQ1O3?eazk0uzd@q{c-ILq2Bd%XS2 zW-{Dh_i>6<$CzUS>G^nPu=Ci2@eA7&nny&81om&PGL0Y1FTW6r7uYiI+L?(=!8Lct z03qHrPxpf!R|GQ0z8u`TkG=J@2-*VdAx8unp*710WL9U5D5zNXlj!$SF?Je(G67vj z@V9Fal5F?QkW_)R5;haD2+?8|5PlN~?-6*e*`J+q_@NWF{Pz})zdxZ{J!gh-MJR#< z3O-(D5|Bh8e0|`z9rJUU0zo2#gOKeeJE$HC=U`^SA?<q{SB~8{O?$$KR6@p-1wj?` zW14}UhH%@Ck!wwygX2KT)nj%Oe*9MOht|445s<+iE#mk5&=2l$bl*|{E)io)dO%t8 z2;Twf&R<A}M9)ezc6oE#5~e^Z6GK+t5cLlhk`Xmc%oA_Ok(EOd2F!exbw5r~)+$+K zWO$~v3D1v)gi=WlWYAD$st;dZ%aNN7ahHbeRkA`ORWFxofWeugA?v284RvsLDH2de z(dB*%CfqbIhRV5gkSC^rXve~|H>41=*pTzHof>-;VkPaVYtmYYwDp3w%cqwDYkAQ* zDVYG_x+DX+kx(NHrFpO{MbCgs7=RrmY?@Z2)s*-@O$3XO8Lnt<de55mx@E56eKpV2 z!EMN{kjRjq9E{QS*W6sUZLszYCF}YX$lT2HW^g5Es-7feC9voxmNk>Xzm7!FLKT_U z=yj?tuIdc92@csuQ+X(BPrT*k*p|db$c?Q2tbuO3gpJS{N&J7SzEALujsyDf#rAQP zG7fHzmB!RR;oHQC;3g9&5d{|v8*7i*Vbqj=dZH@0fq?KeOvHI%G1ViXAjV`qMT<g# zv>1qsBv7U<(h$;-sJ>uww9F`kG5BB>|MR1|h;iv?2>Kw8CvtvZu(fuDtx5kR`Fu^K za7NfqtspCZtWNL;{XTX$U0x))BO&jMN3gjVRxV&q*U(7Xt5xx2{`{<<ukSmjFc=px z;uA{RYRCQ^cQ|SF+Nn99K1?P@-*NGX#eMg@X5yT{lb44^J~QQD;V#JmT`Hw}c=$u! zO@|)nx0vC8CQ^;7ciz;QLM=G{&gj7{=|~FO>4D)mThdxI*`5<Vkjr($%hx2N_Smu8 zGWA?Qku|sVR)k!r6*pFx1f|b+FySchz46Z3Z*kmSqfg5<6EwpUQG2D2dM9mlEf3}- zOzfnxBZ)y^%lpT%marY7M_5O(MWjTM)h|u(1#KR+P~G-5p(hL!AwM4s?H;1AY1K|m z!!h6L7fOA;+VP~wkRS=njUpsWROy!n!FJMV8l1`F-cxP!(DcChtD;~+O#BoGR3R_^ z7Qwte3N{l9Vd0QCjSpfrX}c!`x}OX_NcjTAJEcCidC4Dv^sh*^1Gym-&GHhE(m){C z1E#<^bV2-`q|OTD-pgZZQMDm((|U{W62ylS!K(m;ItYtS`9U%fwr8guCEl)R-_N%x zc~*E{<!j}J<Ra3542}$0WDY_|3WQ{$8n)8zW-}pt$BBr<<vSX6fQxAS;|zG^B0+M- z8Z88ACdN+K)18Oq&4%ZT$K=>2W(7o~__XH^5@6TPTotbzU2fJ72DT!xF*TV?-c3Ks z<fynT8{zQ}NfTVS%F43zwXIb`ZYW!?jd=&Zw7do?Ez;3E`U4TbXSFGvS{Yc_vKZ0h zi{YRLo|*TtoJ!I|U~Q`4&=l4pNKfU6F}+R-N>fY4Z>}nR=T0j7&Tv+1Ej1CxWs(@k zhPpu^^1OA4y~vwI{u^C?$-}GLtOF!s2V>DzXEN6AkNRxG{}BKbCj&`LlULIi8umv? z05Q&}CP+;hsWDkaBpT&~T_SSm<#E|IWO|?`1uh#6-K;u#=)~2hF4Y@{w(jgXJ*-p) z6CyI0g#o*4pQe6%w8TYuw(O#99kEx-%U`X0O}zrr`_RB*aF?&)*f8Yo>Qt#ZjMUY{ zd#lJ(7t=8lk|Y%agls#;9`43E{9v|$wkd!3qroF_UgPONNNeb`9s<BM&0tVep_?sj z_lX~+Gu`V7$H!-GKXusJtWzldZXyzUUc;F46GwBHmdZ2dxWbV`JJO#&%%0)6GqE$N zo7^SEVs+ibS<U@irS<sL^--T;RH~G}EPfjgmb^2Rgc}(Q?gqvJVNWAh?1_J&5~MWa z$+mU=#_3c?8RM#ipm1m9!lVs);>;?|t;%QqgoS(44L{XfLDNk})T<R9SuyAJjMgI% z6e2mb2tn=YjU-lv#^>>HY@5P1!uetBjvpzXROgNNkpPm^(Cq8gGhkR4Fnffa3RwVJ z(4f@@D~lwK%|lZwdtI(dTQ1wxwv|=!AfyFbCLJUYo4e2dt}BMM$0DDrH6?%g{EP1o zA6R`p6b_q6kWi@2qKR3;W_l(=HIx;Qx?veGW6w|DHF2Eog7?co3};Q_1hHm#D}LGU zubW2Fjl6m*3T8|lp0dR1^Bnegy;kDH!^4LxQ-NmMo%U3i$Wq@HOzi~(=c)$MJrA4a z+;atKj!wnSk`v|Q1kLK$op26rR&&gW+`#R-_l8r;j~BU9E1Kx(M&UJoJdJbP*RnZq zemr9G1mDYkym&)(Pp^L*$#*z_Lxyy0+D6*NYc(J5IwRXPp_W8Ob`>N0_YM#5>FfBL z;+m+LKBU)ikAu+2syUa!Nnr#c{BQnyI+IC|3sdDKw|sXxetK$+0l6XKCaQ_Uae;mg zu>ry+CkUmmpT2x3#u4~%T(I?q<n`KUq|V%Si>MfpNaW`nsVIN=o=f1`>KQk=9F7!U zyAD;Y+hBm9zD+}7zdIDNm`5h+xLD2?s>*)#vjx4NgS$V_XcxDK<Cn*0O`4b)WJd-B zJ4`w}@5v=WufkEdn9VI~I%qI8U$>m&o<{qrCMuI+=Q^iO!*2~Qzp9bN@G4nB7so4K z4#Pg@b}v1CUy^oI>1~lNdnNsw|4w3?*Ik^utO=Dqr*=>4?z57;|7Bt~wX>U3CHk zLLkc}f@5;qfKOLEXwHqA=;9Wc!t?iIxgI#!K}1vt*0S`LY#b1zb7gxx%{3MO5I7iJ zK5DCocUzPquod)|RnchQZO0_<wU}{Mt`ju<22R0q)K965|1NAW_EmP}Tw+V=TLzCl z`iEW^G%*4`l$OTMcDdMk?|D`bxZ?T7Ve{4TDgjk`vB0Ag5!<WqNiA{Q@^Ar93#wgo zPkY&mQym!9bsZ5&D%Y}39O9vrV2ULUPl|<<y5e>O(V<D1*|SbuIDyT8#r7%(m^O3V z6qTN@6*O@<$cwo?di`mU=vo`tBV0&3|9EA>fQk=K_U!u<ncb~gQaf|BZ}q)Pl<#D; z3k>DG5MS~VGUs)DCXpbKMQ(i8_DRF{BwI(Z1IJZ{N`IZgYJydNvIx_!^g5^Of&wIt zdnIXP1sYz9HXP>jDige}RCpNZH$f66QqP13r|N#$jR<L0x3?~{B6s!#%tScM?s^jY zVgTW_9rsn9V@W6OIU9|x%cR5&W_2YcZBlPR8?mbFwgo?0VJL*s<<q5}gne}m0+457 zLac9x#cY6Ip8+jvjwgmjJ#+NgcVhk0k!!-fRF3WK+899yeO$B+KgA1uo_t3_$SAp4 z%CG4`;~JC&j0lHR>nKNjxPO}k5(<{AG*uB+@Q<<4k{eNKHH~9q3GnbyFlZuTp4wx8 zU|nd?=i(UAv`+oJZsOG+OX2(SwszQO=^eS{+NK|<v*{>uL!!g*(ob*RT-^!LcI3za zO#w9H5Z=LK5F;W963hk)Dl-IOBr%o@qcGh-_}6x-_E}yr-RBM-H61*6%WgSGzbiej z2h^<AB=yJ>{xvr4S0iVTvd@Awi+qWNf%z@aZ&!}kT)=@<&`}R#Bfj#nN_D;p`{~{2 z1gey0lRq5skmnx)V^o}MSsfqMPY52!DqE_q@E$nw|HMm>Fe0M}bQ8dj4-akB<7NkY z2bX^RAdac7#d%4;N`fUqCmku_A09LQvCQ?4&~i7T+*fhPca^p_SZ0v-qJ|)AXd*-# zN1p>U-4z#~6X#QpbMPz~OD~DZy+u=-+D}sG?B<0Qu|<w)<3Q{Z7NBbwgy&1O#EfbA zEO+L%Bu`)Mfs>+F)HL#NBU-Ol^Gd@Dqt`mqUPyN4M@4?3#UBqpbmdaP+@tDpB>U_D z(2w`to{dgtrrLS3m6m4KBd-hI*<cN%D3heYBm%GGmn&T2{xUg;<Ww{-5HPNIlayOr z1FN0+{)<Hq)0uC-Q;prXn}k4}6lo7jq=`H}72MgR9ek2J>q#SO@Q9-I?e~zjPLWeg ze$e`JWbTgGwHFbRxgOEfdZAQxVSDXeX9GAm_tlme->kIe36mM()@X!#31=w_@APa$ zN~>P>3{aZL(3`=&sJA4dSgH2L-RB-yzs@<W7<&K~BKBtWwq<$r^~<qna4{LOA*mFp zNZ=vLDXt*yUBqgGoL4>ppKpj*N<nHzENU<-Opp_eLl5-ULCl0mr5KCf2Xu?`u+md1 z7TGN<>ZBEIA9B&{`ENs{dYQ5(ZE6WW;n#9<8tP3zXl)Pwp=?64!r~!XIvi=$5QkaB zH^LustXsDdkvfk^IS={*mbQoE*Rsh6G<^vd;5{Kk%1i3)q0EBgjO-pdp6?#cHqpxD zK}TkidMSVH#e($pzKEvd=g##W@@3D+Y0P{Q61D?dJinCX^r-udOg8&{Mo6mOBH!Mr zAY&M*sKRhw#uZik<JZyg90%qThvL={;UW8#<)Kihzo;@DO>_y5Sgu52F|mRhB&)!u zgR#aGwqUV^KS_?CPoV=w8h6yK={5Jy`SqO&o<+@Qjwz0+MTV$+XPVtY?k}v9=jHKY zd7)})(s(xeR5fKe^Atx=AH`64SgUjZ=VZf8xPE@ZXe1$NloC!9x|@0Uq-6n83S4+a z#WDqDwKP-XwhR5m{3f#w0C{nAwV{MrRG?8^#&%7TfC3*5tTk!}ynt;Snpn)_Q?)c5 zymaKl7~&^*A=wNP+X=<xpjhIfHn0KW*P_CuS}fW4qnFAmL!r9q54x9cXRnJOo2ZKa zc0~KS@=D$8x_R&M^?crNT0C*&aD>JLood}xL~Ge@))rB3238Xm)H5DuJ3l`%ty<d~ zI}-mE@1YTzYp|bHe;S$h^f@F>>i@tYr7|TKdII$>a^@cx4B<~aH)}PKhJ(vA?em!k z6K+szME16wf@_wKw5gH(ENSfdGs7}pc41zNp%q$g^p#O?=}{Clksvm3<Liy*nbhra zf!^SW7O_~3+#B9zhQEds`rvKGkyTQN@e9K!&@Apf(G1>4d=6?zn(2vv;2J9Sb{VM5 ze|K~xs^s*GHR8j2lgPerDb4KW%5P@XYC)QqbJo#wCjR`%!-00}D%UN=Q8BZbC8&2> zE?M)y|9$shJV2sROpm>!2I1_@O8Ck9>+T4qXbza|_N&Cst5AM6DJn<P#H1q$3Swu} zP0zRoW6T;XT0C<3@_FtswsTWTl0q5h;8xyLPkIKsrO0I+%tm@HHwwhY0(ym11Rk%V zhM%Vhl+lb(yi(4}=1}>{lcx^g-8mamQdo3uN#L&}@F{WOyqNdzlW|<>uyONe*>vXY zW_%zhqH2T{x2<AT^qdL4zO*a*&{SjLYalC|>@Rbe@DP)aMsOmQMk}`?nBFYr+leGi zeE`zkJ~a9bu!od|NE{}ChFe;rVOazL>(S;4sQMRwP5)cN@xvF#-Z2u9nYGare;r>d zPVKVP&qs#oOyc+}U+)PZ)aguRDs)CqHe24k$ABk?e;KibutM2LOPE|DL*@h2hJOhi zh-j-_Y<8K=SZhzk(Q%+mnq!lCe<Y>Y!(#vlRH1ipA(8<n9kGFWVgOptcQszg@c05A z<+s_rjX`l1CU)1+#Str;KNH!Y_aRg3!3h}qSFC>lL#-@@NP;ofhL9VRM#|7?BvgWc za}E3W*nx{KN0ZDJt|T#!Q^Ab?Gl}!?W(a0coTmRL7&%nR$CzW25(3L<L31F|yEXPq zo7sP>^&_i1PR3Z!k22*UX__Q05`arIETJ0R@Ik1kN5AEmIN`u<Xc<hAVRLKh-MDr| zd~9hi-1KTT>1j67?8R+!=tu{5S>;qYw;OOv0)%|?yy=K{b)gG-)yfaj9yg<82fZ#M zLO-g2^oWjS+VpRc(95v}HEu2|4xDp=iw6R^-0|23GGEgQI0R>FITq7m&a6PO#!#Cz zg%(ugy^>#^iut2HLQ~!uEvQDKSOQ-h7WD&-8SU%^cDQvu-K$JpKF7sbpRbC>sCI_V zs@Q#)8}=u0n5Y@3yfo<ZB_`jvf%Rr*u=B0~2Lm_Gv^x|$M5qlIuuo_hm{O6yCHjVX z4$!1KKJ@3)KkONL;R9A^9qNMtI|^)(+HpiUu?<L*o~=cA95Xei4E3@n37K~DpYWd5 zNxUjUkK@K<$;+5UcI}c?VKTE&ZwJN>1)RaYW^Q706CYdNG?@_s?}qcc*}{pndEh*^ z217~V<J9Sc5mCSTCRH|fmHJeFy{SJ%#>0{o1HI0&h;NRUO~;q@Maq9LLz#t~qg=^W z#lic<czmzLi$npYN##)-+p_~Lx5#E|_otl-M(`hH8|kDN{mwtAjyIlHk8aUEz7SEL z?q5D`(~fUX>Xwb~J2I|``gs@&W_4`l$mM6@@MS1awRE{Nt@-Bz2Opk2G;|KfM2=;7 zGe=9GZG1m{s^>&?@4yMTNUeg3S?!Iqxp$u!c;KE+pP~l?$3E}y*?DYWaQfoBiot=4 zTg~#qkR2DG-)(q!wH<-dlOxNe)2AzFoylZ<XNiU*OXk&&rQjnVw7$jmJ+<9#l<0o8 zz6TvVQ5le4rXvV>C*??|gH4CISnk$buzZk*L8ZBI6A}{Z(=^vDi^ws<GGmccl_L|A z=Rzm+X{usIRkw$&;-xxW>8vu8-BO_XpjZ3-P`ZIg2f>7y&3M^(Y-Q{o57b=sU0uf4 zpZzpPL)NY&u@Bnnd^%NVn%1YzZ1isI)72tQDIswaScC>P3l()z-Lv>EWr@f)=GzlK zns8wW@faS8Vj_L3pUEKc%w~4qsy2ofoO8a`Slqh?pDtHj4sjwM+<T-fqv99sYmzUM z1n<b1k!!Et^ZjIU-lBP5c5}La?Mjd#x0^1c79IkwKFjI!lc!lt>Xy@jzpT;QItHez zY3hTIm|mpjN_h!=Q5APuTB%-0I?Bbb36_MT2(x-b`%)kX(8I8b^N6VN1eYp4vrrHO zjNfX190lthAxfI?gdxWW#{?IQr@d6f1_$~DROApPbo}1_#Sl}x{Y6kj7fTI6+JLMR zxherimuOeVMQ09eA*FVnUVr2Ai+Us}HU866(FW5Hd2PQhbELH!`r(<rUKnnk(81qq zBkL2NIs@xl!GuSm1ui@a`2x(j(_V{bTqMaRF3E3dBl!rEt9~``nEwUiYJBJGmgRNS z4e0-j{S-r3PpkpX8u<qGy<*N_0$INIq`u?63W48tFnV7N#scosx!8$uEm`9nXZd7Y z?mp3HPW1L?wj<0|3)!JO87+CGp*JkWqQ_{R(!e#lkRuabfa{Gg%lZkz@(Wr=f5KXC zP!vrEv6hbd9XZ&wqr-o~7XL2EmiyQ6LN#iHJlcJF#FQE#9>%>9;(NB!``^YCl0PKf zmnLzEElQ;tT#*nNGTB=^R^5s<P^`{LkBVoI$jkx_Y0dfl_4CuHJ=F~Y0*~n2xN6z? zvFx>HupE-LY#{)AN04+^aaKkh>jB9=Sk`)917wFO)Z+LFT9t@qQK_8EEUEN50jC65 z``3RXBPKWcIsM$ijJ5m8RjD@!uJ_jYDnSA&vJ;GCyb`@?)qt2mTDIw_c6a!o-1s*i z*_T6ns<(te<&;{mY|0U6o%Exoc5+rN8&Y-KI+{;Y9Ud?4E$9kuZ}fDxfDc&CaHm}$ z%lqOv{sj}A5~!VJ7u{b(*OXt;UJ0<Uf+nyeBHml8-7ZKUH3<5NyqksOQ+NOt1E8_t zu<{^@@g|~!#d<<7{;3g|!{UHFsKgQg1VG|{C>dV6<GsqthsqKs0KnYO->L%u{%}d= zx8vS-2q%*72Y><w03hHK?IqVpf)JBW1~3%Ad!q+3JgY4SYju|*^I!(RbZ3Oj`oXX< zC2wznu3lJnM|~MG3-;WD)!l&LNxEUk^f>;-MT7gKHN6eit^$;Ubw(1ma>9Fjm>`IR z@B~FcgrGpRINh?NfO1<wxMgL)<Mu$yZ96?0O4TCMry$!SWT47mfpu&~O%Hg`>-r}M zVC|Dy5v&6Z!Av0bh?vSAagPcJ<GSe-xEC9Ho^oU+#pr5kdm0d&B51WxzY@X04esiK zhOSl9(GaT2kh)4ILWNz6mfDP#j*20fZiQ_?+OaeRj;<y8;4mT^KeTHWZlq216|j!@ zjin$K?ncu<4IWt9m0?*;L7A)uTU%JUErBArN=%7+Km=A!aAqJA0pr8AE*tyScqp!; zZ2iD7fw9flq$pl#9xwp+coUPX7`|ts)QkFYry0fV07^ji5*#Rb8Ql1=S3(3qFGno| zuZ)ct^(v^P(k*U8$$Tf|fr~DBy~wAcw;W2E^!lM84_}dUOb4rMVDQ#JMPKyRK}|=! z^-$8w-c=~3i>qryKD{yyHWW~rio;+b12%|MMVAeMO81eWhF2#(;}ivd7o!78LfrFg ztf*p<7*ZmuKNPcNee4)cq>qc3b0{5?%nvA%m~@?(FmrMmf5Gw0F+~&(sxNC3@uW?< z46w7<%<X|9vw1vwdIO>p(lHz*H+w*xHml5vr1{nOtr@Y=5ep7ZV;826*f~)@6$rKB z+^m>r&Y}4j^R_u*=F+X6i*~J;4E@A@D92LZ)lR2bIKJU6$Nd3LoJ6)D4L+a{0m`b3 zXYnLMl%PntpDT~=`(WP#JS{<#WJT3<!?bM2^#Blp5fsA-lA;;*@q_=A9509xsZ6d= zs?-{-PH!-p%oeN7?r^%?9<R@D-+@C%j-5D#F)%VQv#_$kow>k{;Naxq=Hcbz7Z4Oe z3X6yWC^QC(!xM-kG6i%_6@$bjB&DQfWNC8pF1logD%DheQbVoQPP^36(9+Q})S}OI z4p5>Sp3=Rem9Rm1Ijn%j6(k@@NVjK!js{1Y=s@hEhmjLtN%`acFeGI}L)1)B`pSqt z`n*=JG}eu@R>n3vk&#DVX_08<{jm?0z>Q=BSt}x2oEAkdB+VjsrCK`fCk0DdQ(9$K zQYlW*F$aFKptvDrNQ!PrJg|fHfR7GdGFGNUE7O8m9IAr>B+c;H_)D3h9cfDlGAi}a zG1xS8!K3kerw`s7{Q&Nr2k%z^7gMA;KsrhQ!I%Oa)$Oh$ZdwGriZ8jd-vj^vW`+A= literal 0 HcmV?d00001 diff --git a/.next/static/media/51ed15f9841b9f9d-s.woff2 b/.next/static/media/51ed15f9841b9f9d-s.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..49132b59a02246ca1030cd5cfe522b00072a9bca GIT binary patch literal 22524 zcmV)2K+L~)Pew8T0RR9109X6~5&!@I0H25e09TIy0RR9100000000000000000000 z0000Qf+ZWCbQ~%_NLE2ogdqlCKT}jeRDn1Ef@Cjj5eN#{0LKvvf<6E+fu1k{HUcCA zgmwfV1%+G(j6NHllqJgTBgO52`OErkv{49b9Dv@#HjfMh8wUb<_}J|KKPSjBMvT52 zsMc4COS+?5x`&X^YH`9OUoy5{tV*un7XBrLT<y%uGb}YnR(3`pgRo-+a>bTM$KzUw zD>c*Vuziv`Zy$OgUW=9dQ!7f4-99uoppb4mGns+ZB-1X^O|2h&XFCJiM*bux@Bi?) z>EHYE^74|rgctIF5CS|gV88%R%`jrX7l@i-#DJ+rixO#6YEeO{#fnM-Ygxzq`5UKW z{m#Qy=jS_5$G2?r_xShQmO0K2-?5fiT5X4pw$#QpVno!C=hMGV`-9UODV_D=*4Y>* zxGqQ+5V0T_%OGPJ3y?uz0Wua?fPhTc{<W`^UjDXdcz$mGN0ySK2Mi09krq5s2W%kV z$R4e3!c?M!L5sMN1IHMh#uE@^2--wFxx}L$>b_#n`uzX&ZvO8xnS>Am#?PPI;&;(o z?ydLtKQs9dski0z`dZ%K_xro<`u%1m0nw&yth7ao7(b<{jW%F}NFxmzF=Bv-1BR~y z1PmdB00TrAXL$bojh(w62qeY`j4?(rB}21B=~hxR6@!*)3q1ZIZ~tw(jV-b+3nXBU zhu*!t&S>=Bmg=+$U<eOHhSKgoHh?@u*A7RqI&6sl(ps4;_LIpTRcSK*us}GOly=YU z_3gU?OJbp_7jz5H_xt^C?eo9GbRrc(5xxJRrWf~+84`&m9!;k+U3{<UQKv7cua|6J zk4t?$cWk=dKmGUXPPV(&7D6_{7PbJ{5w>h(Ti?h;39?a$ASw|=Aqp`>Kc`Toaa#YP z(hU87YHqo`3?9O@`d%gJo}T@LheDr_v&Z0k*X%zaRKUUkIv@?i8w+(qF7et|OeVIK zefP_xb?u$I0V;BPvl9k&U<3{^!r1<Q$aX`Q6MR7b7k$75vSxLAa8`eBs@eVr9C*u% zSVcHPj?kThLeX5vm7Qxh-N)ZW*j=u)0Hr&Cprpmpv=*RvT4D)l0g7ixH}nyga$GD3 z-x3h#K!UskUCy;bEOY6ixz^5Qh<%7fb4_a(on5;u+?FnC`_+DG|K+6wSGIJr!vBe~ zHRdP0^GdX{1wut+bd~8u$jU-llj-tVOg|3cM29vf7_NgLI3&(F>>GQH-KXa3W$8PQ zL_?8K>dcu9ru}3lb!OBU<1#MCQlHV8EW>5>shm`eK!Vk_m;EvQ2z+kr{JC$~g&Psl zfJ*!B@&L)CYNl==@JPuaI?_muXIeu`vvf2koil(&Mhw~{o8~Q{m&)gsfkuTiT8=@N z5V)0~kqv{kTf<d=M(b$g#Guy;(3`Mytq|?CLT|;<+pN>OB<LpF^b7KISQ`DN^0^TJ zi!kE>tb&Ly0D$<p12q7|j=jOCkjjW!mJi^3Kp+4Cr0Jg&Uz}?RXxh1nz0!+&<^chu z(^5f3_`J(S*b(=O<<Na3wIaF^Xatj500ck+fc2_H-x~>lL#X>x!zOPo&!(<bU#1$@ zeWrUmB=efpVlvL^=JQB(s_GB;?*|&03vefpra&_fUxKaB{BW5KaCm9(ayEPQoaNZg zUWnZ+a?GURoI*WZgD!#a4#i?VHw1^?JiRp7-A{+CGj`gg?gw5A()7+S(8o@Sa7?8@ zc-OX~NS0)|?v@-j40Sd$^!rJdCb4yi#4k?4*}i^A^t#`1X#Ra9MQD8Z5+C~{Pl-9; zaU{|pAKm0n_icwvl=<1>(0%1!)?oM6`;JQx+j&fK-0%IxB!2=v;4P!1;n4l?FC+BV zFNx6zK8_y)MVwVzN#4Tn&l&#}w04g!e*0VcP#J`ue>yr$|F}c)=6%JM?+0;=;PS3> z)_wvuDcWJf9;-~Xoj!>|*!K8pFdbXmSR+`;N!J)24`(^0EFdy-VLk`$+A)%AnDyYZ zJ=;@9$FiDO>sdp&$l)=$YHl0mcA~$B9e+cd5~TzcDpesu?o<}lBjPp)L`iZrVaL@L zTu^-3TdqoIrMD^+E`fXQN!cvS7lwGCw~?;0nAQ5Q-fAyFDpk>UIf2CT#i1w%ZX4ou zz>gi=nat<Zut9>mh>b$rGlXWoKsd00WM|J2od8fEAV^RE$U#631!(}OWRf_kM3DV} zgwfPBVs6KC(#*hE7v^^SQs(1j3N5$)a3!0v3ec^U%8At#AA>XGa#Rd&y~;}_O_S#3 zjO>iLU)1&@BJ$i(q+3o+Q+`!QhvyhP!$`I&g$z0<p$CN&H7dhcR&6S4;SDOhQl-~g z=VhvSPOBcb8UCnRf6*3Rs!-zxc}TZfG?Q1=>j{V8PdV)``}yG>gyp4x1UmU=P2KId zTv@gHm#go%94t~lDN1Z2Lpo$o#c@ntkLL=-SsXwYF7VjO!=tr1x^P&#G)8|+fCmgf z7Y<~;SaW;>Ky?yfWBZr^0Gru3y?PFP-!-PmJQ)C|o26G`PGplaOEbQI`yT*?4B7ui zAOO&Vk?;Q6F#N;eKiv6`yT7^jKllIR;eR~-pQlHjXYc*(i}H7W_+a{Q=);jOKfL|T zJKvl+5H0^!82<&3inU+*`2;ip0s;^KCf8883gnwXz6GS)K)eHlyMVtJga?3q2-rse ze;Uvi0DckhmqC3K__u+5AJne^`w6}R1P}m#$v28BH-NV7A>7Gkf=&7fJ{cfP$=d{* z3=xK82f-w}2uQw#5^@wJWFE!keo(fPXhP1StMVcmR-jm<!#SwrWRK#AK(CD2UKzn& z6KeOQU*f!7e+DEW^d86uB(Ys3i491pbV*G)PYR|>+L!aB=8$`HRC-Hr{ZKHyH9b-} z)ZQLcZ%>!h85U(b3y_&7)k>UKx4b;oSIT24DweUnMXa5j+by?KDbZyhjSM~?7>vtp z4D&J?9bVnKwXRNc&&qKYiX2_0^R+XdO1R7%7)>GtnQU!=eYv;ia+n`}uu`WxOaFAo zgO(GiNlOD_i4wojW_78GXZ}H1X+K+>US3H)6n0yFWI91L<R7oK37h)wZ;735E+L|w z3M}^ApyOayA`${9Zu`vue0-WC`wO--LEa#sNJZVgZT%y-ich1ON$!6MS86mx@$F8d z(B*gxglL4mIaQ{_>yb6f8GxflF$q?yy>C1#J2#F<p?k<40Dwb5h-Z(D(Gx4kK9xv@ zNPzg1ub9Q%*~{<`U+ZUYlTYlkXB-DIRs%n1074Wdvl9VN(@FFShBdu0Cu)6J_O&dm z>Qntnbz3D#Mai62*=I7;dq(w^D%MlKzAj#8B<=wL{W&Z=2gP$%LIuV%(W_lp1gynn z;E>iKD&}oGaFq9AcE};8>7*&OLCit)&hT7mti)P}V?;4oLe$4;NR<&Ks*Q2+x<ufy zg2PK&-btDXi&(WLsxGdjZG%gLO<VhYPfEu8zVb}0lg!#H?@6&9aTX&W>z)FIio|%> zRW+KXiiafX>|q$S`;}lTB_^BHT2ImQf5>1&l;4pHv`J8SLB$9_G9aiGQv}F!`UGQK znu8TGAOe{XM_CcV56FhAD7RI{i%Z7ILqJKg2VPsx*(7uTz&J=<3Xu96K==dzM*#u= zxv_H+x&+9+9LVMh%7W?jY62&|xO-6dzy0FUswaQ|;)|0-0bP-36B=cS;<A@u33(-M zaHe3dAjCjx6ovC7WI#qFMo38#c`E?PxK0EDNKxjCGPj5jkd635!Ye1uV6BX_UY5jR zi$#uqj`=>m)J(csGp_p}&nbcc2?uISm-?ZIkm2k_=wDT%7OIK?DQGNJv8)4vZA<8% zR9%B5wa5!N)`7LRe#tyZYjz!v2UjKnN0KoYUG6lYIIiDxxDdYVjdnO;;<2+QfD0p5 z5WwL7nQdZ8_z?Z+ixOv|E|8zVIR4_k8exg!2ErpybOQBhw!y|`(utsjPo+EIglsUD zC=U)_B*cgtbuxz9R9r>7aSy|-+~7{_V^{NQ-tP+A-^MSwHQdPYb-!l4P+uZMKWnTX zw{6u`q*JI}o=2O&aE(6jX2#hhXQh0c+02`FaOQAJ8|x#|3AM|SAN>yki}b~=6|XKV zlN3=#Uo!F(2yGg0yvIDYaXD`wf{>MMTRmbl#Md?B>jnX}o<R*&@mzqBf7Gd=LBU0U zrB&peg}c-FjPlFD2|U&j(Z*=tC!n>fVafX!#b!*{`+y2Oq8S_T9Wp48Qf0tRH5H+( zLp=i!!*WLT#cYJ|xh={tB;-ethDjo!tm@YG6=BHns9f-NLGlt|AMTa;ys`OF!2PTO z2jSujL;vK~F!5(YB#}p|g~<nzJvRo)F$z$@6Ixo%MuG&xy>ECv|BO-;c02kX1Ps%X z&qd?955<=;FtiQ|cFdQY4m=L52!TKm_ozUR4YeGN^6=@(m8K-WiB$Of#r`Dk&`wt| zJGOr^<7~Og=*qo+1i%oa5?jIW4M}NP{kLP9(3a+vQdmTxTE^8F`z19RZo?#GcdVEo zhkM&*X)Yx!A<Rw$l&r*k6E*P(rB-?;0)HEX5WFh?qJu{gd<HCeS+PUEFfIwBQco)a zg_x{ebE%sc5*B|g6uA}}A=8TE16!VJ+Ia@7o#vprWZtoEQN6GN5tO39A%cWihHau5 zody+KogUXRX+Mk6OA{AWG{A?1U2x)a@Or{SSUo9WK1YJ)?<5n^C#|x5<k!QWt;pMS zWCofD@ChCKPpSYWeib~V|0i5$QzI(}Kbnk$uFcNFwwB$}DyRjI+ybl{uqP$4n&d<$ z69)I<mJXr?Bor=nLHt@5R7=sVJPN5<F(%Ax$xX;=Gwax~nlLClkn(+#S1YwqNZX`P zQ#U{3we69$MX>|B`~lU=PUTkT^mNErkMykKkr*Sx!wTc1n_mgxk6ejl<LB?L1d=rG z0w^nqF-P_GP*02h5XJ&YQX16f%dJ@ue|)Qw)BCjPxdEbAxULH;JX>~9mb(~vS#-%m zp~&Kngi@;)6h-TyvwIHO{-w8Pc$M6AUD9{6_UN8~<uk2~ThXIuy}-nns5w&1^?dKj zk4*=a7!=}TEsP^S+PqTdHuEcwDhiW$AD&Qdz=W5wTi^_SOOCffuu2ITI~ucv#M*^L z6j;)!3iOy0=^60XHXMPe<HbTLW-;;eyty*0;dj2V5|HRpZO>0Gn$~%f^eJQB&E>AY zvrwZVo2sdLG9Cm`?z!@ntDkgvNoVcgP-bODe@SQXWu00Lk)ff+9nJ2nCH$0&@gNF> z0X+}eN^M*G`%eFk)~Yr7|MheG5D<@*yC*u-JA~|x6CS%~UqIU8$V!6;F{8N?V}U3j zO-vtl+hxqE1IExv4BQr!?xuwAa8$0tkPdNUCr67if`F&g0LCUIS6B_1+svD&)(E$R z?kiL9A8;zIH6Nc`FFIM4!@o6EIENfO=$$SI5d&nXgB3k53P#?sQwPpID_)zQ4U2&@ zIkjjdLeL^p${YA*>}9Pz{K=2><CrE9!H4!^>6|1ko&D5U`7Gf0BXK}5`5p=!LjtXE zDBM`Pi#Px?@f3u#9<K>KD&m8y>Eez*TO@Lba2G&ylK<ZwVPw!h`aK0i008-Dv(r(F z45z(-Odg~C{^ceMHVj}65V=?gTVNtN79db41WSrHuAH~GCBd8W%imC!7atG;8ph}3 z3$wqmGkjaw!5)foeu%-BQ&ws?H@@nyKD}EMe11NVef~lh|6-PK;W@p}<6<Q(yMN&M z42Y>@2<0!*syPw;24VNL`@1fQiV`R3ewg91K3a|Z1)&PJ==)+D#;Y7zDoyt!l3|lH z<%aDmpy(SYO%W<wpw@Jqms+iGQHZN3{PqFTUYu5ruD$R(+hrypsE-SA?+Kt}*MgIj zfAZFliot$z_x^x}WAxT8I-4w310f);jIyK=H!n9K5=z!9zIeDZO3wyTOT6qmQYN`a zS*%gIkfhJ&>W_wKYp37aeZCAx^#cCItU9c7_*pXxkQ|2xOj8_4%z|hZk}>m`bslvK zW7>iw^PYZ@F95%BJ46e(?eAH&0}}0k=OF)~c*zGMRzciC-q&1kn2dlt0YD*)h<*gn zLpbvBWLwdZ+qVnVPjr0Pfwt?%FME$9CVD@764BTPP-Z~CW`-yLpo}+e!RG@-Em)#* z#Uu~oNni+@*9Zy2<Y5gGU@pLW0k<c80E?@J(<Swhh2-oh61D78%m^cWmPooU<Y@-Z zFIu3-99S@T))>0=wk_<hrxP`>*!p={mO%OZy&7)rOXd}kj>~k^%aeJ&C4}%;c^83f zHg^FegXUEb0AwqZ@@nLAu{f52^l}U>I5`@1mTnp3XJKKY<%x`LoG^UU5&V9qBNY5Z z91GofpJUj(n&v&L4n%R@4BY$dA}@q%&5tmuv<LG9fEERL*Uk?-xWHgMxX7nHDNg{9 z5Zw?z-LaI+U_i-d;=~WbBZB&9Uxacn=@7}^R*GZ{8DA;FQ!g7tsG6t*Tgk6)rT?el zaMF?_WmP;0rWQ59G)h%nC0*}lew{ba_G+S8j+H0owGOXbwC2~2t<l#Q2*c#NhSo$y zg*Na#nHb<31`wpCZZv?k^?%*=2O-0Qma7=xPewo#$VF2o-a70A0J2H1gRqb_p8*LW z5NQQ~28~!mPxcZFX12GT0BqYK1qnw0+Xnnq+zHr%X9CZc!}D=7ZNQq9e4dOLm~viS zoprtRU}I*3Ixy|Lx;EiL8@#>#yyO3Axq_;yn{R(H8Wx&%Io8{#%(sAn9g_q!!~hL& z@nIx?FZjgt3h;uz_$mE{=Z3%E5F)NM;v0$C{kJL~zWnQfCa4Ybh_TtIwwOWtxYxE| zY|L@Oo3yA_;@aK8v_T8lbc3a>Otay+W-qO0BL$zMx+VhUs)q}F$JKw%Sb%>{ncos5 z)RD=|Jhk}ULF)MPB{U0;!MMq|!L{V;smC28znoghbd%TI4pM=&<N%3Y5YSB0O+HWr z=<!2QrM^iWLF^IrhxNgqzSM^t85u6_4hl%V6?NJ|t|kaRR?E)k=Ld_ly&a0?*D#C6 zxFMoI2p$;PqdHy@{^q}ipd(L)@}6B}4jxbNRilchlTaR?l(atmF#K*++?9m>q6>(Y z3&H5#fw;)pgvk4(F)3To2LB;PgsZ*mcq)<eVD192nyMa8p}RY!^E;{)RBG--E;zeH zea{J^)b|7@rS)G5?Y$V{-BU-WkD^G{EXb#fV?Pv{oFYWkjYmDFN7V(m-*V5Lx_v9G z$t9#D2++1DK-<o7f5@-^k^-P)%Eyl8gM*c;6afXWRde0)bKht!YQAcMyDtpF;!?cN z9@ce9^SY*^OO;EJ!@cC$;D;t=G>5o0FL71zd!Jp4S4A^cvL7P(zs2P`Z?)y-WVPlx zZRO(V0k7Muq7`%6n9gs3j_SY!{T{8t(k;q{HksbhbUQ^gT_{cs?yOH*vAEuYji?&W zJgu9VaCOZ(jWE%<K)gc3r=DgOJwa1DJCPT7V=}oyY<Pc4Id3q7N~ycrcn{cCgE;SW zaAZN%wEH|KJh~)w-(7>|QxEF`C|L`1e^#Oik(jD`G{TOelBmWvT#@WMtv?^~sDST% z@m(zmA_0?;%M}15%<RbNM=dftxNnkE!6-noQGkSz`_Jm>U4dc!z~1BvO+Z$_AeNVx zsPKn}_wy@DjKA0`ZmJFrkEjlo-~8Y~ei^*KyCkOLUweJB{-%FNOlL))I*_11G=oMr zA?&k~*c285Wvp-B?_LJpkoJp??BjWgaNNd5lXCn8-wWxofr=)t6#ZmP>z7*1IuAU` znbRSgimNG4{cSAEtxDlYmT$n&0i_HsaJ;*rKHqmLJF(N;_nP;O4fd<iy64lTF`e@T z%*I)b*wOP3RWY!W<8`AgZvtca#k~I6PK|Q4M>_SX5uo~qCDcM2v&vZC5Z#N1&-j>K z#h#Ng5;fGnm)$Z4!72dxn}J&s00~im1bZsOTJNmABK{yrLjKl5sDky)JKf7*+yo%J zA~im2Q&-vlVj3WKy&>F0sfFUbVeU*~{<?m7Ip12n*{AeY;FYZQT$ha;T$d}ht0p(E zz1IE*NCla$V5LQ_UF62U!TQM7;Q?04{ru2B^@h<=kJbunH7fB<E@y(w;tSt~xUdqP zd`|?OB)RJ+sVtqu4;AAE4Bu8!@S~u1{(v4nNWC_vyof}V_!FIX{C<|<`nUxA_|%l< zIL}S?E1&Q9xveNSr==+M%|DRixYd^T7S6*XV`Je6VIbgG1)x<(AjtDPZfzxbz-)oD zC-jp}CgCi&m4nO2&Ofp)wr3ZU?8q3ch!AVQ%g0gnD4jN;hKuztZPl!bbB8L|eq?lf z)7K&aJ8cFOhTpWaYX<b5-tk|q3_Li!?veIwhn(@^Ki^}mJhB33?W)6#UWc=^M&l>2 zcwU+cwtIE^aBHqap{(>p@F6GX6j~inJQ!f?y6m}^z3$6UpR?V|4e8-cY4XcHXK1C* zgZyGsW?CJH2DaUP|L0#}w(F91*`-N8x2vnAng;y9t6a)X+TFwZ4EPuS^Q{(Hh4`8+ zwXW-ud4!MhLmj@!fST*?WrGH-QKk9ImA(gGtUITDL#JMzj5+$@nE;?8QJ~NO!~=C9 zd(^&6lx!(1N#|~_JRf-e&lQ~|Ze{zIq15xc6X#<+7;WOz*33zo*v)Y%wO7`0i~Hv% z<6WuPP77gXlK=E2s%?hs0XowT0){d8dqcXE?S%`r-z_JOJ2@T)23w`5n9C%X&88x; z@0G@+rietAIuZpVUr#GZwN+1p%IhgQlmniA)MvSye>M`sip(}3*m>I9J9!caPOd4( z&h^BwiG`C_v89&<_6lID-4VV)9{sTEVaMRI<wG=x0Gt1Xumgc(@1(fIS`%kJ6RBk4 zb7Y9&xjp0qdqb!p2{MH}ic7UFD)Y1N(J!}(xRULr2_wJRW3fR)G*i)h+SZ|nP>Uwf z(6&gbeAw0aI2q|~#rawo;6hsm6v|VN{QJ)OI%Lm3w`m!dAGf1BqGt+r%wOyKHH(d# zUY|pMZHHaIfGSZCE$ER$#58(iFENeg^2~gM0_q6dtPR4>z*tjdcBp9HYX1hy^x2Ne zlbVRl@6$$=13L1vxI>%Ev%_ugYU2%8b_%?g?{Kf{zN)M@sBTOO3+0UXgSBSyu2dFR z>E#4ZPqSreL4C2bmlSe_^VU@1%PUV@V;hn@y;{cU4SxUb&ogm(6`|dHh!E``q+{w9 zekG<gmA0+-*BzJ8U)QLMVO@T-yIHxmQ*|*pIc+h{Q@Ky>O#yLP#ufTKpjrh0+QHIL zIU-oVE*Obml>CJg8TX*)5FneafCcyN$0ov`Fd`yl5S9yQZ^^?=)n{T7%(|m~o0z)> z)?BX9a}_T86vCfpi+*B&w*Wu_2T1S=;FvKYNb8-9S}NEACLeb4b<-)J#!i9GLpWGf z=4jHYBNnb*mM*};<r0~rlvPlsmIZ*y9XO`zS&f62#*qUsZj>R-mr`j3o8D+${|#G* zY$UjqVg_!#Uk==@g~cEDW;t#kZsz3qm_5Zz`X47;u6TnN^Uhm&tJW@#CAxvKC92<k z(T$)a>@rpv((7i&n17FjT~YRx>(*kqx>oPLdhSO?_uPrZuZJy^%?{x<xITFP)RZQl z=d*zuE;u3E{dF;??V9te1RT%#M;j|A$8n1Ba0vyjJbr-wOYD30-C?VDu2FkoxVfj< z1-6BQ`&~xFll6nbh-q}{5Yd9J4AZ;#p9HMs#5Z2?BbX9AN$-MPC`#R)Ic$fGddgUV zv--=m9%NBJ0?|yOdBcy{oMtX@Cz+D#*~t#|QOS;E9Az?do%Av<1vKb^U{YH>f6iYn zNc4E(1b^CV4O<pFH$%TM^9%j?@zWATv4YD3*m922gXfs%_wUcvv)jj>JT3}h1h`$i zl#44%|MVyCj+!OH3T-a2q?e|UNgKEgk@Oyb29rNj&?c8;f5P8K^NiHY_`Ujbdk^~9 zdePw)rNQG`5P-miV>7=uejA2m2E*Dbv(Q-ubprz{7>JESRWTU_MQ!^}0Wf(tUGGs+ zZ@Oh>5}<$uB$Nkn8AVV37a|vuc$%z<{l0X3*i90gegsF^c_*`Ng9;nDmOIJh9BW|< zudt@^u^5j;HUAWWD*EHnk%>a@3Gx`*S?%R?r})iZt^<#i^$&PzJ^3>m>JzLE*>Ix3 z`&su|53;cTH=>e6vxfO>PBV`v%rVR{7Y1u?#z-SNokZL?FA!yBzH$h27e;|=NZ5S` z-F2m!&m%;O&PksCX8(HhpIgNVdpF3`0u#TtHy#0HduHZ8oKg?Cp%si#*apOvqSh1# zZT@KE3JBS2i3H{k8`r;!6)k(Kb4T9tXteX7WvA9a>{UWfbVALU;Df%B3o&_p8CrV8 z%_#GM;MXTARSq%t^%%6v{#u%Sp07C*oj~{+3u=OfQNk!Q;^PgNTWvYxTP9alo4A2z z@p-5Ys@qT>V>#X_NwWILTAt=K=M&%FeRaNXE<RNNeSv_-P#w3GNnA@dOtxHm3Y;6L z!z|L6;h`{z%0``7>~+RPXg|L%qYSM<f%ouP0PY2}gY(7P?}=Va5NSJbX!D=R{;r++ z1S3fBI>Pu}%i!(h2kKvV?98|(q5RpOu<fB*m2K5WwGmsp*M8oh7P#9Owq2@!bK<~6 ziKDSQWtFmTayt;z6#-wc?+X;PZbD<oD*&L3n0i<?i)1Kulqthq>(HP2>QXBOjE-JV zK&y@b^*{zP<5|c>4)YS5cYhaF6u^QaT61odpz{y|8O2zERr~?Cx+H!l&R#19@g{To zOeRFSOF6CR6GZ7o8!wck+Lv<@%}_oQlit|R#)HP|$4AnN8x;zl4(@EUB?*MT>+i_W zT9NywQwomsU@tq{-asJ>X43!JP+ip&&;mqWh4bNHaqR3x<q`13nFa@Il9220rCN%l zYROzWcmM;Py-&;=-JXG;-3k(82OkzLh20FCX9Fvc!a{>{cR@Wu_2%0h>NAUG+S@9> z#RY4^bchCpb=4S%?x9wUA(kQnlrmCQW>bmqfxjPs2C23gw-@xpHVSVb7rGLW{tYpv z0fJ($7S2O)RAU<riN0j4pHzv!wZL92(x->>8czE8|3MVjil9bd9qw&a#<=$Y)2UId z7vLlGm`+UnbL^yHY%w#W%>RSx0W)&`UR#xJh$2#^jqAx{BrQ_&e^h-%!}U;o2Dez+ zS}VG{fNY)oDZO1H>?|4BW{3uP1sp&{B2Bmi+Q=B;p&^*9ZN<{V&DL|Z1pic`|5udD zq{nCg00aU6>pzqO+qh-%{|i>IN7a$gU>E8`67iWpiSxuT@d5Eq;#*=-RY6Hu0E`N| z2D>hsP(h?P97{UE{oohi`Q#w^l$=u=%1H<p!~;qcsX(2i&QNsZHDt3wS)r~lQdps= zs94lW&O5C++78`AKcHXa9#j@67jgwU8C9}qooZ0^Q!G=xsgDxRWWGtDC9s-GEl#VY zeOmB-T?=cDam0*Bi%A=$dD1J=AEb9lO6HX8KG`JM9~?^Vlsrm)w|tlU1Nj&7OA1#M zK4pYprLhOGMp!Dg8#|1Bf&EX(SgAzmfpV<!@2ni0HO>c@jVo4FQFT;JQ)Q`+s!plC z+gH^qmgl$K{~tv>|9;WUq6fQNJ;9zcyKe8U?fqm=L*JWw-Tm+E%gyiF_xZkW_C4I6 zS1_>u!v2x{xA)(}DBuDNWC4QwA^?u(ozBkf08pAA<f)KoUKwzYhHN=HgM3{GEL1VP zGDW#;0!kh!*N}IZ(qLp2fc&haI8LmS{LxJv9ILVJDGe6+!39G&Ur<qrP5==IRZ?16 zlct>#LEhqUXcrw(uT}ku7V|v7-1hVxqh#$i^cA<bJ9hM})EiF21^~yDcg66z|1DbH zyTGx-Ke8?3r~t&BJc!76+iTZ=y?)^ORehXPO}4Z%?nCy`F&73O+d<6Y7=9e_4M|&F z<aUC@kS}htQ3(`Ke2Cqso$Xv~FO>;I!nj(4rjiM%^B}V6DI`9?%??b3j0NU}=irpK z(8@gB+vst=@(tb(1|Qt<_+FbTjufZ+bEqLx#A#iYUGIf8;RGvf`RQhZnYt~crUwR6 zi3OHcLd}g$ZCL9edVl7i&hR1y8p>>ueU9&XDl`bOMz|jKhN};15ar+w#RsKN^)?Rh z<ulJyC=10@qeX?=Uh`wh3_jMDpH{%H%4e*MMx{5WQz0WY(BL~;Jm!~yteM^aa5J>S zz;-2&^YY4#u!g<CcLI&*l`24w{$_7|t1rse(P~)7uV?wxp2m7Z|9sb6E)`uim^A@* zKBZB9-v!5$C7yoe2n7z-si$oaKFwAul3T|ERbxCW#J(^|t6=^wj`-qM)J8)NmU7R< zciZ<7><wO-0pIr9vOcXfE72xM1+vn{Aq#hpS2GJcEL$j`GME`Ys8JVVal@E1NLj|- zhG6XoY;#&ncE$v}1p|$YBTUX^V8gmF5$io~IJ^KSCIA9$8g%s@f1u_46kyOaKTrSt zy(-krjBkYk`M0y$WIQT;T-M&3Q5TrHoc#Fhe$u}s0)8V9!{u_cbdm1s!4dDmGU(`u z=2Z&aP&+NWsD_UawcerqH7$qD6jLDXq>)k$7ERQ2xBs@<6Ch~Ah#X|G(=!n3=OI|P ztCzLUFUAcD7eAEG)MNU$Uz$04opx28iE^Y?2kD<Vf-Pz6KvO%8w|oG4WLT=8+*~!v zeZ?7YhGGncj^RUt;I|#>`$GeYcTl3)br);P);^4tMLNuuJ3%d|?a<bq7QmThD{*{+ zG62Un_H9ThPG9dhBmZ*yUoMJWASA4=0Y3w!Hw0mQ6kZ12`F@aT$U%75=;reUO4f%8 zuf&fQKPVe#cmR3CX&nVKkEsYG2oaR%J9PL>sN1@lG`mZIM|D@5rzfiTuD-@a-{>%z zG%l~%<Nz~m<WS1=V9lXEhyF{yJd^sO2G6LwC!Vp(ouNRfYoP3d)wRtvZn(mCX0@9n zh}vyB?Uyu!4&m>hLa4R}+Gy$z)jng(MrRC5%}!HQI)+=KePpQs!DNZ4$OK2;zw2_H zGW7@&mdIyM%m&(N91oAwqQJ1%mhs7_9vaKfwvC<svAcJ}0DzMv9QLd*($;Nk;XVDv z7;t(aS{%kXDNx8?2zG#_P?|@%-A_81qemUQtZ#wQH!aY~Q7J`B7UV>BvIq4!%1XNm zwfAF27aZ!H@yV0qj1hhqK|bGDSQMgU=pXBJ(k=l?pe!HUmB}}YKT;yK)U(H6?knkc zxvWUZTA}==;;JZwE^K}X_$oZ;a8#LM*vM=nKL647+cyUzS^D6UeyMnYA*BO8h-ID6 z)@-<m91{9u2rq#VnKG3$A`-;ey@%KeruI0kH)#YcKZ^r|afVp9j5ggNb$7!r8qcQW zgmS4){ZCQF%M=9p$TA|x-2FAx7$#zwq1{ZZ16KSjOJyi}Y*c``ehBz!sCuQ_ljo~~ zjkQEoOCRt%C;d;cxYDnCh%p#H3!(vDG0Nd@;bAKZt_$ftUwAyVw9e~P7!UjYW!atU z(Y6!b={_CWK2PoRZo^Clsg+?;#lXWqIP%dF6#n<Pl+_OAz|`IL7|(co;_)%kRCMG# z;CX)WIYCscGTue*BEWZqKtJgdtpNd?wQ>WVsTuU$JV!nlQ3k0}QsL_9E;`^r742=f zZy2__=d--+z9Sab@(d_Im6nZEu#KQ-;NCLejaP_<z`;w!c$j;n%J6H6=JG2O-V4TG z2CA9(ANG~OwM?_}diU3%915I_u(?|q+<*TV+ib8*vBvW^370GLWv(sQD!&$;P7u;o zpkFSmu9pM)x_*3}P)`G)Pp$N^j6*}3DBxIrY$&yH-1u>mtOe1-W+Y14`H1j$)~0$q z;CsvHUO7qoa;2_M`A!-;c{^^n>p6s$ze6h0C*>p(mXGE>tdV~h9v_)A3s5(a7%}t* z&&a_37S-~_;zFjNb2rgbRJ93dwq16~SK9F=fvb`hrbL`}%Hu0nm&Gg1X3?WzLm#e| z{{P_HJ{n~6W(xtw10jYA2%%?F8{1d%>=aubfP7S70bsx;+Z6BKmJk+Vv^A}B9(A&4 zBFbWNR%Htgof&>`!uoUw!&#Dui!k~-sLsx)F2#0kXgR3nBGD~osOXSq(Qwbt&koj+ zW_!ggHph;Ml|`HmbgXx%qv`%^8lq!IN86--M)e^|(KxBRVDU5VL+~L^cEuy@oK5(2 zF%qYG5FVfFR`ZkAe8Yp&T~twr^p{{1vM3Njgn7VYpkW*G;9YDO@b1Nb5QbF)^9;lO z%#L=bQXK^{6~jNB6llvZs^@}d;h>tDDOhS&)of*a_>1fQBlC_seP?NPUGFvdAhT{` zv-I)S&wIg1RxekOPoI(KmD3F4Cnou=nNN(@(<;(DyC1RWQP!Sop*{<7f_;Rwg~Fii zgm%`G5snb-3kLGxlc8PEed?(jgT_CmKbio5rG_M>WTVJ1`iI>ji|GPa8LjE?hf>5D z!aGH!oOwA}ND>35<HBGQY>nmM=gam~b8117$mDWn8CQSb>I<IB(RTYCwu6x@5owBZ z2+8%5B=^(ah;4>xzq5VOgkR_qPs0Iw_x`oy+@nw^(iiLT`40Drn*IeJ0ZfK8JY!f| zLqV!PLApRO`n+-1EACgj`la1|JM-Q|zia!QhKq$~VZUljs7z+~m}IkE*E~MHuEgwK ze{bKtMEpu~*%Utkdb0UymVES-MCQUW$*RFwGi&s4H(7q7&U{Xklh;pR&0A+lJ`Az< zp<G<wbem=B$@=k0lSKpv7t<)&0N9VsmT?C>L!hR@axV>1xJ80S$;m3vtUp?d=&w)E zfA%G=@Dpv36DW<Kf?f>#eKR_Z!3h-GPsfd|!VAx!Iu#f}=#fv2+v|@E^ArmX@2NQ< z(c?Xd-7nZ~2cR&)PC(DJK_;MiRz1)yf@O7Km2S~RZD_=2sy(}T50JwP6)^UZK!ukQ zl~8)?)?AAox{1WM8t4g^vB=s)AgF@LK<u%0=f*Od1a)(<Op#%*4_ZozWHy=#a;z0~ zDU7R3p;G}D8=@F=XLD0<+8idE_H=TTu0YqjBpj(3Rgc|u%xIz2ZS+Mvo=aeoGhuB~ zX&_A^4KXHG^Nr>`bvN3u(aX$kUzi%<JnV%#XDL<U_3WQY!5ip_dpz+iO$1$%J<(r@ zTp^&gW=av`c9Z&)iIZ3px>C{oY?85LT4@&Xpr<6OF^qMEa5RQ+HDDU7h8mNsA9gW6 zoE2_<=#*UFE+kgpwY_T{Yx5Q~5KG(UtMD0onibctL~r<98OUy};*}0Co0VCn4wl%0 z1O*zZh224$wTN*OE|a30Rs&$<wCTL?2~4tc1AH(AqD9AAcCy}yVK&C50FW~OTTV9N zw0^_TYk1`QszTAUy|x%~fUkj^smfeH*vfICDgG0+8B0190%7asFt0>Z8UKh|XNJW} z0>R<epz-zSJ&t%O=#t0SC_g{nA!~RR=YEwy{~3-Gg{k-zz)FJ{DF;B$7NiK`BD6pz zOoT~<F%!Oi0QL|5zL=#&7FCiKH!6I(U)3eoCJyzh!AieZIq%c|B0jpZBG9XeeH1*B z&o=Ttmv%T1Fq`ma1*dv|pNE9ejB1T0;C5yIq=of2dq5(!0SI_4Zb68f;3NK!_@>kH z0H`yC-kXnq=dD0m91hq{2&31GAnG~}-x^A&!r*ORnNFiFRF`dv0`Jytvy<0+*H2T= zK^%Fds?^Z9q^^2gV=U4B+6f?&?D|yssA2y5nWQ|kDCK_Zs4|Pvs`pMvo1dc*6BXLF z%Lq>%!?k-hP*S#25dd_2zT9FdwCxgrg&W_;6dFSL|3U+(4bbr6LKv}vSf`QAfNsF- zj@;z8_zJw7;ZB$kkN5#XXV-tBxdw)ln(VxR+0<QOXw=9IROl%D-43%wlR{H$6UicH zZH1YunH2>3Li9A9ZqShU=B;qkz?a-YPnx~|QB$~YGL@oCA+KFz1gtUXOY%_Y;Th>^ z*ec9}sw#Lc6^qdd-B<9LEsuan0GlB@#M<6-D3D6AE&H=rr^O9p<+va?EgmwolETWN z;6;b$Jr+%Ss9Pit7OVCJg(j3Cp#*l@p$j4jv{-`u*sh(0FKb@+IMLtcb-O>Nt@P*c z{Z>^<6uM&k`h%L;`xmNcYw3*&TjV;=gPx4h|JxW{7UFZO9Qk;5LTIZvji@yJTj?~T z{yn^<jYc2NbFo^dsD4b_toD!(bTyC;h@HrQ%H5wfSi~%YAX3w^8X^~{G(CNsmbI)< zve@rM(QJ^SJp84#x)}s&#)u{CcC~{xOPV4~D$*>rgLKZmR6FVLAPK)Ou0+6W0HmQv zxm6@n1KmNQ!Ox0HQmQ5TFu>GA2Frc>0mM9jeQ@|`;CAO#4d)l+Tg^37vacT0IXlub zU9~UU6ycJvCQc;aEXd0bK)j3I@hdnIPIZ{PG$|#hTxDwIiZD_dHbOS?2G`ehPn=`< zlYDA^S{P{yg>OBPO1tn4t+db=Z=U-a4n_(x)?^CY;}~VAI!>H1Mlz-LS}@HmrcPti z^^ha}%=BXA7+<3}l**!ko9H{T(GOxyv-t;}Peal-;!w+RP)aHusEZeOtF3Z&q046E zTX2Lrqb`NeWB1tY2d-iDJJ$X<<Ueg!J+;2zU|SVd|K{2OL4Qx^x>Ow+xEK-An*_L! zEUnGI!xAE8@<~M`q7UbtwStIBXNNd_Nqo6AyxwN8wws9BfVl8~d-2&4Bfl65+y9)> zHFa*8TTi^yn&!tYznWwFz;P4SsxQ8=jY5f_R9iIGCzLT01Kcc&!DDP&2(`Al5whyA zmbZ{mQO__}vGpRHV4iLzso4>0qW4IMYPhW1^&p<?E-G7`m&<FaIa!7kd&+{99zD_p z96U6XnGCb_e(_n@doz~o(rs-w!pp#@mh)}<dSEOWb#gT;JyXJQvx;)T!V3b!QDoZI zWBRv4R_MCHTnTlX&}CIzT2tus(x7bU-ny_XM6A)#*+h3&e?;5a{Qhv5pD$@>d9lNB z{TN0?_XLXX^PS<qf9yM|^gdaHZ?cS9TKpf>WLTA3D@h$B|BFf0Sg+J3_3K@QFAEc! z<gMg;!GRUjO<T8Yxic#qe}Grvw-1hLHgnT`-FGbz4xhpn{_0|?k6q}Q(u#Y;ttC}7 zksbb`$!pT(_SG~Yt#|C;W25oTvksVi*S^}UfM~9p2^-a9lJMlO?9;E??U!nds?^qa z2=cn}{aRUVYq{mCg{-mw(f7N@w8H+WrHw|%sxZN_iXOu6SqTDZ10@yY@rIcUZ``z> zxa+9<)Yg;ElV{pf6@3e9d_V}l$0r7@>KlH)GxN`t_R44WMjA!?|HOVA@m(K(9?EM@ zmuX6f&-5xgQ|Gck;20d8<*z||-Zg$=oCU_>tQg<uBGPBYniz}0k@oiTFt|x{wPt!K z3F4~)2-wt)|NoEMXU<qgpz3Lo{S%tLs@gy}1H)B{5;zXmRk^>nC<LxXmL|e5dUrIy zbM<f7BwD9RM2@_A;x4QXh)*fG#j;V?AlA>*PF~=14a#@l$z-n8Te4SnC^A8btnXXX z?3kTwnb(S~IIznzX;fL0$|fy;MKnPZ<n*I4>{K1RcG`|@^$nfENSe$4epHBz&MvMl zZ_tekpPH<WDYfjMc%gG%N&kB){h{sGCj);D7M=x(jNHBrMO=&TlzSGhgyG1+qxgZS zbRS-U3_KFTh`tFiBw|SvqYvW8@s4)yKcrw#7wh|Aa6Nv8ID?BPq`f{RD>Fy?>M`0p zG=I(oqu@UrxMi`h-DqB9bMFoI$6`xQtdo)i35uu~Uk1F)19P8yy%R6m1@xj{tOIh@ zg@z9QTkgxY@aJH6-m|-3d(PeZU{Fw-ZBsUizBlR|K6=<v$i)VIHp-%MzdmPf@alY< zX|)$S8ek^1Mq>>!ojCO|t*mXg-6ScO6XA8z!>`s`Ek;z&q@HNZoIFe_bu1gCK!Q3n zTH|f#vcd7Qtl>rY0x3I9shDp2t$4MLhE<l{=-4GKKD-mUliHXrg5HSl;_tTy+ZTS^ zT&9qx;M>_2#r4^X@0h-`(F@Qsd{JwGMpix9V>?Qfy8TeUkex}2+`7awvOvhCS!_hU zh**{mlTYUpi5s-tsv8+oJ8<CLPGrlb8?)s20`@|iLeS?g4S&@+5lN!0!ecHMt%0wE zAOG0@U6+^8195q2iy<>bp*EQovW0Lf*_@z{zNA@s=L~ICOZmIE+?_i1y}Mn}^x7t4 zvB{nhpCt?-YA!kj#zn~3{yW5ssV#goNa!`HYMwsi`LWO!8_E}aCr!QDdm|m;sDYgT z0G=$+EA?KC=z_-xx)CIT(1C_&DppdE%4Vt(sZ3H*&5!ZJETx^DUBYJG;PQ<9HPzJ@ zYu>G?B{EIj{PBzR4$u?cI6@>OC0rgC*h9!2ps5rG@3v8+VY{zv>r$qDP8R7b1p_7d zsG8Ti+dWV?Glox4w}|mbk|VxNkRf1BH{k-Do%uMim6V7;@1Y<-JG|C~z17xvbm0n? zxM2lvYeQV>;!Gw3Bz4-AK8AR!qx8Mgx<tIYN(z6qwS)nrpUoLE4SRFbj%+r(naws{ zZtNJQZ%3o$_=s`SCy#|Jj|qULbI$gcaVIG_-5Q;veU6Xeb;!b^c6n@2^R_!tjE4ER z4L>KIXxLar#K9ru#@%R~c)8o_(G5e|<2eB3vQSRvB>#tXAMRb?^5%N||1)XPp%E(U z-;BYc<^$8v6p3Y7=TJda3+RkPw>mA@QAHGF3AVmwRf_h~s6^evSAt8p0#KW*Ma^US zF?R)<w#Y%PI^j1s=Y<DZOohklp@atk2yl~7=Tz5R25`6zcEj23X0&DeXi$<mT$wKs zfRtU(6{htll?<}|Ns!15qnj`S%^%5k?#eX)0is9#*4f9x8*vem5P-HvDCNq~9%J&` zccvyrhQYlu{26UhRQ^i(Jf6!<wHJMb-?g=ci?MR5m3tp{H<+NreIsd^Nu@?uJjDb2 z^hRWy+-HePPQl0~bLNhzY}%VV23yXiR<^J6SfANemO=SNR-JE58mHKZM~aua$v7Pl zG>5ATUa3`&pF(!^Uql0Tqe(9P>=~6g^aXDT7raBb!$W3lH2DM)n`w%ykA>G^$cj84 z81tSq8rBa_(ziboqS5%w($nlpvb))RmXAhxzr}qFA1~Gu9{WCIw^zFE4j$^WnO#0T zS>L@wRx&u3aPl+=G-!4otH_&gg3XrnG#x`@k}G<eOuiBxMkh7f<95Dnd;7x8MI%4i z`Y4_xOeJfUJ(-xcVW`r&KjTFgGXPBBC;M&Qu#0?bfQGZW!$~I7GkeS6X|lc~8fVB} zx;^q!qhq=y%6U^IPV=y)W-#&8Ua(HrAvN4>eFz>P`f-ID7roI%j+jrSoams+iDk_M zI|`mEy7S1k0g7~~FE(rR%qbCg-M~>%2LapA4jG&oj|v+0QdZqf47$8Qjdsn-358gS zFDs1IlqtrMo8SeI0hV#M%2lYJO*;#m)P`{Tu{lYaF2+_7CMZCu7;gnuM56+^KS3ch zfX<@Gf@ygKm*buAgCKOCvyC!Tf4#ylrEo^9W{)fh&G19cthuG%{WAUF#^q7lAMyO1 zXqIy}KT3@2t9OUGycg$s>#^;E?J$wdhMA!h8RpR#msw3rQY!IG&u=hW0;ZjpQR!{{ zg(=fSHwLub;hMIq$5f#&&s~S00Y%5n#T%tJ614l0EJfYIBN$X01?4+NYmx2T4aoK~ zjXi#akePCAlCUs~oF=|ta5!@0VYs&oGhrrt+uH;K42((j*azJmliT`XwVIQH-L1Q* z5f(bo3^XtSls>=#I5viI?8ZlRbw?JS+53sb-I_6ppvWi5{aH|HwXw5AmA6sr4tIQF z29Z!64MR_Ad;qt$K~QOAcl;4*J8|7Y(ap~;y<1yf>uA-GBlY)U@l8cShLT^<X~=Hm zZKsf=uOp3x_xgNjQwswc;NG;2FW)9gd*zl%5$#0wIir#A<19OJOTm{}u;lj<ueX}k zEgzE&?#&o7_tGen2|D*5k>+yXhlT=+Dw8qlX*NbE(gAP+ek9RxtCAiJ`7hWgWvz46 zDF$2&jxLHu?Xs_M;etai1fkscHu5opyj%9|Y+Wb>vD}s%&&VW6Sa#;M-0hp5YfmJk zS60U55H)7DHhY63`ni`n1EijEJfC#lj?dMt<G3{Q7JWMy)3$s-Y$nFin-#@sN8MnW z%Q7!Csf62lmmSsrZVv|AGsay6c~&T42v<5f(#FlRh`<n<byL<Ejr0w(Xl9y2NtuP4 zO$bo{C*@`qrt?$;w@mNnG~9L*s0{Femv=_4^ldCG9MY*u-{+)sSJ;g%$to>~7b6G& zJlu=dT9>N1mjRO&h?_NKW_TCNzNuIpw@*CL;M#0?=3d=}ze5r4!#nU1`~y~?3vYzm z#cl^2jP-g5@_Gktl2MUG#b}y?Co15s2R4AWesy`@+wWZH*RI;zs2dazZP48x@qDiy z!OqSJGIO;ZbRm|A@$b>*$g&&Oxr!KdNRyaNEKEIF<WNd%a!aUUI$6q~yUTMfnBL@< zqTHX@y(y@XRkxk~?3xeUEQ_W}Tp+11g?z1rB}})P<zVLXc@Eu+Z67E=k?tyGpvz?7 z-a9s|@@1#edEqKys2SXTdyW$j3*Jdd!VN#BeoB)4L1nmuhV`vgIiojWLQW{TQb&Gr zW+3)xsJp357GuV6EF-BRwd7PAUFWj6x1SCfa$K1VoE<Eq^JbBnI+aWh4$N}-(TAaM z&-CK>zpcFWfInq2)4W+b#b$)#shZ4aE$ev|RFw%mc3>WTh{go>{${cdeK4tQ-0spS z;U(5*abW>^@fCc7`TxQk6fhMYwq{Gb!?6SV(XUVh(hM$(Ld$hGDZ1BcHjN|+B3z)( zTFP6Oa}fS;R>upcsO~YSzNmHGGHaw=SDsyQdx8dDng~5HwWcCvPbQ;Q9j-gHBrKy) zayauwzcD4OA@rVgEB_p21xfi$5-afP-ij?80FcjE1|^kHk%$)35QGGQQcss!;Ga7M z7rssdgX1B<+I9mxd4f`>y|un#dQp0oTk2yhPauMZ(C^WR$1kGpJQ46lY$EqgTnPW8 z1J2lRs9^%{Q1n~mqZv5i?Xitk03oo9Mn*^w(qd{B6%2`}p7kx6c?Ryka;B!{%<Xy5 zuid9~KWK&hu@rlssvf)8-_e)JEQ-r3t5%mpbK_ogs^W2zXK#t53hnlEC;Kgz%K)31 zY?-b-E`eZtlw%t$q?E#Z2u*QDz2*xwy+;CqYV|p>u8Byp8^klvRTKR}u&Kk{Z(dgX zgG$$J%OW&j5tgAtj9P+97=<_AeV;Eu1r&tYxNLtG%^s)*QMWc@hr{a`&r*eQsElIQ z+P_~LCg#(b#5bIU|E?1T&dOeSPL|{)S(F!*wK5e8N;Ge{F)YW}V;4ObcyaJGFE|D? zPW^K@(1Z~@uu#03iBD>$ZutG)n*eg8=`F7rHU582^WE9E2oA>qUL7VCO3-Z#k$N5E zD#98yFI<)iEx!TD7dGh8$VNWdQB*V6{c}d*4Einl9U8=54=#ZlmLmkg?h(8RBoj(H zkrIjd?Y=)pm(d9NBe=bD+6x(R+%kq2Zo|JK3*ESl_Q=e*EDy1yLGwh@T;-aSIAwRL zhRdlIN0|J&e|%aKBB^i2`=4-x(9-g}P1{e=MBV6A+erPEZ|LR^ub)_@=gq#VYdPpB z9hAmsiD*iV1tQ^{o8=KS>cQZp1N`h$k?4qEg(6uot@miz$(k=VYE@mgKuHxzj@B{+ zVI1pIin=~UcIVhse~b3$Y<>#sQC_Vc_u!S9jAdT%85BgwYMs7Ys#x*hgo-bp-syPL z<@bMg&FXR&yRMj;%s56`IvqlcI!wA;2Tc#p{Eq5;Y-zu%v#~{MR21dwJ;GEhvH|tI zQ8TK<=%C0F3s03$_a6Jrgu$)Lwa(tJx7%EJAbV5Bm|F?Gawf8G$N;1l;NC0-8bA-+ z-NI{^sa#d+2hJ#~il<Vd4ZdhVjy}YcRGj_<$Mak>K`pAuf{iGCnkMBYw^+Oc<m*O! z&dU#Y2B7beYq$>pN@f=6OBKyJiQF2CwVGfg;O%+2FJY8g+3D64h1TrmA>|IicBmf* z<`L^9$`b(y@F}*n^$gezfwe!N-{@x@To2?+82`IM=H}9XMDC1MSEr!*xIDvf&EfbU z`S~V~kVSqx6r<h9Z5L77-7wLUXIT22u+eAG{;gsr100QYK-D>xU3hGVWU1L@6g1jV zK2cyXk2aBv#FMa;aw??XN85b0Lbi~TQz{ZN3URKMGf@7`sOH=5m2>qt`zQ=!=(L6p zj)Wgbh;atMkV^Da)Tr-hW!jiE`~iOV&|r_tXoAB@mG{B^M?<5Drv~cja(b+@)2i$Y zhB`i-%nB>%;`^otk^AidSmVi+mPL6@mK0p`a#Eg>hvZ>7E{lqK;JnRJsD{cL_1>4S znfa&q28Bsr)WeyT3rZG-_l9D^0q5`zUnGoOtSV}HJ(AsE_u;&uPy*}a3<+L(d0Mt3 zkG%?ZTtb6}PM1);+*-PN!>yHqbwyCB3Lr38{djU*LKo2+=s3QHFX5y30QzwdO`=cH zS7?q<5e!DrzXHtY@1S7@7k6Up&Is)hQlqk5p<l4j=|5{y1^s}AFuXSGe_r3Opf6mQ z#D|XeX$><j?44ubneFLr0t!|JDeFmELGPHN=k__daLIh&xYZp+fRaBYPsQ9SDd#?J zbMFn5AKnbi)iC*2teQj15v!3N&qkmptk!4~<f9d~WXgGDYAc!eo(t%V=wnsXRho-d zIx(VL7leO0(D{pSkOhsXL<-Zf2#sh!9y^LrxJtqB(8#LRMuIKDU?H}nhB%7@wX=IX zFwiqDAVk?R_0khg%A8_h9!NilEFBO6yi*+s7(B!M`R%C;^Cjb?G9_nGEKbQ`><>EN zXQlQ3loE1s_U!q{Vjj&=9}Y$Rr?Bk}{`=X-r(Ncsi^FKLmN6GrKSUjT1OkOnl`zjK ziR5eQ!p&ilTpXX!OeEGgQk7*k@1QCmv%j_LCkn2n#j34gaRO>ZwuzeVkVADd9+J)F zsf%Zp#i?$n@RlhII>4;cX#MUWFw^S#nV$9^s+wKKj2kbzF9V>Gj0ILwPQRiwx*Te( zc(5~A!m&gVR^9Cig-q5sMCn?dz@sg0L|6<ujcCFm5Or&b%$SA4JLvz)0Q8(;gNT(6 zPQ1{o1FQC&M^jUw3$A*5sr#O=1+U0qSmjuj+NJNMryEQfRB>?7PKtJu6noT0k16jL zB2T*s0N$RuxELQzifdA+XOy<#5_h)rbL$uLEh$;{;Pne%ZLL#!zy1<skg3%0Qt3o( zNTeX*g6)7fH(x_5mMOR``GN>y%Nh|%Oi^HhgOafDo4VnNNsuW)qktAMURcqDlqS&` zC}Bj~9#p0uq^we;%+Ix_jE3)k_n5W}U1kxqI>Wn}3nFT2ree3-_+?F4{ctqm6?NhD zGqKFz-H^P&I*Bvjb!n5azYb{h-s$4>DLTcx+Fu!dL%^<{N}XhIrO;C%4RajIqzI<p zMU4IsAhwB!T_J`0Hz21t&kbjYk}K){#RTa2>E`P{%`z$W%$!Ioc8~MHNa5SN$N2C` ztAtNk7+8`%$V+uBY=aE1qhn@(SI<xxl*je`sy$9Fu4S|7aPXZ{oohx8YQwmas#sgb z(NX4UD6!h*dijF<pYp|^UY2h%I4j56pxI(^!(%*X2M8mlqpdmN1cli!OH#SWTPMpL zUI}3Ot!+suA;N={Ahfznc0)4-l(5qmPtB|pXXzMP?^P%i4Cz`n!z<d9tAb*n;q)q2 z(NKxk6rvpfTH1&y@w!P(HBq6biwu+B^bLsL4CO3!&avagOq~ma$cn%sp;QDEgTSN> z8qX%qWu9K5((cvzvXQGYeM?ZdQGymK-?q12X3@?I_8M$LjQ4`3ScW^npi$ylkj97w zkmhP8LoF|7As-K23LoQwmXYI6c|1iJl~vCH{Xno%N>v_eFlE2O`DX82&6=ib@LX?L zO>_-b1`Sk6MGw3}C5BNi0PMob`pXMR!)la#6L}llDYWQN;wWt{FHbZxyBhfHRw7SZ zEv1BQs19sua>m41?Qx6QJ<6gl7wu?<r(@o<{S)%6#-7d?!-FcgFFWIKg*ZBzkb@hg z@@bkyH@ocX2c?JbK}p8y<ATr-xdwd>L{`e>nQvB8S$N*kO+l)a1<ddDs;-8^0Skg5 z^m`ec>4^uz@*!GO%6Eo<OU_HX{P^bC&c<N$XAQD^)2Q(}E0Tr;1;N3#u>Rde%>Z$< z=|)lo5CG@V>}c0)+I+q9on1TNN?wpbeGZNxtsYO>hrNJuoC?t3+EIV^Br}2w=t>n( z_mx<kPEe&7(p4}f-naboM|J0$V;RBcs6OTGj1DZS!{q!x;2dLC!<@3lS?=HFR_f{} zfeYr}hz|KIiJ1prc``2&n$oSQ?4tD5SGUcDZg+IF`x{Tce_Kl@l=N>i^NTpWnj}e8 zDre12p_e;LiDX5$fuI#5Gh5pR&Kmt-$#V@1wiu5{#k^)w;*4eS*bSpf<7&|l#$H1( z1dfELz74h{N2FE;{Rk^lWR8qm1}hhNMbz$kZ;0l&RPGDUUg1&COGy2VZqN0e^cL$R z*7$yMdkr%uIv<7ZlH~QEq<t9i`=c37qbm`IO$=G}89lY$BL4M&JKn8g9Tq=$d>*6< z=SX3FJG$nOp3a0kgYod&mooC4NPT)VP?y$0e{QPzb9`nt<}WPwZ><MI?vLL3Hv78A z2Id*4zV(yY@3n@7?0C2(NWr5*@LZu%KLBEG7%o}&thl4$8hS?acel4<)c@fl;sRR% zr{SbZk>oPBN<4*?zTJI!c9slxL`8#F-mhXz<DTyDn=Liw;F)|i>&gXXQ%t`M;(7!? zWx^tdXZ!uxwn>A7%&>_w{F5D-ggxXLC4$gKBZtu|KGZ)cn)g>?^9QNH?Z20h_1&9> z+}B$CElaecC>63{YPv$lX3c{Lw4L`5!ci6zY@I$CI<)3RkdX%a<52fgg8<;tF!_sZ zarn8a!{OLvf0<fX<24o1;D{}6S9&zvhs)}@QexFGNP_b*8xd{&dvs*365w^XSVF3| zr+jpE<Nc={t^Vg;Q!a@qXrrl;i%*3Z1pe7rblSyrBSXDYZ`&+)10@{V{}p#Wn|s_- z3JO!jYsyIuuAHKc@yP><=rr<(uWbBN8gjd}j7~4h$RFsH6%LTkFD2HBI$)2(o_aZY zdux5VIT!~MV&}F0GBni0g>_A0yBheBGZVC~0UtqzhD!SDM8b$9QlW+06vO@hTB{d1 zhs?43*T~pvFQejC08*m%h}HH%QyO_2!l}7T^m9;JsW*Rlc9<~O>`s%zrT;VyO)cCR z_A!fT7mSQo`^sTpXVA{xW<1^D_`9kHw2M<RjZ4GXO>L|htwOus9eg=tSYU5w^c_Bd z&4Qcr#IS2p4W;zyoPlMTZ(=Q_7K}oN?isenS_500Y$<}QC{&<Obkq(pb!69ikf7Fg zU!U<&8;-v-ZmT}1G2o+kT;*tI(5@2Ncpg)wmI7hMFv+66Dl1qdV8uMGgxfN6?l=x# zt(l91)Zz>>_r%BsO=k~?W~=@*cwnLuL#G9)&m#LMqYoj)X!$W74cW!~-x}T0QSWX0 zz~f29%Sd%~u^4(L+TnxR8U%b&nx!8ji9w)|fY2%s<lT}jPV`n-T~$quQuM!S;w(uz zB`0V9DBr8FpA62CXj=8jt+fS!@-()LD4qYj0(vFHkv=)i+DBMcj+M2nox<U))23fp zI!8>}F|EWw45=Sgv4h0a1vw<DaU340fTbBs87I5hn0ZQ1U=O?)g@x#C4s#9O8BTtq zUD}&>dmAa^JNe%%tj~DZ>pgb~#%di@3^zEJ#6<Lp$)<how_36``tmR&{Do$xAgozJ z^07Cjf2W<B=g?Q(Hds^zwpp7uUiJ-qeBR}9#a`M;f%H9lU}Pp&Nb(}cw;SuxJ_M_r zdKrkYN%(v+L3)TcsIclV$68OWov}k+@02>MR#UOP#5{)<pR)>h1%8}G8VvDJO;j%T zhyIYbZFELi(Aa1$a^=LE7yfD3Q;{#s7WC^nvS%^$?BKH3zx{qQWO5_(Z2+DbeQ`r0 z6A5WClhtRZg-K(%i_~b)Fqo`<rhe0CW3q1ibTrx(mux7ohd~sr>|3V&2DZM@9gRM3 zA7hhT;tZ!LL}XFz%B^j#nio?6$^aAXq`UV6e+#Gt8EvH?=f(BBd6@X)@ZfP)9nTtK z8nvt4%;>97a)zyH>n<yOJL2PP3HvuV4&9@{lT)1&(zukOBQJGW^_kh&Im%V8KNbq8 zuVRh$&20Sea&&HkZb~b_Lr=Nwyt~%j<B@Zs$|Tm3i_MVh4kfi~`$YGwF}y{|kg>-J z$>xbi4o@2(|K;nRAoG3ApEqZC<5Xb$lj381aRa6ye)N(lHm?XREKa6%Uy!4&lJs0x z<o=R2eLbNsbp^NATTEmrkkMUTY^?1NAbtTf{fx&GC#?!Y#|%%FxcsL(uJ|MI#Sf>S zk4OA809NzPLACCTWlHT`Q%b;H55yG;x+^!qZJX6fGg#y?^jVpQHDxAQa+#<+V|z8I zNCExW#u%DG(`W>B01~~Z1!|rMA7Sglr8#6LBF-Zf=rx8Y%ur^%@GkT>B4!$mHXP2V zGMEW@QXW#235}lXYeDXn83~19b3k9Lst(N+W~we-kXe+VN2`zHjOYi0ecGT@kmM6S za>nS=T9zYt>=>N=tPOK4xVJ5yU%yU6@+ZmT@(pE8h3mW09C{?aEH6HoPQBrt8<!}b zl^b#dUHs)JQ;KH9z)eTNZ^(QA&3(4M?7<JgcM~GpPJ`tK54xN>VlW8GkUW;{tV1@P z>}PL}TMJoowMFw}8+cQe#sBjL65AMD$daPp0|HY|`}q{|<Zbz*<)g-_*wDRuy|EWI zPlVBfj0sF+-|<Vn^SEU`+)(X2-~7$d{Y{4|P_57aE#}4(C+No8J;A~FY>r7a>F?r$ zLC@dL^Pit-=8P)(>rHzfjBj*rLQAky6+O_1>G6ba86Q`f^#mlo;AxzafY6((o)zML zl~wHuEFXrQ83@Kw1Jb6`OQ5!%HX@OnJA3b^qymjcqfLYp5m0Jfn~=T=k+c3~Lv98! z;GT^+wYC4V?yu^c0{P^~@Afob^=a-&&h6isH~4*W>NDE9wrHCs0mw}d_2KiGLmFMo zPDUJWGLtw@^1-QCi8?wNpG@Uhw-hT{rFdujTL<kr-g@CPC5H*70}&A6dN~Yy>c%7~ zOp;oTfyC@hfS%K`M`>giftfYgnu_UZwmH4PI9ZPkyV3Rpz)aASI$7y-LU>^xYSQvs zjadM_F(0-y(e&s-vlwLt(y>u%eiB~L6r00tSd*zu)UkIPNZ{)LvRvD`_6}XkP{S4# zrMv#ikOI(zKCt96hl)-T?P2pcBhxLdF(nQsvYbo3!&cXZ#jl@mgRa(LZ%KEffF~Db zSMmpBY%e2UR&6<XC~;6;D7v_TtRTJ}ibTpkYhahAF#xdAt52kNRHGd#r9HFqEm%s& zM;5k~@_pEU_{esP_0Ac4ps!{vw0)PZOUzj<Bfe#z%vJ;Kx9lNcVq<OGLSHfoq0OOU zh6N#}GY^}FefgMKC*hI{jx=@TTHIhk<}?r&Ub|?T?zoT6W#uS)zj)^jvpbI}_TU$k zl&cBv$TvkW!L(Gt!87W#Ac_=+9GWpoVvJi0h5gVGg?MT&XHfe*`uI7wrgrJZtt!eM zm$rFnuB-X9**Zn*n_D*cP*hUsdSWVe$tVwljoL}V8Y9r2`%t*e=1e-QrfDD^E_3L? zn9Twc1L!ycyb<-#Ry#HRD279W0@mRNNCAr^I29J$l#8gUqYYQ$jj-l(=^2-+LdeA~ zL}@TMU3c2YuA0m;wQuKgY2k;nocifR_`A7^Fj`XG$(-_#apd1R`iu2ncIIuag#uKd zf-bUlKxlA$7hE6KynE@BYrv<<>z#_SxwC88Fz>2$Y`9}^FB(vA9YL*^HBDp}7w74b zjHcj{lFM=AB>qZ^lSlZ3paB46<mW#f^wL7(nZG~OW~l*lZvFE4PPh-BUoq*23ip3S zM_tzi5Kuq>0008~MQb?LpcrImeNO*!BL-QVxuO-8ccwK%_H`4$5I^9Qu^;NtEC%3( z_NzcJ&$1J=G7I&nG6JRg!F{Q;EWj`5^=&sob`Q(3y_($91Hg3*C^0Bw0<w71f`w}5 zp;-Y~zNGy$x>{?%VVW77uP<knThbUo2;}P>Rs--!s{@JA2ldiO4t0pZ(Ke%`G21_h zKui%GR?X6v7jA$jm-K6wH;#b0U?4&{V-J|aG(2+*WBO@uZudRF##S)>HT4h01|3Tk z&T&12XC&W9@4vJz2Mw3rmM9Qo@1;S2;<OO)Qyw%-O?G990*SI^5Y$S;MCBmh5It{+ zfiQNVF0~XH0U4^S4NAx*B{V8HK$y#vyo=Ew*sah8;F;nen`gkKDGFc2q6IkM50t;S zgcP$7pw>8d?g$0h59$|ff^&BHff`@I#A3!Sw%kQW7oTt;7mYm)0C4V~wCQpn*J}!d zpR0$Y^8iWZHZuY$3J5BQ1Ol}1W{`mZ?m&VOVnGfwEM?{b#Td(wmMvAoFa?+#3v8-{ zgDyIKK_8cXNo&^(jb-G|A!Nqna>$C!pF(zYu7})GbK`$YQe~D=iK?b7CrhTWTS@3B z&sVtZ{bv+uFDY;0U9==WGaac;l_YYhWqUa-0;*9nol_cZzg#fs*-x4D{K*QYBDG-8 zCSDN!Jd#Bsi)8y%k<4WJ(C>m3)>y0Fs-S<KkNjq0_wm?Fc1E$kC#Tf@Vizr{l!;vT zm?>3I*7-w+CRvJw7I*BZw2i9LHcsXcCFP8fZ0q3`KCGB+tGOy+McPr$2KCY*<;pl4 z@%UVV$3!}5MFGj?3b!dG3dxm|ACJvtxRkb|OLN2|c~AX06aRk<fifgfjua}8MkT6H zjSOl~iz&#`Nu|e0lP-fnCZjAS*>dFKEs<v_vwQ`Xu_#nzIjdqNN(ok2X%(9vD6^W~ z8s*k<s8DGgkq3oFc=`A-0&ZKz3JSR+Y(>N>&YGwg-nzIAf=vlqL`f-Wl5H7TvYfmf zih`mN)vmHVnu@A@x|+HMLsLuJU8&Nf%aAEcwj9^xx*^X^Of2~d6e?1z1Y4;xw{Vo> zsyNYa?zxE+Zf(6up#A%<7&G7@Cy*Dsa_v42#|TGmj)=_6^3%>0tB{A>TF9|qg{P_{ zhAVeEg}xv8nLtq-JNN?|Ckwn>R_4q2%fBO!NhHqY*6uIWL)e_{5TLj;s3Z&Vam|9b z9tJYB>9`9iZr{uZ>KDWCZR1$np&3%?PNrh%+30JAEkONJA<BdJ%k033v1X0i^YFLb zl9+C7OJ$jp?2;bRtm`E|a?ERSD#$u5B2QZ65D%8xT}+xPr&e79fC@~GHevuH7)8rU X&V~Zx({w!>;S|GO?uV<zBLM&a?Od<k literal 0 HcmV?d00001 diff --git a/.next/static/media/9c4f34569c9b36ca-s.woff2 b/.next/static/media/9c4f34569c9b36ca-s.woff2 deleted file mode 100644 index edd834682f04645ed69f712d97ffaf1618401de1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 57244 zcmV)HK)t_rPew8T0RR910N<Pd5&!@I0r@Zh0N*SC0RR9100000000000000000000 z0000Qgj*Ydfm9rNKS)+VQjjYKU_Vn-K~#Y_0Etj9Y!L_wf~5$7`dbT%Ish<)fFc1l z0we>Ja0DO)g<J<9Taw*zqrh?Z%0$tdRh45j=lT7Y$mWjN4CH17+;^3~j;R>ilDORt zK~e1QY_k9V|LkKTV|fYQC8cde035GuKadcFAQDlKvrD?9%L$xZXRx64o(&!BQJ9H3 zP%54oS+(dDYsnyTj?9faOF{<-@?6(LPAbASx}B2?-Bl_Chd_2hXsHIGB{B)UcL*WG zE<^KY?=L%QrW25CH;sKEv^tl4|DgHD?xpiFbY`rNNz=b>MO~bB%a_+5zcr_P_rUeu zOuyYO42L046Xfq++;s-AK*J20GQIKPe=*Y|=n>p3y(iu_{ux>M$F$>g&Le*FLlpd$ z%WjbQm=$Z_$FN=s%goWiCB|J)ULtgJYLi35@6$XJ>Cn)j;ridEP}w0IIL$D}_wrtk zKc}w)Y}W!&n9>x(dZ^$3f6A@@ePYx&VOmhr5}||uB}R>OgcxGHsj4JJEJ6uIC@{o; z5z>&x2vO4zHD#RM?E32s!@ydrdwzqf*BktA@!p?$@c%bW{F&Fy>P62q_4D*@_UGQY zGnpilWD<rjBtsZNfDs~%8Zlzj$p=J5i<Y{!OS`t~{{L>5Oj6hG^X+rH_WO7LZcBf! z_Rn@{YyYgJib^eOBScLx&=7{1>FM37_d-C#tTG(#P_vm?ZkD-YXW2b&irw?}+X0-f zv)`|^<$nI&mRIG?x^*Fm4&y{O>!6d-h#AdbgorIhY_NqEn$VCYG@%JiXrKuVG@%I{ zXkr6RK*epnaf)~}VR*>fKgU=Mi^(-1aviyj%{}Mly2r*HbFU0zi-p`d7jjoiVntDw zbJdEE%K!FD<(Gc@rP5Eoeg^2>^e^EE2b^%i2?rc-z=;P2h!{hZ0|Ev;Bx1y<0VBp3 zAxgj~5u*nFv(#p7YN=zDc05O0-kSN+mbN^XIohU<*YRxX(k`{BjV{)#P3@^EM2(mL z0Ro0kZ@PKw@BJD#b;%J-*oJLt8j~)KDTesqm0S`xIf@&u#r<y%Cv3_QR*5C7=mait z5>rh36j{ZgPV^MHWm8UIz-ipnNmle)ozS(iz>OAUflFO*rK{@xSJLSo)Yo2G&+P8J zy(7f(C>D8|EKyNoWK<F%uRI}1<P{1bqtNMps9@~(JBw+=Q-Y=%s#^3$B4pD@q{J5r z5|a4;ckoYL?7a={0J9cuyz&2q0&9Zc00XAr_UcpD_sp)eaw1$xv1fKA%bYL!g%rL* zp4G0b#jNpS3r8VjlY}i`F|tkw*_H#G$mU2Q92hY9VsIT0|G!pm-QEDfL`Hv0Z+iM8 zaNf>_LFYsQ8Ox}`j^Gy0|Nq+e?_B59se5n3`!4_>0bS$&9GAElpAlEPs{;;L;_#6` z?0_9Zp>DY5{RMqKoq8v5nC33KRK~S$r;#R|?IH)k4WI%@C4m3Or+2E8S(#VS3RPBS zRVZSuJ6R3un1(vk@3r+bG<mHX(U$(RiB&%~(GE?hW8Jg;un+r;ALcNJx!{Mnzy%IC z$R%9p6%KMGSL!C0^pZN%O}x}iyv$48)a$&;>U`<6=WVTIE1Okzd0FBRqQy;#wT`?N zM7CvHHZlk?D1$r*2}Ur$AO<nWzxUJcr&i9tpGv96J^j)^#fcip9Jhpk0|JjGp0Ad% z?%5^8AUrw+k46}TpSe4Nke;gl;9s0s(wD3_N!vZH8!Z6Do(!NkuK_|D0^0N24822L zs9Q*u#q&M;;y~Tf9GSH4@<et(toCZ-B=>-L(P~Cv%jSV7VwZ;*XRv?+c!34@i0}Wa z^Oe$Tl4SWwa_kU&r$k$q6@W&xqa`^VGZ$yXsms*+x0%jpS9|A~{}&_&sv=dnATkQj zz<>TUySh$y=~Ab%-36g@6<|S~XE$cVXNc9`G>+*1&1ssE(14eu2fzEFUjJCQ;uZM$ z;f+|R3O_rqss^moO$Lt;4zTkvh7Z9Y?0on*z_9Z_nk#KK^F`EvMn0h`s8`~$+59{Z z$f6@R3wZ+cRTZw<RoYyE)XDxCt^5C%s`cA<s|sL2rqm>5siBFGXE+0mCQ#O#S%aZ_ zG$G_&{2_r=fPkt3!~#IdC={VCf}~vlM0Wuo)Ci)j0w|fuNph5(CrX{wKI%R_I{kqv z(FO_8A0z}f+w82C&v-%z&Oe5*+5W}uFP48l>z{Xjw@RDM-z`I0|Ls2?`f~5|vDBwH zx|0l61ym{B{ot555W>Op^vicPZ%@+I&UbOqC<b9tHO|8Ozu%Oqc2G<d5{XKy!XqRK zJOs1zl6HVtOi}X}rT;&tRtpmBL+jOroQg{8yIftpRW<Yfj0VksgatT&BhGm<wzLn& z3n6qNhPFDtZ<^9Ojn<{MpAN9a4t{6^{iKyAi8SfRmr^>m*k01vK>-*T44N;?{LGU= zmR0%+L;MNG7%+#^OuOHDtl#!o?JK$aN)C;e+|-jqM5HK0L`3Wf^uhmc`H$bVPd}rM zGLRAu7ZDK&5+q2F)PAP@zxNbX;l5}0d@r&rN*N=J_8(*WzS5uN?Y%M(M8UuzN^}GA zi?*+lVAAjA_>0&w$j>m<--F&+x4e1%?sa+jZmd|cE+c`&DL{zy8fq5gYmI!X4D-<` zn6gHg!w6%9HZt+dzYU7Ylm1@?^fR;}OO8;k_$W`iqQvT>8fuLS=Z}haJZgQ>sEw&n zSCop{)kxHr8;|;CGf_Y3a?~%X1lyZC*qwQT-P_Gzf9hVar^181P<ODGV}l)QJlID~ z2b*X%*kp3B3$2HmZ8lU{6d*KW0AUdah!Y8jw+5uKWk|FRB-VN)ku#FY8`)9-az$at z)kPxL7K>b0BJ#CTkZ+ca{I~+-=g~lWYX#j=C+NP0L4WQB=;<av&vq~9RbxRP;)0G7 zg3g!=Ix7`ajD=h(42{DsKy&X#^X^3xuSN6kM_Y3oP2B@+<6dajPeA+mWV8d<gP{P9 ztO59dBLSxaE=1uU5dgqqfdWv#Y6zfEq00wvd*Ay%^3hLz_KP&ba=akQiu&K-Kto6l zN7RIx&ch3U1OQolQG{wiy(_@VZk_@H0$O{Q%1W;3rLEbOg~1CH3<Ls@9SLeoA^;3S zgbXZoD;n0%jufV_9%yoEdI|v`I3WN45C9~w!0<>Bfe-)yar9#nkm4Ik(}&YGHFef2 z)?O23dKs7zZ<B&hiQp4T50w5D<CW3MNt}0?ZZ#@@u)%ZZHdUVLA6&ruoxg*NHq9NX zJEkzD#v`V%Ea9BkcaGjwlg@sit~}MLKhW?PnLb)=M{Mxs9X#8rLD%4-?O5$GZ*Pe? z=%v<an8{~U=korRk^mPYHF0f@&_wEGXja8tYQ2JNX^v`v%GI$kwVHeuHJXGzi&WOC zJubbnR$EvA%O`68yQ;?&))k`DlzNEXC@|K2peKE=)N2glgvLq34JYnPa&Wo_pavP( z;5B)bpw)EHoOvI&RU=MYBhy&1oT1#?Ii>Po>#XF9AnRwF7;l3{UJ5r*Z0Ir6H`}ao z_~i$}ckqB405%DB1;7y0BM*IbViO{-1zjZ;e_Oegg&OTtAC0$kZGMGX!pzS52I}T3 zE+>#arnu$0aiUv(iaqj_&!v~Kn}OV&4Y8ES#Y&fn8r`v4Dn1!)V}j<XMGv8Y;O2Ny zOKRI7$a4H}m9TSSaTaqme1W<c=H)=-lqF|E3|17qmik{sw4=C$rb6GUF;z<>Z#`&n z<C=XS+JK<;gr0aLhf`iJXuFneSc8FyQ$!|1T?5oysmUwX3=cfL+y8o@;>m)Xs@Due zt@glmpiaO41Hzkh?c_ClDriyzyu0z%A54O1*SY}WnZ|n<@EovK)BNG(tVmfmZA!`< zp|!qmp>g!ZTHC{XhPB#THME7hUd-9Gi$OY5UYJ2IsQENw<(u<0Fy~PpPNgNE7VmQx zrXF~#WvQIwil58NrK?tlCdN1yD+F@~^QG1<O4fSP{JBtT*9F_%0F6t%5)l8x+y2!l zUd^1aw?ItG#b<Nwyr3VoI!H)-GV^i9`TGch)>7dX)S3~w1L$!H1II3I13~Vi#w64_ zHJ<ptYezx;Z|EYh&n4&+<=e-+h+aZNw+kbGj}b%UJ&5>7C{*h&+PsZiMTd@~#>_k{ zm$b%>eM0g(2!njflCUCgVp6)K7_rz1k|6QM6`QcZfEX!b-jhCf=LKOUq8=NXkS2<7 zQvX}5a`jA&LixB#$K|?Y+ww(3h}YHff>kKj#?%u%OSw>6(Be$U(E4E?Ldf0Jg@t!z zmX-1(2;TDaYGaF5CtFmTON5)|^9WTrm&8EEn$Cv)_&Vt-+T2Iy*C3|#RXg32QQG0I z*D7k2ek4+-l(+9GV=v7|X6)&e?XbBvaT|Bm4KuZo3x<mAEP&Jm1$Ytrx3DPWllBvT zihJVI{1QLV(|!06@hf|%{u+<)Yo1IGaNN3=Hmvv!f8+0N_l2FlWc*{RiZLd6%UXU@ z(UvqK5Cr%rjLUCvdXvhs^$vXQUqqD_(nfFL+Q!uJW`3c6@ZbE30^nN-$aA!6cY8{} zg<KicKtfMg2+xWO;>8_4fP<A`*~}AaIbgtyGKS1#znA&R0Z6nt8)kIQF>}b}W)8c; zOuK8%=w0Wd1NtZFlthL!Aa(TvTYb2Koc_HSfb>ZNq~E;WZC<%txU8+$_t!`9l*mPB zc+n*<X}au6xmrEO2v~9(Ui70qJ{&6JNcMsRPW)*Ealp;1(VgP)4_9N%0HQMXj-wvC zZ*OgHu~=KJ?kH=2=LRL{MxSw$jlM{6vrTRh_9eH9__8f-qxy>5ZIy!sOIEDeu;s{$ zHy^(I_`|{p5F$dPD6t5L5+zBNB2BssCuPb)k}XHBd<6=fa#|6JVkJsZm80p<iK$Ds z9vAiM({I3_p@zLCG-TL_QFr>b?I!K8(=G{j+3jAB(Cjng2h#TYA>Bcb`H@*acIe<I zrM!eshrDQNF9D-15j^dFQ$R=HZU>Na%9QDk>*>?oiI=BH>vhrxww$8-(6*0ceC)I{ z3}>D53Df!i@9Y}Pg3j#9KmRyGb1zZCmvk4jX01mh8#10W+CREGgs<gGjf#rZ)|T7u zTkBEDhKwhTHsB#%00000003aeoqFg1000kA17osUUHJO)^VG4Lnwp(s(L7AZ_|<~N zCVWHct6&9S7=~dOh86Z`#Mi^P@8m77_gP+k6jt*ccI>(^`@Xi@1&o8#YjmVv$Y<oX zoqe8GrQ$J$2S3jx*5LSF`THC051+v8>BktJ5^6_7rBbO>DwSGI-jb(#kG!ubYHuwX z4&r@ARR@<_LNU?}@$?|7eSE6>q79-=!WhWVnq)J42`_DTr(JQB8>L4klgVT<nM@{o zA6C_?+@~&ZL*nhNcsE}+0~T_Ry~@Qf{moByg6-dSUak(ex##0w;x&c#X>;1#qpL!k z!7=1R<K&}L7zZ^>-U%o<%1rz4a&%QyU>N4_G`>@265uh=fdAr3d7VHI8TDUK3}?>q z38`y5rv7Ili@$iIMcZ@v7ALbP2e3LD^ea;QC1EH_u?-{%ld2!G)QpPkLm~9LzRtl9 zd;i{8N>PYY`;f-bQ_`+Erv|`o*0lV`F20y9^~~xQGo0&Q5Fe=SMmun-453ulAr=4t z0001>;ym6c3jn}ZTw!E9&;kGe00000R5Eyw8EXLm00000065a#u9oXfZIr<P3;+NC zs3PC;pa^3yVE(4LDbJ+FoAqF6e7z?=f9K5Hr<d<`{F*I4_!A-!pFY5G4?Mx^e3MC2 zjUnhhq4-%Le@~y;dSy%7T2Zc{h2JdqM~IBq7zU5)kTlHX#?x~-yqV$TknEbAS-=Z$ z5gPDf!6gGPK@%>+75i!p5ho{f_^gn+P8SV%Z@DOvtq_B2Ir{5zO1nFPrvxitb3I_d zfB^#r449bZG4|YtrvxY9z=3z?7mHB9fol>6aNxih?}sOYsz79$>Z0xIF^O~N%O|te ziaqW!4%yu>KJlBL@wWf@|7-d;v9gR$*8!Ulz{SnO%g1lXuo0uitPyCnOKkStdY-?$ z-K_X4t&!s9nADEDpE33ccfUhI>M@J@?64$GRs5Pni&Yx{P`?HN3<v?S!0TZPK|(}H zOv)3)a#fVGEgLj_A>A&yV`jSWpD=m?u;e#4{2<Vtr%V)-%q~8+xCX|W#78kis>l)f zg8xMkY7QcJAVY{mwUBmj=S&6v`UUVLl0^{}w2wQV7v9kOSO)!E8hym|HKdXL#Y#@Y zq4?|ZiqYEPZ}#diYr=|;scK?XJiEb8L9oG?7y}8_Q;N}$5`HMg9QD;Pgq&}i(E-ul z4m-UMxMn~QtBXHW-H*sQWG9?NU>eOGAJ2&=;9^4)r(9+aNbPu~(THdSk!Zq00m1^c zs)ZLtJ<KtRRI1BbHjr*Ze)hXiGfe6s`U&vNzj~MBBaZq6M886a?-1%=5H{S2bykrT zr?_VU-@v*CC{)Rsl|z(82S<B1mOO@&qx$}RcZ)R0E>*%RtD==l`6@ME=98ZoH&>RH z(u{6QpBo>inNTtNb^t#oc7c!&!ip#@(xyaZSFM#Owstdy0v6O${;Uq_LTe|8oWe%X z$=#KhpnM3?ukuA7aLwY{od8Vi{dF50W%wba?F!JF%GTI31PYfGygX_-=mkr$Lcu!$ zz_6M*JQiP->QXfgj*~0(thyXfwOJ_D-(nJW3z*+E-X{P-3hu>_*AT(k@H1bruV!17 ztt!rd5*C8^6Oi;n&T{<{lBW3hGhGIOWDtlI#Vw$^2rU*`AqV|Z4h**V4%!KjS_D)O zQfD!Ph>EjoKq?qSyc#xK>?oFWd(eEuOQq_d#}dC{)i7{~3!FHZV-S)ItB;35h>LCT z{|pv%db5pf+<Q;St(?svY@%C$(X6cspo-KzqHv&fZ%;P|mO}=BYq10XLeQ#@-z?(U z1U#O?U&vK%ufJXd0n%%Cyl*Rm0YHUsz#jM`dj06+D?30C(uf0wzRYVIZ;_R7M2%x9 zj{Scoo8NTf_Fe8=*8b>d*2rdanS3&@4bK*$vy;SBI7Me8(@c`haFg5=r-^E?uT&_B zSBDx>!>X!IzxRA+zAJQRM54>b7dN<MG;D>jNXExv4-hZ_WbN0n`@|uNKa+k;?Rh}& z2keXO5MUqxTE|2cL_Q(9DB{;ezK6h{;$?gc#$cyVC81?l8C_Q3H2*XF6=;R;ta{GF zc{v|Padz|PImcBcRl%LX{VazGHQ{D3S8zQKeV%h3HXqKN95sO&$DdgL!degF9=R#2 z#clCeP>XK?xd?nq0xf6@*MhK?9BsZfyq%*35FJ4F0n-Qd12J`C3JDkh^8WXmF77bk z@wpr-5+-8WRLl^@+x#d%##xF{<rWJp;u1tOI}%OmafM>MY<Mh)SS76(uNfF^Y{Ita z>La#7h8MC)@wLuS2NI4m;S6_Vl_k^_cXU{|<<sl#98u1-GP!oZ;+!KXbHBJrW2(wi z9e5TwD%N;d#3%@vBVvc*)M$#`aIsrK>hkjdCX$AEk7QOP(!>&$@_a}%n<5FR2@OYR zDpGSSXM_Y26i6&FmLN2RA(kWN#bIngF-4YT!I>9xv_*mqVpZe4!ouBVOdK$c_0=fd z{+YVJ;cjYzbzVXR$?+*cg3y=^OMUg8RMUm@QTVE@+C7Mh_h-kK*?QVmuSQc@eL|9> zJ7l5jFe4Id&C8dR4S6y2Mc_Yn=!=0{qrWix=R~+HLUT86hbgb?I;P(NpBCmkYz6p? z&$3`Kw+uPK8*CgO2PZTNNH}A64B4M{FIBGuU#@L(O41b2^N&X*GbX%@TY?H~jlUc; zEQJeiFvy491~!)jb1cH6+CJFD-4DekI~L^*Z&*cPTI%xfyc`}DjO+-1jq$%oMucW$ zD@H<9@m{yqDr;Sstm7WwFu;Ybmg5##C_|1yfIn2PCAhe7>+|@1NBn^m#eF7SaE*bx zoO50aJ5Q@hull>aNFWN|)^Rrx#zQ{83)a-8WwGH{EKbHD4oJImq`hejEmu2M@}4uK z+bVg2;Ub1vn^wZo78_TG!LPtbf%h6Gj^rumZbFE{4}#&R77=1H((yP2henXxr=C0{ z_}d*Cd=%)thWA%m?bTRzArjhO)ET&6o5q(#kk5^S<<$#csSDj9?7|0(kih@e?;5vZ zFFRPdTIHy!F{oQ9qfws<cU?kW#*JIBDi`2uE`3b^|JZGH{Z@o4CV^guE=j(e76M=x zvEtrWcONVQ9uvdoe@eKJ9yXIN3AB2_R)q`>2nZ}N072S!hXQ<gCR?CHz>#yRK!^|o z$Ot2b9;VTlB}*O<0FZ~Y8=PKTt&!H9@WFL$iPm8iknWXV_AnuMajlh8_tsxrUqp!e ziiUYGL<&selQ1B$bHOsTYbDm^ld};r2r#KIZ0A#B-PG27+oKJ;!jymC``aDKkvVti zw}cQ8pf<Lk;IsNx5cpuj)~DyaKOYiJUx4`5(~r%Sym{Z)vxV3H_;Y{=LPINXawl5n zi~j!BaIF||q<<gZ1rx<6V-Vo81d)#{m!Bj_BFPGpG}ELgOvtNI9Mt5HW{0)#P=weL z*b&*2IEZnha+Tn30FExepddqYEmB&vv*J%OA>E`5IVX27%>~IGS7a8&oMP9J-Bzg{ z!#mDu)Z?0qyn5YoMKhKbR|Sk{ciRI~dv!~X-g@;#3e~5-5UPFyO_)ry*nBDLE>ac! zx-KYq*O?V>y38kYaDmdkt*z#M{`Kr6FaYL9HBxD1;Y&IBY=+Z5-5C{op5yb{_w}?J zqyAD89_^GDdW^Jny}y}n1G{9G2@_XYdho<M&pq$_<F%4cn-RN*3Yxs;`=VeURE09w zfN+E8!iJ(n{HKjA#I~3V4eP~(Im$@zA=R8}c0Qq)?d?}D!pW(XJEepL1|9>qX|=aX zwv3ipqD`x$5W_-!#5w2H`cR+i`VAQ_g6XzvFw@hfdxQIDQhe`~R0}LkLhqP1|EI|T zjz3u7X3fr${LU$peP@j4av;D7KlGyBKKktQR5v=O)f!!wa2JYs%wh!#aYTWK4XW5d zz(E~BBcBkzCX!}#S_ClS6?W88?b>y?j8DXI9imVa9=dso!|39yhnId>ef*q5FotMc zqQ_*KlI1*-ylfZcxg_6Z1+FM{71jSMV^!`wO&T=2=)6l>T-M==PB#qj8T64MO@_4^ zb;ot6F?Wq?!`9)BPIo;t1IKCDNQ`JBMvGz_HCD`c<GAAZCQZeQH)XnMGYJySnrqQg zX$xj7x`Y9(*WDvXf@o#Ye{X0_@|HVCZpup2Qad_n%r9=mRdble-dQZvum!vKeCuB9 zz&32hE_~bV%b3Cl-|?kmTyrf1a5oGDAuHJLFKKtx+y(sxAls1}beQS@Uqw4jal>x7 z3lGBzsx>to_QE|>Z|a<PA5X^snVbWd+UFAtA7~Zw8CUP62R!b9llu+t8rY2e+IWNZ z038TP8<~P@hXj&lg)$<+<=`8s@Ti0&9R-k@0z3n~i(5be-sDnBgT5RmsQu~#nyNIp z#wBhVIHu5^)8t_^4NFnlGJ+^vAlf7zqCYek=pRBXqp_3NS1YH4kw~A_WE#}`qXXH& z;M2X&dDbg+eLguM-V?skuy1<*6@3ai&Vq<v4G2g@0ZN6$_DCQrz-MM<7r!BuLDjln zWhdL|)DD!=vvf&l;WS*O-<^=PVG@)r6bM~4+E=U!Sq^2BY13&#A;^w(DzqNJrxO(E zv<N5`SK0458Adi9BoJ~Tw9Bk)g{qQLLn;8J*-BWk2YcL}Sb2av%|nEwtTKuSgkn1> z+nuiL09f7e;|F7-W5k6hP{gE#5lTS_H>eCsEK2Iq6jL*OyFqA@u*7m{KuHyqWl@R= zXq(hZML=pZumDx1DUJRuJh4Z&K9_cRL_3u4v-|eIcDL9$mT5~-#-#EIa^<>-N`PeF z&XBt*MivXC`i9U2f_NM@gGeOwT@Xv4#qK@iuGH7A<~f7KZtT^%sIk2@^)H1c*x?C* zRF_fWPA)rYMJiJXwTCn%Ss~cTgjVSH7K@^c_M)7i8*~Cv69tJ`ei@bbo*gIW5<w)= zQp$O}cLs!r1Y@%^cGjsV2YFsaNY+X(9gO>I!65Yt^hP9vj#ezAzUyQ`tLI<VGiL&4 zLwm>_p^G3;imt&gmrn)hK(|lacn}7U&imI+8(nH^=vQ91t7Mh8Vm!GnSaozcG*4x( zkcOtiTYXBmFk?<LxvVMFNEi;ZFMr_f+DpNPGiSJ?dL9;npYgOq0zkN#y*|V>fn4Zu z-L4eT)(&ZDJomgu=iIAS#TWj#%dT4^qkwVIC0&CTXNkSHDDT6xvSaTW<%19`=yiPI zj(S}QQ`^`veOOEUksdVcT9&mo`6O>!v3&(>0^{53u-5M^^**EcS$oXqlR-$GzqPLC zct2A4BI%$BXeBUFB&DzG6Sq4&$LA+H)v&zPw-yAK7BL#O)|uCMzs%*x6K#Bmu#2jb zqy(@pIhoDRqazo|hR$r59A@RxYj$lO2Ei4#^_nKK=1hibJutZwC#5se(U~EaAtw%K z5nF1V7~c!eNMU6v`4Rl|-EoqE2Z!?1Wrb}%DLL{K9LXe?mFKa@*HaC;Hkbh@$`GQc z^!?nVmg0kqms&{k4`#d_4Y-vy%``=OJC?yVU!1)9noY_L`5ua^%GD4GM_tgUiq^84 z077>&&k#;0dwk5Z?^%pjgK6CaG6783B<FrC4lW4rT(t+@vR}(%W0Vj87pNL`mlV$T zgsfHFTTRt=z%NMvf&n(2`=o>#g^L3p<2%;sml1rV9X-S!FtR`t6=FEy-<q*ilhkEv zQeN8JgSbKg%Ymnq1lBA3#J*BMNd>X<L=(t)BScbUm+bw-!;e~plYm?m+Tz%#|4crk zh@vNNeG-&!yb|SdC3MiqH$#oa6ZBjgw)i#4eFr_bF8F_y<lzI&VSmcKY+=j95kOeL z<M<2si{&!TI%WrP6L4t-2<AXUT>QLC9Z@H~f;dlCZPEU&>8;bcEGq#zXjZERE2<Sw zn*^NQ%Rq@Z+6z44Q2w|UUlwNf9lKRqr(j=!;2jHt6y@be<vmy*A%Q*}Zxu8%H=z#9 zadQYyCG<~wgVuaVT%Kd^Q6L*a@pT>rThMmcGNAJ9+}B!-!X`6p+*-qaaqkgtr^-1u z+<LtZ8QvW%#Z;q$6LZom+Ud)`tU`2*8eG(3Cg8A9=kGjz{gdLIwr@&~h!4O4d}FOX zq4*3K%+w+-n;HkQmT3%AWDx-gGL42JiZ&+Y^pXpJFo8&Rj0cisZFT(pYPR8oJlVmF zxuBG4!X^CPab%}y3D;<1a=4u*u<_M9c+6Of(`m0;9PkVKl-&8K<as6C=Xr}SDDlP1 zW-3R|8o>sOc*vpDaBZV--h3C|i7R{Jh2+1x+>n<Q;DsF+w~~L8OLQ(0@(`l0)ZzTJ z4%@c-)m`{Dx}C<@D<*&LzHbOq0GY#YL!g6y-ivDn8;@C2NPF6E+EnQFu-gHQ)YFD5 zTc$|FQ761#xqaBfK&vj~^<yvH@D@QQlJpkEdh#uoDY!5QxSnz-H347VAP`;{uyKNe z!a*I=vOuH&HE>l1Sy}jg{-wf!bytPJpo>5&Rh3N;fU`mo&mOEIej`8k_<ZRMQ<=Ac z`k3=QU|^Y9<fxjkfrA^2ihIEo2k&km6Zhr^RjZao;u=69beIU|1aio846EM-W-P#l zxYrK^qN?ItG=$^=Kt>sBq&9Noy*Y~*@|>feU9Rn7X;urfUM;($>;4cUIo|Qxd)erg zaT<Tlf1C%pit+enB!5omG3AcckU<kD;1$LWY78F~f&crCsCWp`eFjXM6!tNz{*Ylp zvxo=>8v{q^!_Tn4@E#4%T0rT6aiR?Vt_BG+aImP>Lgq%z%0c1Lm<74#Q<w)b&{UW# z2YZ)|l=KMvDpkad{J%sHrTq`w_}t@>_rXW$x`7$HKu9}?Ls}MZ;+UWE2*Tb$10&Fi zpZiyQ&Q(ImH~xEqp7HA!5B;E$e|fyUAPPApbpSU@5R_$Hd|jis`>z-}=yP9*FE`ZT z8C!FiqXxigyV-(6*q-Xdw4|r{v4&yJ7MQ7Dwi;Qzx0G$>d3O$9a9!c|MuQwk0`Puh z%)LJec<S|)pl{Vcm{>*Uzw6}yF29rfayVM75XgOxuS1FrV>k=<{20U5atx+PBya-J zr}7O8<J%rJw8&jG<~zO?5;JPoI2b;)xuao!BsrEYwXEd*%^zowmNW8^#W%+#+@eIb zq~`9!ARdz(v7M<4T6b=#yAK#QTf`~YiC}BZLkak<K$&YiN9`)9R#?IZ>fBl~fF@6} zFf0`ASAxFiEfyoVUwLh8g50z0a{xjLI)5&1$R;w(wt_!a#cMbvXEX$a&)jM~^3buV zD(l}7D)_T%T%!n?o00W#Uv_-JEop9D?8j<n>cx^jO*1=yocaU`p1{$9W+0u-a+VzN zsoaO@8}WaR8Eke|Vze-6hd;_1Oc8^*$9%q@V?#U9xyiVAH#6JUG_SF$-x%}=@9-3~ zyk_oF6&8riJ7|vLOCMRl>AqPaCW0)b%fk!=DL0svt$aM@{JY_vS(l;D+FLyGGu!8Z zIet)wsC0Y6RZtZt?fi5iYU3mYyQO=nQ)%;V_D0Y4)5IZ$dp{d-v5#Y<<7`0O)oo)J zL()isSr%o!vdUpT$#BLk3g5Nrx!AmKz$l60x~JIT9*1NBRbYEm9I(sd^VOsSk3qjh z%IIkXju7GvKe@!W*P#gjI#2+Zt&FjSt77yvjssE^cZ3vFSN?LsRr$%`@n!|wtU-*; zGE~xkLx}Gf)wZkMn}Z1tKCa@2g~ffkB(SaPc&JiO$z!um)b^W}fgjq*OcXHpUYMtc z-8}u&%|#_WRsStJZWy#SU)*t(A3!7_#yX}+F?++=`>kbJN6|Nqz1+EfNM8KiV^SK) ztLJ;@e>W4gX=qQyo;huqu$f&wRTsWDS^IAKH0U8Tgz1e;H#Nl3`!WhCR?EdpYFqAU zc{G;Vfw$ZMU_QOIlH)5WU>+I-NErTSDcSGYht#NPF`O7w1)OKQjNqPvuzT5!0f!%^ zQXll?>s-d(K{Q!rMDjrb$>7Ir@GQles(@bJSyaZtuNYNlO8de+k1jel_$>KvEmoH# z^2znryPT=`=;6NVe!%|HV+VeaMsuhj!m&jPS8IGNLW@#>Ae6W`*mf5RQ*MLvJ%C8w znNxRIP}|LU5kmC?x)9CmloX1IhnTUeQ-F9TxmDF#i~7eGZKrT+uiEsRIK}_Hk8(aO zp$YzZP}&9alH3l)`Y>AY?U5PZICJn!VfmRjz<H9HLx$Y@dIHmlZ`kwI<?y1e5pygD zwF|VektP*Rm?@~oY(F<NDUbrzf`%BT0orm<B%8Ju4S)8u)C_d*C-EmZf`n$rX`&39 zqR+sgIFHMX`*!{yZ(-o*Y`;Z<niPE7YiZ+4tlF4pu~(cN%;Kr5rU-hqk}ijv)#jt^ zV635VTtmwZGibDDZ;K7Kf9&nI?tP;I?P2_jOX;;q@LN`CTVR*HRcX3o(<XwTc14|p zoGG#c8s8NDPMW2&4pIpmR6Kdc!YSm`ZK=Q9d#T6u;GZf5_NouHNu%QiGx;Uh*CF=> zt=V2{yV`(dRr7)do9y(N&;))EG^`!OCF5tIZ$st%fW^D;WbR99)&t0HE(gtKopKzH zAx*dBIK4u3-g?kcNKWMB0W2!Mh*CF0DV+P(iZyE8z)McHNhFx^2c6O{IeooFklivx zUq(6|p8O+bJeh|VZHjn!(c^F=1B;tn^v!xBbf1JD<>M%c+kjyH!92ww?V@P=_sd1{ zR*71T%thFCSlK6s>Ojt^uuzA&AJrQmy|v>RucMSPyFpsEH+WEt3lG(c+nO*(WnON& zeRTfEpnWP4>mmv9D4)7Z9_TGtUu{0mGMCrC^?`Z-Ks^*)99x)kX#u{XCeU764!Fr< z8m{ijROBmy>%By6C7{Wjd;L_j_8-6Mae@N-(16cpGx^L(0e>5aE6tWmT79m3E+6az ziutGVjg|kl(4()k5W*A?F_1fjr7wCrs=pf5eSW_w_%c6TnUXp>msYXA!6UK5(z-J$ zr>1%9z_?Ot9_Q<EgoO6pVUS`bZ)DQBq8LD}rh+rnefhMEiyfI$)=9Swr$$doNU%Nd zx06zPURy@5eCoamv+3I=3m(xa)_U-6zndG|nHL*pJNujdCH>t!0idT%u;WNt7~x^= zt2}u$QOhn82f7?s7Mb7sZnFoylZT?UbpJ?ddM|Fr^ovK*_K_DF|NRVyBRWjU!%tY_ zH$Wl-C`R>%_Fi(G(64#p|4wX@e)-MyrT(}7VUjav*8-r&w^m^fe_igG{lXT>14sfs z|K^S$AAuS-U;qGxNlNm(!z5|)|30@gWr1)nQDblDwjIartZ4ahBDmm+2HWo~{yLk? zCpUwA$49Vl%S#=x%!3`{@?Pc1<BP(`J@tP(Wio`SPE6}*%)VuxbyIKZ+DQqCf1Wg% zx;qMMX+cc;$fWRL{QtksC-e4@j)U#}ZePmj9}jyrEc7bk`J+vHD$RgePU5z4)kP2* zzb*<Es6Qp2K@zOn2&oO0cyQgGKb}!$_ZL@WZuLd!l3O#Ndf-+HIbcO%SFpUqIW&@M z+%|0Z9QJVt$zy|L-#*{Ce}8r3EqR~(YREwEJWzuQZ3sX!!1`Jm^L2+Iza1NfoId~h z!d_S?wbe5|{d|P~NGa&#u{b5Rw0$?rIi}@2(a?}Kd7zeF`rGD-IVv{nmg|&ifGuId zS&t#>8|ayf^1>jlO!9%%8Nfbq53nWYK}nWO0q7c3^eY;pdsPI0SP-EL*dh@?+yVKF z4zW8HF{wYXe`?(+=BqsgM4f&Dsx2$E$ufA(cZ1|^B{F(i^GSf^Dm`;z@(%&m1EPKM zWT1mZbf9S}t)ox<A6+$6rLFWs2Dlc~nj8Ujc-_0=v>nXflompp1=6r4Nhh=Jo+$0j z$0N?{+Vvp2ih3%_ygi$`&(iGEgCd;IHANbYIT*Ps_{dxnP19b%CuI8530Bkb8#fwt z%tk)$dUpnvvLk1UiX!jb&m3X{aRt;se8zs7O*=nFu+AQ;%{h(%VG@h(*0O8f+oV#u zNx`h^gXxxTKQ}INbaz?Q#C_u6?-Cl$wW-nC)YU}BfYO{gWs3rx2VZ^+hE#yVtp`Jw z7!Sfo?FoVYc}2dJrnSq~Sj4;+yCi?1evl>UeL=uSpS$_L<PbP?gwe8!IbHiQnl?yE z$}YWyO;`P~`J<b{!E)+0aHySMG_PTQ5$yoVi(uE&G5*E8W^vx3_BLQGD;#{(et4#< zw%hSvFG(cY;LGUR)2kRp%b{E#`MaC{qtEdL-WOPsgZ23f?2-j9f5fu2kKCkpMMY); zsr^A1gR<yDsRjFhBtO(R9_e0b`4;qBbyUz&*h5Lx#`9oweiUX^#f_O!OVGq_R<;@t z=GK?l*<R;J*dmQ&F(vLstAVrOmB13_r5fi~Q~*f==t(U;9soWah%5VmxB|Y%IFq71 zu+G=tx9ohk$m~B}+ySCha-ApMm(K`pw<t_@ZzT-tdJ^vWn#((mgwd_!zHCS`rdH=M ziPN7xnLRM8pS|-xXvbP;JA1=du6(7J@3eq23}t6NPeOR#`g~1Cl*9O@IKi`-CfeUm zqk?{-NHl69f(x|89E!F(@>u}L(1Ze!^^0_biU(a03?ec=^C*Dyz{6<=pa2DOL=^BL zEnPRTk7{X%NZ}aL(sKjI2BHOk)TB)-LWwkXWBcy=&WXk4&3tsuWM$7n<Bd>Do~mW) zmf^=-sjJ1>mymF0qwsi?J3f+6Ei%#_6^Z|G`BZ{@vFQFhD(FY`4Rsba+g*$l%@0R| z|E>fQC$%mXTfg(i3pRPn*G?lD>+JFK`h|ng+3=LBp<R{C_N$e=(9#Ut|H-a`(ysEB zcB8MewUrQV8z!B?mo7$tyEGgB$*f*&p(poWjafBLld3*EB8xM!g^u?0^<A22(hhoo zwXfzfKRD%ibB?jo3xA*36Rg0pv$Aht<JW39CljvXH(nBv<%rYL!BLW37WkCNqMH<u z1Jn-!{?q0f{Md38xxgd8!_JIlAAd&d;f<CjJ)F*`p5s-Wd|tvBIko$YQXA7^aWYL6 z`x>R0duil59?MywI*_u)><%gYtk^Z<R2Y)`CD=e;x!B)3%=sI$PMt?CxR#yK$b`(X z5UL^lb$^F|eLxZ1LtCRMBMB|DI`;+$pZ7i@9-rkjUr&fDX-5h~4qEp^=bCGq7nwwf z{@w)9#kQ9Exq5;y*v$a^W<|V*Y8yb2a2$~St?)vs`iAwxp~N?Tvy!YHtn`W$4m^{q z6DX%l_A;v;*X9V1jFH42H`GL*M<o}^2MOdVnH!)4L_k4x6`JGx0IkT)PZH^7A>hWs zr#rqhjC_0nN$E$38AqLSe0G4i_xU4&&b`@|k%VYUD`GDQpzsTj?Qtd76LQyT=b96t zBP@dOTz!4ZVq1b}Z$D9DkqP9vfX!!P#I?|7Z~k(8=`(<gYo_;?g}^o;oM5k&l<I>C zi*!d}f_6M5bF6rUMXjCIsJH|HF>BzD#es~3K6VtP<5qdlV$xa`t4d3b`g8O=>-i7} zSSeNyRsc-?SqkK?>JAm!?WVw>aV*nC!d<kV25KLwk#LRt5uZqO>z@#!fmoYfbZsFl zGwh_w71xLIFU|9l@^gS#1=x51t^-%50@ObPMe_(j-+|zI2%7%`d<z%+m9L?_H73|8 z+V}X3%ed;>pT;>hi1ygiqp>ZwwXa>q?g|ECbvUyvqY1H;R>eI(5Q{91?HlI7M0#uI z$`Zd^9whufS6AP%*qU(gQBK@jtO7_^CQ|^Q2=1bm1sgRtF1)9dgT)mAXJVQ=ly@^e zWeRN6{YhvA6H7(b?$8-ZfA$D^*l`mKlzs8jP1?8N6~W5ZOo*pEeZN6jk`vtkVhCD? zm|eg<A;!hU>t49ZU7v5wU%~<_zvD!k-+>vm_~qH`W|$((3q!#4gp&Ny5W=;dfl1XJ zSKO1tQ1x*Wkv!AxD_RfN5J%?>0Sl;Ku&{4KeMWOk(55msvGg+t#He5o%^Ek1s?(bz zp&&B?F2SMgWNLkA?J^Og0Eq#_j{xXH0DIrTXo!B3`V1>Tx|0$#Q414;^~cjwotzak z@6Pc_@0D{RPtiK_Y6PJ#Qym{J_o5H6#Hh_znp^)EkSdI+4w6}fpHKrs)a2n#jI{ai z&_w@YUUdI1YI6DsqowTu!{#*HuHb#mz+(tVbQeS~-)bo7y*_(>XBVek>ZyqCipR6E zIpU<T%30=Z){ZdWm6U;bJUut29`t9A#wShzmZ0Af-Xmi=n&bp;PP2eK(sWZS(#_<b z-S@5SUfJE+-V<Y*TgQ}R$Xu~m7$JPvy_6W(m6IiL_rnOG!tz?z!;A6a9Ubw99`<$Z z+<oYUTRhJIMM15}u3{Fidso{7VE(2xsv?iSy(sy8n1~NJ+N2{^N_@oGy(fn>VVZG< zK12bQZtvk9_Eka{f-bao{oSmLMX-HsWqQH{BeuuY%srfzA0UmX?d<oiP8c0rZ+SA+ zp^ZQk5OH>qL@l&@-Yf1fM%bp@2kK?F*~W)Dgd63l=Q)&TmVugpg{66ZRNvNz$b8E@ z1q=Y7RdQ(<zQa9Q1AUk6!2K?}OfGXAJKic6SG?b*6u(h$YQMMYa>M(gqJvJQ#VfhZ z;=H%7&g3IrJh`j%q%-%!uRmlfEh)@D_Pztx%icU!rR*nUw)<W%%!D)&P3%qKfdKmO zn!SZDk>;Fy?lzSWUYb~`@!I;4*?rzcddsp@;rM&=hq`kwtksIfiW&xHYY4ckj9ldd z`#H1u)$a1frC&#Tw?&sgVS4%7i<*f{jGe9((OD|0o7Wy05MJe-UuQ?u{82l{>LF7i zKWyD6vb5cs+H*yD_uT55SzUT+(MRb1Ym$M6@uH(eFRXRvPCOKhNf)*((=R^Y@yuRZ zGc-yP!wI*k=Q<jzk79wf2jC*PZ?gmd(jeL;M5|lqD84dTBZtVk5buUiu2q056YouG z7T-P@-o?2mu!?@HCtgY1AOK<^_w)puD-nxx^odN-Nie0Qk6%AUZSA}=@oD=>8g+Kz zeoK(e*>pmyRh%98jYQLp#6@xe<QQfWIXO8%#9KJ8#%QzzMd91O?j5OrQBwK`r{U?P zrtq5)lv{u(=C;y?<t-(#`za|7N6M8&bm)oEVj!;q?AlhKOy|NY0}E9TupgXngCpo| zKM`)t!9kdB-p`{u@}lF4qyUN)AS+i};2#fK;QNDG;BOD?^j4u9Vq_KVmqX-fl1VB0 zc?N}=6;Q@AtGl>mP*BFa?1TAJ3X1d$?X2v_m+2ILhNT{=j~IGXKPJ7~Zb)m;)OqYB z3q;OiCW8T(gnKY#e$=wqR&+evmrt3t6jj1A_`tgi?TbE|8SI9$;97~QNc^5@%lQ;A zx4v_Q0hTv$CAR_@<*7~K<q?5a+Rk#>`BB}xrbt30H88O}zA2}?GceOaZj*muVRqS^ zk+Q6y@)q2+d&4aR2VbV{>;wR?<0mHA!G)66b6ZF=5f5uccMgGfA99@qB#v=4{~B7L z!dd(cMVj@WZ_c1OPcKCnJe+O(oHx1>FW<vCgD%uYvsT>Tv)~KGe_htxq-T6O<lV5i zc(qR#`{gga1EEC#+q_8en<)6|GJwtqKR@V~H?nZGSMNxKL55SM|5f9Yh8`4{xwzIW z*Q-Y-Q`giPWo6~;Vx+5;=FwwbC^z~WK01Z`Z~*uKUh(w0{L_E+mo=j`1rv{~lgOo! zo?6C1<q^e3#_5Ps1oCm0m+s8Uy8aB)>oKzD)S-vtr&OW+CtB`_&7DG41-@ZbF)FT9 z1-z+3lH&fj+LN!qVATfxJ#>eFSl}za&`sZdI6xYWPnrVkpAyOB+IyG+>cf!2%cWV# zcmK-2+s{2nhNtkS*_y3z8e}`}a$nr<)N5mKyUxcq%}QrJ0b7WRrwC~M?aRIE`rhK{ za?db$G1-8$N-}`x`@H?JFQ33|+iFCn{WJGeEpic!-Ujr!06?+020(!mbn3nXw=HAw z->NFe`7fKygW^^rs8q0DAvC*R0fc=8z>|iC^WpVV#HbMxso52;UkBofv|G8YGf*ct zIB2^oe3{_`K8W-{y1oqnVDWA@5W|h;s3JodwM)3vUdqJg$~M*Yg~Oh>r{&0Kca?<c z#s9?gT^-=E4B+|}#et4z0kj7dh~@U#LgC{92nbPWL%>8tV8gfR7$Bj>h(y%QfxHfI z@Bg47+*9Z&Ju*60DzDI8e2=_re_bys$~`oTnjLAO7K!!nl%KK=Q9KpopP^Oc5^2|0 zP&)2)x@9T5@VaW;GFHLe{p3kha5%}%iimbP>W4N#t)a3snrYsbqNzpPwH*2|f6fd( z%183wdI|u9u`^|n7@ePk1_?N0Xd`yB;XC}Deoju{Vo6C5=U&Dj`&1jY?V4P!)0&*D z(>EFgWKkABmkRiruEC1z)wghflPG`OI;tOIOWPM>03+H;<&5=wJ?M4E@Gnq70%cqD zZcER%Nr9*jiHQJ2P{B4oX-;l@VUYvE#adf_HU~bN*4YXTDng&uL+%Vnsnw0L4=PUX z_UvVzJkw_%7}^(-Iv~@^=CK{_r5rPW*vq?fsZ^jq8E=2*sB$es+<OqLT0&3s_gBIg zg#xL@SGPse8EZ^C)m&7n%4^qOKBewCLuXBvqd0(1UJ7|P8jH-SW551wcdWoI#qvOH zv!_c%K>n?Yk>1}b+F_#?x79KM?F@ojN(Bm(jl$i^p)-}+iJoTxkiaC}t_5=%m2zob zz^n?;&Ah=D`)DHWJ~MEoXvPjbwcByMs}ArF|1#-#?55%y^O8|U>|>#1q5ue>aCxsh zT5mw4L;A5ki6iTULDttDh5C7pK-wSYFrA_p{TGBQsYrg?Q!XizPugk38!!HSTH%PT z!xd}(8_y}%CokihzDZNF{>;$6IgQ)by^jPIJ<zC=NEyVOzWvvu-s`V!59AIfooj1o zyOC7F@7qdYwimQzCAtcE3S)5&C`>Ra7#ofP7L!no29UWAy{?J_qiz4>4L%Lk9Ccf1 zby1k)FxQLfUt4x|&S7*eMYXoa=Tuy+3fgA4F@wcNyQ^wg-Tv<~!5Jzbh;5mA*6f;A z)(Fv%^Si;3mh)wiJw)PUNwW~~?Jn<}L+uYvsOMfhkqwWdluQPbsH+8(y=j49&xAi) zWs7EBxesJc0O%*5(wXvosw%sz1P*9rKT^0agqPfiRnYx!zsEoh0DCKI=iLAA8}9kl z*X;iJr>cMM@p#5N!QSC_+;L<51yR65*g671bItq=zVf`i6oyd1O9Xm1ngR85)`v%J zK=`%O>5o5r?s)dF;mE$PUi+7|pLx*m8_hp>4US4Tcn*ci0>{M1Qu<T)*n14~?sl`d zXO{l)yw2`>T~OA}@xC0Jk#ymDNLIlJKK5$9fIT2{v~`><-+Do)D;xK8QS93E!}st> zKG0wQ{xsi&fgDw;zVt=Bb62Wri+!PFKA-fMR*|>*@Kia70Sk8j-&GO+beH0Xdq%-t z-f>Qz)*c(ST$&#_VKxdhpa5qFXNNvIlmYinP4!;V%rpRJ3iJ*R06uWS0G1eA>jL;8 zpRWd50PDWYsV3$jgp92mh$TF|T*T<>rk-x*HhY?yW02`8fTo!1%NGdiWpGSv%zOx% zK9uodNK|JCn2aH7_;PE+0p+#*^`{6LxU;3$42SgB#^U1Sgn0YNY?*DCHr6ay+sf8I z95pV(9GNI{kI;5E^V7Dq^$rJaT)-XX0&_0l_r7?<x%2!{FW)~jKQ%QnAIOWVVlq`K zSV{d6_;x(CclXC7CH2O|cH{A}?Y$9+t-<NJ7@u@<@DL>XU@nz_3ZsU6=@J>|N2B@S zaLsNGN0it)r+{EbM|+*faexZ+9D=()7}bb7Ww3sdWoh|k>%Gh3oiV5F+}#t+vZ3I@ z-cRLQhO!`^FF`>0n-#BR?Jr+!eEr#JczzjRweh_#e&cX9f9vH3L=+@tgq`vSh83*& zjTA_zk*QU&S)_RD@_HRPsVv4%5^OW!MgMCwekO5fGNy#{V!fO6R8u2Q0SlqX+|2BE zJ)>m(J$7^cxhBpR{{Qb7DwJ<r$ApZHF=dR~`Qp!@HM1n*7_sT)`YIG?IpAl<w7pAa zY^>{$X%l}7&E8o#ytwPzdUA86iHK!gO{)d&wDldXMajsA;n7<^?9a?UusSpP?K1M* zlQ9lsA|$3QF#^{$Mrhu8YrVtTs=tSgzj(Slr+e0m{F1-YgycOG@;Sx1>zRN5$L9(~ z2=LpmpNFbC*1mN&jr<y@Qoha|(KPSA-?nmP1|Gf@1ps^P3;Oy{%pVK+pKj+_Kl{s| zcw#g0+8;LHd(?0V-lh%l8h^r|_}O21*0(<`<j4N;>JVb>%XAa~TjB64Gb?Rei|!Fk z?)56=UvG{yeJki(gI0lbQG_TRyK+X-qX0WV#J}Z%;~D;c$KwBFsfgI$mU}?1&YfQM zaKTK=Z0;e$wl1r_rH%aP<_RB}@g8K)%L2md{o1nSI$^Je6^GeCf+B!bMdj|4b^^y9 z<cFkZ+>Ya{Xb#vIHJmS&+^+1rEi`$?XR~KCK(^=3hlDOKrhJbPPSbUnS8UR#*(Hlr zX#3{{+o(r=^+x$mV1fbs4Za>N8Y3R(Gx1ZyLRt(1tf|PyUgu{FUI9oJ`St<$j6VOY zWLM^8q|4?Y_#08urW60|FS1`fH1InQ4xKDeR9951W^UV7U4+e7oqW06-Js*6g5RF5 zxs8wRPa*{mPDZy-fcSd#2%%l$1*)M5!~h4YDu!p$byd>WhETY0p8)?T2b6z!fWKc9 za1fi4Z1pW_ecf4U6%g$2gA0x_dR%ZJ^Y!5<$)INGidGOP5)AsIbdX>@#%<}fE-HY> z6%I!g!sXsO_(l2q2cY`H{ptQguES!@VxQe10N&{^8jK!_J$s|G$RtR!KCB<WT)9co zB=B<)U0KI}jg28Ck2jUR`mZ0xL~b*qbmvxA_2;^xwvqjfM-Y>93NE8EH;YLWQf@XB zk`6|8;l8u#su--g!0%ni-qz1?PQw*i^%E6ge4ry?&@@3Ln^Z2_#Czge!K?3IS+>pZ z5U$eJ85iN>9}wY!!Ug+b{ljQ>=zws4A6z(Uy8T%a^U@Y)Fg&<*DZJFRY`l-%n~9#e zqq|K3VRBf|)Y4m(1n{^bJiChEU=?)sn)T=p>&}XP4!h%L(T@qqRzZ3za69BZ{Fw(9 z{+_#uE4Df6iTg&MtF02`&;I;zw6%kpf7cDn#W1;CAhvuiCNokNQoFGkBdImV`TC=t zhoHQ8b&XO^U8j_+mQzdC*Gs77YbC|&YhiXVCf4!Z8RV=mhd49qcudx*3}7xI<qS%8 zT|iFrrY|5R-x&O9^mF;I@cxTk?JY!RPUJjgg%Y)RA<r#=K5sZLGQR>Kr9A*CS(p2A zIGhu+zVn9jfPe;)=Vv~dmQFmf?;L|)yD}(+?7b!q*KB1^^Hbml$=v=sZ}OAxW|bCR z=7p3NaxmmtiDUpf0a(MPv!nGaspX@v-~17OA(Ihu!8D}+k_@NRY{6?6M@6%0m+0i; zk#FQ1$4@C$T3ceB{L3TSQ)D*7FaIE%y<R}C9Qv9(ph;7y_BD?JuJ>x(JfpI`N`14F zJzKK@Vt=P+Mz&9>dv=&7J(*sAUo?A!D_dLhsstg@mP~Fx;h#`x=^iB_dIQgt2h=?P z5CaMr$hUxrYi5GMds)pg@CMj-UYj$f;eoyQgrM(WM~zaXqfNCS!5PUr_HE}2_0qNe z+KV@xJqpV>6m#OQTN;6d$Kvx$ij?VY?WL;TJ{BjW481FmutR`G0OqmYoagH~&87sI zA8HTtZ)lN=n&`le!`)U_2v8PX*gVW3v62(+RXEf{8eBgj@?AjrBd}`JHS;4%smLMK zKEc%8rM^j&Vlh$@4fMQm1}4ZLlk`gNFc;`ydcJilns?JCq~?)5(JR9%k}3}VQCL5m zG+Su)&H*8e-z<m=_Q6vT3=m86JQhz<6Qv13tR1Ss^~K(-7Ywxj#s!%m4NTkzDr3#C z$!hhLY)wWDhCup{+qbp!o)%y_aKHleJy9yMlI`(*n%B6Qe@cEAfN;1i(C<51;DT;u zm3u$8p;oQ8<a+$rrumOTvit`O(ds>#_k(Jr-1j;7aTOJ--m!}?jjPAAtui(=A2$Uq z+WgT#(E06E%IJyOSaWAO!r^3+hD*y}w~J7t&0yTSYenb<G=Ne#U^)iZq6rh=XcP(F z+5kB&ap_wGev2s}U+T&6^`p?daT9(q!wXyK6o9j{W3N;3yO%)hm3^~qV331LV2CX> ze~?*39&CE<@-L!w7Ji}+2(GPp$?X;)M|~tVCglfY(9yalVsSEGd8RzcAOxc*F4#fC z4JOOqNR-9IUI>f3*9A;GBFn(ihE;W0>RVenfl(7UCO%!LmQ;2=$veUvYwlp=gfUOg zMJQ$_IYpaAn%Nn-xV}}9guNjyGK3r)veLUqV*RcJ{`X<<q1v57fPWO$3Vr{3XsCZe zCMBTlY+$f^q_(G-zqYNFUzEeRcoLRb86M1EF>Xvgrkklu!gB<AxpsxM0@N^C-T8;Q z+WrkB$&>Hp#G<18f@vMsNBt-Kga<_47Z$%8Y%F*$e0CMjwY-#>GDs3v$YRke2U-Tp z=pB9S`Ls|WbD3a|03aA>bPxK40;yCb@41)z=Q+9{UTm4ldJ$&72c%z+@$yL)P~id~ zLDlWwW<VMH+fsUG-yL`r6-@XJxC&_J?|GK=PG`n)<tve)&d<G=pVMx0DOwom`<rR` zFFyd2<(2my>CFG8sBao>E-%cMP6Z@2;E|Wv-yJG>i<XtwA=6WLT|*$eds3w8&TPG& zj$pyy9w#dL!$!BF&GrYA{Bq&Dm56&I@jPIl#uM0hvM#@%7gy6OVi;(j`~Y}!-3GK^ zd|&hX*SEjBF1%NeZ>?@dwLoSGV*OCp4Y)n_QpcCemC-XGQP=?iEOln)!g@?w(@(!R zXa4U!Zg+Ll?)sd6Wbn#smI0tZ01Lp1KCS*V?CgD+2kZBbgfX6~KMiBtN38Ph9}YYF z^_lvH$Q+L+GO?k)Au_pqUu0I~y-mrgehH(7US3O8-)I&8H?RH`Yh`68ICjydS?a{f zDe_|`tMS#p#`EGERQ2*&dJUDast-Eolj=`HDwm`ltS=o2>7zA-v1GL*6H@tgnG|2L z!;Y3G65LfuEOIwX*6pZmH7ymr)Dyh(kiClf{jtZ7zci-q-HR{#Te>z@zrSE#4DzTa z*8k5&Ej8tB>vj~-A_A3OHN?m)P1AYAhM6#VX?wWb`#S&q(eWu5r!H1b9PjY?KHOA2 zHuF(+$VMeQezH4*Ts6?(_037B6fj)`U=jINxd17si-mEf#=no&`pdl!mmUq1Z<yf` z>C-Yx4KZ^6;~ie#1{$i!-5K$dD%m!2S@_Am%);v7CZF%XW7Yv!WCfLN1r=bCvF^Hb z?h^{=7|VMBv}QRlFEu*9DdELvjfFO}hUB%3UW3-bAosQXlxQ5=HZayaZ}DY+e;?d- zc=nN`P69C3@ZBbHv74@3*{7Wmy4#Wd@yqi(G|QozI@58ne7&=Q$-QzV3Xy^U*Q0@! z$GoRK-<Sa`#hjXp^ESp9zy~yJ(z&uEe3MD3O(pneW=T<sxtp80kvEVzV}y$aOc8+5 zzZ?>t(vOm8li3{bglLdy=ji4^E2b+Td`X=jNCo^K-@jb%^%j2v954}8d%n1&Cp2HD ze{;S@{Ycl!z-PvVmwvKUz8jv@30v%jxQW5*VU2$pn}2szxyl|(`!rk>ozoQ^I7VeA zKe<#&{M$t|b=J=mv6>#Y)a3Jay$2B(x*UG@o#Zt8lUxvWu=dndd4WvC==AT|hp~(x zGDQZme66^6t(;oCzE)CR`x_(oX<m8B+In&6H@lc%E<h%Qb-$evyfaQ^0X+|Z5D6E} zy_Zu@9ER)Qo8^#i)b(Okg^1rbsn<N^UZ_A+7RM`rM)IkS>%oAiDx&w9n953+r6c?n zHO{+cWs!r!NaU=H!0+mb@~%I13XMk*6*lMiH|Ju?kZ#Hwe(JTd=03PUcYoCyMTPkc z`jKGLp~21|$2?jnX7<mP20tpu4>~eNRX)Bz_gQ{14#FWTyZ``r9|>?km+_`qSw}r! zulO7BvY3k2EXRoq*+s_s{N7bj`SNb-8+uWF>o9_|tM>|Xi3~WWl3LGktN%hPZ}kmB z{e+1+MT{z+i|sU8cGT_ddfvty`fk?n_zmjXfP9BKb7^zC;%Z<}Z6y9QZ9S&)_!C>D zq3X9Cy(6C;D%PvDoc{fN8+>(qN+)E!RN9@&nDmN03+z19DTC2VA0qht8;4D26UkjR zf7VZK`o7Phe1jZNfx+$qK5Y2)6ubK!?{@EWF>XP1o>?dI?MutJ!uaNUtRxProNSsi z-SC$GL?*Vi#cs&^%*mNiGS@bGYW(B))Dj?4=cnczJ>jn?fcZw%_x^bF6DUglOYoU4 zJ`UplM%muWe+4u|{Xkqs05<-!B#4#;zZ4E@oqk5By(=<vCghdd)AQ!an{~badGOy_ zXH2Xff9_Tv_=(lPAYaUg+w)u`U4;P3m&VK;q^N<ULeyKJ8x<4x;=v$(@KcfsNNd=A zX0SdvGL`FUvRAE1)^l<_gF~P+KxF$_Mdia2vzJ3ll<R8rsiekSH3oM>jQ@K1HrIBx zROCsd<zxfCAt}dl)p0C)OegEut8w+C*M`f@{ph2w^r)OL0HT%$K)MZ_j6Tx**&Lx- zfRBbQxyL%Qvm2Q&R)tD)ZkvSdn|%*WW2G8{ZN#pEPAp-jqR9%)#EUq*tncYTw<>mj z?7^IH2~Z^gvUG&j3l#&hmmAFtv*}{(jou!>$-S)9#Ev?zA&+Xes>RW(=op|VjGH>0 zw3X}v`}?bHZ|1Zad9=pucC~H{J6)UUr;NK9k=;z_1{51OD+j?g&Oodd;Hv3a3X`Qh z&~%T@N6QS;&KlfPFM_yaYRn14&`Jw56)bzIW+A0AQZ6f15Bszj+y+$|B<+~4$tJ$V z!AV$tFs0#@RPa1y<Y4Z6?pGzlN%C1LzwlUZY$gBfv6L30lTE>(RDkb-C+~3-F|a)s z9-pM`WPV=b(`~v<`GFF#Gx4w^#14TQh=V_&AU@NVzbUiea5_}dacAO=sWeBtW;P%_ zF}u0o5Zdja6XT6|;GfSWsx!j{P>jv7ux#bZI$CNMj+C&wAbxkj{Be)O+=XzFi`Mzu zBc@n2p=rZXm88O&9|G{KI)KPI+(4BK^hyZ05ge_e9qZ}j*DRIT>Z=0^*2~&O-lz=g zisCK+SU)J*MR{Xe;23GY#4&q9O2dnN^_aPWtQ<H1t#7Q;%n}Iyb3LB33Fq$>*nbC2 z!roX)WpIjpra|cg<YQYg@xaQv-HbL2mKhl&IVdJb+I1t?q4FsdO@NU)C!>je6nh__ z9^hfLNOJ<-DXVkT+_*AB3zr&&PmEN%CbxccQIpKN_+U1z2mot<DIYm2W6Y>B$70an zBF6nP)M=H<jUO40G{Cy6!)i59Ux4x?NLr5d`k2lk$6k#`EqaYztb^0+W0ttKm9vd~ zZ&+$c#h^Y%T4bcb$*_>-2{=ME0gj_3g#94_tdpAENV!-QD$T{WPta<eTP0tEaY#_$ zbbu8-29Kg<$YGsW!VJr#m2~wie(#=gYoer79RmPm4j|YH0fnT2*({lQquF&tMRc<* zHX7N(8@<*oHx8%#;%N}g8$4>9G`pSlbC+4(UvT3ez%h&JdECB#=8$#~Ht0N%C6C^S zRYtp`Fx!IrNXp}^95};lF(@a2D*tR}6`H8$RUChngQ`s67WF5Q<vaER>$KPdP3nF~ zjxckCp=IyV^gGK^^f#=Zh7~wgqXoGi``>rHhbpFId#&D}0<yI^GMLuUA8E;{oN=Xb z8fQ^c)e?WxE9@h`wfy{V=+xmUMuGr201sp0+W}pCFh4KE=<*`B<DHawE1O%+pX3ZV zyJ9wOuf^<mZ;4Na@Jn{a!M+rq?Hf<40DL6OQZLF%>$J!dv&r)O!NHS#h`&rTIMi&2 z(dk%5W<SbwOi@t^Nnm%SSXq@)d7(d)3RPVtjhH3?Ko<ZSb0BG1kB1h5?WE$bXSyby z?)vPjB^Bp12Tw@?h*}gdQqNWp1<lBaq8&AX-mWe(8M>Y*SWg%5MoO$R&9^<Yei${O z^4h7Rhj#74Bq{&w4ipn}IqXYerVc|3GgV_UXY1md*PW3yF%Z0$UX8;5OUewgrgKWA z<t_eaP%Z8Fc0Ls4;KcIYb3<+j=^Y5(YfYm={H2bzy2u(|=Pl|bdE0is`}Mfy^?K|$ zhdR7m0e_CZzc$FbhjGG3jO%k?exmzC4c}k6$D<CYJm~!Ko?{K3`=_eR#s?>37Z&Fx z(&o8~?TVN{K05S~*EV)0s_6#j7KdAuN`AK^1-$xg9r))TGzlo8zB?$Wtb;fGyj1Pi z_o#`|hK~p1tEI2^s}8=DJp2;c%}oARx_nR}uy3D_P-Y&ZKK*iF#%>4o?BM^I>%Tgw z00=WQ07|i^#}PD)0+Is>z!yF%p{2M1&e)>yj?QCT6wA$wMlCN^(mNa}=Wv`$yoFM$ zQ3&$9HU;>UJDVd)FE{lJHOm*P;rS@cSgk`o$|zb!uLi~vIsHhUPNC5mn;*qUPQGh$ zl}R1ww4a>Om{Gq0<`{JsTG!{8OlZ`yo-U!3$w3#~iV!_kXXWHk%!JPkOX<F@$-~6~ zmz~WixN2H{p8KIj<?<3m&#n&^jGJG6w53}~p;EPLl<MD}C)LYkxp$x$>``rxWu}l( zFgWpEA56~!C{|beij5wCW}7j{CB~p=TA^_s#HtY3)d6q@?k7@8s15sD<%U;J;5~4X zwTXmxbqvl&#Z2atZW+oA=Bi$<QD7u-1hX?{awjAAQap*)sLL^p(p)A`%TK6>dYUOu zD|HXOHtTww$>c_c-!Z+8u%4oi`S3NFX}V=UIU$uEIxYFaBcqHMq~d~ohgIQjS9D(@ zFn-sK0wv$&&UB<U8d`(d(vp@Rk!$GY4G+hS<2o1|@2vBe3K?%2H#fVqXiGzn!-z9$ zjh9fX?UaEjz<bw)pjMB6SjU7(6+c4vqYp<$V{@aJfHx){Oj@E_jY43s1-O|F&xcIi z;MK~YhjyiyjD|be%uFz|oMU-0hEFB1#awKJoa`aMMlC<72+27|V3lL)CRO@TJQZXk z_i~+zc1~w0o24`uELwU|9WOvdr+U_SdfHO-s2+QQ-qmIDZ8E7tyDVE`)Ng<}#{>@r zuGUpT0G%_X09UdT-Go7(Zo{b>SGR4?zyeU!tp&4(V$aAL^0`6fG6pkR@!9^%*+i{3 zT*XlP<S0)<n=}aHCHv<{$1$RRoj=aPMRoLYGSW`CXCT4a%#yuotway7W0W3^cB@+3 z$42oM-F8cQTTe(Y6sHtCsjp?EExj6Be>57;HOME}y>^aE?)W>+*yyJw+_jqH`5VR! zdqJ=!NUY8>7SI;%OXcbqoRvU|%3#s$N~M8O%p)Zu$wu~cGr5s*8!K+vrQThU$=!y` zWu0mPY`rh3gkz};;Ie1DN0qL{GnUs&xBMu&8bDFiRGh(<M*T*PZ3N#v-cyGq%SK={ zT$*m#PoAJJl|~=Y2zMD}#~}4jDLa;4gVdB_F$;E~8f#-q&>(5<K)A$><<P2Zn=4sN zv=y|hcFuf~Fe|DfLk|lXytuvdy40bEh{{}fZ*c&Eq)XRU&;XB>C|1K7M1X(P8K&ME zmo)b*Kf7c#vYsa!6S}kJ(28z?LyckZ;=mleWt4fqqcJOnn^e=SMq!{6XL9%&tCPO) zZ|$8Ja(#w&&VI8Ue-oU&k}A|){rK2x)u!Nc={~U&e)T6p`%_mn=G(u-(@yEfqOIRH zMIh(3dr_v&$_b~pwh8Sh`6xxEXG^K6PW)mUlfbzD<JHmQf5*vE3Y{zklyM#x@rpOR z?PJzwc6C%|b=sruoWs7uyBu~+_LQ#lt^Llvy=(h-<G%5FLWyKs?#k{Q%<=pq|H?Zx zG&5Vb)K_b=6s4_WHBe90nVPR=E!D^VnyJp>eC8l{P@Z!`!b>7tB1s}of+o=<aZ%#B z#AAs+B?J;bBoEnZB=aTLNw!E{mz<Sck$fTfQSui|nv-CKFfojQg~1YG*|16266~3j zxT8jDrIb)gDiti%C3QpUp44NhKc)Vb`cGQiDM(jH*Gor8H%j+Nk4R5Tzn0#W{v{*r zl4MrPY>;7OLS=5ik#Ga}Ir#qa{KIDsHyyrs__}O>Y`iQ<wnX-vEK~Nf>@C?v*(b8E zWj`l_Dp+#3T#{U#+<zzz5sSz`P!QFKcEk|k24V^EMBY|@UH+B)rxf6YA31u&@QB?J z?;{aM(iMbK8x*c8+);R>u&MA);Ts0Q<P{?nhZP?w$te{ool!ck)TcD2#8FySdZF}> z(vNhBbVX%dWh-S5<xpj!a*lGD^1AZB8DbenRDx6pD!D2&l_r&oDx)f|RCaM786tC# z<;X9YLYaqEHB`-1omB%=&#I27-uZiS{$EPpsqSZqXZaqDIeJqqKrK!!ORYrhoLZ;a z6}4Mx_tl=M{iXJW5GKCo9LiD9sMF{=cJ!FxG5cd)$F6H?XijJ@YCh52*8EJ0kQA-z z<1#B>9RKI|&wPn|MQv?uOKmspAnio$-*rNC5_NKQ%5)lZF6xZx+|_xc^QVqL=LaQ8 zsp!_~KF~X?hu6!}E7n)nH`aI5_tB5gPthmqSLnCsztI23AlqQxV9nsA!S3n<!$`iW zp`l@{A<3}Ru-354aK!MAkz|pwk*<-ok%v)<(K(}KqvysJ#;(Qz#_`7OCZZ(>6HOCy z6IYWUlSC7`NwcYhK+V+H)X~((G}1J~w8*r|bkWSw%-1Z+EX{2Eg#L-m6K_xayB4xm z&RoOX)Es5*ZysZwVg8#1%Hod2Ba2OocNX8*owppYWLwT!{${yl`N8s+2qsdoGO)6< z!dTt2j<?RTF1B&8d1Y&0>tO3^8*Q6zd&>5#ZM*Fy+i6>#otNE@a*1+9dmVdgdk^~% zd!l`=J<Yz!L5dD{c;bk29CW<lxZt?v_{wp&;#Z|q<x!^ur);M+r`JxOtAwiHD0P%E z$`R#@ibAEKPN5j6Hq<a`0=0;Gg39O(<Q$?}jj=(NWtZ74d>UWCH}EUu7vw+7q{KJa zKh+mJ=18_A+mm6TUpOZegs<?|_^&m4#jD~+)Gum&s`<P20(V&Y_rvSLzkK<gz&o!@ ziT<OCF&daE%&ymA?@;eW9~qxCpLf36zMFose)ay+{tT=UHX1h;U=h$BAPD#wSRU9A zgbXSUst%S94h$v)Q-WuL9|pe&5e-ocNe|(KybaY1wGK@SZ43Pth6^hQyB796Tr%7! zJU0A%_^t4d5lRt>5tEV7NQFqv$f79KD1)fpsIh3BXsc+q=#Xea3?!y3rXl8^*r3?^ zagaE4TxHyP+#9?s{y6?wyg~fA_yd=iFhfuz<Pf+-VWK_peIhB5l311aGpQw6G}$(J zA>~j?OUiW0^VGo9(bQ+D`)T57)#;k)R_X5PQR%nRpJxPQ?3^?>Nj`bdzmWMM%P;Fs z5|#8bo1XnO$0HY(JDWF_KU4rONGoV4cvEOy=vf$1c#14Su04e~b>VdW>9wLw3Y)T9 zoPq`%KotfsG62F#bpVL<_4;}}0ze<2vQ|k6gsJ1H0OJLw0R{$zM1RKw6j{`tulT{K zYPua3E!40cLJwQyaL)lmYlayWY9D2f@2g;Vs2W%m98|&zQ+R!3&@qDuuMuWG0%?d% zm@4YQ4iJJ8FhUsSuTgIX_<EyABB%lHk~p~~0doHYkTE72Aol850ANsw{X#VNL0A_j z6ZsAnrgV2nH^<4Cm$l=j+S!4Jcr?XlI#+>(>r|wS8~B52QCo67y{a~io!goR7Pg^P zZORyF;;X?Z>GT!|$aM%N%<J9mdHVj@&OP%QmFyuml>6A-Tv&}t!wwD}E)MPfnnsZC za3Sxa7G2^;)Kw+|I>N?&q?l+hSnNXG$FY>}RVp<xND)H_$fd}GW-#zVGi~@VQdn5} z;dj8Mn(A=*qnra4;6K28s_;EAE=Af1;QI*LfC77<SGh!%SEF?)u`YxOVx%u%z3x=` z-8)itb`)Bq15R+$xc)fox=R$ws7i5(A?B7KFHKCy(pqMzC@HR-T-4bM^i1->0&G$M z3p%T8aXultC<3Je!u^P<UdpPV)-jliK;1k%iU`(9pJFYjJH>N1AV#T7`JEsZXf}+h z70vRBCQfu5wknsG8K@x-3g?MlF~0}&YI5Cw{DPZ<zN39Srd14anA$*dUtK1qyPY9I zHe!f_xP_=fAtEKfQIW_+@ZG83T&pmN*^~Eq5=~s5>gi5b6Fuj#T(?fdb!pHfQr7<2 z@OniJWrhac7tJKSO%<uR$z+LLhv>uf@Kvssfhcd#QlHhZ!FtgGM1Bo6)7ZhiH)#2R zK%i*Oh+ZVJJIUT69b-x*H%U81NDRG2)YdbwojjY~CaUBidYWD%1(;KZTXOotNHOC0 zA-g^40+7BRf{8pUMw1a#NY<$kXz0_D;yycj=9Y5MgMDyHn;kxRa`sGPf%R}{sNv1s zd*n}@nVl=%A6nhZD`a?=tbm`BJ+T*ufLe+^`Rud+9yEHN7pN-}tRyKql2cjE8rG=E zkPR08scAQR7(0jFYx<cMpZ9%L!nqKk6xgZF>;K5@7f}VHO;ao#b@IY__WKxXS@ZFi z3xFoz1$rv!w+3u*St8Qu#KshOVhYyP==m-SaZcLw+?Yp`A1F|?ebB&03mg~Da#u8T zA4m3`k90JMVftn+ZjlQusc};Ap1uwumge$IMLY6gnU#+3&E2bKb<G%{vN|m5#$V?^ zH<x%6)2#(qBexP7t~-N;Fj}7`qee~Sif>alm>MP2&1+>D64jsu{kqKs)Qu1r)!~xE z*(0bpZ`Hk;8*Q|yqjfrxR-gdz>Ld`4Efe~t7ct~O{f$*F_mxKkIBwj-0T_4<a!Tp< z^=|#rJo3g%RS!%XK|A-2XjlRc!D${M2Cfn3$Vfh+3jmlsDLMAbi`=+aia&`o(?6}` zFNrgxidpvja&EpqkANSX=UN^VJ{lYn;Rir!U56Lla*dd>gfmdUt~56o$wK}r8YmvF zbM?l6^J29ot|jn($&iR~xgdmZ@I|n(Tv=K|2&P&7U9-|uj4coslxvK0URu2gR8wO4 zKDU%_wAuz;$$G<`6E-=)jntns4LS5BZJ``$FOoC=>NI@)<5^}nI_3J}<B1S_z}%N? z<qtrm{2ne%7Iz?UACRG8W7+Hnc1Ah%VOvh=>}S59qCyS%g67Rb$IwRSwS3+MTt--4 z(scuBB>Y&H8?hQ+=BZN>I0n5QTWso;c%n&_)Ayz2GFBs@h0YcVH`K6CirFO?N*6Cq zTo!1`ITuZgJ4ew1(P;7t(1#f!R^R|sB^a4YF;v2!Hj+~2-n?NuMA15xSwXTw0HYYY z6~ke$C^BFRnBHSOxE!wLYL7Lf$&_%HDij#B2zBEkMrRGM33pF*1fx!EN6w`~+^*<Q z2RpB%^E^LduqRxRmqt>u6P(5?huw}*6!gH2Y>}UDPUk<9zGq0L7Dd-V`(EjlW6_f_ zjc#!k2n!HAiMi-tvN>gasyUrKx^CGXNJAmu7CwOj`EWUqjIdz~gYet6nV#=Ed1sun zCeOd7Ni3&YsE(sXCzX@rnF>OZ0+uCHH@MYFA;!&mg-s}Jtj5@pbEcPDJW|+|nq$8v zP2+C0L<T^zt?GLz@Bm#nRUd%u6176*+0^UU=5-+un^A8x@oK`1P(2`F*#K6{y1|^S z0+1&zqEThY)}IjlO4LKDGKYhGHsC<uG26ilPtlgNaSSRvnm4IkdWcJOTCvT6QpVX+ zlOuBPGYESnN*HsFJ&wbV2^3;IQOrzFNJMBeL#NX{3$Ah3v^({lOh*Uk*uWOPa`u58 zNSOk_rc8q_5Ins7c=6_kMLXP%1fNYp`|8<OMTd@GN)1p-_c?|Zw}{8nAeAycgb({+ zEOg|j)$M5QtQ%0dFI>0`Jb{U#k4>*B#WD>)|CNIq&_#3Hw5a{UWjI)M$=Gmq$wr>( zUFg6W>l?a9nVD1C4EYb+re*g@PzzngD(IkRe%RATL})tDSn57L(J1*Lmwl(`R3Xn6 zD1vBsTGl-GY@hv!%Aij}__5ugV62!nb=1Madm`|~S}C=5eEj~zGdb*FZmb<1{X^HZ zJ3|u=W*Ix9L(j<55<Z<~D44GCQhyKw^dl0tk|dz=v{Uv}7g$o{!nSx{KJa8W6WS~B z2K;T_7eDAHbPk)bS%Myp%HP@N{*<Cl9`n^PgSjUii_N0tJWf64?bl#{vpzB+M_%L8 zG-&qKX+H*9zxE}ukASMnK=eV??a?GA;NTiwg3o@ts`~M%eG_VHIX>2&POn@PZ(ms; zO!AVvFGpCJ`X$Ihv^FN@p1TT_d$+!tH_@Lag}#BQAS!Uw|MiFIU`Z|oLM*U`5!#K! zT!Ij#IuVTq_422tVkL=a6TL>2&r|#Qu3SEEL~{)OW(HU7bsI6LXa(9`9NU;<(wjGg zxC{HbI2jAlG2$BtYh;T&>%<k;*DQ2J%o|~KR6?3VTH6dHPEU!&%e?!`7k~NKCsrXA zcq&l$qHZcfmY_11p?ls}5;a4Bnlp4@@s7gDg*k)_4|E^thBxq7^=|!e-;G*N!m-H? z8q@=#11MyIoCV>ayFmw$00BqYq?O(M*3e)XshU{C9qgN!Pgk94a+6d-vT@Rf!}9F& zWo+XE0v^y-0HA?tv|9mn_VBh$D8Y@t>%={8^U*>vkG}t2-ll?5o``<#CU<03h1gM@ zc&>2kSk#truACo>ih5T1+x$)eNSYdn#Tg*<UmYjhM#PIQo<;N3OWmnDs4#RnBar^E zZ4g7=0CxvYfxao<klxE{r7q_hBrLOZ(KL{)h{Q!0tM_oUBcouq`2lwqa(G;J6Atbh z`R<Y66AYxz=t;M%@c}Cksl75OP>3?8_3Ax0_>@{E0-yB;n>YrFVwpa{b?>qH^=zJ; z!J!L&wTR1d?<aU0HYpGdyvz)`OdZh=Gz%(VqX-eP{PUig!rLUXT-X>&n1n$OKbROZ zmUw_DoqFgwn|!}NKhdJ~aELxhT_5A@pkGm;T8EE=-kJ|vQk;TC-LqLgFx5{11W-Dq zeSVE3Y>NWxhs@f*o)nEfkhSGL5N3<cpAH$A0p_#-sP@OwK^~N_Oe+tGzm6&9CDy$6 zuav-6h^1bSGb5BDV(T!pIOm`uklScw(+`T9*?PYiS`e|(j6!+y>M|BJ*gc5e<N_YV z+=Unr`hf148#u0RV!^!44p<;@Q9Wpr6%R~OsI3lYv?TyUYfS|14tnO8V9+WKi;+JG zbSeRZ@j{6BUh<off-+(dYYu{!Yu>!(D7J!vCCR|&1*tE4WN6k!-S5FXVX`rhm#;A+ zJ6k4K-eRenl2@Z-+LuM#b2o_&4LRx)KUg~V9i)!I)ElBv^fh6Sv4%t7c!X#!hK1^> zS#YNkJXW-Vn|^>U73+f;HX{Ie;+b0K=xe<I^4v%Mp0!?>0aACEXrqH1$fKv{8KIF% zF`-o2TfY_7OPVN3dN{<oivOOq`;6`r%+3^fO~MQ=(DmBP{Et*iT^*;~idh#YqXtJv z!%NgT7nnCASnUOhL6i$U#k5plk9OgzWOFz|`|lY|B!bALvz$7`5>6tGpH_GisPk|T z9Y~tcO5|xenEmSoEdfZu0($$+O@jsJ(^*y$u_x9V3Wu_`S%7WCaZ=4D_}$JD<2GJM z=kQ2KB1G*TKd|TEKI{rU#}RQ_4GiKsCaIuNFcp(Wi;NTPnv6VcA^(@jra^79K}~Bd zrW?V7ci<@&hMRkRWD2;T>PH9+UbS1c>Cs9Gig65HV3U()*6<VIuu;M;*b@f*>V$Sq z>p`S*TYQt5lIA*f{o&%e)|80bug<ipo}IdmQYOg<QRWIuayvih*VI-z?A_B^xAGs7 zq$k+N6!p_pqRFj7-MLZLAZ`@WcY8wdXp;Y57UvsLju-?g(8?-!u#}P0#V!OLw#*%u z%v-Pu`@^;YH0;ye*FJ7JzgoKDh_1;mqe?VV_VgPXCyx_&14lGtj4KF9>5z(hQf@Sg zXqJ0>s0)*!BjilHLX*$&hryEQ?#`@UMG9JXqXI5OjSkoW+Jn5$q>Bl8!&PdZ=Lr@3 z<))t6LRUj(^m}CqJ$&aA>N#Xfka(+RjN{<fziY<g2AC(0eGKm%_7Ty31gAXFGf&_W zOYVBWqvixq+gZON0?la&Mou%N_JFHIP5M&>xtG?AhvoALIf)*$Ui-?iiDm7$1P&NZ zUe)W{!x}GiyheNv4sD&%;WY7*e-_H1$7?|nE>)G3InBI*5=R~=#KASR!@zR`<S&#} zRG_Zl+|}$iHSwYldsPVUp$FpgXeibIBCf!p^<M4-l%-^wF=|I`CX9bGH|Xfnx_F|C zgq|Io^){P;Au{P?7D<MK@ci}sZ$BWe!9`8rAnNZ9O^dzc^DS*<{41997rWl_k*am& zY~u02y|nM&p`Q0u89j|-k;cc4(YCDCmy7exFJChvU-f)u@b;TZ5o;iavjP}HppR8M zY7E5J$9u-cBztrN{K1A}s2l|w&0*WDc(#CU^zdNw_Oz;(;f=0D1B4DLLcoG%J{Nm_ zGwZZ82CGq1$7w7(H?1%O++~RfbvtA5&(1qF;ldGhLds-rK2tvsCR8l66$?;3^3qLo zAz*bS_`^recoQGYhX|=?y{jHL4`LZJk`F{yZO?-KIX7`Y&?~}^MU7k8;;fx?y#NaJ zXVu}TARK*1Q%9z8nMW8)vi&gdpkYXlCfr6fs`1rEw011GK<#7&oaI#g!O*)1f-mdn zk+5y7V1~gFRo-Un@@rGXefZxzNv%)hRS4KeQerLE+f*y>oux`RNscg)IhjFWe}IF@ zDz;=~Z&uO$W`=(TZ^qda11lm#@I)#@4^Rt{)LKdVNk9%0AYHS0y{STXdSZO!^#};b z#8Khz;|o9v0d}+LUnWu*KH><Qy-K?_`7gJ4`sf)!P|lLJK(Cbk?K&uB%vjzMUeT?A zo*BPqA3rVvD3iQET?W);Yq+Td_j;lq-Q=IolFPO_#T<?}2@pUk4e(Y&dOF*&5ItKV zsBV1I1m2-)Y~v|Tup3~<Ahpc_{Ih^S?(wpLEEbTj5bl*2K5_7FRzd03d&wI(uBrtR zLW51cA;xW-eeoF?VtwjDy-%c}r;v9t+So|FyVI#EmLn$kNR@D`K{Ei;62T?T(lj64 zkl8oKKB_?H@Mu@CR8p-So&~GyF)S<Jf7Si#CJ8|z)%OjBUMw!RE|&o5wnG=y!xWM| zxJ?I|g`YMhO$UFt%9=0?lNoH}5q_MyDk#rwV=}mL_=l;MG-vMW(q^zdmKd*;Pcth^ zTMZsZlZQ(AmQYXCIkqc`&IN#60`3=qX${~BbuOiLezXUT3DI{rp%SOfCuSJpToreb zN7@@DVNaQ&^mTjuRw4Rl0F^`J5ro3A9%$hp01OeA^g=qws%vQ1U@35@q@AyS<Z@IG z1-mR@dA-^i7PWn_2Y-idN%f8Ggi``&9K3+H0=QPM3Riw|+qTUWr;^G1$kFQR2nWCs zrSa$<5sz7+(%;5==fmz<yd+_wam3I!mu>WJtH9l~IRW-rz#!j<07EOqI0g|&MW5I4 z-*<g!VJ|R`V+2HzE}b5MJh;7ZAN+23*Tr5BvFNX<Dm)70t*#Z0f$qT`xKQS3;qf7{ zk5}$~-kLjaaiQStci!mWH2krIbKfC4v>;A@WRcbHj=zgW->6dC(BuIzW93lW@MJ-W zPl+)2WnDNudP(ws#<#W9s}H2vQPITnTm7CbeTvdy@o^7APL%lke+vwg*sPqpl(^R- zM9eKrm<nARMSzj`gDOW`vWPkCE%}eiGzC%9IEO)<&<1VVq}g<D)YZ_RUvfCuoY1a( z>#ua3yVgX5OeoZSFSk-^$)u9zU;;6xXUN-dzjgI#oAgsZ+Jwdhz02~SR!l^3(uG1R zVy#Mg^th8_X@Da;t5;r^PYy>nW#0F@Js!hFS~_?RUZ6&bCH>rurdmTvEM?7@H#XX4 zJsAKROEFK23vkG<A)`?B%~Q59k6m)$*G2GwSckJ*yvDU95GjY9+Ki0O^b1?&o>ZKE zXF67qY7-G$f%VWkQ_Ba|>tjFu{S*vG%nXTwyY*UBu6WSh+Kch5BZGz?Af8qWi9%2) z8<+qfUTxUasgc4ILtuYO&1BpyHliTnIJLz2IJpuu7!z$}4@TS@5`W#1T52?cI?~W| z(P_rvkmJ<tWdlXz!muf6+)6jv?H|i-1W71)h$aZLJ_>yp<=*myK-i5AXcx%LOr4tb zp`fr=y}#!P5=H{ir{*CRM-7_Vv)ViW-ALn<noUsMI*GAvy@Ur;MbHX}8AaCy#84xo z%qW7DSB6P%r)_eUTgayWcz{ruxNO(bTIDRP4=y7yDmOo*7gH#)y8LMFNaKL-PPqS0 zkHyX^YVgA=Xl7%bn5<DY4v$h$9vOfk>w0^-aaIy8rWG60GFjv$9t!QZ*@4e~q2$sd z#Br0OF8RgE!3#?>1VCVGD-lN5*$6;ff{}^BVi!#MbLxjuXJrt5?oV1c20bli8rSQ; zk$;k3EWzTC_N~$YtSn~Z70RzZj~<U2qdAcpm&!y4oAX`wjJ*p7*RTQADnNyNw2O{x z%EXtVvV6CW4WF5U$q-270uCeO<&sFYUo!+rdkwb~P=J)}=sg$XwhC6n37;*hsI*2` z6D)qfT?b(&&`bC6YgkyCtl-WN=9+|00zz--?~~&-G=tg?W!3MQKPq49)oD#Qyj{OT zMCqgi_f-M9B&N&8&veN7Y%hcRwULA;((U24IoDxOTOiJ5cYZa3a>i0B6v6pmC3ocq zR3!`*F$bA!H@b)Jho5&5Jl11;`lOW!zKwk<v>GG=z+r}6KS`;>Lv!3grrfpexiY9h zt0o?hJu56LVf&;ZiRsx*02$yq(#2xFZ>HoQ&6^=J0+1Kd^AeN4VHUF6oTPXL4F`pX zMSn#Rw0lNs<00goj>)qgV$cxMjs1K9(eN>-fn7<i5y}Ym+i<4mN*Z4+2xC*xLp@xo zd~ycyQAtRlV0YgGBz5|2Ej3@P+;zu&a#<i$8+Oct$kD`qf46*<IiRCL_Cj5^+Okdy z8Gu()H6{7vYE#7;1YL>a7wlTRynlz|H3+yZAeF=!Y#Knqd*;JYGu>HTWNTj!UcGLr z*~GRCtON1lNUTv!ARV72F%5BU`5ZJgl>;tH1_}*uZmBr+ljLLZpccA8h?O^^69(F` zXhA-uiYB26or|-g!ZHRkVh#q5nS+L-e3oRU8|#+9he2@Tj9M#j8X;p;3*B@Y1)+%3 zSqz}NK1z6rfv8ioSGyzRF1D*5Lr8$GawFKjg4J*-ilo2|HOJv0nHsApu7uqq$YK%1 z>N4G+tlm5)UIVYO1*MP_<T3yIiAGfGY<V+~Xup`l77h%@$T|F#4EWGKIjuG~kpfmi zzAlK&)TN@g)R@+2X6=RQK&DPyOdV3YMOG-@7p-t1H=h*f)P^h}6<luzX)gJds3Tf{ z1gp{>yYvCSA&h&fr<%CG5vIYqrFN;q%>u-8!}soW`nIY{HVtc{BI5jde~zoYI$EGm zyagLB`T=2Rphu{V2qNK#L8*fXvQGD!OY_Hp_SckItHi=JRlu)~0|AV{sL=uX*>w7& zYfxPKbIixZ^O)~lOTo9$Bm`Wz(3NOtA7-2orA?UQB-U7lJ)uXjw@dzpMG-S1Tk!kS zos4bFM=*G}Q=TX2Z%XAy&`+>Ur$-%J;8xxnN*~f|BtKxcKI#5(bOY8Lnn7=dEpm6L zfiXfjQrNFx-bn5W1q&E$6asvMLru1>Fu3ES?c^Z$(48Dc3f4qQ0pR8vCMqkV^z}EV z^x*qTUUyV_ed66{l5@nqA@zn7YPkG~(?U9zfz?6?p{hVIzzDyMs?JfsneMYaR=0IP z_FfHM6LO5mAuj+Ex8t5uKtr_60SXvgQ*#I*9xN6^1HuBzf+180KXNGw%0*N|61FB- z-LEOQ0Th%&%`nArgBae}V`8Zz<hR?&wLQ(0%L9aqdmezEOgO)m5|y5*y@{Gx7GFs~ zs-{GamMVX5@$CiB-ieM{$r0jiA;NJY4otClMS<o!2KIzIDQ{`uxz_m7Sdcu8UIOy# zH6rh)WeQ;VK~>%Pej>HHFg4EU`mQVZoT;t~JRcdsMz-X89Ls8158<+an(kAVO(u$5 zicG~2i@t|XFuj`1*+`;0O<e2<5I2h`wO{-?CN>JX8%YB?ED^L-p^NQS6j4~v**9~l zx&S{2MhQteN~h!cF@c!~2K_K4$5!$i+-y4+x?z5IPq@NqeC(grJ?O^-xw;q>*dG!j z;>83L%PA+;ue>tJ{<W@9cR#2#6C{gkg{IEbb~ZA(qNLZ0ps8}~NbhAAjp&^j-J>#O zUAD~%dP~jMRDrf|VQOMLqaOh6OP1s)AHR}JE7mjLiq3U$@?hGqmQ1Z7oFv3~0rfR! zJ|RJ|z8=VJ4YicW-D#<6`qMd8LN$XtwDj-p9uWx!HrTr0sWV~DNS7}B<M)cZuR-9S z`8J`5PoYeOxTuLY($^h_%MBS~CuLK0;eUHLZLX?#O8VF5^Fy0brKcI_wdR2lbGU{i zTVEo&&2FSYbhTrEV$DB>9?&{w@zh#8s7QRmMZB>083-Swu~{6R>;E$$05`8w)X6i# zn0jm<K-_sWB5}I#kcdSt)Hh2#8%-hs8V6Ag0ioN~$Iy2qB7aN=mtNdJf-Bh)))yC8 z7IhgAJlkO}&DEMhh~}ccbRd<SU%e~imX7hfX*RUDX#yXuZQCZUc4dD7l%G5STB%tn z%J8HS?T^FB3RS&NZhf%@g9nW^i&TX@%SYlFsqr=^b!rdbzPo*Z?Au1h<)#gW{pyZg zQ$6EdrK4KwPBL_0)|dnD=kUb7yablaL93d&Q88sJR$=2iXG#jO-+Ptj&rp?Tz-Q%F z&*?F)IPSWCr#I~rx|^(Mga2Sh4V&-9&UK-@Ov>L+eIU*e-H<5?lG_n|_e$5x{DZX2 zFjd~txuqJY)6!<;r>FmK0Es?RQaP$HP)+S3dk59U&|2$Xr-WqV|2J`&^vS+11~|Dm zZpt*|dZ>g|$t1hUw1t2+Wtt5d7|>E=`SUR+en1<avRbdab_bU}mhUWGnn>hMXqKgN zv|34cp)&z$g;<q@R?Q$Q%~Rm1szDgFUYW6lM&jwaIxP{Sx8|K7H99U!EY8&%mEct4 zSg7E1w8(;w$3Wp3CiK8%6o}ZxR=FC~m~(lus$E*vkv>ML3%F}Y3P}6W>lFk~?rm_< zEy~gM3_L7>lPB`!Rtn}vL;t~AZEKB`ml7bhL+{oG1waR9@49t?0^(S~X}5l%4ndQG zqvtoD9Cf<OsB4+y<RRgNXB9KdOOh>8`p1Y_Wh<lF#(}y)L*0w;+PGjRbjY6N{f#ab zt+R&s?t$!2S8Xnj<!~9kgO}up;@XhS+{<lv3n-;3qb+1%hY&)u9JdoJG==p<E{vsp zc)X4*YPk?<!woVk95e890**QfoyG$nR8C7cADFHV{xysq_eX&kN3@|i8W51>1&L{p zL!t)1as<?|5g_RpWq_(EMwnC_LgK2zJ^Kkjpn~qV2)J;r{q*f$tMs|lT;aETQNEzS zd1O`XzCvYOg9+XWHh%w?Ja-(PiuSaoQr!z%?QB-d;72tpLy?+OIGIOZpCR8?9g*EB zTgbCr*@r%zd{jgL)_AP-<Y#B+uLD~Lm@3N13v8a$5ih(toaB0ZdV4GYCbdU|=7A!X z1KJI_34>xb<*HZrYi?qErdU$&t;J<1;0YiM_V=1!N%<Lil~?C8v~wp{Rr}YRu1Sg+ zab)p%&yk*gE%i{6BJ$KQHI+v&M%|$BRttt=xWi#SR+iv~qH7J{;V{n~K`h>?)&bRb z?Mz&kvx$?TRcFp)gX|l}w$g+~yP{X1Sm?0cudt^s7<JszPTH6~Xm8uF=s;tY%tR1( zBN#>?b1{-Sy)ZYMGAK@y(5irBml1nG;gTO%7GJAG$lyK2oie~nAtdE7_(t>!^h{8P z6EOT+fhw1|%82Z#Bt;sg7-`)F3{qz(FwjDk5mh0MOoKK9%8Y{sI_jhb**&J;942m; z{D0iFSZ#zNP!W9A2^e;i*)X`P9^3=70u(h+GuupqNe;vHdpP#NC#1^&$OtvL&+#TD zHN8h%VipsV3qLGo{PwSX<H4nr>K)~a4#@Iks(?U)yC;xy&$(qeahFmLMKLU$4U-cF zTw~_f16cFBRf^bs*qyO>8+>V`U8tr^34Fz?{7FmQEYNTg+<f7%43ttv_`aCzNRPFU zCTmtd6r4aE42k3Mwd<7FC7-R2xY?sC<za}4MJ%!c>t<80o3J>8b&eQiS#~nyVKOE` zxlHq$x-0Zsod)I@-n~^T&P*7nlt+;C?Xo#dm3x6&MZlb1Y6($^{1T@hMNzydN0)U- ze!c?r&t*-<u44cWtZpUM@>uW(<=c2eg;x-LyO)W#X1&QKKJ2!J_<^WY3u|s?Hn67l zwlIQVU^4>-JxoqteDLz4n>$uA6jmY4Wcin?h^1mEErpYE&C1?77uEqwaBKGTgnd8H ze@>mWl_veFJo0E!J!(@=Li_siVv2XTZ1%Dw+miQ8KJudN0Yt_$qA7;=B5%hA&>GK5 zy%PMwAcitWH4y!299k)#4&#h18d=Gs(c~->S1k@}+F+|gn<(*`({<KH9|Leh1P&Po z(W@h<>gQ^>!mf$Mb*l1x(@~9Ub<TnetW5eyH*IYslv%H{38`UHoyTu3h4SHyws5=3 z3+qG6DA#qHM=#MjE)|Q(==dv{05B<IPrVJg;9{{#*jB_p(J-(0vCAS6+5n^G7)Fg) z4dZ&n4Jhiy1Z=|%1)TWmBwn?jh4@uzv4Ap~G%jqrT?G2IK%epKk+VirE)=DgIjn~Z zI%Bmnc*@HZ4^zJ|rE8wR(dtpueTHTxXXX!TW7#8bF22$p!_PYo#`D^qd50!er`IB9 z?2pFWbD^&B2(<t`hasw^skmdc&Nv)Di$`R&LKQ$-rViWn+=X6d9nlG0&Mau-?JI;x z<S1?G5+IVi(X#0O?MSF5ecM*2<tT`QnAbZfh6>)JQR^{*e0ep#qdz96{K@4Ylu#(U zp_9%z)0luWG})NG;dSVIid)f07g8iVRs?p+BN|&Qs1m5<ao$EEdY7`Q#PKS<@wX@o zsC(t!&&U38Oe|eppHm5E8I|@P&d2$<$IXW}B7}uNe}S|Z-`OQ{63g!M`YcIcBW$Gy zOp2SW2H_vb?m4cqZ5QJOQ69c^QcM7;5Hoxr@MZ}SR?(@g+<TqE>xwaieL*7=3=<QN z;)LqjkwR0v?JZR|Q$ZIGu^=E20|AtaV-urpRt4wat<v&?tgl`<)VD`w3rIRdf}fC5 zY9Dz`Co7K4o86Lh#1ff|Q1PWTSCen4hYQnRGu;WYrgSd}8m>jy5X^Y|?DVlsRhJ~b z^%gG4-&4N*5?s9vI7ySn<D}vn54*8`#8o70sa9?tGJpB%DOU{}up;Vb`tS9YWm`NT z>hIFFDb{n~@Sj4!6nZzO4{fQkJ&Wnk6au6->GAIh;7G=)k}JqmOlSY(11(seevGS= z1dsT^L*zg!ULjV7_P3=Yw$)&fLA-j(P#Ke90AD&D2z=TI!3@fD)$QUOlU}_cC>SeN z$v5|ZpIF<+ju*&kM3vzgl<B(L;~3N!Qb!jg;WE0z#e*`~DvKYspAa{t5OFIUwm^?O z=FjMsm<?({*N{f^MNL~Y#SFp>pOW+gBC5Mw+hiy>hg>!%W|b)E+4MKjP!3$6e}%Aq z%PrNFrL~pL(~^z;XTdlC@U;!x-d&Z~S>R2<9}5<xA)0^zUf}BG`~XHkxxYm8gdOu? zey<Si>xfQ@qW71$c8};6E{XuH5RK@jc6QMe`*u=`B~J7??8XeG|8Uu=e0^@{>C*P0 zq#;SWTk()~n^F`=V<P=m;p^K@o;@ljL;Kv7O>I{2Xkk){fZ5462BAVGSgOyGHj3>k z)=Bm+lX3Aq^s+h;l}b(>$~{6AG|fe_*f;tb{NbfmJIyA&{%7HbmUHJ**3z#I$AWLj ze%5~lcF0JK4a9(H*img`!~+UO@f3eMG7k_~6{opPHigszoBBUJG7J#Pp$JLkcmd&- z@OLsohFHQu+h8xEb=cI8Uo2OvpBG|qPaVbn>|(X>JS3C=prIhR(r#N*o}?Glk^q@j ziWvl485I-WeR@#W{TuXH{;D8$SyY9OqOy-i!Q|jwj^(>)R)Mo8)A{0TjX(~gCgFoS zi&0tirt3+2OwwBBQ}cE~Yc>@XIBghM;2Jq7k14Q#ui(KOgnd|@pk^B)iFaa;I5(3r zKHd-RGAhGb{?5eXmK1#U>0HxXMA9gLzE<vLoZsC!aSeMS>fOgqHPljcDT#<TK_n15 zQA_|}p1hc`WI5k`Sva;M;f1nk#gH%(rKzXjW_ng?k`j=!mHL9SXUa_YgX3Dp<#2s! zFxJy;YD=KExB3A1VIjm&4C@%rWew4m%sXqkPK-=(PAxD?r`EP98{v=>aZdX3GeawU zcxd}i%B>H^2S|F18x9th;Raf0$m6*r4OLf!e6XC7E4Cr%P96|}WM;1<RCu__N%MLV zl};sZkf_tC{DG1{syQuNhQ@>2dW*Jzu*nVl9{?^4)T13ohk$g!rKdH_y9<vUa~qNJ zz=le&3CvlN(u%OjL$<loql0yK7Bco}O#(<V<_4rkr)obf(!#{$B?h2&CPKo28k+(h zY!{@)X5f<|EQa>GG@02<6$8-Nya4h=!sV8u@s!>^W}T4E98vz>5kSX~Hb;YK7qUK- zx7}VSauk|lEX|e6k1t|JP1HBfEi{uy2wVBjMw4u8O~Mjp|9sM7wdb(qZ6P64BLcd# zf^tHj1iVuKO48>(9@WWXU?ETF#xw0g7WSkus2DXd=0XL`OQb`Mr+Qb=OTh+JWIcec z;pAtgV<0JN;R(Sm-Vkg`QxfM?!OYUmoQ8KxnTIYEA91tHJhNLP3woD%dfX<X@KG?2 zLBt#j5u@q@WYy{MAgX&BolOEY&uHmEz&LNzse?RK*#kh54^N`J4M7UZ7zfneGv#r! zT6zsmaFsOuT<$ZGf}I$@c!2S?z;H^Eaz*LCw*YWy5=cKRu_eL+8tB0s(pEiOq!thP z#fw&7d4K-dbwy@ejE6~*1`~QHEML#luz>KwY0XQDkN77sj}{JVl4z8H2eEU1@5uFp z(r9x!0@M|1M9;c6#cCygUvcpN%HmbYq#nJL`Nbbh2PyS`er8nD77XYn)S17$YqS4& z&Sr4}5j_S`>JoszAFs*#cF9(u<hj~P37BICZQ5Gm>?4Y%AJpi=zOOSFFhByC0DdTW z^e>E=&NxtCfqI7Gf}tg-P#E2Wks$1b^W5eTjm65AEd{(UH14Ga&&6KG2kJs#KzbD& zrlFgh8jj{rFShBJIuLCd1lk6igCbNRf!nvAdXEAAV@Yep$EE&Q3>r!g=yOEd7S$$@ z;feLwX958Oq=)y@@0K(bhtf@!HD;8r=RKPS0=;zToQ%UxqYdgq&gc#+I9r?t5?bMO zgZ7y3VAKkQt$2@P1spSg@%|Et+fLX!(l|-ycbB&KM*Vh!fGb2{4rw{xQPixBc#Q)P zY%Zm|Via741V5k7PRL&Q2AK}NlE&I=$0SuYb<i&_*$Qx6NOD`1BUB|t98m>+jFDqj z&Wli#fm)DFr{>bEO}cqVO4!Jq{DFoluEVIHGbY`HC_m^Xj}y%m!_xqVnxg1*55eg{ zkg(!Vu^f%6M1{2^+8k{MX%e!ZyJmxd%yp0U_xMcxtPP4MvOx$q5Is!xnV5?qY<w~Z zXsP+f#jcxs)R+lg`m~=}W4qYX74dkYOC6M??W;nVOr6dQrEG-9q|aH!QoOsG!nQjG z+ErNKH-*5_<9)W`9W%WpmA^<1s1wT;Avm_D-&&`UXto<Q8A^Bec|KL?D>x5VFsHN= zRF<gG%PtAc%roqNzCB-jV|#2$njWS&gOLSL-la&Al_*`umC5+;&OS-A^m0X(QFpPy zug2e~J%e~+_VvKPGd(`AEum>fpuZ&vkKtPJ67STfd2KTxFy=>J^K1T3Tz2YaN<!}5 zC};~lbNT1cO(V_>`EW-W#tgA83d*7ua!nxr=wW_vD}C3>et<}~v(GjO<mvH|Hrww+ zvxmBhO2>KQ7Ho5d8@QnIi8dEtK#U7&4iPXYi=<!piws1eR!o>N2i1TCJqK?`OwBzk z4Q?tNpf`^IgUddvH=A9+cc~CL>?GTeegBh#yRed|z|g&vReHO$Ql?+scwQ237do_r zIlz=&70+827j%x5GlbtVllWobh;hT*WvBh*+F7}rS{oh6*l1Siy|U&#)_Z#0qZTrp zN+<T+tcU=(f-p$B&ANbB=i{cE9z45#<{20aO_EW5yrUP|?w;je7LV{^eqn*mX=i8w z!)qjP?;3PS6Zv9(UMQO>T!QV%4$FRhixswGLDO<DnqPVCY}QFrUy!|i-W~L{GDGk` z=B!Gr6o@9fu8M;p@*iEdL@*$zLDS1yd%pGGXSm8d5u7vThX81LfdP7DU=n6mr^Cm` zzR6yiXB7NRnzv~Bp571=!acWD7It0$UMpn35!`L^#gc<6|0WK>HPg*DJ5DsZIA_zM zEkkhwJvFPh$tlLndV@_sc&JDl(^+0@dH`o{fC;ZaYcL=85o($CFQ*I+E~MT9^V`Dx zF*%XhUnYMF<H+wze`q@7tU*tdFn38A1O0QQIR>~l3<u-iKBw<zlRq7Dq-=%9f_l=; zBtGHWjJhBa*z_U>c@xj8=AiumfjVQw2?#N6Q|B`@+d&-tx^xghoSKwCTq{zS<SlxH zvk379VCV@(M-hlvq6Qi?<Of9*$PmuvMVk1~Mw!SL6QT3snB+Kpd!$T*yq14fS`0WK zqDui<X46o#{Zq<a7oHA&XGOWbWEcN%T8+U}f0D$Y1;LNRq=%8P^P}GC8n>#N&rgYV z%CaG>D=yH5FNNnw8!dW&rQoBcdFa#?2dy*0d!_qpzY!GcrB}p`Vd1BLy*YDZbelv% zDt(#y;qhrmxiazj=hK!)XtD}el3r0O^Q(z3dZ;&-A36b@x|)NDcTa+@HS$yZY<M63 zPr=;m+nY-wZZa8FwlJu2GSJ3J=s(S#QTeqRT=&J9iJg$=OtP|JDuT%JQOKK}?+4p- zKDQzWTAFY)%Ry3%lsI*Z?%KLGv^y$E-y6wzB+-MkQ7}R-wyIC5%km7~RayY++b%(F z*B3J7NV0|xuf8P5OH5|ow?y8OEgbGJ;51fjA?}PGlh$AVg|^Qdj3PDp3)#<{j9rt& z*HQC;Y+bsaX)kmE=tu7%VFP>R0kpxwC8-P+)=%jhHgVW%palzmT!&zS-=PaZ!21yV zHk(2LlatH%o@wn#pFHSwhjr0r2Ck_OonM0_@U6?&g~PnL;!Q_~kA^?~fX9+hj7&}6 z??|lgzzp4C0lFySJJKdv$k;5K)X+fcqA;F$`tu-P3;K}(hDNjg)Z^9J6R35}L8m(o z!EA_;vSZxOR<(V4+ZO8uV<bH~#%fJWM#-LYwrSS=7i{F9RUUZ+&_9o&1DKjHyoq87 z=$VWe1ETn~!t(Y1o{vcL_#9Q6!>b>kX!@er3Dwl-ZnV{_(dE`p9e=Lo<=WDdeXOWm z5(ny7_BwHp-M+5asY>_l*m8m=y^4V#A)m`iNUi9k8*muW{9YRgr8yu82){~^?$|46 z%?d4g6GZyH^SM3}WW`CUI{BBTS9u2)eseOC6tms6I2c5zqm+gsxS%ffK@j60#053a z=*N}CN|8v6a|WPrS!oNvX7=9BR$oF9-2?trfS(o!pv3qbJW?4aJB9n;!W80sh2>7& z5LF~hPPa}bXhmmAK=|%0X`fHtx@}@voGx4uC8POLrkUT@kU6|7#KITB^PZ^p0@u_u zm`hQ1UPKJS299=d=Eoh`LLWDi*7S%nQm~i&Aid3q`)U*=(iv{#2}tTHNO>CJmWw3? zVV4PJcyytfwoSKf#D#8n@4CyWn$vQ}RR3b3`=B~GaWlDM_=5N?CX?BqQ42+mFRRV~ zr1b3wUli<92L@G-3nYCf0|+zMuJBQgwmHk)ZgO#dabZUj>r~<Q=&!%42G(cD{+`E! z4|_))X#fAAZR>3VQvp-V7p<TX9Zm^D0ozEu_B=w{$PG72V#`qfB?3%3tv8hoW84-# z7!)^#y!y?6`w578YEg+Y5k?S0pLf&5Fdj{!r*lj2s>^QEgo_8Mn=;=)BUGVhlr!!r z#T+A^3iZ050DI-Wph&{qBv)?;q6hQDXcMcJsmaz1sIKB7;^N^YHP&s*Xekirr>s~f zfi~#Ru*;my({ou6ZgdNmrY!yDpL@2N_<arQORD6NMJVdL`!Q1<)?<TEGtj*RBz$9d zO}C<SOx`?9J^Cc2=vwIgnOl7XmLJ(Aeq7pfZ9&A4&Rw}&24L0y<0gcXu#838PQ;#& z54vQVNmPdw)!@+`ruoxH`Jsba@6E@#_~!}&6rWQ3a0!!c%APKav@K4iH=BFhp~0M% z8NeN-)k<6ub#OpcgP!qQO)Lg|)SFU4CDhYr(vhFVVv!t6b`-eC5Qk^pQsx9t1XvVW z`VFyM^2-vu#1p_$Su2y`?1Y^m)b`EIqH`#{mHpgE?+`%|q;`7s&3n}@5-tBgM6+Qm zTO;}#dUi>6YDq;cLWO`H`h$G>8J@W_h5pNRefZqOg~@bUMvh(rFI%PXMhiAuy2~4% zMEEAfTJs=(9NGpDsT@9*v{pZ!E=;XkTG}J)#r2*kGGffe;Mjf@9|l8Ttw=jnfYN<% z4Lva^U#b)N(Z2NAa;m?LCnAmON{80{vpuFcfD#?H^f#st?|}Bt@3za{jW1W~Byc~g zmrgKS5kjpJrG}Iq{ZCg+R_=Igb%%@;!go?|B;7*!-e|%MXju1}$@PmEl|yrkvW>`t z*e_?|-(;!aL_41{G0$gJq?MVu#S(dSK4pLo6Z!bULHV&qq?QsL&OcvNe!TBu>FjA) zkL=Uv&CwDD-~@fAMo;8!UUf=x-rhbAUp@JhW%n=b=q6%oF4>V8ldqm^38d`ZQz$rz zxnN5J2+!7oB(W*KKRrYH)UAgx_AYAB6WI1py}nxL-4oFU!i(RY#DE5kT2{jGiLpt* zHtc0Eh=ekb%A%@%eQ8tbdRU7EW1#(O*_kiaROAZaN?GN+m&VLcip(^q0-D2Ya3wCr zqR8QG1s|XszZdQtz=3I`-JHyi?tTv-R#~X2h2XH>3Wr`N4t7Y$(FcE|dx-zUcu>!% zwjmec{;L#Ki*VrWVb_Wzv`)*QRFq>q!R2Al;O|(+^sp>}@cvc6Dz+6}@}fAOl)ijT zxCz1`*g`*ssIi?Ww9)a4>IeMh2<edg?c`t|S#8Ki@DZw?Z27ox%(JB&ca}qysS>wh z(oT&s`XGIQ+-GW->cO>dN>XzOMGs~O*oLnbY7-=Zi=j5~-%s<|1_*7XR9c^99^pQ? z1ro9|I-R}GBCwgPs;<fUNubuGJtpmw2)z$J@XsjLbr(T1DQcc=4mu|(GqfG1ld7dc z2LOf|5de(Lz@Lj%iJ)1anlw$i0^Ty2Pr*(a*}&!=zEYK*mOc&yWSI;DbDMTyUXad> ztfo%$bD$7JD?}lWYVuo-{c`yovG%dpJszn6)KE{YicxgS#reWLdu!AGPJF#eO|C2; z6q-JJ-$ErlmfUw&F__<f##c6Arb6Y@Q*-qr5}920BvFza<fu192voSJCWNyGVnWaZ zFEP=BAi;F9Lk{F8sZ!U?vW6rF%NrIh;Gc_I{V{NrfQ4Il`(7j;`9D{aj}U4mzu7|D zY)q~L1Y81PZh?L?vJi8Ddo~<tkZ(XA0FxIsK&6)L>^3^vGn_JVmF5JZ#H47Hz_Y0@ zq7yD>bj^eG<hQ<4H_leR=-iB!3)OeMM+Yy=O$MVbQf?~yc=O8<l8DmKv$UM5I*IcM zIET^R+PUGn8JDr5YQ5FUuz!{o3DA;sWPV3wFwaH)cL-~`Tc~mA%2oYnB=`UbpO8sD zr^+^u({V2q0>$6-)GvEbF>}c+MR)!{@cqolFcThPi9R{6K>{lihMvTY1)MU=JFLBp z%lRyihfRf|ByoVV+PzEjEvSd>^!LEIAeUC(vE}r!`r#w$jL4}bl7?SXV?sPgQ0*{L zP(Mw%rRvQq*kRKP@URbohyB%)rBzSnCjvzzY<Q<WuTf4fJwd-f9P=Urd!eseVJzV4 z+|G!PuNjGFMS_cmi$yUR;OvGZ#B&&XBK)|t=vt?(c@urj?awC_Dd-3@g$>+ALt7^a z5Z=6&oGiZkIEo6p2bBCRw$dX$5gZ6{p#}P)^VNk0VU=!kg2DmD008~_Q?4LQE;bdl zT&~M7iC7~75mfVBA35RUDzEG=6ap*Bn`fm~MP~)RB+0w~vP0vtvlDsy&Z?B4)dVtB z)-wk)$#-PLbpOUC+sjx~#Q$3!=Q#Uzi77U^WP|p;Dc46>z+R$_v?DA24vv8-v0DW} ziC>*gm5%$}0ncc#i+(DGVQx>x*W2BwDB%E^QKk31w66d{)rv@y$DH)UiqD=8(pxqc z6zdQ*o}}UT!J&wx6~u$bHbWzUGKr?0)J_~UlM9MrUj6=tUy=YvrMs1Nwh>JUwXPPe z+qvJ6Q4{!|+mrAFqn?(V5UsQ?T;kX~12`P1IRx2h9%{)gy@TkmdmyPOqLWb17p+HG zn3bQ8p(I<k!V>3~19b^!I}B7Az91vZs^l!mzFCPb=llVo6DU+vy2e(irjP?^a>BEP zCPm!r+tA6hOUV%G0&-I(6TvQ#XILjZT$p&AoK7YvND*;hvg7UK(DqiK_j`SIJnz@x zHPO^as<j-ZWoG9uNno6h{#{VvZ`lRm_gOa(iXMsp4siM{Evr=_YKOKkj7`@c<icQ7 z0&x%u19>mA09N)7AT^T*#gDQ<TX#_xV|p9vm5jx)0evuBtLujXd?H_W_hrVPbcajQ zmS>*=Oc6p50kKxl=O_+=eUEGUoZ6`U+;vziYGs200wyS>{-^Wco1~oNW(Ey0ReQ74 zfk&4~*pF$!X?Y2!&c%7~eAn^io68Jy@01u2@}V9~5tCp2)QvcLMg99W#`EXGICv|W ze@}HCj*Bmz5_EI36r(hZl>m5d;F$AGXmwP(cj`u7sfW!^xW7Vk%bS|^X!%w<h9NkU z4Tm1g1VvUibE7n)WUioI(@CmN_TFr=j=yHcCSF#c81%LPp&4^6SU5L0=Y`KMrK>rO zi_D`Dyno(Ct~vaMD5SH3qj*V?+f8#EL*R^nzzkwt1m?$eyXcxhc_^e4v<ZEX{5IT7 zb#TdqR#&}pc`s&ERFMs0L{SyVVEelXhKK0)bj(VC{`1CR=)7s74?v;sWC2N&*Ql|s zDFJ3)F%%m_c8!5<JyRJAAe8p}yKlt`@g!)vp8CW(#Qx2rX}9VV=%Dt^-S*O)r;<&* z23tWqbt)0gxT&%2?Z`{#19rH)0J^vFJ1&6KAvnsYQ`{z<5C~_PorRaALpG@zX9w4o zOKx(bQhXvekWmORO1G6*y_a%mW&S~K3$Y_^Pc-V2th`Bf!~V}p;!jAF#)~nUH-CPw z!$gyu8x*EewyIyI1$ugAy)x%{=%~=58I1r{rmG+frcLj+!`@l@frLQ$*MeXt1aV~h zC`srE>el-`-32~b)I~iw-vPRlU|2-*Vq!uJ4SDfMEFheu$LnKXxq<{e&ZWSpi{2rs z@kqXF3t5sa&b@DQyX0|gX@UWVw5|?C;j?5x&4m0Mk8#|_r>p0U%&R#So_!Y&YE?cm z^RU)E@tKOt=oe-FuBWlb>DDoscFisoB2nSfs}z)M{z>ZEfez@3L0B+}#j&D`ETlZ- zmEO1X-Nv>{S}n#^n^pI3#v@WmFR`%wTmqB=EuGxFBu*&%R8ngh%&}*2s9HS&_C9Gb zt(#@qqCwc11=1x&GtheuGyAhbB^O=Lb=x6-Hamx6k;I*nLIkq7oaS**dcUI_gb*EK z$cMo?Lxjus_uc@1I3Tt%yGbG%SZMaVhoge)kC`}&Hc2JV6i!1o*`;0h?%L~5?p-=C zG&FW0K1{iIDrw;2Puja{JVXT(KyK*6C{Imsfr{ZdFT(>i0^%O-ghMD!c+)rQ2&pQx z$45z=vm3MK39#cRT4h}wU6`jLzDGa}oa%EI1~PL#_<pUexU(1IK`ED_kw{`HraXet zN@_SbrHldVL~Q4Y-qoH9qUvpFp-Z~HmOF`Cwh<ne{%CiaE)P3*043~5B?lX7XRXxo zUcM%_M3nrLY@JJSVMUceicRr*G%5okn7TIv$S*ErQ3gKl(#KmY+^uDRYJNsMtQ^ri za>sa@*hU+sYokS177H#|tNld-LxzuPSMyoPxjQ!?VK;OShGUzi{2ECVmm)O4!xHk^ z2x=kESkRKn1+?7$d97J!52q9qY8FJ$w7-Ky_!^R<4K<gTgxB#d^ad_}`X&!ImQq1$ zq|#|Q&gY9Bw@u8y^)B<+fEa;Wsg`A#vM@OC-QSMxm{n&zJpw>TU2{m?2r%YG){ubK zV9`H=6K>(V0U=+^Wq#WS198sj)k0fjA?HLxk$~TkMo{8MDC;IbpAGDxrWmE-hXwp^ zA99{eIVAjX?rN;$sutpk4gkC-lpLv7b$K5wyt6z>hN~A0N<RDmzWpW1+e_ss0T?oF zd>O%>6FZCgk+fQ8!^5{_ro1aWSry<vc5!b3xwUGAt~lSgZKg02#zbP#*Qo;~@?_30 zDu94X_BiblKxB6``YfvYWiNT~C9wIZz?>EG0JM3{j1N8ogmfwQW$P`;eqX47;IJY; zfU!-Kvd!(Rt&3_t-wYrHNfNCxq3#U+xnwevnXbmY`bQ<E%y^EOFi_C$|GN&7^AhtV zXA+0einsB7RQylAhenL2zLi$IgA2f%j%&FH3`;PLIiq5HGk=#ZbO1*`qjW&2<%!@y z#4(L>mj-6yme`6$Two(0-uNZlJW=Hrv&#N_M*lh?Ielmhx2{fiEd?73zvjwGBYjcO zJ12Xq;J#S=szQw_!EbKduldeCjs&>KAQ_I&@?2s~GXe?y$Q5nvtm%r$qi3fw^2v1a zjKGJRJcRyQ<RK(W6u-Z1;+<(5u&N=QA<Fq~Am10wzV>mjA&gdVUgI)Y(!n_#Tw2qX z7`5XO?=S<Pv5(}l+MOb4*LRBgVXY><Y!8#T2?YVQ+6o`C!E#g1G#>?!EL$q41s@>D zPvWz$L;9eA!W_glM;sX-BWp{i1_2m(@L{Nzhsl@fCrwOIKs08Z5`!-{<BwpEU-eil zO+LvB;w|FrcgB3NT}zCaI?FsOmL_xAi-HKDjO`V>3u(ecrkjCl3hj~u(@OV8+c@4t zdny@cQew%8-NBv%AL-CLLKnl3=r~UwDwso~c@bYtXa^me7$Ntym*0!E!ij)FO*MT% z76_?YAX0>U2CJT8LN-mn-jExZn7D%4#ffB|M#$ak?jPUxfb^vzPoD^1<H+|U@sZA* z`3mDe_R@iUG>r_OE|~H5RMn!iBt%4*VYGaMa|29MSxIg5nw4>4V!@`-m^m&`Y;oE@ z4V@?k+}FG->?h50w+HQM_P+xODeVOlNtKlhsR<9t`W~ih4Fiq$*{#uI=W$*OeKQwU z>TOg>7r$Ehph+}&M)wo$%n;4Xj+qHFFzPAwM&62?5?xF)j1_W0IW>_04Z7gtgl^~q zfpeG}&@UAcB@`JiG}VK=uc@;4dbs@`;}L~nvF>@zG#!BN5dj-wfUz>X96(Z5KHIC) z=H1#^Pryn5fm^KM?UhO-tD6WE2;$p^5{WZrVn8QFQgoIU6+~p}sxh%S`kBj#0;b=} z$|XUSxQqAiHEBeT#VP8oDLQ_!P`IQu2@6X%@xS&F61#KIGe6Knl9iqvrKMzF7@Bj< zX{x!VhEba_rtkDBYB{$(%bextdt}dw?+G}9#~*ryxBs~7ZDx7*q8%ZF)}%p3K`+wF zxO}XWC66qJLN&p3xQ!L7h{=wAd}Nn|WO%3_JU#@M_!BjngYxM9dus;!f@uWwpbN21 zLY^$`XvQxQEbC}m$oMdZwte&lahGgBk_cE!uIK2+<3{ccSW>-}E63^&I*NRO`sVnd z^fSM?39k`wqj5aT2lrL<nZJ_etgdWU*yG@E`Wg53yaE#lyo26d5K<akOc+P>kqb*3 zf=Nt*fv`lL80T=o9Be4ST9rGLMwd(Pfy;7eGC8=#sx~<zI4LNcAG66d^k`d+Dg51Z zSu-(PgX^tv((}sdpjHtrv;A(G`vP|HrpFlAVJ`hyD70Tu9_3Qgsls|`w&L4ApA5|F z-UB?xt?uaAt>L2c&=0+UG@e9s8R1k%5dIgOu(#Sw&r%0yZ0jyuO5x*JfIx_4AEhv; zHHz~-neQYXgqPt}=wzn1T!-Wg6gzw!UWBL1*t8gY$4d6sB&n=ft6<kSeFIF<Z62B* zZup#=t?lmRZy+*dS&r6tXLz(AUzHGGguK0X26(&j7FMCv(#JU9vWHSC`G|nGK5v29 z%p#G;I6RgMCKYrXwQGrAT@eQ$efV!9ctWU%n!0J|ZLGlmHKSy{<V!3LdKh}mlVP%) z&->%H_0ya`zU&S8`{a#h<U9iHFdXB*pZ!AL9m%|s?o|SkZ9)ww)a`Y=fvOuX@)Qoh z&_Bc6!#*FBPm?1?=0DYAZvGlxg#XE{`~C;w4L*vtPW|oesd3_K$JsD8e)81Zh^qw5 zWg~N?4~{5y%a)+{VnjAQCr{?77(#&mL|YaGf@R}FI5+6d=Ah>l{CcX7F4!X=DE$vj z`qVwuz8f4`U#M|;pJ1+7Yfp>`ptghNzFjNXrTF~qT!WWTw|d+C92dgBT%giy28{f^ zI8+*n^5ap5ZO{C;0CYJgOogT8xlfjE|EhPTGd7_BoY1XJJsQTm;_^K6I)+JIS^YAv z86ibyS<Mhd<CX&@WDYlAAESkmvb{Nq`{=p{^beQ)^IB|43J*XUlPgq~Zta1Mh(cmC z5_Or-)zri;N{U@5X7`)xtw-F$7VUHydv%$)oTk@WqmmRqWRC_91X<o2X@T9-lzAt+ zDc}Sb+ZZyUA4mLZXT&eXB8T$6B=1Z{{E1}{B?WS~v6yTdbMUt6rh{ZXp;g4WjOz%a zVg}@@V2)XiR(r<wh>#ejVvql_BP2bHf|teeZ(jZG3lX{XDh(UK1u|^m@g8gN)o~3H z<WF)*+oj)9Xp|+L22+S@@Id2|_Q;AdbxpC8=@))jFP$Y9jOu`Z%l32#`ozLS@B#ln zRr`y_4-oftFy-{_nyD!cqV+I#rL59h!WEZ$rxXt3ml8a^Pw*Hw2xY4mW?;6&&D2v% z#l+BFTuZE$W=(r(V!fu|bz4<J!<#2j#9c^4f?Tip|7W&{F+9K}ST)*&X84b~L3rVk zG8c2>Xu<r`L=HJGGRbwA_>K-U!8A=&a0#wOB@cOragq@ekEdY8^XnioBu*b+8(^Tf zou`KVoc2qv-epmbe=)F9hysgWl10#=d9U}O^jzV8J<-^5n^}5TQxfF8(w)dv0sMa} zSyc~bXF^mMm_(Je$2Ehpsh^tXf%MTx*U^K()5msDi?r*KggGYawe;2ixm;_NEQZ^C zA$lIP!pj+#eR=*<%zWyHv2+%D0xABx%UZ>yy?rTn2TKvX-T6X%I4JbfI`XP58-RMl z0Cy$0KLrli;m9D3N(8s0Mw1t~Tbe~P+~1N6in_ibeBb}(u)hqWkctZiKjz6<DUFK| zlyEe5^mW-}G((rl#SM${yePo2!{c;N4a^y-yIJj%sUgJAzJSXxpj<+`a#ogcp#r9& zo2w<=M>Tn)t|ty?6q+FwnX!F99KOt!Ru5L#mkUwJyeIP*L0;>J;uP7Z7(z@fzvkXh z4UPndT77~15g+v(1RPAC3VAXeMI}6viB*^&_C{YzOR+{UPx^dXfjwlLXZ(;6o5XkP zIiiMC3)@Pp-rz}6Tl-*9O25f%4YWGf;=Mu*RksoHe8HKWV`mqtCf^aiSd9wT8i#pZ zSB~6h;)kuWs$UI6%&+=xGH%9a>a(5dsBe01XmYnFjo4QQXG<q&OpN0gDB(|CO~!}q zHUoU8?xx=VErx|RDbB(2%rz13xke(*E@pUpeddaUExS}eiQ2|_fS{F5d_GMV4NADq z33WbCd{)wf&c?a7eG6a~J3{&m;e;L-(4zJ}pSu_B`X1&@z{ZNp@}^DeY$B!D(1Z1y zmtEkHxbZXcvZ_ZFlVb&FxdvG^GROtOMSQ}}k^e`DahZFJ?(KO@G4LZ3Be{C|c=2+0 z{f$SOX6Cf&u`%h8<i1#+VCpxQ-ULEwd%a)>UG<qIX=zVY=9&P>Mci<W<kn|qB&>yl zfP>(ZbZ5lNPQ{0$sv|^%-ko1#^-M08DGoV7S=6vrg3+k=J#Xabi-GOFO;a?SWsN3i zmR4bZ`@5Rz9dP>LUu1#Rg7C-bXZAdm*&nIg4`pbpglX0i1NoymxdF{>2Kp|c1(e<U ze{ym|e5tp<cF-#Qo`|%5n_{J}S{K_BiDT@DB@}N8Xd@0ySTtmhQq`cs5K6zVWFq*a z3TVk;iZiy48O%!z^2)N#xW+u`zG6C9c`K55rJ^yvN5B9cKZYHNSxP#Fqju1Gzy%%A zNg_jsF@1O>HyI9|Xmb3HiEgyWw(R#UEh?Jl$!yQVl_{3l+=H6=)@kwQ;0%)wz{-g* z>KiN??7sRhwA_^qheXk;?v?60yje;YFHU+L?u04CtLj#vEgv8g+k_b##=EuUx3oq^ z1L7%h({IR9HX}~dv;Ia6siD&s^5^4TCG#WsXv#l0!4ATzGPju1;U`^%+|Bzjl%^Ic zz#>d+k~M{z`XnUjB6jI9;mcnS7g3M`Ar>B`g;ew`JxRYKkJbNktS*RLf+-*lQbu<^ zFJXxOtgb7)k=I+7yMQyNg=%E|lzedpJ7LcLrbskst11wp^_gHFY<NcgKgF8DHF@0s zp@B#a0;YtQ;J`?R-I}=a-!^?P_fHvzEY$G(2*0P@XtN}9VIXHPCf)@X7-|be!chL> z60Iaa!q+>QwGJDb@24Zjn$QuwlUq!u25S#9&Dkj=^dae)HQ@R=;RZ)@#zAG_L1yNA z&VlN4avls7s9b_N{vee`wKBu;+dyJb_=)Wh<^^HU({UppO25*X(k+YNe5=!;uTbf+ z1xNfHcFB7Lm22mZRbtj#KUa&F=Jolb6XrDrb5`ourP%>hhEAosEB099ZHHm`0lOo% z51h1Jtgyb!8!*+_0*L@ufUg#Wb2Vm{kY$BGnBCrA?hCWRqe_7+lpO(dtUxuJS2ho@ zxfqqVTP*!D{J+R5Wy#WCmXt{u0YwEO<T|J~2x7<d%DsIYv|M0jV(Bkn!~Qc38eq%V z22}GiGj2Y`jHFJdS%jrx<xy&avG>F6wQN1?M2K9qoQ;E#SsjCkMA8E$eAMwFPM#Fo z`Hr~G^E#|lhc|3v0VhbT^5l8V_Vw~)2MgW*;B(LsE~H{2@urj`-~m*i-}}KyAPaIs zDEy-BWyHotS%+cVk5&2t#(*SX*-6RHDbYfZ<V=B!j7;d>l2M)jT1k;Im)>ST1j5zV ze*Kz4R|uG<>KYfXg2wR|pNk%{=pT31M!^2#3c<ljJX-FJ4_gLUtbZ(8P=4W31WiHf z*~Nan8?B6#2!EgCTbQZ9#Y6AELWi|z3Q(X5i^F+X85$aC2N+RpSH-#14$HE_8362! z>z%2|H5X^{>XLzpJer|28FY_>5-8}0zuN8$pLC;4f1SKzmFb!LDQD9GXpR4%&}zuf zWL9bp)qxi0jCkj$q3VNBbw3(cPoZDSRTOUt%Cd*zSEaq)f<R_q6_;0!2V*KZQQ|mp zTD>&Kdoy+1QHlBWsTxwZl_c;Al(MNiX0_st!cKAzGJAXXbZI8&-RS{GfLJryyR9x^ zp|-PEL|L5CHpGthFhC!O3W7j<`>dZn_vCU|+6PYWU-*VjPY?HZ(Ou<2|Ijoo01N{* zm<K%Y&W8>cYXJk8+87!J)h?}q2dKVy7Yd3NN($l1RQ5t?X=~#?hX(F%Z0&psm1=zT zaogKkxm#be3l1_|$zOk}^o2`p47Y<GFQ({8G1|LXGIzB#(79ITnhTsHd$@a@4f-z* zVA=5D@4EWl<m#=K&Ym{i?#^b*_&&UGVG!f62fDas3z)7L=S^UMNkLpD1GiM%cgEx8 z7gOsCTFjI63$JJS{MgFs(=m2*F12N;M`z#2Ql(*3e7gM*$rc;*bU7Zp#0mM(1ZNL~ z6~g4WHCYC(;Z7jK2AOtQ%uR8{a)+{VaN%CNVBVzNzc+g8iUIPQ0N<<tqA^325!uKX z)ZW%vu1@r2tEu7pI!&~SC@Mr(jHNJ+GI4lw)WwQwovI3@7NvgFJtN8DcuKuD*a%XI z`E%Dn`~yxGh4^{P71H0}Tj&!Kz;e*h4pIe3scNd#HtxZFTboB(e@^mJ`b|d!4a^;J zrF1b10#I>XF(gUVzMVHBO00R_RzWQla2X)jK?Y=mP*M%#ru8-5;PX5rpE4p)yOmV@ z8Nwvb(;({{V64gjL4mW@Kma5i<#M>4;9j2>Bu^QVgK5b~5}f336X<IT7YsG6*wCr^ zR~C6;71u-YgXhNnYd#U57>j{&gUn3WeBWT%<x$^ZW!7LMSZSbB_QrZrbVF!itTxi< z>x{46?9a~h@}d4|Jt#^`%Q{!JX2=5cU{ZJ(O=yPS-q}YWF~Xv=uem!HI`E(|Q^Ksf zsFFJIsLT}-TdNE*A#<FH617!;y|`M7l=E31;^ukQC*&g)lsa(o^ub5|aQ}2wMfQ3R z^IRSA@C7#TOVS;m?cDraLcn}dYX0@7W~YZvbYvw~5eFUJ_}$7Yen!B5(eA0d^3rnn zT#b-?W-vh&4IF&B4CdvE8Mu@CiM3@-a<<34?e_!eSLbn%Z()KWwD;BT`RzN$xPunq zYGA6DDM7D7-gQUIjIB&dpg6-!=UQQPZIX**jqWIfT*tGN0m8<0h1*rQbu;ZJon=49 zxO=_jo-*a-eJ>|p^NXOVe`)F~K9{sHL}O`F!dQ;PQSJJl*tJ2qMB@YpeA&4CMARom zKY=aF+lB=|5<p7}MPG~n3hAmy!(@6_1b37ee50>0o<7-}y}0+P_$DpW_oJ5KSnTOk z{L#xI{IG3c{f>Y;H2f$P8Zj}B#@9%Ox*aWELE{F#JVhkz0BT`nmpjrQ=MYj!J`!f* zqIx8=y{%{MdJv8RLNzp&^2qW((=I1?Q-LR#dR9L5uPQB!3=XxuHy&e?i~Mec{Lb9O z_)49skBYD{OdhF}tYmS1ciD_i-jB3WT2=6+`Wn=2gqn*Ws@2QeN?pK~vH6YmfeL_5 zqIYV3A)}H*{`R=$TPK*=?mL6wK;b2|sESpLE~q1$dkXhI%+H<6I-}4z|Id3i-*WSR z_M@z$#^+?owi&KL5UY^#^ElJlD$FrMu9ELoP0(CQVq9)+XOP)<T#~H2rcGN8+Bi-? z7Vi?9O${MVZVm|#BC9B(YhEP4C`D5O-xh&zxXn-xF6tUDYEuHH=<fP(!FK^V-hN@8 za@jCNKJDmTXn!-Wij^(9PB+ijJmLG6Jg&3q?Uv`aG505rSLiDDE_j9BTot~WETed( zu#8(Wf+PzF$)sCik1_aKi`$cxBf!LM6Tzc$;O@?L>KabVk?EsjhcCvM_q?uaOonCi zlCR6@yQeNKH4u1+=<{=`S8p4;B4FA&wL5#C%k%;{D?_y>y{`kfMZf{R8@6o?bcpG6 zYU@d|2F(I3;o8oyub7cK0YRyd%$=QnqiF`4cqaN(C8E^UVRG_cb+s7Ysq}GJdQQX) z8~Ay@Rtd33lQ4IP4122O11^EHWfDX#<@`3ZL$@D7s`&$*1VhIBT)eq>XYGGWIZMfS zmz-l<HfhookP?|2gk$Y45v59nx$$$V4(d-AA-eoRe>(kQHRl(yyzK}$b@A~LI<jKq z8Cip}W`TA|)tcK)y7j}_0Zt&}j>fKCOLFkz#989RArU6zZt-Iyb&W=v#nNC0*bSo1 zgb{H{5-xwgYuXn4D`oFzE)%0Pw56^@^x}NL7xr3~e0(WZiMF<0<xtvShc-A~!mjUe z?-T{8EhhZ|0VxKiGqTlsYKm1xuYb>>n$lmJH38TLY=K5&25hAa&d!kY5qc!fGYFs@ z$<BUZ=Q_HsziB!eP@R@jB}IAD&_4M<tX@w|wIw_p;+{xghOxJ9QRZzro#KZsmSRc; zW9?05GpzSR7vP1B%+SW1wzTtl-Lb&DqU);J6}NSu%Khcj`R$iR!#Gw=C-3*JPG5^Q z4{(DF&!{6vVk%%WGkHO8DVxBB<SlR!e3R%^M>!)jV-t*$7dd)SUaLojRIx3xngye& z#!jIr36{9Si66OZ$dih~{D-RePoK6l$<1{J-~1rQ)Xw&L$MmyjmoG;P6EmC9$v-Y> zS}@N}m(O^=n7q(cwQI2H7SX-&pAP`>(D30@$EE3D=+wx#Y$M2i4KbtnXNMY_De1`0 z;BU}1Z@Zapu5UC2LZ=AA@<aDL95k?pj$IXT>@Q~5RdPD*432~`Wi_)!GfD-_sbnuV z(qmL@u=w{SU00rF8UEK?VV`<^qiFTp`l12mH4)>q=s?Cs<;+V}z*y9btbDMoEltON z-TZog1wHi2mNRp5hP^(AA3~!1!(UGA-8_YbhkTB3@|h3=2OTUc&E1+Wb@dcMed%R* zu;*UBZqe)`e^<3|o+Qr{KJ(sdQxG0=)^=C|*&l3Uq~$(f+!>2%PCpi|Mg!2z)^gZo zc8t3CSfgsmaARwAhb5z@ynrtsIA5toK~ZQ_Y}Oxjc)w1QTNL-_{3(Cx7AaO#$$WvH zI$!taD^6J&2Y(CN_y{(>gMOx+iEY#72d6wu@%T$2u#ZRiQ^ia<KkD1&2udydAs=rk ztgY1L2wIv)Wcq8_=YpWr8(oQlE7Z!`PHA7?GIn?Epm}1dCSy=TL{xd4i5)NZO<X9H zpbmLs<J(>Nh*PC(LxSG6%vf$d)j_=L90yN91qWpMl>xZ`Z)zb()coR=1BYQLj3$!t zEpFf3*+*No6}U@|=(LSwAb2E)u=EY%CQwH2tJWFm@GKg5vViKK!=l?w)e(>#s-}q1 zyH}IPhVe)`to>$!PHmE3hij{qbOpqTm@jRBdlr~>D!RGD-f}CLyM|zbRRbp!A%kvz zt=bVf!Jt4!HsN{iJeE4WH6Bq;-Jyohrx&VC1Pi-)FN4KLZHL6lcO=b1%V(#e&^Pn3 zAVc$W!?XFBnWuG0Gsakq@kJ-NK6V<COJ)r?uWVz0JyJt~Es)1dXeR(&95Cr3l7L2` zGO%-NqZO!WNN^X_u>~k4NexE_@ENFDy3N!pZ}de&7Dwjme&zC`ovo@iYmmNV?9YPP zQD-2AwSKr-?YH;6h^_XZ$A_^umYS3ejG`6K3_)NMEmqTVEifAj+B0^2#GOjNkP@b7 zZ67Vw0x+f+-Kme1w7;~+l*tsAHZ)IIe#+q#`k)j<d9b?xW`uH{k@wB~3}s<M8Ctl; z3U-5{_r2@0OH*XB#DOWhH@g3u<L7p3^ZH?O_Bm%@lDv+30~!p-7xDeE10te4JoG1B z@oqj-r~s)mQMEK{4-(fH$%HUMUEt+{wU*o9O=4D}<n<CiZp%D8wO6dLCcLmeAut~f zRt?qiV#)>}Sd7Jh1Iz4lWSK$eayZ_tHkARq!f9M0=t$dqEYc#GTUgRIQjm*n=MRDd zWIZ_G1P?t9qYffpXUK%_OzEvtH(l<f8+ZZi5;k{{z(1n|{%&zyU*_CKIX?rcH2`3> zcn?>5PfjV)edd~l;6hTUQ6>o3G&Q`3$|8qM^x`|9Z<(6oQHDc(LSkAx%?*Inj>LD5 zfahYKHyUrihshCw*mD3RyXwd8BB7&QM>rtQ8vFh;W}*kPT>C%kA5Lq%<Gh7qLoenK z8Ln7lh<05z4FXh53sUiG(WraS&GfNU@5W_$+(9pOei<Nz$(7tWawHIV6W+^JHS$X0 z=T|?w6emHneVOECo-wTb6=&EOxUyZ2@u~B0WL(6eSw%$76c3(3(?zwLV9<?bhV5yI zrp!lW>L@xYVyvs<W^;SVeqi*;TEEg-bFSOFUx^7NUD(~w+5qeattY5!Bp?_|#Ew*a zXIIlp?J45p4jyE}*d^3@@jQ?|!cqh>-<s<|NJuTzjXVB{;?M=}z<Iro;3a5-6L16o z6qZyv$4bda7?}R3`A2e76Sf3^#fi?N$DX}F#4t;$*T)S&F4hjD2KrRqmB6`pd)u<M zRXYt>yEZ_fCC0X0K6s7Vr*jiO@973rRZw>oVOD+fw;iH%BA+|a9cOJ``|a)d{<r-4 z98M$g#i2@$ra`ii`!8{k3*m%5Ld=(bh6P)hlPm34HteOljhNT&lAbc>=X$RN#^#J7 zCGBa{FK77)Vbk51(gPaZ^TLNiGmMAbV;hit?uNunQ83z+STjVA!_VsGz2%|wD%&lj zZH4QpNFnvvjK;VXJlUb5J3jdw6s<7}gg<oDWQrx80{bB03gd(ulKK`1<nsA9X<}dV z2c8e=qnur4l^Wj_l9dzoJA5_8&#>KSg;NR_A38zz3r-^TKyW_ZI*x7;f6{^XzsOj_ z&FUTh_GBh%Tg2r9BmHQB)<~C-gn+@U<oian8?f;@wTP6{f|3pY%ZF$`$m=(%MX=7n zOdPV`Zuq6KlcFhXU#5bB2g@+(y7jLb(L>=LtacI(;V9@RX&-cTvpp&)skI?G`bBQ= zW3jb$in&3wf~<?BA2@3>Sw$&`>aYhiLXugP{kw)e7c%rr{F<0Br%Ap(clw?7cTUyM zET<oyB(A^dw|EG=klvX2K1xT8`MMWq9(Nt)MM)BQ`-_R`_KKmKcB=ax^Tzo{YWR>l z4s7^<&~uduPTY09Bsj$ur5hqo@i99iixWZ;6h+Ac%iooGxvJ>3Z*LNdnxbKM9+K*| zV36*hG`1XqKo{la+=~vRtzsYNxv8_%<T#VKa`k9FA3cG`wWbFZk-5`7!0>rAdDbCl zY0y-?<rmn47Q8rI=w1*C7=1?5l2t91feO_}RGa7+pFE+-fR>@NPgoDg1p8V8BIo6* z9^|0l(#ENnhUAihRuq9~HX?6RXncvd%x@qCRnfNIu#gOtwO&@@q12k*+kK}F2G{LX z6S!Tv<HG=dGLFz7cRpB9$$ZIOh7#wngzgC2XuMZfGoG|LIC{t-#tI9~ur+xDqVqw} zhp`y!Z*r^|`cK(|s(ELz@4RAT*AU~XukWh=OJHkRwD*k9%dQmh3WV5)khb}~IoL#k zS5Bw$Y{6Y0Aij{F*x<x1I<7JUUIm$NIw}|%ZaR2m@S{xgzP2VIXxoL(ML;uGNGR1E z?b*vEY<>Q|;DG~^xsnf2^I~6W^+&dl%B$z7)xrZi^MC{VMT*|P_|HPI;D;5D4s;-e zX1RW+YAZ!tzCbBVsIuJmF}9%MKI0H}EFQAY1$1w{1S{Hs*l63i3}hTL-oJNb+b1fr zXJNXbYz{FPLJ1vpL~%jF=1av1j|D;@(zDIKqA&EHn*9Mg9iYAUyH5TwK9{bLVMp+% z;%!Pijqch@F#GRPI&94J1yYmmwG18FYGkA`+11ih;SKm8426fU-Konsxg}NOGI3j| z)}$<p^MjtC32j!THVA1%v1%fAKtxR1Sl<*s*%Yw6@@}f*9#J(g)r`e*TFdzyKVdWh zUfI^dW~@J-^01LLY9pgpBnUo4p|s3BTW@XePn{3(r#sXSr_?QhZ@^^~cbtHe@B{dF z=<Dc&c4&p`;H$3*4qqF?qI{Oq0UCj$@D-?GI8XfD>_4&v1v4g1;EanC&5^8-Et^}g zsW*a&QDt2uFd)rdUZCTPIc9=_!&$v|{NEBFM#2#oTwrm&e?Hujx6-wR9n8etwxepH z3!YD?UDcb_w3LtRF&<yAwQkGz3%vmmw<ulmKBiMqdDy?(+HefU2S`XqxvbRVyZZ8E z=XvqSpiYw#<AEI_095onx<g&;?bu|M!9idp@Qyg;=YZMS6T=+uSXCRZUOk`F07J!@ z5Kd5M+x4@>_1munhF0{Qs_!C?NU){|ENIOJdXWCq`7PRJrHW5`!*mkKDOuCBe|p!> z<OEz`XA=bf!T-oG6ao^jwJ0C~{h0Yj9{uhdPDxTAt8)BtW!^@`zab#(C%eh9=Una% zZmHNf&R%zB)RVx$=mL(|^+U<v4J&#jS!)jO3cpWlmtDo>tGF0jEfwSZ(whW=KU|!| zgi6!<AO1YaIlaFkmvB9(MT}q=s=*K!c4kQGjt5kpIlu|*jm1<lK>WmJE;+jZU5h`F z_m8<t+B5o5Y>`kEYDn^$@)U9(+#TgOIUQXsgJcy?&*Tsb=^HGbBI3Sbo@jD=UX8R- z<&}mg>iLyKE!*4GsX}sdrpNL#8=Of>l-S0<(f(aBR)ZgynfLSAduLTbE5L_qxha&1 z2Y7S*B5r-6p+Tny1WhOX*7DH9@mxCNTEE_PG&48x+Q7y6aOmNh)av1bYeqx@efwNH zwwZ`N+#B_fAp@DuTLb2IWm1$8z(Fx{Yw2dSVj4w@Sa;B;M>+$xs%`9a(`eN-Dp0`E z8z9H*SUe=RA4+k>PNWGEJ}#Z1s4u&uNx!`7Ziw}S-{TQo+|r!X+`c;A+3vSIo*w~y zc^?0abg#FqKYJjDEyDq5&tSiv%?uByigs_RRKYKScbuq_JNt5nvK%K(uTf}&u2q?@ z%HGS%AY7<xmi7l4)o4rmT&8(zFg`XeEUau|jP)nw@}<9&&Z2E#DD~EfSM5H}1UnS! zTJLYq35$zDi<Wen0mpXr9UAS@e)_(WMDf1l)TTClHnE&B(qInGa+Mboj*#>rZ=LQC z)1HQgmR6bP*};8?gM&N9ONhg5pa^yL5hwxyT`rXW+7A}<p{VAM`6Pw!76h|=3PdL= zFH=$^zT2yl=5Lw|iIiEQHuh38OcWwliE7M*fxcKMWiGs?@@pC-HmcXbFnZ3BC`3zT z<z~yL8oY2MH9!EzYcsT_J`@(M`~EW`B6)z$b*GA}rj&+o{iRS_Un@7^z03n<3-*do zDDEJgp^&eGo&S!0d-kfYbn!MTVfh*Bb&!1D*CdRakTNRXmLSSn;vgNgI9+=fD$(W5 zAYsV1C{m9BlO!vWB)pI&)IB?FUxC^gJ$^6mTv$k)27y?_;ow?)6rcvitL#{014=SR z`B6Hsimuq&QQv62zxf_cM%3g}Uqcm?BbBelti<K@w+0<z)29RFO?t;~%BCh~>PUQ6 z)#?Ps*}B0<BK44lRz&?@hwenDzL2{tgIZb45CB`JF7R5_mFtNO<91)#O&ac3qAeT- zz(Q*zgfn9T2fQ_o#)D5s0ofiV;YZ%Ymok`*VcF(bdV<-@Hc_zQpgE016LUyKCMZEZ z_AqLiyDIF2D`!;<9ql>T($OQ|u^QjFZF6;d6}8&(rU;p+X9j?S$BXnLPIe*Bw;6mO z6r(e68XI^OHq#H_T$3r+;?QNn;YW2Ki7H68bQ?WU#>O&m9*#;)dI_jt#R>&yorId6 znEV(esgt%^FF_-#aQ9>OG|}=g!rkV|>+eIeImn}{pl`OO%r4)h(O8JTOL8P2TH{D6 z7q@GaKiTxf1KJXpjZKVwoS(%*%9Qluyo(?$5aJIovC)&AAkZ_2&<K?TCH`Z)iAF;v zmhp}c{L<iv0=*V`lN)6Uy?rvKwE&zTlsM))MjtklgleAUWCLMI3g62l$KYO3<OXfB z0gZ?mOhwx-BpGcTq{C?n1!^X=B`W_v$%Uq22(*n&$kdY97Ij)qfv`Aa#v&V%W~M6$ z8J6rMV~5Zpr|ylkMv%sK_Mo`B#2vSN7~^o|n(Ntigb4qbILQJim6@<n&L0jgl&j?U zu-`)!SZ~Ouk)Y`hR4b!oa7P@v5wF5i4BRah8JwP|dYxPqb3Zl~jUyr-9Go+uB!}lp zN-Qsxc)Qb>Bi?$}9Q19;n7e(=thX6vNN+EGpvSaRaW^oLQ8#(JIy@<4wXec*6r~P_ z9_d9WswS|SVydi5P=m<=b*-t6&CzVO`JBYbNql$;CFbVv#Y8cmGJ$Sqk!XK!W!T&n zfk9*nK&Ip8UW&-+J)JqIsy4l;K|YarK(WD1a#0Z*l9wRMZm7DYAr33b08v`7x58)4 zLR4qh^~6`*IvoqPR*UeCRmwkT_Ac3I%7cI;ftqrUquzMD-bw7p7((o#1RRyMKuMGA zRbnyOiM_e>4Y7+nY3afac0<r*AqJff64vo1<>d|>nYe@NlN;pmcJ`}bsJV*ax9HU} zK#mM%7$#*FIeQJoK1MBX7A3N9u44gj#ERc^pXo*}4G&;(X1p1+)bW9^A$`)PLj+Uo zRelAV91!^}ma9I#`fVNS(xSKsVG@*k3m>KWNf?L8DuR<}vE;SOD7<6gq9hn{Mupnt zi=}URQHD<$7(D3Xt&(Ug?M+KqND_&^?Y8#Ml1gZCP;!CjHt@gx5LE;u@NOXeQx7qK zHpFq%evR&QAJ#k}jbF~QX<+I>W&E-dH_}=XS~iZ1!jFZpM7v4%I%Pha7VrA`+k~m| zHxiSOfM55izzcDLgyLH!L~z9<^cZ=7QS$F8ARX_jaJ~e=m+edA8S0<|WgPJsf@u)v zc>=OhDDWoY?%TU3Hv?E4_l4o>mUR=ei>mqTqX{}S4v10}H)*F88B_jn&=7~(q>$N_ z3@@DVFZTE0L7b3KH@#5et)mSpMZqUa9tmP;jj7!!OQMUlN6f3#n96lo-36e}4afcD zKSfCC)6<zOJ=7PEgmRCi`sB{e)jfTw$#w-fB+kjMq2NKI+$X}XPpjT6$R)f^QpzJ3 zGbo3#<?>^I%jRT@Wwh6)|D0)z<@Q9ryh|6_rZez>7vWq;O>AJ&e?^b0*)Yyv3@=}+ z^MhzX6TG;kWOPfly*7i{FDAAlO#uHkrcumaG^1418Lo|7Dt}qa5&L%skGKswGF$?X zZ|;phJ~QP>i<4Y)?1}J{M>A$uu2A)x8=CfXB4A)R*6~wiQxAMjQL>WM)QdZIl82tB zhX_N^7~WHI_sYLBvyo^eB@?bKSVM=-^y&yjWK`)qBW3?^L83u?vC^&M+(%&wCUHOb z?u0>o!m-I1Wmay%2L@TQX)zwdA<#h2$?yFA5CwL8Gh<x+oVM$n)738E(vZ;RbtdHo zeyH2$^ac~f?}3-ETqwuhPkh)~Tr{lh@SPs8d7l?Il7BwE$J9&65E%C!9nLdN6$g=P zZhV^`5TxZ>G`#PyUgErk9n*{Ve}DV>@vWQ9E&M-zTYfMz_29*O;Xi8o=PyZ7LPPk2 z^>y*DuU|cUaR2esO*zFSI0esL2-r^OFAcPpw-?Ua8(o414DpP>$RIZ-X9riXkA18F z=3}tROK}5C@CfYd3#4H6kMofP8o_Ak(;(VTp+%=pyMtQLi^?|8qEV9O<fQgC6pyDW zI4MDPNRykbKfvC4xgkWg;cKzPq6l{gVeS!Ut>-qk_6=9BHW6!Vi&q~wEqK9}63xvv z`|`a6iD4lP)iSS(J9(2Rw?tN_J?)xKcKHW%tar)NS`qL9{L!JAl0CDogCjMXm5`#( zIb}G@okd+_NeuxKPK%%D-I7DJC1V3)XC~4jcFgMWk6ri7SZ`<hvQQSNYdfNV+*Z`x zDfwF$xR-Mh4z+(cFfcE5e@j&F=<DrGPF{-D?DX`>ZP(Lgm{6!cB)8_)O$CSWUrm>Y z0%BEA8}DBdH6yRd=>^W>uz1U)H8EWwv9hg#iCYXEq4H~~0e}$#Rg3^rr$*jn1Ot*p zP$ZF0@6u&8<Bi3Gq{W;sS=Bp3fn_}{@kDZ}S0H`2Z^r`mtDT;e{llr@Oe&>?5XT;R z#-_&g-hTDD4C9K#dg;=~4_(pQJ2orJ%v3_yRnGj+o8=u<>^0p}y!bqgyRkSCx45JB zfY*S)UZM;Hv71iTGtrx>ZFHp}&PE??RBMFUBy5BIe<JDVyqDQ`fFInNI6FOgDJS8o z6%kkX_kGi;sDEwb@qWf7)9aNNB>{1zousEuRIh~F$qs9tu1Z>JeCR&w%hFl>EJbML z80vUp9Jf;+l=H=dfy=nEOkd<{M`|F7UeyOVv%}d`)jRs}>#s8J3sEvoVVVFP*)&ez z1B~Jr-p6NVGeR{(XWUv~Ic7EsZqqcPUu?C@JtS$+lQAH&UJ=HhN!!xM;ZMVIQW8^O z{qLH|vs9!<x6Ghb#H;@$016`0fuGE~t&1K&SR2fCg!Y+0&r=_fa7^c$JPaGiiIip1 zP)x;c7XCrM$)dAb2)5XTAVkxCV7Qq}FbEHlfEZz`k+m=xrpSS~l+0)*hpFM^0l(wX z*6es=WENcpKj~1R!0T|K4*IYDWNKR9u5xaftQ2l&0x=yA8GlTyp@G7EH62yUZP7XQ zapOU7aa0J|ng)j&9p|*exwHm^eZ1UXwPh!Q2iv!s($Yqv>5zny$d_G5{mQPpJ&dNw zHrsaOqon8P&-C~;@qsCeL`xN{%cp3uV&x9x$JqPBv*mLVE+&I;>0oS}P^({l{|2cX zK*&d}T%)`tVo3H^C4{9Y-ccXHlc35`<#|LN$ORX!9h0XMc4`?M=pfAuxQjE<Q7UsK z0w;8ViA@9<8kKhRM<K7Nz!BaUvk7%pU^FrNCIT+IB`Fi%@4cTkKEfnb6Z5;(D5F2^ z_AcA~-14)d5e&^~SM*(e2Lq7DXnUTOi^2N%RYR4Z@d`Yk$p|K37lZs#y#GSylSwLi zmB!)ou$~C$IjN31shi@^hC1)SPvB?pj1?QNe5$1+ExOk$f4LNGtWHL*!(WNUAhA7y zP5B-h9XWG&SBNdZQFvL?mY3E8vFuo8!-bn}qTd}aBIlKyUuSRhU7y#`uqbz^?8m__ z+iu+bj4LmF<tl@3=ySPFaFrtXa`&DRHIa{D@@^jHqs|1gqQ!91d|OYS>fH6_;+?t7 zvPZ|;0MV%tUN4;zuMf*f*CxL?N4*DQB>_5>I+ZnUS*#1dG8L;W%eb+PqWkUdbx=@V z6g_JEQnKG=$Z!u5bNRt+coQcDx?~ZZt3FuiaLQ8NBkP(cx{`RYoA4h|y5K1etPF2% zCjn4{<{`y=>u@bkovU@>n3na_wDjWH^sw_x*U((!4U#v!+qKBGHQIKQiyz;eXU`w) z2Y1VVGH)-&$}9V^Z-YlP6x=c6alOZR-U$(DJA)1}5*s7>7;*~O!BkS%3W!e@Rmvpn zgyov*drF=Wu;Mad3M_60BPTIx4G-RSd9#!9|4)^NlZ>?#2hFu52fT)NxO`*t$HWJ5 z58nRZV@XmCEj(&6K22D&7ghLnM(`M{Q^<a-*)dbwuoW0t&4m78hT|{W867Lvqf;QT z3NGC`XwP0GF<}IxMrv_kp8jBbE&MoA!%<R8s<96mqE0qO5PBM?{{62Pu;awTV;uO- zRPanO?Pzqar6k`?Kem<;wfW{xJbu;l#(&LZU2B;e3bv(hzl0BAZj8D+FxbxSGA_~P zcq*QoBp;oZifI;s$ag;)<B8N(HHUhp%zWgM_^eA2PaipR^W9D)7iSLZ9(`rCJ@qC> zV2J{nfofB^><WXMW71YO?8)+-a98d%#%<lXp=uJvhGTmhzo}&$D{K2&2=mg9hPjKy zZ95V{S>u+3(#HL~1{P>zld7$8qRAlIbQnQHAjudwHm5TYZ%j{O+nQY&30tWm2|WU; zY18jjJBKshzx(67gKwQSjs2zE7s3djP@+;I2YK#9XvxOtny*HIi7UR2KZ={qOVxQr zONB&43O8oUbHh@kKeK>8lU5#hWxP7xr0-B`X)nX<D|nfQNOShGXVdTY!zE6o9Hg)U zOe<SS+afJb!wghkfOp}NqU!UX87A6eU0TmqcIOTsc-Q&Nv)m2ul4Q+FueS)}<+>7& z9u?qMK1wYJt&^>`o-9~uINm=s><hZ@@g`<MNDgM3Xb`XD1{Fq_=?yBokNbIIt_QEp zxSBJqs)#Iqou7V6dBQ#W+2HOFIN@dXgN!dYkO*M;JCecbd_vt*fX1F+TOM_di`B`A zOGUBDCDZW`<3sUdOo9|44I=p19{*4-mf5nlV@|7$W@mb`n9TqV1|=8sH}{{M&RyI4 z&FlEQGtsjeUXfCvC+2Oh&X%w6#Cm(AdD0IZ3S)$Z%Wv2Ve;fGYu1s60&DKMnvmn$C zYd>2+^2{2T+%~`#DZRBVtCgcULoM6`Ki~98SMG9)*^U!I%xx34ZMJl@{+`8|ouz(p zq1pZPY2>e&Xl_nKKMj`SuL{i!wKr{X)z-L>TrE^#ejFk-m3Y~Qu#UBk!f-P{EiCjL zHl`8VNW3P&h!9gk1@jwSq~YaOP82W4DlD=cvRVnXSWx<sf`OrH;#YwU)wGIDgB8rT zQg-FFZ-?ru^bLuAMwhcMC(0dtQ)j~Le989Oo3fjSlf*_v96U0(0A|z!mDkEEo5GqF zF<{~d>Qiw*Z|;P02svEjscQ=n%(<?{VuNLzIy$9Q=AZ5g5qyk8N$KW#aY;}Nh5UiW zdgm~pq!aG4N^r&tpz|R9TC49X3RqN)R7OgrlclWYNo!j!j&zp7GK|U_Z@-{`5Mz*P z!^?K0_&`MR&7YP$oyC$RR||e|U*$M{$g+n@o0f5N+&%1}ct3&=1md{0RZ5D(w`;Z4 z-1UClPFP&tHzon~Mp**X)9tb^Zy<i#ij>~32&;kLFps`OME`ZxIIxKob$l-i$ky5s zY#0OXt7T|{_5`j(KK*<_mXmN>fOjsuPJ9()tu(kk+%6+s>n7Ak(X+y44|vLJN7pPG z_~gW7q`Ys{0`gPG__CK)Yh@b>g_YEjk<rm7bP(4H*RfmQ^mC&dpTsi)kS{2syc!$T z&xR2tlKruEKzniJMH8!p`QnR!^J<n@3G*AJcA;pcqamWDEiE_>=h?1&ks$=K%y~Aj z0~9$lzq3NSi?s(%V`gWkSzSN+t_qzqn5DUeTvfUZvIU8wc`@SQK+Nw7I=pp(z+rdI z*~*IoQn0t#Z|4hp0+JpQvJs>&@)~cMr0kuf_Q5zE&TR-I<TLy>CvZyU#Gc1O{lcnE zekgyN{-T-cbh@U}kyiviBc|`Ba+S=+vhdcQZ>99G`JD7lU{n(ivzh{<POIm(-x?gp zHi=XRUPr0*arC<)N^jklJ<t_@L1Y5C!|swDdy6|X%e{fYDaY?y(EulO!y2=nk~Ye~ z<kaOq&MnA1msBs9)u~%u<^xIH8(pyPVn?@M2^ZB+?vAO%g`dTfvOR<_L?i?~I4$8V zV`I%cO$Ea?2Ngv&w<*ig<|9finNk~<12)U5*)1%c=hoZB;TlTB6Y4OG$tt302LZoD zBeFn`vb~7##ufazG;SM3YX-qpK8k_zK4Insbs`251@CG;Mx+_VqR~AlgHu)ay5%fa z&(5UXCBqtFQJLjYOw2IIkyB1emoky!3Jx=vzt;f|hr6I;e8LDbV5IZDk>BBPrWL=# z-o@))t1#yXdnVsZeQ_3wnaS=0BXyt(8T2+L9Lv$cT>y>`r@%6CqlILQ8KV?jyo_On z9q#0<bVkaL-FZ>t6!A7rA+LrrB`%V37?#t6x`+YPADEp=(Jzd!acPIv_TEb`nJ(py zk()dMxjS_>y4U#iEssbPme&$9dL^8x)P~nmPq*Ml@Xyd@<qfo-2uj1Ot6fjo{rDz- zgaJ6C+uwn=;d`)Oe*kWzA0Zy|f+lM!=W^DTv9TM{)0LHDck=l=vYu~<xr)FK7~-v` zi#HkTvnFywp3+MaQVbfq)tb3s(ZpNr;cyaO5;vKBG(h4MiZoO*gYiv<D%G5l26|p{ z&P$obg9w1YI~XIvf0@-H^^+z1Ca<H;z-+7#yy)qeOCHpv!@I}E&JMl6e;vL7-?X+1 ztLV-gD#I8Gt9_Zh^Z|4mP|GR{z<G{RAk>iU9v9ukg78@cz#MoD+6~*&-0y`TSdP&h zw=EbBXXj&MFG@fYPTA8G+(?=NI1R%gRQ`Efw6hlhqE~~hxTZmUjFo=(4xDtdhJ{Fb ze(>Pl+~eN}!3XU6Vh!AFilXX(FU(UFZd2Fl9iD!qaLVz3B;Oe~HBZ!`wd_mOm^+(W zW9saK*Wt$0JFIrdA8$nW4x()6qJ5D4F@6dRcPu%S-u15r^2dv%jD!`Hr^>#2x+UR6 zT$Y3sQB*Ff9-;Wvda2e42q<pWMpjSDVChLB2`zgUc%Ei-!<$H&zGN0>q@snGWOCI! zX^j;JBXTmMG)?B;?e}Bpx}(t*daS$Eso>jdm*N|ZjD?!!;$2P5F*Nqfy!8N+5C?S+ zG9`FAnSwj3RVjhi$fe~|EJ$8!4Wrvx(<d5QYn(qh@#Y8ZRu+6j!+Bjv=kHJLWG&9c zRAQ$7a=doZ>Q%8-suYey<!G1BKKov@W#lR8Q4xy&(U384DY~5~r1^6Y1Y8M@x@ldp zo+~w<qoQoOh$Vq__{1XoLad5f_JWp!L8;4#g>yrV>J8@MU%4>!1|QOFm)jeq{G_n% zY#VRmG1TEy{w=?qKTRAT!hw^xV<XxT!%3Xo`7OMN2oa5x`a1rC3@a7BvWNiKNx{wd zZT_0(|1~dxBOEpIdzohpq4`t>IlO6Yqg~oAh|kWJgk5dv=ERz6rebC>ThincEv<E? zq_nkoN=BNQbE3yvM<*f<@BB0uYLmlc?B0Y~z41!`B|-#j5iF5NmXbpRWl@vzF7-YV zlYq*?e^R^bEJ6u}f8#Yeg@B{w9BMF|9P7(0E8KcYSGu7k5ebw*Ep!Nulio}41U*dz z3c(l0L<BLW>paeIi%zyn;vNcZbd!$7ast=dSX`>|LzwG@F5F|^7k7~U%H_}|0<|Zw zcWUoo4w%OpnO(RxfwQh)H|(Ypl#XdG##!r3D`-Y>E}X%X>J?3&O+*@U+V&50xW&CW zw5H629{O@%(67(k>YG@8Q`NL@?<|e5$TO*keLE^C;EoYE30Zg=26C^!SK%1c(Y~%q zsr=lQ%{V|B%fO=3J0%Ho?7k*FdH<)ME8R9B3q-gciAZh-h(iq(sWpWpwB6z(G~X&@ z=+~+ohz+ve<d{7M!|yY2D<bbEHKM9bS6}%h*n+72D=dd!xftD;X(?!Y=sOOh*Lm+v z(xUewCWsL#fnk+2s5p{tWt5{Ul9*~OC2Klum!bi`S1k%cq6Ti>nB>vb4))|eC6Y^$ zWWFnPw(k*H;#sa%e6su#m+MNAyNr|EBK+-ZPXmLgYyR_f)m~1J23+d?sB&=3E-RFL zIxoTxA%DV1Z%8|-sp{6cJ}t_W$Kp80*FbceogcywGJRUs8bWUw8Ht7GU=z8J+o@1Z zy$o*|051G6zmq1Q+W=#kY>h=@(B9@T0QOI;;8`f7Og*^ebfc`gFwT05RVHaUL4!zB zmjSi6c%1jg$rFtO5F|Ghev~_3`f7J?V)@z~?iK0A)E#*VQ(O2u7VMH#B&D+{UEuUJ zP2O{}9EM1GU4p++41^eUzytH*Rq4mAedLO86`=>i6b}1M$~-@g51Y;Of}doH0TSjH zm3oykg~RYu%@1%ECF3}`s?~2q$uoAQPYaLxaZ$Y;8)KHHy6z4Bq^UiBERsHO%EoMi zrgv$Vec};+5ZX~X5)=(QNvA~la8hX2B`%+sjrnpx;z~Lr-6zet5XK~rma>hq?CMUP z)^vt&bjiy1Lq_ou?3@}-40~4?PlxR#Y8XVsDrnO4kjP>CwYD>esb&+ga0ZaNgNA16 zq*hA7E){95Cc*Y%(oqV|WxowiQ9F65%dfP%j7^h)=JyGcCZ9Lt+(^83w6?&`yiOF$ z*odvnig|T%uvoDf^)9H;kmjQi?lv14E1_4UxxM*Oyx-NHk~bU(p)6aKyYmU|1G*UB ztZb{IWutTGyWb9oYa%dt6%e|Uz6QGQqZaV)eMl}~T9_ug(RLwR39><C5jGWCLRA9U zfF-to0!Y|01`jB|^VDV9zzuG-=saC>Zxi0n;m0Bl);d;HOh~Ax*xXLsN8w!)PvWPW zqwbPy?Jumw1@~9fXrQZ5gSC@QRx1gJiDZ7FtHG<9aUS2dNgs+JWCoAc7qh&=s8$If z+fa@S&Wtfu{c_Q98<$a_4WtQpuN7d*6Kzz8fEXW!JBW}e6ZOOFr5A0!Xd6e2`Duzp zpyuXdAp(!pIgET44-Kxc3jm<V$#1>(-z&bf{lPc#{aXM40LK6PTp9oXPQG^De>|D^ zx965`ZnXda3~&Je00cne{x1)HzIEl#g>NNk0=q!Zp{FXT(gBVP65B4f_XQQkDZfCf z+7t?yHTR}x$StdnbE*`=B#^|v4iulfEJ61rafC)@Xv=5}R|FHt^)&L?S8y(0r0}OW zt8X$0c$C{+@-SWyXJQ;Jk&?b|b4_;H*mTJ7MJs}X(w}6iH<f#cw=`?%C})vRX(d9_ z<}lr+s9^&6PkW6I$`zbn;bl^gAOEj^GP2zGF}aevAE3aLoGB`dbMjE(p8%$Nm(ZP4 zoDWujDJGfgT?mub*L@1Vw~P6?8inn0Bj#-51jJCWQGr3DJH@7LQorx8SF`R_o!p2z z=5QWrCK2`BJId?FXv<;yuO585A-p6e{pw0ftAZ&iY@;gzawdrP6kZwRCBK?PfyWv~ z8N>A80gqsF1#ibTuE?D@k6?5Tyc7$1Bl|i`Ivxn_=VbCEyu~)olA|0(a~grt?eOrO zQA7p<N*~|sGt{wp`CqN7gt^D<^jkI)GpJ;8fvd^^GEPggv?!T%af8(Mlbrq(ZER;X zX>71xI_bI9<NIVZJ_Rbjpp4Eno}}}+>m`S$_dmA+0u~l{N08c!LZ8emz-BNFIkPs@ z(d+)F00>SJxHgzU?rh+-nEd8Ev`&~MyE1U@=4My25eGWQjybOc+<Oy<CouzTkZ+%s z-TLT-oyhLJQ$@g>NJBCk&9AQmgYzL^Zev#P;z+&5r|_=Mq>}h|Jz8U$EX`H~4lN)# zuOIf~<pSnd-{{X1Sm4u+e47A#H^9Rt;zNxE3KlC1+)7sdNiN(W_1BpeUW8ud)1MfF zw~U`G5omWtR*BKGEbxi*KLZYec<+NfX_LxBs^u^U_#KBo6M`3*a~ZGCcC#!j!lJ(_ zu+QDh78dd?fSg#Oug<vlh3)h`HrVl=Y#2*!5qNg2&<pAsdc}~h{npVIqlk33{&H(Q z?zuSN_B$OCD!&b3ftY7?v?)P|a^om>FK-gO8^--{F4~p%Q!M&xu;}ej`MqV>giNq9 zzumyY1kH=}g*mRvPFz?5PUmR$6FVavovHHCN}B@Jz#QAKQ|NrMVTO9@l`7{?UO@jh zFNuY8aN)E7S{=;v!&Q`{eRdU+a)3ju1_vB_I|t&x+RlXpc&$AO1n{?mkPfar8bnxg z^H@*RhbDlKYSNGkVDwYkc@!Y6-Hm*-zr6~@G|E(`4Trdz;~liu!h{}g_oI-mwAUg3 z&*|;<dXJ6Q*5E#QssUnVB+%ib1Vtj!N)VVCw4*!v=){a7V|Zbpd*@D(!j?%8e1lSa zOps#`D3S=*T~)Cos75DTg@O1$=qgeOjj1nSo_a|{IMyE8aRO@@Sxywa?3#_DP_b`Q zH;^-2864W_O5myx9SaQV(*;(CO6E!`w5;Z5QnaQ`<cheAI{M<+sgD9dBUg|Rv4S(@ zI<7iYrmOL8uel0`*hi<74?+n8Gb;4yh(iv{{+Klqm<W3#gz~EfaKW{^b_qj`v>M#2 R0x73@ZZCdSiF_LX008Is@NNJA diff --git a/.next/static/media/ae9ae6716d4f8bf8-s.woff2 b/.next/static/media/ae9ae6716d4f8bf8-s.woff2 deleted file mode 100644 index d22d6939b0e587efdd8611d363fe0ae61050fd1d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 11924 zcmV;FE^E<uPew8T0RR9104|gO5&!@I0C6Ay04^v10RR9100000000000000000000 z0000Qfjk?B3LGjwNLE2ogi!`yKT}jeRDn1EgcvVu5eN#(e8YMRgbn~O>~sM(0we>7 z4g??tg<J<98&+yHY?~HCyB*-u>wngbqKvZIqo^5_lU4Eme@Wm5hyvY$+V3JEtYS1f z%V>KH+vT;tpLX{Sy?3_b6~?d$B2xpZRxL)rsIZD$Lx3hW_Iuy&?ZFZcM-5E~-@vnb zcES)4rm7<{M1<oQq^4hl&aQ^7)f*u~gpX0%dUyKTZsb2gq)(5~*eAL0|6g7I|8wn# zL{*&&v-^|}!07Ya8Mp2i(UR07E7s4Wo4t>=rA}<=l}_W@I3}nVf?^vHg;vm1qXY#( zNFh{IT*cnmx$T<U8{3=P+urmCVr~7K*#Tx|SsgbtTDg^s3=NGdEWStHfMlFUM&5Su z@9%ZneeU1h{k;zT{>y(+e*h%f$hf_!wj|?pQ`XR^xDAbrJW_7MjrNEmj}%wbDbdhH z#odwNdGhxDO$Ia_=*V}8%>oGky9+1{)9zAWZlQ0x=q{ENsd%CULZT51`N0qtAN#J= zC%fEC56~$T5)kZmVmiC-=%eyq0cq}}0|zYJy|2zphGkJAAAuE?9{dO0@4tZfKXX=T z{jRE>ZdpLPPq4aok9qIdW7gOpX@t((%m;B(ja0N6WO~Fs5Sm@tF&2h3jK)?Y3%WgL zoy-`{bIW?oo-ro(KJuB5f(yb8Hw!PmAWe<)%jGN8X(hL{`+e7Tg!-sasR*y-c`lM$ z5)`GubbvRdb!r5H69}_uT8Yxk$TY_YlIMNz7*q2g)GQnwT6;AYq)LSFJR#Z8tDokL zHl<yug1{(*{LCX3vioP+K?olvfNIOr@R-QIV1EfhBorb{Iz%QJ1g;cfw%HJ6v=DPq z5Vcqchs6*}t%g|ZAjDx8ATGHKan&P;Cq9Pw+_w;a_ygiU|3M&tm3RP~0sA2kFpz-^ zAmC}|Z5@0-Ai!E%`4|G2B7)&vQcP-L>YB5`ROo(2hYbV}K}-OE00KS;0dQazKmY`) z1Tzqu&_f`Fc7W@CS`678OKNC!gzKKQWKXyI0OexmlZ;9$;OTKB>A+eGDD>o3r&Xio zs9A+J*W2iYY6&v|9o~Qe&&S`xT5P~({DAe4A6PxEj|cD{v1{8PC`f5>TfPMDht)t5 zVjQ<)0*f(%F)YR+Kr!XUV38%#(GoFCV9BXP@CX|qF>0Y+s>RzELz~_MdQOx907i@! z92g+EK-?c`7w)tdK-JJg1`EL83~K@OAg~VCM!-}K!s)G#2l$*8?lh!3!vT&9A%KGt z+WxUSZaDAysO!_F43n{D*dz3WHm}a>^3)_*^puDaS)$9*GEtG8%9zSHo5;o15*v!Y zq_cPnBdG=Dge1%d1W-T#`07(2^DIcd01_{P_)8%EG6=i^qOXMT>mc$v2)_ZsZ-U`B z1N&A8zYRj~fZ)4e_+7w!5MtjH^pA#H00k5PwdAPMvV^j=PR*8$;kui6jfJHZCsjX3 z_*PLc)Ebg&T|zRgt4K;98Mc+6?Xn3B2|I)dCV}9jZdP)E6DG7$wTm(@SWeJ#FhnfZ zX{#<@^6VnDV!lJYAU7c$>BFPaqS3O7uOE)wl*-7gxYF{7vXqppFmaxwPznkQFqzX# zH#9k&mgYD(N_K2XSZQJ^?h0E!K5-eDK$AM4X@^5G?c{gBxVc{G&P@76EG|^BRo$wx z+KEPav6?e!8RBp}`36Hvxmr!m%A$jBm#kHc0lNL|7J%=Fwdu#)EL(#y2|)23#H!*= zvrGdwJB0qzgNqq}>2gIB&}#u`;RCQ!fZYM_Q@55Mz+SvZHJLaR4DhgJ<B$M^5GGL$ zB`unjTOR~~R>6Rl)-^nIuT!F--$9zJRX}_casDR###*<8ZtgZ@>yCtFcBMW-2`PZ; zKQ=(9vDPBk7q@TtdXK|=DFp54LRW;YbK%h!zm%z>S7V+|ue_7Uy#D@AzwM|tb_lJZ zD;>M?<SQk0ulGfro<Mx;$Xg%$vg4oj?f7`+lczs{Pj-M`wZc*ZA2&Xp{`fM$FTY*# zf@<KG&uBQ@!d`#>xC}4?zUu3sC;&jm0d@%&AySlRF=8Ed#8Jl_cfv`hWXh5)N3J{) zQff~;^~`fG40_dT>d@*nFkl!pYWKO-zOdDoPWuYwYj=I)b>9ji7=aKIOe8ePfNi$h zVW(Yo+ap1uB*{{UrAqULH@)R;?|9dH-e+Rg%)+XLja|RR{O~7$Kwk2l@BQFMKiO-a z{SG*2rciO>r5pB(-<)yQIe$3sf_w!E$^7Xr|G4MA2mW)(We+`4p^}EyZ2ucY;1@oo zRH{iWHaz4D2w){12%+)t9a;fqOwR+HDIcvsAwUOOWAjCqwSjy<8_@mQWbk*iMU6Yq zHZ?wqb};8mY8T<z1+uLGpuN__5&$=Yd;>uHJ7C!Z0ov~ZKm*U!fV`R_JVMki!t~J( zQ}lR52srLhA*tsuBkE>vyc{!K<RutNSzWAy!R`6L)6J>POsYZZSpnGksQ#>LL}1P} zs(K#kcb}j6y^j+WF=Mqui(<+el*(BB2v@-i+b_{#nM)y0G`@UAI$&*rP&K-BwtQzH z&TH711MA$x)IX2-lWKU<I&~sHMV&a9iaedho<pa82J9R7o=@D3Ds_I)3yV>uyCb8j zT`i|CDduK!8=T!|#a8~H&+pQiR(7vWZj(YYy`$5IoVfk;E(M$1ssQz=_ZW$&z_2#N zx=~S8b8??yls^zUHZ`EUI~&xZ3D`6y)F@do78NU{&`c&kLtD|K;XW#!NRx%md^iNP zHO>hp<^e_q6N_)<(5z9RI3G&isV8`vsWGFRelp=Ra%_>FCTGFw<X$lHvDIXYG_ZkW z;z>os@WaFvwGIM#Gw+^)Q5*?XhN+gP`;DMCnMH2t5(%<NVLKg~nzl2O^k|-xn>4Rc zg^Ao8CCjGhS)^h5Y<@1XcIPxS)5vaEq=HT8*`MrZy>>OS?kIIEDh)Gq;M#5ZdZcBX zr>Oh0YN5s4jj<h|kI(r*y#Ikd)Q;k4Uy@k7u%LPFamzxMZLlOCq#|5!?BXyT`<^C_ z@BOQIfCM%koe*h_ZpT+duq?vZCvzmekbQ;I#SPEV>`Ju<CvVPS%hZf}gtd8^;Vsm& z@X^q&3s|{69{3Zy;V}QZy#^4f4a<jJaGW<={XqJr;E~<e8jD_gRe;F{L_?zQewl;r z)P!5FVACaM*1llXdCOT>d4fe#o4eXz>h*=-{{UJe487|bv&k6`ie@Aw6%gsIp@z<Z z#+1^T^0<<j2}wBNO{7(tQyNLDd{dN5!N3UMP$&<b9T*z8`2A4hSTjVd`r>Dabr3oT ze1OHFqYsF0-rhJ$zB<ZWqNVUBx!=i_#4DFC?{uB($Bf^<?-G~NVr!$$om&%=di<y1 zGPm!+{Oa2s9o4rU*$$kAagl)a!}Qy{S4CFU^km{JIYL4PgAL}~J8t-Kc)!uQ2YJdk z{9{q4!i(3pKiO43Zp)VX@lSSbm)IVQ5F1yi1`d{w3hwoMaUkOTKI_lpXRW?}f2W&n zeeXw@UcD-UqeJhAyxAXoxkz^NtwZ{RC%0Gs%AFjn7w)>b=!;%|Qi?#oo3CPWF)8ek zoSBZ%2kql7PGdLFjNG=SZ@${!5cTNBvM0?eu8G^J2upz1cc}di7G%l4)pTK}+tGey zt$EDh{RaM-O>X<1cKc=Ge()^6pZ?7+_l<Z;o!+tK`dem5YQysEMe8=j9In**s`vQ8 zbKNt%BLNn}iG7}r@WrP^ww(_a<tHy{cYdl|SU7m%9l66A+nc{)?IXVB#EG%y?e`}v z84>;ZO83_7*ZM5<Ugv?9nFNJ=AY216RR1i?-2DEE{o!w(bwdU*RRb|3KK$8R&i6fW z_Z8?6L+$LqgC#%gUK@C(QhK7(vi#t?C*bHgAhMx5dp1Vn!x#RryZlq#$BMy?rVYt- zxbSr7^vdnq|7N*k^gmwu+7l0bdEekqe%r4&*|Raeb1=AX*ZTi}o2|Fd;fLD$Ua`M# zoArjC%o|V6b|V|LlJ%118%LIEl>caE_}}>P?l-5d``&YPWr7(N><4Mzh(ouX>6o*3 z>3VONJDE%6zS^|>>w!1-H9ju=9=y*}RXs83f4}{kM-7g;@2%v%`^~Szn~r^z{^B_K z2Ip}+XRCFQc-)>d3<BmaLiTN0xaT31-*EC+`lA!ac9z%w)MYkTyI}D{boi_~ce&kF zkzmp2Q)?z$aMR}Jz=b`Hz3x}UgNf3*nZfDAvM;7=K1#v|=?mjFAHUt3TNPcNs*TRd zRp|=P1P>g)(5ui#D^km%b8~0uVEijNxJqB4D%0cAvMSXvyUHsmtk9`i{Y~fgB~}$U zBMhB>k2+8<N@^kEl#dVK_pNiP-H#*6FAhM{l}}tTAq+&b@Y{@REHQ#bB3te3h{=$( zdWAfltwr8@-xoyt#lnqOBB!ez8rt0LE+5a_)wTQ=;8cm09%K|zu1y_sjimfkU7)tJ z@Y`=QLel?FHh&`fz-JYzD(S%=$n-hr9Hwm@i~FxQlKt;L+3-DoqU6H-7+bH18pb-0 z+!X!kc^BY_0VS*05feVyl3JsmwqoBLl@o(50R(^+P9JT~QyFCp5z%n1gG&|ME^StN z=}fg$yeYKRlxP&}DGYf7DJ`9C>az!+7K{)Y5Cag@w_23Mf;MXX7sWv+AeMYHa)_RL zU9)Cw!-yyXZ9c&gF1;$Mq_Q~{qS~jQc0d=Nd088(ln9cg5Vd6`N{%&Ih$C36RQgmR z(3bY*56RI!{d;10=Ksvg^j*2;B;`GCb;Agv0Y+8d7JHI9pEY7luM4ebx&(!Hw@Fdq z**0O}*#>dpnF9fYcQ@f6LW%~G74%9fl{yqKS!z#iR?a$~c!`u`Q4A!VTHr~C(iI(# zRgv;!M1gd7rz(#E#i`K!B$oA39ZFm@GJJdUv^5^7KG~eL9%H0UmmLeFEt|E($~C4f zq*`OfkybW@AcEHH-@oQl(I%F>PJIJyI$ISf6gZ!(Ke8!qQ^h}dh>8sCSDm#*TKp(Z z1$U~PN8%J25efS*J$mDO0KBbi8!8ORLwre{{8qR|_{+=Ev*bGbUlBlhf#nYPIqX=I zXgL4#ds8nku~4>KB)FyeW~g%(qKpf*Ml^H2@~}3~Trr83m?r)L)pdY^%<p$nAE-$4 zD6J$J(Gyo{O+YYA|MQfh(tMs&Sa^;>TzFp|2q4fF%kS}QXa72Aiaot?-Rc|b8|xeE z8y9Rut!k(rqK#RZv8F=Me7ATNw4emE8qkUWsv0P3v^uy?gg;@5e1cD&s-aKEr0zb( zH&MiGQMjmEaWE%VDh=jif-o$p6Wj{duveF95FfZsQglh4hQ?6c4^i3=QQ8kt&<(NF zekj#SNY>avo|SIdQE0NBWk1w5il6}<04WXB00cGA1dvrgS);{mt4*@Hl=eeKTHm4( zN0VpsZj^<mZj@`zjdC4!qwEYf%C+f6*^C=~)3PyhAlPAhI+$vPr%%<YR?S27>5B&c z-P6hGsVCEiP|kn2FubHrcml4`FRN!Tu=G0F{l@BmFK0!KsQ^&}TTC^>)2C`xiwM!D zFBbn@91p@t<HlQ19+Y+Q0an(Hb2!{MhuV#Eux^~g>Bboi2y#Aowm}6gC;_bov?742 z2Fe<(4s-;Kj^es|mjXQk<0==$V|jYx(K8L!DCmc<e;w0ukh?a~z5c@(9;QWT^h=>t zn~nbv;G;y(>;7Np_MgIyAI#2vyuWVY<S&G__4oeQOTR=h0N@IsQ{x}G^~FA15H~=O z*(RwpK$y)Bg#=_AvFgGugVOq9)Yafb5X@92Rc}C;g?G4%d8a1mLNslYejJZOHQCpi z356L_=HG400M0@-1XTvfpEQ%=c-wRY2O1*jwn?2ZQ+{n94v2j+g|pyT*n4J)K=RC$ z!7!j9l4dXrVoi)N=!?m;1>$IHA~>GVR}(5oPh0j8W)xzpk&|R32oaFQaEmu&l{B)1 zP!~S$ZMXs)isG!=KivX)s7^Q-ram&F^f?unJu#dGAJAnCT{F-}QKvm{1?3W|X+SuK zbpdDIA2VmKoFP|Qz~cn7U<Z1uDrDCxaRnF<!>Y+i1)8ILi-s^0z1@eK0}H#0u2FOv zrk2J@h2{v)+!%~Lh|<?3c_W07Pqr>R&MhHQEERiUFEdye3{Ec)g|LlcS%Ni@GAk}u zo111ln}yOMEgEJ9xg|u(aKrYQf+50b5X-ovRfa8F)2>A&L=;tEp_vFY5v3-JnE@2t z6()$3kV0zsa8`)=t2hWwHOZlWt%m3qbQ`pIxq5H~vWtu;iO0FWmRxOyZwZlV#90|S zO|+ksy+j4rXJT*1<1`bgD2T0J*k=mnBEsDo#gJf!;4&+GZxE+!h=qLm{3y_wMwev2 z;Io+JPvFau0!09V2gL5*1A+bj|MmbK6Ssbw{NSJ1P#0RE9onx$`dp_p9b<TtA~tfO zl&9yl@%m#pqH!R`qa5dhAJYyS?Q9RLFxu?aX-n-ji(1mMCiY}6aO`NY;f@N>u)%|6 z2xBh};3zzv@#23sy3>0-<YABcm}l5Q^UWHzu$wFSCin3pP82P<M`DuLB#%p;lsqGO zQL-IhhU@XQ_@e|t$cZJyO2SM$O8h6WiSQ61B0{`F93m!&3UPt_E%|@sbL7k9TV#UF zkdtJEyhye_mr}QqRUozMWRpkBv|UGaMUPa9-$z$0i!E^^F3002<*g~s!c=8l+OsED z=0G0FtNAp`S+7^^6<O(3Tyx4;T=mtx`m)Z{l}7I!(djL3O&fZC_x9@EHM<2#0*PSx z_R(ba?XQ08jF1^JGbA}AKV)|2>_T8Hc62!6g*j*hhd!*s0bIs2e1hM&@#4%UD`}*Q z{T$#6{wdd6jdoq75~V(!(!0Tw;2%5-A<PWF;mv4rG)A9jL-Zu(#sBzZd?T5f{E}74 z;p9%zuaELn=!&5s4HF=Rg@C~A7{J;$-Ux-B9Rp}H<<)i)K_6Zkuv`f#EDQ-7^aS-6 z?s5PIYb67tbtV!PjhBsr#~zh|wytb7(x8zF1*g+X%ZfB(mum#E0|rr|xX6){3uxKg zTa6Z2ARIRego*hWAb=Pe)nJH0G(Xb|raDqdbh#*kphm&d8xXP4>WAh$4ve^8<GeH= zYOMnvUeNlOd!%wKCdWsmIYrH)9+Wv(Ur|jT8eUra{lypKcqfjVSFKvnS>P`*^WTr3 zrPZ#%!4k)nVzIaPyqig6--*ZbdFSG(g(MG^AAVH>^Zt&CFHWNvfI81;Itv(B&_I-{ zvZoxBKXRtYw`ONs7r(7^t0|Nq(dJbV7I6Q&NmL;}G?uil@cd-y+SRMX;(PJm);V)! z;`{2uk)feK@5Z!u-b0q>tTbR-I=aI(Y@r(Io!yGXI$e3FQaN$HC6%_-74kgJ3~^%b zc4wpLTln9#2L4M8N+5N0b}7Gli}>onlb{z84c^Pd$kxzdZj#INXGI_Zd02FjH4kil zB4xfrGBS~Ad>r>PsB@-?AIP}WMs+E04$K{IK`N0KAu~X8bOWw9&4`*hoFd5?;^a<E zAVm~c!u0fS#o%kKm)Nij+=S%GPJC=C5L=R=R47wgwh~s{df>XONYHf=q;Zl~zqyC@ zbUA}G)$A?FkZd633NX^SP`gDX%q>#8H=%;y78*wBUe3fxk3HeL15`$cjjE-Ag1kuW z=#z*?!&xve06X?HP6<0g`%<@QkSnD^lK|SKcJ#8o)EJalS4{bO>Oz!(f^1Vrxdbfg zhzxnQ7#X&Mo-#0Z{(>xj2SSc_IiA;Gh!?OH2wqCsy@cFL8buE{3j|Y?B;GOy`R8b( z)zJG%BE2;SRQ3avY?K;-jt?S`3`=VEzV_8ZfD6v+keXGf-E&F{8ei59Db$Bp>f#oZ zhYYeID;?nOK28VaHgy!tf*H0b4;j=WI}@Vqu%tcS4%LvmB(Bz1?twfqAfWaHj;WZF z`3%I0zs=Rd0L}2Z7o^l~*RYA2@FOZ-U_XcfPlZ&~j`*=!rWFVz+-_1EJz`Vb#*yC6 zRyI1xKK&*N9Hrzr$PC!j20Iia+~#02;>Xm`iW)>IBwY&Y(L|_|8`M9B3>qghXbBWR zTzRPypb3R6S3s#e*M=e}N<&&f>lv0H+zP!9=;Nee@--Ripc0faaJJ-OH6$NmqwR9U zq8qrR?R0M>L_?w^heP@)f%X8ZzsIa-FpmOCkNr4U<I>nbcEpU+7L7SKh%sj9>2lBZ zHLV&Lqb~RfI11OFO=PEPSLUkxEmBu&Q`v;$&hlxs>w_k9qPp(64{Hl;Mko~qX(v1w zDTOQlJWRTF1r!z>qHxaqyKXr9Qj>MTdb#Q~63kv2pvB$O1-q2f-D28`L(sHkDFj-Y zfV`BD3;EQig-~@BBlHypxp>Kwr|Zxe>}i|Z3HvW`zI|bt{MZj0E`h(nXOYuG*)TV~ zua<-BZAv>x1%$7zhuM3s7y;a;RKcD1kV`{SBE5|mtyc?j83aba0+%FG8u~Fr7V*9b zost2EMRi0+qoTvQ^|0WE^$2CSUwWuoi{<+Rv^#@g7}}ndZ*h@G{S2Y=ip04_=y?z? z-Z?kjsl9K5Nzl{DQ**T&<lrGJmN|<BgVqavi9;}3x$V76CzItCn@w7p1(SLqZ-n&W zM=<ny+pd3=cyW!L2fwei=$2`vvwvFirW@lW&pNb64}OTqIk+8`OlG5Ol#Fy-Wg9U{ zM?)rq=rzfW<nwMCMpm2ycNwCG5CK=DMO2!LHX1-n9#vc}+d0f3)prG^QfkeOHq#|@ zaq_G~O(RX9t2_&&H2B6~n2P%{vI^GuRI*W>+~mqs&H|sSYPJlYCITn1usTHEC<c?g z$1XRBoGVZ%Ib2n_Lg`ebR-{{$ddUy<q2`*Dfk)A=v)KH#k3!`^iZ<@p`>~+JG46uO zJ}KhD*VTO{yG4Z*I}Q2b?r5j5Yu7Ofn^!Ta9gMbe&OA7Qt$G@V;Y#`GRoKKJZR?y= zxBih~$3I%?%1*c0oSxZ`SQs)k6MQ+F3YxXRFePdB!GS555o|?_VInaGf~OH6i$$0T zvSjh4W%#*4(+<8GY49Ar%m_ZRb64_@5re$N9BE~2VbMcFzATF%zojW5$v(|Me1!b7 zAzN&SN7YLJ_A`p`NsWi{;tUrc>++}p2p1qSU{Gibsny3-YT3`0o<AYVdDpq(p?Ea9 z$7GiU7A%iOd0s(O>GXvi+-E!eCb!w`*5-x377CCr%o;Ow1y4>@s^86c^7RX+D~D>> zV>891RT}I`Z<QBpl*1mP>>-dIk(Bq;p|gNEi=<LUvzD5$DPQTcZzwh0q=c=o;7(CN z>^TySSDrVSTsHZ?RofLX%4uQQ%5XG0ElRKzW)0P>!r$}nbn5vM4<?zf*8Q%A|6W72 zm?TFq_-mN?)TJ&pK*2IQBFCFAO3zIgBKHM5pG*nd)2L)Y9hu!3n79Y219~vwGQjp> zv~L(XISTt=KRXw!8X`oNts-z7F8wGwwj&e>JZJKpTF<eLi>p{J^Qvt9zb(4(@NJLT zjn-S|DqG^^M8fDS3d6s9H(kf2yFKXenTr~G?V}pT<|KQh{%AJQCROO-mvy6==7Nl- zcd1?<c~iD7D+)6%p}11m&H=LARhNu?&6*etvX2;D_Fy+v0ztmk&4`|5!z?3fJ)THf zr&7(|>Tg%xBBNyUWioKh*kdx(NEMsaQr?RsPZA=qrA)*tT}qfdxed#LH9;cs=xId9 zoOXK~88A4I`%*Xzsm^+t<Yf!ssFhvPF<j}Y`}is<7;Dp|!6l~0J}d(h_afyT^kA|( zZ(n2nwmzFElEQi_FjhiEFOhbxFezjHHoHYQCdcV9;d2BVYiyh_>tvi#LD_CpxubS= zDl2u?JNq_W03>t_rIFZ1@f(u_bIZS=qWGC0r>Vm;%J12{GIsGIrC;9eh4Sw|;h+R~ zrq2jLn5Oq$g`C@-`h8s5H|y#dcm1?m27{Bn3}4n`EDnQHg%P!8n*0r6q5kDJT59PT zuw4qHl=v97K6idn1IM2AfUVUgndfvy&KSv)k6r@t-aK-(lG9pGT;L{-6?3?&|7<o} zxTK-F6!0kx_<-iwwxVzOrNVeN)&F>Ydh*;f=z1BE@ZSv(VV<@{>lwz2h>n^C)`{5) zOpHq(FvD&t*;hNFAB((LI{no(B<8dvU<xr|bRG*#l?@`uCOIJjO46xY<<y}uX{vmj zLNiDkf_fsQQjrrC&N|1cx(!omMJHbN4UWk=9piom;<>=0C~O&QiwBn_LC{T_1hh-- zNvuX;B{-kV4g4G_<MJ59%lL`pLE3QEg-XjyHKi(=6^%!f@}zjVg>rZb2{?*txJ0sU zfT`k!#$0d(%LFCFD#yhw?FxIGDvI}~3e6-0;I+LPa`)~d$rnxDSFvSBWTO4i$9KOO zJ^01(ib&<}-3RI7{iLBs9;;p|s~=Bzjkej5mvvu0zTf0_yS*Tf9@!1Wf_HVTlif3r z(jJpdqGIzIhKWR|XRh!&H&3JP;w|4Io)N2LA`eE)qbLUsENpImp=lf<#|w?i3G-R# zU^_=SMvjU6YYmbLn;79e-k5IrIg@|o)6A!}n-<Uzo;Gg9E`5^z<nn5h1BYFtiRJJI zg89)3I8KS<?88BL1Xsa9iQUiLru!cpB2c;6&}^Rnw&7X9-@uk=7vU6dQFH^LDBOe1 zUgEd|CR4DvVM`(drM%&wWiJ%ba2S_oH5AK^AV@#XaUfE(pA?^$5dye!6qAZ~Dhn>e z(Bi|Cy3)@&OR=fxg8Sg13LBRN^*JmX2<&2q*kMQJ)r`LL$sIw+7Z{kMJTEMa>vQyO z#L_1RRs=H)%#GC7Q6jO9@|F@`a<#m*iGTooqKr+FS~eF!n)(Q8E0CF^x!kuN^gM^T zA##apEoA3Q81w};CZ6C&4PqvLz?qgvBN_O)ASq#BXpPG?Qmz0+1t}9zny{QGGoX=y zlO6=4W{$yPNnv@Ge5U5%mk2g&q&_74)`Qf?#URfxR?@6O0uaSv`sqOB89>qBhSZ>4 znrp+Ei0=zW9Re{X6P%&g4hhE>az~E`hc$dFXhkt<<|slW6h-M?MGOP$SV)a1l?xIR zac)Ma+))qONjse=h^!+dm4%R?hx=2BW<B=-v$nc>Uzsu64(>}|p$DMN75Ca^%>A}6 z_pC6fTEj!7{yv#Q{c6b(3h9KCG)2I)00H<3dx$3U<vP&9evwC%zmaBNwfBg%astD! zdwaZ(j37=qA8^9N8xmlaIA~x@M9EK5g`?Z1jgXjMHX|ir2>-y#^PV?@oMIvc_)mo1 zLDWFT7qD4FSs9|$;4WA{Y*ho`3MK8zWCdNtr7VVQ+GzJuWPIeXtP!_i<f4@OLJZIk zTg|<`uJGAkzxm?8-Z%TnKMRFV^G(n5#{S7oN!L6sRVgN2p4>sZJ25^uQkc%q->+eE zmX5AFGzw{pU*d*TxpuV6rA{A>h`dsMuBg!bl7K%Gsk8qqbEQv|wH3c?w>$z{d52M0 zFkg-=y^lE0^9+9>O_SKy?3aF_CEj1-wrfRuzK!UflEdd*$Esh6T_viP-te@I%aqj6 zE%Lx47eY}gwCAyI0^Xrer;_Opck-qP!RSbMZmh;DKEFGUg(ERGOy3D=IKmOI7Hrke zRt2}cw6loc^Q(?_4-Oul!?%30P?+=&`1tr~?3VlVK)T&%z3{ThW}Dp91jc6&X}ep@ zU*ImEJvZ&q+`5;<#gxSougASGahWjRIkIS$OWa`V^4`biQPiT5VfgX)6F~L4k&?y? zEE)JI-j&wF9I01C$>99&E_rmJl;U~DfjnU|Py&KHE;C{RfC3VEr=mci2}(9ND3OBZ z!jEVoz;W&BK_o3M>(QI6!YSvZqpqK<FHmA{a<6<ujKOFM$j5`WuQ_PBY*H_BciAHd z@<&Y;!tidDyzKHi+4`=<x307rt!Y8x#`IF!GY<%aC{){QPy5oY7<=zJzCjRryaDzl zJkw&!O&x1?t-)~!3KzSf9X^mu#y<kO#)=zTwJyHv7=9J#s<a<ef<Z0T?!hDk%$w-O zZkh*##3OE3YOBf02iRH~_FUJpb$Q-R9Mm@CZR8y!!cS>M=0K6*dO0fDk>$X1ns@mV zEU%o5ez~tA?;#1~1I%BgtqQ19t?Ly(_eNwDLcs*lxA_`7Mmj8RHzx0x5%-&%dQ{Kq zjl9-)c0laG&K0M=5xX(*H&exP9#lKfg&3FqS$Ut=p6&TT@l1!@8%n)`sK$Kqp%yVl zp;%Lml?kCjiXllX)hZNZGk1SZ6VeqXp}klS%_5_~Y#1seKyzXoGRNi!dIVLw0Hl(X z-B`Cp<Bnqff|rZ(DPeKKqM=nWxb+BWi|r=mxf(^iHnS77B9z*$jwLh~n`ssqt(NT= zr45ASV6HqDkFoU6C~=ibhZ&Tt^;~q+Ow-lO32~l77`Z5Fu4O`sAVs9{pt@F5E97Lg zjI`aONm{6f5^@DN+yzUw@UDw2$iZ#OtBepla#ydP&;K<Bk>UpZ{go{Ay_kS`je?gA z7r`W7@ceZBoKKIKj3p{{#ZxGoJJf1P4ZlRKzR#S<Fb$~Cq7+?;Wv1t2kGIL;MM9#g zktSFe!f^N9OUT@Jl-l5v`Uqx%Bkb$1hDLz4=+>*R6#rQR^Kq&Xx3MJNb@PE97q=b? ziX|>z5@RCXnPB5i=QK%PKuw%ND|wjc)I%PR7D)F5P(>UAcfpBin&+nc0xW?g!>gYD zqjeN{*LFs>vqK}J??bG#*=#AbUV@u#%2{VDSF630GGC4ylPR{{!ErPR2W7HbieR-G zbSJ{&z!2X|KFlj}eeYT;v`aw`KX`8p_H1mR=W?a$xpUmKJT|dotbFQZ;b{78KSayT zTJ4max;}Y7>VGR1yP$LZ@FCqQ^<L?wuCDK|{)wqsS6mXej0Vs2|9?|E2hUwIx6Waa zRo={pAC{}t#aSB7@+DfDf3|x1;tia*EKGn8o?Ri~_{pf*oXPqvaZU6jo=gVUTIa~x z%--8Vq;(NY#*B8@)O%lfJ^b2h;b4Gv*DO80KQg-aFR!q>b^>j`awpczsJE%aIWLaQ zX1%jYg?kajn*E7?OirF@b&6m3@%vxw-SR49vW+9y@ys!fyVda6m8s?X#|$ctkFV}+ z#UT!7&rkIh;Q9w3Z2bwjygzMnFfB#Ez|7QD-hDsP=}L2+(;2>NSP<bAhQCaCzpRTC zUQzvD8PC5QHrFg%>i>b6uGYG0jMfKh@`eLgn7+u#xv)z+cF^^3`wk5{`1M(pZLaYu z?FFG#AU(Ki_Ca@(Gmj*R4Bh6(uu{8JrBvOnQUOh(ya;Vu$?-CCW*)X_+cr|~Ep79l zy~m0&y7+OyE9J3M&MJnXNHTpNl_`s)dc*w&1JK0FBOh1^>hzUXX7|}zYH12YHr;uH z<5ziq8Gx?wLcO~B^I{%No7`@b)bNA*j9NlhNXvjGRbEPkm1xC!u0BOi@2%O~!U?)U zwVn2~2hZ00VFIfz4{^EV;G4<ieKWhgN;8k8xf+Tx+*Fjp!|<cazv0upuOG<eCqMsu z^6;U=WxiVc`b04|{#EI^;nsd@uvp*!6Z(3&^=a0@#n_gr8f%S;tYnw~DMig$xWZt# zM`;!RB&qyf?F$2F0_8<juz_t=8{QijdN-3DKYDch;8^V2MtS1P;zZ`~7x^`Uw$AG8 zd=p$%A908cb|+{E@Ug14x|^zXwJa-=D->OKtg<KzHFg~gldBy283vl5&dwLqWTzH~ zm9RW@Y0YJ?ps@5@wO1s$MyNa@m3@cvB+#|!o;%Z#@zO293!Mg?mq;e#kx1O<W0*DW zPT{YGt>O0qZD~O%p7&5G;!4L7GfaI;E6`aQrLj!*3NmM$tM&**&BCnLO>0j+m_=dB zdRa1)NyTERP$(FD;l6!NzqiEDOH+q(V5M|Nzj1S)u9KTDW5L%8o-qs4Vc!U=M!N1U zb1iv8r$MK-MlVIv49C%tRs}&w4fikA0ZrV35%%g&ex>4WtF&$-)PW{_nbWd+cRidn zCAiXH#xrIi0A7ZPE*Rkz&OGMl0S*iyLNga_s;6n4POnh!m2cr8cH(0Tj{4=aof#}$ zK#w2BzmCKhW>_K&O;rk;{J!#vX_}&_xm*!2csI$s$MBiO$STh_2$>$rA0o`WLjfMm z)6C2oH`gyG_cl-d%#05)Hr)Xai>y|YcQ;Jla|C%w)?+BlYIfvIbKs5_!Zf8};W5~- z{Kc;Jy2`b_6-Q6v(N$yHt&Y@^fYtgb5?RPNtGTc%^juq6IFipd|2g?dGy><V;ziU0 zGD!7X3@Yw)c?Z1(_<B8c9?YQ$NT=JI8{p@}2%Kmzu$O!IIsl@~!<*Z=9T#kLb3IgN zHhxMceYRE8Ik!vwn4+BM6kpKI=Wf1D(E`-*&&NQ70fHiJNUCfSzyl_;v=bKtv{r+` zN?y$Mi)yZ?Xg4faB?Uml^LbONA<(8r*jt!3G0)HV+CH25uRL}VDqi?47?}6_3mFE` z@qFLY0`EbrFi<NX?-OANf+8rwV<s3TKoGgN4-^I604%Lu?e}G#e<OJnTMcg&@=#Ed z_LggfPQyxXdruEZmdW$Y8IR3<&t5H5ilox&5+B(Ti{0|HV#S)#1&^;?Tl-@4Y-0uN z^jyK|G?~nGdRpzgT6E%*7=I8z${)OFtD9dJEd576Z3Y1R^u2Ncz|S`ITh~73J&NW4 zpoIqj0{$C#-?k&7G=5`s;o-}WlqKuX?3`fvs<g7IAO-@2@cF!Vj5E@;NXtUAYl5Sz zsxnoolO&9wg4%C(tDq6woRlFu$tp{jItxPpCDkbh4Y0qwal}q+0f(761_cMr>{N1Z ze><$81qHIIjSB^Q!3m{wB-gZZ7_sAh5bc}7FkuJBOnF*|3<=q(CT3NI*jyzZ1E%Gn z+1tU_*}&2_!8#q0pqU;l)6ET??dy7?2kS%u18oRGH^$JV8({CVLUy7CgI`_D0I(U2 zsFMOzka=20=6JpCq!22%LBn4!TPKumd{Kiuq)|u}STj%n3NmH|NI?Ul;Dmm#-?+cE zKz6o7Q2$rS;>&dyQOePiNxUmOo0={OW{T_}uVgX=VVGv6GD?zbBx-_>L>(#DWniwI z4(2eia8~Fp8kM_WJp`zQbpl|GJ7!$I1_ZFiw|qc(JOIxFl>owzRRJDBYzg=vb}-<} zRPO}FkmZ-aSf(cSMnPl*KOG8&04)dz@YBLT2z)IIOhlM<=A<A!n3ycW2uvYBrvuXv z<a%HRd_50@G9hoRE(||?jhr2;je}Ve6AmVg_*ojGErYSvQZ^hT2aKA7T{9y?Pi_$x zjw$6kIALPF(j2yw&XbZeP0Y5HT^b}auxpXhlWyUp*F0iw+_-cl<NLF_Sk-e#|MtaF z<&vnRQAR`3QzGfJpzYMQ=9aXRSs&8|^N;HOJWL{1FH<V9EJk7t<9Ougr;L*!(KL%I zSjodOR>>KeO`(I!6(dzKrfzB6*a((6OC+t}#&lROY2~l`mHi-?Vdl~jNzig}oShZ( a>R<&ojzfLj!bjy9SorX8pX%Ty0002573QS? diff --git a/.next/static/media/b1db3e28af9ef94a-s.woff2 b/.next/static/media/b1db3e28af9ef94a-s.woff2 deleted file mode 100644 index 75c4362e5a9ece4377f9b91e3b4ad0b967d1d5bc..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8652 zcmV;-Av4~0Pew8T0RR9103pl(5&!@I07u*a03l-l0RR9100000000000000000000 z0000Qfg~G?E*vU9NLE2of^i05KT}jeRDn1Ef;ca15eN#YXrxgKf)W5Qz+?e70we>3 zAOs)<g<J<98~Z{d5y8d*K!SA~kp0y`HipVSs%02UP&G_-OC4Kljtazc!(H+nXN0#b zAN_J(dLmJ~Pz|c7Z9L)#NoL{y`~Rt~ec?%wNpgtDR0P(w3j_fwd=aoy0CYReI|sy^ zH47V9mQAw87*|8=R#9ohii#R-stZ9yr44F~B*qqFOo)k!iZz<35IE&h+H%U-)KW_| z=jB@J<t*1y8!e|?%2`yZyycXuRC!B1%u%J5Dh)*H-KWijhhEVN4A@4{T;%R1$sPY+ zD88aX$%GS9Ru(dgb2d9C9UFajWr-d7!p4sLjX)>ZmYb_POExB3nW5x=fKgz0rL#(> zH6x!42eOaA`}JCQqWFEj2cVQglw|2-?O69-2()nIebDZc_x#}Xp-vC}-KTw|3;?wB zM4SRfL>XX^04C9=F$H<@5L480kc$3>M-|=9a)<v7UFAX4YnhAJ*v3T`5x+?Ai)@B% zZ7PJP5%gOgj72@_MFnMiKLUP`a()6SKg)c6zNP#|mh+oh&2LY`@2r_Wke)x<F8%ZX zq;n`^0sR2u26_`W0g8a&+}GcaB~xh(f_W}hV_It`_6$*?4;rg&eN_#N-wlSXFdlNq zemk}T389`I01)6P;%KxSRJBX-8-fD8YcJ++sqgW_-fz}59}858DDui-`L9ucFfAOV zjG*^LmT4}En*=b1f#n{?Uqx{XgtTpV1Vjp<Qlkg~4K_Fp&pKpyVu4YP15t}yjMuTp zvKkRARAIDvmK<|O!X%o?Qwvrp6U8E%%-uk%h!YlJ_C>@Ia{7K_w9w9c{Z)_DuX%9_ zAy!h3<V>-biTc$jdYfV@k>`{XlbC6i*`#C?mZ?^2EsgcsZL!rhEOwx!p@neZw^L7r zUJ<>~^or??p;tn0EIo=|DLnzbDq3n<-($1co?Zhj=!sr4^Eef~2pFvwD~!=g62<}r zr68b)PYsLOT8F{;cnqfSWc)mxRpsy^yc93TYh@Z*CV)JBJkTHW0l6|UE)&gwGldkF z5@VPJoSIq%{8bU`9GQjeq8XbWqrfxje@_zx<2aA9DKWP>v^Lk&;uGidDm3P_g#ob& z;19fTApi%OnJ^$K7&t+}ke^bi+3~ojyhPu<NUi1I)S(C9tCO?j5FB6%%z|xUZ#b^> znyC24@u_zkia(UV-E2L0tWV)nh13y6L>1Adlz)o)1hBA7&;=~O#?t{P?-H7JiW&NV zAshnkzudV?+_=P&B~~m+Y6&ae#@7i1ZiDN8FwXoSujdY~%?DVKC!yE)y4HyN=t<l* z1(#{0wkDyb7X_PhcdqMuP(5ZjMlxnh2~)x_y~a%&$IN2ZMHZn^p0VbVB{Qvdbn9p^ zRp!#AYbdP+BYQ|lV7=S&EYz&7(X3LhU8w-HFiCbI6h>vofVWhE{}7*Va70hbg(0-| zt14ecThB|Y!6(*`+e`iHG(c&M>j&KekWmB}f<TBO4(I^~Mqr(AfX;vv!ZEwmfRG^c zKohH=R70y>2MYpFg(lGT>rR00DKYq|oqEd-?qT!TzDlECf2YYGXzw@J(=|iAg@(~& z0N7(7N$|9XSynu%5f5G?5*sJ4ik?%eKG49Rf9cyT2RW4`l1?uDb<mQbz5g5b$t^^q zVkIc!2}}ThW4`^C8L!rKIuq0rYsF@LC>zM58HZL}+F-1QM+=+<_$)%OSUyb(SZEZL zA}<;3WyPwEp;lt0u~wn1R%$H)jc2SwYw)b~CVIsruM*OlY=bEpO|_9oljm$wuG#Z8 zo1u+FyP39_Wvkh?k<y!Mhk16YU@+e<2vEjC^uVK-XAYX`bSZG0i5gS^B<fzy^O-CM z7M1GlQl`ENf1>_gx1&C=;9)e_>xURaX}<RfSxy50=K`n<uo(D8Al5>>68r=Jh&bzy znMYEci_a`R{BjGYE}URDI|bYm+(ILEL^E2(XzZv)p?4{UUIDEQ<uYc;5?r>NQW;B5 z{SWcRkHyFKSZ~~|Pd!;%5Tu}7Kem8QUM^4}@v^0xYGDZV;G0~Vk}DKGufoABJ0RT$ zEwJlyBePU;YB5|$`<&oH*R8JSoAT=HMjmbUl}++T%pz_7Uh|@|LsRzOQ0j6?%4C(p zq7*Jnl2ljZ6*{mxb~e+Lly0JpopT`qsk%O<DL^W-z&pB#J#lI-n+W&>MjM!L0s0_Q zY;kR^I*oRy?^BDU;j27)c?)sV-TEx&&%%?N<eJf7u^;Am2p7Lhl4@T*(ts7$(x=%h zUgIGy%k9eJi?w@5td-Rvi4A<=E-ut{sGaPzm!?G7cqd#N-`|+em{mI-e@uyb<6nLi z1bfxFF2AX>Ilr#6UV|eo{7ulgy$P~MHL}LIjo1jKx679m2%oB9FOGcsEw^;-`1V%Q zk?QoEj-hcKUo%*>+IoInYrK|dIu>JH1k#ufdzRDL!rw&H)@<8*`7DiSX{^JW?KI(y zTD)aTZ0f2+%Xap5<<bma?i?8fznp;`;L;+a_TBmPFq?)Mn3PW<I%UZqNmn_kC<Xc- zqtTI<o;un3U*?1Tn|&!XT3r6;^!I^<%-!H8kEdAyijV<=(f&%W{{D-2xZCnLqfYNr zo53>}*xcZhGePm)w{Pb-GsVhRTxS2T3Ln@q;fu3pMU?!Kc;97r(UB}5CiDHyxBh{e z@A+QF#&aP<p6Z%kxoPmHpHx)++O>55g<WyfoJd=4|LA8+d*UdVHas=qH{dL5*l#<w zZowzFxE@VVD+nf;2dVszC3s%pQFW<!clhB4TVKC+)Y7uz<MnSozd8T)QKyU4)8}Ij z*U6KA`SQq=)wio(cs<}8UT9eEo9Jmf;oqO7lObaJw(Xx+?{(eg+tT>4_Wkdh1l`4Z z3u@N!k4v?>`p!?gnCYW^lP~<K>CcCM+Gq4XE*w4GxNFzj#pxtq5dTr|&a0>Yt?`)a zZ(ek4DxP+4bQkURqeH!o;Y43kX~+q4eDrsW-`)6Q(yg0yDb(>}^_OS1kNmdD6&&bp zera%5^^IW9mbC}0r#pWAw(G6+S4+2SE~~z~XwuHVoc>iy1P&zO0Cy=Y-g~`V-nf3T z(pI~}3?m(?_~+@3Kc`ObM``HN-1O`4t;l6uy?*@b4>lBz9ox|D>yyWa_(_$B7uwIU zu<mR_XMBkNYyZA`uAFdWDrc5=YPmDmcKrh@8OS+?yC+WDZ|^?<{@0Vf{=u(~Xzr~$ z^>b*-6rtYgm%nQE^mQFrS<*e8ty}+gY+GEpzKD9^>Y6cTezUIJFm3mwgBXmr1jxKi zAR3BId(Gtha0S^;H9#kmIH5;Zi|1X18Amh^J+kI-yjRDD6(g(OkL-TTl0Xf4KjXf0 z`hscx+9}mDYo^Sd|FUM$Cxy<_pP3f#G-dJ3m!{00zgz>e0}x$y`?Bxccb88@U#{KN z+FHL0#0TB}h%T>ox@7LYnf2VauZG|1*x$5%Gd@U>?6Jt6{Z%-&KlZ`Jiz$A*!;987 zw71qbjDF=vVeEFHx!0ptK7k{1TpEt-zwyDjv;R(ef6<zT=4QE1tLq2Ze{FP{vZ>{J zo~`Ha{MV)SwJ&!mmSZscP&jJ3b;@_{yHlp<qFQZh>u?{gy|#N&v*{1b8`sUOo>@74 zp<;Gt=|+>YdE&A%#Z+b4wCQpMu$K(J-PSppL+)OWt~wuGY!Qxa0r`f+;5yPr+J1QS z<smPZw!uuLsIx6o_>})NQ@8!IkNUl<V>LZpvU%!CuG#b1p8e~$sudW_u@Wb%yZF~7 zp5eCc@anc_R+<lLr!N+4az9tTY>}|7bmf5_?YOGa>rCm?yM`BlU|VX_Yhz6T1b_l` zieYI*`?3r`QCF5=35(1!vd|(6-~>g#lNd<|2N_iGbc}{Qs$kLT2WB*}NH8AMB#98Z zC1r`|=vZw;K*|E!3^HbH$7Ic3TrkK4u!xX;>nEh2FiYYlLUt!cZF=oE$P)W)ATcf| z7y2|Uyf1hF0#Ftx=oKe_L2HyngfpbfPX{UUtB;iVB_(A(4QRA@!clh1!IFJCh-x7< z6z-Lt1sZ`d&5Uc<X~CLYTm@Db;!wDQ6&pUy?qsKn6dQAVaE&o1n>fMF!4Y;2PT&Pc z>0}VC-vK;yv{@m_*V&0tl|?4p2#UHHK(wuyET~wnJ$Q;N))fNbcl29g+YAoQ3C=YS zH5p$MVCB|_oRtk487*nSYuqrAvBDR3uq!~Ph@)h%_e5inSpXqusS4D%u$!!a1rkb9 zd0u)%#hL{i2lF5pYs%VZ1hxj-Nu58llDc5l0c@R*ghX8|%%yA{9wc?lrlhVl0ZLpy zb~kRVE`yFg=eA&~XtfuQk^YGmmgupUs*xD%*)Uqe;9k;dd@5}&(^5sYCbqlNhoxd1 zR0!q<6>rRt?P$x}&4EII#UlqE$o=qtJGbrc{rt;^SpdL>KtY5Tm!k%zSMUiGRPqHN z1rb)VszilrcU;#T3f6DfT}*&3_`E2_0RcYY!=)KnoG-{lO^jf(jNz+9qQYkqTn82) zG`OZYH=lr@rm+MVz?$mM^<o0f;t~pmCty{H3RfSlJBGUfcR_kq(UFwP(K%rb$XN7} zn3;76sl))~d;+U-XK|Niin)qZU|k%9Fx+Ke+ybVEl2Wi+bTq^i$3t7?sIG$bGxp7< zmnU!u>2d>%V8|@ysS*`7u~FxUNLuU}F9uYlWE+meW5|%<!=xE=kSEA_OjMv#ic&&F z(+H-^xdMDg?}QP+S$PCkDI|k2BEW&bgc38z6Xg5`P!UmJ0>^=vJOl^kQj#h<m7=MG zV}OVyhYb`FtC9mK=Mh+yi^N=-DdsAY#ZiEEoiER~rl<f1q#i~7KcF->7*JraxqtxS zK%=k%XdJ+38af@UT+15n=Xq{&pC<^eeiEx&Cp4fhby-m*_0-|6pPS|uxaCgc&iZ+N zv0vkx{7!H2NBl{D#`}E8-}b{n8hXR2;0YJQweWrTDMD<B^W%!RE_#I9@;W&s93f{G zN5-k<tmm|G_HcgB>E)c_csLh0*SIUV_1t!Dj62L7!3eArE63(zN=$?GU{35K><jD? zZwBvU-WR;DdH?1mc)#Eryab<&OK}Ch8gIl;;eY3k<xk<y<uBpa@|*du@elI<#gFh4 z{0zY*C_+pyL<@0}xRIZqKQF&3-<0nwpbGXC^cO@5Cl&S-zQ^Fh=zxGyKwvTr&?6kS z+kamQFxIr+=Hm#fKP{l#2nJE2R%j0qh@L;w0cf(CEC!irC>q*75S8V+bY&D6)9l~L zNR#&AuwHLwq(U<84b+Ed0EK?~=^{u_UBF1)l{7MnC5Fjz3i^-(4|t=hvet;yuSvlM zoHlS8SO~(B<=S@$h%yGix?_MuX-R=h`tcBvFn|Yn6QaHJ4nM%lz*A5O(1&Tk>C4ol zNPrU&CC+G2hG`=N5D0HVm1tA0ec4v~ppiAO|1BK!XVfUk?7An@l6f9c%)U_~Op!tR z?(SfGk@c_)t$84ciD)!aQY!-!#@+`S%E?3me(L-tboJVQ>~`gbBGJGAq*Ibx({ir; z&{cHaUO6~#d^^g@Lx20t;>8}1*o=zeap8G|EmhpORK5E%i3D2mLXBGsMKbU)2XC|a zd@``itqLNOsfuhn#~hu#S(V!eZ90G0BiZbT#iz7;rp$4|=&dP$0;j~Uh@<q{2krid zk-@0})eYcABet#<@S(>iox;eNAoVtec=81<;!5AuZitlF!F-@7ML!1Bh$T{Jg9xLr zdl8~10e}(CI2jx_J6;-)tfB-5AY?95B(tti*g6<MB#O2aw}1y_P(MqI%x$@^7>$1L zhZg@N2Z7f>&;T)e(qiX_*ery_V!$Vxs(q%Ul!db!fypx_uoEN*?Qz%UbQoEV6e{BG z>jxFAMoljC@^}Jwl0O#;{R+v)$vXj0)4tWE$@4vOGt3%ahrURbsy97)!;A=@*Nx%? z{QP%!_~mC1w8^0#a}8T2z`bkarYW9(jGJZH(reop$%IE?y@8J=NSJmx*o?t6J4mz& z2#H2x2zjjp>~lAHfi@YD;h(z0qZAYscC!nM;B=e4SY%>tw@$;VHn>=V5{Xsy3);YB z@ojUivg0fe?nEI!r1HLUII%FSP6l7#h-5_(q*cERBfj7x1drge7}IoP@Fv#4fK6r% zoMgjdc^5{#Q?h#4L!d2)z8SRka)oY0$LW=50Z5}t<m%?^13VfWDH5Rl$Q>HQJA7&H zWLOR)sPzbFMcgVzaqo~)E(C|?i0pya$g?Ec=S1q9Fnbt#?W82tO=6eC9T9>Bu-IzC z+8FXVhKC8UVyRMT&-&sqF|k1g)?Je-P^NAU3#FYrb~h{OH_NR7E@k#7&5U8MN{UT< z5)by-YO3(TvO7uqogQ-@43`CgWWvP77@_TA#bOhpJfMK<LLpV<0cE*EJ)=ckZ*{em z(=@D9PG)8H>r;_2!)DQRvm654C*)Nvug;6}?am`=YBtnLBuga3KIc*<mfL+?ZXMny zyxD9{_ZX&Myg?GEzHtZuhj88uBuF7yKr8`7bQj>aQhnVP@bIdYf`nuB4pVlEhh`EE zchtz5Fwiarl!t64?#Xf>7>n3L!DKY0W9Y-=ROK5G%5$27eMQB^z?goUkWk3PVEldk zJ0P(>QUP|X7E1{tM1-t#8W>R>Tvu1QRX}?H7X+M!Akr&SPPcD#5J3Yyh@(;=DSfC0 zq3qNVgB}|gv-<(&q_JnkUh?tK4Z#zx_%dz}Ui^bqT>QPy|GytR#zAZvOQ`?d3Eg1N zH-2W$ng-^IY34?s0beRa(cc~>KRxEY9KLevK}xY#6*!jn{X3<0DfSDBqIa%y8%(H9 zH;aeLa(eo&_wgpf_N|*+nl#fO^9+;IKe+SVevfx@;!UgL_X^vs9e1GqMl{RdA~E?7 zGp4JL1iKY5$d~jtNoU8B+g>f1S>oGoRGD71+uGmzajIBZ1xE=rH{9(6RVpNik)P7T zS+a~G$3I(4dgWHr6w8wXGShxb$3Q###^+Iy3B|B@l8}J|M_qkE+PU(~=Yxaihlc5O z3^>X@m<Hc+UIA5qoexR24yhh$#wzE4v;$ui`-<nO1$NMGMoSQdB2gl!oYFs{1Zh1G zksqkzS|l-42&;3t6G#T_2UQ|l6ens&BuYk!BR$F>Z?gn%#DP5yg&bt~h7v~wZQLGG z^@)cC4-L{D#sfc0lpIZ2t|Q#O1p*0u|7zer9NKf(Hv@x5<<^1AXh%K=Uo!CuMnURN zlxmh=R#x=MZ=GAjhO4=~_hy#X$)R`IIOxl>Av?3d!kpf(gI<08yyLV@-;x&VV(U^a zyfUqOTDxV|#&9b+f3;{kAEU}8aF}6H;=zR^_9`e6hai3)Mn!ZtySN~cFry@yOc8R3 z5u?v7grT-vGja18w^j&d$>12VBJ<%iQygP+Q?Ej{4)~PFp0^mkDig#zjBM`+D3TGe ziK~mz$k%}0X<k|S1a9)l&$ol#sngkY>Iy7*tG~*+IJ$u!+lBPx>e`yVQ-NVfr8FwP z2pjor>Q4UkeX&~Y_djhoG?T;@#3LQ|x%>v|KHfcJci-b$cx2{=-`o3kM6gN$-Sl9Y zRVxrUHXZM7?>!LhSPWNrLIw}yxmYL2_>NlTI61|eZW$;O2Su}44A1N4#V-Yup^#LX zext?IO$XzIK+~Ju(+ZyE4SQePRSejiR*0HQD(HdKa{E9T(o2OBDD8eEGaQ=baL^-9 zAC6QySs;rlkv*CdoQOoJXmN0%3>uvNgRDV952UCl9TiYoGlPbgBMfADpW%#Sv|2s- zoY8nLY+_L{yUa8+%^srw<nhQzkt(d5obU-ItGndj#bv1r82XZ#?{eM9PSmj3#Ow`M z;Q_BS|EbNa7{=j%FomrgLSH*{oPWS;+ST?KgCy7_yb4j!hk1NIge#DABx(n1pvCH! zU<-s^Ou$ZD{={9(b2;%qsM%)HgGBt}8+d>BT?m!P=ac9!ziyp*jFS9GUD$I4UC=p0 z=K}OfkA;gyuKOkD`iN-NJ~`NC9r%5##9>8lD@D`Z)(nf6fRQ^Q8nGHMRzZD&#`E%~ zLM|IQ=$t%M4gmsKd^z?*k9@N(TF(zyxeP1>SOh({AB#+u+Z<<w-#?FxJo=S0ruQ{h zVvQfKlEG1W{KRs)c!clsplb#fu5w*Pg}hFe?E5H#D;0*rAKL8>$NOi~woj~JKZFiT z0Mw<ygocnpZNC%gzdwY~`%bB+T`*;##qL!H?G{?>j5_GB&|>)2gQ$K8l}aLZc!CoQ zf(tP0vRg=&h@F#VUD##!B*|_fyCD4$0hk90tB+dU*O%!U&ElHn3o9Ji?#xxJqDBqT z1eOj~D)pe7#eEnsAznw7HOz84;>`{u6p|hDB%YK9J9RVq_1V9BJXNGf@e_XzU9Drk z0R~?Jv6)5FtZvpADr-X921kjCV?Kwz<7pZb1#Ppw7cJ^p(rTo*(>DGL3|J4j6m7k| zmabCGS1z0-c4Yi?y_gj%6~GvO<Ea!rdzmsG|Nr~Z|7vQP6o>^eBd;K1Ax@m%Btoi? zSWJcp5CNXeX5s#iw=VtD?^hsz0D{10*!-TU-vgsw6D|;BhTQH*<N=W!aTA^M(^w`t zNFwmrU$zB5Lx39h+HIb6gu#wb10r651GOhU0(y@tq5~G7g@0Zt-Fu4MyKr?FWr-wA z&QRf?SeDa!ts9*~;7TThMaXjoT5Z*BOqygyp*AaUJ7X!eFMArq9^bv}aSSk|9K$#i zL?lJ#BIDpfmBE@!2tHm8*9h^cYoq-p87^FjrPY*M%ACYO(XuuDu$U{aB<a@0k^)qS z;)FR&F%oWxA&%YET_tNUd$tK@V(C!>ldIVs6e8lXVE-oQ(a;Sun@pw1L;tX=>BwWJ zVzHFjWj>lEXL9@F#46n0t_@)VGm#UAo<>7qn3T!2x87cGB`kp^5;3ngmN3gnk`ams z1Xa){6%t0mMn)-975s^v6$-Pw!Ca8u_P%|B^1?I_g@t4(qmB-Jhw`}D|0S-UhD_>R zQ!_5;z5ek@fA~*s_XBCKMK5Wdo;vebVK8_%l{a31XMVjEmCh_Bx#|D@jExeS$6~Ok zTCH9(S1g`BMZ#eB;&+FC!!WG4&ch6Nu7*2Wrghz(3<;l0oUo8e{WtV?cfpiF#b<13 zRhZBm?WvqORu#b&eZ%idFBklCNG@CYvU(-(ZRLwZ+@yrLBGEiWzBB+cYy3PVoR7yP zz-5AbO_(!y;(-?`UtF=kTo{cGef3>-VwEEK-z+hDgk=W%MtNYQFF%!knD?7`F8ANw zo!s<!toPU-?NDhdWEd1-r_-^RP$;Cz#Sflg{6v#zz_<v)l3{3ThJN?ZHYO4o!;)s* z&1M*~%bk@1XTzL~XU@?oz(xSswhq4CK9np{vRP4b$R0i9LEhwvbUM=nB2&(c7n7=Q zGwE?e=15LcX9R+$8@Iu0G+rc4OOGsnk`pc_A4sE6lwv$gp=dh$0HlQ#6+$y~wLqBb zSZmbdu7`z_7N|FO7As`n#a?}2HO_?I9^_JQn}E}easqC5z#KNp?1*LSTZa>hPz#ev zd%Rwo)6z-AY8WuK^7_di{TlueMRAnkJEky$wRnYDe=bCuxrtsIUzL|1KKy2t+^AR7 zE5A>D`0i21;SY{G7u#|K&V8!##pFp-SsYS6fx{1<qSQ2T=9dwCOn!m63M)y5IZ{-y z&kT@75>-0`J!M@g_|1**jsH(3C3`#e>UF@-%T3(xB4#n0<mx#BK|KCL<hyW~Ab9ED zve{Un1!}EUd+pqe%gHUej^1Cj>eEmEc65n#{v<8Rz0#}pk3-f&Z(6O4-G<9|=|lV5 zM{P#Abva<~Vr<G5K7O3Pz~lM9$$Jm6?j1jS?GZ_A0%5Y?$-T2ri2L0)-hAsla}`FS z+~W12>d{{X=x3zrrUQhorAgQPaz#be3RU*$(`*(SClU+zz)Ua`y%QjO$5g<f!fX*y zL~v*}Y%0+-#g|PIDLDrbJo{wn$xUUh;0))^+M%4>)^jXBQ)O~T;-VCVqD?4f0?dqI zKoUueCe;ksr951n;-uG0k^$1?^|}aQ8i=0!4fEc-!xSew;xVHp6D_PuPk_lcCzh0^ z88BuvEv1A)%B-Xp2L|l)W5bF9o2wyffQ82@DpLPj#Ug<~gc_E^qAPC8zZ<!k+pm#4 z@7<B-h-rBF{qXVQ?;T!hI-6B{PI<UbMl8n2T|%K~r9PMxhCO^#B$T!2gp(#o7L-je zbBe_=X_rLFfU%nh<6{^`2}RWkFoNzY-gI{=@sgxnuG*VU4?b|-{THV*82ly>yBmuL zn(+GS`y=P)ZJAg@$E>xcp^VF~S7SMu`R1CY1YY{m<_1bJRMcuU(Al?`{9u|OWjhU( zQj#*MyC@rXckF3p#EfuwVH7_4PxMyG+=SJ&(>eycp-EL?*tr7w@NgD4f8-E0j&YqZ zy}TVZH`H$2BLgcIw|yQkgwljqrcz`q=ti&pK3Djo{=rWNdU?EqiGL*m*r@zFz?T@| zaIyTA0KYclp|1(A9Y_fX@L_FZ@x#~mD6ISoE3E;5&fmZ255U^()Hi;KWxEC(OaPGK z01$lEDmn12aOpG$h`m35=ay1rxO$YoK|12f^^&l`%t2Qxi|R>Mf)pCVq9jTNi(2}N zmJ!uPvy2mw;Q?J57K3M5RjwN48az_$`)mWl{4k>GTA2sqos%^*yzfbKDOoSe?DM)q zBkZlsFIsXS)I<a#+NBegl}0;<&R8~fILQr^Hv+FmBX5TkQQ-du;D0J_(yb8|5a*(i zm4by!qt!l;0ts^^wKT^q9UA4;b$1^&3f+K9;ZhJKE)^X0TrYU0=obS0M1;sJ4~2|= z5zSc7jL2uD25NP@PzG1KPyy40LU)Se(0i`4YiRHA3WUB8x>M*6ne)OxFuf`arYJY= z+)!|ROO<W(_Sm6S3mpU6ERx?<w3-Gs-PmQeGT3AXn%WNAY_`cp$10g!rR&<v9d@FL z2$~w`?X<v*sA<t^ZGV?W&)aC5EoL}MrSFtYT8Z<Y3-WbbWs?@WwA)~Z*`6mc(|j*j zWwn>A_JU(G(-+ekhey*|)bG@4+xl*3QZ>p?!|5b8m}4f1xi*n#45B5f%xiYq$fKoa zuv20o^!AdO(OcH0uC|2ATAR40t0`n+nQ57as>M3ccjzdU!?fr6OV8;|X6~{D=>l8o e<+f>`8L6gTtb@T08wOM!AY-F8Z2I+(OYi|X2!~Gq diff --git a/.next/static/media/b967158bc7d7a9fb-s.woff2 b/.next/static/media/b967158bc7d7a9fb-s.woff2 deleted file mode 100644 index c974fecaa2f8304b62c079a68c9a3b1edc916a52..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 17040 zcmV)8K*qm!Pew8T0RR91078%e5&!@I0Dr6i0751J0RR9100000000000000000000 z0000Qf;JnTXdHn!KS)+VQiOj7U_Vn-K~#Y_0D>GZY!L_w$27VY3xXa1F#37{HUcCA zgg68s1%+G(ARD@N73>!H?_}KmLmY*;9Vt-=TaTi2l8V{?pAzVhVL_h)Y(9r*R4osU zYOF;d+Xs^j%O0y|ye&iDY}C#g+0IM~(a1u^BE5tYMkU8DKX35%>Lf%6LpGke5UNIv z=&H<ixb5y*&1iKW!6Qijk)&k5bG3o+{f?g>p|MYLeR%%etaD#pl9vzR5uPDH0zm>s zjT$j(gw(!#gomaYHMLYxBc?zrT3Q*KQM5@wWo+8b?65OVhnZzv+Gb{0m+3G&wCi+e z%UC+gv`lMT+Mz9N8Ou7fjW%MYO?gn!+P~d1`vAb@8xhOO0Sdo+7tj&XTusrt)%PS( zP|!s;cSqgETIw!)$5!#GsCxI|T~Sv(Nx(cGZ#Vn-Q?Gdc`*2s>pQ@s&W|DvrXJLeZ z0S6c~D_Mv*;wS+I7-7WG9dLjFN6hMoS&SNSz=%-;OzG4VfCFX<%OSK`=g7cs0e+=7 z%W`4uFlNj&6lfSb0`Gvt!;j5-xVH!)GqDg!3kgE$6RT@mLjKX5|IH+m&30yYL+t~3 z48opp1v~&uGNygU59EPyB<u-W{D4Lu4}Ht;cdNVS#SQ;|lFi0%J|G-UcFjD_Y7`bD zqs3`lhy_vj_f*fqLA0q9N$*2TDO^|15MT`J?$UdG#Lw9e7RRo^t)ii{P9c<34Gjd7 zVA7I<U>-bpkn5*h4^r{8p^zT54N_(6)ZeE;?(S6y0JB@@otCBc+kO;3M}asv;gRL| z@P@H<WvZ1<0~89BC2<aS@2GnRyoJuieCwl2f_K?s2CH=hxm=JE91S4pZvmQG>=Jh% zDAs{ahUdInVud=GGZ08hI=VN!H^xNXq#wKdg8V}lB>(9rnGe$7gYcubYVR*gS3_1) z2$dGH5uhX(^Fvy?mXMc)tR5*{4$7T78C?oOokX5KBjlMZRZcRovyUp95Xy2MpT7Dx zmi9iVJx&=X<Fxj2^ZAx4Arui25z%CiK{u`Iz-xh+<CEju2LcJSvO5V1r6`Ypo&<6z zK%m;I9B8mu`E=C-K`{aof~A29%dNE1Dz@5zU;_dNg6e?NT|8<D1l#!Rut%f)4r=kB zBaV5b$AO@8`9G@!XPgJY5AY-i2mp=*fEnNh>_R||ViW+t<3R@?AU#7@M#p4TizW2r zLCvlVCW}?@Ljr&TKvEy9YzjyQ0s<lqs$jM0#}H;f04SknLU}*>0w~%Y>NtiX<jAK- zkAX#?0S5pG016B!XjOroElZi<1qe%3{YEvX`cv(xvDCwNHy|t?3(6{wefJJct4{tl zB?@G%B8JBkt2zobSIfVA-_1M1Z=wn4+)V;JTga8+Otr{_ax{C<&F90Yn7FB^^9N4D ztJ*b-6$W`{4c~-#cnPj%u@JScn@fCi$y5nIB-6yWgua8h>BqQ^HzJD>X|`6jad9q} zVu1@r*3ZPE3HU2~lpy?CO@fj6(2w`377`+T^AO10GFOgzzqhK`PL?-OlW-N@nre8I z@em$KkAWUZjil<u%Zxs)5aGD(rb5Iy8!v(%$7+t_Uw}W*6tZ!HI_pu@?-LM_ML1vc zV;#7(xfCLF9YvbHay+Pp<679v@lsedc1-MArnw*6OKLlwlWa49G3DbGc4KSFqspZa z^)M`IHa2K9(T>r+A5K)li+}sYSQtfS(@f#dfd~?x=BoPI*}+FH?=*=}ch+m(l0kh~ zB8*NQ4<Es6)Xe%8Q-0C$bwiA8Q_UXN1zL0VPk2!Fs_l-5<PX@DXTk0&2vo4)xp@fc zZMEHA2c1EIGYR1IE)nctpX8`_(b=}r4>=MFmex}IIzn;l!zBWs;GyG=Jp#925gvY< zttvyE(bt!tKmmabDM~3LLj`lFVJ=zbQ5OqT1uJGZgAHcnuoBfO4R3N^8qeiDa@K5% zS{34df0=FWvD^*~toGS2A3NxTP0l!nogoeOc2I~z5A_Nl$JL(&Iu-;1IglB-gjy+p zkR*pB7~cd6kPFr;RcI1)$^n8v;CZH7>`@?~u$VAVT>Zk8Ng*|sVKGm3AO(dAS7oe> zgW_FDEiWzmR8dVQPu&%75`+XrV9DU>b0~o-pd76tH5KrP%aSNlD9O>$k<9Ls4swKG zWn7|#2zim?HbCH5+JOT#3=?|NQp%+GT>g-<7^eKal4=0*`?F#*Kp{iPeE?R7CM>i} zB|Ah3pj(oZ0yE}t2?1ykr3iqCxE(-PGO(g2utOq}88JZ-a1Udchlbb;Xj*5wbC?s! z4e>L&*%+9EfB?zl0TYl`po=L>*!_75o0*tZkpS@rvzBb(QmYwUORxqFN~!AH83F65 zva3R%1p(Gpp=iQN>A%VWIXHltffQC>W%yTIdii(J2@!;qp#D|TGX|CV@ThaB@@VH- z?^*xZ@TK;vWmhY2=D+dbt-s!JJ#;>CJSltPdQ$NWJ}ZAwG+jL7eB=61IP3c2_+g#T zpLhOoGJ4X6v@Y#R^XZNSM`nw%&ZZq<bNx6##Co*Qt{D0F9|k7QG1!Cgo)F{oCy+|u z+K(CP!&o0Z{pjn*KtK8iF#jt?1`&TAJ;RvzA1=Ox$SC?oF))gOYq&Uz$vM!IqPQpI zp+Es3i+c)Nyg?F+3(<)cSHx1|q7Xbn1n`>`17Ru+;U^dYLP3l3LSG&=BZke3ou)Cm zn6kuEB#S7B0(<TC06)PY?!?>n8tV8EcAHyme{YmTje5M_6dd~+-od-r4iDbI7+*&g zJ7g3OI^bmjYz?z_gZ(cqIYdTi`~}TkB?N~}A&S3(_a?4li?{F!?sJa@O+v}VpYR?U zBga85ty%~^Km<G7Z=6t=AQ~dYB<{6`&#p+Y4FJOWGk`$UIAj!V5Aa5bLtY~}_&+ph zj2w;bL(5ku0VyD_Y&;F%?O?U!1B^;GP>@P?&NM*r0)2|?+TOFfJw;NsP$s`?0F+58 z1dx9R0NL7WYHB{-3@88`B>*$(u`jJ1Bo{coJJvy11RN792SGqko3L&W03dlnknERl zymm>fAUQfk3X%Y*E3Z2WlOFF^Txr<W_<6t5swq@f?Z#swWVn*x1}I3xy)Fbs6Gm!T zzDG+4eX#tHK3Ap_MM^qBCuk=9r#LNq+|nRv+zuZH7%0%-Ebdc0c=)@lU3T+1hb7LV z4h0^K$GOSj;l<I}qE<c?^dg8NhAs%|bz|!=0NeNcb_&@3Doys<r_liw4hlNt0-78a z@&LPL8!Xkrsa5r#qfTVaHb*_I-La2khwrJh%yK`#2@Y%6RC&asES^9dcX^1*erG%h z0)Rz<fTI9o%K-=hNdS7(g5;7sctrUU#;qm6QX&OKu!SU8MoBU3Bx1B5wu%JHR#Jv% zh6F^^1_1CB01yM<Ie^JP?h*zXI|m6GQ7H;RPCmXeQD(MYkaH9D8A&{gC?ue!Ly9w3 zi`OohK}{3M2$Cg8fTBNnpqW?OOCZby@Ao5+k}Go_ho*2%qKbIhk44k<H|?RNF7u<# zQP<}#&re>qfgdd%c<eFfj;Wlh$pu_dl*>ELpK{%<u^HRkQh3>ymP%nM^B)nZgENkf zkEs=`o#ls4=wY%cQ0IZX=&&JEq({%Q@1_J-Tk_5aES2K#QST>K_H6HwvOmv{M0$WI zioq3<11%Dz_Uf&J8F;6@aV^&sl%m;%Hn7CH51Y+=;ye7NzX)9UmK}OLrywe)?z!Lj z-bZJ7SAL7_MzU50m6vrb{(jvbVzpK)T0u_5m5O>|s#F?IOQT0obvMD1clf-vD9b*K z6@R8o>FdU|W4d!qbPvV2=9Yz%v`TvQjCUNB8@tkB{QbPgi0@n%K{^0(hGDmt8ePa( z!_rv$%3$LK25N_XLl;UJ4!4D?bw5qhW}v7LnDsVnb#v{sT`OwC=_lvi60U@ITM%)D zy}3V(l3eW43?u)I^$@Ke{{($6uZbVgoYyt{0`r9SLej@-+~&?(>X3W@*kiHc9M1^| z8oWH#QhUyz`*2}c!Y5iatU|&mcbI(Xs${=!v4BcoxghR*6n`83Tn4s)*epZv<1D_8 ziY7Ka#(Q96U-S`jnFSdEX^XPM1zm5N3R5jqK>p&1wm9`&_x4#ftu7g`koN!8i+dvt z26i_=8jcq33D1Zb-N>sSeB|H%z<v0>`{=_D&i&DLckD)^cE_$c;$ui5_YumV^f*4_ zgDszCGkp%CMJ$vzlSDG{`mCo|BgAnVy;f+LuemSXr`FatnXj?=1v_Vb2{U8tF|*j` zNSsK5Wt}C&dbMT4b%_^HLMDwh)O)VkE?i|@pAsi;AmU$=!ZTy}##9|z>x~1~Z1h`x zDreH%#f&u`YU?F;qdb7L=8~ko`l0pJo3KiGgtVd9x{TTIX4kuDb<Qzk`)~wiuuvhF z@0sJV(Px;eQ9LI~p!|lB7O<dXG(e=OI#*B{^nD=5xBbSm==sKV-|gJfAHkW&g0s4K zU0d@m$sl-eJga@}{5c%s_w&|)Yf77-{u}wVdZ)z#)VuediYN@JV=y8i3r#^S79~!! zj<fx3`@S!QJshOR_~U<TXS*7X(ZBC3TS)9Ko>tzn9y;^1dmD(8NfezV@}F&euN5AP zN_*A`V|~$Y{Rff=$w&U{srg$T4)E7AY$rVj-85D)?W;^Jl(z3R_Nq?pRHTvNze9sQ z#1<n2iSJtHYsw>y)!YhaeB*Z!$nmv^KQ@SuCpC%{xLtI5?pwuE!pd7{C>{B+p1C(h zNwe9qWD70qOc`dY!VwqbK6_EAC&4<G7GQ@ymoJVba`&<LZ^&O=?Q$Vmd%Q*khu=IM zxgZvR(Lrkgi;=;QkPg>fdGX>^=5@TPd)q+=>>c!8z1w#npf<<U?sC=N8_)dW;X${Z zfvhPfUNMZ=t!>Nw9wu?`>CC^a@A`>$6x?z{_;UjUU-37BxMBfbGetbdHbj8TJe@G< z0P*J?+<6=c00{;Lr%dtLMEGiJT7Z2@)0MhhY`>yq?&;G<dca{Z@=&MZ{J+(Fum4qZ zj_H~AORptmytq_f_|LM^Tc2-Xb0b`CNa$H<SPuSJ;);)jHAm!LxjHfdiP=0{C#<ct zKI)27(2Gm23`J5XjuP?3AffW|BHDC9Ge*K6{WlrbI`K0?&BDh=Or}yQ5>6<kzRG{; z8cZN079!zA45c^V31(SP*UJ=uSrAAV2f#TGb4f-9O10IB`?}RqtKKxuA3MscarX<a zI<dDmqvT`C=&$d}FdZlR90x*63%W)Y%xa<81NKYK4d|PWJ&^DL2prww;H8xg{=-|v zJdBTC3Qhrp??9lJTon|ceBgC0-%Qf-#Z|_&@-h>`!ruw;%<7&W*_``bh25&lUnx+$ zV<^Vs)~Pg)o3BT8iGgT_BRQa5BX$kv{e6sE=YMc-eA@2Zl_hUF?c;=c@u`H{iOwGC z&PEJ57oY!0?E>=gyy`JlYRN0FtWIuFOva^s;U=%#zj*bw@Aq7WO(kQ4Yl?>FRO^9s z-Wmk~5FdzU+|~d+5?H7l){0o?doi)rFOK<M!?b?eE&V~Y2aK({uIT%}hsMjj!@Kd_ z&|p>ZMO5KfH9uH%#(QjaSWcmKuXg{ce_;eI?d^ZusI)!w@s5p0$A!~d;<rkcijO2c z`Taa5(_*4yF75Lhk4qx`&#)hV5@77+QZ<J?sZ9)at4G@TbYSpIk2elK7x?Z*Pte+H zlWi(V9gh~3&Krh|v<VCDmBcFd_Hl{#%8R_Jwgx|@^TB+6Zr@`#1&$KabADjZADiz9 zS@Ubg<c~XU^u^fR2(^ry%?uj8lE5n-DTsXbcwTR^;!#bhcQqsOA(MAMyW8scFMGeT zA$3eM%(n)ETT6l-a`X0jxNZGB_&xhXI2gP32{9l6Q_vkxOvTSNeooJXK{+P5a8=e7 zf8H<T%97tlxEJ9nCgN-g91SgVJZyGS-Llv5Iu(x}OJ3pS%f=o90hqWD>%h(5+r`D} z7BJ75?RheA2gj27xkA6h+Dq8?Ux^XW^l6Ajr$um1B|JSlqC1x+Hf5^Zar-i7I@KF^ z=O+_?pkg|ukmt?urr}mUVtu_IdAPmFvF+*xOU%F4;L%nf@l$Ezn#S~A|LR+IH=p6m z&UXaZOpFTt^7lPeM_&pz=iWe)R8S%q6b4X4ZT_l*wbf<PGLAAF;CGL2WcWf^+k%TP z^Ek&d0&^|iY`nYn&O|G}`o4Nn|K~Ns7U{=MW~ZJ{EAO~f#QE<6$~D~HIJS1+t>(;% zp<gj=Q>sItpM&VQP^0xkthpGyyGHB2NMYx<7Vp>Q*1UPIjz<*~viPqn|50AYfFXZe z%f8Kk{ou@!#HjG}t|DDtG9Xk1(=8yH1wcY=Y$WCBW^XP$5?Wr`r`Fde)LdRSO?*Tu zy2TCX3#fcGF}8>z87{(67~H>1@Le}oe;P<vw^5d|B|Zx_j$t0op!nl(dzEY6EKBub zW7vLO;7O{Wg*yox_*PrV#8L}S95X74o~i8LgT;91t8tc<u?W`j41@OE;aOtK52Alk z$;~~9{9(_y_K2A1o=1K{5fY_dJQmU%5#m|bc_b$6^6rE()j)+>%eh(G+}~W+tS$dq zenvc3zg+9((kG0xOH6XAfrkW3ReFB(;9!A=Bi7i%_W%59w<Et3SW`~klkHm~mCKY} z(Tp~B{6kq~C3Ty(^dJ9!4fwv<Kr)={S;o)^ei1lE@yO1A^|pNn%>K<<YRa}^X3Uux z()6<%cJO_u{X9nq8*|mnsYAoBhbt6!{@{0acB%K-Wbbr&Dp}l@O1z(>mpM+bngbig z%@ER^vEuufD#H#!Rg3`9U=Ex-UZ5odK3E&tb8|cYPy<b%S5n60G&kK{R#ecc=1ka9 zE@{5rt1Rk+;R6|vpEDpnsl>{I!nf?9<G!p%VvuJ9zeFtZcmN_EGP;qT5>V2R`7>$p zuhNK~$Y8k<?QGjxoawr;z(`dD&=#(`&T+;L`l}b#O*syobUW0yayzpSb~KCTm0ee6 zsjfYF;=l3g(>~1dL<6^N<5hH3wr^na(e@q)ARqdC9Lyhm^8V{t>~^A?WOjn@f{S}= zhr*-p<QHR+^zzCLm#=>d|L`Y~Ayy>4<oE8&d6%=j%OQy8asPiHe)dj)=Y_O1kFzpg zk^M{C^xCE$>7DysrO}#8De)#|tNxpkT65SaF}y!KJ>IS@DV4tv{q2kF+9p{}8C50c z=MKulQaa&!*@4N?d-<E^`kQztwDdM5SCx8Cwq#%bs{X#I!&6wVQiM{MXE7pYT-9d` zqzRulzinPP)T%OBDDw{gGgb2KWb`D30ek}>Uc({1<|MJAAOHe_48VYy&>u*EMfMCE z3&LR;pH%ARdcpC%s#vXAZL~B-Q}Z@`&%Z3n{e{@9>$x4XGpD^*b8p;py!C6Iv50tS z{|A$%a#N*L$K<)DLRn$>uQS~dpI=Wa4sLgg%iSU+CzWT`!($*I9=CciQq)oVyWwF~ zi*IOWN@CKb7vaLWN6FOuxPYYmywv#-zi%#s)x`8`jVciUYY<2VYGw=szz$;iajfC} zsfVI#F7)zVy2h-g%3tTStnr<EwWqz<MefDs$|)AfE=#Z25e&(8Mq2Qk{z55MhLxq? zzH)LoU)xI6#>C2G0VYVMRzgzl4`Ogncwxz%_^ds<V)M89FcYNWoD6nwd3sK6f3m6% zu98-I{lAEowrOsrBsH_VInp9$kCf-{-o!4dx~InNZdVGcz7A5)<&FU@AOI6BR~6Bh z5<FhbRw%S<u!VoN%+*kMCwC$b_9KVezO_XcN^pY2s0%>zRWmaR%H>yAn>N4vOFtgC zC^=hrM_)SRKw>`#w7a)$^Vkm2VAvyVLw>ZeGP~Wyj@f$=9rx0#K#HIlguigUA22f2 zKv83|7@t227q}PX9IJt0j`iSQ7od;@1iSm&mLf~yfBA6R){b^`q*DI)E1m`DI?AzT zpXXQ&PR1I>lX|>5TI9!j-tWP_2qy>tYUalim_kJSZeHPFer%QdJX7nA<p`3mbQ0|| z>9C&Bhe$UV6wT8x@kCAC4tDkIT2McC0A@z;ONfAY380LJj4IO?WhgM)`t!pXx?UU6 zFwuVNLdMHGd@-N&FZ0@Xe`S1Xe_hc<Fxw8)gOZl)$A+SPPbRK=foE9wB@lm9IAk*_ zS6p3f`oPOcKi=Mn$5r|rK8_mX)zZPf7yHrW$-at&v_5X}=g%@X$Gd3R7nZsIL&*0+ zTdDjIcg#F~(R0Kxe9_B#{;h5`LDko~56Aqgo4igyHeBiO`<k)N9mFrUr`?)vL9j6^ zh^*+fW~NW)gE@xjVZB%4LCsQop)rFSRdVvA0_nn6ktrijmShZn8QGBx1ibA34nOzR z%UJ=GM(;>wrr$d}{m|*}Uxr}UdpK*aPT9)<W)?y`1Xcw3+<mjtn^^HcPH675SrR9n zi?Bup)b`@8<l6JQZD{Y&gwRlr1i)dT*py?YgJ7O7tGDZCpg-Y`7-=2(ZJOX=Lj3qs zc_ne<?<7<RCK6&(Ma=ly3FSjj3)1qE<0_N$w7j%<0ac=wbWfP$lnew9T}mKB<r@Gw zzE4fPv6D>OGAIF1qq11pcCj;;+Q8MuWCf>F83Y!nXvb2Psk|1->tqu@A85wPJvqXc z;d`#2m20&QxSkue30QOPl#2lP{B?`R3?X9u3lGRqP#I-9cbuVRN!CLOi~q>YyqkrT z%7AI)Hf*kIGfp++y;&C8EbMhk3L2v_gh!?KQ03A|R5h9J2rT{nU&H;J%mm?6c=`6n z+n<y64gfR&sKiwO!Fb;n$N;jQVx@F?g|Z)bYNX0)C8-3F1&O`%jE*v!z{gCYXF~3u z_ZI?^Vk{kDEc(T$2|1M5KWQ9u`)J94WoiY}pU7(ppyt!MBtS9=BtXKVZu)<oq%n=% zK*mwhEHew+i|WLl8U|^23<On@j`C7MjB$8sxLlM?Lf`5aH6mk>P8?(bSz2_23cR8< z^vJ^bKsLsS2-)o2AE6e?tm#z(9<6j7!;_>V3}_mCE6_YxBQl8~@1X!vwJ{1C{`Yp7 z1`n9REV<8*xr-blG#MpV$p_>*xm|Hqgb2rPs8Q-6m8r@kt=W;I^uE$ky66k^U1{g2 zN2=GejrPgX=IW-iDNKIGSX$es!RhZ9fyuTR`6AQFVdO;eB>6psO^Kj<r2L~Yqb{LF zQU9XeppH{9+Gg5uT0d<zhp*nJ{zXGwW1q&D#?Rbcnr)f`n%~)dYzO-$FE~%qZqt6G z{W{+||B3uRITpuo1Ki6co0j}Qr>(2f9ny8_WV+Y7uX^-?KNLJK_^H1^->7fY-!HT& zJX(0Wh*9+GVvFJjiysyLG}bm$7{Z1=!v*73qu*F={EhLiM$A}btTT2SFBpf6PmLdp z|C$m^=_O0I>GJTf1~rO-puz;eT~kOB9t6Mw?I&4ELS;7x!dKupAsqAtMqv5uT?GKX zaGQY^!CIP<OcYf`brirN+F6vOWWT0V&FkW$jHJSK5kwkbLQ+T#i4>iH;fkI`y~sr~ zj7wZ&t!EB0knzz+sT=<<zHU$n`{0anxlqo|oeML8|AyyhFF%y$SMn42x(4)fFEb=a z=cJb74A?A*SbFy8%zCrz6D{%J=FLQWJ?a(^#VVNCU*i)rtX|r!KavFn2Ae5P6!{i= zKqg13?+^R^C*G7G+tK^mYQdN4pYVYr;Zq6<f3TQ3S1Qj^e#9I22@0d0JxeN0>nhZ0 zkfY2u>ts<o8YqaXHlO$!$f+)QCxqFwfk$+ZnxxHQ(>hRi0SDn^c4n-4<;jEP^9p4X z;W8e5O5(={SDXruO+VQso8Mqftbkoe>{NU;4U!o(eEUyw79q&eAGbq%RD(!5<I7oN zV`tX#4PquniG@Gi)JGGt$A*8(N|%$dA32)ym<toqgECs|#qS471d>O7r*Y1mj#;=b z6wYS7$hIR3uTJy?e@zm>O3mZs0yHvkL=wF7f^q3&s*g+|Mksiy*%mY1(!u`Rm?1US zEjZ-&=mF$1Z7e1eMiLw;s2GHbp|Y;}b4TJeS@5dx(dv!xj=DY06HCdNREq=TAP+>E zp%|&f4D4L*tXW}BUI;?YE6Ckm$IVVALI*?J(>yQ<$`Zsge3gr|yUVjgKvja^!<4jG zKw(vzV$uZZEYIKA!$yiw6c0Y)Wg7&rlrdbcXmJ#_l)+udlK|K}cEWqBjXLU<ALW#r zT|%U3{h+*HT4MvBxM51V=QiEELetHT5dpx5iFKRm0pcS`Nl$Uh1NMUV`ocD1?i=5A zHmtmHMFbF*xWVZtjv<<zb)enTdtIU&g^4z27vSG410L59ya45}CQT*?i3C=)$$sc} zMy@fE1XQ}wG#zG$gG<CgcO!A)5Imkxe$<G7c-5%-Lu5jj&Stn}5Xg?AZqbnstcDHg z5bi`GVoJq<>%)1j-W)IJrD-RTnMZX}+oNG6=IE}{vw*mZT;g=PttcTehS^9}E!+1d z5Lz5mkK3zQD1(?1!GW->EA>;y;S^<xSgN4{EIX12y}dpN9VxvR>aqQzlcFe&rh?i% zXh5g4ARZCc<g3UglRHfuC2eerBmBMM{|Ss&tI0MSir!=zgw65>Uv<3;up2^~>4sTx zIq@vlO5|7;+5efeqj-L--kQv7a(E>1hJP~D#1NGtW>Ttg`*$~e=NYgZ8Ake!qa|4R z&UT@8OU#2p3~4fNEBRVs+S3vrKg$im7RpJ2!k{jZ6XYJWfh-wSRAdDCaxF%GJpc?c z=4#RZWY}UH>aMs9-haa6B~E&OGYd-v+y(dONCaWN2RaChx=?ldOq{0mx4Y~vuj2D$ zA_186?9E?k+qi3*LlfHN*KE6TaNGWB>Y^&^-joGFjCYM|>>M|7#9;(1QAd1KM&T_x zD&EZa&ztO*c9kP0j-8AZPqD}BgS?K=JV7@MBr>*j?6lainb>9n9BCco)}|wA+L3<s z#nLH<tH&yj(XZ8)Wj@B-t<#zE`(*O}Um5d5`+<Q-V&GREXfhA%qxy!H!hg>5425BR z(d8sf)BjwSW&TU&rrgB_RV`zqkL|w4R;*}zbx0-MP&Mlidvjk1K?tyDMyqN*6^7j> z=|bz`T^hYhUjK@*!5dN6eNOq$ZSFy^w`iE)5>j8dZ*tRG%EB**p1_sBo{Vr6m$7>I ziS%M!a#Umcq4i6a*wj!nWN0b%<E}-ICDAYX<nAHsZSEP`3+-hibLElS@OeMxF(-=) zv?$*vr7dwfF~^~*e>OBWkUR?z?uk$$S>qH4ko%_PK8t24*l?cv2Z~1`Z;;hamD$Dt zR#(iLAiXFU?DbImM#r-h7IqRKW#acYDbXm&oU;IC-$gWn1|aCZca+h8rVf?q(DO!u zXRLjLEd(jdj9p-hB9k%>ab9Et@s}t9$yYDKHvB}WbP{;?fVHzzat3>}9U_pF9qG(6 zE1egn7A@aoSSS9Nn>^+#;6CAnC->PCl_lErUoFdv#&Tlm`g=$5Z{USV4*))2qv`L~ z6BpaV)5^@P$GUgC2Y#Y#JGI%FJ0==^I-k)PrCVF86!c(O_Nr@lsN<1i54D6ERwDH) z6!yx#6CoDylMO!q5r@&hlNrRh>}D4xX))FWrK8XCSRR~lp+sy6k!|*%OdACse`yz@ ztW4>6@KdXhLn}F{yd6hb=Bm|;Ysu9#JEmug$~bn!CZ0I>6oXnRDrPmlI~2{2niys_ zk?rFC=lFWBCP_UrFvM|VQ>%IV68N>p#9PYXUUXCeZEA11nMI9?baebeq+*m(U+A#e z!4)psXZ75=*3gv~N9KT@(QK)l{&utfs2R1o!Hod)9j&J9a;HsveK+60kvl1`!Xo=X zV1)|?Yg-oQO=3o0SYIjUu@GvsXLxVvu;slUrfe`S>5V2pzT8RE;$pRHVhnl5TWSP* z6_^=>LIyvpqh)lJrwMpmd^^3IcCluCi4U6K`*J~gm(fhe68Zeg+jpd#6jifo8<V&d zva23yHew=K5g!s5cvf6Z4&0ZcWfpUM`pv@vf4?!|Rin7cOABFtR`^2dI65&vhF3Cb z+00_L8(W4{9&Yu#BpTx)Isq}vj>q|r7I585DX3(0x!;iCTYWYtr=eY<yaQOGSM(!G zqNrt(r~V$n<Z=chUF@>39}LvmjE`UZk>U#CM5kFPX16mGDYLEj1i>H2Z?A~q!znIb zCab3$c1SYdAb8=by(C~Rgf1}1=@!b9Llrd%^z}a+DIOEALMp!aO#hup<pj(+Rx*7D z{p>95&r~fB+bv;XVv~XM0hi$9c=wSb7%If#$sc-5xrknRk}ZdIw<bO*^kZ;()HVjG zS~HxZr-!@Ye%TNwiX5iIuuflXt&iwu3%V&qD8gbG2m(Gq<wj-Gn{Mh(wj+uN`v)sM zY_v7ZXrFF$p$DfJW)Bg~u3Gd&%tKGCRidT%h3!qhG8nfOGa5=zaCAWVu$y5*in|T} zzha64`pNu=l{{ZAgmU#sgMtU)3IA$)4}S!@uRdcm<yPz3O?<^}=UItoUXfN_(&(#H zdPS9fw>vM<!--M@_KA?62s4_`wT6#+{r;XI;S9?P`Dnq!jUB5O*4#u%Z-D~mLr-)F z55=K1Cd3821WiK8_vZWi<^KW0MitzkpCQpMokVK60EElV{mzOxs^0RiawCF+(Fsmc zJX!tpVtOedy-Tx;v?mC%5#&4{&-eBMMZlM|1lRqrbA?Z<bGGj(Umq2Wa||5lIdj#X z@i{DFBe!j_LP?Lw1ew-uZqJ#~v_1A+*#~*QtG(VpZT&ni8t|#FVYdI+|G+>p1GCx* zp!g7*&@{kmSnt>JyZLT4UrelL)277@eFG*?5;r6UVs3=cTSSl^d?<1Q>?3-S&{Yk6 z>xLjm3+i>2Ws2uuRwU9X+6&$o4qaTF6uMl3S%KiFt6&@K9>0V)|NIXEv=_`@@*cZO zd>(m3=IUo6q;zY@h?d#%7kTIZu-UwJza7W}<M&*_=AoeL5p-sB{KLJ_A{WgW4Q4tR zBy-c}!w&3p{IRv6r~Hd}?2LO~c!uu*Iq^LzmcH}CMAMlK6RU!&c=%F3W2!!N<8Z2) zexn{LdZlG?UXY&oElX;3a3J^7yR6rikjNStELth31+(ntRiDBpa1F++)TRn?tuBI= zNohAkB5z;8d|q$+e_!XUzn{6ng_r2Lm}H9!nxISH;&Al(G4kqtiSH(;q&abUssVeX zkYt|{-!RNTQ+zwV5GLoy_<%ZR0z!*)do9QcA=GBSDK-t+rNF-zIpAlKa(V>}MysiB z2%q@qxnttCWvTkL1s=xTSh7?Q+z?YP7Y_#??ak(C%q||+V#(S%B+WiPL1o5_bMd`g zEX!n}zkH@vt5b;_HVS_2B}jvKd#i#hN5KVWOKQsPm>5eXG{d=6Yr<N1=azcL%epR> zKY{7`Id!Ab)>D5my8Sa($ELuKY{hk7s;3)4I1L;>*MmkRn#yU9NqllK!e3VJti>c* zUF^2`re7iJo>-RK=c}!;ma{ZX8@nL-7*`*ey}eNH4$U2uO1#@%Nqc2hQ*ZzF<gksD zd-`s|rGMndmy)wmPpD^nd)*tl!x(`?5(-SW+wD>S{q@(;{hR&$?z`V_%cV8Bfd>}C zDGT@gKJ74M#)m^)1LDeN46Npx!%HGi29+wlkVT6TqEf(?@$`36DXMmWObqm2z@J}v zwD3>Z(87*n%(}7=Dr~Yv0MUs-0vF(aZN^M4p`jW!|MwQk>#xZ5iR-H-%3|Y1p-2TT zA+3T@Q-Dq!q10{>QGp9LmcUVOa<du6@1(kwZS~(unG5%(Sw92O8_)N8QNvC)kU~sM zh%a$OS>$Gp>|#4&8pBa&bQ*#UE4l#(AO%G*hPL={3w#-IzR3WzgisVEnIxV6L8ujc zdbP>IJL=#dw}}mDv$#d10+DdexwQ1^AYNRs;zy(jHFX#~uuD%XlqV#Tbk?7b(!Y8@ zc(#t}oC=C#e<HygBa<oAzJ~+bhU6QoxLrC`2%~_!(+o|QF;09sET$nJdio7cl%OvA z{uRD_vaxUyv%Vw^eu8MaOXj;ig^@vPKNhIwqIRN*cxHJQSIp33w7@oL#R)*T+a-*X z2@I(FNhKg2#q~dU`4Ql_6Gt1kfnBgCi=5*$dXAyLK_e@C2DXB`&0SMAnY?2Rmk(*X z6}|-Ndk3V+BZC5qzp(wM=@AQERvT_P3?20HOv=R26l3y4X0Rgd6yu^Ttj-N28g<0a z;#Filsa;e}NMLe9hI*`>vSe{r$!@vHgN09yY@VE8*c@R4RQp~3uY?bY=@*?B^A-;| zPLJa>4erH&bY`1M(RL`sFqmRdFIY`vOu)f<l4HlZJs~?QU}o5uS@lqqBNj=-K=m1h z3}GZ=6i5-rV3j(^Y;9``=0(u~mexKv0~b~F%!^{5V;d#~y~HoYj4OG%a(@%cdX2~5 z^5wH;)br$FqId&4s|?bVYw!$p{`Q!FbXxLUlMz}PMczLaKT>WQr1<WdfS{4yIfI#B z;u=1q+A5>ScUx{1Yt-jSz}$|<*T3`9ru4uM12!a=`TKUu%@b}JXqYvzWJ&3kA0s~v zv<*EoUvT5biY&d2r@ynfrdV)kF(&w;t<8&*Ch#ulXaQ7a)L6P}Ui%gVToWV8@$1um z<77~gGr975geWoQE~dE(N{SkcxwFLiJF^c=w4%_IFOv_H!^)sSr;WK&HoNMR?o{1A z?WPLFTLjs@y^9PnIN&bG)%}JLjW|(S=%7j*0;wjS_EkroH9=ZCI=o@FV24e!R&g9n zw96_jebk48JYtU)ZD1acf>>g93q->iCp>7UjPwVt)-I{ZrTK58DvBUZF%YzqsC-4J z@3F&`krG5Q%`^(Op+atqDRw3bd<=OT6N}P#;OX~&V9-LxOIHw&go~?yU_`7Dh`1tQ zTtN*u7m1ltiL*C17>%AcVK&cejuLq?aBcvw<Q8$5As?k(s`j78VXEMUvGYo8rXX0W zomDpT+`%w|C^;!<34^d`1EeKZikK+-v<suYvqmJ`v8Rl8IDxu8&49Ttt&n62GbW78 zkcFN<e4b}CS7;X!!V#MsJVG3ucnAgKdj8w!t+6_r1-97gc(+>KTs;0bxsWodnJOpv z_P02SR}VS-Imz2ycA=(p-QHl+m4>gNSO^QLCM^U5t|dkdjMK28Ww2(#w&FHHLHbkb z6cZCvO|6ruUNlj|L~ICACQ~#}%(IBoQg!;_LtXuFHO*Npu847tj4Y)s>yV;2t+`p! zicReoP5+{XkG0$c;Hm|dmbv;&%31E~bM+e-0I)V1FW#Hfxpb%BUq%i>(G+DD$swE+ ziQ9=(fC9ujBCB#Uf^6`2f$@k5Qf_(o)Y#DFZ#UKI`Jt}U6Vt1ijM-()>4g=&iNDT% zGnQaQ{*GSORdB4e+15I%*z+Ly5@x6bk6j~cJsjCvtyZt+^Cw-eXVKTDlLAUyJjMW& zNF1>Q3us1zUaQ*kv0z_vR8lmYG}wfNdgBHFG{>3Eln29Ta(!=4_wsL9m9w~YAUQK6 z+-0Ds>u3bA>pIxTNRLshuctEH?VM)Y;XS^g{}r#x@^#_5ex9Du1mV*{#H?tUho;Xi z++Ei$B|0_p)}ps|@QwS2dEj#h8s7v(QOt}6cE}W6qCkb{vGf<s^#2U=uD3F*o>e(* z)NM$bkVt4sNG$b?#sBNzQ9r|Z(GKP<QH1iSfj@?k@w;uNBEZbsLTLdhVR0v}#pSJ8 z(~$60{Gi!fGlt=blnUBAuO}+df`z$>o0mXn@c4$HHctQmXEy8g$zsin%$ntW&hBn+ zv438WtE?S6ok@@sY>=MGfwg`3)j#%zkTJpIc}!>D;M+evH15!{x5EsB5)+HTT8F#1 zahdMj43|+5g<{R&Fk-G=eD^T=xt<-Kys+gtBefno+>68g^ryoR&(=M*^I7)Zk=N>l z`rHwJAmBtImETB$T;r-Kv-bbY6^?LUP&q6hIqfa;C>%B&>)Kmr$Fhr~m#GWoX+jkr zW)B>P^M#btQF-b9<0q?n_T@nrLf#d^tRrz?*nCSq*~FUQ{FWbe1K-VLYk#1&SeL&D zWh*YaA5Ayfx(PhJReOK`^#m>e*$NrB>ufu?KNxJR|G}S#Ya><U59H@~Vh}44zT;k8 z2|_>!UhBtwe!q)&k?ss%#XqK{>3zNgi3yPsD@7t(Fk?t7EKzOPa_T&L^B81A?xB^J zD?tndY%mn_<VlBU5u&q|U&$oiegDa1%%s;B{#|Zk5AoJ@XZQH5W_0nEIN|bbgJFk$ zrTmm(nct(%dHdfVo{b#*v%8;4|L}b4=GK&n+XoVLq=1@kl=sWtW;CEoXoeGNS`d;+ ztE=4!%Q<<|9;58i%|&}YS$XciH?LmH%}1FAnMS{?WUjViAa_puX4-_NowAE-&@E@R zyt_~4&~0ri^NrmWOF0|cvAD-Pvq8m>FTV90R9Rs`!Fo*E4WW~7^#_zr`;Kj1ryKoN zq{cPnsRI__c1k486IxFCHfJRO5xKLy*Iw1eeu9@_@HoBNJ~8Z2@VurGD-9esb>F=s zb6Y4Xk#zyHx<EC@ToXW~%U%Mli7Y0(Mv4&14bopJ@}e|QmuEKszTnAX8Jq3*()H}T zsH*b*8pq^n*a^E(`659g@)1eg4wWjgo9$NBH5TZ@ifh+dm*vF}wfZb1(z?BWEn>*? zU_cicBj<2R&$;$_1i|GUnNhRENYDh-7;t3Nt_~>^vo=n9D<G)*QJ}+Y;qGq62*;fT zW(ePlsXn^3ZAIQYS0)CILi^)}_d6MHO*I~yc(TZ799+(*bne>9J8<(9YKvCx)!?PX zcVwSvuD05kNvgA0?#rW5DCtX#Cg0qor=POL-omr9nzptGDt@_Au~8}LW))6XeQt<l zL109dBy(q<;obrwlDOpL(jnMxoC(^97}2-<c6B8H3M6h4b+5<b9#d+T<C+5~VFnp> zQ_G#p^HNJla&{kscDp$TiLZwx6bJ`OGy#x~392x4%3*(EUz!3fk6nr_ujiJTN^b}= z+F4-yWQiP`*+LS6#r(^dJiBSi(dH_ZE>T3vc5Sy$aoS@tqX>h6sMy6A3T@vZfIt$Z ziEe1Hh(6iu#h-ChnnP>OxS+rxk|C6cej5`2B<7w(o{YwTrK{KqgZS;w5_oSvy$%Bg z-Z0pvt@;hcCKIx~H_>$UHwT|?FD)XPIMmdDISR~OfO$q?6?qXtLOnr(;+7Q#X|w@D zCnU?TUURn&d}o>MZR@1kdav;Vy>uFyUwO)!Tovq1Rar4@+%wRw$leOo*=%hHOgsQ) z5<?C=;z5JXFo)yA|DM;|=QiDZur8XqU0;m)iTUS1D6%M7*C?%<7~T)6aj@WTiXY~` zn}85T)H>C$AR5K5Rym(j&UUKAmP5#){z&3OeVl_RqDN<Q-toKr9>Z*T;XH2(I8Q@6 z)!U=43I3W$ym%Hfb`03?Kwbw}wqFv5%k%oTMp`9B<_D3iBu`9Jd88Sq+Dr7pRdO^B z)#z1!&ELUpcsN^y!;wzR%Gd8}iGHiRcqJN$nnRqcO@A?9UK3p1d8#@cfR>)!<+e?F z`kU3~Y8i>z6e%x9(}pRatDEk>$<GN$mD{diRy)v$v>JT&h+~K}M{6_BL6n#~cVbJ} z=i;45N^#);zl8&C)7q6y;LNVwn)Kc~$<%{K*$Yo`H(`*^VPCFDWcGh^HMF8iJ?1{T zvz#bG74~Qh=ha_A+%lOoN=YYc=#Z_s2KL>Ma17F0E3@mBT?cj+-}^CulBTsqR>$2= zVO<0jKWsA>Y0r`=1=eT%$DzW>E*l#%-43BULsMK}DJ0-brj+rNe6gk3^SYK~K=}yu zJbQUIvHp*n0v9?&O1iYLK(82noU3k$z6=es4Ve!m0fr_-XeppSBUBj?F+wg+47E^K z0uDD(#iADfXE1CHzp^{DU&IGSJg!{P^MQ?G*MUUr)aA*pWRf8!$1jr42c^0ZesGin z(v6=|4|UD#OwEUn$cR^b3-f`ciY1Hr$caGojDWl-(%6Xci_}MfCvFMfgC~8kEi1|U z7gAej`u8=ojx`4Z&!BE@Z~)Wk+-z0LRO!1@5sgW6bCW~&oYxac99WB3;y_$9f0*U; zx@Mz)P+*i-<Jt95w?ze$NF=dr2~FqFGDf`f-};s@hKOR1{6Lg~*!%Ma!{M2|&Ut9( z&bc6RItH&Bhusrjrj(?4CX`2q3pSuzYioxWop_=>wLI)w{`H(aZ#M`+Oh$2a!p=_f zM1}2Xu_LO#b3KZZ*ox)ls53hj)9KCZ+-z#o1g}YZK{uyT6M!mSadfDBRJX$s2l0ey z%mc%6K0`KJ*$Igkas?nOUZEIvB;<eU>*-in6JG@Y>89vx!!esD;ka2AdgBCum1r^K z3Wozz6lrMa-o)heke#iGFpxe(FTN%Kk;xP5vxdXo=+YLsfGTh<V2N6teq(Cga;tMN z{OPcZJ#{C=yHSux%<lKKMSb(KO36O+-IJGRBN^Fb^z!IPgmnc8(c`njg`C5h#^E|Y zoEdRAJMASWy?b$;thPxQl^(cxD1-7M)SpWa@@oG6G<0LM{_A6yx%lH*K_%4nA6R({ zX=<NxW|1V5`!GvUC=6zT50fYTEi+JWr;XMW30#gBz4FH@h<~^n$v7k&VDX`+fFysj z$$J_a8P?GJNN9Iv&i1H)eZ*hM5;>E1sactA@+n2j#ltp#I5`UOP7FQ<s)VK7gW%t+ z|BZA-y_ixV-b3g98Z!em`&YdM!{^&oheDg$VcVTOzlEmv_WIr_HfL&PyUd|RW#Y{K z`TJh{3bW~CVp8K&CZ+N4jchkJ#LX{mdnQIcy^s*4zj%Sa9*mA$_RoHAf?TeHQEsy( z^6ZDOJ$uqrv2u&bpDvPA1>3e&^YPfEy0drd&v5uEIfzU6J7J;|fkphjhoi#5L*yDI zqt;ja)SZ>3?p*sPuZfxfhYJ#<i$?gyX(m2F&Pc9g=*8oIE9fnu8oiXD*MB}sui4-U zOptcAn0)j2|6r7I+MTHJoaDE!=!3}+p=`y3NsY%kQV^HZ!N{Gr^D5jO^4wWSO3(7A z*j)Gt(Z@pMi2NpMXdJ>TaXf8pQPR5-8J-gwz5~QH>LpUghZn<>oKcY#KniQnU3pN@ zPnY%ja#b2x-1x4DC?0R(^ohG}HSfO5jxIHP;#S2?^xU;GLHK$+bC^84UVr*W;rb{Z z{$4taPzhohIIcR2)JuVXr5xNdcrl_by<$2mri5kZqPYvPk{U-m&lxFGY-Aq*0tMJ- z<cgAFA|?oq<TOC#t6hd0S=~yRt|(vCJZvD~G?*Ed!L1=ImtRP_Sk@BhJSuKuzJswV zz{|Qsn7|nFwuXl<acwDFZiW*em^%}_ig0n!JHSNxMSi0(L6^bcd@P4~ifKaquydGQ z9~gLWO8>}@?{FHn(Y&?^NcY2zg0nWeEib2qyb01$g6+tk8xoG2(GCi@CwuEuOTY$} ztv>55$=GE#@+aZEohaC`n|!@*af8FrT7u7HloAsuMbcTmw1tHj;2S$t*{Yp9e9;Oh zaevt`u*xUYK%K0+$ohQ@5}oYn7=HEz1L8l~{F{tLJqc5xTSx4rId3`QMFXDL<~X$h z<yLhV4#T6xl<8#DSYps}=D;Ags7@x*?(uV11)8HGnbK))A=S?zPF@|kLIc)S)Wb*l zLmThrSSEFIPL@Q9vd1q9UDvaO_l0Qd!5l_#rXl+_b00M$`T8BqU-X1}9$RVfeD0;* zI_j=LE`Wyvd`X8C_iC(jYI))!b%v$oKhAk&V)-XcE>GpBQ(!6GStF4T2O;8ywjHVB z4+CiJA~I&9MT$~wDz$EfMx@3TD$T^jaVu1j;cfO$Su!eoY6_HR46#@yn%;V<+|YJ* zo)OqIY0ZG6(6NC^U2Y2hCfJ+J#W~;T(}NL_FMOltEd3y#CT@Q^qZ3C+R1V~s#zjZ3 zPe9x4$$Fb@Wg(M=WMocYE8wPYMJ4I1!y$EmDLOf3qH8-*ok1UTmIu2Gdh?0p8u8s2 zo#vnEvCty9d9(hTg_L}{`8cy$zj)FkLCT+Wrug0EqfivJi4mr;KEW_IK^CLg^Hgc` z-)C+*`zA5$xcd@hqzZHom!55PpK!9%(Hy0~gK&bJ{1kEy>tVCcd*=twG&(wHZZD00 z)#-40eCf{jx27%mcxkcACYx%qa{<g`+mElaXP$IP+S`4;KT}Yu=Hlg@ia8D}u5Mi8 z1tpj&spFZ(q8EM0GW^5FB09YaD@5^1=j3CNByGuL<whAzYdAHst27I;ISuWGM$^)& z)Ylyja6w#)c(%<U(cvvrL%pKF;ZVQmr;C(tFjz{gyt+cAz8J_|F@-LpR-q<lqg}x9 z>&G2mDL_>P@2hdFFM7flCq7)_!2s4u96fh(Txa_?j|YxVSptqGTTDwRB6R|nVG0<L z3rp%onuxeF>I^d$^CC{C?+!7+HE%1ON<kBuPWAPas*odr*?iO%U+<mGto<e>gE;k_ z(b5b?zpg(O`4KB5DzB^U94#L;8jt^Kv%KfQ^7Ks82_Px^pDyUB=fI>6*<|w7W?G@I zcpT8aI_654DMMjf1r#Bck@jRy-o_M)uWi$@Tf#zQxF&?+9!&wv>wp)Spb4v?jX=0G zIn`?CScy1Ask@Y83^-p9CP+uYAWkNwNDFqO-6V#jm(&3aQVJ5M_}%qe#|+z_hryoC zU$SB=f=#5(2Q=TIKCUi$jBHBJx!SMM|1<BZDNWP6XbwZF+=-~^<lzP*HD%ZiTYKv8 zzWYNC<#%{3Eyx5OEi<d)(OH3o?;$OKv3AU-;Asz9VV1Lm+Z6p;Fl0+_8um?K3(L(h zHJp%JaTvh=Q}_vZ86FQT$H5|ZF*tTDTU`*j_bL66d?5_z#6gkORVa#@L=!6&AM*YK z=FB>B+OD}gWy{oU_wU5?THa%^$mda)VX<uVj%PnN>(D&!=7pMiI1OjZp#)(ZQujsY zs&Ub|B|)-m2uoScX>_pvR42W<gYMN_$)7SMs+>)w&T7m3X!<`8Hu}4M?0f#rhu>Aj zAj!APJe5dk36<9JIht~bJ$gC0f1xysV@Qp?Zejm(Xs=hr3Fm=+x_nfU&wIB3gYip( zk9RrQG37k96?F(rIs}31Od`G|6p%qJwIB=-k?X(&Fk@)s2wi`el@ANi3Na*v<1};g z$v58MqVr}(Zf==_3#?Ti;;Y?YrH95<kr5yv_ld$v5eai%>o+wEjy2J*#fIq*<TB4X zGM|Hqk<JAJ=ZGwzV?<i$9QIF4&B5&gl|IJAZvvT3BMmxTT^xqPpEEpd4En%o8ERDQ zkw|LO96!KMEHl6~=9uiyqq?`B5}W`j7ltvw8zIhfs%;w5wMnMos%=(t=P(Cv!$6q) z;5vrcdR3VgD<cac@aKl%g-n1<I+0m`0FclhemZ;V<-uI%|H<Mm0ATvoNHG9>c(4E6 zJ6g8J@Sz$2WS{^51o%hk0apU3{i1Q-u%?q|1A=VeQ%YS%-Yy}xS!CV`10-dBWR^4L zmDJpGh{H=t$MZC;GK%q6W&~SM$%Dz#GIARIwK;kY?rZubH0%;ftS{*|HcSlc-zX%} zRI5l95QQX9mKZ(BB#^MNn0k_Q6umZG_-PH3V77oV@|3KcR|X0&UJ0Fc`I^9_+)!RU z1)({ooQBXEMzZD3?bAf9@b@UI!7Ig#rSvF1E!k}{s(_={7Q2E<s`83LgL0RWObk6z z4Z%jI#tKYH)rQytvT4}cdf|Gz!i_`@bFohOTf8>3BKJ2-BXVyVBR|K)YDEvyN9A?` zt&`FsqKK87mSA+P4XciNinY!fmxjY;lkkWPBN(ll1{PUWMn?9u_${)my4R|OR5e(| zc8~L;{L=i90*m5`0C)<$7*M-5KaffK_ILSiKmtN503?9Y5h#&x6f}6+Nnn$7G>S|) zDK@y}WGITITLXLC!$>aF<b-1>NzCP8NZjS)((9H`lB5cnFM%thCeOQKY+iCk40*$q z(&pViE2AWH?<pt2uFOz0(gl2Z)ZrN#*|vzDURIyDMu|PDP8pY*cTeYMWkqLW5D`q` zoHrzj*?Y2C^VElu;H8X$B2x_G=k1MTsRnh3e0B5vpvUK*olm8s_WV5MOWarYSB|Dr z1~P?_+Ar#umbmopG*&0`59ym~_-c(*1ub1hrLM+6uSlVZ#Cs&;sn+rMMr2Q`vR0Z! z648A@4spGML%ABExc}Klzv~Z}rjUyeu3eFMP{j4l(1u+7pp^#B)VU+sc&YC(dP~|u diff --git a/.next/static/media/c0f5ec5bbf5913b7-s.woff2 b/.next/static/media/c0f5ec5bbf5913b7-s.woff2 deleted file mode 100644 index 3d1a12183a6f775825606c74337997d611f60a2b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 21960 zcmV)2K+L~)Pew8T0RR9109D8U5&!@I0GH?h099Q80RR9100000000000000000000 z0000Qf-4)Ia2zT>NLE2ogenGLKT}jeRDn1Ef>bYT5eN#`1ja54f;s>&ft)@8HUcCA zgl+^N1%+G(AR8Wy1ssQWJ1}<bd!H+cx}anQBLl(40r57xC;R`J+#G`KpjP!ikjcob zPRzN`oGV4%>dCfbObGiR_kD4w_~bYAYeUc{4;+}A72POns9zj<|3U@6nIz?xB=X-; z+DnUa8nukdsw0@LMS>mGa%8*2t37(V5-k{pG5N;dW6!|0kw3}F>wix=`_6scYPF;W z2@paAW03_TKx=D22Ej<J1{xzk#%+)>7#T#cN5%}uAtS{1Qh(WBY|i`;GWB!hhwPnV zYne=W7~TQtRs$)7B7`0wC<;iZf(?3*gdXTNY;+3<Q7KIbbdeIO2qCm8O)M`UNDx#I zDNS6!gMf&+6FatthiI+dSKU3ca~vciBllQ_ouAqb5G!Ee0A*MM%H-?Z_3->}^AB`^ z3tsH1SG^+G&CuN(E;3Rws;i=rQA497qohX38WkEfEoun#nOWm4YP{v!?6c;YuknhN zEBANJ*K^J_*X(bNidWQbhDwDt|EOE#*6gkA9KE%_YooW8V~$!<2oTE$0)~>-wB(f( zqog&~z>5$dLezpeUclgtQn9De7kxdgH+ksY+pA_q?`^4eS^+eK2cke}_aB>)0Dzh< zT6j6enZE$9lctlD(&@$SPj`{2vS|+p^JnyrV&txX-j@IM?_8#YIb&VM3?pMk#*{W? z3Pk-FzrFX(A{q*WL{s(mg=AU+i9{2Rrqh`&e*4$jZ}+a<9$73|W2l6pc?FZEx}ia- zglM6ty>;Z|ONPWxuhV+M0yo8BTkCGS{j1mS-D}kvxYD=u!X-*0c%wK95wYTkQX^xT z$RI$#05TrWsOa`&qCgRo3%_q!>zdiXRdsDd2~-jWp*9jy?CMXNS>h~baVf}@g+gw8 z4|gcA{5(3f_r8RTN5<N>$N!QLWOQ!dSX)8@6Njd9LQ}6g@+Ll#DmJ#MOLAmW7std$ z#-<5&)}mvXzc<xv|HD60i;G-EI75!mode}mU&xhRxpvci{9T0I&!rZic!T9qCtx9- z0FXQ_0a03jqz)H214`!<^8zd0A&7GzL0*C`@N%r2bLq~N+mKp!otxI~T)KDB6)tKU zb>?^`8p{MEiy;n4fc}r)w&1nr`LyW8nw6;+pjK<G)fgJPrzUM{v;4g!k?=?fb>{EK z^yQAwomc7lbJ}0OA~A??43(s&*(~Ew2k7AMk+mB6$PYycxX5Nv2KS<z*i5h{sieN` zJ{kxD3RUSJDDWUHfFMPlU?D4SgTm*-&KGh@F7O050biz^uXLQRQX|!YCp7ScMgrca zMe>6uoFL%av`d}f30*wl83I14kMDPykBRX^hWRr_c*7Wf!33W)!_QmbS26g%b$des z;3VYM0@|Ur82bzY2>ZYWfSfiyQ4Q0=61@pO8dxsvXQ)aL9k4Nh_yU*n%M4(JyK7p~ zdSeF4PR}f&3_Ux$ya)%2I#rD7kYqo*kOu!<U4GY<B(x>`TiX96r{peaB0Xe(x*;TF zLjEV~X1~>U{624x1uE{#^vPfT%IC(s4{ty+R4=IfzlCp_Q`oru{!yW8ci^s4j@PyV z>y5gP`QkpF8@oT?53${6pc=m|=kVDNZEm%GxVIHrqyu*}z=5m_y93VTz1q;>gYG`{ zp35D$d{zIAUl}^v;k|~Gp~ekn!W(m2^+6nB#yOK~QcO6sA&a_h5{u)T&JDMAdrbY} z_dZ~b_6ams5qPio$p5le=6`gl`zln!?Y-f0wTCXvsbO~Q%vKQxlW&4?(tBZ;%4Im< z<E!o4a7U}M{NJA}N`yUoLk*6N_Ys_YnziT@5~hk7^ulcy=eUIP#$7aJ&hyq8`l%4R z3I+8@mr#79)hrr5ANz(j*!SRvK4im3K3*?;mKg~<2Rw?$SR$L9r?YVeyC7_m#HJEF z$L0ku42w|9q+<w>O?5^W5qZEdeLSiZfG!|pXXjIPL3D<&vcz<lLCtOjN-`DT#0EPD zHo9PA$6+gC%^tD~dZOw_0`&1f=P`6yd=#7jg~&R?;1W-6V+a+90?IKAWo=lfnH{7P zLctt}%o4=W4`ktsIGH<eqaXMx)uVM9G-`d=?}R{z2B)OZ!XhCV3``tkIA_#Y7?w`D zWcsotWp+5^r``8g_)+b;2vZ=5&A397;f#D9T-eR>!$!=o16#0yC0wAD2|y_i9;H*@ zi*)i9g!ocjJVS)po2pqc0N#ukUu=*$L&#$bOl-DBm?JA`yk<ihe4+ci%U=!if#IpP zU<nh5rMAEr3X9rxVVvRdu|;gh3N~X06WWMfSimwST&#!zGi@o(#{y=!kXcNYS%YWH zu!%sLjJyRGnV<m7uyE`mT(CkO%T@scZL0u*;RXhlK-38g0IL8KW?05%Okh#y0<6JU zyQ2&jMqR2SWb|`k3g86#6CiAVmEA-DUceQ=O~5Bp08nwqGXS)8a}ebeG~xT_ouA(Q z>%Cvz|LMb@KK|v?^5^gGeDKAC@BaBg{;=*t`Im3~>b+mT_glwa=C{|wzi3B;ZNHy| z3@~0i%#FX{`Ah%qF#zzr6~yla@i7n|2jNNJp9bz(U|#_4WuRXL`gOqG1LR|HegfEM zAb$hww?O|0@;`w73(f{6m;j)odrIf%C!m~vMN~&If*whPIND5vN83E;k?g^bW<1DI z%mc>0$wjHgMXAn(X#%A4GS@rmavh_ioUZ`V%h~a-g|u)L6s@DrZr(n-eb-By+|?oH zy3lZ~sofA-j#JDHNpT|}J{>Sm1;pn9<_k^irWWt!#`N`#>XyKHZIipT5#1UPzt<9^ za~I@iq2!mZ)g>)W@D&q#B`Z6J_npLNW~QZKs>#da<i*9Y;{5z5)SEYJp?lw2c6MG~ zPR@=iHm{H%`&#^IeD3JRjwQwjgHKXQMq)@*G>gd`cpo-K-*_q{l$tOhcdb1e`=`Gj z1S|p~!yi&s1{dOI(^IFOOmXHHGcx+$C3BNr#INpnzI-Db?D$Jz^Y!UOz8Qo-xCv;p z4j&UR0CPRI7y#crSugwq`cN4Li~yUxqNCu%$RiGJeJdTc&13$iD1wbEOqBiwR!Wd{ z4`moI`Qx4EWCc)*-JD;@kQlIXiy6WrIC=O4=?qC}x2)p>04k7zi*-f5#21GIgmW?~ z2{&M$xO;19gkfEI(Ul&1c-`?z=vCEKkBc~n@*mI-Ry%XvO;31{!kUAlnm>e_LY$CZ zu^OnCDnnQjqJ*Td-cu{8B~+^q3w`wy94dJMCnS6iJd!HS4Y3}o^kyY)%8=<Ymqkki zq$#kYNHfhj3=%qp*x;9sE`{7glsT?jm1oomYv2>nNEPMO;<RBSMqSeHpxPM{cg9(U zTN3WM@4PnSE|?@Q!$~Qp+|}(dW?H)$3*I8sI!nF!%vzO=DMyH$D{fkL*NQcfvaXR} z?mw3&Ujads`)jBDO$w4KjxlWySRfAp4yhDv0RafyWM{aEis-ip6+8H#1h$|QUPk3q zuMs+iCinz8?iM^y#n!PQaqR)@AGtk28fUY)3m-gTJ9P;Y7*|q2IJ!toipqkI=c*Ak zkXcgY{OzcOJah(jl!XidJq*PZp;nZBP>Hai2s#C`f?W)lQ55^=0>lNqA>z1nThvJb zn1I0}b)}|CVMdw;LGeMx|FAS`qV={}3wSJX;T#J?EU7|zt+S@bsLZRP2pI=j!s*RJ z5uw06ia30lPHogw6LL_`)39PlN5_%Tx7s{YMe0#jaMr=v?|#L3mbXk^UjPv&0!M-| zkD;zSBMr~Lyi|-uJecitAtdwQNB|c`oJ9arI16Q}j8c43!rMivhnkNZ+Gs872<qcp zp&J0y&DHnvS+Y;Z24`9)o@Uw-XyApcNs-wocR4vC=n^usX371+$D>dVh4bHPGcqUX zn92~3d@<<1MJRu@R+81+MY+w=qR^V4jYg^YM6#V!+Ep>GwklX<)CIjl<IIpTkkW=l zc`0_oW=T<KEI0lKg+==kH)}8-2c;A-!B_?dj*K2_Bsmg(_sD)3AcByM)!dCr8p8Fd zDT8#8?6{yb<j7j2BLAFYAh;TefJ`GCJmQbH3Kgz?T$qTl2|{QQTxi3J!s9HIZ$_>d ztKJ7Jy5W@A$eA`cfb@~Z@$vG~7-NKb1|Wv{6@^WHgz%L0R#Zr}A0-|pp*dHYT{eG< zh%3o#91A#Rc$I04jK<kfi1|^3er=8F;o21%{-w)e+h0smi!$k&wV$Zzr55NG6()0m z3F%A$6A89w%*%ZK6+u+x7y54$jBuu0r6%RKaQPuei6)WK!pB+A2bm}4mO6E{bg2|5 z#MaD`W;MQlE{)TK|InntjvimW#rr!C&Kq`*eW3!W42Bhcm*4yo!B9o%y$tn+j5HVy z7E%j(%gE3;22tp!AWV=j;F(J0Fgjl^SSE<@42(mwpJ@-3b|J_ZnJJ|jG?ciEtgIsL zSBGkZ?8aI(a=&SF5tIcZXrT|>xU`M(Vp_%NkWln%20^A~M)Djf`dRFR!da4>IPA!* zk9C3d(H^KI?=AdgS>jk5Ehs7Kq(zEKE67cmF$kB-H5k*#Bz=>q@-j9`a@UYkY#kh} z(Y;v66gE%r*y};3z1N0`*u$RVg?a47<spU~&>2~Pra1UiAM*ZM5lr$Z`jz=p!=t*Z z(a0e;C!=jg&)`msOxN#_UC1o;A&P)M8NdvNQ@lw8wa=XEgR+3OY=#TUr(;38%vdl- zv2M1uNToTfI}3SjcEAhoxqu=Q-G6p1He_sMkS3Y8x7@|rbHm%BcmejzS7f{#6f);r zF5LmKT}xTXOr24{uoY6e%rBkGJ5-8I{PN{Upz7?IA!{XYDoML9DW)Y~RI<P--5ccd zNA)sl*qf?;2-xb(EKq)Kg6L!C2P3!Z0Ev?R>pfAUWQJT0l(_8m%#=vH(&3F4uq6@j z*mP(&bCQVHH|)uI2yHv8aBf5FJ{$;BXX0{dNWToZtFZbNx%{(|re!Tmvs_DF=_z!> z(4$6V^!Jf{)(yCDKl1@DsBiP$ISJ7!A!kQ*aVPb5x&IIh>9j>l!%_)~0J}?SI+({& z!8jF#hF<k_<Fb>!;3m>h$wIZSx<6>#H$AkE1A_1A<#4HQPDPWdtp$eEqna#(3WenV zq%`2ee(+)zYeo;4GvsZO_n5@ZoO4IjqPK(}aT6{?LL20H$X6Q6{@U-qp9vj(f7kv@ z^zg(;9qPcomqNWmiajond8qplAjQ#0Lnfu7=Ruq*M27Vw^bymp;8p{!Mat3Zeg(?V zX@Xy?(KzcG#38BWw6qvaM0%6zuS@M(s(AzLp&OuPg~ltY?~kXE{e%gfd-H2kzobsX zvUHEBYzlI)&|@EjNB}zB!AjPGB4F;=fo+HHv!3Z4j{Ula9_Y^vLX}0QjCa$^t5MP0 z!|(m&Ztr0dB|g2YrFW&|%iU{@?Q7~hKDrDLi!Zqv&6H5^b~A*gvOi9B2Wa4^%zCox zwp-~#IIi!#!zq6ekuHLAQtrtJ`-l9UA9270U`sZCd&R78-HRB%59jx96}sN41FuAB zCLn|z_dJLIjFB1X+|=&}lTJ4k`W%;)I>YJ-k6WrNzWFUX`}4y$ye}i&sTVG`aW187 z^^edyk6$VaOzr9(nSwAMV=M8JxuQ6zOW*&TR#)3)At8{YKJqU~-CSU$^u>q*EAPj( zX8g%R*jwB0msF||Q?cbn>^mUuJNV$?mdwSsDlhFGP$6?ELM+Yw{(RymKXiM=`*MHC z?J$KPoh*d)kcX@$w@fPY%^RZT!!G*cc>#vCij!v>$d(2V|M)6BEXf{*-|Ght<^k9O z)<*`i#W9&3^_ZxFmC~;j#~8P)y#fkOI<~}3a)sU}7$$Bh4{=zB27I-&5+82wB0y{d zNUKt+36w~yX&tamDH7l<Ck6UCgvyZEbPd{+QGIL4D_EKw>lgV7@SC(rv_<;<k&#W< zY5?XS{?KysM~bR~Y75ohb0L@yLQVke`Z9w0Q9#Ss`9e-}p6b1OxoUbXA2*TpnxQKm z{n61LPo4+Wb%H=Gz<;cQcmnJuJxN=>5hOcdH|LH|sF0{&3aji9DxL`ybt+&!h#Np$ zl-NzcCq~qv`e|FV%{NKNvePpA>HL5tmVO#JVGi&2SU9LE&FK%<`K@g<`yYNWR*4F) znU&1u$zN!%WTlU0UFC1-pbL!VWSlM_pMP80EhL%BnuA!_@d$W;UCQ!&)qf>lgdl>5 zNQngc#D)r3(=ENvSXh{1`9?>#ju|{{@%eAF#Sik>GUm7WUrA8q)g*hk!b_mI*h_G@ ziXFmL=0{kdt`4(gfWy3u>leBoUt};IU*c^ZlfeTlcw7<Fh#RpC1`=x)fvCVwWVM0L zAbB6<9_k7^F{%+_bag)|phiDPWUSy*BE7Pf_)gs^$5JU~wR;i!Gy}GngoxA>5)b}T zt@Z%X4JO(ZS)IVoYqLv)Dl45>tMhmSpT%+as|*S8tL2=?!h=2u2x6xp7@&Lq&+HQk z#9+7O03KHGL5L^f#*~HA&$s~W+9p;b1jL5JK(-JF_5jFWL@#c#d*O__zU~6>*a6F1 zcLsQ@&v{GKL(MghkvLK$4sog(Y&6l4jiBxc*SBw{-7i1pPH_XeCtcqzkGTc*+*=uG z`M)EbS6-gE@taXQSHGQ*{Zun+0~qc>QNUpnV8E4|mH(4E6?T_L;{7Fe^$)tV{I76} zb-j*MN5ZqdQskgxK@;1%&G@H`)jH)jNr9gP?Q#YOog|XgH_A0>T^@WhGDk?%Usy{v z@0)2jsX5%A^TpaW<|S3pSCLQB{MSqXa;`k5(R)i<B02fMn;%YMx;_U2EsFJrjED5E zZ@&?*>lFL-qNU`c(i-dD3aG}Nz~2B~pmCz{M^7GZh!%3|bWDqPVZYjw8lTT!YkXDv z`|{hp&&A#jF}1)dz0re3g-j09hrhYS568*R${%F;3W07ysh3Z2r1bpzceUQC&wDe5 zFJ<-UM(LFUkVG^h%t4FVm_9lGpgiJgR9D_bOk=GN?ru>;a8*?BBkG`-ozMyYB}YLk zhieW*fB1OjB527i&n9r~G2+aY3K@mU`@wUrZXrL?ygh3=d}0#1F8kfR<m=H<O{WhC zP;Ii2Q$@v&y?(KATLRT1AtUsV>T}0#A4{LOciX?-&9}fCZ~-3R0&LdL_-w#R0Hv~< zFu;V}zPFw{Pr&<U+NEc{2R167p2U0bQs2KW&cj+o$IWr_y0%UL7Kaf>*|wzKu_=vS zmhC99JW_D@ZlofPvA^&MmJ>-#cU@~vPfKY^cUem((yQk0l!wZuHD|eQfHtQzMt>Ms zYI!uoHgG(#rT$)=V&WDO;L}<Yvt)6jgAmj*lx(V#9CdBkCV@QGI!C!0NQyVj%6pCr zXl=z_WDiQDZ{g?9$Ca>qk^(%duhl&Sy8uMklRm*Y<&(!|i_eD^`0ae4-*Dhb^*PU! zIr`b`Xk$uIyw2XB1)d7glQ;%TqMdPvW__RLa6B%3sG=fNAWF?F9$>-UlsXi0Evtp~ zJ~kc(0PElZ7M&j(uA#Si`FDY%?2e2fRzS!bl@us&`ucWp$_k9W8kA-#_Vo2D_LO9P zJWd<++0|YU*7A?zA=>oSvn^q*rCw^lmw=ZPNH-?$wBoP6o%52g+54z{5j;Tpk0(=g zGi1?3>rahKNEh`N6D7TpjbF*0NieBdXfkhAdYU$)O;d;{3m$kim~ymSMm6R1xn3o? zBo;Uy;;PMd9!QODJ#zZG$4zeGtAXl~Nt3WIW^=OYrq#ncFFaAiqxO$f4>Z2_3g_gr zyQW*!OO&5#*Te?_<y!>-xwhtI;ir9dE{V-fQP&9e;|<LxtNl29`v~~@0Xb_9$QWS3 z11t=#C)pgdUMNf2P321?bAB>5d+)a|!jLhr;{28Fg!;Ckf5U2#V+VVQW4A11ANH}P zqM0j)N=i63Y7M7u-S)bgawpx5n?`JNC$v?jXWXfB{0R+6HekPk-QmBPjp{@<wRLC5 zJ!1O(tuY9-K3&eOQZFObyP0`Yk+~bbZrRZ;r}eyZs7nsTq%Q0y_2v`14K~U>Ndr*z zLnR(wOLuJ#oGhX!L{4qJf96*av6Dq64NXjF46%<&ep6yPe`(H3PixFeW0^{6&TGvX zPvHz)KeiUm2p$1vKOk=r9xvmBu1$%kl8S}UaZVR?e~i$gxvXcg?EEupD?HJbMRR5h zlm-dc@?Fsta1_wK5>a<k{nk=UDYf5Iw)``x<@<C^DliZ!5OCMrDXi>1_~QQA#WJtm zlPkv)zSFd%m+wyRYhu%6ikGiB-Ms5$9av}d92Ln<P$0CwT~}#J-;s;D6#$&#v;#Ob z;CLX9;wzH&J$H{SBAu=dqg?U6RdHHRrz^75d7SogRbo;Nc*%9IzUxZ`e!V(oyYN=b zul0%wvHFSJ$R58{7_)sujs@`d{E@XrNtwtaYszgmL^JqL$v@HN7<VhXM;G;LH3#Ho zuauqM{c^=M;X54PF&?(}<1i0!TRf0y1CeC4FQ4*iv}mJxK_Y8?X{3AP^;PW!R@t4e z-^O3q9y=O-oY5>2(3I4%?UK~$ow7FRNv~g-?^5Y{f^Swb?Qdta@~ST%h|4qvg(vva zgVSzz@uJ;tik_~EMi=s?i3Q-VC{ebnvK0R-^>GdU9Vx=W0w~&P=2)qjG6`kxZ_=J3 zxc+F4bckskjL!~E)h9dX935RwkjXCEl;_~C*Jo@|cCtF`qy_O=z|C+*bJ2S_ZF$E+ z)tN{jLPo9sLD)oK-%D|B;Wm`1FO&cpWd!SMV9%f_3Hk>3MoHv$$Szd5Da=m)hZ~jU zcc(c_lKcM@4u*U82AT*ladu95<SHCB5NC%CkoMmg86hFwE<0O=0;&CLN-`z!s{eej zxq&!x>{l%#m=T*g{Rd5ec73bq(#SWepSQ<-`x<qlR-izDVnGk?r6kbn?otv0-G-0! zdx8rguG?Z9^o=wWrhD^dt#)y<O@=oWo>vB~{+Ki@>(-W@Chl2XobGG>P!(ygw3*|v zc%OAc=T%vaennl3zh80xSul1XZ4%imxzRE9L5;?VIkh*p?oxftiZ@JTzD7NF53h|m zak6oUUVG-BT^Yu1zXoYF>>-D)@YXgtT75OFDL!!h;Nkmje!s5=yzy^46Zjw{-EN{f zEG?}$%ylCD`NIhi5t1I#AA+JEKn~$)G3)2e5#|i}QG+?Bm-G-BL4fA60urv=&Cab% zMo_Q>#&QnlA*$ki*eq;|d3(qo<0D$H%H=K{*U*x`;dr?>XM{mX0U$w&4}0e<?331e zYkrVWj)yfcu50D!Bzl6K;fY*8h^TV8fta_>1hm%SL>>Vx^+#^N^DPwBqyUs3K;s$1 zl};zsRh3XI9z&cXra%YwPc*IkL9IZl1W24YApiM6SCe}F3%y^A=#E%3el+YfVdMT+ zUU#wdy|^cP?9F&<<K|qT<CRdL`2BV}#xrW0@s=UJV!kiye}n#4<xgYnn%VB|728hl z{B*U?=tU2ySP0D1iCoqx5@%vUgTp?>CHCd$Nw$BxmezdT^;Hy+?fSDhJ1xyfim{1N z6=~dbfcxUykJJZ!Rv+9$1X0A#zf*JUa(i~U{U8#1$a@VXfgaFHv7pPN4u1Ym0>)ku zuHzZ93HgNbgO8i1T>FW%LMLvG=U|Sj+URlzHZLE8X+Y!HZO;me8(5UhSkLqmt%ZK4 z6jFm3d$Y3AT@EH+K397X-r%)_XUon?dGmDtL~|xjE)$BvXQt>kr+(wUC@%_Rg>yQ( z2_?mHk4Nw$j~-3e6y6zp{w&Xzaqj4)%jv|T#LuG{_mwSKR=6WOJiWXpAHyYb`4f`> z2cj<*yu%r@Q19$A4KuN+<%c!)g1g-h9t^FvxaBjXi2wo@E2jQ%{}_ZV`h8l#%wq0> zhCtr~Hew@4c}#>LA?yA(0Hz)!9()>eH_<XV2C%>b8%7CYQr?SyeWiT2n$ofeKa_|1 zj*3FuakPMgM{J>;cWxcaax<2eX0z4E&aJF_Cd@_)G~{9g@*XUxj^%oc(FO}$l}9IA zMKViQ;P`v-2Xy8WoGGr_SoT2NU@XVu-t=+@HaGtds|=0HZsQadH?S#NX$EOWwnAlA zQhyyT5skT7%@fL+`QyVJabx7T`yTJQk8At58mciudF(OYJ2QVJ^zWo35g!6MCus5a z`?+#Byl86n;{mmEdo+DenRTGNm)8{Mq{SJiTLRz3mTXX|t6TXYoTs*-eP7x#Gqk+N zvQ@J?{2I9<G^*0fXX5GDxjE@W5`oU3%#b79KJ$8I3VX74cIe-c{O!#?K1a+#w~)Wb zf?dKOBobmydG-b7%hpIeT_jah75xRT!k5$4NHte&Fxy!v37T5}a+xV^U{W^J*W`Z< z`3G{4uLvAJUCnCBqAbT6#1=2#S@8v_zHI8C!KpBn2De%`{FHf-_gvVSRD@H<LLVsw z&~d<pq<quyM09V4Yr4{&)z{-)ZJVD&86v#-AfpeBJ@*zLt9?}>Obuy}ONRgYulH6d ztSdgP3R>H4+rsYAgtPzSA0LsbJEmoFE=}yfj*g{i_y{m1FaTIR7yyv4eh*Stz#<#w zARdQ?%_P>j`WZi6&8LLxE1>3jKz|FH*#`79u(%^m#L34_!6GbVMCRed*YIsD#+jI8 zS)SXn@EBMy#joNicq*F)m`;pMx9K|yPCu-uwJ(#DHO2g+HBpI+jSb8%Su5uGi^H+- zu;^3D$}x<!qn4bA9bpM2mo1D9`2Y~SZ2jhxSB?k64hfdQ=xx=8Hz2y;z#-M{s&q1A zEjIBJ@DSb_9NTh4as>9~i-z-=DhqScYfC$4E;?Y)5}*$kbmEzg(?6Q^c6hw10k&*H z9-H#5$&lGA1Fdg|G(g&L0<hf!3zIB-bencZQrM(l*165TkuR~y>u}RPa&Rok75t7u zz)E4gKL-GV)$?0D9r;^Fn&Sa4)E?n96uJwLQZ~9G#i;Cbu}6j~zr)1Ggf$GN2f=z< zePB2yVEp=7gbNQ);6@-S8Fd%Bq|X2b(mPHKoM-qil~CzhqfNHs(7=$^&mvy0Suvq% zv7qQhqzqWt1y6<KaNhq;Z@Yk@-z0BOkRzN_mmP5Tq)V%<jmSspb(|y22~#&%010fc zsgz*^MB1a40eIXx+##2WqnEq{-BNnb?kxo0O$Go6OaK~s#|(`8f58UOv4C}y2A7Iy zH({_m*34$G`OL(uY$y4E1WCA$Effk%h1J3V?l5<iyT=XkDPoDZNURdS=YQd^JLa19 zJ3e-tcl_*l=3`4Iq@#jQ_(Awp2=@cdg4t@mSajJrQ=Tg?kxvv0EGsRWEQd-s)@Eyo z)ma*ATeOV|vC2c`A7zKfka?es@sC}U|F(Ua{o=SQ;|Cm`@kb}T5@#x?E7(23JCPGF zO`Rl0GC`6lB_PF=dM9ltZJl^5(LeFGOmxz}vc<BEvi-7O2}T54{1{HhIdVJYtOX$O zDTphKD{zT;q9U=H_*zj|k)Y@xIwcB8Q{TC?OJ!Gsk{#ho#1Jo){@pFR`_jbOJ)Y^S z%F4>)DkduRs)DNi8CNr6Gn)49-n(zF>E273VHETMgMkPXfC1I{0GwR#Gum_J{$c<~ z<}0N<Vw;Z#s;Ll7#9%;gCINZ>%?5z5YG5c30R?T_XU3FdTn8YUK1K>y=*v8_Cr3j~ zk+0lw40U(_tr**hi-!#$G+7_>HZ)*4!U6E60~^?Kb`>@@E;KWsG|q^aNk)ff=?rNk zxDOGeVkiMQjwP4O)Azhbhh=EH1&tp4u>Jdpd=tAOkv-eL^6eTqeQSA=E>CR`x=qi9 z`Ta^bqR&Ah^)X4cxR`xAYcHkKw$&6xNoTqpyMAD&n&<=Br-txnRgl7A%{K+VroJ8p ztaiz(8{+XBYYkvocRt+<srUC99^tEtqnR<JXNmruibav?+$m`Who+B7tS6>rAm)%~ zEvijoH%J)5gl(H+`~>Kx?8-kFRkUA-+69)26_J?E07nB=XiFW)JAXZXXR0Qoy(P*Q zP5jcFu}_-1bNANHKz)$C_pV>81)#&WkNf`vkjiT0#W}Sq7*V0V698R@x=<C*y+`^w z^O+j1aqzGe!v~1m+^Ypd@Tns0M{*|y*Jx-DqP9a{s}7`IAzTtxX}AzkWOKb2d!(tI z=8@#<DiD6u4C^b}RmELH#uICYV79{aNvQWvwb+VgSTiQ?&iNhupaTbva}av&ed6#Y zY+V5SB9{cKA2>2VBvd$ssp&lMZ!b5&vXkFPGg%LB42+qYa!oq$=$bc^>Ne=R8%1)H zsv!j*NpKO5myNBX?CMG6y^#(K$qP;ImO8;W3?aqf5?ISau}4JJuAOQbON~cS?p&ZG zlm-q<`@HI;h8$Ft=UP<8>ga?H=7BXz>u`(Q6s718JuyoCSFc#UjlJ3O)us_2TY$&^ zA%eD4<-pdiROfm~KzP4d3jBJK{t+{7?oUlo$ndR;3%_#M^v`jStVRlxwn}Xd%O)j} zW4iRtu@J*z!mw(4kf1Ux`e@Wq2LLA@;&B*1Gily=ZvF7~4=?5Iz$HwrfE^=seS<be z^12GE|J`R2*~jZMcA+qGLLU}Ft{a_l;I@u<08Cq^XA1PJ;F!c%7*aH?>pco(M--8X zJ*R^0Qad%Vs*to3Hg|5h-v?!N!}Y8y2k5Euxci3iA|Kx8xHoq8@C{e7oCljO-wc-B zjma}CWKDRQR8`@u6I635h}OQW!PKfx^G8pU!<2ZNl4v%xe1$q_`~;?UfuN$cQs?E| zid@s^2eVjFIPek|%T*({!|95@MqI#|%CWIG9p|U`!FQ>V{?r2EpX_+g+ANPS(%mlk z_~(fLD2Jqg(Zc3obs+iA{SlFbtLjHv;;9EM3ILp`5k)Z7fw5=$7(QI3fhOLX3v-AZ zW`jg~Fhjs3m{K6=`j)Bwwm-q!i%qj*nn0$P<v+2a2x6jKbYW9)jk4>Iy9Yh&knFa$ zc`GqfxECXc*UuN8$TAm*k2x{f!NF^gTL^s&M;XXGs*pzPjJw56pYm9i2O+f}jK5ik zBg?*2c@tpEz)2A*<hYs0ZvJTOx2=Wp5F|<yY#vvO5Cm#s@Ilm3aD<<?ja&lSJdJ%I zK*DT`Ohk-5U3t)9sOmC3w?sI!k2D(88ckV*ULub)!QCx?9Cu_=i?y}6|0Y+2!bp&T z$o)dl|1uPyP(eGf-Hxwb4<Bh7OF4Q1EGXkmfE|*_CUtobp1}xr!+qvWV9}}nP0ajD zS@*CnLE}3hdMqa8`lyqIMaVcAu4pt_wA*Wo&MZYG^urCq<)OOD;&hb`yWY5dRD2eC zsu*Kg<9P~(UPb&!8;<@(UK-cdRf2oZg`*Y+a*K@RNZYVK?WwNotz)HB+GfW(B~os1 zlxt9%F}>B`2kw^BfZ0{W$9E9_G^0%6#uwt`k<$ryN>`qQSrgEdo=JLzv-$$Ab2e~* zmk~bjB=t8aCTBMfSpEpzhQPWHOWC8wBR}y^6XDeTv)%{fKLT7J_lFZI_%su8zR`9e z)KHXUV1bRG>wE1~C+)JO%I7DS-?MJt9h8Nt-23_GOyE)<oA8u0uY4h(ujLlkN=Kq_ z-9EX=yR+7fUZn!-oJW1D48yu}Wud8RSRH%PV`08u_)OEeXX((3l1FM%ca_rR{d|=) zD7Sa#?RqY*^D~G?34JE9L={r)CRK*)J^4|1ssQpn0xeqqSr`RzzGHQ6-!%EwIVY0- z$oxVXGU_DW5mmN^`LQNtnBg`JR`8Ac)`ZD!6?!OSq$M@~zxJyedI5es8&qhsDht4X zYu{$VuW<8>ai<nCP-X?dO*zc(?8Qt7YcZPGoZZ;eus1DI`c!8P$&--74ebLVjb{lK z#xVN_INQCb%0hH*Fz?GWCc4G&S#|Ps;g1CQMzoGN`Op-dd0=F@9Z7o~^G-LLo{wxu zjy*HALb>yndf_3pB&AsHqNCOe_f0wBiZ3@hQ<zr4E!HPy`@sKnv8Z$BcOERRaiw!w zJwd=yzc31f2vGqD3M6FP4m^1*3E1$G*ZX1hKtFcXUuIZwj%+EAaHjJ+W`h!=$g=>j z7}li<Z;wo>Rb3G`oZH$RD_>!y<8O-!(d_lZBhK2n3#m`^y)gt<Rx4wf#n)GPjGAOc zNf495X7WUf?}!%BKK36Mal{Q4lhW1wTwvTINvk-d3D=q<x23fjIs$=Z!k>fHA9sbV z7vVIhid6uhDL^7WYHV>0|1cC`Sfx=Mtl10ixlux6-c~Z{?U!wh5HY}32MY6HQLK{w zC97`kx!xp%AL}@s(J_0|jNmB=H3Tnl4``_ocV`YEL+s%M_h@YH>G*(P?q0k*mQC`9 zSWx}5OJ+iYNm*9oso7BU(GelbJ;Tu8BtphHQ)pVlA+$47)F7$5-MX_y|5xi6IZ<bC zzdD+DulZOjq4l&es<EN$^8G@Sa9nWU#|V9*16K9q#AwZ<r1`bJs#M!WP*WQd;}A!d zd1N1Sc+>_8dS;j2c$m+>+h;yoJD{FQYI>KDM|)+C?xm-f-?y6%b=!!qZ>(iNPAx~@ zr+VRZS#Mc)IA_T0shTE9#7kGxOLWO3s!+HyQnTdymE!Zh#npIeAS(idLQp}S3Gw?O zaE4OfLOM(*ox?*2^H5m|ir?>&Pbh51QaO1n3J&k7J;R#)u8LYKyI}xOn_wm&C)y}Y z+8?kQvL>h_&cVfPIiW1{N9EqD*1#V4@Magd{fjXcLaI_!nZp)ceh?kIDUy!{s0qC^ zluT>joCBNcSm|>X)6T(Cg|Tnt_?E#MFqaGC-&|FnCYe<>&3P@WC=|j($sPsSHcbzn z6o<tozE~`bj{#X9@SwJ;oXfB(BuhKp0bk@<-5SL^6Up>a6fT{p15LfRM$o<m4AZGw zm&*%{xY~%RW6nE1-*Y+eb?i^&xE&ufzl!7zoz_sq+oSzX3l=68R@Dt3kM30|ieJQv z#I;i4qia)2-ee~0W*sH{JC^yFJQ~a_Z3fx~c~ELo{w=%ut)Q``&Q!c%k74b;D<{uX z%uJ7%pdj@r9q>7|?BWA*&_SQ=C*8ve6GjfGePue-mQTry8bTDA3hf#Lk}8JvQl_R4 z-YtMaOua+{pZ*qfFs%o3AZBD-=;-sCDA6M}13(nquaodC)AJ2LuHgIa$ZU!?zZwi_ zKr|p{MIoP})Le@H?o9tgb*ZD%jl-=!T(0fpDs+D&y|+g~A`1i?{sGG#A6@ejF9X{m zl2-nHwvbwy8gu`Sz;o;{gH;S#B9#o{e-HpUD+pmEguI|h$b?~NGtvGf0J}&0z6qs8 z6;#gKu!1hoN22^nCfPdz<pJ^eb@tl8<T1JP0b*mIaSGj3F>P8-Up($I<FAl&-5}3n zLM^RI_L4AK>K`Q}zd04LbT1&RrI7^UK^RPScyR$~A<qo8n~n;P1VG-90yGmGXqOdX zm7{NO*3vAQZJ{*=WWm%`)vlgTx#iu{745EJ_bEKl?suD-mQstnQ4q`I#eM*JO`H%f zpBOOwf0c5)(jtTZ3>5M*R_Y&LB!?`EqJW1jQ(ImJ?!QSb4;-UG78)Sq8yzG$S+;xv zXsBo-9m3Y&{26+&21sZr27V)m6{^h^(t$b|6O!Mwc{Gt>8*G>^0T8{~gqzwRoh$o9 z)e}YR2ia_4f=-xaPa&RfzTUD?W?G*Yt{xw0ZPj^SWCez?*gG^Jhn5wek0yUOd5kW! zWw)iZGZ|mB?J*4$q@WB?%1K`mhvS1fBeS1mb*}btOo$?56?m2N6&x<ofsKYpL`-z} z<)8w&l&Yn=94#Oew@bZWT0l4jTFH@+STErj-iRqW6QORATwRTH1e+>k96=F?O$R%; zb@F<>{n$=r<D)VW_smL!?QpnV)ZCxL_m8?CM~_yHCC)#?55Dz*U$mazm}T43ozX!} zRdWATWbeqD^&aA%RTqqK1Is9x?ydYjS)ZIa^tmW1F`kdsGV}FzQKvZ!KCmO64~U&S zaXG!U<o8nZI^1x<iwuN6Q-$SUt`~(BYv<L|6Fms)4v0D9=VsA$WL8xo!Kxi^>jGpV z$H8-oy|Q)DQoO5iih&b^FN^X}bh)SrEko31_s5gtFcc8E-K@eTrDnEC0UFD5Q>5?! z2pHDDhTFioFul;5k(nV8m$r_(cjPVeV675+ZLN-ViWN4cVH(wxweka8&L!8vuV4sr zsWrq6q2(pY*&RQ7ssp+1K8R``SiVXdvDU}*W$eb1kq_@ze%eoN9E+orVwOdNsH8a` z<4HlAc06LCKyywCc$K21>b8@@G!$EU91Q3cM1E3-My0KBg<-f+D87|O#$I052QlYi z$Yd=K$xEoUGYnjn=K)%k@%!rWEiNQYT0R7|P48oa*}rZ?4C8Ybfa1P;&puhIG1N?T zG?5AWsp9hmhd<$w5&I|*T4+ugwS)cONNS?Z=peJCEPm=l2+>y>*4jX3cVs}kb%~y7 z@vo1}yf)-c2Y|T95B~mYA^#u8!*s)4#3tKtN3qtUp3C&%xO=EGt#??q#r0|KpyyOX za3a;57ud$!HZs7jX%sBFrf1Qz6h^iwy-valh4KQTe1d9~+XVecGpjjJk$&f)^9;GA z*bq>*4VRQ-dHMuGOHE6~r><O{aKN4AV}WrF`ZggR^t;77VE_0wDVnn6VHkNEh8-tn z%=T7++o?LndM;UIYjMrboT7L^=0t?)>i3wP+j<}P<zbf+nl^&zWIMKEsMMmjFmlr( z9YeKN3sq}(ETInA7Cw+v^v2ox2R%3@C2mBGXV1|5M2{+)e|kdxZfJiCF4k1X%Qw!z zE3R=9hEk~<vc4$GTI)6D#j@g#(6@z(`6eg-T_WA(oV4|@^sm>hw)bEse17d%AK%^* z?v8fFlgf+K(jRs;P|-A48lWyEr@DEe%WiIKr)_G-p54|W2Pl>%#+t&>w}Y_xnmkX; z0ihfh2v%Q;2%aCf%NHJuw1p%YwY460WQOwRGs{bTGxk)TG&R>?=zBx+1Je1qr2|IY zNe4k492e2W&J4n}3)B!&fmK7N(POJ!_??Y<-uWuCs&<ck@2JV8y>Q{4CYO#{^*42i zK*~>U!}p22DvGeK=Tsm4(e4Y!K~udYDHTz?D#-D-^_Bv}&{$%eRE@#(3-O6{jukYg z()#xnQQ5ftA5_KUM0;`7RMbiAeYahd1QB%sKjr-R_@}pPYn4ej=V%h$6Q2K5R|oDG zO}~P<VHnI%l|JinaFRihCV~&0s|EV!h9`7jJD5zAz+*V={+a=;#3oc*1_>Z0R?tse z>|5JZ7(U=QKQ<`Yjst8QuOu$^^EWwAU0lDc6<c%eP@c-8#)Wvtm=$*MBqUBy+z>;h z^+s2XL3R7*{YJiq#{7NGPz%*ouXA8rxACQHbxLWZc52H;8_e}*Ytm5QFPn*11H~vo zq~I|FMA1UBIIW~fxE^V=k*sXCa!MxzBal&SY^ee`xar|&0<E5k`lEj+heA`d3xQA% zZJ{QW7Ch_h8KKJVk9|}jnuqq!M-m!*^k{!ONuo|1#-eb7|IW|M&3$`k<LpI+LiDj& z3oM?_HhQ1C+S*n$%>vTU?MX0MYikD|X4<c+myatS6+U{lvaJ5m`21UpiXDu#!Kzls z#Jz|_QkUAC?@T<h9mKBk8aqGFw=B2WhVc!9wJ;Nplb5$c_Cdb6I*aWKqN;ZojmBX3 z6U4TMEO9N8JnG9~fB96TFbQZuan_atHLAcNHB|Y+VI*}(^%=uGa6aW)w2EtM)jmc? zy$CJJw^=ut>KfWEZ?_L}Q6M+NClF7jBh$@mP0K1ONZ8igTTuShgEMqz955ephV9h} z^nsB}Cj~aDonCz?KS)=~7>$dr@|pe#Fp2}PMmf|0JNOq3%i18CZEEwJ@G7u(rxiJD z`Uh)i+YYOt#$fV)wv2!ERqJ%vUNxO~&k~jL{_w-uW0z|^TC^@q+lS&Q<2km9iimqO z_#w3-qY-uSbAIg=t#TcHdo<iXgnp(arqxys7Gw+M$>FL8&$6ZHG-$UV;+U%`(7<@s z>j7c6I_K<tm#cr2ji<6}q=wS3-}O0lM$!C^UK;>Q4alXUf0i0D-q27C5^%CF)t_Y3 zXJ^KvDZHrdlu6(4yq*)8?TF|S7RYX!XZ3^vf#%SrP&JXfbbk8DJ3&wrmiLh;VQb~t zh&+p`WRyxt&chxy8TLijG%l^{aHq<+U>QxStR1y4s4@{qtW^q|Ag@Vxs*K3P%X|Y+ zM`qlIcV=d5TxTUBuyHB~V1->t+6Z`-(HSnw<S2veZ4OIGudMDNrTp;T1#M%{{XBSk zVR?C(U7~jNCIO_N6}8F}wmWBvP{$NhBsjJ6V2-{s-z#U&PV70$vQv3X08Ib56?iO^ z<nWK1Y_+yhB~2z2Pcf|m9a0sV{8`na3|c~4nSSEJ0P>xm(kl8Nc9U$EyO>a1lN-wb z3Xv_ceJ}He9UmELqSC=R>6df56xz@1@@)zlrJs|>rbv6S7;GI|xC0Ev`rSbbax^On zA;UJ-B~#ScS|!-txINJx9Rnbrnj-gFoy=bYBa}yAG#C5^Yann!DIT|^iHoNM7yv&d z)Ol6;q6MP?og9MEWM|A#?1)<+y;Pf#2|(N=RzvtUhEGM=bAm*!1lC~$rXT56`pCNg zA)-fLikn1uG$AB{0cx%%`$tZnR5o_$ot}k!4(#vcz7^GN$zMIuNTj2)x;Z-gaouiz zF&0gS@?U@x+hhnOegGf;#Iq4b{c2!GS`@6@R|#a2;NPc5&)u9X|5|1gbR&4Zd&C^I zW8Q3f0EAm`@s^`bXe2p+g)1p#-^+~$01E-F!s5z3TLw4$KgD?sNu5HBh|nm)o0%H| z!fC=Cj+wQ=;uEm;b8Hk{EHpxECGkJwZ+}-MxvCp(p>OtQHO;KFm)&l8_qy<_8BNnA z#hL|k5};!@f7f6bdMB3;&C~Q9)b^q;*rW2QgaURJzDvLa3rzW8rhC43po)x)w73Y4 z@Bc{Y_r``}xDF3u*I(5$vl6o^d%g&irXJ05H~5J<hHAf7-Y1$v5u@{-IX~BfB6<L@ z0e^alOcM`6&-^f95>@<?UgYX417IoGoEM1^(@u3t#Z(m<IFe>}`|Jq6Xgd3Zbm}N1 zj`W~Od;4HNd`<MDSvEA==@ufxwrxeH)RBCyNyD+4mx^rHj@Gdu%_gelCn(#)z-oz; z9kLLx1TBptl8I<=KARc!kf+76y&ChXQj0N{v<_3Op`e)-O`i=QMNPH0#=Yp#^3F^} zbBekT)`?89DgDXl2L}ij-EN>2Bq@-;7aP!v&FJ0;E7p>Vl(@(ZnU`#%D%)Q_<`*}N zTBA8NDuM}iNVVGV<zE+;_H5{=xhJXX+cg)NJ;$x0P;@ag)l)n;_YSpDb_1GIoftT4 z^PyW_S%XA~jFB>{0@2G|i~KHAY4lykj?S6t#V9Zrhw_((qf3tQVbvM9RSUyGD(RFz zfRk$n0g^Prc}%HQe(q_>dSW~ObClhT;*@(}&YWwTgj7b65N`SviZqr3W{yQ?h?#cm zp@wRjoGjGMA;q1sJ|E5>Crez+28+fV>0pKnK!%c}c3`j;HqT-C((A4D_2sMWm$oUs z=oy=JG4#|Pel4MlS8(r|+TB)JTdJ44D;xylwH%b?#wR#C^%F}`1m5}elylvj$nn>z zTQ*fUR0sP6=mQOJrp$wzq{&?3V2Cf~P?J&NrLX(zN}g==B8L&UwBWzf5>Nh;q|EN? zW5wc5am?A3QuetV7@PuERzc(cPJL$wL?d{kZ1y3?pRziNC=sXdlG;>98c>YSBzY-{ zpa@3yJ)C?1Y=w7K`DLq9%g9ob&ZOM)K9fyoP83>r!gd_1zqBT@XQW`9co_dQg1lVq zTXX$>847axSka+8#JuBIGM7)csmq=dWV+oVm8r4N*zub^B@CWt^N@y1eH~PAKHmp& zC73f&{Q9lg!LiI#FI*1e@msmDf?9W`K2b?<Y}10<_HEQf_ZuRSX=mbyh6;(`q7_r> zZsm>J*N{nB42GE&nV#qw5d&8cj!_Xt$jBxENyZ2b+R9Yq2of661EW3$lmQyh$dSZV zZgwS&+YHF^A_x~8A!`wvO`)<{vIYPz?!~*U+;Xo9U@{uK1?J2wAEUxI3w1mu(@z8! zkl{)dQw~v7PDP|68O<UkN$_Kl2LTl=#_IvV>q(>&v{`9Hblybp^B7>Z2TDNGyscw% z<4aA)2Byv4y>m~6OAciBQbwQC^%#vV@G0$bz{_fc)?XIQp$@j){XGt`Wrb+fYL@o5 z5RTuU-D2lt##?gHGvp-&wz=jq6z}?rlM`y?Y}f-|?TUh3)3E<j8gMc!p`tFtQ%cT( zI>Ey~8wekrXdZBYlUXgf;1x1R-<>P*-Ho~U_$NdmX0W^M^%1x{_T(`^v%?<leX8&w zIe1sQs%!PABMxGLT5N(<$F|{0I+e`s{$Y*Kf*>-Lkzg{mylOVrTZ%`=nUp>}ZZl{$ zi)x9c9MaOIqgp0iMPow$mzCM2R`Kc0?N9X=WwZJnSEysRrS-X*?69=C9suDEkwA5H z6o14nCVii6){qo;<%|`YYQ(!yEkRUI8ZwcYg>xv4q!f?ecjk&%f5cKcfrrrzDU}u^ z`*x6`R=jec#Sp~U+Sr)#8bb0a2D*N(4iWzC>hPFS-^zz}UCO-c_PAvRGc>SiA@a9I zR{9{}$)a|X9;sN1NCzgVB#X<(CUU|iCD9LuRk)RD0@1O7#4^OMEY8L_fc#ffag1fl zOO{!I$vA@e`dGQ=pFaXGJst%L!!n?)!VT`f%@p|CscnWw$?D(~Lnl2suob^VziTJZ zS?Zejh)LutDF$EJ17oZvVqk;Sg#ASsBnC+&-?(7`2%n}3;}}QqH&Pg7)L!0K>l4g# zod|gH`8PtL+I<ZWI_J{E4=hj}vj;a-x1#yjOx$r=xYO<3<cwslmJm;|sE`-#4JrHR zpggG{`gMvVP-dsLMkU~4Kx%`exmHRge0LhK-z%9gS*7;(J@Kp>#h;@p6Cp7N{4pwT zqe?b(s?%%5uVhc3tvpQ#xhacsNx^EqMqG5ln)U@gdU-5BV2{(XVJ&U@TokZxtBiFa zO~jYVYbauuG%IgA*Ty=?aLvhlLo@uRN&M|;w$nN#v`sN>u}*91y@ZtO|8eW89J#;O z9KpoqQ@48`7X(Q=SCT5CP2kaGVqGRw!q~m9$71#_06Eck^G`Pkevt`Wp8ah0-@(rj zF%F(%LENMUKA`|`&1*u8$KUGDu75%+o9EJzO{E>q-%}g=@N@hETX0lOvAAqF%m|Hj zl#M7BL=?i6iadGj2Y3qocs5C^*NhM}OnzASp0$SZ2}KX)fMxtMEvl@><9W}0Ce=0> zu{~J8TQ1wveg}X5SaHeMz_b7NLSjE6()5GK!@T@Kl=9EJyv>!KufcQi!y|i_$v)N? z!&DGQycPiMeJTN!6>93tNge~3uzIT4hn*1$R_gGPc2j`^5hRcmH~+Fstu4wxG&NeO z-roySa*()F9U-t`*_^q&-6OoSNM`*tJv$^zsMw3}dbK`=#g(U>Gqm?q@G!2~jCLMf zKNP^MZ(ora++f9GUz?GauZ+D_Oip#4qu2#EAYxnNm73Tei8Ft#dfSQismk0WbLQ^# zboy(9Mk%HK1I;b3Di<weut*}yEZgZac3t-C`lycJ$#)Fhh6jo_;}m_J(Biivd_w^s ze*inzBG5wuV3&)&(82OAHZo|cA{Vx89DwcPAVw1+H5busn1{gh1Pf8=IP@X8GEXYq z&9RbVkZ%|zb7@A>QwRQd{Zo7t08$nf<+{bjAyPVJF*kiiJ>KDWZnD5r=HA?Qoor)q z^R!BbpaRP0LDj67#~cS>0Q?x;YDOkJHw0Q&fc++S9JKb(kEHe+gGzhjfYO{5LIc;~ z+*|UTfdP+d_0WwRKg(w&upCWJR0Sy*yZUbp4&yb;CN9+AvA;gKSO<ngJL{ZFG?Q3V zAX^&k#R8qwRi5YwDNk&)tZHR=+T!ux@sH?fs1-ykt)x_87)3Z%%kw_?ZH(L(_tH>* zO}hc!Lm|@>QW!!G2sEAx0Jg=$^<>4S-;UwUku{uwFP4YaEy)ZIMEAYrSTb9%mi_D( zo!WdfdXv;G3R}D_m8GyGmHWvf>aOX{FwN_$MloHXgwblyGA+?8%~6wLW*an{M20L@ z4mQ|pPle?tZNJdMD1H|N1cNQC!P@a?cGmwHcic>9xK(D0e<kT>V0K?#W^Ag61%%!E zB1(g(4i>_UHf$Mh3re$Jl}yPiY0r^LrW#W>CIC@rRaj!Q;R!s5^|Y4O&{EQpoLaCC zui!l#^zfKMd-zv?K<*v%skES(F^fKRVi(KI`<^}iAS%5o%kU-}kg*0!C%~hC+jgfW z`7yXfR0_g&+n17+BU~yC1lt~vu%5Mo-E)S$yART%Ck}63@3Ei^Q1Pe4>9gWO8HK;s zg@Xa-{tZ_;lKe#~i!<vH>+$N?h5jmsgP(uMk95V3af-^;c|LlD63Bw+jTKf@Oieij zs1>ad<MC6uhl1uv5)hXpa#0ou2q!`gWRvtHjq5{|LyhKYI1&gol9jp;^IFhqL3IQg za;AmKGF?ku{+TROF7fDe5Z%Y37=Qur{;D{H%(1oQ?WK@PqQzusQkSF6F;xrZ2X(N& ze9`x(CoV6{7aU8qhGEuxC96rBsg2G4{8DR=<$7J|mo|&zJ&P(1`+~e4;<LfdghwJA zqt`=CyUy^?8^r}*@8uQ5^U7<*OH~DAS2b%<?^7Llv3i>z)uMWNcIWv{pCc6^AMLh5 zq(0|#@KO()rCC;S$XR+Fz~YO8K($GW+k46HWQOA!G-@m>-UonqstPo(pekWLWLZCT zJ%W}%nWBp0;2sRf@}zYhR=z%lMyC==42%+-_A8_;gt6Q1NZB`VIE}t_0M?JSVGysK zbh&n%>;;QPN+tONtHE$vbF3Ls=0VzYJoT|vxz+GMo2;aYQ<DneH)Lbcqj|~kko~_r z!D_uW;L<D!W3y1kD<m{i7}xd?6%EJGgwZvmJvA7-x{0s!)f+<>URPUWt9;nh+Dq)m zW5D>#ZEd(?_$5*7Q1;zd&j<sqJqaPbl>`es#0w2wg%f_B1CbOk`H5un#Rz_Y^AV^t zggmfSq?FwUTtFmI=BHDuy3k(fL6vhXOXXh}eb(@D4gv}}h5i%U!kLcG;TS5Y-{s>R z69T%E*&&-Z^47-~PWJvEr2Tb*-9Nr^x~qS5j(Nx2`Y3at$DZ0=*yp5;Vn>Pi!f_~z zV#;4yr1M(<`w@8b5+PJifV7$Eb~r1{m4N?pH352?N$FqKXpxlo^S3fg4`vSwK?%@K z3t>~V*c=7Lpn{O1EY&r2BqB7T&32$q)UuRlQShko1%7nJb!$rGe{KV-LL<UbWbxM5 z*$WuB#hXxOP1AQqkB@#jdLpDwjb59gg_EYkAcaue!h*RPH(~{_wdcR9qC3RgSdh3| zwZ{Hs0oAXc6V}22*HVU-5z0GZ5CekS*1l|3x~HecA#hPVts*3*Xu||=vVuD;rSxkq zS4Inqb$CNAtN<vflm7hwWjSxdBmxrG`2QbG<BJ=LCPg~X?m<eK2FS+cLnF!*0ofoG z@&>I3=2Y^V3$u(*YJ=%i`P?!XHaf5ZryYG;hlZ8^ZS-Ipe0-Ofj3larMj^$8#5h_+ zfUK&Sj<qr^LVhi5OCIBbUZF>1%Jc(KRERDC{ZX(?Rv5uHIXfAqr`uLcSoH;%I}$w4 z;sux-%|MiRQe!dk@ZoL%m<1I)4;GII?LKZy)My-QohrQMn$li%HN~@gXZ*Fj)^Kc; z8&>VA4yrM|Qf932uvy_eC*s|EK@4QZ1D?0PSr+Got~e8c6Aw?|uF`<AUNJDj@Ku@p zdQHS@1Hrcku7??j#HnJuAtXeuAt4W2OKIV+cI$DZhajB{oKYg9JZ+TgNGh8R2wKsX zaYT}hd(q+{9<z=Ua6=1jIq|#|BD^!0{Mm)iA7~QvL`CYEtb*V|J01SR-gN*6(EQJn z6^c;=%hAzEnZIH$K7CTX9p3j<u_@?{kampQf<7BiKjwfyTCezP+ae=4j@s+Mw)rVZ zK>&=iyInjmC0@1s^WFN!o)eA{3I;aY{aU)^b@0RK&0AHMT;?6J&mG4O*Oe~)Q*3hm zM)BYsWQd~xJe=w(CcpLU^nBOLi(ef6qP%TpW?I@=vt{1^e8^niq-11a2{Di;S__?$ z3FG1Q&g#Ldjhqq<St!iTY9&rdXz!Zm1{8GBog$|b{856WuDJ1P5T&Y}>I0=+3<_ch zVAb|kj3E-=ZR|syC<*gK%!aXhR9D2SYL8}9q|n$UZ*~edcxjX*z7I#b2WyA=`hfDg zzE@7`9aLaM-oZoPNRWXcRf?q@B*e8)ULgXhKC7&jd#UFSxRWD1*6sNpJlY7#i<d~D zxR10Yq}wthPm&LLa1z3*+-kU4*j#^e2zYXG>Em3bnv!Pc>!!{R4uwCq_fkh=L<jvC z*=bjFZyOB}x2UX7jKLy88aqLyc>wsF==;>1#mQ$g7$82)|1E4kIpt;BkBA900^Wgb zDM=I?bd`A>NWNK761>5OOOo~yUvKfN@{Ge~$z?^GQ>Vwy_mz2@4W#rP9M*9F7AHJm z@v45;ynEOmf|3K&)5P;5Q<%2wB`s2EO%y?teM*M%C%uLxA2okyZwtrXw5Z^m+#2rc zjrG0*E1Kd#BrI)ca%e#&f_z9j79rA=7@C<PbBE$cQWilc8saxWt(Hy$fXVTF>kmvC z4G`pR$W;{T-mD}C&-%S>>&bMV=J7IZ@@C3qJ9HdBY|;<qpAt%dMmSN%zG2kuH_Teo z(T=nfu9PDMv$-GW=y&}HyxLqxN5{o0g0g83SeLqHS$+B8%&CO(!z)mfWk<fD95%Sb z{*D|X8Fug)#@`-lA|cpU{o6f%Ym^U+*8A1#wyY&KZ@%u9j=N~H_V)j_>Wnyb%jC<I z%d>=G^31pU5Y!p4Xn;#xgT5QSf7zNqVCn3Is)EMVzrfOiprjrNm(-4yU@kj+696I6 zy5+HP(A1TYw`&!TgU1j=mWq^jh#UkD$P3&+PRJidq3~xd4EdMFyYIeL<&#?uU(7Pv zJ2yE#lZ)|B(kY1DG``TdJev1yhDOMbD?T>)GVmZF9*m|(H?Y8}!iKO-x9@2lwvgn+ zQ55<AiS=$v27wtIh-fsZ<*B*h1b83}Wk<)@F{X)QLlKmc>$%4leN3mJP*kj6&&O%R zH2V}89l7EWo6ZwdT9L!e6e=}r@*6>~CTEQ(TWd+Fyn{V@EwmH|@iUXj+|48Wt9<Tr z6n884Uq9FDrjV&1^dP)<(t0aGbUru`M}uf4@lvbKFZ;}S2wwI?K|`jdVj_i{i52Us zC)}{Pkh~uWGJ=E-8kU}*96_-@MWe8$)CMNs`~UBxnTH}gK-Mpf(J0(UL9Qn_w=J5^ zUI5Z5HJvNi{+SMP50osuK3%p?uma2#1MdeJ7M`mE@~`xGiI}?dm(p)W!`wP?#|V)+ z6Mdov>*4z`K+^>(ioqc|0w2&5SP5@Mage;tQ(bo)$dxb3$lUgz{d;Empzw3#faIaM z@3ywUTz#h)eghvR=}mtv>zL=B)#`AD)=ogFyD)7_{WB&)yz$Fij~^LqAiQ@t08gke zbvwNIwo&(cz_P3p=Z&ktU0@D~P@xT_df<+?TPu@07}Y?+I6y%s(HaXHd}F*thE_!_ zz46jfn0u#fk9Zx97-|1x<}kw1V~ql~z@BlU+Z~o)O3LMb@7a$J@4U_;nwuL`zpmWS z^!*91$G5sH=@v~?pZ)t+Z{F~q8@Kd;KPMp%<M3P)vL{+;j*^z+3Zh~MFX&Kex1%6o zDqeL;WQ(LdTQ~pav=%c-01cOPc#xt_({-uNV?A3{Mo$f5i>!*oXH?`1AX@w0!?oKz zXbr$E;9G5*Uj2j614756rW4|&VSz9Y65gjwEsBn?>!*D&w)POoSE)K~qlG=iU6tEv z4Wl9&{08;ltc5446Be>B|4HZ1yJhvC4(jhRHz>bHM%ceU@qL4yt#uvg`hf-gk4WKx z`@@DD?)9$j)Vm6cBzB{9>^3y#P||8`O*ni?;F!uq#Ql91v2Lb%=Yl%uujtT4KEu#| zL64fv?MdIC^~W-&Phh3XWv^%t#FMaFl#9u_*l4Jw5d30H-PImQ>d~UEq0ps?FX{mj zWEEGXgAN}8Bu{~<?~6ooywySEegE?|8uQ}F_E^eX{qWYqrYg|@$de<ZYSTeGH`=*M z%;2SKTb}|jHcrB*Txs2$qBhOD@#-1}Yr8P{*WO2FzeRr_ypaR)CXFr(-~jru4zAdZ zW*B}BDU+?zLS_x(Hp|C=Tv1>_wlm9c4m_=d^Cs8X_GqfCC8KnaW*Il5G5l;b=^SQR z3=wcZU#!Z4>1tQ~ElsjZd*GeGdYW;eB~-uZw{S%9iLSmOIkP%c#SJ$_vs2V5w+VZf z;=T3jw2xgk_K(raY(_a625JaL@U0^0v6N#k(YY%{-yYTHdG5rYrf|{*A%bg`Lf&8a z0C`v0cQb;ELF5SKutq`q2-=Wk`|>><ZhnHps@g5-;0?OiX`f^=3gvm#O@tG|R8qIw zf_1pUIB<C?5dlQicM^#l^5XR|oexg&vFYs2opY%(2AduD)R_d8A3A=^x9h#b$|nJ{ zvFA&j;iiiVs1@{JwlAx!6vw?IlE|3VexVw|k8_#GSI@5KD+<KCl11^erm>&S9i&e} zNidTO9cU!%@sw^^AL7~sCW!uCr?o`DQ&d}cWW+t$v}}io6VOtCkSe7R_8aOl%$&~Z zBwDUty-#d1!uRm=4;6h~lT6Lb3m=~gg)#mu+eUz5u+P@Y>gr$ac;1m#FP}8lgTZw> ze0m1U^;5?S>i@o0`c~8u74qaT0M!Y+c<C|7A&ni%@$PYL5N2_1;mdxcpKS{bn~V0a zWO(s<=KA8W?;$3-1KFvjYiD26&=w2=gV0kpfX$MwkBP!V`A!8yS8o&qXTErp#`q#t zg0k*h%<#6nS0;@(MTZS5P=yZs*6T^10yk@x$R=JjMIh#J+XB*C;j<P!d($h;V$3Ym zBU8KnFxm8F*E;O5$zNAVgD-TDCf5OE`T98Pty`Hn)oW2Ib+PjRgaC{R>4PDB!Q#k9 zlRaV?XJoprT}n7-xyYtoqT9R9;0w2gK~~9o>`yth0_uD`UWyKmw@+r|Zg$R#;N_b| zQn5pgLCGqa!Iawl;|6tRN*=&uQJ?1FrBURPC3P<--;qgjINv<Hoc1HJNBd@wk~>}_ z@H^fodHM2NITt%5q(8b2RA@Aa{y2UxRG@U&yV94=LYULov_E2`^!Am>312#97DFta z>qt{qu+t7C5@*2v`{7G%%L#|Xyu*&N_e(A~6W-4aN<IGt$LQaQ<^x}%Kn0RkVL_+W zfh@*jBqe8xloaiWTA>>1qIfyCmzU|C^Ec;@)wML&<;K4<J0xwxq#j#W<I++Txz2Vt zu@|#kdM@cd@sT8gsj`0N!3+t=p1T~XT5$^OaKJK{uXGSToewBb;l+BQNJ0ttrrI?B zQPc#V{8UC(@&XOVxl1I?FBKPWqJ~OIf*07tH`5}{qLN8?C@|GmD}!AJWe*~?U*+2B zO75*9$BPB!^5Yx_PK@RXr##}zoX)-X$Me1$SFgy2Oq7{ILF(`Gg<9s<WYvW>wQTDG zHaShaHMF}p_>mjB_imaV&y81g;m9~?V(HFuCX<Y<E-olzh<n%J%})u$>xCHWZvo6A z><)ws00`pGo*txq?YADqD+8%E008V>*fa|O;AeNu`N4Yz`NQzF3IKovCIA2e`1Mfr znA+hmrpdWCpZgy+X>iRJOx&*|5qX3Rz_$FiYK$I8!({ft{8lk2x>;;cN)Xb~f**#U zgZ*YSMc^0m$QB7Ar?PaNo~&AB05jk%&@jd*xOj{i#cr%#tHH$0tx+VK2Y|s!G2D+V z&4ugg=tc<iV;z&du(_EAYt#;tdZY##o@p_TNaLl60-W64sAS?N3l*G`l7H2L(GU6p zfm`xM7wE$P%sxl3DhkgX{X0NM3v_=g^@kDy75xQFB^P0~8XD<+vRMU%)ZV5Lz;X1W zK?*W2B=Y2geB2~ArV!w8EG-~c7`+ukha$Lpp}`pKXm_aU2ynPtTHtJY<BY~d22doY zmfxEq6AMORHehz4Ihkj{M^gy4ThRjkE&o9%Hz4V$g%sW-eO9{U;NB1J7cK0$m&*^- z<a?(yVj(VZxQYMF+ovovXz_U!7y$lJJ`pT2zY!hNV|S6~Rgh@O>=ppQiY+kY<L@EB zZyO@Y{0Jtrc@YxIM)LUxtWZF9D0Bl3R$4;=nKn_xIgeG`r?<Tle;FvH(ECu%v2SpU zOy9t9g}eM%6)Qb<=$a+BExT;qf((xn{CmFUVN@`i?zbrOke0I)-?VG4tZc@pMO;tP zLai-ZDVdi*;)Y9BbZFJ*U9Ke~>1i!yF8WoiM(wH<+jN;++UO#UY|{L=mUgMAeNqd* zKXOW^5oZm0X{T{7&CBA_<MXglq*q*atv|y<4Rlg!F11UZu1V6`%q|yl+9fnlaiOo6 ziBVgU$*jdgN+%kOG~YYtuwF4^W}{|j8I(+erZH$eZb4eM-k72IA`PCCQWx#Is~{P! f?ykBfEv4t|aZARsO9@jQcFcH|@NXpc`I!X(g26tf diff --git a/.next/static/media/c9a5bc6a7c948fb0-s.p.woff2 b/.next/static/media/c9a5bc6a7c948fb0-s.p.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..3edd2e53dbeae440f38cd226a4746791ea45a65f GIT binary patch literal 46552 zcmY(pV~j3b&@K41ZJxGm+qP}nwr!lYZQHhO+c<5^`{mxbb7!TJU8(xBvr>B}wX)ph z#h3s<fdA044nY3z0Gj>!FSq<(wg0LA|A7@Ej~%#)iL<Q7FQF!=6m1S}z^|+#s1nEl z2xXzSL4t%19OnrvV}l7d126;)>j1F<lYqoafD(X(>Ohq9X=`>Q0;xHr*vxT&{j1A@ zEl-v+FYR5@7dT-kIQQ%MgY_J~onuaH6Axl?e{lW#AKFN;nPdcbfk_lqt3GV4U$tMe zU{$4HP4F_LNMCzL_ov4&sk4338JM-zu<XT}7DmChJ_o&}Ky@`}igCE8t^!jUL4`!j z%qEcq3tZY8sotE(h_gW->9?fhUpb=^%AU(R7o4SUkDs}^I~hV8L_2A(vZuUt<#eXO zGi&f)(w)?xnTo(<pq{~%ncz}PSg7~89`$A0?lzpz3aLlCkCb&&1?t3;{HmmQMTCuI zsh;yeqg?8bpbq9-+7otnyk*z(WGM05B15~noVP>;Kt=N3#lNE09hL6v^s+mm12pCj zU7`7(6WQLoyd_s>cd*f*mZi^Skles;5vj3MwUBVW%1-7S`M*bg-usmjGNdYr2+W$@ zGf*qN_%s~d``R-gBLtSHYHf-c^JJ@i?GGq_?>3nj-2S9Qu&w^{9<IBXyY}|G1APkS zhHnW*6d@rbBn4d(CKfyFi@jGSI$d6jfT|EF=Wvvw1be&FeyQ?W*+F6Z%9C8cB(Y$@ zGUTw(nR!7DT^vt1dqkLH-2L=Zp@BYo%26aWU_&@Qss_sf=fhJ_`UZG@o>54rSo!*W z<rN-%)H2^zGZdYqTicvsi49FRG;j)SJHt)kII}p1C_r&G=J~2jQl<L+%+dEPzxsdQ zBmBhjx2b6t7J#So1*#xhMl;O+Qf?ynal7C7BNZ*eEf|#(=?+^U3DdNaMEr8w-Vtu# zwk1FR7JsfzTG`vi2vXsQ6)}Jp2vUxYskfNVO*IRSgbZ%|7cqkpu<`&GZd*h<p?;tG zr5l&fmo?W>0a*Scx$_IJO~KbP-AywaEx!gdaYxIu4P%^9LtHXL<W<ug^Q?#U5Xp`h zxpcfNC(5jQCN@I^u8=Dq>2MGOpdKu1(rk?{@mC+PH4!pos0Cr;bUES$Y(C!0>epBh zy)sW^5IrLeAaGQN2q7FJ6o_8a4M;UiFi@my5Hd^!WPGIIiHxMe^egSDe@WE7Fk2ZJ z)9~y=uC>p!+iI<NQ~Ekh$ETa*3jNRlJ6(&+U5dmpH#-4bxw(2}yc5=zr1URZddDMr z(^AzlVw%%L=uI3^np=ZN!-Rtr`G}#AR5+xHI)ck$vLg3&F?B@~9!j#a$qx>h%QNp@ zxty|M$<CbYWo|4nbSsLiMWs>-ky2ng2_qYbh9*sHevWx&gNkpTZqB=9co-1ng#$s$ zm0*{@@?1A{!y2#*4W==;Bh+bb==LYsrmyw59X9JXzy5v~U%e$PGxy%ml(^(ld~(lC z!vna%K_=n`f8s|7z!@VL@gfCzipK5}z!{Tr#dt*6zW<vwX5xueCX*~sh{d+F$1WV> zAcx5#e?UK>pdIU+|MhF#XZKfth+DuBkU|f3`v5Q(=&z|MIhJW)NKAFD!mv5+OpS<9 zAx637<tv|W#@p4HUah>|cJ>?bgSgP~N63V0X~r8d;Y~YV14XIg%CG;AZI$os=dtSJ zB}fWlzJXNNXsuhJ?vn5;mG{EUjPzyE5Qph+uMGVvY!yaT_<Pf;(W)1{rwSM>R+NBv z3?iddfI&%=I1+<UfPz>}kbrnB=CzVE#f6Y`=e&{-Q$=OT%HTk#+{sAH^m+`!Suklx zsYe3vlmR1{G$NQ1Vyad;*EiGh!{@Uxr7I1ZAvWZdg>O}<X?*d{1;NdN`7@BCkQp7b zT|}%f$vSBEOVc~q2F;8Ir2;z)KBAczkp19`JXJNI>gcweRLjF%5?H|2>I52Ab1kEI z_Vlz@Px~9`V`yn>u%=M*weOEp2a76XFau`n0vcAN0(59O0f~eFB&O#nn0HYn83&<7 zWK2Iaf`vjFWXuJ`^=iGHP>;Nr5@<lb-24Q%AZm7yvIF!k3<4smU@};8>xDTlX+Kd4 zAz}g~SRgcaa^zi4pH+bn+PR<cSLQ(4vPah5h$U4z$<MAz)iXapmW_20N1&$s@2a5l zRL828m99*bbxb@xQ}07pmPIgnRzQ9rp}Bxlv30`oG`Yky8<0~tTmlw!u}f73uKC=I zMb6r+E^FWcort76qU1a4?rd)SYQ}kYY)&K@6n!tj*4tvV4W>S#9-<!d_AmdLb#m`q zHCyN?AZX#nTT)+K#E+g`hszck1ep6kBQYzr+Q;ulqXai0Ycs_8>DS*%@}G~oIf;DK z9>qx3t&J8~HS02<B4A4YG47b%KXWvaC-XLCfny}D4Z~g#M!`T7$Rc|Y#wr%P|9&2T z8X&w6z#JR|Rxkhz4IFq{^{Hq1mWgmDqJ_l({iWOa4R+6kc88&uYK)TXoP@Tws;+&% zv2`;)m2wi_fQ$wv)T!`%N7Pb;CnUMor&YFb?`uH=*MtadpGDP8w=4NRT9>QvIHjXa z2CxK;^Zb6oHTlqyiwI9f=_PkJw=0R`2eM_@u4Q|Gp+J(GulgYFTagR`$?rLB2KNbT zyQWko*_j*?sTV%q6yK5PJ}4xXK!<iYOOV|E-pT%MdYe<O+SvrU$PEg%J4zD}z*NFj zRNsmt{1p)SA_RpZD!dy`>n0cU{WM`oF%V)D#54|J$c5Bf{q#R->-qkih5X*UKHL(5 zBGd^2MM?~YWkQ3xIQ^WG@i(k*O2}8l^n}_)bLal|Z+D>8WkOK&ta^lGI0mu!<qd&m z&~l}kkn-~KRX;$Q-?#$5d1m(O-%Y!>#@e4MP$Ydsq(BO+G=E-V0aW9)W1|qL-`WA3 zMi<!27f`RuKhJ{%EH)uy1R&|isR1pK2w7oxZ0cg`z!`?RlY^~C;Wuk&t2OM`AqVBN z?I@~sYlNT%(Lno9`H1@!fIP5v6rwyX7yyA3ssm8KJn}`L1WoF!Nl_sQb!DlsQp045 zXy!IYLu&CKwS<+Fj3Ig;1^`9=wA~x*7w=PQ=&6WyBkM-)^>??grCp@IeDTr6Ul*>N znPH|XrgzdaSB@&Ptfq_Wfs^+jqQH(x){{m~qmABcjh8wJr?sfF*QJv3Ahh~;n3+(S zz_;)H|6a~(&8F03acKjoI;HyL@60><Yu}`oHK*#&Zr>OEyphy�V>tutUx=?LR3? zN@8F8nVwT$S}7^eq>jlFPN!g{{H#s0+DPc5dUYJfl97cI3a;L>a@!}B3d*!`auasf zG%kBLsT>x?^IS{ga~JyM$)}asfDsE2;Hq}9L1I9_x&d&AB7umJQz&SCWOJgNP$3*7 zFkpqKY`;kWkpK{wCg1~h-X`z{2#N21gIu2z_=N}M2RvXPrV9K@-%P6u)ZmHg5rYGj zucIK{W+xQUkIg;d5hK_=h}HV<bcu3j_lhFG0iJ9<O5Wr~H#)62YU1h(Mf{7xhknP6 z&|(BWSWf%O4}tH^T^_n4!mQ_C3BuZ4O=X0xTg^57`&(zch?-=5CF-N(A90#HI)f4c zWS$N09}k^qEY|UBzrEw@&Nz?D$W!TrVPHA;Ez$T{wPJq<R_f;tDfc;6oxLxwlw8q0 zH=Yq34=2;<6{@F=2Y-(Y<56I&401Kh{cG+{d9%^WR#sxKe9ivF%4?govUg;b4!4@I z4~rm56TzY}<{e?mcp>PdIpFk*2HB~yS=i}nMLgi|8)Y@G)r;f1yp$9557#i#@7Kr& z!N7#ZAUQxB^)5vu0;m3RpD)RS7<Hk#f%dOdU{iC3>eN=?J|}L-2QMYk9zVw8xs{@{ zOgK$tWlTFy-Q@pGhY3NU>-qJd_P*j;v>wqxs4sr|8<g$ObN6O!u-ZN8-CwO5zd<;{ zOxbA%caLNfo2Q1+y1jWMzp#}&8&@^Lq`bBJ`PeVIMz&A!;uuAwKAPvPe_YsKonY-N zs&HiSw`<Jbk0%zt0Xa?B{36CwvIgsZXvwE*&=Di6)T%!Fa7sU5rdT-wofb!^QR2HX zPyFqSBgyJ8b(!=1IP&f;l7X5uD|-(HJM6@%(TroV5_#ebc|%sF>lz8~UA~yw5lL;P z35y4U8TKD$VIICzt6fChZ4>WH!Y!g-LSD$eFz(th=|kY{eAVoU7>8&FX%Va2_bH@J z@+#}!U2L9a&tu`Cms&AR+~<iD@KYXJXDy9~93;TjFtFHI#f#+CKG>PYVu&<}=+W46 zFZvbscE)R&g|x!mz9P})9WR4K{uz81iK1EV4z)JK)=p#xF^*Z<v+^Tze}WLM$*4dn zj}6|Xb%^xlvYE|mOGWHsL-=V$3gvl2)sL41of0>p8zN_hd!fp&4TeLuKyzoSxSKaW z-`^C{zHvI4IQ8F)KNt9!Fa7wQ5#aKt0&xM77+MpO2E6mG6(tB5((SN~&jqdEud?9_ z_<}ZlwhmLQoYsuRH<e3%`X#fU^x+K}Ij5X(OunG{{LLe?nYLUnb1_POQj?pz8s?(P zwF%bAlA*12Z4AL(1A9KqXP4-n6Y>P2MGi<EG{-;1t}rj+>`l|N3v<#VWhlmm+jLf{ zJ%_`2v$4M*&f*BfaPNZmj#EZ|UH>XMg{ns&SvTc;mt0<GI6ZJ3D!aL>^f$$RrAk%M zpXV`igr0YisB^vC{!^CVs1-v$%|r5y`F-<iRB29?>t7n4V~82;$khV(!kv{aZWV1j z+?x8D6!!Q3IGN;|PQ53pxS9WsQ((nw^M=nB4iI;s;r<{&w6{EEJb1V1we)ZoZgZqd zDDTM_EJS*h{i|0JH&tY+$2h^-jL~3Jg}e&yH-OQB8``DzDUh&FL7exp=B%rG@Z&-< ze%;ZLYPDInP&MlyerUg}!u#cL#j>8q$+KzYyh=VJuH}&(wdhRhTCcMtmA=s1Mv0GB z-;z0D(cFM1w@0X=A5ngnx~F=vdw|-V6?I47O6ME;Y!z8LztVNtQv4cafuqH&V$h8u z^2;|>C#}^f%`#Q(YT@h<eJ;eD6I?MTeCcC7aeNq!|A*CM6G&&y%rVZ&9M<9xm3f)O zWH$%0@Y9mOl%xiWW|p0rfVQT?Y)GrDhr3HEH$_O0?$M;L_;vh@MU~ml`tfuj_%9Du z=BZL&9*%Zh624Zs^EX<pCG-!1bOPJ!4d^mg2HPEx<t%De^zrr6QdqoVRS6q<rzv?K zd+ojE-qQ};zq4pX|A|&Y=J3#mzz!xZZx%0`f3}%QS2&({vg8-^(Pr2)RX<c#kAYQ+ zT;ckSZtc$=#Ty+=-Xx+WbaN&ZqW<r<#eQyloHd($Hm~H?(1&hg_D|ws%HPK47-qTm z{$eWL^nQkC5PkO#QTiJ1L-<z}W(IF`MAs&e*?0sZA)El|vGfbKDI|9u#~tN4p8LW4 zvar~<RYTo>Yc*~Dm;X8iHAegc(r%-?ohHIvFhT7KKpIdFbllcDD(g#=5AM$Lald=K z997F><QN<YD!1{p(*^p~wCqAYK%+H~S|qlZsLCB6@o@qJ1CYs=tT!n`fnW-w{*uPK zp!wH5TfZC<5qYYXqa%UlaAHa$le7v@&_*i$g39HSsFPNR4bT*ZD92f(=4&gA{FUi$ z8&<!r>d$nb(jwRb+52Y#KGjLtv5H*(5pcP@2f{oml#ZFIx1gTV?nmM`L9)yQazlc^ z_(gHTOEjQnBVM`oMbjT8o0nD-%tNXhrxxk+q1piUaNLYo!g~+NMx0AaR6OLSEJ(zS z|9$r^{lqenpt}H*h1#CHY(Zh(tZzYJ|G>n#$1eT^Ym%xW0^-05ALU9W8BMl{_vD2# zs)n+2%^E5TQu>o%{dB#T(O4>N12;3R>`brQ5JtRqc#cwPEhq?w1OFZIMkV%+U^BZ? zLZ!|*WuvSridI)hp@W-}91W0zB1Gk97m3gijiG6>iG9`y>Xfnw7lE45W7XF^sE2}A zmuEW-QhR(RLc7Ct>hvL_T4`a5eH|lP?OIMh-Jo0BU>Z@lqAf_yFe;~$n)hlh9R#zb zu~AI7*b|EjH+xVWfu5<w7MalSP2JetmQ%py3@DMZ&#*J!;`UJ7xp6bka_;9m(Q&-x zq&HG*-vPm_*&M!{^Xw1UTOB5x8db(KAY=z(=@ZX$Hz=q@MB}iKX}|>D+<bk&1ENp@ zcZG*%vQY}JQ<WT)bzBzLt%VMOLg)hX{$jJ@pO<ms*oTZO<q5k}_xSi$$#InLXTIal zXc=ib7{-0&o}skEHZTEI7M)~SnqgR?X^PwlZm%u4vyBp5R9~+>DNC*tt$Z!%Ew+w! z$e&XyxYCSwj&C=WhE{hOtv;LMZP<6qDOgX|FzIPqW+(?6bMx=Mj)ct>N4ZTA2y>@v zSO;~KB6sv3Z5fgm{Av8-P$EaNjw}8GdOa4no9U$*2o$#SXHgP-S}vjy10}i(i?U^K z=O4Vczjk_M#ox{@(UFznF3D7g{C6NL!}*=FEo4>qY0H4qx)d%LxXwYjkcKK(_t>r# z(KtF}pxi+`o*YgEVP14IinGQY<nI=<w99*|*^zZ=W0>_BJ!a(=AvVA{ZjJc<P~~o# z`%S8DH?CahO~v=-KXha)U^46iBrZma#cI*3`Bns9bngBNPBSY}EfKo^g<AQJ&K(G7 zCiIH0Y$K`J5{-x3!&*R+L3zNafujd-VvLBK;0Brk%f`4!G2uU!paS`W%zn<ZZ2N^V znrBYL#;Dxfm{|-kPne>qf9iwEh^n7WSd{2EtJ1I<teUaw#X?AQ&~xC@l#HX8#xdGr z#uT0t=Y;eHeEEzTIJp8O#EHrZy#`9ZW+9&aPQ+g^@PIGizRRacYy0khv)=g62>$HC zZXKz;m5z7mcPLQYxf0!l<}|8I7dYmR3n|q!P_DA<7`l(XxgB4<)!mNX1`bCG`CL!W zU`y*{_JSobk`(FN3~K4uNqOcuBT0F2Y!oWqQ;Bw3V`<p|XHP*>B9ZFZ2U(n-+BLyG z>JJ}&KNO9<&nph!2>tM*EuSR)$B~q@=3EVj!_o;9l8vYpi^Wq3l+vv@9gkrRb(kD# z4QjQV0WrKN;r}07l=q}jqga@W4SAdt&f3OIn+fH&c@`wKFr;|GgMHwat+tlVZ<Z>? zH>OTY`2WKSnl}NTR#Exf3X<pztRmcmMc~0PS(N`uwP;oA7i{0#%2jt@+pgzb@Xx{B zga;?(yB<l=atNsrk|!%XxJ*#Uh~slU%a3%kRKi{M9q-dN4E@s8*S<KvZ0gYkADOH4 zJ@gY*640ADrVpIxJDUEjr6j6klD@QMt~&@2Vjn0N3wZPpN`wiC6ZB+SLa0J8*^E~6 z-_}vwlK)X~A)B!Yk&vl@Sk#5{9uXb!yCW1=u)G~XiqaL6AxVr`Zv_4{4ND(_^a3A% z5yug7sXT6Yww=>qaF3^uYR6GKolM-3p4V@1xxnJ0Ocw};!{c&cIq{}W2Wa#jMV1XM zIwJ`}R*bnhH|qEPwkbOv%tm0?n|+-$CfHXih@L{fHpI&|E>e-UuGdc6k*jbX#r&b` zG%5AQ%d8n|JN3Nn5cPXW8`1kzHxDonc9IwvMO6rqr7Qs5QZik5@iSS9lY6pq=la^r zO3a5hA*&A7jJkG!&*s|oJo_YKanTP8yr|;wa3P|x(Lb9gOMZX6u?f7-q1JG~AR=;O zOlqe~B`Ek@nD;^iDGD!<zEdQ%^3o|9)gzhToC*o~o)4+;yDk{}UZke_0zokK1_FR0 z(kD-tD1S;9C{Un6mxOw?jOjAp7_WVg#9*8Go|g7yI!~RQM6c2WJJW+`_DsH#?1_K# zdRN&QX#N0x?TUUiaH|=sO8+<5Zse<8z^0OR;<DspwG@-m+ua)BbL>jbljdbzW#aWR zkLZ^<z$o=hlPDA`Wjdf!D^;o#tK@ub1F-(=UYeMFYLxGLd~1a#%W>YsG|h6}#dY0! zE8wx662K~f0Z^$^x?-P4`NiC9sImMa5yvGSIOm1$2<)xa91oU>{z+#>c4#3ZyQBS| zub_Bg(rp8GC=N;Oxn8uCX2VG*ky^gD3L14ai8fftbkb3!T%|+{u2#$SQg<mpU)xjw z`(SLWTAIvYF~#zA2Jv$Rr0;~V&J#5L$=2Ew#@#f8wrW)7yPIqW-lt>(PE+abfzLQ5 zC@B0D>!tMP3B8oRHI$JPq}s3Tq8rVq7c8UEWXe&rwwv(R%?pmGPwF1G9~5zboHv6T z6i!U0jetB5$OWnq$f^X5p~Q)>0ar*gKN9gI-=T6DQQidDxBv|G`pemX`ZmD;Vj;X9 zku;xxSqu(7fS6`HJ<(by8NE^(uuMQK+o}LwqEVNyPfi#qqy`TVPa=!v0KC+Pz(SYj z6CNTuIjtUl0gX)wV)<MMi+x22!G|F$3W;dPSuCrdFJzdW4<dV|o}d#;Cz_ft-$sT_ za~XVgG=&F0dM>cV-5qGt2DvLi6*5zWE~pa6^|D3M$e?Iv46K^%?TCf>w6+>$Myusc zE`?a?;b|RTse07~A}t{y=Vl`dk3`TKmtLoT`-d(=2@fg97nT^$1(T!jeR*My_nB%4 z3USQC6rodNOeTjX+QZr#$A&`3oR!au%b;b9i#K>xgM-UuHY-}PXVg)eDW5Z>jq*q% zO4E*AJo`7Jb*5|DGS8xGhiqAKJ9A(Ew@rsn>wUIw+!165!#g^!J2LI?mHlgZih!{z z*m1)?i|ev@-8R1M4bSF%43Ue+Yt8-m8-4dB^4O#w>Gy;|?5p?iw7Dk&0^Wi3h`(8H zSSq$p1x<M$A%-PnlmO&Q)42a994CaV5Yli$0X+QdOQIDBQmM=$+3=shJg9>BI;sdU zGApuVQC%KnSPm}J4UI^PWoMD<vm(_NIy!C|#l~VP{BtUb@kuQ0rC90&?Qf$2G)0#8 z&&fSSzE7GGTbR1a(VGY>9-V2ZPZ1SzLSy8;Vk%@@B`Tq*X@sIG^i(GnQf#f7i3YCI z=t}ftCwRl3HL~7_O;QpTO(VsHg=jiaDMm(yC|Y5$#F^y0ZZs?8%_`P{snWtuGcMD3 zp18^}qe-tGXe4H&)<9jA!ax-m)({I+)+h^-?pu0*lboMn3?(`$;xeZqi%Q-Stk(Dh zn`Yce2E#^70<1qG0jh$q;N|@}HXaHmH#vc0tw4WZKrk-i3*y{_FhuX={@$cTMC9*g zq7|gveGt2k(H<y~gA+qI*t8+gQ;?{Z*6Kn7^;&<jPp+qEL9nI_h6JCf;7HoP=O~Bv z0o*u;U~ZmqF3vo-t^5OE_4a-=B^mX7ijsgZP%I@GcBnPHvwTS>p+e)TO0<$<T%faJ znX3E@AHfzeFy{DvjXjmeP&QtD4dz0z4(F-dOD;#3HXez~ijvnC)ICqPNPl4ke?BI_ z6C2=IEm;fU9v*OmAC(EkFm)dW%%6)xNXw#abvr95(C^7T<CM1~=UNgFHC7({7LAC% z)vbip9m7cF(==Bt$?b%T(Y!5>5@f{<esmsm)qzyBDw%L;4x7<B_e^3MDMM><snV@F zrsb9XWs=`n7|1kW8Fie~YW@JzPr{MUyTe`1`%SY!4sO;~5ZMLD-pYFVI+mF&;L4E^ zn}^Dh^~WoSt6>}xmJ4k`aJ(5zX)PF(onr}KB@I*iLq_Ll<*51P24v0|yvEXB<94(% z^RN;ivjR}AtoN*uqN@(d7W4e$VhTi80;HVe*b~(iV3-`(j21KH^tVr=5W~JujGD9u zrXse?1|^MVYX+HzZna1h!A~3xi%`Gfhn2{On^L}MZlUArhi#D_(Ra*9Eb?;<q~7rp zQ=Fj|Klt>z-6w(p^9%^4R9?Isr9YpqP2eN_sK8uH<df+rTsLy>n&YIF6;MlezXHY4 zJcxrE{n}VuK^frBU1Pnf*sx|OrJ7#HL;@0>^Tsg{*#je2$CE!<9U1*4x#heY)@S@e z5~vKq5LyC*hP^f^wd@2eC0#aD0=|vRNW41uEwPRLXB2Uddt}ubLen2>bE>XgU=F#g zFH#{MtjHDL9IWxudJFik3p?i(8K|CXQe`wS`5af+{zY+uAi1CgJOe?5RXV^5)7L^r z2m}HcBJh!9{+t-y$YhGWVLg5sXhNsHdP9;(9?)E_juWmD;lv?rXu|@AFUurtSr!P4 zX9UfA7!?ppDN=AjsY>#y$n+OjmDC=B@Q9QJR>mNeL!t<IG%r#Dn6?G^0$P-rJr_T+ zOeOiAWuy&+qeO0YLPJc9acE*+q8Nq9t<=EtIF~>at5nu7#tJE53M9fHGUYBTEDL`_ zm!c%^O6%Z8Q_DVJZwW5;pM!I^rxGP>{OBTAJO75-9xU(aucF6aUA>R^^U1sR3--dr zD%cgJ)5c}(lRU~8BZ^Qb3!YR3IM(0HQ#HF(6<1ajZCCrKN@`ZESN4{V?%dh4*UKpX z)iHI3b|hA40_6VnHJ+Bt5amB6l=tirB^<JEsZ0Bya4!F;$2c1Mf}l{S`Cc^#sp&(= ztM#G08UTSuJcgHqeDQR?iZE#S&PVwrY27F2vqggG_HVHwScQ8WLk&w=d@30v_}+By zaz#;6ttDu@v5Lj5>QUj%_IfH{7E_s;Oj`Z<4`bt%oUDYeKB5x$(WnI;@UdWFF1?u! zbi6wVhHvHN2=TFX?k#ZEnz3g_o|yQlaF2YmK}`O!xdTOZ?9Jx7Mmw|TiQWMqL+;8? zPkmI~?Cg!zTontDWyQi&md^9;oj=dltTBHx(@bhT`yqh<kf0O>0buY3A=^>#uuP(Y z{pquMHiyX;Q;zvzF?)!}g7~o8=+z-e(jv?VM9t;0Gr9yGot1U;T?j1Kj>`=iWA|;T zL^(tR03!wpfPfxQ0URU%SRp`&JfRN+034v(+X5g9;lyNO%90Ov&N|F8f<WY_QdgnW zWdMBDIafHnfG7yDBc+wT9|v^C_fKtH38QoGQRkJc5CgOPBoZ}C)<{1AZBZOEh!23` z@Z{3j-qh4?s>kID9fh>!b@p&si7!l^H$ciiA}9QUCNw4{pNiLv69=4Pn7x;z@|jN1 zW=pt?X?1b7kHa|Vp?Bbr@NtNLtFgr1eu2{X<0!t$luq>U0mj^m>UihPGCoE6pFl-@ zJ(*~4=Rg9L37SgXt-uCf1p-;ABvh*w%bTe*N|Y~DUF!=&9C7sTTncIhIa}4MM9_#w zWzw09=|Y(?YQYgai}N@-t<YO0>fd*8zd22x>P;t;Xvfex9*?P&s^?X~5*tEdm?BgQ zRWh7#(5O@^)Qa%racein-@N5MOLtyam(w`;e}MJIXiw8nVgk+!#PPJBhn1!4%zqBO zZ$nM#iI0L=WEbB%4nH6;g@Im%d<22GDV$jRPcy&Y{(|7F4l-;^0Zm*z-zPB_7h1-h z%YWyyZZOSIM%9!vN1MqheG|#;eDp)4pB37q<g;{HOK?-PbZqAXOqT?H@UX_~zhp;& zoG`71B`mqZ?$w1|>SSS#<OOiRxND>)M!#tt1>*B5>31W0r)UW_OnHNGkYSc0t^QKL zMyk&pwiQMsg&nl**peAX;a6YUuVrn5@00`8w&z>H{<r5x&^Tcq#xgrT5Y4p=^C3Ry zirY-I{25Ue=)}AkL&CEYX?+ds95-;Q+-)B_m4pNsX~irH{*#9Y><I&0!b&GQpahk_ zoPPq2L#=-XTpuzt+{DCjL#Xpdki;_x@?9U3UzQs)9}+8%;#HOW;;BlNZyP1QbzY;l z%Q#?*Me#D5*H!`HF#N6|Z!0H!$e#WM@nWipmFYybXszW+Bnpm{$YK$*LtCzMNTaNP z(Gb%M<v-N<i_YGd)eYIR!RwMJH;(&9ND4Eq#UMc!vbUsmyXa%j>>uFoqC|{@17aNr z?#r+ffkyUEVJ(3=KnF!>V@#biuS+|tr#%GwW)?O-4ja-XrK6gBjB~lio(6j+_oeBi z^RkW?oQW@q7If*#u@D|8W&qJD#Yv*PKp~^3t|2OIq=fzc`-nm1LEqkmMsRCIHW3!$ z2Vg}Ws9F`*Iv{}*vHJpWc2qWuP>|aWeVa}+x@M~WrGDF4l<c-oyVF-x-LPe!I1ddL z-;1V4^YRur&-B0)NaS^2mA`}^VZb8R6@1`E?BoBja7KLHqXi;@jH;&~vcNckeyNoT zZt@ElElH$>?~sq?7?}-Dg3jXP6Lk-={n5#Cmi;?Jz?1@4f2y*KDN!zqI1g<K8{+C7 zkA%X}0{mgvWyy?RS}s4pns;MKAw>oU0v!{<Y{M#GGPr#=0D7f(FLABSIeHBwX{7== zhctf_?LpmHRk=tFHTG|r<=SodAwK{BfCh;*SXgsz|Em(2|AUTpacPaEsUXxdOCjHo zTGK-yPz|~_NK<?pN9_u+4*CZ_?tuLbPTw&Zp=noJho7#$W(6FHV}PJV4q@*AqxTdM zfZ%&vW;CVceOXbuvMP4CY}-;Z&IDz-QzJ8kMCQN~ju|6x@kExIs7&P>12_p+!VG)+ z>BFZbVQBKVs%Y9aKv>(D*wJbz?kZKcTB<+)&;Y7b4svRSADtw}Iq;>s=Tv`B6t+2| zp)&#EtTtv29d>|)oJYq|f4J-sNVs$&=x@dX$*wK=Mp}d>Q46@e+eta2`FE%HYH;59 z!NqgRa1oV|a$G{8YB?K2BcoWkglP!QbO}25D1?!I#Ko?C&L_SOi1+#?vr#foB3}JZ ze-j!+LkuHR(Cm;<Fhx3Hki0#(F!^f=4ssN7YwzZU-PL~McvJV!&u@mMERl@$1Jl?M zi=BX7kqgVP$^dzdfFn%8*f_}sDObHNer?|9YC%UzkfTD{IfN4qwa-eW7+a+<OQm#+ zWDz&XBEzJUU3*}h3qBfyxuKDj=jq}gcYPxll`osd%?uWQ4)mosWUe^s+j2j#*@<H5 zt;XfvqVY}Xkuww7k3N+rxpVu3rI*Mck%AfE8x0n|df5M;u$p?%Kot_AZVm4q2x;nP z<~oj=m;4jU%64k=7vtz0r;JQPEA3yk5K<fx3ixUdkZrE9oF;J_9hYuTB~iP}^%q$R zc6!5V#Z&m=DgnWqTn;}W{NRvC#glMsLMM1YiTn|ENWY>+kmxTkPNI<cNxhoi+V8wf z5=n)1jy1f0V?7T{=1??vQjqQ!vfARLmJP3xy~dlB_Hv`Z-ui(dHeRpa)D!-x-&(4j zL-;4p;isMl$6JOvzD3`^`6E<^EaNa!Zn~yM9-aQ7=wiE!K}{mfl2GA7hJQ7Gq!ec} z>9eKOK>LKug_W?e^vYuAvDHSgZW*rZwsH=D)2ctox_o`jOP$y5=$v!FZeQxjX&#nZ zZt=hUzRv;^z{}w)n8RX7b-WHGW{Dial1d;k+Phzrjz3)U780h;=oeTWVs(_$j-kOO z^zRI*B4NIe`rQ(dwC$A*m(|HP7Dh>ssK(B=l~JtQ<A{G8FZ$vVVnY3S_?~#g0XR=F zZ5ZHaz5Kj3W&Ot!RemBu$3QKWmC%NNT)V|G;tVg27^~yZ$t~;TeEGc7fT%maA3W%* z$Fe+-1~9Zvz3$FzZWyv<op-M&vi9iLI!oLJTm80Ag0~_QCN-n8Dz#kI#h!2ARoATi z{UUJZ2h6`b5q>@SkYoh#BAqA&$|)X{OeQInlopJKE1Q<I3p~kby{{#1)Fv~ZwGy3J zv05%llT*7imVHtc(qjgUoZHin2Rs~<>=?nukddn_h84#H2z`(^nw+_&C36yub9ezT zLJ|AWh_F~dXw-Bh3KK#UQ|*p-bne`@)4E&~%ZXabUcxehQ^T`4g_5l5tSw_+;o{xv z*dCi(b{-ZdV9{=t{pFNTYBrmei%Lu8(~}qR{!asQ-;w$sV`7a}!&05-$Z3iyOQjRX z=)xyOK{>MrPTt*_rz2iY%J!V3XGuv_R->xZ5wv03S-d^I-+|Q<hK1A(Ga*`XcC@^J z$XC*YSV)IOR>Y`b<O&&h5vEjl<^_g~Y(l7|2@<xg^uPvTmxaGh56fv1e+ZvN>+Y)W z9*gV5r#uuADlY#s#-Zvn?BEvUiVt?>y~cMF&=ZXWn=77-WfZ;-VJ)YR*qsRSX^5`v zj4P-9#9nOc;QCW<WJbqHVq%C!^Y$|hun9*m>1?2uSWsuCQN4cHfRPwPNug41n#n72 z6ZURH`3((1CEGh{parr!q22KuP^uMY!GO#&1X~au6AenigP;<R;v>SK-qWBULVyo5 z5~e{2)6IqW0KvWkqa;u;6CgoKkg<<X%|d)FMt5Q2??O4<IebRav?4>1JPGR+jq^|s zr4t4+R3?!~0{^E-qJ94ww7)lkp0OWye;(*zY@y(`PYl1S$mo)xm5HkKwSvAI@*Qz6 z+b<|a_<Fc@So7g@;I|ZU8eVW1lQDug|DAmdJR0LqDH(pIzetKfRiaG)o)5?~la{qR zcV5ajY@61;A3vh8^vGNxwZHl1{!%|7XAHR8x}-4q<c$+zTTLV({qG|Et8@zcQEYlz zJEiL@ND;Tf20aLL;hoZlOW6~U*fSlnw<%grWqn@-#5GErid<K=h%bf~RmmZAD>21r zlB4~9Nw<vDk0;e@lxkWo9agfK>_*XyUU!}rnW^<Wj#|$6KDNy7d><zGTa%kmgeTx1 z2QO!Y0rWp#Z+4O8|56Ea8xYKNNB(A_iMwS-4LwfutSjSJhNM(5OZGsY7^lisTFM!h z_*Uq0X~tE6uVnPxuJJJQ){&SxHj+*zG7XEj&X52-7GBuDsY$WUYtm+A_+E%9{<+?! zvUTBbp(XOabG7&@`srB9KTF_MBodKIpdTnC8pUd{Xcq<lM6+TUnyR*C6~6Ow{t{Z3 z<2GRGzWq9`y!XCg|Iy7hKO>&j+vKGy%@p$onS*6hm}TxzBeR!h-@W;hD0H(|=`7os zL{cgV6cCV+akA@Af2MPFq!lC7x_3ljLJloXm~}}a2>_&LXtJF(IL~&tl8P6IBo+Vf zS|o|&f1~jK2C3v?rO5x)h58@a`u|{hdfKMu|7vd({M!F#1F4_9v*qD01^k|6q6TFF zg9%t?@3H5;5l&K+NC~`K@-fDBB5-vyU+md`-1olsLVOMQ^IOVR%T;?e9!#9hee&(S zy_eGeeqQz3v-!0hcxzwoAMO{rFZ5x0EdH|O%$7{ed8MVxuw_kJBBwc@Mo|}j9qn!T zqc{G_)0B;bZ2!x0?{V$<Y{UO0)e4wZhVDB9b|4Ccb)u-2%ALMlzE%EF=*Q4``+@BZ zV*Afk({U!~1GJ0*(gQjxP0$Ozhz)5o*bVlf9q|J^0pws0;sep{4(Nfn^p5xjPeBNH zM~sO_ObL2`QqTvwr6%wNd$SLCft&9IIh61Jfx7PlJYzHXA4Q}Beg_!YL8krLH}98? z394#9Z2tuGiE={%RBkd|>|d0dy~@aNd)<qxR5>OMu6BI}UfXVt7D1Ro97GsOYJ%r{ z9%IP8F)}Oh10j^xwo_P2Iz^SXh%6t2JQ6)3a}O=YdHW&e*txO$4WBT}>i^wA5=9Vk zXkJk?C3@Nq)!wH#v%4fA1R*;7+{Wn<eEqkGM(QQ6paT~fE~mO2@Vx(;#9^RNNIC); zOY6d}2UO1u6?DO!nMWEl_REcQy#^C27|NPCFZZ@{Hdf?RyG{&nebreXy>~qiCz?B7 z+J!bnXq$O2<I#YjyVsO>p0!{~?|tb!U`laUTqm9%C6LxnG=QBlw6v%zg{BWdY_(2k zct$qAEc6~z4xiT-=Q-Ag;G*)?Q_uEEVc2gTQxpn_Ypm!&npKlxqy>R6w}P=+YulZ( zackuG&>fl7zqa|OI84RH397zK167N^ISC2VsAJ*e4kt<=Q-#dd!?zeS3udR}cfJqS zG|MlN3(>$h;KoCHOAv{Q?%KA&7vaiT0x<H7M7Fav7pmG+h>bkmyq2}iVfW#6*TC)x z(97#`a_&gd1>b<dr&NK<U40j`kA^wTEBsG+{YmF*kd7Zj`)Pi}L9CENJU{~|kpj>? zzkE*wyMVMtYal8@WGXxtrIX4uawt!Q0Rc~`fu9A@x+kW&BDOM(^M4ZDACEg<Ib58f zH`|`VZ}nUo-OsK}=Ao|>_l^J}x-zC{8F=fD#&Ia2f=@_Re-posXYXaEmlA7XMU{a| zG~33w|J8iReFJ0-`U%4rE!Le><yd&*@k=eAnttDy6`s({q`jQXBn%PDyK=^oyvsp4 zE|Dla=bcU+r|!*P*>w5GymPc2KfJt_q2LFmau`|BoRP{;-0dIlRTjYU3pfBHeqe8E z&OWj}H4RnKbKYWKGBXypaPAS6_XuTPrBt~%=TYujg->^z)W-Zh$ED+0EzM-j5Mfp0 z>@Q#+83+)m5+XC+#A&<8v!2_g@~`*Cicg2-^X2&1PzxaYhP0g`QKxhvxmdo1`@_=n z8&8M%J0fU9!r^Xf75<F_`na)!$;^f$nQ+>A-S7A1Z4!}5B+(dY?oecuij~tUzn2Z` zJ}@*5^W=X&mbI>`+eZB$aGKW=m}}cFGo|THmrUuqm#@6-zt3WM+O!Q1tb=bc&B$b2 zAO%7NN<qJnno?FA$T9EK`ZZagTSpHWba+LE1ThCzk_dI!zggI9ojAAQz09v$D|o%? zW;c+2&Oqm18S{H%!%W?@GS`yqT%Y7W(!;}l{C8Yt#?c*;MAn&9J^XIu9XZv@`$XSt z<Al%pqOSXK6SaJ%=HB60$_5kNDZ)XdL-0MjHWM>5qCWUS^Xp5z&TgP5)U98Su2=jU zjCe1HNQTl?M>L5ApE>L?h?F^?R9htns2*O3G{XeC6_CLM+3T7LE5c+k`r-22r9`dc zB4v_MB<wxAbb!aWME+)tSX>vWmv3?|kY8Q)wYFcx%Uv2-G`n+Z(uk(CH(_aZBJuzY zG^*rm^CaE`h82Ds`VNs)-h~VxXV<(dg@7_{ATWZnSz1L^7Wa~@N+!{g<aX|?+1Ayu z*^%1ej*Cg@B*=MPU>?t!ynl^u((jv5dJ|&N*-nJPy|zoJ$L{2ac5E&4@{_F02pwZ! z=6;lsC{gR&?}6*plla^*c_0MC_76Gq%An~)GM)jK5LgR0bSa^m3~9A#+?9fVk?Q@H z6Q4Y8J$qmulRdii$ot`e9c^3dbb!WOk10%GrX@Jm?g07w*wTo-(x`AIee>}P8UU5Y zqjzXyWzRR+T6XAXPVkY|h-jaTiy)rnb;mHAhQuS0xcE&i#Vco%W#ggD8L$P>42$;L zgY~sz3!349q>uGHJY%LQz~8;tNa{QH${NlUiKQr9Sj!YKVs9I%_70P_9UQ`)Y=lma z*+qMuc|Z^C271Jo>NrGy`17iPO?$>x2pAd;0l2+uNEw&4iQ~TB<8TQ>ks!!HU=1Yj z|LJ%@q%Au#yBE@FUxvY@p><?RRTg13<jBOBgz)f$lPVylCKGOIoRDdCS3xK=YnJ|y zn2aZa+Ymi1S~^94z&qw`6j8c+X02)9sPC!JXv@ziQ$>ne-}SY>D3XcHwrPS)@K<r( zyxE>U@$0EQn>1FID%FY=@$Cb8@T#&^ZiAKSJZF=YKuEos=|&Qva@3T-s-BgDfP?$O z^bZDjdZXe68xpEq=fF}?GGO3^u<yoiq_WX!4Y-zl|0KU$b4W!1lLhUd<&EuLBm+AA zbV~mP-M{aON$7)y+6(&wQ8ueZxT?wgL7_Jv(TNys^-x|St~j#>TXHra1n-b#QMMc= z5v8&?%j!HNs)WUrJQ$??>89G;GndySNXKu~bX+$IF<`SDM866vudJG<9}a^0iR?0; zbIzhA^d$o7eTqj5kCBd{1u8WW?m_TrE*!7Tcr&gRywKf=CeHEYVvUd;Z8iHMia{9A zCp)IYFM_v(Acu5izdW7sXsK5iHI?SIe;ye2^5gnJnN$A5>oh)xns<f51mV@)G%fXY zzyZK1zqHST@>+g{tKt3NnY-8=sFPag_oQKp>t(Fd*)p0x?&2qlcix$b%j&j{6*5o9 z(W$=x_aJki_?c8&-)b?z=5{4<H8UlRmoZWhC8L}Cv`2KBQ`ST#i!m(HuWvFySS&44 zlV`~8hG-3@_>`@e^dZ{bIhmcu2zGxQEQ5aOWKdNWhwVU<iExv1OSn00-CbAF#<udd zUShFfqm~>sxfP^R+WkPK{1KfWyC=ei6j)#M%EgS3>=UzYJ7!exE@@h1aSmK@>hL9Z zCnNjKc+{v>ttP}&kh-&X?~)zg&9Id!n!KGDosD8!FZ!Viu_$ThNTJ0KX4MWl?(khy zeUv!x&OaR#X_&IXG1J=58<NhF&{~6hSbeSnct2|l+f9W*P#doI2xtwsjy`Fz)-<)5 z3#io!0My3CXt<L6pG74rd+3C|;Y^)^VMQF~b>Ot-zr8Li_lbDXa+rpGt@7m5)77I} z*)F7OZ;V?C5=Obf+{I~3vnueA?cP+<Y4CnHkjWgaf%p4oV3an@2QCj}shlckruy+4 zGaLC%bLAO3u%=f|oTA-zlr>K(du}6-p_LYZ9}_xz$optw0+|=QJcmbARnGK4uA8xC z4sY2)`B$brI}&gWz&Rxp)cuQ2+!^(7a;0M|A+pDE1>3^0=`8-UD{_kdzPeQP_<)NV z>SkK&J^AlsdE{4vH-Ib`DmeHnIt5b@*hvh*!3FP{#r??zMonbHVH)pEAHR-CuWd?$ z!yym{p+($;@kCYGB<C!#wB?(0$mLgZxZJzzkT)idL8>4frCP|4x0FD%QA3F2-jVSG zZrhOTA)INKF-kTJA9h1qo=85-5t+fc7y&s~kXl1&`dfnq)}}XY$kRBJvlRgEihx^J zlFgwz8w|hKi}ys!3r*(ylR{+JZ4kXV5~)Y+tv81=2Igz_9EU2?YN2mk5Sg<H(LB8@ zqUS53J-&q<vbDiB6m}$=Z<`X<0j+K$ETc?!V7k_f>}wh0gEuv<U)DLDsgmT=j9^?@ zq;w-n2?GDIomE$>a`N{kbBZ>kZ3a#ZN-*@$qOl+o>5UG2(_^d1{^1o!mcDpOdgBmP zo`xJI`eCuSxg~ZpWAOW#bD+G1Pf|Iqp@@p)P>#6v+Nl2l3ZJ>S`MjnZCW`HYmeskk z7|srP4efRH+fh@qzFtb3hkFjYa)wr(pnH<`xj)wF&LHqq4bOwLiKLizN!ka*KKfzY zK?(HTi%!D=yd5vozEgX4M!k^lwc8Y>rQ9Di(Ezp?BD>g&JU!o>Z6ujOo_8x+|LLbn zh%B32r8I!^c3tzs>>=0a9zO%PLJdz>iM8z>xk4JIeVTXR-$#AnEDuz=Fid{x-<o0n zdZayof(tSU3XoHP5n{g(O4s%lZVkgWQ1_<xZn#B`NnlN6f<X1nWHJN`1YYpjE!sW0 zAz9;fp2KN}%Wm)h=r0A<tr}6<(It8s7x{X(?cz>IwBrB*0?X6iYa3WQPVL~ah>2lr zO;TY07{S>&WdB+ehlnm*IWBSP?Sn734JWL1u_O&*%B029RW0)BbVdYtV1ktB5!4_Z zlb!6a<$l8HGoHxAZd&-Z7RM{w245+u^0Vb;y+l@CPXMm=)_n!kpsOAj6u+PV>xPzR zS8R=~`28Mo?E8)5SLhKqMptXIb_pv4U$3oYTga+f(;<rVQZMzlToMY9`^TLa`+?Z= zGexX0GmzvQ?xerDUxZ!jUVj#={w)i|gHd2H$#i6%ZyqW~PsA%N2|+GPMHUgK<jANw zqv0G1^AVpGc}(14L=#MWQR~WC!gi;g=EB&h<mC;~Y*zpr10xxJGW=0sej~qewo}5; zM=mlvubdM6#n|(hk$r6L=bCk|yOiVlW4wybJ0mfw``1ta5kND(eqvVBt@s)Y!xJ|o zo^NNq=PXQ><)*_*sRcYs7iDPGqq~I|FWek1+_`!5pil2np0bEDu&||dk)f96FEzMu zc4d0D3w5*8ST3)0Cfb()ND3OTUL#ONa~kyte6^%{fHgI9=JM&5bXhS20B=M5Q@XLw zVcqWrCn$|-(SNH(WHdVLvU|=Pn!i_D>yrd;79Iv8R@B6nE{d{859#0Wb%EgnaI-lR z`>S|DovJuOMgq7zLS!K-+JGQFN$Petlhe@8y{xO<1-~>d6(8#sb*o?3&Hg?|SySQB zHhs<_y+J+@a6>XJHho#Ojb5~O?=!t(Z&%#I(C?N{stI>vE<y@x#q(v*qtfyGt}-V8 z@)m;Sga(2Fq^`!35UgX@xfrI0g|Y@#sEv^|5~(|BJqw-DmpqKC2o<fX&?U?+I)wx0 zxc=#up(5$|SNwtHAx!GuYJ3|mpJ_e+wIfyUT7Fnslob2&)ahky7)}(E{dxf`d{nbI ze_oZoZN_6s>qMX|!^OiO?^dlFOzXmw{+gYKClhsc5Yd$HybyR|=(P8=Mi#u7u}+cW z;l)yQAZ@tWkzIcaoP^+?fFu93m2$Gj2M9votr#A7jnYI!{ZKYLu9I3Ql|R=z)4V%d zx*w|oOxQ8=Mu_}6zXQ7-v|-Ofw0u8GnkJN$f!Ey{NSDF&KDw>Y)v9hXop3lFq^s;H z)K0y3k1w}O7TA>aJ%y3U$ukG|Ye@W@yala$@v=WPdx~Diqp?ZGUV{i%iz}rQ8rv35 zOt-f#F4FWA&4QrDmEC-%2X2lsCnJ<7XU4`9VIEk!uEAkSuAfS(J)N(eQ)Ad=z>bBN zpnE@-Mo;0}7Y&oa)lxITPN@!*FfU(@)~^P$zVuS6^$?kv*GV<n4AzHXIQ)BA=>B!( z9mZ#&o2(TxE4{z&t^IMolLylU=V0{T8Z)R$G)JY{$MX6)d>rL=Gf}|?@565)f_``8 z?^Xh^7Say@B{qs?+fKw3u58PhZ4N4vx4XW93ZB>7tXqBZ@RrU2JNw`1S&b6_69Si~ z#!Sm_)()T%9XQ1l#isa!vlYwan8H7cJWz~XFLV{43MK=rR-*jb4zetH({+NQGGF04 z2*iMT43huAx>}Ew%NwhY<E6`{TbU-c(6FXlThzAZ$UP!|X$$iEGbg1{r~0VwvWpXr zyXmpxf13t*(#<>Alg?}w!GxE$=T-K6K7wI~?y0=}s<sS69PUkwlJ{(1Etz6uY-HaF zHggs)0;WGk-%Da;LU7Sl-^+ak`(W69+>4r>CUy!V*4>w&GDG#*mx$$iuli<EYY$73 zhy@ICsYsSzIY3?vjP3d71V?hnD&#Z<%l{R^F<;a9*V*NAc@1Wb^)}MdzkTN-j`uNr z93`4bf_dm+y6SMd{LGSbu=w8?CD;$nP<ce&ww|`Nt{vJ>v^#bp10sA@nssdbXk5U% z{$T2S@7*w}qE}6WAOjPARVKdG%@Q+$s6F<Tz>iBs!~LAJ;J;svVmOmf{V0ZXX0K~I zl!K#D&BMfn#KzkF{${FJ){dG~#9<9h!41%~^7VB@8h*tIN-S!kao{p*y3Fb3kgp$e zh>5q}VnMowi-+F977#-axb1BSFvrG0yQsn7L!UmUtNGz?jI|e2XADF1b5mCFxEMAh zcD`IvoG$K3B=FA?6$19v0C7**A}WR&>bFOq0S!$^p>@FoTxzOA85Qs;b{1qb@^*ui z6(2k1U8L^TRU|VX{X(ISKOh#?)I2aq^ec1FnS3v?bIsVLG-Yn)KsNM^$=r9IqTZqv zZCi8K{+5XHQSreyiVVy5H+j6+kFMKc8o%I)TMVAT{;x6VL{-4&g@D=pg;}<?e=Vf} z#>7Q9iVgx&p_`-s4*(`W*}n>~u8Ho=(^Mrnmx8hMkWX#Rg#X71i#QV%!CPD&abqGE zG(24H8t{<TkwyuN`8R6crDVW_WNoB>c&dfk7Zf%Gi@-vX2HGBQ4EDFP(;PE@v;Y25 zZRr6qgUbD*zJP5kz|W4xmMN(zNtKXFWI|ee<3%bsQE2YDM@LRex4vC_W*+(T*lFNl z|Czl0Y2lw4<AO#nRC%6W=jC;z4*g*cr}BP|DP6@p;az^ygKf|tuF1FEEKY0a8ZBR4 z*I>2svi$0T@Ex%u`tYzQPeWZQ5OV)WONa3)^TyEq##m8M$dLD%C8qa;g!k*h5LG03 zBxL=4$)U{beBI2oAcgAcpdB;(y2`^3+94^-xA^!=g*fV>N;3IkMX3FD!`Eed^c=8r zEj_jdp08|ZEa0aIc^cwv(%xrfZB8QtZj!Pk>DJg-xkSAF(^BM(@~@Uvl@qZ`S91@z z%IK|kW0iC$LO)_dm>9Czf_V!=7b43x^y(m!;LQlhKJ?n;SG{TRH8y8fIkD%R!OZco z7bXXjyOWEXM)L`n81m%<TNXF<#^>rYN+!R@Hmt}`!T^}LcFsSFY+;)+qvl;>XV3dW zJ>=-#O~pqIrQdg!^e#(RqUyZ7YKV0Yf9>mCW`>lI+#3CgZcjGVhzCkx+Z=>+!<5F< z+n6<A(nRxMKTX49YOi$WX_xle5pQ2g>CA!)vef)FU?It?7*St02#a2%F&t&MV0g0B zyU!=(riSg-@>9cxZ-+CPw<9!=GMrdZI!k+&Hf<nHv!W?!!-UT5{V=ehtOCmx^6v7G zDIY-8{B*Mkn~YR2=^htNH|FO_|9Yt3Nd%G~!#_NQ-LCJRy3x12Zr4Aba&$-!x4pOv zf8tNyFP?A=8}*@vH>)ox7=NPlKI^{!r&jdfKaROn^|#aq7b1S*JCkb{4z5NX`8M<y zE`D5+rJx9$jdk0(ck=0(x*ElX2I2Gwo~lSy3dXP@4OD7K^O$#m3gjwq4Q%u6OIsWD zDa?a2xA@MFp3<Kt?Z4SZz3!HnsE$09+^MB^=&z*EmKINxvNDM`tgzV<aAsh7zT{pu z;Y~q?&(_$fx{|x)fuD<VeBR$F1LXj$ku6vjAMk64Nf)YXUy*v&4(ZJkJG^`d>>&V( zm~%HkyyrZaTm>F;IM4gvY=pbnmj`u@ddKak{P+nrb&!#@zG=uq`b~Oiy-w-*c?jTb z06PNTg?E<2){QHTA4+BAh}%+47ci#(m{?jT?ypyu86zq@5gydI$}RkZRDa!iQ6u)P zwQ?w~h<5>p@503ngYUi5zLV}uaGFHP6gi0;DhOhA1kV0@^<vE#&$it|wNZ+S#G$e_ zZ|<2Kw_?I<Sn!X;sxS1dN4Fguz@f4)^~fkNf$axpzqC9;y9gdxZ7wf^gYJSZx%t1j zzFb=Vr?W_r5<fRq_Wa-8LdBTNb9W)E7XX1O*ox98=WknXTj=G#PDrmBxzH9sCe?Ob zib)XS1Fpxf^)~JPxuU0ce?_fKT`cC&#P-hNnRhA!Qqb!f6NcHn9~F4t6oL~A?z$$h zXM8X7$+0mVkAt|4(nk7#S6Dqc%(trfQf$PaOMH=h$oe+kjgLpOyKe8UEdICndhe&| zUsUcMe1aHj=|z}S0G}^5bu22gB%Wj&stilz_^$$C+o?6+0gSkY=*PU)PYN~b%DKzE zwQ1w=ln1OV>fB6H2Kd80^Z(zfD~zolmwG$-D!sgA8#;WnTVOOfF4Wf(fk{>)RpzVj z?9<c)4V93_yPA8;uXiZrw0=^n+c<P(>_)?Tm0E~bF~L^ThHS${TEb5KiQBE_`U4N1 zrA?($=Q9`-$#`;FApZhA-Lct^9ydRg4#)?ckSdx|4}euO1vLof8V}4%I%VP4kRB@S zEsNQwRC46{ci09s^`F(Q_I9gY<$Z?r&>;L?ctk0BUsqYU6y`vaNY=DOyp%WX6UB!p zxE$YgKO}=C4xx6zWr!m4XM7N2;^;Q7pjrrr(7@_eZ0zNBtba9xLO8y*-3yErja2yh z>)FNB_yc=L%_E28D$};1dTm29f4r~Zuf4VO+I_Jq$r~Zk77E$J0#p5)v(HzhQ0JIT zCmm(1@TJB5_93X3)wr)!S}W7cBu|XArCvI=<Y^j~9*)i_jzK4&?PxYAbP2uE*3Eo8 zMMIY*h)nOC5B-&vOP4&Sa;l#tB#y?F7C%n)tI)X;5_IPzp3rn7gic)w?j8zLXj&2b z%fuHO+&+6dIQk434k@7O8d;UwM&zhm2oJxIsi*6X(FLVVrE7=FZq1CoF2?<L7}-Ng zGPj*y=H&&M^ZkR3)7^r73#(iMJSyx%iWTC&DYWwbMlc#g@_7ZHxY2f9DS2K-UdG`x zohF%Nr5HCdhoJWlE5YwvUghNmS(F42jG36(+@#{|53s%Unlq+ZLqBt0JH}`6^l^Hh zqQogUMbqEgFsA3d?;kb%K$fIWahwikgsyw0bpOJf>p>CDaS9+dQO3bT!53dCtluxC zg`L-ElWRDg$eOe+9jCILj5+Z|=;Mqi-}`zew7-?E*e0?Jr*mx@*?BD~4S|c?`sXmZ zDBif7jiMUZkFT$-L#T&1hlJW3Kd9rdoxb6XwbRgl*lcajf2eb$`By8usn$b3Huq^5 z7qA`_tDo@M9IU86*K#U7WalNNq~OrHv$1mN^7kUx19lq)*={ciT1JR5I|)1Z+To}r zCCWk$)}MhRk@Jpgtz@C(OJ2XYemeNhySO4*WLECitz8~scXmERKRm(LvoPs@GGVZM zNSUvZ)fDOcq*-uri0@2`<0W9nsZ9Ijs$5vukARGr21ZQ}P6jf;cX-&D)|VN&pi+qB z8m-4NmfxkC_4lWmF8^^Xy|wLly6OzmQfHX0y$OzIv@Rt-B3|qAU1fLIX(?TAY}|F7 zr`0XuY3~yL!ZxjM*{9BLQ9O5ipL#uCRTV!Xh^wjc`HJ@I)3vCoLs%Yv;(XbnxIxSA zQEs35$$<O1R3KHJW;RM2VcwwA?7)&rnNlc_dq%tg8aUz*+4>o@q{)PY$s~HhgfdC= zi3FXVRC3_#i`dbhFZ>o}uZQ^nrNhmd5o+b*HySel2Le!kvb``O9ceDSJnola#5ql; z7fLNJAY{qzNR?Ozx$|#S?R#fW{B}}SIcsMOuy!w`yqAlU)25DTZd)@-V<7ur6y#jW z_~ScCsTXpE5y*&KLH6x1w3Nh^<;9J=0h<dvOhyr$JuPJ%XXKp#1lvh!xHNR1U%Dt+ zbd|->5D35$*w(%rjzHH=d)b2t%TOX$w2T2*h5{z<96PL{!pF}sD>DxME}P?W$DPB% zoKaz+^79Q1MLCCt$+MO8-F0-__3IH(|E&=*;~3WQ>~KF-s4T0%FM+a6vD1CNB$B|J z9B|&++rY?^kRp??xa6Ts_p@8PqXJOYKD+K7Mv=*YJ!gx=x_9<P_h=5^YYJN;Pr0}0 zl>3=H<%ln`v1=)7P9x+M<O&RxF#u9<v0+d|)K=b)V|W#*V9mZq&AJDU3e4U8m)`}p zWX~`cxt=Quj@-Tx;Do>IRl=EY{R?3jcUMZZncgm%^pK0Kor8<cPt_6XzWu)4J-)y~ zHXlk}T1r0D+$@~Zhmv!Y%}sX%`}q8Q0s(O}QIH=doEBlOURk-mv0y!^c5W~G<37@j z3@VWy6vQVIi6fFo<z*mAA6JRex!;ot8cm$Bj5aIfX&V3V;l@;W3g2Yn(BV}6)1}!` z&BJ`)BSx9G?WY(oUouX@UT9;S>WveO_O=tCUoj*5K(J>2>g7o$px$UYzF@yrXNj%J zhGph5#EO=AOkQ9N#fAdMMH)kroGf85Dh?AFxjAhT74PU6k3tbg6H)M;4)jIdf*0D` z9T(zg_ikVA>W#79rQ5eecDs_CH$JFDS={4I(IR~<&77^Urg3^MPKQ<Nf3oGJUv27c zyIS>U^IssG<B|(5FFi~xdH(<2hcy%XWInmP%&reM<m5yiEk2HyOr~Athw=%0K$u{& zV6&YqHb6P)>Po~w*GXT=22KvJzh59&un~(8TAq9&nL9QuTv!m1X~_fvlL<Hl?e){t zr)QdL4i66C^fQ8|#NA(Z{I?q5mZh<hp3!y{7iVis(6_V?BY1pey$&Iq_l>YD^uORz znilJ<D(_@v--s_Oy#3aXUH3U9?|0s6sfe2$BOu4P*oP1tzp`GC2<LstmPP(3r}ETz zcU8oD7cM>}bz~{Jp!!8d((l{sKbjliFS&fpetk1e51Wj|Q|T8@Uw&Lc*9nLR^>y&k zZt>fK<70^!_#AAQuXjA_AEe`Jh`SO_BD3QBCGG!9CfJh!F^yp!wt0EwQGs%=5kwIj zIlG>_=$m#;CR{3uDG!c`=R{($yvS@Kj~G)%z@k$_NTd>i>_v%8IKBRX4>RMQS4>qf zx%5ip9z+R}TOUJ8<vsI*?dGaLn`K$H?pJS((CkQjtAPrWh#_Ff(znw)5#Nq2EqyzN z*!k`B)Asn>sj*wR6Y=r66Su~4r=XprxU*|vf4{^An3e6Jff%nCYjl!74wn?{K2`PR z_Tb>N+gDMh$!VFPmzH`E+5*sOWKLa*E5|Q5vT+0gGr$pb)ho`s%$vaWbhL~0!QoPI zj$#@AsN$iEG+IA8G{@VYl^nSXk+r8Nm*5v$H0=StV~sl>7p-_lzLS>-0>?JxoM7Ar zR2%6-7bDAMg2b|}bblNvGr=E!<ub`EOz+9qF$;@v0rHrIymgj^dsv4ji5nIj(|#`q zPBr>BpG{9cfB$N8<c{BJs@tF4+I2;;(;))w&SpIvL}<E-{7Df_K7lpC5#*N9AXYtr zP4n`~rsC})O)Ubv5I*!+;A)N)A@BlAf#z5x9BX9Hx+ms&;;XBudk~Sx!~(2GRQix} z0(H=tobG{5EQmxR=*Y4vf6v6cU)|G79U^or-E>hop#(ef85=i!R90x%2QONXogK~J z3m5NiXBQs?heRxs--X6V#oxHq!l$>;a&7Yu2XZBWjCvcAiKV|emYqmIMOYgL1~w=y zDe^`@*<Asst^>1OzK1>Q2Dz*c`PX%Sp&dC;T;ivkNXnV-R6CA$fMq}RFYN5x==kIt zDhI`Wwf-oN*mALjd*EY}&rGWR-vKXdeZ(^|>Jt1srq)ZojWTC11}+(Wrqc{R21u>F zs){P3TmYTUBvbqbyD7|!PKwVU<;{Z|6qW0u_zuo2k^Q|&$l;zP{vBL=n&C=ZSTjRU zMr?nkQyVQ=@@W=nG7CP0Owgxu<z)L@mD|3rlvTq>9+*{SV_C(%e$oG$S_Le}2Kp7M zgrn(ZUPs;Zut$x}(B9TPySc*tbVr|~j(V;~&CD)%1F}~<WY-<0;HqE>%xoVMUpDIf z9bb36R#a`{yWL!Orboo5FEq?5)cDiQ9UVjTViC}#*eF!2Mpl3-k!_6sthvnT{*Lj* zux*}abd6K>a3`<d*@Z$HDc#?7CvfzQ!%mK=9P?{PRYg(~i3d`@LsDV`w5_!*`C|lt z^k#W1TlMzM+qWn3mX><(Angf~c61X@ha$4#t*NR?Km!j*|G7zt_kpBs+_FgRI;3=N z@llu|@RlaMLEN5s%}*MGhqyz~HK{a+*TurNPJZ0e!#AO(y&0cVZi5q7FewaJ(M+H9 zqGu8W4p?l@lzL(_J+9Jwo0+?OZ~T357oK?DdzR7M_V<C^keF1{PSm<tQBjqYG&woo zR-x^n=kZL#9W;Q))V5^{)1a>@#d9v-yv@fceQx$Op|-(}5*olUJ4H(e8LE>#>t#>P zL>cKc5q&kO$+E@xIHTQt?5r_ZS2wg5%iPA@8|{qowzhQjMWe^V0*4(wJ2QIAw{LH* z;B_Us;PwdSl#a$loyhFKdcqzXi9oVb-4gBV=8EyQwsyy&oiSLJg{}J~G}?8t9D{X6 zFD!?n*D>~h#;Hk;H+~_KX7mT~gB-T?CLScEmy<5|7`Pc&p0Pq1ln+Zt<&v!Y^l*CS zXYB0Xs$08yqtWh{?1*!gf{4Dw0ykG+hC*lEIwqI!ENo^ABpnj47{Jg)XEwf+_IuF| zfQ^ol06`^R?{g{qw1h)Mghz-EM@g8wCKnK9<?7B!S!5K?9F2-|4D^P?QA^aY$g}Uq zS)vv~+aPA2D`Liy4HI|Cb!a>~0{2^{kyc#HN8w*!ZbtH>d0mYps=Y9+=vhG4(;!jn z@rML^dRd#3Jv$?CbkVo?NQkiO^HtLI`D(%SwW^i)6(rJ*^?FUpY>rly<mjY0$EZbC zOp<-ANg(@LcND5wGt0_MyKi{raNqC>#onGpKHIC#lwy>ES@?j@4vZg*asWpT5R(HW z<N%BAz`3^^`2N)9wq-fIArq%R31?*f{(7P<N-%oqZQklPn@Zn@hij!o9CeSP`;mud zKa%rwt!O`{JOf~)3t%A$3t5igXattz(jphDL(B>Zr?8JaQ7o?7Y*2(ZWKjDHk0^2% z`$<UbywtN0RbP4x@Q+(5DzhXUVzWmhR0YpYRtY1K{`tt(d#&aHh*CI8>?nor6@(}? z3R1&&)GI7#4fFPjTyE0n2;`!u>3@?cHF-HVYWZ-1a1?6C`fnz-Mp+a|Z;1H~DpR?g z!ss}qiiY6rND=R*qb=CfJ(j@f6dr*x8U-%uC9JLESGA6{NfyAiKzPCvfj>4}MQs2r z;USsrxtb+}&D0$w35Tl5@JKZ`8m$(J$603-a+2w)fIC^w7-CbII|G;g9i!Pw!HHNz z!Y(QBu6tvhG1SW{aCyxUSu1m*Pfe|Q%I4An!?DEXII@Y*T|$>lOxa{gHVK!u6a+J@ zZj-#-8$wXKc_j~)xWs;mrft!FMbQQ}-I>lxk?C+XTs0??OLH``{yRQ3xq6J6j?(4v zxWphUhgJ?!y02XCv-^yb|JfWSp2HMT;Sd#jS=(ZI)OI~h$dHBY&{T1h%HSYt%hr~P z)(}pH<;cfo6r<V>3#~{*LNY9^reV2h$=Z-rR%Pp2v-S;HhpUs?igp{d03a6T3Uj6T zH)gAOw{cHQF56+Y1N1E#)c*ilHCM2UzB@2k@+r4RHc0SsdQepv59PiD%zT$AUuJM3 z(QGl$>H62n=>i~(bQSiM_pXC;xC@K)p#Jc?;IwVR@&SD{uz5l*tNNP0_{B{zez{PL z^{dKrQzqa#30<-jsnReor3d%;Pi@v^GV3#g7qlf0bScs>r3Y=vWhJ3YmLgRe2Ii6e z11^*yr|ZyJ3L{VYwvGS7D`gwLSLvIw{bk-R&rIjn<!O5VW4jxZ3z&N<nkM$E2WCn9 zR&%S?1-C=<%a6%^*_3Y^RJ!`@^gp`0lW~mSXFo-~*~&*T{=XF%^=>p7TTlG;=6j9t zzazEAgF+P?vi6)gD?F%ifP=L^CB`>!r2hegeY1=}FJNnTcJbN*)Yn}A+vo$MIS|~+ z;ih(%6Cwdbs~Sy!OkB*^{EjZ@?g>(jmiNp9q;hH{%1;R{u-q{Uy2`ZFE^#0#rwtK- zRAAw9aqQK3ioFU5-mR!+12k);3r*D2w7s`EzYZD@f91@uI3V;|5-jOJa8rxbEn#`8 zCz!$%NTgf{SgaJnaDhAeoEf5!&^z?u7CRR04q98B^1A?~E^#=hI2CL(N*|!GLZmVR z5(Vq9ybhYx16Z+GcO*{qMag%fF?%M>o1WNQOnsf|q}p9TZCkgM3s@=MJN*t~i32ol zq*~iY39aUavvUR_>ZCVYd@|Mma&F{nBt>GJ0HzNNrHI;~Bn3e3Tp^)G)0rOX&fsw% zMg#N#I-9~yDSShmGyq3t<9b#BEO-ds-q6LoG*>IR!VpIkr;dV^DZdIzZd8)7C3Ohm z(k|jsQHi4+KxxE6BYh*M3L`3Q+F6Yy0m>ORz-EG%lHk`fNxaPghz079o=;WHvjV9u z>XwT3xTabx;dZI8JZ-eJSoL{aNh`!fNXBY9A_|8_aryuWJ?JA?iL|yDwVv;Ju?EMD zV4YZ^Z1$kfzDT(!?HXYc@vNGXjH96soVcJ5kPo>uBSW?z`@bfMsS{w=4N-;S))uGy zf~W048Bn4QK{2$HZ378p)7Jt@ND*Rn+_$QMLuk_?X%ll1*_IMf0Hl;0u0x2;K?J0= zoah7Oqq2N2k8Vd783YjH3cw}+xy5a8XK0WHUn6gjRV2o%L9yQ)9db*knTEG{Qmxqg zW%2<Ae&ia-gmxC%aE;?mQCe%H4uthC6n?pZo|vLa33>%|Z-E0K3`(Qo$P>!}9-ff4 zyxo)*k=oKt9(8Gc5DIw0z{dQL;zDY(dyYT=+Odm&xxs-fKnj3DmldA;1*8L_b`eiX z%*XT=5%Mhf5iVBAHrU&ta*l4?5~Mdr1nDX4DFXPYD6SW_0Ek9PEXxA=4}Bu@%|p*2 z$OddastgJFG5z}Cd7(`3H$);Nxr8}We_CV;bnWO#61moOSei8kdMR|qVX3?*BA|4w zE>IT2fwOfNR6!)0;LiQk7ZIfo)dr|yGWzqhsPI$Ou&$`MLYa_6N@*zUhE2?3HsAm! zcEx8$F;FF;te^=NA<0#k3;I=BR50Xs^dyN~>pE9buu}nbc?Hlq(xUacy=67$O?RP$ zq$6<KJx{5n$9A#@)Ye->fxeCOr{E2|3ThqR{)R=I!!;KEftm_D&pyzE0){eoy#GH^ zgW3Qf5P<O2SMEer{%cDASJ{#%-0|EiBPsC{HCo*?J==)cXlL~_t=hV5(9YQ0T|Pk1 z(6-0pgq@V*eMpCTSf}`0FOTEs;D&un8jWMtSU#4=`|))O8hq}U`{q+Ke{PuKxisIk zthQd;+O95XL$B_p?(UJEr5^vx7rLOaDp#xKt5gl@)NP5iq(AhpIsJ%Fcq$HA7eV?? z_jBS|fBx^RIG>&G&VMg{lX2b_npguIftK4igPZk)_bF-KAzz2M4#B>2FTM8GBiHRb zd}3c2ukYn!!h`eRF6A`IwBR#SnW|jzwYuKa-};&snG<Hq{8@inwgbDj6}HLVuw$;# zU3Wun#<%!|pZ>}B{Ku#KeQyPAPz`HA!bO;d@7NU8BgBLF5R<VHe`7J#CUlCXML=%R zTUT1|NinIX%JkBVN_wQ8ltigCgMMWK``HXzV()^mATh`SWq5%Ei7*8B;R&8WgJ<-? zaHL@l3a}q1@P97x%X6;yJHO2Pgt<5g9}y;KB1cq+aWOAmg(t%A$U6FsUE{oXE2$^* z$>(%Tx|$uzJ|*2W-h2cNTmuo@fd_CGa!}52R?VxK^MBb@p38rIug<pmrrnO)r~lJf zkK$23u8*NHJ?6&p+&RBy!|a*A&U<rXt|Nl#c!dFsV-9P0!2!I7v#6s<9G#Mb3N)Y> ziAm)T^CwTT%xN~bB0ABML%El*oTNu2vMSXra_e*J+7`0w(m@_&h)k7*vPbPvOm);= zd8t%&L*3G+^pBA<kGXFT*sZ16+M=Wo75|mRWqJ9q)UI&EAN?FnAMaIOlr!z37Fts= z)zftvqG_6=Wh#I`2|ECGa0xf!nBs^JsIbBTuJf1=T*sY!kGG^wP>$qI{F0WsjAbvS zQZFL8D=j2(Om!@FY;xQ@=X#EMPIPYFN#04{so3eh(<7&MPG3>Zs0>sAY5+BYnnF#X zW>K@Kzt8V0D`SwcGI_CaukpHZ*yL}Tn6kw5*sL~3r52~oogdV8^QFVPXYRGg(mth~ zu$o$R)*x$P`W<V(EjHu2-Nx>dK1UTe3%!5@Hb8K01z=h{BD@4d863MuQKh~<D<J74 zoRoz2kpG1ej5w~e7v3{@hu(>O9ic}@B31S=iF5}<N6Qv>S}=ut@%v_;SAj%>J;jq7 z9oR$g?+ivnKt$2n;<gObS;ftC^sWvKcTuykb=2J%GY61#vj6)&W-_Hm>i+ZnV%t|d zb1@+sa43Wa|C_R1`(nPvIFY{M`Nt7ri)(!tNwDo~@Xk8h4%RY<$z{5Q5+XB>1-koz z<6>}s?uWdQwBDu7lCD&$EL^$={9b|p!aCizcAZZCyNt>$5?fuV{!B&8jkfG4xzMDD z%E_zUL<E5;z2meoNjvWSd1pVl)xmYxVh}wOj2-uS&j?I+M^ok5HG|J378iS}a~-y# z@FV-E)7+Z&$;F(U(&~l|ZM;@pl0(fAdIeAexfCq{-q70xw_yVE>Gu=?)O~jaj(9f= z@MK+%zbsWMef$2?SANgePsSfFrHCE>eR%zFVgB`d&Mud=A;5YjI_3NIf{Gca_;ZU{ z)G#ONuHL`gb&FZh*a3VMkM>18iGnI|Vu8T}`FGT-_%EkY{9{eC{0R-_UMJOXmI-Dm zj06oHE)r`FFp}<YxS8cQ0?c<&twlWi;Nb?OdPo6jnAGGp`S)+(@n&}itMfWyoas3x zx3LQ~L%0cBXKEGKRi+?Z5PUq9DkQ%l%NvRF$(x<M9f?ej53-M3ZJlm6x*Ljh#B`|l z&V+sxE~O7%`s<B8oYJHx@%{OEjPhd|G7~#~rum6M(2r9uH{xeRa44~e(O~D``6%F% zGmO<AtLlYh53syGkck8LLO+KBw%dPI^a0;N6o$J6XyrMd!86j9zkYKqxu+d*iF*4Y zpHbuY#09|~2Nd=$s4KPNFM_Vwht}S|lk+6uZDNZ^Utl6kE3V`=&CL#1OIE*zQw4Ws zi}=V(vvawp|9`zfGxIs>yXSzeV3+RG31}Gxd-%a=5dwzQivggYu=M|(SDPj-){U{< zw0c~G?dYH9*^M)jprz4E(6Tsnm>-sKGe{f`toCxC^~+`#0<wlBs<WFB9=mJ#Sn@6W zvm$8o(2Q!*sNQXigERo41g{`oxDS`@JXvVY7Pk3PbK}Cec#lByPM*n$SAUq9Z)K6o zZIj*W4iuLftLEZOZ4RwE7_Bf0;*X?Zx>v?W<!Nauakp>Y*dM_lYP^`NN2l#0Oi3+? zcdF0~&QL}#F#BeOuiNP{AsUakEZs^Az(GCcHNYz9>~~>)KI4pDYm2x+sSPJt8TMi! zH&Q3rMMevDDqXQU5xtNM`J1HavRXRFjVFnIsZ&F}CwMxMs=d7B44sLG@Tv9+%#SVC zgh>C(dxJI`MD&htphapln2q>Aqp6>YLAN3tR9def_l&Qx04B&XY?E7xGt0d{4`o6* z<@ZYAr&=hw`4F%Q9DeDF^cPAV)Dp0lqBv+xc1dfIoPv|T0=Ft(SP;S_N)B3VI!L_e z)M!`*2^kBTLPh4F9mR5)$-b?1=qx!4A*86`OdjVgQ)`!lbcFCq&a^<5@Xel5@6vRx zufkhjTe$Wx_tQDOdc}_^U}S+RG;<%o<~_!ZwjWhj!h!a{_Q7O&ruk^rq)VBI$=i$A zGQ^=RbrsX4x;7SS>U9Qn<_5RdE5Q9%X;-h5iJi0WvBhJnO)xL%9Qfx8%ClP&^Sy34 ztTHjN*D(!sd!Sj*1ZrN<I@(m`9ij#r$nA(MY?dqsV7JxgG%+`{gz>$kVzTR)wo@tG zNw)^YlM?jL-M3ffC-vCRbHS||UfQ6vUT^aWYergCjO|&pI7sDL#EmpZi?+$12Fk6? zF}$C5tb4F-c5W0>qL5(k4elO;va49v6;u)|dIL)ZUTgwg0$&lDQ&CrAbP+c_wA89d zlDtRQIUuNsF%BHjH6QLEI~*&uN0|~Kg0VfPR7x_3qQf%-&j-Cq93skTB%fQq*qh|# z9bF$$Z>42E;w(v~-ceaO^^iO+_F<mmWf+C@8;4fLYs;|foG55aa=^E(W~?gOY3GQX zf<{O+Qv5qj$V9S`4&q?V^@7+0dMvS1_eE-5ZnI}SMFt;Ch%dPoCZw}zqs5R!N0bSE zRW*@yp^$TLr+OKqI*uJH%rd(KfYV@w@g-jT{$?Py(`!))$?*JGNq~N0hQ10>KxjA{ zX#VTzq!!Num&b_SaOc-CAW&&ATd;MU>K|(d!Z$BlXKj=s5au~(z$ZiQmG21Y8$ULS z?L{p<Jskp<K6ld`r5|b%Z||jO@R4Ac)?@4#h2JAqyVp7MNC%my)Lo1lZU*8g08av3 zlqkR=o<&kCelFffYs0U5ivt1ynebTdVZC>hes3HG#hP0|ENR?9yQk%ykQf2xh3d>@ ziw{Zch)F(7nA(9i1ZSdm$B?{YPxafgIq9LIu2?MA8)a7A+A89%o~Bx#j{Kuwca<cc z3imN=fuJR=^u`7IfoZf7Ma|Akx@=y(9|?<4SMTQ2xzSpig0h@I&7bU=ZBztnWZPG# z5K%w+=<%8d)yYurr&=Vuti_AC$~)>ux5zY8WZ(4Phc>Y-))qqlkLgKQu0m=_WG|)w zQPLdQ2eSw<z(!QjN|qLpMZ&*>Tqqm1_{Ua0gEt$D#u+lPOY81*?~&HFbtPYwVf5vh z_c+I3r%rWsK2fjY!{@yCU=zG&^au6oR6jB$xWo2yUlA&_{UFP7p-m7nBG^u#1w=X} z!F=866#!f-l^|26<<G{&A9{o%gocG!IdxJ`c%Rfce23cPdf+=60oHDxwe*j>h21hN zqBc%7yrsF2xWMjWnY9+Hk7;u5RZ@<tlOhnDhh?OS&YPQtl)H<ly9p8sq5f&IY$b~X z@$oz&Q-5=h0*pKz1a2)8X(-QQvgpJ`&{*>8tcQ#P`4FNYkve5kE1_-qGP*9;M9OPI ztO%DJ6)qP~MklRP^JSrsf&nA0O0$cu@{$Pob>t<_fz+>_2tDKDA54HU!#;Dz=+o4^ zf&VMuhFjd(;Fl4t5q9Fz)u$WOp331@F$ighYKH&r@cxICnn<lV6X|aC^ep&Zmbvzm zMqs`0714E@=98lR3>Qd_0R|B~AR^a@f?5uxQ*3+8%5Ezque4=|*DukI%JEU!lm_vA z^Om4H-mT2uc%2w<As$xrk%S40u>k2dLa)5`?_67ywwyfu^>iRMd#i!7tZrp)Is_^G z4NVQ~z9B<&Ju|a|?TKOt2Sv`sXmHK`Ga}ec>Cv;F!?5fjFOw6S-a#KP`1JU7B4_!9 z)%i=?J?fm%TfUNe3i1w*QP~CskKC`#L#mUIgIbuK!Lc>F3KF07vKi25{dI#sKhKz) zBJ-MbC)m=jmJZMBF0a6I|0U&L0{=8AoTG3n)Xw7ql$qom614&`RnOmE`|_h{O(VBy zJ@O^{^&`~uH#F8Udj>Soj|Uf<m_!tms8VOd4aEHdt3L3py(n-l?fNfHc*fbn=@d0o zKX?H4#q<m7>Ci5&Gtq^9G`OauKIH-GEs^N7-g4SFwHc^OVPsj8U9*kSFduf9l#YXF zQ9q+Qy=ELpb<bx$TOKYmw!Ty<nVb3E-Yt1KcA!)?2}$-fR#>ghr|BDOEX=h;K}j8d z5e0&mfx7XKkKVF66B&x?`k`{hgdp+Dj3h-K^-ApKZ2VYBtKX+6y<I}9Zs*-z5=>6U z2yx@x&_YFkD&l6;Fi5K&FdT;*M-LvU`2S9%v|w)-se@td8BGC1VN*X7ni2nyJao3o z42fvqp&7*lRmtkAc)tA?|2kgUb1a!OM-FY?%pxGEYRg1>wfElgp%(cZe|LP<e?Rnm z%;b`oOud@p**{;>bzf~7iU&bfP9JPZilzwy7WzmJHel>E0gyyr%A~eiIO&;dgLeKy z5omiTteD^YnkTu6s-1yUSH!<V7>XyrG1ufwkqwTK+KvDDgkJs}F()HnFf)>tPgaXO z9^_+EPS8BvHhLw81#aHFx>)8lT^tC;J;6{REbPCIX?lTy6M7m7<AynkD$V{ea$J`1 z+kl8qFZ!aKH$xrCr6P1|vP)h|+9^0~QQr8s<>e-mbgEi+wth*4fw<7>vPHKdU&yms zwq$dCO8KnB1x<=1yOPa@U1THN$qFnW3w{0B*t8@tkPM=6M3Fgxjwl`lu;#22yAC#B zo60+s92dtDx=|7~#&ION+ai!pT{Qp^-~DhCo-NFS&L}$El@<ELh)k2jb`eGoAPDIb zAg4P=WlPUA2@Hsjh`r3jP&jCDEIB*~l~7atpAv$*a_nw_$n`JRPhm3rG&0E6Wyk=9 z@zYT^n!6%5&oI@b8KxQ()7w*p7N~}F6_!m~uCyjGr<l_$@dB{-Zi*slqH8NQLacK^ zc^6!AtJ}!p08MhTwXaK!4XT^fUM)HWtT?Yu(;-u$8td7Q)BuDcJqV6;lLGtumMJ_1 zvFR2-T;Uq&28j9Q#FO|D)YYX(H#j3*3~-))8Guu5eGDDhN@u|h*kVww;OF?mEDQYm zNEQ&&-C&2moi@`1?=#Sm`5-ke)JNf9*1;gqBsp1Ck!TmepA5?!#qTO@H+(B?ZS_+3 z#&?SyUM=8y!K7=v4yrt5M~=w%PkP;a$c&?|w8%QqaB&ljV|dW6YW1_7oLL-?7t1=H z#-PzFS4nyjQ;@A<7Y75EmRb%2hDurm>g^)vNng0CB$1JKlcg#atW_J&BqBt6gqng5 z?i-x$d>&X`qEsF2pKaLpGQe+w2*IK4LG`W#^~x!DGSKl+eGW9W99T$cf<OoCF*?^- zli$@>CX(K@dZx_R>e(j(F6{3(y1sHrm%HlE;@{nql6C9-x9xo{NuM8EnfC~AHbUZ^ zJif9gIU&av)`<OP6b&GcZ2|#!i?P%Pf2#LbqTguJF%F%IcgO9%?9}AxiL~ATqH~>$ zb^Gko35%ZnPXxkSeQSXL7Ob=Ca0Hv&NDp#Ur(52Xpt{`W)XQ`knuLjEpi+OG@L+LK zx6FO~Ud9o{40AL0@&*doh^W;K)1YWMj<%REbWsC0asO4y0-4pMGvSNl<<>C~R;FgS zUg|%Gw<mYB`kx;;p2?gXGY-B$(J&oq=Yc0x{G3ZG5NW&%Zv0?9<8`?0kgMGo5BXN3 zvP%L|4&{{pK1HYX^@nc=`%@(2J)ZyK)*HG`zw-f^ci>AZQ(@aIcI>vDG{0{c<)lc* z*ox#5wJSy?t;w!}lgy(YYBk<scnZ0V8-xU;G+qQ(;pN@qp+qj%I%o<0TMgz<mC=AG z@8@%u6EIe8M*D{#qoic*bUzp$FujJ@7yVD})2Ea1b6eOWnM8cAX`0W(U(CEA?s&sX z^FpzLG=ZwA*NJ)`m6#gw%>54|6q|3Ym>Wn_ZbkSUyrpPpqjIqFz7~5S^2fZkxeY0< zOd|q)UqhmOW2L1E!Z+-SQ(2J-4W-7)Ob<Wisw@qeI@kALp6)z8l>E+17mETF8p5*s z6SK=o>Y10lqQ^JJqVs@U$v|WnO-4HX-wY(a|HkSEoa)o*@(W`?!-kh_@+$ndTGd}G z?bVS`@@hR0Y6~*xL*sM`SKp#me;WGMK93If==3sN3<-@X(FF9>Q0y&Ny`m_(?rCb5 zYb3!*ymjo|`T2Re8uyUsYyfGk^@gus6Gv}6{a*(yukq}Yf$%oOIL=cWuf~bpO8Y)S zypWtNCn8}O$sjSpQ7=kY>&mZ-Sd!Yg%A*<pCF){}`+>^O4nyAjbU7a96biO@eNdg_ zhJ*5+N<D$dsw>sJnLTVeNI|!p7in-4vW)^qM0b=jte!fDH6fV{B{0XnU6wx+4efo$ zD#nMRRet!qvhhVA6pzPZCqA^aJ7tU2Lss^k7;yUBJV{I%gUFsEuyY4bH4h!k=9wv} z=j%GHzyh_HD98vuH$l;0kJ!plVYgW%Bkf$y-OhA^B{1EwL1i%D5l2eT#w9Q0I6ti8 zI#&@6;wU`hVEP1cdOLR2LGqAs3rWdY>_*41R|3zCjM-v^`9~_es$tt&bS5>6K-EFW zhk9e-YumT`YSyhfQw<+Yuf6IFXU}LvT<Lc9B58QaNI!Do<x3D6hFWVAZ&w*MONy%g zj8)V+l+4Rqu=nY={q(@<t)mN5xy*6a$z(*Fw@GTV$ys(<!ge5Vcz7~|gvKw$s20h( z<v0TZlQJaMHpI2RkN#qIGqKc0EfJE5OgoOSHs0$r_(J8v-Y}6xV(ZC$2t%SCq-IQQ z79n6&4AjEZu7>HG^^QB@o*r8{%<g#ij@>Ciu;iV$V|QJon`=_}(C(^<#q{wpOtP+i z0m3;ZA(lgm+Og4F4irH2%lhVJN*euJuwIe+_yI$iO}`-;n;8qY5IvJl2fC)}b(uoR z*WMYQn-3rJg=fqfaaeT3G3Al3H5PzEoTrSaw+x2n#szE#nifRVC51>I9=v?%!4_4y zo=0Tjs}am{O)b|)bvJNOE#bs!087>zwvugH{MG$?qM7~C&2QiA2;L30GD71h#-1_T zyZg1TypT6GCoI_1?69>DRO2^QJcv|naaCfn4t+Nnt>JSv(Ia8VST8IVnS7;}ZpPe= z*7GsE?PFLlmv@Hez17IG0WF**^>PS#v^?!9l+{b^ktz__yL}I_*xo%O?#<Z#Oxs&A zdi<W_dEm9MmrEC%XRjn5T$^nLCgE9FRmOFP?C+*zt}teesS<9KHa;W_i9vbW{S+VJ zmMvo9)xvoFKos&6gTey7M5h20R$6EumA9yWWD053%Pb_2EY6wAV>&Kn{Jzwew`Oxy z8<C(#$s`tkCc5c$&3S|{X!@DG=Wiyl5lp-QF?F{hkv7`3K}qN8y_knIf^8_Z;0}UT zh0*{ENqyk$JcLmki1tqyXIk>ujH-7^RW0$Ekx!L*Qs`+XIG_UC115NQU<JL4ee24f zT5h7}4;8W8NZFq?|3gDYQ~!kZM4w#tG6bQ>iG}mAR2`YqpoRSCF7?GUPC&U1Vfi{V zP7$pBg6aIX72lm5cc*i;vbusdTed-qfZVkmy6H3-o3kwwe;sE1u}_ZpSOV-K^V*rm zQ=W?9HR71j_CKbA!GJ2eS~zkeV{IPeJ7r3u9cSt#Tw1@Z>SnK`fm8%Ez1WYAh~SB7 z>*k~&mZbLSi<bE&B}n)M_FyX*8cHOul+N`CHNNYw$JIG=jzYSsU4n9P75F~JknB{@ zEPon=K)T_)CD_R?q^|D`Y}pbJtvcxM#o=fWI8k1hLaRJ`!0{G2PW1AElrBOF+iH}w z9*Hy5cFSX)hgtb35lQ6HTJB8*m(Q^q9OXV2mK{et`{pV$26Sr7b$`JpY>W}7;F$wP zgfkV~q8*ow0^bA%4s7B+99Tl25zNER?^)zjcmGb;Un%+-{x|4uiL&6N2LQ4x>Jzr3 zHKHlUobw`-xLia);M4Dj$KIl5ohw!;$v}|2A`j!b4NmU~!&0%AQwGkk3#UmB_r5e1 zW^7-V%SD-eQ-`PZw*sXV2Sn0~+zl*$X(QZr&5j4S9-BWr4Y|r1N$Onw@z}4F(9Uux zAL^44(#;^PzB~%ZA#(8~cZw@p&02-D42RXmP|O+rjWj=TYB|+gE#V`dY{e6&5STBP zs*E=UydfyEkly3mcaF~F70PTBNwM<)tTfp4$P`a1(QDEIci1twKt4&hhv4xO_WWEl zD$XiXm#kd5Ke%lO2CGFcur(zRj<?26AQf^8uPiFE*6flgmDYQwcDmRzR_Me_N(cjP zn4TP6k|x(gezZlZzT++lRPmPxHJ1%-^C25N>0r!8!H}1*SWN(6SG5p@vM<zqu6~`_ z-d<w{QQk>%uTFMHXY%_}K(rQiB(1K5Ahj7VobbZVVww}pe}<$)%H*gOc22?X<Hx&d z)|yrotrjhkh*eh@XyjWogta6nKv4<iIG(&W{5leOBq;o|n$nP$+h6L?fNO>ie3;VY z9#p{eIXgOov2eh*C9rpYDA27=6~UuE0DA4T!<d=ZS^B1z6)kxoxKN<<F+?Sw@V9&{ z%~MevBj{dH$v%F#xG|Ext#U`ii}C^`tv+?jwKX4V!KSU)xqakg0@z3`x?MB1-4n$r z5z(ar8Q#IOQK&*<uk+~XW7+XEFWgvDGCbW<#`^E^UhpXDw`RGFklWdSPi1@gP@4n- zN4`<Nz;uce&ZloMpNPP7;lXf3<W0c->MNm4R9m#V{VpDkTK;b~pDoy=A|RMtZk%(R zk6@ipBD%l$&b7O=SSy1B?tDRWfm})xo?-&N?G!wjT=Pw;kPnr{vKKx<_+$|^XyRg$ zWlf;9qwdqH@A~>%{ToL75KOYZuF1YtV%R)iWYDd4*@<K4neMq0-fn^7+YCFsITK~` zj7|4k^osV>3qAh4eXZ&+GIYx|0Lnc}Hl-Iequ6_vq-CKP;fF_nktI=sPDfXZV`ZE6 zd%ZDsjkOpsBJW_s_Swk9xI4ow$mqDc%`IOUQ@?h~^cLmRmhmOmN-*na6rl(VPm`68 zv|vfB7>gLuJvtGM&5lZywXafUv7KJpv{Jvs_FSGnlF}}=!iguwTAnTq><eA~MxzK5 z@P-c7s~CoEQ!4$zNr<8G?NhbGzSOVLuICu}km-nkqM5D%g=LDdCcCn0ft`XA=R?P* zP+S7wG|{?zxw__^nY@OF<2^=*ujL!jcNZMcRVaOACr__XX~*sp1vm)|C1_p{?JCct zhhAF|Bd-P}W0`zr;xT<^3WW|8QIQC8rq=stb}$6Va|h(TwE@jL?_2fv<4NnM!7h8! z`JMuWV#P5CN-vO^B2wXZUN;~k+~J#b*jJ=HU{9)d+WfutA3J|W*>~r+OB_<2fHKs= zG^N?vTXp9KGEur=!@Y8db@cvFvtHh2>BXhg4?i<{Y<ykALVRS|xoFA<Z<R1NSoBHd zab5AD{+Nu_UDaJq-Ql3JI<2;ekNk_$AX!mFKP(tIk{|Kl!s{7cFGmALK!oUWHf$BM zOij1pG|6jq)-@U@!<~M|WAS0lO|mtYXvvdkOm5xQ>qs<g>71#UUC2GmX3+o|@0`L8 zG`&D_NZ^_g*UhChsX_%TG`sF-+wx#RdCM&CJ}di@ZX3>&iXHsaw$XBp(~HV*SV$U| z?bn|?naMDEHi}6Q7P2|cJ^K9@(%Et4-p06~kl3r5^*-(X<Wy6iqQs9d+tK#jbw!>h z6f>n<i(SE(_qg7}DZ}piBPc4EHdTZFf6dYoVae$$!Z-bIHhkGEi*F=eJXOm+$3kqq z!lNWd9PROlu_OEasd96VQ$0SQ3Jr|uKck?+G1o=?;%}byR>M|e-$*`N9f!QY_;H9p zH=_h%DNSUU4h!|V-YU5t&d;AU^hb2?+Sd3a6^KyW*~Zlj$LqrNmg@c`x97HDZ;yS! zz-Y-k(SyZ&>I`)_e2&^hzUGQi{!-QT{P^NlW6&xc^nw;oRdzWp5n|qVFUwJ~kJubD z-Ee~j&zDK5I7z-m^5iec9z@XOtHk8*sHkOxhs?;W;=#z~g1UIv9R)>?DxZ0QIWsGN zQXY3ef0fr=xO;02{P0))OVuKTc=W2Y1&Mx?RdG$|!r4UHPaw@mh=5f7$TY5ao}H|H zK9yDCca+fRC9={Yu)y+3rJqrBcNd|a`j27{t-M7<RutS3+pU&-ap;i*hxltvjDIzb zB|1I@)VD9bl=4euAE;|KhI7`)^}23jGPr7N)3HNTTD3)3bvIE3L6t1mdmwa}UoMV3 zgwSyer>cG>zL2^e(>hyuQFP%KSYA`%B<O|7WQ}Lqn=wBvhCR(N6Jhm*as{7W)$KD$ zCts<zM~+(7UXcyF(ITfx{|pGX3`)64PF-rVNAZI^#S90o>P?l!0$&z|!@z@cn!FAb zyj2*IAv>sc2!jYGQt5G3!p9WY)@?L2HME0k26bNoGujJ+1bv?t^dMprB<vBWt8rXt zTotK9(!2*yY+7S@<tX^wUo_t!MK7cdez5n{r6?4{V4vs=iEfLSlM*C`Y|g}K|3sZk zT7=puCX<7C<J;kYuNfT3rBn-6&Qudi7`6B(kY43X0yyVdp!|6Q;~ih!EP8>#5^Uze zI}_c)3XB(P`~v``>9(`>>*$RgNG-yPT7q4=2LxvMDq}LOFIOJycNw!)IR)Gyc#hO2 z2u$vs;-^Mu^iy|4T?PMX;E8-5ViPyEC43~ktmhiaYl7lbmIQbuU_9N67CCIrkCGJD z+_GpwoM6&|sds;ys_Czj9drJm7~XnnMhc`;?gHKwZz6#s=u&v+uD1*XkQ4K+rE31| zDBHpVm^xO@@$$2I+;Cp+gBu)LRPGa@^@Uz@9R!p*PxBm&XXAlJDR>iD5QITQG5giq zs@rF#3`X5vuOQsRNJfQ<j@h~lQmeuASr}hK`i#H6=f1GapRGxIpyU4{yRvlWQaHsE zGJ)RH3^F+KG4c>LW&!TeApJ5CH<>P$*SPecLw<8IuU^k>Sg<W^6olKJJ7r>w&k41X z%C<>8@{x{yrYp=@GvP@)n3RGt?$Mrc98BU`YF(14Qeu`7Qz0bf!PF%Y5?sP~2ZsvF zrwW4n@_Q(Nq!^2ABe4oSNX3}R%F<;e-b2LW+OuT{6ZSMP5ndB9XFiYYHW5IrXciJu z7%B)Zzef?7<kwV}|5scGyAO|>@$Y+PLy~0jIs1^%=m>%WAI3A2c1aT$rq4yzE`kSo z68I)CnbM>RA&_FTJUpte7TtHA4w=|{T0;kRg*sw;!dxX_GW~Zg!Ma?knme1&`>ez7 zSk0my%L7SCDXYd^oKM0M9gL+bd;#Vvg5^-@g_eT}5Y+VBov=C@(R=f9%eosRJsxr8 z=R*j34Layf=7#2AKz3VpQS|KUQ@h81_25K{>Q|iXnywh=s8u<IJ5G!rS(0*^&x@(9 z4kap36`-?(o^h8r=!AFJnbKT)-LfHy`~Bw)_+J_-IO`O@!-zQc@!k_ru-B`?A^l7+ z*5QWqlHPrfZ&Nx~$8zmd>B8gw;1gZ^wYG7i=3G(j8GrPfC}x2i-W+YNyl#@c|I?2J zCA`5U73$?8ew=W33_0%_bF5l`{+MBY&CYb1V(7^Eo5`ztj}9fm`&+?&b0uxE9&Oo? zw*E|Urp^-X#Vhwj+(R=gtH{=|U?xqo<0`?#o;iIlI{cJrzlfDhjrC7$&abA~rn~N) zfdCoLjcY~=3l>+Ic#dsCCfXW!PAEf7)J6?Lk%t9n_`u&d={`38`!E6@dV)KvNO#LY zDJJ%1+wqn^U|pcv53!Ty;^fq>b0W@?oUMWF-T}7)hZ70Q;9(=<9HXE~G2*Y!6q1MV z9D=ABE(sWdeaaext=I|43w|`2pB>Zs2rPzuPj9u!wUAs8bN4iZf^hQ}bY9FqB>y!` zfR?At;(E)~tw5Wh{)P>^u9kgSd1MH(-To61GjRKDxMEG~*Lab3_{|^m+br5by)B&; z6K-t$4mG<&oe-;{&+u>ZATPD(G0y8o)k=KYP2#;~!&+~7yG|{<hCp?ci7>lyx!8e$ z$~ywO-pR*fPW*!o6lNF1PT(i;3x+fqQISZ8+C55MI?pRv@ckta^D<-=JdJiV6WRRs zcal*M6~jT5dl5yoq>MPGK&!7CpNfQHp%|vW1|6ApdTFMOm5kWUJ`P_CU1R67*<4p8 zrAxo|uK44N(=pGtZ^Z;-S))>%2d2Ig4AV!~%46(RGQerPDwePFa&zznBiK7FVh)Fk zH+%9tEy6v$Sj7^r_n`cBejok?p2E|cz_F$sG}YexnCDy+v?*uVZSna_$6X@EqmKUV z3J*@h9gi0z*9(VJ?5TtVN|mRDv&|l~SEzZZHPA(*d9R`@t~=}XfKq5A8;VW1JT$ZP zm>tdSh@T`b0B}rV+`?yC_VaSy`7i7Nv|CF4SILz*7c)11P~B?0;?DAWfd85<C_0QW zT%^bCK5<hM0VXxs%EG_$_@lqxCA&xtpG!wv{44XhIK*fn|4hn02l2Xa?qmQBPtWCs znn~x-bt*S^0Y6Q2TM`NTH;|gH)w^M>)<AR}UzJv|#&J5p<`Cd29Hmcru|g;d`|yRl zAAe1h1F#o9ZRu;eYhK*mQIm3JhYLl<jo7zlZ~<j3CXV%~_8@8%4BqCYhh<=GsMXVA z1AS+wBD}jFz^xZ^r1M0oYYn`a|Cz1#f7Rtihvmb<((Ib9#o;1PJATG>>Fp>j4Gykd zYdh|Iu;lVbMoDqj_#`z|wy^Gl!6=6|#!s>_)<Hu5U)hz8I)eqU1#89agV&p8x0lF( z**&V(R<!%F0}y?htz<!pL3Nc6EZ<<a1*eb=W#n>!B@P@_iVSX6^wC&sM;y?asVi~1 z51uUe+`#*aEck$>+eYIhj^z6;9Q0g<aDviG4KFv`!_&LFZGFt<i|Ob{TI%1ec%|l< zj&2c$nnKB8(u{q$-`k1v-hrOCOeqN(v&m0G*$0o)g8Qy7g}T%^i^_#QTZZHDJQ<fC zrX!;Vc89b$T&`UOvtUh%IQeC(!22Xj{Au*GUiUb)q5Hc2C1puGHdxMIRW61Gf~&jG zvUN2UHQ;wzDNV;p@P+XsCY>P3pf7i5fu584IBHynN&2~)E;%WBuphAzs2!tqn|Gk) zcw-Ilw-Cy&_lo5Dg&h$shASHN2><;{8W)PYXD@qY;(crMsmN2uZ;`Ei7$Q@K*pn}O z<n5JEw+`FDL?9z!(FSbYTydeChOn*2G-GJG$^-K9_JUfT<AZwBYi}#TF2npez<zje z(PLA*<B{}}>H7>+x0Gwr2pIezAWL%jT`!2<{)V0efarAC+6~fl7QUv)_65Tog)+{> zVynTk&y7gALhq*6H%`Xq3j|drl+IWyb%jSraJx{sritzfdbQ8s-or2X8DUzAXr0S7 zVbwXeQCg?Tw^<XnZC#3-eKFQfO$CBR$TXBlbj0wOVv<pfq5U{bH)zB5<Mo;-J+l)g z^`R;AY$8C9%_cWC^NCjqzUs7fvQq68{r)e{rL}nOIJ)+?DYNn{eCwH)A~?f{Z0yn4 z>}gV_Kjn5HWWxwlL7VtJ$9=D*4578lG$kCSN5rdjh*!?NmTMzvQ9?H+-L_%O!|4yb z!{&CDGwXQ^ov@j3<a3z^So+mYr7{WavjZ+*3_Cl@nZbd8?&jiaG`z(t@VKNj<`elv z>Yso0ObqSOL=eJCzmS^*Hg(&Er@mEw``PmX+6?^Fec&L}|6h$J+-Wl5fT66USJW*L zxf!wwg&h(@8?|y;lj5M5!?*v=#zpJs`7Oqm_@3~VfLD`eZO1t@Eb_s7uRYgmAQ}~j z@RvXR<+4Q^{`tdmk?Z$A_}OE=@N+T<81z_PP4mm)`?a}{c#m$aeZuu*H0tFt3&``^ zkd$1AgBDdW^)>bATG~t<@GK)AF;U>z8u8)<O|>ox44md7w`!V~h{rgRcr$e^Jgb9~ zM>vPM)<DQCtfip`{3TR^c8P)`?2rgx9enx9y>IO^)L!~Awr5bGm87Yq2EQ3To<6=e z7<@W8oEkoM0Xw?K(qp1CxbT8D>F~EbZ5Q6b4SlDKQ?xL6vtMh5tf@G53GA0nt*H>S zvTjwj89eoMzIv$9>4r>e10kZ+=>c+k_&lPID<&Hh6o2CJ1Wig^-bD-9HgbPLlyCY< z@;CWgE922|wT4|*^?*0JjRczR#U@gz9z9g5-*|HSu%4S<`TfNU*3qet`s0}MIJOcm z*@q{1{pRYFyj#9odon&_yDqsUo-pl-tI$xjs#;eyO^aZ2)#mHhEi*?LY}yToYC|9! zIkq_=)Py6>dP-oAM=*{b>{9Kr)*qCo8t?*0;c~`%?Rh^1tRBpAuf6HfLGa;>hfZFR z^c`K&9bEe4KMG|CQrkGla*={8T-45m^it6=HE-m%!P)!`T<=wNy@cFDBL~Mx%?!M8 z-!UGtT_!_fW_?bt0mrD&rmY_7<k7{1P@l^1-g>F@xGaLk;}&vUY{xp^6IduA?UKRf z+jnz4b^;M{R<8Ed{dYPuaqD7Y-%F<>;j706KO*6>-wS-`%I2chv=VzOd8oJ#H0TDZ zPu`pm(_4?S+xrbeLembAj~`=hy=~=(?nIOGs`V38TwaOQ={;uyK7O|lwRtDqLe%a} zI6;%z_%Lay&rmPLvutySjV@G)iPikK!PCs-DXx^6I&!fP4RMY|&#bDfFE|3Hj0L|3 zU-rp*C@bn7dY~*`F}q<<hMJ%WwCVZIiR<oUZ8GI^170FZyV8H^=5t2ce9mWH*PO-@ zvu$SEa9N(6mhLR9Q@jtuu}-wm?!j2R?8aWIuUGYWA>p?UwBlo0G>XY<hIoU9Rg^_# z7-PkJM|YRhV2>J%Itg)K0R<1Y9_T=t9BQN41mzV`*441y-dxH$WFKwE3>oZC;fdU% zeDsYKoyV(nz8sqA{0DRoWYqjd5S3UPUkh|J*K?}JUp_p<jnOL>`h|%~`==_Df${Fj z#Bk+1@xQ!$c0<veoOL{Q_?#5;Q)Yl;XVdY~YonX{5{ImCI8r{vAL+m%hphT7O#CFa zrgt`@W2318wW1)@<j}*boiAW6JKUn$2R35%bug15lN{&}bCJ$UJp@M<i009&%!E5T zP*;ljZLuh3(=stYZ!;V6EPCd#Yotw}2xpIL^ApzxwTO0DPu@ZRgq<$weS2cXg(kHG z!RA`URZ=QVQsq;Iga!)^p;7&vWs1PFL&eHK9OXC!r!vIuQBmj&3MA%oE!cG_5JWzx zFsbn}MqnOv*)*&UcawGQBSVS_;i2-{_h8%x-NKNqv@-f^6uTFm4Q?^F1%qYQVTZ#> zX|4l|`bkKMZVI%1^2PVCo8C_BA92j?Pn_5_Msl97)34zB#wHR}K5seaMpmCqJ?1v7 z$)VFR(fM1#i%~GHXn~5={BG6k!i?Vq20aY=cn^nAZi`C(S36ZrZ9f$ULu|>8<@c^b zGp`QAE~GpC%}DbHGofG?gI)0#s4jvbCf}=#U)8`)Us2|hOLcsj3I-OyO5up=X$U?a z^Vb9%<y`jm*wNDVr-${=Ja@dH6dN#$>vy#InGTA|3mOW>Bou)lSoJ-Z%7z?!@cEwI z6!8CL{`EB-_VFs}BHPeuG$x9_dEkr`due}U2{~j<P6FS{9md!2U_B!I)9I&@q^G|p zUE~1Ckq)Sw!$r*+X=`A;Bu)$P*aeO4kE>-f;X$quZd8=b9!u{%u6x;2L@&d)?DL_5 z_Bf~SNlz%#D{k5?frDey%8fq>@|xwTn%}HSwRQFe_Wof#K35qHc~KOS<`0;>Y$|sM zhTuI4E#B|+&$AQkXMhV(k_|Y9En=T~Pr|<@bo%Tazb$j<v;m)2J1w$=CWLe@hCffT z<U?dX*-hL;^4#4W=_tVYC=i@%S{#a{)n6DIO`kX?Y1az{9|+*hA=7Tc;)k2JV<DJ+ z`s3~VDv-}dchxoE``Q}8!;g%1fAOl|35qbcAgr4kI{B(tMD#*jOIYp1bEPQdbO9-o z*RQ2V4;88nMPS@&wq8nqm`2$yLSjVH9eQ5a0{w&}2w)Q&Xx}n$k;?=|)utJoQI#Ae zdc{=*MklXMn^+b*;V}2$vfdHjLOt5h4-cqnzmnF7*4&m-nT(Zs>|%4`>aqR=ssD@E zu0LOT&Am&hV<>E^=vS*!P8^8DHk_|T{90(k2FEuuuPr3zb$??ebw0fI+2gvmwWG5g zjcqlNaa%V{=^KfkePk<7t&ud~#Ce<vU2SaUXa#A5<Q|y*X5Q0)!>hihoOw;xzbwNH z<KxkNgbUoQULPb9Kkdat2fLFHm?&Ex-+qdETjtqs*BW4F{hD%Ps34skI5;1|qx9R? zB?p{67ug!*x1u=I)9)laEvyMr37^1fwO567bijhKpA+-UbM$&7mdxXS;5;{WKYZgP z`W{z1e!c6}@$|VjU6JeJ$vgP@)Z|w~LO*V#?is#p@`~7;wnO2j_Rbvy6(jd{XTA_Q zkeFIdB^F5FH4%e`(RJe9I{iI~co_j6I(xKp#So=%GQGqxPQYZz7C-2~?4xS<%UzGJ zkg;9Yse<Uc6K9OSxrczOz)U}|MsE&0|Dv2Avp95ghTgI@@=`Vsd*i-ieA=mNAIm0E zXOtEF;cKj6&2lve>5O4ZV-^k4)JbB=k8cvCkPVv4)}=QO7wLXUZ=|MDM<Nk0*sDSj zAH(n3vN=F?)-u+^gZz;VjWeM%X+AZjZsg=^xIe3E;U`<Tz3(TFpBqdbcpbv?H*Ro^ zU7~J3tvy!)VXsj+e_fntQ0POAWJQiIQ6psPf1gQ6@#eq%<tTI7<1)>7DcJd<KrqTt zJ%au*`%gO2h>=tCTNAMx4sl=yKkFLJnW9##Qs(O!VthQTQ~A>0H0fw~p!dYPYU)D@ zO;XzPJDkx0a%Apc%fs8fA%4G8$Egmtl1E4Ndc3q8cgN>y2h#9`=UE7+V;|js<GNjS zOvilb?ZUmMI;}C^T2I@JrY(qk79&SpfwHH+2ZnolWQR|kPo)9<34@ebS>WJLJzn}F zIaK>F+c@|8AIPy`zxdG)DWMN7HvvNFMGB^@CyKA|QjNxi<mgyZ&3TWQ&g0T#NkUV_ zp;L~Bd{2Zt6+B0V3^ugW$F-mQs=V*H(Nx;Zn#BFC+i1{HXx=welZWa3Ph@FJ;zC_k z7#DIB%({@joLoD0>?%QSa-?|X2TLmCQu#G!f-sJckZCl|e`@l{K!ccSiu);#Y74_B z;0SJ+3uJjQ<yNTs%gkKW;s9^>1^Xiz?-noUdqO~PD2WmMN53L!k3i|r#@TguJ`)Rh zLI)U#mCx!^bE*yIreYHl;bSTN*s0wM&h9;MOzS%!Pn@x!;?g*Gauxc16Zh$EF7hDX z$%b8@@g2F|ml(^PZk{v71-%P@c7Cji_{jlq<GK7ES<7$4yWH|VnP|58gZ79@`0W$V z-<wbaqrL5ILfcclqnW9T5*U-9yjwBXT$sujqp9K4@W@2w%(=PwxpQYIxbSBwga{cC zaD<hI=llWMV}PLL&Q`nBOzPl$F_g&^O~ARN7jRtkuf;E;mlV|~zzPIf2(TzPYKdF{ z2;7;)<`I@R?2R%0ulWyJC0UwtmIJ6-RhqHa%g*r4hf*eCbXwjbkl8#-Kelzl%|cf$ zE4$Pmr(EGxftgU^=KzbfrQ47E5bdkhTPefdgOz=E&7h@epw|lhU=P%fA3gU&e-gw% z&#CdIP*GXBuSyv4x~r|kaIwNTWeMke3B9oyi}v6NBV`Y+JB=cVuH(-m7@_QQ7mXrp z-P&e>i&j>mwwHewaI#7x{~Y(`Zvnf>*mWCoU_)yVvWYk0gx|erpOABlz*GB9uS7D# z-X6vd=v9~3W1iVaU9l+xnjAi059R~rpbe?1$gS>HaX3r1kjYYLvMVB(n;<mU>W~DG z$DO9FgQ;}x!r?ryz<vs>0&1EJMz|=}acqCm(aszolF^^Z0gVOV2J0~jqJx0zs+&%s zB?Y>6pi0OSI1Y)u3p}HeNGTwE3P?=w6UTbuk>P^$d;H-9$HY%N0$|G7;$7gt%%H%5 zDOJ1@bW#s=azD$WLesju0+i}cUcp3k15{;ze1R$sbO=Pmpc0u$*83N-VRj#KeG!7d zu239c6{uQm?T0Y1mbKg7O7)@O<FRzQbN{|>yMoK93(#F9u%8e|e|;c3cRrK3{wFP~ zh)_;lP!?0>7^{|Q*})Us6Shfp(37{h*4WXrJ#_|f3Io8;Hyh`iDoizUx`?Bij@F+k z7)WtgHcASRtR%#__AK^V{e*sFolU8E;L{*$vgG2?l%FDgRMc4cf{190<NJ=iGxE(Y z+3jSQ`p(7DW`{&0T91=z=hZ~7`O380VV_I9_OfZhZr=<FO$=u3@XA9;oh3rAieNO8 zv3B~Z!#pp|Q;}&3NZ;l{X{XIMm%{dHUwGR+WgvcqWsUR+aPDM0f@m1M)gm<Hqimvv zk4b&iw$&oc<SUI8MQ1a1TvfRggJ%xH9u(!AiOw5$y8)P}!$1NDoNPR!7+9nuu~IxJ z!7}1VxMZdh0ars{=XPFzlwv0c0GS$i$6o99r#q}8-t?mMsYT_VNeU&c?l`c%C%>Q= zl|f@P$jLr-u%4$yF>7GrG7P~@NC(A12Oe1hr&n|j5OS=8IL;q98M_=4pw=p7V9s=l z{FEJk*bSJf(r8q&z!_wM+6SXsw3Wt50WuX0pay4?L+1y~OvYSso;Jk3+ewd@Sm`!V z11|V^8q-H&AR3KVpmTqFr_l_L+(-{iM%|&|s{%$gHL8n1D=%~Btv1t<8vw9QB6gXG z+`$a-XKObKQBx@*cHGgJER*Q_%midlfVzu9MrBz5j0DuiI!TM{F5Z%AcU}Xb5!tnn zEMl%;j+_kC-BtXb`d%5pY1@0~kJq--PB0|;qXW>2>oaQP5343R-&yRpco7yM1;#jv z$auVkC_OW1$98vg%E>jSi<9=QdqG`n9m^#8E?jd*Ago>q8}jwyn{BU92m|A9Sj;{< zLGjd??Aiy`Iw98C@wVDnHf&?hagkhm1nkyqnTtKqQ(gp_a|7s9R-vB97%xn64rANg zqxN`-$l5KXBuvm@(?sz$QxB@GY%V&Yw|*h^9n)D?YV8A^zy!u$qK$6E0T@DFs_;Ig z!hL2|h(I|XqgcW1B5P<B4IjwLEBpC)VArX_qLZV0s)^?Vz`0y_`SRAlz+hgRSLWnU zQaoXrQ^S1YHqvC|CmPCsj-!K3&G`Bno|%aLI)Wh+(;GAvw)anEMT~eAH-k)R?u`$J zb2%B~7{|L|Wkh8rj!%DZN#;O&SLjE$C+>%oxSg-HvYd*0Df;0~ED4~U9)m=$kLdp# z;RO8}VWh}(HU?`o(vv@G7IL*#ytZ*xLYfz^V1pa8y<2I`-8kRjq<W2|Cc4o-1>-g; zg7*utwFfgA<B=?G^~Fl~84gvuv`NwBpMCXpT2c_kL`F|Y=7dN}v1$;AA<`L$)=m{y zAxoEr-C_IWE@F}sK-oMmNlVByO~A<>H~eFn$`u<YodxYx%AolRPGFZRr9z=pGitJ$ z8A;JN7v!?0wg?V6lUX3O{!DB04gIgbz|sMfQcha&IJ&tpnv0wHfD4SWT|k9Ww}&gG zg~i+|@ketG3%cwKX23gJGUP<Q15E2&Ah$uGl&}!~o+kXd44bY-s{o|cvhA5y+S29u zCwIFo*`0j{!L&@O3re7#Tw2yrdb)Al1`h4aq~;w;&er2uOwX+Tv33tpLn0{XS)cNO zcOB|>`>zQ8g=^rh+{px0m<F_jPX(cYaHsrOD?Hsbr1&2yxs&EH4wLJFR9w;4<@)Zf ztIY;I8JQ$*G%vB{SIBBTT1;C4E&U7c8~K%`qmmZ}&fird&@yJ5osA^dtb@Nl));hu z3p6-6yucdR6l_>XW>|}dFa0_hFqDsm70yzQPBnAqDByJaPfGdmVZUUmucai^k;nDn z&07uLeT!EO;~d$J-V?SEH5@xEtuf*3Hs0P3ZeI2%!9PBzz5KlP%R4Iz?>VUbtyJB8 z);;I0bT*pww6K(ve2gRGT4no)h!L2__H?y!`-#BR>RLf*G&RQPMj4=xdVzXbxB{j0 zOgPD$G8x2#UUzRHZbl-dX%{q6eEVgt?4-v;jFIaj9NE!nWm9|oQ(8&ZSAo51sH_sg z^L#3z3DN_uvjzj8A%D3)Z+?<TD46)bGANbx3$H~G(g*l_f#g8iLOPG1Ttbt93eKRI z4{s_042M92@_iHCV&P4%kv_cmBB%+q7)XXxL%#z#=$Azz@P1NeX(rekO|qh8;K3K; zwy#_h7W>k=6l8G3nVo*#uBTUvo7;jzbK|V`!`nT<ZTD5-Zls!3U}dXFYm>lgYDG-( z5^LN<+Ld$}r3NIe#j)`I6ZtuVI<qks8`&RjCE;{_C~)%a8CNEiPqSo@FpL=}UcIW1 z2DNF7rOXj8z8&lq(;ZBTKiOMr=6(Ij=wOc$+rRY5%k89s$E08`>SHbH!{QlPPF@=X z(dR7&URX#yf9Ec!$%juF>S~pN1XkvhR+cYxNiH)bQ!bNuIL(VI7^$jozt`!8^gd0K zq#k`FlZ?}5I-Qy$$pIB_pFTL8_Kpl{33<M15(GI7d~A|Z`}tMKwhAqk>5W{Ii0!9y z`rm1^rhst0v0SU-BdKTftnINxrhJm^gJftBK5R#@Ecw%d`*Mlb90j#~(RSX^>~wxn z-UbOb8`Wt|O!ua^$n*<J3_n;_+FaG2&`xAn<4H{pJ60sL!4xj5f<P}DofKQ3M~Weh zTqS_^)4G8NZJ+^-X@Q@Kg(oXin1|YUzwJ5D((hmeExs7k{vvK<^9yq3*9{M_WU6?` z7Y%{jHg}dN;|D$2*o?2s`GFUBNsA}$O`dhk(~(_a<cg`ZQwyKUB9~`~D*Fg-wj^H7 zQSMlNaUipj?@1YBN#l$mS|;i!F@xMU5q4Lt3cZFR+2H^!mJJxqs^!3^WDpw@7~@Qh z00cbq5IfZ}FROJRL?nE`kC}rpu2c+U(4OrEFHM>GB^Rw{WzZ3F>PM$<@C(m3*)keR z7EWxMHIkPK6IIz37)U_iyi%fU&XS#kj}RDd)QMT^yyYkkg~z@Rj-eZ@ZL}=TX&9|o z5!gi1g+wR6JakeZ5gY9fGV|46Kk~UH2()Alc~sh7)*Iev0`GkFLbOG-@&Ur?GD~tl z6bJ+R#2=EOOni7cud6Gww~d3Y-y=`9nPG3)ilU^^1lQM`p-Jj=T%c%-Oqss1>8;Bg z4s%l11s<o0*LFE|)Lo)L?`vkUr`fXST%;1A*7YO9Vevyt3MqJp;TBPgtJcZ*9#}x% ze0XbIUEC<hF@Mu0FW*hcBo)p^GDn@+2+niHe7TB(e0&_MA`mQ*U{oF1odpCfS)t_j zSQdS39o{j)*tmswC#KIH4>LXq=V&zNOszxdMu-s?3pSe_(;kaZ!Nuc{!a-&rvi-?K zPU-hDP+{rA7n^*amw(Va^2naBW)%=!<+bUy)20Ylh=>>Q0yc_?!NIzjC)?{UOXc(> z>Zym!FLc@SAFIpcMI!6n8hR{U_+U@Yb156dKs@R65+GU6XsgHPgNaTaLFWgfwkJ<! zr`s}W2EMsImen~*aAc`CCa{L_I{iw2_aP}T6%3lrvd2gzS=%Dk<kpum1xz@aGTtW! z{&-y3Y72verPl|jZ#|=o1UY~c<02WC?`cXrl+!vvMPyMgOoWNH-&_M<Y-D3Q@_3g3 zyU1-NOC5YMSU($xt+KXObt$0N7)mCei9)1`pr>)eK&m<%fH^f;&!aq3rDEAxC5|-0 zyja`h!F7IdtuRf~_M5nR>5}yAvu*gd7<P$Vbq=ay_9lMNn_AB4E~4ofU2lIfIgqly zxgKOKV|fkN?Cy!k93}2YQ9Gm8P6ZogiEL8dv4TgG0adoT^-co{yumx$*5Vab@?11H zSGg@>#4i;YoZyn!pL><&F)n2zZ6IFmx0NO%M=AOHuRhdUWnx(u3*awfvp(B9yJkcy z$ntd%x`YUk5SXy#rag9itDQO8jS=M#N5@CG|C`!UsSubHVWkfL`5M=uL5W1(fwW0O z0o-|we<`KGOas;CVcIAi5`I(`2KhAD8n}Fo8vKo(NBO{=x3H5k>`CPj7?EXhs~AdO zib5?i#<Wj!<Gl>V){%4Qt8SXKUS}Z!B8bIqtm5$*sX?zk6CG@wek?-!b5`axBPL;) z)S0|(5)K;7O%&M8<4TL4ACQ96;jp>5<XYEyjy8-jY|EKNm<$u&N#NC%tcZ$VPm<1n zesxL=B=MS}6uG|cPANAN#D6Ef0NmNMn*???`Uc)(4|}KILWrN{j7|8BU;=_v<F|$r zct_Id1M$w$x4-~4NA!!KaFLl~QXvfVh{ir*KB`5}J0P{$4O57w!4#ya-GhFZSo9`x z;UY=em(l%4<kcGm)NAP$^eVdErzC=HAQh6-%veO7f@wg%Gf*3&!xvvy%86XO4-B$W zt(O{9nLq~`=K_+Ag-ugMCjP?N-NY^q@<bog?!FBqR!0_;y;ut-cVEe5*3&|IMii5Z ztH+dR(7VT01g$o&E~G$;ZQJt0?Pgyre6(N^%r2Uf!^t*wE}o7jtQRA@2bcHRo`9G} z(@I8`Ls6Iuq*=1-R0Csb(A*XmW;J1i$iv<?@@rF8?;dRD)G9_j!CTn>cAYdhsCGtz z16>OC)DMU>s8%-AooSi<@IpFrUPGtEY_yYSNH$?GE3yn9!8qdnmG|K}o{}1^boKFo zvsJB}2;aDa+k)PGS*3ti^u09l$3SS`S&-8B#`>0lGHX=tdwi5FL?09pmR8qT@eybU z`U662Yd6qX)PFzKVOZ6zXglZcHL`f(U^-P*JEh6$u%TCPq0wrk`vv=`p@nvXLK>31 zyw3I<`1y)2IK7hJ7zh^QETjQ~vd0}J9%6Q*hj~7&&OwgkFS9HGnLtc(DxRd7|2+$u z8B3ByBHZzhvYDtS5?bk2#)B&XN0e8`sVhA!c(r)rY}h*(k4M6+cvdzZWW5jN&~BYM zQrx7N`|_25a-8v3hGU~_<!uH~HMo%PUKOL%YK#_dTV)%9?>Sz=jU0B{HgG&xQf#8d zqfHC3p$HG6;PGGeYO=h9Sp>MbU7WXjP&v%AtR$*l%z5)@)xl)225mE=7RryY2GCuc z9k9(#M!da7R;o|NdXcPE2K)LY4j9HiKdzlaHze(JC(8Q*+^Rkm@M;(I5|@`#C?XzM zy*{)%K<2@MQflX8;bXN*65F;AR0l;@qpVJF;Bd}p1mnrZWgw+Zp*78!hd{^gzU8Q+ z0qEB~PE69=Px<FNUA3qb-fLIJT7CHkXxip7V%Lh3aJuxRzE-mKYtqVEkg}%3%A<VO zAuX{F*Q{QLnyTvAzG11W8j17xgt5}%i+A(+$cuS<F{$A)=zqiTCEdxmlZI?@AiA#i zEYceJnuQ%>Kq^go@UOsKFGesaihPbY$y&rdS?J5almskFL_!i4q(4n%d9^#gFjL1s zJld3q<T93-fV;`|keSE^aWaBv6mxq%n$U;V{2Z3k|7(MGva;t8oW;N5^ox~hhvY15 zF_oP+he^6oh9vm7ssPdi$%Fj)*7hCeVu4AwExABPv9pvynD*674)`j`v@_SvJc8xf z{##r<-T`uAIv?nqVdBk&ygt6BrFo!J{~}Wae332%g42VTK?+70CQ59<lL4f(ID9&i zY$UvG6jkp~TS{683~Sjku|NvyiQI+L?U1wcIqwFBV*T^Ac*bN4uYtbr#Qn7V!5X5V z<NL+rmX5kC1ZwY=4rbO|F9+vsE@{Cq^J8YBWlT_%$%x69Rsw}v8RCGYq|$yUP3Yn@ z`|}9`+=tjDZFTu&)SBd2boS+wzdXcYI8*tsoQF6>Cy@_9d5A-Irt)EBTzLSm2$$GK z5QYMuZvB9cB7A1{r!GCSt}f#QAlUH$P$ll?qB}9-Huf*1z#8aQ?(IC2tIFkPqKUot zSgEqv6J2pp$+UXEw&Rb?^^)03JG%Tm0-P}^)7IM?m5JJ&uURKWmw4Ga$j{2u9&RcK zm}(^^-3npzniMmo!uX;eaMu^Zc++zkhAsnjY-`!hJ2$m#>o~B_F6;1aq+>(zQhr-k zhLJxmax*zT+yTZ3H+Uf5C^DGxdV9bQjo>%Y;k=p-WLgAck#;5+kGQ5{m?cH&v+bM~ zY632e<T|9a5>%weHA&HkQ$rDD&Ij2VhHN<K2>TE=CNED6vnC9`NXg#HG4bon=0E#o z>`+>pG%=Acppi){>w8dwR0jXL!&qE>OAyf4h<j!7v30LrQ`R&x@svBGZ;6zpw)jX3 z>CGn~15#3ZU>^htT<0&oA$es}9GM;MDW(Q&zeRm>TF$uF##DP|lB)>F`^QKs$?R?^ zFZ5qxL`I`=CuUGbF2z5t3#@J59142`nOqK?<6Ko>XJ;EcI(rwig{dUsu~$(Y>y>KI ztAQV41oq%mj9kkE<BBP(=tP>=c?2jGQ52`O;q)XDv;-o8sKwh4J_d<Jd7W42*P*4L z9Q7$uss&r_hrjeIEtUooxW>k&J%YM=b&=88D(h(G93o?hOS>_v`})O%_xWV<M!WmK zGkRhmzl6H=x?Uo+EndA<T2R|}x1w4zw+T1;CYHbu*{!PaW`^0>!3vK1Q%gn_hLvUp zTJ<X!9DZ{19xQ(^nOR=WZWwDnj#`)R-A#;-9WcS?5>K)+U+!C@Deqy+x@B`e)t5TP zk-U1otYvr4G2^rzZ{KSXFtoXNYN$^P_4f}?Pd}`1iDG^vDoHICk~FnYoRU)JG8+m3 z7LgOB5zc|yW?xM?IL?hWQmZsVM#30X1G|t5cZvJ}gMs3^PW<|?r`9g&dMDRsPssm& z%<bl*^AZGke>R1gCo<M$hkUw_p+rtq$dpjRk#045z(DFcc6f8E-^3W0$ct7z*ApPR zviymv?8hRIX$+9HaiD-x#}K&=Loi+fM&lU2YF8*lS1v^rtv?Pm%DV(1)8UhQnMc62 z{`a|*KV4$*at3O}uLAMr;!_pOv<_(RQWjYe4NmlA2SU{TKdSOe_kCE4(0mN%S!|B? zwRB#Q->9z`v*_kfY8qjE&M+r5O+$`eOm0`Vu9m%@)Z*&JN@)B#VeU!FPWjlOl@{UB z<dZ;XWiLY!v}Sz|@<%UG76eitIkku755xi2ePiTQ3CX57b%cdNObGi%J`X+?R8)t? z`hQ#xy@iM)nDibFl2O5NJt5odcrNLS$h1-ZB`@Hg#CK(^@tZ_<o#7hGIr4Dvi0#Rz zTP7Nd<%ye%)Et%8zNJXhrgH-D!H(H;)sL#bsm?c%-&ND+bFS@dFGlw43L$4T3e?^v z%$b^Yl%hPbIe88I@lC+`Gz|x0HhGAnc7Mt-^R?oFy<6SBF*tH)!zETY?E05ORR?}F zC4r@bnOz*yp)uU-;EKDXt-kP7e7@VMEVms@J1VIHb8w9KG^VzcU$|X^#U}-RIP&N@ zgJ*TtV1<qRtL5f8cg4sh|Ch+XpFH`wy<^$I(G_HW$v$Ge&#oq}?y`sXKKlq}p87-K z$9y!{zAvX&W`uMiBk{s6+Lk@WN;lSti+PW4Nr3v*$lWQ<0vf@dr7Q2qZd2_>`LZs( zKXGq%fA~a`Tch>|hPH4$S{pdJMAi51ou2X*0juYk9kJ#&IJW-51UKMJ1x*KAdBN8y zZly$gJzuB4kC)QMDb>3-McGsT1J3Q*_Dd8lEG{M;OiePAzeGiVQ@}&$v3;j_kvKzn z-vtDLAZ=Kc7>fQkGZR3ZU?YY%U##s_1o(uVT3@7LY%KLD5MTP;t;cxqrO)lvKFSpW zC+6^_^&GJ#pX`pp>z~c1n&+E5QqLQ2zITPPAx}e(Uh`OHFGPFZN~*YVAp5T-dcXo~ zB=$1$E*}g0aKx{35ujb)f^vDUR<+!{b?$0+><gJ$-6JD^@WdWHhXp4n87_X2_<#k4 zMd;Xz(OIw9&U%Fbj*Wdw79U?+OAZb<Pt&Mfp$Yra(W>eNadr^^VV(nbQ-`t$$gKVS z#HcO$0Zqu(anruITU$#18c3|9U0?oc-LyNJ>NWd>jJY>IzK0A&aoDV;=9-l=+G$xI z8C2yHV-lYm6hh<+rtTdC%lpRqX_JX#|4~@xd*7H~gA<7rQ&a<1Z+8!dmd;8ycMCs5 z!8OJs+2w<G9HC5fo1}G1@A>uF?J~m`(N0Eu|J_$YXP1HrY=!0YTeE!0Ej3p6bEWFW zRqcmJBV;?q4sEG;26cMa_*QqqC8A#ZX?LTEe9GPtM3fijyW8_6j?XWTWisIpLjjr0 zR0GdwmQMwlQ&TP*sS_v~_R4-}m<+)iz3Wsqyu;TmdQYyRi35w%V2uU_Jc^hY*px_F z$XpcESaGGTlnq;PgjaP-D`}<;N0=6`DU65o)E<)UK*5A<lHuYEn__q??^c;&dAyG} zH+IsU`;5B>)=${99hdsEBAj7EJ2_g;^@OhuSq}8Yykbl+;sKqUB|a95Eh>JJ`m(-Q zH;f<jzS>&0yb0(h?N#Ch(7s_?&E~ll6CtE??1H%e?|l<Tun@394)fe40f`u+-`Dpu zk9T^=IIs+)!^uvD?3iV+C*t{FVyz;gBfrON8`K=GqT|j7YL!Nj(_>>xA9+;23wNEa z7rD_`6?dE*$Qf>zx<UYA##M{kYE5J0MX_e~Dsmib)uWVJGd50}um)G^^o8ohI7Y*Y zs15C)cbU`_*cw@`6MN!e!kd!8fH*vm$3UYcY_@_?(`E_eR_8Q~qqK396tL#k^@DJV zM&!e8#MtYMw(ki2uw9hsiwL()MA9_lD{%7<Q+E7=j8R^%+6|qppULC-2b-&Rlh^x? zVxz{@i>5}882^O_cM%eqPRzu;Rg1PZ9>oi`g)(Ee=2w>D*G9v;%c<$9$?(gs-^)2S zmEHZI2@)j?+$<FI<;}m`p1c)LE+G0%U>YnsGPT?Br$e-(vqSCdq?ag|DbO?6E4B89 z`w=lA;hI0348H`<bx}nbD;M{j#(eN07X`IQ9j(XbW@lrlTa3x3nY-UP-AW2=Ff^IV zN4RjbFV<zD0XNiPdPV!9v1bO(24rsecyNs__B8%e_S0O1P@rG*H*Ge0urYTP>nzS2 z_mfb)B3(7TCF&_gYjD!d?zc0|><%Kh!}<e-d`kffCm;^8U#X5?cny19Cx%X>hlaEW zrf};E<C7D5PoMhJQFrdSx7@X{r}0=%&-iS4&rSA=CDT3n=I^<xAn+ZUaZ{h6^3Uyy z?G0#ZEIA(rmTU1r2<aJcCg8?4rWh@y8XM8H?SdN<@`_+NLiXNv2(jZyRX7p7Fr)H& zLIFSk2;!B?$2y6ZcIMt<TekuLDF6R|mIDA>d8GQ=wPMw~_SJ0w02u@TfB^r6bbZB@ zFKF9&VYK09b-LLogM}Xz+eYMhx-H*$SUL3~x|sqXag#|z^lhfLG{z92(9IPFLLG%@ z5fhixl3F2Mm2M@_uDA)tP=y~)skeoe%Pf}HWpM8l$HUbNf!;(`jtW?q^a+-qmP6Q5 zi-LKauV_Tpz2I1D?#4xK6dvLt@;4t{2oE&}xO~Il#$z7Qate^j-<5u%R-tQ@?Z=Hq zVXsz$WflUmIhcyFc(^8~7_NU`4}lleoSO{_C^#3Y;fU$PrS&xIdp8CjCewhSO}SOg zMm=me>=XGRg@$k57l{CVhT9pjWFKrO+$Fv`66C#Eg=ld69OuT2n++`(95l*+MsLe_ z{P=x}!f>6f8ybVQf!H~kc~}#G!i0h!6R^i3<k10U%;5ArF_F+)4H-o48n`kKaA2X< zak!ldqqCy0uwsaz;$^GiVA`NJU=Z~zg0KIuHw7^AoJJYiicA=&5{TL)zbzn`yN3jH z_KpHLaFucg=}Al2(qIY<PuusgNN*k%j3b3?>|Wcq!M4zv6@yw~++9;u+}^{Hs&>bi z3?ZV1n@$4hf-J<VyLstc<AXfbDcY(vMWRs|C~!Q@<OSTIcrYfuT>z}cf8Iof{wSf= zDxk+1G)EM$o=2r2&}|8|W?-NVpuc_|WXqx2@)&3(^tWDATMqrzLB18x-*O;pNA+uE zz8w|aR`)?EF$n+Qi8_6grfsc+T?GTH5bzMTrMV@d$fGnmtpuPjjKXR%Jd*Z*pu{26 zAPOY}0;o0t-2PF(S7ne|Q~4GAtjAg40RSEsVE9Vdbu#XVNGp%X3EmoSxp>FqHtrTg z!g={qZTD0i|9ld$MVSnPK&2DltN9is)d+oZ2DNR=$8e=R2jaS4KcDYMH{tK?YK1=e zJYE&j*djb!yTm$xo;cMbM0C~@D6p=cf-i)68rHDu83f~h>sj(=o$D<W0*ko~RDx7{ zy(+P}^+xe6sW-{AF4=5N?a?gkG3u?7I#zF!s?+s$@!hU>$hgPH=9t*8#cE_QRkLc9 zs<cw`=X;B)<$a($nXEzUBR3a0t4ABvTxw}yG+J9kt2EAfTd27zL|Yk#Xc(UwuT-5) zwkhF#(A%h<PhqrPi(0FdC%T!)IbE*YkJgzqd}af9^W`VhC^>Sa%QdR7fL9nTu1&3u zL9#`)#`RWeRk6va7vC*8=zHz@3RccniHX>$c!{<swWpdvY7uV{ujB2ET)84MB}g;Y zey`PB4Xliv#y&*jO+jvUYg)mmRZc%+m#NmK-giO05u;Jv#2@|DqeX0RdZ}9ET;ZEN zTZ7*(79-~pmj5KeUbqEIR;<~aUR2IA0_$?;;dK6F?;Q8#cg`1DV8CCCM-BVBK&3~E z5Gjf+JNBm_CZ8)3s<fPU*sRdpV7T*e5!R)1_w(f^=L5(0#K7VqNN1i1;n|VMqC|^1 z<*={+IG0hy|H9neKRiA?zr4P^e=L^gCFX&Vi^uR&67xv%Yf9C0!?bM2_52`=;v~)T z;-rzFmfPIZ597JNw5@Wfjb%HocLG6QIKwDT(kw5^s&3#!#Qx1(DsARv-S*?W?&sae z7tGD#mQ^ZOXw|M^)f`3DbRiAXvK`m+Ib0rJMO95*LsJVuF#&)$Ary%vQkh&^M^{hZ zz|hFp#MI23q-cg!C@m}zU_whr&%nsU%)-jX&cVsW&BM#bFCZu+EFvl<E+Hu;Eh8%@ zub`-;tfH!>uA!-=t)r`_Z(wL-Y+`C=Zed~R)0b~Qe*O6e06|~~6b45iQD_VnhbIt8 zWD1o=XE0f84wuIl2t{IvR3=v_Rceh^r#Bc)W-DtO7MsK6@dZMWSR$3l6-t#_10Wbd zF`Urq^ai7eq-e%$vD)kor_1f}dJ}D5@!t~wg7H0#RssVcWO{-Chdrk_0a@a9JXBj& zGeLk!W=8`<=0cq-NlSGimzWbm3&XA4S{@=>O3P?LTT=uS7$jk7t%XmkQpb*uNC#nE zb)Z0EP8e?yN#TX@7EGPSUJNOXR$ewz6AsJsp0y>ih;krUqGk1wD4^0z_%sElR;6hr zAhkFzm83!zl}K`gSn`;S40b7%J#h)rtL#LN){4)G@&k`HBD0d^RHTvI>i{4`r-YNO zbFE*ZqljzAMg&VOMNN#(@g<qJV<Hq9BP2l@UJoE?g!Aab-jlgv)5s~2HK|PoG52PF z<ee*TBvV6%JmRS1WN5acd*rfL+ZEDP5uHaptW{)nJx6uFXQ{1-dE`N7tOQz6<nTQD ztTQ$(!p+(M%d#vxt-7a-TJ3<ebofzr#V1FVNRau+(dP0<t4CNaWy^Vl?Y@E}-AGst z^t?uqT6uKov`(NP?00fCC$VaRVH8hF5b24A1kvZ1qy?dSz98m8F#v>M1jTU9{j1qq zn>}Cz#c&Q+(Sr<*MDcQ<(ec|f(|aYnKMK6m?56)8lZgViBQF5m@hrfi^++Jta6S%c zw5m2YX}PGuK075qb}1qb={{glI4eg)fv%Hv)x4slCx;?HsR3gVuJM2d;fOJVV8u&z zQyJp;SC=7z2CQ@fx=^7MWnaL?#i$vvd_{O}ao56;@khg;mA~AX!r5+=9q&2V&3+TG zL1y75Huji{uXHn?6~)V9payhpoFGvpv?<E_%f%qHIYoyX!gT@E-RwL-M?w_CIb4FI z!i9$5VtlIrf)I?L7|!7mBt<j6tpS8!1jTR;mmn#c@ofVj1S3)#sR5M^lYK73eB$|e zcc6d2{QUZ#>+=57=YQ}e75qkBFW~$CpMSo5y;(u5ZkCR9eZYzV0ffVK9uy}WjsrG6 zAlLE{UijNr9~!tvi#lD9+e}SU>kdKWeF!1Uj`>9pq@C;@%pYkl8tugJH9BjzX~cTp yxu|P$+gsOr5d}t{0mDEMY!_&c%%$*HISgW?Ipb|D#yuYH$`&icF^#j{x1C)Z8fq>8 literal 0 HcmV?d00001 diff --git a/.next/static/media/d1d9458b69004127-s.woff2 b/.next/static/media/d1d9458b69004127-s.woff2 deleted file mode 100644 index 822edcdbcdb60111a5b7613b0d9f1cd1eb65da4e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 26728 zcmV({K+?Z=Pew8T0RR910BC3c5&!@I0LCx?0B8LG0RR9100000000000000000000 z0000QgDD%8ZX7B<NLE2ohbIPLKT}jeRDn1EgCH+#5eN$UP~=GqgFpZ<f!1OHHUcCA zhI#}b1%+G(AR8{Y1>1(b+W{QSeZR25wqfsazyx>DkqBYq03eF3Nd7-3w?>F{1J$hh zfe?*5!jrYSYM&d(z9^pc7K%-EX(!FS#0hO*p=Tnx%P<2PNRTP|7lB7bXe22uokGz( zq70EU=Vw1F&OUJJKPOxBZ+zICBFD=$aA{0X1c}2WghhZmJw(cS5)WMCo430^GVLF5 z0wqP-VHRcD>G5#_wY45*>=5ZzlfHof5dwrJp$B>Z=|Us{q9Cm+fi5i|RYhqLIHd$Z zYLEyh<&Y){DhGi?j2Z>of#;rLc||Xt{OO(O;o<X-ZT2^I<4<jeZdP|ZWgN7WVJ!8d zQX4{8#HeYT(o~}c3>XzKV!#w5w#C2f`z*`iEX(ehKg+T|`1f7)sVB*<F8_6fgTT;X zV3Gi6cV)o=G!O;goDj6>4$m{U{{y>Y*Lj`Si4(W$yeiJ?#EBCXm8Tbmib_VdZ2Fdu zbQ;e`wru+LZ28y)bI(tHQZiEN?-}{_i;RkD*)&SpBcn+RCr(tHILTe-bzbM)b_YKH z{5R+CeeRu^%P<g3Xru&v(>hIPnp(89k9M)zb7uyaSZaA$)TWmD=v%BVR-5{G|E%@0 z+Iwau38rJ5Bs4`I!ATy8Q=LYPqs2&48ZlDENbQKDk_J;uQK?166cz5Va87f{KGc2z z$c;ehEv{M8bLrK{O%mBDpvT-Z%3*}Dg?}E?^X=L<1z=5L34GLJy``xsdG@6{+aIGA zkV29@ovv|rB2K~<>_B6oZh%V*e<4<g{~!A`_n{$^36W@`C2>ep51H(;8@C0~$iFki zQjI>(uRiZje`ZG0s^71EzxutmQLutD8<ix)M_jDK33afHbwnjDb#T14Nxb!un5eQ% zd|bNIP!E&pTAE{SxD37k;Q9a7dft7ix_aOf%8>EtkEo(-T;G{6I7StT5|@ue8HsO7 zhnt}kLyDTx2K*EO;r{=x{jbh>`<v}2t0TTTRYUZYn7Jc&%{$-hqS~Qy-&aeBHPKAt zlQdBxp+#~f#Kzy7s<r<SB>W-DVo-t{q4Qx5^d;(In^RGS)Lpmu3yAo;gtPz@uvn1> zNJ+B*1kEl$+RHRDsNfjV0wC=rpg;nW$21)&hY+gEp-QQXU8?RnmoCcdsu+r@xT?NM zow>>{=c)(dj=bYCbQ(p@%YxL2a$iFk==NSG0Ni@rHulHf_ss##tL+Bk8bX!0{d~-K zqw+V}>u?!FWDpx9WL`t|wEh1c#-{7I!6sQEs2`NdQ2t%oNlemNnU@3_*v3qvT`S)) z?Q|nTR9+)e%3bdlD9X||vJzCVg@T5FRU+WShVm3iw1X;Cs7jrhbV#8`BgQ!uL@*CQ zOID<@r!)856QnRn*%yNTc!m%d?r0tbQVx(3M@j-I$)u!);2~4YlxDVB=F?edo+TDp z>J(4cvEd9m&arnWAH|nY#;+h;yN-MgL=h5UA@memq{MAXJ>(;g`NXgP^PYJQ0RiZT z0?Y$ef%PcJ#}EQoj)oyXAWq-D|JaE{V~Hfq#ALgNF`SU;c&r5!fP9=IvI>_X!azVk z)a}Zq`STb8(29%#x!Ri(Q2XL~7PSz&l5<&DAt+J?5I_NfKm=+cKv61h1+*ydjCBCV z14Y_Mhw8<qooUmSW?lOP@_}<)A9>mr&jv<0ZE@^_ndSz^K4Y7<?tESF=`<sibhDk# zIyuDp;UR=C-LD-g(oISj(v~$-PLl62iBTy3o?+7G3}uL{&$FHzA$XJ-(R^LxcMW3& zK>qHqMn{Q;C-#kXHOpnfB+1u)UB|{zJiTJ;tp^T)uF<|Y?P<s#M7%I*drS!i)3#&C zwA(zt`J4+iAXvT?zBtRY)=^I)pCjk1)vgX}tJ*m2siFfmfpwl&ri$`yZTg+oO>2KE z9Z2T9Vvel`YxC{4|A;?6RR>1hW20lg7j1e}jo;#z`QAi+V9J~`8$44vmS?-pp>vK} z-|x=%vwS@l_us?B_~5)USE)Ji?|e=?t9Oxfq5m2do;(5tiWm5Bb*j|XTbi_J!%%#8 zmdgBsz9)?>JN9(p`ukxKQ9RKxBgP~sl2Rrv(&4%#YlbFsf3{%WqLL*iD(ZQS&1XA0 zyUzFYUbxslFgP?eK5=>S%GK8&3yIydNNUNl2OeIG&mwv0QMsuF%A$N$9!i}<QdGri zRD}r!C_&xUhM_~Ms#fs<5Fu8A65HI4&Xd?rGbLAOx1JBU35!<yxK1Ruh~hQ}xIr8@ zN??T~LuV&!hNKm9j8ufo3LI{bs}<1PMulL7<E(Om7Nx9EMo0zG>ZycBC5^;tCec}< zbP%JHSY4_P+sWyL?m+JF`ay&Ng}^(42@vNB(XRFo=A>K*MH%4`7C{^-5tfLxOq>VA zdq{at?xG>>HVN`ek)JD#F+c;MSQjeJ9^m>=(`Cp&0jU^ICc&-crxz;)&X`HSW_+#B zV$9i;3c_i<o5-4>mVgafLAu5UhgYsD7k~jm(e74+0YEzfJ}cS=RYLEu#)wGcih{0q z$15@d0~Am|0Ht!cfdm%NS&UzgiXQ=k128Z^0a>CSXz3t5r9g=itq3}$U5mE*pig_N zK%z|8(X5T6T@eVhpbZ7OrKzU~+E5B2`@&nViLFCbhS;;4G(H(HsBGn5dQk7GL3T5? z$jx~#OaJ^I&gV+%-S{Q^U)MnUX{B%1P2<<Qo}y1(PdndxK6<|DZ!q6vx}6Jk-mAOc z@TmTA?c@5#jZZ6|R;?OdFubCDL-!{Bj&3Q#;%wd3!@2NBh;Ylz-UcuB1Oi9^P*?s0 zs>jI?00{&DCO-uGV?dvT{24@PLTQ+vLplKEE8xBc>1$BFMkE9A+rZy}^*wIMqV)r? zKLh*)Wh3;C&@~F_R{;GEh<^p{KLPhIV0)XZAOsQsT-k?oHD<V6OlWW!fx8xAab2Ry z?GdC~6AJe$LAYlH?zRccy&zCGNT1tI@ZWiXxZMbDH<)x2Ot>lXX;uLKTM`7_K|!0# z30gI5Sx=Tt*UF+DGHH(*G;L&RE!J8~wN9kwEtm#znM&b0CQOSm=ppl_QI$Gj{8R+# zoq~0(xwF>DthI2~N}@GMb<W7Fw{SLCFb|jq-8e7_H$qUlZ^k7)>j8QC*V8t-*MmVh z8EZ^=Y1jDBwmaRPlFB@+ljrzPPsvRALAm`i7u$^aQA_4088TjgvH&jxq6y#3z<=H4 zF%R{**@vPp<qbFcBjS@T<G2|C_iLmKn=%JmJ;`R<=J8;}(GdjF6k|)KQUa2Bq#`j* zY~vYW3AkBA8Y0q-EHYtkwI|44k9#N}Tn4i+3zOwedVt3Q)~|s`V@9&F=w2lILuMcg z1YxqtyyT`a5N&DTt4~L%<*Op_?&2rZ4#0_L4xT7e2i<NNjHIxZr0@w~ZKi;YdwZ{& zfZQh^2{U3eW1?#24e6RsDV^!{6l)`fZdw)x4A8XLcmnV;pIW|xaK#Fk(hY~cs{p`o z&FMdk8#eo5cWd^a2vl5Tt+@l#G=d&BrV$_@K#+iba)5cr{i&)>DFM4*R;P#%NGL2g zVG+pE49f_B^hknoavw>}Kx9xxiwwoVGw-i&H4-*V9xJN0KhZXMs>G$4(#BVYz(8~T zky<GE{&kYqpmYAau@?~vvbt0qsUEJhCp+z5vZuSos;%fVRi-*scc)M9&+q+GXLQRx zKv0(BoAc+t18&^tKkA2L=b!5NP4^1Hs^+QodHb9#%BeF~_;y-mT7PMqZMu4k#N6nD z+wQnaU4pwE(ZF8gL<kdW%-^2bAz4_8RjNwaHscU1I-=yq<DHATo}kFbSu&tt&^+EA z;ZB?$5W4U?7R8Sa*(k>*xqdLDB9jY>5j101RCwkhtmwGu;&XklNGDZIs=2JmmX>SU zuHSQ?8)v(@aObLaaLKZBzw$JqS)K<xgaC9yLLk9|e1)O3<}zTZBwfc3ztcS&xW^eF zFTM;JT!s<&ipGdn{F(3)aflyioqL=a_JXoet#8J7kMoeE9qpRJ!ym4W1d6Xqt|47$ zEepKX*qoZKy=(7!lZOk#wRbJa5@qQe5ZS5~st~3!yMDyrDiStp4ntmspw`8Jw48bn z&mQE(mpX<Aq9@)L6B^Faw5ym?yy`;(Q>ijaR$oOyrW)CApK5T>u(0W}S5FUT)NPQ_ zvw*n>+?OFx{V<#+<oR{TC&tPrU0^L^JywXV2cJD*{8|w?d3p^Lzp>4ohb{XgcpPPn zE9MtV$^q~0;6fetf)F7{{Zzjv1EwF%$IPmOOwZcIH2{vm6CRQU@W+Q02osU$#}>pg zp(iBKHYXXeEUe_<bsuI$jd)bkhRms{DvIMVB!t3WcBC81UhrHjF&t(!DxJ4@4NQuy zqEv1%rQRbYI4+2j9!VV|O&0I;-TN1rngq_6>ThW!+A2pThf4F;WiPl<eIS%Di`BIV zWWo7rg^G|FAn<ShN;aVV_o23Hkrj%HgfHGRr(=FaJ71YYI5#~c$No7S<uO}|D^ZD{ z1g}baN#m=B#7XF2EM!$hU?4L^90eOHOd}R;tofEnFC;@7A)h0cm&w-Vu_Sjp#pls( zFNHm;`i41@nJG4qRkbjZ9;P;d(&nU4i!L^Vud7%=fkad)nleV6qQptMz(f?^f0IfL zMa;*C3uupn`jwK$A|SO2(r;KM8sb}!U$W}~B~kZCi&dxl<iT|jz@J4>!Sjt9$um-g z>kxKohn$f-@<U0&Lqj_yKl2MWUPXk8NQ;l+F2H8qX|Dv3;&&S`{ooT$6?5E)1@nO5 z9ehvPto90K&-{8-P(gg|`&kV9OEND4*4&HFP~@~6K*8hBTkGXY6-%`)R%2nhartaY z(r}?5E@ZdhJxRPhfVYqZ8aAgA3rFHe(!r1Y)?8>lR6qxpH8QQ!m=xI$JUZJmU)r08 zt|hE{z6cKJ#atLb2@991^29T|6U_dyYE5-56$$E-Nw%sV9Cs5Nc%d4Jw)x*qC7+Tc z=EiK_Tzm=+M^ee6)_fxf8#=UI<rA7cYjeZJ1VMwV1IpTf4FGo-QTzfTPocJ?0`&ZO zgCXIx_OoG~UM(d<&l-^7R9`yU+s?5E>N;XV1=~uQY$0&W?HBqnj>{CUw2vNGLO9_U zSC+iFEDX4*a7hivnVN@gIq?-7=D3^Vv%m7TZ4R2${=v$r`8shBA?r#%(<L9<-cz&w zO~a|LH(q0gIXr_)5x{g4cuB;Xp+8%rqKw%+4k$FTCoRqMQ<(o?dih<xv?m+z@cN+_ zdc`3Jyw=aGdO?37N6+|UunW(V-k^~p9%8J@WRZ`#JUlasB`3dpNe&dr8ntH>h8s>& zKkJ0^GT1cgwO$4)@G_F>B(ya0jDesAQHZ)1q+(uZ$T5Y|M$=5laNsEvrEzc<B+C&h zsWiSSbTGot!W@(h;&q{WeK5Neba1f)&L)B1iO<ZJVU+8^=QWNK`Rs)!jnyM~`Zd<4 zR(mNW!q$8lCGKHu2l{dRE1JItX%p*d&##4C(jDgVW&R!#H1?S06|}S)cG_ywucZxp zTmU*@fQJW^5a9sQsY5puq!zkt(j}izY^BF(Nr7{*-($p4>*%Ht%_D9`s`~o9Ux1t; zX{LkPWVu<kTmMUE;n1N37Mo+1IXkG0derUD(Iw`x(9@*Ddz7d5?Av0<P&kUJkjvzj zt6^`c?xPji&2@|0MswUgm`}0HF2Pb6zhEhK<HO6E&IBqHt)ZIdcODE&dVFd%R!EpL zs8=5{X}KjydA-yc3{#rpK-d~!=bA*xQyk-qyaW`!kIGK8attWk`I?M_MLro`;RG;y z16>_4st7r7>?U6rZ#+yfszAiJQV8A^zh5GvFs~^f5RKh;E$+_XRkiYW$E5rN@I1&2 z?Ix^D={FhgGC5ndv$xclFHCNj9wd{soOKPm0vX<Sz%V3aYJZ(fk*OAQ>BwH4uvglE zGxiXYZZn(&6uLI*YE6s<Wp>p_vm;OrjYkJ1gH|5*X6deZ@5-B6o22Ngn!ZOLBV_b} z&gq=-EsO75<1WfHLMKw8wWDgyw<L}d8PC7fK6|umq8VhM?Evm}!$!k<XdQkWd+E@r zt8!Eu>qu*`$dY2|>`Sp389r~gKap$J8+9$Sz_q>*bI67$gOe%ly%)-KR2?^IJ#LH^ z7It_UJ-SPP{1n;AX=hZkKuiyw0>(a{(8<`d^SE=*C_NZvcTTzaxQ>&W9pl}RnK!s) zI()n7>Wdl_V;sSt-I!Hf3Q3y-5}s0h&aEmnefEm9s=D%T%Tz=s>MGaC5#nAj0Rg!k ze#+(r5-#z88nnXQG2@IM6cJDd5Xh1(6sfp>ng%S&!9TUyxDpVx%>`+p?u)jKDYQZk zGQZNM>EJp1U+N?ccmRNB(W`qcgdiL6Lt8^m`)H##de0Ck3_ckqf6!5EpYdR`J-pb_ zICIg_ULMixf7iDKV7Wsejt*dWk`MEzW$+t-3pMY$W!TGrB`_#FS+=RVEAxCu_6^6B z>lQc0vgG8zw8HfiV&cJN_NX4(EOIw}eKt&t>cqBgzh7Z8nPCCj$qX;i^bgnsgva#R zw${zGmREJ?(>8-d`q$;q)6{a`#AL=1eTE?mIUs$NuS!oabczlP5ejfT7Z8ID0WQ=s zogfCf<Y)r~keOtG@@@@ta6^SRiZksP#Z)^HcNez=DD?uWc~u|TD3uiJ09#3-0@g4I zaO<5EUw~~Td4p~MZT1l(c`dRwz%edRElo|fIqMU{Bx&YhS1TOv5V=;#dF+n!!5DTQ zn=0xqwLtp-gvobpy-h|}uADKUjeOdG*Du`4jb1o*EPDQScK;;6g#fhI5M~1ab8X_Z zX@EKe^iY+=h#{2;ipTIuwRhE8LsKVp1n6F%ZBRKwuK(*&+lo2qx2Xr6H=OyHefnVw zH?{B5frnP<3a59BC<j_PLry_&@8DdMamb4R*V7XIpYHklg!+>iMNg-`$d(DYoZM>x z@sDbSSqYcet1pwZD@aEbLu2I6*|XE4k6kUHeTWeMw3+h9zQcgB9rRC0$o$`Zm$Yw6 zi{A&#P2?J_BnhNr6)AUT3d-uFr?Q@(s2Mr3aiygGK#P4=x=z4r4}-kHk#Fn(;WGc( zX^+&JCarJy;3KO;1f=pIoS<Xp`+5e1_gD8$wJt{aNxf{0XqcoE*4OYM4A_@ZRvqv5 zC%^qLoZ@h2xd&BrVMV1urkOU~!#{Pu{xEW6A_sTBu{QRsM{1F3h)kuLzY0!(T|&xp zx_CH2CL2zBx(q7e-%FwR6*Y_o&}Q)YG5|rgL0VL}T6?AIkCF<oxGWP+%}Dz5ug0g{ zkWIVnbaN!}&yA5CEw|hZCU5jd3=EbYox6KJ9@o(kkH6b{Zt?W86CPZ=!to9fWbEg? zOK-SAiqu}J*IOl%lCeNuLUp&=4R65^0!Y63qWx}c$w)%Wg30`a#J|{&YK#_y&EpAi zC)!CCz>7YT42hcSn-}>>a%7l*UTkaOiFk=fK&}FuJgp{v+O8&YLaK@Hwub{a9&QJe z$*xObs+IC7X=eH6MFv$6(Bw*p^a%t|7uU=S%lSjTu!jT@MYqO^;Tn&X02m$u;t&9b zHC#IHW<c#Ueb<^>#hAj&GOFwca}l;6(p+oV#2oLZ_7g)3uT2%9bF4Rp#()rfAYjV1 zFh)f!^cb}=W4ypv4Il1QZGBNK%K&8uPG#DQ_SKVr;RIW_grfTS{e|4SF?qe2xt!sZ zczz$;cXT=;tvfR<ru|}AZu)h<0v<YfBU^CgFXKbwvr27^-x@!i{M=DSoY#E{iTWoY z$5s$6%<x2x^h+nxlR~%#?sok6aO+R%h}tN6Vqk~{BwbO-mj+-|*#}dRd*&BYzxQ<q zQ?D$co{3-Rd?zk)R3s|<0EA74wqTSwIg4Zc`T*;VTUlMNdzPFfvI1VS*(dTXB+5o! zeL(cb$5*R6*Q5xJ1ONt!TI*%|lAJwbf^>Z?yeWj4%uQUo30rtin#QH~UQOhK=o$bA z0|3|ikhGS-8=fo}BxnTSYA8mUHx(dCz-G>MXn5Y68`4Q=R<GA%lGZ#)6?(Pm=Lw0A zZI1LPz4Axe>e2+JSB@AK$24Hg%>pdO1@qrIgH*msEwqOPTQ%@86BB$Tt9CfZR$B|% z7jlv&lA2yVe#pu|J4MldLk@^TVL$lYBS2Ys`R>~oeY4O@_~tR!bJKsO?N$cown`mP z5slcmjJ*Axv3|2pQ>H2EiGTa&7tgT~D^NBjmZ1h3Z3&*-7wli_!@#ZKq3wmb@aHAc znu9;G*=JUTF1(lMqcL|#n_YITx3e3Wmo6mhOp>L1FXdmx9@FP0_TDe!hrj2QM@F8h zid=6_TZbcCW`VqCd97o7yhDnj>I9+x@s}>&JE`EOIoT5Q+xz$a>zBtZ`N2XUvA3|2 z+x-3yLYk`|l^LRy@pY-0=CM?B!R4kdaFA%*^Of%3+nK-f>E-Ib(O-VBHpkZ-junE{ zF^hpzrQf?JB*>d3`=$AvOmZvy?};h)px$X~RmRdd&;7YAxU9G2Qj6>7S%qbH!-|GV zIjOV%E12z*Y^UC)!84Nvt;9;qo4BFgxTj^K6GWHJ`&VhDbN>fXZ@G;5z9-$xH<Zxb z=|)LL7t<z!f2LsD$N=jFK!eF6i+Mor<QiMX1`2zCO!{_6MeRt>TZ6Hm6l;+&n)8+- z*BOJ*ts9OP&BYokx!tjP_g)8A`~#IwJSa5&bXNwTv<$Eo0W1NSkPKh}icL^R>Ssx& z!QshxCEGu$O8i`MfuM~$R@^LWE|zZsMb%rl)ZvWN^|$jY_xm3H$>SjO7^<r(Wv4cl zR8?OtMjzbFI@U1zHB->@XHJFiXhmapmL4%2Q<mU!j$M29J|<_N7m?mF3q&zi%swK( zLe^)6_K<3RuzI)`_<WO2n~c{c3~igQ)zKPIS`C*yVV%3CcD1GI$H&1A4OdZ`Mt4#4 zh1h}<lh2dSm{emXtQf__8cN@wf*YO0&#!ew+Qg>n<r+M?1SY`1ei6V@SicG|%NGbc zdBr$5o!YsH6>9Z^<%j_$WUp?3YqQ;%GCvq!20RgTJ+5%gv<e8Rivae6OJEW04H`Yc zeo-bI2s<``ywg<-N=_OshBKNv(5T~U!@G}P9-8^!I#pI!Y^-unMRjors*+wR<S~TT z;7z|_Oo$XKFR_5#(vI(}d^~?Ls6zxGi`aK>9IG|+#$~9yAjiomJEZR2)u3`HS!<t( zZ<Ty6Cj>-P$^N5Y!)tJWPM5_cavH`(LsKS`6-KqT?`60A<p7+SObCYNZa}X}lks?3 zQD?`)Q>ANPxqhw@`){kg+?0Rxa(nIc{)$aPGVs7fVLhM@7a#%tWg%wNf^FLeEAKYH z6fC`*0)XIK=@o(NNpVv>4a*@p4-Fr+#Ymm*w#6DgdN_b-KKrdb6_L<#E;b6B#Es+e z-~Q=T!QMRk;jsl+00YNv*zcZe|AdLKs~Y+=(W&XUl%jd=c+?QPtWdPfsi9P|`^l{o zQXzoL9`Ea#F_QW@&zJmir>;@M=g~3Up5nm1gsN)M%R^NMkpiDtF`+f^YamDgQrLLt z$=j?qW5el?xTU5>+>@?0GPyRDwD<mRQrgO3?%SN}M~t5i@nFxKT&Cz~&c%EMN%x8R z7cJ#LFmmbeZ&6W)?+T`e#&LVj0xv9pm*H%Tp;ptEX#*^G(vayFD|C{-T79yuMf&Y~ zjxTC;F1hPZ<}eBC1rwM1he{>a<XC1)DU)FpNW5dPQZZv-zK5QzB_7)Vj<@JjeSOu0 znj)FPnOE1*88wgiE;@N0hqPWZ{##$_b-4d0>!lbWfX!P{{mH}%6`}<Eea}U|keRk? zTQ|_hvnr_ITGdF;gQ|AI*!efQ*+3ubvg?O3`ZHhjqfPpOJ`T*gn6WntN_AjLfMh@d z>^{F3*7M??@R#TJdSL(Xf<uR*3xGN<s1&eYzC694{Bh3`uJgcA7cZ}5S}p`!-!AW6 zGXA`@`gzIX>=HQ4EQ2HH0Inzp|G}F}=3kZG-)~NI$(yz4Rq=^US7xDv{YbXzGdN{+ zOZ#N@&D)vP?a!NwROZ^Ij;cT9JFaT40;OIcIBQZdC=;9;{79>mN(RKwW<<P}>2Z-@ zZbcGUM3g@}h&4Gi%RCev?#1#;NO8~QT#hgrIGR0HJpSMCWvAl7n5h24Q?F*9i1FCw zPoF-25)wH@H5o-j@bw=6W_A-`W=F0M7SvrG9BF&j&|rD_;&6o>KhVbor&ig_gnbF` z*mZ)<<MltlzCF{!>%)rG^ybj@5O4mP-}esV^PQ&Mif3tU9%VFFk3hOFdB%o6($F5n zqqTTkqJ4<q_)2UO?YQf;4qlmwkq^4p3p!?R6K{7c6!4}7N0@JzLf((>ZwLfiHAhJg ziOZ*Q>y)-^eZ6Os9i(OALoi?YQ}R+_{@RUP9jq(vT)0iV-8l=q_u7o{Gf|zAvCXm+ zz|0b3m%W(<InMlIhgSZ_<0qkJys;GAxxocBTY<^y?t<=rJx3d3KMZV9_?PqN76lcT zJR>f)1XiKfoz}I`RVHsDnU;Ox$(?p>s7Xn#abuQm#O{d_Cv7Ld;U>XBbO0kn{8%|` zU0Hzg&FY3DjH{`JmJk@bz6KcM6iUC0S+IZ_gD#WGGJH109AGl&>tEK<Vj=585?Qv2 zw)|7g&M(ZTbEW~o;Ql?I-j`*e51-;67Pp^}g0d@%fs(cuq1VqiZ@2%JiC)02X5BM> zLcn<@l}UlQ_ttHd0W@kZq#LkBq3|@EN?-c{?{nx^$2)^*vbV#D4!3{Wn-j|2#;{-2 zG@%fFsDHmDc+u&%wnY60%R{)PvzQ@tdf551G3<)--M)x3PAB$lc--2{q-B8h0>L8+ zDQ#DZj&@ujC(cOv#C<o4(&H~AofFKxkn9e=zI3wjvD~pKrlhUwSpw(s;6BkuMAg`z zQ~z^2J9H$!;FppGG4f_lpBsJjQ*AH>`|8i419GPwK4eUHl`Sz!Q7f7JfaFFSae=9& zVj)<0L6K3KdTZGQ6SYnCP58B(L&F}bdHI3U9D2qqKeTjD+><zN{R>X{OW@*N3`k&y z7rEJY`+xRB{t%4vLc{ehO3J^_IA_bhy*O51|2wDj<q#dFH+9q&uv;&VH;=RqI+wvP zyJ>KwdA#W&yWm`H6CI`xmA-tz;nn|stn}M?=S=DM>m^1vIKC3Ae!Fr;W_+ZPuiG@e zc!t*QQATr1a;ts&NPSHM?Q9&l+;ST3i#dn4d~d)TLya$AaOyQn9oir<O|RFo^Vy&z z-MBVDA;oR!2=3aNYB`5a{on)sx2D}VmuP1_8fZc7BaJQgGh|jE!^5qN*6uMwE2e{; z65?wWPE0^IY7PQ6i@%_G9phgE^>=^bB#st;!W)Qf)q0~NwLUfckvM9`U#A$mnWz7V z8*TbS<<seRiI?x?f9GgN^ScqI{tT3>39{iYtPLjvv~aEP^oDl^E#0G<mgtec3Aa)8 zUBP5#D~;n3PXkWa2%p2}RdYLeoHhrKAeOINs2$=<{^7R9>S})DVZO6lurJFsc>9%6 zTPKfO&CkSla0~MFau3>p5<Z7!22KRSSS$<D%4fkuJeO)5+`{BYTGa!=uU<a#6@6yz zYeHZDcerLQx4ZkQ1E)p8=Larv<6awBS5}j5Jc@}UiUyv=2|aH0>xfB8CqD}E-8uSv z=n$RBs+|z#xR@rDO^9(NT0;&T-&>-Hn7=8iE5ZI6ibbtO)5_%Lq^e?5;`=&OJs_@0 z@~KtbH&k7vZ=f&YD{Ovx(j#Lar@gD^`da%ecPeKf=g?m7l(nFP_Q!x7L^jKswahms zIkPOJTXJti`*6(A`Ge{E>KtQo!v&E+wr=hLyNptOb@m#i1nhG6V(rGL1;rDcH9j?w zH9$;)16e8tGeVWZCc+v_g5M1Yex4Z_6uk4iX$TL)YL&4%2C)tXmEu0tM6ph9l6734 zfk<q(utp(KKo)}zN6-NrGIvgCa`6TqdaP1>R08jA7)vfuLrf$a-CSN)^IFzq67%Mk zjWH4HRM-jDwX-MMgRC|1%|bttz=Avg1`jdyG|Yvcp0=0SdmAl+<<dC~G2Qy~L&KX{ zu;)ey0N_JSNCA)wLL%YEU^RO#jD!LNFn6Mn)q&1SE3Dmm^{XAty*i)J!3!LUmsiIt zK<up&I6m5hCU8a|o9!ZK$bkFIx*ixEJZ%)OR1Yr=aAs1&Vo-*eGFeTPLIf?85-A%! zaDL+Ct?Gb_tE-6zI@T9*BLf<k^-a?w0jTz*^LTTSO*kuGx(T1$ctF}0!><Nip`-Z7 znWw-)BV5@zon}y${8`15W~%w3n8rKR!_%X;zM?}tfPN8aH5Xc(g!J~d;>Bi6>(Jtw ziU;ogt$5X@UWTyyGFr^Q-9^PqmDyW~*bIl%ro^THt&$^h%$+q8=(W7XqZQ^X{i*r% zJNR550o<INT8&OsdxCkM9YVL*_6AZCN}MdCkw6~+KGS(JHnx~m0}}+G!UJSr#f3F3 zK-DM1X-jW$uX6SRuli@{iBK2_J*Rar0Rv0mBcxyKEI7g!lWK0%l-8;d1EggZbPRY` z#bip<;9ijbF7+M}s3l1T_M46BU_rm$QSeK5Wj-d6UPY-C=xLIxf<iB%LLd<#y2sRW z7ZJv&7^<{!P{D4t;<RE^Jo<S(sOr|E-uB~l2OL6)NBW~EsOx4AG$tD4d&l=)4_%pB z>j$|*4o&&DSO6?ndS?8yToeYi?o|esSS2}VeoR{{^0j$Ek>snmBRgN%T6vgkVPvu# zovnAO4_Tg`Pq*q&KsN4fulRMVEoK2wM0v8KEEij=Ry%0C3j`#>NUffL1ybbb1~Bu5 z?(~Bcxv4>4^M8vcYyl}K*AyTEusIQJm1eI_<bX;+ux-g!n07DNnT1mjMUF%s3pgsw zW}P<aAapyNx8&eTBJ9@ZMGYK9*`Xi2!J;lNgt5C;OKV|70K9X4Qi6yfn-ju<?48SJ z${>9WmCCG1e&laPtojjzFKoyx0%t`{Jr#j+oV8Y27CvBgmZad`wRlw)h6p>VwX-OH z$Pe<61e2NVtMiHx$2%=jVqx}9!RsN92kBo^1gymw;rW&TbfUabtJw;i9k7I3M73Ae z`dZdZ&o^4ki{~V>F}T6monEjVA)B#0;&eh4FSHu!EvlJHVWa)ltTQfmO4MG9wM9~) zuY1K$?o^W(iCZ*Ry&X~$QP#h9hyF?I0RRFCz`}o(prQ(!P-T+;pJ*!t75oqX%gY=P zR*LOnk8p~Q#7*(QAPl9k!`N$BjiUw&In8F%YkudEcod$Uo_(G-JzsdA@)5qpK0-B+ zGqei2gxAB*$JgVzcpm<5f15l;euw;Y`H$rv6VwSO3C{_C626z=71R}GDJ)W0tB|0u zps=E-rdXobs`yq(U#UUq8qt85Ol&8<BmT3)u%mOwd*y@5*~%3v9x76j4{25vs2Zxa zs1B*lsNoC9Y67)+wMXj6$p_T4)d$sIktt*w@*Z+JxtM&0+(W*jp`l@_!PFSh_(kKp zW^Q4yW{2h%tqoc?wbit<bS!mZbw2Ej-#Mfkr_0q{p;%Dplsw8X<v!&(<xk2FJ(pg; z-c>!Z-eY}t{f`Fe25*dXjBXqKYV<#&&&F9LL}LTvYbI$X113MH2%$war8-ipsV&qC z)GJhpDPoSLsi$d_>5A!F)4$E2Qj(d0S)I9~d4+ksd6$K{MWf}kRiYK&YQXA>)qU$d z*88nvt<$Z$tS7DiPeW<pv;(v(S_$nGt&KKFyJi!*d2M^7{OR)77RL7uDpn|(>ffzD zUH?`6Pb3h~00CMMz$genWg+TFFIND1D(jb}xfJQlfb|kA49yF)j}fTY5)V!}1&N`a zB5Xj};TbhCF%<_r#kJce25UqMwOUz*o}9NOJgmar7@+!s!$||^7}RcCD^|glty$P( z2xPxXhvmz7V8ITyo{ikfsb5zUj#+n}=H2-UH5a{S+U-ptWtO5^a=rELa7^L}PH&A| zl)RONTk0#^iiF{^qd~gt2m`9}Bh$)QcdH{Ygzjr-E|SRbPVBlgFaG>%{A4ZrIskty zUp6L?0v_-)9DEEnZrL7J3t$1usRw^jJ(MTG9N9LN1@H;-%pcU1v2TZ!`988ctCA$) zoC#!=M2fGqohZ{rBJCpD18TWRdyS<MsVI>M6o^od%Mf9ev|hC-NwC|gx-Aa&mztfU zXJAD6sW%vly@5D%G!LxtoeRaWU3AnPR^Jce!(E_fjujV-m0ur>5iMLrrBVbsNPEZp z?RgL@B}V4$VW3jC{?B?4dWMufov^?4hpfa<7RX(c3H$NSG9_-Di&(=5C99gJ=4N<z zvS<X4dWbGB)fZiLHK~w+33^!8o_E)Z??+`M1BJxX3|JNNjt`0!r`ch4b2?DSq4XBq z`#grFyS44J30!JA7gBD@9AH5H8cHyoM;!_(2{M4syYWkUV<YL&^mxnyc}<J<U7bJ* zP)yMiF!|yD9EY<!(v*m;3&nZdc?U{6RO26Fy6dd#WXS@(kS)OHK(pF->yBg`6bg_T zSitdoYKD=ao&A%rq+S!xW;2shxvZi@B0o-dePxVk$)+ny+J1lY;VASEqOAwasWT_3 zJZ^tzBu?LOg8J6wrte~LpsN0uhQA?d!40|bMf-=wanOQ)jZu>9sjZ;Akz;bq9wTIs zQ3`K91zy{_UWDm-IlKm@K_;%DkBGmpwx>*cD%m(De252ax&V4`HDnkg7p!)GCmntp zHjF?@GIlKh%a=*`hH_mev6HTEBuMiu(yImOATaH9Ddsn_BUoMlJSGH7^Q6<Uet5Ol z5K;&U6npDlCa_~#Apl;vtR^yYNUCW1QAyGz!>Q^5l~d++<#5BTCwp6wMc=T3^#K<C z&`*geHWIT^`)beu1DFF0(|gYnN$f~l_2I*H|LN5<9UugeDz6N0Hv+YT%5Nl;WC1JW zu>OG9Mnq2*jDDh_4M~;MzQviz#4t<Qt_3>mkW#Ad4SzS_780r&HAJ?S*5c2P^wevB z*z9J<Cv(<<2~0?s4n!-|UkPq$nDOm4g$eU`6QcBj5u)}9Bi7f~E0M!6eO%Azt{B%T zWv3n1gdJp^-GI+vr=qD89@H4|ZLnG96tsK@m6ms8H(l1*NE}@ELCM4pG*YAwm!k~= z0)mbl#Z4K7)Afbt(LIiFI9kg0KnP0ej`jKcL=XLVJW2I)Ippu!9;~C!?<2EowH<nL zp@>hyD~DrC;%06De_y4{CyxR4V>8xvdHH(K`{nR~q28IZ+CcDLvve0fiemhzSWc!H zz)3@g1DAEG!c|4Ou?{$TxhC@Eu>W1kd}M%n7~|LC%(Lz%tQY%}pTPsqVvMPc50DeI z?>g<(h;g$FG?edqwY8Z>oc{esn$*uzQR6t1eJ4Jviu!U6vn#qW!Vlv60j&4M?KReR zLo1&&$B<<p<G$E-*VR6G^3Z4u7#=gWfhQpUT8`HM>xC4~k}57%Gvtq9Kg6v}nAy!F zN?p~MI2m<T4ti*}@69;-=B|zs40`n1ye)}=V#ggc>P}0PPyC#G$wn1)cjun*@@)YW zNx1S4NY#nGrB0`Npkpk@yp(%2e_d;r#@~x7!GWWsle22LNjttMTxMD>hqlWS#?aOL z-4UZNbRE&UnEycJ5obep)j%1kV2|nK&J3lbrWC`29DADu_ERu5)3R%PV}ZSxX=)v& z(C*I#HJ=^h9M9#YEQ;&IU0$ZTEJ+&xeE60yDN~mDh7_!%UVre6Ce;Q!Ujx#za_j(U z<vwNoj{asb0aPaQc=mL9B3VpLZg?9hE5X>0s>x9(FdXWn9x44UE?_-vDMqFmCArOW zMfg0WgabEMB{!WB!Lpz_lel4*UvKKtKPZC%xnT*OzJ<Dj?bFz2IWmKrZBM=3yG48} z5PWdg@4!sea>;|9NLN;04XnE>ES7%1yi@W75SA;U(Ldg!uXYUIdwl=d#|>sY12m(u z-JfX>Ju%7k>Jcus9G#YCi-!#Tps%{+lJax2(^Hco&B5l=^lj~s<97~Bs*j%fnr0WV zyQ0pMPS@H$5A3uth9r1Us`@82e`jGC?$1JVSPolcqNTd*(pwR=H0xx(|K@C`E`ScM zD89XhY^^~8?nAbJ1)VBE3#W_G*06$*^x^PenAh}+(e=a(angjXxdlXBiFLSdOF8R4 ze(H(Q(X;3K@nIT**1_G~>UqP(LTeeYD6eZnLqQyeNUh|*#<_n@1-+fd;OVe*Ht;S? zn)}Ud1@x$}?MGN&0jIQC8QNt1kA7(je_v@H@^#{HJwtk_x>1jctDn@*Qy$ecyL zW10q7vm%}W(SJ>|LjG=nkZ;&-L(O}iwX(N|la4;p2PgP>&yPyyoczO}#9bX_;^X$0 zCMMd>jmk)_Waa$8GGH!V28mJ?1w`-~1evctcTdLiE5YGEhaqCO@sjY@OTG=u<zne4 zPo;BLazHv=Y4AgnxSQVKUn-7QZTkL*OMKrj+;)BfvaSi3)6x9vw#>9B&%)SoBAKR# zGdSAr{ovW3n%n0t{d99g6P8*kdvJ69%|vm}YvZ3inAZu8-qYK+uRE1}Sur|_6IW+y zmtd){a*N3q1K-0b0h#?$Rfg!PlH{{tIucQM*tf#+n4_JlsrvQGKO!*1$I9RGYAX%c zj3KBykWPgLYCg`x5N<xZfk!Jw#;%fJmk0;ek60C<EHOJM%z`X=?PA`{kn&C)!^VI6 z*huH{Y0Tv#VGS(p^28sQ@oT!3YfeA;B8Zd<Wc$pI=PL`WKw!Hp+byOb-!piiuVXJa z@(E`vA-vt=6nR-F+ri*FWAw$HTa@o%F%<-F60D56x(Qdk17UO{s@Vn_S6;}}=}KhA zc{$lUf(GzH4&5WTss$@Fg>5q%TF~D3EJR_D07v9&m&QyD;aHqQfAsj~WM}uluH8Nh z{aQ<lyULc$evX~>bWHgBiHUykjBCc_TWRlQHLV({Ml??;Zwgxpy4*D$-LIsvjVy{5 zo4%3~notvi`FQ`YL@tO)yTM^G=f>t5E^xRvjHE}otp!unQ*VWbb3I+7SFNv=f|=9_ z1{`6(T$M^SD4Wu8277n!?giCf>4)KwffP{T&8y(~QA#{Pl#06V_a+Ly25q9OLx27j z{EnV!e+cYsxIbS-9_3@&_uY@-8JU2fD&Z=^lPOC4aRq9G{H()l#}n(e!&h(=CIr&b zY&mll!ceLL)$>_c2nQ@H_57DPhy3%Y`%*En>wYTvse&4W_s_sBRW`Q5d@=+nd3g{* zOTiv#Z7mO9fR_DlCv|xJt5C;2sW|+E`}?>Pzo&_fi)5Xnzp>33)sieM_RK1}B?RCX zMNN7I?8vp5$J5pp+f>Vd^m@!NFpTY`*4=&K_s8P!U*J+B>cy1@{;tzinc2F`bY8yi z<yb=saq72!-K2in8+8N+?u#R{!pl8KuJ~FBKZ4vD!TJVL+F@<eHM33Ab*TdEt8Hh4 zEzcMS2Z3{{T)(m8%t^I4)r_;vy;pUP)1*8(XHIvJQ_W8lV??=orRFl%luNg)AyTHH zs&NS9;YN3^Z_!;*<CHb^O7&~onb!jTUpS7_H#|ChHZIj4EKV|c|3v&A>XgaG|1tA( za}v9il=qmtDqbVuJxB=u2M_0L5`|wId1AZZyZb4R)R^5d#h2C^#uT(ljfASw<H6@C zC=22XIF4rk>o(}6i^6N!NMK%rVXy=Un8D7!_I>rVBdh{9OdNSjVfZmAad5Db*hy5; zNaIFoK2IDk#cQGd4-j%L(iPT5+!BR?K&-QsBO(#r2~8>6q-~%F#z}JO3e|LSG%5<4 zi0+hBepLw^<)HQfy!T-ViD6O$5(QW$+Zfo>i=hx`ayb(50}wv^wcrBo#rUs$Ea*LV zsUH&7){#W_=%j3#5-p@<;QU;RqA;*O|FDypcFI|3w5_IkiO?m^<~MKs+_464Kkx4w zmPCS-Kab)?!Nr_{A9o2?in-NcG`I%Z--5wL8<||fxV=ps;N&hTC`e3xgaME8`dnRh z1TK4mOy9ZScbYsj-imuKI13EcE(Hc-IZ73N#6B9qIx5xZRz~hb=6|KL#3;tW%mI`c zHtc-B2>kX-B%N==Xch7l?Y5@$@y;ZhxHLYsmI2KO*()4Z_7S(C%-ph7jMVF6v|34$ zP8E<U%bCdr7PS-r)1VN-m`ca~(~vHB?D%*!B&k1h-7|?SLzb}C?IJA--E)}n5+$5% zLiG#g>~rmBjt<yrEIdOzw5w+H{=<ncUYQyJ{W$6H@lz9*@9?pnga`D(YCukNDXF%d zej!S}OQ*fCwzhWU5%H$n(Z!gQ-*8zIRRuZ*65u?{`Cp`PFOV6wmo}hk3dODVk2<-U zl9=TIuz=c`NO^2;m6eYBQKr>aG*c0=CT)Y1wKV+(MNrgnoF<7h5vzuyWIcDIAO{)c zRizFN*aboRHW#;v`N81h!Sp)aNRjnytD;-uZqe?F>z1M&nLs7+doeiPh+T@i?_7>V zWW&&}W`pO7>!@l3X(1-u!YAqxGXN)cN0yJGqp^8M=rm<d>UZ>K4h7lA-M|FDu)qmu zOEPCaERrjoavJ@M{ddW%xsv+ZuZ8s7?WtLuk&}x(n%<jgT#P28-(&^|B*OEY;C#2M z{}Yn{l_KO(yn4V$D{qcWrgE3J3th4JMWIv{hJh!md1E6-(^M&Xon%55fIdjg4~*JO zeCdk={b3v%34KHD!;@hrQJK89zly!XV2{7MxBuQJKEPLKP-HNN^PUrLV15>5Bal&C z%sW`DG71^d)hh93DP!6;O$$OaAwcEueQ&fiL_9{Z_AR}wsU`;ogLMp`hkM{Rb5v=D z{`0p#AgJV%!HJ?~1Osf2Sjqaej&v98yz?%co<5C_HD}!eGs=zuxqYo4DC@+YY6f+b z<|Wdxo>gxXzQcq=0IX7W2LV8pL)70TKOtNI14jof-PZci8B!S?7j|b)v00sQqT+#{ zE|(#_t&ul3wGa|8=9I*YG8+yFaVpr{-T_l8!N-Ez0HBaBsVaNe3kTUBE-Kwe4=G2w z^yGdS5^ng4a><apC}D4nbFTPdQju^!O^E{W+Bw>T{3ZFf#YsOn+=cW)<D<X_Vx~Hk zS5Y@Ci7fnK!6F+P$Q=JnP9%G(MGKP;*B-OLkF`7QEU9mckaXoX9dg<hSW3$4hC+K? zC-F0@wx4|DqCv0+=Mk4yRziZcn@R}xK>Kun6e%!|7Vpl0pqz*j#;4VoN;qwdTXX;K z5BfNc?f&EScuWmjb>bO{&?<h8+Bek$Lpe=gE@CqYxY~*_-(&d;t_q0Rg_&%8`Ngp# z2;bbpwxf1ze{t*RMSS|H*phP%=CXO4W#i2q9p&~TxPsfrtYXpr@GFCGUX>)g{6Q@l zVw7QGOzX(V(CS2u;ri_(F6Rj)v#CVz(ZWGX7jrICmCL26HIx|kdA}v#LHizvc`Rvl zn!%v#(@7&e$I&{k?zZNp1^tjk5O^$XNS4MWshSKSHAQ936+6C?B=HqeZ*v-&t<u>) z<~?O*ajYC)1CKvrR2rC0Gvc@2*$(p}!DAG7puiNsifA6!YV7XF*(aX9K8hd<Puzdv z+^_vG92#(fQhfX)uS18=rzxuM$b<Q|9`6FVe1WPQJ%qTK;<OmtH^J3${M+qa2=XP# z7X43+pf6ZrgEm58f}piZk?0I!IT`diwB572^Y_^^lhHUb79$S1LMNR-bpp_W{d|<J zdUA0HJ+HhJNEZ(|OUr1jlC)OkR5TlQ$#Qkh8Ly0nVyvN5JPu(O4iVgN>~>1*YoM7s z&wn~Nc;?-)(EP==W5@Qy`oG!CVJ1h@qq{mi9^)=}a^g}Xaw&L;IV4HEv0^MU^Yghd z7Fec^AO>jEwx{O#0M`2-I1+?RNy52Kjb)n5Afw(C3m3;SUGwZdnU4fX77wX`q9Pw_ zpyO)npKi>HEt~eQ!P4Uku}d<U?ehrB*W|AEou0aK-xg6tMW(r?L{bg!P^qHt$u(<Z zy{CWI*WVw*;Y=qP_OgTRR?;y!>(!K&T7gyol3Nk9Bu7Wz-QFd(Mev2tKSn}ZB3x<! zDY($UW-RvaY)DNM3YVQzqlyiP`Kwa#|8#*2%DuE~ftZf__M@beQ&G5V3;3eE;coTr zMB>AU3g$STpUvV2_6N}2PNi|nv$e!bl=7s<NoNOz6z^ZOwhV{^DwO%SrMN;p>u>CK z^EzMBXeNW2If)r9JW|$%P_&wv8mMD`YY!g=4VJg|j<u&rv5#}1=kmslityQ}nKAV% zc_5FBj-J0udAJ+n%0`hDM<?9PFQaS%B{EP1!q70k5yzCdNjca%A&5@U0p6Q_6-?mk z#PAGhR5`iM#Uyy{-hG2a2?-|YIDBI}J$-Xzaw+x9yLG<Z<3!DYdSQ5`?{UNEhaTP6 z;xTq(gBB+}bCPKw<?ngHKOU^kPRNMrSPyLno?gEFL{<TPcqoMlI;tqh6HHRBW@A4Q zZe?zdB8XgxXj$HH)`B`rh=I-+yJc6;?%AI3-35O{Lb0eITpb5G(eF$jAlXF5vjMUd zqn{4mv&r2c8Q}$Dv0W*QAz{+dCW5Q^i>UNl(TgQ?Q<=dkXjx5#qkJQk;6c=uDcA7d z@b=_-+ghiOrL2($ug44>D9>wTm1M-QzF3%BzM1yadtKYppGTEtc?DUI;Gw5cwt<&| zQmFT%#(v1OaC34Z)K~QFN8ZVk)YbUJ#}Tt~kwe?@!>*)<?RO6$EGp*W`29|N38Y(q zLz^g-D!ct+=hhJi1O+}Bf<+>3P5-7eI{Ii=?qB_g;+3ZCx6!q|;f#`^5Qx_>6TYaV zt9U+DAi*7;uVf_G?AO8&3?O1eaiK@mZRG$&+k!#{d`G76v{LkbFl4w(obnY`muQ$j z4qj?39cJj}CPA75T)*kfqTP40D9(ov;S0sDn!j&jku1@}ZP7P48?yq1(Tb|O-<{%? z7t)exOXIN>Dh-LIFPhG)g>$zDuxve^UTtb27Om%*ScwMP^q4N?nG{Hr3s$I-iS@c` zM%$;0JKv2civDu(L&fU+FxvFc3cr>Q&UP;_At|{0O#!r9V+FOJ_T3S)-~K5WboEC; z$Lnhy@TlgCzaL1a4;&mAOAg<DAn6RfUjX!_JhIz_bDn)biL7<C6OkUhC7W}#=qP7S z=fZp28^3HeiUqqD;lk~*FBVlCvLMfoE&B!9B<9Ii5D;~AW8amkf~`-EV>Pb+7PaES zE$PR^Rc!8OVm;tA_)77{;r$2Y>C{`??9FLfU(i6=c5~-Sz%em@_aUF*8gk-9$`df2 zCiFA?fnC!2t>ZXHw0eTG*^!Z32!#Sc3Wy_(Sem^$c0|AY;X%;Y;-108E|Z<d`+-K( z*K8Ub>}YMrCM;Q3af%f~{wH2X1gjK@4h;Zj*qvf*yNNy?wl)jr{MeymQgPyFNd))z zFS~WM0Xrzf*O{~M5=FrwdD4V!CFsGfc^%s9OxY66r;O9u(mnJpYiNQ-*=0zTRI`~& zR6wf??$}>-7X!3_!hyrccIxjw=f3-zd*N5k#f78)<V-++j;6D8+F(D5IMTQ&gV8A= zmlX&(kQ!XmkRtEi|DSHZ%rKAG!6(By-2>|=1_`u=emd~?#z`9UDht$PDhsOs<V-Df zi(cZ$utIFZ?FSlQM!t6&8H+~@(jCg<{eMPhDRkK(^)5nY0>*Q==?JPyxMO|HE}cDZ z(F$#pLRiI8E~ZKhSjI6BgG=SRMt)vRfkinFI<QhTsV)E>0)w@_(cpI$<u>|6*M466 z|03G+C^6W-c!<Rqn`%ILs~>-`f(CgcuM4NcUVJPEhbJ|KMF7Pc%-6u%;v;uM7`~fy z$#>RZ>*m7Q+bmxTrEAfS*RE$hei`3N6JstO^6|zoa!Vfi^{r578QRm<^LI-HS&Xf- z#<Kh72hlS^tzI?#S&z6ZsG=#<kwnVDX^PbyDS7C355SHk?Z`<ia7<7{P{7xz46>P& z@4sDMVM0ADs*)rNE>xBJ#+>UIZ}RflW7%8hTOFP3?7Z-8oAd(Bf~hw#B(s58-Bn!v z`d;3WHbJ-{5KAFzxx*U@UCc7#fh^N3Grg96@^v7cMKO~(%zYZZCU`Jh<3+lVr*aa9 zSJl;!N)u|sSY(HA#0sobS;L}>iQVL8>eg9Q+Ih8Bk5^h-A9aEzme9o*1;xGl>d|;0 z2;s~L9a(lB+J6dBI!#?O4q47l^ZY0>euW!_$Q#rlP@}r_E-6iQUJZ9FFE=Rd2uo&= zkb&*>iGUD-!id71F5{<eYW&f5sz%9_87z=%B)HI4-v@fqYmbA*24j~HFElU&OU~m+ z)6LCkhy^j#Ir#CUFzCszINL@Q_ExOgzU(rik!JVLhlSBiiN4)Lh&Ym99M|vk`ind4 z0r=trM#7UPZM&GiemfagyYK4FUz)hPv~;XT+V$<4Oh`>QqR}bPQ|qd(q2Qm#qW=6Z z=vF>{cuw52Srm&xPPBq$wJlg=t62OJj!=j#zw){Vzel@<W!g*fE&24;<dDNNGvOvd z-rKR@wcFn&tEP&sj-3uWmtRu!bVjNiA}T6i^(bId0^p<$bbM;}Az06L2{s%~uCFHo zOiAo(bmwSWr9pG^A#W1=zvv?6MUjRhM%N0HuMi<L<I*xnQr~Ze2yJi>r#X>4+!SPr zi2=uJRFcov5;B>^$rLqTr5P9`-x_or(34%h*4w*EuGfUwQ^&$<DHu{8D9KN`CZ8UR zEvbF$hh2IJw%~T<KM_EdiWV=NBU5>E+vk7XyXV-%tvG0vW797v_~Ao~8HPRa#)IL5 zj*n;KPoH~oB>!<xC~4}YmTCtrTei3GU=AsY4XGnmx$gt^Lc);;&rJT|R|Sp=b`xMR zKnPD>$&JSw*{MoUv5m4(T7$y`48r2s=5ySsq=Ffegxacc0ERt@xjAzGpwRg{&XPn5 zsHdo75F^6v{`|mzjZWY3P)X7QV5)0+ik;950KyKGJ*o4wpG-CUxVu8omQRw?>gq?> zZ`{=EBDQop!C<(|fn?)i0_FB5K`_RmxS40o&V4oa5$8a@exZL1`IaM?4L$nz@rO4o zH@}rV04D4g%ySG*nqyI-Ks4XRw1dW?2Y1sV2<M%wC*~`r*I-ZOc%9Q&)R&-YVz9Vd zvZ+28Z;oH`^DrD{IxSd;wxrW1<C)BVR|Mk0aoXrsz?S&)k!<9Zf)f`hho;Zjnm~r2 z^uiT~39o)H+r2M!IBg!9pz(I7<Ry4IW^I3};oJ#Ab#y469-hACaSm~iHeWP+Rp~l2 z1%~56d3Fp89?idryR<{0fret){Ke}I(q9cuj2chWD}majRP#aYXzpnaqib=Yj_Ax| z;uFR|Axd1Qt|P&D?*q`DSLJpi&eNvxV%B^ofHng(s}Fm(a6P9pnO{kl<haLnmUOcp zc_`CcOTyl9lS;^d<6(5B_O37?k&I#(V2F?8dY~rO`O6)YCN@_~Eeswc&9c|p0@S}Y zlW84(t3UkR^x&v6kbUq6M;D{715$}=&P1D+lQgq2WkU1MemaEzfka~)X{)nug_p0A zXb62;Ufw2lO#G`)!pK?=2>c7O@z1%(N21<?6FeVU*6rMjRM~SJtyb5He~#!zSqOs@ z_@2BChY#OeUci$!!tKJ{`8-t&QrhsM2JqN&?Oxksxo%(>!AD--pYQ8MCpDOt?LY6! zf2cqh^3V12wie(ijV!N2iwnW8r){JsFJxqcQyC5ktnu#w{G@3qYTw@I&v*YkCza>> zvF|;q8UydA><*CTAeG<TqE{Lw9}M>cdAt$Z62{E{K`<9;yH6b-k4ANI0}&3p@gy(= znTxVvBhM|vohv0T@c;>buv1<s=8;j<x1Rc~W=KYfN*Ju+6cJ+)7<_^a&uhYnzQnfW zDIe_nrUaWB(86*=a2(|NNUXFaPhY#%-x*))@CD*MHi!k9fGo&w6^lO|bT4GMmr9Gq z4Ku&~W<=!2o@2(%7_u*_Z{NGX2$Wrv<OO&z6tZ#j5v_b+|5mqr?i84pKMUUGGyr7| z#3#d_MO|VX#Y!{cya_eiC|TLPvHo)sLK51y_QE~90VDcYqN>qFPW4EJFVEN)la>QF zO46rH6pMr3K3KLTJC<>s3hQG($?KED!>@pYEK0bhloby@rc8cXl{m+u%7rAcS5&gU z<$jy{1D%PZ<yisvj|Q&}uGUq^e3J!=9H+F~lDSv%W^XLX`d?|)7MUXd7I3sG{lE)9 zoGzbDXr#M8A9WSaPO2(~_~Z{6)g8{igoxRxqv87xc%;twhrga3`!SBlI%Pk6e)H!+ zGfS#_W)xT-vM&E~CosKVs7Hr=Ha<UxC$}XEeh_+t@U6FWqzi)|vqXtS(u^^EY8s1; znY+1E?2~rwB2!|`_fuF^mE_+k;aLIpet&gLd%A6G5MR2Ark9J#f557fhvzkE#Ki>z zQQ_}R&d@_U9=?to$A%1tM@T#kY*@MDXce$UJ(wc{j;Zt1`_MWX+`8+_gy`EOY=O&v zhH1DFY`-P(T$v)mNPV%iP|wyHNXJA-3sLMyzI||-RYzK#fF}DMcCwl2s4o>M<>4gL z*fmjKzq>w64!8+N=DMc5CL3B2ekVI47#H_UsbT_;7b#!I{X@kE=?t*Fy1rT+^E5ff zP$%>xKf{SbXBW0J_=cp?o+*06&N7C6d^_6IZsbC0`>Lje4xZs{0f~&9CPf`#^mVhu zhtVBj=0p{n=uJdBx8~vsj)4rs--4s*CAwiWT=Y1y5XwpvW5H9Y8aPb}wx>uEMUIy# zUm}+_Z!SNqy|j_Yi>704+X|Fz`<xwXIA_vRt~ruu?tY#XfSt%V-6hkfe;)kj?nte^ zY5RvWCZdQ34YzLBk}^~<S#yO3nNwlZDO$k^GY1v8Bn-!)QGfl;)tkL6Tek1^>kl~` z2d<5E{QPBx_1*2a8QPlSfzO&W;SF9VxgDPvnpsLv+!x$pxX%H*e61t7r-O!rZ*9H| zA+mWgoqJ#IQd|$~J9}jGwQ^?&tU){NYVs0>ye@Gw`?;;)&1MO=(TJtY!VlPPtW7f& zgjkM$@Oecq{pGrtSD}bRGMh4=ieS>7>K}^Nh6JuN_Oe*TKSsk<;mWIp!0Ew}6GOxO z*=(`~bd(Bv-xRc_JhhG@Y&ApCOTqQtLHHo_jo71&{(kUE6$go|lStF+dkC-WlOVcb zf+=M?WNNNwSc+pSnn?sEy2(-j>kfW~ak9pisil5#+l;1zL;GSu%u6+vRHvS#|8V;~ zRNojHi*&nO{dQrGAuRLg>2kJ1y)Bk%i+kOT;M(bF@c#Ch$qItHni<dXDYF(#IKstT zODvs1m1YNJ>x69K*^zatGc=^puxmAeTFv=tE_ptSexH3jTsUXwUe;-RBeWD_4@P<G zwjg+%NycHD$#{N&7}wIqf3w+&YvA*&f<S8f{<AQO&9Os6F4ONv30ze31NHmKJR$b+ zEZZ4mdZ0gwDJ6V-e4nTIx+9B1+1jz^iTRYYg(_tR5dJYh>dRu2Ej@xQTF|oBj0W+> zlH#gT)iPN$x1^25LKv4=*tJo|SQ}^t>0S+R+Fzj$5wa|{MWz6KOB#_Va(811>O1^n zVCQ%iNbsq~>ahxkE20(TA}sJn``V!e@~eZK-toZ|&4?q76?^HdPU{)q^4I(?0c~Aw zpVrhCWjd)uy3_|t?t?g%;=d<PB$e~seR{$C*<vqONcgTBT+kc_!+e#Fn#7GKmh6tl z7M})R!G%>cXP!xA$vHw+>Y3)p?gR)(jt!LU6n1%iMd_S*f6s8p!3Z2-DhF#YB`hYj zYU^=DLME#J1H<%9eU*b;3fEbT3fCz!gHvp#Y!5t*hOOGq8_It=uknWm_=E81mdl9R z99p&<qIQXP_Z}-RgOCaDJV&NTv&?kU*Yy64fH!C`_?t;9BEZvT(RYPUQW&`|;<dJr z;(F&S&L+W9oKM}ZAimS&@$C>hGPp)n#`eFI`mb+zK1C<5^t09!v_LDwaN7`+?;;AM ztL&x{K6H^mZ;h=@xyeoH<0SBrop8@vn8Yjt?t%l>iw`3l)4r!=8s;?QQp0T<T>cO( zuSWo!Hg$QpEKZ&wDU*Xk-1Va|r#M7y4G5+>y>=@9eUTd))MzL5k<p<fdmq;G$T7J6 z^de8mw%0zD=*s}<OD8>J%eeT%)SUtRkwZ}&MN%=*3S#4W4(%FZD*26o1yipbm0)qn zf~Ky<o~1~Zv5<KLSi(J1BtfTqsWCW0Tu(UyP_w5%2UECde^cYCmF8wm4rwRAEKhrI zMX?I~0pcqTT(NH1+x9^+YBgDghvB%$@`$~d*VkAOJeMTgkxLK!v^Fp8fu4owu)0Ws zkgdTb0du5NHB<|i2J#AR6K<pw5>T=l<r5Pf*OHQYBNF_%EtlIg)lc71dC?KG6ARiD zd>7Ap4736qEvd9TcV1;tynym#azAU7`vd5uS_Ag=73^nWX9D(p@tJY;5vcCynJ1Sx zPUz)Dee82M(!X7A$VM;~0v*t6QLuSJ8k$9v2rkcqSEEG3SjwDWL<<+Rq=*kX7vk2I zhbJ>ANoZkIjilE(bi=q}{W#b6l!tl`KboCQwEVrkq!unX>wiGH)GcZtf9jo2njD$F z>l|c=!b5u}k89w^J*TeBJ1oRD`DagL&xUpAKx(Gy+~A{%m*v-%&7P6;w7PkT-1&=G z536<WbHx*^X7A{kUmuW`rjhQS@I)=4Y&eX(T^KAbL2EB+0mE7stEj2i7DVTll-Q+W z!M&CB3d38U<{r9)DjqTjxVX@>X`Iw*+e_0%%_Do`hE^R7<In?ZZ{U);`Lt&hEP@wf z$`quAY<Soap^29j)rz@WGe(A{&+q}OTIjUa@zEe8O8ATFHtMF1KmDt^gZM@h6KmQF zb;)3ZeiH4pqT)u1D+mO#QE34Fjj-X~2cPLedWJM2A^FDnDhEnShTf}}Adw+UvD^P| z_@yaf(6_h|LXAJGiUeNsxrzmt%qyIa&QW6GZQCd&^9kBxQLu^fGor7X9!a3;Vasc1 zU^Ssi(I5guf1F2&4ES3^Ke6jy)K`B{b*w})riq^I9e?g+$H8XY=M`}=DKv?~6%wUW z$b_S@>(l85<*mk>8|zNq&%r1N_s?|)ydBHoZOO0W5!0Bu)W4jY7#VRv$foFpisEP) zIPiUi{F*;@ErunNw;HK^q7ZCdDWL7;fpA?&^A*XSdZD+1c^2dGV2b~_t%LcLdn@4} zQ4$h7SOGGlc3`OyUAgx+%6v$#<c*6P<H}b;QE~_*J)ZIQl`<_<vYMB5iNrBCS@^Z+ zf8HkC4uZ~XeHtRSxb!tQEGo55uor!grfIj!4e0_#QREpYBbl1eD3ucdk}aP}if>XJ zQ_~Th%Z4~&wjY*x*5}{z>vwjW{_38E>dkJ&{o1|s<`}4~3OyD#4P*f5Oqnt>jh_mI zNJhAS`O;;}=gLUBI&tC0AA>)IN<JDLO?OSFk<u@Lwe{Y<&)}4il2J37(}em)-==t@ z-&QuO)qe(%)Z(n2eppkM>ra%YZ#3gpF^!LYy~#GHk9z&jaMB1QWgWkvi!aj17g&`P z`ZH_!Cf^}KlRjFaqOt}hG7$)i8Wb`x4V7^O&6NK}As!nmq}4Et(f#v9hsg`c)JHx@ z))Ge#3)~--)=_)wN?v-MBa1;bYsf`PZh<yk_!Cdoo}g$8TcRjjI6U@HI)K~#*-vju z&K*7A`%iOt{#fh9x21o6au(35;pIu3+`CNLC|qHqbh7<b{Z3dOlfi#`-l!5V-c}Sx zM<Y6BY6}!AR@jzG<+^38YjPCy)1Vr=eHvdw5>-Q;`+6BX$v8P~X$`RfZ4SBe%AC%W z`QJv5sxgsh;YR!O)fiJ1t$j}XahiVW^DvrDzZt!&Em_C(&#yPjn{bujn7aEs0Aj*C zk7fPuKaWEjanZkMH&{XL9Hs!W4u{Co)14Arp@2_gzXS-BZPBI_l?_$~$7|HqUO25q zUz5vr!1(;vxK0JLmB6<@N=GmqXp*%VfMYB4tD**99QjTxi4}~%*d(m|vjwdqBrO)m zgJJ-SE*oE3&$?tJrFCS%w$!m1fd}=nyb;lc6w{12k$eCfYl=Z3E8@VBrV!dtdyUXy z3y<u#qq-Eu=Dwzs+_2tNX}Vh%$aht}Fvl)XcDVH@Rl;4ImC%*nZ_VoF7gvD8dVSMc z4ydW~cgf=4$h7WZI_?h*UctM{s1<epIj3Mn#FX<+!Bf1zU|8Tp|B*b_b)#zT<SQFh zQJFjg+7h6f3i?8&5@GfDg<)mbWg(R+@n#AV>%Q9VRqIMK_gi1d^C-xR+q9tL#GU1{ zIACn9Su%z}7zp;<d1-O$5y0BJ@&8V@Hv461Gz~`IAC0blv+5C*u1%|PsdU9?@9JmE zjIgW0tMVY-N|#y9tpc}r)VF$M^`cwjR#)vCc1@qG9QpZ?G7`JY)q^$3+u;^6$C;rU zPjh31;3)nbGn;rF`<Wv`3@RxVce3dneUINW1aO*~I*NsatiUedkUFx#ToEv4<rf1- zk}5QwBI^;^!w=SRgZm0xin3=%ae`QZB#cKg>4>OBi&P=^u$^hRm;y95g!evxmoKKL zZT#;Gjc8r%sK&tB)-VX27zw=$Qn!R^x&rsz9U+V=<Q}7(O;wDkR=l=^ArSk$Bi?jF zuGh*UGb{yU{*$}P?TclhtEPQa7N0h|Pr0hwqAg(ZB02m>PMM-IJgvijPZTY%F5gF> z;igRJZKIzs>+}~zWe$ldY8hh-9Rd{|(I!Y%+t&P|iqXabGw%aM5TVqrKmhAAy_ue& z+)|0LG$(tFR$%-tVM)Ij<C1X^ggrYu*moM%lUkd9;=aUD`F@I2!Jw*qi6X?Z>H+!S z?I@(>rxT0mB9B`u9-4t5QG&~a(la!>Kqwe;y*gGe-{xX{zgVEY9S#fvAg=-|vQ{F{ zml456fJGYyWy6f_2;ga87u;c6MWM&~w7m(DL1b-5TU)SD{!7_#FS`V3>)8LAwj~nv zld!S`7}!ExSRsb^@1yDIdtGAjzyL@q_Y4n?^I*yK=8XAi6uZHDr$xRY7mT&JQPv~$ zqnl}S*MVt;=5ML%3T(SHxUuh_y%T}^8ivDJa^75$$Uk!adOQwZED1QtthR$0^WJ0} zCIM1Vm?6&sX>={ORs!h`YIhr+N<u)pa0o;o4$gC>CwJcP;e=<?^w*Ei7nE_Z5-7~< zbWtc9fH<}S)aq|sVqy5gf9GtXzDM`l=#jsOW_`a@d@%A`N;Kmim(gY6wA_Kq&#|mo zW5Yg9f%nWUgXjHOL@HGx@~k}J|5n1kH>&UKl7zZ}bv=DRdmQ5dhETMy7`bndv%C8s zRmZKId(zbHhc0(L*YTt*<ZA9BNz#B!<djLwr-+qRMDUG{jrn;n>vcRqxuFIs=+8iW zq<mf=87JGl7p%@i4WcQUHZDEG1QhIvatRkC6?nW8AyVMZUL&X>m(4OxYx)<AufY~H zXJ&v6DXPj7CyHrE)`4$NwjLW8=v?;>MIVnji5qPx{!Cju(rNI)%8$CNZ;nHzT|3uf z?IyYWITl>NL7U}$Q-J%_i4jqhn0=r=N~=5ejpb!s$1K=B&!AH;bp)RtTCvH9V7(A+ zL%xhWRj3*PNpT$I@vs~Up#jRwzA`-A7t4&NldcQVWuiB0zy{k@E9yzNszE0V%j?He zH~dEl_uTvIk-226ucm9fH5E(-Peph{CZ{R*oBN-wAig3yiS^UZje<<~AJS}(f1N&% z6P&Yr<RP@0m9Z|&6PJ5{TJbVT{j$Xi%0L&J(P*Bd@CeoAUH0C4R<;gaEq?UV$#~>Q zzW%~h?R53#WVujX-5!96t;iUw{b3$FMlg(<jMVnfFviP%*!ShwAY=uKxh$lDi-?0k zi0xOQIWp;<J&mg6Dn->0Lm$```G6+%G*Bvt928p-HuDb9*`nfQg*U(>{qun&bNbt3 z9IWwdjHZWqtB?4u?#S1gCEG&2-}tq{guCZ$Ezeu)rt|Y?0T{^paR`4Xr0=KCmd{_j zX1o_=nyP-orUU{zbTvI5D2ebe$8k?UUiIhyw1(p@$&bFkqB=hW!j-{s9e8ajhFFH! zhIE`(E^^4wug8Z@RFmL$30qR`9z`LDDa0Q59H*98ceFWVUHV*(=m%!pk+&weln=?M zA^^W<O!yb4FWy6{AU!B2vgvq6p=ic%Z8F7-UDyuw_Z=QQK6Z1G7m(Al&@4vpUS;#^ z-_Mvc=*XHy^x^<zK%c#R3&nvO3Hp7Vm0#hlY$V<zGu4EcI7?=cd<;b&x5k}O3?j}k zXz&Yk{hNN!X;3mi`SZq#52W7To_pE1;i*q0@3xDPU0zvA;Z})y1YS78aq+Pk0Qcp0 zaua0=9Ap!@>rb^gj9=$Q6()zhqa1s#H_Pbzpj;VT-G6?v$Wjeka)m|2h*!&G4d(5` zdo2A%@(w*#_N{DQ&u0gnefF@&5IGk1w`DUdwnRW6i2LmoXoZ6#nufN6u@;6QK~~5t zuMB{#xQ7QwWjPcEK?qGANJUA>B-dN?-hkYOz+c%FSOYiltz%>&TD#Lh)T1><8{JI$ z5u|Oo3uyYjX$BK&egZdfH$J&PkDfgrQUz%P_29{JFmr*0PQWH}bS2fBBy@ZF$+Kw@ ziuwZ1cK^-ob04M??gh5SO{v<->UHn9m)*c3c4R<F=gF#a$e!Pi^-<oT-U7!(kEm9T zungR}69Am=xPTYzzw`IbtN#9e*1=yHqBivf+&%3Zn2n#FGpAH2+}yA!{z}S7DI>$j zhKBn%S@vZ9|5s1)PRjbPMpHeGckwqylqtE~TuBIDanshVg|v>uy_^|Gzu_k~rfxJH zldY03u-e(g<`6@M$QfH=ke;FX`Jvv%_NQ98{shEKL6{Bu5eE3v{>zNX=&1yKuBDvL z@vPtkj$>wM1z^I>i!z_HxSV=N7F<b%L@WBdNePUpmcp$z>H&yo^ausOJ364>4bEk9 z2zIy@<aCRd4N^3O{RsFCPq{TtqMHVMkL|%X(O0nar95=mp$}%|9=`7$St|I^wpm@A z+G^aq`&3X@)A1Pe9%vjlJ!Jhj((O44wC|pm<Rx{~wxsP+H|!={rsD?60gh+fgvRL5 znX=-kz}7n|gsr8qST1khi1$gd;AWm^ck)a$`GoTHUmDaTRVND8I|FrnNeU`C%Q(tf zp~CJ(jMGaKAv*FU2=M~ni$y<QNlE~@lmvef`yVKHm+#Ugi!cWNBIZvA7HVdMR<>2S z6hjk@Mo1bAj;l?2H&6{(4#K8vuC^Ua0~SUR9#tpy{#U*?uq6c28XbzVhjj)ksl4ka zf>i%-?sWAP+=myHS1($s3Rs&gvSGOCCB@RP-F2w1FO~ZFo@6}gH2t&>T)gtJ7keeJ z*Uw`{rL!rflo<w9AP$P-w=$^UEH--eblp~!`ug$OzboCFO7|xm6RiYFmJQf&M6Os# z{V|MV=RIg}WP&tMDXi*io<4dL6328yxs<c`Uyj~4&^qYIiXo<W)W0muT2WucizY>V z!;LDDCp=qlZ11`H$-8Sf0s9?0Zq<a^A)8RP<>Do(kFVb19Be;(h*|*3>uTt0)xj<; zInE%w$RGdnHyO`>Q-_B4*l8U@%#r7z?B&6cey}eu6wBq|F!I_TuH+b7=UTd}4n^dW zk7Qhqyj1t*8GZyVi-76fW;I7U$wc(EPMsyUhxQ&HR-pXc!r*4gPh9p&i~Eet>9e!= zM`xymYCVb+M_vU>%G|XORHaV(u*Tr2p!W9DN(_V=%WKRXT3Y02-bV^bL{RkrfC3iS zC8&NGtHeSGA{dd3N86FGydEmMv6H^Qek190vNx9<NvI6Cf^A-3a3UmUdbxN6MW4}d zOo&bhF1xp$iO*0|k1A@GE-FW=YW(rp)HA;eTEDHY5s9tY(}Rl^Y}78)^HwZahn-g3 zbkKd=h57ws7;FabENl-kO)2-<Z@cBL!xRK&VNO;geG^IU(xb8NWO9CfTx>Yq$;!%I z$_aHK5;HR+LVcZ>ds5C^^&V|)ln`Zxdx8nAUuPT+wX)g+PPI1+4rhkvFv77G)rxEu zD`+iK18PyloMHxeOkGCNED8eyndMivq8arpo}^Nu{doCY4RR_y$YgX18=6cuphS$d zwK2gIjJCF+Y{-fW3WU9~2@BRwFZN77X@p;g*;8g07G_1W3cpY|t9pnvA@e-8Ou=(; z;SP)6?U4?7(c4`ID(esQ;n8>(G`(t1Bd7^MPxYZ7)=i?4#Q=@zs2WlQpwe7NTMAp! zaen4P?~J^fqh+TPA9VfT7TvH!NlVjkK>fsTZ{2tm^)#(=Qk&AIfL3)y3xK>iSr|bz z-4^hhej`LH$yf00+YZloH>ycJdNCizUiaqDXR+_8>xCMHy*#_+CRYdn^V@n;XCnI1 z?4OqPlyiBIDaz~Q3q8a7?&lNSMQg_SAD6kxluCmq-G6J@!T;l*E{{Z$GhDhG&QIg* zogFtg9tOi4=^dzS<2>;n*V&NHF|53)b!03QNJL`{2hj^Olq@C^OzY@Gs4bn!<g)#a z)8C&-_YY+f4*>)~M1cyudO#r4T(7}kI)#jPz(?{<T*sK#h7liRH8S)vW@2gFt{~uf zf~y`9<#JnuZd4`hnasEajRTIO&9)?D_zC|+{)vc+bT&3K5^w{s8UY-XB~&61$_U%J z+7@i@8d1h7V8%K|=3*97OqiP}Bw*^M8V*(B7fm15)#$lg<~k@KGoU<(X+rvYiu%@* zK4zpxeAgN0n^*=7&scv_QC9hMHe&N?5{%S*nsf{9O^7Pf4ep(RcyJm8nAKVLqBNGS z>Cv+gotf6TSEc0p+y~u<#C{bWNmFfS_|LeXyI&*>*qWU^C^(K*9(tJrkv~&R%r^S4 z&%na`bsoNj1kLWoln#zTRXcWf4+0>>TTqsghS5dzwUYK$_kAe<%Lqm3@LJ44h1bjm zP$U?H7UOp`MPaxNuSUGi9k<@V^Fj`ce8kIv6NoEk863T0!Qh?WwPc%2ChzhJnpTv5 zJjD7+QAi=r3u#Ny?ns*N_%J<~L6EZB)b@(Hah)9{@|Xjgh%UBHMIWc*ZZsF#MU&YO zDhR`b0nN`t)*uYmRDi)17>D<6%qBWwjz4z^@^4zHywI!M^6_v$A!2Ho4>$GBv`*11 zkqJ_gkOsxFoZef+4pWnX@9%d|yQU@(){p|;9CQne*^*aFDo7V1Z?Pq){h`%<65BFG z>1J@al;t@v1o7Tq4qbh-B&6p&7%n>Q$S7ZR2hK8<{k{t&WY7zJQZdb9i6JvQ-bl^g zU6dACeCuZfhC5_-SrvpK^{VaN+y(53ZebX;UCL74Adx<>Qe`8Rzlo^h0R86%_<n}t zmDiiY@iv8?(sHW|oPsk!`-ZIRX~`y&b#n5nU&Pn&%`trvQ>e5pJc;QGv51*_Y+o^H z(YuiArc(3Ns;>eq#Kl@<c-66})&O{+0O;GSGCZ>V@4J1qvI`F!EH)Ce;c)y?vJT~G zfbg%2LMhAiRS@--j$)%{qPU2)imEIStT9|sS0mwWq=D@4Sj@rzYzSvtLy}5W9rV@L zt~c`l_JC(;IJo6BTPD_%D&Arl7Xh$wj%tc5EnX~wzszWrv06Q5D)p6u*8AqKS!_g< z_y#fU5MtVAvV|Z(<k-MgovMok5Fs|RBMYLW+n3Nr!F1y#kDm-nzOMkUmOFBetXm5N zViI0HB%9D~+?{UVmZvx9RTQKv=l<?$+*x-xt#ch0O`mf2yP+e)oD^-_e=mH4bJcku zyG1@3VY4vnhlT396=XMu1vVN4#0Bw^m7<0GZJchkq+n-^oIRZcEbF8V2;QM!;!J0T zO5k*8<U+on6rx_oETo!wnx^i;0U!Wn^)~Q+q`D<_`$kn80C@AS9|Q3A@{c|t{1-Jv zB>*%+0toPr28D@Pz-){`rQcl8yCk0(!1-#y;4fp($rm^RkX@ZfHngNri<+=M<`XGz zQ$XT#%qj`d8?too&<J&!l?R*;MbifQ4`cwdD&QD<mRVM5g{js8kBmQp*8!e<_tx`A z+YfIrpnk<+q{(qGdX-3g4B#yX5+vzsMlG_WIsh<r!1`1LsFz}3q)&~5Inh#_2*F}> z21!X(j<jfENJ<&tJrX2~^&Q;c*A$F{AIwM~e^eqiklmKFWtX5HkJ{MkfOl9&Dc@=W z)KO#Hu@zu#K<*#~LKh!Nc*i!xc@HH%pe-W-pq<rE4Gc+Ss63KfW{G%M;D8uAOXCOw zoQJuVBLtSrysHQKm4>*Wu&owamMJC!JUHIs48TXry4?C_`+LwJK=2Wro|Um}%=4ZC z)_YFg#D*M5a1h&D?zcd-J9LtOGitk+5x}!pQNnr9lcm85Nv`jg*l5rrFANAYR_Qy8 z;mq4mE8P~??2(p%XctNni5}lz;)n!db7s0n0>_Z{sO7+bT8mYqKCbi<v8ENZGUhRN zBuLT9HEVYg8n^s?mRpfU>?Syghlr)b!vwuEi~0f|x7tm~o|OT<GY$1)Qp*4o$U>}l z>PK!509+zC7&-PkI(biRRZ8sh0ScmO0bB;99YGGyj-;r=j$&iLj;3kVj^W@hJC<g| zGZopVd9HLJWS_m8Tu#}0Ksj&kL&`}9aus*^AsH^Rk09ipeGIYl_6bm)*rzDhHL@9U z`2dC)n&WaNO;G7<Y}qU#MQ8}g=w4a6qq&U+HsXw_4?o@^?vZb)8jCq|5l>}ew611O z7i%fiWK%RR!8IA5k#SZB%^1To4-MFU>oD<<<n*+8X>mDw)i!9Hxpu|F`fdB&9Xqn; ze%tXC+4vYm=S-T(?a;>V5=-|)V!VBE)P{rP_s&ch)}YvRC*>K(DQa}jyGBWAE<ki5 zvt)n}&QVF^{9!IBOMf9a#2^DS*O|dJZo8oU^Nxy1c^RjNjLevk?lj~}1{riY@hZ;@ PN*On8jr6Ymp9ui~09&#P diff --git a/.next/static/media/d6b16ce4a6175f26-s.woff2 b/.next/static/media/d6b16ce4a6175f26-s.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..725ee6b6507caeede49fe3032fa4e47095d42801 GIT binary patch literal 80044 zcmV)RK(oJhPew8T0RR910XVDx5&!@I0?Gsc0XRJX0RR9100000000000000000000 z0000Qh$kC?wq_iJIzLEOK~j@(24Fu^R6$gMH~@=GFKiJA3WJ4Yg3MhDj8FhDg}GP( zHUcCAnH&Tl1%+G(zd&2|rE&zb!{iHfGj_&SZMAy@@NfAIRIklVe$aE9j)uglWl_Pl zY0<k|O0rfE!OH*t|9g^2jBT5BxBdS=0EnupMp{-03{of#6)BfmGHTAXwNkoL`ZBa} z$}-IZhXJX^c1|)a(FJ5jaRV?Dg{qVYVMr{Ywn1wl0SV9m8jQ9-9OHCWvuDV3k#<SA zEIF1Vn*`L=wW}LL^=j{TL{>E8+7ANxm{LhDzFveW&XUe~CkM4ZjEnwE5o*9J?k*!$ zH%$_h>&1S&-{&UzY|<p&%PQr>M&Ze+xeM12(xAX}m=5h2Rd@w@^<{2hoGE<s=LRsp z-{ktxw4U<PuAyOfn;k#KPoaFo&oSwkU+VCSwW-4(E-sIU<e^Uz&#x|SGb<aryG(+V zTBw)#Lhj}<t;jhqLsIFKx|>Sr+ahU^w8)MB9<^2-5wQ*R|1<#;Fp)Pt%3L(XtG9N$ z|8Gr{zg3+OSbwKc`fT(H#*eDf8xH}t>j%V`NcC)m<S<Y8|L@zI?sKcVs=D7343U9k z0FWI|8-NsICHy%QV1;c~SZ1EE&03CuVKSrFcZlY8_xs;|0Sp*9qGQ0Ql1L>b+G@I_ za?m1CHbx_2G%6)Vp`wC0M9tYi2G}Gk65K?LYs83(ikh>W%~@I@`EBoee;MfW{Ps_u z-~L?9*;G>-<45TlF%p7g0~@lC0hVQUW_WmS|EJ6+l$D9HN|y?KkZ)RT80NcSZ2n{O zUp5TG%-FDezw?Rtl*K|(6y>*SMY!c<w^S<kwp%LQbn9LJKk2l;Z|2QtB%Z`bjHHn? zh(QP}!&n|bHe(QYQ~<eShqxWG>uegy*2ZShh?LIR?=79}{(qZK4!<YerKPh8?$}El zg(bFZ3tPY-==r$V+kZFBv2^2Q0Vk3L5^$gyGzkP@^iRLv|G%T>x^Uj#HsDCu2o+7B z5rkyrQAS0jA{<b8lo2-j&Og0d{=Ff5)U2XqyPPfEr7hdz+rw!+E$#F5n*dt3Yg_yK zdwM*3?B9N$r_b|F2$5yo=w@Bih!G=3h!AjqfCG+U2tycP2tydckPKl+1{lH+COBY# z0Ve33>o;Ku3#?>Iw{%;gu5`sc8tGb7h-IZ)8gQ+77-`x|X<AnZG?oA<q%_dw+t}m0 zTwh+rJL+*A^cc(Ya-B@gd9fFrsIg`=*1W!`u|~|*v_>0y5%wU$mcj%7>DHgwilt-6 z4p>^mEQHYR+_^I;3}Fl*1PmcSh!G=<7%@VGW$~3#ze?k^-nW$EbKu`svlkBlDQdCD z{>!!}IepqTB{`a+ZKLbcV>)|JF<@>D7!W}iC5Rw`NYvB>H3(O6ltg5mAQ(3*Zg<u# zmxuLIcP6FY#UHn~_d4z#*OA%jb)?6g?W9b$^+w~<t19gh1{bKA5C|DDsD_X!8_}q# zHVA>5sL5p!P-0^fE>K%1{b_|-<f9E-D{Pvld5^~<c_feI6L}<$)R8<<C-Eemq?1HR zC+Q@e<g<KL8HaYx4sA0w<FGcHu@2`FDH{+O5$^g60!<=s9t3Eiw166%+e6*_X4Xgv zYGnT3HhZSyna6Z|ma()&OO@JGqoR$P(o`cx2^b+lga83T2=NjE1PBly#DJZ*Y-`Va zy=7UJ+atbuvXx)$*Q{!4ir1Oq1+$4^f(RlrL%>_-1rxlWQZq#HKonC1GeOHl5kUkI z%qEH{qL?6xDQ`h^qKG1jSVbl}t(c&8rikJNQM}X?(|W-KQB2W-`R4h5_UrZB7nCJb zh>nN;WCDl<1Ql6bjY?E@RhNYVzMJ?bUG;sO%#@0{duACOx0~P2f@!R$TdMuY9y<mR zdkorlzkh+KkX{NjZ9feVjGjU{IW=Y36B&VOM!Yllp04uM5Dj1eyZ5*~APbyubx&>p z4e_tVH8Q!n_6hWWQ2{0G1JX5G%_!`#>5qjQs&GKK0|u~QPrw#|g#SWXTT|Hklcf>H zm*R(x<3D~5NDmA*GsxbRkTCHoF}436b=KeaBw02!g>9u@J;|~mOlM2a&M&P!S;7cn zK!5`dalj!CIN&e}F@z993>a`anPnypVG~l?4m+QnFrBk8{@2pogk4#<8Xq88S()c6 zRMq_gsQ|#H0i-?P&4upxhiQiAKlj!0@@H8WgxoY1JQ`sTKACO`VFgw9K!j^pxJ=IE zu7HY_tW64t4?yy*;Mts_s=EI%aD4+Weedj_L@yPU1Q0Qt)X79k=)z)2#mTw<@29g* zGG!yp81J}guPPlov<M$CGo!}NcG>;i0at)j5d`Xc--K<2-k}mA{~=ix&r|Mg8&dyp zP17F<H>KwY6tK~pru{6r?*7yA_xftULII$01W^MABim%O_);2bb_Cp5IA){JJ28Mv zIMId)28yTKe@kci8QP8FQ%8bwSef+QyY!_s*}F&b5E7-DG5oL2s?E$Sb5Y$j9YKZF zRh9I=EZLG3+acJ=W+<>Qyvr9&oOupR4hh-{u;}aizq!%^vc8g#$E?c6H8aV7yICjz z8M%LF0-fXlQJLxr=MPvFePxA`rN}1J*MWp!UpQBa+PqM8773B;c-YyZz&LykBpwg{ zzxJ;-XLjI0=!PY!tQhkGDAoV>e?DtMGzqJuK$0g&s$@)rD+pO3O=Wfee^ae5eHT>) z7S)sn6k9XUSZI0-^z{wZy}L0*={sYyJqLINkf?en5(Ee}fFd+Sken_6O?3ev)F4Xe zW&xC%BH2!AKW*H2*WVRTVmCyH-6SEj<G6PJ`)FPEopa&ZaDNbPy4i*sgc~KBZM0Ej zY!Ggqc&nDpPIuq`&pc^CQ3yjJgbQ(Nj#`$O%4hdNGPGu9cT1R*C9-gg#-f`b?g7E3 zxG5ij0@?zgD(6xnRt#WtoksMkPQsIr@BcUTjoP{%yQfL1Mdzgg9t9a*7=)#fCduff zHKmlcyY!2VcRLd_fQuLNg)dy?i^o%yQ!<JH;+v7XZ2!McIXm~l&@dkO??nFl=U#8K zbU%%VQKO<es-D`<U;X#$<ZVk!6C`9rBuEHBoDigOf+Hb_G$M|8m-T;^%}=dY{odp{ zHs=&9SWLlU0?-Hp&<Gt75Dl&Hsfg=y1^lkb>5KWxcv6h{7OBEDMufz1KFrMJ*dF(G z-Qx24|C!V8gJ{OQe{DYJoYY#Y1d$~oA}SI@LJ$$j0}%-^sU1WSYVEt{!bhk@7&%-L zhJ5up>u)5d%kJX#aV|Eoi46%yf=Ol#j({vM3J7UN64EdTX(Y?M+pjeA+xiUHjHi3J zD}q6YU=*}HWQcKZz2Ex?0(_m09UDR@mk~rTp++Qek||J1n{HNYVzbMQM}7j^D!LeP zCE3<~2Rkgad_{3|)~&Y@W1VxMYi@MYtzLQE8}It;3nkw%@*l2<kcbQg2oWZVNt`5U zGUO;xp-P<*6DG_!afP!<fM6j)kwl1<D9s_6j^N0UAzOhWr7F~E)P`fos2iqDn{mej zk36+(#aC<AvOZWNAWY(uBt0c6Q>8IO#xrI%YtD1$HcuYI2^&S!BE>IG;^L)@zIn@! zV1+AGy3(y$RnTfyt8vZR)`qhVhoP%0Xafq`xPo@Gg5TL)zrXwbc#nN<bN*tg{wn+* zL6n~rMEN;Elz)^#==Q%XEaV)(<^ab6>H<;$eFOm(69d372v`q5AmfK)r;lHD-Ayb1 zwMduQYQ5Rz`zKU|o?CA)Ew=kPNdXnW05m?>q~1BzVVtN}^=tibzy#rt3DeO&8jkCD zNL1zv35&3afTWV`NuLzRK1D6Mi<y*1Lz>e;IzijCOLyol-J@k@x2!Wh(_;o~C7a3W ztj)S?hwZTvJLKXO&tLcS=Dg2e<po~k6^SyN4I`*<HzQ};B8ViaxF_C}MWrE;v?c9H zcNI~Q)VwtkA>%g~NRM=p$K>aO;97<1HKFyJ*tBhf!q6o$$IQud+#I}=SP~2iHbNWO zUWEXrLx4bMuRC(V`!4y&H7qbb2`OuVXdy|`cn$TeV*a}4h{_`hL1&TJg_BHYVZ zT*l-&lG|W+7kKwGewg*+NBwC?o(A)EtSKPDzyNgivZ$k%>4KWBLqh-z@*<~TuqhWP zb(&ruE`I6z>UFqC=?|a2aUGgh5WQ-U08)M%WH8t|xYRjm@yiSJ!hOxr^B-=v0e)oc z@2p=eqXXz8)o@$3$p{tS5uPX{0@ul-Chb{})x??isy~>LtF6io>SM}ZJk*@QqK<95 zrLHz|c^^Aqm83NDM(v0c8NVBc_6_*HGrCjzFLbHB>O%#0*CX=*8i98BDUvD{n)qPE z=~&y-Sjk=P-kh7-D>V9iF}sI7#IiLlscVRp{I;M0Ry6n+CfobmQ?_@xgm+X4M;lNm z9BDi4?P?t%Q(M}0yWFu!Ka)*mj#~UL3l@}Sf-rAOvqNwFEdU6B#Lg-wceB7$SzOs4 z-_0L3IWuOpi|5XmTcoR-)=GOplhGGLjw4|>kQs)qkplkx2A4s{jv7ylg*}VoTSwRi zGEKSXV1XOkv-u`;pAFcT|0Tl6L;$yjblFdVsB%o4+$H=!Ou{@Pn2eE}el1WtvMU?a z9%>6r`$Oz5{~vv=Il}?CBD+i25lm)FYbN0Pn`C?7iG~^zvqx;(RKn$R^T@Zeg}6v` zb0pMCqmSv!^hIMX(pbm1@vLVZ=^gznehj={DSqxX_pHG*vu<o3>RVY~H?0U&enlj< z{ujSL1TQv{UOu8C&6ke!ZVhHBLeb~J{kWr8J_Lgi&Dn!n{J7cfWV>*u!wgr<cnCHl zZt)^(%;UEABLu8dU(eMIa6^mn<>IY`_(vi4)@!7pt1<lhN2w{)Jo&*Sur@aYLfEgs zdfvoGRlh)*e5Ci!wPVdg*nZ$iwulh~qv4LiLuXZwne8qkqg$6#zDuQFSNMH2-Dl0y z=F4=UoFkJTeb~MhbEg`bDSIyQPz$B~FPku1M}PoL6w24uO&Oy@aiItsGtztswjXE- z+uu0aXs|W+82mOOxaN*Kw;GuQG@P+<^P03PZ!*j0`F>o{DMwASldIxs^X6M;_O7=` z5l2h<0VZi%+B-R-&WE+xab6bNzS0O@(e7dQ?8DMWw09z*y89a}X|5gPo&C@juJpgH zEYGVYN37A?PuaOs=eUAz8^2ukgf6W<(}Vgg4PNhp&4AU0a|MrpJ+ZoWxQCtuWEzt3 zQ4eikD+8Jz^R7}4jtsLw9)Hixf0~t+)Oq7XRGJ_s3&e^v+J2^e!IPnR+s-J;7%MK3 z+6j|+RJ-l%PS6gcljctI|ApAhb}ekK8!k247;QC+PJ%4o^Td6?jNUmKbIF`%SO8nM z7W|>Jb3cR4A7SG!lJAXu#AFqc`UrG1#u0M7F8tG%E;X^+zbe_S8@W1Squ=I+Gxk&i z?2fKfcaAQXdvrhc3R$ZA&HWgz5{&2RrwypaKHY;^<HdL{oQL!Z2fsC+=&~j%W|j!g zp*H!NfL0g;?Dzo){>p3VN&x%>Ms#T=LxnL@Y%cr-3K1*89wo{(=rUl?bvK=K+MGp8 zR(-YRrw!-Tzpn?t9kp?2)MRLKDXK4O8*4uYIEoR*oCXOCYiw}D6(53#C6zR?$fbf7 zu$4Y8ah2QL;TbaC@RoPHj}NDZeDmYeYWd76-&o@ZKVuzpHuxQXB<Jt&FO&9Iy(j$A zNIq=fZEL@`tZjzMd&J*N0YvImQ!S>ib3|+st5qLO>RG#EaL(?t*=5{#WAaY^g(<w0 znx6$l=+9}!z}~*Y!1@g50=LNg1OqoV*|1_`aT^^_4Ko#aaW3-&#mRYx&*D<m`cm9| z5o4NPLUlD9*}DL&$L!&HU)<-qV}Zbqa-h5Rm@0<z?AKR)rTRd&*S1*RrH;X-$sp~s z-)8xHT0X5hN9CeDYyWi{bS-a#YCeYj28<eO&R5zY<3^)mO!^HNHP)P;CNK0f50fK~ z#<4mSqZOS+@<o?v1>1{{1#7V5r1XgMfuZGNQr2+vzB{A4w}IwlrkaHL1=km@MD#|d zgK=3)8XHF4IvsoK^b0GX)GDygd0av%zlU1cs~&*n(`$!KA3p51B}2L-iHOoIPKo$* zTqs%D0#RFu&aJR3>foK4(AP_9o8xY|t@O|Qytah90=O_wy$**QcEnM~9CzY4`Jyg- zt&AEqYSgGvqehJyeY%Vp`!TvFj2Scbn127i`e6<^?1-a|IqpQ~jFZ#MNT<j^Cv9vG zo#p;m7v?%_Z;kZ04tgQvkJ$kmbkYATpR@3Iq3<pGkptYQv7h=pi_X)W?SbnDuB)r7 zAGp4v{;)ZH@%CxW$C+9?Fm|e&o#H)q;KHV++CwUpN~KaCzDDZCoU<j9$z(E_On&Gp zs|b9j1BfZ)Dk_VD$W7d4m9|lP3~l%9BF(=`%U5YY{qnTU55e{{1L$wvg<f=(K=i<t z2l>A#jM~E8qjmR)*`B`tkMq2KPxm`I6IoHn&3y02qPy2EYuY<O(;;OX*~zjC*3%^< zBh@Z9I&i1XrgIeCAi5c#J+9UcjGgM5U9&i$=|-k|`ZM10tG2v`&exek4m;wgV~#r! zCm(H%pQA1)+p0#I>2`a(uJ?JX?B=X`+TI<Ajg2i}+N%uaNEC*n;4TO#%TGPtqHgfj zw%&fV(C*>8Rv+2V4Hz_PtT}%H++F8BIPN2PSKDj;dd{8!o))_9?-(CMqg!r_?&e<p zUp(mJ$PKUZw5fGg>1D@<aVTCp6u=~?xH`PRCeu^Klen8%;)CE_JfznO@I3Zt053HR zoWB{YLZ}b%amU&(#_EZ74dJqn714EsAwsc!Y!@4rK_NMQLrPANF+>e@bZ*gI!T>|q zjccVzjM8t&4FC55m+n~=K}rxy%k(9SbVSsr7)l?P=|5qP3?nH@)EF|y#ccR6cf2(@ zg0oBuX#^N<XyHEW+sKQ(OmYf1vId;<1xXkmLywPhI`sqKYb<b*)9JEoNCsLI<R`o? z`XH=8PPe6E%%HHSh_4mTs&i6)M4EWCU96cu?<gh#&B!R8WI*m9-6gUN3xpw#K3*|* zRQ|~td@u1MqqB({$sDgnwfWOg2Cxr~@SMv+vBlHz0_E_xkBVHZ#P%pfk0X7<hh<C0 z!l;@Rmo%j%xr+}ex~IqWHer!8YP$|VtlWcI4h<-!8Rd0zK6gtW*B=^I!I#FK%zen| zs*iOvK@#ryUOJvGrl!8y<_S-}nqUQ0ExeG>I$|<oot-S>P1zg8r4om3gZ;ZKzhsS9 zDS*9AD{;ek5NF!go$ZaG>c9QUBbCeG9kAE$L3GEH0002+^w^=Ky)m#*FrSG**PkXK zRN`=4eyK7fe9z5H2=1h~(w*X5NecgwR6_AjWy=Z@y+9@^fh&}vB&*aqy884RFld_T zW|(QVIpwo|r1@O`7U*~F^d>!b9MBtPXa;{{-+4pUB!H68`^!9+n)AjM6iQK&Rcakw zefkX;G|hA~%rwhvbIdi*d<*6u*%VAxO|kSYRZ25T^FmsHB^E2zVRLmA*xLD7>r=On zXWzIkKe9eGvOYB+aYjl-PKh!VJE&5lZl_%|K<&1NCKxSyY16UKe!2^{wu3jWikTop zh#~+0E8|E2|BJ7k38)ync2@SZXN?~G(r}Am7Ok{v+>#K5P%8du-wV#9EqcYgP+}46 z&B@tu;rsUiHPu#R7rI$&tkMpJipw3X#a*2Rv|yBaV*HOJn<P!CvsC6Eb%h%BuF|C6 zb%u<a-QDY6iEYunTiGV{dTXzJ_$jkB9l?dc0{TA%7AZl6W$JLlMoomZXd|jq7jZoi zNn@mxvG7@ziw{{_O4wK=JbjCQ5Q2Ei{7G8QWTzx|>N_hwv{661if~TSF;D57k92Lb zbT549GI8L_c13!&M?|ZUW2=*ab;$8`Cxc`$gg<T!Z>7ly+8EuR$k^e(W4zQvypSF3 zthV513oWv-O>Am2o7=*cwz6*kV&YN81?g>_g>cS!NGNDHUcC9h^W}$tC<sZIa1mm~ zp}HU*O@c&87?Pz(#grx;OC~msY&p1ia^=Z)QGrffx?Ryj<f>kM#IET#&^SRiIC8*2 zhXe^0A`}@#gh)}M#fX)PD_5R;d>0icR-#my3YDr<t5K^?{e|O*D;@<5diQ4q$TI}w zjx$~Gz|?@u!(GOrJzHh(Kxb*myB>A$tZ=Hq9*uUp1oQU=^HcuC692QQ-8NUj$TLTt z>FQGB0RR910000c0RV6)000000001(1ONa400000z$<pRJseB|0001h1Jyob5OyWS z4QxqSae*vUm}Ze#F>|xn!7}1nGtwu={LLZ;F|RWKz#z6b(w}qcMVXs}Q0wYM+HBAw zrGwds8LfHA1;}*^L2eC62ObD6+<_)ln_>E^I-e7cf0Z^hreR+Ev-@^n?gh6s50#ie z!NMhEvMs;;%HwF6s(GsVjF~Z860N1ABeUqe_2$=Y0B)uQhw95@G(_2Cgm*-9=(iH! z=+#&z>anr&#a(WAcXfj7@gsI>GFdMsrEE9oK$MqzD!OI0DzOzk(`>w4nnXU=g?X9t zxcpoZz46t5OIy6tYXJGg;w;5$QACo860)l(BYTPp(pbnyccCByg^JuSG-Rc4AsZXH z3H;v}4?u{nO+-WxAz)zzzp#lOdrre7G$<H+OToCZxe!-E3oj8xp4#g3FhmcW963w5 zdXrwB|HA_lc2SvXDlR0g(FtP^*(;Or95TWs&=gwxj*D49)u<s+Ke-{3syY;i33)(B zC)Cg3O-y0JBZ&sTi%&o@di=Jn%5ZbLq@M4T682Py+grh3`=m#A04vhmh==^rq^E&A zOMWO=tBLqX3}vY-bjs&ReBKzUCe2}b)`L)So(G}vuq(RmXN78%Aq+VP)t#jf-BqX_ zRG9CadSbbnHr7Z$Vi=<^UdEdx5)Ia1=wZazF|I6O_e^jLm&9Y(VU*-C0)q@P$zf8& z&=l?WBIZmm$jn*j@&lll=$U+iDX?wL2+!4xYlamCa?YQBfuay&g;?4OF$T=UkM<?h zem1G(^PU<n$QtA5Y`mT8F4|PVo3KqXxA=+7OfSQjZ#l(R6j<^g14(Q^D}(_-Do9sO z31K1!@zIo0q(6)cSzOWarsEXH3vALne&^;GcL?cMLKQ0P6vFu!Uo;^FDsYq9PK}yK zlUhoPs{O!o>NS?4#t{+@RSG`CXUgL<7@K6x;5HaJSD~|~@Mu1U>M<D95Q?hNuTnA= zQy|7Yb1%LP9z8@sJyLugr(kNqGs2fqoW3ikABxk@l<oI{0x!@sgAOK`rqEaKe4;Uf z=&?3wGkIt_v-rk5;wCfW8VM>!e;FSCM2wPP%0YuDRCBe(%0wB;$e*Vi_m>dD)NdOg z?t4@iwLDL;q9iY{&O!(^7a(q&fXCdRB(Zl|$IUJ-ECo*H+$e=PvlJc|2TPcJ%Wf5D z%sqsn0(+BMbGXE&uv6?EimgBE^qC2pCzW&iUQ*2boKUrtf9K<hU-xoMK4gw7e%Xns zCJ%O*eZkNBITC&r<c9a1>;&}(L_^+J>O-*lpf;`dUFgUIt(md6>3&stE1gAo#y5Le zf5AWZbBwNU6ZB1at0$M~b*k2t6kv_2u}I$Up2HwHNp<fW5UQhyJ-2Jft7?Sf73_KB zN4K|Rn?V%k?TT!a&7ox-F>r^bReGUX=y@nQ?_3&x*!Ml@bU(yAse+#+GPG2jxm4+i zH<P~icAkC5$Awr`d=#a|?3?_W>fnVQR^9E(R{4Nj=<tgm1SUaD9_CS?J?`Up1@9$B zy)<S$jF+Iyg7h1Jl;^!lF1+THgzHFc2HJ((R-6_xNom<a&WV7w%qo&&pw^5k>5z2` zjIM8YD=05NNX6?VOS%9zMYx%=4{s$3QA*e=rD3HmI;|r#<SBVV@lV_0h4?H@71v%M z!VJX=R0XS(R$Q*NBrRJN6fb#s_!th9Ea{^6D?P4N>k+u&8%tVM8fBpQd5~H@07S*G z6}greMyVJAtJ?c!`5qyk-EHqS%_)6yISy7RD`B#WOpqM+GUa9n)Pv}xMwNe&DuIy# z_H48u4g=i~9M#LCizX`7ufjnB;#rT~Ak^%XVB*R_Dwe|Ks%myg7ctP!(dJKs5dK~W z41nFn;pE2vHHUV*B?vUcOm!DEBe_H<AOtBUco$HQKrJGOkHijDoN+U3J4j0wMv78C zZ2$rk&@%>2n{2anv{rzK3V|b`MFt@@c*W+YMCXuL0S^O4aT9FNTPPD+reFdSIPR+e z;>!$BA^}dHAZuibsGP`%<Y5a@n{m;j4&f$T1f2Zn?qCr^!j}ce3Bu2u@YOq>$&zRk zD%fm?wZljxWe+awxJr~Do)ur(bZGD&0dnO3?;Pp_W+xW~44q7}&Z&F<;x;AIC@{h& zzj5A$eVrUFV#FI+<Q5<T5ZS@J%PCacBoj5FP#_RHBf-K$K5Op=EKb-ih{OHw0P<f! z)`C$Srj)bWPApkL<!KaV*QU16{|CJL1>VdDUP-0x_ceHIhMQ+jc;{CZYpZIgt?n?s z>p-KO4BK_8D@}(@-tBQO8vVikhY3u{5+uvO3FjAwy4Fnhd)j;}LCXsV0s$yRfz)r) zBHUMOVA|Ccssjot^-2g$Az#F{=@m75el1>7>vn1LRanLX7E4QXnXc0nx=PnLA&$uj zb0TS?4L~%)c2Rt7fPvp|FAVLJcGSGs5e<SB6*<(spr~6$hvE&)421JK)u=x=IbdV5 zq1{=oIKHm_UHo)+1&l(jEo?NI7R&KHa5*VYw!ClpykGS7FuU&XPzkkrY9vI`KSwc# zdw36*iQ$MyX@Nd1FltEu{rP`^_%1(+ae|ewr8o1I+PzW3b<AKE_ls(2u?h->6s3c; z2ANutq_sRIHu76)x5q1g%Km><`f{8VBtK;SW1^q3_$l$vLht7g{Q^9OGe$T@_$!j% z;QS8%bi&hFoQ`(}<1=y3!aW=RY@Bn6&cz&OHVz)g87CQ6KF;iqSbt{rXSRQq@Mp09 z!gvCIf@nhB39v4}zkta_gcm8ki1B53modH^<4TOHRK1GmCU!Srti)c)Y$g6mX)D3` z7s0=n-v-WISd(~@_>*LlL?vZ>KhFI`_v^*`5kC(0^UPm{^kp#LCc5t*#SP$tEsy$P z$KIEY=o|1SN?-tpSML|q?El|F%>Al~-MT^PHZ-vtV|q8<4DWDl-k-1&ceFw8L_2Zw ziQOd_cQfI;h0E>Wayzka7xvvs@4kg`-y(I7M(`dbb>AU;PZ<54Wa=I>;d@&BcOsXY zH2mKm4g9-bM)#7T|Ng1@JFU4}(e$lY$}Jn~PU+H(jec+9`EP3SF6{nIwU+2P@U)X% z=A^NoxaL$V{AspV*nVEu&zt!9sT?mb{rQ^S2>VZ{&Zs&AIYV}q;Ox}>Qo3Ji;g=|W zIma&(yxq?EB1a4zA^UIC_AZfM1^ZR8-ecxHwfq{E3)n8G@R!x}SJd!6v5OLXfa?QQ z{r93>f^`YaC485dyF{@psqd0(e@)a8h&%$-TvqHOVpoV<QO$4Q`3*8xskw^lDv_%q zj|Q@9?EEHE*YR9u>9@#;+k!@)wnfo=K=)@B#mzOUE8MEfwWddeV*wpl^p8)~(Z2F= zbk^yv9=){hO0t$}3g||MXW@bdJq5dLLbkPqe8_?j*_G4#7~hQZNVV0X9RaqWak7wx z&qZ^2p9flHeGV>^5po5Q<KB!Tq%GcrD;w9bFF-wyzB2AI_~eh63j|zKPz<V@D)QIo z-MBC!$FUDwIa+`ysozo2Qxny7azr~UDcV{Yv&(X*mdcqcZDnJq47D>#vh1N5pf{fp zDBDlE#8y;9A9zEg5+#!I&{JT{WKmNT3I{zh>V!_a#UGakU0hIHMDibMmWRHuvKI?B z{VG2nm{oRQ_SY!s6_n0-eDa!%&&nyMU37VX8K`}#M5t!a(aI~e%Jml`#GZN4&Oy57 zC5`}X{ftQO#uRx{!~`Lw4j`q-Q}@g>@!h@1sY=z=s;kP?s%mmoJ(dryRo5{Z20Ya7 z25r5nv}(t;sJ!7i7m&T943BI;DFVEM0Qzcdv{5u@T}in-D`aP&^8<Rfx<oysWf3*! zO#iSFX6XbDR1hDgA^3VOR~wXm95`G?07JBHMA(W~Bf~05*2^7E4<vi|Aj1eAc#krZ za0oOI<`xFZpc!KJO=rUeo;1BwLkrwysmt^QhMemBJ5PVB(5A9+)5XBu=(fvLJc+6g znw)3-hVQ5TrA8Scl_oKeph21VYn3lmj%KYSh$?VQrfgKmr`B~e_|drnRxGg{!=rAH zr^PwdGNh?cM1h5LO~&MU>BR_|3M37%kHgYNFLeR_m+uIVHg!@47QkB;9Ve&t*L$ja z<hiSdsjQw}ec=BhV6y8T)_K1M0sk_xPPE?)b3g#hwD{iGAmlsWDU>t~0KRdZC~43j zjHFV_D2KcYEup<-1_7XHMFym2%;;L@ENT#vCLyIByh-trdDiF|3+6v}k@6X9A1P_w zlWA#zY@pqLaj-^YrUK`kXgT@awPjMFaAVaaS{!(p*zp4iD1l6nJ<1=tm;C=hZ@3Ga zwOd<e6kj?q+~xTOogskRa)LK?0AVLMb^wX*!PTF{p<R3z+fT6bJLop?u4g{~;l&>x z_RQZVx8pwy3}0qhHZ8yLE@?Zv5A&qM9=`i@<Ew;X<<rA|-%A!fvdDlU-lWJSO+Fb4 z$x=+2=4z>=%RD_6>9foLD??T}z~{&}Cw@62<cX3Wa+}4sMPeb63YA>gv^i9??Be8Y zzHO@7uDTs+)}f-kic8f~n%>g&m8YX(W0e@M)I`0W*5_IM<{I;+ac`UOu1W8^;8*YY zy#X6djsR|t2xdnDcZP$zBZGURfOnJayJ_|VHk|;nCx}>XnP}oujk)6o1qw-$Ni(IX zqrP)l&DGUsGrrl6lhC#nRI*&fTiB;^b;qg5=z90LZZjL|oUd!xEo*(SKOODXP{elP z)=V7{F<#@EcYhC-vV^06JUa^ewzYlVY}yRRX+Q3|$~P2M6c8?@GLzjO6+9RXJRBEz zG;Z*CJkTkcXn;%HK#)*&d~!i7UVi0HRN>^Bc31jp(xRU$|NIvvkfA@4_!A;ryBl$f z3V6f=j96#PrU<D;Vpi!?N1g7N=M8w#lhJ!R-cI<?C4UZyfP+mU&JL(?C<H3R5R>S* zfC+Y0&Q$GeHO^IQs-LE%T&ExQ9d!a1U?fkveckkWriYur1H^iD=&>M*kzv8zMm*@R zX%N`>CW!3|S*p}_V;lQ5=ef^w9@2SlX)W{Iuu#E5Bn-E9CCZd;MU!TYx^UKQdOcg+ zR}Z)Dk!4Gsc)Y&#TiMOM+{~t}`#y{ycjPBNnHg?)X0zFo-P@DB*z=uT)#01dE**ZU z3fAe)o^Fl-V@3x<e*4K|PY>e=?2$0xD_Gu2SGb~;#EX##@kB|)B$*tgRA{A2J2g6~ z(@le3rff4~mpS_^IAqB&Hf(MJ@)DW1sC-1{At+xl1)~+{LJ9aKx>%BecB*Zcx^}B? zkA@Cv?T||y)>futWf>^j@p24S=X~`p)Zk)`F4gIFU1mG(WrOA$ve2-_PWsp>pE~Vx zXRP+FFTL+?hyCk_|G8}dJT|`O#^3WXdNF}sPO#UL=*=X1Ke;|kzK@gc(-itV#lDzI zUrn`j(}o}{3Wya5Vl8&t5T)th<HqA?H+6*DFx`HcUcXJhKW4Doi&(@iEM(COTfpKL zyco6%UgV<Ap#?2`p(BlQ^p5lbMx5XIZE+)vy7(Y~!4M#f$lzOuC2~Y#Jt)sb1CTdR z;%9_3ZnIgT%`pdKn1}amLD=zFgqv*bgpLgBxYxD3R6u6{5E+KPm3U~tUJh*W065?R znDYjpf9HLItk|yj>Ae7wL*ZEg{GiA|)(?bw@;+Gjgo)S@6A@BnsXD|MKq?00ZmiXY zLPhv!0t9G1JtP};A8kM_%P9#12dw?nKMMgwIT}_$hikZ-D<hUeG9#`*1eGgfewZXb zRE(Uvr_>y^_ghKJG!+a}iToCj1?~o?97Nd~x@0;P!hSHj(>+#wgwP{E>5#bQfJTSU zhpG=Ml5zI6`;gd$i8Fc};h~8~qm~qkTZutQ`alH-N+3amo`Vsh02@asPwG&K76eI3 zkYU+J31SFTd@F`N-TF?*3xT-_gkI}H0$kF!y@-&(K#3&4CgVQD_dYSEO`sC>!whp1 zj5j%p(B44-iVmy?A#m+`a1n+w{#^thk33kQaN;=r3Vh*v9Wv&aA%t<XU19Z=S~nZp z1riN+oHqLLB`@`*tG_2qp`{h$jWZ%J>br}?GH(jh`SRsm?`%(>#zf-Uc66gLjHB+W zd#!WNGE0>U7k8QWkG!%|60)3;2^_~T?We4)tAis|l<Zlv&&nx3zUIC~iEct`4s<a2 zZaRYgAIt)z`dX=Lk?e8`N#>LqhLC5UJsRIcLnjXj!3Pz?KzQw5``0h=F1mE|2LERl zJyv<l<h~a%;Y<id=fN2>97h;lKSZd0zwGyc-#sL=oZT>y;(lim#wasn=?nfVbds=} zdnv;V`(Bc->QJn2Mf>{;URj&)gyjQ^CF9J4Y2r;{cq6Kz6s+-6wq}sX_fadub|O-? zqfXr|_xmdA9e!5TlsgisUy;wujRYyO?fyo+JDtriq&M8Ip&Oo~``Cxz-VpYeA`ez9 z*T*SeZ~d#cya<Pq?;3EGuciFvgnMuq9xmdS;wFUJ?GLvwPGf6qBkK!~7ttlWaD>Em z^-E&mMyt|ID;#%Pwu-m6-_BQcjr!J=vyRL(O^?3zB((1_V}w;;U0nmQjg7x?NF$$a zJYR~xW@(PLnd_kht}L3;4@xW1Ryi^SdEo~xGr?BP1w%uvg@_nB&BV`T5lDlq9LVKO z-oy+-EV+ngsX(ycs_Iei=nKVGa;-36*aZWj83h2s_GR7KPmW>Jnw)4nYxXOXsUMp6 zdf|9ZOS3PtR_FM+V8?eFLVl}5pEv<e@7S%~>--|j3L8fGab5_)ylT|>@B_{VqLtcD zb1y3Vkj0i+=6PqEB*<V*Z*0akrDWnR%tU{SJDw@5&cyiC^p?a3+AD;QiZPH2Y_2R! z-vxdlVixe(LC@AV@u{sjc!<+2BM0V-dogCv*rVSfj2fS1?mEIe)hjW?F_e;q&A0y; z6&<$J$s+-W7U|pB$wxnHs!KFHt}{9uH5SEQNsyK>spoR!2EZf$U1E#1vC8#>YSLex zak(VAeRYA&5HM)J<h5m+OG1VmW!FNIe{!B~my<@LF$o2Mitxom;SBtR457S{$x3<_ z_X`uAjxBhh_?_UXgYA7r;d*m|=Fn^EDgJ_1v8p5^Rv!&1E1T8J&{6?y<H#NKRvI^t zG5MUWa-vWhJXjvUk<GIEMQ@=&oO`WaV5^F)mdU6splYz`kaG1$<(v#_k#Kt5#%3^d zQo>?PVcS*G2$>kCj}}8}%*58ebcQmmmkCd~lJ<86880mS^pw$RngSYL$#k}i=&%7q zI6`P+qQ*P+NCCADVt^^U#{&*YNV|+lmrUG3q?TZ_8?$;e%0(sao;(*K>U{A}SAt6& zYXrtXZkL|{hoi<dM#*)qngaRbB$G)XepXTxyUqk=p@ZmPxb<7`39U9z1PE=xHboU6 z5X^#zkUqFdJGvY`OX6Oapd&ThUMSHm(7+OP!)(_&4E*t`Vnz5bsJOSJyC9vV-CW%) zsQ_}!M6N+C7_FY3>EO(5l?~08OqBzE|A%;(pI_9l*?1SAqoK7dEnz$CM<cP<@e~Ev zn-0pL616QIxPjgi3qM24dN#!vtLOweL%%1XX<Qq$49C8BR(<d6n9@+InGmV)=73ha zU_!Rx+36h$Q$yJnefAVp+4sXM`_&*}V#_tmmHA4(@ofHRXs)ItBc<I-_vjgHrZg$T zV@6@&%O%~PsSep#`u$1Bac983pyDcdQ6K};Ho~)7p?+0Q$)d!ZPPu|~)2#~C5Yv8I zQ1r|$Xy?&mpvB^&PGY0Mf>ikRCN#3sHm$2>NsU-Q+DIc{vvrwn746+auRW#pM0(rW zJH%^XV5t>t{Vw_YKwlV3k!?fKPoA40+%5(T@ahwUASD^_<M9e2>PWX88@b-%s-btc zw=o<?BWeb)4+yIe*_pso4A8laLWb$<mjqYIka|>gFohy13%(BAZcrl;e?v!x#QSfa z#Ok(mc+~F*a2Ot`z2KI7$FNg?g!jJVfQ1fmW7Zpu7ww=o-aLoH3>vqx(Tn!rq)8y2 z1re}Afef7SZ=7{H<cYpb=INZ|Zf%RV(i;WT_O?nn2V_9E)r7s#YJ8`3l_LUYc&{4x zqYz8SeX-{AD244pN|?m!PmOqvEn79UR~`O*%Z-wo69nNm-RJvL3}um*hvGlYDOsZ~ ztu#cBH1rX5TZPU5JXlor&xu)edCeua9%*<HY{)^20c1Hpnm{AC0o|%GpiuafTIcmK z!<X~dp@@vM8mz8fgd+@P+9A+ii@}9p5uuKntSQB7zk;3+<Ve6CJ@o<a=3XP`1}WN5 zg<g1VB@E%9Ip~u%`qUtJZ!mVu%yYOM$dJm;1O#%`2e@~iukYP9x(PjPAcTULV)jkk zO)jIqEr*70a&!4x>cF*K3{XJr8kg>nfS`9=caCf78j+FLAgXFJS#N1D`|r?eueBa> zuu)%-@*`I0>Z+b*!+6WKUM&5Lt#+Mf#xQ$3)3A_6aem?73-|b&J2Ek>gGWz%$Z;y? z{yt0ERU5WhIuC5V9$A%rw|*w4d(_@)q@gW#sPE)#=mFvR^WBgU5JYf@*icL?T;Oa` zCIs(fVhJ*4&{zDvbB_%``u)QJqBXu6-(fI72!je)k}w!WLoQ?_ib*1iA;)-(;1l0j zn&Q`wPxaBUIyq9OC&x26=@wzM>moyYE-Tfs87jUmzmggq#R0YJEX6ysmpM&kyb2^1 zpkRuHn;f^%CDvfbsdm>2YEk<0Ic>wFvs8n^2jDlCanzAEnEVahV8pOT2bj6p*byd! z6PgW%P#m7lKZiqwi8q(~$RX1+-)sE@6f8Vxtkf$rqV2+>pqG#;+-wNvLzX*A(a2#= zWV>F<48N`~5~ly3637qy4s204TuKVw^N3ZFU1Ur#nL~Zc1|%ov6aHbSGNv@*S1_Z7 z$|pc^V<C<;e_939UQ0;a0T#&w6s?B{@Lf~N#^QO+&N8oScbj^%I1{}47)fgas6}cO zpC$!&7m`o$7y4)TXM<S5e($p+TD%gztSk$vF3C|qP3yFMw|mTb0hn2$=UHnLItx<V zv?PV~;%G~qYU(|1L(XeLKv|G0-gK{aJzEGFTRb)R2EBF_eg(vqzbANV5t}rtjR&)2 zAx4Z8={1kiZa+nkqm-_;uHrCVYqTSpEPyYmvlRe2JA>eQP1^C7mjHr2-$0lowT^Q9 zWwi`!`}<uFHyOOI#BhBAc<A2N%p*^qi=(c#ZM!53M$M78?{#)TRDG_+QNIid_+m|j z&7_eU=CYt@9b(whco?X5aTH!vKM$t9>retKn9CeV_HAzg%;<*VP>jqj&BL*K<I<#- zopQ6|lLk7yDz_~By&#ZBUG^BDhcHZmX_3ffCM*U}RxnhGgqc<n6dXfXN@oEZJS*6t zJ>pkJY^pU~!3_<%(GsA~_gEokAOdFzTXV!?A&CCi@gg3;M<x3Ulg@}O=`KeJON=OH zNDKLVlR$Xx+a?mXh-|7#^Ikv!uQ9IB6g9O#{p|R0enfos*tDq(!yQXKoN<z7&H}mC z4Jv654i;hx(%Dgls!MuRoxzNc`9F^t9Cp-(sP_ny)w+9Ipc=yHF|NJIr&hCMr1#{| zWL$Y%2YPUt7q0#XhJC_A-Uq294UAMzH{nFX)x$<pj7%bHggLm@L^ladzAB9^pwLD* zh+FXDE|-ng>HD<D;mxekO&+`brCIJk4|r$*K%p|;uCH>5VaXB7Rn=%2x;-E2%ncJ0 zyW)X?xMKSt2Q$SE<it6Mz6wq2SYr3`A|0k!m{8>-lsIp$tCSirYmnvAS~DHRPrb_L zi!(PE(oo1rCK8Iso_Vq<nYTmcd53pLt2x|(9Ydso%MyI!_ZqOdpI1GH3O8VD67yhy z*ZwSsQClT8qXtojhIMRBck2XR#E|BO$9$wc2omh*Y>hCDyTRHb7oG+xY*#G-lnaH! z`{8w~WD9piA1jwEL0sVsve#-gb*fDqqifb3u`$V4YW8s6RDmYXT{>R}JPLLoz;r#U zc$wys__MT7T6A0@JFq@ShzbrgCw=YhPyiRYD|VJdYff93d<6`LQ`+MSRJcN$ex&yf zFcj4K{?K1><8J9PoSwrxu;jLl5C_zv%BD{<EmF4=7FW<=-prE*6?AvfMU%a*z8+Od zs&y_a&jGqG;>AfHS^$zRzw^x9`MTDy%2O-260Ka9s8{a{aaR@HZ8RYvkB`{pBjbQE zSGPSBjE75ey&4H>X{zLTZ$CT=^<@^UPOo(OpZ&w%JIrJk_|?lb@N=NOT_#MuKR4Pm z#uZ&h#Fw5sM14L38urmc5s_p1F--qnlyOKAM=m3&MUU(Bsuw7t5o=LAB7>Z-i$a)` zb_r%jC2NnoUEB_(QM_H(>Y>W}Wkpl?;PCRcI3Q_3E-AZfDRVm&4)$nsdUCRVLWdSR zTe^tCar=3Ovjkh(_uqYrKY99$0y@luR0>QRNr?x~JOzrl^xx0khYbe+8-BkQmE^|v zWC1B01G-g|MfjP#m5vXV@K|H54K}4T)nmntV@t2q??#g$BF9t!6-dd*fL(v4JqJ0W zPGJTjIyr_RT}-uXh<TcJ0~J23?GT+#;Hj;n|7GwJhq3U}eB@)2u(NU2FBr%%YWKom zPp+sYMnfIg4&SH`3KMfTOvs(#ow6dmlZ%y#efRKbv)P*7lV>k9>4y2Yk)E6c^aHJq zjCf?VK;Uv#-NjYN0AhL)ivC4;!zfT^Exc!8OZ)#Map|ZaX~98mZxubNP#a{pH38=u zjS2^PpAJ+S*D-@F-a+!>Z`Kz;Wj2HfuAi^7*X_hTrGvk7tsFkVfeOF!m|<$*2xI=! z;qq6WfF!4;+GsO#lXx%aD&7kQRkIjDkfDcVYpBK;goy8b9HWAAJq@t2bJ*dU)He2; zsd;N07_JPtSgjC4t_!BPg`etX?S!!!M~sNwl3JM(ID>luW3l&c_5rtpWx;vYfQBB* z$jL3kW<>P&sxa*fvX1ZSB2I4*XVOQ8(fWik`G`PB0VYDj+_D&H?(LwQo?sb*jU3k2 zwjD*I-#V!zBkq5#Zk4myhr10<0CIcpfdd-i@gYJlIS^RvIqDBQ@}W`;3P8VN&@_a2 z>8Ru(_b*?L_p52lmJB<yz-`&DIFG9`A0k%}tLQ{}yUy7JabkS)&jwnp2th-8{<6?v z`d8h50xe-nD~*4RRXQLOQ|8XWX4t=OQ<xKlZB7}Tj72~Nm{|oE>_<nG`dP??1~vX& zn!GhD4=%)Mx2l^J!`yTX-XWB9{uMwk!iWd9O{W|P>(m||tu2OV`&+Y!Ukd{rC~-r! z&g2A(8bE3{!SuTm0L~ekT#m`D_sq6Wj_F>zq>ajaj}Ep<)Ggp%?d!j|3u&55?xwX6 z)Vda+gvU;D`Vs^Jv9K%cus8p8S5;1mHbdXPO=NAs2<PmenlyiOaZ_F8rk5DmAFY6m z5X)i%l(Cpqz57)kWPp>b{u?;xk5=E>4Fv>#M(Xeho)rV~$@?y#d*l6DwZ3vioO`88 zv46!QI#QB=-h+&U;lKdg3_k1`lR=)9nsqR|*4yo^Sf;{@41c1mGMz~@o<ktkjTYQZ z)A=5_22QwpH<pMCbjR4bQ|lgMp`#<tCC<4D;q3G3NFV=}YO5|WE_p4~7x&h@#v#Ev z$^SkODhreX0LoNQl@o6tM>>GJXo9=#hZ}O#ZWOBLAkdNN)Eex%Jc=ZdkdCAPyk!9a zj>rJg&+;@7UJW@zfhzF5R8*w@&tGM}s{(`~n3D|(WP)M2Y!&1gR9em$v^&ToGLQv0 zkUrI_$p5E`7t~WjCTPQg6>q0zy=-eJ{H9*=<^8h!t8_F!Iz~JZo45H`N*^S|wovm& zMx~3OvcX^y=kBzZj&fh)(}Rbv$MYl*3?RL#zIx84Kpgc_L;Q$!<gF7U;tQ&(?8<># zk=`{}9kop>W>dGJ^7}Ip)W1=wcI)jWG@4x;AWpH1gO&f#`SqS0IAVteL+J*X?cI{s z3@sGJz%~E}sE2PW@cOp<M<*V^w?%c<=HA%2HY(lYF71uogf~|F^T~GmH?${q-`XZy z#dnbM?*Io?#$6i=lJlrH(t&>_mg)a_Tx^f|ck_`*yYclRppv^H5xz`8m3DS&rE@j( zHJR+2Ux*CW&RjJY0F?z(gk~NwOdtM-U{SNAfT0?4%1LF_aBTA+7&!Y2poXG)2TQg% z$doawz~<)T<g;~*m|jbU`ft~yuNhjT3<9$i^M1-GiK9n}ZLLVSd6ss=Xr%9gs_N<m zlaV`O^_m*ksGCN#OkMW>r^!s|2DEN#`4akT4)4=$=klpG9g<93xxuUioE*BOPNJuP z(AyL#bDUq)XNuw0b>x_GOOmSj=FewL*qd{$UWP8Kbhrv#1vpN)xzuqGQQg^!(Sc$V zTym<e`@{?N$MQN49>#qCV(I?<`K9;FP3B_PaieN*$SXosfU@(*V8fH8yA^-m->sNl z{ibQd&zDo{92QsY@7bHh$>40djJca^{Rx5PB;~{j?(mjm4a%;mGr_?UZaRz{@H#^t zvNPiEarbsk!rm}IGMJQss(LVZ`Y!OQO@dmcoJ|csl_%6OmSG>Y24paXA>jEC450o7 z9OGJd-SG;>i!qxBq7%_QV0VCS3dzViT1=%Sp8s@}si+8kYfE7iaEU@*{LpYHy$Er$ zPD4fGfCbhaeGM|o3ZER-D}C)UN*Hk5r#8x81#z#u%G@;~+tNMWD)}z;r>Q|f>0Jo- z-L0c@KH^4-`!ZVdvR$1kTP||X#`*Z$6;}qF>_?n*)OOS8gTx+{=42WCtkYk4<oflB zV`jad)@5rQGYJ9rGBN`0-jDAZ1j+`$D<yV*7d9Ql<8p;_Q;iSKaq=($N)OT3b=xX+ zJ6x%4*8I_Q#ZV{-4G`~Q1`ge)bnX+XP1GIY*6AHmm<0P~^;jz`l}Yfh0Q!c(?yjw_ z9sUCXy*}LAlab+`Z(1^IjfG9R46>7_$~r}Au1#_os`$qLsa;@462E31lV0*Fh}%hz zOvt*4jXUtu`7>I3>vsAUK(tIwn->j!MH|5Wd5}?T82GANI6a9dxdlYC+FPHspU&|I zRsnupBI(@DS3xD|^B8{3jwC?sy77NjkxcH|BvR`vOP(5JPq}!)X06>chh6jX;=}3n z4+wnLv>U4gYyu4TvFP01mbsemUUv!ueP##`)ee+b1M#F--6~%aJa#BtAG@4idz?J6 zI6Ii&QcTBY9F9`jcWtTmxZQ~!Z?@oak=<(!P{aW|-#|tHFF?@00zk$C$_DFzWB|Ts zSL*~jVeQU`maY2=bMX1g+W;bDmO7K%Wqf?SMQW5|ExFs!nGF8{`-ju%VAz0j&#r=T zpP$4;jDG%NAhYJ5NpDAOn=0<w2Ct{*TV~E$4aml@)+QOM+wsN8qJ}`kz_N1dwV4YM z3b`C0q$mWnlY|vOxyP?#bT6nIfcha7;Me{uJeaN%PX{cRWBnSK0=Q0sQVKxG3mg{o zP+bE<H0Vs_KA@n1Lf60u4Im95d;tFtcT@*x_$l<D`=<L_5J|s{eX@%eCEQa9JBgfe zK9H?vN&L-$Giq1IN}@Op`f;mpmnTTb-~b`Aooz=(2OX8@K{6r=R2hMSe1osuTfF`J z<sfs#-S%)4*3RkIj|~UDGsNhte$DxU`m6a;zbq=1XK(UY^}6r5*V`LwYsthjgk90H zU70ZObN!0H;|u3&cu~Tu!SknLcNXsM-Ge)MMrES4z5Vi7<x!uP*t3Na!N>Cq*YV#5 z<5K@OwDDn1J%N^R6C1WrG=3rcDrxBz1)c*---QoUYqlUo2V~q}0pqYi7g_IeH|Gou zhbzAAAobAm*U@Xof4UxnPf3}7V#oRujy$8ZO2s*m4@Z+Z#nOTcFWCIvwDo7KlHeMP z3$X{VZ;<*)mwSJNx{uEdTrqm#DurmFC}iPOj5?%Q2pg4`E(zPZ$M4LZZ`|ADkez!t zUU5PMJK!rU{mU1u102XVVAVma-td}x$L@BJzid1~IdX5j>RNaxyB;oA*joO%%0yL3 z)wF=3Dr^gfOxM+vO_Y(h1A+}?RXP+})+&I&u3SLJ&l#@Qq9hrIjHtU1Q)Vu01SoDW z*m(SMfhI@9>YjLD!S$A`A9h8&`%4sQ^<b_|A+_U~W~qFC^l+P?;BiUf_TGNF^5gQN zplW1Ps+NyjGheU-h9JNT?3z&Hb`MZG5<+zcY8G;d4^KATP*&wWG6g3~9?zQi)cV2Y zX!$!4+3J4bzoLfTx0ik@ZM!r4zC$ghCa;g^+dwI(m29InFBaV9klm<g^U&GwhYf?> z1*O0&r#F7&UI%64%M;{dckk8oh6k}~VH<J)fmJ!YK9qeeJZYh1qAEhAS47@EQC3zn zT^9~%6H-*C1t6ND@MV@4Vi0v?iCluS4WJmHv>2}?-I(n*>GbX9PMx90Xn$q|Q<^0s zYU86SEPM~UDRoQVKG8r$9z@`AfXH9fbN+<o>N>12C|j!lys|-zvH>@4SM?WvS1zEz zsiJ*d2w(|Lz7d%c<AxywI3h7VYtCwkR?^gr+D2<+Xt<n0>v%rhK@D#o3}iLj%<-9y zT%gU!epW;dc&&IOC_?5p4*Zr71C%PuLe24Xtww>ls=<L0F9hD&91-J0%g>+kXV2;n zWu$gp{`;5D%Jl+Li%)2Ih~v4Ig3>nuU7E`>io^<Hbe9qO(u5|XF{ocRqTt+k{dDTX z*aIRUh{Ho5=!FAdg{=OB%6&D>)?($(VWFyF>2%7Hc^{o|LzBC@6Pu7T;7-pOqs3g0 zr9|J5GHN7C$`7SZ+YMx8ll>L}EOUA<P?Mr?xm*-&^<d7(hWH~3W~Q#Rd?4^OZ9YBE zwC2fVbo41w@(}D*`<S1QnV{M;LKYAgc^Q3Egm}UQ-5!UBTCdELBa;&WQ2=aoa19~R z$OD*bAcO~#w{LxTpCSrRItxbX`R3bJWP%;x{s>FBf-AiBd1TxMRv(fs4yn0ywC@Ub zUEUFLY+PceUY(6qAUkoTe^YIzx`L%-B0J*il}_^iCrZm|rfb8uUcyi|rVBvu-0-S| zY+Dx-Q=-S8HzWQ^*QX1(DiFv41mx>5{gkDm>rEe6IbeEDK0Y)m>0;aniyi^G^B`$k z2+;=TMapkJA<Dq2490Rvui#I1HkjNccYWl6FhLv^p(T<FuWT6gDrBNGL)-mJ!#+Xs z1XvEdWR1t)_eZO|bue^@k35_Cbea3Tdrm&LGUn^71vbr4Mjzo>(Tz~srefZfbS7U{ zQ_e*hX1>9$tzt7Y;;C%N6bLA}Y4p_p6%ID9CD~va!^|R(v>2_GWkREGv$4x6iu4DE z%1C@XI~$|71Y}_DFv`xr_UT}Id*eA)7#NIu?~D*aK(Rd!e-B14A<f=Ps8ZLV#noXn z3z?maq6Tv)<HlZCxXR9S?j~pa_gMWTk}xun-gzs4-o4U|ArO&<1}M}~V}d&$xh`Mw zwP>QSDx6WsN%VNYL}8OwOOL_B1=zuf6MzE-^fXBL-qn6`LICP?Cx&Kz$$<<d-+(0# zoCqv6nxG>UeR9bHtZBeD=g4ZpgWyLOfUyLK+qVWgd60W1WvMOPCBdD%7}Z7;f0IZP zCPtEk{Ulas#TiPBMHvAihudSr@W%GWN1cojfdowV9<IE(@ENwI?nn=}l>uRbv7RJe z%y~O){X$PZQymjeGjy!uulkeQ<DF&ak}kPX*eC1UcS*`fAv^h!7$~}#zsI(6KE&ka zTJSFO?yeyrSlU!)9-8UD^K0rJ@NLqewkaQqIvy(m4M+`g<z_j%?b^NSwRL#L<<`8Q z<}i{dVI1%|uz@Q(4JD-O_jh@qefZjk89!3Wc%mxAReHNV$WW+N6u?nLsB6jo21U=G z1K}#RU9^>YiYqX1c6h9nbc%=ST#sw6O3oB}v8Gr!+T`!`Yhs*ZLK@Fh(kU*wn`WuV zh12hU?;cn-?V2RJ%-A`bsb2EO_1=igo<l^BSpV2d?#k>!^TSJF$_))+J07+-@0jf% zfvG&efQ+YVqa2hh?v?kb6Cko}4Gc46tJ7*fx+x^DgO$gWwvux6fmg~7eVQI@cXxg$ zQfeVR+@3e6HuMY$IMnI}JdtZC*a^^$NgUbM?nm{_jSiV$lr|*#NxNf{y>?+r2)Cr* z8I=44%y0JyzR_*Pc)s6q<86d4c}<a1%1Wp^6Xu5?o{T=$tmB8|A}rVWlisSaqSnu4 zr<^U=y%uNM8r0*8{qXGgxrX=qGxI*IvNGRkpRd0=Z-3qOk`CfnzQt?J<xIx=*SX2C zm%rcH_j_Z~$NyRq_RZ+MzF&hHB`g;g?DyDaw%U(ZH%aLYqO?UzfvREiHq-5<N90;Y z#FtpaMA_Do$5+Q=6E4JSJb63Z?WUxDj@VhH_j_`{eV8IoG%?-)wTH21uG>@fpm&W$ za+G~78C;UH$o92vT8#z%pr>m0+|`F_Ukpw31kv9!I`haa%<urRS1>dxM1>wWgPkd| z-*qB%22(D*9lk`O<fsq0|IGU{R`<eL3wH|FE~@wzhfK_h$UpqX`jOdv=_Ovx?9SAI z59SXICtg|~%IME1@3>b)#?h!r`?pN*noZ8P<W$W3m(aEfnE@}+qyn5fKII@v<H=iT zx0}-8zO^UQ81!N{zkfgeS2^!5=|>1KwuV*|yPbh8()s`|Vu5RNsVznSr{hIYcZCJK zZtHf1nbkJ$8vFyE(=su?V76ttWYJE(SJY8HkZ~~MrM2P2>4)<EU8yy*yh{(HQnNSK z{KM=BBKa1lxS^u(AQl+v;2K==o+bym!xY=_AU%s?I<HL@n7(`LDR+EXeR-f~=z~d- z4(|8gZ-IKAkig6yJ`ND%+kT&Hl>-^vHZC0JK*8e9xdlWY3peG)4O~m()He1EeO~@O zmUD0FevOaK#W-@URjAX5>Z9q<jly6tBQ6L<c#suL)}Q@%>z?{$W_AYnG=}BZKG>Gf zyw~!lkbq{JaH{8dS37_2659fX8v%pwFSzf00i?iW$c3>AP&Dngk0KW{3?CkDoN%R# zBJ*XFL!i69Y3nU}$<F%Sse5#$l6b?PbrVoL=(#$qbS838$cjen&DpPDZcD>!6IERt zrlP>4$2L+M$siBV4}*1!0rp!GsE2^7>8k2IPGB8&sSXO`)%{|ytFr23)#lCgjTU4| zhieJM%>zsmoiL#NlM<kxwg`@79|H9K7T_WJ9wK;;&e>UCEv{N*v@zp&s(zjd2W^&| zUpbzVEx6)_e@;P%M?FeQczlJ&^5k0@A=@c_2aSW{T5P)vI!*2RUx`3K9y5#wU>NGe zXIUxEUetZ`6RDiW9!~#WjHbJcbrm4kZJ^vy2jlT*oW&lA8eP_UHRZv@#kC$jm|e!P zZ+i1{Vk(I_{@zwc?KBgT16!n(0ptLVcSKHDWnxaFcf5t>vW!S80LI!l4uOx{o$wHx zaSm+nlZiP$dRALaR-g_oOTix${65E%FCA(8{7L^T#z<sG@U=BB0M<N|<ZHOxLF<VX zxS2vsG-o&g<FN-{6aiJPME`Bq6bCAjE$MKr|9F>+8h?7(|M<gu6<>A^&V^~Uj_0EK zeaE%dS(1sMQ<-nC=r8lApLe*HPfwo#19$BmKnZ}4UtxI+rF^sRKv9X+ogR$dsjF>9 zd;O17&*ytyJ$2!P6HDEkWHL)~X+0KiXljSFva+*3X=o7Z)M}o3Quw=mELBDXKn9TT z(`#B!|DpEk2kFa)9$7~+vjUtAPWj~cXP!J22g`!NA2+)gj?FC^j|p5J!&}pKJRC?n zpfYm0=C0C28oa>!ov47H*Hhs2t^iICeSWnyS(`5^@%{@uEa0>BVQQ13FT;iUgxlMF zJ?j8>lNLwr>tMaKzu2!6-#U|f?o@7i(rZi(a;|U5A(3jBeXgYPzDitQpHfWo^qzuE z;pma9#^&3+IFc}_YZ(00ZSQQLt4$;2cD-M*-zOg<nDj1gqdomex7R(8=-w&f{(iYA z@}DQXmfGQKi~yL=>J7ZcTmWul=W<(TwBrZ(EA|~Ma-VwK=7EgsS>3%)xKtNkMw26T zn2r(*cL|e7akqKR4Wn5)QJb3iP18y-eSIo%mG?`|8D=L^pE-zuIl_Ck(RvpNCS&q_ zEB5cZq?BCFb*q{8bC&WT4)N+*=6F&6h~)jm{k>C==pJSC$KMM-oq(&kwi4&OJNd+b zcZ92fMZbO*g}B!=F*n3npczQ`FcSO3S86~8t$jTW-g?+U7l%cTfSpP@Igd&|i#+JG z^X<w~*d9#rt!poUijjKnUu`|K$6e3M+RW($WHUD6aVf0V?v&kGD=WM6$Is(?{lv!= zZ4k5U6It56%1--Q?_LE<Kn57E>AxH<>Zr@!k5_9Ajp<BFNxk_pPVn{7MtWWnCG{dd zeM4Fmns0##M~7XCFR20^vs4*QW?h+2;0;&iJuvu-62&aJi%H=;^i92zMT@%gHu;WF zvQ?%>%SH$FYoT1l)zB;Lq5tFb^+RnNAKx&`8v6{4rHE7qFwyT{ZOj|HD#vL)!;qBr zc*f>4X@EDSn{{8mfRkqmVex05ImQ?;Gq}7uV4NSAFyA$R3RH*3*)+RWN1gr$nXg#= z^_gJnQ1wX_jePSQ3~ZhQLa8gj-b6uV(6SLqU@x6+0On<jAkW~p8T9J0j#ACeP69Ly zzn+tUIB3@44)47HaJYM1NufT$QRt$U%-~|$SVPNms~m@yhz*;Tn!Vzd0#(!2e~HF6 z2<RUEoNVN{io;95=p3NL*`(+!83_Pn8>ci#V2eN*$!r=r=*WHw1$m=`(E$4Lq+xSa zyESXCxIarvyCw53bN1{tqrgB%KN=??z~WE<*2!6G#M)OU&Bv2!kYOKS+n$m&;F4Z5 zlaPAtK<F%1+tKmD1tgwGx3!|6&L8wZnIIRCw8K?g*ULei49P+wuUj@@1{KTTviHt% zkXz;=pffx?St1HBVuvXYitRn(nruxtp6ETzX8VlarFISudXPoyn!Tk4!^5S<C&hp% zieyO~Ak%liUx*p{kQ}HLl_S=HLd+TNCgg*Y=3M@m^<)`nbHvD+IDnDtm2ySznyfob zCL<&x0QhsT%G2z;Cflw6w`Urxc-U+?KeJBIF4x`mL7C$1j-7`}#DiPe?)8?9q{Q6z zv)+E~zA+sdwS&?@#NFtK0ZJ3=k{AvEk}a+H56m&R&^Hc2+X8AxD9l&qr^<I$yuJmA z<1Ywo4<sRDbl*7q=XS&~vFoDAY~VPE6OS*A#Y!QhhyC`K?QbdQXv-~04`=&4ujHF~ zy=_nO>ea=URu9F4j9i!`ivxgUi;ESN$P-+Wk+g3FKotndSB++W&5{*c4YZp8&&(Cf zvxut@s+g+E`o*sNK~}jlDu?9pUy?<_F6+EAXN&nEkGDlp<RGmA6>wp2+q?o0alf^z zGLh#eEiRthHX=O-qzcY%9_xa|XTqHvE~|Sgp$Ew5YZatZ(|@IF?>&R)v6j7a9&z~n zRaoVBZVv4a>d_mcxJ|?BaA1k{KG{fNbz;(Qy?xYn?e(pWr0&S#y7Ic~k!)G}O0=Lp zrH&Tiu+4cp7KcD$@JKwChy<2yav=&}tdDIDIvwJ=zZsoR{q)7?xmtVe;c>xYM%f$7 z#>NTEvCDzA^<jy5R||Yr`Dg)NS=>@kBx>>eGah7d0NJx*>Rhz0l~c5h3!hw<_tsQr z2eeWs!|bX+d#VfAC31xL@G{Az(+SW}7JC>^=gg<DHb&+04QA-Yf-@*V&wU`z11kS~ zE>^tjhWQEEY$#w1)_*zHE$Hl0y+CCXXPklU05*P=Zgl*Adw1)9?NyFneqpkGW`O#q zd?WU)WZ;zX6a*-NO-mm5%vQ;$vi*}lQ72RY83kZ0ngRVK+NVc#VEd!=xW^yATzK@b zeDCH;+0p;Xgo3TInErEV`MG`9rHE8W0U3ERS{N;Z(r=hAzGiXvFRlx7bg=zRN_PFY z>y;2{WYaZYT1qb|<Z7~futVcu^}wK3ZPT{q1l-eUrM}UJAE3iB@PG|uqcRgdT)eOF z@>f#hI#<EUU=w>Xnf{oY$C!VZmIH#}vhDxh>neY+Za7DD4pe`2+b(MKXn(im%w+Fr zGch>q1-3bkuTjz}e5h+ojB9I{nR?+&K~AHtY*U5<Kn7}qmj}(v8JP3E8ybiY7TpCS zm4Y2G9(N8<!Z^FwEAbXhozdnT&Dqo(1DOs5ko82q&cdu`L78XLyh|mni~6z)a;yuO z3?Xayt9NAJVhotfCU45WzQ^a)pGAxF!$ZpTz4x-u5RPKa@JFrAcoLBV8iL-TY)Aj2 zj%FT5&zx~30!C1ZeTcIQAk-}Zj}}0@?d7BK+b<rq$vpj%V`2i5fq;DIf@Ow9kwSk` zJxTh$MHm_x*%lhoLL!CKxA{lZ;^UGqZgEU}R$;nfT-N~8E@EE3%*1(cxgI#20pj3F zXl&_uFZ{W4#5-TY0Zeb`ay0VFK@F^jT6S!5_F~(ta$|71t)pXvS%L~^JmVSpA9m3c zzg$)XR$fNAb}g<JoV_#WGJEvv?9$iS6V<a|{j|MTACS?>@BUFz+sh~8<I7LlWM2L$ zkyJvOCr}HECYPcW{Z5)%Wts&j*Um1MG9$BtJ=6g9a}$yOfGLZobPWfy$6qeC&}rV7 zfHa^-#JP3d^@po!n3c>{e#w;fm*xK_grg!mRVq;I?-yvCs+B1}Qz^Pfr}R@QUoFn7 z07?#sGSm8IjsE`T9i|ns71ZF`-0tc1m6hLb%vDmbqN}kbz|mY>lUT5OKX!|6{xr>+ zd|;I;{@x2O{=I*kKja%+7vYa<?k88RytiHxt(4uxhFwa}No=|2!h9v0tAtA*ZgWc; zzvG;I|K|hk3>bKf@M}jw!@~EJir)V^3ie-<^y-_p+^?JK8G{m60s$CY_zGLv5&V2A z`SUG?^|QCfGl!NV`kvc>FLI))blHZ|CmTAR`Rpyj`qt;m$sx~Q?||L=Iv5DR3K7~f zHdiOHXzA6LTr1fBUq^4{_ucgiDg_{nZt97*CO~|K7wx+TjVD*`T|b8Gcs##{TlQvW z=_YUC<BA^6JcBjOT4AS478!hMhjE;h*BVa-o)b1kh10^{dk(s(E)DMyYLIB5%vQ3f zZBj%gl4a1bV5WKyy-{`oG~||+pi2-)^QU~UzaIc4uy#_2fnmZA$&;(@Fn3VePB~f{ zVNaK>%dB$f{TKFONBO+zjL`R~-czCPshPR+3}vQTuCnJ+^d+@=wV=Ff)r7AldS%3~ z{gwQHTD41R(Mz7W%BgBe${<dJq4buyTs5bf2j_BS|0ah0A<|Xwyw7n`ygHFS?_`e| z)mYwucAv4Ich9Pj1yv2XX$-W&TVJJ+-)uUj&6aL=d6>6*5U8SHz-nrlw3gKfPSddA zz(d3HiV^0GtzB7<csZO$UsC%eGD$JJia;o=6Hqo`AZ<b(U?cLxWNcCz3hM*#?8;)+ z6@A&2x(>c^)7k0+^91~3<TFXb5mC@Mh>1^3W~!~`H{RMdoa?sSD)!pbdi!H|vx`8h z^(0Q;VOE-HQla0x2diE8_shYPty=TfbAAEMAedW{8F7O!>w<Ps+qvP^=pF_ba`<DH z>apXmK`s;ii#hxS`tsCyFrPt<+mi^BEd}l}o%nZsZt(TP;~v#uM}CTqp3b2{!RncU zOX`ya7hcV_lpk}`C9RGY-691EBkB0g;h-88Anlj(-?o10GUtSeq7@2$=XOZJVR6J^ zU8wD_ekh~JoGd)zux@FiB7sUkA(yz-`_3@jJr-xE8@JGf#1Y-RJOdF(PvW00djtYA z&#YRldq(Y>#s+=wh4*yB;el38Z*1Fv>87YZ-*<)|xj$C)kjCq6)AS(yICU;WrZxfD zWj=Q|YN(Z&m_AY&qj;s0tTIr?q_wBhZlR|&TvgFOM;svfdvN9%4R@Z#fJhUA{wpsU zA|2&FBo~Z&?cBw&G~e)?zw`|cZy)B{YigqTt}DVkKCiVj=<R`Qs#bpRmyWueg3cCK z<xf#-K^f;T#_D^N4qa{X-EEp(@!)SAAXs%hJ!sq=HZ!J!T0T*(h_5qr4jFZj1Qg%9 za&6VB@i#MDLC$~i7wnlKmBDCxQ!FxMoYm8V^hTaE!=550rats<Iuk(<n-!b=)@Zfb zJ9VWvz;PyI<fx-hL#0yXWH&X2Im!lRcB?(k*Uih5h~$&b@uHa??TTE7d|ViK3=Y-@ z(KBzfyK-n~YIk5NRPzJEBhb^+tDTtWDeQl0@p_t-zBpn)-3cMaqq;&aUT@4W@zF0M z2!Xl+HcTG|X45=kB_^1q=mAl*3ty=gHm@F&mU>Hs)8*dB9>4BaDy!PSsv#;se5a=2 zvcO@T&EeRsUv2;%3^KP!`WCX89yL&z_4;3qx&Xc^2sE6SpEsUp4qSx`EB3;MC$#Ow z8aFcOEP7IcisB$1-i-SpDlOoPO1*zH!`o`VgjjUv8I%p>5oF+@605!mEXpK**6LM? zO<0PlFgNS<jFPV5j2+J3&C|=@9*M(yU_A+3Ta*{k(+x*N&YA*ERj?64k9TWsT_B>+ zXJ6=M`@jl%VFoRR^dguLd`4#8tBxERnt`<|0}9%_fj(>TPs94W9v$4x+VXQqtyUga z3(!6=RdM{5n^5T*SqI<4t*3${PD#D$y2f9BJX+X7n{UBI-Sj!To@`WTSC%{ZJ~<)x z7Ki+2lTEJalaPu+kD&01Ai}WfMHotkXUa>xcMaZ_oS5tk``f0Q1RcEl|7h@887R@e z?f`!o6ICS|%N-a+gI#%ryxJlNDg@O!wX4v3xm;+6iya^g8%aE7YA~aXbt^c!J@(q` zI~^GdlxROUhnDu)<+!-MEIh`CfIzzAka)7M{l3&nzCU<>NDgGUuise0HH(J12jfoy zM0s&=e83*X`laPyHG_-e-~KXklILX3FR*eri!Anh4u`$C$mZlMurn7I2)4l{)?uzx zCXIjyHM0)G(9);?K;NIuEnym96g$+OH4@Z}-|YZjHKL#fyu8BX@3AzNB}CO}1at+> zc&A!(6MR%U+5}fS*ZE8R&+dPl_Djw6H55T&z$9yq6*%3*K!@`tPfRLI&Vk&j4b!pC zaUVaZp1$W!U(TRd2cv_>YN36*RnJy^t;vY|JT<*PbudY4({O><9NG5z{(auE_f^IM z7n$F}MY^4PnO#Or^|H5*3FtZ%a&g>;nQtR-p(TiCB67whTV*;GL?EDE9{a3yWa!b^ z#(rpDPv=f}Tc0viwsvq-77g8sz9zi=E;;HBEi3hk)Hf@29K$S8jRLehAnG=~CoU81 zoIR-i!t=1Ec)o9wX>^KW6qHr80xg*qLue&4JZ5I^_q}6B()Q(BTVl_9=J?k~Yb+D5 z{EW!Emcq;L`WD@x&($q-HxC5f(?z8G3u8u?k9>|h(w?4japp%__u$syoJ9_d(9l|3 zpOfopd)}kSI!Sw{T4Z*JS9Twg(3@j!ZCT9Cj#{Y9KhFQD;ZiAJAg3SxawE%WR<B#$ z4cD8~3u3ix8u3?M_#8Y4BL!L?v^Mkz96z!UY=@6M4FcX+vl;`UY!|*#0X-euG-CP; z9=4gQt%sI3^wxmAB9zf(CfN2PX)|4fb`DH%$#PGKa;{APjMseasR?dbjtK;3Uesj9 znq*H&(Q7tL;cyhQ{<LR!zNKTJ0_1|!R0<yU;}J5%>aoYA-qWmU20S5F#foLs8>DK8 z8n}9=rlF_Vah-LL?Xcb>Q0NiCM8Irjy(PI%MAUS-{MY?TB~=?(Ekwm39?{#Vk1Q0+ z?jwJtD1X|3t^p|>03`qe7T{LF7BxQn_=i3E+29?h+1od9ic12f^0d5t>x~+y!$X-G zD5l5MZlA5IPBn@%c)Ouydf}jYDLL=<+na~IQ-2F%m}Kndq3g2_xVl-K-f3-{QzYyF zd%c|LoGFM`0XDWR@x@|dl_^={=b@X)*A18%l{{dZldS4#d+moTF7F<vi=x8s<{^p# zj$hlW@Qqi_BXIR(^VrWIkqku4*>F=w`?5+1%c7SZ1bFyB4j>@MZu{e!BQ<A+nlR1J zPZ-y7zHHqL$DgWHh9uXFt%VO-ltY7jfN~A)xCz|HBrf0J$@x{V^?S39c?)+40J|JO z&2`VI>6&>4Vm)xc9G!dC&dZnO@uGsmyJ1z}0b^lODw3+{TY|a@))qO=cmT8V@Ic|W zI3E-EaT7<TGOBGGTCKZUZ4~k=YM|rIx?vrjHUO*)3OE2!Ue8jPOK|!zDy>*fPSaWk zSS!@JA#@j~*rTdMIj%2kI0ci0B&VMVR6S2+YJCg@Bf5$i?^V4y?k~W~7&1h!VV$8B zT1FbQqAuw_uJoR^d0tLF_T+W6_;g8#xg8INxDa{RzNWLqep`i2XXu}O8K@}~z)?`Z z%8vI1k%xeD7$$?-T+T5VO0`_gs-`FQJpKV0g`l?ztF=$EI8V;}o56{-`fD@2V%M?^ znpXMOW~_lQ<IKODCv#bK>;K1wj6yoGGui&`^sH*j)zqOJ1Dner>k>ryy8-MP*YJui zf#W*cg^$_1(p=HjB~fdJD9=|YDu;*uI5JleFy}s9<E{UAp-;WI=?(bogWifT#8fih z@^ky~CqetW^;X)RLo7CRb?`~>e$5%ZB(wYEx?11JNCFu+=_I{GGYPrA*6)SsM}Q=u zQ_VnCk8TJEW=>#P-vP}6W#;=Y)A!)r%*(Bb?j9_zE3OE93FCszKktRJwI$y9%5_UX zoZ4g=d;1{ly?xJck~;+%%+5-Hy$kY)Fu<YIA1eQ{++~nhNAwfyjBq|K4mO<WZ`O6$ zd0G0e0TsV|(PFsMeh#rQ;%7A2DTCf)d(IP4<C4|yrG_D>>outyAHEZ%z)G5n;D@h_ z=JE4y(e3=Yvdmm+a+iFj7FOdNb|;^>=1q1rFzwgx3M1|_P0S5-Zqf_}mUDAbiBydY z156zgO&}Nss9|<qlPxtJB=MVL(UW}hy8<X+qwTjygFFn3v&DhSKQ{LZc7yCt%ZRGC z@Qp^#nzcGKP(g;LLvR}3q^43e9~eI)6puKJR^KzX6tM>r(nJWo+YC(f6cIAB<j*mD zMDJz|HSa4RBYRU1MP^q=y84@A%@HThW6XWe$eDu3^Fd|-X0|8o9p3A1U?pGs)ej-4 ztDH0v0_$M}+)k-)dvb^7@bV1ATA_*us7pAc5$#oX(Hrj=aMan%^XM5Xk3htLawJxe zPs9(^uD*qIGmXL#kk=8Y*^)WY9JoJdKv~??-02QdVg3hArJO#FeDs*ZBjIU}?Hvjq zQZxVTtVsE={o*`HVtF|}x|6P~oh;(zchq!d^BUUglevD|%z4tSa)8<>R4eMGHa$z1 z@$YTbXPmQ#{Z|t8lADE-qEJq~R8|rwS+IZsh9z+g#+pRYKg_&PznwTi;Co!u{qMBg z{fV6XCqFX!#aro~)hbwW*_FmZeqp$ygZD+t7;X6ZT_20{%kDtPy#{LrHTA9sA)iXo zQczj|fGSE4*ib6`&E=g&d4Fyl97q{*?{JWFtM59q+eYI<BwG1!Kf4z$f-i9=B`gEX zuKUZe$*(?wEf?lKIK>J6J;ixfeq(m(Ue<_LWH||bW$=etj&#~G|C-|H$Q=h?Md{t0 z^uopjqt*tzymMnJFzDk_i;m6eN0a27?RWBFcYDL6VDtN=avNvSm6yECLS9}lALW+p z1+6MwQb`%ul-+oG>xa$d587I_g;mHJ#d~BWp^C#2^epyr!`I&YpfM0Z5e#4%6vR(0 z2G>>oat*PQ{jU{$$1wJeTlJ&kuU+o(feL^E2Y{6|s`r#|@xI1`#rt~+{HJ<P3H<x8 zdFlP#gp1!E=`ATtNTmuxOL|KR!?X7l?kRk*Vb2@0`9-{(5{}+dt@1yN($}K7xix&q zv`y8{)3a&J#{yBs>wg$Wm6terIVHRz4u9SlthI*qp8Dp`?0m2|v)8vbqA!0Yz8MYQ z{BO5ID9?mYo+13MDj6!(X~{Bs(UwzJRFl`nIW4VL+{i229De-xt9NY2oW6qxoyYxU zo3CI*Manrn`QJu0MLBhgwk%MkpwhWm9;`7l%9B#c#|T=xJVeb8rJkGOff4ob(hyB$ zMV;G^?#jacu}=rOY;+UChFhr2f{t>R@8{uGz^=dm2Yw;b<#2gvi2C@*z>mQaPt6a+ zU1EY(`IwZ#8`YR857zuYyw2r&M|lCWg&H=jn_#0!BMrC5rxtcsy8QrlGYDYO6VhGP z)&&+lcSl2-RfGlVCN&;FH4P!STw(W)Ee$s4_badUWz>lKR7%wq({;Zn75%Hn&9_iG zeFqQA#46(1C%PUT&=izAmC8z<o}SH&+--Ln;y!)7C`E}7Eu682OF4^;<pN1hParHB z20nv8PM>r>D?7ypmY$&g^rX!x444DQP$omj?0L~BM|6<{m21Oi%KSJ$M&9zChiR{$ zGD2gi4UNT76}bjnn(_d1*Mxz&Jw1!I2pLQjuE7LNVSqkTG116}kHl?692lcTic=nn zO3jLk7^g6V1zc=oadsrB(sW`f*(8T$XGEK$(dH*z0hzN-LLF#TIU8s@F;KN`P@NSI z@8uTr%zfre=YU~BPv*@5vY#&p%#&5_fCCeebAEZ*Xj{0{_{L<B-rnZ9jxV`QuRQh? zxGy<#hR$G@lucCMbRYh^qUwJRx>pDLV?TFi1SK{HdG~V!QNLf#BDGrtaqfAT!sg>b zXDZ#^FSf$G{bq@U8Duf@%iuBuVd!kA`w||3IVRjN^%I>`)avlzISZMY3pt$3#RYaw z$rFCkQ$`MZVKFo7yY1$L5@FJ#%iWCZN=>5yWgRetY{tb8ntBo4&|@TA6W{Ng#Z0yl zsm`68K4;CBx{5}NBl+O)pQSZi!-L58C|KNvMrh&pcrcIY!_^Kn8WT^TGig-sA9`E0 z9DW_!b4m=$vniI{m<Y~>qxUa)=#}g-cf)x*dLAg!(VnEzbTVl;JV<2*Kbp!E2=8U# zAEhMw?Ct05KQhI0n|(O|h|-+Y3jpaSG88a%BvTsgpp*J**+r7F^J;15hNyd{`HDKY zy6^gWt@a%+qpY?YHoi`EB-jUd73;>7jibxHW?&Fq2*^byFpUzJGZE5wa`v2ITl0%L zLDvuMvd8a`eH~g2dV-nd)x4|TJ|zL9bnaqs{*m9$?CUCg-_X|k#VmWV(BS+(^>xts zfstdri&?uIIs9Rlkc+@p*JE`C&3yEi$*%7<y%)i3w)vxMI1M@1A>DltNN>EOT&CXr zW@NDCPwB0;(M;Ubfk{EB!uPMw4rmW7f558Yu=}G-6GzM6%YN4gsjac?a?QOkCT2>` z1dR-Q8W@=YCO$bban2cfHwCb=rq_wXP*f|xIy#;+(6Itm=4}+F5~$|mrM+H3Y`r2| zcYU5^nq`uH(m8#t3x4sVZk;kcBGevX?{1mxTwvLk5rvdCcj{1<o*D$oP8yYA-M4nw zI@{eIjR=71$+|||?!gzoB>L`_rOuU>t)aGhMM3O7FYt3_wR>B3x%TT;XsZw_&bRk@ zv+9>`?;#dKgU@;*j9t}^OD@>Kgh#z15?w6PcU60+zb@BS7zKyLB*@ca01olT#EVOV zUM8y7jy@xo+))_I^?i+gT5Z06xwP$HySew))S>w!FVJP)pGD<-<|S&V_{%$`v{49< zY(fapLn?xy0dv*m$7-7vC1jA*;uk3hsy#q1Vg`H_H~&aSGs&e>XP&_1^F#F*rdS-# z$E`IX@L3g(0b*Vl5Kh4AB@kLfcEXTv`0#e$ZN7J<5<SAyGIr%N*g8bTzYn!j=6h}f z#TZGAq5`Zt*haA>vQf4rh}saYc}+#NJ%f%Ywgy?vV6^yQ40Mq-{UcrKB^N(5%$`zt zFJ)l$nK+1}oniF+kXg&Au?C~IBM4o_T0VniV$1<nQO{fxRc3wn_tCtWM6yjE&y4(* zMFv|4B>|8)D{7izYAX=XJqkKxza<e(SS;fh2XI)EE;gE;+DK>XwP^n76<dL31;!R9 z>2R>aoD}z)lgN}aM6J0-I&^s7D(v4H8!T!j77Y^{k`Rg+7>g9)ZDt@wDe$iGJ1JTi zYK4K6D^_V!rV4X?R`6UhvI-nn<JL7Wgy|m2&2VHdmuc;EnIoY?T|r6=wiHT3AZxb- zsRMGqv)n+zR;92)R!h`+Mpp~yx61X4bSxJxZd>?^1ef9|AyPGHZFkK%$W<Bu{1@x1 z|9W|k?SMWbD7sc1Sg?|OlC1eqN>SKeLJ14an&`Ba1|4J8PK?1?=wZ%EjMW2z6eUQ~ z5y~qMpJ|V^VQfmVGChNp%BBQXI_d@+jCNgtD4vmwRaErM^xrKBtQigGkhSPpJKSdV zP|ZdgJ>MRTIS<O5S4v@lwmBarxMD>+k8pK*oakF(rCC<*pR@r*%E4NQZw92GrUr76 zxBwr;x|}3_>fu>Aa?A$P<Mg_Nlv3;&4wK43;^Z#^9DYswoVX=inn5Cn%h;o1ZlP~( z`F<m;cp24_xm`%#Ufl>SvCxLO%_OdZEdpU{aG0_N9j*@C;zE4BwEuhkmRvBFu@cK* zA`ANaDQ+qDH)Q&)OKj_Zn6Whf!Ukg`AG&2DxE5J^XkQg3W+2f-03!jX%SbL`-?Q`= zl5RP`*Iy!~_$9lR)l_iKLFMNhn(h2hsoxs}4MMP+x<ZQgE*c_o<}Lz|^o0hv;$_Wz zgcR?M!-tyUbgNgg6n0Nrow9-Q&(19O0KmGZo=e%wbZ?;WhGL`K0_U39QudNGgpHmD zBg+BFY<|c^PKQT$;9k^t<-cM>UC~CcuY{2>NtbasWV~r1o+3a#;*h$$lnCG;iaWz- z`ysQI)4@~QNG;Hk;kj1KgFZ8Y$9pFdmld#P!(bKJGm5=&74^)CRhiWXc4YsuWYK9; z`<6upKq%^f#9G=6NHGopwKcGObzI1Bh<0yey8t>UEPMy;n2*Pje@<~hX)_qzw>^vo zU&~H5Qj!jtO~9<UtNm@Z#{Gesw|Y1QaPVBxX25U^;<P_BU5Ev8^jLN3;dp3d!}Zu9 z;cZX?qJ^>Qbh|5oVCo#1uKq)v{<hAhBy}3Y&)HfubB|hfr2&trcncV^eg0eAl&}@W zL2(^Z%&o-`v}cqlw$nu&3x5e`V54vec^OSS|Gt`XM@&&0SvQ{^6t@VGGIO!3NRicP zR72?85t83}Tfaz`<r2X=dU3r#F2r91r*ecUV^HC*-B*y`l44}p#Sf!yuOkT6{;3`n zz4Px&<u)E`R7@l$FsB&4Y1PEYZOMEZ?kEOpUy06Rg|%pW;{B4jYmWaadN(T;gXp-t z<4Ax#u#<`jhH}d#b(h-8`i6_(WNGexH?L+-qYx_+BgL}6%N3a-E9<ct{p=k-RMWD- z!qihmva9>##1H`j$O55K2eOufa<DtrYVgLSm%AmuDOJabV_D4!=@OLyEq>qvj0DA@ z<RHhf2Pdadf*zf_ovVO5q8y|Y*T7+%auECcTkH?NMTt7VqZ}J3(%*l2F|a?ZD(3Q= z_G_fxoC49|MghU&BFEHbR|N|-nQO%m7^W1)35%;EN?qiRrm^dwTywDiD{KbENkU>_ zH5WHo2hGA`u%Q4Al+oc(zuU*~hUg|Lms&nmJztjGq_}UeTcgun-X8DOV;o<$eqM8_ zb#*s;W2a15yc+{n;}CDISzlB2YAp&r4VxDRk3MJIXd*lAY1;I*{`r2fhkEz`^(1fA zqoD<Pq<jL?r}mFy_L9$CJ%1n3r<)UJs3V&~=%+{%BV8q(3vR333+gB0J(!xs7k5+2 zDh1Bdg{y9UDh>6*PP@C+OFz8tz%sNPG|h?A-Q4$Bm;9}5vc~_@wPs+z7iRj_EFA44 z#=FBw^k-Q|&S6Ky@fvH}c=G1v-{gPoZDL4Tp8fVC@51cbq2G}M_CIV-ilZ+nWJ_op z2KWmAm|210Wg7_ufTw@t05o89r2*^@RJBP=-PLp8dFQZH!>68`P!4MuOI>LDRK+}W z5n_7@PKR0&o*YYsty^An#}ok3tPxu#+cQu+e>{8>Wx_W}#tTNCgF?1vdwhX}@CxVc zcnW#2c}b+x=K=I}E%N77u4+K&;F4SJv$$$%&0wNh*46%wA?}q<LuC@2P1oYQ2Iw9# zfDqdgkC*EfgE7x`Qp=@}sUDF|eNOsA3&nbn5jq|0kuiK(-Cp+5ii~1VbB@>cZtbRf zwFc()T%!d3tS9R=^0^YtT5k6x8PwR9-kq*hGT&RKeA73Pt2p)Zt#4vC0RT4FGQoW_ z8w@Nycg3j=#&sJ>?PYQ+I3_h*czVRZb-ZCJ&drQuBBwPLZUip8ZTN*8m-<6d27^7L zVFXGLQ;f%THTQN?VGUpeJjS^=X0TtS*u~~fw>KnWFv=dr=a2_A4tFX*9NUuZc{<0- z59NC6F!Tt8_#oqcn1Bi}8O*4jy@Y^+rw1;S#(m}Y2$I>Jd(~WLPYzIzb-2?2QDSUK zX3yPw^20gc<=jKW($SKhd2mCe`Ky*!iLE*94VV-O?2^}?qGhHV?qJaT=DJ`o-gE!f z(@#3k!(s&UA+2M$Qwar5T!gbelY`tmqTPjhe>~b7?t$30>Lzh85ND*1*c+!#WiY@X zg7bjl!r`YY#N&~H*tVAp>LIf&*`9&s&jMaN=BskR$TS|PV;Xf-hs{|<@F99`smAJ@ zoz3<V4<@Qv2Fb-9`Z{)6$MB4k>JT2T+O{qoFBq9YM9%eE!!b-fE4`g1+p0pInRW-w zZ|;eZay-97gO?fT`Ho*^Bq%qY#cC+ZWbizy)luz)I!&jcmIP;OG6(@7?bWM^UYt8M z<Q`5<W4a~EV1P!)s~C&H7XlCW+?j0$24tRv>q9!LB?qn0Lb)aKF<t?J*W+Yb<~(T0 z@+2ei#R_bm%7QMQ6&kWUlDnR(Vg<YdvfQR;VrA?;V7sjPv=;~R1YoBSE?ZdbzJdmt zJ=YFd9wxKg#6@OV3oS!rAh?dWEDuY#!=DH~LGQHlFg+cz?bGD2C!+iD^qX1Yy_O`t z$EVp=Zq!aUTfX5!zVO{%YG?LD4l@SVo{M0tmJ60PSYRmQ+*1@~FqlhY%PpGU+)JZz z9)d?qfsTy8jeVvtm{!F)-dx!t3dI8%EQVxu6cVT2ehpU@B93jz_NdPB@;&7zVl!hQ zXcSTwYwhyuReG%_hA?&BXW8d~8{$}!N=Af2EorBfmLzL^`1y36uS+gtMKarSuNtdi zPZ6Py(vsn72a?6uI+fUS!y+k&z6(j7dz(mGLsrFbOCr(okXCyy4ZE-x^kqD!oMf&S zIIEIuUKa2y4Mfs%xCYXAbG6yJCctfSAnI5SOd@~-2ffEK3nn_PV@Fj9W{xhV#SRis z#u-U2f)OC(z4DNed&2@sZJ{iCC81qVY8l}}O1-#@v&;aE+;~D7ha<#H#hJqcO35Re zGiDHy*_LdNK=IjQzA5!sU5juh1a&0B{5R`<ApSDfJ?k}1qoUr@)|6VtYeY75cH@qw z;r@ocJt3ITGHHp~yBpWXLu!+@8S?!d_E`1E`}?{_i<=$ydv1K*RlQAY#=LI{8^$UI zP%62OBy};(gQ=)@NKD+~IEM;<FMtJGqE28*h!|jHZ|$4>q(nYKe6**#g5oS7`=0mz z%|xFYVyOTB4)yPLFZ<kol~9r<OCCZ{u@q_0@3iS*h}FDC+QJt0d4CT#;oOtX)AOhI zPrsgVO!!&#ne!t468ZAx<=ZPlqQ6SKs=b=MmcO>X4!+L5&cA+o{qvyW%!lg3_~G#I zdr%%p5ALJlar*J>@$;S6yYP3*?}c2@OY%~`OfRP^;EKMOSM|lYMy?Cj?DgXMc>TFN z_{g1$#F%4~OH2|c1u<`y(fm@9RIVf%DcfCpwJodsM#^@zhYd8M)@9eLQ6|fE!7VR2 zY23A0#qyMQc~ibNJDRaNP<J(;M$5$;>OukP(W|T;YfJB_Uuj*?ZB;d)SuNv$FV^rk z7~yfTjr^#^QG8lV#>KcDFUK=+E?u5}mN3IEvsl44_Q`y%<zYF`|K*^(U(T0>QWvZE zL|^>P@0#yI1M={P7-V4s6u1iu@C9J-#yL8!kciQkf;<dk23PSAXYnQJ(19q#plftU zcW8mW5HA1h$st_81)djA2^E@TNvWh|MIH=UUgt}__=Em}-{;%>8-5o$;5qEUd%(dm zY=*|LK491v&V*+IS4paD&DACKvpU&)t@+$cG_gi*zt)Dj-*h52<3?mWfEV#Sq^XKu z;I|T#r0}vMs)S@-lz4ZX)7gY3G8?iZlR1-xEN42;=9R1#zLXXzhs)*iPWe->Gi8~U znl_t?OmCS5pGKT^J?(!w>U8pH-s!5-ZKwNB|1>8*nrC5cF=DZ$pJ27CD$I&*#kMN8 z5?J+E-LkrG_0yWGTFm;m^;v5->j3Lm>on^b>!;SM)?Y732mN%T{@SPurZdL2Vw<u> z`^4Qm#4mWJ7kkn*UkNOBjN%qA(mP|4nfVz>HaGK9qGItJ^j!XVlk<(pT|2~)Cy-~6 zJk)knnw_zo$Zptf#_p-zs@)fRXb-hNWPi&3oPC=E)S<+o*+JxR%i#e!5}kt1MOUKR z(AUso=vnk1XgT_qBh_)gqmknoM~oxEF~V`)@r4t?>AN%Ltm%9Wlj5@1CDeuP(&u`_ zHO{ry^^WUf*FRi8xc+pby6L)|ay#!f;;!hP<8i{{g~#6>KRqd)`#p_3Z9JVl{X8Q* zQ#{wPrr2Q|1efK7@hbIt>$TyHdhhW*>}}$G&fDEP*!z;V7^EkB+C(?;7-1P}WCCC3 zjqxXbj(7Z;<=8UYXCGgzY+HTUdB^wg-6#3vvz}h~;46E#0Q~m)9r3gDWBR=ym=o*> zUIY?>Mqm?42+f46gl|L{;%Op-xbE-oALXCoKk2{V|Jwg^Kx)A4K##zsAp4;Ig7fLO z8SM}{^M}HotjfMF`)1K<_@l$GOC~KhN8PRL(YpZ_@rkjo=IO{U=l?-`qV`A4Mk_`0 zVz$SyVh_jS;yS5@)MDxib^XHb3%T*o_=NZ@+76l%jY+#mYoooTeWqh{WBPe|IsIM2 z&IFf)iwR8$a|!<?Zce<BC`-~x3QbB#%1o+A8cdpGz!;7U7K6_aF<vLDClix<l5eK$ zNYP0#NMWTOOg)j>o;tuZWVWQC(|ppB)3|9>X;;%m(q5-0WoTtkG6q?uEEG$SxjmDa z*_-(fTZest{a02M$AweI`GfN*TQ~buc2f>Er=6?FP36jX*1R&_U%9B<^xT0w<GlKO z%lx-|0$;{o<8S0`zt~!^r$AJQFU&8jEc~~STJ*f=uVQTR&EosT{}mUM2ugZNK9#b{ zwwD=}xt852hnG8)Q_7Rdzn7O*5-KOF0;}SyGOH@9J|Ep%?O!dexmb&@{ZMzRE~9>X zeQW*aI$Xm_BUfNAxYOj+G}Nrp{J4eJ%D5DBX};}5n@?MKTYOu3o2cEQ{bKv`_P^SH zap1zv4zrG-PE?mpS4ubgGU0ON74((y9-Fy!gh6I(01aRQ0`eLFVVto#>^=Yq7+s|W zh&sI`;BZA^#z?>?O+krO$KRQHSarY<4l?uykd+V%OC_KWH|mu%D1Cyt@YEufh0W&% zi-iX0fo_}$@~H4YWEJ%a2S;&SA|fI8Mv$~m+m)@Pd!%Ul34X?%c|C-t<%g)Q^@&}L zl(}NgaAVmQZE>APn;DK?t@+X4xPD>@uisvW5t$fm_O7`v1Ytpmshg<oHygzk(^Lz= z;EDy7i>V(U$Xp>SN#9{Ji3~}8GgKf0d0;re5l)(aK{HgFC^#L+q!L6Wz_)VP!)3(* zkKq6)4#D(hre1)-rdcTf@)K>m_3mvPKqh~dqv>;xa%+vkJ)bReLWgFqrx6elk<$-F z!WLD^^tXb7Vip+aK~Lgi<u5GdJIcVo$-Mmou!?O;J**7<dW9Z#L~0wWr_MwK?=Zq3 z8?AwsS|0!s@$Rf&H@hY%!|K`iO|PYqAr3+^u)Q^cD$<GDVHouU{rV3zg8xcJ<S95O z^OJhC*GDx2L&tM^<bke)MlUpaA-d8ttSQkTMh!k7NzsB{(6B=8`duAUS(J7$o4~+C zWLMaSxC>Z-dv@e%*Z@i7i8c<nDuT8kL6Fg5bg<G7Uk~=DIp;pa@$mt-^U*urXMDV5 zcXzp89Cd;x&ZHj2T4Gg|GRsSJG0e{J($e&_B(8-^08}Sda&B!7`h50s6Lw5OBa>Bh zTE4EmWB}n1Z|@GA>EAbit#fzLLf$6%Wf0`dX@&_!K2Kt8Iu)Y6&Nmc%fnH&juWOTA z>j@LPtxET>;j)yG%5r7NdY=e7mA&&L7iVBJxRM1$>QqA*qi)b!)zi@4z4~aOhZ-nA zITfAGwFQcUu_h1`;75h1nIYi7U=clTPqZ=?G}F5EdS={iyKWu8rYTO4U>hxu-?s8M z^<`0>(b-KlRAh2ftEF5zQO$CYI_`v*G60%=5j_H-!Fk0pNPGh}`-MlZ>aMlx1wmEZ zxPAnp2Z{b89C5Xw5AS)R;t>Ch#Ew(2gO+W-Bw_eGzsI*I0c~`eRQ)Dtg=>7QXc=aw z@|Se9XpC4rBFF>ImpC{>y+cx~>*lWNT>=#df&I0);Kf&GhW06pozaO^Jbz$G`AlJE zw*39k)qS$r4F_Z${4FUd|Jo=}D$|v1Z3%}C>%%EPJ{rwhvirvyj@I&syAO$w4SxJ5 zGIKt<l7;MQDwz>FvHKO*f|EvI#^KcJ(>6cQI!2l!Sv__c!Y7Q4thK}2B$yOtfiaU2 zqb|p?b1-3|^%3yui32S-(`9~^Vam_ueMp>F!I8yClR4F>#gI<`ML@d0&T{L!KnW}a zx|_lqdJl(Z-}R1keoP4a`YfVP@L8$UcbifibK-?3i?`}%Dj^t91v6At;qRMJ#Z!nh z-LV;Kq)uGTWhcBCR(~ZMF*TK`zRB(ND1wmW8)btdig3%0@vRY{bV0CFZ#jvAW&$DO zSXV<wqrqLldF3N%3JL(%UIbKu>nzwCK7BMn`(>j9ZpAnU<7KB10cmeQLRS7>t>Yh& zi|@SDIIi0TQq!+QQz;M&2LhlLtQuxU#yLEc0GK`u8h7#rV^)l;`&|u8ekEr$W0NcF za-S?`mXGZN;Ct8RpHuA=INk>;4!QMq8ns=)XB^oI*bl9@EUo6C{8*iAhP$l2$+16L ziiM2?bCB6%Fr^fP;_OraowaE53O5F(p}Xd6of>ix39>lJx-Qkx60#Yv_F`8Mt-5XM zB<-m0UPNM%6Ul!<2I=@T=U@u9Pmv>aYQg{gv7H_Z&RAb7N$J>ud3fI;$0#&vL6S0f z$pB{jkaUm1>XVaqK?zxph$UP5E!FPTkwe^~*`Gy51LD$yB^NM>dU2Hy3d)%M8)_Tg z2xmI>G6mb=u;1pS+>%bTsw{YHIEiRAjUqI=5bW6F5E~CqE`L#7)N47i#St*j0UZbF zwrTe5;bt5<T;_h%AQ=BuiP8v*n%D>YvxAmjf+$)?bqwOx43ug-Ml7RHY)TmEz2LXr zYmQV5dgEo%Y>SjhXB8L|0(&vh6APwj=;*$h8CK^dkKfUI(;qb|ID*ehnH0zMAIp2r z&x`#k+X*fXcn`Y6q@n^sXHhvn*r-+hBlGE#A~_-G5nA`Bq?U1Wvl`uL$&DI<!CJH! zL$pGM)Zfym&3y03<CSJLCIFi&3M3^S85Qs&;jl$EzrHk^xz5QtdCBNXKhPk~OA}-l zkYo1lbeZQXd9tZkifpUQpx#BaunWFRLmMbpfBiHG=I|vYme;Ee?J1U%8q_n#05&JO zdd>!j0J{2?CIGDTw0^ny8)`T)FJCm$V?xA`Xf#Y=WoxIMTf*qs-U99^0q&>RH!Mvd z+&b=>4ug<dT7v@x0MXQ>ZU6Oe(n{@N9+71X-K=_dhJNfJu+wNETQgK$1jzai3_U4j zOd<19bmdn`DslaD<hg4B9>nNibMu+Zeb)Rfo4Vybw4a@#bK$LY<h>odkbe#Uw<}`c z6qU<8H-xiG&Pk`;?vG3C@oMEiBw^-XjXFqWc>SYuTd-3ZU`MAjn~!N04Lt_d>K>$a z!!>BUlnK^=7f^oW$^L<?Y8LqTuN)bS8ji|G1^;^LDh%5YY^~WP6S-^lM+HSYKVTaQ z_gl35uJqc7rQ`z)T2{>3gcvxqGz@io+@p0Z?p>L87`~2<uQ`uOuJ|#DOO8aPwDUUM zUs1<a^pPKnFH98F#-@(WBv|-1cJx%ugra#cFqZiC102fCuYisJAjsSpoi-~%WYa&| zPE9F3eBhW)_m)({!=-rrpqlhJ2~2(6<@;J^ndV5j>+wF<3@zR47&3{w{dlfj{Y~xt zIc>9tx`D_0vO7rf;!A-wEXrIZ#AdS?8OwzLS6P7+$RENXIr`kcgH{AiExrvz@WvO^ zHilAA0O=6x`e=+a2vnd1F8{Ksy6w_a<IW*1ywR1(9NO0tJCqxh&WGn!H6)2)R3VGO zzPQ-?K3NgDb!*(bwEmnFCiWfyVo^)K`{P<@Id=jf4pxo9b%}(p$P=Y8qAo$>+@&>a zMUFP|El|J7p;@CvcixF+1!&_%tvA3f3<^T2Aum-=(h2EYl~(uS*+juDY0g>Pg_6?@ zc4(70)&J?`j_5E2m$gwy@i5-g4LrvRI^{Kf<&QuA<MSIMN+_@xi08=LfI-WU6;#3Y zHY4mv<3GiyVG5eSkg+C42voET<9jE2;TfW!*Aa%}RUOX*esMCL`r6Sb3b%tV;Gjak z022fnf*6uytx(@hjo~6f_f$u&!q8>j!)aq8OFH#1#RRDnrThPb6t-XN2;9Nk0CEB= z<fnpaS=pY0-MGLTo$)Qze$5eZ(U%|Rvlz$~L^AJXPj6Tx9>gHAJ4^<S^fbkK;mM$& zMs%{>uMZEb$%!~EI)VS}U49!^Pgt2x9jN1)&g=xm!VpWH^lKv~v6dEK@Bpg<@5(u8 zZpvz-ol!kuX}G|!S%YFV2vS5*dSk~s{f_9jCIS00bg<~}HU-$b`S$7J+zlkpYw^6C zDVGtDO20NCm1`@~U{S4Q3zwcfTCw0Y8oCGcmHd91-Mgj7Qwv#w2M=G={R;X^-gWo3 z?9KuP#KJ7HECZvSxPOB=*hrxEMS>oyK318g^SRf;2~VThyiXQC(r&Q;FN4OYxJmr^ zNJFASYZCxfs*1A_P#@FKC+azDYD=yBpgGM_v8Z?E!^62j66gVCP}&X{q-gu#BXD}b zAqKrhBo-&4)&n3+g`htPFfb2|$_6Mi947&?pee8#ALD=jUYK4siuJB@HP97OT3wGa ztfV69SQI)fHId<nZGVax0o85D#{V|DV1zk)B+@-=8#SOX?tqPL5nx9SFGC2ZhLHKd zQ-YhMO$eWF^#B?OO3*jZ=Az!rl7XHvV1}GRfJIOfgYDX^3Y`L4#Thd39R(S}U<yAG zD1MT-roACV1kjS9S+y3=Y98b`C>W9pxO~J~s(w*Uo2u<Mu#6vW+9b=DahuH+BW<pf zR+(hrh@TtR5|#OiOC9TC&hLXzIMi>TQTBP^fFbOXFs!iFhroCa7$N-|wPT-nk9>+O zxxk|_f$mhg-BRc=4!EC6QR^=18s>oCaa=DLZkU1eghl9K25FGx9@Gm$A!IcKTeX*c zMmQ*8`bhEbL&~TL-YH|CpeOhOcS^ICg%(+0^mpy-n_@YhDCb<7+(f}qr^mWc`TF1s zw5t&ehXD;RD27b)IIl2gM{`4MF)HDwKRuC11S6KA1lKu+>ZV8hyw1ykxGN(APSO*t zMjBqv_}{PA3Lv6RFurLYIwdjCmgS@oIdP+=yj9y80BDy27xgr>a<2h;sz)3|iI`nv z5yC${dRV;+(;e2}rz`?izraFHV-o_pG9F=~?I`%?<c0*9e;M|Fi5)ui>Kifi<1%~U z{R#qNl`L|{W}9suczqomjbh?@9VHg>E)n04nK)(4hP4H=1nuu(0AC1-gZa3;T~xgB z^_-pBv@TAI9VU7FLEXf|h#%2vksvxp!W1>XGEm5}*OVr9`2p%vTI(J2{&l_S{Rcr% z(@Y;p{_23?S=JzYxm1@$*ho-s_JHc6W#E4)<a__}I3oy#NJWR4GOD=6as-!IYutU+ zl4U!XU^4oECf8$MWr$slua_bFgC$-RL`0XW7vIJl9M0k>Vp{My-B2V)EFphNr(6v; z=d~-in+gmJKI2bPv@CZbj0BRnF>SnEWfk3}hY9IcBX~jNVV-|v3TbJ5dDMN0AnEzz z6W!YtZ<C+&n=-kduB~RqC>AG$Rzq7r;QPNLw^RlN#}+}%w~r|zL>}kVR~FaTag$N} zyaUmT5@Hj<#Ubd;D+<BQC}#od5HA7ba&kL`+(IP1Btz~(>yzz8ilei?0A6P<UeNCc z6Yqt@H;8}y`1lAv?;sxHCBDeU(;Gohy<1|n?H$aM%6H{K`v_DZ9@2hnfc!n&c5~O; zC39T<ToWn^aeI2%MNWwA;#R5-u)l;&WVw}lfVSgR&J^_^5ydrs1sBY`R|J*aUgX)g z;RUbL&@d&=(zQhxGYol`vu8}ur^wxD!C~|fvxXz$ihfI*Dc8V(k;1#rj+chvl1w@< z)RFOi=l9)G8SoBlI<8%g_PsTgiDK-4{p4GEcw05QEY5ze6wo|5a#%u{gpIdG$0jGR zKAy?v)mncqsOcdTD1KO@9kKc<`wr;gJ`Q&@<#jbM=Xw(u9PL*Lz<}a;F&%-<f?mcL z7p0VS*p}krObs(|uQgiOtB*+nR{?cK!1etE!432tmxqQ?RmdFLs_?95(S+(7pfhch zo{DzUkqU8T3p)=YD}n`dP<$~A+X8SkpjrRnMl^K55LuTe?(I*k-$+%dYn@YW*#V)< zinSZnwjBlN=f$x@)Gh-Q4K*&J(^C7$4<rPb&&E!_Ae?$nLxV$_mX8hv1NQ<0!W4cv zGt{g)-9R-<ZkIf5>XP7r1=jeK1?ftIujy%MriTj-Li)HKt2|BA*0z9$Io20R=YRHH z61avH#@T5{Yc0$DlAFRgA_`LO$$2P0ACj;cp(M5JkH~Vk+JgTH<Giy}!YgL5P^ny& zFYr6W!P&rP*u_{o!26#zy1hzud9XH3M&g!_KLcTqZBQvEzN-y?B1?H$(krkR{Z-uN zI@j>QllM}*oMmmYTa5qw2vV69Yt}2RJqhUZQ<s{RBL<*t*$cFdg0_>&ZX1172Q7bp z;^$YMe<*_PPq+y1km_}?+7#~0OzlReGd8GhYF!H3qhjv%EgaAxpd(FcYY1SU3Irbh zI1Lb$9LD*=O<|Ca8LUq?LfWhKtP>a&=o_b1j9X9AQ$2!%)PNDuL-IoI8&Z%9S!csp z4~^*O@-?vdb?^%%s>vEn1r-b`TZoyUxZt|mfm@6pBQLUID9dUI3Oq7pHpsS4%D?;C z{reLN7Xi%elRhk$A8+lWA;Qir2}*q`Klj+Nn;FnCSP5Rw&kiUSGJ#XTQD^h#$h%y1 zrUXm#%woU4J?4uVhl{mNpO&zx>IdONMSUI8Wbzo!vE*i|K4!d8bm9Pr#o_rr7+3{( z&y%%Y-~7ZJ66btqC9S~b&8KZNeidh4=8BFLQ`yy7yQj;y+Un(hAD~C{tZ+fqh21ET zAOK|nH;scEX2%1Rdl+fhWb`(E@X%$EJ>}|J$M#^UG#u$Q;ESzIG^dAV4WA$(v6uy{ z2JnQ&t?S>v`)uu^qjcIGzN6Kx5<nYCIusfn>5vr){1We<kC<ibVZuUY1d)ZjiGJV8 zQ-ih!0s5)H;L(KuMQ9}|ri#KUTyEm8>;I7Q24O#k5)e_ncKa#TC{Ov@sb5eLFU@9v zjQ)~q#LHl;_+NQD?Hj%a5tKikEaOS)Q^y8EO7AcVkvkaY(0v&J2cX@+F@Bs5FACO& zw(cWt{(98=cul>osnz9bSKJxuI=R}k#g+-fKdTD4ks>Q_otx+ghdAV|ITqZdtpRIG zk8L;EQtXqEMrA&_F?WKFZPrd-Oz$*v9(QwRbQSsr1JE!3j>^&X5sWr@nzJtvtc~9s z)-22jq<|xv(l&KWPbMr!Z#pcDMebeAg7QSad&EMOjLM;12a^Z~6%z^3pCIT;7qu>o z7>Dm7;npD1ip+{R4rX6gRzqCWr`U>+hRJU)*YH*b8nw*5=59AV7+RLU<rf&3@f89A zIZ%M@#)?6Hs-ae$AWK=JHA>cIHE4MBSPebUk)|9|>LhN}cyl_P$>e?vd#{N7OmsWD z3s&iy9Fxlt6;+gOO@H(B><ir<P^Wtp4n=^<2{=!!om)QiSUCCZKg<c+&w?BYd+|6^ zt<dUi+{{$A@pl@3fmRMrCGbPQY<DF<sM@l9D<TyK1djbckjov}WOJ7dHpyYwN68ka z>5yRZ&7T~4zr1XS3toeuN*aZiN){ZRSEgGIjut4nK@YPLl$hx0JxQkoz6j(q0T|Fu zp>RE6sqZgq^Z3VF3n=#yX_>ur#-Z{C_AJ+5NEUgR2^}5cD3qb}Mz%EukS-dR^fWZN z*C0K)*Ek)cjAdgT$e;uy^^;%(*3nelipJH4hX_Y^#B!1k6ZQYF0}^7Sj`t`3suwUO zU}rqG?8_$X<s?#ER(}+aWw0pFgUJ85@Y0BRn!wl$a+A*ILa9bynh>hl*#QUEaUJMM z1(T6rt6He$RVOMP4nG}H?t`uyymUTJ{EaLtG%)EMzBq5gfgZYAj4-)wMF8R~3boUe z*d15+0S!XPvmtFd>Pjg)1!Ft1eeKPk#aq&w7Rm<^K_u)rBdz3OrJ>JIyboEeQfhm* zC;-0&KVsm$_asmO6J)Cb9sKPP-I=6L>4n1KH#TwN6*#m{2Zt|U6d{ik+qEf%CQVc_ zjLpCugi?v@d+|Dj76jcHk<`erN^7GgZZo&oaRaDjc$Eo`PfboRvxGgR_#hy1=iy=B zaYG=42B8$5{-!^w_T<o_&aB<xuZTz=6xZ&Ts1oR|Jv7wB@{e{O+@Bjx`nr02{M{ED z1$Dc7SUGsqYI;4w<fms})R_vYNS4~m+K^y%XltplXUn}Le!dRsPCue5zk2bpA9=df z!=IarT@o17V#S*`x9KfK2S1lR+x4FKKW=~->XDzMS+K%3?S1TE(!s)-xR~)KxLe8j z+rOJ@THn=4qIRH5be>&#ZJ8%x=$I~Lly8D~B16M@8PeZiovQWU&Lk8d`7P3JLwmxK zw7HmabeA)$R83E1ZBX0tIY;P+ovLcD(W9niEmpdh4HMxm%-NRlT-XPW%^FB<Bgua9 zYyJ%nucB8}tD{Gi|MHKAA2Sc%gz)dBf&S*7=rMLkkVcB)*K6(S^v0p>MzI#_z$$3i zFt+v^*M|NImw>nwvc30uxz=Qc1q)zdqhaq`@aN)J-f?jWQ7vE!8hg(cYr8KdWIP<- zN|a;XDnJsBuZgIs_QRsCp8h7>BQCmv9nj9}K((2O4J^575HZ1=(+hrTb}hf?s^O!u z1RW*p(zjh?>Cf`=y$L?2TA?-G|1BDlvS26<+5}FHG=`hnlH3wO*xPo(mTf1dng-5l zGhZ}k4AvG2mXxjM5aw2iPpjpsdrZNrU>FX;B{3gDf^1d2Y>3NFXrZ5`zYboZD2#?L zbUwIAUS|%n;G%V2S}BP2tRb^B3e~NvY&i^BV=H{da-w7W@|t=JT#YTQs`w>ZqQCsU zMvP5{e1T1`p{^a%K_JtKFXA7QprnRo!{O6=_$81B1yc}Rk9HaPaGl5XZJ~p~ZrU(N zgswpR<1#B$U#cHg_?A$q^~g~PV-VbRmahb1q{pTK%VJr3^1-<8Q;)ANooSe(jvF4R zNK(x0aR%sfp(%G~(w|<`pnajGuq5v%XSBXheUSC9rvE@kioQ$+TKN)(i4ce58bb&o zyu$GCm8BaX{ja?s3+_j??gDPrB1l;@n6MflVWAjVpi@Nb{1$tg>l1Y7ccK2!(2J;U z7-B0)gKM96$m?>Byx0m7Me)e**4CKZ;93M`Wc4*XXEQ`=;lw+k!f}Te*&j(EtUlk< z4sx?Thb3dbn5+<mlpkXdwrVd61~VU9bu>^iMm^er(qs$|(Sqxm*~4!oKzmFF0M^G} zw%64@`{wgQnE%SIC$*N#?YtRHQv2^)(=G(zj)M&i22sLHb3+KBh9KpFMfDp*iY0+1 zAQ8qkD>nhfXAHkkq}WhG+y~4rZ}KjcERwAuKmtoCdMa8)r7Jo4kZ@mi3a?SQ)SI(W zko`zkKkaUV^>wtRw}1dsupXmfGMxUL(nmA2A+S85*k)8T?OXBI96t<W{<^lV#=4N1 zeR4xW%daFQmZnCEiH(0x_`Ex6??lBX*|B8kiM>^xbZqG{70{X|>@V)BvV}zHQHF@8 z(P#{6aVW19BsZ>P7F56yf*U)o#*(WGGgGWezITCR#8QhX&xEG3;LX`S$F@6;gSTuT z79_X_70rD&8y=-P96YQfteP}hB*(vN88MnVaGcS@DkFS%+_AczPa|PSw^clKN>r)K zR=ZR-jC2o<Jb`)hXoBFDuuer&2GN08dj_e{t!Ps@wWghK`8@^y%2w)J#Aa``KaF0( ziPc39=X#Z?iq~RvD5H^Cv*ymU_+>@E#SxIJ62wa-Wu!ZOE*^-i$bCl*Y+D^aT2fpU zGP^vHZ4{#Ua6=<BoK>IF`%UEw6XR!csly=sGikKFWa>^TlT=@e9c@ex^Q+LZuj<-+ zxrk5jI#PVG;J89^kW1xr4c>-jQpWV27q6-`vSuZdOPjnIgQx<u*m_}cB}~diTzGa| z5qW>D!2iz{tAu6{CCa(131{Jp?iKGtBE(Hgx}BW-a=30@)Og_G$nk7;YQ9jI6Oe1X z$bv88N(SEM;^<zXE*f}mw-`Lta2t#PO<BMar}CrCQ`7xOq!}WE4<Yx11&l@<{14ns z@2Jh{U3|n?<P#guRP?trPtoP;M;wYE-2&}2Xc|!{4uW1DwE3f&giJK3f>jTpy-_=# z)^jcMZ$;}~hj(^h`_tEe`s-Ud#ueS!NnM<lbJNxOb}4EcH?X#2FRa$ll||Cv5Qg%J zlfIVvD*lCDRm0Tfg`~7bliabg;OtW}X**vfp+NBZxij{S*7nXl@zir5r^W@Yk4La- z7C%ia*td9}yl4^+tGv^g*Wc5qhTBz9KU3q@<|N4<3B^7zU%;4i+~hzBmBu|Dt-2e( zUWCo1f3B-izzvne6;o$rD(jczp$R-8<zSHbwJhrpDhBJM3NfpR&Z2>%7EW_(@V$Fu zAw$XFim3*q>MDBPF2Tl?qA-V*m0fH$=UhUFn`~ZiyJszq_gOqY)a?bbEuBd(4PUGn zxo2|NHs^P5o5E(EgzYA=;k|ebkpCnI(v`QAL=Hu?Aigw`C}y1R6I<V$NbRucu#_vo z{+CJro1{*)JLx+%z#R0M6n5w=8<yIRG5d%2{yo(xPl<|b?aN@~P(b?t96u3DJZ~-H z6b>8JR;kY9s%CzD&l{D*#NQp*$d6ExY2#aRyX)eFp*r>6^>{GTSKHreN1M!%Wt};C z(#oghqt#NrGrgX4;JuJ93gVyWDYANZ`I5twMAIc`@oJfqV^T5&hIelEPszcLlyr_} z1w`X?IMv_@3za&b>=Kf#|JTMA(v{|J7i>h_WKwt1kWtOjWSiJaeyae|bG$SV4r#R_ ze)zp{r{}Vkv}~EEf8@NBN;EjhWFj$fQ?sq|$K(*yveOBWE2M+5S<x(sYgBM}5rR4E z+vaLqoT}*cyo5B_qG?2K%vyvvExAMWU}RGm2-i3|roojc1Wv&;A8aEFkDpC$wAzNJ z4~O^N!%F#@%8ZGT7Z`L%NQnp0)1|n93+sHBC@8NSS$NTdHO_zqwQVbCccYg1WIJBH zjuaet5%hL>5g;%oFn{94`$(}26kHtN<?211OE%>{*N4lO8iEbB{PIz`k+FnSk(?J& zY64Htd|})4;lJa3`LXlrM7GMI!FJc}-_srK&&qVCUdR5Ev=zx`3;7FMs;X$Mi#><; zkZ=YtUk3kGORybm6moE;9s#9@F)aOME$XoxA6Q8UjTi}6Ol$S^6r_XT9f3j_<Er1k zI0J@uJ8~4(sFSA2Gz<T6j-mq5X`iuL#WCoxX}Lx`XH<>KjFI0eQWOWODF0b&$EYQ3 zx=+CwcTXE+kqq#n^p0v0;-#g9lLAfoG5AKWw99)8G_{~M&rzImgd&6VHFUIij|lic zqT-r7Sf^XI+KQ92qvJadEU$l5%NXz*yd}of<-Lb<U!OSfERZXg<y!Ef0WoGcLUv0# z9IMk&V}+-}WJ!xwk+Y|WS?8oiS(L212pLoEb*inn9+-T1@MyAGEvMaa7QvyWv;YAw z4~Un`@RVu5&&@g-T|AhH?gdaXNQ4H`C?Z2LKDYsj3xZ+yw+Og;C;MRXoz8s*HC6q$ zd{w_sh2`k#<ZT7ZtiWE#%g)I9uYw;tj{g|+wTk%ZNR$vojw2nn_8HZBUlb$zk&{#S zx@w|&R+%t)7)<VMW%k4JXAK-fBOPpmrI`&amx0<tR7DJx32Ry<q=GyVfcX`;o+cnO z$b`O_Yw7@ocp5LQOrnR~AMLoMI#R=C@S00(0vA3Xu<I9FY+papy&vUt@G`~%`rv0Q zR&4TS6$oXN<seh15M!DpWUrtue7=QDm$^~uj$fRbogG0tW#q8CxD=k<<T!e3C<c9F z!|f5DdijTxmS*;=%933t&@t2Ty4qBHw37N=IUC;oj3z@EZRI$B%CCXskaFM?f_Z{_ zJGI?zf(%1hv6ln9t9eLrR58@h`63HtVy5@VDSh}U%Xs^m#FCvPOdpT?Q`8;t@2STy z@juF;)2vW=O&=>v-tI6hu`rN*Zb0{fZ^IxDMR==R9kiPARr2;<Rh)zZE g1zq3 zaj~^XTzfAep6n|x5nQupXsT`qYm1*o&bWjRql+l1^2``HlZBh4r%0^R5MmMT&K*km ziky&>J3`c<t|GggiMJh1&f`T?n7EbaTiXd;pm?XyGZSJH-srtCRToz6ce!!j$4$h9 zoBRfq-psRC%t{W6>;NGT%e%!SR+HS42PSic1X42ubdfApiikWbTYrbM)xyunj)oV& z7np=TG}7;GwEYkC!kCIZ<9yCS5H}`~s*5nBNbcMyzI7WnsN4(>N&<0Vvei*qUX$ig zi=j2)>m}e{-nlHKs`6-CB?l+%h)7o3vyHRnGFETnVO4SujQY{!=gM~7*Y!1v=oT+8 z`3gUPHs}%V2srGdV|_9WE~v6}U2B;5{gzOTs`WZtAWa+^QF5=txl=WZq<yS^a9YZ6 z6;4XR>+$7;7G%{UBnZM7nxn;+tX)^PUHumo<+bcJbLvHi-Ws=7{zRqJO;$bpS}fqu zBoSeIj_)S_U_%!-z{t97@p9DyJ<_I=Lu(qOA|5;=2>cj8qoNIJzAsPrVGo;0MQ1%w zN#7sD15r|IXK3;Ha$QFHJXNr0!s3ntuXTD(Gg0P6I(ytf#n*SwyC+mQA|(Ix*xjXr zu7Y;bY{4NYVG`jO4BGIdL!(qo`aU?nNe~v#Bc)+4Y93sG*)Yi2=So}Tc!O2FgcmE; z6H*tyHuB6D&kf}dBpD6PB#$i1@^o@Pt_CUaMEo_cEGKR^y0}C|x-vpcYZRGW{@N1S z{@(Q>*a@dc4bGtUk9F~^YODypo{Idt)+(Fjmkyl08_O|TENJ1|V!AtH{F27dv1PUq z2kU5CptCEY-E?kNe$tWUrQpKRAVTsHhpe!wv2jf)g8@ck@zV^$MErJzK{p7iWxcSa z&WO=zQgpDIb<vhZ$!M8wfP~MJ;%h2w3$&^ZCZ;=~upV3tQ_rGEU8J*nn#BHi1<F5b zNauIC01K@zHEEj+cBlC~9(yQKp84K!`t=3pXy~{0T1VexYIO~Fv{PHMuXiSK1Rlrz zY+ym*D6}h#2U$&R5kK2v@%^m8N73Pen;?NF2jU^DF{WT*=ke~{m2lgSsz|o-Qu_UP zw`Nc%B7E7}3jrm785D>)Q`S_eCI``%fnFT3tl=B{Rk4eej206JSWz3LxW*<`=1ulH zH1E8nj3+Y1bSYxulr>hrbG<0B&g6{)8P=*^(XpOkOO`YMwO+<D?o3O)DFK$<@9V>5 z@69?Mii;@JH5Cd!5sEX0GV$*(14ULPN#WN6r77d>aKfgCU{WKa+NH1RS_i2?Eyp<v zztiMVgz`y#X;3mFg-9<;ZyXx$YIiM{f92QJNm|!)-W~w#fW%l7q#U&BJjr+=3u)+S zo1oM*T)*xb3W{u{7LHL0hPsEtC(w6MbOdg)i|XiM9$*C)N858p7t}mhc>_yKz5<$L zF9zmdZ~_TXw$xlatbR+!q1lw2if<5r!>UA|A@p9(8?^BBN9zlF_NZ&iq+|4|mY;!V z2NF?51EwQ&+z(f^%jP$g7DplPqCw@=E3)Mg8;?`!8V<C}<l&igPMab1Dn=QLz>kg_ z?F>C;IE5OGU6?R!%2(sJY2sDzK+XErzAyz;Fer~e99o@sXf*4Q%Zec0lYwGnlcV6- zplP3a4dRadYJ#B^_jI!fpC}~~Cc*3~t2&a(JjB2tE-Nydq?=$-QA`%R+VJN2(XF9t ze=-o3*gEoy)mA({sMx^e)J;26P;AJIuejVcy|J%*gw?3#d0G>4&rJG)t`*m`VTu++ z=iNaBDr@Y%U7&n~IE!f^9QG;RseRQt=b%N|DxcSvw8#JZwa%(q#HF(Q@>+xsZ-^xm zALuU>R#l$A^&V%OikBnbPuu<$qICmZRE~YfbZBX6P3?+t1<DJ9SVE*FFz-il#oIP{ z-<C95&$DU2s^Mie3vEuIJqh!o@eOAZ&c>`Zd-z2c80$%ovIIQUvD2M8QuVOxVrb`Q z=A6w6j*bTug6a_*WtdfhYCw9m8lnlE!Ev{=t&lgMm^By=j15l)z@?jA7Up7d2T&;S z?im@gi>dQb4IzzD5N1JHA>a?DLpPO}Rdox^2T}~=o}db2uuNkiaglJ@HU2>fjprB< z<l2kG&@mU|8{$@Ibugh_thYcy{Rxk^;NcVZA?laPG0Pn%BaPkh+I0sS3@){hyf@RB zUFl8t1mb?1W*^_&TcgBxwcjj$YXS*NPHiJ@Vq48@)WOs~O9lI*Lq{t9nY?Iu0G*~F zsJR)nM7aU6fwX-1R(*^Fw?>}a^%D;b&RHaoDOKvV72U0Zs-B{By%_{TGaZ_6{rNI? z*{aRXG(|xVjxZb{Km*JJuAJ323;5*Sp7TdSQqq;`2fnyW%4JnP??@wsnVJ<_{+h?1 zGb!l)P=vG`4$X&g**IETVu<31Q;0)EB>iwZOGX!{#$7VC!SS_weh~lnmssF3bQe{O z2ns3eA6m{R>D~}mH{eEtFuww~GUW<OSy-ZYUq`|e*nlfn`*@;E>0<bIvRB6fvFc`c ze~!y&oEBn0EQ}T<^l%c2k&K!Ew|?ts3U`e~@%luXgf~V=A&LVY<%vSJm8)wST4EJ) zD=luo_aNqwsPv_H^*)3R9I<DY9-V`7=roqcciU$p2ZojuW<McQ4gHf4lLv}RI@HX@ ze1TVzmU>mwf$?w#-h=oo`E>U(gPrUFF(uqifEw@5pACH$+<R-&bYk@#ab9)HTvTp+ z;|m4Yy%4My=2>x3ZZBKsKS;e>SMhWv>@F%N@2<OQ8DLdF^-RB4ZQBuBQKQl5_IdX# zRTD7#@5UR$zL|4}!%-V#TLyZ1!Kh8M?Kct@PIqn46p0L}gk<*8owH|CDg^5602q?u zXq8j=SEf{2j}xWS5C~ou%uq`ay&B~&jy1H@7)5Ei@*D~IiKEt=6I*SU!@nO`l<CV% zC3q1R64^zmP2v4>`LHNHHmkSf@K|V1G6_>Z{iN-$-?)HXFjW$1U{&DwYorM5iDG|U z<IxwRtoV3{XZ8ysO{G5w1Y)SBAMTH<)sD0f>#X_6y5mG0MTcHvd(H>d+D_mW&ebSz z^I8wx3+j8ra3v)L%eD4PajhOV{>3q(7t7l)d+AM`{Tu@q3U)y-iQJUUOVyKfLVCGM zlQ3B+)!W{G9dW%dc4365&$(g#2f2H<`TY%0LRk+2<tP!2S#4klu8LTXd|kb%Iq$LS z>uu=E5BfSa7LR~jFgmG73}lvgO%Qf}VgnCG1m%h4ZW;H~q=d^1StUp$Aw_{E_2@(T zkIum@S<>8AR#qCOL=*jCK|2bVC%K}ov$xt6y%O3(w?z%XzQ7@fgWO2P#BuBNeT?>Z zhB()BsZa$lcy>pWAJ<83+XtfU(O8itQ~Zg0eXWI(68vaEjcY4nn|`tHaZtgOX76ZM z*MW+Sq@G2d`OO^0yaHE76j8={ubCHigAhOf3lal5_F|nwbPxG51Xp~G3!hEz(h!sp zTI%?5vG+VwqEj+dd++pf@R7?FEZG{5CnB+ar9>mdUwX5N%Ca_F+`?Sayw0<j$Wov@ zl@9*L4V+hh+G{FkGC8^sf0`eYrQOz1NnKQcyP=`mqS2U;xg$t{0#Y*`J_aM<VqZz_ zQ=!MZqi!WA`xd=#)(Z;4Gt)Q;y~&kJy!M-vv8-@qDRNrM(&pFpT$egFfBta!$#H%` z&<r0kM~rA&k_;J(!TmWpxbWi9uTmB0ntKmtmP`Dat2Gt@b5dGNXr!%F*Aa+f%L^4c z^V=nEewf*=9*8Nk^H}s841g_&?RITyUF_-Z=+L02Q|GZQoH7lFw1Jqm<=-6N?|ZO{ z?E~-Y6SrGQm3R!`gx@_ra`-lwRx2hJ*$3Bo&JET84cJsE(YAi2nKOJ~Rt@3<{*53U z#a9EDt+my;VC*}&IP$XUg1N17zU%J#k@PC6s&HaY%uxrrB$L<`FTk6SGv@?=MdV!T z0c(rn*#U4AL=vm?^<>j!zYt>4Zv&wMI0p>f3`H>fu?qhZFD#C+%ov3%f}8LH(&!I{ zw@3v!x$Qj*FQN2x@?Ly~u)f)}^vMj!!By0AF|8cJMhuxUELk#{*YIxIPp<AvU2Y^f z52ku6ACCB|8r1bZ$IxK)#Mt^I0y(#a6Fe4A|D&3dPC{fu_4MlxLPUb=T|;-UA4qF> zkgDu6f7~!UEkhwjEUjOV7xk;Mb4;KDmJqNQ$$8!FcPoCMbYSmb!xH|R|Ctj@WQsS; zGmgZWy;U36x!#T)h|Dthvm(Z5z0E^BpcGRnlpiGF@uNc&**`<oCg>Y)8~JF+GdLPS zB1_}A0UMx`d)R=9G`Y90i3pmo>EGC{b2j{s^U0+!#a^;1c^MkWyKDe?J))L(+t<mm z-e4*ck*pUU2yB_9(~jp!CzsprC836LJ}eh5FxjzT(8{3_c+V3#&t+yQ<~6CD3GQji z29frNpDmbYJGO~}vmjBE6aJXXU37XDkhmiQK<RGYnMOWJl#Ynd$$2XV2BcONOjF+I zz%PTy`&E6MIvPf68WQirQYJo|)GpiMewk%iP4-RqHK*bBk505Egl4q^sPo#aBKot) zsxi92-gnM)O)Zj3kt5!sA|XtI=m21zv~-DKiPBuHXgiaBP;??G$O{K~43>{5lb+$A zQ3WiWG~rn|pJG9c6OMPiUT)){osf^q6}^cPmaoui&|viuak+2xeszqkl?Z|5idqSd z(8{2$_FITZaCZdYqEmw_+%Idpu4-bXkCzB)k{$Cf&a=xl8d9+ory=u_$h*jZzqnVI zZ5$?vp~9O6c};=m)VN0s41hJihiUxUh}kjzW)c?8rryu|9@olxCY0P-)Y1+#-Femc zSe51376q<ngAEJL$m{qJWHj>dD=hnFrO&*$X@(CiFdv&jot;;m5M7;d_j|lOQg@3o zlmEpkKrp^IzzMppWD+2OjRqf1rKGVOQ}_stB-HVTwF`<%A+z)J^NRnc<Zl+KW>H~6 z-CC69P1yIcQL&KJ+hT1_%V(+P5<O(;6y!MN9liK)8phn`l<J+;hb0akI5(#i_4fO< z9a7wzY36r0$QMe#+mVGDNgUiFS<x^5T&IeIMZ7z~$JZdsE6@SQ3s_%`{V)_2o_r~+ ztMk93F`d@oxXCtZ^Vn%qe6)yXh<?fFC|+ND1~E$*G}c~FV-2tza#}Tp8Sd&Z@Wq}+ zLA);syyG-L=^qc;AcQ(X49}VMsA%H$LV;)>ik3#R{Uk6tRQ3yAnZcV2SHy!@NHNPX z1hUD*t;qKrwt$InlS`<T2wb46OVtY$<FFZU6o>N-P=clS)~G?2!Si<eHstoul!h-a zg7%QyJ>4G|klb$1k#A8ypI+zft?ei{Nh>@Z*ux>-=1k8;-g3DD0!COgAl<TO+(QPI z&;#`Mp_|MYQ2+^Hi-_10A{0m?x+t1P5cIWJgKd<a&g$HUlr_AE8Pq_}PDN=k&3TuM zcT`0y&a9<_D^!E3ZNYy&$Hs+*vqcV?;>i<fY=5ES8|$8?ui&L+L}4T<4=#dHjNcVj z7d$7FT)*wc7hxdKi<78t;~<EbQ-D5IRZ@`TeX>p!tR;9~EBl{@g9$@PVcsA%YyB1p zhAH_=AI2=sE(S3K|C+~%Q!bs<bUm_n((FxE3|JOtpA&ve2H>mg+8baDb@q?nU$w|_ zZJw=<^Pro~2ImLoc-3!eCp_)C6kfufUKyxJ)zd*a;W2}gyH>m4^IS`YCx={&GIa%d z;mNPHEKHGtE&7sSisrUe;5S}_&7seVk^;;TsX8y~!2h6L59l*FD=bIH$6^iZE2uHZ z>n*-Z7V-y@09k+T8*Z>23()Ukfo%0O8*c6GfjQ7;Y2r91P|YU9?f9t)fy5Ydk!*&` zQUf$dQiF)7kX_Si&tPieCW4a(U8bX$#vFb+!&%~DrZec}>-;!4B-ovee1`apS&a`a zI#B9q+qd3*v~Xfd2#*jlhhwTI7#4NhSU6WV1)Wv+U!dAO6SF6<C`lW*2_A<Brz<7J z)1#RNARcoA&5V2d&~`D<SMGmseSVF&Q_Tn5teZbw3odQb0oiKvJZ!i-`||q{<$X@u zoEAVdCWs+a0RO$@uk1U#ss_XPzA^^X$xreBRdMoRJCQny=wkDrOF>J4o8<<AP~7A8 z)Yz$Tg7zA;yHpn}r9_qTIjj}}RC{6l*QuDM3U;G&)qS1M@-zAx=+~_CdMr64Q^L)n zphtvs%8LlIK=qXOEuKCGl(VmKit2GA!5Jx7_B!BxAY~6cz&AAwYRa&;(h()KH0q*t zDc>dEa6d62_qh@Ey^^9}k$Q=WCQWemP5;aQf?5WQ9GP_mW!L~>MweLOoS=ynqTm3j zh;pqMs<(Uk99!3+iNQ1DY`zY0&#}5Co4{(ycK?Jc(jqVwqA)>5#y2E6XCiU!C<Ghg zaTkwX3zPJh{Kk?T^sf=G=W&10wRTTX?4}y(xkXz6C`XbnmLk4{H<;H%foW1s0X=CT zwHrGfqDE=tIg>DV%8HrDjhxYbE8XIPsA81g1_+IZ6vCr3PzA@rAgm$&eDE}U=s7u= z0Tbs+d8Hr-qiiIQK0!K)Vj6++lOX=b0$X~od;H}$aC~B3KI7-5H_PzfWgu4wfdrC} z>1lXgOa??m9j<6|#IfonHx<n!ulSP9MQH*!{jmv{**Do*4NElki&LSnz#^aX(Fd1e zTCE?ql<J@$&q}g7?HX!6JHZFY?#LJh<;JjRC-k|}s+O7Gy{Z^L&=;F3Rbwwp#e!_< z^h7Wxw-4LAv{T&u^LS4>T@s>T#~6Z1s&W)N`59JS;RH!bWv7=Bw;#b_z17<41q`s1 zs;8pyeMr+T3aStrnN>_-v9KC`MJf^P%L(Csh=pvP>aYsx^yt11M<OkKBl+?M(yUsH z{eat3^ec_?njXt+d69OM4tN<!Tb9@53>x8)n(4@zEaB+!8mwM#D1IbcrN=Fqmyhr~ zghHASiG74;*%3Ii<UTMOkGuIs3nn6C)BZkYdh>k-jbkv6KW3gfJsYn+wlb#+IZGXG zEyW_Zro*N^iAXNjgO&~5zl9v<HB`Y_i$lHuj#aGE&(YMV;*{*q_M!J5JC~RdqhqAE zVPF9q-EK=mDU_1LI*?@BCT@9w$`{WXs;|}fQT%}S9v+rhUvn(~Xzv+4n@%H_8f;F* zdQ`7)jNx22c2S42G!3^Mc5S$dR$0pV%!7lFmffDxe+=C;u4>ZlZ_;F1Ak?<BB&0oE z6-dAHG&^}_qRk#(XXwk-PhJ;j%<x)!#IMWc+cO18S=^X{J&+m(9LZQ_U1z7C6JoOR zD=|#`&8MAg%>Lt9<(tF{CIBK(+C@$|n~zcL9(JJ1@c20!ihS0ROo$I@K&n67;F`A+ z6mi}gBtJH;{MDCTs0nsCF*UzQu^kFA2qVlKBZqS7D>|2~SJegvo629Jofl80B!q@r zg2A*+e+Uv)V0c{_a0?A;iq})oDaKGCG(kPaizv5$xTUZNW9>A(h&VydE<Vc`WiRi! zK7AY%Nbyon-gE>wzoUZa6PzjjH!~DECyACvJJL>>bMi_NcW~c=D70XJwfH!o%P248 zW7QX{PL?W=pP!ZdB5we0zx4Shdf?<0rG%WBSenU+U2ptq`RP<2+;t>ggiA;$ZAdE) z0o==B%vxkzz`B950mEYWe|p7TNRTl&8T?E&_lo%374`w?@Gf!{n<Bh=4_hGR4HCTR z-RL-1%64U*FM3i{3h}zZxzN-(VR8ABybJ`n+EcH)%^JgL?$ossC~uSs>dgYBbAs@y zis=>Q5(@tO4<R-VG!jUaE;jb^*lZO;z!Kq#!}4ALg-1w%!wRrFqiWs}-aPe()uo!X zy+5Zpif(M)tP|z!W$m)il_7X5HSC?>_5MJ2vcK~`$6=VNj51A*6OHyxsJG&Qf>Z&y z7PP(v(LyhHjfRFOp~4}D3p}>}IOJaeEe3+-2&b^cR{YC_+eVrjo^OHKvmXwIq}ayD znf=<w(H~X6H=T6uUJ`3ngs~+U&zr5x3b4I(e|z9_W2q50`*oC~r8bI8akJdleaoA4 z1x#%F#>ZeRz&YAW4LuDI$n!Qdf>twbedO(IHE2&Ay&CB>Mb4^mN~w_L8{oJ{2P+^k zB@<vOpgCbTegTGx7AfT{Qj9zA7WO69ITH1!YoW;U$UjR`p-QSkrx1uBx&>Q=WOMul z($?^|;Ww0U>E!&Y#^TBsN>cdKV{f<;@+tP{gjDVj4oksmg>c9aB5rB{cTUYw`27fV zB3nrNuko`i#~E6ZH>Qb81?EJz+W}!;7J!bqA~>@6<16iwyq+I=R<n6_#>^5NysRMJ z<g?yhPQ#+#MhlFVW`P{GUoFOYj5^)03-uM>=p0bLRjOZa5QyrajMDr`4ler6$=sFE zB^?>l=wEVwZ(Wdf?}7Z^Ok18Ii5jAljnaDGw~~PWz~Dr7>ZTm^>5LZP<}n!EH+)W# z21=nhp~rZfu)Jd?ASw>FvS?fU6rzz1U$55ZSYXK#8B&Ujd1~e|s+TAvGjZr+?p|VR zr5$n?QvXJytMy71EtW04xRCeL%wuuQ=lVuTt72|V^qXd%J%);oxWktkcZNXL?q185 z0iX^zak;~VzA$n*ujlfg{~#jSY}@pX2f3V(wq4K2XuiPxAS@CrBUj{807-k4L>*34 zw<Di_V857Og0HpiLjMuGtCc|MH&h`%G4lJS2-?<<?>?F~)t}c7V%MtUPcr1PmKji^ zTbw)6g<#isdMU&!62=!T?mCx>Wneea2tXG(mft_&gN0dn=|bX`H$Y40exM>(52~R) zK#fcJ<&kkJ+|q(i;m*Fy?N+qix?&A1?_Cpasa6vB#+EKc;g>IbTf5fJ@Rx2sUnCZh znbrAYN%*I&adD5Kqp7Tg$~BGA-2mx(#{6SZe3;_Ps&>lcq+mV<Q-t}8xV<JS>^=&0 zC`6ndV*9wUVXh@2&TX?})WjrHYdR7nd{-luRrlZPD@qPax&bgBM~KPH1Moc6r6HQJ z<VOF_?PGI$)jVzS>;<w*q8qkg*7BfjZUnPr4i$c&Y?~jeJ!7`CzWN0?3fy#iSR{6| z@U}`Hma1u+8*@Yi0QsgKAz8pWNj?Q95G+l833r;ErT+L6slx94Joar-l8rEUid`oo zPo||J2MLAHF6DELsl*en4k2OR>fE=7wrIsK(H|=hMqtc+;T?l}vM6WPJu@7_@w#Jt zMfJ8k1`}3o8n6vR0uj0mG)F|0G>6{)5jI>(7j9&kN$Tv!7(cW$N;_ox;>0~jODY_7 z0fxVnH4%5bSxOFdUy_NZU4`j~5Nulp>&?8S%w!#SO0?7L{t&P51%|MB-6t}i-WG3p zMviAZ`hJj3rwO}nhoCUGGI;YkvB+6tA;J(c*rzY(Aw{w1ZJWgg#JLU=sDPElT&}HU zf3(cPEEfs*{R2&j7FGJqy{;wf>y#-0aW69FZP-UhmUmQpi0PU;uL?qIpcG(7(GZw4 zu=Ny+A-uDz+JX8RgTa~_vEC9s5RcV1TQ`#ercPNj7FZUe!0E4~iu-&+v?)NN!KN}< zIO5bjaP2S>wc)jYE*bDNskHQRL=<k+BLiPC`FSSh7gum@lw}_WfIxb+nidv9mHTo} z8bfgMqH9EE=cb#x6JO&A(gPMIN%49*Ymzcl%5p$Pl*RKXk6CU9*m&^?8vWk$=#yZj zexYwryq*E8VG%I~tuuRM2WfFn#12)KD?X>2h@Tywd)OfcW$g#+CINi{f#oS@a@akY z$)lOIEN5v36sPyGRH1#75Zf$nV`VJ(Af^&5YDcDlFL%VCnTjS5ab>{~s`D2Wiwep$ zDJ15cR^<#^F*kv+grse3LV(nvejEhc1z-DT!|Ni$ZR*?jd9;{bZ1~P*#C##UQ2EM- zH{6aGEfz;_CU-wKjAo0Kjqu}5V=FAi!56@%t$X)eWgA+7FN(U8Mj4wHj{7wB!Kv}w z`|NBASy3HtoH-x)IV&{RWo@g)SI1+Bt81A0IL0pLkv3j;@m9@l6j{_Zb@yE|?s~U= zQvZRaDX#g(zUE-=;4;qWjj4f?57pn9&b?KPSO|!zRSn>)#^-s?>F;y;`W@eLD1WyL z2z%+_ocD8lTGe_#q<TjR*&U=xjYByam4POIP${4@N3-VM0sp$P{rJa8;i$J~<VtDA zQO5-Rt7G}=VNXR|kuBbT&wrStS_0dLN~L7z$gC$LKhBL(c1c+_Iud5f_mswP8!Lj# z7HZ+luhFbN;)t(r`03zG6gB=CIlHtqJ<%%GrTi7tqs%dNgBNn&-zY|z$jcvZ6D^MW z;{S{Q!<>s}3MNyIals&aFzJ?l=yo^6Z6+6Gvg0N$6#TfGA%wM%K%Xc+e4)o_=jFeG zO#hqRZ(!il<L4Da^m8hytm<66hTC!IsGXK=o{qNZ^dyb%Lztdu%jnr_b9VsKr;j78 zpN^{Oi_5o96awxL&9KmiAR1B&Dsasv`D(d%vzyyr+4%X(OZo=*@uuTNEFy6T1=ZnI zXo;~$qErRC8s}d4wMs{iZ8v2a9|`V%np6p@{`tHyfTP)ICja_=U>kEmCJo(rn-*Zl zpW>v0PAp>(wxb2#Cbv7YP{T`0kGyzx!?w*m%T6t8S6n^ChCioEBp;Hk+zOUE`|f1d z+Iv%(Q({avTFePw0B#I1J+4%P{yxWPcb<E6u*-;I4nGtuz?sYIQ66?{>WCHh<fOnT zi;X?2Rs=)^CigpWCeE8XdkG7fN%*Nz(pZ(%E0yrswM7}ECbfq+$Od;F9|AAEvjop} zymIru^FK({Nt3m?p7|l)u2`liHm%4kB1nML2%rDFAGwvPo^7er;Mn+ubJ;ArgnI7Q zF&r*Po3B>{TeHAR8q9kHP`oFmz4hHYiq&UIt1@98$@u5GCJM7H?MGd}_d~(!<!b|F z1TY9{>CFXocZ>y~wT)oU+?7tr5}7>G^hK4*HBuZz*MCBs&Fng?BU<>;2}Y4XAn{%A z)SDZ_{uP@G+2C*}1*HcxQm)rz?t3+U6H7ESA1!v@d%7#GX`&+&V{+DIRt%8-&)`b9 zb@N_okW^=ULf)qJF0n?5#+2pj^?T!Sa`TDR9XLKa@;I%stP9kis|N~@#^`AFHg6D9 zLNQO(a~$KL->v6=Ns>{Zh8wvC^PG10TJ@wHN(-0J1QaX8iSE#I1eAAntNmEFg~+1( zr>8DePM!^?tUZX%P2>{*(RjQuXdPHm3jMEP9(=Af%uRKrI(8?=X|5)$bjAzY>PT5K z(-)unok-r}#Oc@r)Z3*$@L!O=XjfuzNe3@&YU;8;>BjJEbBP<(8h6JJWctJIrqibi zrZOpw%dF(6cZo}Njr69j5A_GKpW|J#t6HsgM(cXUzgD2bb$3+YH~VM-p*a?R`8c{% zhf1Cx;6($2G_$9N032?0uaYU{r%5j7Ks%Ss6U8@FOJLW-Hh7=s@DP7fA=f%{F=W8! zF72#)*abx9Q9eM~DAhZ9b8~Y=Z}HS*HsgbPy7tUHr@+ImYIyzh+F2|=RC99f6@i9~ zvnBlXvee!%_1<{$@c=wP!@o3WX*IJfrfY`E%;L`Eq=g5XE4j9#CO9547qL6o!AY(^ zl_Mdt)ME}R*I^Qa6=iE)lA#>p)N9)zzvnp>=24Mn@^O`4ls#B-hkv^u8)p0R=^3WL z0sLNfTA}_VHkH19;(&DeJC?{tLdsfxRHoI}PjtG|ktwE}jg`v4U|>jP#&ix8g&6Hw z{65d>58bygVqG12`#eBie2viC|12};ICXs%wKFYxwrT&zlp~tf!*~e_njbJMq&;ci zd?5MwmQ>12MBCpvU*Oa^hZ4eU8FgV(-i>gL`VzD{h6Pp<p$*lBh;7y(^3={q&uIQ{ zjg-d0AK82o=(jnd9viMv!|Rmov{F<F?)(|s+$+Sw0XMJw9ULSWdkkaM@;H9+l5004 zv{^!t+P0gA+IK3@@UN`1#78NRJTUiX)TY+$;k$+T1Se+IHAoDegopSS<~_BO2zzrW zvBeC`Bl1DwZzID4L~4;%0uzYdzkcQrupezD3bo|#N*ARS9jD*`9^5wzQH=`P8FjWd zkya;yja!Pef5w(wg&<miKGG0BE}i_e4O|AjItv9Hs@@ft=b#nJVD(R@S@uM-W7SrS zaPYU9kAQyWb=E5HB8ppEK0ole>H?)tkuiCz0vr@mvYv|8?}Lwq8D&`pdbn6Hm2!%x z=Z;Zm7#wZIG3HOT4EOE-0R$B14UW%2XX72z>xeej$AVUy>4ZGX9C{ZLfX=Jt`=j7H zDCy~X!qmvD*r&`#G_LdvqEUdM#iaCwKZE0+dshJs2y~RKB8I({XFQ<(a7bT|HQ8p> z6V~ZH>>v!x$5M~xSOKMbdTLa$%~6)Z#kJN_47@zV8`9`$@2!A<Poz^oUkDHZu>?h_ zBXxE5Jj9TGg55jA3kVM^wZY>yF=K+pa?BN6&A$%dEDq2t4o}}bCP@V<V6aX^Sh{DO zOU&2qtYym2$3GntYe0U5Vy8@1pR~w#4^6nF)4vbzNv-L!Kh~$xEQh~uNFy1k^rHg; z?Hlk6)h*l8paj~!7Q2vZeRc@~DoDRM;HIqF&ypFx<@BtnSKoh6DrU)E?R40yg96^5 z_nxkmGNaKBojoC_ws85vptilhY+5(w{tnLU92|DzNT5d6A}`A|UqJlIJzE8Uw;A=9 zbZ`-BDw^7dI6b`&X`0=`1Ja<7rAL=qum+VOz^U^-|I}oEj|SG_uzZ1EeqqYdJye=< zR8TT~W`eT)g+2QM@Ben^7a+g9xY}Zc=t7LEffNQl8yW|gfJH6a&27^a-&j&BjSK~F z9NZ;)3GDM534=&UTCGN;=BRNkJVe$%X=pYbt+s4`iAq_VHG85irrvb-twTpvaTh~; z1HPd_3j7(ap>?$mZLA`hY_cd99?~udTVM+_X!;%E^wuVQxSnD0=@oZf^3dTC)N||! zAi2n%vi+^Y^-10Lk-ZSmX2BnQr$R!BR->EW3BEiweViT{W$*zhtI>m&56jo^aDi_2 zl^xdIM5cw75z`}BH|Z?kNk6?WoD9wbp3d2~ecSl^%c;b`$*Z{J^5`CL1$%d$CnBQ- z(FLi3_J`DKs$J5a-EB|6@0}Rz@Z8c&;Y9s{?k)t&K<y5fwA8biukvpZ&Tk3<UEFak zj26E>B4uT|D8qGj6!HCZ6jHI+0D^nLY4su|FX$wtsc7~cUU%zC0CYaKXn;moy9`vc zf<@hf0W+|_Z|>5=-ifOx+xPV-49lHUd)sAvM(-QmE%t>lE#d+|hcM|+a#3{)7ln#* zGXzM0kXaIqf^Czh7K+Apke)bAT>`$3I)L#~Hp41J*rR;llbwh-GTr!ms{tudHu$(e z9oZC`R?Gog50*mf8Yf?F5V5fZCa!`epp%R`0QMW7oGB{+_zcXdJUrOO{7bS_3<s@R zAsB#FfanyNZNUTHdrPII8WsOmUrfro0<Hw+<Bv@mK8eu|Lx%6fg73<cg_C2cHAT-^ z|3gT&<;fVyeRd@3i8JC=W|>n<ra67l1BQ6(o(iW5+hK2JPY672q{oCNMOmm#cS?>h z^dVEqb|mE-+~4e{5d|mY7k7$&G2p8fKy5OgY^PSY?()#>c}AF(zmw)q!i1!Ut+c`~ zn_-Z^H4N~}93l&OnjjnF;PhXh5_n9E+_&$Rgl55#D{7;l^9~v{VH$T&UW6x)GV8DP zYwVSdA%KlVpy`!j0Zn~Un6gIwH0BbjoAaZJGLW`yqe-}y)UT;_Vb0iw3V%s;tt*Y; zZJ6XlAGoQ%bMC;H1%Ngz1>&rH-jg+m!^UHZSdeE&k0{cKCdF+MuneWvAhs`<xZ&`_ z<bwx9M#j$a{N3fL8MpcX3nT^g`DkK~FxawA>wL_<qx$JbMrg-g5=UD0FW`YQ&v}FH zP1BO3i0-2FeT%$1c{2#T8jT8Sf2T2OdcU<#>xO+39x8O9Z$u~ZwcactIf>2TjA43( ze#g;K+49IA%(sUfvY<d^={la??I66IgbtWBP9|SnQ`x}gX`2^mT&3pHcGA|I)Np}Q zBknB}yjujcZ=XRk4l>Gq8aH|ukh+)2(EiKLooVEwa4iL!KEx5a;3fE_t~Cht$V;b= z-=`Zo;aTW~AHfiE1Mofg70eD3%~QOdeUa3miqNc`qa5Y;w)rgiKGWWA0?IiC8t4kC zV~W@7QWW#F!|TDaegeNx8a9^uYMB(AX<hlQ2&CKO?-Vl1^^bz6bPpgR-bEhhd!U#4 z8YR2h5R^qpVH<1%ngUwVi9-<}O;bh(6uDu*L%+sE8WW5s!VDa%49}DOvbJ)lFV$~u z|CAhg!Z^6;-j;Qx+>=Fl%Xu{dbP+sbfT1heoJEp^^#gkTs>(s+^cjp;NfQ}~LyA=D zOU{6OXf)BuB28Y^>KyfBQ3nLqSy6D|DlP|vY?$t5Lu(8zBG72J@bDaz0SV<U47o1n z{;+$%@$m=-R+I2Ys$1N!{A4YHuuU#$HT`S_fYXEbU2CdXtW@MssVvk2OG7tqr=;ag zWPZsTH6&)3rKiJzHyz_z%d;d71(>xG=S)K5NPlCiePftgh&78=5q2@k)iY>q+ugXh z`xD>ZY^WW@BI`(wb-sYe6|-L*0%uk*fl)!OH`M5$VbMku_@--0!_cOBQjOlUGF0)e zJc0?7eI7o+HW;w$YpN!)ElyTL37>-)z1+hq(5_FDhi|CII%Fk4>fK-z1{-?#8mRQW zZmVdBj|9=kghb0rno2>mrvzjhJl+!kilw8p<5g&GmSm_dXF?K7^!kcPBwij)Rtc3? z^ec~U`fOrXZ@^L!F1?m?(v;EEH5vHAk-;FGJOw&e_d`QOGH3|OlSMj<Gkz4!vZfbb zGL5D~b`e%^uV0E&bE^94mEJ)VBdr6=M%_&|wle>OOK$3jdvhw}r6N4Va=F1Omc(O% z3_KN6^SqBb_E>0?i^Hjzq^bPhQJ#vfJl8AE2T$?Mn%)JlL4W4?qbcV3alCD=ayI!U z?SmlL2}VTNHO3%crOoW0`B&g_AOFZPSn72?MIL@4I3P1Bhy;@~A18|T^Off019#xa zjCCh4>gIV8O-c4%S=g0rb3FPkQxzW7lEF`a<GDzaH^S%0A`Vym)WGLYmzKW0$Kb*g zW@H>K`SK1D4rBIZL@a)D{8R%z)K67Zo$H()E}n*1rY_m~Sj{)2t)=_cljkc<eOYIc zQ>QAz+riM#2)6!wkQ;ztY8y3{`0~7$+pb{`y*%B?r~q!1cVqKL2mB_9R|i{uW5_U+ zap>-x{MsAw=YD*wZVe|Gq|JBA{JpH)^0OxPX2gU>bRg0QQ?kzAm6X6ZY?@+r7S@{N z(Y`;|RvuUykUn-%hdv7HJlFf?`qnN}rX(|D?lJY`q2@o6TUcQ&MxYm%uovRSJ(;`f z(XYy5u-w!%oz5RBs6jMfgH?mQTbeOUyv!l(N>P^G##E({tcB)jt<VH@iuEEst46(g z&3D;gw02YKimCvq4kl=S7UOH4!unFQl8Oo5KvtB@lI<~-Mk-I^(!g^z?=B_|Lsa&< zw`<T5F^tOPMfp<sI)9ly=XjlMz0^4@Df5YSP?9BCAYGE>=Lehg{9XCZlVzsCt%gcm zt8xjSJHJHI{oI2HvO`+vTU8Yl1Hh|ackL<_`)f_ra8U)L<Gbq7q0QXVj#NG~Ban3} z*-K)>d>anV+o&)X^g{6dx(XFo2;AJ43#PZ0L0QUKYg@f<!uoT6LdC?6d2<OxS#DS- zAQQ?8QLq{{R(F%!QwxeA%&TgGs)M)hfzO{mGOBOlyjTUdF-#`*;7EV+XNNnt;n~T4 z@5?S^#v}m}C2wqwD9-#kGge3$2IG^ZsbpD`YACjC?JvbQl!Yo><uJ((rxj)A3OcJ> zea$(+lrf7RLAX|U*V>G?Qj`4|<tkh4#$cA--`LeQx#4H^hP!mio$aajkMlA*8Pe>& zHF`&FmnAWj*mT(5buaxwhPWE50UHE)A$OG4zHl<CZhBMeKl0S(MVvSz)l}SRb6b>C zbyNZIGBPZ@+ztmCPut1Ut_!*JbZxWEInY-p#>{Bn%%Qgkz|N^hf-27)huZs^^|_K- z7!Ijga4)V|np)20YSGo%IlsGSN1T@1VZQXATtt#SD!Fr>JW;IgxJUl_2D`kv1uD>N z?(dYvbOSar3)fXO32f<hzNuYWI<Sn6DBmcRJ2c5r%5zH19jt!vb4613p5Ns@)eG<s z60jt6Ge3aG?*c%8J0<S>)jBwKtXK>kx&+SKkZw&!(^^OKQ@yv>zwTqK1KtvrL9QIj zjEXd={8m<5Iag&!>wT>dreOL5hcfEr)-6N%%)9IwnA5BsOtIGwW^z$fT^$WmG&e8T z9CJ#<UcPGg?ZM5>`OHw86ML`<+?k6zJJhM}#E<reHmQ-(K0<@$i1p)5m0w`c!*z7( zCX^zE`%WKDywV#pbUblns--qX>|@<pH@C2zJQ4^Ii+JB@kNFybPcs(PEkj);$rReu zuA`M`^8Kw@C5ngd<ox<a2OWFn$e5g=dSKaZxGxrU7AUj#-sFo~XG2D}RDX24?Y{yM zU*U79<b88|f-E~{zPMp)|H?d=fvcGx88yV`=6z$XZlCj=lQv$Mw#SADRQ{wg86`Sy ziM<P81m*%wvlR8yZv1J|0JQ3D$(83+5_AThw9XS4VEPfXY6?>2O3n`T&y|t<v-Vl( zSm9d$0^qDhT-SUk1HJTLnF#0NwK~;~pD}{|@Y>v|4~dW<v(wUc%XK^yBIT(F@C0o% zKxxqN%wih!AuEGsQbQ1wi73SOh{;=oqkB37k7W!9lKL=+r%m;CjW0X7qysq{4{XFg z!pJn`f?;<%A0P**xwM>D2ADQ32I@{MymN%JluyzCzbEr*f589XIL}khKP+WX%pYq; zb?yX6V{3%>&yNne9@?qoj9}fcS#==A-OS$RsG$^+jq7c#DB0<;MP6b&aUNSp+ExVc zUiw@=iB)acceOGb#5Pqfvt*OCPQ-fQj%QK!3#4p&>c)7`4<{C1CnoR}>ec7<tghh` zYXLv^x)2DsWV7h9K3Y=D4P#mrL-xDDOsuE2P*KJCW(y0LZI%=j?YFTuf23Pn3WwWQ zPWJ2?70Qb&3~7H%Ti*5qv}5?V#=f8Ze~Ntl{l5&S`u<^&Y~PH+HXeMlS`SCgzXvrA zJ5r!zJk6(*stJsVv}lUAB1HyHHs|mNp5+%^CqZ8D5yJ`-Jt)OMA&@f2+)Wjly3HiC zO_`#ByOkLa9|QIYaWO?$$zm}e?8t%KL#k#Wua3BD-{Q&M_t4x72VA}q_^Kk|JSm|Y zyV%^Osm=R;_cP`<6Jjly(B3DYa}V|*$8k`nI$1{q@w6}zv?H;k=lFGAvV=6budLtz z+C2*0*#i|e%-nw{IXX2pdt1**$~KeGH27!N{%SEuR4QnP%@x2j`_cprJ625`Lx_M> zMjJ-}NL?P2rwIWELwaS90!I%PEaB1aF{H*iRHGJ4U3>|L@LXGp7y5Fu0fGL+w(j=L zOa)~pEl6ZHw{tytw1%H~X-*XjtKbRITwJ5w(O~4R9J^`s@!~<El8MMj`rmzg0R2q6 z2Y>L&#S=BP8=fv#HV$Q2Pk7=pTAzZ_@(Q;6kjiUhQLhjB@Wb#3fcWW!T~ih=A9C-! zoVQnNw{U!cQW$mI5})ikg>;*!+0?K{udfkip{@S@8YLp;Sl`IuBsC+zLV2|f3B$SP zL=X|V*tgXR4jN&95ne0!e+*HQm>EQpFvF7FQxdE8Sdw*2RFi#*c*3nwb)u&Flos&; zP9WD#<U?tf*h!lRnjj72<rK$NUE=RRd-2@kiUSg=#ltFausk(5D9z7>)|ZvCGbRBc zbfXv#2Z(!^N7%(rV9|$BP?UTo=qcBv1eV)lWX$0l5ZeV3i`G<_)co4yVVTcB%T)k% zU=W0r{6^+Q!T$AI);`}rC_TeUSn-wsQCwFPo~Lz49j{hNJOdWa<O4{7`}YY%Iot$4 z_@9aGZPY{`Sa9~1rZXL1E9dX0>lH;f%*AIf)%vDOaQ>2&DIijqm0T#!*KNO8x@eM0 zJ{sgX)JTIb-7Nz>Oo=f|qzLpeZfWinL|sy2#Sd>0mk;vv6)uiKx5G**`;$RHR37=7 z>%(jMn_LZu0!C={6t=NQTPWjfTvXniiGk)Dv641c(o+chzf!5OvCTTZ>%ZaTH-#^b zQzA`wjqm@a2}Z|FDR({*yu<~5!#+^`tv})%cXI#JMt;i~#J}J+@-jYt04rChPJhwA zZ!2%(=OfbABBKWrz@uD49@-&?_|zry0_Qj*O#rj&b)+$oe{@9-RruzcPz(+92)7RN z>Xj>P<v+`hXz7a$==Qa&tgyBCo>FyCfm*~t{hMbsD6@fKVkA7rv9UFDnIBVQhnjk= z*BxEox>a#Uvgsjtz*q0WhJ8qPLJ>&g>8=NHK=87pm|_7hQJO$}M|2Lv@*wW?PUt>G z@?dDz9pOvl5MvFtrq$*(41#diYwhY@9d3f_;h>Fb?&R!d;67hajD-%rn9+xu;l!r~ zQ51fNxh<+VQ$bn}D|6Y#NmtYGmDtGz|C5Nnv3T}O36rJ9fm^T2UBf?N+puQw=Vrt} zMVop;`uH~v%W>UYb~N_mzYpVAo;Int;14sl&nDB=e=HXUQwx`*9;Jnn&HIDt6hu*? z-N)gK_m`%x!Zo&SAA^bWzY}q(8<AquhyP6n!Hf!lf1BvHgdQ`=QDKPzWH7~`n+8~- zA$}|d9hmPARFca|<wRwuN+gwb4<WQ{;&gzGP<?2iNO`i!0NlAaIIyt{t^3bacrA|Q zANl@;r+zPg=?KziU~ei~sn}54ce{&<5@tW`WTiCu5yvU>-W@yEM^+>Ze6+Ayy;JQ) zGm{7TQ@$0ebYptKp-WUw2^4IW$j(@Y>h{7G(MwUD^t})1YiG9w7Rz3RgpXxRh6;$T zsyf4V&!B{Hir>&=TpY$)v0wB;Jh06Q;k9qn{?;NbC80e}QO%N;C(M;aYG`hqd!TGZ zNq(Nn=pW_?Pe2`e*o7LSa0$XFOaS*?s57V!5T3>tnaaiXgU4V%+3%Ow>>u%Zo_>RI zX_%7&&nL(mH_nOy+LJ8Mmn6LIQ;Q|HcEhJ3f~L?FN;BNA@q}qz8iER*tBM+tB|IrG zvacn^EcFE-%2!k}2OY7@U**_z?Bf#u&(NdEWTeN<72IdghdlQTp1D*iO(*Jv#U(HH z_ha0GH*HpJXpSI`AsI{@7IyT~#nv5(+_uLxoM(z=c8K1+kY!g&Oq*=Aeo-<%f{hGi zo`0zRJe@WBbtMK5nn<T+^!yQjg1aZPuY7Jf9QKCNfs&S$;lqPG&_1R}M27m`C=pys zWKrV=Q+|UTb;Dp^x(|mjRDQ;xGB7oe`*#2xcQhP0+>2ID&R*f#7hV8)6LiOnH2_V? z2kOq29{nAoc%r5<k#+ZxXC6F|`SuIH$JaWz33)cOaR0F;qOYj@%29gsyT&uv8K!La zFB2LdKpz?sAUtWc`HUcD$FC=wf@KQhVh4j%={yRFV>LN~(VU4%w8WVOrZDJ9&EXw( zz~~6zoYZh;tikx?v$MTy_;*&RV_>%~_`ShlF}&+SMrp3>9&BOEFQMBT&I{;?ul$?O zb(~%9XKRs$+2^>dw=d2oG~M=Nz_HTm4vCDHiFd&yj03_{<Y+ZT4ikf~!fAWRJb%D* zAknR_Je}daI0283Gn*tatkp?NKG6AQ?uVD)Wf)|BsL_O|3XBK-8NLQjRB`ANHz4cT zxKEUe=8e)!i8sqYr&=gcH^wb*$C>ik*R$`(v%dS3#(29jvA;Y}IL?cK%6=3+&^$f> zMYXC1FTsEqpv{g$SinQi8$xZo<NEU~9GVF_24wu@5epwIEdVsP;4cwsiZ9;xXj4$z zPXhiwOEG)pd-B4N02yz193+my{Nk_M1<Eb{3*TD$K5^xl-0C47GE@9@<FARCqnW<O ztx7<AHzHw~+`f$O)8xu)SceG6_}7@sIK5EX9v<e8f2k*J>`y3$<Hgn2ttUNP5b4x7 zxwan~r{_pMK7!`|_S)=lZE4txinEpH1>|PS_T<9Cq~c>2Uv<^haX_z3Rh}DVnD8j( z3cYY*n0ctDW(KJJ2Qs+GF0mP>n#FCs#mQuQ>RS4whuV;fI1kDXC`=lwCAtP5eIvuL z06yQ`xSE(@{V!eW&20cJ(h`SbLN<IO>e%_-H%5T2^XN3>wRzZ&Y43H%fB}9^HYgeP zBh?>d$#{E)dEJveczX4+hMb@hjx#hl4AqK2la<!O6)~|K&%%2mN6#MlJ@vCaKaZ_2 zOO^qeO9|)eZt{e890UZo4ziN&uw*Zla8j%Eg21OdS?&lso3MsN^oa?6+2{ML@gw1! z2sy?h9M7dZVZEEG9It8Bb&<##uWe_U5xU#mz_KoJz@QWof4oZir4W)Zi&Kx2k4T+X z&?6<xPI4P+0hU@`;}hsCXwEh(7C0GjN?<#3E+>xM9DF57O!p!ys=WUX?5|%AP2E3C zVG(SgGO8_f#gtR`t&<=p$tFy1`I<zcR&<&y&fl#F)~$@HttGNt%~PlwKYRNv0b)U$ zZU_)4vqdmV72Wgs<cF$;3GR?2Wa9&;Vj#`ILfmAjYErW$cY3|2OcTE3O=6lYb-s27 ze-x*CxztR1ZXBH}c(WwwB9oFf6wKe5-qo@iyoXa%zXS>!>J19yZR72yFZZB{s!G*l zXT5bt)6rTgounTY&oGOYeu1Bd5|f5Bz<b+m!f6$<^|&?^!QfjXqS>H=@lxTzoWKLk z9PxAj0dl%qc3&K97!b4Su96Gx0U`uie$fo1@P%)l1vw%+zA@eOiW~23MRJk6TG5l3 zlW=cgSmg^dHa|H6bXZ{HvBUz+6z))%m(R3xl0m@IISDHDZJ$;w(!i{_w>$9daw#CV zT}{g_dT1!iUj37nZ?a2i1*EL{w6wsF_H1>NgF|Wee4NDld$YNzF;CFWCS0eg=!SM- z!k~$wCj|>aIPgZR0<Nv}8seg4q-}=gXI*@VqWXjKnZb8w*BOH$vY6|@6jroS7&YM4 zU?LvmDUG<<233+|-J)hM3BW@5<x@%kLLz<#rvutRCv@@!Ou~eEDdo|iQqvCivo&k9 z)ueAT5_g5E<Y7di8)Jg_OviL=*jCRAu!Rkw7-F7h&jpM_AZ`R6G!hq=sYKsX?Av<6 z@n8s58OopFe&55Lu$?(1-K!L2Uvaf3ae~NSfYp>V1HpX!GVq@(8h!~^OlI4G;2h8W z?1Qp%bDvstYQxTD=!U}t?V8CJ{;27d`l~n$ijedfTi~9&GWTWnElCQck<q25BL-2u zYmeY;!Bx?t)J}=zuP!v6$9aYEL+7cc&-fl_ET5bjaW)B8${^^FOh+hWfab|W*o&=L z{)H!d&wKM2mX4Sd;;^PLZ?NkDkvK=_vF$zJs^Zul8z@rRIS%0DauZIC1SJ?qV)?K) z7M>G(r*mQUUDpE$SdPGA?S?~;R*OFM>9R*rRcF`-Ap<8nD~l3Uxk(fgD^KFHtzE%! zb=`HML?x55GR<@crIba~8hOM5-XaNp)59~~puaUbN%i~sNLpZg`gO6|_j38NdF#Vx z#7h3S>d!*fF6iv;J}EWGS001}+;*R^gL!FsNnFa_QJ9zH+{8|i@yw?R7Zv-FAb=9M zkiLR(0!Rcjb}&X%sSGjr%@{0iWy8npQ0_}`w%h$N&pVF9wJrD#mZ>=kEU*TGwMz}y z|H4Q*XbcYAdodlX%gBF5U!DH1vFy=GF-rln3A;H9EX40O$Q5Ya&D2m8EfDF;{`E;g z>m$4aJRwpYuvBUNcDw38t0_z-5@)FsHas=5V2Cue7_t(&pQZ+i1(!#hMIJYj`k?!r z>?1<#v7#(_$cQwz$L&W`rCv|jzxa)07GU`fiRY|vlf#_&o+CzCcMF_{Tz5_*Eb^T9 zW_L_!ST~(*aQ1fy9<)p>oz7%IMPX%T?&+a~X@$~0&VO;k`T;l;rT|?2QxzH>3TtrV z)vslvhbOLN<gBKzi!`jUSX39y4u|Q|M^h7jMuOAw;4mTB&>Q0JodxB^X?F-ExSD?^ zt2C^(8{B*$MzJS%!JUlxz1im}$643pqTTpaxne{u{GF~t?ED5Zmu4R~V-YGiwCg<e zeToECz#bncPJXvc^g;}TIM~Pvev3cgYy2)P*8DfIx?sfO3J=eRP&(|oib?8*_D*jy zNNb;=Kkb|%q~Y}fW$#V&rs%?YH5Rf}8|We9LZ}$2`L^!<JT~!a8KX;RArixYF7ClK z(1M3-8nq@KnHp5*9eC1^7H%&lzf5j7Sdv8(=zX+FZ7_dtwYki=)c<iaTan~o%HVTN zO=_D1HBgCK61u~Im1R#L?zcMR19%A^T$-(#cbp#EuL_A5Z(Z-t@|MMq(%bfX(nW~9 zpk5lB=2L5I%=OsOFmMmj6S}PdckkkDaICoSlBzJ^dfpm0BYG6xmx4Jmm7&_$uilKN zSqZ-oVoSuB+V-$7^2_$_a{w>n9l@mPFo5Ojoo++9F2tscySiOevZ>m8!sqIVTfTZ5 zt4lRfo6rmXN3-vWxAxU+0wuzrniYCwvu(TEVEFgUj>|W2=Z&rf24iE9t$n})v^sEq z!<);YN&%Ua9VdI#@yAcaGbw*9fCNa!&=>o4!J3d+z*>aXv8PnCboPIVRcrSh?=^{; zk%ECS0+Cn&?SddOj;($0--5Pggg3IxXLF<fy#P0Gn(Re3KN2MK{KaH0pA{2bN*|1J z9hm$s<T+=+Bjzbd0$M#X4*WV78My#2{1ktQV?C<Ut#r>?NzV};Q4*3@?55(D2pRRY z9Zl)t{F+J?cCJ4Lew2%>nocap8I(KF@}MKfD}V&Z#E|ka2djjEi@BYJxBYrby(w)< z<k9g}xss(O9gHM31sg3j7&T(m!wHlUL=R-PA20yDhwuBvyDKU&(8(+LRl4(ce^i@q zF&E`TD>SP^pV&IV*4L48989Nw=eMojl9Kxu-$uOsgC3VHe$}Sc&hC_~1$Yb2-*8Sn z_cjPv?r<Ed(Wk6xQ1z<&LOi*{ahza(0j7^akNKno=6^91o1b4uwaq^t&n%yx2@ZG< z*}^MtGp6^%$2RoTbsWxQUZ!omz1c@Qyja%L+}_-EM`1i=g${1fL65^nGQG07H#s!L zm-)=!CMp*NlnQQ<<ywC@W`>QaSc(wBwN9XklygOHa>gpYW}VSXS@lA0GN{uZG(mY7 z{zA|m8>mn;U7x+nsCipw+QTOd{Vc&M{X)DeYjXL~d40z<<K8<qF1q9|9fxAhsohh` zNyDPVkxd$HY0+OUARbcGQk3vhFa@8@cb&a#Yj{(S#RY|x*}<LFCbw4<oQWPg%ABxS z!C*xnGpNE%_HN=z%-$1S8y_ad=evoEdhZILOt@_zGqqEI1ep?=xINHfjkO63#*s@j zIad|llT9UitTxz}9LSnagp;G7kVr%=AqC)w54ae|=Q<a)@SVg<#YO{$Wfkudl%nis zhj1+nvAmeV?yGbB+U;0ZA+^5tAi#z4541g>{DDU?TT{F7RMk%S?cQ|kJ+U^6v=={1 zjIkZvP1AjZhpP3<b$f>vq-wjPyKlvGe|NiW{v@0!UL=Jul&8|ZW5j!1nv+5yJ`HJ& zh{)=mzb{gpTTDK$qo$STg@ZXRCx2lvG|5cFlUue1^>$PDAsL0@7sNs$`{LaC@-eI^ z@j1{GTd9{G)=8bS2x`GLg$lx$Bl5MgM&{@|GQcnhR|7aFRUV@wz2~)gO9KTW8_(!K zA7+HgL?xkgcj9@KBh`I@NI*ySWT&2+=;ao8W2=~~)37*k$`Y#?&gDYEEe;~?Jy{Z_ zlFA2z4X|bQ4ezqxki{k=J>x-3@H1YZL7fUl2Fx+Y)x7czJr^|arPm5s9QCUU6#K=` z9X=#5caGSVO9c=>h0V3lvzXjRvSx$a@I�xb)S)B)~+Y-CYM;Ed;Iff#ueS6mo*) z$Z|%4CPqkDFz`k#!wLQ+z_c)zuM14i;!XNck87m9%l#Y9tmo1G_9Md|X#v;hP*~;O z4x>Jr0$qT)m}b<4C07qyNf-bDoWK!Jg2gry1J~|$kw?wOSulS>&-t3YS@_s<9o&!f zhjD_bm2a{>5y4^e0|YFR-Pg6tR!va7xwX*O8**!)1#(=d(D8O$`@k=REJAYnGd7Dw zhHe`9oSUA^-AobmV;5W%rsIckN`_lY`FrPM;pxc`I4X#58hO7$$NQtb!J%>UvTD%@ zwfj^jM8$$X#v>T*a?|kEK<B1lq%zL=2cv3dKs~&y@>MgM9Dr|{#N)iq8_e29-yw)` zuG+fK*1g+-0a3}gx16GjIOQ*b!eV0!(zgy^x3mo6MEuEdDO_wU^VBL$^ujqWV)8tf z;&YH1(giH6oy>@`$A5KTQH(oQl57QuaR<ey88TJh>ps<yk}RcUEj{ZWC#MEFcIAYO z>dJU}sCExd$|b?$cC8X=QCl9lT1~{8S)@2X4grNK%?>6}p-@R)BktM*(Rjt^CxYlf zSq*aX`U(l+yCFu~u}orLKI3n=hy8`lt14U8bDK4jpA;3uEkdDXEp=Jvl_OLp)+>JN zJ39;k0h>*^i*>ML6QAMFq-QW$O0JWmL!Eq4Kd8CydS58|&yf4ATuF)^fYi@SLJ^44 zh&uf~C~`!}XT91M@HO$a&!zv2{oMuJ8-tXAl;MtL%mU+fCwv%TBDL$&U#SS}({TAr zwzEF6eQ3^jmMy;<bc}^UuL$Y0mkm(Z*|Gi*&sdEB*tR$<X7co!^PCtoDFGEAU%qBV zVh8XwvdXvlGY@hwUdZ|Rxv-$b&SG7CN3s?u@Z7MINoany_`O;NE7)Y@^20x;tWNMM zg-ay)N$O(wK*g6;WU?K+^qY5C7TAqDq<doV<CTg9=T!AV(N-ckIl*c9(VlU?vLA1y zbQ(}ER98pd9>+1y4knv<LgWPuqb5#Aq2@*=(cYB{3RyKJ2((PsfkP?tSF##dFd(U# zezaj}SWV!_2CgaR*IFii>#s~b-SW3jEPw0=zY4Fvbe{1QGiL2$c>n|}B>yx;_jGd3 zF_>zlse61e$zo5~m~t<DV6R$h;eZXGUa>hU0a2(kaf9AVh}isMEXWQl!0+D{U<nT; z6)kZ-X8^I-%~}U01mR6~LNY`3T!#9gdffdd_q@32P?!FwdvG_K(P7GE-|~x1Et({V zxMJ6@D)&S)%RRP@_p(Vk;3s_BD0leF_&bq06X=**gdolVB-)_6ht3P^?U3ori6YR! z+xy^<+VgsEW5XoIc6Ivf!Q+b|`Xd|Z+7uJdT6<dDxMJpJ()7faMN+G@S+Z5WDw%UY z?!o@oKpg0*4X7P)%Q>)31ZLQdF(=lL2|i97Sb32si$YS&xVN*ms2jq?*PsrG(z)rw z^rI$|4hv2d25L}eiL;;L#<t*@&Ci>*USN>DT>PNlGQpb-0W-rm%E+PxN&r{NB8c+R z`y7ae-9ZQ&a1Ip`jKcC_Xrpx3stbi4;&!@A>Li=akbDA!tZ*F?uA)*zVRB(|?y5=v z^ZvvK^KT@x*<Y9Dx}SkZjse#ZE<8>JR<yD*r47~`P#)5>rln~X{JMOZc!VjfIJNIx zY1!$_QT(6J8E8;?g-$k2jac=r;_wu72x2Oj_*|Ai=kDw+U3J$0<C$iPTzDGa=#UV# z)`2M=3+)NSaA5nZ=-R6Jm=1`BT?Q4R&AChzq$aJx09jg7KzG)^MZcS>>7!@8V(ycX zc~ikk7>CdWx<mzRrOT9B@h1UlJj~JhfU-9{`HfxV?2+EOe9*1xS6DswbNtBzx=%-U zk))+P(XkMd)Y6SHj=CMGADML07~ig8Mgvk^O&c$esbg2Ui=L=34b?cBE$K0};Ji#o z5HtgPhTBor#e8mit7NiKWs`&6H`0GVoPRgdzR(z&A>-uU=xAJ)mFKqT2Td&z{Q>g{ zyI&3*9!6#%@fUAzLt_&RxLV$s^pB@I#4uR4z8s32JfMho2Hwa$))ginSE|-}W(Bm2 zwBzUlrZ&{5;<1D}T0*}liIvI3fM)S@BDs57-mVXU`hC=3j&(QpmeJc(iaNCzx2t5` z0^PqcjVJ?3k)bV>Ct16S5K0GeO$!)!1a->!w?=#Ze(}sfLmBi%Y%gZb&pl^7gB>j` zVP=RyBfVEDqQ{JFzI<=5EwbcsWM_77YS;1VNa<)X#hw)6zuj_+MJ6VPcArJVD5iK( ztI<dv_`$X#Agy+1+-V6*!}T!vMJ-G!5b8&*wxb=s>uJe|;<*zbDpv?GR#$%`qk27D z`8O~0dU(N?ss8%2H3n>;wdO%+t`N>u+Y>pxqnFv6Ss`Rru8ly~3kMUL0D*EAgB}t4 zl2GLW<ymCF=BHLfyFJUpEE2cF1#pHLpNB_1D73I&CeY%3>mvVCf2)NxM0G0y`+`x< z;h*UAVtZB{g?>1t`iSN06E9wt@odVUFSaZ7W3Y_}&BuOymc#ZJHWvZKkZn|-5RQ>G z(LX=4#kJ#{(bB0Dat3XC(g#hMQJ-&WXIpgTTp1PCbK+iNm1=ZiVudVg!1s)l&D>qQ z^pjm*1q;gJr9vcn1Ahii*_*RAwmgui3|30aLi_gV+|Nw=5E1cwY*fwDi`5#5_yo^! ze|n6zap+}IaPFw+tBc|c_RYvEu}I40ntFO(KKScCa8O_ET~MWZR^N|ZotjND$Hy>A zCbEk9KM&Q#i=Wf7PiiUk=t*B4gn%DN->wuqI{;3BIbV_34YYasTTQX~MzL#M^<&3V zT;rg^85wRdmBjOWbx%nJ-g&>e1WMqi8Kt4R%#FTMOwvc!df)7eSNi+W>cHL&TjGVK zG^&(UFr};JUi-RmCR)uv!-uPW)${Ze42N1i3~X77ra%|Qrz8_WHW(N!Ef1O1@G4pJ zJ8RE6(|V&%J}Y)k`yI~(95>|k&HG_P+4Rty!Ny<wZox2`vWLz$nX!|=VgaKLOmucs zpIM7&*ePWW6rYywP%Hlwo11V3LReU-#e_OhFe4zzr*&SA9wfs_m1UsKXf&ed>!@t= zf022rfE_rOTH5Q;zyFPB<Cei=?&@5b2-4Kj&fwg9gfK7E?HE)SiF4-iwHwvd?HOn( zelu`-@k)FNYWK>aWQ*qmvy)UZ6!spw+;UlLg_2DLUDJbz3kYWu+8HVT(Qi%b8nik7 z_JzTAfADWH!9~M5-+Ah-d5k~L)UC0V6Z6pjf1mJDXL#3R0UE?Op+7Q<NI3yqWT7uN zlRrT-%Vvy{G^bClnH1OV#BBE(7UB4FPPiuWZjbp@Ex%8M$jfTmQ?6Wb4urloIX>Vt zI?E9fEQjUmacLv_+g%h0nat~F?=(Jf9H$-#EYosfJ_KG?I8}B$YLTY;3ZS|SpCX<4 zdbV!I%*hv294s-)_jBL!;_w`=Z2w4SMd5wEZbnAt{E4B8B^<Rq{TobS7-h=SLX{m8 zZoJdx+?40WYin*uW#9i?tbg={E+z!gLwE$KiSyttH0av(5f>!wtSkLt4O^PRQtrO~ z4|RWjOP{6j#xJ0aAF}uqh8ZjJn{rE&w^&;?QSmqggAAhf{H2lS*#vh8A_<=?tgfrL zrRH@wTl=)aJwAO~0fnj98l;TjIIz9bZG+1gsdqD{t-xI(1v&VDF^y=@y|y=Ko^V1t zr_AY^_TCt}<!*`#!>!LfS0CzdsrL~A>kteP3iJMuw4aoUR>h?C_|TyvaFj-p>Dcxo z?YFM1bodOgl_(O64QC<vg0`kahuQ`ZVxPL&tW0DU1H9HCI%v0;5pO&TNR5@I3S+NF z>1MCZ`v7Zyqf^OE_`Uv`>m=L(p%k;z3o!VAI^`vs!6keN3dL)X0s1kpZ6>&2uxHiC z%E}={g;r_EOwZft+jG^92<0A-M&V(fNTqOgukI~Wc=ql2Deq*`Tm3Q$!;Cgmxh#m* ztWxJ$ww#}mNza5-#5w2A&|8>8*(GMoR9=p{T{vA^p)H>dh<NK(ZrNq-AqhzIfq<Ud z*PecfJrY`iHEStS?nw)a^|K!?U)?Sw`q71;-=Mt$_4yR@6Fr@(EIyP!MeHTMz}0x5 z1sY8Nrvb6eu<;$r%S}F?eL<``G2lQ`L8&~H1q&NTqIRQ+ooN1`hQ>2f>)P!7$`G70 zld-_e5z8I~M(7}4z^{gstq^ei9rP-Ad_fA!OG}uAKfls6Bd;v;6V#J-kbl9Z0S$Tb zk~q_@#dy>xYDL6M>>T4au;-eYO_`JslRs8p<Kk@v=ETl;JRH~_T^(sjF0U@k%giR^ zsr>;)NH+$s*C4q6V!%;s<gxn<-1j%F7#PKBk`Et67oT0cO<tzUUTeHjX~%8p%#Ie3 zqX4o_fH!{K`7XVyZ-QPS*$cVy!|Nzyl@L2#)dJ{%fd=kvU>PTEca?p!Q6d{#_huEe zheC&-=v|IDz~vbtm*3D#C0l0j%!4||jmd46n0d_|oF?j#+@VuIxk%zqGavz!@MQT^ z?TDLd0S-a3!W*F)Ijsf*V)NZo>9yS0*)aq#8M{R>UpLkKWYn}wURk|!Uf?}&cjchD zF>4Qq6_-|ZjTp?Rud8H`Qm`JGSJdmGo!4c8(Xa7KR+<%Ov^M9Ny3?Q;=bp;FlHEw@ zT8plTfzc3^!yo>9VVp_%_&JkH<FKcYcI_3nsmN@Q*q^^vB?lLugA&1|yGsVh1dWXQ zM{>DEl6$nAW&k$<exj@Qm{W$O9C>P%LmR-SUzo}O>Y*<X{+$m%Z(GyA{ILNnHy)Wl zjtmd|?;G=p4eIh##0qz0E}YsNeq$oy`b3uTaHgB`^|`?wRU1DT3`mtX9Oh+`<`e%^ zQ=t`^<4_%gxSZXgK4I7}XsK-?xPgEj141*+W=l^=8xc)ew=iMx@D`4e^g8ZEwU*>; zxoi?!exo7+zA$ISqWRe?abq)c#Z*D=GZWSM<mng;cO*J7r7N-b)nd!pkPtjR@q03W z*v?Xwd)e&9GHt$%>hH8*5|<K&r(LZe5RhL263jSt{FjsyvOD*IFuV|vadyyb+^|N~ z!Z>v0vf*#vZ%L!8Qc_p3+HdB3a^puP(<V_^J!b>|p}vzXq!Rc1XyY+~2l;QJjrA>Y zTz5`(eI}r%W^J5Z`=+OMXVpibNMIHY%8q?PD_)Q(!CdG;{9J`pYKnEGIuGP`M_Ez; zWk4~SPTrm7gSsRI2J}bQnDx?!Kj=632Po0llh2+HK!~HYZC)N~bq5A#%i@hyL5WlD zw4*uT4SNduPGT`dm(z#)httIe_V>Fp(pm?#MUHThes|i^J@y(bSVg1ONYh~7+{ts~ zBcLPdU1N1cV6Crc8am1q!B$Sm6Sl`ss)Z3{7Nw@vzP^)p=ldhiG4P`ou{oJ4l@`1? z(RDOz+1+;-!T;BA6~Oj#8JB0%CTLx1K_^09;3tj!R@UlCvQX*DT9w2iv7fxvs8(6+ zFC8ojK97YKMas2w>L?<rQzd$+`5jRp)?u_8mA6aTQj%A7iz;euy7uO-6_R}g=ZW8L zR?4%RKMrwO!J#6cdm|K>AUx=jk5WxpyXGFL?OSJCmmSPF+KJEo1BLu;43wRV>m+;w zSZP<~QN1s9Fu<OFDN=`6$7^KhIe3f_;qe!1equhc8`~=#1N9!R2?q)`ap#JTi6`;| zfYZLwk6i_?rKEFp?^oQ$juS*4K_Dk6KG&BKo0z$(9P|6+&s7Z+9VMnWpMPvkUvXdC z?74S6Sj||oI41CS^Wkj&h9{VdwHmq?jk?SCDD>uVsV)p~;b}Bvzk>$9W&>P`UdrA@ zq-uv~h&weCUVWXgUyH0Q*mG91m83QE^}~${lYYTZ-J2(S{Te_pS@#2g5$5VPGER<n zUqa>oF*Q84$>Sar+GDXna&xw?Kl<2bKWC`lHSHqXS?vA7LYWpl_2$fdJju1a&geVv zos=3rpNqU=@?HQK18-+A786gKdvJHVB}~;uq($BFhb)_+&Ao!SVJ${ZJtP?kwMI`> zK!<-g>C;o@z1VLqev7GsIGUz8iA<ug?~?<vFtENbaTGF~i-JWMtcnjKvmSl}IpG0* z<H$4`Q{+mtVeBQse9Z;wOjUiefG@7W6S4Q3g5E|i)}m)aL=%dtaH+Pj7MSm`zfRtz zfMsM5JQ|JN-F2f~>7?^fR(L$GD{x_X5@-UiG#-}P_h}IN`5oF|_kUpsM&Jz?Hv0#> z0NrpJjspPERgI;|o%|CS#E-b*pL38s*y5&mWQR^qc;g~`;yuUTPR8vm8;90Aea?a9 zc2dd9P0dYhyBA>pNu{I>I(AZCxFhIExk}JMdj^&bP{Sf5O6lnQ3_lf=t5@c2T<x8| zImZRxa1q=HC8USDN_*pcExWW2@f*u=yjqLk7YZM;gz#uXl{)*h$@O?!Gy9Q?@?m>E z-hVGNJB#Botn4AbGjkxtZ?;@Z<qrE==J}kNtGNfi$zDVsd1ml46!A9$XMz8eUBlUT zXrmR&oeL%7I8s+l5b#?EB|%VlO_fS^Z#)K`+yyd*V0dNSDFtyMRS>m$G4ZC9aR&fO zwY%oE2!{tOOWErbTPbGLmDnA+x>wupu~!xzvg{^`-I8)7kOVPJBy<Ko%*Wc3$mz^4 zXK?<=F0(Oq=9V0>k1h612q_0f=J!S@jnIW8JnhE!4EeSWRRgPgFK3W;g-4<(UcQeS zf!BY4GoW3AN*(T>uKAVarUhL#(#cdZMtTvN@DqB}AjXz_G)ploh|&;#(0&o`c}kYo zuL|oP5D9uI-<OP#S~?Y>QtCW(HWdoCT~bp+5QImQEU1F+8k-A7UyaTiC4YsK`njve z-eCLjhFajtq00PybFNBPz#EAt^XHv>4VH&JMSaq`k`zQy;3^+!RCmo#!Yb%KdjoXg z9hMZ8#<)+ci@ozAp=9d6GSCcP1LXIMhvBh1$ebQcfFn+J!Sb)izFcDXT|cg(#q4vz zPlFW6Ed;1;8<Q>IxjQRa^td=Q5bL&y)JWp2$+En<_O6L+HhMG08G!3OCH6vZPa3e& zG}Z`o)@VqU+*3r*D|X{#?qFL;*LzMnowqYmMRa#{gDMY=spkju2<RK!52_jj>7b=E zC=!u00(gKoN#p5KX#^`_psoR=SdYB$OSuCWFYz-ZhrR5|hlV5q<&1AF{aEh}_0)Hr z+{9zLtH6MZrMsU4_$L|@tI{}64qIk)=pfR>qKdJ^n~?afDyMQiUY<Da61Ad3Ah>4t zBDfv|hA`<O&Zgrma9(Fx8T&?cpg=YE?v#@IJz|nZ261E8^k`MmL<Ru1IRw`p0|j+) z7ZS;*5?WLS6XRVcy?c|OcD_dYJ1sUYfc!6;%NyLTI()<^VqMr!$%|-EDa0;>2Rq#+ zjB0In?rn^?wcN?wadg$f<RrcMdZ9HP-6E^s6(U!2mv_${4m+-q;*Iitz~lZv<0UX~ zP~j@oJ7X6fY3C<MQz5R@1DDXYa{T0z==F4+L#~2rm+RHvO=^xrxaSw_6>oN2t+xk~ z*jA4YR?>{|IcRe1=c?VHyHpe=KIslE!#~~770uN%P3e%0fWss^JCSySv(Po-Fb7|d zE)ir3e8HPYI@=i6o0SQ7diC~>sVn+=7cE3)I!uWO_EoQXD$J+Mzpx%%g-ii8)Y^o1 zmnzKKFjGDg1U@@4asZ7xp*=&a_=kvvUgeK1jxdLNX1)K&iy5H3z4jf3f7?<iZMO0b zpH^AQ$$|-UIoiVPsc*pawr!5u)H<nZ^7Wu~)?~^aH6TY|N+p)PJ>=OxC<)mDGA1DJ zUrM0`DLX*4ZZ3VbZ;OGxXBn-#+-xU0fxo!79|&t?{j>zMm|7XVra*Xr!P?*hGq0v2 z(WZjDNW4Hnm9@B#kTWMQ3U}lF<P#xztk)VV?5)zbYVhS-NtwoqKG@t1nouOe6JCTD z96G8s-APt2a#-pxK5)6L)GQ8I#8{OVi%&*(r${W<HLm{tvL}exc0<K|_OMHMfCe`X zMI@i3kwf`8YKDn&#X&*^R0k@(oO(vq3nQtOB(mzPy~0z<wQt|iC_g!FlP})cxK~8{ z=gstFile>f-}jMyo=iNls_BC#yROkX@bt!=c0=Z7>SbTMb>+26S#!fpj0CCRV{<JE z;L>x^n7`tTzM6V@8CcV{DoDD%XU=pzQFG4QGdUrKV~@Wh<@LeV{&1cX4Q!ru=&K{9 zWWN1U1TVH(tQZ!-O1vehs<{e!T(D0!-dY}qxW!STbJ}sfy!4^len&H@1<_c@Bi1R( zJzTE6EqhOSXtIojXFqo%llw>xPLr3FHM)gK)oDo)=7;S;BTC$KX*@c`=NgWj9?IyA zN_^lP7irKPvPA#5;Xe6}t%PIN(q2s=J3xMGQjI#Q@fn|<Z>76*RcPd@g7@pLaLML* zaKTrj=Vc}r2Q;1RM-DhE9N!C@3D|ua&cMIJk6@yE5PF~sZiBN?qdGqoWkoq__(MkG z-X<;A;BWi3Ja^WoshAZpjWs1q5GPt8Sr%V#Xcxgo#b~2MQGzg=$P)aUsu=YL#wfGn zKfaF#iHMjua+A@OJPsiZ#Y9gRJ%BBJrFt$kumd6#J^ll`TGtZtLRg;h291v@bpq|+ z#=$yy6be*mBT=KpD6SkV0>_4EFbSMPiQ&|<GLwwK#yYn{jUM^xGRcZ#d4!_#4IEB; zt=cj9Q&i3Qbde)c`-XHUzOEMDCb}GHBh;FOkvo1Y-P$t2SU$hhAkiBw<|h$>Qi~ve zlhK08u`YNJwi*zXRbdC@W%wHEMkXuOt!=cgFrv*?e3_khi*#D;w`k!Tib7-hLLaO$ zUIAc8!QMK}crTw^s#y?DPj@0g9(Q&c0MwlQ?VZlu{oV8XL~t1BLAdfV{~?fYT+PLl zw~VUe4t^%b0Y(L&vrV4e_4kF@9rIBMsD^j$>enob1>GLXAtZXW0i4_SBsW{9f!B1I z<s?$Klr%E`?}&1ec;FPt!t*1`JAj}P5GRvG1~DXT)?df8b>cN7nL`zIPf`MdQN)=k z1>!&)G$vM`+k%uhTN7N$A;Ta9IPU6Y5;?wHb7YK8K2!;bCeK3c+_doY;Nt5m11&IT z+}XG2AbPSDlX~!GMtJAcb%w+`81PX+h2Ay7@}B{)H&4jQG*0^B_OPGo7N2&V4nUtT zXjZAMno}e=OwZI(=V8e@F2h@v!cMb7?oCSg7L^{-2p8Wo_su}g=jT4K#kw9)SG~1r zLTd*#z{TeHXASC>BF@(>*<*7(f!uT3@G0KvWNe`78Hjo#v6KFe)ZT%)6sKu+SzBgx z+cRIOVs-G_2X@_&`{1|~GYt*zZu`(ibEi*~6T)D3QH8_mo|l&L^!UQvEeEfK_D6k! zq)rZ`f>%V{wqg636&Cv`5UO0tFEUe<)v^HR=MQ80ppjBZ)4DvjzxfwMrw{5<D<eaW zQ@r_PS?KwK5mghDoO1UhiY7uZj(Ggq=HsTc@s*l>Fb`PVi*L@o-nRI|IGhX(sCC}~ zB;PTS_u6J8*1CslcOy{C+eamYT>9ZkmkIDHW9)1Rl|oq~>iwE1l65auo|Em!g&{ke znMv;6R@WheAOVy!>AI+J8oq6f{XZxCO7|9(;Zr=w{^(XZ=CMI&$SrMD4Sh%;gdfyj z4V4g2?B>C*_QU<xDwWiMMoQ&J{7;`r51(8v(Jm7D$m!14t!g+J5BXq3LzG<SQf+@H zlp+Es3DTVIbGN(F=95CkW8`)B){b%V)wMerp<#y(3|PE8(1u$UpI<x(A-QLVvYic= z7EY1lUo#=gU)#DK9_R6((<N4#jfvD2T^DbU1}yr8HRx+g1a62s{p};;mmAs#bU}Rs zG-CW~IS_OF0IVg>4bDvA7Ji3E9QJbEOY8Iwbl$)41xW~f?$rO}8dUloB<ehc5!<rw z?5hN8aHoZNytL|E%jM9@Y<g_eX&q|!xtF^_#IQ)3&ZNdG)yhI(YHUf(JG_*3Y{hhM zq_9yTvL@rd{BO&EEQp{82l;KTrQ51+<5vmbtME&>WGXePRiJ)O@HSj96~Qm{GpFFU z@H?19=7+GKeQZ_<!L{pNR7q7&3DAbV)rTVuIG|rTgb$zWdXq}e#G}tqGe~4PZ_)H+ zSy>h~*F<@qLmA7-v7Iwq!f+(M=<N*BNZCVS)GuJ~NhLu1=;qKqb94D$@zy4qp$E`W zJx{sSz!x|E0Hr^Z#0Is1b~?4<ynu7Hh*lf;vhie8V3$pO+#+jef#i<D2J}eN7f;lQ zmbi?yN1V4ue6hZTCs0+M1V7t*UeFX->k{yY20JM?JB)qml3U%l=ks%O|E_@YTB6Ty zKkT3u7dMF#r#qwxrb%-!Y=WXt+R>iRCl)pvmi)2p1w?#`CQQgseUgq;Am9wr=T6^f z7}FH6g?<Ji*^}?hT9<&X+NF!*c66(q?nL+R4N~Ggv*q*q$St&aTadosC}l4`Av|9O zn-Br<1)TYCZm`d>_1%B7%Gw<7InkuLhbFGjB;HnyL2c^H(!5{!dR7FXzTUlhFt|3Y zu87{+*f_3)C#U#@l}$56nN>|&diG4UZ1Id1{`1PCmEPDiGwSyqXHO-(zbNgBRcmrK zGR-BY4)36)sP;s%Cov8Ob;W6%RieQJ&N=JYj@z+(nzb$5;!6A0)vjoiyF|eOL?Qgz zLlx3s12FI`aJNF%as69_;K}L=!+;lxD+2zqOvZ_{*Je@jEMa9`3(?4=cAr#bosAx< zk1=ztW|2j3vno}oA9Z$Ja*U0*Zit+$df0kRhKdr+iPN&9cYwnSM?~&1y8fs*il6b+ znlrXG@JZA}UE6b;6895{{YzUXLql<{PA5o=J<-_r%VOXS`FI1lm3GFNv7dRM8_~!? z@TqxT5wO2+R>MHzG`Bp(YxAj+JWyf97VU_|cOHJ!*5a3(JTOt~%}cK>r6F3Z4m_$& z*r#0!jU_jL#5FCFbe|#t!Uo|grJU-I16Lo}+$r|*AB_g-HuxBAuqEe?EKVBT_9rC* z5{6eblLuDQP?abK8HG!ewy*P#Bxr%=B}Uao9HHVvpblEx6$sPKJu%)yF#8&J>2+Gj zc%g%*Fc3a1K|lJjL4!2^%2H(J+yGu)Px2d=e=|In@zQ9?0(EMXSo5Uf)bU1$n=BG! zq8tJkh{j%5Z;M<7ub##-LSR^o`9zkB<H%EgA$p8%;MM)<!lJIERjIk@pBU<7Mm!zg zVWHs3J|vRA<j;gmd<b^_H-7!rZJAm^Ui6sreb%GkjrIeIDJf|&p|)y5IYSL|SnAe? z1dW)=r$AoNi6DZ{kO<L=1QExt0r6^2{4-E~>khW@j!O1J8w8<<-^_5l1Ry5N&_#1s zFEtw`xFC4QOl+qvl>+f<de{L=8227q|8p+YQyg20{RIEP_Idl8Kx0`jE>()dHX$Hi zhghNQ<X3hu47E2JwDe>ZXzuCjsZ6>$gIZ*1P)6r5hDJZw6ATZQ6QS9-%F=s^tp}6@ z;1U{LG4lTkeI6?LW%Y6xVtqlA0LB4%fwyePS7YmR`#>MR7_Zxd(g>tMAxAQgZr;Ol z$Wcu#GBOnv0*tz;f?6mh-W1O)vQRrancBi)Q61mF9u-u?2IM`vl9r}!9AVtjx*-D| z4{X}BHWPlO-F)n$Pt=|$b((rJ_)J$TD)2k2AFWYb>?&Dm6I>vq@ha#=ExZhy`4uQ{ z+U$G`)kX+>NIQ~vDX&=B%vY;8=+f@WSgUS_0H>jpVAXXsW3NRc%Sg$cHq~0>3?M`H z!}K`{&8ZOSH~JHmgPc{+hCif#H1#IUhyY5kr$D&>n|6Nl$%gfeEKkpC$WQ4x7YIy{ z4MyRbLr*vX$@(+__D}*4&YP1VeM{4VoYUrqyKo2bD?`Epq#xKjx=ef~Oqbc5H4RU} zM)pGW$QmbCvFK6wPA!=V&ip%)2YStI@4<DLF}({T@Kg9Y<k-tbxB*?TY=V_Lz3-|8 zc#Ar^u`PFN<l-il+SF9b@fWdS78cqNh)j{xAS)M0$>tBW_j*-6#IG3*YIL&%`5<oW zn9KY!NxD*JmGK?SeGm|rlbqoW1m}pp<9dPJ;FEMKR3nE6A4Tp3iPo3D1mq{*?Ok*U z5ue0<tTXaKvI<@He<u%Dd+1$PAgUQ4yc))1;;=d`*(^k<$f_0Nn2VZjzRE@NPACq_ zv&9(!3h0F^I*fvfJ2@hnG7@Vfmh4sZ!;`s#yDeSI_yKs2EREy&Ky6$;JOQHhaeO=q z?i$UvaSKaad?u4fzQYiG)emgs6U<w><=GyjAPr}q@@bs*G291}C5nX5c#6*XoUt#> zc^S=E_lx04UAtC~C^d0gl^ESc5|O-=?!rGwK0a)*!MMpO$svvS2hgR`n8bM|%_JyA zRP%@$%ZvGFPnO;CujT9^drQvV71+pm+fD}{+TYm7%uXg+a}&Ub-!-SItQ19EZVSgT zglOiQK8=Bf3GAejmn9QgXY>a^KF!2ReS$+~FyY9OI)m*$gcz$BZA}#O3Da<GE)mmn z#=ekj36PHVh9G-JEZ!$dMPK&>H1Qf@YIvGS-4M)yd8ML?Pl>B0P9JI*E|7h*pa6Za z2~XCTku2J)S0_uw_iYB9^mGPp@otzRl&{0{ZVxT76A)iW4b@XD6_3|A+)HSpFS-Ll zM%Zs?_x)Z?lO3)zOV^e9QwEzCJ<_ddx4aaL{E>{;Y0k+REK#_}E`KM;ay{~tIHtF{ zp$HwV0@y!Xv9hUXou;p0*EpHqR3%ZLpK80M7mz&Jn^yMb@g<aDUvz`xfM<0y7C+-8 z!2>Jx3;%FZsnFA7RjR%*{2Rg<8?K)~7)Rt?r9Z(0DQOBLJ|fqsn#lisEfQ~)GSLZ* zL#q!Wf$p?s(kec##_+*1a!8aKt2Sp9%PD5}b50)Xwo}PO3_>Z8uoIl{Gc^&g;O$UG zG_8^zW$-}Atj3nUP9zDMZAW7;^9Ih_jD(G_fq<%J<YkAfvr0Mp{UUJ8aGJd$x*;iA zKEqTd5yxrT-GLOb<lwz;Rlw3~Npv)2?AWoEA266lrjlBl7~mD(B$!PLeGnGTI;5uS ztWJnzPEE!qK0vXK?aH99E3<>~-j+OlU)fLH<s>hP3R?o2+p)AK(sc+1!Mq)Wjl-R_ zTI^H<{N0MO<U_X$nFc!1QPPQH)_-TvPkxE#3AA(+9_6>7nu#}+a7cOz3!Jv4X^|(> zAEcCf3g<SWDF4EZ-n!N-JOgd~8UF?%a8H1DdJ8RV#}pFjA!F9(Tk~_4wL@}|3>AMk z*niS0huVn`wITT@c7lI>s}A%bhG)~(nyCqP#UwpmX$@!(8DwAe1MIE;4b>`g5NbCu zex=D(e5lPikW740msDde*rs5Ai_c1jFU<w}dXwnBCzhFb2%3sU=oXDjZ)q>2ob=l> zq9>->aYb3{YH>~d%dh6l7m>ahsDyFNw7AaW@m$^Mke?{-$V$jDtX=YAImW4t^Gv3U ze+7NZb12p43W}sjv!v5{p{G}E1l!GpxOXgLnT7eDGZm!obQ~a*KzYK*_xCLl^B1#( zal{~UmEL!n2#zm-x8g;3ze#CQASq%76cX_9<e3`aGcC2Z#t1_z>k;mY-IEQHtsx`o z^{|#Ph9=i)$--|QYOJNkfMZOtGhwo6zruw^YF7^FR|}xiY#$~cguTqbe`^#d#7XC{ z{O4-J#NJ4dKV8Lb^gTMc7CVZFihw;JqukCNj--17-}rFM>4gT-W$vOCBduqw$9suS z?u{Dsht~!{d`tS1^A%Kn#!T6Fk$dJ^A1|r5QEHO>fbt*&pxI7l?>Hp5;h+-&xYJ2h zmX!k<@H^wGj}>sOeqj`om1TXO=lFURmstc?FqmoJfQu2j?~Gpf#RIFg4i0-UwOa2u zx;V3_*t7m=DmM)9QXzL)TTAUDuKJ)l0_R)|e5xE9igNiNA3}!IWhDCa8>}z&^b=}< z>;25hPL4)R@5(rm5z*LXZ_}d=iTKF~!GtAx;rlIJw|i3ATvs0GiCKE_e5NPdvU^>o zCv&cafpkbrGg}6hVI5~Znd6x?kAqm;6C}he+!YH{!rDf1@&J*D6J@bX^gDmhvvD?C z3|ut%iA^AoyM$QZyZ^nsw|BSOiPXx<C8@ldlOXdU)E4|`LhBiUQN0kUMLc%=GB>0g zeFffqqqqHnr2IR$l(k^5(m2kJF}ms~M*bxCtu$>*!++j11;I5O8)x<TnkEeN!G%&7 zdtng+N9uBm*e@h7sSTmGMKqo2;nnsdSBL|t>%Ojmh~lAIZ39mhwLjJjj@bt+fpNS= z07vmU?=puHtF;GBs$>8C?JA`bT;$$ecbi?JI2R3IJ7+lpI%3n}^1cjB6qCfL@I-jt z&F>C$DqBBhwYX=G4$;iX4X4wYNaOC@j>uL+@DjP*b&|f!Z!*A5t83jQH=^MTI^i|t z@P^^OX&uwR4#(*p9KeC2>PN6}O4=I*RzC>ehHt<>!5R2J@Q>-K3&6iY2ek4v_VXh8 zsyOrrL%J1Hz|j`NcZ-)Z`TtRVO_z5G7DoJ2#L)Ql^PSgI(D1VF(+UnOKfM+|?)B29 z$f&`oE*uT8-M}?CA4$~lb)I|nJN|)wIMy3N67S<$TKi9JWVmCLMbTPc;(rE@BX^^I z?*CpY!zE%+qiSG7GZsJLP1nX{*CYJzT))$Q=}Uc~|F<g`Xj9>=g#SCUtW}&;@Z*{a zEnzys5ZQ|LhYR-LOw<4$TL2`%DGmq>g92V_h&MTN)|X$mlRzDLANQTrUKr7OjH<l} zr;x{GE&>{&`E#B|?T0%!*krQ;)^`BibF2_3a3NDwfqbDrHhMi+t)0RmZSxe=!V^p8 z!2=|fbYtv$A=JvE4_@lXaeiaEvkQoD;{gr5^OZhPh$$Abwx~eB@YD_zLwQUu^p?*2 zaWXfuPScR^|DLkg%U^k&Y5vy^4|k75oDYpy<zd)8Ou&EBJXEd0Vt6vNBGWdi-@RRe z$Y1C`(NfmkN)o`>=b`kKixa*+y%y<}dE&En?fBGBkkX?vGI!2sCYG_uHw`v+V|SUH zHT)jOVfPVQ_$I$i7vd(Vp~{gfEJO=;BXI*)P|S9$p<-2iXDB09O<aMhhK@DK%hHBE zK%j!bkf$;d3aa>d3I5!YkI$h&W=tl}<?aM#V790LgWKCkKlh<A^Ie<V+(wIf7nPel z&b2K^v!ZjG$$WII8;<uk;K`xuCD{LCr(1?W8>8tHp0lNDIky|?vs>;erH#B}Mgp7y zi3qklATrMe^uO9(Sm=X?EqBj&r+<HZeR?q-=)OTlOHaqghI>a&UM_2XS=~?b2T&9P z>+inz-t#Z4e{|>YP#_eESJeRfA!j4q=JDT0hh3r(CmI!Vf?VbXJIk(t9@QRd?d^pm zn*D2_(hMqS?@3$K%6e^)AWNTOMa);JJiT*vX2v8S18Pe2V?*QZ&5F2ORiSBurH5?U zVa-A#Rvb1%7Uo_&v9Ez?p>ZOgrIz8HY&;+l%z>09pqhA2zhc*W>U93;Sq_!Y;Mm4t z%h*vPt_ys-DBIL^X@8@mgV2(Ln%(dI#&UrIX!j7e75i-7!pn^vR-~zh4F#KZs+y-* zWOOk6b>&|MPdDIQ$!K4GXgq6h%N(B%c6}G+<1O2p!#N<Hlt<A@xe{%+5^QaA1tA!W z)?VK-`exL5`jomW5s#<OO^?&e)KurHPxEGJzkkqg*+~}gv@;YJZA)~HS71&S&UGMa zH9X0pw!{`uRYSZ}Gp8-V-1<(GMXJP(AQc_CdVmOCbnP-2T{)U_79I(L;Hr#&xHna& zi~jC-2-}wDvC~?2IM|%A#ggf{eqGK7+!GyCG^@@v{ezjoTqcvy384>z7fzf>#e1DE zjw!h(w!UTc<EwYX<N295E>0xnrquE;50`h01#F85suF97!anFt^w><hZBW&KoP(kP zseR$qirNa-JbDMy)Pqda>D7W-8{ARYpD4k;{id<!mn+j-lcQ7Tri+UERs`IE?uSog zLcvSb=SP&>5nbPLj574l8Y2?^+=Z2IN$s(B8R`SqYSS&*jgJwxv@=%Vwoqx7U=;{C zXc+7=dS_q~@2K3T`J*TpivARvk!~#HYxRuP^Yu@(d=GWb)5sI3jM1|=J<w@%3Psky zW0#gFo3;cUU+zU>K1cFXeLRtg2@f+71*EDoVSB>yHMMehV@yeiLJ~axcjRT31=;^- z5Y)gqrFsvH3!YBANOP&HF<_Y466D;snMV62Cy2vII1Skj*vM`qovBA-AM4`i|L{A# z<eX-_o#Blj4DkD4FpaN(ES-X+giu_q%$3LpNeqR>#0K&b)@#TEo@x`VSve}TN)o|~ z2JeCcTk0FTU8(e@_yxqV#W*RXMGT~A_W>Vp!rqX2h_fvd-PhWqH5y2PBgk2Zh8_Ay z%VT$lR*<9#!ou@)@Vd=PLXF?k@4PK7+di(IPcWpzG%0`YeTmH_!c~SHD96Az_^*5g z6;I4qAy~mXP|m~i8gJ|z%G2bnlUsGOikm5=$kmvfjt3k5f9w64$plhXU68J6pM)uR zPLV)bCs>CUH?X4cguJL{1+>DAC!JAqD(P$B^_vS)2697(J3%CrKPH6JFqVeDe5P4p z#{~-PMT4mBcc=ec3s#bCdJ2c}s&1$DKhYz2h*6&Dul!GcY1U*I`*ENYrT_ll`JIGC z&Oh&qZIKe!Ny7(}VuPI`Evcgq2~E2`vfIkJ?rqibq_#=MGWls&h4w=S-K%;2LAR%+ zJ%`#3N+O3QL@AA4DQOeT)X%s;^{o{3oGGnJ-7S63+y~<MdMpI*Z_uTc>_C{{0T;+u zRQed@b}<S+gYzO^?q^QJDEuC#EHezxLK}7D?0`@3G4we}Lfj^dZ}iSKm|5+)EWf2- zHEPe^3|~#pE2ue_$da`<`AWsGhs>_1%V|Yr1%~+si-ULgKG-WH7K55lJ;=}5J@5h_ zq6yPAGN4=}H+>(EGb*g~`~#cfezEocqsz{~{?Xf}kN%E3c<|R9fB2+iF{z7R<rjGp zrl5>9vhSAE&e`~$fyH0dcvxU;s1od9nM=Cd$@On5&h%e!3jP*8MTE?{Im{8-7=msv z`73-Meh5z)aR{D(yKL5?j$Zq~e7=(z+~!7a2JyhrrIbnj7Cjih*Z-J)j)rYe_FZ91 ziO)O2g?#R|8;wkoYoPHCNqNRIP`|6GY2U;Z&j&nvBa!A`w?ldH>mz}E!fh-GtR+)F z*}vpsl5VJ(5Aeiqw%eB%P?Kbpz4i2|mhU~g=!<WBqH?AI=p)n!NAR@r?O8(T8-wf< znteH3k*E~PC~182Py}F&42_m;c(6^N>!}~lkU&}CKQ{dnxnhnchCE5IZWuJzyL?Ay zCXhyT-{oqG;yfnLQOI3LNB126gRosG4_~8fYJ@T<L-CYksdefT;>jf+B4B$h>s(ZP z^Ef+LllBghR=I<C?r>ICrHST9q}9dm+IB@+X6{DzI(}O+PP{zY+ngt)sy&Nv7QAby z&A~f3oZ60%BC6UXK0p&QV3uAzg5AKdRp+C9jN4(GOml~+i;^vO@gudk*%|62W*-he zQM-9)_*<^}(C>=<>TpRrm&rptj-$KkXK=0SlTciJvZzp0n=>7b;>Pi9kNbC9{5`bG zh~Cq-?9G}7S8!1Dip9S*V?B>4%PCR>n!`)s0=H>5Iq$g^OEKDIaSr=v){sYA>p`)? zD%Ry%aiRiga?aN^V8}70xl4OT(9`ji5(|EKhNB7T()Id?4og1nQbh*kqQ}nB=mC!h z|FewqDa)TJ*pz>Tw=-NjNKd&ZV~Z@S{Y^dTo{3djWLG+_SvMvIdamySL{q2gk-l3Z zJoTm!_Nt5zDO~I=iB#{{3dzKwJT((F@qoc1sUvF0ms)4?R6^W})U4!vBi@N8O<8&C zfr=GW3lnN=`c>9&-Lw9H&XUaAVe^u(zBAb_8{Cq#8~BAaV1N`K#;)~K4JI+=O<X2n zLV@SR=W~|7JKu>-9s6>M<LqFNFM({P{7a=yusB)2_|=x9$1YpuCAVjni35S)m*zX@ ziXEPnpCmi(55W+r{+WImk6a^G1Z0ysNlTggA|+-0%IeMi7};<L7ezQ2YMTF%u_CX5 zw-tvX1~#_d!~S)A5H50VgB{PV09~wSax5~^<9-33Q5b>&Rn-q(kxq4ub8$)T+CQ;! zXq)rORG%%T$828^_fGJ_xw-)_ze`Z{+c+r?Wm@aJ+O&Gd%E+xTXV4*SuXKe&C~}E8 z2||@<O`Yiz(e;Mh0qO0u!-v(*l<IV=3J7bTm!d87r``M8{P*gxyvx@4jduS)vK4FJ znQm{*$CQ7KfYX8W);!{x+qv}kbXlB=>1<3F0X=pWSLE1j1D<!@3#^NdW2?3yVR4!h z-RX1X=>l-DW{c6_>~QB)Oc3H9{!GuSisiBskTvRbNB!H~xsr93wz*p^$-mMaBtn6; z*X&i#xc~aGTmx<|$lzlOB*?J#XD;N-t^wVeIGa?yT-FpyD&pwj6D$Ynzt#GC-2&aU z6QaybnN>&4dpiHp@?tILz5jZ<`|^5QPR-H!jR`|fq#9pIY<9HkB$sYF4Btu8OG;|Z z5Xf_}lO~{vPAv?ibdcEv-w7tU5LD7_6IhUxEHurRJ4?%15(h#<?ZAiQKac4#z0_2^ zgvQg0m3|hujG2|DkSI2EoUD`!iiWbj^#?ue8+?1Wp%K~Bj#NU*HQaRMJB%0I8|MCC z6M+rG^HENCq4s3OO(!v;0)|W)N9IaH`qOV#{D>(+qg<+6Ec(>^CVZ&u+^NgEPCpY* zE#W+()m0hSQ+atU_xtX6JK25UMcNVq6DoNT%_ku|0EE9zuT7LCE1Hq2m|7WRm7=hr zt3^E4Q)KswUwe0lZd5V>YFCl|Ql&kq@?Z8sIo4BfeIY&+RL_-_C$B&kk~b5b&FhA; z*&T*8c$20o+NI>k<a$k&TD;t!+KfP5zcX=Y7rr8Bu<K=C(_Dgf%%5P`yBBfv74!D` zqI)m1reYa_(%82$hhhyL#b$C<&v74u_zWV9g}$WAT9QX>pzq!$><DsJ24=r6Ch5IL z7jZ~|zs_C@?B($w&+HrBuq~0cXU8%GM(3S1uW}o{?d8(b$&ba6kxv^Stfi52*M8{Y zR_Ce#Ab~z1Po>2-`>9bAKS8)K*jjVHj#aTeqsF;nzRWds?=m9l*W;Rm#d@s}kfM$% z3#dHf%@&O6gO_;^47|X*h(VSuP(!_1DR59&UP*?KiQ^I`mr+}@3*Jfy7;GOh+haT8 zA`nYgh7?bAFnG{?=6+XKT8i|;^6gUfQc6@kdj*TkG2h@L)1-ZnNT1%MMlu`wal4J% zjwu)^AsMI+P4cTIaY4DxUn0*rP_1|K$PZ+N>%o^9pIAwxsm6P@dinQey~@V2vqTfO zISr20W;FBoV;cXt6Nc6XbI#K0=a3)CEAHkH^g-9^AFK*XkKeYGDYO1b%V}#5D1_vY zY8Rj(nv!NW&aAPPMCtc94N$xfZ>AaYYdLe801~4&O|La&h8!&^AQ)B`iXm^~6`-o5 zPk|wj;3A~4Y5r{Ovtdzj@^E2~HP*$);tB54I5^0RCe3UdHnT^#fVyL!e;e>$wp#|^ z=#nVPq8g$DFpx{mpRsL!6^#%Jd+C5DG=1~~p<q$bav0^1^z&QPfhmpx9N{7W17jD? zFqm!LV9<2-A%^F2yj2gb$iokg{iG9j65)ZbIk97?@#PXp%tkO(35HpSj?Id<{TN?} zJ)Tesb|q(c?U!?ETXL~-Cbx9gl}M47ox88389oZ9WLFMR@JB4FhVllUDh~SWD`ZHi zJrs$^_NGX4+J3_8!*hJWX~16511(xi-WgLx;5Jxdj~>7n4=KVqJMLiCZ8`1aR6Qe^ zs10$RlZ?2tAE_5OIrf#mR8R1;Z!qIga0F&YHcB}(VYZx6PfOsE4Np|sb+BCO6NWL5 zFfWaok7L5>m^>-*<ao1%sm6#ikM&=Wk>KE6MHYPGp?W1)G*|30lScr7V+5#GpR$?a z|9^tS|Fo`EqYUy~&$!c<wL!2%FurJTGQ*6)2KXe{4~3;0vYHKAqIenqDwHXz4S$pw z6SLVDAHf^~CNXWY6w_d^$cQRN&JB0WjTEfH`z~AV8)w4ej>Xt_JGHr8DK^7tP9J<X z@R`sK`pz{^7$(;goh7;tEY_A)YUd362mBj!Td|eT(9KntV{>uK^j`jue}gIL(_L@C z>+m8RF&~Ay_-Ba6Jdf#GOWe()RW}tp5%C1o6TTeflAQDv9xukfEC{v1?FT}hf>8wa zn7z1@B&{H(9<^p|OwtrnT_5&AiL^1$|LK#IgDS=_3kCTZt?8z;tl0Oc6BZK1qqqs+ zxZ(+K^1*4jku*N<vK|Q?yRLkwBR?Fo>7zva`glG+I<Q6kDVd4|6hqv|r|$JKjv~-X zzs*5jf>8}BZIS@|XX)%1fps*b1#M^)y&Vb`BUMM_vT42ei#oiu*vtTl5$_0no}7G> z1Zocyd(&&<(^i24kQqbS?*t$`c@^j**FY;C+8aE7ZT#-`Ty?p7>w(Ga<Z@%#wg+|W zz;1YGFP|n!vI4lmzVtRc&dgLN)-G;i+9ZKE-_v7hl3<WsNLV*<-(uV@I7FSpb?G$^ zchuF>j3PTRwDxOfA^DU38YuR}bo6a{zlJt1kU7PchNvER)#u5MKpY8W*$xTm8u9QW zN=>SJAebm)BAZWyp{XhUQ3+@`_GUA|ccw1$S1n*g$~_vCD8oyFX}}@KZ7Eqnev9hb zaaSm{=4Pzb49#}hvpykfE?izu2)(Wno@rHd(BsUFe|)0QFoWoTd~v2x^qtv_kOTp< z?`HokO%eAx>ro(EBsJJs?F1SG{;oY_$n!KF^;!5s=Pe@=b1n9Y@aQMW@<%?^rnTwH zv_j!fB+xwiQM6;ag*<B@`J*%<R;^cif?lM!(gp;!IE%d9E6I4&A9hIwE$oP*&AxgO zWjR`1wkJWIEEwd9rGrBW9Ux4@qhc8Uq6rOB?t$2lfT8JZ(@8wVD1854|Db=>7_Z{M z4!hU!7GK~TvgbX9gIpmmj!i-7IhS2Go+v(uv7;Q^hPmGnwSVuM#7Ke@ED&Cea4hM{ zFh@SvSbNQF7sOA_ROF_u>H5$Og{309NHNkYS|8aFPk5|G_C(+r#R<K8pBWjqwzSPh zJyDxHg(o`}MdsQc2auwI+cDk}k!UFo(9I5hT@{}D9J|@Yix=9(ncNNv<Y7sDo1B5e zV7rPKNrMu}$(p=vuyVBvC2}NiHNV3ooKmy@hR69mBB(?$|5AbzTfXtr6a~unsU$@p zM8S_;Z(-WTv`I9kR-+Imo1q#xeV>fSaR1KT(2;{vE*QtH#<2`Ak2Wi+SbhX7jRt<; z$MJofjEm5gTB2GsOVzh%8aXvnnO}&WPg)|Dw;ql6z-aU)sV)TY;Tbf910VZbRgW+- zUq4PZD5YUnMBYIov%8C?X_zrxgsI|p;mdFmnt8U<&hRcA&=C(nINrQ6jz8<pcIy@G z5)1qx8SNG+ryt`_Pc!03abzTBv)9}(B%P<;qDUzumuR0qa=r;{yon5ixX#E$Q_J`K z7r<B<A2QJaTbotZqteorV>&nbL#;58;{C~xm>uLRicmMWpurTUvm`yw%M;l=9Zi<9 z%N%yNl)m$@S`-AHG4SZ@iOq3E3`BG3PD8lD=+2DxoODY(=U~K^<*!p3)bqV&Yv2s- ziXFKNG<VG`z0e=99FJI$$QTb4*JMQ0C;PN(fPxUXVq-Rt=u9}y%C^2-=o~#6!rHXT z^YPW{Ou{pqE0AzYoB1cw@C@8<@khR_AJ4r6|D^#CAg{We`(acAmxCRRXcBt1#x#KI zz7u>As<_4s7F=#*>}UO4Wh1NaVGFro{m_;Lt*;2d&OD8v9fcr%BKP0g`NH4z4kr4K zoTqDh(fTEM5q<9}Yff~M*+M2Icat@wZ`+g}gX^AOg$lHZgxw6J@EE40J>`NOACjVy zZL)4$$3i@NA+y(X?0{=g6-Ian{BLW`5=Rm*F)JLOLKc`#k>VD)dmev>sUj~N_Vco_ zBK0|gGL7!e!O3BXGA3A@X@|Re0mHM(xJOI;@*=8ociL6v@9_*$4*i*W5@~03CcMrQ zV%CJEVgGGW)rm_SSLu2xTsx3Cok$71G4EUaNr@m`fL%lV(h=|T;;3j>krEbRM-|dh z6A+l44mLJKP%|4zLm$A|L_(e;>}MPH*ih#>cJ12DpD_(X)6c^J4$;cdL~K@C%Omf` zeqBq+T@cF#V%y{8#rN7>sn*bG<a4nPrzQ(^n~=Q0Tx<4#UnOZK@ZP{E-C%n16WEBG zfg;-)=z-yMJ(jxv!i?*3e5p!05-PjY@gIGEb<EK)+?q{Dc6s^=uzgb}xbTfB1x#nk z<cXp{QBP<F__HVj10{lgPcy(Op`~P?mm#Z(fumRb)9=;|$5hVyMz${o>^;GCe5$$2 zdcd<(h!kXN;_6YQ={~yIY3tZ`v~V_6XArkx%Qoj!WNVVEQu?QWgE{CY6H0k6KOzIb zQmT2sL4J#b&4d~4+&P&!4$0tu2c|g>ou%PZW`o;pH5>b+R=3vDeQMY}FL6p^P9R== zU^3b0YqC$>VDh8^yN_EZk5LpATG&APk)nVIU+Dypsc=q05MG3udHYbdqkY;Way5uC zdxIu~|LdKEDZ)A9;$&&nv>yvmnm6%uAD(o}`TBfxtw|akY6x?^Md`Ye;5*dbpI*e# z3gJXo|H!3)7zc#(^J<Thtp}4emi)pC-V<C@M7f4xFKkb+7u!!0tNN10jmX#QUd1jO z+_si7C-vAO;shM)<I7Nx@}eT;!5LG!qU==Ac&~|a*9X&_J9<|J(lE&@s^?LQScILK zmcgYc-Oep<MT0KblYBBhel}HBxZkn=Rn*w3(TX396_=^?EuA7VZ?dNfq>n+;&&i3Q zrL5<LWgJ@AW|~dIQzz4l<_-v-TYg|2+Qzc(vCm+|?29P138ZkCZ7%Kc;xm+u+pz1C z=4<$Yb*qQVaT_29p?jk*>tv!_Y>K)ECMfn>Q3H6srdB5p!<Iy@8e-FYurHZ*$0K{& zbkEGq0}bJTg<BQ}&Ns8Brc_~rq5&ewm&s9sjIa2QM3C?Ecm73!q6<Ft88{F3fu(#~ zll_mu7@JR3GKOKXbj9#d4$FTozP+8#omR-R7w%1#2u$LuyEMs4w$#pb-G5}f90DMa z|2<wPe|*|A{0G#JJAigP{_Z~(z<cn-F=rk;F?&sWqYFR;0{{U(M1??qa>TY23!xKs z4nM1N3iwwdDReU*rQUq@#86b9BjzP$1}3t;+czjaJ#8th4rUp27LYyaTY>R$W2fR8 zvqm(GDqB@g$G8?Qz}VN;r@cvW?g?fWQBd1<4<Jfr#hNiZ24(Hk(1P{(P`l@nOUua0 z0u`ToYEhu!$I7x-bsPe3i}K<))&w74t{dz73hlN?l5hdzk4$NAV_JG{JW!}O7c)^D zIlkdFXe1KGdE@!!)0miJh$=G_)-hNwb9{`}F^;e9#a_9zPyF)|O^+9z#JSFzU;iT1 z$r|@Fn!|cgR=2S1aY+&K5M2RTAG(@YLWupo3-u6}0)c<dp|pkE2+HH5bR4#;hU>9$ zCCadeLdZ@x1bxC*b*>!5mnUGCK}IXXwH&Ha4=w3zkA~Yc9>z@#dRn#_uCVUpR-he= z0l*gZK->Z0p*974euZ_KDBHNva7f`sn8Ce9v+{tr(z6ea`ynzV_yg;?6GZ>Sa<XCu z3UkLnGdM`Y@T&UWqun*QDZD#x*RZm{wc{UZdzNF^SHTg<P*p*)umIDKOsn^)-oiuH zF_2i;L>1&IZc!tHb=wXqdML!YVGwbE*Z64#bI~C<pro{-O~x<iGG@B-qyUaDC`7Ym zpUs6EG8)gGAurm;fJ~YL!BN2C0%M^JpR9rO@yt0Yts0jmj~qwNXO(+AM-DD`;b?`G z&>rVfPPjy_u+)XJgmS=&tT~c?&}pQ6x<Y0<(m1iNg%F3ko-ILvV4{whJmfM*SP!<_ zonk4Nq-53;sg6JKnz+Nx8YqNE#T+<et*`IJ&Qdib%c~1>(rzbDMAf5%YK(PRo)wEh zpfx>EFj*9Sh-E?>�i(j4f!!%2F5&8K_zUlcmA3$eH|rv-`?0Zcyk6cT}U6ljAS| ze#f>vyQaT=bqSqoUqg_Cof>Fgvl~>T4NZx_;{pzFN@6J-$+0#Oa~ww8t?B`fb7Y>H zB=eeru7<nJ@#4d&)9gp~8)TKVt&GtK`!lkTXe&oo)HC3KUFy_K$N*R~3`}XZ3XB!t z@v}t;lii$)wlOc*xCBFxG;Wi~1zlkk+=C$&a6b&|MIylzW)e!mI($5OeD)<nD$HA; z$PYtUEPpI}&)`@MY=t79!`f0=z|;$7!jz+X3P_lFyb+GLeCq1iDrXbtM6}zgQrn3t z3q@+b7ZA4uI|{;NgH2C4gGj>#jRI5sLyU|SW(7=MJ0fdb@Uy`Nr5KKnS9rc!?U;Dy zQiw-@w@}|41k!#uiX6_^ao{<ou(?mcgd*sK5<88=49a64&@#h9x6EU3YGMZ<ZdD%q zpOB&8G|t___#oe(!6V@s`GdB73`hkvjHL$saAq1{YuvPe`DAGcJMvu`VZNAC`eA#$ z#2Lgh&?VkTX-<jT>9bJ8Bz=x*l0xN0fzosbLSB9XMWSgKDKomWsd%_%Qpxx{#Cv1X zQS>I8l1ph{+lwu_n06+WPFm-vRNg1pnsh9wod<q<<2`0Hxwu~vQ5UspS43k<Uei00 zO3BP+KIIrSNwZ7Q#a5c{Dm;xMN-i-?7ENpigRxEKDmUaeO+NZDno!u0*Ztxru9bGi znYJmfT=UAbZXWdyGb?(NBECrOD7NJCSg8gc$Gmz@hNYi&@CJ7`Q>*X;d|>}Udp4vU zMO0}trJaswe43PyMmbfBPBZuHa><YTs-1Yfo0QbfKX8>qZQBcedw;+s|I8h{>kphG zi)~klZU>2nT9;fxk=dDV)Srj@u$+kEL)iY(+O3(&7KY-87!4r`F-U|Yh(j`@Kq><e z;ZCbt;>8y=vY7xuLWGGB^$v)Mlki!He~M=9WF>hD{00Q&@1z+^jdMM3R*N<ry7cHX zV91Cu6Q;%&zlB|AQ|viFbL7Msh6`72v6VFA2@A)IHy?Pu{1A*dQh>n7h#H3oMG__) z8AXIhZgAN#V#T3;UuE!ydruO%;7Z9-Vy5KN;={|pl8G$~N1AjQGG)n@BUj$I_fnyv zZ^Z{+3R3>x^=Ncdm1;F=)v4F;lT?CczBQ8e)nDN6;th05z4{E}%?~(k(2!vxMvWOa zVbTdFf4m;)GtN2}W3%>xi!QnBO5DxOUU$Py({7n@+pIh8y666PTL~UD^Tbon%z5sG zm*y>4^am-uvf?_>%v<lg_rXV>e75R~uX9Ise)l82Zo@D4gMXX)*FP^6*qF>LSYf3_ zOO~y&+B(*?KI^vu8w5ZIMo<hVlE@S)jm}`Q*c>j8FA$2v5~)nCP^#1#txj(+n#>lf z&F-*kPXH+>WFO@~SOo1*R1D)tTmma8C5@AjmBY&u6o`r>$AA)9nWCbqMpf6)q-kmE z&~^3n83s%zEJGuw?yy5SV4Pgsa2{Sh1iyeFXi`WRDIzL{5|=QAmXwmln3gevHET{5 zXWoKEyd}$42v)6Gm$PBh7SXmHyCi$|9gsm_2owfKAW>)x7KbMgNn{F@MrSZtYz~*l z7YIdSiBu+6C{=2WR;M=@6_tJ<8|jKF?Z=<-?>f{G28ta)!Tv-*5G7erHQg{R+W|lb zMo<hVlE@S)jm}`Q*c>j8FA$2v5~)nCP^#1#txj(+n#>lf&F<LU3y{IkK6Ma|(1+0& za}-ao$yA!lWOIC8D2PSr7?k9)QmNL|dZVee+8w>y>l*{}#2SuH@7PfX=5)DnkJm@| z13@?$3X_p&jEX0w=wvF*OlM};*|{t?zp%(JEw2cxYwNj<%`I_zXII+WKae39K{1>l zDVkw9UJxZ&Q8nE#E!%NDKM12ZNwd5ttGa2sei)~DS-1T-ulsqw|G@*{8P9=+mX4l* zkqw3k%ND`mQ38=frZBUxW6yyjC(c~Ba^uc}+U>&7ZTtZs*oDx4!^{@5;l%Ioasrqn zqi4*1yYNgP`iAuT|J?y!WPRD3`O>k}*QFs()N)t+DlB-tw-6($_6Y5hPcEy)$)-qg zYbOFkqE3a~&#!mcOD$GA*{0-x)vEkTFR|L4bW2vRv;&z~#+I7F?)&1lm5RnHCuKDV zpjw0EcB&Xsi<L~ppI!*EB{8_=Zyt33m+!t-<p6i&kw99+V^?9UU;d@0FljeI7Xxd& z&O!^0R5RP-(YAm>7E73ZvOZ5Cu-enkIVWBvT=&Bm9|@@)_Jg@Fl1d}cPD(e6)TF7M z4~jhrw{|SN%}mBrb>4g>$6NIftI`*ipnCcXAwV7+PIuL+wqD>dNw;>ZUw(y)CW|$_ z+>OMZr~H*(ijZXJ*0zC{MtX@~Z|322y0z0lG>83c4yr5yv>XJB)vlcDPPeuXda=ak zPF-1Y+d)khYwc^sU_X4tRkMrzsAiSIl!e4%t<)Ae3A&h305Bo@hLn1G4{F;Fbbkl% z?5()xkQD)~!Uhj7w@Utc6_y3f#S5&8`=(6R6;L=0`$9jAWj8nMH9CXgfTfJjk+n`~ zl(Ox!mD;*j?=x=V%eORjt1KDLR-Sy8eqJD};>>y@i(lxV`r%R56lHj@Ib3<$_t$*( z-_-ffzkc^ObXm^}eVJ(~47{B$X8rQIzumSxZ;vi7W)s_ac<Ei%^5P-kN3~K%EGf?1 z<k`w<JTJ`TVyJpK8m0zl#ZQD!v-gO2kh)MBoW0Sr=a?p>2)D><_mIULJ8(HNE;|qN z!EfJDlzynzQY)|Os?&^W=J{Dq9{!?wwSOkL)Kk(dDZ#;uZZ;2t!&U9&{*jzv*m_}( zG+hg7+G6b*Tl%_W#i_+wDUYh0E7|g3b5O0j?}vR4?K@)1=y>rM>Mfk}OrV=o9!^r9 zp>94D&nb^?EWX{J&-*OxU2UE32RIsd{%DPNCQu;LP?$amartsw@?fh}Bcf_u@uJHU zFN5kQwYI-YO&^qcbX#*3SGZ{Qvk@)ff(Vswzbl;WCQ)<di(=@}wIOB0UP^UAp2Ov- z+J`O8@n*5wNzh1H3}!zYAru@g2D)DlaoDO6Fv3|Fc{WprM<dLni1zF_TuhucC0km< zdW~P_=wtP>5oOsNr!=dD^fv-7d#Rfh5a!JIiJOm)F2pIwem=NFOEUAvTXcJw6o#zy z$q!+IW^euz{Yy{@k3-&Rp^<?@GK&i{)nxQb%);lVoYi)(xyA?2x9i*L+XqxFFAwUq zO75PgjBC$Pe8SB?`<MT?p#T5*k6-?0F#h@U)4z6($iJpPv;O<<kH3HZ<+JtME#T^y z`Qh>D|DSwV3Hwv^>C?jp1B$_Ck#Dpe;--PuEZIDA`Sy45!bXTy*@uxa%8tE|I<4ea z9lV&Q9T;>oj$92y^R%Fdm!6JU3pA8;QQG?Veeuh+{#xf>|6rf@t^1|93hal-uZ`G_ z-|XA}e1M;S_~~Ddbp4x(zBwnkc*ps|SVq*1DNKtu-gr#85ajKw`JFj)XXOoP%8B;g zfLu_yvE|vR42{*;kt^lRjYlPq1j(=L98ukVOXi$@y;D~!EBEu_0jF9R#J9a-Oo&@M z7hbMa@<u9e@N<jFceey;wVg+6YHquj9VKMn&fBNTI?r8a`jYd#-C?69k5E#$(v7W} uNnjFBcEuDl@!HB52&!k6dfy|Bfo@*9+#YXTyhklqZBO+`yD_#WD115-voe1G literal 0 HcmV?d00001 diff --git a/.next/static/media/ec159349637c90ad-s.woff2 b/.next/static/media/ec159349637c90ad-s.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..3c039fcc6ed083671a153d328b4b9deb07e19f0b GIT binary patch literal 27316 zcmV(}K+wN;Pew8T0RR910BW=V5&!@I0L~x)0BS}60RR9100000000000000000000 z0000QgC-l5avUl@NLE2og)|0WKT}jeRDn1EgD@{_5eN$UP~=MsgF*l>f!1UJHUcCA zhJFMf1%+G(k!c$pz%|OYPmN&gfIUC`Z=4D?uF!iNL@Sgw5@9zuD}3_*pOc)(7@rAj z*Lka|fPyn!<$0Vv>m(8v)LM!1J;%he*=HSdK_%R?@tjzF_Zm369N6|qw}uyCS0t%M ziozrWqCw272b0WF;B;k>Rzxte>`0aw6e-PNh0Wc*M_ogE%NyME*``N-!{46o*GBD7 zIQ~I}CZml14_gGd(?g`Jr%%u4R)5aTOY#yz2oNE%b?l}gAVS3Gpv~aR0tAg3Fd{12 zQ6t74z=)xnnW5<fn4SNdv6yYAYM5TO)&F~QHa}Ixl+4bbp?A7Jzr}a$dp@0gpZlH` zZ|qri|Bq+e{j2=<`<|X;!FYDhvh(XxznI;B*|WSWJ!6F^Mg~Cy5k`0nQ9uD<gb_wK z!U&@w20TPD0!&aC$78^gIIJFG-#0w(wjM)8B_na*N)QL;ik9<|1e0>k64yj?rd}=* zDhGx+QAsJ4Q=Fxh877sbrKz2E_iJBy9i?}9MV+1SFU@~eZjwn`zJG}lSe!uk%q#5b z6~eEv<nTa$sPB(UaI7Jki$K70p04v^u~w1|Sgmlh_lM`%=Km3|bW_rsk&)i)W@KdK z$f&4TU67KB^;o&anrpnWVm)TAna|g(hd|5Mcz(9A#)@sc#%uofSYwSfE7w@vdeoR> zhDAknGcroDo89cHS2UTf<)ERWAywbrWO2=so=dMrZj#7OJz?${<uJn7!iag^cJJS& zoJg10l=E1lV4Hs$1P#S#DrIc`)2%YIZHld6XRO#`j}V!lp{P-_PL_%I2SWTn0wI1N zhEIrLOK*qMoIP*r?_TO@`*GpF|GDSgXD%iAgtBCOQvgsB=+4V4vSU=0C~<j0S&1(* zI4|Tp=-35Jv2x<`{MYyQedy23+|=vy{nzhbPjV7xbE0A-DTzceVnR+lG18QnO+-U2 z8oXX2%}`}3%`n!7TBgG|q!9g&{eJeMDbPKdXh|Fr)k7wme9`z@5RJT@#c3&J{z-O{ zPf!a;A-O%1u3=l`23xQLl@)aZTw3@`hnt}kLyDTx82l6g;g5zZL{nuQL;b-xQn4EW zXU9P40N}oIt4180@WAYP!Z6CYzc<w?{SQtJiK7Kb8E`GM7VD`!muht9BO7Gr!^^sV zH-P@#XsUrGM`(bQ08pB00HUq|kULF~EUD=vKhAQEwJ_u^j0_1#yTj#JX}#v0G0|Q) zb(zgvbeC<oL3l}cp|@dnVRBJ?@O>N_|9L6AfWb_JgWk$c#y6E)5efTY1ka+Sv-dxn zdM>?4A7xA5-Snywn$S294xvy2g+(|J2M2Vrh5<+xgcwvfZ2q%LO`r?qzvZZN?i{U1 zjdKW(u-Fh4%Yo#P(LyPfiHy}bf0&ajf26ds&tev1gikSwPA8o1)IN+&-NqidGEm79 zF&^;mVyOS8t^)yH$g=aaXOA(n7)|MSlfKzA)s6_GvN|G5_`e{70^8z|5E?N?WL9L& zgH4`%1)Q9UxRk1}!S$+Cw+5&#P_IFwt#;ViAW$pX9oVN+%mD}W^f1sd6h|jfA4&#p z@dX10oHb<Fu-lBd-I$D^DV?Tm^dsBN+S3Q{DIU^~Jmm=b0wBBy=H;|rb<cl!;4O>( z;EBtYXTb|F=&lAh2!I=W3gTpVBN~6dLNS2&{QArbW;hZh<4KAp-*Hh)Bv$jVAb}t& zAB+m*D)N``b9jI~ZIj<PWavgf5j!g?!Aojr5EaBJ6p5j1lIcN|5mdp05I}$efV2r9 zDwoi}(p&-$bD%F<7BNbOgeXMbeI&JZ2PCyZ!&4W_w>zZoVKPwHM(ve{0G_POHd3g~ zJwHid>z8i)xf8Fr{H_)OipgjFc=6G3q)N+|gO^B>-h)R8Cn;PHYB2y4dz`V?*SVT) zvT9npy`__Eau-2KeTT%ZDS4|zLRoEX1XdouG~RjnYI_~)U=K6qseKPd>+y(giAyv? zfS725&#<}QxLKPTn@!&X7suRcyD6sw+q;#+me5pE(Vh*d_J_hlfTqd9l=Uq6e=C{V zfSLYF{^e}M#=cw`bXPM=m+B{{1-5|sdEOnVhi0(dR+-a1E4@dVM&S8#{-zW*^Yb0F znO=tW9?xIVr`l|JT@stWU7|Ykav?CQeNq-h5J%5oZIMZ>Gvig03`cNw0R(Fo86md| z$Om+h3idc)tBOhi=mH82qriq1W)xJLP<d+}Z2>t595&0KjbuT;^$`pdMrKwvx$N>5 zl);oD#nY)&nR1LUy0xuQw~%x<+QMh6ZqodFScly@9dg()aVMS9=d|RKF_=1MrJSqu z|K4WAm^)+$LF;wdV3W;W7T2xEZ}r;c6-lq!ZIAu>9FTEPze5lIKIV?Q?s;h5V+$6S zi7njcmo7~GnI7d76{{C!RMfU%>1&r;^;6iPnbGltqu4`7o6ZGnLfEll=@m{nO^`z_ zLP8n~YJ@vT23b`bSB(id+$r*HtI>u02vYr6wSFSiPrWe6xI73k4@vQ`tK$sw807G{ zm0)LUn_hLdUXQBZlHh(PCBK)l%Tn+^1$S%cC=^t|05;51ggn@s0J#`2U}BxE(PNQC zLm8G^P(GYZE`uzyuyS?Skw#1o!TC%fYAa`mP#>_jMV(!ya8wPYQ8@!h7;_O~k%5@( zcNJKeg)TrY-_au9wUP`@yE5@Z^BvVJdvQLgHV2X4xN6p2o6@(Nsf9oQ3(8w8m`hg5 z3KS|$)h%J=z1aX*cCinLndw(;E@@j!PvZps5?Lh%hDsPa`jyojJpY*`092QF>*X@v z(+_`l;_0`>+tqLX=TqC~wy&BOj4v53GQm}Et1oFUYvxt+ntA<#EG8$lf733hmeucK zlzJtxg00kjI({{Dp9cU^CT{dLd2t2O00#^JZ{7|4exQfIKZ+ni&@|M?5yv4s3+j1r z&qH{gcs~dG3XE5wy-pkEaPCcz?*o2F;wQ+PC1(!Y#{hi}*k6J5C!qcU)~i_n4&VUb zTs`9Xvf`Ae(CUQ1bQ3d4C)4Tm4A=8as{g=5`YDF#?F`k=F+?ZGCod5Af0*&~>+sfF z6qh8CGC^$WHi7?d6CnqvT{6^W16#F=WwrBVvPCk;MKwys+)!C)hb*?k!X<BBXvK`i zEFFR{85Jr;X=Tjp(5q6)Mn|<ExmB>NH7jb(jau`gRsxA6ltpu+!Te}6FJwA}C<0Or z6!79z;w7%@?QN*8ZeS4Ps)n6zPzp2?i-rpc?{bP&wkB){*VhjY#$q1UYeYSQ2L56& zpbQzXSgM_F3OMILx3BN8Z<v2T)i0DCe*Idaoq9A{s19G?Rq4^D+u8_tA8E#$Tt*?N z+D+Q+eSMmTVI1WUzwPY$k&*JF7l{;KUm?!Wp#QLE-L|p|Lp$Ju;<FVc=T57tvRK9; z+8B4VVlA;Fe5a1icDhdl2Ge4Crj&>k5%tBb>_XH}M+(=qmluA$v1u>w%Rr61a40kc zrCN{60p{(x5&C@z*S8q{NGc;3697>ruI0bf?Am+w;{}IqVNL#vz)>;j;TyP3)GBbZ zAyNsy@tmxHO5&PHrkMkrpTRVd$jPlvldzb$ej_Fk0Bn?i_U2X>-5r)-I8cOQToCWW zy9YK7n@1z$@Cn-H*~G^elf}+LDp2yS-&o0z!6NH!CHz<|;t1O}@q4B3%-iz5Y?tiw zPnZ5@5;pX;#c%y6Cvx9#`H@#$s$8Y7Se;!Pmcip&D3J11y$=5s@Lf4c|L;!w^|+|h zB?4s^U2s9xRzuu1I&8v5{kCcJJx9e1+TwLlhZNl>G2pldX3WAl=`95+Y<0l_t!~#U zZq_(;eZo%5mz3+QJShi^>2`;2>l1fUn=u5#_Q?2}+eD4%RPUgyuvZ;(+1rjdW!lf# zoMSiSKkc#1fCh>xM%Bz}Sk>wAsush#Tye=|p~gMvQ4e{<W40*slqWpxj5$Bqp~X#h zYW5#?8}(Sb^QexwUfS<0f&m-^a<Wj<j6!0FFA(BFu*UoVN394hCQ>9k_pyf>=78ab zMow`i6A$lb<}}Qu1-l|*2`^ooi^lRB;34D<QLaZRPcd<G2pKbo6zt_C$OW~zXZ#$v z<4b@5KXV6s2(sBG0>^a>mcX^c%Y}st0yWU?BR(PwCtSmapdg7?Nqm@<X3?#b;=Vg6 zXhD{NBPWPG_A1bTQUOLmb43H9-=N@-x|m~!DM;L_Ymg+!2%iG%f{-Ig`rOYy8F9ga zrWGmRNJur`kFl*f_CrK*%P@V@qoB~;5~c67?Onz_@1t)#*yS_VVNC@PJ^}=(oA%@s zArd0GlpL7<w46(9dT6=00aqDVuW)b?VhPA}(uLIWRvWEgZRrI~v@bTN7KSeogyVZ` zXuy-1%g3>Jbxq7Ulp_4dy<&j*^YK_rV|+=qMwYXuu05HQiQbtcyx0{-ia0*NHfaRt z(hI&n&QKeK5;)1!e^gqDw#tzyAaDQ3<w)GAJ_&S~s!)qS7F-{7xsVwl=$GV940QbZ zYQGj)Ug1jkrpBDkIgAdzGN*8EcuhgKB{(W#wiM@4QDF<trz6w&@u6`obSMgBb&=pm zk|K@*qrx;|(Z(9F%=DsUXl96TWaIs^w|T6{Yr4eX>ads6-l!U(98b>{2HDh0Bk5_V z2)fNlp_ZNB5xvc`f&z)GST@mEbwG(zR5KC9&+bgcmLm6K6z&p7Tr{_sJ}o??@{s<( zGSw)40g;kDJD>~hjEu<d9+OA+MS*@~$nkpTN9G(;dDmeW8b|HXJpM~XqL+piOg}lq zomW0Wk!bV%Vq1u%`KVb*AV}DifZ59fxQekr6Av~3JTGXpWAmC7%FMz#FUXOc3w?@# z_bKL2fRRV~3`Ne!AP#-}+$z1^sB*2Ua&u(5b*mw1xme(DWLo%4GH(Xx3S^N+8{{$J zNFISqAaOfc7Mf2L(4mEm42RN`<g?f4qeGtg*4<p}DuhjcDC7&eu|AZcLxEdexy+OJ ziDxG38q!QhsYp;?Y%-~Nay(3I(0Szqbj?q;TPeCEiFq(PHM6(iaH5n@G@1iE!RXNT zl}~7vuq})(QV=zC1rV(Z*cspjj3|DO&`+VUbVcY7Cx27#FwSd|9S)_R3MF&T2*_}* zZ$0fl@39x^K4GE?_7!uPAaKs@5d9RV%Yd2I>xT;vPxOt`wjX^}SZJ~ERy3TaYae{( zsOuaSc$oE+zw-8NPMS3S!^)+_LM%tfp?sQ!N<H@cI_)&SYq$;d*a|Z&;4Rz=4~&8A zB@xpM(^)Yp$ym3m0fk@WfU>yE4>12F^p|(xgFD$7kDlti*BcHw;7Y%>>OH-IFui^M z7+}DaN&l>2Coaa=I;)ECS<0g|qgdeV7e3HKWxPTi7!mUgM>F(x6rC3W(5)-I4y)jY z6DxHsvMl--BS9P`A=STOD$Qv_jwuvuG9@9yQHzl<izE9mVY@=bE3I!D9f{~EEI_#+ zR+W0v%Zpo~E^ZDYDGL0RKC@iMQDgx9BhC}~?8PTe)#G?G7}J;5dzcboYrkG4?=kHN z-22&YaQVJs5~&^t{3ztDxXV($-@ijb*520q3tGSrrgO+lYr)1nT@XSDhzLLhNN_|T zcQC*(abZePpL{~G`GgBe4%`&Sy+)j{PHvpgT*4(%^-u4<hMXaByJ4>=aw&Vz{KqEU zbSQzv%sH1i<+!oxVZWEqTg+vp=Sh!eRHkP(l!Xk1lc*DU8-L|`+$+=!k)GXBcerb~ z#LdBeiY@E{II7oQu*AJz-25`qnLvf24HW0)or{Kj1HQCcD+Jh6uGdep%5sim%EHoU zG0bU+BVlU+a|7q9LQe6Fmw>|i3E7QSgaL>1eu%6?i|}Q65jTM07wCp6Cs)V;*rFlE zI}cq<DpXma7=as0-z!iQ77Yai+1T%?<u$|ewek<gq~c|;7SHWCuJF>23tp0(ty}y` z)k1+w!`xuuqNQ5bvJ_<a%maOp(3yI0CX0+v?xh)f$r*cFn{jr&fUK*8vw%X^MO|;m zaZK4=t)assQnrs@KDL57B=+$^z4~5622%lU(HGVBoq1p>na7@9jjtSTZg4*8ZN!eM zLTe|~*>4HBO7vQIyL|TWvPt!z7rGAPanG^S@E=>pZl_)#b~d$gv@zCENW=Lob{3p_ zF)>Sr+c&&rBG+!Vnp$>&qlSnDWOI~+n<*}MWo168Puo;YTa%SVd%TX`ewP3#DY8>j z=}|+0iR+PF$mQ=pr=839j`xnyw};;2TW-H<;;dn(_+(<1E$)~eKWe+?ssZH`Cot-^ z7Il|G@&gV?cuvhFck0yk*(=k!>Z^Z{t*}YtmMZj0gnA?<ARu>SPcd(j@D?AaLD%Bp zm~}=$#iDS`w##L)NX66BI%09|_@x!#G7xngCGH^ZiLr|*bV3fY_LObY!#fu5z}M%1 z9RP6Ml=}5E3Cs&TR2!ACA8+JG+r}|?Djx^odP=C>ZFgocoLw1Vc-_LnT%E%h|D8S> zK>ZIW5XnJoe1s42$7Il3Fs5N<|2^YQDl`p&`t}mJW^(Gq=JXr3@z*VH45X>3fcEnB zc%tK_rFLj0$qV?rufO+VLR%CYwjM0gXiT%rO_=5bcwc}VC@isOyN2Wu8n^BfrPYBL z{t4OZO)7PdiKCu0q8iiT-LtQ=H7U`?c40pL5&;Q+2^pvXC^d8hC{n->zj}cJNX-)~ zy_>yqwB<tU`Kf!U`J}y5to^JakP`x=PgMwUMo6Sv1$UW~1X!e;Kv){3+kj$=#$k|k zAo&7*4cEK$bx>#l-2!?B+kI<Pn*{6=JkB}Uyc{c30`~E%a2Wrra5S&I*b+GaP#F1O zPcP5p%9ZnGWbxWMw0h}YX4vh*!m!Ev>0Kj0sR5`CV~7C&WVwW~t)T4&1SJ5IG$zqN z;e}g5+jG&3%^4aCkRhPIynGy2|F27ZYubp1Tmud-KmRfP+(JDoLD+X}!8&={xgBD4 zA1ixQouIR`=N8Y@|An{XxoQ5VgV{$VMk6VCPe(Uo^XN=w<~8rA#Y#z9bRT2oRjhuQ zMuA#DxN6%zMq*gu)gspOf_;hF^0$3Ef!V(Ii>EFAJKCpzXEy&&?^{EeCd;vc*@3e7 znem*Gs@bz?&rfm0C)ckQRUfP0mzHec{l=M?)g%7K@RrPr?@wIRYpX<I@9{<JBs9W) zJ$5MGMPWy`<Xh{(7Ohrl>1jf`!jxCTAW&HIArMGS{EF>NSKPY~z3~Sg%y%I2E-hng zWV(rC9sIM8s!zbhLm5hsKCFzm;GB@B=`X{w`72;A=I8OxDbn6(nXEVQ><o0Go)ts> z_G&H!Ks|iE48V}hXzb5jsl3wqS5X<bJ1Ucmj!$=GUyVw<p_*~t?v6O-)4Dj$3-j%0 z+<IR`qsH7~+swr%rRL@+<(aSAE_^35;FaPzCz}__G!ndb-Sx}kXZOt#IxAGtQ-^SK zi1r4%?=6E80Q0vS`VA39;^_L@W|Nm<{-H0$n%tJu4Ms<vYSOR-u3Q|4nsQXv-Q~xs zP|axMU1vRaiW>t5xV3=!@9M&=ZMiTz{9Ty$TPp#_|LAl~9p^X~s9CNWpSUaAB9B;s z0=m{ThJFeGqT!boxutxOJL-I3p%iD#jnHgW5yZylfGi4t>7Or|y<WAOBrisloe$3) zmXTzy(HnUaBE!jgxx$_<QWw#5<u!vTWQmo+S=2?r%?->gOH;&>m_V(R8Qsd%mGC<| zN#AIyl1@Za0y|Ux?mqU&KT7URrA>L&lb*S(neeR6)J$gYaui<(2@A%86Wdc0!<#M# zW+q?v$l)U6)-&8!{xM|_PHb<i{Z`vI^10a>Gimq~HTCrf%JzF8EMMTU8s?9pS?v;t z1GU@serJolHJEC|6Qn?>0*$ApiZ&X-jGz!A!B0%yP59p1?nk;Zhxna%VelQZ-&Tz@ zAp|JMO_?RN#LiwC;UNU{38#{(&Vy+xR)Pw>blFekYw+~lIfsr-{q^zn@zR>*K_LJ@ z*!<XP$<bJQmvCQ0cgw?gG%+N{XmVKGHew!`+<7&I55htK`X&HSr<;b}9Ee9`ejr1W z81uN>aQlM=Fh#(m8k2e_53~GR&~@6?1e(T67mYGPrS?U1%+l_Y9ot{8fxGHm2{dnp z6q1J55baC@kM(~1FPo}SdRjeINQbOz_zFWq{O#61fTHY-A6F}HXT%Q0@?I@1&{L3h zN%TJ<#|i<E2lRdsVCP@G|281Ilj|yZyTo#l`^Am-QkeI#RRDWjyxT$i?t9AW9igsF zcd8@m-KPzg0kJhG$xCI3?%F+QVde|QuhoIze<{({*{Y!DMYEjaKQi>^S0oPHSIC0! z2O9F$O1*az>#2R0;tWP`vwT<en*&RfTSG@4mGFc9<d%knoUaI3txH^mLh2`gs$-sP z9vp0*MUcvUkzcHTpMQ9In}_a5z3*>-{^_+kJZQ!DlYn5OrL{`vpMRkf9X&`if4!8i zi&DwXbDT>KcMQRSqW(Vq_D8?%%-;EQnEfx3KK}9+U$-|x0-|Zl?u6~nz8so{-)Z!m z&2FLL8leA9jWT)&=WH~obA#N2&-Z{~n^oDCUp-0BEtv_-6BRQPCjQ8o5KeC;EJ}pN zM~DrWa)q~ViaH~omh=x{99kY-B^TfN8-z}>sFT7c?X<V}fS;00Vofe5ZUp~{Vj9N* zMJE6{1{Wvg0z&&shKvEmtp&1?cOtCT$&Po#fir5A@NnHpt0~8EV!-At+shVGo#o8- z2*SfReq~=!O+$}!P1j~*0FKCjdKkotAfsU!Z~^i^hCnBL7HrjIxH4|h)>E#S&&5+{ zeKRk=PF9z%$^&^Fn@ZbyQ_fZ2&o1|LKXJzSIBE&5swie8)D~5+hx3ug<>~L$Onglh zbbQJvlN6NIwx<y=K?)_&Zf%Up3y%~sx;tUX^%G#~ht@P91}H+-YmF3YG$M$;d^5!P zW-Yr@-k4GKcYkFsaX@hgRPu!0c1`PQeZ`NDJ<U3fQ;9n5d103#a!!prk2`P1CLFe= z=3_XFev=Arv|v8JF`UxJ@YwSlWn>YAhJbV!#6}>a3c#(A&$yjy_yN1KJLQUjf-Z1a zH8L7}+C-)CJv-wkd!kB!3sDFx$xHJJAo=)R5Nkmj<|51oT9bk2@l?nMvgN^~u{s5c zUOx0cPzrAZ30;3<_~XZog<Wn+E!br`Ls7l6jGbSEC}&rQau_eXgydnPG8*t=C1Dn@ z54Y`oYd4oO#44CKJdZJRqp)(<VWkx83tXg%`nH54`)jaCae7D1+$&T&nf~C_wW|MC zu;vovZP04jhf7p&Sg$LS$#O#*nvO8)|2Y8c4H^o9Z{0vXovvqTOwAyF;cW5CudET4 z6&L@0<uEV1V7RGr%(F~RNdwNVrI_B@fCaEXd0Uu1>U56Zh~@X-4+Sf)oi}iQExF8R zH8ygzqh{VeW5IZ_F?`l;rZK{JaiLqG?!vdG)!^v*wun%$4>xv3efzsz8AE=mv+y<~ zfWX4-kjF#Et|2o?D;u?TyhYb`E?&3o=TH%&BzJ0_$-$R1rpZUhKOlfgmX5ZLo6LIH zPZr&LP*tnrwpeJ`k?$jnu3%5SN~$;x7lh1{(Xa^q7>Ia;#!W>}-le@A=uJjR4{|ut zj$|$I$ji~#BaeQYB`^16zRS3N()6i_3%O)u(xwVBE@y9>{_<4yi~3R^$o8H1Ej0AR zj9^SOsC4K8aCHJ`6iQbxF6C{E`9LbCjk*4Eg|zr9?9+|)v){fetwyZuB~QM;gvAw| zVB_+w16$5AD@?5~rcteZFb{~!W#dGPLzHwq>A*U$JxLiA3fX8*o^0Fs*VmCLoJGEa zL6&op-W%%wtBYMvbe*x83zvYHNsaa28I>y2nD@UA9gK2miTk$<wQepIzB$(_#2t?- zn$QCm-x{WaB4^{?E>uca>WeO<*{^|-3+%h*RpeeBH%3(i!Q?cU_xOWhJue<gZa#n5 z0eJ=GBqfFAfJrWCj<=_3X>v~KQpcQ9%dr9nSJyalCJH!C&L5dG{XDnwdCu~}9N1}; zK*1Cc3zUMN;Jb<@UoX9Xx7qROw=ct1q^IQ0t+PdpMcIm5i1{nP1p?x(Vwp4a7J zZ#9k<Xg}rKuIR6ToDdKUnw9m)1Z_PZ$>p=t-O}I3r?~ZFgHwWA%hNu27}e`Nie}%O zpe2O`xzatN;}2#shl5SJ3(^Pj2mkMVVwc|&9@=$c^!3COsj_0-+S=ze35J=+Ny)>2 zuTKGm3Ih}>$FBF}R9)>6cRfMWQ(Ag=rGe%j$UTCyD-2rn(dhS#DuMjx>L1{!HrBh^ ztH!3dXRWhT{@eUp-p;CQyD_Ky338)z3E9!vhvJSK-^~}-H2HGL_0E0d55Y|L={+%f zS*w)?TvKC09=EUNG*8^e+;6^}!yWAr)85h~+#lb676>*u=QS2E^H=@mSz5{JYR9Z` zHRdr3pr48z>JmwQ1>&ncRrxKq?_=(_On}2Hb`S7V5iQdL@{-lhlB32Qr?LyO-9fuy zi2w2D(@4E>N5O;pT=4j&Pn`BaLHmC${k0Jvx;OEguO{2>3d;Iif-l$mR3KMnt9r-~ zv$r8ME1`5`r`;V=Y^-DCfYn>+!I)_~eLKLkVj*7&h|!cQRi3?$e!%!c>f|C-u}Q{O zC@}CO2bj9{<<0mk=^)QTk<H3d+~j;Ypm`{(8>>iZfcJbt%oV)ZZ#9cwSd3+i0kpz; zd<&iDWdRFMl@}Jb-ywCTm*;~V`;5VaF6za-p7+cM-uvqe&wEI~j!Uz$SuoqTc^BJ_ zMBMUk2aMwZ&={0JdHD-`!QH>wKIlo5z3YuRaQ|2PuIN&yHSCXSa$W*07(J@@yKDDb zV~o+`d65$Df`SN{9C-0UIHT-hyF2W>-KnGN9=`s(#ysFUfnfi(_{J-F1<hA*G2_!h zsqjW#a@3{RHo>hI(?9uLpF3T<q*6Fan{I6VJ(@Y(b9Cw>tYYBP=pRlOL?^RzZWi5^ z!tWfJau*(X+zH_oGk=*nrgHAUhm^6_k~wNIV%f;|j;q}*%`vx9)5Y=?ybRCltYqX2 zRq~n-=T|b5RxIMY`oOFUIKL}9p!iValSo$e3ufsnu-KOm_}Jmaxtq4@xnJbp0Ykk= zsO3db>G$!viPCQ`3ahK1F^gY`C=i9$T$#gYxI9=VZs@TufglF2M_f0^yUfUGtK?B2 zim3S23nsVvSz+<FGj-#|-)|O~++ey-TTk0lQ&XctOx&HuDEZ^$Cg&2eQ<i)7HHoX; zHRKCf;BeBecPdux-E_YJt&2)uy<k=wRw!E6Smza1@(b@q>~I#)%_?om0P1=<mCU5G z4}QSw<d_q)k9@(ohV0uUuC3oUj-&ffot;X^P0r)wd<rNmV%}hx;oj|tTPU!5_#c`t zVEU_4J@bc?+MmCMFCwDBxIzulTdVmirr&CR9bMl`Joi^*KkqN>+PU{J!~5EQw`8^! zd#g<N1*mtRW!???x?>&axyGQe^}{LTWM?)x#yQ&xA0_sTU?jDH%yf<-13Txui^=D* zSuI><;{j)1y1P@rUf3}IL}M+R&96Pdw|DY$r#t#>{eINj!ez1f<@g7jeBE6S`tCr$ z&qEze01Tpmbh<^!r4yhdkp=ewr$8-)T=7`&Vv194?=!vc4tVqbbJVd|?cH}C$cE9M ze?7;Fd_%M;XKUP843ET2b^jhIalY4OAl2C3^3dUCZc!!!4w3O}t{p5jGMtB<<#0zL z9P(kh-<t{!|5pXO9C(KCmX(&g<q`RaQ<;3){Y`+jcO-9mtwGy8KpQLU76yNXXMbzN zIi)+JskP(!%ccp|XhwHN(vidQFMW^iD+Kf0lsZ|Ro`rlwz6*hFpMEITKM^jvcs%)N zm2G%tkRZf&kJCZ#{U!<S21iWdz4sq<rT?UGNRU6&!g1q-aDa3f<U_|2$0gWY9{OcW z1A5;r_+?z&BY5v}#~A8`w8|q4h!F>f<vSq?o(DF+GUcn)jc?8_KS#_vOJaNsynT+g z@Tvyqn&)4p3_AF5(sIAGzM@cj>wo50izX9@V8;1yIB)r-e3j$f=SPb(!k^o=Ad5|% zCq<;-?H|FjfcC`~F318K{Ktd`#;xPmK4?rzSKN33Sa&}E2!S_zaPn6$@T1@Wz>G7( z1%O`+!icFNnl#pr-va@%YWk}kMRA3tODZ1Din~`Pz~8*aG4YKfF9Td<<1u|xjenq} zXv8<?Le~b|b#)Jd&)BGDC5^t^s6xZ6DX>Ywq^4&!5UdyjCi{V8XYbT?U}2a8`_Zm` zKP@qkKsBOMzyKl@+}suit<1rHtcG`Gfio0+my)P_*n!bC!9ovwcTMh!RlMJ}rf=vK zqBdq@W+8njZ$9+51_Rj?X&8%Hb|ggA{%keSx7sk#Tee_iv{mJ)0ZcXiY&1>_Y}RRg zWkZjy!t?6RX}7v;MdYaOJ=Y<tbZuz^{BqWOHWeS4>%fNHxvHO3b|KZN1Jcx4YJ^PA zHQ?6ooFLX^ZBJ5GYSk43cRYYfOAiE8U(Z+o;R-R*)N7N@sW+z6pI~4RHlZjvomC(~ zGS?xSI^6-AiX1F3v3L!YD6nT(*3q3^jwo0vAY$<MQQkG-w|G5+Ze8aNX=&_mKO%e~ zgUMEf<qib191;RqfB;~}MR<??O*`nKe|D_$N^_9g_02drI21m}kCkhH<$iRd>z~J5 z%lK(LapA9K0AQb4mRH*%*=By41L$S&<5o~wa3AZZRRC7q#_{TuT%>~9W9Dbv0=2`8 z^i{P>Df8F;B;p`)_RdATwQ;o5jY3LlY>Dhd7w;RUBUY-&f_INDCtoE?w6|{_%$OXd za7NlmR?xi*)Czb#Kf)1k13Ug1wIJf>>Zk^GyjUyG{<b<oZeWG78e~{46m!^{`<Es) ze-Ee}Aa9wnF4g8lBVjcGex6mQ#|=7i8fl0Mc2MhhP7-lff?-=jpR-XzF$P=jAIwdd zAPnr<+$t3%55P20ja%Tu6m|un&F!2nLxz%P*eaV%{O4A8#9}OhXuR=8DNu^3xyKb) zfU(j}w~9LIDoX;^uGJ}5QG^-fqmy9P1}i9|IEc)UtIouaIQBm(Zqb=B!gG6+!$ZlJ zaRjUcvRpY4fH;`RP~BP3*<dDIM%cT%*4#RBI+7*o#7ZVJ7OZea+yu75q$J!k0+k_G zyj0`a!k)1eb~K4(p&*P{44E<xnJhWYYxH04M3v?8Jr&>MnhK`AZ9grJV*mgMH~`1K zt^{2Sqgwy}Q5{{J=A1;7@@x7Zbx}X3QfwAGg@gT@-DZy!kwIqIV%TM{C?6>_<WSwJ zS3T_z7^TLo#(LxXj^oak%p&swvr=88E?2)nsZ6lgSn`!w%3S4ttxi=1)g3v69Fgi0 zPutdle$M;E`<^>?n|7{A?*7~(+oHGK9=DvWWjD2tslCfF$}8G_4MW7lVVW@SF<*B0 z>}c8Xr}}aAboDZ<Gj>+PO=Ch6Xf|lpYl<|-wUo77S^}*}twn9P_EGJ0?H=vdI6Q7Q z?hq~+mybJ->%cwG(a|y2q3MWqZt8s3RnhIzZPwk;^U}Mcuce=6U}X?t@L^}vPLW}x zA<J+XZ;7Yiv+%w6NBHOXPxv2%MnV_iDnUwEGCFAVk(f+;Yhqw>-{e=5KTJNGB1|2o zMAK_#iDunqKS*d&Dao8<OJbAiNtZ}hNYmyp^G)V1=Aq`x=I_k^-G$uc+(q0~WnpVk zW>Ia?YN>5mYc*yaW6ihjw!UKh$mWoZr%i-SvQ4Yah|S+*3^|B=jGRU;BA+EUl6%P4 z_8i$WA7WXo?BTpWZyAubNShl!Z9LleL*scI2w(sWJ*2^;9sp-4Vvp?a1$e;yQcWhs z_PT(65i|%42>PZXkSHsB`_w`ZABqrR1DZ>ZE2NFB81N8xyG96FiIi$n6Ff9zyv^Yu z9R{Ntk#8|E)d*bLY`bO?O@dXwWMS_ikp4M3p*@S$&h2N<X5O7t?mG&}QSe6fS*Woq zlf0(=VQs|X*0}^X+g{XT%rABRGkaO^$P#|5+g*W3z`UhN#%*Z_qydL%uNl-?9jR@o z+s67NV49E7eHlLbGnd#&q0sGC?2XJZ6pR#<LAf^*AI+f+=ZBMkA}9*kI}uCVu~}e& z_6+9M;sS~+zg;`SU)Pm*9KAapj^mPZDv%T$PQI3I30s4M>nzd+Y}G3%qe+H@WFQ6E zg4AF(!f4LzRqYhV>spGk)x>Zv*&f}iU@C%mgF<6(0Fy{m&;Xzc4TS}fMA;JGWy`o; z!ejg;88Nb;Fkkv`O<7SkfH9U9FkfVf%4@#?T9m^7+jPPOv|@r%ybnx!ww#NTU{#M1 ziRF+rV%xG=g{}B98(_DF!WJE-R8;cFM3HQ32t{FB3X#0cS8&bg6;cgjs7GV(RO8`4 zipXmE^F4nGfTR|_<5MS->GP0D8iA;a%v<r$`Di1)I@ex~0CRQx%Y9z6+D{>Op_x&g zJ0=vc2-k0Rp7{e!;U^-wNFizp`D~kPPxk_m2FVc0gekfPC<#iLCryUvbR|23`)<MZ zBenFGIlcO7^~G%yWJl5g&jUr3(KZp0Fp+jZWuOC--!MWyLo9FbZBDUId3<ni;LI&U zgNZ~qJRMp6lrFmCTGv;#|L*pa5tWff(88c3sRnM_lMRqB9VAU;()(R3)@z_ih6lbZ zG1D?AV;AEC8^gmWfi+q_vV~WG@Jsv={1or1*^v+e@0|sjvbtJ?7~d7DfJzH0o~02M zdPB9T39^N)#<42LSkSHupaEwfLnl<~U3Sp8!(YV@MNn2UNbfS$RZf^^Q>!oh7puSF zz|FT$_GY*fC2V!6zBJ1PL0cM>DRg~%#z@3J4BI;t4u#NwWNSIf1beBy&~fsrLQ0tp zfh(DO(U#PcdWv>Eb<OjXFlo)+Y;UXK<Vy=^TgvbAlkYqOSrH0XBqcxrrXN#?yw98w zr|c1rG&EJ0mLyFF6hh%Dp9=40NvIXrBQp^RvVb)@aPfffEJcr(^nQszPXsQZ?bD7# z!jI}g^H!i+3n7KsCoBI7;2Z+Vo0U?sbDYcmOt!6F351SrHhekeDX2i@gy}<wL!mQ% zX*iTe%?b_m{NY6C1rtPC5C;EDG{oUWQGL9WlAL}P3!$YRo}d=^6MY5n9P~mIGGT6| z5x)wp7^fiRL#~|jQQGO!XC^YSm^PKh(Imh{`qA>4rZf@KesmA<n=*||(){6kdabD( zFp6z0_@mf~D9U7t-N|P;B(=!ZpnvuLzS88Gb!2w8j{Qfb3$&+TyGdD=aW&J1fA0p= z=g)xt!i<f~Z&!exXY`Yr`eeeQ0fBpsnz!(2gxXIFy?B2BFmRZ#WA-Z9t(<Vudx5=I zt?`nZ)c1i|eQJOvDLDl=cCKrL^%-9DV|e6T9HM*Z5psg2lhag<Oypbu5^DS2iEK!s zPP6TIh2Mn@lT0NyO|q+sYL>(7TsKDIE&ovf&m(?WwWm>A!{&V=Iv4<tH=)(k)r~p1 zb~FYBQDJNYTgFSTS?mKv38iq(sq%gW3NM|5Cq$k~sB@phkxlYu@~~k+4y8b^J{xyL zC$5c%Sn|k?DXWEMr;eX!C~$Rf!Gw*Hg=>?bH;cP-Bwayd;PBL2uF@FHrIxPvkEVtK zZ&k0xovKP<>@!0E2fjduD+*Y79p5@;o0j*$*zBM(crEjy$LPzYCS4l!cX>_;ZuD0T z)Df04stgyia*At9`oJK^K2(5y7F0@VeR_OjfxX#bZXFgd?oZV#KRd%Yc27piD&NcR ziW1dTurvVRo|R!xrV5dil$F%T|8^KuWq_9+2e`GYsRc+6>nwYZ`me<VkVO))>}Gnx zS**=|_+mm<f@uV<$x$qjZs?>u$cXa`*aK}r;n60J9~vz1&!-G_s30XVok>B{s7#V- z9F0h&oc=)xbZbqw;c0a|@xX;KbZCsY#_jgwABH~7zY`!H-}jr)(_D$*ad-GidOvsS z{8xIlx0^a`_W}7rNV(QO-M=+;I?{3D5v4jF1cUmj$>@WhLsa|An`5f7sv+4p7Bcip ze*R^3b^6@kEvFMb8v%2IOLSMeUQTATKu>2V`n+KoEj?%du6C;*hj2w~;41##$Nw6F zMq7WD&2CNCB2$GfzVc6xD6OdG=htS6)j?EZiPr61Bz+;zra!s;-W*acK=P;Ykv3gH z#PwBrFl=b@M!9l$T-2n(>ffe$ib|Zvz72NTwX^SVE;l&bhrO<W(K?v9x}G;&reS3O zBx-eK<sgCYATDA4qagfaDk!ZQgHMG;-M}Z9H1{XB70^-n_qXv}09St9Qz4(2$eSqN z5CFta4cj2086LJwWyN;VAkfu;q?s-)$dN?PC{k)5Z;pRGl>AeQX6*eEF<)A1L&KTt z9Q56^W$MRzLy?_x@L2CXdw)M5ajv6me0Jfjjb!`K1sTp1teuI^0_yTr5DBp;Pej~+ zAmz_*JQQoAuMk782f*TlvQ79K1t)d6yhG}6UnDg-2BZO{q4tbW*OO~b*oQlJdAr9N zkDGyETh~FBg#mRM+@G{3#<<xkwKJwCV|m|pgD&r#bz`I3FI;WG?a_v%o4Rt>=H5<p zd)|HJ+ua$x)Q<I`=(_G?`QF}f0W;5!eS9IB_#rhDKNt8JrZY(SK39=8G+q@y6-tJ~ zQYrmUT^_5fBaiF8KlisF6!8;fo8F0NfTpj6x&!W1sNelzHi|IEsWl!W8_rs;fy`lU ztB+?<1WV*FQJ@oPTER^A^h!0HGM0|LelWXg-AZ+B)5X}{vqQh9aw?LEX9kX(1A!2= z8D{0`d}Xg{v-QYwR5rNT?(UP)`uKbkJ!h;ck?DGY7P~m&{s8uI2syh_Gm@bYy2Zl} z3YJTqcl<SPTt}vz25kZk<xWVEDV3{?Q<vo%K@}*dVt5$yo3VwG@E$`4?X^8M5QRZB zoYabMkDXG9Z{e8a{byH3ie2%i4|l7{ORX)=m93I(h@P>pJ2tzk*e4#ncwDZUlK!Hm z4;ijPbWFA_owW*Cy;6vYS5s(L2pQI!zP1!BDkP>HpZ`g;vlU%j27|5qR9-7%0-HlR z9QEXEC5WoN>eg6yrm<^Gsr8*gP@6hIfGv1xu5h?XR(jLy4z;(3K#lM7lTbDu26DW& zFqWMUu;)Bkmefak69G@78bLl0`7<kV#@h675s$M@_-8M2=nvZRUw*XB@B{>T8w(4K zB+Tr=B-8}{Tn}l(m*ukq3pffZ0&Y56&XI&bl%PY&R61IT51O7h{e8+Ob2{-zs2jfF zQ6m10g4PJ{AAseeF3X`jA5@jUI-nvs;E=SQDG!{17Js>u`n<OT>R88hceO~rT=4Ma zl&I@=vaXW$bk#*vQisLKx+0%m0l=S%n)e#ek!myESm%l@^BM)|G%9ReKoCJ#m0jxl z11|5+C}-cJb{SD=y7It3IjxoHr>9NlwYoIA!78c&r_UAkacEmNY!BXq$IJ@PdXSv^ zT1hNL|Ivo$5A?2H&n`M)V~{|PFThR8;u~x>V;md@=Bs4qM@_|IwRn{wt{*;py>q-; z)ZWHZQ#;73Ooh}IGanU|drE4ySk{!;vWBn)A>Ddh$f9bwwB{MtqUt(vbBJraupYe> z@NY6rGn&qgoeFS`w<goFwija$5wTdD^I-g<+rnkR<vq%u3e-sAA_yY#$&)!-oH#8b zPo^{WdW`aLjXlmj%9f-qf(&j87boPJE)cI0qJj-DltUX<Imm8gY`zyAS1|K21eyR0 zX0Z6TRPRgLbs^k0(Q;kd;71pciP3_ii+mVI98eNd+5GVu%mek^;ZgO2<RYXAD-8&^ zkg2vZge4+Q!C=~sXd4i~G*1gd!N)r}imO5|MwcXIJ7mD_Ch}W+d=JN!_Dv;RNkLQm z>jCKDr9na9@NRP0Etq@0798MUE7r*m(|U$}?}IoVFD?y_jEJWxX){gn;jxq;j_q*% zJDo(%&E|BIrVH0*!7Gfl+SqZ`bPwD;?T@B80mHQ!16xuq;AEWb9Lfb{mIP45qS^l9 zCYm&OcxU>aT6KWaCz4Z;jO3L7Xw>Q}-i$Cp#srysvY|fl@|4(wH!Ro%2KR{qgE5Oz zC5{M3!gxl6fwU(O-_F~!Jw6stj60~kC^I~E{D2Yo(=QP--$o(X`LHC%ryB39yp=NX zsht#XBi{8vab-W|eh9I1YeI8<|5~YZ5Sgd~5|*L^53;E304NHD5Qa+;|9>3Z22Y*8 z#N)W^eQ@17Ff2obfHdrOTNLuu)3O@_KiY-JpD~x6!w-%Q7`a$JM=mn2hWMMWipMWZ zQG=%QHt*~!cHQG+dD(S6zXaf6Z^1>!(X$Z>|9-TU_lg?D2_jS~TwjbS_!qOi)IkX? zMPMA%nN4B*3uHBITPdO-f;;v%uS7wCSssAGBU&bzE1M%S=A<7vBwrEk>lT+~m_UNP z;`AHTK&?cEtGNV?P!ttdJ*=5f1_>dFQilVS1ET)5FFz{k7v25!sa3Kci`&^W8Ck6# zw_OvnTPJDq1j51vC!)}VOM+?!Cp{6~D99h6!G9~SVii2K5-MEG#~Kh)0H$mvFCRsd zDPzBOwa^rF)ZZKmvaMgi20t^wDQL`7Dt|8U%A9fr<GbxxJbkuCPv?!GCUP+`LsP4c zi5`e_g#T^<5|8|th@%Acc}}!kHZ8tu1Rxg#8MAb)%Sh{Awu~e)m&Amg*nf^A)NUOH zzP}o)nrI{ys6omF<I@4^PGYKm#8R=9<6SWwlfy7+jpxZ>T@?lOh3z6rQICIedP{7} z;X7E15*ZZK;#j}yT~rZ5j&=|oP%`$1u$>MN?bKK$-gBW$?MkIu!EzK2^=<q1M9ae- zBmd~Cp0=>p-NE2IH!#8#KQv*k8BKok#{&qmtane~HX{%z3uG)07T6<QwD^CX^tA1x z$XRpNJ<vPh7|<>(Q2^x=$rkp3#&Y48nhn(5t=N%4hX7a?{8SGBTn^Dl34TI815SKB zjFz?Kb1^tqI?mJ#j<Z?Cm?>!Q*km2Aw}trkgDr#xDB~1Im26HA0WnJHZta0e%t6b9 zy8!^lOU_kf4@clQ`@=1zYsW@ma%=Bh=OIq%cG<!~S5Xqq>da7!K&2vif08!S_yx06 zozX`!H~3rpprAICoNjudZ2hLXkfxRbZIY-!x49qC#du=pM{*Lkg`2f7f4seDCXAQH zj{BTTA7S#Y-c1G_ngv#n67OKJ!*!B<kgg~Df}=s$2llJZS>}Y&3aX1mu6XNwP+FLj zLGkH0@Z9tWFq>0TIOw#gZSL6b_PH45_Qf}E#-a-7dLnsxJ)CR34>7Ix0j--}3@luZ z!2uRcG4^;gbH-Hx;U}2N#@n90XkxLiu4UWNdQl($>f}Rw`m1ooCmKhW%}3<5jU63j z_9Hlg)9Tc6*|zV(0G#d8BrkuxO2&wDNR*sfMus8NFp3v<o1`4O1kaLS#DUU2w>n(6 zSY9R(CMw8>Ey6@#k>mhC#<66`^kIO$k!mEk@2O}TsO#R)v|tpotOp(omyzvpMd+6? zz>+$vpZMihT*^Pd^)|*(4}nMZ*!NhJ*64ht0ya)WqtZZ#4FUsp-aAKuwg3eL$0%?{ zJ_P`vJX<`TQ(|%T#I-xmexP}>lkJypKm3G384oy7V~Bn=Eav+JmzL^UMI%10cI4f= z$xeGPY_Q>jX{4>-BQ7C~gYJ|t2Q+%WMk_e<+A0+C%7*k1NFYH{fFmhNVWhY#_!t5x zRgcp(=?s4N&Do`RUK{!(wkvc~GZ1YsK?a^;sIKzGm?u+HD+Qu=48?W?Vho2HtIDeo zSyaSeROgKo6^Nphm7-FK;1u>#{)p=JgwdwEfo%Pchkb2rH~&_JR&S1XbX3sk70sMj zS5ju^fliGH@))==JvTo;C!JeoQvl<PMpw3oXrLQt!g&ngB}kk=FS^+Y{a`9Mjc<^X zh)5&_M#}stTyeW@<!uQ|W$kJWPY@eI+i&UTfqolhtAP%aq3g;Zg+5I;2Ivt*_HT_^ z_c8j2KoAlF5<-dN@y*xgmp}Gx#OhH&U4A)7xk9aMe~onJ$ikK3j=a;+Sj>-!84liN zfp*%gtphn46;x3r5C_1q+=G-<sZ2Go9ek??N61a(Os*w^Qv-;na;dNQ!*j_7g@l;T zI!8yOdy(-MC1PK9fim!ouyigz8S{0bt-YfWxU>!&cV}o#@=cQb$|J-omHf7XE!!PL zT|2c$<#is>bj0jPjT0^oaLn}RvZZ-ItScZylo(eLCr$lz7oYbPWok5lJbgrJr1Vsl zYD0z{sA&zc?2fdsA>crF);{sHwMpv*3nu41_0rHO!~B@~Yk4<Ya=GFAW(RYtAS>ir zFgfUM-UdD#g2bQ(=;dK)mY(K$M3@*HWTH55fmVvY3WlibsDTJ+8lKLfs4Vi+mUTWI z0P8UJ@TGNN?Dp`aT1?KqGkn2g8Wth9`ouH#kQu@v)46rc9x#a;Qd9VQl6fh({2O-U z{qmW<X=D<YYs$AIM=y3I&F+WiLNVTyb?Hz53JOem$r1b1FpdD#<TyA=EefH6f~dDC zy|{d0lV%3~_Js731L11f8|OvO?goVCsB+i@l?u^^4BWF`KPVabtY~r6SUXzrld(E1 zuo|}@vS@h+Dv;?`5p|GSL1{+$R?9Jp$Wtn-h<?S{oeF)ub6S?!J^c8csCFB|vbwDD za13eY^K&bf(#dkFi!OX;D9Q4@=pM#nXCuc!UJ8n#I)XC$p<MOl;bO42pn3m$*;05d zR{W1gT`pSaIJj9#{b2aTe?t7IE5*U>W?%`xhk*k%vM%cGp6lFr)B{1b^_4JJjJv1p z={<Jr@|DcD{D`uZiuieBZEq!U(wM<B8I%cEglk1CJ5|C#wO5^#RQuTZb}%&K5+aJp zDWVC>)_~=AAy5XV;SsPomm-gXWy8)f-IZTbtPK3L`$|*I5H;<)E-l5%?0crSf@%gs z$i(H~;-`t<_`YunAv&NN%OdYGR%Qiq(~gJlpYG$-*_7bArSZ&Cxl(SWpFSOT^EYk| zV$($&-)XH9&0if2bdPBuO@kg6j)^vMLE4(RYJyMwOs;kQOU0jh6vbl2_+=6KLIujG zrxkH8A6)5S?f6N?<aP&9ZjCjie5^m#U3vFBK{#Uu==@^s2OL$d?dgg{x;Dh~@u9n~ zSZ437JZM}v#NDxbPCYiW^g_=>WKwEPrlbm$<*e$+thcq{d!Jiez=;LSK)QHKLB$~r zvLdKEEHI|9PhTlb<YfZ=DOVA!esUHqbH<w0N(i@P1RGCtxK2j9!PW4&pj(>{AN1#u z>&(nU{S5t031QpKrR9KuoVx#nwO1Wu#))U2fO0lIr;!hA*BmEJ)7)koPIxYv&9219 z$HP+|F{BVpD>sxap=&?w1`g?TV6d@<uHw$Lw;A#I)WF9k+rzl!&HHK2XgTOV{0=Ye znwdns8UO)>DtguS@Kb@|o12pdb!)SE(LdhU!xbBoxfI+VTXq|-(Z|}2fq=`hiG!MT zAU9o^QlpHsD!rt0Ddtq)$V1*)B@K`eIuGH&Zh@WL7!t{l816n?^%n#5055>UsC4$N zxo7KE-yj^%xw<j=Rn;Km^C)q>tr_e`NqYp#GZZp$iL(MB0}`TnO;a@N`0dz*E{eK! z`|iE_e(8sGRD*2zngNyxRMSWjmC5oHGMmkn2RzbStdt^&1S`}D$hO`t$MSv9MA3l9 zAihvLst<A%nswQ^)Fw!ofN~yIx{3y}P(wqwQaE$Y{H3a0<k7_vE}&f0E#+89fw}TS zB{QWUxag;V3(kt3_xW<rAgECrnzjDAg3Kltw|JB4|JzxaZDs>~Gy7SLj&Kut$>Ydh zZ)ZRisg^`0!6tlk6XPv)(>#Eey!jd&cDhl$Nr%I7+wrYs=&HGJ<q6BRg^_KYO}A%u z@_w7$s7c(5hhn&K3_sxK5lsY|O+q@`Uf#Eu;q%c|)>vg<(4=9QRPuY|oxHehD#wXr zIDs&6wV<lr6hDu+;&3#}j@(28`v!pka>Oc?K^mRfo0GFkljI)hN%r=}V@<3m@uN8} zfj>*iW@gcMhTEJT>Fhjr(&wE`(qPIL7?OS%tnO)^{dO~ZVKf$dArMXQR&s|I72GM^ zFkYLkD7lJBmCtYAl!}=~N0C`)!=VIh+I(*+btYTxBu-TMr$Nq#qY7XhXYfn3L<^g$ zL#VMgCh%rRrbDQ0=QFaS?1<Dn?F0_%OdVzvbbIT4NGuSTaQcJWa=Fa>x)e#K%!|kI zRx?uU+<a}$8Z)nw<klh3B8K(S<b+q<rGK<O*(9^Ucb;C52l_P^7ceF$3?W$IG&<@` zl;7xPb(SX|_!3YFp<QTao&g@rUTdN_L+KpX3k{6HN-#RoN~R{1@&bHZIq;uJbKt@6 z0JY}?1`E>lOuEcSpq2d*5lR;c<VUcOG&$aJs$oQO7I)YaaHo#38t&bz>81SQLn|QK zpATiOOqg9#lI7ugzuk~%P)Lrg7<8!jrMhQm`iCsUn%kg$<v;r-_)A~w=_v}nFfy7p z+OdukV)0jSm^j$1mX$xg9Jw+i4n2}-&ZktJL&2Dt$uCJ7-i;DB?w+(Bp2EGBKdM{G zFD|;7k+Pw%ipp3yn&>0|$fypue4_mnZ2BGQ8;-Ib>>)y6NYOV#a*nn;1>DVtoOy7* zRfi`QMS^Fv?iNNaAwV!<Qjs8BeuYASb`0?{&58JPG{dKu7_hxdmQ3d3BC*(HCdx`Z zwpDofuWr)>9_;qDK5UWPlnK2Tz7SeT7_&Z5aX(2k`8C1V<dWV$%;_cU0jKwUT`g~= zVB5S|V!1c<z2)zR*7g+d#K1W>ZTh{YAK18<Q8SV6J|5a<x>$Pr#7{@EnYWLCpym+K z)Y!tNytzFJ;)omQP}t6PR&TY1gy&5h9eLna1$I08a2SMuLdtkgbu7)YQ<cENGp&>s zbeI4!Ax`=3agn3E1zd*Ks<8sYp2R|r+z%E`{fFzh1OcVy)d7SEV<mqk9@mhOJ05dR z+y$oE?H_tWNdVACsC!a3h}{=%I$I;sqK{a_sC4zm*l$$S+U?Z3#t8;P77r4ymjTpA zo7ID{Zi>GH>f*##3!ich`0Jz9V;MH_TuM_a{e9y2h86l-*%P3Fr>qRIG~vz=vIrm~ zcFNGNVco$RQnA>5d+Uk*h#n0XC`_kg42_-wL?JP!m#LD7Lb-DKkr#9*EH}<wj<iN1 zdjpBY|E@4(gJF!&R=||}8BaF6r)lGMVUl5^)eE8(l)i15V!&IkC)XTH9gaF;8zk%_ zw|fb`2F3IJaMMp02tAPulBZ2%9z<M2BqZ(;O*>?+Gi&)u7J(n^@$Ma&Ygno3aNFMU zLh%a=R&{E6OYvy!M!|!~Z)%jE<aeY_Feu{-^VQOzjE&!CFpw>hI`RY#ijTLD&R5|h zTyC~)qY0_{U=U?ABeA3Hs$;qb5{Xy2HQCo|7SNV$+nz+|<2dw=<s!%f9@mjkDNj-b z5|aiB%_!o>vhFR5cK&(~!KK^P(g}kLaR)EiSb(LA6N#4b_xeJo#|B240@;?nAvY6w z2e=+we9UNHf@^`CgbFR4`lgr2E5XLDB~?dsj{SUVuLdSfeMFL%9aFdRWtd!P1U_#- z)BilxpN$^7i!585RgYXx--PElT5)xYeTvXb6Tx5y?yp$s=FML$E8xplLanhk^Z6=K zaLtVsRl!rswbyS?<vPePf}2(p%S1zz2zO_A_e?bNXDRZae_lGHc>%b&k?pi=e~CCT zW+gqXn&HR9Dzl%V&3_HzH%e9@rp?X%O!sdv%8ftge|E^rv{6584v<}eXZ_~(?P!{` zPwxj>*%QtW;b(xrPYAHxw-gGIh&qcA;cx<v3>Ks;$|i9BG>dSwlp^2(hO3EH@mGrZ zyv(GDTt+NvNJg89c968GfG7(<;lGe#Sv`#CSJ;|gGQ;LQ8c0<G$9Izv1(56KVIiw^ z`T1-4GvjL+e?WYd714511Zj{xBxcTUa4(d3BNP^l8=_7h%8GXI4QgD`Df?#btIy6* zX|e?6H36(X7_@Op!%}r%cZXLpdos)_qQKjn>IBsO*huJG!x~3GYY)d66>9S%OI7mv zhwlk8L1q2gi*R@YM*5kcxjHRcUyER<YsS8rllRsOQb+zoak%v3i&?AnqjfA6x-@H~ zUK~!RFMv^Q+Q`qL`JX)tsO;39p7S9zU_maM%ANEd8eerSkcAjxnH7N7h2Y%*pX@;5 zLEginf^%7|)P?MsRmJK5$L%=6qvW3gANevr@a9jZd1s20y>EV(lhXZXl1U8l`FAT- zy>)N45i_F~!r@=ANKDxO|2CLE8{>)NaX%a!^JjpgI@j>bXtKJ^vE=pbz;JV{3>os- z_+k%FeoGWQAmBdX_3LWs1@kn2$Ke!>1i7<0A00cpwuJBFdN1KAv0*BV?Y<13rHxZ* z=*NAJu1_tr=LfLu%QbDXsN&YD)1G)P3Ds_`HMlD_>-88v^DMH06d(5*4xULW8YnaL z9g{_^)$mdd?Db5Uqu7enX`t%%Z6fYT3%0<v-!KL@qOmoKr?N{40~TT#rI(iJmt_&N zIVg7WWPLHfIon#yz|iBS>7;=k2%SngdB9@g-wyZAW$DBGfFw<x`<wEv9Ec<INpd`G z+_+=1iwg9Y&908^z2(QLQP^JN-zkZDyq1V{LO%5#5&H+HHwXTY+<Nx%yjQnC0^|O6 zwCm&aoJZ9{RWy;Ej?rBPiL$&*W>OP|Fc~F#1a;zM9@ep$yoqX~jk&CpV<7|eZ($hR zMi*QNCwWX>L|HdkjuJ=0kHaZ5qr1zvgtDJEyU0{T{rjE+l41fmFRAv4O)F5|&406D zmoSw~mU9A^$X%yd0oaL5%`TY*txKRE|4B-X&ENa%j7dVVzzO@|97&9FRJ0(XQN}49 zF?5!8!d!tII0?hgP+Pj_e->}|(DY|-y?FBpgYV5t`HqX<Cs^OzMVB^uT`cgeR~z2o z6-n!0ad3LAh~j?9wZb(7ba%C7Qzr;*=X;wkV+b^!ti;~86N&mK4e=H+3oYB)29g%e za;eGNC=xGuJL8oO(DZ5{H&Ku6%)l>@N$*Kf9zwL^3%;x9yZ!=oxJfDvhetPMelmhd z`(*!0e134?*n5P<y1(8<Lb`U_wNl_{cXn5AI+jdYkAn^ux-MMStd|PS1gmY3b~9=h zy%Odw$TOis75Z`aq%Hyuo@!Vmc5?s(O^z?clZ_3+h3!zzoF{2BWjWepM6Jx=g$Y=9 z@Cyv$HMVl2^Q&xEnm6>W^9LCU7Z=hJ^ITq&eGYRpPZbllP0pBR+f&dr9wVKqv@z7I zGsopk8BWj5o(k_D9vvx{#N4&>SkgT6!Gx>KMvrJwk+~+rt<{Xr;5?UIx?(^BR~knb zNdz(HXL!c4O7a$c=l-KLgAbEV<NKkt9DO{(2EQ319;7(MpmS0=Y#_>&w9>!GZSQv@ zU!@KVoYkjqJ%(elK|+%4X<CF!<lA~p{6;@PoS{>6fe0dd`xh`l7Fs^~oQ}|Y8D6AW z&0&V~&{RTLY_6gDYuRVuHReV~T6z^nq@)TxldH#?stR2t^2OpvW^puxwHSE7+N273 zvaFyPWcUGqW7XwypO7UXEj$YFH4=yfF^@Ar()9Yrz+!o(anP#5>TwRn3ql;k5f*r% zqodFc;x7j|x!3Bpm_8oYLhUs(=ERMl>v<w?0d1YNPitYb606i9S=2@y_kkTt+1J@c zB-KvJH85@QRIz6j5`J?13R*>>sDly16ePZ^RM`*CybeCch1IzeCll!so+~|Z(*4q( z02-;VfwDybownOXotgJf)<Xh{VF*z<*nl}^F-emSRTOS8QTdIcZjAnr@}%p>VvAA7 zVxf*=v^sj9J#sdRoS=MKV?RHv^tbPgcEY1us}p&~B;_3=@+?$c(`Vsj5X#}b^JEr{ z`}vDoD0ltH;8IC2aGyzQp_Wam1&3m*v71*OY_c>H<3*<#oJkQ&a7J~bt=LBi8;3K5 zCJ&}b)X{x!CI072PbHG^t9`U31wGJ<QI8Hmjc!tpHaVFHx{wd3MGv(nym>^%?SpKB zMsHZxDT=I6;4e5RO3Gn`Yhzzc1vaxGrwz9ay8I!Stw#Wyv$pbFwkA(6cRdFNXD{#Y zn`NKw=@)coT4Of<b(tBwt4rr?lh=NWy-yg~(u2@RFIraC4(&3|b_PhlYvK{z%B6ql z`|kk$<bDHF5!Z@TLR7Unf^v$4B;$_^7IeRRBm<4#S!0S4bRBV)GN0K5SiwWONrIMm zb~|tuVi6@rW?-f?D>RGchnv-1zUKC66QC0UEBwicIcY1J1jMg7@DKLqUD1_jKB&^v zoEsiz=|=H2%<J7Icu&RgJ5uJrPfy#*0Oa)ukJU*KgzRyzq*2dv^zpP-E)67h^l+}F z5Ta3BF6_l($BnoY-U<^J+f%7cQ;Vc6&P#T`t6V^@lt+<X#6TS2Bj<wcxOb68+<9il zXy&&v+3p~ABeDyaRy*i#b&mt~%f`lW3GUje-j+EM&SD}>{C0g@u-GH7Kd2oHqg$fX z2R*D4Iv|9Vvxqh^-0}EgL^LJKtd2KCO6OG4f`(!<?tD5jNr|k4u9UnP_d17m7}OON znBL<adh9!ptdOnu8rrI2h>HIeZmmorp6Pq<zg}-l-%H#{4D;=UP8L)BXWf01bJoSW zbN!V=$w6I@)>AU^c?tNp2kLS?r8A3?e4BUO#z&5b<!PP&4av{9s6Dx(uXS;qR#JUM zkD&wHaG3nCG*DQgjvmA^iq<#_t9EQ^MfI1oSwk&r_E!3&+V{Rm?YV+f`|wu4#f8Zw zI^nD~Ha2ZE9NBezB;|^P@acwCH!$&%xwvmRG#Fl!Aqx;I;s?@>2t%N*z{6+mj2meO zKQp?lYPpg+&!+<_ccQw$yEZ+V#y{1|ldbrX5)SXOH@xv+gGCaFI}m;o@f`#L>8MzN zbt7ydwEN^0;xEg7#3UaoS6LY;S$>bb5I`Ost86c)-<n(jd<_Mdnmtzq0Fu4SUIn!w za~zm3vkBdWW{PKmWQ#??Ci<^o*<c#tF*d-HR#3|-LhD463ShCgfefSIe~L80Ce82k zHA0AvHS9y>XwQ~9cWv7V8tnz=2H3>PiDt~@$X-G!6l5wQktW%L!JEook3SlN(iHBS zxE}ESXuZ8Kej?ye!@^p9KQTdl)CHm0N=}zIUrWFao#y0d{>(!t8jn91gu)3NusK=6 z*uw(O(n_W7=45-Gw}Chpo$+8=zi6wVp5?-jCL+Ocg}KY&M#K(mHzIQn-#4pIl5^SP z#+7mQwV)yQA(BZi`-QpE5Ja*XnBz`~Q&jDwmUMbODmw@|EA`qCnZw9SG9=d7YI%5A zcwSD+D>7*35eLds870|5+6Z+U0fHwTBh7>CUOPQWJCikW(q6yJa^L<R`t>v2!MF75 zG50mSR-TZ*--UHpH?`#Bc(C6FT*S%EGm-s^U=Y`|&o5cDc*$%ruDQr_XU`JngT(_Q z^Kxt~#VgqgR@VFIMp{A-fD49~LxpB?H_UV^rYV_b4L1TD(P_qrA6n?;eB12k&1Kx} z7k~5<O|ljm5tsi62kC)`sg6IAlm1LS-=HpO_Bw0%K7B$wDl}6ScBdO5ZzEuCVxX7- zW3W#4GDb?sgS4!5NRIXhI;6s54-m`2!(@Ye6)|+9f&ZiNRa8B2$!A@a;YFMEi8Twy zO%U%!y!+M8yV>p4b+F{8c6V%yD7eR;{WWFf_~iiT{<BLgdv0`MUHvnAD*#_jYzMh_ zA2;hZW3Gnm#o^w5CvTSV;C~nuRRRV_igGUJ(KA!qt7y60w$#HHt@$gHR)H==MgHz( zwnEC2#}be1#qgx!aKZ5k=>~Eo6z*G@E73gv6ApPZNmimsdwnYe(b@y-!2tc(Ppp_4 zxW?Rt=BzvA^M5Lx7_)E;8Irp_09e8tG)Vg2zikZKVYB9UHiLzf*-rrfJSt@ADN~HA z2w<kM(*hVu=4cm!WK9+#3N;$2JtmxrzGjwfo6e&zah)u72cF6P=xRX^lB`K{C}w9H z<gRLbYj$Em)Pj+|1K<3!7PLMDpbBaVK5*HDQ#&^<!Kupdf^Ml}GXfW?HEnfSJ8{2u z#EJZ?xVdF0l$EfR7H<e`Y<`AmF-0w%T2z;o$Q|`2Cqwr3iRDE*Prkc~g*kSCa?DyU zL=|(XBC)HN@677<6b3<IkF>sk0Sd%DowNQJnW3&z`E+@(9rnVbR@9}>C$L3)O1P)v z5jsaiIANxLRW`ldw1Qi?V<vL4NXnpH0dkR)zECeih=Tm0pq1&o;8{`SO_U^a{n`bu zSXbJyW_{()!IT$wYr)vYeeN=uAZ(}VGKL=Lj;3~YI%NX_lr4MMUx%!%JX=R}Fmh|Y zH2>qgN34@pqf*CGi>~#|f4fYJl1l0tzeHK76W3DLfGoV`n{S!FB&+p?dD})w!%tTk z{`z@VA)g*y+*gyL7H*+2%r7CEipGa22vc`nMmE!Z<{}MqP*_Kyx|PlM^k?)l1py9g z^H{zRkWRBPI3)ILG*j42(fP|kh7$`E&yu&pwS~LtIOx6thnD=YJPbukxLo&eBI1#l z8H-dWS6a(BIHmv{TE@p)ys=R|U!R_xZo;`miz?JtMcUya!%9Fe5v0DvsuRJd{*I79 zvPgZ6QeOFdR8B~`gu#dMI3?S<BI&iV@C-`_DV_RuIkw8eOx~7LH>~`n{+uq#RvQMD z7tZ02W%Fc(;%OP54HivVn(HGF{A&@Vy67jEUim+(%zH*TRg6+A*%=}{texSk5;*-# z$H?CmnEts<KtL#+OA(-?t?!vL*i0QL(>U4PXh7E`W-{Nb)!p?$z@g*z^PPtJ@|NTt z+8R8wU9Xg!Amo-?6fv6C2IM=|kxp&n%ZjSQ^OlOoia-!0IIYN>VV4sw1=~_)$7(4* z7s#(f1I0RiB>)(tZLG*S3END95q}532O1QF8CB{tAj95h{uke;S*d95$`d`EE_7j8 z893`l$|lP6np@9o(w9qsTtCAG7KmG@o9}zwF?>0jJ^gusXiefR*TaLeT<)-ZoUy2) zx()hnihP4_Xd8=9Og(vxR*Uk$fi_oNbCbfu8mLl#bJGOiT68EVDyG*gWM=>H%~%Y) z<{U7J)%Fbu_2Ebi#sN~;)~m__8DuvftR&(cl!;b6Cz3&<I0Xz~mS&u68@eyOIp|n_ z`9%Lzo&}=?L!f7`5rM1;@M9}LW$CKhv>Sf=zlPl0-UFSkwf~RY8Ar#y^t<pM32xEn z7NeUtHM76#jSpF~#)f^o63$~QNALT!h{8Y>*SPk4?sp|3Uo-TbU6ROcWL;`E(2_;D zmqAobREX-g;8m0CWF0qh_Ql|Je(G}faz8dP<#PqM6DMwf6lAz6T1tqB<x=pCu9EOG zAkK$`izSNWffHsOh4?Wvn*gVAqOW(vy4$Ek&@CCG%o#QypkF3eFvb<Q%K;w=w)@Nx z)R4ty>9A?4FX*bqan$D^fC2G2&Rx68DM-$P{~l@UiN{xMHw{Mm{i=}YP4hM-*+`}E z#mY}^UGD_Ln_4_Jsi0aSc_joY;9$h&wBE*i<HSfpk(Cp<cTH9A)+|=?tLFCH7C`k< z#-fEdF}SpQB#fW&(c8**k`xMgGr$oXM-3b_vq(W~W;Np<>2x%fnaCvLt8qm|8kHb} z?OakH?pHNvfnKeskhtYP+E~Bkwd_Q^%~hQ^S(6~*#1RjVNat3jzu$SPT+%JB60M_e zjDXSWFLL#Y{Ug3}3^8H(Xfe?As<xe<hpu)5(F1h?-{J*xOF@@*A*+Tt3ZA2JAJW%v zTBxo2ZvWHsdjp;`?Zt5^@3YGuUm%y1)VINj74Q)3;3EBCF^nPHMp11_gHqnM!scz^ zec(wW(5HEnay~Io2%_^BK7H_Tdv-R<m&m2M!vSsQ_V5P`YM_=vA<8AO4Za!sfonrH zP?vuLJlr=GNN`2pg%}5CeJCTT`*T5;=up~|s~R1%EwugmmVD9^vp3qa3-r_yJ1qbe z9bN^j4V9Wb+GfcM3o1@_AcsT)O|;SN0xErm8q?qr=P-vEH@%1KM>oA#5s5sK$(^N< zaBKi<d6!dzri@xz(G2wESB}d*U}^_{+u6J8Q5<yVkj~}aAlwY1^2;9kO!MQSRR=c& zElZ!Xh<@NudfwIyi}E23l_{`##w0ckTz*KrT>4Ryvw3GiF(X5`J9Y($r`C<J=;rR7 z`P&m^0FT9ul2hcxRkn!!wZoA>EoWzu%l&2rsyUo*rv6(&^7}gLzlWyEaHIn>)nPs{ z7SAHZD5^f%7#AZLKn#->gWn`+{?`v&jaeR`^n7C_22$zoUEBT}&ia`=!rdDs!|u#6 zV--gs0xz5txcImW0G?{6G85{g_=qPkH;=db6mBvjjY*#^Bh2lip$fTMpiC%CU3ztq z#RaR{oJGXQJ}MSBjy`<n&Pu);zn9Ds?;9LW4-f9E>$T|~AaW448{!=y99J3vBRsMl zkQ}2ul7X?&cqxkFa4V$Poi?x;aIk>4%nk+M;=-83mN2Aal6#zbPp!lcMqJnx$b-#d zWQ-i%n#;0)rII$v1U^)6A^y$01Vru+9%F<188jOwp|zd-XmB{<<#GaY_fFG>#2FeT z@|rB+O>@X1_JeeiC$qUo=Qy02_=oJ3Ph>@&V{81BYOI?cc~5r9z#?UGMR4cI>0Ef~ z$N65fbFinxFr{s(RV7UEUmpYkgK`1y-97kYb8n<R&${%<LG#CY1Fp7iGqv{mS+hzw zoZ6=K$Cna%+BtgU(BUJyBk{Oz^rxS@<M$Gl-x$r@ar_4TL1Cp^H5V--gs-^GiLHgC zj?`V89;d(IJUX@<rbh;ECEs8b<1({|VwA{fJEe`kOvUcy-i1srMIw7nfYoG#&@uQ0 z1K@1^2Pf&0hBDApTf}M1p@ZW&j+r42!1xa>!d%Ya5^6HMU|Ft^h@;nQai9zyGgfIR z2*8Zc0Rr%z4wS9~hLxQNHr^J*H2d#2h@c_tN5Eh6Ayx%Ql+*yvu<pKwByjd7_+&fM z2Yso1PyHi{ou7_|YZ&#e)?d<}i%J)RXh5mQHU^0w-47D~L3RM?-4}tp;>)us8M#r0 zBq^zmtBf6dk4e%-SuWAMVvE|1#{{QR6@?N>`zD>w<E3WDp?1eR((&hJN8cu>CWSgw zviv#_*H>Ih8E2VASS#c>v4Ao1l7SE%g+)L;N1w&2pLQhU0De1({>pZLq2qn}l$>%h zee_N7!nD3naFk;ubCpw2u-K#oC1`NCHksN$1+(0aM$TLv983e2wSw4)R739Hab$0P z5TvTrwJWqg9Y7T#_VNIM>zAJfT$7lbnqTIczeuiFycXFCNH$4Rdt!ZlV>B8Lzp&N{ z80Oev{=hp{x;ro^h(RyJj54z+*0ci#O~5RPg|7xs3&nam7RQzE6eUjd_r;x&P&g6` znkwQ1GL{V(a8h&3CEg6-+xZY07+zedRK`~I4e$Sb4dRE>BdV5YV1M1QHQqAnNsl3> zd)hb4Nng`KPi~zU@umMx&h_ZC1>g0V)Vz7WLSS&wvSn{7Rx)U1vglB}#N6SXU3CK& z23J)DKn*R5G+LGWib_`4gBOkCgZIVS04NHe;_Vr*V~F{(teUYp@Zlopwt0MsBoyMk z`->}8%ErI7uBqDZkxPCold@;HhP%hv5!e#g3A4@W2#!fa^z~dCB<5PJDIZqA|GtHv z&Zhm)RWH}NifU7*D%ilWF^)pU0nu_1RJgi*nUHVIy3l6gNWJRfQNj9ye`i@}>`nFe zM6_r#9!rE{$#f8aG$f#NkiQhG#EGs)s6}$z=te|kKB%<5lZC*rY$RfZQps#kWxx^k zG&I*=3`&$8k>g=x_!<e<N>l_Q*K|~4MQX~+!@X#J8IrrOXQv8}9wRK@mTp9BYffHd zhEd#fFVu@o*tCaX#vxh8cR!E*&M^#X!PJMI5YvKOsy*P9xDE?)eQKab+eA`*&+gt9 zfuJsZb8olSWMx&~vm>?*L5%$eW4oJF2U1MV<u60giFBwtfP(g{NIPTor3$Pcop%lO zcc+5kSo@&Wgu_8=<u(Axs&*uZ5{=sfWA)K!sQkHGVaTarkeEbv;qvboNH6~=5I_mM zkiaz^OBSPOM$nysmI*asULL1MUQS-ov_gK`MF`#xGrMQz=clLB^BeMKR9>_ukN${v zH19)U{*i_6=7pys_usjb9LqmRv#41w44Z0CB5;Rbw$MPtCr+WDg8|Wlpv+VlfI^BL zqZ3xkG@r9NGLeKFEytEW$o=4Be6VccmL}nV1W0Ua-E0TF46Jezw~~Q?bad4V0FuUJ zp#?6|8i@7B2$4Dp=ly(k<jA{GSK%E(e*lA??CDQp=q2}tTVN31E<d?~KUn;2P`&EJ zu1|a4Uc9u7$%YhR_iBIZ9?~TLLNb@!MX#M*Tv{rVX?>}_uTGfwKk%1j;YhrwRQ<x4 zF|4e!;}*lr-k;^B{>o^?7dyMk&FjpgmXEb%^T7ZaiBgQ3oK8aVGD%Wxxni(A5>BL& zG1H925|LPMBDe=Y07VoiJ*5W(vK<At0W?!cmmLn`kFl6B?+hWl-6|yLW$ne=>z{Um zvWRxo18I{+B4B1EZJ8WOdyN71vqx@n@NkAYgEl}w(qx?1hzLv_R>8v%!eYu02sIvK zTwy0pjSomn9SoFpjPixdC!a8@$su4}LzEnI;#W;y(V}!;EiK*0AjOt-@Dv5JUzkY~ z$-1cFs}jCRHQ@>MFtAkcR~2ENO~$G2`8a6hvXbj*eL2!Hy-~j}P)DZ_fH60z->##2 zb&p(+^mJXV&rfNq^+)x`#C{d|FiljQmA|ZiqklW0!0KXUA7hwl;YiLh2!CTHveM*2 zZ-j;Z%dFvLlKQWsN(Y5dF^X%F`v4Ha$C%j&w}Kj2Hjt&<>W=mXq0x>&w!ItnQ1gm& zL1bWP0cHKcR3gD}*Ibm?=Or=Aa+YNb7`{IzpIPENXJ~z!_-O<8j<r@AiO27=(&ePo z@{1uhJc2?3c|MH|Pf`xcxv?L}yS5D>la@O?5gD^HqTy_2!6xbqEko&Na$H7ou^|S` zhCE)>3@Xsl6lAG~;W7spm~-Rv(X9&E5%s-zB`tUJGTGa_+$+g}ZCON2wK(?WW~Q}U zvP3ori9;gfYg$mRc=ow868L$$iCPWo10kg}p|Zsl$Xl(u#X;#s<d4`8=FWx{{-f*5 zMM*6<;KJ?c>Lqo{OTF801xNgf2gAkKj)ZVk_2PPC+3yFC<Cf%fuTa+?LItgy#Kta( zsr&PdJt6GmG%f~4f|P_>P8hSi#i?XW!0<$OQdF+)!Y#W&APb-+vL=!}?$N+Hb+HNf z-p6#|^rkS~y72(puQG5J&PV+#a!E&P(y~4;!Sz4c2}EB^pW!SD6AMqOJnoM)6Zdqd z)839|K3H;(F4sMqgA)iblsaY<k^p$A1n{+2C?4KD+wQ8B6YM(KuaK2cD1IqkhvFN- z{OdlSm`e3k77dOc#9_}wbv|nq>6~CZA)LysLPRx)1I^A;GKvCVLpVn&f~oMs`&{*P z@}{4_A#iCA7v}7t*5Yc}!5^`hn*h*pjvz%BQa)b>znPKZu_F7D@x)x3YBw%FGt-11 z_+>(}fr)8f&MFZBEJclM(=F<75CNjgo4oL{+_ueBAuu`k!096)flUA|mOHXf7A^s4 zVigjf<4tJy?^fNDW%?TVeMr$JrC*Rry;lxNzivuIKO%SQzRANl$=bj7d+i-Ecb-R7 zBXUV`+{`Gy6CytoLDy+0%}QDUahbg|nP?^UF_o4}@CO@hWM1c+fMwmZ2Huw{7`wxf zp#z2qLQKdPl-L6En1vJvO=8xm2XHh&07L%M+I{WR&3W>V>H`2^;h!!A;7^CY{FA%d z{n!=&OauTR{FZ}ZgmyE5T5;99Wv)yVVDMb#HV}Kq6n};RfVt{GbeUTSwWyh@j)qy{ z?v+B|viDU5@kP1SU#cGBR+R;e3qkW5&DW&`QKhhVOk!sh+6|p1*m%6`w3CU#dmHfM z?T1|`&`>exu{j2!R3#!81z5KoQJW{vp41|VoCd(9hW3dZ&=8M;u)ZY*Vob(k!~=Yg zUO-f(%VCKjil~MH-hm+As;{{~*94U22T@48G{_JwysIaXrb~bZs?=tx9d>J@M7SCN zbwnSJZ3C!{NHrl4A`duv2N`0dcBC4TDkOk+)<4lQ#F2L0fD4H|>7aofYIG9DNeVdH zSZaVkx7o0I@KQ~J%?Pa3M5eu4rGSTuS%w1mY}Qx6f4?;q4FWhm?31rdS<8TT3}nxb zt%b%B<2Z2csr@F1dB;WpG}G3-R2n==Nvi};^mq?u5tqoXEQYjxv`m43agHXz=+(Fv zY;BDyxMw6)c+wdqX6z?is5mJAUmXd|h%yAdr%jClwU(&@ySi+aa5gEhwfu|)7)Oe# z;P%cCDmeeIBFx#sdE+?o4B<@i4CCmTEQ%^uTk<A&&qD#<M1uW{(5(d`yyNT{{jrOV zfJGTpM;M<&MMEuC=wF9nFIxai!);_WO|bhR1Ft!X67!6<`G`qLNM+}XOJg2v;Z}~U zVO)M{m{OQCb-ON?xhu9Yus&OONNJ8tC{GP<yRL%#ilA^q*06;7o5I2utDkXNQkq*M z@2<MVLO7M~Feu%Sp_xRTde$w0c(OzF8}=j_t3%F5qDM(hOWoBS8Z>^|8Bu!J3H5{7 zvj#MDr~}T^jxz%euNkIxIW@fXuztr4*^=wE*>*Q|)&2I^;Wu?0Wz+40d3$cL8|m}T zIGa1tt<ITMH}R&))>!r0HgHG1P7Dh;=5EE$I~k{%l5WNNQKaAFfXM00f%~+HIOtU5 z;(jeW00)laP+N_F3~_Hnc<_Pj87GNZ9X0^Eg@LOEoYgN;22~Dj;z0!`eSxrjg*u5B zP>ZTD2pXu+NYiK8EoPyWIkYjC_V?;GSBIrRlNN0_I&{Cyv>gLG8NwqlLS)Q@>6hvA z=JRP;uw=!WjV}eHkA7VWHIL`({qy_xpVf0$%5Y?JYn$8I-Fu&OJNws!yQ0^{gV^DF zuU8*WNJ;q!rqUTj&E~Yc{#ixYLb3F|@Jnx&amA|Ir%vr|01+mXaiOT1E)CPN9oO?e zoLW7KlQheVug|%^>!$7cVVve=-S*?W?&tk}pog-Dmu5$DM+aZeL*#R!UivpqkQB|Z z950CP+5e9uE2^d&re!;>=P%Gz5(LY`mP;9cT2`b-JmjEgej#m@RC9zzpuw_`<k58W zx>QQid+rx&3mZw0o$S%ABbeNa#<l{DWak>iJ6FfLqcUr+s$QPVYL&5Ntfs)FWnL1! z+8vo(ixe$iL!$={#z?>=Wb{&k2HK<^J(^YB2x?VH%_be?BvGZNhm6$dQRieVxHlA+ zHyXtZ)ed8|C?}^&mDK`@HI+!NrjLiV<>n%K#Ul?6Wy(y>9#=|)Q4*xG?`TBnV{>qb zfpNn%580j5%p0UX{_y&rP)+^E(;jC&-xe#C&ulLkHfshY)nzqmVKHV)RHohx+%hsJ z;r12u$xMkn)6(S91YKI?jy^a0WkK{nUcEjW$wzPwxcnXEaa1X)nx-BZ$?`q(`8L#+ z>*_k6W}i4Wu6UN_lrUqxM)pawQi4=Nkt#jf^h*OU*lKz~CvsTTbB2@IW_L`^3kE1` fzKiYia~fEV&FDDyid3%*+a_mNXBqNxI{*LxrEuuk literal 0 HcmV?d00001 diff --git a/.next/static/media/fd4db3eb5472fc27-s.woff2 b/.next/static/media/fd4db3eb5472fc27-s.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..7f60b4264c7d4c58fc53587dc4c221608e7367be GIT binary patch literal 12768 zcmV<6F(1x%Pew8T0RR9105RYI5&!@I0DSBK05Nj_0RR9100000000000000000000 z0000QfixS33LGjwNLE2ogh>WqKT}jeRDn1EgeWg;5eN#)c*I=`gc1NS?q&ft0we>7 z76c##g<J=eZyN%37skfK>LI%Ud^OwuRW`E&HEf(2z<Rfr{r~?xL5(qdunrNdRkL7X zhLVX^hKgxdMN+8uMw#l;CR3?vY4*}}Z>@3*A6)PX1puHzF~bFS&G05JxZo1uMa1aD zB=)B#Z0mh1`&wqD-J08!jc_4Nw=zxH8K$H3c)`%+pa+NJzkzHwPTcqB%v0arF>!pm zU|;=4dOXMT!2j7sNHY8LJahYV9}jpi=5V6oL`B7giiU+c74^ZGqTxhciMFp;SSy$D zb$$196~J6%Xrxq2$(BwfMWrNNibZ}>GBUEoC&i>Wl?n|N4Hdcb&G{yOh}80>j2FHT zU)lkX(35+6e!`HP1r~15i_3gH$(DDov$RHNAP680dUK&H6qjE;JbbPF=egZIj~4*s z)(V5O8$cBnGOUQEmsH3lj#&YdBpG(^&*fSs|2f*-Lm2-Br-59jLSM4xz>#rPu0lQ$ z)o$;J0!%Fl3`;D~p9aqj7!Sa!epFw~E!1t8{7kJj8jb5bHa7Mqjl#rb!)?-DHWyyC zWJ0qC(;ndYi{nbp<Dnf|x+ZYol>MEggOnx{c4_kcZUYX4@Cff`tHlBf9P9z_|ELB> zQ#W=az@{TKW=a4DEy%aZOfK1y=kLu~rT_ikzo%Ok7zbxL!yZ~=gQO8UZ!;gn-5;b+ z(?Tm4>53L(n31*$=^PAe7|!t<p<&>hHw>&{J!`CX&lnS0-JW%k&wLbIkY2V~c<}{k ze18AeO8aM$EM@lqSXF2e22jafX7=Ua{}N7F0m@c2<(Vs!Jz=U@w~$DJhx(<{7xtx< z@py%Ccga$h{;5WGVNu=#kFV+Ur7Qi(X-)-vN}br*@O$5P=__FZ#4d4P;bnr3s)#|J zC=*-JdX3?IwqNb50)(O5YSDqvkAI;qgj5&~8EGP9GBuJ$8fhL1X}$`QK?li5M{05p zvdLD+d-g$mzJweXgnZ?D$PaoTS7ji1c?bqU0C*690T2Xe=MiiO0{9#dw=q0}6a-*^ zKDdwy2)9)$*Q|!22+b^A9f&Sn(X<*w2%rE#1pov9Bme-$AOL_M-UkgJ<`QY(K?&fF zLx|xv5tXnRcfj8^mP7H_v5{MK+)FW^kO8NBT#3ibSfgOqYlWpm6_(rfrq1H5&#>Ak z`dF4e!qSH<{iFq3EaqRp$PmEG5<(QSVI~?kKL|xi2q(eH43-UqBrL+b4+97&r6FJq z%s4WPJVs`aS!A{~pNu?3R+AR;Iyed6&4A&AX)*Z`4q+dZ35(R>62c;~S4)k~0<!oj z0uVqB-j4?WkbR`jj&hXXBQXF7011ZCbU<za21q)t0dO1;5FrR*1dRqGfcR$+$gezd zL$Ku}7lvUJR!{ZLmSVYBE!H{*;y4jWfJ85OI;lyW|NU@};;Jky&B$`1d%Oo!kpuvW z%O8*&+oeAQ1Rwy29*6KP(6vRt&Hp}sJI6NO?K~YiI(T;SbZXzty_d(!wU5)M-N$m6 zFNUj{VGsfc06;|{N)@$)xHuQ(i+X4;?%^-`lD6m<EdCgUV!T%tGZ8J`MB(CH6vSL; z$2xOj154>Kv_NkXi5mpiY*}oU5I2d$>#VnLv81<qp*ee@F%jh&vUzpE`aGf1*Sxz$ z|NfwoenW)>vz#@QyWsjmF{o@IIe;@~K4V^4*#N|^7(84wWXNza&|BZK*xuZ__3e!u zoXkLKHk!lht9}n%JS`kSf6&q~EE>g)*rN;^!-kwy+upzQ#TX~*`hos~TIV~Ow(41W zx1+9AbGR(S?DkFb^?Kc0Alc)Q3zz`IO4c?2UzOL&=OL7r5-=G6g{0XzUwsLkwP@ZV z2vH3yRv*0G5!^@03((yFfQ148Vmt^!Api()0Z0&6FU}-GfVEpT$p|7KCR0VLqz7?b zhX4Rt#)POhuMlys3R#5JL&d;w0pexzj&+e!n>Qpw{U-b7Em@q|mRo5sQh<v8w}5Yg zaXeXQ?Ix4p<M|jdQaP178HNo5cX$B@88pmeF-v%wfAJb`a)<z7e&zyylcV?m+|L|X zaKIIC;2}qgzIbmf$ASYtM>s{Ci`?Sw1OA2#{=NWVNQ8d?FqbowgVb-SHMIbw8X$FH zrBCnx3Aizd#H<nb9~V*SIN|}I-2g_C7^Tu9q(&RV=YWF_@%zl@4x6mX6jM#3G~Emf zeQ?%~Vt#VY&$_KJFa*&UEDrX|R@ZzaE#ME!{Bz1*ev!e~SGj%!`Ws-N9X{6K6FcqF zX}594dz9P+k9nLz-2Wx~>bwh*E_#s&k;oJ(&0TNfDb+_Aq3dq=Th>i`?B(^TeZ+<v zOJ<^5a_;)V5l7{9`O-|Z3oiQafrn0u_zw0d=#1|zQc_kyMW8?g{I17bX}lgi3b6nI z;3FUc98_8>1e`~AfRri*v;_49n`lJ}B8i&<iy5@WC5hG<{EIfI#06-RO1zA=uoRs| z+h~r6pdNbwBO8dNpv9MmyaK`A2ud$Uu)YQWzyv@b`_+tczDzuRv{Ad4Xl&|kj}N(U z>k~r+<yes*doN0Esnz}n^iZs+w#jfS41{h@E%Qwms*$Qv;7${@ij9Y_fJjAA1wB1I z+4$TwWpwK5Mg>F>RrS`&Mx|6hZ3U{NB3G4tT*PmSmC=cQ{WbZ-z9s{GD!KjI_$)YT zSQ!RNMWwya;HNKsKAKlg`Q@xAw=O9I`9&_W%MiR&y6d`AyBHpX|6=4+q~Z(x(hBX= zK@Cn~^ZZ4{JlQjD@8#zGN&9Q|dA<Gew8J!CVg2mD;rf~|*wd5rS5+KEJZbhdvfta_ z=;gg|+@IhQs~y_$)s>b8!{i`+d0Q@wmYpU{mW3~Z<J|?`(efEo4)G#u1pM}Ov_I~x zZ(WG-S^>UmFgNENm|m6O#@N5XMbD=A5fMAF8(vJmjlX5rHFi3sL`wGb87|<@oU+I^ zEOP?y;ucKMz~j&Ckt~;D?&z-%=JA_n21d;G1$(Tm^>yfvSw&IORP-yzW@X{V+gcUx zHY&y<_jl}HPBu(4*bR?(7>tzdT5|Zy#9d~L62``x>=2P$;)C9Tcs4oqOne{0uLBCV z<_jU)4xM=Mqb1;e+of{wOrk-B<JS5U3+~mweEYC0A9xMdADSv!NayOPWl+~><xjbW zji>}H-z=z$$J^0r!5ELD%PNZfZK@u6SXPCp)%vVUOO_b3y6&ah<w<%H&pcgXSpOU< zT>^haI8A_EZuw<;*ZIwf{PPC5fICL?*<(+kw%?iLqm;4zdXts2f_!ncN0<~o(4x<& z;7p@&W{q(vui4V2H8YnQALwOl^Gp1{j9~k5v1r=itv{OeQ#YAknLl>bqGeOweYU~% z^P%K4tQ+~P)&1OL-H_9&A>+o)&^*3w*t4&Bo_lo8(CX2%hmIYm*4Smn+C`r&nzpXG zebg&8CddN?-9IM-o}{NMle{~hcWGQ}zgy#mVRJA7w1(?jLG#D|KftW~08_8IE&aQi z>wigh{MfOruJv3M+3LL)`0Fv>)=^)4vE`8o2mj6{)4Naqd+Evb>z97>-RivoU`v2> zfM}#WD72nL<23<YUIz+`I9B!T!Dnw|53aO$Os7|7Z`|s1`SIr+-+!`#y=~hH&iA`^ zNNkrG#Ms|^0q@T~{<oGZdq-YqZM?~u`|hbzTitY<zA)1C(#7HXk_n-G^2Mtg=urIA zC1bxo`R?r|e{6-|lhCA3dhwYlgsQFAaQrNtz%uQyNNhY*A9Hy~{52X9{pk5WuI+hd z)OTMyzkhM_3Hht_BUkb4WU}OcWFPJHZ=OHe(Y)r><6B=~?%VS$b-2Cx<z277d`xqy zY%cd7{2gCSj$EgIeEqhs;xE8BhB#*KYW%3?$)-7tKiLm@zj$MaJ<nV9?4jK)m(*{4 zE?nJldc*Yb8(v-8qqWV99ZFQMX_Q*0Z{GSHwd&9z)(bmMm2b=opFjS__8li$R~b9k z?(G6mwa1eI7WDopnAmh-^FhxauUjFE#m@i>0xy2Q+w5QQ+;J#nLFQ<qdD_gOvr4a| z5-ZBJn~r_<8=T$)Og*u)PU!WwU;odZ<Wq{TMX?Xm1G_?=?)9$A6Sr^wpZ1YYpZ?&( z6>HiKY+Tgq5c%tb{+%102X@uo1FH?^KxrFfo_XKk->lPH!XK?J*@ONqXV<dF{X0K; zk@kUXNZUtGjQF_cUhBcT6US;`z#iZkJ56ZhmGyo0jegJWNneTvqra{hchU3lf!x>D z2K@Pjb&D-N-m3k1|1oTR%6)y{<BOg(<9?n0;<)rt+Gg6kLH97Qe&iJs0!;)Wk3`_{ z2qf>j^h4;xZ$Ioz);{&h3ok5v1x7?Dvwq5^mtR>hcGaRK6P_NpO5O0l&w-;4KWA-z zQy!Bkmk%v_oa4MQX!#Km%r+ine|Yeub;{z(`4j3YCrzm}%sgD?Ie64sv!t?S!o12U zQ|20g^JbO0cFBU;c}vvFd5de0`HSt-W-c()*7}3v)vH}RW9`UiU(0s19$C@2^_tPz zrv=ofhU9XMPi0h_eB7zEe#Xi<g7IfBY>}Z^8s04=>s~hJ8=jr??q+!&*QxB^K3G!O zCKr5gTq4rcuwnP&&6iK(ly{fuUw{?tI%CXKGwPN0_0@}}&Hrq9DaXCA#kV<<?RYS` zaA@-0%L{53D-Ze1M8=`!sCh`VF4??)a^b;b7}6%2c61c{!S>_AoAc$TLc(3m9mPL+ zvt8zVgL>eq2~RKCTX(rH?~6w>J#m!<S9axZhY_2GvuwCsMC*<37wL@)MeS@6*PDE{ zH)sOZzWf~vF%qhUDP8@D8_B{$H<gb<dD+_X14>}+mi6Oup|L2$k_`$IzXSK=Td{rs zu{)raon3I-<0V`&++-T~^*fGbT5+Mh7O5`8h=2>2*@);0=8C{~A||^=<dg?MbNzk- zO!Ye%aC4!+Dct#wP7X0D#)<*NkO4<8F@2pp2aAjk-P1G_w(t_Xe9*;DP^{-EC|2?n z6gKh}yu9)77X)t{(r+{Z5?zzR;fk~#ZDN{D%6{cR1ue4_LBS|RFfmDRIJp@lc(fz1 zpOgiag@UT+a_aLaDe%UVB5<NwdwuCjFT?rvqxl4DuTCMy&ae~!@~->E1V^;{4i-SB zyMQIJpdT@CovU0r^E6_LCDVm5OdQH;qeFq?P}U`LR4;W%k%ks{QRHzHYbznwD!QCf zLW&vwEW!{z&01J|^?CyE>NOAx#lYVNw?NH1!#(i4pF>sH=m8Y|i3n5=Zg|9U?qE*l z;NbELrH)9kK%|Y0o27j?NyTl#3vj5I0cg4k#R5mu<Ud$va<G(&hxCfCfhB1_k&VDW zOuIu&5@F!k(>EFiuQcUX67v(&N<5x|6_k7huPTka1<)K97n3!!YB|p*zqYrC*S_|( zuVrog+M2zK8o=BA5NWh01u46iM}dJFl!?MJQdnjRWoV&HEi7ZjU6_9ly<)P3%Ps3{ zqeJ$c?JtmsVuM*Vc&9iV!Qd3dIn}(;EpYA(_rNflgB<vKA3&F|1YvNKLzdhSA~%G{ z4Ni13l9D@QR4S)4D6)r0p__qAy46tW#@g_@sVo%A#X=b=l$V9FQz%CRWolvh#w=@- zK7|muqmZq2)6?27H}?hH&p3+vxfsR$Tx`evj1{<_i+SA7*o6BT)3~3pA?%;vYEi)b zru997VvHb{H8<d9{#eSadn}v)MCruZo{esSXJ@zv4OtG6x|vQ8p%b8>6TqhvPO6yg z<pH_Nt?v=QJ;-Iv4Y=u}{5i`o%0vO9j0zZK6u~GHCX6y6#V8YQj51-yC=-qlokWV2 z4Ah`Z6qb>~GE*o+3uS6y87nMv3mX9r@2nzn57@VmMFrLQwPR**w!lg5+p_BX0Flud ziS?ip;K68vD2UEbF|;xXk)i^@pO-DiUthux`TMI_{Cj@^y#L_3dV&ANzrYFr09wG7 zQY9B7ofMXL0~W-IgB*>^OSpg%<=oY|0YRwhb3=k|z#0<7y+a%gPN?sqNdv7=Hppq9 zC=cyJRK^rUE>UnXXBQeNH$<YSSAemB5*|ejayuy?7lsBoS&oJZ<3<XQ;Z{E72GiU? zS@b*@6Dolq0l6?F5F}X0lf>X6hZxO3(;%~hqC!<WNPu;NWGhGGT+#<OFa%t{9XM@5 z;d2}-jLu)+EWMMS5`jsbU)uXt&A3Q)PDfd4#m>qUt%Budl5#^U06T0>caZX;%B_pE zln#;<AW9&vQF^hF#i;$5E}TlB{Fv(o1E6$O92pl=B2YSuv=4DopePkOWgHDw?Wa7Z zgZ~Y_^O|56b*{F-Nl}yv`%vQ(3=GrYWt!c^J0Q65rEH=6xCxvflOpxdpjJ>ZFmTiX zB9PpJEJ4C;qe(+uxVPRQ{rPT4%tK8(D~OxG2}UTWVP(J|f@6Rs;M}Yvm|hC?8BcMK zLd9;#CmbfkS3_%t0Z}}KV>m$^1kU*=H}?8_DZpkmgwSv;8K(gow#lhv`$1C>nTMM$ z$`8g_>3dfcH-Qrzq}&t|V51FE(#uJK`vo`|C_jcd!6=Zs|Dj=}z<fn;ia{16+|)E# zm&^e%wYIt;COOajaS0~4C2_08w7;F}lR^N1fB+yWzhDAm%tzAyzcu*LC4a-H44Kdx zbOqfZm_&bK6fu#QMHq+|i59|1d`ui7LPU(n68Nab$X9eJq$mS1<gx6K19D6v!X%Rg zjspM<85XpFfN>Ao;Ki4SfFZ@Kp_dY>YpScZ73oLSTIpfUE(236vX8xQCk<L+o2NgV zcH0|&<6rt|C!YGU$~xD79a<+=G=g|1J_=tPk7&p!<II-NWYftes|oXK4mr5tn-U`q ztdge1>)guS{DP-RnR4E-@0;4@&UbeI+G|DKiY%jw%GT@JTSw~KqLtO&*;kWob=AdY z+wFV3z4!Hrj<)W)?|GbgT7xE-d$Vo!&9ON%a*8<)3V9*Fqx1M&BzmGas-YRWYMEB) zzj{;eX}1D8saU;MZ`bzPU%`sj#rmrrxa9CT7>C*hukst-;@v*(@0@hTIOy1Bby~79 zALi2>&A0hE50><_FINlCb+2n*_wLD;@7}TFQ+oZ)f9Gr~>PH4m8uae1ZrByuDyCK} zYSuM7a_?CRcm_j84FJKpxNLC>=nog4a+eDtR<8+Y=RlAaTZ7z41k%snaR6Fek^oe= zMkGkDKdHhPtR&F5wro&A4swj{ZnN1=BOS{7W}{AI01~{sS|BPKEkGl^b%P4ehcAj! z;Rul<IjkPjn%pMIo6u<93B2EZg}<vXK=V^<R%eWJ8%Czlb6sbEsWPGPV%H`$uBjKB zHg#PT-or7@anw0T)>&3o`2($-4Nm(cb^bmPpQI+rXTc{Tu7(g#1+I4S<evlr7YYM4 z`fLLW7Xr7Fb}4}aoUL8tWZP;%vi-ts9^i^4MInI@p~AS0Kw?D<Nyv{2V2SkB&Uyez zwI-PVFx3jZM<jhdp&Fk~>H4+TgTmLc<ChvMdl(D8zbF<(l~a^v>eTV&-BhK9I^;h~ z%UfcxL^_@D`S$PqEF6d&^7~WZ>{Z~~xCKak|7!*`m8GfHC<a*o{Ou~-695_?rp5>^ z&O@?K?9`Qfq4?lI@y4I2p;A7<;S%|~Ow!^0&$<YaureAvs`SXY#6NfMaz;$TKeGJ( zowMIp$2+%d*}8|6kA0k*>@!hG?%u8~Em<vkQH~ud8lg}mld05ie-(K=Mph&*<w`Qm zvhQrZiCPCg{AVEK@ZZew`8-#7g?O!p6?$L11XU|Jxk8%AI@<1Jlaq956-W-+?%+#h zk8i}%P^K`KAwz_7<w9GR%!w?u0e6yTrHV9jOMS0_hq=dta0_`01x-6+7)hzgDH1tM z&D>w+Q9ffrjkVTdyz6wdy>@TthlI0i*7*DWWNEuxFW>QY!a{=w`E@ilEy&rTh7hw* zG-xa|79q2fhTd8w*wi^jv>Q4bS2Ac-9&W)U-hc$0i!E4CsFlMBuIC=m-9oAZU$1I& z$jKEhK_OH??Rgqoa9djHr<@ew%Aj}yy(@^ihXSTb{89UK&=O;_%ZFn9vO)wi-GUBC z$p+}vP629JJP7UB#8eVcw(kG|e+OJ9pUIW8@LTCBIBOu(*P9F1TZpJ*uHcjov%SeQ z#9l1ZQm8-0TyMq%sRtuzaeW6m>IBm(i+CD)b7vVBP?+t__sYEF%$I|V&KEI25E+q~ zwr~rIK^W;#BW>iAzO(|8SCx8cgbKwVjOt`_f>~t|ug>0}3~Htn59UkOK@2GoP(y;U zbS1lDVenax=axDX(ArN&t8qyxL++nr+Cow&NgJ?$N)tRuy|b-k!nNRssZ^f7)Pod1 zy>ui^MpC1}tg&ht1-B`&G=yjMQkg1%sZ<)4JKKsBYB6lo6D!iCP8Luzm(gz_1duzR z!-7bF2sjs=CkAL-F0B?4^-TtW2!e)CICVCa;3N||48&8V!LnEvrY6cpIRjVgBCJe` zh3ILC++oo-yrv~|pAk`)SW72E8Yl<t1wwyGatktfM38vO=Rr3a&9@NgEDJPV-WObk zNTg6Vk(8s$Hp}1$ZGlB#DqS52M0zrJ$|Qc8{JWW+NWf&8KREN%Mm09e-rAeTGlTUj zAyF-;gkvMQJh*fBQ1;Iq5Uo;!7sn|t4TY<BJ{Rn&_j>IraB|KXY5CCG-F_}_50%r6 zYH;>6=feeZqXuFjR)rADMme}jtLR{~TF{M~Hu82B%FAqwvT`_hB0d9&Hq-qeEY!gN z6bd6hhJ|*)eVHiSyQ<g#Ji+YCR>6b2Eb0WxCzin2JBx;(3v<0W9~9pt2x)M1K#o_K zspP8CNYJrs1SYJMJVFpjLA_#{x~pKoHL@L$gz0!*uUc(pFO5UDSS&Qghu!Ipj_ehV z!n<;=<y<cCS9_m+W95?<HVBHA_ms&OR)dYFY;%-!I(0LjQG>JSJg9$EArM60(qO>p zB3P%lV=4%pcn3<WopJBiz@}<!9P;VZ>f+!;;N9v6<Lh<9n75{}rwZDjLyp2Is4NFz zi*+9IO9n)&UU#`b08>_(HDWO<4VJpAUHW8H1uk≪lXFg+wj~bO;|%T3S-LO6_aU zfnb7^0KJfT%~C#uj_BlQl<iRD_oi^k@n~qZ#9>nITWBiG^+{T6kn=o*n%2UPs?^=2 zFgt`aHp7e%;UEi4_bPjpAqhFH$``_2HQn7fI6W)8W@X`~UzRRLhfo-vM9=3z#UBij z#DheP^bd!9K`(rgzAiD8jl7=jJ)p+TWtZ?>hFG;OD&dp=+#@N?-zE7apz0era@ly6 zoVs2O?cK=rQ^~U%Y20|^N{c_g&Ha8ZN*BJCEIGz&3xSb!cNv+8ZYQf-HVZ6zf>*SJ z9+nRDRu)Mz+w%+9RxuP7lT<@QL~9;HUE8SMZY^TtHEN6sT1Ac|kiSblh*_57tBHOz z^w1D%>NZO+(x5Q6K3EI>4q`8Yn)Rq)>t_QTWS-%>G&Wig`?UnkjiDT%bXgLB1-a&h zRC+X}7cCuq>OtK1UON7j-|OA0#uoG8@9I?-3L?#7!;+b$>F;;8sj-KPQ{VogyBlKF zQjKBL1(#r|_wV~Q^4|5!sjmtIr{E%Fk3(?mP7e5YHSFcJmm@D=C-)X1EQx%eU{Hls zOV940cl!PhzLb7m3mdrM4oV^SkupW4-cn=GHroD_8fxHEmxC-i!|7tyYC&(cR6}oZ z#^05f6w>}|8_Di3RlHOU-<eLos*w<p@I}%Tf;Bh^fs!$-@n}J#<|PG*gso$oPauZ$ zb4f)&Ivu;iaQ4o4Ca5DEmlC#T31d4nvKJ1(LG}W$XXwzeXex)I;O4K9BRgCU$D3+g z9@+FBEp<4O$%15Z)s$h^Bl~R{%uuIB717@d1XTDale{fndmd_wXJ&h<pf|7FkQtUe zvEfKh<ahqve4fbDgJR5>p+q=8K#{l4vf0iD-p@)$JVaC9GzYfBmk`meEE2Hmys=U# zIMHd_7dO|>1}9vMfv8I5!vp9Pw6p}aLLwQz)sGSn67U861p;X4rzf{8&97n)w2}R_ zk*5nfpt(s$F1o~U?tn~2K$qZ}i-4k$!t!j}n+sDqQ2K%tY*EeGCS9*qfI{ooD>-Iu z+?zDMlmw1kRS|*~aaQaj!*KSlcm)&G5pFy-sOFDnqrR*%bM>U)NCOEe=BA?E`(plh zHfT%7Ik9bFP@_SL%q^WPBS?xbfn+Mzs~tHdgOS-_#%x@U1GrGSmC@;%`j$$YYL;_h zwVhDr<l(VRlZDrmmm#-QI%1gEFX+(0!U-$Z)bpvZQ3Xzxrhbx0nBFnt`<Ud%S?Q2R zpL&Cajbme&64b4nH5`7g7H08&zVHy+bfHa!PosPXeGPmn;cM>ZsAaVbez>Iuqh9ww z@VIpzRzXZG)pL-2VE%3@s^|5$>*=#U#G_P8Lm(3AzA3AJy#~IO!}~R6^Ah8@o84z3 z!G;zpbne=1P*^QY{O|=PX=4nlHJR*)d0K;2b{8E?euh`0fjv^iT6e?~OgkA0{rV4@ zXx0ay2U)@>JX+{!>NHDhXutuei}u_!vjQE#J<a`|nvFCk1eJJ{Cu&JTBTf@k-@=~3 zl!Cw7o9nV}FD$fKz`qbw)JC*(48QZNA(V8DCIBV4WR^|}b_wQZu|mOamnr!O_?xu( z%NuFVnE~ZB=kcQw8WAOv#PpoQt1J{HJ!n3+abEk$x`ohFt&p<|NfCiSE$OJ=p`sOG z&r?x#FDlZU0|$J#*l_pkIrV>hB<H$HHyvk7o?N!`WACw_&Zn3Xf6vY~&f3FO)>TWT zqXpUX0lNyz=w-~%Tjvj|v5$*gK0UPu;+3kXm@B(0P-3qdb7j~1JxMZ|gslwUDf-H! z6`b}U)_s;lz_gK^zI?t(4Q}L`<+9vY6xbm*8$5glnqa%reh_uGJTF5*j~Y6C?xRWb zzf9Bbd>j5Y({BI`o=I-F_~tjEZ*I+KSfhqrLVU$@6l>mU;Jk$M4lseIgBB|V3haJu zq++caI?%mYn9u+9XU<kuct}>thf#b^llc(w`IL=(a5J6$QjJ^4Rd<4^q>+6TSicYA zs69-JX9mQZcABLI66KJ1=%5sTX)17NSs)*d-?j*}APbE@R$j}jvriiz%D2E|nAc^k z(^*yJb~_xq+*{o3jx;Utm(UI;#40q}iK#QT`Mo|>R-`pngS!c~Xtb*!I|2m)b0N8y z@Qb_Omhym+VVW8CGM=_c1tD49=dD8c2oa6`X(RqhRGPFxhXyZ0pmt1yjTyiq;q&^a z3})ABTxmIWgyEAyO*s(@&G331kJBQrP|KXCci6O8XF%4%DY!&Z4Yv>$7FmbSD&C_L zUKyl7NLVrI_5;tC_CbtUtS&KyX+LTu^z)E}VK}8PhGd`wm!%*r41WURbr^rAxGr!o z@;FkOpU9<CHY<_wO5j3Cs^K<?lMwyZxY9EV%w;2~p;Rc;gfp4$2P$+7PRnVzlcyvY z3zrH)xKIVt(+t|}g(qP%jl8k%Zo-@!54?Vdrh)F87VF8?JPvF)+j9XrWpXyD;(O%? z*(Z<?@liQkl1Ci4jQ{~$uot`x&8;lZLB3c7UihDoTC>l=#}aZ#lAKg$|D*`~w8;nQ zAjS6~K!ckgCy|0pUQI=g$!e=0FurywNCb%rpL2OW$4wxlr05B48=<}x!^#wGa<a+d z5P2O%?1I{MNjU)RVpM@FqEk6D%2Iu#A!4hrt5u?sPEwge6-Fr5vN1#n4Y0x7=_B#w zTYvoY<-Sw>=KtN@-^TJb*OC9HdwA8$q^Fwxx6bXL@i;84aH?9$doN^2Ib3PQBQg=M zSlG`)o_H1>k>pSxnT9)+H{&ANGaA^cqsiYInp7(@VjX`e(Jp`u4*8TD=6k{Z5Ab`- zYw(GXJh6*BSY9sY9InRR8$^5VM~ZdT@S}TJ*|%R;Nl1AQZLHiazEU}qX@dnSh=+uz zTl|Iw4(V>vUHLyNMLil!vl%bRtTU<BY}@XJQxj_#;|3|5;%1ly`rfBgotxj;8K)j! zx&GA_HQ2nVb@93G?sNWrKXc|XIcRbfaIID%+x?yz^Kh`$appeal~`GY>*-rpuidtx zvaB5fCqS}X+Lk84*)KMj$7wl<*$hCt`epyBxAU@y7E|XB2Y_$2qJ&HXZejcs@5;5% zhi7N<1@PCeH*M&8VrJ(#1KbTwz!%KYGHP*{_K^c~Z<`nR=q%+9nE0Y6jfU^kbU>PO z>IWts(bUFPno5ICbB(?RZhtpl^pPgfQw|d^>H+T4K;y|G&}7ptHqv8FPno4xH4*T@ zXFa;>l;XMK-^D`lPBB-!ji>Qkyc6<F4UUwhIe2isv&%>MuJa4=VmJVdeC(mfsit*= zjeh~AXA!d)Wc!z0UH%h57kySMId$%siXYlIY%We7O*x%%afyv&bD(cOE7`9vaM(6h ziCA8mO&xVOFV%gmV$9sB_BC)UHlzLM5b96|)}cNS*WMqdZU!_C3UJwH-sSdwjyM;7 zfIde7bQE*tyd;7w^fvwBKkC2HRK$m~yl42K9UV<*tyWT4dY{#xPUT(kdX-9_*YtX$ z+(urD_x!=KlB_>^;@511yzzDOLR7t8?f914US_lImkRA8s249EJ|Ai&wBp2sd_zTF z6PGO{9@0g4T9Ja9c+zw4kcuz??TrD*J98&$7=DO@M#ag;JTe;S0qUIq@Gy_PpPpLY zw~w`5yl^906+-LefZEOS!Og~{jgQ(TmuW=((ZrsYRUy(=j4hzKF)UvtMy)zFzSa>E zg)+H}9AUG*$R+9JwL`yQ)DJft`DjMNeiM5)#6sf^e6<!D7rrGE`F#3(s*5h%HMABQ zyIqaskR`+rtuF8=8ePB>hw%Iq{9nZ+DsZ0kFq{1=_Jt2Rsuij}RLN6iC9&AgBevT@ zHJtO4w<fiHzCEQ@&92oi`07cnR4Qd>@Ux}T$(n>h5Rjl@X~P6<Zub{2`)@UD;wpRU zXmC~wNBP)emE7pxe5taP*GjO(+3DW)fomtwc=_6!PR0M90nK=RZnEY9+gH5jK<91M z!H0OktyjXp@#XVsD!<e0s5F4o>bW-il|;{HI~{W1wx0$5UD5$Y^jm|~Aj%E+ZK#CG z?6T+sxucGAwzFfqdrRl1hrw4Fdi|prD<}ORFNeRceL`>NYo`m5sl49&>YAn|qYe&5 zxs`{=Oa_L^@El3h3M_AH;*RhRHC{d%s$klCqQ&?$M_h|0daqqe-xf*(JB}oOztnv? zw7(6!bzoiHpeU|y4txE(eZK1o*UWi_RW7mf)>KqXn6aqgMZ>JwqsP!-o4oPDvM1G3 zs-IfEW*GK3kb;@>_4-+pWU_IUa+<o@d-=vgib=uf0Il$PhfGnIyc%o*n$t3?_Y&3B z<(!3UY##aIJ&h$8+}Y(*VI6L=zrW4%;fEflgT|wE=*+>6PxpQDzI)eBpz+LQtT-Q5 zZ(gi!@~XuTBHjn$n&uWYTMh<(K6ma)v0VK4M*OFJiyv6jSmq=YvmGJR>EX)7Z%4Hs zEmlg>6g8uMof`Z&Vp&%|gQ}_lkM*v-eOq2*GQFe%3(HixDw;gUV3<?&<(%xJSuDhh zvn1&KCCe0fnb`|r&jpj-HCL_lPtzEe*14Wu+4v~W+eZNyY#+jVQ|as4v4bw2EZLz! z$1Yx#=%0#wU-;Niv;x;gCFC>=tqS_;bQ*<X^JADOA1x6}MoA<<L!fQ~#s*3<#$21S ztF?JE>CbtaJ!sz#aREK+slog8)24#HCR4pmH-8_^)2ftJ%IQia(BQA1^uR=r+Na?} za=#mi^?9tx?=`#g%-w>&7C;yMR{l3ue_r%88XKCM8<fgvlT~#Z!%Uh68iMt^s4x+Y z-{OpC=62_Zr1fd6DAi+t^VrplKUQ!DDMBqR)zI31?OUe?!{SB%G8>zouCJGCIiX-a z%(>uedOEj#8I7I$@yBx~zY5$c^u{m#7LT6!HSuQQ(zL-D&pzqXyR8oY3hUemar3H| z#;0p_3r!{-kI(Njc)U{ixL7Ct{ygC%`6~iwaMbUof*$m%T65mB<+E_)%<0o-jvev+ znM<DiC4M%1@~2oeE;V^!YdxFp)yE%vUA#ZYG|;Mc+t~d4Qp2+Ebhi+RDju1t)y|X| zY;L$vlFrXJ(BNe1{5o3Nsij~dj7y(Xj3zG@p*+f{M_g_-E}Uemw4RJ{fiA|aW&LaP z=dP0KE>|k-oUSf^M~A<))nci}<C**A0C}4oXncAh_=SQEQk9h|t<*rz7hFJL$wI}# z$%_Rjjxy>HL1=L5tt)}cu?PXp7j3!WaM0%qx?E1@+aJ~!+@{&LyfcjHI84NkB=JRa zza8gtw@Bx<ZqI1&YCP~rYCB!rV=WuLI<rbeu=8l=8;z!>CZj}GqtPgp(?=_S2LG@{ z<eR?qQOe3l6-R1<fXqG_A2j#QaWbz5x5UP<XEb;=UW<Or=<vQ~dGhl>4Hho0X$#%3 z!e}%YmelB<idQg?J>N-Ty?Gs7TQ(-H6GsixS0Fh_Dl2i4D-jLEoSj9}_5QYcs!0VF z_H}g5L^7onx3^HpaRgP6e1R~1D*;ay#r^x$SZH2H?v*We<$mTcRckl1Or5U5<In7~ z7jt?ibVp8@<?MK=vAd41e`!$ThQ+Y3{Rz0i^N}w8$?{&Jrc{l7x6xTlV6xG(amkpA z8pY=2g?j7Yd@Pp#yW~GR4LH`sj--t=1V_zEN&2Vct<}$<w#2&0uYd+eC=`2h4SXUr z;E2WphGz38fAA*rJ2~F@V?T#5zAE1D^0I!`vt6lWLdT<dQBr2+`!Efhu=$Qe74R>6 ze=#sgKm=l-U{Z|<8Uck@PO$(6I;B#ldk&XmW?Y}6J}_XFd;rNGi>Zq_Y^2v=U$rn; zg~I(-mQk<&)sFjvtJ>kaFVOe*7XmTBuuw2M9G`=)S|C$F*vcdkA`pQJq#D{eI0@~} zAX0`xb~a;1o40xEqprK;4A@<{KLE~?e9%AL<;scnlDaybZeI0tjbiard+JR>s<KnX z3i)`J7(r1K<HuKHyLrpJ+~mEQ8xK2)I+)E34KFNTV$`plBRb*z0|6kD7ptA0y}G<i zd50QY0)U_YK0X+LU(VIXi@*HbiE9Bc00MwV^j}(^o{@oqI}|{|YGfpw!OcP*o&(zq z+H<8CQL!8}Ab{Sfgl)xKTMXQgXXn8*>{VqVR>xh?iMrKMlUoA0;5;V@k#R(sk?Pa~ z4%DSi(vSng>zYCaPBWNX7)=n7hCFFjN_}$Bt{?{y(y2`ga`;jjC+rR~quo8oKpDYH z<#Bd4fN3huBUUaPS;=BLRpzE1Cm&c?1;|qdXl3g`JIaG@(kVgHD$q`v28Q}8^tcLi zV-YkCT;M7qq4u8x!zh9yvlNt*te6g<33aM-H>8lJCOf0KQnPvBQa1;)aHV9KAyN2J z24WCGE)}~?#|8KhHd8<la^M9sG=SlH4XK65-U^RKf0b_d$Sia!$ut#~c_L<(DifiZ z&DcUr2^VleJB{EZ%D81`%HUQKS>Wh|nNf}VneD_pNkK9d!fV%l5kMnQVp?g+h+#3> zbN&2zoh+PoqYDHOE?0oi$F=~2oHszKkO(kMax1`65$SdNP(*zQR0h2GPk@gbwm@H0 zI0O9%;x_xo)SDO>o*^&@FFp?p#?M!QA*eVT7^Xb&)eXmuv}y{KN5^AvOzS;H{)a7A z_YG)!4!LO4^tqFsP9dNT9c>jWo1EG@<JOWA*d}$dPkJ<Ep2u4kEdzUBuoY5)IocA# zj(&l-en$|yfPU$S7Nk#is8DW#DW(<eB5GTI%CW(oMWr5Xy;Z@Yfv3d#t|yJM{CT*C z+zLlbAUDZM`#lqcM;blNtTmL;R+$%TZ-@-CR~VCx9(ukQpo*5-DpD|FCNz`5j&d<| zn*t7%*CzE^FvPP+#thQpMG91ySaa`6BMWf64@05}tCNaT$Uin30l;723KdnQnkLO! zX|0X6+G($Y%2~bVyzbZg!}lkiq-ciactMn8Mb&h}v~0)q{2+|tB+c>*7cWJkv3Mex zN&_mB&E*TlQn^yC)f>%LyVLFU2SZ3REXNBXl4M2Ibi=f4$MyUGhokXjKw{AlQ!cgj zVRP+spMQdwP{xH++F0j9Ou1Bb({}wZPV=&E`*B|P^L{@dv8eMQrd(>XKIYozzHh%& z+F0kqC{EHWFUqQJ+O8kQX<pWCKhEoZ-tTwr?%~C&r?>Vj^SUKcUe8;P`H>5$w6XD4 z<w8cS+=W!y*rcxJd}V0tT1cg1R_zrO;nxBol{PlssxxX8E~L`NCRN550RR9{0JL!} zWL1cGlu}A*dya#YOQTxu>{KZeZ?!Juf!p{XOn`<R-5nu&wS3i%D<PFOHeNkdNg<__ zQjYVgu`F&x8WW(*iMzZs_JiV_bI!XOfC*5iZVX`<V~laT;(I_RgT@3Xb5ep(A%qY@ zh}Ht2PR1Mo0012ZILSGVG3I(~hmh51tLrjTSTh19K$(+VBCWM{yqQY~6QE_v$&l3w zVFI*FIdNA{fI555@01U}Wc=gn=l7@o`}be3zW@IJzfQEz?+z6!V6IRx<FfHqO?Wi7 mORI;I+P3lX2Rfur^mt-po|q0G7@ID|x<=<7OfDA*0001FBaN>B literal 0 HcmV?d00001 diff --git a/.next/trace b/.next/trace index 79b5e1c..87cbb37 100644 --- a/.next/trace +++ b/.next/trace @@ -1,2 +1,35 @@ -[{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"generate-buildid","id":4,"timestamp":108269043230,"duration":240,"tags":{},"startTime":1696405374373},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"load-custom-routes","id":5,"timestamp":108269043651,"duration":1755,"tags":{},"startTime":1696405374374},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"create-pages-mapping","id":6,"timestamp":108269230114,"duration":119,"tags":{},"startTime":1696405374560},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"collect-app-paths","id":7,"timestamp":108269230260,"duration":3538,"tags":{},"startTime":1696405374560},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"create-app-mapping","id":8,"timestamp":108269233817,"duration":730,"tags":{},"startTime":1696405374564},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"public-dir-conflict-check","id":9,"timestamp":108269234994,"duration":410,"tags":{},"startTime":1696405374565},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"generate-routes-manifest","id":10,"timestamp":108269235541,"duration":1643,"tags":{},"startTime":1696405374566},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"create-dist-dir","id":11,"timestamp":108269237622,"duration":865,"tags":{},"startTime":1696405374568},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"write-routes-manifest","id":12,"timestamp":108269250270,"duration":577,"tags":{},"startTime":1696405374580},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"generate-required-server-files","id":13,"timestamp":108269250905,"duration":333,"tags":{},"startTime":1696405374581},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"create-entrypoints","id":15,"timestamp":108269380236,"duration":13869,"tags":{},"startTime":1696405374710},{"traceId":"46e9d9bc8b206a47","parentId":14,"name":"generate-webpack-config","id":16,"timestamp":108269394197,"duration":286131,"tags":{},"startTime":1696405374724},{"traceId":"46e9d9bc8b206a47","parentId":17,"name":"next-trace-entrypoint-plugin","id":18,"timestamp":108269744343,"duration":2078,"tags":{},"startTime":1696405375074},{"traceId":"46e9d9bc8b206a47","parentId":19,"name":"add-entry","id":26,"timestamp":108269752187,"duration":420427,"tags":{"request":"next/dist/pages/_document"},"startTime":1696405375082},{"traceId":"46e9d9bc8b206a47","parentId":19,"name":"add-entry","id":22,"timestamp":108269752127,"duration":438419,"tags":{"request":"next-app-loader?page=%2Ffavicon.ico%2Froute&name=app%2Ffavicon.ico%2Froute&pagePath=private-next-app-dir%2Ffavicon.ico&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Ffavicon.ico&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=!"},"startTime":1696405375082},{"traceId":"46e9d9bc8b206a47","parentId":19,"name":"add-entry","id":20,"timestamp":108269751605,"duration":478045,"tags":{"request":"next/dist/pages/_app"},"startTime":1696405375082},{"traceId":"46e9d9bc8b206a47","parentId":19,"name":"add-entry","id":21,"timestamp":108269752104,"duration":477561,"tags":{"request":"next/dist/pages/_error"},"startTime":1696405375082},{"traceId":"46e9d9bc8b206a47","parentId":19,"name":"add-entry","id":24,"timestamp":108269752164,"duration":515247,"tags":{"request":"next-app-loader?page=%2Fwiston%2Fpage&name=app%2Fwiston%2Fpage&pagePath=private-next-app-dir%2Fwiston%2Fpage.tsx&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Fwiston%2Fpage&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=!"},"startTime":1696405375082},{"traceId":"46e9d9bc8b206a47","parentId":19,"name":"add-entry","id":23,"timestamp":108269752151,"duration":515275,"tags":{"request":"next-app-loader?page=%2Fpage&name=app%2Fpage&pagePath=private-next-app-dir%2Fpage.tsx&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Fpage&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=!"},"startTime":1696405375082},{"traceId":"46e9d9bc8b206a47","parentId":19,"name":"add-entry","id":27,"timestamp":108269752197,"duration":552799,"tags":{"request":"next-app-loader?page=%2Feveryone-votes%2Fprivacy%2Fpage&name=app%2Feveryone-votes%2Fprivacy%2Fpage&pagePath=private-next-app-dir%2Feveryone-votes%2Fprivacy%2Fpage.tsx&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Feveryone-votes%2Fprivacy%2Fpage&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=!"},"startTime":1696405375082},{"traceId":"46e9d9bc8b206a47","parentId":19,"name":"add-entry","id":25,"timestamp":108269752176,"duration":574931,"tags":{"request":"next-app-loader?page=%2Fspace%2Fpage&name=app%2Fspace%2Fpage&pagePath=private-next-app-dir%2Fspace%2Fpage.tsx&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Fspace%2Fpage&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=!"},"startTime":1696405375082},{"traceId":"46e9d9bc8b206a47","parentId":19,"name":"add-entry","id":28,"timestamp":108269752208,"duration":574970,"tags":{"request":"next-app-loader?page=%2Feveryone-votes%2Fterms%2Fpage&name=app%2Feveryone-votes%2Fterms%2Fpage&pagePath=private-next-app-dir%2Feveryone-votes%2Fterms%2Fpage.tsx&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Feveryone-votes%2Fterms%2Fpage&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=!"},"startTime":1696405375082},{"traceId":"46e9d9bc8b206a47","parentId":17,"name":"make","id":19,"timestamp":108269751265,"duration":1027721,"tags":{},"startTime":1696405375081},{"traceId":"46e9d9bc8b206a47","parentId":45,"name":"get-entries","id":46,"timestamp":108270780257,"duration":1584,"tags":{},"startTime":1696405376110},{"traceId":"46e9d9bc8b206a47","parentId":45,"name":"node-file-trace","id":47,"timestamp":108270782260,"duration":69395,"tags":{"traceEntryCount":"18"},"startTime":1696405376112},{"traceId":"46e9d9bc8b206a47","parentId":45,"name":"collect-traced-files","id":48,"timestamp":108270851668,"duration":733,"tags":{},"startTime":1696405376182},{"traceId":"46e9d9bc8b206a47","parentId":18,"name":"finish-modules","id":45,"timestamp":108270780079,"duration":72333,"tags":{},"startTime":1696405376110},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"chunk-graph","id":50,"timestamp":108271025817,"duration":26964,"tags":{},"startTime":1696405376356},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"optimize-modules","id":52,"timestamp":108271052910,"duration":24119,"tags":{},"startTime":1696405376383},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"optimize-chunks","id":53,"timestamp":108271077198,"duration":16399,"tags":{},"startTime":1696405376407},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"optimize-tree","id":54,"timestamp":108271093743,"duration":132,"tags":{},"startTime":1696405376424},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"optimize-chunk-modules","id":55,"timestamp":108271093977,"duration":58589,"tags":{},"startTime":1696405376424},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"optimize","id":51,"timestamp":108271052852,"duration":99813,"tags":{},"startTime":1696405376383},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"module-hash","id":56,"timestamp":108271174741,"duration":50647,"tags":{},"startTime":1696405376505},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"code-generation","id":57,"timestamp":108271225443,"duration":3190,"tags":{},"startTime":1696405376555},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"hash","id":58,"timestamp":108271233349,"duration":7095,"tags":{},"startTime":1696405376563},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"code-generation-jobs","id":59,"timestamp":108271240443,"duration":243,"tags":{},"startTime":1696405376570},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"module-assets","id":60,"timestamp":108271240643,"duration":453,"tags":{},"startTime":1696405376571},{"traceId":"46e9d9bc8b206a47","parentId":49,"name":"create-chunk-assets","id":61,"timestamp":108271241109,"duration":1351,"tags":{},"startTime":1696405376571},{"traceId":"46e9d9bc8b206a47","parentId":18,"name":"create-trace-assets","id":62,"timestamp":108271243554,"duration":6972257,"tags":{},"startTime":1696405376574},{"traceId":"46e9d9bc8b206a47","parentId":17,"name":"seal","id":49,"timestamp":108270966797,"duration":7256952,"tags":{},"startTime":1696405376297},{"traceId":"46e9d9bc8b206a47","parentId":14,"name":"webpack-compilation","id":17,"timestamp":108269742672,"duration":8490433,"tags":{"name":"server"},"startTime":1696405375073},{"traceId":"46e9d9bc8b206a47","parentId":14,"name":"emit","id":63,"timestamp":108278233614,"duration":24454,"tags":{},"startTime":1696405383564},{"traceId":"46e9d9bc8b206a47","parentId":14,"name":"webpack-close","id":64,"timestamp":108278258780,"duration":726,"tags":{"name":"server"},"startTime":1696405383589},{"traceId":"46e9d9bc8b206a47","parentId":64,"name":"webpack-generate-error-stats","id":65,"timestamp":108278259551,"duration":2671,"tags":{},"startTime":1696405383590},{"traceId":"46e9d9bc8b206a47","parentId":66,"name":"make","id":67,"timestamp":108278279352,"duration":315,"tags":{},"startTime":1696405383609},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"chunk-graph","id":69,"timestamp":108278281284,"duration":26,"tags":{},"startTime":1696405383611},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"optimize-modules","id":71,"timestamp":108278281365,"duration":34,"tags":{},"startTime":1696405383611},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"optimize-chunks","id":72,"timestamp":108278281460,"duration":70,"tags":{},"startTime":1696405383611},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"optimize-tree","id":73,"timestamp":108278281579,"duration":9,"tags":{},"startTime":1696405383612},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"optimize-chunk-modules","id":74,"timestamp":108278281656,"duration":53,"tags":{},"startTime":1696405383612},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"optimize","id":70,"timestamp":108278281326,"duration":422,"tags":{},"startTime":1696405383611},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"module-hash","id":75,"timestamp":108278281973,"duration":16,"tags":{},"startTime":1696405383612},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"code-generation","id":76,"timestamp":108278282000,"duration":18,"tags":{},"startTime":1696405383612},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"hash","id":77,"timestamp":108278282064,"duration":62,"tags":{},"startTime":1696405383612},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"code-generation-jobs","id":78,"timestamp":108278282126,"duration":47,"tags":{},"startTime":1696405383612},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"module-assets","id":79,"timestamp":108278282163,"duration":22,"tags":{},"startTime":1696405383612},{"traceId":"46e9d9bc8b206a47","parentId":68,"name":"create-chunk-assets","id":80,"timestamp":108278282192,"duration":16,"tags":{},"startTime":1696405383612},{"traceId":"46e9d9bc8b206a47","parentId":66,"name":"terser-webpack-plugin-optimize","id":81,"timestamp":108278282820,"duration":353,"tags":{"compilationName":"edge-server","swcMinify":"true"},"startTime":1696405383613},{"traceId":"46e9d9bc8b206a47","parentId":66,"name":"css-minimizer-plugin","id":82,"timestamp":108278283261,"duration":111,"tags":{"webpackVersion":"5"},"startTime":1696405383613},{"traceId":"46e9d9bc8b206a47","parentId":66,"name":"seal","id":68,"timestamp":108278281090,"duration":4441,"tags":{},"startTime":1696405383611},{"traceId":"46e9d9bc8b206a47","parentId":14,"name":"webpack-compilation","id":66,"timestamp":108278277337,"duration":8368,"tags":{"name":"edge-server"},"startTime":1696405383607},{"traceId":"46e9d9bc8b206a47","parentId":14,"name":"emit","id":83,"timestamp":108278285841,"duration":1067,"tags":{},"startTime":1696405383616},{"traceId":"46e9d9bc8b206a47","parentId":14,"name":"webpack-close","id":84,"timestamp":108278287096,"duration":194,"tags":{"name":"edge-server"},"startTime":1696405383617},{"traceId":"46e9d9bc8b206a47","parentId":84,"name":"webpack-generate-error-stats","id":85,"timestamp":108278287297,"duration":654,"tags":{},"startTime":1696405383617},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":98,"timestamp":108278297451,"duration":318684,"tags":{"request":"next-flight-client-entry-loader?server=false!"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":99,"timestamp":108278297458,"duration":318689,"tags":{"request":"next-flight-client-entry-loader?server=false!"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":100,"timestamp":108278297461,"duration":318688,"tags":{"request":"next-flight-client-entry-loader?server=false!"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":96,"timestamp":108278297335,"duration":373257,"tags":{"request":"next-flight-client-entry-loader?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cwiston%5Cpage.tsx&server=false!"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":91,"timestamp":108278297302,"duration":394360,"tags":{"request":"next-client-pages-loader?absolutePagePath=next%2Fdist%2Fpages%2F_app&page=%2F_app!"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":93,"timestamp":108278297315,"duration":395921,"tags":{"request":"next-client-pages-loader?absolutePagePath=next%2Fdist%2Fpages%2F_error&page=%2F_error!"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":102,"name":"read-resource","id":103,"timestamp":108278688227,"duration":6477,"tags":{},"startTime":1696405384018},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":92,"timestamp":108278297308,"duration":611265,"tags":{"request":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\router.js"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":107,"name":"postcss-process","id":108,"timestamp":108279265460,"duration":217756,"tags":{},"startTime":1696405384595},{"traceId":"46e9d9bc8b206a47","parentId":102,"name":"postcss-loader","id":107,"timestamp":108279265330,"duration":217973,"tags":{},"startTime":1696405384595},{"traceId":"46e9d9bc8b206a47","parentId":102,"name":"css-loader","id":109,"timestamp":108279483484,"duration":33268,"tags":{"astUsed":"true"},"startTime":1696405384813},{"traceId":"46e9d9bc8b206a47","parentId":105,"name":"read-resource","id":106,"timestamp":108278908407,"duration":622282,"tags":{},"startTime":1696405384238},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":90,"timestamp":108278297292,"duration":1243096,"tags":{"request":"next-flight-client-entry-loader?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Capp-router.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Clayout-router.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Crender-from-template-context.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Cerror-boundary.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Cstatic-generation-searchparams-bailout-provider.js&server=false!"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":89,"timestamp":108278297273,"duration":1243128,"tags":{"request":"./node_modules/next/dist/client/app-next.js"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":110,"name":"postcss-process","id":111,"timestamp":108279564623,"duration":98305,"tags":{},"startTime":1696405384895},{"traceId":"46e9d9bc8b206a47","parentId":105,"name":"postcss-loader","id":110,"timestamp":108279564612,"duration":98363,"tags":{},"startTime":1696405384895},{"traceId":"46e9d9bc8b206a47","parentId":105,"name":"css-loader","id":112,"timestamp":108279663006,"duration":4911,"tags":{"astUsed":"true"},"startTime":1696405384993},{"traceId":"46e9d9bc8b206a47","parentId":101,"name":"build-module-scss","id":102,"timestamp":108278671286,"duration":1026106,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss.webpack[javascript/auto]!=!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\css-loader\\src\\index.js??ruleSet[1].rules[2].oneOf[13].use[2]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\postcss-loader\\src\\index.js??ruleSet[1].rules[2].oneOf[13].use[3]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\resolve-url-loader\\index.js??ruleSet[1].rules[2].oneOf[13].use[4]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\sass-loader\\cjs.js??ruleSet[1].rules[2].oneOf[13].use[5]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss"},"startTime":1696405384001},{"traceId":"46e9d9bc8b206a47","parentId":104,"name":"build-module-scss","id":105,"timestamp":108278908250,"duration":789217,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss.webpack[javascript/auto]!=!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\css-loader\\src\\index.js??ruleSet[1].rules[2].oneOf[13].use[2]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\postcss-loader\\src\\index.js??ruleSet[1].rules[2].oneOf[13].use[3]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\resolve-url-loader\\index.js??ruleSet[1].rules[2].oneOf[13].use[4]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\sass-loader\\cjs.js??ruleSet[1].rules[2].oneOf[13].use[5]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss"},"startTime":1696405384238},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":88,"timestamp":108278297203,"duration":1546172,"tags":{"request":"./node_modules/next/dist/client/next.js"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":86,"name":"build-module-scss","id":101,"timestamp":108278650139,"duration":1214074,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss"},"startTime":1696405383980},{"traceId":"46e9d9bc8b206a47","parentId":86,"name":"build-module-scss","id":104,"timestamp":108278690076,"duration":1175294,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss"},"startTime":1696405384020},{"traceId":"46e9d9bc8b206a47","parentId":101,"name":"build-module","id":113,"timestamp":108279974359,"duration":176,"tags":{"name":"undefined"},"startTime":1696405385304},{"traceId":"46e9d9bc8b206a47","parentId":104,"name":"build-module","id":114,"timestamp":108279974554,"duration":24,"tags":{"name":"undefined"},"startTime":1696405385305},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":94,"timestamp":108278297322,"duration":1677654,"tags":{"request":"next-flight-client-entry-loader?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cfont%5Cgoogle%5Ctarget.css%3F%7B%22path%22%3A%22app%5C%5Clayout.tsx%22%2C%22import%22%3A%22Inter%22%2C%22arguments%22%3A%5B%7B%22subsets%22%3A%5B%22latin%22%5D%7D%5D%2C%22variableName%22%3A%22inter%22%7D&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cglobals.scss&server=false!"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":95,"timestamp":108278297328,"duration":1680171,"tags":{"request":"next-flight-client-entry-loader?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cpage.tsx&server=false!"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":87,"name":"add-entry","id":97,"timestamp":108278297433,"duration":1699476,"tags":{"request":"next-flight-client-entry-loader?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cspace%5Cpage.tsx&server=false!"},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":86,"name":"make","id":87,"timestamp":108278296687,"duration":1700302,"tags":{},"startTime":1696405383627},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"chunk-graph","id":116,"timestamp":108280087327,"duration":20058,"tags":{},"startTime":1696405385417},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"optimize-modules","id":118,"timestamp":108280107431,"duration":9,"tags":{},"startTime":1696405385437},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"optimize-chunks","id":119,"timestamp":108280107459,"duration":10890,"tags":{},"startTime":1696405385437},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"optimize-tree","id":120,"timestamp":108280118387,"duration":9,"tags":{},"startTime":1696405385448},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"optimize-chunk-modules","id":121,"timestamp":108280118424,"duration":65951,"tags":{},"startTime":1696405385448},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"optimize","id":117,"timestamp":108280107415,"duration":76992,"tags":{},"startTime":1696405385437},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"module-hash","id":122,"timestamp":108280197860,"duration":41005,"tags":{},"startTime":1696405385528},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"code-generation","id":123,"timestamp":108280238895,"duration":2945,"tags":{},"startTime":1696405385569}] -[{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"hash","id":124,"timestamp":108280244373,"duration":4576,"tags":{},"startTime":1696405385574},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"code-generation-jobs","id":125,"timestamp":108280248947,"duration":120,"tags":{},"startTime":1696405385579},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"module-assets","id":126,"timestamp":108280249046,"duration":480,"tags":{},"startTime":1696405385579},{"traceId":"46e9d9bc8b206a47","parentId":115,"name":"create-chunk-assets","id":127,"timestamp":108280249537,"duration":3069,"tags":{},"startTime":1696405385580},{"traceId":"46e9d9bc8b206a47","parentId":86,"name":"NextJsBuildManifest-generateClientManifest","id":129,"timestamp":108280253866,"duration":583,"tags":{},"startTime":1696405385584},{"traceId":"46e9d9bc8b206a47","parentId":86,"name":"NextJsBuildManifest-createassets","id":128,"timestamp":108280253259,"duration":1203,"tags":{},"startTime":1696405385583},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":131,"timestamp":108280264342,"duration":1017,"tags":{"name":"static/chunks/main-dba5d122367f02b7.js","cache":"HIT"},"startTime":1696405385594},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":132,"timestamp":108280264485,"duration":884,"tags":{"name":"static/chunks/main-app-0be5dce44311dbbf.js","cache":"HIT"},"startTime":1696405385594},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":133,"timestamp":108280264499,"duration":870,"tags":{"name":"static/chunks/pages/_app-b555d5e1eab47959.js","cache":"HIT"},"startTime":1696405385594},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":134,"timestamp":108280264510,"duration":861,"tags":{"name":"static/chunks/pages/_error-d79168f986538ac0.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":135,"timestamp":108280264520,"duration":852,"tags":{"name":"static/chunks/app/layout-3d94fcc1098e9e97.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":136,"timestamp":108280264528,"duration":844,"tags":{"name":"static/chunks/app/page-8204c3b0f59bd205.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":137,"timestamp":108280264535,"duration":838,"tags":{"name":"static/chunks/app/wiston/page-becb82f49ed47545.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":138,"timestamp":108280264545,"duration":830,"tags":{"name":"static/chunks/app/space/page-aa0f5917bd776cea.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":139,"timestamp":108280264551,"duration":824,"tags":{"name":"static/chunks/app/space/loading-df1b886b524be596.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":140,"timestamp":108280264558,"duration":819,"tags":{"name":"static/chunks/app/everyone-votes/privacy/page-4d788de82a96b899.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":141,"timestamp":108280264569,"duration":808,"tags":{"name":"static/chunks/app/everyone-votes/terms/page-5aa776690a4e5edf.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":142,"timestamp":108280264578,"duration":800,"tags":{"name":"static/chunks/webpack-54b114c68857d808.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":143,"timestamp":108280264585,"duration":794,"tags":{"name":"static/chunks/716.21f9bdadee25fb55.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":144,"timestamp":108280264594,"duration":787,"tags":{"name":"static/chunks/framework-8883d1e9be70c3da.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":145,"timestamp":108280264600,"duration":781,"tags":{"name":"static/chunks/f75787ed-011198ef7e5d7754.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":146,"timestamp":108280264606,"duration":776,"tags":{"name":"static/chunks/43cb4aaa-0dfcb2e81cc1cbc1.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":147,"timestamp":108280264612,"duration":771,"tags":{"name":"static/chunks/f126df28-0647fc1012c29407.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":148,"timestamp":108280264618,"duration":766,"tags":{"name":"static/chunks/51231e76-cf1b2fc1d6b83e48.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":149,"timestamp":108280264625,"duration":760,"tags":{"name":"static/chunks/53417c1a-c755bb806ffa7a5d.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":150,"timestamp":108280264631,"duration":754,"tags":{"name":"static/chunks/2443530c-097fe1871e1d7679.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":151,"timestamp":108280264637,"duration":749,"tags":{"name":"static/chunks/23-fb41cbadaf19fac2.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":152,"timestamp":108280264643,"duration":744,"tags":{"name":"static/chunks/488-66ca2c1db348e680.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":153,"timestamp":108280264649,"duration":739,"tags":{"name":"server/middleware-react-loadable-manifest.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":157,"timestamp":108280265347,"duration":42,"tags":{"name":"server/next-font-manifest.js","cache":"HIT"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":154,"timestamp":108280264692,"duration":1717,"tags":{"name":"static/Qb5fVlqLpQAODnw100j4z/_ssgManifest.js","cache":"MISS"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":156,"timestamp":108280265315,"duration":1131,"tags":{"name":"static/Qb5fVlqLpQAODnw100j4z/_buildManifest.js","cache":"MISS"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":130,"name":"minify-js","id":155,"timestamp":108280265214,"duration":1260,"tags":{"name":"server/middleware-build-manifest.js","cache":"MISS"},"startTime":1696405385595},{"traceId":"46e9d9bc8b206a47","parentId":86,"name":"terser-webpack-plugin-optimize","id":130,"timestamp":108280255014,"duration":11464,"tags":{"compilationName":"client","swcMinify":"true"},"startTime":1696405385585},{"traceId":"46e9d9bc8b206a47","parentId":158,"name":"minify-css","id":159,"timestamp":108280266579,"duration":90,"tags":{"file":"static/css/3bcdf32fef69c651.css","cache":"HIT"},"startTime":1696405385597},{"traceId":"46e9d9bc8b206a47","parentId":158,"name":"minify-css","id":160,"timestamp":108280266620,"duration":52,"tags":{"file":"static/css/8c222b83c13bd107.css","cache":"HIT"},"startTime":1696405385597},{"traceId":"46e9d9bc8b206a47","parentId":86,"name":"css-minimizer-plugin","id":158,"timestamp":108280266527,"duration":147,"tags":{"webpackVersion":"5"},"startTime":1696405385597},{"traceId":"46e9d9bc8b206a47","parentId":86,"name":"seal","id":115,"timestamp":108280049452,"duration":230005,"tags":{},"startTime":1696405385379},{"traceId":"46e9d9bc8b206a47","parentId":14,"name":"webpack-compilation","id":86,"timestamp":108278295272,"duration":1984321,"tags":{"name":"client"},"startTime":1696405383625},{"traceId":"46e9d9bc8b206a47","parentId":14,"name":"emit","id":161,"timestamp":108280279631,"duration":7430,"tags":{},"startTime":1696405385610},{"traceId":"46e9d9bc8b206a47","parentId":14,"name":"webpack-close","id":162,"timestamp":108280287264,"duration":39646,"tags":{"name":"client"},"startTime":1696405385617},{"traceId":"46e9d9bc8b206a47","parentId":162,"name":"webpack-generate-error-stats","id":163,"timestamp":108280326921,"duration":593,"tags":{},"startTime":1696405385657},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"run-webpack-compiler","id":14,"timestamp":108269380234,"duration":10947300,"tags":{},"startTime":1696405374710},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"format-webpack-messages","id":164,"timestamp":108280327538,"duration":84,"tags":{},"startTime":1696405385658},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"verify-and-lint","id":166,"timestamp":108280362122,"duration":1733411,"tags":{},"startTime":1696405385692},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"verify-typescript-setup","id":165,"timestamp":108280330828,"duration":2564164,"tags":{},"startTime":1696405385661},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-static-error-page","id":168,"timestamp":108283080366,"duration":3076,"tags":{},"startTime":1696405388410},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-static-error-page","id":168,"timestamp":108283080366,"duration":3086,"tags":{},"startTime":1696405388410},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-page","id":169,"timestamp":108283212991,"duration":1107,"tags":{"page":"/_app"},"startTime":1696405388543},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-page","id":171,"timestamp":108283213635,"duration":475,"tags":{"page":"/_document"},"startTime":1696405388544},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-page","id":170,"timestamp":108283213555,"duration":677,"tags":{"page":"/_error"},"startTime":1696405388544},{"traceId":"46e9d9bc8b206a47","parentId":173,"name":"is-page-static","id":180,"timestamp":108283214937,"duration":264390,"tags":{},"startTime":1696405388545},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-page","id":173,"timestamp":108283213718,"duration":265642,"tags":{"page":"/everyone-votes/terms"},"startTime":1696405388544},{"traceId":"46e9d9bc8b206a47","parentId":177,"name":"is-page-static","id":183,"timestamp":108283215238,"duration":264856,"tags":{},"startTime":1696405388545},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-page","id":177,"timestamp":108283213911,"duration":266205,"tags":{"page":"/wiston"},"startTime":1696405388544},{"traceId":"46e9d9bc8b206a47","parentId":175,"name":"is-page-static","id":181,"timestamp":108283215006,"duration":265340,"tags":{},"startTime":1696405388545},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-page","id":175,"timestamp":108283213782,"duration":266587,"tags":{"page":"/"},"startTime":1696405388544},{"traceId":"46e9d9bc8b206a47","parentId":174,"name":"is-page-static","id":178,"timestamp":108283214669,"duration":274438,"tags":{},"startTime":1696405388545},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-page","id":174,"timestamp":108283213748,"duration":275423,"tags":{"page":"/favicon.ico"},"startTime":1696405388544},{"traceId":"46e9d9bc8b206a47","parentId":172,"name":"is-page-static","id":179,"timestamp":108283214863,"duration":277431,"tags":{},"startTime":1696405388545},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-page","id":172,"timestamp":108283213664,"duration":278709,"tags":{"page":"/everyone-votes/privacy"},"startTime":1696405388544},{"traceId":"46e9d9bc8b206a47","parentId":176,"name":"is-page-static","id":182,"timestamp":108283215072,"duration":446863,"tags":{},"startTime":1696405388545},{"traceId":"46e9d9bc8b206a47","parentId":167,"name":"check-page","id":176,"timestamp":108283213830,"duration":448134,"tags":{"page":"/space"},"startTime":1696405388544},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"static-check","id":167,"timestamp":108283080007,"duration":581985,"tags":{},"startTime":1696405388410},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"apply-include-excludes","id":184,"timestamp":108283705209,"duration":854,"tags":{},"startTime":1696405389035},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"trace-next-server","id":185,"timestamp":108283706082,"duration":5667,"tags":{},"startTime":1696405389036},{"traceId":"46e9d9bc8b206a47","parentId":187,"name":"load-dotenv","id":188,"timestamp":108283736779,"duration":111,"tags":{},"startTime":1696405389067},{"traceId":"46e9d9bc8b206a47","parentId":187,"name":"run-export-path-map","id":189,"timestamp":108283740052,"duration":264,"tags":{},"startTime":1696405389070},{"traceId":"46e9d9bc8b206a47","parentId":187,"name":"export-page","id":195,"timestamp":108283743407,"duration":52024,"tags":{"path":"/favicon.ico"},"startTime":1696405389073},{"traceId":"46e9d9bc8b206a47","parentId":187,"name":"export-page","id":196,"timestamp":108283743808,"duration":183544,"tags":{"path":"/everyone-votes/privacy"},"startTime":1696405389074},{"traceId":"46e9d9bc8b206a47","parentId":187,"name":"export-page","id":191,"timestamp":108283741654,"duration":318124,"tags":{"path":"/500"},"startTime":1696405389072},{"traceId":"46e9d9bc8b206a47","parentId":187,"name":"export-page","id":190,"timestamp":108283740933,"duration":326073,"tags":{"path":"/404"},"startTime":1696405389071},{"traceId":"46e9d9bc8b206a47","parentId":187,"name":"export-page","id":193,"timestamp":108283742541,"duration":441075,"tags":{"path":"/wiston"},"startTime":1696405389073},{"traceId":"46e9d9bc8b206a47","parentId":187,"name":"export-page","id":194,"timestamp":108283742939,"duration":455244,"tags":{"path":"/"},"startTime":1696405389073},{"traceId":"46e9d9bc8b206a47","parentId":187,"name":"export-page","id":192,"timestamp":108283742098,"duration":471359,"tags":{"path":"/everyone-votes/terms"},"startTime":1696405389072},{"traceId":"46e9d9bc8b206a47","parentId":187,"name":"export-page","id":197,"timestamp":108283744296,"duration":514770,"tags":{"path":"/space"},"startTime":1696405389074},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"next-export","id":187,"timestamp":108283736171,"duration":758018,"tags":{},"startTime":1696405389066},{"traceId":"46e9d9bc8b206a47","parentId":186,"name":"move-exported-page","id":198,"timestamp":108284494841,"duration":1339,"tags":{},"startTime":1696405389825},{"traceId":"46e9d9bc8b206a47","parentId":186,"name":"move-exported-page","id":199,"timestamp":108284496190,"duration":579,"tags":{},"startTime":1696405389826},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"static-generation","id":186,"timestamp":108283719258,"duration":778930,"tags":{},"startTime":1696405389049},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"print-tree-view","id":200,"timestamp":108284503575,"duration":10975,"tags":{},"startTime":1696405389834},{"traceId":"46e9d9bc8b206a47","parentId":1,"name":"telemetry-flush","id":201,"timestamp":108284514566,"duration":176010,"tags":{},"startTime":1696405389845},{"traceId":"46e9d9bc8b206a47","name":"next-build","id":1,"timestamp":108268928900,"duration":15761686,"tags":{"version":"13.4.4"},"startTime":1696405374259}] +[{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"generate-buildid","id":4,"timestamp":839447775886,"duration":154,"tags":{},"startTime":1704500734959},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"load-custom-routes","id":5,"timestamp":839447776190,"duration":1271,"tags":{},"startTime":1704500734960},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"create-pages-mapping","id":6,"timestamp":839447840732,"duration":85,"tags":{},"startTime":1704500735024},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"collect-app-paths","id":7,"timestamp":839447840834,"duration":1447,"tags":{},"startTime":1704500735024},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"create-app-mapping","id":8,"timestamp":839447842297,"duration":639,"tags":{},"startTime":1704500735026},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"public-dir-conflict-check","id":9,"timestamp":839447843188,"duration":468,"tags":{},"startTime":1704500735027},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"generate-routes-manifest","id":10,"timestamp":839447843768,"duration":1419,"tags":{},"startTime":1704500735027},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"create-dist-dir","id":11,"timestamp":839447845523,"duration":31505,"tags":{},"startTime":1704500735029},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"write-routes-manifest","id":12,"timestamp":839447880937,"duration":513,"tags":{},"startTime":1704500735065},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"generate-required-server-files","id":13,"timestamp":839447881792,"duration":225,"tags":{},"startTime":1704500735065},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"create-entrypoints","id":15,"timestamp":839447884059,"duration":15134,"tags":{},"startTime":1704500735068},{"traceId":"4dea77cda8cb5b99","parentId":14,"name":"generate-webpack-config","id":16,"timestamp":839447899211,"duration":194454,"tags":{},"startTime":1704500735083},{"traceId":"4dea77cda8cb5b99","parentId":17,"name":"next-trace-entrypoint-plugin","id":18,"timestamp":839448143683,"duration":1205,"tags":{},"startTime":1704500735327},{"traceId":"4dea77cda8cb5b99","parentId":19,"name":"add-entry","id":22,"timestamp":839448148631,"duration":249251,"tags":{"request":"next/dist/pages/_app"},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":19,"name":"add-entry","id":21,"timestamp":839448148615,"duration":253471,"tags":{"request":"next-route-loader?kind=PAGES&page=%2F_error&preferredRegion=&absolutePagePath=next%2Fdist%2Fpages%2F_error&absoluteAppPath=next%2Fdist%2Fpages%2F_app&absoluteDocumentPath=next%2Fdist%2Fpages%2F_document&middlewareConfigBase64=e30%3D!"},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":19,"name":"add-entry","id":28,"timestamp":839448148676,"duration":257090,"tags":{"request":"next/dist/pages/_document"},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":19,"name":"add-entry","id":20,"timestamp":839448148287,"duration":278934,"tags":{"request":"next-app-loader?page=%2F_not-found&name=app%2F_not-found&pagePath=next%2Fdist%2Fclient%2Fcomponents%2Fnot-found-error&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=next%2Fdist%2Fclient%2Fcomponents%2Fnot-found-error&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!"},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":19,"name":"add-entry","id":23,"timestamp":839448148640,"duration":292003,"tags":{"request":"next-app-loader?page=%2Feveryone-votes%2Fterms%2Fpage&name=app%2Feveryone-votes%2Fterms%2Fpage&pagePath=private-next-app-dir%2Feveryone-votes%2Fterms%2Fpage.tsx&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Feveryone-votes%2Fterms%2Fpage&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!"},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":19,"name":"add-entry","id":24,"timestamp":839448148648,"duration":292001,"tags":{"request":"next-app-loader?page=%2Feveryone-votes%2Fprivacy%2Fpage&name=app%2Feveryone-votes%2Fprivacy%2Fpage&pagePath=private-next-app-dir%2Feveryone-votes%2Fprivacy%2Fpage.tsx&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Feveryone-votes%2Fprivacy%2Fpage&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!"},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":19,"name":"add-entry","id":26,"timestamp":839448148662,"duration":291990,"tags":{"request":"next-app-loader?page=%2Fpage&name=app%2Fpage&pagePath=private-next-app-dir%2Fpage.tsx&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Fpage&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!"},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":19,"name":"add-entry","id":27,"timestamp":839448148669,"duration":291985,"tags":{"request":"next-app-loader?page=%2Fspace%2Fpage&name=app%2Fspace%2Fpage&pagePath=private-next-app-dir%2Fspace%2Fpage.tsx&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Fspace%2Fpage&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!"},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":19,"name":"add-entry","id":25,"timestamp":839448148655,"duration":292035,"tags":{"request":"next-app-loader?page=%2Ffavicon.ico%2Froute&name=app%2Ffavicon.ico%2Froute&pagePath=private-next-app-dir%2Ffavicon.ico&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Ffavicon.ico&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!"},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":31,"name":"next-swc-transform","id":32,"timestamp":839448439177,"duration":4255,"tags":{},"startTime":1704500735623},{"traceId":"4dea77cda8cb5b99","parentId":30,"name":"next-swc-loader","id":31,"timestamp":839448438657,"duration":4781,"tags":{},"startTime":1704500735622},{"traceId":"4dea77cda8cb5b99","parentId":17,"name":"build-module-tsx","id":30,"timestamp":839448436221,"duration":18191,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx","layer":"rsc"},"startTime":1704500735620},{"traceId":"4dea77cda8cb5b99","parentId":19,"name":"add-entry","id":29,"timestamp":839448148797,"duration":312640,"tags":{"request":"next-app-loader?page=%2Fwiston%2Fpage&name=app%2Fwiston%2Fpage&pagePath=private-next-app-dir%2Fwiston%2Fpage.tsx&appDir=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp&appPaths=%2Fwiston%2Fpage&pageExtensions=tsx&pageExtensions=ts&pageExtensions=jsx&pageExtensions=js&basePath=&assetPrefix=&nextConfigOutput=&preferredRegion=&middlewareConfig=e30%3D!"},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":17,"name":"build-module-scss&server=true!","id":51,"timestamp":839448472423,"duration":1142,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\next-flight-client-entry-loader.js?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cfont%5Cgoogle%5Ctarget.css%3F%7B%22path%22%3A%22app%5C%5Clayout.tsx%22%2C%22import%22%3A%22Inter%22%2C%22arguments%22%3A%5B%7B%22subsets%22%3A%5B%22latin%22%5D%7D%5D%2C%22variableName%22%3A%22inter%22%7D&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cglobals.scss&server=true!","layer":"ssr"},"startTime":1704500735656},{"traceId":"4dea77cda8cb5b99","parentId":17,"name":"make","id":19,"timestamp":839448148070,"duration":553049,"tags":{},"startTime":1704500735332},{"traceId":"4dea77cda8cb5b99","parentId":52,"name":"get-entries","id":53,"timestamp":839448702019,"duration":884,"tags":{},"startTime":1704500735886},{"traceId":"4dea77cda8cb5b99","parentId":52,"name":"node-file-trace-plugin","id":54,"timestamp":839448703275,"duration":46239,"tags":{"traceEntryCount":"16"},"startTime":1704500735887},{"traceId":"4dea77cda8cb5b99","parentId":52,"name":"collect-traced-files","id":55,"timestamp":839448749520,"duration":460,"tags":{},"startTime":1704500735933},{"traceId":"4dea77cda8cb5b99","parentId":18,"name":"finish-modules","id":52,"timestamp":839448701890,"duration":48094,"tags":{},"startTime":1704500735885},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"chunk-graph","id":57,"timestamp":839448832550,"duration":18277,"tags":{},"startTime":1704500736016},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"optimize-modules","id":59,"timestamp":839448850900,"duration":15,"tags":{},"startTime":1704500736034},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"optimize-chunks","id":60,"timestamp":839448850964,"duration":11447,"tags":{},"startTime":1704500736035},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"optimize-tree","id":61,"timestamp":839448862461,"duration":86,"tags":{},"startTime":1704500736046},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"optimize-chunk-modules","id":62,"timestamp":839448862601,"duration":37312,"tags":{},"startTime":1704500736046},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"optimize","id":58,"timestamp":839448850868,"duration":49108,"tags":{},"startTime":1704500736034},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"module-hash","id":63,"timestamp":839448917705,"duration":31304,"tags":{},"startTime":1704500736101},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"code-generation","id":64,"timestamp":839448949040,"duration":6783,"tags":{},"startTime":1704500736133},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"hash","id":65,"timestamp":839448959309,"duration":4775,"tags":{},"startTime":1704500736143},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"code-generation-jobs","id":66,"timestamp":839448964082,"duration":175,"tags":{},"startTime":1704500736148},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"module-assets","id":67,"timestamp":839448964216,"duration":308,"tags":{},"startTime":1704500736148},{"traceId":"4dea77cda8cb5b99","parentId":56,"name":"create-chunk-assets","id":68,"timestamp":839448964534,"duration":2977,"tags":{},"startTime":1704500736148},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":71,"timestamp":839448977695,"duration":2931,"tags":{"name":"../pages/_error.js","cache":"HIT"},"startTime":1704500736161},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":72,"timestamp":839448977744,"duration":2885,"tags":{"name":"../pages/_app.js","cache":"HIT"},"startTime":1704500736161},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":75,"timestamp":839448978737,"duration":1893,"tags":{"name":"../app/favicon.ico/route.js","cache":"HIT"},"startTime":1704500736162},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":78,"timestamp":839448979228,"duration":1403,"tags":{"name":"../pages/_document.js","cache":"HIT"},"startTime":1704500736163},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":80,"timestamp":839448980389,"duration":243,"tags":{"name":"../webpack-runtime.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":81,"timestamp":839448980402,"duration":230,"tags":{"name":"106.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":82,"timestamp":839448980407,"duration":226,"tags":{"name":"862.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":83,"timestamp":839448980412,"duration":222,"tags":{"name":"323.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":84,"timestamp":839448980416,"duration":218,"tags":{"name":"310.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":85,"timestamp":839448980481,"duration":154,"tags":{"name":"676.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":86,"timestamp":839448980491,"duration":144,"tags":{"name":"840.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":87,"timestamp":839448980496,"duration":139,"tags":{"name":"984.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":88,"timestamp":839448980500,"duration":136,"tags":{"name":"201.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":89,"timestamp":839448980503,"duration":134,"tags":{"name":"837.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":90,"timestamp":839448980506,"duration":131,"tags":{"name":"2.js","cache":"HIT"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":70,"timestamp":839448976837,"duration":5677,"tags":{"name":"../app/_not-found.js","cache":"MISS"},"startTime":1704500736160},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":73,"timestamp":839448977750,"duration":5200,"tags":{"name":"../app/everyone-votes/terms/page.js","cache":"MISS"},"startTime":1704500736161},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":74,"timestamp":839448978424,"duration":4544,"tags":{"name":"../app/everyone-votes/privacy/page.js","cache":"MISS"},"startTime":1704500736162},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":91,"timestamp":839448980509,"duration":2985,"tags":{"name":"622.js","cache":"MISS"},"startTime":1704500736164},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":76,"timestamp":839448978748,"duration":5508,"tags":{"name":"../app/page.js","cache":"MISS"},"startTime":1704500736162},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":79,"timestamp":839448979236,"duration":7121,"tags":{"name":"../app/wiston/page.js","cache":"MISS"},"startTime":1704500736163},{"traceId":"4dea77cda8cb5b99","parentId":69,"name":"minify-js","id":77,"timestamp":839448979134,"duration":8483,"tags":{"name":"../app/space/page.js","cache":"MISS"},"startTime":1704500736163},{"traceId":"4dea77cda8cb5b99","parentId":17,"name":"terser-webpack-plugin-optimize","id":69,"timestamp":839448970055,"duration":17567,"tags":{"compilationName":"server","swcMinify":"true"},"startTime":1704500736154},{"traceId":"4dea77cda8cb5b99","parentId":17,"name":"css-minimizer-plugin","id":92,"timestamp":839448987703,"duration":99,"tags":{"webpackVersion":"5"},"startTime":1704500736171},{"traceId":"4dea77cda8cb5b99","parentId":18,"name":"create-trace-assets","id":93,"timestamp":839448987919,"duration":558,"tags":{},"startTime":1704500736172},{"traceId":"4dea77cda8cb5b99","parentId":17,"name":"seal","id":56,"timestamp":839448799280,"duration":195813,"tags":{},"startTime":1704500735983},{"traceId":"4dea77cda8cb5b99","parentId":14,"name":"webpack-compilation","id":17,"timestamp":839448142491,"duration":858524,"tags":{"name":"server"},"startTime":1704500735326},{"traceId":"4dea77cda8cb5b99","parentId":14,"name":"emit","id":94,"timestamp":839449001284,"duration":4897,"tags":{},"startTime":1704500736185},{"traceId":"4dea77cda8cb5b99","parentId":14,"name":"webpack-close","id":95,"timestamp":839449006525,"duration":492413,"tags":{"name":"server"},"startTime":1704500736190},{"traceId":"4dea77cda8cb5b99","parentId":95,"name":"webpack-generate-error-stats","id":96,"timestamp":839449498994,"duration":2250,"tags":{},"startTime":1704500736683},{"traceId":"4dea77cda8cb5b99","parentId":97,"name":"make","id":98,"timestamp":839449507833,"duration":135,"tags":{},"startTime":1704500736691},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"chunk-graph","id":100,"timestamp":839449508522,"duration":24,"tags":{},"startTime":1704500736692},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"optimize-modules","id":102,"timestamp":839449508580,"duration":6,"tags":{},"startTime":1704500736692},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"optimize-chunks","id":103,"timestamp":839449508625,"duration":54,"tags":{},"startTime":1704500736692},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"optimize-tree","id":104,"timestamp":839449508709,"duration":6,"tags":{},"startTime":1704500736692},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"optimize-chunk-modules","id":105,"timestamp":839449508763,"duration":47,"tags":{},"startTime":1704500736692},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"optimize","id":101,"timestamp":839449508555,"duration":282,"tags":{},"startTime":1704500736692},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"module-hash","id":106,"timestamp":839449508958,"duration":11,"tags":{},"startTime":1704500736693},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"code-generation","id":107,"timestamp":839449508976,"duration":9,"tags":{},"startTime":1704500736693},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"hash","id":108,"timestamp":839449509016,"duration":37,"tags":{},"startTime":1704500736693},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"code-generation-jobs","id":109,"timestamp":839449509054,"duration":24,"tags":{},"startTime":1704500736693},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"module-assets","id":110,"timestamp":839449509072,"duration":13,"tags":{},"startTime":1704500736693},{"traceId":"4dea77cda8cb5b99","parentId":99,"name":"create-chunk-assets","id":111,"timestamp":839449509089,"duration":9,"tags":{},"startTime":1704500736693},{"traceId":"4dea77cda8cb5b99","parentId":97,"name":"terser-webpack-plugin-optimize","id":112,"timestamp":839449510779,"duration":31,"tags":{"compilationName":"edge-server","swcMinify":"true"},"startTime":1704500736694},{"traceId":"4dea77cda8cb5b99","parentId":97,"name":"css-minimizer-plugin","id":113,"timestamp":839449510843,"duration":5,"tags":{"webpackVersion":"5"},"startTime":1704500736694},{"traceId":"4dea77cda8cb5b99","parentId":97,"name":"seal","id":99,"timestamp":839449508408,"duration":3731,"tags":{},"startTime":1704500736692},{"traceId":"4dea77cda8cb5b99","parentId":14,"name":"webpack-compilation","id":97,"timestamp":839449506723,"duration":5492,"tags":{"name":"edge-server"},"startTime":1704500736690},{"traceId":"4dea77cda8cb5b99","parentId":14,"name":"emit","id":114,"timestamp":839449512251,"duration":868,"tags":{},"startTime":1704500736696},{"traceId":"4dea77cda8cb5b99","parentId":14,"name":"webpack-close","id":115,"timestamp":839449513299,"duration":198,"tags":{"name":"edge-server"},"startTime":1704500736697},{"traceId":"4dea77cda8cb5b99","parentId":115,"name":"webpack-generate-error-stats","id":116,"timestamp":839449513502,"duration":630,"tags":{},"startTime":1704500736697},{"traceId":"4dea77cda8cb5b99","parentId":121,"name":"build-module-js&server=false!","id":133,"timestamp":839449536226,"duration":3877,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\next-flight-client-entry-loader.js?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Capp-router.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Cerror-boundary.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Clayout-router.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Cnot-found-boundary.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Crender-from-template-context.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Cstatic-generation-searchparams-bailout-provider.js&server=false!","layer":"app-pages-browser"},"startTime":1704500736720},{"traceId":"4dea77cda8cb5b99","parentId":126,"name":"build-module-scss&server=false!","id":134,"timestamp":839449540156,"duration":997,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\next-flight-client-entry-loader.js?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cfont%5Cgoogle%5Ctarget.css%3F%7B%22path%22%3A%22app%5C%5Clayout.tsx%22%2C%22import%22%3A%22Inter%22%2C%22arguments%22%3A%5B%7B%22subsets%22%3A%5B%22latin%22%5D%7D%5D%2C%22variableName%22%3A%22inter%22%7D&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cglobals.scss&server=false!","layer":"app-pages-browser"},"startTime":1704500736724},{"traceId":"4dea77cda8cb5b99","parentId":127,"name":"build-module-js?server=false!","id":135,"timestamp":839449541168,"duration":129,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\next-flight-client-entry-loader.js?server=false!","layer":"app-pages-browser"},"startTime":1704500736725},{"traceId":"4dea77cda8cb5b99","parentId":129,"name":"build-module-tsx&server=false!","id":136,"timestamp":839449541343,"duration":508,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\next-flight-client-entry-loader.js?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cpage.tsx&server=false!","layer":"app-pages-browser"},"startTime":1704500736725},{"traceId":"4dea77cda8cb5b99","parentId":130,"name":"build-module-tsx&server=false!","id":137,"timestamp":839449541866,"duration":625,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\next-flight-client-entry-loader.js?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cspace%5Cpage.tsx&server=false!","layer":"app-pages-browser"},"startTime":1704500736725},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":127,"timestamp":839449520798,"duration":21964,"tags":{"request":"next-flight-client-entry-loader?server=false!"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":128,"timestamp":839449520805,"duration":21962,"tags":{"request":"next-flight-client-entry-loader?server=false!"},"startTime":1704500736704}] +[{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":131,"timestamp":839449520812,"duration":23070,"tags":{"request":"next-flight-client-entry-loader?server=false!"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":132,"timestamp":839449520814,"duration":23073,"tags":{"request":"next-flight-client-entry-loader?server=false!"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":138,"name":"next-client-pages-loader","id":139,"timestamp":839449545085,"duration":102,"tags":{"absolutePagePath":"next/dist/client/components/not-found-error"},"startTime":1704500736729},{"traceId":"4dea77cda8cb5b99","parentId":122,"name":"build-module-js?absolutePagePath=next%2Fdist%2Fclient%2Fcomponents%2Fnot-found-error&page=%2F_not-found!","id":138,"timestamp":839449544345,"duration":2593,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\next-client-pages-loader.js?absolutePagePath=next%2Fdist%2Fclient%2Fcomponents%2Fnot-found-error&page=%2F_not-found!","layer":"app-pages-browser"},"startTime":1704500736728},{"traceId":"4dea77cda8cb5b99","parentId":140,"name":"next-client-pages-loader","id":141,"timestamp":839449547347,"duration":20,"tags":{"absolutePagePath":"next/dist/pages/_error"},"startTime":1704500736731},{"traceId":"4dea77cda8cb5b99","parentId":123,"name":"build-module-js?absolutePagePath=next%2Fdist%2Fpages%2F_error&page=%2F_error!","id":140,"timestamp":839449547000,"duration":815,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\next-client-pages-loader.js?absolutePagePath=next%2Fdist%2Fpages%2F_error&page=%2F_error!","layer":"null"},"startTime":1704500736731},{"traceId":"4dea77cda8cb5b99","parentId":142,"name":"next-client-pages-loader","id":143,"timestamp":839449548015,"duration":49,"tags":{"absolutePagePath":"next/dist/pages/_app"},"startTime":1704500736732},{"traceId":"4dea77cda8cb5b99","parentId":124,"name":"build-module-js?absolutePagePath=next%2Fdist%2Fpages%2F_app&page=%2F_app!","id":142,"timestamp":839449547919,"duration":520,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\next-client-pages-loader.js?absolutePagePath=next%2Fdist%2Fpages%2F_app&page=%2F_app!","layer":"null"},"startTime":1704500736732},{"traceId":"4dea77cda8cb5b99","parentId":151,"name":"next-swc-transform","id":152,"timestamp":839449552503,"duration":6877,"tags":{},"startTime":1704500736736},{"traceId":"4dea77cda8cb5b99","parentId":150,"name":"next-swc-loader","id":151,"timestamp":839449552451,"duration":6933,"tags":{},"startTime":1704500736736},{"traceId":"4dea77cda8cb5b99","parentId":120,"name":"build-module-js","id":150,"timestamp":839449551823,"duration":11583,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\app-next.js","layer":"app-pages-browser"},"startTime":1704500736735},{"traceId":"4dea77cda8cb5b99","parentId":148,"name":"next-swc-transform","id":149,"timestamp":839449550693,"duration":12737,"tags":{},"startTime":1704500736734},{"traceId":"4dea77cda8cb5b99","parentId":145,"name":"next-swc-loader","id":148,"timestamp":839449550642,"duration":12791,"tags":{},"startTime":1704500736734},{"traceId":"4dea77cda8cb5b99","parentId":119,"name":"build-module-js","id":145,"timestamp":839449550306,"duration":14595,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\next.js","layer":"null"},"startTime":1704500736734},{"traceId":"4dea77cda8cb5b99","parentId":146,"name":"next-swc-transform","id":147,"timestamp":839449550638,"duration":16091,"tags":{},"startTime":1704500736734},{"traceId":"4dea77cda8cb5b99","parentId":144,"name":"next-swc-loader","id":146,"timestamp":839449550416,"duration":16318,"tags":{},"startTime":1704500736734},{"traceId":"4dea77cda8cb5b99","parentId":125,"name":"build-module-js","id":144,"timestamp":839449549979,"duration":21754,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\router.js","layer":"null"},"startTime":1704500736734},{"traceId":"4dea77cda8cb5b99","parentId":159,"name":"next-swc-transform","id":160,"timestamp":839449553991,"duration":17761,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"next-swc-loader","id":159,"timestamp":839449553938,"duration":17816,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":133,"name":"build-module-js","id":153,"timestamp":839449553646,"duration":24223,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js","layer":"app-pages-browser"},"startTime":1704500736737},{"traceId":"4dea77cda8cb5b99","parentId":167,"name":"next-swc-transform","id":168,"timestamp":839449554177,"duration":23713,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":157,"name":"next-swc-loader","id":167,"timestamp":839449554102,"duration":23790,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":133,"name":"build-module-js","id":157,"timestamp":839449553804,"duration":24742,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js","layer":"app-pages-browser"},"startTime":1704500736737},{"traceId":"4dea77cda8cb5b99","parentId":169,"name":"next-swc-transform","id":170,"timestamp":839449554308,"duration":24256,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":158,"name":"next-swc-loader","id":169,"timestamp":839449554220,"duration":24346,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":133,"name":"build-module-js","id":158,"timestamp":839449553884,"duration":25262,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js","layer":"app-pages-browser"},"startTime":1704500736737},{"traceId":"4dea77cda8cb5b99","parentId":165,"name":"next-swc-transform","id":166,"timestamp":839449554101,"duration":25137,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":156,"name":"next-swc-loader","id":165,"timestamp":839449554070,"duration":25171,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":133,"name":"build-module-js","id":156,"timestamp":839449553777,"duration":27063,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js","layer":"app-pages-browser"},"startTime":1704500736737},{"traceId":"4dea77cda8cb5b99","parentId":161,"name":"next-swc-transform","id":162,"timestamp":839449554030,"duration":27018,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":154,"name":"next-swc-loader","id":161,"timestamp":839449553993,"duration":27058,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":133,"name":"build-module-js","id":154,"timestamp":839449553708,"duration":28973,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js","layer":"app-pages-browser"},"startTime":1704500736737},{"traceId":"4dea77cda8cb5b99","parentId":172,"name":"next-swc-transform","id":173,"timestamp":839449555174,"duration":27530,"tags":{},"startTime":1704500736739},{"traceId":"4dea77cda8cb5b99","parentId":171,"name":"next-swc-loader","id":172,"timestamp":839449555131,"duration":27575,"tags":{},"startTime":1704500736739},{"traceId":"4dea77cda8cb5b99","parentId":142,"name":"build-module-js","id":171,"timestamp":839449555057,"duration":28407,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\pages\\_app.js","layer":"null"},"startTime":1704500736739},{"traceId":"4dea77cda8cb5b99","parentId":163,"name":"next-swc-transform","id":164,"timestamp":839449554069,"duration":29413,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":155,"name":"next-swc-loader","id":163,"timestamp":839449554031,"duration":29453,"tags":{},"startTime":1704500736738},{"traceId":"4dea77cda8cb5b99","parentId":133,"name":"build-module-js","id":155,"timestamp":839449553746,"duration":33383,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js","layer":"app-pages-browser"},"startTime":1704500736737},{"traceId":"4dea77cda8cb5b99","parentId":176,"name":"next-swc-transform","id":177,"timestamp":839449555688,"duration":31458,"tags":{},"startTime":1704500736739},{"traceId":"4dea77cda8cb5b99","parentId":174,"name":"next-swc-loader","id":176,"timestamp":839449555660,"duration":31488,"tags":{},"startTime":1704500736739},{"traceId":"4dea77cda8cb5b99","parentId":138,"name":"build-module-js","id":174,"timestamp":839449555545,"duration":32234,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-error.js","layer":"app-pages-browser"},"startTime":1704500736739},{"traceId":"4dea77cda8cb5b99","parentId":178,"name":"next-swc-transform","id":179,"timestamp":839449555708,"duration":32089,"tags":{},"startTime":1704500736739},{"traceId":"4dea77cda8cb5b99","parentId":175,"name":"next-swc-loader","id":178,"timestamp":839449555690,"duration":32108,"tags":{},"startTime":1704500736739},{"traceId":"4dea77cda8cb5b99","parentId":140,"name":"build-module-js","id":175,"timestamp":839449555606,"duration":33001,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\pages\\_error.js","layer":"null"},"startTime":1704500736739},{"traceId":"4dea77cda8cb5b99","parentId":184,"name":"next-swc-transform","id":185,"timestamp":839449556200,"duration":32423,"tags":{},"startTime":1704500736740},{"traceId":"4dea77cda8cb5b99","parentId":181,"name":"next-swc-loader","id":184,"timestamp":839449556184,"duration":32441,"tags":{},"startTime":1704500736740},{"traceId":"4dea77cda8cb5b99","parentId":137,"name":"build-module-tsx","id":181,"timestamp":839449556094,"duration":33514,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx","layer":"app-pages-browser"},"startTime":1704500736740},{"traceId":"4dea77cda8cb5b99","parentId":182,"name":"next-swc-transform","id":183,"timestamp":839449556180,"duration":33454,"tags":{},"startTime":1704500736740},{"traceId":"4dea77cda8cb5b99","parentId":180,"name":"next-swc-loader","id":182,"timestamp":839449556136,"duration":33500,"tags":{},"startTime":1704500736740},{"traceId":"4dea77cda8cb5b99","parentId":136,"name":"build-module-tsx","id":180,"timestamp":839449555769,"duration":34765,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx","layer":"app-pages-browser"},"startTime":1704500736739},{"traceId":"4dea77cda8cb5b99","parentId":197,"name":"next-swc-transform","id":198,"timestamp":839449606028,"duration":2254,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":189,"name":"next-swc-loader","id":197,"timestamp":839449606017,"duration":2269,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":150,"name":"build-module-js","id":189,"timestamp":839449605825,"duration":3447,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\app-webpack.js","layer":"app-pages-browser"},"startTime":1704500736789},{"traceId":"4dea77cda8cb5b99","parentId":193,"name":"next-swc-transform","id":194,"timestamp":839449606003,"duration":3289,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":187,"name":"next-swc-loader","id":193,"timestamp":839449605988,"duration":3305,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":145,"name":"build-module-js","id":187,"timestamp":839449605779,"duration":4443,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\webpack.js","layer":"null"},"startTime":1704500736789},{"traceId":"4dea77cda8cb5b99","parentId":195,"name":"next-swc-transform","id":196,"timestamp":839449606016,"duration":4522,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":188,"name":"next-swc-loader","id":195,"timestamp":839449606004,"duration":4538,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":150,"name":"build-module-js","id":188,"timestamp":839449605801,"duration":5596,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\app-bootstrap.js","layer":"app-pages-browser"},"startTime":1704500736789},{"traceId":"4dea77cda8cb5b99","parentId":191,"name":"next-swc-transform","id":192,"timestamp":839449605987,"duration":7283,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":186,"name":"next-swc-loader","id":191,"timestamp":839449605955,"duration":7319,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":150,"name":"build-module-js","id":186,"timestamp":839449605715,"duration":9454,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\app-index.js","layer":"app-pages-browser"},"startTime":1704500736789},{"traceId":"4dea77cda8cb5b99","parentId":222,"name":"next-swc-transform","id":223,"timestamp":839449607396,"duration":7789,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":204,"name":"next-swc-loader","id":222,"timestamp":839449607375,"duration":7811,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":144,"name":"build-module-js","id":204,"timestamp":839449606839,"duration":8749,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\with-router.js","layer":"null"},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":199,"name":"next-swc-transform","id":200,"timestamp":839449606041,"duration":9562,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":190,"name":"next-swc-loader","id":199,"timestamp":839449606029,"duration":9575,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":171,"name":"build-module-js","id":190,"timestamp":839449605849,"duration":11716,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\utils.js","layer":"null"},"startTime":1704500736789},{"traceId":"4dea77cda8cb5b99","parentId":224,"name":"next-swc-transform","id":225,"timestamp":839449607412,"duration":10172,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":205,"name":"next-swc-loader","id":224,"timestamp":839449607397,"duration":10188,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":144,"name":"build-module-js","id":205,"timestamp":839449606884,"duration":10937,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router-context.shared-runtime.js","layer":"null"},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":226,"name":"next-swc-transform","id":227,"timestamp":839449607425,"duration":10411,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":206,"name":"next-swc-loader","id":226,"timestamp":839449607413,"duration":10424,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":206,"timestamp":839449606924,"duration":11569,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\add-base-path.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":228,"name":"next-swc-transform","id":229,"timestamp":839449607437,"duration":11071,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":207,"name":"next-swc-loader","id":228,"timestamp":839449607426,"duration":11084,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":207,"timestamp":839449606957,"duration":11938,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\has-base-path.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":230,"name":"next-swc-transform","id":231,"timestamp":839449607449,"duration":11460,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":208,"name":"next-swc-loader","id":230,"timestamp":839449607438,"duration":11472,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":208,"timestamp":839449606983,"duration":12339,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\remove-base-path.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":234,"name":"next-swc-transform","id":235,"timestamp":839449607475,"duration":11862,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":210,"name":"next-swc-loader","id":234,"timestamp":839449607462,"duration":11875,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":210,"timestamp":839449607040,"duration":12830,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.shared-runtime.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":236,"name":"next-swc-transform","id":237,"timestamp":839449607487,"duration":12409,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":211,"name":"next-swc-loader","id":236,"timestamp":839449607475,"duration":12422,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":211,"timestamp":839449607095,"duration":13637,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\use-reducer-with-devtools.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":238,"name":"next-swc-transform","id":239,"timestamp":839449607658,"duration":13090,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":212,"name":"next-swc-loader","id":238,"timestamp":839449607488,"duration":13261,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":212,"timestamp":839449607139,"duration":13871,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hooks-client-context.shared-runtime.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":232,"name":"next-swc-transform","id":233,"timestamp":839449607461,"duration":13563,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":209,"name":"next-swc-loader","id":232,"timestamp":839449607450,"duration":13576,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":175,"name":"build-module-js","id":209,"timestamp":839449607015,"duration":16696,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head.js","layer":"null"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":244,"name":"next-swc-transform","id":245,"timestamp":839449607697,"duration":16031,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":215,"name":"next-swc-loader","id":244,"timestamp":839449607686,"duration":16043,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":215,"timestamp":839449607208,"duration":16813,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\infinite-promise.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":240,"name":"next-swc-transform","id":241,"timestamp":839449607673,"duration":16363,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":213,"name":"next-swc-loader","id":240,"timestamp":839449607659,"duration":16378,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":213,"timestamp":839449607166,"duration":17498,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect-boundary.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":242,"name":"next-swc-transform","id":243,"timestamp":839449607685,"duration":16995,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":214,"name":"next-swc-loader","id":242,"timestamp":839449607674,"duration":17008,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":214,"timestamp":839449607188,"duration":18101,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router-announcer.js","layer":"app-pages-browser"},"startTime":1704500736791}] +[{"traceId":"4dea77cda8cb5b99","parentId":246,"name":"next-swc-transform","id":247,"timestamp":839449607709,"duration":17721,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":216,"name":"next-swc-loader","id":246,"timestamp":839449607698,"duration":17734,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":216,"timestamp":839449607227,"duration":18657,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router-headers.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":248,"name":"next-swc-transform","id":249,"timestamp":839449607721,"duration":18177,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":217,"name":"next-swc-loader","id":248,"timestamp":839449607710,"duration":18189,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":158,"name":"build-module-js","id":217,"timestamp":839449607245,"duration":18944,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\searchparams-bailout-proxy.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":250,"name":"next-swc-transform","id":251,"timestamp":839449607733,"duration":18763,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":218,"name":"next-swc-loader","id":250,"timestamp":839449607722,"duration":18777,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":155,"name":"build-module-js","id":218,"timestamp":839449607265,"duration":19705,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\match-segments.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":220,"name":"next-swc-transform","id":221,"timestamp":839449607372,"duration":23638,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"next-swc-loader","id":220,"timestamp":839449607335,"duration":23678,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":145,"name":"build-module-js","id":201,"timestamp":839449606629,"duration":29350,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\index.js","layer":"null"},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":252,"name":"next-swc-transform","id":253,"timestamp":839449607744,"duration":28252,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":219,"name":"next-swc-loader","id":252,"timestamp":839449607734,"duration":28264,"tags":{},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":156,"name":"build-module-js","id":219,"timestamp":839449607289,"duration":30043,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\navigation.js","layer":"app-pages-browser"},"startTime":1704500736791},{"traceId":"4dea77cda8cb5b99","parentId":255,"name":"next-swc-transform","id":256,"timestamp":839449613138,"duration":24210,"tags":{},"startTime":1704500736797},{"traceId":"4dea77cda8cb5b99","parentId":254,"name":"next-swc-loader","id":255,"timestamp":839449613110,"duration":24240,"tags":{},"startTime":1704500736797},{"traceId":"4dea77cda8cb5b99","parentId":181,"name":"build-module-js","id":254,"timestamp":839449612957,"duration":24901,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-dynamic.js","layer":"app-pages-browser"},"startTime":1704500736797},{"traceId":"4dea77cda8cb5b99","parentId":272,"name":"next-swc-transform","id":273,"timestamp":839449628392,"duration":9683,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":257,"name":"next-swc-loader","id":272,"timestamp":839449628368,"duration":9709,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":181,"name":"build-module-tsx","id":257,"timestamp":839449627918,"duration":10358,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\loading.tsx","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":276,"name":"next-swc-transform","id":277,"timestamp":839449628420,"duration":9869,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":259,"name":"next-swc-loader","id":276,"timestamp":839449628409,"duration":9882,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":180,"name":"build-module-tsx","id":259,"timestamp":839449627987,"duration":10575,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\Card.tsx","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":280,"name":"next-swc-transform","id":281,"timestamp":839449628446,"duration":10129,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":261,"name":"next-swc-loader","id":280,"timestamp":839449628434,"duration":10142,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":261,"timestamp":839449628023,"duration":10975,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\router-reducer-types.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":282,"name":"next-swc-transform","id":283,"timestamp":839449628457,"duration":10554,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":262,"name":"next-swc-loader","id":282,"timestamp":839449628446,"duration":10566,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":262,"timestamp":839449628041,"duration":11240,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\create-href-from-url.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":274,"name":"next-swc-transform","id":275,"timestamp":839449628408,"duration":10888,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":258,"name":"next-swc-loader","id":274,"timestamp":839449628393,"duration":10903,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":181,"name":"build-module-tsx","id":258,"timestamp":839449627963,"duration":12459,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\ParameterPanel.tsx","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":284,"name":"next-swc-transform","id":285,"timestamp":839449628469,"duration":13783,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":263,"name":"next-swc-loader","id":284,"timestamp":839449628458,"duration":13797,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":263,"timestamp":839449628059,"duration":14918,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\router-reducer.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":286,"name":"next-swc-transform","id":287,"timestamp":839449628482,"duration":14512,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":264,"name":"next-swc-loader","id":286,"timestamp":839449628470,"duration":14525,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":264,"timestamp":839449628076,"duration":15540,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\create-initial-router-state.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":290,"name":"next-swc-transform","id":291,"timestamp":839449628505,"duration":15126,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":266,"name":"next-swc-loader","id":290,"timestamp":839449628494,"duration":15139,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":155,"name":"build-module-js","id":266,"timestamp":839449628112,"duration":15815,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\create-router-cache-key.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":288,"name":"next-swc-transform","id":289,"timestamp":839449628493,"duration":15448,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":265,"name":"next-swc-loader","id":288,"timestamp":839449628482,"duration":15461,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":155,"name":"build-module-js","id":265,"timestamp":839449628094,"duration":16691,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\fetch-server-response.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":292,"name":"next-swc-transform","id":293,"timestamp":839449628517,"duration":16282,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":267,"name":"next-swc-loader","id":292,"timestamp":839449628506,"duration":16295,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":155,"name":"build-module-js","id":267,"timestamp":839449628129,"duration":16972,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\create-record-from-thenable.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":294,"name":"next-swc-transform","id":295,"timestamp":839449628529,"duration":16585,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":268,"name":"next-swc-loader","id":294,"timestamp":839449628518,"duration":16598,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":268,"timestamp":839449628147,"duration":18228,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\reducers\\find-head-in-cache.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":296,"name":"next-swc-transform","id":297,"timestamp":839449628541,"duration":17849,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":269,"name":"next-swc-loader","id":296,"timestamp":839449628530,"duration":17862,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":155,"name":"build-module-js","id":269,"timestamp":839449628164,"duration":18501,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\reducers\\get-segment-value.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":298,"name":"next-swc-transform","id":299,"timestamp":839449628554,"duration":18341,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":270,"name":"next-swc-loader","id":298,"timestamp":839449628542,"duration":18356,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":155,"name":"build-module-js","id":270,"timestamp":839449628182,"duration":18953,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\handle-smooth-scroll.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":300,"name":"next-swc-transform","id":301,"timestamp":839449628566,"duration":18689,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":271,"name":"next-swc-loader","id":300,"timestamp":839449628555,"duration":18702,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":271,"timestamp":839449628199,"duration":19660,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\is-bot.js","layer":"app-pages-browser"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":202,"name":"read-resource","id":203,"timestamp":839449606813,"duration":41912,"tags":{},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":144,"name":"build-module-js","id":202,"timestamp":839449606667,"duration":42481,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\lib\\is-error.js","layer":"null"},"startTime":1704500736790},{"traceId":"4dea77cda8cb5b99","parentId":278,"name":"next-swc-transform","id":279,"timestamp":839449628433,"duration":20989,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"next-swc-loader","id":278,"timestamp":839449628421,"duration":21004,"tags":{},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":144,"name":"build-module-js","id":260,"timestamp":839449628007,"duration":33286,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\router.js","layer":"null"},"startTime":1704500736812},{"traceId":"4dea77cda8cb5b99","parentId":319,"name":"next-swc-transform","id":320,"timestamp":839449677754,"duration":2807,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":306,"name":"next-swc-loader","id":319,"timestamp":839449677740,"duration":2826,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":306,"timestamp":839449677163,"duration":3850,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\remove-base-path.js","layer":"null"},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":323,"name":"next-swc-transform","id":324,"timestamp":839449677780,"duration":3247,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":308,"name":"next-swc-loader","id":323,"timestamp":839449677768,"duration":3261,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":308,"timestamp":839449677198,"duration":4192,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\app-router-context.shared-runtime.js","layer":"null"},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":321,"name":"next-swc-transform","id":322,"timestamp":839449677768,"duration":3637,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":307,"name":"next-swc-loader","id":321,"timestamp":839449677755,"duration":3651,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":307,"timestamp":839449677183,"duration":4555,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\has-base-path.js","layer":"null"},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":325,"name":"next-swc-transform","id":326,"timestamp":839449677793,"duration":4159,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":309,"name":"next-swc-loader","id":325,"timestamp":839449677781,"duration":4173,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":309,"timestamp":839449677214,"duration":4943,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\handle-smooth-scroll.js","layer":"null"},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":327,"name":"next-swc-transform","id":328,"timestamp":839449677805,"duration":6561,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":312,"name":"next-swc-loader","id":327,"timestamp":839449677794,"duration":6576,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":312,"timestamp":839449677514,"duration":7135,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hooks-client-context.shared-runtime.js","layer":"null"},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":317,"name":"next-swc-transform","id":318,"timestamp":839449677738,"duration":6936,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":305,"name":"next-swc-loader","id":317,"timestamp":839449677708,"duration":6968,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":181,"name":"build-module-tsx","id":305,"timestamp":839449677127,"duration":8315,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonScene.tsx","layer":"app-pages-browser"},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":335,"name":"next-swc-transform","id":336,"timestamp":839449683019,"duration":4135,"tags":{},"startTime":1704500736867},{"traceId":"4dea77cda8cb5b99","parentId":331,"name":"next-swc-loader","id":335,"timestamp":839449682993,"duration":4164,"tags":{},"startTime":1704500736867},{"traceId":"4dea77cda8cb5b99","parentId":186,"name":"build-module-js","id":331,"timestamp":839449682746,"duration":4771,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\app-call-server.js","layer":"app-pages-browser"},"startTime":1704500736866},{"traceId":"4dea77cda8cb5b99","parentId":337,"name":"next-swc-transform","id":338,"timestamp":839449683034,"duration":4498,"tags":{},"startTime":1704500736867},{"traceId":"4dea77cda8cb5b99","parentId":332,"name":"next-swc-loader","id":337,"timestamp":839449683021,"duration":4513,"tags":{},"startTime":1704500736867},{"traceId":"4dea77cda8cb5b99","parentId":186,"name":"build-module-js","id":332,"timestamp":839449682782,"duration":5062,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\on-recoverable-error.js","layer":"app-pages-browser"},"startTime":1704500736866},{"traceId":"4dea77cda8cb5b99","parentId":341,"name":"next-swc-transform","id":342,"timestamp":839449683060,"duration":4798,"tags":{},"startTime":1704500736867},{"traceId":"4dea77cda8cb5b99","parentId":334,"name":"next-swc-loader","id":341,"timestamp":839449683048,"duration":4810,"tags":{},"startTime":1704500736867},{"traceId":"4dea77cda8cb5b99","parentId":206,"name":"build-module-js","id":334,"timestamp":839449682822,"duration":5515,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\normalize-trailing-slash.js","layer":"app-pages-browser"},"startTime":1704500736866},{"traceId":"4dea77cda8cb5b99","parentId":339,"name":"next-swc-transform","id":340,"timestamp":839449683047,"duration":5303,"tags":{},"startTime":1704500736867},{"traceId":"4dea77cda8cb5b99","parentId":333,"name":"next-swc-loader","id":339,"timestamp":839449683035,"duration":5316,"tags":{},"startTime":1704500736867},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":333,"timestamp":839449682804,"duration":5862,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\on-recoverable-error.js","layer":"null"},"startTime":1704500736866},{"traceId":"4dea77cda8cb5b99","parentId":356,"name":"next-swc-transform","id":357,"timestamp":839449689472,"duration":3238,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":344,"name":"next-swc-loader","id":356,"timestamp":839449689458,"duration":3257,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":209,"name":"build-module-js","id":344,"timestamp":839449689086,"duration":3896,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head-manager-context.shared-runtime.js","layer":"null"},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":354,"name":"next-swc-transform","id":355,"timestamp":839449689456,"duration":3541,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":343,"name":"next-swc-loader","id":354,"timestamp":839449689429,"duration":3569,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":186,"name":"build-module-js","id":343,"timestamp":839449689040,"duration":4154,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head-manager-context.shared-runtime.js","layer":"app-pages-browser"},"startTime":1704500736873}] +[{"traceId":"4dea77cda8cb5b99","parentId":358,"name":"next-swc-transform","id":359,"timestamp":839449689486,"duration":3828,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":345,"name":"next-swc-loader","id":358,"timestamp":839449689473,"duration":3843,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":186,"name":"build-module-js","id":345,"timestamp":839449689109,"duration":4585,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\is-next-router-error.js","layer":"app-pages-browser"},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":360,"name":"next-swc-transform","id":361,"timestamp":839449689499,"duration":4213,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":346,"name":"next-swc-loader","id":360,"timestamp":839449689487,"duration":4228,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":209,"name":"build-module-js","id":346,"timestamp":839449689130,"duration":5097,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\side-effect.js","layer":"null"},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":362,"name":"next-swc-transform","id":363,"timestamp":839449689511,"duration":4731,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":347,"name":"next-swc-loader","id":362,"timestamp":839449689500,"duration":4743,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":209,"name":"build-module-js","id":347,"timestamp":839449689145,"duration":5298,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\amp-context.shared-runtime.js","layer":"null"},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":368,"name":"next-swc-transform","id":369,"timestamp":839449689547,"duration":4911,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":350,"name":"next-swc-loader","id":368,"timestamp":839449689536,"duration":4924,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":209,"name":"build-module-js","id":350,"timestamp":839449689201,"duration":5507,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\amp-mode.js","layer":"null"},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":366,"name":"next-swc-transform","id":367,"timestamp":839449689535,"duration":5188,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":349,"name":"next-swc-loader","id":366,"timestamp":839449689524,"duration":5201,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":217,"name":"build-module-js","id":349,"timestamp":839449689181,"duration":6366,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-bailout.js","layer":"app-pages-browser"},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":364,"name":"next-swc-transform","id":365,"timestamp":839449689523,"duration":6041,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":348,"name":"next-swc-loader","id":364,"timestamp":839449689512,"duration":6054,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":213,"name":"build-module-js","id":348,"timestamp":839449689162,"duration":7175,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\redirect.js","layer":"app-pages-browser"},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":313,"name":"read-resource","id":314,"timestamp":839449677560,"duration":19799,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":189,"name":"build-module-js","id":313,"timestamp":839449677545,"duration":20781,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\deployment-id.js","layer":"app-pages-browser"},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":315,"name":"read-resource","id":316,"timestamp":839449677583,"duration":20750,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":187,"name":"build-module-js","id":315,"timestamp":839449677570,"duration":21062,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\deployment-id.js","layer":"null"},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":310,"name":"read-resource","id":311,"timestamp":839449677494,"duration":21263,"tags":{},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":180,"name":"build-module-js","id":310,"timestamp":839449677229,"duration":21812,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\react\\jsx-runtime.js","layer":"app-pages-browser"},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":370,"name":"next-swc-transform","id":371,"timestamp":839449689559,"duration":10069,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":351,"name":"next-swc-loader","id":370,"timestamp":839449689548,"duration":10084,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":206,"name":"build-module-js","id":351,"timestamp":839449689220,"duration":10922,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\add-path-prefix.js","layer":"app-pages-browser"},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":372,"name":"next-swc-transform","id":373,"timestamp":839449689571,"duration":10680,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":352,"name":"next-swc-loader","id":372,"timestamp":839449689560,"duration":10694,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":207,"name":"build-module-js","id":352,"timestamp":839449689238,"duration":11392,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\path-has-prefix.js","layer":"app-pages-browser"},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module","id":436,"timestamp":839449704159,"duration":187,"tags":{"name":"undefined","layer":"null"},"startTime":1704500736888},{"traceId":"4dea77cda8cb5b99","parentId":439,"name":"read-resource","id":440,"timestamp":839449718392,"duration":7,"tags":{},"startTime":1704500736902},{"traceId":"4dea77cda8cb5b99","parentId":398,"name":"next-swc-transform","id":399,"timestamp":839449691882,"duration":153507,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":377,"name":"next-swc-loader","id":398,"timestamp":839449691868,"duration":153530,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":377,"timestamp":839449691448,"duration":154801,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\mitt.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":400,"name":"next-swc-transform","id":401,"timestamp":839449691896,"duration":154372,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":378,"name":"next-swc-loader","id":400,"timestamp":839449691883,"duration":154387,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":378,"timestamp":839449691469,"duration":156368,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\performance-relayer.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":374,"name":"next-swc-transform","id":375,"timestamp":839449689583,"duration":158270,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":353,"name":"next-swc-loader","id":374,"timestamp":839449689572,"duration":158284,"tags":{},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":353,"timestamp":839449689256,"duration":165814,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\head-manager.js","layer":"null"},"startTime":1704500736873},{"traceId":"4dea77cda8cb5b99","parentId":396,"name":"next-swc-transform","id":397,"timestamp":839449691867,"duration":163223,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":376,"name":"next-swc-loader","id":396,"timestamp":839449691841,"duration":163250,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":376,"timestamp":839449691405,"duration":165433,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\page-loader.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":404,"name":"next-swc-transform","id":405,"timestamp":839449691920,"duration":164934,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":380,"name":"next-swc-loader","id":404,"timestamp":839449691909,"duration":164947,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":380,"timestamp":839449691501,"duration":165716,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\runtime-config.external.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":402,"name":"next-swc-transform","id":403,"timestamp":839449691908,"duration":165327,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":379,"name":"next-swc-loader","id":402,"timestamp":839449691896,"duration":165340,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":379,"timestamp":839449691486,"duration":166605,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\route-announcer.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":406,"name":"next-swc-transform","id":407,"timestamp":839449691932,"duration":166174,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":381,"name":"next-swc-loader","id":406,"timestamp":839449691921,"duration":166187,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":381,"timestamp":839449691515,"duration":166860,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\image-config-context.shared-runtime.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":410,"name":"next-swc-transform","id":411,"timestamp":839449691959,"duration":166430,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":383,"name":"next-swc-loader","id":410,"timestamp":839449691945,"duration":166445,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":383,"timestamp":839449691560,"duration":167605,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\querystring.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":412,"name":"next-swc-transform","id":413,"timestamp":839449691971,"duration":167208,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":384,"name":"next-swc-loader","id":412,"timestamp":839449691960,"duration":167221,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":384,"timestamp":839449691586,"duration":167875,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\is-dynamic.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":408,"name":"next-swc-transform","id":409,"timestamp":839449691944,"duration":167533,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":382,"name":"next-swc-loader","id":408,"timestamp":839449691933,"duration":167546,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":382,"timestamp":839449691536,"duration":168840,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\adapters.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":414,"name":"next-swc-transform","id":415,"timestamp":839449691983,"duration":168408,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":385,"name":"next-swc-loader","id":414,"timestamp":839449691972,"duration":168421,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":219,"name":"build-module-js","id":385,"timestamp":839449691620,"duration":169203,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\client-hook-in-server-component-error.js","layer":"app-pages-browser"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":416,"name":"next-swc-transform","id":417,"timestamp":839449691995,"duration":168853,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":386,"name":"next-swc-loader","id":416,"timestamp":839449691984,"duration":168867,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":219,"name":"build-module-js","id":386,"timestamp":839449691658,"duration":169718,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found.js","layer":"app-pages-browser"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":418,"name":"next-swc-transform","id":419,"timestamp":839449692007,"duration":169386,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":387,"name":"next-swc-loader","id":418,"timestamp":839449691996,"duration":169398,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":219,"name":"build-module-js","id":387,"timestamp":839449691681,"duration":170082,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\server-inserted-html.shared-runtime.js","layer":"app-pages-browser"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":422,"name":"next-swc-transform","id":423,"timestamp":839449692031,"duration":169748,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":389,"name":"next-swc-loader","id":422,"timestamp":839449692020,"duration":169760,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":389,"timestamp":839449691720,"duration":170470,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\add-base-path.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":424,"name":"next-swc-transform","id":425,"timestamp":839449692043,"duration":170187,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":390,"name":"next-swc-loader","id":424,"timestamp":839449692032,"duration":170200,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":390,"timestamp":839449691735,"duration":170856,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\is-bot.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":426,"name":"next-swc-transform","id":427,"timestamp":839449692055,"duration":170549,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":395,"name":"next-swc-loader","id":426,"timestamp":839449692044,"duration":170562,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":209,"name":"build-module-js","id":395,"timestamp":839449691785,"duration":171008,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\utils\\warn-once.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":420,"name":"next-swc-transform","id":421,"timestamp":839449692019,"duration":171167,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":388,"name":"next-swc-loader","id":420,"timestamp":839449692008,"duration":171181,"tags":{},"startTime":1704500736876},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":388,"timestamp":839449691700,"duration":173456,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\script.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":329,"name":"read-resource","id":330,"timestamp":839449682728,"duration":182619,"tags":{},"startTime":1704500736866},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":329,"timestamp":839449682698,"duration":182848,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\react\\index.js","layer":"app-pages-browser"},"startTime":1704500736866},{"traceId":"4dea77cda8cb5b99","parentId":443,"name":"next-swc-transform","id":444,"timestamp":839449843806,"duration":21791,"tags":{},"startTime":1704500737027},{"traceId":"4dea77cda8cb5b99","parentId":433,"name":"next-swc-loader","id":443,"timestamp":839449843789,"duration":21811,"tags":{},"startTime":1704500737027},{"traceId":"4dea77cda8cb5b99","parentId":263,"name":"build-module-js","id":433,"timestamp":839449704076,"duration":161944,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\reducers\\restore-reducer.js","layer":"app-pages-browser"},"startTime":1704500736888},{"traceId":"4dea77cda8cb5b99","parentId":445,"name":"next-swc-transform","id":446,"timestamp":839449843821,"duration":22215,"tags":{},"startTime":1704500737027},{"traceId":"4dea77cda8cb5b99","parentId":434,"name":"next-swc-loader","id":445,"timestamp":839449843807,"duration":22230,"tags":{},"startTime":1704500737027},{"traceId":"4dea77cda8cb5b99","parentId":263,"name":"build-module-js","id":434,"timestamp":839449704099,"duration":162649,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\reducers\\server-patch-reducer.js","layer":"app-pages-browser"},"startTime":1704500736888},{"traceId":"4dea77cda8cb5b99","parentId":449,"name":"read-resource","id":450,"timestamp":839449868299,"duration":488,"tags":{},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":447,"name":"next-swc-transform","id":448,"timestamp":839449843836,"duration":62300,"tags":{},"startTime":1704500737027},{"traceId":"4dea77cda8cb5b99","parentId":435,"name":"next-swc-loader","id":447,"timestamp":839449843822,"duration":62322,"tags":{},"startTime":1704500737027},{"traceId":"4dea77cda8cb5b99","parentId":263,"name":"build-module-js","id":435,"timestamp":839449704118,"duration":203135,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\reducers\\refresh-reducer.js","layer":"app-pages-browser"},"startTime":1704500736888},{"traceId":"4dea77cda8cb5b99","parentId":441,"name":"next-swc-transform","id":442,"timestamp":839449843785,"duration":63646,"tags":{},"startTime":1704500737027},{"traceId":"4dea77cda8cb5b99","parentId":432,"name":"next-swc-loader","id":441,"timestamp":839449843728,"duration":63706,"tags":{},"startTime":1704500737027},{"traceId":"4dea77cda8cb5b99","parentId":263,"name":"build-module-js","id":432,"timestamp":839449704043,"duration":205138,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\reducers\\navigate-reducer.js","layer":"app-pages-browser"},"startTime":1704500736888},{"traceId":"4dea77cda8cb5b99","parentId":472,"name":"next-swc-transform","id":473,"timestamp":839449873996,"duration":35398,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":451,"name":"next-swc-loader","id":472,"timestamp":839449873960,"duration":35438,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":307,"name":"build-module-js","id":451,"timestamp":839449868308,"duration":41333,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\path-has-prefix.js","layer":"null"},"startTime":1704500737052}] +[{"traceId":"4dea77cda8cb5b99","parentId":478,"name":"next-swc-transform","id":479,"timestamp":839449874040,"duration":35755,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":458,"name":"next-swc-loader","id":478,"timestamp":839449874028,"duration":35769,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":202,"name":"build-module-js","id":458,"timestamp":839449868443,"duration":41607,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\is-plain-object.js","layer":"null"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":474,"name":"next-swc-transform","id":475,"timestamp":839449874014,"duration":36050,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":456,"name":"next-swc-loader","id":474,"timestamp":839449874000,"duration":36066,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":456,"timestamp":839449868403,"duration":41961,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\tracing\\report-to-socket.js","layer":"null"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":476,"name":"next-swc-transform","id":477,"timestamp":839449874027,"duration":36352,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":457,"name":"next-swc-loader","id":476,"timestamp":839449874015,"duration":36366,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":457,"timestamp":839449868425,"duration":42459,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\tracing\\tracer.js","layer":"null"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":480,"name":"next-swc-transform","id":481,"timestamp":839449874053,"duration":36846,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":461,"name":"next-swc-loader","id":480,"timestamp":839449874041,"duration":36859,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":265,"name":"build-module-js","id":461,"timestamp":839449868477,"duration":42699,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\hash.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":482,"name":"next-swc-transform","id":483,"timestamp":839449874066,"duration":37124,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":462,"name":"next-swc-loader","id":482,"timestamp":839449874054,"duration":37138,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":264,"name":"build-module-js","id":462,"timestamp":839449868551,"duration":43153,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\fill-lazy-items-till-leaf-with-head.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":484,"name":"next-swc-transform","id":485,"timestamp":839449874080,"duration":37640,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":463,"name":"next-swc-loader","id":484,"timestamp":839449874067,"duration":37653,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":264,"name":"build-module-js","id":463,"timestamp":839449868575,"duration":43908,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\compute-changed-path.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":486,"name":"next-swc-transform","id":487,"timestamp":839449874093,"duration":38405,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":464,"name":"next-swc-loader","id":486,"timestamp":839449874081,"duration":38418,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":263,"name":"build-module-js","id":464,"timestamp":839449868596,"duration":44423,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\reducers\\prefetch-reducer.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":492,"name":"next-swc-transform","id":493,"timestamp":839449874164,"duration":38869,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":467,"name":"next-swc-loader","id":492,"timestamp":839449874120,"duration":38915,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":467,"timestamp":839449868657,"duration":44663,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\remove-trailing-slash.js","layer":"null"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":488,"name":"next-swc-transform","id":489,"timestamp":839449874106,"duration":39231,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":465,"name":"next-swc-loader","id":488,"timestamp":839449874094,"duration":39243,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":263,"name":"build-module-js","id":465,"timestamp":839449868616,"duration":45392,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\reducers\\fast-refresh-reducer.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":494,"name":"next-swc-transform","id":495,"timestamp":839449874180,"duration":40416,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":468,"name":"next-swc-loader","id":494,"timestamp":839449874166,"duration":40433,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":334,"name":"build-module-js","id":468,"timestamp":839449868710,"duration":46080,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\remove-trailing-slash.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":496,"name":"next-swc-transform","id":497,"timestamp":839449874193,"duration":40611,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":471,"name":"next-swc-loader","id":496,"timestamp":839449874181,"duration":40624,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":254,"name":"build-module-js","id":471,"timestamp":839449868763,"duration":46335,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\loadable.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":490,"name":"next-swc-transform","id":491,"timestamp":839449874119,"duration":41000,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":466,"name":"next-swc-loader","id":490,"timestamp":839449874107,"duration":41015,"tags":{},"startTime":1704500737058},{"traceId":"4dea77cda8cb5b99","parentId":263,"name":"build-module-js","id":466,"timestamp":839449868636,"duration":48065,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\reducers\\server-action-reducer.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":391,"name":"read-resource","id":392,"timestamp":839449691760,"duration":227880,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":186,"name":"build-module-js","id":391,"timestamp":839449691749,"duration":228454,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\polyfills\\polyfill-module.js","layer":"app-pages-browser"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":393,"name":"read-resource","id":394,"timestamp":839449691783,"duration":228438,"tags":{},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":393,"timestamp":839449691772,"duration":228864,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\polyfills\\polyfill-module.js","layer":"null"},"startTime":1704500736875},{"traceId":"4dea77cda8cb5b99","parentId":498,"name":"postcss-process","id":500,"timestamp":839450080855,"duration":194630,"tags":{},"startTime":1704500737264},{"traceId":"4dea77cda8cb5b99","parentId":499,"name":"postcss-process","id":501,"timestamp":839450098897,"duration":176595,"tags":{},"startTime":1704500737282},{"traceId":"4dea77cda8cb5b99","parentId":439,"name":"postcss-loader","id":498,"timestamp":839450080754,"duration":194880,"tags":{},"startTime":1704500737264},{"traceId":"4dea77cda8cb5b99","parentId":449,"name":"postcss-loader","id":499,"timestamp":839450080850,"duration":194786,"tags":{},"startTime":1704500737264},{"traceId":"4dea77cda8cb5b99","parentId":439,"name":"css-loader","id":502,"timestamp":839450275777,"duration":21399,"tags":{"astUsed":"true"},"startTime":1704500737459},{"traceId":"4dea77cda8cb5b99","parentId":449,"name":"css-loader","id":503,"timestamp":839450275990,"duration":22890,"tags":{"astUsed":"true"},"startTime":1704500737460},{"traceId":"4dea77cda8cb5b99","parentId":428,"name":"read-resource","id":429,"timestamp":839449703998,"duration":598006,"tags":{},"startTime":1704500736888},{"traceId":"4dea77cda8cb5b99","parentId":218,"name":"build-module-js","id":428,"timestamp":839449703972,"duration":598381,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\server\\app-render\\get-segment-param.js","layer":"app-pages-browser"},"startTime":1704500736888},{"traceId":"4dea77cda8cb5b99","parentId":437,"name":"read-resource","id":438,"timestamp":839449706194,"duration":596171,"tags":{},"startTime":1704500736890},{"traceId":"4dea77cda8cb5b99","parentId":430,"name":"read-resource","id":431,"timestamp":839449704030,"duration":620327,"tags":{},"startTime":1704500736888},{"traceId":"4dea77cda8cb5b99","parentId":259,"name":"build-module-js","id":430,"timestamp":839449704015,"duration":620486,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\image.js","layer":"app-pages-browser"},"startTime":1704500736888},{"traceId":"4dea77cda8cb5b99","parentId":459,"name":"read-resource","id":460,"timestamp":839449868468,"duration":459477,"tags":{},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":265,"name":"build-module-js","id":459,"timestamp":839449868459,"duration":460942,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\lib\\constants.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":452,"name":"read-resource","id":453,"timestamp":839449868356,"duration":461057,"tags":{},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":452,"timestamp":839449868343,"duration":461380,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\react-dom\\client.js","layer":"null"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":469,"name":"read-resource","id":470,"timestamp":839449868748,"duration":460987,"tags":{},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":186,"name":"build-module-js","id":469,"timestamp":839449868737,"duration":461281,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\react-dom\\client.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":454,"name":"read-resource","id":455,"timestamp":839449868391,"duration":461805,"tags":{},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":155,"name":"build-module-js","id":454,"timestamp":839449868377,"duration":462141,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\react-dom\\index.js","layer":"app-pages-browser"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":534,"name":"next-swc-transform","id":535,"timestamp":839450332375,"duration":4179,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":508,"name":"next-swc-loader","id":534,"timestamp":839450332363,"duration":4196,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":508,"timestamp":839450331826,"duration":5347,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\route-matcher.js","layer":"null"},"startTime":1704500737515},{"traceId":"4dea77cda8cb5b99","parentId":532,"name":"next-swc-transform","id":533,"timestamp":839450332362,"duration":4851,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":507,"name":"next-swc-loader","id":532,"timestamp":839450332347,"duration":4869,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":507,"timestamp":839450331800,"duration":5837,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\parse-relative-url.js","layer":"null"},"startTime":1704500737515},{"traceId":"4dea77cda8cb5b99","parentId":538,"name":"next-swc-transform","id":539,"timestamp":839450332405,"duration":5252,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":512,"name":"next-swc-loader","id":538,"timestamp":839450332391,"duration":5267,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":512,"timestamp":839450331894,"duration":6113,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\page-path\\denormalize-page-path.js","layer":"null"},"startTime":1704500737515},{"traceId":"4dea77cda8cb5b99","parentId":536,"name":"next-swc-transform","id":537,"timestamp":839450332390,"duration":5633,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":509,"name":"next-swc-loader","id":536,"timestamp":839450332376,"duration":5648,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":258,"name":"build-module-tsx","id":509,"timestamp":839450331843,"duration":7579,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\BabylonInteractivity.tsx","layer":"app-pages-browser"},"startTime":1704500737515},{"traceId":"4dea77cda8cb5b99","parentId":540,"name":"next-swc-transform","id":541,"timestamp":839450332417,"duration":9074,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":513,"name":"next-swc-loader","id":540,"timestamp":839450332406,"duration":9089,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":513,"timestamp":839450331914,"duration":10655,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\resolve-href.js","layer":"null"},"startTime":1704500737515},{"traceId":"4dea77cda8cb5b99","parentId":542,"name":"next-swc-transform","id":543,"timestamp":839450332430,"duration":10171,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":516,"name":"next-swc-loader","id":542,"timestamp":839450332418,"duration":10189,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":516,"timestamp":839450331951,"duration":11609,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\bloom-filter.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":530,"name":"next-swc-transform","id":531,"timestamp":839450332345,"duration":11233,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":506,"name":"next-swc-loader","id":530,"timestamp":839450332310,"duration":11270,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":506,"timestamp":839450331741,"duration":14608,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\route-loader.js","layer":"null"},"startTime":1704500737515},{"traceId":"4dea77cda8cb5b99","parentId":546,"name":"next-swc-transform","id":547,"timestamp":839450332454,"duration":13911,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":518,"name":"next-swc-loader","id":546,"timestamp":839450332444,"duration":13923,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":518,"timestamp":839450331991,"duration":14751,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\detect-domain-locale.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":544,"name":"next-swc-transform","id":545,"timestamp":839450332443,"duration":14315,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":517,"name":"next-swc-loader","id":544,"timestamp":839450332431,"duration":14329,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":517,"timestamp":839450331975,"duration":15821,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\route-regex.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":548,"name":"next-swc-transform","id":549,"timestamp":839450332467,"duration":15345,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":519,"name":"next-swc-loader","id":548,"timestamp":839450332455,"duration":15358,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":519,"timestamp":839450332021,"duration":18230,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\get-next-pathname-info.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":550,"name":"next-swc-transform","id":551,"timestamp":839450332479,"duration":17788,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":520,"name":"next-swc-loader","id":550,"timestamp":839450332468,"duration":17800,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":520,"timestamp":839450332041,"duration":18671,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\add-locale.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":556,"name":"next-swc-transform","id":557,"timestamp":839450332514,"duration":18212,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":523,"name":"next-swc-loader","id":556,"timestamp":839450332503,"duration":18225,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":334,"name":"build-module-js","id":523,"timestamp":839450332086,"duration":18906,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\parse-path.js","layer":"app-pages-browser"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":552,"name":"next-swc-transform","id":553,"timestamp":839450332491,"duration":18516,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":521,"name":"next-swc-loader","id":552,"timestamp":839450332480,"duration":18529,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":521,"timestamp":839450332056,"duration":19267,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\format-next-pathname-info.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":554,"name":"next-swc-transform","id":555,"timestamp":839450332503,"duration":18834,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":522,"name":"next-swc-loader","id":554,"timestamp":839450332491,"duration":18846,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":522,"timestamp":839450332070,"duration":19487,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\parse-path.js","layer":"null"},"startTime":1704500737516}] +[{"traceId":"4dea77cda8cb5b99","parentId":558,"name":"next-swc-transform","id":559,"timestamp":839450332526,"duration":19185,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":524,"name":"next-swc-loader","id":558,"timestamp":839450332515,"duration":19197,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":524,"timestamp":839450332105,"duration":19904,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\compare-states.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":560,"name":"next-swc-transform","id":561,"timestamp":839450332538,"duration":19484,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":525,"name":"next-swc-loader","id":560,"timestamp":839450332527,"duration":19496,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":525,"timestamp":839450332119,"duration":20149,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\is-local-url.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":562,"name":"next-swc-transform","id":563,"timestamp":839450332550,"duration":19732,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":526,"name":"next-swc-loader","id":562,"timestamp":839450332539,"duration":19745,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":526,"timestamp":839450332135,"duration":20533,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\remove-locale.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":568,"name":"next-swc-transform","id":569,"timestamp":839450332587,"duration":20095,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":529,"name":"next-swc-loader","id":568,"timestamp":839450332575,"duration":20108,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":529,"timestamp":839450332191,"duration":20669,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\omit.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":564,"name":"next-swc-transform","id":565,"timestamp":839450332563,"duration":20964,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":527,"name":"next-swc-loader","id":564,"timestamp":839450332551,"duration":20978,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":527,"timestamp":839450332151,"duration":22116,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\format-url.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":566,"name":"next-swc-transform","id":567,"timestamp":839450332575,"duration":21707,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":528,"name":"next-swc-loader","id":566,"timestamp":839450332563,"duration":21720,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":528,"timestamp":839450332175,"duration":22535,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\interpolate-as.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":595,"name":"next-swc-transform","id":596,"timestamp":839450340317,"duration":14447,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":572,"name":"next-swc-loader","id":595,"timestamp":839450340290,"duration":14476,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":572,"timestamp":839450339724,"duration":15271,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\i18n\\normalize-locale-path.js","layer":"null"},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":599,"name":"next-swc-transform","id":600,"timestamp":839450340346,"duration":14664,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":574,"name":"next-swc-loader","id":599,"timestamp":839450340334,"duration":14677,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":389,"name":"build-module-js","id":574,"timestamp":839450339787,"duration":15440,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\add-path-prefix.js","layer":"null"},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":601,"name":"next-swc-transform","id":602,"timestamp":839450340358,"duration":14883,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":575,"name":"next-swc-loader","id":601,"timestamp":839450340347,"duration":14896,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":332,"name":"build-module-js","id":575,"timestamp":839450339806,"duration":15652,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\no-ssr-error.js","layer":"app-pages-browser"},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":597,"name":"next-swc-transform","id":598,"timestamp":839450340333,"duration":19520,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":573,"name":"next-swc-loader","id":597,"timestamp":839450340319,"duration":19537,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":389,"name":"build-module-js","id":573,"timestamp":839450339759,"duration":20559,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\normalize-trailing-slash.js","layer":"null"},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":605,"name":"next-swc-transform","id":606,"timestamp":839450340383,"duration":19951,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":577,"name":"next-swc-loader","id":605,"timestamp":839450340371,"duration":19964,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":349,"name":"build-module-js","id":577,"timestamp":839450339845,"duration":20873,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\hooks-server-context.js","layer":"app-pages-browser"},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":603,"name":"next-swc-transform","id":604,"timestamp":839450340370,"duration":20363,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":576,"name":"next-swc-loader","id":603,"timestamp":839450340359,"duration":20375,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":333,"name":"build-module-js","id":576,"timestamp":839450339829,"duration":21166,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\no-ssr-error.js","layer":"null"},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":607,"name":"next-swc-transform","id":608,"timestamp":839450340395,"duration":20620,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":578,"name":"next-swc-loader","id":607,"timestamp":839450340384,"duration":20634,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":349,"name":"build-module-js","id":578,"timestamp":839450339865,"duration":21422,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-async-storage.external.js","layer":"shared"},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":609,"name":"next-swc-transform","id":610,"timestamp":839450340407,"duration":20894,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":579,"name":"next-swc-loader","id":609,"timestamp":839450340396,"duration":20906,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":349,"name":"build-module-js","id":579,"timestamp":839450339885,"duration":21716,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\maybe-postpone.js","layer":"app-pages-browser"},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":611,"name":"next-swc-transform","id":612,"timestamp":839450340419,"duration":21196,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":580,"name":"next-swc-loader","id":611,"timestamp":839450340408,"duration":21208,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":348,"name":"build-module-js","id":580,"timestamp":839450339904,"duration":21937,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\request-async-storage.external.js","layer":"shared"},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":617,"name":"next-swc-transform","id":618,"timestamp":839450340454,"duration":21400,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":587,"name":"next-swc-loader","id":617,"timestamp":839450340443,"duration":21412,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":381,"name":"build-module-js","id":587,"timestamp":839450339999,"duration":22119,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\image-config.js","layer":"null"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":615,"name":"next-swc-transform","id":616,"timestamp":839450340443,"duration":21689,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":586,"name":"next-swc-loader","id":615,"timestamp":839450340432,"duration":21701,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":201,"name":"build-module-js","id":586,"timestamp":839450339978,"duration":22480,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\portal\\index.js","layer":"null"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":619,"name":"next-swc-transform","id":620,"timestamp":839450340467,"duration":22005,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":588,"name":"next-swc-loader","id":619,"timestamp":839450340455,"duration":22018,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":376,"name":"build-module-js","id":588,"timestamp":839450340016,"duration":22653,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\get-asset-path-from-route.js","layer":"null"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":621,"name":"next-swc-transform","id":622,"timestamp":839450340478,"duration":22204,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":589,"name":"next-swc-loader","id":621,"timestamp":839450340467,"duration":22216,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":382,"name":"build-module-js","id":589,"timestamp":839450340038,"duration":22807,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\as-path-to-search-params.js","layer":"null"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":623,"name":"next-swc-transform","id":624,"timestamp":839450340490,"duration":22368,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":590,"name":"next-swc-loader","id":623,"timestamp":839450340479,"duration":22380,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":434,"name":"build-module-js","id":590,"timestamp":839450340052,"duration":23197,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\apply-flight-data.js","layer":"app-pages-browser"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":625,"name":"next-swc-transform","id":626,"timestamp":839450340502,"duration":22763,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":591,"name":"next-swc-loader","id":625,"timestamp":839450340491,"duration":22775,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":434,"name":"build-module-js","id":591,"timestamp":839450340070,"duration":23532,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\is-navigating-to-new-root-layout.js","layer":"app-pages-browser"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":613,"name":"next-swc-transform","id":614,"timestamp":839450340431,"duration":23187,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":581,"name":"next-swc-loader","id":613,"timestamp":839450340420,"duration":23199,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":376,"name":"build-module-js","id":581,"timestamp":839450339922,"duration":24890,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\constants.js","layer":"null"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":627,"name":"next-swc-transform","id":628,"timestamp":839450340513,"duration":24349,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":592,"name":"next-swc-loader","id":627,"timestamp":839450340502,"duration":24362,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":434,"name":"build-module-js","id":592,"timestamp":839450340088,"duration":25349,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\apply-router-state-patch-to-tree.js","layer":"app-pages-browser"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":629,"name":"next-swc-transform","id":630,"timestamp":839450340525,"duration":24928,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":593,"name":"next-swc-loader","id":629,"timestamp":839450340514,"duration":24940,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":388,"name":"build-module-js","id":593,"timestamp":839450340105,"duration":25788,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\request-idle-callback.js","layer":"null"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":631,"name":"next-swc-transform","id":632,"timestamp":839450340536,"duration":25372,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":594,"name":"next-swc-loader","id":631,"timestamp":839450340526,"duration":25384,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":434,"name":"build-module-js","id":594,"timestamp":839450340119,"duration":26356,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\handle-mutable.js","layer":"app-pages-browser"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":648,"name":"next-swc-transform","id":649,"timestamp":839450357409,"duration":9512,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":641,"name":"next-swc-loader","id":648,"timestamp":839450357384,"duration":9541,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":435,"name":"build-module-js","id":641,"timestamp":839450357046,"duration":10218,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\read-record-value.js","layer":"app-pages-browser"},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":652,"name":"next-swc-transform","id":653,"timestamp":839450357438,"duration":9843,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":643,"name":"next-swc-loader","id":652,"timestamp":839450357426,"duration":9857,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":432,"name":"build-module-js","id":643,"timestamp":839450357099,"duration":10591,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\invalidate-cache-below-flight-segmentpath.js","layer":"app-pages-browser"},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":650,"name":"next-swc-transform","id":651,"timestamp":839450357424,"duration":10280,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":642,"name":"next-swc-loader","id":650,"timestamp":839450357411,"duration":10295,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":432,"name":"build-module-js","id":642,"timestamp":839450357077,"duration":11124,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\fill-cache-with-data-property.js","layer":"app-pages-browser"},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":654,"name":"next-swc-transform","id":655,"timestamp":839450357450,"duration":10765,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":644,"name":"next-swc-loader","id":654,"timestamp":839450357439,"duration":10778,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":432,"name":"build-module-js","id":644,"timestamp":839450357118,"duration":11591,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\get-prefetch-cache-entry-status.js","layer":"app-pages-browser"},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":660,"name":"next-swc-transform","id":661,"timestamp":839450357487,"duration":11324,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":647,"name":"next-swc-loader","id":660,"timestamp":839450357476,"duration":11337,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":432,"name":"build-module-js","id":647,"timestamp":839450357181,"duration":11958,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\should-hard-navigate.js","layer":"app-pages-browser"},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":656,"name":"next-swc-transform","id":657,"timestamp":839450357463,"duration":11691,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":645,"name":"next-swc-loader","id":656,"timestamp":839450357451,"duration":11704,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":432,"name":"build-module-js","id":645,"timestamp":839450357136,"duration":12436,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\create-optimistic-tree.js","layer":"app-pages-browser"},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":658,"name":"next-swc-transform","id":659,"timestamp":839450357475,"duration":12111,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":646,"name":"next-swc-loader","id":658,"timestamp":839450357464,"duration":12123,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":432,"name":"build-module-js","id":646,"timestamp":839450357155,"duration":12728,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\reducers\\prune-prefetch-cache.js","layer":"app-pages-browser"},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":514,"name":"read-resource","id":515,"timestamp":839450331939,"duration":46073,"tags":{},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":260,"name":"build-module-js","id":514,"timestamp":839450331929,"duration":46338,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\lib\\is-api-route.js","layer":"null"},"startTime":1704500737516},{"traceId":"4dea77cda8cb5b99","parentId":510,"name":"read-resource","id":511,"timestamp":839450331878,"duration":46669,"tags":{},"startTime":1704500737515},{"traceId":"4dea77cda8cb5b99","parentId":186,"name":"build-module-js","id":510,"timestamp":839450331865,"duration":46808,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\react-server-dom-webpack\\client.js","layer":"app-pages-browser"},"startTime":1704500737515},{"traceId":"4dea77cda8cb5b99","parentId":667,"name":"next-swc-transform","id":668,"timestamp":839450371472,"duration":7852,"tags":{},"startTime":1704500737555}] +[{"traceId":"4dea77cda8cb5b99","parentId":664,"name":"next-swc-loader","id":667,"timestamp":839450371447,"duration":8015,"tags":{},"startTime":1704500737555},{"traceId":"4dea77cda8cb5b99","parentId":463,"name":"build-module-js","id":664,"timestamp":839450371320,"duration":8312,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\segment.js","layer":"app-pages-browser"},"startTime":1704500737555},{"traceId":"4dea77cda8cb5b99","parentId":671,"name":"next-swc-transform","id":672,"timestamp":839450371501,"duration":8146,"tags":{},"startTime":1704500737555},{"traceId":"4dea77cda8cb5b99","parentId":666,"name":"next-swc-loader","id":671,"timestamp":839450371488,"duration":8160,"tags":{},"startTime":1704500737555},{"traceId":"4dea77cda8cb5b99","parentId":471,"name":"build-module-js","id":666,"timestamp":839450371380,"duration":8470,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\lazy-dynamic\\dynamic-no-ssr.js","layer":"app-pages-browser"},"startTime":1704500737555},{"traceId":"4dea77cda8cb5b99","parentId":669,"name":"next-swc-transform","id":670,"timestamp":839450371487,"duration":8376,"tags":{},"startTime":1704500737555},{"traceId":"4dea77cda8cb5b99","parentId":665,"name":"next-swc-loader","id":669,"timestamp":839450371473,"duration":8392,"tags":{},"startTime":1704500737555},{"traceId":"4dea77cda8cb5b99","parentId":464,"name":"build-module-js","id":665,"timestamp":839450371358,"duration":9198,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\promise-queue.js","layer":"app-pages-browser"},"startTime":1704500737555},{"traceId":"4dea77cda8cb5b99","parentId":570,"name":"read-resource","id":571,"timestamp":839450339706,"duration":41983,"tags":{},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":144,"name":"build-module-js","id":570,"timestamp":839450339682,"duration":42173,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\react\\index.js","layer":"null"},"startTime":1704500737523},{"traceId":"4dea77cda8cb5b99","parentId":582,"name":"read-resource","id":583,"timestamp":839450339947,"duration":42024,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":329,"name":"build-module-js","id":582,"timestamp":839450339936,"duration":44372,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\react\\cjs\\react.production.min.js","layer":"app-pages-browser"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":584,"name":"read-resource","id":585,"timestamp":839450339970,"duration":44352,"tags":{},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":310,"name":"build-module-js","id":584,"timestamp":839450339960,"duration":44669,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\react\\cjs\\react-jsx-runtime.production.min.js","layer":"app-pages-browser"},"startTime":1704500737524},{"traceId":"4dea77cda8cb5b99","parentId":633,"name":"read-resource","id":634,"timestamp":839450356761,"duration":29036,"tags":{},"startTime":1704500737540},{"traceId":"4dea77cda8cb5b99","parentId":144,"name":"build-module-js","id":633,"timestamp":839450356483,"duration":29673,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@swc\\helpers\\esm\\_interop_require_default.js","layer":"null"},"startTime":1704500737540},{"traceId":"4dea77cda8cb5b99","parentId":635,"name":"read-resource","id":636,"timestamp":839450356998,"duration":29167,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":158,"name":"build-module-js","id":635,"timestamp":839450356782,"duration":29567,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@swc\\helpers\\esm\\_interop_require_default.js","layer":"app-pages-browser"},"startTime":1704500737540},{"traceId":"4dea77cda8cb5b99","parentId":637,"name":"read-resource","id":638,"timestamp":839450357015,"duration":29346,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":153,"name":"build-module-js","id":637,"timestamp":839450357003,"duration":29860,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@swc\\helpers\\esm\\_interop_require_wildcard.js","layer":"app-pages-browser"},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":639,"name":"read-resource","id":640,"timestamp":839450357044,"duration":29826,"tags":{},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":209,"name":"build-module-js","id":639,"timestamp":839450357034,"duration":30162,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@swc\\helpers\\esm\\_interop_require_wildcard.js","layer":"null"},"startTime":1704500737541},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":122,"timestamp":839449520785,"duration":867005,"tags":{"request":"next-client-pages-loader?absolutePagePath=next%2Fdist%2Fclient%2Fcomponents%2Fnot-found-error&page=%2F_not-found!"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":662,"name":"read-resource","id":663,"timestamp":839450371303,"duration":16945,"tags":{},"startTime":1704500737555},{"traceId":"4dea77cda8cb5b99","parentId":258,"name":"build-module-js","id":662,"timestamp":839450371279,"duration":70902,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\tweakpane\\dist\\tweakpane.js","layer":"app-pages-browser"},"startTime":1704500737555},{"traceId":"4dea77cda8cb5b99","parentId":681,"name":"next-swc-transform","id":682,"timestamp":839450387993,"duration":56135,"tags":{},"startTime":1704500737572},{"traceId":"4dea77cda8cb5b99","parentId":677,"name":"next-swc-loader","id":681,"timestamp":839450387968,"duration":56165,"tags":{},"startTime":1704500737572},{"traceId":"4dea77cda8cb5b99","parentId":430,"name":"build-module-js","id":677,"timestamp":839450387838,"duration":56777,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\image-external.js","layer":"app-pages-browser"},"startTime":1704500737571},{"traceId":"4dea77cda8cb5b99","parentId":683,"name":"next-swc-transform","id":684,"timestamp":839450388009,"duration":56625,"tags":{},"startTime":1704500737572},{"traceId":"4dea77cda8cb5b99","parentId":680,"name":"next-swc-loader","id":683,"timestamp":839450387995,"duration":56641,"tags":{},"startTime":1704500737572},{"traceId":"4dea77cda8cb5b99","parentId":456,"name":"build-module-js","id":680,"timestamp":839450387915,"duration":57321,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\dev\\error-overlay\\websocket.js","layer":"null"},"startTime":1704500737571},{"traceId":"4dea77cda8cb5b99","parentId":691,"name":"next-swc-transform","id":692,"timestamp":839450443051,"duration":4885,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":685,"name":"next-swc-loader","id":691,"timestamp":839450443008,"duration":4932,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":512,"name":"build-module-js","id":685,"timestamp":839450442829,"duration":5315,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\page-path\\normalize-path-sep.js","layer":"null"},"startTime":1704500737626},{"traceId":"4dea77cda8cb5b99","parentId":695,"name":"next-swc-transform","id":696,"timestamp":839450443118,"duration":5041,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":687,"name":"next-swc-loader","id":695,"timestamp":839450443069,"duration":5091,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":521,"name":"build-module-js","id":687,"timestamp":839450442914,"duration":5471,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\add-path-suffix.js","layer":"null"},"startTime":1704500737626},{"traceId":"4dea77cda8cb5b99","parentId":693,"name":"next-swc-transform","id":694,"timestamp":839450443068,"duration":5331,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":686,"name":"next-swc-loader","id":693,"timestamp":839450443053,"duration":5347,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":517,"name":"build-module-js","id":686,"timestamp":839450442890,"duration":5727,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\escape-regexp.js","layer":"null"},"startTime":1704500737626},{"traceId":"4dea77cda8cb5b99","parentId":697,"name":"next-swc-transform","id":698,"timestamp":839450443132,"duration":5543,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":688,"name":"next-swc-loader","id":697,"timestamp":839450443119,"duration":5558,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":519,"name":"build-module-js","id":688,"timestamp":839450442931,"duration":5938,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\remove-path-prefix.js","layer":"null"},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":699,"name":"next-swc-transform","id":700,"timestamp":839450443145,"duration":5762,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":689,"name":"next-swc-loader","id":699,"timestamp":839450443133,"duration":5776,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":521,"name":"build-module-js","id":689,"timestamp":839450442948,"duration":6165,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\add-locale.js","layer":"null"},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":701,"name":"next-swc-transform","id":702,"timestamp":839450443158,"duration":5968,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":690,"name":"next-swc-loader","id":701,"timestamp":839450443146,"duration":5981,"tags":{},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":506,"name":"build-module-js","id":690,"timestamp":839450442964,"duration":6442,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\trusted-types.js","layer":"null"},"startTime":1704500737627},{"traceId":"4dea77cda8cb5b99","parentId":673,"name":"read-resource","id":674,"timestamp":839450385196,"duration":64220,"tags":{},"startTime":1704500737569},{"traceId":"4dea77cda8cb5b99","parentId":463,"name":"build-module-js","id":673,"timestamp":839450385161,"duration":64798,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\server\\future\\helpers\\interception-routes.js","layer":"app-pages-browser"},"startTime":1704500737569},{"traceId":"4dea77cda8cb5b99","parentId":675,"name":"read-resource","id":676,"timestamp":839450385226,"duration":64739,"tags":{},"startTime":1704500737569},{"traceId":"4dea77cda8cb5b99","parentId":517,"name":"build-module-js","id":675,"timestamp":839450385212,"duration":65178,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\server\\future\\helpers\\interception-routes.js","layer":"null"},"startTime":1704500737569},{"traceId":"4dea77cda8cb5b99","parentId":708,"name":"next-swc-transform","id":709,"timestamp":839450447509,"duration":3976,"tags":{},"startTime":1704500737631},{"traceId":"4dea77cda8cb5b99","parentId":704,"name":"next-swc-loader","id":708,"timestamp":839450447493,"duration":3996,"tags":{},"startTime":1704500737631},{"traceId":"4dea77cda8cb5b99","parentId":581,"name":"build-module-js","id":704,"timestamp":839450447363,"duration":4250,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\modern-browserslist-target.js","layer":"null"},"startTime":1704500737631},{"traceId":"4dea77cda8cb5b99","parentId":706,"name":"next-swc-transform","id":707,"timestamp":839450447491,"duration":4134,"tags":{},"startTime":1704500737631},{"traceId":"4dea77cda8cb5b99","parentId":703,"name":"next-swc-loader","id":706,"timestamp":839450447466,"duration":4161,"tags":{},"startTime":1704500737631},{"traceId":"4dea77cda8cb5b99","parentId":578,"name":"build-module-js","id":703,"timestamp":839450447105,"duration":4892,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\async-local-storage.js","layer":"shared"},"startTime":1704500737631},{"traceId":"4dea77cda8cb5b99","parentId":710,"name":"next-swc-transform","id":711,"timestamp":839450447522,"duration":4649,"tags":{},"startTime":1704500737631},{"traceId":"4dea77cda8cb5b99","parentId":705,"name":"next-swc-loader","id":710,"timestamp":839450447510,"duration":4663,"tags":{},"startTime":1704500737631},{"traceId":"4dea77cda8cb5b99","parentId":590,"name":"build-module-js","id":705,"timestamp":839450447388,"duration":5241,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\fill-cache-with-new-subtree-data.js","layer":"app-pages-browser"},"startTime":1704500737631},{"traceId":"4dea77cda8cb5b99","parentId":678,"name":"read-resource","id":679,"timestamp":839450387900,"duration":64798,"tags":{},"startTime":1704500737571},{"traceId":"4dea77cda8cb5b99","parentId":454,"name":"build-module-js","id":678,"timestamp":839450387886,"duration":121653,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\react-dom\\cjs\\react-dom.production.min.js","layer":"app-pages-browser"},"startTime":1704500737571},{"traceId":"4dea77cda8cb5b99","parentId":715,"name":"next-swc-transform","id":716,"timestamp":839450451341,"duration":59556,"tags":{},"startTime":1704500737635},{"traceId":"4dea77cda8cb5b99","parentId":712,"name":"next-swc-loader","id":715,"timestamp":839450451317,"duration":59584,"tags":{},"startTime":1704500737635},{"traceId":"4dea77cda8cb5b99","parentId":382,"name":"build-module-js","id":712,"timestamp":839450451200,"duration":59925,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\index.js","layer":"null"},"startTime":1704500737635},{"traceId":"4dea77cda8cb5b99","parentId":720,"name":"next-swc-transform","id":721,"timestamp":839450510282,"duration":4860,"tags":{},"startTime":1704500737694},{"traceId":"4dea77cda8cb5b99","parentId":717,"name":"next-swc-loader","id":720,"timestamp":839450510250,"duration":4895,"tags":{},"startTime":1704500737694},{"traceId":"4dea77cda8cb5b99","parentId":677,"name":"build-module-js","id":717,"timestamp":839450510106,"duration":5218,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\utils\\warn-once.js","layer":"app-pages-browser"},"startTime":1704500737694},{"traceId":"4dea77cda8cb5b99","parentId":303,"name":"build-module-scss","id":439,"timestamp":839449706218,"duration":809919,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss.webpack[javascript/auto]!=!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\css-loader\\src\\index.js??ruleSet[1].rules[12].oneOf[13].use[2]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\postcss-loader\\src\\index.js??ruleSet[1].rules[12].oneOf[13].use[3]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\resolve-url-loader\\index.js??ruleSet[1].rules[12].oneOf[13].use[4]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\sass-loader\\cjs.js??ruleSet[1].rules[12].oneOf[13].use[5]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","layer":"null"},"startTime":1704500736890},{"traceId":"4dea77cda8cb5b99","parentId":304,"name":"build-module-scss","id":449,"timestamp":839449868203,"duration":647949,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss.webpack[javascript/auto]!=!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\css-loader\\src\\index.js??ruleSet[1].rules[12].oneOf[13].use[2]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\postcss-loader\\src\\index.js??ruleSet[1].rules[12].oneOf[13].use[3]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\resolve-url-loader\\index.js??ruleSet[1].rules[12].oneOf[13].use[4]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\sass-loader\\cjs.js??ruleSet[1].rules[12].oneOf[13].use[5]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss","layer":"null"},"startTime":1704500737052},{"traceId":"4dea77cda8cb5b99","parentId":713,"name":"read-resource","id":714,"timestamp":839450451259,"duration":65009,"tags":{},"startTime":1704500737635},{"traceId":"4dea77cda8cb5b99","parentId":510,"name":"build-module-js","id":713,"timestamp":839450451244,"duration":65186,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\react-server-dom-webpack\\client.browser.js","layer":"app-pages-browser"},"startTime":1704500737635},{"traceId":"4dea77cda8cb5b99","parentId":718,"name":"read-resource","id":719,"timestamp":839450510186,"duration":7029,"tags":{},"startTime":1704500737694},{"traceId":"4dea77cda8cb5b99","parentId":570,"name":"build-module-js","id":718,"timestamp":839450510171,"duration":8594,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\react\\cjs\\react.production.min.js","layer":"null"},"startTime":1704500737694},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":124,"timestamp":839449520791,"duration":998260,"tags":{"request":"next-client-pages-loader?absolutePagePath=next%2Fdist%2Fpages%2F_app&page=%2F_app!"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":123,"timestamp":839449520788,"duration":998354,"tags":{"request":"next-client-pages-loader?absolutePagePath=next%2Fdist%2Fpages%2F_error&page=%2F_error!"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":733,"name":"next-swc-transform","id":734,"timestamp":839450516860,"duration":2444,"tags":{},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":728,"name":"next-swc-loader","id":733,"timestamp":839450516848,"duration":2460,"tags":{},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":677,"name":"build-module-js","id":728,"timestamp":839450516694,"duration":3215,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\image-loader.js","layer":"app-pages-browser"},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":729,"name":"next-swc-transform","id":730,"timestamp":839450516831,"duration":3520,"tags":{},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":726,"name":"next-swc-loader","id":729,"timestamp":839450516804,"duration":3549,"tags":{},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":677,"name":"build-module-js","id":726,"timestamp":839450516616,"duration":4876,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\image-component.js","layer":"app-pages-browser"},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":722,"name":"read-resource","id":723,"timestamp":839450515915,"duration":5765,"tags":{},"startTime":1704500737699},{"traceId":"4dea77cda8cb5b99","parentId":452,"name":"build-module-js","id":722,"timestamp":839450515887,"duration":6019,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\react-dom\\index.js","layer":"null"},"startTime":1704500737699},{"traceId":"4dea77cda8cb5b99","parentId":731,"name":"next-swc-transform","id":732,"timestamp":839450516847,"duration":6735,"tags":{},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":727,"name":"next-swc-loader","id":731,"timestamp":839450516833,"duration":6753,"tags":{},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":677,"name":"build-module-js","id":727,"timestamp":839450516667,"duration":8172,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\get-img-props.js","layer":"app-pages-browser"},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":724,"name":"read-resource","id":725,"timestamp":839450515944,"duration":8919,"tags":{},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":378,"name":"build-module-js","id":724,"timestamp":839450515928,"duration":10519,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\web-vitals\\web-vitals.js","layer":"null"},"startTime":1704500737700},{"traceId":"4dea77cda8cb5b99","parentId":744,"name":"next-swc-transform","id":745,"timestamp":839450520138,"duration":6326,"tags":{},"startTime":1704500737704},{"traceId":"4dea77cda8cb5b99","parentId":739,"name":"next-swc-loader","id":744,"timestamp":839450520124,"duration":6340,"tags":{},"startTime":1704500737704},{"traceId":"4dea77cda8cb5b99","parentId":705,"name":"build-module-js","id":739,"timestamp":839450520058,"duration":6703,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\router-reducer\\invalidate-cache-by-router-state.js","layer":"app-pages-browser"},"startTime":1704500737704},{"traceId":"4dea77cda8cb5b99","parentId":742,"name":"next-swc-transform","id":743,"timestamp":839450520123,"duration":6652,"tags":{},"startTime":1704500737704},{"traceId":"4dea77cda8cb5b99","parentId":738,"name":"next-swc-loader","id":742,"timestamp":839450520110,"duration":6667,"tags":{},"startTime":1704500737704},{"traceId":"4dea77cda8cb5b99","parentId":675,"name":"build-module-js","id":738,"timestamp":839450520032,"duration":7066,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\app-paths.js","layer":"null"},"startTime":1704500737704},{"traceId":"4dea77cda8cb5b99","parentId":740,"name":"next-swc-transform","id":741,"timestamp":839450520108,"duration":7003,"tags":{},"startTime":1704500737704},{"traceId":"4dea77cda8cb5b99","parentId":737,"name":"next-swc-loader","id":740,"timestamp":839450520084,"duration":7029,"tags":{},"startTime":1704500737704},{"traceId":"4dea77cda8cb5b99","parentId":673,"name":"build-module-js","id":737,"timestamp":839450519981,"duration":7436,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\app-paths.js","layer":"app-pages-browser"},"startTime":1704500737704},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"read-resource","id":736,"timestamp":839450519122,"duration":10336,"tags":{},"startTime":1704500737703}] +[{"traceId":"4dea77cda8cb5b99","parentId":305,"name":"build-module-js","id":735,"timestamp":839450519089,"duration":11337,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\index.js","layer":"app-pages-browser"},"startTime":1704500737703},{"traceId":"4dea77cda8cb5b99","parentId":747,"name":"next-swc-transform","id":748,"timestamp":839450528001,"duration":2610,"tags":{},"startTime":1704500737712},{"traceId":"4dea77cda8cb5b99","parentId":746,"name":"next-swc-loader","id":747,"timestamp":839450527975,"duration":2639,"tags":{},"startTime":1704500737712},{"traceId":"4dea77cda8cb5b99","parentId":712,"name":"build-module-js","id":746,"timestamp":839450527867,"duration":3699,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router\\utils\\sorted-routes.js","layer":"null"},"startTime":1704500737711},{"traceId":"4dea77cda8cb5b99","parentId":755,"name":"next-swc-transform","id":756,"timestamp":839450529327,"duration":4964,"tags":{},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":750,"name":"next-swc-loader","id":755,"timestamp":839450529313,"duration":4982,"tags":{},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":726,"name":"build-module-js","id":750,"timestamp":839450529161,"duration":5346,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\image-config.js","layer":"app-pages-browser"},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":757,"name":"next-swc-transform","id":758,"timestamp":839450529340,"duration":5197,"tags":{},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":751,"name":"next-swc-loader","id":757,"timestamp":839450529328,"duration":5211,"tags":{},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":726,"name":"build-module-js","id":751,"timestamp":839450529188,"duration":5519,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\image-config-context.shared-runtime.js","layer":"app-pages-browser"},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":759,"name":"next-swc-transform","id":760,"timestamp":839450529353,"duration":5367,"tags":{},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":752,"name":"next-swc-loader","id":759,"timestamp":839450529341,"duration":5380,"tags":{},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":726,"name":"build-module-js","id":752,"timestamp":839450529210,"duration":5658,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\router-context.shared-runtime.js","layer":"app-pages-browser"},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":753,"name":"next-swc-transform","id":754,"timestamp":839450529311,"duration":5733,"tags":{},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":749,"name":"next-swc-loader","id":753,"timestamp":839450529285,"duration":5762,"tags":{},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":726,"name":"build-module-js","id":749,"timestamp":839450529111,"duration":6690,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\head.js","layer":"app-pages-browser"},"startTime":1704500737713},{"traceId":"4dea77cda8cb5b99","parentId":770,"name":"next-swc-transform","id":771,"timestamp":839450533304,"duration":3852,"tags":{},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":761,"name":"next-swc-loader","id":770,"timestamp":839450533279,"duration":3881,"tags":{},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":738,"name":"build-module-js","id":761,"timestamp":839450532925,"duration":4415,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\segment.js","layer":"null"},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":762,"name":"read-resource","id":763,"timestamp":839450532990,"duration":7816,"tags":{},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":665,"name":"build-module-js","id":762,"timestamp":839450532973,"duration":8005,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@swc\\helpers\\esm\\_class_private_field_loose_key.js","layer":"app-pages-browser"},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":766,"name":"read-resource","id":767,"timestamp":839450533040,"duration":7977,"tags":{},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":665,"name":"build-module-js","id":766,"timestamp":839450533030,"duration":8161,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@swc\\helpers\\esm\\_class_private_field_loose_base.js","layer":"app-pages-browser"},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":764,"name":"read-resource","id":765,"timestamp":839450533021,"duration":8394,"tags":{},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":439,"name":"build-module-js","id":764,"timestamp":839450533008,"duration":8759,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\css-loader\\src\\runtime\\api.js","layer":"null"},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":768,"name":"read-resource","id":769,"timestamp":839450533059,"duration":10096,"tags":{},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":713,"name":"build-module-js","id":768,"timestamp":839450533048,"duration":12066,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\react-server-dom-webpack\\cjs\\react-server-dom-webpack-client.browser.production.min.js","layer":"app-pages-browser"},"startTime":1704500737717},{"traceId":"4dea77cda8cb5b99","parentId":134,"name":"build-module-scss","id":303,"timestamp":839449676535,"duration":873316,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss","layer":"app-pages-browser"},"startTime":1704500736860},{"traceId":"4dea77cda8cb5b99","parentId":180,"name":"build-module-scss","id":304,"timestamp":839449677035,"duration":873347,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\style.scss","layer":"app-pages-browser"},"startTime":1704500736861},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":120,"timestamp":839449520769,"duration":1030027,"tags":{"request":"./node_modules/next/dist/client/app-next.js"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":794,"name":"next-swc-transform","id":795,"timestamp":839450540605,"duration":10213,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":775,"name":"next-swc-loader","id":794,"timestamp":839450540591,"duration":10229,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":749,"name":"build-module-js","id":775,"timestamp":839450540361,"duration":10639,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\amp-context.shared-runtime.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":796,"name":"next-swc-transform","id":797,"timestamp":839450540618,"duration":10396,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":776,"name":"next-swc-loader","id":796,"timestamp":839450540606,"duration":10409,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":749,"name":"build-module-js","id":776,"timestamp":839450540387,"duration":10777,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\amp-mode.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":798,"name":"next-swc-transform","id":799,"timestamp":839450540630,"duration":10547,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":777,"name":"next-swc-loader","id":798,"timestamp":839450540619,"duration":10560,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":727,"name":"build-module-js","id":777,"timestamp":839450540410,"duration":10959,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\image-blur-svg.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":792,"name":"next-swc-transform","id":793,"timestamp":839450540589,"duration":10914,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":774,"name":"next-swc-loader","id":792,"timestamp":839450540566,"duration":10940,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":749,"name":"build-module-js","id":774,"timestamp":839450540314,"duration":11488,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\side-effect.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":802,"name":"next-swc-transform","id":803,"timestamp":839450540655,"duration":11160,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":779,"name":"next-swc-loader","id":802,"timestamp":839450540644,"duration":11172,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":737,"name":"build-module-js","id":779,"timestamp":839450540445,"duration":11494,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\page-path\\ensure-leading-slash.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":800,"name":"next-swc-transform","id":801,"timestamp":839450540643,"duration":11307,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":778,"name":"next-swc-loader","id":800,"timestamp":839450540631,"duration":11320,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":738,"name":"build-module-js","id":778,"timestamp":839450540430,"duration":11631,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\shared\\lib\\page-path\\ensure-leading-slash.js","layer":"null"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":772,"name":"read-resource","id":773,"timestamp":839450539943,"duration":13167,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":722,"name":"build-module-js","id":772,"timestamp":839450539918,"duration":53324,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\react-dom\\cjs\\react-dom.production.min.js","layer":"null"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":780,"name":"read-resource","id":781,"timestamp":839450540474,"duration":53155,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":780,"timestamp":839450540463,"duration":53666,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\abstractScene.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":790,"name":"read-resource","id":791,"timestamp":839450540557,"duration":53583,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":790,"timestamp":839450540549,"duration":53681,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\types.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":784,"name":"read-resource","id":785,"timestamp":839450540512,"duration":53727,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":784,"timestamp":839450540503,"duration":55380,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\node.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"read-resource","id":787,"timestamp":839450540527,"duration":55369,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":786,"timestamp":839450540518,"duration":64329,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\scene.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":788,"name":"read-resource","id":789,"timestamp":839450540543,"duration":64317,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":788,"timestamp":839450540533,"duration":64674,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\sceneComponent.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":782,"name":"read-resource","id":783,"timestamp":839450540497,"duration":64722,"tags":{},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":782,"timestamp":839450540487,"duration":68679,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\assetContainer.js","layer":"app-pages-browser"},"startTime":1704500737724},{"traceId":"4dea77cda8cb5b99","parentId":303,"name":"build-module","id":884,"timestamp":839450610440,"duration":79,"tags":{"name":"undefined","layer":"undefined"},"startTime":1704500737794},{"traceId":"4dea77cda8cb5b99","parentId":304,"name":"build-module","id":885,"timestamp":839450610529,"duration":11,"tags":{"name":"undefined","layer":"undefined"},"startTime":1704500737794},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":129,"timestamp":839449520809,"duration":1091170,"tags":{"request":"next-flight-client-entry-loader?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cpage.tsx&server=false!"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":804,"name":"read-resource","id":805,"timestamp":839450552479,"duration":59742,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":804,"timestamp":839450552454,"duration":59923,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Actions\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":806,"name":"read-resource","id":807,"timestamp":839450552511,"duration":59883,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":806,"timestamp":839450552497,"duration":60014,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Audio\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"read-resource","id":809,"timestamp":839450552530,"duration":59990,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":808,"timestamp":839450552520,"duration":60152,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":810,"name":"read-resource","id":811,"timestamp":839450552547,"duration":60133,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":810,"timestamp":839450552537,"duration":60247,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Bones\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":814,"name":"read-resource","id":815,"timestamp":839450552576,"duration":60217,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":814,"timestamp":839450552567,"duration":60313,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Buffers\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":822,"name":"read-resource","id":823,"timestamp":839450552636,"duration":60253,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":822,"timestamp":839450552628,"duration":60348,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Compute\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":824,"name":"read-resource","id":825,"timestamp":839450552650,"duration":60335,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":824,"timestamp":839450552641,"duration":60426,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Culling\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":818,"name":"read-resource","id":819,"timestamp":839450552607,"duration":60469,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":818,"timestamp":839450552596,"duration":60567,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Collisions\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"read-resource","id":821,"timestamp":839450552622,"duration":60549,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":820,"timestamp":839450552612,"duration":60715,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":816,"name":"read-resource","id":817,"timestamp":839450552590,"duration":60745,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":816,"timestamp":839450552581,"duration":60868,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":828,"name":"read-resource","id":829,"timestamp":839450552679,"duration":60780,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":828,"timestamp":839450552669,"duration":60891,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Debug\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":826,"name":"read-resource","id":827,"timestamp":839450552663,"duration":60904,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":826,"timestamp":839450552655,"duration":60986,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\DeviceInput\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":812,"name":"read-resource","id":813,"timestamp":839450552561,"duration":61087,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":812,"timestamp":839450552553,"duration":61157,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\BakedVertexAnimation\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":832,"name":"read-resource","id":833,"timestamp":839450552707,"duration":61010,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":832,"timestamp":839450552698,"duration":61097,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gamepads\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":830,"name":"read-resource","id":831,"timestamp":839450552693,"duration":61134,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":830,"timestamp":839450552685,"duration":61219,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Events\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"read-resource","id":837,"timestamp":839450552735,"duration":61177,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":836,"timestamp":839450552726,"duration":61398,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":838,"name":"read-resource","id":839,"timestamp":839450552749,"duration":61382,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":838,"timestamp":839450552741,"duration":61460,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Instrumentation\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":840,"name":"read-resource","id":841,"timestamp":839450552763,"duration":61445,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":840,"timestamp":839450552755,"duration":61540,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Helpers\\index.js","layer":"app-pages-browser"},"startTime":1704500737736}] +[{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"read-resource","id":835,"timestamp":839450552721,"duration":61698,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":834,"timestamp":839450552713,"duration":61832,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":842,"name":"read-resource","id":843,"timestamp":839450552777,"duration":61776,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":842,"timestamp":839450552768,"duration":61852,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\LensFlares\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":846,"name":"read-resource","id":847,"timestamp":839450552805,"duration":61822,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":846,"timestamp":839450552797,"duration":61913,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Layers\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":848,"name":"read-resource","id":849,"timestamp":839450552818,"duration":61898,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":848,"timestamp":839450552810,"duration":61979,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Loading\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"read-resource","id":851,"timestamp":839450552832,"duration":61965,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":850,"timestamp":839450552824,"duration":62200,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":844,"name":"read-resource","id":845,"timestamp":839450552791,"duration":62240,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":844,"timestamp":839450552782,"duration":62339,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":852,"name":"read-resource","id":853,"timestamp":839450552846,"duration":62282,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":852,"timestamp":839450552838,"duration":62367,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":854,"name":"read-resource","id":855,"timestamp":839450552860,"duration":62352,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":854,"timestamp":839450552851,"duration":62423,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Morph\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"read-resource","id":857,"timestamp":839450552874,"duration":62407,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":856,"timestamp":839450552866,"duration":62613,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":860,"name":"read-resource","id":861,"timestamp":839450552900,"duration":62587,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":860,"timestamp":839450552892,"duration":62658,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Offline\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":858,"name":"read-resource","id":859,"timestamp":839450552888,"duration":62669,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":858,"timestamp":839450552879,"duration":62739,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Navigation\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"read-resource","id":865,"timestamp":839450552926,"duration":62699,"tags":{},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":864,"timestamp":839450552918,"duration":62915,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\index.js","layer":"app-pages-browser"},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":872,"name":"read-resource","id":873,"timestamp":839450552983,"duration":62857,"tags":{},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":872,"timestamp":839450552975,"duration":62937,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\States\\index.js","layer":"app-pages-browser"},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":866,"name":"read-resource","id":867,"timestamp":839450552941,"duration":62978,"tags":{},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":866,"timestamp":839450552932,"duration":63067,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\index.js","layer":"app-pages-browser"},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"read-resource","id":863,"timestamp":839450552913,"duration":63093,"tags":{},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":862,"timestamp":839450552905,"duration":63235,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\index.js","layer":"app-pages-browser"},"startTime":1704500737736},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"read-resource","id":877,"timestamp":839450553011,"duration":63136,"tags":{},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":876,"timestamp":839450553002,"duration":63258,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\index.js","layer":"app-pages-browser"},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":874,"name":"read-resource","id":875,"timestamp":839450552997,"duration":63271,"tags":{},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":874,"timestamp":839450552988,"duration":63353,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Sprites\\index.js","layer":"app-pages-browser"},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"read-resource","id":869,"timestamp":839450552957,"duration":63392,"tags":{},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":868,"timestamp":839450552946,"duration":63529,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\index.js","layer":"app-pages-browser"},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"read-resource","id":879,"timestamp":839450553024,"duration":63459,"tags":{},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":878,"timestamp":839450553016,"duration":63858,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\index.js","layer":"app-pages-browser"},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":870,"name":"read-resource","id":871,"timestamp":839450552970,"duration":63913,"tags":{},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":870,"timestamp":839450552962,"duration":63983,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Probes\\index.js","layer":"app-pages-browser"},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":880,"name":"read-resource","id":881,"timestamp":839450553038,"duration":69052,"tags":{},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":880,"timestamp":839450553030,"duration":69155,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Compat\\index.js","layer":"app-pages-browser"},"startTime":1704500737737},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"read-resource","id":883,"timestamp":839450593445,"duration":28763,"tags":{},"startTime":1704500737777},{"traceId":"4dea77cda8cb5b99","parentId":735,"name":"build-module-js","id":882,"timestamp":839450593402,"duration":28932,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\index.js","layer":"app-pages-browser"},"startTime":1704500737777},{"traceId":"4dea77cda8cb5b99","parentId":888,"name":"read-resource","id":889,"timestamp":839450666837,"duration":5637,"tags":{},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":784,"name":"build-module-js","id":888,"timestamp":839450666824,"duration":7480,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\tslib.es6.js","layer":"app-pages-browser"},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":894,"name":"read-resource","id":895,"timestamp":839450666884,"duration":7435,"tags":{},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":784,"name":"build-module-js","id":894,"timestamp":839450666876,"duration":8149,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\observable.js","layer":"app-pages-browser"},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":898,"name":"read-resource","id":899,"timestamp":839450666913,"duration":8142,"tags":{},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":784,"name":"build-module-js","id":898,"timestamp":839450666905,"duration":8325,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\engineStore.js","layer":"app-pages-browser"},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":896,"name":"read-resource","id":897,"timestamp":839450666899,"duration":8343,"tags":{},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":784,"name":"build-module-js","id":896,"timestamp":839450666891,"duration":8482,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\devTools.js","layer":"app-pages-browser"},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":900,"name":"read-resource","id":901,"timestamp":839450666926,"duration":8458,"tags":{},"startTime":1704500737851},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":900,"timestamp":839450666918,"duration":12774,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\tools.js","layer":"app-pages-browser"},"startTime":1704500737851},{"traceId":"4dea77cda8cb5b99","parentId":892,"name":"read-resource","id":893,"timestamp":839450666870,"duration":12868,"tags":{},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":784,"name":"build-module-js","id":892,"timestamp":839450666861,"duration":14180,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\decorators.js","layer":"app-pages-browser"},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":890,"name":"read-resource","id":891,"timestamp":839450666855,"duration":14198,"tags":{},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":784,"name":"build-module-js","id":890,"timestamp":839450666845,"duration":29847,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.vector.js","layer":"app-pages-browser"},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":886,"name":"read-resource","id":887,"timestamp":839450666809,"duration":29901,"tags":{},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":678,"name":"build-module-js","id":886,"timestamp":839450666773,"duration":30104,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\scheduler\\index.js","layer":"app-pages-browser"},"startTime":1704500737850},{"traceId":"4dea77cda8cb5b99","parentId":902,"name":"read-resource","id":903,"timestamp":839450669422,"duration":32900,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":902,"timestamp":839450669396,"duration":33108,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\precisionDate.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":908,"name":"read-resource","id":909,"timestamp":839450669474,"duration":33041,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":908,"timestamp":839450669466,"duration":34906,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\uniformBuffer.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":904,"name":"read-resource","id":905,"timestamp":839450669444,"duration":34941,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":904,"timestamp":839450669432,"duration":35330,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\smartArray.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":914,"name":"read-resource","id":915,"timestamp":839450669516,"duration":35260,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":914,"timestamp":839450669508,"duration":35898,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Collisions\\pickingInfo.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":918,"name":"read-resource","id":919,"timestamp":839450669543,"duration":35875,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":918,"timestamp":839450669534,"duration":36449,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\postProcessManager.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":906,"name":"read-resource","id":907,"timestamp":839450669460,"duration":36535,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":906,"timestamp":839450669450,"duration":36952,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\tags.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":916,"name":"read-resource","id":917,"timestamp":839450669529,"duration":36886,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":916,"timestamp":839450669521,"duration":37089,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Actions\\actionEvent.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":922,"name":"read-resource","id":923,"timestamp":839450669569,"duration":37052,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":922,"timestamp":839450669561,"duration":37361,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\perfCounter.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":910,"name":"read-resource","id":911,"timestamp":839450669488,"duration":37445,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":910,"timestamp":839450669480,"duration":37753,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\stringDictionary.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":926,"name":"read-resource","id":927,"timestamp":839450669595,"duration":37648,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":926,"timestamp":839450669587,"duration":37853,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\domManagement.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":920,"name":"read-resource","id":921,"timestamp":839450669555,"duration":37895,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":920,"timestamp":839450669548,"duration":38510,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\renderingManager.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":912,"name":"read-resource","id":913,"timestamp":839450669502,"duration":38567,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":912,"timestamp":839450669493,"duration":39755,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\imageProcessingConfiguration.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":924,"name":"read-resource","id":925,"timestamp":839450669582,"duration":39678,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":924,"timestamp":839450669574,"duration":40037,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.frustum.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":928,"name":"read-resource","id":929,"timestamp":839450669609,"duration":40014,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":928,"timestamp":839450669601,"duration":40139,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\uniqueIdGenerator.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":930,"name":"read-resource","id":931,"timestamp":839450669621,"duration":40128,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":930,"timestamp":839450669614,"duration":42192,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.color.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":932,"name":"read-resource","id":933,"timestamp":839450669634,"duration":42184,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":932,"timestamp":839450669627,"duration":44253,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\fileTools.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":934,"name":"read-resource","id":935,"timestamp":839450669648,"duration":44245,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":934,"timestamp":839450669639,"duration":44439,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\lightConstants.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":938,"name":"read-resource","id":939,"timestamp":839450669674,"duration":44416,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":938,"timestamp":839450669666,"duration":44882,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\logger.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":940,"name":"read-resource","id":941,"timestamp":839450669687,"duration":44873,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":782,"name":"build-module-js","id":940,"timestamp":839450669679,"duration":52110,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\transformNode.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":946,"name":"read-resource","id":947,"timestamp":839450669733,"duration":52071,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":782,"name":"build-module-js","id":946,"timestamp":839450669719,"duration":53418,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\instancedMesh.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":942,"name":"read-resource","id":943,"timestamp":839450669700,"duration":53466,"tags":{},"startTime":1704500737853}] +[{"traceId":"4dea77cda8cb5b99","parentId":782,"name":"build-module-js","id":942,"timestamp":839450669692,"duration":60197,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\abstractMesh.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":948,"name":"read-resource","id":949,"timestamp":839450669747,"duration":60156,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":782,"name":"build-module-js","id":948,"timestamp":839450669738,"duration":61503,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\light.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":936,"name":"read-resource","id":937,"timestamp":839450669661,"duration":61593,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":936,"timestamp":839450669653,"duration":61905,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\arrayTools.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":944,"name":"read-resource","id":945,"timestamp":839450669714,"duration":61876,"tags":{},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":782,"name":"build-module-js","id":944,"timestamp":839450669706,"duration":72492,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\mesh.js","layer":"app-pages-browser"},"startTime":1704500737853},{"traceId":"4dea77cda8cb5b99","parentId":950,"name":"read-resource","id":951,"timestamp":839450671187,"duration":77756,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":782,"name":"build-module-js","id":950,"timestamp":839450671162,"duration":80595,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\camera.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":958,"name":"read-resource","id":959,"timestamp":839450671257,"duration":80514,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":804,"name":"build-module-js","id":958,"timestamp":839450671249,"duration":80780,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Actions\\abstractActionManager.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":954,"name":"read-resource","id":955,"timestamp":839450671229,"duration":80816,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":954,"timestamp":839450671219,"duration":81005,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Inputs\\pointerPickingConfiguration.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":952,"name":"read-resource","id":953,"timestamp":839450671212,"duration":81023,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":786,"name":"build-module-js","id":952,"timestamp":839450671200,"duration":83908,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Inputs\\scene.inputManager.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":960,"name":"read-resource","id":961,"timestamp":839450671270,"duration":83851,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":804,"name":"build-module-js","id":960,"timestamp":839450671262,"duration":85193,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Actions\\actionManager.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":956,"name":"read-resource","id":957,"timestamp":839450671243,"duration":85224,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":804,"name":"build-module-js","id":956,"timestamp":839450671235,"duration":85680,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Actions\\action.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":964,"name":"read-resource","id":965,"timestamp":839450671298,"duration":85628,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":804,"name":"build-module-js","id":964,"timestamp":839450671289,"duration":85876,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Actions\\directAudioActions.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":968,"name":"read-resource","id":969,"timestamp":839450671325,"duration":85851,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":804,"name":"build-module-js","id":968,"timestamp":839450671317,"duration":86246,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Actions\\interpolateValueAction.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":962,"name":"read-resource","id":963,"timestamp":839450671284,"duration":86289,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":804,"name":"build-module-js","id":962,"timestamp":839450671276,"duration":86759,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Actions\\condition.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":970,"name":"read-resource","id":971,"timestamp":839450671337,"duration":86708,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":806,"name":"build-module-js","id":970,"timestamp":839450671330,"duration":87177,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Audio\\analyser.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":966,"name":"read-resource","id":967,"timestamp":839450671311,"duration":87206,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":804,"name":"build-module-js","id":966,"timestamp":839450671303,"duration":88109,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Actions\\directActions.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":974,"name":"read-resource","id":975,"timestamp":839450671364,"duration":88061,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":806,"name":"build-module-js","id":974,"timestamp":839450671356,"duration":88812,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Audio\\audioEngine.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":976,"name":"read-resource","id":977,"timestamp":839450671377,"duration":88804,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":806,"name":"build-module-js","id":976,"timestamp":839450671369,"duration":89341,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Audio\\soundTrack.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":978,"name":"read-resource","id":979,"timestamp":839450671390,"duration":89332,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":806,"name":"build-module-js","id":978,"timestamp":839450671382,"duration":89778,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Audio\\weightedsound.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":980,"name":"read-resource","id":981,"timestamp":839450671404,"duration":89768,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":806,"name":"build-module-js","id":980,"timestamp":839450671395,"duration":94946,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Audio\\sound.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":982,"name":"read-resource","id":983,"timestamp":839450671417,"duration":94937,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":982,"timestamp":839450671409,"duration":97129,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\animatable.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":986,"name":"read-resource","id":987,"timestamp":839450671442,"duration":97109,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":986,"timestamp":839450671434,"duration":97257,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\animationPropertiesOverride.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":990,"name":"read-resource","id":991,"timestamp":839450671468,"duration":97234,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":990,"timestamp":839450671460,"duration":97909,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\easing.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":984,"name":"read-resource","id":985,"timestamp":839450671429,"duration":97951,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":984,"timestamp":839450671422,"duration":102328,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\animation.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":994,"name":"read-resource","id":995,"timestamp":839450671492,"duration":102270,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":994,"timestamp":839450671485,"duration":102431,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\animationEvent.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":988,"name":"read-resource","id":989,"timestamp":839450671455,"duration":102472,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":988,"timestamp":839450671446,"duration":103767,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\runtimeAnimation.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":972,"name":"read-resource","id":973,"timestamp":839450671351,"duration":103875,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":806,"name":"build-module-js","id":972,"timestamp":839450671343,"duration":105073,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Audio\\audioSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":992,"name":"read-resource","id":993,"timestamp":839450671481,"duration":104947,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":992,"timestamp":839450671473,"duration":106731,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\animationGroup.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":1000,"name":"read-resource","id":1001,"timestamp":839450671565,"duration":106651,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":1000,"timestamp":839450671557,"duration":106738,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\animatable.interface.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":996,"name":"read-resource","id":997,"timestamp":839450671505,"duration":106799,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":996,"timestamp":839450671498,"duration":106928,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\animationKey.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":998,"name":"read-resource","id":999,"timestamp":839450671551,"duration":106885,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":998,"timestamp":839450671510,"duration":107145,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\pathCursor.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":1006,"name":"read-resource","id":1007,"timestamp":839450671605,"duration":107062,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":1006,"timestamp":839450671597,"duration":107189,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\animationRange.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":1004,"name":"read-resource","id":1005,"timestamp":839450671591,"duration":107223,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":808,"name":"build-module-js","id":1004,"timestamp":839450671584,"duration":107456,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Animations\\animationGroupMask.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":1002,"name":"read-resource","id":1003,"timestamp":839450671579,"duration":107489,"tags":{},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":810,"name":"build-module-js","id":1002,"timestamp":839450671571,"duration":109172,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Bones\\bone.js","layer":"app-pages-browser"},"startTime":1704500737855},{"traceId":"4dea77cda8cb5b99","parentId":1008,"name":"read-resource","id":1009,"timestamp":839450671963,"duration":124297,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":810,"name":"build-module-js","id":1008,"timestamp":839450671942,"duration":125212,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Bones\\boneIKController.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1012,"name":"read-resource","id":1013,"timestamp":839450671999,"duration":125168,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":810,"name":"build-module-js","id":1012,"timestamp":839450671990,"duration":126476,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Bones\\boneLookController.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1010,"name":"read-resource","id":1011,"timestamp":839450671983,"duration":126496,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":810,"name":"build-module-js","id":1010,"timestamp":839450671973,"duration":128490,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Bones\\skeleton.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1014,"name":"read-resource","id":1015,"timestamp":839450672013,"duration":128463,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":814,"name":"build-module-js","id":1014,"timestamp":839450672005,"duration":128669,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Buffers\\dataBuffer.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1016,"name":"read-resource","id":1017,"timestamp":839450672029,"duration":128656,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":814,"name":"build-module-js","id":1016,"timestamp":839450672021,"duration":130098,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Buffers\\buffer.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1020,"name":"read-resource","id":1021,"timestamp":839450672055,"duration":130078,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":814,"name":"build-module-js","id":1020,"timestamp":839450672048,"duration":130456,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Buffers\\storageBuffer.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1018,"name":"read-resource","id":1019,"timestamp":839450672043,"duration":130474,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":822,"name":"build-module-js","id":1018,"timestamp":839450672035,"duration":137295,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Compute\\computeEffect.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1024,"name":"read-resource","id":1025,"timestamp":839450672081,"duration":137261,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":824,"name":"build-module-js","id":1024,"timestamp":839450672074,"duration":138018,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Culling\\boundingBox.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1026,"name":"read-resource","id":1027,"timestamp":839450672094,"duration":138010,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":814,"name":"build-module-js","id":1026,"timestamp":839450672087,"duration":138563,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Buffers\\buffer.align.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1028,"name":"read-resource","id":1029,"timestamp":839450672107,"duration":138555,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":824,"name":"build-module-js","id":1028,"timestamp":839450672099,"duration":139218,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Culling\\boundingInfo.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1036,"name":"read-resource","id":1037,"timestamp":839450672159,"duration":139171,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":818,"name":"build-module-js","id":1036,"timestamp":839450672151,"duration":139298,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Collisions\\intersectionInfo.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1030,"name":"read-resource","id":1031,"timestamp":839450672120,"duration":139339,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":824,"name":"build-module-js","id":1030,"timestamp":839450672112,"duration":139771,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Culling\\boundingSphere.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1022,"name":"read-resource","id":1023,"timestamp":839450672069,"duration":139829,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":822,"name":"build-module-js","id":1022,"timestamp":839450672060,"duration":140674,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Compute\\computeShader.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1034,"name":"read-resource","id":1035,"timestamp":839450672146,"duration":140600,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":818,"name":"build-module-js","id":1034,"timestamp":839450672138,"duration":141891,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Collisions\\collider.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1040,"name":"read-resource","id":1041,"timestamp":839450672184,"duration":141858,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":818,"name":"build-module-js","id":1040,"timestamp":839450672176,"duration":142012,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Collisions\\meshCollisionData.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1038,"name":"read-resource","id":1039,"timestamp":839450672172,"duration":142026,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":818,"name":"build-module-js","id":1038,"timestamp":839450672164,"duration":142351,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Collisions\\collisionCoordinator.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1042,"name":"read-resource","id":1043,"timestamp":839450672197,"duration":142334,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1042,"timestamp":839450672189,"duration":143604,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\targetCamera.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1044,"name":"read-resource","id":1045,"timestamp":839450672211,"duration":143595,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1044,"timestamp":839450672203,"duration":144111,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\cameraInputsManager.js","layer":"app-pages-browser"},"startTime":1704500737856}] +[{"traceId":"4dea77cda8cb5b99","parentId":1032,"name":"read-resource","id":1033,"timestamp":839450672133,"duration":144320,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":824,"name":"build-module-js","id":1032,"timestamp":839450672126,"duration":148627,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Culling\\ray.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1048,"name":"read-resource","id":1049,"timestamp":839450672237,"duration":148529,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1048,"timestamp":839450672230,"duration":148796,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\freeCameraInputsManager.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1046,"name":"read-resource","id":1047,"timestamp":839450672224,"duration":148813,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1046,"timestamp":839450672216,"duration":149522,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\freeCamera.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1052,"name":"read-resource","id":1053,"timestamp":839450672263,"duration":149487,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1052,"timestamp":839450672255,"duration":149659,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\arcRotateCameraInputsManager.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1054,"name":"read-resource","id":1055,"timestamp":839450672277,"duration":149649,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1054,"timestamp":839450672269,"duration":149890,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\touchCamera.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1050,"name":"read-resource","id":1051,"timestamp":839450672250,"duration":149920,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1050,"timestamp":839450672242,"duration":152128,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\arcRotateCamera.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1058,"name":"read-resource","id":1059,"timestamp":839450672303,"duration":152080,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1058,"timestamp":839450672296,"duration":152749,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\flyCamera.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1056,"name":"read-resource","id":1057,"timestamp":839450672290,"duration":152765,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1056,"timestamp":839450672282,"duration":152922,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\flyCameraInputsManager.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1062,"name":"read-resource","id":1063,"timestamp":839450672328,"duration":152885,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1062,"timestamp":839450672321,"duration":153528,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\followCamera.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1060,"name":"read-resource","id":1061,"timestamp":839450672316,"duration":153545,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1060,"timestamp":839450672308,"duration":153876,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\deviceOrientationCamera.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1064,"name":"read-resource","id":1065,"timestamp":839450672342,"duration":153855,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1064,"timestamp":839450672334,"duration":154064,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\followCameraInputsManager.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1068,"name":"read-resource","id":1069,"timestamp":839450672367,"duration":154041,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1068,"timestamp":839450672359,"duration":154200,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\gamepadCamera.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1070,"name":"read-resource","id":1071,"timestamp":839450672380,"duration":154190,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1070,"timestamp":839450672372,"duration":154346,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\virtualJoysticksCamera.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":1066,"name":"read-resource","id":1067,"timestamp":839450672355,"duration":154382,"tags":{},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1066,"timestamp":839450672347,"duration":154628,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\universalCamera.js","layer":"app-pages-browser"},"startTime":1704500737856},{"traceId":"4dea77cda8cb5b99","parentId":504,"name":"font-loader","id":505,"timestamp":839450320068,"duration":525961,"tags":{},"startTime":1704500737504},{"traceId":"4dea77cda8cb5b99","parentId":504,"name":"postcss","id":1152,"timestamp":839450846215,"duration":870,"tags":{},"startTime":1704500738030},{"traceId":"4dea77cda8cb5b99","parentId":437,"name":"next-font-loader","id":504,"timestamp":839450302496,"duration":544629,"tags":{},"startTime":1704500737486},{"traceId":"4dea77cda8cb5b99","parentId":437,"name":"css-loader","id":1153,"timestamp":839450847105,"duration":5779,"tags":{"astUsed":"true"},"startTime":1704500738031},{"traceId":"4dea77cda8cb5b99","parentId":302,"name":"build-module-tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}","id":437,"timestamp":839449704356,"duration":1148797,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css.webpack[javascript/auto]!=!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\css-loader\\src\\index.js??ruleSet[1].rules[12].oneOf[2].use[1]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\build\\webpack\\loaders\\next-font-loader\\index.js??ruleSet[1].rules[12].oneOf[2].use[2]!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}","layer":"null"},"startTime":1704500736888},{"traceId":"4dea77cda8cb5b99","parentId":134,"name":"build-module-tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}","id":302,"timestamp":839449674209,"duration":1181187,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}","layer":"app-pages-browser"},"startTime":1704500736858},{"traceId":"4dea77cda8cb5b99","parentId":1072,"name":"read-resource","id":1073,"timestamp":839450842388,"duration":16328,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":816,"name":"build-module-js","id":1072,"timestamp":839450842354,"duration":16481,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\behavior.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1080,"name":"read-resource","id":1081,"timestamp":839450842467,"duration":16380,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":828,"name":"build-module-js","id":1080,"timestamp":839450842458,"duration":16978,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Debug\\rayHelper.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1074,"name":"read-resource","id":1075,"timestamp":839450842420,"duration":17027,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":828,"name":"build-module-js","id":1074,"timestamp":839450842407,"duration":17668,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Debug\\axesViewer.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1082,"name":"read-resource","id":1083,"timestamp":839450842482,"duration":17604,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":828,"name":"build-module-js","id":1082,"timestamp":839450842474,"duration":20232,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Debug\\skeletonViewer.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1076,"name":"read-resource","id":1077,"timestamp":839450842437,"duration":20280,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":828,"name":"build-module-js","id":1076,"timestamp":839450842428,"duration":20843,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Debug\\debugLayer.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1084,"name":"read-resource","id":1085,"timestamp":839450842496,"duration":20787,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":828,"name":"build-module-js","id":1084,"timestamp":839450842488,"duration":20868,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Debug\\ISkeletonViewer.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1088,"name":"read-resource","id":1089,"timestamp":839450842525,"duration":20838,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":812,"name":"build-module-js","id":1088,"timestamp":839450842516,"duration":21383,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\BakedVertexAnimation\\bakedVertexAnimationManager.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1078,"name":"read-resource","id":1079,"timestamp":839450842452,"duration":21458,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":828,"name":"build-module-js","id":1078,"timestamp":839450842443,"duration":23751,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Debug\\physicsViewer.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1086,"name":"read-resource","id":1087,"timestamp":839450842510,"duration":23696,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":828,"name":"build-module-js","id":1086,"timestamp":839450842502,"duration":23935,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Debug\\boneAxesViewer.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1090,"name":"read-resource","id":1091,"timestamp":839450842538,"duration":23910,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":812,"name":"build-module-js","id":1090,"timestamp":839450842530,"duration":24281,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\BakedVertexAnimation\\vertexAnimationBaker.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1092,"name":"read-resource","id":1093,"timestamp":839450842552,"duration":24270,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":828,"name":"build-module-js","id":1092,"timestamp":839450842544,"duration":25683,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Debug\\directionalLightFrustumViewer.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1098,"name":"read-resource","id":1099,"timestamp":839450842608,"duration":25631,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":832,"name":"build-module-js","id":1098,"timestamp":839450842596,"duration":25920,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gamepads\\gamepadSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1096,"name":"read-resource","id":1097,"timestamp":839450842588,"duration":25940,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":832,"name":"build-module-js","id":1096,"timestamp":839450842579,"duration":26548,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gamepads\\gamepadManager.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1094,"name":"read-resource","id":1095,"timestamp":839450842569,"duration":26568,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":832,"name":"build-module-js","id":1094,"timestamp":839450842557,"duration":27055,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gamepads\\gamepad.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1102,"name":"read-resource","id":1103,"timestamp":839450842635,"duration":26988,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":832,"name":"build-module-js","id":1102,"timestamp":839450842627,"duration":27653,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gamepads\\dualShockGamepad.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1100,"name":"read-resource","id":1101,"timestamp":839450842622,"duration":27670,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":832,"name":"build-module-js","id":1100,"timestamp":839450842614,"duration":30620,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gamepads\\xboxGamepad.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1104,"name":"read-resource","id":1105,"timestamp":839450842650,"duration":30597,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":830,"name":"build-module-js","id":1104,"timestamp":839450842641,"duration":30861,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Events\\pointerEvents.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1108,"name":"read-resource","id":1109,"timestamp":839450842676,"duration":30837,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":830,"name":"build-module-js","id":1108,"timestamp":839450842669,"duration":30999,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Events\\deviceInputEvents.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1106,"name":"read-resource","id":1107,"timestamp":839450842663,"duration":31014,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":830,"name":"build-module-js","id":1106,"timestamp":839450842656,"duration":31187,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Events\\keyboardEvents.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1110,"name":"read-resource","id":1111,"timestamp":839450842696,"duration":31158,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":830,"name":"build-module-js","id":1110,"timestamp":839450842682,"duration":31318,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Events\\clipboardEvents.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1116,"name":"read-resource","id":1117,"timestamp":839450842741,"duration":31268,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":806,"name":"build-module-js","id":1116,"timestamp":839450842733,"duration":31343,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Audio\\Interfaces\\IAudioEngine.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1114,"name":"read-resource","id":1115,"timestamp":839450842727,"duration":31356,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1114,"timestamp":839450842719,"duration":31415,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\engineCapabilities.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1112,"name":"read-resource","id":1113,"timestamp":839450842713,"duration":31428,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1112,"timestamp":839450842705,"duration":32051,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\constants.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1118,"name":"read-resource","id":1119,"timestamp":839450842754,"duration":32012,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":806,"name":"build-module-js","id":1118,"timestamp":839450842746,"duration":32077,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Audio\\Interfaces\\ISoundOptions.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1122,"name":"read-resource","id":1123,"timestamp":839450842783,"duration":32047,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":824,"name":"build-module-js","id":1122,"timestamp":839450842775,"duration":32140,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Culling\\Octrees\\index.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1124,"name":"read-resource","id":1125,"timestamp":839450842796,"duration":32126,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1124,"timestamp":839450842788,"duration":32188,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\instancingAttributeInfo.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1120,"name":"read-resource","id":1121,"timestamp":839450842769,"duration":32214,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1120,"timestamp":839450842760,"duration":32391,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\index.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1128,"name":"read-resource","id":1129,"timestamp":839450842823,"duration":32336,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1128,"timestamp":839450842814,"duration":32440,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Stereoscopic\\index.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1132,"name":"read-resource","id":1133,"timestamp":839450842850,"duration":32413,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1132,"timestamp":839450842842,"duration":32486,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\RigModes\\index.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1136,"name":"read-resource","id":1137,"timestamp":839450842878,"duration":32457,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":826,"name":"build-module-js","id":1136,"timestamp":839450842869,"duration":32517,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\DeviceInput\\InputDevices\\deviceTypes.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1142,"name":"read-resource","id":1143,"timestamp":839450842940,"duration":32452,"tags":{},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":826,"name":"build-module-js","id":1142,"timestamp":839450842932,"duration":32904,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\DeviceInput\\InputDevices\\deviceSourceManager.js","layer":"app-pages-browser"},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":1130,"name":"read-resource","id":1131,"timestamp":839450842836,"duration":33011,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":816,"name":"build-module-js","id":1130,"timestamp":839450842829,"duration":33098,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Cameras\\index.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1126,"name":"read-resource","id":1127,"timestamp":839450842809,"duration":33126,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1126,"timestamp":839450842801,"duration":47196,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\thinEngine.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1138,"name":"read-resource","id":1139,"timestamp":839450842908,"duration":47104,"tags":{},"startTime":1704500738026}] +[{"traceId":"4dea77cda8cb5b99","parentId":826,"name":"build-module-js","id":1138,"timestamp":839450842884,"duration":47429,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\DeviceInput\\InputDevices\\deviceSource.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1140,"name":"read-resource","id":1141,"timestamp":839450842926,"duration":47399,"tags":{},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":826,"name":"build-module-js","id":1140,"timestamp":839450842916,"duration":48119,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\DeviceInput\\InputDevices\\deviceEnums.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1144,"name":"read-resource","id":1145,"timestamp":839450842954,"duration":48093,"tags":{},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":816,"name":"build-module-js","id":1144,"timestamp":839450842946,"duration":48226,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Meshes\\index.js","layer":"app-pages-browser"},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":1134,"name":"read-resource","id":1135,"timestamp":839450842863,"duration":48317,"tags":{},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":820,"name":"build-module-js","id":1134,"timestamp":839450842855,"duration":48467,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\VR\\index.js","layer":"app-pages-browser"},"startTime":1704500738026},{"traceId":"4dea77cda8cb5b99","parentId":1148,"name":"read-resource","id":1149,"timestamp":839450842987,"duration":48350,"tags":{},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1148,"timestamp":839450842978,"duration":48427,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\IPipelineContext.js","layer":"app-pages-browser"},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":1150,"name":"read-resource","id":1151,"timestamp":839450842999,"duration":48413,"tags":{},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1150,"timestamp":839450842992,"duration":51608,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\nullEngine.js","layer":"app-pages-browser"},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":1146,"name":"read-resource","id":1147,"timestamp":839450842969,"duration":51643,"tags":{},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1146,"timestamp":839450842959,"duration":54403,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\engine.js","layer":"app-pages-browser"},"startTime":1704500738027},{"traceId":"4dea77cda8cb5b99","parentId":1154,"name":"read-resource","id":1155,"timestamp":839450853931,"duration":46236,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1154,"timestamp":839450853906,"duration":46355,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\ICanvas.js","layer":"app-pages-browser"},"startTime":1704500738037},{"traceId":"4dea77cda8cb5b99","parentId":1164,"name":"read-resource","id":1165,"timestamp":839450854029,"duration":46242,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1164,"timestamp":839450854021,"duration":46314,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\engineFeatures.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1162,"name":"read-resource","id":1163,"timestamp":839450854015,"duration":46328,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1162,"timestamp":839450854007,"duration":46497,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\engineFactory.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"read-resource","id":1157,"timestamp":839450853962,"duration":46552,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1156,"timestamp":839450853949,"duration":54766,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\webgpuEngine.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1158,"name":"read-resource","id":1159,"timestamp":839450853984,"duration":54744,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1158,"timestamp":839450853973,"duration":54968,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\performanceConfigurator.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1166,"name":"read-resource","id":1167,"timestamp":839450854044,"duration":54909,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1166,"timestamp":839450854035,"duration":54990,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\IMaterialContext.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1160,"name":"read-resource","id":1161,"timestamp":839450854001,"duration":55031,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1160,"timestamp":839450853991,"duration":61312,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\nativeEngine.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1168,"name":"read-resource","id":1169,"timestamp":839450854059,"duration":61257,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1168,"timestamp":839450854050,"duration":61354,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\IDrawContext.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1174,"name":"read-resource","id":1175,"timestamp":839450854099,"duration":61314,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":838,"name":"build-module-js","id":1174,"timestamp":839450854092,"duration":61569,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Instrumentation\\engineInstrumentation.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1172,"name":"read-resource","id":1173,"timestamp":839450854085,"duration":61586,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":838,"name":"build-module-js","id":1172,"timestamp":839450854078,"duration":62467,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Instrumentation\\sceneInstrumentation.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1176,"name":"read-resource","id":1177,"timestamp":839450854114,"duration":62443,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1176,"timestamp":839450854105,"duration":63253,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\renderTargetWrapper.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1180,"name":"read-resource","id":1181,"timestamp":839450854142,"duration":63228,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":840,"name":"build-module-js","id":1180,"timestamp":839450854134,"duration":64174,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Helpers\\environmentHelper.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1182,"name":"read-resource","id":1183,"timestamp":839450854156,"duration":64164,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":840,"name":"build-module-js","id":1182,"timestamp":839450854148,"duration":64660,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Helpers\\sceneHelpers.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1170,"name":"read-resource","id":1171,"timestamp":839450854072,"duration":64747,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1170,"timestamp":839450854064,"duration":64926,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\shaderStore.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1186,"name":"read-resource","id":1187,"timestamp":839450854184,"duration":64817,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1186,"timestamp":839450854175,"duration":65540,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\axisDragGizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1184,"name":"read-resource","id":1185,"timestamp":839450854169,"duration":65558,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":840,"name":"build-module-js","id":1184,"timestamp":839450854161,"duration":65754,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Helpers\\photoDome.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1178,"name":"read-resource","id":1179,"timestamp":839450854128,"duration":65801,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":838,"name":"build-module-js","id":1178,"timestamp":839450854119,"duration":65901,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Instrumentation\\timeToken.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1188,"name":"read-resource","id":1189,"timestamp":839450854198,"duration":65831,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":840,"name":"build-module-js","id":1188,"timestamp":839450854190,"duration":66087,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Helpers\\videoDome.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1190,"name":"read-resource","id":1191,"timestamp":839450854212,"duration":66076,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1190,"timestamp":839450854204,"duration":67285,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\gizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1192,"name":"read-resource","id":1193,"timestamp":839450854226,"duration":67275,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1192,"timestamp":839450854218,"duration":68198,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\axisScaleGizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1196,"name":"read-resource","id":1197,"timestamp":839450854254,"duration":68175,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1196,"timestamp":839450854246,"duration":68922,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\gizmoManager.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1198,"name":"read-resource","id":1199,"timestamp":839450854267,"duration":68912,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1198,"timestamp":839450854259,"duration":71724,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\planeRotationGizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1200,"name":"read-resource","id":1201,"timestamp":839450854280,"duration":71715,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1200,"timestamp":839450854273,"duration":72332,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\positionGizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1202,"name":"read-resource","id":1203,"timestamp":839450854295,"duration":72321,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1202,"timestamp":839450854286,"duration":72911,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\rotationGizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1204,"name":"read-resource","id":1205,"timestamp":839450854311,"duration":72897,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1204,"timestamp":839450854303,"duration":73863,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\lightGizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1194,"name":"read-resource","id":1195,"timestamp":839450854240,"duration":73938,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1194,"timestamp":839450854231,"duration":75990,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\boundingBoxGizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1206,"name":"read-resource","id":1207,"timestamp":839450854325,"duration":75909,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1206,"timestamp":839450854317,"duration":76573,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\scaleGizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1208,"name":"read-resource","id":1209,"timestamp":839450854338,"duration":76567,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1208,"timestamp":839450854330,"duration":77151,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\planeDragGizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1210,"name":"read-resource","id":1211,"timestamp":839450854351,"duration":77142,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":834,"name":"build-module-js","id":1210,"timestamp":839450854343,"duration":77712,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Gizmos\\cameraGizmo.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1212,"name":"read-resource","id":1213,"timestamp":839450854365,"duration":77702,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":842,"name":"build-module-js","id":1212,"timestamp":839450854356,"duration":77918,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\LensFlares\\lensFlare.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1216,"name":"read-resource","id":1217,"timestamp":839450854392,"duration":77893,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":842,"name":"build-module-js","id":1216,"timestamp":839450854384,"duration":78360,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\LensFlares\\lensFlareSystemSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1214,"name":"read-resource","id":1215,"timestamp":839450854378,"duration":78377,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":842,"name":"build-module-js","id":1214,"timestamp":839450854371,"duration":81500,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\LensFlares\\lensFlareSystem.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1218,"name":"read-resource","id":1219,"timestamp":839450854405,"duration":81480,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":846,"name":"build-module-js","id":1218,"timestamp":839450854397,"duration":82071,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Layers\\effectLayerSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1220,"name":"read-resource","id":1221,"timestamp":839450854419,"duration":82061,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":846,"name":"build-module-js","id":1220,"timestamp":839450854410,"duration":83769,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Layers\\highlightLayer.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1222,"name":"read-resource","id":1223,"timestamp":839450854433,"duration":83784,"tags":{},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":846,"name":"build-module-js","id":1222,"timestamp":839450854425,"duration":86405,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Layers\\effectLayer.js","layer":"app-pages-browser"},"startTime":1704500738038},{"traceId":"4dea77cda8cb5b99","parentId":1228,"name":"read-resource","id":1229,"timestamp":839450856538,"duration":89795,"tags":{},"startTime":1704500738040},{"traceId":"4dea77cda8cb5b99","parentId":846,"name":"build-module-js","id":1228,"timestamp":839450856529,"duration":91919,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Layers\\layerSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738040},{"traceId":"4dea77cda8cb5b99","parentId":1224,"name":"read-resource","id":1225,"timestamp":839450856492,"duration":91968,"tags":{},"startTime":1704500738040},{"traceId":"4dea77cda8cb5b99","parentId":846,"name":"build-module-js","id":1224,"timestamp":839450856469,"duration":93029,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Layers\\glowLayer.js","layer":"app-pages-browser"},"startTime":1704500738040},{"traceId":"4dea77cda8cb5b99","parentId":1226,"name":"read-resource","id":1227,"timestamp":839450856521,"duration":92989,"tags":{},"startTime":1704500738040},{"traceId":"4dea77cda8cb5b99","parentId":846,"name":"build-module-js","id":1226,"timestamp":839450856507,"duration":93588,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Layers\\layer.js","layer":"app-pages-browser"},"startTime":1704500738040},{"traceId":"4dea77cda8cb5b99","parentId":1230,"name":"read-resource","id":1231,"timestamp":839450856554,"duration":93552,"tags":{},"startTime":1704500738040},{"traceId":"4dea77cda8cb5b99","parentId":848,"name":"build-module-js","id":1230,"timestamp":839450856545,"duration":94099,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Loading\\loadingScreen.js","layer":"app-pages-browser"},"startTime":1704500738040},{"traceId":"4dea77cda8cb5b99","parentId":1232,"name":"read-resource","id":1233,"timestamp":839450856569,"duration":94086,"tags":{},"startTime":1704500738040},{"traceId":"4dea77cda8cb5b99","parentId":848,"name":"build-module-js","id":1232,"timestamp":839450856560,"duration":95670,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Loading\\sceneLoader.js","layer":"app-pages-browser"},"startTime":1704500738040},{"traceId":"4dea77cda8cb5b99","parentId":1234,"name":"read-resource","id":1235,"timestamp":839450858414,"duration":97897,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":848,"name":"build-module-js","id":1234,"timestamp":839450858338,"duration":98134,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Loading\\sceneLoaderFlags.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1242,"name":"read-resource","id":1243,"timestamp":839450858498,"duration":97985,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1242,"timestamp":839450858489,"duration":99928,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\effect.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1238,"name":"read-resource","id":1239,"timestamp":839450858467,"duration":99963,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1238,"timestamp":839450858456,"duration":100072,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\iEffectFallbacks.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1236,"name":"read-resource","id":1237,"timestamp":839450858447,"duration":100091,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1236,"timestamp":839450858432,"duration":102744,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\colorCurves.js","layer":"app-pages-browser"},"startTime":1704500738042}] +[{"traceId":"4dea77cda8cb5b99","parentId":1240,"name":"read-resource","id":1241,"timestamp":839450858482,"duration":102816,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1240,"timestamp":839450858473,"duration":103120,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\effectFallbacks.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1248,"name":"read-resource","id":1249,"timestamp":839450858541,"duration":103064,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1248,"timestamp":839450858533,"duration":103560,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\clipPlaneMaterialHelper.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1246,"name":"read-resource","id":1247,"timestamp":839450858528,"duration":103577,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1246,"timestamp":839450858518,"duration":105569,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\material.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1244,"name":"read-resource","id":1245,"timestamp":839450858513,"duration":105588,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1244,"timestamp":839450858505,"duration":105869,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\fresnelParameters.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1252,"name":"read-resource","id":1253,"timestamp":839450858569,"duration":105815,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1252,"timestamp":839450858560,"duration":106304,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\multiMaterial.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1254,"name":"read-resource","id":1255,"timestamp":839450858582,"duration":106294,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1254,"timestamp":839450858574,"duration":106542,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\pushMaterial.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1250,"name":"read-resource","id":1251,"timestamp":839450858554,"duration":106572,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1250,"timestamp":839450858547,"duration":107031,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\materialDefines.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1256,"name":"read-resource","id":1257,"timestamp":839450858596,"duration":106994,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1256,"timestamp":839450858588,"duration":108495,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\materialHelper.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1264,"name":"read-resource","id":1265,"timestamp":839450858649,"duration":108445,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1264,"timestamp":839450858641,"duration":108946,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\materialFlags.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1268,"name":"read-resource","id":1269,"timestamp":839450858676,"duration":108922,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1268,"timestamp":839450858668,"duration":111728,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGL\\webGLPipelineContext.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1258,"name":"read-resource","id":1259,"timestamp":839450858610,"duration":111800,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1258,"timestamp":839450858602,"duration":114518,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\shaderMaterial.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1260,"name":"read-resource","id":1261,"timestamp":839450858623,"duration":114510,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1260,"timestamp":839450858615,"duration":114652,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\shaderLanguage.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"read-resource","id":1267,"timestamp":839450858662,"duration":114615,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1266,"timestamp":839450858654,"duration":114794,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\index.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1262,"name":"read-resource","id":1263,"timestamp":839450858636,"duration":114822,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1262,"timestamp":839450858628,"duration":118243,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\standardMaterial.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1270,"name":"read-resource","id":1271,"timestamp":839450858690,"duration":125058,"tags":{},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1270,"timestamp":839450858682,"duration":125597,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGL\\webGL2ShaderProcessors.js","layer":"app-pages-browser"},"startTime":1704500738042},{"traceId":"4dea77cda8cb5b99","parentId":1272,"name":"read-resource","id":1273,"timestamp":839451004616,"duration":6854,"tags":{},"startTime":1704500738188},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1272,"timestamp":839451004582,"duration":7143,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGL\\webGLHardwareTexture.js","layer":"app-pages-browser"},"startTime":1704500738188},{"traceId":"4dea77cda8cb5b99","parentId":1274,"name":"read-resource","id":1275,"timestamp":839451004646,"duration":7091,"tags":{},"startTime":1704500738188},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1274,"timestamp":839451004633,"duration":7192,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Native\\index.js","layer":"app-pages-browser"},"startTime":1704500738188},{"traceId":"4dea77cda8cb5b99","parentId":1276,"name":"read-resource","id":1277,"timestamp":839451004664,"duration":7170,"tags":{},"startTime":1704500738188},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1276,"timestamp":839451004654,"duration":11866,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuCacheRenderPipeline.js","layer":"app-pages-browser"},"startTime":1704500738188},{"traceId":"4dea77cda8cb5b99","parentId":1278,"name":"read-resource","id":1279,"timestamp":839451008446,"duration":9229,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1278,"timestamp":839451008419,"duration":10402,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuConstants.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1286,"name":"read-resource","id":1287,"timestamp":839451008521,"duration":10312,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1286,"timestamp":839451008513,"duration":10639,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuDrawContext.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1282,"name":"read-resource","id":1283,"timestamp":839451008489,"duration":10674,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1282,"timestamp":839451008477,"duration":11473,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuCacheBindGroups.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1280,"name":"read-resource","id":1281,"timestamp":839451008469,"duration":11493,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1280,"timestamp":839451008457,"duration":11787,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuCacheRenderPipelineTree.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1290,"name":"read-resource","id":1291,"timestamp":839451008551,"duration":11704,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1290,"timestamp":839451008541,"duration":12634,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\shaderCodeInliner.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1292,"name":"read-resource","id":1293,"timestamp":839451008564,"duration":12622,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1292,"timestamp":839451008556,"duration":12706,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\iShaderProcessor.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1288,"name":"read-resource","id":1289,"timestamp":839451008535,"duration":12735,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1288,"timestamp":839451008527,"duration":13014,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuTintWASM.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1300,"name":"read-resource","id":1301,"timestamp":839451008677,"duration":12874,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1300,"timestamp":839451008665,"duration":13056,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\drawWrapper.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1284,"name":"read-resource","id":1285,"timestamp":839451008506,"duration":13227,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1284,"timestamp":839451008495,"duration":14284,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuCacheSampler.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1296,"name":"read-resource","id":1297,"timestamp":839451008593,"duration":14198,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1296,"timestamp":839451008585,"duration":14782,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\effectRenderer.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1298,"name":"read-resource","id":1299,"timestamp":839451008655,"duration":14724,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1298,"timestamp":839451008599,"duration":15715,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\shadowDepthWrapper.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1302,"name":"read-resource","id":1303,"timestamp":839451008692,"duration":15634,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1302,"timestamp":839451008684,"duration":16092,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\materialPluginBase.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1308,"name":"read-resource","id":1309,"timestamp":839451008735,"duration":16052,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1308,"timestamp":839451008728,"duration":16495,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\material.detailMapConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1304,"name":"read-resource","id":1305,"timestamp":839451008706,"duration":16527,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1304,"timestamp":839451008698,"duration":20874,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\materialPluginManager.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1310,"name":"read-resource","id":1311,"timestamp":839451008749,"duration":20835,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":848,"name":"build-module-js","id":1310,"timestamp":839451008741,"duration":20934,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Loading\\Plugins\\index.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1306,"name":"read-resource","id":1307,"timestamp":839451008722,"duration":20962,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1306,"timestamp":839451008712,"duration":21123,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\materialPluginEvent.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1312,"name":"read-resource","id":1313,"timestamp":839451008761,"duration":21084,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1312,"timestamp":839451008754,"duration":21166,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Background\\index.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"read-resource","id":1315,"timestamp":839451008776,"duration":21151,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1314,"timestamp":839451008767,"duration":21370,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\index.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"read-resource","id":1295,"timestamp":839451008579,"duration":21566,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":836,"name":"build-module-js","id":1294,"timestamp":839451008571,"duration":21661,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\index.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1318,"name":"read-resource","id":1319,"timestamp":839451008802,"duration":21437,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1318,"timestamp":839451008795,"duration":21545,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\index.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1320,"name":"read-resource","id":1321,"timestamp":839451008815,"duration":21532,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1320,"timestamp":839451008808,"duration":21635,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\index.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1322,"name":"read-resource","id":1323,"timestamp":839451008831,"duration":21619,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1322,"timestamp":839451008821,"duration":22028,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\material.decalMapConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1316,"name":"read-resource","id":1317,"timestamp":839451008789,"duration":22071,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1316,"timestamp":839451008781,"duration":22149,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Occlusion\\index.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1326,"name":"read-resource","id":1327,"timestamp":839451008858,"duration":22080,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1326,"timestamp":839451008850,"duration":22324,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\materialPluginFactoryExport.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1324,"name":"read-resource","id":1325,"timestamp":839451008844,"duration":22339,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1324,"timestamp":839451008837,"duration":23326,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\meshDebugPluginMaterial.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1330,"name":"read-resource","id":1331,"timestamp":839451008885,"duration":23288,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1330,"timestamp":839451008877,"duration":23424,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\material.decalMap.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1328,"name":"read-resource","id":1329,"timestamp":839451008871,"duration":23440,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":844,"name":"build-module-js","id":1328,"timestamp":839451008864,"duration":24056,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\directionalLight.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1336,"name":"read-resource","id":1337,"timestamp":839451008925,"duration":24005,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":844,"name":"build-module-js","id":1336,"timestamp":839451008918,"duration":24306,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\hemisphericLight.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1332,"name":"read-resource","id":1333,"timestamp":839451008899,"duration":24335,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":844,"name":"build-module-js","id":1332,"timestamp":839451008890,"duration":24754,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\shadowLight.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1340,"name":"read-resource","id":1341,"timestamp":839451008954,"duration":24701,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":852,"name":"build-module-js","id":1340,"timestamp":839451008946,"duration":25064,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.functions.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1334,"name":"read-resource","id":1335,"timestamp":839451008913,"duration":25108,"tags":{},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":844,"name":"build-module-js","id":1334,"timestamp":839451008905,"duration":25882,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\spotLight.js","layer":"app-pages-browser"},"startTime":1704500738192},{"traceId":"4dea77cda8cb5b99","parentId":1338,"name":"read-resource","id":1339,"timestamp":839451008940,"duration":25858,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":844,"name":"build-module-js","id":1338,"timestamp":839451008933,"duration":26268,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\pointLight.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1342,"name":"read-resource","id":1343,"timestamp":839451008967,"duration":26245,"tags":{},"startTime":1704500738193}] +[{"traceId":"4dea77cda8cb5b99","parentId":852,"name":"build-module-js","id":1342,"timestamp":839451008959,"duration":26895,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.scalar.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1344,"name":"read-resource","id":1345,"timestamp":839451008981,"duration":26972,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":852,"name":"build-module-js","id":1344,"timestamp":839451008972,"duration":27162,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1348,"name":"read-resource","id":1349,"timestamp":839451009008,"duration":27137,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":852,"name":"build-module-js","id":1348,"timestamp":839451009001,"duration":28245,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\sphericalPolynomial.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1346,"name":"read-resource","id":1347,"timestamp":839451008995,"duration":28263,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":852,"name":"build-module-js","id":1346,"timestamp":839451008987,"duration":29051,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.polar.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1350,"name":"read-resource","id":1351,"timestamp":839451009026,"duration":29024,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":854,"name":"build-module-js","id":1350,"timestamp":839451009018,"duration":30014,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Morph\\morphTargetManager.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1352,"name":"read-resource","id":1353,"timestamp":839451009041,"duration":30002,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":854,"name":"build-module-js","id":1352,"timestamp":839451009032,"duration":33787,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Morph\\morphTarget.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1356,"name":"read-resource","id":1357,"timestamp":839451009068,"duration":33763,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1356,"timestamp":839451009061,"duration":35589,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\csg.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1354,"name":"read-resource","id":1355,"timestamp":839451009055,"duration":35606,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1354,"timestamp":839451009047,"duration":35725,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\abstractMesh.decalMap.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1360,"name":"read-resource","id":1361,"timestamp":839451009096,"duration":35686,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1360,"timestamp":839451009088,"duration":36189,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\meshUVSpaceRenderer.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1362,"name":"read-resource","id":1363,"timestamp":839451009111,"duration":36178,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1362,"timestamp":839451009102,"duration":36839,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\goldbergMesh.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1364,"name":"read-resource","id":1365,"timestamp":839451009124,"duration":36827,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1364,"timestamp":839451009116,"duration":37418,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\trailMesh.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1358,"name":"read-resource","id":1359,"timestamp":839451009082,"duration":37463,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1358,"timestamp":839451009073,"duration":40155,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\geometry.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1368,"name":"read-resource","id":1369,"timestamp":839451009151,"duration":40091,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1368,"timestamp":839451009143,"duration":40807,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\groundMesh.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1366,"name":"read-resource","id":1367,"timestamp":839451009137,"duration":40823,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1366,"timestamp":839451009130,"duration":41338,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\linesMesh.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"read-resource","id":1373,"timestamp":839451009179,"duration":41301,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1372,"timestamp":839451009171,"duration":45297,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\meshBuilder.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1374,"name":"read-resource","id":1375,"timestamp":839451009192,"duration":45290,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1374,"timestamp":839451009184,"duration":45556,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\meshSimplificationSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1370,"name":"read-resource","id":1371,"timestamp":839451009166,"duration":45585,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1370,"timestamp":839451009156,"duration":50481,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\mesh.vertexData.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1378,"name":"read-resource","id":1379,"timestamp":839451009219,"duration":50436,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1378,"timestamp":839451009210,"duration":53545,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\geodesicMesh.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1376,"name":"read-resource","id":1377,"timestamp":839451009204,"duration":53643,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1376,"timestamp":839451009197,"duration":60947,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\meshSimplification.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1380,"name":"read-resource","id":1381,"timestamp":839451009232,"duration":60924,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1380,"timestamp":839451009224,"duration":61269,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\subMesh.project.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1384,"name":"read-resource","id":1385,"timestamp":839451009257,"duration":61247,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1384,"timestamp":839451009250,"duration":62405,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\subMesh.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1386,"name":"read-resource","id":1387,"timestamp":839451009274,"duration":62393,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1386,"timestamp":839451009263,"duration":62515,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\meshLODLevel.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1382,"name":"read-resource","id":1383,"timestamp":839451009245,"duration":62543,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1382,"timestamp":839451009237,"duration":63596,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\polygonMesh.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1388,"name":"read-resource","id":1389,"timestamp":839451009289,"duration":63556,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1388,"timestamp":839451009280,"duration":64875,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\thinInstanceMesh.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1390,"name":"read-resource","id":1391,"timestamp":839451009303,"duration":64864,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":860,"name":"build-module-js","id":1390,"timestamp":839451009295,"duration":66521,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Offline\\database.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1392,"name":"read-resource","id":1393,"timestamp":839451009316,"duration":66512,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":858,"name":"build-module-js","id":1392,"timestamp":839451009309,"duration":66624,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Navigation\\INavigationEngine.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1394,"name":"read-resource","id":1395,"timestamp":839451009329,"duration":66613,"tags":{},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1394,"timestamp":839451009322,"duration":66826,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\blackAndWhitePostProcess.js","layer":"app-pages-browser"},"startTime":1704500738193},{"traceId":"4dea77cda8cb5b99","parentId":1396,"name":"read-resource","id":1397,"timestamp":839451010388,"duration":75411,"tags":{},"startTime":1704500738194},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1396,"timestamp":839451010366,"duration":75621,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\anaglyphPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738194},{"traceId":"4dea77cda8cb5b99","parentId":1398,"name":"read-resource","id":1399,"timestamp":839451010410,"duration":75589,"tags":{},"startTime":1704500738194},{"traceId":"4dea77cda8cb5b99","parentId":860,"name":"build-module-js","id":1398,"timestamp":839451010400,"duration":75671,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Offline\\IOfflineProvider.js","layer":"app-pages-browser"},"startTime":1704500738194},{"traceId":"4dea77cda8cb5b99","parentId":1400,"name":"read-resource","id":1401,"timestamp":839451010425,"duration":75653,"tags":{},"startTime":1704500738194},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1400,"timestamp":839451010417,"duration":75856,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\bloomMergePostProcess.js","layer":"app-pages-browser"},"startTime":1704500738194},{"traceId":"4dea77cda8cb5b99","parentId":1402,"name":"read-resource","id":1403,"timestamp":839451010443,"duration":75850,"tags":{},"startTime":1704500738194},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1402,"timestamp":839451010435,"duration":76180,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\bloomEffect.js","layer":"app-pages-browser"},"startTime":1704500738194},{"traceId":"4dea77cda8cb5b99","parentId":1408,"name":"read-resource","id":1409,"timestamp":839451011144,"duration":77543,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1408,"timestamp":839451011135,"duration":77813,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\colorCorrectionPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1410,"name":"read-resource","id":1411,"timestamp":839451011158,"duration":77801,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1410,"timestamp":839451011150,"duration":78047,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\convolutionPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1416,"name":"read-resource","id":1417,"timestamp":839451011201,"duration":78006,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1416,"timestamp":839451011193,"duration":78457,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\depthOfFieldEffect.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1414,"name":"read-resource","id":1415,"timestamp":839451011188,"duration":78473,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1414,"timestamp":839451011178,"duration":78693,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\depthOfFieldBlurPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1418,"name":"read-resource","id":1419,"timestamp":839451011214,"duration":78667,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1418,"timestamp":839451011206,"duration":78866,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\depthOfFieldMergePostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1412,"name":"read-resource","id":1413,"timestamp":839451011172,"duration":78910,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1412,"timestamp":839451011164,"duration":79183,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\circleOfConfusionPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1424,"name":"read-resource","id":1425,"timestamp":839451011256,"duration":79101,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1424,"timestamp":839451011248,"duration":79302,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\extractHighlightsPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1422,"name":"read-resource","id":1423,"timestamp":839451011242,"duration":79317,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1422,"timestamp":839451011233,"duration":79501,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\filterPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1406,"name":"read-resource","id":1407,"timestamp":839451011128,"duration":79616,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1406,"timestamp":839451011114,"duration":79953,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\chromaticAberrationPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1404,"name":"read-resource","id":1405,"timestamp":839451011103,"duration":79975,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1404,"timestamp":839451011081,"duration":80651,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\blurPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1432,"name":"read-resource","id":1433,"timestamp":839451011309,"duration":80434,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1432,"timestamp":839451011300,"duration":80604,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\highlightsPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1420,"name":"read-resource","id":1421,"timestamp":839451011227,"duration":80688,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1420,"timestamp":839451011219,"duration":80855,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\displayPassPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1428,"name":"read-resource","id":1429,"timestamp":839451011282,"duration":80802,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1428,"timestamp":839451011274,"duration":81054,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\grainPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1436,"name":"read-resource","id":1437,"timestamp":839451011337,"duration":81002,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1436,"timestamp":839451011329,"duration":81942,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\GreasedLine\\greasedLineSimpleMaterial.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1434,"name":"read-resource","id":1435,"timestamp":839451011323,"duration":81959,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1434,"timestamp":839451011315,"duration":83121,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\GreasedLine\\greasedLinePluginMaterial.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1430,"name":"read-resource","id":1431,"timestamp":839451011294,"duration":83171,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1430,"timestamp":839451011287,"duration":83811,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\imageProcessingPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1438,"name":"read-resource","id":1439,"timestamp":839451011350,"duration":83759,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1438,"timestamp":839451011343,"duration":83969,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\GreasedLine\\greasedLineMaterialInterfaces.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1440,"name":"read-resource","id":1441,"timestamp":839451011365,"duration":83957,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":850,"name":"build-module-js","id":1440,"timestamp":839451011356,"duration":84127,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\GreasedLine\\greasedLineMaterialDefaults.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1426,"name":"read-resource","id":1427,"timestamp":839451011269,"duration":84225,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1426,"timestamp":839451011261,"duration":84479,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\fxaaPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1442,"name":"read-resource","id":1443,"timestamp":839451011379,"duration":84372,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1442,"timestamp":839451011371,"duration":84489,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Compression\\index.js","layer":"app-pages-browser"},"startTime":1704500738195}] +[{"traceId":"4dea77cda8cb5b99","parentId":1444,"name":"read-resource","id":1445,"timestamp":839451011392,"duration":84578,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":844,"name":"build-module-js","id":1444,"timestamp":839451011384,"duration":84725,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\Shadows\\index.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1446,"name":"read-resource","id":1447,"timestamp":839451011406,"duration":84714,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1446,"timestamp":839451011398,"duration":84843,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\WebGPU\\webgpuDataBuffer.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1448,"name":"read-resource","id":1449,"timestamp":839451011421,"duration":84849,"tags":{},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1448,"timestamp":839451011411,"duration":85083,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\index.js","layer":"app-pages-browser"},"startTime":1704500738195},{"traceId":"4dea77cda8cb5b99","parentId":1450,"name":"read-resource","id":1451,"timestamp":839451016860,"duration":88611,"tags":{},"startTime":1704500738200},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1450,"timestamp":839451016835,"duration":89583,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\GreasedLine\\greasedLineMesh.js","layer":"app-pages-browser"},"startTime":1704500738200},{"traceId":"4dea77cda8cb5b99","parentId":1452,"name":"read-resource","id":1453,"timestamp":839451016889,"duration":89541,"tags":{},"startTime":1704500738200},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1452,"timestamp":839451016876,"duration":90135,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\GreasedLine\\greasedLineBaseMesh.js","layer":"app-pages-browser"},"startTime":1704500738200},{"traceId":"4dea77cda8cb5b99","parentId":1456,"name":"read-resource","id":1457,"timestamp":839451016954,"duration":90068,"tags":{},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1456,"timestamp":839451016941,"duration":90202,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\WebGL\\webGLDataBuffer.js","layer":"app-pages-browser"},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":1454,"name":"read-resource","id":1455,"timestamp":839451016928,"duration":90226,"tags":{},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1454,"timestamp":839451016898,"duration":91617,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\GreasedLine\\greasedLineRibbonMesh.js","layer":"app-pages-browser"},"startTime":1704500738200},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"read-resource","id":1459,"timestamp":839451016970,"duration":91556,"tags":{},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":856,"name":"build-module-js","id":1458,"timestamp":839451016961,"duration":91999,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\index.js","layer":"app-pages-browser"},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":1460,"name":"read-resource","id":1461,"timestamp":839451016984,"duration":91987,"tags":{},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1460,"timestamp":839451016976,"duration":92615,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\motionBlurPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":1464,"name":"read-resource","id":1465,"timestamp":839451017030,"duration":92575,"tags":{},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1464,"timestamp":839451017003,"duration":92917,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\passPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":1462,"name":"read-resource","id":1463,"timestamp":839451016999,"duration":92934,"tags":{},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1462,"timestamp":839451016991,"duration":98152,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\postProcess.js","layer":"app-pages-browser"},"startTime":1704500738201},{"traceId":"4dea77cda8cb5b99","parentId":1466,"name":"read-resource","id":1467,"timestamp":839451137031,"duration":5520,"tags":{},"startTime":1704500738321},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1466,"timestamp":839451137000,"duration":5921,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\refractionPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738321},{"traceId":"4dea77cda8cb5b99","parentId":1470,"name":"read-resource","id":1471,"timestamp":839451137080,"duration":5853,"tags":{},"startTime":1704500738321},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1470,"timestamp":839451137067,"duration":6160,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\stereoscopicInterlacePostProcess.js","layer":"app-pages-browser"},"startTime":1704500738321},{"traceId":"4dea77cda8cb5b99","parentId":1468,"name":"read-resource","id":1469,"timestamp":839451137059,"duration":6180,"tags":{},"startTime":1704500738321},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1468,"timestamp":839451137047,"duration":6423,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\sharpenPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738321},{"traceId":"4dea77cda8cb5b99","parentId":1472,"name":"read-resource","id":1473,"timestamp":839451137095,"duration":6387,"tags":{},"startTime":1704500738321},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1472,"timestamp":839451137086,"duration":7552,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\volumetricLightScatteringPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738321},{"traceId":"4dea77cda8cb5b99","parentId":1474,"name":"read-resource","id":1475,"timestamp":839451139297,"duration":11225,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1474,"timestamp":839451139271,"duration":11521,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\tonemapPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1476,"name":"read-resource","id":1477,"timestamp":839451139321,"duration":11482,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1476,"timestamp":839451139309,"duration":11678,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\vrMultiviewToSingleviewPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1478,"name":"read-resource","id":1479,"timestamp":839451139337,"duration":11660,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1478,"timestamp":839451139328,"duration":11884,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\vrDistortionCorrectionPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1488,"name":"read-resource","id":1489,"timestamp":839451139412,"duration":11809,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":872,"name":"build-module-js","id":1488,"timestamp":839451139402,"duration":11990,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\States\\stencilState.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1480,"name":"read-resource","id":1481,"timestamp":839451139354,"duration":12048,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1480,"timestamp":839451139343,"duration":12334,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\screenSpaceCurvaturePostProcess.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1482,"name":"read-resource","id":1483,"timestamp":839451139368,"duration":12319,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1482,"timestamp":839451139360,"duration":12826,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\screenSpaceReflectionPostProcess.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1486,"name":"read-resource","id":1487,"timestamp":839451139397,"duration":12799,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":872,"name":"build-module-js","id":1486,"timestamp":839451139389,"duration":13107,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\States\\alphaCullingState.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1490,"name":"read-resource","id":1491,"timestamp":839451139426,"duration":13081,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":872,"name":"build-module-js","id":1490,"timestamp":839451139417,"duration":13414,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\States\\stencilStateComposer.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1484,"name":"read-resource","id":1485,"timestamp":839451139382,"duration":13459,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":872,"name":"build-module-js","id":1484,"timestamp":839451139375,"duration":13770,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\States\\depthCullingState.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1494,"name":"read-resource","id":1495,"timestamp":839451139453,"duration":13700,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":866,"name":"build-module-js","id":1494,"timestamp":839451139445,"duration":13767,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\physicsEngineComponent.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1492,"name":"read-resource","id":1493,"timestamp":839451139439,"duration":13779,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":858,"name":"build-module-js","id":1492,"timestamp":839451139431,"duration":13849,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Navigation\\Plugins\\index.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1500,"name":"read-resource","id":1501,"timestamp":839451139493,"duration":13794,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1500,"timestamp":839451139486,"duration":14346,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\webgl2ParticleSystem.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1498,"name":"read-resource","id":1499,"timestamp":839451139480,"duration":14361,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":866,"name":"build-module-js","id":1498,"timestamp":839451139472,"duration":14590,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\physicsRaycastResult.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1496,"name":"read-resource","id":1497,"timestamp":839451139467,"duration":14605,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":866,"name":"build-module-js","id":1496,"timestamp":839451139458,"duration":16382,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\physicsHelper.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1502,"name":"read-resource","id":1503,"timestamp":839451139508,"duration":16343,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1502,"timestamp":839451139499,"duration":16828,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\computeShaderParticleSystem.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1506,"name":"read-resource","id":1507,"timestamp":839451139535,"duration":16803,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1506,"timestamp":839451139527,"duration":17559,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\baseParticleSystem.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1508,"name":"read-resource","id":1509,"timestamp":839451139552,"duration":17547,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1508,"timestamp":839451139544,"duration":17620,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\IParticleSystem.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1510,"name":"read-resource","id":1511,"timestamp":839451139566,"duration":17605,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1510,"timestamp":839451139557,"duration":18123,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\particle.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1504,"name":"read-resource","id":1505,"timestamp":839451139521,"duration":18169,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1504,"timestamp":839451139513,"duration":24183,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\gpuParticleSystem.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1514,"name":"read-resource","id":1515,"timestamp":839451139593,"duration":24115,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1514,"timestamp":839451139585,"duration":24504,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\particleSystemComponent.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1512,"name":"read-resource","id":1513,"timestamp":839451139579,"duration":24521,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1512,"timestamp":839451139572,"duration":25010,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\particleHelper.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1516,"name":"read-resource","id":1517,"timestamp":839451139606,"duration":24987,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1516,"timestamp":839451139598,"duration":25367,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\particleSystemSet.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1520,"name":"read-resource","id":1521,"timestamp":839451139633,"duration":25343,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1520,"timestamp":839451139624,"duration":25878,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\solidParticle.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1524,"name":"read-resource","id":1525,"timestamp":839451139659,"duration":25853,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1524,"timestamp":839451139652,"duration":26200,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\cloudPoint.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1526,"name":"read-resource","id":1527,"timestamp":839451139672,"duration":26190,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1526,"timestamp":839451139665,"duration":26524,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\subEmitter.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1518,"name":"read-resource","id":1519,"timestamp":839451139618,"duration":26582,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1518,"timestamp":839451139611,"duration":35981,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\particleSystem.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1522,"name":"read-resource","id":1523,"timestamp":839451139646,"duration":35958,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1522,"timestamp":839451139638,"duration":44083,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\solidParticleSystem.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1528,"name":"read-resource","id":1529,"timestamp":839451139688,"duration":44055,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1528,"timestamp":839451139679,"duration":46362,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\pointsCloudSystem.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1530,"name":"read-resource","id":1531,"timestamp":839451139701,"duration":50333,"tags":{},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1530,"timestamp":839451139693,"duration":50979,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXREnterExitUI.js","layer":"app-pages-browser"},"startTime":1704500738323},{"traceId":"4dea77cda8cb5b99","parentId":1534,"name":"read-resource","id":1535,"timestamp":839451140285,"duration":50400,"tags":{},"startTime":1704500738324},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1534,"timestamp":839451140275,"duration":51175,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRExperienceHelper.js","layer":"app-pages-browser"},"startTime":1704500738324},{"traceId":"4dea77cda8cb5b99","parentId":1532,"name":"read-resource","id":1533,"timestamp":839451140264,"duration":51217,"tags":{},"startTime":1704500738324},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1532,"timestamp":839451140243,"duration":52078,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRCamera.js","layer":"app-pages-browser"},"startTime":1704500738324},{"traceId":"4dea77cda8cb5b99","parentId":1536,"name":"read-resource","id":1537,"timestamp":839451140299,"duration":52033,"tags":{},"startTime":1704500738324},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1536,"timestamp":839451140291,"duration":52466,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRManagedOutputCanvas.js","layer":"app-pages-browser"},"startTime":1704500738324},{"traceId":"4dea77cda8cb5b99","parentId":1538,"name":"read-resource","id":1539,"timestamp":839451140315,"duration":60003,"tags":{},"startTime":1704500738324},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1538,"timestamp":839451140305,"duration":60436,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRInput.js","layer":"app-pages-browser"},"startTime":1704500738324},{"traceId":"4dea77cda8cb5b99","parentId":1542,"name":"read-resource","id":1543,"timestamp":839451142094,"duration":58660,"tags":{},"startTime":1704500738326},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1542,"timestamp":839451142082,"duration":58827,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRTypes.js","layer":"app-pages-browser"},"startTime":1704500738326},{"traceId":"4dea77cda8cb5b99","parentId":1540,"name":"read-resource","id":1541,"timestamp":839451142070,"duration":58849,"tags":{},"startTime":1704500738326},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1540,"timestamp":839451142045,"duration":59347,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRInputSource.js","layer":"app-pages-browser"},"startTime":1704500738326},{"traceId":"4dea77cda8cb5b99","parentId":1544,"name":"read-resource","id":1545,"timestamp":839451142109,"duration":59293,"tags":{},"startTime":1704500738326}] +[{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1544,"timestamp":839451142101,"duration":60244,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRSessionManager.js","layer":"app-pages-browser"},"startTime":1704500738326},{"traceId":"4dea77cda8cb5b99","parentId":1546,"name":"read-resource","id":1547,"timestamp":839451142124,"duration":60233,"tags":{},"startTime":1704500738326},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1546,"timestamp":839451142116,"duration":60929,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRFeaturesManager.js","layer":"app-pages-browser"},"startTime":1704500738326},{"traceId":"4dea77cda8cb5b99","parentId":1548,"name":"read-resource","id":1549,"timestamp":839451146458,"duration":59450,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1548,"timestamp":839451146434,"duration":59845,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRDefaultExperience.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1550,"name":"read-resource","id":1551,"timestamp":839451146487,"duration":59804,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":874,"name":"build-module-js","id":1550,"timestamp":839451146475,"duration":59887,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Sprites\\ISprites.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1554,"name":"read-resource","id":1555,"timestamp":839451146520,"duration":59849,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":874,"name":"build-module-js","id":1554,"timestamp":839451146511,"duration":60866,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Sprites\\spriteMap.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1556,"name":"read-resource","id":1557,"timestamp":839451146537,"duration":60851,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":874,"name":"build-module-js","id":1556,"timestamp":839451146526,"duration":65558,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Sprites\\spriteManager.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1564,"name":"read-resource","id":1565,"timestamp":839451146641,"duration":65455,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1564,"timestamp":839451146609,"duration":66552,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\depthRenderer.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1566,"name":"read-resource","id":1567,"timestamp":839451146662,"duration":66512,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1566,"timestamp":839451146651,"duration":66990,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\depthRendererSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1552,"name":"read-resource","id":1553,"timestamp":839451146504,"duration":67150,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":874,"name":"build-module-js","id":1552,"timestamp":839451146495,"duration":67606,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Sprites\\sprite.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1568,"name":"read-resource","id":1569,"timestamp":839451146694,"duration":67418,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1568,"timestamp":839451146674,"duration":68674,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\depthPeelingRenderer.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1560,"name":"read-resource","id":1561,"timestamp":839451146564,"duration":68840,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1560,"timestamp":839451146556,"duration":69767,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\boundingBoxRenderer.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1572,"name":"read-resource","id":1573,"timestamp":839451146739,"duration":69596,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":866,"name":"build-module-js","id":1572,"timestamp":839451146725,"duration":69740,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v1\\index.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1570,"name":"read-resource","id":1571,"timestamp":839451146718,"duration":69756,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":864,"name":"build-module-js","id":1570,"timestamp":839451146701,"duration":69906,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\index.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1574,"name":"read-resource","id":1575,"timestamp":839451146755,"duration":69862,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":866,"name":"build-module-js","id":1574,"timestamp":839451146746,"duration":70077,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v1\\physicsEngineComponent.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1576,"name":"read-resource","id":1577,"timestamp":839451146785,"duration":70048,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":866,"name":"build-module-js","id":1576,"timestamp":839451146766,"duration":70241,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\index.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1558,"name":"read-resource","id":1559,"timestamp":839451146550,"duration":70467,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":874,"name":"build-module-js","id":1558,"timestamp":839451146542,"duration":71186,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Sprites\\spriteSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1562,"name":"read-resource","id":1563,"timestamp":839451146597,"duration":71148,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":874,"name":"build-module-js","id":1562,"timestamp":839451146577,"duration":71341,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Sprites\\spritePackedManager.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1578,"name":"read-resource","id":1579,"timestamp":839451146810,"duration":71119,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1578,"timestamp":839451146793,"duration":71386,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\depthPeelingSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1580,"name":"read-resource","id":1581,"timestamp":839451146837,"duration":71356,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1580,"timestamp":839451146819,"duration":73327,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\geometryBufferRenderer.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1582,"name":"read-resource","id":1583,"timestamp":839451146853,"duration":73305,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1582,"timestamp":839451146845,"duration":77119,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\geometryBufferRendererSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1584,"name":"read-resource","id":1585,"timestamp":839451146867,"duration":77110,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1584,"timestamp":839451146859,"duration":79276,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\edgesRenderer.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1586,"name":"read-resource","id":1587,"timestamp":839451146880,"duration":79267,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1586,"timestamp":839451146873,"duration":79750,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\subSurfaceSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1588,"name":"read-resource","id":1589,"timestamp":839451146893,"duration":79741,"tags":{},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1588,"timestamp":839451146886,"duration":81312,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\prePassRenderer.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1592,"name":"read-resource","id":1593,"timestamp":839451146944,"duration":81266,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1592,"timestamp":839451146935,"duration":82113,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\outlineRenderer.js","layer":"app-pages-browser"},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":1590,"name":"read-resource","id":1591,"timestamp":839451146926,"duration":82133,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1590,"timestamp":839451146899,"duration":82553,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\prePassRendererSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738330},{"traceId":"4dea77cda8cb5b99","parentId":1600,"name":"read-resource","id":1601,"timestamp":839451147001,"duration":82461,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1600,"timestamp":839451146994,"duration":83994,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\dds.js","layer":"app-pages-browser"},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":1596,"name":"read-resource","id":1597,"timestamp":839451146974,"duration":84025,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1596,"timestamp":839451146966,"duration":84802,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\renderingGroup.js","layer":"app-pages-browser"},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":1602,"name":"read-resource","id":1603,"timestamp":839451147014,"duration":84765,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1602,"timestamp":839451147007,"duration":89976,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\basis.js","layer":"app-pages-browser"},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":1604,"name":"read-resource","id":1605,"timestamp":839451147029,"duration":89967,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1604,"timestamp":839451147020,"duration":90105,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\deferred.js","layer":"app-pages-browser"},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":1598,"name":"read-resource","id":1599,"timestamp":839451146988,"duration":90147,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1598,"timestamp":839451146979,"duration":90493,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\andOrNotEvaluator.js","layer":"app-pages-browser"},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"read-resource","id":1611,"timestamp":839451147070,"duration":90413,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1610,"timestamp":839451147063,"duration":90590,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\index.js","layer":"app-pages-browser"},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":1606,"name":"read-resource","id":1607,"timestamp":839451147042,"duration":90619,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1606,"timestamp":839451147034,"duration":92021,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\assetsManager.js","layer":"app-pages-browser"},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":1608,"name":"read-resource","id":1609,"timestamp":839451147057,"duration":92009,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1608,"timestamp":839451147048,"duration":93646,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\environmentTextureTools.js","layer":"app-pages-browser"},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":1594,"name":"read-resource","id":1595,"timestamp":839451146957,"duration":93748,"tags":{},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1594,"timestamp":839451146949,"duration":94637,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\utilityLayerRenderer.js","layer":"app-pages-browser"},"startTime":1704500738331},{"traceId":"4dea77cda8cb5b99","parentId":1612,"name":"read-resource","id":1613,"timestamp":839451204580,"duration":54921,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1612,"timestamp":839451204553,"duration":55057,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\native\\index.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1622,"name":"read-resource","id":1623,"timestamp":839451204720,"duration":54900,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1622,"timestamp":839451204664,"duration":55290,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\observable.extensions.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1618,"name":"read-resource","id":1619,"timestamp":839451204643,"duration":55322,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1618,"timestamp":839451204635,"duration":56036,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\filesInput.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1626,"name":"read-resource","id":1627,"timestamp":839451204766,"duration":55916,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1626,"timestamp":839451204758,"duration":56301,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\performanceMonitor.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1616,"name":"read-resource","id":1617,"timestamp":839451204629,"duration":56443,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":862,"name":"build-module-js","id":1616,"timestamp":839451204620,"duration":56576,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\EmitterTypes\\index.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1620,"name":"read-resource","id":1621,"timestamp":839451204658,"duration":56555,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1620,"timestamp":839451204649,"duration":56927,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\meshExploder.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1624,"name":"read-resource","id":1625,"timestamp":839451204750,"duration":56836,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1624,"timestamp":839451204731,"duration":57438,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\khronosTextureContainer.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1614,"name":"read-resource","id":1615,"timestamp":839451204611,"duration":57569,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":876,"name":"build-module-js","id":1614,"timestamp":839451204597,"duration":57705,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\motionController\\index.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1630,"name":"read-resource","id":1631,"timestamp":839451204793,"duration":57518,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1630,"timestamp":839451204785,"duration":58756,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\sceneOptimizer.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1628,"name":"read-resource","id":1629,"timestamp":839451204780,"duration":58773,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1628,"timestamp":839451204772,"duration":62918,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\sceneSerializer.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1632,"name":"read-resource","id":1633,"timestamp":839451204808,"duration":62894,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1632,"timestamp":839451204798,"duration":63833,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\textureTools.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1636,"name":"read-resource","id":1637,"timestamp":839451204835,"duration":63809,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1636,"timestamp":839451204827,"duration":64799,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\tga.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1634,"name":"read-resource","id":1635,"timestamp":839451204821,"duration":64817,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1634,"timestamp":839451204814,"duration":65266,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\videoRecorder.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1640,"name":"read-resource","id":1641,"timestamp":839451204877,"duration":65215,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1640,"timestamp":839451204866,"duration":65375,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\typeStore.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1638,"name":"read-resource","id":1639,"timestamp":839451204858,"duration":65415,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1638,"timestamp":839451204842,"duration":65820,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\workerPool.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1644,"name":"read-resource","id":1645,"timestamp":839451204904,"duration":65816,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1644,"timestamp":839451204896,"duration":65948,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\filesInputStore.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1642,"name":"read-resource","id":1643,"timestamp":839451204891,"duration":65964,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1642,"timestamp":839451204883,"duration":67362,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\virtualJoystick.js","layer":"app-pages-browser"},"startTime":1704500738388}] +[{"traceId":"4dea77cda8cb5b99","parentId":1646,"name":"read-resource","id":1647,"timestamp":839451204917,"duration":67453,"tags":{},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1646,"timestamp":839451204909,"duration":67893,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\deepCopier.js","layer":"app-pages-browser"},"startTime":1704500738388},{"traceId":"4dea77cda8cb5b99","parentId":1648,"name":"read-resource","id":1649,"timestamp":839451204939,"duration":67878,"tags":{},"startTime":1704500738389},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1648,"timestamp":839451204923,"duration":68144,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\pivotTools.js","layer":"app-pages-browser"},"startTime":1704500738389},{"traceId":"4dea77cda8cb5b99","parentId":302,"name":"build-module","id":1808,"timestamp":839451284040,"duration":26,"tags":{"name":"undefined","layer":"undefined"},"startTime":1704500738468},{"traceId":"4dea77cda8cb5b99","parentId":1650,"name":"read-resource","id":1651,"timestamp":839451258338,"duration":25932,"tags":{},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1650,"timestamp":839451258310,"duration":26930,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\screenshotTools.js","layer":"app-pages-browser"},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":1662,"name":"read-resource","id":1663,"timestamp":839451258446,"duration":26805,"tags":{},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1662,"timestamp":839451258438,"duration":26902,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\customAnimationFrameRequester.js","layer":"app-pages-browser"},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":1652,"name":"read-resource","id":1653,"timestamp":839451258368,"duration":26981,"tags":{},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1652,"timestamp":839451258355,"duration":27178,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\iInspectable.js","layer":"app-pages-browser"},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":1654,"name":"read-resource","id":1655,"timestamp":839451258386,"duration":27158,"tags":{},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1654,"timestamp":839451258376,"duration":27569,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\webRequest.js","layer":"app-pages-browser"},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":1658,"name":"read-resource","id":1659,"timestamp":839451258418,"duration":27540,"tags":{},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1658,"timestamp":839451258410,"duration":27905,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\gradients.js","layer":"app-pages-browser"},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":1664,"name":"read-resource","id":1665,"timestamp":839451258462,"duration":27865,"tags":{},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1664,"timestamp":839451258452,"duration":27942,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\fileRequest.js","layer":"app-pages-browser"},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":1656,"name":"read-resource","id":1657,"timestamp":839451258404,"duration":27997,"tags":{},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1656,"timestamp":839451258393,"duration":28464,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\brdfTextureTools.js","layer":"app-pages-browser"},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":1660,"name":"read-resource","id":1661,"timestamp":839451258432,"duration":28436,"tags":{},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1660,"timestamp":839451258424,"duration":28918,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\rgbdTextureTools.js","layer":"app-pages-browser"},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":1666,"name":"read-resource","id":1667,"timestamp":839451258475,"duration":28881,"tags":{},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1666,"timestamp":839451258467,"duration":29070,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\retryStrategy.js","layer":"app-pages-browser"},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":1668,"name":"read-resource","id":1669,"timestamp":839451258489,"duration":29061,"tags":{},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":868,"name":"build-module-js","id":1668,"timestamp":839451258481,"duration":29234,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\fluidRenderer\\index.js","layer":"app-pages-browser"},"startTime":1704500738442},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":126,"timestamp":839449520795,"duration":1767734,"tags":{"request":"next-flight-client-entry-loader?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cfont%5Cgoogle%5Ctarget.css%3F%7B%22path%22%3A%22app%5C%5Clayout.tsx%22%2C%22import%22%3A%22Inter%22%2C%22arguments%22%3A%5B%7B%22subsets%22%3A%5B%22latin%22%5D%7D%5D%2C%22variableName%22%3A%22inter%22%7D&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cglobals.scss&server=false!"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":1670,"name":"read-resource","id":1671,"timestamp":839451278471,"duration":11522,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1670,"timestamp":839451278443,"duration":12004,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\stringTools.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1676,"name":"read-resource","id":1677,"timestamp":839451278538,"duration":11922,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1676,"timestamp":839451278529,"duration":13109,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\sceneRecorder.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1678,"name":"read-resource","id":1679,"timestamp":839451278553,"duration":13099,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1678,"timestamp":839451278544,"duration":13522,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\depthReducer.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1672,"name":"read-resource","id":1673,"timestamp":839451278503,"duration":13583,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1672,"timestamp":839451278489,"duration":14613,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\minMaxReducer.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1674,"name":"read-resource","id":1675,"timestamp":839451278522,"duration":14595,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1674,"timestamp":839451278512,"duration":14903,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\dataReader.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1682,"name":"read-resource","id":1683,"timestamp":839451278601,"duration":14833,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1682,"timestamp":839451278590,"duration":16818,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\trajectoryClassifier.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1680,"name":"read-resource","id":1681,"timestamp":839451278581,"duration":16839,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1680,"timestamp":839451278558,"duration":18092,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\khronosTextureContainer2.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1684,"name":"read-resource","id":1685,"timestamp":839451278778,"duration":17886,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1684,"timestamp":839451278607,"duration":18286,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\dataStorage.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1686,"name":"read-resource","id":1687,"timestamp":839451278815,"duration":18088,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1686,"timestamp":839451278798,"duration":18604,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\timer.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1688,"name":"read-resource","id":1689,"timestamp":839451278831,"duration":18587,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1688,"timestamp":839451278823,"duration":18869,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\reflector.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1690,"name":"read-resource","id":1691,"timestamp":839451278859,"duration":18843,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1690,"timestamp":839451278838,"duration":19272,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\coroutine.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1692,"name":"read-resource","id":1693,"timestamp":839451278879,"duration":19242,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1692,"timestamp":839451278867,"duration":19485,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\pressureObserverWrapper.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1694,"name":"read-resource","id":1695,"timestamp":839451278892,"duration":19470,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1694,"timestamp":839451278885,"duration":19849,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\copyTools.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1696,"name":"read-resource","id":1697,"timestamp":839451278907,"duration":19841,"tags":{},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1696,"timestamp":839451278899,"duration":20164,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\guid.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1698,"name":"read-resource","id":1699,"timestamp":839451278920,"duration":20162,"tags":{},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1698,"timestamp":839451278912,"duration":20565,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\observableCoroutine.js","layer":"app-pages-browser"},"startTime":1704500738462},{"traceId":"4dea77cda8cb5b99","parentId":1700,"name":"read-resource","id":1701,"timestamp":839451278935,"duration":20559,"tags":{},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1700,"timestamp":839451278926,"duration":20834,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\error.js","layer":"app-pages-browser"},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":1702,"name":"read-resource","id":1703,"timestamp":839451278948,"duration":20828,"tags":{},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1702,"timestamp":839451278940,"duration":21288,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\dumpTools.js","layer":"app-pages-browser"},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":1704,"name":"read-resource","id":1705,"timestamp":839451278961,"duration":21278,"tags":{},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1704,"timestamp":839451278954,"duration":25601,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\copyTextureToTexture.js","layer":"app-pages-browser"},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":1708,"name":"read-resource","id":1709,"timestamp":839451278991,"duration":25575,"tags":{},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1708,"timestamp":839451278983,"duration":25993,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\equirectangularCapture.js","layer":"app-pages-browser"},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":1706,"name":"read-resource","id":1707,"timestamp":839451278977,"duration":26011,"tags":{},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1706,"timestamp":839451278969,"duration":27085,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\greasedLineTools.js","layer":"app-pages-browser"},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":1712,"name":"read-resource","id":1713,"timestamp":839451279018,"duration":27048,"tags":{},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":870,"name":"build-module-js","id":1712,"timestamp":839451279009,"duration":27872,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Probes\\reflectionProbe.js","layer":"app-pages-browser"},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":1714,"name":"read-resource","id":1715,"timestamp":839451279032,"duration":27861,"tags":{},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"build-module-js","id":1714,"timestamp":839451279024,"duration":28369,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraph.js","layer":"app-pages-browser"},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":1710,"name":"read-resource","id":1711,"timestamp":839451279004,"duration":28399,"tags":{},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":880,"name":"build-module-js","id":1710,"timestamp":839451278996,"duration":28495,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Compat\\compatibilityOptions.js","layer":"app-pages-browser"},"startTime":1704500738463},{"traceId":"4dea77cda8cb5b99","parentId":1724,"name":"read-resource","id":1725,"timestamp":839451280747,"duration":30068,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"build-module-js","id":1724,"timestamp":839451280739,"duration":30271,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphEventCoordinator.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1716,"name":"read-resource","id":1717,"timestamp":839451280677,"duration":30348,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"build-module-js","id":1716,"timestamp":839451280652,"duration":30599,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphSignalConnection.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1726,"name":"read-resource","id":1727,"timestamp":839451280763,"duration":30500,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"build-module-js","id":1726,"timestamp":839451280753,"duration":31041,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphContext.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1722,"name":"read-resource","id":1723,"timestamp":839451280733,"duration":31072,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"build-module-js","id":1722,"timestamp":839451280725,"duration":31224,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphEventBlock.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1718,"name":"read-resource","id":1719,"timestamp":839451280702,"duration":31258,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"build-module-js","id":1718,"timestamp":839451280688,"duration":31588,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphBlock.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1728,"name":"read-resource","id":1729,"timestamp":839451280776,"duration":31511,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"build-module-js","id":1728,"timestamp":839451280768,"duration":31818,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphCoordinator.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1732,"name":"read-resource","id":1733,"timestamp":839451280802,"duration":31794,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1732,"timestamp":839451280795,"duration":31881,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\HighDynamicRange\\index.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1720,"name":"read-resource","id":1721,"timestamp":839451280719,"duration":31964,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"build-module-js","id":1720,"timestamp":839451280710,"duration":32205,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphExecutionBlock.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1738,"name":"read-resource","id":1739,"timestamp":839451280843,"duration":32081,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1738,"timestamp":839451280836,"duration":32148,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\interfaces\\screenshotSize.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1730,"name":"read-resource","id":1731,"timestamp":839451280789,"duration":32201,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"build-module-js","id":1730,"timestamp":839451280782,"duration":32512,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphRichTypes.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1736,"name":"read-resource","id":1737,"timestamp":839451280830,"duration":32473,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1736,"timestamp":839451280821,"duration":32565,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\PerformanceViewer\\index.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1740,"name":"read-resource","id":1741,"timestamp":839451280857,"duration":32536,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":878,"name":"build-module-js","id":1740,"timestamp":839451280849,"duration":32595,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\interfaces\\iPerfViewer.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1742,"name":"read-resource","id":1743,"timestamp":839451280870,"duration":32580,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":882,"name":"build-module-js","id":1742,"timestamp":839451280862,"duration":32650,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\index.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1746,"name":"read-resource","id":1747,"timestamp":839451280899,"duration":32620,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":900,"name":"build-module-js","id":1746,"timestamp":839451280891,"duration":32785,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\instantiationTools.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1744,"name":"read-resource","id":1745,"timestamp":839451280886,"duration":32800,"tags":{},"startTime":1704500738464}] +[{"traceId":"4dea77cda8cb5b99","parentId":900,"name":"build-module-js","id":1744,"timestamp":839451280876,"duration":33086,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\timingTools.js","layer":"app-pages-browser"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1748,"name":"read-resource","id":1749,"timestamp":839451281015,"duration":32957,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":890,"name":"build-module-js","id":1748,"timestamp":839451280995,"duration":33131,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.constants.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1750,"name":"read-resource","id":1751,"timestamp":839451281039,"duration":33100,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":924,"name":"build-module-js","id":1750,"timestamp":839451281027,"duration":33510,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.plane.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1752,"name":"read-resource","id":1753,"timestamp":839451281054,"duration":33495,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":908,"name":"build-module-js","id":1752,"timestamp":839451281045,"duration":33774,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.uniformBuffer.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1754,"name":"read-resource","id":1755,"timestamp":839451281071,"duration":33758,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":940,"name":"build-module-js","id":1754,"timestamp":839451281061,"duration":33936,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.axis.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1756,"name":"read-resource","id":1757,"timestamp":839451281084,"duration":33925,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":932,"name":"build-module-js","id":1756,"timestamp":839451281076,"duration":35177,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\shaderProcessor.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1758,"name":"read-resource","id":1759,"timestamp":839451281099,"duration":35166,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":950,"name":"build-module-js","id":1758,"timestamp":839451281091,"duration":35320,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.viewport.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1766,"name":"read-resource","id":1767,"timestamp":839451281154,"duration":35268,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":984,"name":"build-module-js","id":1766,"timestamp":839451281146,"duration":35502,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.size.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1768,"name":"read-resource","id":1769,"timestamp":839451281168,"duration":35491,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1022,"name":"build-module-js","id":1768,"timestamp":839451281160,"duration":39729,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.computeShader.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1764,"name":"read-resource","id":1765,"timestamp":839451281140,"duration":39765,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1010,"name":"build-module-js","id":1764,"timestamp":839451281133,"duration":40113,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\rawTexture.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1772,"name":"read-resource","id":1773,"timestamp":839451281195,"duration":40063,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1048,"name":"build-module-js","id":1772,"timestamp":839451281187,"duration":40738,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\freeCameraKeyboardMoveInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1762,"name":"read-resource","id":1763,"timestamp":839451281127,"duration":40809,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":990,"name":"build-module-js","id":1762,"timestamp":839451281118,"duration":42928,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.path.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1774,"name":"read-resource","id":1775,"timestamp":839451281208,"duration":42851,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1022,"name":"build-module-js","id":1774,"timestamp":839451281201,"duration":43123,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\textureSampler.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1776,"name":"read-resource","id":1777,"timestamp":839451281221,"duration":43115,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1048,"name":"build-module-js","id":1776,"timestamp":839451281213,"duration":43701,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\freeCameraMouseWheelInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1778,"name":"read-resource","id":1779,"timestamp":839451281235,"duration":43689,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1048,"name":"build-module-js","id":1778,"timestamp":839451281226,"duration":44212,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\freeCameraMouseInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1782,"name":"read-resource","id":1783,"timestamp":839451281264,"duration":44185,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1052,"name":"build-module-js","id":1782,"timestamp":839451281257,"duration":44688,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\arcRotateCameraKeyboardMoveInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1780,"name":"read-resource","id":1781,"timestamp":839451281251,"duration":44704,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1048,"name":"build-module-js","id":1780,"timestamp":839451281242,"duration":45147,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\freeCameraTouchInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1770,"name":"read-resource","id":1771,"timestamp":839451281182,"duration":45218,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1022,"name":"build-module-js","id":1770,"timestamp":839451281173,"duration":50071,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\texture.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1786,"name":"read-resource","id":1787,"timestamp":839451281290,"duration":49972,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1052,"name":"build-module-js","id":1786,"timestamp":839451281283,"duration":50598,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\arcRotateCameraMouseWheelInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1784,"name":"read-resource","id":1785,"timestamp":839451281277,"duration":50615,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1052,"name":"build-module-js","id":1784,"timestamp":839451281269,"duration":51067,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\arcRotateCameraPointersInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1790,"name":"read-resource","id":1791,"timestamp":839451281317,"duration":51030,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1050,"name":"build-module-js","id":1790,"timestamp":839451281310,"duration":51385,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Cameras\\bouncingBehavior.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1788,"name":"read-resource","id":1789,"timestamp":839451281305,"duration":51400,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1050,"name":"build-module-js","id":1788,"timestamp":839451281295,"duration":51788,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Cameras\\autoRotationBehavior.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1792,"name":"read-resource","id":1793,"timestamp":839451281331,"duration":51762,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1056,"name":"build-module-js","id":1792,"timestamp":839451281323,"duration":52268,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\flyCameraMouseInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1734,"name":"read-resource","id":1735,"timestamp":839451280815,"duration":52787,"tags":{},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":772,"name":"build-module-js","id":1734,"timestamp":839451280807,"duration":52934,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\scheduler\\index.js","layer":"null"},"startTime":1704500738464},{"traceId":"4dea77cda8cb5b99","parentId":1794,"name":"read-resource","id":1795,"timestamp":839451281344,"duration":52407,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1050,"name":"build-module-js","id":1794,"timestamp":839451281336,"duration":53200,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Cameras\\framingBehavior.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1798,"name":"read-resource","id":1799,"timestamp":839451281372,"duration":53176,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1064,"name":"build-module-js","id":1798,"timestamp":839451281364,"duration":53819,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\followCameraKeyboardMoveInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1800,"name":"read-resource","id":1801,"timestamp":839451281384,"duration":53811,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1064,"name":"build-module-js","id":1800,"timestamp":839451281377,"duration":54192,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\followCameraMouseWheelInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1796,"name":"read-resource","id":1797,"timestamp":839451281359,"duration":54220,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1056,"name":"build-module-js","id":1796,"timestamp":839451281350,"duration":54783,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\flyCameraKeyboardInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1804,"name":"read-resource","id":1805,"timestamp":839451281412,"duration":54731,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1064,"name":"build-module-js","id":1804,"timestamp":839451281404,"duration":55251,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\followCameraPointersInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1802,"name":"read-resource","id":1803,"timestamp":839451281399,"duration":55267,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1060,"name":"build-module-js","id":1802,"timestamp":839451281391,"duration":55917,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\freeCameraDeviceOrientationInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1760,"name":"read-resource","id":1761,"timestamp":839451281113,"duration":56206,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":886,"name":"build-module-js","id":1760,"timestamp":839451281105,"duration":57297,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\compiled\\scheduler\\cjs\\scheduler.production.min.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1806,"name":"read-resource","id":1807,"timestamp":839451281426,"duration":66467,"tags":{},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1070,"name":"build-module-js","id":1806,"timestamp":839451281417,"duration":66795,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\freeCameraVirtualJoystickInput.js","layer":"app-pages-browser"},"startTime":1704500738465},{"traceId":"4dea77cda8cb5b99","parentId":1811,"name":"read-resource","id":1812,"timestamp":839451284136,"duration":64104,"tags":{},"startTime":1704500738468},{"traceId":"4dea77cda8cb5b99","parentId":1082,"name":"build-module-js","id":1811,"timestamp":839451284122,"duration":64609,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\dynamicTexture.js","layer":"app-pages-browser"},"startTime":1704500738468},{"traceId":"4dea77cda8cb5b99","parentId":1813,"name":"read-resource","id":1814,"timestamp":839451284155,"duration":64588,"tags":{},"startTime":1704500738468},{"traceId":"4dea77cda8cb5b99","parentId":1082,"name":"build-module-js","id":1813,"timestamp":839451284146,"duration":65479,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\shapeBuilder.js","layer":"app-pages-browser"},"startTime":1704500738468},{"traceId":"4dea77cda8cb5b99","parentId":1809,"name":"read-resource","id":1810,"timestamp":839451284105,"duration":65531,"tags":{},"startTime":1704500738468},{"traceId":"4dea77cda8cb5b99","parentId":1080,"name":"build-module-js","id":1809,"timestamp":839451284077,"duration":66365,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\linesBuilder.js","layer":"app-pages-browser"},"startTime":1704500738468},{"traceId":"4dea77cda8cb5b99","parentId":1815,"name":"read-resource","id":1816,"timestamp":839451284171,"duration":66283,"tags":{},"startTime":1704500738468},{"traceId":"4dea77cda8cb5b99","parentId":1078,"name":"build-module-js","id":1815,"timestamp":839451284162,"duration":67301,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\boxBuilder.js","layer":"app-pages-browser"},"startTime":1704500738468},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":121,"timestamp":839449520781,"duration":1834299,"tags":{"request":"next-flight-client-entry-loader?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Capp-router.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Cerror-boundary.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Clayout-router.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Cnot-found-boundary.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Crender-from-template-context.js&modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Cnode_modules%5Cnext%5Cdist%5Cclient%5Ccomponents%5Cstatic-generation-searchparams-bailout-provider.js&server=false!"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":1819,"name":"read-resource","id":1820,"timestamp":839451289238,"duration":71281,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1082,"name":"build-module-js","id":1819,"timestamp":839451289225,"duration":71776,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\sphereBuilder.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1817,"name":"read-resource","id":1818,"timestamp":839451289208,"duration":71806,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1078,"name":"build-module-js","id":1817,"timestamp":839451289181,"duration":73254,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v1\\physicsImpostor.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1821,"name":"read-resource","id":1822,"timestamp":839451289266,"duration":73181,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1078,"name":"build-module-js","id":1821,"timestamp":839451289247,"duration":73868,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\capsuleBuilder.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1825,"name":"read-resource","id":1826,"timestamp":839451289301,"duration":73825,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1098,"name":"build-module-js","id":1825,"timestamp":839451289290,"duration":74203,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\freeCameraGamepadInput.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1827,"name":"read-resource","id":1828,"timestamp":839451289316,"duration":74187,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1142,"name":"build-module-js","id":1827,"timestamp":839451289308,"duration":74479,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\DeviceInput\\internalDeviceSourceManager.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1823,"name":"read-resource","id":1824,"timestamp":839451289283,"duration":74513,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1078,"name":"build-module-js","id":1823,"timestamp":839451289274,"duration":75464,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\cylinderBuilder.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1829,"name":"read-resource","id":1830,"timestamp":839451289335,"duration":75416,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1122,"name":"build-module-js","id":1829,"timestamp":839451289322,"duration":75904,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Culling\\Octrees\\octreeBlock.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1831,"name":"read-resource","id":1832,"timestamp":839451289350,"duration":75887,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1098,"name":"build-module-js","id":1831,"timestamp":839451289341,"duration":76195,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\arcRotateCameraGamepadInput.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1833,"name":"read-resource","id":1834,"timestamp":839451289364,"duration":76183,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1120,"name":"build-module-js","id":1833,"timestamp":839451289356,"duration":76818,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\BaseCameraPointersInput.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1837,"name":"read-resource","id":1838,"timestamp":839451289395,"duration":76790,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1120,"name":"build-module-js","id":1837,"timestamp":839451289387,"duration":77079,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\BaseCameraMouseWheelInput.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1839,"name":"read-resource","id":1840,"timestamp":839451289413,"duration":77063,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1122,"name":"build-module-js","id":1839,"timestamp":839451289401,"duration":77532,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Culling\\Octrees\\octreeSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1835,"name":"read-resource","id":1836,"timestamp":839451289381,"duration":77564,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1122,"name":"build-module-js","id":1835,"timestamp":839451289369,"duration":77925,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Culling\\Octrees\\octree.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1843,"name":"read-resource","id":1844,"timestamp":839451289450,"duration":77855,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1128,"name":"build-module-js","id":1843,"timestamp":839451289433,"duration":78081,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Stereoscopic\\anaglyphArcRotateCamera.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1841,"name":"read-resource","id":1842,"timestamp":839451289426,"duration":78098,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1120,"name":"build-module-js","id":1841,"timestamp":839451289419,"duration":78377,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Inputs\\arcRotateCameraVRDeviceOrientationInput.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1845,"name":"read-resource","id":1846,"timestamp":839451289480,"duration":78326,"tags":{},"startTime":1704500738473}] +[{"traceId":"4dea77cda8cb5b99","parentId":1128,"name":"build-module-js","id":1845,"timestamp":839451289463,"duration":78692,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Stereoscopic\\anaglyphGamepadCamera.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1847,"name":"read-resource","id":1848,"timestamp":839451289521,"duration":78644,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1128,"name":"build-module-js","id":1847,"timestamp":839451289498,"duration":78830,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Stereoscopic\\anaglyphFreeCamera.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1849,"name":"read-resource","id":1850,"timestamp":839451289544,"duration":78792,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1128,"name":"build-module-js","id":1849,"timestamp":839451289533,"duration":78973,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Stereoscopic\\stereoscopicArcRotateCamera.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1851,"name":"read-resource","id":1852,"timestamp":839451289564,"duration":78951,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1128,"name":"build-module-js","id":1851,"timestamp":839451289552,"duration":79120,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Stereoscopic\\stereoscopicGamepadCamera.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1853,"name":"read-resource","id":1854,"timestamp":839451289579,"duration":79102,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1128,"name":"build-module-js","id":1853,"timestamp":839451289570,"duration":79302,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Stereoscopic\\stereoscopicFreeCamera.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1855,"name":"read-resource","id":1856,"timestamp":839451289594,"duration":79288,"tags":{},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1128,"name":"build-module-js","id":1855,"timestamp":839451289585,"duration":79616,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Stereoscopic\\stereoscopicScreenUniversalCamera.js","layer":"app-pages-browser"},"startTime":1704500738473},{"traceId":"4dea77cda8cb5b99","parentId":1857,"name":"read-resource","id":1858,"timestamp":839451355054,"duration":25212,"tags":{},"startTime":1704500738539},{"traceId":"4dea77cda8cb5b99","parentId":1128,"name":"build-module-js","id":1857,"timestamp":839451355024,"duration":25444,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Stereoscopic\\anaglyphUniversalCamera.js","layer":"app-pages-browser"},"startTime":1704500738539},{"traceId":"4dea77cda8cb5b99","parentId":1859,"name":"read-resource","id":1860,"timestamp":839451375612,"duration":5574,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1128,"name":"build-module-js","id":1859,"timestamp":839451375584,"duration":5800,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\Stereoscopic\\stereoscopicUniversalCamera.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1865,"name":"read-resource","id":1866,"timestamp":839451375680,"duration":5715,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1132,"name":"build-module-js","id":1865,"timestamp":839451375671,"duration":5847,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\RigModes\\stereoscopicAnaglyphRigMode.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1861,"name":"read-resource","id":1862,"timestamp":839451375643,"duration":5884,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1132,"name":"build-module-js","id":1861,"timestamp":839451375631,"duration":6068,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\RigModes\\stereoscopicRigMode.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1869,"name":"read-resource","id":1870,"timestamp":839451375709,"duration":5999,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1126,"name":"build-module-js","id":1869,"timestamp":839451375700,"duration":6199,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGL\\webGLShaderProcessors.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1867,"name":"read-resource","id":1868,"timestamp":839451375695,"duration":6214,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1126,"name":"build-module-js","id":1867,"timestamp":839451375686,"duration":6893,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\internalTexture.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1871,"name":"read-resource","id":1872,"timestamp":839451375725,"duration":6867,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1146,"name":"build-module-js","id":1871,"timestamp":839451375715,"duration":7287,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.alpha.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1863,"name":"read-resource","id":1864,"timestamp":839451375664,"duration":7350,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1132,"name":"build-module-js","id":1863,"timestamp":839451375652,"duration":7581,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\RigModes\\vrRigMode.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1873,"name":"read-resource","id":1874,"timestamp":839451375739,"duration":7505,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1146,"name":"build-module-js","id":1873,"timestamp":839451375731,"duration":7926,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.readTexture.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1879,"name":"read-resource","id":1880,"timestamp":839451375786,"duration":7882,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1146,"name":"build-module-js","id":1879,"timestamp":839451375777,"duration":8106,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.dynamicBuffer.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1875,"name":"read-resource","id":1876,"timestamp":839451375752,"duration":8141,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1875,"timestamp":839451375745,"duration":9707,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuShaderProcessorsGLSL.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1877,"name":"read-resource","id":1878,"timestamp":839451375771,"duration":9693,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1877,"timestamp":839451375758,"duration":10347,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuPipelineContext.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1883,"name":"read-resource","id":1884,"timestamp":839451375817,"duration":10298,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1144,"name":"build-module-js","id":1883,"timestamp":839451375808,"duration":13549,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Meshes\\fadeInOutBehavior.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1885,"name":"read-resource","id":1886,"timestamp":839451375832,"duration":13538,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1144,"name":"build-module-js","id":1885,"timestamp":839451375824,"duration":14053,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Meshes\\attachToBoxBehavior.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"read-resource","id":1882,"timestamp":839451375802,"duration":14087,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1881,"timestamp":839451375794,"duration":16210,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuShaderProcessorsWGSL.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1893,"name":"read-resource","id":1894,"timestamp":839451375890,"duration":16126,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1144,"name":"build-module-js","id":1893,"timestamp":839451375881,"duration":16765,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Meshes\\surfaceMagnetismBehavior.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1889,"name":"read-resource","id":1890,"timestamp":839451375861,"duration":16797,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1144,"name":"build-module-js","id":1889,"timestamp":839451375854,"duration":17716,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Meshes\\sixDofDragBehavior.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1891,"name":"read-resource","id":1892,"timestamp":839451375876,"duration":17707,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1144,"name":"build-module-js","id":1891,"timestamp":839451375867,"duration":19134,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Meshes\\pointerDragBehavior.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1887,"name":"read-resource","id":1888,"timestamp":839451375848,"duration":19166,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1144,"name":"build-module-js","id":1887,"timestamp":839451375838,"duration":19572,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Meshes\\multiPointerScaleBehavior.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1895,"name":"read-resource","id":1896,"timestamp":839451375904,"duration":19517,"tags":{},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1144,"name":"build-module-js","id":1895,"timestamp":839451375896,"duration":20518,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Meshes\\baseSixDofDragBehavior.js","layer":"app-pages-browser"},"startTime":1704500738559},{"traceId":"4dea77cda8cb5b99","parentId":1897,"name":"read-resource","id":1898,"timestamp":839451378521,"duration":20412,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1144,"name":"build-module-js","id":1897,"timestamp":839451378497,"duration":24742,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Meshes\\followBehavior.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1899,"name":"read-resource","id":1900,"timestamp":839451378554,"duration":24697,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1144,"name":"build-module-js","id":1899,"timestamp":839451378538,"duration":25459,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Behaviors\\Meshes\\handConstraintBehavior.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1901,"name":"read-resource","id":1902,"timestamp":839451378571,"duration":25437,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1134,"name":"build-module-js","id":1901,"timestamp":839451378562,"duration":25661,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\VR\\vrCameraMetrics.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1907,"name":"read-resource","id":1908,"timestamp":839451378615,"duration":25617,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1134,"name":"build-module-js","id":1907,"timestamp":839451378606,"duration":25798,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\VR\\vrDeviceOrientationGamepadCamera.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1903,"name":"read-resource","id":1904,"timestamp":839451378586,"duration":25828,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1134,"name":"build-module-js","id":1903,"timestamp":839451378578,"duration":26011,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\VR\\vrDeviceOrientationArcRotateCamera.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1911,"name":"read-resource","id":1912,"timestamp":839451378645,"duration":25953,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1911,"timestamp":839451378637,"duration":26496,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuShaderProcessingContext.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1913,"name":"read-resource","id":1914,"timestamp":839451378659,"duration":26486,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1913,"timestamp":839451378651,"duration":27037,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuBufferManager.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1909,"name":"read-resource","id":1910,"timestamp":839451378631,"duration":27068,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1134,"name":"build-module-js","id":1909,"timestamp":839451378621,"duration":29360,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\VR\\vrExperienceHelper.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1905,"name":"read-resource","id":1906,"timestamp":839451378600,"duration":29393,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1134,"name":"build-module-js","id":1905,"timestamp":839451378592,"duration":29580,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Cameras\\VR\\vrDeviceOrientationFreeCamera.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1915,"name":"read-resource","id":1916,"timestamp":839451378672,"duration":29510,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1915,"timestamp":839451378665,"duration":29781,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuStencilStateComposer.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1919,"name":"read-resource","id":1920,"timestamp":839451378701,"duration":29755,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1919,"timestamp":839451378693,"duration":30046,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuHardwareTexture.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1921,"name":"read-resource","id":1922,"timestamp":839451378714,"duration":30035,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1921,"timestamp":839451378706,"duration":30174,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuRenderPassWrapper.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1925,"name":"read-resource","id":1926,"timestamp":839451378743,"duration":30147,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1925,"timestamp":839451378735,"duration":30573,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuClearQuad.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1917,"name":"read-resource","id":1918,"timestamp":839451378687,"duration":30631,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1917,"timestamp":839451378678,"duration":38655,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuTextureHelper.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1923,"name":"read-resource","id":1924,"timestamp":839451378730,"duration":38615,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1923,"timestamp":839451378722,"duration":38900,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuDepthCullingState.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1927,"name":"read-resource","id":1928,"timestamp":839451378756,"duration":38877,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1927,"timestamp":839451378748,"duration":39326,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuBundleList.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1929,"name":"read-resource","id":1930,"timestamp":839451378778,"duration":39308,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1929,"timestamp":839451378762,"duration":39610,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuMaterialContext.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1931,"name":"read-resource","id":1932,"timestamp":839451378792,"duration":39591,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1931,"timestamp":839451378784,"duration":39945,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuOcclusionQuery.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1933,"name":"read-resource","id":1934,"timestamp":839451378805,"duration":39934,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1933,"timestamp":839451378798,"duration":40171,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuTimestampQuery.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1935,"name":"read-resource","id":1936,"timestamp":839451378819,"duration":40159,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1935,"timestamp":839451378811,"duration":40435,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuSnapshotRendering.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1939,"name":"read-resource","id":1940,"timestamp":839451378847,"duration":40408,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1160,"name":"build-module-js","id":1939,"timestamp":839451378837,"duration":40676,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Native\\nativeDataStream.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1937,"name":"read-resource","id":1938,"timestamp":839451378832,"duration":40692,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1937,"timestamp":839451378824,"duration":41371,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuShaderProcessor.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1941,"name":"read-resource","id":1942,"timestamp":839451378860,"duration":41346,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1160,"name":"build-module-js","id":1941,"timestamp":839451378852,"duration":41476,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Native\\nativeHardwareTexture.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1945,"name":"read-resource","id":1946,"timestamp":839451378887,"duration":41450,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1160,"name":"build-module-js","id":1945,"timestamp":839451378879,"duration":41602,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Native\\nativeRenderTargetWrapper.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1943,"name":"read-resource","id":1944,"timestamp":839451378874,"duration":41616,"tags":{},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1160,"name":"build-module-js","id":1943,"timestamp":839451378866,"duration":42586,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Native\\nativePipelineContext.js","layer":"app-pages-browser"},"startTime":1704500738562}] +[{"traceId":"4dea77cda8cb5b99","parentId":1947,"name":"read-resource","id":1948,"timestamp":839451378925,"duration":42651,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1160,"name":"build-module-js","id":1947,"timestamp":839451378893,"duration":43229,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Native\\nativeHelpers.js","layer":"app-pages-browser"},"startTime":1704500738562},{"traceId":"4dea77cda8cb5b99","parentId":1949,"name":"read-resource","id":1950,"timestamp":839451378946,"duration":43186,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1180,"name":"build-module-js","id":1949,"timestamp":839451378935,"duration":44041,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\cubeTexture.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1951,"name":"read-resource","id":1952,"timestamp":839451378960,"duration":44027,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1180,"name":"build-module-js","id":1951,"timestamp":839451378952,"duration":48199,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\mirrorTexture.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1957,"name":"read-resource","id":1958,"timestamp":839451379026,"duration":48137,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1180,"name":"build-module-js","id":1957,"timestamp":839451379017,"duration":48476,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\planeBuilder.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1953,"name":"read-resource","id":1954,"timestamp":839451378975,"duration":48530,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1180,"name":"build-module-js","id":1953,"timestamp":839451378967,"duration":50400,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Background\\backgroundMaterial.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1955,"name":"read-resource","id":1956,"timestamp":839451379007,"duration":50372,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1180,"name":"build-module-js","id":1955,"timestamp":839451378980,"duration":51480,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\baseTexture.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1961,"name":"read-resource","id":1962,"timestamp":839451379054,"duration":51419,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1184,"name":"build-module-js","id":1961,"timestamp":839451379046,"duration":52170,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Helpers\\textureDome.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1959,"name":"read-resource","id":1960,"timestamp":839451379041,"duration":52188,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1182,"name":"build-module-js","id":1959,"timestamp":839451379033,"duration":53270,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrMaterial.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1965,"name":"read-resource","id":1966,"timestamp":839451379083,"duration":53231,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1198,"name":"build-module-js","id":1965,"timestamp":839451379076,"duration":53619,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\torusBuilder.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1963,"name":"read-resource","id":1964,"timestamp":839451379070,"duration":53637,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1188,"name":"build-module-js","id":1963,"timestamp":839451379060,"duration":54585,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\videoTexture.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1967,"name":"read-resource","id":1968,"timestamp":839451379096,"duration":54560,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1156,"name":"build-module-js","id":1967,"timestamp":839451379089,"duration":54694,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\postprocess.vertex.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1969,"name":"read-resource","id":1970,"timestamp":839451379110,"duration":54682,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1204,"name":"build-module-js","id":1969,"timestamp":839451379102,"duration":54885,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\hemisphereBuilder.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1975,"name":"read-resource","id":1976,"timestamp":839451379152,"duration":54845,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1182,"name":"build-module-js","id":1975,"timestamp":839451379144,"duration":55056,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Loaders\\envTextureLoader.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1971,"name":"read-resource","id":1972,"timestamp":839451379123,"duration":55087,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1206,"name":"build-module-js","id":1971,"timestamp":839451379116,"duration":59180,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\polyhedronBuilder.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1973,"name":"read-resource","id":1974,"timestamp":839451379139,"duration":59170,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1220,"name":"build-module-js","id":1973,"timestamp":839451379129,"duration":61387,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\renderTargetTexture.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1977,"name":"read-resource","id":1978,"timestamp":839451379165,"duration":61368,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1182,"name":"build-module-js","id":1977,"timestamp":839451379157,"duration":61702,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Loaders\\ddsTextureLoader.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1979,"name":"read-resource","id":1980,"timestamp":839451379178,"duration":61692,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1182,"name":"build-module-js","id":1979,"timestamp":839451379171,"duration":62020,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Loaders\\ktxTextureLoader.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1983,"name":"read-resource","id":1984,"timestamp":839451379206,"duration":61995,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1246,"name":"build-module-js","id":1983,"timestamp":839451379198,"duration":62296,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\materialStencilState.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1985,"name":"read-resource","id":1986,"timestamp":839451379220,"duration":62286,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":1985,"timestamp":839451379212,"duration":62391,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.debugging.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1981,"name":"read-resource","id":1982,"timestamp":839451379193,"duration":62423,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1262,"name":"build-module-js","id":1981,"timestamp":839451379184,"duration":62615,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\prePassConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1989,"name":"read-resource","id":1990,"timestamp":839451379275,"duration":62533,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":1989,"timestamp":839451379267,"duration":62718,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.transformFeedback.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1987,"name":"read-resource","id":1988,"timestamp":839451379260,"duration":62735,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":1987,"timestamp":839451379247,"duration":63482,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.query.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1993,"name":"read-resource","id":1994,"timestamp":839451379303,"duration":63437,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":1993,"timestamp":839451379296,"duration":63683,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.dynamicTexture.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1991,"name":"read-resource","id":1992,"timestamp":839451379290,"duration":63700,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":1991,"timestamp":839451379281,"duration":64218,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.multiview.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1997,"name":"read-resource","id":1998,"timestamp":839451379330,"duration":64181,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":1997,"timestamp":839451379322,"duration":64283,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.externalTexture.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1995,"name":"read-resource","id":1996,"timestamp":839451379317,"duration":64297,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":1995,"timestamp":839451379309,"duration":65361,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.rawTexture.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2001,"name":"read-resource","id":2002,"timestamp":839451379400,"duration":65281,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":2001,"timestamp":839451379390,"duration":65502,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.videoTexture.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1999,"name":"read-resource","id":2000,"timestamp":839451379380,"duration":65521,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":1999,"timestamp":839451379335,"duration":66336,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.cubeTexture.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2003,"name":"read-resource","id":2004,"timestamp":839451379414,"duration":66269,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":2003,"timestamp":839451379406,"duration":70800,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.renderTarget.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2005,"name":"read-resource","id":2006,"timestamp":839451379427,"duration":70793,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":2005,"timestamp":839451379420,"duration":71761,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.multiRender.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2007,"name":"read-resource","id":2008,"timestamp":839451379442,"duration":71750,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":2007,"timestamp":839451379433,"duration":71854,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.textureSampler.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2009,"name":"read-resource","id":2010,"timestamp":839451379456,"duration":71839,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":2009,"timestamp":839451379448,"duration":72271,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.views.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2011,"name":"read-resource","id":2012,"timestamp":839451379468,"duration":72261,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":2011,"timestamp":839451379461,"duration":72516,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.renderTargetCube.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2015,"name":"read-resource","id":2016,"timestamp":839451379496,"duration":72491,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":2015,"timestamp":839451379487,"duration":72753,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.textureSelector.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2013,"name":"read-resource","id":2014,"timestamp":839451379482,"duration":72768,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1266,"name":"build-module-js","id":2013,"timestamp":839451379474,"duration":72892,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Extensions\\engine.storageBuffer.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2017,"name":"read-resource","id":2018,"timestamp":839451379510,"duration":72866,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1214,"name":"build-module-js","id":2017,"timestamp":839451379502,"duration":72984,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\lensFlare.fragment.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2019,"name":"read-resource","id":2020,"timestamp":839451379523,"duration":72972,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1214,"name":"build-module-js","id":2019,"timestamp":839451379515,"duration":73088,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\lensFlare.vertex.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2021,"name":"read-resource","id":2022,"timestamp":839451379536,"duration":73075,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1220,"name":"build-module-js","id":2021,"timestamp":839451379528,"duration":73187,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\glowMapMerge.fragment.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2023,"name":"read-resource","id":2024,"timestamp":839451379550,"duration":73174,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1220,"name":"build-module-js","id":2023,"timestamp":839451379542,"duration":73283,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\glowBlurPostProcess.fragment.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2025,"name":"read-resource","id":2026,"timestamp":839451379565,"duration":73268,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1220,"name":"build-module-js","id":2025,"timestamp":839451379556,"duration":73371,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\glowMapMerge.vertex.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2027,"name":"read-resource","id":2028,"timestamp":839451379579,"duration":73357,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1222,"name":"build-module-js","id":2027,"timestamp":839451379571,"duration":73478,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\glowMapGeneration.fragment.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2029,"name":"read-resource","id":2030,"timestamp":839451379592,"duration":73467,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1226,"name":"build-module-js","id":2029,"timestamp":839451379584,"duration":73592,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\layer.vertex.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"read-resource","id":2032,"timestamp":839451379605,"duration":80240,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1222,"name":"build-module-js","id":2031,"timestamp":839451379597,"duration":80477,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\glowMapGeneration.vertex.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2033,"name":"read-resource","id":2034,"timestamp":839451379619,"duration":80468,"tags":{},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":1226,"name":"build-module-js","id":2033,"timestamp":839451379610,"duration":80603,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\layer.fragment.js","layer":"app-pages-browser"},"startTime":1704500738563},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"read-resource","id":2036,"timestamp":839451380922,"duration":90254,"tags":{},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":1262,"name":"build-module-js","id":2035,"timestamp":839451380900,"duration":90526,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\default.fragment.js","layer":"app-pages-browser"},"startTime":1704500738564},{"traceId":"4dea77cda8cb5b99","parentId":2041,"name":"read-resource","id":2042,"timestamp":839451381019,"duration":90418,"tags":{},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":1296,"name":"build-module-js","id":2041,"timestamp":839451381006,"duration":90567,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\postprocess.vertex.js","layer":"app-pages-browser"},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"read-resource","id":2038,"timestamp":839451380972,"duration":90613,"tags":{},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":1262,"name":"build-module-js","id":2037,"timestamp":839451380937,"duration":90841,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\default.vertex.js","layer":"app-pages-browser"},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":2049,"name":"read-resource","id":2050,"timestamp":839451381080,"duration":90708,"tags":{},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2049,"timestamp":839451381072,"duration":91293,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\equiRectangularCubeTexture.js","layer":"app-pages-browser"},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":2039,"name":"read-resource","id":2040,"timestamp":839451380998,"duration":91380,"tags":{},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":1274,"name":"build-module-js","id":2039,"timestamp":839451380986,"duration":91584,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Native\\validatedNativeDataStream.js","layer":"app-pages-browser"},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":2045,"name":"read-resource","id":2046,"timestamp":839451381052,"duration":91528,"tags":{},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2045,"timestamp":839451381041,"duration":91699,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\baseTexture.polynomial.js","layer":"app-pages-browser"},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":2051,"name":"read-resource","id":2052,"timestamp":839451381094,"duration":91655,"tags":{},"startTime":1704500738565}] +[{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2051,"timestamp":839451381086,"duration":91967,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\externalTexture.js","layer":"app-pages-browser"},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":2043,"name":"read-resource","id":2044,"timestamp":839451381034,"duration":92032,"tags":{},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":1290,"name":"build-module-js","id":2043,"timestamp":839451381026,"duration":92573,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\codeStringParsingTools.js","layer":"app-pages-browser"},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":2053,"name":"read-resource","id":2054,"timestamp":839451381129,"duration":92482,"tags":{},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2053,"timestamp":839451381100,"duration":93278,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\hdrCubeTexture.js","layer":"app-pages-browser"},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":2047,"name":"read-resource","id":2048,"timestamp":839451381066,"duration":93324,"tags":{},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":1310,"name":"build-module-js","id":2047,"timestamp":839451381058,"duration":95816,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Loading\\Plugins\\babylonFileLoader.js","layer":"app-pages-browser"},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":2055,"name":"read-resource","id":2056,"timestamp":839451381150,"duration":101433,"tags":{},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2055,"timestamp":839451381139,"duration":101972,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\colorGradingTexture.js","layer":"app-pages-browser"},"startTime":1704500738565},{"traceId":"4dea77cda8cb5b99","parentId":2057,"name":"read-resource","id":2058,"timestamp":839451489220,"duration":9072,"tags":{},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2057,"timestamp":839451489189,"duration":9477,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\htmlElementTexture.js","layer":"app-pages-browser"},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":2067,"name":"read-resource","id":2068,"timestamp":839451489320,"duration":9359,"tags":{},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2067,"timestamp":839451489310,"duration":9612,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\refractionTexture.js","layer":"app-pages-browser"},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":2065,"name":"read-resource","id":2066,"timestamp":839451489304,"duration":9630,"tags":{},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2065,"timestamp":839451489296,"duration":9822,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\rawTexture2DArray.js","layer":"app-pages-browser"},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":2061,"name":"read-resource","id":2062,"timestamp":839451489269,"duration":9858,"tags":{},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2061,"timestamp":839451489260,"duration":10797,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\multiRenderTarget.js","layer":"app-pages-browser"},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":2059,"name":"read-resource","id":2060,"timestamp":839451489251,"duration":10818,"tags":{},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2059,"timestamp":839451489236,"duration":10928,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\internalTextureLoader.js","layer":"app-pages-browser"},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":2063,"name":"read-resource","id":2064,"timestamp":839451489289,"duration":10884,"tags":{},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2063,"timestamp":839451489276,"duration":11120,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\rawCubeTexture.js","layer":"app-pages-browser"},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":2071,"name":"read-resource","id":2072,"timestamp":839451489348,"duration":11058,"tags":{},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2071,"timestamp":839451489340,"duration":11439,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\thinTexture.js","layer":"app-pages-browser"},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":2073,"name":"read-resource","id":2074,"timestamp":839451489362,"duration":11427,"tags":{},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2073,"timestamp":839451489354,"duration":11638,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\thinRenderTargetTexture.js","layer":"app-pages-browser"},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":2069,"name":"read-resource","id":2070,"timestamp":839451489334,"duration":11668,"tags":{},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2069,"timestamp":839451489326,"duration":11829,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\rawTexture3D.js","layer":"app-pages-browser"},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":2075,"name":"read-resource","id":2076,"timestamp":839451489377,"duration":11786,"tags":{},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2075,"timestamp":839451489368,"duration":12020,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\ktx2decoderTypes.js","layer":"app-pages-browser"},"startTime":1704500738673},{"traceId":"4dea77cda8cb5b99","parentId":2077,"name":"read-resource","id":2078,"timestamp":839451495759,"duration":7078,"tags":{},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":1318,"name":"build-module-js","id":2077,"timestamp":839451495707,"duration":7300,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\nodeMaterialConnectionPointCustomObject.js","layer":"app-pages-browser"},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":2081,"name":"read-resource","id":2082,"timestamp":839451495812,"duration":7205,"tags":{},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":1318,"name":"build-module-js","id":2081,"timestamp":839451495802,"duration":7995,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\nodeMaterialBlockConnectionPoint.js","layer":"app-pages-browser"},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":2087,"name":"read-resource","id":2088,"timestamp":839451495886,"duration":7921,"tags":{},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":1320,"name":"build-module-js","id":2087,"timestamp":839451495876,"duration":8445,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrAnisotropicConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"read-resource","id":2080,"timestamp":839451495792,"duration":8540,"tags":{},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":1318,"name":"build-module-js","id":2079,"timestamp":839451495778,"duration":12171,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\nodeMaterial.js","layer":"app-pages-browser"},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":2085,"name":"read-resource","id":2086,"timestamp":839451495867,"duration":12094,"tags":{},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2085,"timestamp":839451495835,"duration":12262,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Loaders\\index.js","layer":"app-pages-browser"},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":2091,"name":"read-resource","id":2092,"timestamp":839451495935,"duration":15153,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2091,"timestamp":839451495909,"duration":15529,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.alpha.js","layer":"app-pages-browser"},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":2093,"name":"read-resource","id":2094,"timestamp":839451495954,"duration":15494,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2093,"timestamp":839451495945,"duration":15724,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.debugging.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2089,"name":"read-resource","id":2090,"timestamp":839451495902,"duration":15776,"tags":{},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2089,"timestamp":839451495893,"duration":16205,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.computeShader.js","layer":"app-pages-browser"},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":2083,"name":"read-resource","id":2084,"timestamp":839451495828,"duration":16281,"tags":{},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":1318,"name":"build-module-js","id":2083,"timestamp":839451495819,"duration":17676,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\nodeMaterialBlock.js","layer":"app-pages-browser"},"startTime":1704500738679},{"traceId":"4dea77cda8cb5b99","parentId":2097,"name":"read-resource","id":2098,"timestamp":839451495984,"duration":17522,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2097,"timestamp":839451495976,"duration":17711,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.dynamicBuffer.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2099,"name":"read-resource","id":2100,"timestamp":839451496012,"duration":17684,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2099,"timestamp":839451495989,"duration":17830,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.externalTexture.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2095,"name":"read-resource","id":2096,"timestamp":839451495969,"duration":17858,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2095,"timestamp":839451495961,"duration":18095,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.cubeTexture.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2101,"name":"read-resource","id":2102,"timestamp":839451496034,"duration":18031,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2101,"timestamp":839451496023,"duration":18181,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.dynamicTexture.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2103,"name":"read-resource","id":2104,"timestamp":839451496048,"duration":18165,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2103,"timestamp":839451496040,"duration":19133,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.multiRender.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2105,"name":"read-resource","id":2106,"timestamp":839451496062,"duration":19124,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2105,"timestamp":839451496054,"duration":19426,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.query.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2109,"name":"read-resource","id":2110,"timestamp":839451496108,"duration":19382,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2109,"timestamp":839451496082,"duration":19903,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.renderTarget.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2111,"name":"read-resource","id":2112,"timestamp":839451496126,"duration":19876,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2111,"timestamp":839451496117,"duration":20005,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.readTexture.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2107,"name":"read-resource","id":2108,"timestamp":839451496076,"duration":20055,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2107,"timestamp":839451496068,"duration":21001,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.rawTexture.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2115,"name":"read-resource","id":2116,"timestamp":839451496154,"duration":20938,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2115,"timestamp":839451496146,"duration":21203,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.renderTargetCube.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2113,"name":"read-resource","id":2114,"timestamp":839451496140,"duration":21220,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2113,"timestamp":839451496133,"duration":21566,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.storageBuffer.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2117,"name":"read-resource","id":2118,"timestamp":839451496185,"duration":21524,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2117,"timestamp":839451496159,"duration":21691,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.textureSampler.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2119,"name":"read-resource","id":2120,"timestamp":839451496204,"duration":21662,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2119,"timestamp":839451496195,"duration":21911,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.uniformBuffer.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2123,"name":"read-resource","id":2124,"timestamp":839451496260,"duration":21855,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1330,"name":"build-module-js","id":2123,"timestamp":839451496248,"duration":21993,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\standardMaterial.decalMap.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2121,"name":"read-resource","id":2122,"timestamp":839451496223,"duration":22028,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1294,"name":"build-module-js","id":2121,"timestamp":839451496210,"duration":22260,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\Extensions\\engine.videoTexture.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2127,"name":"read-resource","id":2128,"timestamp":839451496293,"duration":22188,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1326,"name":"build-module-js","id":2127,"timestamp":839451496285,"duration":22463,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrBRDFConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2129,"name":"read-resource","id":2130,"timestamp":839451496307,"duration":22451,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1326,"name":"build-module-js","id":2129,"timestamp":839451496299,"duration":23306,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrIridescenceConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2125,"name":"read-resource","id":2126,"timestamp":839451496275,"duration":23341,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1326,"name":"build-module-js","id":2125,"timestamp":839451496267,"duration":30933,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrBaseMaterial.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2131,"name":"read-resource","id":2132,"timestamp":839451496340,"duration":30874,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1326,"name":"build-module-js","id":2131,"timestamp":839451496312,"duration":31676,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrSheenConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2133,"name":"read-resource","id":2134,"timestamp":839451496357,"duration":31643,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1326,"name":"build-module-js","id":2133,"timestamp":839451496348,"duration":32765,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrClearCoatConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2135,"name":"read-resource","id":2136,"timestamp":839451496371,"duration":32754,"tags":{},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":1326,"name":"build-module-js","id":2135,"timestamp":839451496363,"duration":37624,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrSubSurfaceConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738680},{"traceId":"4dea77cda8cb5b99","parentId":2137,"name":"read-resource","id":2138,"timestamp":839451497198,"duration":39806,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1330,"name":"build-module-js","id":2137,"timestamp":839451497173,"duration":39972,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrMaterial.decalMap.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2141,"name":"read-resource","id":2142,"timestamp":839451497238,"duration":39919,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1320,"name":"build-module-js","id":2141,"timestamp":839451497229,"duration":40272,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrMetallicRoughnessMaterial.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2139,"name":"read-resource","id":2140,"timestamp":839451497222,"duration":40289,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1320,"name":"build-module-js","id":2139,"timestamp":839451497211,"duration":40628,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrBaseSimpleMaterial.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2143,"name":"read-resource","id":2144,"timestamp":839451497252,"duration":40598,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1320,"name":"build-module-js","id":2143,"timestamp":839451497244,"duration":40911,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\PBR\\pbrSpecularGlossinessMaterial.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"read-resource","id":2152,"timestamp":839451497371,"duration":40794,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1318,"name":"build-module-js","id":2151,"timestamp":839451497363,"duration":41150,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\index.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2149,"name":"read-resource","id":2150,"timestamp":839451497357,"duration":41164,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2149,"timestamp":839451497349,"duration":41233,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Packer\\index.js","layer":"app-pages-browser"},"startTime":1704500738681}] +[{"traceId":"4dea77cda8cb5b99","parentId":2147,"name":"read-resource","id":2148,"timestamp":839451497342,"duration":41359,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2147,"timestamp":839451497329,"duration":41917,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Filtering\\hdrFiltering.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2145,"name":"read-resource","id":2146,"timestamp":839451497316,"duration":41942,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1316,"name":"build-module-js","id":2145,"timestamp":839451497258,"duration":42165,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Occlusion\\occlusionMaterial.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2159,"name":"read-resource","id":2160,"timestamp":839451497426,"duration":42008,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1318,"name":"build-module-js","id":2159,"timestamp":839451497418,"duration":42103,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Enums\\index.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2153,"name":"read-resource","id":2154,"timestamp":839451497384,"duration":42145,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1314,"name":"build-module-js","id":2153,"timestamp":839451497377,"duration":42246,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Procedurals\\index.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2155,"name":"read-resource","id":2156,"timestamp":839451497400,"duration":42232,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1318,"name":"build-module-js","id":2155,"timestamp":839451497390,"duration":42463,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Decorators\\nodeDecorator.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2157,"name":"read-resource","id":2158,"timestamp":839451497413,"duration":42451,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1318,"name":"build-module-js","id":2157,"timestamp":839451497405,"duration":42582,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Optimizers\\index.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2163,"name":"read-resource","id":2164,"timestamp":839451497455,"duration":42542,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1360,"name":"build-module-js","id":2163,"timestamp":839451497445,"duration":42698,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\meshUVSpaceRenderer.vertex.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2161,"name":"read-resource","id":2162,"timestamp":839451497439,"duration":42713,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1344,"name":"build-module-js","id":2161,"timestamp":839451497431,"duration":42888,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.vertexFormat.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2167,"name":"read-resource","id":2168,"timestamp":839451497482,"duration":42846,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1366,"name":"build-module-js","id":2167,"timestamp":839451497474,"duration":42969,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\color.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2165,"name":"read-resource","id":2166,"timestamp":839451497468,"duration":42983,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1360,"name":"build-module-js","id":2165,"timestamp":839451497461,"duration":43090,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\meshUVSpaceRenderer.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2169,"name":"read-resource","id":2170,"timestamp":839451497495,"duration":43064,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1378,"name":"build-module-js","id":2169,"timestamp":839451497487,"duration":43339,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Maths\\math.isovector.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2171,"name":"read-resource","id":2172,"timestamp":839451497509,"duration":43326,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1366,"name":"build-module-js","id":2171,"timestamp":839451497499,"duration":43460,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\color.vertex.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2173,"name":"read-resource","id":2174,"timestamp":839451497522,"duration":43445,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1394,"name":"build-module-js","id":2173,"timestamp":839451497514,"duration":43553,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\blackAndWhite.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2177,"name":"read-resource","id":2178,"timestamp":839451497550,"duration":43524,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1400,"name":"build-module-js","id":2177,"timestamp":839451497541,"duration":43630,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\bloomMerge.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2175,"name":"read-resource","id":2176,"timestamp":839451497536,"duration":43644,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1396,"name":"build-module-js","id":2175,"timestamp":839451497528,"duration":43750,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\anaglyph.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2179,"name":"read-resource","id":2180,"timestamp":839451497564,"duration":43722,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1408,"name":"build-module-js","id":2179,"timestamp":839451497556,"duration":43829,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\colorCorrection.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2181,"name":"read-resource","id":2182,"timestamp":839451497579,"duration":43814,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1412,"name":"build-module-js","id":2181,"timestamp":839451497570,"duration":43947,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\circleOfConfusion.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2183,"name":"read-resource","id":2184,"timestamp":839451497592,"duration":43933,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2183,"timestamp":839451497585,"duration":45104,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\ribbonBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2187,"name":"read-resource","id":2188,"timestamp":839451497623,"duration":45079,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1410,"name":"build-module-js","id":2187,"timestamp":839451497615,"duration":45226,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\convolution.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2185,"name":"read-resource","id":2186,"timestamp":839451497606,"duration":45244,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2185,"timestamp":839451497599,"duration":45604,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\discBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2193,"name":"read-resource","id":2194,"timestamp":839451497664,"duration":45550,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2193,"timestamp":839451497656,"duration":45998,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\torusKnotBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2189,"name":"read-resource","id":2190,"timestamp":839451497638,"duration":46027,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1418,"name":"build-module-js","id":2189,"timestamp":839451497629,"duration":46159,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\depthOfFieldMerge.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2201,"name":"read-resource","id":2202,"timestamp":839451497718,"duration":46091,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2201,"timestamp":839451497710,"duration":46608,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\tubeBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2199,"name":"read-resource","id":2200,"timestamp":839451497704,"duration":46624,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2199,"timestamp":839451497695,"duration":47679,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\groundBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2197,"name":"read-resource","id":2198,"timestamp":839451497689,"duration":47697,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2197,"timestamp":839451497682,"duration":48447,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\polygonBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2203,"name":"read-resource","id":2204,"timestamp":839451497731,"duration":48409,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2203,"timestamp":839451497724,"duration":54067,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\tiledPlaneBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2205,"name":"read-resource","id":2206,"timestamp":839451497744,"duration":54059,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2205,"timestamp":839451497737,"duration":55872,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\decalBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2191,"name":"read-resource","id":2192,"timestamp":839451497651,"duration":55970,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2191,"timestamp":839451497643,"duration":56748,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\tiledBoxBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2207,"name":"read-resource","id":2208,"timestamp":839451497758,"duration":56645,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2207,"timestamp":839451497749,"duration":57171,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\goldbergBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2209,"name":"read-resource","id":2210,"timestamp":839451497771,"duration":57160,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2209,"timestamp":839451497763,"duration":57782,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\icoSphereBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2211,"name":"read-resource","id":2212,"timestamp":839451497784,"duration":57773,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2211,"timestamp":839451497776,"duration":57976,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\geodesicBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2213,"name":"read-resource","id":2214,"timestamp":839451497797,"duration":57965,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2213,"timestamp":839451497789,"duration":58633,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\textBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2215,"name":"read-resource","id":2216,"timestamp":839451497811,"duration":58624,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1402,"name":"build-module-js","id":2215,"timestamp":839451497802,"duration":59047,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\postProcessRenderEffect.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2195,"name":"read-resource","id":2196,"timestamp":839451497676,"duration":59186,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1372,"name":"build-module-js","id":2195,"timestamp":839451497669,"duration":59530,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\latheBuilder.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2221,"name":"read-resource","id":2222,"timestamp":839451497851,"duration":59359,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1406,"name":"build-module-js","id":2221,"timestamp":839451497844,"duration":59495,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\chromaticAberration.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2223,"name":"read-resource","id":2224,"timestamp":839451497865,"duration":59482,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1404,"name":"build-module-js","id":2223,"timestamp":839451497857,"duration":59632,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\kernelBlur.vertex.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2219,"name":"read-resource","id":2220,"timestamp":839451497838,"duration":59659,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1422,"name":"build-module-js","id":2219,"timestamp":839451497831,"duration":59772,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\filter.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2217,"name":"read-resource","id":2218,"timestamp":839451497825,"duration":59786,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1424,"name":"build-module-js","id":2217,"timestamp":839451497817,"duration":59909,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\extractHighlights.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2225,"name":"read-resource","id":2226,"timestamp":839451497879,"duration":59856,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1404,"name":"build-module-js","id":2225,"timestamp":839451497871,"duration":59993,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\kernelBlur.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2227,"name":"read-resource","id":2228,"timestamp":839451497891,"duration":59984,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1432,"name":"build-module-js","id":2227,"timestamp":839451497884,"duration":60116,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\highlights.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2229,"name":"read-resource","id":2230,"timestamp":839451497904,"duration":60105,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1420,"name":"build-module-js","id":2229,"timestamp":839451497896,"duration":60221,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\displayPass.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2231,"name":"read-resource","id":2232,"timestamp":839451497917,"duration":60209,"tags":{},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":1428,"name":"build-module-js","id":2231,"timestamp":839451497910,"duration":60319,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\grain.fragment.js","layer":"app-pages-browser"},"startTime":1704500738681},{"traceId":"4dea77cda8cb5b99","parentId":2233,"name":"read-resource","id":2234,"timestamp":839451497932,"duration":60305,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1426,"name":"build-module-js","id":2233,"timestamp":839451497923,"duration":60445,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fxaa.fragment.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2243,"name":"read-resource","id":2244,"timestamp":839451498001,"duration":60376,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1436,"name":"build-module-js","id":2243,"timestamp":839451497993,"duration":60497,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\greasedLine.vertex.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2235,"name":"read-resource","id":2236,"timestamp":839451497945,"duration":60553,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1430,"name":"build-module-js","id":2235,"timestamp":839451497938,"duration":60703,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\imageProcessing.fragment.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2239,"name":"read-resource","id":2240,"timestamp":839451497970,"duration":60680,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1436,"name":"build-module-js","id":2239,"timestamp":839451497963,"duration":60850,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\greasedLine.fragment.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2247,"name":"read-resource","id":2248,"timestamp":839451498026,"duration":60798,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1444,"name":"build-module-js","id":2247,"timestamp":839451498019,"duration":68614,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\Shadows\\shadowGenerator.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2241,"name":"read-resource","id":2242,"timestamp":839451497986,"duration":68660,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1442,"name":"build-module-js","id":2241,"timestamp":839451497977,"duration":69709,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Compression\\dracoCompression.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2245,"name":"read-resource","id":2246,"timestamp":839451498014,"duration":69683,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1442,"name":"build-module-js","id":2245,"timestamp":839451498006,"duration":69887,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Compression\\meshoptCompression.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2237,"name":"read-resource","id":2238,"timestamp":839451497958,"duration":69955,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1426,"name":"build-module-js","id":2237,"timestamp":839451497951,"duration":70086,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fxaa.vertex.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2249,"name":"read-resource","id":2250,"timestamp":839451498062,"duration":75350,"tags":{},"startTime":1704500738682}] +[{"traceId":"4dea77cda8cb5b99","parentId":1444,"name":"build-module-js","id":2249,"timestamp":839451498032,"duration":79136,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\Shadows\\shadowGeneratorSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2251,"name":"read-resource","id":2252,"timestamp":839451498243,"duration":78964,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1444,"name":"build-module-js","id":2251,"timestamp":839451498227,"duration":80971,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Lights\\Shadows\\cascadedShadowGenerator.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2253,"name":"read-resource","id":2254,"timestamp":839451498261,"duration":85924,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1448,"name":"build-module-js","id":2253,"timestamp":839451498252,"duration":87030,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Builders\\greasedLineBuilder.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2255,"name":"read-resource","id":2256,"timestamp":839451498275,"duration":87020,"tags":{},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2255,"timestamp":839451498268,"duration":88143,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\nodeGeometry.js","layer":"app-pages-browser"},"startTime":1704500738682},{"traceId":"4dea77cda8cb5b99","parentId":2257,"name":"read-resource","id":2258,"timestamp":839451502356,"duration":84102,"tags":{},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2257,"timestamp":839451502333,"duration":85050,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\nodeGeometryBlock.js","layer":"app-pages-browser"},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":2265,"name":"read-resource","id":2266,"timestamp":839451502437,"duration":84958,"tags":{},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":1460,"name":"build-module-js","id":2265,"timestamp":839451502429,"duration":85139,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\motionBlur.fragment.js","layer":"app-pages-browser"},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":2259,"name":"read-resource","id":2260,"timestamp":839451502388,"duration":85193,"tags":{},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2259,"timestamp":839451502373,"duration":88078,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\nodeGeometryBlockConnectionPoint.js","layer":"app-pages-browser"},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":2261,"name":"read-resource","id":2262,"timestamp":839451502407,"duration":88057,"tags":{},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2261,"timestamp":839451502397,"duration":88965,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\nodeGeometryBuildState.js","layer":"app-pages-browser"},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":2263,"name":"read-resource","id":2264,"timestamp":839451502423,"duration":88952,"tags":{},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":1460,"name":"build-module-js","id":2263,"timestamp":839451502414,"duration":89069,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\motionBlurConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":2267,"name":"read-resource","id":2268,"timestamp":839451502453,"duration":89040,"tags":{},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":1464,"name":"build-module-js","id":2267,"timestamp":839451502443,"duration":89166,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\pass.fragment.js","layer":"app-pages-browser"},"startTime":1704500738686},{"traceId":"4dea77cda8cb5b99","parentId":2269,"name":"read-resource","id":2270,"timestamp":839451607406,"duration":5458,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1464,"name":"build-module-js","id":2269,"timestamp":839451607370,"duration":5674,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\passCube.fragment.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2279,"name":"read-resource","id":2280,"timestamp":839451607506,"duration":5551,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2279,"timestamp":839451607498,"duration":5718,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\geometryOutputBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2271,"name":"read-resource","id":2272,"timestamp":839451607442,"duration":5784,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2271,"timestamp":839451607424,"duration":5886,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Interfaces\\nodeGeometryExecutionContext.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2275,"name":"read-resource","id":2276,"timestamp":839451607475,"duration":5844,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2275,"timestamp":839451607467,"duration":6468,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\mathBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2277,"name":"read-resource","id":2278,"timestamp":839451607491,"duration":6454,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2277,"timestamp":839451607481,"duration":6994,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\conditionBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2281,"name":"read-resource","id":2282,"timestamp":839451607520,"duration":6966,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2281,"timestamp":839451607512,"duration":7319,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\mapRangeBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2273,"name":"read-resource","id":2274,"timestamp":839451607461,"duration":7382,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2273,"timestamp":839451607451,"duration":7761,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\geometryOptimizeBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2283,"name":"read-resource","id":2284,"timestamp":839451607553,"duration":7668,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2283,"timestamp":839451607526,"duration":8269,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\randomBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2289,"name":"read-resource","id":2290,"timestamp":839451607607,"duration":8199,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2289,"timestamp":839451607598,"duration":8556,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\mergeGeometryBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2285,"name":"read-resource","id":2286,"timestamp":839451607577,"duration":8589,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2285,"timestamp":839451607565,"duration":9319,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\geometryInputBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2291,"name":"read-resource","id":2292,"timestamp":839451607623,"duration":9272,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2291,"timestamp":839451607613,"duration":9703,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\geometryCollectionBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2287,"name":"read-resource","id":2288,"timestamp":839451607593,"duration":9735,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2287,"timestamp":839451607585,"duration":10377,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\noiseBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2293,"name":"read-resource","id":2294,"timestamp":839451607636,"duration":10337,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2293,"timestamp":839451607629,"duration":10514,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\geometryElbowBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2295,"name":"read-resource","id":2296,"timestamp":839451607651,"duration":10502,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2295,"timestamp":839451607643,"duration":10716,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\computeNormalsBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2297,"name":"read-resource","id":2298,"timestamp":839451607664,"duration":10706,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2297,"timestamp":839451607656,"duration":11238,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\vectorConverterBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2299,"name":"read-resource","id":2300,"timestamp":839451607679,"duration":11226,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2299,"timestamp":839451607670,"duration":11656,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\geometryTransformBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2305,"name":"read-resource","id":2306,"timestamp":839451607720,"duration":11615,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2305,"timestamp":839451607712,"duration":11834,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\debugBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2301,"name":"read-resource","id":2302,"timestamp":839451607693,"duration":11863,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2301,"timestamp":839451607685,"duration":12052,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\normalizeVectorBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2303,"name":"read-resource","id":2304,"timestamp":839451607707,"duration":12040,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2303,"timestamp":839451607699,"duration":12243,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\intFloatConverterBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2307,"name":"read-resource","id":2308,"timestamp":839451607736,"duration":12215,"tags":{},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2307,"timestamp":839451607726,"duration":15300,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\geometryTrigonometryBlock.js","layer":"app-pages-browser"},"startTime":1704500738791},{"traceId":"4dea77cda8cb5b99","parentId":2309,"name":"read-resource","id":2310,"timestamp":839451610927,"duration":13392,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2309,"timestamp":839451610900,"duration":13710,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\geometryInfoBlock.js","layer":"app-pages-browser"},"startTime":1704500738794},{"traceId":"4dea77cda8cb5b99","parentId":2319,"name":"read-resource","id":2320,"timestamp":839451611011,"duration":13609,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2319,"timestamp":839451611003,"duration":13757,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Enums\\nodeGeometryConnectionPointTypes.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2311,"name":"read-resource","id":2312,"timestamp":839451610951,"duration":13819,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2311,"timestamp":839451610939,"duration":14036,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\boundingBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2317,"name":"read-resource","id":2318,"timestamp":839451610997,"duration":13987,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2317,"timestamp":839451610987,"duration":14398,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\booleanGeometryBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2315,"name":"read-resource","id":2316,"timestamp":839451610981,"duration":14414,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2315,"timestamp":839451610973,"duration":14600,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\matrixComposeBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2323,"name":"read-resource","id":2324,"timestamp":839451611037,"duration":14545,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2323,"timestamp":839451611029,"duration":14866,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\planeBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2321,"name":"read-resource","id":2322,"timestamp":839451611025,"duration":14880,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2321,"timestamp":839451611017,"duration":15035,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Enums\\nodeGeometryContextualSources.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2327,"name":"read-resource","id":2328,"timestamp":839451611066,"duration":14995,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2327,"timestamp":839451611056,"duration":15389,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\boxBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2313,"name":"read-resource","id":2314,"timestamp":839451610967,"duration":15488,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2313,"timestamp":839451610958,"duration":15934,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\mappingBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2325,"name":"read-resource","id":2326,"timestamp":839451611050,"duration":15852,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2325,"timestamp":839451611042,"duration":16180,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\icoSphereBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2331,"name":"read-resource","id":2332,"timestamp":839451611093,"duration":16139,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2331,"timestamp":839451611085,"duration":16434,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\meshBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2329,"name":"read-resource","id":2330,"timestamp":839451611079,"duration":16449,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2329,"timestamp":839451611071,"duration":16834,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\gridBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2333,"name":"read-resource","id":2334,"timestamp":839451611107,"duration":16810,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2333,"timestamp":839451611099,"duration":17169,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\sphereBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2339,"name":"read-resource","id":2340,"timestamp":839451611151,"duration":17368,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2339,"timestamp":839451611142,"duration":17738,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\capsuleBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2337,"name":"read-resource","id":2338,"timestamp":839451611137,"duration":17754,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2337,"timestamp":839451611129,"duration":18033,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\torusBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2335,"name":"read-resource","id":2336,"timestamp":839451611122,"duration":18049,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2335,"timestamp":839451611115,"duration":18399,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\cylinderBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2341,"name":"read-resource","id":2342,"timestamp":839451611165,"duration":18359,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2341,"timestamp":839451611157,"duration":18631,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\discBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2343,"name":"read-resource","id":2344,"timestamp":839451611176,"duration":18640,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2343,"timestamp":839451611169,"duration":18776,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Sources\\nullBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2345,"name":"read-resource","id":2346,"timestamp":839451611189,"duration":18764,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2345,"timestamp":839451611182,"duration":19073,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Set\\setNormalsBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2349,"name":"read-resource","id":2350,"timestamp":839451611217,"duration":19050,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2349,"timestamp":839451611208,"duration":19362,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Set\\setTangentsBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2347,"name":"read-resource","id":2348,"timestamp":839451611202,"duration":19377,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2347,"timestamp":839451611195,"duration":19683,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Set\\setPositionsBlock.js","layer":"app-pages-browser"},"startTime":1704500738795}] +[{"traceId":"4dea77cda8cb5b99","parentId":2351,"name":"read-resource","id":2352,"timestamp":839451611230,"duration":19780,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2351,"timestamp":839451611223,"duration":20237,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Set\\setUVsBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2353,"name":"read-resource","id":2354,"timestamp":839451611244,"duration":20227,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2353,"timestamp":839451611236,"duration":20577,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Set\\setColorsBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2355,"name":"read-resource","id":2356,"timestamp":839451611257,"duration":20566,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2355,"timestamp":839451611249,"duration":20885,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Set\\setMaterialIDBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2357,"name":"read-resource","id":2358,"timestamp":839451611273,"duration":20872,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2357,"timestamp":839451611264,"duration":21064,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Matrices\\rotationXBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2361,"name":"read-resource","id":2362,"timestamp":839451611300,"duration":21037,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2361,"timestamp":839451611293,"duration":21247,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Matrices\\rotationZBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2367,"name":"read-resource","id":2368,"timestamp":839451611342,"duration":21208,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2367,"timestamp":839451611334,"duration":21423,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Matrices\\alignBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2369,"name":"read-resource","id":2370,"timestamp":839451611355,"duration":21412,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2369,"timestamp":839451611348,"duration":22002,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Instances\\instantiateOnVerticesBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2363,"name":"read-resource","id":2364,"timestamp":839451611313,"duration":22046,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2363,"timestamp":839451611306,"duration":25874,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Matrices\\scalingBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2371,"name":"read-resource","id":2372,"timestamp":839451611369,"duration":25905,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2371,"timestamp":839451611361,"duration":26567,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Instances\\instantiateOnFacesBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2373,"name":"read-resource","id":2374,"timestamp":839451611384,"duration":26555,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2373,"timestamp":839451611375,"duration":26883,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Instances\\instantiateBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2377,"name":"read-resource","id":2378,"timestamp":839451611411,"duration":26857,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2377,"timestamp":839451611403,"duration":27407,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Instances\\instantiateOnVolumeBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2375,"name":"read-resource","id":2376,"timestamp":839451611398,"duration":27422,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2375,"timestamp":839451611390,"duration":27814,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Instances\\instantiateLinearBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2359,"name":"read-resource","id":2360,"timestamp":839451611287,"duration":27928,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2359,"timestamp":839451611279,"duration":28119,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Matrices\\rotationYBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2379,"name":"read-resource","id":2380,"timestamp":839451611424,"duration":27984,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2379,"timestamp":839451611416,"duration":28377,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Instances\\instantiateRadialBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2381,"name":"read-resource","id":2382,"timestamp":839451611437,"duration":28367,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2381,"timestamp":839451611429,"duration":28640,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Teleport\\teleportOutBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2383,"name":"read-resource","id":2384,"timestamp":839451611451,"duration":28627,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2383,"timestamp":839451611442,"duration":28896,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Teleport\\teleportInBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2387,"name":"read-resource","id":2388,"timestamp":839451611477,"duration":28870,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2387,"timestamp":839451611470,"duration":29242,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Textures\\geometryTextureBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2385,"name":"read-resource","id":2386,"timestamp":839451611464,"duration":29257,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2385,"timestamp":839451611457,"duration":29632,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Textures\\geometryTextureFetchBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2389,"name":"read-resource","id":2390,"timestamp":839451611492,"duration":29607,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1468,"name":"build-module-js","id":2389,"timestamp":839451611483,"duration":29733,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\sharpen.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2391,"name":"read-resource","id":2392,"timestamp":839451611539,"duration":29686,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1466,"name":"build-module-js","id":2391,"timestamp":839451611497,"duration":29826,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\refraction.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2365,"name":"read-resource","id":2366,"timestamp":839451611328,"duration":30003,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1458,"name":"build-module-js","id":2365,"timestamp":839451611319,"duration":30192,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Matrices\\translationBlock.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2393,"name":"read-resource","id":2394,"timestamp":839451611563,"duration":29956,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1472,"name":"build-module-js","id":2393,"timestamp":839451611550,"duration":30078,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\volumetricLightScattering.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2395,"name":"read-resource","id":2396,"timestamp":839451611579,"duration":30057,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1470,"name":"build-module-js","id":2395,"timestamp":839451611571,"duration":30165,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\stereoscopicInterlace.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2397,"name":"read-resource","id":2398,"timestamp":839451611592,"duration":30151,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1472,"name":"build-module-js","id":2397,"timestamp":839451611585,"duration":30266,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\volumetricLightScatteringPass.vertex.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2401,"name":"read-resource","id":2402,"timestamp":839451611659,"duration":30200,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1472,"name":"build-module-js","id":2401,"timestamp":839451611635,"duration":30335,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\depth.vertex.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2403,"name":"read-resource","id":2404,"timestamp":839451611677,"duration":30302,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1474,"name":"build-module-js","id":2403,"timestamp":839451611667,"duration":30406,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\tonemap.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2399,"name":"read-resource","id":2400,"timestamp":839451611629,"duration":30452,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1472,"name":"build-module-js","id":2399,"timestamp":839451611617,"duration":30554,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\volumetricLightScatteringPass.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2405,"name":"read-resource","id":2406,"timestamp":839451611691,"duration":30488,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1476,"name":"build-module-js","id":2405,"timestamp":839451611683,"duration":30590,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\vrMultiviewToSingleview.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2407,"name":"read-resource","id":2408,"timestamp":839451611706,"duration":30575,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1478,"name":"build-module-js","id":2407,"timestamp":839451611698,"duration":30672,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\vrDistortionCorrection.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2409,"name":"read-resource","id":2410,"timestamp":839451611722,"duration":30656,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1480,"name":"build-module-js","id":2409,"timestamp":839451611712,"duration":30931,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\screenSpaceCurvature.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2413,"name":"read-resource","id":2414,"timestamp":839451611750,"duration":30902,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1482,"name":"build-module-js","id":2413,"timestamp":839451611742,"duration":30993,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\screenSpaceReflectionsConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2415,"name":"read-resource","id":2416,"timestamp":839451611763,"duration":30979,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1500,"name":"build-module-js","id":2415,"timestamp":839451611755,"duration":31197,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\uniformBufferEffectCommonAccessor.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2411,"name":"read-resource","id":2412,"timestamp":839451611736,"duration":31224,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1494,"name":"build-module-js","id":2411,"timestamp":839451611728,"duration":31611,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\joinedPhysicsEngineComponent.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2417,"name":"read-resource","id":2418,"timestamp":839451611793,"duration":31557,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1482,"name":"build-module-js","id":2417,"timestamp":839451611768,"duration":31718,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\screenSpaceReflection.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2419,"name":"read-resource","id":2420,"timestamp":839451611811,"duration":31683,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1500,"name":"build-module-js","id":2419,"timestamp":839451611802,"duration":31792,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\gpuUpdateParticles.fragment.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2423,"name":"read-resource","id":2424,"timestamp":839451611839,"duration":31763,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1502,"name":"build-module-js","id":2423,"timestamp":839451611831,"duration":31938,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\gpuUpdateParticles.compute.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2425,"name":"read-resource","id":2426,"timestamp":839451611854,"duration":31923,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1494,"name":"build-module-js","id":2425,"timestamp":839451611844,"duration":32074,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\physicsEngineComponent.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2421,"name":"read-resource","id":2422,"timestamp":839451611825,"duration":32101,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1500,"name":"build-module-js","id":2421,"timestamp":839451611817,"duration":32259,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\gpuUpdateParticles.vertex.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2429,"name":"read-resource","id":2430,"timestamp":839451611881,"duration":32203,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1500,"name":"build-module-js","id":2429,"timestamp":839451611873,"duration":32426,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\EmitterTypes\\customParticleEmitter.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2427,"name":"read-resource","id":2428,"timestamp":839451611868,"duration":32441,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1504,"name":"build-module-js","id":2427,"timestamp":839451611860,"duration":32729,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\EmitterTypes\\boxParticleEmitter.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2431,"name":"read-resource","id":2432,"timestamp":839451611894,"duration":32704,"tags":{},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":1496,"name":"build-module-js","id":2431,"timestamp":839451611887,"duration":32988,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\IPhysicsEnginePlugin.js","layer":"app-pages-browser"},"startTime":1704500738795},{"traceId":"4dea77cda8cb5b99","parentId":2435,"name":"read-resource","id":2436,"timestamp":839451612382,"duration":46275,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1504,"name":"build-module-js","id":2435,"timestamp":839451612371,"duration":46440,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\gpuRenderParticles.fragment.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2439,"name":"read-resource","id":2440,"timestamp":839451612442,"duration":46379,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1518,"name":"build-module-js","id":2439,"timestamp":839451612429,"duration":46522,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\particles.fragment.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2433,"name":"read-resource","id":2434,"timestamp":839451612359,"duration":46602,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1492,"name":"build-module-js","id":2433,"timestamp":839451612339,"duration":47915,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Navigation\\Plugins\\recastJSPlugin.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2437,"name":"read-resource","id":2438,"timestamp":839451612419,"duration":47846,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1504,"name":"build-module-js","id":2437,"timestamp":839451612389,"duration":48040,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\gpuRenderParticles.vertex.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2445,"name":"read-resource","id":2446,"timestamp":839451612487,"duration":47950,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1538,"name":"build-module-js","id":2445,"timestamp":839451612478,"duration":48477,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\motionController\\webXRMotionControllerManager.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2443,"name":"read-resource","id":2444,"timestamp":839451612472,"duration":48494,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1536,"name":"build-module-js","id":2443,"timestamp":839451612463,"duration":48748,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRWebGLLayer.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2441,"name":"read-resource","id":2442,"timestamp":839451612457,"duration":48764,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1514,"name":"build-module-js","id":2441,"timestamp":839451612449,"duration":48911,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\particles.vertex.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2447,"name":"read-resource","id":2448,"timestamp":839451612501,"duration":48868,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1544,"name":"build-module-js","id":2447,"timestamp":839451612493,"duration":49083,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\native\\nativeXRRenderTarget.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2449,"name":"read-resource","id":2450,"timestamp":839451612515,"duration":49071,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1554,"name":"build-module-js","id":2449,"timestamp":839451612507,"duration":49194,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\spriteMap.fragment.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2451,"name":"read-resource","id":2452,"timestamp":839451612529,"duration":49180,"tags":{},"startTime":1704500738796}] +[{"traceId":"4dea77cda8cb5b99","parentId":1554,"name":"build-module-js","id":2451,"timestamp":839451612521,"duration":49428,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\spriteMap.vertex.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2453,"name":"read-resource","id":2454,"timestamp":839451612544,"duration":49416,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1556,"name":"build-module-js","id":2453,"timestamp":839451612535,"duration":50289,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Sprites\\spriteRenderer.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2455,"name":"read-resource","id":2456,"timestamp":839451612558,"duration":50276,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1552,"name":"build-module-js","id":2455,"timestamp":839451612550,"duration":50514,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Sprites\\thinSprite.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2457,"name":"read-resource","id":2458,"timestamp":839451612571,"duration":50520,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1564,"name":"build-module-js","id":2457,"timestamp":839451612564,"duration":50655,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\depth.fragment.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2461,"name":"read-resource","id":2462,"timestamp":839451612804,"duration":54208,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1568,"name":"build-module-js","id":2461,"timestamp":839451612774,"duration":54374,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\oitFinal.fragment.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2463,"name":"read-resource","id":2464,"timestamp":839451612825,"duration":54334,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1560,"name":"build-module-js","id":2463,"timestamp":839451612814,"duration":54452,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\boundingBoxRenderer.fragment.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2459,"name":"read-resource","id":2460,"timestamp":839451612767,"duration":54506,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1568,"name":"build-module-js","id":2459,"timestamp":839451612753,"duration":54617,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\oitBackBlend.fragment.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2465,"name":"read-resource","id":2466,"timestamp":839451612840,"duration":64080,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1560,"name":"build-module-js","id":2465,"timestamp":839451612832,"duration":64253,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\boundingBoxRenderer.vertex.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2467,"name":"read-resource","id":2468,"timestamp":839451612852,"duration":64243,"tags":{},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":1548,"name":"build-module-js","id":2467,"timestamp":839451612845,"duration":65792,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRControllerPointerSelection.js","layer":"app-pages-browser"},"startTime":1704500738796},{"traceId":"4dea77cda8cb5b99","parentId":2469,"name":"read-resource","id":2470,"timestamp":839451673955,"duration":7507,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1548,"name":"build-module-js","id":2469,"timestamp":839451673890,"duration":9367,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRNearInteraction.js","layer":"app-pages-browser"},"startTime":1704500738857},{"traceId":"4dea77cda8cb5b99","parentId":2473,"name":"read-resource","id":2474,"timestamp":839451674037,"duration":9232,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1572,"name":"build-module-js","id":2473,"timestamp":839451674025,"duration":9310,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v1\\IPhysicsEnginePlugin.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2471,"name":"read-resource","id":2472,"timestamp":839451674012,"duration":9329,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1548,"name":"build-module-js","id":2471,"timestamp":839451673984,"duration":12636,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRControllerTeleportation.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2477,"name":"read-resource","id":2478,"timestamp":839451674096,"duration":12536,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1572,"name":"build-module-js","id":2477,"timestamp":839451674080,"duration":12843,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v1\\physicsJoint.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2475,"name":"read-resource","id":2476,"timestamp":839451674060,"duration":12873,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1572,"name":"build-module-js","id":2475,"timestamp":839451674044,"duration":13269,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v1\\physicsEngine.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2479,"name":"read-resource","id":2480,"timestamp":839451674116,"duration":13207,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1580,"name":"build-module-js","id":2479,"timestamp":839451674105,"duration":13362,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\geometry.fragment.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2481,"name":"read-resource","id":2482,"timestamp":839451674132,"duration":13344,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1584,"name":"build-module-js","id":2481,"timestamp":839451674123,"duration":13464,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\line.vertex.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2485,"name":"read-resource","id":2486,"timestamp":839451674187,"duration":13408,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1592,"name":"build-module-js","id":2485,"timestamp":839451674176,"duration":13526,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\outline.fragment.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2483,"name":"read-resource","id":2484,"timestamp":839451674162,"duration":13548,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1586,"name":"build-module-js","id":2483,"timestamp":839451674139,"duration":13887,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\subSurfaceConfiguration.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2489,"name":"read-resource","id":2490,"timestamp":839451674243,"duration":13792,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1584,"name":"build-module-js","id":2489,"timestamp":839451674221,"duration":13920,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\line.fragment.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2487,"name":"read-resource","id":2488,"timestamp":839451674206,"duration":13943,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1580,"name":"build-module-js","id":2487,"timestamp":839451674195,"duration":14087,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\geometry.vertex.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2491,"name":"read-resource","id":2492,"timestamp":839451674261,"duration":14032,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1592,"name":"build-module-js","id":2491,"timestamp":839451674251,"duration":14151,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\outline.vertex.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2493,"name":"read-resource","id":2494,"timestamp":839451674283,"duration":14126,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1588,"name":"build-module-js","id":2493,"timestamp":839451674267,"duration":14366,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\prePassRenderTarget.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2495,"name":"read-resource","id":2496,"timestamp":839451674316,"duration":14326,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1600,"name":"build-module-js","id":2495,"timestamp":839451674296,"duration":14883,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\HighDynamicRange\\cubemapToSphericalPolynomial.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2499,"name":"read-resource","id":2500,"timestamp":839451674350,"duration":14840,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1570,"name":"build-module-js","id":2499,"timestamp":839451674342,"duration":15112,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\postProcessRenderPipelineManager.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2497,"name":"read-resource","id":2498,"timestamp":839451674334,"duration":15129,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1570,"name":"build-module-js","id":2497,"timestamp":839451674325,"duration":15525,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\postProcessRenderPipeline.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2501,"name":"read-resource","id":2502,"timestamp":839451674366,"duration":15494,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1576,"name":"build-module-js","id":2501,"timestamp":839451674356,"duration":16192,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\physicsBody.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2505,"name":"read-resource","id":2506,"timestamp":839451674394,"duration":16164,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1576,"name":"build-module-js","id":2505,"timestamp":839451674386,"duration":16422,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\physicsEngine.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2503,"name":"read-resource","id":2504,"timestamp":839451674380,"duration":16438,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1570,"name":"build-module-js","id":2503,"timestamp":839451674372,"duration":16624,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\postProcessRenderPipelineManagerSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2507,"name":"read-resource","id":2508,"timestamp":839451674408,"duration":16598,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1576,"name":"build-module-js","id":2507,"timestamp":839451674400,"duration":17065,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\physicsConstraint.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2509,"name":"read-resource","id":2510,"timestamp":839451674422,"duration":17053,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1576,"name":"build-module-js","id":2509,"timestamp":839451674414,"duration":17622,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\physicsShape.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2513,"name":"read-resource","id":2514,"timestamp":839451674451,"duration":17595,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1576,"name":"build-module-js","id":2513,"timestamp":839451674443,"duration":17712,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\physicsMaterial.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2511,"name":"read-resource","id":2512,"timestamp":839451674437,"duration":17727,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1576,"name":"build-module-js","id":2511,"timestamp":839451674428,"duration":18277,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\physicsAggregate.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2517,"name":"read-resource","id":2518,"timestamp":839451674480,"duration":18235,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2517,"timestamp":839451674472,"duration":18419,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRAbstractFeature.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2515,"name":"read-resource","id":2516,"timestamp":839451674466,"duration":18435,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2515,"timestamp":839451674457,"duration":18886,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRPlaneDetector.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2519,"name":"read-resource","id":2520,"timestamp":839451674494,"duration":18859,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2519,"timestamp":839451674486,"duration":23404,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRAnchorSystem.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2521,"name":"read-resource","id":2522,"timestamp":839451674507,"duration":23396,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2521,"timestamp":839451674499,"duration":23804,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRHitTestLegacy.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2523,"name":"read-resource","id":2524,"timestamp":839451674525,"duration":23788,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2523,"timestamp":839451674514,"duration":24030,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRBackgroundRemover.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2525,"name":"read-resource","id":2526,"timestamp":839451674539,"duration":24015,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2525,"timestamp":839451674531,"duration":24833,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRControllerPhysics.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2527,"name":"read-resource","id":2528,"timestamp":839451674557,"duration":24820,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2527,"timestamp":839451674545,"duration":25253,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRHitTest.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2537,"name":"read-resource","id":2538,"timestamp":839451674629,"duration":25179,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2537,"timestamp":839451674620,"duration":25453,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRDOMOverlay.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2533,"name":"read-resource","id":2534,"timestamp":839451674599,"duration":25483,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2533,"timestamp":839451674591,"duration":25983,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRMeshDetector.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2531,"name":"read-resource","id":2532,"timestamp":839451674586,"duration":26000,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2531,"timestamp":839451674578,"duration":27830,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRHandTracking.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2539,"name":"read-resource","id":2540,"timestamp":839451674642,"duration":27779,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2539,"timestamp":839451674634,"duration":28495,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRLightEstimation.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2541,"name":"read-resource","id":2542,"timestamp":839451674662,"duration":28478,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2541,"timestamp":839451674649,"duration":28805,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXREyeTracking.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2543,"name":"read-resource","id":2544,"timestamp":839451674687,"duration":28777,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2543,"timestamp":839451674671,"duration":29466,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRControllerMovement.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2545,"name":"read-resource","id":2546,"timestamp":839451674709,"duration":29439,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2545,"timestamp":839451674696,"duration":30455,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRWalkingLocomotion.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2529,"name":"read-resource","id":2530,"timestamp":839451674570,"duration":30593,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2529,"timestamp":839451674563,"duration":30965,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRFeaturePointSystem.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2547,"name":"read-resource","id":2548,"timestamp":839451674733,"duration":30806,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2547,"timestamp":839451674718,"duration":31516,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRLayers.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2551,"name":"read-resource","id":2552,"timestamp":839451674789,"duration":31456,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2551,"timestamp":839451674767,"duration":35554,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRDepthSensing.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2549,"name":"read-resource","id":2550,"timestamp":839451674757,"duration":35576,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2549,"timestamp":839451674743,"duration":36371,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRSpaceWarp.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2535,"name":"read-resource","id":2536,"timestamp":839451674615,"duration":36511,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1610,"name":"build-module-js","id":2535,"timestamp":839451674605,"duration":37125,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\features\\WebXRImageTracking.js","layer":"app-pages-browser"},"startTime":1704500738858}] +[{"traceId":"4dea77cda8cb5b99","parentId":2555,"name":"read-resource","id":2556,"timestamp":839451674846,"duration":37007,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1570,"name":"build-module-js","id":2555,"timestamp":839451674836,"duration":37166,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\Pipelines\\index.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2553,"name":"read-resource","id":2554,"timestamp":839451674826,"duration":37185,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1572,"name":"build-module-js","id":2553,"timestamp":839451674806,"duration":37298,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v1\\Plugins\\index.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2557,"name":"read-resource","id":2558,"timestamp":839451674862,"duration":37253,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1608,"name":"build-module-js","id":2557,"timestamp":839451674854,"duration":37417,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\rgbdEncode.fragment.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2559,"name":"read-resource","id":2560,"timestamp":839451674881,"duration":37406,"tags":{},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":1608,"name":"build-module-js","id":2559,"timestamp":839451674869,"duration":37569,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\rgbdDecode.fragment.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2561,"name":"read-resource","id":2562,"timestamp":839451674921,"duration":37533,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1576,"name":"build-module-js","id":2561,"timestamp":839451674892,"duration":37642,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\Plugins\\index.js","layer":"app-pages-browser"},"startTime":1704500738858},{"traceId":"4dea77cda8cb5b99","parentId":2563,"name":"read-resource","id":2564,"timestamp":839451674947,"duration":37600,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1612,"name":"build-module-js","id":2563,"timestamp":839451674936,"duration":37952,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\native\\nativeXRFrame.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2565,"name":"read-resource","id":2566,"timestamp":839451674964,"duration":37934,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1616,"name":"build-module-js","id":2565,"timestamp":839451674955,"duration":38363,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\EmitterTypes\\coneParticleEmitter.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2569,"name":"read-resource","id":2570,"timestamp":839451674994,"duration":38335,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1616,"name":"build-module-js","id":2569,"timestamp":839451674984,"duration":38638,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\EmitterTypes\\pointParticleEmitter.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2567,"name":"read-resource","id":2568,"timestamp":839451674978,"duration":38655,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1616,"name":"build-module-js","id":2567,"timestamp":839451674970,"duration":39127,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\EmitterTypes\\cylinderParticleEmitter.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2571,"name":"read-resource","id":2572,"timestamp":839451675008,"duration":39098,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1616,"name":"build-module-js","id":2571,"timestamp":839451675000,"duration":39201,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\EmitterTypes\\IParticleEmitterType.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2573,"name":"read-resource","id":2574,"timestamp":839451675024,"duration":39185,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1616,"name":"build-module-js","id":2573,"timestamp":839451675014,"duration":39474,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\EmitterTypes\\hemisphericParticleEmitter.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2581,"name":"read-resource","id":2582,"timestamp":839451675081,"duration":39417,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1614,"name":"build-module-js","id":2581,"timestamp":839451675073,"duration":39742,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\motionController\\webXRControllerComponent.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2575,"name":"read-resource","id":2576,"timestamp":839451675038,"duration":39786,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1616,"name":"build-module-js","id":2575,"timestamp":839451675030,"duration":40196,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\EmitterTypes\\sphereParticleEmitter.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2577,"name":"read-resource","id":2578,"timestamp":839451675053,"duration":40183,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1616,"name":"build-module-js","id":2577,"timestamp":839451675044,"duration":40626,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Particles\\EmitterTypes\\meshParticleEmitter.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2579,"name":"read-resource","id":2580,"timestamp":839451675067,"duration":40613,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1614,"name":"build-module-js","id":2579,"timestamp":839451675059,"duration":41135,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\motionController\\webXRAbstractMotionController.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2583,"name":"read-resource","id":2584,"timestamp":839451675095,"duration":41110,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1614,"name":"build-module-js","id":2583,"timestamp":839451675087,"duration":41315,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\motionController\\webXRGenericHandController.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2587,"name":"read-resource","id":2588,"timestamp":839451675123,"duration":41289,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1614,"name":"build-module-js","id":2587,"timestamp":839451675115,"duration":41487,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\motionController\\webXRGenericMotionController.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2589,"name":"read-resource","id":2590,"timestamp":839451675137,"duration":41475,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1614,"name":"build-module-js","id":2589,"timestamp":839451675129,"duration":41786,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\motionController\\webXRHTCViveMotionController.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2585,"name":"read-resource","id":2586,"timestamp":839451675110,"duration":41815,"tags":{},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":1614,"name":"build-module-js","id":2585,"timestamp":839451675101,"duration":42483,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\motionController\\webXRMicrosoftMixedRealityController.js","layer":"app-pages-browser"},"startTime":1704500738859},{"traceId":"4dea77cda8cb5b99","parentId":2591,"name":"read-resource","id":2592,"timestamp":839451679264,"duration":50593,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1614,"name":"build-module-js","id":2591,"timestamp":839451679241,"duration":51097,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\motionController\\webXROculusTouchMotionController.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2593,"name":"read-resource","id":2594,"timestamp":839451679291,"duration":51059,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1614,"name":"build-module-js","id":2593,"timestamp":839451679279,"duration":51521,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\motionController\\webXRProfiledMotionController.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2605,"name":"read-resource","id":2606,"timestamp":839451679388,"duration":51424,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1672,"name":"build-module-js","id":2605,"timestamp":839451679379,"duration":51574,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\minmaxRedux.fragment.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"read-resource","id":2596,"timestamp":839451679313,"duration":51653,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1668,"name":"build-module-js","id":2595,"timestamp":839451679303,"duration":52605,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\fluidRenderer\\fluidRenderer.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2601,"name":"read-resource","id":2602,"timestamp":839451679358,"duration":52561,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1668,"name":"build-module-js","id":2601,"timestamp":839451679350,"duration":54029,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\fluidRenderer\\fluidRenderingTargetRenderer.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2607,"name":"read-resource","id":2608,"timestamp":839451679402,"duration":53990,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1704,"name":"build-module-js","id":2607,"timestamp":839451679394,"duration":54127,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\copyTextureToTexture.fragment.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2603,"name":"read-resource","id":2604,"timestamp":839451679372,"duration":54159,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1668,"name":"build-module-js","id":2603,"timestamp":839451679365,"duration":54423,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\fluidRenderer\\fluidRenderingObjectParticleSystem.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2597,"name":"read-resource","id":2598,"timestamp":839451679330,"duration":54469,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1668,"name":"build-module-js","id":2597,"timestamp":839451679319,"duration":54871,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\fluidRenderer\\fluidRenderingObject.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2609,"name":"read-resource","id":2610,"timestamp":839451679415,"duration":54785,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1708,"name":"build-module-js","id":2609,"timestamp":839451679408,"duration":54903,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\equirectangularPanorama.fragment.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2599,"name":"read-resource","id":2600,"timestamp":839451679344,"duration":54975,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1668,"name":"build-module-js","id":2599,"timestamp":839451679336,"duration":55324,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\fluidRenderer\\fluidRenderingObjectCustomParticles.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2611,"name":"read-resource","id":2612,"timestamp":839451679428,"duration":55242,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1708,"name":"build-module-js","id":2611,"timestamp":839451679421,"duration":55644,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Procedurals\\customProceduralTexture.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2615,"name":"read-resource","id":2616,"timestamp":839451679458,"duration":55617,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1716,"name":"build-module-js","id":2615,"timestamp":839451679450,"duration":55906,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphConnection.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2613,"name":"read-resource","id":2614,"timestamp":839451679444,"duration":55922,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1714,"name":"build-module-js","id":2613,"timestamp":839451679435,"duration":56077,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphVariableDefinitions.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2617,"name":"read-resource","id":2618,"timestamp":839451679472,"duration":56049,"tags":{},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":1722,"name":"build-module-js","id":2617,"timestamp":839451679464,"duration":56201,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphAsyncExecutionBlock.js","layer":"app-pages-browser"},"startTime":1704500738863},{"traceId":"4dea77cda8cb5b99","parentId":2621,"name":"read-resource","id":2622,"timestamp":839451680882,"duration":63957,"tags":{},"startTime":1704500738864},{"traceId":"4dea77cda8cb5b99","parentId":1732,"name":"build-module-js","id":2621,"timestamp":839451680870,"duration":64540,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\HighDynamicRange\\hdr.js","layer":"app-pages-browser"},"startTime":1704500738864},{"traceId":"4dea77cda8cb5b99","parentId":2629,"name":"read-resource","id":2630,"timestamp":839451680944,"duration":64478,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1736,"name":"build-module-js","id":2629,"timestamp":839451680936,"duration":65454,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\PerformanceViewer\\performanceViewerCollector.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2619,"name":"read-resource","id":2620,"timestamp":839451680859,"duration":65543,"tags":{},"startTime":1704500738864},{"traceId":"4dea77cda8cb5b99","parentId":1718,"name":"build-module-js","id":2619,"timestamp":839451680834,"duration":65786,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphDataConnection.js","layer":"app-pages-browser"},"startTime":1704500738864},{"traceId":"4dea77cda8cb5b99","parentId":2623,"name":"read-resource","id":2624,"timestamp":839451680899,"duration":65730,"tags":{},"startTime":1704500738864},{"traceId":"4dea77cda8cb5b99","parentId":1732,"name":"build-module-js","id":2623,"timestamp":839451680889,"duration":66223,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\HighDynamicRange\\panoramaToCubemap.js","layer":"app-pages-browser"},"startTime":1704500738864},{"traceId":"4dea77cda8cb5b99","parentId":2631,"name":"read-resource","id":2632,"timestamp":839451680958,"duration":66165,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1756,"name":"build-module-js","id":2631,"timestamp":839451680950,"duration":66559,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\shaderCodeNode.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2625,"name":"read-resource","id":2626,"timestamp":839451680914,"duration":66605,"tags":{},"startTime":1704500738864},{"traceId":"4dea77cda8cb5b99","parentId":1736,"name":"build-module-js","id":2625,"timestamp":839451680905,"duration":67366,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\PerformanceViewer\\performanceViewerCollectionStrategies.js","layer":"app-pages-browser"},"startTime":1704500738864},{"traceId":"4dea77cda8cb5b99","parentId":2627,"name":"read-resource","id":2628,"timestamp":839451680930,"duration":67351,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1736,"name":"build-module-js","id":2627,"timestamp":839451680921,"duration":67531,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\PerformanceViewer\\dynamicFloat32Array.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2633,"name":"read-resource","id":2634,"timestamp":839451680972,"duration":67489,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1736,"name":"build-module-js","id":2633,"timestamp":839451680964,"duration":67580,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Misc\\PerformanceViewer\\performanceViewerSceneExtension.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2639,"name":"read-resource","id":2640,"timestamp":839451681014,"duration":67572,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1756,"name":"build-module-js","id":2639,"timestamp":839451681006,"duration":67688,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\shaderCodeTestNode.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2641,"name":"read-resource","id":2642,"timestamp":839451681029,"duration":67678,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1742,"name":"build-module-js","id":2641,"timestamp":839451681020,"duration":67780,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\index.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2637,"name":"read-resource","id":2638,"timestamp":839451681001,"duration":67806,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1756,"name":"build-module-js","id":2637,"timestamp":839451680992,"duration":67983,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\shaderCodeConditionNode.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2635,"name":"read-resource","id":2636,"timestamp":839451680986,"duration":68001,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1756,"name":"build-module-js","id":2635,"timestamp":839451680978,"duration":68216,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\shaderCodeCursor.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2643,"name":"read-resource","id":2644,"timestamp":839451681043,"duration":68161,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1742,"name":"build-module-js","id":2643,"timestamp":839451681034,"duration":68261,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\index.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2645,"name":"read-resource","id":2646,"timestamp":839451681058,"duration":68244,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1756,"name":"build-module-js","id":2645,"timestamp":839451681049,"duration":68605,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\Expressions\\shaderDefineExpression.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2647,"name":"read-resource","id":2648,"timestamp":839451681072,"duration":68592,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1756,"name":"build-module-js","id":2647,"timestamp":839451681064,"duration":68713,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\Expressions\\Operators\\shaderDefineOrOperator.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2649,"name":"read-resource","id":2650,"timestamp":839451681086,"duration":68700,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1756,"name":"build-module-js","id":2649,"timestamp":839451681078,"duration":68889,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\Expressions\\Operators\\shaderDefineArithmeticOperator.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2651,"name":"read-resource","id":2652,"timestamp":839451681334,"duration":75734,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1756,"name":"build-module-js","id":2651,"timestamp":839451681315,"duration":75917,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\Expressions\\Operators\\shaderDefineIsDefinedOperator.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2657,"name":"read-resource","id":2658,"timestamp":839451681385,"duration":75856,"tags":{},"startTime":1704500738865}] +[{"traceId":"4dea77cda8cb5b99","parentId":1827,"name":"build-module-js","id":2657,"timestamp":839451681377,"duration":76207,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\DeviceInput\\nativeDeviceInputSystem.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2653,"name":"read-resource","id":2654,"timestamp":839451681355,"duration":76240,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1756,"name":"build-module-js","id":2653,"timestamp":839451681345,"duration":76357,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\Processors\\Expressions\\Operators\\shaderDefineAndOperator.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2655,"name":"read-resource","id":2656,"timestamp":839451681371,"duration":76341,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1742,"name":"build-module-js","id":2655,"timestamp":839451681362,"duration":76430,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Event\\index.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2659,"name":"read-resource","id":2660,"timestamp":839451681400,"duration":76399,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1827,"name":"build-module-js","id":2659,"timestamp":839451681391,"duration":78232,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\DeviceInput\\webDeviceInputSystem.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2661,"name":"read-resource","id":2662,"timestamp":839451681414,"duration":78220,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1734,"name":"build-module-js","id":2661,"timestamp":839451681406,"duration":78989,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\scheduler\\cjs\\scheduler.production.min.js","layer":"null"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":125,"timestamp":839449520793,"duration":2241322,"tags":{"request":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\router.js"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":119,"timestamp":839449520720,"duration":2241400,"tags":{"request":"./node_modules/next/dist/client/next.js"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":2663,"name":"read-resource","id":2664,"timestamp":839451681429,"duration":81076,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1925,"name":"build-module-js","id":2663,"timestamp":839451681421,"duration":81223,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\clearQuad.vertex.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2665,"name":"read-resource","id":2666,"timestamp":839451681443,"duration":81210,"tags":{},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":1925,"name":"build-module-js","id":2665,"timestamp":839451681435,"duration":81329,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\clearQuad.fragment.js","layer":"app-pages-browser"},"startTime":1704500738865},{"traceId":"4dea77cda8cb5b99","parentId":2667,"name":"read-resource","id":2668,"timestamp":839451751519,"duration":13120,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2667,"timestamp":839451751490,"duration":13287,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\bonesDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2675,"name":"read-resource","id":2676,"timestamp":839451751662,"duration":13125,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2675,"timestamp":839451751653,"duration":13341,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\bakedVertexAnimation.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2677,"name":"read-resource","id":2678,"timestamp":839451751678,"duration":13329,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2677,"timestamp":839451751668,"duration":13494,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\clipPlaneFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2669,"name":"read-resource","id":2670,"timestamp":839451751603,"duration":13572,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2669,"timestamp":839451751538,"duration":13802,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\bonesVertex.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2673,"name":"read-resource","id":2674,"timestamp":839451751647,"duration":13705,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2673,"timestamp":839451751638,"duration":13898,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\clipPlaneFragment.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2671,"name":"read-resource","id":2672,"timestamp":839451751630,"duration":13918,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2671,"timestamp":839451751617,"duration":14083,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\bakedVertexAnimationDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2681,"name":"read-resource","id":2682,"timestamp":839451751706,"duration":14007,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2681,"timestamp":839451751699,"duration":14160,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\clipPlaneVertex.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2683,"name":"read-resource","id":2684,"timestamp":839451751720,"duration":14150,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2683,"timestamp":839451751712,"duration":14269,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\instancesDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2679,"name":"read-resource","id":2680,"timestamp":839451751693,"duration":14298,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2679,"timestamp":839451751685,"duration":14401,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\clipPlaneVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2685,"name":"read-resource","id":2686,"timestamp":839451751796,"duration":14297,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2685,"timestamp":839451751726,"duration":14499,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\instancesVertex.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2687,"name":"read-resource","id":2688,"timestamp":839451751816,"duration":14419,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2687,"timestamp":839451751804,"duration":14528,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\meshUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2689,"name":"read-resource","id":2690,"timestamp":839451751838,"duration":14502,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2689,"timestamp":839451751829,"duration":14611,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\morphTargetsVertex.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2693,"name":"read-resource","id":2694,"timestamp":839451751866,"duration":14583,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2693,"timestamp":839451751858,"duration":14683,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\morphTargetsVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2695,"name":"read-resource","id":2696,"timestamp":839451751881,"duration":14668,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2695,"timestamp":839451751871,"duration":14771,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\morphTargetsVertexGlobalDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2697,"name":"read-resource","id":2698,"timestamp":839451751895,"duration":14756,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2697,"timestamp":839451751887,"duration":14850,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\sceneUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2703,"name":"read-resource","id":2704,"timestamp":839451751939,"duration":14805,"tags":{},"startTime":1704500738936},{"traceId":"4dea77cda8cb5b99","parentId":1931,"name":"build-module-js","id":2703,"timestamp":839451751931,"duration":15162,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuQuerySet.js","layer":"app-pages-browser"},"startTime":1704500738936},{"traceId":"4dea77cda8cb5b99","parentId":2705,"name":"read-resource","id":2706,"timestamp":839451751952,"duration":15153,"tags":{},"startTime":1704500738936},{"traceId":"4dea77cda8cb5b99","parentId":2003,"name":"build-module-js","id":2705,"timestamp":839451751945,"duration":15689,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGL\\webGLRenderTargetWrapper.js","layer":"app-pages-browser"},"startTime":1704500738936},{"traceId":"4dea77cda8cb5b99","parentId":2691,"name":"read-resource","id":2692,"timestamp":839451751852,"duration":15793,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1881,"name":"build-module-js","id":2691,"timestamp":839451751844,"duration":15928,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\ShadersWGSL\\ShadersInclude\\morphTargetsVertexGlobal.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2707,"name":"read-resource","id":2708,"timestamp":839451755441,"duration":12343,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":1991,"name":"build-module-js","id":2707,"timestamp":839451751959,"duration":16015,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\MultiviewRenderTarget.js","layer":"app-pages-browser"},"startTime":1704500738936},{"traceId":"4dea77cda8cb5b99","parentId":2711,"name":"read-resource","id":2712,"timestamp":839451755532,"duration":12451,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2027,"name":"build-module-js","id":2711,"timestamp":839451755519,"duration":12571,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\clipPlaneFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2709,"name":"read-resource","id":2710,"timestamp":839451755505,"duration":12596,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2027,"name":"build-module-js","id":2709,"timestamp":839451755461,"duration":12759,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\helperFunctions.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2715,"name":"read-resource","id":2716,"timestamp":839451755567,"duration":12664,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2715,"timestamp":839451755558,"duration":12765,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\bonesDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2713,"name":"read-resource","id":2714,"timestamp":839451755551,"duration":12780,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2027,"name":"build-module-js","id":2713,"timestamp":839451755541,"duration":12930,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\clipPlaneFragment.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2701,"name":"read-resource","id":2702,"timestamp":839451751923,"duration":16560,"tags":{},"startTime":1704500738936},{"traceId":"4dea77cda8cb5b99","parentId":1953,"name":"build-module-js","id":2701,"timestamp":839451751915,"duration":16690,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\background.vertex.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2717,"name":"read-resource","id":2718,"timestamp":839451755600,"duration":13013,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2717,"timestamp":839451755572,"duration":13159,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\bakedVertexAnimationDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2719,"name":"read-resource","id":2720,"timestamp":839451755623,"duration":13119,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2719,"timestamp":839451755612,"duration":13256,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\morphTargetsVertexGlobalDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2721,"name":"read-resource","id":2722,"timestamp":839451755638,"duration":13239,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2721,"timestamp":839451755630,"duration":13340,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\morphTargetsVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2725,"name":"read-resource","id":2726,"timestamp":839451755685,"duration":13293,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2725,"timestamp":839451755659,"duration":13403,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\morphTargetsVertexGlobal.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2723,"name":"read-resource","id":2724,"timestamp":839451755653,"duration":13417,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2723,"timestamp":839451755644,"duration":13515,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\clipPlaneVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2729,"name":"read-resource","id":2730,"timestamp":839451755720,"duration":13448,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2729,"timestamp":839451755712,"duration":13545,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\instancesDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2699,"name":"read-resource","id":2700,"timestamp":839451751908,"duration":17358,"tags":{},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":1953,"name":"build-module-js","id":2699,"timestamp":839451751901,"duration":17512,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\background.fragment.js","layer":"app-pages-browser"},"startTime":1704500738935},{"traceId":"4dea77cda8cb5b99","parentId":2727,"name":"read-resource","id":2728,"timestamp":839451755706,"duration":13715,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2727,"timestamp":839451755696,"duration":13850,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\morphTargetsVertex.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2731,"name":"read-resource","id":2732,"timestamp":839451755737,"duration":13819,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2731,"timestamp":839451755726,"duration":13925,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\instancesVertex.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2735,"name":"read-resource","id":2736,"timestamp":839451755787,"duration":13872,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2735,"timestamp":839451755777,"duration":13972,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\clipPlaneVertex.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2737,"name":"read-resource","id":2738,"timestamp":839451755802,"duration":13956,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2737,"timestamp":839451755794,"duration":14065,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\bakedVertexAnimation.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2733,"name":"read-resource","id":2734,"timestamp":839451755767,"duration":14101,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2031,"name":"build-module-js","id":2733,"timestamp":839451755743,"duration":14220,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\bonesVertex.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2739,"name":"read-resource","id":2740,"timestamp":839451755815,"duration":14155,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2739,"timestamp":839451755808,"duration":14296,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\defaultFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2741,"name":"read-resource","id":2742,"timestamp":839451755833,"duration":14280,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2741,"timestamp":839451755825,"duration":14384,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\defaultUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2743,"name":"read-resource","id":2744,"timestamp":839451755848,"duration":14368,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2743,"timestamp":839451755839,"duration":16980,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\prePassDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2747,"name":"read-resource","id":2748,"timestamp":839451755875,"duration":16955,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2747,"timestamp":839451755868,"duration":17086,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\lightFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2745,"name":"read-resource","id":2746,"timestamp":839451755862,"duration":17101,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2745,"timestamp":839451755854,"duration":17237,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\oitDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2749,"name":"read-resource","id":2750,"timestamp":839451755889,"duration":17213,"tags":{},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2749,"timestamp":839451755881,"duration":17329,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\lightUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738939},{"traceId":"4dea77cda8cb5b99","parentId":2751,"name":"read-resource","id":2752,"timestamp":839451761794,"duration":14686,"tags":{},"startTime":1704500738945},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2751,"timestamp":839451761770,"duration":14841,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\mainUVVaryingDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738945}] +[{"traceId":"4dea77cda8cb5b99","parentId":2757,"name":"read-resource","id":2758,"timestamp":839451761860,"duration":14863,"tags":{},"startTime":1704500738945},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2757,"timestamp":839451761851,"duration":15026,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\samplerFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738945},{"traceId":"4dea77cda8cb5b99","parentId":2755,"name":"read-resource","id":2756,"timestamp":839451761845,"duration":15043,"tags":{},"startTime":1704500738945},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2755,"timestamp":839451761836,"duration":15278,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\shadowsFragmentFunctions.js","layer":"app-pages-browser"},"startTime":1704500738945},{"traceId":"4dea77cda8cb5b99","parentId":2753,"name":"read-resource","id":2754,"timestamp":839451761827,"duration":15296,"tags":{},"startTime":1704500738945},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2753,"timestamp":839451761809,"duration":15421,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\lightsFragmentFunctions.js","layer":"app-pages-browser"},"startTime":1704500738945},{"traceId":"4dea77cda8cb5b99","parentId":2763,"name":"read-resource","id":2764,"timestamp":839451761964,"duration":15274,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2763,"timestamp":839451761955,"duration":15372,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\imageProcessingDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2765,"name":"read-resource","id":2766,"timestamp":839451761978,"duration":15357,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2765,"timestamp":839451761969,"duration":15474,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\imageProcessingFunctions.js","layer":"app-pages-browser"},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2761,"name":"read-resource","id":2762,"timestamp":839451761948,"duration":15503,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2761,"timestamp":839451761936,"duration":15623,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\reflectionFunction.js","layer":"app-pages-browser"},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2759,"name":"read-resource","id":2760,"timestamp":839451761926,"duration":15640,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2759,"timestamp":839451761866,"duration":15783,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\fresnelFunction.js","layer":"app-pages-browser"},"startTime":1704500738945},{"traceId":"4dea77cda8cb5b99","parentId":2769,"name":"read-resource","id":2770,"timestamp":839451762008,"duration":15649,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2769,"timestamp":839451762000,"duration":15752,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\bumpFragmentMainFunctions.js","layer":"app-pages-browser"},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2771,"name":"read-resource","id":2772,"timestamp":839451762026,"duration":15733,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2771,"timestamp":839451762016,"duration":15825,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\logDepthDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2767,"name":"read-resource","id":2768,"timestamp":839451761994,"duration":15856,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2767,"timestamp":839451761984,"duration":15990,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\bumpFragmentFunctions.js","layer":"app-pages-browser"},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2773,"name":"read-resource","id":2774,"timestamp":839451762040,"duration":15943,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2773,"timestamp":839451762032,"duration":16043,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\fogFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2775,"name":"read-resource","id":2776,"timestamp":839451762053,"duration":16029,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2775,"timestamp":839451762045,"duration":16145,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\bumpFragment.js","layer":"app-pages-browser"},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2777,"name":"read-resource","id":2778,"timestamp":839451762067,"duration":16135,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2777,"timestamp":839451762059,"duration":16241,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\decalFragment.js","layer":"app-pages-browser"},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2779,"name":"read-resource","id":2780,"timestamp":839451762082,"duration":16226,"tags":{},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2779,"timestamp":839451762073,"duration":16320,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\depthPrePass.js","layer":"app-pages-browser"},"startTime":1704500738946},{"traceId":"4dea77cda8cb5b99","parentId":2781,"name":"read-resource","id":2782,"timestamp":839451763449,"duration":16745,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2781,"timestamp":839451763426,"duration":16903,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\logDepthFragment.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2789,"name":"read-resource","id":2790,"timestamp":839451763556,"duration":16783,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2789,"timestamp":839451763548,"duration":16898,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\defaultVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2793,"name":"read-resource","id":2794,"timestamp":839451763607,"duration":16848,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2793,"timestamp":839451763577,"duration":16973,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\prePassVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2783,"name":"read-resource","id":2784,"timestamp":839451763476,"duration":17083,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2783,"timestamp":839451763464,"duration":17254,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\lightFragment.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2785,"name":"read-resource","id":2786,"timestamp":839451763519,"duration":17207,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2785,"timestamp":839451763483,"duration":17340,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\oitFragment.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2791,"name":"read-resource","id":2792,"timestamp":839451763571,"duration":17260,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2791,"timestamp":839451763563,"duration":17393,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\uvAttributeDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2795,"name":"read-resource","id":2796,"timestamp":839451763625,"duration":17341,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2795,"timestamp":839451763615,"duration":17456,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\samplerVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2787,"name":"read-resource","id":2788,"timestamp":839451763541,"duration":17539,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2035,"name":"build-module-js","id":2787,"timestamp":839451763531,"duration":17642,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\fogFragment.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2797,"name":"read-resource","id":2798,"timestamp":839451763638,"duration":17543,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2797,"timestamp":839451763631,"duration":17640,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\lightVxFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2799,"name":"read-resource","id":2800,"timestamp":839451763653,"duration":17626,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2799,"timestamp":839451763645,"duration":17722,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\fogVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2803,"name":"read-resource","id":2804,"timestamp":839451763702,"duration":17672,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2803,"timestamp":839451763692,"duration":17769,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\lightVxUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2801,"name":"read-resource","id":2802,"timestamp":839451763684,"duration":17785,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2801,"timestamp":839451763658,"duration":17895,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\bumpVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2805,"name":"read-resource","id":2806,"timestamp":839451763716,"duration":17845,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2805,"timestamp":839451763708,"duration":17943,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\prePassVertex.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2809,"name":"read-resource","id":2810,"timestamp":839451763763,"duration":17896,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2809,"timestamp":839451763736,"duration":18009,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\samplerVertexImplementation.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2807,"name":"read-resource","id":2808,"timestamp":839451763730,"duration":18022,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2807,"timestamp":839451763723,"duration":18111,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\uvVariableDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2811,"name":"read-resource","id":2812,"timestamp":839451763782,"duration":18058,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2811,"timestamp":839451763772,"duration":18154,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\vertexColorMixing.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2813,"name":"read-resource","id":2814,"timestamp":839451763795,"duration":18139,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2813,"timestamp":839451763787,"duration":18296,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\fogVertex.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2815,"name":"read-resource","id":2816,"timestamp":839451763808,"duration":18285,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2815,"timestamp":839451763801,"duration":18381,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\bumpVertex.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2817,"name":"read-resource","id":2818,"timestamp":839451763826,"duration":18363,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2817,"timestamp":839451763814,"duration":18461,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pointCloudVertex.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2819,"name":"read-resource","id":2820,"timestamp":839451763859,"duration":18423,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2819,"timestamp":839451763832,"duration":18534,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\logDepthVertex.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2821,"name":"read-resource","id":2822,"timestamp":839451763877,"duration":18497,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2037,"name":"build-module-js","id":2821,"timestamp":839451763868,"duration":18593,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\shadowsVertex.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2825,"name":"read-resource","id":2826,"timestamp":839451763906,"duration":18563,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2047,"name":"build-module-js","id":2825,"timestamp":839451763898,"duration":20226,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v1\\Plugins\\cannonJSPlugin.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2823,"name":"read-resource","id":2824,"timestamp":839451763893,"duration":20243,"tags":{},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2047,"name":"build-module-js","id":2823,"timestamp":839451763885,"duration":21161,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v1\\Plugins\\oimoJSPlugin.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2827,"name":"read-resource","id":2828,"timestamp":839451763921,"duration":21136,"tags":{},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2047,"name":"build-module-js","id":2827,"timestamp":839451763912,"duration":27058,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v1\\Plugins\\ammoJSPlugin.js","layer":"app-pages-browser"},"startTime":1704500738947},{"traceId":"4dea77cda8cb5b99","parentId":2831,"name":"read-resource","id":2832,"timestamp":839451764413,"duration":29638,"tags":{},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2081,"name":"build-module-js","id":2831,"timestamp":839451764399,"duration":29815,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Enums\\nodeMaterialBlockConnectionPointTypes.js","layer":"app-pages-browser"},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2829,"name":"read-resource","id":2830,"timestamp":839451764383,"duration":29842,"tags":{},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2829,"timestamp":839451764343,"duration":30802,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\nodeMaterialBuildState.js","layer":"app-pages-browser"},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2841,"name":"read-resource","id":2842,"timestamp":839451764550,"duration":30606,"tags":{},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2841,"timestamp":839451764535,"duration":30998,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\remapBlock.js","layer":"app-pages-browser"},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2835,"name":"read-resource","id":2836,"timestamp":839451764463,"duration":31128,"tags":{},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2835,"timestamp":839451764444,"duration":31432,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\nodeMaterialBuildStateSharedData.js","layer":"app-pages-browser"},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2833,"name":"read-resource","id":2834,"timestamp":839451764430,"duration":31476,"tags":{},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2081,"name":"build-module-js","id":2833,"timestamp":839451764422,"duration":31609,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Enums\\nodeMaterialBlockTargets.js","layer":"app-pages-browser"},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2837,"name":"read-resource","id":2838,"timestamp":839451764492,"duration":31549,"tags":{},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2837,"timestamp":839451764474,"duration":32021,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\transformBlock.js","layer":"app-pages-browser"},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2845,"name":"read-resource","id":2846,"timestamp":839451764580,"duration":31927,"tags":{},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2845,"timestamp":839451764572,"duration":32243,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\colorSplitterBlock.js","layer":"app-pages-browser"},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2843,"name":"read-resource","id":2844,"timestamp":839451764566,"duration":32259,"tags":{},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2843,"timestamp":839451764558,"duration":32518,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\multiplyBlock.js","layer":"app-pages-browser"},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2839,"name":"read-resource","id":2840,"timestamp":839451764526,"duration":32564,"tags":{},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2839,"timestamp":839451764505,"duration":33252,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\vectorMergerBlock.js","layer":"app-pages-browser"},"startTime":1704500738948},{"traceId":"4dea77cda8cb5b99","parentId":2847,"name":"read-resource","id":2848,"timestamp":839451775406,"duration":29206,"tags":{},"startTime":1704500738959},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2847,"timestamp":839451775381,"duration":29366,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Enums\\nodeMaterialModes.js","layer":"app-pages-browser"},"startTime":1704500738959},{"traceId":"4dea77cda8cb5b99","parentId":2849,"name":"read-resource","id":2850,"timestamp":839451779081,"duration":26431,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2849,"timestamp":839451779058,"duration":28034,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Procedurals\\proceduralTexture.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2853,"name":"read-resource","id":2854,"timestamp":839451779147,"duration":27958,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2853,"timestamp":839451779117,"duration":28133,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Enums\\nodeMaterialSystemValues.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2851,"name":"read-resource","id":2852,"timestamp":839451779109,"duration":28170,"tags":{},"startTime":1704500738963}] +[{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2851,"timestamp":839451779097,"duration":28795,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\trigonometryBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2861,"name":"read-resource","id":2862,"timestamp":839451779212,"duration":28691,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2085,"name":"build-module-js","id":2861,"timestamp":839451779202,"duration":28851,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Loaders\\tgaTextureLoader.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2863,"name":"read-resource","id":2864,"timestamp":839451779226,"duration":28837,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2109,"name":"build-module-js","id":2863,"timestamp":839451779218,"duration":28928,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuRenderTargetWrapper.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2855,"name":"read-resource","id":2856,"timestamp":839451779169,"duration":28986,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2089,"name":"build-module-js","id":2855,"timestamp":839451779157,"duration":29408,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuComputeContext.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2857,"name":"read-resource","id":2858,"timestamp":839451779183,"duration":29392,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2089,"name":"build-module-js","id":2857,"timestamp":839451779175,"duration":29517,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuComputePipelineContext.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2865,"name":"read-resource","id":2866,"timestamp":839451779257,"duration":29444,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2085,"name":"build-module-js","id":2865,"timestamp":839451779232,"duration":29666,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Loaders\\hdrTextureLoader.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2871,"name":"read-resource","id":2872,"timestamp":839451779305,"duration":29602,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2871,"timestamp":839451779297,"duration":31116,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Input\\inputBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2859,"name":"read-resource","id":2860,"timestamp":839451779196,"duration":31227,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2099,"name":"build-module-js","id":2859,"timestamp":839451779189,"duration":31331,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Engines\\WebGPU\\webgpuExternalTexture.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2873,"name":"read-resource","id":2874,"timestamp":839451779319,"duration":31209,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2873,"timestamp":839451779311,"duration":31317,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Input\\animatedInputBlockTypes.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2875,"name":"read-resource","id":2876,"timestamp":839451779353,"duration":31284,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2875,"timestamp":839451779325,"duration":31517,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Particle\\particleRampGradientBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2877,"name":"read-resource","id":2878,"timestamp":839451779373,"duration":31478,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2877,"timestamp":839451779364,"duration":31694,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Particle\\particleBlendMultiplyBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2867,"name":"read-resource","id":2868,"timestamp":839451779276,"duration":31792,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2085,"name":"build-module-js","id":2867,"timestamp":839451779265,"duration":32075,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Loaders\\basisTextureLoader.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2881,"name":"read-resource","id":2882,"timestamp":839451779401,"duration":31949,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2881,"timestamp":839451779394,"duration":32518,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Dual\\currentScreenBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2883,"name":"read-resource","id":2884,"timestamp":839451779416,"duration":32506,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2883,"timestamp":839451779407,"duration":32942,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\fragmentOutputBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2889,"name":"read-resource","id":2890,"timestamp":839451779478,"duration":32881,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2889,"timestamp":839451779467,"duration":33073,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\addBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2879,"name":"read-resource","id":2880,"timestamp":839451779388,"duration":33162,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2879,"timestamp":839451779380,"duration":33652,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Particle\\particleTextureBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"read-resource","id":2886,"timestamp":839451779429,"duration":33614,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2125,"name":"build-module-js","id":2885,"timestamp":839451779422,"duration":33889,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\pbr.fragment.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2869,"name":"read-resource","id":2870,"timestamp":839451779290,"duration":34030,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2079,"name":"build-module-js","id":2869,"timestamp":839451779283,"duration":34224,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Vertex\\vertexOutputBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2893,"name":"read-resource","id":2894,"timestamp":839451779505,"duration":34011,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2893,"timestamp":839451779497,"duration":34192,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\scaleBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2887,"name":"read-resource","id":2888,"timestamp":839451779459,"duration":34240,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2125,"name":"build-module-js","id":2887,"timestamp":839451779435,"duration":34458,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\pbr.vertex.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2895,"name":"read-resource","id":2896,"timestamp":839451779534,"duration":34368,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2895,"timestamp":839451779511,"duration":34578,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\dotBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2891,"name":"read-resource","id":2892,"timestamp":839451779491,"duration":34607,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2891,"timestamp":839451779484,"duration":34852,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\clampBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2899,"name":"read-resource","id":2900,"timestamp":839451779566,"duration":34779,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2899,"timestamp":839451779558,"duration":35285,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\customBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2901,"name":"read-resource","id":2902,"timestamp":839451779579,"duration":35275,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2901,"timestamp":839451779571,"duration":35463,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\normalizeBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2897,"name":"read-resource","id":2898,"timestamp":839451779552,"duration":35492,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2897,"timestamp":839451779542,"duration":35696,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\crossBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2909,"name":"read-resource","id":2910,"timestamp":839451779668,"duration":35578,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2909,"timestamp":839451779660,"duration":35764,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\divideBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2907,"name":"read-resource","id":2908,"timestamp":839451779654,"duration":35779,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2907,"timestamp":839451779645,"duration":35970,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\lerpBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2903,"name":"read-resource","id":2904,"timestamp":839451779592,"duration":36032,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2903,"timestamp":839451779584,"duration":39559,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\colorMergerBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2905,"name":"read-resource","id":2906,"timestamp":839451779636,"duration":39521,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2905,"timestamp":839451779598,"duration":39949,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\vectorSplitterBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2911,"name":"read-resource","id":2912,"timestamp":839451779682,"duration":39875,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2911,"timestamp":839451779675,"duration":40082,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\subtractBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2913,"name":"read-resource","id":2914,"timestamp":839451779697,"duration":40070,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2913,"timestamp":839451779688,"duration":40264,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\stepBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2917,"name":"read-resource","id":2918,"timestamp":839451779724,"duration":40239,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2917,"timestamp":839451779717,"duration":40413,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\maxBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2915,"name":"read-resource","id":2916,"timestamp":839451779711,"duration":40429,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2915,"timestamp":839451779703,"duration":40604,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\oneMinusBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2923,"name":"read-resource","id":2924,"timestamp":839451779770,"duration":40547,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2923,"timestamp":839451779761,"duration":40801,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\fresnelBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2919,"name":"read-resource","id":2920,"timestamp":839451779737,"duration":40834,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2919,"timestamp":839451779730,"duration":41054,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\viewDirectionBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2921,"name":"read-resource","id":2922,"timestamp":839451779755,"duration":41039,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2921,"timestamp":839451779747,"duration":41224,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\minBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2927,"name":"read-resource","id":2928,"timestamp":839451779796,"duration":41185,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2927,"timestamp":839451779788,"duration":41351,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\lengthBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2925,"name":"read-resource","id":2926,"timestamp":839451779783,"duration":41365,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2925,"timestamp":839451779775,"duration":41549,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\distanceBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2933,"name":"read-resource","id":2934,"timestamp":839451779836,"duration":41497,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2933,"timestamp":839451779828,"duration":41655,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\arcTan2Block.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2929,"name":"read-resource","id":2930,"timestamp":839451779808,"duration":41683,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2929,"timestamp":839451779801,"duration":41841,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\negateBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2931,"name":"read-resource","id":2932,"timestamp":839451779823,"duration":41828,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2931,"timestamp":839451779814,"duration":41996,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\powBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2935,"name":"read-resource","id":2936,"timestamp":839451779854,"duration":41964,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2935,"timestamp":839451779847,"duration":42147,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\randomNumberBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2937,"name":"read-resource","id":2938,"timestamp":839451779867,"duration":42136,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2937,"timestamp":839451779860,"duration":42311,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\smoothStepBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2939,"name":"read-resource","id":2940,"timestamp":839451779881,"duration":42298,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2939,"timestamp":839451779874,"duration":42537,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\replaceColorBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2943,"name":"read-resource","id":2944,"timestamp":839451779909,"duration":42510,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2943,"timestamp":839451779902,"duration":42685,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\reciprocalBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2945,"name":"read-resource","id":2946,"timestamp":839451779923,"duration":42673,"tags":{},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2945,"timestamp":839451779915,"duration":42936,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\waveBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2941,"name":"read-resource","id":2942,"timestamp":839451779896,"duration":42965,"tags":{},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2941,"timestamp":839451779887,"duration":43153,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\posterizeBlock.js","layer":"app-pages-browser"},"startTime":1704500738963},{"traceId":"4dea77cda8cb5b99","parentId":2947,"name":"read-resource","id":2948,"timestamp":839451779936,"duration":43113,"tags":{},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2947,"timestamp":839451779928,"duration":43582,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\gradientBlock.js","layer":"app-pages-browser"},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2951,"name":"read-resource","id":2952,"timestamp":839451779964,"duration":43561,"tags":{},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2951,"timestamp":839451779956,"duration":44198,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\worleyNoise3DBlock.js","layer":"app-pages-browser"},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2949,"name":"read-resource","id":2950,"timestamp":839451779951,"duration":44214,"tags":{},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2949,"timestamp":839451779942,"duration":44410,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\nLerpBlock.js","layer":"app-pages-browser"},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2953,"name":"read-resource","id":2954,"timestamp":839451779977,"duration":44383,"tags":{},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2953,"timestamp":839451779970,"duration":44616,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\normalBlendBlock.js","layer":"app-pages-browser"},"startTime":1704500738964}] +[{"traceId":"4dea77cda8cb5b99","parentId":2957,"name":"read-resource","id":2958,"timestamp":839451780006,"duration":44679,"tags":{},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2957,"timestamp":839451779997,"duration":44989,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\simplexPerlin3DBlock.js","layer":"app-pages-browser"},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2955,"name":"read-resource","id":2956,"timestamp":839451779991,"duration":45005,"tags":{},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2955,"timestamp":839451779984,"duration":45192,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\reflectBlock.js","layer":"app-pages-browser"},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2961,"name":"read-resource","id":2962,"timestamp":839451780032,"duration":45153,"tags":{},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2961,"timestamp":839451780024,"duration":45344,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\rotate2dBlock.js","layer":"app-pages-browser"},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2959,"name":"read-resource","id":2960,"timestamp":839451780019,"duration":45358,"tags":{},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2959,"timestamp":839451780011,"duration":45555,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\refractBlock.js","layer":"app-pages-browser"},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2963,"name":"read-resource","id":2964,"timestamp":839451780045,"duration":45530,"tags":{},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2963,"timestamp":839451780037,"duration":45725,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\desaturateBlock.js","layer":"app-pages-browser"},"startTime":1704500738964},{"traceId":"4dea77cda8cb5b99","parentId":2965,"name":"read-resource","id":2966,"timestamp":839451798504,"duration":46952,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2965,"timestamp":839451798477,"duration":47233,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\modBlock.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2971,"name":"read-resource","id":2972,"timestamp":839451798568,"duration":47154,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2971,"timestamp":839451798560,"duration":47595,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\cloudBlock.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2975,"name":"read-resource","id":2976,"timestamp":839451798653,"duration":47525,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2975,"timestamp":839451798642,"duration":48609,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\triPlanarBlock.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2969,"name":"read-resource","id":2970,"timestamp":839451798553,"duration":48708,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2969,"timestamp":839451798543,"duration":49160,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\conditionalBlock.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2981,"name":"read-resource","id":2982,"timestamp":839451798696,"duration":49017,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2981,"timestamp":839451798689,"duration":49135,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Dual\\index.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2979,"name":"read-resource","id":2980,"timestamp":839451798683,"duration":49148,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2979,"timestamp":839451798675,"duration":49228,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Vertex\\index.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2967,"name":"read-resource","id":2968,"timestamp":839451798534,"duration":49375,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2967,"timestamp":839451798521,"duration":49642,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\matrixBuilderBlock.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2977,"name":"read-resource","id":2978,"timestamp":839451798669,"duration":49503,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2977,"timestamp":839451798661,"duration":49719,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\elbowBlock.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2973,"name":"read-resource","id":2974,"timestamp":839451798630,"duration":49759,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2973,"timestamp":839451798575,"duration":50053,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\voronoiNoiseBlock.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"read-resource","id":2984,"timestamp":839451798729,"duration":49908,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2983,"timestamp":839451798702,"duration":50056,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\index.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2987,"name":"read-resource","id":2988,"timestamp":839451798762,"duration":50003,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2987,"timestamp":839451798754,"duration":50072,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Input\\index.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2985,"name":"read-resource","id":2986,"timestamp":839451798748,"duration":50084,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2985,"timestamp":839451798738,"duration":50149,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Particle\\index.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2989,"name":"read-resource","id":2990,"timestamp":839451798777,"duration":50116,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2147,"name":"build-module-js","id":2989,"timestamp":839451798768,"duration":50226,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\hdrFiltering.vertex.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2991,"name":"read-resource","id":2992,"timestamp":839451798812,"duration":50191,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2991,"timestamp":839451798782,"duration":50379,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\matrixTransposeBlock.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2993,"name":"read-resource","id":2994,"timestamp":839451798831,"duration":50339,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2147,"name":"build-module-js","id":2993,"timestamp":839451798821,"duration":50452,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\hdrFiltering.fragment.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2995,"name":"read-resource","id":2996,"timestamp":839451798845,"duration":50435,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2995,"timestamp":839451798838,"duration":50697,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\biPlanarBlock.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2997,"name":"read-resource","id":2998,"timestamp":839451798859,"duration":50685,"tags":{},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2997,"timestamp":839451798851,"duration":54091,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\meshAttributeExistsBlock.js","layer":"app-pages-browser"},"startTime":1704500738982},{"traceId":"4dea77cda8cb5b99","parentId":2999,"name":"read-resource","id":3000,"timestamp":839451804971,"duration":51606,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":2999,"timestamp":839451804948,"duration":52717,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\curveBlock.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3001,"name":"read-resource","id":3002,"timestamp":839451804999,"duration":52689,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":3001,"timestamp":839451804984,"duration":53058,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\matrixDeterminantBlock.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3005,"name":"read-resource","id":3006,"timestamp":839451805032,"duration":53023,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2149,"name":"build-module-js","id":3005,"timestamp":839451805023,"duration":54748,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Packer\\packer.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3007,"name":"read-resource","id":3008,"timestamp":839451805047,"duration":54743,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2159,"name":"build-module-js","id":3007,"timestamp":839451805038,"duration":54955,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Enums\\nodeMaterialBlockConnectionPointMode.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3011,"name":"read-resource","id":3012,"timestamp":839451805120,"duration":54885,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":3011,"timestamp":839451805098,"duration":55098,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\PBR\\index.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3017,"name":"read-resource","id":3018,"timestamp":839451805168,"duration":55042,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2225,"name":"build-module-js","id":3017,"timestamp":839451805160,"duration":55236,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\kernelBlurFragment2.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3009,"name":"read-resource","id":3010,"timestamp":839451805063,"duration":55353,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2151,"name":"build-module-js","id":3009,"timestamp":839451805053,"duration":55496,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Teleport\\index.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3013,"name":"read-resource","id":3014,"timestamp":839451805139,"duration":55420,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2223,"name":"build-module-js","id":3013,"timestamp":839451805129,"duration":55579,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\kernelBlurVaryingDeclaration.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3003,"name":"read-resource","id":3004,"timestamp":839451805016,"duration":55703,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2149,"name":"build-module-js","id":3003,"timestamp":839451805007,"duration":55808,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Packer\\frame.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3015,"name":"read-resource","id":3016,"timestamp":839451805154,"duration":55668,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2223,"name":"build-module-js","id":3015,"timestamp":839451805146,"duration":55781,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\kernelBlurVertex.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3019,"name":"read-resource","id":3020,"timestamp":839451805184,"duration":55752,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2225,"name":"build-module-js","id":3019,"timestamp":839451805174,"duration":55899,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\packingFunctions.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3021,"name":"read-resource","id":3022,"timestamp":839451805204,"duration":55879,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2153,"name":"build-module-js","id":3021,"timestamp":839451805190,"duration":56276,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Procedurals\\noiseProceduralTexture.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3023,"name":"read-resource","id":3024,"timestamp":839451805238,"duration":56239,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2225,"name":"build-module-js","id":3023,"timestamp":839451805219,"duration":56368,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\kernelBlurFragment.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3025,"name":"read-resource","id":3026,"timestamp":839451805259,"duration":56338,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2153,"name":"build-module-js","id":3025,"timestamp":839451805249,"duration":56546,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Textures\\Procedurals\\proceduralTextureSceneComponent.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3027,"name":"read-resource","id":3028,"timestamp":839451805275,"duration":56530,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2157,"name":"build-module-js","id":3027,"timestamp":839451805265,"duration":56633,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Optimizers\\nodeMaterialOptimizer.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3031,"name":"read-resource","id":3032,"timestamp":839451805304,"duration":56607,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2247,"name":"build-module-js","id":3031,"timestamp":839451805296,"duration":56989,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\shadowMap.vertex.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3029,"name":"read-resource","id":3030,"timestamp":839451805290,"duration":57007,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2247,"name":"build-module-js","id":3029,"timestamp":839451805282,"duration":57133,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\shadowMap.fragment.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3041,"name":"read-resource","id":3042,"timestamp":839451805398,"duration":57026,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2443,"name":"build-module-js","id":3041,"timestamp":839451805390,"duration":57227,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRLayerWrapper.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3043,"name":"read-resource","id":3044,"timestamp":839451805411,"duration":57236,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2443,"name":"build-module-js","id":3043,"timestamp":839451805403,"duration":57569,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\XR\\webXRRenderTargetTextureProvider.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3035,"name":"read-resource","id":3036,"timestamp":839451805355,"duration":57639,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2247,"name":"build-module-js","id":3035,"timestamp":839451805343,"duration":57950,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\shadowMapFragmentSoftTransparentShadow.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3039,"name":"read-resource","id":3040,"timestamp":839451805384,"duration":57920,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2373,"name":"build-module-js","id":3039,"timestamp":839451805376,"duration":58223,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\Node\\Blocks\\Instances\\instantiateBaseBlock.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3037,"name":"read-resource","id":3038,"timestamp":839451805370,"duration":58241,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2241,"name":"build-module-js","id":3037,"timestamp":839451805362,"duration":58357,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Meshes\\buffer.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3033,"name":"read-resource","id":3034,"timestamp":839451805333,"duration":58395,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2247,"name":"build-module-js","id":3033,"timestamp":839451805315,"duration":58519,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\depthBoxBlur.fragment.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3045,"name":"read-resource","id":3046,"timestamp":839451805464,"duration":69926,"tags":{},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":2435,"name":"build-module-js","id":3045,"timestamp":839451805423,"duration":70134,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\clipPlaneFragmentDeclaration2.js","layer":"app-pages-browser"},"startTime":1704500738989},{"traceId":"4dea77cda8cb5b99","parentId":3047,"name":"read-resource","id":3048,"timestamp":839451843690,"duration":35323,"tags":{},"startTime":1704500739027},{"traceId":"4dea77cda8cb5b99","parentId":2453,"name":"build-module-js","id":3047,"timestamp":839451843415,"duration":35772,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\sprites.fragment.js","layer":"app-pages-browser"},"startTime":1704500739027},{"traceId":"4dea77cda8cb5b99","parentId":3053,"name":"read-resource","id":3054,"timestamp":839451843755,"duration":35442,"tags":{},"startTime":1704500739027},{"traceId":"4dea77cda8cb5b99","parentId":2463,"name":"build-module-js","id":3053,"timestamp":839451843747,"duration":35584,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\boundingBoxRendererFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739027},{"traceId":"4dea77cda8cb5b99","parentId":3049,"name":"read-resource","id":3050,"timestamp":839451843722,"duration":35617,"tags":{},"startTime":1704500739027},{"traceId":"4dea77cda8cb5b99","parentId":2437,"name":"build-module-js","id":3049,"timestamp":839451843708,"duration":35756,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\clipPlaneVertexDeclaration2.js","layer":"app-pages-browser"},"startTime":1704500739027},{"traceId":"4dea77cda8cb5b99","parentId":3051,"name":"read-resource","id":3052,"timestamp":839451843741,"duration":35732,"tags":{},"startTime":1704500739027},{"traceId":"4dea77cda8cb5b99","parentId":2453,"name":"build-module-js","id":3051,"timestamp":839451843731,"duration":35872,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\sprites.vertex.js","layer":"app-pages-browser"},"startTime":1704500739027},{"traceId":"4dea77cda8cb5b99","parentId":3055,"name":"read-resource","id":3056,"timestamp":839451877777,"duration":5371,"tags":{},"startTime":1704500739061}] +[{"traceId":"4dea77cda8cb5b99","parentId":2463,"name":"build-module-js","id":3055,"timestamp":839451877749,"duration":5758,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\boundingBoxRendererUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":3057,"name":"read-resource","id":3058,"timestamp":839451877812,"duration":5719,"tags":{},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":2465,"name":"build-module-js","id":3057,"timestamp":839451877796,"duration":5899,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\boundingBoxRendererVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":3063,"name":"read-resource","id":3064,"timestamp":839451877874,"duration":5834,"tags":{},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":2487,"name":"build-module-js","id":3063,"timestamp":839451877861,"duration":5978,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\geometryUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":3061,"name":"read-resource","id":3062,"timestamp":839451877855,"duration":5993,"tags":{},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":2479,"name":"build-module-js","id":3061,"timestamp":839451877843,"duration":6125,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\mrtFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":3059,"name":"read-resource","id":3060,"timestamp":839451877836,"duration":6145,"tags":{},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":2483,"name":"build-module-js","id":3059,"timestamp":839451877821,"duration":6503,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\subSurfaceScatteringPostProcess.js","layer":"app-pages-browser"},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":3065,"name":"read-resource","id":3066,"timestamp":839451877892,"duration":6441,"tags":{},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":2487,"name":"build-module-js","id":3065,"timestamp":839451877881,"duration":6581,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\geometryVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":3067,"name":"read-resource","id":3068,"timestamp":839451877911,"duration":6559,"tags":{},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":2549,"name":"build-module-js","id":3067,"timestamp":839451877899,"duration":6695,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\velocity.fragment.js","layer":"app-pages-browser"},"startTime":1704500739061},{"traceId":"4dea77cda8cb5b99","parentId":3071,"name":"read-resource","id":3072,"timestamp":839451877946,"duration":6735,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"build-module-js","id":3071,"timestamp":839451877935,"duration":6878,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fluidRenderingParticleDepth.vertex.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3069,"name":"read-resource","id":3070,"timestamp":839451877929,"duration":6894,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2549,"name":"build-module-js","id":3069,"timestamp":839451877918,"duration":7037,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\velocity.vertex.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3077,"name":"read-resource","id":3078,"timestamp":839451878052,"duration":6915,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"build-module-js","id":3077,"timestamp":839451877994,"duration":7091,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fluidRenderingParticleDepth.fragment.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3073,"name":"read-resource","id":3074,"timestamp":839451877968,"duration":7126,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"build-module-js","id":3073,"timestamp":839451877955,"duration":7251,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fluidRenderingParticleThickness.fragment.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3075,"name":"read-resource","id":3076,"timestamp":839451877988,"duration":7225,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"build-module-js","id":3075,"timestamp":839451877976,"duration":7350,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fluidRenderingParticleThickness.vertex.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3081,"name":"read-resource","id":3082,"timestamp":839451878091,"duration":7243,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"build-module-js","id":3081,"timestamp":839451878081,"duration":7404,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fluidRenderingBilateralBlur.fragment.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3079,"name":"read-resource","id":3080,"timestamp":839451878074,"duration":7419,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"build-module-js","id":3079,"timestamp":839451878061,"duration":7555,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fluidRenderingParticleDiffuse.fragment.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3083,"name":"read-resource","id":3084,"timestamp":839451878110,"duration":7515,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"build-module-js","id":3083,"timestamp":839451878097,"duration":7645,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fluidRenderingParticleDiffuse.vertex.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3085,"name":"read-resource","id":3086,"timestamp":839451878129,"duration":7622,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"build-module-js","id":3085,"timestamp":839451878117,"duration":7747,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fluidRenderingStandardBlur.fragment.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3087,"name":"read-resource","id":3088,"timestamp":839451878145,"duration":7726,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"build-module-js","id":3087,"timestamp":839451878135,"duration":7957,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\fluidRenderer\\fluidRenderingDepthTextureCopy.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3089,"name":"read-resource","id":3090,"timestamp":839451878162,"duration":7939,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2595,"name":"build-module-js","id":3089,"timestamp":839451878151,"duration":8102,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\fluidRenderingRender.fragment.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3093,"name":"read-resource","id":3094,"timestamp":839451878199,"duration":8062,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2555,"name":"build-module-js","id":3093,"timestamp":839451878185,"duration":9257,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\Pipelines\\lensRenderingPipeline.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3091,"name":"read-resource","id":3092,"timestamp":839451878179,"duration":9274,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2601,"name":"build-module-js","id":3091,"timestamp":839451878168,"duration":10475,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\fluidRenderer\\fluidRenderingTextures.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3095,"name":"read-resource","id":3096,"timestamp":839451878217,"duration":10436,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2555,"name":"build-module-js","id":3095,"timestamp":839451878206,"duration":12939,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\Pipelines\\defaultRenderingPipeline.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3097,"name":"read-resource","id":3098,"timestamp":839451878233,"duration":12922,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2555,"name":"build-module-js","id":3097,"timestamp":839451878223,"duration":25952,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\Pipelines\\standardRenderingPipeline.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3099,"name":"read-resource","id":3100,"timestamp":839451878248,"duration":25938,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2555,"name":"build-module-js","id":3099,"timestamp":839451878239,"duration":27751,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\Pipelines\\ssao2RenderingPipeline.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3103,"name":"read-resource","id":3104,"timestamp":839451878328,"duration":27674,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2555,"name":"build-module-js","id":3103,"timestamp":839451878273,"duration":28629,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\Pipelines\\ssaoRenderingPipeline.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3101,"name":"read-resource","id":3102,"timestamp":839451878265,"duration":28647,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2555,"name":"build-module-js","id":3101,"timestamp":839451878255,"duration":31565,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\PostProcesses\\RenderPipeline\\Pipelines\\ssrRenderingPipeline.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3107,"name":"read-resource","id":3108,"timestamp":839451878370,"duration":31461,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2641,"name":"build-module-js","id":3107,"timestamp":839451878359,"duration":31671,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\flowGraphLogBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3109,"name":"read-resource","id":3110,"timestamp":839451878387,"duration":31653,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2641,"name":"build-module-js","id":3109,"timestamp":839451878377,"duration":31925,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\flowGraphSetPropertyBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3111,"name":"read-resource","id":3112,"timestamp":839451878408,"duration":31907,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2641,"name":"build-module-js","id":3111,"timestamp":839451878393,"duration":32104,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\flowGraphSetVariableBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3105,"name":"read-resource","id":3106,"timestamp":839451878352,"duration":32155,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2561,"name":"build-module-js","id":3105,"timestamp":839451878340,"duration":43842,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Physics\\v2\\Plugins\\havokPlugin.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3113,"name":"read-resource","id":3114,"timestamp":839451878426,"duration":43769,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2643,"name":"build-module-js","id":3113,"timestamp":839451878416,"duration":44027,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\flowGraphConditionalDataBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3115,"name":"read-resource","id":3116,"timestamp":839451878445,"duration":44009,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2643,"name":"build-module-js","id":3115,"timestamp":839451878434,"duration":44288,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\flowGraphCoordinateTransformBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3117,"name":"read-resource","id":3118,"timestamp":839451878462,"duration":44269,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2641,"name":"build-module-js","id":3117,"timestamp":839451878451,"duration":44475,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\flowGraphSendCustomEventBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3119,"name":"read-resource","id":3120,"timestamp":839451878478,"duration":44458,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2643,"name":"build-module-js","id":3119,"timestamp":839451878468,"duration":44655,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\flowGraphGetVariableBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3121,"name":"read-resource","id":3122,"timestamp":839451878496,"duration":44637,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2643,"name":"build-module-js","id":3121,"timestamp":839451878485,"duration":44803,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\flowGraphConstantBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3123,"name":"read-resource","id":3124,"timestamp":839451878513,"duration":44784,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2657,"name":"build-module-js","id":3123,"timestamp":839451878502,"duration":45528,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\DeviceInput\\eventFactory.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3125,"name":"read-resource","id":3126,"timestamp":839451878531,"duration":45511,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2655,"name":"build-module-js","id":3125,"timestamp":839451878519,"duration":45835,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Event\\flowGraphMeshPickEventBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3129,"name":"read-resource","id":3130,"timestamp":839451878563,"duration":45801,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2655,"name":"build-module-js","id":3129,"timestamp":839451878554,"duration":46092,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Event\\flowGraphReceiveCustomEventBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3127,"name":"read-resource","id":3128,"timestamp":839451878548,"duration":46108,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2655,"name":"build-module-js","id":3127,"timestamp":839451878537,"duration":46316,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Event\\flowGraphSceneReadyEventBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3131,"name":"read-resource","id":3132,"timestamp":839451878580,"duration":46282,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2655,"name":"build-module-js","id":3131,"timestamp":839451878569,"duration":46482,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Event\\flowGraphSceneTickEventBlock.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3135,"name":"read-resource","id":3136,"timestamp":839451878616,"duration":46445,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2641,"name":"build-module-js","id":3135,"timestamp":839451878606,"duration":46575,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\Audio\\index.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"read-resource","id":3134,"timestamp":839451878599,"duration":46592,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2641,"name":"build-module-js","id":3133,"timestamp":839451878587,"duration":46777,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\index.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3141,"name":"read-resource","id":3142,"timestamp":839451878668,"duration":46705,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2643,"name":"build-module-js","id":3141,"timestamp":839451878656,"duration":46848,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\Math\\index.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3137,"name":"read-resource","id":3138,"timestamp":839451878631,"duration":46882,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2641,"name":"build-module-js","id":3137,"timestamp":839451878622,"duration":46969,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\Animation\\index.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3139,"name":"read-resource","id":3140,"timestamp":839451878648,"duration":46950,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2643,"name":"build-module-js","id":3139,"timestamp":839451878638,"duration":47027,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\Logic\\index.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3143,"name":"read-resource","id":3144,"timestamp":839451878685,"duration":46986,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2701,"name":"build-module-js","id":3143,"timestamp":839451878675,"duration":47168,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\backgroundVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3145,"name":"read-resource","id":3146,"timestamp":839451878703,"duration":47150,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2699,"name":"build-module-js","id":3145,"timestamp":839451878693,"duration":47304,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\backgroundFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3147,"name":"read-resource","id":3148,"timestamp":839451878719,"duration":47290,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2701,"name":"build-module-js","id":3147,"timestamp":839451878709,"duration":47444,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\backgroundUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3149,"name":"read-resource","id":3150,"timestamp":839451878736,"duration":47427,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2739,"name":"build-module-js","id":3149,"timestamp":839451878725,"duration":47588,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\decalFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3151,"name":"read-resource","id":3152,"timestamp":839451878792,"duration":47532,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2741,"name":"build-module-js","id":3151,"timestamp":839451878742,"duration":47714,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\sceneUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3153,"name":"read-resource","id":3154,"timestamp":839451878815,"duration":47650,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2741,"name":"build-module-js","id":3153,"timestamp":839451878803,"duration":47808,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\meshUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3155,"name":"read-resource","id":3156,"timestamp":839451878833,"duration":47787,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2789,"name":"build-module-js","id":3155,"timestamp":839451878823,"duration":47918,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\decalVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739062}] +[{"traceId":"4dea77cda8cb5b99","parentId":3157,"name":"read-resource","id":3158,"timestamp":839451878852,"duration":48035,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3157,"timestamp":839451878841,"duration":48209,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrFragmentDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3159,"name":"read-resource","id":3160,"timestamp":839451878873,"duration":48186,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3159,"timestamp":839451878858,"duration":48370,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3161,"name":"read-resource","id":3162,"timestamp":839451878890,"duration":48348,"tags":{},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":2849,"name":"build-module-js","id":3161,"timestamp":839451878880,"duration":48513,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\procedural.vertex.js","layer":"app-pages-browser"},"startTime":1704500739062},{"traceId":"4dea77cda8cb5b99","parentId":3165,"name":"read-resource","id":3166,"timestamp":839451881239,"duration":52120,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3165,"timestamp":839451881220,"duration":52332,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrFragmentSamplersDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3163,"name":"read-resource","id":3164,"timestamp":839451881202,"duration":52361,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3163,"timestamp":839451881173,"duration":52571,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrFragmentExtraDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3169,"name":"read-resource","id":3170,"timestamp":839451881279,"duration":52476,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3169,"timestamp":839451881268,"duration":52636,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\importanceSampling.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3171,"name":"read-resource","id":3172,"timestamp":839451881296,"duration":52617,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3171,"timestamp":839451881286,"duration":52838,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\harmonicsFunctions.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3173,"name":"read-resource","id":3174,"timestamp":839451881315,"duration":52818,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3173,"timestamp":839451881302,"duration":52969,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrHelperFunctions.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3167,"name":"read-resource","id":3168,"timestamp":839451881261,"duration":53023,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3167,"timestamp":839451881248,"duration":53155,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\subSurfaceScatteringFunctions.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3175,"name":"read-resource","id":3176,"timestamp":839451881334,"duration":53078,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3175,"timestamp":839451881322,"duration":53209,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrDirectLightingSetupFunctions.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3177,"name":"read-resource","id":3178,"timestamp":839451881356,"duration":53182,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3177,"timestamp":839451881345,"duration":53332,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\hdrFilteringFunctions.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3181,"name":"read-resource","id":3182,"timestamp":839451881389,"duration":53297,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3181,"timestamp":839451881378,"duration":53432,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrIBLFunctions.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3179,"name":"read-resource","id":3180,"timestamp":839451881372,"duration":53447,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3179,"timestamp":839451881362,"duration":59319,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrDirectLightingFalloffFunctions.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3183,"name":"read-resource","id":3184,"timestamp":839451881406,"duration":59286,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3183,"timestamp":839451881394,"duration":59497,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBRDFFunctions.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3185,"name":"read-resource","id":3186,"timestamp":839451881425,"duration":59476,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3185,"timestamp":839451881412,"duration":59661,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrDirectLightingFunctions.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3187,"name":"read-resource","id":3188,"timestamp":839451881440,"duration":59643,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3187,"timestamp":839451881430,"duration":59792,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockAlbedoOpacity.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3191,"name":"read-resource","id":3192,"timestamp":839451881473,"duration":59759,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3191,"timestamp":839451881462,"duration":59893,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockAlphaFresnel.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3189,"name":"read-resource","id":3190,"timestamp":839451881456,"duration":59908,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3189,"timestamp":839451881446,"duration":60051,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockReflectivity.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3193,"name":"read-resource","id":3194,"timestamp":839451881493,"duration":60015,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3193,"timestamp":839451881479,"duration":60142,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockAmbientOcclusion.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3195,"name":"read-resource","id":3196,"timestamp":839451881510,"duration":60120,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3195,"timestamp":839451881499,"duration":60266,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockAnisotropic.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3197,"name":"read-resource","id":3198,"timestamp":839451881526,"duration":60248,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3197,"timestamp":839451881516,"duration":60435,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockSheen.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3199,"name":"read-resource","id":3200,"timestamp":839451881542,"duration":60418,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3199,"timestamp":839451881532,"duration":60667,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockReflection.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3207,"name":"read-resource","id":3208,"timestamp":839451881612,"duration":60596,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3207,"timestamp":839451881602,"duration":60717,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockNormalFinal.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3209,"name":"read-resource","id":3210,"timestamp":839451881630,"duration":60697,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3209,"timestamp":839451881618,"duration":60838,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockNormalGeometric.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3201,"name":"read-resource","id":3202,"timestamp":839451881561,"duration":74322,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3201,"timestamp":839451881549,"duration":74836,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockClearcoat.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3213,"name":"read-resource","id":3214,"timestamp":839451881663,"duration":74735,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3213,"timestamp":839451881652,"duration":74909,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockGeometryInfo.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3211,"name":"read-resource","id":3212,"timestamp":839451881646,"duration":74927,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3211,"timestamp":839451881636,"duration":75081,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockLightmapInit.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3215,"name":"read-resource","id":3216,"timestamp":839451881679,"duration":75049,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3215,"timestamp":839451881669,"duration":75200,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockDirectLighting.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3205,"name":"read-resource","id":3206,"timestamp":839451881596,"duration":75283,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3205,"timestamp":839451881586,"duration":75457,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockIridescence.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3203,"name":"read-resource","id":3204,"timestamp":839451881580,"duration":75502,"tags":{},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3203,"timestamp":839451881568,"duration":75768,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockSubSurface.js","layer":"app-pages-browser"},"startTime":1704500739065},{"traceId":"4dea77cda8cb5b99","parentId":3217,"name":"read-resource","id":3218,"timestamp":839451882080,"duration":79074,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3217,"timestamp":839451882039,"duration":79258,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockReflectance0.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3219,"name":"read-resource","id":3220,"timestamp":839451882115,"duration":79191,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3219,"timestamp":839451882099,"duration":79354,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockFinalUnlitComponents.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3223,"name":"read-resource","id":3224,"timestamp":839451882502,"duration":78960,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3223,"timestamp":839451882419,"duration":79169,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockFinalLitComponents.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3221,"name":"read-resource","id":3222,"timestamp":839451882406,"duration":79190,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3221,"timestamp":839451882380,"duration":79318,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockReflectance.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3227,"name":"read-resource","id":3228,"timestamp":839451882696,"duration":79011,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3227,"timestamp":839451882666,"duration":79138,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockImageProcessing.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3229,"name":"read-resource","id":3230,"timestamp":839451882719,"duration":79092,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3229,"timestamp":839451882707,"duration":79243,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrDebug.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3225,"name":"read-resource","id":3226,"timestamp":839451882649,"duration":79308,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2885,"name":"build-module-js","id":3225,"timestamp":839451882521,"duration":79540,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrBlockFinalColorComposition.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3231,"name":"read-resource","id":3232,"timestamp":839451882740,"duration":79330,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2887,"name":"build-module-js","id":3231,"timestamp":839451882726,"duration":79460,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\pbrVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3239,"name":"read-resource","id":3240,"timestamp":839451882813,"duration":79381,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2981,"name":"build-module-js","id":3239,"timestamp":839451882800,"duration":81127,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Dual\\textureBlock.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3233,"name":"read-resource","id":3234,"timestamp":839451882756,"duration":81182,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2899,"name":"build-module-js","id":3233,"timestamp":839451882746,"duration":81657,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Dual\\imageSourceBlock.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3235,"name":"read-resource","id":3236,"timestamp":839451882776,"duration":81638,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2981,"name":"build-module-js","id":3235,"timestamp":839451882763,"duration":82174,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Dual\\fogBlock.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3237,"name":"read-resource","id":3238,"timestamp":839451882794,"duration":82154,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2981,"name":"build-module-js","id":3237,"timestamp":839451882783,"duration":83214,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Dual\\lightBlock.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3241,"name":"read-resource","id":3242,"timestamp":839451882829,"duration":83179,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2981,"name":"build-module-js","id":3241,"timestamp":839451882819,"duration":83807,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Dual\\sceneDepthBlock.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3245,"name":"read-resource","id":3246,"timestamp":839451882862,"duration":83774,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2981,"name":"build-module-js","id":3245,"timestamp":839451882850,"duration":84212,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Dual\\clipPlanesBlock.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3247,"name":"read-resource","id":3248,"timestamp":839451882921,"duration":84152,"tags":{},"startTime":1704500739067},{"traceId":"4dea77cda8cb5b99","parentId":2979,"name":"build-module-js","id":3247,"timestamp":839451882868,"duration":84716,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Vertex\\instancesBlock.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3243,"name":"read-resource","id":3244,"timestamp":839451882845,"duration":84749,"tags":{},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":2981,"name":"build-module-js","id":3243,"timestamp":839451882835,"duration":85303,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Dual\\reflectionTextureBlock.js","layer":"app-pages-browser"},"startTime":1704500739066},{"traceId":"4dea77cda8cb5b99","parentId":3249,"name":"read-resource","id":3250,"timestamp":839451882949,"duration":85199,"tags":{},"startTime":1704500739067},{"traceId":"4dea77cda8cb5b99","parentId":2979,"name":"build-module-js","id":3249,"timestamp":839451882935,"duration":85757,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Vertex\\bonesBlock.js","layer":"app-pages-browser"},"startTime":1704500739067},{"traceId":"4dea77cda8cb5b99","parentId":3251,"name":"read-resource","id":3252,"timestamp":839451882967,"duration":85735,"tags":{},"startTime":1704500739067},{"traceId":"4dea77cda8cb5b99","parentId":2979,"name":"build-module-js","id":3251,"timestamp":839451882956,"duration":88531,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Vertex\\lightInformationBlock.js","layer":"app-pages-browser"},"startTime":1704500739067},{"traceId":"4dea77cda8cb5b99","parentId":3253,"name":"read-resource","id":3254,"timestamp":839451959818,"duration":19557,"tags":{},"startTime":1704500739143},{"traceId":"4dea77cda8cb5b99","parentId":2979,"name":"build-module-js","id":3253,"timestamp":839451959755,"duration":20432,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Vertex\\morphTargetsBlock.js","layer":"app-pages-browser"},"startTime":1704500739143},{"traceId":"4dea77cda8cb5b99","parentId":3261,"name":"read-resource","id":3262,"timestamp":839451959919,"duration":20281,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3261,"timestamp":839451959909,"duration":20467,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\frontFacingBlock.js","layer":"app-pages-browser"},"startTime":1704500739143},{"traceId":"4dea77cda8cb5b99","parentId":3259,"name":"read-resource","id":3260,"timestamp":839451959902,"duration":20486,"tags":{},"startTime":1704500739143}] +[{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3259,"timestamp":839451959892,"duration":20816,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\discardBlock.js","layer":"app-pages-browser"},"startTime":1704500739143},{"traceId":"4dea77cda8cb5b99","parentId":3255,"name":"read-resource","id":3256,"timestamp":839451959859,"duration":20860,"tags":{},"startTime":1704500739143},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3255,"timestamp":839451959843,"duration":21971,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\perturbNormalBlock.js","layer":"app-pages-browser"},"startTime":1704500739143},{"traceId":"4dea77cda8cb5b99","parentId":3265,"name":"read-resource","id":3266,"timestamp":839451959949,"duration":21876,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3265,"timestamp":839451959940,"duration":22159,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\screenSizeBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3263,"name":"read-resource","id":3264,"timestamp":839451959934,"duration":22176,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3263,"timestamp":839451959925,"duration":22452,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\fragCoordBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3267,"name":"read-resource","id":3268,"timestamp":839451959964,"duration":22422,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3267,"timestamp":839451959955,"duration":22646,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\derivativeBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3257,"name":"read-resource","id":3258,"timestamp":839451959885,"duration":22725,"tags":{},"startTime":1704500739143},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3257,"timestamp":839451959868,"duration":23216,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\imageProcessingBlock.js","layer":"app-pages-browser"},"startTime":1704500739143},{"traceId":"4dea77cda8cb5b99","parentId":3269,"name":"read-resource","id":3270,"timestamp":839451959978,"duration":23116,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3269,"timestamp":839451959970,"duration":23451,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\screenSpaceBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3271,"name":"read-resource","id":3272,"timestamp":839451959991,"duration":23439,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3271,"timestamp":839451959984,"duration":26057,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\TBNBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3273,"name":"read-resource","id":3274,"timestamp":839451960005,"duration":26047,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3273,"timestamp":839451959997,"duration":26478,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\heightToNormalBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3277,"name":"read-resource","id":3278,"timestamp":839451960033,"duration":26453,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3277,"timestamp":839451960025,"duration":26757,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\shadowMapBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3285,"name":"read-resource","id":3286,"timestamp":839451960091,"duration":26701,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3031,"name":"build-module-js","id":3285,"timestamp":839451960082,"duration":26848,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\shadowMapVertexExtraDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3281,"name":"read-resource","id":3282,"timestamp":839451960062,"duration":26879,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3281,"timestamp":839451960053,"duration":27265,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\prePassOutputBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3283,"name":"read-resource","id":3284,"timestamp":839451960076,"duration":27251,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3031,"name":"build-module-js","id":3283,"timestamp":839451960068,"duration":27373,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\shadowMapVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3275,"name":"read-resource","id":3276,"timestamp":839451960020,"duration":27436,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3275,"timestamp":839451960011,"duration":27803,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\twirlBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3279,"name":"read-resource","id":3280,"timestamp":839451960047,"duration":27777,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2983,"name":"build-module-js","id":3279,"timestamp":839451960039,"duration":27983,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Fragment\\fragDepthBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3287,"name":"read-resource","id":3288,"timestamp":839451960104,"duration":27928,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3031,"name":"build-module-js","id":3287,"timestamp":839451960095,"duration":28042,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\shadowMapUboDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3289,"name":"read-resource","id":3290,"timestamp":839451960120,"duration":28025,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3031,"name":"build-module-js","id":3289,"timestamp":839451960112,"duration":28157,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\shadowMapVertexNormalBias.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3297,"name":"read-resource","id":3298,"timestamp":839451960176,"duration":28101,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3021,"name":"build-module-js","id":3297,"timestamp":839451960169,"duration":28213,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\noise.fragment.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3293,"name":"read-resource","id":3294,"timestamp":839451960149,"duration":28241,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3029,"name":"build-module-js","id":3293,"timestamp":839451960140,"duration":28346,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\shadowMapFragment.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3291,"name":"read-resource","id":3292,"timestamp":839451960134,"duration":28359,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3029,"name":"build-module-js","id":3291,"timestamp":839451960126,"duration":28476,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\shadowMapFragmentExtraDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3295,"name":"read-resource","id":3296,"timestamp":839451960163,"duration":28448,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3031,"name":"build-module-js","id":3295,"timestamp":839451960155,"duration":28560,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\shadowMapVertexMetric.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3299,"name":"read-resource","id":3300,"timestamp":839451960190,"duration":28535,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":2987,"name":"build-module-js","id":3299,"timestamp":839451960181,"duration":28850,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Input\\prePassTextureBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3307,"name":"read-resource","id":3308,"timestamp":839451960245,"duration":28799,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3011,"name":"build-module-js","id":3307,"timestamp":839451960237,"duration":29283,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\PBR\\anisotropyBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3303,"name":"read-resource","id":3304,"timestamp":839451960218,"duration":29311,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3011,"name":"build-module-js","id":3303,"timestamp":839451960210,"duration":29822,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\PBR\\sheenBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3305,"name":"read-resource","id":3306,"timestamp":839451960232,"duration":29810,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3011,"name":"build-module-js","id":3305,"timestamp":839451960224,"duration":30715,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\PBR\\reflectionBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3309,"name":"read-resource","id":3310,"timestamp":839451960258,"duration":30692,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3011,"name":"build-module-js","id":3309,"timestamp":839451960250,"duration":31632,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\PBR\\clearCoatBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3311,"name":"read-resource","id":3312,"timestamp":839451960272,"duration":31620,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3011,"name":"build-module-js","id":3311,"timestamp":839451960264,"duration":32390,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\PBR\\refractionBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3315,"name":"read-resource","id":3316,"timestamp":839451960299,"duration":32365,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3009,"name":"build-module-js","id":3315,"timestamp":839451960291,"duration":32689,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Teleport\\teleportOutBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3313,"name":"read-resource","id":3314,"timestamp":839451960286,"duration":32704,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3009,"name":"build-module-js","id":3313,"timestamp":839451960278,"duration":32957,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Teleport\\teleportInBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3301,"name":"read-resource","id":3302,"timestamp":839451960204,"duration":33041,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3011,"name":"build-module-js","id":3301,"timestamp":839451960196,"duration":38464,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\PBR\\pbrMetallicRoughnessBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3319,"name":"read-resource","id":3320,"timestamp":839451960330,"duration":38341,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3047,"name":"build-module-js","id":3319,"timestamp":839451960320,"duration":38482,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\imageProcessingCompatibility.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3317,"name":"read-resource","id":3318,"timestamp":839451960313,"duration":38499,"tags":{},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3011,"name":"build-module-js","id":3317,"timestamp":839451960305,"duration":39221,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\PBR\\subSurfaceBlock.js","layer":"app-pages-browser"},"startTime":1704500739144},{"traceId":"4dea77cda8cb5b99","parentId":3325,"name":"read-resource","id":3326,"timestamp":839451978161,"duration":30868,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3097,"name":"build-module-js","id":3325,"timestamp":839451978150,"duration":31065,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\standard.fragment.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3323,"name":"read-resource","id":3324,"timestamp":839451978141,"duration":31083,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3093,"name":"build-module-js","id":3323,"timestamp":839451978128,"duration":31237,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\lensHighlights.fragment.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3335,"name":"read-resource","id":3336,"timestamp":839451978235,"duration":31138,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3103,"name":"build-module-js","id":3335,"timestamp":839451978227,"duration":31255,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ssao.fragment.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3327,"name":"read-resource","id":3328,"timestamp":839451978177,"duration":31312,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3093,"name":"build-module-js","id":3327,"timestamp":839451978168,"duration":31443,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\depthOfField.fragment.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3321,"name":"read-resource","id":3322,"timestamp":839451978111,"duration":31508,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3059,"name":"build-module-js","id":3321,"timestamp":839451978086,"duration":31658,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\subSurfaceScattering.fragment.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3333,"name":"read-resource","id":3334,"timestamp":839451978221,"duration":31530,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3099,"name":"build-module-js","id":3333,"timestamp":839451978213,"duration":31629,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ssaoCombine.fragment.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3329,"name":"read-resource","id":3330,"timestamp":839451978193,"duration":31657,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3099,"name":"build-module-js","id":3329,"timestamp":839451978183,"duration":31759,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\ssao2Configuration.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3337,"name":"read-resource","id":3338,"timestamp":839451978249,"duration":31702,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3101,"name":"build-module-js","id":3337,"timestamp":839451978240,"duration":31837,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Rendering\\screenSpaceReflections2Configuration.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3339,"name":"read-resource","id":3340,"timestamp":839451978264,"duration":31823,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3101,"name":"build-module-js","id":3339,"timestamp":839451978256,"duration":31991,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\screenSpaceReflection2.fragment.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3331,"name":"read-resource","id":3332,"timestamp":839451978207,"duration":32048,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3099,"name":"build-module-js","id":3331,"timestamp":839451978199,"duration":32183,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ssao2.fragment.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3345,"name":"read-resource","id":3346,"timestamp":839451978306,"duration":32084,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3107,"name":"build-module-js","id":3345,"timestamp":839451978297,"duration":32205,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\flowGraphWithOnDoneExecutionBlock.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3343,"name":"read-resource","id":3344,"timestamp":839451978291,"duration":32220,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3101,"name":"build-module-js","id":3343,"timestamp":839451978283,"duration":32343,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\screenSpaceReflection2BlurCombiner.fragment.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3349,"name":"read-resource","id":3350,"timestamp":839451978333,"duration":32302,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3135,"name":"build-module-js","id":3349,"timestamp":839451978325,"duration":34408,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\Audio\\flowGraphPlayAudioBlock.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3341,"name":"read-resource","id":3342,"timestamp":839451978278,"duration":34465,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3101,"name":"build-module-js","id":3341,"timestamp":839451978270,"duration":34601,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\screenSpaceReflection2Blur.fragment.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3351,"name":"read-resource","id":3352,"timestamp":839451978347,"duration":34532,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3351,"timestamp":839451978339,"duration":34749,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphForLoopBlock.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3353,"name":"read-resource","id":3354,"timestamp":839451978361,"duration":34735,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3353,"timestamp":839451978353,"duration":34880,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphBranchBlock.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3347,"name":"read-resource","id":3348,"timestamp":839451978320,"duration":34924,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3135,"name":"build-module-js","id":3347,"timestamp":839451978312,"duration":35063,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\Audio\\flowGraphStopAudioBlock.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3355,"name":"read-resource","id":3356,"timestamp":839451978375,"duration":35008,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3355,"timestamp":839451978367,"duration":35164,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphDoNBlock.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3359,"name":"read-resource","id":3360,"timestamp":839451978404,"duration":35136,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3359,"timestamp":839451978394,"duration":35463,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphMultiGateBlock.js","layer":"app-pages-browser"},"startTime":1704500739162}] +[{"traceId":"4dea77cda8cb5b99","parentId":3357,"name":"read-resource","id":3358,"timestamp":839451978389,"duration":35598,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3357,"timestamp":839451978380,"duration":35785,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphThrottleBlock.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3361,"name":"read-resource","id":3362,"timestamp":839451978417,"duration":35757,"tags":{},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3361,"timestamp":839451978409,"duration":36000,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphTimerBlock.js","layer":"app-pages-browser"},"startTime":1704500739162},{"traceId":"4dea77cda8cb5b99","parentId":3365,"name":"read-resource","id":3366,"timestamp":839451979146,"duration":37671,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3365,"timestamp":839451979133,"duration":37900,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphSwitchBlock.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3367,"name":"read-resource","id":3368,"timestamp":839451979162,"duration":37882,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3367,"timestamp":839451979153,"duration":38080,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphCounterBlock.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3363,"name":"read-resource","id":3364,"timestamp":839451979123,"duration":38122,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3165,"name":"build-module-js","id":3363,"timestamp":839451979101,"duration":38254,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\samplerFragmentAlternateDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3369,"name":"read-resource","id":3370,"timestamp":839451979177,"duration":38186,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3369,"timestamp":839451979168,"duration":38438,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphWaitAllBlock.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3375,"name":"read-resource","id":3376,"timestamp":839451979223,"duration":38392,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3375,"timestamp":839451979213,"duration":38552,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphFlipFlopBlock.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3381,"name":"read-resource","id":3382,"timestamp":839451979266,"duration":38509,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3141,"name":"build-module-js","id":3381,"timestamp":839451979257,"duration":39086,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\Math\\flowGraphVector3MathBlocks.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3371,"name":"read-resource","id":3372,"timestamp":839451979193,"duration":39160,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3371,"timestamp":839451979183,"duration":39336,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphDebounceBlock.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3373,"name":"read-resource","id":3374,"timestamp":839451979207,"duration":39320,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3133,"name":"build-module-js","id":3373,"timestamp":839451979198,"duration":39513,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\ControlFlow\\flowGraphWhileLoopBlock.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3377,"name":"read-resource","id":3378,"timestamp":839451979238,"duration":39484,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3141,"name":"build-module-js","id":3377,"timestamp":839451979229,"duration":40064,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\Math\\flowGraphVector2MathBlocks.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3379,"name":"read-resource","id":3380,"timestamp":839451979252,"duration":40051,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3141,"name":"build-module-js","id":3379,"timestamp":839451979243,"duration":41178,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\Math\\flowGraphNumberMathBlocks.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3383,"name":"read-resource","id":3384,"timestamp":839451979280,"duration":41153,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3141,"name":"build-module-js","id":3383,"timestamp":839451979271,"duration":41922,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\Math\\flowGraphMatrixBlocks.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3387,"name":"read-resource","id":3388,"timestamp":839451979307,"duration":41896,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3137,"name":"build-module-js","id":3387,"timestamp":839451979298,"duration":42234,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\Animation\\flowGraphPlayAnimationBlock.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3389,"name":"read-resource","id":3390,"timestamp":839451979321,"duration":42220,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3137,"name":"build-module-js","id":3389,"timestamp":839451979313,"duration":42361,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\Animation\\flowGraphStopAnimationBlock.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3385,"name":"read-resource","id":3386,"timestamp":839451979294,"duration":42388,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3141,"name":"build-module-js","id":3385,"timestamp":839451979286,"duration":42825,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\Math\\flowGraphVector4MathBlocks.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3391,"name":"read-resource","id":3392,"timestamp":839451979335,"duration":42787,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3137,"name":"build-module-js","id":3391,"timestamp":839451979327,"duration":42921,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Execution\\Animation\\flowGraphPauseAnimationBlock.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3393,"name":"read-resource","id":3394,"timestamp":839451979350,"duration":45417,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3139,"name":"build-module-js","id":3393,"timestamp":839451979341,"duration":45669,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\Logic\\flowGraphLogicBlocks.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3395,"name":"read-resource","id":3396,"timestamp":839451979364,"duration":45657,"tags":{},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3139,"name":"build-module-js","id":3395,"timestamp":839451979356,"duration":46046,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\Logic\\flowGraphBitwiseBlocks.js","layer":"app-pages-browser"},"startTime":1704500739163},{"traceId":"4dea77cda8cb5b99","parentId":3397,"name":"read-resource","id":3398,"timestamp":839452008120,"duration":18044,"tags":{},"startTime":1704500739192},{"traceId":"4dea77cda8cb5b99","parentId":3243,"name":"build-module-js","id":3397,"timestamp":839452008093,"duration":19250,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\Dual\\reflectionTextureBaseBlock.js","layer":"app-pages-browser"},"startTime":1704500739192},{"traceId":"4dea77cda8cb5b99","parentId":3399,"name":"read-resource","id":3400,"timestamp":839452023684,"duration":6425,"tags":{},"startTime":1704500739207},{"traceId":"4dea77cda8cb5b99","parentId":3283,"name":"build-module-js","id":3399,"timestamp":839452023656,"duration":6591,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\sceneVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739207},{"traceId":"4dea77cda8cb5b99","parentId":3403,"name":"read-resource","id":3404,"timestamp":839452023732,"duration":6527,"tags":{},"startTime":1704500739207},{"traceId":"4dea77cda8cb5b99","parentId":3291,"name":"build-module-js","id":3403,"timestamp":839452023722,"duration":6648,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\bayerDitherFunctions.js","layer":"app-pages-browser"},"startTime":1704500739207},{"traceId":"4dea77cda8cb5b99","parentId":3401,"name":"read-resource","id":3402,"timestamp":839452023714,"duration":6664,"tags":{},"startTime":1704500739207},{"traceId":"4dea77cda8cb5b99","parentId":3283,"name":"build-module-js","id":3401,"timestamp":839452023701,"duration":6771,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\meshVertexDeclaration.js","layer":"app-pages-browser"},"startTime":1704500739207},{"traceId":"4dea77cda8cb5b99","parentId":3405,"name":"read-resource","id":3406,"timestamp":839452025850,"duration":4812,"tags":{},"startTime":1704500739209},{"traceId":"4dea77cda8cb5b99","parentId":3301,"name":"build-module-js","id":3405,"timestamp":839452025822,"duration":5224,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Materials\\Node\\Blocks\\PBR\\iridescenceBlock.js","layer":"app-pages-browser"},"startTime":1704500739209},{"traceId":"4dea77cda8cb5b99","parentId":3407,"name":"read-resource","id":3408,"timestamp":839452029681,"duration":1827,"tags":{},"startTime":1704500739213},{"traceId":"4dea77cda8cb5b99","parentId":3321,"name":"build-module-js","id":3407,"timestamp":839452029655,"duration":1975,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\fibonacci.js","layer":"app-pages-browser"},"startTime":1704500739213},{"traceId":"4dea77cda8cb5b99","parentId":3411,"name":"read-resource","id":3412,"timestamp":839452029731,"duration":1907,"tags":{},"startTime":1704500739213},{"traceId":"4dea77cda8cb5b99","parentId":3339,"name":"build-module-js","id":3411,"timestamp":839452029721,"duration":2071,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\screenSpaceRayTrace.js","layer":"app-pages-browser"},"startTime":1704500739213},{"traceId":"4dea77cda8cb5b99","parentId":3409,"name":"read-resource","id":3410,"timestamp":839452029712,"duration":2089,"tags":{},"startTime":1704500739213},{"traceId":"4dea77cda8cb5b99","parentId":3321,"name":"build-module-js","id":3409,"timestamp":839452029699,"duration":2224,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\Shaders\\ShadersInclude\\diffusionProfile.js","layer":"app-pages-browser"},"startTime":1704500739213},{"traceId":"4dea77cda8cb5b99","parentId":3413,"name":"read-resource","id":3414,"timestamp":839452030058,"duration":2037,"tags":{},"startTime":1704500739214},{"traceId":"4dea77cda8cb5b99","parentId":3381,"name":"build-module-js","id":3413,"timestamp":839452030037,"duration":2200,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\flowGraphBinaryOperationBlock.js","layer":"app-pages-browser"},"startTime":1704500739214},{"traceId":"4dea77cda8cb5b99","parentId":3415,"name":"read-resource","id":3416,"timestamp":839452030081,"duration":2265,"tags":{},"startTime":1704500739214},{"traceId":"4dea77cda8cb5b99","parentId":3379,"name":"build-module-js","id":3415,"timestamp":839452030069,"duration":2395,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\flowGraphConstantOperationBlock.js","layer":"app-pages-browser"},"startTime":1704500739214},{"traceId":"4dea77cda8cb5b99","parentId":3417,"name":"read-resource","id":3418,"timestamp":839452030098,"duration":2376,"tags":{},"startTime":1704500739214},{"traceId":"4dea77cda8cb5b99","parentId":3381,"name":"build-module-js","id":3417,"timestamp":839452030089,"duration":2499,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\flowGraphUnaryOperationBlock.js","layer":"app-pages-browser"},"startTime":1704500739214},{"traceId":"4dea77cda8cb5b99","parentId":3419,"name":"read-resource","id":3420,"timestamp":839452032900,"duration":167,"tags":{},"startTime":1704500739216},{"traceId":"4dea77cda8cb5b99","parentId":3413,"name":"build-module-js","id":3419,"timestamp":839452032872,"duration":426,"tags":{"name":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\@babylonjs\\core\\FlowGraph\\Blocks\\Data\\flowGraphCachedOperationBlock.js","layer":"app-pages-browser"},"startTime":1704500739216},{"traceId":"4dea77cda8cb5b99","parentId":118,"name":"add-entry","id":130,"timestamp":839449520811,"duration":2512607,"tags":{"request":"next-flight-client-entry-loader?modules=X%3A%5CSome%20Useful%20Stuff%5CApplications%5CWeb%5Cnext-sukadia.dev%5Capp%5Cspace%5Cpage.tsx&server=false!"},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":117,"name":"make","id":118,"timestamp":839449520538,"duration":2512935,"tags":{},"startTime":1704500736704},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"chunk-graph","id":3422,"timestamp":839452107402,"duration":13394,"tags":{},"startTime":1704500739291},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"optimize-modules","id":3424,"timestamp":839452120819,"duration":4,"tags":{},"startTime":1704500739304},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"optimize-chunks","id":3425,"timestamp":839452120834,"duration":7536,"tags":{},"startTime":1704500739304},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"optimize-tree","id":3426,"timestamp":839452128389,"duration":6,"tags":{},"startTime":1704500739312},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"optimize-chunk-modules","id":3427,"timestamp":839452128414,"duration":46520,"tags":{},"startTime":1704500739312},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"optimize","id":3423,"timestamp":839452120809,"duration":54143,"tags":{},"startTime":1704500739304},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"module-hash","id":3428,"timestamp":839452186658,"duration":21094,"tags":{},"startTime":1704500739370},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"code-generation","id":3429,"timestamp":839452207765,"duration":654656,"tags":{},"startTime":1704500739391},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"hash","id":3430,"timestamp":839452864398,"duration":2867,"tags":{},"startTime":1704500740048},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"code-generation-jobs","id":3431,"timestamp":839452867264,"duration":332,"tags":{},"startTime":1704500740051},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"module-assets","id":3432,"timestamp":839452867580,"duration":279,"tags":{},"startTime":1704500740051},{"traceId":"4dea77cda8cb5b99","parentId":3421,"name":"create-chunk-assets","id":3433,"timestamp":839452867865,"duration":3825,"tags":{},"startTime":1704500740051},{"traceId":"4dea77cda8cb5b99","parentId":117,"name":"NextJsBuildManifest-generateClientManifest","id":3435,"timestamp":839452876578,"duration":470,"tags":{},"startTime":1704500740060},{"traceId":"4dea77cda8cb5b99","parentId":117,"name":"NextJsBuildManifest-createassets","id":3434,"timestamp":839452876173,"duration":880,"tags":{},"startTime":1704500740060},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3440,"timestamp":839452899255,"duration":233882,"tags":{"name":"static/chunks/pages/_error-b646007f40c4f0a8.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3438,"timestamp":839452899144,"duration":234025,"tags":{"name":"static/chunks/main-app-cf3eb22ffef632f7.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3441,"timestamp":839452899285,"duration":233897,"tags":{"name":"static/chunks/pages/_app-1534f180665c857f.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3439,"timestamp":839452899196,"duration":233995,"tags":{"name":"static/chunks/app/_not-found-fbdfab077d258bb2.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3442,"timestamp":839452899311,"duration":233890,"tags":{"name":"static/chunks/app/layout-ca25527909104096.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3443,"timestamp":839452899342,"duration":233867,"tags":{"name":"static/chunks/app/everyone-votes/terms/page-c0da9088d7e5e9ae.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3444,"timestamp":839452899363,"duration":233855,"tags":{"name":"static/chunks/app/everyone-votes/privacy/page-29a62894605199e6.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3447,"timestamp":839452899638,"duration":233588,"tags":{"name":"static/chunks/app/space/loading-12fd180f06101306.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3448,"timestamp":839452899658,"duration":233578,"tags":{"name":"static/chunks/app/wiston/page-c31b345ea6ea73af.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3445,"timestamp":839452899383,"duration":233871,"tags":{"name":"static/chunks/app/page-39b6caed82efc627.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3450,"timestamp":839452899747,"duration":233519,"tags":{"name":"static/chunks/751.4a2a15d2edbade23.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3446,"timestamp":839452899515,"duration":233761,"tags":{"name":"static/chunks/app/space/page-b8120f6d5470d1c7.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3449,"timestamp":839452899675,"duration":233609,"tags":{"name":"static/chunks/webpack-c42a79c5d8b7c910.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3452,"timestamp":839452900083,"duration":233218,"tags":{"name":"static/chunks/e1206f8c-ab5b5541f866e530.js","cache":"MISS"},"startTime":1704500740084},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3453,"timestamp":839452900841,"duration":232478,"tags":{"name":"static/chunks/1f3d3139-f107a678ff6361e9.js","cache":"MISS"},"startTime":1704500740084},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3454,"timestamp":839452901605,"duration":231729,"tags":{"name":"static/chunks/604a08ec-59af37265fb99b3d.js","cache":"MISS"},"startTime":1704500740085},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3455,"timestamp":839452902417,"duration":230933,"tags":{"name":"static/chunks/d67c510a-e497b3cd5bf43bb4.js","cache":"MISS"},"startTime":1704500740086},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3437,"timestamp":839452896690,"duration":236680,"tags":{"name":"static/chunks/main-07bf56c05aa7cd6e.js","cache":"MISS"},"startTime":1704500740080},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3451,"timestamp":839452899792,"duration":233662,"tags":{"name":"static/chunks/framework-8883d1e9be70c3da.js","cache":"MISS"},"startTime":1704500740083},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3456,"timestamp":839452903051,"duration":230493,"tags":{"name":"static/chunks/537cd76e-7aba1cf7a4752418.js","cache":"MISS"},"startTime":1704500740087},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3460,"timestamp":839452978933,"duration":173585,"tags":{"name":"static/chunks/986-37229c658d9b7b30.js","cache":"MISS"},"startTime":1704500740163},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3461,"timestamp":839452979180,"duration":173425,"tags":{"name":"server/middleware-react-loadable-manifest.js","cache":"MISS"},"startTime":1704500740163},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3462,"timestamp":839452979269,"duration":173457,"tags":{"name":"static/9CqSqX2Hqhh4fwiD8kSfJ/_ssgManifest.js","cache":"MISS"},"startTime":1704500740163}] +[{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3463,"timestamp":839452979344,"duration":173567,"tags":{"name":"server/middleware-build-manifest.js","cache":"MISS"},"startTime":1704500740163},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3464,"timestamp":839452979360,"duration":173673,"tags":{"name":"static/9CqSqX2Hqhh4fwiD8kSfJ/_buildManifest.js","cache":"MISS"},"startTime":1704500740163},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3465,"timestamp":839452979373,"duration":173759,"tags":{"name":"server/next-font-manifest.js","cache":"MISS"},"startTime":1704500740163},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3457,"timestamp":839452903877,"duration":285466,"tags":{"name":"static/chunks/fd9d1056-ba10bf844a47945b.js","cache":"MISS"},"startTime":1704500740087},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3459,"timestamp":839452977679,"duration":236395,"tags":{"name":"static/chunks/472-51fd3a56159f1e5b.js","cache":"MISS"},"startTime":1704500740161},{"traceId":"4dea77cda8cb5b99","parentId":3436,"name":"minify-js","id":3458,"timestamp":839452904106,"duration":1822430,"tags":{"name":"static/chunks/173-2ffa9652644381a8.js","cache":"MISS"},"startTime":1704500740088},{"traceId":"4dea77cda8cb5b99","parentId":117,"name":"terser-webpack-plugin-optimize","id":3436,"timestamp":839452877651,"duration":1848905,"tags":{"compilationName":"client","swcMinify":"true"},"startTime":1704500740061},{"traceId":"4dea77cda8cb5b99","parentId":3466,"name":"minify-css","id":3467,"timestamp":839454726729,"duration":310968,"tags":{"file":"static/css/cbd4bf37afeacdab.css","cache":"MISS"},"startTime":1704500741910},{"traceId":"4dea77cda8cb5b99","parentId":3466,"name":"minify-css","id":3468,"timestamp":839454726761,"duration":310939,"tags":{"file":"static/css/8c222b83c13bd107.css","cache":"MISS"},"startTime":1704500741910},{"traceId":"4dea77cda8cb5b99","parentId":117,"name":"css-minimizer-plugin","id":3466,"timestamp":839454726668,"duration":311036,"tags":{"webpackVersion":"5"},"startTime":1704500741910},{"traceId":"4dea77cda8cb5b99","parentId":117,"name":"seal","id":3421,"timestamp":839452078527,"duration":2966674,"tags":{},"startTime":1704500739262},{"traceId":"4dea77cda8cb5b99","parentId":14,"name":"webpack-compilation","id":117,"timestamp":839449519849,"duration":5525401,"tags":{"name":"client"},"startTime":1704500736703},{"traceId":"4dea77cda8cb5b99","parentId":14,"name":"emit","id":3469,"timestamp":839455045273,"duration":7212,"tags":{},"startTime":1704500742229},{"traceId":"4dea77cda8cb5b99","parentId":14,"name":"webpack-close","id":3470,"timestamp":839455052597,"duration":787293,"tags":{"name":"client"},"startTime":1704500742236},{"traceId":"4dea77cda8cb5b99","parentId":3470,"name":"webpack-generate-error-stats","id":3471,"timestamp":839455839896,"duration":505,"tags":{},"startTime":1704500743023},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"run-webpack-compiler","id":14,"timestamp":839447884058,"duration":7956519,"tags":{},"startTime":1704500735068},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"format-webpack-messages","id":3472,"timestamp":839455840579,"duration":64,"tags":{},"startTime":1704500743024},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"verify-and-lint","id":3474,"timestamp":839455863116,"duration":1198828,"tags":{},"startTime":1704500743047},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"verify-typescript-setup","id":3473,"timestamp":839455841747,"duration":2082807,"tags":{},"startTime":1704500743025},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-static-error-page","id":3476,"timestamp":839458052866,"duration":5306,"tags":{},"startTime":1704500745236},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-static-error-page","id":3476,"timestamp":839458052866,"duration":5318,"tags":{},"startTime":1704500745236},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-page","id":3477,"timestamp":839458188636,"duration":1042,"tags":{"page":"/_app"},"startTime":1704500745372},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-page","id":3479,"timestamp":839458189179,"duration":508,"tags":{"page":"/_document"},"startTime":1704500745373},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-page","id":3478,"timestamp":839458189139,"duration":657,"tags":{"page":"/_error"},"startTime":1704500745373},{"traceId":"4dea77cda8cb5b99","parentId":3483,"name":"is-page-static","id":3487,"timestamp":839458190086,"duration":111940,"tags":{},"startTime":1704500745374},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-page","id":3483,"timestamp":839458189365,"duration":112693,"tags":{"page":"/favicon.ico"},"startTime":1704500745373},{"traceId":"4dea77cda8cb5b99","parentId":3480,"name":"is-page-static","id":3488,"timestamp":839458190222,"duration":119937,"tags":{},"startTime":1704500745374},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-page","id":3480,"timestamp":839458189242,"duration":120933,"tags":{"page":"/_not-found"},"startTime":1704500745373},{"traceId":"4dea77cda8cb5b99","parentId":3481,"name":"is-page-static","id":3492,"timestamp":839458190439,"duration":120232,"tags":{},"startTime":1704500745374},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-page","id":3481,"timestamp":839458189319,"duration":121367,"tags":{"page":"/everyone-votes/privacy"},"startTime":1704500745373},{"traceId":"4dea77cda8cb5b99","parentId":3486,"name":"is-page-static","id":3493,"timestamp":839458190840,"duration":119917,"tags":{},"startTime":1704500745374},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-page","id":3486,"timestamp":839458189414,"duration":121526,"tags":{"page":"/wiston"},"startTime":1704500745373},{"traceId":"4dea77cda8cb5b99","parentId":3482,"name":"is-page-static","id":3490,"timestamp":839458190309,"duration":121221,"tags":{},"startTime":1704500745374},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-page","id":3482,"timestamp":839458189350,"duration":122207,"tags":{"page":"/everyone-votes/terms"},"startTime":1704500745373},{"traceId":"4dea77cda8cb5b99","parentId":3484,"name":"is-page-static","id":3491,"timestamp":839458190353,"duration":121242,"tags":{},"startTime":1704500745374},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-page","id":3484,"timestamp":839458189377,"duration":122223,"tags":{"page":"/"},"startTime":1704500745373},{"traceId":"4dea77cda8cb5b99","parentId":3485,"name":"is-page-static","id":3489,"timestamp":839458190271,"duration":173101,"tags":{},"startTime":1704500745374},{"traceId":"4dea77cda8cb5b99","parentId":3475,"name":"check-page","id":3485,"timestamp":839458189391,"duration":173988,"tags":{"page":"/space"},"startTime":1704500745373},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"static-check","id":3475,"timestamp":839458052344,"duration":311060,"tags":{},"startTime":1704500745236},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"load-dotenv","id":3497,"timestamp":839458374847,"duration":82,"tags":{},"startTime":1704500745558},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"run-export-path-map","id":3498,"timestamp":839458493221,"duration":215,"tags":{},"startTime":1704500745677},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"export-page","id":3501,"timestamp":839458494095,"duration":961943,"tags":{"path":"/favicon.ico"},"startTime":1704500745678},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"export-page","id":3500,"timestamp":839458494058,"duration":962140,"tags":{"path":"/500"},"startTime":1704500745678},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"export-page","id":3499,"timestamp":839458493928,"duration":962306,"tags":{"path":"/404"},"startTime":1704500745678},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"export-page","id":3502,"timestamp":839458494123,"duration":962153,"tags":{"path":"/_not-found"},"startTime":1704500745678},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"export-page","id":3503,"timestamp":839458494148,"duration":962160,"tags":{"path":"/everyone-votes/privacy"},"startTime":1704500745678},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"export-page","id":3506,"timestamp":839458494216,"duration":962122,"tags":{"path":"/"},"startTime":1704500745678},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"export-page","id":3505,"timestamp":839458494194,"duration":962174,"tags":{"path":"/everyone-votes/terms"},"startTime":1704500745678},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"export-page","id":3504,"timestamp":839458494171,"duration":962228,"tags":{"path":"/wiston"},"startTime":1704500745678},{"traceId":"4dea77cda8cb5b99","parentId":3496,"name":"export-page","id":3507,"timestamp":839458494237,"duration":962245,"tags":{"path":"/space"},"startTime":1704500745678},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"next-export","id":3496,"timestamp":839458374315,"duration":1922445,"tags":{},"startTime":1704500745558},{"traceId":"4dea77cda8cb5b99","parentId":3495,"name":"move-exported-app-not-found-","id":3508,"timestamp":839460297051,"duration":2831,"tags":{},"startTime":1704500747481},{"traceId":"4dea77cda8cb5b99","parentId":3495,"name":"move-exported-page","id":3509,"timestamp":839460299971,"duration":4639,"tags":{},"startTime":1704500747484},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"static-generation","id":3495,"timestamp":839458371189,"duration":1953928,"tags":{},"startTime":1704500745555},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"node-file-trace-build","id":3494,"timestamp":839458365064,"duration":5115774,"tags":{"isTurbotrace":"false"},"startTime":1704500745549},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"apply-include-excludes","id":3510,"timestamp":839463480845,"duration":446,"tags":{},"startTime":1704500750664},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"print-tree-view","id":3511,"timestamp":839463481831,"duration":2071,"tags":{},"startTime":1704500750665},{"traceId":"4dea77cda8cb5b99","parentId":1,"name":"telemetry-flush","id":3512,"timestamp":839463483906,"duration":39,"tags":{},"startTime":1704500750667},{"traceId":"4dea77cda8cb5b99","name":"next-build","id":1,"timestamp":839447703769,"duration":15780178,"tags":{"buildMode":"default","isTurboBuild":"false","version":"14.0.1"},"startTime":1704500734887}] diff --git a/.next/types/app/everyone-votes/privacy/page.ts b/.next/types/app/everyone-votes/privacy/page.ts index ec043c5..83b3819 100644 --- a/.next/types/app/everyone-votes/privacy/page.ts +++ b/.next/types/app/everyone-votes/privacy/page.ts @@ -1,6 +1,6 @@ // File: X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\everyone-votes\privacy\page.tsx import * as entry from '../../../../../app/everyone-votes/privacy/page.js' -import type { ResolvingMetadata } from 'next/dist/lib/metadata/types/metadata-interface.js' +import type { ResolvingMetadata, ResolvingViewport } from 'next/dist/lib/metadata/types/metadata-interface.js' type TEntry = typeof import('../../../../../app/everyone-votes/privacy/page.js') @@ -15,9 +15,12 @@ checkFields<Diff<{ fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache' preferredRegion?: 'auto' | 'global' | 'home' | string | string[] runtime?: 'nodejs' | 'experimental-edge' | 'edge' + maxDuration?: number metadata?: any generateMetadata?: Function + viewport?: any + generateViewport?: Function }, TEntry, ''>>() @@ -30,6 +33,12 @@ if ('generateMetadata' in entry) { checkFields<Diff<ResolvingMetadata, SecondArg<MaybeField<TEntry, 'generateMetadata'>>, 'generateMetadata'>>() } +// Check the arguments and return type of the generateViewport function +if ('generateViewport' in entry) { + checkFields<Diff<PageProps, FirstArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>() + checkFields<Diff<ResolvingViewport, SecondArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>() +} + // Check the arguments and return type of the generateStaticParams function if ('generateStaticParams' in entry) { checkFields<Diff<{ params: PageParams }, FirstArg<MaybeField<TEntry, 'generateStaticParams'>>, 'generateStaticParams'>>() diff --git a/.next/types/app/everyone-votes/terms/page.ts b/.next/types/app/everyone-votes/terms/page.ts index 62aef2c..3668fe5 100644 --- a/.next/types/app/everyone-votes/terms/page.ts +++ b/.next/types/app/everyone-votes/terms/page.ts @@ -1,6 +1,6 @@ // File: X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\everyone-votes\terms\page.tsx import * as entry from '../../../../../app/everyone-votes/terms/page.js' -import type { ResolvingMetadata } from 'next/dist/lib/metadata/types/metadata-interface.js' +import type { ResolvingMetadata, ResolvingViewport } from 'next/dist/lib/metadata/types/metadata-interface.js' type TEntry = typeof import('../../../../../app/everyone-votes/terms/page.js') @@ -15,9 +15,12 @@ checkFields<Diff<{ fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache' preferredRegion?: 'auto' | 'global' | 'home' | string | string[] runtime?: 'nodejs' | 'experimental-edge' | 'edge' + maxDuration?: number metadata?: any generateMetadata?: Function + viewport?: any + generateViewport?: Function }, TEntry, ''>>() @@ -30,6 +33,12 @@ if ('generateMetadata' in entry) { checkFields<Diff<ResolvingMetadata, SecondArg<MaybeField<TEntry, 'generateMetadata'>>, 'generateMetadata'>>() } +// Check the arguments and return type of the generateViewport function +if ('generateViewport' in entry) { + checkFields<Diff<PageProps, FirstArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>() + checkFields<Diff<ResolvingViewport, SecondArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>() +} + // Check the arguments and return type of the generateStaticParams function if ('generateStaticParams' in entry) { checkFields<Diff<{ params: PageParams }, FirstArg<MaybeField<TEntry, 'generateStaticParams'>>, 'generateStaticParams'>>() diff --git a/.next/types/app/page.ts b/.next/types/app/page.ts index 52000ce..41604ff 100644 --- a/.next/types/app/page.ts +++ b/.next/types/app/page.ts @@ -1,6 +1,6 @@ // File: X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\page.tsx import * as entry from '../../../app/page.js' -import type { ResolvingMetadata } from 'next/dist/lib/metadata/types/metadata-interface.js' +import type { ResolvingMetadata, ResolvingViewport } from 'next/dist/lib/metadata/types/metadata-interface.js' type TEntry = typeof import('../../../app/page.js') @@ -15,9 +15,12 @@ checkFields<Diff<{ fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache' preferredRegion?: 'auto' | 'global' | 'home' | string | string[] runtime?: 'nodejs' | 'experimental-edge' | 'edge' + maxDuration?: number metadata?: any generateMetadata?: Function + viewport?: any + generateViewport?: Function }, TEntry, ''>>() @@ -30,6 +33,12 @@ if ('generateMetadata' in entry) { checkFields<Diff<ResolvingMetadata, SecondArg<MaybeField<TEntry, 'generateMetadata'>>, 'generateMetadata'>>() } +// Check the arguments and return type of the generateViewport function +if ('generateViewport' in entry) { + checkFields<Diff<PageProps, FirstArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>() + checkFields<Diff<ResolvingViewport, SecondArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>() +} + // Check the arguments and return type of the generateStaticParams function if ('generateStaticParams' in entry) { checkFields<Diff<{ params: PageParams }, FirstArg<MaybeField<TEntry, 'generateStaticParams'>>, 'generateStaticParams'>>() diff --git a/.next/types/app/space/page.ts b/.next/types/app/space/page.ts index 8c1d91e..1d9d272 100644 --- a/.next/types/app/space/page.ts +++ b/.next/types/app/space/page.ts @@ -1,6 +1,6 @@ // File: X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\space\page.tsx import * as entry from '../../../../app/space/page.js' -import type { ResolvingMetadata } from 'next/dist/lib/metadata/types/metadata-interface.js' +import type { ResolvingMetadata, ResolvingViewport } from 'next/dist/lib/metadata/types/metadata-interface.js' type TEntry = typeof import('../../../../app/space/page.js') @@ -15,9 +15,12 @@ checkFields<Diff<{ fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache' preferredRegion?: 'auto' | 'global' | 'home' | string | string[] runtime?: 'nodejs' | 'experimental-edge' | 'edge' + maxDuration?: number metadata?: any generateMetadata?: Function + viewport?: any + generateViewport?: Function }, TEntry, ''>>() @@ -30,6 +33,12 @@ if ('generateMetadata' in entry) { checkFields<Diff<ResolvingMetadata, SecondArg<MaybeField<TEntry, 'generateMetadata'>>, 'generateMetadata'>>() } +// Check the arguments and return type of the generateViewport function +if ('generateViewport' in entry) { + checkFields<Diff<PageProps, FirstArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>() + checkFields<Diff<ResolvingViewport, SecondArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>() +} + // Check the arguments and return type of the generateStaticParams function if ('generateStaticParams' in entry) { checkFields<Diff<{ params: PageParams }, FirstArg<MaybeField<TEntry, 'generateStaticParams'>>, 'generateStaticParams'>>() diff --git a/.next/types/app/wiston/page.ts b/.next/types/app/wiston/page.ts index 4ebe031..3a7953a 100644 --- a/.next/types/app/wiston/page.ts +++ b/.next/types/app/wiston/page.ts @@ -1,6 +1,6 @@ // File: X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\wiston\page.tsx import * as entry from '../../../../app/wiston/page.js' -import type { ResolvingMetadata } from 'next/dist/lib/metadata/types/metadata-interface.js' +import type { ResolvingMetadata, ResolvingViewport } from 'next/dist/lib/metadata/types/metadata-interface.js' type TEntry = typeof import('../../../../app/wiston/page.js') @@ -15,9 +15,12 @@ checkFields<Diff<{ fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache' preferredRegion?: 'auto' | 'global' | 'home' | string | string[] runtime?: 'nodejs' | 'experimental-edge' | 'edge' + maxDuration?: number metadata?: any generateMetadata?: Function + viewport?: any + generateViewport?: Function }, TEntry, ''>>() @@ -30,6 +33,12 @@ if ('generateMetadata' in entry) { checkFields<Diff<ResolvingMetadata, SecondArg<MaybeField<TEntry, 'generateMetadata'>>, 'generateMetadata'>>() } +// Check the arguments and return type of the generateViewport function +if ('generateViewport' in entry) { + checkFields<Diff<PageProps, FirstArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>() + checkFields<Diff<ResolvingViewport, SecondArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>() +} + // Check the arguments and return type of the generateStaticParams function if ('generateStaticParams' in entry) { checkFields<Diff<{ params: PageParams }, FirstArg<MaybeField<TEntry, 'generateStaticParams'>>, 'generateStaticParams'>>() diff --git a/app/wiston/page.tsx b/app/wiston/page.tsx index 5f780b7..a33851d 100644 --- a/app/wiston/page.tsx +++ b/app/wiston/page.tsx @@ -1,5 +1,3 @@ -"use client" - import type { Metadata } from "next" export const metadata: Metadata = { title: "wiston" diff --git a/next.config.js b/next.config.js index 348ead9..28633aa 100644 --- a/next.config.js +++ b/next.config.js @@ -38,6 +38,11 @@ module.exports = { destination: "https://ko-fi.com/sukadia/tiers", permanent: false, }, + { + source: "/poster", + destination: "https://ko-fi.com/s/3cf296742e", + permanent: false, + }, { source: "/dark", destination: "https://marketplace.visualstudio.com/items?itemName=Sukadia.sukadia-dev-dark", diff --git a/package-lock.json b/package-lock.json index e464c31..8d60d04 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,7 @@ "autoprefixer": "10.4.14", "eslint": "8.42.0", "eslint-config-next": "13.4.4", - "next": "13.4.4", + "next": "^14.0.0", "postcss": "8.4.24", "react": "18.2.0", "react-dom": "18.2.0", @@ -46,9 +46,9 @@ } }, "node_modules/@babel/runtime": { - "version": "7.22.11", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.22.11.tgz", - "integrity": "sha512-ee7jVNlWN09+KftVOu9n7S8gQzD/Z6hN/I8VBRXW4P1+Xe7kJGXMwu8vds4aGIMHZnNbdpSWCfZZtinytpcAvA==", + "version": "7.23.2", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.2.tgz", + "integrity": "sha512-mM8eg4yl5D6i3lu2QKPuPH4FArvJ8KhTofbE7jwMUv9KX5mBvwPAqnV3MlyBNqdp9RyRKP6Yck8TrfYrPvX3bg==", "dependencies": { "regenerator-runtime": "^0.14.0" }, @@ -57,9 +57,9 @@ } }, "node_modules/@babylonjs/core": { - "version": "6.18.0", - "resolved": "https://registry.npmjs.org/@babylonjs/core/-/core-6.18.0.tgz", - "integrity": "sha512-Tufbl8S0aNm5Czt6J2l7kPHkU6UYcK6o7zWtS76QDwIHE1yvNq1MwounTSuLc+u9vQR7Ml0HuACmePDmUNUSfw==" + "version": "6.28.1", + "resolved": "https://registry.npmjs.org/@babylonjs/core/-/core-6.28.1.tgz", + "integrity": "sha512-7D0L//yQDq0WU5Mj6os3fGNoy8dtCONgRJ2ji2PMNwZlQ6jH3e5OnoaMYss1QuNCoGeTrXbNuNa7z8RezuFrCQ==" }, "node_modules/@eslint-community/eslint-utils": { "version": "4.4.0", @@ -76,17 +76,17 @@ } }, "node_modules/@eslint-community/regexpp": { - "version": "4.8.0", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.8.0.tgz", - "integrity": "sha512-JylOEEzDiOryeUnFbQz+oViCXS0KsvR1mvHkoMiu5+UiBvy+RYX7tzlIIIEstF/gVa2tj9AQXk3dgnxv6KxhFg==", + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.10.0.tgz", + "integrity": "sha512-Cu96Sd2By9mCNTx2iyKOmq10v22jUVQv0lQnlGNy16oE9589yE+QADPbrMGCkA51cKZSg3Pu/aTJVTGfL/qjUA==", "engines": { "node": "^12.0.0 || ^14.0.0 || >=16.0.0" } }, "node_modules/@eslint/eslintrc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.2.tgz", - "integrity": "sha512-+wvgpDsrB1YqAMdEUCcnTlpfVBH7Vqn6A/NT3D8WVXFIaKMlErPIZT3oCIAVCOtarRpMtelZLqJeU3t7WY6X6g==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.3.tgz", + "integrity": "sha512-yZzuIG+jnVu6hNSzFEN07e8BxF3uAzYtQb6uDkaYZLo6oYZDCq454c5kB8zxnzfCYyP4MIuyBn10L0DqwujTmA==", "dependencies": { "ajv": "^6.12.4", "debug": "^4.3.2", @@ -114,11 +114,11 @@ } }, "node_modules/@humanwhocodes/config-array": { - "version": "0.11.10", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.10.tgz", - "integrity": "sha512-KVVjQmNUepDVGXNuoRRdmmEjruj0KfiGSbS8LVc12LMsWDQzRXJ0qdhN8L8uUigKpfEHRhlaQFY0ib1tnUbNeQ==", + "version": "0.11.13", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.13.tgz", + "integrity": "sha512-JSBDMiDKSzQVngfRjOdFXgFfklaXI4K9nLF49Auh21lmBWRLIK3+xTErTWD4KU54pb6coM6ESE7Awz/FNU3zgQ==", "dependencies": { - "@humanwhocodes/object-schema": "^1.2.1", + "@humanwhocodes/object-schema": "^2.0.1", "debug": "^4.1.1", "minimatch": "^3.0.5" }, @@ -139,9 +139,9 @@ } }, "node_modules/@humanwhocodes/object-schema": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz", - "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==" + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.1.tgz", + "integrity": "sha512-dvuCeX5fC9dXgJn9t+X5atfmgQAzUOWqS1254Gh0m6i8wKd10ebXkfNKiRK+1GWi/yTvvLDHpoxLr0xxxeslWw==" }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.3", @@ -178,18 +178,18 @@ "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" }, "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.19", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.19.tgz", - "integrity": "sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw==", + "version": "0.3.20", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.20.tgz", + "integrity": "sha512-R8LcPeWZol2zR8mmH3JeKQ6QRCFb7XgUhV9ZlGhHLGyg4wpPiPZNQOOWhFZhxKw8u//yTbNGI42Bx/3paXEQ+Q==", "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "node_modules/@next/env": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/@next/env/-/env-13.4.4.tgz", - "integrity": "sha512-q/y7VZj/9YpgzDe64Zi6rY1xPizx80JjlU2BTevlajtaE3w1LqweH1gGgxou2N7hdFosXHjGrI4OUvtFXXhGLg==" + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@next/env/-/env-14.0.1.tgz", + "integrity": "sha512-Ms8ZswqY65/YfcjrlcIwMPD7Rg/dVjdLapMcSHG26W6O67EJDF435ShW4H4LXi1xKO1oRc97tLXUpx8jpLe86A==" }, "node_modules/@next/eslint-plugin-next": { "version": "13.4.4", @@ -200,9 +200,9 @@ } }, "node_modules/@next/swc-darwin-arm64": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-13.4.4.tgz", - "integrity": "sha512-xfjgXvp4KalNUKZMHmsFxr1Ug+aGmmO6NWP0uoh4G3WFqP/mJ1xxfww0gMOeMeSq/Jyr5k7DvoZ2Pv+XOITTtw==", + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.0.1.tgz", + "integrity": "sha512-JyxnGCS4qT67hdOKQ0CkgFTp+PXub5W1wsGvIq98TNbF3YEIN7iDekYhYsZzc8Ov0pWEsghQt+tANdidITCLaw==", "cpu": [ "arm64" ], @@ -215,9 +215,9 @@ } }, "node_modules/@next/swc-darwin-x64": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-13.4.4.tgz", - "integrity": "sha512-ZY9Ti1hkIwJsxGus3nlubIkvYyB0gNOYxKrfsOrLEqD0I2iCX8D7w8v6QQZ2H+dDl6UT29oeEUdDUNGk4UEpfg==", + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.0.1.tgz", + "integrity": "sha512-625Z7bb5AyIzswF9hvfZWa+HTwFZw+Jn3lOBNZB87lUS0iuCYDHqk3ujuHCkiyPtSC0xFBtYDLcrZ11mF/ap3w==", "cpu": [ "x64" ], @@ -230,9 +230,9 @@ } }, "node_modules/@next/swc-linux-arm64-gnu": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-13.4.4.tgz", - "integrity": "sha512-+KZnDeMShYkpkqAvGCEDeqYTRADJXc6SY1jWXz+Uo6qWQO/Jd9CoyhTJwRSxvQA16MoYzvILkGaDqirkRNctyA==", + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.0.1.tgz", + "integrity": "sha512-iVpn3KG3DprFXzVHM09kvb//4CNNXBQ9NB/pTm8LO+vnnnaObnzFdS5KM+w1okwa32xH0g8EvZIhoB3fI3mS1g==", "cpu": [ "arm64" ], @@ -245,9 +245,9 @@ } }, "node_modules/@next/swc-linux-arm64-musl": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-13.4.4.tgz", - "integrity": "sha512-evC1twrny2XDT4uOftoubZvW3EG0zs0ZxMwEtu/dDGVRO5n5pT48S8qqEIBGBUZYu/Xx4zzpOkIxx1vpWdE+9A==", + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.0.1.tgz", + "integrity": "sha512-mVsGyMxTLWZXyD5sen6kGOTYVOO67lZjLApIj/JsTEEohDDt1im2nkspzfV5MvhfS7diDw6Rp/xvAQaWZTv1Ww==", "cpu": [ "arm64" ], @@ -260,9 +260,9 @@ } }, "node_modules/@next/swc-linux-x64-gnu": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-13.4.4.tgz", - "integrity": "sha512-PX706XcCHr2FfkyhP2lpf+pX/tUvq6/ke7JYnnr0ykNdEMo+sb7cC/o91gnURh4sPYSiZJhsF2gbIqg9rciOHQ==", + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.0.1.tgz", + "integrity": "sha512-wMqf90uDWN001NqCM/auRl3+qVVeKfjJdT9XW+RMIOf+rhUzadmYJu++tp2y+hUbb6GTRhT+VjQzcgg/QTD9NQ==", "cpu": [ "x64" ], @@ -275,9 +275,9 @@ } }, "node_modules/@next/swc-linux-x64-musl": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-13.4.4.tgz", - "integrity": "sha512-TKUUx3Ftd95JlHV6XagEnqpT204Y+IsEa3awaYIjayn0MOGjgKZMZibqarK3B1FsMSPaieJf2FEAcu9z0yT5aA==", + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.0.1.tgz", + "integrity": "sha512-ol1X1e24w4j4QwdeNjfX0f+Nza25n+ymY0T2frTyalVczUmzkVD7QGgPTZMHfR1aLrO69hBs0G3QBYaj22J5GQ==", "cpu": [ "x64" ], @@ -290,9 +290,9 @@ } }, "node_modules/@next/swc-win32-arm64-msvc": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-13.4.4.tgz", - "integrity": "sha512-FP8AadgSq4+HPtim7WBkCMGbhr5vh9FePXiWx9+YOdjwdQocwoCK5ZVC3OW8oh3TWth6iJ0AXJ/yQ1q1cwSZ3A==", + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.0.1.tgz", + "integrity": "sha512-WEmTEeWs6yRUEnUlahTgvZteh5RJc4sEjCQIodJlZZ5/VJwVP8p2L7l6VhzQhT4h7KvLx/Ed4UViBdne6zpIsw==", "cpu": [ "arm64" ], @@ -305,9 +305,9 @@ } }, "node_modules/@next/swc-win32-ia32-msvc": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-13.4.4.tgz", - "integrity": "sha512-3WekVmtuA2MCdcAOrgrI+PuFiFURtSyyrN1I3UPtS0ckR2HtLqyqmS334Eulf15g1/bdwMteePdK363X/Y9JMg==", + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.0.1.tgz", + "integrity": "sha512-oFpHphN4ygAgZUKjzga7SoH2VGbEJXZa/KL8bHCAwCjDWle6R1SpiGOdUdA8EJ9YsG1TYWpzY6FTbUA+iAJeww==", "cpu": [ "ia32" ], @@ -320,9 +320,9 @@ } }, "node_modules/@next/swc-win32-x64-msvc": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-13.4.4.tgz", - "integrity": "sha512-AHRITu/CrlQ+qzoqQtEMfaTu7GHaQ6bziQln/pVWpOYC1wU+Mq6VQQFlsDtMCnDztPZtppAXdvvbNS7pcfRzlw==", + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.0.1.tgz", + "integrity": "sha512-FFp3nOJ/5qSpeWT0BZQ+YE1pSMk4IMpkME/1DwKBwhg4mJLB9L+6EXuJi4JEwaJdl5iN+UUlmUD3IsR1kx5fAg==", "cpu": [ "x64" ], @@ -367,14 +367,14 @@ } }, "node_modules/@rushstack/eslint-patch": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@rushstack/eslint-patch/-/eslint-patch-1.3.3.tgz", - "integrity": "sha512-0xd7qez0AQ+MbHatZTlI1gu5vkG8r7MYRUJAHPAHJBmGLs16zpkrpAVLvjQKQOqaXPDUBwOiJzNc00znHSCVBw==" + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@rushstack/eslint-patch/-/eslint-patch-1.5.1.tgz", + "integrity": "sha512-6i/8UoL0P5y4leBIGzvkZdS85RDMG9y1ihZzmTZQ5LdHUYmZ7pKFoj8X0236s3lusPs1Fa5HTQUpwI+UfTcmeA==" }, "node_modules/@swc/helpers": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.1.tgz", - "integrity": "sha512-sJ902EfIzn1Fa+qYmjdQqh8tPsoxyBz+8yBKC2HKUxyezKJFwPGOn7pv4WY6QuQW//ySQi5lJjA/ZT9sNWWNTg==", + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.2.tgz", + "integrity": "sha512-E4KcWTpoLHqwPHLxidpOqQbcrZVgi0rsmmZXUle1jXmJfuIf/UWpczUJ7MZZ5tlxytgJXyp0w4PGkkeLiuIdZw==", "dependencies": { "tslib": "^2.4.0" } @@ -395,9 +395,9 @@ "integrity": "sha512-JJulVEQXmiY9Px5axXHeYGLSjhkZEnD+MDPDGbCbIAbMslkKwmygtZFy1X6s/075Yo94sf8GuSlFfPzysQrWZQ==" }, "node_modules/@types/prop-types": { - "version": "15.7.5", - "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.5.tgz", - "integrity": "sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==" + "version": "15.7.10", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.10.tgz", + "integrity": "sha512-mxSnDQxPqsZxmeShFH+uwQ4kO4gcJcGahjjMFeLbKE95IAZiiZyiEepGZjtXJ7hN/yfu0bu9xN2ajcU0JcxX6A==" }, "node_modules/@types/react": { "version": "18.2.8", @@ -418,9 +418,9 @@ } }, "node_modules/@types/scheduler": { - "version": "0.16.3", - "resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.3.tgz", - "integrity": "sha512-5cJ8CB4yAx7BH1oMvdU0Jh9lrEXyPkar6F9G/ERswkCuvP4KQZfZkSjcMbAICCpQTN4OuZn8tz0HiKv9TGZgrQ==" + "version": "0.16.6", + "resolved": "https://registry.npmjs.org/@types/scheduler/-/scheduler-0.16.6.tgz", + "integrity": "sha512-Vlktnchmkylvc9SnwwwozTv04L/e1NykF5vgoQ0XTmI8DD+wxfjQuHuvHS3p0r2jz2x2ghPs2h1FVeDirIteWA==" }, "node_modules/@typescript-eslint/parser": { "version": "5.62.0", @@ -519,9 +519,9 @@ } }, "node_modules/acorn": { - "version": "8.10.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", - "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz", + "integrity": "sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w==", "bin": { "acorn": "bin/acorn" }, @@ -622,14 +622,14 @@ } }, "node_modules/array-includes": { - "version": "3.1.6", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.6.tgz", - "integrity": "sha512-sgTbLvL6cNnw24FnbaDyjmvddQ2ML8arZsgaJhoABMoplz/4QRhtrYS+alr1BUM1Bwp6dhx8vVCBSLG+StwOFw==", + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.7.tgz", + "integrity": "sha512-dlcsNBIiWhPkHdOEEKnehA+RNUWDc4UqFtnIXU4uuYDPtA4LDkr7qip2p0VvFAEXNDr0yWZ9PJyIRiGjRLQzwQ==", "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4", - "get-intrinsic": "^1.1.3", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", + "get-intrinsic": "^1.2.1", "is-string": "^1.0.7" }, "engines": { @@ -648,15 +648,15 @@ } }, "node_modules/array.prototype.findlastindex": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.2.tgz", - "integrity": "sha512-tb5thFFlUcp7NdNF6/MpDk/1r/4awWG1FIz3YqDf+/zJSTezBb+/5WViH41obXULHVpDzoiCLpJ/ZO9YbJMsdw==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.3.tgz", + "integrity": "sha512-LzLoiOMAxvy+Gd3BAq3B7VeIgPdo+Q8hthvKtXybMvRV0jrXfJM/t8mw7nNlpEcVlVUnCnM2KSX4XU5HmpodOA==", "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", "es-shim-unscopables": "^1.0.0", - "get-intrinsic": "^1.1.3" + "get-intrinsic": "^1.2.1" }, "engines": { "node": ">= 0.4" @@ -666,13 +666,13 @@ } }, "node_modules/array.prototype.flat": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.1.tgz", - "integrity": "sha512-roTU0KWIOmJ4DRLmwKd19Otg0/mT3qPNt0Qb3GWW8iObuZXxrjB/pzn0R3hqpRSWg4HCwqx+0vwOnWnvlOyeIA==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.2.tgz", + "integrity": "sha512-djYB+Zx2vLewY8RWlNCUdHjDXs2XOgm602S9E7P/UpHgfeHL00cRiIF+IN/G/aUJ7kGPb6yO/ErDI5V2s8iycA==", "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", "es-shim-unscopables": "^1.0.0" }, "engines": { @@ -683,13 +683,13 @@ } }, "node_modules/array.prototype.flatmap": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.1.tgz", - "integrity": "sha512-8UGn9O1FDVvMNB0UlLv4voxRMze7+FpHyF5mSMRjWHUMlpoDViniy05870VlxhfgTnLbpuwTzvD76MTtWxB/mQ==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.2.tgz", + "integrity": "sha512-Ewyx0c9PmpcsByhSW4r+9zDU7sGjFc86qf/kKtuSCRdhfbk0SNLLkaT5qvcHnRGgc5NP/ly/y+qkXkqONX54CQ==", "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", "es-shim-unscopables": "^1.0.0" }, "engines": { @@ -700,25 +700,26 @@ } }, "node_modules/array.prototype.tosorted": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array.prototype.tosorted/-/array.prototype.tosorted-1.1.1.tgz", - "integrity": "sha512-pZYPXPRl2PqWcsUs6LOMn+1f1532nEoPTYowBtqLwAW+W8vSVhkIGnmOX1t/UQjD6YGI0vcD2B1U7ZFGQH9jnQ==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/array.prototype.tosorted/-/array.prototype.tosorted-1.1.2.tgz", + "integrity": "sha512-HuQCHOlk1Weat5jzStICBCd83NxiIMwqDg/dHEsoefabn/hJRj5pVdWcPUSpRrwhwxZOsQassMpgN/xRYFBMIg==", "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", "es-shim-unscopables": "^1.0.0", - "get-intrinsic": "^1.1.3" + "get-intrinsic": "^1.2.1" } }, "node_modules/arraybuffer.prototype.slice": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.1.tgz", - "integrity": "sha512-09x0ZWFEjj4WD8PDbykUwo3t9arLn8NIzmmYEJFpYekOAQjpkGSyrQhNoRTcwwcFRu+ycWF78QZ63oWTqSjBcw==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.2.tgz", + "integrity": "sha512-yMBKppFur/fbHu9/6USUe03bZ4knMYiwFBcyiaXB8Go0qNehwX6inYPzK9U0NeQvGxKthcmHcaR8P5MStSRBAw==", "dependencies": { "array-buffer-byte-length": "^1.0.0", "call-bind": "^1.0.2", "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", "get-intrinsic": "^1.2.1", "is-array-buffer": "^3.0.2", "is-shared-array-buffer": "^1.0.2" @@ -731,9 +732,9 @@ } }, "node_modules/ast-types-flow": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.7.tgz", - "integrity": "sha512-eBvWn1lvIApYMhzQMsu9ciLfkBY499mFZlNqG+/9WR7PVlroQw0vG30cOQQbaKz3sCEc44TAOu2ykzqXSNnwag==" + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz", + "integrity": "sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==" }, "node_modules/asynciterator.prototype": { "version": "1.0.0", @@ -787,9 +788,9 @@ } }, "node_modules/axe-core": { - "version": "4.7.2", - "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.7.2.tgz", - "integrity": "sha512-zIURGIS1E1Q4pcrMjp+nnEh+16G56eG/MUllJH8yEvw7asDo7Ac9uhC9KIH5jzpITueEZolfYglnCGIuSBz39g==", + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.7.0.tgz", + "integrity": "sha512-M0JtH+hlOL5pLQwHOLNYZaXuhqmvS8oExsqB1SBYgA4Dk7u/xx+YdGHXaK5pyUfed5mYXdlYiphWq3G8cRi5JQ==", "engines": { "node": ">=4" } @@ -836,9 +837,9 @@ } }, "node_modules/browserslist": { - "version": "4.21.10", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.10.tgz", - "integrity": "sha512-bipEBdZfVH5/pwrvqc+Ub0kUPVfGUhlKxbvfD+z1BDnPEO/X98ruXGA1WP5ASpAFKan7Qr6j736IacbZQuAlKQ==", + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.1.tgz", + "integrity": "sha512-FEVc202+2iuClEhZhrWy6ZiAcRLvNMyYcxZ8raemul1DYVOVdFsbqckWLdsixQZCpJlwe77Z3UTalE7jsjnKfQ==", "funding": [ { "type": "opencollective", @@ -854,10 +855,10 @@ } ], "dependencies": { - "caniuse-lite": "^1.0.30001517", - "electron-to-chromium": "^1.4.477", + "caniuse-lite": "^1.0.30001541", + "electron-to-chromium": "^1.4.535", "node-releases": "^2.0.13", - "update-browserslist-db": "^1.0.11" + "update-browserslist-db": "^1.0.13" }, "bin": { "browserslist": "cli.js" @@ -878,12 +879,13 @@ } }, "node_modules/call-bind": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", - "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.5.tgz", + "integrity": "sha512-C3nQxfFZxFRVoJoGKKI8y3MOEo129NQ+FgQ08iye+Mk4zNZZGdjfs06bVTr+DBSlA66Q2VEcMki/cUCP4SercQ==", "dependencies": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.1", + "set-function-length": "^1.1.1" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -906,9 +908,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001524", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001524.tgz", - "integrity": "sha512-Jj917pJtYg9HSJBF95HVX3Cdr89JUyLT4IZ8SvM5aDRni95swKgYi3TgYLH5hnGfPE/U1dg6IfZ50UsIlLkwSA==", + "version": "1.0.30001561", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001561.tgz", + "integrity": "sha512-NTt0DNoKe958Q0BE0j0c1V9jbUzhBxHIEJy7asmGrpE0yG63KTV7PLHPnK2E1O9RsQrQ081I3NLuXGS6zht3cw==", "funding": [ { "type": "opencollective", @@ -1065,11 +1067,25 @@ "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==" }, + "node_modules/define-data-property": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.1.tgz", + "integrity": "sha512-E7uGkTzkk1d0ByLeSc6ZsFS79Axg+m1P/VsgYsxHgiuc3tFSj+MjMIwe90FC4lOAZzNBdY7kkO2P2wKdsQ1vgQ==", + "dependencies": { + "get-intrinsic": "^1.2.1", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/define-properties": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.0.tgz", - "integrity": "sha512-xvqAVKGfT1+UAvPwKTVw/njhdQ8ZhXK4lI0bCIuCMrp2up9nPnaDftrLtmpTazqd1o+UY4zgzU+avtMbDP+ldA==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", "dependencies": { + "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" }, @@ -1121,9 +1137,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.4.504", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.504.tgz", - "integrity": "sha512-cSMwIAd8yUh54VwitVRVvHK66QqHWE39C3DRj8SWiXitEpVSY3wNPD9y1pxQtLIi4w3UdzF9klLsmuPshz09DQ==" + "version": "1.4.578", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.578.tgz", + "integrity": "sha512-V0ZhSu1BQZKfG0yNEL6Dadzik8E1vAzfpVOapdSiT9F6yapEJ3Bk+4tZ4SMPdWiUchCgnM/ByYtBzp5ntzDMIA==" }, "node_modules/emoji-regex": { "version": "9.2.2", @@ -1143,25 +1159,25 @@ } }, "node_modules/es-abstract": { - "version": "1.22.1", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.22.1.tgz", - "integrity": "sha512-ioRRcXMO6OFyRpyzV3kE1IIBd4WG5/kltnzdxSCqoP8CMGs/Li+M1uF5o7lOkZVFjDs+NLesthnF66Pg/0q0Lw==", + "version": "1.22.3", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.22.3.tgz", + "integrity": "sha512-eiiY8HQeYfYH2Con2berK+To6GrK2RxbPawDkGq4UiCQQfZHb6wX9qQqkbpPqaxQFcl8d9QzZqo0tGE0VcrdwA==", "dependencies": { "array-buffer-byte-length": "^1.0.0", - "arraybuffer.prototype.slice": "^1.0.1", + "arraybuffer.prototype.slice": "^1.0.2", "available-typed-arrays": "^1.0.5", - "call-bind": "^1.0.2", + "call-bind": "^1.0.5", "es-set-tostringtag": "^2.0.1", "es-to-primitive": "^1.2.1", - "function.prototype.name": "^1.1.5", - "get-intrinsic": "^1.2.1", + "function.prototype.name": "^1.1.6", + "get-intrinsic": "^1.2.2", "get-symbol-description": "^1.0.0", "globalthis": "^1.0.3", "gopd": "^1.0.1", - "has": "^1.0.3", "has-property-descriptors": "^1.0.0", "has-proto": "^1.0.1", "has-symbols": "^1.0.3", + "hasown": "^2.0.0", "internal-slot": "^1.0.5", "is-array-buffer": "^3.0.2", "is-callable": "^1.2.7", @@ -1169,23 +1185,23 @@ "is-regex": "^1.1.4", "is-shared-array-buffer": "^1.0.2", "is-string": "^1.0.7", - "is-typed-array": "^1.1.10", + "is-typed-array": "^1.1.12", "is-weakref": "^1.0.2", - "object-inspect": "^1.12.3", + "object-inspect": "^1.13.1", "object-keys": "^1.1.1", "object.assign": "^4.1.4", - "regexp.prototype.flags": "^1.5.0", - "safe-array-concat": "^1.0.0", + "regexp.prototype.flags": "^1.5.1", + "safe-array-concat": "^1.0.1", "safe-regex-test": "^1.0.0", - "string.prototype.trim": "^1.2.7", - "string.prototype.trimend": "^1.0.6", - "string.prototype.trimstart": "^1.0.6", + "string.prototype.trim": "^1.2.8", + "string.prototype.trimend": "^1.0.7", + "string.prototype.trimstart": "^1.0.7", "typed-array-buffer": "^1.0.0", "typed-array-byte-length": "^1.0.0", "typed-array-byte-offset": "^1.0.0", "typed-array-length": "^1.0.4", "unbox-primitive": "^1.0.2", - "which-typed-array": "^1.1.10" + "which-typed-array": "^1.1.13" }, "engines": { "node": ">= 0.4" @@ -1195,13 +1211,13 @@ } }, "node_modules/es-iterator-helpers": { - "version": "1.0.14", - "resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.0.14.tgz", - "integrity": "sha512-JgtVnwiuoRuzLvqelrvN3Xu7H9bu2ap/kQ2CrM62iidP8SKuD99rWU3CJy++s7IVL2qb/AjXPGR/E7i9ngd/Cw==", + "version": "1.0.15", + "resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.0.15.tgz", + "integrity": "sha512-GhoY8uYqd6iwUl2kgjTm4CZAf6oo5mHK7BPqx3rKgx893YSsy0LGHV6gfqqQvZt/8xM8xeOnfXBCfqclMKkJ5g==", "dependencies": { "asynciterator.prototype": "^1.0.0", "call-bind": "^1.0.2", - "define-properties": "^1.2.0", + "define-properties": "^1.2.1", "es-abstract": "^1.22.1", "es-set-tostringtag": "^2.0.1", "function-bind": "^1.1.1", @@ -1211,29 +1227,29 @@ "has-proto": "^1.0.1", "has-symbols": "^1.0.3", "internal-slot": "^1.0.5", - "iterator.prototype": "^1.1.0", - "safe-array-concat": "^1.0.0" + "iterator.prototype": "^1.1.2", + "safe-array-concat": "^1.0.1" } }, "node_modules/es-set-tostringtag": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.1.tgz", - "integrity": "sha512-g3OMbtlwY3QewlqAiMLI47KywjWZoEytKr8pf6iTC8uJq5bIAH52Z9pnQ8pVL6whrCto53JZDuUIsifGeLorTg==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.2.tgz", + "integrity": "sha512-BuDyupZt65P9D2D2vA/zqcI3G5xRsklm5N3xCwuiy+/vKy8i0ifdsQP1sLgO4tZDSCaQUSnmC48khknGMV3D2Q==", "dependencies": { - "get-intrinsic": "^1.1.3", - "has": "^1.0.3", - "has-tostringtag": "^1.0.0" + "get-intrinsic": "^1.2.2", + "has-tostringtag": "^1.0.0", + "hasown": "^2.0.0" }, "engines": { "node": ">= 0.4" } }, "node_modules/es-shim-unscopables": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.0.tgz", - "integrity": "sha512-Jm6GPcCdC30eMLbZ2x8z2WuRwAws3zTBBKuusffYVUrNj/GVSUAZ+xKMaUpfNDR5IbyNA5LJbaecoUVbmUcB1w==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.2.tgz", + "integrity": "sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==", "dependencies": { - "has": "^1.0.3" + "hasown": "^2.0.0" } }, "node_modules/es-to-primitive": { @@ -1370,9 +1386,9 @@ } }, "node_modules/eslint-import-resolver-typescript": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.6.0.tgz", - "integrity": "sha512-QTHR9ddNnn35RTxlaEnx2gCxqFlF2SEN0SE2d17SqwyM7YOSI2GHWRYp5BiRkObTUNYPupC/3Fq2a0PpT+EKpg==", + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.6.1.tgz", + "integrity": "sha512-xgdptdoi5W3niYeuQxKmzVDTATvLYqhpwmykwsh7f6HIOStGWEIL9iqZgQDF9u9OEzrRwR8no5q2VT+bjAujTg==", "dependencies": { "debug": "^4.3.4", "enhanced-resolve": "^5.12.0", @@ -1418,25 +1434,25 @@ } }, "node_modules/eslint-plugin-import": { - "version": "2.28.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.28.1.tgz", - "integrity": "sha512-9I9hFlITvOV55alzoKBI+K9q74kv0iKMeY6av5+umsNwayt59fz692daGyjR+oStBQgx6nwR9rXldDev3Clw+A==", - "dependencies": { - "array-includes": "^3.1.6", - "array.prototype.findlastindex": "^1.2.2", - "array.prototype.flat": "^1.3.1", - "array.prototype.flatmap": "^1.3.1", + "version": "2.29.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.29.0.tgz", + "integrity": "sha512-QPOO5NO6Odv5lpoTkddtutccQjysJuFxoPS7fAHO+9m9udNHvTCPSAMW9zGAYj8lAIdr40I8yPCdUYrncXtrwg==", + "dependencies": { + "array-includes": "^3.1.7", + "array.prototype.findlastindex": "^1.2.3", + "array.prototype.flat": "^1.3.2", + "array.prototype.flatmap": "^1.3.2", "debug": "^3.2.7", "doctrine": "^2.1.0", - "eslint-import-resolver-node": "^0.3.7", + "eslint-import-resolver-node": "^0.3.9", "eslint-module-utils": "^2.8.0", - "has": "^1.0.3", - "is-core-module": "^2.13.0", + "hasown": "^2.0.0", + "is-core-module": "^2.13.1", "is-glob": "^4.0.3", "minimatch": "^3.1.2", - "object.fromentries": "^2.0.6", - "object.groupby": "^1.0.0", - "object.values": "^1.1.6", + "object.fromentries": "^2.0.7", + "object.groupby": "^1.0.1", + "object.values": "^1.1.7", "semver": "^6.3.1", "tsconfig-paths": "^3.14.2" }, @@ -1475,26 +1491,26 @@ } }, "node_modules/eslint-plugin-jsx-a11y": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.7.1.tgz", - "integrity": "sha512-63Bog4iIethyo8smBklORknVjB0T2dwB8Mr/hIC+fBS0uyHdYYpzM/Ed+YC8VxTjlXHEWFOdmgwcDn1U2L9VCA==", - "dependencies": { - "@babel/runtime": "^7.20.7", - "aria-query": "^5.1.3", - "array-includes": "^3.1.6", - "array.prototype.flatmap": "^1.3.1", - "ast-types-flow": "^0.0.7", - "axe-core": "^4.6.2", - "axobject-query": "^3.1.1", + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.8.0.tgz", + "integrity": "sha512-Hdh937BS3KdwwbBaKd5+PLCOmYY6U4f2h9Z2ktwtNKvIdIEu137rjYbcb9ApSbVJfWxANNuiKTD/9tOKjK9qOA==", + "dependencies": { + "@babel/runtime": "^7.23.2", + "aria-query": "^5.3.0", + "array-includes": "^3.1.7", + "array.prototype.flatmap": "^1.3.2", + "ast-types-flow": "^0.0.8", + "axe-core": "=4.7.0", + "axobject-query": "^3.2.1", "damerau-levenshtein": "^1.0.8", "emoji-regex": "^9.2.2", - "has": "^1.0.3", - "jsx-ast-utils": "^3.3.3", - "language-tags": "=1.0.5", + "es-iterator-helpers": "^1.0.15", + "hasown": "^2.0.0", + "jsx-ast-utils": "^3.3.5", + "language-tags": "^1.0.9", "minimatch": "^3.1.2", - "object.entries": "^1.1.6", - "object.fromentries": "^2.0.6", - "semver": "^6.3.0" + "object.entries": "^1.1.7", + "object.fromentries": "^2.0.7" }, "engines": { "node": ">=4.0" @@ -1503,14 +1519,6 @@ "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8" } }, - "node_modules/eslint-plugin-jsx-a11y/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "bin": { - "semver": "bin/semver.js" - } - }, "node_modules/eslint-plugin-react": { "version": "7.33.2", "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.33.2.tgz", @@ -1563,11 +1571,11 @@ } }, "node_modules/eslint-plugin-react/node_modules/resolve": { - "version": "2.0.0-next.4", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.4.tgz", - "integrity": "sha512-iMDbmAWtfU+MHpxt/I5iWI7cY6YVEZUQ3MBgPQ++XD1PELuJHIl82xBmObyP2KyQmkNB2dsqF7seoQQiAn5yDQ==", + "version": "2.0.0-next.5", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.5.tgz", + "integrity": "sha512-U7WjGVG9sH8tvjW5SmGbQuui75FiyjAX72HX15DwBBwF9dNiQZRQAg9nnPhYy+TUnE0+VcrttuvNI8oSxZcocA==", "dependencies": { - "is-core-module": "^2.9.0", + "is-core-module": "^2.13.0", "path-parse": "^1.0.7", "supports-preserve-symlinks-flag": "^1.0.0" }, @@ -1672,9 +1680,9 @@ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" }, "node_modules/fast-glob": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz", - "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", + "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", @@ -1753,11 +1761,11 @@ } }, "node_modules/flat-cache": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.1.0.tgz", - "integrity": "sha512-OHx4Qwrrt0E4jEIcI5/Xb+f+QmJYNj2rrK8wiIdQOIrB9WrrJL8cjZvXdXuBTkkEwEqLycb5BeZDV1o2i9bTew==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.1.1.tgz", + "integrity": "sha512-/qM2b3LUIaIgviBQovTLvijfyOQXPtSRnRK26ksj2J7rzPIecePUIpJsZ4T02Qg+xiAEKIs5K8dsHEd+VaKa/Q==", "dependencies": { - "flatted": "^3.2.7", + "flatted": "^3.2.9", "keyv": "^4.5.3", "rimraf": "^3.0.2" }, @@ -1766,9 +1774,9 @@ } }, "node_modules/flatted": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.7.tgz", - "integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==" + "version": "3.2.9", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.9.tgz", + "integrity": "sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ==" }, "node_modules/for-each": { "version": "0.3.3", @@ -1779,15 +1787,15 @@ } }, "node_modules/fraction.js": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.2.1.tgz", - "integrity": "sha512-/KxoyCnPM0GwYI4NN0Iag38Tqt+od3/mLuguepLgCAKPn0ZhC544nssAW0tG2/00zXEYl9W+7hwAIpLHo6Oc7Q==", + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", + "integrity": "sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==", "engines": { "node": "*" }, "funding": { "type": "patreon", - "url": "https://www.patreon.com/infusion" + "url": "https://github.com/sponsors/rawify" } }, "node_modules/fs.realpath": { @@ -1809,9 +1817,12 @@ } }, "node_modules/function-bind": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/function.prototype.name": { "version": "1.1.6", @@ -1839,14 +1850,14 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.1.tgz", - "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.2.tgz", + "integrity": "sha512-0gSo4ml/0j98Y3lngkFEot/zhiCeWsbYIlZ+uZOVgzLyLaUw7wxUL+nCTP0XJvJg1AXulJRI3UJi8GsbDuxdGA==", "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", + "function-bind": "^1.1.2", "has-proto": "^1.0.1", - "has-symbols": "^1.0.3" + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -1868,9 +1879,9 @@ } }, "node_modules/get-tsconfig": { - "version": "4.7.0", - "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.7.0.tgz", - "integrity": "sha512-pmjiZ7xtB8URYm74PlGJozDNyhvsVLUcpBa8DZBG3bWHwaHa9bPiRpiSfovw+fjhwONSCWKRyk+JQHEGZmMrzw==", + "version": "4.7.2", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.7.2.tgz", + "integrity": "sha512-wuMsz4leaj5hbGgg4IvDU0bqJagpftG5l5cXIAvo8uZrqn0NJqwtfupTN00VnkQJPcIRrxYrm1Ue24btpCha2A==", "dependencies": { "resolve-pkg-maps": "^1.0.0" }, @@ -1908,10 +1919,15 @@ "node": ">=10.13.0" } }, + "node_modules/glob-to-regexp": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", + "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==" + }, "node_modules/globals": { - "version": "13.21.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.21.0.tgz", - "integrity": "sha512-ybyme3s4yy/t/3s35bewwXKOf7cvzfreG2lH0lZl0JB7I4GxRP2ghxOK/Nb9EkRXdbBXZLfq/p/0W2JUONB/Gg==", + "version": "13.23.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.23.0.tgz", + "integrity": "sha512-XAmF0RjlrjY23MA51q3HltdlGxUpXPvg0GioKiD9X6HD28iMjo2dKC8Vqwm7lne4GNr78+RHTfliktR6ZH09wA==", "dependencies": { "type-fest": "^0.20.2" }, @@ -1976,17 +1992,6 @@ "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==" }, - "node_modules/has": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "dependencies": { - "function-bind": "^1.1.1" - }, - "engines": { - "node": ">= 0.4.0" - } - }, "node_modules/has-bigints": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz", @@ -2004,11 +2009,11 @@ } }, "node_modules/has-property-descriptors": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.0.tgz", - "integrity": "sha512-62DVLZGoiEBDHQyqG4w9xCuZ7eJEwNmJRWw2VY84Oedb7WFcA27fiEVe8oUQx9hAUJ4ekurquucTGwsyO1XGdQ==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.1.tgz", + "integrity": "sha512-VsX8eaIewvas0xnvinAe9bw4WfIeODpGYikiWYLH+dma0Jw6KHYqWiWfhQlgOVK8D6PvjubK5Uc4P0iIhIcNVg==", "dependencies": { - "get-intrinsic": "^1.1.1" + "get-intrinsic": "^1.2.2" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -2050,6 +2055,17 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/hasown": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", + "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/ignore": { "version": "5.2.4", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", @@ -2101,12 +2117,12 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, "node_modules/internal-slot": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.5.tgz", - "integrity": "sha512-Y+R5hJrzs52QCG2laLn4udYVnxsfny9CpOhNhUvk/SSSVyF6T27FzRbF0sroPidSu3X8oEAkOn2K804mjpt6UQ==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.6.tgz", + "integrity": "sha512-Xj6dv+PsbtwyPpEflsejS+oIZxmMlV44zAhG479uYu89MsjcYOhCFnNyKrkJrihbsiasQyY0afoCl/9BLR65bg==", "dependencies": { - "get-intrinsic": "^1.2.0", - "has": "^1.0.3", + "get-intrinsic": "^1.2.2", + "hasown": "^2.0.0", "side-channel": "^1.0.4" }, "engines": { @@ -2189,11 +2205,11 @@ } }, "node_modules/is-core-module": { - "version": "2.13.0", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.0.tgz", - "integrity": "sha512-Z7dk6Qo8pOCp3l4tsX2C5ZVas4V+UxwQodwZhLopL91TX8UyyHEXafPcyoeeWuLrwzHcr3igO78wNLwHJHsMCQ==", + "version": "2.13.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz", + "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==", "dependencies": { - "has": "^1.0.3" + "hasown": "^2.0.0" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -2424,21 +2440,21 @@ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" }, "node_modules/iterator.prototype": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.0.tgz", - "integrity": "sha512-rjuhAk1AJ1fssphHD0IFV6TWL40CwRZ53FrztKx43yk2v6rguBYsY4Bj1VU4HmoMmKwZUlx7mfnhDf9cOp4YTw==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.2.tgz", + "integrity": "sha512-DR33HMMr8EzwuRL8Y9D3u2BMj8+RqSE850jfGu59kS7tbmPLzGkZmVSfyCFSDxuZiEY6Rzt3T2NA/qU+NwVj1w==", "dependencies": { - "define-properties": "^1.1.4", - "get-intrinsic": "^1.1.3", + "define-properties": "^1.2.1", + "get-intrinsic": "^1.2.1", "has-symbols": "^1.0.3", - "has-tostringtag": "^1.0.0", - "reflect.getprototypeof": "^1.0.3" + "reflect.getprototypeof": "^1.0.4", + "set-function-name": "^2.0.1" } }, "node_modules/jiti": { - "version": "1.19.3", - "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.19.3.tgz", - "integrity": "sha512-5eEbBDQT/jF1xg6l36P+mWGGoH9Spuy0PCdSr2dtWRDGC6ph/w9ZCL4lmESW8f8F7MwT3XKescfP0wnZWAKL9w==", + "version": "1.21.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.0.tgz", + "integrity": "sha512-gFqAIbuKyyso/3G2qhiO2OM6shY6EPP/R0+mkDbyspxKazh8BXDC5FiFsUjlczgdNz/vfra0da2y+aHrusLG/Q==", "bin": { "jiti": "bin/jiti.js" } @@ -2500,9 +2516,9 @@ } }, "node_modules/keyv": { - "version": "4.5.3", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.3.tgz", - "integrity": "sha512-QCiSav9WaX1PgETJ+SpNnx2PRRapJ/oRSXM4VO5OGYGSjrxbKPVFVhB3l2OCbLCk329N8qyAtsJjSjvVBWzEug==", + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", "dependencies": { "json-buffer": "3.0.1" } @@ -2513,11 +2529,14 @@ "integrity": "sha512-tN0MCzyWnoz/4nHS6uxdlFWoUZT7ABptwKPQ52Ea7URk6vll88bWBVhodtnlfEuCcKWNGoc+uGbw1cwa9IKh/w==" }, "node_modules/language-tags": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.5.tgz", - "integrity": "sha512-qJhlO9cGXi6hBGKoxEG/sKZDAHD5Hnu9Hs4WbOY3pCWXDhw0N8x1NenNzm2EnNLkLkk7J2SdxAkDSbb6ftT+UQ==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.9.tgz", + "integrity": "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==", "dependencies": { - "language-subtag-registry": "~0.3.2" + "language-subtag-registry": "^0.3.20" + }, + "engines": { + "node": ">=0.10" } }, "node_modules/levn": { @@ -2641,9 +2660,9 @@ } }, "node_modules/nanoid": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz", - "integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==", + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", + "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", "funding": [ { "type": "github", @@ -2663,38 +2682,37 @@ "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==" }, "node_modules/next": { - "version": "13.4.4", - "resolved": "https://registry.npmjs.org/next/-/next-13.4.4.tgz", - "integrity": "sha512-C5S0ysM0Ily9McL4Jb48nOQHT1BukOWI59uC3X/xCMlYIh9rJZCv7nzG92J6e1cOBqQbKovlpgvHWFmz4eKKEA==", + "version": "14.0.1", + "resolved": "https://registry.npmjs.org/next/-/next-14.0.1.tgz", + "integrity": "sha512-s4YaLpE4b0gmb3ggtmpmV+wt+lPRuGtANzojMQ2+gmBpgX9w5fTbjsy6dXByBuENsdCX5pukZH/GxdFgO62+pA==", "dependencies": { - "@next/env": "13.4.4", - "@swc/helpers": "0.5.1", + "@next/env": "14.0.1", + "@swc/helpers": "0.5.2", "busboy": "1.6.0", "caniuse-lite": "^1.0.30001406", - "postcss": "8.4.14", + "postcss": "8.4.31", "styled-jsx": "5.1.1", - "zod": "3.21.4" + "watchpack": "2.4.0" }, "bin": { "next": "dist/bin/next" }, "engines": { - "node": ">=16.8.0" + "node": ">=18.17.0" }, "optionalDependencies": { - "@next/swc-darwin-arm64": "13.4.4", - "@next/swc-darwin-x64": "13.4.4", - "@next/swc-linux-arm64-gnu": "13.4.4", - "@next/swc-linux-arm64-musl": "13.4.4", - "@next/swc-linux-x64-gnu": "13.4.4", - "@next/swc-linux-x64-musl": "13.4.4", - "@next/swc-win32-arm64-msvc": "13.4.4", - "@next/swc-win32-ia32-msvc": "13.4.4", - "@next/swc-win32-x64-msvc": "13.4.4" + "@next/swc-darwin-arm64": "14.0.1", + "@next/swc-darwin-x64": "14.0.1", + "@next/swc-linux-arm64-gnu": "14.0.1", + "@next/swc-linux-arm64-musl": "14.0.1", + "@next/swc-linux-x64-gnu": "14.0.1", + "@next/swc-linux-x64-musl": "14.0.1", + "@next/swc-win32-arm64-msvc": "14.0.1", + "@next/swc-win32-ia32-msvc": "14.0.1", + "@next/swc-win32-x64-msvc": "14.0.1" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0", - "fibers": ">= 3.1.0", "react": "^18.2.0", "react-dom": "^18.2.0", "sass": "^1.3.0" @@ -2703,18 +2721,15 @@ "@opentelemetry/api": { "optional": true }, - "fibers": { - "optional": true - }, "sass": { "optional": true } } }, "node_modules/next/node_modules/postcss": { - "version": "8.4.14", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.14.tgz", - "integrity": "sha512-E398TUmfAYFPBSdzgeieK2Y1+1cpdxJx8yXbK/m57nRhKSmk1GB2tO4lbLBtlkfPQTDKfe4Xqv1ASWPpayPEig==", + "version": "8.4.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", + "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", "funding": [ { "type": "opencollective", @@ -2723,10 +2738,14 @@ { "type": "tidelift", "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" } ], "dependencies": { - "nanoid": "^3.3.4", + "nanoid": "^3.3.6", "picocolors": "^1.0.0", "source-map-js": "^1.0.2" }, @@ -2772,9 +2791,9 @@ } }, "node_modules/object-inspect": { - "version": "1.12.3", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz", - "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", + "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -3147,9 +3166,9 @@ } }, "node_modules/punycode": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", - "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", "engines": { "node": ">=6" } @@ -3221,14 +3240,14 @@ } }, "node_modules/reflect.getprototypeof": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.3.tgz", - "integrity": "sha512-TTAOZpkJ2YLxl7mVHWrNo3iDMEkYlva/kgFcXndqMgbo/AZUmmavEkdXV+hXtE4P8xdyEKRzalaFqZVuwIk/Nw==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.4.tgz", + "integrity": "sha512-ECkTw8TmJwW60lOTR+ZkODISW6RQ8+2CL3COqtiJKLd6MmB45hN51HprHFziKLGkAuTGQhBb91V8cy+KHlaCjw==", "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4", - "get-intrinsic": "^1.1.1", + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1", + "get-intrinsic": "^1.2.1", "globalthis": "^1.0.3", "which-builtin-type": "^1.1.3" }, @@ -3245,13 +3264,13 @@ "integrity": "sha512-srw17NI0TUWHuGa5CFGGmhfNIeja30WMBfbslPNhf6JrqQlLN5gcrvig1oqPxiVaXb0oW0XRKtH6Nngs5lKCIA==" }, "node_modules/regexp.prototype.flags": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.0.tgz", - "integrity": "sha512-0SutC3pNudRKgquxGoRGIz946MZVHqbNfPjBdxeOhBrdgDKlRoXmYLQN9xRbrR09ZXWeGAdPuif7egofn6v5LA==", + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.1.tgz", + "integrity": "sha512-sy6TXMN+hnP/wMy+ISxg3krXx7BAtWVO4UouuCN/ziM9UEne0euamVNafDfvC83bRNr95y0V5iijeDQFUNpvrg==", "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.2.0", - "functions-have-names": "^1.2.3" + "set-function-name": "^2.0.0" }, "engines": { "node": ">= 0.4" @@ -3261,9 +3280,9 @@ } }, "node_modules/resolve": { - "version": "1.22.4", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.4.tgz", - "integrity": "sha512-PXNdCiPqDqeUou+w1C2eTQbNfxKSuMxqTCuvlmmMsk1NWHL5fRrhY6Pl0qEYYc6+QqGClco1Qj8XnjPego4wfg==", + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", "dependencies": { "is-core-module": "^2.13.0", "path-parse": "^1.0.7", @@ -3338,12 +3357,12 @@ } }, "node_modules/safe-array-concat": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.0.0.tgz", - "integrity": "sha512-9dVEFruWIsnie89yym+xWTAYASdpw3CJV7Li/6zBewGf9z2i1j31rP6jnY0pHEO4QZh6N0K11bFjWmdR8UGdPQ==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.0.1.tgz", + "integrity": "sha512-6XbUAseYE2KtOuGueyeobCySj9L4+66Tn6KQMOPQJrAJEowYKW/YR/MGJZl7FdydUdaFu4LYyDZjxf4/Nmo23Q==", "dependencies": { "call-bind": "^1.0.2", - "get-intrinsic": "^1.2.0", + "get-intrinsic": "^1.2.1", "has-symbols": "^1.0.3", "isarray": "^2.0.5" }, @@ -3368,9 +3387,9 @@ } }, "node_modules/sass": { - "version": "1.66.1", - "resolved": "https://registry.npmjs.org/sass/-/sass-1.66.1.tgz", - "integrity": "sha512-50c+zTsZOJVgFfTgwwEzkjA3/QACgdNsKueWPyAR0mRINIvLAStVQBbPg14iuqEQ74NPDbXzJARJ/O4SI1zftA==", + "version": "1.69.5", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.69.5.tgz", + "integrity": "sha512-qg2+UCJibLr2LCVOt3OlPhr/dqVHWOa9XtZf2OjbLs/T4VPSJ00udtgJxH3neXZm+QqX8B+3cU7RaLqp1iVfcQ==", "dependencies": { "chokidar": ">=3.0.0 <4.0.0", "immutable": "^4.0.0", @@ -3405,6 +3424,33 @@ "node": ">=10" } }, + "node_modules/set-function-length": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.1.1.tgz", + "integrity": "sha512-VoaqjbBJKiWtg4yRcKBQ7g7wnGnLV3M8oLvVWwOk2PdYY6PEFegR1vezXR0tw6fZGF9csVakIRjrJiy2veSBFQ==", + "dependencies": { + "define-data-property": "^1.1.1", + "get-intrinsic": "^1.2.1", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.1.tgz", + "integrity": "sha512-tMNCiqYVkXIZgc2Hnoy2IvC/f8ezc5koaRFkCjrpWzGpCd3qbZXPzVy9MAZzK1ch/X0jvSkojys3oqJN0qCmdA==", + "dependencies": { + "define-data-property": "^1.0.1", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -3462,9 +3508,9 @@ } }, "node_modules/string.prototype.matchall": { - "version": "4.0.9", - "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.9.tgz", - "integrity": "sha512-6i5hL3MqG/K2G43mWXWgP+qizFW/QH/7kCNN13JrJS5q48FN5IKksLDscexKP3dnmB6cdm9jlNgAsWNLpSykmA==", + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.10.tgz", + "integrity": "sha512-rGXbGmOEosIQi6Qva94HUjgPs9vKW+dkG7Y8Q5O2OYkWL6wFaTRZO8zM4mhP94uX55wgyrXzfS2aGtGzUL7EJQ==", "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.2.0", @@ -3473,6 +3519,7 @@ "has-symbols": "^1.0.3", "internal-slot": "^1.0.5", "regexp.prototype.flags": "^1.5.0", + "set-function-name": "^2.0.0", "side-channel": "^1.0.4" }, "funding": { @@ -3480,13 +3527,13 @@ } }, "node_modules/string.prototype.trim": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.7.tgz", - "integrity": "sha512-p6TmeT1T3411M8Cgg9wBTMRtY2q9+PNy9EV1i2lIXUN/btt763oIfxwN3RR8VU6wHX8j/1CFy0L+YuThm6bgOg==", + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.8.tgz", + "integrity": "sha512-lfjY4HcixfQXOfaqCvcBuOIapyaroTXhbkfJN3gcB1OtyupngWK4sEET9Knd0cXd28kTUqu/kHoV4HKSJdnjiQ==", "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4" + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1" }, "engines": { "node": ">= 0.4" @@ -3496,26 +3543,26 @@ } }, "node_modules/string.prototype.trimend": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.6.tgz", - "integrity": "sha512-JySq+4mrPf9EsDBEDYMOb/lM7XQLulwg5R/m1r0PXEFqrV0qHvl58sdTilSXtKOflCsK2E8jxf+GKC0T07RWwQ==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.7.tgz", + "integrity": "sha512-Ni79DqeB72ZFq1uH/L6zJ+DKZTkOtPIHovb3YZHQViE+HDouuU4mBrLOLDn5Dde3RF8qw5qVETEjhu9locMLvA==", "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4" + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/string.prototype.trimstart": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.6.tgz", - "integrity": "sha512-omqjMDaY92pbn5HOX7f9IccLA+U1tA9GvtU4JrodiXFfYB7jPzzHpRzpglLAjtUV6bB557zwClJezTqnAiYnQA==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.7.tgz", + "integrity": "sha512-NGhtDFu3jCEm7B4Fy0DpLewdJQOZcQ0rGbwQ/+stjnrp2i+rlKeCvos9hOIeCmqwratM47OBxY7uFZzjxHXmrg==", "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.4", - "es-abstract": "^1.20.4" + "define-properties": "^1.2.0", + "es-abstract": "^1.22.1" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -3873,9 +3920,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.11.tgz", - "integrity": "sha512-dCwEFf0/oT85M1fHBg4F0jtLwJrutGoHSQXCh7u4o2t1drG+c0a9Flnqww6XUKSfQMPpJBRjU8d4RXB09qtvaA==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", + "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", "funding": [ { "type": "opencollective", @@ -3914,6 +3961,18 @@ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" }, + "node_modules/watchpack": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.0.tgz", + "integrity": "sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg==", + "dependencies": { + "glob-to-regexp": "^0.4.1", + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -3983,12 +4042,12 @@ } }, "node_modules/which-typed-array": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.11.tgz", - "integrity": "sha512-qe9UWWpkeG5yzZ0tNYxDmd7vo58HDBc39mZ0xWWpolAGADdFOzkfamWLDxkOWcvHQKVmdTyQdLD4NOfjLWTKew==", + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.13.tgz", + "integrity": "sha512-P5Nra0qjSncduVPEAr7xhoF5guty49ArDTwzJ/yNuPIbZppyRxFQsRCWrocxIY+CnMVG+qfbU2FmDKyvSGClow==", "dependencies": { "available-typed-arrays": "^1.0.5", - "call-bind": "^1.0.2", + "call-bind": "^1.0.4", "for-each": "^0.3.3", "gopd": "^1.0.1", "has-tostringtag": "^1.0.0" @@ -4011,9 +4070,9 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/yaml": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.3.2.tgz", - "integrity": "sha512-N/lyzTPaJasoDmfV7YTrYCI0G/3ivm/9wdG0aHuheKowWQwGTsK0Eoiw6utmzAnI6pkJa0DUVygvp3spqqEKXg==", + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.3.4.tgz", + "integrity": "sha512-8aAvwVUSHpfEqTQ4w/KMlf3HcRdt50E5ODIQJBw1fQ5RL34xabzxtUlzTXVqc4rkZsPbvrXKWnABCD7kWSmocA==", "engines": { "node": ">= 14" } @@ -4028,14 +4087,6 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } - }, - "node_modules/zod": { - "version": "3.21.4", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.21.4.tgz", - "integrity": "sha512-m46AKbrzKVzOzs/DZgVnG5H55N1sv1M8qZU3A8RIKbs3mrACDNeIOeilDymVb2HdmP8uwshOCF4uJ8uM9rCqJw==", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } } } } diff --git a/package.json b/package.json index e1d9427..413dcb0 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "autoprefixer": "10.4.14", "eslint": "8.42.0", "eslint-config-next": "13.4.4", - "next": "13.4.4", + "next": "^14.0.0", "postcss": "8.4.24", "react": "18.2.0", "react-dom": "18.2.0",